summaryrefslogtreecommitdiffstats
path: root/third_party/heimdal/lib
diff options
context:
space:
mode:
Diffstat (limited to 'third_party/heimdal/lib')
-rw-r--r--third_party/heimdal/lib/Makefile.am50
-rw-r--r--third_party/heimdal/lib/NTMakefile79
-rw-r--r--third_party/heimdal/lib/asn1/ChangeLog1665
-rw-r--r--third_party/heimdal/lib/asn1/MANUAL.md1287
-rw-r--r--third_party/heimdal/lib/asn1/Makefile.am567
-rw-r--r--third_party/heimdal/lib/asn1/NTMakefile548
-rw-r--r--third_party/heimdal/lib/asn1/README-X681.md1124
-rw-r--r--third_party/heimdal/lib/asn1/README-template.md278
-rw-r--r--third_party/heimdal/lib/asn1/README.md1327
-rw-r--r--third_party/heimdal/lib/asn1/asn1-common.h90
-rw-r--r--third_party/heimdal/lib/asn1/asn1-template.h305
-rw-r--r--third_party/heimdal/lib/asn1/asn1_compile-version.rc36
-rw-r--r--third_party/heimdal/lib/asn1/asn1_compile.1350
-rw-r--r--third_party/heimdal/lib/asn1/asn1_err.et29
-rw-r--r--third_party/heimdal/lib/asn1/asn1_gen.c187
-rw-r--r--third_party/heimdal/lib/asn1/asn1_print.1135
-rw-r--r--third_party/heimdal/lib/asn1/asn1_print.c692
-rw-r--r--third_party/heimdal/lib/asn1/asn1parse.y2034
-rw-r--r--third_party/heimdal/lib/asn1/canthandle.asn115
-rw-r--r--third_party/heimdal/lib/asn1/check-ber.c280
-rw-r--r--third_party/heimdal/lib/asn1/check-common.c422
-rw-r--r--third_party/heimdal/lib/asn1/check-common.h92
-rw-r--r--third_party/heimdal/lib/asn1/check-der.c1210
-rw-r--r--third_party/heimdal/lib/asn1/check-gen.c2685
-rw-r--r--third_party/heimdal/lib/asn1/check-gen.h9
-rw-r--r--third_party/heimdal/lib/asn1/check-template.c532
-rw-r--r--third_party/heimdal/lib/asn1/check-timegm.c81
-rw-r--r--third_party/heimdal/lib/asn1/cms.asn1149
-rw-r--r--third_party/heimdal/lib/asn1/cms.opt2
-rw-r--r--third_party/heimdal/lib/asn1/crmf.asn1110
-rw-r--r--third_party/heimdal/lib/asn1/crmf.opt0
-rw-r--r--third_party/heimdal/lib/asn1/der.c142
-rw-r--r--third_party/heimdal/lib/asn1/der.h107
-rw-r--r--third_party/heimdal/lib/asn1/der_cmp.c159
-rw-r--r--third_party/heimdal/lib/asn1/der_copy.c245
-rw-r--r--third_party/heimdal/lib/asn1/der_format.c170
-rw-r--r--third_party/heimdal/lib/asn1/der_free.c156
-rw-r--r--third_party/heimdal/lib/asn1/der_get.c798
-rw-r--r--third_party/heimdal/lib/asn1/der_length.c305
-rw-r--r--third_party/heimdal/lib/asn1/der_locl.h63
-rw-r--r--third_party/heimdal/lib/asn1/der_print.c229
-rw-r--r--third_party/heimdal/lib/asn1/der_put.c705
-rw-r--r--third_party/heimdal/lib/asn1/digest.asn1179
-rw-r--r--third_party/heimdal/lib/asn1/extra.c285
-rw-r--r--third_party/heimdal/lib/asn1/fuzz-inputs/KrbFastArmoredReqbin0 -> 55 bytes
-rw-r--r--third_party/heimdal/lib/asn1/fuzz-inputs/minimal-ek.crtbin0 -> 643 bytes
-rw-r--r--third_party/heimdal/lib/asn1/fuzz-inputs/x690sample.der5
-rw-r--r--third_party/heimdal/lib/asn1/fuzzer.c742
-rw-r--r--third_party/heimdal/lib/asn1/gen.c2016
-rw-r--r--third_party/heimdal/lib/asn1/gen_copy.c290
-rw-r--r--third_party/heimdal/lib/asn1/gen_decode.c841
-rw-r--r--third_party/heimdal/lib/asn1/gen_encode.c747
-rw-r--r--third_party/heimdal/lib/asn1/gen_free.c240
-rw-r--r--third_party/heimdal/lib/asn1/gen_glue.c162
-rw-r--r--third_party/heimdal/lib/asn1/gen_length.c309
-rw-r--r--third_party/heimdal/lib/asn1/gen_locl.h192
-rw-r--r--third_party/heimdal/lib/asn1/gen_print.c43
-rw-r--r--third_party/heimdal/lib/asn1/gen_seq.c127
-rw-r--r--third_party/heimdal/lib/asn1/gen_template.c1675
-rw-r--r--third_party/heimdal/lib/asn1/hash.c206
-rw-r--r--third_party/heimdal/lib/asn1/hash.h87
-rw-r--r--third_party/heimdal/lib/asn1/heim_asn1.h71
-rw-r--r--third_party/heimdal/lib/asn1/krb5.asn11052
-rw-r--r--third_party/heimdal/lib/asn1/krb5.opt9
-rw-r--r--third_party/heimdal/lib/asn1/kx509.asn1204
-rw-r--r--third_party/heimdal/lib/asn1/lex.h42
-rw-r--r--third_party/heimdal/lib/asn1/lex.l310
-rw-r--r--third_party/heimdal/lib/asn1/libasn1-exports.def2649
-rw-r--r--third_party/heimdal/lib/asn1/main.c487
-rw-r--r--third_party/heimdal/lib/asn1/ocsp.asn1113
-rw-r--r--third_party/heimdal/lib/asn1/ocsp.opt2
-rw-r--r--third_party/heimdal/lib/asn1/oid_resolution.c341
-rw-r--r--third_party/heimdal/lib/asn1/pkcs10.asn164
-rw-r--r--third_party/heimdal/lib/asn1/pkcs10.opt1
-rw-r--r--third_party/heimdal/lib/asn1/pkcs12.asn181
-rw-r--r--third_party/heimdal/lib/asn1/pkcs8.asn129
-rw-r--r--third_party/heimdal/lib/asn1/pkcs9.asn129
-rw-r--r--third_party/heimdal/lib/asn1/pkinit.asn1200
-rw-r--r--third_party/heimdal/lib/asn1/pku2u.asn130
-rw-r--r--third_party/heimdal/lib/asn1/rfc2459.asn11210
-rw-r--r--third_party/heimdal/lib/asn1/rfc2459.opt12
-rw-r--r--third_party/heimdal/lib/asn1/rfc4108.asn1207
-rw-r--r--third_party/heimdal/lib/asn1/roken_rename.h46
-rw-r--r--third_party/heimdal/lib/asn1/setchgpw2.asn1193
-rw-r--r--third_party/heimdal/lib/asn1/symbol.c173
-rw-r--r--third_party/heimdal/lib/asn1/symbol.h265
-rw-r--r--third_party/heimdal/lib/asn1/tcg.asn142
-rw-r--r--third_party/heimdal/lib/asn1/template.c3075
-rw-r--r--third_party/heimdal/lib/asn1/test.asn1309
-rw-r--r--third_party/heimdal/lib/asn1/test.gen14
-rw-r--r--third_party/heimdal/lib/asn1/test.opt7
-rw-r--r--third_party/heimdal/lib/asn1/timegm.c136
-rw-r--r--third_party/heimdal/lib/asn1/version-script.map6
-rw-r--r--third_party/heimdal/lib/asn1/x690sample.asn1181
-rw-r--r--third_party/heimdal/lib/base/Makefile.am95
-rw-r--r--third_party/heimdal/lib/base/NTMakefile134
-rw-r--r--third_party/heimdal/lib/base/array.c478
-rw-r--r--third_party/heimdal/lib/base/baselocl.h98
-rw-r--r--third_party/heimdal/lib/base/bool.c59
-rw-r--r--third_party/heimdal/lib/base/bsearch.c888
-rw-r--r--third_party/heimdal/lib/base/common_plugin.h105
-rw-r--r--third_party/heimdal/lib/base/config_file.c1458
-rw-r--r--third_party/heimdal/lib/base/config_reg.c658
-rw-r--r--third_party/heimdal/lib/base/context.c394
-rw-r--r--third_party/heimdal/lib/base/data.c166
-rw-r--r--third_party/heimdal/lib/base/db.c1721
-rw-r--r--third_party/heimdal/lib/base/dict.c305
-rw-r--r--third_party/heimdal/lib/base/dll.c325
-rw-r--r--third_party/heimdal/lib/base/error.c178
-rw-r--r--third_party/heimdal/lib/base/error_string.c177
-rw-r--r--third_party/heimdal/lib/base/expand_path.c725
-rw-r--r--third_party/heimdal/lib/base/heim_err.et57
-rw-r--r--third_party/heimdal/lib/base/heimbase-atomics.h255
-rw-r--r--third_party/heimdal/lib/base/heimbase-svc.h83
-rw-r--r--third_party/heimdal/lib/base/heimbase.c1081
-rw-r--r--third_party/heimdal/lib/base/heimbase.h527
-rw-r--r--third_party/heimdal/lib/base/heimbasepriv.h115
-rw-r--r--third_party/heimdal/lib/base/json.c811
-rw-r--r--third_party/heimdal/lib/base/log.c1074
-rw-r--r--third_party/heimdal/lib/base/null.c53
-rw-r--r--third_party/heimdal/lib/base/number.c136
-rw-r--r--third_party/heimdal/lib/base/plugin.c785
-rw-r--r--third_party/heimdal/lib/base/roken_rename.h61
-rw-r--r--third_party/heimdal/lib/base/string.c260
-rw-r--r--third_party/heimdal/lib/base/test_base.c962
-rw-r--r--third_party/heimdal/lib/base/version-script.map208
-rw-r--r--third_party/heimdal/lib/base/warn.c169
-rw-r--r--third_party/heimdal/lib/com_err/ChangeLog235
-rw-r--r--third_party/heimdal/lib/com_err/Makefile.am50
-rw-r--r--third_party/heimdal/lib/com_err/NTMakefile91
-rw-r--r--third_party/heimdal/lib/com_err/com_err.3246
-rw-r--r--third_party/heimdal/lib/com_err/com_err.c172
-rw-r--r--third_party/heimdal/lib/com_err/com_err.h76
-rw-r--r--third_party/heimdal/lib/com_err/com_right.h87
-rw-r--r--third_party/heimdal/lib/com_err/compile_et-version.rc36
-rw-r--r--third_party/heimdal/lib/com_err/compile_et.c243
-rw-r--r--third_party/heimdal/lib/com_err/compile_et.h78
-rw-r--r--third_party/heimdal/lib/com_err/error.c114
-rw-r--r--third_party/heimdal/lib/com_err/lex.h39
-rw-r--r--third_party/heimdal/lib/com_err/lex.l123
-rw-r--r--third_party/heimdal/lib/com_err/libcom_err-exports.def14
-rw-r--r--third_party/heimdal/lib/com_err/libcom_err-version.rc36
-rw-r--r--third_party/heimdal/lib/com_err/parse.y175
-rw-r--r--third_party/heimdal/lib/com_err/roken_rename.h62
-rw-r--r--third_party/heimdal/lib/com_err/version-script.map20
-rw-r--r--third_party/heimdal/lib/gss_preauth/Makefile.am25
-rw-r--r--third_party/heimdal/lib/gss_preauth/NTMakefile70
-rw-r--r--third_party/heimdal/lib/gss_preauth/README.md110
-rw-r--r--third_party/heimdal/lib/gss_preauth/pa_client.c252
-rw-r--r--third_party/heimdal/lib/gss_preauth/pa_common.c255
-rw-r--r--third_party/heimdal/lib/gssapi/ChangeLog2970
-rw-r--r--third_party/heimdal/lib/gssapi/Makefile.am468
-rw-r--r--third_party/heimdal/lib/gssapi/NTMakefile747
-rw-r--r--third_party/heimdal/lib/gssapi/gen-oid.pl149
-rw-r--r--third_party/heimdal/lib/gssapi/gss-commands.in61
-rw-r--r--third_party/heimdal/lib/gssapi/gss-token.1108
-rw-r--r--third_party/heimdal/lib/gssapi/gss-token.c678
-rw-r--r--third_party/heimdal/lib/gssapi/gss_acquire_cred.3688
-rw-r--r--third_party/heimdal/lib/gssapi/gssapi.3172
-rw-r--r--third_party/heimdal/lib/gssapi/gssapi.h41
-rw-r--r--third_party/heimdal/lib/gssapi/gssapi/gssapi.h1281
-rw-r--r--third_party/heimdal/lib/gssapi/gssapi/gssapi_krb5.h225
-rw-r--r--third_party/heimdal/lib/gssapi/gssapi/gssapi_netlogon.h50
-rw-r--r--third_party/heimdal/lib/gssapi/gssapi/gssapi_ntlm.h41
-rw-r--r--third_party/heimdal/lib/gssapi/gssapi/gssapi_oid.h262
-rw-r--r--third_party/heimdal/lib/gssapi/gssapi/gssapi_spnego.h87
-rw-r--r--third_party/heimdal/lib/gssapi/gssapi_mech.h725
-rw-r--r--third_party/heimdal/lib/gssapi/gsstool.c264
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/8003.c313
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/accept_sec_context.c978
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/acquire_cred.c686
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/add_cred.c254
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/address_to_krb5addr.c77
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/aeap.c178
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/arcfour.c1391
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/authorize_localname.c66
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/canonicalize_name.c58
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/ccache_name.c78
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/cfx.c1797
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/cfx.h65
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/compare_name.c53
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/compat.c125
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/context_time.c94
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/copy_ccache.c200
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/creds.c276
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/decapsulate.c216
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/delete_sec_context.c86
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/display_name.c72
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/display_status.c198
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/duplicate_cred.c168
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/duplicate_name.c58
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/encapsulate.c153
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/export_name.c92
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/export_sec_context.c257
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/external.c413
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/get_mic.c330
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/gkrb5_err.et33
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/gsskrb5_locl.h153
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/import_name.c294
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/import_sec_context.c221
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/indicate_mechs.c55
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/init.c82
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/init_sec_context.c1021
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/inquire_context.c110
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/inquire_cred.c225
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/inquire_cred_by_mech.c78
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/inquire_cred_by_oid.c81
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/inquire_mechs_for_name.c55
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/inquire_names_for_mech.c77
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/inquire_sec_context_by_oid.c598
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/name_attrs.c1171
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/pname_to_uid.c70
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/prf.c148
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/process_context_token.c66
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/release_buffer.c46
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/release_cred.c77
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/release_name.c53
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/sequence.c292
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/set_cred_option.c249
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/set_sec_context_option.c353
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/store_cred.c372
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/test_acquire_cred.c187
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/test_cfx.c173
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/test_cred.c277
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/test_kcred.c155
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/test_oid.c51
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/test_sequence.c367
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/ticket_flags.c58
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/unwrap.c468
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/verify_mic.c360
-rw-r--r--third_party/heimdal/lib/gssapi/krb5/wrap.c592
-rw-r--r--third_party/heimdal/lib/gssapi/libgssapi-exports.def203
-rw-r--r--third_party/heimdal/lib/gssapi/libgssapi-version.rc36
-rw-r--r--third_party/heimdal/lib/gssapi/mech/compat.h94
-rw-r--r--third_party/heimdal/lib/gssapi/mech/context.c361
-rw-r--r--third_party/heimdal/lib/gssapi/mech/context.h51
-rw-r--r--third_party/heimdal/lib/gssapi/mech/cred.c81
-rw-r--r--third_party/heimdal/lib/gssapi/mech/cred.h65
-rw-r--r--third_party/heimdal/lib/gssapi/mech/doxygen.c133
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_accept_sec_context.c519
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_acquire_cred.c50
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_acquire_cred_from.c302
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_acquire_cred_impersonate_name.c51
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_acquire_cred_with_password.c85
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_add_cred.c58
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_add_cred_from.c292
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_add_cred_with_password.c88
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_add_oid_set_member.c87
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_aeap.c334
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_authorize_localname.c187
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_buffer_set.c124
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_canonicalize_name.c104
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_compare_name.c102
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_context_time.c40
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_create_empty_oid_set.c51
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_cred.c326
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_decapsulate_token.c72
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_delete_name_attribute.c65
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_delete_sec_context.c62
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_destroy_cred.c74
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_display_name.c82
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_display_name_ext.c68
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_display_status.c227
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_duplicate_cred.c153
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_duplicate_name.c93
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_duplicate_oid.c51
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_duplicate_oid_set.c57
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_encapsulate_token.c66
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_export_name.c113
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_export_name_composite.c66
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_export_sec_context.c147
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_get_mic.c51
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_get_name_attribute.c83
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_get_neg_mechs.c54
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_import_name.c323
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_import_sec_context.c147
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_indicate_mechs.c74
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_init_sec_context.c281
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_inquire_context.c120
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_inquire_cred.c218
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_inquire_cred_by_mech.c92
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_inquire_cred_by_oid.c90
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_inquire_mechs_for_name.c76
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_inquire_name.c79
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_inquire_names_for_mech.c73
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_inquire_sec_context_by_oid.c70
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_krb5.c927
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_mech_switch.c585
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_mo.c636
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_names.c262
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_oid.c370
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_oid_equal.c58
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_oid_to_str.c67
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_pname_to_uid.c197
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_process_context_token.c41
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_pseudo_random.c70
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_release_buffer.c42
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_release_cred.c66
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_release_name.c63
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_release_oid.c46
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_release_oid_set.c44
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_rfc4121.c111
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_seal.c45
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_set_cred_option.c118
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_set_name_attribute.c69
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_set_neg_mechs.c60
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_set_sec_context_option.c102
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_sign.c41
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_store_cred.c57
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_store_cred_into.c181
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_test_oid_set_member.c46
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_unseal.c43
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_unwrap.c56
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_utils.c324
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_verify.c42
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_verify_mic.c52
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_wrap.c71
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gss_wrap_size_limit.c52
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gssapi.asn112
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gssspi_exchange_meta_data.c115
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gssspi_query_mechanism_info.c55
-rw-r--r--third_party/heimdal/lib/gssapi/mech/gssspi_query_meta_data.c117
-rw-r--r--third_party/heimdal/lib/gssapi/mech/mech.594
-rw-r--r--third_party/heimdal/lib/gssapi/mech/mech_locl.h77
-rw-r--r--third_party/heimdal/lib/gssapi/mech/mech_switch.h43
-rw-r--r--third_party/heimdal/lib/gssapi/mech/name.h77
-rw-r--r--third_party/heimdal/lib/gssapi/mech/utils.h82
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/accept_sec_context.c89
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/acquire_cred.c186
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/add_cred.c89
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/canonicalize_name.c46
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/compare_name.c61
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/context_time.c47
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/crypto.c733
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/delete_sec_context.c62
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/display_name.c67
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/display_status.c55
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/duplicate_cred.c54
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/duplicate_name.c77
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/export_name.c45
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/export_sec_context.c50
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/external.c111
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/import_name.c94
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/import_sec_context.c50
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/indicate_mechs.c48
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/init_sec_context.c289
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/inquire_context.c76
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/inquire_cred.c68
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/inquire_cred_by_mech.c66
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/inquire_mechs_for_name.c48
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/inquire_names_for_mech.c58
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/iter_cred.c44
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/netlogon.h150
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/process_context_token.c46
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/regen.sh3
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/release_cred.c54
-rw-r--r--third_party/heimdal/lib/gssapi/netlogon/release_name.c54
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/accept_sec_context.c256
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/acquire_cred.c88
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/add_cred.c60
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/canonicalize_name.c45
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/compare_name.c45
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/context_time.c45
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/creds.c159
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/crypto.c636
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/delete_sec_context.c69
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/display_name.c71
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/display_status.c54
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/duplicate_cred.c57
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/duplicate_name.c48
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/export_name.c50
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/export_sec_context.c50
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/external.c140
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/import_name.c112
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/import_sec_context.c48
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/indicate_mechs.c46
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/init_sec_context.c536
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/inquire_context.c68
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/inquire_cred_by_mech.c58
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/inquire_mechs_for_name.c48
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/inquire_names_for_mech.c51
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/inquire_sec_context_by_oid.c90
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/iter_cred.c99
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/kdc.c435
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/ntlm.h146
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/process_context_token.c44
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/release_cred.c66
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/release_name.c52
-rw-r--r--third_party/heimdal/lib/gssapi/ntlm/set_sec_context_option.c60
-rw-r--r--third_party/heimdal/lib/gssapi/oid.txt173
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/accept_sec_context.c169
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/acquire_cred.c59
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/add_cred.c65
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/canonicalize_name.c48
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/compare_name.c54
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/context_time.c50
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/crypto.c333
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/delete_sec_context.c62
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/display_name.c50
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/display_status.c60
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/duplicate_cred.c43
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/duplicate_name.c43
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/export_cred.c40
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/export_name.c52
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/export_sec_context.c52
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/external.c270
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/import_cred.c42
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/import_name.c163
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/import_sec_context.c55
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/init_sec_context.c205
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/inquire_context.c75
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/inquire_cred.c58
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/inquire_cred_by_mech.c74
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/inquire_mechs_for_name.c54
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/inquire_names_for_mech.c77
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/inquire_sec_context_by_oid.c61
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/negoex.c131
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/process_context_token.c42
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/release_cred.c42
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/release_name.c42
-rw-r--r--third_party/heimdal/lib/gssapi/sanon/sanon_locl.h84
-rw-r--r--third_party/heimdal/lib/gssapi/spnego/accept_sec_context.c1024
-rw-r--r--third_party/heimdal/lib/gssapi/spnego/compat.c684
-rw-r--r--third_party/heimdal/lib/gssapi/spnego/context_storage.c492
-rw-r--r--third_party/heimdal/lib/gssapi/spnego/context_stubs.c578
-rw-r--r--third_party/heimdal/lib/gssapi/spnego/external.c165
-rw-r--r--third_party/heimdal/lib/gssapi/spnego/init_sec_context.c841
-rw-r--r--third_party/heimdal/lib/gssapi/spnego/negoex_ctx.c1041
-rw-r--r--third_party/heimdal/lib/gssapi/spnego/negoex_err.et25
-rw-r--r--third_party/heimdal/lib/gssapi/spnego/negoex_locl.h127
-rw-r--r--third_party/heimdal/lib/gssapi/spnego/negoex_util.c1042
-rw-r--r--third_party/heimdal/lib/gssapi/spnego/spnego.asn166
-rw-r--r--third_party/heimdal/lib/gssapi/spnego/spnego.opt1
-rw-r--r--third_party/heimdal/lib/gssapi/spnego/spnego_locl.h159
-rw-r--r--third_party/heimdal/lib/gssapi/test_acquire_cred.c344
-rw-r--r--third_party/heimdal/lib/gssapi/test_add_store_cred.c219
-rw-r--r--third_party/heimdal/lib/gssapi/test_common.c71
-rw-r--r--third_party/heimdal/lib/gssapi/test_common.h36
-rw-r--r--third_party/heimdal/lib/gssapi/test_context.c1610
-rw-r--r--third_party/heimdal/lib/gssapi/test_cred.c236
-rw-r--r--third_party/heimdal/lib/gssapi/test_kcred.c198
-rw-r--r--third_party/heimdal/lib/gssapi/test_names.c675
-rw-r--r--third_party/heimdal/lib/gssapi/test_negoex_mech.c592
-rw-r--r--third_party/heimdal/lib/gssapi/test_ntlm.c337
-rw-r--r--third_party/heimdal/lib/gssapi/test_oid.c71
-rw-r--r--third_party/heimdal/lib/gssapi/version-script.map210
-rw-r--r--third_party/heimdal/lib/hcrypto/ChangeLog1227
-rw-r--r--third_party/heimdal/lib/hcrypto/DESperate.txt108
-rw-r--r--third_party/heimdal/lib/hcrypto/Makefile.am427
-rw-r--r--third_party/heimdal/lib/hcrypto/NTMakefile274
-rw-r--r--third_party/heimdal/lib/hcrypto/aes.c142
-rw-r--r--third_party/heimdal/lib/hcrypto/aes.h83
-rw-r--r--third_party/heimdal/lib/hcrypto/bn.c529
-rw-r--r--third_party/heimdal/lib/hcrypto/bn.h139
-rw-r--r--third_party/heimdal/lib/hcrypto/camellia-ntt.c1458
-rw-r--r--third_party/heimdal/lib/hcrypto/camellia-ntt.h63
-rw-r--r--third_party/heimdal/lib/hcrypto/camellia.c113
-rw-r--r--third_party/heimdal/lib/hcrypto/camellia.h72
-rw-r--r--third_party/heimdal/lib/hcrypto/common.c65
-rw-r--r--third_party/heimdal/lib/hcrypto/common.h45
-rw-r--r--third_party/heimdal/lib/hcrypto/des-tables.h196
-rw-r--r--third_party/heimdal/lib/hcrypto/des.c1186
-rw-r--r--third_party/heimdal/lib/hcrypto/des.h146
-rw-r--r--third_party/heimdal/lib/hcrypto/destest.c621
-rw-r--r--third_party/heimdal/lib/hcrypto/dh-ltm.c264
-rw-r--r--third_party/heimdal/lib/hcrypto/dh-tfm.c248
-rw-r--r--third_party/heimdal/lib/hcrypto/dh.c551
-rw-r--r--third_party/heimdal/lib/hcrypto/dh.h148
-rw-r--r--third_party/heimdal/lib/hcrypto/doxygen.c102
-rw-r--r--third_party/heimdal/lib/hcrypto/dsa.c127
-rw-r--r--third_party/heimdal/lib/hcrypto/dsa.h142
-rw-r--r--third_party/heimdal/lib/hcrypto/ec.c178
-rw-r--r--third_party/heimdal/lib/hcrypto/ec.h97
-rw-r--r--third_party/heimdal/lib/hcrypto/ecdh.h47
-rw-r--r--third_party/heimdal/lib/hcrypto/ecdsa.h52
-rw-r--r--third_party/heimdal/lib/hcrypto/engine.c396
-rw-r--r--third_party/heimdal/lib/hcrypto/engine.h120
-rw-r--r--third_party/heimdal/lib/hcrypto/evp-cc.c943
-rw-r--r--third_party/heimdal/lib/hcrypto/evp-cc.h102
-rw-r--r--third_party/heimdal/lib/hcrypto/evp-crypt.c217
-rw-r--r--third_party/heimdal/lib/hcrypto/evp-hcrypto.c854
-rw-r--r--third_party/heimdal/lib/hcrypto/evp-hcrypto.h103
-rw-r--r--third_party/heimdal/lib/hcrypto/evp-openssl.c644
-rw-r--r--third_party/heimdal/lib/hcrypto/evp-openssl.h102
-rw-r--r--third_party/heimdal/lib/hcrypto/evp-pkcs11.c832
-rw-r--r--third_party/heimdal/lib/hcrypto/evp-pkcs11.h157
-rw-r--r--third_party/heimdal/lib/hcrypto/evp-w32.c140
-rw-r--r--third_party/heimdal/lib/hcrypto/evp-w32.h100
-rw-r--r--third_party/heimdal/lib/hcrypto/evp-wincng.c727
-rw-r--r--third_party/heimdal/lib/hcrypto/evp-wincng.h97
-rw-r--r--third_party/heimdal/lib/hcrypto/evp.c1521
-rw-r--r--third_party/heimdal/lib/hcrypto/evp.h361
-rw-r--r--third_party/heimdal/lib/hcrypto/example_evp_cipher.c165
-rw-r--r--third_party/heimdal/lib/hcrypto/gen-des.pl217
-rw-r--r--third_party/heimdal/lib/hcrypto/hash.h74
-rw-r--r--third_party/heimdal/lib/hcrypto/hmac.c178
-rw-r--r--third_party/heimdal/lib/hcrypto/hmac.h86
-rw-r--r--third_party/heimdal/lib/hcrypto/libhcrypto-exports.def354
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/LICENSE26
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/NTMakefile203
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/README.md44
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/appveyor.yml20
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/astylerc30
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_cutoffs.c14
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_deprecated.c321
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_2expt.c31
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_abs.c26
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_add.c38
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_add_d.c89
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_addmod.c25
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_and.c56
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_clamp.c27
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_clear.c20
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_clear_multi.c19
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cmp.c26
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cmp_d.c28
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cmp_mag.c39
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cnt_lsb.c37
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_complement.c12
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_copy.c47
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_count_bits.c28
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_decr.c34
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div.c250
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_2.c49
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_2d.c71
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_3.c63
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_d.c84
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_dr_is_modulus.c27
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_dr_reduce.c78
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_dr_setup.c15
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_error_to_string.c27
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_exch.c17
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_expt_u32.c46
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_exptmod.c76
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_exteuclid.c73
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_fread.c60
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_from_sbin.c25
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_from_ubin.c39
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_fwrite.c45
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_gcd.c92
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_double.c18
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_i32.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_i64.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_l.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_ll.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_u32.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_u64.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_ul.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_ull.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_grow.c38
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_incr.c30
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init.c23
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_copy.c21
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_i32.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_i64.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_l.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_ll.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_multi.c41
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_set.c16
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_size.c24
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_u32.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_u64.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_ul.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_ull.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_invmod.c23
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_is_square.c93
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_iseven.c10
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_isodd.c10
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_kronecker.c129
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_lcm.c44
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_log_u32.c180
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_lshd.c51
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mod.c31
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mod_2d.c38
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mod_d.c10
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_montgomery_calc_normalization.c44
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_montgomery_reduce.c102
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_montgomery_setup.c42
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul.c52
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul_2.c64
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul_2d.c69
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul_d.c61
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mulmod.c25
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_neg.c24
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_or.c56
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_pack.c69
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_pack_count.c12
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_fermat.c47
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_frobenius_underwood.c132
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_is_prime.c314
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_miller_rabin.c91
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_next_prime.c132
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_rabin_miller_trials.c47
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_rand.c141
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_strong_lucas_selfridge.c289
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_radix_size.c65
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_radix_smap.c22
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_rand.c46
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_read_radix.c79
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce.c83
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k.c48
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k_l.c49
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k_setup.c32
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k_setup_l.c28
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_is_2k.c38
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_is_2k_l.c28
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_setup.c17
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_root_u32.c139
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_rshd.c51
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sbin_size.c11
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set.c14
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_double.c47
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_i32.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_i64.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_l.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_ll.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_u32.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_u64.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_ul.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_ull.c7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_shrink.c22
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_signed_rsh.c22
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqr.c28
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqrmod.c25
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqrt.c67
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqrtmod_prime.c118
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sub.c40
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sub_d.c74
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_submod.c25
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_to_radix.c84
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_to_sbin.c22
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_to_ubin.c41
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_ubin_size.c12
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_unpack.c49
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_xor.c56
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_mp_zero.c13
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_prime_tab.c61
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_add.c91
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_balance_mul.c81
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_exptmod.c198
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_exptmod_fast.c254
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_get_bit.c21
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_invmod_fast.c118
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_invmod_slow.c119
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_karatsuba_mul.c174
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_karatsuba_sqr.c110
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_montgomery_reduce_fast.c159
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_digs.c74
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_digs_fast.c90
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_high_digs.c64
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_high_digs_fast.c81
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_prime_is_divisible.c35
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_rand_jenkins.c52
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_rand_platform.c168
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_reverse.c22
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_sqr.c69
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_sqr_fast.c97
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_sub.c71
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_toom_mul.c215
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_toom_sqr.c147
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/changes.txt497
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/demo/mtest_opponent.c402
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/demo/shared.c42
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/demo/shared.h21
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/demo/test.c2522
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/demo/timing.c406
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/doc/bn.pdfbin0 -> 430812 bytes
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/doc/bn.tex2507
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/2kprime.12
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/2kprime.c81
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/drprime.c67
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/drprimes.2825
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/drprimes.txt9
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/makefile44
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/makefile.icc67
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/makefile.msvc24
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/mersenne.c138
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/mont.c44
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/pprime.c411
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/prime.1024414
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/prime.512205
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/timer.asm37
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/etc/tune.c542
-rwxr-xr-xthird_party/heimdal/lib/hcrypto/libtommath/etc/tune_it.sh107
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/gen.pl20
-rwxr-xr-xthird_party/heimdal/lib/hcrypto/libtommath/helper.pl482
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/libtommath.pc.in10
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/libtommath_VS2008.sln29
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/libtommath_VS2008.vcproj966
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/README13
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/add.log16
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/addsub.pngbin0 -> 5921 bytes
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/expt.log7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/expt.pngbin0 -> 7290 bytes
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/expt_2k.log6
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/expt_2kl.log3
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/expt_dr.log7
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/graphs.dem16
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/index.html27
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/invmod.log8
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/invmod.pngbin0 -> 6294 bytes
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/mult.log84
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/mult.pngbin0 -> 8308 bytes
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/mult_kara.log84
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/sqr.log84
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/sqr_kara.log84
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/logs/sub.log16
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/makefile165
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/makefile.mingw109
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/makefile.msvc93
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/makefile.shared99
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/makefile.unix106
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/makefile_include.mk166
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/mtest/logtab.h24
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi-config.h90
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi-types.h20
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi.c3987
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi.h233
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/mtest/mtest.c374
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/pre_gen/mpi.c9541
-rwxr-xr-xthird_party/heimdal/lib/hcrypto/libtommath/testme.sh394
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/tommath.def145
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/tommath.h781
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/tommath_class.h1319
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/tommath_cutoffs.h13
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/tommath_private.h303
-rw-r--r--third_party/heimdal/lib/hcrypto/libtommath/tommath_superclass.h110
-rw-r--r--third_party/heimdal/lib/hcrypto/md2.c138
-rw-r--r--third_party/heimdal/lib/hcrypto/md2.h63
-rw-r--r--third_party/heimdal/lib/hcrypto/md4.c250
-rw-r--r--third_party/heimdal/lib/hcrypto/md4.h62
-rw-r--r--third_party/heimdal/lib/hcrypto/md5.c274
-rw-r--r--third_party/heimdal/lib/hcrypto/md5.h62
-rw-r--r--third_party/heimdal/lib/hcrypto/md5crypt_test.c75
-rw-r--r--third_party/heimdal/lib/hcrypto/mdtest.c348
-rw-r--r--third_party/heimdal/lib/hcrypto/passwd_dialog.apsbin0 -> 30428 bytes
-rw-r--r--third_party/heimdal/lib/hcrypto/passwd_dialog.clw34
-rw-r--r--third_party/heimdal/lib/hcrypto/passwd_dialog.rc143
-rw-r--r--third_party/heimdal/lib/hcrypto/passwd_dialog.resbin0 -> 320 bytes
-rw-r--r--third_party/heimdal/lib/hcrypto/passwd_dlg.c89
-rw-r--r--third_party/heimdal/lib/hcrypto/passwd_dlg.h47
-rw-r--r--third_party/heimdal/lib/hcrypto/pkcs12.c158
-rw-r--r--third_party/heimdal/lib/hcrypto/pkcs12.h57
-rw-r--r--third_party/heimdal/lib/hcrypto/pkcs5.c152
-rw-r--r--third_party/heimdal/lib/hcrypto/rand-fortuna.c649
-rw-r--r--third_party/heimdal/lib/hcrypto/rand-timer.c210
-rw-r--r--third_party/heimdal/lib/hcrypto/rand-unix.c175
-rw-r--r--third_party/heimdal/lib/hcrypto/rand-w32.c150
-rw-r--r--third_party/heimdal/lib/hcrypto/rand.c402
-rw-r--r--third_party/heimdal/lib/hcrypto/rand.h106
-rw-r--r--third_party/heimdal/lib/hcrypto/randi.h49
-rw-r--r--third_party/heimdal/lib/hcrypto/rc2.c240
-rw-r--r--third_party/heimdal/lib/hcrypto/rc2.h71
-rw-r--r--third_party/heimdal/lib/hcrypto/rc2test.c167
-rw-r--r--third_party/heimdal/lib/hcrypto/rc4.c79
-rw-r--r--third_party/heimdal/lib/hcrypto/rc4.h46
-rw-r--r--third_party/heimdal/lib/hcrypto/rctest.c161
-rw-r--r--third_party/heimdal/lib/hcrypto/resource.h18
-rw-r--r--third_party/heimdal/lib/hcrypto/rijndael-alg-fst.c1223
-rw-r--r--third_party/heimdal/lib/hcrypto/rijndael-alg-fst.h46
-rw-r--r--third_party/heimdal/lib/hcrypto/rnd_keys.c138
-rw-r--r--third_party/heimdal/lib/hcrypto/rsa-gmp.c584
-rw-r--r--third_party/heimdal/lib/hcrypto/rsa-ltm.c637
-rw-r--r--third_party/heimdal/lib/hcrypto/rsa-tfm.c573
-rw-r--r--third_party/heimdal/lib/hcrypto/rsa.c706
-rw-r--r--third_party/heimdal/lib/hcrypto/rsa.h184
-rw-r--r--third_party/heimdal/lib/hcrypto/rsakey.derbin0 -> 609 bytes
-rw-r--r--third_party/heimdal/lib/hcrypto/rsakey2048.derbin0 -> 1192 bytes
-rw-r--r--third_party/heimdal/lib/hcrypto/rsakey4096.derbin0 -> 2349 bytes
-rw-r--r--third_party/heimdal/lib/hcrypto/sha.c300
-rw-r--r--third_party/heimdal/lib/hcrypto/sha.h115
-rw-r--r--third_party/heimdal/lib/hcrypto/sha256.c233
-rw-r--r--third_party/heimdal/lib/hcrypto/sha512.c301
-rw-r--r--third_party/heimdal/lib/hcrypto/test_bn.c392
-rw-r--r--third_party/heimdal/lib/hcrypto/test_bulk.c314
-rw-r--r--third_party/heimdal/lib/hcrypto/test_cipher.c436
-rw-r--r--third_party/heimdal/lib/hcrypto/test_crypto.in120
-rw-r--r--third_party/heimdal/lib/hcrypto/test_dh.c472
-rw-r--r--third_party/heimdal/lib/hcrypto/test_engine_dso.c329
-rw-r--r--third_party/heimdal/lib/hcrypto/test_hmac.c74
-rw-r--r--third_party/heimdal/lib/hcrypto/test_pkcs12.c138
-rw-r--r--third_party/heimdal/lib/hcrypto/test_pkcs5.c147
-rw-r--r--third_party/heimdal/lib/hcrypto/test_rand.c219
-rw-r--r--third_party/heimdal/lib/hcrypto/test_rsa.c397
-rw-r--r--third_party/heimdal/lib/hcrypto/ui.c218
-rw-r--r--third_party/heimdal/lib/hcrypto/ui.h49
-rw-r--r--third_party/heimdal/lib/hcrypto/undef.h169
-rw-r--r--third_party/heimdal/lib/hcrypto/validate.c307
-rw-r--r--third_party/heimdal/lib/hcrypto/version-script.map341
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/NTMakefile46
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/align.h7
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10.c2886
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10.h174
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10_fe_25_5.h1067
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10_fe_51.h539
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/fe_25_5/base.h1344
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/fe_25_5/base2.h40
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/fe_25_5/constants.h40
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/fe_25_5/fe.h220
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/fe_51/base.h1344
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/fe_51/base2.h40
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/fe_51/constants.h41
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/fe_51/fe.h116
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519/x25519_ref10.c209
-rw-r--r--third_party/heimdal/lib/hcrypto/x25519_ref10.h55
-rw-r--r--third_party/heimdal/lib/hdb/Makefile.am168
-rw-r--r--third_party/heimdal/lib/hdb/NTMakefile189
-rw-r--r--third_party/heimdal/lib/hdb/common.c1745
-rw-r--r--third_party/heimdal/lib/hdb/data-mkey.mit.des3.bebin0 -> 46 bytes
-rw-r--r--third_party/heimdal/lib/hdb/data-mkey.mit.des3.lebin0 -> 30 bytes
-rw-r--r--third_party/heimdal/lib/hdb/db.c391
-rw-r--r--third_party/heimdal/lib/hdb/db3.c495
-rw-r--r--third_party/heimdal/lib/hdb/dbinfo.c291
-rw-r--r--third_party/heimdal/lib/hdb/ext.c786
-rw-r--r--third_party/heimdal/lib/hdb/hdb-keytab.c232
-rw-r--r--third_party/heimdal/lib/hdb/hdb-ldap.c2117
-rw-r--r--third_party/heimdal/lib/hdb/hdb-mdb.c692
-rw-r--r--third_party/heimdal/lib/hdb/hdb-mitdb.c1500
-rw-r--r--third_party/heimdal/lib/hdb/hdb-sqlite.c1075
-rw-r--r--third_party/heimdal/lib/hdb/hdb.asn1251
-rw-r--r--third_party/heimdal/lib/hdb/hdb.c848
-rw-r--r--third_party/heimdal/lib/hdb/hdb.h337
-rw-r--r--third_party/heimdal/lib/hdb/hdb.opt5
-rw-r--r--third_party/heimdal/lib/hdb/hdb.schema144
-rw-r--r--third_party/heimdal/lib/hdb/hdb_err.et33
-rw-r--r--third_party/heimdal/lib/hdb/hdb_locl.h73
-rw-r--r--third_party/heimdal/lib/hdb/keys.c855
-rw-r--r--third_party/heimdal/lib/hdb/keytab.c449
-rw-r--r--third_party/heimdal/lib/hdb/libhdb-exports.def180
-rw-r--r--third_party/heimdal/lib/hdb/libhdb-version.rc36
-rw-r--r--third_party/heimdal/lib/hdb/mkey.c769
-rw-r--r--third_party/heimdal/lib/hdb/ndbm.c406
-rw-r--r--third_party/heimdal/lib/hdb/print.c597
-rw-r--r--third_party/heimdal/lib/hdb/test_concurrency.c506
-rw-r--r--third_party/heimdal/lib/hdb/test_dbinfo.c156
-rw-r--r--third_party/heimdal/lib/hdb/test_hdbkeys.c124
-rw-r--r--third_party/heimdal/lib/hdb/test_mkey.c55
-rw-r--r--third_party/heimdal/lib/hdb/test_namespace.c941
-rw-r--r--third_party/heimdal/lib/hdb/version-script.map189
-rw-r--r--third_party/heimdal/lib/heimdal/NTMakefile98
-rw-r--r--third_party/heimdal/lib/heimdal/heimdal-version.rc36
-rw-r--r--third_party/heimdal/lib/hx509/ChangeLog2749
-rw-r--r--third_party/heimdal/lib/hx509/Makefile.am398
-rw-r--r--third_party/heimdal/lib/hx509/NTMakefile180
-rw-r--r--third_party/heimdal/lib/hx509/TODO61
-rw-r--r--third_party/heimdal/lib/hx509/ca.c3093
-rw-r--r--third_party/heimdal/lib/hx509/cert.c3892
-rw-r--r--third_party/heimdal/lib/hx509/char_map.h45
-rw-r--r--third_party/heimdal/lib/hx509/cms.c1718
-rw-r--r--third_party/heimdal/lib/hx509/collector.c331
-rw-r--r--third_party/heimdal/lib/hx509/crypto-ec.c533
-rw-r--r--third_party/heimdal/lib/hx509/crypto.c2804
-rw-r--r--third_party/heimdal/lib/hx509/data/PKITS.pdfbin0 -> 754584 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/PKITS_data.zipbin0 -> 2149008 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/bleichenbacher-bad.pem12
-rw-r--r--third_party/heimdal/lib/hx509/data/bleichenbacher-good.pem12
-rw-r--r--third_party/heimdal/lib/hx509/data/bleichenbacher-sf-pad-correct.pem16
-rw-r--r--third_party/heimdal/lib/hx509/data/ca.crt32
-rw-r--r--third_party/heimdal/lib/hx509/data/ca.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/crl1.crl16
-rw-r--r--third_party/heimdal/lib/hx509/data/crl1.derbin0 -> 649 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/eccurve.pem3
-rwxr-xr-xthird_party/heimdal/lib/hx509/data/gen-req.sh360
-rw-r--r--third_party/heimdal/lib/hx509/data/https.crt116
-rw-r--r--third_party/heimdal/lib/hx509/data/https.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/j.pem26
-rw-r--r--third_party/heimdal/lib/hx509/data/kdc.crt122
-rw-r--r--third_party/heimdal/lib/hx509/data/kdc.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/key.derbin0 -> 609 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/key2.derbin0 -> 610 bytes
-rwxr-xr-xthird_party/heimdal/lib/hx509/data/mkcert.sh83
-rw-r--r--third_party/heimdal/lib/hx509/data/n0ll.pem47
-rw-r--r--third_party/heimdal/lib/hx509/data/nist-data91
-rw-r--r--third_party/heimdal/lib/hx509/data/nist-data2291
-rw-r--r--third_party/heimdal/lib/hx509/data/nist-result231
-rw-r--r--third_party/heimdal/lib/hx509/data/no-proxy-test.crt30
-rw-r--r--third_party/heimdal/lib/hx509/data/no-proxy-test.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/ocsp-req1.derbin0 -> 105 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/ocsp-req2.derbin0 -> 105 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/ocsp-resp1-2.derbin0 -> 999 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/ocsp-resp1-3.derbin0 -> 363 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/ocsp-resp1-ca.derbin0 -> 2159 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/ocsp-resp1-keyhash.derbin0 -> 2060 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/ocsp-resp1-ocsp-no-cert.derbin0 -> 748 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/ocsp-resp1-ocsp.derbin0 -> 2078 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/ocsp-resp1.derbin0 -> 918 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/ocsp-resp2.derbin0 -> 2095 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/ocsp-responder.crt119
-rw-r--r--third_party/heimdal/lib/hx509/data/ocsp-responder.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/openssl.1.0.cnf190
-rw-r--r--third_party/heimdal/lib/hx509/data/openssl.1.1.cnf185
-rw-r--r--third_party/heimdal/lib/hx509/data/pkinit-ec.crt81
-rw-r--r--third_party/heimdal/lib/hx509/data/pkinit-ec.key5
-rw-r--r--third_party/heimdal/lib/hx509/data/pkinit-proxy-chain.crt149
-rw-r--r--third_party/heimdal/lib/hx509/data/pkinit-proxy.crt30
-rw-r--r--third_party/heimdal/lib/hx509/data/pkinit-proxy.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/pkinit-pw.key54
-rw-r--r--third_party/heimdal/lib/hx509/data/pkinit.crt119
-rw-r--r--third_party/heimdal/lib/hx509/data/pkinit.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/proxy-level-test.crt31
-rw-r--r--third_party/heimdal/lib/hx509/data/proxy-level-test.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/proxy-test.crt30
-rw-r--r--third_party/heimdal/lib/hx509/data/proxy-test.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/proxy10-child-child-test.crt32
-rw-r--r--third_party/heimdal/lib/hx509/data/proxy10-child-child-test.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/proxy10-child-test.crt31
-rw-r--r--third_party/heimdal/lib/hx509/data/proxy10-child-test.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/proxy10-test.crt30
-rw-r--r--third_party/heimdal/lib/hx509/data/proxy10-test.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/revoke.crt116
-rw-r--r--third_party/heimdal/lib/hx509/data/revoke.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/secp256r1TestCA.cert.pem12
-rw-r--r--third_party/heimdal/lib/hx509/data/secp256r1TestCA.key.pem5
-rw-r--r--third_party/heimdal/lib/hx509/data/secp256r1TestCA.pem17
-rw-r--r--third_party/heimdal/lib/hx509/data/secp256r2TestClient.cert.pem12
-rw-r--r--third_party/heimdal/lib/hx509/data/secp256r2TestClient.key.pem5
-rw-r--r--third_party/heimdal/lib/hx509/data/secp256r2TestClient.pem17
-rw-r--r--third_party/heimdal/lib/hx509/data/secp256r2TestServer.cert.pem12
-rw-r--r--third_party/heimdal/lib/hx509/data/secp256r2TestServer.key.pem5
-rw-r--r--third_party/heimdal/lib/hx509/data/secp256r2TestServer.pem17
-rw-r--r--third_party/heimdal/lib/hx509/data/sf-class2-root.pem24
-rw-r--r--third_party/heimdal/lib/hx509/data/static-file84
-rw-r--r--third_party/heimdal/lib/hx509/data/sub-ca.crt123
-rw-r--r--third_party/heimdal/lib/hx509/data/sub-ca.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/sub-cert.crt116
-rw-r--r--third_party/heimdal/lib/hx509/data/sub-cert.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/sub-cert.p12bin0 -> 7072 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/tcg-devid.pem24
-rw-r--r--third_party/heimdal/lib/hx509/data/tcg-ek-cp.pem24
-rw-r--r--third_party/heimdal/lib/hx509/data/test-ds-only.crt117
-rw-r--r--third_party/heimdal/lib/hx509/data/test-ds-only.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/test-enveloped-aes-128bin0 -> 3547 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/test-enveloped-aes-256bin0 -> 3547 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/test-enveloped-desbin0 -> 3527 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/test-enveloped-des-ede3bin0 -> 3530 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/test-enveloped-rc2-128bin0 -> 3535 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/test-enveloped-rc2-40bin0 -> 3536 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/test-enveloped-rc2-64bin0 -> 3535 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/test-ke-only.crt117
-rw-r--r--third_party/heimdal/lib/hx509/data/test-ke-only.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/test-nopw.p12bin0 -> 5510 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/test-pw.key54
-rw-r--r--third_party/heimdal/lib/hx509/data/test-signed-databin0 -> 5057 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/test-signed-data-noattrbin0 -> 4826 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/test-signed-data-noattr-nocertsbin0 -> 3537 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/test-signed-sha-1bin0 -> 5037 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/test-signed-sha-256bin0 -> 5057 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/test-signed-sha-512bin0 -> 5090 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/test.combined.crt168
-rw-r--r--third_party/heimdal/lib/hx509/data/test.crt116
-rw-r--r--third_party/heimdal/lib/hx509/data/test.key52
-rw-r--r--third_party/heimdal/lib/hx509/data/test.p12bin0 -> 5608 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/win-u16-in-printablestring.derbin0 -> 772 bytes
-rw-r--r--third_party/heimdal/lib/hx509/data/yutaka-pad-broken-ca.pem16
-rw-r--r--third_party/heimdal/lib/hx509/data/yutaka-pad-broken-cert.pem18
-rw-r--r--third_party/heimdal/lib/hx509/data/yutaka-pad-ok-ca.pem16
-rw-r--r--third_party/heimdal/lib/hx509/data/yutaka-pad-ok-cert.pem18
-rw-r--r--third_party/heimdal/lib/hx509/data/yutaka-pad.key15
-rw-r--r--third_party/heimdal/lib/hx509/doxygen.c85
-rw-r--r--third_party/heimdal/lib/hx509/env.c245
-rw-r--r--third_party/heimdal/lib/hx509/error.c220
-rw-r--r--third_party/heimdal/lib/hx509/file.c387
-rw-r--r--third_party/heimdal/lib/hx509/hx509.h221
-rw-r--r--third_party/heimdal/lib/hx509/hx509_err.et110
-rw-r--r--third_party/heimdal/lib/hx509/hx_locl.h330
-rw-r--r--third_party/heimdal/lib/hx509/hxtool-commands.in1057
-rw-r--r--third_party/heimdal/lib/hx509/hxtool-version.rc36
-rw-r--r--third_party/heimdal/lib/hx509/hxtool.c3162
-rw-r--r--third_party/heimdal/lib/hx509/keyset.c846
-rw-r--r--third_party/heimdal/lib/hx509/ks_dir.c231
-rw-r--r--third_party/heimdal/lib/hx509/ks_file.c800
-rw-r--r--third_party/heimdal/lib/hx509/ks_keychain.c627
-rw-r--r--third_party/heimdal/lib/hx509/ks_mem.c224
-rw-r--r--third_party/heimdal/lib/hx509/ks_null.c101
-rw-r--r--third_party/heimdal/lib/hx509/ks_p11.c1230
-rw-r--r--third_party/heimdal/lib/hx509/ks_p12.c756
-rw-r--r--third_party/heimdal/lib/hx509/libhx509-exports.def288
-rw-r--r--third_party/heimdal/lib/hx509/lock.c252
-rw-r--r--third_party/heimdal/lib/hx509/name.c1529
-rw-r--r--third_party/heimdal/lib/hx509/peer.c237
-rw-r--r--third_party/heimdal/lib/hx509/print.c1144
-rw-r--r--third_party/heimdal/lib/hx509/quote.py101
-rw-r--r--third_party/heimdal/lib/hx509/ref/pkcs11.h1722
-rw-r--r--third_party/heimdal/lib/hx509/req.c1520
-rw-r--r--third_party/heimdal/lib/hx509/revoke.c1650
-rw-r--r--third_party/heimdal/lib/hx509/sel-gram.y130
-rw-r--r--third_party/heimdal/lib/hx509/sel-lex.l148
-rw-r--r--third_party/heimdal/lib/hx509/sel.c240
-rw-r--r--third_party/heimdal/lib/hx509/sel.h100
-rw-r--r--third_party/heimdal/lib/hx509/softp11.c1777
-rw-r--r--third_party/heimdal/lib/hx509/test_ca.in480
-rw-r--r--third_party/heimdal/lib/hx509/test_cert.in84
-rw-r--r--third_party/heimdal/lib/hx509/test_chain.in256
-rw-r--r--third_party/heimdal/lib/hx509/test_cms.in514
-rw-r--r--third_party/heimdal/lib/hx509/test_crypto.in192
-rw-r--r--third_party/heimdal/lib/hx509/test_expr.c87
-rw-r--r--third_party/heimdal/lib/hx509/test_java_pkcs11.in73
-rw-r--r--third_party/heimdal/lib/hx509/test_name.c468
-rw-r--r--third_party/heimdal/lib/hx509/test_nist.in117
-rw-r--r--third_party/heimdal/lib/hx509/test_nist2.in136
-rw-r--r--third_party/heimdal/lib/hx509/test_nist_cert.in68
-rw-r--r--third_party/heimdal/lib/hx509/test_nist_pkcs12.in77
-rw-r--r--third_party/heimdal/lib/hx509/test_pkcs11.in62
-rw-r--r--third_party/heimdal/lib/hx509/test_query.in203
-rw-r--r--third_party/heimdal/lib/hx509/test_req.in135
-rw-r--r--third_party/heimdal/lib/hx509/test_soft_pkcs11.c228
-rw-r--r--third_party/heimdal/lib/hx509/test_windows.in89
-rw-r--r--third_party/heimdal/lib/hx509/tst-crypto-available113
-rw-r--r--third_party/heimdal/lib/hx509/tst-crypto-available25
-rw-r--r--third_party/heimdal/lib/hx509/tst-crypto-available36
-rw-r--r--third_party/heimdal/lib/hx509/tst-crypto-select1
-rw-r--r--third_party/heimdal/lib/hx509/tst-crypto-select11
-rw-r--r--third_party/heimdal/lib/hx509/tst-crypto-select21
-rw-r--r--third_party/heimdal/lib/hx509/tst-crypto-select31
-rw-r--r--third_party/heimdal/lib/hx509/tst-crypto-select41
-rw-r--r--third_party/heimdal/lib/hx509/tst-crypto-select51
-rw-r--r--third_party/heimdal/lib/hx509/tst-crypto-select61
-rw-r--r--third_party/heimdal/lib/hx509/tst-crypto-select71
-rw-r--r--third_party/heimdal/lib/hx509/version-script.map302
-rw-r--r--third_party/heimdal/lib/ipc/Makefile.am72
-rw-r--r--third_party/heimdal/lib/ipc/client.c610
-rw-r--r--third_party/heimdal/lib/ipc/common.c206
-rw-r--r--third_party/heimdal/lib/ipc/heim-ipc.h133
-rw-r--r--third_party/heimdal/lib/ipc/heim_ipc.defs66
-rw-r--r--third_party/heimdal/lib/ipc/heim_ipc_async.defs56
-rw-r--r--third_party/heimdal/lib/ipc/heim_ipc_reply.defs51
-rw-r--r--third_party/heimdal/lib/ipc/heim_ipc_types.h44
-rw-r--r--third_party/heimdal/lib/ipc/hi_locl.h83
-rw-r--r--third_party/heimdal/lib/ipc/server.c1385
-rw-r--r--third_party/heimdal/lib/ipc/tc.c138
-rw-r--r--third_party/heimdal/lib/ipc/ts-http.c136
-rw-r--r--third_party/heimdal/lib/ipc/ts.c116
-rw-r--r--third_party/heimdal/lib/kadm5/ChangeLog1389
-rw-r--r--third_party/heimdal/lib/kadm5/Makefile.am230
-rw-r--r--third_party/heimdal/lib/kadm5/NTMakefile296
-rw-r--r--third_party/heimdal/lib/kadm5/acl.c242
-rw-r--r--third_party/heimdal/lib/kadm5/ad.c1489
-rw-r--r--third_party/heimdal/lib/kadm5/admin.h271
-rw-r--r--third_party/heimdal/lib/kadm5/bump_pw_expire.c59
-rw-r--r--third_party/heimdal/lib/kadm5/check-cracklib.pl112
-rw-r--r--third_party/heimdal/lib/kadm5/chpass_c.c175
-rw-r--r--third_party/heimdal/lib/kadm5/chpass_s.c466
-rw-r--r--third_party/heimdal/lib/kadm5/client_glue.c150
-rw-r--r--third_party/heimdal/lib/kadm5/common_glue.c437
-rw-r--r--third_party/heimdal/lib/kadm5/context_s.c312
-rw-r--r--third_party/heimdal/lib/kadm5/create_c.c114
-rw-r--r--third_party/heimdal/lib/kadm5/create_s.c357
-rw-r--r--third_party/heimdal/lib/kadm5/default_keys.c121
-rw-r--r--third_party/heimdal/lib/kadm5/delete_c.c88
-rw-r--r--third_party/heimdal/lib/kadm5/delete_s.c145
-rw-r--r--third_party/heimdal/lib/kadm5/destroy_c.c58
-rw-r--r--third_party/heimdal/lib/kadm5/destroy_s.c91
-rw-r--r--third_party/heimdal/lib/kadm5/ent_setup.c272
-rw-r--r--third_party/heimdal/lib/kadm5/error.c48
-rw-r--r--third_party/heimdal/lib/kadm5/flush.c48
-rw-r--r--third_party/heimdal/lib/kadm5/flush_c.c41
-rw-r--r--third_party/heimdal/lib/kadm5/flush_s.c41
-rw-r--r--third_party/heimdal/lib/kadm5/free.c92
-rw-r--r--third_party/heimdal/lib/kadm5/get_c.c96
-rw-r--r--third_party/heimdal/lib/kadm5/get_princs_c.c119
-rw-r--r--third_party/heimdal/lib/kadm5/get_princs_s.c127
-rw-r--r--third_party/heimdal/lib/kadm5/get_s.c411
-rw-r--r--third_party/heimdal/lib/kadm5/init_c.c868
-rw-r--r--third_party/heimdal/lib/kadm5/init_s.c265
-rw-r--r--third_party/heimdal/lib/kadm5/iprop-commands.in187
-rw-r--r--third_party/heimdal/lib/kadm5/iprop-log-version.rc36
-rw-r--r--third_party/heimdal/lib/kadm5/iprop-log.8254
-rw-r--r--third_party/heimdal/lib/kadm5/iprop-log.c653
-rw-r--r--third_party/heimdal/lib/kadm5/iprop.8208
-rw-r--r--third_party/heimdal/lib/kadm5/iprop.h80
-rw-r--r--third_party/heimdal/lib/kadm5/ipropd-master-version.rc36
-rw-r--r--third_party/heimdal/lib/kadm5/ipropd-slave-version.rc36
-rw-r--r--third_party/heimdal/lib/kadm5/ipropd_common.c266
-rw-r--r--third_party/heimdal/lib/kadm5/ipropd_master.c1877
-rw-r--r--third_party/heimdal/lib/kadm5/ipropd_slave.c1162
-rw-r--r--third_party/heimdal/lib/kadm5/kadm5-hook.h151
-rw-r--r--third_party/heimdal/lib/kadm5/kadm5-pwcheck.h73
-rw-r--r--third_party/heimdal/lib/kadm5/kadm5_err.et114
-rw-r--r--third_party/heimdal/lib/kadm5/kadm5_locl.h91
-rw-r--r--third_party/heimdal/lib/kadm5/kadm5_pwcheck.3159
-rw-r--r--third_party/heimdal/lib/kadm5/keys.c132
-rw-r--r--third_party/heimdal/lib/kadm5/libkadm5srv-exports.def91
-rw-r--r--third_party/heimdal/lib/kadm5/libkadm5srv-version.rc36
-rw-r--r--third_party/heimdal/lib/kadm5/log.c2756
-rw-r--r--third_party/heimdal/lib/kadm5/marshall.c474
-rw-r--r--third_party/heimdal/lib/kadm5/modify_c.c93
-rw-r--r--third_party/heimdal/lib/kadm5/modify_s.c215
-rw-r--r--third_party/heimdal/lib/kadm5/password_quality.c508
-rw-r--r--third_party/heimdal/lib/kadm5/private.h208
-rw-r--r--third_party/heimdal/lib/kadm5/privs_c.c89
-rw-r--r--third_party/heimdal/lib/kadm5/privs_s.c44
-rw-r--r--third_party/heimdal/lib/kadm5/prune_c.c73
-rw-r--r--third_party/heimdal/lib/kadm5/prune_s.c149
-rw-r--r--third_party/heimdal/lib/kadm5/randkey_c.c154
-rw-r--r--third_party/heimdal/lib/kadm5/randkey_s.c204
-rw-r--r--third_party/heimdal/lib/kadm5/rename_c.c94
-rw-r--r--third_party/heimdal/lib/kadm5/rename_s.c188
-rw-r--r--third_party/heimdal/lib/kadm5/sample_hook.c286
-rw-r--r--third_party/heimdal/lib/kadm5/sample_passwd_check.c87
-rw-r--r--third_party/heimdal/lib/kadm5/send_recv.c99
-rw-r--r--third_party/heimdal/lib/kadm5/server_glue.c150
-rw-r--r--third_party/heimdal/lib/kadm5/server_hooks.c97
-rw-r--r--third_party/heimdal/lib/kadm5/set_keys.c420
-rw-r--r--third_party/heimdal/lib/kadm5/set_modifier.c54
-rw-r--r--third_party/heimdal/lib/kadm5/setkey3_s.c220
-rw-r--r--third_party/heimdal/lib/kadm5/test_pw_quality.c99
-rw-r--r--third_party/heimdal/lib/kadm5/version-script-client.map61
-rw-r--r--third_party/heimdal/lib/kadm5/version-script.map96
-rw-r--r--third_party/heimdal/lib/kafs/ChangeLog572
-rw-r--r--third_party/heimdal/lib/kafs/Makefile.am96
-rw-r--r--third_party/heimdal/lib/kafs/NTMakefile35
-rw-r--r--third_party/heimdal/lib/kafs/afskrb5.c353
-rw-r--r--third_party/heimdal/lib/kafs/afsl.exp6
-rw-r--r--third_party/heimdal/lib/kafs/afslib.c53
-rw-r--r--third_party/heimdal/lib/kafs/afslib.exp3
-rw-r--r--third_party/heimdal/lib/kafs/afssys.c630
-rw-r--r--third_party/heimdal/lib/kafs/afssysdefs.h109
-rw-r--r--third_party/heimdal/lib/kafs/common.c469
-rw-r--r--third_party/heimdal/lib/kafs/kafs.3296
-rw-r--r--third_party/heimdal/lib/kafs/kafs.h216
-rw-r--r--third_party/heimdal/lib/kafs/kafs_locl.h163
-rw-r--r--third_party/heimdal/lib/kafs/roken_rename.h64
-rw-r--r--third_party/heimdal/lib/kafs/rxkad_kdf.c221
-rw-r--r--third_party/heimdal/lib/kdfs/ChangeLog28
-rw-r--r--third_party/heimdal/lib/kdfs/Makefile.am12
-rw-r--r--third_party/heimdal/lib/kdfs/NTMakefile35
-rw-r--r--third_party/heimdal/lib/kdfs/k5dfspag.c368
-rw-r--r--third_party/heimdal/lib/krb5/Makefile.am455
-rw-r--r--third_party/heimdal/lib/krb5/NTMakefile544
-rw-r--r--third_party/heimdal/lib/krb5/acache.c1127
-rw-r--r--third_party/heimdal/lib/krb5/acl.c293
-rw-r--r--third_party/heimdal/lib/krb5/add_et_list.c54
-rw-r--r--third_party/heimdal/lib/krb5/addr_families.c1574
-rw-r--r--third_party/heimdal/lib/krb5/aes-test.c1056
-rw-r--r--third_party/heimdal/lib/krb5/an2ln_plugin.h91
-rw-r--r--third_party/heimdal/lib/krb5/aname_to_localname.c469
-rw-r--r--third_party/heimdal/lib/krb5/appdefault.c140
-rw-r--r--third_party/heimdal/lib/krb5/asn1_glue.c162
-rw-r--r--third_party/heimdal/lib/krb5/auth_context.c621
-rw-r--r--third_party/heimdal/lib/krb5/authdata.c124
-rw-r--r--third_party/heimdal/lib/krb5/build_ap_req.c64
-rw-r--r--third_party/heimdal/lib/krb5/build_auth.c267
-rw-r--r--third_party/heimdal/lib/krb5/cache.c2300
-rw-r--r--third_party/heimdal/lib/krb5/ccache_plugin.h46
-rw-r--r--third_party/heimdal/lib/krb5/changepw.c860
-rw-r--r--third_party/heimdal/lib/krb5/codec.c214
-rw-r--r--third_party/heimdal/lib/krb5/config_file.c758
-rw-r--r--third_party/heimdal/lib/krb5/constants.c67
-rw-r--r--third_party/heimdal/lib/krb5/context.c1473
-rw-r--r--third_party/heimdal/lib/krb5/convert_creds.c95
-rw-r--r--third_party/heimdal/lib/krb5/copy_host_realm.c72
-rw-r--r--third_party/heimdal/lib/krb5/crc.c69
-rw-r--r--third_party/heimdal/lib/krb5/creds.c282
-rw-r--r--third_party/heimdal/lib/krb5/crypto-aes-sha1.c177
-rw-r--r--third_party/heimdal/lib/krb5/crypto-aes-sha2.c199
-rw-r--r--third_party/heimdal/lib/krb5/crypto-algs.c94
-rw-r--r--third_party/heimdal/lib/krb5/crypto-arcfour.c368
-rw-r--r--third_party/heimdal/lib/krb5/crypto-des-common.c158
-rw-r--r--third_party/heimdal/lib/krb5/crypto-des.c403
-rw-r--r--third_party/heimdal/lib/krb5/crypto-des3.c292
-rw-r--r--third_party/heimdal/lib/krb5/crypto-evp.c671
-rw-r--r--third_party/heimdal/lib/krb5/crypto-null.c103
-rw-r--r--third_party/heimdal/lib/krb5/crypto-pk.c295
-rw-r--r--third_party/heimdal/lib/krb5/crypto-rand.c152
-rw-r--r--third_party/heimdal/lib/krb5/crypto-stubs.c102
-rw-r--r--third_party/heimdal/lib/krb5/crypto.c3264
-rw-r--r--third_party/heimdal/lib/krb5/crypto.h231
-rw-r--r--third_party/heimdal/lib/krb5/data.c228
-rw-r--r--third_party/heimdal/lib/krb5/db_plugin.c41
-rw-r--r--third_party/heimdal/lib/krb5/db_plugin.h68
-rw-r--r--third_party/heimdal/lib/krb5/dcache.c855
-rw-r--r--third_party/heimdal/lib/krb5/deprecated.c726
-rw-r--r--third_party/heimdal/lib/krb5/derived-key-test.c145
-rw-r--r--third_party/heimdal/lib/krb5/digest.c1165
-rw-r--r--third_party/heimdal/lib/krb5/dll.c76
-rw-r--r--third_party/heimdal/lib/krb5/doxygen.c700
-rw-r--r--third_party/heimdal/lib/krb5/eai_to_heim_errno.c118
-rw-r--r--third_party/heimdal/lib/krb5/enomem.c42
-rw-r--r--third_party/heimdal/lib/krb5/error_string.c236
-rw-r--r--third_party/heimdal/lib/krb5/expand_hostname.c177
-rw-r--r--third_party/heimdal/lib/krb5/expand_path.c94
-rw-r--r--third_party/heimdal/lib/krb5/fast.c962
-rw-r--r--third_party/heimdal/lib/krb5/fcache.c1693
-rw-r--r--third_party/heimdal/lib/krb5/free.c51
-rw-r--r--third_party/heimdal/lib/krb5/free_host_realm.c59
-rw-r--r--third_party/heimdal/lib/krb5/generate_seq_number.c48
-rw-r--r--third_party/heimdal/lib/krb5/generate_subkey.c73
-rw-r--r--third_party/heimdal/lib/krb5/get_addrs.c283
-rw-r--r--third_party/heimdal/lib/krb5/get_cred.c2026
-rw-r--r--third_party/heimdal/lib/krb5/get_default_principal.c95
-rw-r--r--third_party/heimdal/lib/krb5/get_default_realm.c80
-rw-r--r--third_party/heimdal/lib/krb5/get_for_creds.c367
-rw-r--r--third_party/heimdal/lib/krb5/get_host_realm.c300
-rw-r--r--third_party/heimdal/lib/krb5/get_in_tkt.c555
-rw-r--r--third_party/heimdal/lib/krb5/get_port.c52
-rw-r--r--third_party/heimdal/lib/krb5/init_creds.c436
-rw-r--r--third_party/heimdal/lib/krb5/init_creds_pw.c4011
-rw-r--r--third_party/heimdal/lib/krb5/k524_err.et20
-rw-r--r--third_party/heimdal/lib/krb5/k5e1_err.et13
-rw-r--r--third_party/heimdal/lib/krb5/kcm.c1506
-rw-r--r--third_party/heimdal/lib/krb5/kcm.h87
-rw-r--r--third_party/heimdal/lib/krb5/kerberos.8115
-rw-r--r--third_party/heimdal/lib/krb5/keyblock.c203
-rw-r--r--third_party/heimdal/lib/krb5/keytab.c975
-rw-r--r--third_party/heimdal/lib/krb5/keytab_any.c260
-rw-r--r--third_party/heimdal/lib/krb5/keytab_file.c856
-rw-r--r--third_party/heimdal/lib/krb5/keytab_keyfile.c456
-rw-r--r--third_party/heimdal/lib/krb5/keytab_memory.c231
-rw-r--r--third_party/heimdal/lib/krb5/krb5-plugin.7359
-rw-r--r--third_party/heimdal/lib/krb5/krb5-v4compat.h139
-rw-r--r--third_party/heimdal/lib/krb5/krb5.conf.51442
-rw-r--r--third_party/heimdal/lib/krb5/krb5.h1069
-rw-r--r--third_party/heimdal/lib/krb5/krb5.moduli3
-rw-r--r--third_party/heimdal/lib/krb5/krb524_convert_creds_kdc.386
-rw-r--r--third_party/heimdal/lib/krb5/krb5_425_conv_principal.3224
-rw-r--r--third_party/heimdal/lib/krb5/krb5_acl_match_file.3111
-rw-r--r--third_party/heimdal/lib/krb5/krb5_aname_to_localname.380
-rw-r--r--third_party/heimdal/lib/krb5/krb5_appdefault.388
-rw-r--r--third_party/heimdal/lib/krb5/krb5_auth_context.3395
-rw-r--r--third_party/heimdal/lib/krb5/krb5_c_make_checksum.3297
-rw-r--r--third_party/heimdal/lib/krb5/krb5_ccapi.h239
-rw-r--r--third_party/heimdal/lib/krb5/krb5_check_transited.3106
-rw-r--r--third_party/heimdal/lib/krb5/krb5_create_checksum.3226
-rw-r--r--third_party/heimdal/lib/krb5/krb5_creds.3119
-rw-r--r--third_party/heimdal/lib/krb5/krb5_digest.3260
-rw-r--r--third_party/heimdal/lib/krb5/krb5_eai_to_heim_errno.368
-rw-r--r--third_party/heimdal/lib/krb5/krb5_encrypt.3278
-rw-r--r--third_party/heimdal/lib/krb5/krb5_err.et314
-rw-r--r--third_party/heimdal/lib/krb5/krb5_find_padata.387
-rw-r--r--third_party/heimdal/lib/krb5/krb5_generate_random_block.357
-rw-r--r--third_party/heimdal/lib/krb5/krb5_get_all_client_addrs.374
-rw-r--r--third_party/heimdal/lib/krb5/krb5_get_credentials.3181
-rw-r--r--third_party/heimdal/lib/krb5/krb5_get_creds.3173
-rw-r--r--third_party/heimdal/lib/krb5/krb5_get_forwarded_creds.379
-rw-r--r--third_party/heimdal/lib/krb5/krb5_get_in_cred.3274
-rw-r--r--third_party/heimdal/lib/krb5/krb5_get_init_creds.3403
-rw-r--r--third_party/heimdal/lib/krb5/krb5_get_krbhst.386
-rw-r--r--third_party/heimdal/lib/krb5/krb5_getportbyname.367
-rw-r--r--third_party/heimdal/lib/krb5/krb5_init_context.3308
-rw-r--r--third_party/heimdal/lib/krb5/krb5_is_thread_safe.358
-rw-r--r--third_party/heimdal/lib/krb5/krb5_krbhst_init.3174
-rw-r--r--third_party/heimdal/lib/krb5/krb5_locl.h485
-rw-r--r--third_party/heimdal/lib/krb5/krb5_mk_req.3187
-rw-r--r--third_party/heimdal/lib/krb5/krb5_mk_safe.382
-rw-r--r--third_party/heimdal/lib/krb5/krb5_openlog.3305
-rw-r--r--third_party/heimdal/lib/krb5/krb5_parse_name.367
-rw-r--r--third_party/heimdal/lib/krb5/krb5_principal.3371
-rw-r--r--third_party/heimdal/lib/krb5/krb5_rcache.3163
-rw-r--r--third_party/heimdal/lib/krb5/krb5_rd_error.398
-rw-r--r--third_party/heimdal/lib/krb5/krb5_rd_safe.381
-rw-r--r--third_party/heimdal/lib/krb5/krb5_set_default_realm.3164
-rw-r--r--third_party/heimdal/lib/krb5/krb5_set_password.3143
-rw-r--r--third_party/heimdal/lib/krb5/krb5_string_to_key.3156
-rw-r--r--third_party/heimdal/lib/krb5/krb5_timeofday.3118
-rw-r--r--third_party/heimdal/lib/krb5/krb5_verify_init_creds.3103
-rw-r--r--third_party/heimdal/lib/krb5/krb5_verify_user.3241
-rw-r--r--third_party/heimdal/lib/krb5/krb_err.et63
-rw-r--r--third_party/heimdal/lib/krb5/krbhst-test.c109
-rw-r--r--third_party/heimdal/lib/krb5/krbhst.c1275
-rw-r--r--third_party/heimdal/lib/krb5/krcache.c2075
-rw-r--r--third_party/heimdal/lib/krb5/kuserok.c753
-rw-r--r--third_party/heimdal/lib/krb5/kuserok_plugin.h91
-rw-r--r--third_party/heimdal/lib/krb5/kx509.c1323
-rw-r--r--third_party/heimdal/lib/krb5/kx509_err.et39
-rw-r--r--third_party/heimdal/lib/krb5/libkrb5-exports.def.in895
-rw-r--r--third_party/heimdal/lib/krb5/locate_plugin.h81
-rw-r--r--third_party/heimdal/lib/krb5/log.c252
-rw-r--r--third_party/heimdal/lib/krb5/mcache.c623
-rw-r--r--third_party/heimdal/lib/krb5/misc.c111
-rw-r--r--third_party/heimdal/lib/krb5/mit_glue.c434
-rw-r--r--third_party/heimdal/lib/krb5/mk_cred.c324
-rw-r--r--third_party/heimdal/lib/krb5/mk_error.c117
-rw-r--r--third_party/heimdal/lib/krb5/mk_priv.c151
-rw-r--r--third_party/heimdal/lib/krb5/mk_rep.c119
-rw-r--r--third_party/heimdal/lib/krb5/mk_req.c114
-rw-r--r--third_party/heimdal/lib/krb5/mk_req_ext.c151
-rw-r--r--third_party/heimdal/lib/krb5/mk_safe.c139
-rw-r--r--third_party/heimdal/lib/krb5/n-fold-test.c119
-rw-r--r--third_party/heimdal/lib/krb5/n-fold.c150
-rw-r--r--third_party/heimdal/lib/krb5/net_read.c53
-rw-r--r--third_party/heimdal/lib/krb5/net_write.c118
-rw-r--r--third_party/heimdal/lib/krb5/pac.c2130
-rw-r--r--third_party/heimdal/lib/krb5/padata.c62
-rw-r--r--third_party/heimdal/lib/krb5/parse-name-test.c192
-rw-r--r--third_party/heimdal/lib/krb5/pcache.c81
-rw-r--r--third_party/heimdal/lib/krb5/pkinit-ec.c241
-rw-r--r--third_party/heimdal/lib/krb5/pkinit.c2674
-rw-r--r--third_party/heimdal/lib/krb5/plugin.c208
-rw-r--r--third_party/heimdal/lib/krb5/principal.c2205
-rw-r--r--third_party/heimdal/lib/krb5/prog_setup.c64
-rw-r--r--third_party/heimdal/lib/krb5/prompter_posix.c72
-rw-r--r--third_party/heimdal/lib/krb5/pseudo-random-test.c112
-rw-r--r--third_party/heimdal/lib/krb5/rd_cred.c348
-rw-r--r--third_party/heimdal/lib/krb5/rd_error.c125
-rw-r--r--third_party/heimdal/lib/krb5/rd_priv.c184
-rw-r--r--third_party/heimdal/lib/krb5/rd_rep.c121
-rw-r--r--third_party/heimdal/lib/krb5/rd_req.c1108
-rw-r--r--third_party/heimdal/lib/krb5/rd_safe.c214
-rw-r--r--third_party/heimdal/lib/krb5/read_message.c104
-rw-r--r--third_party/heimdal/lib/krb5/recvauth.c264
-rw-r--r--third_party/heimdal/lib/krb5/replay.c328
-rw-r--r--third_party/heimdal/lib/krb5/salt-aes-sha1.c102
-rw-r--r--third_party/heimdal/lib/krb5/salt-aes-sha2.c135
-rw-r--r--third_party/heimdal/lib/krb5/salt-arcfour.c107
-rw-r--r--third_party/heimdal/lib/krb5/salt-des.c222
-rw-r--r--third_party/heimdal/lib/krb5/salt-des3.c146
-rw-r--r--third_party/heimdal/lib/krb5/salt.c362
-rw-r--r--third_party/heimdal/lib/krb5/scache.c1599
-rw-r--r--third_party/heimdal/lib/krb5/send_to_kdc.c1357
-rw-r--r--third_party/heimdal/lib/krb5/send_to_kdc_plugin.h70
-rw-r--r--third_party/heimdal/lib/krb5/sendauth.c255
-rw-r--r--third_party/heimdal/lib/krb5/set_default_realm.c85
-rw-r--r--third_party/heimdal/lib/krb5/sock_principal.c68
-rwxr-xr-xthird_party/heimdal/lib/krb5/sp800-108-kdf.c100
-rw-r--r--third_party/heimdal/lib/krb5/store-int.c67
-rw-r--r--third_party/heimdal/lib/krb5/store-int.h50
-rw-r--r--third_party/heimdal/lib/krb5/store-test.c117
-rw-r--r--third_party/heimdal/lib/krb5/store.c2041
-rw-r--r--third_party/heimdal/lib/krb5/store_emem.c214
-rw-r--r--third_party/heimdal/lib/krb5/store_fd.c200
-rw-r--r--third_party/heimdal/lib/krb5/store_mem.c212
-rw-r--r--third_party/heimdal/lib/krb5/store_sock.c160
-rw-r--r--third_party/heimdal/lib/krb5/store_stdio.c264
-rw-r--r--third_party/heimdal/lib/krb5/string-to-key-test.c140
-rw-r--r--third_party/heimdal/lib/krb5/test_acl.c118
-rw-r--r--third_party/heimdal/lib/krb5/test_addr.c239
-rw-r--r--third_party/heimdal/lib/krb5/test_alname.c219
-rw-r--r--third_party/heimdal/lib/krb5/test_ap-req.c228
-rwxr-xr-xthird_party/heimdal/lib/krb5/test_canon.c177
-rw-r--r--third_party/heimdal/lib/krb5/test_cc.c1218
-rw-r--r--third_party/heimdal/lib/krb5/test_config.c246
-rw-r--r--third_party/heimdal/lib/krb5/test_config_strings.cfg12
-rw-r--r--third_party/heimdal/lib/krb5/test_crypto.c216
-rw-r--r--third_party/heimdal/lib/krb5/test_crypto_wrapping.c168
-rw-r--r--third_party/heimdal/lib/krb5/test_expand_toks.c104
-rw-r--r--third_party/heimdal/lib/krb5/test_forward.c134
-rw-r--r--third_party/heimdal/lib/krb5/test_fx.c253
-rw-r--r--third_party/heimdal/lib/krb5/test_get_addrs.c111
-rw-r--r--third_party/heimdal/lib/krb5/test_gic.c148
-rw-r--r--third_party/heimdal/lib/krb5/test_hostname.c150
-rw-r--r--third_party/heimdal/lib/krb5/test_keytab.c291
-rw-r--r--third_party/heimdal/lib/krb5/test_kuserok.c109
-rw-r--r--third_party/heimdal/lib/krb5/test_mem.c71
-rw-r--r--third_party/heimdal/lib/krb5/test_mkforwardable.c191
-rw-r--r--third_party/heimdal/lib/krb5/test_pac.c1255
-rw-r--r--third_party/heimdal/lib/krb5/test_pkinit_dh2key.c216
-rw-r--r--third_party/heimdal/lib/krb5/test_pknistkdf.c373
-rw-r--r--third_party/heimdal/lib/krb5/test_plugin.c131
-rw-r--r--third_party/heimdal/lib/krb5/test_prf.c100
-rw-r--r--third_party/heimdal/lib/krb5/test_princ.c365
-rw-r--r--third_party/heimdal/lib/krb5/test_renew.c119
-rw-r--r--third_party/heimdal/lib/krb5/test_rfc3961.c522
-rw-r--r--third_party/heimdal/lib/krb5/test_set_kvno0.c182
-rw-r--r--third_party/heimdal/lib/krb5/test_store.c364
-rw-r--r--third_party/heimdal/lib/krb5/test_time.c85
-rw-r--r--third_party/heimdal/lib/krb5/test_x500.c110
-rw-r--r--third_party/heimdal/lib/krb5/ticket.c967
-rw-r--r--third_party/heimdal/lib/krb5/time.c138
-rw-r--r--third_party/heimdal/lib/krb5/transited.c699
-rw-r--r--third_party/heimdal/lib/krb5/verify_init.c246
-rw-r--r--third_party/heimdal/lib/krb5/verify_krb5_conf-version.rc36
-rw-r--r--third_party/heimdal/lib/krb5/verify_krb5_conf.895
-rw-r--r--third_party/heimdal/lib/krb5/verify_krb5_conf.c795
-rw-r--r--third_party/heimdal/lib/krb5/verify_user.c258
-rw-r--r--third_party/heimdal/lib/krb5/version-script.map886
-rw-r--r--third_party/heimdal/lib/krb5/version.c39
-rw-r--r--third_party/heimdal/lib/krb5/warn.c330
-rw-r--r--third_party/heimdal/lib/krb5/write_message.c87
-rw-r--r--third_party/heimdal/lib/libedit/COPYING30
-rw-r--r--third_party/heimdal/lib/libedit/ChangeLog300
-rw-r--r--third_party/heimdal/lib/libedit/INSTALL229
-rw-r--r--third_party/heimdal/lib/libedit/Makefile.am9
-rw-r--r--third_party/heimdal/lib/libedit/THANKS1
-rw-r--r--third_party/heimdal/lib/libedit/acinclude.m466
-rw-r--r--third_party/heimdal/lib/libedit/config.h.in218
-rw-r--r--third_party/heimdal/lib/libedit/configure.ac111
-rw-r--r--third_party/heimdal/lib/libedit/doc/Makefile.am33
-rw-r--r--third_party/heimdal/lib/libedit/doc/editline.3.roff883
-rw-r--r--third_party/heimdal/lib/libedit/doc/editrc.5.roff490
-rw-r--r--third_party/heimdal/lib/libedit/doc/mdoc2man.awk459
-rw-r--r--third_party/heimdal/lib/libedit/examples/Makefile.am14
-rw-r--r--third_party/heimdal/lib/libedit/examples/fileman.c496
-rw-r--r--third_party/heimdal/lib/libedit/examples/tc1.c309
-rw-r--r--third_party/heimdal/lib/libedit/examples/wtc1.c269
-rw-r--r--third_party/heimdal/lib/libedit/libedit.pc.in12
-rw-r--r--third_party/heimdal/lib/libedit/src/Makefile.am43
-rw-r--r--third_party/heimdal/lib/libedit/src/chared.c753
-rw-r--r--third_party/heimdal/lib/libedit/src/chared.h155
-rw-r--r--third_party/heimdal/lib/libedit/src/chartype.c340
-rw-r--r--third_party/heimdal/lib/libedit/src/chartype.h114
-rw-r--r--third_party/heimdal/lib/libedit/src/common.c835
-rw-r--r--third_party/heimdal/lib/libedit/src/editline.3997
-rw-r--r--third_party/heimdal/lib/libedit/src/editline.7935
-rw-r--r--third_party/heimdal/lib/libedit/src/editrc.5317
-rw-r--r--third_party/heimdal/lib/libedit/src/el.c640
-rw-r--r--third_party/heimdal/lib/libedit/src/el.h153
-rw-r--r--third_party/heimdal/lib/libedit/src/eln.c388
-rw-r--r--third_party/heimdal/lib/libedit/src/emacs.c512
-rw-r--r--third_party/heimdal/lib/libedit/src/filecomplete.c573
-rw-r--r--third_party/heimdal/lib/libedit/src/filecomplete.h44
-rw-r--r--third_party/heimdal/lib/libedit/src/getline.c128
-rw-r--r--third_party/heimdal/lib/libedit/src/hist.c245
-rw-r--r--third_party/heimdal/lib/libedit/src/hist.h79
-rw-r--r--third_party/heimdal/lib/libedit/src/histedit.h313
-rw-r--r--third_party/heimdal/lib/libedit/src/history.c1157
-rw-r--r--third_party/heimdal/lib/libedit/src/historyn.c3
-rw-r--r--third_party/heimdal/lib/libedit/src/keymacro.c669
-rw-r--r--third_party/heimdal/lib/libedit/src/keymacro.h76
-rw-r--r--third_party/heimdal/lib/libedit/src/makelist177
-rw-r--r--third_party/heimdal/lib/libedit/src/map.c1427
-rw-r--r--third_party/heimdal/lib/libedit/src/map.h79
-rw-r--r--third_party/heimdal/lib/libedit/src/parse.c289
-rw-r--r--third_party/heimdal/lib/libedit/src/parse.h48
-rw-r--r--third_party/heimdal/lib/libedit/src/prompt.c199
-rw-r--r--third_party/heimdal/lib/libedit/src/prompt.h58
-rw-r--r--third_party/heimdal/lib/libedit/src/read.c628
-rw-r--r--third_party/heimdal/lib/libedit/src/read.h45
-rw-r--r--third_party/heimdal/lib/libedit/src/readline.c2367
-rw-r--r--third_party/heimdal/lib/libedit/src/readline/readline.h227
-rw-r--r--third_party/heimdal/lib/libedit/src/refresh.c1187
-rw-r--r--third_party/heimdal/lib/libedit/src/refresh.h57
-rw-r--r--third_party/heimdal/lib/libedit/src/search.c641
-rw-r--r--third_party/heimdal/lib/libedit/src/search.h64
-rw-r--r--third_party/heimdal/lib/libedit/src/shlib_version5
-rw-r--r--third_party/heimdal/lib/libedit/src/sig.c205
-rw-r--r--third_party/heimdal/lib/libedit/src/sig.h70
-rw-r--r--third_party/heimdal/lib/libedit/src/sys.h112
-rw-r--r--third_party/heimdal/lib/libedit/src/terminal.c1691
-rw-r--r--third_party/heimdal/lib/libedit/src/terminal.h125
-rw-r--r--third_party/heimdal/lib/libedit/src/tokenizer.c466
-rw-r--r--third_party/heimdal/lib/libedit/src/tokenizern.c3
-rw-r--r--third_party/heimdal/lib/libedit/src/tty.c1342
-rw-r--r--third_party/heimdal/lib/libedit/src/tty.h481
-rw-r--r--third_party/heimdal/lib/libedit/src/unvis.c553
-rw-r--r--third_party/heimdal/lib/libedit/src/vi.c1157
-rw-r--r--third_party/heimdal/lib/libedit/src/vis.c728
-rw-r--r--third_party/heimdal/lib/libedit/src/vis.h120
-rw-r--r--third_party/heimdal/lib/libedit/src/wcsdup.c43
-rw-r--r--third_party/heimdal/lib/ntlm/ChangeLog120
-rw-r--r--third_party/heimdal/lib/ntlm/Makefile.am49
-rw-r--r--third_party/heimdal/lib/ntlm/NTMakefile90
-rw-r--r--third_party/heimdal/lib/ntlm/apop.c263
-rw-r--r--third_party/heimdal/lib/ntlm/digest.c994
-rw-r--r--third_party/heimdal/lib/ntlm/heim-auth.h135
-rw-r--r--third_party/heimdal/lib/ntlm/heimntlm.h166
-rw-r--r--third_party/heimdal/lib/ntlm/libheimntlm-exports.def24
-rw-r--r--third_party/heimdal/lib/ntlm/libheimntlm-version.rc36
-rw-r--r--third_party/heimdal/lib/ntlm/ntlm.c2030
-rw-r--r--third_party/heimdal/lib/ntlm/ntlm_err.et60
-rw-r--r--third_party/heimdal/lib/ntlm/test_commonauth.c425
-rw-r--r--third_party/heimdal/lib/ntlm/test_ntlm.c617
-rw-r--r--third_party/heimdal/lib/ntlm/version-script.map30
-rw-r--r--third_party/heimdal/lib/otp/ChangeLog128
-rw-r--r--third_party/heimdal/lib/otp/Makefile.am90
-rw-r--r--third_party/heimdal/lib/otp/NTMakefile35
-rw-r--r--third_party/heimdal/lib/otp/otp.c63
-rw-r--r--third_party/heimdal/lib/otp/otp.h101
-rw-r--r--third_party/heimdal/lib/otp/otp_challenge.c68
-rw-r--r--third_party/heimdal/lib/otp/otp_db.c233
-rw-r--r--third_party/heimdal/lib/otp/otp_locl.h70
-rw-r--r--third_party/heimdal/lib/otp/otp_md.c231
-rw-r--r--third_party/heimdal/lib/otp/otp_md.h46
-rw-r--r--third_party/heimdal/lib/otp/otp_parse.c2522
-rw-r--r--third_party/heimdal/lib/otp/otp_print.c99
-rw-r--r--third_party/heimdal/lib/otp/otp_verify.c78
-rw-r--r--third_party/heimdal/lib/otp/otptest.c142
-rw-r--r--third_party/heimdal/lib/otp/roken_rename.h73
-rw-r--r--third_party/heimdal/lib/otp/version-script.map25
-rw-r--r--third_party/heimdal/lib/roken/ChangeLog2229
-rw-r--r--third_party/heimdal/lib/roken/Makefile.am290
-rw-r--r--third_party/heimdal/lib/roken/NTMakefile312
-rw-r--r--third_party/heimdal/lib/roken/base32-test.c106
-rw-r--r--third_party/heimdal/lib/roken/base32.c315
-rw-r--r--third_party/heimdal/lib/roken/base32.h61
-rw-r--r--third_party/heimdal/lib/roken/base64-test.c97
-rw-r--r--third_party/heimdal/lib/roken/base64.c258
-rw-r--r--third_party/heimdal/lib/roken/base64.h55
-rw-r--r--third_party/heimdal/lib/roken/bswap.c74
-rw-r--r--third_party/heimdal/lib/roken/chown.c42
-rw-r--r--third_party/heimdal/lib/roken/cloexec.c75
-rw-r--r--third_party/heimdal/lib/roken/closefrom.c57
-rw-r--r--third_party/heimdal/lib/roken/clz.c69
-rw-r--r--third_party/heimdal/lib/roken/concat.c110
-rw-r--r--third_party/heimdal/lib/roken/copyhostent.c98
-rw-r--r--third_party/heimdal/lib/roken/ct.c82
-rw-r--r--third_party/heimdal/lib/roken/daemon.c80
-rw-r--r--third_party/heimdal/lib/roken/detach.c226
-rw-r--r--third_party/heimdal/lib/roken/dirent-test.c278
-rw-r--r--third_party/heimdal/lib/roken/dirent.c235
-rw-r--r--third_party/heimdal/lib/roken/dirent.hin66
-rw-r--r--third_party/heimdal/lib/roken/dlfcn.hin109
-rw-r--r--third_party/heimdal/lib/roken/dlfcn_w32.c700
-rw-r--r--third_party/heimdal/lib/roken/doxygen.c44
-rw-r--r--third_party/heimdal/lib/roken/dumpdata.c96
-rw-r--r--third_party/heimdal/lib/roken/ecalloc.384
-rw-r--r--third_party/heimdal/lib/roken/ecalloc.c53
-rw-r--r--third_party/heimdal/lib/roken/emalloc.c53
-rw-r--r--third_party/heimdal/lib/roken/environment.c162
-rw-r--r--third_party/heimdal/lib/roken/eread.c51
-rw-r--r--third_party/heimdal/lib/roken/erealloc.c53
-rw-r--r--third_party/heimdal/lib/roken/err.c46
-rw-r--r--third_party/heimdal/lib/roken/err.hin99
-rw-r--r--third_party/heimdal/lib/roken/errx.c45
-rw-r--r--third_party/heimdal/lib/roken/esetenv.c45
-rw-r--r--third_party/heimdal/lib/roken/estrdup.c53
-rw-r--r--third_party/heimdal/lib/roken/ewrite.c51
-rw-r--r--third_party/heimdal/lib/roken/fchown.c42
-rw-r--r--third_party/heimdal/lib/roken/flock.c154
-rw-r--r--third_party/heimdal/lib/roken/fnmatch.c175
-rw-r--r--third_party/heimdal/lib/roken/fnmatch.hin66
-rw-r--r--third_party/heimdal/lib/roken/freeaddrinfo.c54
-rw-r--r--third_party/heimdal/lib/roken/freehostent.c59
-rw-r--r--third_party/heimdal/lib/roken/fseeko.c48
-rw-r--r--third_party/heimdal/lib/roken/ftello.c48
-rw-r--r--third_party/heimdal/lib/roken/gai_strerror.c74
-rw-r--r--third_party/heimdal/lib/roken/get_window_size.c132
-rw-r--r--third_party/heimdal/lib/roken/getaddrinfo-test.c151
-rw-r--r--third_party/heimdal/lib/roken/getaddrinfo.c414
-rw-r--r--third_party/heimdal/lib/roken/getaddrinfo_hostspec.c101
-rw-r--r--third_party/heimdal/lib/roken/getarg.3341
-rw-r--r--third_party/heimdal/lib/roken/getarg.c607
-rw-r--r--third_party/heimdal/lib/roken/getarg.h112
-rw-r--r--third_party/heimdal/lib/roken/getauxval.c255
-rw-r--r--third_party/heimdal/lib/roken/getauxval.h176
-rw-r--r--third_party/heimdal/lib/roken/getcwd.c54
-rw-r--r--third_party/heimdal/lib/roken/getdtablesize.c99
-rw-r--r--third_party/heimdal/lib/roken/getegid.c46
-rw-r--r--third_party/heimdal/lib/roken/geteuid.c46
-rw-r--r--third_party/heimdal/lib/roken/getgid.c45
-rw-r--r--third_party/heimdal/lib/roken/gethostname.c70
-rw-r--r--third_party/heimdal/lib/roken/getifaddrs-test.c137
-rw-r--r--third_party/heimdal/lib/roken/getifaddrs.c1309
-rw-r--r--third_party/heimdal/lib/roken/getifaddrs_w32.c161
-rw-r--r--third_party/heimdal/lib/roken/getipnodebyaddr.c71
-rw-r--r--third_party/heimdal/lib/roken/getipnodebyname.c83
-rw-r--r--third_party/heimdal/lib/roken/getnameinfo.c124
-rw-r--r--third_party/heimdal/lib/roken/getnameinfo_verified.c94
-rw-r--r--third_party/heimdal/lib/roken/getopt.c124
-rw-r--r--third_party/heimdal/lib/roken/getprogname.c48
-rw-r--r--third_party/heimdal/lib/roken/gettimeofday.c94
-rw-r--r--third_party/heimdal/lib/roken/getuid.c45
-rw-r--r--third_party/heimdal/lib/roken/getuserinfo.c334
-rw-r--r--third_party/heimdal/lib/roken/getusershell.c185
-rw-r--r--third_party/heimdal/lib/roken/h_errno.c38
-rw-r--r--third_party/heimdal/lib/roken/hex-test.c115
-rw-r--r--third_party/heimdal/lib/roken/hex.c114
-rw-r--r--third_party/heimdal/lib/roken/hex.h57
-rw-r--r--third_party/heimdal/lib/roken/hostent_find_fqdn.c56
-rw-r--r--third_party/heimdal/lib/roken/hstrerror.c78
-rw-r--r--third_party/heimdal/lib/roken/ifaddrs.hin79
-rw-r--r--third_party/heimdal/lib/roken/inet_aton.c46
-rw-r--r--third_party/heimdal/lib/roken/inet_ntop.c151
-rw-r--r--third_party/heimdal/lib/roken/inet_pton.c116
-rw-r--r--third_party/heimdal/lib/roken/initgroups.c42
-rw-r--r--third_party/heimdal/lib/roken/innetgr.c45
-rw-r--r--third_party/heimdal/lib/roken/install-sh251
-rw-r--r--third_party/heimdal/lib/roken/issuid.c276
-rw-r--r--third_party/heimdal/lib/roken/localtime_r.c60
-rw-r--r--third_party/heimdal/lib/roken/lstat.c42
-rw-r--r--third_party/heimdal/lib/roken/memmem.c72
-rw-r--r--third_party/heimdal/lib/roken/memmove.c62
-rw-r--r--third_party/heimdal/lib/roken/memset_s.c51
-rw-r--r--third_party/heimdal/lib/roken/mergesort.c50
-rw-r--r--third_party/heimdal/lib/roken/mergesort_r.c339
-rw-r--r--third_party/heimdal/lib/roken/mini_inetd.c197
-rw-r--r--third_party/heimdal/lib/roken/missing190
-rw-r--r--third_party/heimdal/lib/roken/mkdir.c53
-rw-r--r--third_party/heimdal/lib/roken/mkdtemp.c87
-rw-r--r--third_party/heimdal/lib/roken/mkinstalldirs40
-rw-r--r--third_party/heimdal/lib/roken/mkostemp.c87
-rw-r--r--third_party/heimdal/lib/roken/mkstemp.c82
-rw-r--r--third_party/heimdal/lib/roken/ndbm_wrap.c227
-rw-r--r--third_party/heimdal/lib/roken/ndbm_wrap.h93
-rw-r--r--third_party/heimdal/lib/roken/net_read.c118
-rw-r--r--third_party/heimdal/lib/roken/net_write.c134
-rw-r--r--third_party/heimdal/lib/roken/parse_bytes-test.c89
-rw-r--r--third_party/heimdal/lib/roken/parse_bytes.c81
-rw-r--r--third_party/heimdal/lib/roken/parse_bytes.h50
-rw-r--r--third_party/heimdal/lib/roken/parse_reply-test.c126
-rw-r--r--third_party/heimdal/lib/roken/parse_time-test.c118
-rw-r--r--third_party/heimdal/lib/roken/parse_time.3173
-rw-r--r--third_party/heimdal/lib/roken/parse_time.c104
-rw-r--r--third_party/heimdal/lib/roken/parse_time.h72
-rw-r--r--third_party/heimdal/lib/roken/parse_units.c525
-rw-r--r--third_party/heimdal/lib/roken/parse_units.h116
-rw-r--r--third_party/heimdal/lib/roken/putenv.c79
-rw-r--r--third_party/heimdal/lib/roken/qsort.c203
-rw-r--r--third_party/heimdal/lib/roken/rand.c74
-rw-r--r--third_party/heimdal/lib/roken/rcmd.c49
-rw-r--r--third_party/heimdal/lib/roken/readv.c64
-rw-r--r--third_party/heimdal/lib/roken/realloc.c47
-rw-r--r--third_party/heimdal/lib/roken/recvmsg.c66
-rw-r--r--third_party/heimdal/lib/roken/rename.c49
-rw-r--r--third_party/heimdal/lib/roken/resolve-test.c309
-rw-r--r--third_party/heimdal/lib/roken/resolve.c956
-rw-r--r--third_party/heimdal/lib/roken/resolve.h251
-rw-r--r--third_party/heimdal/lib/roken/rkpty.c392
-rw-r--r--third_party/heimdal/lib/roken/roken-common.h566
-rw-r--r--third_party/heimdal/lib/roken/roken.awk46
-rw-r--r--third_party/heimdal/lib/roken/roken.h.in1330
-rw-r--r--third_party/heimdal/lib/roken/roken_gethostby.c292
-rw-r--r--third_party/heimdal/lib/roken/rtbl.3201
-rw-r--r--third_party/heimdal/lib/roken/rtbl.c558
-rw-r--r--third_party/heimdal/lib/roken/rtbl.h124
-rw-r--r--third_party/heimdal/lib/roken/search.hin44
-rw-r--r--third_party/heimdal/lib/roken/secure_getenv.c47
-rw-r--r--third_party/heimdal/lib/roken/secure_getenv.h42
-rw-r--r--third_party/heimdal/lib/roken/sendmsg.c148
-rw-r--r--third_party/heimdal/lib/roken/setegid.c54
-rw-r--r--third_party/heimdal/lib/roken/setenv.c74
-rw-r--r--third_party/heimdal/lib/roken/seteuid.c54
-rw-r--r--third_party/heimdal/lib/roken/setprogname.c91
-rw-r--r--third_party/heimdal/lib/roken/signal.c77
-rw-r--r--third_party/heimdal/lib/roken/simple_exec.c325
-rw-r--r--third_party/heimdal/lib/roken/simple_exec_w32.c431
-rw-r--r--third_party/heimdal/lib/roken/sleep.c55
-rw-r--r--third_party/heimdal/lib/roken/snprintf-test.c268
-rw-r--r--third_party/heimdal/lib/roken/snprintf.c700
-rw-r--r--third_party/heimdal/lib/roken/socket.c371
-rw-r--r--third_party/heimdal/lib/roken/socket_wrapper.c1911
-rw-r--r--third_party/heimdal/lib/roken/socket_wrapper.h146
-rw-r--r--third_party/heimdal/lib/roken/sockstartup_w32.c75
-rw-r--r--third_party/heimdal/lib/roken/stdbool.hin13
-rw-r--r--third_party/heimdal/lib/roken/stdint.hin43
-rw-r--r--third_party/heimdal/lib/roken/strcasecmp.c55
-rw-r--r--third_party/heimdal/lib/roken/strcollect.c93
-rw-r--r--third_party/heimdal/lib/roken/strdup.c47
-rw-r--r--third_party/heimdal/lib/roken/strerror.c54
-rw-r--r--third_party/heimdal/lib/roken/strerror_r.c84
-rw-r--r--third_party/heimdal/lib/roken/strftime.c402
-rw-r--r--third_party/heimdal/lib/roken/strlcat.c60
-rw-r--r--third_party/heimdal/lib/roken/strlcpy.c73
-rw-r--r--third_party/heimdal/lib/roken/strlwr.c50
-rw-r--r--third_party/heimdal/lib/roken/strncasecmp.c59
-rw-r--r--third_party/heimdal/lib/roken/strndup.c53
-rw-r--r--third_party/heimdal/lib/roken/strnlen.c46
-rw-r--r--third_party/heimdal/lib/roken/strpftime-test.c295
-rw-r--r--third_party/heimdal/lib/roken/strpftime-test.h61
-rw-r--r--third_party/heimdal/lib/roken/strpool.c114
-rw-r--r--third_party/heimdal/lib/roken/strptime.c449
-rw-r--r--third_party/heimdal/lib/roken/strsep.c58
-rw-r--r--third_party/heimdal/lib/roken/strsep_copy.c66
-rw-r--r--third_party/heimdal/lib/roken/strtok_r.c62
-rw-r--r--third_party/heimdal/lib/roken/strtoll.c155
-rw-r--r--third_party/heimdal/lib/roken/strtoull.c129
-rw-r--r--third_party/heimdal/lib/roken/strupr.c50
-rw-r--r--third_party/heimdal/lib/roken/swab.c50
-rw-r--r--third_party/heimdal/lib/roken/syslog.hin248
-rw-r--r--third_party/heimdal/lib/roken/syslogc.c339
-rw-r--r--third_party/heimdal/lib/roken/test-auxval.c236
-rw-r--r--third_party/heimdal/lib/roken/test-detach.c100
-rw-r--r--third_party/heimdal/lib/roken/test-getuserinfo.c136
-rw-r--r--third_party/heimdal/lib/roken/test-mem.c215
-rw-r--r--third_party/heimdal/lib/roken/test-mem.h39
-rw-r--r--third_party/heimdal/lib/roken/test-mini_inetd.c371
-rw-r--r--third_party/heimdal/lib/roken/test-readenv.c115
-rw-r--r--third_party/heimdal/lib/roken/timegm.c85
-rw-r--r--third_party/heimdal/lib/roken/timeval.c286
-rw-r--r--third_party/heimdal/lib/roken/tm2time.c58
-rw-r--r--third_party/heimdal/lib/roken/tsearch-test.c125
-rw-r--r--third_party/heimdal/lib/roken/tsearch.c175
-rw-r--r--third_party/heimdal/lib/roken/unsetenv.c69
-rw-r--r--third_party/heimdal/lib/roken/unvis.c283
-rw-r--r--third_party/heimdal/lib/roken/verr.c44
-rw-r--r--third_party/heimdal/lib/roken/verrx.c44
-rw-r--r--third_party/heimdal/lib/roken/version-script.map238
-rw-r--r--third_party/heimdal/lib/roken/versionsupport.h139
-rw-r--r--third_party/heimdal/lib/roken/vis-extras.h27
-rw-r--r--third_party/heimdal/lib/roken/vis.c649
-rw-r--r--third_party/heimdal/lib/roken/vis.hin170
-rw-r--r--third_party/heimdal/lib/roken/vsyslog.c113
-rw-r--r--third_party/heimdal/lib/roken/vwarn.c43
-rw-r--r--third_party/heimdal/lib/roken/vwarnx.c44
-rw-r--r--third_party/heimdal/lib/roken/warn.c46
-rw-r--r--third_party/heimdal/lib/roken/warnerr.c58
-rw-r--r--third_party/heimdal/lib/roken/warnx.c45
-rw-r--r--third_party/heimdal/lib/roken/win32_alloc.c76
-rw-r--r--third_party/heimdal/lib/roken/win32_version.c128
-rw-r--r--third_party/heimdal/lib/roken/write_pid.c117
-rw-r--r--third_party/heimdal/lib/roken/writev.c61
-rw-r--r--third_party/heimdal/lib/roken/xdbm.h52
-rw-r--r--third_party/heimdal/lib/roken/xfree.c42
-rw-r--r--third_party/heimdal/lib/sl/ChangeLog329
-rw-r--r--third_party/heimdal/lib/sl/Makefile.am50
-rw-r--r--third_party/heimdal/lib/sl/NTMakefile74
-rw-r--r--third_party/heimdal/lib/sl/roken_rename.h67
-rw-r--r--third_party/heimdal/lib/sl/sl.c499
-rw-r--r--third_party/heimdal/lib/sl/sl.h71
-rw-r--r--third_party/heimdal/lib/sl/sl_locl.h45
-rw-r--r--third_party/heimdal/lib/sl/slc-gram.y791
-rw-r--r--third_party/heimdal/lib/sl/slc-lex.l158
-rw-r--r--third_party/heimdal/lib/sl/slc.h56
-rw-r--r--third_party/heimdal/lib/sl/test_sl.c98
-rw-r--r--third_party/heimdal/lib/sqlite/Makefile.am20
-rw-r--r--third_party/heimdal/lib/sqlite/NTMakefile52
-rw-r--r--third_party/heimdal/lib/sqlite/README25
-rw-r--r--third_party/heimdal/lib/sqlite/sqlite3.c231382
-rw-r--r--third_party/heimdal/lib/sqlite/sqlite3.h12229
-rw-r--r--third_party/heimdal/lib/sqlite/sqlite3ext.h659
-rw-r--r--third_party/heimdal/lib/vers/ChangeLog74
-rw-r--r--third_party/heimdal/lib/vers/Makefile.am13
-rw-r--r--third_party/heimdal/lib/vers/NTMakefile56
-rw-r--r--third_party/heimdal/lib/vers/make-print-version.c66
-rw-r--r--third_party/heimdal/lib/vers/print_version.c59
-rw-r--r--third_party/heimdal/lib/vers/vers.h41
-rw-r--r--third_party/heimdal/lib/wind/ChangeLog136
-rw-r--r--third_party/heimdal/lib/wind/CompositionExclusions-3.2.0.txt176
-rw-r--r--third_party/heimdal/lib/wind/DerivedNormalizationProps.txt2574
-rw-r--r--third_party/heimdal/lib/wind/Makefile.am147
-rw-r--r--third_party/heimdal/lib/wind/NTMakefile159
-rw-r--r--third_party/heimdal/lib/wind/NormalizationCorrections.txt43
-rw-r--r--third_party/heimdal/lib/wind/NormalizationTest.txt17166
-rw-r--r--third_party/heimdal/lib/wind/UnicodeData.py57
-rw-r--r--third_party/heimdal/lib/wind/UnicodeData.txt15100
-rw-r--r--third_party/heimdal/lib/wind/bidi.c92
-rw-r--r--third_party/heimdal/lib/wind/combining.c62
-rw-r--r--third_party/heimdal/lib/wind/doxygen.c47
-rw-r--r--third_party/heimdal/lib/wind/errorlist.c77
-rw-r--r--third_party/heimdal/lib/wind/gen-bidi.py102
-rw-r--r--third_party/heimdal/lib/wind/gen-combining.py104
-rw-r--r--third_party/heimdal/lib/wind/gen-errorlist.py121
-rw-r--r--third_party/heimdal/lib/wind/gen-map.py158
-rw-r--r--third_party/heimdal/lib/wind/gen-normalize.py211
-rw-r--r--third_party/heimdal/lib/wind/gen-punycode-examples.py130
-rw-r--r--third_party/heimdal/lib/wind/generate.py86
-rw-r--r--third_party/heimdal/lib/wind/idn-lookup.c164
-rw-r--r--third_party/heimdal/lib/wind/ldap.c91
-rw-r--r--third_party/heimdal/lib/wind/libwind-exports.def27
-rw-r--r--third_party/heimdal/lib/wind/map.c85
-rw-r--r--third_party/heimdal/lib/wind/normalize.c325
-rw-r--r--third_party/heimdal/lib/wind/punycode.c168
-rw-r--r--third_party/heimdal/lib/wind/rfc3454.py60
-rw-r--r--third_party/heimdal/lib/wind/rfc4518.py150
-rw-r--r--third_party/heimdal/lib/wind/stringprep.c145
-rw-r--r--third_party/heimdal/lib/wind/stringprep.py92
-rw-r--r--third_party/heimdal/lib/wind/test-bidi.c81
-rw-r--r--third_party/heimdal/lib/wind/test-ldap.c128
-rw-r--r--third_party/heimdal/lib/wind/test-map.c98
-rw-r--r--third_party/heimdal/lib/wind/test-normalize.c176
-rw-r--r--third_party/heimdal/lib/wind/test-prohibited.c138
-rw-r--r--third_party/heimdal/lib/wind/test-punycode.c83
-rw-r--r--third_party/heimdal/lib/wind/test-rw.c186
-rw-r--r--third_party/heimdal/lib/wind/test-utf8.c174
-rw-r--r--third_party/heimdal/lib/wind/utf8.c527
-rw-r--r--third_party/heimdal/lib/wind/util.py48
-rw-r--r--third_party/heimdal/lib/wind/version-script.map29
-rw-r--r--third_party/heimdal/lib/wind/wind.h86
-rw-r--r--third_party/heimdal/lib/wind/wind_err.et23
-rw-r--r--third_party/heimdal/lib/wind/windlocl.h67
1749 files changed, 736066 insertions, 0 deletions
diff --git a/third_party/heimdal/lib/Makefile.am b/third_party/heimdal/lib/Makefile.am
new file mode 100644
index 0000000..dc70116
--- /dev/null
+++ b/third_party/heimdal/lib/Makefile.am
@@ -0,0 +1,50 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+if LIBEDIT
+dir_editline = libedit
+endif
+if OTP
+dir_otp = otp
+endif
+if DCE
+dir_dce = kdfs
+endif
+if COM_ERR
+dir_com_err = com_err
+endif
+if !SQLITE3
+dir_sqlite = sqlite
+endif
+if MAINTAINER_MODE
+dir_sqlite = sqlite
+endif
+if !NO_AFS
+dir_afs = kafs
+endif
+
+SUBDIRS = \
+ roken \
+ vers \
+ $(dir_com_err) \
+ base \
+ $(dir_editline) \
+ sl \
+ wind \
+ asn1 \
+ $(dir_sqlite) \
+ hcrypto \
+ ipc \
+ hx509 \
+ krb5 \
+ ntlm \
+ $(dir_afs) \
+ gssapi \
+ gss_preauth \
+ hdb \
+ kadm5 \
+ $(dir_otp) \
+ $(dir_dce)
+
+EXTRA_DIST = NTMakefile heimdal
diff --git a/third_party/heimdal/lib/NTMakefile b/third_party/heimdal/lib/NTMakefile
new file mode 100644
index 0000000..39a0db5
--- /dev/null
+++ b/third_party/heimdal/lib/NTMakefile
@@ -0,0 +1,79 @@
+########################################################################
+#
+# Copyright (c) 2009-2016, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+
+!ifdef OTP
+dir_otp = otp
+!endif
+!ifdef DCE
+dir_dce = kdfs
+!endif
+
+# Third party plugins must be added to the assembly
+# Permit third party assembly scripts
+
+!if exist(..\thirdparty\plugin\NTMakefile)
+plugin=..\thirdparty\plugin
+!endif
+
+!if exist(..\thirdparty\assembly\NTMakefile)
+assembly=..\thirdparty\assembly
+!else
+assembly=..\packages\windows\assembly
+!endif
+
+SUBDIRS = roken vers com_err base sl wind asn1 sqlite \
+ hcrypto hx509 krb5 heimdal ntlm kafs gssapi gss_preauth \
+ hdb kadm5 $(dir_otp) $(dir_dce) $(plugin) $(assembly)
+
+!include ../windows/NTMakefile.w32
+
+# We can't build some of the lib tools until after we have LIBHEIMDAL.
+# So we build tools in a separate build step:
+
+all:: all-tools
+
+all-tools:: asn1-tools hx509-tools krb5-tools kadm5-tools gss-tools
+
+asn1-tools:
+ @( cd asn1 && $(RMAKE) all-tools && cd .. ) || exit /b 1
+
+hx509-tools:
+ @( cd hx509 && $(RMAKE) all-tools && cd .. ) || exit /b 1
+
+krb5-tools:
+ @( cd krb5 && $(RMAKE) all-tools && cd .. ) || exit /b 1
+
+kadm5-tools:
+ @( cd kadm5 && $(RMAKE) all-tools && cd .. ) || exit /b 1
+
+gss-tools:
+ @( cd gssapi && $(RMAKE) all-tools && cd ..) || exit /b 1
diff --git a/third_party/heimdal/lib/asn1/ChangeLog b/third_party/heimdal/lib/asn1/ChangeLog
new file mode 100644
index 0000000..523e24b
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/ChangeLog
@@ -0,0 +1,1665 @@
+2008-04-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * pkinit.asn1: add id-pkinit-kdf
+
+ * pkinit.asn1: add PkinitSP80056AOtherInfo
+
+2008-04-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen.c: Use unsigned where appropriate.
+
+2008-03-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * k5.asn1: Match name in ClientCanonicalizedNames with -10
+
+ * k5.asn1: add referral-valid-until
+
+2008-01-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * asn1-common.h gen.c der.c gen_encode.c: add and use der_{malloc,free}
+
+2007-12-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * libasn1.h: remove, not used.
+
+2007-12-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add DigestTypes, add --seq to antoher type.
+
+ * digest.asn1: Add supportedMechs request.
+
+2007-10-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * k5.asn1: Some "old" windows enctypes. From Andy Polyakov.
+
+2007-07-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Fold in pk-init-alg-agilty.
+
+ * pkinit.asn1: Fold in pk-init-alg-agilty.
+
+2007-07-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * parse.y: Passe object id is its part of the module defintion
+ statement.
+
+2007-07-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-gen.c: test SEQ OF SIZE (...)
+
+ * Makefile.am: Include more sizeof tests.
+
+2007-07-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * try to avoid aliasing of pointers enum {} vs int
+
+2007-07-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test.asn1: Test SIZE attribute for SEQ and OCTET STRING
+
+ * parse.y (OctetStringType): add SIZE to OCTET STRING.
+
+ * Makefile.am: New library version.
+
+2007-07-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rfc2459.asn1: Re-add size limits.
+
+ * k5.asn1: Add size limits from RFC 4120.
+
+ * gen_decode.c: Check range on SEQ OF and OCTET STRING.
+
+ * asn1_err.et (min|max|exact) constraints.
+
+ * parse.y: Parse size limitations to SEQ OF.
+
+2007-06-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add AuthorityInfoAccessSyntax.
+
+ * rfc2459.asn1: Add AuthorityInfoAccessSyntax.
+
+ * rfc2459.asn1: Add authorityInfoAccess, rename proxyCertInfo.
+
+ * Makefile.am: Add authorityInfoAccess, rename proxyCertInfo.
+
+2007-06-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * der_get.c (der_get_time): avoid using wrapping of octet_string
+ and realloc.
+
+ * der_get.c: No need to undef timetm, we don't use it any more.
+
+ * timegm.c: Fix spelling caused by too much query-replace.
+
+ * gen.c: Include <limits.h> for UINT_MAX.
+
+ * gen_decode.c: Check for multipication overrun.
+
+ * gen_encode.c: Paranoia check in buffer overun in output
+ function.
+
+ * check-der.c: Test boolean.
+
+ * check-der.c: test universal strings.
+
+ * check-der.c: Test failure cases for der_get_tag.
+
+ * check-der.c: test dates from last century.
+
+ * check-der.c: Move zero length integercheck to a better place.
+
+ * check-der.c: Test zero length integer.
+
+2007-06-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-der.c: Init data to something.
+
+2007-06-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * k5.asn1: Add KRB5-AUTHDATA-INITIAL-VERIFIED-CAS.
+
+2007-06-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * pkinit.asn1: Make the pkinit nonce signed (like the kerberos
+ nonce).
+
+2007-06-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-der.c: Free more memory.
+
+ * der_format.c: Don't accect zero length hex numbers.
+
+ * check-der.c: Also free right memory.
+
+ * main.c: Close asn1 file when done.
+
+ * check-der.c: more check for der_parse_hex_heim_integer
+
+ * der_format.c (der_parse_hex_heim_integer): check length before
+ reading data.
+
+ * check-gen.c (test_authenticator): free memory
+
+2007-05-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add MS-UPN-SAN
+
+ * pkinit.asn1: add MS-UPN-SAN
+
+ * rfc2459.asn1: Do evil things to handle IMPLICIT encoded
+ structures. Add id-ms-client-authentication.
+
+2007-05-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add asn1_id_ms_cert_enroll_domaincontroller.x
+
+2007-05-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen.c: Add struct units; as a forward declaration. Pointed out
+ by Marcus Watts.
+
+ * rfc2459.asn1: Netscape extentions
+
+ * Makefile.am: add U.S. Federal PKI Common Policy Framework
+
+ * rfc2459.asn1: add U.S. Federal PKI Common Policy Framework
+
+2007-04-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_seq.c: Handle the case of resize to 0 and realloc that
+ returns NULL.
+
+ * check-gen.c (check_seq): free seq.
+
+2007-04-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-der.c (test_heim_oid_format_same): avoid leaking memory in
+ the non failure case too
+
+2007-04-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: remove extra ^Q
+
+2007-04-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * der_get.c: Allow trailing NULs. We allow this since MIT Kerberos
+ sends an strings in the NEED_PREAUTH case that includes a trailing
+ NUL.
+
+2007-02-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+
+ * Makefile.am: Add PA-ClientCanonicalized and friends.
+
+ * k5.asn1: Add PA-ClientCanonicalized and friends.
+
+2007-02-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-der.c: Drop one over INT_MAX test-case.
+
+2007-02-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * pkinit.asn1: add id-pkinit-ms-eku
+
+ * pkinit.asn1: fill in more bits of id-pkinit-ms-san
+
+2007-02-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * digest.asn1: rename hash-a1 to session key
+
+2007-02-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * digest.asn1: Add elements to send in requestResponse to KDC and
+ get status of the request.
+
+2007-01-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: seq rules for CRLDistributionPoints
+
+2007-01-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add CRLDistributionPoints and friends
+
+2007-01-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-der.c: check BMPstring oddlength more
+
+ * check-der.c: Test for NUL char in string in GENERAL STRING.
+
+ * der_get.c: Check for NUL characters in string and return
+ ASN1_BAD_CHARACTER error-code if we find them.
+
+ * asn1_err.et: Add BAD_CHARACTER error.
+
+2007-01-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add id-at-streetAddress.
+
+ * rfc2459.asn1: Add id-at-streetAddress.
+
+2007-01-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rfc2459.asn1: Add PKIXXmppAddr and id-pkix-on-xmppAddr.
+
+2006-12-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add id-pkix-kp oids.
+
+ * rfc2459.asn1: Add id-pkix-kp oids.
+
+2006-12-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_encode.c: Named bit strings have this horrible, disgusting,
+ compress bits until they are no longer really there but stuff in
+ an initial octet anyway encoding scheme. Try to get it right and
+ calculate the initial octet runtime instead of compiletime.
+
+ * check-gen.c: Check all other silly bitstring combinations.
+
+ * Makefile.am: Add --sequence=Extensions to rfc2459.
+
+2006-12-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * kx509.asn1: Add kx509.
+
+ * Makefile.am: Add kx509.
+
+ * Add VisibleString parsing
+
+2006-12-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add ntlm files.
+
+ * digest.asn1: Add bits for handling NTLM.
+
+2006-12-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add pkix proxy cert policy lang oids
+
+ * rfc2459.asn1: add pkix proxy cert policy lang oids
+
+2006-12-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rfc2459.asn1: unbreak id-pe-proxyCertInfo
+
+ * rfc2459.asn1: Add id-pkix-on-dnsSRV and related oids
+
+2006-11-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add explicit depenency to LIB_roken for libasn1.la,
+ make AIX happy.
+
+2006-11-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * der_format.c (der_print_heim_oid): oid with zero length is
+ invalid, fail to print.
+
+2006-11-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * der_format.c (der_print_heim_oid): use delim when printing.
+
+2006-11-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * k5.asn1: Make KRB5-PADATA-S4U2SELF pa type 129.
+
+2006-10-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * asn1_err.et: add EXTRA_DATA
+
+2006-10-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-gen.c: avoid leaking memory
+
+ * check-der.c: avoid leaking memory
+
+ * der_format.c (der_parse_heim_oid): avoid leaking memory
+
+ * check-common.c: Print size_t as (unsigned long) and cast.
+
+ * check-common.c: Try to align data, IA64's gets upset if its
+ unaligned.
+
+ * lex.l: add missing */
+
+ * lex.c: need %e for hpux lex
+
+2006-10-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: remove dups from gen_files_test, add check-timegm.
+
+ * Makefile.am: include more test.asn1 built files
+
+ * Makefile.am: More files, now for make check.
+
+2006-10-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add missing files
+
+ * Makefile.am (asn1_compile_SOURCES): add gen_locl.h
+
+ * check-timegm.c: Add check for _der_timegm.
+
+ * der_get.c (generalizedtime2time): always use _der_timegm.
+
+ * timegm.c: make more strict
+
+ * der_locl.h: Rename timegm to _der_timegm.
+
+2006-10-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * timegm.c: vJust fail if tm_mon is out of range for now XXXX this
+ is wrong.
+
+2006-10-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: extra depencies on der-protos.h
+
+2006-10-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-der.c: Prefix primitive types with der_.
+
+ * timegm.c: rename the buildin timegm to _der_timegm
+
+ * heim_asn1.h: move prototype away from here.
+
+ * der_format.c: Add der_parse_heim_oid
+
+ * gen_free.c: prefix primitive types with der_
+
+ * der_copy.c: prefix primitive types with der_
+
+ * gen_length.c: prefix primitive types with der_
+
+ * der_length.c: prefix primitive types with der_
+
+ * der_cmp.c: prefix primitive types with der_
+
+ * gen_free.c: prefix primitive types with der_
+
+ * der_free.c: prefix primitive types with der_
+
+ * gen_copy.c: prefix primitive types with der_
+
+ * der_copy.c: rename copy_ to der_copy_
+
+ * Makefile.am: Add der-protos.h to nodist_include_HEADERS.
+
+ * der.h: use newly built <der-protos.h>
+
+ * Makefile.am: Generate der prototypes.
+
+ * gen.c: move any definitions here.
+
+ * asn1-common.h: move any definitions here.
+
+ * der.h: remove der_parse_oid prototype, it was never implemented.
+
+ * der.h: New der_print_heim_oid signature. Test
+ der_parse_heim_oid
+
+ * check-der.c: New der_print_heim_oid signature. Test
+ der_parse_heim_oid
+
+2006-10-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * lex.l: Grow an even larger output table size.
+
+ * Makefile.am: split build files into dist_ and noinst_ SOURCES
+
+2006-10-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_seq.c: In generation of remove_TYPE: if you just removed the
+ last element, you must not memmove memory beyond the array. From
+ Andrew Bartlett
+
+2006-10-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * lex.l: Grow (%p, %a, %n) tables for Solaris 10 lex. From Harald
+ Barth.
+
+2006-09-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_decode.c (decode_type): drop unused variable realtype.
+
+2006-09-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add KRB5SignedPath and friends.
+
+ * k5.asn1: Add KRB5SignedPath and friends.
+
+ * Makefile.am: Add new sequence generation for GeneralNames.
+
+2006-09-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * CMS.asn1 (CMSVersion): rename versions from v0 to CMSVersion_v0,
+ ...
+
+2006-09-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add TESTSeqOf for testing sequence generation code.
+
+ * check-gen.c: Add sequence tests.
+
+ * test.asn1: Add TESTSeqOf for testing sequence generation code.
+
+ * gen_seq.c: fix warning.
+
+ * gen_seq.c: make generated data work
+
+ * setchgpw2.asn1: enctype is part of the krb5 module now, use that
+ instead of locally defining it.
+
+ * Makefile.am: asn1_compile += gen_seq.c
+
+ * gen_locl.h: add new prototypes, remove unused ones.
+
+ * gen.c: Generate sequence function.
+
+ * main.c: add --sequence
+
+ * gen_seq.c: Add generated add_ and remove_ for "SEQUENCE OF
+ TType". I'm tried of writing realloc(foo->data,
+ sizeof(foo->data[0]) + (foo->len + 1)); Only generated for those
+ type that is enabled by the command flag --sequence.
+
+2006-08-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * digest.asn1 (DigestRequest): add authid
+
+ * digest.asn1: Comment describing on how to communicate the sasl
+ int/conf mode.
+
+2006-08-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * digest.asn1: Add some missing fields needed for digest.
+
+2006-08-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * digest.asn1: Tweak to make consisten and more easier to use.
+
+2006-07-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Remove CMS symmetric encryption support. Add
+ DigestProtocol.
+
+ * digest.asn1: DigestProtocol
+
+ * k5.asn1: Remove CMS symmetric encryption support.
+
+2006-06-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-der.c (check_fail_heim_integer): disable test
+
+ * der_get.c (der_get_heim_integer): revert part of previous
+
+ * der_get.c (der_get_heim_integer): Add more checks
+
+ * asn1_print.c: Add printing of bignums and use der_print_heim_oid
+
+ * check-der.c (test_heim_oid_format_same): add printing on failure
+
+ * check-der.c: Add one check for heim_int, add checking for oid
+ printing
+
+2006-06-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Impersonation support bits (and sort)
+
+ * k5.asn1: Impersonation support bits.
+
+2006-05-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * der_format.c (der_parse_hex_heim_integer): avoid shadowing.
+
+2006-04-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add ExternalPrincipalIdentifiers, shared between
+ several elements.
+
+ * pkinit.asn1: Add ExternalPrincipalIdentifiers, shared between
+ several elements.
+
+2006-04-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * parse.y: Add missing ;'s, found by bison on a SuSE 8.2 machine.
+
+2006-04-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add definitions from RFC 3820, Proxy Certificate
+ Profile.
+
+ * rfc2459.asn1: Add definitions from RFC 3820, Proxy Certificate
+ Profile.
+
+2006-04-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rfc2459.asn1: Add id-Userid
+
+ * Makefile.am: Add UID and email
+
+ * pkcs9.asn1: Add id-pkcs9-emailAddress
+
+ * Makefile.am: Add attribute type oids from X520 and RFC 2247 DC
+ oid
+
+ * rfc2459.asn1: Add attribute type oids from X520 and RFC 2247 DC
+ oid
+
+2006-04-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add sha-1 and sha-2
+
+ * rfc2459.asn1: add sha-1 and sha-2
+
+2006-04-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add id-pkcs1-sha256WithRSAEncryption and friends
+
+ * rfc2459.asn1: Add id-pkcs1-sha256WithRSAEncryption and friends
+
+ * CMS.asn1: Turn CMSRC2CBCParameter.rc2ParameterVersion into a
+ constrained integer
+
+2006-04-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hash.c (hashtabnew): check for NULL before setting structure.
+ Coverity, NetBSD CID#4
+
+2006-03-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: gen_files_rfc2459 += asn1_ExtKeyUsage.x
+
+ * rfc2459.asn1: Add ExtKeyUsage.
+
+ * gen.c (generate_header_of_codefile): remove unused variable.
+
+2006-03-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen.c: Put all the IMPORTed headers into the headerfile to avoid
+ hidden depencies.
+
+2006-03-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add id-pkinit-ms-san.
+
+ * pkinit.asn1: Add id-pkinit-ms-san.
+
+ * k5.asn1 (PADATA-TYPE): Add KRB5-PADATA-PA-PK-OCSP-RESPONSE
+
+2006-03-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add pkinit-san.
+
+ * pkinit.asn1: Rename id-pksan to id-pkinit-san
+
+2006-03-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen.c (init_generate): Nothing in the generated files needs
+ timegm(), so no need to provide a prototype for it.
+
+2006-02-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * pkinit.asn1: paChecksum is now OPTIONAL so it can be upgraded to
+ something better then SHA1
+
+2006-01-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * extra.c: Stub-generator now generates alloc statements for
+ tagless ANY OPTIONAL, remove workaround.
+
+ * check-gen.c: check for "tagless ANY OPTIONAL"
+
+ * test.asn1: check for "tagless ANY OPTIONAL"
+
+2006-01-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * der.h: UniversalString and BMPString are both implemented.
+
+ * der.h: Remove , after the last element of enum.
+
+ * asn1_gen.c: Spelling.
+
+2006-01-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * der_length.c (length_heim_integer): Try handle negative length
+ of integers better.
+
+ * der_get.c (der_get_heim_integer): handle negative integers.
+
+ * check-der.c: check heim_integer.
+
+2006-01-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Its cRLReason, not cRLReasons
+
+ * canthandle.asn1: "Allocation is done on CONTEXT tags" works just
+ fine.
+
+ * rfc2459.asn1: Add CRL structures and OIDs.
+
+ * Makefile.am: Add CRL and TESTAlloc structures and OIDs.
+
+ * check-gen.c: Check OPTIONAL context-tagless elements.
+
+ * test.asn1: Check OPTIONAL context-tagless elements.
+
+ * der_cmp.c (heim_integer_cmp): make it work with negative
+ numbers.
+
+2006-01-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-der.c: check that der_parse_hex_heim_integer() handles odd
+ length numbers.
+
+ * der_format.c (der_parse_hex_heim_integer): make more resiliant
+ to errors, handle odd length numbers.
+
+2006-01-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add RSAPrivateKey
+
+ * rfc2459.asn1: Add RSAPrivateKey.
+
+2006-01-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * der_copy.c (copy_heim_integer): copy the negative flag
+
+2005-12-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * parse.y: Drop ExceptionSpec for now, its not used.
+
+2005-12-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test.asn1: Add test string for constraints.
+
+ * symbol.h: Add support for part of the Constraint-s
+
+ * gen.c: Set new constraints pointer in Type to NULL for inline
+ constructed types.
+
+ * parse.y: Add support for parsing part of the Constraint-s
+
+2005-10-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add some X9.57 (DSA) oids, sort lines
+
+ * rfc2459.asn1: Add some X9.57 (DSA) oids.
+
+2005-10-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Remove pk-init-19 support.
+
+ * pkinit.asn1: Fix comment
+
+ * check-der.c: Add tests for parse and print functions for
+ heim_integer.
+
+ * Makefile.am: Add parse and print functions for heim_integer.
+
+ * der_format.c: Add parse and print functions for heim_integer.
+
+ * der.h: Add parse and print functions for heim_integer.
+
+2005-09-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am (gen_files_rfc2459) += asn1_DHPublicKey.x
+
+ * rfc2459.asn1: Add DHPublicKey, and INTEGER to for storing the DH
+ public key in the SubjectPublicKeyInfo.subjectPublicKey BIT
+ STRING.
+
+2005-09-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_decode.c: TSequenceOf/TSetOf: Increase the length of the
+ array after successful decoding the next element, so that the
+ array don't contain heap-data.
+
+2005-09-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-der.c: Avoid empty array initiators.
+
+ * pkcs8.asn1 (PKCS8PrivateKeyInfo): Inline SET OF to avoid
+ compiler "feature"
+
+ * check-common.c: Avoid signedness warnings.
+
+ * check-common.h: Makes bytes native platform signed to avoid
+ casting everywhere
+
+ * check-der.c: Don't depend on malloc(very-very-larger-value) will
+ fail. Cast to unsigned long before printing size_t.
+
+ * check-gen.c: Don't depend on malloc(very-very-larger-value) will
+ fail.
+
+ * check-gen.c: Fix signedness warnings.
+
+ * lex.l: unput() have to hanppen in actions for flex 2.5.31, can
+ do them in user code sesction, so move up handle_comment and
+ handle_string into action, not much sharing was done anyway.
+
+2005-09-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-der.c (test_one_int): len and len_len is size_t
+
+2005-08-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_encode.c: Change name of oldret for each instance its used
+ to avoid shadow warning. From: Stefan Metzmacher
+ <metze@samba.org>.
+
+ * gen_length.c: Change name of oldret for each instance its used
+ to avoid shadow warning. From: Stefan Metzmacher
+ <metze@samba.org>.
+
+ * gen_decode.c: Change name of oldret for each instance its used
+ to avoid shadow warning. From: Stefan Metzmacher
+ <metze@samba.org>.
+
+ * parse.y: Const poision yyerror.
+
+ * gen.c: Const poision.
+
+2005-08-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * k5.asn1: Add KRB5-PADATA-PK-AS-09-BINDING, client send
+ this (with an empty pa-data.padata-value) to tell the KDC that the
+ client support the binding the PA-REP to the AS-REQ packet. This
+ is to fix the problem lack of binding the AS-REQ to the PK-AS-REP
+ in pre PK-INIT-27. The nonce is replaced with a asCheckSum.
+
+2005-08-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * canthandle.asn1: Allocation is done on CONTEXT tags.
+
+ * asn1_gen.c: rename optind to optidx to avoid shadow warnings
+
+2005-07-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rfc2459.asn1: add id-rsadsi-rc2-cbc
+
+ * Makefile.am: add another oid for rc2
+
+2005-07-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-der.c: Make variable initiation constant by moving them to
+ global context
+
+ * check-gen.c: change to c89 comment
+
+2005-07-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: remove duplicate asn1_CMSAttributes.x
+
+2005-07-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * asn1_print.c: rename optind to optidx
+
+ * Makefile.am: Update to pkinit-27
+
+ * pkinit.asn1: Update to pkinit-27
+
+2005-07-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-der.c: make it work for non c99 compilers too
+
+ * check-der.c: start testing BIT STRING
+
+ * der_cmp.c (heim_bit_string_cmp): try handle corner cases better
+
+ * gen_free.c (free_type): free bignum integers
+
+2005-07-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add PKCS12-OctetString
+
+ * pkcs12.asn1: add PKCS12-OctetString
+
+ * Makefile.am: add new files
+
+ * rfc2459.asn1: include SET OF in Attribute to make the type more
+ useful
+
+ * CMS.asn1: handle IMPLICIT and share some common structures
+
+2005-07-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rfc2459.asn1: Include enough workarounds that this even might
+ work.
+
+ * check-gen.c: Two implicit tests, one with all structures inlined
+
+ * test.asn1: fix workaround for IMPLICIT CONS case
+
+ * canthandle.asn1: fix workaround for IMPLICIT CONS case
+
+ * asn1_print.c: hint that there are IMPLICIT content when we find
+ it
+
+ * check-gen.c: Added #ifdef out test for IMPLICIT tagging.
+
+ * Makefile.am: test several IMPLICIT tag level deep
+
+ * test.asn1: test several IMPLICIT tag level deep
+
+ * test.asn1: tests for IMPLICIT
+
+ * Makefile.am: tests for IMPLICIT
+
+ * canthandle.asn1: Expand on what is wrong with the IMPLICIT
+ tagging
+
+ * rfc2459.asn1: some of the structure are in the IMPLICIT TAGS
+ module
+
+2005-07-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * asn1_print.c: print size_t by casting to unsigned long and use
+ right printf format tags are unsigned integers
+
+ * gen.c (generate_constant): oid elements are unsigned
+
+ * gen_decode.c (decode_type): tagdatalen should be an size_t.
+
+ * extra.c (decode_heim_any): tag is unsigned int.
+
+ * der_get.c (der_match_tag): tag is unsigned int.
+
+ * gen_length.c (length_type): cast size_t argument to unsigned
+ long and use appropriate printf format
+
+ * check-der.c (check_fail_bitstring): check for length overflow
+
+ * der_get.c: rewrite integer overflow tests w/o SIZE_T_MAX
+
+ * check-common.c (generic_decode_fail): only copy in if checklen
+ its less then 0xffffff and larger than 0.
+
+ * gen_decode.c (find_tag): find external references, we can't
+ handle those, so tell user that instead of crashing
+
+2005-07-18 Dave Love <fx@gnu.org>
+
+ * extra.c (free_heim_any_set): Fix return.
+
+ * gen_decode.c (find_tag): Fix return in TType case.
+
+2005-07-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_encode.c (TChoice): add () to make sure variable expression
+ is evaluated correctly
+
+ * gen_length.c (TChoice): add () to make sure variable expression
+ is evaluated correctly
+
+ * k5.asn1: reapply 1.43 that got lost in the merge: rename pvno to
+ krb5-pvno
+
+2005-07-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_decode.c (decode_type): TChoice: set the label
+
+ * check-gen.c (cmp_Name): do at least some checking
+
+ * gen_locl.h: rename function filename() to get_filename() to
+ avoid shadowing
+
+ * lex.l: rename function filename() to get_filename() to avoid
+ shadowing
+
+ * gen.c: rename function filename() to get_filename() to avoid
+ shadowing
+
+ * check-der.c: add failure checks for large oid elements
+
+ * check-gen.c: add failure checks for tag (and large tags)
+
+ * der_get.c: Check for integer overflows in tags and oid elements.
+
+2005-07-10 Assar Westerlund <assar@kth.se>
+
+ * gen_decode.c: Fix decoding of choices to select which branch to
+ try based on the tag and return an error if that branch fails.
+
+ * check-gen.c: Fix short choice test cases.
+
+2005-07-09 Assar Westerlund <assar@kth.se>
+
+ * symbol.c:
+ * parse.y:
+ * main.c:
+ * lex.l:
+ * gen_length.c:
+ * gen_free.c:
+ * gen_encode.c:
+ * gen_decode.c:
+ * gen_copy.c:
+ * gen.c:
+ * extra.c:
+ * check-gen.c:
+ * check-der.c:
+ * check-common.c:
+ * asn1_print.c:
+ * asn1_gen.c:
+ Use emalloc, ecalloc, and estrdup.
+ Check return value from asprintf.
+ Make sure that malloc(0) returning NULL is not treated as an
+ error.
+
+2005-07-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-gen.c: test cases for CHOICE, its too liberal right now,
+ it don't fail hard on failure on after it successfully decoded the
+ first tag in a choice branch
+
+ * asn1_gen.c: calculate the basename for the output file,
+ pretty-print tag number
+
+ * test.gen: sample for asn1_gen
+
+ * check-gen.c: check errors in SEQUENCE
+
+ * Makefile.am: build asn1_gen, TESTSeq and new, and class/type/tag
+ string<->num converter.
+
+ * test.asn1: TESTSeq, for testing SEQUENCE
+
+ * asn1_gen.c: generator for asn1 data
+
+ * asn1_print.c: use class/type/tag string<->num converter.
+
+ * der.c: Add class/type/tag string<->num converter.
+
+ * der.h: Add class/type/tag string<->num converter.
+ Prototypes/structures for new time bits.
+
+2005-07-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * der_get.c (der_get_unsigned) check for length overflow
+ (der_get_integer) ditto
+ (der_get_general_string) ditto
+
+ * der_get.c: check for overruns using SIZE_T_MAX
+
+ * check-der.c: check BIT STRING and OBJECT IDENTIFIER error cases
+
+ * check-common.c (generic_decode_fail): allocate 4K for the over
+ sized memory test
+
+ * der_get.c (der_get_oid): check for integer overruns and
+ unterminated oid correctly
+
+ * check-common.h (map_alloc, generic_decode_fail): prototypes
+
+ * check-common.c (map_alloc): make input buffer const
+ (generic_decode_fail): verify decoding failures
+
+2005-07-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_encode.c: split up the printf for SET OF, also use the
+ generate name for the symbol in the SET OF, if not, the name might
+ contain non valid variable name characters (like -)
+
+2005-07-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: move pkcs12 defines into their own namespace
+
+ * pkcs12.asn1: move pkcs12 defines into their own namespace
+
+ * pkcs9.asn1: add PKCS9-friendlyName with workaround for SET OF
+ bug
+
+ * heim_asn1.h: reuse heim_octet_string for heim_any types
+
+ * main.c: use optidx, handle the case where name is missing and
+ use base of filename then
+
+ * asn1-common.h: include ASN1_MALLOC_ENCODE
+
+ * gen_decode.c: use less context so lower indentention level, add
+ missing {} where needed
+
+2005-07-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_copy.c: Use a global variable to keep track of if the 'goto
+ fail' was used, and use that to only generate the label if needed.
+
+ * asn1_print.c: do indefinite form loop detection and stop after
+ 10000 recursive indefinite forms, stops crashing due to running
+ out of stack
+
+ * asn1_print.c: catch badly formated indefinite length data
+ (missing EndOfContent tag) add (negative) indent flag to speed up
+ testing
+
+2005-07-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * canthandle.asn1: Can't handle primitives in CHOICE
+
+ * gen_decode.c: Check if malloc failes
+
+ * gen_copy.c: Make sure to free memory on failure
+
+ * gen_decode.c: Check if malloc failes, rename "reallen" to
+ tagdatalen since that is what it is.
+
+2005-05-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * prefix Der_class with ASN1_C_ to avoid problems with system
+ headerfiles that pollute the name space
+
+2005-05-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * pkcs12.asn1: add PKCS12CertBag
+
+ * pkcs9.asn1: add pkcs9 certtype x509 certificate
+
+ * Makefile.am: add pkcs12 certbag and pkcs9 certtype x509
+ certificate
+
+ * pkcs12.asn1: split off PKCS12Attributes from SafeBag so it can
+ be reused
+
+ * Makefile.am: add PKCS12Attributes
+
+2005-05-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * canthandle.asn1: fix tags in example
+
+2005-05-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * pkinit.asn1: Let the Windows nonce be an int32 (signed), if not
+ it will fail when using Windows PK-INIT.
+
+2005-05-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add pkcs12-PBEParams
+
+ * pkcs12.asn1: add pkcs12-PBEParams
+
+ * parse.y: objid_element: exit when the condition fails
+
+2005-04-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_glue.c: 1.8: switch the units variable to a
+ function. gcc-4.1 needs the size of the structure if its defined
+ as extern struct units foo_units[] an we don't want to include
+ <parse_units.h> in the generate headerfile
+
+2005-03-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add the des-ede3-cbc oid that ansi x9.52 uses
+
+ * rfc2459.asn1: add the des-ede3-cbc oid that ansi x9.52 uses
+
+ * Makefile.am: add oids for x509
+
+ * rfc2459.asn1: add oids now when the compiler can handle them
+
+2005-03-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add pkcs9 files
+
+ * pkcs9.asn1: add small number of oids from pkcs9
+
+2005-03-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add a bunch of pkcs1/pkcs2/pkcs3/aes oids
+
+ * rfc2459.asn1: add a bunch of pkcs1/pkcs2/pkcs3/aes oids
+
+2005-03-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * k5.asn1: merge pa-numbers
+
+2005-03-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add oid's
+
+ * rfc2459.asn1: add encryption oids
+
+ * CMS.asn1: add signedAndEnvelopedData oid
+
+ * pkcs12.asn1: add pkcs12 oids
+
+ * CMS.asn1: add pkcs7 oids
+
+2005-03-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen.c (generate_header_of_codefile): break out the header
+ section generation
+ (generate_constant): generate a function that return the oid
+ inside a heim_oid
+
+ * parse.y: fix the ordering of the oid's
+
+ * parse.y: handle OBJECT IDENTIFIER as value construct
+
+2005-02-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Preserve content of CHOICE element that is unknown if ellipsis
+ was used when defining the structure
+
+2005-02-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * parse.y: use ANS1_TAILQ macros
+
+ * *.[ch]: use ASN1_TAILQ macros
+
+ * asn1_queue.h: inline bsd sys/queue.h and rename TAILQ to
+ ASN1_TAILQ to avoid problems with name polluting headerfiles
+
+2005-01-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen.c: pull in <krb5-types.h>
+
+2005-01-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Add BMPString and UniversalString
+
+ * k5.asn1 (EtypeList): make INTEGER constrained (use krb5int32)
+
+2005-01-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rfc2459.asn1: add GeneralNames
+
+2004-11-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen.c: use unsigned integer for len of SequenceOf/SetOf and
+ bitstring names
+
+2004-11-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: switch to krb5int32 and krb5uint32
+
+ * Unify that three integer types TInteger TUInteger and TBigInteger.
+ Start to use constrained integers where appropriate.
+
+2004-10-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * CMS.asn1: remove no longer used commented out elements
+
+ * gen_glue.c: make units structures const
+
+2004-10-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * lex.l: handle hex number with [a-fA-F] in them
+
+2004-10-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_free.c: free _save for CHOICE too
+
+ * rfc2459.asn1: use Name and not heim_any
+
+ * gen_decode.c: if malloc for _save failes, goto fail so we free
+ the structure
+
+ * gen_copy.c: copy _save for CHOICE too
+
+ * gen.c: add _save for CHOICE too
+
+ * CMS.asn1: RecipientIdentifier and SignerIdentifier is the same
+ name is CMSIdentifier and add glue for that so we can share code
+ use Name and not heim_any
+
+2004-10-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: drop AlgorithmIdentifierNonOpt add
+ {RC2CBC,}CBCParameter here where they belong
+
+ * CMS.asn1: add {RC2CBC,}CBCParameter here where they belong
+
+ * rfc2459.asn1: drop AlgorithmIdentifierNonOpt
+
+ * rfc2459.asn1: stop using AlgorithmIdentifierNonOpt hint that we
+ really want to use Name and some MS stuff
+
+2004-09-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * asn1_print.c: handle end of content, this is part BER support,
+ however, OCTET STRING need some tweeking too.
+
+ * der.h: add UT_EndOfContent
+
+ * test.asn1: test asn1 spec file
+
+ * check-gen.c: check larget tags
+
+ * Makefile.am: add test asn1 spec file that we can use for testing
+ constructs that doesn't exists in already existing spec (like
+ large tags)
+
+ * der_put.c (der_put_tag): make sure there are space for the head
+ tag when we are dealing with large tags (>30)
+
+ * check-gen.c: add test for tag length
+
+ * check-common.c: export the map_ functions for OVERRUN/UNDERRUN
+ detection restore the SIGSEGV handler when test is done
+
+ * check-common.h: export the map_ functions for OVERRUN/UNDERRUN
+ detection
+
+ * gen_decode.c: check that the tag-length is not longer the length
+ use forwstr on some more places
+
+ * parse.y: revert part of 1.14.2.21, multiple IMPORT isn't allowed
+
+ * pkinit.asn1: correct usage of IMPORT
+
+ * CMS.asn1: correct usage of IMPORT
+
+ * pkcs8.asn1: pkcs8, encrypting private key
+
+ * pkcs12.asn1: pkcs12, key/crl/certificate file transport PDU
+
+ * Makefile.am: add pkcs8 and pkcs12
+
+ * der_free.c: reset length when freing primitives
+
+ * CMS.asn1: add EncryptedData
+
+2004-08-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_decode.c (decode_type): if the entry is already optional
+ when parsing a tag and we allocate the structure, not pass down
+ optional since that will case the subtype's decode_type also to
+ allocate an entry. and we'll leak an entry. Bug from Luke Howard
+ <lukeh@padl.com>. While here, use calloc.
+
+2004-04-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * k5.asn1: shift the last added etypes one step so rc2 doesn't
+ stomp on cram-md5
+
+2004-04-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * k5.asn1: add ETYPE_AESNNN_CBC_NONE
+
+ * CMS.asn1: add CMS symmetrical parameters moved to k5.asn1
+
+ * k5.asn1: add CMS symmetrical parameters here, more nametypes
+ enctype rc2-cbc
+
+2004-04-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_decode.c: free data on decode failure
+
+2004-04-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add CBCParameter and RC2CBCParameter
+
+ * CMS.asn1: add CBCParameter and RC2CBCParameter
+
+2004-04-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-der.c: add simple test for oid's, used to trigger malloc
+ bugs in you have picky malloc (like valgrind/purify/third)
+
+ * der_get.c (der_get_oid): handle all oid components being smaller
+ then 127 and allocate one extra element since first byte is split
+ to to elements.
+
+2004-04-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * canthandle.asn1: one thing handled
+
+ * gen_decode.c: handle OPTIONAL CONS-tag-less elements
+
+ * der_length.c (length_len): since length is no longer the same as
+ an unsigned, do the length counting here. ("unsigned" is zero
+ padded when most significate bit is set, length is not)
+
+2004-04-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * canthandle.asn1: document by example what the encoder can't
+ handle right now
+
+ * Makefile.am: add more stuff needed whem implementing x509
+ preserve TBSCertificate
+
+ * rfc2459.asn1: add more stuff needed whem implementing x509
+
+ * CMS.asn1: move some type to rfc2459.asn1 where they belong (and
+ import them)
+
+ * gen.c: preserve the raw data when asked too
+
+ * gen_decode.c: preserve the raw data when asked too
+
+ * gen_copy.c: preserve the raw data when asked too
+
+ * gen_free.c: preserve the raw data when asked too
+
+ * gen_locl.h: add preserve_type
+
+ * heim_asn1.h: add heim_any_cmp
+
+ * main.c: add flag --preserve-binary=Symbol1,Symbol2,... that make
+ the compiler generate stubs to save the raw data, its not used
+ right now when generating the stat
+
+ * k5.asn1: Windows uses PADATA 15 for the request too
+
+ * extra.c: add heim_any_cmp
+
+ * der_put.c: implement UTCtime correctly
+
+ * der_locl.h: remove #ifdef HAVE_TIMEGM\ntimegm\n#endif here from
+ der.h so one day der.h can get installed
+
+ * der_length.c: implement UTCtime correctly
+
+ * der_get.c: implement UTCtime correctly, prefix dce_fix with
+ _heim_fix
+
+ * der_copy.c: make copy_bit_string work again
+
+ * der_cmp.c: add octet_string, integer, bit_string cmp functions
+
+ * der.h: hide away more symbols, add more _cmp functions
+
+2004-03-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add more pkix types make k5 use rfc150 bitstrings,
+ everything else use der bitstrings
+
+ * main.c: as a compile time option, handle no rfc1510 bitstrings
+
+ * gen_locl.h: rfc1510 bitstrings flag
+
+ * gen_length.c: as a compile time option, handle no rfc1510
+ bitstrings
+
+ * gen_encode.c: as a compile time option, handle no rfc1510
+ bitstrings
+
+ * gen_decode.c: handle no rfc1510 bitstrings
+
+ * check-gen.c: test for bitstrings
+
+ * rfc2459.asn1: add Certificates and KeyUsage
+
+2004-02-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * pkinit.asn1: use Name from PKIX
+
+ * rfc2459.asn1: add more silly string types to DirectoryString
+
+ * gen_encode.c: add checks for data overflow when encoding
+ TBitString with members encode SET OF correctly by bytewise
+ sorting the members
+
+ * gen_decode.c: add checks for data overrun when encoding
+ TBitString with members
+
+ * der_put.c: add _heim_der_set_sort
+
+ * der_cmp.c: rename oid_cmp to heim_oid_cmp
+
+ * der.h: rename oid_cmp to heim_oid_cmp, add _heim_der_set_sort
+
+ * check-gen.c: add check for Name and (commented out) heim_integer
+
+ * check-der.c: test for "der_length.c: Fix len_unsigned for
+ certain negative integers, it got the length wrong" , from
+ Panasas, Inc.
+
+ * der_length.c: Fix len_unsigned for certain negative integers, it
+ got the length wrong, fix from Panasas, Inc.
+
+ rename len_int and len_unsigned to _heim_\&
+
+ * gen_length.c: 1.14: (length_type): TSequenceOf: add up the size
+ of all the elements, don't use just the size of the last element.
+
+2004-02-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rfc2459.asn1: include defintion of Name
+
+ * pkinit.asn1: no need for ContentType, its cms internal
+
+ * CMS.asn1: move ContentInfo to CMS
+
+ * pkinit.asn1: update to pk-init-18, move ContentInfo to CMS
+
+ * Makefile.am: align with pk-init-18, move contentinfo to cms
+
+2004-02-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * der_get.c: rewrite previous commit
+
+ * der_get.c (der_get_heim_integer): handle positive integer
+ starting with 0
+
+ * der_length.c (der_put_heim_integer): try handle negative
+ integers better (?)
+
+ * der_put.c (der_put_heim_integer): try handle negative integers
+ better
+
+ * der_get.c (der_get_heim_integer): dont abort on negative integer just
+ return ASN1_OVERRUN for now
+
+ * parse.y: add ia5string, and printablestring
+
+ * gen_length.c: add ia5string, and printablestring
+
+ * gen_free.c: add ia5string, and printablestring
+
+ * gen_decode.c: add ia5string, and printablestring
+
+ * gen_copy.c: add ia5string, and printablestring
+
+ * gen.c: add ia5string, printablestring, and utf8string change
+ implemetation of heim_integer and store the data as bigendian byte
+ array with a external flag for signedness
+
+ * der_put.c: add ia5string, printablestring, and utf8string change
+ implemetation of heim_integer and store the data as bigendian byte
+ array with a external flag for signedness
+
+ * der_length.c: add ia5string, printablestring, and utf8string
+ change implemetation of heim_integer and store the data as
+ bigendian byte array with a external flag for signedness
+
+ * der_get.c: add ia5string, printablestring, and utf8string change
+ implemetation of heim_integer and store the data as bigendian byte
+ array with a external flag for signedness
+
+ * der_free.c: add ia5string, printablestring, and utf8string
+
+ * der_copy.c: add ia5string, printablestring, and utf8string
+
+ * der.h: add ia5string, printablestring, and utf8string
+
+ * asn1-common.h: add signedness flag to heim_integer, add
+ ia5string and printablestring
+
+2004-02-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rfc2459.asn1: use BIGINTEGER where appropriate
+
+ * setchgpw2.asn1: spelling and add op-req again
+
+2004-02-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: clean up better
+
+2004-02-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_decode.c (decode_type): TTag, don't overshare the reallen
+ variable
+
+ * Makefile.am: adapt to log file name change
+
+ * gen.c: genereate log file name based on base name
+
+2003-11-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: += asn1_AlgorithmIdentifierNonOpt.x
+
+ * rfc2459.asn1: add AlgorithmIdentifierNonOpt and use it where
+ it's needed, make DomainParameters.validationParms heim_any as a
+ hack. Both are workarounds for the problem with heimdal's asn1
+ compiler have with decoing context tagless OPTIONALs.
+
+ * pkinit.asn1: don't import AlgorithmIdentifier
+
+2003-11-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * der_put.c (der_put_bit_string): make it work somewhat better
+ (should really prune off all trailing zeros)
+
+ * gen_encode.c (encode_type): bit string is not a constructed type
+
+ * der_length.c (length_bit_string): calculate right length for
+ bitstrings
+
+2003-11-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * der_cmp.c (oid_cmp): compare the whole array, not just
+ length/sizeof(component)
+
+ * check-common.c: mmap the scratch areas, mprotect before and
+ after, align data to the edge of the mprotect()ed area to provoke
+ bugs
+
+ * Makefile.am: add DomainParameters, ValidationParms
+
+ * rfc2459.asn1: add DomainParameters, ValidationParms
+
+ * check-der.c: add free function
+
+ * check-common.h: add free function
+
+ * check-common.c: add free function
+
+ * check-gen.c: check KRB-ERROR
+
+ * asn1_print.c: check end of tag_names loop into APPL class tags
+
+2003-11-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * der_put.c (der_put_generalized_time): check size, not *size
+
+2003-11-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_decode.c (decode_type/TBitString): skip over
+ skipped-bits-in-last-octet octet
+
+ * gen_glue.c (generate_units): generate units in reverse order to
+ keep unparse_units happy
+
+2003-11-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: generate all silly pkinit files
+
+ * pkinit.asn1: make it work again, add strange ms structures
+
+ * k5.asn1: PROV-SRV-LOCATION, PacketCable provisioning server
+ location, PKT-SP-SEC-I09-030728
+
+ * asn1-common.h: add bit string
+
+ * der_put.c: add bit string and utctime
+
+ * gen.c: add bit string and utctime
+
+ * gen_copy.c: add bit string and utctime
+
+ * der_copy.c: add bit string
+
+ * gen_decode.c: add utctime and bitstring
+
+ * gen_encode.c: add utctime and bitstring
+
+ * gen_free.c: add utctime and bitstring
+
+ * gen_glue.c: don't generate glue for member-less bit strings
+
+ * der_cmp.c: compare function for oids
+
+ * gen_length.c: add utc time, make bit string work for bits
+ strings w/o any members
+
+ * der_cmp.c: compare function for oids
+
+ * der.h: update boolean prototypes add utctime and bit_string
+
+ * der_free.c: add free_bit_string
+
+ * der_get.c: add bit string and utctime
+
+ * der_length.c: add bit string and utctime, fix memory leak in
+ length_generalized_time
+
+ * CMS.asn1: make EncryptedContentInfo.encryptedContent a OCTET
+ STRING to make the generator do the right thing with IMPLICIT
+ mumble OPTIONAL, make CertificateSet a heim_any_set
+
+ * extra.c, heim_asn1.h: add any_set, instead of just consuming one
+ der object, its consumes the rest of the data avaible
+
+ * extra.c, heim_asn1.h: extern implementation of ANY, decoder
+ needs to have hack removed when generator handles tagless optional
+ data
+
+ * pkinit.asn1: add KdcDHKeyInfo-Win2k
+
+2003-11-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * der_copy.c (copy_oid): copy all components
+
+ * parse.y: parse UTCTime, allow multiple IMPORT
+
+ * symbol.h: add TUTCTime
+
+ * rfc2459.asn1: update
+
+ * x509.asn1: update
+
+ * pkinit.asn1: update
+
+ * CMS.asn1: new file
+
+ * asn1_print.c: print some more lengths, check length before
+ steping out in the void, parse SET, only go down CONTEXT of type
+ CONS (not PRIM)
+
+2003-09-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_encode.c (TChoice, TSequence): code element in reverse
+ order...
+
+2003-09-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen.c: store NULL's as int's for now
+
+ * parse.y: remove dup of type def of UsefulType
+
+2003-09-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_decode.c (decode_type): if malloc failes, return ENOMEM
+
+2003-09-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * parse.y: kw_UTF8String is a token put tag around the OID
+
+ * asn1_print.c (UT_Integer): when the integer is larger then int
+ can handle, just print BIG INT and its size
+
+2003-09-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gen_decode.c (decode_type): TTag, try to generate prettier code
+ in the non optional case, also remember to update length
+
+2003-01-22 Johan Danielsson <joda@pdc.kth.se>
+
+ * gen_decode.c: add flag to decode broken DCE BER encoding
+
+ * gen_locl.h: add flag to decode broken DCE BER encoding
+
+ * main.c: add flag to decode broken DCE BER encoding
+
diff --git a/third_party/heimdal/lib/asn1/MANUAL.md b/third_party/heimdal/lib/asn1/MANUAL.md
new file mode 100644
index 0000000..89c452a
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/MANUAL.md
@@ -0,0 +1,1287 @@
+# Introduction
+
+Heimdal is an implementation of PKIX and Kerberos. As such it must handle the
+use of [Abstract Syntax Notation One (ASN.1)](https://www.itu.int/rec/T-REC-X.680-X.693-202102-I/en)
+by those protocols. ASN.1 is a language for describing the schemata of network
+protocol messages. Associated with ASN.1 are the ASN.1 Encoding Rules (ERs)
+that specify how to encode such messages.
+
+In short:
+
+ - ASN.1 is just a _schema description language_
+
+ - ASN.1 Encoding Rules are specifications for encoding formats for values of
+ types described by ASN.1 schemas ("modules")
+
+Similar languages include:
+
+ - [DCE RPC's Interface Description Language (IDL)](https://pubs.opengroup.org/onlinepubs/9629399/chap4.htm#tagcjh_08)
+ - [Microsoft Interface Description Language (IDL)](https://docs.microsoft.com/en-us/windows/win32/midl/midl-start-page)
+ (MIDL is derived from the DCE RPC IDL)
+ - ONC RPC's eXternal Data Representation (XDR) [RFC4506](https://datatracker.ietf.org/doc/html/rfc4506)
+ - [XML Schema](https://en.wikipedia.org/wiki/XML_schema)
+ - Various JSON schema languages
+ - [Protocol Buffers](https://developers.google.com/protocol-buffers)
+ - and [many, many others](https://en.wikipedia.org/wiki/Comparison_of_data-serialization_formats)!
+ Many are not even listed there.
+
+Similar encoding rules include:
+
+ - DCE RPC's [NDR](https://pubs.opengroup.org/onlinepubs/9629399/chap14.htm)
+ - ONC RPC's [XDR](https://datatracker.ietf.org/doc/html/rfc4506)
+ - XML
+ - FastInfoSet
+ - JSON
+ - CBOR
+ - [Protocol Buffers](https://developers.google.com/protocol-buffers)
+ - [Flat Buffers](https://google.github.io/flatbuffers/)
+ - and [many, many others](https://en.wikipedia.org/wiki/Comparison_of_data-serialization_formats)!
+ Many are not even listed there.
+
+Many such languages are quite old. ASN.1 itself dates to the early 1980s, with
+the first specification published in 1984. XDR was first published in 1987.
+IDL's lineage dates back to sometime during the 1980s, via the Apollo Domain
+operating system.
+
+ASN.1 is standardized by the International Telecommunications Union (ITU-T),
+and has continued evolving over the years, with frequent updates.
+
+The two most useful and transcending features of ASN.1 are:
+
+ - the ability to formally express what some know as "open types", "typed
+ holes", or "references";
+
+ - the ability to add encoding rules over type, which for ASN.1 includes:
+
+ - binary, tag-length-value (TLV) encoding rules
+ - binary, non-TLV encoding rules
+ - textual encoding rules using XML and JSON
+ - an ad-hoc generic text-based ER called GSER
+
+ In principle ASN.1 can add encoding rules that would allow it to
+ interoperate with many others, such as: CBOR, protocol buffers, flat
+ buffers, NDR, and others.
+
+ Readers may recognize that some alternatives to ASN.1 have followed a
+ similar arc. For example, Protocol Buffers was originally a syntax and
+ encoding, and has become a syntax and set of various encodings (e.g., Flat
+ Buffers was added later). And XML has FastInfoSet as a binary encoding
+ alternative to XML's textual encoding.
+
+As well, ASN.1 has [high-quality, freely-available specifications](https://www.itu.int/rec/T-REC-X.680-X.693-202102-I/en).
+
+## ASN.1 Example
+
+For example, this is a `Certificate` as used in TLS and other protocols, taken
+from [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280):
+
+ ```ASN.1
+ Certificate ::= SEQUENCE {
+ tbsCertificate TBSCertificate,
+ signatureAlgorithm AlgorithmIdentifier,
+ signatureValue BIT STRING
+ }
+
+ TBSCertificate ::= SEQUENCE {
+ version [0] EXPLICIT Version DEFAULT v1,
+ serialNumber CertificateSerialNumber,
+ signature AlgorithmIdentifier,
+ issuer Name,
+ validity Validity,
+ subject Name,
+ subjectPublicKeyInfo SubjectPublicKeyInfo,
+ issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
+ subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
+ extensions [3] EXPLICIT Extensions OPTIONAL
+ }
+ ```
+
+and the same `Certificate` taken from a more modern version -from
+[RFC5912](https://datatracker.ietf.org/doc/html/rfc5912)- using newer features
+of ASN.1:
+
+ ```ASN.1
+ Certificate ::= SIGNED{TBSCertificate}
+
+ TBSCertificate ::= SEQUENCE {
+ version [0] Version DEFAULT v1,
+ serialNumber CertificateSerialNumber,
+ signature AlgorithmIdentifier{SIGNATURE-ALGORITHM,
+ {SignatureAlgorithms}},
+ issuer Name,
+ validity Validity,
+ subject Name,
+ subjectPublicKeyInfo SubjectPublicKeyInfo,
+ ... ,
+ [[2:
+ issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
+ subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL
+ ]],
+ [[3:
+ extensions [3] Extensions{{CertExtensions}} OPTIONAL
+ ]], ...
+ }
+ ```
+
+As you can see, a `Certificate` is a structure containing a to-be-signed
+sub-structure, and a signature of that sub-structure, and the sub-structure
+has: a version number, a serial number, a signature algorithm, an issuer name,
+a validity period, a subject name, a public key for the subject name, "unique
+identifiers" for the issuer and subject entities, and "extensions".
+
+To understand more we'd have to look at the types of those fields of
+`TBSCertificate`, but for now we won't do that. The point here is to show that
+ASN.1 allows us to describe "types" of data in a way that resembles
+"structures", "records", or "classes" in various programming languages.
+
+To be sure, there are some "noisy" artifacts in the definition of
+`TBSCertificate` which mostly have to do with the original encoding rules for
+ASN.1. The original encoding rules for ASN.1 were tag-length-value (TLV)
+binary encodings, meaning that for every type, the encoding of a value of that
+type consisted of a _tag_, a _length_ of the value's encoding, and the _actual
+value's encoding_. Over time other encoding rules were added that do not
+require tags, such as the octet encoding rules (OER), but also JSON encoding
+rules (JER), XML encoding rules (XER), and others. There is almost no need for
+tagging directives like `[1] IMPLICIT` when using OER. But in existing
+protocols like PKIX and Kerberos that date back to the days when DER was king,
+tagging directives are unfortunately commonplace.
+
+## ASN.1 Crash Course
+
+This is not a specification. Readers should refer to the ITU-T's X.680 base
+specification for ASN.1's syntax.
+
+A schema is called a "module".
+
+A module looks like:
+
+```ASN.1
+-- This is a comment
+
+-- Here's the name of the module, here given as an "object identifier" or
+-- OID:
+PKIXAlgs-2009 { iso(1) identified-organization(3) dod(6)
+ internet(1) security(5) mechanisms(5) pkix(7) id-mod(0)
+ id-mod-pkix1-algorithms2008-02(56) }
+
+
+-- `DEFINITIONS` is a required keyword
+-- `EXPLICIT TAGS` will be explained later
+DEFINITIONS EXPLICIT TAGS ::=
+BEGIN
+-- list exported types, or `ALL`:
+EXPORTS ALL;
+-- import some types:
+IMPORTS PUBLIC-KEY, SIGNATURE-ALGORITHM, ... FROM AlgorithmInformation-2009
+ mda-sha224, mda-sha256, ... FROM PKIX1-PSS-OAEP-Algorithms-2009;
+
+-- type definitions follow:
+...
+
+END
+```
+
+Type names start with capital upper-case letters. Value names start with
+lower-case letters.
+
+Type definitions are of the form `TypeName ::= TypeDefinition`.
+
+Value (constant) definitions are of the form `valueName ::= TypeName <literal>`.
+
+There are some "universal" primitive types (e.g., string types, numeric types),
+and several "constructed" types (arrays, structures.
+
+Some useful primitive types include `BOOLEAN`, `INTEGER` and `UTF8String`.
+
+Structures are either `SEQUENCE { ... }` or `SET { ... }`. The "fields" of
+these are known as "members".
+
+Arrays are either `SEQUENCE OF SomeType` or `SET OF SomeType`.
+
+A `SEQUENCE`'s elements or members are ordered, while a `SET`'s are not. In
+practice this means that for _canonical_ encoding rules a `SET OF` type's
+values must be sorted, while a `SET { ... }` type's members need not be sorted
+at run-time, but are sorted by _tag_ at compile-time.
+
+Anonymous types are supported, such as `SET OF SET { a A, b B }` (which is a
+set of structures with an `a` field (member) of type `A` and a `b` member of
+type `B`).
+
+The members of structures can be `OPTIONAL` or have a `DEFAULT` value.
+
+There are also discriminated union types known as `CHOICE`s: `U ::= CHOICE { a
+A, b B, c C }` (in this case `U` is either an `A`, a `B`, or a `C`.
+
+Extensibility is supported. "Extensibility" means: the ability to add new
+members to structures, new alternatives to discriminated unions, etc. For
+example, `A ::= SEQUENCE { a0 A0, a1 A1, ... }` means that type `A` is a
+structure that has two fields and which may have more fields added in future
+revisions, therefore decoders _must_ be able to receive and decode encodings of
+extended versions of `A`, even encoders produced prior to the extensions being
+specified! (Normally a decoder "skips" extensions it doesn't know about, and
+the encoding rules need only make it possible to do so.)
+
+## TLV Encoding Rules
+
+The TLV encoding rules for ASN.1 are:
+
+ - Basic Encoding Rules (BER)
+ - Distinguished Encoding Rules (DER), a canonical subset of BER
+ - Canonical Encoding Rules (CER), another canonical subset of BER
+
+"Canonical" encoding rules yield just one way to encode any value of any type,
+while non-canonical rules possibly yield many ways to encode values of certain
+types. For example, JSON is not a canonical data encoding. A canonical form
+of JSON would have to specify what interstitial whitespace is allowed, a
+canonical representation of strings (which Unicode codepoints must be escaped
+and in what way, and which must not), and a canonical representation of decimal
+numbers.
+
+It is important to understand that originally ASN.1 came with TLV encoding
+rules, and some considerations around TLV encoding rules leaked into the
+language. For example, `A ::= SET { a0 [0] A0, a1 [1] A1 }` is a structure
+that has two members `a0` and `a1`, and when encoded those members will be
+tagged with a "context-specific" tags `0` and `1`, respectively.
+
+Tags only have to be specified when needed to disambiguate encodings.
+Ambiguities arise only in `CHOICE` types and sometimes in `SEQUENCE`/`SET`
+types that have `OPTIONAL`/`DEFAULT`ed members.
+
+In modern ASN.1 it is possible to specify that a module uses `AUTOMATIC`
+tagging so that one need never specify tags explicitly in order to fix
+ambiguities.
+
+Also, there are two types of tags: `IMPLICIT` and `EXPLICIT`. Implicit tags
+replace the tags that the tagged type would have otherwise. Explicit tags
+treat the encoding of a type's value (including its tag and length) as the
+value of the tagged type, thus yielding a tag-length-tag-length-value encoding
+-- a TLTLV encoding!
+
+Thus explicit tagging is more redundant and wasteful than implicit tagging.
+But implicit tagging loses metadata that is useful for tools that can decode
+TLV encodings without reference to the schema (module) corresponding to the
+types of values encoded.
+
+TLV encodings were probably never justified except by lack of tooling and
+belief that codecs for TLV ERs can be hand-coded. But TLV RTs exist, and
+because they are widely used, cannot be removed.
+
+## Other Encoding Rules
+
+The Packed Encoding Rules (PER) and Octet Encoding Rules (OER) are rules that
+resemble XDR, but with a 1-byte word size instead of 4-byte word size, and also
+with a 1-byte alignment instead of 4-byte alignment, yielding space-efficient
+encodings.
+
+Hand-coding XDR codecs is quite common and fairly easy. Hand-coding PER and
+OER is widely considered difficult because PER and OER try to be quite
+space-efficient.
+
+Hand-coding TLV codecs used to be considered easy, but really, never was.
+
+But no one should hand-code codecs for any encoding rules.
+
+Instead, one should use a compiler. This is true for ASN.1, and for all schema
+languages.
+
+## Encoding Rule Specific Syntactic Forms
+
+Some encoding rules require specific syntactic forms for some aspects of them.
+
+For example, the JER (JSON Encoding Rules) provide for syntax to select the use
+of JSON arrays vs. JSON objects for encoding structure types.
+
+For example, the TLV encoding rules provide for syntax for specifying
+alternative tags for disambiguation.
+
+## ASN.1 Syntax Specifications
+
+ - The base specification is ITU-T
+ [X.680](https://www.itu.int/rec/T-REC-X.680-202102-I/en).
+
+ - Additional syntax extensions include:
+
+ - [X.681 ASN.1 Information object specification](https://www.itu.int/rec/T-REC-X.681/en)
+ - [X.682 ASN.1 Constraint specification](https://www.itu.int/rec/T-REC-X.682/en)
+ - [X.682 ASN.1 Parameterization of ASN.1 specifications](https://www.itu.int/rec/T-REC-X.683/en)
+
+ Together these three specifications make the formal specification of open
+ types possible.
+
+## ASN.1 Encoding Rules Specifications
+
+ - The TLV Basic, Distinguished, and Canonical Encoding Rules (BER, DER, CER)
+ are described in ITU-T [X.690](https://www.itu.int/rec/T-REC-X.690/en).
+
+ - The more flat-buffers/XDR-like Packed Encoding Rules (PER) are described in
+ ITU-T [X.691](https://www.itu.int/rec/T-REC-X.691/en), and its successor,
+ the Octet Encoding Rules (OER) are described in
+ [X.696](https://www.itu.int/rec/T-REC-X.692/en).
+
+ - The XML Encoding Rules (XER) are described in ITU-T
+ [X.693](https://www.itu.int/rec/T-REC-X.693/en).
+
+ Related is the [X.694 Mapping W3C XML schema definitions into ASN.1](https://www.itu.int/rec/T-REC-X.694/en)
+
+ - The JSON Encoding Rules (JER) are described in ITU-T
+ [X.697](https://www.itu.int/rec/T-REC-X.697/en).
+
+ - The Generic String Encoding Rules are specified by IETF RFCs
+ [RFC3641](https://datatracker.ietf.org/doc/html/rfc3641),
+ [RFC3642](https://datatracker.ietf.org/doc/html/rfc3642),
+ [RFC4792](https://datatracker.ietf.org/doc/html/rfc4792).
+
+Additional ERs can be added.
+
+For example, XDR can clearly encode a very large subset of ASN.1, and with a
+few additional conventions, all of ASN.1.
+
+NDR too can clearly encode a very large subset of ASN.1, and with a few
+additional conventions, all of ASN. However, ASN.1 is not sufficiently rich a
+_syntax_ to express all of what NDR can express (think of NDR conformant and/or
+varying arrays), though with some extensions it could.
+
+## Commentary
+
+The text in this section is the personal opinion of the author(s).
+
+ - ASN.1 gets a bad rap because BER/DER/CER are terrible encoding rules, as are
+ all TLV encoding rules.
+
+ The BER family of encoding rules is a disaster, yes, but ASN.1 itself is
+ not. On the contrary, ASN.1 is quite rich in features and semantics -as
+ rich as any competitor- while also being very easy to write and understand
+ _as a syntax_.
+
+ - ASN.1 also gets a bad rap because its full syntax is not context-free, and
+ so parsing it can be tricky.
+
+ And yet the Heimdal ASN.1 compiler manages, using LALR(1) `yacc`/`bison`/`byacc`
+ parser-generators. For the subset of ASN.1 that this compiler handles,
+ there are no ambiguities. However, we understand that eventually we will
+ need run into ambiguities.
+
+ For example, `ValueSet` and `ObjectSet` are ambiguous. X.680 says:
+
+ ```
+ ValueSet ::= "{" ElementSetSpecs "}"
+ ```
+
+ while X.681 says:
+
+ ```
+ ObjectSet ::= "{" ObjectSetSpec "}"
+ ```
+
+ and the set members can be just the symbolic names of members, in which case
+ there's no grammatical difference between those two productions. These then
+ cause a conflict in the `FieldSetting` production, which is used in the
+ `ObjectDefn` production, which is used in defining an object (which is to be
+ referenced from some `ObjectSet` or `FieldSetting`).
+
+ This particular conflict can be resolved by one of:
+
+ - limiting the power of object sets by disallowing recursion (object sets
+ containing objects that have field settings that are object sets ...),
+
+ - or by introducing additional required and disambiguating syntactic
+ elements that preclude full compliance with ASN.1,
+
+ - or by simply using the same production and type internally to handle
+ both, the `ValueSet` and `ObjectSet` productions and then internally
+ resolving the actual type as late as possible by either inspecting the
+ types of the set members or by inspecting the expected kind of field that
+ the `ValueSet`-or-`ObjectSet` is setting.
+
+ Clearly, only the last of these is satisfying, but it is more work for the
+ compiler developer.
+
+ - TLV encodings are bad because they yield unnecessary redundance in
+ encodings. This is space-inefficient, but also a source of bugs in
+ hand-coded codecs for TLV encodings.
+
+ EXPLICIT tagging makes this worse by making the encoding a TLTLV encoding
+ (tag length tag length value). (The inner TLV is the V for the outer TL.)
+
+ - TLV encodings are often described as "self-describing" because one can
+ usually write a `dumpasn1` style of tool that attempts to decode a TLV
+ encoding of a value without reference to the value's type definition.
+
+ The use of `IMPLICIT` tagging with BER/DER/CER makes schema-less `dumpasn1`
+ style tools harder to use, as some type information is lost. E.g., a
+ primitive type implicitly tagged with a context tag results in a TLV
+ encoding where -without reference to the schema- the tag denotes no
+ information about the type of the value encoded. The user is left to figure
+ out what kind of data that is and to then decode it by hand. For
+ constructed types (arrays and structures), implicit tagging does not really
+ lose any metadata about the type that wasn't already lost by BER/DER/CER, so
+ there is no great loss there.
+
+ However, Heimdal's ASN.1 compiler includes an `asn1_print(1)` utility that
+ can print DER-encoded values in much more detail than a schema-less
+ `dumpasn1` style of tool can. This is because `asn1_print(1)` includes
+ a number of compiled ASN.1 modules, and it can be extended to include more.
+
+ - There is some merit to BER, however. Specifically, an appropriate use of
+ indeterminate length encoding with BER can yield on-line encoding. Think of
+ encoding streams of indeterminate size -- this cannot be done with DER or
+ Flat Buffers, or most encodings, though it can be done with some encodings,
+ such as BER and NDR (NDR has "pipes" for this).
+
+ Some clues are needed in order to produce an codec that can handle such
+ on-line behavior. In IDL/NDR that clue comes from the "pipe" type. In
+ ASN.1 there is no such clue and it would have to be provided separately to
+ the ASN.1 compiler (e.g., as a command-line option).
+
+ - Protocol Buffers is a TLV encoding. There was no need to make it a TLV
+ encoding.
+
+ Public opinion seems to prefer Flat Buffers now, which is not a TLV encoding
+ and which is more comparable to XDR/NDR/PER/OER.
+
+# Heimdal ASN.1 Compiler
+
+The Heimdal ASN.1 compiler and library implement a very large subset of the
+ASN.1 syntax, meanign large parts of X.680, X.681, X.682, and X.683.
+
+The compiler currently emits:
+
+ - a JSON representation of ASN.1 modules
+ - C types corresponding to ASN.1 modules' types
+ - C functions for DER (and some BER) codecs for ASN.1 modules' types
+
+We vaguely hope to eventually move to using the JSON representation of ASN.1
+modules to do code generation in a programming language like `jq` rather than
+in C. The idea there is to make it much easier to target other programming
+languages than C, especially Rust, so that we can start moving Heimdal to Rust
+(first after this would be `lib/hx509`, then `lib/krb5`, then `lib/hdb`, then
+`lib/gssapi`, then `kdc/`).
+
+The compiler has two "backends":
+
+ - C code generation
+ - "template" (byte-code) generation and interpretation
+
+## Features and Limitations
+
+Supported encoding rules:
+
+ - DER
+ - BER decoding (but not encoding)
+
+As well, the Heimdal ASN.1 compiler can render values as JSON using an ad-hoc
+metaschema that is not quite JER-compliant. A sample rendering of a complex
+PKIX `Certificate` with all typed holes automatically decoded is shown in
+[README.md#features](README.md#features).
+
+The Heimdal ASN.1 compiler supports open types via X.681/X.682/X.683 syntax.
+Specifically: (when using the template backend) the generated codecs can
+automatically and recursively decode and encode through "typed holes".
+
+An "open type", also known as "typed holes" or "references", is a part of a
+structure that can contain the encoding of a value of some arbitrary data type,
+with a hint of that value's type expressed in some way such as: via an "object
+identifier", or an integer, or even a string (e.g., like a URN).
+
+Open types are widely used as a form of extensibility.
+
+Historically, open types were never documented formally, but with natural
+language (e.g., English) meant only for humans to understand. Documenting open
+types with formal syntax allows compilers to support them specially.
+
+See the the [`asn1_compile(1)` manual page](#Manual-Page-for-asn1_compile)
+below and [README.md#features](README.md#features), for more details on
+limitations. Excerpt from the manual page:
+
+```
+The Information Object System support includes automatic codec support
+for encoding and decoding through “open types” which are also known as
+“typed holes”. See RFC5912 for examples of how to use the ASN.1 Infor-
+mation Object System via X.681/X.682/X.683 annotations. See the com-
+piler's README files for more information on ASN.1 Information Object
+System support.
+
+Extensions specific to Heimdal are generally not syntactic in nature but
+rather command-line options to this program. For example, one can use
+command-line options to:
+ • enable decoding of BER-encoded values;
+ • enable RFC1510-style handling of ‘BIT STRING’ types;
+ • enable saving of as-received encodings of specific types
+ for the purpose of signature validation;
+ • generate add/remove utility functions for array types;
+ • decorate generated ‘struct’ types with fields that are nei-
+ ther encoded nor decoded;
+etc.
+
+ASN.1 x.680 features supported:
+ • most primitive types (except BMPString and REAL);
+ • all constructed types, including SET and SET OF;
+ • explicit and implicit tagging.
+
+Size and range constraints on the ‘INTEGER’ type cause the compiler to
+generate appropriate C types such as ‘int’, ‘unsigned int’, ‘int64_t’,
+‘uint64_t’. Unconstrained ‘INTEGER’ is treated as ‘heim_integer’, which
+represents an integer of arbitrary size.
+
+Caveats and ASN.1 x.680 features not supported:
+ • JSON encoding support is not quite X.697 (JER) compatible.
+ Its JSON schema is subject to change without notice.
+ • Control over C types generated is very limited, mainly only
+ for integer types.
+ • When using the template backend, `SET { .. }` types are
+ currently not sorted by tag as they should be, but if the
+ module author sorts them by hand then correct DER will be
+ produced.
+ • ‘AUTOMATIC TAGS’ is not supported.
+ • The REAL type is not supported.
+ • The EmbeddedPDV type is not supported.
+ • The BMPString type is not supported.
+ • The IA5String is not properly supported, as it's essen‐
+ tially treated as a UTF8String with a different tag.
+ • All supported non-octet strings are treated as like the
+ UTF8String type.
+ • Only types can be imported into ASN.1 modules at this time.
+ • Only simple value syntax is supported. Constructed value
+ syntax (i.e., values of SET, SEQUENCE, SET OF, and SEQUENCE
+ OF types), is not supported. Values of `CHOICE` types are
+ also not supported.
+```
+
+## Easy-to-Use C Types
+
+The Heimdal ASN.1 compiler generates easy-to-use C types for ASN.1 types.
+
+Unconstrained `INTEGER` becomes `heim_integer` -- a large integer type.
+
+Constrained `INTEGER` types become `int`, `unsigned int`, `int64_t`, or
+`uint64_t`.
+
+String types generally become `char *` (C strings, i.e., NUL-terminated) or
+`heim_octet_string` (a counted byte string type).
+
+`SET` and `SEQUENCE` types become `struct` types.
+
+`SET OF SomeType` and `SEQUENCE OF SomeType` types become `struct` types with a
+`size_t len` field counting the number of elements of the array, and a pointer
+to `len` consecutive elements of the `SomeType` type.
+
+`CHOICE` types become a `struct` type with an `enum` discriminant and a
+`union`.
+
+Type names have hyphens turned to underscores.
+
+Every ASN.1 gets a `typedef`.
+
+`OPTIONAL` members of `SET`s and `SEQUENCE`s become pointer types (`NULL`
+values mean "absent", while non-`NULL` values mean "present").
+
+Tags are of no consequence to the C types generated.
+
+Types definitions to be topographically sorted because of the need to have
+forward declarations.
+
+Forward `typedef` declarations are emmitted.
+
+Circular type dependencies are allowed provided that `OPTIONAL` members are
+used for enough circular references so as to avoid creating types whose values
+have infinite size! (Circular type dependencies can be used to build linked
+lists, though that is a bit of a silly trick when one can use arrays instead,
+though in principle this could be used to do on-line encoding and decoding of
+arbitrarily large streams of objects. See the [commentary](#Commentary)
+section.)
+
+Thus `Certificate` becomes:
+
+```C
+typedef struct TBSCertificate {
+ heim_octet_string _save; /* see below! */
+ Version *version;
+ CertificateSerialNumber serialNumber;
+ AlgorithmIdentifier signature;
+ Name issuer;
+ Validity validity;
+ Name subject;
+ SubjectPublicKeyInfo subjectPublicKeyInfo;
+ heim_bit_string *issuerUniqueID;
+ heim_bit_string *subjectUniqueID;
+ Extensions *extensions;
+} TBSCertificate;
+
+typedef struct Certificate {
+ TBSCertificate tbsCertificate;
+ AlgorithmIdentifier signatureAlgorithm;
+ heim_bit_string signatureValue;
+} Certificate;
+```
+
+The `_save` field in `TBSCertificate` is generated when the compiler is invoked
+with `--preserve-binary=TBSCertificate`, and the decoder will place the
+original encoding of the value of a `TBSCertificate` in the decoded
+`TBSCertificate`'s `_save` field. This is very useful for signature
+validation: the application need not attempt to re-encode a `TBSCertificate` in
+order to validate its signature from the containing `Certificate`!
+
+Let's compare to the `Certificate` as defined in ASN.1:
+
+```ASN.1
+ Certificate ::= SEQUENCE {
+ tbsCertificate TBSCertificate,
+ signatureAlgorithm AlgorithmIdentifier,
+ signatureValue BIT STRING
+ }
+
+ TBSCertificate ::= SEQUENCE {
+ version [0] EXPLICIT Version DEFAULT v1,
+ serialNumber CertificateSerialNumber,
+ signature AlgorithmIdentifier,
+ issuer Name,
+ validity Validity,
+ subject Name,
+ subjectPublicKeyInfo SubjectPublicKeyInfo,
+ issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
+ subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
+ extensions [3] EXPLICIT Extensions OPTIONAL
+ }
+```
+
+The conversion from ASN.1 to C is quite mechanical and natural. That's what
+code-generators do, of course, so it's not surprising. But you can see that
+`Certificate` in ASN.1 and C differs only in:
+
+ - in C `SEQUENCE { }` becomes `struct { }`
+ - in C the type name comes first
+ - in C we drop the tagging directives (e.g., `[0] EXPLICIT`)
+ - `DEFAULT` and `OPTIONAL` become pointers
+ - in C we use `typedef`s to make the type names usable without having to add
+ `struct`
+
+## Circular Type Dependencies
+
+As noted above, circular type dependencies are supported.
+
+Here's a toy example from [XDR](https://datatracker.ietf.org/doc/html/rfc4506)
+-- a linked list:
+
+```XDR
+struct stringentry {
+ string item<>;
+ stringentry *next;
+};
+
+typedef stringentry *stringlist;
+```
+
+Here is the same example in ASN.1:
+
+```ASN.1
+Stringentry ::= SEQUENCE {
+ item UTF8String,
+ next Stringentry OPTIONAL
+}
+```
+
+which compiles to:
+
+```C
+typedef struct Stringentry Stringentry;
+struct Stringentry {
+ char *item;
+ Stringentry *next;
+};
+```
+
+This illustrates that `OPTIONAL` members in ASN.1 are like pointers in XDR.
+
+Making the `next` member not `OPTIONAL` would cause `Stringentry` to be
+infinitely large, and there is no way to declare the equivalent in C anyways
+(`struct foo { int a; struct foo b; };` will not compile in C).
+
+Mutual circular references are allowed too. In the following example `A`
+refers to `B` and `B` refers to `A`, but as long as one (or both) of those
+references is `OPTIONAL`, then it will be allowed:
+
+```ASN1
+A ::= SEQUENCE { name UTF8String, b B }
+B ::= SEQUENCE { name UTF8String, a A OPTIONAL }
+```
+
+```ASN1
+A ::= SEQUENCE { name UTF8String, b B OPTIONAL }
+B ::= SEQUENCE { name UTF8String, a A }
+```
+
+```ASN1
+A ::= SEQUENCE { name UTF8String, b B OPTIONAL }
+B ::= SEQUENCE { name UTF8String, a A OPTIONAL }
+```
+
+In the above example values of types `A` and `B` together form a linked list.
+
+Whereas this is broken and will not compile:
+
+```ASN1
+A ::= SEQUENCE { name UTF8String, b B }
+B ::= SEQUENCE { name UTF8String, a A } -- infinite size!
+```
+
+## Generated APIs For Any Given Type T
+
+The C functions generated for ASN.1 types are all of the same form, for any
+type `T`:
+
+```C
+int decode_T(const unsigned char *, size_t, TBSCertificate *, size_t *);
+int encode_T(unsigned char *, size_t, const TBSCertificate *, size_t *);
+size_t length_T(const TBSCertificate *);
+int copy_T(const TBSCertificate *, TBSCertificate *);
+void free_T(TBSCertificate *);
+char * print_T(const TBSCertificate *, int);
+```
+
+The `decode_T()` functions take a pointer to the encoded data, its length in
+bytes, a pointer to a C object of type `T` to decode into, and a pointer into
+which the number of bytes consumed will be written.
+
+The `length_T()` functions take a pointer to a C object of type `T` and return
+the number of bytes its encoding would need.
+
+The `encode_T()` functions take a pointer to enough bytes to encode the value,
+the number of bytes found there, a pointer to a C object of type `T` whose
+value to encode, and a pointer into which the number of bytes output will be
+written.
+
+> NOTE WELL: The first argument to `encode_T()` functions must point to the
+> last byte in the buffer into which the encoder will encode the value. This
+> is because the encoder encodes from the end towards the beginning.
+
+The `print_T()` functions encode the value of a C object of type `T` in JSON
+(though not in JER-compliant JSON). A sample printing of a complex PKIX
+`Certificate` can be seen in [README.md#features](README.md#features).
+
+The `copy_T()` functions take a pointer to a source C object of type `T` whose
+value they then copy to the destination C object of the same type. The copy
+constructor is equivalent to encoding the source value and decoding it onto the
+destination.
+
+The `free_T()` functions take a pointer to a C object of type `T` whose value's
+memory resources will be released. Note that the C object _itself_ is not
+freed, only its _content_.
+
+See [sample usage](#Using-the-Generated-APIs).
+
+These functions are all recursive.
+
+> NOTE WELL: These functions use the standard C memory allocator.
+> When using the Windows statically-linked C run-time, you must link with
+> `LIBASN1.LIB` to avoid possibly freeing memory allocated by a different
+> allocator.
+
+## Error Handling
+
+All codec functions that return errors return them as `int`.
+
+Error values are:
+
+ - system error codes (use `strerror()` to display them)
+
+or
+
+ - `ASN1_BAD_TIMEFORMAT`
+ - `ASN1_MISSING_FIELD`
+ - `ASN1_MISPLACED_FIELD`
+ - `ASN1_TYPE_MISMATCH`
+ - `ASN1_OVERFLOW`
+ - `ASN1_OVERRUN`
+ - `ASN1_BAD_ID`
+ - `ASN1_BAD_LENGTH`
+ - `ASN1_BAD_FORMAT`
+ - `ASN1_PARSE_ERROR`
+ - `ASN1_EXTRA_DATA`
+ - `ASN1_BAD_CHARACTER`
+ - `ASN1_MIN_CONSTRAINT`
+ - `ASN1_MAX_CONSTRAINT`
+ - `ASN1_EXACT_CONSTRAINT`
+ - `ASN1_INDEF_OVERRUN`
+ - `ASN1_INDEF_UNDERRUN`
+ - `ASN1_GOT_BER`
+ - `ASN1_INDEF_EXTRA_DATA`
+
+You can use the `com_err` library to display these errors as strings:
+
+```C
+ struct et_list *etl = NULL;
+ initialize_asn1_error_table_r(&etl);
+ int ret;
+
+ ...
+
+ ret = decode_T(...);
+ if (ret) {
+ const char *error_message;
+
+ if ((error_message = com_right(etl, ret)) == NULL)
+ error_message = strerror(ret);
+
+ fprintf(stderr, "Failed to decode T: %s\n",
+ error_message ? error_message : "<unknown error>");
+ }
+```
+
+## Using the Generated APIs
+
+Value construction is as usual in C. Use the standard C allocator for
+allocating values of `OPTIONAL` fields.
+
+Value destruction is done with the `free_T()` destructors.
+
+Decoding is just:
+
+```C
+ Certificate c;
+ size_t sz;
+ int ret;
+
+ ret = decode_Certificate(pointer_to_encoded_bytes,
+ number_of_encoded_bytes,
+ &c, &sz);
+ if (ret == 0) {
+ if (sz != number_of_encoded_bytes)
+ warnx("Extra bytes after Certificate!");
+ } else {
+ warnx("Failed to decode certificate!");
+ return ret;
+ }
+
+ /* Now do stuff with the Certificate */
+ ...
+
+ /* Now release the memory */
+ free_Certificate(&c);
+```
+
+Encoding involves calling the `length_T()` function to compute the number of
+bytes needed for the encoding, then allocating that many bytes, then calling
+`encode_T()` to encode into that memory. A convenience macro,
+`ASN1_MALLOC_ENCODE()`, does all three operations:
+
+```C
+ Certificate c;
+ size_t num_bytes, sz;
+ char *bytes = NULL;
+ int ret;
+
+ /* Build a `Certificate` in `c` */
+ ...
+
+ /* Encode `c` */
+ ASN1_MALLOC_ENCODE(Certificate, bytes, num_bytes, &c, sz, ret);
+ if (ret)
+ errx(1, "Out of memory encoding a Certificate");
+
+ /* This check isn't really needed -- it never fails */
+ if (num_bytes != sz)
+ errx(1, "ASN.1 encoder internal error");
+
+ /* Send the `num_bytes` in `bytes` */
+ ...
+
+ /* Free the memory allocated by `ASN1_MALLOC_ENCODE()` */
+ free(bytes);
+```
+
+or, the same code w/o the `ASN1_MALLOC_ENCODE()` macro:
+
+```C
+ Certificate c;
+ size_t num_bytes, sz;
+ char *bytes = NULL;
+ int ret;
+
+ /* Build a `Certificate` in `c` */
+ ...
+
+ /* Encode `c` */
+ num_bytes = length_Certificate(&c);
+ bytes = malloc(num_bytes);
+ if (bytes == NULL)
+ errx(1, "Out of memory");
+
+ /*
+ * Note that the memory to encode into, passed to encode_Certificate()
+ * must be a pointer to the _last_ byte of that memory, not the first!
+ */
+ ret = encode_Certificate(bytes + num_bytes - 1, num_bytes,
+ &c, &sz);
+ if (ret)
+ errx(1, "Out of memory encoding a Certificate");
+
+ /* This check isn't really needed -- it never fails */
+ if (num_bytes != sz)
+ errx(1, "ASN.1 encoder internal error");
+
+ /* Send the `num_bytes` in `bytes` */
+ ...
+
+ /* Free the memory allocated by `ASN1_MALLOC_ENCODE()` */
+ free(bytes);
+```
+
+## Open Types
+
+The handling of X.681/X.682/X.683 syntax for open types is described at length
+in [README-X681.md](README-X681.md).
+
+## Command-line Usage
+
+The compiler takes an ASN.1 module file name and outputs a C header and C
+source files, as well as various other metadata files:
+
+ - `<module>_asn1.h`
+
+ This file defines all the exported types from the given ASN.1 module as C
+ types.
+
+ - `<module>_asn1-priv.h`
+
+ This file defines all the non-exported types from the given ASN.1 module as
+ C types.
+
+ - `<module>_asn1_files`
+
+ This file is needed because the default is to place the code for each type
+ in a separate C source file, which can help improve the performance of
+ builds by making it easier to parallelize the building of the ASN.1 module.
+
+ - `asn1_<Type>.c` or `asn1_<module>_asn1.c`
+
+ If `--one-code-file` is used, then the implementation of the module will be
+ in a file named `asn1_<module>_asn1.c`, otherwise the implementation of each
+ type in the module will be in `asn1_<Type>.c`.
+
+ - `<module>_asn1.json`
+
+ This file contains a JSON description of the module (the schema for this
+ file is ad-hoc and subject to change w/o notice).
+
+ - `<module>_asn1_oids.c`
+
+ This file is meant to be `#include`d, and contains just calls to a
+ `DEFINE_OID_WITH_NAME(sym)` macro that the user must define, where `sym` is
+ the suffix of the name of a variable of type `heim_oid`. The full name of
+ the variable is `asn1_oid_ ## sym`.
+
+ - `<module>_asn1_syms.c`
+
+ This file is meant to be `#include`d, and contains just calls to these
+ macros that the user must define:
+
+ - `ASN1_SYM_INTVAL(name, genname, sym, num)`
+ - `ASN1_SYM_OID(name, genname, sym)`
+ - `ASN1_SYM_TYPE(name, genname, sym)`
+
+ where `name` is the C string literal name of the value or type as it appears
+ in the ASN.1 module, `genname` is the C string literal name of the value or
+ type as generated (e.g., with hyphens replaced by underscores), `sym` is the
+ symbol or symbol suffix (see above0, and `num` is the numeric value of the
+ integer value.
+
+Control over the C types used for ASN.1 `INTEGER` types is done by ASN.1 usage
+convention:
+
+ - unconstrained `INTEGER` types, or `INTEGER` types where only the minimum, or
+ only the maximum value is specified generate `heim_integer`
+
+ - constrained `INTEGER` types whose minimum and maximum fit in `unsigned`'s
+ range generate `unsigned`
+
+ - constrained `INTEGER` types whose minimum and maximum fit in `int`'s
+ range generate `int`
+
+ - constrained `INTEGER` types whose minimum and maximum fit in `uin64_t`'s
+ range generate `uin64_t`
+
+ - constrained `INTEGER` types whose minimum and maximum fit in `in64_t`'s
+ range generate `in64_t`
+
+ - `INTEGER` types with named members generate a C `struct` with `unsigned int`
+ bit-field members
+
+ - all other `INTEGER` types generate `heim_integer`
+
+Various code generation options are provided as command-line options or as
+ASN.1 usage conventions:
+
+ - `--type-file=C-HEADER-FILE` -- generate an `#include` directive to include
+ that header for some useful base types (within Heimdal we use `krb5-types.h`
+ as that header)
+
+ - `--template` -- use the "template" (byte-coded) backend
+
+ - `--one-code-file` -- causes all the code generated to be placed in one C
+ source file (mutually exclusive with `--template`)
+
+ - `--support-ber` -- accept non-DER BER when decoding
+
+ - `--preserve-binary=TYPE` -- add a `_save` field to the C struct type for the
+ ASN.1 `TYPE` where the decoder will save the original encoding of the value
+ of `TYPE` it decodes (useful for cryptographic signature verification!)
+
+ - `--sequence=TYPE` -- generate `add_TYPE()` and `remove_TYPE()` utility
+ functions (`TYPE` must be a `SET OF` or `SEQUENCE OF` type)
+
+ - `--decorate=DECORATION` -- add fields to generated C struct types as
+ described in the `DECORATION` (see the
+ [manual page](#Manual-Page-for-asn1_compile) below)
+
+ Decoration fields are never encoded or decoded. They are meant to be used
+ for, e.g., application state keeping.
+
+ - `--no-parse-units` -- normally the compiler generates code to use the
+ Heimdal `libroken` "units" utility for displaying bit fields; this option
+ disables this
+
+See the [manual page for `asn1_compile(1)`](#Manual-Page-for-asn1_compile) for
+a full listing of command-line options.
+
+### Manual Page for `asn1_compile(1)`
+
+```
+ASN1_COMPILE(1) BSD General Commands Manual ASN1_COMPILE(1)
+
+NAME
+ asn1_compile — compile ASN.1 modules
+
+SYNOPSIS
+ asn1_compile [--template] [--prefix-enum] [--enum-prefix=PREFIX]
+ [--encode-rfc1510-bit-string] [--decode-dce-ber]
+ [--support-ber] [--preserve-binary=TYPE] [--sequence=TYPE]
+ [--decorate=DECORATION] [--one-code-file] [--gen-name=NAME]
+ [--option-file=FILE] [--original-order] [--no-parse-units]
+ [--type-file=C-HEADER-FILE] [--version] [--help]
+ [FILE.asn1 [NAME]]
+
+DESCRIPTION
+ asn1_compile compiles an ASN.1 module into C source code and header
+ files.
+
+ A fairly large subset of ASN.1 as specified in X.680, and the ASN.1 In‐
+ formation Object System as specified in X.681, X.682, and X.683 is sup‐
+ ported, with support for the Distinguished Encoding Rules (DER), partial
+ Basic Encoding Rules (BER) support, and experimental JSON support (encod‐
+ ing only at this time).
+
+ See the compiler's README files for details about the C code and inter‐
+ faces it generates.
+
+ The Information Object System support includes automatic codec support
+ for encoding and decoding through “open types” which are also known as
+ “typed holes”. See RFC 5912 for examples of how to use the ASN.1 Infor‐
+ mation Object System via X.681/X.682/X.683 annotations. See the com‐
+ piler's README files for more information on ASN.1 Information Object
+ System support.
+
+ Extensions specific to Heimdal are generally not syntactic in nature but
+ rather command-line options to this program. For example, one can use
+ command-line options to:
+ • enable decoding of BER-encoded values;
+ • enable RFC1510-style handling of ‘BIT STRING’ types;
+ • enable saving of as-received encodings of specific types
+ for the purpose of signature validation;
+ • generate add/remove utility functions for array types;
+ • decorate generated ‘struct’ types with fields that are nei‐
+ ther encoded nor decoded;
+ etc.
+
+ ASN.1 x.680 features supported:
+ • most primitive types (except BMPString and REAL);
+ • all constructed types, including SET and SET OF;
+ • explicit and implicit tagging.
+
+ Size and range constraints on the ‘INTEGER’ type cause the compiler to
+ generate appropriate C types such as ‘int’, ‘unsigned int’, ‘int64_t’,
+ ‘uint64_t’. Unconstrained ‘INTEGER’ is treated as ‘heim_integer’, which
+ represents an integer of arbitrary size.
+
+ Caveats and ASN.1 x.680 features not supported:
+ • JSON encoding support is not quite X.697 (JER) compatible.
+ Its JSON schema is subject to change without notice.
+ • Control over C types generated is very limited, mainly only
+ for integer types.
+ • When using the template backend, `SET { .. }` types are
+ currently not sorted by tag as they should be, but if the
+ module author sorts them by hand then correct DER will be
+ produced.
+ • ‘AUTOMATIC TAGS’ is not supported.
+ • The REAL type is not supported.
+ • The EmbeddedPDV type is not supported.
+ • The BMPString type is not supported.
+ • The IA5String is not properly supported, as it's essen‐
+ tially treated as a UTF8String with a different tag.
+ • All supported non-octet strings are treated as like the
+ UTF8String type.
+ • Only types can be imported into ASN.1 modules at this time.
+ • Only simple value syntax is supported. Constructed value
+ syntax (i.e., values of SET, SEQUENCE, SET OF, and SEQUENCE
+ OF types), is not supported. Values of `CHOICE` types are
+ also not supported.
+
+ Options supported:
+
+ --template
+ Use the “template” backend instead of the “codegen” backend
+ (which is the default backend).
+
+ The template backend generates “templates” which are akin to
+ bytecode, and which are interpreted at run-time.
+
+ The codegen backend generates C code for all functions directly,
+ with no template interpretation.
+
+ The template backend scales better than the codegen backend be‐
+ cause as we add support for more encoding rules and more opera‐
+ tions (we may add value comparators) the templates stay mostly
+ the same, thus scaling linearly with size of module. Whereas the
+ codegen backend scales linear with the product of module size and
+ number of encoding rules supported.
+
+ --prefix-enum
+ This option should be removed because ENUMERATED types should al‐
+ ways have their labels prefixed.
+
+ --enum-prefix=PREFIX
+ This option should be removed because ENUMERATED types should al‐
+ ways have their labels prefixed.
+
+ --encode-rfc1510-bit-string
+ Use RFC1510, non-standard handling of “BIT STRING” types.
+
+ --decode-dce-ber
+
+ --support-ber
+
+ --preserve-binary=TYPE
+ Generate a field named ‘_save’ in the C struct generated for the
+ named TYPE. This field is used to preserve the original encoding
+ of the value of the TYPE.
+
+ This is useful for cryptographic applications so that they can
+ check signatures of encoded values as-received without having to
+ re-encode those values.
+
+ For example, the TBSCertificate type should have values preserved
+ so that Certificate validation can check the signatureValue over
+ the tbsCertificate's value as-received.
+
+ The alternative of encoding a value to check a signature of it is
+ brittle. For types where non-canonical encodings (such as BER)
+ are allowed, this alternative is bound to fail. Thus the point
+ of this option.
+
+ --sequence=TYPE
+ Generate add/remove functions for the named ASN.1 TYPE which must
+ be a ‘SET OF’ or ‘SEQUENCE OF’ type.
+
+ --decorate=ASN1-TYPE:FIELD-ASN1-TYPE:fname[?]
+ Add to the C struct generated for the given ASN.1 SET, SEQUENCE,
+ or CHOICE type named ASN1-TYPE a “hidden” field named fname of
+ the given ASN.1 type FIELD-ASN1-TYPE, but do not encode or decode
+ it. If the fname ends in a question mark, then treat the field
+ as OPTIONAL.
+
+ This is useful for adding fields to existing types that can be
+ used for internal bookkeeping but which do not affect interoper‐
+ ability because they are neither encoded nor decoded. For exam‐
+ ple, one might decorate a request type with state needed during
+ processing of the request.
+
+ --decorate=ASN1-TYPE:void*:fname
+ Add to the C struct generated for the given ASN.1 SET, SEQUENCE,
+ or CHOICE type named ASN1-TYPE a “hidden” field named fname of
+ type ‘void *’ (but do not encode or decode it.
+
+ The destructor and copy constructor functions generated by this
+ compiler for ASN1-TYPE will set this field to the ‘NULL’ pointer.
+
+ --decorate=ASN1-TYPE:FIELD-C-TYPE:fname[?]:[copyfn]:[freefn]:header
+ Add to the C struct generated for the given ASN.1 SET, SEQUENCE,
+ or CHOICE type named ASN1-TYPE a “hidden” field named fname of
+ the given external C type FIELD-C-TYPE, declared in the given
+ header but do not encode or decode this field. If the fname ends
+ in a question mark, then treat the field as OPTIONAL.
+
+ The header must include double quotes or angle brackets. The
+ copyfn must be the name of a copy constructor function that takes
+ a pointer to a source value of the type, and a pointer to a des‐
+ tination value of the type, in that order, and which returns zero
+ on success or else a system error code on failure. The freefn
+ must be the name of a destructor function that takes a pointer to
+ a value of the type and which releases resources referenced by
+ that value, but does not free the value itself (the run-time al‐
+ locates this value as needed from the C heap). The freefn should
+ also reset the value to a pristine state (such as all zeros).
+
+ If the copyfn and freefn are empty strings, then the decoration
+ field will neither be copied nor freed by the functions generated
+ for the TYPE.
+
+ --one-code-file
+ Generate a single source code file. Otherwise a separate code
+ file will be generated for every type.
+
+ --gen-name=NAME
+ Use NAME to form the names of the files generated.
+
+ --option-file=FILE
+ Take additional command-line options from FILE.
+
+ --original-order
+ Attempt to preserve the original order of type definition in the
+ ASN.1 module. By default the compiler generates types in a topo‐
+ logical sort order.
+
+ --no-parse-units
+ Do not generate to-int / from-int functions for enumeration
+ types.
+
+ --type-file=C-HEADER-FILE
+ Generate an include of the named header file that might be needed
+ for common type defintions.
+
+ --version
+
+ --help
+
+NOTES
+ Currently only the template backend supports automatic encoding and de‐
+ coding of open types via the ASN.1 Information Object System and
+ X.681/X.682/X.683 annotations.
+
+HEIMDAL February 22, 2021 HEIMDAL
+```
+
+# Future Directions
+
+The Heimdal ASN.1 compiler is focused on PKIX and Kerberos, and is almost
+feature-complete for dealing with those. It could use additional support for
+X.681/X.682/X.683 elements that would allow the compiler to understand
+`Certificate ::= SIGNED{TBSCertificate}`, particularly the ability to
+automatically validate cryptographic algorithm parameters. However, this is
+not that important.
+
+Another feature that might be nice is the ability of callers to specify smaller
+information object sets when decoding values of types like `Certificate`,
+mainly to avoid spending CPU cycles and memory allocations on decoding types in
+typed holes that are not of interest to the application.
+
+For testing purposes, a JSON reader to go with the JSON printer might be nice,
+and anyways, would make for a generally useful tool.
+
+Another feature that would be nice would to automatically generate SQL and LDAP
+code for HDB based on `lib/hdb/hdb.asn1` (with certain usage conventions and/or
+compiler command-line options to make it possible to map schemas usefully).
+
+For the `hxtool` command, it would be nice if the user could input arbitrary
+certificate extensions and `subjectAlternativeName` (SAN) values in JSON + an
+ASN.1 module and type reference that `hxtool` could then parse and encode using
+the ASN.1 compiler and library. Currently the `hx509` library and its `hxtool`
+command must be taught about every SAN type.
diff --git a/third_party/heimdal/lib/asn1/Makefile.am b/third_party/heimdal/lib/asn1/Makefile.am
new file mode 100644
index 0000000..eb0308e
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/Makefile.am
@@ -0,0 +1,567 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+WFLAGS += $(WFLAGS_ENUM_CONV)
+
+YFLAGS = -o asn1parse.c -t
+
+AM_CPPFLAGS += $(ROKEN_RENAME) -I$(top_builddir)/include -I$(top_srcdir)/lib/base
+
+man_MANS = asn1_print.1 asn1_compile.1
+
+lib_LTLIBRARIES = libasn1.la libasn1template.la
+libasn1_la_LDFLAGS = -version-info 8:0:0
+libasn1template_la_LDFLAGS = -version-info 8:0:0
+
+noinst_LTLIBRARIES = libasn1base.la
+
+if versionscript
+libasn1_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+libasn1template_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+endif
+
+
+libasn1_la_LIBADD = \
+ libasn1base.la \
+ @LIB_com_err@ \
+ $(LIBADD_roken)
+
+libasn1template_la_LIBADD = \
+ libasn1base.la \
+ @LIB_com_err@ \
+ $(LIBADD_roken)
+
+BUILT_SOURCES = \
+ $(gen_files_rfc2459) \
+ $(gen_files_rfc4108) \
+ $(gen_files_cms) \
+ $(gen_files_krb5) \
+ $(gen_files_ocsp) \
+ $(gen_files_pkinit) \
+ $(gen_files_pkcs8) \
+ $(gen_files_pkcs9) \
+ $(gen_files_pkcs10) \
+ $(gen_files_pkcs12) \
+ $(gen_files_digest) \
+ $(gen_files_kx509)
+
+BUILT_TEMPLATE_SOURCES = \
+ $(gen_files_rfc2459_template) \
+ $(gen_files_rfc4108_template) \
+ $(gen_files_cms_template) \
+ $(gen_files_krb5_template) \
+ $(gen_files_ocsp_template) \
+ $(gen_files_pkinit_template) \
+ $(gen_files_pkcs8_template) \
+ $(gen_files_pkcs9_template) \
+ $(gen_files_pkcs10_template) \
+ $(gen_files_pkcs12_template) \
+ $(gen_files_digest_template) \
+ $(gen_files_kx509_template)
+
+gen_files_krb5 = asn1_krb5_asn1.c
+gen_files_krb5_template = asn1_krb5_template_asn1.c
+gen_files_cms = asn1_cms_asn1.c
+gen_files_cms_template = asn1_cms_template_asn1.c
+gen_files_crmf = asn1_crmf_asn1.c
+gen_files_crmf_template = asn1_crmf_template_asn1.c
+gen_files_rfc2459 = asn1_rfc2459_asn1.c
+gen_files_rfc2459_template = asn1_rfc2459_template_asn1.c
+gen_files_rfc4108 = asn1_rfc4108_asn1.c
+gen_files_rfc4108_template = asn1_rfc4108_template_asn1.c
+gen_files_ocsp = asn1_ocsp_asn1.c
+gen_files_ocsp_template = asn1_ocsp_template_asn1.c
+gen_files_pkinit = asn1_pkinit_asn1.c
+gen_files_pkinit_template = asn1_pkinit_template_asn1.c
+gen_files_pkcs10 = asn1_pkcs10_asn1.c
+gen_files_pkcs10_template = asn1_pkcs10_template_asn1.c
+gen_files_pkcs12 = asn1_pkcs12_asn1.c
+gen_files_pkcs12_template = asn1_pkcs12_template_asn1.c
+gen_files_pkcs8 = asn1_pkcs8_asn1.c
+gen_files_pkcs8_template = asn1_pkcs8_template_asn1.c
+gen_files_pkcs9 = asn1_pkcs9_asn1.c
+gen_files_pkcs9_template = asn1_pkcs9_template_asn1.c
+gen_files_test = asn1_test_asn1.c
+gen_files_test_template = asn1_test_template_asn1.c
+gen_files_digest = asn1_digest_asn1.c
+gen_files_digest_template = asn1_digest_template_asn1.c
+gen_files_kx509 = asn1_kx509_asn1.c
+gen_files_kx509_template = asn1_kx509_template_asn1.c
+gen_files_x690sample = asn1_x690sample_asn1.c
+gen_files_x690sample_template = asn1_x690sample_template_asn1.c
+
+oid_resolution.lo: $(BUILT_SOURCES)
+
+noinst_PROGRAMS = asn1_gen
+
+bin_PROGRAMS = asn1_compile asn1_print
+
+TESTS = check-der check-gen check-gen-template check-timegm check-ber check-template
+check_PROGRAMS = $(TESTS)
+
+asn1_gen_SOURCES = asn1_gen.c
+asn1_print_SOURCES = asn1_print.c
+asn1_print_SOURCES += $(gen_files_x690sample_template)
+asn1_print_CPPFLAGS = -DASN1_PRINT_SUPPORTED
+check_der_SOURCES = check-der.c check-common.c check-common.h
+
+check_template_SOURCES = check-template.c check-common.c check-common.h
+nodist_check_template_SOURCES = $(gen_files_test_template)
+
+check_gen_template_CPPFLAGS = -DASN1_IOS_SUPPORTED
+dist_check_gen_template_SOURCES = check-gen.c check-common.c check-common.h
+nodist_check_gen_template_SOURCES = $(gen_files_test_template) \
+ $(gen_files_x690sample_template)
+
+dist_check_gen_SOURCES = check-gen.c check-common.c check-common.h
+nodist_check_gen_SOURCES = $(gen_files_test) $(gen_files_x690sample)
+
+build_HEADERZ = asn1-template.h
+
+asn1_compile_SOURCES = \
+ asn1parse.y \
+ der.h \
+ gen.c \
+ gen_copy.c \
+ gen_decode.c \
+ gen_encode.c \
+ gen_print.c \
+ gen_free.c \
+ gen_glue.c \
+ gen_length.c \
+ gen_locl.h \
+ gen_seq.c \
+ gen_template.c \
+ hash.c \
+ hash.h \
+ lex.l \
+ lex.h \
+ main.c \
+ asn1-template.h \
+ symbol.c \
+ symbol.h
+
+dist_libasn1base_la_SOURCES = \
+ der_locl.h \
+ der.c \
+ der.h \
+ der_get.c \
+ der_put.c \
+ der_free.c \
+ der_print.c \
+ der_length.c \
+ der_copy.c \
+ der_cmp.c \
+ der_format.c \
+ fuzzer.c \
+ heim_asn1.h \
+ extra.c \
+ roken_rename.h \
+ template.c \
+ timegm.c
+
+dist_libasn1_la_SOURCES = oid_resolution.c
+dist_libasn1template_la_SOURCES = oid_resolution.c
+
+nodist_libasn1base_la_SOURCES = \
+ asn1_err.h \
+ asn1_err.c
+
+nodist_libasn1_la_SOURCES = $(BUILT_SOURCES)
+
+if !ASN1_TEMPLATING
+nodist_libasn1template_la_SOURCES = $(BUILT_TEMPLATE_SOURCES)
+else
+nodist_libasn1template_la_SOURCES = $(BUILT_SOURCES)
+endif
+
+asn1_compile_LDADD = \
+ $(LIB_roken) $(LEXLIB)
+
+check_der_LDADD = \
+ libasn1.la \
+ $(LIB_roken)
+
+check_template_LDADD = $(check_der_LDADD)
+asn1_print_LDADD = libasn1template.la $(LIB_roken) $(LIB_com_err)
+asn1_gen_LDADD = $(check_der_LDADD)
+check_timegm_LDADD = $(check_der_LDADD)
+
+check_gen_template_LDADD = \
+ libasn1template.la \
+ $(LIB_roken)
+
+check_gen_LDADD = \
+ libasn1template.la \
+ $(LIB_roken)
+
+check_ber_LDADD = $(check_gen_LDADD)
+
+CLEANFILES = \
+ $(BUILT_SOURCES) \
+ $(gen_files_rfc2459) \
+ $(gen_files_rfc2459_template) \
+ $(gen_files_rfc4108) \
+ $(gen_files_rfc4108_template) \
+ $(gen_files_cms) \
+ $(gen_files_cms_template) \
+ $(gen_files_krb5) \
+ $(gen_files_krb5_template) \
+ $(gen_files_ocsp) \
+ $(gen_files_ocsp_template) \
+ $(gen_files_pkinit) \
+ $(gen_files_pkinit_template) \
+ $(gen_files_pkcs8) \
+ $(gen_files_pkcs8_template) \
+ $(gen_files_pkcs9) \
+ $(gen_files_pkcs9_template) \
+ $(gen_files_pkcs10) \
+ $(gen_files_pkcs10_template) \
+ $(gen_files_pkcs12) \
+ $(gen_files_pkcs12_template) \
+ $(gen_files_digest) \
+ $(gen_files_digest_template) \
+ $(gen_files_kx509) \
+ $(gen_files_kx509_template) \
+ $(gen_files_x690sample) \
+ $(gen_files_x690sample_template) \
+ $(gen_files_test) \
+ $(gen_files_test_template) \
+ $(nodist_check_gen_SOURCES) \
+ asn1parse.c asn1parse.h lex.c \
+ asn1_err.c asn1_err.h \
+ rfc2459_asn1_files rfc2459_asn1*.h \
+ rfc2459_template_asn1_files rfc2459_template_asn1*.h \
+ rfc4108_asn1_files rfc4108_asn1*.h \
+ rfc4108_template_asn1_files rfc4108_template_asn1*.h \
+ cms_asn1_files cms_asn1*.h \
+ cms_template_asn1_files cms_template_asn1* \
+ crmf_asn1_files crmf_asn1* \
+ crmf_template_asn1_files crmf_template_asn1* \
+ krb5_asn1_files krb5_asn1* \
+ krb5_template_asn1_files krb5_template_asn1* \
+ ocsp_asn1_files ocsp_asn1* \
+ ocsp_template_asn1_files ocsp_template_asn1* \
+ pkinit_asn1_files pkinit_asn1* \
+ pkinit_template_asn1_files pkinit_template_asn1* \
+ pkcs8_asn1_files pkcs8_asn1* \
+ pkcs8_template_asn1_files pkcs8_template_asn1* \
+ pkcs9_asn1_files pkcs9_asn1* \
+ pkcs9_template_asn1_files pkcs9_template_asn1* \
+ pkcs10_asn1_files pkcs10_asn1* \
+ pkcs10_template_asn1_files pkcs10_template_asn1* \
+ pkcs12_asn1_files pkcs12_asn1* \
+ pkcs12_template_asn1_files pkcs12_template_asn1* \
+ digest_asn1_files digest_asn1* \
+ digest_template_asn1_files digest_template_asn1* \
+ kx509_asn1_files kx509_asn1* \
+ kx509_template_asn1_files kx509_template_asn1* \
+ x690sample_asn1_files x690sample_asn1* \
+ x690sample_template_asn1_files x690sample_template_asn1* \
+ test_asn1_files test_asn1* \
+ test_template_asn1_files test_template_asn1* \
+ asn1_*_asn1.c *_asn1.json *_asn1_syms.c *_asn1_oids.c
+
+dist_include_HEADERS = der.h heim_asn1.h
+dist_include_HEADERS += $(srcdir)/der-protos.h $(srcdir)/der-private.h
+dist_include_HEADERS += asn1-common.h
+
+nodist_include_HEADERS = asn1_err.h
+nodist_include_HEADERS += krb5_asn1.h
+nodist_include_HEADERS += krb5_template_asn1.h
+nodist_include_HEADERS += pkinit_asn1.h
+nodist_include_HEADERS += pkinit_template_asn1.h
+nodist_include_HEADERS += cms_asn1.h
+nodist_include_HEADERS += cms_template_asn1.h
+nodist_include_HEADERS += crmf_asn1.h
+nodist_include_HEADERS += crmf_template_asn1.h
+nodist_include_HEADERS += rfc2459_asn1.h
+nodist_include_HEADERS += rfc2459_template_asn1.h
+nodist_include_HEADERS += rfc4108_asn1.h
+nodist_include_HEADERS += rfc4108_template_asn1.h
+nodist_include_HEADERS += ocsp_asn1.h
+nodist_include_HEADERS += ocsp_template_asn1.h
+nodist_include_HEADERS += pkcs8_asn1.h
+nodist_include_HEADERS += pkcs8_template_asn1.h
+nodist_include_HEADERS += pkcs9_asn1.h
+nodist_include_HEADERS += pkcs9_template_asn1.h
+nodist_include_HEADERS += pkcs10_asn1.h
+nodist_include_HEADERS += pkcs10_template_asn1.h
+nodist_include_HEADERS += pkcs12_asn1.h
+nodist_include_HEADERS += pkcs12_template_asn1.h
+nodist_include_HEADERS += digest_asn1.h
+nodist_include_HEADERS += digest_template_asn1.h
+nodist_include_HEADERS += kx509_asn1.h
+nodist_include_HEADERS += kx509_template_asn1.h
+nodist_include_HEADERS += x690sample_asn1.h
+nodist_include_HEADERS += x690sample_template_asn1.h
+
+priv_headers = krb5_asn1-priv.h
+priv_headers += krb5_template_asn1-priv.h
+priv_headers += pkinit_asn1-priv.h
+priv_headers += pkinit_template_asn1-priv.h
+priv_headers += cms_asn1-priv.h
+priv_headers += cms_template_asn1-priv.h
+priv_headers += crmf_asn1-priv.h
+priv_headers += crmf_template_asn1-priv.h
+priv_headers += rfc2459_asn1-priv.h
+priv_headers += rfc2459_template_asn1-priv.h
+priv_headers += rfc4108_asn1-priv.h
+priv_headers += rfc4108_template_asn1-priv.h
+priv_headers += ocsp_asn1-priv.h
+priv_headers += ocsp_template_asn1-priv.h
+priv_headers += pkcs8_asn1-priv.h
+priv_headers += pkcs8_template_asn1-priv.h
+priv_headers += pkcs9_asn1-priv.h
+priv_headers += pkcs9_template_asn1-priv.h
+priv_headers += pkcs10_asn1-priv.h
+priv_headers += pkcs10_template_asn1-priv.h
+priv_headers += pkcs12_asn1-priv.h
+priv_headers += pkcs12_template_asn1-priv.h
+priv_headers += digest_asn1-priv.h
+priv_headers += digest_template_asn1-priv.h
+priv_headers += kx509_asn1-priv.h
+priv_headers += kx509_template_asn1-priv.h
+priv_headers += x690sample_asn1-priv.h
+priv_headers += x690sample_template_asn1-priv.h
+priv_headers += test_asn1.h test_asn1-priv.h
+priv_headers += test_template_asn1.h test_template_asn1-priv.h
+
+
+
+$(asn1_compile_OBJECTS): asn1parse.h asn1parse.c $(srcdir)/der-protos.h $(srcdir)/der-private.h
+$(libasn1_la_OBJECTS): $(nodist_include_HEADERS) $(priv_headers) asn1_err.h $(srcdir)/der-protos.h $(srcdir)/der-private.h
+$(libasn1template_la_OBJECTS): $(nodist_include_HEADERS) $(priv_headers) asn1_err.h $(srcdir)/der-protos.h $(srcdir)/der-private.h
+$(libasn1base_la_OBJECTS): asn1_err.h $(srcdir)/der-protos.h $(srcdir)/der-private.h
+$(check_gen_OBJECTS): test_asn1.h
+$(check_template_OBJECTS): test_asn1_files
+$(asn1_print_OBJECTS): $(nodist_include_HEADERS) $(priv_headers)
+
+asn1parse.h: asn1parse.c
+
+$(gen_files_krb5) krb5_asn1.h krb5_asn1-priv.h: krb5_asn1_files
+$(gen_files_krb5_template) krb5_template_asn1.h krb5_template_asn1-priv.h: krb5_template_asn1_files
+$(gen_files_ocsp) ocsp_asn1.h ocsp_asn1-priv.h: ocsp_asn1_files
+$(gen_files_ocsp_template) ocsp_template_asn1.h ocsp_template_asn1-priv.h: ocsp_template_asn1_files
+$(gen_files_pkinit) pkinit_asn1.h pkinit_asn1-priv.h: pkinit_asn1_files
+$(gen_files_pkinit_template) pkinit_template_asn1.h pkinit_template_asn1-priv.h: pkinit_template_asn1_files
+$(gen_files_pkcs8) pkcs8_asn1.h pkcs8_asn1-priv.h: pkcs8_asn1_files
+$(gen_files_pkcs8_template) pkcs8_template_asn1.h pkcs8_template_asn1-priv.h: pkcs8_template_asn1_files
+$(gen_files_pkcs9) pkcs9_asn1.h pkcs9_asn1-priv.h: pkcs9_asn1_files
+$(gen_files_pkcs9_template) pkcs9_template_asn1.h pkcs9_template_asn1-priv.h: pkcs9_template_asn1_files
+$(gen_files_pkcs10) pkcs10_asn1.h pkcs10_asn1-priv.h: pkcs10_asn1_files
+$(gen_files_pkcs10_template) pkcs10_template_asn1.h pkcs10_template_asn1-priv.h: pkcs10_template_asn1_files
+$(gen_files_pkcs12) pkcs12_asn1.h pkcs12_asn1-priv.h: pkcs12_asn1_files
+$(gen_files_pkcs12_template) pkcs12_template_asn1.h pkcs12_template_asn1-priv.h: pkcs12_template_asn1_files
+$(gen_files_digest) digest_asn1.h digest_asn1-priv.h: digest_asn1_files
+$(gen_files_digest_template) digest_template_asn1.h digest_template_asn1-priv.h: digest_template_asn1_files
+$(gen_files_kx509) kx509_asn1.h kx509_asn1-priv.h: kx509_asn1_files
+$(gen_files_kx509_template) kx509_template_asn1.h kx509_template_asn1-priv.h: kx509_template_asn1_files
+$(gen_files_rfc2459) rfc2459_asn1.h rfc2459_asn1-priv.h: rfc2459_asn1_files
+$(gen_files_rfc2459_template) rfc2459_template_asn1.h rfc2459_template_asn1-priv.h: rfc2459_template_asn1_files
+$(gen_files_rfc4108) rfc4108_asn1.h rfc4108_asn1-priv.h: rfc4108_asn1_files
+$(gen_files_rfc4108_template) rfc4108_template_asn1.h rfc4108_template_asn1-priv.h: rfc4108_template_asn1_files
+$(gen_files_cms) cms_asn1.h cms_asn1-priv.h: cms_asn1_files
+$(gen_files_cms_template) cms_template_asn1.h cms_template_asn1-priv.h: cms_template_asn1_files
+$(gen_files_crmf) crmf_asn1.h crmf_asn1-priv.h: crmf_asn1_files
+$(gen_files_crmf_template) crmf_template_asn1.h crmf_template_asn1-priv.h: crmf_template_asn1_files
+$(gen_files_x690sample) x690sample_asn1.h x690sample_asn1-priv.h: x690sample_asn1_files
+$(gen_files_x690sample_template) x690sample_template_asn1.h x690sample_template_asn1-priv.h: x690sample_template_asn1_files
+$(gen_files_test) test_asn1.h test_asn1-priv.h: test_asn1_files
+$(gen_files_test_template) test_template_asn1.h test_template_asn1-priv.h: test_template_asn1_files
+
+if ASN1_TEMPLATING
+TEMPLATE_OPTION=--template
+else
+TEMPLATE_OPTION=
+endif
+
+# If the default is not templating, then we build a variant of libasn1 that is
+# templated anyways.
+rfc2459_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/rfc2459.asn1
+ $(ASN1_COMPILE) --one-code-file --template --option-file=$(srcdir)/rfc2459.opt $(srcdir)/rfc2459.asn1 rfc2459_template_asn1 || (rm -f rfc2459_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_rfc2459_template_asn1.c
+
+rfc4108_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/rfc4108.asn1
+ $(ASN1_COMPILE) --one-code-file --template $(srcdir)/rfc4108.asn1 rfc4108_template_asn1 || (rm -f rfc4108_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_rfc4108_template_asn1.c
+
+cms_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/cms.asn1 $(srcdir)/cms.opt
+ $(ASN1_COMPILE) --one-code-file --template --option-file=$(srcdir)/cms.opt $(srcdir)/cms.asn1 cms_template_asn1 || (rm -f cms_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_cms_template_asn1.c
+
+crmf_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/crmf.asn1 $(srcdir)/crmf.opt
+ $(ASN1_COMPILE) --one-code-file --template --option-file=$(srcdir)/crmf.opt $(srcdir)/crmf.asn1 crmf_template_asn1 || (rm -f crmf_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_crmf_template_asn1.c
+
+krb5_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/krb5.asn1 $(srcdir)/krb5.opt
+ $(ASN1_COMPILE) --one-code-file --template \
+ --option-file=$(srcdir)/krb5.opt \
+ $(srcdir)/krb5.asn1 krb5_template_asn1 || (rm -f krb5_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_krb5_template_asn1.c
+
+ocsp_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/ocsp.asn1
+ $(ASN1_COMPILE) --one-code-file --template --option-file=$(srcdir)/ocsp.opt $(srcdir)/ocsp.asn1 ocsp_template_asn1 || (rm -f ocsp_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_ocsp_template_asn1.c
+
+pkinit_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkinit.asn1
+ $(ASN1_COMPILE) --one-code-file --template $(srcdir)/pkinit.asn1 pkinit_template_asn1 || (rm -f pkinit_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_pkinit_template_asn1.c
+
+pkcs8_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkcs8.asn1
+ $(ASN1_COMPILE) --one-code-file --template $(srcdir)/pkcs8.asn1 pkcs8_template_asn1 || (rm -f pkcs8_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_pkcs8_template_asn1.c
+
+pkcs9_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkcs9.asn1
+ $(ASN1_COMPILE) --one-code-file --template $(srcdir)/pkcs9.asn1 pkcs9_template_asn1 || (rm -f pkcs9_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_pkcs9_template_asn1.c
+
+pkcs10_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkcs10.asn1
+ $(ASN1_COMPILE) --one-code-file --template --option-file=$(srcdir)/pkcs10.opt $(srcdir)/pkcs10.asn1 pkcs10_template_asn1 || (rm -f pkcs10_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_pkcs10_template_asn1.c
+
+pkcs12_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkcs12.asn1
+ $(ASN1_COMPILE) --one-code-file --template $(srcdir)/pkcs12.asn1 pkcs12_template_asn1 || (rm -f pkcs12_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_pkcs12_template_asn1.c
+
+digest_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/digest.asn1
+ $(ASN1_COMPILE) --one-code-file --template $(srcdir)/digest.asn1 digest_template_asn1 || (rm -f digest_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_digest_template_asn1.c
+
+kx509_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/kx509.asn1
+ $(ASN1_COMPILE) --one-code-file --template $(srcdir)/kx509.asn1 kx509_template_asn1 || (rm -f kx509_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_kx509_template_asn1.c
+
+rfc2459_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/rfc2459.asn1
+ $(ASN1_COMPILE) --one-code-file $(TEMPLATE_OPTION) --option-file=$(srcdir)/rfc2459.opt $(srcdir)/rfc2459.asn1 rfc2459_asn1 || (rm -f rfc2459_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_rfc2459_asn1.c
+
+rfc4108_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/rfc4108.asn1
+ $(ASN1_COMPILE) --one-code-file $(TEMPLATE_OPTION) $(srcdir)/rfc4108.asn1 rfc4108_asn1 || (rm -f rfc4108_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_rfc4108_asn1.c
+
+cms_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/cms.asn1 $(srcdir)/cms.opt
+ $(ASN1_COMPILE) --one-code-file $(TEMPLATE_OPTION) --option-file=$(srcdir)/cms.opt $(srcdir)/cms.asn1 cms_asn1 || (rm -f cms_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_cms_asn1.c
+
+crmf_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/crmf.asn1 $(srcdir)/crmf.opt
+ $(ASN1_COMPILE) --one-code-file $(TEMPLATE_OPTION) --option-file=$(srcdir)/crmf.opt $(srcdir)/crmf.asn1 crmf_asn1 || (rm -f crmf_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_crmf_asn1.c
+
+krb5_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/krb5.asn1 $(srcdir)/krb5.opt
+ $(ASN1_COMPILE) --one-code-file $(TEMPLATE_OPTION) \
+ --option-file=$(srcdir)/krb5.opt \
+ $(srcdir)/krb5.asn1 krb5_asn1 || (rm -f krb5_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_krb5_asn1.c
+
+ocsp_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/ocsp.asn1
+ $(ASN1_COMPILE) --one-code-file $(TEMPLATE_OPTION) --option-file=$(srcdir)/ocsp.opt $(srcdir)/ocsp.asn1 ocsp_asn1 || (rm -f ocsp_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_ocsp_asn1.c
+
+pkinit_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkinit.asn1
+ $(ASN1_COMPILE) --one-code-file $(TEMPLATE_OPTION) $(srcdir)/pkinit.asn1 pkinit_asn1 || (rm -f pkinit_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_pkinit_asn1.c
+
+pkcs8_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkcs8.asn1
+ $(ASN1_COMPILE) --one-code-file $(TEMPLATE_OPTION) $(srcdir)/pkcs8.asn1 pkcs8_asn1 || (rm -f pkcs8_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_pkcs8_asn1.c
+
+pkcs9_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkcs9.asn1
+ $(ASN1_COMPILE) --one-code-file $(TEMPLATE_OPTION) $(srcdir)/pkcs9.asn1 pkcs9_asn1 || (rm -f pkcs9_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_pkcs9_asn1.c
+
+pkcs10_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkcs10.asn1
+ $(ASN1_COMPILE) --one-code-file $(TEMPLATE_OPTION) --option-file=$(srcdir)/pkcs10.opt $(srcdir)/pkcs10.asn1 pkcs10_asn1 || (rm -f pkcs10_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_pkcs10_asn1.c
+
+pkcs12_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkcs12.asn1
+ $(ASN1_COMPILE) --one-code-file $(TEMPLATE_OPTION) $(srcdir)/pkcs12.asn1 pkcs12_asn1 || (rm -f pkcs12_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_pkcs12_asn1.c
+
+digest_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/digest.asn1
+ $(ASN1_COMPILE) --one-code-file $(TEMPLATE_OPTION) $(srcdir)/digest.asn1 digest_asn1 || (rm -f digest_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_digest_asn1.c
+
+kx509_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/kx509.asn1
+ $(ASN1_COMPILE) --one-code-file $(TEMPLATE_OPTION) $(srcdir)/kx509.asn1 kx509_asn1 || (rm -f kx509_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_kx509_asn1.c
+
+x690sample_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/x690sample.asn1
+ $(ASN1_COMPILE) --one-code-file --template $(srcdir)/x690sample.asn1 x690sample_template_asn1 || (rm -f x690sample_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_x690sample_template_asn1.c
+
+x690sample_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/x690sample.asn1
+ $(ASN1_COMPILE) --one-code-file $(srcdir)/x690sample.asn1 x690sample_asn1 || (rm -f x690sample_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_x690sample_asn1.c
+
+test_template_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/test.asn1
+ $(ASN1_COMPILE) --one-code-file \
+ --template \
+ --option-file=$(srcdir)/test.opt \
+ $(srcdir)/test.asn1 test_template_asn1 || (rm -f test_template_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_test_template_asn1.c
+
+test_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/test.asn1
+ $(ASN1_COMPILE) --one-code-file \
+ --option-file=$(srcdir)/test.opt \
+ $(srcdir)/test.asn1 test_asn1 || (rm -f test_asn1_files ; exit 1)
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i asn1_test_asn1.c
+
+
+EXTRA_DIST = \
+ NTMakefile \
+ README-template.md \
+ asn1_compile-version.rc \
+ libasn1-exports.def \
+ canthandle.asn1 \
+ cms.asn1 \
+ cms.opt \
+ crmf.asn1 \
+ crmf.opt \
+ digest.asn1 \
+ krb5.asn1 \
+ krb5.opt \
+ kx509.asn1 \
+ ocsp.asn1 \
+ ocsp.opt \
+ pkcs10.asn1 \
+ pkcs10.opt \
+ pkcs12.asn1 \
+ pkcs8.asn1 \
+ pkcs9.asn1 \
+ pkinit.asn1 \
+ pku2u.asn1 \
+ rfc2459.asn1 \
+ rfc2459.opt \
+ rfc4108.asn1 \
+ setchgpw2.asn1 \
+ tcg.asn1 \
+ test.asn1 \
+ test.opt \
+ x690sample.asn1 \
+ test.gen \
+ asn1_err.et \
+ asn1_err.c \
+ asn1_err.h \
+ asn1_print.1 \
+ asn1_compile.1 \
+ version-script.map
+
+DER_PROTOS = $(srcdir)/der-protos.h $(srcdir)/der-private.h
+
+ALL_OBJECTS = $(libasn1_la_OBJECTS)
+ALL_OBJECTS += $(libasn1template_la_OBJECTS)
+ALL_OBJECTS += $(libasn1base_la_OBJECTS)
+ALL_OBJECTS += $(asn1_print_OBJECTS)
+ALL_OBJECTS += $(asn1_compile_OBJECTS)
+ALL_OBJECTS += $(asn1_gen_OBJECTS)
+ALL_OBJECTS += $(check_template_OBJECTS)
+
+$(ALL_OBJECTS): $(DER_PROTOS) asn1_err.h
+
+$(srcdir)/der-protos.h: $(dist_libasn1base_la_SOURCES) $(dist_libasn1_la_SOURCES)
+ cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -o der-protos.h $(dist_libasn1base_la_SOURCES) $(dist_libasn1_la_SOURCES) || rm -f der-protos.h
+
+$(srcdir)/der-private.h: $(dist_libasn1base_la_SOURCES) $(dist_libasn1_la_SOURCES)
+ cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p der-private.h $(dist_libasn1base_la_SOURCES) $(dist_libasn1_la_SOURCES) || rm -f der-private.h
diff --git a/third_party/heimdal/lib/asn1/NTMakefile b/third_party/heimdal/lib/asn1/NTMakefile
new file mode 100644
index 0000000..19255c6
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/NTMakefile
@@ -0,0 +1,548 @@
+########################################################################
+#
+# Copyright (c) 2009-2022, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\asn1
+
+intcflags=-I$(SRCDIR) -I$(OBJ) -DROKEN_RENAME -DASN1_IOS_SUPPORTED -DASN1_LIB
+
+!include ../../windows/NTMakefile.w32
+
+ASN1_BINARIES = \
+ $(LIBEXECDIR)\asn1_compile.exe
+
+$(BINDIR)\asn1_compile.exe: \
+ $(OBJ)\asn1parse.obj \
+ $(OBJ)\gen.obj \
+ $(OBJ)\gen_copy.obj \
+ $(OBJ)\gen_decode.obj \
+ $(OBJ)\gen_encode.obj \
+ $(OBJ)\gen_print.obj \
+ $(OBJ)\gen_free.obj \
+ $(OBJ)\gen_glue.obj \
+ $(OBJ)\gen_length.obj \
+ $(OBJ)\gen_seq.obj \
+ $(OBJ)\gen_template.obj \
+ $(OBJ)\hash.obj \
+ $(OBJ)\lex.obj \
+ $(OBJ)\main.obj \
+ $(OBJ)\symbol.obj \
+ $(OBJ)\asn1_compile-version.res
+ $(EXECONLINK) $(LIBROKEN) $(LIBVERS)
+ $(EXEPREP_NOHEIM)
+
+$(OBJ)\lex.c: lex.l $(OBJ)\asn1parse.h
+ $(LEX) -o$@ lex.l
+
+$(OBJ)\lex.obj: $(OBJ)\lex.c
+ $(C2OBJ) -DYY_NO_UNISTD_H
+
+$(OBJ)\asn1parse.c $(OBJ)\asn1parse.h: asn1parse.y
+ $(YACC) -o $(OBJ)\asn1parse.c --defines=$(OBJ)\asn1parse.h $**
+
+$(OBJ)\asn1_err.c $(OBJ)\asn1_err.h: asn1_err.et
+ cd $(OBJ)
+ $(BINDIR)\compile_et.exe $(SRCDIR)\asn1_err.et
+ cd $(SRCDIR)
+
+$(BINDIR)\asn1_print.exe: $(OBJ)\asn1_print.obj $(LIBHEIMDAL)
+ $(EXECONLINK) $(LIBVERS) $(LIBROKEN) $(LIBCOMERR)
+ $(EXEPREP)
+
+$(BINDIR)\asn1_gen.exe: $(OBJ)\asn1_gen.obj $(LIBHEIMDAL)
+ $(EXECONLINK) $(LIBVERS) $(LIBROKEN)
+ $(EXEPREP)
+
+LIBASN1_X= \
+ $(OBJ)\asn1_rfc2459_asn1.c \
+ $(OBJ)\asn1_rfc4108_asn1.c \
+ $(OBJ)\asn1_cms_asn1.c \
+ $(OBJ)\asn1_krb5_asn1.c \
+ $(OBJ)\asn1_ocsp_asn1.c \
+ $(OBJ)\asn1_pkinit_asn1.c \
+ $(OBJ)\asn1_pkcs8_asn1.c \
+ $(OBJ)\asn1_pkcs9_asn1.c \
+ $(OBJ)\asn1_pkcs10_asn1.c \
+ $(OBJ)\asn1_pkcs12_asn1.c \
+ $(OBJ)\asn1_digest_asn1.c \
+ $(OBJ)\asn1_kx509_asn1.c \
+ $(OBJ)\asn1_x690sample_asn1.c
+
+LIBASN1_OBJS= \
+ $(OBJ)\der.obj \
+ $(OBJ)\der_get.obj \
+ $(OBJ)\der_put.obj \
+ $(OBJ)\der_free.obj \
+ $(OBJ)\der_print.obj \
+ $(OBJ)\der_length.obj \
+ $(OBJ)\der_copy.obj \
+ $(OBJ)\der_cmp.obj \
+ $(OBJ)\der_format.obj \
+ $(OBJ)\template.obj \
+ $(OBJ)\extra.obj \
+ $(OBJ)\oid_resolution.obj \
+ $(OBJ)\timegm.obj \
+ $(OBJ)\asn1_rfc2459_asn1.obj \
+ $(OBJ)\asn1_rfc4108_asn1.obj \
+ $(OBJ)\asn1_cms_asn1.obj \
+ $(OBJ)\asn1_krb5_asn1.obj \
+ $(OBJ)\asn1_ocsp_asn1.obj \
+ $(OBJ)\asn1_pkinit_asn1.obj \
+ $(OBJ)\asn1_pkcs8_asn1.obj \
+ $(OBJ)\asn1_pkcs9_asn1.obj \
+ $(OBJ)\asn1_pkcs10_asn1.obj \
+ $(OBJ)\asn1_pkcs12_asn1.obj \
+ $(OBJ)\asn1_digest_asn1.obj \
+ $(OBJ)\asn1_kx509_asn1.obj \
+ $(OBJ)\asn1_x690sample_asn1.obj \
+ $(OBJ)\asn1_err.obj
+
+$(OBJ)\oid_resolution.obj: $(LIBASN1_X)
+
+$(LIBASN1): $(LIBASN1_OBJS)
+ $(LIBCON_C) -out:$@ @<<
+$(**: =
+)
+<<
+
+clean::
+ -$(RM) $(LIBASN1)
+
+#
+# The static runtime version LIBASN1_S is for use by thirdparty
+# components. It is not used in the construction of the Heimdal
+# DLLs.
+
+LIBASN1_S_OBJS= \
+ $(OBJ)\der.s.obj \
+ $(OBJ)\der_get.s.obj \
+ $(OBJ)\der_put.s.obj \
+ $(OBJ)\der_free.s.obj \
+ $(OBJ)\der_print.s.obj \
+ $(OBJ)\der_length.s.obj \
+ $(OBJ)\der_copy.s.obj \
+ $(OBJ)\der_cmp.s.obj \
+ $(OBJ)\der_format.s.obj \
+ $(OBJ)\template.s.obj \
+ $(OBJ)\extra.s.obj \
+ $(OBJ)\oid_resolution.s.obj \
+ $(OBJ)\timegm.s.obj \
+ $(OBJ)\asn1_rfc2459_asn1.s.obj \
+ $(OBJ)\asn1_rfc4108_asn1.s.obj \
+ $(OBJ)\asn1_cms_asn1.s.obj \
+ $(OBJ)\asn1_krb5_asn1.s.obj \
+ $(OBJ)\asn1_ocsp_asn1.s.obj \
+ $(OBJ)\asn1_pkinit_asn1.s.obj \
+ $(OBJ)\asn1_pkcs8_asn1.s.obj \
+ $(OBJ)\asn1_pkcs9_asn1.s.obj \
+ $(OBJ)\asn1_pkcs10_asn1.s.obj \
+ $(OBJ)\asn1_pkcs12_asn1.s.obj \
+ $(OBJ)\asn1_digest_asn1.s.obj \
+ $(OBJ)\asn1_kx509_asn1.s.obj \
+ $(OBJ)\asn1_x690sample_asn1.s.obj \
+ $(OBJ)\asn1_err.s.obj
+
+$(OBJ)\oid_resolution.s.obj: oid_resolution.c $(LIBASN1_X)
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ oid_resolution.c
+
+$(OBJ)\der.s.obj: der.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\der_get.s.obj: der_get.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\der_put.s.obj: der_put.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\der_free.s.obj: der_free.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\der_print.s.obj: der_print.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\der_length.s.obj: der_length.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\der_copy.s.obj: der_copy.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\der_cmp.s.obj: der_cmp.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\der_format.s.obj: der_format.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\template.s.obj: template.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\extra.s.obj: extra.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\timegm.s.obj: timegm.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_rfc2459_asn1.s.obj: $(OBJ)\asn1_rfc2459_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_rfc4108_asn1.s.obj: $(OBJ)\asn1_rfc4108_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_cms_asn1.s.obj: $(OBJ)\asn1_cms_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_krb5_asn1.s.obj: $(OBJ)\asn1_krb5_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_ocsp_asn1.s.obj: $(OBJ)\asn1_ocsp_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_pkinit_asn1.s.obj: $(OBJ)\asn1_pkinit_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_pkcs8_asn1.s.obj: $(OBJ)\asn1_pkcs8_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_pkcs9_asn1.s.obj: $(OBJ)\asn1_pkcs9_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_pkcs10_asn1.s.obj: $(OBJ)\asn1_pkcs10_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_pkcs12_asn1.s.obj: $(OBJ)\asn1_pkcs12_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_digest_asn1.s.obj: $(OBJ)\asn1_digest_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_kx509_asn1.s.obj: $(OBJ)\asn1_kx509_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_x690sample_asn1.s.obj: $(OBJ)\asn1_x690sample_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_test_asn1.s.obj: $(OBJ)\asn1_test_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_test_template_asn1.s.obj: $(OBJ)\asn1_test_template_asn1.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(OBJ)\asn1_err.s.obj: $(OBJ)\asn1_err.c
+ $(C2OBJ_C_MT) -Fo$@ -Fd$(@D)\ $**
+
+$(LIBASN1_S): $(LIBASN1_S_OBJS)
+ $(LIBCON_C) -out:$@ @<<
+$(**: =
+)
+<<
+
+clean::
+ -$(RM) $(LIBASN1_S)
+
+
+#
+# Generate list of exports
+#
+# This target is only used during development to generate a list of
+# symbols that are exported from all the object files in LIBASN1_OBJS.
+#
+exports-list.txt: $(LIBASN1_OBJS)
+ $(PERL) ..\..\cf\w32-list-externs-from-objs.pl -q -u @<< > $@
+$(**: =
+)
+<<
+
+$(OBJ)\asn1_krb5_asn1.c $(OBJ)\krb5_asn1.h: $(BINDIR)\asn1_compile.exe krb5.asn1 krb5.opt
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe \
+ --template \
+ --one-code-file \
+ --option-file=$(SRCDIR)\krb5.opt \
+ $(SRCDIR)\krb5.asn1 krb5_asn1 \
+ || ($(RM) $(OBJ)\krb5_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(OBJ)\asn1_ocsp_asn1.c $(OBJ)\ocsp_asn1.h: $(BINDIR)\asn1_compile.exe ocsp.asn1
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe \
+ --template \
+ --one-code-file \
+ --option-file=$(SRCDIR)\ocsp.opt \
+ $(SRCDIR)\ocsp.asn1 \
+ ocsp_asn1 \
+ || ($(RM) $(OBJ)\ocsp_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(OBJ)\asn1_pkinit_asn1.c $(OBJ)\pkinit_asn1.h: $(BINDIR)\asn1_compile.exe pkinit.asn1
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe --template --one-code-file $(SRCDIR)\pkinit.asn1 pkinit_asn1 \
+ || ($(RM) $(OBJ)\pkinit_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(OBJ)\asn1_pkcs8_asn1.c $(OBJ)\pkcs8_asn1.h: $(BINDIR)\asn1_compile.exe pkcs8.asn1
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe --template --one-code-file $(SRCDIR)\pkcs8.asn1 pkcs8_asn1 \
+ || ($(RM) $(OBJ)\pkcs8_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(OBJ)\asn1_pkcs9_asn1.c $(OBJ)\pkcs9_asn1.h: $(BINDIR)\asn1_compile.exe pkcs9.asn1
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe --template --one-code-file $(SRCDIR)\pkcs9.asn1 pkcs9_asn1 \
+ || ($(RM) $(OBJ)\pkcs9_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(OBJ)\asn1_pkcs10_asn1.c $(OBJ)\pkcs10_asn1.h: $(BINDIR)\asn1_compile.exe pkcs10.asn1
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe \
+ --template \
+ --one-code-file \
+ --option-file=$(SRCDIR)\pkcs10.opt \
+ $(SRCDIR)\pkcs10.asn1 \
+ pkcs10_asn1 \
+ || ($(RM) $(OBJ)\pkcs10_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(OBJ)\asn1_pkcs12_asn1.c $(OBJ)\pkcs12_asn1.h: $(BINDIR)\asn1_compile.exe pkcs12.asn1
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe --template --one-code-file $(SRCDIR)\pkcs12.asn1 pkcs12_asn1 \
+ || ($(RM) $(OBJ)\pkcs12_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(OBJ)\asn1_digest_asn1.c $(OBJ)\digest_asn1.h: $(BINDIR)\asn1_compile.exe digest.asn1
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe --template --one-code-file $(SRCDIR)\digest.asn1 digest_asn1 \
+ || ($(RM) $(OBJ)\digest_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(OBJ)\asn1_kx509_asn1.c $(OBJ)\kx509_asn1.h: $(BINDIR)\asn1_compile.exe kx509.asn1
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe --template --one-code-file $(SRCDIR)\kx509.asn1 kx509_asn1 \
+ || ($(RM) $(OBJ)\kx509_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(OBJ)\asn1_rfc2459_asn1.c $(OBJ)\rfc2459_asn1.h: $(BINDIR)\asn1_compile.exe rfc2459.asn1
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe \
+ --template \
+ --one-code-file \
+ --option-file=$(SRCDIR)\rfc2459.opt \
+ $(SRCDIR)\rfc2459.asn1 rfc2459_asn1 \
+ || ($(RM) $(OBJ)\rfc2459_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(OBJ)\asn1_rfc4108_asn1.c $(OBJ)\rfc4108_asn1.h: $(BINDIR)\asn1_compile.exe rfc4108.asn1
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe \
+ --template \
+ --one-code-file \
+ $(SRCDIR)\rfc4108.asn1 rfc4108_asn1 \
+ || ($(RM) $(OBJ)\rfc4108_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(OBJ)\asn1_cms_asn1.c $(OBJ)\cms_asn1.h: $(BINDIR)\asn1_compile.exe cms.asn1 cms.opt
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe \
+ --template \
+ --one-code-file --option-file=$(SRCDIR)\cms.opt \
+ $(SRCDIR)\cms.asn1 cms_asn1 \
+ || ($(RM) $(OBJ)\cms_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(gen_files_crmf) $(OBJ)\crmf_asn1.h: $(BINDIR)\asn1_compile.exe crmf.asn1 crmf.opt
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe \
+ --template \
+ --one-code-file --option-file=$(SRCDIR)\crmf.opt \
+ $(SRCDIR)\crmf.asn1 crmf_asn1 \
+ || ($(RM) $(OBJ)\crmf_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(OBJ)\asn1_x690sample_asn1.c $(OBJ)\x690sample_asn1.h: $(BINDIR)\asn1_compile.exe x690sample.asn1
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe \
+ --template \
+ --one-code-file \
+ $(SRCDIR)\x690sample.asn1 x690sample_asn1 \
+ || ($(RM) $(OBJ)\x690sample_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(OBJ)\asn1_test_asn1.c $(OBJ)\test_asn1.h: $(BINDIR)\asn1_compile.exe test.asn1
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe \
+ --template \
+ --option-file=$(SRCDIR)/test.opt \
+ --one-code-file \
+ $(SRCDIR)\test.asn1 test_asn1 \
+ || ($(RM) $(OBJ)\test_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+$(OBJ)\asn1_test_template_asn1.c $(OBJ)\test_template_asn1.h: $(BINDIR)\asn1_compile.exe test.asn1
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe \
+ --template \
+ --option-file=$(SRCDIR)/test.opt \
+ --one-code-file \
+ $(SRCDIR)\test.asn1 test_template_asn1 \
+ || ($(RM) $(OBJ)\test_template_asn1.h ; exit /b 1)
+ cd $(SRCDIR)
+
+INCFILES= \
+ $(INCDIR)\der.h \
+ $(INCDIR)\heim_asn1.h \
+ $(INCDIR)\der-protos.h \
+ $(INCDIR)\der-private.h \
+ $(INCDIR)\asn1-common.h \
+ $(INCDIR)\asn1-template.h \
+ $(OBJ)\asn1_err.h
+
+$(INCDIR)\der-protos.h: $(OBJ)\der-protos.h
+
+GENINCFILES= \
+ $(INCDIR)\asn1_err.h \
+ $(INCDIR)\cms_asn1.h \
+ $(INCDIR)\crmf_asn1.h \
+ $(INCDIR)\digest_asn1.h \
+ $(INCDIR)\krb5_asn1.h \
+ $(INCDIR)\kx509_asn1.h \
+ $(INCDIR)\ocsp_asn1.h \
+ $(INCDIR)\pkcs12_asn1.h \
+ $(INCDIR)\pkcs8_asn1.h \
+ $(INCDIR)\pkcs9_asn1.h \
+ $(INCDIR)\pkcs10_asn1.h \
+ $(INCDIR)\pkinit_asn1.h \
+ $(INCDIR)\rfc2459_asn1.h \
+ $(INCDIR)\rfc4108_asn1.h \
+ $(INCDIR)\x690sample_asn1.h \
+ $(OBJ)\krb5_asn1-priv.h \
+ $(OBJ)\ocsp_asn1-priv.h \
+ $(OBJ)\pkinit_asn1-priv.h \
+ $(OBJ)\cms_asn1-priv.h \
+ $(OBJ)\crmf_asn1-priv.h \
+ $(OBJ)\rfc2459_asn1-priv.h \
+ $(OBJ)\rfc4108_asn1-priv.h \
+ $(OBJ)\x690sample_asn1-priv.h \
+ $(OBJ)\pkcs8_asn1-priv.h \
+ $(OBJ)\pkcs9_asn1-priv.h \
+ $(OBJ)\pkcs10_asn1-priv.h \
+ $(OBJ)\pkcs12_asn1-priv.h \
+ $(OBJ)\digest_asn1-priv.h \
+ $(OBJ)\kx509_asn1-priv.h \
+ $(OBJ)\test_template_asn1.h \
+ $(OBJ)\test_template_asn1-priv.h \
+ $(OBJ)\test_asn1.h \
+ $(OBJ)\test_asn1-priv.h
+
+libasn1_base_SOURCES= \
+ der_locl.h \
+ der.c \
+ der.h \
+ der_get.c \
+ der_put.c \
+ der_free.c \
+ der_print.c \
+ der_length.c \
+ der_copy.c \
+ der_cmp.c \
+ der_format.c \
+ template.c \
+ heim_asn1.h \
+ extra.c \
+ timegm.c
+
+libasn1_SOURCES= \
+ oid_resolution.c
+
+$(OBJ)\der-protos.h: $(libasn1_SOURCES)
+ $(PERL) ..\..\cf\make-proto.pl -q -P remove -o $(OBJ)\der-protos.h $(libasn1_base_SOURCES) $(libasn1_SOURCES) || $(RM) $(OBJ)\der-protos.h
+
+$(OBJ)\der-private.h: $(libasn1_SOURCES)
+ $(PERL) ..\..\cf\make-proto.pl -q -P remove -p $(OBJ)\der-private.h $(libasn1_base_SOURCES) $(libasn1_SOURCES) || $(RM) $(OBJ)\der-private.h
+
+clean::
+ -$(RM) $(INCDIR)\der-protos.h
+
+all:: $(INCFILES) $(GENINCFILES) $(ASN1_BINARIES) $(LIBASN1) $(LIBASN1_S)
+
+all-tools:: $(LIBEXECDIR)\asn1_print.exe $(BINDIR)\asn1_gen.exe
+
+clean::
+ -$(RM) $(INCFILES)
+ -$(RM) $(GENINCFILES)
+ -$(RM) $(ASN1_BINARIES:.exe=.*)
+ -$(RM) $(LIBASN1)
+ -$(RM) $(LIBEXECDIR)\asn1_print.*
+ -$(RM) $(LIBEXECDIR)\asn1_gen.*
+
+TEST_BINARIES=\
+ $(OBJ)\check-der.exe \
+ $(OBJ)\check-gen-template.exe \
+ $(OBJ)\check-timegm.exe \
+ $(OBJ)\check-ber.exe \
+ $(OBJ)\check-template.exe
+
+test-binaries: $(TEST_BINARIES)
+
+test-run:
+ cd $(OBJ)
+ -check-der.exe
+ -check-gen-template.exe
+ -check-timegm.exe
+ -check-ber.exe
+ -check-template.exe
+ cd $(SRC)
+
+test:: test-binaries test-run
+
+clean::
+ -$(RM) $(TEST_BINARIES:.exe=*)
+
+$(OBJ)\check-ber.exe: $(OBJ)\check-ber.obj \
+ $(LIBHEIMDAL) $(LIBROKEN)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\check-der.exe: $(OBJ)\check-der.obj $(OBJ)\check-common.obj \
+ $(LIBHEIMDAL) $(LIBROKEN)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\check-gen-template.exe: $(OBJ)\check-gen.obj $(OBJ)\check-common.obj \
+ $(LIBHEIMDAL) $(LIBROKEN) $(OBJ)\asn1_test_template_asn1.obj
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\check-timegm.exe: $(OBJ)\check-timegm.obj \
+ $(LIBHEIMDAL) $(LIBROKEN)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\check-template.exe: $(OBJ)\check-template.obj $(OBJ)\check-common.obj \
+ $(LIBHEIMDAL) $(LIBROKEN) $(OBJ)\asn1_test_asn1.obj
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
diff --git a/third_party/heimdal/lib/asn1/README-X681.md b/third_party/heimdal/lib/asn1/README-X681.md
new file mode 100644
index 0000000..e0d270b
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/README-X681.md
@@ -0,0 +1,1124 @@
+# Automatic Open Type Handling via X.68x Support in Heimdal's ASN.1 Compiler
+
+## Table of Contents
+
+ 1. [Introduction](#Introduction)
+ 2. [Typed Holes / Open Types](#typed-holes--open-types)
+ 3. [ASN.1 IOS, Constraint, and Parameterization](#asn1-ios-constraint-and-parameterization)
+ - [IOS Crash Course](#ios-crash-course)
+ 4. [Usage](#Usage)
+ 5. [Limitations](#Limitations)
+ 6. [Implementation Design](#implementation-design)
+ 7. [Moving From C](#moving-from-c)
+
+## Introduction
+
+ASN.1 is a set of specifications for "syntax" for defining data schemas, and
+"encoding rules" for encoding values of data of types defined in those schemas.
+There are many encoding rules, but one syntax.
+
+The base of ASN.1 _syntax_ is specified by X.680, an ITU-T standard. The
+encoding rules are specified by the X.69x series (X.690 through X.697).
+
+This README is concerned primarily with the X.68x series.
+
+While X.680 is essential for implementing many Internet (and other) protocols,
+and sufficient for implementing all of those, there are extensions in the
+remainder of the X.68x series that can make life a lot easier for developers
+who have to use ASN.1 for interoperability reasons.
+
+Various syntax extensions are specified in X.68x series documents:
+
+ - X.681: Information Object specification
+ - X.682: Constraint specification
+ - X.683: Parameterization of ASN.1 specifications
+
+The intent of X.681, X.682, and X.683 is to add ways to formally express
+constraints that would otherwise require natural language to express. Give a
+compiler more formally-expressed constraints and it can do more labor-saving
+than it could otherwise.
+
+A subset of these three extensions, X.681, X.682, and X.683, can enable some
+rather magical features. These magical features are generally not the focus of
+those ITU-T specifications nor of many RFCs that make use of them, but
+nonetheless they are of interest to us.
+
+This README covers some ideas for what this magic is, and implementation of it.
+
+RFC 6025 does an excellent job of elucidating X.681, which otherwise most
+readers unfamiliar with it will no doubt find inscrutable. Hopefully this
+README improves that further.
+
+The magic that we're after is simply the *automatic and recursive handling of
+open types by an ASN.1 compiler*.
+
+Combined with eventual support for the ASN.1 JSON Encoding Rules (JER) [X.697],
+this feature could give us unprecendented visibility into really complex data
+structures, such as Endorsement Key Certificates (EKcerts) for Trusted Platform
+Module (TPM) applications.
+
+Support for JER and automatic handling of open types should allow us to
+trivially implement a command-line tool that can parse any DER or JER (JSON)
+encoding of any value whose type is known and compiled, and which could
+transcode to the other encoding rules. I.e., dump DER to JSON, and parse JSON
+to output DER.
+
+Indeed, Heimdal's `asn1_print` program currently supports transcoding of DER to
+JSON, though it's not quite X.697-compliant JSON! Heimdal does not currently
+support parsing JSON-encoded values of ASN.1 types.
+
+Combined with transcoders for JSON/CBOR and other binary-JSON formats, we could
+support those encodings too.
+
+We could really see how much space OER/JER/CBOR save over DER for Kerberos
+tickets, PKIX certificates, and much else.
+
+We especially want this for PKIX, and more than anything for certificates, as
+the TBSCertificate type is full of deeply nested open types: DNs and
+subjectDirectory attributes, otherName SAN types, and certificate extensions.
+
+Besides a magical ASN.1 DER/JER dumper/transcoder utility, we want to replace
+DN attribute and subject alternative name (SAN) `otherName` tables and much
+hand-coded handling of certificate extensions in `lib/hx509/`.
+
+The reader should already be familiar with ASN.1, which anyways is a set of two
+things:
+
+ - an abstract syntax for specifying schemas for data interchange
+
+ - a set of encoding rules
+
+A very common thing to see in projects that use ASN.1, as well as projects that
+use alternatives to ASN.1, is a pattern known as the "typed hole" or "open
+type".
+
+The ASN.1 Information Object System (IOS) [X.681] is all about automating the
+otherwise very annoying task of dealing with "typed holes" / "open types".
+
+The ASN.1 IOS is not sufficient to implement the magic we're after. Also
+needed is constraint specification and parameterization of types.
+
+ITU-T references:
+
+https://www.itu.int/rec/T-REC-X.680-201508-I/en
+https://www.itu.int/rec/T-REC-X.681-201508-I/en
+https://www.itu.int/rec/T-REC-X.682-201508-I/en
+https://www.itu.int/rec/T-REC-X.683-201508-I/en
+
+
+## Typed Holes / Open Types
+
+A typed hole or open type is a pattern of data structure that generally looks
+like:
+
+```
+ { type_id, bytes_encoding_a_value_of_a_type_identified_by_type_id }
+```
+
+I.e., an opaque datum and an identifier of what kind of datum that is. This
+happens because the structure with the typed hole is used in contexts where it
+can't know all possible things that can go in it. In many cases we do know
+what all possible things are that can go in a typed hole, but many years ago
+didn't, say, or anyways, had a reason to use a typed hole.
+
+These are used not only in protocols that use ASN.1, but in many protocols that
+use syntaxes and encodings unrelated to ASN.1. I.e., these concepts are *not*
+ASN.1-specific.
+
+Many Internet protocols use typed holes, and many use typed holes in ASN.1
+types. For example, PKIX, Kerberos, LDAP, and others, use ASN.1 and typed
+holes.
+
+For examples of an Internet protocol that does not use ASN.1 but which still
+has typed holes, see IP, MIME, SSHv2, IKEv2, and others. Most quintessentilly,
+IP itself, since IP packet payloads are for some upper layer protocol
+identified in the IP packet header.
+
+In ASN.1 these generally look like:
+
+```ASN.1
+ TypedHole ::= SEQUENCE {
+ typeId INTEGER,
+ opaque OCTET STRING
+ }
+```
+
+or
+
+```ASN.1
+ -- Old ASN.1 style
+ TypedHole ::= SEQUENCE {
+ typeId OBJECT IDENTIFIER,
+ opaque ANY DEFINED BY typeID
+ }
+```
+
+or
+
+```ASN.1
+ -- Old ASN.1 style
+ TypedHole ::= SEQUENCE {
+ typeId OBJECT IDENTIFIER,
+ opaque ANY -- DEFINED BY typeID
+ }
+```
+
+or any number of variations.
+
+ Note: the `ANY` variations are no longer conformant to X.680 (the base
+ ASN.1 specification).
+
+The pattern is `{ id, hole }` where the `hole` is ultimately an opaque sequence
+of bytes whose content's schema is identified by the `id` in the same data
+structure. The pattern does not require just two fields, and it does not
+require any particular type for the hole, nor for the type ID. Sometimes the
+"hole" is an `OCTET STRING`, sometimes it's a `BIT STRING`, sometimes it's an
+`ANY` or `ANY DEFINED BY`. Sometimes the hole is even an array of (`SET OF` or
+`SEQUENCE OF`, in ASN.1) values of the type identified by the id field.
+
+An example from PKIX:
+
+```ASN.1
+Extension ::= SEQUENCE {
+ extnID OBJECT IDENTIFIER, -- <- type ID
+ critical BOOLEAN OPTIONAL,
+ extnValue OCTET STRING, -- <- hole
+}
+```
+
+which shows that typed holes don't always have just three fields, and the type
+identifier isn't always an integer.
+
+Now, Heimdal's ASN.1 compiler generates the obvious C data structure for PKIX's
+`Extension` type:
+
+```C
+ typedef struct Extension {
+ heim_oid extnID;
+ int *critical;
+ heim_octet_string extnValue;
+ } Extension;
+```
+
+and applications using this compiler have to inspect the `extnID` field,
+comparing it to any number of OIDs, to determine the type of `extnValue`, then
+must call `decode_ThatType()` to decode whatever that octet string has.
+
+This is very inconvenient.
+
+Compare this to the handling of discriminated unions (what ASN.1 calls a
+`CHOICE`):
+
+```C
+ /*
+ * ASN.1 definition:
+ *
+ * DistributionPointName ::= CHOICE {
+ * fullName [0] IMPLICIT SEQUENCE OF GeneralName,
+ * nameRelativeToCRLIssuer [1] RelativeDistinguishedName,
+ * }
+ */
+
+ /* C equivalent */
+ typedef struct DistributionPointName {
+ enum DistributionPointName_enum {
+ choice_DistributionPointName_fullName = 1,
+ choice_DistributionPointName_nameRelativeToCRLIssuer
+ } element;
+ union {
+ struct DistributionPointName_fullName {
+ unsigned int len;
+ GeneralName *val;
+ } fullName;
+ RelativeDistinguishedName nameRelativeToCRLIssuer;
+ } u;
+ } DistributionPointName;
+```
+
+The ASN.1 encoding on the wire of a `CHOICE` value, almost no matter the
+encoding rules, looks... remarkably like the encoding of a typed hole. Though
+generally the alternatives of a discriminated union have to all be encoded with
+the same encoding rules, whereas with typed holes the encoded data could be
+encoded in radically different encoding rules than the structure containing it
+in a typed hole.
+
+In fact, extensible `CHOICE`s are handled by our compiler as a discriminated
+union one of whose alternatives is a typed hole when the `CHOICE` is
+extensible:
+
+```C
+ typedef struct DigestRepInner {
+ enum DigestRepInner_enum {
+ choice_DigestRepInner_asn1_ellipsis = 0, /* <--- unknown CHOICE arm */
+ choice_DigestRepInner_error,
+ choice_DigestRepInner_initReply,
+ choice_DigestRepInner_response,
+ choice_DigestRepInner_ntlmInitReply,
+ choice_DigestRepInner_ntlmResponse,
+ choice_DigestRepInner_supportedMechs
+ /* ... */
+ } element;
+ union {
+ DigestError error;
+ DigestInitReply initReply;
+ DigestResponse response;
+ NTLMInitReply ntlmInitReply;
+ NTLMResponse ntlmResponse;
+ DigestTypes supportedMechs;
+ heim_octet_string asn1_ellipsis; /* <--- unknown CHOICE arm */
+ } u;
+ } DigestRepInner;
+```
+
+The critical thing to understand is that our compiler automatically decodes
+(and encodes) `CHOICE`s' alternatives, but it used to NOT do that for typed
+holes because it knows nothing about them. Now, however, our compiler can
+do this for typed holes provided the module specifies what the alternatives
+are.
+
+It would be nice if we could treat *all* typed holes like `CHOICE`s whenever
+the compiler knows the alternatives!
+
+And that's exactly what the ASN.1 IOS system makes possible. With ASN.1 IOS
+support, our compiler can automatically decode all the `Certificate`
+extensions, and all the distinguished name extensions it knows about.
+
+There is a fair bit of code in `lib/hx509/` that deals with encoding and
+decoding things in typed holes where the compiler could just handle that
+automatically for us, allowing us to delete a lot of code.
+
+Even more importantly, if we ever add support for visual encoding rules of
+ASN.1, such as JSON Encoding Rules (JER) [X.697] or Generic String Encoding
+Rules (GSER) [RFC2641], we could have a utility program to automatically
+display or compile DER (and other encodings) of certifcates and many other
+interesting data structures.
+
+Indeed, we do now have such a utility (`asn1_print`), able to transcode DER to
+JSON.
+
+## ASN.1 IOS, Constraint, and Parameterization
+
+The ASN.1 IOS is additional syntax that allows ASN.1 module authors to express
+all the details about typed holes that ASN.1 compilers need to make developers'
+lives much easier.
+
+RFC5912 has lots of examples, such as this `CLASS` corresponding to the
+`Extension` type from PKIX:
+
+```ASN.1
+ -- A class that provides some of the details of the PKIX Extension typed
+ -- hole:
+ EXTENSION ::= CLASS {
+ -- The following are fields of a class (as opposed to "members" of
+ -- SEQUENCE or SET types):
+ &id OBJECT IDENTIFIER UNIQUE, -- This is a fixed-type value field.
+ -- UNIQUE -> There can be only one
+ -- object with this OID
+ -- in any object set of
+ -- this class.
+ -- I.e., this is like a
+ -- PRIMARY KEY in a SQL
+ -- TABLE spec.
+ &ExtnType, -- This is a type field (the hole).
+ &Critical BOOLEAN DEFAULT {TRUE | FALSE } -- fixed-type value set field.
+ } WITH SYNTAX {
+ -- This is a specification of easy to use (but hard-to-parse) syntax for
+ -- specifying instances of this CLASS:
+ SYNTAX &ExtnType IDENTIFIED BY &id
+ [CRITICALITY &Critical]
+ }
+
+ -- Here's a parameterized Extension type. The formal parameter is an as-yet
+ -- unspecified set of valid things this hole can carry for some particular
+ -- instance of this type. The actual parameter will be specified later (see
+ -- below).
+ Extension{EXTENSION:ExtensionSet} ::= SEQUENCE {
+ -- The type ID has to be the &id field of the EXTENSION CLASS of the
+ -- ExtensionSet object set parameter.
+ extnID EXTENSION.&id({ExtensionSet}),
+ -- This is the critical field, whose DEFAULT value should be that of
+ -- the &Critical field of the EXTENSION CLASS of the ExtensionSet object
+ -- set parameter.
+ critical BOOLEAN
+ -- (EXTENSION.&Critical({ExtensionSet}{@extnID}))
+ DEFAULT FALSE,
+ -- Finally, the hole is an OCTET STRING constrained to hold the encoding
+ -- of the type named by the &ExtnType field of the EXTENSION CLASS of the
+ -- ExtensionSet object set parameter.
+ --
+ -- Note that for all members of this SEQUENCE, the fields of the object
+ -- referenced must be of the same object in the ExtensionSet object set
+ -- parameter. That's how we get to say that some OID implies some type
+ -- for the hole.
+ extnValue OCTET STRING (CONTAINING
+ EXTENSION.&ExtnType({ExtensionSet}{@extnID}))
+ -- contains the DER encoding of the ASN.1 value
+ -- corresponding to the extension type identified
+ -- by extnID
+ }
+
+ -- This is just a SEQUENCE of Extensions, the parameterized version.
+ Extensions{EXTENSION:ExtensionSet} ::=
+ SEQUENCE SIZE (1..MAX) OF Extension{{ExtensionSet}}
+```
+
+and these uses of it in RFC5280 (PKIX base) where the actual parameter is
+given:
+
+```ASN.1
+ -- Here we have an individual "object" specifying that the OID
+ -- id-ce-authorityKeyIdentifier implies AuthorityKeyIdentifier as the hole
+ -- type:
+ ext-AuthorityKeyIdentifier EXTENSION ::= { SYNTAX
+ AuthorityKeyIdentifier IDENTIFIED BY
+ id-ce-authorityKeyIdentifier }
+
+ -- And here's the OID, for completeness:
+ id-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 35 }
+ ...
+
+ -- And Here's an object set for the EXTENSION CLASS collecting a bunch of
+ -- related extensions (here they are the extensions that certificates can
+ -- carry in their extensions member):
+ CertExtensions EXTENSION ::= {
+ ext-AuthorityKeyIdentifier | ext-SubjectKeyIdentifier |
+ ext-KeyUsage | ext-PrivateKeyUsagePeriod |
+ ext-CertificatePolicies | ext-PolicyMappings |
+ ext-SubjectAltName | ext-IssuerAltName |
+ ext-SubjectDirectoryAttributes |
+ ext-BasicConstraints | ext-NameConstraints |
+ ext-PolicyConstraints | ext-ExtKeyUsage |
+ ext-CRLDistributionPoints | ext-InhibitAnyPolicy |
+ ext-FreshestCRL | ext-AuthorityInfoAccess |
+ ext-SubjectInfoAccessSyntax, ... }
+ ...
+
+ -- Lastly, we have a Certificate, and the place where the Extensions type's
+ -- actual parameter is specified.
+ --
+ -- This is where the rubber meets the road:
+
+ Certificate ::= SIGNED{TBSCertificate}
+
+ TBSCertificate ::= SEQUENCE {
+ version [0] Version DEFAULT v1,
+ serialNumber CertificateSerialNumber,
+ signature AlgorithmIdentifier{SIGNATURE-ALGORITHM,
+ {SignatureAlgorithms}},
+ issuer Name,
+ validity Validity,
+ subject Name,
+ subjectPublicKeyInfo SubjectPublicKeyInfo,
+ ... ,
+ [[2: -- If present, version MUST be v2
+ issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
+ subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL
+ ]],
+ [[3: -- If present, version MUST be v3 --
+ extensions [3] Extensions{{CertExtensions}} OPTIONAL
+ -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ -- The rubber meets the road *here*.
+ --
+ -- This says that the set of *known* certificate
+ -- extensions are those for which there are "objects"
+ -- in the "object set" named CertExtensions.
+ ]], ... }
+```
+
+Notice that the `extensions` field of `TBSCertificate` is of type `Extensions`
+parametrized by the `CertExtensions` "information object set".
+
+This allows the compiler to know that if any of the OIDs listed in the
+`CertExtensions` object set appear as the actual value of the `extnID` member
+of an `Extension` value, then the `extnValue` member of the same `Extension`
+value must be an instance of the type associated with that OID. For example,
+an `Extension` with `extnID` value of `id-ce-authorityKeyIdentifier` must have
+an `extnValue` of type `AuthorityKeyIdentifier`.
+
+
+### IOS Crash Course
+
+The ASN.1 IOS may be... a bit difficult to understand -- the syntax isn't
+pretty. And X.681 has a lot of strange terminology, like "variable type value
+set field".
+
+An IOS "class" has fields, and those fields are of kind
+`[Fixed]Type[Value[Set]]` or `Object[Set]`. Then there's "objects" and "object
+sets". Hopefully this section will make all of that comprehensible.
+
+_Classes_ have fields of various kinds. More on this below.
+
+_Classes_ can also have zero, one, or more _object sets_ associated with them,
+and each object set has zero, one, or more _objects_ that are also themselves
+associated with classes. Each object has a setting for each required field of
+a class, and possibly also for optional/defaulted fields as well.
+
+As X.681 explains, IOS object sets really are akin to relational database
+tables, while objects are akin to rows of the same, with columns specified by
+classes.
+
+Or one can think of _classes_ as relational tables with one predefined column
+naming object sets, and rows being objects grouped into object sets by that
+column. IOS supports complex path expressions across these objects (but we
+won't need to support that yet).
+
+These relational entities are immutable in that they are defined in ASN.1
+modules that are compiled and there is no way to change them at run-time, only
+query them (although perhaps object sets marked as extensible are intended to
+be extensible at run-time?). To mutate them one must edit the ASN.1 module
+that defines them and recompile it. IOS entities also have no on-the-wire
+representation.
+
+So far, the IOS seems just so useless to us: we have some, but non-urgent need
+to specify immutable relational data. For example, cryptosystem parameters,
+which PKIX does define using IOS, but again: not urgent.
+
+The magic for us lies in being able to document and constrain actual datatypes
+using the IOS [X.681], constraint specification [X.682], and type
+parameterization [X.683]. We can express the following things:
+
+ - that some _member_ of a `SET` or `SEQUENCE` is of open type
+
+ - that some _member_ of a `SET` or `SEQUENCE` identifies a type encoded into
+ an open type member of the same (or related) `SET` or `SEQUENCE`
+
+ - what pairs of `{type ID value, type}` are allowed for some `SET`'s or
+ `SEQUENCE`'s open type members
+
+With this our ASN.1 compiler has the metadata it needs in order to
+auto-generate decoding and encoding of values of open types.
+
+A termnology point: `CHOICE`, `SET`, and `SEQUENCE` types have "members", but
+_classes_ and _objects_ have "fields", and _object sets_ have "elements".
+
+Objects must have "_settings_" for all the required fields of the object's
+class and none, some, or all of the `OPTIONAL` or `DEFAULT` fields of the
+class. This is very similar to `SET`/`SEQUENCE` members, which can be
+`OPTIONAL` or `DEFAULT`ed.
+
+The _members_ (we call them fields in C, instance variables in C++, Java, ...)
+of a `SET` or `SEQUENCE` type are typed, just as in C, C++, Java, etc. for
+struct or object types.
+
+There are several kinds of fields of classes. These can be confusing, so it is
+useful that we explain them by reference to how they relate to the members of
+`SEQUENCE` types constrained by object sets:
+
+ - A `type field` of a class is one that specifies a `SET` or `SEQUENCE` member
+ of unknown (i.e., open) type.
+
+ The type of that `SET` or `SEQUENCE` member will not be not truly unknown,
+ but determined by some other member of the SET or SEQUENCE, and that will be
+ specified in a "value field" (or "value set" field) an "object" in an
+ "object set" of that class.
+
+ This is essentially a "type variable", akin to those seen in high-level
+ languages like Haskell.
+
+ - A `fixed type value field` of a class is one that specifies a SET or
+ SEQUENCE member of fixed type. Being of fixed-type, this is not a type
+ variable, naturally.
+
+ - A `fixed type value set field` of a class is like a `fixed type value
+ field`, but where object sets should provide a set of values with which to
+ constrain `SET`/`SEQUENCE` members corresponding to the field.
+
+ - A `variable type value [set] field` is one where the type of the `SET` or
+ `SEQUENCE` member corresponding to the field will vary according to some
+ specified `type field` of the same class.
+
+ - An `object field` will be a field that names another class (possibly the
+ same class), which can be used to provide rich hierarchical type semantics
+ that... we mostly don't need for now.
+
+ These define relations between classes, much like `FOREIGN KEY`s in SQL.
+
+ These are also known as `link fields`.
+
+ - Similarly for `object set field`s.
+
+As usual for ASN.1, the case of the first letter of a field name is meaningful:
+
+ - value and object field names start with a lower case letter;
+ - type, value set, and object set fields start with an upper-case letter.
+
+The form of a `fixed type value` field and a `fixed type value set` field is
+the same, differing only the case of the first letter of the field name.
+Similarly for `variable type value` and `variable type value set` fields.
+Similarly, again, for `object` and `object set` fields.
+
+Here's a simple example from PKIX:
+
+```ASN.1
+ -- An IOS class used to impose constraints on the PKIX Extension type:
+ EXTENSION ::= CLASS {
+ &id OBJECT IDENTIFIER UNIQUE,
+ &ExtnType,
+ &Critical BOOLEAN DEFAULT {TRUE | FALSE }
+ } WITH SYNTAX {
+ SYNTAX &ExtnType IDENTIFIED BY &id
+ [CRITICALITY &Critical]
+ }
+```
+
+ - The `&id` field of `EXTENSION` is a fixed-type value field. It's not a
+ fixed-type value _set_ field because its identifier (`id`) starts with a
+ lower-case letter.
+
+ The `&id` field is intended to make the `extnId` member of the `Extension`
+ `SEQUENCE` type name identify the actual type of the `extnValue` member of
+ the same `SEQUENCE` type.
+
+ Note that `UNIQUE` keyword tells us there can be only one object with any
+ given value of this field in any object set of this class. (There is no way
+ to specify the equivalent of a multi-column `PRIMARY KEY` from SQL, only
+ single-column primary/unique keys. Note that the `&id` field is not marked
+ `OPTIONAL` or `DEFAULT`, which is like saying it's `NOT NULL` in SQL.)
+
+ - The `&ExtnType` field is a type field. We can tell because no type is named
+ in its declaration!
+
+ - The `&Critical` field is a fixed-type value set field. We can tell because
+ it specifies a type (`BOOLEAN`) and starts with an upper-case letter.
+
+ In-tree we could avoid having to implement fixed-type value set fields by
+ renaming this one to `&critical` and eliding its `DEFAULT <ValueSet>` given
+ that we know there are only two possible values for a `BOOLEAN` field.
+
+ - Ignore the `WITH SYNTAX` clause for now. All it does is specify a
+ user-friendly but implementor-hostile syntax for specifying objects.
+
+Note that none of the `Extension` extensions in PKIX actually specify
+`CRITICALITY`/`&Critical`, so... we just don't need fixed-type value set
+fields. We could elide the `&Critical` field of the `EXTENSION` class
+altogether.
+
+Here's another, much more complex example from PKIX:
+
+```ASN.1
+ ATTRIBUTE ::= CLASS {
+ &id OBJECT IDENTIFIER UNIQUE,
+ &Type OPTIONAL,
+ &equality-match MATCHING-RULE OPTIONAL,
+ &minCount INTEGER DEFAULT 1,
+ &maxCount INTEGER OPTIONAL
+ }
+ MATCHING-RULE ::= CLASS {
+ &ParentMatchingRules MATCHING-RULE OPTIONAL,
+ &AssertionType OPTIONAL,
+ &uniqueMatchIndicator ATTRIBUTE OPTIONAL,
+ &id OBJECT IDENTIFIER UNIQUE
+ }
+```
+
+ - For `ATTRIBUTE` the fields are:
+ - The `&id` field is a fixed-type value field (intended to name the type of
+ members linked to the `&Type` field).
+ - The `&Type` field is a type field (open type).
+ - The `&equality-match` is an object field linking to object sets of the
+ `MATCHING-RULE` class.
+ - The `minCount` and `maxCount` fields are fixed-type value fields.
+ - For `MATCHING-RULE` the fields are:
+ - The `&ParentMatchingRules` is an object set field linking to more
+ `MATCHING-RULE`s.
+ - The `&AssertionType` field is a type field (open type).
+ - The `&uniqueMatchIndicator` field is an object field linking back to some
+ object of the `ATTRIBUTE` class that indicates whether the match is
+ unique (presumably).
+ - The `&id` field is a fixed-type value field (intended to name the type of
+ members linked to the `&AssertionType` field).
+
+No `Attribute`s in PKIX (at least RFC 5912) specify matching rules, so we
+really don't need support for object nor object set fields.
+
+Because
+ - no objects in object sets of `EXTENSION` in PKIX specify "criticality",
+ - and no objects in object sets of `ATTRIBUTE` in PKIX specify matching rules,
+ - and no matching rules are specified in PKIX (or maybe just one),
+we can drop `MATCHING-RULE` and simplify `ATTRIBUTE` and `EXTENSION` as:
+
+```ASN.1
+ EXTENSION ::= CLASS {
+ &id OBJECT IDENTIFIER UNIQUE,
+ &ExtnType
+ }
+ ATTRIBUTE ::= CLASS {
+ &id OBJECT IDENTIFIER UNIQUE,
+ &Type OPTIONAL,
+ &minCount INTEGER DEFAULT 1,
+ &maxCount INTEGER OPTIONAL
+ }
+```
+
+X.681 has an example in appendix D.2 that has at least one field of every kind.
+
+Again, the rubber that are IOS classes and object sets meet the road when
+defining types:
+
+```ASN.1
+ -- Define the Extension type but link it to the EXTENSION class so that
+ -- an object set for that class can constrain it:
+ Extension{EXTENSION:ExtensionSet} ::= SEQUENCE {
+ extnID EXTENSION.&id({ExtensionSet}),
+ critical BOOLEAN
+ (EXTENSION.&Critical({ExtensionSet}{@extnID}))
+ DEFAULT FALSE,
+ extnValue OCTET STRING (CONTAINING
+ EXTENSION.&ExtnType({ExtensionSet}{@extnID}))
+ }
+ -- Most members of TBSCertificate elided for brevity:
+ TBSCertificate ::= SEQUENCE {
+ ...,
+ extensions [3] Extensions{{CertExtensions}} OPTIONAL
+ -- ^^^^^^^^^^^^^^^^
+ -- the rubber meets the road here!!
+ ...
+ }
+
+ OTHER-NAME ::= TYPE-IDENTIFIER
+ -- Most members of GeneralName elided for brevity:
+ GeneralName ::= CHOICE {
+ otherName [0] INSTANCE OF OTHER-NAME({KnownOtherNames}),
+ -- ^^^^^^^^^^^^^^^^^
+ -- rubber & road meet!
+ ...
+ }
+```
+
+(The `CertExtensions` and `KnownOtherNames` object sets are not shown here for
+brevity. PKIX doesn't even define an `KnownOtherNames` object set, though it
+well could.)
+
+The above demonstrates two ways to create `SEQUENCE` types that are constrained
+by IOS classes. One is by defining the types of the members of a `SEQUENCE`
+type by reference to class fields. The other is by using `INSTANCE OF` to say
+that the class defines the type directly. The first lets us do things like
+have a mix members of a `SEQUENCE` type where some are defined by relation to a
+class and others are not, or where multiple classes are used.
+
+In the case of `INSTANCE OF`, what shall the names of the members of the
+derived type be? Well, such types can _only_ be instances of `TYPE-IDENTIFIER`
+or classes copied from and isomorphic to it (as `OTHER-NAME` is in the above
+exammle), and so the names of their two members are just baked in by X.681
+annex C.1 as:
+
+```ASN.1
+ SEQUENCE {
+ type-id <DefinedObjectClass>.&id,
+ value[0] <DefinedObjectClass>.&Type
+ }
+ -- where <DefinedObjectClass> is the name of the class, which has to be
+ -- `TYPE-IDENTIFIER` or exactly like it.
+```
+
+(This means we can't use `INSTANCE OF` with `EXTENSION`, though we can for
+`OTHER-NAME`.)
+
+PKIX has much more complex classes for relating and constraining cryptographic
+algorithms and their parameters:
+
+ - `DIGEST-ALGORITHM`,
+ - `SIGNATURE-ALGORITHM`,
+ - `PUBLIC-KEY`,
+ - `KEY-TRANSPORT`,
+ - `KEY-AGREE`,
+ - `KEY-WRAP`,
+ - `KEY-DERIVATION`,
+ - `MAC-ALGORITHM`,
+ - `CONTENT-ENCRYPTION`,
+ - `ALGORITHM`,
+ - `SMIME-CAPS`,
+ - and `CURVE`.
+
+These show the value of just the relational data aspect of IOS. They can not
+only be used by the codecs at run-time to perform validation of, e.g.,
+cryptographic algorithm parameters, but also to provide those rules to other
+code in the application so that the programmer doesn't have to manually write
+the same in C, C++, Java, etc, and can refer to them when applying those
+cryptographic algorithms. And, of course, the object sets for the above
+classes can be and are specified in standards documents, making it very easy to
+import them into projects that have an IOS-capable ASN.1 compiler.
+
+Still, for Heimdal we won't bother with the full power of X.681/X.682/X.683 for
+now.
+
+## Usage
+
+To use this feature you must use the `--template` and `--one-code-file`
+arguments to `asn1_compile`. C types are generated from ASN.1 types as
+described above.
+
+Note that failure to decode open type values does not cause decoding to fail
+altogether. It is important that applications check for undecoded open types.
+Open type decoding failures manifest as `NULL` values for the `u` field of the
+decoded open type structures (see above).
+
+For examples of X.681/X.682/X.683 usage, look at `lib/asn1/rfc2459.asn1`.
+
+## Limitations
+
+ - `AtNotation` supported is very limited.
+
+ - Object set extensibility is not supported.
+
+ - Only one formal (and actual) type parameter is supported at this time.
+
+ - `TYPE-IDENTIFIER` is not built-in at this time. (But users can define it as
+ specified.)
+
+ - `CLASS` "copying" is not supported at this time.
+
+ - Link fields are not supported.
+
+ - `Information from objects` constructs are not supported.
+
+ - `IMPORTS` of IOS entities are not supported at this time.
+
+ - ...
+
+## Implementation Design
+
+NOTE: This has already be implemented in the `master` branch of Heimdal.
+
+ - The required specifications, X.681, X.682, and X.683, are fairly large and
+ non-trivial. We can implement just the subset of those three that we need
+ to implement PKIX, just as we already implement just the subset of X.680
+ that we need to implement PKIX and Kerberos.
+
+ For dealing with PKIX, the bare minimum of IOS classes we want are:
+
+ - `ATTRIBUTE` (used for `DN` attributes in RFC5280, specifically for the
+ `SingleAttribute` and `AttributeSet` types, RDNs, and the
+ `subjectDirectoryAttributes` extension)
+ - `EXTENSION` (used for `Extension`, i.e., certificate extensions in
+ RFC5280)
+ - `TYPE-IDENTIFIER` (used for `OtherName` and for CMS' `Content-Type`)
+
+ The minimal subset of X.681, X.682, and X.683 needed to implement those
+ three is all we need.
+
+ _Eventually_ we may want to increase that subset so as to implement other
+ IOS classes from PKIX, such as `DIGEST-ALGORITHM`, and to provide object
+ sets and query functionality for them to applications so that we can use
+ standard modules to encode information about cryptosystems. But not right
+ now.
+
+ Note that there's no object set specified for OTHER-NAME instances, but we
+ can and have creates our own. We want magic open type decoding to recurse
+ all the way down and handle DN attributes, extensions, SANs, policy
+ qualifiers, the works.
+
+ - We'll really want to do this mainly for the template compiler and begin
+ abandoning the original compiler. The codegen backend generates the same C
+ types, but no code for automatic, recursive handling of open types.
+
+ Maintaining two compiler backends is difficult enough; adding complex
+ features beyond X.680 to both is too much work. The template compiler is
+ simply superior just on account of its output size scaling as `O(N)` instead
+ of `O(M * N)` where `M` is the number of encoding rules supported and `N` is
+ the size of an ASN.1 module (or all modules).
+
+ - Also, to make the transition to using IOS in-tree, we'll want to keep
+ existing fields of C structures as generated by the compiler today, only
+ adding new ones, that way code that hasn't been updated to use the automatic
+ encoding/decoding can still work and we can then update Heimdal in-tree
+ slowly to take advantage of the new magic.
+
+ Below are the C types for the ASN.1 PKIX types we care about, as generated
+ by the current prototype.
+
+ `Extension` compiles to:
+
+```C
+typedef struct Extension {
+ heim_oid extnID;
+ int critical;
+ heim_octet_string extnValue;
+ /* NEW: */
+ struct {
+ enum {
+ choice_Extension_iosnumunknown = 0,
+ choice_Extension_iosnum_id_x509_ce_authorityKeyIdentifier,
+ choice_Extension_iosnum_id_x509_ce_subjectKeyIdentifier,
+ choice_Extension_iosnum_id_x509_ce_keyUsage,
+ choice_Extension_iosnum_id_x509_ce_privateKeyUsagePeriod,
+ choice_Extension_iosnum_id_x509_ce_certificatePolicies,
+ choice_Extension_iosnum_id_x509_ce_policyMappings,
+ choice_Extension_iosnum_id_x509_ce_subjectAltName,
+ choice_Extension_iosnum_id_x509_ce_issuerAltName,
+ choice_Extension_iosnum_id_x509_ce_basicConstraints,
+ choice_Extension_iosnum_id_x509_ce_nameConstraints,
+ choice_Extension_iosnum_id_x509_ce_policyConstraints,
+ choice_Extension_iosnum_id_x509_ce_extKeyUsage,
+ choice_Extension_iosnum_id_x509_ce_cRLDistributionPoints,
+ choice_Extension_iosnum_id_x509_ce_inhibitAnyPolicy,
+ choice_Extension_iosnum_id_x509_ce_freshestCRL,
+ choice_Extension_iosnum_id_pkix_pe_authorityInfoAccess,
+ choice_Extension_iosnum_id_pkix_pe_subjectInfoAccess,
+ } element;
+ union {
+ void *_any;
+ AuthorityKeyIdentifier* ext_AuthorityKeyIdentifier;
+ SubjectKeyIdentifier* ext_SubjectKeyIdentifier;
+ KeyUsage* ext_KeyUsage;
+ PrivateKeyUsagePeriod* ext_PrivateKeyUsagePeriod;
+ CertificatePolicies* ext_CertificatePolicies;
+ PolicyMappings* ext_PolicyMappings;
+ GeneralNames* ext_SubjectAltName;
+ GeneralNames* ext_IssuerAltName;
+ BasicConstraints* ext_BasicConstraints;
+ NameConstraints* ext_NameConstraints;
+ PolicyConstraints* ext_PolicyConstraints;
+ ExtKeyUsage* ext_ExtKeyUsage;
+ CRLDistributionPoints* ext_CRLDistributionPoints;
+ SkipCerts* ext_InhibitAnyPolicy;
+ CRLDistributionPoints* ext_FreshestCRL;
+ AuthorityInfoAccessSyntax* ext_AuthorityInfoAccess;
+ SubjectInfoAccessSyntax* ext_SubjectInfoAccessSyntax;
+ } u;
+ } _ioschoice_extnValue;
+} Extension;
+```
+
+ The `SingleAttribute` and `AttributeSet` types compile to:
+
+```C
+typedef struct SingleAttribute {
+ heim_oid type;
+ HEIM_ANY value;
+ struct {
+ enum {
+ choice_SingleAttribute_iosnumunknown = 0,
+ choice_SingleAttribute_iosnum_id_at_name,
+ choice_SingleAttribute_iosnum_id_at_surname,
+ choice_SingleAttribute_iosnum_id_at_givenName,
+ choice_SingleAttribute_iosnum_id_at_initials,
+ choice_SingleAttribute_iosnum_id_at_generationQualifier,
+ choice_SingleAttribute_iosnum_id_at_commonName,
+ choice_SingleAttribute_iosnum_id_at_localityName,
+ choice_SingleAttribute_iosnum_id_at_stateOrProvinceName,
+ choice_SingleAttribute_iosnum_id_at_organizationName,
+ choice_SingleAttribute_iosnum_id_at_organizationalUnitName,
+ choice_SingleAttribute_iosnum_id_at_title,
+ choice_SingleAttribute_iosnum_id_at_dnQualifier,
+ choice_SingleAttribute_iosnum_id_at_countryName,
+ choice_SingleAttribute_iosnum_id_at_serialNumber,
+ choice_SingleAttribute_iosnum_id_at_pseudonym,
+ choice_SingleAttribute_iosnum_id_domainComponent,
+ choice_SingleAttribute_iosnum_id_at_emailAddress,
+ } element;
+ union {
+ void *_any;
+ X520name* at_name;
+ X520name* at_surname;
+ X520name* at_givenName;
+ X520name* at_initials;
+ X520name* at_generationQualifier;
+ X520CommonName* at_x520CommonName;
+ X520LocalityName* at_x520LocalityName;
+ DirectoryString* at_x520StateOrProvinceName;
+ DirectoryString* at_x520OrganizationName;
+ DirectoryString* at_x520OrganizationalUnitName;
+ DirectoryString* at_x520Title;
+ heim_printable_string* at_x520dnQualifier;
+ heim_printable_string* at_x520countryName;
+ heim_printable_string* at_x520SerialNumber;
+ DirectoryString* at_x520Pseudonym;
+ heim_ia5_string* at_domainComponent;
+ heim_ia5_string* at_emailAddress;
+ } u;
+ } _ioschoice_value;
+} SingleAttribute;
+```
+
+ and
+
+```C
+typedef struct AttributeSet {
+ heim_oid type;
+ struct AttributeSet_values
+ {
+ unsigned int len;
+ HEIM_ANY* val;
+ } values;
+ struct {
+ enum {
+ choice_AttributeSet_iosnumunknown = 0,
+ choice_AttributeSet_iosnum_id_at_name,
+ choice_AttributeSet_iosnum_id_at_surname,
+ choice_AttributeSet_iosnum_id_at_givenName,
+ choice_AttributeSet_iosnum_id_at_initials,
+ choice_AttributeSet_iosnum_id_at_generationQualifier,
+ choice_AttributeSet_iosnum_id_at_commonName,
+ choice_AttributeSet_iosnum_id_at_localityName,
+ choice_AttributeSet_iosnum_id_at_stateOrProvinceName,
+ choice_AttributeSet_iosnum_id_at_organizationName,
+ choice_AttributeSet_iosnum_id_at_organizationalUnitName,
+ choice_AttributeSet_iosnum_id_at_title,
+ choice_AttributeSet_iosnum_id_at_dnQualifier,
+ choice_AttributeSet_iosnum_id_at_countryName,
+ choice_AttributeSet_iosnum_id_at_serialNumber,
+ choice_AttributeSet_iosnum_id_at_pseudonym,
+ choice_AttributeSet_iosnum_id_domainComponent,
+ choice_AttributeSet_iosnum_id_at_emailAddress,
+ } element;
+ unsigned int len;
+ union {
+ void *_any;
+ X520name* at_name;
+ X520name* at_surname;
+ X520name* at_givenName;
+ X520name* at_initials;
+ X520name* at_generationQualifier;
+ X520CommonName* at_x520CommonName;
+ X520LocalityName* at_x520LocalityName;
+ DirectoryString* at_x520StateOrProvinceName;
+ DirectoryString* at_x520OrganizationName;
+ DirectoryString* at_x520OrganizationalUnitName;
+ DirectoryString* at_x520Title;
+ heim_printable_string* at_x520dnQualifier;
+ heim_printable_string* at_x520countryName;
+ heim_printable_string* at_x520SerialNumber;
+ DirectoryString* at_x520Pseudonym;
+ heim_ia5_string* at_domainComponent;
+ heim_ia5_string* at_emailAddress;
+ } *val;
+ } _ioschoice_values;
+} AttributeSet;
+```
+
+ The `OtherName` type compiles to:
+
+```C
+typedef struct OtherName {
+ heim_oid type_id;
+ HEIM_ANY value;
+ struct {
+ enum {
+ choice_OtherName_iosnumunknown = 0,
+ choice_OtherName_iosnum_id_pkix_on_xmppAddr,
+ choice_OtherName_iosnum_id_pkix_on_dnsSRV,
+ choice_OtherName_iosnum_id_pkix_on_hardwareModuleName,
+ choice_OtherName_iosnum_id_pkix_on_permanentIdentifier,
+ choice_OtherName_iosnum_id_pkix_on_pkinit_san,
+ choice_OtherName_iosnum_id_pkix_on_pkinit_ms_san,
+ } element;
+ union {
+ void *_any;
+ heim_utf8_string* on_xmppAddr;
+ heim_ia5_string* on_dnsSRV;
+ HardwareModuleName* on_hardwareModuleName;
+ PermanentIdentifier* on_permanentIdentifier;
+ KRB5PrincipalName* on_krb5PrincipalName;
+ heim_utf8_string* on_pkinit_ms_san;
+ } u;
+ } _ioschoice_value;
+} OtherName;
+```
+
+ If a caller to `encode_Certificate()` passes a certificate object with
+ extensions with `_ioselement == choice_Extension_iosnumunknown` (or
+ whatever, for each open type), then the encoder will use the `extnID` and
+ `extnValue` fields, otherwise it will use the new `_ioschoice_extnValue`
+ field and leave `extnID` and `extnValue` cleared. If both are set, the
+ `extnID` and `extnValue` fields, and also the new `_ioschoice_extnValue`
+ field, then the encoder will ignore the latter.
+
+ In both cases, the `critical` field gets used as-is. The rule is be that we
+ support *two* special C struct fields for open types: a hole type ID enum
+ field, and a decoded hole value union. All other fields will map to either
+ normal (possibly constrained) members of the SET/SEQUENCE.
+
+ - Type ID values get mapped to discrete enum values. Object sets get sorted
+ by object type IDs so that for decoding they can be and are binary-searched.
+ For encoding and other cases (destructors and copy constructors) we directly
+ index the object set by the mapped type ID enum.
+
+ - The C header generator remains shared between the two backends.
+
+ - SET and SEQUENCE types containing an open type are represented as follows in
+ their templates.
+
+```C
+ extern const struct asn1_template asn1_CertExtensions[];
+ /*...*/
+ const struct asn1_template asn1_Extension_tag__22[] = {
+ /* 0 */ { 0, sizeof(struct Extension), ((void*)5) },
+ /* 1 */ { A1_TAG_T(ASN1_C_UNIV, PRIM, UT_OID),
+ offsetof(struct Extension, extnID),
+ asn1_AttributeType_tag__1 },
+ /* 2 */ { A1_OP_DEFVAL | A1_DV_BOOLEAN, ~0, (void*)0 },
+ /* 3 */ { A1_TAG_T(ASN1_C_UNIV, PRIM, UT_Boolean) | A1_FLAG_DEFAULT,
+ offsetof(struct Extension, critical),
+ asn1_Extension_tag_critical_24 },
+ /* 4 */ { A1_TAG_T(ASN1_C_UNIV, PRIM, UT_OctetString),
+ offsetof(struct Extension, extnValue),
+ asn1_Extension_tag_extnValue_25 },
+ /* NEW: vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
+ /* 5 */ { A1_OP_OPENTYPE_OBJSET | 0 | (2 << 10) | 0,
+ offsetof(Extension, _ioschoice_extnValue),
+ asn1_CertExtensions }
+ };
+ const struct asn1_template asn1_Extension[] = {
+ /* 0 */ { 0, sizeof(Extension), ((void*)1) },
+ /* 1 */ { A1_TAG_T(ASN1_C_UNIV, CONS, UT_Sequence),
+ 0, asn1_Extension_tag__22 }
+ };
+
+ /* NEW: */
+ const struct asn1_template asn1_CertExtensions[] = {
+ /*
+ * Header template entry bearing the count of objects in
+ * this object set:
+ */
+ /* 0 */ { 0, 0, ((void*)18) },
+
+ /*
+ * Value of object #0 in this set: two entries, one naming
+ * a type ID field value, and the other naming the type
+ * that corresponds to that value.
+ *
+ * In this case, the first object is for the
+ * AuthorityKeyIdentifier type as a certificate extension.
+ */
+ /* 1 */ { A1_OP_OPENTYPE_ID, 0,
+ (const void*)&asn1_oid_id_x509_ce_authorityKeyIdentifier },
+ /* 2 */ { A1_OP_OPENTYPE, sizeof(AuthorityKeyIdentifier),
+ (const void*)&asn1_AuthorityKeyIdentifier },
+
+ /* Value of object #1 (SubjectKeyIdentifier): */
+
+ /* 3 */ { A1_OP_OPENTYPE_ID, 0,
+ (const void*)&asn1_oid_id_x509_ce_subjectKeyIdentifier },
+ /* 4 */ { A1_OP_OPENTYPE, sizeof(SubjectKeyIdentifier),
+ (const void*)&asn1_SubjectKeyIdentifier },
+ /* 5 */
+
+ /* And so on...*/
+
+ /* Value of object #17 */
+ /* 35 */ { A1_OP_OPENTYPE_ID, 0,
+ (const void*)&asn1_oid_id_pkix_pe_subjectInfoAccess },
+ /* 36 */ { A1_OP_OPENTYPE, sizeof(SubjectInfoAccessSyntax),
+ (const void*)&asn1_SubjectInfoAccessSyntax }
+ };
+```
+
+ After the template entries for all the normal fields of a struct there will
+ be an object set reference entry identifying the type ID and open type
+ fields's entries' indices in the same template. The object set has a header
+ entry followed by pairs of entries each representing a single object and all
+ of them representing the object set.
+
+ This allows the encoder and decoder to both find the object set quickly,
+ especially since the objects are sorted by type ID value.
+
+## Moving From C
+
+ - Generate and output a JSON representation of the compiled ASN.1 module.
+
+ - Code codegen/templategen backends in jq or Haskell or whatever.
+
+ - Code template interpreters in &lt;host&gt; language.
+
+ - Eventually rewrite the compiler itself in Rust or whatever.
diff --git a/third_party/heimdal/lib/asn1/README-template.md b/third_party/heimdal/lib/asn1/README-template.md
new file mode 100644
index 0000000..9f1b60f
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/README-template.md
@@ -0,0 +1,278 @@
+
+#Notes on Heimdal's ASN.1 compiler's "template" backend
+
+```bash
+size .libs/libasn1.dylib
+size .libs/libasn1base.a | awk '{sum += $1} END {print sum}' | sed 's/^/TEXT baselib: /'
+size .libs/asn1_*.o | awk '{sum += $1} END {print sum}' | sed 's/^/generated code stubs: /'
+size *_asn1-template.o | awk '{sum += $1} END {print sum}' | sed 's/^/TEXT stubs: /'
+```
+
+Notes about the template parser:
+
+ - assumption: code is large, tables smaller
+
+ - size scales better as features as added:
+
+ - adding encoding rules, textual value parsers, comparators, and so on, are
+ just new template interpreter, and generally that means no change to
+ templates.
+
+ - so template sizing scales like `O(M + N)` where `M` is the size of the
+ modules and `N` is the size of the interpreters
+
+ - but codegen sizing scales like `O(M * N)`
+
+ - as we add interpreters the size advantage of templates increases
+
+ - smaller tables and code, more memory sharing, smaller cache footprint,
+ should lead to better performance
+
+ - templates are shared for encode/decode/free/copy/print interpreters,
+ whereas none of those operations as generated by the codegen backend
+ share any code
+
+ - very compressible -- we waste a lot of space in `struct asn1_template` on
+ 64-bit systems, and still it's smaller than the code generated by the
+ codegen backend
+
+ Note that the template backend does currently dedup templates, though that
+ is a quadratic operation that we may eventually have to make optional (right
+ now it's not a problem).
+
+ If we made the `ptr` field a `uint32_t` instead of a pointer, and wrote a
+ linker for templates, and squeezed out some bits of `tt` and `offset` (we'll
+ never need even 8 bits for tags, let alone 20!, and we'll never need 32 bits
+ for struct sizes and field offsets either, maybe not even 16-bits), we could
+ cut the size of `struct asn1_template` in half.
+
+ Also, once we add OER/JER we could have an option to not support TLV ERs and
+ then drop a lot of the tag-related parts of the minified AST that templates
+ are, further shrinking the templates.
+
+ The smaller the templates, the faster interpreting will be.
+
+ - use explicit stack instead of recursion in template interpreter to reduce
+ stack use and increase speed
+
+ The code generated by the codegen backend is also recursive, though the
+ compiler could inline some calls. Using an explicit stack in an iterative
+ interpreter would likely be a big win.
+
+ - how to generate template based stubs
+
+ (Note: it's now the default for Heimdal itself.)
+
+ Use the `--template` option to `asn1_compile` to use the template backend,
+ or leave it off to use the codegen backend.
+
+ - the template backend now has more functionality than the codegen backend
+
+ - much easier to extend! adding new encoding rules is just adding a few
+ functions to template.c, one set of length/encode/decode functions per ER,
+ so we could add OER/PER/XDR/GSER/JER with very little work outside that one
+ file and `gen_template.c` (to generate stub functions and possibly slight
+ alterations to templates) and gen.c (to generate declarations of those stub
+ functions).
+
+ - template decoding has been fuzzed extensively with American Fuzzy Lop (AFL)
+
+TODO:
+
+ - Generate templates for enumerations, with their names and values, so that
+ values of enumerated types can be printed.
+
+ - Remove old fuzzer. Rely on AFL only.
+
+ - Fuzzing tests, always more fuzzing:
+
+ - Instructions:
+
+```
+ $ git clone https://github.com/heimdal/heimdal
+ $ cd heimdal
+ $ srcdir=$PWD
+ $ autoreconf -fi
+ $
+ $ mkdir build
+ $ cd build
+ $
+ $ ../configure --srcdir=$srcdir ...
+ $ make -j4
+ $
+ $ cd lib/asn1
+ $ make clean
+ $ AFL_HARDEN=1 make -j4 asn1_print check CC=afl-gcc # or CC=afl-clang
+ $
+ $ # $srcdir/lib/asn1/fuzz-inputs/ has at least one minimized DER value
+ $ # produced by taking an EK certificate and truncating the signatureValue
+ $ # and tbsCertificate.subjectPublicKeyInfo fields then re-encoding, thus
+ $ # cutting down the size of the certificate by 45%. AFL finds interesting
+ $ # code paths much faster if the input corpus is minimized.
+ $
+ $ mkdir f
+ $ ../../libtool --mode=execute afl-fuzz -i $srcdir/lib/asn1/fuzz-inputs -o $PWD/f ./asn1_print '@@' Certificate
+ $
+ $ # Or
+ $ ../../libtool --mode=execute afl-fuzz -i $srcdir/lib/asn1/fuzz-inputs -o $PWD/f ./asn1_print -A '@@'
+ $
+ $ # Examine crash reports, if any. Each crash report consists of an input
+ $ # that caused a crash, so run valgrind on each such input:
+ $
+ $ for i in f/crashes/id*; do
+ > echo $i
+ > ../../libtool --mode=execute valgrind --num-callers=64 ./asn1_print $i \
+ > Certificate IOSCertificationRequest >/dev/null 2> f/crashes/vg-${i##*/}
+ > done
+ $
+ $ # then review the valgrind output:
+ $ $PAGER f/crashes/vg-*
+```
+
+ - Here's a screenshot of AFL running on the previous commit:
+
+```
+ american fuzzy lop 2.52b (asn1_print)
+
+┌─ process timing ─────────────────────────────────────┬─ overall results ─────┐
+│ run time : 1 days, 22 hrs, 39 min, 51 sec │ cycles done : 18 │
+│ last new path : 0 days, 0 hrs, 38 min, 5 sec │ total paths : 2310 │
+│ last uniq crash : none seen yet │ uniq crashes : 0 │
+│ last uniq hang : none seen yet │ uniq hangs : 0 │
+├─ cycle progress ────────────────────┬─ map coverage ─┴───────────────────────┤
+│ now processing : 997* (43.16%) │ map density : 2.19% / 8.74% │
+│ paths timed out : 0 (0.00%) │ count coverage : 3.25 bits/tuple │
+├─ stage progress ────────────────────┼─ findings in depth ────────────────────┤
+│ now trying : interest 16/8 │ favored paths : 319 (13.81%) │
+│ stage execs : 13.1k/13.4k (98.18%) │ new edges on : 506 (21.90%) │
+│ total execs : 91.9M │ total crashes : 0 (0 unique) │
+│ exec speed : 576.2/sec │ total tmouts : 2158 (180 unique) │
+├─ fuzzing strategy yields ───────────┴───────────────┬─ path geometry ────────┤
+│ bit flips : 565/5.60M, 124/5.60M, 74/5.59M │ levels : 19 │
+│ byte flips : 4/699k, 17/375k, 15/385k │ pending : 552 │
+│ arithmetics : 323/20.7M, 8/10.6M, 1/517k │ pend fav : 0 │
+│ known ints : 85/1.76M, 148/9.98M, 175/16.8M │ own finds : 2308 │
+│ dictionary : 0/0, 0/0, 12/6.62M │ imported : n/a │
+│ havoc : 757/6.35M, 0/0 │ stability : 100.00% │
+│ trim : 14.30%/336k, 46.60% ├────────────────────────┘
+└─────────────────────────────────────────────────────┘ [cpu000:196%]
+```
+
+ - TODO: Make building with AFL a ./cofigure option.
+
+ - TODO: Make fuzzing with AFL a make target.
+
+ - Fuzz decode round-tripping (don't just decode, but also encoded the
+ decoded).
+
+ - Performance testing
+
+ - `ASN1_MALLOC_ENCODE()` as a function, replaces `encode_` and `length_`
+
+ - Fix SIZE constraits
+
+ - Proper implementation of `SET { ... }`
+
+ - Compact types that only contain on entry to not having a header.
+
+
+SIZE - Futher down is later generations of the template parser
+
+```
+ code:
+ ==================
+ __TEXT __DATA __OBJC others dec hex
+ 462848 12288 0 323584 798720 c3000 (O2)
+
+ trivial types:
+ ==================
+ __TEXT __DATA __OBJC others dec hex
+ 446464 12288 0 323584 782336 bf000 (O2)
+
+ OPTIONAL
+ ==================
+ __TEXT __DATA __OBJC others dec hex
+ 425984 16384 0 323584 765952 bb000 (O2)
+
+ SEQ OF
+ ==================
+ __TEXT __DATA __OBJC others dec hex
+ 368640 32768 0 327680 729088 b2000 (O2)
+ 348160 32768 0 327680 708608 ad000 (Os)
+
+ BOOLEAN
+ ==================
+ 339968 32768 0 327680 700416 ab000 (Os)
+
+ TYPE_EXTERNAL:
+ ==================
+ 331776 32768 0 327680 692224 a9000 (Os)
+
+ SET OF
+ ==================
+ 327680 32768 0 327680 688128 a8000 (Os)
+
+ TYPE_EXTERNAL everywhere
+ ==================
+ __TEXT __DATA __OBJC others dec hex
+ 167936 69632 0 327680 565248 8a000 (Os)
+
+ TAG uses ->ptr (header and trailer)
+ ==================
+ 229376 102400 0 421888 753664 b8000 (O0)
+
+ TAG uses ->ptr (header only)
+ ==================
+ 221184 77824 0 421888 720896 b0000 (O0)
+
+ BER support for octet string (not working)
+ ==================
+ 180224 73728 0 417792 671744 a4000 (O2)
+
+ CHOICE and BIT STRING missign
+ ==================
+ __TEXT __DATA __OBJC others dec hex
+ 172032 73728 0 417792 663552 a2000 (Os)
+
+ No accessor functions to global variable
+ ==================
+ __TEXT __DATA __OBJC others dec hex
+ 159744 73728 0 393216 626688 99000 (Os)
+
+ All types tables (except choice) (id still objects)
+ ==================
+ __TEXT __DATA __OBJC others dec hex
+ 167936 77824 0 421888 667648 a3000
+ base lib: 22820
+
+ __TEXT __DATA __OBJC others dec hex
+ ==================
+ 167936 77824 0 421888 667648 a3000 (Os)
+ baselib: 22820
+ generated code stubs: 41472
+ TEXT stubs: 112560
+
+ All types, id still objects
+ ==================
+ __TEXT __DATA __OBJC others dec hex
+ 155648 81920 0 430080 667648 a3000 (Os)
+ TEXT baselib: 23166
+ generated code stubs: 20796
+ TEXT stubs: 119891
+
+ All types, id still objects, dup compression
+ ==================
+ __TEXT __DATA __OBJC others dec hex
+ 143360 65536 0 376832 585728 8f000 (Os)
+ TEXT baselib: 23166
+ generated code stubs: 20796
+ TEXT stubs: 107147
+
+ All types, dup compression, id vars
+ ==================
+ __TEXT __DATA __OBJC others dec hex
+ 131072 65536 0 352256 548864 86000
+ TEXT baselib: 23166
+ generated code stubs: 7536
+ TEXT stubs: 107147
+```
diff --git a/third_party/heimdal/lib/asn1/README.md b/third_party/heimdal/lib/asn1/README.md
new file mode 100644
index 0000000..9c4e697
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/README.md
@@ -0,0 +1,1327 @@
+# Heimdal's ASN.1 Compiler
+
+This is a new README, and it's not very rich in contents yet. Be sure to check
+out the [README on the template backend](/lib/asn1/README-template.md) and the [README
+on automatic open type decoding via X.681/X.682/X.683
+annotations](/lib/asn1/README-X681.md).
+
+## Table of Contents
+
+ 1. [Introduction](#Introduction)
+ 2. [ASN.1 Support in Heimdal](#asn1-support-in-heimdal)
+ 3. [News](#News)
+ 4. [Features](#Features)
+ 5. [Limitations](#Limitations)
+ 6. [Compiler Usage](#Compiler-usage)
+ 7. [APIs Generated by the Compiler](#APIs-generated-by-the-compiler)
+ 8. [`asn1_print` Usage](#asn1_print-usage)
+ 9. [Implementation](#implementation)
+ 10. [Moving From C](#moving-from-c)
+
+## Introduction
+
+ASN.1 is a... some would say baroque, perhaps obsolete, archaic even, "syntax"
+for expressing data type schemas, and also a set of "encoding rules" (ERs) that
+specify many ways to encode values of those types for interchange.
+
+Some ERs are binary, others are textual. Some binary ERs are tag-length-value
+(TLV), others have no need for tagging. Some of the ERs are roundly and
+rightly disliked, but then there are XER (XML Encoding Rules) and JER (JSON
+Encoding Rules) that really illustrate how the syntax and the encoding rules
+really are separate and distinct things.
+
+ASN.1 is a wheel that everyone loves to reinvent, and often badly. It's worth
+knowing a bit about it before reinventing this wheel badly yet again.
+
+It's also worth pondering that there appears to be ways to map most data
+exchange metaschemas and schemas onto others, and therefore too, transliterate
+most encodings onto others.
+
+First, an example of the syntax:
+
+```ASN.1
+-- This is what a certificate looks like (as in TLS server certificates, or
+-- "SSL certs):
+Certificate ::= SEQUENCE {
+ tbsCertificate TBSCertificate,
+ signatureAlgorithm AlgorithmIdentifier,
+ signatureValue BIT STRING
+}
+
+-- The main body of a certificate is here though:
+TBSCertificate ::= SEQUENCE {
+ version [0] Version DEFAULT 1,
+ serialNumber CertificateSerialNumber,
+ signature AlgorithmIdentifier,
+ issuer Name,
+ validity Validity,
+ subject Name,
+ subjectPublicKeyInfo SubjectPublicKeyInfo,
+ issuerUniqueID [1] IMPLICIT BIT STRING OPTIONAL,
+ subjectUniqueID [2] IMPLICIT BIT STRING OPTIONAL,
+ extensions [3] EXPLICIT Extensions OPTIONAL
+}
+```
+
+Here we see something akin to a "structure" or "record" with various named
+fields of various types. Some of these are optional, which means they can have
+no value given in encodings. One is defaulted, which means that if no values
+is given in encodings then the default value is intended.
+
+Those `[0]` things are called tags and are decidedly obsolete, along with all
+"tag-length-value" (TLV) or "self-describing" encoding rules. Tags appear as
+lexical tokens in ASN.1 only because a) in the early 80s TLV encodings were
+thought fantastic, and b) automatic tagging wasn't invented and implemented
+until it was too late. New ASN.1 modules should never need to have those tags
+appear in the syntax.
+
+ASN.1 has a lot of competition, and may even be obsolete. Obsolete
+technologies take decades to die out because of the need to interoperate with
+the installed base. So even if ASN.1 is obsolete, we find ourselves needing to
+implement a large subset of it in order to implement certain important network
+protocols.
+
+Encoding rules? There are many:
+
+ - JSON Encoding Rules (JER) ([X.697](https://www.itu.int/rec/T-REC-X/recommendation.asp?lang=en&parent=T-REC-X.697))
+
+ Use JSON instead of some binary scheme like DER (see below).
+
+ - XML Encoding Rules (XER) ([X.693](https://www.itu.int/rec/T-REC-X/recommendation.asp?lang=en&parent=T-REC-X.693))
+
+ - Generic String Encoding Rules (GSER) ([RFC3641](https://tools.ietf.org/html/rfc3641))
+
+ - Basic, Distinguished, and Canonical Encoding Rules (BER, DER, CER) ([X.690](https://www.itu.int/rec/T-REC-X/recommendation.asp?lang=en&parent=T-REC-X.690)
+
+ These are the dreaded tag-length-value encoding rules. They are redundant,
+ wasteful, and inefficient in spite of being non-textual (i.e., binary)!
+
+ The descriptor "tag-length-value" is due to all values being encoded as some
+ bytes for a "tag", then some bytes for the length of the encoded value, then
+ the encoded value itself. The body of a structured type (e.g.,
+ `Certificate`) is itself a concatenation of the TLV encodings of the fields
+ of that structured type, in order.
+
+ DER and CER are alternative canonical forms of BER.
+
+ - Packed Encoding Rules (PER) ([X.691](https://www.itu.int/rec/T-REC-X/recommendation.asp?lang=en&parent=T-REC-X.691)) and Octet Encoding Rules (OER) ([X.696](https://www.itu.int/rec/T-REC-X/recommendation.asp?lang=en&parent=T-REC-X.696))
+
+ These are a lot like eXternal Data Representation
+ ([XDR](https://tools.ietf.org/html/rfc4506.html)), but with 1-octet
+ alignment instead of 4-octet alignment.
+
+There is also a meta encoding rule system, the Encoding Control Notation (ECN)
+([X.692](https://www.itu.int/rec/T-REC-X/recommendation.asp?lang=en&parent=T-REC-X.692))
+intended to be able to express all sorts of kinds of encodings.
+
+Heimdal currently only supports DER for encoding, and DER and BER for decoding,
+but soon may support JER as well, and can print values as JSON, though not
+compliant with JER.
+
+The syntax itself is specified by
+[X.680](https://www.itu.int/rec/T-REC-X/recommendation.asp?lang=en&parent=T-REC-X.680),
+with extensions via
+[X.681](https://www.itu.int/rec/T-REC-X/recommendation.asp?lang=en&parent=T-REC-X.681),
+[X.682](https://www.itu.int/rec/T-REC-X/recommendation.asp?lang=en&parent=T-REC-X.682),
+and
+[X.683](https://www.itu.int/rec/T-REC-X/recommendation.asp?lang=en&parent=T-REC-X.683),.
+
+## ASN.1 Support in Heimdal
+
+Heimdal contains an implementation of:
+
+ - ASN.1
+ - PKIX
+ - Kerberos
+ - misc. Heimdal-specific protocols related to PKIX and Kerberos, such as:
+
+ - Online certification authority protocols
+ - Kerberos KDC replication protocols
+ - Kerberos administration protocols
+
+PKIX and Kerberos both require ASN.1 and DER support.
+
+For historical reasons many ASN.1-using projects have used hand-rolled codecs
+that have proven difficult to implement, maintain, and extend, and, of course,
+buggy. Heimdal has its own ASN.1 module compiler and library in order to avoid
+the pitfalls of hand-rolled codecs, and to satisfy Heimdal's internal needs.
+
+There are other ASN.1 compilers and libraries out there, of course, but it
+would prove difficult to switch compilers as generally ASN.1 compilers lack
+sufficient control over generated types and APIs for programming languages.
+
+Heimdal's ASN.1 compiler supports a large subset of X.680, X.681, X.682, and
+X.683, as well as a large subset of X.690, with an architecture that should
+make it easy to add support for encoding rules other than X.690.
+
+## News
+
+In recent times the following features have been added:
+
+ - Feature parity for the "template" backend, even superiority, as the codegen
+ backend does not yet support automatic open type decoding/encoding.
+
+ - IMPLICIT tagging support is finally complete.
+
+ - Automatic open type traversal, using a subset of X.681/X.682/X.683 for
+ expressing the requisite metadata.
+
+ - Decoration of ASN.1 types with "hidden" fields (ones that don't get encoded
+ or decoded) of ASN.1 or C types.
+
+## Futures
+
+ - JER support?
+
+ - XDR/NDR/OER support?
+
+ - Generate comparators? (lib/hx509 has a half-baked Certificate comparator)
+
+## Features
+
+ - Most of X.680 is supported.
+
+ - Most of X.690 is supported for decoding, with only DER supported for
+ encoding.
+
+ - For cryptographic applications there is a `--preserve-binary=TYPE` compiler
+ option that causes the `TYPE`'s C `struct` to gain a `_save` field where the
+ original encoding of the `TYPE` is preserved by the decoder. This allows
+ cryptographic applications to validate signatures, MACs, authenticated
+ decryption tags, checksums, etc., without having to re-encode the `TYPE`
+ (which wouldn't even work if the encoding received were BER and BER were
+ permitted for that `TYPE`).
+
+ - Unconstrained integer types have a large integer representation in C that is
+ not terribly useful in common cases. Range and member constraints on
+ integer types cause the compiler to use `int`, `int64_t`, `unsigned int`,
+ and/or `uint64_t` as appropriate.
+
+ - The Heimdal ASN.1 compiler currently handles a large subset of X.680, and
+ (in a branch) a small subset of X.681, X.682, and X.683, which manifests as
+ automatic handling of all open types contained in `SET`/`SEQUENCE` types
+ that are parameterized with information object sets. This allows all open
+ types in PKIX certificates, for example, to get decoded automatically no
+ matter how deeply nested. We use a TCG EK certificate that has eight
+ certificate extensions, including subject alternative names and subject
+ directory attributes where the attribute values are not string types, and
+ all of these things get decoded automatically.
+
+ - The template backend dedups templates to save space. This is an O(N^2) kind
+ of feature that we need to make optional, but it works. (When we implement
+ JER this will have the side-effect of printing the wrong type names in some
+ cases because two or more types have the same templates and get deduped.)
+
+ - There is an _experimental_ ASN.1 module -> JSON feature in the compiler. It
+ currently dumps type and value definitions, but not class, or object set
+ definitions. Even for types, it is not complete, and the JSON schema used
+ is subject to change *WITHOUT NOTICE*.
+
+ Perhaps eventually we can re-write the compiler as a C-coded ASN.1 -> JSON
+ stage followed by a jq-coded code and template generator state, which would
+ make it much easier to extend the compiler.
+
+ - We have an `asn1_print` program that can decode DER from any exported types
+ from any ASN.1 modules committed in Heimdal:
+
+ ```bash
+ $ ./asn1_print ek.crt Certificate |
+ jq '.tbsCertificate.extensions[3]._extnValue[]._values'
+ ```
+
+ ```JSON
+ [
+ {
+ "_type": "TPMSpecification",
+ "family": "2.0",
+ "level": 0,
+ "revision": 138
+ }
+ ]
+ [
+ {
+ "_type": "TPMSecurityAssertions",
+ "version": 0,
+ "fieldUpgradable": true,
+ "ekGenerationType": "ekgt-injected",
+ "ekGenerationLocation": "tpmManufacturer",
+ "ekCertificateGenerationLocation": "tpmManufacturer",
+ "ccInfo": {
+ "_type": "CommonCriteriaMeasures",
+ "version": "3.1",
+ "assurancelevel": "ealevel4",
+ "evaluationStatus": "evaluationCompleted",
+ "plus": true,
+ "strengthOfFunction": null,
+ "profileOid": null,
+ "profileUri": null,
+ "targetOid": null,
+ "targetUri": null
+ },
+ "fipsLevel": {
+ "_type": "FIPSLevel",
+ "version": "140-2",
+ "level": "sllevel2",
+ "plus": false
+ },
+ "iso9000Certified": false,
+ "iso9000Uri": null
+ }
+ ]
+ ```
+
+ A complete dump of such a certificate:
+
+ ```bash
+ $ ./asn1_print ek.crt Certificate | jq .
+ ```
+
+ ```JSON
+ {
+ "_type": "Certificate",
+ "tbsCertificate": {
+ "_type": "TBSCertificate",
+ "_save": "30820376A00302010202146A0597BA71D7E6D3AC0EDC9EDC95A15B998DE40A300D06092A864886F70D01010B05003055310B3009060355040613024348311E301C060355040A131553544D6963726F656C656374726F6E696373204E56312630240603550403131D53544D2054504D20454B20496E7465726D656469617465204341203035301E170D3138313231343030303030305A170D3238313231343030303030305A300030820122300D06092A864886F70D01010105000382010F003082010A0282010100CC14EB27A78CEB0EA486FA2DF7835F5FA8E905B097012B5BDE50380C355B1A2A721BBC3D08DD21796CDB239FA95310651B1B56FD2CFE53C87352EBD996E33256160404CE9302A08066801E786A2F86E181F949966F492A85B58EAA4A6A8CB3697551BB236E87CC7BF8EC1347871C91E15437E8F266BF1EA5EB271FDCF374D8B47DF8BCE89E1FAD61C2A088CB4036B359CB72A294973FEDCCF0C340AFFD14B64F041165581ACA34147C1C75617047058F7ED7D603E032508094FA73E8B9153DA3BF255D2CBBC5DF301BA8F74D198BEBCE86040FC1D2927C7657414490D802F482F3EBF2DE35EE149A1A6DE8D16891FBFBA02A18AFE59F9D6F149744E5F0D559B10203010001A38201A9308201A5301F0603551D230418301680141ADB994AB58BE57A0CC9B900E7851E1A43C0866030420603551D20043B303930370604551D2000302F302D06082B060105050702011621687474703A2F2F7777772E73742E636F6D2F54504D2F7265706F7369746F72792F30590603551D110101FF044F304DA44B304931163014060567810502010C0B69643A353335343444323031173015060567810502020C0C53543333485450484148433031163014060567810502030C0B69643A303034393030303830670603551D090460305E301706056781050210310E300C0C03322E300201000202008A304306056781050212313A30380201000101FFA0030A0101A1030A0100A2030A0100A310300E1603332E310A01040A01020101FFA40F300D16053134302D320A0102010100300E0603551D0F0101FF040403020520300C0603551D130101FF0402300030100603551D250409300706056781050801304A06082B06010505070101043E303C303A06082B06010505073002862E687474703A2F2F7365637572652E676C6F62616C7369676E2E636F6D2F73746D74706D656B696E7430352E637274",
+ "version": "rfc3280_version_3",
+ "serialNumber": "6A0597BA71D7E6D3AC0EDC9EDC95A15B998DE40A",
+ "signature": {
+ "_type": "AlgorithmIdentifier",
+ "algorithm": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "1.2.840.113549.1.1.11",
+ "components": [
+ 1,
+ 2,
+ 840,
+ 113549,
+ 1,
+ 1,
+ 11
+ ],
+ "name": "id-pkcs1-sha256WithRSAEncryption"
+ },
+ "parameters": "0500"
+ },
+ "issuer": {
+ "_choice": "rdnSequence",
+ "value": [
+ [
+ {
+ "_type": "AttributeTypeAndValue",
+ "type": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.5.4.6",
+ "components": [
+ 2,
+ 5,
+ 4,
+ 6
+ ],
+ "name": "id-at-countryName"
+ },
+ "value": {
+ "_choice": "printableString",
+ "value": "CH"
+ }
+ }
+ ],
+ [
+ {
+ "_type": "AttributeTypeAndValue",
+ "type": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.5.4.10",
+ "components": [
+ 2,
+ 5,
+ 4,
+ 10
+ ],
+ "name": "id-at-organizationName"
+ },
+ "value": {
+ "_choice": "printableString",
+ "value": "STMicroelectronics NV"
+ }
+ }
+ ],
+ [
+ {
+ "_type": "AttributeTypeAndValue",
+ "type": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.5.4.3",
+ "components": [
+ 2,
+ 5,
+ 4,
+ 3
+ ],
+ "name": "id-at-commonName"
+ },
+ "value": {
+ "_choice": "printableString",
+ "value": "STM TPM EK Intermediate CA 05"
+ }
+ }
+ ]
+ ]
+ },
+ "validity": {
+ "_type": "Validity",
+ "notBefore": {
+ "_choice": "utcTime",
+ "value": "2018-12-14T00:00:00Z"
+ },
+ "notAfter": {
+ "_choice": "utcTime",
+ "value": "2028-12-14T00:00:00Z"
+ }
+ },
+ "subject": {
+ "_choice": "rdnSequence",
+ "value": []
+ },
+ "subjectPublicKeyInfo": {
+ "_type": "SubjectPublicKeyInfo",
+ "algorithm": {
+ "_type": "AlgorithmIdentifier",
+ "algorithm": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "1.2.840.113549.1.1.1",
+ "components": [
+ 1,
+ 2,
+ 840,
+ 113549,
+ 1,
+ 1,
+ 1
+ ],
+ "name": "id-pkcs1-rsaEncryption"
+ },
+ "parameters": "0500"
+ },
+ "subjectPublicKey": "2160:3082010A0282010100CC14EB27A78CEB0EA486FA2DF7835F5FA8E905B097012B5BDE50380C355B1A2A721BBC3D08DD21796CDB239FA95310651B1B56FD2CFE53C87352EBD996E33256160404CE9302A08066801E786A2F86E181F949966F492A85B58EAA4A6A8CB3697551BB236E87CC7BF8EC1347871C91E15437E8F266BF1EA5EB271FDCF374D8B47DF8BCE89E1FAD61C2A088CB4036B359CB72A294973FEDCCF0C340AFFD14B64F041165581ACA34147C1C75617047058F7ED7D603E032508094FA73E8B9153DA3BF255D2CBBC5DF301BA8F74D198BEBCE86040FC1D2927C7657414490D802F482F3EBF2DE35EE149A1A6DE8D16891FBFBA02A18AFE59F9D6F149744E5F0D559B10203010001"
+ },
+ "issuerUniqueID": null,
+ "subjectUniqueID": null,
+ "extensions": [
+ {
+ "_type": "Extension",
+ "extnID": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.5.29.35",
+ "components": [
+ 2,
+ 5,
+ 29,
+ 35
+ ],
+ "name": "id-x509-ce-authorityKeyIdentifier"
+ },
+ "critical": false,
+ "extnValue": "301680141ADB994AB58BE57A0CC9B900E7851E1A43C08660",
+ "_extnValue_choice": "ext-AuthorityKeyIdentifier",
+ "_extnValue": {
+ "_type": "AuthorityKeyIdentifier",
+ "keyIdentifier": "1ADB994AB58BE57A0CC9B900E7851E1A43C08660",
+ "authorityCertIssuer": null,
+ "authorityCertSerialNumber": null
+ }
+ },
+ {
+ "_type": "Extension",
+ "extnID": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.5.29.32",
+ "components": [
+ 2,
+ 5,
+ 29,
+ 32
+ ],
+ "name": "id-x509-ce-certificatePolicies"
+ },
+ "critical": false,
+ "extnValue": "303930370604551D2000302F302D06082B060105050702011621687474703A2F2F7777772E73742E636F6D2F54504D2F7265706F7369746F72792F",
+ "_extnValue_choice": "ext-CertificatePolicies",
+ "_extnValue": [
+ {
+ "_type": "PolicyInformation",
+ "policyIdentifier": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.5.29.32.0",
+ "components": [
+ 2,
+ 5,
+ 29,
+ 32,
+ 0
+ ],
+ "name": "id-x509-ce-certificatePolicies-anyPolicy"
+ },
+ "policyQualifiers": [
+ {
+ "_type": "PolicyQualifierInfo",
+ "policyQualifierId": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "1.3.6.1.5.5.7.2.1",
+ "components": [
+ 1,
+ 3,
+ 6,
+ 1,
+ 5,
+ 5,
+ 7,
+ 2,
+ 1
+ ],
+ "name": "id-pkix-qt-cps"
+ },
+ "qualifier": "1621687474703A2F2F7777772E73742E636F6D2F54504D2F7265706F7369746F72792F"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "_type": "Extension",
+ "extnID": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.5.29.17",
+ "components": [
+ 2,
+ 5,
+ 29,
+ 17
+ ],
+ "name": "id-x509-ce-subjectAltName"
+ },
+ "critical": true,
+ "extnValue": "304DA44B304931163014060567810502010C0B69643A353335343444323031173015060567810502020C0C53543333485450484148433031163014060567810502030C0B69643A3030343930303038",
+ "_extnValue_choice": "ext-SubjectAltName",
+ "_extnValue": [
+ {
+ "_choice": "directoryName",
+ "value": {
+ "_choice": "rdnSequence",
+ "value": [
+ [
+ {
+ "_type": "AttributeTypeAndValue",
+ "type": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.23.133.2.1",
+ "components": [
+ 2,
+ 23,
+ 133,
+ 2,
+ 1
+ ],
+ "name": "tcg-at-tpmManufacturer"
+ },
+ "value": {
+ "_choice": "utf8String",
+ "value": "id:53544D20"
+ }
+ }
+ ],
+ [
+ {
+ "_type": "AttributeTypeAndValue",
+ "type": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.23.133.2.2",
+ "components": [
+ 2,
+ 23,
+ 133,
+ 2,
+ 2
+ ],
+ "name": "tcg-at-tpmModel"
+ },
+ "value": {
+ "_choice": "utf8String",
+ "value": "ST33HTPHAHC0"
+ }
+ }
+ ],
+ [
+ {
+ "_type": "AttributeTypeAndValue",
+ "type": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.23.133.2.3",
+ "components": [
+ 2,
+ 23,
+ 133,
+ 2,
+ 3
+ ],
+ "name": "tcg-at-tpmVersion"
+ },
+ "value": {
+ "_choice": "utf8String",
+ "value": "id:00490008"
+ }
+ }
+ ]
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "_type": "Extension",
+ "extnID": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.5.29.9",
+ "components": [
+ 2,
+ 5,
+ 29,
+ 9
+ ],
+ "name": "id-x509-ce-subjectDirectoryAttributes"
+ },
+ "critical": false,
+ "extnValue": "305E301706056781050210310E300C0C03322E300201000202008A304306056781050212313A30380201000101FFA0030A0101A1030A0100A2030A0100A310300E1603332E310A01040A01020101FFA40F300D16053134302D320A0102010100",
+ "_extnValue_choice": "ext-SubjectDirectoryAttributes",
+ "_extnValue": [
+ {
+ "_type": "AttributeSet",
+ "type": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.23.133.2.16",
+ "components": [
+ 2,
+ 23,
+ 133,
+ 2,
+ 16
+ ],
+ "name": "tcg-at-tpmSpecification"
+ },
+ "values": [
+ "300C0C03322E300201000202008A"
+ ],
+ "_values_choice": "at-TPMSpecification",
+ "_values": [
+ {
+ "_type": "TPMSpecification",
+ "family": "2.0",
+ "level": 0,
+ "revision": 138
+ }
+ ]
+ },
+ {
+ "_type": "AttributeSet",
+ "type": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.23.133.2.18",
+ "components": [
+ 2,
+ 23,
+ 133,
+ 2,
+ 18
+ ],
+ "name": "tcg-at-tpmSecurityAssertions"
+ },
+ "values": [
+ "30380201000101FFA0030A0101A1030A0100A2030A0100A310300E1603332E310A01040A01020101FFA40F300D16053134302D320A0102010100"
+ ],
+ "_values_choice": "at-TPMSecurityAssertions",
+ "_values": [
+ {
+ "_type": "TPMSecurityAssertions",
+ "version": 0,
+ "fieldUpgradable": true,
+ "ekGenerationType": "ekgt-injected",
+ "ekGenerationLocation": "tpmManufacturer",
+ "ekCertificateGenerationLocation": "tpmManufacturer",
+ "ccInfo": {
+ "_type": "CommonCriteriaMeasures",
+ "version": "3.1",
+ "assurancelevel": "ealevel4",
+ "evaluationStatus": "evaluationCompleted",
+ "plus": true,
+ "strengthOfFunction": null,
+ "profileOid": null,
+ "profileUri": null,
+ "targetOid": null,
+ "targetUri": null
+ },
+ "fipsLevel": {
+ "_type": "FIPSLevel",
+ "version": "140-2",
+ "level": "sllevel2",
+ "plus": false
+ },
+ "iso9000Certified": false,
+ "iso9000Uri": null
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "_type": "Extension",
+ "extnID": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.5.29.15",
+ "components": [
+ 2,
+ 5,
+ 29,
+ 15
+ ],
+ "name": "id-x509-ce-keyUsage"
+ },
+ "critical": true,
+ "extnValue": "03020520",
+ "_extnValue_choice": "ext-KeyUsage",
+ "_extnValue": [
+ "keyEncipherment"
+ ]
+ },
+ {
+ "_type": "Extension",
+ "extnID": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.5.29.19",
+ "components": [
+ 2,
+ 5,
+ 29,
+ 19
+ ],
+ "name": "id-x509-ce-basicConstraints"
+ },
+ "critical": true,
+ "extnValue": "3000",
+ "_extnValue_choice": "ext-BasicConstraints",
+ "_extnValue": {
+ "_type": "BasicConstraints",
+ "cA": false,
+ "pathLenConstraint": null
+ }
+ },
+ {
+ "_type": "Extension",
+ "extnID": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.5.29.37",
+ "components": [
+ 2,
+ 5,
+ 29,
+ 37
+ ],
+ "name": "id-x509-ce-extKeyUsage"
+ },
+ "critical": false,
+ "extnValue": "300706056781050801",
+ "_extnValue_choice": "ext-ExtKeyUsage",
+ "_extnValue": [
+ {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "2.23.133.8.1",
+ "components": [
+ 2,
+ 23,
+ 133,
+ 8,
+ 1
+ ],
+ "name": "tcg-kp-EKCertificate"
+ }
+ ]
+ },
+ {
+ "_type": "Extension",
+ "extnID": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "1.3.6.1.5.5.7.1.1",
+ "components": [
+ 1,
+ 3,
+ 6,
+ 1,
+ 5,
+ 5,
+ 7,
+ 1,
+ 1
+ ],
+ "name": "id-pkix-pe-authorityInfoAccess"
+ },
+ "critical": false,
+ "extnValue": "303C303A06082B06010505073002862E687474703A2F2F7365637572652E676C6F62616C7369676E2E636F6D2F73746D74706D656B696E7430352E637274",
+ "_extnValue_choice": "ext-AuthorityInfoAccess",
+ "_extnValue": [
+ {
+ "_type": "AccessDescription",
+ "accessMethod": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "1.3.6.1.5.5.7.48.2",
+ "components": [
+ 1,
+ 3,
+ 6,
+ 1,
+ 5,
+ 5,
+ 7,
+ 48,
+ 2
+ ],
+ "name": "id-pkix-ad-caIssuers"
+ },
+ "accessLocation": {
+ "_choice": "uniformResourceIdentifier",
+ "value": "http://secure.globalsign.com/stmtpmekint05.crt"
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "signatureAlgorithm": {
+ "_type": "AlgorithmIdentifier",
+ "algorithm": {
+ "_type": "OBJECT IDENTIFIER",
+ "oid": "1.2.840.113549.1.1.11",
+ "components": [
+ 1,
+ 2,
+ 840,
+ 113549,
+ 1,
+ 1,
+ 11
+ ],
+ "name": "id-pkcs1-sha256WithRSAEncryption"
+ },
+ "parameters": "0500"
+ },
+ "signatureValue": "2048:3D4C381E5B4F1BCBE09C63D52F1F04570CAEA142FD9CD942043B11F8E3BDCF50007AE16CF8869013041E92CDD3280BA4B51FBBD40582ED750219E261A695095674855AACEB520ADAFF9E7E908480A39CDCF900462D9171960FFE55D3AC49E8C981341BBD2EFBCC252A4C18A4F3B7C84CCE42CE70A208C84D2630A7ABFBE72D6271E75B9FF1C971D20EB3DBD763F1E04D834EAA692D2E4001BBF4730A3E3FDA9711AE386524D91C63BE0E516D00D5C6141FCCF6C539F3518E180049865BE16B69CAE1F8CB7FDC474B38F7EE56CBE7D8A89D9BA99B65D5265AEF32AA62426B10E6D75BB8677EC44F755BBC2806FD2B4E04BDF5D44259DBEAA42B6F563DF7AA7506"
+ }
+ ```
+
+ (Notice that OID names look a bit weird. For reasons that may have been
+ lost to time and may no longer be relevant, these OIDs are defined with
+ slightly different names in the ASN.1 modules in Heimdal's source tree.
+ We'll fix this eventually.)
+
+...
+
+## Limitations
+
+ - `libasn1`'s and, therefore, `asn1_print`'s JSON support is not X.697 (JER)
+ compatible.
+
+ - Control over C types generated is very limited, mainly only for integer
+ types.
+
+ - When using the template backend, `SET { .. }` types are currently not sorted
+ by tag as they should be, but if the module author sorts them by hand then
+ DER will be produced.
+
+ - `REAL` is not supported.
+
+ - `EmbeddedPDV` is not supported.
+
+ - `BMPString` is not supported.
+
+ - IA5String is not properly supported -- it's essentially treated as a
+ `UTF8String` with a different tag. This is true of all the string types.
+
+ - Only types can be imported at this time. Without some rototilling we likely
+ will not be able to import anything other than types, values, and object
+ sets.
+
+ - Only simple value syntax is supported. Constructed value syntax (i.e.,
+ values of `SET`, `SEQUENCE`, `SET OF`, and `SEQUENCE OF`), is not supported.
+ Values of `CHOICE` types are also not supported.
+
+ - There is no way to substitute object sets at run-time. This means that
+ automatic decoding through open types will spend more CPU cycles than the
+ application might want, by decoding more types than the application might
+ care about. The ability to substitute object sets at run-time would require
+ a change to the APIs generated.
+
+ - ...
+
+## Compiler Usage
+
+The various options for the Heimdal ASN.1 compiler are described in its manual
+page, which is included below.
+
+The `--option-file=FILE` option is particularly useful, as it allows additional
+compiler options to be read from a file.
+
+The `--preserve-binary=TYPE-NAME` option is critical for signature validation
+as it causes the decoder to save the encoding of the given type so that
+signature validation code can easily find the original encoding and thus avoid
+having to re-encode or resort to other hacks. E.g., we use this for preserving
+the original encoding of the `tbsCertificate` field of `Certificate`.
+
+The `--sequence=TYPE-NAME` causes the compiler to generate additional utility
+functions for adding or removing items from the named type when it is a
+`SEQUENCE OF` or `SET OF` type.
+
+See the manual page `asn1_compile.1`:
+
+```text
+ASN1_COMPILE(1) BSD General Commands Manual ASN1_COMPILE(1)
+
+NAME
+ asn1_compile — compile ASN.1 modules
+
+SYNOPSIS
+ asn1_compile [--template] [--prefix-enum] [--enum-prefix=PREFIX]
+ [--encode-rfc1510-bit-string] [--decode-dce-ber]
+ [--support-ber] [--preserve-binary=TYPE] [--sequence=TYPE]
+ [--decorate=DECORATION] [--one-code-file] [--gen-name=NAME]
+ [--option-file=FILE] [--original-order] [--no-parse-units]
+ [--type-file=C-HEADER-FILE] [--version] [--help]
+ [FILE.asn1 [NAME]]
+
+DESCRIPTION
+ asn1_compile compiles an ASN.1 module into C source code and header
+ files.
+
+ A fairly large subset of ASN.1 as specified in X.680, and the ASN.1 In‐
+ formation Object System as specified in X.681, X.682, and X.683 is sup‐
+ ported, with support for the Distinguished Encoding Rules (DER), partial
+ Basic Encoding Rules (BER) support, and experimental JSON support (encod‐
+ ing only at this time).
+
+ See the compiler's README files for details about the C code and inter‐
+ faces it generates.
+
+ The Information Object System support includes automatic codec support
+ for encoding and decoding through “open types” which are also known as
+ “typed holes”. See RFC 5912 for examples of how to use the ASN.1 Infor‐
+ mation Object System via X.681/X.682/X.683 annotations. See the com‐
+ piler's README files for more information on ASN.1 Information Object
+ System support.
+
+ Extensions specific to Heimdal are generally not syntactic in nature but
+ rather command-line options to this program. For example, one can use
+ command-line options to:
+ • enable decoding of BER-encoded values;
+ • enable RFC1510-style handling of ‘BIT STRING’ types;
+ • enable saving of as-received encodings of specific types
+ for the purpose of signature validation;
+ • generate add/remove utility functions for array types;
+ • decorate generated ‘struct’ types with fields that are nei‐
+ ther encoded nor decoded;
+ etc.
+
+ ASN.1 x.680 features supported:
+ • most primitive types (except BMPString and REAL);
+ • all constructed types, including SET and SET OF;
+ • explicit and implicit tagging.
+
+ Size and range constraints on the ‘INTEGER’ type cause the compiler to
+ generate appropriate C types such as ‘int’, ‘unsigned int’, ‘int64_t’,
+ ‘uint64_t’. Unconstrained ‘INTEGER’ is treated as ‘heim_integer’, which
+ represents an integer of arbitrary size.
+
+ Caveats and ASN.1 x.680 features not supported:
+ • JSON encoding support is not quite X.697 (JER) compatible.
+ Its JSON schema is subject to change without notice.
+ • Control over C types generated is very limited, mainly only
+ for integer types.
+ • When using the template backend, `SET { .. }` types are
+ currently not sorted by tag as they should be, but if the
+ module author sorts them by hand then correct DER will be
+ produced.
+ • ‘AUTOMATIC TAGS’ is not supported.
+ • The REAL type is not supported.
+ • The EmbeddedPDV type is not supported.
+ • The BMPString type is not supported.
+ • The IA5String is not properly supported, as it's essen‐
+ tially treated as a UTF8String with a different tag.
+ • All supported non-octet strings are treated as like the
+ UTF8String type.
+ • Only types can be imported into ASN.1 modules at this time.
+ • Only simple value syntax is supported. Constructed value
+ syntax (i.e., values of SET, SEQUENCE, SET OF, and SEQUENCE
+ OF types), is not supported. Values of `CHOICE` types are
+ also not supported.
+
+ Options supported:
+
+ --template
+ Use the “template” backend instead of the “codegen” backend
+ (which is the default backend).
+
+ The template backend generates “templates” which are akin to
+ bytecode, and which are interpreted at run-time.
+
+ The codegen backend generates C code for all functions directly,
+ with no template interpretation.
+
+ The template backend scales better than the codegen backend be‐
+ cause as we add support for more encoding rules and more opera‐
+ tions (we may add value comparators) the templates stay mostly
+ the same, thus scaling linearly with size of module. Whereas the
+ codegen backend scales linear with the product of module size and
+ number of encoding rules supported.
+
+ --prefix-enum
+ This option should be removed because ENUMERATED types should al‐
+ ways have their labels prefixed.
+
+ --enum-prefix=PREFIX
+ This option should be removed because ENUMERATED types should al‐
+ ways have their labels prefixed.
+
+ --encode-rfc1510-bit-string
+ Use RFC1510, non-standard handling of “BIT STRING” types.
+
+ --decode-dce-ber
+
+ --support-ber
+
+ --preserve-binary=TYPE
+ Generate a field named ‘_save’ in the C struct generated for the
+ named TYPE. This field is used to preserve the original encoding
+ of the value of the TYPE.
+
+ This is useful for cryptographic applications so that they can
+ check signatures of encoded values as-received without having to
+ re-encode those values.
+
+ For example, the TBSCertificate type should have values preserved
+ so that Certificate validation can check the signatureValue over
+ the tbsCertificate's value as-received.
+
+ The alternative of encoding a value to check a signature of it is
+ brittle. For types where non-canonical encodings (such as BER)
+ are allowed, this alternative is bound to fail. Thus the point
+ of this option.
+
+ --sequence=TYPE
+ Generate add/remove functions for the named ASN.1 TYPE which must
+ be a ‘SET OF’ or ‘SEQUENCE OF’ type.
+
+ --decorate=ASN1-TYPE:FIELD-ASN1-TYPE:fname[?]
+ Add to the C struct generated for the given ASN.1 SET, SEQUENCE,
+ or CHOICE type named ASN1-TYPE a “hidden” field named fname of
+ the given ASN.1 type FIELD-ASN1-TYPE, but do not encode or decode
+ it. If the fname ends in a question mark, then treat the field
+ as OPTIONAL.
+
+ This is useful for adding fields to existing types that can be
+ used for internal bookkeeping but which do not affect interoper‐
+ ability because they are neither encoded nor decoded. For exam‐
+ ple, one might decorate a request type with state needed during
+ processing of the request.
+
+ --decorate=ASN1-TYPE:void*:fname
+ Add to the C struct generated for the given ASN.1 SET, SEQUENCE,
+ or CHOICE type named ASN1-TYPE a “hidden” field named fname of
+ type ‘void *’ (but do not encode or decode it.
+
+ The destructor and copy constructor functions generated by this
+ compiler for ASN1-TYPE will set this field to the ‘NULL’ pointer.
+
+ --decorate=ASN1-TYPE:FIELD-C-TYPE:fname[?]:[copyfn]:[freefn]:header
+ Add to the C struct generated for the given ASN.1 SET, SEQUENCE,
+ or CHOICE type named ASN1-TYPE a “hidden” field named fname of
+ the given external C type FIELD-C-TYPE, declared in the given
+ header but do not encode or decode this field. If the fname ends
+ in a question mark, then treat the field as OPTIONAL.
+
+ The header must include double quotes or angle brackets. The
+ copyfn must be the name of a copy constructor function that takes
+ a pointer to a source value of the type, and a pointer to a des‐
+ tination value of the type, in that order, and which returns zero
+ on success or else a system error code on failure. The freefn
+ must be the name of a destructor function that takes a pointer to
+ a value of the type and which releases resources referenced by
+ that value, but does not free the value itself (the run-time al‐
+ locates this value as needed from the C heap). The freefn should
+ also reset the value to a pristine state (such as all zeros).
+
+ If the copyfn and freefn are empty strings, then the decoration
+ field will neither be copied nor freed by the functions generated
+ for the TYPE.
+
+ --one-code-file
+ Generate a single source code file. Otherwise a separate code
+ file will be generated for every type.
+
+ --gen-name=NAME
+ Use NAME to form the names of the files generated.
+
+ --option-file=FILE
+ Take additional command-line options from FILE.
+
+ --original-order
+ Attempt to preserve the original order of type definition in the
+ ASN.1 module. By default the compiler generates types in a topo‐
+ logical sort order.
+
+ --no-parse-units
+ Do not generate to-int / from-int functions for enumeration
+ types.
+
+ --type-file=C-HEADER-FILE
+ Generate an include of the named header file that might be needed
+ for common type defintions.
+
+ --version
+
+ --help
+
+NOTES
+ Currently only the template backend supports automatic encoding and de‐
+ coding of open types via the ASN.1 Information Object System and
+ X.681/X.682/X.683 annotations.
+
+HEIMDAL February 22, 2021 HEIMDAL
+```
+
+## APIs Generated by the Compiler
+
+Every named type in an ASN.1 module gets a corresponding type in C.
+Em-dashes in symbols become underscores.
+
+Every named type in an ASN.1 module also gets several functions generated
+associated with it:
+
+ - `int decode_TypeName(const unsigned char *, size_t, TypeName *, size_t *);`
+
+ Decodes a value of `TypeName` in the given byte array of the given size,
+ into the given `TypeName` object, and outputs the number of bytes parsed.
+
+ Returns 0 on success, or an error that can be formatted as a string using
+ the `com_err` library.
+
+ - `int encode_TypeName(unsigned char *, size_t, const TypeName *, size_t *);`
+
+ Encodes the given object of `TypeName` type into the given byte array of the
+ given size, outputting the number of bytes used.
+
+ NOTE WELL: the `unsigned char *` pointer must point to the _last_ byte of
+ the buffer!
+
+ Returns 0 on success, or an error that can be formatted as a string using
+ the `com_err` library, including system errors such as `ENOMEM`.
+
+ - `int length_TypeName(const TypeName *);`
+
+ Returns the number of bytes needed to encode the given object.
+
+ - `void free_TypeName(TypeName *);`
+
+ Releases the memory associated with the content of the given object, but
+ note that the object itself is _not_ released.
+
+ - `int copy_TypeName(const TypeName *, TypeName *);`
+
+ Copies the content of the given `const` object to the destination,
+ non-`const` object.
+
+ Returns 0 on success, or an error that can be formatted as a string using
+ the `com_err` library, including system errors such as `ENOMEM`.
+
+ - `char *print_TypeName(const TypeName *, int);`
+
+ Returns a string (JSON) representation of the given object. The `int`
+ argument is a bitset of flags:
+
+ - `ASN1_PRINT_INDENT`
+
+ Indent the JSON. If not given the the JSON will have no interstitial
+ whitespace, including newlines.
+
+You will want to review the data structures generated. They look like:
+
+```C
+ typedef struct TBSCertificate TBSCertificate;
+ typedef struct AlgorithmIdentifier AlgorithmIdentifier;
+ typedef struct ... ...;
+
+ /*
+ Certificate ::= SEQUENCE {
+ tbsCertificate TBSCertificate,
+ signatureAlgorithm AlgorithmIdentifier,
+ signatureValue BIT STRING {
+ },
+ }
+ */
+
+ typedef struct Certificate {
+ TBSCertificate tbsCertificate;
+ AlgorithmIdentifier signatureAlgorithm;
+ heim_bit_string signatureValue;
+ } Certificate;
+
+ /*
+ TBSCertificate ::= SEQUENCE {
+ version [0] Version OPTIONAL,
+ serialNumber CertificateSerialNumber,
+ signature AlgorithmIdentifier,
+ issuer Name,
+ validity Validity,
+ subject Name,
+ subjectPublicKeyInfo SubjectPublicKeyInfo,
+ issuerUniqueID [1] IMPLICIT BIT STRING {
+ } OPTIONAL,
+ subjectUniqueID [2] IMPLICIT BIT STRING {
+ } OPTIONAL,
+ extensions [3] Extensions OPTIONAL,
+ }
+ */
+
+ typedef struct TBSCertificate {
+ heim_octet_string _save;
+ Version *version;
+ CertificateSerialNumber serialNumber;
+ AlgorithmIdentifier signature;
+ Name issuer;
+ Validity validity;
+ Name subject;
+ SubjectPublicKeyInfo subjectPublicKeyInfo;
+ heim_bit_string *issuerUniqueID;
+ heim_bit_string *subjectUniqueID;
+ Extensions *extensions;
+ } TBSCertificate;
+```
+
+Note how trivial the mapping onto C is.
+
+`OPTIONAL` fields become pointer fields, with `NULL` indicating
+absence and non-NULL indicating presence.
+
+And so on.
+
+## `asn1_print` Usage
+
+```text
+ASN1_PRINT(1) BSD General Commands Manual ASN1_PRINT(1)
+
+NAME
+ asn1_print — dump ASN.1 DER encoded values
+
+SYNOPSIS
+ asn1_print [-i | --no-indent] [-I | --inner] [-l | --list-types]
+ [-A | --try-all-types] [-S | --raw-sequence] [-n | --no-print]
+ [-q | --quiet] [--test-encode] [--test-copy]
+ [-l -v | --version] [-l -h | --help] [FILE [TypeName...]]
+
+DESCRIPTION
+ asn1_print Dumps ASN.1 DER-encoded values. If one or more TypeName argu-
+ ments are given, then asn1_print will print the value in a JSON-like for-
+ mat using its knowledge of the ASN.1 modules defining those types, stop-
+ ping at the first type for which it can successfully decode the value.
+ If TypeNames are given, they must be the names of ASN.1 types exported by
+ an ASN.1 modules that are compiled into asn1_print. Use the
+ --try-all-types option to attempt decoding as all ASN.1 types known to
+ asn1_print. If neither any TypeName nor --try-all-types are given, then
+ the value will be parsed and displayed using just the self-describing
+ nature of DER.
+
+ Options supported:
+
+ -i, --no-indent
+ Do not indent dump.
+
+ -I, --inner
+ Try to parse inner structures of OCTET STRING and constructed
+ values.
+
+ -l, --list-types
+ List all types known to asn1_print.
+
+ -A, --try-all-types
+ Attempt to decode the value as any of all types known to
+ asn1_print.
+
+ -S, --raw-sequence
+ If a value parses as a given TypeName but any bytes are left
+ over, try to parse those separately as well until all bytes are
+ consumed or an error occurs.
+
+ -n, --no-print
+ For the case where -A or --try-all-types or where a TypeName is
+ given, do not output a JSON representation of the value, just
+ attempt to decode it. This is useful for fuzzing.
+
+ -q, --quiet
+ Similar to -n, --no-print but JSON output will be formatted, just
+ not output. As with -n, --no-print, this option requires -A -/
+ --try-all-types or that a TypeName be given. This is useful for
+ fuzzing.
+
+ --test-encode
+ Check that encoding produces the same value as decoding. Useful
+ for fuzzing.
+
+ --test-copy
+ Test copy functions. Useful for fuzzing.
+
+ -v, --version
+
+ -h, --help
+
+HEIMDAL February 22, 2021 HEIMDAL
+```
+
+## Implementation
+
+See:
+
+ - `lib/asn1/main.c` for the `main()` function of the compiler
+ - `lib/asn1/asn1parse.y` for the grammar and most of the parsing into an AST
+ - `lib/asn1/symbol.h` for the types making up the AST
+ - `lib/asn1/{hash,symbol}.c` for compiler AST supporting functionality
+ - `lib/asn1/gen.c` for the C header file generator
+ - `lib/asn1/gen_template.c` for the template generator
+ - `lib/asn1/gen_{decode,encode,length,copy,free}.c` for the C code generator
+ - `lib/asn1/gen_{glue,seq}.c` for misc code generator
+ - `lib/asn1/template.c` for the template interpreter
+ - `lib/asn1/der*.c` for primitive type primitives
+ - `lib/asn1/extra.c` for primitives related to `ANY`
+
+...
+
+## Futures
+
+ - Add JER support so we can convert between JER and DER?
+
+ - Add XDR support? There are no ASN.1 Encoding Rules based on XDR, but it is
+ trivial to construct such for at least that subset of ASN.1 for which the
+ XDR syntax has equivalent semantics.
+
+ - Add OER support?
+
+ - Add NDR support? There are no ASN.1 Encoding Rules based on NDR, but it is
+ trivial to construct such for at least that subset of ASN.1 for which the
+ IDL syntax has equivalent semantics.
+
+ - Perhaps third parties will contribute more control over generated types?
+ This may require separate publication of the Heimdal ASN.1 compiler from the
+ rest of Heimdal.
+
+## Moving From C
+
+ - Generate and output a JSON representation of the compiled ASN.1 module.
+
+ - Code codegen/templategen backends in jq or Haskell or whatever.
+
+ - Code template interpreters in some host language.
+
+ - Eventually rewrite the compiler itself in Rust or whatever.
diff --git a/third_party/heimdal/lib/asn1/asn1-common.h b/third_party/heimdal/lib/asn1/asn1-common.h
new file mode 100644
index 0000000..7797eed
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/asn1-common.h
@@ -0,0 +1,90 @@
+/* $Id$ */
+
+#include <stddef.h>
+#include <time.h>
+#include <krb5-types.h>
+
+#ifndef __asn1_common_definitions__
+#define __asn1_common_definitions__
+
+#ifndef __HEIM_BASE_DATA__
+#define __HEIM_BASE_DATA__ 1
+struct heim_base_data {
+ size_t length;
+ void *data;
+};
+#endif
+
+typedef struct heim_integer {
+ size_t length;
+ void *data;
+ int negative;
+} heim_integer;
+
+typedef struct heim_base_data heim_octet_string;
+
+typedef char *heim_general_string;
+typedef char *heim_utf8_string;
+typedef struct heim_base_data heim_printable_string;
+typedef struct heim_base_data heim_ia5_string;
+
+typedef struct heim_bmp_string {
+ size_t length;
+ uint16_t *data;
+} heim_bmp_string;
+
+typedef struct heim_universal_string {
+ size_t length;
+ uint32_t *data;
+} heim_universal_string;
+
+typedef char *heim_visible_string;
+
+typedef struct heim_oid {
+ size_t length;
+ unsigned *components;
+} heim_oid;
+
+typedef struct heim_bit_string {
+ size_t length;
+ void *data;
+} heim_bit_string;
+
+typedef struct heim_base_data heim_any;
+typedef struct heim_base_data heim_any_set;
+typedef struct heim_base_data HEIM_ANY;
+typedef struct heim_base_data HEIM_ANY_SET;
+
+enum asn1_print_flags {
+ ASN1_PRINT_INDENT = 1,
+};
+
+#define ASN1_MALLOC_ENCODE(T, B, BL, S, L, R) \
+ do { \
+ (BL) = length_##T((S)); \
+ (B) = malloc((BL)); \
+ if((B) == NULL) { \
+ (R) = ENOMEM; \
+ } else { \
+ (R) = encode_##T(((unsigned char*)(B)) + (BL) - 1, (BL), \
+ (S), (L)); \
+ if((R) != 0) { \
+ free((B)); \
+ (B) = NULL; \
+ } \
+ } \
+ } while (0)
+
+#ifdef _WIN32
+#ifndef ASN1_LIB
+#define ASN1EXP __declspec(dllimport)
+#else
+#define ASN1EXP
+#endif
+#define ASN1CALL __stdcall
+#else
+#define ASN1EXP
+#define ASN1CALL
+#endif
+
+#endif
diff --git a/third_party/heimdal/lib/asn1/asn1-template.h b/third_party/heimdal/lib/asn1/asn1-template.h
new file mode 100644
index 0000000..07c4461
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/asn1-template.h
@@ -0,0 +1,305 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* asn1 templates */
+
+#ifndef __TEMPLATE_H__
+#define __TEMPLATE_H__
+
+/*
+ * TBD:
+ *
+ * - For OER also encode number of optional/default/extension elements into
+ * header entry's ptr field, not just the number of entries that follow it.
+ *
+ * - For JER we'll need to encode encoding options (encode as array, encode as
+ * object, etc.)
+ *
+ * - For open types we'll need to be able to indicate what encoding rules the
+ * type uses.
+ *
+ * - We have too many bits for tags (20) and probably not enough for ops (4
+ * bits, and we've used all but one).
+ */
+
+/* header:
+ * HF flags if not a BIT STRING type
+ * HBF flags if a BIT STRING type
+ *
+ * ptr is count of elements
+ * offset is size of struct
+ */
+
+/* tag:
+ * 0..20 tag
+ * 21 type
+ * 22..23 class
+ * 24..27 flags
+ * 28..31 op
+ *
+ * ptr points to template for tagged type
+ * offset is offset of struct field
+ */
+
+/* parse:
+ * 0..11 type
+ * 12..23 unused
+ * 24..27 flags
+ * 28..31 op
+ *
+ * ptr is NULL
+ * offset is ...
+ */
+
+/* defval: (next template entry is defaulted)
+ *
+ * DV flags (ptr is or points to defval)
+ *
+ * ptr is default value or pointer to default value
+ * offset is all ones
+ */
+
+/* name: first one is the name of the SET/SEQUENCE/CHOICE type
+ * subsequent ones are the name of the nth field
+ *
+ * 0..23 unused
+ * 24..27 flags A1_NM_*
+ * 28..31 op
+ *
+ * ptr is const char * pointer to the name as C string
+ * offset is all zeros
+ */
+
+/* objset:
+ * 0..9 open type ID entry index
+ * 10..19 open type entry index
+ * 20..23 unused
+ * 24..27 flags A1_OS_*
+ * 28..31 op
+ *
+ * ptr points to object set template
+ * offset is the offset of the choice struct
+ */
+
+/* opentypeid: offset is zero
+ * ptr points to value if it is not an integer
+ * ptr is the value if it is an integer
+ * 0..23 unused
+ * 24..27 flags A1_OTI_*
+ * 28..31 op
+ */
+
+/* opentype: offset is sizeof C type for this open type choice
+ * ptr points to template for type choice
+ * 0..23 unused
+ * 24..27 flags
+ * 28..31 op
+ */
+
+#define A1_OP_MASK (0xf0000000)
+#define A1_OP_TYPE (0x10000000) /* templated type */
+#define A1_OP_TYPE_EXTERN (0x20000000) /* templated type (imported) */
+#define A1_OP_TAG (0x30000000) /* a tag */
+#define A1_OP_PARSE (0x40000000) /* primitive type */
+#define A1_OP_SEQOF (0x50000000) /* sequence of */
+#define A1_OP_SETOF (0x60000000) /* set of */
+#define A1_OP_BMEMBER (0x70000000) /* BIT STRING member */
+#define A1_OP_CHOICE (0x80000000) /* CHOICE */
+#define A1_OP_DEFVAL (0x90000000) /* def. value */
+#define A1_OP_OPENTYPE_OBJSET (0xa0000000) /* object set for open type */
+#define A1_OP_OPENTYPE_ID (0xb0000000) /* open type id field */
+#define A1_OP_OPENTYPE (0xc0000000) /* open type field */
+#define A1_OP_NAME (0xd0000000) /* symbol */
+#define A1_OP_TYPE_DECORATE (0xe0000000) /* decoration w/ templated type */
+#define A1_OP_TYPE_DECORATE_EXTERN (0xf0000000) /* decoration w/ some C type */
+ /* 0x00.. is still free */
+
+#define A1_FLAG_MASK (0x0f000000)
+#define A1_FLAG_OPTIONAL (0x01000000)
+#define A1_FLAG_IMPLICIT (0x02000000)
+#define A1_FLAG_DEFAULT (0x04000000)
+
+#define A1_TAG_T(CLASS,TYPE,TAG) ((A1_OP_TAG) | (((CLASS) << 22) | ((TYPE) << 21) | (TAG)))
+#define A1_TAG_CLASS(x) (((x) >> 22) & 0x3)
+#define A1_TAG_TYPE(x) (((x) >> 21) & 0x1)
+#define A1_TAG_TAG(x) ((x) & 0x1fffff)
+
+#define A1_TAG_LEN(t) ((uintptr_t)(t)->ptr)
+#define A1_HEADER_LEN(t) ((uintptr_t)(t)->ptr)
+
+#define A1_PARSE_T(type) ((A1_OP_PARSE) | (type))
+#define A1_PARSE_TYPE_MASK 0xfff
+#define A1_PARSE_TYPE(x) (A1_PARSE_TYPE_MASK & (x))
+
+#define A1_PF_INDEFINTE 0x1
+#define A1_PF_ALLOW_BER 0x2
+
+#define A1_HF_PRESERVE 0x1
+#define A1_HF_ELLIPSIS 0x2
+
+#define A1_HBF_RFC1510 0x1
+
+#define A1_DV_BOOLEAN 0x01
+#define A1_DV_INTEGER 0x02
+#define A1_DV_INTEGER32 0x04
+#define A1_DV_INTEGER64 0x08
+#define A1_DV_UTF8STRING 0x10
+
+#define A1_OS_IS_SORTED (0x01000000)
+#define A1_OS_OT_IS_ARRAY (0x02000000)
+#define A1_OTI_IS_INTEGER (0x04000000)
+
+
+struct asn1_template {
+ uint32_t tt;
+ uint32_t offset;
+ const void *ptr;
+};
+
+typedef int (ASN1CALL *asn1_type_decode)(const unsigned char *, size_t, void *, size_t *);
+typedef int (ASN1CALL *asn1_type_encode)(unsigned char *, size_t, const void *, size_t *);
+typedef size_t (ASN1CALL *asn1_type_length)(const void *);
+typedef void (ASN1CALL *asn1_type_release)(void *);
+typedef int (ASN1CALL *asn1_type_copy)(const void *, void *);
+typedef char * (ASN1CALL *asn1_type_print)(const void *, int);
+
+struct asn1_type_func {
+ asn1_type_encode encode;
+ asn1_type_decode decode;
+ asn1_type_length length;
+ asn1_type_copy copy;
+ asn1_type_release release;
+ asn1_type_print print;
+ size_t size;
+};
+
+struct template_of {
+ unsigned int len;
+ void *val;
+};
+
+enum template_types {
+ A1T_IMEMBER = 0,
+ A1T_HEIM_INTEGER,
+ A1T_INTEGER,
+ A1T_INTEGER64,
+ A1T_UNSIGNED,
+ A1T_UNSIGNED64,
+ A1T_GENERAL_STRING,
+ A1T_OCTET_STRING,
+ A1T_OCTET_STRING_BER,
+ A1T_IA5_STRING,
+ A1T_BMP_STRING,
+ A1T_UNIVERSAL_STRING,
+ A1T_PRINTABLE_STRING,
+ A1T_VISIBLE_STRING,
+ A1T_UTF8_STRING,
+ A1T_GENERALIZED_TIME,
+ A1T_UTC_TIME,
+ A1T_HEIM_BIT_STRING,
+ A1T_BOOLEAN,
+ A1T_OID,
+ A1T_TELETEX_STRING,
+ A1T_NUM_ENTRY
+};
+
+extern struct asn1_type_func asn1_template_prim[A1T_NUM_ENTRY];
+
+#define ABORT_ON_ERROR() abort()
+
+#define DPOC(data,offset) ((const void *)(((const unsigned char *)data) + offset))
+#define DPO(data,offset) ((void *)(((unsigned char *)data) + offset))
+
+/*
+ * These functions are needed by the generated template stubs and are
+ * really internal functions. Since they are part of der-private.h
+ * that contains extra prototypes that really a private we included a
+ * copy here.
+ */
+
+int
+_asn1_copy_top (
+ const struct asn1_template * /*t*/,
+ const void * /*from*/,
+ void * /*to*/);
+
+void
+_asn1_free_top(const struct asn1_template *, void *);
+
+char *
+_asn1_print_top(const struct asn1_template *, int, const void *);
+
+int
+_asn1_decode_top (
+ const struct asn1_template * /*t*/,
+ unsigned /*flags*/,
+ const unsigned char * /*p*/,
+ size_t /*len*/,
+ void * /*data*/,
+ size_t * /*size*/);
+
+int
+_asn1_encode (
+ const struct asn1_template * /*t*/,
+ unsigned char * /*p*/,
+ size_t /*len*/,
+ const void * /*data*/,
+ size_t * /*size*/);
+
+int
+_asn1_encode_fuzzer (
+ const struct asn1_template * /*t*/,
+ unsigned char * /*p*/,
+ size_t /*len*/,
+ const void * /*data*/,
+ size_t * /*size*/);
+
+void
+_asn1_free (
+ const struct asn1_template * /*t*/,
+ void * /*data*/);
+
+size_t
+_asn1_length (
+ const struct asn1_template * /*t*/,
+ const void * /*data*/);
+
+size_t
+_asn1_length_fuzzer (
+ const struct asn1_template * /*t*/,
+ const void * /*data*/);
+
+
+#endif
diff --git a/third_party/heimdal/lib/asn1/asn1_compile-version.rc b/third_party/heimdal/lib/asn1/asn1_compile-version.rc
new file mode 100644
index 0000000..120fb85
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/asn1_compile-version.rc
@@ -0,0 +1,36 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#define RC_FILE_TYPE VFT_APP
+#define RC_FILE_DESC_0409 "ASN.1 Compiler"
+#define RC_FILE_ORIG_0409 "asn1_compile.exe"
+
+#include "../../windows/version.rc"
diff --git a/third_party/heimdal/lib/asn1/asn1_compile.1 b/third_party/heimdal/lib/asn1/asn1_compile.1
new file mode 100644
index 0000000..a7953df
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/asn1_compile.1
@@ -0,0 +1,350 @@
+.\" Copyright (c) 2019 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd February 22, 2021
+.Dt ASN1_COMPILE 1
+.Os HEIMDAL
+.Sh NAME
+.Nm asn1_compile
+.Nd compile ASN.1 modules
+.Sh SYNOPSIS
+.Nm
+.Bk -words
+.Op Fl Fl template
+.Op Fl Fl prefix-enum
+.Op Fl Fl enum-prefix=PREFIX
+.Op Fl Fl encode-rfc1510-bit-string
+.Op Fl Fl decode-dce-ber
+.Op Fl Fl support-ber
+.Op Fl Fl preserve-binary=TYPE
+.Op Fl Fl sequence=TYPE
+.Op Fl Fl decorate=DECORATION
+.Op Fl Fl one-code-file
+.Op Fl Fl gen-name=NAME
+.Op Fl Fl option-file=FILE
+.Op Fl Fl original-order
+.Op Fl Fl no-parse-units
+.Op Fl Fl type-file=C-HEADER-FILE
+.Op Fl Fl version
+.Op Fl Fl help
+.Op Ar FILE.asn1 Op Ar NAME
+.Ek
+.Sh DESCRIPTION
+.Nm
+compiles an ASN.1 module into C source code and header files.
+.Pp
+A fairly large subset of ASN.1 as specified in X.680, and the
+ASN.1 Information Object System as specified in X.681, X.682, and
+X.683 is supported, with support for the Distinguished Encoding
+Rules (DER), partial Basic Encoding Rules (BER) support, and
+experimental JSON support (encoding only at this time).
+.Pp
+See the compiler's README files for details about the C code and
+interfaces it generates.
+.Pp
+The Information Object System support includes automatic codec
+support for encoding and decoding through
+.Dq open types
+which are also known as
+.Dq typed holes .
+See RFC 5912 for examples of how to use the ASN.1
+Information Object System via X.681/X.682/X.683 annotations. See
+the compiler's README files for more information on ASN.1
+Information Object System support.
+.Pp
+Extensions specific to Heimdal are generally not syntactic in
+nature but rather command-line options to this program.
+For example, one can use command-line options to:
+.Bl -bullet -compact -width Ds -offset indent
+.It
+enable decoding of BER-encoded values;
+.It
+enable RFC1510-style handling of
+.Sq BIT STRING
+types;
+.It
+enable saving of as-received encodings of specific types for the
+purpose of signature validation;
+.It
+generate add/remove utility functions for array types;
+.It
+decorate generated
+.Sq struct
+types with fields that are neither encoded nor decoded;
+.El
+etc.
+.Pp
+ASN.1 x.680 features supported:
+.Bl -bullet -compact -width Ds -offset indent
+.It
+most primitive types (except BMPString and REAL);
+.It
+all constructed types, including SET and SET OF;
+.It
+explicit and implicit tagging.
+.El
+.Pp
+Size and range constraints on the
+.Sq INTEGER
+type cause the compiler to generate appropriate C types such as
+.Sq int ,
+.Sq unsigned int ,
+.Sq int64_t ,
+.Sq uint64_t .
+Unconstrained
+.Sq INTEGER
+is treated as
+.Sq heim_integer ,
+which represents an integer of arbitrary size.
+.Pp
+Caveats and ASN.1 x.680 features not supported:
+.Bl -bullet -compact -width Ds -offset indent
+.It
+JSON encoding support is not quite X.697 (JER) compatible.
+Its JSON schema is subject to change without notice.
+.It
+Control over C types generated is very limited, mainly only for
+integer types.
+.It
+When using the template backend, `SET { .. }` types are currently
+not sorted by tag as they should be, but if the module author
+sorts them by hand then correct DER will be produced.
+.It
+.Sq AUTOMATIC TAGS
+is not supported.
+.It
+The
+.Va REAL
+type is not supported.
+.It
+The
+.Va EmbeddedPDV
+type is not supported.
+.It
+The
+.Va BMPString
+type is not supported.
+.It
+The
+.Va IA5String
+is not properly supported, as it's essentially treated as a
+.Va UTF8String
+with a different tag.
+.It
+All supported non-octet strings are treated as like the
+.Va UTF8String
+type.
+.It
+Only types can be imported into ASN.1 modules at this time.
+.It
+Only simple value syntax is supported.
+Constructed value syntax (i.e., values of SET, SEQUENCE, SET OF,
+and SEQUENCE OF types), is not supported.
+Values of `CHOICE` types are also not supported.
+.El
+.Pp
+Options supported:
+.Bl -tag -width Ds
+.It Fl Fl template
+Use the
+.Dq template
+backend instead of the
+.Dq codegen
+backend (which is the default backend).
+.Pp
+The template backend generates
+.Dq templates
+which are akin to bytecode, and which are interpreted at
+run-time.
+.Pp
+The codegen backend generates C code for all functions directly,
+with no template interpretation.
+.Pp
+The template backend scales better than the codegen backend
+because as we add support for more encoding rules and more
+operations (we may add value comparators) the templates stay
+mostly the same, thus scaling linearly with size of module.
+Whereas the codegen backend scales linear with the product of
+module size and number of encoding rules supported.
+.It Fl Fl prefix-enum
+This option should be removed because ENUMERATED types should
+always have their labels prefixed.
+.It Fl Fl enum-prefix=PREFIX
+This option should be removed because ENUMERATED types should
+always have their labels prefixed.
+.It Fl Fl encode-rfc1510-bit-string
+Use RFC1510, non-standard handling of
+.Dq BIT STRING
+types.
+.It Fl Fl decode-dce-ber
+.It Fl Fl support-ber
+.It Fl Fl preserve-binary=TYPE
+Generate a field named
+.Sq _save
+in the C struct generated for the named
+.Ar TYPE .
+This field is used to preserve the original encoding of the value
+of the
+.Ar TYPE .
+.Pp
+This is useful for cryptographic applications so that they can
+check signatures of encoded values as-received without having to
+re-encode those values.
+.Pp
+For example, the TBSCertificate type should have values preserved
+so that Certificate validation can check the signatureValue over
+the tbsCertificate's value as-received.
+.Pp
+The alternative of encoding a value to check a signature of it is
+brittle.
+For types where non-canonical encodings (such as BER) are
+allowed, this alternative is bound to fail.
+Thus the point of this option.
+.It Fl Fl sequence=TYPE
+Generate add/remove functions for the named ASN.1
+.Ar TYPE
+which must be a
+.Sq SET OF
+or
+.Sq SEQUENCE OF
+type.
+.It Fl Fl decorate=ASN1-TYPE:FIELD-ASN1-TYPE:fname[?]
+Add to the C struct generated for the given ASN.1 SET, SEQUENCE, or
+CHOICE type named
+.Ar ASN1-TYPE
+a
+.Dq hidden
+field named
+.Ar fname
+of the given ASN.1 type
+.Ar FIELD-ASN1-TYPE ,
+but do not encode or decode it.
+If the
+.Ar fname
+ends in a question mark, then treat the field as OPTIONAL.
+.Pp
+This is useful for adding fields to existing types that can be
+used for internal bookkeeping but which do not affect
+interoperability because they are neither encoded nor decoded.
+For example, one might decorate a request type with state needed
+during processing of the request.
+.It Fl Fl decorate=ASN1-TYPE:void*:fname
+Add to the C struct generated for the given ASN.1 SET, SEQUENCE, or
+CHOICE type named
+.Ar ASN1-TYPE
+a
+.Dq hidden
+field named
+.Ar fname
+of type
+.Sq void *
+(but do not encode or decode it.
+.Pp
+The destructor and copy constructor functions generated by this
+compiler for
+.Ar ASN1-TYPE
+will set this field to the
+.Sq NULL
+pointer.
+.It Fl Fl decorate=ASN1-TYPE:FIELD-C-TYPE:fname[?]:[copyfn]:[freefn]:header
+Add to the C struct generated for the given ASN.1 SET, SEQUENCE, or
+CHOICE type named
+.Ar ASN1-TYPE
+a
+.Dq hidden
+field named
+.Ar fname
+of the given external C type
+.Ar FIELD-C-TYPE ,
+declared in the given
+.Ar header
+but do not encode or decode this field.
+If the
+.Ar fname
+ends in a question mark, then treat the field as OPTIONAL.
+.Pp
+The
+.Ar header
+must include double quotes or angle brackets.
+The
+.Ar copyfn
+must be the name of a copy constructor function that takes a
+pointer to a source value of the type, and a pointer to a
+destination value of the type, in that order, and which returns
+zero on success or else a system error code on failure.
+The
+.Ar freefn
+must be the name of a destructor function that takes a pointer to
+a value of the type and which releases resources referenced by
+that value, but does not free the value itself (the run-time
+allocates this value as needed from the C heap).
+The
+.Ar freefn
+should also reset the value to a pristine state (such as all
+zeros).
+.Pp
+If the
+.Ar copyfn
+and
+.Ar freefn
+are empty strings, then the decoration field will neither be
+copied nor freed by the functions generated for the
+.Ar TYPE .
+.It Fl Fl one-code-file
+Generate a single source code file.
+Otherwise a separate code file will be generated for every type.
+.It Fl Fl gen-name=NAME
+Use
+.Ar NAME
+to form the names of the files generated.
+.It Fl Fl option-file=FILE
+Take additional command-line options from
+.Ar FILE .
+.It Fl Fl original-order
+Attempt to preserve the original order of type definition in the
+ASN.1 module.
+By default the compiler generates types in a topological sort
+order.
+.It Fl Fl no-parse-units
+Do not generate to-int / from-int functions for enumeration
+types.
+.It Fl Fl type-file=C-HEADER-FILE
+Generate an include of the named header file that might be needed
+for common type defintions.
+.It Fl Fl version
+.It Fl Fl help
+.El
+.Sh NOTES
+Currently only the template backend supports automatic encoding
+and decoding of open types via the ASN.1 Information Object
+System and X.681/X.682/X.683 annotations.
diff --git a/third_party/heimdal/lib/asn1/asn1_err.et b/third_party/heimdal/lib/asn1/asn1_err.et
new file mode 100644
index 0000000..ac7a9eb
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/asn1_err.et
@@ -0,0 +1,29 @@
+#
+# Error messages for the asn.1 library
+#
+# This might look like a com_err file, but is not
+#
+id "$Id$"
+
+error_table asn1
+prefix ASN1
+error_code BAD_TIMEFORMAT, "ASN.1 failed call to system time library"
+error_code MISSING_FIELD, "ASN.1 structure is missing a required field"
+error_code MISPLACED_FIELD, "ASN.1 unexpected field number"
+error_code TYPE_MISMATCH, "ASN.1 type numbers are inconsistent"
+error_code OVERFLOW, "ASN.1 value too large"
+error_code OVERRUN, "ASN.1 encoding ended unexpectedly"
+error_code BAD_ID, "ASN.1 identifier doesn't match expected value"
+error_code BAD_LENGTH, "ASN.1 length doesn't match expected value"
+error_code BAD_FORMAT, "ASN.1 badly-formatted encoding"
+error_code PARSE_ERROR, "ASN.1 parse error"
+error_code EXTRA_DATA, "ASN.1 extra data past end of end structure"
+error_code BAD_CHARACTER, "ASN.1 invalid character in string"
+error_code MIN_CONSTRAINT, "ASN.1 too few elements"
+error_code MAX_CONSTRAINT, "ASN.1 too many elements"
+error_code EXACT_CONSTRAINT, "ASN.1 wrong number of elements"
+error_code INDEF_OVERRUN, "ASN.1 BER indefinte encoding overrun"
+error_code INDEF_UNDERRUN, "ASN.1 BER indefinte encoding underun"
+error_code GOT_BER, "ASN.1 got BER encoded when expected DER"
+error_code INDEF_EXTRA_DATA, "ASN.1 EoC tag contained data"
+end
diff --git a/third_party/heimdal/lib/asn1/asn1_gen.c b/third_party/heimdal/lib/asn1/asn1_gen.c
new file mode 100644
index 0000000..6a0244f
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/asn1_gen.c
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+#include <com_err.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <ctype.h>
+#include <getarg.h>
+#include <hex.h>
+#include <err.h>
+
+RCSID("$Id$");
+
+static int
+doit(const char *fn)
+{
+ char buf[2048];
+ char *fnout = NULL;
+ const char *bname;
+ unsigned long line = 0;
+ FILE *f, *fout;
+ size_t offset = 0;
+
+ f = fopen(fn, "r");
+ if (f == NULL)
+ err(1, "fopen");
+
+ bname = strrchr(fn, '/');
+ if (bname)
+ bname++;
+ else
+ bname = fn;
+
+ if (asprintf(&fnout, "%s.out", bname) < 0 || fnout == NULL)
+ errx(1, "malloc");
+
+ fout = fopen(fnout, "w");
+ if (fout == NULL)
+ err(1, "fopen: output file");
+
+ while (fgets(buf, sizeof(buf), f) != NULL) {
+ char *ptr, *class, *type, *tag, *length, *data, *foo;
+ int ret, l, c, ty, ta;
+ unsigned char p[6], *pdata;
+ size_t sz;
+
+ line++;
+
+ buf[strcspn(buf, "\r\n")] = '\0';
+ if (buf[0] == '#' || buf[0] == '\0')
+ continue;
+
+ ptr = buf;
+ while (isspace((unsigned char)*ptr))
+ ptr++;
+
+ class = strtok_r(ptr, " \t\n", &foo);
+ if (class == NULL) errx(1, "class missing on line %lu", line);
+ type = strtok_r(NULL, " \t\n", &foo);
+ if (type == NULL) errx(1, "type missing on line %lu", line);
+ tag = strtok_r(NULL, " \t\n", &foo);
+ if (tag == NULL) errx(1, "tag missing on line %lu", line);
+ length = strtok_r(NULL, " \t\n", &foo);
+ if (length == NULL) errx(1, "length missing on line %lu", line);
+ data = strtok_r(NULL, " \t\n", &foo);
+
+ c = der_get_class_num(class);
+ if (c == -1) errx(1, "no valid class on line %lu", line);
+ ty = der_get_type_num(type);
+ if (ty == -1) errx(1, "no valid type on line %lu", line);
+ ta = der_get_tag_num(tag);
+ if (ta == -1)
+ ta = atoi(tag);
+
+ l = atoi(length);
+
+ printf("line: %3lu offset: %3lu class: %d type: %d "
+ "tag: %3d length: %3d %s\n",
+ line, (unsigned long)offset, c, ty, ta, l,
+ data ? "<have data>" : "<no data>");
+
+ ret = der_put_length_and_tag(p + sizeof(p) - 1, sizeof(p),
+ l,
+ c,
+ ty,
+ ta,
+ &sz);
+ if (ret)
+ errx(1, "der_put_length_and_tag: %d", ret);
+
+ if (fwrite(p + sizeof(p) - sz , sz, 1, fout) != 1)
+ err(1, "fwrite length/tag failed");
+ offset += sz;
+
+ if (data) {
+ size_t datalen;
+
+ datalen = strlen(data) / 2;
+ pdata = emalloc(sz);
+
+ if (hex_decode(data, pdata, datalen) != datalen)
+ errx(1, "failed to decode data");
+
+ if (fwrite(pdata, datalen, 1, fout) != 1)
+ err(1, "fwrite data failed");
+ offset += datalen;
+
+ free(pdata);
+ }
+ }
+ printf("line: eof offset: %lu\n", (unsigned long)offset);
+
+ if (fclose(fout) == EOF)
+ err(1, "writes to file %s failed", fnout);
+ fclose(f);
+ return 0;
+}
+
+
+static int version_flag;
+static int help_flag;
+struct getargs args[] = {
+ { "version", 0, arg_flag, &version_flag, NULL, NULL },
+ { "help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+int num_args = sizeof(args) / sizeof(args[0]);
+
+static void
+usage(int code)
+{
+ arg_printusage(args, num_args, NULL, "parse-file");
+ exit(code);
+}
+
+int
+main(int argc, char **argv)
+{
+ int optidx = 0;
+
+ setprogname (argv[0]);
+
+ if(getarg(args, num_args, argc, argv, &optidx))
+ usage(1);
+ if(help_flag)
+ usage(0);
+ if(version_flag) {
+ print_version(NULL);
+ exit(0);
+ }
+ argv += optidx;
+ argc -= optidx;
+ if (argc != 1)
+ usage (1);
+
+ return doit (argv[0]);
+}
diff --git a/third_party/heimdal/lib/asn1/asn1_print.1 b/third_party/heimdal/lib/asn1/asn1_print.1
new file mode 100644
index 0000000..8066b0b
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/asn1_print.1
@@ -0,0 +1,135 @@
+.\" Copyright (c) 2021 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd February 22, 2021
+.Dt ASN1_PRINT 1
+.Os HEIMDAL
+.Sh NAME
+.Nm asn1_print
+.Nd dump ASN.1 DER encoded values
+.Sh SYNOPSIS
+.Nm
+.Bk -words
+.Oo Fl i \*(Ba Xo Fl Fl no-indent Xc Oc
+.Oo Fl I \*(Ba Xo Fl Fl inner Xc Oc
+.Oo Fl l \*(Ba Xo Fl Fl list-types Xc Oc
+.Oo Fl A \*(Ba Xo Fl Fl try-all-types Xc Oc
+.Oo Fl S \*(Ba Xo Fl Fl raw-sequence Xc Oc
+.Oo Fl n \*(Ba Xo Fl Fl no-print Xc Oc
+.Oo Fl q \*(Ba Xo Fl Fl quiet Xc Oc
+.Oo Xo Fl Fl test-encode Xc Oc
+.Oo Xo Fl Fl test-copy Xc Oc
+.Oo Fl l v \*(Ba Xo
+.Fl Fl version
+.Xc
+.Oc
+.Oo Fl l h \*(Ba Xo
+.Fl Fl help
+.Xc
+.Oc
+.Op Ar FILE Op Ar TypeName...
+.Ek
+.Sh DESCRIPTION
+.Nm
+Dumps ASN.1 DER-encoded values.
+If one or more
+.Ar TypeName
+arguments are given, then
+.Nm
+will print the value in a JSON-like format using its knowledge of
+the ASN.1 modules defining those types, stopping at the first type
+for which it can successfully decode the value.
+If
+.Ar TypeNames
+are given, they must be the names of ASN.1 types exported by an
+ASN.1 modules that are compiled into
+.Nm .
+Use the
+.Fl Fl try-all-types
+option to attempt decoding as all ASN.1 types known to
+.Nm .
+If neither any
+.Ar TypeName
+nor
+.Fl Fl try-all-types
+are given, then the value will be parsed and displayed using just
+the self-describing nature of DER.
+.Pp
+Options supported:
+.Bl -tag -width Ds
+.It Fl i, Fl Fl no-indent
+Do not indent dump.
+.It Fl I, Fl Fl inner
+Try to parse inner structures of OCTET STRING and constructed values.
+.It Fl l, Fl Fl list-types
+List all types known to
+.Nm .
+.It Fl A, Fl Fl try-all-types
+Attempt to decode the value as any of all types known to
+.Nm .
+.It Fl S, Fl Fl raw-sequence
+If a value parses as a given
+.Ar TypeName
+but any bytes are left over, try to parse those separately as
+well until all bytes are consumed or an error occurs.
+.It Fl n, Fl Fl no-print
+For the case where
+.Fl A
+or
+.Fl Fl try-all-types
+or where a
+.Ar TypeName
+is given, do not output a JSON representation of the value, just
+attempt to decode it.
+This is useful for fuzzing.
+.It Fl q, Fl Fl quiet
+Similar to
+.Fl n, Fl Fl no-print
+but JSON output will be formatted, just not output.
+As with
+.Fl n, Fl Fl no-print,
+this option requires
+.Fl A / Fl Fl try-all-types
+or that a
+.Ar TypeName
+be given.
+This is useful for fuzzing.
+.It Fl Fl test-encode
+Check that encoding produces the same value as decoding.
+Useful for fuzzing.
+.It Fl Fl test-copy
+Test copy functions.
+Useful for fuzzing.
+.It Fl v, Fl Fl version
+.It Fl h, Fl Fl help
+.El
diff --git a/third_party/heimdal/lib/asn1/asn1_print.c b/third_party/heimdal/lib/asn1/asn1_print.c
new file mode 100644
index 0000000..40c37fb
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/asn1_print.c
@@ -0,0 +1,692 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+#include <com_err.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <dlfcn.h>
+#include <getarg.h>
+#include <err.h>
+#include <der.h>
+#include "cms_asn1.h"
+#include "digest_asn1.h"
+#include "krb5_asn1.h"
+#include "kx509_asn1.h"
+#include "ocsp_asn1.h"
+#include "pkcs10_asn1.h"
+#include "pkcs12_asn1.h"
+#include "pkcs8_asn1.h"
+#include "pkcs9_asn1.h"
+#include "pkinit_asn1.h"
+#include "rfc2459_asn1.h"
+#include "rfc4108_asn1.h"
+#ifdef ASN1_PRINT_SUPPORTED
+#include "x690sample_template_asn1.h"
+#else
+#include "x690sample_asn1.h"
+#endif
+
+static int quiet_flag = 0;
+static int print_flag = 1;
+static int test_copy_flag;
+static int test_encode_flag;
+static int sequence_flag;
+static int try_all_flag;
+static int indent_flag = 1;
+static int inner_flag;
+
+static unsigned long indefinite_form_loop;
+static unsigned long indefinite_form_loop_max = 10000;
+
+typedef size_t (*lengther)(void *);
+typedef int (*copyer)(const void *, void *);
+typedef int (*encoder)(unsigned char *, size_t, void *, size_t *);
+typedef int (*decoder)(const unsigned char *, size_t, void *, size_t *);
+typedef char *(*printer)(const void *, int);
+typedef void (*releaser)(void *);
+const struct types {
+ const char *name;
+ size_t sz;
+ copyer cpy;
+ lengther len;
+ decoder decode;
+ encoder encode;
+ printer print;
+ releaser release;
+} types[] = {
+#define ASN1_SYM_INTVAL(n, gn, gns, i)
+#define ASN1_SYM_OID(n, gn, gns)
+#ifdef ASN1_PRINT_SUPPORTED
+#define ASN1_SYM_TYPE(n, gn, gns) \
+ { \
+ n, \
+ sizeof(gns), \
+ (copyer)copy_ ## gns, \
+ (lengther)length_ ## gns, \
+ (decoder)decode_ ## gns, \
+ (encoder)encode_ ## gns, \
+ (printer)print_ ## gns, \
+ (releaser)free_ ## gns, \
+ },
+#else
+#define ASN1_SYM_TYPE(n, gn, gns) \
+ { \
+ n, \
+ sizeof(gns), \
+ (copyer)copy_ ## gns, \
+ (lengther)length_ ## gns, \
+ (decoder)decode_ ## gns, \
+ (encoder)encode_ ## gns, \
+ 0, \
+ (releaser)free_ ## gns, \
+ },
+#endif
+#include "cms_asn1_syms.c"
+#include "digest_asn1_syms.c"
+#include "krb5_asn1_syms.c"
+#include "kx509_asn1_syms.c"
+#include "ocsp_asn1_syms.c"
+#include "pkcs10_asn1_syms.c"
+#include "pkcs12_asn1_syms.c"
+#include "pkcs8_asn1_syms.c"
+#include "pkcs9_asn1_syms.c"
+#include "pkinit_asn1_syms.c"
+#include "rfc2459_asn1_syms.c"
+#include "rfc4108_asn1_syms.c"
+#ifdef ASN1_PRINT_SUPPORTED
+#include "x690sample_template_asn1_syms.c"
+#else
+#include "x690sample_asn1_syms.c"
+#endif
+};
+
+struct types sorted_types[sizeof(types)/sizeof(types[0])];
+
+static size_t
+loop (unsigned char *buf, size_t len, int indent)
+{
+ unsigned char *start_buf = buf;
+
+ while (len > 0) {
+ int ret;
+ Der_class class;
+ Der_type type;
+ unsigned int tag;
+ size_t sz;
+ size_t length;
+ size_t loop_length = 0;
+ int end_tag = 0;
+ const char *tagname;
+
+ ret = der_get_tag (buf, len, &class, &type, &tag, &sz);
+ if (ret)
+ errx (1, "der_get_tag: %s", error_message (ret));
+ if (sz > len)
+ errx (1, "unreasonable length (%u) > %u",
+ (unsigned)sz, (unsigned)len);
+ buf += sz;
+ len -= sz;
+ if (indent_flag) {
+ int i;
+ for (i = 0; i < indent; ++i)
+ printf (" ");
+ }
+ printf ("%s %s ", der_get_class_name(class), der_get_type_name(type));
+ tagname = der_get_tag_name(tag);
+ if (class == ASN1_C_UNIV && tagname != NULL)
+ printf ("%s = ", tagname);
+ else
+ printf ("tag %d = ", tag);
+ ret = der_get_length (buf, len, &length, &sz);
+ if (ret)
+ errx (1, "der_get_tag: %s", error_message (ret));
+ if (sz > len)
+ errx (1, "unreasonable tag length (%u) > %u",
+ (unsigned)sz, (unsigned)len);
+ buf += sz;
+ len -= sz;
+ if (length == ASN1_INDEFINITE) {
+ if ((class == ASN1_C_UNIV && type == PRIM && tag == UT_OctetString) ||
+ (class == ASN1_C_CONTEXT && type == CONS) ||
+ (class == ASN1_C_UNIV && type == CONS && tag == UT_Sequence) ||
+ (class == ASN1_C_UNIV && type == CONS && tag == UT_Set)) {
+ printf("*INDEFINITE FORM*");
+ } else {
+ fflush(stdout);
+ errx(1, "indef form used on unsupported object");
+ }
+ end_tag = 1;
+ if (indefinite_form_loop > indefinite_form_loop_max)
+ errx(1, "indefinite form used recursively more then %lu "
+ "times, aborting", indefinite_form_loop_max);
+ indefinite_form_loop++;
+ length = len;
+ } else if (length > len) {
+ printf("\n");
+ fflush(stdout);
+ errx (1, "unreasonable inner length (%u) > %u",
+ (unsigned)length, (unsigned)len);
+ }
+ if (class == ASN1_C_CONTEXT || class == ASN1_C_APPL) {
+ printf ("%lu bytes [%u]", (unsigned long)length, tag);
+ if (type == CONS) {
+ printf("\n");
+ loop_length = loop (buf, length, indent + 2);
+ } else {
+ printf(" IMPLICIT content\n");
+ }
+ } else if (class == ASN1_C_UNIV) {
+ switch (tag) {
+ case UT_EndOfContent:
+ printf (" INDEFINITE length was %lu\n",
+ (unsigned long)(buf - start_buf));
+ break;
+ case UT_Set :
+ case UT_Sequence :
+ printf ("%lu bytes {\n", (unsigned long)length);
+ loop_length = loop (buf, length, indent + 2);
+ if (indent_flag) {
+ int i;
+ for (i = 0; i < indent; ++i)
+ printf (" ");
+ printf ("}\n");
+ } else
+ printf ("} indent = %d\n", indent / 2);
+ break;
+ case UT_Integer : {
+ int val;
+
+ if (length <= sizeof(val)) {
+ ret = der_get_integer (buf, length, &val, NULL);
+ if (ret)
+ errx (1, "der_get_integer: %s", error_message (ret));
+ printf ("integer %d\n", val);
+ } else {
+ heim_integer vali;
+ char *p;
+
+ ret = der_get_heim_integer(buf, length, &vali, NULL);
+ if (ret)
+ errx (1, "der_get_heim_integer: %s",
+ error_message (ret));
+ ret = der_print_hex_heim_integer(&vali, &p);
+ if (ret)
+ errx (1, "der_print_hex_heim_integer: %s",
+ error_message (ret));
+ printf ("BIG NUM integer: length %lu %s\n",
+ (unsigned long)length, p);
+ free(p);
+ }
+ break;
+ }
+ case UT_OctetString : {
+ heim_octet_string str;
+ size_t i;
+
+ ret = der_get_octet_string (buf, length, &str, NULL);
+ if (ret)
+ errx (1, "der_get_octet_string: %s", error_message (ret));
+ printf ("(length %lu), ", (unsigned long)length);
+
+ if (inner_flag) {
+ Der_class class2;
+ Der_type type2;
+ unsigned int tag2;
+
+ ret = der_get_tag(str.data, str.length,
+ &class2, &type2, &tag2, &sz);
+ if (ret || sz > str.length ||
+ type2 != CONS || tag2 != UT_Sequence)
+ goto just_an_octet_string;
+
+ printf("{\n");
+ loop (str.data, str.length, indent + 2);
+ for (i = 0; i < indent; ++i)
+ printf (" ");
+ printf ("}\n");
+
+ } else {
+ unsigned char *uc;
+
+ just_an_octet_string:
+ uc = (unsigned char *)str.data;
+ for (i = 0; i < min(16,length); ++i)
+ printf ("%02x", uc[i]);
+ printf ("\n");
+ }
+ free (str.data);
+ break;
+ }
+ case UT_IA5String :
+ case UT_PrintableString : {
+ heim_printable_string str;
+ unsigned char *s;
+ size_t n;
+
+ memset(&str, 0, sizeof(str));
+
+ ret = der_get_printable_string (buf, length, &str, NULL);
+ if (ret)
+ errx (1, "der_get_general_string: %s",
+ error_message (ret));
+ s = str.data;
+ printf("\"");
+ for (n = 0; n < str.length; n++) {
+ if (isprint((int)s[n]))
+ printf ("%c", s[n]);
+ else
+ printf ("#%02x", s[n]);
+ }
+ printf("\"\n");
+ der_free_printable_string(&str);
+ break;
+ }
+ case UT_GeneralizedTime :
+ case UT_GeneralString :
+ case UT_VisibleString :
+ case UT_UTF8String : {
+ heim_general_string str;
+
+ ret = der_get_general_string (buf, length, &str, NULL);
+ if (ret)
+ errx (1, "der_get_general_string: %s",
+ error_message (ret));
+ printf ("\"%s\"\n", str);
+ free (str);
+ break;
+ }
+ case UT_OID: {
+ heim_oid o;
+ char *p;
+
+ ret = der_get_oid(buf, length, &o, NULL);
+ if (ret)
+ errx (1, "der_get_oid: %s", error_message (ret));
+ ret = der_print_heim_oid_sym(&o, '.', &p);
+ der_free_oid(&o);
+ if (ret)
+ errx (1, "der_print_heim_oid_sym: %s", error_message (ret));
+ printf("%s\n", p);
+ free(p);
+
+ break;
+ }
+ case UT_Enumerated: {
+ int num;
+
+ ret = der_get_integer (buf, length, &num, NULL);
+ if (ret)
+ errx (1, "der_get_enum: %s", error_message (ret));
+
+ printf("%u\n", num);
+ break;
+ }
+ default :
+ printf ("%lu bytes\n", (unsigned long)length);
+ break;
+ }
+ }
+ if (end_tag) {
+ if (loop_length == 0)
+ errx(1, "zero length INDEFINITE data ? indent = %d\n",
+ indent / 2);
+ if (loop_length < length)
+ length = loop_length;
+ if (indefinite_form_loop == 0)
+ errx(1, "internal error in indefinite form loop detection");
+ indefinite_form_loop--;
+ } else if (loop_length)
+ errx(1, "internal error for INDEFINITE form");
+ buf += length;
+ len -= length;
+ }
+ return 0;
+}
+
+static int
+type_cmp(const void *va, const void *vb)
+{
+ const struct types *ta = (const struct types *)va;
+ const struct types *tb = (const struct types *)vb;
+
+ return strcmp(ta->name, tb->name);
+}
+
+static int
+dotype(unsigned char *buf, size_t len, char **argv, size_t *size)
+{
+ const char *typename = "";
+ size_t matches = 0;
+ size_t sz;
+ size_t tried = 0;
+ size_t i = 0;
+ void *v;
+ int ret = 0;
+
+ *size = len;
+
+ memcpy(sorted_types, types, sizeof(types));
+ qsort(sorted_types,
+ sizeof(types)/sizeof(types[0]),
+ sizeof(types[0]),
+ type_cmp);
+
+ while ((try_all_flag && i < sizeof(types)/sizeof(types[0])) ||
+ (typename = (argv++)[0])) {
+
+ if (try_all_flag) {
+ typename = sorted_types[i].name;
+ } else {
+ size_t right = sizeof(types)/sizeof(types[0]) - 1;
+ size_t left = 0;
+ size_t mid = (left + right) >> 1;
+ int c = -1;
+
+ while (left <= right) {
+ mid = (left + right) >> 1;
+ c = strcmp(sorted_types[mid].name, typename);
+ if (c < 0)
+ left = mid + 1;
+ else if (c > 0)
+ right = mid - 1;
+ else
+ break;
+ }
+ if (c != 0)
+ errx(1, "Type %s not found", typename);
+ i = mid;
+ }
+ v = ecalloc(1, sorted_types[i].sz);
+ ret = sorted_types[i].decode(buf, len, v, &sz);
+ if (ret == 0) {
+ matches++;
+ if (!quiet_flag && sz == len) {
+ fprintf(stderr, "Match: %s\n", typename);
+ } else if (sequence_flag) {
+ *size = sz;
+ } else if (!quiet_flag) {
+ fprintf(stderr, "Prefix match: %s\n", typename);
+ }
+ if (print_flag) {
+ static int warned = 0;
+
+ if (!sorted_types[i].print) {
+ if (!warned)
+ warnx("Missing print support; try enabling / not "
+ "disabling ASN.1 templating in build "
+ "configuration");
+ warned = 1;
+ } else {
+ char *s;
+
+ s = sorted_types[i].print(v, indent_flag ? ASN1_PRINT_INDENT : 0);
+ if (!s)
+ err(1, "Could not print %s\n", typename);
+ if (!quiet_flag)
+ printf("%s\n", s);
+ free(s);
+ }
+ }
+ if (test_encode_flag) {
+ unsigned char *der = emalloc(sz);
+ size_t wants = sorted_types[i].len(v);
+
+ if (wants != sz)
+ errx(1, "Encoding will not round trip");
+ ret = sorted_types[i].encode(der + (sz - 1), sz, v, &sz);
+ if (ret != 0)
+ errx(1, "Encoding failed");
+ if (memcmp(buf, der, sz) != 0)
+ errx(1, "Encoding did not round trip");
+ free(der);
+ }
+ if (test_copy_flag) {
+ void *vcpy = ecalloc(1, sorted_types[i].sz);
+
+ ret = sorted_types[i].cpy(v, vcpy);
+ if (ret != 0)
+ errx(1, "Copy function failed");
+ if (test_encode_flag) {
+ unsigned char *der = emalloc(sz);
+ size_t wants = sorted_types[i].len(vcpy);
+
+ if (wants != sz)
+ errx(1, "Encoding of copy will not round trip");
+ ret = sorted_types[i].encode(der + (sz - 1), sz, vcpy, &sz);
+ if (ret != 0)
+ errx(1, "Encoding of copy failed");
+ if (memcmp(buf, der, sz) != 0)
+ errx(1, "Encoding of copy did not round trip");
+ free(der);
+ }
+ sorted_types[i].release(vcpy);
+ free(vcpy);
+ }
+ }
+ sorted_types[i].release(v);
+ free(v);
+ tried++;
+ i++;
+
+ if (ret == 0 && !try_all_flag && !argv[0])
+ return 0;
+
+ if (!try_all_flag && argv[0])
+ continue;
+
+ if (try_all_flag) {
+ if (i < sizeof(types)/sizeof(types[0]))
+ continue;
+ if (matches)
+ break;
+ }
+ if (tried > 1)
+ errx(1, "No type matched the input value");
+
+ /* XXX Use com_err */
+ switch (ret) {
+ case ASN1_BAD_TIMEFORMAT:
+ errx(1, "Could not decode and print data as type %s: "
+ "Bad time format", typename);
+ case ASN1_MISSING_FIELD:
+ errx(1, "Could not decode and print data as type %s: "
+ "Missing required field", typename);
+ case ASN1_MISPLACED_FIELD:
+ errx(1, "Could not decode and print data as type %s: "
+ "Fields out of order", typename);
+ case ASN1_TYPE_MISMATCH:
+ errx(1, "Could not decode and print data as type %s: "
+ "Type mismatch", typename);
+ case ASN1_OVERFLOW:
+ errx(1, "Could not decode and print data as type %s: "
+ "DER value too large", typename);
+ case ASN1_OVERRUN:
+ errx(1, "Could not decode and print data as type %s: "
+ "DER value too short", typename);
+ case ASN1_BAD_ID:
+ errx(1, "Could not decode and print data as type %s: "
+ "DER tag is unexpected", typename);
+ case ASN1_BAD_LENGTH:
+ errx(1, "Could not decode and print data as type %s: "
+ "DER length does not match value", typename);
+ case ASN1_BAD_FORMAT:
+ case ASN1_PARSE_ERROR:
+ errx(1, "Could not decode and print data as type %s: "
+ "DER badly formatted", typename);
+ case ASN1_EXTRA_DATA:
+ errx(1, "Could not decode and print data as type %s: "
+ "Extra data past end of end structure", typename);
+ case ASN1_BAD_CHARACTER:
+ errx(1, "Could not decode and print data as type %s: "
+ "Invalid character encoding in string", typename);
+ case ASN1_MIN_CONSTRAINT:
+ errx(1, "Could not decode and print data as type %s: "
+ "Too few elements", typename);
+ case ASN1_MAX_CONSTRAINT:
+ errx(1, "Could not decode and print data as type %s: "
+ "Too many elements", typename);
+ case ASN1_EXACT_CONSTRAINT:
+ errx(1, "Could not decode and print data as type %s: "
+ "Wrong count of elements", typename);
+ case ASN1_INDEF_OVERRUN:
+ errx(1, "Could not decode and print data as type %s: "
+ "BER indefinte encoding overun", typename);
+ case ASN1_INDEF_UNDERRUN:
+ errx(1, "Could not decode and print data as type %s: "
+ "BER indefinte encoding underun", typename);
+ case ASN1_GOT_BER:
+ errx(1, "Could not decode and print data as type %s: "
+ "BER encoding when DER expected", typename);
+ case ASN1_INDEF_EXTRA_DATA:
+ errx(1, "Could not decode and print data as type %s: "
+ "End-of-contents tag contains data", typename);
+ default:
+ errx(1, "Could not decode and print data as type %s", typename);
+ }
+ }
+ return 0;
+}
+
+static int
+doit(char **argv)
+{
+ int fd = open(argv[0], O_RDONLY);
+ struct stat sb;
+ unsigned char *buf;
+ size_t len;
+ int ret;
+
+ if(fd < 0)
+ err(1, "opening %s for read", argv[0]);
+ if (fstat (fd, &sb) < 0)
+ err(1, "stat %s", argv[0]);
+ len = sb.st_size;
+ buf = emalloc(len);
+ if (read(fd, buf, len) != len)
+ errx(1, "read failed");
+ close(fd);
+
+ argv++;
+ if (argv[0] || try_all_flag) {
+ size_t off = 0;
+ size_t sz = 0;
+
+ do {
+ ret = dotype(buf + off, len - off, argv, &sz);
+ off += sz;
+ } while (ret == 0 && sequence_flag && off < len);
+ } else {
+ ret = loop(buf, len, 0);
+ }
+ free(buf);
+ return ret;
+}
+
+
+static int list_types_flag;
+static int version_flag;
+static int help_flag;
+struct getargs args[] = {
+ { "indent", 'i', arg_negative_flag, &indent_flag,
+ "\tdo not indent dump", NULL },
+ { "inner", 'I', arg_flag, &inner_flag,
+ "\ttry to parse inner structures of OCTET STRING", NULL },
+ { "list-types", 'l', arg_flag, &list_types_flag,
+ "\tlist ASN.1 types known to this program", NULL },
+ { "try-all-types", 'A', arg_flag, &try_all_flag,
+ "\ttry all known types", NULL },
+ { "raw-sequence", 'S', arg_flag, &sequence_flag,
+ "\ttry parsing leftover data", NULL },
+ { "test-encode", 0, arg_flag, &test_encode_flag,
+ "\ttest encode round trip (for memory debugging and fuzzing)", NULL },
+ { "test-copy", 0, arg_flag, &test_copy_flag,
+ "\ttest copy operation (for memory debugging and fuzzing)", NULL },
+ { "print", 'n', arg_negative_flag, &print_flag,
+ "\ttest copy operation (for memory debugging and fuzzing)", NULL },
+ { "quiet", 'q', arg_flag, &quiet_flag,
+ "\tOutput nothing (exit status 0 means type matched)", NULL },
+ { "version", 'v', arg_flag, &version_flag, NULL, NULL },
+ { "help", 'h', arg_flag, &help_flag, NULL, NULL }
+};
+int num_args = sizeof(args) / sizeof(args[0]);
+
+static void
+usage(int code)
+{
+ arg_printusage(args, num_args, NULL, "dump-file [TypeName [TypeName ...]]");
+ exit(code);
+}
+
+int
+main(int argc, char **argv)
+{
+ int optidx = 0;
+
+ setprogname(argv[0]);
+ initialize_asn1_error_table();
+ if (getarg(args, num_args, argc, argv, &optidx))
+ usage(1);
+ if (help_flag)
+ usage(0);
+ if (version_flag) {
+ print_version(NULL);
+ exit(0);
+ }
+ argv += optidx;
+ argc -= optidx;
+
+ if (sequence_flag && try_all_flag)
+ errx(1, "--raw-sequence and --try-all-types are mutually exclusive");
+ if (quiet_flag && !try_all_flag && argc < 2)
+ errx(1, "--quiet requires --try-all-types or that a TypeName be given");
+ if (!print_flag && !try_all_flag && argc < 2)
+ errx(1, "--no-print requires --try-all-types or that a TypeName be given");
+
+ if (list_types_flag) {
+ size_t i;
+
+ if (argc)
+ errx(1, "--list-types is exclusive of other options or arguments");
+
+ for (i = 0; i < sizeof(types)/sizeof(types[0]); i++)
+ printf("%s\n", types[i].name);
+ exit(0);
+ }
+
+ if (argc < 1)
+ usage(1);
+ return doit(argv);
+}
diff --git a/third_party/heimdal/lib/asn1/asn1parse.y b/third_party/heimdal/lib/asn1/asn1parse.y
new file mode 100644
index 0000000..f6f6ec0
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/asn1parse.y
@@ -0,0 +1,2034 @@
+/*
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+%{
+
+#include <config.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+#include "symbol.h"
+#include "lex.h"
+#include "gen_locl.h"
+#include "der.h"
+
+static Type *new_type (Typetype t);
+/*static IOSClass *new_class(struct fieldhead *);*/
+/*static IOSObject *new_object(struct objfieldhead *);*/
+/*IOSObjectSet *new_object_set(struct objectshead *);*/
+static struct objectshead *add_object_set_spec(struct objectshead *, IOSObject *);
+static ObjectField *new_field_setting(char *, Type *, struct value *);
+static struct objfieldhead *add_field_setting(struct objfieldhead *, ObjectField *);
+static struct fieldhead *add_field_spec(struct fieldhead *, Field *);
+static Field *new_type_field(char *, int, Type *);
+static Field *new_fixed_type_value_field(char *, Type *, int, int, struct value *);
+static Type *parametrize_type(Type *, IOSClass *);
+static Type *type_from_class_field(IOSClass *, const char *);
+static void validate_object_set(IOSObjectSet *);
+/*static Type *type_from_object(const char *, const char *);*/
+static struct constraint_spec *new_constraint_spec(enum ctype);
+static Type *new_tag(int tagclass, int tagvalue, int tagenv, Type *oldtype);
+void yyerror (const char *);
+#define yyerror yyerror
+static struct objid *new_objid(const char *label, int value);
+static void add_oid_to_tail(struct objid *, struct objid *);
+static void fix_labels(Symbol *s);
+
+struct string_list {
+ char *string;
+ struct string_list *next;
+};
+
+static int default_tag_env = TE_EXPLICIT;
+static unsigned long idcounter;
+
+/* Declarations for Bison */
+#define YYMALLOC malloc
+#define YYFREE free
+
+%}
+
+%union {
+ int64_t constant;
+ struct value *value;
+ struct range *range;
+ char *name;
+ Type *type;
+ IOSClass *class;
+ IOSObjectSet *objectset;
+ IOSObject *object;
+ Field *field;
+ ObjectField *objfield;
+ Member *member;
+ IOSClass *formalparam;
+ struct objid *objid;
+ char *defval;
+ struct string_list *sl;
+ struct tagtype tag;
+ struct memhead *members;
+ struct fieldhead *fields;
+ struct objectshead *objects;
+ struct objfieldhead *objfields;
+ struct constraint_spec *constraint_spec;
+}
+
+%token kw_ABSENT
+%token kw_ABSTRACT_SYNTAX
+%token kw_ALL
+%token kw_APPLICATION
+%token kw_AUTOMATIC
+%token kw_BEGIN
+%token kw_BIT
+%token kw_BMPString
+%token kw_BOOLEAN
+%token kw_BY
+%token kw_CHARACTER
+%token kw_CHOICE
+%token kw_CLASS
+%token kw_COMPONENT
+%token kw_COMPONENTS
+%token kw_CONSTRAINED
+%token kw_CONTAINING
+%token kw_DEFAULT
+%token kw_DEFINITIONS
+%token kw_EMBEDDED
+%token kw_ENCODED
+%token kw_END
+%token kw_ENUMERATED
+%token kw_EXCEPT
+%token kw_EXPLICIT
+%token kw_EXPORTS
+%token kw_EXTENSIBILITY
+%token kw_EXTERNAL
+%token kw_FALSE
+%token kw_FROM
+%token kw_GeneralString
+%token kw_GeneralizedTime
+%token kw_GraphicString
+%token kw_IA5String
+%token kw_IDENTIFIER
+%token kw_IMPLICIT
+%token kw_IMPLIED
+%token kw_IMPORTS
+%token kw_INCLUDES
+%token kw_INSTANCE
+%token kw_INTEGER
+%token kw_INTERSECTION
+%token kw_ISO646String
+%token kw_MAX
+%token kw_MIN
+%token kw_MINUS_INFINITY
+%token kw_NULL
+%token kw_NumericString
+%token kw_OBJECT
+%token kw_OCTET
+%token kw_OF
+%token kw_OPTIONAL
+%token kw_ObjectDescriptor
+%token kw_PATTERN
+%token kw_PDV
+%token kw_PLUS_INFINITY
+%token kw_PRESENT
+%token kw_PRIVATE
+%token kw_PrintableString
+%token kw_REAL
+%token kw_RELATIVE_OID
+%token kw_SEQUENCE
+%token kw_SET
+%token kw_SIZE
+%token kw_STRING
+%token kw_SYNTAX
+%token kw_T61String
+%token kw_TAGS
+%token kw_TRUE
+%token kw_TYPE_IDENTIFIER
+%token kw_TeletexString
+%token kw_UNION
+%token kw_UNIQUE
+%token kw_UNIVERSAL
+%token kw_UTCTime
+%token kw_UTF8String
+%token kw_UniversalString
+%token kw_VideotexString
+%token kw_VisibleString
+%token kw_WITH
+
+%token RANGE
+%token EEQUAL
+%token ELLIPSIS
+
+%token <name> TYPE_IDENTIFIER referencename
+%token <name> CLASS_IDENTIFIER
+%token <name> VALUE_IDENTIFIER
+%token <name> STRING
+
+%token <constant> NUMBER
+%type <constant> SignedNumber
+%type <constant> Class tagenv
+%type <constant> DummyReference
+
+%type <name> Identifier
+
+/*
+ * The NULL keyword being both a value and a type causes a reduce/reduce
+ * conflict in the FieldSetting production since its alternatives are
+ *
+ * '&' Identifier Type
+ *
+ * and
+ *
+ * '&' Identifier Value
+ *
+ * and NULL is both a type and a value.
+ *
+ * For now we work around this by having a ValueExNull production that excludes
+ * the NULL value. To really get past this will require unifying the type and
+ * value types (e.g., via type punning).
+ */
+%type <value> Value ValueExNull
+%type <value> BuiltinValue BuiltinValueExNull
+%type <value> IntegerValue
+%type <value> BooleanValue
+%type <value> ObjectIdentifierValue
+%type <value> CharacterStringValue
+%type <value> NullValue
+%type <value> DefinedValue
+%type <value> ReferencedValue
+%type <value> Valuereference
+
+%type <class> DefinedObjectClass ParamGovernor
+%type <class> ObjectClassDefn
+%type <class> Parameter
+
+%type <type> Type
+%type <type> BuiltinType
+%type <type> BitStringType
+%type <type> BooleanType
+%type <type> ChoiceType
+%type <type> ConstrainedType
+%type <type> UnconstrainedType
+%type <type> EnumeratedType
+%type <type> IntegerType
+%type <type> NullType
+%type <type> OctetStringType
+%type <type> SequenceType
+%type <type> SequenceOfType
+%type <type> SetType
+%type <type> SetOfType
+%type <type> TaggedType
+%type <type> ReferencedType
+%type <type> DefinedType
+%type <type> UsefulType
+%type <type> ObjectIdentifierType
+%type <type> CharacterStringType
+%type <type> RestrictedCharactedStringType
+%type <type> ObjectClassFieldType
+%type <type> ParameterizedType
+/*%type <type> TypeFromObject*/
+
+%type <objectset> ObjectSet DefinedObjectSet
+%type <objectset> ActualParameter
+%type <object> Object DefinedObject ObjectDefn
+%type <objfield> FieldSetting
+
+%type <tag> Tag
+
+%type <field> FieldSpec TypeFieldSpec FixedTypeValueFieldSpec
+%type <fields> FieldSpecList
+%type <member> ComponentType
+%type <member> NamedBit
+%type <member> NamedNumber
+%type <member> NamedType
+%type <members> ComponentTypeList
+%type <members> Enumerations
+%type <members> NamedBitList
+%type <members> NamedNumberList
+%type <objects> ObjectSetSpec
+%type <objfields> FieldSettings
+
+%type <objid> objid objid_list objid_element objid_opt
+%type <range> range size
+
+%type <sl> referencenames
+
+%type <constraint_spec> Constraint
+%type <constraint_spec> ConstraintSpec
+%type <constraint_spec> SubtypeConstraint
+%type <constraint_spec> GeneralConstraint
+%type <constraint_spec> ContentsConstraint
+%type <constraint_spec> UserDefinedConstraint
+%type <constraint_spec> SimpleTableConstraint TableConstraint
+%type <constraint_spec> ComponentRelationConstraint
+
+
+%start ModuleDefinition
+
+%%
+
+/*
+ * We have sinned by allowing types to have names that start with lower-case,
+ * and values that have names that start with upper-case.
+ *
+ * UPDATE: We sin no more. However, parts of this block comment are still
+ * relevant.
+ *
+ * That worked when we only supported basic X.680 because the rules for
+ * TypeAssignment and ValueAssignment are clearly unambiguous in spite of the
+ * case issue.
+ *
+ * We now pay the price because X.681 adds productions where the only thing we
+ * have to help us distinguish certain rules is the form of an identifier: the
+ * case of its first letter.
+ *
+ * We have cleansed our sin by not allowing wrong-case identifiers any more.
+ *
+ * Some historical instances of this sin in-tree:
+ *
+ * - DOMAIN-X500-COMPRESS (value (enum) but name starts with upper-case)
+ * - krb5int32 (type but name starts with lower-case)
+ * - krb5uint32 (type but name starts with lower-case)
+ * - hdb_keyset (type but name starts with lower-case)
+ * - hdb_entry (type but name starts with lower-case)
+ * - hdb_entry_alias (type but name starts with lower-case)
+ * - HDB_DB_FORMAT INTEGER (value (int) but name starts with upper-case)
+ *
+ * We have fixed all of these and others, in some cases leaving behind aliases
+ * in header files as needed.
+ *
+ * We have one shift/reduce conflict (shift ObjectClassAssignment, reduce
+ * TypeAssignment) and one reduce/reduce conflict (ObjectAssignment vs
+ * ValueAssignment) that we avoid by requiring CLASS names to start with an
+ * underscore.
+ *
+ * In the FieldSetting rule, also, we get a reduce/reduce conflict if we use
+ * `Identifier' instead of `TYPE_IDENTIFIER' for type field settings and
+ * `VALUE_IDENTIFIER' for value field settings, and then we can't make
+ * progress.
+ *
+ * Looking forward, we may not (will not) be able to distinguish ValueSet and
+ * ObjectSet field settings from each other either, and we may not (will not)
+ * be able distinguish Object and Value field settings from each other as well.
+ * To deal with those we will have to run-time type-tag and type-pun the C
+ * structures for valueset/objectset and value/object, and have one rule for
+ * each of those that inspects the type of the item to decide what kind of
+ * setting it is.
+ *
+ * Sadly, the extended syntax for ASN.1 (x.680 + x.681/2/3) appears to have
+ * ambiguities that cannot be resolved with bison/yacc.
+ */
+Identifier : TYPE_IDENTIFIER { $$ = $1; }
+ | VALUE_IDENTIFIER { $$ = $1; };
+
+ModuleDefinition: Identifier objid_opt kw_DEFINITIONS TagDefault ExtensionDefault
+ EEQUAL kw_BEGIN ModuleBody kw_END
+ {
+ struct objid **o = objid2list($2);
+ size_t i;
+
+ fprintf(jsonfile,
+ "{\"module\":\"%s\",\"tagging\":\"%s\",\"objid\":[", $1,
+ default_tag_env == TE_EXPLICIT ? "explicit" : "implicit");
+
+ for (i = 0; o && o[i]; i++) {
+ fprintf(jsonfile, "%s{\"value\":%d", i ? "," : "", o[i]->value);
+ if (o[i]->label)
+ fprintf(jsonfile, ",\"label\":\"%s\"", o[i]->label);
+ fprintf(jsonfile, "}");
+ }
+ fprintf(jsonfile, "]}\n");
+ free(o);
+ }
+ ;
+
+TagDefault : kw_EXPLICIT kw_TAGS
+ { default_tag_env = TE_EXPLICIT; }
+ | kw_IMPLICIT kw_TAGS
+ { default_tag_env = TE_IMPLICIT; }
+ | kw_AUTOMATIC kw_TAGS
+ { lex_error_message("automatic tagging is not supported"); }
+ | /* empty */
+ ;
+
+ExtensionDefault: kw_EXTENSIBILITY kw_IMPLIED
+ { lex_error_message("no extensibility options supported"); }
+ | /* empty */
+ ;
+
+ModuleBody : Exports Imports AssignmentList
+ | /* empty */
+ ;
+
+Imports : kw_IMPORTS SymbolsImported ';'
+ | /* empty */
+ ;
+
+SymbolsImported : SymbolsFromModuleList
+ | /* empty */
+ ;
+
+SymbolsFromModuleList: SymbolsFromModule
+ | SymbolsFromModuleList SymbolsFromModule
+ ;
+
+SymbolsFromModule: referencenames kw_FROM Identifier objid_opt
+ {
+ /*
+ * FIXME We really could use knowing what kind of thing the
+ * identifier identifies -- a type, a value, what?
+ *
+ * Our sin of allowing type names to start with lower-case
+ * and values with upper-case means we can't tell. So we
+ * assume it's types only, but that means we can't import
+ * OID values, but we really want to!
+ *
+ * One thing we could do is not force `s->stype = Stype'
+ * here, instead set it to a new `Sunknown' value so that
+ * the first place that refers to this symbol with enough
+ * context to imply a symbol type can set it.
+ */
+ struct string_list *sl;
+ for(sl = $1; sl != NULL; sl = sl->next) {
+ Symbol *s = addsym(sl->string);
+ s->stype = Stype;
+ gen_template_import(s);
+ }
+ add_import($3);
+ }
+ ;
+
+Exports : kw_EXPORTS referencenames ';'
+ {
+ struct string_list *sl;
+ for(sl = $2; sl != NULL; sl = sl->next)
+ add_export(sl->string);
+ }
+ | kw_EXPORTS kw_ALL
+ | /* empty */
+ ;
+
+AssignmentList : Assignment
+ | Assignment AssignmentList
+ ;
+
+Assignment : TypeAssignment
+ | ValueAssignment
+ | ParameterizedTypeAssignment
+ | ObjectClassAssignment
+ | ObjectAssignment
+ | ObjectSetAssignment
+ /* | ParameterizedAssignment // from X.683 */
+ ;
+
+referencenames : Identifier ',' referencenames
+ {
+ $$ = emalloc(sizeof(*$$));
+ $$->string = $1;
+ $$->next = $3;
+ }
+ | Identifier
+ {
+ $$ = emalloc(sizeof(*$$));
+ $$->string = $1;
+ $$->next = NULL;
+ }
+ ;
+
+DefinedObjectClass
+ : CLASS_IDENTIFIER
+ {
+ Symbol *s = addsym($1);
+ if(s->stype != Sclass)
+ lex_error_message ("%s is not a class\n", $1);
+ $$ = s->iosclass;
+ };
+
+ObjectClassAssignment
+ : CLASS_IDENTIFIER EEQUAL ObjectClassDefn
+ {
+ Symbol *s = addsym($1);
+ s->stype = Sclass;
+ s->iosclass = $3;
+ s->iosclass->symbol = s;
+ fix_labels(s);
+ }
+ | CLASS_IDENTIFIER EEQUAL DefinedObjectClass
+ {
+ Symbol *s = addsym($1);
+ s->stype = Sclass;
+ s->iosclass = $3;
+ }
+ /* | ParameterizedObjectClass */
+ ;
+
+ObjectClassDefn : kw_CLASS '{' FieldSpecList '}'
+ {
+ $$ = ecalloc(1, sizeof(*$$));
+ $$->fields = $3;
+ $$->id = idcounter++;
+ };
+
+ObjectAssignment: VALUE_IDENTIFIER DefinedObjectClass EEQUAL Object
+ {
+ Symbol *s = addsym($1);
+ s->stype = Sobj;
+ s->object = $4;
+ s->object->iosclass = $2;
+ if (!s->object->symbol)
+ s->object->symbol = s;
+ fix_labels(s);
+ }
+ ;
+
+ObjectSetAssignment
+ : TYPE_IDENTIFIER DefinedObjectClass EEQUAL ObjectSet
+ {
+ Symbol *s = addsym($1);
+ s->stype = Sobjset;
+ s->iosclass = $2;
+ s->objectset = $4;
+ s->objectset->symbol = s->objectset->symbol ? s->objectset->symbol : s;
+ s->objectset->iosclass = $2;
+ validate_object_set($4);
+ generate_template_objectset_forwards(s);
+ }
+ ;
+
+ObjectSet : '{' ObjectSetSpec '}'
+ {
+ $$ = ecalloc(1, sizeof(*$$));
+ $$->objects = $2;
+ $$->id = idcounter++;
+ }
+ ;
+
+ObjectSetSpec : DefinedObject
+ { $$ = add_object_set_spec(NULL, $1); }
+ | ObjectSetSpec '|' DefinedObject
+ { $$ = add_object_set_spec($1, $3); }
+ ;
+
+Object : DefinedObject
+ | ObjectDefn
+ /* | ObjectFromObject */
+ /* | ParameterizedObject */
+ ;
+
+DefinedObject : VALUE_IDENTIFIER
+ {
+ Symbol *s = addsym($1);
+ if(s->stype != Sobj)
+ lex_error_message ("%s is not an object\n", $1);
+ $$ = s->object;
+ }
+ ;
+
+DefinedObjectSet: TYPE_IDENTIFIER
+ {
+ Symbol *s = addsym($1);
+ if(s->stype != Sobjset && s->stype != SUndefined)
+ lex_error_message ("%s is not an object set\n", $1);
+ $$ = s->objectset;
+ }
+ ;
+
+
+ObjectDefn : '{' FieldSettings '}' /* DefaultSyntax */
+ {
+ $$ = ecalloc(1, sizeof(*$$));
+ $$->objfields = $2;
+ $$->id = idcounter++;
+ }
+ /* | DefinedSyntax */
+ ;
+
+FieldSettings : FieldSetting
+ {
+ $$ = add_field_setting(NULL, $1);
+ }
+ | FieldSettings ',' FieldSetting
+ {
+ $$ = add_field_setting($1, $3);
+ }
+ ;
+
+/* See note on `Identifier' */
+FieldSetting : '&' Identifier Type
+ { $$ = new_field_setting($2, $3, NULL); }
+ | '&' Identifier ValueExNull
+ { $$ = new_field_setting($2, NULL, $3); }
+ /* | '&' TYPE_IDENTIFIER ValueSet */
+ /* | '&' VALUE_IDENTIFIER Object */
+ /* | '&' TYPE_IDENTIFIER ObjectSet */
+ ;
+
+/* Fields of a class */
+FieldSpecList : FieldSpec
+ { $$ = add_field_spec(NULL, $1); }
+ | FieldSpecList ',' FieldSpec
+ { $$ = add_field_spec($1, $3); };
+
+/*
+ * Fields of a CLASS
+ *
+ * There are seven kinds of class/object fields:
+ *
+ * - type fields,
+ * - fixed-type value fields,
+ * - fixed-type value set fields,
+ * - variable-type value fields
+ * - variable-type value set fields
+ * - object fields
+ * - object set fields
+ *
+ * We care only to support the bare minimum to treat open types as a CHOICE of
+ * sorts and automatically encode/decode values in open types. That's: type
+ * fields and fixed-type value fields.
+ */
+FieldSpec : TypeFieldSpec
+ | FixedTypeValueFieldSpec
+ /* | VariableTypeValueFieldSpec */
+ /* | VariableTypeValueSetFieldSpec */
+ /* | FixedTypeValueSetFieldSpec */
+ /* | ObjectFieldSpec */
+ /* | ObjectSetFieldSpec */
+ ;
+TypeFieldSpec : '&' Identifier
+ { $$ = new_type_field($2, 0, NULL); }
+ | '&' Identifier kw_OPTIONAL
+ { $$ = new_type_field($2, 1, NULL); }
+ | '&' Identifier kw_DEFAULT Type
+ { $$ = new_type_field($2, 1, $4); }
+ ;
+
+FixedTypeValueFieldSpec
+ : '&' Identifier Type
+ { $$ = new_fixed_type_value_field($2, $3, 0, 0, NULL); }
+ | '&' Identifier Type kw_UNIQUE
+ { $$ = new_fixed_type_value_field($2, $3, 1, 0, NULL); }
+ | '&' Identifier Type kw_UNIQUE kw_OPTIONAL
+ { $$ = new_fixed_type_value_field($2, $3, 1, 1, NULL); }
+ | '&' Identifier Type kw_UNIQUE kw_DEFAULT Value
+ { $$ = new_fixed_type_value_field($2, $3, 1, 0, $6); }
+ | '&' Identifier Type kw_OPTIONAL
+ { $$ = new_fixed_type_value_field($2, $3, 0, 1, NULL); }
+ | '&' Identifier Type kw_DEFAULT Value
+ { $$ = new_fixed_type_value_field($2, $3, 0, 0, $5); };
+
+/*
+ * Now we need a bit of X.683, just enough to parse PKIX.
+ *
+ * E.g., we need to parse this sort of type definition, which isn't quite the
+ * final type definition because the ExtensionSet will be provided later.
+ *
+ *-- <- ObjectClassDefn ->
+ * EXTENSION ::= CLASS {
+ * &id OBJECT IDENTIFIER UNIQUE,
+ * -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ * -- FixedTypeValueFieldSpec
+ *
+ * &ExtnType,
+ * -- ^^^^^^^^^
+ * -- TypeFieldSpec
+ *
+ * &Critical BOOLEAN DEFAULT {TRUE | FALSE }
+ * -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ * -- FixedTypeValueFieldSpec
+ * } WITH SYNTAX {
+ * SYNTAX &ExtnType IDENTIFIED BY &id
+ * [CRITICALITY &Critical]
+ * }
+ *
+ *-- <--------- ParameterizedTypeAssignment -------->
+ * -- NOTE: The name of this type has to be Extension, really.
+ * -- But the name of the Extension type with the actual
+ * -- parameter provided also has to be Extension.
+ * -- We could disallow that and require that the various
+ * -- Extension types all have different names, then we'd
+ * -- let the one with the actual parameter in PKIX be the
+ * -- one named Extension. Or we could find a way to let
+ * -- them all share one symbol name, or at least two:
+ * -- the one with the formal parameter, and just one with
+ * -- an actual parameter.
+ * --
+ * -- Also, IMPORTing types that have formal parameters is
+ * -- almost certainly going to require parsing the IMPORTed
+ * -- module. Until we do that, users will be able to work
+ * -- around that by just copying CLASSes and pameterized
+ * -- type definitions around. But when we do start parsing
+ * -- IMPORTed modules we might need to do something about
+ * -- many types possibly having the same names, though we
+ * -- might do nothing and simply say "don't do that!".
+ * Extension{EXTENSION:ExtensionSet} ::= SEQUENCE {
+ * -- ^^^^^^^^^^^^
+ * -- is a DummyReference, which is a Reference, basically
+ * -- it is an object set variable which will have an object
+ * -- set value supplied where constrained types are defined
+ * -- from this one, possibly anonymous types where
+ * -- SEQUENCE/SET members of this type are defined.
+ * -- ^^^^^^^^^
+ * -- is a ParamGovernor, really, just Governor, either a Type or
+ * -- DefinedObjectClass (we only need DefinedObjectClass)
+ * -- ^^^^^^^^^^^^^^^^^^^^^^
+ * -- is a Parameter
+ * -- ^^^^^^^^^^^^^^^^^^^^^^^^
+ * -- is a ParameterList (we need only support one param though)
+ * extnID EXTENSION.&id({ExtensionSet}),
+ * -- ^^^^^^^^^^^^^^^^
+ * -- simple table constraint limiting id to OIDs
+ * -- from ExtensionSet
+ * -- ^^^^^^^^^^^^^
+ * -- a reference to the id field of the EXTENSION CLASS
+ * critical BOOLEAN DEFAULT FALSE,
+ * extnValue OCTET STRING (CONTAINING
+ * -- ObjectClassFieldType
+ * -- vvvvvvvvvvvvvvvvvvv
+ * EXTENSION.&ExtnType({ExtensionSet}{@extnID}))
+ * -- ^^^^^^^^^
+ * -- AtNotation
+ * -- ^^^^^^^^^^^^^^
+ * -- DefinedObjectSet
+ * -- ^^^^^^^^^^^^^^^^^^^^^^^^
+ * -- ComponentRelationConstraint
+ * -- says that extnValue will contain
+ * -- a value of a type identified by
+ * -- the OID in extnID in the object
+ * -- set ExtensionSet (which is a set
+ * -- of {OID, type} objects)
+ * -- ^^^^^^^^^^^^^^^^^^^^^^^^^^
+ * -- ConstraintSpec
+ * -- ^^^^^^^^^^^^^^^^^^^
+ * -- another type ref
+ * }
+ *
+ * Then later we'll see (ParameterizedType, a part of DefinedType):
+ *
+ * TBSCertificate ::= SEQUENCE {
+ * ...
+ * -- Here is where the object set is linked into the
+ * -- whole thing, making *magic* possible. This is
+ * -- where the real Extensions type is defined. Sadly
+ * -- this might mean we can't have a C type named
+ * -- Extensions. Hmmm. We might need an ASN.1
+ * -- extension that lets use do this:
+ * --
+ * -- Extension ::= Extension{{CertExtensions}}
+ * --
+ * -- or
+ * --
+ * -- Extension ::= ParameterizedExtension{{CertExtensions}}
+ * --
+ * -- and then rename the Extension type above to this.
+ * -- Then we can define Extensions as a SEQUENCE OF
+ * -- that.
+ * --
+ * -- <- ParameterizedType ->
+ * extensions [3] Extensions{{CertExtensions}} OPTIONAL
+ * -- ^^^^^^^^^^^^^^
+ * -- ObjectSetSpec
+ * -- ^^^^^^^^^^^^^^^^
+ * -- ObjectSet
+ * -- ^^^^^^^^^^^^^^^^^^
+ * -- ActualParameterList
+ * -- ^^^^^^^^^^
+ * -- Type
+ * }
+ *
+ * Then:
+ *
+ * -- Object set, limits what Extensions can be in TBSCertificate.
+ *-- <- ObjectSetAssignment ->
+ * CertExtensions EXTENSION ::= {
+ * -- ^^^^^^^^^
+ * -- DefinedObjectClass
+ *-- ^^^^^^^^^^^^^^
+ *-- objectsetreference, for us, IDENTIFIER
+ * ext-AuthorityKeyIdentifier | ext-SubjectKeyIdentifier | ...
+ * }
+ *
+ * and:
+ *
+ * -- ObjectAssignment (with defined syntax, which we're not going to support):
+ * --
+ * -- Defines one particular object in the CertExtensions object set.
+ * -- We don't need th SYNTAX bits though -- ETOOMUCHWORK.
+ * -- This says that the OID id-ce-authorityKeyIdentifier means the extnValue
+ * -- is a DER-encoded AuthorityKeyIdentifier.
+ * ext-AuthorityKeyIdentifier EXTENSION ::= { SYNTAX
+ * AuthorityKeyIdentifier IDENTIFIED BY
+ * id-ce-authorityKeyIdentifier }
+ * id-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 35 }
+ *
+ * -- ObjectAssignment (with default syntax):
+ * ext-AuthorityKeyIdentifier EXTENSION ::= {
+ * -- fields don't have to be in order since we have the field names
+ * &extnId id-ce-authorityKeyIdentifier,
+ * &extnValue AuthorityKeyIdentifier
+ * }
+ *
+ * -- Plain old type def using only X.680
+ * AuthorityKeyIdentifier ::= SEQUENCE {
+ * keyIdentifier [0] KeyIdentifier OPTIONAL,
+ * authorityCertIssuer [1] GeneralNames OPTIONAL,
+ * authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL }
+ *
+ * In terms of compilation, we'll want to support only the template backend,
+ * though we'll generate the same C types for both, the template backend and
+ * the codegen backend.
+ *
+ * The generators should see a type for Extension that includes a) the
+ * parametrization (relating members in the SEQUENCE to fields in the CLASS),
+ * and b) the object set CertExtensions for the _same_ class.
+ *
+ * - The C types for ASN.1 parametrized types with object set parameters
+ * should be laid out just as before, but with additional fields:
+ *
+ * typedef struct Extension {
+ * heim_oid extnID;
+ * int *critical;
+ * heim_octet_string extnValue;
+ * // NEW FIELDS BELOW
+ * enum {
+ * opentypechoice_unknown_Extension = 0
+ * opentypechoice_Extension_id_ce_authorityKeyIdentifier,
+ * ...
+ * } _element;
+ * union {
+ * // er, what should this be named?! we have no name information
+ * // and naming it after its object value name is probably not a good
+ * // idea or not easy. We do have the OID value and possible name
+ * // though, so we should use that:
+ * AuthorityKeyIdentifier id_ce_authorityKeyIdentifier;
+ * ...
+ * } _u;
+ * } Extension;
+ *
+ * - The template for this should consist of new struct asn1_template entries
+ * following the ones for the normal fields of Extension. The first of these
+ * should have an OP that indicates that the following N entries correspond
+ * to the object set that specifies this open type, then the following N
+ * entries should each point to an object in the object set. Or maybe the
+ * object set should be a separate template -- either way. We'll also want a
+ * flag to indicate whether the object set is sorted (none of the type IDs
+ * are IMPORTed) or not (some of the type IDs are IMPORTed) so we can binary
+ * search the object set at encode/decode time.
+ *
+ * Hmm, we can assume the object sets are already sorted when there's
+ * IMPORTed IDs -- the author can do it. Yes, they're sets, but lexically
+ * they must be in some order.
+ *
+ * I like that, actually, requiring that the module author manually sort the
+ * object sets, at least when they refer to type IDs that are IMPORTed. Or
+ * maybe forbid object sets that use IMPORTed type IDs -- the module author
+ * can always copy their definitions anyways.
+ */
+
+TypeAssignment : Identifier EEQUAL Type
+ {
+ Symbol *s = addsym($1);
+ s->stype = Stype;
+ s->type = $3;
+ fix_labels(s);
+
+ /*
+ * Hack: make sure that non-anonymous enumeration types get
+ * a symbol tacked on so we can generate a template for
+ * their members for value printing.
+ */
+ if (s->type->type == TTag && $3->symbol == NULL &&
+ $3->subtype != NULL && $3->subtype->type == TInteger &&
+ $3->subtype->symbol == NULL) {
+ $3->subtype->symbol = s;
+ }
+ if (original_order)
+ generate_type(s);
+ else
+ generate_type_header_forwards(s);
+ }
+ ;
+
+ParameterizedTypeAssignment
+ /* For now we'll only support one parameter -- enough for PKIX */
+ : Identifier '{' Parameter '}' EEQUAL Type
+ {
+ char *pname = NULL;
+ Symbol *s;
+
+ if (asprintf(&pname, "%s{%s:x}", $1, $3->symbol->name) == -1 ||
+ pname == NULL)
+ err(1, "Out of memory");
+ s = addsym(pname);
+ free($1);
+ s->stype = Sparamtype;
+ s->type = parametrize_type($6, $3);
+ s->type->symbol = s;
+ fix_labels(s);
+ }
+ ;
+
+/*
+ * We're not going to support governor variables for now. We don't need to.
+ *
+ * Also, we're not going to support more than one formal parameter.
+ * Correspondingly we'll only support a single actual parameter (the count of
+ * formal and actual parameters has to match, naturally).
+ */
+
+Parameter : ParamGovernor ':' DummyReference
+ { $$ = $1; };
+ /* | DummyReference */
+ ;
+
+DummyReference : TYPE_IDENTIFIER { $$ = idcounter++; };
+
+ParamGovernor : DefinedObjectClass
+ { $$ = $1; }
+ /* | DummyGovernor */
+ /* | Type */
+ ;
+
+UnconstrainedType : BitStringType
+ | BooleanType
+ | CharacterStringType
+ | ChoiceType
+ | EnumeratedType
+ | IntegerType
+ | NullType
+ | ObjectIdentifierType
+ | OctetStringType
+ | SequenceType
+ | SetType
+ | ObjectClassFieldType; /* X.681 */
+
+Type : BuiltinType | ReferencedType | ConstrainedType ;
+
+BuiltinType : BitStringType
+ | BooleanType
+ | CharacterStringType
+ | ChoiceType
+ | EnumeratedType
+ | IntegerType
+ | NullType
+ | ObjectIdentifierType
+ | OctetStringType
+ | SequenceType
+ | SequenceOfType
+ | SetType
+ | SetOfType
+ | TaggedType
+ | ObjectClassFieldType /* X.681 */
+ /* | InstanceOfType // X.681 */
+ ;
+
+ObjectClassFieldType
+ : DefinedObjectClass '.' '&' Identifier
+ { $$ = type_from_class_field($1, $4); };
+
+BooleanType : kw_BOOLEAN
+ {
+ $$ = new_tag(ASN1_C_UNIV, UT_Boolean,
+ TE_EXPLICIT, new_type(TBoolean));
+ }
+ ;
+
+ /*
+ * The spec says the values in a ValueRange are Values, but a) all
+ * the various value ranges do not involve OBJECT IDENTIFIER, b)
+ * we only support integer value ranges at this time (as opposed
+ * to, e.g., time ranges, and we don't even support time values at
+ * this time), c) allowing OBJECT IDENTIFIER here causes a
+ * shift-reduce conflict, so we limit ourselves to integer values
+ * in ranges. We could always define IntegerValueRange,
+ * TimeValueRange, etc. when we add support for more value types.
+ */
+range : IntegerValue RANGE IntegerValue
+ {
+ if($1->type != integervalue)
+ lex_error_message("Non-integer used in first part of range");
+ if($1->type != integervalue)
+ lex_error_message("Non-integer in second part of range");
+ $$ = ecalloc(1, sizeof(*$$));
+ $$->min = $1->u.integervalue;
+ $$->max = $3->u.integervalue;
+ }
+ | IntegerValue RANGE kw_MAX
+ {
+ if($1->type != integervalue)
+ lex_error_message("Non-integer in first part of range");
+ $$ = ecalloc(1, sizeof(*$$));
+ $$->min = $1->u.integervalue;
+ $$->max = INT_MAX;
+ }
+ | kw_MIN RANGE IntegerValue
+ {
+ if($3->type != integervalue)
+ lex_error_message("Non-integer in second part of range");
+ $$ = ecalloc(1, sizeof(*$$));
+ $$->min = INT_MIN;
+ $$->max = $3->u.integervalue;
+ }
+ | IntegerValue
+ {
+ if($1->type != integervalue)
+ lex_error_message("Non-integer used in limit");
+ $$ = ecalloc(1, sizeof(*$$));
+ $$->min = $1->u.integervalue;
+ $$->max = $1->u.integervalue;
+ }
+ ;
+
+
+IntegerType : kw_INTEGER
+ {
+ $$ = new_tag(ASN1_C_UNIV, UT_Integer,
+ TE_EXPLICIT, new_type(TInteger));
+ }
+ | kw_INTEGER '{' NamedNumberList '}'
+ {
+ $$ = new_type(TInteger);
+ $$->members = $3;
+ $$ = new_tag(ASN1_C_UNIV, UT_Integer, TE_EXPLICIT, $$);
+ }
+ ;
+
+NamedNumberList : NamedNumber
+ {
+ $$ = emalloc(sizeof(*$$));
+ HEIM_TAILQ_INIT($$);
+ HEIM_TAILQ_INSERT_HEAD($$, $1, members);
+ }
+ | NamedNumberList ',' NamedNumber
+ {
+ HEIM_TAILQ_INSERT_TAIL($1, $3, members);
+ $$ = $1;
+ }
+ | NamedNumberList ',' ELLIPSIS
+ { $$ = $1; } /* XXX used for Enumerations */
+ ;
+
+NamedNumber : Identifier '(' SignedNumber ')'
+ {
+ $$ = emalloc(sizeof(*$$));
+ $$->name = $1;
+ $$->gen_name = estrdup($1);
+ output_name ($$->gen_name);
+ $$->val = $3;
+ $$->optional = 0;
+ $$->ellipsis = 0;
+ $$->type = NULL;
+ }
+ | Identifier '(' DefinedValue ')'
+ {
+ if ($3->type != integervalue)
+ lex_error_message("Named number %s not a numeric value",
+ $3->s->name);
+ $$ = emalloc(sizeof(*$$));
+ $$->name = $1;
+ $$->gen_name = estrdup($1);
+ output_name ($$->gen_name);
+ $$->val = $3->u.integervalue;
+ $$->optional = 0;
+ $$->ellipsis = 0;
+ $$->type = NULL;
+ }
+ ;
+
+EnumeratedType : kw_ENUMERATED '{' Enumerations '}'
+ {
+ $$ = new_type(TInteger);
+ $$->members = $3;
+ $$ = new_tag(ASN1_C_UNIV, UT_Enumerated, TE_EXPLICIT, $$);
+ }
+ ;
+
+Enumerations : NamedNumberList /* XXX */
+ ;
+
+BitStringType : kw_BIT kw_STRING
+ {
+ $$ = new_type(TBitString);
+ $$->members = emalloc(sizeof(*$$->members));
+ HEIM_TAILQ_INIT($$->members);
+ $$ = new_tag(ASN1_C_UNIV, UT_BitString, TE_EXPLICIT, $$);
+ }
+ | kw_BIT kw_STRING '{' NamedBitList '}'
+ {
+ $$ = new_type(TBitString);
+ $$->members = $4;
+ $$ = new_tag(ASN1_C_UNIV, UT_BitString, TE_EXPLICIT, $$);
+ }
+ ;
+
+ObjectIdentifierType: kw_OBJECT kw_IDENTIFIER
+ {
+ $$ = new_tag(ASN1_C_UNIV, UT_OID,
+ TE_EXPLICIT, new_type(TOID));
+ }
+ ;
+OctetStringType : kw_OCTET kw_STRING size
+ {
+ Type *t = new_type(TOctetString);
+ t->range = $3;
+ if (t->range) {
+ if (t->range->min < 0)
+ lex_error_message("can't use a negative SIZE range "
+ "length for OCTET STRING");
+ }
+ $$ = new_tag(ASN1_C_UNIV, UT_OctetString,
+ TE_EXPLICIT, t);
+ }
+ ;
+
+NullType : kw_NULL
+ {
+ $$ = new_tag(ASN1_C_UNIV, UT_Null,
+ TE_EXPLICIT, new_type(TNull));
+ }
+ ;
+
+size :
+ { $$ = NULL; }
+ | kw_SIZE '(' range ')'
+ { $$ = $3; }
+ ;
+
+
+SequenceType : kw_SEQUENCE '{' /* ComponentTypeLists */ ComponentTypeList '}'
+ {
+ $$ = new_type(TSequence);
+ $$->members = $3;
+ $$ = new_tag(ASN1_C_UNIV, UT_Sequence, default_tag_env, $$);
+ }
+ | kw_SEQUENCE '{' '}'
+ {
+ $$ = new_type(TSequence);
+ $$->members = NULL;
+ $$ = new_tag(ASN1_C_UNIV, UT_Sequence, default_tag_env, $$);
+ }
+ ;
+
+SequenceOfType : kw_SEQUENCE size kw_OF Type
+ {
+ $$ = new_type(TSequenceOf);
+ $$->range = $2;
+ if ($$->range) {
+ if ($$->range->min < 0)
+ lex_error_message("can't use a negative SIZE range "
+ "length for SEQUENCE OF");
+ }
+
+ $$->subtype = $4;
+ $$ = new_tag(ASN1_C_UNIV, UT_Sequence, default_tag_env, $$);
+ }
+ ;
+
+SetType : kw_SET '{' /* ComponentTypeLists */ ComponentTypeList '}'
+ {
+ $$ = new_type(TSet);
+ $$->members = $3;
+ $$ = new_tag(ASN1_C_UNIV, UT_Set, default_tag_env, $$);
+ }
+ | kw_SET '{' '}'
+ {
+ $$ = new_type(TSet);
+ $$->members = NULL;
+ $$ = new_tag(ASN1_C_UNIV, UT_Set, default_tag_env, $$);
+ }
+ ;
+
+SetOfType : kw_SET kw_OF Type
+ {
+ $$ = new_type(TSetOf);
+ $$->subtype = $3;
+ $$ = new_tag(ASN1_C_UNIV, UT_Set, default_tag_env, $$);
+ }
+ ;
+
+ChoiceType : kw_CHOICE '{' /* AlternativeTypeLists */ ComponentTypeList '}'
+ {
+ $$ = new_type(TChoice);
+ $$->members = $3;
+ }
+ ;
+
+ReferencedType : DefinedType
+ | UsefulType
+ /* | TypeFromObject // X.681 */
+ /* | ValueSetFromObjects // X.681 */
+ ;
+
+/*
+TypeFromObject : VALUE_IDENTIFIER '.' '&' TYPE_IDENTIFIER
+ { $$ = type_from_object($1, $4); };
+ */
+
+DefinedType : TYPE_IDENTIFIER
+ {
+ Symbol *s = addsym($1);
+ $$ = new_type(TType);
+ if(s->stype != Stype && s->stype != SUndefined)
+ lex_error_message ("%s is not a type\n", $1);
+ else
+ $$->symbol = s;
+ }
+ | ParameterizedType
+ { $$ = $1; }
+ ;
+
+ /*
+ * Should be ActualParameterList, but we'll do just one for now
+ * as that's enough for PKIX.
+ */
+ParameterizedType
+ : Identifier '{' ActualParameter '}' /* XXX ActualParameterList */
+ {
+ Symbol *s, *ps;
+ char *pname = NULL;
+
+ if ($3 == NULL) {
+ lex_error_message("Unknown ActualParameter object set parametrizing %s\n", $1);
+ exit(1);
+ }
+
+ /* Lookup the type from a ParameterizedTypeAssignment */
+ if (asprintf(&pname, "%s{%s:x}", $1,
+ $3->iosclass->symbol->name) == -1 ||
+ pname == NULL)
+ err(1, "Out of memory");
+ ps = addsym(pname);
+ if (ps->stype != Sparamtype)
+ lex_error_message ("%s is not a parameterized type\n", $1);
+
+ s = addsym($1);
+ $$ = ps->type; /* XXX copy, probably */
+ if (!ps->type)
+ errx(1, "Wrong class (%s) parameter for parameterized "
+ "type %s", $3->iosclass->symbol->name, $1);
+ s->stype = Stype;
+ if(s->stype != Stype && s->stype != SUndefined)
+ lex_error_message ("%s is not a type\n", $1);
+ else
+ $$->symbol = s;
+ $$->actual_parameter = $3;
+ if ($$->type == TTag)
+ $$->subtype->actual_parameter = $3;
+ }
+
+/*
+ * Per X.683 $1 for ActualParameter should be any of: a Type, a Value, a
+ * ValueSet, a DefinedObjectClass, an Object, or an ObjectSet. For PKIX we
+ * need nothing more than an ObjectSet here.
+ *
+ * Also, we can't lexically or syntactically tell the difference between all
+ * these things, though fortunately we can for ObjectSet.
+ */
+ActualParameter : DefinedObjectSet
+ { $$ = $1; };
+
+UsefulType : kw_GeneralizedTime
+ {
+ $$ = new_tag(ASN1_C_UNIV, UT_GeneralizedTime,
+ TE_EXPLICIT, new_type(TGeneralizedTime));
+ }
+ | kw_UTCTime
+ {
+ $$ = new_tag(ASN1_C_UNIV, UT_UTCTime,
+ TE_EXPLICIT, new_type(TUTCTime));
+ }
+ ;
+
+ConstrainedType : UnconstrainedType Constraint
+ {
+ $$ = $1;
+ if ($2->ctype == CT_RANGE) {
+ if ($1->type != TTag || $1->subtype->type != TInteger)
+ lex_error_message("RANGE constraints apply only to INTEGER types");
+ $$->subtype->range = $2->u.range;
+ free($2);
+ } else {
+ $$->constraint = $2;
+ }
+ /* if (Constraint.type == contentConstraint) {
+ assert(Constraint.u.constraint.type == octetstring|bitstring-w/o-NamedBitList); // remember to check type reference too
+ if (Constraint.u.constraint.type) {
+ assert((Constraint.u.constraint.type.length % 8) == 0);
+ }
+ }
+ if (Constraint.u.constraint.encoding) {
+ type == der-oid|ber-oid
+ }
+ */
+ }
+ ;
+
+
+Constraint : '(' ConstraintSpec ')'
+ {
+ $$ = $2;
+ }
+ ;
+
+ConstraintSpec : SubtypeConstraint | GeneralConstraint
+ ;
+
+SubtypeConstraint: range
+ {
+ $$ = new_constraint_spec(CT_RANGE);
+ $$->u.range = $1;
+ }
+
+GeneralConstraint: ContentsConstraint
+ | UserDefinedConstraint
+ | TableConstraint
+ ;
+
+ContentsConstraint: kw_CONTAINING Type
+ {
+ $$ = new_constraint_spec(CT_CONTENTS);
+ $$->u.content.type = $2;
+ $$->u.content.encoding = NULL;
+ }
+ | kw_ENCODED kw_BY Value
+ {
+ if ($3->type != objectidentifiervalue)
+ lex_error_message("Non-OID used in ENCODED BY constraint");
+ $$ = new_constraint_spec(CT_CONTENTS);
+ $$->u.content.type = NULL;
+ $$->u.content.encoding = $3;
+ }
+ | kw_CONTAINING Type kw_ENCODED kw_BY Value
+ {
+ if ($5->type != objectidentifiervalue)
+ lex_error_message("Non-OID used in ENCODED BY constraint");
+ $$ = new_constraint_spec(CT_CONTENTS);
+ $$->u.content.type = $2;
+ $$->u.content.encoding = $5;
+ }
+ ;
+
+UserDefinedConstraint: kw_CONSTRAINED kw_BY '{' '}'
+ {
+ $$ = new_constraint_spec(CT_USER);
+ }
+ ;
+
+TableConstraint : SimpleTableConstraint
+ { $$ = $1; }
+ | ComponentRelationConstraint
+ { $$ = $1; };
+
+SimpleTableConstraint
+ : '{' TYPE_IDENTIFIER '}'
+ {
+ $$ = ecalloc(1, sizeof(*$$));
+ $$->ctype = CT_TABLE_CONSTRAINT;
+ $$->u.content.crel.objectname = $2;
+ $$->u.content.crel.membername = 0;
+ };
+
+/*
+ * In X.682, ComponentRelationConstraint is a fantastically more complicated
+ * production. The stuff in the second set of braces is a list of AtNotation,
+ * and AtNotation is '@' followed by some number of '.'s, followed by a
+ * ComponentIdList, which is a non-empty set of identifiers separated by '.'s.
+ * The number of '.'s is a "level" used to identify a SET, SEQUENCE, or CHOICE
+ * where the path of member identifiers is rooted that ultimately identifies
+ * the field providing the constraint.
+ *
+ * So in
+ *
+ * extnValue OCTET STRING
+ * (CONTAINING
+ * EXTENSION.&ExtnType({ExtensionSet}{@extnID}))
+ * ^^^^^^^^^^^^^^^^^^^
+ * ObjectClassFieldType
+ * meaning the open type field
+ * &ExtnType of EXTENSION
+ * ^^^^^^^^^^^^^^^^^^^^^^^^^
+ * GeneralConstraint
+ * ^^^^^^^^^^^^^^^^^^^^^^^
+ * ComponentRelationConstraint
+ * ^^^^^^^^^^^^^^
+ * DefinedObjectSet
+ * ^^^^^^^^
+ * '{' AtNotation ',' + '}'
+ *
+ * we have EXTENSION.&ExtnType is the ObjectClassFieldType, and
+ * ({ExtensionSet}{@extnID}) is the ComponentRelationConstraint on the
+ * extnValue member, where {ExtensionSet} is the DummyReference from the formal
+ * parameter of the enclosing parameterized type, and {@extnID} is the
+ * AtNotation list identifying the field of the class/objects-in-the-object-set
+ * that will be identifying the type of the extnValue field.
+ *
+ * We need just the one AtNotation component.
+ */
+ComponentRelationConstraint
+ : '{' TYPE_IDENTIFIER '}' '{' '@' Identifier '}'
+ {
+ $$ = ecalloc(1, sizeof(*$$));
+ $$->ctype = CT_TABLE_CONSTRAINT;
+ $$->u.content.crel.objectname = $2;
+ $$->u.content.crel.membername = $6;
+ };
+
+TaggedType : Tag tagenv Type
+ {
+ $$ = new_type(TTag);
+ $$->tag = $1;
+ $$->tag.tagenv = $2;
+ if (template_flag) {
+ $$->subtype = $3;
+ } else if ($2 == TE_IMPLICIT) {
+ Type *t = $3;
+
+ /*
+ * FIXME We shouldn't do this... The logic for
+ * dealing with IMPLICIT tags belongs elsewhere.
+ */
+ while (t->type == TType) {
+ if (t->subtype)
+ t = t->subtype;
+ else if (t->symbol && t->symbol->type)
+ t = t->symbol->type;
+ else
+ break;
+ }
+ /*
+ * IMPLICIT tags of CHOICE types are EXPLICIT
+ * instead.
+ */
+ if (t->type == TChoice)
+ $$->tag.tagenv = TE_EXPLICIT;
+ if($3->type == TTag && $2 == TE_IMPLICIT) {
+ $$->subtype = $3->subtype;
+ free($3);
+ } else {
+ $$->subtype = $3;
+ }
+ } else {
+ $$->subtype = $3;
+ }
+ }
+ ;
+
+Tag : '[' Class NUMBER ']'
+ {
+ $$.tagclass = $2;
+ $$.tagvalue = $3;
+ $$.tagenv = default_tag_env;
+ }
+ ;
+
+Class : /* */
+ {
+ $$ = ASN1_C_CONTEXT;
+ }
+ | kw_UNIVERSAL
+ {
+ $$ = ASN1_C_UNIV;
+ }
+ | kw_APPLICATION
+ {
+ $$ = ASN1_C_APPL;
+ }
+ | kw_PRIVATE
+ {
+ $$ = ASN1_C_PRIVATE;
+ }
+ ;
+
+tagenv : /* */
+ {
+ $$ = default_tag_env;
+ }
+ | kw_EXPLICIT
+ {
+ $$ = default_tag_env;
+ }
+ | kw_IMPLICIT
+ {
+ $$ = TE_IMPLICIT;
+ }
+ ;
+
+
+ValueAssignment : VALUE_IDENTIFIER Type EEQUAL Value
+ {
+ Symbol *s;
+ s = addsym ($1);
+
+ s->stype = SValue;
+ s->value = $4;
+ generate_constant (s);
+ /*
+ * Save this value's name so we can know some name for
+ * this value wherever _a_ name may be needed for it.
+ *
+ * This is useful for OIDs used as type IDs in objects
+ * sets of classes with open types. We'll generate
+ * enum labels from those OIDs' names.
+ */
+ s->value->s = s;
+ }
+ ;
+
+CharacterStringType: RestrictedCharactedStringType
+ ;
+
+RestrictedCharactedStringType: kw_GeneralString
+ {
+ $$ = new_tag(ASN1_C_UNIV, UT_GeneralString,
+ TE_EXPLICIT, new_type(TGeneralString));
+ }
+ | kw_TeletexString
+ {
+ $$ = new_tag(ASN1_C_UNIV, UT_TeletexString,
+ TE_EXPLICIT, new_type(TTeletexString));
+ }
+ | kw_UTF8String
+ {
+ $$ = new_tag(ASN1_C_UNIV, UT_UTF8String,
+ TE_EXPLICIT, new_type(TUTF8String));
+ }
+ | kw_PrintableString
+ {
+ $$ = new_tag(ASN1_C_UNIV, UT_PrintableString,
+ TE_EXPLICIT, new_type(TPrintableString));
+ }
+ | kw_VisibleString
+ {
+ $$ = new_tag(ASN1_C_UNIV, UT_VisibleString,
+ TE_EXPLICIT, new_type(TVisibleString));
+ }
+ | kw_IA5String
+ {
+ $$ = new_tag(ASN1_C_UNIV, UT_IA5String,
+ TE_EXPLICIT, new_type(TIA5String));
+ }
+ | kw_BMPString
+ {
+ $$ = new_tag(ASN1_C_UNIV, UT_BMPString,
+ TE_EXPLICIT, new_type(TBMPString));
+ }
+ | kw_UniversalString
+ {
+ $$ = new_tag(ASN1_C_UNIV, UT_UniversalString,
+ TE_EXPLICIT, new_type(TUniversalString));
+ }
+
+ ;
+
+ComponentTypeList: ComponentType
+ {
+ $$ = emalloc(sizeof(*$$));
+ HEIM_TAILQ_INIT($$);
+ HEIM_TAILQ_INSERT_HEAD($$, $1, members);
+ }
+ | ComponentTypeList ',' ComponentType
+ {
+ HEIM_TAILQ_INSERT_TAIL($1, $3, members);
+ $$ = $1;
+ }
+ | ComponentTypeList ',' ELLIPSIS
+ {
+ struct member *m = ecalloc(1, sizeof(*m));
+ m->name = estrdup("...");
+ m->gen_name = estrdup("asn1_ellipsis");
+ m->ellipsis = 1;
+ HEIM_TAILQ_INSERT_TAIL($1, m, members);
+ $$ = $1;
+ }
+ ;
+
+NamedType : Identifier Type
+ {
+ $$ = emalloc(sizeof(*$$));
+ $$->name = $1;
+ $$->gen_name = estrdup($1);
+ output_name ($$->gen_name);
+ $$->type = $2;
+ $$->ellipsis = 0;
+ }
+ ;
+
+ComponentType : NamedType
+ {
+ $$ = $1;
+ $$->optional = 0;
+ $$->defval = NULL;
+ }
+ | NamedType kw_OPTIONAL
+ {
+ $$ = $1;
+ $$->optional = 1;
+ $$->defval = NULL;
+ }
+ | NamedType kw_DEFAULT Value
+ {
+ $$ = $1;
+ $$->optional = 0;
+ $$->defval = $3;
+ }
+ ;
+
+NamedBitList : NamedBit
+ {
+ $$ = emalloc(sizeof(*$$));
+ HEIM_TAILQ_INIT($$);
+ HEIM_TAILQ_INSERT_HEAD($$, $1, members);
+ }
+ | NamedBitList ',' NamedBit
+ {
+ HEIM_TAILQ_INSERT_TAIL($1, $3, members);
+ $$ = $1;
+ }
+ ;
+
+NamedBit : Identifier '(' NUMBER ')'
+ {
+ $$ = emalloc(sizeof(*$$));
+ $$->name = $1;
+ $$->gen_name = estrdup($1);
+ output_name ($$->gen_name);
+ $$->val = $3;
+ $$->optional = 0;
+ $$->ellipsis = 0;
+ $$->type = NULL;
+ }
+ ;
+
+objid_opt : objid
+ | /* empty */ { $$ = NULL; }
+ ;
+
+objid : '{' objid_list '}'
+ {
+ $$ = $2;
+ }
+ ;
+
+objid_list : /* empty */
+ {
+ $$ = NULL;
+ }
+ | objid_element objid_list
+ {
+ if ($2) {
+ $$ = $2;
+ add_oid_to_tail($2, $1);
+ } else {
+ $$ = $1;
+ }
+ }
+ ;
+
+objid_element : Identifier '(' NUMBER ')'
+ {
+ $$ = new_objid($1, $3);
+ }
+ | Identifier
+ {
+ Symbol *s = addsym($1);
+ if(s->stype != SValue ||
+ s->value->type != objectidentifiervalue) {
+ lex_error_message("%s is not an object identifier\n",
+ s->name);
+ exit(1);
+ }
+ $$ = s->value->u.objectidentifiervalue;
+ }
+ | NUMBER
+ {
+ $$ = new_objid(NULL, $1);
+ }
+ ;
+
+Value : BuiltinValue
+ | ReferencedValue
+ ;
+
+ValueExNull : BuiltinValueExNull
+ | ReferencedValue
+ ;
+
+BuiltinValue : BooleanValue
+ | CharacterStringValue
+ | IntegerValue
+ | ObjectIdentifierValue
+ | NullValue
+ ;
+
+BuiltinValueExNull
+ : BooleanValue
+ | CharacterStringValue
+ | IntegerValue
+ | ObjectIdentifierValue
+ ;
+
+ReferencedValue : DefinedValue
+ ;
+
+DefinedValue : Valuereference
+ ;
+
+Valuereference : VALUE_IDENTIFIER
+ {
+ Symbol *s = addsym($1);
+ if(s->stype != SValue)
+ lex_error_message ("%s is not a value\n",
+ s->name);
+ else
+ $$ = s->value;
+ }
+ ;
+
+CharacterStringValue: STRING
+ {
+ $$ = emalloc(sizeof(*$$));
+ $$->type = stringvalue;
+ $$->u.stringvalue = $1;
+ }
+ ;
+
+BooleanValue : kw_TRUE
+ {
+ $$ = emalloc(sizeof(*$$));
+ $$->type = booleanvalue;
+ $$->u.booleanvalue = 1;
+ }
+ | kw_FALSE
+ {
+ $$ = emalloc(sizeof(*$$));
+ $$->type = booleanvalue;
+ $$->u.booleanvalue = 0;
+ }
+ ;
+
+IntegerValue : SignedNumber
+ {
+ $$ = emalloc(sizeof(*$$));
+ $$->type = integervalue;
+ $$->u.integervalue = $1;
+ }
+ ;
+
+SignedNumber : NUMBER
+ ;
+
+NullValue : kw_NULL
+ {
+ }
+ ;
+
+ObjectIdentifierValue: objid
+ {
+ $$ = emalloc(sizeof(*$$));
+ $$->type = objectidentifiervalue;
+ $$->u.objectidentifiervalue = $1;
+ }
+ ;
+
+%%
+
+void
+yyerror (const char *s)
+{
+ lex_error_message ("%s\n", s);
+}
+
+static Type *
+new_tag(int tagclass, int tagvalue, int tagenv, Type *oldtype)
+{
+ Type *t;
+ if(oldtype->type == TTag && oldtype->tag.tagenv == TE_IMPLICIT) {
+ t = oldtype;
+ oldtype = oldtype->subtype; /* XXX */
+ } else
+ t = new_type (TTag);
+
+ t->tag.tagclass = tagclass;
+ t->tag.tagvalue = tagvalue;
+ t->tag.tagenv = tagenv;
+ t->subtype = oldtype;
+ return t;
+}
+
+static struct objid *
+new_objid(const char *label, int value)
+{
+ struct objid *s;
+ s = emalloc(sizeof(*s));
+ s->label = label;
+ s->value = value;
+ s->next = NULL;
+ return s;
+}
+
+static void
+add_oid_to_tail(struct objid *head, struct objid *tail)
+{
+ struct objid *o;
+ o = head;
+ while (o->next)
+ o = o->next;
+ o->next = tail;
+}
+
+static Type *
+new_type (Typetype tt)
+{
+ Type *t = ecalloc(1, sizeof(*t));
+ t->type = tt;
+ t->id = idcounter++;
+ return t;
+}
+
+static struct constraint_spec *
+new_constraint_spec(enum ctype ct)
+{
+ struct constraint_spec *c = ecalloc(1, sizeof(*c));
+ c->ctype = ct;
+ return c;
+}
+
+static void fix_labels2(Type *t, const char *prefix);
+static void fix_labels1(struct memhead *members, const char *prefix)
+{
+ Member *m;
+
+ if(members == NULL)
+ return;
+ HEIM_TAILQ_FOREACH(m, members, members) {
+ if (asprintf(&m->label, "%s_%s", prefix, m->gen_name) < 0)
+ errx(1, "malloc");
+ if (m->label == NULL)
+ errx(1, "malloc");
+ if(m->type != NULL)
+ fix_labels2(m->type, m->label);
+ }
+}
+
+static void fix_labels2(Type *t, const char *prefix)
+{
+ for(; t; t = t->subtype)
+ fix_labels1(t->members, prefix);
+}
+
+static void
+fix_labels(Symbol *s)
+{
+ char *p = NULL;
+ if (asprintf(&p, "choice_%s", s->gen_name) < 0 || p == NULL)
+ errx(1, "malloc");
+ if (s->type)
+ fix_labels2(s->type, p);
+ free(p);
+}
+
+static struct objectshead *
+add_object_set_spec(struct objectshead *lst, IOSObject *o)
+{
+ if (lst == NULL) {
+ lst = emalloc(sizeof(*lst));
+ HEIM_TAILQ_INIT(lst);
+ HEIM_TAILQ_INSERT_HEAD(lst, o, objects);
+ } else {
+ HEIM_TAILQ_INSERT_TAIL(lst, o, objects);
+ }
+ return lst;
+}
+
+static struct objfieldhead *
+add_field_setting(struct objfieldhead *lst, ObjectField *f)
+{
+ if (lst == NULL) {
+ lst = emalloc(sizeof(*lst));
+ HEIM_TAILQ_INIT(lst);
+ HEIM_TAILQ_INSERT_HEAD(lst, f, objfields);
+ } else {
+ HEIM_TAILQ_INSERT_TAIL(lst, f, objfields);
+ }
+ return lst;
+}
+
+static struct fieldhead *
+add_field_spec(struct fieldhead *lst, Field *f)
+{
+ if (lst == NULL) {
+ lst = emalloc(sizeof(*lst));
+ HEIM_TAILQ_INIT(lst);
+ HEIM_TAILQ_INSERT_HEAD(lst, f, fields);
+ } else {
+ HEIM_TAILQ_INSERT_TAIL(lst, f, fields);
+ }
+ return lst;
+}
+
+static ObjectField *
+new_field_setting(char *n, Type *t, struct value *v)
+{
+ ObjectField *of;
+
+ of = ecalloc(1, sizeof(*of));
+ of->value = v;
+ of->type = t;
+ of->name = n;
+ return of;
+}
+
+static Field *
+new_type_field(char *n, int optional, Type *t)
+{
+ Field *f;
+
+ f = ecalloc(1, sizeof(*f));
+ f->optional = optional;
+ f->unique = 0;
+ f->defval = 0;
+ f->type = t;
+ f->name = n;
+ return f;
+}
+
+static Field *
+new_fixed_type_value_field(char *n, Type *t, int unique, int optional, struct value *defval)
+{
+ Field *f;
+
+ f = ecalloc(1, sizeof(*f));
+ f->optional = optional;
+ f->unique = unique;
+ f->defval = defval;
+ f->type = t;
+ f->name = n;
+ return f;
+}
+
+static Type *
+parametrize_type(Type *t, IOSClass *c)
+{
+ Type *type;
+
+ type = new_type(TType);
+ *type = *t; /* XXX Copy, or use subtype; this only works as long as we don't cleanup! */
+ type->formal_parameter = c;
+ return type;
+}
+
+static Type *
+type_from_class_field(IOSClass *c, const char *n)
+{
+ Field *f;
+ Type *t;
+
+ HEIM_TAILQ_FOREACH(f, c->fields, fields) {
+ if (strcmp(f->name, n) == 0) {
+ t = new_type(TType);
+ if (f->type) {
+ *t = *f->type;
+ } else {
+ Symbol *s = addsym("HEIM_ANY");
+ if(s->stype != Stype && s->stype != SUndefined)
+ errx(1, "Do not define HEIM_ANY, only import it\n");
+ s->stype = Stype;
+ t->symbol = s;
+ }
+ t->typeref.iosclass = c;
+ t->typeref.field = f;
+ return t;
+ }
+ }
+ return NULL;
+}
+
+static void
+validate_object_set(IOSObjectSet *os)
+{
+ IOSObject **objects;
+ ObjectField *of;
+ IOSObject *o;
+ Field *cf;
+ size_t nobjs, i;
+
+ /* Check unique fields */
+ HEIM_TAILQ_FOREACH(cf, os->iosclass->fields, fields) {
+ if (!cf->unique)
+ continue;
+ if (!cf->type)
+ errx(1, "Type fields of classes can't be UNIQUE (%s)",
+ os->iosclass->symbol->name);
+ sort_object_set(os, cf, &objects, &nobjs);
+ for (i = 0; i < nobjs; i++) {
+ HEIM_TAILQ_FOREACH(of, objects[i]->objfields, objfields) {
+ if (strcmp(cf->name, of->name) != 0)
+ continue;
+ if (!of->value)
+ errx(1, "Value not specified for required UNIQUE field %s of object %s",
+ cf->name, objects[i]->symbol->name);
+ break;
+ }
+ if (i == 0)
+ continue;
+ if (object_cmp(&objects[i - 1], &objects[i]) == 0)
+ errx(1, "Duplicate values of UNIQUE field %s of objects %s and %s",
+ cf->name, objects[i - 1]->symbol->name,
+ objects[i]->symbol->name);
+ }
+ free(objects);
+ }
+
+ /* Check required fields */
+ HEIM_TAILQ_FOREACH(cf, os->iosclass->fields, fields) {
+ if (cf->optional || cf->defval || !cf->type)
+ continue;
+ HEIM_TAILQ_FOREACH(o, os->objects, objects) {
+ int specified = 0;
+
+ HEIM_TAILQ_FOREACH(of, o->objfields, objfields) {
+ if (strcmp(of->name, cf->name) != 0)
+ continue;
+ if (of->value)
+ specified = 1;
+ break;
+ }
+ if (!specified)
+ errx(1, "Value not specified for required non-UNIQUE field %s of object %s",
+ cf->name, o->symbol->name);
+ }
+ }
+}
diff --git a/third_party/heimdal/lib/asn1/canthandle.asn1 b/third_party/heimdal/lib/asn1/canthandle.asn1
new file mode 100644
index 0000000..4378428
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/canthandle.asn1
@@ -0,0 +1,15 @@
+-- $Id$ --
+
+CANTHANDLE DEFINITIONS ::= BEGIN
+
+-- Currently the compiler handles SET { ... } types, but does NOT sort
+-- their members as should be done in the case of conforming DER encoders.
+-- The workaround is to sort the members of such types manually in their
+-- definitions. See X.690, section 10.3, and X.680, section 8.6 for details.
+
+-- Can't handle primitives in SET OF, causing the compiler to crash
+-- Workaround is to define a type that is only an integer and use that
+
+Baz ::= SET OF INTEGER
+
+END
diff --git a/third_party/heimdal/lib/asn1/check-ber.c b/third_party/heimdal/lib/asn1/check-ber.c
new file mode 100644
index 0000000..57450f4
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/check-ber.c
@@ -0,0 +1,280 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <der_locl.h>
+#include <rfc2459_asn1.h>
+#include <cms_asn1.h>
+
+
+RCSID("$Id$");
+
+static const unsigned char *contentdata = (unsigned char *)
+ "\x30\x80\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x07\x02\xa0\x80\x30"
+ "\x80\x02\x01\x03\x31\x0b\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05"
+ "\x00\x30\x80\x06\x07\x2b\x06\x01\x05\x02\x03\x01\xa0\x80\x24\x80"
+ "\x04\x40\x30\x3e\xa0\x3c\x30\x3a\xa0\x05\x02\x03\x0e\x03\x86\xa1"
+ "\x11\x18\x0f\x32\x30\x30\x38\x31\x32\x31\x33\x31\x39\x34\x35\x34"
+ "\x32\x5a\xa2\x06\x02\x04\xba\xbd\x97\x8a\xa3\x16\x04\x14\x41\x28"
+ "\x79\xa8\xd0\xe4\xb1\x0f\xb1\xfc\xa6\x0b\x4d\x2b\x85\x3d\xd9\x17"
+ "\x3f\xdc\x00\x00\x00\x00\x00\x00\xa0\x82\x0b\x6c\x30\x82\x05\x57"
+ "\x30\x82\x04\x3f\xa0\x03\x02\x01\x02\x02\x03\x47\x3d\x05\x30\x0d"
+ "\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x30\x81\x86"
+ "\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x55\x53\x31\x1d\x30"
+ "\x1b\x06\x03\x55\x04\x0a\x13\x14\x41\x70\x70\x6c\x65\x20\x43\x6f"
+ "\x6d\x70\x75\x74\x65\x72\x2c\x20\x49\x6e\x63\x2e\x31\x2d\x30\x2b"
+ "\x06\x03\x55\x04\x0b\x13\x24\x41\x70\x70\x6c\x65\x20\x43\x6f\x6d"
+ "\x70\x75\x74\x65\x72\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74"
+ "\x65\x20\x41\x75\x74\x68\x6f\x72\x69\x74\x79\x31\x29\x30\x27\x06"
+ "\x03\x55\x04\x03\x13\x20\x41\x70\x70\x6c\x65\x20\x2e\x4d\x61\x63"
+ "\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x20\x41\x75\x74"
+ "\x68\x6f\x72\x69\x74\x79\x30\x1e\x17\x0d\x30\x38\x31\x30\x30\x31"
+ "\x30\x38\x30\x36\x33\x33\x5a\x17\x0d\x30\x39\x31\x30\x30\x32\x30"
+ "\x38\x30\x36\x33\x33\x5a\x30\x71\x31\x0b\x30\x09\x06\x03\x55\x04"
+ "\x06\x13\x02\x55\x53\x31\x13\x30\x11\x06\x03\x55\x04\x0a\x13\x0a"
+ "\x41\x70\x70\x6c\x65\x20\x49\x6e\x63\x2e\x31\x0f\x30\x0d\x06\x03"
+ "\x55\x04\x0b\x13\x06\x6d\x65\x2e\x63\x6f\x6d\x31\x15\x30\x13\x06"
+ "\x03\x55\x04\x03\x13\x0c\x62\x69\x74\x63\x6f\x6c\x6c\x65\x63\x74"
+ "\x6f\x72\x31\x25\x30\x23\x06\x03\x55\x04\x0d\x13\x1c\x4d\x6f\x62"
+ "\x69\x6c\x65\x4d\x65\x20\x53\x68\x61\x72\x69\x6e\x67\x20\x43\x65"
+ "\x72\x74\x69\x66\x69\x63\x61\x74\x65\x30\x81\xa3\x30\x0d\x06\x09"
+ "\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00\x03\x81\x91\x00\x30"
+ "\x81\x8d\x02\x81\x81\x00\xe1\x15\xd8\xfa\xe9\xc2\xb7\x2e\xf0\xd9"
+ "\xbe\xdb\x0c\xd8\xcb\xf3\x88\x13\xd7\x22\xf8\x4d\xf4\xb6\x31\x17"
+ "\xe5\x92\x42\xef\x15\xe4\x5f\x12\x58\x3d\x8d\x0b\xa4\x03\x76\xe0"
+ "\xd0\xf2\x46\xb4\x4b\x14\x78\x23\x1c\x38\xb0\x99\xff\x36\x6f\x0e"
+ "\x26\xdf\x76\xd0\x01\x03\x7a\xd9\xcd\x1c\x92\xa6\x10\x5e\xed\x8a"
+ "\xb0\xfe\x9b\x8c\x96\xb0\x91\x9f\x97\xd0\xf4\x9c\x81\x8e\xbf\xb5"
+ "\x41\x24\x81\xb0\x1b\xb3\x8c\xd3\x92\x5c\xfd\x2b\x04\x61\xc3\x21"
+ "\x6c\xa9\xe4\xa0\xfe\xa5\x1c\x76\xfd\xda\x3b\x81\x7c\xa0\x5c\x2c"
+ "\xf6\x8f\x6e\x74\x52\x35\x02\x07\x01\x00\x01\x00\x01\x00\x01\xa3"
+ "\x82\x02\x60\x30\x82\x02\x5c\x30\x0c\x06\x03\x55\x1d\x13\x01\x01"
+ "\xff\x04\x02\x30\x00\x30\x0e\x06\x03\x55\x1d\x0f\x01\x01\xff\x04"
+ "\x04\x03\x02\x03\x88\x30\x28\x06\x03\x55\x1d\x25\x04\x21\x30\x1f"
+ "\x06\x08\x2b\x06\x01\x05\x05\x07\x03\x02\x06\x0a\x2a\x86\x48\x86"
+ "\xf7\x63\x64\x03\x02\x01\x06\x07\x2b\x06\x01\x05\x02\x03\x04\x30"
+ "\x1d\x06\x03\x55\x1d\x0e\x04\x16\x04\x14\x11\xb3\x15\xb5\xab\x31"
+ "\xbb\xa5\x48\xee\xd6\x33\xd2\x86\xc3\x0b\x2a\x4c\x5e\x94\x30\x1f"
+ "\x06\x03\x55\x1d\x23\x04\x18\x30\x16\x80\x14\x7a\x7d\x90\xb1\x30"
+ "\x59\x08\x92\x91\xf9\x53\xb9\x71\x1d\x35\x33\x67\x34\x8b\xd5\x30"
+ "\x81\xa5\x06\x08\x2b\x06\x01\x05\x05\x07\x01\x01\x04\x81\x98\x30"
+ "\x81\x95\x30\x27\x06\x08\x2b\x06\x01\x05\x05\x07\x30\x01\x86\x1b"
+ "\x68\x74\x74\x70\x3a\x2f\x2f\x63\x65\x72\x74\x69\x6e\x66\x6f\x2e"
+ "\x6d\x65\x2e\x63\x6f\x6d\x2f\x6f\x63\x73\x70\x30\x44\x06\x08\x2b"
+ "\x06\x01\x05\x05\x07\x30\x02\x86\x38\x68\x74\x74\x70\x3a\x2f\x2f"
+ "\x77\x77\x77\x2e\x61\x70\x70\x6c\x65\x2e\x63\x6f\x6d\x2f\x63\x65"
+ "\x72\x74\x69\x66\x69\x63\x61\x74\x65\x61\x75\x74\x68\x6f\x72\x69"
+ "\x74\x79\x2f\x63\x61\x73\x69\x67\x6e\x65\x72\x73\x2e\x68\x74\x6d"
+ "\x6c\x30\x24\x06\x03\x55\x1d\x12\x86\x1d\x68\x74\x74\x70\x3a\x2f"
+ "\x2f\x63\x65\x72\x74\x69\x6e\x66\x6f\x2e\x6d\x65\x2e\x63\x6f\x6d"
+ "\x2f\x43\x41\x2e\x63\x65\x72\x30\x82\x01\x28\x06\x03\x55\x1d\x20"
+ "\x04\x82\x01\x1f\x30\x82\x01\x1b\x30\x82\x01\x17\x06\x09\x2a\x86"
+ "\x48\x86\xf7\x63\x64\x05\x02\x30\x82\x01\x08\x30\x40\x06\x08\x2b"
+ "\x06\x01\x05\x05\x07\x02\x01\x16\x34\x68\x74\x74\x70\x3a\x2f\x2f"
+ "\x77\x77\x77\x2e\x61\x70\x70\x6c\x65\x2e\x63\x6f\x6d\x2f\x63\x65"
+ "\x72\x74\x69\x66\x69\x63\x61\x74\x65\x61\x75\x74\x68\x6f\x72\x69"
+ "\x74\x79\x2f\x74\x65\x72\x6d\x73\x2e\x68\x74\x6d\x6c\x30\x81\xc3"
+ "\x06\x08\x2b\x06\x01\x05\x05\x07\x02\x02\x30\x81\xb6\x1a\x81\xb3"
+ "\x52\x65\x6c\x69\x61\x6e\x63\x65\x20\x6f\x6e\x20\x74\x68\x69\x73"
+ "\x20\x63\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x20\x62\x79\x20"
+ "\x61\x6e\x79\x20\x70\x61\x72\x74\x79\x20\x61\x73\x73\x75\x6d\x65"
+ "\x73\x20\x61\x63\x63\x65\x70\x74\x61\x6e\x63\x65\x20\x6f\x66\x20"
+ "\x74\x68\x65\x20\x74\x68\x65\x6e\x20\x61\x70\x70\x6c\x69\x63\x61"
+ "\x62\x6c\x65\x20\x73\x74\x61\x6e\x64\x61\x72\x64\x20\x74\x65\x72"
+ "\x6d\x73\x20\x61\x6e\x64\x20\x63\x6f\x6e\x64\x69\x74\x69\x6f\x6e"
+ "\x73\x20\x6f\x66\x20\x75\x73\x65\x2c\x20\x63\x65\x72\x74\x69\x66"
+ "\x69\x63\x61\x74\x65\x20\x70\x6f\x6c\x69\x63\x79\x20\x61\x6e\x64"
+ "\x20\x63\x65\x72\x74\x69\x66\x69\x63\x61\x74\x69\x6f\x6e\x20\x70"
+ "\x72\x61\x63\x74\x69\x63\x65\x20\x73\x74\x61\x74\x65\x6d\x65\x6e"
+ "\x74\x73\x2e\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05"
+ "\x05\x00\x03\x82\x01\x01\x00\x39\xb1\x81\xbe\x55\xf1\xb1\xe4\x16"
+ "\x5d\x7c\x5b\x6a\xe8\xcf\xee\xaa\x87\x91\x81\xf2\x57\x0d\x32\x6c"
+ "\xc6\x47\xdc\x71\x70\xfa\x7c\x47\x84\x7f\xa5\x69\x1b\x4c\x52\x98"
+ "\x7f\xc8\x1f\x62\x06\x83\xae\x0a\xef\x55\x29\x35\xb3\xa0\x04\x88"
+ "\xa6\x45\x0a\xd0\xd7\x4e\x5c\x63\x3e\xe7\xb2\x28\x85\xd3\x01\x56"
+ "\x2b\x89\xb5\x60\x9a\xa5\x9d\x85\x0d\x76\x9e\xe1\x4a\x54\x8b\x6f"
+ "\xad\xc4\xc2\x43\x2f\x18\xaa\x18\x1a\x64\x2f\x2e\xe3\xc9\xb8\xa8"
+ "\xdd\xba\x53\xc4\x18\xcf\x4e\x30\xbf\x06\xa7\xdb\x12\x34\x24\x5c"
+ "\x71\x60\x2a\xd2\x93\xef\x54\x83\x4e\x5d\xc5\x5f\x00\x8d\x02\x85"
+ "\xe5\x17\x68\x46\xfa\xd4\x45\x96\x71\xf7\x93\x58\x4d\x83\x6b\x01"
+ "\xcb\xdb\x7d\x61\x67\x69\xbe\xf1\x4c\x4b\xe2\x3e\xf6\x4e\x62\x77"
+ "\x26\x86\xc4\x3b\x96\x38\x27\x0b\x02\x0d\x07\xc9\x95\x53\x6d\x03"
+ "\xff\x61\xfb\x67\x7f\x8a\x2e\x2f\xc5\xff\x5a\xf9\x53\xd8\xb3\xae"
+ "\xf1\x05\x27\x92\x79\x22\xd5\x55\x6e\xd6\xbf\xdb\x9d\xad\xbf\xbf"
+ "\x7d\x15\xd8\x1c\x3d\x63\x86\xf1\xf1\x78\xfe\xfb\x62\x06\x8c\xf4"
+ "\x0f\xa8\x91\xa8\x7c\xef\x51\x96\x09\x52\x68\xec\x09\xdd\xb9\x9a"
+ "\x62\x49\xac\xbe\x20\x20\x9b\x30\x82\x06\x0d\x30\x82\x04\xf5\xa0"
+ "\x03\x02\x01\x02\x02\x01\x0f\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7"
+ "\x0d\x01\x01\x05\x05\x00\x30\x81\x86\x31\x0b\x30\x09\x06\x03\x55"
+ "\x04\x06\x13\x02\x55\x53\x31\x1d\x30\x1b\x06\x03\x55\x04\x0a\x13"
+ "\x14\x41\x70\x70\x6c\x65\x20\x43\x6f\x6d\x70\x75\x74\x65\x72\x2c"
+ "\x20\x49\x6e\x63\x2e\x31\x2d\x30\x2b\x06\x03\x55\x04\x0b\x13\x24"
+ "\x41\x70\x70\x6c\x65\x20\x43\x6f\x6d\x70\x75\x74\x65\x72\x20\x43"
+ "\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x20\x41\x75\x74\x68\x6f"
+ "\x72\x69\x74\x79\x31\x29\x30\x27\x06\x03\x55\x04\x03\x13\x20\x41"
+ "\x70\x70\x6c\x65\x20\x52\x6f\x6f\x74\x20\x43\x65\x72\x74\x69\x66"
+ "\x69\x63\x61\x74\x65\x20\x41\x75\x74\x68\x6f\x72\x69\x74\x79\x30"
+ "\x1e\x17\x0d\x30\x35\x30\x32\x31\x30\x32\x30\x33\x38\x32\x37\x5a"
+ "\x17\x0d\x31\x31\x31\x31\x31\x30\x32\x30\x33\x38\x32\x37\x5a\x30"
+ "\x81\x86\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x55\x53\x31"
+ "\x1d\x30\x1b\x06\x03\x55\x04\x0a\x13\x14\x41\x70\x70\x6c\x65\x20"
+ "\x43\x6f\x6d\x70\x75\x74\x65\x72\x2c\x20\x49\x6e\x63\x2e\x31\x2d"
+ "\x30\x2b\x06\x03\x55\x04\x0b\x13\x24\x41\x70\x70\x6c\x65\x20\x43"
+ "\x6f\x6d\x70\x75\x74\x65\x72\x20\x43\x65\x72\x74\x69\x66\x69\x63"
+ "\x61\x74\x65\x20\x41\x75\x74\x68\x6f\x72\x69\x74\x79\x31\x29\x30"
+ "\x27\x06\x03\x55\x04\x03\x13\x20\x41\x70\x70\x6c\x65\x20\x2e\x4d"
+ "\x61\x63\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x20\x41"
+ "\x75\x74\x68\x6f\x72\x69\x74\x79\x30\x82\x01\x22\x30\x0d\x06\x09"
+ "\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00\x03\x82\x01\x0f\x00"
+ "\x30\x82\x01\x0a\x02\x82\x01\x01\x00\xbb\x73\x84\xb0\x48\x36\x64"
+ "\xf8\x1f\xa2\x57\x89\xb6\xe2\x71\x3c\x36\x5e\x56\xeb\xdb\x96\x16"
+ "\x23\x1c\x81\xd0\x14\x2d\xd6\xf0\x4b\x22\x9b\x3f\xb7\x7a\x2c\xa2"
+ "\xf0\x69\x48\x33\xb7\x9e\xef\x68\xe7\xbc\x30\x07\x73\xbc\x61\xb0"
+ "\x01\x51\xef\x44\xdf\xdb\x45\x04\x96\x80\x2c\x7b\xe8\x93\x1f\x89"
+ "\x92\x60\x21\xcd\x34\x55\x00\x66\x31\x03\x01\x01\x44\x25\x94\x0b"
+ "\x42\x78\xca\x5a\x05\x1e\x77\x73\x24\x75\x6a\xc8\x45\x9c\xef\x2b"
+ "\x2a\x51\x29\x8f\xeb\x7e\x62\xd7\xfa\xcd\x32\xfd\x31\xe8\xcd\xde"
+ "\xab\x0d\xb5\xb4\x56\xc2\x68\x51\x09\x0c\x29\xe5\x38\x7b\x50\x68"
+ "\xbe\x00\x87\x8c\x56\xef\xd3\x1b\xa3\xc9\x6e\xa6\x74\x43\xeb\x83"
+ "\xd4\x63\x5f\x13\x79\x1e\xf8\x85\xbf\xbf\x73\x69\x36\xc5\x56\x12"
+ "\x6c\xe4\xee\xaf\x86\xab\x65\xb6\x04\xf0\x5a\x63\x2d\xa3\x31\x6c"
+ "\xe8\x48\x10\x65\xc0\x74\x45\x0d\x97\x58\x90\x3d\x91\x83\x14\xf2"
+ "\x6f\xba\xad\x2f\x6c\x41\x6e\x3c\xb7\x8f\x72\x4a\x1d\xf0\xb7\x1a"
+ "\xc0\xf0\x72\x0b\x3d\x9d\x7a\x8b\x4d\xb0\x33\xb7\x5f\x83\xef\x08"
+ "\x5b\x5f\x35\x35\x3b\x52\xdf\x30\xb1\x00\x6c\xa6\x3a\x86\xc4\xf4"
+ "\x7c\xe1\x79\x74\x5f\x0b\x35\xb8\xe1\x02\x03\x01\x00\x01\xa3\x82"
+ "\x02\x82\x30\x82\x02\x7e\x30\x0e\x06\x03\x55\x1d\x0f\x01\x01\xff"
+ "\x04\x04\x03\x02\x01\x86\x30\x0f\x06\x03\x55\x1d\x13\x01\x01\xff"
+ "\x04\x05\x30\x03\x01\x01\xff\x30\x1d\x06\x03\x55\x1d\x0e\x04\x16"
+ "\x04\x14\x7a\x7d\x90\xb1\x30\x59\x08\x92\x91\xf9\x53\xb9\x71\x1d"
+ "\x35\x33\x67\x34\x8b\xd5\x30\x1f\x06\x03\x55\x1d\x23\x04\x18\x30"
+ "\x16\x80\x14\x2b\xd0\x69\x47\x94\x76\x09\xfe\xf4\x6b\x8d\x2e\x40"
+ "\xa6\xf7\x47\x4d\x7f\x08\x5e\x30\x82\x01\x28\x06\x03\x55\x1d\x20"
+ "\x04\x82\x01\x1f\x30\x82\x01\x1b\x30\x82\x01\x17\x06\x09\x2a\x86"
+ "\x48\x86\xf7\x63\x64\x05\x02\x30\x82\x01\x08\x30\x40\x06\x08\x2b"
+ "\x06\x01\x05\x05\x07\x02\x01\x16\x34\x68\x74\x74\x70\x3a\x2f\x2f"
+ "\x77\x77\x77\x2e\x61\x70\x70\x6c\x65\x2e\x63\x6f\x6d\x2f\x63\x65"
+ "\x72\x74\x69\x66\x69\x63\x61\x74\x65\x61\x75\x74\x68\x6f\x72\x69"
+ "\x74\x79\x2f\x74\x65\x72\x6d\x73\x2e\x68\x74\x6d\x6c\x30\x81\xc3"
+ "\x06\x08\x2b\x06\x01\x05\x05\x07\x02\x02\x30\x81\xb6\x1a\x81\xb3"
+ "\x52\x65\x6c\x69\x61\x6e\x63\x65\x20\x6f\x6e\x20\x74\x68\x69\x73"
+ "\x20\x63\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x20\x62\x79\x20"
+ "\x61\x6e\x79\x20\x70\x61\x72\x74\x79\x20\x61\x73\x73\x75\x6d\x65"
+ "\x73\x20\x61\x63\x63\x65\x70\x74\x61\x6e\x63\x65\x20\x6f\x66\x20"
+ "\x74\x68\x65\x20\x74\x68\x65\x6e\x20\x61\x70\x70\x6c\x69\x63\x61"
+ "\x62\x6c\x65\x20\x73\x74\x61\x6e\x64\x61\x72\x64\x20\x74\x65\x72"
+ "\x6d\x73\x20\x61\x6e\x64\x20\x63\x6f\x6e\x64\x69\x74\x69\x6f\x6e"
+ "\x73\x20\x6f\x66\x20\x75\x73\x65\x2c\x20\x63\x65\x72\x74\x69\x66"
+ "\x69\x63\x61\x74\x65\x20\x70\x6f\x6c\x69\x63\x79\x20\x61\x6e\x64"
+ "\x20\x63\x65\x72\x74\x69\x66\x69\x63\x61\x74\x69\x6f\x6e\x20\x70"
+ "\x72\x61\x63\x74\x69\x63\x65\x20\x73\x74\x61\x74\x65\x6d\x65\x6e"
+ "\x74\x73\x2e\x30\x43\x06\x03\x55\x1d\x1f\x04\x3c\x30\x3a\x30\x38"
+ "\xa0\x36\xa0\x34\x86\x32\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77"
+ "\x2e\x61\x70\x70\x6c\x65\x2e\x63\x6f\x6d\x2f\x63\x65\x72\x74\x69"
+ "\x66\x69\x63\x61\x74\x65\x61\x75\x74\x68\x6f\x72\x69\x74\x79\x2f"
+ "\x72\x6f\x6f\x74\x2e\x63\x72\x6c\x30\x81\xa9\x06\x08\x2b\x06\x01"
+ "\x05\x05\x07\x01\x01\x04\x81\x9c\x30\x81\x99\x30\x44\x06\x08\x2b"
+ "\x06\x01\x05\x05\x07\x30\x02\x86\x38\x68\x74\x74\x70\x3a\x2f\x2f"
+ "\x77\x77\x77\x2e\x61\x70\x70\x6c\x65\x2e\x63\x6f\x6d\x2f\x63\x65"
+ "\x72\x74\x69\x66\x69\x63\x61\x74\x65\x61\x75\x74\x68\x6f\x72\x69"
+ "\x74\x79\x2f\x63\x61\x73\x69\x67\x6e\x65\x72\x73\x2e\x68\x74\x6d"
+ "\x6c\x30\x51\x06\x03\x55\x1d\x12\x86\x4a\x68\x74\x74\x70\x3a\x2f"
+ "\x2f\x77\x77\x77\x2e\x61\x70\x70\x6c\x65\x2e\x63\x6f\x6d\x2f\x63"
+ "\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x61\x75\x74\x68\x6f\x72"
+ "\x69\x74\x79\x2f\x41\x70\x70\x6c\x65\x43\x6f\x6d\x70\x75\x74\x65"
+ "\x72\x52\x6f\x6f\x74\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65"
+ "\x2e\x63\x65\x72\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01"
+ "\x05\x05\x00\x03\x82\x01\x01\x00\x16\x06\xe5\x56\x65\x44\x7d\xd0"
+ "\xaa\x99\x29\xe5\xc6\x97\x0b\x02\x43\x25\x88\x8c\x42\xba\xfb\xd6"
+ "\x5b\xb7\x20\x10\x69\x04\x4e\x91\x81\x08\xec\xf5\x23\x1f\xd2\x6d"
+ "\x3f\x35\xae\xdb\xff\xb8\xc9\x2b\x4b\x28\x73\xc4\x26\x03\xe1\x92"
+ "\x5e\xb2\x84\x0d\xa7\x13\xc6\x34\x54\xf1\x49\x1f\xa9\x47\x88\xb1"
+ "\x40\x9b\xd3\x61\x93\x5b\xcf\xc7\x53\xe7\x9f\x54\x7b\x30\xc6\xb8"
+ "\x3a\x89\x6f\x06\x09\x45\xa1\x94\x98\xbe\x8b\xea\x25\x7d\x91\x89"
+ "\xf9\x27\x62\xb9\x5f\x2d\xea\xa9\xe7\x96\x5c\xbe\xe5\x84\x6d\xe8"
+ "\x50\x27\xb4\xb1\xea\x9f\xf7\x92\x0d\x54\x86\xf0\x37\x31\x47\x0d"
+ "\x54\xde\x91\xe8\x78\xe8\x61\x27\x7c\xc3\xea\xd0\xfc\x21\xa1\x08"
+ "\xc8\xe5\x01\x0e\x15\xf5\x61\x60\xce\xff\xbd\x44\xd6\x8a\x1b\x67"
+ "\xf8\x1f\x82\xe2\xa6\xb3\xfc\x3a\xc7\x30\xae\x93\x89\x29\x2e\x81"
+ "\x43\x0c\x9b\xd5\x18\xa6\x74\x66\x7d\x1c\x79\xe6\x22\xef\xba\xf8"
+ "\x23\xb3\xd3\x50\x76\x20\xde\x7a\x93\x91\x40\xcd\x16\xad\x82\x6a"
+ "\xe6\xe7\x25\xf5\xb3\xbb\x36\x61\x38\x8f\xaf\x36\x5f\x4b\xae\xc1"
+ "\xc6\x89\x99\xb1\xb1\xd9\xf1\xa3\x51\x50\xa1\x00\x3d\xdd\x16\x89"
+ "\xcf\x35\x05\x62\xa0\x8b\x48\x0a\x31\x82\x01\x35\x30\x82\x01\x31"
+ "\x02\x01\x01\x30\x81\x8e\x30\x81\x86\x31\x0b\x30\x09\x06\x03\x55"
+ "\x04\x06\x13\x02\x55\x53\x31\x1d\x30\x1b\x06\x03\x55\x04\x0a\x13"
+ "\x14\x41\x70\x70\x6c\x65\x20\x43\x6f\x6d\x70\x75\x74\x65\x72\x2c"
+ "\x20\x49\x6e\x63\x2e\x31\x2d\x30\x2b\x06\x03\x55\x04\x0b\x13\x24"
+ "\x41\x70\x70\x6c\x65\x20\x43\x6f\x6d\x70\x75\x74\x65\x72\x20\x43"
+ "\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x20\x41\x75\x74\x68\x6f"
+ "\x72\x69\x74\x79\x31\x29\x30\x27\x06\x03\x55\x04\x03\x13\x20\x41"
+ "\x70\x70\x6c\x65\x20\x2e\x4d\x61\x63\x20\x43\x65\x72\x74\x69\x66"
+ "\x69\x63\x61\x74\x65\x20\x41\x75\x74\x68\x6f\x72\x69\x74\x79\x02"
+ "\x03\x47\x3d\x05\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x30"
+ "\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00\x04\x81"
+ "\x80\x6d\xba\xa5\x44\x89\x98\x2d\x5e\xc4\xf6\xc0\x1e\x36\x70\x63"
+ "\x43\xf6\x61\x3c\x0b\x43\x32\x50\x54\x95\x1e\x51\x41\x17\xd2\x7f"
+ "\x47\x00\x21\x92\x61\xbf\x42\x63\xa4\xc8\x3a\x7f\x8d\x36\xea\xf1"
+ "\x2d\x9f\x0c\x30\xbc\xe1\x5e\x16\xea\xcc\x01\xdf\xbd\x6b\xc8\xc3"
+ "\xad\x12\x0e\x6a\x4d\xd5\xad\x15\x41\xcd\xde\xb9\xf9\xf5\xf2\xdc"
+ "\x65\xaf\x61\x28\x68\x40\x52\x59\xf8\xb8\xa6\xec\xce\xed\x5e\x16"
+ "\x7b\xbd\x72\x5e\x6a\x6e\x8b\x29\xb2\x97\x22\xe9\x99\xa3\xd6\xa9"
+ "\x0e\xb3\x5e\xd3\x18\x24\x06\x20\x78\xc8\xa7\xa8\xe7\x76\x3a\x8a"
+ "\x19\x00\x00\x00\x00\x00\x00";
+
+static size_t contentlen = 3367;
+
+
+static int
+test_ber(void)
+{
+ ContentInfo ci;
+ size_t size;
+ int ret;
+
+ ret = decode_ContentInfo(contentdata, contentlen, &ci, &size);
+ if (ret)
+ return 1;
+
+ free_ContentInfo(&ci);
+ return 0;
+}
+
+int
+main(int argc, char **argv)
+{
+ int ret = 0;
+
+ ret += test_ber();
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/asn1/check-common.c b/third_party/heimdal/lib/asn1/check-common.c
new file mode 100644
index 0000000..8a6b5da
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/check-common.c
@@ -0,0 +1,422 @@
+/*
+ * Copyright (c) 1999 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#ifdef HAVE_SYS_MMAN_H
+#include <sys/mman.h>
+#endif
+#include <stdio.h>
+#include <string.h>
+#include <err.h>
+#include <roken.h>
+
+#include "asn1-common.h"
+#include "check-common.h"
+
+struct map_page {
+ void *start;
+ size_t size;
+ void *data_start;
+ size_t data_size;
+ enum map_type type;
+};
+
+/* #undef HAVE_MMAP */
+
+void *
+map_alloc(enum map_type type, const void *buf,
+ size_t size, struct map_page **map)
+{
+#ifndef HAVE_MMAP
+ unsigned char *p;
+ size_t len = size + sizeof(long) * 2;
+ int i;
+
+ *map = ecalloc(1, sizeof(**map));
+
+ p = emalloc(len);
+ (*map)->type = type;
+ (*map)->start = p;
+ (*map)->size = len;
+ (*map)->data_start = p + sizeof(long);
+ for (i = sizeof(long); i > 0; i--)
+ p[sizeof(long) - i] = 0xff - i;
+ for (i = sizeof(long); i > 0; i--)
+ p[len - i] = 0xff - i;
+#else
+ unsigned char *p;
+ int flags, ret, fd;
+ size_t pagesize = getpagesize();
+
+ *map = ecalloc(1, sizeof(**map));
+
+ (*map)->type = type;
+
+#ifdef MAP_ANON
+ flags = MAP_ANON;
+ fd = -1;
+#else
+ flags = 0;
+ fd = open ("/dev/zero", O_RDONLY);
+ if(fd < 0)
+ err (1, "open /dev/zero");
+#endif
+ flags |= MAP_PRIVATE;
+
+ (*map)->size = size + pagesize - (size % pagesize) + pagesize * 2;
+
+ p = (unsigned char *)mmap(0, (*map)->size, PROT_READ | PROT_WRITE,
+ flags, fd, 0);
+ if (p == (unsigned char *)MAP_FAILED)
+ err (1, "mmap");
+
+ (*map)->start = p;
+
+ ret = mprotect (p, pagesize, 0);
+ if (ret < 0)
+ err (1, "mprotect");
+
+ ret = mprotect (p + (*map)->size - pagesize, pagesize, 0);
+ if (ret < 0)
+ err (1, "mprotect");
+
+ switch (type) {
+ case OVERRUN:
+ (*map)->data_start = p + (*map)->size - pagesize - size;
+ break;
+ case UNDERRUN:
+ (*map)->data_start = p + pagesize;
+ break;
+ default:
+ abort();
+ }
+#endif
+ (*map)->data_size = size;
+ if (buf)
+ memcpy((*map)->data_start, buf, size);
+ return (*map)->data_start;
+}
+
+void
+map_free(struct map_page *map, const char *test_name, const char *map_name)
+{
+#ifndef HAVE_MMAP
+ unsigned char *p = map->start;
+ int i;
+
+ for (i = sizeof(long); i > 0; i--)
+ if (p[sizeof(long) - i] != 0xff - i)
+ errx(1, "%s: %s underrun %d\n", test_name, map_name, i);
+ for (i = sizeof(long); i > 0; i--)
+ if (p[map->size - i] != 0xff - i)
+ errx(1, "%s: %s overrun %lu\n", test_name, map_name,
+ (unsigned long)map->size - i);
+ free(map->start);
+#else
+ int ret;
+
+ ret = munmap (map->start, map->size);
+ if (ret < 0)
+ err (1, "munmap");
+#endif
+ free(map);
+}
+
+static void
+print_bytes (unsigned const char *buf, size_t len)
+{
+ int i;
+
+ for (i = 0; i < len; ++i)
+ printf ("%02x ", buf[i]);
+}
+
+#ifndef MAP_FAILED
+#define MAP_FAILED (-1)
+#endif
+
+static char *current_test = "<uninit>";
+static char *current_state = "<uninit>";
+
+static RETSIGTYPE
+segv_handler(int sig)
+{
+ int fd;
+ char msg[] = "SIGSEGV i current test: ";
+ /* For compilers that insist we check write(2)'s result here */
+ int e = 1;
+
+ fd = open("/dev/stdout", O_WRONLY, 0600);
+ if (fd >= 0) {
+
+ if (write(fd, msg, sizeof(msg)) == -1 ||
+ write(fd, current_test, strlen(current_test)) == -1 ||
+ write(fd, " ", 1) == -1 ||
+ write(fd, current_state, strlen(current_state)) == -1 ||
+ write(fd, "\n", 1) == -1)
+ e = 2;
+ (void) close(fd);
+ }
+ _exit(e);
+}
+
+int
+generic_test (const struct test_case *tests,
+ unsigned ntests,
+ size_t data_size,
+ int (ASN1CALL *encode)(unsigned char *, size_t, void *, size_t *),
+ size_t (ASN1CALL *length)(void *),
+ int (ASN1CALL *decode)(unsigned char *, size_t, void *, size_t *),
+ void (ASN1CALL *free_data)(void *),
+ int (*cmp)(void *a, void *b),
+ int (ASN1CALL *copy)(const void *from, void *to))
+{
+ unsigned char *buf, *buf2;
+ int i;
+ int failures = 0;
+ void *data;
+ struct map_page *data_map, *buf_map, *buf2_map;
+
+#ifdef HAVE_SIGACTION
+ struct sigaction sa, osa;
+#endif
+
+ for (i = 0; i < ntests; ++i) {
+ int ret;
+ size_t sz, consumed_sz, length_sz, buf_sz;
+ void *to = NULL;
+
+ current_test = tests[i].name;
+
+ current_state = "init";
+
+#ifdef HAVE_SIGACTION
+ sigemptyset (&sa.sa_mask);
+ sa.sa_flags = 0;
+#ifdef SA_RESETHAND
+ sa.sa_flags |= SA_RESETHAND;
+#endif
+ sa.sa_handler = segv_handler;
+ sigaction (SIGSEGV, &sa, &osa);
+#endif
+
+ data = map_alloc(OVERRUN, NULL, data_size, &data_map);
+
+ buf_sz = tests[i].byte_len;
+ buf = map_alloc(UNDERRUN, NULL, buf_sz, &buf_map);
+
+ current_state = "encode";
+ ret = (*encode) (buf + buf_sz - 1, buf_sz,
+ tests[i].val, &sz);
+ if (ret != 0) {
+ printf ("encoding of %s failed %d\n", tests[i].name, ret);
+ ++failures;
+ continue;
+ }
+ if (sz != tests[i].byte_len) {
+ printf ("encoding of %s has wrong len (%lu != %lu)\n",
+ tests[i].name,
+ (unsigned long)sz, (unsigned long)tests[i].byte_len);
+ ++failures;
+ continue;
+ }
+
+ current_state = "length";
+ length_sz = (*length) (tests[i].val);
+ if (sz != length_sz) {
+ printf ("length for %s is bad (%lu != %lu)\n",
+ tests[i].name, (unsigned long)length_sz, (unsigned long)sz);
+ ++failures;
+ continue;
+ }
+
+ current_state = "memcmp";
+ if (memcmp (buf, tests[i].bytes, tests[i].byte_len) != 0) {
+ printf ("encoding of %s has bad bytes:\n"
+ "correct: ", tests[i].name);
+ print_bytes ((unsigned char *)tests[i].bytes, tests[i].byte_len);
+ printf ("\nactual: ");
+ print_bytes (buf, sz);
+ printf ("\n");
+#if 0
+ rk_dumpdata("correct", tests[i].bytes, tests[i].byte_len);
+ rk_dumpdata("actual", buf, sz);
+ exit (1);
+#endif
+ ++failures;
+ continue;
+ }
+
+ buf2 = map_alloc(OVERRUN, buf, sz, &buf2_map);
+
+ current_state = "decode";
+ ret = (*decode) (buf2, sz, data, &consumed_sz);
+ if (ret != 0) {
+ printf ("decoding of %s failed %d\n", tests[i].name, ret);
+ ++failures;
+ continue;
+ }
+ if (sz != consumed_sz) {
+ printf ("different length decoding %s (%ld != %ld)\n",
+ tests[i].name,
+ (unsigned long)sz, (unsigned long)consumed_sz);
+ ++failures;
+ continue;
+ }
+ current_state = "cmp";
+ if ((*cmp)(data, tests[i].val) != 0) {
+ printf ("%s: comparison failed\n", tests[i].name);
+ ++failures;
+ continue;
+ }
+
+ current_state = "copy";
+ if (copy) {
+ to = emalloc(data_size);
+ ret = (*copy)(data, to);
+ if (ret != 0) {
+ printf ("copy of %s failed %d\n", tests[i].name, ret);
+ ++failures;
+ continue;
+ }
+
+ current_state = "cmp-copy";
+ if ((*cmp)(data, to) != 0) {
+ printf ("%s: copy comparison failed\n", tests[i].name);
+ ++failures;
+ continue;
+ }
+ }
+
+ current_state = "free";
+ if (free_data) {
+ (*free_data)(data);
+ if (to) {
+ (*free_data)(to);
+ free(to);
+ }
+ }
+
+ current_state = "free";
+ map_free(buf_map, tests[i].name, "encode");
+ map_free(buf2_map, tests[i].name, "decode");
+ map_free(data_map, tests[i].name, "data");
+
+#ifdef HAVE_SIGACTION
+ sigaction (SIGSEGV, &osa, NULL);
+#endif
+ }
+ current_state = "done";
+ return failures;
+}
+
+/*
+ * check for failures
+ *
+ * a test size (byte_len) of -1 means that the test tries to trigger a
+ * integer overflow (and later a malloc of to little memory), just
+ * allocate some memory and hope that is enough for that test.
+ */
+
+int
+generic_decode_fail (const struct test_case *tests,
+ unsigned ntests,
+ size_t data_size,
+ int (ASN1CALL *decode)(unsigned char *, size_t, void *, size_t *))
+{
+ unsigned char *buf;
+ int i;
+ int failures = 0;
+ void *data;
+ struct map_page *data_map, *buf_map;
+
+#ifdef HAVE_SIGACTION
+ struct sigaction sa, osa;
+#endif
+
+ for (i = 0; i < ntests; ++i) {
+ int ret;
+ size_t sz;
+ const void *bytes;
+
+ current_test = tests[i].name;
+
+ current_state = "init";
+
+#ifdef HAVE_SIGACTION
+ sigemptyset (&sa.sa_mask);
+ sa.sa_flags = 0;
+#ifdef SA_RESETHAND
+ sa.sa_flags |= SA_RESETHAND;
+#endif
+ sa.sa_handler = segv_handler;
+ sigaction (SIGSEGV, &sa, &osa);
+#endif
+
+ data = map_alloc(OVERRUN, NULL, data_size, &data_map);
+
+ if (tests[i].byte_len < 0xffffff && tests[i].byte_len >= 0) {
+ sz = tests[i].byte_len;
+ bytes = tests[i].bytes;
+ } else {
+ sz = 4096;
+ bytes = NULL;
+ }
+
+ buf = map_alloc(OVERRUN, bytes, sz, &buf_map);
+
+ if (tests[i].byte_len == -1)
+ memset(buf, 0, sz);
+
+ current_state = "decode";
+ ret = (*decode) (buf, tests[i].byte_len, data, &sz);
+ if (ret == 0) {
+ printf ("sucessfully decoded %s\n", tests[i].name);
+ ++failures;
+ continue;
+ }
+
+ current_state = "free";
+ if (buf)
+ map_free(buf_map, tests[i].name, "encode");
+ map_free(data_map, tests[i].name, "data");
+
+#ifdef HAVE_SIGACTION
+ sigaction (SIGSEGV, &osa, NULL);
+#endif
+ }
+ current_state = "done";
+ return failures;
+}
diff --git a/third_party/heimdal/lib/asn1/check-common.h b/third_party/heimdal/lib/asn1/check-common.h
new file mode 100644
index 0000000..6ea1f81
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/check-common.h
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 1999 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#define IF_OPT_COMPARE(ac,bc,e) \
+ if (((ac)->e == NULL && (bc)->e != NULL) || (((ac)->e != NULL && (bc)->e == NULL))) return 1; \
+ if ((ac)->e)
+#define COMPARE_OPT_STRING(ac,bc,e) \
+ do { if (strcmp(*(ac)->e, *(bc)->e) != 0) return 1; } while(0)
+#define COMPARE_OPT_OCTET_STRING(ac,bc,e) \
+ do { if ((ac)->e->length != (bc)->e->length || memcmp((ac)->e->data, (bc)->e->data, (ac)->e->length) != 0) return 1; } while(0)
+#define COMPARE_STRING(ac,bc,e) \
+ do { if (strcmp((ac)->e, (bc)->e) != 0) return 1; } while(0)
+#define COMPARE_INTEGER(ac,bc,e) \
+ do { if ((ac)->e != (bc)->e) return 1; } while(0)
+#define COMPARE_OPT_INTEGER(ac,bc,e) \
+ do { if (*(ac)->e != *(bc)->e) return 1; } while(0)
+#define COMPARE_MEM(ac,bc,e,len) \
+ do { if (memcmp((ac)->e, (bc)->e,len) != 0) return 1; } while(0)
+#define COMPARE_OCTET_STRING(ac,bc,e) \
+ do { if ((ac)->e.length != (bc)->e.length || memcmp((ac)->e.data, (bc)->e.data, (ac)->e.length) != 0) return 1; } while(0)
+
+struct test_case {
+ void *val;
+ ssize_t byte_len;
+ const char *bytes;
+ char *name;
+};
+
+typedef int (ASN1CALL *generic_encode)(unsigned char *, size_t, void *, size_t *);
+typedef size_t (ASN1CALL *generic_length)(void *);
+typedef int (ASN1CALL *generic_decode)(unsigned char *, size_t, void *, size_t *);
+typedef void (ASN1CALL *generic_free)(void *);
+typedef int (ASN1CALL *generic_copy)(const void *, void *);
+
+int
+generic_test (const struct test_case *tests,
+ unsigned ntests,
+ size_t data_size,
+ int (ASN1CALL *encode)(unsigned char *, size_t, void *, size_t *),
+ size_t (ASN1CALL *length)(void *),
+ int (ASN1CALL *decode)(unsigned char *, size_t, void *, size_t *),
+ void (ASN1CALL *free_data)(void *),
+ int (*cmp)(void *a, void *b),
+ int (ASN1CALL *copy)(const void *a, void *b));
+
+int
+generic_decode_fail(const struct test_case *tests,
+ unsigned ntests,
+ size_t data_size,
+ int (ASN1CALL *decode)(unsigned char *, size_t, void *, size_t *));
+
+
+struct map_page;
+
+enum map_type { OVERRUN, UNDERRUN };
+
+struct map_page;
+
+void * map_alloc(enum map_type, const void *, size_t, struct map_page **);
+void map_free(struct map_page *, const char *, const char *);
diff --git a/third_party/heimdal/lib/asn1/check-der.c b/third_party/heimdal/lib/asn1/check-der.c
new file mode 100644
index 0000000..a8956a7
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/check-der.c
@@ -0,0 +1,1210 @@
+/*
+ * Copyright (c) 1999 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+#include <err.h>
+#include <roken.h>
+
+#include <asn1-common.h>
+#include <asn1_err.h>
+#include <der.h>
+
+#include "check-common.h"
+
+RCSID("$Id$");
+
+static int
+cmp_integer (void *a, void *b)
+{
+ int *ia = (int *)a;
+ int *ib = (int *)b;
+
+ return *ib - *ia;
+}
+
+static int
+test_integer (void)
+{
+ struct test_case tests[] = {
+ {NULL, 1, "\x00", NULL },
+ {NULL, 1, "\x7f", NULL },
+ {NULL, 2, "\x00\x80", NULL },
+ {NULL, 2, "\x01\x00", NULL },
+ {NULL, 1, "\x80", NULL },
+ {NULL, 2, "\xff\x7f", NULL },
+ {NULL, 1, "\xff", NULL },
+ {NULL, 2, "\xff\x01", NULL },
+ {NULL, 2, "\x00\xff", NULL },
+ {NULL, 4, "\x7f\xff\xff\xff", NULL }
+ };
+
+ int values[] = {0, 127, 128, 256, -128, -129, -1, -255, 255,
+ 0x7fffffff};
+ int i, ret;
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ for (i = 0; i < ntests; ++i) {
+ tests[i].val = &values[i];
+ if (asprintf (&tests[i].name, "integer %d", values[i]) < 0)
+ errx(1, "malloc");
+ if (tests[i].name == NULL)
+ errx(1, "malloc");
+ }
+
+ ret = generic_test (tests, ntests, sizeof(int),
+ (generic_encode)der_put_integer,
+ (generic_length) der_length_integer,
+ (generic_decode)der_get_integer,
+ (generic_free)NULL,
+ cmp_integer,
+ NULL);
+
+ for (i = 0; i < ntests; ++i)
+ free (tests[i].name);
+ return ret;
+}
+
+static int
+test_one_int(int val)
+{
+ int ret, dval;
+ unsigned char *buf;
+ size_t len_len, len;
+
+ len = _heim_len_int(val);
+
+ buf = emalloc(len + 2);
+
+ buf[0] = '\xff';
+ buf[len + 1] = '\xff';
+ memset(buf + 1, 0, len);
+
+ ret = der_put_integer(buf + 1 + len - 1, len, &val, &len_len);
+ if (ret) {
+ printf("integer %d encode failed %d\n", val, ret);
+ return 1;
+ }
+ if (len != len_len) {
+ printf("integer %d encode fail with %d len %lu, result len %lu\n",
+ val, ret, (unsigned long)len, (unsigned long)len_len);
+ return 1;
+ }
+
+ ret = der_get_integer(buf + 1, len, &dval, &len_len);
+ if (ret) {
+ printf("integer %d decode failed %d\n", val, ret);
+ return 1;
+ }
+ if (len != len_len) {
+ printf("integer %d decoded diffrent len %lu != %lu",
+ val, (unsigned long)len, (unsigned long)len_len);
+ return 1;
+ }
+ if (val != dval) {
+ printf("decode decoded to diffrent value %d != %d",
+ val, dval);
+ return 1;
+ }
+
+ if (buf[0] != (unsigned char)'\xff') {
+ printf("precanary dead %d\n", val);
+ return 1;
+ }
+ if (buf[len + 1] != (unsigned char)'\xff') {
+ printf("postecanary dead %d\n", val);
+ return 1;
+ }
+ free(buf);
+ return 0;
+}
+
+static int
+test_integer_more (void)
+{
+ int i, n1, n2, n3, n4, n5, n6;
+
+ n2 = 0;
+ for (i = 0; i < (sizeof(int) * 8); i++) {
+ n1 = 0x01 << i;
+ n2 = n2 | n1;
+ n3 = ~n1;
+ n4 = ~n2;
+ n5 = (-1) & ~(0x3f << i);
+ n6 = (-1) & ~(0x7f << i);
+
+ test_one_int(n1);
+ test_one_int(n2);
+ test_one_int(n3);
+ test_one_int(n4);
+ test_one_int(n5);
+ test_one_int(n6);
+ }
+ return 0;
+}
+
+static int
+cmp_unsigned (void *a, void *b)
+{
+ return *(unsigned int*)b - *(unsigned int*)a;
+}
+
+static int
+test_unsigned (void)
+{
+ struct test_case tests[] = {
+ {NULL, 1, "\x00", NULL },
+ {NULL, 1, "\x7f", NULL },
+ {NULL, 2, "\x00\x80", NULL },
+ {NULL, 2, "\x01\x00", NULL },
+ {NULL, 2, "\x02\x00", NULL },
+ {NULL, 3, "\x00\x80\x00", NULL },
+ {NULL, 5, "\x00\x80\x00\x00\x00", NULL },
+ {NULL, 4, "\x7f\xff\xff\xff", NULL }
+ };
+
+ unsigned int values[] = {0, 127, 128, 256, 512, 32768,
+ 0x80000000, 0x7fffffff};
+ int i, ret;
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ for (i = 0; i < ntests; ++i) {
+ tests[i].val = &values[i];
+ if (asprintf (&tests[i].name, "unsigned %u", values[i]) < 0)
+ errx(1, "malloc");
+ if (tests[i].name == NULL)
+ errx(1, "malloc");
+ }
+
+ ret = generic_test (tests, ntests, sizeof(int),
+ (generic_encode)der_put_unsigned,
+ (generic_length)der_length_unsigned,
+ (generic_decode)der_get_unsigned,
+ (generic_free)NULL,
+ cmp_unsigned,
+ NULL);
+ for (i = 0; i < ntests; ++i)
+ free (tests[i].name);
+ return ret;
+}
+
+static int
+cmp_octet_string (void *a, void *b)
+{
+ return der_heim_octet_string_cmp(a, b);
+}
+
+static int
+test_octet_string (void)
+{
+ heim_octet_string s1 = {8, "\x01\x23\x45\x67\x89\xab\xcd\xef"};
+
+ struct test_case tests[] = {
+ {NULL, 8, "\x01\x23\x45\x67\x89\xab\xcd\xef", NULL }
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+ int ret;
+
+ tests[0].val = &s1;
+ if (asprintf (&tests[0].name, "a octet string") < 0)
+ errx(1, "malloc");
+ if (tests[0].name == NULL)
+ errx(1, "malloc");
+
+ ret = generic_test (tests, ntests, sizeof(heim_octet_string),
+ (generic_encode)der_put_octet_string,
+ (generic_length)der_length_octet_string,
+ (generic_decode)der_get_octet_string,
+ (generic_free)der_free_octet_string,
+ cmp_octet_string,
+ NULL);
+ free(tests[0].name);
+ return ret;
+}
+
+static int
+cmp_bmp_string (void *a, void *b)
+{
+ heim_bmp_string *oa = (heim_bmp_string *)a;
+ heim_bmp_string *ob = (heim_bmp_string *)b;
+
+ return der_heim_bmp_string_cmp(oa, ob);
+}
+
+static uint16_t bmp_d1[] = { 32 };
+static uint16_t bmp_d2[] = { 32, 32 };
+
+static int
+test_bmp_string (void)
+{
+ heim_bmp_string s1 = { 1, bmp_d1 };
+ heim_bmp_string s2 = { 2, bmp_d2 };
+
+ struct test_case tests[] = {
+ {NULL, 2, "\x00\x20", NULL },
+ {NULL, 4, "\x00\x20\x00\x20", NULL }
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+ int ret;
+
+ tests[0].val = &s1;
+ if (asprintf (&tests[0].name, "a bmp string") < 0)
+ errx(1, "malloc");
+ if (tests[0].name == NULL)
+ errx(1, "malloc");
+ tests[1].val = &s2;
+ if (asprintf (&tests[1].name, "second bmp string") < 0)
+ errx(1, "malloc");
+ if (tests[1].name == NULL)
+ errx(1, "malloc");
+
+ ret = generic_test (tests, ntests, sizeof(heim_bmp_string),
+ (generic_encode)der_put_bmp_string,
+ (generic_length)der_length_bmp_string,
+ (generic_decode)der_get_bmp_string,
+ (generic_free)der_free_bmp_string,
+ cmp_bmp_string,
+ NULL);
+ free(tests[0].name);
+ free(tests[1].name);
+ return ret;
+}
+
+static int
+cmp_universal_string (void *a, void *b)
+{
+ heim_universal_string *oa = (heim_universal_string *)a;
+ heim_universal_string *ob = (heim_universal_string *)b;
+
+ return der_heim_universal_string_cmp(oa, ob);
+}
+
+static uint32_t universal_d1[] = { 32 };
+static uint32_t universal_d2[] = { 32, 32 };
+
+static int
+test_universal_string (void)
+{
+ heim_universal_string s1 = { 1, universal_d1 };
+ heim_universal_string s2 = { 2, universal_d2 };
+
+ struct test_case tests[] = {
+ {NULL, 4, "\x00\x00\x00\x20", NULL },
+ {NULL, 8, "\x00\x00\x00\x20\x00\x00\x00\x20", NULL }
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+ int ret;
+
+ tests[0].val = &s1;
+ if (asprintf (&tests[0].name, "a universal string") < 0)
+ errx(1, "malloc");
+ if (tests[0].name == NULL)
+ errx(1, "malloc");
+ tests[1].val = &s2;
+ if (asprintf (&tests[1].name, "second universal string") < 0)
+ errx(1, "malloc");
+ if (tests[1].name == NULL)
+ errx(1, "malloc");
+
+ ret = generic_test (tests, ntests, sizeof(heim_universal_string),
+ (generic_encode)der_put_universal_string,
+ (generic_length)der_length_universal_string,
+ (generic_decode)der_get_universal_string,
+ (generic_free)der_free_universal_string,
+ cmp_universal_string,
+ NULL);
+ free(tests[0].name);
+ free(tests[1].name);
+ return ret;
+}
+
+static int
+cmp_general_string (void *a, void *b)
+{
+ char **sa = (char **)a;
+ char **sb = (char **)b;
+
+ return strcmp (*sa, *sb);
+}
+
+static int
+test_general_string (void)
+{
+ char *s1 = "Test User 1";
+
+ struct test_case tests[] = {
+ {NULL, 11, "\x54\x65\x73\x74\x20\x55\x73\x65\x72\x20\x31", NULL }
+ };
+ int ret, ntests = sizeof(tests) / sizeof(*tests);
+
+ tests[0].val = &s1;
+ if (asprintf (&tests[0].name, "the string \"%s\"", s1) < 0)
+ errx(1, "malloc");
+ if (tests[0].name == NULL)
+ errx(1, "malloc");
+
+ ret = generic_test (tests, ntests, sizeof(unsigned char *),
+ (generic_encode)der_put_general_string,
+ (generic_length)der_length_general_string,
+ (generic_decode)der_get_general_string,
+ (generic_free)der_free_general_string,
+ cmp_general_string,
+ NULL);
+ free(tests[0].name);
+ return ret;
+}
+
+static int
+cmp_generalized_time (void *a, void *b)
+{
+ time_t *ta = (time_t *)a;
+ time_t *tb = (time_t *)b;
+
+ return (int)(*tb - *ta);
+}
+
+static int
+test_generalized_time (void)
+{
+ struct test_case tests[] = {
+ {NULL, 15, "19700101000000Z", NULL },
+ {NULL, 15, "19851106210627Z", NULL }
+ };
+ time_t values[] = {0, 500159187};
+ int i, ret;
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ for (i = 0; i < ntests; ++i) {
+ tests[i].val = &values[i];
+ if (asprintf (&tests[i].name, "time %d", (int)values[i]) < 0)
+ errx(1, "malloc");
+ if (tests[i].name == NULL)
+ errx(1, "malloc");
+ }
+
+ ret = generic_test (tests, ntests, sizeof(time_t),
+ (generic_encode)der_put_generalized_time,
+ (generic_length)der_length_generalized_time,
+ (generic_decode)der_get_generalized_time,
+ (generic_free)NULL,
+ cmp_generalized_time,
+ NULL);
+ for (i = 0; i < ntests; ++i)
+ free(tests[i].name);
+ return ret;
+}
+
+static int
+test_cmp_oid (void *a, void *b)
+{
+ return der_heim_oid_cmp((heim_oid *)a, (heim_oid *)b);
+}
+
+static unsigned oid_comp1[] = { 1, 1, 1 };
+static unsigned oid_comp2[] = { 1, 1 };
+static unsigned oid_comp3[] = { 6, 15, 1 };
+static unsigned oid_comp4[] = { 6, 15 };
+
+static int
+test_oid (void)
+{
+ struct test_case tests[] = {
+ {NULL, 2, "\x29\x01", NULL },
+ {NULL, 1, "\x29", NULL },
+ {NULL, 2, "\xff\x01", NULL },
+ {NULL, 1, "\xff", NULL }
+ };
+ heim_oid values[] = {
+ { 3, oid_comp1 },
+ { 2, oid_comp2 },
+ { 3, oid_comp3 },
+ { 2, oid_comp4 }
+ };
+ int i, ret;
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ for (i = 0; i < ntests; ++i) {
+ tests[i].val = &values[i];
+ if (asprintf (&tests[i].name, "oid %d", i) < 0)
+ errx(1, "malloc");
+ if (tests[i].name == NULL)
+ errx(1, "malloc");
+ }
+
+ ret = generic_test (tests, ntests, sizeof(heim_oid),
+ (generic_encode)der_put_oid,
+ (generic_length)der_length_oid,
+ (generic_decode)der_get_oid,
+ (generic_free)der_free_oid,
+ test_cmp_oid,
+ NULL);
+ for (i = 0; i < ntests; ++i)
+ free(tests[i].name);
+ return ret;
+}
+
+static int
+test_cmp_bit_string (void *a, void *b)
+{
+ return der_heim_bit_string_cmp((heim_bit_string *)a, (heim_bit_string *)b);
+}
+
+static int
+test_bit_string (void)
+{
+ struct test_case tests[] = {
+ {NULL, 1, "\x00", NULL }
+ };
+ heim_bit_string values[] = {
+ { 0, "" }
+ };
+ int i, ret;
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ for (i = 0; i < ntests; ++i) {
+ tests[i].val = &values[i];
+ if (asprintf (&tests[i].name, "bit_string %d", i) < 0)
+ errx(1, "malloc");
+ if (tests[i].name == NULL)
+ errx(1, "malloc");
+ }
+
+ ret = generic_test (tests, ntests, sizeof(heim_bit_string),
+ (generic_encode)der_put_bit_string,
+ (generic_length)der_length_bit_string,
+ (generic_decode)der_get_bit_string,
+ (generic_free)der_free_bit_string,
+ test_cmp_bit_string,
+ NULL);
+ for (i = 0; i < ntests; ++i)
+ free(tests[i].name);
+ return ret;
+}
+
+static int
+test_cmp_heim_integer (void *a, void *b)
+{
+ return der_heim_integer_cmp((heim_integer *)a, (heim_integer *)b);
+}
+
+static int
+test_heim_integer (void)
+{
+ struct test_case tests[] = {
+ {NULL, 2, "\xfe\x01", NULL },
+ {NULL, 2, "\xef\x01", NULL },
+ {NULL, 3, "\xff\x00\xff", NULL },
+ {NULL, 3, "\xff\x01\x00", NULL },
+ {NULL, 1, "\x00", NULL },
+ {NULL, 1, "\x01", NULL },
+ {NULL, 2, "\x00\x80", NULL }
+ };
+
+ heim_integer values[] = {
+ { 2, "\x01\xff", 1 },
+ { 2, "\x10\xff", 1 },
+ { 2, "\xff\x01", 1 },
+ { 2, "\xff\x00", 1 },
+ { 0, "", 0 },
+ { 1, "\x01", 0 },
+ { 1, "\x80", 0 }
+ };
+ int i, ret;
+ int ntests = sizeof(tests) / sizeof(tests[0]);
+ size_t size;
+ heim_integer i2;
+
+ for (i = 0; i < ntests; ++i) {
+ tests[i].val = &values[i];
+ if (asprintf (&tests[i].name, "heim_integer %d", i) < 0)
+ errx(1, "malloc");
+ if (tests[i].name == NULL)
+ errx(1, "malloc");
+ }
+
+ ret = generic_test (tests, ntests, sizeof(heim_integer),
+ (generic_encode)der_put_heim_integer,
+ (generic_length)der_length_heim_integer,
+ (generic_decode)der_get_heim_integer,
+ (generic_free)der_free_heim_integer,
+ test_cmp_heim_integer,
+ NULL);
+ for (i = 0; i < ntests; ++i)
+ free (tests[i].name);
+ if (ret)
+ return ret;
+
+ /* test zero length integer (BER format) */
+ ret = der_get_heim_integer(NULL, 0, &i2, &size);
+ if (ret)
+ errx(1, "der_get_heim_integer");
+ if (i2.length != 0)
+ errx(1, "der_get_heim_integer wrong length");
+ der_free_heim_integer(&i2);
+
+ return 0;
+}
+
+static int
+test_cmp_boolean (void *a, void *b)
+{
+ return !!*(int *)a != !!*(int *)b;
+}
+
+static int
+test_boolean (void)
+{
+ struct test_case tests[] = {
+ {NULL, 1, "\xff", NULL },
+ {NULL, 1, "\x00", NULL }
+ };
+
+ int values[] = { 1, 0 };
+ int i, ret;
+ int ntests = sizeof(tests) / sizeof(tests[0]);
+ size_t size;
+ heim_integer i2;
+
+ for (i = 0; i < ntests; ++i) {
+ tests[i].val = &values[i];
+ if (asprintf (&tests[i].name, "heim_boolean %d", i) < 0)
+ errx(1, "malloc");
+ if (tests[i].name == NULL)
+ errx(1, "malloc");
+ }
+
+ ret = generic_test (tests, ntests, sizeof(int),
+ (generic_encode)der_put_boolean,
+ (generic_length)der_length_boolean,
+ (generic_decode)der_get_boolean,
+ (generic_free)NULL,
+ test_cmp_boolean,
+ NULL);
+ for (i = 0; i < ntests; ++i)
+ free (tests[i].name);
+ if (ret)
+ return ret;
+
+ /* test zero length integer (BER format) */
+ ret = der_get_heim_integer(NULL, 0, &i2, &size);
+ if (ret)
+ errx(1, "der_get_heim_integer");
+ if (i2.length != 0)
+ errx(1, "der_get_heim_integer wrong length");
+ der_free_heim_integer(&i2);
+
+ return 0;
+}
+
+static int
+check_fail_unsigned(void)
+{
+ struct test_case tests[] = {
+ {NULL, sizeof(unsigned) + 1,
+ "\x01\x01\x01\x01\x01\x01\x01\x01\x01", "data overrun" }
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ return generic_decode_fail(tests, ntests, sizeof(unsigned),
+ (generic_decode)der_get_unsigned);
+}
+
+static int
+check_fail_integer(void)
+{
+ struct test_case tests[] = {
+ {NULL, sizeof(int) + 1,
+ "\x01\x01\x01\x01\x01\x01\x01\x01\x01", "data overrun" }
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ return generic_decode_fail(tests, ntests, sizeof(int),
+ (generic_decode)der_get_integer);
+}
+
+static int
+check_fail_length(void)
+{
+ struct test_case tests[] = {
+ {NULL, 0, "", "empty input data"},
+ {NULL, 1, "\x82", "internal length overrun" }
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ return generic_decode_fail(tests, ntests, sizeof(size_t),
+ (generic_decode)der_get_length);
+}
+
+static int
+check_fail_boolean(void)
+{
+ struct test_case tests[] = {
+ {NULL, 0, "", "empty input data"}
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ return generic_decode_fail(tests, ntests, sizeof(int),
+ (generic_decode)der_get_boolean);
+}
+
+static int
+check_fail_general_string(void)
+{
+ struct test_case tests[] = {
+ { NULL, 3, "A\x00i", "NUL char in string"}
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ return generic_decode_fail(tests, ntests, sizeof(heim_general_string),
+ (generic_decode)der_get_general_string);
+}
+
+static int
+check_fail_bmp_string(void)
+{
+ struct test_case tests[] = {
+ {NULL, 1, "\x00", "odd (1) length bmpstring"},
+ {NULL, 3, "\x00\x00\x00", "odd (3) length bmpstring"}
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ return generic_decode_fail(tests, ntests, sizeof(heim_bmp_string),
+ (generic_decode)der_get_bmp_string);
+}
+
+static int
+check_fail_universal_string(void)
+{
+ struct test_case tests[] = {
+ {NULL, 1, "\x00", "x & 3 == 1 universal string"},
+ {NULL, 2, "\x00\x00", "x & 3 == 2 universal string"},
+ {NULL, 3, "\x00\x00\x00", "x & 3 == 3 universal string"},
+ {NULL, 5, "\x00\x00\x00\x00\x00", "x & 3 == 1 universal string"},
+ {NULL, 6, "\x00\x00\x00\x00\x00\x00", "x & 3 == 2 universal string"},
+ {NULL, 7, "\x00\x00\x00\x00\x00\x00\x00", "x & 3 == 3 universal string"}
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ return generic_decode_fail(tests, ntests, sizeof(heim_universal_string),
+ (generic_decode)der_get_universal_string);
+}
+
+static int
+check_fail_heim_integer(void)
+{
+#if 0
+ struct test_case tests[] = {
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ return generic_decode_fail(tests, ntests, sizeof(heim_integer),
+ (generic_decode)der_get_heim_integer);
+#else
+ return 0;
+#endif
+}
+
+static int
+check_fail_generalized_time(void)
+{
+ struct test_case tests[] = {
+ {NULL, 1, "\x00", "no time"}
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ return generic_decode_fail(tests, ntests, sizeof(time_t),
+ (generic_decode)der_get_generalized_time);
+}
+
+static int
+check_fail_oid(void)
+{
+ struct test_case tests[] = {
+ {NULL, 0, "", "empty input data"},
+ {NULL, 2, "\x00\x80", "last byte continuation" },
+ {NULL, 11, "\x00\x81\x80\x80\x80\x80\x80\x80\x80\x80\x00",
+ "oid element overflow" }
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ return generic_decode_fail(tests, ntests, sizeof(heim_oid),
+ (generic_decode)der_get_oid);
+}
+
+static int
+check_fail_bitstring(void)
+{
+ struct test_case tests[] = {
+ {NULL, 0, "", "empty input data"},
+ {NULL, 1, "\x08", "larger then 8 bits trailer"},
+ {NULL, 1, "\x01", "to few bytes for bits"},
+ {NULL, -2, "\x00", "length overrun"},
+ {NULL, -1, "", "length to short"}
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ return generic_decode_fail(tests, ntests, sizeof(heim_bit_string),
+ (generic_decode)der_get_bit_string);
+}
+
+static int
+check_heim_integer_same(const char *p, const char *norm_p, heim_integer *i)
+{
+ heim_integer i2;
+ char *str;
+ int ret;
+
+ ret = der_print_hex_heim_integer(i, &str);
+ if (ret)
+ errx(1, "der_print_hex_heim_integer: %d", ret);
+
+ if (strcmp(str, norm_p) != 0)
+ errx(1, "der_print_hex_heim_integer: %s != %s", str, p);
+
+ ret = der_parse_hex_heim_integer(str, &i2);
+ if (ret)
+ errx(1, "der_parse_hex_heim_integer: %d", ret);
+
+ if (der_heim_integer_cmp(i, &i2) != 0)
+ errx(1, "der_heim_integer_cmp: p %s", p);
+
+ der_free_heim_integer(&i2);
+ free(str);
+
+ ret = der_parse_hex_heim_integer(p, &i2);
+ if (ret)
+ errx(1, "der_parse_hex_heim_integer: %d", ret);
+
+ if (der_heim_integer_cmp(i, &i2) != 0)
+ errx(1, "der_heim_integer_cmp: norm");
+
+ der_free_heim_integer(&i2);
+
+ return 0;
+}
+
+static int
+test_heim_int_format(void)
+{
+ heim_integer i = { 1, "\x10", 0 };
+ heim_integer i2 = { 1, "\x10", 1 };
+ heim_integer i3 = { 1, "\01", 0 };
+ char *p =
+ "FFFFFFFF" "FFFFFFFF" "C90FDAA2" "2168C234" "C4C6628B" "80DC1CD1"
+ "29024E08" "8A67CC74" "020BBEA6" "3B139B22" "514A0879" "8E3404DD"
+ "EF9519B3" "CD3A431B" "302B0A6D" "F25F1437" "4FE1356D" "6D51C245"
+ "E485B576" "625E7EC6" "F44C42E9" "A637ED6B" "0BFF5CB6" "F406B7ED"
+ "EE386BFB" "5A899FA5" "AE9F2411" "7C4B1FE6" "49286651" "ECE65381"
+ "FFFFFFFF" "FFFFFFFF";
+ heim_integer bni = {
+ 128,
+ "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xC9\x0F\xDA\xA2"
+ "\x21\x68\xC2\x34\xC4\xC6\x62\x8B\x80\xDC\x1C\xD1"
+ "\x29\x02\x4E\x08\x8A\x67\xCC\x74\x02\x0B\xBE\xA6"
+ "\x3B\x13\x9B\x22\x51\x4A\x08\x79\x8E\x34\x04\xDD"
+ "\xEF\x95\x19\xB3\xCD\x3A\x43\x1B\x30\x2B\x0A\x6D"
+ "\xF2\x5F\x14\x37\x4F\xE1\x35\x6D\x6D\x51\xC2\x45"
+ "\xE4\x85\xB5\x76\x62\x5E\x7E\xC6\xF4\x4C\x42\xE9"
+ "\xA6\x37\xED\x6B\x0B\xFF\x5C\xB6\xF4\x06\xB7\xED"
+ "\xEE\x38\x6B\xFB\x5A\x89\x9F\xA5\xAE\x9F\x24\x11"
+ "\x7C\x4B\x1F\xE6\x49\x28\x66\x51\xEC\xE6\x53\x81"
+ "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF",
+ 0
+ };
+ heim_integer f;
+ int ret = 0;
+
+ ret += check_heim_integer_same(p, p, &bni);
+ ret += check_heim_integer_same("10", "10", &i);
+ ret += check_heim_integer_same("00000010", "10", &i);
+ ret += check_heim_integer_same("-10", "-10", &i2);
+ ret += check_heim_integer_same("-00000010", "-10", &i2);
+ ret += check_heim_integer_same("01", "01", &i3);
+ ret += check_heim_integer_same("1", "01", &i3);
+
+ {
+ int r;
+ r = der_parse_hex_heim_integer("-", &f);
+ if (r == 0) {
+ der_free_heim_integer(&f);
+ ret++;
+ }
+ /* used to cause UMR */
+ r = der_parse_hex_heim_integer("00", &f);
+ if (r == 0)
+ der_free_heim_integer(&f);
+ else
+ ret++;
+ }
+
+ return ret;
+}
+
+static int
+test_heim_oid_format_same(const char *str, const heim_oid *oid)
+{
+ int ret;
+ char *p;
+ heim_oid o2;
+
+ ret = der_print_heim_oid(oid, ' ', &p);
+ if (ret) {
+ printf("fail to print oid: %s\n", str);
+ return 1;
+ }
+
+ if (strcmp(p, str) != 0) {
+ printf("oid %s != formated oid %s\n", str, p);
+ free(p);
+ return 1;
+ }
+
+ ret = der_parse_heim_oid(p, " ", &o2);
+ if (ret) {
+ printf("failed to parse %s\n", p);
+ free(p);
+ return 1;
+ }
+ free(p);
+ ret = der_heim_oid_cmp(&o2, oid);
+ der_free_oid(&o2);
+
+ if (ret != 0)
+ return 1;
+ return 0;
+}
+
+static unsigned sha1_oid_tree[] = { 1, 3, 14, 3, 2, 26 };
+
+static int
+test_heim_oid_format(void)
+{
+ heim_oid sha1 = { 6, sha1_oid_tree };
+ int ret = 0;
+
+ ret += test_heim_oid_format_same("1 3 14 3 2 26", &sha1);
+
+ return ret;
+}
+
+static int
+check_trailing_nul(void)
+{
+ int i, ret;
+ struct {
+ int fail;
+ const unsigned char *p;
+ size_t len;
+ const char *s;
+ size_t size;
+ } foo[] = {
+ { 1, (const unsigned char *)"foo\x00o", 5, NULL, 0 },
+ { 1, (const unsigned char *)"\x00o", 2, NULL, 0 },
+ { 0, (const unsigned char *)"\x00\x00\x00\x00\x00", 5, "", 5 },
+ { 0, (const unsigned char *)"\x00", 1, "", 1 },
+ { 0, (const unsigned char *)"", 0, "", 0 },
+ { 0, (const unsigned char *)"foo\x00\x00", 5, "foo", 5 },
+ { 0, (const unsigned char *)"foo\0", 4, "foo", 4 },
+ { 0, (const unsigned char *)"foo", 3, "foo", 3 }
+ };
+
+ for (i = 0; i < sizeof(foo)/sizeof(foo[0]); i++) {
+ char *s;
+ size_t size;
+ ret = der_get_general_string(foo[i].p, foo[i].len, &s, &size);
+ if (foo[i].fail) {
+ if (ret == 0)
+ errx(1, "check %d NULL didn't fail", i);
+ continue;
+ }
+ if (ret)
+ errx(1, "NULL check %d der_get_general_string failed", i);
+ if (foo[i].size != size)
+ errx(1, "NUL check i = %d size failed", i);
+ if (strcmp(foo[i].s, s) != 0)
+ errx(1, "NUL check i = %d content failed", i);
+ free(s);
+ }
+ return 0;
+}
+
+static int
+test_misc_cmp(void)
+{
+ int ret;
+
+ /* diffrent lengths are diffrent */
+ {
+ const heim_octet_string os1 = { 1, "a" } , os2 = { 0, NULL };
+ ret = der_heim_octet_string_cmp(&os1, &os2);
+ if (ret == 0)
+ return 1;
+ }
+ /* diffrent data are diffrent */
+ {
+ const heim_octet_string os1 = { 1, "a" } , os2 = { 1, "b" };
+ ret = der_heim_octet_string_cmp(&os1, &os2);
+ if (ret == 0)
+ return 1;
+ }
+ /* diffrent lengths are diffrent */
+ {
+ const heim_bit_string bs1 = { 8, "a" } , bs2 = { 7, "a" };
+ ret = der_heim_bit_string_cmp(&bs1, &bs2);
+ if (ret == 0)
+ return 1;
+ }
+ /* diffrent data are diffrent */
+ {
+ const heim_bit_string bs1 = { 7, "\x0f" } , bs2 = { 7, "\x02" };
+ ret = der_heim_bit_string_cmp(&bs1, &bs2);
+ if (ret == 0)
+ return 1;
+ }
+ /* diffrent lengths are diffrent */
+ {
+ uint16_t data = 1;
+ heim_bmp_string bs1 = { 1, NULL } , bs2 = { 0, NULL };
+ bs1.data = &data;
+ ret = der_heim_bmp_string_cmp(&bs1, &bs2);
+ if (ret == 0)
+ return 1;
+ }
+ /* diffrent lengths are diffrent */
+ {
+ uint32_t data;
+ heim_universal_string us1 = { 1, NULL } , us2 = { 0, NULL };
+ us1.data = &data;
+ ret = der_heim_universal_string_cmp(&us1, &us2);
+ if (ret == 0)
+ return 1;
+ }
+ /* same */
+ {
+ uint32_t data = (uint32_t)'a';
+ heim_universal_string us1 = { 1, NULL } , us2 = { 1, NULL };
+ us1.data = &data;
+ us2.data = &data;
+ ret = der_heim_universal_string_cmp(&us1, &us2);
+ if (ret != 0)
+ return 1;
+ }
+
+ return 0;
+}
+
+static int
+corner_generalized_time(void)
+{
+ const char *str = "760520140000Z";
+ size_t size;
+ time_t t;
+ int ret;
+
+ ret = der_get_generalized_time((const unsigned char*)str, strlen(str),
+ &t, &size);
+ if (ret)
+ return 1;
+ return 0;
+}
+
+static int
+corner_tag(void)
+{
+ struct {
+ int ok;
+ const char *ptr;
+ size_t len;
+ } tests[] = {
+ { 1, "\x00", 1 },
+ { 0, "\xff", 1 },
+ { 0, "\xff\xff\xff\xff\xff\xff\xff\xff", 8 }
+ };
+ int i, ret;
+ Der_class cl;
+ Der_type ty;
+ unsigned int tag;
+ size_t size;
+
+ for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
+ ret = der_get_tag((const unsigned char*)tests[i].ptr,
+ tests[i].len, &cl, &ty, &tag, &size);
+ if (ret) {
+ if (tests[i].ok)
+ errx(1, "failed while shouldn't");
+ } else {
+ if (!tests[i].ok)
+ errx(1, "passed while shouldn't");
+ }
+ }
+ return 0;
+}
+
+struct randomcheck {
+ asn1_type_decode decoder;
+ asn1_type_release release;
+ size_t typesize;
+ size_t inputsize;
+} randomcheck[] = {
+#define el(name, type, maxlen) { \
+ (asn1_type_decode)der_get_##name, \
+ (asn1_type_release)der_free_##name, \
+ sizeof(type), \
+ maxlen \
+ }
+ el(integer, int, 6),
+ el(heim_integer, heim_integer, 12),
+ el(integer, int, 6),
+ el(unsigned, unsigned, 6),
+ el(general_string, heim_general_string, 12),
+ el(octet_string, heim_octet_string, 12),
+ { (asn1_type_decode)der_get_octet_string_ber,
+ (asn1_type_release)der_free_octet_string,
+ sizeof(heim_octet_string), 20 },
+ el(generalized_time, time_t, 20),
+ el(utctime, time_t, 20),
+ el(bit_string, heim_bit_string, 10),
+ el(oid, heim_oid, 10),
+ { NULL, NULL, 0, 0 }
+#undef el
+};
+
+static void
+asn1rand(uint8_t *randbytes, size_t len)
+{
+ while (len) {
+ *randbytes++ = rk_random();
+ len--;
+ }
+}
+
+static int
+check_random(void)
+{
+ struct randomcheck *r = randomcheck;
+ uint8_t *input;
+ void *type;
+ size_t size, insize;
+ int ret;
+
+ while (r->decoder) {
+ type = emalloc(r->typesize);
+ memset(type, 0, r->typesize);
+
+ input = emalloc(r->inputsize);
+
+ /* try all zero first */
+ memset(input, 0, r->inputsize);
+
+ ret = r->decoder(input, r->inputsize, type, &size);
+ if (!ret)
+ r->release(type);
+
+ /* try all one first */
+ memset(input, 0xff, r->inputsize);
+ ret = r->decoder(input, r->inputsize, type, &size);
+ if (!ret)
+ r->release(type);
+
+ /* try 0x41 too */
+ memset(input, 0x41, r->inputsize);
+ ret = r->decoder(input, r->inputsize, type, &size);
+ if (!ret)
+ r->release(type);
+
+ /* random */
+ asn1rand(input, r->inputsize);
+ ret = r->decoder(input, r->inputsize, type, &size);
+ if (!ret)
+ r->release(type);
+
+ /* let make buffer smaller */
+ insize = r->inputsize;
+ do {
+ insize--;
+ asn1rand(input, insize);
+
+ ret = r->decoder(input, insize, type, &size);
+ if (!ret)
+ r->release(type);
+ } while(insize > 0);
+
+ free(type);
+
+ r++;
+ }
+ return 0;
+}
+
+
+
+int
+main(int argc, char **argv)
+{
+ int ret = 0;
+
+ ret += test_integer ();
+ ret += test_integer_more();
+ ret += test_unsigned ();
+ ret += test_octet_string ();
+ ret += test_bmp_string ();
+ ret += test_universal_string ();
+ ret += test_general_string ();
+ ret += test_generalized_time ();
+ ret += test_oid ();
+ ret += test_bit_string();
+ ret += test_heim_integer();
+ ret += test_boolean();
+
+ ret += check_fail_unsigned();
+ ret += check_fail_integer();
+ ret += check_fail_length();
+ ret += check_fail_boolean();
+ ret += check_fail_general_string();
+ ret += check_fail_bmp_string();
+ ret += check_fail_universal_string();
+ ret += check_fail_heim_integer();
+ ret += check_fail_generalized_time();
+ ret += check_fail_oid();
+ ret += check_fail_bitstring();
+ ret += test_heim_int_format();
+ ret += test_heim_oid_format();
+ ret += check_trailing_nul();
+ ret += test_misc_cmp();
+ ret += corner_generalized_time();
+ ret += corner_tag();
+ ret += check_random();
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/asn1/check-gen.c b/third_party/heimdal/lib/asn1/check-gen.c
new file mode 100644
index 0000000..6b5c71c
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/check-gen.c
@@ -0,0 +1,2685 @@
+/*
+ * Copyright (c) 1999 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <stdio.h>
+#include <string.h>
+#include <err.h>
+#include <roken.h>
+
+#include <asn1-common.h>
+#include <asn1_err.h>
+#include <der.h>
+#include <krb5_asn1.h>
+#include <heim_asn1.h>
+#include <rfc2459_asn1.h>
+#include <x690sample_asn1.h>
+#include <test_asn1.h>
+#include <cms_asn1.h>
+
+#include "check-common.h"
+
+static int my_copy_vers_called;
+static int my_free_vers_called;
+
+int
+my_copy_vers(const my_vers *from, my_vers *to)
+{
+ my_copy_vers_called++;
+ *to = *from;
+ return 0;
+}
+
+void
+my_free_vers(my_vers *v)
+{
+ my_free_vers_called++;
+ v->v = -1;
+}
+
+static char *lha_principal[] = { "lha" };
+static char *lharoot_princ[] = { "lha", "root" };
+static char *datan_princ[] = { "host", "nutcracker.e.kth.se" };
+static char *nada_tgt_principal[] = { "krbtgt", "NADA.KTH.SE" };
+
+static int
+cmp_principal (void *a, void *b)
+{
+ Principal *pa = a;
+ Principal *pb = b;
+ int i;
+
+ COMPARE_STRING(pa,pb,realm);
+ COMPARE_INTEGER(pa,pb,name.name_type);
+ COMPARE_INTEGER(pa,pb,name.name_string.len);
+
+ for (i = 0; i < pa->name.name_string.len; i++)
+ COMPARE_STRING(pa,pb,name.name_string.val[i]);
+
+ return 0;
+}
+
+static int
+test_principal (void)
+{
+
+ struct test_case tests[] = {
+ { NULL, 29,
+ "\x30\x1b\xa0\x10\x30\x0e\xa0\x03\x02\x01\x01\xa1\x07\x30\x05\x1b"
+ "\x03\x6c\x68\x61\xa1\x07\x1b\x05\x53\x55\x2e\x53\x45",
+ NULL
+ },
+ { NULL, 35,
+ "\x30\x21\xa0\x16\x30\x14\xa0\x03\x02\x01\x01\xa1\x0d\x30\x0b\x1b"
+ "\x03\x6c\x68\x61\x1b\x04\x72\x6f\x6f\x74\xa1\x07\x1b\x05\x53\x55"
+ "\x2e\x53\x45",
+ NULL
+ },
+ { NULL, 54,
+ "\x30\x34\xa0\x26\x30\x24\xa0\x03\x02\x01\x03\xa1\x1d\x30\x1b\x1b"
+ "\x04\x68\x6f\x73\x74\x1b\x13\x6e\x75\x74\x63\x72\x61\x63\x6b\x65"
+ "\x72\x2e\x65\x2e\x6b\x74\x68\x2e\x73\x65\xa1\x0a\x1b\x08\x45\x2e"
+ "\x4b\x54\x48\x2e\x53\x45",
+ NULL
+ }
+ };
+
+
+ Principal values[] = {
+ { { KRB5_NT_PRINCIPAL, { 1, lha_principal } }, "SU.SE", NULL },
+ { { KRB5_NT_PRINCIPAL, { 2, lharoot_princ } }, "SU.SE", NULL },
+ { { KRB5_NT_SRV_HST, { 2, datan_princ } }, "E.KTH.SE", NULL }
+ };
+ int i, ret;
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ for (i = 0; i < ntests; ++i) {
+ tests[i].val = &values[i];
+ if (asprintf (&tests[i].name, "Principal %d", i) < 0)
+ errx(1, "malloc");
+ if (tests[i].name == NULL)
+ errx(1, "malloc");
+ }
+
+ ret = generic_test (tests, ntests, sizeof(Principal),
+ (generic_encode)encode_Principal,
+ (generic_length)length_Principal,
+ (generic_decode)decode_Principal,
+ (generic_free)free_Principal,
+ cmp_principal,
+ NULL);
+ for (i = 0; i < ntests; ++i)
+ free (tests[i].name);
+
+ return ret;
+}
+
+static int
+cmp_authenticator (void *a, void *b)
+{
+ Authenticator *aa = a;
+ Authenticator *ab = b;
+ int i;
+
+ COMPARE_INTEGER(aa,ab,authenticator_vno);
+ COMPARE_STRING(aa,ab,crealm);
+
+ COMPARE_INTEGER(aa,ab,cname.name_type);
+ COMPARE_INTEGER(aa,ab,cname.name_string.len);
+
+ for (i = 0; i < aa->cname.name_string.len; i++)
+ COMPARE_STRING(aa,ab,cname.name_string.val[i]);
+
+ return 0;
+}
+
+static int
+test_authenticator (void)
+{
+ struct test_case tests[] = {
+ { NULL, 63,
+ "\x62\x3d\x30\x3b\xa0\x03\x02\x01\x05\xa1\x0a\x1b\x08"
+ "\x45\x2e\x4b\x54\x48\x2e\x53\x45\xa2\x10\x30\x0e\xa0"
+ "\x03\x02\x01\x01\xa1\x07\x30\x05\x1b\x03\x6c\x68\x61"
+ "\xa4\x03\x02\x01\x0a\xa5\x11\x18\x0f\x31\x39\x37\x30"
+ "\x30\x31\x30\x31\x30\x30\x30\x31\x33\x39\x5a",
+ NULL
+ },
+ { NULL, 67,
+ "\x62\x41\x30\x3f\xa0\x03\x02\x01\x05\xa1\x07\x1b\x05"
+ "\x53\x55\x2e\x53\x45\xa2\x16\x30\x14\xa0\x03\x02\x01"
+ "\x01\xa1\x0d\x30\x0b\x1b\x03\x6c\x68\x61\x1b\x04\x72"
+ "\x6f\x6f\x74\xa4\x04\x02\x02\x01\x24\xa5\x11\x18\x0f"
+ "\x31\x39\x37\x30\x30\x31\x30\x31\x30\x30\x31\x36\x33"
+ "\x39\x5a",
+ NULL
+ }
+ };
+
+ Authenticator values[] = {
+ { 5, "E.KTH.SE", { KRB5_NT_PRINCIPAL, { 1, lha_principal } },
+ NULL, 10, 99, NULL, NULL, NULL },
+ { 5, "SU.SE", { KRB5_NT_PRINCIPAL, { 2, lharoot_princ } },
+ NULL, 292, 999, NULL, NULL, NULL }
+ };
+ int i, ret;
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ for (i = 0; i < ntests; ++i) {
+ tests[i].val = &values[i];
+ if (asprintf (&tests[i].name, "Authenticator %d", i) < 0)
+ errx(1, "malloc");
+ if (tests[i].name == NULL)
+ errx(1, "malloc");
+ }
+
+ ret = generic_test (tests, ntests, sizeof(Authenticator),
+ (generic_encode)encode_Authenticator,
+ (generic_length)length_Authenticator,
+ (generic_decode)decode_Authenticator,
+ (generic_free)free_Authenticator,
+ cmp_authenticator,
+ (generic_copy)copy_Authenticator);
+ for (i = 0; i < ntests; ++i)
+ free(tests[i].name);
+
+ return ret;
+}
+
+static int
+cmp_KRB_ERROR (void *a, void *b)
+{
+ KRB_ERROR *aa = a;
+ KRB_ERROR *ab = b;
+ int i;
+
+ COMPARE_INTEGER(aa,ab,pvno);
+ COMPARE_INTEGER(aa,ab,msg_type);
+
+ IF_OPT_COMPARE(aa,ab,ctime) {
+ COMPARE_INTEGER(aa,ab,ctime);
+ }
+ IF_OPT_COMPARE(aa,ab,cusec) {
+ COMPARE_INTEGER(aa,ab,cusec);
+ }
+ COMPARE_INTEGER(aa,ab,stime);
+ COMPARE_INTEGER(aa,ab,susec);
+ COMPARE_INTEGER(aa,ab,error_code);
+
+ IF_OPT_COMPARE(aa,ab,crealm) {
+ COMPARE_OPT_STRING(aa,ab,crealm);
+ }
+#if 0
+ IF_OPT_COMPARE(aa,ab,cname) {
+ COMPARE_OPT_STRING(aa,ab,cname);
+ }
+#endif
+ COMPARE_STRING(aa,ab,realm);
+
+ COMPARE_INTEGER(aa,ab,sname.name_string.len);
+ for (i = 0; i < aa->sname.name_string.len; i++)
+ COMPARE_STRING(aa,ab,sname.name_string.val[i]);
+
+ IF_OPT_COMPARE(aa,ab,e_text) {
+ COMPARE_OPT_STRING(aa,ab,e_text);
+ }
+ IF_OPT_COMPARE(aa,ab,e_data) {
+ /* COMPARE_OPT_OCTET_STRING(aa,ab,e_data); */
+ }
+
+ return 0;
+}
+
+static int
+test_krb_error (void)
+{
+ struct test_case tests[] = {
+ { NULL, 127,
+ "\x7e\x7d\x30\x7b\xa0\x03\x02\x01\x05\xa1\x03\x02\x01\x1e\xa4\x11"
+ "\x18\x0f\x32\x30\x30\x33\x31\x31\x32\x34\x30\x30\x31\x31\x31\x39"
+ "\x5a\xa5\x05\x02\x03\x04\xed\xa5\xa6\x03\x02\x01\x1f\xa7\x0d\x1b"
+ "\x0b\x4e\x41\x44\x41\x2e\x4b\x54\x48\x2e\x53\x45\xa8\x10\x30\x0e"
+ "\xa0\x03\x02\x01\x01\xa1\x07\x30\x05\x1b\x03\x6c\x68\x61\xa9\x0d"
+ "\x1b\x0b\x4e\x41\x44\x41\x2e\x4b\x54\x48\x2e\x53\x45\xaa\x20\x30"
+ "\x1e\xa0\x03\x02\x01\x01\xa1\x17\x30\x15\x1b\x06\x6b\x72\x62\x74"
+ "\x67\x74\x1b\x0b\x4e\x41\x44\x41\x2e\x4b\x54\x48\x2e\x53\x45",
+ "KRB-ERROR Test 1"
+ }
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+ KRB_ERROR e1;
+ PrincipalName lhaprincipalname = { 1, { 1, lha_principal } };
+ PrincipalName tgtprincipalname = { 1, { 2, nada_tgt_principal } };
+ char *realm = "NADA.KTH.SE";
+
+ e1.pvno = 5;
+ e1.msg_type = 30;
+ e1.ctime = NULL;
+ e1.cusec = NULL;
+ e1.stime = 1069632679;
+ e1.susec = 322981;
+ e1.error_code = 31;
+ e1.crealm = &realm;
+ e1.cname = &lhaprincipalname;
+ e1.realm = "NADA.KTH.SE";
+ e1.sname = tgtprincipalname;
+ e1.e_text = NULL;
+ e1.e_data = NULL;
+
+ tests[0].val = &e1;
+
+ return generic_test (tests, ntests, sizeof(KRB_ERROR),
+ (generic_encode)encode_KRB_ERROR,
+ (generic_length)length_KRB_ERROR,
+ (generic_decode)decode_KRB_ERROR,
+ (generic_free)free_KRB_ERROR,
+ cmp_KRB_ERROR,
+ (generic_copy)copy_KRB_ERROR);
+}
+
+static int
+cmp_Name (void *a, void *b)
+{
+ Name *aa = a;
+ Name *ab = b;
+
+ COMPARE_INTEGER(aa,ab,element);
+
+ return 0;
+}
+
+static int
+test_Name (void)
+{
+ struct test_case tests[] = {
+ { NULL, 35,
+ "\x30\x21\x31\x1f\x30\x0b\x06\x03\x55\x04\x03\x13\x04\x4c\x6f\x76"
+ "\x65\x30\x10\x06\x03\x55\x04\x07\x13\x09\x53\x54\x4f\x43\x4b\x48"
+ "\x4f\x4c\x4d",
+ "Name CN=Love+L=STOCKHOLM"
+ },
+ { NULL, 35,
+ "\x30\x21\x31\x1f\x30\x0b\x06\x03\x55\x04\x03\x13\x04\x4c\x6f\x76"
+ "\x65\x30\x10\x06\x03\x55\x04\x07\x13\x09\x53\x54\x4f\x43\x4b\x48"
+ "\x4f\x4c\x4d",
+ "Name L=STOCKHOLM+CN=Love"
+ }
+ };
+
+ int ntests = sizeof(tests) / sizeof(*tests);
+ Name n1, n2;
+ RelativeDistinguishedName rdn1[1];
+ RelativeDistinguishedName rdn2[1];
+ AttributeTypeAndValue atv1[2];
+ AttributeTypeAndValue atv2[2];
+ unsigned cmp_CN[] = { 2, 5, 4, 3 };
+ unsigned cmp_L[] = { 2, 5, 4, 7 };
+
+ /* n1 */
+ n1.element = choice_Name_rdnSequence;
+ n1.u.rdnSequence.val = rdn1;
+ n1.u.rdnSequence.len = sizeof(rdn1)/sizeof(rdn1[0]);
+ rdn1[0].val = atv1;
+ rdn1[0].len = sizeof(atv1)/sizeof(atv1[0]);
+
+ atv1[0].type.length = sizeof(cmp_CN)/sizeof(cmp_CN[0]);
+ atv1[0].type.components = cmp_CN;
+ atv1[0].value.element = choice_DirectoryString_printableString;
+ atv1[0].value.u.printableString.data = "Love";
+ atv1[0].value.u.printableString.length = 4;
+
+ atv1[1].type.length = sizeof(cmp_L)/sizeof(cmp_L[0]);
+ atv1[1].type.components = cmp_L;
+ atv1[1].value.element = choice_DirectoryString_printableString;
+ atv1[1].value.u.printableString.data = "STOCKHOLM";
+ atv1[1].value.u.printableString.length = 9;
+
+ /* n2 */
+ n2.element = choice_Name_rdnSequence;
+ n2.u.rdnSequence.val = rdn2;
+ n2.u.rdnSequence.len = sizeof(rdn2)/sizeof(rdn2[0]);
+ rdn2[0].val = atv2;
+ rdn2[0].len = sizeof(atv2)/sizeof(atv2[0]);
+
+ atv2[0].type.length = sizeof(cmp_L)/sizeof(cmp_L[0]);
+ atv2[0].type.components = cmp_L;
+ atv2[0].value.element = choice_DirectoryString_printableString;
+ atv2[0].value.u.printableString.data = "STOCKHOLM";
+ atv2[0].value.u.printableString.length = 9;
+
+ atv2[1].type.length = sizeof(cmp_CN)/sizeof(cmp_CN[0]);
+ atv2[1].type.components = cmp_CN;
+ atv2[1].value.element = choice_DirectoryString_printableString;
+ atv2[1].value.u.printableString.data = "Love";
+ atv2[1].value.u.printableString.length = 4;
+
+ /* */
+ tests[0].val = &n1;
+ tests[1].val = &n2;
+
+ return generic_test (tests, ntests, sizeof(Name),
+ (generic_encode)encode_Name,
+ (generic_length)length_Name,
+ (generic_decode)decode_Name,
+ (generic_free)free_Name,
+ cmp_Name,
+ (generic_copy)copy_Name);
+}
+
+static int
+cmp_KeyUsage (void *a, void *b)
+{
+ KeyUsage *aa = a;
+ KeyUsage *ab = b;
+
+ return KeyUsage2int(*aa) != KeyUsage2int(*ab);
+}
+
+static int
+test_bit_string (void)
+{
+ struct test_case tests[] = {
+ { NULL, 4,
+ "\x03\x02\x07\x80",
+ "bitstring 1"
+ },
+ { NULL, 4,
+ "\x03\x02\x05\xa0",
+ "bitstring 2"
+ },
+ { NULL, 5,
+ "\x03\x03\x07\x00\x80",
+ "bitstring 3"
+ },
+ { NULL, 3,
+ "\x03\x01\x00",
+ "bitstring 4"
+ }
+ };
+
+ int ntests = sizeof(tests) / sizeof(*tests);
+ KeyUsage ku1, ku2, ku3, ku4;
+
+ memset(&ku1, 0, sizeof(ku1));
+ ku1.digitalSignature = 1;
+ tests[0].val = &ku1;
+
+ memset(&ku2, 0, sizeof(ku2));
+ ku2.digitalSignature = 1;
+ ku2.keyEncipherment = 1;
+ tests[1].val = &ku2;
+
+ memset(&ku3, 0, sizeof(ku3));
+ ku3.decipherOnly = 1;
+ tests[2].val = &ku3;
+
+ memset(&ku4, 0, sizeof(ku4));
+ tests[3].val = &ku4;
+
+
+ return generic_test (tests, ntests, sizeof(KeyUsage),
+ (generic_encode)encode_KeyUsage,
+ (generic_length)length_KeyUsage,
+ (generic_decode)decode_KeyUsage,
+ (generic_free)free_KeyUsage,
+ cmp_KeyUsage,
+ (generic_copy)copy_KeyUsage);
+}
+
+static int
+cmp_TicketFlags (void *a, void *b)
+{
+ TicketFlags *aa = a;
+ TicketFlags *ab = b;
+
+ return TicketFlags2int(*aa) != TicketFlags2int(*ab);
+}
+
+static int
+test_bit_string_rfc1510 (void)
+{
+ struct test_case tests[] = {
+ { NULL, 7,
+ "\x03\x05\x00\x80\x00\x00\x00",
+ "TF bitstring 1"
+ },
+ { NULL, 7,
+ "\x03\x05\x00\x40\x20\x00\x00",
+ "TF bitstring 2"
+ },
+ { NULL, 7,
+ "\x03\x05\x00\x00\x20\x00\x00",
+ "TF bitstring 3"
+ },
+ { NULL, 7,
+ "\x03\x05\x00\x00\x00\x00\x00",
+ "TF bitstring 4"
+ }
+ };
+
+ int ntests = sizeof(tests) / sizeof(*tests);
+ TicketFlags tf1, tf2, tf3, tf4;
+
+ memset(&tf1, 0, sizeof(tf1));
+ tf1.reserved = 1;
+ tests[0].val = &tf1;
+
+ memset(&tf2, 0, sizeof(tf2));
+ tf2.forwardable = 1;
+ tf2.pre_authent = 1;
+ tests[1].val = &tf2;
+
+ memset(&tf3, 0, sizeof(tf3));
+ tf3.pre_authent = 1;
+ tests[2].val = &tf3;
+
+ memset(&tf4, 0, sizeof(tf4));
+ tests[3].val = &tf4;
+
+
+ return generic_test (tests, ntests, sizeof(TicketFlags),
+ (generic_encode)encode_TicketFlags,
+ (generic_length)length_TicketFlags,
+ (generic_decode)decode_TicketFlags,
+ (generic_free)free_TicketFlags,
+ cmp_TicketFlags,
+ (generic_copy)copy_TicketFlags);
+}
+
+static int
+cmp_KerberosTime (void *a, void *b)
+{
+ KerberosTime *aa = a;
+ KerberosTime *ab = b;
+
+ return *aa != *ab;
+}
+
+static int
+test_time (void)
+{
+ struct test_case tests[] = {
+ { NULL, 17,
+ "\x18\x0f\x31\x39\x37\x30\x30\x31\x30\x31\x30\x31\x31\x38\x33\x31"
+ "\x5a",
+ "time 1" },
+ { NULL, 17,
+ "\x18\x0f\x32\x30\x30\x39\x30\x35\x32\x34\x30\x32\x30\x32\x34\x30"
+ "\x5a",
+ "time 2" }
+ };
+
+ int ntests = sizeof(tests) / sizeof(*tests);
+ KerberosTime times[] = {
+ 4711,
+ 1243130560
+ };
+
+ tests[0].val = &times[0];
+ tests[1].val = &times[1];
+
+ return generic_test (tests, ntests, sizeof(KerberosTime),
+ (generic_encode)encode_KerberosTime,
+ (generic_length)length_KerberosTime,
+ (generic_decode)decode_KerberosTime,
+ (generic_free)free_KerberosTime,
+ cmp_KerberosTime,
+ (generic_copy)copy_KerberosTime);
+}
+
+struct {
+ const char *cert;
+ size_t len;
+} certs[] = {
+ {
+ "\x30\x82\x02\x6c\x30\x82\x01\xd5\xa0\x03\x02\x01\x02\x02\x09\x00"
+ "\x99\x32\xde\x61\x0e\x40\x19\x8a\x30\x0d\x06\x09\x2a\x86\x48\x86"
+ "\xf7\x0d\x01\x01\x05\x05\x00\x30\x2a\x31\x1b\x30\x19\x06\x03\x55"
+ "\x04\x03\x0c\x12\x68\x78\x35\x30\x39\x20\x54\x65\x73\x74\x20\x52"
+ "\x6f\x6f\x74\x20\x43\x41\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13"
+ "\x02\x53\x45\x30\x1e\x17\x0d\x30\x39\x30\x34\x32\x36\x32\x30\x32"
+ "\x39\x34\x30\x5a\x17\x0d\x31\x39\x30\x34\x32\x34\x32\x30\x32\x39"
+ "\x34\x30\x5a\x30\x2a\x31\x1b\x30\x19\x06\x03\x55\x04\x03\x0c\x12"
+ "\x68\x78\x35\x30\x39\x20\x54\x65\x73\x74\x20\x52\x6f\x6f\x74\x20"
+ "\x43\x41\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x53\x45\x30"
+ "\x81\x9f\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05"
+ "\x00\x03\x81\x8d\x00\x30\x81\x89\x02\x81\x81\x00\xb9\xd3\x1b\x67"
+ "\x1c\xf7\x5e\x26\x81\x3b\x82\xff\x03\xa4\x43\xb5\xb2\x63\x0b\x89"
+ "\x58\x43\xfe\x3d\xe0\x38\x7d\x93\x74\xbb\xad\x21\xa4\x29\xd9\x34"
+ "\x79\xf3\x1c\x8c\x5a\xd6\xb0\xd7\x19\xea\xcc\xaf\xe0\xa8\x40\x02"
+ "\x1d\x91\xf1\xac\x36\xb0\xfb\x08\xbd\xcc\x9a\xe1\xb7\x6e\xee\x0a"
+ "\x69\xbf\x6d\x2b\xee\x20\x82\x61\x06\xf2\x18\xcc\x89\x11\x64\x7e"
+ "\xb2\xff\x47\xd1\x3b\x52\x73\xeb\x5a\xc0\x03\xa6\x4b\xc7\x40\x7e"
+ "\xbc\xe1\x0e\x65\x44\x3f\x40\x8b\x02\x82\x54\x04\xd9\xcc\x2c\x67"
+ "\x01\xb6\x16\x82\xd8\x33\x53\x17\xd7\xde\x8d\x5d\x02\x03\x01\x00"
+ "\x01\xa3\x81\x99\x30\x81\x96\x30\x1d\x06\x03\x55\x1d\x0e\x04\x16"
+ "\x04\x14\x6e\x48\x13\xdc\xbf\x8b\x95\x4c\x13\xf3\x1f\x97\x30\xdd"
+ "\x27\x96\x59\x9b\x0e\x68\x30\x5a\x06\x03\x55\x1d\x23\x04\x53\x30"
+ "\x51\x80\x14\x6e\x48\x13\xdc\xbf\x8b\x95\x4c\x13\xf3\x1f\x97\x30"
+ "\xdd\x27\x96\x59\x9b\x0e\x68\xa1\x2e\xa4\x2c\x30\x2a\x31\x1b\x30"
+ "\x19\x06\x03\x55\x04\x03\x0c\x12\x68\x78\x35\x30\x39\x20\x54\x65"
+ "\x73\x74\x20\x52\x6f\x6f\x74\x20\x43\x41\x31\x0b\x30\x09\x06\x03"
+ "\x55\x04\x06\x13\x02\x53\x45\x82\x09\x00\x99\x32\xde\x61\x0e\x40"
+ "\x19\x8a\x30\x0c\x06\x03\x55\x1d\x13\x04\x05\x30\x03\x01\x01\xff"
+ "\x30\x0b\x06\x03\x55\x1d\x0f\x04\x04\x03\x02\x01\xe6\x30\x0d\x06"
+ "\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x03\x81\x81\x00"
+ "\x52\x9b\xe4\x0e\xee\xc2\x5d\xb7\xf1\xba\x47\xe3\xfe\xaf\x3d\x51"
+ "\x10\xfd\xe8\x0d\x14\x58\x05\x36\xa7\xeb\xd8\x05\xe5\x27\x6f\x51"
+ "\xb8\xec\x90\xd9\x03\xe1\xbc\x9c\x93\x38\x21\x5c\xaf\x4e\x6c\x7b"
+ "\x6c\x65\xa9\x92\xcd\x94\xef\xa8\xae\x90\x12\x14\x78\x2d\xa3\x15"
+ "\xaa\x42\xf1\xd9\x44\x64\x2c\x3c\xc0\xbd\x3a\x48\xd8\x80\x45\x8b"
+ "\xd1\x79\x82\xe0\x0f\xdf\x08\x3c\x60\x21\x6f\x31\x47\x98\xae\x2f"
+ "\xcb\xb1\xa1\xb9\xc1\xa3\x71\x5e\x4a\xc2\x67\xdf\x66\x0a\x51\xb5"
+ "\xad\x60\x05\xdb\x02\xd4\x1a\xd2\xb9\x4e\x01\x08\x2b\xc3\x57\xaf",
+ 624 },
+ {
+ "\x30\x82\x02\x54\x30\x82\x01\xbd\xa0\x03\x02\x01\x02\x02\x01\x08"
+ "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x30"
+ "\x2a\x31\x1b\x30\x19\x06\x03\x55\x04\x03\x0c\x12\x68\x78\x35\x30"
+ "\x39\x20\x54\x65\x73\x74\x20\x52\x6f\x6f\x74\x20\x43\x41\x31\x0b"
+ "\x30\x09\x06\x03\x55\x04\x06\x13\x02\x53\x45\x30\x1e\x17\x0d\x30"
+ "\x39\x30\x34\x32\x36\x32\x30\x32\x39\x34\x30\x5a\x17\x0d\x31\x39"
+ "\x30\x34\x32\x34\x32\x30\x32\x39\x34\x30\x5a\x30\x1b\x31\x0b\x30"
+ "\x09\x06\x03\x55\x04\x06\x13\x02\x53\x45\x31\x0c\x30\x0a\x06\x03"
+ "\x55\x04\x03\x0c\x03\x6b\x64\x63\x30\x81\x9f\x30\x0d\x06\x09\x2a"
+ "\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00\x03\x81\x8d\x00\x30\x81"
+ "\x89\x02\x81\x81\x00\xd2\x41\x7a\xf8\x4b\x55\xb2\xaf\x11\xf9\x43"
+ "\x9b\x43\x81\x09\x3b\x9a\x94\xcf\x00\xf4\x85\x75\x92\xd7\x2a\xa5"
+ "\x11\xf1\xa8\x50\x6e\xc6\x84\x74\x24\x17\xda\x84\xc8\x03\x37\xb2"
+ "\x20\xf3\xba\xb5\x59\x36\x21\x4d\xab\x70\xe2\xc3\x09\x93\x68\x14"
+ "\x12\x79\xc5\xbb\x9e\x1b\x4a\xf0\xc6\x24\x59\x25\xc3\x1c\xa8\x70"
+ "\x66\x5b\x3e\x41\x8e\xe3\x25\x71\x9a\x94\xa0\x5b\x46\x91\x6f\xdd"
+ "\x58\x14\xec\x89\xe5\x8c\x96\xc5\x38\x60\xe4\xab\xf2\x75\xee\x6e"
+ "\x62\xfc\xe1\xbd\x03\x47\xff\xc4\xbe\x0f\xca\x70\x73\xe3\x74\x58"
+ "\x3a\x2f\x04\x2d\x39\x02\x03\x01\x00\x01\xa3\x81\x98\x30\x81\x95"
+ "\x30\x09\x06\x03\x55\x1d\x13\x04\x02\x30\x00\x30\x0b\x06\x03\x55"
+ "\x1d\x0f\x04\x04\x03\x02\x05\xe0\x30\x12\x06\x03\x55\x1d\x25\x04"
+ "\x0b\x30\x09\x06\x07\x2b\x06\x01\x05\x02\x03\x05\x30\x1d\x06\x03"
+ "\x55\x1d\x0e\x04\x16\x04\x14\x3a\xd3\x73\xff\xab\xdb\x7d\x8d\xc6"
+ "\x3a\xa2\x26\x3e\xae\x78\x95\x80\xc9\xe6\x31\x30\x48\x06\x03\x55"
+ "\x1d\x11\x04\x41\x30\x3f\xa0\x3d\x06\x06\x2b\x06\x01\x05\x02\x02"
+ "\xa0\x33\x30\x31\xa0\x0d\x1b\x0b\x54\x45\x53\x54\x2e\x48\x35\x4c"
+ "\x2e\x53\x45\xa1\x20\x30\x1e\xa0\x03\x02\x01\x01\xa1\x17\x30\x15"
+ "\x1b\x06\x6b\x72\x62\x74\x67\x74\x1b\x0b\x54\x45\x53\x54\x2e\x48"
+ "\x35\x4c\x2e\x53\x45\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01"
+ "\x01\x05\x05\x00\x03\x81\x81\x00\x83\xf4\x14\xa7\x6e\x59\xff\x80"
+ "\x64\xe7\xfa\xcf\x13\x80\x86\xe1\xed\x02\x38\xad\x96\x72\x25\xe5"
+ "\x06\x7a\x9a\xbc\x24\x74\xa9\x75\x55\xb2\x49\x80\x69\x45\x95\x4a"
+ "\x4c\x76\xa9\xe3\x4e\x49\xd3\xc2\x69\x5a\x95\x03\xeb\xba\x72\x23"
+ "\x9c\xfd\x3d\x8b\xc6\x07\x82\x3b\xf4\xf3\xef\x6c\x2e\x9e\x0b\xac"
+ "\x9e\x6c\xbb\x37\x4a\xa1\x9e\x73\xd1\xdc\x97\x61\xba\xfc\xd3\x49"
+ "\xa6\xc2\x4c\x55\x2e\x06\x37\x76\xb5\xef\x57\xe7\x57\x58\x8a\x71"
+ "\x63\xf3\xeb\xe7\x55\x68\x0d\xf6\x46\x4c\xfb\xf9\x43\xbb\x0c\x92"
+ "\x4f\x4e\x22\x7b\x63\xe8\x4f\x9c",
+ 600
+ }
+};
+
+static int
+test_cert(void)
+{
+ Certificate c, c2;
+ size_t size;
+ size_t i;
+ int ret;
+
+ for (i = 0; i < sizeof(certs)/sizeof(certs[0]); i++) {
+
+ ret = decode_Certificate((unsigned char *)certs[i].cert,
+ certs[i].len, &c, &size);
+ if (ret)
+ return ret;
+
+ ret = copy_Certificate(&c, &c2);
+ free_Certificate(&c);
+ if (ret)
+ return ret;
+
+ free_Certificate(&c2);
+ }
+
+ return 0;
+}
+
+struct {
+ const char *sd;
+ size_t len;
+} signeddata[] = {
+ {
+ "\x30\x80\x02\x01\x03\x31\x0b\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a"
+ "\x05\x00\x30\x80\x06\x07\x2b\x06\x01\x05\x02\x03\x03\xa0\x80\x24"
+ "\x80\x04\x50\x30\x4e\xa0\x2b\x30\x29\xa0\x03\x02\x01\x12\xa1\x22"
+ "\x04\x20\x78\xf4\x86\x31\xc6\xc2\xc9\xcb\xef\x0c\xd7\x3a\x2a\xcd"
+ "\x8c\x13\x34\x83\xb1\x5c\xa8\xbe\xbf\x2f\xea\xd2\xbb\xd8\x8c\x18"
+ "\x47\x01\xa1\x1f\x30\x1d\xa0\x03\x02\x01\x0c\xa1\x16\x04\x14\xa6"
+ "\x2c\x52\xb2\x80\x98\x30\x40\xbc\x5f\xb0\x77\x2d\x8a\xd7\xa1\xda"
+ "\x3c\xc5\x62\x00\x00\x00\x00\x00\x00\xa0\x82\x02\x09\x30\x82\x02"
+ "\x05\x30\x82\x01\x6e\xa0\x03\x02\x01\x02\x02\x04\x49\x75\x57\xbf"
+ "\x30\x0b\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x30\x3b\x31"
+ "\x1f\x30\x1d\x06\x03\x55\x04\x03\x0c\x16\x63\x6f\x6d\x2e\x61\x70"
+ "\x70\x6c\x65\x2e\x6b\x65\x72\x62\x65\x72\x6f\x73\x2e\x6b\x64\x63"
+ "\x31\x18\x30\x16\x06\x03\x55\x04\x0a\x0c\x0f\x53\x79\x73\x74\x65"
+ "\x6d\x20\x49\x64\x65\x6e\x74\x69\x74\x79\x30\x1e\x17\x0d\x30\x39"
+ "\x31\x32\x30\x34\x30\x30\x32\x30\x32\x34\x5a\x17\x0d\x32\x39\x31"
+ "\x31\x32\x39\x30\x30\x32\x30\x32\x34\x5a\x30\x3b\x31\x1f\x30\x1d"
+ "\x06\x03\x55\x04\x03\x0c\x16\x63\x6f\x6d\x2e\x61\x70\x70\x6c\x65"
+ "\x2e\x6b\x65\x72\x62\x65\x72\x6f\x73\x2e\x6b\x64\x63\x31\x18\x30"
+ "\x16\x06\x03\x55\x04\x0a\x0c\x0f\x53\x79\x73\x74\x65\x6d\x20\x49"
+ "\x64\x65\x6e\x74\x69\x74\x79\x30\x81\x9f\x30\x0d\x06\x09\x2a\x86"
+ "\x48\x86\xf7\x0d\x01\x01\x01\x05\x00\x03\x81\x8d\x00\x30\x81\x89"
+ "\x02\x81\x81\x00\xb2\xc5\x4b\x34\xe3\x93\x99\xbb\xaa\xd1\x70\x62"
+ "\x6c\x9c\xcc\xa6\xbc\x47\xc3\x23\xff\x15\xb9\x11\x27\x0a\xf8\x55"
+ "\x4c\xb2\x43\x34\x75\xad\x55\xbb\xb9\x8a\xd0\x25\x64\xa4\x8c\x82"
+ "\x74\x5d\x89\x52\xe2\x76\x75\x08\x67\xb5\x9c\x9c\x69\x86\x0c\x6d"
+ "\x79\xf7\xa0\xbe\x42\x8f\x90\x46\x0c\x18\xf4\x7a\x56\x17\xa4\x65"
+ "\x00\x3a\x5e\x3e\xbf\xbc\xf5\xe2\x2c\x26\x03\x52\xdd\xd4\x85\x3f"
+ "\x03\xd7\x0c\x45\x7f\xff\xdd\x1e\x70\x6c\x9f\xb0\x8c\xd0\x33\xad"
+ "\x92\x54\x17\x9d\x88\x89\x1a\xee\xef\xf7\x96\x3e\x68\xc3\xd1\x60"
+ "\x47\x86\x80\x5d\x02\x03\x01\x00\x01\xa3\x18\x30\x16\x30\x14\x06"
+ "\x03\x55\x1d\x25\x04\x0d\x30\x0b\x06\x09\x2a\x86\x48\x86\xf7\x63"
+ "\x64\x04\x04\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05"
+ "\x05\x00\x03\x81\x81\x00\x9b\xbb\xaa\x63\x66\xd8\x70\x84\x3e\xf6"
+ "\xa1\x3b\xf3\xe6\xd7\x3d\xfc\x4f\xc9\x45\xaa\x31\x43\x8d\xb5\x72"
+ "\xe4\x34\x95\x7b\x6e\x5f\xe5\xc8\x5e\xaf\x12\x08\x6d\xd7\x25\x76"
+ "\x40\xd5\xdc\x83\x7f\x2f\x74\xd1\x63\xc0\x7c\x26\x4d\x53\x10\xe7"
+ "\xfa\xcc\xf2\x60\x41\x63\xdf\x56\xd6\xd9\xc0\xb4\xd0\x73\x99\x54"
+ "\x40\xad\x90\x79\x2d\xd2\x5e\xcb\x13\x22\x2b\xd0\x76\xef\x8a\x48"
+ "\xfd\xb2\x6e\xca\x04\x4e\x91\x3f\xb4\x63\xad\x22\x3a\xf7\x20\x9c"
+ "\x4c\x0e\x47\x78\xe5\x2a\x85\x0e\x90\x7a\xce\x46\xe6\x15\x02\xb0"
+ "\x83\xe7\xac\xfa\x92\xf8\x31\x81\xe8\x30\x81\xe5\x02\x01\x01\x30"
+ "\x43\x30\x3b\x31\x1f\x30\x1d\x06\x03\x55\x04\x03\x0c\x16\x63\x6f"
+ "\x6d\x2e\x61\x70\x70\x6c\x65\x2e\x6b\x65\x72\x62\x65\x72\x6f\x73"
+ "\x2e\x6b\x64\x63\x31\x18\x30\x16\x06\x03\x55\x04\x0a\x0c\x0f\x53"
+ "\x79\x73\x74\x65\x6d\x20\x49\x64\x65\x6e\x74\x69\x74\x79\x02\x04"
+ "\x49\x75\x57\xbf\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x30"
+ "\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00\x04\x81"
+ "\x80\x50\x2c\x69\xe1\xd2\xc4\xd1\xcc\xdc\xe0\xe9\x8a\x6b\x6a\x97"
+ "\x1b\xb4\xe0\xa8\x20\xbe\x09\x6d\xe1\x55\x5f\x07\x70\x94\x2e\x14"
+ "\xed\x4e\xb1\x69\x75\x40\xbb\x99\x87\xed\x23\x50\x27\x5f\xaa\xc4"
+ "\x84\x60\x06\xfe\x45\xfd\x7e\x1b\x18\xe0\x0b\x77\x35\x2a\xb2\xf2"
+ "\xe0\x88\x31\xad\x82\x31\x4a\xbc\x6d\x71\x62\xe6\x4d\x33\xb4\x09"
+ "\x6e\x3f\x14\x12\xf2\x89\x29\x31\x84\x60\x2b\xa8\x2d\xe6\xca\x2f"
+ "\x03\x3d\xd4\x69\x89\xb3\x98\xfd\xac\x63\x14\xaf\x6a\x52\x2a\xac"
+ "\xe3\x8e\xfa\x21\x41\x8f\xcc\x04\x2d\x52\xee\x49\x54\x0d\x58\x51"
+ "\x77\x00\x00",
+ 883
+ }
+};
+
+static int
+test_SignedData(void)
+{
+ SignedData sd;
+ size_t size, i;
+ int ret;
+
+ for (i = 0; i < sizeof(signeddata) / sizeof(signeddata[0]); i++) {
+
+ ret = decode_SignedData((unsigned char *)signeddata[i].sd,
+ signeddata[i].len, &sd, &size);
+ if (ret)
+ return ret;
+
+ free_SignedData(&sd);
+ }
+
+ return 0;
+}
+
+
+static int
+cmp_TESTLargeTag (void *a, void *b)
+{
+ TESTLargeTag *aa = a;
+ TESTLargeTag *ab = b;
+
+ COMPARE_INTEGER(aa,ab,foo);
+ COMPARE_INTEGER(aa,ab,bar);
+ return 0;
+}
+
+static int
+test_large_tag (void)
+{
+ struct test_case tests[] = {
+ { NULL, 15, "\x30\x0d\xbf\x7f\x03\x02\x01\x01\xbf\x81\x00\x03\x02\x01\x02", "large tag 1" }
+ };
+
+ int ntests = sizeof(tests) / sizeof(*tests);
+ TESTLargeTag lt1;
+
+ memset(&lt1, 0, sizeof(lt1));
+ lt1.foo = 1;
+ lt1.bar = 2;
+
+ tests[0].val = &lt1;
+
+ return generic_test (tests, ntests, sizeof(TESTLargeTag),
+ (generic_encode)encode_TESTLargeTag,
+ (generic_length)length_TESTLargeTag,
+ (generic_decode)decode_TESTLargeTag,
+ (generic_free)free_TESTLargeTag,
+ cmp_TESTLargeTag,
+ (generic_copy)copy_TESTLargeTag);
+}
+
+struct test_data {
+ int ok;
+ size_t len;
+ size_t expected_len;
+ void *data;
+};
+
+static int
+check_tag_length(void)
+{
+ struct test_data td[] = {
+ { 1, 3, 3, "\x02\x01\x00"},
+ { 1, 3, 3, "\x02\x01\x7f"},
+ { 1, 4, 4, "\x02\x02\x00\x80"},
+ { 1, 4, 4, "\x02\x02\x01\x00"},
+ { 1, 4, 4, "\x02\x02\x02\x00"},
+ { 0, 3, 0, "\x02\x02\x00"},
+ { 0, 3, 0, "\x02\x7f\x7f"},
+ { 0, 4, 0, "\x02\x03\x00\x80"},
+ { 0, 4, 0, "\x02\x7f\x01\x00"},
+ { 0, 5, 0, "\x02\xff\x7f\x02\x00"}
+ };
+ size_t sz;
+ TESTuint32 values[] = {0, 127, 128, 256, 512,
+ 0, 127, 128, 256, 512 };
+ TESTuint32 u;
+ int i, ret, failed = 0;
+ void *buf;
+
+ for (i = 0; i < sizeof(td)/sizeof(td[0]); i++) {
+ struct map_page *page;
+
+ buf = map_alloc(OVERRUN, td[i].data, td[i].len, &page);
+
+ ret = decode_TESTuint32(buf, td[i].len, &u, &sz);
+ if (ret) {
+ if (td[i].ok) {
+ printf("failed with tag len test %d\n", i);
+ failed = 1;
+ }
+ } else {
+ if (td[i].ok == 0) {
+ printf("failed with success for tag len test %d\n", i);
+ failed = 1;
+ }
+ if (td[i].expected_len != sz) {
+ printf("wrong expected size for tag test %d\n", i);
+ failed = 1;
+ }
+ if (values[i] != u) {
+ printf("wrong value for tag test %d\n", i);
+ failed = 1;
+ }
+ }
+ map_free(page, "test", "decode");
+ }
+ return failed;
+}
+
+static int
+check_tag_length64(void)
+{
+ struct test_data td[] = {
+ { 1, 3, 3, "\x02\x01\x00"},
+ { 1, 7, 7, "\x02\x05\x01\xff\xff\xff\xff"},
+ { 1, 7, 7, "\x02\x05\x02\x00\x00\x00\x00"},
+ { 1, 9, 9, "\x02\x07\x7f\xff\xff\xff\xff\xff\xff"},
+ { 1, 10, 10, "\x02\x08\x00\x80\x00\x00\x00\x00\x00\x00"},
+ { 1, 10, 10, "\x02\x08\x7f\xff\xff\xff\xff\xff\xff\xff"},
+ { 1, 11, 11, "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xff"},
+ { 0, 3, 0, "\x02\x02\x00"},
+ { 0, 3, 0, "\x02\x7f\x7f"},
+ { 0, 4, 0, "\x02\x03\x00\x80"},
+ { 0, 4, 0, "\x02\x7f\x01\x00"},
+ { 0, 5, 0, "\x02\xff\x7f\x02\x00"}
+ };
+ size_t sz;
+ TESTuint64 values[] = {0, 8589934591LL, 8589934592LL,
+ 36028797018963967LL, 36028797018963968LL,
+ 9223372036854775807LL, 18446744073709551615ULL,
+ 0, 127, 128, 256, 512 };
+ TESTuint64 u;
+ int i, ret, failed = 0;
+ void *buf;
+
+ if (sizeof(TESTuint64) != sizeof(uint64_t)) {
+ ret += 1;
+ printf("sizeof(TESTuint64) %d != sizeof(uint64_t) %d\n",
+ (int)sizeof(TESTuint64), (int)sizeof(uint64_t));
+ }
+
+ for (i = 0; i < sizeof(td)/sizeof(td[0]); i++) {
+ struct map_page *page;
+
+ buf = map_alloc(OVERRUN, td[i].data, td[i].len, &page);
+
+ ret = decode_TESTuint64(buf, td[i].len, &u, &sz);
+ if (ret) {
+ if (td[i].ok) {
+ printf("failed with tag len test %d\n", i);
+ printf("ret = %d\n", ret);
+ failed = 1;
+ }
+ } else {
+ if (td[i].ok == 0) {
+ printf("failed with success for tag len test %d\n", i);
+ failed = 1;
+ }
+ if (td[i].expected_len != sz) {
+ printf("wrong expected size for tag test %d\n", i);
+ printf("sz = %lu\n", (unsigned long)sz);
+ failed = 1;
+ }
+ if (values[i] != u) {
+ printf("wrong value for tag test %d\n", i);
+ printf("Expected value: %llu\nActual value: %llu\n",
+ (unsigned long long)values[i], (unsigned long long)u);
+ failed = 1;
+ }
+ }
+ map_free(page, "test", "decode");
+ }
+ return failed;
+}
+
+static int
+check_tag_length64s(void)
+{
+ struct test_data td[] = {
+ { 1, 3, 3, "\x02\x01\x00"},
+ { 1, 7, 7, "\x02\x05\xfe\x00\x00\x00\x01"},
+ { 1, 7, 7, "\x02\x05\xfe\x00\x00\x00\x00"},
+ { 1, 9, 9, "\x02\x07\x80\x00\x00\x00\x00\x00\x01"},
+ { 1, 9, 9, "\x02\x07\x80\x00\x00\x00\x00\x00\x00"},
+ { 1, 10, 10, "\x02\x08\x80\x00\x00\x00\x00\x00\x00\x01"},
+ { 1, 9, 9, "\x02\x07\x80\x00\x00\x00\x00\x00\x01"},
+ { 0, 3, 0, "\x02\x02\x00"},
+ { 0, 3, 0, "\x02\x7f\x7f"},
+ { 0, 4, 0, "\x02\x03\x00\x80"},
+ { 0, 4, 0, "\x02\x7f\x01\x00"},
+ { 0, 5, 0, "\x02\xff\x7f\x02\x00"}
+ };
+ size_t sz;
+ TESTint64 values[] = {0, -8589934591LL, -8589934592LL,
+ -36028797018963967LL, -36028797018963968LL,
+ -9223372036854775807LL, -36028797018963967LL,
+ 0, 127, 128, 256, 512 };
+ TESTint64 u;
+ int i, ret, failed = 0;
+ void *buf;
+
+ for (i = 0; i < sizeof(td)/sizeof(td[0]); i++) {
+ struct map_page *page;
+
+ buf = map_alloc(OVERRUN, td[i].data, td[i].len, &page);
+
+ ret = decode_TESTint64(buf, td[i].len, &u, &sz);
+ if (ret) {
+ if (td[i].ok) {
+ printf("failed with tag len test %d\n", i);
+ printf("ret = %d\n", ret);
+ failed = 1;
+ }
+ } else {
+ if (td[i].ok == 0) {
+ printf("failed with success for tag len test %d\n", i);
+ failed = 1;
+ }
+ if (td[i].expected_len != sz) {
+ printf("wrong expected size for tag test %d\n", i);
+ printf("sz = %lu\n", (unsigned long)sz);
+ failed = 1;
+ }
+ if (values[i] != u) {
+ printf("wrong value for tag test %d\n", i);
+ printf("Expected value: %lld\nActual value: %lld\n",
+ (long long)values[i], (long long)u);
+ failed = 1;
+ }
+ }
+ map_free(page, "test", "decode");
+ }
+ return failed;
+}
+
+static int
+cmp_TESTChoice (void *a, void *b)
+{
+ return 0;
+}
+
+static int
+test_choice (void)
+{
+ struct test_case tests[] = {
+ { NULL, 5, "\xa1\x03\x02\x01\x01", "large choice 1" },
+ { NULL, 5, "\xa2\x03\x02\x01\x02", "large choice 2" }
+ };
+
+ int ret = 0, ntests = sizeof(tests) / sizeof(*tests);
+ TESTChoice1 c1;
+ TESTChoice1 c2_1;
+ TESTChoice2 c2_2;
+
+ memset(&c1, 0, sizeof(c1));
+ c1.element = choice_TESTChoice1_i1;
+ c1.u.i1 = 1;
+ tests[0].val = &c1;
+
+ memset(&c2_1, 0, sizeof(c2_1));
+ c2_1.element = choice_TESTChoice1_i2;
+ c2_1.u.i2 = 2;
+ tests[1].val = &c2_1;
+
+ ret += generic_test (tests, ntests, sizeof(TESTChoice1),
+ (generic_encode)encode_TESTChoice1,
+ (generic_length)length_TESTChoice1,
+ (generic_decode)decode_TESTChoice1,
+ (generic_free)free_TESTChoice1,
+ cmp_TESTChoice,
+ (generic_copy)copy_TESTChoice1);
+
+ memset(&c2_2, 0, sizeof(c2_2));
+ c2_2.element = choice_TESTChoice2_asn1_ellipsis;
+ c2_2.u.asn1_ellipsis.data = "\xa2\x03\x02\x01\x02";
+ c2_2.u.asn1_ellipsis.length = 5;
+ tests[1].val = &c2_2;
+
+ ret += generic_test (tests, ntests, sizeof(TESTChoice2),
+ (generic_encode)encode_TESTChoice2,
+ (generic_length)length_TESTChoice2,
+ (generic_decode)decode_TESTChoice2,
+ (generic_free)free_TESTChoice2,
+ cmp_TESTChoice,
+ (generic_copy)copy_TESTChoice2);
+
+ return ret;
+}
+
+/* Test --decorate=TYPE:FIELD-TYPE:field-name[?] */
+static int
+test_decorated(void)
+{
+ TESTNotDecorated tnd;
+ TESTDecorated td, td_copy;
+ size_t len, size;
+ void *ptr;
+ int ret;
+
+ memset(&td, 0, sizeof(td));
+ memset(&tnd, 0, sizeof(tnd));
+
+ my_copy_vers_called = 0;
+ my_free_vers_called = 0;
+
+ td.version = 3;
+ td.version3.v = 5;
+ td.privthing = &td;
+ if ((td.version2 = malloc(sizeof(*td.version2))) == NULL)
+ errx(1, "out of memory");
+ *td.version2 = 5;
+ ASN1_MALLOC_ENCODE(TESTDecorated, ptr, len, &td, &size, ret);
+ if (ret) {
+ warnx("could not encode a TESTDecorated struct");
+ return 1;
+ }
+ ret = decode_TESTNotDecorated(ptr, len, &tnd, &size);
+ if (ret) {
+ warnx("could not decode a TESTDecorated struct as TESTNotDecorated");
+ return 1;
+ }
+ free(ptr);
+ if (size != len) {
+ warnx("TESTDecorated encoded size mismatch");
+ return 1;
+ }
+ if (td.version != tnd.version) {
+ warnx("TESTDecorated did not decode as a TESTNotDecorated correctly");
+ return 1;
+ }
+ if (copy_TESTDecorated(&td, &td_copy)) {
+ warnx("copy_TESTDecorated() failed");
+ return 1;
+ }
+ if (td.version != td_copy.version) {
+ warnx("copy_TESTDecorated() did not work correctly (1)");
+ return 1;
+ }
+ if (td_copy.version2 == NULL || *td.version2 != *td_copy.version2) {
+ warnx("copy_TESTDecorated() did not work correctly (2)");
+ return 1;
+ }
+ if (td.version3.v != td_copy.version3.v ||
+ my_copy_vers_called != 1) {
+ warnx("copy_TESTDecorated() did not work correctly (3)");
+ return 1;
+ }
+ if (td_copy.privthing != 0) {
+ warnx("copy_TESTDecorated() did not work correctly (4)");
+ return 1;
+ }
+
+ free_TESTDecorated(&td_copy);
+ free_TESTDecorated(&td);
+ if (td.version2) {
+ warnx("free_TESTDecorated() did not work correctly (1)");
+ return 1;
+ }
+ if (td.version3.v != 0 || my_free_vers_called != 2) {
+ warnx("free_TESTDecorated() did not work correctly (2)");
+ return 1;
+ }
+ if (td.privthing != 0) {
+ warnx("free_TESTDecorated() did not work correctly (3)");
+ return 1;
+ }
+ return 0;
+}
+
+static int
+test_decorated_choice(void)
+{
+ TESTNotDecoratedChoice tndc;
+ TESTDecoratedChoice tdc, tdc_copy;
+ size_t len, size;
+ void *ptr;
+ int ret;
+
+ memset(&tdc, 0, sizeof(tdc));
+ memset(&tndc, 0, sizeof(tndc));
+
+ my_copy_vers_called = 0;
+ my_free_vers_called = 0;
+
+ tdc.element = choice_TESTDecoratedChoice_version;
+ tdc.u.version = 3;
+ tdc.version3.v = 5;
+ tdc.privthing = &tdc;
+ if ((tdc.version2 = malloc(sizeof(*tdc.version2))) == NULL)
+ errx(1, "out of memory");
+ *tdc.version2 = 5;
+ ASN1_MALLOC_ENCODE(TESTDecoratedChoice, ptr, len, &tdc, &size, ret);
+ if (ret) {
+ warnx("could not encode a TESTDecoratedChoice struct");
+ return 1;
+ }
+ ret = decode_TESTNotDecoratedChoice(ptr, len, &tndc, &size);
+ if (ret) {
+ warnx("could not decode a TESTDecoratedChoice struct as TESTNotDecoratedChoice");
+ return 1;
+ }
+ free(ptr);
+ if (size != len) {
+ warnx("TESTDecoratedChoice encoded size mismatch");
+ return 1;
+ }
+ if ((int)tdc.element != (int)tndc.element ||
+ tdc.u.version != tndc.u.version) {
+ warnx("TESTDecoratedChoice did not decode as a TESTNotDecoratedChoice correctly");
+ return 1;
+ }
+ if (copy_TESTDecoratedChoice(&tdc, &tdc_copy)) {
+ warnx("copy_TESTDecoratedChoice() failed");
+ return 1;
+ }
+ if ((int)tdc.element != (int)tdc_copy.element ||
+ tdc.u.version != tdc_copy.u.version) {
+ warnx("copy_TESTDecoratedChoice() did not work correctly (1)");
+ return 1;
+ }
+ if (tdc_copy.version2 == NULL || *tdc.version2 != *tdc_copy.version2) {
+ warnx("copy_TESTDecoratedChoice() did not work correctly (2)");
+ return 1;
+ }
+ if (tdc.version3.v != tdc_copy.version3.v ||
+ my_copy_vers_called != 1) {
+ warnx("copy_TESTDecoratedChoice() did not work correctly (3)");
+ return 1;
+ }
+ if (tdc_copy.privthing != 0) {
+ warnx("copy_TESTDecoratedChoice() did not work correctly (4)");
+ return 1;
+ }
+
+ free_TESTDecoratedChoice(&tdc_copy);
+ free_TESTDecoratedChoice(&tdc);
+ if (tdc.version2) {
+ warnx("free_TESTDecoratedChoice() did not work correctly (1)");
+ return 1;
+ }
+ if (tdc.version3.v != 0 || my_free_vers_called != 2) {
+ warnx("free_TESTDecoratedChoice() did not work correctly (2)");
+ return 1;
+ }
+ if (tdc.privthing != 0) {
+ warnx("free_TESTDecoratedChoice() did not work correctly (3)");
+ return 1;
+ }
+ return 0;
+}
+
+
+static int
+cmp_TESTImplicit (void *a, void *b)
+{
+ TESTImplicit *aa = a;
+ TESTImplicit *ab = b;
+
+ COMPARE_INTEGER(aa,ab,ti1);
+ COMPARE_INTEGER(aa,ab,ti2.foo);
+ COMPARE_INTEGER(aa,ab,ti3);
+ return 0;
+}
+
+static int
+cmp_TESTImplicit2 (void *a, void *b)
+{
+ TESTImplicit2 *aa = a;
+ TESTImplicit2 *ab = b;
+
+ COMPARE_INTEGER(aa,ab,ti1);
+ COMPARE_INTEGER(aa,ab,ti3);
+ IF_OPT_COMPARE(aa,ab,ti4) {
+ COMPARE_INTEGER(aa,ab,ti4[0]);
+ }
+ return 0;
+}
+
+static int
+cmp_TESTImplicit3 (void *a, void *b)
+{
+ TESTImplicit3 *aa = a;
+ TESTImplicit3 *ab = b;
+
+ COMPARE_INTEGER(aa,ab,element);
+ if (aa->element == choice_TESTImplicit3_ti1) {
+ COMPARE_INTEGER(aa,ab,u.ti1);
+ } else {
+ COMPARE_INTEGER(aa,ab,u.ti2.element);
+ COMPARE_INTEGER(aa,ab,u.ti2.u.i1);
+ }
+ return 0;
+}
+
+static int
+cmp_TESTImplicit4 (void *a, void *b)
+{
+ TESTImplicit4 *aa = a;
+ TESTImplicit4 *ab = b;
+
+ COMPARE_INTEGER(aa,ab,element);
+ if (aa->element == choice_TESTImplicit4_ti1) {
+ COMPARE_INTEGER(aa,ab,u.ti1);
+ } else {
+ COMPARE_INTEGER(aa,ab,u.ti2.element);
+ COMPARE_INTEGER(aa,ab,u.ti2.u.i1);
+ }
+ return 0;
+}
+
+static int
+test_implicit (void)
+{
+ int ret = 0;
+ /*
+ * UNIV CONS Sequence = 14 bytes {
+ * CONTEXT PRIM tag 0 = 1 bytes [0] IMPLICIT content
+ * CONTEXT CONS tag 1 = 6 bytes [1]
+ * CONTEXT CONS tag 127 = 3 bytes [127]
+ * UNIV PRIM Integer = integer 2
+ * CONTEXT PRIM tag 2 = 1 bytes [2] IMPLICIT content
+ * }
+ */
+ struct test_case tests[] = {
+ { NULL, 16,
+ "\x30\x0e\x80\x01\x00\xa1\x06\xbf\x7f\x03\x02\x01\x02\x82\x01\x03",
+ "implicit 1" }
+ };
+ /*
+ * UNIV CONS Sequence = 10 bytes {
+ * CONTEXT PRIM tag 0 = 1 bytes [0] IMPLICIT content
+ * CONTEXT PRIM tag 2 = 1 bytes [2] IMPLICIT content
+ * CONTEXT PRIM tag 51 = 1 bytes [51] IMPLICIT content
+ * }
+ */
+ struct test_case tests2[] = {
+ { NULL, 12,
+ "\x30\x0a\x80\x01\x01\x82\x01\x03\x9f\x33\x01\x04",
+ "implicit 2" }
+ };
+ /*
+ * CONTEXT CONS tag 5 = 5 bytes [5]
+ * CONTEXT CONS tag 1 = 3 bytes [1]
+ * UNIV PRIM Integer = integer 5
+ */
+ struct test_case tests3[] = {
+ { NULL, 7,
+ "\xa5\x05\xa1\x03\x02\x01\x05",
+ "implicit 3" }
+ };
+ /*
+ * Notice: same as tests3[].bytes.
+ *
+ * CONTEXT CONS tag 5 = 5 bytes [5]
+ * CONTEXT CONS tag 1 = 3 bytes [1]
+ * UNIV PRIM Integer = integer 5
+ */
+ struct test_case tests4[] = {
+ { NULL, 7,
+ "\xa5\x05\xa1\x03\x02\x01\x05",
+ "implicit 4" }
+ };
+
+ TESTImplicit c0;
+ TESTImplicit2 c1;
+ TESTImplicit3 c2;
+ TESTImplicit4 c3;
+ int ti4 = 4;
+
+ memset(&c0, 0, sizeof(c0));
+ c0.ti1 = 0;
+ c0.ti2.foo = 2;
+ c0.ti3 = 3;
+ tests[0].val = &c0;
+
+ memset(&c1, 0, sizeof(c1));
+ c1.ti1 = 1;
+ c1.ti3 = 3;
+ c1.ti4 = &ti4;
+ tests2[0].val = &c1;
+
+ memset(&c2, 0, sizeof(c2));
+ c2.element = choice_TESTImplicit3_ti2;
+ c2.u.ti2.element = choice_TESTImplicit3_ti2_i1;
+ c2.u.ti2.u.i1 = 5;
+ tests3[0].val = &c2;
+
+ memset(&c3, 0, sizeof(c3));
+ c3.element = choice_TESTImplicit4_ti2;
+ c3.u.ti2.element = choice_TESTChoice2_i1;
+ c3.u.ti2.u.i1 = 5;
+ tests4[0].val = &c3;
+
+ ret += generic_test(tests,
+ sizeof(tests) / sizeof(*tests),
+ sizeof(TESTImplicit),
+ (generic_encode)encode_TESTImplicit,
+ (generic_length)length_TESTImplicit,
+ (generic_decode)decode_TESTImplicit,
+ (generic_free)free_TESTImplicit,
+ cmp_TESTImplicit,
+ (generic_copy)copy_TESTImplicit);
+
+ ret += generic_test(tests2,
+ sizeof(tests2) / sizeof(*tests2),
+ sizeof(TESTImplicit2),
+ (generic_encode)encode_TESTImplicit2,
+ (generic_length)length_TESTImplicit2,
+ (generic_decode)decode_TESTImplicit2,
+ (generic_free)free_TESTImplicit2,
+ cmp_TESTImplicit2,
+ NULL);
+
+ ret += generic_test(tests3,
+ sizeof(tests3) / sizeof(*tests3),
+ sizeof(TESTImplicit3),
+ (generic_encode)encode_TESTImplicit3,
+ (generic_length)length_TESTImplicit3,
+ (generic_decode)decode_TESTImplicit3,
+ (generic_free)free_TESTImplicit3,
+ cmp_TESTImplicit3,
+ NULL);
+
+ ret += generic_test(tests4,
+ sizeof(tests4) / sizeof(*tests4),
+ sizeof(TESTImplicit4),
+ (generic_encode)encode_TESTImplicit4,
+ (generic_length)length_TESTImplicit4,
+ (generic_decode)decode_TESTImplicit4,
+ (generic_free)free_TESTImplicit4,
+ cmp_TESTImplicit4,
+ NULL);
+
+ return ret;
+}
+
+static int
+cmp_TESTAlloc (void *a, void *b)
+{
+ TESTAlloc *aa = a;
+ TESTAlloc *ab = b;
+
+ IF_OPT_COMPARE(aa,ab,tagless) {
+ COMPARE_INTEGER(aa,ab,tagless->ai);
+ }
+
+ COMPARE_INTEGER(aa,ab,three);
+
+ IF_OPT_COMPARE(aa,ab,tagless2) {
+ COMPARE_OPT_OCTET_STRING(aa, ab, tagless2);
+ }
+
+ return 0;
+}
+
+/*
+UNIV CONS Sequence 12
+ UNIV CONS Sequence 5
+ CONTEXT CONS 0 3
+ UNIV PRIM Integer 1 01
+ CONTEXT CONS 1 3
+ UNIV PRIM Integer 1 03
+
+UNIV CONS Sequence 5
+ CONTEXT CONS 1 3
+ UNIV PRIM Integer 1 03
+
+UNIV CONS Sequence 8
+ CONTEXT CONS 1 3
+ UNIV PRIM Integer 1 04
+ UNIV PRIM Integer 1 05
+
+*/
+
+static int
+test_taglessalloc (void)
+{
+ struct test_case tests[] = {
+ { NULL, 14,
+ "\x30\x0c\x30\x05\xa0\x03\x02\x01\x01\xa1\x03\x02\x01\x03",
+ "alloc 1" },
+ { NULL, 7,
+ "\x30\x05\xa1\x03\x02\x01\x03",
+ "alloc 2" },
+ { NULL, 10,
+ "\x30\x08\xa1\x03\x02\x01\x04\x02\x01\x05",
+ "alloc 3" }
+ };
+
+ int ret = 0, ntests = sizeof(tests) / sizeof(*tests);
+ TESTAlloc c1, c2, c3;
+ heim_any any3;
+
+ memset(&c1, 0, sizeof(c1));
+ c1.tagless = ecalloc(1, sizeof(*c1.tagless));
+ c1.tagless->ai = 1;
+ c1.three = 3;
+ tests[0].val = &c1;
+
+ memset(&c2, 0, sizeof(c2));
+ c2.tagless = NULL;
+ c2.three = 3;
+ tests[1].val = &c2;
+
+ memset(&c3, 0, sizeof(c3));
+ c3.tagless = NULL;
+ c3.three = 4;
+ c3.tagless2 = &any3;
+ any3.data = "\x02\x01\x05";
+ any3.length = 3;
+ tests[2].val = &c3;
+
+ ret += generic_test (tests, ntests, sizeof(TESTAlloc),
+ (generic_encode)encode_TESTAlloc,
+ (generic_length)length_TESTAlloc,
+ (generic_decode)decode_TESTAlloc,
+ (generic_free)free_TESTAlloc,
+ cmp_TESTAlloc,
+ (generic_copy)copy_TESTAlloc);
+
+ free(c1.tagless);
+
+ return ret;
+}
+
+static int
+cmp_TESTOptional (void *a, void *b)
+{
+ TESTOptional *aa = a;
+ TESTOptional *ab = b;
+
+ IF_OPT_COMPARE(aa,ab,zero) {
+ COMPARE_OPT_INTEGER(aa,ab,zero);
+ }
+ IF_OPT_COMPARE(aa,ab,one) {
+ COMPARE_OPT_INTEGER(aa,ab,one);
+ }
+ return 0;
+}
+
+/*
+UNIV CONS Sequence 5
+ CONTEXT CONS 0 3
+ UNIV PRIM Integer 1 00
+
+UNIV CONS Sequence 5
+ CONTEXT CONS 1 3
+ UNIV PRIM Integer 1 03
+
+UNIV CONS Sequence 10
+ CONTEXT CONS 0 3
+ UNIV PRIM Integer 1 00
+ CONTEXT CONS 1 3
+ UNIV PRIM Integer 1 01
+
+*/
+
+static int
+test_optional (void)
+{
+ struct test_case tests[] = {
+ { NULL, 2,
+ "\x30\x00",
+ "optional 0" },
+ { NULL, 7,
+ "\x30\x05\xa0\x03\x02\x01\x00",
+ "optional 1" },
+ { NULL, 7,
+ "\x30\x05\xa1\x03\x02\x01\x01",
+ "optional 2" },
+ { NULL, 12,
+ "\x30\x0a\xa0\x03\x02\x01\x00\xa1\x03\x02\x01\x01",
+ "optional 3" }
+ };
+
+ int ret = 0, ntests = sizeof(tests) / sizeof(*tests);
+ TESTOptional c0, c1, c2, c3;
+ int zero = 0;
+ int one = 1;
+
+ c0.zero = NULL;
+ c0.one = NULL;
+ tests[0].val = &c0;
+
+ c1.zero = &zero;
+ c1.one = NULL;
+ tests[1].val = &c1;
+
+ c2.zero = NULL;
+ c2.one = &one;
+ tests[2].val = &c2;
+
+ c3.zero = &zero;
+ c3.one = &one;
+ tests[3].val = &c3;
+
+ ret += generic_test (tests, ntests, sizeof(TESTOptional),
+ (generic_encode)encode_TESTOptional,
+ (generic_length)length_TESTOptional,
+ (generic_decode)decode_TESTOptional,
+ (generic_free)free_TESTOptional,
+ cmp_TESTOptional,
+ (generic_copy)copy_TESTOptional);
+
+ return ret;
+}
+
+static int
+check_fail_largetag(void)
+{
+ struct test_case tests[] = {
+ {NULL, 14, "\x30\x0c\xbf\x87\xff\xff\xff\xff\xff\x7f\x03\x02\x01\x01",
+ "tag overflow"},
+ {NULL, 0, "", "empty buffer"},
+ {NULL, 7, "\x30\x05\xa1\x03\x02\x02\x01",
+ "one too short" },
+ {NULL, 7, "\x30\x04\xa1\x03\x02\x02\x01",
+ "two too short" },
+ {NULL, 7, "\x30\x03\xa1\x03\x02\x02\x01",
+ "three too short" },
+ {NULL, 7, "\x30\x02\xa1\x03\x02\x02\x01",
+ "four too short" },
+ {NULL, 7, "\x30\x01\xa1\x03\x02\x02\x01",
+ "five too short" },
+ {NULL, 7, "\x30\x00\xa1\x03\x02\x02\x01",
+ "six too short" },
+ {NULL, 7, "\x30\x05\xa1\x04\x02\x02\x01",
+ "inner one too long" },
+ {NULL, 7, "\x30\x00\xa1\x02\x02\x02\x01",
+ "inner one too short" },
+ {NULL, 8, "\x30\x05\xbf\x7f\x03\x02\x02\x01",
+ "inner one too short"},
+ {NULL, 8, "\x30\x06\xbf\x64\x03\x02\x01\x01",
+ "wrong tag"},
+ {NULL, 10, "\x30\x08\xbf\x9a\x9b\x38\x03\x02\x01\x01",
+ "still wrong tag"}
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ return generic_decode_fail(tests, ntests, sizeof(TESTLargeTag),
+ (generic_decode)decode_TESTLargeTag);
+}
+
+
+static int
+check_fail_sequence(void)
+{
+ struct test_case tests[] = {
+ {NULL, 0, "", "empty buffer"},
+ {NULL, 24,
+ "\x30\x16\xa0\x03\x02\x01\x01\xa1\x08\x30\x06\xbf\x7f\x03\x02\x01\x01"
+ "\x02\x01\x01\xa2\x03\x02\x01\x01",
+ "missing one byte from the end, internal length ok"},
+ {NULL, 25,
+ "\x30\x18\xa0\x03\x02\x01\x01\xa1\x08\x30\x06\xbf\x7f\x03\x02\x01\x01"
+ "\x02\x01\x01\xa2\x03\x02\x01\x01",
+ "inner length one byte too long"},
+ {NULL, 24,
+ "\x30\x17\xa0\x03\x02\x01\x01\xa1\x08\x30\x06\xbf\x7f\x03\x02\x01"
+ "\x01\x02\x01\x01\xa2\x03\x02\x01\x01",
+ "correct buffer but missing one too short"}
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ return generic_decode_fail(tests, ntests, sizeof(TESTSeq),
+ (generic_decode)decode_TESTSeq);
+}
+
+static int
+check_fail_choice(void)
+{
+ struct test_case tests[] = {
+ {NULL, 6,
+ "\xa1\x02\x02\x01\x01",
+ "choice one too short"},
+ {NULL, 6,
+ "\xa1\x03\x02\x02\x01",
+ "choice one too short inner"}
+ };
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ return generic_decode_fail(tests, ntests, sizeof(TESTChoice1),
+ (generic_decode)decode_TESTChoice1);
+}
+
+static int
+check_fail_Ticket(void)
+{
+ char buf[100];
+ size_t i;
+ int ret;
+ struct test_case test;
+ Ticket ticket;
+
+ for (i = 0; i < sizeof(buf); i++) {
+ memset(buf, 0, sizeof(buf));
+ memset(&ticket, 0, sizeof(ticket));
+ test.val = &ticket;
+ test.byte_len = i;
+ test.bytes = buf;
+ test.name = "zero life";
+ ret = generic_decode_fail(&test, 1, sizeof(Ticket),
+ (generic_decode)decode_Ticket);
+ if (ret)
+ return ret;
+ }
+ return 0;
+}
+
+static int
+check_seq(void)
+{
+ TESTSeqOf seq;
+ TESTInteger i = 0;
+ int ret;
+
+ seq.val = NULL;
+ seq.len = 0;
+
+ ret = add_TESTSeqOf(&seq, &i);
+ if (ret) { printf("failed adding\n"); goto out; }
+ ret = add_TESTSeqOf(&seq, &i);
+ if (ret) { printf("failed adding\n"); goto out; }
+ ret = add_TESTSeqOf(&seq, &i);
+ if (ret) { printf("failed adding\n"); goto out; }
+ ret = add_TESTSeqOf(&seq, &i);
+ if (ret) { printf("failed adding\n"); goto out; }
+
+ ret = remove_TESTSeqOf(&seq, seq.len - 1);
+ if (ret) { printf("failed removing\n"); goto out; }
+ ret = remove_TESTSeqOf(&seq, 2);
+ if (ret) { printf("failed removing\n"); goto out; }
+ ret = remove_TESTSeqOf(&seq, 0);
+ if (ret) { printf("failed removing\n"); goto out; }
+ ret = remove_TESTSeqOf(&seq, 0);
+ if (ret) { printf("failed removing\n"); goto out; }
+ ret = remove_TESTSeqOf(&seq, 0);
+ if (ret == 0) {
+ printf("can remove from empty list");
+ return 1;
+ }
+
+ if (seq.len != 0) {
+ printf("seq not empty!");
+ return 1;
+ }
+ free_TESTSeqOf(&seq);
+ ret = 0;
+
+out:
+
+ return ret;
+}
+
+#define test_seq_of(type, ok, ptr) \
+{ \
+ heim_octet_string os; \
+ size_t size; \
+ type decode; \
+ ASN1_MALLOC_ENCODE(type, os.data, os.length, ptr, &size, ret); \
+ if (ret) \
+ return ret; \
+ if (os.length != size) \
+ abort(); \
+ ret = decode_##type(os.data, os.length, &decode, &size); \
+ free(os.data); \
+ if (ret) { \
+ if (ok) \
+ return 1; \
+ } else { \
+ free_##type(&decode); \
+ if (!ok) \
+ return 1; \
+ if (size != 0) \
+ return 1; \
+ } \
+ return 0; \
+}
+
+static int
+check_seq_of_size(void)
+{
+#if 0 /* template */
+ TESTInteger integers[4] = { 1, 2, 3, 4 };
+ int ret;
+
+ {
+ TESTSeqSizeOf1 ssof1f1 = { 1, integers };
+ TESTSeqSizeOf1 ssof1ok1 = { 2, integers };
+ TESTSeqSizeOf1 ssof1f2 = { 3, integers };
+
+ test_seq_of(TESTSeqSizeOf1, 0, &ssof1f1);
+ test_seq_of(TESTSeqSizeOf1, 1, &ssof1ok1);
+ test_seq_of(TESTSeqSizeOf1, 0, &ssof1f2);
+ }
+ {
+ TESTSeqSizeOf2 ssof2f1 = { 0, NULL };
+ TESTSeqSizeOf2 ssof2ok1 = { 1, integers };
+ TESTSeqSizeOf2 ssof2ok2 = { 2, integers };
+ TESTSeqSizeOf2 ssof2f2 = { 3, integers };
+
+ test_seq_of(TESTSeqSizeOf2, 0, &ssof2f1);
+ test_seq_of(TESTSeqSizeOf2, 1, &ssof2ok1);
+ test_seq_of(TESTSeqSizeOf2, 1, &ssof2ok2);
+ test_seq_of(TESTSeqSizeOf2, 0, &ssof2f2);
+ }
+ {
+ TESTSeqSizeOf3 ssof3f1 = { 0, NULL };
+ TESTSeqSizeOf3 ssof3ok1 = { 1, integers };
+ TESTSeqSizeOf3 ssof3ok2 = { 2, integers };
+
+ test_seq_of(TESTSeqSizeOf3, 0, &ssof3f1);
+ test_seq_of(TESTSeqSizeOf3, 1, &ssof3ok1);
+ test_seq_of(TESTSeqSizeOf3, 1, &ssof3ok2);
+ }
+ {
+ TESTSeqSizeOf4 ssof4ok1 = { 0, NULL };
+ TESTSeqSizeOf4 ssof4ok2 = { 1, integers };
+ TESTSeqSizeOf4 ssof4ok3 = { 2, integers };
+ TESTSeqSizeOf4 ssof4f1 = { 3, integers };
+
+ test_seq_of(TESTSeqSizeOf4, 1, &ssof4ok1);
+ test_seq_of(TESTSeqSizeOf4, 1, &ssof4ok2);
+ test_seq_of(TESTSeqSizeOf4, 1, &ssof4ok3);
+ test_seq_of(TESTSeqSizeOf4, 0, &ssof4f1);
+ }
+#endif
+ return 0;
+}
+
+static int
+check_TESTMechTypeList(void)
+{
+ TESTMechTypeList tl;
+ unsigned oid1[] = { 1, 2, 840, 48018, 1, 2, 2};
+ unsigned oid2[] = { 1, 2, 840, 113554, 1, 2, 2};
+ unsigned oid3[] = { 1, 3, 6, 1, 4, 1, 311, 2, 2, 30};
+ unsigned oid4[] = { 1, 3, 6, 1, 4, 1, 311, 2, 2, 10};
+ TESTMechType array[] = {{ 7, oid1 },
+ { 7, oid2 },
+ { 10, oid3 },
+ { 10, oid4 }};
+ size_t size, len;
+ void *ptr;
+ int ret;
+
+ tl.len = 4;
+ tl.val = array;
+
+ ASN1_MALLOC_ENCODE(TESTMechTypeList, ptr, len, &tl, &size, ret);
+ if (ret)
+ errx(1, "TESTMechTypeList: %d", ret);
+ if (len != size)
+ abort();
+ free(ptr);
+ return 0;
+}
+
+static int
+cmp_TESTSeqOf4(void *a, void *b)
+{
+ TESTSeqOf4 *aa = a;
+ TESTSeqOf4 *ab = b;
+ int i;
+
+ IF_OPT_COMPARE(aa, ab, b1) {
+ COMPARE_INTEGER(aa->b1, ab->b1, len);
+ for (i = 0; i < aa->b1->len; ++i) {
+ COMPARE_INTEGER(aa->b1->val+i, ab->b1->val+i, u1);
+ COMPARE_INTEGER(aa->b1->val+i, ab->b1->val+i, u2);
+ COMPARE_OCTET_STRING(aa->b1->val+i, ab->b1->val+i, s1);
+ COMPARE_OCTET_STRING(aa->b1->val+i, ab->b1->val+i, s2);
+ }
+ }
+ IF_OPT_COMPARE(aa, ab, b2) {
+ COMPARE_INTEGER(aa->b2, ab->b2, len);
+ for (i = 0; i < aa->b2->len; ++i) {
+ COMPARE_INTEGER(aa->b2->val+i, ab->b2->val+i, u1);
+ COMPARE_INTEGER(aa->b2->val+i, ab->b2->val+i, u2);
+ COMPARE_INTEGER(aa->b2->val+i, ab->b2->val+i, u3);
+ COMPARE_OCTET_STRING(aa->b2->val+i, ab->b2->val+i, s1);
+ COMPARE_OCTET_STRING(aa->b2->val+i, ab->b2->val+i, s2);
+ COMPARE_OCTET_STRING(aa->b2->val+i, ab->b2->val+i, s3);
+ }
+ }
+ IF_OPT_COMPARE(aa, ab, b3) {
+ COMPARE_INTEGER(aa->b3, ab->b3, len);
+ for (i = 0; i < aa->b3->len; ++i) {
+ COMPARE_INTEGER(aa->b3->val+i, ab->b3->val+i, u1);
+ COMPARE_INTEGER(aa->b3->val+i, ab->b3->val+i, u2);
+ COMPARE_INTEGER(aa->b3->val+i, ab->b3->val+i, u3);
+ COMPARE_INTEGER(aa->b3->val+i, ab->b3->val+i, u4);
+ COMPARE_OCTET_STRING(aa->b3->val+i, ab->b3->val+i, s1);
+ COMPARE_OCTET_STRING(aa->b3->val+i, ab->b3->val+i, s2);
+ COMPARE_OCTET_STRING(aa->b3->val+i, ab->b3->val+i, s3);
+ COMPARE_OCTET_STRING(aa->b3->val+i, ab->b3->val+i, s4);
+ }
+ }
+ return 0;
+}
+
+static int
+test_seq4 (void)
+{
+ int ret = 0;
+ struct test_case tests[] = {
+ { NULL, 2,
+ "\x30\x00",
+ "seq4 0" },
+ { NULL, 4,
+ "\x30\x02" "\xa1\x00",
+ "seq4 1" },
+ { NULL, 8,
+ "\x30\x06" "\xa0\x02\x30\x00" "\xa1\x00",
+ "seq4 2" },
+ { NULL, 2 + (2 + 0x18) + (2 + 0x27) + (2 + 0x31),
+ "\x30\x76" /* 2 SEQ */
+ "\xa0\x18\x30\x16" /* 4 [0] SEQ */
+ "\x30\x14" /* 2 SEQ */
+ "\x04\x00" /* 2 OCTET-STRING */
+ "\x04\x02\x01\x02" /* 4 OCTET-STRING */
+ "\x02\x01\x01" /* 3 INT */
+ "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xff"
+ /* 11 INT */
+ "\xa1\x27" /* 2 [1] IMPL SEQ */
+ "\x30\x25" /* 2 SEQ */
+ "\x02\x01\x01" /* 3 INT */
+ "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xff"
+ /* 11 INT */
+ "\x02\x09\x00\x80\x00\x00\x00\x00\x00\x00\x00"
+ /* 11 INT */
+ "\x04\x00" /* 2 OCTET-STRING */
+ "\x04\x02\x01\x02" /* 4 OCTET-STRING */
+ "\x04\x04\x00\x01\x02\x03" /* 6 OCTET-STRING */
+ "\xa2\x31" /* 2 [2] IMPL SEQ */
+ "\x30\x2f" /* 2 SEQ */
+ "\x04\x00" /* 2 OCTET-STRING */
+ "\x02\x01\x01" /* 3 INT */
+ "\x04\x02\x01\x02" /* 4 OCTET-STRING */
+ "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xff"
+ /* 11 INT */
+ "\x04\x04\x00\x01\x02\x03" /* 6 OCTET-STRING */
+ "\x02\x09\x00\x80\x00\x00\x00\x00\x00\x00\x00"
+ /* 11 INT */
+ "\x04\x01\x00" /* 3 OCTET-STRING */
+ "\x02\x05\x01\x00\x00\x00\x00", /* 7 INT */
+ "seq4 3" },
+ };
+
+ int ntests = sizeof(tests) / sizeof(*tests);
+ TESTSeqOf4 c[4];
+ struct TESTSeqOf4_b1 b1[4];
+ struct TESTSeqOf4_b2 b2[4];
+ struct TESTSeqOf4_b3 b3[4];
+ struct TESTSeqOf4_b1_val b1val[4];
+ struct TESTSeqOf4_b2_val b2val[4];
+ struct TESTSeqOf4_b3_val b3val[4];
+
+ c[0].b1 = NULL;
+ c[0].b2 = NULL;
+ c[0].b3 = NULL;
+ tests[0].val = &c[0];
+
+ b2[1].len = 0;
+ b2[1].val = NULL;
+ c[1].b1 = NULL;
+ c[1].b2 = &b2[1];
+ c[1].b3 = NULL;
+ tests[1].val = &c[1];
+
+ b1[2].len = 0;
+ b1[2].val = NULL;
+ b2[2].len = 0;
+ b2[2].val = NULL;
+ c[2].b1 = &b1[2];
+ c[2].b2 = &b2[2];
+ c[2].b3 = NULL;
+ tests[2].val = &c[2];
+
+ b1val[3].s1.data = "";
+ b1val[3].s1.length = 0;
+ b1val[3].u1 = 1LL;
+ b1val[3].s2.data = "\x01\x02";
+ b1val[3].s2.length = 2;
+ b1val[3].u2 = -1LL;
+
+ b2val[3].s1.data = "";
+ b2val[3].s1.length = 0;
+ b2val[3].u1 = 1LL;
+ b2val[3].s2.data = "\x01\x02";
+ b2val[3].s2.length = 2;
+ b2val[3].u2 = -1LL;
+ b2val[3].s3.data = "\x00\x01\x02\x03";
+ b2val[3].s3.length = 4;
+ b2val[3].u3 = 1LL<<63;
+
+ b3val[3].s1.data = "";
+ b3val[3].s1.length = 0;
+ b3val[3].u1 = 1LL;
+ b3val[3].s2.data = "\x01\x02";
+ b3val[3].s2.length = 2;
+ b3val[3].u2 = -1LL;
+ b3val[3].s3.data = "\x00\x01\x02\x03";
+ b3val[3].s3.length = 4;
+ b3val[3].u3 = 1LL<<63;
+ b3val[3].s4.data = "\x00";
+ b3val[3].s4.length = 1;
+ b3val[3].u4 = 1LL<<32;
+
+ b1[3].len = 1;
+ b1[3].val = &b1val[3];
+ b2[3].len = 1;
+ b2[3].val = &b2val[3];
+ b3[3].len = 1;
+ b3[3].val = &b3val[3];
+ c[3].b1 = &b1[3];
+ c[3].b2 = &b2[3];
+ c[3].b3 = &b3[3];
+ tests[3].val = &c[3];
+
+ ret += generic_test (tests, ntests, sizeof(TESTSeqOf4),
+ (generic_encode)encode_TESTSeqOf4,
+ (generic_length)length_TESTSeqOf4,
+ (generic_decode)decode_TESTSeqOf4,
+ (generic_free)free_TESTSeqOf4,
+ cmp_TESTSeqOf4,
+ (generic_copy)copy_TESTSeqOf4);
+ return ret;
+}
+
+static int
+cmp_test_seqof5 (void *a, void *b)
+{
+ TESTSeqOf5 *aval = a;
+ TESTSeqOf5 *bval = b;
+
+ IF_OPT_COMPARE(aval, bval, outer) {
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u0);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s0);
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u1);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s1);
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u2);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s2);
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u3);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s3);
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u4);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s4);
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u5);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s5);
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u6);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s6);
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u7);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s7);
+ }
+ return 0;
+}
+
+static int
+test_seqof5(void)
+{
+ struct test_case tests[] = {
+ { NULL, 2, "\x30\x00", "seq5 0" },
+ { NULL, 126,
+ "\x30\x7c" /* SEQ */
+ "\x30\x7a" /* SEQ */
+ "\x30\x78" /* SEQ */
+ "\x02\x01\x01" /* INT 1 */
+ "\x04\x06\x01\x01\x01\x01\x01\x01" /* "\0x1"x6 */
+ "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xfe" /* INT ~1 */
+ "\x04\x06\x02\x02\x02\x02\x02\x02" /* "\x02"x6 */
+ "\x02\x01\x02" /* INT 2 */
+ "\x04\x06\x03\x03\x03\x03\x03\x03" /* "\x03"x6 */
+ "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xfd" /* INT ~2 */
+ "\x04\x06\x04\x04\x04\x04\x04\x04" /* ... */
+ "\x02\x01\x03"
+ "\x04\x06\x05\x05\x05\x05\x05\x05"
+ "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xfc"
+ "\x04\x06\x06\x06\x06\x06\x06\x06"
+ "\x02\x01\x04"
+ "\x04\x06\x07\x07\x07\x07\x07\x07"
+ "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xfb"
+ "\x04\x06\x08\x08\x08\x08\x08\x08",
+ "seq5 1" },
+ };
+
+ int ret = 0, ntests = sizeof(tests) / sizeof(*tests);
+ TESTSeqOf5 c[2];
+ struct TESTSeqOf5_outer outer;
+ struct TESTSeqOf5_outer_inner inner;
+ TESTuint64 u[8];
+ heim_octet_string s[8];
+ int i;
+
+ c[0].outer = NULL;
+ tests[0].val = &c[0];
+
+ for (i = 0; i < 8; ++i) {
+ u[i] = (i&1) == 0 ? i/2+1 : ~(i/2+1);
+ s[i].data = memset(malloc(s[i].length = 6), i+1, 6);
+ }
+
+ inner.u0 = u[0]; inner.u1 = u[1]; inner.u2 = u[2]; inner.u3 = u[3];
+ inner.u4 = u[4]; inner.u5 = u[5]; inner.u6 = u[6]; inner.u7 = u[7];
+ inner.s0 = s[0]; inner.s1 = s[1]; inner.s2 = s[2]; inner.s3 = s[3];
+ inner.s4 = s[4]; inner.s5 = s[5]; inner.s6 = s[6]; inner.s7 = s[7];
+
+ outer.inner = inner;
+ c[1].outer = &outer;
+ tests[1].val = &c[1];
+
+ ret += generic_test (tests, ntests, sizeof(TESTSeqOf5),
+ (generic_encode)encode_TESTSeqOf5,
+ (generic_length)length_TESTSeqOf5,
+ (generic_decode)decode_TESTSeqOf5,
+ (generic_free)free_TESTSeqOf5,
+ cmp_test_seqof5,
+ NULL);
+
+ for (i = 0; i < 8; ++i)
+ free(s[i].data);
+
+ return ret;
+}
+
+static int
+cmp_default(void *a, void *b)
+{
+ TESTDefault *aa = a;
+ TESTDefault *ab = b;
+
+ COMPARE_STRING(aa,ab,name);
+ COMPARE_INTEGER(aa,ab,version);
+ COMPARE_INTEGER(aa,ab,maxint);
+ COMPARE_INTEGER(aa,ab,works);
+ return 0;
+}
+
+static int
+test_default(void)
+{
+ struct test_case tests[] = {
+ { NULL, 2, "\x30\x00", NULL },
+ { NULL, 25,
+ "\x30\x17\x0c\x07\x68\x65\x69\x6d\x64\x61"
+ "\x6c\xa0\x03\x02\x01\x07\x02\x04\x7f\xff"
+ "\xff\xff\x01\x01\x00",
+ NULL
+ },
+ { NULL, 10,
+ "\x30\x08\xa0\x03\x02\x01\x07\x01\x01\x00",
+ NULL
+ },
+ { NULL, 17,
+ "\x30\x0f\x0c\x07\x68\x65\x69\x6d\x64\x61\x6c\x02\x04"
+ "\x7f\xff\xff\xff",
+ NULL
+ }
+ };
+
+ TESTDefault values[] = {
+ { "Heimdal", 8, 9223372036854775807, 1 },
+ { "heimdal", 7, 2147483647, 0 },
+ { "Heimdal", 7, 9223372036854775807, 0 },
+ { "heimdal", 8, 2147483647, 1 },
+ };
+ int i, ret;
+ int ntests = sizeof(tests) / sizeof(*tests);
+
+ for (i = 0; i < ntests; ++i) {
+ tests[i].val = &values[i];
+ if (asprintf (&tests[i].name, "TESTDefault %d", i) < 0)
+ errx(1, "malloc");
+ if (tests[i].name == NULL)
+ errx(1, "malloc");
+ }
+
+ ret = generic_test (tests, ntests, sizeof(TESTDefault),
+ (generic_encode)encode_TESTDefault,
+ (generic_length)length_TESTDefault,
+ (generic_decode)decode_TESTDefault,
+ (generic_free)free_TESTDefault,
+ cmp_default,
+ (generic_copy)copy_TESTDefault);
+ for (i = 0; i < ntests; ++i)
+ free(tests[i].name);
+
+ return ret;
+}
+
+static int
+test_x690sample(void)
+{
+ /*
+ * Taken from X.690, Appendix A, though sadly it's not specified whether
+ * it's in BER, DER, or CER, but it is clearly BER and neither DER nor CER
+ * because the tags of the members of the X690SamplePersonnelRecord type
+ * are not canonically sorted in the given sample.
+ *
+ * Our compiler does NOT canonically sort the members of SET { ... } types
+ * so it produces the same encoding after decoding this test vector. That
+ * is clearly a bug given that we aim to output DER.
+ *
+ * The template compiler doesn't even decode SET { ... } values properly
+ * when their members are not in the same order as defined (but the regular
+ * compiler does).
+ */
+ X690SamplePersonnelRecord r;
+ heim_octet_string os;
+ unsigned char encoded_sample[] = {
+ 0x60, 0x81, 0x85, 0x61, 0x10, 0x1a, 0x04, 0x4a, 0x6f, 0x68, 0x6e, 0x1a,
+ 0x01, 0x50, 0x1a, 0x05, 0x53, 0x6d, 0x69, 0x74, 0x68, 0xa0, 0x0a, 0x1a,
+ 0x08, 0x44, 0x69, 0x72, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x42, 0x01, 0x33,
+ 0xa1, 0x0a, 0x43, 0x08, 0x31, 0x39, 0x37, 0x31, 0x30, 0x39, 0x31, 0x37,
+ 0xa2, 0x12, 0x61, 0x10, 0x1a, 0x04, 0x4d, 0x61, 0x72, 0x79, 0x1a, 0x01,
+ 0x54, 0x1a, 0x05, 0x53, 0x6d, 0x69, 0x74, 0x68, 0xa3, 0x42, 0x31, 0x1f,
+ 0x61, 0x11, 0x1a, 0x05, 0x52, 0x61, 0x6c, 0x70, 0x68, 0x1a, 0x01, 0x54,
+ 0x1a, 0x05, 0x53, 0x6d, 0x69, 0x74, 0x68, 0xa0, 0x0a, 0x43, 0x08, 0x31,
+ 0x39, 0x35, 0x37, 0x31, 0x31, 0x31, 0x31, 0x31, 0x1f, 0x61, 0x11, 0x1a,
+ 0x05, 0x53, 0x75, 0x73, 0x61, 0x6e, 0x1a, 0x01, 0x42, 0x1a, 0x05, 0x53,
+ 0x6d, 0x69, 0x74, 0x68, 0xa0, 0x0a, 0x43, 0x08, 0x31, 0x39, 0x35, 0x39,
+ 0x30, 0x37, 0x31, 0x37
+ };
+ size_t sz = 0;
+ int ret;
+
+ memset(&r, 0, sizeof(r));
+ if (decode_X690SamplePersonnelRecord(encoded_sample, sizeof(encoded_sample), &r, &sz))
+ return 1;
+ if (sz != sizeof(encoded_sample))
+ return 1;
+ free_X690SamplePersonnelRecord(&r);
+ memset(&r, 0, sizeof(r));
+
+ /* We re-construct the record manually to double-check the spec */
+ r.name.givenName = strdup("John");
+ r.name.initial = strdup("P");
+ r.name.familyName = strdup("Smith");
+ r.title = strdup("Director");
+ r.dateOfHire = strdup("19710917");
+ r.number = 51;
+ r.nameOfSpouse.givenName = strdup("Mary");
+ r.nameOfSpouse.initial = strdup("T");
+ r.nameOfSpouse.familyName = strdup("Smith");
+ r.children.val = calloc(2, sizeof(r.children.val[0]));
+ r.children.len = 2;
+ r.children.val[0].name.givenName = strdup("Ralph");
+ r.children.val[0].name.initial = strdup("T");
+ r.children.val[0].name.familyName = strdup("Smith");
+ r.children.val[0].dateOfBirth = strdup("19571111");
+ r.children.val[1].name.givenName = strdup("Susan");
+ r.children.val[1].name.initial = strdup("B");
+ r.children.val[1].name.familyName = strdup("Smith");
+ r.children.val[1].dateOfBirth = strdup("19590717");
+ os.length = 0;
+ os.data = 0;
+ ASN1_MALLOC_ENCODE(X690SamplePersonnelRecord, os.data, os.length, &r, &sz,
+ ret);
+ if (ret || sz != sizeof(encoded_sample) || sz != os.length ||
+ memcmp(encoded_sample, os.data, sz) != 0)
+ return 1;
+ free_X690SamplePersonnelRecord(&r);
+ free(os.data);
+ return 0;
+}
+
+#if ASN1_IOS_SUPPORTED
+static int
+test_ios(void)
+{
+ unsigned char encoded_sample[] = {
+ 0x30, 0x82, 0x04, 0x8e, 0x30, 0x82, 0x03, 0x76,
+ 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x14, 0x6a,
+ 0x05, 0x97, 0xba, 0x71, 0xd7, 0xe6, 0xd3, 0xac,
+ 0x0e, 0xdc, 0x9e, 0xdc, 0x95, 0xa1, 0x5b, 0x99,
+ 0x8d, 0xe4, 0x0a, 0x30, 0x0d, 0x06, 0x09, 0x2a,
+ 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b,
+ 0x05, 0x00, 0x30, 0x55, 0x31, 0x0b, 0x30, 0x09,
+ 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x43,
+ 0x48, 0x31, 0x1e, 0x30, 0x1c, 0x06, 0x03, 0x55,
+ 0x04, 0x0a, 0x13, 0x15, 0x53, 0x54, 0x4d, 0x69,
+ 0x63, 0x72, 0x6f, 0x65, 0x6c, 0x65, 0x63, 0x74,
+ 0x72, 0x6f, 0x6e, 0x69, 0x63, 0x73, 0x20, 0x4e,
+ 0x56, 0x31, 0x26, 0x30, 0x24, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x1d, 0x53, 0x54, 0x4d, 0x20,
+ 0x54, 0x50, 0x4d, 0x20, 0x45, 0x4b, 0x20, 0x49,
+ 0x6e, 0x74, 0x65, 0x72, 0x6d, 0x65, 0x64, 0x69,
+ 0x61, 0x74, 0x65, 0x20, 0x43, 0x41, 0x20, 0x30,
+ 0x35, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x38, 0x31,
+ 0x32, 0x31, 0x34, 0x30, 0x30, 0x30, 0x30, 0x30,
+ 0x30, 0x5a, 0x17, 0x0d, 0x32, 0x38, 0x31, 0x32,
+ 0x31, 0x34, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
+ 0x5a, 0x30, 0x00, 0x30, 0x82, 0x01, 0x22, 0x30,
+ 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
+ 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82,
+ 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02,
+ 0x82, 0x01, 0x01, 0x00, 0xcc, 0x14, 0xeb, 0x27,
+ 0xa7, 0x8c, 0xeb, 0x0e, 0xa4, 0x86, 0xfa, 0x2d,
+ 0xf7, 0x83, 0x5f, 0x5f, 0xa8, 0xe9, 0x05, 0xb0,
+ 0x97, 0x01, 0x2b, 0x5b, 0xde, 0x50, 0x38, 0x0c,
+ 0x35, 0x5b, 0x1a, 0x2a, 0x72, 0x1b, 0xbc, 0x3d,
+ 0x08, 0xdd, 0x21, 0x79, 0x6c, 0xdb, 0x23, 0x9f,
+ 0xa9, 0x53, 0x10, 0x65, 0x1b, 0x1b, 0x56, 0xfd,
+ 0x2c, 0xfe, 0x53, 0xc8, 0x73, 0x52, 0xeb, 0xd9,
+ 0x96, 0xe3, 0x32, 0x56, 0x16, 0x04, 0x04, 0xce,
+ 0x93, 0x02, 0xa0, 0x80, 0x66, 0x80, 0x1e, 0x78,
+ 0x6a, 0x2f, 0x86, 0xe1, 0x81, 0xf9, 0x49, 0x96,
+ 0x6f, 0x49, 0x2a, 0x85, 0xb5, 0x8e, 0xaa, 0x4a,
+ 0x6a, 0x8c, 0xb3, 0x69, 0x75, 0x51, 0xbb, 0x23,
+ 0x6e, 0x87, 0xcc, 0x7b, 0xf8, 0xec, 0x13, 0x47,
+ 0x87, 0x1c, 0x91, 0xe1, 0x54, 0x37, 0xe8, 0xf2,
+ 0x66, 0xbf, 0x1e, 0xa5, 0xeb, 0x27, 0x1f, 0xdc,
+ 0xf3, 0x74, 0xd8, 0xb4, 0x7d, 0xf8, 0xbc, 0xe8,
+ 0x9e, 0x1f, 0xad, 0x61, 0xc2, 0xa0, 0x88, 0xcb,
+ 0x40, 0x36, 0xb3, 0x59, 0xcb, 0x72, 0xa2, 0x94,
+ 0x97, 0x3f, 0xed, 0xcc, 0xf0, 0xc3, 0x40, 0xaf,
+ 0xfd, 0x14, 0xb6, 0x4f, 0x04, 0x11, 0x65, 0x58,
+ 0x1a, 0xca, 0x34, 0x14, 0x7c, 0x1c, 0x75, 0x61,
+ 0x70, 0x47, 0x05, 0x8f, 0x7e, 0xd7, 0xd6, 0x03,
+ 0xe0, 0x32, 0x50, 0x80, 0x94, 0xfa, 0x73, 0xe8,
+ 0xb9, 0x15, 0x3d, 0xa3, 0xbf, 0x25, 0x5d, 0x2c,
+ 0xbb, 0xc5, 0xdf, 0x30, 0x1b, 0xa8, 0xf7, 0x4d,
+ 0x19, 0x8b, 0xeb, 0xce, 0x86, 0x04, 0x0f, 0xc1,
+ 0xd2, 0x92, 0x7c, 0x76, 0x57, 0x41, 0x44, 0x90,
+ 0xd8, 0x02, 0xf4, 0x82, 0xf3, 0xeb, 0xf2, 0xde,
+ 0x35, 0xee, 0x14, 0x9a, 0x1a, 0x6d, 0xe8, 0xd1,
+ 0x68, 0x91, 0xfb, 0xfb, 0xa0, 0x2a, 0x18, 0xaf,
+ 0xe5, 0x9f, 0x9d, 0x6f, 0x14, 0x97, 0x44, 0xe5,
+ 0xf0, 0xd5, 0x59, 0xb1, 0x02, 0x03, 0x01, 0x00,
+ 0x01, 0xa3, 0x82, 0x01, 0xa9, 0x30, 0x82, 0x01,
+ 0xa5, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23,
+ 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x1a, 0xdb,
+ 0x99, 0x4a, 0xb5, 0x8b, 0xe5, 0x7a, 0x0c, 0xc9,
+ 0xb9, 0x00, 0xe7, 0x85, 0x1e, 0x1a, 0x43, 0xc0,
+ 0x86, 0x60, 0x30, 0x42, 0x06, 0x03, 0x55, 0x1d,
+ 0x20, 0x04, 0x3b, 0x30, 0x39, 0x30, 0x37, 0x06,
+ 0x04, 0x55, 0x1d, 0x20, 0x00, 0x30, 0x2f, 0x30,
+ 0x2d, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05,
+ 0x07, 0x02, 0x01, 0x16, 0x21, 0x68, 0x74, 0x74,
+ 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e,
+ 0x73, 0x74, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x54,
+ 0x50, 0x4d, 0x2f, 0x72, 0x65, 0x70, 0x6f, 0x73,
+ 0x69, 0x74, 0x6f, 0x72, 0x79, 0x2f, 0x30, 0x59,
+ 0x06, 0x03, 0x55, 0x1d, 0x11, 0x01, 0x01, 0xff,
+ 0x04, 0x4f, 0x30, 0x4d, 0xa4, 0x4b, 0x30, 0x49,
+ 0x31, 0x16, 0x30, 0x14, 0x06, 0x05, 0x67, 0x81,
+ 0x05, 0x02, 0x01, 0x0c, 0x0b, 0x69, 0x64, 0x3a,
+ 0x35, 0x33, 0x35, 0x34, 0x34, 0x44, 0x32, 0x30,
+ 0x31, 0x17, 0x30, 0x15, 0x06, 0x05, 0x67, 0x81,
+ 0x05, 0x02, 0x02, 0x0c, 0x0c, 0x53, 0x54, 0x33,
+ 0x33, 0x48, 0x54, 0x50, 0x48, 0x41, 0x48, 0x43,
+ 0x30, 0x31, 0x16, 0x30, 0x14, 0x06, 0x05, 0x67,
+ 0x81, 0x05, 0x02, 0x03, 0x0c, 0x0b, 0x69, 0x64,
+ 0x3a, 0x30, 0x30, 0x34, 0x39, 0x30, 0x30, 0x30,
+ 0x38, 0x30, 0x67, 0x06, 0x03, 0x55, 0x1d, 0x09,
+ 0x04, 0x60, 0x30, 0x5e, 0x30, 0x17, 0x06, 0x05,
+ 0x67, 0x81, 0x05, 0x02, 0x10, 0x31, 0x0e, 0x30,
+ 0x0c, 0x0c, 0x03, 0x32, 0x2e, 0x30, 0x02, 0x01,
+ 0x00, 0x02, 0x02, 0x00, 0x8a, 0x30, 0x43, 0x06,
+ 0x05, 0x67, 0x81, 0x05, 0x02, 0x12, 0x31, 0x3a,
+ 0x30, 0x38, 0x02, 0x01, 0x00, 0x01, 0x01, 0xff,
+ 0xa0, 0x03, 0x0a, 0x01, 0x01, 0xa1, 0x03, 0x0a,
+ 0x01, 0x00, 0xa2, 0x03, 0x0a, 0x01, 0x00, 0xa3,
+ 0x10, 0x30, 0x0e, 0x16, 0x03, 0x33, 0x2e, 0x31,
+ 0x0a, 0x01, 0x04, 0x0a, 0x01, 0x02, 0x01, 0x01,
+ 0xff, 0xa4, 0x0f, 0x30, 0x0d, 0x16, 0x05, 0x31,
+ 0x34, 0x30, 0x2d, 0x32, 0x0a, 0x01, 0x02, 0x01,
+ 0x01, 0x00, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d,
+ 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02,
+ 0x05, 0x20, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d,
+ 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00,
+ 0x30, 0x10, 0x06, 0x03, 0x55, 0x1d, 0x25, 0x04,
+ 0x09, 0x30, 0x07, 0x06, 0x05, 0x67, 0x81, 0x05,
+ 0x08, 0x01, 0x30, 0x4a, 0x06, 0x08, 0x2b, 0x06,
+ 0x01, 0x05, 0x05, 0x07, 0x01, 0x01, 0x04, 0x3e,
+ 0x30, 0x3c, 0x30, 0x3a, 0x06, 0x08, 0x2b, 0x06,
+ 0x01, 0x05, 0x05, 0x07, 0x30, 0x02, 0x86, 0x2e,
+ 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x73,
+ 0x65, 0x63, 0x75, 0x72, 0x65, 0x2e, 0x67, 0x6c,
+ 0x6f, 0x62, 0x61, 0x6c, 0x73, 0x69, 0x67, 0x6e,
+ 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x73, 0x74, 0x6d,
+ 0x74, 0x70, 0x6d, 0x65, 0x6b, 0x69, 0x6e, 0x74,
+ 0x30, 0x35, 0x2e, 0x63, 0x72, 0x74, 0x30, 0x0d,
+ 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
+ 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, 0x01,
+ 0x01, 0x00, 0x3d, 0x4c, 0x38, 0x1e, 0x5b, 0x4f,
+ 0x1b, 0xcb, 0xe0, 0x9c, 0x63, 0xd5, 0x2f, 0x1f,
+ 0x04, 0x57, 0x0c, 0xae, 0xa1, 0x42, 0xfd, 0x9c,
+ 0xd9, 0x42, 0x04, 0x3b, 0x11, 0xf8, 0xe3, 0xbd,
+ 0xcf, 0x50, 0x00, 0x7a, 0xe1, 0x6c, 0xf8, 0x86,
+ 0x90, 0x13, 0x04, 0x1e, 0x92, 0xcd, 0xd3, 0x28,
+ 0x0b, 0xa4, 0xb5, 0x1f, 0xbb, 0xd4, 0x05, 0x82,
+ 0xed, 0x75, 0x02, 0x19, 0xe2, 0x61, 0xa6, 0x95,
+ 0x09, 0x56, 0x74, 0x85, 0x5a, 0xac, 0xeb, 0x52,
+ 0x0a, 0xda, 0xff, 0x9e, 0x7e, 0x90, 0x84, 0x80,
+ 0xa3, 0x9c, 0xdc, 0xf9, 0x00, 0x46, 0x2d, 0x91,
+ 0x71, 0x96, 0x0f, 0xfe, 0x55, 0xd3, 0xac, 0x49,
+ 0xe8, 0xc9, 0x81, 0x34, 0x1b, 0xbd, 0x2e, 0xfb,
+ 0xcc, 0x25, 0x2a, 0x4c, 0x18, 0xa4, 0xf3, 0xb7,
+ 0xc8, 0x4c, 0xce, 0x42, 0xce, 0x70, 0xa2, 0x08,
+ 0xc8, 0x4d, 0x26, 0x30, 0xa7, 0xab, 0xfb, 0xe7,
+ 0x2d, 0x62, 0x71, 0xe7, 0x5b, 0x9f, 0xf1, 0xc9,
+ 0x71, 0xd2, 0x0e, 0xb3, 0xdb, 0xd7, 0x63, 0xf1,
+ 0xe0, 0x4d, 0x83, 0x4e, 0xaa, 0x69, 0x2d, 0x2e,
+ 0x40, 0x01, 0xbb, 0xf4, 0x73, 0x0a, 0x3e, 0x3f,
+ 0xda, 0x97, 0x11, 0xae, 0x38, 0x65, 0x24, 0xd9,
+ 0x1c, 0x63, 0xbe, 0x0e, 0x51, 0x6d, 0x00, 0xd5,
+ 0xc6, 0x14, 0x1f, 0xcc, 0xf6, 0xc5, 0x39, 0xf3,
+ 0x51, 0x8e, 0x18, 0x00, 0x49, 0x86, 0x5b, 0xe1,
+ 0x6b, 0x69, 0xca, 0xe1, 0xf8, 0xcb, 0x7f, 0xdc,
+ 0x47, 0x4b, 0x38, 0xf7, 0xee, 0x56, 0xcb, 0xe7,
+ 0xd8, 0xa8, 0x9d, 0x9b, 0xa9, 0x9b, 0x65, 0xd5,
+ 0x26, 0x5a, 0xef, 0x32, 0xaa, 0x62, 0x42, 0x6b,
+ 0x10, 0xe6, 0xd7, 0x5b, 0xb8, 0x67, 0x7e, 0xc4,
+ 0x4f, 0x75, 0x5b, 0xbc, 0x28, 0x06, 0xfd, 0x2b,
+ 0x4e, 0x04, 0xbd, 0xf5, 0xd4, 0x42, 0x59, 0xdb,
+ 0xea, 0xa4, 0x2b, 0x6f, 0x56, 0x3d, 0xf7, 0xaa,
+ 0x75, 0x06,
+ };
+ char cert_json[] = {
+ "{\"_type\":\"Certificate\",\"tbsCertificate\":{\"_type\":\"TBSCertificate"
+ "\",\"_save\":\"30820376A00302010202146A0597BA71D7E6D3AC0EDC9EDC95A15"
+ "B998DE40A300D06092A864886F70D01010B05003055310B30090603550406130"
+ "24348311E301C060355040A131553544D6963726F656C656374726F6E6963732"
+ "04E56312630240603550403131D53544D2054504D20454B20496E7465726D656"
+ "469617465204341203035301E170D3138313231343030303030305A170D32383"
+ "13231343030303030305A300030820122300D06092A864886F70D01010105000"
+ "382010F003082010A0282010100CC14EB27A78CEB0EA486FA2DF7835F5FA8E90"
+ "5B097012B5BDE50380C355B1A2A721BBC3D08DD21796CDB239FA95310651B1B5"
+ "6FD2CFE53C87352EBD996E33256160404CE9302A08066801E786A2F86E181F94"
+ "9966F492A85B58EAA4A6A8CB3697551BB236E87CC7BF8EC1347871C91E15437E"
+ "8F266BF1EA5EB271FDCF374D8B47DF8BCE89E1FAD61C2A088CB4036B359CB72A"
+ "294973FEDCCF0C340AFFD14B64F041165581ACA34147C1C75617047058F7ED7D"
+ "603E032508094FA73E8B9153DA3BF255D2CBBC5DF301BA8F74D198BEBCE86040"
+ "FC1D2927C7657414490D802F482F3EBF2DE35EE149A1A6DE8D16891FBFBA02A1"
+ "8AFE59F9D6F149744E5F0D559B10203010001A38201A9308201A5301F0603551"
+ "D230418301680141ADB994AB58BE57A0CC9B900E7851E1A43C08660304206035"
+ "51D20043B303930370604551D2000302F302D06082B060105050702011621687"
+ "474703A2F2F7777772E73742E636F6D2F54504D2F7265706F7369746F72792F3"
+ "0590603551D110101FF044F304DA44B304931163014060567810502010C0B696"
+ "43A353335343444323031173015060567810502020C0C5354333348545048414"
+ "8433031163014060567810502030C0B69643A303034393030303830670603551"
+ "D090460305E301706056781050210310E300C0C03322E300201000202008A304"
+ "306056781050212313A30380201000101FFA0030A0101A1030A0100A2030A010"
+ "0A310300E1603332E310A01040A01020101FFA40F300D16053134302D320A010"
+ "2010100300E0603551D0F0101FF040403020520300C0603551D130101FF04023"
+ "00030100603551D250409300706056781050801304A06082B060105050701010"
+ "43E303C303A06082B06010505073002862E687474703A2F2F7365637572652E6"
+ "76C6F62616C7369676E2E636F6D2F73746D74706D656B696E7430352E637274\""
+ ",\"version\":\"rfc3280_version_3\",\"serialNumber\":\"6A0597BA71D7E6D3A"
+ "C0EDC9EDC95A15B998DE40A\",\"signature\":{\"_type\":\"AlgorithmIdentifi"
+ "er\",\"algorithm\":{\"_type\":\"OBJECT IDENTIFIER\",\"oid\":\"1.2.840.1135"
+ "49.1.1.11\",\"components\":[1,2,840,113549,1,1,11],\"name\":\"id-pkcs1"
+ "-sha256WithRSAEncryption\"},\"parameters\":\"0500\"},\"issuer\":{\"_choi"
+ "ce\":\"rdnSequence\",\"value\":[[{\"_type\":\"AttributeTypeAndValue\",\"ty"
+ "pe\":{\"_type\":\"OBJECT IDENTIFIER\",\"oid\":\"2.5.4.6\",\"components\":[2"
+ ",5,4,6],\"name\":\"id-at-countryName\"},\"value\":{\"_choice\":\"printabl"
+ "eString\",\"value\":\"CH\"}}],[{\"_type\":\"AttributeTypeAndValue\",\"type"
+ "\":{\"_type\":\"OBJECT IDENTIFIER\",\"oid\":\"2.5.4.10\",\"components\":[2,"
+ "5,4,10],\"name\":\"id-at-organizationName\"},\"value\":{\"_choice\":\"pri"
+ "ntableString\",\"value\":\"STMicroelectronics NV\"}}],[{\"_type\":\"Attr"
+ "ibuteTypeAndValue\",\"type\":{\"_type\":\"OBJECT IDENTIFIER\",\"oid\":\"2."
+ "5.4.3\",\"components\":[2,5,4,3],\"name\":\"id-at-commonName\"},\"value\""
+ ":{\"_choice\":\"printableString\",\"value\":\"STM TPM EK Intermediate C"
+ "A 05\"}}]]},\"validity\":{\"_type\":\"Validity\",\"notBefore\":{\"_choice\""
+ ":\"utcTime\",\"value\":\"2018-12-14T00:00:00Z\"},\"notAfter\":{\"_choice\""
+ ":\"utcTime\",\"value\":\"2028-12-14T00:00:00Z\"}},\"subject\":{\"_choice\""
+ ":\"rdnSequence\",\"value\":[]},\"subjectPublicKeyInfo\":{\"_type\":\"Subj"
+ "ectPublicKeyInfo\",\"algorithm\":{\"_type\":\"AlgorithmIdentifier\",\"al"
+ "gorithm\":{\"_type\":\"OBJECT IDENTIFIER\",\"oid\":\"1.2.840.113549.1.1."
+ "1\",\"components\":[1,2,840,113549,1,1,1],\"name\":\"id-pkcs1-rsaEncry"
+ "ption\"},\"parameters\":\"0500\"},\"subjectPublicKey\":\"2160:3082010A02"
+ "82010100CC14EB27A78CEB0EA486FA2DF7835F5FA8E905B097012B5BDE50380C"
+ "355B1A2A721BBC3D08DD21796CDB239FA95310651B1B56FD2CFE53C87352EBD9"
+ "96E33256160404CE9302A08066801E786A2F86E181F949966F492A85B58EAA4A"
+ "6A8CB3697551BB236E87CC7BF8EC1347871C91E15437E8F266BF1EA5EB271FDC"
+ "F374D8B47DF8BCE89E1FAD61C2A088CB4036B359CB72A294973FEDCCF0C340AF"
+ "FD14B64F041165581ACA34147C1C75617047058F7ED7D603E032508094FA73E8"
+ "B9153DA3BF255D2CBBC5DF301BA8F74D198BEBCE86040FC1D2927C7657414490"
+ "D802F482F3EBF2DE35EE149A1A6DE8D16891FBFBA02A18AFE59F9D6F149744E5"
+ "F0D559B10203010001\"},\"issuerUniqueID\":null,\"subjectUniqueID\":nul"
+ "l,\"extensions\":[{\"_type\":\"Extension\",\"extnID\":{\"_type\":\"OBJECT I"
+ "DENTIFIER\",\"oid\":\"2.5.29.35\",\"components\":[2,5,29,35],\"name\":\"id"
+ "-x509-ce-authorityKeyIdentifier\"},\"critical\":false,\"extnValue\":\""
+ "301680141ADB994AB58BE57A0CC9B900E7851E1A43C08660\",\"_extnValue_ch"
+ "oice\":\"ext-AuthorityKeyIdentifier\",\"_extnValue\":{\"_type\":\"Author"
+ "ityKeyIdentifier\",\"keyIdentifier\":\"1ADB994AB58BE57A0CC9B900E7851"
+ "E1A43C08660\",\"authorityCertIssuer\":null,\"authorityCertSerialNumb"
+ "er\":null}},{\"_type\":\"Extension\",\"extnID\":{\"_type\":\"OBJECT IDENTI"
+ "FIER\",\"oid\":\"2.5.29.32\",\"components\":[2,5,29,32],\"name\":\"id-x509"
+ "-ce-certificatePolicies\"},\"critical\":false,\"extnValue\":\"30393037"
+ "0604551D2000302F302D06082B060105050702011621687474703A2F2F777777"
+ "2E73742E636F6D2F54504D2F7265706F7369746F72792F\",\"_extnValue_choi"
+ "ce\":\"ext-CertificatePolicies\",\"_extnValue\":[{\"_type\":\"PolicyInfo"
+ "rmation\",\"policyIdentifier\":{\"_type\":\"OBJECT IDENTIFIER\",\"oid\":\""
+ "2.5.29.32.0\",\"components\":[2,5,29,32,0],\"name\":\"id-x509-ce-certi"
+ "ficatePolicies-anyPolicy\"},\"policyQualifiers\":[{\"_type\":\"PolicyQ"
+ "ualifierInfo\",\"policyQualifierId\":{\"_type\":\"OBJECT IDENTIFIER\",\""
+ "oid\":\"1.3.6.1.5.5.7.2.1\",\"components\":[1,3,6,1,5,5,7,2,1],\"name\""
+ ":\"id-pkix-qt-cps\"},\"qualifier\":\"1621687474703A2F2F7777772E73742E"
+ "636F6D2F54504D2F7265706F7369746F72792F\",\"_qualifier_choice\":\"pq-"
+ "CPS\"}]}]},{\"_type\":\"Extension\",\"extnID\":{\"_type\":\"OBJECT IDENTIF"
+ "IER\",\"oid\":\"2.5.29.17\",\"components\":[2,5,29,17],\"name\":\"id-x509-"
+ "ce-subjectAltName\"},\"critical\":true,\"extnValue\":\"304DA44B3049311"
+ "63014060567810502010C0B69643A35333534344432303117301506056781050"
+ "2020C0C53543333485450484148433031163014060567810502030C0B69643A3"
+ "030343930303038\",\"_extnValue_choice\":\"ext-SubjectAltName\",\"_extn"
+ "Value\":[{\"_choice\":\"directoryName\",\"value\":{\"_choice\":\"rdnSequen"
+ "ce\",\"value\":[[{\"_type\":\"AttributeTypeAndValue\",\"type\":{\"_type\":\""
+ "OBJECT IDENTIFIER\",\"oid\":\"2.23.133.2.1\",\"components\":[2,23,133,2"
+ ",1],\"name\":\"tcg-at-tpmManufacturer\"},\"value\":{\"_choice\":\"utf8Str"
+ "ing\",\"value\":\"id:53544D20\"}}],[{\"_type\":\"AttributeTypeAndValue\","
+ "\"type\":{\"_type\":\"OBJECT IDENTIFIER\",\"oid\":\"2.23.133.2.2\",\"compon"
+ "ents\":[2,23,133,2,2],\"name\":\"tcg-at-tpmModel\"},\"value\":{\"_choice"
+ "\":\"utf8String\",\"value\":\"ST33HTPHAHC0\"}}],[{\"_type\":\"AttributeTyp"
+ "eAndValue\",\"type\":{\"_type\":\"OBJECT IDENTIFIER\",\"oid\":\"2.23.133.2"
+ ".3\",\"components\":[2,23,133,2,3],\"name\":\"tcg-at-tpmVersion\"},\"val"
+ "ue\":{\"_choice\":\"utf8String\",\"value\":\"id:00490008\"}}]]}}]},{\"_typ"
+ "e\":\"Extension\",\"extnID\":{\"_type\":\"OBJECT IDENTIFIER\",\"oid\":\"2.5."
+ "29.9\",\"components\":[2,5,29,9],\"name\":\"id-x509-ce-subjectDirector"
+ "yAttributes\"},\"critical\":false,\"extnValue\":\"305E3017060567810502"
+ "10310E300C0C03322E300201000202008A304306056781050212313A30380201"
+ "000101FFA0030A0101A1030A0100A2030A0100A310300E1603332E310A01040A"
+ "01020101FFA40F300D16053134302D320A0102010100\",\"_extnValue_choice"
+ "\":\"ext-SubjectDirectoryAttributes\",\"_extnValue\":[{\"_type\":\"Attri"
+ "buteSet\",\"type\":{\"_type\":\"OBJECT IDENTIFIER\",\"oid\":\"2.23.133.2.1"
+ "6\",\"components\":[2,23,133,2,16],\"name\":\"tcg-at-tpmSpecification\""
+ "},\"values\":[\"300C0C03322E300201000202008A\"],\"_values_choice\":\"at"
+ "-TPMSpecification\",\"_values\":[{\"_type\":\"TPMSpecification\",\"famil"
+ "y\":\"2.0\",\"level\":0,\"revision\":138}]},{\"_type\":\"AttributeSet\",\"ty"
+ "pe\":{\"_type\":\"OBJECT IDENTIFIER\",\"oid\":\"2.23.133.2.18\",\"componen"
+ "ts\":[2,23,133,2,18],\"name\":\"tcg-at-tpmSecurityAssertions\"},\"valu"
+ "es\":[\"30380201000101FFA0030A0101A1030A0100A2030A0100A310300E1603"
+ "332E310A01040A01020101FFA40F300D16053134302D320A0102010100\"],\"_v"
+ "alues_choice\":\"at-TPMSecurityAssertions\",\"_values\":[{\"_type\":\"TP"
+ "MSecurityAssertions\",\"version\":0,\"fieldUpgradable\":true,\"ekGener"
+ "ationType\":\"ekgt-injected\",\"ekGenerationLocation\":\"tpmManufactur"
+ "er\",\"ekCertificateGenerationLocation\":\"tpmManufacturer\",\"ccInfo\""
+ ":{\"_type\":\"CommonCriteriaMeasures\",\"version\":\"3.1\",\"assurancelev"
+ "el\":\"ealevel4\",\"evaluationStatus\":\"evaluationCompleted\",\"plus\":t"
+ "rue,\"strengthOfFunction\":null,\"profileOid\":null,\"profileUri\":nul"
+ "l,\"targetOid\":null,\"targetUri\":null},\"fipsLevel\":{\"_type\":\"FIPSL"
+ "evel\",\"version\":\"140-2\",\"level\":\"sllevel2\",\"plus\":false},\"iso900"
+ "0Certified\":false,\"iso9000Uri\":null}]}]},{\"_type\":\"Extension\",\"e"
+ "xtnID\":{\"_type\":\"OBJECT IDENTIFIER\",\"oid\":\"2.5.29.15\",\"component"
+ "s\":[2,5,29,15],\"name\":\"id-x509-ce-keyUsage\"},\"critical\":true,\"ex"
+ "tnValue\":\"03020520\",\"_extnValue_choice\":\"ext-KeyUsage\",\"_extnVal"
+ "ue\":[\"keyEncipherment\"]},{\"_type\":\"Extension\",\"extnID\":{\"_type\":"
+ "\"OBJECT IDENTIFIER\",\"oid\":\"2.5.29.19\",\"components\":[2,5,29,19],\""
+ "name\":\"id-x509-ce-basicConstraints\"},\"critical\":true,\"extnValue\""
+ ":\"3000\",\"_extnValue_choice\":\"ext-BasicConstraints\",\"_extnValue\":"
+ "{\"_type\":\"BasicConstraints\",\"cA\":false,\"pathLenConstraint\":null}"
+ "},{\"_type\":\"Extension\",\"extnID\":{\"_type\":\"OBJECT IDENTIFIER\",\"oi"
+ "d\":\"2.5.29.37\",\"components\":[2,5,29,37],\"name\":\"id-x509-ce-extKe"
+ "yUsage\"},\"critical\":false,\"extnValue\":\"300706056781050801\",\"_ext"
+ "nValue_choice\":\"ext-ExtKeyUsage\",\"_extnValue\":[{\"_type\":\"OBJECT "
+ "IDENTIFIER\",\"oid\":\"2.23.133.8.1\",\"components\":[2,23,133,8,1],\"na"
+ "me\":\"tcg-kp-EKCertificate\"}]},{\"_type\":\"Extension\",\"extnID\":{\"_t"
+ "ype\":\"OBJECT IDENTIFIER\",\"oid\":\"1.3.6.1.5.5.7.1.1\",\"components\":"
+ "[1,3,6,1,5,5,7,1,1],\"name\":\"id-pkix-pe-authorityInfoAccess\"},\"cr"
+ "itical\":false,\"extnValue\":\"303C303A06082B06010505073002862E68747"
+ "4703A2F2F7365637572652E676C6F62616C7369676E2E636F6D2F73746D74706"
+ "D656B696E7430352E637274\",\"_extnValue_choice\":\"ext-AuthorityInfoA"
+ "ccess\",\"_extnValue\":[{\"_type\":\"AccessDescription\",\"accessMethod\""
+ ":{\"_type\":\"OBJECT IDENTIFIER\",\"oid\":\"1.3.6.1.5.5.7.48.2\",\"compon"
+ "ents\":[1,3,6,1,5,5,7,48,2],\"name\":\"id-pkix-ad-caIssuers\"},\"acces"
+ "sLocation\":{\"_choice\":\"uniformResourceIdentifier\",\"value\":\"http:"
+ "//secure.globalsign.com/stmtpmekint05.crt\"}}]}]},\"signatureAlgor"
+ "ithm\":{\"_type\":\"AlgorithmIdentifier\",\"algorithm\":{\"_type\":\"OBJEC"
+ "T IDENTIFIER\",\"oid\":\"1.2.840.113549.1.1.11\",\"components\":[1,2,84"
+ "0,113549,1,1,11],\"name\":\"id-pkcs1-sha256WithRSAEncryption\"},\"par"
+ "ameters\":\"0500\"},\"signatureValue\":\"2048:3D4C381E5B4F1BCBE09C63D5"
+ "2F1F04570CAEA142FD9CD942043B11F8E3BDCF50007AE16CF8869013041E92CD"
+ "D3280BA4B51FBBD40582ED750219E261A695095674855AACEB520ADAFF9E7E90"
+ "8480A39CDCF900462D9171960FFE55D3AC49E8C981341BBD2EFBCC252A4C18A4"
+ "F3B7C84CCE42CE70A208C84D2630A7ABFBE72D6271E75B9FF1C971D20EB3DBD7"
+ "63F1E04D834EAA692D2E4001BBF4730A3E3FDA9711AE386524D91C63BE0E516D"
+ "00D5C6141FCCF6C539F3518E180049865BE16B69CAE1F8CB7FDC474B38F7EE56"
+ "CBE7D8A89D9BA99B65D5265AEF32AA62426B10E6D75BB8677EC44F755BBC2806"
+ "FD2B4E04BDF5D44259DBEAA42B6F563DF7AA7506\""
+ "}"
+ };
+ heim_octet_string os;
+ Certificate c0, c1;
+ size_t i, nknown, size;
+ char *s;
+ int ret;
+
+ /*
+ * Test automatic decoding of open types.
+ *
+ * Decode a value that has plenty of open types with values of known
+ * alternatives in them, then check that we got what we wanted.
+ */
+ ret = decode_Certificate(encoded_sample, sizeof(encoded_sample),
+ &c0, &size);
+ if (ret)
+ return 1;
+ if (size != sizeof(encoded_sample))
+ return 1;
+
+ s = print_Certificate(&c0, 0);
+ if (!s)
+ return 1;
+ if (strcmp(s, cert_json) != 0)
+ return 1;
+ free(s);
+
+ ret = copy_Certificate(&c0, &c1);
+ if (ret)
+ return 1;
+
+ if (!c0.tbsCertificate.extensions || !c1.tbsCertificate.extensions)
+ return 1;
+ if (!c0.tbsCertificate.extensions->len ||
+ c0.tbsCertificate.extensions->len != c1.tbsCertificate.extensions->len)
+ return 1;
+ for (i = nknown = 0; i < c0.tbsCertificate.extensions->len; i++) {
+ if (c0.tbsCertificate.extensions->val[i]._ioschoice_extnValue.element !=
+ c1.tbsCertificate.extensions->val[i]._ioschoice_extnValue.element)
+ return 1;
+ if (c0.tbsCertificate.extensions->val[i]._ioschoice_extnValue.element) {
+#if 0
+ fprintf(stderr, "extension %llu known %u\n",
+ (unsigned long long)i,
+ c0.tbsCertificate.extensions->val[i]._ioschoice_extnValue._element);
+#endif
+ nknown++;
+ }
+ }
+ if (!nknown)
+ return 1;
+
+
+ /*
+ * Check that this round trips. But note that this attempt to encode will
+ * ignore the automatically decoded open type values from above because
+ * their encodings are still present.
+ */
+ ASN1_MALLOC_ENCODE(Certificate, os.data, os.length, &c1, &size, ret);
+ if (ret)
+ return 1;
+ if (os.length != size || size != sizeof(encoded_sample))
+ return 1;
+ if (memcmp(os.data, encoded_sample, os.length) != 0)
+ return 1;
+ der_free_octet_string(&os);
+
+ /*
+ * Test automatic encoding of open types by clearing the encoding of one
+ * such open type value, forcing the encoder to encode the value from
+ * before.
+ */
+ der_free_octet_string(&c0.tbsCertificate.extensions->val[0].extnValue);
+ der_free_oid(&c0.tbsCertificate.extensions->val[0].extnID);
+
+ ASN1_MALLOC_ENCODE(Certificate, os.data, os.length, &c0, &size, ret);
+ if (ret)
+ return 1;
+ if (os.length != size || size != sizeof(encoded_sample))
+ return 1;
+ if (memcmp(os.data, encoded_sample, os.length) != 0)
+ return 1;
+ der_free_octet_string(&os);
+
+ /*
+ * Repeat, but with the copy, as this will test that copying data
+ * structures with decoded open types in them also copies those.
+ */
+ der_free_octet_string(&c1.tbsCertificate.extensions->val[0].extnValue);
+ der_free_oid(&c1.tbsCertificate.extensions->val[0].extnID);
+
+ ASN1_MALLOC_ENCODE(Certificate, os.data, os.length, &c1, &size, ret);
+ if (ret)
+ return 1;
+ if (os.length != size || size != sizeof(encoded_sample))
+ return 1;
+ if (memcmp(os.data, encoded_sample, os.length) != 0)
+ return 1;
+ der_free_octet_string(&os);
+
+ free_Certificate(&c0);
+ free_Certificate(&c1);
+ return 0;
+}
+#endif
+
+int
+main(int argc, char **argv)
+{
+ int ret = 0;
+
+#define DO_ONE(t) if (t()) { fprintf(stderr, "%s() failed!\n", #t); ret++; }
+ DO_ONE(test_principal);
+ DO_ONE(test_authenticator);
+ DO_ONE(test_krb_error);
+ DO_ONE(test_Name);
+ DO_ONE(test_bit_string);
+ DO_ONE(test_bit_string_rfc1510);
+ DO_ONE(test_time);
+ DO_ONE(test_cert);
+
+ DO_ONE(check_tag_length);
+ DO_ONE(check_tag_length64);
+ DO_ONE(check_tag_length64s);
+ DO_ONE(test_large_tag);
+ DO_ONE(test_choice);
+
+ DO_ONE(test_implicit);
+
+ DO_ONE(test_taglessalloc);
+ DO_ONE(test_optional);
+
+ DO_ONE(check_fail_largetag);
+ DO_ONE(check_fail_sequence);
+ DO_ONE(check_fail_choice);
+ DO_ONE(check_fail_Ticket);
+
+ DO_ONE(check_seq);
+ DO_ONE(check_seq_of_size);
+ DO_ONE(test_SignedData);
+
+ DO_ONE(check_TESTMechTypeList);
+ DO_ONE(test_seq4);
+ DO_ONE(test_seqof5);
+
+ DO_ONE(test_x690sample);
+
+ DO_ONE(test_default);
+
+ DO_ONE(test_decorated_choice);
+ DO_ONE(test_decorated);
+
+#if ASN1_IOS_SUPPORTED
+ DO_ONE(test_ios);
+#endif
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/asn1/check-gen.h b/third_party/heimdal/lib/asn1/check-gen.h
new file mode 100644
index 0000000..df8c474
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/check-gen.h
@@ -0,0 +1,9 @@
+#ifndef _CHECK_GEN_H
+#define _CHECK_GEN_H
+typedef struct my_vers_s {
+ int v;
+} my_vers;
+
+int my_copy_vers(const my_vers *, my_vers *);
+void my_free_vers(my_vers *);
+#endif /* _CHECK_GEN_H */
diff --git a/third_party/heimdal/lib/asn1/check-template.c b/third_party/heimdal/lib/asn1/check-template.c
new file mode 100644
index 0000000..ef5bd69
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/check-template.c
@@ -0,0 +1,532 @@
+/*
+ * Copyright (c) 1999 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdio.h>
+#include <string.h>
+#include <err.h>
+#include <roken.h>
+
+#include <asn1-common.h>
+#include <asn1_err.h>
+#include <der.h>
+#include <test_asn1.h>
+
+#include "check-common.h"
+#include "der_locl.h"
+
+int
+my_copy_vers(const my_vers *from, my_vers *to)
+{
+ *to = *from;
+ return 0;
+}
+
+void
+my_free_vers(my_vers *v)
+{
+ v->v = -1;
+}
+
+static int
+cmp_dummy (void *a, void *b)
+{
+ return 0;
+}
+
+static int
+test_uint64(void)
+{
+ struct test_case tests[] = {
+ { NULL, 3, "\x02\x01\x00", "uint64 0" },
+ { NULL, 7, "\x02\x05\x01\xff\xff\xff\xff", "uint64 1" },
+ { NULL, 7, "\x02\x05\x02\x00\x00\x00\x00", "uint64 2" },
+ { NULL, 9, "\x02\x07\x7f\xff\xff\xff\xff\xff\xff", "uint64 3" },
+ { NULL, 10, "\x02\x08\x00\x80\x00\x00\x00\x00\x00\x00", "uint64 4" },
+ { NULL, 10, "\x02\x08\x7f\xff\xff\xff\xff\xff\xff\xff", "uint64 5" },
+ { NULL, 11, "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xff", "uint64 6" }
+ };
+
+ size_t i;
+ int ret = 0, ntests = sizeof(tests) / sizeof(*tests);
+ TESTuint64 values[] = { 0, 8589934591LL, 8589934592LL,
+ 36028797018963967LL, 36028797018963968LL,
+ 9223372036854775807LL, 18446744073709551615ULL };
+
+ for (i = 0; i < ntests; i++)
+ tests[i].val = &values[i];
+
+ if (sizeof(TESTuint64) != sizeof(uint64_t)) {
+ ret += 1;
+ printf("sizeof(TESTuint64) %d != sizeof(uint64_t) %d\n",
+ (int)sizeof(TESTuint64), (int)sizeof(uint64_t));
+ }
+
+ ret += generic_test (tests, ntests, sizeof(TESTuint64),
+ (generic_encode)encode_TESTuint64,
+ (generic_length)length_TESTuint64,
+ (generic_decode)decode_TESTuint64,
+ (generic_free)free_TESTuint64,
+ cmp_dummy,
+ NULL);
+ return ret;
+}
+
+static int
+test_seqofseq(void)
+{
+ struct test_case tests[] = {
+ { NULL, 2,
+ "\x30\x00",
+ "seqofseq 0" },
+ { NULL, 9,
+ "\x30\x07\x30\x05\xa0\x03\x02\x01\x00",
+ "seqofseq 1" },
+ { NULL, 16,
+ "\x30\x0e\x30\x05\xa0\x03\x02\x01\x00\x30\x05\xa0\x03\x02\x01\x01",
+ "seqofseq 2" }
+ };
+
+ int ret = 0, ntests = sizeof(tests) / sizeof(*tests);
+ TESTSeqOfSeq c0, c1, c2;
+ struct TESTSeqOfSeq_val i[2];
+
+ i[0].zero = 0;
+ i[1].zero = 1;
+
+ c0.len = 0;
+ c0.val = NULL;
+ tests[0].val = &c0;
+
+ c1.len = 1;
+ c1.val = i;
+ tests[1].val = &c1;
+
+ c2.len = 2;
+ c2.val = i;
+ tests[2].val = &c2;
+
+ ret += generic_test (tests, ntests, sizeof(TESTSeqOfSeq),
+ (generic_encode)encode_TESTSeqOfSeq,
+ (generic_length)length_TESTSeqOfSeq,
+ (generic_decode)decode_TESTSeqOfSeq,
+ (generic_free)free_TESTSeqOfSeq,
+ cmp_dummy,
+ NULL);
+ return ret;
+}
+
+static int
+test_seqofseq2(void)
+{
+ struct test_case tests[] = {
+ { NULL, 2,
+ "\x30\x00",
+ "seqofseq2 0" },
+ { NULL, 11,
+ "\x30\x09\x30\x07\xa0\x05\x1b\x03\x65\x74\x74",
+ "seqofseq2 1" },
+ { NULL, 21,
+ "\x30\x13\x30\x07\xa0\x05\x1b\x03\x65\x74\x74\x30\x08\xa0"
+ "\x06\x1b\x04\x74\x76\x61\x61",
+ "seqofseq2 2" }
+ };
+
+ int ret = 0, ntests = sizeof(tests) / sizeof(*tests);
+ TESTSeqOfSeq2 c0, c1, c2;
+ struct TESTSeqOfSeq2_val i[2];
+
+ i[0].string = "ett";
+ i[1].string = "tvaa";
+
+ c0.len = 0;
+ c0.val = NULL;
+ tests[0].val = &c0;
+
+ c1.len = 1;
+ c1.val = i;
+ tests[1].val = &c1;
+
+ c2.len = 2;
+ c2.val = i;
+ tests[2].val = &c2;
+
+ ret += generic_test (tests, ntests, sizeof(TESTSeqOfSeq2),
+ (generic_encode)encode_TESTSeqOfSeq2,
+ (generic_length)length_TESTSeqOfSeq2,
+ (generic_decode)decode_TESTSeqOfSeq2,
+ (generic_free)free_TESTSeqOfSeq2,
+ cmp_dummy,
+ NULL);
+ return ret;
+}
+
+static int
+test_seqof2(void)
+{
+ struct test_case tests[] = {
+ { NULL, 4,
+ "\x30\x02\x30\x00",
+ "seqof2 1" },
+ { NULL, 9,
+ "\x30\x07\x30\x05\x1b\x03\x66\x6f\x6f",
+ "seqof2 2" },
+ { NULL, 14,
+ "\x30\x0c\x30\x0a\x1b\x03\x66\x6f\x6f\x1b\x03\x62\x61\x72",
+ "seqof2 3" }
+ };
+
+ int ret = 0, ntests = sizeof(tests) / sizeof(*tests);
+ TESTSeqOf2 c0, c1, c2;
+ heim_general_string i[2];
+
+ i[0] = "foo";
+ i[1] = "bar";
+
+ c0.strings.val = NULL;
+ c0.strings.len = 0;
+ tests[0].val = &c0;
+
+ c1.strings.len = 1;
+ c1.strings.val = i;
+ tests[1].val = &c1;
+
+ c2.strings.len = 2;
+ c2.strings.val = i;
+ tests[2].val = &c2;
+
+ ret += generic_test (tests, ntests, sizeof(TESTSeqOf2),
+ (generic_encode)encode_TESTSeqOf2,
+ (generic_length)length_TESTSeqOf2,
+ (generic_decode)decode_TESTSeqOf2,
+ (generic_free)free_TESTSeqOf2,
+ cmp_dummy,
+ NULL);
+ return ret;
+}
+
+static int
+test_seqof3(void)
+{
+ struct test_case tests[] = {
+ { NULL, 2,
+ "\x30\x00",
+ "seqof3 0" },
+ { NULL, 4,
+ "\x30\x02\x30\x00",
+ "seqof3 1" },
+ { NULL, 9,
+ "\x30\x07\x30\x05\x1b\x03\x66\x6f\x6f",
+ "seqof3 2" },
+ { NULL, 14,
+ "\x30\x0c\x30\x0a\x1b\x03\x66\x6f\x6f\x1b\x03\x62\x61\x72",
+ "seqof3 3" }
+ };
+
+ int ret = 0, ntests = sizeof(tests) / sizeof(*tests);
+ TESTSeqOf3 c0, c1, c2, c3;
+ struct TESTSeqOf3_strings s1, s2, s3;
+ heim_general_string i[2];
+
+ i[0] = "foo";
+ i[1] = "bar";
+
+ c0.strings = NULL;
+ tests[0].val = &c0;
+
+ s1.val = NULL;
+ s1.len = 0;
+ c1.strings = &s1;
+ tests[1].val = &c1;
+
+ s2.len = 1;
+ s2.val = i;
+ c2.strings = &s2;
+ tests[2].val = &c2;
+
+ s3.len = 2;
+ s3.val = i;
+ c3.strings = &s3;
+ tests[3].val = &c3;
+
+ ret += generic_test (tests, ntests, sizeof(TESTSeqOf3),
+ (generic_encode)encode_TESTSeqOf3,
+ (generic_length)length_TESTSeqOf3,
+ (generic_decode)decode_TESTSeqOf3,
+ (generic_free)free_TESTSeqOf3,
+ cmp_dummy,
+ NULL);
+ return ret;
+}
+
+
+static int
+test_seqof4(void)
+{
+ struct test_case tests[] = {
+ { NULL, 2,
+ "\x30\x00",
+ "seq4 0" },
+ { NULL, 4,
+ "\x30\x02" "\xa1\x00",
+ "seq4 1" },
+ { NULL, 8,
+ "\x30\x06" "\xa0\x02\x30\x00" "\xa1\x00",
+ "seq4 2" },
+ { NULL, 2 + (2 + 0x18) + (2 + 0x27) + (2 + 0x31),
+ "\x30\x76" /* 2 SEQ */
+ "\xa0\x18\x30\x16" /* 4 [0] SEQ */
+ "\x30\x14" /* 2 SEQ */
+ "\x04\x00" /* 2 OCTET-STRING */
+ "\x04\x02\x01\x02" /* 4 OCTET-STRING */
+ "\x02\x01\x01" /* 3 INT */
+ "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xff"
+ /* 11 INT */
+ "\xa1\x27" /* 2 [1] IMPL SEQ */
+ "\x30\x25" /* 2 SEQ */
+ "\x02\x01\x01" /* 3 INT */
+ "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xff"
+ /* 11 INT */
+ "\x02\x09\x00\x80\x00\x00\x00\x00\x00\x00\x00"
+ /* 11 INT */
+ "\x04\x00" /* 2 OCTET-STRING */
+ "\x04\x02\x01\x02" /* 4 OCTET-STRING */
+ "\x04\x04\x00\x01\x02\x03" /* 6 OCTET-STRING */
+ "\xa2\x31" /* 2 [2] IMPL SEQ */
+ "\x30\x2f" /* 2 SEQ */
+ "\x04\x00" /* 2 OCTET-STRING */
+ "\x02\x01\x01" /* 3 INT */
+ "\x04\x02\x01\x02" /* 4 OCTET-STRING */
+ "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xff"
+ /* 11 INT */
+ "\x04\x04\x00\x01\x02\x03" /* 6 OCTET-STRING */
+ "\x02\x09\x00\x80\x00\x00\x00\x00\x00\x00\x00"
+ /* 11 INT */
+ "\x04\x01\x00" /* 3 OCTET-STRING */
+ "\x02\x05\x01\x00\x00\x00\x00", /* 7 INT */
+ "seq4 3" },
+ };
+
+ int ret = 0, ntests = sizeof(tests) / sizeof(*tests);
+ TESTSeqOf4 c[4];
+ struct TESTSeqOf4_b1 b1[4];
+ struct TESTSeqOf4_b2 b2[4];
+ struct TESTSeqOf4_b3 b3[4];
+ struct TESTSeqOf4_b1_val b1val[4];
+ struct TESTSeqOf4_b2_val b2val[4];
+ struct TESTSeqOf4_b3_val b3val[4];
+
+ c[0].b1 = NULL;
+ c[0].b2 = NULL;
+ c[0].b3 = NULL;
+ tests[0].val = &c[0];
+
+ b2[1].len = 0;
+ b2[1].val = NULL;
+ c[1].b1 = NULL;
+ c[1].b2 = &b2[1];
+ c[1].b3 = NULL;
+ tests[1].val = &c[1];
+
+ b1[2].len = 0;
+ b1[2].val = NULL;
+ b2[2].len = 0;
+ b2[2].val = NULL;
+ c[2].b1 = &b1[2];
+ c[2].b2 = &b2[2];
+ c[2].b3 = NULL;
+ tests[2].val = &c[2];
+
+ b1val[3].s1.data = "";
+ b1val[3].s1.length = 0;
+ b1val[3].u1 = 1LL;
+ b1val[3].s2.data = "\x01\x02";
+ b1val[3].s2.length = 2;
+ b1val[3].u2 = (TESTuint64)-1LL;
+
+ b2val[3].s1.data = "";
+ b2val[3].s1.length = 0;
+ b2val[3].u1 = 1LL;
+ b2val[3].s2.data = "\x01\x02";
+ b2val[3].s2.length = 2;
+ b2val[3].u2 = (TESTuint64)-1LL;
+ b2val[3].s3.data = "\x00\x01\x02\x03";
+ b2val[3].s3.length = 4;
+ b2val[3].u3 = 1ULL<<63;
+
+ b3val[3].s1.data = "";
+ b3val[3].s1.length = 0;
+ b3val[3].u1 = 1LL;
+ b3val[3].s2.data = "\x01\x02";
+ b3val[3].s2.length = 2;
+ b3val[3].u2 = (TESTuint64)-1LL;
+ b3val[3].s3.data = "\x00\x01\x02\x03";
+ b3val[3].s3.length = 4;
+ b3val[3].u3 = 1ULL<<63;
+ b3val[3].s4.data = "\x00";
+ b3val[3].s4.length = 1;
+ b3val[3].u4 = 1LL<<32;
+
+ b1[3].len = 1;
+ b1[3].val = &b1val[3];
+ b2[3].len = 1;
+ b2[3].val = &b2val[3];
+ b3[3].len = 1;
+ b3[3].val = &b3val[3];
+ c[3].b1 = &b1[3];
+ c[3].b2 = &b2[3];
+ c[3].b3 = &b3[3];
+ tests[3].val = &c[3];
+
+ ret += generic_test (tests, ntests, sizeof(TESTSeqOf4),
+ (generic_encode)encode_TESTSeqOf4,
+ (generic_length)length_TESTSeqOf4,
+ (generic_decode)decode_TESTSeqOf4,
+ (generic_free)free_TESTSeqOf4,
+ cmp_dummy,
+ NULL);
+ return ret;
+}
+
+static int
+cmp_test_seqof5 (void *a, void *b)
+{
+ TESTSeqOf5 *aval = a;
+ TESTSeqOf5 *bval = b;
+
+ IF_OPT_COMPARE(aval, bval, outer) {
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u0);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s0);
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u1);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s1);
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u2);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s2);
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u3);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s3);
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u4);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s4);
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u5);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s5);
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u6);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s6);
+ COMPARE_INTEGER(&aval->outer->inner, &bval->outer->inner, u7);
+ COMPARE_OCTET_STRING(&aval->outer->inner, &bval->outer->inner, s7);
+ }
+ return 0;
+}
+
+static int
+test_seqof5(void)
+{
+ struct test_case tests[] = {
+ { NULL, 2, "\x30\x00", "seq5 0" },
+ { NULL, 126,
+ "\x30\x7c" /* SEQ */
+ "\x30\x7a" /* SEQ */
+ "\x30\x78" /* SEQ */
+ "\x02\x01\x01" /* INT 1 */
+ "\x04\x06\x01\x01\x01\x01\x01\x01" /* "\0x1"x6 */
+ "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xfe" /* INT ~1 */
+ "\x04\x06\x02\x02\x02\x02\x02\x02" /* "\x02"x6 */
+ "\x02\x01\x02" /* INT 2 */
+ "\x04\x06\x03\x03\x03\x03\x03\x03" /* "\x03"x6 */
+ "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xfd" /* INT ~2 */
+ "\x04\x06\x04\x04\x04\x04\x04\x04" /* ... */
+ "\x02\x01\x03"
+ "\x04\x06\x05\x05\x05\x05\x05\x05"
+ "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xfc"
+ "\x04\x06\x06\x06\x06\x06\x06\x06"
+ "\x02\x01\x04"
+ "\x04\x06\x07\x07\x07\x07\x07\x07"
+ "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xfb"
+ "\x04\x06\x08\x08\x08\x08\x08\x08",
+ "seq5 1" },
+ };
+
+ int ret = 0, ntests = sizeof(tests) / sizeof(*tests);
+ TESTSeqOf5 c[2];
+ struct TESTSeqOf5_outer outer;
+ struct TESTSeqOf5_outer_inner inner;
+ TESTuint64 u[8];
+ heim_octet_string s[8];
+ int i;
+
+ c[0].outer = NULL;
+ tests[0].val = &c[0];
+
+ for (i = 0; i < 8; ++i) {
+ u[i] = (i&1) == 0 ? i/2+1 : ~(i/2+1);
+ s[i].data = memset(malloc(s[i].length = 6), i+1, 6);
+ }
+
+ inner.u0 = u[0]; inner.u1 = u[1]; inner.u2 = u[2]; inner.u3 = u[3];
+ inner.u4 = u[4]; inner.u5 = u[5]; inner.u6 = u[6]; inner.u7 = u[7];
+ inner.s0 = s[0]; inner.s1 = s[1]; inner.s2 = s[2]; inner.s3 = s[3];
+ inner.s4 = s[4]; inner.s5 = s[5]; inner.s6 = s[6]; inner.s7 = s[7];
+
+ outer.inner = inner;
+ c[1].outer = &outer;
+ tests[1].val = &c[1];
+
+ ret += generic_test (tests, ntests, sizeof(TESTSeqOf5),
+ (generic_encode)encode_TESTSeqOf5,
+ (generic_length)length_TESTSeqOf5,
+ (generic_decode)decode_TESTSeqOf5,
+ (generic_free)free_TESTSeqOf5,
+ cmp_test_seqof5,
+ NULL);
+
+ for (i = 0; i < 8; ++i)
+ free(s[i].data);
+
+ return ret;
+}
+
+int
+main(int argc, char **argv)
+{
+ int ret = 0;
+
+ ret += test_uint64();
+ ret += test_seqofseq();
+ ret += test_seqofseq2();
+ ret += test_seqof2();
+ ret += test_seqof3();
+ ret += test_seqof4();
+ ret += test_seqof5();
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/asn1/check-timegm.c b/third_party/heimdal/lib/asn1/check-timegm.c
new file mode 100644
index 0000000..13d3abc
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/check-timegm.c
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <der_locl.h>
+
+RCSID("$Id$");
+
+static int
+test_timegm(void)
+{
+ int ret = 0;
+ struct tm tm;
+ time_t t;
+
+ memset(&tm, 0, sizeof(tm));
+ tm.tm_year = 106;
+ tm.tm_mon = 9;
+ tm.tm_mday = 1;
+ tm.tm_hour = 10;
+ tm.tm_min = 3;
+
+ t = _der_timegm(&tm);
+ if (t != 1159696980)
+ ret += 1;
+
+ tm.tm_mday = 0;
+ t = _der_timegm(&tm);
+ if (t != -1)
+ ret += 1;
+
+ _der_gmtime(1159696980, &tm);
+ if (tm.tm_year != 106 ||
+ tm.tm_mon != 9 ||
+ tm.tm_mday != 1 ||
+ tm.tm_hour != 10 ||
+ tm.tm_min != 3 ||
+ tm.tm_sec != 0)
+ errx(1, "tmtime failes");
+
+ return ret;
+}
+
+int
+main(int argc, char **argv)
+{
+ int ret = 0;
+
+ ret += test_timegm();
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/asn1/cms.asn1 b/third_party/heimdal/lib/asn1/cms.asn1
new file mode 100644
index 0000000..ae547e5
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/cms.asn1
@@ -0,0 +1,149 @@
+-- From RFC 3369 --
+-- $Id$ --
+
+CMS DEFINITIONS ::= BEGIN
+
+IMPORTS CertificateSerialNumber, AlgorithmIdentifier, Name,
+ Attribute, Certificate, SubjectKeyIdentifier FROM rfc2459
+ HEIM_ANY FROM heim;
+
+id-pkcs7 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
+ us(840) rsadsi(113549) pkcs(1) pkcs7(7) }
+
+id-pkcs7-data OBJECT IDENTIFIER ::= { id-pkcs7 1 }
+id-pkcs7-signedData OBJECT IDENTIFIER ::= { id-pkcs7 2 }
+id-pkcs7-envelopedData OBJECT IDENTIFIER ::= { id-pkcs7 3 }
+id-pkcs7-signedAndEnvelopedData OBJECT IDENTIFIER ::= { id-pkcs7 4 }
+id-pkcs7-digestedData OBJECT IDENTIFIER ::= { id-pkcs7 5 }
+id-pkcs7-encryptedData OBJECT IDENTIFIER ::= { id-pkcs7 6 }
+
+CMSVersion ::= INTEGER {
+ cMSVersion-v0(0),
+ cMSVersion-v1(1),
+ cMSVersion-v2(2),
+ cMSVersion-v3(3),
+ cMSVersion-v4(4)
+}
+
+DigestAlgorithmIdentifier ::= AlgorithmIdentifier
+DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
+SignatureAlgorithmIdentifier ::= AlgorithmIdentifier
+
+ContentType ::= OBJECT IDENTIFIER
+MessageDigest ::= OCTET STRING
+
+ContentInfo ::= SEQUENCE {
+ contentType ContentType,
+ content [0] EXPLICIT HEIM_ANY OPTIONAL -- DEFINED BY contentType
+}
+
+EncapsulatedContentInfo ::= SEQUENCE {
+ eContentType ContentType,
+ eContent [0] EXPLICIT OCTET STRING OPTIONAL
+}
+
+CertificateSet ::= SET OF HEIM_ANY
+
+CertificateList ::= Certificate
+
+CertificateRevocationLists ::= SET OF CertificateList
+
+IssuerAndSerialNumber ::= SEQUENCE {
+ issuer Name,
+ serialNumber CertificateSerialNumber
+}
+
+-- RecipientIdentifier is same as SignerIdentifier,
+-- lets glue them togheter and save some bytes and share code for them
+
+CMSIdentifier ::= CHOICE {
+ issuerAndSerialNumber IssuerAndSerialNumber,
+ subjectKeyIdentifier [0] SubjectKeyIdentifier
+}
+
+SignerIdentifier ::= CMSIdentifier
+RecipientIdentifier ::= CMSIdentifier
+
+--- CMSAttributes are the combined UnsignedAttributes and SignedAttributes
+--- to store space and share code
+
+CMSAttributes ::= SET OF Attribute -- SIZE (1..MAX)
+
+SignatureValue ::= OCTET STRING
+
+SignerInfo ::= SEQUENCE {
+ version CMSVersion,
+ sid SignerIdentifier,
+ digestAlgorithm DigestAlgorithmIdentifier,
+ signedAttrs [0] IMPLICIT CMSAttributes OPTIONAL,
+ signatureAlgorithm SignatureAlgorithmIdentifier,
+ signature SignatureValue,
+ unsignedAttrs [1] IMPLICIT CMSAttributes OPTIONAL
+}
+
+SignerInfos ::= SET OF SignerInfo
+
+SignedData ::= SEQUENCE {
+ version CMSVersion,
+ digestAlgorithms DigestAlgorithmIdentifiers,
+ encapContentInfo EncapsulatedContentInfo,
+ certificates [0] IMPLICIT CertificateSet OPTIONAL,
+ crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
+ signerInfos SignerInfos
+}
+
+OriginatorInfo ::= SEQUENCE {
+ certs [0] IMPLICIT CertificateSet OPTIONAL,
+ crls [1] IMPLICIT CertificateRevocationLists OPTIONAL
+}
+
+KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
+ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
+
+EncryptedKey ::= OCTET STRING
+
+KeyTransRecipientInfo ::= SEQUENCE {
+ version CMSVersion, -- always set to 0 or 2
+ rid RecipientIdentifier,
+ keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
+ encryptedKey EncryptedKey
+}
+
+RecipientInfo ::= KeyTransRecipientInfo
+
+RecipientInfos ::= SET OF RecipientInfo
+
+EncryptedContent ::= OCTET STRING
+
+EncryptedContentInfo ::= SEQUENCE {
+ contentType ContentType,
+ contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
+ encryptedContent [0] IMPLICIT OCTET STRING OPTIONAL
+}
+
+UnprotectedAttributes ::= SET OF Attribute -- SIZE (1..MAX)
+
+CMSEncryptedData ::= SEQUENCE {
+ version CMSVersion,
+ encryptedContentInfo EncryptedContentInfo,
+ unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL
+}
+
+EnvelopedData ::= SEQUENCE {
+ version CMSVersion,
+ originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
+ recipientInfos RecipientInfos,
+ encryptedContentInfo EncryptedContentInfo,
+ unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL
+}
+
+-- Data ::= OCTET STRING
+
+CMSRC2CBCParameter ::= SEQUENCE {
+ rc2ParameterVersion INTEGER (0..4294967295),
+ iv OCTET STRING -- exactly 8 octets
+}
+
+CMSCBCParameter ::= OCTET STRING
+
+END
diff --git a/third_party/heimdal/lib/asn1/cms.opt b/third_party/heimdal/lib/asn1/cms.opt
new file mode 100644
index 0000000..49333e5
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/cms.opt
@@ -0,0 +1,2 @@
+--decode-dce-ber
+--sequence=DigestAlgorithmIdentifiers
diff --git a/third_party/heimdal/lib/asn1/crmf.asn1 b/third_party/heimdal/lib/asn1/crmf.asn1
new file mode 100644
index 0000000..696a89b
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/crmf.asn1
@@ -0,0 +1,110 @@
+-- $Id$
+PKCS10 DEFINITIONS ::=
+
+BEGIN
+
+IMPORTS
+ Time,
+ GeneralName,
+ SubjectPublicKeyInfo,
+ RelativeDistinguishedName,
+ AttributeTypeAndValue,
+ Extension,
+ AlgorithmIdentifier
+ FROM rfc2459
+ HEIM_ANY
+ FROM heim;
+
+CRMFRDNSequence ::= SEQUENCE OF RelativeDistinguishedName
+
+Controls ::= SEQUENCE -- SIZE(1..MAX) -- OF AttributeTypeAndValue
+
+PKMACValue ::= SEQUENCE {
+ algId AlgorithmIdentifier,
+ value BIT STRING
+}
+
+-- XXX IMPLICIT brokenness
+POPOSigningKeyInput ::= SEQUENCE {
+ authInfo CHOICE {
+ sender [0] IMPLICIT GeneralName,
+ publicKeyMAC PKMACValue
+ },
+ publicKey SubjectPublicKeyInfo
+} -- from CertTemplate
+
+-- XXX IMPLICIT brokenness
+POPOSigningKey ::= SEQUENCE {
+ poposkInput [0] IMPLICIT POPOSigningKeyInput OPTIONAL,
+ algorithmIdentifier AlgorithmIdentifier,
+ signature BIT STRING }
+
+PBMParameter ::= SEQUENCE {
+ salt OCTET STRING,
+ owf AlgorithmIdentifier,
+ iterationCount INTEGER,
+ mac AlgorithmIdentifier
+}
+
+SubsequentMessage ::= INTEGER {
+ encrCert (0),
+ challengeResp (1)
+}
+
+POPOPrivKey ::= CHOICE {
+ thisMessage [0] BIT STRING, -- Deprecated
+ subsequentMessage [1] IMPLICIT SubsequentMessage,
+ dhMAC [2] BIT STRING, -- Deprecated
+ agreeMAC [3] IMPLICIT PKMACValue,
+ encryptedKey [4] HEIM_ANY
+}
+
+ProofOfPossession ::= CHOICE {
+ raVerified [0] NULL,
+ signature [1] POPOSigningKey,
+ keyEncipherment [2] POPOPrivKey,
+ keyAgreement [3] POPOPrivKey
+}
+
+CertTemplate ::= SEQUENCE {
+ version [0] INTEGER OPTIONAL,
+ serialNumber [1] INTEGER OPTIONAL,
+ signingAlg [2] SEQUENCE {
+ algorithm OBJECT IDENTIFIER,
+ parameters HEIM_ANY OPTIONAL
+ } -- AlgorithmIdentifier -- OPTIONAL,
+ issuer [3] IMPLICIT CHOICE {
+ rdnSequence CRMFRDNSequence
+ } -- Name -- OPTIONAL,
+ validity [4] SEQUENCE {
+ notBefore [0] Time OPTIONAL,
+ notAfter [1] Time OPTIONAL
+ } -- OptionalValidity -- OPTIONAL,
+ subject [5] IMPLICIT CHOICE {
+ rdnSequence CRMFRDNSequence
+ } -- Name -- OPTIONAL,
+ publicKey [6] IMPLICIT SEQUENCE {
+ algorithm AlgorithmIdentifier,
+ subjectPublicKey BIT STRING OPTIONAL
+ } -- SubjectPublicKeyInfo -- OPTIONAL,
+ issuerUID [7] IMPLICIT BIT STRING OPTIONAL,
+ subjectUID [8] IMPLICIT BIT STRING OPTIONAL,
+ extensions [9] IMPLICIT SEQUENCE OF Extension OPTIONAL
+}
+
+CertRequest ::= SEQUENCE {
+ certReqId INTEGER,
+ certTemplate CertTemplate,
+ controls Controls OPTIONAL
+}
+
+CertReqMsg ::= SEQUENCE {
+ certReq CertRequest,
+ popo ProofOfPossession OPTIONAL,
+ regInfo SEQUENCE OF AttributeTypeAndValue OPTIONAL }
+
+CertReqMessages ::= SEQUENCE OF CertReqMsg
+
+
+END
+
diff --git a/third_party/heimdal/lib/asn1/crmf.opt b/third_party/heimdal/lib/asn1/crmf.opt
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/crmf.opt
diff --git a/third_party/heimdal/lib/asn1/der.c b/third_party/heimdal/lib/asn1/der.c
new file mode 100644
index 0000000..bea4ae5
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/der.c
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+#include <com_err.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <getarg.h>
+#include <err.h>
+
+RCSID("$Id$");
+
+
+static const char *class_names[] = {
+ "UNIV", /* 0 */
+ "APPL", /* 1 */
+ "CONTEXT", /* 2 */
+ "PRIVATE" /* 3 */
+};
+
+static const char *type_names[] = {
+ "PRIM", /* 0 */
+ "CONS" /* 1 */
+};
+
+static const char *tag_names[] = {
+ "EndOfContent", /* 0 */
+ "Boolean", /* 1 */
+ "Integer", /* 2 */
+ "BitString", /* 3 */
+ "OctetString", /* 4 */
+ "Null", /* 5 */
+ "ObjectID", /* 6 */
+ NULL, /* 7 */
+ NULL, /* 8 */
+ NULL, /* 9 */
+ "Enumerated", /* 10 */
+ NULL, /* 11 */
+ "UTF8String", /* 12 */
+ NULL, /* 13 */
+ NULL, /* 14 */
+ NULL, /* 15 */
+ "Sequence", /* 16 */
+ "Set", /* 17 */
+ NULL, /* 18 */
+ "PrintableString", /* 19 */
+ NULL, /* 20 */
+ NULL, /* 21 */
+ "IA5String", /* 22 */
+ "UTCTime", /* 23 */
+ "GeneralizedTime", /* 24 */
+ NULL, /* 25 */
+ "VisibleString", /* 26 */
+ "GeneralString", /* 27 */
+ NULL, /* 28 */
+ NULL, /* 29 */
+ "BMPString" /* 30 */
+};
+
+static int
+get_type(const char *name, const char *list[], unsigned len)
+{
+ unsigned i;
+ for (i = 0; i < len; i++)
+ if (list[i] && strcasecmp(list[i], name) == 0)
+ return i;
+ return -1;
+}
+
+#define SIZEOF_ARRAY(a) (sizeof((a))/sizeof((a)[0]))
+
+const char * ASN1CALL
+der_get_class_name(unsigned num)
+{
+ if (num >= SIZEOF_ARRAY(class_names))
+ return NULL;
+ return class_names[num];
+}
+
+int ASN1CALL
+der_get_class_num(const char *name)
+{
+ return get_type(name, class_names, SIZEOF_ARRAY(class_names));
+}
+
+const char * ASN1CALL
+der_get_type_name(unsigned num)
+{
+ if (num >= SIZEOF_ARRAY(type_names))
+ return NULL;
+ return type_names[num];
+}
+
+int ASN1CALL
+der_get_type_num(const char *name)
+{
+ return get_type(name, type_names, SIZEOF_ARRAY(type_names));
+}
+
+const char * ASN1CALL
+der_get_tag_name(unsigned num)
+{
+ if (num >= SIZEOF_ARRAY(tag_names))
+ return NULL;
+ return tag_names[num];
+}
+
+int ASN1CALL
+der_get_tag_num(const char *name)
+{
+ return get_type(name, tag_names, SIZEOF_ARRAY(tag_names));
+}
diff --git a/third_party/heimdal/lib/asn1/der.h b/third_party/heimdal/lib/asn1/der.h
new file mode 100644
index 0000000..f732348
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/der.h
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __DER_H__
+#define __DER_H__
+
+#include <stdint.h>
+
+typedef enum {
+ ASN1_C_UNIV = 0,
+ ASN1_C_APPL = 1,
+ ASN1_C_CONTEXT = 2,
+ ASN1_C_PRIVATE = 3
+} Der_class;
+
+typedef enum {PRIM = 0, CONS = 1} Der_type;
+
+#define MAKE_TAG(CLASS, TYPE, TAG) (((CLASS) << 6) | ((TYPE) << 5) | (TAG))
+
+/* Universal tags */
+
+enum {
+ UT_EndOfContent = 0,
+ UT_Boolean = 1,
+ UT_Integer = 2,
+ UT_BitString = 3,
+ UT_OctetString = 4,
+ UT_Null = 5,
+ UT_OID = 6,
+ UT_Enumerated = 10,
+ UT_UTF8String = 12,
+ UT_Sequence = 16,
+ UT_Set = 17,
+ UT_PrintableString = 19,
+ UT_IA5String = 22,
+ UT_UTCTime = 23,
+ UT_GeneralizedTime = 24,
+ UT_UniversalString = 25,
+ UT_VisibleString = 26,
+ UT_GeneralString = 27,
+ UT_BMPString = 30,
+ /* unsupported types */
+ UT_ObjectDescriptor = 7,
+ UT_External = 8,
+ UT_Real = 9,
+ UT_EmbeddedPDV = 11,
+ UT_RelativeOID = 13,
+ UT_NumericString = 18,
+ UT_TeletexString = 20,
+ UT_VideotexString = 21,
+ UT_GraphicString = 25
+};
+
+#define ASN1_INDEFINITE 0xdce0deed
+
+typedef struct heim_der_time_t {
+ time_t dt_sec;
+ unsigned long dt_nsec;
+} heim_der_time_t;
+
+typedef struct heim_ber_time_t {
+ time_t bt_sec;
+ unsigned bt_nsec;
+ int bt_zone;
+} heim_ber_time_t;
+
+struct asn1_template;
+
+#include <der-protos.h>
+
+int _heim_fix_dce(size_t reallen, size_t *len);
+int _heim_der_set_sort(const void *, const void *);
+int _heim_time2generalizedtime (time_t, heim_octet_string *, int);
+
+#endif /* __DER_H__ */
diff --git a/third_party/heimdal/lib/asn1/der_cmp.c b/third_party/heimdal/lib/asn1/der_cmp.c
new file mode 100644
index 0000000..ccaf6fd
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/der_cmp.c
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) 2003-2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+
+int ASN1CALL
+der_heim_oid_cmp(const heim_oid *p, const heim_oid *q)
+{
+ int c;
+
+ if (p->length == q->length)
+ return memcmp(p->components,
+ q->components,
+ p->length * sizeof(*p->components));
+ if (p->length < q->length) {
+ c = memcmp(p->components,
+ q->components,
+ p->length * sizeof(*p->components));
+ if (c == 0)
+ return -1;
+ return c;
+ }
+ c = memcmp(p->components,
+ q->components,
+ q->length * sizeof(*p->components));
+ if (c == 0)
+ return 1;
+ return c;
+}
+
+int ASN1CALL
+der_heim_octet_string_cmp(const heim_octet_string *p,
+ const heim_octet_string *q)
+{
+ int c;
+
+ if (p->length == q->length)
+ return memcmp(p->data, q->data, p->length);
+ if (p->length < q->length) {
+ if ((c = memcmp(p->data, q->data, p->length)) == 0)
+ return -1;
+ return c;
+ }
+ if ((c = memcmp(p->data, q->data, q->length)) == 0)
+ return 1;
+ return c;
+}
+
+int ASN1CALL
+der_printable_string_cmp(const heim_printable_string *p,
+ const heim_printable_string *q)
+{
+ return der_heim_octet_string_cmp(p, q);
+}
+
+int ASN1CALL
+der_ia5_string_cmp(const heim_ia5_string *p,
+ const heim_ia5_string *q)
+{
+ return der_heim_octet_string_cmp(p, q);
+}
+
+int ASN1CALL
+der_heim_bit_string_cmp(const heim_bit_string *p,
+ const heim_bit_string *q)
+{
+ int r1, r2;
+ size_t i;
+ if (p->length != q->length)
+ return (int)(p->length - q->length);
+ i = memcmp(p->data, q->data, p->length / 8);
+ if (i)
+ return (int)i;
+ if ((p->length % 8) == 0)
+ return 0;
+ i = (p->length / 8);
+ r1 = ((unsigned char *)p->data)[i];
+ r2 = ((unsigned char *)q->data)[i];
+ i = 8 - (p->length % 8);
+ r1 = r1 >> i;
+ r2 = r2 >> i;
+ return r1 - r2;
+}
+
+int ASN1CALL
+der_heim_integer_cmp(const heim_integer *p,
+ const heim_integer *q)
+{
+ if (p->negative != q->negative)
+ return q->negative - p->negative;
+ if (p->length != q->length)
+ return (int)(p->length - q->length);
+ return memcmp(p->data, q->data, p->length);
+}
+
+int ASN1CALL
+der_heim_bmp_string_cmp(const heim_bmp_string *p, const heim_bmp_string *q)
+{
+ int c;
+
+ if (p->length == q->length)
+ return memcmp(p->data, q->data, p->length * sizeof(q->data[0]));
+ if (p->length < q->length) {
+ if ((c = memcmp(p->data, q->data, p->length * sizeof(q->data[0]))) == 0)
+ return -1;
+ return c;
+ }
+ if ((c = memcmp(p->data, q->data, q->length * sizeof(q->data[0]))) == 0)
+ return 1;
+ return c;
+}
+
+int ASN1CALL
+der_heim_universal_string_cmp(const heim_universal_string *p,
+ const heim_universal_string *q)
+{
+ int c;
+
+ if (p->length == q->length)
+ return memcmp(p->data, q->data, p->length * sizeof(q->data[0]));
+ if (p->length < q->length) {
+ if ((c = memcmp(p->data, q->data, p->length * sizeof(q->data[0]))) == 0)
+ return -1;
+ return c;
+ }
+ if ((c = memcmp(p->data, q->data, q->length * sizeof(q->data[0]))) == 0)
+ return 1;
+ return c;
+}
diff --git a/third_party/heimdal/lib/asn1/der_copy.c b/third_party/heimdal/lib/asn1/der_copy.c
new file mode 100644
index 0000000..2084cef
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/der_copy.c
@@ -0,0 +1,245 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+
+RCSID("$Id$");
+
+int ASN1CALL
+der_copy_general_string (const heim_general_string *from,
+ heim_general_string *to)
+{
+ *to = strdup(*from);
+ if(*to == NULL)
+ return ENOMEM;
+ return 0;
+}
+
+int ASN1CALL
+der_copy_integer (const int *from, int *to)
+{
+ *to = *from;
+ return 0;
+}
+
+int ASN1CALL
+der_copy_integer64 (const int64_t *from, int64_t *to)
+{
+ *to = *from;
+ return 0;
+}
+
+int ASN1CALL
+der_copy_unsigned (const unsigned *from, unsigned *to)
+{
+ *to = *from;
+ return 0;
+}
+
+int ASN1CALL
+der_copy_unsigned64 (const uint64_t *from, uint64_t *to)
+{
+ *to = *from;
+ return 0;
+}
+
+int ASN1CALL
+der_copy_generalized_time (const time_t *from, time_t *to)
+{
+ *to = *from;
+ return 0;
+}
+
+int ASN1CALL
+der_copy_utctime (const time_t *from, time_t *to)
+{
+ *to = *from;
+ return 0;
+}
+
+int ASN1CALL
+der_copy_utf8string (const heim_utf8_string *from, heim_utf8_string *to)
+{
+ return der_copy_general_string(from, to);
+}
+
+int ASN1CALL
+der_copy_printable_string (const heim_printable_string *from,
+ heim_printable_string *to)
+{
+ assert(from->length == 0 || (from->length > 0 && from->data != NULL));
+ to->data = malloc(from->length + 1);
+ if (to->data == NULL) {
+ to->length = 0;
+ return ENOMEM;
+ }
+ to->length = from->length;
+ if (to->length > 0)
+ memcpy(to->data, from->data, to->length);
+ ((char *)to->data)[to->length] = '\0';
+ return 0;
+}
+
+int ASN1CALL
+der_copy_ia5_string (const heim_ia5_string *from,
+ heim_ia5_string *to)
+{
+ return der_copy_printable_string(from, to);
+}
+
+int ASN1CALL
+der_copy_bmp_string (const heim_bmp_string *from, heim_bmp_string *to)
+{
+ assert(from->length == 0 || (from->length > 0 && from->data != NULL));
+ if (from->length == 0)
+ to->data = calloc(1, sizeof(from->data[0]));
+ else
+ to->data = malloc(from->length * sizeof(from->data[0]));
+ if (to->data == NULL) {
+ to->length = 0;
+ return ENOMEM;
+ }
+ to->length = from->length;
+ if (to->length > 0)
+ memcpy(to->data, from->data, to->length * sizeof(to->data[0]));
+ return 0;
+}
+
+int ASN1CALL
+der_copy_universal_string (const heim_universal_string *from,
+ heim_universal_string *to)
+{
+ assert(from->length == 0 || (from->length > 0 && from->data != NULL));
+ if (from->length == 0)
+ to->data = calloc(1, sizeof(from->data[0]));
+ else
+ to->data = malloc(from->length * sizeof(from->data[0]));
+ if (to->data == NULL) {
+ to->length = 0;
+ return ENOMEM;
+ }
+ to->length = from->length;
+ if (to->length > 0)
+ memcpy(to->data, from->data, to->length * sizeof(to->data[0]));
+ return 0;
+}
+
+int ASN1CALL
+der_copy_visible_string (const heim_visible_string *from,
+ heim_visible_string *to)
+{
+ return der_copy_general_string(from, to);
+}
+
+int ASN1CALL
+der_copy_octet_string (const heim_octet_string *from, heim_octet_string *to)
+{
+ assert(from->length == 0 || (from->length > 0 && from->data != NULL));
+ if (from->length == 0)
+ to->data = calloc(1, 1);
+ else
+ to->data = malloc(from->length);
+ if (to->data == NULL) {
+ to->length = 0;
+ return ENOMEM;
+ }
+ to->length = from->length;
+ if (to->length > 0)
+ memcpy(to->data, from->data, to->length);
+ return 0;
+}
+
+int ASN1CALL
+der_copy_heim_integer (const heim_integer *from, heim_integer *to)
+{
+ assert(from->length == 0 || (from->length > 0 && from->data != NULL));
+ if (from->length == 0)
+ to->data = calloc(1, 1);
+ else
+ to->data = malloc(from->length);
+ if (to->data == NULL) {
+ to->length = 0;
+ return ENOMEM;
+ }
+ to->length = from->length;
+ if (to->length > 0)
+ memcpy(to->data, from->data, to->length);
+ to->negative = from->negative;
+ return 0;
+}
+
+int ASN1CALL
+der_copy_oid (const heim_oid *from, heim_oid *to)
+{
+ if (from->length == 0) {
+ to->length = 0;
+ to->components = calloc(1, sizeof(*from->components));
+ if (to->components == NULL)
+ return ENOMEM;
+ return 0;
+ }
+ assert(from->components != NULL);
+ to->components = malloc(from->length * sizeof(*from->components));
+ if (to->components == NULL) {
+ to->length = 0;
+ return ENOMEM;
+ }
+ to->length = from->length;
+ memcpy(to->components, from->components,
+ to->length * sizeof(*to->components));
+ return 0;
+}
+
+int ASN1CALL
+der_copy_bit_string (const heim_bit_string *from, heim_bit_string *to)
+{
+ size_t len;
+
+ assert(from->length == 0 || (from->length > 0 && from->data != NULL));
+
+ len = (from->length + 7) / 8;
+ if (len == 0)
+ to->data = calloc(1, 1);
+ else
+ to->data = malloc(len);
+ if (to->data == NULL) {
+ to->length = 0;
+ return ENOMEM;
+ }
+ to->length = from->length;
+ if (len > 0)
+ memcpy(to->data, from->data, len);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/asn1/der_format.c b/third_party/heimdal/lib/asn1/der_format.c
new file mode 100644
index 0000000..bb4a7ce
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/der_format.c
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+#include <hex.h>
+
+RCSID("$Id$");
+
+int ASN1CALL
+der_parse_hex_heim_integer (const char *p, heim_integer *data)
+{
+ ssize_t len;
+
+ data->length = 0;
+ data->negative = 0;
+ data->data = NULL;
+
+ if (*p == '-') {
+ p++;
+ data->negative = 1;
+ }
+
+ len = strlen(p);
+ if (len <= 0) {
+ data->data = NULL;
+ data->length = 0;
+ return EINVAL;
+ }
+
+ data->length = (len / 2) + 1;
+ data->data = malloc(data->length);
+ if (data->data == NULL) {
+ data->length = 0;
+ return ENOMEM;
+ }
+
+ len = hex_decode(p, data->data, data->length);
+ if (len < 0) {
+ free(data->data);
+ data->data = NULL;
+ data->length = 0;
+ return EINVAL;
+ }
+
+ {
+ unsigned char *q = data->data;
+ while(len > 0 && *q == 0) {
+ q++;
+ len--;
+ }
+ data->length = len;
+ memmove(data->data, q, len);
+ }
+ return 0;
+}
+
+int ASN1CALL
+der_print_hex_heim_integer (const heim_integer *data, char **p)
+{
+ ssize_t len;
+ char *q;
+
+ len = hex_encode(data->data, data->length, p);
+ if (len < 0)
+ return ENOMEM;
+
+ if (data->negative) {
+ len = asprintf(&q, "-%s", *p);
+ free(*p);
+ if (len < 0)
+ return ENOMEM;
+ *p = q;
+ }
+ return 0;
+}
+
+int ASN1CALL
+der_print_heim_oid (const heim_oid *oid, char delim, char **str)
+{
+ struct rk_strpool *p = NULL;
+ size_t i;
+
+ if (oid->length == 0)
+ return EINVAL;
+
+ for (i = 0; i < oid->length ; i++) {
+ p = rk_strpoolprintf(p, "%d", oid->components[i]);
+ if (p && i < oid->length - 1)
+ p = rk_strpoolprintf(p, "%c", delim);
+ if (p == NULL) {
+ *str = NULL;
+ return ENOMEM;
+ }
+ }
+
+ *str = rk_strpoolcollect(p);
+ if (*str == NULL)
+ return ENOMEM;
+ return 0;
+}
+
+int ASN1CALL
+der_parse_heim_oid (const char *str, const char *sep, heim_oid *data)
+{
+ char *s, *w, *brkt, *endptr;
+ unsigned int *c;
+ long l;
+
+ data->length = 0;
+ data->components = NULL;
+
+ if (sep == NULL)
+ sep = ".";
+
+ s = strdup(str);
+
+ for (w = strtok_r(s, sep, &brkt);
+ w != NULL;
+ w = strtok_r(NULL, sep, &brkt)) {
+
+ c = realloc(data->components,
+ (data->length + 1) * sizeof(data->components[0]));
+ if (c == NULL) {
+ der_free_oid(data);
+ free(s);
+ return ENOMEM;
+ }
+ data->components = c;
+
+ l = strtol(w, &endptr, 10);
+ if (*endptr != '\0' || l < 0 || l > INT_MAX) {
+ der_free_oid(data);
+ free(s);
+ return EINVAL;
+ }
+ data->components[data->length++] = (unsigned int)l;
+ }
+ free(s);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/asn1/der_free.c b/third_party/heimdal/lib/asn1/der_free.c
new file mode 100644
index 0000000..d80406f
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/der_free.c
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+
+RCSID("$Id$");
+
+void ASN1CALL
+der_free_general_string (heim_general_string *str)
+{
+ free(*str);
+ *str = NULL;
+}
+
+void ASN1CALL
+der_free_integer (int *i)
+{
+ *i = 0;
+}
+
+void ASN1CALL
+der_free_integer64 (int64_t *i)
+{
+ *i = 0;
+}
+
+void ASN1CALL
+der_free_unsigned (unsigned *u)
+{
+ *u = 0;
+}
+
+void ASN1CALL
+der_free_unsigned64 (uint64_t *u)
+{
+ *u = 0;
+}
+
+void ASN1CALL
+der_free_generalized_time(time_t *t)
+{
+ *t = 0;
+}
+
+void ASN1CALL
+der_free_utctime(time_t *t)
+{
+ *t = 0;
+}
+
+
+void ASN1CALL
+der_free_utf8string (heim_utf8_string *str)
+{
+ free(*str);
+ *str = NULL;
+}
+
+void ASN1CALL
+der_free_printable_string (heim_printable_string *str)
+{
+ der_free_octet_string(str);
+}
+
+void ASN1CALL
+der_free_ia5_string (heim_ia5_string *str)
+{
+ der_free_octet_string(str);
+}
+
+void ASN1CALL
+der_free_bmp_string (heim_bmp_string *k)
+{
+ free(k->data);
+ k->data = NULL;
+ k->length = 0;
+}
+
+void ASN1CALL
+der_free_universal_string (heim_universal_string *k)
+{
+ free(k->data);
+ k->data = NULL;
+ k->length = 0;
+}
+
+void ASN1CALL
+der_free_visible_string (heim_visible_string *str)
+{
+ free(*str);
+ *str = NULL;
+}
+
+void ASN1CALL
+der_free_octet_string (heim_octet_string *k)
+{
+ free(k->data);
+ k->data = NULL;
+ k->length = 0;
+}
+
+void ASN1CALL
+der_free_heim_integer (heim_integer *k)
+{
+ free(k->data);
+ k->data = NULL;
+ k->length = 0;
+}
+
+void ASN1CALL
+der_free_oid (heim_oid *k)
+{
+ free(k->components);
+ k->components = NULL;
+ k->length = 0;
+}
+
+void ASN1CALL
+der_free_bit_string (heim_bit_string *k)
+{
+ free(k->data);
+ k->data = NULL;
+ k->length = 0;
+}
diff --git a/third_party/heimdal/lib/asn1/der_get.c b/third_party/heimdal/lib/asn1/der_get.c
new file mode 100644
index 0000000..c12f817
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/der_get.c
@@ -0,0 +1,798 @@
+/*
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+
+/*
+ * All decoding functions take a pointer `p' to first position in
+ * which to read, from the left, `len' which means the maximum number
+ * of characters we are able to read, `ret' were the value will be
+ * returned and `size' where the number of used bytes is stored.
+ * Either 0 or an error code is returned.
+ */
+
+int ASN1CALL
+der_get_unsigned (const unsigned char *p, size_t len,
+ unsigned *ret, size_t *size)
+{
+ unsigned val = 0;
+ size_t oldlen = len;
+
+ if (len == sizeof(val) + 1 && p[0] == 0)
+ ;
+ else if (len > sizeof(val))
+ return ASN1_OVERRUN;
+
+ while (len--)
+ val = val * 256 + *p++;
+ *ret = val;
+ if(size) *size = oldlen;
+ return 0;
+}
+
+int ASN1CALL
+der_get_unsigned64 (const unsigned char *p, size_t len,
+ uint64_t *ret, size_t *size)
+{
+ uint64_t val = 0;
+ size_t oldlen = len;
+
+ if (len == sizeof(val) + 1 && p[0] == 0)
+ ;
+ else if (len > sizeof(val))
+ return ASN1_OVERRUN;
+
+ while (len--)
+ val = val * 256 + *p++;
+ *ret = val;
+ if(size) *size = oldlen;
+ return 0;
+}
+
+int ASN1CALL
+der_get_integer (const unsigned char *p, size_t len,
+ int *ret, size_t *size)
+{
+ int val = 0;
+ size_t oldlen = len;
+
+ if (len > sizeof(val))
+ return ASN1_OVERRUN;
+
+ if (len > 0) {
+ val = (signed char)*p++;
+ while (--len)
+ val = val * 256 + *p++;
+ }
+ *ret = val;
+ if(size) *size = oldlen;
+ return 0;
+}
+
+int ASN1CALL
+der_get_integer64 (const unsigned char *p, size_t len,
+ int64_t *ret, size_t *size)
+{
+ int64_t val = 0;
+ size_t oldlen = len;
+
+ if (len > sizeof(val))
+ return ASN1_OVERRUN;
+
+ if (len > 0) {
+ val = (signed char)*p++;
+ while (--len)
+ val = val * 256 + *p++;
+ }
+ *ret = val;
+ if(size) *size = oldlen;
+ return 0;
+}
+
+
+int ASN1CALL
+der_get_length (const unsigned char *p, size_t len,
+ size_t *val, size_t *size)
+{
+ size_t v;
+
+ if (len <= 0)
+ return ASN1_OVERRUN;
+ --len;
+ v = *p++;
+ if (v < 128) {
+ *val = v;
+ if(size) *size = 1;
+ } else {
+ int e;
+ size_t l;
+ unsigned tmp;
+
+ if(v == 0x80){
+ *val = ASN1_INDEFINITE;
+ if(size) *size = 1;
+ return 0;
+ }
+ v &= 0x7F;
+ if (len < v)
+ return ASN1_OVERRUN;
+ e = der_get_unsigned (p, v, &tmp, &l);
+ if(e) return e;
+ *val = tmp;
+ if(size) *size = l + 1;
+ }
+ return 0;
+}
+
+int ASN1CALL
+der_get_boolean(const unsigned char *p, size_t len, int *data, size_t *size)
+{
+ if(len < 1)
+ return ASN1_OVERRUN;
+ if(*p != 0)
+ *data = 1;
+ else
+ *data = 0;
+ *size = 1;
+ return 0;
+}
+
+int ASN1CALL
+der_get_general_string (const unsigned char *p, size_t len,
+ heim_general_string *str, size_t *size)
+{
+ const unsigned char *p1;
+ char *s;
+
+ assert(p != NULL);
+
+ if (size)
+ *size = 0;
+
+ p1 = memchr(p, 0, len);
+ if (p1 != NULL) {
+ /*
+ * Allow trailing NULs. We allow this since MIT Kerberos sends
+ * an strings in the NEED_PREAUTH case that includes a
+ * trailing NUL.
+ */
+ while ((size_t)(p1 - p) < len && *p1 == '\0')
+ p1++;
+ if ((size_t)(p1 - p) != len) {
+ *str = NULL;
+ return ASN1_BAD_CHARACTER;
+ }
+ }
+ if (len == SIZE_MAX) {
+ *str = NULL;
+ return ASN1_BAD_LENGTH;
+ }
+
+ *str = s = malloc (len + 1);
+ if (s == NULL)
+ return ENOMEM;
+ memcpy (s, p, len);
+ s[len] = '\0';
+
+ if(size) *size = len;
+ return 0;
+}
+
+int ASN1CALL
+der_get_utf8string (const unsigned char *p, size_t len,
+ heim_utf8_string *str, size_t *size)
+{
+ return der_get_general_string(p, len, str, size);
+}
+
+#define gen_data_zero(_data) \
+ do { (_data)->length = 0; (_data)->data = NULL; } while(0)
+
+int ASN1CALL
+der_get_printable_string(const unsigned char *p, size_t len,
+ heim_printable_string *str, size_t *size)
+{
+ assert(p != NULL);
+
+ if (size)
+ *size = 0;
+
+ if (len == SIZE_MAX) {
+ gen_data_zero(str);
+ return ASN1_BAD_LENGTH;
+ }
+ str->length = len;
+ str->data = malloc(len + 1);
+ if (str->data == NULL) {
+ gen_data_zero(str);
+ return ENOMEM;
+ }
+
+ memcpy(str->data, p, len);
+ ((char *)str->data)[len] = '\0';
+ if(size) *size = len;
+ return 0;
+}
+
+int ASN1CALL
+der_get_ia5_string(const unsigned char *p, size_t len,
+ heim_ia5_string *str, size_t *size)
+{
+ return der_get_printable_string(p, len, str, size);
+}
+
+int ASN1CALL
+der_get_bmp_string (const unsigned char *p, size_t len,
+ heim_bmp_string *data, size_t *size)
+{
+ size_t i;
+
+ assert(p != NULL);
+
+ if (size)
+ *size = 0;
+
+ if (len & 1) {
+ gen_data_zero(data);
+ return ASN1_BAD_FORMAT;
+ }
+ data->length = len / 2;
+ if (data->length > UINT_MAX/sizeof(data->data[0])) {
+ gen_data_zero(data);
+ return ERANGE;
+ }
+ data->data = malloc(data->length * sizeof(data->data[0]));
+ if (data->data == NULL && data->length != 0) {
+ gen_data_zero(data);
+ return ENOMEM;
+ }
+
+ for (i = 0; i < data->length; i++) {
+ data->data[i] = (p[0] << 8) | p[1];
+ p += 2;
+ /* check for NUL in the middle of the string */
+ if (data->data[i] == 0 && i != (data->length - 1)) {
+ free(data->data);
+ gen_data_zero(data);
+ return ASN1_BAD_CHARACTER;
+ }
+ }
+ if (size) *size = len;
+
+ return 0;
+}
+
+int ASN1CALL
+der_get_universal_string (const unsigned char *p, size_t len,
+ heim_universal_string *data, size_t *size)
+{
+ size_t i;
+
+ assert(p != NULL);
+
+ if (size)
+ *size = 0;
+
+ if (len & 3) {
+ gen_data_zero(data);
+ return ASN1_BAD_FORMAT;
+ }
+ data->length = len / 4;
+ if (data->length > UINT_MAX/sizeof(data->data[0])) {
+ gen_data_zero(data);
+ return ERANGE;
+ }
+ data->data = malloc(data->length * sizeof(data->data[0]));
+ if (data->data == NULL && data->length != 0) {
+ gen_data_zero(data);
+ return ENOMEM;
+ }
+
+ for (i = 0; i < data->length; i++) {
+ data->data[i] = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
+ p += 4;
+ /* check for NUL in the middle of the string */
+ if (data->data[i] == 0 && i != (data->length - 1)) {
+ free(data->data);
+ gen_data_zero(data);
+ return ASN1_BAD_CHARACTER;
+ }
+ }
+ if (size) *size = len;
+ return 0;
+}
+
+int ASN1CALL
+der_get_visible_string (const unsigned char *p, size_t len,
+ heim_visible_string *str, size_t *size)
+{
+ return der_get_general_string(p, len, str, size);
+}
+
+int ASN1CALL
+der_get_octet_string (const unsigned char *p, size_t len,
+ heim_octet_string *data, size_t *size)
+{
+ assert(p != NULL);
+
+ if (size)
+ *size = 0;
+
+ if (len == 0)
+ data->data = malloc(1);
+ else
+ data->data = malloc(len);
+ if (data->data == NULL) {
+ data->length = 0;
+ return ENOMEM;
+ }
+ data->length = len;
+ memcpy (data->data, p, len);
+ if (size)
+ *size = len;
+ return 0;
+}
+
+int ASN1CALL
+der_get_octet_string_ber (const unsigned char *p, size_t len,
+ heim_octet_string *data, size_t *size)
+{
+ int e;
+ Der_type type;
+ Der_class cls;
+ unsigned int tag, depth = 0;
+ size_t l, datalen, oldlen = len;
+
+ assert(p != NULL);
+
+ if (size)
+ *size = 0;
+
+ data->length = 0;
+ data->data = NULL;
+
+ while (len) {
+ e = der_get_tag (p, len, &cls, &type, &tag, &l);
+ if (e) goto out;
+ if (cls != ASN1_C_UNIV) {
+ e = ASN1_BAD_ID;
+ goto out;
+ }
+ if (type == PRIM && tag == UT_EndOfContent) {
+ if (depth == 0)
+ break;
+ depth--;
+ }
+ if (tag != UT_OctetString) {
+ e = ASN1_BAD_ID;
+ goto out;
+ }
+
+ p += l;
+ len -= l;
+ e = der_get_length (p, len, &datalen, &l);
+ if (e) goto out;
+ p += l;
+ len -= l;
+
+ if (datalen > len)
+ return ASN1_OVERRUN;
+
+ if (type == PRIM && datalen) {
+ void *ptr;
+
+ ptr = realloc(data->data, data->length + datalen);
+ if (ptr == NULL) {
+ e = ENOMEM;
+ goto out;
+ }
+ data->data = ptr;
+ memcpy(((unsigned char *)data->data) + data->length, p, datalen);
+ data->length += datalen;
+ } else if (type != PRIM)
+ depth++;
+
+ p += datalen;
+ len -= datalen;
+ }
+ if (depth != 0)
+ return ASN1_INDEF_OVERRUN;
+ if(size) *size = oldlen - len;
+ return 0;
+ out:
+ free(data->data);
+ data->data = NULL;
+ data->length = 0;
+ return e;
+}
+
+
+int ASN1CALL
+der_get_heim_integer (const unsigned char *p, size_t len,
+ heim_integer *data, size_t *size)
+{
+ data->length = 0;
+ data->negative = 0;
+ data->data = NULL;
+
+ if (size)
+ *size = 0;
+
+ if (len == 0)
+ return 0;
+
+ assert(p != NULL);
+
+ if (p[0] & 0x80) {
+ unsigned char *q;
+ int carry = 1;
+ data->negative = 1;
+
+ data->length = len;
+
+ if (p[0] == 0xff) {
+ p++;
+ data->length--;
+ }
+ data->data = malloc(data->length);
+ if (data->data == NULL) {
+ data->length = 0;
+ if (size)
+ *size = 0;
+ return ENOMEM;
+ }
+ q = &((unsigned char*)data->data)[data->length - 1];
+ p += data->length - 1;
+ while (q >= (unsigned char*)data->data) {
+ *q = *p ^ 0xff;
+ if (carry)
+ carry = !++*q;
+ p--;
+ q--;
+ }
+ } else {
+ data->negative = 0;
+ data->length = len;
+
+ if (p[0] == 0) {
+ p++;
+ data->length--;
+ }
+ data->data = malloc(data->length);
+ if (data->data == NULL && data->length != 0) {
+ data->length = 0;
+ if (size)
+ *size = 0;
+ return ENOMEM;
+ }
+ memcpy(data->data, p, data->length);
+ }
+ if (size)
+ *size = len;
+ return 0;
+}
+
+static int
+generalizedtime2time (const char *s, time_t *t)
+{
+ struct tm tm;
+
+ memset(&tm, 0, sizeof(tm));
+ if (sscanf (s, "%04d%02d%02d%02d%02d%02dZ",
+ &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour,
+ &tm.tm_min, &tm.tm_sec) != 6) {
+ if (sscanf (s, "%02d%02d%02d%02d%02d%02dZ",
+ &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour,
+ &tm.tm_min, &tm.tm_sec) != 6)
+ return ASN1_BAD_TIMEFORMAT;
+ if (tm.tm_year < 50)
+ tm.tm_year += 2000;
+ else
+ tm.tm_year += 1900;
+ }
+ tm.tm_year -= 1900;
+ tm.tm_mon -= 1;
+ *t = _der_timegm (&tm);
+ return 0;
+}
+
+static int ASN1CALL
+der_get_time (const unsigned char *p, size_t len,
+ time_t *data, size_t *size)
+{
+ char *times;
+ int e;
+
+ assert(p != NULL);
+
+ if (size)
+ *size = 0;
+
+ if (len == SIZE_MAX || len == 0)
+ return ASN1_BAD_LENGTH;
+
+ times = malloc(len + 1);
+ if (times == NULL)
+ return ENOMEM;
+ memcpy(times, p, len);
+ times[len] = '\0';
+ e = generalizedtime2time(times, data);
+ free (times);
+ if(size) *size = len;
+ return e;
+}
+
+int ASN1CALL
+der_get_generalized_time (const unsigned char *p, size_t len,
+ time_t *data, size_t *size)
+{
+ return der_get_time(p, len, data, size);
+}
+
+int ASN1CALL
+der_get_utctime (const unsigned char *p, size_t len,
+ time_t *data, size_t *size)
+{
+ return der_get_time(p, len, data, size);
+}
+
+int ASN1CALL
+der_get_oid (const unsigned char *p, size_t len,
+ heim_oid *data, size_t *size)
+{
+ size_t n;
+ size_t oldlen = len;
+
+ assert(p != NULL);
+
+ if (size)
+ *size = 0;
+
+ if (len < 1)
+ return ASN1_OVERRUN;
+
+ if (len == SIZE_MAX)
+ return ASN1_BAD_LENGTH;
+
+ if (len + 1 > UINT_MAX/sizeof(data->components[0]))
+ return ERANGE;
+
+ data->components = malloc((len + 1) * sizeof(data->components[0]));
+ if (data->components == NULL) {
+ data->length = 0;
+ return ENOMEM;
+ }
+ data->components[0] = (*p) / 40;
+ data->components[1] = (*p) % 40;
+ --len;
+ ++p;
+ for (n = 2; len > 0; ++n) {
+ unsigned u = 0, u1;
+
+ do {
+ --len;
+ u1 = u * 128 + (*p++ % 128);
+ /* check that we don't overflow the element */
+ if (u1 < u) {
+ der_free_oid(data);
+ return ASN1_OVERRUN;
+ }
+ u = u1;
+ } while (len > 0 && p[-1] & 0x80);
+ data->components[n] = u;
+ }
+ if (n > 2 && p[-1] & 0x80) {
+ der_free_oid (data);
+ return ASN1_OVERRUN;
+ }
+ data->length = n;
+ if (size)
+ *size = oldlen;
+ return 0;
+}
+
+int ASN1CALL
+der_get_tag (const unsigned char *p, size_t len,
+ Der_class *cls, Der_type *type,
+ unsigned int *tag, size_t *size)
+{
+ size_t ret = 0;
+
+ if (size)
+ *size = 0;
+
+ if (len < 1)
+ return ASN1_MISSING_FIELD;
+
+ assert(p != NULL);
+
+ *cls = (Der_class)(((*p) >> 6) & 0x03);
+ *type = (Der_type)(((*p) >> 5) & 0x01);
+ *tag = (*p) & 0x1f;
+ p++; len--; ret++;
+ if(*tag == 0x1f) {
+ unsigned int continuation;
+ unsigned int tag1;
+ *tag = 0;
+ do {
+ if(len < 1)
+ return ASN1_OVERRUN;
+ continuation = *p & 128;
+ tag1 = *tag * 128 + (*p % 128);
+ /* check that we don't overflow the tag */
+ if (tag1 < *tag)
+ return ASN1_OVERFLOW;
+ *tag = tag1;
+ p++; len--; ret++;
+ } while(continuation);
+ }
+ if(size) *size = ret;
+ return 0;
+}
+
+int ASN1CALL
+der_match_tag (const unsigned char *p, size_t len,
+ Der_class cls, Der_type type,
+ unsigned int tag, size_t *size)
+{
+ Der_type thistype;
+ int e;
+
+ e = der_match_tag2(p, len, cls, &thistype, tag, size);
+ if (e) return e;
+ if (thistype != type) return ASN1_BAD_ID;
+ return 0;
+}
+
+int ASN1CALL
+der_match_tag2 (const unsigned char *p, size_t len,
+ Der_class cls, Der_type *type,
+ unsigned int tag, size_t *size)
+{
+ size_t l;
+ Der_class thisclass;
+ unsigned int thistag;
+ int e;
+
+ if (size)
+ *size = 0;
+
+ e = der_get_tag(p, len, &thisclass, type, &thistag, &l);
+ if (e) return e;
+ /*
+ * We do depend on ASN1_BAD_ID being returned in places where we're
+ * essentially implementing an application-level CHOICE where we try to
+ * decode one way then the other. In Heimdal this happens only in lib/hdb/
+ * where we try to decode a blob as an hdb_entry, then as an
+ * hdb_entry_alias. Applications should really not depend on this.
+ */
+ if (cls != thisclass && (cls == ASN1_C_APPL || thisclass == ASN1_C_APPL))
+ return ASN1_BAD_ID;
+ if (cls != thisclass || tag != thistag)
+ return ASN1_MISSING_FIELD;
+ if (size) *size = l;
+ return 0;
+}
+
+/*
+ * Returns 0 if the encoded data at `p' of length `len' starts with the tag of
+ * class `cls`, type `type', and tag value `tag', and puts the length of the
+ * payload (i.e., the length of V in TLV, not the length of TLV) in
+ * `*length_ret', and the size of the whole thing (the TLV) in `*size' if
+ * `size' is not NULL.
+ *
+ * Else returns an error.
+ */
+int ASN1CALL
+der_match_tag_and_length (const unsigned char *p, size_t len,
+ Der_class cls, Der_type *type, unsigned int tag,
+ size_t *length_ret, size_t *size)
+{
+ size_t l, ret = 0;
+ int e;
+
+ e = der_match_tag2 (p, len, cls, type, tag, &l);
+ if (e) return e;
+ p += l;
+ len -= l;
+ ret += l;
+ e = der_get_length (p, len, length_ret, &l);
+ if (e) return e;
+ if(size) *size = ret + l;
+ return 0;
+}
+
+
+
+/*
+ * Old versions of DCE was based on a very early beta of the MIT code,
+ * which used MAVROS for ASN.1 encoding. MAVROS had the interesting
+ * feature that it encoded data in the forward direction, which has
+ * it's problems, since you have no idea how long the data will be
+ * until after you're done. MAVROS solved this by reserving one byte
+ * for length, and later, if the actual length was longer, it reverted
+ * to indefinite, BER style, lengths. The version of MAVROS used by
+ * the DCE people could apparently generate correct X.509 DER encodings, and
+ * did this by making space for the length after encoding, but
+ * unfortunately this feature wasn't used with Kerberos.
+ */
+
+int
+_heim_fix_dce(size_t reallen, size_t *len)
+{
+ if(reallen == ASN1_INDEFINITE)
+ return 1;
+ if(*len < reallen)
+ return -1;
+ *len = reallen;
+ return 0;
+}
+
+int ASN1CALL
+der_get_bit_string (const unsigned char *p, size_t len,
+ heim_bit_string *data, size_t *size)
+{
+ assert(p != NULL);
+
+ if (size)
+ *size = 0;
+
+ if (len < 1)
+ return ASN1_OVERRUN;
+ if (p[0] > 7)
+ return ASN1_BAD_FORMAT;
+ if (len - 1 == 0 && p[0] != 0)
+ return ASN1_BAD_FORMAT;
+ /* check if any of the three upper bits are set
+ * any of them will cause a interger overrun */
+ if ((len - 1) >> (sizeof(len) * 8 - 3))
+ return ASN1_OVERRUN;
+ /*
+ * If there is data to copy, do that now.
+ */
+ if (len - 1 > 0) {
+ data->length = (len - 1) * 8;
+ data->data = malloc(len - 1);
+ if (data->data == NULL) {
+ data->length = 0;
+ return ENOMEM;
+ }
+ memcpy (data->data, p + 1, len - 1);
+ data->length -= p[0];
+ } else {
+ data->data = NULL;
+ data->length = 0;
+ }
+ if(size) *size = len;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/asn1/der_length.c b/third_party/heimdal/lib/asn1/der_length.c
new file mode 100644
index 0000000..9a99133
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/der_length.c
@@ -0,0 +1,305 @@
+/*
+ * Copyright (c) 1997-2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+
+RCSID("$Id$");
+
+size_t
+_heim_len_unsigned (unsigned val)
+{
+ size_t ret = 0;
+ int last_val_gt_128;
+
+ do {
+ ++ret;
+ last_val_gt_128 = (val >= 128);
+ val /= 256;
+ } while (val);
+
+ if(last_val_gt_128)
+ ret++;
+
+ return ret;
+}
+
+size_t
+_heim_len_unsigned64 (uint64_t val)
+{
+ size_t ret = 0;
+ int last_val_gt_128;
+
+ do {
+ ++ret;
+ last_val_gt_128 = (val >= 128);
+ val /= 256;
+ } while (val);
+
+ if(last_val_gt_128)
+ ret++;
+
+ return ret;
+}
+
+size_t
+_heim_len_int (int val)
+{
+ unsigned char q;
+ size_t ret = 0;
+
+ if (val >= 0) {
+ do {
+ q = val % 256;
+ ret++;
+ val /= 256;
+ } while(val);
+ if(q >= 128)
+ ret++;
+ } else {
+ val = ~val;
+ do {
+ q = ~(val % 256);
+ ret++;
+ val /= 256;
+ } while(val);
+ if(q < 128)
+ ret++;
+ }
+ return ret;
+}
+
+size_t
+_heim_len_int64 (int64_t val)
+{
+ unsigned char q;
+ size_t ret = 0;
+
+ if (val >= 0) {
+ do {
+ q = val % 256;
+ ret++;
+ val /= 256;
+ } while(val);
+ if(q >= 128)
+ ret++;
+ } else {
+ val = ~val;
+ do {
+ q = ~(val % 256);
+ ret++;
+ val /= 256;
+ } while(val);
+ if(q < 128)
+ ret++;
+ }
+ return ret;
+}
+
+static size_t
+len_oid (const heim_oid *oid)
+{
+ size_t ret = 1;
+ size_t n;
+
+ for (n = 2; n < oid->length; ++n) {
+ unsigned u = oid->components[n];
+
+ do {
+ ++ret;
+ u /= 128;
+ } while(u > 0);
+ }
+ return ret;
+}
+
+size_t ASN1CALL
+der_length_len (size_t len)
+{
+ if (len < 128)
+ return 1;
+ else {
+ int ret = 0;
+ do {
+ ++ret;
+ len /= 256;
+ } while (len);
+ return ret + 1;
+ }
+}
+
+size_t ASN1CALL
+der_length_tag(unsigned int tag)
+{
+ size_t len = 0;
+
+ if(tag <= 30)
+ return 1;
+ while(tag) {
+ tag /= 128;
+ len++;
+ }
+ return len + 1;
+}
+
+size_t ASN1CALL
+der_length_integer (const int *data)
+{
+ return _heim_len_int (*data);
+}
+
+size_t ASN1CALL
+der_length_integer64 (const int64_t *data)
+{
+ return _heim_len_int64 (*data);
+}
+
+size_t ASN1CALL
+der_length_unsigned (const unsigned *data)
+{
+ return _heim_len_unsigned(*data);
+}
+
+size_t ASN1CALL
+der_length_unsigned64 (const uint64_t *data)
+{
+ return _heim_len_unsigned64(*data);
+}
+
+size_t ASN1CALL
+der_length_enumerated (const unsigned *data)
+{
+ return _heim_len_int (*data);
+}
+
+size_t ASN1CALL
+der_length_general_string (const heim_general_string *data)
+{
+ return strlen(*data);
+}
+
+size_t ASN1CALL
+der_length_utf8string (const heim_utf8_string *data)
+{
+ return strlen(*data);
+}
+
+size_t ASN1CALL
+der_length_printable_string (const heim_printable_string *data)
+{
+ return data->length;
+}
+
+size_t ASN1CALL
+der_length_ia5_string (const heim_ia5_string *data)
+{
+ return data->length;
+}
+
+size_t ASN1CALL
+der_length_bmp_string (const heim_bmp_string *data)
+{
+ return data->length * 2;
+}
+
+size_t ASN1CALL
+der_length_universal_string (const heim_universal_string *data)
+{
+ return data->length * 4;
+}
+
+size_t ASN1CALL
+der_length_visible_string (const heim_visible_string *data)
+{
+ return strlen(*data);
+}
+
+size_t ASN1CALL
+der_length_octet_string (const heim_octet_string *k)
+{
+ return k->length;
+}
+
+size_t ASN1CALL
+der_length_heim_integer (const heim_integer *k)
+{
+ if (k->length == 0)
+ return 1;
+ if (k->negative)
+ return k->length + (((~(((unsigned char *)k->data)[0])) & 0x80) ? 0 : 1);
+ else
+ return k->length + ((((unsigned char *)k->data)[0] & 0x80) ? 1 : 0);
+}
+
+size_t ASN1CALL
+der_length_oid (const heim_oid *k)
+{
+ return len_oid (k);
+}
+
+size_t ASN1CALL
+der_length_generalized_time (const time_t *t)
+{
+ heim_octet_string k;
+ size_t ret;
+
+ _heim_time2generalizedtime (*t, &k, 1);
+ ret = k.length;
+ free(k.data);
+ return ret;
+}
+
+size_t ASN1CALL
+der_length_utctime (const time_t *t)
+{
+ heim_octet_string k;
+ size_t ret;
+
+ _heim_time2generalizedtime (*t, &k, 0);
+ ret = k.length;
+ free(k.data);
+ return ret;
+}
+
+size_t ASN1CALL
+der_length_boolean (const int *k)
+{
+ return 1;
+}
+
+size_t ASN1CALL
+der_length_bit_string (const heim_bit_string *k)
+{
+ return (k->length + 7) / 8 + 1;
+}
diff --git a/third_party/heimdal/lib/asn1/der_locl.h b/third_party/heimdal/lib/asn1/der_locl.h
new file mode 100644
index 0000000..a086e18
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/der_locl.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 1997 - 2002, 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __DER_LOCL_H__
+#define __DER_LOCL_H__
+
+
+#include <config.h>
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <ctype.h>
+#include <time.h>
+#include <errno.h>
+#include <roken.h>
+
+#include <asn1-common.h>
+#include <asn1_err.h>
+#include <der.h>
+#include <der-private.h>
+#include "asn1-template.h"
+
+time_t _der_timegm (struct tm *);
+struct tm * _der_gmtime(time_t t, struct tm *);
+size_t _heim_len_unsigned (unsigned);
+size_t _heim_len_int (int);
+
+#endif /* __DER_LOCL_H__ */
diff --git a/third_party/heimdal/lib/asn1/der_print.c b/third_party/heimdal/lib/asn1/der_print.c
new file mode 100644
index 0000000..1d45985
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/der_print.c
@@ -0,0 +1,229 @@
+/*
+ * Copyright (c) 2021 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+#include "hex.h"
+
+RCSID("$Id$");
+
+char * ASN1CALL
+der_print_general_string(const heim_general_string *str, int flags)
+{
+ return strdup(*str);
+}
+
+char * ASN1CALL
+der_print_boolean(const int *i, int flags)
+{
+ return *i ? strdup("true") : strdup("false");
+}
+
+char * ASN1CALL
+der_print_integer(const int *i, int flags)
+{
+ char *s = NULL;
+
+ if (asprintf(&s, "%d", *i) == -1 || s == NULL)
+ return NULL;
+ return s;
+}
+
+char * ASN1CALL
+der_print_integer64(const int64_t *i, int flags)
+{
+ char *s = NULL;
+
+ if (asprintf(&s, "%lld", (long long)*i) == -1 || s == NULL)
+ return NULL;
+ return s;
+}
+
+char * ASN1CALL
+der_print_unsigned(const unsigned *u, int flags)
+{
+ char *s = NULL;
+
+ if (asprintf(&s, "%u", *u) == -1 || s == NULL)
+ return NULL;
+ return s;
+}
+
+char * ASN1CALL
+der_print_unsigned64(const uint64_t *u, int flags)
+{
+ char *s = NULL;
+
+ if (asprintf(&s, "%llu", (long long)*u) == -1 || s == NULL)
+ return NULL;
+ return s;
+}
+
+char * ASN1CALL
+der_print_generalized_time(const time_t *t, int flags)
+{
+ struct tm tms;
+ char str[sizeof("1970-01-01T00:00:00Z")];
+
+#ifdef WIN32
+ if (gmtime_s(&tms, t) != 0 ||
+ strftime(str, sizeof(str), "%Y-%m-%dT%H:%M:%SZ", &tms) == 0)
+ return NULL;
+#else
+ if (strftime(str, sizeof(str), "%Y-%m-%dT%H:%M:%SZ", gmtime_r(t, &tms)) == 0)
+ return NULL;
+#endif
+ return strdup(str);
+}
+
+char * ASN1CALL
+der_print_utctime(const time_t *t, int flags)
+{
+ struct tm tms;
+ char str[sizeof("1970-01-01T00:00:00Z")];
+
+#ifdef WIN32
+ if (gmtime_s(&tms, t) != 0 ||
+ strftime(str, sizeof(str), "%Y-%m-%dT%H:%M:%SZ", &tms) == 0)
+ return NULL;
+#else
+ if (strftime(str, sizeof(str), "%Y-%m-%dT%H:%M:%SZ", gmtime_r(t, &tms)) == 0)
+ return NULL;
+#endif
+ return strdup(str);
+}
+
+
+char * ASN1CALL
+der_print_utf8string(const heim_utf8_string *str, int flags)
+{
+ return strdup(*str);
+}
+
+char * ASN1CALL
+der_print_printable_string(const heim_printable_string *str, int flags)
+{
+ return strndup(str->data, str->length);
+}
+
+char * ASN1CALL
+der_print_ia5_string(const heim_ia5_string *str, int flags)
+{
+ return strndup(str->data, str->length);
+}
+
+char * ASN1CALL
+der_print_bmp_string(const heim_bmp_string *k, int flags)
+{
+ return strdup("<BMPString-not-supported>");
+}
+
+char * ASN1CALL
+der_print_universal_string(const heim_universal_string *k, int flags)
+{
+ return strdup("<UniversalString-not-supported>");
+}
+
+char * ASN1CALL
+der_print_visible_string(const heim_visible_string *str, int flags)
+{
+ return strdup(*str);
+}
+
+char * ASN1CALL
+der_print_octet_string(const heim_octet_string *k, int flags)
+{
+ char *s = NULL;
+
+ (void) hex_encode(k->data, k->length, &s);
+ return s;
+}
+
+char * ASN1CALL
+der_print_heim_integer(const heim_integer *k, int flags)
+{
+ char *s = NULL;
+
+ (void) der_print_hex_heim_integer(k, &s);
+ return s;
+}
+
+char * ASN1CALL
+der_print_oid(const heim_oid *k, int flags)
+{
+ struct rk_strpool *r = NULL;
+ const char *sym = NULL;
+ char *s = NULL;
+ size_t i;
+
+ (void) der_print_heim_oid(k, '.', &s);
+
+ if (!s)
+ return NULL;
+ r = rk_strpoolprintf(r, "{\"_type\":\"OBJECT IDENTIFIER\","
+ "\"oid\":\"%s\","
+ "\"components\":[",
+ s);
+ free(s);
+ for (i = 0; i < k->length; i++)
+ r = rk_strpoolprintf(r, "%s%u", i ? "," : "", k->components[i]);
+ if (r)
+ r = rk_strpoolprintf(r, "]");
+ (void) der_find_heim_oid_by_oid(k, &sym);
+ if (sym && r) {
+ if ((s = strdup(sym))) {
+ for (i = 0; s[i]; i++)
+ if (s[i] == '_')
+ s[i] = '-';
+ }
+ r = rk_strpoolprintf(r, ",\"name\":\"%s\"", s ? s : sym);
+ free(s);
+ }
+ if (r)
+ r = rk_strpoolprintf(r, "}");
+ return rk_strpoolcollect(r);
+}
+
+char * ASN1CALL
+der_print_bit_string(const heim_bit_string *k, int flags)
+{
+ char *s2 = NULL;
+ char *s = NULL;
+
+ (void) hex_encode(k->data, k->length / 8, &s);
+ if (asprintf(&s2, "%llu:%s", (unsigned long long)k->length, s) == -1 || !s2)
+ return NULL;
+ free(s);
+ return s2;
+}
diff --git a/third_party/heimdal/lib/asn1/der_put.c b/third_party/heimdal/lib/asn1/der_put.c
new file mode 100644
index 0000000..8fbd6f3
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/der_put.c
@@ -0,0 +1,705 @@
+/*
+ * Copyright (c) 1997-2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+
+RCSID("$Id$");
+
+/*
+ * All encoding functions take a pointer `p' to first position in
+ * which to write, from the right, `len' which means the maximum
+ * number of characters we are able to write. The function returns
+ * the number of characters written in `size' (if non-NULL).
+ * The return value is 0 or an error.
+ */
+
+int ASN1CALL
+der_put_unsigned (unsigned char *p, size_t len, const unsigned *v, size_t *size)
+{
+ unsigned char *base = p;
+ unsigned val = *v;
+
+ *size = 0;
+
+ if (val) {
+ while (len > 0 && val) {
+ *p-- = val % 256;
+ val /= 256;
+ --len;
+ }
+ if (val != 0)
+ return ASN1_OVERFLOW;
+ else {
+ if(p[1] >= 128) {
+ if(len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = 0;
+ }
+ *size = base - p;
+ return 0;
+ }
+ } else if (len < 1)
+ return ASN1_OVERFLOW;
+ else {
+ *p = 0;
+ *size = 1;
+ return 0;
+ }
+}
+
+int ASN1CALL
+der_put_unsigned64 (unsigned char *p, size_t len, const uint64_t *v, size_t *size)
+{
+ unsigned char *base = p;
+ uint64_t val = *v;
+
+ *size = 0;
+
+ if (val) {
+ while (len > 0 && val) {
+ *p-- = val % 256;
+ val /= 256;
+ --len;
+ }
+ if (val != 0)
+ return ASN1_OVERFLOW;
+ else {
+ if(p[1] >= 128) {
+ if(len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = 0;
+ }
+ *size = base - p;
+ return 0;
+ }
+ } else if (len < 1)
+ return ASN1_OVERFLOW;
+ else {
+ *p = 0;
+ *size = 1;
+ return 0;
+ }
+}
+
+int ASN1CALL
+der_put_integer (unsigned char *p, size_t len, const int *v, size_t *size)
+{
+ unsigned char *base = p;
+ int val = *v;
+
+ *size = 0;
+
+ if(val >= 0) {
+ do {
+ if(len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = val % 256;
+ len--;
+ val /= 256;
+ } while(val);
+ if(p[1] >= 128) {
+ if(len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = 0;
+ len--;
+ }
+ } else {
+ val = ~val;
+ do {
+ if(len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = ~(val % 256);
+ len--;
+ val /= 256;
+ } while(val);
+ if(p[1] < 128) {
+ if(len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = 0xff;
+ len--;
+ }
+ }
+ *size = base - p;
+ return 0;
+}
+
+int ASN1CALL
+der_put_integer64 (unsigned char *p, size_t len, const int64_t *v, size_t *size)
+{
+ unsigned char *base = p;
+ int64_t val = *v;
+
+ *size = 0;
+
+ if(val >= 0) {
+ do {
+ if(len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = val % 256;
+ len--;
+ val /= 256;
+ } while(val);
+ if(p[1] >= 128) {
+ if(len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = 0;
+ len--;
+ }
+ } else {
+ val = ~val;
+ do {
+ if(len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = ~(val % 256);
+ len--;
+ val /= 256;
+ } while(val);
+ if(p[1] < 128) {
+ if(len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = 0xff;
+ len--;
+ }
+ }
+ *size = base - p;
+ return 0;
+}
+
+
+int ASN1CALL
+der_put_length (unsigned char *p, size_t len, size_t val, size_t *size)
+{
+ if (size)
+ *size = 0;
+
+ if (len < 1)
+ return ASN1_OVERFLOW;
+
+ if (val < 128) {
+ *p = val;
+ if (size)
+ *size = 1;
+ } else {
+ size_t l = 0;
+
+ while(val > 0) {
+ if(len < 2)
+ return ASN1_OVERFLOW;
+ *p-- = val % 256;
+ val /= 256;
+ len--;
+ l++;
+ }
+ *p = 0x80 | l;
+ if(size)
+ *size = l + 1;
+ }
+ return 0;
+}
+
+int ASN1CALL
+der_put_boolean(unsigned char *p, size_t len, const int *data, size_t *size)
+{
+ *size = 0;
+
+ if(len < 1)
+ return ASN1_OVERFLOW;
+ if(*data != 0)
+ *p = 0xff;
+ else
+ *p = 0;
+ *size = 1;
+ return 0;
+}
+
+int ASN1CALL
+der_put_general_string (unsigned char *p, size_t len,
+ const heim_general_string *str, size_t *size)
+{
+ size_t slen;
+
+ assert(p != NULL && str != NULL && *str != NULL && size != NULL);
+ *size = 0;
+ slen = strlen(*str);
+ if (len < slen)
+ return ASN1_OVERFLOW;
+ p -= slen;
+ memcpy (p+1, *str, slen);
+ *size = slen;
+ return 0;
+}
+
+int ASN1CALL
+der_put_utf8string (unsigned char *p, size_t len,
+ const heim_utf8_string *str, size_t *size)
+{
+ return der_put_general_string(p, len, str, size);
+}
+
+int ASN1CALL
+der_put_printable_string (unsigned char *p, size_t len,
+ const heim_printable_string *str, size_t *size)
+{
+ return der_put_octet_string(p, len, str, size);
+}
+
+int ASN1CALL
+der_put_ia5_string (unsigned char *p, size_t len,
+ const heim_ia5_string *str, size_t *size)
+{
+ return der_put_octet_string(p, len, str, size);
+}
+
+int ASN1CALL
+der_put_bmp_string (unsigned char *p, size_t len,
+ const heim_bmp_string *data, size_t *size)
+{
+ size_t i;
+
+ assert(p != NULL && data != NULL);
+
+ if (size)
+ *size = 0;
+
+ if (len / 2 < data->length)
+ return ASN1_OVERFLOW;
+ p -= data->length * 2;
+ for (i = 0; i < data->length; i++) {
+ p[1] = (data->data[i] >> 8) & 0xff;
+ p[2] = data->data[i] & 0xff;
+ p += 2;
+ }
+ if (size) *size = data->length * 2;
+ return 0;
+}
+
+int ASN1CALL
+der_put_universal_string (unsigned char *p, size_t len,
+ const heim_universal_string *data, size_t *size)
+{
+ size_t i;
+
+ if (size)
+ *size = 0;
+
+ if (len / 4 < data->length)
+ return ASN1_OVERFLOW;
+ p -= data->length * 4;
+ for (i = 0; i < data->length; i++) {
+ p[1] = (data->data[i] >> 24) & 0xff;
+ p[2] = (data->data[i] >> 16) & 0xff;
+ p[3] = (data->data[i] >> 8) & 0xff;
+ p[4] = data->data[i] & 0xff;
+ p += 4;
+ }
+ if (size) *size = data->length * 4;
+ return 0;
+}
+
+int ASN1CALL
+der_put_visible_string (unsigned char *p, size_t len,
+ const heim_visible_string *str, size_t *size)
+{
+ return der_put_general_string(p, len, str, size);
+}
+
+int ASN1CALL
+der_put_octet_string (unsigned char *p, size_t len,
+ const heim_octet_string *data, size_t *size)
+{
+ assert(p != NULL && data != NULL && size != NULL);
+
+ *size = 0;
+ if (len < data->length)
+ return ASN1_OVERFLOW;
+ p -= data->length;
+ memcpy (p+1, data->data, data->length);
+ *size = data->length;
+ return 0;
+}
+
+int ASN1CALL
+der_put_heim_integer (unsigned char *p, size_t len,
+ const heim_integer *data, size_t *size)
+{
+ unsigned char *buf;
+ int hibitset = 0;
+
+ assert(p != NULL);
+
+ if (size)
+ *size = 0;
+
+ if (data->length == 0) {
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = 0;
+ if (size)
+ *size = 1;
+ return 0;
+ }
+ if (len < data->length)
+ return ASN1_OVERFLOW;
+
+ assert(data->data != NULL);
+ buf = data->data;
+ len -= data->length;
+
+ if (data->negative) {
+ ssize_t i;
+ int carry;
+ for (i = data->length - 1, carry = 1; i >= 0; i--) {
+ *p = buf[i] ^ 0xff;
+ if (carry)
+ carry = !++*p;
+ p--;
+ }
+ if (p[1] < 128) {
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = 0xff;
+ len--;
+ hibitset = 1;
+ }
+ } else {
+ p -= data->length;
+ memcpy(p + 1, buf, data->length);
+
+ if (p[1] >= 128) {
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ p[0] = 0;
+ len--;
+ hibitset = 1;
+ }
+ }
+ if (size)
+ *size = data->length + hibitset;
+ return 0;
+}
+
+int ASN1CALL
+der_put_generalized_time (unsigned char *p, size_t len,
+ const time_t *data, size_t *size)
+{
+ heim_octet_string k;
+ size_t l;
+ int e;
+
+ e = _heim_time2generalizedtime (*data, &k, 1);
+ if (e)
+ return e;
+ e = der_put_octet_string(p, len, &k, &l);
+ free(k.data);
+ if(e)
+ return e;
+ if(size)
+ *size = l;
+ return 0;
+}
+
+int ASN1CALL
+der_put_utctime (unsigned char *p, size_t len,
+ const time_t *data, size_t *size)
+{
+ heim_octet_string k;
+ size_t l;
+ int e;
+
+ e = _heim_time2generalizedtime (*data, &k, 0);
+ if (e)
+ return e;
+ e = der_put_octet_string(p, len, &k, &l);
+ free(k.data);
+ if(e)
+ return e;
+ if(size)
+ *size = l;
+ return 0;
+}
+
+int ASN1CALL
+der_put_oid (unsigned char *p, size_t len,
+ const heim_oid *data, size_t *size)
+{
+ unsigned char *base = p;
+ size_t n;
+
+ for (n = data->length - 1; n >= 2; --n) {
+ unsigned u = data->components[n];
+
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = u % 128;
+ u /= 128;
+ --len;
+ while (u > 0) {
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = 128 + u % 128;
+ u /= 128;
+ --len;
+ }
+ }
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = 40 * data->components[0] + data->components[1];
+ *size = base - p;
+ return 0;
+}
+
+/*
+ * Output a copy of the DER TLV at `p' with a different outermost tag.
+ *
+ * This is used in the implementation of IMPLICIT tags in generated decoder
+ * functions.
+ */
+int ASN1CALL
+der_replace_tag(const unsigned char *p, size_t len,
+ unsigned char **out, size_t *outlen,
+ Der_class class, Der_type type,
+ unsigned int tag)
+{
+ Der_class found_class;
+ Der_type found_type;
+ unsigned int found_tag;
+ size_t payload_len, l, tag_len, len_len;
+ int e;
+
+ assert(p != NULL && out != NULL && outlen != NULL);
+
+ e = der_get_tag(p, len, &found_class, &found_type, &found_tag, &l);
+ if (e)
+ return e;
+ if (found_type != type)
+ return ASN1_TYPE_MISMATCH;
+ /* We don't care what found_class and found_tag are though */
+ tag_len = der_length_tag(tag);
+ p += l;
+ len -= l;
+ e = der_get_length(p, len, &payload_len, &len_len);
+ if (e)
+ return e;
+ if (payload_len > len)
+ return ASN1_OVERFLOW;
+ /*
+ * `p' now points at the payload; `*out' + the length of the tag points at
+ * where we should copy the DER length and the payload.
+ */
+ if ((*out = malloc(*outlen = tag_len + len_len + payload_len)) == NULL)
+ return ENOMEM;
+ memcpy(*out + tag_len, p, len_len + payload_len);
+
+ /* Put the new tag */
+ e = der_put_tag(*out + tag_len - 1, tag_len, class, type, tag, &l);
+ if (e)
+ return e;
+ if (l != tag_len)
+ return ASN1_OVERFLOW;
+ return 0;
+}
+
+#if 0
+int ASN1CALL
+der_encode_implicit(unsigned char *p, size_t len,
+ asn1_generic_encoder_f encoder,
+ void *obj, size_t *size,
+ Der_type type,
+ unsigned int ttag, Der_class iclass, unsigned int itag)
+{
+ size_t ttaglen = der_length_tag(ttag);
+ size_t itaglen = der_length_tag(itag);
+ size_t l;
+ unsigned char *p2;
+ int e;
+
+ assert(p != NULL && size != NULL);
+
+ /* Attempt to encode in place */
+ e = encoder(p, len, obj, size);
+ if (e == 0) {
+ /* Fits! Rewrite tag, adjust reported size. */
+ e = der_put_tag(p + ttaglen - 1, itaglen, iclass, type, itag, &l);
+ if (e == 0) {
+ (*size) -= ttaglen;
+ (*size) += itaglen;
+ }
+ return e;
+ }
+ if (e != ASN1_OVERFLOW || itaglen <= ttaglen)
+ return e;
+
+ /*
+ * Did not fit because ttaglen > itaglen and this was the last / only thing
+ * being encoded in a buffer of just the right size.
+ */
+ if ((p2 = malloc(len + ttaglen - itaglen)) == NULL)
+ e = ENOMEM;
+ if (e == 0)
+ e = encoder(p2 + len + ttaglen - itaglen - 1, len + ttaglen - itaglen,
+ obj, size);
+ if (e == 0)
+ e = der_put_tag(p2 + ttaglen - 1, itaglen, iclass, type, itag, &l);
+ if (e == 0) {
+ (*size) -= ttaglen;
+ (*size) += itaglen;
+ memcpy(p - *size, p2 + ttaglen - itaglen, *size);
+ }
+ free(p2);
+ return e;
+}
+#endif
+
+int ASN1CALL
+der_put_tag (unsigned char *p, size_t len, Der_class class, Der_type type,
+ unsigned int tag, size_t *size)
+{
+ if (tag <= 30) {
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ *p = MAKE_TAG(class, type, tag);
+ *size = 1;
+ } else {
+ size_t ret = 0;
+ unsigned int continuation = 0;
+
+ do {
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = tag % 128 | continuation;
+ len--;
+ ret++;
+ tag /= 128;
+ continuation = 0x80;
+ } while(tag > 0);
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = MAKE_TAG(class, type, 0x1f);
+ ret++;
+ *size = ret;
+ }
+ return 0;
+}
+
+int ASN1CALL
+der_put_length_and_tag (unsigned char *p, size_t len, size_t len_val,
+ Der_class class, Der_type type,
+ unsigned int tag, size_t *size)
+{
+ size_t ret = 0;
+ size_t l;
+ int e;
+
+ e = der_put_length (p, len, len_val, &l);
+ if(e)
+ return e;
+ p -= l;
+ len -= l;
+ ret += l;
+ e = der_put_tag (p, len, class, type, tag, &l);
+ if(e)
+ return e;
+
+ ret += l;
+ *size = ret;
+ return 0;
+}
+
+int
+_heim_time2generalizedtime (time_t t, heim_octet_string *s, int gtimep)
+{
+ struct tm tm;
+ const size_t len = gtimep ? 15 : 13;
+ int bytes;
+
+ s->data = NULL;
+ s->length = 0;
+ if (_der_gmtime(t, &tm) == NULL)
+ return ASN1_BAD_TIMEFORMAT;
+ s->data = malloc(len + 1);
+ if (s->data == NULL)
+ return ENOMEM;
+ s->length = len;
+ if (gtimep)
+ bytes = snprintf(s->data, len + 1, "%04d%02d%02d%02d%02d%02dZ",
+ tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
+ tm.tm_hour, tm.tm_min, tm.tm_sec);
+ else
+ bytes = snprintf(s->data, len + 1, "%02d%02d%02d%02d%02d%02dZ",
+ tm.tm_year % 100, tm.tm_mon + 1, tm.tm_mday,
+ tm.tm_hour, tm.tm_min, tm.tm_sec);
+
+ if (bytes > len)
+ abort();
+
+ return 0;
+}
+
+int ASN1CALL
+der_put_bit_string (unsigned char *p, size_t len,
+ const heim_bit_string *data, size_t *size)
+{
+ size_t data_size;
+
+ assert(p != NULL && data != NULL && size != NULL);
+
+ *size = 0;
+ data_size = (data->length + 7) / 8;
+ if (len < data_size + 1)
+ return ASN1_OVERFLOW;
+ p -= data_size + 1;
+
+ memcpy (p+2, data->data, data_size);
+ if (data->length && (data->length % 8) != 0)
+ p[1] = 8 - (data->length % 8);
+ else
+ p[1] = 0;
+ *size = data_size + 1;
+ return 0;
+}
+
+int
+_heim_der_set_sort(const void *a1, const void *a2)
+{
+ const heim_octet_string *s1, *s2;
+ int ret;
+
+ assert(a1 != NULL && a2 != NULL);
+ s1 = a1;
+ s2 = a2;
+ ret = memcmp(s1->data, s2->data,
+ s1->length < s2->length ? s1->length : s2->length);
+ if (ret != 0)
+ return ret;
+ return (int)(s1->length - s2->length);
+}
diff --git a/third_party/heimdal/lib/asn1/digest.asn1 b/third_party/heimdal/lib/asn1/digest.asn1
new file mode 100644
index 0000000..7a73993
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/digest.asn1
@@ -0,0 +1,179 @@
+-- $Id$
+
+DIGEST DEFINITIONS ::=
+BEGIN
+
+IMPORTS EncryptedData, Principal FROM krb5;
+
+DigestTypes ::= BIT STRING {
+ ntlm-v1(0),
+ ntlm-v1-session(1),
+ ntlm-v2(2),
+ digest-md5(3),
+ chap-md5(4),
+ ms-chap-v2(5)
+}
+
+DigestInit ::= SEQUENCE {
+ type UTF8String, -- http, sasl, chap, cram-md5 --
+ channel [0] SEQUENCE {
+ cb-type UTF8String,
+ cb-binding UTF8String
+ } OPTIONAL,
+ hostname [1] UTF8String OPTIONAL -- for chap/cram-md5
+}
+
+DigestInitReply ::= SEQUENCE {
+ nonce UTF8String, -- service nonce/challenge
+ opaque UTF8String, -- server state
+ identifier [0] UTF8String OPTIONAL
+}
+
+
+DigestRequest ::= SEQUENCE {
+ type UTF8String, -- http, sasl-md5, chap, cram-md5 --
+ digest UTF8String, -- http:md5/md5-sess sasl:clear/int/conf --
+ username UTF8String, -- username user used
+ responseData UTF8String, -- client response
+ authid [0] UTF8String OPTIONAL,
+ authentication-user [1] Principal OPTIONAL, -- principal to get key from
+ realm [2] UTF8String OPTIONAL,
+ method [3] UTF8String OPTIONAL,
+ uri [4] UTF8String OPTIONAL,
+ serverNonce UTF8String, -- same as "DigestInitReply.nonce"
+ clientNonce [5] UTF8String OPTIONAL,
+ nonceCount [6] UTF8String OPTIONAL,
+ qop [7] UTF8String OPTIONAL,
+ identifier [8] UTF8String OPTIONAL,
+ hostname [9] UTF8String OPTIONAL,
+ opaque UTF8String -- same as "DigestInitReply.opaque"
+}
+-- opaque = hex(cksum(type|serverNonce|identifier|hostname,digest-key))
+-- serverNonce = hex(time[4bytes]random[12bytes])(-cbType:cbBinding)
+
+
+DigestError ::= SEQUENCE {
+ reason UTF8String,
+ code INTEGER (-2147483648..2147483647)
+}
+
+DigestResponse ::= SEQUENCE {
+ success BOOLEAN,
+ rsp [0] UTF8String OPTIONAL,
+ tickets [1] SEQUENCE OF OCTET STRING OPTIONAL,
+ channel [2] SEQUENCE {
+ cb-type UTF8String,
+ cb-binding UTF8String
+ } OPTIONAL,
+ session-key [3] OCTET STRING OPTIONAL
+}
+
+NTLMInit ::= SEQUENCE {
+ flags [0] INTEGER (0..4294967295),
+ hostname [1] UTF8String OPTIONAL,
+ domain [1] UTF8String OPTIONAL
+}
+
+NTLMInitReply ::= SEQUENCE {
+ flags [0] INTEGER (0..4294967295),
+ opaque [1] OCTET STRING,
+ targetname [2] UTF8String,
+ challenge [3] OCTET STRING,
+ targetinfo [4] OCTET STRING OPTIONAL
+}
+
+NTLMRequest ::= SEQUENCE {
+ flags [0] INTEGER (0..4294967295),
+ opaque [1] OCTET STRING,
+ username [2] UTF8String,
+ targetname [3] UTF8String,
+ targetinfo [4] OCTET STRING OPTIONAL,
+ lm [5] OCTET STRING,
+ ntlm [6] OCTET STRING,
+ sessionkey [7] OCTET STRING OPTIONAL
+}
+
+NTLMResponse ::= SEQUENCE {
+ success [0] BOOLEAN,
+ flags [1] INTEGER (0..4294967295),
+ sessionkey [2] OCTET STRING OPTIONAL,
+ tickets [3] SEQUENCE OF OCTET STRING OPTIONAL
+}
+
+NTLMRequest2 ::= SEQUENCE {
+ loginUserName [0] UTF8String,
+ loginDomainName [1] UTF8String,
+ flags [2] INTEGER (0..4294967295),
+ lmchallenge [3] OCTET STRING SIZE (8),
+ ntChallengeResponce [4] OCTET STRING,
+ lmChallengeResponce [5] OCTET STRING
+}
+
+NTLMReply ::= SEQUENCE {
+ success [0] BOOLEAN,
+ flags [1] INTEGER (0..4294967295),
+ sessionkey [2] OCTET STRING OPTIONAL
+}
+
+DigestReqInner ::= CHOICE {
+ init [0] DigestInit,
+ digestRequest [1] DigestRequest,
+ ntlmInit [2] NTLMInit,
+ ntlmRequest [3] NTLMRequest,
+ supportedMechs [4] NULL
+}
+
+DigestREQ ::= [APPLICATION 128] SEQUENCE {
+ apReq [0] OCTET STRING,
+ innerReq [1] EncryptedData
+}
+
+DigestRepInner ::= CHOICE {
+ error [0] DigestError,
+ initReply [1] DigestInitReply,
+ response [2] DigestResponse,
+ ntlmInitReply [3] NTLMInitReply,
+ ntlmResponse [4] NTLMResponse,
+ supportedMechs [5] DigestTypes,
+ ...
+}
+
+DigestREP ::= [APPLICATION 129] SEQUENCE {
+ apRep [0] OCTET STRING,
+ innerRep [1] EncryptedData
+}
+
+
+-- HTTP
+
+-- md5
+-- A1 = unq(username-value) ":" unq(realm-value) ":" passwd
+-- md5-sess
+-- A1 = HEX(H(unq(username-value) ":" unq(realm-value) ":" passwd ) ":" unq(nonce-value) ":" unq(cnonce-value))
+
+-- qop == auth
+-- A2 = Method ":" digest-uri-value
+-- qop == auth-int
+-- A2 = Method ":" digest-uri-value ":" H(entity-body)
+
+-- request-digest = HEX(KD(HEX(H(A1)),
+-- unq(nonce-value) ":" nc-value ":" unq(cnonce-value) ":" unq(qop-value) ":" HEX(H(A2))))
+-- no "qop"
+-- request-digest = HEX(KD(HEX(H(A1)), unq(nonce-value) ":" HEX(H(A2))))
+
+
+-- SASL:
+-- SS = H( { unq(username-value), ":", unq(realm-value), ":", password } )
+-- A1 = { SS, ":", unq(nonce-value), ":", unq(cnonce-value) }
+-- A1 = { SS, ":", unq(nonce-value), ":", unq(cnonce-value), ":", unq(authzid-value) }
+
+-- A2 = "AUTHENTICATE:", ":", digest-uri-value
+-- qop == auth-int,auth-conf
+-- A2 = "AUTHENTICATE:", ":", digest-uri-value, ":00000000000000000000000000000000"
+
+-- response-value = HEX( KD ( HEX(H(A1)),
+-- { unq(nonce-value), ":" nc-value, ":",
+-- unq(cnonce-value), ":", qop-value, ":",
+-- HEX(H(A2)) }))
+
+END
diff --git a/third_party/heimdal/lib/asn1/extra.c b/third_party/heimdal/lib/asn1/extra.c
new file mode 100644
index 0000000..253ac5a
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/extra.c
@@ -0,0 +1,285 @@
+/*
+ * Copyright (c) 2003 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+#include "heim_asn1.h"
+#include <vis.h>
+#include <vis-extras.h>
+
+RCSID("$Id$");
+
+int ASN1CALL
+encode_heim_any(unsigned char *p, size_t len,
+ const heim_any *data, size_t *size)
+{
+ return der_put_octet_string (p, len, data, size);
+}
+
+int ASN1CALL
+decode_heim_any(const unsigned char *p, size_t len,
+ heim_any *data, size_t *size)
+{
+ size_t len_len, length, l;
+ Der_class thisclass;
+ Der_type thistype;
+ unsigned int thistag;
+ int e;
+
+ memset(data, 0, sizeof(*data));
+
+ e = der_get_tag (p, len, &thisclass, &thistype, &thistag, &l);
+ if (e) return e;
+ if (l > len)
+ return ASN1_OVERFLOW;
+ e = der_get_length(p + l, len - l, &length, &len_len);
+ if (e) return e;
+ if (length == ASN1_INDEFINITE) {
+ if (len < len_len + l)
+ return ASN1_OVERFLOW;
+ length = len - (len_len + l);
+ } else {
+ if (len < length + len_len + l)
+ return ASN1_OVERFLOW;
+ }
+
+ data->data = malloc(length + len_len + l);
+ if (data->data == NULL)
+ return ENOMEM;
+ data->length = length + len_len + l;
+ memcpy(data->data, p, length + len_len + l);
+
+ if (size)
+ *size = length + len_len + l;
+
+ return 0;
+}
+
+void ASN1CALL
+free_heim_any(heim_any *data)
+{
+ der_free_octet_string(data);
+}
+
+char * ASN1CALL
+print_heim_any(const heim_any *data, int flags)
+{
+ char *s2 = NULL;
+ char *s = der_print_octet_string(data, 0);
+ int r = -1;
+
+ (void)flags;
+ if (s)
+ r = rk_strasvis(&s2, s, VIS_CSTYLE|VIS_TAB|VIS_NL, "\"");
+ free(s);
+ s = NULL;
+ if (r > -1)
+ (void) asprintf(&s, "\"%s\"", s2);
+ free(s2);
+ return s;
+}
+
+size_t ASN1CALL
+length_heim_any(const heim_any *data)
+{
+ return data->length;
+}
+
+int ASN1CALL
+copy_heim_any(const heim_any *from, heim_any *to)
+{
+ return der_copy_octet_string(from, to);
+}
+
+int ASN1CALL
+encode_HEIM_ANY(unsigned char *p, size_t len,
+ const heim_any *data, size_t *size)
+{
+ return encode_heim_any(p, len, data, size);
+}
+
+int ASN1CALL
+decode_HEIM_ANY(const unsigned char *p, size_t len,
+ heim_any *data, size_t *size)
+{
+ return decode_heim_any(p, len, data, size);
+}
+
+void ASN1CALL
+free_HEIM_ANY(heim_any *data)
+{
+ der_free_octet_string(data);
+}
+
+char * ASN1CALL
+print_HEIM_ANY(const heim_any *data, int flags)
+{
+ char *s2 = NULL;
+ char *s = der_print_octet_string(data, 0);
+ int r = -1;
+
+ (void)flags;
+ if (s)
+ r = rk_strasvis(&s2, s, VIS_CSTYLE|VIS_TAB|VIS_NL, "\"");
+ free(s);
+ s = NULL;
+ if (r > -1)
+ (void) asprintf(&s, "\"%s\"", s2);
+ free(s2);
+ return s;
+}
+
+size_t ASN1CALL
+length_HEIM_ANY(const heim_any *data)
+{
+ return data->length;
+}
+
+int ASN1CALL
+copy_HEIM_ANY(const heim_any *from, heim_any *to)
+{
+ return der_copy_octet_string(from, to);
+}
+
+int ASN1CALL
+encode_heim_any_set(unsigned char *p, size_t len,
+ const heim_any_set *data, size_t *size)
+{
+ return der_put_octet_string (p, len, data, size);
+}
+
+int ASN1CALL
+decode_heim_any_set(const unsigned char *p, size_t len,
+ heim_any_set *data, size_t *size)
+{
+ return der_get_octet_string(p, len, data, size);
+}
+
+void ASN1CALL
+free_heim_any_set(heim_any_set *data)
+{
+ der_free_octet_string(data);
+}
+
+char * ASN1CALL
+print_heim_any_set(const heim_any_set *data, int flags)
+{
+ char *s2 = NULL;
+ char *s = der_print_octet_string(data, 0);
+ int r = -1;
+
+ (void)flags;
+ if (s)
+ r = rk_strasvis(&s2, s, VIS_CSTYLE|VIS_TAB|VIS_NL, "\"");
+ free(s);
+ s = NULL;
+ if (r > -1)
+ (void) asprintf(&s, "\"%s\"", s2);
+ free(s2);
+ return s;
+}
+
+size_t ASN1CALL
+length_heim_any_set(const heim_any *data)
+{
+ return data->length;
+}
+
+int ASN1CALL
+copy_heim_any_set(const heim_any_set *from, heim_any_set *to)
+{
+ return der_copy_octet_string(from, to);
+}
+
+int ASN1CALL
+heim_any_cmp(const heim_any_set *p, const heim_any_set *q)
+{
+ return der_heim_octet_string_cmp(p, q);
+}
+
+int ASN1CALL
+encode_HEIM_ANY_SET(unsigned char *p, size_t len,
+ const heim_any_set *data, size_t *size)
+{
+ return encode_heim_any_set(p, len, data, size);
+}
+
+int ASN1CALL
+decode_HEIM_ANY_SET(const unsigned char *p, size_t len,
+ heim_any_set *data, size_t *size)
+{
+ return decode_heim_any_set(p, len, data, size);
+}
+
+void ASN1CALL
+free_HEIM_ANY_SET(heim_any_set *data)
+{
+ der_free_octet_string(data);
+}
+
+char * ASN1CALL
+print_HEIM_ANY_SET(const heim_any_set *data, int flags)
+{
+ char *s2 = NULL;
+ char *s = der_print_octet_string(data, 0);
+ int r = -1;
+
+ (void)flags;
+ if (s)
+ r = rk_strasvis(&s2, s, VIS_CSTYLE|VIS_TAB|VIS_NL, "\"");
+ free(s);
+ s = NULL;
+ if (r > -1)
+ (void) asprintf(&s, "\"%s\"", s2);
+ free(s2);
+ return s;
+}
+
+size_t ASN1CALL
+length_HEIM_ANY_SET(const heim_any *data)
+{
+ return data->length;
+}
+
+int ASN1CALL
+copy_HEIM_ANY_SET(const heim_any_set *from, heim_any_set *to)
+{
+ return der_copy_octet_string(from, to);
+}
+
+int ASN1CALL
+HEIM_ANY_cmp(const heim_any_set *p, const heim_any_set *q)
+{
+ return der_heim_octet_string_cmp(p, q);
+}
diff --git a/third_party/heimdal/lib/asn1/fuzz-inputs/KrbFastArmoredReq b/third_party/heimdal/lib/asn1/fuzz-inputs/KrbFastArmoredReq
new file mode 100644
index 0000000..21ac360
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/fuzz-inputs/KrbFastArmoredReq
Binary files differ
diff --git a/third_party/heimdal/lib/asn1/fuzz-inputs/minimal-ek.crt b/third_party/heimdal/lib/asn1/fuzz-inputs/minimal-ek.crt
new file mode 100644
index 0000000..7e9bc70
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/fuzz-inputs/minimal-ek.crt
Binary files differ
diff --git a/third_party/heimdal/lib/asn1/fuzz-inputs/x690sample.der b/third_party/heimdal/lib/asn1/fuzz-inputs/x690sample.der
new file mode 100644
index 0000000..ec1c2c2
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/fuzz-inputs/x690sample.der
@@ -0,0 +1,5 @@
+`aJohnPSmith
+DirectorB3
+C19710917aMaryTSmithB1aRalphTSmith
+C195711111aSusanBSmith
+C19590717 \ No newline at end of file
diff --git a/third_party/heimdal/lib/asn1/fuzzer.c b/third_party/heimdal/lib/asn1/fuzzer.c
new file mode 100644
index 0000000..527f7e9
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/fuzzer.c
@@ -0,0 +1,742 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 - 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+#include <com_err.h>
+
+enum trigger_method { FOFF, FRANDOM, FLINEAR, FLINEAR_SIZE };
+
+#ifdef ASN1_FUZZER
+static enum trigger_method method = FOFF;
+
+/* FLINEAR */
+static unsigned long fnum, fcur, fsize;
+#endif
+
+int
+asn1_fuzzer_method(const char *mode)
+{
+#ifdef ASN1_FUZZER
+ if (mode == NULL || strcasecmp(mode, "off") == 0) {
+ method = FOFF;
+ } else if (strcasecmp(mode, "random") == 0) {
+ method = FRANDOM;
+ } else if (strcasecmp(mode, "linear") == 0) {
+ method = FLINEAR;
+ } else if (strcasecmp(mode, "linear-size") == 0) {
+ method = FLINEAR_SIZE;
+ } else
+ return 1;
+ return 0;
+#else
+ return 1;
+#endif
+}
+
+void
+asn1_fuzzer_reset(void)
+{
+#ifdef ASN1_FUZZER
+ fcur = 0;
+ fsize = 0;
+ fnum = 0;
+#endif
+}
+
+void
+asn1_fuzzer_next(void)
+{
+#ifdef ASN1_FUZZER
+ fcur = 0;
+ fsize = 0;
+ fnum++;
+#endif
+}
+
+int
+asn1_fuzzer_done(void)
+{
+#ifndef ASN1_FUZZER
+ abort();
+#else
+ /* since code paths */
+ return (fnum > 10000);
+#endif
+}
+
+#ifdef ASN1_FUZZER
+
+static int
+fuzzer_trigger(unsigned int chance)
+{
+ switch(method) {
+ case FOFF:
+ return 0;
+ case FRANDOM:
+ if ((rk_random() % chance) != 1)
+ return 0;
+ return 1;
+ case FLINEAR:
+ if (fnum == fcur++)
+ return 1;
+ return 0;
+ case FLINEAR_SIZE:
+ return 0;
+ }
+ return 0;
+}
+
+static int
+fuzzer_size_trigger(unsigned long *cur)
+{
+ if (method != FLINEAR_SIZE)
+ return 0;
+ if (fnum == (*cur)++)
+ return 1;
+ return 0;
+}
+
+static size_t
+fuzzer_length_len (size_t len)
+{
+ if (fuzzer_size_trigger(&fsize)) {
+ len = 0;
+ } else if (fuzzer_size_trigger(&fsize)) {
+ len = 129;
+ } else if (fuzzer_size_trigger(&fsize)) {
+ len = 0xffff;
+ }
+
+ if (len < 128)
+ return 1;
+ else {
+ int ret = 0;
+ do {
+ ++ret;
+ len /= 256;
+ } while (len);
+ return ret + 1;
+ }
+}
+
+static int
+fuzzer_put_length (unsigned char *p, size_t len, size_t val, size_t *size)
+{
+ if (len < 1)
+ return ASN1_OVERFLOW;
+
+ if (fuzzer_size_trigger(&fcur)) {
+ val = 0;
+ } else if (fuzzer_size_trigger(&fcur)) {
+ val = 129;
+ } else if (fuzzer_size_trigger(&fcur)) {
+ val = 0xffff;
+ }
+
+ if (val < 128) {
+ *p = val;
+ *size = 1;
+ } else {
+ size_t l = 0;
+
+ while(val > 0) {
+ if(len < 2)
+ return ASN1_OVERFLOW;
+ *p-- = val % 256;
+ val /= 256;
+ len--;
+ l++;
+ }
+ *p = 0x80 | l;
+ if(size)
+ *size = l + 1;
+ }
+ return 0;
+}
+
+static int
+fuzzer_put_tag (unsigned char *p, size_t len, Der_class class, Der_type type,
+ unsigned int tag, size_t *size)
+{
+ unsigned fcont = 0;
+
+ if (tag <= 30) {
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ if (fuzzer_trigger(100))
+ *p = MAKE_TAG(class, type, 0x1f);
+ else
+ *p = MAKE_TAG(class, type, tag);
+ *size = 1;
+ } else {
+ size_t ret = 0;
+ unsigned int continuation = 0;
+
+ do {
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = tag % 128 | continuation;
+ len--;
+ ret++;
+ tag /= 128;
+ continuation = 0x80;
+ } while(tag > 0);
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ if (fuzzer_trigger(100))
+ *p-- = MAKE_TAG(class, type, 0);
+ else
+ *p-- = MAKE_TAG(class, type, 0x1f);
+ ret++;
+ *size = ret;
+ }
+ return 0;
+}
+
+static int
+fuzzer_put_length_and_tag (unsigned char *p, size_t len, size_t len_val,
+ Der_class class, Der_type type,
+ unsigned int tag, size_t *size)
+{
+ size_t ret = 0;
+ size_t l;
+ int e;
+
+ e = fuzzer_put_length (p, len, len_val, &l);
+ if(e)
+ return e;
+ p -= l;
+ len -= l;
+ ret += l;
+ e = fuzzer_put_tag (p, len, class, type, tag, &l);
+ if(e)
+ return e;
+
+ ret += l;
+ *size = ret;
+ return 0;
+}
+
+static int
+fuzzer_put_general_string (unsigned char *p, size_t len,
+ const heim_general_string *str, size_t *size)
+{
+ size_t slen = strlen(*str);
+
+ if (len < slen)
+ return ASN1_OVERFLOW;
+ p -= slen;
+ if (slen >= 2 && fuzzer_trigger(100)) {
+ memcpy(p+1, *str, slen);
+ memcpy(p+1, "%s", 2);
+ } else if (slen >= 2 && fuzzer_trigger(100)) {
+ memcpy(p+1, *str, slen);
+ memcpy(p+1, "%n", 2);
+ } else if (slen >= 4 && fuzzer_trigger(100)) {
+ memcpy(p+1, *str, slen);
+ memcpy(p+1, "%10n", 4);
+ } else if (slen >= 10 && fuzzer_trigger(100)) {
+ memcpy(p+1, *str, slen);
+ memcpy(p+1, "%n%n%n%n%n", 10);
+ } else if (slen >= 10 && fuzzer_trigger(100)) {
+ memcpy(p+1, *str, slen);
+ memcpy(p+1, "%n%p%s%d%x", 10);
+ } else if (slen >= 7 && fuzzer_trigger(100)) {
+ memcpy(p+1, *str, slen);
+ memcpy(p+1, "%.1024d", 7);
+ } else if (slen >= 7 && fuzzer_trigger(100)) {
+ memcpy(p+1, *str, slen);
+ memcpy(p+1, "%.2049d", 7);
+ } else if (fuzzer_trigger(100)) {
+ memset(p+1, 0, slen);
+ } else if (fuzzer_trigger(100)) {
+ memset(p+1, 0xff, slen);
+ } else if (fuzzer_trigger(100)) {
+ memset(p+1, 'A', slen);
+ } else {
+ memcpy(p+1, *str, slen);
+ }
+ *size = slen;
+ return 0;
+}
+
+
+struct asn1_type_func fuzzerprim[A1T_NUM_ENTRY] = {
+#define fuzel(name, type) { \
+ (asn1_type_encode)fuzzer_put_##name, \
+ (asn1_type_decode)der_get_##name, \
+ (asn1_type_length)der_length_##name, \
+ (asn1_type_copy)der_copy_##name, \
+ (asn1_type_release)der_free_##name, \
+ sizeof(type) \
+ }
+#define el(name, type) { \
+ (asn1_type_encode)der_put_##name, \
+ (asn1_type_decode)der_get_##name, \
+ (asn1_type_length)der_length_##name, \
+ (asn1_type_copy)der_copy_##name, \
+ (asn1_type_release)der_free_##name, \
+ sizeof(type) \
+ }
+#define elber(name, type) { \
+ (asn1_type_encode)der_put_##name, \
+ (asn1_type_decode)der_get_##name##_ber, \
+ (asn1_type_length)der_length_##name, \
+ (asn1_type_copy)der_copy_##name, \
+ (asn1_type_release)der_free_##name, \
+ sizeof(type) \
+ }
+ el(integer, int),
+ el(integer64, int64_t),
+ el(heim_integer, heim_integer),
+ el(integer, int),
+ el(unsigned, unsigned),
+ el(uninteger64, uint64_t),
+ fuzel(general_string, heim_general_string),
+ el(octet_string, heim_octet_string),
+ elber(octet_string, heim_octet_string),
+ el(ia5_string, heim_ia5_string),
+ el(bmp_string, heim_bmp_string),
+ el(universal_string, heim_universal_string),
+ el(printable_string, heim_printable_string),
+ el(visible_string, heim_visible_string),
+ el(utf8string, heim_utf8_string),
+ el(generalized_time, time_t),
+ el(utctime, time_t),
+ el(bit_string, heim_bit_string),
+ { (asn1_type_encode)der_put_boolean, (asn1_type_decode)der_get_boolean,
+ (asn1_type_length)der_length_boolean, (asn1_type_copy)der_copy_integer,
+ (asn1_type_release)der_free_integer, sizeof(int)
+ },
+ el(oid, heim_oid),
+ el(general_string, heim_general_string),
+#undef fuzel
+#undef el
+#undef elber
+};
+
+
+
+int
+_asn1_encode_fuzzer(const struct asn1_template *t,
+ unsigned char *p, size_t len,
+ const void *data, size_t *size)
+{
+ size_t elements = A1_HEADER_LEN(t);
+ int ret = 0;
+ size_t oldlen = len;
+
+ t += A1_HEADER_LEN(t);
+
+ while (elements) {
+ switch (t->tt & A1_OP_MASK) {
+ case A1_OP_TYPE:
+ case A1_OP_TYPE_EXTERN: {
+ size_t newsize;
+ const void *el = DPOC(data, t->offset);
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ void **pel = (void **)el;
+ if (*pel == NULL)
+ break;
+ el = *pel;
+ }
+
+ if ((t->tt & A1_OP_MASK) == A1_OP_TYPE) {
+ ret = _asn1_encode_fuzzer(t->ptr, p, len, el, &newsize);
+ } else {
+ const struct asn1_type_func *f = t->ptr;
+ ret = (f->encode)(p, len, el, &newsize);
+ }
+
+ if (ret)
+ return ret;
+ p -= newsize; len -= newsize;
+
+ break;
+ }
+ case A1_OP_TAG: {
+ const void *olddata = data;
+ size_t l, datalen;
+
+ data = DPOC(data, t->offset);
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ void **el = (void **)data;
+ if (*el == NULL) {
+ data = olddata;
+ break;
+ }
+ data = *el;
+ }
+
+ ret = _asn1_encode_fuzzer(t->ptr, p, len, data, &datalen);
+ if (ret)
+ return ret;
+
+ len -= datalen; p -= datalen;
+
+ ret = fuzzer_put_length_and_tag(p, len, datalen,
+ A1_TAG_CLASS(t->tt),
+ A1_TAG_TYPE(t->tt),
+ A1_TAG_TAG(t->tt), &l);
+ if (ret)
+ return ret;
+
+ p -= l; len -= l;
+
+ data = olddata;
+
+ break;
+ }
+ case A1_OP_PARSE: {
+ unsigned int type = A1_PARSE_TYPE(t->tt);
+ size_t newsize;
+ const void *el = DPOC(data, t->offset);
+
+ if (type > sizeof(fuzzerprim)/sizeof(fuzzerprim[0])) {
+ ABORT_ON_ERROR();
+ return ASN1_PARSE_ERROR;
+ }
+
+ ret = (fuzzerprim[type].encode)(p, len, el, &newsize);
+ if (ret)
+ return ret;
+ p -= newsize; len -= newsize;
+
+ break;
+ }
+ case A1_OP_SETOF: {
+ const struct template_of *el = DPOC(data, t->offset);
+ size_t ellen = _asn1_sizeofType(t->ptr);
+ heim_octet_string *val;
+ unsigned char *elptr = el->val;
+ size_t i, totallen;
+
+ if (el->len == 0)
+ break;
+
+ if (el->len > UINT_MAX/sizeof(val[0]))
+ return ERANGE;
+
+ val = malloc(sizeof(val[0]) * el->len);
+ if (val == NULL)
+ return ENOMEM;
+
+ for(totallen = 0, i = 0; i < el->len; i++) {
+ unsigned char *next;
+ size_t l;
+
+ val[i].length = _asn1_length(t->ptr, elptr);
+ val[i].data = malloc(val[i].length);
+
+ ret = _asn1_encode_fuzzer(t->ptr, DPO(val[i].data, val[i].length - 1),
+ val[i].length, elptr, &l);
+ if (ret)
+ break;
+
+ next = elptr + ellen;
+ if (next < elptr) {
+ ret = ASN1_OVERFLOW;
+ break;
+ }
+ elptr = next;
+ totallen += val[i].length;
+ }
+ if (ret == 0 && totallen > len)
+ ret = ASN1_OVERFLOW;
+ if (ret) {
+ do {
+ free(val[i].data);
+ } while(i-- > 0);
+ free(val);
+ return ret;
+ }
+
+ len -= totallen;
+
+ qsort(val, el->len, sizeof(val[0]), _heim_der_set_sort);
+
+ i = el->len - 1;
+ do {
+ p -= val[i].length;
+ memcpy(p + 1, val[i].data, val[i].length);
+ free(val[i].data);
+ } while(i-- > 0);
+ free(val);
+
+ break;
+
+ }
+ case A1_OP_SEQOF: {
+ struct template_of *el = DPO(data, t->offset);
+ size_t ellen = _asn1_sizeofType(t->ptr);
+ size_t newsize;
+ unsigned int i;
+ unsigned char *elptr = el->val;
+
+ if (el->len == 0)
+ break;
+
+ elptr += ellen * (el->len - 1);
+
+ for (i = 0; i < el->len; i++) {
+ ret = _asn1_encode_fuzzer(t->ptr, p, len,
+ elptr,
+ &newsize);
+ if (ret)
+ return ret;
+ p -= newsize; len -= newsize;
+ elptr -= ellen;
+ }
+
+ break;
+ }
+ case A1_OP_BMEMBER: {
+ const struct asn1_template *bmember = t->ptr;
+ size_t size = bmember->offset;
+ size_t elements = A1_HEADER_LEN(bmember);
+ size_t pos;
+ unsigned char c = 0;
+ unsigned int bitset = 0;
+ int rfc1510 = (bmember->tt & A1_HBF_RFC1510);
+
+ bmember += elements;
+
+ if (rfc1510)
+ pos = 31;
+ else
+ pos = bmember->offset;
+
+ while (elements && len) {
+ while (bmember->offset / 8 < pos / 8) {
+ if (rfc1510 || bitset || c) {
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = c; len--;
+ }
+ c = 0;
+ pos -= 8;
+ }
+ _asn1_bmember_put_bit(&c, data, bmember->offset, size, &bitset);
+ elements--; bmember--;
+ }
+ if (rfc1510 || bitset) {
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = c; len--;
+ }
+
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ if (rfc1510 || bitset == 0)
+ *p-- = 0;
+ else
+ *p-- = bitset - 1;
+
+ len--;
+
+ break;
+ }
+ case A1_OP_CHOICE: {
+ const struct asn1_template *choice = t->ptr;
+ const unsigned int *element = DPOC(data, choice->offset);
+ size_t datalen;
+ const void *el;
+
+ if (*element > A1_HEADER_LEN(choice)) {
+ printf("element: %d\n", *element);
+ return ASN1_PARSE_ERROR;
+ }
+
+ if (*element == 0) {
+ ret += der_put_octet_string(p, len,
+ DPOC(data, choice->tt), &datalen);
+ } else {
+ choice += *element;
+ el = DPOC(data, choice->offset);
+ ret = _asn1_encode_fuzzer(choice->ptr, p, len, el, &datalen);
+ if (ret)
+ return ret;
+ }
+ len -= datalen; p -= datalen;
+
+ break;
+ }
+ default:
+ ABORT_ON_ERROR();
+ }
+ t--;
+ elements--;
+ }
+
+ if (fuzzer_trigger(1000)) {
+ memset(p + 1, 0, oldlen - len);
+ } else if (fuzzer_trigger(1000)) {
+ memset(p + 1, 0x41, oldlen - len);
+ } else if (fuzzer_trigger(1000)) {
+ memset(p + 1, 0xff, oldlen - len);
+ }
+
+ if (size)
+ *size = oldlen - len;
+
+ return 0;
+}
+
+size_t
+_asn1_length_fuzzer(const struct asn1_template *t, const void *data)
+{
+ size_t elements = A1_HEADER_LEN(t);
+ size_t ret = 0;
+
+ t += A1_HEADER_LEN(t);
+
+ while (elements) {
+ switch (t->tt & A1_OP_MASK) {
+ case A1_OP_TYPE:
+ case A1_OP_TYPE_EXTERN: {
+ const void *el = DPOC(data, t->offset);
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ void **pel = (void **)el;
+ if (*pel == NULL)
+ break;
+ el = *pel;
+ }
+
+ if ((t->tt & A1_OP_MASK) == A1_OP_TYPE) {
+ ret += _asn1_length(t->ptr, el);
+ } else {
+ const struct asn1_type_func *f = t->ptr;
+ ret += (f->length)(el);
+ }
+ break;
+ }
+ case A1_OP_TAG: {
+ size_t datalen;
+ const void *olddata = data;
+
+ data = DPO(data, t->offset);
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ void **el = (void **)data;
+ if (*el == NULL) {
+ data = olddata;
+ break;
+ }
+ data = *el;
+ }
+ datalen = _asn1_length(t->ptr, data);
+ ret += der_length_tag(A1_TAG_TAG(t->tt)) + fuzzer_length_len(datalen);
+ ret += datalen;
+ data = olddata;
+ break;
+ }
+ case A1_OP_PARSE: {
+ unsigned int type = A1_PARSE_TYPE(t->tt);
+ const void *el = DPOC(data, t->offset);
+
+ if (type >= sizeof(asn1_template_prim)/sizeof(asn1_template_prim[0])) {
+ ABORT_ON_ERROR();
+ break;
+ }
+ ret += (asn1_template_prim[type].length)(el);
+ break;
+ }
+ case A1_OP_SETOF:
+ case A1_OP_SEQOF: {
+ const struct template_of *el = DPOC(data, t->offset);
+ size_t ellen = _asn1_sizeofType(t->ptr);
+ const unsigned char *element = el->val;
+ unsigned int i;
+
+ for (i = 0; i < el->len; i++) {
+ ret += _asn1_length(t->ptr, element);
+ element += ellen;
+ }
+
+ break;
+ }
+ case A1_OP_BMEMBER: {
+ const struct asn1_template *bmember = t->ptr;
+ size_t size = bmember->offset;
+ size_t elements = A1_HEADER_LEN(bmember);
+ int rfc1510 = (bmember->tt & A1_HBF_RFC1510);
+
+ if (rfc1510) {
+ ret += 5;
+ } else {
+
+ ret += 1;
+
+ bmember += elements;
+
+ while (elements) {
+ if (_asn1_bmember_isset_bit(data, bmember->offset, size)) {
+ ret += (bmember->offset / 8) + 1;
+ break;
+ }
+ elements--; bmember--;
+ }
+ }
+ break;
+ }
+ case A1_OP_CHOICE: {
+ const struct asn1_template *choice = t->ptr;
+ const unsigned int *element = DPOC(data, choice->offset);
+
+ if (*element > A1_HEADER_LEN(choice))
+ break;
+
+ if (*element == 0) {
+ ret += der_length_octet_string(DPOC(data, choice->tt));
+ } else {
+ choice += *element;
+ ret += _asn1_length(choice->ptr, DPOC(data, choice->offset));
+ }
+ break;
+ }
+ default:
+ ABORT_ON_ERROR();
+ break;
+ }
+ elements--;
+ t--;
+ }
+ return ret;
+}
+
+#endif /* ASN1_FUZZER */
diff --git a/third_party/heimdal/lib/asn1/gen.c b/third_party/heimdal/lib/asn1/gen.c
new file mode 100644
index 0000000..10153c6
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/gen.c
@@ -0,0 +1,2016 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gen_locl.h"
+
+extern const char *enum_prefix;
+extern int prefix_enum;
+
+RCSID("$Id$");
+
+FILE *jsonfile, *privheaderfile, *headerfile, *oidsfile, *codefile, *logfile, *templatefile;
+FILE *symsfile;
+
+#define STEM "asn1"
+
+static const char *orig_filename;
+static char *privheader, *header, *template;
+static const char *headerbase = STEM;
+
+/* XXX same as der_length_tag */
+static size_t
+length_tag(unsigned int tag)
+{
+ size_t len = 0;
+
+ if(tag <= 30)
+ return 1;
+ while(tag) {
+ tag /= 128;
+ len++;
+ }
+ return len + 1;
+}
+
+/*
+ * list of all IMPORTs
+ */
+
+struct import {
+ const char *module;
+ struct import *next;
+};
+
+static struct import *imports = NULL;
+
+void
+add_import (const char *module)
+{
+ struct import *tmp = emalloc (sizeof(*tmp));
+
+ tmp->module = module;
+ tmp->next = imports;
+ imports = tmp;
+
+ fprintf (headerfile, "#include <%s_asn1.h>\n", module);
+ fprintf(jsonfile, "{\"imports\":\"%s\"}\n", module);
+}
+
+/*
+ * List of all exported symbols
+ *
+ * XXX A hash table would be nice here.
+ */
+
+struct sexport {
+ const char *name;
+ int defined;
+ struct sexport *next;
+};
+
+static struct sexport *exports = NULL;
+
+void
+add_export (const char *name)
+{
+ struct sexport *tmp = emalloc (sizeof(*tmp));
+
+ tmp->name = name;
+ tmp->next = exports;
+ exports = tmp;
+}
+
+int
+is_export(const char *name)
+{
+ struct sexport *tmp;
+
+ if (exports == NULL) /* no export list, all exported */
+ return 1;
+
+ for (tmp = exports; tmp != NULL; tmp = tmp->next) {
+ if (strcmp(tmp->name, name) == 0) {
+ tmp->defined = 1;
+ return 1;
+ }
+ }
+ return 0;
+}
+
+const char *
+get_filename (void)
+{
+ return orig_filename;
+}
+
+void
+init_generate (const char *filename, const char *base)
+{
+ char *fn = NULL;
+
+ orig_filename = filename;
+ if (base != NULL) {
+ headerbase = strdup(base);
+ if (headerbase == NULL)
+ errx(1, "strdup");
+ }
+
+ /* JSON file */
+ if (asprintf(&fn, "%s.json", headerbase) < 0 || fn == NULL)
+ errx(1, "malloc");
+ jsonfile = fopen(fn, "w");
+ if (jsonfile == NULL)
+ err(1, "open %s", fn);
+ free(fn);
+ fn = NULL;
+
+ /* public header file */
+ if (asprintf(&header, "%s.h", headerbase) < 0 || header == NULL)
+ errx(1, "malloc");
+ if (asprintf(&fn, "%s.h", headerbase) < 0 || fn == NULL)
+ errx(1, "malloc");
+ headerfile = fopen (fn, "w");
+ if (headerfile == NULL)
+ err (1, "open %s", fn);
+ free(fn);
+ fn = NULL;
+
+ /* private header file */
+ if (asprintf(&privheader, "%s-priv.h", headerbase) < 0 || privheader == NULL)
+ errx(1, "malloc");
+ if (asprintf(&fn, "%s-priv.h", headerbase) < 0 || fn == NULL)
+ errx(1, "malloc");
+ privheaderfile = fopen (fn, "w");
+ if (privheaderfile == NULL)
+ err (1, "open %s", fn);
+ free(fn);
+ fn = NULL;
+
+ /* template file */
+ if (asprintf(&template, "%s-template.c", headerbase) < 0 || template == NULL)
+ errx(1, "malloc");
+ fprintf (headerfile,
+ "/* Generated from %s */\n"
+ "/* Do not edit */\n\n",
+ filename);
+ fprintf (headerfile,
+ "#ifndef __%s_h__\n"
+ "#define __%s_h__\n\n", headerbase, headerbase);
+ fprintf (headerfile,
+ "#include <stddef.h>\n"
+ "#include <stdint.h>\n"
+ "#include <time.h>\n\n");
+ fprintf (headerfile,
+ "#ifndef __asn1_common_definitions__\n"
+ "#define __asn1_common_definitions__\n\n");
+ fprintf (headerfile,
+ "#ifndef __HEIM_BASE_DATA__\n"
+ "#define __HEIM_BASE_DATA__ 1\n"
+ "struct heim_base_data {\n"
+ " size_t length;\n"
+ " void *data;\n"
+ "};\n"
+ "typedef struct heim_base_data heim_octet_string;\n"
+ "#endif\n\n");
+ fprintf (headerfile,
+ "typedef struct heim_integer {\n"
+ " size_t length;\n"
+ " void *data;\n"
+ " int negative;\n"
+ "} heim_integer;\n\n");
+ fprintf (headerfile,
+ "typedef char *heim_general_string;\n\n"
+ );
+ fprintf (headerfile,
+ "typedef char *heim_utf8_string;\n\n"
+ );
+ fprintf (headerfile,
+ "typedef struct heim_base_data heim_printable_string;\n\n"
+ );
+ fprintf (headerfile,
+ "typedef struct heim_base_data heim_ia5_string;\n\n"
+ );
+ fprintf (headerfile,
+ "typedef struct heim_bmp_string {\n"
+ " size_t length;\n"
+ " uint16_t *data;\n"
+ "} heim_bmp_string;\n\n");
+ fprintf (headerfile,
+ "typedef struct heim_universal_string {\n"
+ " size_t length;\n"
+ " uint32_t *data;\n"
+ "} heim_universal_string;\n\n");
+ fprintf (headerfile,
+ "typedef char *heim_visible_string;\n\n"
+ );
+ fprintf (headerfile,
+ "typedef struct heim_oid {\n"
+ " size_t length;\n"
+ " unsigned *components;\n"
+ "} heim_oid;\n\n");
+ fprintf (headerfile,
+ "typedef struct heim_bit_string {\n"
+ " size_t length;\n"
+ " void *data;\n"
+ "} heim_bit_string;\n\n");
+ fprintf (headerfile,
+ "typedef struct heim_base_data heim_any;\n"
+ "typedef struct heim_base_data heim_any_set;\n"
+ "typedef struct heim_base_data HEIM_ANY;\n"
+ "typedef struct heim_base_data HEIM_ANY_SET;\n\n");
+
+ fprintf (headerfile,
+ "enum asn1_print_flags {\n"
+ " ASN1_PRINT_INDENT = 1,\n"
+ "};\n\n");
+ fputs("#define ASN1_MALLOC_ENCODE(T, B, BL, S, L, R) \\\n"
+ " do { \\\n"
+ " (BL) = length_##T((S)); \\\n"
+ " (B) = calloc(1, (BL)); \\\n"
+ " if((B) == NULL) { \\\n"
+ " *(L) = 0; \\\n"
+ " (R) = ENOMEM; \\\n"
+ " } else { \\\n"
+ " (R) = encode_##T(((unsigned char*)(B)) + (BL) - 1, (BL), \\\n"
+ " (S), (L)); \\\n"
+ " if((R) != 0) { \\\n"
+ " free((B)); \\\n"
+ " (B) = NULL; \\\n"
+ " *(L) = 0; \\\n"
+ " } \\\n"
+ " } \\\n"
+ " } while (0)\n\n",
+ headerfile);
+ fputs("#ifdef _WIN32\n"
+ "#ifndef ASN1_LIB\n"
+ "#define ASN1EXP __declspec(dllimport)\n"
+ "#else\n"
+ "#define ASN1EXP\n"
+ "#endif\n"
+ "#define ASN1CALL __stdcall\n"
+ "#else\n"
+ "#define ASN1EXP\n"
+ "#define ASN1CALL\n"
+ "#endif\n",
+ headerfile);
+ fputs("#ifndef ENOTSUP\n"
+ "/* Very old MSVC CRTs lack ENOTSUP */\n"
+ "#define ENOTSUP EINVAL\n"
+ "#endif\n",
+ headerfile);
+ fprintf (headerfile, "struct units;\n\n");
+ fprintf (headerfile, "#endif\n\n");
+ if (asprintf(&fn, "%s_files", base) < 0 || fn == NULL)
+ errx(1, "malloc");
+ logfile = fopen(fn, "w");
+ if (logfile == NULL)
+ err (1, "open %s", fn);
+ free(fn);
+ fn = NULL;
+
+ if (asprintf(&fn, "%s_oids.c", base) < 0 || fn == NULL)
+ errx(1, "malloc");
+ oidsfile = fopen(fn, "w");
+ if (oidsfile == NULL)
+ err (1, "open %s", fn);
+ if (asprintf(&fn, "%s_syms.c", base) < 0 || fn == NULL)
+ errx(1, "malloc");
+ symsfile = fopen(fn, "w");
+ if (symsfile == NULL)
+ err (1, "open %s", fn);
+ free(fn);
+ fn = NULL;
+
+ /* if one code file, write into the one codefile */
+ if (one_code_file)
+ return;
+
+ templatefile = fopen (template, "w");
+ if (templatefile == NULL)
+ err (1, "open %s", template);
+
+ fprintf (templatefile,
+ "/* Generated from %s */\n"
+ "/* Do not edit */\n\n"
+ "#include <stdio.h>\n"
+ "#include <stdlib.h>\n"
+ "#include <time.h>\n"
+ "#include <string.h>\n"
+ "#include <errno.h>\n"
+ "#include <limits.h>\n"
+ "#include <asn1_err.h>\n"
+ "#include <%s>\n",
+ filename,
+ type_file_string);
+
+ fprintf (templatefile,
+ "#include <%s>\n"
+ "#include <%s>\n"
+ "#include <der.h>\n"
+ "#include <asn1-template.h>\n",
+ header, privheader);
+
+
+}
+
+void
+close_generate (void)
+{
+ fprintf (headerfile, "#endif /* __%s_h__ */\n", headerbase);
+
+ if (headerfile && fclose(headerfile) == EOF)
+ err(1, "writes to public header file failed");
+ if (privheaderfile && fclose(privheaderfile) == EOF)
+ err(1, "writes to private header file failed");
+ if (templatefile && fclose(templatefile) == EOF)
+ err(1, "writes to template file failed");
+ if (!jsonfile) abort();
+ if (fclose(jsonfile) == EOF)
+ err(1, "writes to JSON file failed");
+ if (!oidsfile) abort();
+ if (fclose(oidsfile) == EOF)
+ err(1, "writes to OIDs file failed");
+ if (!symsfile) abort();
+ if (fclose(symsfile) == EOF)
+ err(1, "writes to symbols file failed");
+ if (!logfile) abort();
+ fprintf(logfile, "\n");
+ if (fclose(logfile) == EOF)
+ err(1, "writes to log file failed");
+}
+
+void
+gen_assign_defval(const char *var, struct value *val)
+{
+ switch(val->type) {
+ case stringvalue:
+ fprintf(codefile, "if((%s = strdup(\"%s\")) == NULL)\nreturn ENOMEM;\n", var, val->u.stringvalue);
+ break;
+ case integervalue:
+ fprintf(codefile, "%s = %lld;\n",
+ var, (long long)val->u.integervalue);
+ break;
+ case booleanvalue:
+ if(val->u.booleanvalue)
+ fprintf(codefile, "%s = 1;\n", var);
+ else
+ fprintf(codefile, "%s = 0;\n", var);
+ break;
+ default:
+ abort();
+ }
+}
+
+void
+gen_compare_defval(const char *var, struct value *val)
+{
+ switch(val->type) {
+ case stringvalue:
+ fprintf(codefile, "if(strcmp(%s, \"%s\") != 0)\n", var, val->u.stringvalue);
+ break;
+ case integervalue:
+ fprintf(codefile, "if(%s != %lld)\n",
+ var, (long long)val->u.integervalue);
+ break;
+ case booleanvalue:
+ if(val->u.booleanvalue)
+ fprintf(codefile, "if(!%s)\n", var);
+ else
+ fprintf(codefile, "if(%s)\n", var);
+ break;
+ default:
+ abort();
+ }
+}
+
+void
+generate_header_of_codefile(const char *name)
+{
+ char *filename = NULL;
+
+ if (codefile != NULL)
+ abort();
+
+ if (asprintf (&filename, "%s_%s.c", STEM, name) < 0 || filename == NULL)
+ errx(1, "malloc");
+ codefile = fopen (filename, "w");
+ if (codefile == NULL)
+ err (1, "fopen %s", filename);
+ if (logfile)
+ fprintf(logfile, "%s ", filename);
+ free(filename);
+ filename = NULL;
+ fprintf (codefile,
+ "/* Generated from %s */\n"
+ "/* Do not edit */\n\n"
+ "#if defined(_WIN32) && !defined(ASN1_LIB)\n"
+ "# error \"ASN1_LIB must be defined\"\n"
+ "#endif\n"
+ "#include <stdio.h>\n"
+ "#include <stdlib.h>\n"
+ "#include <time.h>\n"
+ "#include <string.h>\n"
+ "#include <errno.h>\n"
+ "#include <limits.h>\n"
+ "#include <%s>\n",
+ orig_filename,
+ type_file_string);
+
+ fprintf (codefile,
+ "#include \"%s\"\n"
+ "#include \"%s\"\n",
+ header, privheader);
+ fprintf (codefile,
+ "#include <asn1_err.h>\n"
+ "#include <der.h>\n"
+ "#include <asn1-template.h>\n\n");
+
+ if (parse_units_flag)
+ fprintf (codefile,
+ "#include <parse_units.h>\n\n");
+
+#ifdef _WIN32
+ fprintf(codefile, "#pragma warning(disable: 4101)\n\n");
+#endif
+}
+
+void
+close_codefile(void)
+{
+ if (codefile == NULL)
+ abort();
+
+ if (fclose(codefile) == EOF)
+ err(1, "writes to source code file failed");
+ codefile = NULL;
+}
+
+/* Object identifiers are parsed backwards; this reverses that */
+struct objid **
+objid2list(struct objid *o)
+{
+ struct objid *el, **list;
+ size_t i, len;
+
+ for (el = o, len = 0; el; el = el->next)
+ len++;
+ if (len == 0)
+ return NULL;
+ list = ecalloc(len + 1, sizeof(*list));
+
+ for (i = 0; o; o = o->next)
+ list[i++] = o;
+ list[i] = NULL;
+
+ /* Reverse the list */
+ for (i = 0; i < (len>>1); i++) {
+ el = list[i];
+ list[i] = list[len - (i + 1)];
+ list[len - (i + 1)] = el;
+ }
+ return list;
+}
+
+void
+generate_constant (const Symbol *s)
+{
+ switch(s->value->type) {
+ case booleanvalue:
+ break;
+ case integervalue:
+ /*
+ * Work around the fact that OpenSSL defines macros for PKIX constants
+ * that we want to generate as enums, which causes conflicts for things
+ * like ub-name (ub_name).
+ */
+ fprintf(headerfile,
+ "#ifdef %s\n"
+ "#undef %s\n"
+ "#endif\n"
+ "enum { %s = %lld };\n\n",
+ s->gen_name, s->gen_name, s->gen_name,
+ (long long)s->value->u.integervalue);
+ if (is_export(s->name))
+ fprintf(symsfile, "ASN1_SYM_INTVAL(\"%s\", \"%s\", %s, %lld)\n",
+ s->name, s->gen_name, s->gen_name,
+ (long long)s->value->u.integervalue);
+ fprintf(jsonfile,
+ "{\"name\":\"%s\",\"gen_name\":\"%s\",\"type\":\"INTEGER\","
+ "\"constant\":true,\"exported\":%s,\"value\":%lld}\n",
+ s->name, s->gen_name, is_export(s->name) ? "true" : "false",
+ (long long)s->value->u.integervalue);
+ break;
+ case nullvalue:
+ break;
+ case stringvalue:
+ break;
+ case objectidentifiervalue: {
+ struct objid *o, **list;
+ size_t i, len;
+ char *gen_upper;
+
+ if (!one_code_file)
+ generate_header_of_codefile(s->gen_name);
+
+ list = objid2list(s->value->u.objectidentifiervalue);
+ for (len = 0; list && list[len]; len++)
+ ;
+ if (len == 0) {
+ errx(1, "Empty OBJECT IDENTIFIER named %s\n", s->name);
+ break;
+ }
+
+ fprintf(jsonfile,
+ "{\"name\":\"%s\",\"gen_name\":\"%s\","
+ "\"type\":\"OBJECT IDENTIFIER\","
+ "\"constant\":true,\"exported\":%s,\"value\":[\n",
+ s->name, s->gen_name, is_export(s->name) ? "true" : "false");
+ fprintf (headerfile, "/* OBJECT IDENTIFIER %s ::= { ", s->name);
+ for (i = 0; i < len; i++) {
+ o = list[i];
+ fprintf(headerfile, "%s(%d) ",
+ o->label ? o->label : "label-less", o->value);
+ if (o->label == NULL)
+ fprintf(jsonfile, "%s{\"label\":null,\"value\":%d}",
+ i ? "," : "", o->value);
+ else
+ fprintf(jsonfile, "%s{\"label\":\"%s\",\"value\":%d}",
+ i ? "," : "", o->label, o->value);
+ }
+ fprintf(jsonfile, "]}\n");
+
+ fprintf (codefile, "static unsigned oid_%s_variable_num[%lu] = {",
+ s->gen_name, (unsigned long)len);
+ for (i = 0; list[i]; i++) {
+ fprintf(codefile, "%s %d", i ? "," : "", list[i]->value);
+ }
+ fprintf(codefile, "};\n");
+
+ fprintf (codefile, "const heim_oid asn1_oid_%s = "
+ "{ %lu, oid_%s_variable_num };\n\n",
+ s->gen_name, (unsigned long)len, s->gen_name);
+
+ fprintf(oidsfile, "DEFINE_OID_WITH_NAME(%s)\n", s->gen_name);
+ if (is_export(s->name))
+ fprintf(symsfile, "ASN1_SYM_OID(\"%s\", \"%s\", %s)\n",
+ s->name, s->gen_name, s->gen_name);
+
+ free(list);
+
+ /* header file */
+
+ gen_upper = strdup(s->gen_name);
+ len = strlen(gen_upper);
+ for (i = 0; i < len; i++)
+ gen_upper[i] = toupper((int)s->gen_name[i]);
+
+ fprintf (headerfile, "} */\n");
+ fprintf (headerfile,
+ "extern ASN1EXP const heim_oid asn1_oid_%s;\n"
+ "#define ASN1_OID_%s (&asn1_oid_%s)\n\n",
+ s->gen_name,
+ gen_upper,
+ s->gen_name);
+
+ free(gen_upper);
+
+ if (!one_code_file)
+ close_codefile();
+
+ break;
+ }
+ default:
+ abort();
+ }
+}
+
+int
+is_tagged_type(const Type *t)
+{
+ /*
+ * Start by chasing aliasings like this:
+ *
+ * Type0 ::= ...
+ * Type1 ::= Type0
+ * ..
+ * TypeN ::= TypeN-1
+ *
+ * to <Type0>, then check if <Type0> is tagged.
+ */
+ while (t->type == TType) {
+ if (t->subtype)
+ t = t->subtype;
+ else if (t->symbol && t->symbol->type)
+ t = t->symbol->type;
+ else
+ abort();
+
+ }
+ if (t->type == TTag && t->tag.tagenv == TE_EXPLICIT)
+ return 1;
+ if (t->type == TTag) {
+ if (t->subtype)
+ return is_tagged_type(t->subtype);
+ if (t->symbol && t->symbol->type)
+ return is_tagged_type(t->symbol->type);
+ /* This is the tag */
+ return 1;
+ }
+ return 0;
+}
+
+int
+is_primitive_type(const Type *t)
+{
+ /*
+ * Start by chasing aliasings like this:
+ *
+ * Type0 ::= ...
+ * Type1 ::= Type0
+ * ..
+ * TypeN ::= TypeN-1
+ *
+ * to <Type0>, then check if <Type0> is primitive.
+ */
+ while (t->type == TType &&
+ t->symbol &&
+ t->symbol->type) {
+ if (t->symbol->type->type == TType)
+ t = t->symbol->type; /* Alias */
+ else if (t->symbol->type->type == TTag &&
+ t->symbol->type->tag.tagenv == TE_IMPLICIT)
+ /*
+ * IMPLICIT-tagged alias, something like:
+ *
+ * Type0 ::= [0] IMPLICIT ...
+ *
+ * Just recurse.
+ */
+ return is_primitive_type(t->symbol->type);
+ else
+ break;
+
+ }
+ /* EXPLICIT non-UNIVERSAL tags are always constructed */
+ if (t->type == TTag && t->tag.tagclass != ASN1_C_UNIV &&
+ t->tag.tagenv == TE_EXPLICIT)
+ return 0;
+ if (t->symbol && t->symbol->type) {
+ /* EXPLICIT non-UNIVERSAL tags are constructed */
+ if (t->symbol->type->type == TTag &&
+ t->symbol->type->tag.tagclass != ASN1_C_UNIV &&
+ t->symbol->type->tag.tagenv == TE_EXPLICIT)
+ return 0;
+ /* EXPLICIT UNIVERSAL tags are constructed if they are SEQUENCE/SET */
+ if (t->symbol->type->type == TTag &&
+ t->symbol->type->tag.tagclass == ASN1_C_UNIV) {
+ switch (t->symbol->type->tag.tagvalue) {
+ case UT_Sequence: return 0;
+ case UT_Set: return 0;
+ default: return 1;
+ }
+ }
+ }
+ switch(t->type) {
+ case TInteger:
+ case TBoolean:
+ case TOctetString:
+ case TBitString:
+ case TEnumerated:
+ case TGeneralizedTime:
+ case TGeneralString:
+ case TTeletexString:
+ case TOID:
+ case TUTCTime:
+ case TUTF8String:
+ case TPrintableString:
+ case TIA5String:
+ case TBMPString:
+ case TUniversalString:
+ case TVisibleString:
+ case TNull:
+ return 1;
+ case TTag:
+ return is_primitive_type(t->subtype);
+ default:
+ return 0;
+ }
+}
+
+static void
+space(int level)
+{
+ while(level-- > 0)
+ fprintf(headerfile, " ");
+}
+
+static const char *
+last_member_p(struct member *m)
+{
+ struct member *n = HEIM_TAILQ_NEXT(m, members);
+ if (n == NULL)
+ return "";
+ if (n->ellipsis && HEIM_TAILQ_NEXT(n, members) == NULL)
+ return "";
+ return ",";
+}
+
+static struct member *
+have_ellipsis(Type *t)
+{
+ struct member *m;
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ if (m->ellipsis)
+ return m;
+ }
+ return NULL;
+}
+
+static void
+define_asn1 (int level, Type *t)
+{
+ switch (t->type) {
+ case TType:
+ if (!t->symbol && t->typeref.iosclass) {
+ fprintf(headerfile, "%s.&%s",
+ t->typeref.iosclass->symbol->name,
+ t->typeref.field->name);
+ } else if (t->symbol)
+ fprintf(headerfile, "%s", t->symbol->name);
+ else
+ abort();
+ break;
+ case TInteger:
+ if(t->members == NULL) {
+ fprintf (headerfile, "INTEGER");
+ if (t->range)
+ fprintf (headerfile, " (%lld..%lld)",
+ (long long)t->range->min,
+ (long long)t->range->max);
+ } else {
+ Member *m;
+ fprintf (headerfile, "INTEGER {\n");
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ space (level + 1);
+ fprintf(headerfile, "%s(%lld)%s\n", m->gen_name,
+ (long long)m->val, last_member_p(m));
+ }
+ space(level);
+ fprintf (headerfile, "}");
+ }
+ break;
+ case TBoolean:
+ fprintf (headerfile, "BOOLEAN");
+ break;
+ case TOctetString:
+ fprintf (headerfile, "OCTET STRING");
+ break;
+ case TEnumerated:
+ case TBitString: {
+ Member *m;
+
+ space(level);
+ if(t->type == TBitString)
+ fprintf (headerfile, "BIT STRING {\n");
+ else
+ fprintf (headerfile, "ENUMERATED {\n");
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ space(level + 1);
+ fprintf(headerfile, "%s(%lld)%s\n", m->name,
+ (long long)m->val, last_member_p(m));
+ }
+ space(level);
+ fprintf (headerfile, "}");
+ break;
+ }
+ case TChoice:
+ case TSet:
+ case TSequence: {
+ Member *m;
+ size_t max_width = 0;
+
+ if(t->type == TChoice)
+ fprintf(headerfile, "CHOICE {\n");
+ else if(t->type == TSet)
+ fprintf(headerfile, "SET {\n");
+ else
+ fprintf(headerfile, "SEQUENCE {\n");
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ if(strlen(m->name) > max_width)
+ max_width = strlen(m->name);
+ }
+ max_width += 3;
+ if(max_width < 16) max_width = 16;
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ size_t width = max_width;
+ space(level + 1);
+ if (m->ellipsis) {
+ fprintf (headerfile, "...");
+ } else {
+ width -= fprintf(headerfile, "%s", m->name);
+ fprintf(headerfile, "%*s", (int)width, "");
+ define_asn1(level + 1, m->type);
+ if(m->optional)
+ fprintf(headerfile, " OPTIONAL");
+ }
+ if(last_member_p(m))
+ fprintf (headerfile, ",");
+ fprintf (headerfile, "\n");
+ }
+ space(level);
+ fprintf (headerfile, "}");
+ break;
+ }
+ case TSequenceOf:
+ fprintf (headerfile, "SEQUENCE OF ");
+ define_asn1 (0, t->subtype);
+ break;
+ case TSetOf:
+ fprintf (headerfile, "SET OF ");
+ define_asn1 (0, t->subtype);
+ break;
+ case TGeneralizedTime:
+ fprintf (headerfile, "GeneralizedTime");
+ break;
+ case TGeneralString:
+ fprintf (headerfile, "GeneralString");
+ break;
+ case TTeletexString:
+ fprintf (headerfile, "TeletexString");
+ break;
+ case TTag: {
+ const char *classnames[] = { "UNIVERSAL ", "APPLICATION ",
+ "" /* CONTEXT */, "PRIVATE " };
+ if(t->tag.tagclass != ASN1_C_UNIV)
+ fprintf (headerfile, "[%s%d] ",
+ classnames[t->tag.tagclass],
+ t->tag.tagvalue);
+ if(t->tag.tagenv == TE_IMPLICIT)
+ fprintf (headerfile, "IMPLICIT ");
+ define_asn1 (level, t->subtype);
+ break;
+ }
+ case TUTCTime:
+ fprintf (headerfile, "UTCTime");
+ break;
+ case TUTF8String:
+ space(level);
+ fprintf (headerfile, "UTF8String");
+ break;
+ case TPrintableString:
+ space(level);
+ fprintf (headerfile, "PrintableString");
+ break;
+ case TIA5String:
+ space(level);
+ fprintf (headerfile, "IA5String");
+ break;
+ case TBMPString:
+ space(level);
+ fprintf (headerfile, "BMPString");
+ break;
+ case TUniversalString:
+ space(level);
+ fprintf (headerfile, "UniversalString");
+ break;
+ case TVisibleString:
+ space(level);
+ fprintf (headerfile, "VisibleString");
+ break;
+ case TOID :
+ space(level);
+ fprintf(headerfile, "OBJECT IDENTIFIER");
+ break;
+ case TNull:
+ space(level);
+ fprintf (headerfile, "NULL");
+ break;
+ default:
+ abort ();
+ }
+}
+
+static void
+getnewbasename(char **newbasename, int typedefp, const char *basename, const char *name)
+{
+ if (typedefp)
+ *newbasename = strdup(name);
+ else {
+ if (name[0] == '*')
+ name++;
+ if (asprintf(newbasename, "%s_%s", basename, name) < 0)
+ errx(1, "malloc");
+ }
+ if (*newbasename == NULL)
+ err(1, "malloc");
+}
+
+static void define_type(int, const char *, const char *, Type *, Type *, int, int);
+
+/*
+ * Get the SET/SEQUENCE member pair and CLASS field pair defining an open type.
+ *
+ * There are three cases:
+ *
+ * - open types embedded in OCTET STRING, with the open type object class
+ * relation declared via a constraint
+ *
+ * - open types not embedded in OCTET STRING, which are really more like ANY
+ * DEFINED BY types, so, HEIM_ANY
+ *
+ * - open types in a nested structure member where the type ID field is in a
+ * member of the ancestor structure (this happens in PKIX's `AttributeSet',
+ * where the open type is essentially a SET OF HEIM_ANY).
+ *
+ * In a type like PKIX's SingleAttribute the type ID member would be the one
+ * named "type" and the open type member would be the one named "value", and
+ * the corresponding fields of the ATTRIBUTE class would be named "id" and
+ * "Type".
+ *
+ * NOTE: We assume a single open type member pair in any SET/SEQUENCE. In
+ * principle there could be more pairs and we could iterate them, or
+ * better yet, we could be given the name of an open type member and then
+ * just find its related type ID member and fields, then our caller would
+ * iterate the SET/SEQUENCE type's members looking for open type members
+ * and would call this function for each one found.
+ */
+void
+get_open_type_defn_fields(const Type *t,
+ Member **typeidmember,
+ Member **opentypemember,
+ Field **typeidfield,
+ Field **opentypefield,
+ int *is_array_of)
+{
+ Member *m;
+ Field *junk1, *junk2;
+ char *idmembername = NULL;
+
+ if (!typeidfield) typeidfield = &junk1;
+ if (!opentypefield) opentypefield = &junk2;
+
+ *typeidfield = *opentypefield = NULL;
+ *typeidmember = *opentypemember = NULL;
+ *is_array_of = 0;
+
+ /* Look for the open type member */
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ Type *subtype = m->type;
+ Type *sOfType = NULL;
+
+ while (subtype->type == TTag ||
+ subtype->type == TSetOf ||
+ subtype->type == TSequenceOf) {
+ if (subtype->type == TTag && subtype->subtype) {
+ if (subtype->subtype->type == TOctetString ||
+ subtype->subtype->type == TBitString)
+ break;
+ subtype = subtype->subtype;
+ } else if (subtype->type == TSetOf || subtype->type == TSequenceOf) {
+ sOfType = subtype;
+ if (sOfType->symbol)
+ break;
+ if (subtype->subtype)
+ subtype = subtype->subtype;
+ } else
+ break;
+ }
+ /*
+ * If we traversed through a non-inlined SET OF or SEQUENCE OF type,
+ * then this cannot be an open type field.
+ */
+ if (sOfType && sOfType->symbol)
+ continue;
+ /*
+ * The type of the field we're interested in has to have an information
+ * object constraint.
+ */
+ if (!subtype->constraint)
+ continue;
+ if (subtype->type != TType && subtype->type != TTag)
+ continue;
+ /*
+ * Check if it's an ANY-like member or like an OCTET STRING CONTAINING
+ * member. Those are the only two possibilities.
+ */
+ if ((subtype->type == TTag || subtype->type == TType) &&
+ subtype->subtype &&
+ subtype->constraint->ctype == CT_CONTENTS &&
+ subtype->constraint->u.content.type &&
+ subtype->constraint->u.content.type->type == TType &&
+ !subtype->constraint->u.content.type->subtype &&
+ subtype->constraint->u.content.type->constraint &&
+ subtype->constraint->u.content.type->constraint->ctype == CT_TABLE_CONSTRAINT) {
+ /* Type like OCTET STRING or BIT STRING CONTAINING open type */
+ if (*opentypemember)
+ errx(1, "Multiple open type members %s and %s for the same "
+ "field %s?", (*opentypemember)->name, m->name,
+ (*opentypefield)->name);
+ *opentypemember = m;
+ *opentypefield = subtype->constraint->u.content.type->typeref.field;
+ *is_array_of = sOfType != NULL;
+ idmembername = subtype->constraint->u.content.type->constraint->u.content.crel.membername;
+ break;
+ } else if (subtype->symbol && strcmp(subtype->symbol->name, "HEIM_ANY") == 0) {
+ /* Open type, but NOT embedded in OCTET STRING or BIT STRING */
+ if (*opentypemember)
+ errx(1, "Multiple open type members %s and %s for the same "
+ "field %s?", (*opentypemember)->name, m->name,
+ (*opentypefield)->name);
+ *opentypemember = m;
+ *opentypefield = subtype->typeref.field;
+ *is_array_of = sOfType != NULL;
+ idmembername = subtype->constraint->u.content.crel.membername;
+ break;
+ }
+ }
+
+ if (!idmembername)
+ errx(1, "Missing open type id member in %s",
+ t->symbol ? t->symbol->name : "<unknown type>");
+ /* Look for the type ID member identified in the previous loop */
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ if (!m->type->subtype || strcmp(m->name, idmembername) != 0)
+ continue;
+ if (m->type->constraint &&
+ m->type->constraint->ctype == CT_TABLE_CONSTRAINT)
+ *typeidfield = m->type->typeref.field;
+ else if (m->type->subtype->constraint &&
+ m->type->subtype->constraint->ctype == CT_TABLE_CONSTRAINT)
+ *typeidfield = m->type->subtype->typeref.field;
+ else
+ continue;
+ /* This is the type ID field (because there _is_ a subtype) */
+ *typeidmember = m;
+ break;
+ }
+}
+
+/*
+ * Generate CHOICE-like struct fields for open types declared via
+ * X.681/682/683 syntax.
+ *
+ * We could support multiple open type members in a SET/SEQUENCE, but for now
+ * we support only one.
+ */
+static void
+define_open_type(int level, const char *newbasename, const char *name, const char *basename, Type *pt, Type *t)
+{
+ Member *opentypemember, *typeidmember;
+ Field *opentypefield, *typeidfield;
+ ObjectField *of;
+ IOSObjectSet *os = pt->actual_parameter;
+ IOSObject **objects;
+ size_t nobjs, i;
+ int is_array_of_open_type;
+
+ get_open_type_defn_fields(pt, &typeidmember, &opentypemember,
+ &typeidfield, &opentypefield,
+ &is_array_of_open_type);
+ if (!opentypemember || !typeidmember ||
+ !opentypefield || !typeidfield)
+ errx(1, "Open type specification in %s is incomplete", name);
+
+ sort_object_set(os, typeidfield, &objects, &nobjs);
+
+ fprintf(headerfile, "struct {\n");
+ fprintf(jsonfile, "{\"opentype\":true,\"arraytype\":%s,",
+ is_array_of_open_type ? "true" : "false");
+ fprintf(jsonfile, "\"classname\":\"%s\",", os->iosclass->symbol->name);
+ fprintf(jsonfile, "\"objectsetname\":\"%s\",", os->symbol->name);
+ fprintf(jsonfile, "\"typeidmember\":\"%s\",", typeidmember->name);
+ fprintf(jsonfile, "\"opentypemember\":\"%s\",", opentypemember->name);
+ fprintf(jsonfile, "\"typeidfield\":\"%s\",", typeidfield->name);
+ fprintf(jsonfile, "\"opentypefield\":\"%s\",", opentypefield->name);
+
+ /* Iterate objects in the object set, gen enum labels */
+ fprintf(headerfile, "enum { choice_%s_iosnumunknown = 0,\n",
+ newbasename);
+ for (i = 0; i < nobjs; i++) {
+ HEIM_TAILQ_FOREACH(of, objects[i]->objfields, objfields) {
+ if (strcmp(of->name, typeidfield->name) != 0)
+ continue;
+ if (!of->value || !of->value->s)
+ errx(1, "Unknown value in value field %s of object %s",
+ of->name, objects[i]->symbol->name);
+ fprintf(headerfile, "choice_%s_iosnum_%s,\n",
+ newbasename, of->value->s->gen_name);
+ }
+ }
+ fprintf(headerfile, "} element;\n");
+
+ if (is_array_of_open_type)
+ fprintf(headerfile, "unsigned int len;\n");
+
+ /* Iterate objects in the object set, gen union arms */
+ fprintf(headerfile, "union {\nvoid *_any;\n");
+ fprintf(jsonfile, "\"members\":[");
+ for (i = 0; i < nobjs; i++) {
+ HEIM_TAILQ_FOREACH(of, objects[i]->objfields, objfields) {
+ char *n = NULL;
+
+ /* XXX Print the type IDs into the jsonfile too pls */
+
+ if (strcmp(of->name, opentypefield->name) != 0)
+ continue;
+ if (!of->type || (!of->type->symbol && of->type->type != TTag) ||
+ of->type->tag.tagclass != ASN1_C_UNIV) {
+ warnx("Ignoring unknown or unset type field %s of object %s",
+ of->name, objects[i]->symbol->name);
+ continue;
+ }
+
+ if (asprintf(&n, "*%s", objects[i]->symbol->gen_name) < 0 || n == NULL)
+ err(1, "malloc");
+ define_type(level + 2, n, newbasename, NULL, of->type, FALSE, FALSE);
+ fprintf(jsonfile, "%s", (i + 1) < nobjs ? "," : "");
+ free(n);
+ }
+ }
+ fprintf(jsonfile, "]}\n");
+ if (is_array_of_open_type) {
+ fprintf(headerfile, "} *val;\n} _ioschoice_%s;\n", opentypemember->gen_name);
+ } else {
+ fprintf(headerfile, "} u;\n");
+ fprintf(headerfile, "} _ioschoice_%s;\n", opentypemember->gen_name);
+ }
+ free(objects);
+}
+
+static const char * const tagclassnames[] = {
+ "UNIVERSAL", "APPLICATION", "CONTEXT", "PRIVATE"
+};
+
+static void
+define_type(int level, const char *name, const char *basename, Type *pt, Type *t, int typedefp, int preservep)
+{
+ const char *label_prefix = NULL;
+ const char *label_prefix_sep = NULL;
+ char *newbasename = NULL;
+
+ fprintf(jsonfile, "{\"name\":\"%s\",\"gen_name\":\"%s\","
+ "\"is_type\":true,\"exported\":%s,\"typedef\":%s,",
+ basename, name,
+ t->symbol && is_export(t->symbol->name) ? "true" : "false",
+ typedefp ? "true" : "false");
+
+ switch (t->type) {
+ case TType:
+ space(level);
+ if (!t->symbol && t->actual_parameter) {
+ define_open_type(level, newbasename, name, basename, t, t);
+ } else if (!t->symbol && pt->actual_parameter) {
+ define_open_type(level, newbasename, name, basename, pt, t);
+ } else if (t->symbol) {
+ fprintf(headerfile, "%s %s;\n", t->symbol->gen_name, name);
+ fprintf(jsonfile, "\"ttype\":\"%s\","
+ "\"alias\":true\n", t->symbol->gen_name);
+ } else
+ abort();
+ break;
+ case TInteger:
+ if (t->symbol && t->symbol->emitted_definition)
+ break;
+
+ space(level);
+ if(t->members) {
+ Member *m;
+
+ label_prefix = prefix_enum ? name : (enum_prefix ? enum_prefix : "");
+ label_prefix_sep = prefix_enum ? "_" : "";
+ fprintf (headerfile, "enum %s {\n", typedefp ? name : "");
+ fprintf(jsonfile, "\"ttype\":\"INTEGER\",\"ctype\":\"enum\","
+ "\"members\":[\n");
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ space (level + 1);
+ fprintf(headerfile, "%s%s%s = %lld%s\n",
+ label_prefix, label_prefix_sep,
+ m->gen_name, (long long)m->val, last_member_p(m));
+ fprintf(jsonfile, "{\"%s%s%s\":%lld}%s\n",
+ label_prefix, label_prefix_sep,
+ m->gen_name, (long long)m->val, last_member_p(m));
+ }
+ fprintf(headerfile, "} %s;\n", name);
+ fprintf(jsonfile, "]");
+ } else if (t->range == NULL) {
+ fprintf(headerfile, "heim_integer %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"INTEGER\",\"ctype\":\"heim_integer\"");
+ } else if (t->range->min < 0 &&
+ (t->range->min < INT_MIN || t->range->max > INT_MAX)) {
+ fprintf(headerfile, "int64_t %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"INTEGER\",\"ctype\":\"int64_t\"");
+ } else if (t->range->min < 0) {
+ fprintf (headerfile, "int %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"INTEGER\",\"ctype\":\"int\"");
+ } else if (t->range->max > UINT_MAX) {
+ fprintf (headerfile, "uint64_t %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"INTEGER\",\"ctype\":\"uint64_t\"");
+ } else {
+ fprintf (headerfile, "unsigned int %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"INTEGER\",\"ctype\":\"unsigned int\"");
+ }
+ break;
+ case TBoolean:
+ space(level);
+ fprintf (headerfile, "int %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"BOOLEAN\",\"ctype\":\"unsigned int\"");
+ break;
+ case TOctetString:
+ space(level);
+ fprintf (headerfile, "heim_octet_string %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"OCTET STRING\",\"ctype\":\"heim_octet_string\"");
+ break;
+ case TBitString: {
+ Member *m;
+ Type i;
+ struct range range = { 0, UINT_MAX };
+ size_t max_memno = 0;
+ size_t bitset_size;
+
+ if (t->symbol && t->symbol->emitted_definition)
+ break;
+ memset(&i, 0, sizeof(i));
+
+ /*
+ * range.max implies the size of the base unsigned integer used for the
+ * bitfield members. If it's less than or equal to UINT_MAX, then that
+ * will be unsigned int, otherwise it will be uint64_t.
+ *
+ * We could just use uint64_t, yes, but for now, and in case that any
+ * projects were exposing the BIT STRING types' C representations in
+ * ABIs prior to this compiler supporting BIT STRING with larger
+ * members, we stick to this.
+ */
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ if (m->val > max_memno)
+ max_memno = m->val;
+ }
+ if (max_memno > 63)
+ range.max = INT64_MAX;
+ else
+ range.max = 1ULL << max_memno;
+
+ i.type = TInteger;
+ i.range = &range;
+ i.members = NULL;
+ i.constraint = NULL;
+
+ space(level);
+ fprintf(jsonfile, "\"ttype\":\"BIT STRING\",");
+ if(HEIM_TAILQ_EMPTY(t->members)) {
+ fprintf (headerfile, "heim_bit_string %s;\n", name);
+ fprintf(jsonfile, "\"ctype\":\"heim_bit_string\"");
+ } else {
+ int64_t pos = 0;
+ getnewbasename(&newbasename, typedefp || level == 0, basename, name);
+
+ fprintf (headerfile, "struct %s {\n", newbasename);
+ fprintf(jsonfile, "\"ctype\":\"struct %s\",\"members\":[\n", newbasename);
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ char *n = NULL;
+
+ /*
+ * pad unused bits beween declared members (hopefully this
+ * forces the compiler to give us an obvious layout)
+ */
+ while (pos < m->val) {
+ if (asprintf (&n, "_unused%lld:1", (long long)pos) < 0 ||
+ n == NULL)
+ err(1, "malloc");
+ define_type(level + 1, n, newbasename, NULL, &i, FALSE, FALSE);
+ fprintf(jsonfile, ",");
+ free(n);
+ pos++;
+ }
+
+ n = NULL;
+ if (asprintf (&n, "%s:1", m->gen_name) < 0 || n == NULL)
+ errx(1, "malloc");
+ define_type(level + 1, n, newbasename, NULL, &i, FALSE, FALSE);
+ fprintf(jsonfile, "%s", last_member_p(m));
+ free (n);
+ n = NULL;
+ pos++;
+ }
+ /* pad unused tail (ditto) */
+ bitset_size = max_memno;
+ if (max_memno > 31)
+ bitset_size += 64 - (max_memno % 64);
+ else
+ bitset_size = 32;
+ if (pos < bitset_size)
+ fprintf(jsonfile, ",");
+ while (pos < bitset_size) {
+ char *n = NULL;
+ if (asprintf (&n, "_unused%lld:1", (long long)pos) < 0 ||
+ n == NULL)
+ errx(1, "malloc");
+ define_type(level + 1, n, newbasename, NULL, &i, FALSE, FALSE);
+ fprintf(jsonfile, "%s", (pos + 1) < bitset_size ? "," : "");
+ free(n);
+ pos++;
+ }
+
+ space(level);
+ fprintf (headerfile, "} %s;\n\n", name);
+ fprintf(jsonfile, "]");
+ }
+ break;
+ }
+ case TEnumerated: {
+ Member *m;
+
+ if (t->symbol && t->symbol->emitted_definition)
+ break;
+
+ label_prefix = prefix_enum ? name : (enum_prefix ? enum_prefix : "");
+ label_prefix_sep = prefix_enum ? "_" : "";
+ space(level);
+ fprintf (headerfile, "enum %s {\n", typedefp ? name : "");
+ fprintf(jsonfile, "\"ctype\":\"enum %s\",\"extensible\":%s,\"members\":[\n",
+ typedefp ? name : "", have_ellipsis(t) ? "true" : "false");
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ space(level + 1);
+ if (m->ellipsis) {
+ fprintf (headerfile, "/* ... */\n");
+ } else {
+ fprintf(headerfile, "%s%s%s = %lld%s\n",
+ label_prefix, label_prefix_sep,
+ m->gen_name, (long long)m->val, last_member_p(m));
+ fprintf(jsonfile, "{\"%s%s%s\":%lld%s}\n",
+ label_prefix, label_prefix_sep,
+ m->gen_name, (long long)m->val, last_member_p(m));
+ }
+ }
+ space(level);
+ fprintf (headerfile, "} %s;\n\n", name);
+ fprintf(jsonfile, "]");
+ break;
+ }
+ case TSet:
+ case TSequence: {
+ Member *m;
+ struct decoration deco;
+ ssize_t more_deco = -1;
+ int decorated = 0;
+
+ getnewbasename(&newbasename, typedefp || level == 0, basename, name);
+
+ space(level);
+
+ fprintf (headerfile, "struct %s {\n", newbasename);
+ fprintf(jsonfile, "\"ttype\":\"%s\",\"extensible\":%s,"
+ "\"ctype\":\"struct %s\"",
+ t->type == TSet ? "SET" : "SEQUENCE",
+ have_ellipsis(t) ? "true" : "false", newbasename);
+ if (t->type == TSequence && preservep) {
+ space(level + 1);
+ fprintf(headerfile, "heim_octet_string _save;\n");
+ fprintf(jsonfile, ",\"preserve\":true");
+ }
+ fprintf(jsonfile, ",\"members\":[\n");
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ if (m->ellipsis) {
+ ;
+ } else if (m->optional) {
+ char *n = NULL;
+
+ if (asprintf(&n, "*%s", m->gen_name) < 0 || n == NULL)
+ errx(1, "malloc");
+ fprintf(jsonfile, "{\"name\":\"%s\",\"gen_name\":\"%s\","
+ "\"optional\":true,\"type\":", m->name, m->gen_name);
+ define_type(level + 1, n, newbasename, t, m->type, FALSE, FALSE);
+ fprintf(jsonfile, "}%s", last_member_p(m));
+ free (n);
+ } else {
+ fprintf(jsonfile, "{\"name\":\"%s\",\"gen_name\":\"%s\","
+ "\"optional\":false,\"type\":", m->name, m->gen_name);
+ define_type(level + 1, m->gen_name, newbasename, t, m->type, FALSE, FALSE);
+ fprintf(jsonfile, "}%s", last_member_p(m));
+ }
+ }
+ fprintf(jsonfile, "]");
+ if (t->actual_parameter && t->actual_parameter->objects) {
+ fprintf(jsonfile, ",\"opentype\":");
+ define_open_type(level, newbasename, name, basename, t, t);
+ }
+ while (decorate_type(newbasename, &deco, &more_deco)) {
+ decorated++;
+ space(level + 1);
+ fprintf(headerfile, "%s %s%s;\n", deco.field_type,
+ deco.opt ? "*" : "", deco.field_name);
+ if (deco.first)
+ fprintf(jsonfile, ",\"decorate\":[");
+ fprintf(jsonfile, "%s{"
+ "\"type\":\"%s\",\"name\":\"%s\",\"optional\":%s,"
+ "\"external\":%s,\"pointer\":%s,\"void_star\":%s,"
+ "\"struct_star\":%s,"
+ "\"copy_function\":\"%s\","
+ "\"free_function\":\"%s\",\"header_name\":%s%s%s"
+ "}",
+ deco.first ? "" : ",",
+ deco.field_type, deco.field_name,
+ deco.opt ? "true" : "false", deco.ext ? "true" : "false",
+ deco.ptr ? "true" : "false", deco.void_star ? "true" : "false",
+ deco.struct_star ? "true" : "false",
+ deco.copy_function_name ? deco.copy_function_name : "",
+ deco.free_function_name ? deco.free_function_name : "",
+ deco.header_name && deco.header_name[0] == '"' ? "" : "\"",
+ deco.header_name ? deco.header_name : "",
+ deco.header_name && deco.header_name[0] == '"' ? "" : "\""
+ );
+ }
+ if (decorated)
+ fprintf(jsonfile, "]");
+ space(level);
+ fprintf (headerfile, "} %s;\n", name);
+ free(deco.field_type);
+ break;
+ }
+ case TSetOf:
+ case TSequenceOf: {
+ Type i;
+ struct range range = { 0, UINT_MAX };
+
+ getnewbasename(&newbasename, typedefp || level == 0, basename, name);
+
+ memset(&i, 0, sizeof(i));
+ i.type = TInteger;
+ i.range = &range;
+
+ space(level);
+ fprintf (headerfile, "struct %s {\n", newbasename);
+ fprintf(jsonfile, "\"ttype\":\"%s\",\"ctype\":\"struct %s\",\"members\":[",
+ t->type == TSetOf ? "SET OF" : "SEQUENCE OF", newbasename);
+ define_type(level + 1, "len", newbasename, t, &i, FALSE, FALSE);
+ fprintf(jsonfile, ",");
+ define_type(level + 1, "*val", newbasename, t, t->subtype, FALSE, FALSE);
+ space(level);
+ fprintf (headerfile, "} %s;\n", name);
+ fprintf(jsonfile, "]");
+ break;
+ }
+ case TGeneralizedTime:
+ space(level);
+ fprintf (headerfile, "time_t %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"GeneralizedTime\",\"ctype\":\"time_t\"");
+ break;
+ case TGeneralString:
+ space(level);
+ fprintf (headerfile, "heim_general_string %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"GeneralString\",\"ctype\":\"heim_general_string\"");
+ break;
+ case TTeletexString:
+ space(level);
+ fprintf (headerfile, "heim_general_string %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"TeletexString\",\"ctype\":\"heim_general_string\"");
+ break;
+ case TTag:
+ fprintf(jsonfile, "\"tagclass\":\"%s\",\"tagvalue\":%d,\"tagenv\":\"%s\",\n",
+ tagclassnames[t->tag.tagclass], t->tag.tagvalue,
+ t->tag.tagenv == TE_EXPLICIT ? "EXPLICIT" : "IMPLICIT");
+ fprintf(jsonfile, "\"ttype\":\n");
+ define_type(level, name, basename, t, t->subtype, typedefp, preservep);
+ break;
+ case TChoice: {
+ struct decoration deco;
+ ssize_t more_deco = -1;
+ int decorated = 0;
+ int first = 1;
+ Member *m;
+
+ getnewbasename(&newbasename, typedefp || level == 0, basename, name);
+
+ space(level);
+ fprintf (headerfile, "struct %s {\n", newbasename);
+ fprintf(jsonfile, "\"ttype\":\"CHOICE\",\"ctype\":\"struct %s\"",
+ newbasename);
+ if (preservep) {
+ space(level + 1);
+ fprintf(headerfile, "heim_octet_string _save;\n");
+ fprintf(jsonfile, ",\"preserve\":true");
+ }
+ space(level + 1);
+ fprintf (headerfile, "enum %s_enum {\n", newbasename);
+ m = have_ellipsis(t);
+ if (m) {
+ space(level + 2);
+ fprintf (headerfile, "%s = 0,\n", m->label);
+ first = 0;
+ }
+ fprintf(jsonfile, ",\"extensible\":%s", m ? "true" : "false");
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ space(level + 2);
+ if (m->ellipsis)
+ fprintf (headerfile, "/* ... */\n");
+ else
+ fprintf (headerfile, "%s%s%s\n", m->label,
+ first ? " = 1" : "",
+ last_member_p(m));
+ first = 0;
+ }
+ space(level + 1);
+ fprintf (headerfile, "} element;\n");
+ space(level + 1);
+ fprintf (headerfile, "union {\n");
+ fprintf(jsonfile, ",\"members\":[\n");
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ if (m->ellipsis) {
+ space(level + 2);
+ fprintf(headerfile, "heim_octet_string asn1_ellipsis;\n");
+ } else if (m->optional) {
+ char *n = NULL;
+
+ if (asprintf (&n, "*%s", m->gen_name) < 0 || n == NULL)
+ errx(1, "malloc");
+ fprintf(jsonfile, "{\"optional\":");
+ define_type(level + 2, n, newbasename, t, m->type, FALSE, FALSE);
+ fprintf(jsonfile, "}%s", last_member_p(m));
+ free (n);
+ } else {
+ define_type(level + 2, m->gen_name, newbasename, t, m->type, FALSE, FALSE);
+ fprintf(jsonfile, "%s", last_member_p(m));
+ }
+ }
+ space(level + 1);
+ fprintf (headerfile, "} u;\n");
+ fprintf(jsonfile, "]");
+
+ while (decorate_type(newbasename, &deco, &more_deco)) {
+ decorated++;
+ space(level + 1);
+ fprintf(headerfile, "%s %s%s;\n", deco.field_type,
+ deco.opt ? "*" : "", deco.field_name);
+ if (deco.first)
+ fprintf(jsonfile, ",\"decorate\":[");
+ fprintf(jsonfile, "%s{"
+ "\"type\":\"%s\",\"name\":\"%s\",\"optional\":%s,"
+ "\"external\":%s,\"pointer\":%s,\"void_star\":%s,"
+ "\"struct_star\":%s,"
+ "\"copy_function\":\"%s\","
+ "\"free_function\":\"%s\",\"header_name\":%s%s%s"
+ "}",
+ deco.first ? "" : ",",
+ deco.field_type, deco.field_name,
+ deco.opt ? "true" : "false", deco.ext ? "true" : "false",
+ deco.ptr ? "true" : "false", deco.void_star ? "true" : "false",
+ deco.struct_star ? "true" : "false",
+ deco.copy_function_name ? deco.copy_function_name : "",
+ deco.free_function_name ? deco.free_function_name : "",
+ deco.header_name && deco.header_name[0] == '"' ? "" : "\"",
+ deco.header_name ? deco.header_name : "",
+ deco.header_name && deco.header_name[0] == '"' ? "" : "\""
+ );
+ }
+ if (decorated)
+ fprintf(jsonfile, "]");
+
+ space(level);
+ fprintf (headerfile, "} %s;\n", name);
+ break;
+ }
+ case TUTCTime:
+ space(level);
+ fprintf (headerfile, "time_t %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"UTCTime\",\"ctype\":\"time_t\"");
+ break;
+ case TUTF8String:
+ space(level);
+ fprintf (headerfile, "heim_utf8_string %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"UTF8String\",\"ctype\":\"heim_utf8_string\"");
+ break;
+ case TPrintableString:
+ space(level);
+ fprintf (headerfile, "heim_printable_string %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"PrintableString\",\"ctype\":\"heim_printable_string\"");
+ break;
+ case TIA5String:
+ space(level);
+ fprintf (headerfile, "heim_ia5_string %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"IA5String\",\"ctype\":\"heim_ia5_string\"");
+ break;
+ case TBMPString:
+ space(level);
+ fprintf (headerfile, "heim_bmp_string %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"BMPString\",\"ctype\":\"heim_bmp_string\"");
+ break;
+ case TUniversalString:
+ space(level);
+ fprintf (headerfile, "heim_universal_string %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"UniversalString\",\"ctype\":\"heim_universal_string\"");
+ break;
+ case TVisibleString:
+ space(level);
+ fprintf (headerfile, "heim_visible_string %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"VisibleString\",\"ctype\":\"heim_visible_string\"");
+ break;
+ case TOID :
+ space(level);
+ fprintf (headerfile, "heim_oid %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"OBJECT IDENTIFIER\",\"ctype\":\"heim_oid\"");
+ break;
+ case TNull:
+ space(level);
+ fprintf (headerfile, "int %s;\n", name);
+ fprintf(jsonfile, "\"ttype\":\"NULL\",\"ctype\":\"int\"");
+ break;
+ default:
+ abort ();
+ }
+ fprintf(jsonfile, "}\n");
+ free(newbasename);
+}
+
+static void
+declare_type(const Symbol *s, Type *t, int typedefp)
+{
+ char *newbasename = NULL;
+
+ if (typedefp)
+ fprintf(headerfile, "typedef ");
+
+ switch (t->type) {
+ case TType:
+ define_type(0, s->gen_name, s->gen_name, NULL, s->type, TRUE, TRUE);
+ if (template_flag)
+ generate_template_type_forward(s->gen_name);
+ emitted_declaration(s);
+ return;
+ case TInteger:
+ case TBoolean:
+ case TOctetString:
+ case TBitString:
+ case TEnumerated:
+ case TGeneralizedTime:
+ case TGeneralString:
+ case TTeletexString:
+ case TUTCTime:
+ case TUTF8String:
+ case TPrintableString:
+ case TIA5String:
+ case TBMPString:
+ case TUniversalString:
+ case TVisibleString:
+ case TOID :
+ case TNull:
+ define_type(0, s->gen_name, s->gen_name, NULL, s->type, TRUE, TRUE);
+ if (template_flag)
+ generate_template_type_forward(s->gen_name);
+ emitted_declaration(s);
+ emitted_definition(s);
+ return;
+ case TTag:
+ declare_type(s, t->subtype, FALSE);
+ emitted_declaration(s);
+ return;
+ default:
+ break;
+ }
+
+ switch (t->type) {
+ case TSet:
+ case TSequence: {
+ struct decoration deco;
+ ssize_t more_deco = -1;
+
+ getnewbasename(&newbasename, TRUE, s->gen_name, s->gen_name);
+ fprintf(headerfile, "struct %s %s;\n", newbasename, s->gen_name);
+ while (decorate_type(newbasename, &deco, &more_deco)) {
+ if (deco.header_name)
+ fprintf(headerfile, "#include %s\n", deco.header_name);
+ free(deco.field_type);
+ }
+ break;
+ }
+ case TSetOf:
+ case TSequenceOf:
+ getnewbasename(&newbasename, TRUE, s->gen_name, s->gen_name);
+ fprintf(headerfile, "struct %s %s;\n", newbasename, s->gen_name);
+ break;
+ case TChoice: {
+ struct decoration deco;
+ ssize_t more_deco = -1;
+
+ getnewbasename(&newbasename, TRUE, s->gen_name, s->gen_name);
+ fprintf(headerfile, "struct %s %s;\n", newbasename, s->gen_name);
+ while (decorate_type(newbasename, &deco, &more_deco)) {
+ if (deco.header_name)
+ fprintf(headerfile, "#include %s\n", deco.header_name);
+ free(deco.field_type);
+ }
+ break;
+ }
+ default:
+ abort ();
+ }
+ free(newbasename);
+ emitted_declaration(s);
+}
+
+static void generate_subtypes_header_helper(const Member *m);
+static void generate_type_header(const Symbol *);
+
+static void
+generate_subtypes_header_helper(const Member *m)
+{
+ Member *sm;
+ Symbol *s;
+
+ if (m->ellipsis)
+ return;
+ if (m->type->symbol && (s = getsym(m->type->symbol->name)) &&
+ !s->emitted_definition) {
+ /* A field of some named type; recurse */
+ if (!m->optional && !m->defval)
+ generate_type_header(s);
+ return;
+ }
+ if (!m->type->subtype && !m->type->members)
+ return;
+ if (m->type->type == TTag &&
+ m->type->subtype && m->type->subtype->symbol &&
+ (s = getsym(m->type->subtype->symbol->name))) {
+ if (!m->optional && !m->defval)
+ generate_type_header(s);
+ return;
+ }
+ if (m->type->subtype) {
+ switch (m->type->subtype->type) {
+ case TSet:
+ case TSequence:
+ case TChoice:
+ break;
+ default:
+ return;
+ }
+ /* A field of some anonymous (inlined) structured type */
+ HEIM_TAILQ_FOREACH(sm, m->type->subtype->members, members) {
+ generate_subtypes_header_helper(sm);
+ }
+ }
+ if (m->type->members) {
+ HEIM_TAILQ_FOREACH(sm, m->type->members, members) {
+ generate_subtypes_header_helper(sm);
+ }
+ }
+}
+
+static void
+generate_subtypes_header(const Symbol *s)
+{
+ Type *t = s->type;
+ Member *m;
+
+ /*
+ * Recurse down structured types to make sure top-level types get
+ * defined before they are referenced.
+ *
+ * We'll take care to skip OPTIONAL member fields of constructed types so
+ * that we can have circular types like:
+ *
+ * Foo ::= SEQUENCE {
+ * bar Bar OPTIONAL
+ * }
+ *
+ * Bar ::= SEQUENCE {
+ * foo Foo OPTIONAL
+ * }
+ *
+ * not unlike XDR, which uses `*' to mean "optional", except in XDR it's
+ * called a "pointer". With some care we should be able to eventually
+ * support the silly XDR linked list example:
+ *
+ * ListOfFoo ::= SEQUENCE {
+ * someField SomeType,
+ * next ListOfFoo OPTIONAL
+ * }
+ *
+ * Not that anyone needs it -- just use a SEQUENCE OF and be done.
+ */
+
+ while (t->type == TTag && t->subtype) {
+ switch (t->subtype->type) {
+ case TTag:
+ case TSet:
+ case TSequence:
+ case TChoice:
+ t = t->subtype;
+ continue;
+ default:
+ break;
+ }
+ break;
+ }
+
+ switch (t->type) {
+ default: return;
+ case TType: {
+ Symbol *s2;
+ if (t->symbol && (s2 = getsym(t->symbol->name)) != s)
+ generate_type_header(s2);
+ return;
+ }
+ case TSet:
+ case TSequence:
+ case TChoice:
+ break;
+ }
+
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ generate_subtypes_header_helper(m);
+ }
+}
+
+static void
+generate_type_header (const Symbol *s)
+{
+ Type *t = s->type;
+
+ if (!s->type)
+ return;
+
+ /*
+ * Recurse down the types of member fields of `s' to make sure that
+ * referenced types have had their definitions emitted already if the
+ * member fields are not OPTIONAL/DEFAULTed.
+ */
+ generate_subtypes_header(s);
+ fprintf(headerfile, "/*\n");
+ fprintf(headerfile, "%s ::= ", s->name);
+ define_asn1 (0, s->type);
+ fprintf(headerfile, "\n*/\n\n");
+
+ /*
+ * Emit enums for the outermost tag of this type. These are needed for
+ * dealing with IMPLICIT tags so we know what to rewrite the tag to when
+ * decoding.
+ *
+ * See gen_encode.c and gen_decode.c for a complete explanation. Short
+ * version: we need to change the prototypes of the length/encode/decode
+ * functions to take an optional IMPLICIT tag to use instead of the type's
+ * outermost tag, but for now we hack it, and to do that we need to know
+ * the type's outermost tag outside the context of the bodies of the codec
+ * functions we generate for it. Using an enum means no extra space is
+ * needed in stripped objects.
+ */
+ if (!s->emitted_tag_enums) {
+ while (t->type == TType && s->type->symbol && s->type->symbol->type) {
+ if (t->subtype)
+ t = t->subtype;
+ else
+ t = s->type->symbol->type;
+ }
+
+ if (t->type == TType && t->symbol &&
+ strcmp(t->symbol->name, "HEIM_ANY") != 0) {
+ /*
+ * This type is ultimately an alias of an imported type, so we don't
+ * know its outermost tag here.
+ */
+ fprintf(headerfile,
+ "enum { asn1_tag_length_%s = asn1_tag_length_%s,\n"
+ " asn1_tag_class_%s = asn1_tag_class_%s,\n"
+ " asn1_tag_tag_%s = asn1_tag_tag_%s };\n",
+ s->gen_name, s->type->symbol->gen_name,
+ s->gen_name, s->type->symbol->gen_name,
+ s->gen_name, s->type->symbol->gen_name);
+ emitted_tag_enums(s);
+ } else if (t->type != TType) {
+ /* This type's outermost tag is known here */
+ fprintf(headerfile,
+ "enum { asn1_tag_length_%s = %lu,\n"
+ " asn1_tag_class_%s = %d,\n"
+ " asn1_tag_tag_%s = %d };\n",
+ s->gen_name, (unsigned long)length_tag(s->type->tag.tagvalue),
+ s->gen_name, s->type->tag.tagclass,
+ s->gen_name, s->type->tag.tagvalue);
+ emitted_tag_enums(s);
+ }
+ }
+
+ if (s->emitted_definition)
+ return;
+
+ if (is_export(s->name))
+ fprintf(symsfile, "ASN1_SYM_TYPE(\"%s\", \"%s\", %s)\n",
+ s->name, s->gen_name, s->gen_name);
+
+ fprintf(headerfile, "typedef ");
+ define_type(0, s->gen_name, s->gen_name, NULL, s->type, TRUE,
+ preserve_type(s->name) ? TRUE : FALSE);
+ fprintf(headerfile, "\n");
+
+ emitted_definition(s);
+}
+
+void
+generate_type_header_forwards(const Symbol *s)
+{
+ declare_type(s, s->type, TRUE);
+ fprintf(headerfile, "\n");
+ if (template_flag)
+ generate_template_type_forward(s->gen_name);
+}
+
+void
+generate_type (const Symbol *s)
+{
+ FILE *h;
+ const char * exp;
+
+ if (!one_code_file)
+ generate_header_of_codefile(s->gen_name);
+
+ generate_type_header(s);
+
+ if (template_flag)
+ generate_template(s);
+
+ if (template_flag == 0 || is_template_compat(s) == 0) {
+ generate_type_encode (s);
+ generate_type_decode (s);
+ generate_type_free (s);
+ generate_type_length (s);
+ generate_type_copy (s);
+ generate_type_print_stub(s);
+ }
+ generate_type_seq (s);
+ generate_glue (s->type, s->gen_name);
+
+ /* generate prototypes */
+
+ if (is_export(s->name)) {
+ h = headerfile;
+ exp = "ASN1EXP ";
+ } else {
+ h = privheaderfile;
+ exp = "";
+ }
+
+ fprintf (h,
+ "%sint ASN1CALL "
+ "decode_%s(const unsigned char *, size_t, %s *, size_t *);\n",
+ exp,
+ s->gen_name, s->gen_name);
+ fprintf (h,
+ "%sint ASN1CALL "
+ "encode_%s(unsigned char *, size_t, const %s *, size_t *);\n",
+ exp,
+ s->gen_name, s->gen_name);
+ fprintf (h,
+ "%ssize_t ASN1CALL length_%s(const %s *);\n",
+ exp,
+ s->gen_name, s->gen_name);
+ fprintf (h,
+ "%sint ASN1CALL copy_%s (const %s *, %s *);\n",
+ exp,
+ s->gen_name, s->gen_name, s->gen_name);
+ fprintf (h,
+ "%svoid ASN1CALL free_%s (%s *);\n",
+ exp,
+ s->gen_name, s->gen_name);
+
+ fprintf(h,
+ "%schar * ASN1CALL print_%s (const %s *, int);\n",
+ exp,
+ s->gen_name, s->gen_name);
+
+ fprintf(h, "\n\n");
+
+ if (!one_code_file) {
+ fprintf(codefile, "\n\n");
+ close_codefile();
+ }
+}
diff --git a/third_party/heimdal/lib/asn1/gen_copy.c b/third_party/heimdal/lib/asn1/gen_copy.c
new file mode 100644
index 0000000..bec6f8b
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/gen_copy.c
@@ -0,0 +1,290 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gen_locl.h"
+
+RCSID("$Id$");
+
+static int used_fail;
+
+static void
+copy_primitive (const char *typename, const char *from, const char *to)
+{
+ fprintf (codefile, "if(der_copy_%s(%s, %s)) goto fail;\n",
+ typename, from, to);
+ used_fail++;
+}
+
+static void
+copy_type (const char *from, const char *to, const Type *t, int preserve)
+{
+ switch (t->type) {
+ case TType:
+#if 0
+ copy_type (from, to, t->symbol->type, preserve);
+#endif
+ fprintf (codefile, "if(copy_%s(%s, %s)) goto fail;\n",
+ t->symbol->gen_name, from, to);
+ used_fail++;
+ break;
+ case TInteger:
+ if (t->range == NULL && t->members == NULL) {
+ copy_primitive ("heim_integer", from, to);
+ break;
+ }
+ fallthrough;
+ case TBoolean:
+ case TEnumerated :
+ fprintf(codefile, "*(%s) = *(%s);\n", to, from);
+ break;
+ case TOctetString:
+ copy_primitive ("octet_string", from, to);
+ break;
+ case TBitString:
+ if (HEIM_TAILQ_EMPTY(t->members))
+ copy_primitive ("bit_string", from, to);
+ else
+ fprintf(codefile, "*(%s) = *(%s);\n", to, from);
+ break;
+ case TSet:
+ case TSequence:
+ case TChoice: {
+ Member *m, *have_ellipsis = NULL;
+
+ if(t->members == NULL)
+ break;
+
+ if ((t->type == TSequence || t->type == TChoice) && preserve) {
+ fprintf(codefile,
+ "{ int ret;\n"
+ "ret = der_copy_octet_string(&(%s)->_save, &(%s)->_save);\n"
+ "if (ret) goto fail;\n"
+ "}\n",
+ from, to);
+ used_fail++;
+ }
+
+ if(t->type == TChoice) {
+ fprintf(codefile, "(%s)->element = (%s)->element;\n", to, from);
+ fprintf(codefile, "switch((%s)->element) {\n", from);
+ }
+
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ char *fs;
+ char *ts;
+
+ if (m->ellipsis) {
+ have_ellipsis = m;
+ continue;
+ }
+
+ if(t->type == TChoice)
+ fprintf(codefile, "case %s:\n", m->label);
+
+ if (asprintf (&fs, "%s(%s)->%s%s",
+ m->optional ? "" : "&", from,
+ t->type == TChoice ? "u." : "", m->gen_name) < 0)
+ errx(1, "malloc");
+ if (fs == NULL)
+ errx(1, "malloc");
+ if (asprintf (&ts, "%s(%s)->%s%s",
+ m->optional ? "" : "&", to,
+ t->type == TChoice ? "u." : "", m->gen_name) < 0)
+ errx(1, "malloc");
+ if (ts == NULL)
+ errx(1, "malloc");
+ if(m->optional){
+ fprintf(codefile, "if(%s) {\n", fs);
+ fprintf(codefile, "%s = calloc(1, sizeof(*%s));\n", ts, ts);
+ fprintf(codefile, "if(%s == NULL) goto fail;\n", ts);
+ used_fail++;
+ }
+ copy_type (fs, ts, m->type, FALSE);
+ if(m->optional){
+ fprintf(codefile, "}else\n");
+ fprintf(codefile, "%s = NULL;\n", ts);
+ }
+ free (fs);
+ free (ts);
+ if(t->type == TChoice)
+ fprintf(codefile, "break;\n");
+ }
+ if(t->type == TChoice) {
+ if (have_ellipsis) {
+ fprintf(codefile, "case %s: {\n"
+ "int ret;\n"
+ "ret=der_copy_octet_string(&(%s)->u.%s, &(%s)->u.%s);\n"
+ "if (ret) goto fail;\n"
+ "break;\n"
+ "}\n",
+ have_ellipsis->label,
+ from, have_ellipsis->gen_name,
+ to, have_ellipsis->gen_name);
+ used_fail++;
+ }
+ fprintf(codefile, "}\n");
+ }
+ break;
+ }
+ case TSetOf:
+ case TSequenceOf: {
+ char *f = NULL, *T = NULL;
+
+ fprintf (codefile, "if(((%s)->val = "
+ "calloc(1, (%s)->len * sizeof(*(%s)->val))) == NULL && (%s)->len != 0)\n",
+ to, from, to, from);
+ fprintf (codefile, "goto fail;\n");
+ used_fail++;
+ fprintf(codefile,
+ "for((%s)->len = 0; (%s)->len < (%s)->len; (%s)->len++){\n",
+ to, to, from, to);
+ if (asprintf(&f, "&(%s)->val[(%s)->len]", from, to) < 0)
+ errx(1, "malloc");
+ if (f == NULL)
+ errx(1, "malloc");
+ if (asprintf(&T, "&(%s)->val[(%s)->len]", to, to) < 0)
+ errx(1, "malloc");
+ if (T == NULL)
+ errx(1, "malloc");
+ copy_type(f, T, t->subtype, FALSE);
+ fprintf(codefile, "}\n");
+ free(f);
+ free(T);
+ break;
+ }
+ case TGeneralizedTime:
+ fprintf(codefile, "*(%s) = *(%s);\n", to, from);
+ break;
+ case TGeneralString:
+ copy_primitive ("general_string", from, to);
+ break;
+ case TTeletexString:
+ copy_primitive ("general_string", from, to);
+ break;
+ case TUTCTime:
+ fprintf(codefile, "*(%s) = *(%s);\n", to, from);
+ break;
+ case TUTF8String:
+ copy_primitive ("utf8string", from, to);
+ break;
+ case TPrintableString:
+ copy_primitive ("printable_string", from, to);
+ break;
+ case TIA5String:
+ copy_primitive ("ia5_string", from, to);
+ break;
+ case TBMPString:
+ copy_primitive ("bmp_string", from, to);
+ break;
+ case TUniversalString:
+ copy_primitive ("universal_string", from, to);
+ break;
+ case TVisibleString:
+ copy_primitive ("visible_string", from, to);
+ break;
+ case TTag:
+ copy_type (from, to, t->subtype, preserve);
+ break;
+ case TOID:
+ copy_primitive ("oid", from, to);
+ break;
+ case TNull:
+ break;
+ default :
+ abort ();
+ }
+}
+
+void
+generate_type_copy (const Symbol *s)
+{
+ struct decoration deco;
+ ssize_t more_deco = -1;
+ int preserve = preserve_type(s->name) ? TRUE : FALSE;
+ int save_used_fail = used_fail;
+
+ used_fail = 0;
+
+ fprintf (codefile, "int ASN1CALL\n"
+ "copy_%s(const %s *from, %s *to)\n"
+ "{\n"
+ "memset(to, 0, sizeof(*to));\n",
+ s->gen_name, s->gen_name, s->gen_name);
+ copy_type ("from", "to", s->type, preserve);
+ while (decorate_type(s->gen_name, &deco, &more_deco)) {
+ if (deco.ext && deco.copy_function_name == NULL) {
+ /* Decorated with field of external type but no copy function */
+ if (deco.ptr)
+ fprintf(codefile, "(to)->%s = 0;\n", deco.field_name);
+ else
+ fprintf(codefile, "memset(&(to)->%s, 0, sizeof((to)->%s));\n",
+ deco.field_name, deco.field_name);
+ } else if (deco.ext) {
+ /* Decorated with field of external type w/ copy function */
+ if (deco.ptr) {
+ fprintf(codefile, "if (from->%s) {\n", deco.field_name);
+ fprintf(codefile, "(to)->%s = calloc(1, sizeof(*(to)->%s));\n",
+ deco.field_name, deco.field_name);
+ fprintf(codefile, "if (%s((from)->%s, (to)->%s)) goto fail;\n",
+ deco.copy_function_name, deco.field_name, deco.field_name);
+ fprintf(codefile, "}\n");
+ } else {
+ fprintf(codefile, "if (%s(&(from)->%s, &(to)->%s)) goto fail;\n",
+ deco.copy_function_name, deco.field_name, deco.field_name);
+ }
+ } else if (deco.opt) {
+ /* Decorated with optional field of ASN.1 type */
+ fprintf(codefile, "if (from->%s) {\n", deco.field_name);
+ fprintf(codefile, "(to)->%s = calloc(1, sizeof(*(to)->%s));\n", deco.field_name, deco.field_name);
+ fprintf(codefile, "if (copy_%s((from)->%s, (to)->%s)) goto fail;\n", deco.field_type, deco.field_name, deco.field_name);
+ fprintf(codefile, "}\n");
+ } else {
+ /* Decorated with required field of ASN.1 type */
+ fprintf(codefile, "if (copy_%s(&(from)->%s, &(to)->%s)) goto fail;\n", deco.field_type, deco.field_name, deco.field_name);
+ }
+ used_fail++;
+ free(deco.field_type);
+ }
+ fprintf (codefile, "return 0;\n");
+
+ if (used_fail)
+ fprintf (codefile, "fail:\n"
+ "free_%s(to);\n"
+ "return ENOMEM;\n",
+ s->gen_name);
+
+ fprintf(codefile,
+ "}\n\n");
+ used_fail = save_used_fail;
+}
+
diff --git a/third_party/heimdal/lib/asn1/gen_decode.c b/third_party/heimdal/lib/asn1/gen_decode.c
new file mode 100644
index 0000000..fa9d79a
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/gen_decode.c
@@ -0,0 +1,841 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gen_locl.h"
+#include "lex.h"
+
+RCSID("$Id$");
+
+static void
+decode_primitive (const char *typename, const char *name, const char *forwstr)
+{
+#if 0
+ fprintf (codefile,
+ "e = decode_%s(p, len, %s, &l);\n"
+ "%s;\n",
+ typename,
+ name,
+ forwstr);
+#else
+ fprintf (codefile,
+ "e = der_get_%s(p, len, %s, &l);\n"
+ "if(e) %s;\np += l; len -= l; ret += l;\n",
+ typename,
+ name,
+ forwstr);
+#endif
+}
+
+static void
+find_tag (const Type *t,
+ Der_class *cl, Der_type *ty, unsigned *tag)
+{
+ switch (t->type) {
+ case TBitString:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_BitString;
+ break;
+ case TBoolean:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_Boolean;
+ break;
+ case TChoice:
+ errx(1, "Cannot have recursive CHOICE");
+ case TEnumerated:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_Enumerated;
+ break;
+ case TGeneralString:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_GeneralString;
+ break;
+ case TTeletexString:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_TeletexString;
+ break;
+ case TGeneralizedTime:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_GeneralizedTime;
+ break;
+ case TIA5String:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_IA5String;
+ break;
+ case TInteger:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_Integer;
+ break;
+ case TNull:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_Null;
+ break;
+ case TOID:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_OID;
+ break;
+ case TOctetString:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_OctetString;
+ break;
+ case TPrintableString:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_PrintableString;
+ break;
+ case TSequence:
+ case TSequenceOf:
+ *cl = ASN1_C_UNIV;
+ *ty = CONS;
+ *tag = UT_Sequence;
+ break;
+ case TSet:
+ case TSetOf:
+ *cl = ASN1_C_UNIV;
+ *ty = CONS;
+ *tag = UT_Set;
+ break;
+ case TTag:
+ *cl = t->tag.tagclass;
+ *ty = !(t->tag.tagclass != ASN1_C_UNIV &&
+ t->tag.tagenv == TE_EXPLICIT) &&
+ is_primitive_type(t->subtype) ? PRIM : CONS;
+ *tag = t->tag.tagvalue; /* XXX is this correct? */
+ break;
+ case TType:
+ if ((t->symbol->stype == Stype && t->symbol->type == NULL)
+ || t->symbol->stype == SUndefined) {
+ lex_error_message("%s is imported or still undefined, "
+ " can't generate tag checking data in CHOICE "
+ "without this information",
+ t->symbol->name);
+ exit(1);
+ }
+ find_tag(t->symbol->type, cl, ty, tag);
+ return;
+ case TUTCTime:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_UTCTime;
+ break;
+ case TUTF8String:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_UTF8String;
+ break;
+ case TBMPString:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_BMPString;
+ break;
+ case TUniversalString:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_UniversalString;
+ break;
+ case TVisibleString:
+ *cl = ASN1_C_UNIV;
+ *ty = PRIM;
+ *tag = UT_VisibleString;
+ break;
+ default:
+ abort();
+ }
+}
+
+static void
+range_check(const char *name,
+ const char *length,
+ const char *forwstr,
+ struct range *r)
+{
+ if (r->min == r->max + 2 || r->min < r->max)
+ fprintf (codefile,
+ "if ((%s)->%s > %lld) {\n"
+ "e = ASN1_MAX_CONSTRAINT; %s;\n"
+ "}\n",
+ name, length, (long long)r->max, forwstr);
+ if ((r->min - 1 == r->max || r->min < r->max) && r->min > 0)
+ fprintf (codefile,
+ "if ((%s)->%s < %lld) {\n"
+ "e = ASN1_MIN_CONSTRAINT; %s;\n"
+ "}\n",
+ name, length, (long long)r->min, forwstr);
+ if (r->max == r->min)
+ fprintf (codefile,
+ "if ((%s)->%s != %lld) {\n"
+ "e = ASN1_EXACT_CONSTRAINT; %s;\n"
+ "}\n",
+ name, length, (long long)r->min, forwstr);
+}
+
+static int
+decode_type(const char *name, const Type *t, int optional, struct value *defval,
+ const char *forwstr, const char *tmpstr, const char *dertype,
+ unsigned int depth)
+{
+ switch (t->type) {
+ case TType: {
+ if (optional)
+ fprintf(codefile,
+ "%s = calloc(1, sizeof(*%s));\n"
+ "if (%s == NULL) %s;\n",
+ name, name, name, forwstr);
+ fprintf (codefile,
+ "e = decode_%s(p, len, %s, &l);\n",
+ t->symbol->gen_name, name);
+ if (optional) {
+ fprintf (codefile,
+ "if(e == ASN1_MISSING_FIELD) {\n"
+ "free(%s);\n"
+ "%s = NULL;\n"
+ "} else if (e) { %s; \n"
+ "} else {\n"
+ "p += l; len -= l; ret += l;\n"
+ "}\n",
+ name, name, forwstr);
+ } else if (defval) {
+ fprintf(codefile,
+ "if (e == ASN1_MISSING_FIELD) {\n");
+ /*
+ * `name' starts with an ampersand here and is not an lvalue.
+ * We skip the ampersand and then it is an lvalue.
+ */
+ gen_assign_defval(name + 1, defval);
+ fprintf(codefile,
+ "} else if (e) { %s;\n"
+ "} else { p += l; len -= l; ret += l; }\n",
+ forwstr);
+ } else {
+ fprintf (codefile,
+ "if(e) %s;\n",
+ forwstr);
+ fprintf (codefile,
+ "p += l; len -= l; ret += l;\n");
+ }
+ break;
+ }
+ case TInteger:
+ if(t->members) {
+ /*
+ * This will produce a worning, how its hard to fix since:
+ * if its enum to an NameType, we can add appriate
+ * type-cast. If its not though, we have to figure out if
+ * there is negative enum enum and use appropriate
+ * signness and size on the intertype we cast the result
+ * too.
+ */
+ fprintf(codefile,
+ "{\n"
+ "int enumint;\n");
+ decode_primitive ("integer", "&enumint", forwstr);
+ fprintf(codefile,
+ "*%s = enumint;\n"
+ "}\n",
+ name);
+ } else if (t->range == NULL) {
+ decode_primitive ("heim_integer", name, forwstr);
+ } else if (t->range->min < 0 &&
+ (t->range->min < INT_MIN || t->range->max > INT_MAX)) {
+ decode_primitive ("integer64", name, forwstr);
+ } else if (t->range->min < 0) {
+ decode_primitive ("integer", name, forwstr);
+ } else if (t->range->max > UINT_MAX) {
+ decode_primitive ("unsigned64", name, forwstr);
+ } else {
+ decode_primitive ("unsigned", name, forwstr);
+ }
+ break;
+ case TBoolean:
+ decode_primitive ("boolean", name, forwstr);
+ break;
+ case TEnumerated:
+ decode_primitive ("enumerated", name, forwstr);
+ break;
+ case TOctetString:
+ if (dertype) {
+ fprintf(codefile,
+ "if (%s == CONS) {\n",
+ dertype);
+ decode_primitive("octet_string_ber", name, forwstr);
+ fprintf(codefile,
+ "} else {\n");
+ }
+ decode_primitive ("octet_string", name, forwstr);
+ if (dertype)
+ fprintf(codefile, "}\n");
+ if (t->range)
+ range_check(name, "length", forwstr, t->range);
+ break;
+ case TBitString: {
+ Member *m;
+ int pos = 0;
+
+ if (HEIM_TAILQ_EMPTY(t->members)) {
+ decode_primitive ("bit_string", name, forwstr);
+ break;
+ }
+ fprintf(codefile,
+ "if (len < 1) return ASN1_OVERRUN;\n"
+ "p++; len--; ret++;\n");
+ fprintf(codefile,
+ "do {\n"
+ "if (len < 1) break;\n");
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ while (m->val / 8 > pos / 8) {
+ fprintf (codefile,
+ "p++; len--; ret++;\n"
+ "if (len < 1) break;\n");
+ pos += 8;
+ }
+ fprintf(codefile,
+ "(%s)->%s = (*p >> %d) & 1;\n",
+ name, m->gen_name, (int)(7 - m->val % 8));
+ }
+ fprintf(codefile,
+ "} while(0);\n");
+ fprintf (codefile,
+ "p += len; ret += len;\n");
+ break;
+ }
+ case TSequence: {
+ Member *m;
+
+ if (t->members == NULL)
+ break;
+
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ char *s = NULL;
+
+ if (m->ellipsis)
+ continue;
+
+ if (asprintf (&s, "%s(%s)->%s", m->optional ? "" : "&",
+ name, m->gen_name) < 0 || s == NULL)
+ errx(1, "malloc");
+ decode_type(s, m->type, m->optional, m->defval, forwstr,
+ m->gen_name, NULL, depth + 1);
+ free (s);
+ }
+
+ break;
+ }
+ case TSet: {
+ /*
+ * SET { ... } is the dumbest construct in ASN.1. It's semantically
+ * indistinguishable from SEQUENCE { ... } but in BER you can write the
+ * fields in any order you wish, and in DER you have to write them in
+ * lexicographic order. If you want a reason to hate ASN.1, this is
+ * certainly one, though the real reason to hate ASN.1 is BER/DER/CER,
+ * and, really, all tag-length-value (TLV) encodings ever invented,
+ * including Protocol Buffers. Fortunately not all ASN.1 encoding
+ * rules are TLV or otherwise self-describing. "Self-describing"
+ * encoding rules other than those meant to be [somewhat] readable by
+ * humans, such as XML and JSON, are simply dumb. But SET { ... } is a
+ * truly special sort of dumb. The only possible use of SET { ... }
+ * might well be for ASN.1 mappings of XML schemas(?).
+ */
+ Member *m;
+ unsigned int memno;
+
+ if(t->members == NULL)
+ break;
+
+ fprintf(codefile, "{\n");
+ fprintf(codefile, "uint64_t members = 0;\n");
+ fprintf(codefile, "while(len > 0) {\n");
+ fprintf(codefile,
+ "Der_class class;\n"
+ "Der_type type;\n"
+ "unsigned int tag;\n"
+ "e = der_get_tag (p, len, &class, &type, &tag, NULL);\n"
+ "if(e) %s;\n", forwstr);
+ fprintf(codefile, "switch (MAKE_TAG(class, type, tag)) {\n");
+ memno = 0;
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ Type *mst = m->type; /* Member sub-type */
+ char *s;
+
+ while (mst->type == TType) {
+ assert(mst->subtype || (mst->symbol && mst->symbol->type));
+ mst = mst->subtype ? mst->subtype : mst->symbol->type;
+ }
+ assert(mst->type == TTag);
+
+ fprintf(codefile, "case MAKE_TAG(%s, %s, %s):\n",
+ classname(mst->tag.tagclass),
+ (mst->tag.tagclass == ASN1_C_UNIV || mst->tag.tagenv == TE_IMPLICIT) &&
+ is_primitive_type(mst->subtype) ? "PRIM" : "CONS",
+ valuename(mst->tag.tagclass, mst->tag.tagvalue));
+
+ if (asprintf (&s, "%s(%s)->%s", m->optional ? "" : "&", name, m->gen_name) < 0 || s == NULL)
+ errx(1, "malloc");
+ if(m->optional)
+ fprintf(codefile,
+ "%s = calloc(1, sizeof(*%s));\n"
+ "if (%s == NULL) { e = ENOMEM; %s; }\n",
+ s, s, s, forwstr);
+ decode_type (s, mst, 0, NULL, forwstr, m->gen_name, NULL, depth + 1);
+ free (s);
+
+ fprintf(codefile, "members |= (1ULL << %u);\n", memno);
+ memno++;
+ fprintf(codefile, "break;\n");
+ }
+ fprintf(codefile,
+ "default:\n"
+ "return ASN1_MISPLACED_FIELD;\n"
+ "break;\n");
+ fprintf(codefile, "}\n");
+ fprintf(codefile, "}\n");
+ memno = 0;
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ char *s;
+
+ if (asprintf (&s, "%s->%s", name, m->gen_name) < 0 || s == NULL)
+ errx(1, "malloc");
+ fprintf(codefile, "if((members & (1ULL << %u)) == 0)\n", memno);
+ if(m->optional)
+ fprintf(codefile, "%s = NULL;\n", s);
+ else if(m->defval)
+ gen_assign_defval(s, m->defval);
+ else
+ fprintf(codefile, "return ASN1_MISSING_FIELD;\n");
+ free(s);
+ memno++;
+ }
+ fprintf(codefile, "}\n");
+ break;
+ }
+ case TSetOf:
+ case TSequenceOf: {
+ char *n = NULL;
+ char *sname = NULL;
+
+ fprintf (codefile,
+ "{\n"
+ "size_t %s_origlen = len;\n"
+ "size_t %s_oldret = ret;\n"
+ "size_t %s_olen = 0;\n"
+ "void *%s_tmp;\n"
+ "ret = 0;\n"
+ "(%s)->len = 0;\n"
+ "(%s)->val = NULL;\n",
+ tmpstr,
+ tmpstr,
+ tmpstr,
+ tmpstr,
+ name,
+ name);
+
+ fprintf (codefile,
+ "while(ret < %s_origlen) {\n"
+ "size_t %s_nlen = %s_olen + sizeof(*((%s)->val));\n"
+ "if (%s_olen > %s_nlen) { e = ASN1_OVERFLOW; %s; }\n"
+ "%s_olen = %s_nlen;\n"
+ "%s_tmp = realloc((%s)->val, %s_olen);\n"
+ "if (%s_tmp == NULL) { e = ENOMEM; %s; }\n"
+ "(%s)->val = %s_tmp;\n",
+ tmpstr,
+ tmpstr, tmpstr, name,
+ tmpstr, tmpstr, forwstr,
+ tmpstr, tmpstr,
+ tmpstr, name, tmpstr,
+ tmpstr, forwstr,
+ name, tmpstr);
+
+ if (asprintf (&n, "&(%s)->val[(%s)->len]", name, name) < 0 || n == NULL)
+ errx(1, "malloc");
+ if (asprintf (&sname, "%s_s_of", tmpstr) < 0 || sname == NULL)
+ errx(1, "malloc");
+ decode_type(n, t->subtype, 0, NULL, forwstr, sname, NULL, depth + 1);
+ fprintf (codefile,
+ "(%s)->len++;\n"
+ "len = %s_origlen - ret;\n"
+ "}\n"
+ "ret += %s_oldret;\n"
+ "}\n",
+ name,
+ tmpstr, tmpstr);
+ if (t->range)
+ range_check(name, "len", forwstr, t->range);
+ free (n);
+ free (sname);
+ break;
+ }
+ case TGeneralizedTime:
+ decode_primitive ("generalized_time", name, forwstr);
+ break;
+ case TGeneralString:
+ decode_primitive ("general_string", name, forwstr);
+ break;
+ case TTeletexString:
+ decode_primitive ("general_string", name, forwstr);
+ break;
+ case TTag:{
+ char *tname = NULL, *typestring = NULL;
+ char *ide = NULL;
+ int replace_tag = 0;
+ int prim = !(t->tag.tagclass != ASN1_C_UNIV &&
+ t->tag.tagenv == TE_EXPLICIT) &&
+ is_primitive_type(t->subtype);
+
+ /*
+ * XXX See the comments in gen_encode() about this.
+ */
+ if (t->tag.tagenv == TE_IMPLICIT && !prim &&
+ t->subtype->type != TSequenceOf && t->subtype->type != TSetOf &&
+ t->subtype->type != TChoice) {
+ if (t->subtype->symbol &&
+ (t->subtype->type == TSequence ||
+ t->subtype->type == TSet))
+ replace_tag = 1;
+ else if (t->subtype->symbol &&
+ strcmp(t->subtype->symbol->name, "HEIM_ANY") != 0)
+ replace_tag = 1;
+ } else if (t->tag.tagenv == TE_IMPLICIT && prim && t->subtype->symbol)
+ replace_tag = is_tagged_type(t->subtype->symbol->type);
+
+ if (asprintf(&typestring, "%s_type", tmpstr) < 0 || typestring == NULL)
+ errx(1, "malloc");
+
+ fprintf(codefile,
+ "{\n"
+ "size_t %s_datalen;\n"
+ "Der_type %s;\n",
+ tmpstr, typestring);
+ if (replace_tag)
+ fprintf(codefile,
+ "const unsigned char *psave%u = p;\n"
+ "unsigned char *pcopy%u;\n"
+ "size_t lensave%u, lsave%u;\n",
+ depth, depth, depth, depth);
+ else if (support_ber)
+ fprintf(codefile,
+ "int is_indefinite%u;\n", depth);
+ if (!replace_tag)
+ fprintf(codefile,
+ "size_t %s_oldlen;\n", tmpstr);
+
+ fprintf(codefile, "e = der_match_tag_and_length(p, len, %s, &%s, %s, "
+ "&%s_datalen, &l);\n",
+ classname(t->tag.tagclass),
+ typestring,
+ valuename(t->tag.tagclass, t->tag.tagvalue),
+ tmpstr);
+
+ /* XXX hardcode for now */
+ if (!replace_tag && support_ber && t->subtype->type == TOctetString) {
+ ide = typestring;
+ } else {
+ fprintf(codefile,
+ "if (e == 0 && %s != %s) { e = ASN1_BAD_ID; }\n",
+ typestring,
+ prim ? "PRIM" : "CONS");
+ }
+
+ if(optional) {
+ fprintf(codefile,
+ "if(e) {\n"
+ "%s = NULL;\n"
+ "} else {\n"
+ "%s = calloc(1, sizeof(*%s));\n"
+ "if (%s == NULL) { e = ENOMEM; %s; }\n",
+ name, name, name, name, forwstr);
+ } else if (defval) {
+ char *s;
+
+ if (asprintf(&s, "*(%s)", name) == -1 || s == NULL)
+ return ENOMEM;
+ fprintf(codefile, "if (e && e != ASN1_MISSING_FIELD) %s;\n", forwstr);
+ fprintf(codefile, "if (e == ASN1_MISSING_FIELD) {\n");
+ gen_assign_defval(s, defval);
+ free(s);
+ fprintf(codefile, "e = 0; l= 0;\n} else {\n");
+ } else {
+ fprintf(codefile, "if (e) %s;\n", forwstr);
+ }
+
+ if (replace_tag)
+ fprintf(codefile,
+ "lsave%u = %s_datalen + l;\n"
+ "lensave%u = len;\n"
+ "e = der_replace_tag(p, len, &pcopy%u, &len, asn1_tag_class_%s, %s, asn1_tag_tag_%s);\n"
+ "if (e) %s;\n"
+ "p = pcopy%u;\n",
+ depth, tmpstr, depth, depth, t->subtype->symbol->gen_name,
+ prim ? "PRIM" : "CONS",
+ t->subtype->symbol->gen_name,
+ forwstr, depth);
+ else
+ fprintf(codefile,
+ "p += l; len -= l; ret += l;\n");
+ if (!replace_tag)
+ fprintf(codefile,
+ "%s_oldlen = len;\n",
+ tmpstr);
+ if (support_ber && !replace_tag)
+ fprintf (codefile,
+ "if((is_indefinite%u = _heim_fix_dce(%s_datalen, &len)) < 0)\n"
+ "{ e = ASN1_BAD_FORMAT; %s; }\n"
+ "if (is_indefinite%u) { if (len < 2) { e = ASN1_OVERRUN; %s; } len -= 2; }",
+ depth, tmpstr, forwstr, depth, forwstr);
+ else if (!replace_tag)
+ fprintf(codefile,
+ "if (%s_datalen > len) { e = ASN1_OVERRUN; %s; }\n"
+ "len = %s_datalen;\n", tmpstr, forwstr, tmpstr);
+ if (asprintf (&tname, "%s_Tag", tmpstr) < 0 || tname == NULL)
+ errx(1, "malloc");
+ /*
+ * If `replace_tag' then here `p' and `len' will be the copy mutated by
+ * der_replace_tag().
+ */
+ decode_type(name, t->subtype, 0, NULL, forwstr, tname, ide, depth + 1);
+ if (replace_tag)
+ fprintf(codefile,
+ "p = psave%u + lsave%u;\n"
+ "len = lensave%u - lsave%u;\n"
+ "ret += lsave%u - l;\n"
+ "free(pcopy%u);\n",
+ depth, depth, depth, depth, depth, depth);
+ else if(support_ber)
+ fprintf(codefile,
+ "if(is_indefinite%u){\n"
+ "len += 2;\n"
+ "e = der_match_tag_and_length(p, len, "
+ "(Der_class)0, &%s, UT_EndOfContent, "
+ "&%s_datalen, &l);\n"
+ "if(e) %s;\n"
+ "p += l; len -= l; ret += l;\n"
+ "if (%s != (Der_type)0) { e = ASN1_BAD_ID; %s; }\n"
+ "} else \n",
+ depth,
+ typestring,
+ tmpstr,
+ forwstr,
+ typestring, forwstr);
+ if (!replace_tag)
+ fprintf(codefile,
+ "len = %s_oldlen - %s_datalen;\n",
+ tmpstr, tmpstr);
+ if (optional)
+ fprintf(codefile, "}\n");
+ else if (defval)
+ fprintf(codefile, "}\n");
+ fprintf(codefile, "}\n");
+ free(tname);
+ free(typestring);
+ break;
+ }
+ case TChoice: {
+ Member *m, *have_ellipsis = NULL;
+ const char *els = "";
+
+ if (t->members == NULL)
+ break;
+
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ const Type *tt = m->type;
+ char *s = NULL;
+ Der_class cl;
+ Der_type ty;
+ unsigned tag;
+
+ if (m->ellipsis) {
+ have_ellipsis = m;
+ continue;
+ }
+
+ find_tag(tt, &cl, &ty, &tag);
+
+ fprintf(codefile,
+ "%sif (der_match_tag(p, len, %s, %s, %s, NULL) == 0) {\n",
+ els,
+ classname(cl),
+ ty ? "CONS" : "PRIM",
+ valuename(cl, tag));
+ fprintf(codefile,
+ "(%s)->element = %s;\n",
+ name, m->label);
+ if (asprintf (&s, "%s(%s)->u.%s", m->optional ? "" : "&",
+ name, m->gen_name) < 0 || s == NULL)
+ errx(1, "malloc");
+ decode_type(s, m->type, m->optional, NULL, forwstr, m->gen_name,
+ NULL, depth + 1);
+ free(s);
+ fprintf(codefile,
+ "}\n");
+ els = "else ";
+ }
+ if (have_ellipsis) {
+ fprintf(codefile,
+ "else {\n"
+ "(%s)->element = %s;\n"
+ "(%s)->u.%s.data = calloc(1, len);\n"
+ "if ((%s)->u.%s.data == NULL) {\n"
+ "e = ENOMEM; %s;\n"
+ "}\n"
+ "(%s)->u.%s.length = len;\n"
+ "memcpy((%s)->u.%s.data, p, len);\n"
+ "p += len;\n"
+ "ret += len;\n"
+ "len = 0;\n"
+ "}\n",
+ name, have_ellipsis->label,
+ name, have_ellipsis->gen_name,
+ name, have_ellipsis->gen_name,
+ forwstr,
+ name, have_ellipsis->gen_name,
+ name, have_ellipsis->gen_name);
+ } else {
+ fprintf(codefile,
+ "else {\n"
+ "e = ASN1_PARSE_ERROR;\n"
+ "%s;\n"
+ "}\n",
+ forwstr);
+ }
+ break;
+ }
+ case TUTCTime:
+ decode_primitive ("utctime", name, forwstr);
+ break;
+ case TUTF8String:
+ decode_primitive ("utf8string", name, forwstr);
+ break;
+ case TPrintableString:
+ decode_primitive ("printable_string", name, forwstr);
+ break;
+ case TIA5String:
+ decode_primitive ("ia5_string", name, forwstr);
+ break;
+ case TBMPString:
+ decode_primitive ("bmp_string", name, forwstr);
+ break;
+ case TUniversalString:
+ decode_primitive ("universal_string", name, forwstr);
+ break;
+ case TVisibleString:
+ decode_primitive ("visible_string", name, forwstr);
+ break;
+ case TNull:
+ fprintf (codefile, "/* NULL */\n");
+ break;
+ case TOID:
+ decode_primitive ("oid", name, forwstr);
+ break;
+ default :
+ abort ();
+ }
+ return 0;
+}
+
+void
+generate_type_decode (const Symbol *s)
+{
+ int preserve = preserve_type(s->name) ? TRUE : FALSE;
+
+ fprintf (codefile, "int ASN1CALL\n"
+ "decode_%s(const unsigned char *p HEIMDAL_UNUSED_ATTRIBUTE,"
+ " size_t len HEIMDAL_UNUSED_ATTRIBUTE, %s *data, size_t *size)\n"
+ "{\n",
+ s->gen_name, s->gen_name);
+
+ switch (s->type->type) {
+ case TInteger:
+ case TBoolean:
+ case TOctetString:
+ case TOID:
+ case TGeneralizedTime:
+ case TGeneralString:
+ case TTeletexString:
+ case TUTF8String:
+ case TPrintableString:
+ case TIA5String:
+ case TBMPString:
+ case TUniversalString:
+ case TVisibleString:
+ case TUTCTime:
+ case TNull:
+ case TEnumerated:
+ case TBitString:
+ case TSequence:
+ case TSequenceOf:
+ case TSet:
+ case TSetOf:
+ case TTag:
+ case TType:
+ case TChoice:
+ fprintf (codefile,
+ "size_t ret = 0;\n"
+ "size_t l HEIMDAL_UNUSED_ATTRIBUTE;\n"
+ "int e HEIMDAL_UNUSED_ATTRIBUTE;\n");
+ if (preserve)
+ fprintf (codefile, "const unsigned char *begin = p;\n");
+
+ fprintf (codefile, "\n");
+ fprintf (codefile, "memset(data, 0, sizeof(*data));\n"); /* hack to avoid `unused variable' */
+
+ decode_type("data", s->type, 0, NULL, "goto fail", "Top", NULL, 1);
+ if (preserve)
+ fprintf (codefile,
+ "data->_save.data = calloc(1, ret);\n"
+ "if (data->_save.data == NULL) { \n"
+ "e = ENOMEM; goto fail; \n"
+ "}\n"
+ "data->_save.length = ret;\n"
+ "memcpy(data->_save.data, begin, ret);\n");
+ fprintf (codefile,
+ "if(size) *size = ret;\n"
+ "return 0;\n");
+ fprintf (codefile,
+ "fail:\n"
+ "free_%s(data);\n"
+ "return e;\n",
+ s->gen_name);
+ break;
+ default:
+ abort ();
+ }
+ fprintf (codefile, "}\n\n");
+}
diff --git a/third_party/heimdal/lib/asn1/gen_encode.c b/third_party/heimdal/lib/asn1/gen_encode.c
new file mode 100644
index 0000000..403ddac
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/gen_encode.c
@@ -0,0 +1,747 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gen_locl.h"
+
+/* XXX same as der_length_tag */
+static size_t
+length_tag(unsigned int tag)
+{
+ size_t len = 0;
+
+ if(tag <= 30)
+ return 1;
+ while(tag) {
+ tag /= 128;
+ len++;
+ }
+ return len + 1;
+}
+
+static void
+encode_primitive (const char *typename, const char *name)
+{
+ fprintf (codefile,
+ "e = der_put_%s(p, len, %s, &l);\n"
+ "if (e) return e;\np -= l; len -= l; ret += l;\n\n",
+ typename,
+ name);
+}
+
+const char *
+classname(Der_class class)
+{
+ const char *cn[] = { "ASN1_C_UNIV", "ASN1_C_APPL",
+ "ASN1_C_CONTEXT", "ASN1_C_PRIV" };
+ if ((int)class >= sizeof(cn) / sizeof(cn[0]))
+ return "???";
+ return cn[class];
+}
+
+
+const char *
+valuename(Der_class class, int value)
+{
+ static char s[32];
+ struct {
+ int value;
+ const char *s;
+ } *p, values[] = {
+#define X(Y) { Y, #Y }
+ X(UT_BMPString),
+ X(UT_BitString),
+ X(UT_Boolean),
+ X(UT_EmbeddedPDV),
+ X(UT_Enumerated),
+ X(UT_External),
+ X(UT_GeneralString),
+ X(UT_GeneralizedTime),
+ X(UT_GraphicString),
+ X(UT_IA5String),
+ X(UT_Integer),
+ X(UT_Null),
+ X(UT_NumericString),
+ X(UT_OID),
+ X(UT_ObjectDescriptor),
+ X(UT_OctetString),
+ X(UT_PrintableString),
+ X(UT_Real),
+ X(UT_RelativeOID),
+ X(UT_Sequence),
+ X(UT_Set),
+ X(UT_TeletexString),
+ X(UT_UTCTime),
+ X(UT_UTF8String),
+ X(UT_UniversalString),
+ X(UT_VideotexString),
+ X(UT_VisibleString),
+#undef X
+ { -1, NULL }
+ };
+ if(class == ASN1_C_UNIV) {
+ for(p = values; p->value != -1; p++)
+ if(p->value == value)
+ return p->s;
+ }
+ snprintf(s, sizeof(s), "%d", value);
+ return s;
+}
+
+static int
+encode_type (const char *name, const Type *t, const char *tmpstr)
+{
+ int constructed = 1;
+
+ switch (t->type) {
+ case TType:
+#if 0
+ encode_type (name, t->symbol->type);
+#endif
+ fprintf (codefile,
+ "e = encode_%s(p, len, %s, &l);\n"
+ "if (e) return e;\np -= l; len -= l; ret += l;\n\n",
+ t->symbol->gen_name, name);
+ constructed = !is_primitive_type(t);
+ break;
+ case TInteger:
+ if(t->members) {
+ fprintf(codefile,
+ "{\n"
+ "int enumint = (int)*%s;\n",
+ name);
+ encode_primitive("integer", "&enumint");
+ fprintf(codefile, "}\n;");
+ } else if (t->range == NULL) {
+ encode_primitive("heim_integer", name);
+ } else if (t->range->min < 0 &&
+ (t->range->min < INT_MIN || t->range->max > INT_MAX)) {
+ encode_primitive("integer64", name);
+ } else if (t->range->min < 0) {
+ encode_primitive("integer", name);
+ } else if (t->range->max > UINT_MAX) {
+ encode_primitive("unsigned64", name);
+ } else {
+ encode_primitive("unsigned", name);
+ }
+
+ constructed = 0;
+ break;
+ case TBoolean:
+ encode_primitive ("boolean", name);
+ constructed = 0;
+ break;
+ case TOctetString:
+ encode_primitive ("octet_string", name);
+ constructed = 0;
+ break;
+ case TBitString: {
+ Member *m;
+ int pos;
+
+ if (HEIM_TAILQ_EMPTY(t->members)) {
+ encode_primitive("bit_string", name);
+ constructed = 0;
+ break;
+ }
+
+ fprintf (codefile, "{\n"
+ "unsigned char c = 0;\n");
+ if (!rfc1510_bitstring)
+ fprintf (codefile,
+ "int rest = 0;\n"
+ "int bit_set = 0;\n");
+#if 0
+ pos = t->members->prev->val;
+ /* fix for buggy MIT (and OSF?) code */
+ if (pos > 31)
+ abort ();
+#endif
+ /*
+ * It seems that if we do not always set pos to 31 here, the MIT
+ * code will do the wrong thing.
+ *
+ * I hate ASN.1 (and DER), but I hate it even more when everybody
+ * has to screw it up differently.
+ */
+ pos = HEIM_TAILQ_LAST(t->members, memhead)->val;
+ if (rfc1510_bitstring) {
+ if (pos < 31)
+ pos = 31;
+ }
+
+ HEIM_TAILQ_FOREACH_REVERSE(m, t->members, memhead, members) {
+ while (m->val / 8 < pos / 8) {
+ if (!rfc1510_bitstring)
+ fprintf (codefile,
+ "if (c != 0 || bit_set) {\n");
+ fprintf (codefile,
+ "if (len < 1) return ASN1_OVERFLOW;\n"
+ "*p-- = c; len--; ret++;\n");
+ if (!rfc1510_bitstring)
+ fprintf (codefile,
+ "if (!bit_set) {\n"
+ "rest = 0;\n"
+ "while(c) { \n"
+ "if (c & 1) break;\n"
+ "c = c >> 1;\n"
+ "rest++;\n"
+ "}\n"
+ "bit_set = 1;\n"
+ "}\n"
+ "}\n");
+ fprintf (codefile,
+ "c = 0;\n");
+ pos -= 8;
+ }
+ fprintf (codefile,
+ "if((%s)->%s) {\n"
+ "c |= 1<<%d;\n",
+ name, m->gen_name, (int)(7 - m->val % 8));
+ fprintf (codefile,
+ "}\n");
+ }
+
+ if (!rfc1510_bitstring)
+ fprintf (codefile,
+ "if (c != 0 || bit_set) {\n");
+ fprintf (codefile,
+ "if (len < 1) return ASN1_OVERFLOW;\n"
+ "*p-- = c; len--; ret++;\n");
+ if (!rfc1510_bitstring)
+ fprintf (codefile,
+ "if (!bit_set) {\n"
+ "rest = 0;\n"
+ "if(c) { \n"
+ "while(c) { \n"
+ "if (c & 1) break;\n"
+ "c = c >> 1;\n"
+ "rest++;\n"
+ "}\n"
+ "}\n"
+ "}\n"
+ "}\n");
+
+ fprintf (codefile,
+ "if (len < 1) return ASN1_OVERFLOW;\n"
+ "*p-- = %s;\n"
+ "len -= 1;\n"
+ "ret += 1;\n"
+ "}\n\n",
+ rfc1510_bitstring ? "0" : "rest");
+ constructed = 0;
+ break;
+ }
+ case TEnumerated : {
+ encode_primitive ("enumerated", name);
+ constructed = 0;
+ break;
+ }
+
+ case TSet:
+ case TSequence: {
+ Member *m;
+
+ if (t->members == NULL)
+ break;
+
+ HEIM_TAILQ_FOREACH_REVERSE(m, t->members, memhead, members) {
+ char *s = NULL;
+
+ if (m->ellipsis)
+ continue;
+
+ if (asprintf (&s, "%s(%s)->%s", m->optional ? "" : "&", name, m->gen_name) < 0 || s == NULL)
+ errx(1, "malloc");
+ fprintf(codefile, "/* %s */\n", m->name);
+ if (m->optional)
+ fprintf (codefile,
+ "if(%s) ",
+ s);
+ else if(m->defval)
+ gen_compare_defval(s + 1, m->defval);
+ fprintf (codefile, "{\n");
+ fprintf (codefile, "size_t %s_oldret HEIMDAL_UNUSED_ATTRIBUTE = ret;\n", tmpstr);
+ fprintf (codefile, "ret = 0;\n");
+ encode_type (s, m->type, m->gen_name);
+ fprintf (codefile, "ret += %s_oldret;\n", tmpstr);
+ fprintf (codefile, "}\n");
+ free (s);
+ }
+ break;
+ }
+ case TSetOf: {
+
+ fprintf(codefile,
+ "{\n"
+ "heim_octet_string *val;\n"
+ "size_t elen = 0, totallen = 0;\n"
+ "int eret = 0;\n");
+
+ fprintf(codefile,
+ "if ((%s)->len > UINT_MAX/sizeof(val[0]))\n"
+ "return ERANGE;\n",
+ name);
+
+ fprintf(codefile,
+ "val = calloc(1, sizeof(val[0]) * (%s)->len);\n"
+ "if (val == NULL && (%s)->len != 0) return ENOMEM;\n",
+ name, name);
+
+ fprintf(codefile,
+ "for(i = 0; i < (int)(%s)->len; i++) {\n",
+ name);
+
+ fprintf(codefile,
+ "ASN1_MALLOC_ENCODE(%s, val[i].data, "
+ "val[i].length, &(%s)->val[i], &elen, eret);\n",
+ t->subtype->symbol->gen_name,
+ name);
+
+ fprintf(codefile,
+ "if(eret) {\n"
+ "i--;\n"
+ "while (i >= 0) {\n"
+ "free(val[i].data);\n"
+ "i--;\n"
+ "}\n"
+ "free(val);\n"
+ "return eret;\n"
+ "}\n"
+ "totallen += elen;\n"
+ "}\n");
+
+ fprintf(codefile,
+ "if (totallen > len) {\n"
+ "for (i = 0; i < (int)(%s)->len; i++) {\n"
+ "free(val[i].data);\n"
+ "}\n"
+ "free(val);\n"
+ "return ASN1_OVERFLOW;\n"
+ "}\n",
+ name);
+
+ fprintf(codefile,
+ "qsort(val, (%s)->len, sizeof(val[0]), _heim_der_set_sort);\n",
+ name);
+
+ fprintf (codefile,
+ "for(i = (int)(%s)->len - 1; i >= 0; --i) {\n"
+ "p -= val[i].length;\n"
+ "ret += val[i].length;\n"
+ "memcpy(p + 1, val[i].data, val[i].length);\n"
+ "free(val[i].data);\n"
+ "}\n"
+ "free(val);\n"
+ "}\n",
+ name);
+ break;
+ }
+ case TSequenceOf: {
+ char *sname = NULL;
+ char *n = NULL;
+
+ fprintf (codefile,
+ "for(i = (int)(%s)->len - 1; i >= 0; --i) {\n"
+ "size_t %s_for_oldret = ret;\n"
+ "ret = 0;\n",
+ name, tmpstr);
+ if (asprintf (&n, "&(%s)->val[i]", name) < 0 || n == NULL)
+ errx(1, "malloc");
+ if (asprintf (&sname, "%s_S_Of", tmpstr) < 0 || sname == NULL)
+ errx(1, "malloc");
+ encode_type (n, t->subtype, sname);
+ fprintf (codefile,
+ "ret += %s_for_oldret;\n"
+ "}\n",
+ tmpstr);
+ free (n);
+ free (sname);
+ break;
+ }
+ case TGeneralizedTime:
+ encode_primitive ("generalized_time", name);
+ constructed = 0;
+ break;
+ case TGeneralString:
+ encode_primitive ("general_string", name);
+ constructed = 0;
+ break;
+ case TTeletexString:
+ encode_primitive ("general_string", name);
+ constructed = 0;
+ break;
+ case TTag: {
+ char *tname = NULL;
+ int replace_tag = 0;
+ int prim = !(t->tag.tagclass != ASN1_C_UNIV &&
+ t->tag.tagenv == TE_EXPLICIT) &&
+ is_primitive_type(t->subtype);
+ int c;
+ if (asprintf (&tname, "%s_tag", tmpstr) < 0 || tname == NULL)
+ errx(1, "malloc");
+ /*
+ * HACK HACK HACK
+ *
+ * This is part of the fix to the bug where we treated IMPLICIT tags of
+ * named types as EXPLICIT. I.e.
+ *
+ * Foo ::= SEQUENCE { ... }
+ * Bar ::= SEQUENCE { foo [0] IMPLICIT Foo }
+ *
+ * would get a context [0] constructed tag *and* a universal sequence
+ * constructed tag when it should get only the first tag.
+ *
+ * Properly fixing this would require changing the signatures of the
+ * encode, length, and decode functions we generate to take an optional
+ * tag to replace the one the encoder would generate / decoder would
+ * expect. That would change the ABI, which... isn't stable, but it's
+ * a bit soon to make that change.
+ *
+ * So, we're looking for IMPLICIT, and if we see any, we generate code
+ * to replace the tag.
+ *
+ * On the decode side we need to know what tag to restore. For this we
+ * generate enums in the generated header.
+ *
+ * NOTE: We *do* "replace" the tags of IMPLICIT-tagged primitive types,
+ * but our primitive codec functions leave those tags out, which
+ * is why we don't have to der_replace_tag() them here.
+ */
+ /*
+ * If the tag is IMPLICIT and it's not primitive and the subtype is not
+ * any kind of structure...
+ */
+ if (t->tag.tagenv == TE_IMPLICIT && !prim &&
+ t->subtype->type != TSequenceOf && t->subtype->type != TSetOf &&
+ t->subtype->type != TChoice) {
+ /* If it is a named type for a structured thing */
+ if (t->subtype->symbol &&
+ (t->subtype->type == TSequence ||
+ t->subtype->type == TSet))
+ replace_tag = 1;
+ else if (t->subtype->symbol && strcmp(t->subtype->symbol->name, "heim_any"))
+ replace_tag = 1;
+ } else if (t->tag.tagenv == TE_IMPLICIT && prim && t->subtype->symbol)
+ /*
+ * Because the subtype is named we are generating its codec
+ * functions, and those will be adding their UNIVERSAL or whatever
+ * tags unlike our raw primtive codec library.
+ */
+ replace_tag = is_tagged_type(t->subtype->symbol->type);
+
+ if (replace_tag)
+ fprintf(codefile,
+ "{ unsigned char *psave_%s = p, *pfree_%s = NULL;\n"
+ "size_t l2_%s, lensave_%s = len;\n"
+ "len = length_%s(%s);\n"
+ /* Allocate a temp buffer for the encoder */
+ "if ((p = pfree_%s = calloc(1, len)) == NULL) return ENOMEM;\n"
+ /* Make p point to the last byte of the allocated buf */
+ "p += len - 1;\n",
+ tmpstr, tmpstr, tmpstr, tmpstr,
+ t->subtype->symbol->gen_name, name, tmpstr);
+
+ /* XXX Currently we generate code that leaks `pfree_%s` here. */
+ c = encode_type (name, t->subtype, tname);
+ /* Explicit non-UNIVERSAL tags are always constructed */
+ if (!c && t->tag.tagclass != ASN1_C_UNIV && t->tag.tagenv == TE_EXPLICIT)
+ c = 1;
+ if (replace_tag)
+ fprintf(codefile,
+ "if (len) { free(pfree_%s); return EINVAL; }\n"
+ /*
+ * Here we have `p' pointing to one byte before the buffer
+ * we allocated above.
+ *
+ * [ T_wrong | LL | VVVV ] // temp buffer
+ * ^ ^
+ * | |
+ * | \
+ * \ +-- p + 1
+ * +-- p
+ *
+ * psave_<fieldName> still points to the last byte in the
+ * original buffer passed in where we should write the
+ * encoding of <fieldName>.
+ *
+ * We adjust psave_<fieldName> to point to before the TLV
+ * encoding of <fieldName> (with wrong tag) in the original
+ * buffer (this may NOT be a valid pointer, but we won't
+ * dereference it):
+ *
+ * [ ... | T_wrong | LL | VVVVV | ... ] // original buffer
+ * ^
+ * |
+ * \
+ * +-- psave_<fieldName>
+ */
+ "psave_%s -= l;\n"
+ /*
+ * We further adjust psave_<fieldName> to point to the last
+ * byte of what should be the T(ag) of the TLV encoding of
+ * <fieldName> (this is now a valid pointer), then...
+ *
+ * |<--->| (not written yet)
+ * | | |<-------->| (not written yet)
+ * [ ... | T_right | LL | VVVVV | ... ] // original buffer
+ * ^
+ * |
+ * \
+ * +-- psave_<fieldName>
+ */
+ "psave_%s += asn1_tag_length_%s;\n"
+ /*
+ * ...copy the L(ength)V(alue) of the TLV encoding of
+ * <fieldName>.
+ *
+ * [ ... | T_right | LL | VVVVV | ... ] // original buffer
+ * ^
+ * |
+ * \
+ * +-- psave_<fieldName> + 1
+ *
+ * |<----->| length is
+ * | | `l' - asn1_tag_length_<fieldName>
+ * [ T_wrong | LL | VVVV ] // temp buffer
+ * ^ ^
+ * | |
+ * | \
+ * \ +-- p + 1 + asn1_tag_length_%s
+ * +-- p + 1
+ */
+ "memcpy(psave_%s + 1, p + 1 + asn1_tag_length_%s, l - asn1_tag_length_%s);\n"
+ /*
+ * Encode the IMPLICIT tag. Recall that encoders like
+ * der_put_tag() take a pointer to the last byte they
+ * should write to, and a length of bytes to the left of
+ * that that they are allowed to write into.
+ *
+ * [ ... | T_right | LL | VVVVV | ... ] // original buffer
+ * ^
+ * |
+ * \
+ * +-- psave_<fieldName>
+ */
+ "e = der_put_tag(psave_%s, %zu, %s, %s, %d, &l2_%s);\n"
+ "if (e) { free(pfree_%s); return e; }\n"
+ /* Restore `len' and adjust it (see `p' below) */
+ "len = lensave_%s - (l + %zu - asn1_tag_length_%s);\n"
+ /*
+ * Adjust `ret' to account for the difference in size
+ * between the length of the right and wrong tags.
+ */
+ "ret += %zu - asn1_tag_length_%s;\n"
+ /* Free the buffer and restore `p' */
+ "free(pfree_%s);\n"
+ /*
+ * Make `p' point into the original buffer again, to one
+ * byte before the bytes we wrote:
+ *
+ * [ ... | T_right | LL | VVVVV | ... ] // original buffer
+ * ^
+ * |
+ * \
+ * +-- p
+ */
+ "p = psave_%s - (1 + %zu - asn1_tag_length_%s); }\n",
+ tmpstr, tmpstr, tmpstr, t->subtype->symbol->name,
+ tmpstr, t->subtype->symbol->name, t->subtype->symbol->name,
+ tmpstr, length_tag(t->tag.tagvalue),
+ classname(t->tag.tagclass),
+ c ? "CONS" : "PRIM",
+ t->tag.tagvalue,
+ tmpstr,
+
+ tmpstr, tmpstr, length_tag(t->tag.tagvalue), t->subtype->symbol->name,
+ length_tag(t->tag.tagvalue), t->subtype->symbol->name,
+ tmpstr, tmpstr, length_tag(t->tag.tagvalue), t->subtype->symbol->name);
+ else
+ fprintf(codefile,
+ "e = der_put_length_and_tag (p, len, ret, %s, %s, %s, &l);\n"
+ "if (e) return e;\np -= l; len -= l; ret += l;\n\n",
+ classname(t->tag.tagclass),
+ c ? "CONS" : "PRIM",
+ valuename(t->tag.tagclass, t->tag.tagvalue));
+ free(tname);
+ constructed = c;
+ break;
+ }
+ case TChoice:{
+ Member *m, *have_ellipsis = NULL;
+ char *s = NULL;
+
+ if (t->members == NULL)
+ break;
+
+ fprintf(codefile, "\n");
+
+ if (asprintf (&s, "(%s)", name) < 0 || s == NULL)
+ errx(1, "malloc");
+ fprintf(codefile, "switch(%s->element) {\n", s);
+
+ HEIM_TAILQ_FOREACH_REVERSE(m, t->members, memhead, members) {
+ char *s2 = NULL;
+
+ if (m->ellipsis) {
+ have_ellipsis = m;
+ continue;
+ }
+
+ fprintf (codefile, "case %s: {", m->label);
+ if (asprintf(&s2, "%s(%s)->u.%s", m->optional ? "" : "&",
+ s, m->gen_name) < 0 || s2 == NULL)
+ errx(1, "malloc");
+ if (m->optional)
+ fprintf (codefile, "if(%s) {\n", s2);
+ fprintf (codefile, "size_t %s_oldret = ret;\n", tmpstr);
+ fprintf (codefile, "ret = 0;\n");
+ constructed = encode_type (s2, m->type, m->gen_name);
+ fprintf (codefile, "ret += %s_oldret;\n", tmpstr);
+ if(m->optional)
+ fprintf (codefile, "}\n");
+ fprintf(codefile, "break;\n");
+ fprintf(codefile, "}\n");
+ free (s2);
+ }
+ free (s);
+ if (have_ellipsis) {
+ fprintf(codefile,
+ "case %s: {\n"
+ "if (len < (%s)->u.%s.length)\n"
+ "return ASN1_OVERFLOW;\n"
+ "p -= (%s)->u.%s.length;\n"
+ "ret += (%s)->u.%s.length;\n"
+ "memcpy(p + 1, (%s)->u.%s.data, (%s)->u.%s.length);\n"
+ "break;\n"
+ "}\n",
+ have_ellipsis->label,
+ name, have_ellipsis->gen_name,
+ name, have_ellipsis->gen_name,
+ name, have_ellipsis->gen_name,
+ name, have_ellipsis->gen_name,
+ name, have_ellipsis->gen_name);
+ }
+ fprintf(codefile, "};\n");
+ break;
+ }
+ case TOID:
+ encode_primitive ("oid", name);
+ constructed = 0;
+ break;
+ case TUTCTime:
+ encode_primitive ("utctime", name);
+ constructed = 0;
+ break;
+ case TUTF8String:
+ encode_primitive ("utf8string", name);
+ constructed = 0;
+ break;
+ case TPrintableString:
+ encode_primitive ("printable_string", name);
+ constructed = 0;
+ break;
+ case TIA5String:
+ encode_primitive ("ia5_string", name);
+ constructed = 0;
+ break;
+ case TBMPString:
+ encode_primitive ("bmp_string", name);
+ constructed = 0;
+ break;
+ case TUniversalString:
+ encode_primitive ("universal_string", name);
+ constructed = 0;
+ break;
+ case TVisibleString:
+ encode_primitive ("visible_string", name);
+ constructed = 0;
+ break;
+ case TNull:
+ fprintf (codefile, "/* NULL */\n");
+ constructed = 0;
+ break;
+ default:
+ abort ();
+ }
+ return constructed;
+}
+
+void
+generate_type_encode (const Symbol *s)
+{
+ fprintf (codefile, "int ASN1CALL\n"
+ "encode_%s(unsigned char *p HEIMDAL_UNUSED_ATTRIBUTE, size_t len HEIMDAL_UNUSED_ATTRIBUTE,"
+ " const %s *data, size_t *size)\n"
+ "{\n",
+ s->gen_name, s->gen_name);
+
+ switch (s->type->type) {
+ case TInteger:
+ case TBoolean:
+ case TOctetString:
+ case TGeneralizedTime:
+ case TGeneralString:
+ case TTeletexString:
+ case TUTCTime:
+ case TUTF8String:
+ case TPrintableString:
+ case TIA5String:
+ case TBMPString:
+ case TUniversalString:
+ case TVisibleString:
+ case TNull:
+ case TBitString:
+ case TEnumerated:
+ case TOID:
+ case TSequence:
+ case TSequenceOf:
+ case TSet:
+ case TSetOf:
+ case TTag:
+ case TType:
+ case TChoice:
+ fprintf (codefile,
+ "size_t ret HEIMDAL_UNUSED_ATTRIBUTE = 0;\n"
+ "size_t l HEIMDAL_UNUSED_ATTRIBUTE;\n"
+ "int i HEIMDAL_UNUSED_ATTRIBUTE, e HEIMDAL_UNUSED_ATTRIBUTE;\n\n");
+
+ encode_type("data", s->type, "Top");
+
+ fprintf (codefile, "*size = ret;\n"
+ "return 0;\n");
+ break;
+ default:
+ abort ();
+ }
+ fprintf (codefile, "}\n\n");
+}
diff --git a/third_party/heimdal/lib/asn1/gen_free.c b/third_party/heimdal/lib/asn1/gen_free.c
new file mode 100644
index 0000000..b6da8ae
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/gen_free.c
@@ -0,0 +1,240 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gen_locl.h"
+
+RCSID("$Id$");
+
+static void
+free_primitive (const char *typename, const char *name)
+{
+ fprintf (codefile, "der_free_%s(%s);\n", typename, name);
+}
+
+static void
+free_type (const char *name, const Type *t, int preserve)
+{
+ switch (t->type) {
+ case TType:
+#if 0
+ free_type (name, t->symbol->type, preserve);
+#endif
+ fprintf (codefile, "free_%s(%s);\n", t->symbol->gen_name, name);
+ break;
+ case TInteger:
+ if (t->range == NULL && t->members == NULL) {
+ free_primitive ("heim_integer", name);
+ break;
+ }
+ /* fallthrough; */
+ case TBoolean:
+ case TEnumerated :
+ case TNull:
+ case TGeneralizedTime:
+ case TUTCTime:
+ /*
+ * This doesn't do much, but it leaves zeros where garbage might
+ * otherwise have been found. Gets us closer to having the equivalent
+ * of a memset()-to-zero data structure after calling the free
+ * functions.
+ */
+ fprintf(codefile, "*%s = 0;\n", name);
+ break;
+ case TBitString:
+ if (HEIM_TAILQ_EMPTY(t->members))
+ free_primitive("bit_string", name);
+ break;
+ case TOctetString:
+ free_primitive ("octet_string", name);
+ break;
+ case TChoice:
+ case TSet:
+ case TSequence: {
+ Member *m, *have_ellipsis = NULL;
+
+ if (t->members == NULL)
+ break;
+
+ if ((t->type == TSequence || t->type == TChoice) && preserve)
+ fprintf(codefile, "der_free_octet_string(&data->_save);\n");
+
+ if(t->type == TChoice)
+ fprintf(codefile, "switch((%s)->element) {\n", name);
+
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ char *s;
+
+ if (m->ellipsis){
+ have_ellipsis = m;
+ continue;
+ }
+
+ if(t->type == TChoice)
+ fprintf(codefile, "case %s:\n", m->label);
+ if (asprintf (&s, "%s(%s)->%s%s",
+ m->optional ? "" : "&", name,
+ t->type == TChoice ? "u." : "", m->gen_name) < 0 || s == NULL)
+ errx(1, "malloc");
+ if(m->optional)
+ fprintf(codefile, "if(%s) {\n", s);
+ free_type (s, m->type, FALSE);
+ if(m->optional)
+ fprintf(codefile,
+ "free(%s);\n"
+ "%s = NULL;\n"
+ "}\n",s, s);
+ free (s);
+ if(t->type == TChoice)
+ fprintf(codefile, "break;\n");
+ }
+
+ if(t->type == TChoice) {
+ if (have_ellipsis)
+ fprintf(codefile,
+ "case %s:\n"
+ "der_free_octet_string(&(%s)->u.%s);\n"
+ "break;",
+ have_ellipsis->label,
+ name, have_ellipsis->gen_name);
+ fprintf(codefile, "}\n");
+ }
+ break;
+ }
+ case TSetOf:
+ case TSequenceOf: {
+ char *n;
+
+ fprintf (codefile, "if ((%s)->val)\nwhile((%s)->len){\n", name, name);
+ if (asprintf (&n, "&(%s)->val[(%s)->len-1]", name, name) < 0 || n == NULL)
+ errx(1, "malloc");
+ free_type(n, t->subtype, FALSE);
+ fprintf(codefile,
+ "(%s)->len--;\n"
+ "} else (%s)->len = 0;\n",
+ name, name);
+ fprintf(codefile,
+ "free((%s)->val);\n"
+ "(%s)->val = NULL;\n", name, name);
+ free(n);
+ break;
+ }
+ case TGeneralString:
+ free_primitive ("general_string", name);
+ break;
+ case TTeletexString:
+ free_primitive ("general_string", name);
+ break;
+ case TUTF8String:
+ free_primitive ("utf8string", name);
+ break;
+ case TPrintableString:
+ free_primitive ("printable_string", name);
+ break;
+ case TIA5String:
+ free_primitive ("ia5_string", name);
+ break;
+ case TBMPString:
+ free_primitive ("bmp_string", name);
+ break;
+ case TUniversalString:
+ free_primitive ("universal_string", name);
+ break;
+ case TVisibleString:
+ free_primitive ("visible_string", name);
+ break;
+ case TTag:
+ free_type (name, t->subtype, preserve);
+ break;
+ case TOID :
+ free_primitive ("oid", name);
+ break;
+ default :
+ abort ();
+ }
+}
+
+void
+generate_type_free (const Symbol *s)
+{
+ struct decoration deco;
+ ssize_t more_deco = -1;
+ int preserve = preserve_type(s->name) ? TRUE : FALSE;
+
+ fprintf (codefile, "void ASN1CALL\n"
+ "free_%s(%s *data)\n"
+ "{\n",
+ s->gen_name, s->gen_name);
+
+ free_type ("data", s->type, preserve);
+ while (decorate_type(s->gen_name, &deco, &more_deco)) {
+ if (deco.ext && deco.free_function_name == NULL) {
+ /* Decorated with field of external type but no free function */
+ if (deco.ptr)
+ fprintf(codefile, "(data)->%s = 0;\n", deco.field_name);
+ else
+ fprintf(codefile,
+ "memset(&(data)->%s, 0, sizeof((data)->%s));\n",
+ deco.field_name, deco.field_name);
+ } else if (deco.ext) {
+ /* Decorated with field of external type w/ free function */
+ if (deco.ptr) {
+ fprintf(codefile, "if ((data)->%s) {\n", deco.field_name);
+ fprintf(codefile, "%s((data)->%s);\n",
+ deco.free_function_name, deco.field_name);
+ fprintf(codefile, "(data)->%s = 0;\n", deco.field_name);
+ fprintf(codefile, "}\n");
+ } else {
+ fprintf(codefile, "%s(&(data)->%s);\n",
+ deco.free_function_name, deco.field_name);
+ fprintf(codefile,
+ "memset(&(data)->%s, 0, sizeof((data)->%s));\n",
+ deco.field_name, deco.field_name);
+ }
+ } else if (deco.opt) {
+ /* Decorated with optional field of ASN.1 type */
+ fprintf(codefile, "if ((data)->%s) {\n", deco.field_name);
+ fprintf(codefile, "free_%s((data)->%s);\n",
+ deco.field_type, deco.field_name);
+ fprintf(codefile, "free((data)->%s);\n", deco.field_name);
+ fprintf(codefile, "(data)->%s = NULL;\n", deco.field_name);
+ fprintf(codefile, "}\n");
+ } else {
+ /* Decorated with required field of ASN.1 type */
+ fprintf(codefile, "free_%s(&(data)->%s);\n",
+ deco.field_type, deco.field_name);
+ }
+ free(deco.field_type);
+ }
+ fprintf (codefile, "}\n\n");
+}
+
diff --git a/third_party/heimdal/lib/asn1/gen_glue.c b/third_party/heimdal/lib/asn1/gen_glue.c
new file mode 100644
index 0000000..424e5de
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/gen_glue.c
@@ -0,0 +1,162 @@
+/*
+ * Copyright (c) 1997, 1999, 2000, 2003 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gen_locl.h"
+
+RCSID("$Id$");
+
+static FILE *
+get_code_file(void)
+{
+ if (!one_code_file && template_flag && templatefile)
+ return templatefile;
+ return codefile;
+}
+
+static void
+generate_2int (const Type *t, const char *gen_name)
+{
+ Member *m;
+
+ fprintf (headerfile,
+ "uint64_t %s2int(%s);\n",
+ gen_name, gen_name);
+
+ fprintf (get_code_file(),
+ "uint64_t %s2int(%s f)\n"
+ "{\n"
+ "uint64_t r = 0;\n",
+ gen_name, gen_name);
+
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ fprintf (get_code_file(), "if(f.%s) r |= (1ULL << %d);\n",
+ m->gen_name, (int)m->val);
+ }
+ fprintf (get_code_file(), "return r;\n"
+ "}\n\n");
+}
+
+static void
+generate_int2 (const Type *t, const char *gen_name)
+{
+ Member *m;
+
+ fprintf (headerfile,
+ "%s int2%s(uint64_t);\n",
+ gen_name, gen_name);
+
+ fprintf (get_code_file(),
+ "%s int2%s(uint64_t n)\n"
+ "{\n"
+ "\t%s flags;\n\n"
+ "\tmemset(&flags, 0, sizeof(flags));\n\n",
+ gen_name, gen_name, gen_name);
+
+ if(t->members) {
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ fprintf (get_code_file(), "\tflags.%s = (n >> %d) & 1;\n",
+ m->gen_name, (int)m->val);
+ }
+ }
+ fprintf (get_code_file(), "\treturn flags;\n"
+ "}\n\n");
+}
+
+/*
+ * This depends on the bit string being declared in increasing order
+ */
+
+static void
+generate_units (const Type *t, const char *gen_name)
+{
+ Member *m;
+
+ fprintf (headerfile,
+ "const struct units * asn1_%s_units(void);\n",
+ gen_name);
+
+ fprintf (get_code_file(),
+ "static struct units %s_units[] = {\n",
+ gen_name);
+
+ if(t->members) {
+ HEIM_TAILQ_FOREACH_REVERSE(m, t->members, memhead, members) {
+ fprintf (get_code_file(),
+ "\t{\"%s\",\t1ULL << %d},\n", m->name, (int)m->val);
+ }
+ }
+
+ fprintf (get_code_file(),
+ "\t{NULL,\t0}\n"
+ "};\n\n");
+
+ fprintf (get_code_file(),
+ "const struct units * asn1_%s_units(void){\n"
+ "return %s_units;\n"
+ "}\n\n",
+ gen_name, gen_name);
+
+
+}
+
+void
+generate_glue (const Type *t, const char *gen_name)
+{
+ switch(t->type) {
+ case TTag:
+ generate_glue(t->subtype, gen_name);
+ break;
+ case TBitString : {
+ Member *m;
+
+ if (HEIM_TAILQ_EMPTY(t->members))
+ break;
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ if (m->val > 63) {
+ warnx("Not generating 2int, int2, or units for %s due to "
+ "having a member valued more than 63", gen_name);
+ return;
+ }
+ }
+ generate_2int (t, gen_name);
+ generate_int2 (t, gen_name);
+ if (parse_units_flag)
+ generate_units (t, gen_name);
+ break;
+ }
+ default :
+ break;
+ }
+}
diff --git a/third_party/heimdal/lib/asn1/gen_length.c b/third_party/heimdal/lib/asn1/gen_length.c
new file mode 100644
index 0000000..ab5c5f3
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/gen_length.c
@@ -0,0 +1,309 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gen_locl.h"
+
+RCSID("$Id$");
+
+static void
+length_primitive (const char *typename,
+ const char *name,
+ const char *variable)
+{
+ fprintf (codefile, "%s += der_length_%s(%s);\n", variable, typename, name);
+}
+
+/* XXX same as der_length_tag */
+static size_t
+length_tag(unsigned int tag)
+{
+ size_t len = 0;
+
+ if(tag <= 30)
+ return 1;
+ while(tag) {
+ tag /= 128;
+ len++;
+ }
+ return len + 1;
+}
+
+
+static int
+length_type (const char *name, const Type *t,
+ const char *variable, const char *tmpstr)
+{
+ switch (t->type) {
+ case TType:
+#if 0
+ length_type (name, t->symbol->type);
+#endif
+ fprintf (codefile, "%s += length_%s(%s);\n",
+ variable, t->symbol->gen_name, name);
+ break;
+ case TInteger:
+ if(t->members) {
+ fprintf(codefile,
+ "{\n"
+ "int enumint = *%s;\n", name);
+ length_primitive ("integer", "&enumint", variable);
+ fprintf(codefile, "}\n");
+ } else if (t->range == NULL) {
+ length_primitive ("heim_integer", name, variable);
+ } else if (t->range->min < 0 &&
+ (t->range->min < INT_MIN || t->range->max > INT_MAX)) {
+ length_primitive ("integer64", name, variable);
+ } else if (t->range->min < 0) {
+ length_primitive ("integer", name, variable);
+ } else if (t->range->max > UINT_MAX) {
+ length_primitive ("unsigned64", name, variable);
+ } else {
+ length_primitive ("unsigned", name, variable);
+ }
+ break;
+ case TBoolean:
+ fprintf (codefile, "%s += 1;\n", variable);
+ break;
+ case TEnumerated :
+ length_primitive ("enumerated", name, variable);
+ break;
+ case TOctetString:
+ length_primitive ("octet_string", name, variable);
+ break;
+ case TBitString: {
+ if (HEIM_TAILQ_EMPTY(t->members))
+ length_primitive("bit_string", name, variable);
+ else {
+ if (!rfc1510_bitstring) {
+ Member *m;
+ int pos = HEIM_TAILQ_LAST(t->members, memhead)->val;
+
+ fprintf(codefile,
+ "do {\n");
+ HEIM_TAILQ_FOREACH_REVERSE(m, t->members, memhead, members) {
+ while (m->val / 8 < pos / 8) {
+ pos -= 8;
+ }
+ fprintf (codefile,
+ "if((%s)->%s) { %s += %d; break; }\n",
+ name, m->gen_name, variable, (pos + 8) / 8);
+ }
+ fprintf(codefile,
+ "} while(0);\n");
+ fprintf (codefile, "%s += 1;\n", variable);
+ } else {
+ fprintf (codefile, "%s += 5;\n", variable);
+ }
+ }
+ break;
+ }
+ case TSet:
+ case TSequence:
+ case TChoice: {
+ Member *m, *have_ellipsis = NULL;
+
+ if (t->members == NULL)
+ break;
+
+ if(t->type == TChoice)
+ fprintf (codefile, "switch((%s)->element) {\n", name);
+
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ char *s;
+
+ if (m->ellipsis) {
+ have_ellipsis = m;
+ continue;
+ }
+
+ if(t->type == TChoice)
+ fprintf(codefile, "case %s:\n", m->label);
+
+ if (asprintf (&s, "%s(%s)->%s%s",
+ m->optional ? "" : "&", name,
+ t->type == TChoice ? "u." : "", m->gen_name) < 0 || s == NULL)
+ errx(1, "malloc");
+ if (m->optional)
+ fprintf (codefile, "if(%s)", s);
+ else if(m->defval)
+ gen_compare_defval(s + 1, m->defval);
+ fprintf (codefile, "{\n"
+ "size_t %s_oldret = %s;\n"
+ "%s = 0;\n", tmpstr, variable, variable);
+ length_type (s, m->type, "ret", m->gen_name);
+ fprintf (codefile, "ret += %s_oldret;\n", tmpstr);
+ fprintf (codefile, "}\n");
+ free (s);
+ if(t->type == TChoice)
+ fprintf(codefile, "break;\n");
+ }
+ if(t->type == TChoice) {
+ if (have_ellipsis)
+ fprintf(codefile,
+ "case %s:\n"
+ "ret += (%s)->u.%s.length;\n"
+ "break;\n",
+ have_ellipsis->label,
+ name,
+ have_ellipsis->gen_name);
+ fprintf (codefile, "}\n"); /* switch */
+ }
+ break;
+ }
+ case TSetOf:
+ case TSequenceOf: {
+ char *n = NULL;
+ char *sname = NULL;
+
+ fprintf (codefile,
+ "{\n"
+ "size_t %s_oldret = %s;\n"
+ "unsigned int n_%s;\n"
+ "%s = 0;\n",
+ tmpstr, variable, tmpstr, variable);
+
+ fprintf (codefile, "for(n_%s = (%s)->len; n_%s > 0; --n_%s){\n",
+ tmpstr, name, tmpstr, tmpstr);
+ fprintf (codefile, "size_t %s_for_oldret = %s;\n"
+ "%s = 0;\n", tmpstr, variable, variable);
+ if (asprintf (&n, "&(%s)->val[n_%s - 1]", name, tmpstr) < 0 || n == NULL)
+ errx(1, "malloc");
+ if (asprintf (&sname, "%s_S_Of", tmpstr) < 0 || sname == NULL)
+ errx(1, "malloc");
+ length_type(n, t->subtype, variable, sname);
+ fprintf (codefile, "%s += %s_for_oldret;\n",
+ variable, tmpstr);
+ fprintf (codefile, "}\n");
+
+ fprintf (codefile,
+ "%s += %s_oldret;\n"
+ "}\n", variable, tmpstr);
+ free(n);
+ free(sname);
+ break;
+ }
+ case TGeneralizedTime:
+ length_primitive ("generalized_time", name, variable);
+ break;
+ case TGeneralString:
+ length_primitive ("general_string", name, variable);
+ break;
+ case TTeletexString:
+ length_primitive ("general_string", name, variable);
+ break;
+ case TUTCTime:
+ length_primitive ("utctime", name, variable);
+ break;
+ case TUTF8String:
+ length_primitive ("utf8string", name, variable);
+ break;
+ case TPrintableString:
+ length_primitive ("printable_string", name, variable);
+ break;
+ case TIA5String:
+ length_primitive ("ia5_string", name, variable);
+ break;
+ case TBMPString:
+ length_primitive ("bmp_string", name, variable);
+ break;
+ case TUniversalString:
+ length_primitive ("universal_string", name, variable);
+ break;
+ case TVisibleString:
+ length_primitive ("visible_string", name, variable);
+ break;
+ case TNull:
+ fprintf (codefile, "/* NULL */\n");
+ break;
+ case TTag:{
+ char *tname = NULL;
+ int replace_tag = 0;
+ int prim = !(t->tag.tagclass != ASN1_C_UNIV &&
+ t->tag.tagenv == TE_EXPLICIT) &&
+ is_primitive_type(t->subtype);
+
+ if (asprintf(&tname, "%s_tag", tmpstr) < 0 || tname == NULL)
+ errx(1, "malloc");
+ length_type (name, t->subtype, variable, tname);
+ /* See the comments in encode_type() about IMPLICIT tags */
+ if (t->tag.tagenv == TE_IMPLICIT && !prim &&
+ t->subtype->type != TSequenceOf && t->subtype->type != TSetOf &&
+ t->subtype->type != TChoice) {
+ if (t->subtype->symbol &&
+ (t->subtype->type == TSequence ||
+ t->subtype->type == TSet))
+ replace_tag = 1;
+ else if (t->subtype->symbol && strcmp(t->subtype->symbol->name, "heim_any"))
+ replace_tag = 1;
+ } else if (t->tag.tagenv == TE_IMPLICIT && prim && t->subtype->symbol)
+ replace_tag = is_tagged_type(t->subtype->symbol->type);
+ if (replace_tag)
+ /*
+ * We're replacing the tag of the underlying type. If that type is
+ * imported, then we don't know its tag, so we rely on the
+ * asn1_tag_tag_<TypeName> enum value we generated for it, and we
+ * use the asn1_tag_length_<TypeName> enum value to avoid having to
+ * call der_length_tag() at run-time.
+ */
+ fprintf(codefile, "ret += %lu - asn1_tag_length_%s;\n",
+ (unsigned long)length_tag(t->tag.tagvalue),
+ t->subtype->symbol->gen_name);
+ else
+ fprintf(codefile, "ret += %lu + der_length_len (ret);\n",
+ (unsigned long)length_tag(t->tag.tagvalue));
+ free(tname);
+ break;
+ }
+ case TOID:
+ length_primitive ("oid", name, variable);
+ break;
+ default :
+ abort ();
+ }
+ return 0;
+}
+
+void
+generate_type_length (const Symbol *s)
+{
+ fprintf (codefile,
+ "size_t ASN1CALL\n"
+ "length_%s(const %s *data)\n"
+ "{\n"
+ "size_t ret = 0;\n",
+ s->gen_name, s->gen_name);
+
+ length_type ("data", s->type, "ret", "Top");
+ fprintf (codefile, "return ret;\n}\n\n");
+}
+
diff --git a/third_party/heimdal/lib/asn1/gen_locl.h b/third_party/heimdal/lib/asn1/gen_locl.h
new file mode 100644
index 0000000..f37f149
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/gen_locl.h
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) 1997-2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __GEN_LOCL_H__
+#define __GEN_LOCL_H__
+
+#include <config.h>
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <ctype.h>
+#include <time.h>
+#include <errno.h>
+#include <err.h>
+#include <roken.h>
+#include <getarg.h>
+#include "hash.h"
+#include "symbol.h"
+#include "asn1-common.h"
+#include "der.h"
+#include "der-private.h"
+
+/*
+ * XXX We need to move all module state out of globals and into a struct that
+ * we pass around when parsing and compiling a module, and also that we keep on
+ * a linked list of parsed modules.
+ *
+ * This is needed to:
+ *
+ * - implement IMPORTS correctly, because we need to know the type of a symbol
+ * in order to emit an extern declaration of it
+ * - implement value parsing
+ * - implement an ASN.1 library that does value parsing
+ *
+ * Value parsing, in particular, would be fantastic. We could then have
+ * options in hxtool(1) to load arbitrary ASN.1 modules and then parse SAN
+ * values given in ASN.1 value syntax on the command-line or in files. Eat
+ * your heart out OpenSSL if we do this!
+ *
+ * As well we'll need a `-I' option to the compiler so it knows where to find
+ * modules to IMPORT FROM.
+ */
+typedef struct asn1_module {
+ /* Name of ASN.1 module file: */
+ const char *orig_filename;
+ /* Name of file to always include for common type definitions: */
+ const char *type_file_string;
+ /* Name of public header file for module: */
+ const char *header;
+ /* Name of private header file for module: */
+ const char *privheader;
+ /* Basename of module: */
+ const char *headerbase;
+ /* Open stdio file handles for output: */
+ FILE *jsonfile;
+ FILE *privheaderfile;
+ FILE *headerfile;
+ FILE *oidsfile;
+ FILE *codefile;
+ FILE *logfile;
+ FILE *templatefile;
+ /* Module contents: */
+ struct sexport *exports;
+ struct import *imports;
+ Hashtab *htab; /* symbols */
+ /* Template state: */
+ struct templatehead *template;
+ struct tlisthead *tlistmaster;
+ /* CLI options and flags needed everywhere: */
+ getarg_strings preserve;
+ getarg_strings seq;
+ const char *enum_prefix;
+ unsigned int one_code_file:1;
+ unsigned int support_ber:1;
+ unsigned int parse_units_flag:1;
+ unsigned int prefix_enum:1; /* Should be a getarg_strings of bitrsting types to do this for */
+ unsigned int rfc1510_bitstring:1; /* Should be a getarg_strings of bitrsting types to do this for */
+} *asn1_module;
+
+void generate_type (const Symbol *);
+void generate_type_header_forwards(const Symbol *);
+void generate_constant (const Symbol *);
+void generate_type_encode (const Symbol *);
+void generate_type_decode (const Symbol *);
+void generate_type_free (const Symbol *);
+void generate_type_length (const Symbol *);
+void generate_type_print_stub(const Symbol *);
+void generate_type_copy (const Symbol *);
+void generate_type_seq (const Symbol *);
+void generate_glue (const Type *, const char*);
+
+const char *classname(Der_class);
+const char *valuename(Der_class, int);
+
+void gen_compare_defval(const char *, struct value *);
+void gen_assign_defval(const char *, struct value *);
+
+int objid_cmp(struct objid *, struct objid *);
+
+void init_generate (const char *, const char *);
+const char *get_filename (void);
+void close_generate(void);
+void add_import(const char *);
+void add_export(const char *);
+int is_export(const char *);
+int yyparse(void);
+int is_primitive_type(const Type *);
+int is_tagged_type(const Type *);
+
+int preserve_type(const char *);
+int seq_type(const char *);
+
+struct decoration {
+ char *field_type; /* C type name */
+ char *field_name; /* C struct field name */
+ char *copy_function_name; /* copy constructor function name */
+ char *free_function_name; /* destructor function name */
+ char *header_name; /* header name */
+ unsigned int decorated:1;
+ unsigned int first:1; /* optional */
+ unsigned int opt:1; /* optional */
+ unsigned int ext:1; /* external */
+ unsigned int ptr:1; /* external, pointer */
+ unsigned int void_star:1; /* external, void * */
+ unsigned int struct_star:1; /* external, struct foo * */
+};
+int decorate_type(const char *, struct decoration *, ssize_t *);
+
+void generate_header_of_codefile(const char *);
+void close_codefile(void);
+
+void get_open_type_defn_fields(const Type *, Member **, Member **, Field **,
+ Field **, int *);
+void sort_object_set(IOSObjectSet *, Field *, IOSObject ***, size_t *);
+int object_cmp(const void *, const void *);
+
+int is_template_compat (const Symbol *);
+void generate_template(const Symbol *);
+void generate_template_type_forward(const char *);
+void generate_template_objectset_forwards(const Symbol *);
+void gen_template_import(const Symbol *);
+
+struct objid **objid2list(struct objid *);
+
+extern FILE *jsonfile, *privheaderfile, *headerfile, *codefile, *logfile, *templatefile;
+extern const char *fuzzer_string;
+extern int support_ber;
+extern int template_flag;
+extern int rfc1510_bitstring;
+extern int one_code_file;
+extern int original_order;
+extern int parse_units_flag;
+extern char *type_file_string;
+
+extern int error_flag;
+
+#endif /* __GEN_LOCL_H__ */
diff --git a/third_party/heimdal/lib/asn1/gen_print.c b/third_party/heimdal/lib/asn1/gen_print.c
new file mode 100644
index 0000000..4cca9e0
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/gen_print.c
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2021 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gen_locl.h"
+
+void
+generate_type_print_stub(const Symbol *s)
+{
+ fprintf(codefile, "char * ASN1CALL\n"
+ "print_%s(const %s *data, int flags)\n"
+ "{ errno = EINVAL; return 0; }\n\n",
+ s->gen_name, s->gen_name);
+}
diff --git a/third_party/heimdal/lib/asn1/gen_seq.c b/third_party/heimdal/lib/asn1/gen_seq.c
new file mode 100644
index 0000000..9762813
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/gen_seq.c
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gen_locl.h"
+
+RCSID("$Id$");
+
+static FILE *
+get_code_file(void)
+{
+ if (!one_code_file && template_flag && templatefile)
+ return templatefile;
+ return codefile;
+}
+
+void
+generate_type_seq (const Symbol *s)
+{
+ char *subname;
+ Type *type;
+
+ if (!seq_type(s->name))
+ return;
+ type = s->type;
+ while(type->type == TTag)
+ type = type->subtype;
+
+ if (type->type != TSequenceOf && type->type != TSetOf) {
+ fprintf(stderr, "%s not seq of %d\n", s->name, (int)type->type);
+ return;
+ }
+
+ /*
+ * Require the subtype to be a type so we can name it and use
+ * copy_/free_
+ */
+
+ if (type->subtype->type != TType) {
+ fprintf(stderr, "%s subtype is not a type, can't generate "
+ "sequence code for this case: %d\n",
+ s->name, (int)type->subtype->type);
+ exit(1);
+ }
+
+ subname = type->subtype->symbol->gen_name;
+
+ fprintf (headerfile,
+ "ASN1EXP int ASN1CALL add_%s (%s *, const %s *);\n"
+ "ASN1EXP int ASN1CALL remove_%s (%s *, unsigned int);\n",
+ s->gen_name, s->gen_name, subname,
+ s->gen_name, s->gen_name);
+
+ fprintf (get_code_file(), "int ASN1CALL\n"
+ "add_%s(%s *data, const %s *element)\n"
+ "{\n",
+ s->gen_name, s->gen_name, subname);
+
+ fprintf (get_code_file(),
+ "int ret;\n"
+ "void *ptr;\n"
+ "\n"
+ "ptr = realloc(data->val, \n"
+ "\t(data->len + 1) * sizeof(data->val[0]));\n"
+ "if (ptr == NULL) return ENOMEM;\n"
+ "data->val = ptr;\n\n"
+ "ret = copy_%s(element, &data->val[data->len]);\n"
+ "if (ret) return ret;\n"
+ "data->len++;\n"
+ "return 0;\n",
+ subname);
+
+ fprintf (get_code_file(), "}\n\n");
+
+ fprintf (get_code_file(), "int ASN1CALL\n"
+ "remove_%s(%s *data, unsigned int element)\n"
+ "{\n",
+ s->gen_name, s->gen_name);
+
+ fprintf (get_code_file(),
+ "void *ptr;\n"
+ "\n"
+ "if (data->len == 0 || element >= data->len)\n"
+ "\treturn ASN1_OVERRUN;\n"
+ "free_%s(&data->val[element]);\n"
+ "data->len--;\n"
+ /* don't move if its the last element */
+ "if (element < data->len)\n"
+ "\tmemmove(&data->val[element], &data->val[element + 1], \n"
+ "\t\tsizeof(data->val[0]) * (data->len - element));\n"
+ /* resize but don't care about failures since it doesn't matter */
+ "ptr = realloc(data->val, data->len * sizeof(data->val[0]));\n"
+ "if (ptr != NULL || data->len == 0) data->val = ptr;\n"
+ "return 0;\n",
+ subname);
+
+ fprintf (get_code_file(), "}\n\n");
+}
diff --git a/third_party/heimdal/lib/asn1/gen_template.c b/third_party/heimdal/lib/asn1/gen_template.c
new file mode 100644
index 0000000..ad25fcf
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/gen_template.c
@@ -0,0 +1,1675 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 - 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * Currently we generate C source code defining constant arrays of structures
+ * containing a sort of a "byte-coded" template of an ASN.1 compiler to be
+ * interpreted at run-time.
+ */
+
+#include "gen_locl.h"
+#include <vis.h>
+#include <vis-extras.h>
+
+static const char *symbol_name(const char *, const Type *);
+static void generate_template_type(const char *, const char **, const char *, const char *, const char *,
+ Type *, int, int, int);
+
+static const char *
+ttype_symbol(const char *basename, const Type *t)
+{
+ return t->symbol->gen_name;
+}
+
+static const char *
+integer_symbol(const char *basename, const Type *t)
+{
+ if (t->members)
+ /*
+ * XXX enum foo -- compute the size either from inspecting the members
+ * and applying the ABI's rules for enum size, OR infer the field
+ * size from a template by using the offsetof field. The latter is
+ * hard to do though.
+ */
+ return "int";
+ else if (t->range == NULL)
+ return "heim_integer";
+ else if (t->range->min < 0 &&
+ (t->range->min < INT_MIN || t->range->max > INT_MAX))
+ return "int64_t";
+ else if (t->range->min < 0)
+ return "int";
+ else if (t->range->max > UINT_MAX)
+ return "uint64_t";
+ else
+ return "unsigned";
+}
+
+static const char *
+boolean_symbol(const char *basename, const Type *t)
+{
+ return "int";
+}
+
+
+static const char *
+octetstring_symbol(const char *basename, const Type *t)
+{
+ return "heim_octet_string";
+}
+
+static const char *
+sequence_symbol(const char *basename, const Type *t)
+{
+ return basename;
+}
+
+static const char *
+time_symbol(const char *basename, const Type *t)
+{
+ return "time_t";
+}
+
+static const char *
+tag_symbol(const char *basename, const Type *t)
+{
+ return symbol_name(basename, t->subtype);
+}
+
+static const char *
+generalstring_symbol(const char *basename, const Type *t)
+{
+ return "heim_general_string";
+}
+
+static const char *
+printablestring_symbol(const char *basename, const Type *t)
+{
+ return "heim_printable_string";
+}
+
+static const char *
+ia5string_symbol(const char *basename, const Type *t)
+{
+ return "heim_ia5_string";
+}
+
+static const char *
+teletexstring_symbol(const char *basename, const Type *t)
+{
+ return "heim_general_string";
+}
+
+static const char *
+visiblestring_symbol(const char *basename, const Type *t)
+{
+ return "heim_visible_string";
+}
+
+static const char *
+utf8string_symbol(const char *basename, const Type *t)
+{
+ return "heim_utf8_string";
+}
+
+static const char *
+bmpstring_symbol(const char *basename, const Type *t)
+{
+ return "heim_bmp_string";
+}
+
+static const char *
+universalstring_symbol(const char *basename, const Type *t)
+{
+ return "heim_universal_string";
+}
+
+static const char *
+oid_symbol(const char *basename, const Type *t)
+{
+ return "heim_oid";
+}
+
+static const char *
+bitstring_symbol(const char *basename, const Type *t)
+{
+ if (t->members)
+ return basename;
+ return "heim_bit_string";
+}
+
+
+
+/* Keep this sorted by `type' so we can just index this by type */
+const struct {
+ enum typetype type;
+ const char *(*symbol_name)(const char *, const Type *);
+ int is_struct;
+} types[] = {
+ { TBitString, bitstring_symbol, 0 },
+ { TBoolean, boolean_symbol, 0 },
+ { TChoice, sequence_symbol, 1 },
+ { TEnumerated, integer_symbol, 0 },
+ { TGeneralString, generalstring_symbol, 0 },
+ { TTeletexString, teletexstring_symbol, 0 },
+ { TGeneralizedTime, time_symbol, 0 },
+ { TIA5String, ia5string_symbol, 0 },
+ { TInteger, integer_symbol, 0 },
+ { TNull, integer_symbol, 1 },
+ { TOID, oid_symbol, 0 },
+ { TOctetString, octetstring_symbol, 0 },
+ { TPrintableString, printablestring_symbol, 0 },
+ { TSequence, sequence_symbol, 1 },
+ { TSequenceOf, tag_symbol, 1 },
+ { TSet, sequence_symbol, 1 },
+ { TSetOf, tag_symbol, 1 },
+ { TTag, tag_symbol, 1 },
+ { TType, ttype_symbol, 1 },
+ { TUTCTime, time_symbol, 0 },
+ { TUTF8String, utf8string_symbol, 0 },
+ { TBMPString, bmpstring_symbol, 0 },
+ { TUniversalString, universalstring_symbol, 0 },
+ { TVisibleString, visiblestring_symbol, 0 },
+};
+
+static FILE *
+get_code_file(void)
+{
+ if (!one_code_file)
+ return templatefile;
+ return codefile;
+}
+
+
+static int
+is_supported_type_p(const Type *t)
+{
+ return t->type >= 0 && t->type <= TVisibleString &&
+ types[t->type].type == t->type;
+}
+
+int
+is_template_compat (const Symbol *s)
+{
+ return is_supported_type_p(s->type);
+}
+
+static const char *
+symbol_name(const char *basename, const Type *t)
+{
+ if (t->type >= 0 && t->type <= TVisibleString &&
+ types[t->type].type == t->type)
+ return (types[t->type].symbol_name)(basename, t);
+ if (t->type >= 0 && t->type <= TVisibleString)
+ errx(1, "types[] is not sorted");
+ errx(1, "unknown der type: %d\n", t->type);
+ return NULL;
+}
+
+
+static char *
+partial_offset(const char *basetype, const char *name, int need_offset, int isstruct)
+{
+ char *str;
+ if (name == NULL || need_offset == 0)
+ return strdup("0");
+ if (asprintf(&str, "offsetof(%s%s, %s)", isstruct ? "struct " : "", basetype, name) < 0 || str == NULL)
+ errx(1, "malloc");
+ return str;
+}
+
+struct template {
+ char *line;
+ char *tt;
+ char *offset;
+ char *ptr;
+ HEIM_TAILQ_ENTRY(template) members;
+};
+
+HEIM_TAILQ_HEAD(templatehead, template);
+
+struct tlist {
+ char *name;
+ char *header;
+ struct templatehead template;
+ HEIM_TAILQ_ENTRY(tlist) tmembers;
+};
+
+HEIM_TAILQ_HEAD(tlisthead, tlist);
+
+static void tlist_header(struct tlist *, const char *, ...) __attribute__ ((__format__ (__printf__, 2, 3)));
+static struct template *
+ add_line(struct templatehead *, const char *, ...) __attribute__ ((__format__ (__printf__, 2, 3)));
+static int tlist_cmp(const struct tlist *, const struct tlist *);
+
+static void add_line_pointer(struct templatehead *, const char *, const char *, const char *, ...)
+ __attribute__ ((__format__ (__printf__, 4, 5)));
+static void add_line_string(struct templatehead *, const char *, const char *, const char *, ...)
+ __attribute__ ((__format__ (__printf__, 4, 5)));
+static void add_line_pointer_reference(struct templatehead *, const char *, const char *, const char *, ...)
+ __attribute__ ((__format__ (__printf__, 4, 5)));
+
+
+static struct tlisthead tlistmaster = HEIM_TAILQ_HEAD_INITIALIZER(tlistmaster);
+static unsigned long numdups = 0;
+
+static struct tlist *
+tlist_new(const char *name)
+{
+ struct tlist *tl = calloc(1, sizeof(*tl));
+ tl->name = strdup(name);
+ HEIM_TAILQ_INIT(&tl->template);
+ return tl;
+}
+
+static void
+tlist_header(struct tlist *t, const char *fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ if (vasprintf(&t->header, fmt, ap) < 0 || t->header == NULL)
+ errx(1, "malloc");
+ va_end(ap);
+}
+
+static unsigned long
+tlist_count(struct tlist *tl)
+{
+ unsigned int count = 0;
+ struct template *q;
+
+ HEIM_TAILQ_FOREACH(q, &tl->template, members) {
+ count++;
+ }
+ return count;
+}
+
+static void
+tlist_add(struct tlist *tl)
+{
+ HEIM_TAILQ_INSERT_TAIL(&tlistmaster, tl, tmembers);
+}
+
+static void
+tlist_print(struct tlist *tl)
+{
+ struct template *q;
+ unsigned int i = 1;
+ FILE *f = get_code_file();
+
+ fprintf(f, "const struct asn1_template asn1_%s[] = {\n", tl->name);
+ fprintf(f, "/* 0 */ %s,\n", tl->header);
+ HEIM_TAILQ_FOREACH(q, &tl->template, members) {
+ int last = (HEIM_TAILQ_LAST(&tl->template, templatehead) == q);
+ fprintf(f, "/* %lu */ %s%s\n", (unsigned long)i++, q->line, last ? "" : ",");
+ }
+ fprintf(f, "};\n");
+}
+
+static struct tlist *
+tlist_find_by_name(const char *name)
+{
+ struct tlist *ql;
+ HEIM_TAILQ_FOREACH(ql, &tlistmaster, tmembers) {
+ if (strcmp(ql->name, name) == 0)
+ return ql;
+ }
+ return NULL;
+}
+
+static int
+tlist_cmp_name(const char *tname, const char *qname)
+{
+ struct tlist *tl = tlist_find_by_name(tname);
+ struct tlist *ql = tlist_find_by_name(qname);
+ if (tl == NULL)
+ return 1;
+ if (ql == NULL)
+ return -1;
+ return tlist_cmp(tl, ql);
+}
+
+static int
+tlist_cmp(const struct tlist *tl, const struct tlist *ql)
+{
+ int ret;
+ struct template *t, *q;
+
+ if (tl == ql)
+ return 0;
+ ret = strcmp(tl->header, ql->header);
+ if (ret != 0) return ret;
+
+ q = HEIM_TAILQ_FIRST(&ql->template);
+ HEIM_TAILQ_FOREACH(t, &tl->template, members) {
+ if (q == NULL) return 1;
+
+ if (t->ptr == NULL || q->ptr == NULL) {
+ ret = strcmp(t->line, q->line);
+ if (ret != 0) return ret;
+ } else {
+ ret = strcmp(t->tt, q->tt);
+ if (ret != 0) return ret;
+
+ ret = strcmp(t->offset, q->offset);
+ if (ret != 0) return ret;
+
+ if ((ret = strcmp(t->ptr, q->ptr)) != 0 ||
+ (ret = tlist_cmp_name(t->ptr, q->ptr)) != 0)
+ return ret;
+ }
+ q = HEIM_TAILQ_NEXT(q, members);
+ }
+ if (q != NULL) return -1;
+ return 0;
+}
+
+
+static const char *
+tlist_find_dup(const struct tlist *tl)
+{
+ struct tlist *ql;
+
+ HEIM_TAILQ_FOREACH(ql, &tlistmaster, tmembers) {
+ if (tlist_cmp(ql, tl) == 0) {
+ numdups++;
+ return ql->name;
+ }
+ }
+ return NULL;
+}
+
+
+/*
+ * Add an entry to a template.
+ */
+
+static struct template *
+add_line(struct templatehead *t, const char *fmt, ...)
+{
+ struct template *q = calloc(1, sizeof(*q));
+ va_list ap;
+ va_start(ap, fmt);
+ if (vasprintf(&q->line, fmt, ap) < 0 || q->line == NULL)
+ errx(1, "malloc");
+ va_end(ap);
+ HEIM_TAILQ_INSERT_TAIL(t, q, members);
+ return q;
+}
+
+/*
+ * Add an entry to a template, with the pointer field being a symbol name of a
+ * template (i.e., an array, which decays to a pointer as usual in C).
+ */
+static void
+add_line_pointer(struct templatehead *t,
+ const char *ptr,
+ const char *offset,
+ const char *ttfmt,
+ ...)
+{
+ struct template *q;
+ va_list ap;
+ char *tt = NULL;
+
+ va_start(ap, ttfmt);
+ if (vasprintf(&tt, ttfmt, ap) < 0 || tt == NULL)
+ errx(1, "malloc");
+ va_end(ap);
+
+ if (ptr[0] == '&')
+ q = add_line(t, "{ %s, %s, %s }", tt, offset, ptr);
+ else
+ q = add_line(t, "{ %s, %s, asn1_%s }", tt, offset, ptr);
+ q->tt = tt;
+ q->offset = strdup(offset);
+ q->ptr = strdup(ptr);
+}
+
+/*
+ * Add an entry to a template where the pointer field is a string literal.
+ */
+static void
+add_line_string(struct templatehead *t,
+ const char *str,
+ const char *offset,
+ const char *ttfmt,
+ ...)
+{
+ struct template *q;
+ va_list ap;
+ char *tt = NULL;
+
+ va_start(ap, ttfmt);
+ if (vasprintf(&tt, ttfmt, ap) < 0 || tt == NULL)
+ errx(1, "malloc");
+ va_end(ap);
+
+ q = add_line(t, "{ %s, %s, \"%s\" }", tt, offset, str);
+ q->tt = tt;
+ q->offset = strdup(offset);
+ q->ptr = strdup(str);
+}
+
+/*
+ * Add an entry to a template, with the pointer field being a reference to
+ * named object of a type other than a template or other array type.
+ */
+static void
+add_line_pointer_reference(struct templatehead *t,
+ const char *ptr,
+ const char *offset,
+ const char *ttfmt,
+ ...)
+{
+ struct template *q;
+ va_list ap;
+ char *tt = NULL;
+
+ va_start(ap, ttfmt);
+ if (vasprintf(&tt, ttfmt, ap) < 0 || tt == NULL)
+ errx(1, "malloc");
+ va_end(ap);
+
+ q = add_line(t, "{ %s, %s, (const void *)&asn1_%s }", tt, offset, ptr);
+ q->tt = tt;
+ q->offset = strdup(offset);
+ q->ptr = strdup(ptr);
+}
+
+static int
+use_extern(const Symbol *s)
+{
+ if (s->type == NULL)
+ return 1;
+ return 0;
+}
+
+static int
+is_struct(const Type *t, int isstruct)
+{
+ if (t->type == TType)
+ return 0;
+ if (t->type == TSequence || t->type == TSet || t->type == TChoice)
+ return 1;
+ if (t->type == TTag)
+ return is_struct(t->subtype, isstruct);
+
+ if (t->type >= 0 && t->type <= TVisibleString &&
+ types[t->type].type == t->type) {
+ if (types[t->type].is_struct == 0)
+ return 0;
+ return isstruct;
+ }
+ if (t->type >= 0 && t->type <= TVisibleString)
+ errx(1, "types[] is not sorted");
+ errx(1, "unknown der type: %d\n", t->type);
+ return isstruct;
+}
+
+static const Type *
+compact_tag(const Type *t)
+{
+ while (t->type == TTag)
+ t = t->subtype;
+ return t;
+}
+
+static void
+defval(struct templatehead *temp, Member *m)
+{
+ switch (m->defval->type) {
+ case booleanvalue:
+ add_line(temp, "{ A1_OP_DEFVAL|A1_DV_BOOLEAN, ~0, (void *)(uintptr_t)%u }",
+ m->defval->u.booleanvalue);
+ break;
+ case nullvalue:
+ add_line(temp, "{ A1_OP_DEFVAL|A1_DV_NULL, ~0, (void *)(uintptr_t)0 }");
+ break;
+ case integervalue: {
+ const char *dv = "A1_DV_INTEGER";
+ Type *t = m->type;
+
+ for (;;) {
+ if (t->range)
+ break;
+ if (t->type == TInteger && t->members)
+ break;
+ if (t->type == TEnumerated)
+ break;
+ if (t->subtype)
+ t = t->subtype;
+ else if (t->symbol && t->symbol->type)
+ t = t->symbol->type;
+ else
+ errx(1, "DEFAULT values for unconstrained INTEGER members not supported");
+ }
+
+ if (t->members)
+ dv = "A1_DV_INTEGER32"; /* XXX Enum size assumptions! No good! */
+ else if (t->range && t->range->min < 0 &&
+ (t->range->min < INT_MIN || t->range->max > INT_MAX))
+ dv = "A1_DV_INTEGER64";
+ else if (t->range && t->range->min < 0)
+ dv = "A1_DV_INTEGER32";
+ else if (t->range && t->range->max > UINT_MAX)
+ dv = "A1_DV_INTEGER64";
+ else
+ dv = "A1_DV_INTEGER32";
+ add_line(temp, "{ A1_OP_DEFVAL|%s, ~0, (void *)(uintptr_t)%llu }",
+ dv, (long long)m->defval->u.integervalue);
+ break;
+ }
+ case stringvalue: {
+ char *quoted;
+
+ if (rk_strasvis(&quoted, m->defval->u.stringvalue,
+ VIS_CSTYLE | VIS_NL, "\"") < 0)
+ err(1, "Could not quote a string");
+ add_line(temp, "{ A1_OP_DEFVAL|A1_DV_UTF8STRING, ~0, (void *)(uintptr_t)\"%s\" }",
+ quoted);
+ free(quoted);
+ break;
+ }
+ case objectidentifiervalue: {
+ struct objid *o;
+ size_t sz = sizeof("{ }");
+ char *s, *p;
+ int len;
+
+ for (o = m->defval->u.objectidentifiervalue; o != NULL; o = o->next) {
+ if ((len = snprintf(0, 0, " %d", o->value)) < 0)
+ err(1, "Could not format integer");
+ sz += len;
+ }
+
+ if ((p = s = malloc(sz)) == NULL)
+ err(1, "Could not allocate string");
+
+ len = snprintf(p, sz, "{");
+ sz -= len;
+ p += len;
+ for (o = m->defval->u.objectidentifiervalue; o != NULL; o = o->next) {
+ if ((len = snprintf(p, sz, " %d", o->value)) < 0 || len > sz - 1)
+ err(1, "Could not format integer");
+ sz -= len;
+ p += len;
+ }
+ if ((len = snprintf(p, sz, " }")) >= sz)
+ abort();
+ sz -= len;
+ if (sz != 0)
+ abort();
+
+ add_line(temp, "{ A1_OP_DEFVAL|A1_DV_INTEGER, ~0, (void *)(uintptr_t)\"%s\" }", s);
+ free(s);
+ break;
+ }
+ default: abort();
+ }
+}
+
+int
+objid_cmp(struct objid *oida, struct objid *oidb)
+{
+ struct objid *p;
+ size_t ai, bi, alen, blen;
+ int avals[20];
+ int bvals[20];
+ int c;
+
+ /*
+ * Our OID values are backwards here. Comparing them is hard.
+ */
+
+ for (p = oida, alen = 0;
+ p && alen < sizeof(avals)/sizeof(avals[0]);
+ p = p->next)
+ avals[alen++] = p->value;
+ for (p = oidb, blen = 0;
+ p && blen < sizeof(bvals)/sizeof(bvals[0]);
+ p = p->next)
+ bvals[blen++] = p->value;
+ if (alen >= sizeof(avals)/sizeof(avals[0]) ||
+ blen >= sizeof(bvals)/sizeof(bvals[0]))
+ err(1, "OIDs with more components than %llu not supported",
+ (unsigned long long)sizeof(avals)/sizeof(avals[0]));
+
+ for (ai = 0, bi = 0; ai < alen && bi < blen;)
+ if ((c = avals[(alen-1)-(ai++)] - bvals[(blen-1)-(bi++)]))
+ return c;
+
+ if (ai == alen && bi == blen)
+ return 0;
+ if (ai == alen)
+ return 1;
+ return -1;
+}
+
+int
+object_cmp(const void *va, const void *vb)
+{
+ const IOSObject *oa = *(const IOSObject * const *)va;
+ const IOSObject *ob = *(const IOSObject * const *)vb;
+
+ switch (oa->typeidf->value->type) {
+ case booleanvalue:
+ return oa->typeidf->value->u.booleanvalue -
+ ob->typeidf->value->u.booleanvalue;
+ case nullvalue:
+ return 0;
+ case integervalue:
+ return oa->typeidf->value->u.integervalue -
+ ob->typeidf->value->u.integervalue;
+ case stringvalue:
+ return strcmp(oa->typeidf->value->u.stringvalue,
+ ob->typeidf->value->u.stringvalue);
+ case objectidentifiervalue: {
+ return objid_cmp(oa->typeidf->value->u.objectidentifiervalue,
+ ob->typeidf->value->u.objectidentifiervalue);
+ }
+ default:
+ abort();
+ return -1;
+ }
+}
+
+void
+sort_object_set(IOSObjectSet *os, /* Object set to sort fields of */
+ Field *typeidfield, /* Field to sort by */
+ IOSObject ***objectsp, /* Output: array of objects */
+ size_t *nobjsp) /* Output: count of objects */
+{
+ IOSObject **objects;
+ IOSObject *o;
+ size_t i, nobjs = 0;
+
+ *objectsp = NULL;
+
+ HEIM_TAILQ_FOREACH(o, os->objects, objects) {
+ ObjectField *typeidobjf = NULL;
+ ObjectField *of;
+
+ HEIM_TAILQ_FOREACH(of, o->objfields, objfields) {
+ if (strcmp(of->name, typeidfield->name) == 0)
+ typeidobjf = of;
+ }
+ if (!typeidobjf) {
+ warnx("Ignoring incomplete object specification of %s "
+ "(missing type ID field)",
+ o->symbol ? o->symbol->name : "<unknown>");
+ continue;
+ }
+ o->typeidf = typeidobjf;
+ nobjs++;
+ }
+ *nobjsp = nobjs;
+
+ if (nobjs == 0)
+ return;
+
+ if ((objects = calloc(nobjs, sizeof(*objects))) == NULL)
+ err(1, "Out of memory");
+ *objectsp = objects;
+
+ i = 0;
+ HEIM_TAILQ_FOREACH(o, os->objects, objects) {
+ ObjectField *typeidobjf = NULL;
+ ObjectField *of;
+
+ HEIM_TAILQ_FOREACH(of, o->objfields, objfields) {
+ if (strcmp(of->name, typeidfield->name) == 0)
+ typeidobjf = of;
+ }
+ if (typeidobjf)
+ objects[i++] = o;
+ }
+ qsort(objects, nobjs, sizeof(*objects), object_cmp);
+}
+
+static void
+template_object_set(IOSObjectSet *os, Field *typeidfield, Field *opentypefield)
+{
+ IOSObject **objects = NULL;
+ IOSObject *o;
+ struct tlist *tl;
+ size_t nobjs, i;
+
+ if (os->symbol->emitted_template)
+ return;
+
+ sort_object_set(os, typeidfield, &objects, &nobjs);
+
+ tl = tlist_new(os->symbol->name);
+ add_line(&tl->template, "{ A1_OP_NAME, 0, \"%s\" }", os->symbol->name);
+ for (i = 0; i < nobjs; i++) {
+ ObjectField *typeidobjf = NULL, *opentypeobjf = NULL;
+ ObjectField *of;
+ char *s = NULL;
+
+ o = objects[i];
+
+ HEIM_TAILQ_FOREACH(of, o->objfields, objfields) {
+ if (strcmp(of->name, typeidfield->name) == 0)
+ typeidobjf = of;
+ else if (strcmp(of->name, opentypefield->name) == 0)
+ opentypeobjf = of;
+ }
+ if (!typeidobjf)
+ continue; /* We've warned about this one already when sorting */
+ if (!opentypeobjf) {
+ warnx("Ignoring incomplete object specification of %s "
+ "(missing open type field)",
+ o->symbol ? o->symbol->name : "<unknown>");
+ continue;
+ }
+
+ add_line(&tl->template, "{ A1_OP_NAME, 0, \"%s\" }", o->symbol->name);
+ /*
+ * Some of this logic could stand to move into sanity checks of object
+ * definitions in asn1parse.y.
+ */
+ switch (typeidobjf->value->type) {
+ case integervalue:
+ add_line(&tl->template,
+ "{ A1_OP_OPENTYPE_ID | A1_OTI_IS_INTEGER, 0, (void *)(uintptr_t)%lld }",
+ (long long)typeidobjf->value->u.integervalue);
+ break;
+ case objectidentifiervalue:
+ if (asprintf(&s, "oid_%s",
+ typeidobjf->value->s->gen_name) == -1 || !s)
+ err(1, "Out of memory");
+ add_line_pointer_reference(&tl->template, s, "0", "A1_OP_OPENTYPE_ID");
+ free(s);
+ s = NULL;
+ break;
+ default:
+ errx(1, "Only integer and OID types supported "
+ "for open type type-ID fields");
+ }
+
+ if (asprintf(&s, "sizeof(%s)",
+ opentypeobjf->type->symbol->gen_name) == -1 || !s)
+ err(1, "Out of memory");
+ add_line_pointer_reference(&tl->template,
+ opentypeobjf->type->symbol->gen_name, s,
+ "A1_OP_OPENTYPE");
+ free(s);
+ }
+ free(objects);
+
+ tlist_header(tl, "{ 0, 0, ((void *)(uintptr_t)%zu) }", nobjs);
+ tlist_print(tl);
+ tlist_add(tl);
+ os->symbol->emitted_template = 1;
+}
+
+static void
+template_open_type(struct templatehead *temp,
+ const char *basetype,
+ const Type *t,
+ size_t typeididx,
+ size_t opentypeidx,
+ Field *typeidfield,
+ Field *opentypefield,
+ Member *m,
+ int is_array_of_open_type)
+{
+ char *s = NULL;
+
+ if (typeididx >= 1<<10 || opentypeidx >= 1<<10)
+ errx(1, "SET/SEQUENCE with too many members (%s)", basetype);
+
+ if (asprintf(&s, "offsetof(%s, _ioschoice_%s)",
+ basetype, m->gen_name) == -1 || !s)
+ err(1, "Out of memory");
+
+ template_object_set(t->actual_parameter, typeidfield, opentypefield);
+ add_line_pointer(temp, t->actual_parameter->symbol->gen_name, s,
+ /*
+ * We always sort object sets for now as we can't import
+ * values yet, so they must all be known.
+ */
+ "A1_OP_OPENTYPE_OBJSET | A1_OS_IS_SORTED |%s | (%llu << 10) | %llu",
+ is_array_of_open_type ? "A1_OS_OT_IS_ARRAY" : "0",
+ (unsigned long long)opentypeidx,
+ (unsigned long long)typeididx);
+ free(s);
+}
+
+static void
+template_names(struct templatehead *temp, const char *basetype, const Type *t)
+{
+ Member *m;
+
+ add_line_string(temp, basetype, "0", "A1_OP_NAME");
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ add_line_string(temp, m->name, "0", "A1_OP_NAME");
+ }
+}
+
+static void
+template_members(struct templatehead *temp,
+ const char *basetype,
+ const char *name,
+ const Type *t,
+ int optional,
+ int defaulted,
+ int implicit,
+ int isstruct,
+ int need_offset)
+{
+ char *poffset = NULL;
+
+ if (optional && t->type != TTag && t->type != TType)
+ errx(1, "%s...%s is optional and not a (TTag or TType)", basetype, name);
+
+ poffset = partial_offset(basetype, name, need_offset, isstruct);
+
+ switch (t->type) {
+ case TType:
+ if (use_extern(t->symbol)) {
+ add_line(temp, "{ A1_OP_TYPE_EXTERN %s%s%s, %s, &asn1_extern_%s}",
+ optional ? "|A1_FLAG_OPTIONAL" : "",
+ defaulted ? "|A1_FLAG_DEFAULT" : "",
+ implicit ? "|A1_FLAG_IMPLICIT" : "",
+ poffset, t->symbol->gen_name);
+ } else {
+ add_line_pointer(temp, t->symbol->gen_name, poffset,
+ "A1_OP_TYPE %s%s%s",
+ optional ? "|A1_FLAG_OPTIONAL" : "",
+ defaulted ? "|A1_FLAG_DEFAULT" : "",
+ implicit ? "|A1_FLAG_IMPLICIT" : "");
+
+ }
+ break;
+ case TEnumerated:
+ case TInteger: {
+ char *varname = NULL;
+ char *itype = NULL;
+
+ if (t->members)
+ itype = "IMEMBER";
+ else if (t->range == NULL)
+ itype = "HEIM_INTEGER";
+ else if (t->range->min < 0 &&
+ (t->range->min < INT_MIN || t->range->max > INT_MAX))
+ itype = "INTEGER64";
+ else if (t->range->min < 0)
+ itype = "INTEGER";
+ else if (t->range->max > UINT_MAX)
+ itype = "UNSIGNED64";
+ else
+ itype = "UNSIGNED";
+
+ /*
+ * If `t->members' then we should generate a template for those
+ * members.
+ *
+ * We don't know the name of this field, and the type may not have a
+ * name. If it has no name, we should generate a name for it, and if
+ * it does have a name, use it, to name a template for its members.
+ *
+ * Then we could use that in _asn1_print() to pretty-print values of
+ * enumerations.
+ */
+ if (t->members && t->symbol) {
+ struct tlist *tl;
+ Member *m;
+ size_t nmemb = 0;
+
+ if (asprintf(&varname, "%s_enum_names", t->symbol->gen_name) == -1 ||
+ varname == NULL)
+ err(1, "Out of memory");
+
+ tl = tlist_new(varname);
+ /*
+ * XXX We're going to assume that t->members is sorted in
+ * numerically ascending order in the module source. We should
+ * really sort it here.
+ */
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ if (m->val > UINT32_MAX)
+ errx(1, "Cannot handle %s type %s with named bit %s "
+ "larger than 63",
+ t->type == TEnumerated ? "ENUMERATED" : "INTEGER",
+ name, m->gen_name);
+ add_line(&tl->template,
+ "{ A1_OP_NAME, %d, \"%s\" }", (int)m->val, m->name);
+ nmemb++;
+ }
+ tlist_header(tl, "{ 0, 0, ((void *)(uintptr_t)%zu) }", nmemb);
+ /* XXX Accidentally O(N^2)? */
+ if (!tlist_find_dup(tl)) {
+ tlist_print(tl);
+ tlist_add(tl);
+ }
+ add_line(temp, "{ A1_PARSE_T(A1T_%s), %s, asn1_%s }", itype, poffset, varname);
+ } else {
+ add_line(temp, "{ A1_PARSE_T(A1T_%s), %s, NULL }", itype, poffset);
+ }
+ break;
+ }
+ case TGeneralString:
+ add_line(temp, "{ A1_PARSE_T(A1T_GENERAL_STRING), %s, NULL }", poffset);
+ break;
+ case TTeletexString:
+ add_line(temp, "{ A1_PARSE_T(A1T_TELETEX_STRING), %s, NULL }", poffset);
+ break;
+ case TPrintableString:
+ add_line(temp, "{ A1_PARSE_T(A1T_PRINTABLE_STRING), %s, NULL }", poffset);
+ break;
+ case TOctetString:
+ add_line(temp, "{ A1_PARSE_T(A1T_OCTET_STRING), %s, NULL }", poffset);
+ break;
+ case TIA5String:
+ add_line(temp, "{ A1_PARSE_T(A1T_IA5_STRING), %s, NULL }", poffset);
+ break;
+ case TBMPString:
+ add_line(temp, "{ A1_PARSE_T(A1T_BMP_STRING), %s, NULL }", poffset);
+ break;
+ case TUniversalString:
+ add_line(temp, "{ A1_PARSE_T(A1T_UNIVERSAL_STRING), %s, NULL }", poffset);
+ break;
+ case TVisibleString:
+ add_line(temp, "{ A1_PARSE_T(A1T_VISIBLE_STRING), %s, NULL }", poffset);
+ break;
+ case TUTF8String:
+ add_line(temp, "{ A1_PARSE_T(A1T_UTF8_STRING), %s, NULL }", poffset);
+ break;
+ case TGeneralizedTime:
+ add_line(temp, "{ A1_PARSE_T(A1T_GENERALIZED_TIME), %s, NULL }", poffset);
+ break;
+ case TUTCTime:
+ add_line(temp, "{ A1_PARSE_T(A1T_UTC_TIME), %s, NULL }", poffset);
+ break;
+ case TBoolean:
+ add_line(temp, "{ A1_PARSE_T(A1T_BOOLEAN), %s, NULL }", poffset);
+ break;
+ case TOID:
+ add_line(temp, "{ A1_PARSE_T(A1T_OID), %s, NULL }", poffset);
+ break;
+ case TNull:
+ break;
+ case TBitString: {
+ struct templatehead template;
+ struct template *q;
+ Member *m;
+ size_t count = 0, i;
+ char *bname = NULL;
+ FILE *f = get_code_file();
+ static unsigned long bmember_counter = 0;
+
+ HEIM_TAILQ_INIT(&template);
+
+ if (HEIM_TAILQ_EMPTY(t->members)) {
+ add_line(temp, "{ A1_PARSE_T(A1T_HEIM_BIT_STRING), %s, NULL }", poffset);
+ break;
+ }
+
+ if (asprintf(&bname, "bmember_%s_%lu", name ? name : "", bmember_counter++) < 0 || bname == NULL)
+ errx(1, "malloc");
+ output_name(bname);
+
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ if (m->val > UINT32_MAX)
+ errx(1, "Cannot handle BIT STRING type %s with named bit %s "
+ "larger than 63", name, m->gen_name);
+ add_line(&template, "{ 0, %d, \"%s\" }", (int)m->val, m->gen_name);
+ }
+
+ HEIM_TAILQ_FOREACH(q, &template, members) {
+ count++;
+ }
+
+ fprintf(f, "static const struct asn1_template asn1_%s_%s[] = {\n", basetype, bname);
+ fprintf(f, "/* 0 */ { 0%s, sizeof(%s), ((void *)(uintptr_t)%lu) },\n",
+ rfc1510_bitstring ? "|A1_HBF_RFC1510" : "",
+ basetype, (unsigned long)count);
+ i = 1;
+ HEIM_TAILQ_FOREACH(q, &template, members) {
+ int last = (HEIM_TAILQ_LAST(&template, templatehead) == q);
+ fprintf(f, "/* %lu */ %s%s\n", (unsigned long)i++, q->line, last ? "" : ",");
+ }
+ fprintf(f, "};\n");
+
+ add_line(temp, "{ A1_OP_BMEMBER, %s, asn1_%s_%s }", poffset, basetype, bname);
+
+ free(bname);
+
+ break;
+ }
+ case TSet: {
+ Member *opentypemember = NULL;
+ Member *typeidmember = NULL;
+ Field *opentypefield = NULL;
+ Field *typeidfield = NULL;
+ Member *m;
+ struct decoration deco;
+ ssize_t more_deco = -1;
+ size_t i = 0, typeididx = 0, opentypeidx = 0;
+ int is_array_of_open_type = 0;
+
+ if (isstruct && t->actual_parameter)
+ get_open_type_defn_fields(t, &typeidmember, &opentypemember,
+ &typeidfield, &opentypefield,
+ &is_array_of_open_type);
+
+ fprintf(get_code_file(), "/* tset: members isstruct: %d */\n", isstruct);
+
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ char *newbasename = NULL;
+
+ if (m->ellipsis)
+ continue;
+
+ if (typeidmember == m) typeididx = i;
+ if (opentypemember == m) opentypeidx = i;
+
+ if (name) {
+ if (asprintf(&newbasename, "%s_%s", basetype, name) < 0)
+ errx(1, "malloc");
+ } else
+ newbasename = strdup(basetype);
+ if (newbasename == NULL)
+ errx(1, "malloc");
+
+ if (m->defval)
+ defval(temp, m);
+
+ template_members(temp, newbasename, m->gen_name, m->type, m->optional, m->defval ? 1 : 0, 0, isstruct, 1);
+
+ free(newbasename);
+ i++;
+ }
+
+ if (isstruct && t->actual_parameter)
+ template_open_type(temp, basetype, t, typeididx, opentypeidx,
+ typeidfield, opentypefield, opentypemember,
+ is_array_of_open_type);
+
+ while (decorate_type(basetype, &deco, &more_deco)) {
+ char *poffset2;
+
+ poffset2 = partial_offset(basetype, deco.field_name, 1, isstruct);
+
+ if (deco.ext) {
+ char *ptr = NULL;
+
+ /* Decorated with external C type */
+ if (asprintf(&ptr, "&asn1_extern_%s_%s",
+ basetype, deco.field_name) == -1 || ptr == NULL)
+ err(1, "out of memory");
+ add_line_pointer(temp, ptr, poffset2,
+ "A1_OP_TYPE_DECORATE_EXTERN %s",
+ deco.opt ? "|A1_FLAG_OPTIONAL" : "");
+ free(ptr);
+ } else
+ /* Decorated with a templated ASN.1 type */
+ add_line_pointer(temp, deco.field_type, poffset2,
+ "A1_OP_TYPE_DECORATE %s",
+ deco.opt ? "|A1_FLAG_OPTIONAL" : "");
+ free(poffset2);
+ free(deco.field_type);
+ }
+
+ if (isstruct)
+ template_names(temp, basetype, t);
+ break;
+ }
+ case TSequence: {
+ Member *opentypemember = NULL;
+ Member *typeidmember = NULL;
+ Field *opentypefield = NULL;
+ Field *typeidfield = NULL;
+ Member *m;
+ struct decoration deco;
+ ssize_t more_deco = -1;
+ size_t i = 0, typeididx = 0, opentypeidx = 0;
+ int is_array_of_open_type = 0;
+
+ if (isstruct && t->actual_parameter)
+ get_open_type_defn_fields(t, &typeidmember, &opentypemember,
+ &typeidfield, &opentypefield,
+ &is_array_of_open_type);
+
+ fprintf(get_code_file(), "/* tsequence: members isstruct: %d */\n", isstruct);
+
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ char *newbasename = NULL;
+
+ if (m->ellipsis)
+ continue;
+
+ if (typeidmember == m) typeididx = i;
+ if (opentypemember == m) opentypeidx = i;
+
+ if (name) {
+ if (asprintf(&newbasename, "%s_%s", basetype, name) < 0)
+ errx(1, "malloc");
+ } else
+ newbasename = strdup(basetype);
+ if (newbasename == NULL)
+ errx(1, "malloc");
+
+ if (m->defval)
+ defval(temp, m);
+
+ template_members(temp, newbasename, m->gen_name, m->type, m->optional, m->defval ? 1 : 0, 0, isstruct, 1);
+
+ free(newbasename);
+ i++;
+ }
+
+ if (isstruct && t->actual_parameter)
+ template_open_type(temp, basetype, t, typeididx, opentypeidx,
+ typeidfield, opentypefield, opentypemember,
+ is_array_of_open_type);
+
+ while (decorate_type(basetype, &deco, &more_deco)) {
+ char *poffset2;
+
+ poffset2 = partial_offset(basetype, deco.field_name, 1, isstruct);
+
+ if (deco.ext) {
+ char *ptr = NULL;
+
+ /* Decorated with external C type */
+ if (asprintf(&ptr, "&asn1_extern_%s_%s",
+ basetype, deco.field_name) == -1 || ptr == NULL)
+ err(1, "out of memory");
+ add_line_pointer(temp, ptr, poffset2,
+ "A1_OP_TYPE_DECORATE_EXTERN %s",
+ deco.opt ? "|A1_FLAG_OPTIONAL" : "");
+ free(ptr);
+ } else
+ /* Decorated with a templated ASN.1 type */
+ add_line_pointer(temp, deco.field_type, poffset2,
+ "A1_OP_TYPE_DECORATE %s",
+ deco.opt ? "|A1_FLAG_OPTIONAL" : "");
+ free(poffset2);
+ free(deco.field_type);
+ }
+
+ if (isstruct)
+ template_names(temp, basetype, t);
+ break;
+ }
+ case TTag: {
+ char *tname = NULL, *elname = NULL;
+ const char *sename, *dupname;
+ int subtype_is_struct = is_struct(t->subtype, isstruct);
+ static unsigned long tag_counter = 0;
+ int tagimplicit = 0;
+ int prim = !(t->tag.tagclass != ASN1_C_UNIV &&
+ t->tag.tagenv == TE_EXPLICIT) &&
+ is_primitive_type(t->subtype);
+
+ if (t->tag.tagenv == TE_IMPLICIT) {
+ Type *t2 = t->subtype ? t->subtype : t->symbol->type;
+
+ while (t2->type == TType && (t2->subtype || t2->symbol->type))
+ t2 = t2->subtype ? t2->subtype : t2->symbol->type;
+ if (t2->type != TChoice)
+ tagimplicit = 1;
+ }
+
+ fprintf(get_code_file(), "/* template_members: %s %s %s */\n", basetype, implicit ? "imp" : "exp", tagimplicit ? "imp" : "exp");
+
+ if (subtype_is_struct)
+ sename = basetype;
+ else
+ sename = symbol_name(basetype, t->subtype);
+
+ if (asprintf(&tname, "tag_%s_%lu", name ? name : "", tag_counter++) < 0 || tname == NULL)
+ errx(1, "malloc");
+ output_name(tname);
+
+ if (asprintf(&elname, "%s_%s", basetype, tname) < 0 || elname == NULL)
+ errx(1, "malloc");
+
+ generate_template_type(elname, &dupname, NULL, sename, name,
+ t->subtype, 0, subtype_is_struct, 0);
+
+ add_line_pointer(temp, dupname, poffset,
+ "A1_TAG_T(%s,%s,%s)%s%s%s",
+ classname(t->tag.tagclass),
+ prim ? "PRIM" : "CONS",
+ valuename(t->tag.tagclass, t->tag.tagvalue),
+ optional ? "|A1_FLAG_OPTIONAL" : "",
+ defaulted ? "|A1_FLAG_DEFAULT" : "",
+ tagimplicit ? "|A1_FLAG_IMPLICIT" : "");
+
+ free(tname);
+ free(elname);
+
+ break;
+ }
+ case TSetOf:
+ case TSequenceOf: {
+ const char *type = NULL, *tname, *dupname;
+ char *sename = NULL, *elname = NULL;
+ int subtype_is_struct = is_struct(t->subtype, 0);
+ static unsigned long seof_counter = 0;
+
+ if (name && subtype_is_struct) {
+ tname = "seofTstruct";
+ if (asprintf(&sename, "%s_%s_val", basetype, name) < 0)
+ errx(1, "malloc");
+ } else if (subtype_is_struct) {
+ tname = "seofTstruct";
+ if (asprintf(&sename, "%s_val", symbol_name(basetype, t->subtype)) < 0)
+ errx(1, "malloc");
+ } else {
+ if (name)
+ tname = name;
+ else
+ tname = "seofTstruct";
+ sename = strdup(symbol_name(basetype, t->subtype));
+ }
+ if (sename == NULL)
+ errx(1, "malloc");
+
+ if (t->type == TSetOf) type = "A1_OP_SETOF";
+ else if (t->type == TSequenceOf) type = "A1_OP_SEQOF";
+ else abort();
+
+ if (asprintf(&elname, "%s_%s_%lu", basetype, tname, seof_counter++) < 0 || elname == NULL)
+ errx(1, "malloc");
+
+ generate_template_type(elname, &dupname, NULL, sename, NULL, t->subtype,
+ 0, subtype_is_struct, need_offset);
+
+ add_line(temp, "{ %s, %s, asn1_%s }", type, poffset, dupname);
+ free(sename);
+ break;
+ }
+ case TChoice: {
+ struct decoration deco;
+ ssize_t more_deco = -1;
+ struct templatehead template;
+ struct template *q;
+ size_t count = 0, i;
+ char *tname = NULL;
+ FILE *f = get_code_file();
+ Member *m;
+ int ellipsis = 0;
+ char *e;
+ static unsigned long choice_counter = 0;
+
+ HEIM_TAILQ_INIT(&template);
+
+ if (asprintf(&tname, "asn1_choice_%s_%s%lu",
+ basetype, name ? name : "", choice_counter++) < 0 || tname == NULL)
+ errx(1, "malloc");
+
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ const char *dupname;
+ char *elname = NULL;
+ char *newbasename = NULL;
+ int subtype_is_struct;
+
+ if (m->ellipsis) {
+ ellipsis = 1;
+ continue;
+ }
+
+ subtype_is_struct = is_struct(m->type, 0);
+
+ if (asprintf(&elname, "%s_choice_%s", basetype, m->gen_name) < 0 || elname == NULL)
+ errx(1, "malloc");
+
+ if (subtype_is_struct) {
+ if (asprintf(&newbasename, "%s_%s", basetype, m->gen_name) < 0)
+ errx(1, "malloc");
+ } else
+ newbasename = strdup(basetype);
+
+ if (newbasename == NULL)
+ errx(1, "malloc");
+
+
+ generate_template_type(elname, &dupname, NULL,
+ symbol_name(newbasename, m->type),
+ NULL, m->type, 0, subtype_is_struct, 1);
+
+ add_line(&template, "{ %s, offsetof(%s%s, u.%s), asn1_%s }",
+ m->label, isstruct ? "struct " : "",
+ basetype, m->gen_name,
+ dupname);
+
+ free(elname);
+ free(newbasename);
+ }
+
+ HEIM_TAILQ_FOREACH(m, t->members, members) {
+ add_line(&template, "{ 0, 0, \"%s\" }", m->name);
+ }
+
+ e = NULL;
+ if (ellipsis) {
+ if (asprintf(&e, "offsetof(%s%s, u.asn1_ellipsis)", isstruct ? "struct " : "", basetype) < 0 || e == NULL)
+ errx(1, "malloc");
+ }
+
+ HEIM_TAILQ_FOREACH(q, &template, members) {
+ count++;
+ }
+
+ fprintf(f, "static const struct asn1_template %s[] = {\n", tname);
+ fprintf(f, "/* 0 */ { %s, offsetof(%s%s, element), ((void *)(uintptr_t)%lu) },\n",
+ e ? e : "0", isstruct ? "struct " : "", basetype, (unsigned long)count);
+ i = 1;
+ HEIM_TAILQ_FOREACH(q, &template, members) {
+ int last = (HEIM_TAILQ_LAST(&template, templatehead) == q);
+ fprintf(f, "/* %lu */ %s%s\n", (unsigned long)i++, q->line, last ? "" : ",");
+ }
+ fprintf(f, "};\n");
+
+ add_line(temp, "{ A1_OP_CHOICE, %s, %s }", poffset, tname);
+
+ while (decorate_type(basetype, &deco, &more_deco)) {
+ char *poffset2;
+
+ poffset2 = partial_offset(basetype, deco.field_name, 1, isstruct);
+
+ if (deco.ext) {
+ char *ptr = NULL;
+
+ /* Decorated with external C type */
+ if (asprintf(&ptr, "&asn1_extern_%s_%s",
+ basetype, deco.field_name) == -1 || ptr == NULL)
+ err(1, "out of memory");
+ add_line_pointer(temp, ptr, poffset2,
+ "A1_OP_TYPE_DECORATE_EXTERN %s",
+ deco.opt ? "|A1_FLAG_OPTIONAL" : "");
+ free(ptr);
+ } else
+ /* Decorated with a templated ASN.1 type */
+ add_line_pointer(temp, deco.field_type, poffset2,
+ "A1_OP_TYPE_DECORATE %s",
+ deco.opt ? "|A1_FLAG_OPTIONAL" : "");
+ free(poffset2);
+ free(deco.field_type);
+ }
+
+ free(e);
+ free(tname);
+ break;
+ }
+ default:
+ abort ();
+ }
+ if (poffset)
+ free(poffset);
+}
+
+static void
+gen_extern_stubs(FILE *f, const char *name)
+{
+ fprintf(f,
+ "static const struct asn1_type_func asn1_extern_%s = {\n"
+ "\t(asn1_type_encode)encode_%s,\n"
+ "\t(asn1_type_decode)decode_%s,\n"
+ "\t(asn1_type_length)length_%s,\n"
+ "\t(asn1_type_copy)copy_%s,\n"
+ "\t(asn1_type_release)free_%s,\n"
+ "\t(asn1_type_print)print_%s,\n"
+ "\tsizeof(%s)\n"
+ "};\n",
+ name, name, name, name,
+ name, name, name, name);
+}
+
+void
+gen_template_import(const Symbol *s)
+{
+ FILE *f = get_code_file();
+
+ if (template_flag == 0)
+ return;
+
+ gen_extern_stubs(f, s->gen_name);
+}
+
+void
+generate_template_type_forward(const char *name)
+{
+ fprintf(get_code_file(), "extern const struct asn1_template asn1_%s[];\n", name);
+}
+
+void
+generate_template_objectset_forwards(const Symbol *s)
+{
+ if (!template_flag)
+ return;
+ fprintf(get_code_file(), "extern const struct asn1_template asn1_%s[];\n",
+ s->gen_name);
+}
+
+static void
+generate_template_type(const char *varname,
+ const char **dupname,
+ const char *symname,
+ const char *basetype,
+ const char *name,
+ Type *type,
+ int optional,
+ int isstruct,
+ int need_offset)
+{
+ struct tlist *tl;
+ const char *d;
+ char *szt = NULL;
+ int have_ellipsis = 0;
+ int implicit = 0;
+ int n;
+
+ tl = tlist_new(varname);
+
+ if (type->type == TTag && type->tag.tagenv == TE_IMPLICIT) {
+ Type *t = type->subtype ? type->subtype : type->symbol->type;
+
+ while (t->type == TType && (t->subtype || t->symbol->type))
+ t = t->subtype ? t->subtype : t->symbol->type;
+ if (t->type != TChoice)
+ implicit = (type->tag.tagenv == TE_IMPLICIT);
+ }
+
+ template_members(&tl->template, basetype, name, type, optional, 0,
+ implicit, isstruct, need_offset);
+
+ /* if its a sequence or set type, check if there is a ellipsis */
+ if (type->type == TSequence || type->type == TSet) {
+ Member *m;
+ HEIM_TAILQ_FOREACH(m, type->members, members) {
+ if (m->ellipsis)
+ have_ellipsis = 1;
+ }
+ }
+
+ if (isstruct)
+ if (name)
+ n = asprintf(&szt, "struct %s_%s", basetype, name);
+ else
+ n = asprintf(&szt, "struct %s", basetype);
+ else
+ n = asprintf(&szt, "%s", basetype);
+ if (n < 0 || szt == NULL)
+ errx(1, "malloc");
+
+ if (HEIM_TAILQ_EMPTY(&tl->template) && compact_tag(type)->type != TNull)
+ errx(1, "Tag %s...%s with no content ?", basetype, name ? name : "");
+
+ fprintf(get_code_file(), "/* generate_template_type: %s */\n", tl->name);
+
+ tlist_header(tl, "{ 0%s%s, sizeof(%s), ((void *)(uintptr_t)%lu) }",
+ (symname && preserve_type(symname)) ? "|A1_HF_PRESERVE" : "",
+ have_ellipsis ? "|A1_HF_ELLIPSIS" : "", szt, tlist_count(tl));
+
+ free(szt);
+
+ /* XXX Accidentally O(N^2)? */
+ d = tlist_find_dup(tl);
+ if (d) {
+#if 0
+ if (strcmp(d, tl->name) == 0)
+ errx(1, "found dup of ourself: %s", d);
+#endif
+ *dupname = d;
+ } else {
+ *dupname = tl->name;
+ tlist_print(tl);
+ tlist_add(tl);
+ }
+}
+
+
+void
+generate_template(const Symbol *s)
+{
+ FILE *f = get_code_file();
+ const char *dupname;
+ struct decoration deco;
+ ssize_t more_deco = -1;
+
+ if (use_extern(s)) {
+ gen_extern_stubs(f, s->gen_name);
+ return;
+ }
+
+ while (decorate_type(s->gen_name, &deco, &more_deco)) {
+ if (!deco.ext)
+ continue;
+ if (deco.void_star && deco.header_name)
+ fprintf(f, "#include %s\n", deco.header_name);
+ fprintf(f,
+ "static const struct asn1_type_func asn1_extern_%s_%s = {\n"
+ "\t(asn1_type_encode)0,\n"
+ "\t(asn1_type_decode)0,\n"
+ "\t(asn1_type_length)0,\n"
+ "\t(asn1_type_copy)%s,\n"
+ "\t(asn1_type_release)%s,\n"
+ "\t(asn1_type_print)0,\n"
+ "\tsizeof(%s)\n"
+ "};\n", s->gen_name, deco.field_name,
+ deco.copy_function_name && deco.copy_function_name[0] ?
+ deco.copy_function_name : "0",
+ deco.free_function_name && deco.free_function_name[0] ?
+ deco.free_function_name : "0",
+ deco.void_star ? "void *" : deco.field_type);
+ free(deco.field_type);
+ }
+
+ generate_template_type(s->gen_name, &dupname, s->name, s->gen_name, NULL, s->type, 0, 0, 1);
+
+ fprintf(f,
+ "\n"
+ "int ASN1CALL\n"
+ "decode_%s(const unsigned char *p, size_t len, %s *data, size_t *size)\n"
+ "{\n"
+ " memset(data, 0, sizeof(*data));\n"
+ " return _asn1_decode_top(asn1_%s, 0|%s, p, len, data, size);\n"
+ "}\n"
+ "\n",
+ s->gen_name,
+ s->gen_name,
+ dupname,
+ support_ber ? "A1_PF_ALLOW_BER" : "0");
+
+ fprintf(f,
+ "\n"
+ "int ASN1CALL\n"
+ "encode_%s(unsigned char *p, size_t len, const %s *data, size_t *size)\n"
+ "{\n"
+ " return _asn1_encode%s(asn1_%s, p, len, data, size);\n"
+ "}\n"
+ "\n",
+ s->gen_name,
+ s->gen_name,
+ fuzzer_string,
+ dupname);
+
+ fprintf(f,
+ "\n"
+ "size_t ASN1CALL\n"
+ "length_%s(const %s *data)\n"
+ "{\n"
+ " return _asn1_length%s(asn1_%s, data);\n"
+ "}\n"
+ "\n",
+ s->gen_name,
+ s->gen_name,
+ fuzzer_string,
+ dupname);
+
+
+ fprintf(f,
+ "\n"
+ "void ASN1CALL\n"
+ "free_%s(%s *data)\n"
+ "{\n"
+ " _asn1_free_top(asn1_%s, data);\n"
+ "}\n"
+ "\n",
+ s->gen_name,
+ s->gen_name,
+ dupname);
+
+ fprintf(f,
+ "\n"
+ "int ASN1CALL\n"
+ "copy_%s(const %s *from, %s *to)\n"
+ "{\n"
+ " return _asn1_copy_top(asn1_%s, from, to);\n"
+ "}\n"
+ "\n",
+ s->gen_name,
+ s->gen_name,
+ s->gen_name,
+ dupname);
+
+ fprintf(f,
+ "\n"
+ "char * ASN1CALL\n"
+ "print_%s(const %s *data, int flags)\n"
+ "{\n"
+ " return _asn1_print_top(asn1_%s, flags, data);\n"
+ "}\n"
+ "\n",
+ s->gen_name,
+ s->gen_name,
+ dupname);
+}
diff --git a/third_party/heimdal/lib/asn1/hash.c b/third_party/heimdal/lib/asn1/hash.c
new file mode 100644
index 0000000..73b6cf9
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/hash.c
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * Hash table functions
+ */
+
+#include "gen_locl.h"
+
+RCSID("$Id$");
+
+static Hashentry *_search(Hashtab * htab, /* The hash table */
+ void *ptr); /* And key */
+
+Hashtab *
+hashtabnew(int sz,
+ int (*cmp) (void *, void *),
+ unsigned (*hash) (void *))
+{
+ Hashtab *htab;
+ int i;
+
+ assert(sz > 0);
+
+ htab = (Hashtab *) malloc(sizeof(Hashtab) + (sz - 1) * sizeof(Hashentry *));
+ if (htab == NULL)
+ return NULL;
+
+ for (i = 0; i < sz; ++i)
+ htab->tab[i] = NULL;
+
+ htab->cmp = cmp;
+ htab->hash = hash;
+ htab->sz = sz;
+ return htab;
+}
+
+/* Intern search function */
+
+static Hashentry *
+_search(Hashtab * htab, void *ptr)
+{
+ Hashentry *hptr;
+
+ assert(htab && ptr);
+
+ for (hptr = htab->tab[(*htab->hash) (ptr) % htab->sz];
+ hptr;
+ hptr = hptr->next)
+ if ((*htab->cmp) (ptr, hptr->ptr) == 0)
+ break;
+ return hptr;
+}
+
+/* Search for element in hash table */
+
+void *
+hashtabsearch(Hashtab * htab, void *ptr)
+{
+ Hashentry *tmp;
+
+ tmp = _search(htab, ptr);
+ return tmp ? tmp->ptr : tmp;
+}
+
+/* add element to hash table */
+/* if already there, set new value */
+/* !NULL if succesful */
+
+void *
+hashtabadd(Hashtab * htab, void *ptr)
+{
+ Hashentry *h = _search(htab, ptr);
+ Hashentry **tabptr;
+
+ assert(htab && ptr);
+
+ if (h)
+ free((void *) h->ptr);
+ else {
+ h = (Hashentry *) malloc(sizeof(Hashentry));
+ if (h == NULL) {
+ return NULL;
+ }
+ tabptr = &htab->tab[(*htab->hash) (ptr) % htab->sz];
+ h->next = *tabptr;
+ *tabptr = h;
+ h->prev = tabptr;
+ if (h->next)
+ h->next->prev = &h->next;
+ }
+ h->ptr = ptr;
+ return h;
+}
+
+/* delete element with key key. Iff freep, free Hashentry->ptr */
+
+int
+_hashtabdel(Hashtab * htab, void *ptr, int freep)
+{
+ Hashentry *h;
+
+ assert(htab && ptr);
+
+ h = _search(htab, ptr);
+ if (h) {
+ if (freep)
+ free(h->ptr);
+ if ((*(h->prev) = h->next))
+ h->next->prev = h->prev;
+ free(h);
+ return 0;
+ } else
+ return -1;
+}
+
+/* Do something for each element */
+
+void
+hashtabforeach(Hashtab * htab, int (*func) (void *ptr, void *arg),
+ void *arg)
+{
+ Hashentry **h, *g;
+
+ assert(htab);
+
+ for (h = htab->tab; h < &htab->tab[htab->sz]; ++h)
+ for (g = *h; g; g = g->next)
+ if ((*func) (g->ptr, arg))
+ return;
+}
+
+/* standard hash-functions for strings */
+
+unsigned
+hashadd(const char *s)
+{ /* Standard hash function */
+ unsigned i;
+
+ assert(s);
+
+ for (i = 0; *s; ++s)
+ i += *s;
+ return i;
+}
+
+unsigned
+hashcaseadd(const char *s)
+{ /* Standard hash function */
+ unsigned i;
+
+ assert(s);
+
+ for (i = 0; *s; ++s)
+ i += toupper((unsigned char)*s);
+ return i;
+}
+
+#define TWELVE (sizeof(unsigned))
+#define SEVENTYFIVE (6*sizeof(unsigned))
+#define HIGH_BITS (~((unsigned)(~0) >> TWELVE))
+
+unsigned
+hashjpw(const char *ss)
+{ /* another hash function */
+ unsigned h = 0;
+ unsigned g;
+ const unsigned char *s = (const unsigned char *)ss;
+
+ for (; *s; ++s) {
+ h = (h << TWELVE) + *s;
+ if ((g = h & HIGH_BITS))
+ h = (h ^ (g >> SEVENTYFIVE)) & ~HIGH_BITS;
+ }
+ return h;
+}
diff --git a/third_party/heimdal/lib/asn1/hash.h b/third_party/heimdal/lib/asn1/hash.h
new file mode 100644
index 0000000..f37bdbb
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/hash.h
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * hash.h. Header file for hash table functions
+ */
+
+/* $Id$ */
+
+struct hashentry { /* Entry in bucket */
+ struct hashentry **prev;
+ struct hashentry *next;
+ void *ptr;
+};
+
+typedef struct hashentry Hashentry;
+
+struct hashtab { /* Hash table */
+ int (*cmp)(void *, void *); /* Compare function */
+ unsigned (*hash)(void *); /* hash function */
+ int sz; /* Size */
+ Hashentry *tab[1]; /* The table */
+};
+
+typedef struct hashtab Hashtab;
+
+/* prototypes */
+
+Hashtab *hashtabnew(int sz,
+ int (*cmp)(void *, void *),
+ unsigned (*hash)(void *)); /* Make new hash table */
+
+void *hashtabsearch(Hashtab *htab, /* The hash table */
+ void *ptr); /* The key */
+
+
+void *hashtabadd(Hashtab *htab, /* The hash table */
+ void *ptr); /* The element */
+
+int _hashtabdel(Hashtab *htab, /* The table */
+ void *ptr, /* Key */
+ int freep); /* Free data part? */
+
+void hashtabforeach(Hashtab *htab,
+ int (*func)(void *ptr, void *arg),
+ void *arg);
+
+unsigned hashadd(const char *s); /* Standard hash function */
+unsigned hashcaseadd(const char *s); /* Standard hash function */
+unsigned hashjpw(const char *s); /* another hash function */
+
+/* macros */
+
+ /* Don't free space */
+#define hashtabdel(htab,key) _hashtabdel(htab,key,FALSE)
+
+#define hashtabfree(htab,key) _hashtabdel(htab,key,TRUE) /* Do! */
diff --git a/third_party/heimdal/lib/asn1/heim_asn1.h b/third_party/heimdal/lib/asn1/heim_asn1.h
new file mode 100644
index 0000000..072ff15
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/heim_asn1.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2003-2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef __HEIM_ANY_H__
+#define __HEIM_ANY_H__ 1
+
+int ASN1CALL encode_heim_any(unsigned char *, size_t, const heim_any *, size_t *);
+int ASN1CALL decode_heim_any(const unsigned char *, size_t, heim_any *, size_t *);
+void ASN1CALL free_heim_any(heim_any *);
+char *ASN1CALL print_heim_any(const heim_any *, int);
+size_t ASN1CALL length_heim_any(const heim_any *);
+int ASN1CALL copy_heim_any(const heim_any *, heim_any *);
+
+int ASN1CALL encode_heim_any_set(unsigned char *, size_t,
+ const heim_any_set *, size_t *);
+int ASN1CALL decode_heim_any_set(const unsigned char *, size_t,
+ heim_any_set *,size_t *);
+void ASN1CALL free_heim_any_set(heim_any_set *);
+char *ASN1CALL print_heim_any_set(const heim_any_set *, int);
+size_t ASN1CALL length_heim_any_set(const heim_any_set *);
+int ASN1CALL copy_heim_any_set(const heim_any_set *, heim_any_set *);
+int ASN1CALL heim_any_cmp(const heim_any_set *, const heim_any_set *);
+
+int ASN1CALL encode_HEIM_ANY(unsigned char *, size_t, const heim_any *, size_t *);
+int ASN1CALL decode_HEIM_ANY(const unsigned char *, size_t, heim_any *, size_t *);
+void ASN1CALL free_HEIM_ANY(heim_any *);
+char *ASN1CALL print_HEIM_ANY(const heim_any *, int);
+size_t ASN1CALL length_HEIM_ANY(const heim_any *);
+int ASN1CALL copy_HEIM_ANY(const heim_any *, heim_any *);
+
+int ASN1CALL encode_HEIM_ANY_SET(unsigned char *, size_t,
+ const heim_any_set *, size_t *);
+int ASN1CALL decode_HEIM_ANY_SET(const unsigned char *, size_t,
+ heim_any_set *,size_t *);
+void ASN1CALL free_HEIM_ANY_SET(heim_any_set *);
+char *ASN1CALL print_HEIM_ANY_SET(const heim_any_set *, int);
+size_t ASN1CALL length_HEIM_ANY_SET(const heim_any_set *);
+int ASN1CALL copy_HEIM_ANY_SET(const heim_any_set *, heim_any_set *);
+int ASN1CALL heim_any_cmp(const heim_any_set *, const heim_any_set *);
+
+#endif /* __HEIM_ANY_H__ */
diff --git a/third_party/heimdal/lib/asn1/krb5.asn1 b/third_party/heimdal/lib/asn1/krb5.asn1
new file mode 100644
index 0000000..00a0acb
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/krb5.asn1
@@ -0,0 +1,1052 @@
+-- $Id$
+
+KERBEROS5 DEFINITIONS ::=
+BEGIN
+EXPORTS
+ AD-AND-OR,
+ AD-IF-RELEVANT,
+ AD-KDCIssued,
+ AD-LoginAlias,
+ AP-REP,
+ AP-REQ,
+ AS-REP,
+ AS-REQ,
+ AUTHDATA-TYPE,
+ Authenticator,
+ AuthorizationData,
+ AuthorizationDataElement,
+ CKSUMTYPE,
+ ChangePasswdDataMS,
+ Checksum,
+ CompositePrincipal,
+ ENCTYPE,
+ ETYPE-INFO,
+ ETYPE-INFO-ENTRY,
+ ETYPE-INFO2,
+ ETYPE-INFO2-ENTRY,
+ EncAPRepPart,
+ EncASRepPart,
+ EncKDCRepPart,
+ EncKrbCredPart,
+ EncKrbPrivPart,
+ EncTGSRepPart,
+ EncTicketPart,
+ EncryptedData,
+ EncryptionKey,
+ EtypeList,
+ HostAddress,
+ HostAddresses,
+ KDC-REQ-BODY,
+ KDCOptions,
+ KDC-REP,
+ KRB-CRED,
+ KRB-ERROR,
+ KRB-PRIV,
+ KRB-SAFE,
+ KRB-SAFE-BODY,
+ KerberosString,
+ KerberosTime,
+ KrbCredInfo,
+ LR-TYPE,
+ LastReq,
+ METHOD-DATA,
+ NAME-TYPE,
+ PA-ClientCanonicalized,
+ PA-ClientCanonicalizedNames,
+ PA-DATA,
+ PA-ENC-TS-ENC,
+ PA-KERB-KEY-LIST-REP,
+ PA-KERB-KEY-LIST-REQ,
+ PA-PAC-OPTIONS,
+ PA-PAC-REQUEST,
+ PA-S4U2Self,
+ PA-S4U-X509-USER,
+ PA-SERVER-REFERRAL-DATA,
+ PA-ServerReferralData,
+ PA-SvrReferralData,
+ PADATA-TYPE,
+ PA-FX-FAST-REQUEST,
+ PA-FX-FAST-REPLY,
+ Principal,
+ PrincipalName,
+ Principals,
+ Realm,
+ TGS-REP,
+ TGS-REQ,
+ Ticket,
+ TicketFlags,
+ TransitedEncoding,
+ TypedData,
+ KrbFastResponse,
+ KrbFastFinished,
+ KrbFastReq,
+ KrbFastArmor,
+ KrbFastArmoredReq,
+ KDCFastState,
+ KDCFastCookie,
+ KDC-PROXY-MESSAGE,
+ KERB-AD-RESTRICTION-ENTRY,
+ KERB-TIMES,
+ KERB-CRED,
+ KERB-TGS-REQ-IN,
+ KERB-TGS-REQ-OUT,
+ KERB-ARMOR-SERVICE-REPLY
+ ;
+
+NAME-TYPE ::= INTEGER {
+ KRB5_NT_UNKNOWN(0), -- Name type not known
+ KRB5_NT_PRINCIPAL(1), -- Just the name of the principal as in
+ KRB5_NT_SRV_INST(2), -- Service and other unique instance (krbtgt)
+ KRB5_NT_SRV_HST(3), -- Service with host name as instance
+ KRB5_NT_SRV_XHST(4), -- Service with host as remaining components
+ KRB5_NT_UID(5), -- Unique ID
+ KRB5_NT_X500_PRINCIPAL(6), -- PKINIT
+ KRB5_NT_SMTP_NAME(7), -- Name in form of SMTP email name
+ KRB5_NT_ENTERPRISE_PRINCIPAL(10), -- Windows 2000 UPN
+ KRB5_NT_WELLKNOWN(11), -- Wellknown
+ KRB5_NT_SRV_HST_DOMAIN(12), -- Domain based service with host name as instance (RFC5179)
+ KRB5_NT_ENT_PRINCIPAL_AND_ID(-130), -- Windows 2000 UPN and SID
+ KRB5_NT_MS_PRINCIPAL(-128), -- NT 4 style name
+ KRB5_NT_MS_PRINCIPAL_AND_ID(-129), -- NT style name and SID
+ KRB5_NT_NTLM(-1200), -- NTLM name, realm is domain
+ KRB5_NT_X509_GENERAL_NAME(-1201), -- x509 general name (base64 encoded)
+ KRB5_NT_GSS_HOSTBASED_SERVICE(-1202), -- not used; remove
+ KRB5_NT_CACHE_UUID(-1203), -- name is actually a uuid pointing to ccache, use client name in cache
+ KRB5_NT_SRV_HST_NEEDS_CANON (-195894762) -- Internal: indicates that name canonicalization is needed
+}
+
+-- message types
+
+MESSAGE-TYPE ::= INTEGER {
+ krb-as-req(10), -- Request for initial authentication
+ krb-as-rep(11), -- Response to KRB_AS_REQ request
+ krb-tgs-req(12), -- Request for authentication based on TGT
+ krb-tgs-rep(13), -- Response to KRB_TGS_REQ request
+ krb-ap-req(14), -- application request to server
+ krb-ap-rep(15), -- Response to KRB_AP_REQ_MUTUAL
+ krb-safe(20), -- Safe (checksummed) application message
+ krb-priv(21), -- Private (encrypted) application message
+ krb-cred(22), -- Private (encrypted) message to forward credentials
+ krb-error(30) -- Error response
+}
+
+
+-- pa-data types
+
+PADATA-TYPE ::= INTEGER {
+ KRB5-PADATA-NONE(0),
+ KRB5-PADATA-TGS-REQ(1),
+ KRB5-PADATA-AP-REQ(1),
+ KRB5-PADATA-ENC-TIMESTAMP(2),
+ KRB5-PADATA-PW-SALT(3),
+ KRB5-PADATA-ENC-UNIX-TIME(5),
+ KRB5-PADATA-SANDIA-SECUREID(6),
+ KRB5-PADATA-SESAME(7),
+ KRB5-PADATA-OSF-DCE(8),
+ KRB5-PADATA-CYBERSAFE-SECUREID(9),
+ KRB5-PADATA-AFS3-SALT(10),
+ KRB5-PADATA-ETYPE-INFO(11),
+ KRB5-PADATA-SAM-CHALLENGE(12), -- (sam/otp)
+ KRB5-PADATA-SAM-RESPONSE(13), -- (sam/otp)
+ KRB5-PADATA-PK-AS-REQ-19(14), -- (PKINIT-19)
+ KRB5-PADATA-PK-AS-REP-19(15), -- (PKINIT-19)
+ KRB5-PADATA-PK-AS-REQ-WIN(15), -- (PKINIT - old number)
+ KRB5-PADATA-PK-AS-REQ(16), -- (PKINIT-25)
+ KRB5-PADATA-PK-AS-REP(17), -- (PKINIT-25)
+ KRB5-PADATA-PA-PK-OCSP-RESPONSE(18),
+ KRB5-PADATA-ETYPE-INFO2(19),
+ KRB5-PADATA-USE-SPECIFIED-KVNO(20),
+ KRB5-PADATA-SVR-REFERRAL-INFO(20), --- old ms referral number
+ KRB5-PADATA-SAM-REDIRECT(21), -- (sam/otp)
+ KRB5-PADATA-GET-FROM-TYPED-DATA(22),
+ KRB5-PADATA-SAM-ETYPE-INFO(23),
+ KRB5-PADATA-SERVER-REFERRAL(25),
+ KRB5-PADATA-ALT-PRINC(24), -- (crawdad@fnal.gov)
+ KRB5-PADATA-SAM-CHALLENGE2(30), -- (kenh@pobox.com)
+ KRB5-PADATA-SAM-RESPONSE2(31), -- (kenh@pobox.com)
+ KRB5-PA-EXTRA-TGT(41), -- Reserved extra TGT
+ KRB5-PADATA-FX-FAST-ARMOR(71), -- fast armor
+ KRB5-PADATA-TD-KRB-PRINCIPAL(102), -- PrincipalName
+ KRB5-PADATA-PK-TD-TRUSTED-CERTIFIERS(104), -- PKINIT
+ KRB5-PADATA-PK-TD-CERTIFICATE-INDEX(105), -- PKINIT
+ KRB5-PADATA-TD-APP-DEFINED-ERROR(106), -- application specific
+ KRB5-PADATA-TD-REQ-NONCE(107), -- INTEGER
+ KRB5-PADATA-TD-REQ-SEQ(108), -- INTEGER
+ KRB5-PADATA-PA-PAC-REQUEST(128), -- jbrezak@exchange.microsoft.com
+ KRB5-PADATA-FOR-USER(129), -- MS-KILE
+ KRB5-PADATA-FOR-X509-USER(130), -- MS-KILE
+ KRB5-PADATA-FOR-CHECK-DUPS(131), -- MS-KILE
+ KRB5-PADATA-AS-CHECKSUM(132), -- MS-KILE
+ KRB5-PADATA-PK-AS-09-BINDING(132), -- client send this to
+ -- tell KDC that is supports
+ -- the asCheckSum in the
+ -- PK-AS-REP
+ KRB5-PADATA-FX-COOKIE(133), -- krb-wg-preauth-framework
+ KRB5-PADATA-AUTHENTICATION-SET(134), -- krb-wg-preauth-framework
+ KRB5-PADATA-AUTH-SET-SELECTED(135), -- krb-wg-preauth-framework
+ KRB5-PADATA-FX-FAST(136), -- krb-wg-preauth-framework
+ KRB5-PADATA-FX-ERROR(137), -- krb-wg-preauth-framework
+ KRB5-PADATA-ENCRYPTED-CHALLENGE(138), -- krb-wg-preauth-framework
+ KRB5-PADATA-OTP-CHALLENGE(141), -- (gareth.richards@rsa.com)
+ KRB5-PADATA-OTP-REQUEST(142), -- (gareth.richards@rsa.com)
+ KBB5-PADATA-OTP-CONFIRM(143), -- (gareth.richards@rsa.com)
+ KRB5-PADATA-OTP-PIN-CHANGE(144), -- (gareth.richards@rsa.com)
+ KRB5-PADATA-EPAK-AS-REQ(145),
+ KRB5-PADATA-EPAK-AS-REP(146),
+ KRB5-PADATA-PKINIT-KX(147), -- krb-wg-anon
+ KRB5-PADATA-PKU2U-NAME(148), -- zhu-pku2u
+ KRB5-PADATA-REQ-ENC-PA-REP(149), --
+ KER5-PADATA-KERB-KEY-LIST-REQ(161), -- MS-KILE
+ KER5-PADATA-KERB-PAKEY-LIST-REP(162), -- MS-KILE
+ KRB5-PADATA-SUPPORTED-ETYPES(165), -- MS-KILE
+ KRB5-PADATA-PAC-OPTIONS(167), -- MS-KILE
+ KRB5-PADATA-GSS(655) -- krb-wg-gss-preauth
+
+}
+
+AUTHDATA-TYPE ::= INTEGER {
+ KRB5-AUTHDATA-IF-RELEVANT(1),
+ KRB5-AUTHDATA-INTENDED-FOR_SERVER(2),
+ KRB5-AUTHDATA-INTENDED-FOR-APPLICATION-CLASS(3),
+ KRB5-AUTHDATA-KDC-ISSUED(4),
+ KRB5-AUTHDATA-AND-OR(5),
+ KRB5-AUTHDATA-MANDATORY-TICKET-EXTENSIONS(6),
+ KRB5-AUTHDATA-IN-TICKET-EXTENSIONS(7),
+ KRB5-AUTHDATA-MANDATORY-FOR-KDC(8),
+ KRB5-AUTHDATA-INITIAL-VERIFIED-CAS(9),
+ KRB5-AUTHDATA-OSF-DCE(64),
+ KRB5-AUTHDATA-SESAME(65),
+ KRB5-AUTHDATA-OSF-DCE-PKI-CERTID(66),
+ KRB5-AUTHDATA-AUTHENTICATION-STRENGTH(70),
+ KRB5-AUTHDATA-FX-FAST-ARMOR(71),
+ KRB5-AUTHDATA-FX-FAST-USED(72),
+ KRB5-AUTHDATA-WIN2K-PAC(128),
+ KRB5-AUTHDATA-GSS-API-ETYPE-NEGOTIATION(129), -- Authenticator only
+ KRB5-AUTHDATA-SIGNTICKET-OLDER(-17),
+ KRB5-AUTHDATA-SIGNTICKET-OLD(142),
+ KRB5-AUTHDATA-SIGNTICKET(512),
+ KRB5-AUTHDATA-SYNTHETIC-PRINC-USED(513), -- principal was synthetised
+ KRB5-AUTHDATA-KERB-LOCAL(141), -- MS-KILE
+ KRB5-AUTHDATA-TOKEN-RESTRICTIONS(142), -- MS-KILE
+ KRB5-AUTHDATA-AP-OPTIONS(143), -- MS-KILE
+ KRB5-AUTHDATA-TARGET-PRINCIPAL(144), -- MS-KILE
+ -- N.B. these assignments have not been confirmed yet.
+ --
+ -- DO NOT USE in production yet!
+ KRB5-AUTHDATA-ON-BEHALF-OF(580), -- UTF8String princ name
+ KRB5-AUTHDATA-BEARER-TOKEN-JWT(581), -- JWT token
+ KRB5-AUTHDATA-BEARER-TOKEN-SAML(582), -- SAML token
+ KRB5-AUTHDATA-BEARER-TOKEN-OIDC(583), -- OIDC token
+ KRB5-AUTHDATA-CSR-AUTHORIZED(584), -- Proxy has authorized client
+ -- to requested exts in CSR
+ KRB5-AUTHDATA-GSS-COMPOSITE-NAME(655) -- gss_export_name_composite
+}
+
+-- checksumtypes
+
+CKSUMTYPE ::= INTEGER {
+ CKSUMTYPE_NONE(0),
+ CKSUMTYPE_CRC32(1),
+ CKSUMTYPE_RSA_MD4(2),
+ CKSUMTYPE_RSA_MD4_DES(3),
+ CKSUMTYPE_DES_MAC(4),
+ CKSUMTYPE_DES_MAC_K(5),
+ CKSUMTYPE_RSA_MD4_DES_K(6),
+ CKSUMTYPE_RSA_MD5(7),
+ CKSUMTYPE_RSA_MD5_DES(8),
+ CKSUMTYPE_RSA_MD5_DES3(9),
+ CKSUMTYPE_SHA1_OTHER(10),
+ CKSUMTYPE_HMAC_SHA1_DES3(12),
+ CKSUMTYPE_SHA1(14),
+ CKSUMTYPE_HMAC_SHA1_96_AES_128(15),
+ CKSUMTYPE_HMAC_SHA1_96_AES_256(16),
+ CKSUMTYPE_HMAC_SHA256_128_AES128(19),
+ CKSUMTYPE_HMAC_SHA384_192_AES256(20),
+ CKSUMTYPE_GSSAPI(0x8003),
+ CKSUMTYPE_HMAC_MD5(-138), -- unofficial microsoft number
+ CKSUMTYPE_HMAC_MD5_ENC(-1138), -- even more unofficial
+ CKSUMTYPE_SHA256(-21),
+ CKSUMTYPE_SHA384(-22),
+ CKSUMTYPE_SHA512(-23)
+}
+
+--enctypes
+ENCTYPE ::= INTEGER {
+ KRB5_ENCTYPE_NULL(0),
+ KRB5_ENCTYPE_DES_CBC_CRC(1),
+ KRB5_ENCTYPE_DES_CBC_MD4(2),
+ KRB5_ENCTYPE_DES_CBC_MD5(3),
+ KRB5_ENCTYPE_DES3_CBC_MD5(5),
+ KRB5_ENCTYPE_OLD_DES3_CBC_SHA1(7),
+ KRB5_ENCTYPE_SIGN_DSA_GENERATE(8),
+ KRB5_ENCTYPE_ENCRYPT_RSA_PRIV(9),
+ KRB5_ENCTYPE_ENCRYPT_RSA_PUB(10),
+ KRB5_ENCTYPE_DES3_CBC_SHA1(16), -- with key derivation
+ KRB5_ENCTYPE_AES128_CTS_HMAC_SHA1_96(17),
+ KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96(18),
+ KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128(19),
+ KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192(20),
+ KRB5_ENCTYPE_ARCFOUR_HMAC_MD5(23),
+ KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56(24),
+ KRB5_ENCTYPE_ENCTYPE_PK_CROSS(48),
+-- some "old" windows types
+ KRB5_ENCTYPE_ARCFOUR_MD4(-128),
+ KRB5_ENCTYPE_ARCFOUR_HMAC_OLD(-133),
+ KRB5_ENCTYPE_ARCFOUR_HMAC_OLD_EXP(-135),
+-- these are for Heimdal internal use
+ KRB5_ENCTYPE_DES_CBC_NONE(-0x1000),
+ KRB5_ENCTYPE_DES3_CBC_NONE(-0x1001),
+ KRB5_ENCTYPE_DES_CFB64_NONE(-0x1002),
+ KRB5_ENCTYPE_DES_PCBC_NONE(-0x1003),
+ KRB5_ENCTYPE_DIGEST_MD5_NONE(-0x1004), -- private use, lukeh@padl.com
+ KRB5_ENCTYPE_CRAM_MD5_NONE(-0x1005) -- private use, lukeh@padl.com
+}
+
+
+
+
+-- this is sugar to make something ASN1 does not have: unsigned
+
+Krb5UInt32 ::= INTEGER (0..4294967295)
+Krb5Int32 ::= INTEGER (-2147483648..2147483647)
+
+KerberosString ::= GeneralString
+
+Realm ::= GeneralString
+PrincipalName ::= SEQUENCE {
+ name-type[0] NAME-TYPE,
+ name-string[1] SEQUENCE OF GeneralString
+}
+
+HostAddress ::= SEQUENCE {
+ addr-type[0] Krb5Int32,
+ address[1] OCTET STRING
+}
+
+-- This is from RFC1510.
+--
+-- HostAddresses ::= SEQUENCE OF SEQUENCE {
+-- addr-type[0] Krb5Int32,
+-- address[1] OCTET STRING
+-- }
+
+-- This seems much better.
+HostAddresses ::= SEQUENCE OF HostAddress
+
+
+KerberosTime ::= GeneralizedTime -- Specifying UTC time zone (Z)
+
+AuthorizationDataElement ::= SEQUENCE {
+ ad-type[0] Krb5Int32,
+ ad-data[1] OCTET STRING
+}
+
+AuthorizationData ::= SEQUENCE OF AuthorizationDataElement
+
+APOptions ::= BIT STRING {
+ reserved(0),
+ use-session-key(1),
+ mutual-required(2)
+}
+
+TicketFlags ::= BIT STRING {
+ reserved(0),
+ forwardable(1),
+ forwarded(2),
+ proxiable(3),
+ proxy(4),
+ may-postdate(5),
+ postdated(6),
+ invalid(7),
+ renewable(8),
+ initial(9),
+ pre-authent(10),
+ hw-authent(11),
+ transited-policy-checked(12),
+ ok-as-delegate(13),
+ enc-pa-rep(15),
+ anonymous(16)
+}
+
+KDCOptions ::= BIT STRING {
+ reserved(0),
+ forwardable(1),
+ forwarded(2),
+ proxiable(3),
+ proxy(4),
+ allow-postdate(5),
+ postdated(6),
+ renewable(8),
+ cname-in-addl-tkt(14), -- ms extension
+ canonicalize(15),
+ request-anonymous(16),
+ disable-transited-check(26),
+ renewable-ok(27),
+ enc-tkt-in-skey(28),
+ renew(30),
+ validate(31)
+}
+
+LR-TYPE ::= INTEGER {
+ LR_NONE(0), -- no information
+ LR_INITIAL_TGT(1), -- last initial TGT request
+ LR_INITIAL(2), -- last initial request
+ LR_ISSUE_USE_TGT(3), -- time of newest TGT used
+ LR_RENEWAL(4), -- time of last renewal
+ LR_REQUEST(5), -- time of last request (of any type)
+ LR_PW_EXPTIME(6), -- expiration time of password
+ LR_ACCT_EXPTIME(7) -- expiration time of account
+}
+
+LastReq ::= SEQUENCE OF SEQUENCE {
+ lr-type[0] LR-TYPE,
+ lr-value[1] KerberosTime
+}
+
+
+EncryptedData ::= SEQUENCE {
+ etype[0] ENCTYPE, -- EncryptionType
+ kvno[1] Krb5Int32 OPTIONAL,
+ cipher[2] OCTET STRING -- ciphertext
+}
+
+EncryptionKey ::= SEQUENCE {
+ keytype[0] Krb5Int32,
+ keyvalue[1] OCTET STRING
+}
+
+-- encoded Transited field
+TransitedEncoding ::= SEQUENCE {
+ tr-type[0] Krb5Int32, -- must be registered
+ contents[1] OCTET STRING
+}
+
+Ticket ::= [APPLICATION 1] SEQUENCE {
+ tkt-vno[0] Krb5Int32,
+ realm[1] Realm,
+ sname[2] PrincipalName,
+ enc-part[3] EncryptedData
+}
+-- Encrypted part of ticket
+EncTicketPart ::= [APPLICATION 3] SEQUENCE {
+ flags[0] TicketFlags,
+ key[1] EncryptionKey,
+ crealm[2] Realm,
+ cname[3] PrincipalName,
+ transited[4] TransitedEncoding,
+ authtime[5] KerberosTime,
+ starttime[6] KerberosTime OPTIONAL,
+ endtime[7] KerberosTime,
+ renew-till[8] KerberosTime OPTIONAL,
+ caddr[9] HostAddresses OPTIONAL,
+ authorization-data[10] AuthorizationData OPTIONAL
+}
+
+Checksum ::= SEQUENCE {
+ cksumtype[0] CKSUMTYPE,
+ checksum[1] OCTET STRING
+}
+
+-- For GSS name attributes [RFC6680] we'll decorate Principal (which is not an
+-- RFC4120 type, but which we use a) in HDB, b) in the API as that which
+-- krb5_principal points to) with PrincipalNameAttrs.
+--
+-- Attributes have three possible sources in Heimdal Kerberos at this time:
+--
+-- - the EncKDCRepPart (for the client's attributes on the client side)
+-- - the EncTicketPart (for the client's attributes on the server side)
+-- - the Authenticator's AuthorizationData (if any; server-side)
+--
+-- In principle there can be more:
+--
+-- - locally-set (asserted) attributes
+-- - locally-looked-up attributes (e.g., in LDAP)
+-- - locally-transformed attributes (e.g., local groups, filtered SIDs from a
+-- PAC, etc.)
+--
+-- We could also cache "cooked" attributes as reported by the RFC6680 API given
+-- the sources we have.
+--
+-- For now we'll only support authenticated attributes where those come from
+-- the KDC, and attributes asserted in Authenticator authz-data.
+PrincipalNameAttrSrc ::= CHOICE {
+ enc-kdc-rep-part [0] EncKDCRepPart, -- minus session key
+ enc-ticket-part [1] EncTicketPart -- minus session key
+}
+PrincipalNameAttrs ::= SEQUENCE {
+ -- True if this name was authenticated via an AP-REQ or a KDC-REP
+ authenticated [0] BOOLEAN,
+ -- These are compiled from the Ticket, KDC-REP, and/or Authenticator
+ source [1] PrincipalNameAttrSrc OPTIONAL,
+ authenticator-ad [2] AuthorizationData OPTIONAL,
+ -- For the server on the client side we should keep track of the
+ -- transit path taken to reach it (if absent -> unknown).
+ --
+ -- We don't learn much more about the server from the KDC.
+ peer-realm [3] Realm OPTIONAL,
+ transited [4] TransitedEncoding OPTIONAL,
+ -- True if the PAC was verified
+ pac-verified [5] BOOLEAN,
+ -- True if any AD-KDC-ISSUEDs in the Ticket were validated
+ kdc-issued-verified [6] BOOLEAN,
+ -- TODO: Add requested attributes, for gss_set_name_attribute(), which
+ -- should cause corresponding authz-data elements to be added to
+ -- any TGS-REQ or to the AP-REQ's Authenticator as appropriate.
+ want-ad [7] AuthorizationData OPTIONAL
+}
+-- This is our type for exported composite name tokens for GSS [RFC6680].
+-- It's the same as Principal (below) as decorated with (see krb5.opt file and
+-- asn1_compile usage), except it's not decorated, so the name attributes are
+-- encoded/decoded.
+CompositePrincipal ::= [APPLICATION 48] SEQUENCE {
+ name[0] PrincipalName,
+ realm[1] Realm,
+ nameattrs[2] PrincipalNameAttrs OPTIONAL
+}
+
+-- This is not part of RFC1510/RFC4120. We use this internally as our
+-- krb5_principal (which is a typedef of *Principal), and in HDB entries.
+Principal ::= SEQUENCE {
+ name[0] PrincipalName,
+ realm[1] Realm
+ -- This will be decorated with an optional nameattrs field of
+ -- PrincipalNameAttrs type that doesn't get encoded. Same as
+ -- CompositePrincipal above, except that CompositePrincipal's
+ -- nameattrs field does get encoded, while Principal's does not:
+ --
+ -- nameattrs[2] PrincipalNameAttrs OPTIONAL
+}
+
+Principals ::= SEQUENCE OF Principal
+
+Authenticator ::= [APPLICATION 2] SEQUENCE {
+ authenticator-vno[0] Krb5Int32,
+ crealm[1] Realm,
+ cname[2] PrincipalName,
+ cksum[3] Checksum OPTIONAL,
+ cusec[4] Krb5Int32,
+ ctime[5] KerberosTime,
+ subkey[6] EncryptionKey OPTIONAL,
+ seq-number[7] Krb5UInt32 OPTIONAL,
+ authorization-data[8] AuthorizationData OPTIONAL
+}
+
+PA-DATA ::= SEQUENCE {
+ -- might be encoded AP-REQ
+ padata-type[1] PADATA-TYPE,
+ padata-value[2] OCTET STRING
+}
+
+ETYPE-INFO-ENTRY ::= SEQUENCE {
+ etype[0] ENCTYPE,
+ salt[1] OCTET STRING OPTIONAL,
+ salttype[2] Krb5Int32 OPTIONAL
+}
+
+ETYPE-INFO ::= SEQUENCE OF ETYPE-INFO-ENTRY
+
+ETYPE-INFO2-ENTRY ::= SEQUENCE {
+ etype[0] ENCTYPE,
+ salt[1] KerberosString OPTIONAL,
+ s2kparams[2] OCTET STRING OPTIONAL
+}
+
+ETYPE-INFO2 ::= SEQUENCE SIZE (1..MAX) OF ETYPE-INFO2-ENTRY
+
+METHOD-DATA ::= SEQUENCE OF PA-DATA
+
+TypedData ::= SEQUENCE {
+ data-type[0] Krb5Int32,
+ data-value[1] OCTET STRING OPTIONAL
+}
+
+TYPED-DATA ::= SEQUENCE SIZE (1..MAX) OF TypedData
+
+KDC-REQ-BODY ::= SEQUENCE {
+ kdc-options[0] KDCOptions,
+ cname[1] PrincipalName OPTIONAL, -- Used only in AS-REQ
+ realm[2] Realm, -- Server's realm
+ -- Also client's in AS-REQ
+ sname[3] PrincipalName OPTIONAL,
+ from[4] KerberosTime OPTIONAL,
+ till[5] KerberosTime OPTIONAL,
+ rtime[6] KerberosTime OPTIONAL,
+ nonce[7] Krb5Int32,
+ etype[8] SEQUENCE OF ENCTYPE, -- EncryptionType,
+ -- in preference order
+ addresses[9] HostAddresses OPTIONAL,
+ enc-authorization-data[10] EncryptedData OPTIONAL,
+ -- Encrypted AuthorizationData encoding
+ additional-tickets[11] SEQUENCE OF Ticket OPTIONAL
+}
+
+KDC-REQ ::= SEQUENCE {
+ pvno[1] Krb5Int32,
+ msg-type[2] MESSAGE-TYPE,
+ padata[3] METHOD-DATA OPTIONAL,
+ req-body[4] KDC-REQ-BODY
+}
+
+AS-REQ ::= [APPLICATION 10] KDC-REQ
+TGS-REQ ::= [APPLICATION 12] KDC-REQ
+
+-- padata-type ::= PA-ENC-TIMESTAMP
+-- padata-value ::= EncryptedData - PA-ENC-TS-ENC
+
+PA-ENC-TS-ENC ::= SEQUENCE {
+ patimestamp[0] KerberosTime, -- client's time
+ pausec[1] Krb5Int32 OPTIONAL
+}
+
+-- draft-brezak-win2k-krb-authz-01
+PA-PAC-REQUEST ::= SEQUENCE {
+ include-pac[0] BOOLEAN -- Indicates whether a PAC
+ -- should be included or not
+}
+
+-- MS-KILE/MS-SFU
+PAC-OPTIONS-FLAGS ::= BIT STRING {
+ claims(0),
+ branch-aware(1),
+ forward-to-full-dc(2),
+ resource-based-constrained-delegation(3)
+}
+
+-- MS-KILE
+PA-PAC-OPTIONS ::= SEQUENCE {
+ flags [0] PAC-OPTIONS-FLAGS
+}
+
+-- MS-KILE
+-- captures show that [UNIVERSAL 16] is required to parse it
+KERB-AD-RESTRICTION-ENTRY ::= [UNIVERSAL 16] SEQUENCE {
+ restriction-type [0] Krb5Int32,
+ restriction [1] OCTET STRING -- LSAP_TOKEN_INFO_INTEGRITY structure
+}
+
+-- MS-KILE Section 2.2.11
+PA-KERB-KEY-LIST-REQ ::= SEQUENCE OF ENCTYPE
+
+-- MS-KILE Section 2.2.12
+
+PA-KERB-KEY-LIST-REP ::= SEQUENCE OF ENCTYPE -- EncryptionType,
+
+-- PacketCable provisioning server location, PKT-SP-SEC-I09-030728.pdf
+PROV-SRV-LOCATION ::= GeneralString
+
+KDC-REP ::= SEQUENCE {
+ pvno[0] Krb5Int32,
+ msg-type[1] MESSAGE-TYPE,
+ padata[2] METHOD-DATA OPTIONAL,
+ crealm[3] Realm,
+ cname[4] PrincipalName,
+ ticket[5] Ticket,
+ enc-part[6] EncryptedData
+}
+
+AS-REP ::= [APPLICATION 11] KDC-REP
+TGS-REP ::= [APPLICATION 13] KDC-REP
+
+EncKDCRepPart ::= SEQUENCE {
+ key[0] EncryptionKey,
+ last-req[1] LastReq,
+ nonce[2] Krb5Int32,
+ key-expiration[3] KerberosTime OPTIONAL,
+ flags[4] TicketFlags,
+ authtime[5] KerberosTime,
+ starttime[6] KerberosTime OPTIONAL,
+ endtime[7] KerberosTime,
+ renew-till[8] KerberosTime OPTIONAL,
+ srealm[9] Realm,
+ sname[10] PrincipalName,
+ caddr[11] HostAddresses OPTIONAL,
+ encrypted-pa-data[12] METHOD-DATA OPTIONAL
+}
+
+EncASRepPart ::= [APPLICATION 25] EncKDCRepPart
+EncTGSRepPart ::= [APPLICATION 26] EncKDCRepPart
+
+AP-REQ ::= [APPLICATION 14] SEQUENCE {
+ pvno[0] Krb5Int32,
+ msg-type[1] MESSAGE-TYPE,
+ ap-options[2] APOptions,
+ ticket[3] Ticket,
+ authenticator[4] EncryptedData
+}
+
+AP-REP ::= [APPLICATION 15] SEQUENCE {
+ pvno[0] Krb5Int32,
+ msg-type[1] MESSAGE-TYPE,
+ enc-part[2] EncryptedData
+}
+
+EncAPRepPart ::= [APPLICATION 27] SEQUENCE {
+ ctime[0] KerberosTime,
+ cusec[1] Krb5Int32,
+ subkey[2] EncryptionKey OPTIONAL,
+ seq-number[3] Krb5UInt32 OPTIONAL
+}
+
+KRB-SAFE-BODY ::= SEQUENCE {
+ user-data[0] OCTET STRING,
+ timestamp[1] KerberosTime OPTIONAL,
+ usec[2] Krb5Int32 OPTIONAL,
+ seq-number[3] Krb5UInt32 OPTIONAL,
+ s-address[4] HostAddress OPTIONAL,
+ r-address[5] HostAddress OPTIONAL
+}
+
+KRB-SAFE ::= [APPLICATION 20] SEQUENCE {
+ pvno[0] Krb5Int32,
+ msg-type[1] MESSAGE-TYPE,
+ safe-body[2] KRB-SAFE-BODY,
+ cksum[3] Checksum
+}
+
+KRB-PRIV ::= [APPLICATION 21] SEQUENCE {
+ pvno[0] Krb5Int32,
+ msg-type[1] MESSAGE-TYPE,
+ enc-part[3] EncryptedData
+}
+EncKrbPrivPart ::= [APPLICATION 28] SEQUENCE {
+ user-data[0] OCTET STRING,
+ timestamp[1] KerberosTime OPTIONAL,
+ usec[2] Krb5Int32 OPTIONAL,
+ seq-number[3] Krb5UInt32 OPTIONAL,
+ s-address[4] HostAddress OPTIONAL, -- sender's addr
+ r-address[5] HostAddress OPTIONAL -- recip's addr
+}
+
+KRB-CRED ::= [APPLICATION 22] SEQUENCE {
+ pvno[0] Krb5Int32,
+ msg-type[1] MESSAGE-TYPE, -- KRB_CRED
+ tickets[2] SEQUENCE OF Ticket,
+ enc-part[3] EncryptedData
+}
+
+KrbCredInfo ::= SEQUENCE {
+ key[0] EncryptionKey,
+ prealm[1] Realm OPTIONAL,
+ pname[2] PrincipalName OPTIONAL,
+ flags[3] TicketFlags OPTIONAL,
+ authtime[4] KerberosTime OPTIONAL,
+ starttime[5] KerberosTime OPTIONAL,
+ endtime[6] KerberosTime OPTIONAL,
+ renew-till[7] KerberosTime OPTIONAL,
+ srealm[8] Realm OPTIONAL,
+ sname[9] PrincipalName OPTIONAL,
+ caddr[10] HostAddresses OPTIONAL
+}
+
+EncKrbCredPart ::= [APPLICATION 29] SEQUENCE {
+ ticket-info[0] SEQUENCE OF KrbCredInfo,
+ nonce[1] Krb5Int32 OPTIONAL,
+ timestamp[2] KerberosTime OPTIONAL,
+ usec[3] Krb5Int32 OPTIONAL,
+ s-address[4] HostAddress OPTIONAL,
+ r-address[5] HostAddress OPTIONAL
+}
+
+KRB-ERROR ::= [APPLICATION 30] SEQUENCE {
+ pvno[0] Krb5Int32,
+ msg-type[1] MESSAGE-TYPE,
+ ctime[2] KerberosTime OPTIONAL,
+ cusec[3] Krb5Int32 OPTIONAL,
+ stime[4] KerberosTime,
+ susec[5] Krb5Int32,
+ error-code[6] Krb5Int32,
+ crealm[7] Realm OPTIONAL,
+ cname[8] PrincipalName OPTIONAL,
+ realm[9] Realm, -- Correct realm
+ sname[10] PrincipalName, -- Correct name
+ e-text[11] GeneralString OPTIONAL,
+ e-data[12] OCTET STRING OPTIONAL
+}
+
+ChangePasswdDataMS ::= SEQUENCE {
+ newpasswd[0] OCTET STRING,
+ targname[1] PrincipalName OPTIONAL,
+ targrealm[2] Realm OPTIONAL
+}
+
+EtypeList ::= SEQUENCE OF ENCTYPE
+ -- the client's proposed enctype list in
+ -- decreasing preference order, favorite choice first
+
+krb5-pvno Krb5Int32 ::= 5 -- current Kerberos protocol version number
+
+-- transited encodings
+
+domain-X500-Compress Krb5Int32 ::= 1
+
+-- authorization data primitives
+
+AD-IF-RELEVANT ::= AuthorizationData
+
+AD-KDCIssued ::= SEQUENCE {
+ ad-checksum[0] Checksum,
+ i-realm[1] Realm OPTIONAL,
+ i-sname[2] PrincipalName OPTIONAL,
+ elements[3] AuthorizationData
+}
+
+AD-AND-OR ::= SEQUENCE {
+ condition-count[0] Krb5Int32,
+ elements[1] AuthorizationData
+}
+
+AD-MANDATORY-FOR-KDC ::= AuthorizationData
+
+-- PA-SAM-RESPONSE-2/PA-SAM-RESPONSE-2
+
+PA-SAM-TYPE ::= INTEGER {
+ PA_SAM_TYPE_ENIGMA(1), -- Enigma Logic
+ PA_SAM_TYPE_DIGI_PATH(2), -- Digital Pathways
+ PA_SAM_TYPE_SKEY_K0(3), -- S/key where KDC has key 0
+ PA_SAM_TYPE_SKEY(4), -- Traditional S/Key
+ PA_SAM_TYPE_SECURID(5), -- Security Dynamics
+ PA_SAM_TYPE_CRYPTOCARD(6) -- CRYPTOCard
+}
+
+PA-SAM-REDIRECT ::= HostAddresses
+
+SAMFlags ::= BIT STRING {
+ use-sad-as-key(0),
+ send-encrypted-sad(1),
+ must-pk-encrypt-sad(2)
+}
+
+PA-SAM-CHALLENGE-2-BODY ::= SEQUENCE {
+ sam-type[0] Krb5Int32,
+ sam-flags[1] SAMFlags,
+ sam-type-name[2] GeneralString OPTIONAL,
+ sam-track-id[3] GeneralString OPTIONAL,
+ sam-challenge-label[4] GeneralString OPTIONAL,
+ sam-challenge[5] GeneralString OPTIONAL,
+ sam-response-prompt[6] GeneralString OPTIONAL,
+ sam-pk-for-sad[7] EncryptionKey OPTIONAL,
+ sam-nonce[8] Krb5Int32,
+ sam-etype[9] Krb5Int32,
+ ...
+}
+
+PA-SAM-CHALLENGE-2 ::= SEQUENCE {
+ sam-body[0] PA-SAM-CHALLENGE-2-BODY,
+ sam-cksum[1] SEQUENCE OF Checksum, -- (1..MAX)
+ ...
+}
+
+PA-SAM-RESPONSE-2 ::= SEQUENCE {
+ sam-type[0] Krb5Int32,
+ sam-flags[1] SAMFlags,
+ sam-track-id[2] GeneralString OPTIONAL,
+ sam-enc-nonce-or-sad[3] EncryptedData, -- PA-ENC-SAM-RESPONSE-ENC
+ sam-nonce[4] Krb5Int32,
+ ...
+}
+
+PA-ENC-SAM-RESPONSE-ENC ::= SEQUENCE {
+ sam-nonce[0] Krb5Int32,
+ sam-sad[1] GeneralString OPTIONAL,
+ ...
+}
+
+PA-S4U2Self ::= SEQUENCE {
+ name[0] PrincipalName,
+ realm[1] Realm,
+ cksum[2] Checksum,
+ auth[3] GeneralString
+}
+
+PA-S4U-X509-USER::= SEQUENCE {
+ user-id[0] S4UUserID,
+ checksum[1] Checksum
+}
+
+S4UUserID ::= SEQUENCE {
+ nonce [0] Krb5UInt32, -- the nonce in KDC-REQ-BODY
+ cname [1] PrincipalName OPTIONAL, -- Certificate mapping hints
+ crealm [2] Realm,
+ subject-certificate [3] OCTET STRING OPTIONAL,
+ options [4] BIT STRING OPTIONAL,
+ ...
+}
+
+AD-LoginAlias ::= SEQUENCE { -- ad-type number TBD --
+ login-alias [0] PrincipalName,
+ checksum [1] Checksum
+}
+
+-- old ms referral
+PA-SvrReferralData ::= SEQUENCE {
+ referred-name [1] PrincipalName OPTIONAL,
+ referred-realm [0] Realm
+}
+
+PA-SERVER-REFERRAL-DATA ::= EncryptedData
+
+PA-ServerReferralData ::= SEQUENCE {
+ referred-realm [0] Realm OPTIONAL,
+ true-principal-name [1] PrincipalName OPTIONAL,
+ requested-principal-name [2] PrincipalName OPTIONAL,
+ referral-valid-until [3] KerberosTime OPTIONAL,
+ ...
+}
+
+FastOptions ::= BIT STRING {
+ reserved(0),
+ hide-client-names(1),
+ critical2(2),
+ critical3(3),
+ critical4(4),
+ critical5(5),
+ critical6(6),
+ critical7(7),
+ critical8(8),
+ critical9(9),
+ critical10(10),
+ critical11(11),
+ critical12(12),
+ critical13(13),
+ critical14(14),
+ critical15(15),
+ kdc-follow-referrals(16)
+}
+
+KrbFastReq ::= SEQUENCE {
+ fast-options [0] FastOptions,
+ padata [1] METHOD-DATA,
+ req-body [2] KDC-REQ-BODY,
+ ...
+}
+
+KrbFastArmor ::= SEQUENCE {
+ armor-type [0] Krb5Int32,
+ armor-value [1] OCTET STRING,
+ ...
+}
+
+KrbFastArmoredReq ::= SEQUENCE {
+ armor [0] KrbFastArmor OPTIONAL,
+ req-checksum [1] Checksum,
+ enc-fast-req [2] EncryptedData -- KrbFastReq --
+}
+
+PA-FX-FAST-REQUEST ::= CHOICE {
+ armored-data [0] KrbFastArmoredReq,
+ ...
+}
+
+KrbFastFinished ::= SEQUENCE {
+ timestamp [0] KerberosTime,
+ usec [1] Krb5Int32,
+ crealm [2] Realm,
+ cname [3] PrincipalName,
+ ticket-checksum [4] Checksum,
+ ...
+}
+
+KrbFastResponse ::= SEQUENCE {
+ padata [0] METHOD-DATA,
+ strengthen-key [1] EncryptionKey OPTIONAL,
+ finished [2] KrbFastFinished OPTIONAL,
+ nonce [3] Krb5UInt32,
+ ...
+}
+
+KrbFastArmoredRep ::= SEQUENCE {
+ enc-fast-rep [0] EncryptedData, -- KrbFastResponse --
+ ...
+}
+
+PA-FX-FAST-REPLY ::= CHOICE {
+ armored-data [0] KrbFastArmoredRep,
+ ...
+}
+
+KDCFastFlags ::= BIT STRING {
+ use-reply-key(0),
+ reply-key-used(1),
+ reply-key-replaced(2),
+ kdc-verified(3),
+ requested-hidden-names(4)
+}
+
+-- KDCFastState is stored in FX_COOKIE
+KDCFastState ::= SEQUENCE {
+ flags [0] KDCFastFlags,
+ expiration [1] GeneralizedTime,
+ fast-state [2] METHOD-DATA,
+ expected-pa-types [3] SEQUENCE OF PADATA-TYPE OPTIONAL
+}
+
+KDCFastCookie ::= SEQUENCE {
+ version [0] UTF8String,
+ cookie [1] EncryptedData
+}
+
+KDC-PROXY-MESSAGE ::= SEQUENCE {
+ kerb-message [0] OCTET STRING,
+ target-domain [1] Realm OPTIONAL,
+ dclocator-hint [2] INTEGER OPTIONAL
+}
+
+-- these messages are used in the GSSCred communication and is not part of Kerberos propper
+
+KERB-TIMES ::= SEQUENCE {
+ authtime [0] KerberosTime,
+ starttime [1] KerberosTime,
+ endtime [2] KerberosTime,
+ renew_till [3] KerberosTime
+}
+
+KERB-CRED ::= SEQUENCE {
+ client [0] Principal,
+ server [1] Principal,
+ keyblock [2] EncryptionKey,
+ times [3] KERB-TIMES,
+ ticket [4] OCTET STRING,
+ authdata [5] OCTET STRING,
+ addresses [6] HostAddresses,
+ flags [7] TicketFlags
+}
+
+KERB-TGS-REQ-IN ::= SEQUENCE {
+ cache [0] OCTET STRING SIZE (16),
+ addrs [1] HostAddresses,
+ flags [2] Krb5UInt32,
+ imp [3] Principal OPTIONAL,
+ ticket [4] OCTET STRING OPTIONAL,
+ in_cred [5] KERB-CRED,
+ krbtgt [6] KERB-CRED,
+ padata [7] METHOD-DATA
+}
+
+KERB-TGS-REQ-OUT ::= SEQUENCE {
+ subkey [0] EncryptionKey OPTIONAL,
+ t [1] TGS-REQ
+}
+
+
+
+KERB-TGS-REP-IN ::= SEQUENCE {
+ cache [0] OCTET STRING SIZE (16),
+ subkey [1] EncryptionKey OPTIONAL,
+ in_cred [2] KERB-CRED,
+ t [3] TGS-REP
+}
+
+KERB-TGS-REP-OUT ::= SEQUENCE {
+ cache [0] OCTET STRING SIZE (16),
+ cred [1] KERB-CRED,
+ subkey [2] EncryptionKey
+}
+
+KERB-ARMOR-SERVICE-REPLY ::= SEQUENCE {
+ armor [0] KrbFastArmor,
+ armor-key [1] EncryptionKey
+}
+
+END
+
+-- etags -r '/\([A-Za-z][-A-Za-z0-9]*\).*::=/\1/' k5.asn1
diff --git a/third_party/heimdal/lib/asn1/krb5.opt b/third_party/heimdal/lib/asn1/krb5.opt
new file mode 100644
index 0000000..a8bd85c
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/krb5.opt
@@ -0,0 +1,9 @@
+--encode-rfc1510-bit-string
+--sequence=Principals
+--sequence=AuthorizationData
+--sequence=METHOD-DATA
+--sequence=ETYPE-INFO
+--sequence=ETYPE-INFO2
+--preserve-binary=KDC-REQ-BODY
+--decorate=PrincipalNameAttrs:void *:pac
+--decorate=Principal:PrincipalNameAttrs:nameattrs?
diff --git a/third_party/heimdal/lib/asn1/kx509.asn1 b/third_party/heimdal/lib/asn1/kx509.asn1
new file mode 100644
index 0000000..af8a4d6
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/kx509.asn1
@@ -0,0 +1,204 @@
+-- $Id$
+
+-- Version 2 of the kx509 protocol is documented in RFC6717.
+--
+-- Our version here has extensions without changing the version number on the
+-- wire.
+
+KX509 DEFINITIONS ::= BEGIN
+IMPORTS Extensions FROM rfc2459
+ KerberosTime FROM krb5;
+
+KX509-ERROR-CODE ::= INTEGER {
+ KX509-STATUS-GOOD(0),
+ KX509-STATUS-CLIENT-BAD(1),
+ KX509-STATUS-CLIENT-FIX(2),
+ KX509-STATUS-CLIENT-TEMP(3),
+ KX509-STATUS-SERVER-BAD(4),
+ KX509-STATUS-SERVER-TEMP(5),
+ -- 6 is used internally in the umich client, avoid that
+ KX509-STATUS-SERVER-KEY(7),
+ -- CSR use negotiation:
+ KX509-STATUS-CLIENT-USE-CSR(8)
+ -- Let us reserve 1000+ for Kebreros protocol wire error codes -Nico
+}
+
+-- Originally kx509 requests carried only a public key. We'd like to have
+-- proof of possession, and the ability to carry additional options, both, in
+-- cleartext and otherwise.
+--
+-- We'll use a CSR for proof of posession and desired certificate extensions.
+--
+-- We'll also provide a non-CSR-based method of conveying desired certificate
+-- extensions. The reason for this is simply that we may want to have a [e.g.,
+-- RESTful HTTP] proxy for the kx509 service, and we want clients to be able to
+-- be as simple as possible -cargo-culted even- with support for attributes
+-- (desired certificate extensions) as parameters outside the CSR that the
+-- proxy can encode without having the private key for the CSR (naturally).
+--
+-- I.e., ultimately we'll have a REST endpoint, /kx509, say, with query
+-- parameters like:
+--
+-- - csr=<base64-encoding-of-DER-encoded-CSR>
+-- - eku=<OID>
+-- - ku=<key-usage-flag-name>
+-- - rfc822Name=<URL-escaped-email-address>
+-- - xMPPName=<URL-escaped-jabber-address>
+-- - dNSName=<URL-escaped-FQDN>
+-- - dNSSrv=<URL-escaped-_service.FQDN>
+-- - registeredID=<OID>
+-- - principalName=<URL-escaped-RFC1964-format-Kerberos-Principal-Name>
+--
+-- with exactly one CSR and zero, one, or more of the other parameters.
+--
+-- We'll even have a way to convey a bearer token from the REST proxy so that
+-- we may have a way to get PKIX credentials using bearer tokens. And then,
+-- using PKINIT, we may have a way to get Kerberos credentials using bearer
+-- tokens.
+--
+-- To do this we define a Kx509CSRPlus that we can use in the `pk-key' field of
+-- Kx509Request (see below):
+Kx509CSRPlus ::= [APPLICATION 35] SEQUENCE {
+ -- PKCS#10, DER-encoded CSR, with or without meaningful attributes
+ csr OCTET STRING,
+ -- Desired certificate Extensions such as KeyUsage, ExtKeyUsage, or
+ -- subjectAlternativeName (SAN)
+ exts Extensions OPTIONAL,
+ -- Desired certificate lifetime
+ req-life KerberosTime OPTIONAL,
+ ...
+}
+
+-- Version 2
+Kx509Request ::= SEQUENCE {
+ authenticator OCTET STRING,
+ pk-hash OCTET STRING, -- HMAC(ticket_session_key, pk-key)
+ pk-key OCTET STRING -- one of:
+ -- - the public key, DER-encoded (RSA, basically)
+ -- - a Kx509CSRPlus
+}
+
+-- Kx509ErrorCode is a Heimdal-specific enhancement with no change on the wire,
+-- and really only just so the error-code field below can fit on one line.
+Kx509ErrorCode ::= INTEGER (-2147483648..2147483647)
+
+Kx509Response ::= SEQUENCE {
+ error-code[0] Kx509ErrorCode DEFAULT 0,
+ hash[1] OCTET STRING OPTIONAL, -- HMAC(session_key, ...)
+ certificate[2] OCTET STRING OPTIONAL, -- DER-encoded Certificate
+ -- if client sent raw RSA SPK
+ -- or DER-encoded Certificates
+ -- (i.e., SEQ. OF Certificate)
+ -- if client used a
+ -- Kx509CSRPlus
+ e-text[3] VisibleString OPTIONAL
+}
+
+-- Offset for Kerberos protocol errors when error-code set to one:
+kx509-krb5-error-base INTEGER ::= 1000
+
+-- RFC6717 says this about error codes:
+--
+-- +------------+-----------------------------+------------------------+
+-- | error-code | Condition | Example |
+-- +------------+-----------------------------+------------------------+
+-- | 1 | Permanent problem with | Incompatible version |
+-- | | client request | |
+-- | 2 | Solvable problem with | Expired Kerberos |
+-- | | client request | credentials |
+-- | 3 | Temporary problem with | Packet loss |
+-- | | client request | |
+-- | 4 | Permanent problem with the | Internal |
+-- | | server | misconfiguration |
+-- | 5 | Temporary problem with the | Server overloaded |
+-- | | server | |
+-- +------------+-----------------------------+------------------------+
+--
+-- Looking at UMich CITI's kca (server-side of kx509) implementation, it always
+-- sends 0 as the status code, and the UMich CITI kx509 client never checks it.
+-- All of these error codes are local only in the UMich CITI implementation.
+--
+-- Meanwhile, Heimdal used to never send error responses at all.
+--
+-- As a result we can use whatever error codes we want. We'll send Kerberos
+-- protocol errors + 1000. And we'll never use RFC6717 error codes at all.
+--
+-- Looking at umich source...
+--
+-- #define KX509_STATUS_GOOD 0 /* No problems handling client request */
+-- #define KX509_STATUS_CLNT_BAD 1 /* Client-side permanent problem */
+-- /* ex. version incompatible */
+-- #define KX509_STATUS_CLNT_FIX 2 /* Client-side solvable problem */
+-- /* ex. re-authenticate */
+-- #define KX509_STATUS_CLNT_TMP 3 /* Client-side temporary problem */
+-- /* ex. packet loss */
+-- #define KX509_STATUS_SRVR_BAD 4 /* Server-side permanent problem */
+-- /* ex. server broken */
+-- #define KX509_STATUS_SRVR_TMP 5 /* Server-side temporary problem */
+-- /* ex. server overloaded */
+-- #define KX509_STATUS_SRVR_CANT_CLNT_VERS 6 /* Server-side doesn't handle */
+-- /* existence of client_version */
+-- /* field in KX509_REQUEST */
+--
+-- The umich server uses these errors in these situations:
+--
+-- - KX509_STATUS_SRVR_TMP is for:
+-- - request decode errors
+-- - krb5_is_ap_req() errors
+-- - wrong Kerberos protocol vno in AP-REQ
+-- - some ENOMEMs
+-- - UDP read errors (??)
+-- - LDAP issues (they use LDAP to map realm-chopped user princ names to
+-- full names)
+-- - pk decode errors
+-- - KX509_STATUS_CLNT_TMP is for:
+-- - HMAC mismatch
+-- - some ENOMEMs
+-- - failure to accept AP-REQ
+-- - failure to unparse princ names from AP-REQ's Ticket
+-- - KX509_STATUS_SRVR_BAD is for:
+-- - configuration issues (missing issuer creds)
+-- - serial number transaction issues (we should randomize)
+-- - subjectName construction issues
+-- - certificate construction issues (ENOMEM, say)
+-- - failure to authenticate (never happens, since KX509_STATUS_CLNT_TMP is
+-- used earlier when krb5_rd_req() fails)
+-- - KX509_STATUS_CLNT_FIX is for:
+-- - more than one component client principals
+-- - client princ name component zero string length shorter than 3 or
+-- longer than 8 (WTF)
+-- - other policy issues
+-- - KX509_STATUS_CLNT_BAD
+-- - wrong protocol version number (version_2_0)
+
+-- Possible new version designs:
+--
+-- - keep the protocol the same but use a CSR instead of a raw RSA public key
+-- - on the server try decoding first a CSR, then a raw RSA public key
+--
+-- - keep the protocol the same but use either a CSR or a self-signed cert
+-- - on the server try decoding first a Certificate, then a CSR, then a raw
+-- RSA public key
+--
+-- CSRs are a pain to deal with. Self-signed certificates can act as a
+-- CSR of a sort. Use notBefore == 1970-01-01T00:00:00Z and an EKU
+-- denoting "this certificate is really a much-easier-to-work-with CSR
+-- alternative".
+--
+-- - keep the protocol similar, but use the checksum field of the
+-- Authenticator to authenticate the request data; use a KRB-PRIV for the
+-- reply
+--
+-- - extend the KDC/AS/TGS protocols to support certificate issuance, either
+-- at the same time as ticket acquisition, or as an alternative
+-- - send a CSR as a authz-data element
+-- - expect an EncryptedData with the issued Certificate inside as the
+-- Ticket in the result (again, ugly hack)
+-- - or maybe just add new messages, but, the thing is that the existing
+-- "AP-REP + stuff" kx509 protocol is a fine design pattern, there's no
+-- need to radically change it, just slightly.
+--
+-- The main benefit of using an extension to the KDC/AS/TGS protocols is that
+-- we could then use FAST for confidentiality protection.
+
+END
diff --git a/third_party/heimdal/lib/asn1/lex.h b/third_party/heimdal/lib/asn1/lex.h
new file mode 100644
index 0000000..1ee5341
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/lex.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#include <roken.h>
+
+void lex_error_message (const char *, ...)
+__attribute__ ((format (printf, 1, 2)));
+extern int error_flag;
+
+int yylex(void);
diff --git a/third_party/heimdal/lib/asn1/lex.l b/third_party/heimdal/lib/asn1/lex.l
new file mode 100644
index 0000000..4554a94
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/lex.l
@@ -0,0 +1,310 @@
+%{
+/*
+ * Copyright (c) 1997 - 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <stdio.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#undef ECHO
+#include "symbol.h"
+#include "asn1parse.h"
+#include "lex.h"
+#include "gen_locl.h"
+
+static unsigned lineno = 1;
+
+#undef ECHO
+
+static void unterminated(const char *, unsigned);
+
+%}
+
+/* This is for broken old lexes (solaris 10 and hpux) */
+%e 2000
+%p 5000
+%a 5000
+%n 1000
+%o 10000
+
+%%
+ABSENT { return kw_ABSENT; }
+ABSTRACT-SYNTAX { return kw_ABSTRACT_SYNTAX; }
+ALL { return kw_ALL; }
+APPLICATION { return kw_APPLICATION; }
+AUTOMATIC { return kw_AUTOMATIC; }
+BEGIN { return kw_BEGIN; }
+BIT { return kw_BIT; }
+BMPString { return kw_BMPString; }
+BOOLEAN { return kw_BOOLEAN; }
+BY { return kw_BY; }
+CHARACTER { return kw_CHARACTER; }
+CHOICE { return kw_CHOICE; }
+CLASS { return kw_CLASS; }
+COMPONENT { return kw_COMPONENT; }
+COMPONENTS { return kw_COMPONENTS; }
+CONSTRAINED { return kw_CONSTRAINED; }
+CONTAINING { return kw_CONTAINING; }
+DEFAULT { return kw_DEFAULT; }
+DEFINITIONS { return kw_DEFINITIONS; }
+EMBEDDED { return kw_EMBEDDED; }
+ENCODED { return kw_ENCODED; }
+END { return kw_END; }
+ENUMERATED { return kw_ENUMERATED; }
+EXCEPT { return kw_EXCEPT; }
+EXPLICIT { return kw_EXPLICIT; }
+EXPORTS { return kw_EXPORTS; }
+EXTENSIBILITY { return kw_EXTENSIBILITY; }
+EXTERNAL { return kw_EXTERNAL; }
+FALSE { return kw_FALSE; }
+FROM { return kw_FROM; }
+GeneralString { return kw_GeneralString; }
+GeneralizedTime { return kw_GeneralizedTime; }
+GraphicString { return kw_GraphicString; }
+IA5String { return kw_IA5String; }
+IDENTIFIER { return kw_IDENTIFIER; }
+IMPLICIT { return kw_IMPLICIT; }
+IMPLIED { return kw_IMPLIED; }
+IMPORTS { return kw_IMPORTS; }
+INCLUDES { return kw_INCLUDES; }
+INSTANCE { return kw_INSTANCE; }
+INTEGER { return kw_INTEGER; }
+INTERSECTION { return kw_INTERSECTION; }
+ISO646String { return kw_ISO646String; }
+MAX { return kw_MAX; }
+MIN { return kw_MIN; }
+MINUS-INFINITY { return kw_MINUS_INFINITY; }
+NULL { return kw_NULL; }
+NumericString { return kw_NumericString; }
+OBJECT { return kw_OBJECT; }
+OCTET { return kw_OCTET; }
+OF { return kw_OF; }
+OPTIONAL { return kw_OPTIONAL; }
+ObjectDescriptor { return kw_ObjectDescriptor; }
+PATTERN { return kw_PATTERN; }
+PDV { return kw_PDV; }
+PLUS-INFINITY { return kw_PLUS_INFINITY; }
+PRESENT { return kw_PRESENT; }
+PRIVATE { return kw_PRIVATE; }
+PrintableString { return kw_PrintableString; }
+REAL { return kw_REAL; }
+RELATIVE_OID { return kw_RELATIVE_OID; }
+SEQUENCE { return kw_SEQUENCE; }
+SET { return kw_SET; }
+SIZE { return kw_SIZE; }
+STRING { return kw_STRING; }
+SYNTAX { return kw_SYNTAX; }
+T61String { return kw_T61String; }
+TAGS { return kw_TAGS; }
+TRUE { return kw_TRUE; }
+TYPE-IDENTIFIER { return kw_TYPE_IDENTIFIER; }
+TeletexString { return kw_TeletexString; }
+UNION { return kw_UNION; }
+UNIQUE { return kw_UNIQUE; }
+UNIVERSAL { return kw_UNIVERSAL; }
+UTCTime { return kw_UTCTime; }
+UTF8String { return kw_UTF8String; }
+UniversalString { return kw_UniversalString; }
+VideotexString { return kw_VideotexString; }
+VisibleString { return kw_VisibleString; }
+WITH { return kw_WITH; }
+[-,;{}()|] { return *yytext; }
+"[" { return *yytext; }
+"]" { return *yytext; }
+"&" { return *yytext; }
+"." { return *yytext; }
+":" { return *yytext; }
+"@" { return *yytext; }
+::= { return EEQUAL; }
+-- {
+ int c, start_lineno = lineno;
+ int f = 0;
+ while((c = input()) != EOF) {
+ if(f && c == '-')
+ break;
+ if(c == '-') {
+ f = 1;
+ continue;
+ }
+ if(c == '\n') {
+ lineno++;
+ break;
+ }
+ f = 0;
+ }
+ if(c == EOF)
+ unterminated("comment", start_lineno);
+ }
+\/\* {
+ int c, start_lineno = lineno;
+ int level = 1;
+ int seen_star = 0;
+ int seen_slash = 0;
+ while((c = input()) != EOF) {
+ if(c == '/') {
+ if(seen_star) {
+ if(--level == 0)
+ break;
+ seen_star = 0;
+ continue;
+ }
+ seen_slash = 1;
+ continue;
+ }
+ if(seen_star && c == '/') {
+ if(--level == 0)
+ break;
+ seen_star = 0;
+ continue;
+ }
+ if(c == '*') {
+ if(seen_slash) {
+ level++;
+ seen_star = seen_slash = 0;
+ continue;
+ }
+ seen_star = 1;
+ continue;
+ }
+ seen_star = seen_slash = 0;
+ if(c == '\n') {
+ lineno++;
+ continue;
+ }
+ }
+ if(c == EOF)
+ unterminated("comment", start_lineno);
+ }
+"\"" {
+ int start_lineno = lineno;
+ int c;
+ char buf[1024];
+ char *p = buf;
+ int f = 0;
+ int skip_ws = 0;
+
+ while((c = input()) != EOF) {
+ if(isspace(c) && skip_ws) {
+ if(c == '\n')
+ lineno++;
+ continue;
+ }
+ skip_ws = 0;
+
+ if(c == '"') {
+ if(f) {
+ *p++ = '"';
+ f = 0;
+ } else
+ f = 1;
+ continue;
+ }
+ if(f == 1) {
+ unput(c);
+ break;
+ }
+ if(c == '\n') {
+ lineno++;
+ while(p > buf && isspace((unsigned char)p[-1]))
+ p--;
+ skip_ws = 1;
+ continue;
+ }
+ *p++ = c;
+ }
+ if(c == EOF)
+ unterminated("string", start_lineno);
+ *p++ = '\0';
+ yylval.name = estrdup(buf);
+ return STRING;
+ }
+
+-?0x[0-9A-Fa-f]+|-?[0-9]+ { char *e, *y = yytext;
+ yylval.constant = strtoll((const char *)yytext,
+ &e, 0);
+ if(e == y)
+ lex_error_message("malformed constant (%s)", yytext);
+ else
+ return NUMBER;
+ }
+[_][-A-Z0-9]* {
+ yylval.name = estrdup ((const char *)yytext);
+ return CLASS_IDENTIFIER;
+ }
+[A-Z][-A-Za-z0-9_]* {
+ yylval.name = estrdup ((const char *)yytext);
+ return TYPE_IDENTIFIER;
+ }
+[a-z][-A-Za-z0-9_]* {
+ yylval.name = estrdup ((const char *)yytext);
+ return VALUE_IDENTIFIER;
+ }
+[ \t] ;
+\n { ++lineno; }
+\.\.\. { return ELLIPSIS; }
+\.\. { return RANGE; }
+. { lex_error_message("Ignoring char(%c)\n", *yytext); }
+%%
+
+int
+yywrap ()
+{
+ return 1;
+}
+
+void
+lex_error_message (const char *format, ...)
+{
+ va_list args;
+
+ va_start (args, format);
+ fprintf (stderr, "%s:%d: ", get_filename(), lineno);
+ vfprintf (stderr, format, args);
+ va_end (args);
+ error_flag++;
+}
+
+static void
+unterminated(const char *type, unsigned start_lineno)
+{
+ lex_error_message("unterminated %s, possibly started on line %d\n", type, start_lineno);
+}
diff --git a/third_party/heimdal/lib/asn1/libasn1-exports.def b/third_party/heimdal/lib/asn1/libasn1-exports.def
new file mode 100644
index 0000000..a7cb720
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/libasn1-exports.def
@@ -0,0 +1,2649 @@
+EXPORTS
+ _asn1_decode_top
+ _asn1_encode
+ _asn1_length
+ _asn1_free_top
+ _asn1_copy_top
+ _asn1_bmember_isset_bit
+ _asn1_bmember_put_bit
+ _asn1_copy
+ _asn1_copy_top
+ _asn1_decode
+ _asn1_decode_top
+ _asn1_encode
+ _asn1_free
+ _asn1_free_top
+ _asn1_length
+ _asn1_print_top
+ _asn1_sizeofType
+ add_AttributeValues
+ add_AuthorizationData
+ add_CertificatePolicies
+ add_Certificates
+ add_CRLDistributionPoints
+ add_DigestAlgorithmIdentifiers
+ add_ETYPE_INFO
+ add_ETYPE_INFO2
+ add_Extensions
+ add_GeneralNames
+ add_METHOD_DATA
+ add_PolicyMappings
+ add_PolicyQualifierInfos
+ add_Principals
+ add_RDNSequence
+ APOptions2int
+ asn1_APOptions_units
+ asn1_DigestTypes_units
+ asn1_DistributionPointReasonFlags_units
+ asn1_FastOptions_units
+ asn1_KDCFastFlags_units
+ asn1_KDCOptions_units
+ asn1_KeyUsage_units
+ asn1_oid_id_aa_communityIdentifiers DATA
+ asn1_oid_id_aa_decryptKeyID DATA
+ asn1_oid_id_aa_firmwarePackageID DATA
+ asn1_oid_id_aa_firmwarePackageInfo DATA
+ asn1_oid_id_aa_implCompressAlgs DATA
+ asn1_oid_id_aa_implCryptoAlgs DATA
+ asn1_oid_id_aa_targetHardwareIDs DATA
+ asn1_oid_id_aa_wrappedFirmwareKey DATA
+ asn1_oid_id_aes_128_cbc DATA
+ asn1_oid_id_aes_192_cbc DATA
+ asn1_oid_id_aes_256_cbc DATA
+ asn1_oid_id_apple_system_id DATA
+ asn1_oid_id_at_commonName DATA
+ asn1_oid_id_at_countryName DATA
+ asn1_oid_id_at_description DATA
+ asn1_oid_id_at_dnQualifier DATA
+ asn1_oid_id_at_emailAddress DATA
+ asn1_oid_id_at_generationQualifier DATA
+ asn1_oid_id_at_givenName DATA
+ asn1_oid_id_at_initials DATA
+ asn1_oid_id_at_localityName DATA
+ asn1_oid_id_at_name DATA
+ asn1_oid_id_at_organizationalUnitName DATA
+ asn1_oid_id_at_organizationName DATA
+ asn1_oid_id_at_pseudonym DATA
+ asn1_oid_id_at_serialNumber DATA
+ asn1_oid_id_at_stateOrProvinceName DATA
+ asn1_oid_id_at_streetAddress DATA
+ asn1_oid_id_at_surname DATA
+ asn1_oid_id_at_title DATA
+ asn1_oid_id_ct_firmwareLoadError DATA
+ asn1_oid_id_ct_firmwareLoadReceipt DATA
+ asn1_oid_id_ct_firmwarePackage DATA
+ asn1_oid_id_dhpublicnumber DATA
+ asn1_oid_id_domainComponent DATA
+ asn1_oid_id_dsa DATA
+ asn1_oid_id_dsa_with_sha1 DATA
+ asn1_oid_id_ecDH DATA
+ asn1_oid_id_ecdsa_with_SHA1 DATA
+ asn1_oid_id_ecdsa_with_SHA224 DATA
+ asn1_oid_id_ecdsa_with_SHA256 DATA
+ asn1_oid_id_ecdsa_with_SHA384 DATA
+ asn1_oid_id_ecdsa_with_SHA512 DATA
+ asn1_oid_id_ec_group_secp160r1 DATA
+ asn1_oid_id_ec_group_secp160r2 DATA
+ asn1_oid_id_ec_group_secp224r1 DATA
+ asn1_oid_id_ec_group_secp256r1 DATA
+ asn1_oid_id_ec_group_secp384r1 DATA
+ asn1_oid_id_ec_group_secp521r1 DATA
+ asn1_oid_id_ecMQV DATA
+ asn1_oid_id_ecPublicKey DATA
+ asn1_oid_id_heim_rsa_pkcs1_x509 DATA
+ asn1_oid_id_ms_cert_enroll_domaincontroller DATA
+ asn1_oid_id_msft DATA
+ asn1_oid_id_msft_kp_msCodeCom DATA
+ asn1_oid_id_msft_kp_msCodeInd DATA
+ asn1_oid_id_msft_kp_msCTLSign DATA
+ asn1_oid_id_msft_kp_msEFS DATA
+ asn1_oid_id_msft_kp_msSGC DATA
+ asn1_oid_id_msft_kp_msSmartcardLogin DATA
+ asn1_oid_id_msft_kp_msUPN DATA
+ asn1_oid_id_netscape_cert_comment DATA
+ asn1_oid_id_netscape DATA
+ asn1_oid_id_nist_aes_algs DATA
+ asn1_oid_id_nistAlgorithm DATA
+ asn1_oid_id_nist_sha_algs DATA
+ asn1_oid_id_on_hardwareModuleName DATA
+ asn1_oid_id_pbeWithSHAAnd128BitRC2_CBC DATA
+ asn1_oid_id_pbeWithSHAAnd128BitRC4 DATA
+ asn1_oid_id_pbeWithSHAAnd2_KeyTripleDES_CBC DATA
+ asn1_oid_id_pbeWithSHAAnd3_KeyTripleDES_CBC DATA
+ asn1_oid_id_pbewithSHAAnd40BitRC2_CBC DATA
+ asn1_oid_id_pbeWithSHAAnd40BitRC4 DATA
+ asn1_oid_id_pkauthdata DATA
+ asn1_oid_id_pkcs12_bagtypes DATA
+ asn1_oid_id_pkcs12_certBag DATA
+ asn1_oid_id_pkcs12_crlBag DATA
+ asn1_oid_id_pkcs_12 DATA
+ asn1_oid_id_pkcs12_keyBag DATA
+ asn1_oid_id_pkcs_12PbeIds DATA
+ asn1_oid_id_pkcs12_pkcs8ShroudedKeyBag DATA
+ asn1_oid_id_pkcs12_safeContentsBag DATA
+ asn1_oid_id_pkcs12_secretBag DATA
+ asn1_oid_id_pkcs_1 DATA
+ asn1_oid_id_pkcs1_md2WithRSAEncryption DATA
+ asn1_oid_id_pkcs1_md5WithRSAEncryption DATA
+ asn1_oid_id_pkcs1_rsaEncryption DATA
+ asn1_oid_id_pkcs1_sha1WithRSAEncryption DATA
+ asn1_oid_id_pkcs1_sha256WithRSAEncryption DATA
+ asn1_oid_id_pkcs1_sha384WithRSAEncryption DATA
+ asn1_oid_id_pkcs1_sha512WithRSAEncryption DATA
+ asn1_oid_id_pkcs_2 DATA
+ asn1_oid_id_pkcs2_md2 DATA
+ asn1_oid_id_pkcs2_md4 DATA
+ asn1_oid_id_pkcs2_md5 DATA
+ asn1_oid_id_pkcs_3 DATA
+ asn1_oid_id_pkcs3_des_ede3_cbc DATA
+ asn1_oid_id_pkcs3_rc2_cbc DATA
+ asn1_oid_id_pkcs3_rc4 DATA
+ asn1_oid_id_pkcs7 DATA
+ asn1_oid_id_pkcs7_data DATA
+ asn1_oid_id_pkcs7_digestedData DATA
+ asn1_oid_id_pkcs7_encryptedData DATA
+ asn1_oid_id_pkcs7_envelopedData DATA
+ asn1_oid_id_pkcs7_signedAndEnvelopedData DATA
+ asn1_oid_id_pkcs7_signedData DATA
+ asn1_oid_id_pkcs_9_at_certTypes DATA
+ asn1_oid_id_pkcs_9_at_certTypes_x509 DATA
+ asn1_oid_id_pkcs_9_at_friendlyName DATA
+ asn1_oid_id_pkcs_9_at_localKeyId DATA
+ asn1_oid_id_pkcs9_contentType DATA
+ asn1_oid_id_pkcs9_countersignature DATA
+ asn1_oid_id_pkcs_9 DATA
+ asn1_oid_id_pkcs9_emailAddress DATA
+ asn1_oid_id_pkcs9_extReq DATA
+ asn1_oid_id_pkcs9_messageDigest DATA
+ asn1_oid_id_pkcs9_signingTime DATA
+ asn1_oid_id_pkdhkeydata DATA
+ asn1_oid_id_pkekuoid DATA
+ asn1_oid_id_pkinit DATA
+ asn1_oid_id_pkinit_kdf_ah_sha1 DATA
+ asn1_oid_id_pkinit_kdf_ah_sha256 DATA
+ asn1_oid_id_pkinit_kdf_ah_sha512 DATA
+ asn1_oid_id_pkinit_kdf DATA
+ asn1_oid_id_pkinit_ms_eku DATA
+ asn1_oid_id_pkinit_ms_san DATA
+ asn1_oid_id_pkinit_san DATA
+ asn1_oid_id_pkix_ad_caIssuers DATA
+ asn1_oid_id_pkix_ad_caRepository DATA
+ asn1_oid_id_pkix_ad DATA
+ asn1_oid_id_pkix_ad_ocsp DATA
+ asn1_oid_id_pkix_ad_timeStamping DATA
+ asn1_oid_id_pkix DATA
+ asn1_oid_id_pkix_kp_bgpsec_router DATA
+ asn1_oid_id_pkix_kp_capwapAC DATA
+ asn1_oid_id_pkix_kp_capwapWTP DATA
+ asn1_oid_id_pkix_kp_clientAuth DATA
+ asn1_oid_id_pkix_kp_cmcArchive DATA
+ asn1_oid_id_pkix_kp_cmcCA DATA
+ asn1_oid_id_pkix_kp_cmcRA DATA
+ asn1_oid_id_pkix_kp_codeSigning DATA
+ asn1_oid_id_pkix_kp DATA
+ asn1_oid_id_pkix_kp_DVCS DATA
+ asn1_oid_id_pkix_kp_emailProtection DATA
+ asn1_oid_id_pkix_kp_ipsecEndSystem DATA
+ asn1_oid_id_pkix_kp_ipsecIKE DATA
+ asn1_oid_id_pkix_kp_ipsecTunnel DATA
+ asn1_oid_id_pkix_kp_ipsecUser DATA
+ asn1_oid_id_pkix_kp_OCSPSigning DATA
+ asn1_oid_id_pkix_kp_secureShellClient DATA
+ asn1_oid_id_pkix_kp_secureShellServer DATA
+ asn1_oid_id_pkix_kp_sendOwner DATA
+ asn1_oid_id_pkix_kp_sendProxiedOwner DATA
+ asn1_oid_id_pkix_kp_sendProxiedRouter DATA
+ asn1_oid_id_pkix_kp_sendRouter DATA
+ asn1_oid_id_pkix_kp_serverAuth DATA
+ asn1_oid_id_pkix_kp_sipDomain DATA
+ asn1_oid_id_pkix_kp_timeStamping DATA
+ asn1_oid_id_pkix_ocsp_basic DATA
+ asn1_oid_id_pkix_ocsp DATA
+ asn1_oid_id_pkix_ocsp_nonce DATA
+ asn1_oid_id_pkix_on DATA
+ asn1_oid_id_pkix_on_dnsSRV DATA
+ asn1_oid_id_pkix_on_hardwareModuleName DATA
+ asn1_oid_id_pkix_on_permanentIdentifier DATA
+ asn1_oid_id_pkix_on_pkinit_ms_san DATA
+ asn1_oid_id_pkix_on_pkinit_san DATA
+ asn1_oid_id_pkix_on_xmppAddr DATA
+ asn1_oid_id_pkix_pe_authorityInfoAccess DATA
+ asn1_oid_id_pkix_pe DATA
+ asn1_oid_id_pkix_pe_proxyCertInfo DATA
+ asn1_oid_id_pkix_pe_subjectInfoAccess DATA
+ asn1_oid_id_pkix_ppl_anyLanguage DATA
+ asn1_oid_id_pkix_ppl DATA
+ asn1_oid_id_pkix_ppl_independent DATA
+ asn1_oid_id_pkix_ppl_inheritAll DATA
+ asn1_oid_id_pkix_qt_cps DATA
+ asn1_oid_id_pkix_qt DATA
+ asn1_oid_id_pkix_qt_unotice DATA
+ asn1_oid_id_pkkdcekuoid DATA
+ asn1_oid_id_pkrkeydata DATA
+ asn1_oid_id_rsa_digestAlgorithm DATA
+ asn1_oid_id_rsa_digest_md2 DATA
+ asn1_oid_id_rsa_digest_md4 DATA
+ asn1_oid_id_rsa_digest_md5 DATA
+ asn1_oid_id_rsadsi_des_ede3_cbc DATA
+ asn1_oid_id_rsadsi_encalg DATA
+ asn1_oid_id_rsadsi_rc2_cbc DATA
+ asn1_oid_id_secsig_sha_1 DATA
+ asn1_oid_id_secsig_sha_1WithRSAEncryption DATA
+ asn1_oid_id_sha224 DATA
+ asn1_oid_id_sha256 DATA
+ asn1_oid_id_sha384 DATA
+ asn1_oid_id_sha512 DATA
+ asn1_oid_id_Userid DATA
+ asn1_oid_id_uspkicommon_card_id DATA
+ asn1_oid_id_uspkicommon_piv_interim DATA
+ asn1_oid_id_x509_ce_anyExtendedKeyUsage DATA
+ asn1_oid_id_x509_ce_authorityKeyIdentifier DATA
+ asn1_oid_id_x509_ce_basicConstraints DATA
+ asn1_oid_id_x509_ce_certificateIssuer DATA
+ asn1_oid_id_x509_ce_certificatePolicies_anyPolicy DATA
+ asn1_oid_id_x509_ce_certificatePolicies DATA
+ asn1_oid_id_x509_ce_cRLDistributionPoints DATA
+ asn1_oid_id_x509_ce_cRLNumber DATA
+ asn1_oid_id_x509_ce_cRLReason DATA
+ asn1_oid_id_x509_ce_cRLReasons DATA
+ asn1_oid_id_x509_ce DATA
+ asn1_oid_id_x509_ce_deltaCRLIndicator DATA
+ asn1_oid_id_x509_ce_extKeyUsage DATA
+ asn1_oid_id_x509_ce_freshestCRL DATA
+ asn1_oid_id_x509_ce_holdInstructionCode DATA
+ asn1_oid_id_x509_ce_inhibitAnyPolicy DATA
+ asn1_oid_id_x509_ce_invalidityDate DATA
+ asn1_oid_id_x509_ce_issuerAltName DATA
+ asn1_oid_id_x509_ce_issuingDistributionPoint DATA
+ asn1_oid_id_x509_ce_keyUsage DATA
+ asn1_oid_id_x509_ce_nameConstraints DATA
+ asn1_oid_id_x509_ce_policyConstraints DATA
+ asn1_oid_id_x509_ce_policyMappings DATA
+ asn1_oid_id_x509_ce_privateKeyUsagePeriod DATA
+ asn1_oid_id_x509_ce_subjectAltName DATA
+ asn1_oid_id_x509_ce_subjectDirectoryAttributes DATA
+ asn1_oid_id_x509_ce_subjectKeyIdentifier DATA
+ asn1_oid_id_x520_at DATA
+ asn1_oid_id_x9_57 DATA
+ asn1_oid_tcg_at_tpmManufacturer DATA
+ asn1_oid_tcg_at_tpmModel DATA
+ asn1_oid_tcg_at_tpmSecurityAssertions DATA
+ asn1_oid_tcg_at_tpmSpecification DATA
+ asn1_oid_tcg_at_tpmVersion DATA
+ asn1_oid_tcg_attribute DATA
+ asn1_oid_tcg_cap_verifiedTPMFixed DATA
+ asn1_oid_tcg_cap_verifiedTPMResidency DATA
+ asn1_oid_tcg_cap_verifiedTPMRestricted DATA
+ asn1_oid_tcg DATA
+ asn1_oid_tcg_kp DATA
+ asn1_oid_tcg_kp_EKCertificate DATA
+ asn1_oid_tcg_on_ekPermIdSha256 DATA
+ asn1_oid_tcg_tpm20 DATA
+ asn1_SAMFlags_units
+ asn1_TicketFlags_units
+ copy_AccessDescription
+ copy_AD_AND_OR
+ copy_AD_IF_RELEVANT
+ copy_AD_INITIAL_VERIFIED_CAS
+ copy_AD_KDCIssued
+ copy_AD_LoginAlias
+ copy_AD_MANDATORY_FOR_KDC
+ copy_AlgorithmIdentifier
+ copy_AliasIA5String
+ copy_AliasPrintableString
+ copy_AliasUTF8String
+ copy_APOptions
+ copy_AP_REP
+ copy_AP_REQ
+ copy_AS_REP
+ copy_AS_REQ
+ copy_Attribute
+ copy_AttributeSet
+ copy_AttributeType
+ copy_AttributeTypeAndValue
+ copy_AttributeValue
+ copy_AttributeValues
+ copy_AUTHDATA_TYPE
+ copy_Authenticator
+ copy_AuthorityInfoAccessSyntax
+ copy_AuthorityKeyIdentifier
+ copy_AuthorizationData
+ copy_AuthorizationDataElement
+ copy_AuthPack
+ copy_AuthPack_Win2k
+ copy_BaseDistance
+ copy_BasicConstraints
+ copy_Certificate
+ copy_CertificateList
+ copy_CertificatePolicies
+ copy_CertificateRevocationLists
+ copy_Certificates
+ copy_CertificateSerialNumber
+ copy_CertificateSet
+ copy_CertificationRequest
+ copy_CertificationRequestInfo
+ copy_CertPolicyId
+ copy_ChangePasswdDataMS
+ copy_Checksum
+ copy_CKSUMTYPE
+ copy_CMSAttributes
+ copy_CMSCBCParameter
+ copy_CMSEncryptedData
+ copy_CMSIdentifier
+ copy_CMSRC2CBCParameter
+ copy_CMSVersion
+ copy_CommonCriteriaMeasures
+ copy_CommunityIdentifier
+ copy_CommunityIdentifiers
+ copy_CompositePrincipal
+ copy_ContentEncryptionAlgorithmIdentifier
+ copy_ContentInfo
+ copy_ContentType
+ copy_CPSuri
+ copy_CRIAttributeSet
+ copy_CRIExtensions
+ copy_CRLCertificateList
+ copy_CRLDistributionPoints
+ copy_CRLReason
+ copy_CurrentFWConfig
+ copy_DecryptKeyIdentifier
+ copy_DHNonce
+ copy_DHParameter
+ copy_DHPublicKey
+ copy_DHRepInfo
+ copy_DigestAlgorithmIdentifier
+ copy_DigestAlgorithmIdentifiers
+ copy_DigestError
+ copy_DigestInfo
+ copy_DigestInit
+ copy_DigestInitReply
+ copy_DigestREP
+ copy_DigestRepInner
+ copy_DigestREQ
+ copy_DigestReqInner
+ copy_DigestRequest
+ copy_DigestResponse
+ copy_DigestTypes
+ copy_DirectoryString
+ copy_DisplayText
+ copy_DistributionPoint
+ copy_DistributionPointName
+ copy_DistributionPointReasonFlags
+ copy_DomainParameters
+ copy_DSAParams
+ copy_DSAPublicKey
+ copy_DSASigValue
+ copy_ECDSA_Sig_Value
+ copy_ECParameters
+ copy_ECPoint
+ copy_EKCertificateGenerationLocation
+ copy_EKGenerationLocation
+ copy_EKGenerationType
+ copy_EncAPRepPart
+ copy_EncapsulatedContentInfo
+ copy_EncASRepPart
+ copy_EncKDCRepPart
+ copy_EncKrbCredPart
+ copy_EncKrbPrivPart
+ copy_EncryptedContent
+ copy_EncryptedContentInfo
+ copy_EncryptedData
+ copy_EncryptedKey
+ copy_EncryptionKey
+ copy_EncTGSRepPart
+ copy_EncTicketPart
+ copy_ENCTYPE
+ copy_EnvelopedData
+ copy_ETYPE_INFO
+ copy_ETYPE_INFO2
+ copy_ETYPE_INFO2_ENTRY
+ copy_ETYPE_INFO_ENTRY
+ copy_EtypeList
+ copy_EvaluationAssuranceLevel
+ copy_EvaluationStatus
+ copy_Extension
+ copy_Extensions
+ copy_ExternalPrincipalIdentifier
+ copy_ExternalPrincipalIdentifiers
+ copy_ExtKeyUsage
+ copy_FastOptions
+ copy_FIPSLevel
+ copy_FirmwarePackageIdentifier
+ copy_FirmwarePackageInfo
+ copy_FirmwarePackageLoadError
+ copy_FirmwarePackageLoadErrorCode
+ copy_FirmwarePackageLoadReceipt
+ copy_FirmwarePkgData
+ copy_FWErrorVersion
+ copy_FWReceiptVersion
+ copy_GeneralName
+ copy_GeneralNames
+ copy_GeneralSubtree
+ copy_GeneralSubtrees
+ copy_HardwareModuleName
+ copy_HardwareModules
+ copy_HardwareSerialEntry
+ copy_heim_any
+ copy_HEIM_ANY
+ copy_heim_any_set
+ copy_HEIM_ANY_SET
+ copy_HostAddress
+ copy_HostAddresses
+ copy_ImplementedCompressAlgorithms
+ copy_ImplementedCryptoAlgorithms
+ copy_IOSCertificationRequest
+ copy_IOSCertificationRequestInfo
+ copy_IssuerAndSerialNumber
+ copy_KDCDHKeyInfo
+ copy_KDCDHKeyInfo_Win2k
+ copy_KDCFastCookie
+ copy_KDCFastFlags
+ copy_KDCFastState
+ copy_KDCOptions
+ copy_KDC_PROXY_MESSAGE
+ copy_KDC_REP
+ copy_KDC_REQ
+ copy_KDC_REQ_BODY
+ copy_KDFAlgorithmId
+ copy_KERB_AD_RESTRICTION_ENTRY
+ copy_KERB_ARMOR_SERVICE_REPLY
+ copy_KERB_CRED
+ copy_KerberosString
+ copy_KerberosTime
+ copy_KERB_TGS_REP_IN
+ copy_KERB_TGS_REP_OUT
+ copy_KERB_TGS_REQ_IN
+ copy_KERB_TGS_REQ_OUT
+ copy_KERB_TIMES
+ copy_KeyEncryptionAlgorithmIdentifier
+ copy_KeyIdentifier
+ copy_KeyTransRecipientInfo
+ copy_KeyUsage
+ copy_Krb5Int32
+ copy_KRB5PrincipalName
+ copy_Krb5UInt32
+ copy_KRB_CRED
+ copy_KrbCredInfo
+ copy_KRB_ERROR
+ copy_KrbFastArmor
+ copy_KrbFastArmoredRep
+ copy_KrbFastArmoredReq
+ copy_KrbFastFinished
+ copy_KrbFastReq
+ copy_KrbFastResponse
+ copy_KRB_PRIV
+ copy_KRB_SAFE
+ copy_KRB_SAFE_BODY
+ copy_Kx509CSRPlus
+ copy_Kx509ErrorCode
+ copy_KX509_ERROR_CODE
+ copy_Kx509Request
+ copy_Kx509Response
+ copy_LastReq
+ copy_LR_TYPE
+ copy_MessageDigest
+ copy_MESSAGE_TYPE
+ copy_METHOD_DATA
+ copy_MS_UPN_SAN
+ copy_Name
+ copy_NameConstraints
+ copy_NAME_TYPE
+ copy_NoticeReference
+ copy_NTLMInit
+ copy_NTLMInitReply
+ copy_NTLMReply
+ copy_NTLMRequest
+ copy_NTLMRequest2
+ copy_NTLMResponse
+ copy_OCSPBasicOCSPResponse
+ copy_OCSPCertID
+ copy_OCSPCertStatus
+ copy_OCSPInnerRequest
+ copy_OCSPKeyHash
+ copy_OCSPRequest
+ copy_OCSPResponderID
+ copy_OCSPResponse
+ copy_OCSPResponseBytes
+ copy_OCSPResponseData
+ copy_OCSPResponseStatus
+ copy_OCSPSignature
+ copy_OCSPSingleResponse
+ copy_OCSPTBSRequest
+ copy_OCSPVersion
+ copy_OriginatorInfo
+ copy_OtherName
+ copy_PA_DATA
+ copy_PADATA_TYPE
+ copy_PA_ENC_SAM_RESPONSE_ENC
+ copy_PA_ENC_TS_ENC
+ copy_PA_FX_FAST_REPLY
+ copy_PA_FX_FAST_REQUEST
+ copy_PA_KERB_KEY_LIST_REP
+ copy_PA_KERB_KEY_LIST_REQ
+ copy_PA_PAC_OPTIONS
+ copy_PA_PAC_REQUEST
+ copy_PA_PK_AS_REP
+ copy_PA_PK_AS_REP_BTMM
+ copy_PA_PK_AS_REP_Win2k
+ copy_PA_PK_AS_REQ
+ copy_PA_PK_AS_REQ_Win2k
+ copy_PA_S4U_X509_USER
+ copy_PA_S4U2Self
+ copy_PA_SAM_CHALLENGE_2
+ copy_PA_SAM_CHALLENGE_2_BODY
+ copy_PA_SAM_REDIRECT
+ copy_PA_SAM_RESPONSE_2
+ copy_PA_SAM_TYPE
+ copy_PA_ServerReferralData
+ copy_PA_SERVER_REFERRAL_DATA
+ copy_PA_SvrReferralData
+ copy_PermanentIdentifier
+ copy_PKAuthenticator
+ copy_PKAuthenticator_Win2k
+ copy_PKCS12_Attribute
+ copy_PKCS12_Attributes
+ copy_PKCS12_AuthenticatedSafe
+ copy_PKCS12_CertBag
+ copy_PKCS12_MacData
+ copy_PKCS12_OctetString
+ copy_PKCS12_PBEParams
+ copy_PKCS12_PFX
+ copy_PKCS12_SafeBag
+ copy_PKCS12_SafeContents
+ copy_PKCS8Attributes
+ copy_PKCS8EncryptedData
+ copy_PKCS8EncryptedPrivateKeyInfo
+ copy_PKCS8PrivateKey
+ copy_PKCS8PrivateKeyAlgorithmIdentifier
+ copy_PKCS8PrivateKeyInfo
+ copy_PKCS9_BMPString
+ copy_PKCS9_friendlyName
+ copy_PkinitSP80056AOtherInfo
+ copy_PkinitSuppPubInfo
+ copy_PKIXXmppAddr
+ copy_PolicyConstraints
+ copy_PolicyInformation
+ copy_PolicyMapping
+ copy_PolicyMappings
+ copy_PolicyQualifierId
+ copy_PolicyQualifierInfo
+ copy_PolicyQualifierInfos
+ copy_PreferredOrLegacyPackageIdentifier
+ copy_PreferredOrLegacyStalePackageIdentifier
+ copy_PreferredPackageIdentifier
+ copy_Principal
+ copy_PrincipalName
+ copy_Principals
+ copy_PrivateKeyUsagePeriod
+ copy_PROV_SRV_LOCATION
+ copy_ProxyCertInfo
+ copy_ProxyPolicy
+ copy_RDNSequence
+ copy_Realm
+ copy_RecipientIdentifier
+ copy_RecipientInfo
+ copy_RecipientInfos
+ copy_RelativeDistinguishedName
+ copy_ReplyKeyPack
+ copy_ReplyKeyPack_Win2k
+ copy_RSAPrivateKey
+ copy_RSAPublicKey
+ copy_SAMFlags
+ copy_SecurityLevel
+ copy_SignatureAlgorithmIdentifier
+ copy_SignatureValue
+ copy_SignedData
+ copy_SignerIdentifier
+ copy_SignerInfo
+ copy_SignerInfos
+ copy_SingleAttribute
+ copy_SkipCerts
+ copy_SRVName
+ copy_StrengthOfFunction
+ copy_SubjectDirectoryAttributes
+ copy_SubjectInfoAccessSyntax
+ copy_SubjectKeyIdentifier
+ copy_SubjectPublicKeyInfo
+ copy_TargetHardwareIdentifiers
+ copy_TBSCertificate
+ copy_TBSCRLCertList
+ copy_TD_DH_PARAMETERS
+ copy_TD_INVALID_CERTIFICATES
+ copy_TD_TRUSTED_CERTIFIERS
+ copy_TGS_REP
+ copy_TGS_REQ
+ copy_Ticket
+ copy_TicketFlags
+ copy_Time
+ copy_TPMSecurityAssertions
+ copy_TPMSpecification
+ copy_TPMVersion
+ copy_TransitedEncoding
+ copy_TrustedCA
+ copy_TrustedCA_Win2k
+ copy_TypedData
+ copy_TYPED_DATA
+ copy_UniqueIdentifier
+ copy_UnprotectedAttributes
+ copy_URIReference
+ copy_UserNotice
+ copy_ValidationParms
+ copy_Validity
+ copy_VendorLoadErrorCode
+ copy_Version
+ copy_WrappedFirmwareKey
+ copy_X520CommonName
+ copy_X520LocalityName
+ copy_X520name
+ copy_X520OrganizationalUnitName
+ copy_X520OrganizationName
+ copy_X520StateOrProvinceName
+ copy_X690SampleChildInformation
+ copy_X690SampleDate
+ copy_X690SampleEmployeeNumber
+ copy_X690SampleName
+ copy_X690SamplePersonnelRecord
+ decode_AccessDescription
+ decode_AD_AND_OR
+ decode_AD_IF_RELEVANT
+ decode_AD_INITIAL_VERIFIED_CAS
+ decode_AD_KDCIssued
+ decode_AD_LoginAlias
+ decode_AD_MANDATORY_FOR_KDC
+ decode_AlgorithmIdentifier
+ decode_AliasIA5String
+ decode_AliasPrintableString
+ decode_AliasUTF8String
+ decode_APOptions
+ decode_AP_REP
+ decode_AP_REQ
+ decode_AS_REP
+ decode_AS_REQ
+ decode_Attribute
+ decode_AttributeSet
+ decode_AttributeType
+ decode_AttributeTypeAndValue
+ decode_AttributeValue
+ decode_AttributeValues
+ decode_AUTHDATA_TYPE
+ decode_Authenticator
+ decode_AuthorityInfoAccessSyntax
+ decode_AuthorityKeyIdentifier
+ decode_AuthorizationData
+ decode_AuthorizationDataElement
+ decode_AuthPack
+ decode_AuthPack_Win2k
+ decode_BaseDistance
+ decode_BasicConstraints
+ decode_Certificate
+ decode_CertificateList
+ decode_CertificatePolicies
+ decode_CertificateRevocationLists
+ decode_Certificates
+ decode_CertificateSerialNumber
+ decode_CertificateSet
+ decode_CertificationRequest
+ decode_CertificationRequestInfo
+ decode_CertPolicyId
+ decode_ChangePasswdDataMS
+ decode_Checksum
+ decode_CKSUMTYPE
+ decode_CMSAttributes
+ decode_CMSCBCParameter
+ decode_CMSEncryptedData
+ decode_CMSIdentifier
+ decode_CMSRC2CBCParameter
+ decode_CMSVersion
+ decode_CommonCriteriaMeasures
+ decode_CommunityIdentifier
+ decode_CommunityIdentifiers
+ decode_CompositePrincipal
+ decode_ContentEncryptionAlgorithmIdentifier
+ decode_ContentInfo
+ decode_ContentType
+ decode_CPSuri
+ decode_CRIAttributeSet
+ decode_CRIExtensions
+ decode_CRIExtensions
+ decode_CRLCertificateList
+ decode_CRLDistributionPoints
+ decode_CRLReason
+ decode_CurrentFWConfig
+ decode_DecryptKeyIdentifier
+ decode_DHNonce
+ decode_DHParameter
+ decode_DHPublicKey
+ decode_DHRepInfo
+ decode_DigestAlgorithmIdentifier
+ decode_DigestAlgorithmIdentifiers
+ decode_DigestError
+ decode_DigestInfo
+ decode_DigestInit
+ decode_DigestInitReply
+ decode_DigestREP
+ decode_DigestRepInner
+ decode_DigestREQ
+ decode_DigestReqInner
+ decode_DigestRequest
+ decode_DigestResponse
+ decode_DigestTypes
+ decode_DirectoryString
+ decode_DisplayText
+ decode_DistributionPoint
+ decode_DistributionPointName
+ decode_DistributionPointReasonFlags
+ decode_DomainParameters
+ decode_DSAParams
+ decode_DSAPublicKey
+ decode_DSASigValue
+ decode_ECDSA_Sig_Value
+ decode_ECParameters
+ decode_ECPoint
+ decode_EKCertificateGenerationLocation
+ decode_EKGenerationLocation
+ decode_EKGenerationType
+ decode_EncAPRepPart
+ decode_EncapsulatedContentInfo
+ decode_EncASRepPart
+ decode_EncKDCRepPart
+ decode_EncKrbCredPart
+ decode_EncKrbPrivPart
+ decode_EncryptedContent
+ decode_EncryptedContentInfo
+ decode_EncryptedData
+ decode_EncryptedKey
+ decode_EncryptionKey
+ decode_EncTGSRepPart
+ decode_EncTicketPart
+ decode_ENCTYPE
+ decode_EnvelopedData
+ decode_ETYPE_INFO
+ decode_ETYPE_INFO2
+ decode_ETYPE_INFO2_ENTRY
+ decode_ETYPE_INFO_ENTRY
+ decode_EtypeList
+ decode_EvaluationAssuranceLevel
+ decode_EvaluationStatus
+ decode_Extension
+ decode_Extensions
+ decode_ExternalPrincipalIdentifier
+ decode_ExternalPrincipalIdentifiers
+ decode_ExtKeyUsage
+ decode_FastOptions
+ decode_FIPSLevel
+ decode_FirmwarePackageIdentifier
+ decode_FirmwarePackageInfo
+ decode_FirmwarePackageLoadError
+ decode_FirmwarePackageLoadErrorCode
+ decode_FirmwarePackageLoadReceipt
+ decode_FirmwarePkgData
+ decode_FWErrorVersion
+ decode_FWReceiptVersion
+ decode_GeneralName
+ decode_GeneralNames
+ decode_GeneralSubtree
+ decode_GeneralSubtrees
+ decode_HardwareModuleName
+ decode_HardwareModules
+ decode_HardwareSerialEntry
+ decode_heim_any
+ decode_HEIM_ANY
+ decode_heim_any_set
+ decode_HEIM_ANY_SET
+ decode_HostAddress
+ decode_HostAddresses
+ decode_ImplementedCompressAlgorithms
+ decode_ImplementedCryptoAlgorithms
+ decode_IOSCertificationRequest
+ decode_IOSCertificationRequest
+ decode_IOSCertificationRequestInfo
+ decode_IOSCertificationRequestInfo
+ decode_IssuerAndSerialNumber
+ decode_KDCDHKeyInfo
+ decode_KDCDHKeyInfo_Win2k
+ decode_KDCFastCookie
+ decode_KDCFastFlags
+ decode_KDCFastState
+ decode_KDCOptions
+ decode_KDC_PROXY_MESSAGE
+ decode_KDC_REP
+ decode_KDC_REQ
+ decode_KDC_REQ_BODY
+ decode_KDFAlgorithmId
+ decode_KERB_AD_RESTRICTION_ENTRY
+ decode_KERB_ARMOR_SERVICE_REPLY
+ decode_KERB_CRED
+ decode_KerberosString
+ decode_KerberosTime
+ decode_KERB_TGS_REP_IN
+ decode_KERB_TGS_REP_OUT
+ decode_KERB_TGS_REQ_IN
+ decode_KERB_TGS_REQ_OUT
+ decode_KERB_TIMES
+ decode_KeyEncryptionAlgorithmIdentifier
+ decode_KeyIdentifier
+ decode_KeyTransRecipientInfo
+ decode_KeyUsage
+ decode_Krb5Int32
+ decode_KRB5PrincipalName
+ decode_Krb5UInt32
+ decode_KRB_CRED
+ decode_KrbCredInfo
+ decode_KRB_ERROR
+ decode_KrbFastArmor
+ decode_KrbFastArmoredRep
+ decode_KrbFastArmoredReq
+ decode_KrbFastFinished
+ decode_KrbFastReq
+ decode_KrbFastResponse
+ decode_KRB_PRIV
+ decode_KRB_SAFE
+ decode_KRB_SAFE_BODY
+ decode_Kx509CSRPlus
+ decode_Kx509ErrorCode
+ decode_KX509_ERROR_CODE
+ decode_Kx509Request
+ decode_Kx509Response
+ decode_LastReq
+ decode_LR_TYPE
+ decode_MessageDigest
+ decode_MESSAGE_TYPE
+ decode_METHOD_DATA
+ decode_MS_UPN_SAN
+ decode_Name
+ decode_NameConstraints
+ decode_NAME_TYPE
+ decode_NoticeReference
+ decode_NTLMInit
+ decode_NTLMInitReply
+ decode_NTLMReply
+ decode_NTLMRequest
+ decode_NTLMRequest2
+ decode_NTLMResponse
+ decode_OCSPBasicOCSPResponse
+ decode_OCSPCertID
+ decode_OCSPCertStatus
+ decode_OCSPInnerRequest
+ decode_OCSPKeyHash
+ decode_OCSPRequest
+ decode_OCSPResponderID
+ decode_OCSPResponse
+ decode_OCSPResponseBytes
+ decode_OCSPResponseData
+ decode_OCSPResponseStatus
+ decode_OCSPSignature
+ decode_OCSPSingleResponse
+ decode_OCSPTBSRequest
+ decode_OCSPVersion
+ decode_OriginatorInfo
+ decode_OtherName
+ decode_PA_DATA
+ decode_PADATA_TYPE
+ decode_PA_ENC_SAM_RESPONSE_ENC
+ decode_PA_ENC_TS_ENC
+ decode_PA_FX_FAST_REPLY
+ decode_PA_FX_FAST_REQUEST
+ decode_PA_KERB_KEY_LIST_REP
+ decode_PA_KERB_KEY_LIST_REQ
+ decode_PA_PAC_OPTIONS
+ decode_PA_PAC_REQUEST
+ decode_PA_PK_AS_REP
+ decode_PA_PK_AS_REP_BTMM
+ decode_PA_PK_AS_REP_Win2k
+ decode_PA_PK_AS_REQ
+ decode_PA_PK_AS_REQ_Win2k
+ decode_PA_S4U_X509_USER
+ decode_PA_S4U2Self
+ decode_PA_SAM_CHALLENGE_2
+ decode_PA_SAM_CHALLENGE_2_BODY
+ decode_PA_SAM_REDIRECT
+ decode_PA_SAM_RESPONSE_2
+ decode_PA_SAM_TYPE
+ decode_PA_ServerReferralData
+ decode_PA_SERVER_REFERRAL_DATA
+ decode_PA_SvrReferralData
+ decode_PermanentIdentifier
+ decode_PKAuthenticator
+ decode_PKAuthenticator_Win2k
+ decode_PKCS12_Attribute
+ decode_PKCS12_Attributes
+ decode_PKCS12_AuthenticatedSafe
+ decode_PKCS12_CertBag
+ decode_PKCS12_MacData
+ decode_PKCS12_OctetString
+ decode_PKCS12_PBEParams
+ decode_PKCS12_PFX
+ decode_PKCS12_SafeBag
+ decode_PKCS12_SafeContents
+ decode_PKCS8Attributes
+ decode_PKCS8EncryptedData
+ decode_PKCS8EncryptedPrivateKeyInfo
+ decode_PKCS8PrivateKey
+ decode_PKCS8PrivateKeyAlgorithmIdentifier
+ decode_PKCS8PrivateKeyInfo
+ decode_PKCS9_BMPString
+ decode_PKCS9_friendlyName
+ decode_PkinitSP80056AOtherInfo
+ decode_PkinitSuppPubInfo
+ decode_PKIXXmppAddr
+ decode_PolicyConstraints
+ decode_PolicyInformation
+ decode_PolicyMapping
+ decode_PolicyMappings
+ decode_PolicyQualifierId
+ decode_PolicyQualifierInfo
+ decode_PolicyQualifierInfos
+ decode_PreferredOrLegacyPackageIdentifier
+ decode_PreferredOrLegacyStalePackageIdentifier
+ decode_PreferredPackageIdentifier
+ decode_Principal
+ decode_PrincipalName
+ decode_Principals
+ decode_PrivateKeyUsagePeriod
+ decode_PROV_SRV_LOCATION
+ decode_ProxyCertInfo
+ decode_ProxyPolicy
+ decode_RDNSequence
+ decode_Realm
+ decode_RecipientIdentifier
+ decode_RecipientInfo
+ decode_RecipientInfos
+ decode_RelativeDistinguishedName
+ decode_ReplyKeyPack
+ decode_ReplyKeyPack_Win2k
+ decode_RSAPrivateKey
+ decode_RSAPublicKey
+ decode_SAMFlags
+ decode_SecurityLevel
+ decode_SignatureAlgorithmIdentifier
+ decode_SignatureValue
+ decode_SignedData
+ decode_SignerIdentifier
+ decode_SignerInfo
+ decode_SignerInfos
+ decode_SingleAttribute
+ decode_SkipCerts
+ decode_SRVName
+ decode_StrengthOfFunction
+ decode_SubjectDirectoryAttributes
+ decode_SubjectInfoAccessSyntax
+ decode_SubjectKeyIdentifier
+ decode_SubjectPublicKeyInfo
+ decode_TargetHardwareIdentifiers
+ decode_TBSCertificate
+ decode_TBSCRLCertList
+ decode_TD_DH_PARAMETERS
+ decode_TD_INVALID_CERTIFICATES
+ decode_TD_TRUSTED_CERTIFIERS
+ decode_TGS_REP
+ decode_TGS_REQ
+ decode_Ticket
+ decode_TicketFlags
+ decode_Time
+ decode_TPMSecurityAssertions
+ decode_TPMSpecification
+ decode_TPMVersion
+ decode_TransitedEncoding
+ decode_TrustedCA
+ decode_TrustedCA_Win2k
+ decode_TypedData
+ decode_TYPED_DATA
+ decode_UniqueIdentifier
+ decode_UnprotectedAttributes
+ decode_URIReference
+ decode_UserNotice
+ decode_ValidationParms
+ decode_Validity
+ decode_VendorLoadErrorCode
+ decode_Version
+ decode_WrappedFirmwareKey
+ decode_X520CommonName
+ decode_X520LocalityName
+ decode_X520name
+ decode_X520OrganizationalUnitName
+ decode_X520OrganizationName
+ decode_X520StateOrProvinceName
+ decode_X690SampleChildInformation
+ decode_X690SampleDate
+ decode_X690SampleEmployeeNumber
+ decode_X690SampleName
+ decode_X690SamplePersonnelRecord
+ der_copy_bit_string
+ der_copy_bmp_string
+ der_copy_generalized_time
+ der_copy_general_string
+ der_copy_heim_integer
+ der_copy_ia5_string
+ der_copy_integer
+ der_copy_integer64
+ der_copy_octet_string
+ der_copy_oid
+ der_copy_printable_string
+ der_copy_universal_string
+ der_copy_unsigned
+ der_copy_unsigned64
+ der_copy_utctime
+ der_copy_utf8string
+ der_copy_visible_string
+ der_find_heim_oid_by_name
+ der_find_heim_oid_by_oid
+ der_find_or_parse_heim_oid
+ der_free_bit_string
+ der_free_bmp_string
+ der_free_generalized_time
+ der_free_general_string
+ der_free_heim_integer
+ der_free_ia5_string
+ der_free_integer
+ der_free_integer64
+ der_free_octet_string
+ der_free_oid
+ der_free_printable_string
+ der_free_universal_string
+ der_free_unsigned
+ der_free_unsigned64
+ der_free_utctime
+ der_free_utf8string
+ der_free_visible_string
+ der_get_bit_string
+ der_get_bmp_string
+ der_get_boolean
+ der_get_class_name
+ der_get_class_num
+ der_get_generalized_time
+ der_get_general_string
+ der_get_heim_integer
+ der_get_ia5_string
+ der_get_integer
+ der_get_integer64
+ der_get_length
+ der_get_octet_string
+ der_get_octet_string_ber
+ der_get_oid
+ der_get_printable_string
+ der_get_tag
+ der_get_tag_name
+ der_get_tag_num
+ der_get_type_name
+ der_get_type_num
+ der_get_universal_string
+ der_get_unsigned
+ der_get_unsigned64
+ der_get_utctime
+ der_get_utf8string
+ der_get_visible_string
+ _der_gmtime
+ der_heim_bit_string_cmp
+ der_heim_bmp_string_cmp
+ der_heim_integer_cmp
+ der_heim_octet_string_cmp
+ der_heim_oid_cmp
+ der_heim_universal_string_cmp
+ der_ia5_string_cmp
+ der_length_bit_string
+ der_length_bmp_string
+ der_length_boolean
+ der_length_enumerated
+ der_length_generalized_time
+ der_length_general_string
+ der_length_heim_integer
+ der_length_ia5_string
+ der_length_integer
+ der_length_integer64
+ der_length_len
+ der_length_octet_string
+ der_length_oid
+ der_length_printable_string
+ der_length_tag
+ der_length_universal_string
+ der_length_unsigned
+ der_length_unsigned64
+ der_length_utctime
+ der_length_utf8string
+ der_length_visible_string
+ der_match_heim_oid_by_name
+ der_match_tag
+ der_match_tag2
+ der_match_tag_and_length
+ der_parse_heim_oid
+ der_parse_hex_heim_integer
+ der_printable_string_cmp
+ der_print_bit_string
+ der_print_bmp_string
+ der_print_boolean
+ der_print_generalized_time
+ der_print_general_string
+ der_print_heim_integer
+ der_print_heim_oid
+ der_print_heim_oid_sym
+ der_print_hex_heim_integer
+ der_print_ia5_string
+ der_print_integer
+ der_print_integer64
+ der_print_octet_string
+ der_print_oid
+ der_print_printable_string
+ der_print_universal_string
+ der_print_unsigned
+ der_print_unsigned64
+ der_print_utctime
+ der_print_utf8string
+ der_print_visible_string
+ der_put_bit_string
+ der_put_bmp_string
+ der_put_boolean
+ der_put_generalized_time
+ der_put_general_string
+ der_put_heim_integer
+ der_put_ia5_string
+ der_put_integer
+ der_put_integer64
+ der_put_length
+ der_put_length_and_tag
+ der_put_octet_string
+ der_put_oid
+ der_put_printable_string
+ der_put_tag
+ der_put_universal_string
+ der_put_unsigned
+ der_put_unsigned64
+ der_put_utctime
+ der_put_utf8string
+ der_put_visible_string
+ der_replace_tag
+ _der_timegm
+ DigestTypes2int
+ DistributionPointReasonFlags2int
+ encode_AccessDescription
+ encode_AD_AND_OR
+ encode_AD_IF_RELEVANT
+ encode_AD_INITIAL_VERIFIED_CAS
+ encode_AD_KDCIssued
+ encode_AD_LoginAlias
+ encode_AD_MANDATORY_FOR_KDC
+ encode_AlgorithmIdentifier
+ encode_AliasIA5String
+ encode_AliasPrintableString
+ encode_AliasUTF8String
+ encode_APOptions
+ encode_AP_REP
+ encode_AP_REQ
+ encode_AS_REP
+ encode_AS_REQ
+ encode_Attribute
+ encode_AttributeSet
+ encode_AttributeType
+ encode_AttributeTypeAndValue
+ encode_AttributeValue
+ encode_AttributeValues
+ encode_AUTHDATA_TYPE
+ encode_Authenticator
+ encode_AuthorityInfoAccessSyntax
+ encode_AuthorityKeyIdentifier
+ encode_AuthorizationData
+ encode_AuthorizationDataElement
+ encode_AuthPack
+ encode_AuthPack_Win2k
+ encode_BaseDistance
+ encode_BasicConstraints
+ encode_Certificate
+ encode_CertificateList
+ encode_CertificatePolicies
+ encode_CertificateRevocationLists
+ encode_Certificates
+ encode_CertificateSerialNumber
+ encode_CertificateSet
+ encode_CertificationRequest
+ encode_CertificationRequestInfo
+ encode_CertPolicyId
+ encode_ChangePasswdDataMS
+ encode_Checksum
+ encode_CKSUMTYPE
+ encode_CMSAttributes
+ encode_CMSCBCParameter
+ encode_CMSEncryptedData
+ encode_CMSIdentifier
+ encode_CMSRC2CBCParameter
+ encode_CMSVersion
+ encode_CommonCriteriaMeasures
+ encode_CommunityIdentifier
+ encode_CommunityIdentifiers
+ encode_CompositePrincipal
+ encode_ContentEncryptionAlgorithmIdentifier
+ encode_ContentInfo
+ encode_ContentType
+ encode_CPSuri
+ encode_CRIAttributeSet
+ encode_CRIExtensions
+ encode_CRIExtensions
+ encode_CRLCertificateList
+ encode_CRLDistributionPoints
+ encode_CRLReason
+ encode_CurrentFWConfig
+ encode_DecryptKeyIdentifier
+ encode_DHNonce
+ encode_DHParameter
+ encode_DHPublicKey
+ encode_DHRepInfo
+ encode_DigestAlgorithmIdentifier
+ encode_DigestAlgorithmIdentifiers
+ encode_DigestError
+ encode_DigestInfo
+ encode_DigestInit
+ encode_DigestInitReply
+ encode_DigestREP
+ encode_DigestRepInner
+ encode_DigestREQ
+ encode_DigestReqInner
+ encode_DigestRequest
+ encode_DigestResponse
+ encode_DigestTypes
+ encode_DirectoryString
+ encode_DisplayText
+ encode_DistributionPoint
+ encode_DistributionPointName
+ encode_DistributionPointReasonFlags
+ encode_DomainParameters
+ encode_DSAParams
+ encode_DSAPublicKey
+ encode_DSASigValue
+ encode_ECDSA_Sig_Value
+ encode_ECParameters
+ encode_ECPoint
+ encode_EKCertificateGenerationLocation
+ encode_EKGenerationLocation
+ encode_EKGenerationType
+ encode_EncAPRepPart
+ encode_EncapsulatedContentInfo
+ encode_EncASRepPart
+ encode_EncKDCRepPart
+ encode_EncKrbCredPart
+ encode_EncKrbPrivPart
+ encode_EncryptedContent
+ encode_EncryptedContentInfo
+ encode_EncryptedData
+ encode_EncryptedKey
+ encode_EncryptionKey
+ encode_EncTGSRepPart
+ encode_EncTicketPart
+ encode_ENCTYPE
+ encode_EnvelopedData
+ encode_ETYPE_INFO
+ encode_ETYPE_INFO2
+ encode_ETYPE_INFO2_ENTRY
+ encode_ETYPE_INFO_ENTRY
+ encode_EtypeList
+ encode_EvaluationAssuranceLevel
+ encode_EvaluationStatus
+ encode_Extension
+ encode_Extensions
+ encode_ExternalPrincipalIdentifier
+ encode_ExternalPrincipalIdentifiers
+ encode_ExtKeyUsage
+ encode_FastOptions
+ encode_FIPSLevel
+ encode_FirmwarePackageIdentifier
+ encode_FirmwarePackageInfo
+ encode_FirmwarePackageLoadError
+ encode_FirmwarePackageLoadErrorCode
+ encode_FirmwarePackageLoadReceipt
+ encode_FirmwarePkgData
+ encode_FWErrorVersion
+ encode_FWReceiptVersion
+ encode_GeneralName
+ encode_GeneralNames
+ encode_GeneralSubtree
+ encode_GeneralSubtrees
+ encode_HardwareModuleName
+ encode_HardwareModules
+ encode_HardwareSerialEntry
+ encode_heim_any
+ encode_HEIM_ANY
+ encode_heim_any_set
+ encode_HEIM_ANY_SET
+ encode_HostAddress
+ encode_HostAddresses
+ encode_ImplementedCompressAlgorithms
+ encode_ImplementedCryptoAlgorithms
+ encode_IOSCertificationRequest
+ encode_IOSCertificationRequest
+ encode_IOSCertificationRequestInfo
+ encode_IOSCertificationRequestInfo
+ encode_IssuerAndSerialNumber
+ encode_KDCDHKeyInfo
+ encode_KDCDHKeyInfo_Win2k
+ encode_KDCFastCookie
+ encode_KDCFastFlags
+ encode_KDCFastState
+ encode_KDCOptions
+ encode_KDC_PROXY_MESSAGE
+ encode_KDC_REP
+ encode_KDC_REQ
+ encode_KDC_REQ_BODY
+ encode_KDFAlgorithmId
+ encode_KERB_AD_RESTRICTION_ENTRY
+ encode_KERB_ARMOR_SERVICE_REPLY
+ encode_KERB_CRED
+ encode_KerberosString
+ encode_KerberosTime
+ encode_KERB_TGS_REP_IN
+ encode_KERB_TGS_REP_OUT
+ encode_KERB_TGS_REQ_IN
+ encode_KERB_TGS_REQ_OUT
+ encode_KERB_TIMES
+ encode_KeyEncryptionAlgorithmIdentifier
+ encode_KeyIdentifier
+ encode_KeyTransRecipientInfo
+ encode_KeyUsage
+ encode_Krb5Int32
+ encode_KRB5PrincipalName
+ encode_Krb5UInt32
+ encode_KRB_CRED
+ encode_KrbCredInfo
+ encode_KRB_ERROR
+ encode_KrbFastArmor
+ encode_KrbFastArmoredRep
+ encode_KrbFastArmoredReq
+ encode_KrbFastFinished
+ encode_KrbFastReq
+ encode_KrbFastResponse
+ encode_KRB_PRIV
+ encode_KRB_SAFE
+ encode_KRB_SAFE_BODY
+ encode_Kx509CSRPlus
+ encode_Kx509ErrorCode
+ encode_KX509_ERROR_CODE
+ encode_Kx509Request
+ encode_Kx509Response
+ encode_LastReq
+ encode_LR_TYPE
+ encode_MessageDigest
+ encode_MESSAGE_TYPE
+ encode_METHOD_DATA
+ encode_MS_UPN_SAN
+ encode_Name
+ encode_NameConstraints
+ encode_NAME_TYPE
+ encode_NoticeReference
+ encode_NTLMInit
+ encode_NTLMInitReply
+ encode_NTLMReply
+ encode_NTLMRequest
+ encode_NTLMRequest2
+ encode_NTLMResponse
+ encode_OCSPBasicOCSPResponse
+ encode_OCSPCertID
+ encode_OCSPCertStatus
+ encode_OCSPInnerRequest
+ encode_OCSPKeyHash
+ encode_OCSPRequest
+ encode_OCSPResponderID
+ encode_OCSPResponse
+ encode_OCSPResponseBytes
+ encode_OCSPResponseData
+ encode_OCSPResponseStatus
+ encode_OCSPSignature
+ encode_OCSPSingleResponse
+ encode_OCSPTBSRequest
+ encode_OCSPVersion
+ encode_OriginatorInfo
+ encode_OtherName
+ encode_PA_DATA
+ encode_PADATA_TYPE
+ encode_PA_ENC_SAM_RESPONSE_ENC
+ encode_PA_ENC_TS_ENC
+ encode_PA_FX_FAST_REPLY
+ encode_PA_FX_FAST_REQUEST
+ encode_PA_KERB_KEY_LIST_REP
+ encode_PA_KERB_KEY_LIST_REQ
+ encode_PA_PAC_OPTIONS
+ encode_PA_PAC_REQUEST
+ encode_PA_PK_AS_REP
+ encode_PA_PK_AS_REP_BTMM
+ encode_PA_PK_AS_REP_Win2k
+ encode_PA_PK_AS_REQ
+ encode_PA_PK_AS_REQ_Win2k
+ encode_PA_S4U_X509_USER
+ encode_PA_S4U2Self
+ encode_PA_SAM_CHALLENGE_2
+ encode_PA_SAM_CHALLENGE_2_BODY
+ encode_PA_SAM_REDIRECT
+ encode_PA_SAM_RESPONSE_2
+ encode_PA_SAM_TYPE
+ encode_PA_ServerReferralData
+ encode_PA_SERVER_REFERRAL_DATA
+ encode_PA_SvrReferralData
+ encode_PermanentIdentifier
+ encode_PKAuthenticator
+ encode_PKAuthenticator_Win2k
+ encode_PKCS12_Attribute
+ encode_PKCS12_Attributes
+ encode_PKCS12_AuthenticatedSafe
+ encode_PKCS12_CertBag
+ encode_PKCS12_MacData
+ encode_PKCS12_OctetString
+ encode_PKCS12_PBEParams
+ encode_PKCS12_PFX
+ encode_PKCS12_SafeBag
+ encode_PKCS12_SafeContents
+ encode_PKCS8Attributes
+ encode_PKCS8EncryptedData
+ encode_PKCS8EncryptedPrivateKeyInfo
+ encode_PKCS8PrivateKey
+ encode_PKCS8PrivateKeyAlgorithmIdentifier
+ encode_PKCS8PrivateKeyInfo
+ encode_PKCS9_BMPString
+ encode_PKCS9_friendlyName
+ encode_PkinitSP80056AOtherInfo
+ encode_PkinitSuppPubInfo
+ encode_PKIXXmppAddr
+ encode_PolicyConstraints
+ encode_PolicyInformation
+ encode_PolicyMapping
+ encode_PolicyMappings
+ encode_PolicyQualifierId
+ encode_PolicyQualifierInfo
+ encode_PolicyQualifierInfos
+ encode_PreferredOrLegacyPackageIdentifier
+ encode_PreferredOrLegacyStalePackageIdentifier
+ encode_PreferredPackageIdentifier
+ encode_Principal
+ encode_PrincipalName
+ encode_Principals
+ encode_PrivateKeyUsagePeriod
+ encode_PROV_SRV_LOCATION
+ encode_ProxyCertInfo
+ encode_ProxyPolicy
+ encode_RDNSequence
+ encode_Realm
+ encode_RecipientIdentifier
+ encode_RecipientInfo
+ encode_RecipientInfos
+ encode_RelativeDistinguishedName
+ encode_ReplyKeyPack
+ encode_ReplyKeyPack_Win2k
+ encode_RSAPrivateKey
+ encode_RSAPublicKey
+ encode_SAMFlags
+ encode_SecurityLevel
+ encode_SignatureAlgorithmIdentifier
+ encode_SignatureValue
+ encode_SignedData
+ encode_SignerIdentifier
+ encode_SignerInfo
+ encode_SignerInfos
+ encode_SingleAttribute
+ encode_SkipCerts
+ encode_SRVName
+ encode_StrengthOfFunction
+ encode_SubjectDirectoryAttributes
+ encode_SubjectInfoAccessSyntax
+ encode_SubjectKeyIdentifier
+ encode_SubjectPublicKeyInfo
+ encode_TargetHardwareIdentifiers
+ encode_TBSCertificate
+ encode_TBSCRLCertList
+ encode_TD_DH_PARAMETERS
+ encode_TD_INVALID_CERTIFICATES
+ encode_TD_TRUSTED_CERTIFIERS
+ encode_TGS_REP
+ encode_TGS_REQ
+ encode_Ticket
+ encode_TicketFlags
+ encode_Time
+ encode_TPMSecurityAssertions
+ encode_TPMSpecification
+ encode_TPMVersion
+ encode_TransitedEncoding
+ encode_TrustedCA
+ encode_TrustedCA_Win2k
+ encode_TypedData
+ encode_TYPED_DATA
+ encode_UniqueIdentifier
+ encode_UnprotectedAttributes
+ encode_URIReference
+ encode_UserNotice
+ encode_ValidationParms
+ encode_Validity
+ encode_VendorLoadErrorCode
+ encode_Version
+ encode_WrappedFirmwareKey
+ encode_X520CommonName
+ encode_X520LocalityName
+ encode_X520name
+ encode_X520OrganizationalUnitName
+ encode_X520OrganizationName
+ encode_X520StateOrProvinceName
+ encode_X690SampleChildInformation
+ encode_X690SampleDate
+ encode_X690SampleEmployeeNumber
+ encode_X690SampleName
+ encode_X690SamplePersonnelRecord
+ FastOptions2int
+ free_AccessDescription
+ free_AD_AND_OR
+ free_AD_IF_RELEVANT
+ free_AD_INITIAL_VERIFIED_CAS
+ free_AD_KDCIssued
+ free_AD_LoginAlias
+ free_AD_MANDATORY_FOR_KDC
+ free_AlgorithmIdentifier
+ free_AliasIA5String
+ free_AliasPrintableString
+ free_AliasUTF8String
+ free_APOptions
+ free_AP_REP
+ free_AP_REQ
+ free_AS_REP
+ free_AS_REQ
+ free_Attribute
+ free_AttributeSet
+ free_AttributeType
+ free_AttributeTypeAndValue
+ free_AttributeValue
+ free_AttributeValues
+ free_AUTHDATA_TYPE
+ free_Authenticator
+ free_AuthorityInfoAccessSyntax
+ free_AuthorityKeyIdentifier
+ free_AuthorizationData
+ free_AuthorizationDataElement
+ free_AuthPack
+ free_AuthPack_Win2k
+ free_BaseDistance
+ free_BasicConstraints
+ free_Certificate
+ free_CertificateList
+ free_CertificatePolicies
+ free_CertificateRevocationLists
+ free_Certificates
+ free_CertificateSerialNumber
+ free_CertificateSet
+ free_CertificationRequest
+ free_CertificationRequestInfo
+ free_CertPolicyId
+ free_ChangePasswdDataMS
+ free_Checksum
+ free_CKSUMTYPE
+ free_CMSAttributes
+ free_CMSCBCParameter
+ free_CMSEncryptedData
+ free_CMSIdentifier
+ free_CMSRC2CBCParameter
+ free_CMSVersion
+ free_CommonCriteriaMeasures
+ free_CommunityIdentifier
+ free_CommunityIdentifiers
+ free_CompositePrincipal
+ free_ContentEncryptionAlgorithmIdentifier
+ free_ContentInfo
+ free_ContentType
+ free_CPSuri
+ free_CRIAttributeSet
+ free_CRIExtensions
+ free_CRIExtensions
+ free_CRLCertificateList
+ free_CRLDistributionPoints
+ free_CRLReason
+ free_CurrentFWConfig
+ free_DecryptKeyIdentifier
+ free_DHNonce
+ free_DHParameter
+ free_DHPublicKey
+ free_DHRepInfo
+ free_DigestAlgorithmIdentifier
+ free_DigestAlgorithmIdentifiers
+ free_DigestError
+ free_DigestInfo
+ free_DigestInit
+ free_DigestInitReply
+ free_DigestREP
+ free_DigestRepInner
+ free_DigestREQ
+ free_DigestReqInner
+ free_DigestRequest
+ free_DigestResponse
+ free_DigestTypes
+ free_DirectoryString
+ free_DisplayText
+ free_DistributionPoint
+ free_DistributionPointName
+ free_DistributionPointReasonFlags
+ free_DomainParameters
+ free_DSAParams
+ free_DSAPublicKey
+ free_DSASigValue
+ free_ECDSA_Sig_Value
+ free_ECParameters
+ free_ECPoint
+ free_EKCertificateGenerationLocation
+ free_EKGenerationLocation
+ free_EKGenerationType
+ free_EncAPRepPart
+ free_EncapsulatedContentInfo
+ free_EncASRepPart
+ free_EncKDCRepPart
+ free_EncKrbCredPart
+ free_EncKrbPrivPart
+ free_EncryptedContent
+ free_EncryptedContentInfo
+ free_EncryptedData
+ free_EncryptedKey
+ free_EncryptionKey
+ free_EncTGSRepPart
+ free_EncTicketPart
+ free_ENCTYPE
+ free_EnvelopedData
+ free_ETYPE_INFO
+ free_ETYPE_INFO2
+ free_ETYPE_INFO2_ENTRY
+ free_ETYPE_INFO_ENTRY
+ free_EtypeList
+ free_EvaluationAssuranceLevel
+ free_EvaluationStatus
+ free_Extension
+ free_Extensions
+ free_ExternalPrincipalIdentifier
+ free_ExternalPrincipalIdentifiers
+ free_ExtKeyUsage
+ free_FastOptions
+ free_FIPSLevel
+ free_FirmwarePackageIdentifier
+ free_FirmwarePackageInfo
+ free_FirmwarePackageLoadError
+ free_FirmwarePackageLoadErrorCode
+ free_FirmwarePackageLoadReceipt
+ free_FirmwarePkgData
+ free_FWErrorVersion
+ free_FWReceiptVersion
+ free_GeneralName
+ free_GeneralNames
+ free_GeneralSubtree
+ free_GeneralSubtrees
+ free_HardwareModuleName
+ free_HardwareModules
+ free_HardwareSerialEntry
+ free_heim_any
+ free_HEIM_ANY
+ free_heim_any_set
+ free_HEIM_ANY_SET
+ free_HostAddress
+ free_HostAddresses
+ free_ImplementedCompressAlgorithms
+ free_ImplementedCryptoAlgorithms
+ free_IOSCertificationRequest
+ free_IOSCertificationRequest
+ free_IOSCertificationRequestInfo
+ free_IOSCertificationRequestInfo
+ free_IssuerAndSerialNumber
+ free_KDCDHKeyInfo
+ free_KDCDHKeyInfo_Win2k
+ free_KDCFastCookie
+ free_KDCFastFlags
+ free_KDCFastState
+ free_KDCOptions
+ free_KDC_PROXY_MESSAGE
+ free_KDC_REP
+ free_KDC_REQ
+ free_KDC_REQ_BODY
+ free_KDFAlgorithmId
+ free_KERB_AD_RESTRICTION_ENTRY
+ free_KERB_ARMOR_SERVICE_REPLY
+ free_KERB_CRED
+ free_KerberosString
+ free_KerberosTime
+ free_KERB_TGS_REP_IN
+ free_KERB_TGS_REP_OUT
+ free_KERB_TGS_REQ_IN
+ free_KERB_TGS_REQ_OUT
+ free_KERB_TIMES
+ free_KeyEncryptionAlgorithmIdentifier
+ free_KeyIdentifier
+ free_KeyTransRecipientInfo
+ free_KeyUsage
+ free_Krb5Int32
+ free_KRB5PrincipalName
+ free_Krb5UInt32
+ free_KRB_CRED
+ free_KrbCredInfo
+ free_KRB_ERROR
+ free_KrbFastArmor
+ free_KrbFastArmoredRep
+ free_KrbFastArmoredReq
+ free_KrbFastFinished
+ free_KrbFastReq
+ free_KrbFastResponse
+ free_KRB_PRIV
+ free_KRB_SAFE
+ free_KRB_SAFE_BODY
+ free_Kx509CSRPlus
+ free_Kx509ErrorCode
+ free_KX509_ERROR_CODE
+ free_Kx509Request
+ free_Kx509Response
+ free_LastReq
+ free_LR_TYPE
+ free_MessageDigest
+ free_MESSAGE_TYPE
+ free_METHOD_DATA
+ free_MS_UPN_SAN
+ free_Name
+ free_NameConstraints
+ free_NAME_TYPE
+ free_NoticeReference
+ free_NTLMInit
+ free_NTLMInitReply
+ free_NTLMReply
+ free_NTLMRequest
+ free_NTLMRequest2
+ free_NTLMResponse
+ free_OCSPBasicOCSPResponse
+ free_OCSPCertID
+ free_OCSPCertStatus
+ free_OCSPInnerRequest
+ free_OCSPKeyHash
+ free_OCSPRequest
+ free_OCSPResponderID
+ free_OCSPResponse
+ free_OCSPResponseBytes
+ free_OCSPResponseData
+ free_OCSPResponseStatus
+ free_OCSPSignature
+ free_OCSPSingleResponse
+ free_OCSPTBSRequest
+ free_OCSPVersion
+ free_OriginatorInfo
+ free_OtherName
+ free_PA_DATA
+ free_PADATA_TYPE
+ free_PA_ENC_SAM_RESPONSE_ENC
+ free_PA_ENC_TS_ENC
+ free_PA_FX_FAST_REPLY
+ free_PA_FX_FAST_REQUEST
+ free_PA_KERB_KEY_LIST_REP
+ free_PA_KERB_KEY_LIST_REQ
+ free_PA_PAC_OPTIONS
+ free_PA_PAC_REQUEST
+ free_PA_PK_AS_REP
+ free_PA_PK_AS_REP_BTMM
+ free_PA_PK_AS_REP_Win2k
+ free_PA_PK_AS_REQ
+ free_PA_PK_AS_REQ_Win2k
+ free_PA_S4U_X509_USER
+ free_PA_S4U2Self
+ free_PA_SAM_CHALLENGE_2
+ free_PA_SAM_CHALLENGE_2_BODY
+ free_PA_SAM_REDIRECT
+ free_PA_SAM_RESPONSE_2
+ free_PA_SAM_TYPE
+ free_PA_ServerReferralData
+ free_PA_SERVER_REFERRAL_DATA
+ free_PA_SvrReferralData
+ free_PermanentIdentifier
+ free_PKAuthenticator
+ free_PKAuthenticator_Win2k
+ free_PKCS12_Attribute
+ free_PKCS12_Attributes
+ free_PKCS12_AuthenticatedSafe
+ free_PKCS12_CertBag
+ free_PKCS12_MacData
+ free_PKCS12_OctetString
+ free_PKCS12_PBEParams
+ free_PKCS12_PFX
+ free_PKCS12_SafeBag
+ free_PKCS12_SafeContents
+ free_PKCS8Attributes
+ free_PKCS8EncryptedData
+ free_PKCS8EncryptedPrivateKeyInfo
+ free_PKCS8PrivateKey
+ free_PKCS8PrivateKeyAlgorithmIdentifier
+ free_PKCS8PrivateKeyInfo
+ free_PKCS9_BMPString
+ free_PKCS9_friendlyName
+ free_PkinitSP80056AOtherInfo
+ free_PkinitSuppPubInfo
+ free_PKIXXmppAddr
+ free_PolicyConstraints
+ free_PolicyInformation
+ free_PolicyMapping
+ free_PolicyMappings
+ free_PolicyQualifierId
+ free_PolicyQualifierInfo
+ free_PolicyQualifierInfos
+ free_PreferredOrLegacyPackageIdentifier
+ free_PreferredOrLegacyStalePackageIdentifier
+ free_PreferredPackageIdentifier
+ free_Principal
+ free_PrincipalName
+ free_Principals
+ free_PrivateKeyUsagePeriod
+ free_PROV_SRV_LOCATION
+ free_ProxyCertInfo
+ free_ProxyPolicy
+ free_RDNSequence
+ free_Realm
+ free_RecipientIdentifier
+ free_RecipientInfo
+ free_RecipientInfos
+ free_RelativeDistinguishedName
+ free_ReplyKeyPack
+ free_ReplyKeyPack_Win2k
+ free_RSAPrivateKey
+ free_RSAPublicKey
+ free_SAMFlags
+ free_SecurityLevel
+ free_SignatureAlgorithmIdentifier
+ free_SignatureValue
+ free_SignedData
+ free_SignerIdentifier
+ free_SignerInfo
+ free_SignerInfos
+ free_SingleAttribute
+ free_SkipCerts
+ free_SRVName
+ free_StrengthOfFunction
+ free_SubjectDirectoryAttributes
+ free_SubjectInfoAccessSyntax
+ free_SubjectKeyIdentifier
+ free_SubjectPublicKeyInfo
+ free_TargetHardwareIdentifiers
+ free_TBSCertificate
+ free_TBSCRLCertList
+ free_TD_DH_PARAMETERS
+ free_TD_INVALID_CERTIFICATES
+ free_TD_TRUSTED_CERTIFIERS
+ free_TGS_REP
+ free_TGS_REQ
+ free_Ticket
+ free_TicketFlags
+ free_Time
+ free_TPMSecurityAssertions
+ free_TPMSpecification
+ free_TPMVersion
+ free_TransitedEncoding
+ free_TrustedCA
+ free_TrustedCA_Win2k
+ free_TypedData
+ free_TYPED_DATA
+ free_UniqueIdentifier
+ free_UnprotectedAttributes
+ free_URIReference
+ free_UserNotice
+ free_ValidationParms
+ free_Validity
+ free_VendorLoadErrorCode
+ free_Version
+ free_WrappedFirmwareKey
+ free_X520CommonName
+ free_X520LocalityName
+ free_X520name
+ free_X520OrganizationalUnitName
+ free_X520OrganizationName
+ free_X520StateOrProvinceName
+ free_X690SampleChildInformation
+ free_X690SampleDate
+ free_X690SampleEmployeeNumber
+ free_X690SampleName
+ free_X690SamplePersonnelRecord
+ heim_any_cmp
+ HEIM_ANY_cmp
+ _heim_der_set_sort
+ _heim_fix_dce
+ _heim_len_int
+ _heim_len_int64
+ _heim_len_unsigned
+ _heim_len_unsigned64
+ _heim_time2generalizedtime
+ initialize_asn1_error_table
+ initialize_asn1_error_table_r
+ int2APOptions
+ int2DigestTypes
+ int2DistributionPointReasonFlags
+ int2FastOptions
+ int2KDCFastFlags
+ int2KDCOptions
+ int2KeyUsage
+ int2SAMFlags
+ int2TicketFlags
+ KDCFastFlags2int
+ KDCOptions2int
+ KeyUsage2int
+ length_AccessDescription
+ length_AD_AND_OR
+ length_AD_IF_RELEVANT
+ length_AD_INITIAL_VERIFIED_CAS
+ length_AD_KDCIssued
+ length_AD_LoginAlias
+ length_AD_MANDATORY_FOR_KDC
+ length_AlgorithmIdentifier
+ length_AliasIA5String
+ length_AliasPrintableString
+ length_AliasUTF8String
+ length_APOptions
+ length_AP_REP
+ length_AP_REQ
+ length_AS_REP
+ length_AS_REQ
+ length_Attribute
+ length_AttributeSet
+ length_AttributeType
+ length_AttributeTypeAndValue
+ length_AttributeValue
+ length_AttributeValues
+ length_AUTHDATA_TYPE
+ length_Authenticator
+ length_AuthorityInfoAccessSyntax
+ length_AuthorityKeyIdentifier
+ length_AuthorizationData
+ length_AuthorizationDataElement
+ length_AuthPack
+ length_AuthPack_Win2k
+ length_BaseDistance
+ length_BasicConstraints
+ length_Certificate
+ length_CertificateList
+ length_CertificatePolicies
+ length_CertificateRevocationLists
+ length_Certificates
+ length_CertificateSerialNumber
+ length_CertificateSet
+ length_CertificationRequest
+ length_CertificationRequestInfo
+ length_CertPolicyId
+ length_ChangePasswdDataMS
+ length_Checksum
+ length_CKSUMTYPE
+ length_CMSAttributes
+ length_CMSCBCParameter
+ length_CMSEncryptedData
+ length_CMSIdentifier
+ length_CMSRC2CBCParameter
+ length_CMSVersion
+ length_CommonCriteriaMeasures
+ length_CommunityIdentifier
+ length_CommunityIdentifiers
+ length_CompositePrincipal
+ length_ContentEncryptionAlgorithmIdentifier
+ length_ContentInfo
+ length_ContentType
+ length_CPSuri
+ length_CRIAttributeSet
+ length_CRIExtensions
+ length_CRLCertificateList
+ length_CRLDistributionPoints
+ length_CRLReason
+ length_CurrentFWConfig
+ length_DecryptKeyIdentifier
+ length_DHNonce
+ length_DHParameter
+ length_DHPublicKey
+ length_DHRepInfo
+ length_DigestAlgorithmIdentifier
+ length_DigestAlgorithmIdentifiers
+ length_DigestError
+ length_DigestInfo
+ length_DigestInit
+ length_DigestInitReply
+ length_DigestREP
+ length_DigestRepInner
+ length_DigestREQ
+ length_DigestReqInner
+ length_DigestRequest
+ length_DigestResponse
+ length_DigestTypes
+ length_DirectoryString
+ length_DisplayText
+ length_DistributionPoint
+ length_DistributionPointName
+ length_DistributionPointReasonFlags
+ length_DomainParameters
+ length_DSAParams
+ length_DSAPublicKey
+ length_DSASigValue
+ length_ECDSA_Sig_Value
+ length_ECParameters
+ length_ECPoint
+ length_EKCertificateGenerationLocation
+ length_EKGenerationLocation
+ length_EKGenerationType
+ length_EncAPRepPart
+ length_EncapsulatedContentInfo
+ length_EncASRepPart
+ length_EncKDCRepPart
+ length_EncKrbCredPart
+ length_EncKrbPrivPart
+ length_EncryptedContent
+ length_EncryptedContentInfo
+ length_EncryptedData
+ length_EncryptedKey
+ length_EncryptionKey
+ length_EncTGSRepPart
+ length_EncTicketPart
+ length_ENCTYPE
+ length_EnvelopedData
+ length_ETYPE_INFO
+ length_ETYPE_INFO2
+ length_ETYPE_INFO2_ENTRY
+ length_ETYPE_INFO_ENTRY
+ length_EtypeList
+ length_EvaluationAssuranceLevel
+ length_EvaluationStatus
+ length_Extension
+ length_Extensions
+ length_ExternalPrincipalIdentifier
+ length_ExternalPrincipalIdentifiers
+ length_ExtKeyUsage
+ length_FastOptions
+ length_FIPSLevel
+ length_FirmwarePackageIdentifier
+ length_FirmwarePackageInfo
+ length_FirmwarePackageLoadError
+ length_FirmwarePackageLoadErrorCode
+ length_FirmwarePackageLoadReceipt
+ length_FirmwarePkgData
+ length_FWErrorVersion
+ length_FWReceiptVersion
+ length_GeneralName
+ length_GeneralNames
+ length_GeneralSubtree
+ length_GeneralSubtrees
+ length_HardwareModuleName
+ length_HardwareModules
+ length_HardwareSerialEntry
+ length_heim_any
+ length_HEIM_ANY
+ length_heim_any_set
+ length_HEIM_ANY_SET
+ length_HostAddress
+ length_HostAddresses
+ length_ImplementedCompressAlgorithms
+ length_ImplementedCryptoAlgorithms
+ length_IOSCertificationRequest
+ length_IOSCertificationRequestInfo
+ length_IssuerAndSerialNumber
+ length_KDCDHKeyInfo
+ length_KDCDHKeyInfo_Win2k
+ length_KDCFastCookie
+ length_KDCFastFlags
+ length_KDCFastState
+ length_KDCOptions
+ length_KDC_PROXY_MESSAGE
+ length_KDC_REP
+ length_KDC_REQ
+ length_KDC_REQ_BODY
+ length_KDFAlgorithmId
+ length_KERB_AD_RESTRICTION_ENTRY
+ length_KERB_ARMOR_SERVICE_REPLY
+ length_KERB_CRED
+ length_KerberosString
+ length_KerberosTime
+ length_KERB_TGS_REP_IN
+ length_KERB_TGS_REP_OUT
+ length_KERB_TGS_REQ_IN
+ length_KERB_TGS_REQ_OUT
+ length_KERB_TIMES
+ length_KeyEncryptionAlgorithmIdentifier
+ length_KeyIdentifier
+ length_KeyTransRecipientInfo
+ length_KeyUsage
+ length_Krb5Int32
+ length_KRB5PrincipalName
+ length_Krb5UInt32
+ length_KRB_CRED
+ length_KrbCredInfo
+ length_KRB_ERROR
+ length_KrbFastArmor
+ length_KrbFastArmoredRep
+ length_KrbFastArmoredReq
+ length_KrbFastFinished
+ length_KrbFastReq
+ length_KrbFastResponse
+ length_KRB_PRIV
+ length_KRB_SAFE
+ length_KRB_SAFE_BODY
+ length_Kx509CSRPlus
+ length_Kx509ErrorCode
+ length_KX509_ERROR_CODE
+ length_Kx509Request
+ length_Kx509Response
+ length_LastReq
+ length_LR_TYPE
+ length_MessageDigest
+ length_MESSAGE_TYPE
+ length_METHOD_DATA
+ length_MS_UPN_SAN
+ length_Name
+ length_NameConstraints
+ length_NAME_TYPE
+ length_NoticeReference
+ length_NTLMInit
+ length_NTLMInitReply
+ length_NTLMReply
+ length_NTLMRequest
+ length_NTLMRequest2
+ length_NTLMResponse
+ length_OCSPBasicOCSPResponse
+ length_OCSPCertID
+ length_OCSPCertStatus
+ length_OCSPInnerRequest
+ length_OCSPKeyHash
+ length_OCSPRequest
+ length_OCSPResponderID
+ length_OCSPResponse
+ length_OCSPResponseBytes
+ length_OCSPResponseData
+ length_OCSPResponseStatus
+ length_OCSPSignature
+ length_OCSPSingleResponse
+ length_OCSPTBSRequest
+ length_OCSPVersion
+ length_OriginatorInfo
+ length_OtherName
+ length_PA_DATA
+ length_PADATA_TYPE
+ length_PA_ENC_SAM_RESPONSE_ENC
+ length_PA_ENC_TS_ENC
+ length_PA_FX_FAST_REPLY
+ length_PA_FX_FAST_REQUEST
+ length_PA_KERB_KEY_LIST_REP
+ length_PA_KERB_KEY_LIST_REQ
+ length_PA_PAC_OPTIONS
+ length_PA_PAC_REQUEST
+ length_PA_PK_AS_REP
+ length_PA_PK_AS_REP_BTMM
+ length_PA_PK_AS_REP_Win2k
+ length_PA_PK_AS_REQ
+ length_PA_PK_AS_REQ_Win2k
+ length_PA_S4U_X509_USER
+ length_PA_S4U2Self
+ length_PA_SAM_CHALLENGE_2
+ length_PA_SAM_CHALLENGE_2_BODY
+ length_PA_SAM_REDIRECT
+ length_PA_SAM_RESPONSE_2
+ length_PA_SAM_TYPE
+ length_PA_ServerReferralData
+ length_PA_SERVER_REFERRAL_DATA
+ length_PA_SvrReferralData
+ length_PermanentIdentifier
+ length_PKAuthenticator
+ length_PKAuthenticator_Win2k
+ length_PKCS12_Attribute
+ length_PKCS12_Attributes
+ length_PKCS12_AuthenticatedSafe
+ length_PKCS12_CertBag
+ length_PKCS12_MacData
+ length_PKCS12_OctetString
+ length_PKCS12_PBEParams
+ length_PKCS12_PFX
+ length_PKCS12_SafeBag
+ length_PKCS12_SafeContents
+ length_PKCS8Attributes
+ length_PKCS8EncryptedData
+ length_PKCS8EncryptedPrivateKeyInfo
+ length_PKCS8PrivateKey
+ length_PKCS8PrivateKeyAlgorithmIdentifier
+ length_PKCS8PrivateKeyInfo
+ length_PKCS9_BMPString
+ length_PKCS9_friendlyName
+ length_PkinitSP80056AOtherInfo
+ length_PkinitSuppPubInfo
+ length_PKIXXmppAddr
+ length_PolicyConstraints
+ length_PolicyInformation
+ length_PolicyMapping
+ length_PolicyMappings
+ length_PolicyQualifierId
+ length_PolicyQualifierInfo
+ length_PolicyQualifierInfos
+ length_PreferredOrLegacyPackageIdentifier
+ length_PreferredOrLegacyStalePackageIdentifier
+ length_PreferredPackageIdentifier
+ length_Principal
+ length_PrincipalName
+ length_Principals
+ length_PrivateKeyUsagePeriod
+ length_PROV_SRV_LOCATION
+ length_ProxyCertInfo
+ length_ProxyPolicy
+ length_RDNSequence
+ length_Realm
+ length_RecipientIdentifier
+ length_RecipientInfo
+ length_RecipientInfos
+ length_RelativeDistinguishedName
+ length_ReplyKeyPack
+ length_ReplyKeyPack_Win2k
+ length_RSAPrivateKey
+ length_RSAPublicKey
+ length_SAMFlags
+ length_SecurityLevel
+ length_SignatureAlgorithmIdentifier
+ length_SignatureValue
+ length_SignedData
+ length_SignerIdentifier
+ length_SignerInfo
+ length_SignerInfos
+ length_SingleAttribute
+ length_SkipCerts
+ length_SRVName
+ length_StrengthOfFunction
+ length_SubjectDirectoryAttributes
+ length_SubjectInfoAccessSyntax
+ length_SubjectKeyIdentifier
+ length_SubjectPublicKeyInfo
+ length_TargetHardwareIdentifiers
+ length_TBSCertificate
+ length_TBSCRLCertList
+ length_TD_DH_PARAMETERS
+ length_TD_INVALID_CERTIFICATES
+ length_TD_TRUSTED_CERTIFIERS
+ length_TGS_REP
+ length_TGS_REQ
+ length_Ticket
+ length_TicketFlags
+ length_Time
+ length_TPMSecurityAssertions
+ length_TPMSpecification
+ length_TPMVersion
+ length_TransitedEncoding
+ length_TrustedCA
+ length_TrustedCA_Win2k
+ length_TypedData
+ length_TYPED_DATA
+ length_UniqueIdentifier
+ length_UnprotectedAttributes
+ length_URIReference
+ length_UserNotice
+ length_ValidationParms
+ length_Validity
+ length_VendorLoadErrorCode
+ length_Version
+ length_WrappedFirmwareKey
+ length_X520CommonName
+ length_X520LocalityName
+ length_X520name
+ length_X520OrganizationalUnitName
+ length_X520OrganizationName
+ length_X520StateOrProvinceName
+ length_X690SampleChildInformation
+ length_X690SampleDate
+ length_X690SampleEmployeeNumber
+ length_X690SampleName
+ length_X690SamplePersonnelRecord
+ print_AccessDescription
+ print_AD_AND_OR
+ print_AD_IF_RELEVANT
+ print_AD_INITIAL_VERIFIED_CAS
+ print_AD_KDCIssued
+ print_AD_LoginAlias
+ print_AD_MANDATORY_FOR_KDC
+ print_AlgorithmIdentifier
+ print_AliasIA5String
+ print_AliasPrintableString
+ print_AliasUTF8String
+ print_APOptions
+ print_AP_REP
+ print_AP_REQ
+ print_AS_REP
+ print_AS_REQ
+ print_Attribute
+ print_AttributeSet
+ print_AttributeType
+ print_AttributeTypeAndValue
+ print_AttributeValue
+ print_AttributeValues
+ print_AUTHDATA_TYPE
+ print_Authenticator
+ print_AuthorityInfoAccessSyntax
+ print_AuthorityKeyIdentifier
+ print_AuthorizationData
+ print_AuthorizationDataElement
+ print_AuthPack
+ print_AuthPack_Win2k
+ print_BaseDistance
+ print_BasicConstraints
+ print_Certificate
+ print_CertificateList
+ print_CertificatePolicies
+ print_CertificateRevocationLists
+ print_Certificates
+ print_CertificateSerialNumber
+ print_CertificateSet
+ print_CertificationRequest
+ print_CertificationRequestInfo
+ print_CertPolicyId
+ print_ChangePasswdDataMS
+ print_Checksum
+ print_CKSUMTYPE
+ print_CMSAttributes
+ print_CMSCBCParameter
+ print_CMSEncryptedData
+ print_CMSIdentifier
+ print_CMSRC2CBCParameter
+ print_CMSVersion
+ print_CommonCriteriaMeasures
+ print_CommunityIdentifier
+ print_CommunityIdentifiers
+ print_CompositePrincipal
+ print_ContentEncryptionAlgorithmIdentifier
+ print_ContentInfo
+ print_ContentType
+ print_CPSuri
+ print_CRIAttributeSet
+ print_CRIExtensions
+ print_CRIExtensions
+ print_CRLCertificateList
+ print_CRLDistributionPoints
+ print_CRLReason
+ print_CurrentFWConfig
+ print_DecryptKeyIdentifier
+ print_DHNonce
+ print_DHParameter
+ print_DHPublicKey
+ print_DHRepInfo
+ print_DigestAlgorithmIdentifier
+ print_DigestAlgorithmIdentifiers
+ print_DigestError
+ print_DigestInfo
+ print_DigestInit
+ print_DigestInitReply
+ print_DigestREP
+ print_DigestRepInner
+ print_DigestREQ
+ print_DigestReqInner
+ print_DigestRequest
+ print_DigestResponse
+ print_DigestTypes
+ print_DirectoryString
+ print_DisplayText
+ print_DistributionPoint
+ print_DistributionPointName
+ print_DistributionPointReasonFlags
+ print_DomainParameters
+ print_DSAParams
+ print_DSAPublicKey
+ print_DSASigValue
+ print_ECDSA_Sig_Value
+ print_ECParameters
+ print_ECPoint
+ print_EKCertificateGenerationLocation
+ print_EKGenerationLocation
+ print_EKGenerationType
+ print_EncAPRepPart
+ print_EncapsulatedContentInfo
+ print_EncASRepPart
+ print_EncKDCRepPart
+ print_EncKrbCredPart
+ print_EncKrbPrivPart
+ print_EncryptedContent
+ print_EncryptedContentInfo
+ print_EncryptedData
+ print_EncryptedKey
+ print_EncryptionKey
+ print_EncTGSRepPart
+ print_EncTicketPart
+ print_ENCTYPE
+ print_EnvelopedData
+ print_ETYPE_INFO
+ print_ETYPE_INFO2
+ print_ETYPE_INFO2_ENTRY
+ print_ETYPE_INFO_ENTRY
+ print_EtypeList
+ print_EvaluationAssuranceLevel
+ print_EvaluationStatus
+ print_Extension
+ print_Extensions
+ print_ExternalPrincipalIdentifier
+ print_ExternalPrincipalIdentifiers
+ print_ExtKeyUsage
+ print_FastOptions
+ print_FIPSLevel
+ print_FirmwarePackageIdentifier
+ print_FirmwarePackageInfo
+ print_FirmwarePackageLoadError
+ print_FirmwarePackageLoadErrorCode
+ print_FirmwarePackageLoadReceipt
+ print_FirmwarePkgData
+ print_FWErrorVersion
+ print_FWReceiptVersion
+ print_GeneralName
+ print_GeneralNames
+ print_GeneralSubtree
+ print_GeneralSubtrees
+ print_HardwareModuleName
+ print_HardwareModules
+ print_HardwareSerialEntry
+ print_heim_any
+ print_HEIM_ANY
+ print_heim_any_set
+ print_HEIM_ANY_SET
+ print_HostAddress
+ print_HostAddresses
+ print_ImplementedCompressAlgorithms
+ print_ImplementedCryptoAlgorithms
+ print_IOSCertificationRequest
+ print_IOSCertificationRequest
+ print_IOSCertificationRequestInfo
+ print_IOSCertificationRequestInfo
+ print_IssuerAndSerialNumber
+ print_KDCDHKeyInfo
+ print_KDCDHKeyInfo_Win2k
+ print_KDCFastCookie
+ print_KDCFastFlags
+ print_KDCFastState
+ print_KDCOptions
+ print_KDC_PROXY_MESSAGE
+ print_KDC_REP
+ print_KDC_REQ
+ print_KDC_REQ_BODY
+ print_KDFAlgorithmId
+ print_KERB_ARMOR_SERVICE_REPLY
+ print_KERB_CRED
+ print_KerberosString
+ print_KerberosTime
+ print_KERB_TGS_REP_IN
+ print_KERB_TGS_REP_OUT
+ print_KERB_TGS_REQ_IN
+ print_KERB_TGS_REQ_OUT
+ print_KERB_TIMES
+ print_KeyEncryptionAlgorithmIdentifier
+ print_KeyIdentifier
+ print_KeyTransRecipientInfo
+ print_KeyUsage
+ print_Krb5Int32
+ print_KRB5PrincipalName
+ print_Krb5UInt32
+ print_KRB_CRED
+ print_KrbCredInfo
+ print_KRB_ERROR
+ print_KrbFastArmor
+ print_KrbFastArmoredRep
+ print_KrbFastArmoredReq
+ print_KrbFastFinished
+ print_KrbFastReq
+ print_KrbFastResponse
+ print_KRB_PRIV
+ print_KRB_SAFE
+ print_KRB_SAFE_BODY
+ print_Kx509CSRPlus
+ print_Kx509ErrorCode
+ print_KX509_ERROR_CODE
+ print_Kx509Request
+ print_Kx509Response
+ print_LastReq
+ print_LR_TYPE
+ print_MessageDigest
+ print_MESSAGE_TYPE
+ print_METHOD_DATA
+ print_MS_UPN_SAN
+ print_Name
+ print_NameConstraints
+ print_NAME_TYPE
+ print_NoticeReference
+ print_NTLMInit
+ print_NTLMInitReply
+ print_NTLMReply
+ print_NTLMRequest
+ print_NTLMRequest2
+ print_NTLMResponse
+ print_OCSPBasicOCSPResponse
+ print_OCSPCertID
+ print_OCSPCertStatus
+ print_OCSPInnerRequest
+ print_OCSPKeyHash
+ print_OCSPRequest
+ print_OCSPResponderID
+ print_OCSPResponse
+ print_OCSPResponseBytes
+ print_OCSPResponseData
+ print_OCSPResponseStatus
+ print_OCSPSignature
+ print_OCSPSingleResponse
+ print_OCSPTBSRequest
+ print_OCSPVersion
+ print_OriginatorInfo
+ print_OtherName
+ print_PA_DATA
+ print_PADATA_TYPE
+ print_PA_ENC_SAM_RESPONSE_ENC
+ print_PA_ENC_TS_ENC
+ print_PA_FX_FAST_REPLY
+ print_PA_FX_FAST_REQUEST
+ print_PA_PAC_REQUEST
+ print_PA_PK_AS_REP
+ print_PA_PK_AS_REP_BTMM
+ print_PA_PK_AS_REP_Win2k
+ print_PA_PK_AS_REQ
+ print_PA_PK_AS_REQ_Win2k
+ print_PA_S4U2Self
+ print_PA_SAM_CHALLENGE_2
+ print_PA_SAM_CHALLENGE_2_BODY
+ print_PA_SAM_REDIRECT
+ print_PA_SAM_RESPONSE_2
+ print_PA_SAM_TYPE
+ print_PA_ServerReferralData
+ print_PA_SERVER_REFERRAL_DATA
+ print_PA_SvrReferralData
+ print_PermanentIdentifier
+ print_PKAuthenticator
+ print_PKAuthenticator_Win2k
+ print_PKCS12_Attribute
+ print_PKCS12_Attributes
+ print_PKCS12_AuthenticatedSafe
+ print_PKCS12_CertBag
+ print_PKCS12_MacData
+ print_PKCS12_OctetString
+ print_PKCS12_PBEParams
+ print_PKCS12_PFX
+ print_PKCS12_SafeBag
+ print_PKCS12_SafeContents
+ print_PKCS8Attributes
+ print_PKCS8EncryptedData
+ print_PKCS8EncryptedPrivateKeyInfo
+ print_PKCS8PrivateKey
+ print_PKCS8PrivateKeyAlgorithmIdentifier
+ print_PKCS8PrivateKeyInfo
+ print_PKCS9_BMPString
+ print_PKCS9_friendlyName
+ print_PkinitSP80056AOtherInfo
+ print_PkinitSuppPubInfo
+ print_PKIXXmppAddr
+ print_PolicyConstraints
+ print_PolicyInformation
+ print_PolicyMapping
+ print_PolicyMappings
+ print_PolicyQualifierId
+ print_PolicyQualifierInfo
+ print_PolicyQualifierInfos
+ print_PreferredOrLegacyPackageIdentifier
+ print_PreferredOrLegacyStalePackageIdentifier
+ print_PreferredPackageIdentifier
+ print_Principal
+ print_PrincipalName
+ print_Principals
+ print_PrivateKeyUsagePeriod
+ print_PROV_SRV_LOCATION
+ print_ProxyCertInfo
+ print_ProxyPolicy
+ print_RDNSequence
+ print_Realm
+ print_RecipientIdentifier
+ print_RecipientInfo
+ print_RecipientInfos
+ print_RelativeDistinguishedName
+ print_ReplyKeyPack
+ print_ReplyKeyPack_Win2k
+ print_RSAPrivateKey
+ print_RSAPublicKey
+ print_SAMFlags
+ print_SecurityLevel
+ print_SignatureAlgorithmIdentifier
+ print_SignatureValue
+ print_SignedData
+ print_SignerIdentifier
+ print_SignerInfo
+ print_SignerInfos
+ print_SingleAttribute
+ print_SkipCerts
+ print_SRVName
+ print_StrengthOfFunction
+ print_SubjectDirectoryAttributes
+ print_SubjectInfoAccessSyntax
+ print_SubjectKeyIdentifier
+ print_SubjectPublicKeyInfo
+ print_TargetHardwareIdentifiers
+ print_TBSCertificate
+ print_TBSCRLCertList
+ print_TD_DH_PARAMETERS
+ print_TD_INVALID_CERTIFICATES
+ print_TD_TRUSTED_CERTIFIERS
+ print_TGS_REP
+ print_TGS_REQ
+ print_Ticket
+ print_TicketFlags
+ print_Time
+ print_TPMSecurityAssertions
+ print_TPMSpecification
+ print_TPMVersion
+ print_TransitedEncoding
+ print_TrustedCA
+ print_TrustedCA_Win2k
+ print_TypedData
+ print_TYPED_DATA
+ print_UniqueIdentifier
+ print_UnprotectedAttributes
+ print_URIReference
+ print_UserNotice
+ print_ValidationParms
+ print_Validity
+ print_VendorLoadErrorCode
+ print_Version
+ print_WrappedFirmwareKey
+ print_X520CommonName
+ print_X520LocalityName
+ print_X520name
+ print_X520OrganizationalUnitName
+ print_X520OrganizationName
+ print_X520StateOrProvinceName
+ print_X690SampleChildInformation
+ print_X690SampleDate
+ print_X690SampleEmployeeNumber
+ print_X690SampleName
+ print_X690SamplePersonnelRecord
+ remove_AttributeValues
+ remove_AuthorizationData
+ remove_CertificatePolicies
+ remove_Certificates
+ remove_CRLDistributionPoints
+ remove_DigestAlgorithmIdentifiers
+ remove_ETYPE_INFO
+ remove_ETYPE_INFO2
+ remove_Extensions
+ remove_GeneralNames
+ remove_METHOD_DATA
+ remove_PolicyMappings
+ remove_PolicyQualifierInfos
+ remove_Principals
+ remove_RDNSequence
+ SAMFlags2int
+ TicketFlags2int
diff --git a/third_party/heimdal/lib/asn1/main.c b/third_party/heimdal/lib/asn1/main.c
new file mode 100644
index 0000000..bcfdad6
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/main.c
@@ -0,0 +1,487 @@
+/*
+ * Copyright (c) 1997-2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gen_locl.h"
+#include <getarg.h>
+#include "lex.h"
+
+extern FILE *yyin;
+
+static getarg_strings preserve;
+static getarg_strings seq;
+static getarg_strings decorate;
+
+static int
+strcmp4mergesort_r(const void *ap, const void *bp, void *d)
+{
+ const char *a = *(const char **)ap;
+ const char *b = *(const char **)bp;
+ char sep = *(const char *)d;
+ int cmp;
+
+ if (sep) {
+ const char *sepa = strchr(a, sep);
+ const char *sepb = strchr(b, sep);
+ size_t alen, blen;
+
+ if (sepa == NULL) sepa = a + strlen(a);
+ if (sepb == NULL) sepb = b + strlen(b);
+ alen = sepa - a;
+ blen = sepb - b;
+ cmp = strncmp(a, b, alen > blen ? alen : blen);
+ if (cmp == 0)
+ cmp = alen - blen;
+ } else
+ cmp = strcmp(a, b);
+ if (cmp == 0)
+ return (uintptr_t)ap - (uintptr_t)bp; /* stable sort */
+ return cmp;
+}
+
+static int
+prefix_check(const char *s, const char *p, size_t plen, char sep, int *cmp)
+{
+ if ((*cmp = strncmp(p, s, plen)) == 0 && s[plen] == sep)
+ return 1;
+ if (*cmp == 0)
+ *cmp = 1;
+ return 0;
+}
+
+static ssize_t
+bsearch_strings(struct getarg_strings *strs, const char *p,
+ char sep, ssize_t *more)
+{
+ ssize_t right = (ssize_t)strs->num_strings - 1;
+ ssize_t left = 0;
+ ssize_t plen = 0;
+ int cmp;
+
+ if (sep)
+ plen = strlen(p);
+
+ if (strs->num_strings == 0)
+ return -1;
+
+ if (sep && more && *more > -1) {
+ /* If *more > -1 we're continuing an iteration */
+ if (*more > right)
+ return -1;
+ if (prefix_check(strs->strings[*more], p, plen, sep, &cmp))
+ return (*more)++;
+ (*more)++;
+ return -1;
+ }
+
+ while (left <= right) {
+ ssize_t mid = left + (right - left) / 2;
+
+ if (sep) {
+ int cmp2;
+
+ while (prefix_check(strs->strings[mid], p, plen, sep, &cmp) &&
+ mid > 0 &&
+ prefix_check(strs->strings[mid - 1], p, plen, sep, &cmp2))
+ mid--;
+ } else
+ cmp = strcmp(p, strs->strings[mid]);
+ if (cmp == 0) {
+ if (more)
+ *more = mid + 1;
+ return mid;
+ }
+ if (cmp < 0)
+ right = mid - 1; /* -1 if `p' is smaller than smallest in strs */
+ else
+ left = mid + 1;
+ }
+ return -1;
+}
+
+int
+preserve_type(const char *p)
+{
+ return bsearch_strings(&preserve, p, '\0', 0) > -1;
+}
+
+int
+seq_type(const char *p)
+{
+ return bsearch_strings(&seq, p, '\0', 0) > -1;
+}
+
+/*
+ * Split `s' on `sep' and fill fs[] with pointers to the substrings.
+ *
+ * Only the first substring is to be freed -- the rest share the same
+ * allocation.
+ *
+ * The last element may contain `sep' chars if there are more fields in `s'
+ * than output locations in `fs[]'.
+ */
+static void
+split_str(const char *s, char sep, char ***fs)
+{
+ size_t i;
+
+ fs[0][0] = estrdup(s);
+ for (i = 1; fs[i]; i++) {
+ char *q;
+
+ if ((q = strchr(fs[i-1][0], sep)) == NULL)
+ break;
+ *(q++) = '\0';
+ fs[i][0] = q;
+ }
+ for (; fs[i]; i++)
+ fs[i][0] = NULL;
+}
+
+/*
+ * If `p' is "decorated" with a not-to-be-encoded-or-decoded field,
+ * output the field's typename and fieldname, whether it's optional, whether
+ * it's an ASN.1 type or an "external" type, and if external the names of
+ * functions to copy and free values of that type.
+ */
+int
+decorate_type(const char *p, struct decoration *deco, ssize_t *more)
+{
+ ssize_t i;
+ char **s[7];
+ char *junk = NULL;
+ char *cp;
+
+ deco->first = *more == -1;
+ deco->decorated = 0;
+ deco->field_type = NULL;
+ if ((i = bsearch_strings(&decorate, p, ':', more)) == -1)
+ return 0;
+
+ deco->decorated = 1;
+ deco->opt = deco->ext = deco->ptr = 0;
+ deco->void_star = deco->struct_star = 0;
+ deco->field_name = deco->copy_function_name = deco->free_function_name =
+ deco->header_name = NULL;
+
+ s[0] = &deco->field_type;
+ s[1] = &deco->field_name;
+ s[2] = &deco->copy_function_name;
+ s[3] = &deco->free_function_name;
+ s[4] = &deco->header_name;
+ s[5] = &junk;
+ s[6] = NULL;
+ split_str(decorate.strings[i] + strlen(p) + 1, ':', s);
+
+ if (junk || deco->field_type[0] == '\0' || !deco->field_name ||
+ deco->field_name[0] == '\0' || deco->field_name[0] == '?') {
+ errx(1, "Invalidate type decoration specification: --decorate=\"%s\"",
+ decorate.strings[i]);
+ }
+ if ((cp = strchr(deco->field_name, '?'))) {
+ deco->opt = 1;
+ *cp = '\0';
+ }
+ if (strcmp(deco->field_type, "void*") == 0 ||
+ strcmp(deco->field_type, "void *") == 0) {
+ deco->ext = deco->ptr = deco->void_star = 1;
+ deco->opt = 1;
+ deco->header_name = NULL;
+ } else if (strncmp(deco->field_type, "struct ", sizeof("struct ") - 1) == 0 &&
+ deco->field_type[strlen(deco->field_type) - 1] == '*')
+ deco->ptr = deco->struct_star = 1;
+ if (deco->ptr || deco->copy_function_name)
+ deco->ext = 1;
+ if (deco->ext && deco->copy_function_name && !deco->copy_function_name[0])
+ deco->copy_function_name = NULL;
+ if (deco->ext && deco->free_function_name && !deco->free_function_name[0])
+ deco->free_function_name = NULL;
+ if (deco->header_name && !deco->header_name[0])
+ deco->header_name = NULL;
+ if (deco->ptr)
+ deco->opt = 0;
+ return 1;
+}
+
+static const char *
+my_basename(const char *fn)
+{
+ const char *base, *p;
+
+ for (p = base = fn; *p; p++) {
+#ifdef WIN32
+ if (*p == '/' || *p == '\\')
+ base = p + 1;
+#else
+ if (*p == '/')
+ base = p + 1;
+#endif
+ }
+ return base;
+}
+
+const char *fuzzer_string = "";
+const char *enum_prefix;
+const char *name;
+int prefix_enum;
+int fuzzer_flag;
+int support_ber;
+int template_flag;
+int rfc1510_bitstring;
+int one_code_file;
+char *option_file;
+int parse_units_flag = 1;
+char *type_file_string = "krb5-types.h";
+int original_order;
+int version_flag;
+int help_flag;
+struct getargs args[] = {
+ { "fuzzer", 0, arg_flag, &fuzzer_flag, NULL, NULL },
+ { "template", 0, arg_flag, &template_flag, NULL, NULL },
+ { "prefix-enum", 0, arg_flag, &prefix_enum,
+ "prefix C enum labels for ENUMERATED types and INTEGER types with the "
+ "type's name", NULL },
+ { "enum-prefix", 0, arg_string, &enum_prefix,
+ "prefix for C enum labels for ENUMERATED types and INTEGER types with "
+ "enumerated values", "PREFIX" },
+ { "encode-rfc1510-bit-string", 0, arg_flag, &rfc1510_bitstring,
+ "Use RFC1510 incorrect BIT STRING handling for all BIT STRING types "
+ "in the module", NULL },
+ { "decode-dce-ber", 0, arg_flag, &support_ber,
+ "Allow DCE-style BER on decode", NULL },
+ { "support-ber", 0, arg_flag, &support_ber, "Allow BER on decode", NULL },
+ { "preserve-binary", 0, arg_strings, &preserve,
+ "Names of types for which to generate _save fields, saving original "
+ "encoding, in containing structures (useful for signature "
+ "verification)", "TYPE" },
+ { "sequence", 0, arg_strings, &seq,
+ "Generate add/remove functions for SEQUENCE OF types", "TYPE" },
+ { "decorate", 0, arg_strings, &decorate,
+ "Generate private field for SEQUENCE/SET type", "DECORATION" },
+ { "one-code-file", 0, arg_flag, &one_code_file, NULL, NULL },
+ { "gen-name", 0, arg_string, &name,
+ "Name of generated module", "NAME" },
+ { "option-file", 0, arg_string, &option_file,
+ "File with additional compiler CLI options", "FILE" },
+ { "original-order", 0, arg_flag, &original_order,
+ "Define C types and functions in the order in which they appear in "
+ "the ASN.1 module instead of topologically sorting types. This "
+ "is useful for comparing output to earlier compiler versions.",
+ NULL },
+ { "parse-units", 0, arg_negative_flag, &parse_units_flag,
+ "Do not generate roken-style units", NULL },
+ { "type-file", 0, arg_string, &type_file_string,
+ "Name of a C header file to generate includes of for base types",
+ "FILE" },
+ { "version", 0, arg_flag, &version_flag, NULL, NULL },
+ { "help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+int num_args = sizeof(args) / sizeof(args[0]);
+
+static void
+usage(int code)
+{
+ if (code)
+ dup2(STDERR_FILENO, STDOUT_FILENO);
+ else
+ dup2(STDOUT_FILENO, STDERR_FILENO);
+ arg_printusage(args, num_args, NULL, "[asn1-file [name]]");
+ fprintf(stderr,
+ "\nA DECORATION is one of:\n\n"
+ "\tTYPE:FTYPE:fname[?]\n"
+ "\tTYPE:FTYPE:fname[?]:[copy_function]:[free_function]:header\n"
+ "\tTYPE:void:fname:::\n"
+ "\nSee the manual page.\n");
+ exit(code);
+}
+
+int error_flag;
+
+int
+main(int argc, char **argv)
+{
+ int ret;
+ const char *file;
+ FILE *opt = NULL;
+ int optidx = 0;
+ char **arg = NULL;
+ size_t len = 0;
+ size_t sz = 0;
+ int i;
+
+ setprogname(argv[0]);
+ if (getarg(args, num_args, argc, argv, &optidx))
+ usage(1);
+ if (help_flag)
+ usage(0);
+ if (version_flag) {
+ print_version(NULL);
+ exit(0);
+ }
+ if (argc == optidx) {
+ /* Compile the module on stdin */
+ file = "stdin";
+ name = "stdin";
+ yyin = stdin;
+ } else {
+ /* Compile a named module */
+ file = argv[optidx];
+
+ /*
+ * If the .asn1 stem is not given, then assume it, and also assume
+ * --option-file was given if the .opt file exists
+ */
+ if (strchr(file, '.') == NULL) {
+ char *s = NULL;
+
+ if (asprintf(&s, "%s.opt", file) == -1 || s == NULL)
+ err(1, "Out of memory");
+ if ((opt = fopen(s, "r")))
+ option_file = s;
+ else
+ free(s);
+ if (asprintf(&s, "%s.asn1", file) == -1 || s == NULL)
+ err(1, "Out of memory");
+ file = s;
+ }
+ yyin = fopen (file, "r");
+ if (yyin == NULL)
+ err (1, "open %s", file);
+ if (argc == optidx + 1) {
+ char *p;
+
+ /* C module name substring not given; derive from file name */
+ name = my_basename(estrdup(file));
+ p = strrchr(name, '.');
+ if (p)
+ *p = '\0';
+ } else
+ name = argv[optidx + 1];
+ }
+
+ /*
+ * Parse extra options file
+ */
+ if (option_file) {
+ char buf[1024];
+
+ if (opt == NULL &&
+ (opt = fopen(option_file, "r")) == NULL)
+ err(1, "Could not open given option file %s", option_file);
+
+ arg = calloc(2, sizeof(arg[0]));
+ if (arg == NULL) {
+ perror("calloc");
+ exit(1);
+ }
+ arg[0] = option_file;
+ arg[1] = NULL;
+ len = 1;
+ sz = 2;
+
+ while (fgets(buf, sizeof(buf), opt) != NULL) {
+ buf[strcspn(buf, "\n\r")] = '\0';
+
+ if (len + 1 >= sz) {
+ arg = realloc(arg, (sz + (sz>>1) + 2) * sizeof(arg[0]));
+ if (arg == NULL) {
+ perror("malloc");
+ exit(1);
+ }
+ sz += (sz>>1) + 2;
+ }
+ arg[len] = strdup(buf);
+ if (arg[len] == NULL) {
+ perror("strdup");
+ exit(1);
+ }
+ arg[len + 1] = NULL;
+ len++;
+ }
+ fclose(opt);
+
+ optidx = 0;
+ if(getarg(args, num_args, len, arg, &optidx))
+ usage(1);
+
+ if (len != optidx) {
+ fprintf(stderr, "extra args");
+ exit(1);
+ }
+ }
+
+ if (fuzzer_flag) {
+ if (!template_flag) {
+ printf("can't do fuzzer w/o --template");
+ exit(1);
+ }
+#ifdef ASN1_FUZZER
+ fuzzer_string = "_fuzzer";
+#endif
+ }
+
+ if (preserve.num_strings)
+ mergesort_r(preserve.strings, preserve.num_strings,
+ sizeof(preserve.strings[0]), strcmp4mergesort_r, "");
+ if (seq.num_strings)
+ mergesort_r(seq.strings, seq.num_strings, sizeof(seq.strings[0]),
+ strcmp4mergesort_r, "");
+ if (decorate.num_strings)
+ mergesort_r(decorate.strings, decorate.num_strings,
+ sizeof(decorate.strings[0]), strcmp4mergesort_r, ":");
+
+ init_generate(file, name);
+
+ if (one_code_file)
+ generate_header_of_codefile(name);
+
+ initsym ();
+ ret = yyparse ();
+ if(ret != 0 || error_flag != 0)
+ exit(1);
+ if (!original_order)
+ generate_types();
+ if (argc != optidx)
+ fclose(yyin);
+
+ if (one_code_file)
+ close_codefile();
+ close_generate();
+
+ if (arg) {
+ for (i = 1; i < len; i++)
+ free(arg[i]);
+ free(arg);
+ }
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/asn1/ocsp.asn1 b/third_party/heimdal/lib/asn1/ocsp.asn1
new file mode 100644
index 0000000..eb090a4
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/ocsp.asn1
@@ -0,0 +1,113 @@
+-- From rfc2560
+-- $Id$
+OCSP DEFINITIONS EXPLICIT TAGS::=
+
+BEGIN
+
+IMPORTS
+ Certificate, AlgorithmIdentifier, CRLReason,
+ Name, GeneralName, CertificateSerialNumber, Extensions
+ FROM rfc2459;
+
+OCSPVersion ::= INTEGER { ocsp-v1(0) }
+
+OCSPCertStatus ::= CHOICE {
+ good [0] IMPLICIT NULL,
+ revoked [1] IMPLICIT -- OCSPRevokedInfo -- SEQUENCE {
+ revocationTime GeneralizedTime,
+ revocationReason[0] EXPLICIT CRLReason OPTIONAL
+ },
+ unknown [2] IMPLICIT NULL }
+
+OCSPCertID ::= SEQUENCE {
+ hashAlgorithm AlgorithmIdentifier,
+ issuerNameHash OCTET STRING, -- Hash of Issuer's DN
+ issuerKeyHash OCTET STRING, -- Hash of Issuers public key
+ serialNumber CertificateSerialNumber }
+
+OCSPSingleResponse ::= SEQUENCE {
+ certID OCSPCertID,
+ certStatus OCSPCertStatus,
+ thisUpdate GeneralizedTime,
+ nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL,
+ singleExtensions [1] EXPLICIT Extensions OPTIONAL }
+
+OCSPInnerRequest ::= SEQUENCE {
+ reqCert OCSPCertID,
+ singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL }
+
+OCSPTBSRequest ::= SEQUENCE {
+ version [0] EXPLICIT OCSPVersion -- DEFAULT v1 -- OPTIONAL,
+ requestorName [1] EXPLICIT GeneralName OPTIONAL,
+ requestList SEQUENCE OF OCSPInnerRequest,
+ requestExtensions [2] EXPLICIT Extensions OPTIONAL }
+
+OCSPSignature ::= SEQUENCE {
+ signatureAlgorithm AlgorithmIdentifier,
+ signature BIT STRING,
+ certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
+
+OCSPRequest ::= SEQUENCE {
+ tbsRequest OCSPTBSRequest,
+ optionalSignature [0] EXPLICIT OCSPSignature OPTIONAL }
+
+OCSPResponseBytes ::= SEQUENCE {
+ responseType OBJECT IDENTIFIER,
+ response OCTET STRING }
+
+OCSPResponseStatus ::= ENUMERATED {
+ successful (0), --Response has valid confirmations
+ malformedRequest (1), --Illegal confirmation request
+ internalError (2), --Internal error in issuer
+ tryLater (3), --Try again later
+ --(4) is not used
+ sigRequired (5), --Must sign the request
+ unauthorized (6) --Request unauthorized
+}
+
+OCSPResponse ::= SEQUENCE {
+ responseStatus OCSPResponseStatus,
+ responseBytes [0] EXPLICIT OCSPResponseBytes OPTIONAL }
+
+OCSPKeyHash ::= OCTET STRING --SHA-1 hash of responder's public key
+ --(excluding the tag and length fields)
+
+OCSPResponderID ::= CHOICE {
+ byName [1] Name,
+ byKey [2] OCSPKeyHash }
+
+OCSPResponseData ::= SEQUENCE {
+ version [0] EXPLICIT OCSPVersion -- DEFAULT v1 -- OPTIONAL,
+ responderID OCSPResponderID,
+ producedAt GeneralizedTime,
+ responses SEQUENCE OF OCSPSingleResponse,
+ responseExtensions [1] EXPLICIT Extensions OPTIONAL }
+
+OCSPBasicOCSPResponse ::= SEQUENCE {
+ tbsResponseData OCSPResponseData,
+ signatureAlgorithm AlgorithmIdentifier,
+ signature BIT STRING,
+ certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
+
+-- ArchiveCutoff ::= GeneralizedTime
+
+-- AcceptableResponses ::= SEQUENCE OF OBJECT IDENTIFIER
+
+-- Object Identifiers
+
+id-pkix-ocsp OBJECT IDENTIFIER ::= {
+ iso(1) identified-organization(3) dod(6) internet(1)
+ security(5) mechanisms(5) pkix(7) pkix-ad(48) 1
+}
+
+id-pkix-ocsp-basic OBJECT IDENTIFIER ::= { id-pkix-ocsp 1 }
+id-pkix-ocsp-nonce OBJECT IDENTIFIER ::= { id-pkix-ocsp 2 }
+-- id-pkix-ocsp-crl OBJECT IDENTIFIER ::= { id-pkix-ocsp 3 }
+-- id-pkix-ocsp-response OBJECT IDENTIFIER ::= { id-pkix-ocsp 4 }
+-- id-pkix-ocsp-nocheck OBJECT IDENTIFIER ::= { id-pkix-ocsp 5 }
+-- id-pkix-ocsp-archive-cutoff OBJECT IDENTIFIER ::= { id-pkix-ocsp 6 }
+-- id-pkix-ocsp-service-locator OBJECT IDENTIFIER ::= { id-pkix-ocsp 7 }
+
+
+END
+
diff --git a/third_party/heimdal/lib/asn1/ocsp.opt b/third_party/heimdal/lib/asn1/ocsp.opt
new file mode 100644
index 0000000..697aa03
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/ocsp.opt
@@ -0,0 +1,2 @@
+--preserve-binary=OCSPTBSRequest
+--preserve-binary=OCSPResponseData
diff --git a/third_party/heimdal/lib/asn1/oid_resolution.c b/third_party/heimdal/lib/asn1/oid_resolution.c
new file mode 100644
index 0000000..db11b11
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/oid_resolution.c
@@ -0,0 +1,341 @@
+/*
+ * Copyright (c) 2019 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+#include <hex.h>
+
+#include "cms_asn1.h"
+#include "crmf_asn1.h"
+#include "digest_asn1.h"
+#include "krb5_asn1.h"
+#include "kx509_asn1.h"
+#include "ocsp_asn1.h"
+#include "pkcs10_asn1.h"
+#include "pkcs12_asn1.h"
+#include "pkcs8_asn1.h"
+#include "pkcs9_asn1.h"
+#include "pkinit_asn1.h"
+#include "rfc2459_asn1.h"
+#include "rfc4108_asn1.h"
+
+
+struct sym_oid {
+ const char *sym;
+ const heim_oid *oid;
+};
+
+#ifndef WIN32
+#define DEFINE_OID_WITH_NAME(sym) \
+ { #sym, &asn1_oid_ ## sym },
+
+static const struct sym_oid sym_oids[] = {
+#include "cms_asn1_oids.c"
+#include "crmf_asn1_oids.c"
+#include "digest_asn1_oids.c"
+#include "krb5_asn1_oids.c"
+#include "kx509_asn1_oids.c"
+#include "ocsp_asn1_oids.c"
+#include "pkcs10_asn1_oids.c"
+#include "pkcs12_asn1_oids.c"
+#include "pkcs8_asn1_oids.c"
+#include "pkcs9_asn1_oids.c"
+#include "pkinit_asn1_oids.c"
+#include "rfc2459_asn1_oids.c"
+#include "rfc4108_asn1_oids.c"
+};
+
+static size_t num_sym_oids = sizeof(sym_oids) / sizeof(sym_oids[0]);
+
+#undef DEFINE_OID_WITH_NAME
+
+#define init_sym_oids()
+
+#else
+
+/*
+ * We can't use C99 non-literal initializers for static objects in the Windows
+ * build...
+ */
+
+static struct sym_oid *sym_oids;
+static size_t num_sym_oids;
+
+#define DEFINE_OID_WITH_NAME(sym) (c++);
+static size_t
+count_sym_oids(void)
+{
+ size_t c = 0;
+#include "cms_asn1_oids.c"
+#include "crmf_asn1_oids.c"
+#include "digest_asn1_oids.c"
+#include "krb5_asn1_oids.c"
+#include "kx509_asn1_oids.c"
+#include "ocsp_asn1_oids.c"
+#include "pkcs10_asn1_oids.c"
+#include "pkcs12_asn1_oids.c"
+#include "pkcs8_asn1_oids.c"
+#include "pkcs9_asn1_oids.c"
+#include "pkinit_asn1_oids.c"
+#include "rfc2459_asn1_oids.c"
+ return c;
+}
+#undef DEFINE_OID_WITH_NAME
+
+#define DEFINE_OID_WITH_NAME(s) \
+ tmp[i].sym = #s; \
+ tmp[i++].oid = &asn1_oid_ ## s;
+
+static void
+init_sym_oids(void)
+{
+ static struct sym_oid *tmp;
+ size_t i = 0;
+ size_t c;
+
+ if (!sym_oids &&
+ (c = count_sym_oids()) &&
+ (tmp = calloc(c, sizeof(tmp[0])))) {
+#include "cms_asn1_oids.c"
+#include "crmf_asn1_oids.c"
+#include "digest_asn1_oids.c"
+#include "krb5_asn1_oids.c"
+#include "kx509_asn1_oids.c"
+#include "ocsp_asn1_oids.c"
+#include "pkcs10_asn1_oids.c"
+#include "pkcs12_asn1_oids.c"
+#include "pkcs8_asn1_oids.c"
+#include "pkcs9_asn1_oids.c"
+#include "pkinit_asn1_oids.c"
+#include "rfc2459_asn1_oids.c"
+ num_sym_oids = c;
+ sym_oids = tmp;
+ }
+}
+#undef DEFINE_OID_WITH_NAME
+
+#endif
+
+static struct sym_oid *sym_oids_sorted_by_name;
+static struct sym_oid *sym_oids_sorted_by_oid;
+
+static int
+sym_cmp_name(const void *va, const void *vb)
+{
+ const struct sym_oid *a = va;
+ const struct sym_oid *b = vb;
+
+ return (strcmp(a->sym, b->sym));
+}
+
+static int
+sym_cmp_oid(const void *va, const void *vb)
+{
+ const struct sym_oid *a = va;
+ const struct sym_oid *b = vb;
+
+ return der_heim_oid_cmp(a->oid, b->oid);
+}
+
+static struct sym_oid *
+sort_sym_oids(int (*cmp)(const void *, const void *))
+{
+ struct sym_oid *tmp;
+
+ init_sym_oids();
+ if ((tmp = calloc(num_sym_oids, sizeof(tmp[0]))) == NULL)
+ return NULL;
+
+ memcpy(tmp, sym_oids, num_sym_oids * sizeof(tmp[0]));
+ qsort(tmp, num_sym_oids, sizeof(struct sym_oid), cmp);
+ return tmp;
+}
+
+static int
+fix_oid_name(const char **namep, char **freeme)
+{
+ char *dash = strchr(*namep, '-');
+
+ *freeme = NULL;
+ if (dash == NULL)
+ return 0;
+ if ((*freeme = strdup(*namep)) == NULL)
+ return ENOMEM;
+ *namep = *freeme;
+ for (dash = strchr(*namep, '-'); dash; dash = strchr(dash, '-'))
+ *dash = '_';
+ return 0;
+}
+
+int ASN1CALL
+der_find_heim_oid_by_name(const char *str, const heim_oid **oid)
+{
+ size_t right = num_sym_oids - 1;
+ size_t left = 0;
+ char *s = NULL;
+ int ret;
+
+ *oid = NULL;
+ if (sym_oids_sorted_by_name == NULL &&
+ (sym_oids_sorted_by_name = sort_sym_oids(sym_cmp_name)) == NULL)
+ return ENOMEM;
+
+ if ((ret = fix_oid_name(&str, &s)))
+ return ret;
+
+ while (left <= right) {
+ size_t mid = left + (right - left) / 2;
+ int cmp;
+
+ cmp = strcmp(str, sym_oids_sorted_by_name[mid].sym);
+ if (cmp == 0) {
+ *oid = sym_oids_sorted_by_name[mid].oid;
+ free(s);
+ return 0;
+ }
+ if (cmp < 0 && mid > 0) {/* avoid underflow */
+ right = mid - 1;
+ } else if (cmp < 0) {
+ free(s);
+ return -1;
+ } else {
+ left = mid + 1;
+ }
+ }
+ free(s);
+ return -1;
+}
+
+int ASN1CALL
+der_find_or_parse_heim_oid(const char *str, const char *sep, heim_oid *oid)
+{
+ const heim_oid *found = NULL;
+
+ switch (der_find_heim_oid_by_name(str, &found)) {
+ case 0: return der_copy_oid(found, oid);
+ case -1: return der_parse_heim_oid(str, sep, oid);
+ default: return ENOMEM;
+ }
+}
+
+int ASN1CALL
+der_find_heim_oid_by_oid(const heim_oid *oid, const char **name)
+{
+ size_t right = num_sym_oids;
+ size_t left = 0;
+
+ *name = NULL;
+ if (sym_oids_sorted_by_oid == NULL &&
+ (sym_oids_sorted_by_oid = sort_sym_oids(sym_cmp_oid)) == NULL)
+ return ENOMEM;
+
+ while (left <= right) {
+ size_t mid = (left + right) >> 1;
+ int cmp;
+
+ cmp = der_heim_oid_cmp(oid, sym_oids_sorted_by_oid[mid].oid);
+ if (cmp == 0) {
+ *name = sym_oids_sorted_by_oid[mid].sym;
+ return 0;
+ }
+ if (cmp < 0 && mid)
+ right = mid - 1;
+ else if (cmp < 0)
+ return -1;
+ else if (mid < num_sym_oids - 1)
+ left = mid + 1;
+ else
+ return -1;
+ }
+ return -1;
+}
+
+int ASN1CALL
+der_match_heim_oid_by_name(const char *str, int *c, const heim_oid **oid)
+{
+ size_t i;
+ char *s = NULL;
+ int ret;
+
+ if ((ret = fix_oid_name(&str, &s)))
+ return ret;
+
+ if (*c < 0)
+ *c = 0;
+
+ init_sym_oids();
+ for (i = (size_t)*c; i < num_sym_oids; i++) {
+ /*
+ * XXX We need a lib/roken strcasestr(), or maybe we should support
+ * globbing here.
+ */
+ if (strstr(sym_oids[i].sym, str)) {
+ *oid = sym_oids[i].oid;
+ free(s);
+ if (i >= INT_MAX)
+ return -1;
+ *c = i + 1; /* num_sym_oids is much less than INT_MAX */
+ return 0;
+ }
+ }
+ free(s);
+ return -1;
+}
+
+/* Warning: der_print_heim_oid_sym() will not round-trip */
+
+int ASN1CALL
+der_print_heim_oid_sym(const heim_oid *oid, char delim, char **strp)
+{
+ const char *sym;
+ char *s1 = NULL;
+ char *s2 = NULL;
+ char *p;
+ int ret;
+
+ if (der_find_heim_oid_by_oid(oid, &sym))
+ return der_print_heim_oid(oid, delim, strp);
+
+ if ((ret = der_print_heim_oid(oid, delim, &s1)))
+ return ret;
+ if (asprintf(&s2, "%s (%s)", s1, sym) == -1 || s2 == NULL) {
+ *strp = s1;
+ return 0;
+ }
+ for (p = s2 + strlen(s1) + 1; *p; p++) {
+ if (*p == '_')
+ *p = '-';
+ }
+ *strp = s2;
+ free(s1);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/asn1/pkcs10.asn1 b/third_party/heimdal/lib/asn1/pkcs10.asn1
new file mode 100644
index 0000000..04cda4e
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/pkcs10.asn1
@@ -0,0 +1,64 @@
+-- $Id$
+PKCS10 DEFINITIONS ::=
+
+BEGIN
+
+IMPORTS
+ Name, SubjectPublicKeyInfo, AlgorithmIdentifier, Attribute, Extensions
+ FROM rfc2459
+ HEIM_ANY FROM heim;
+
+PKCS10-Version ::= INTEGER { pkcs10-v1(0) }
+
+CertificationRequestInfo ::= SEQUENCE {
+ version PKCS10-Version,
+ subject Name,
+ subjectPKInfo SubjectPublicKeyInfo,
+ attributes [0] IMPLICIT SET OF Attribute OPTIONAL
+}
+
+CertificationRequest ::= SEQUENCE {
+ certificationRequestInfo CertificationRequestInfo,
+ signatureAlgorithm AlgorithmIdentifier,
+ signature BIT STRING
+}
+
+IOSCertificationRequestInfo ::= SEQUENCE {
+ version PKCS10-Version,
+ subject Name,
+ subjectPKInfo SubjectPublicKeyInfo,
+ attributes [0] IMPLICIT SET OF CRIAttributeSet OPTIONAL
+}
+
+IOSCertificationRequest ::= SEQUENCE {
+ certificationRequestInfo IOSCertificationRequestInfo,
+ signatureAlgorithm AlgorithmIdentifier,
+ signature BIT STRING
+}
+
+-- Copied from rfc2459.asn1 because we can't IMPORT classes and parameterized
+-- types yet.
+_ATTRIBUTE ::= CLASS {
+ &id OBJECT IDENTIFIER UNIQUE,
+ &Type OPTIONAL,
+ &minCount INTEGER DEFAULT 1,
+ &maxCount INTEGER OPTIONAL
+}
+
+id-pkcs9-extReq-copy OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-9(9) 14
+}
+
+-- Workaround compiler limitation:
+CRIExtensions ::= Extensions
+
+at-extReq _ATTRIBUTE ::= { &Type CRIExtensions, &id id-pkcs9-extReq-copy }
+CRIAttributes _ATTRIBUTE ::= { at-extReq }
+CRIAttributeSet{_ATTRIBUTE:AttrSet} ::= SEQUENCE {
+ type _ATTRIBUTE.&id({AttrSet}),
+ values SET --SIZE (1..MAX)-- OF _ATTRIBUTE.&Type({AttrSet}{@type})
+}
+CRIAttributeSet ::= CRIAttributeSet{CRIAttributes}
+
+END
+
diff --git a/third_party/heimdal/lib/asn1/pkcs10.opt b/third_party/heimdal/lib/asn1/pkcs10.opt
new file mode 100644
index 0000000..499fab2
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/pkcs10.opt
@@ -0,0 +1 @@
+--preserve-binary=CertificationRequestInfo
diff --git a/third_party/heimdal/lib/asn1/pkcs12.asn1 b/third_party/heimdal/lib/asn1/pkcs12.asn1
new file mode 100644
index 0000000..61d3e2c
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/pkcs12.asn1
@@ -0,0 +1,81 @@
+-- $Id$ --
+
+PKCS12 DEFINITIONS ::=
+
+BEGIN
+
+IMPORTS ContentInfo FROM cms
+ DigestInfo FROM rfc2459
+ HEIM_ANY, HEIM_ANY_SET FROM heim;
+
+-- The PFX PDU
+
+id-pkcs-12 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840)
+ rsadsi(113549) pkcs(1) pkcs-12(12) }
+
+id-pkcs-12PbeIds OBJECT IDENTIFIER ::= { id-pkcs-12 1}
+id-pbeWithSHAAnd128BitRC4 OBJECT IDENTIFIER ::= { id-pkcs-12PbeIds 1}
+id-pbeWithSHAAnd40BitRC4 OBJECT IDENTIFIER ::= { id-pkcs-12PbeIds 2}
+id-pbeWithSHAAnd3-KeyTripleDES-CBC OBJECT IDENTIFIER ::= { id-pkcs-12PbeIds 3}
+id-pbeWithSHAAnd2-KeyTripleDES-CBC OBJECT IDENTIFIER ::= { id-pkcs-12PbeIds 4}
+id-pbeWithSHAAnd128BitRC2-CBC OBJECT IDENTIFIER ::= { id-pkcs-12PbeIds 5}
+id-pbewithSHAAnd40BitRC2-CBC OBJECT IDENTIFIER ::= { id-pkcs-12PbeIds 6}
+
+id-pkcs12-bagtypes OBJECT IDENTIFIER ::= { id-pkcs-12 10 1}
+
+id-pkcs12-keyBag OBJECT IDENTIFIER ::= { id-pkcs12-bagtypes 1 }
+id-pkcs12-pkcs8ShroudedKeyBag OBJECT IDENTIFIER ::= { id-pkcs12-bagtypes 2 }
+id-pkcs12-certBag OBJECT IDENTIFIER ::= { id-pkcs12-bagtypes 3 }
+id-pkcs12-crlBag OBJECT IDENTIFIER ::= { id-pkcs12-bagtypes 4 }
+id-pkcs12-secretBag OBJECT IDENTIFIER ::= { id-pkcs12-bagtypes 5 }
+id-pkcs12-safeContentsBag OBJECT IDENTIFIER ::= { id-pkcs12-bagtypes 6 }
+
+
+PKCS12-MacData ::= SEQUENCE {
+ mac DigestInfo,
+ macSalt OCTET STRING,
+ iterations INTEGER OPTIONAL
+}
+
+PKCS12-PFX ::= SEQUENCE {
+ version INTEGER,
+ authSafe ContentInfo,
+ macData PKCS12-MacData OPTIONAL
+}
+
+PKCS12-AuthenticatedSafe ::= SEQUENCE OF ContentInfo
+ -- Data if unencrypted
+ -- EncryptedData if password-encrypted
+ -- EnvelopedData if public key-encrypted
+
+PKCS12-Attribute ::= SEQUENCE {
+ attrId OBJECT IDENTIFIER,
+ attrValues -- SET OF -- HEIM_ANY_SET
+}
+
+PKCS12-Attributes ::= SET OF PKCS12-Attribute
+
+PKCS12-SafeBag ::= SEQUENCE {
+ bagId OBJECT IDENTIFIER,
+ bagValue [0] HEIM_ANY,
+ bagAttributes PKCS12-Attributes OPTIONAL
+}
+
+PKCS12-SafeContents ::= SEQUENCE OF PKCS12-SafeBag
+
+PKCS12-CertBag ::= SEQUENCE {
+ certType OBJECT IDENTIFIER,
+ certValue [0] HEIM_ANY
+}
+
+PKCS12-PBEParams ::= SEQUENCE {
+ salt OCTET STRING,
+ iterations INTEGER (0..4294967295) OPTIONAL
+}
+
+PKCS12-OctetString ::= OCTET STRING
+
+-- KeyBag ::= PrivateKeyInfo
+-- PKCS8ShroudedKeyBag ::= EncryptedPrivateKeyInfo
+
+END
diff --git a/third_party/heimdal/lib/asn1/pkcs8.asn1 b/third_party/heimdal/lib/asn1/pkcs8.asn1
new file mode 100644
index 0000000..6227033
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/pkcs8.asn1
@@ -0,0 +1,29 @@
+-- $Id$ --
+
+PKCS8 DEFINITIONS ::=
+
+BEGIN
+
+IMPORTS Attribute, AlgorithmIdentifier FROM rfc2459;
+
+PKCS8PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
+
+PKCS8PrivateKey ::= OCTET STRING
+
+PKCS8Attributes ::= SET OF Attribute
+
+PKCS8PrivateKeyInfo ::= SEQUENCE {
+ version INTEGER,
+ privateKeyAlgorithm PKCS8PrivateKeyAlgorithmIdentifier,
+ privateKey PKCS8PrivateKey,
+ attributes [0] IMPLICIT SET OF Attribute OPTIONAL
+}
+
+PKCS8EncryptedData ::= OCTET STRING
+
+PKCS8EncryptedPrivateKeyInfo ::= SEQUENCE {
+ encryptionAlgorithm AlgorithmIdentifier,
+ encryptedData PKCS8EncryptedData
+}
+
+END
diff --git a/third_party/heimdal/lib/asn1/pkcs9.asn1 b/third_party/heimdal/lib/asn1/pkcs9.asn1
new file mode 100644
index 0000000..43b4a9d
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/pkcs9.asn1
@@ -0,0 +1,29 @@
+-- $Id$ --
+
+PKCS9 DEFINITIONS ::=
+
+BEGIN
+
+-- The PFX PDU
+
+id-pkcs-9 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840)
+ rsadsi(113549) pkcs(1) pkcs-9(9) }
+
+id-pkcs9-emailAddress OBJECT IDENTIFIER ::= {id-pkcs-9 1 }
+id-pkcs9-contentType OBJECT IDENTIFIER ::= {id-pkcs-9 3 }
+id-pkcs9-messageDigest OBJECT IDENTIFIER ::= {id-pkcs-9 4 }
+id-pkcs9-signingTime OBJECT IDENTIFIER ::= {id-pkcs-9 5 }
+id-pkcs9-countersignature OBJECT IDENTIFIER ::= {id-pkcs-9 6 }
+id-pkcs9-extReq OBJECT IDENTIFIER ::= {id-pkcs-9 14}
+
+id-pkcs-9-at-friendlyName OBJECT IDENTIFIER ::= {id-pkcs-9 20}
+id-pkcs-9-at-localKeyId OBJECT IDENTIFIER ::= {id-pkcs-9 21}
+id-pkcs-9-at-certTypes OBJECT IDENTIFIER ::= {id-pkcs-9 22}
+id-pkcs-9-at-certTypes-x509 OBJECT IDENTIFIER ::= {id-pkcs-9-at-certTypes 1}
+
+PKCS9-BMPString ::= BMPString
+
+PKCS9-friendlyName ::= SET OF PKCS9-BMPString
+
+END
+
diff --git a/third_party/heimdal/lib/asn1/pkinit.asn1 b/third_party/heimdal/lib/asn1/pkinit.asn1
new file mode 100644
index 0000000..9de0059
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/pkinit.asn1
@@ -0,0 +1,200 @@
+-- $Id$ --
+
+PKINIT DEFINITIONS ::= BEGIN
+
+IMPORTS EncryptionKey, PrincipalName, Realm, KerberosTime, Checksum, Ticket FROM krb5
+ IssuerAndSerialNumber FROM cms
+ SubjectPublicKeyInfo, AlgorithmIdentifier FROM rfc2459
+ HEIM_ANY FROM heim;
+
+id-pkinit OBJECT IDENTIFIER ::=
+ { iso (1) org (3) dod (6) internet (1) security (5)
+ kerberosv5 (2) pkinit (3) }
+
+id-pkauthdata OBJECT IDENTIFIER ::= { id-pkinit 1 }
+id-pkdhkeydata OBJECT IDENTIFIER ::= { id-pkinit 2 }
+id-pkrkeydata OBJECT IDENTIFIER ::= { id-pkinit 3 }
+id-pkekuoid OBJECT IDENTIFIER ::= { id-pkinit 4 }
+id-pkkdcekuoid OBJECT IDENTIFIER ::= { id-pkinit 5 }
+
+id-heim-eku-pkinit-certlife-is-max-life OBJECT IDENTIFIER ::=
+ { iso(1) member-body(2) se(752) su(43) heim-pkix(16) 3 }
+
+id-apple-system-id OBJECT IDENTIFIER ::= { 1 2 840 113635 100 4 4 }
+
+id-pkinit-kdf OBJECT IDENTIFIER ::= { id-pkinit 6 }
+id-pkinit-kdf-ah-sha1 OBJECT IDENTIFIER ::= { id-pkinit-kdf 1 }
+id-pkinit-kdf-ah-sha256 OBJECT IDENTIFIER ::= { id-pkinit-kdf 2 }
+id-pkinit-kdf-ah-sha512 OBJECT IDENTIFIER ::= { id-pkinit-kdf 3 }
+
+id-pkinit-san OBJECT IDENTIFIER ::=
+ { iso(1) org(3) dod(6) internet(1) security(5) kerberosv5(2)
+ x509-sanan(2) }
+
+id-pkinit-ms-eku OBJECT IDENTIFIER ::=
+ { iso(1) org(3) dod(6) internet(1) private(4)
+ enterprise(1) microsoft(311) 20 2 2 }
+
+id-pkinit-ms-san OBJECT IDENTIFIER ::=
+ { iso(1) org(3) dod(6) internet(1) private(4)
+ enterprise(1) microsoft(311) 20 2 3 }
+
+MS-UPN-SAN ::= UTF8String
+
+pa-pk-as-req INTEGER ::= 16
+pa-pk-as-rep INTEGER ::= 17
+
+td-trusted-certifiers INTEGER ::= 104
+td-invalid-certificates INTEGER ::= 105
+td-dh-parameters INTEGER ::= 109
+
+DHNonce ::= OCTET STRING
+
+KDFAlgorithmId ::= SEQUENCE {
+ kdf-id [0] OBJECT IDENTIFIER,
+ ...
+}
+
+TrustedCA ::= SEQUENCE {
+ caName [0] IMPLICIT OCTET STRING,
+ certificateSerialNumber [1] INTEGER OPTIONAL,
+ subjectKeyIdentifier [2] OCTET STRING OPTIONAL,
+ ...
+}
+
+ExternalPrincipalIdentifier ::= SEQUENCE {
+ subjectName [0] IMPLICIT OCTET STRING OPTIONAL,
+ issuerAndSerialNumber [1] IMPLICIT OCTET STRING OPTIONAL,
+ subjectKeyIdentifier [2] IMPLICIT OCTET STRING OPTIONAL,
+ ...
+}
+
+ExternalPrincipalIdentifiers ::= SEQUENCE OF ExternalPrincipalIdentifier
+
+PA-PK-AS-REQ ::= SEQUENCE {
+ signedAuthPack [0] IMPLICIT OCTET STRING,
+ trustedCertifiers [1] ExternalPrincipalIdentifiers OPTIONAL,
+ kdcPkId [2] IMPLICIT OCTET STRING OPTIONAL,
+ ...
+}
+
+PKAuthenticator ::= SEQUENCE {
+ cusec [0] INTEGER -- (0..999999) --,
+ ctime [1] KerberosTime,
+ nonce [2] INTEGER (0..4294967295),
+ paChecksum [3] OCTET STRING OPTIONAL,
+ ...
+}
+
+AuthPack ::= SEQUENCE {
+ pkAuthenticator [0] PKAuthenticator,
+ clientPublicValue [1] SubjectPublicKeyInfo OPTIONAL,
+ supportedCMSTypes [2] SEQUENCE OF AlgorithmIdentifier OPTIONAL,
+ clientDHNonce [3] DHNonce OPTIONAL,
+ ...,
+ supportedKDFs [4] SEQUENCE OF KDFAlgorithmId OPTIONAL,
+ ...
+}
+
+TD-TRUSTED-CERTIFIERS ::= ExternalPrincipalIdentifiers
+TD-INVALID-CERTIFICATES ::= ExternalPrincipalIdentifiers
+
+AD-INITIAL-VERIFIED-CAS ::= SEQUENCE OF ExternalPrincipalIdentifier
+
+DHRepInfo ::= SEQUENCE {
+ dhSignedData [0] IMPLICIT OCTET STRING,
+ serverDHNonce [1] DHNonce OPTIONAL,
+ ...,
+ kdf [2] KDFAlgorithmId OPTIONAL,
+ ...
+}
+
+PA-PK-AS-REP ::= CHOICE {
+ dhInfo [0] DHRepInfo,
+ encKeyPack [1] IMPLICIT OCTET STRING,
+ ...
+}
+
+KDCDHKeyInfo ::= SEQUENCE {
+ subjectPublicKey [0] BIT STRING,
+ nonce [1] INTEGER (0..4294967295),
+ dhKeyExpiration [2] KerberosTime OPTIONAL,
+ ...
+}
+
+ReplyKeyPack ::= SEQUENCE {
+ replyKey [0] EncryptionKey,
+ asChecksum [1] Checksum,
+ ...
+}
+
+TD-DH-PARAMETERS ::= SEQUENCE OF AlgorithmIdentifier
+
+
+-- Windows compat glue --
+
+PKAuthenticator-Win2k ::= SEQUENCE {
+ kdcName [0] PrincipalName,
+ kdcRealm [1] Realm,
+ cusec [2] INTEGER (0..4294967295),
+ ctime [3] KerberosTime,
+ nonce [4] INTEGER (-2147483648..2147483647)
+}
+
+AuthPack-Win2k ::= SEQUENCE {
+ pkAuthenticator [0] PKAuthenticator-Win2k,
+ clientPublicValue [1] SubjectPublicKeyInfo OPTIONAL
+}
+
+
+TrustedCA-Win2k ::= CHOICE {
+ caName [1] HEIM_ANY,
+ issuerAndSerial [2] IssuerAndSerialNumber
+}
+
+PA-PK-AS-REQ-Win2k ::= SEQUENCE {
+ signed-auth-pack [0] IMPLICIT OCTET STRING,
+ trusted-certifiers [2] SEQUENCE OF TrustedCA-Win2k OPTIONAL,
+ kdc-cert [3] IMPLICIT OCTET STRING OPTIONAL,
+ encryption-cert [4] IMPLICIT OCTET STRING OPTIONAL
+}
+
+PA-PK-AS-REP-Win2k ::= CHOICE {
+ dhSignedData [0] IMPLICIT OCTET STRING,
+ encKeyPack [1] IMPLICIT OCTET STRING
+}
+
+KDCDHKeyInfo-Win2k ::= SEQUENCE {
+ nonce [0] INTEGER (-2147483648..2147483647),
+ subjectPublicKey [2] BIT STRING
+}
+
+ReplyKeyPack-Win2k ::= SEQUENCE {
+ replyKey [0] EncryptionKey,
+ nonce [1] INTEGER (-2147483648..2147483647),
+ ...
+}
+
+PA-PK-AS-REP-BTMM ::= SEQUENCE {
+ dhSignedData [0] HEIM_ANY OPTIONAL,
+ encKeyPack [1] HEIM_ANY OPTIONAL
+}
+
+
+PkinitSP80056AOtherInfo ::= SEQUENCE {
+ algorithmID AlgorithmIdentifier,
+ partyUInfo [0] OCTET STRING,
+ partyVInfo [1] OCTET STRING,
+ suppPubInfo [2] OCTET STRING OPTIONAL,
+ suppPrivInfo [3] OCTET STRING OPTIONAL
+}
+
+PkinitSuppPubInfo ::= SEQUENCE {
+ enctype [0] INTEGER (-2147483648..2147483647),
+ as-REQ [1] OCTET STRING,
+ pk-as-rep [2] OCTET STRING,
+ ticket [3] Ticket,
+ ...
+}
+
+END
diff --git a/third_party/heimdal/lib/asn1/pku2u.asn1 b/third_party/heimdal/lib/asn1/pku2u.asn1
new file mode 100644
index 0000000..ca3a91f
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/pku2u.asn1
@@ -0,0 +1,30 @@
+-- $Id$
+
+PKU2U DEFINITIONS ::= BEGIN
+
+IMPORTS Checksum FROM krb5
+ GeneralName FROM rfc2459;
+
+GSS_KRB5_FINISHED ::= SEQUENCE {
+ gss-mic [1] Checksum,
+ ...
+}
+
+InitiatorName ::= CHOICE {
+ sanIndex INTEGER (-2147483648..2147483647),
+ nameNotInCert [0] GeneralName,
+ ...
+}
+
+TargetName ::= CHOICE {
+ exportedTargName OCTET STRING,
+ generalName [0] GeneralName,
+ ...
+}
+
+InitiatorNameAssertion ::= SEQUENCE {
+ initiatorName [0] InitiatorName OPTIONAL,
+ targetName [1] TargetName OPTIONAL
+}
+
+END
diff --git a/third_party/heimdal/lib/asn1/rfc2459.asn1 b/third_party/heimdal/lib/asn1/rfc2459.asn1
new file mode 100644
index 0000000..7ceefe3
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/rfc2459.asn1
@@ -0,0 +1,1210 @@
+-- $Id$ --
+-- Definitions from RFCs 2459, 3280, 5280
+--
+-- Note that those RFCs come with *two* ASN.1 modules, one being a default-
+-- EXPLICIT tagged module, and the other being default-IMPLICIT. Some types
+-- are in one module, while others are in the other. Here the two modules
+-- are merged into a single default-EXPLICIT tagged module, with IMPLICIT added
+-- for all tags for types in the default-IMPLICIT module.
+
+RFC2459 DEFINITIONS ::= BEGIN
+
+IMPORTS HEIM_ANY FROM heim
+ PrincipalName, Realm FROM krb5;
+ -- For OtherName we really want to also import:
+ -- KRB5PrincipalName FROM pkinit
+ -- PermanentIdentifier FROM rfc4043
+ -- HardwareModuleName FROM rfc4108;
+ -- But we can't because that creates circular dependencies.
+
+Version ::= INTEGER {
+ rfc3280_version_1(0),
+ rfc3280_version_2(1),
+ rfc3280_version_3(2)
+}
+
+id-pkcs-1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840)
+ rsadsi(113549) pkcs(1) 1 }
+id-pkcs1-rsaEncryption OBJECT IDENTIFIER ::= { id-pkcs-1 1 }
+id-pkcs1-md2WithRSAEncryption OBJECT IDENTIFIER ::= { id-pkcs-1 2 }
+id-pkcs1-md5WithRSAEncryption OBJECT IDENTIFIER ::= { id-pkcs-1 4 }
+id-pkcs1-sha1WithRSAEncryption OBJECT IDENTIFIER ::= { id-pkcs-1 5 }
+id-pkcs1-sha256WithRSAEncryption OBJECT IDENTIFIER ::= { id-pkcs-1 11 }
+id-pkcs1-sha384WithRSAEncryption OBJECT IDENTIFIER ::= { id-pkcs-1 12 }
+id-pkcs1-sha512WithRSAEncryption OBJECT IDENTIFIER ::= { id-pkcs-1 13 }
+
+id-heim-rsa-pkcs1-x509 OBJECT IDENTIFIER ::= { 1 2 752 43 16 1 }
+
+id-pkcs-2 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840)
+ rsadsi(113549) pkcs(1) 2 }
+id-pkcs2-md2 OBJECT IDENTIFIER ::= { id-pkcs-2 2 }
+id-pkcs2-md4 OBJECT IDENTIFIER ::= { id-pkcs-2 4 }
+id-pkcs2-md5 OBJECT IDENTIFIER ::= { id-pkcs-2 5 }
+
+id-rsa-digestAlgorithm OBJECT IDENTIFIER ::=
+{ iso(1) member-body(2) us(840) rsadsi(113549) 2 }
+
+id-rsa-digest-md2 OBJECT IDENTIFIER ::= { id-rsa-digestAlgorithm 2 }
+id-rsa-digest-md4 OBJECT IDENTIFIER ::= { id-rsa-digestAlgorithm 4 }
+id-rsa-digest-md5 OBJECT IDENTIFIER ::= { id-rsa-digestAlgorithm 5 }
+
+id-pkcs-3 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840)
+ rsadsi(113549) pkcs(1) 3 }
+
+id-pkcs3-rc2-cbc OBJECT IDENTIFIER ::= { id-pkcs-3 2 }
+id-pkcs3-rc4 OBJECT IDENTIFIER ::= { id-pkcs-3 4 }
+id-pkcs3-des-ede3-cbc OBJECT IDENTIFIER ::= { id-pkcs-3 7 }
+
+id-rsadsi-encalg OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840)
+ rsadsi(113549) 3 }
+
+id-rsadsi-rc2-cbc OBJECT IDENTIFIER ::= { id-rsadsi-encalg 2 }
+id-rsadsi-des-ede3-cbc OBJECT IDENTIFIER ::= { id-rsadsi-encalg 7 }
+
+id-secsig-sha-1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3)
+ oiw(14) secsig(3) algorithm(2) 26 }
+
+id-secsig-sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { iso(1) identified-organization(3)
+ oiw(14) secsig(3) algorithm(2) 29 }
+
+id-nistAlgorithm OBJECT IDENTIFIER ::= {
+ joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) 4 }
+
+id-nist-aes-algs OBJECT IDENTIFIER ::= { id-nistAlgorithm 1 }
+
+id-aes-128-cbc OBJECT IDENTIFIER ::= { id-nist-aes-algs 2 }
+id-aes-192-cbc OBJECT IDENTIFIER ::= { id-nist-aes-algs 22 }
+id-aes-256-cbc OBJECT IDENTIFIER ::= { id-nist-aes-algs 42 }
+
+id-nist-sha-algs OBJECT IDENTIFIER ::= { id-nistAlgorithm 2 }
+
+id-sha256 OBJECT IDENTIFIER ::= { id-nist-sha-algs 1 }
+id-sha224 OBJECT IDENTIFIER ::= { id-nist-sha-algs 4 }
+id-sha384 OBJECT IDENTIFIER ::= { id-nist-sha-algs 2 }
+id-sha512 OBJECT IDENTIFIER ::= { id-nist-sha-algs 3 }
+
+id-dhpublicnumber OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) ansi-x942(10046)
+ number-type(2) 1 }
+
+-- ECC
+
+id-ecPublicKey OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
+
+id-ecDH OBJECT IDENTIFIER ::= {
+ iso(1) identified-organization(3) certicom(132) schemes(1)
+ ecdh(12) }
+
+id-ecMQV OBJECT IDENTIFIER ::= {
+ iso(1) identified-organization(3) certicom(132) schemes(1)
+ ecmqv(13) }
+
+id-ecdsa-with-SHA512 OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)
+ ecdsa-with-SHA2(3) 4 }
+
+id-ecdsa-with-SHA384 OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)
+ ecdsa-with-SHA2(3) 3 }
+
+id-ecdsa-with-SHA256 OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)
+ ecdsa-with-SHA2(3) 2 }
+
+id-ecdsa-with-SHA224 OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)
+ ecdsa-with-SHA2(3) 1 }
+
+id-ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) 1 }
+
+-- some EC group ids
+
+id-ec-group-secp256r1 OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
+ prime(1) 7 }
+
+id-ec-group-secp160r1 OBJECT IDENTIFIER ::= {
+ iso(1) identified-organization(3) certicom(132) 0 8 }
+
+id-ec-group-secp160r2 OBJECT IDENTIFIER ::= {
+ iso(1) identified-organization(3) certicom(132) 0 30 }
+
+id-ec-group-secp224r1 OBJECT IDENTIFIER ::= {
+ iso(1) identified-organization(3) certicom(132) 0 33 }
+
+id-ec-group-secp384r1 OBJECT IDENTIFIER ::= {
+ iso(1) identified-organization(3) certicom(132) 0 34 }
+
+id-ec-group-secp521r1 OBJECT IDENTIFIER ::= {
+ iso(1) identified-organization(3) certicom(132) 0 35 }
+
+-- DSA
+
+id-x9-57 OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) ansi-x942(10046) 4 }
+
+id-dsa OBJECT IDENTIFIER ::= { id-x9-57 1 }
+id-dsa-with-sha1 OBJECT IDENTIFIER ::= { id-x9-57 3 }
+
+-- x.520 names types
+
+id-x520-at OBJECT IDENTIFIER ::= { joint-iso-ccitt(2) ds(5) 4 }
+
+id-at-commonName OBJECT IDENTIFIER ::= { id-x520-at 3 }
+id-at-surname OBJECT IDENTIFIER ::= { id-x520-at 4 }
+id-at-serialNumber OBJECT IDENTIFIER ::= { id-x520-at 5 }
+id-at-countryName OBJECT IDENTIFIER ::= { id-x520-at 6 }
+id-at-localityName OBJECT IDENTIFIER ::= { id-x520-at 7 }
+id-at-stateOrProvinceName OBJECT IDENTIFIER ::= { id-x520-at 8 }
+id-at-streetAddress OBJECT IDENTIFIER ::= { id-x520-at 9 }
+id-at-organizationName OBJECT IDENTIFIER ::= { id-x520-at 10 }
+id-at-organizationalUnitName OBJECT IDENTIFIER ::= { id-x520-at 11 }
+id-at-title OBJECT IDENTIFIER ::= { id-x520-at 12 }
+id-at-description OBJECT IDENTIFIER ::= { id-x520-at 13 }
+id-at-name OBJECT IDENTIFIER ::= { id-x520-at 41 }
+id-at-givenName OBJECT IDENTIFIER ::= { id-x520-at 42 }
+id-at-initials OBJECT IDENTIFIER ::= { id-x520-at 43 }
+id-at-generationQualifier OBJECT IDENTIFIER ::= { id-x520-at 44 }
+id-at-dnQualifier OBJECT IDENTIFIER ::= { id-x520-at 46 }
+id-at-pseudonym OBJECT IDENTIFIER ::= { id-x520-at 65 }
+-- RFC 2247
+id-Userid OBJECT IDENTIFIER ::=
+ { 0 9 2342 19200300 100 1 1 }
+id-domainComponent OBJECT IDENTIFIER ::=
+ { 0 9 2342 19200300 100 1 25 }
+
+id-at-emailAddress AttributeType ::=
+ { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 9 1 }
+
+
+
+-- rfc3280
+
+id-x509-ce OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 29}
+
+AlgorithmIdentifier ::= SEQUENCE {
+ algorithm OBJECT IDENTIFIER,
+ parameters HEIM_ANY OPTIONAL
+}
+
+AttributeType ::= OBJECT IDENTIFIER
+
+AttributeValue ::= HEIM_ANY
+
+DirectoryString ::= CHOICE {
+ ia5String IA5String,
+ teletexString TeletexString,
+ printableString PrintableString,
+ universalString UniversalString,
+ utf8String UTF8String,
+ bmpString BMPString
+}
+
+AttributeValues ::= SET OF AttributeValue
+
+Attribute ::= SEQUENCE {
+ type AttributeType,
+ value AttributeValues
+}
+
+AttributeTypeAndValue ::= SEQUENCE {
+ type AttributeType,
+ value DirectoryString
+}
+
+-- RDNs really should be SET OF SingleAttribute per the RFCs, but making that
+-- change will affect lib/hx509 code, so we'll wait. The issue is that there
+-- is code in lib/hx509 and in lib/asn1/check-gen.c that assumes that the
+-- `value` of an rdn is a `DirectoryString` and not an open type.
+--
+-- Also, it's really not worth making this change, as a) it will increase the
+-- amount of code needed in lib/hx509, and b) it really is useful to be able to
+-- assume RDN values are ultimately only strings, c) we don't have any attrs
+-- for RDNs that aren't strings, and d) the non-string attributes from TCG that
+-- are used in SubjectDirectoryAttributes will never be used here (so we hope).
+--
+-- Until we fix this lib/hx509 cannot support name attributes whose type isn't
+-- DirectoryString. For example, the UID attribute is broken at this time, as
+-- that wants NumericString.
+--
+RelativeDistinguishedName ::= SET OF AttributeTypeAndValue -- XXX SingleAttribute
+
+RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
+
+Name ::= CHOICE {
+ rdnSequence RDNSequence
+}
+
+CertificateSerialNumber ::= INTEGER
+
+Time ::= CHOICE {
+ utcTime UTCTime,
+ generalTime GeneralizedTime
+}
+
+Validity ::= SEQUENCE {
+ notBefore Time,
+ notAfter Time
+}
+
+UniqueIdentifier ::= BIT STRING
+
+SubjectPublicKeyInfo ::= SEQUENCE {
+ algorithm AlgorithmIdentifier,
+ subjectPublicKey BIT STRING
+}
+
+-- XXX Should be _OTHER-NAME ::= _TYPE-IDENTIFIER
+_OTHER-NAME ::= CLASS {
+ &id OBJECT IDENTIFIER UNIQUE,
+ &Type
+}
+
+OtherName{_OTHER-NAME:OtherNameSet} ::= SEQUENCE {
+ type-id _OTHER-NAME.&id({OtherNameSet}),
+ value [0] _OTHER-NAME.&Type({OtherNameSet}{@type-id})
+}
+
+_ATTRIBUTE ::= CLASS {
+ &id OBJECT IDENTIFIER UNIQUE,
+ &Type OPTIONAL,
+ -- &equality-match MATCHING-RULE OPTIONAL,
+ &minCount INTEGER DEFAULT 1,
+ &maxCount INTEGER OPTIONAL
+}
+
+SingleAttribute{_ATTRIBUTE:AttrSet} ::= SEQUENCE {
+ type _ATTRIBUTE.&id({AttrSet}),
+ value _ATTRIBUTE.&Type({AttrSet}{@type})
+}
+
+AttributeSet{_ATTRIBUTE:AttrSet} ::= SEQUENCE {
+ type _ATTRIBUTE.&id({AttrSet}),
+ values SET --SIZE (1..MAX)-- OF _ATTRIBUTE.&Type({AttrSet}{@type})
+}
+
+_EXTENSION ::= CLASS {
+ &id OBJECT IDENTIFIER UNIQUE,
+ &ExtnType,
+ &Critical BOOLEAN DEFAULT FALSE
+}
+
+Extension{_EXTENSION:ExtensionSet} ::= SEQUENCE {
+ extnID _EXTENSION.&id({ExtensionSet}),
+ critical BOOLEAN
+-- (EXTENSION.&Critical({ExtensionSet}{@extnID}))
+ DEFAULT FALSE,
+ extnValue OCTET STRING (CONTAINING
+ _EXTENSION.&ExtnType({ExtensionSet}{@extnID}))
+}
+
+Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
+
+TBSCertificate ::= SEQUENCE {
+ version [0] Version OPTIONAL, -- EXPLICIT nnn DEFAULT 1,
+ serialNumber CertificateSerialNumber,
+ signature AlgorithmIdentifier,
+ issuer Name,
+ validity Validity,
+ subject Name,
+ subjectPublicKeyInfo SubjectPublicKeyInfo,
+ issuerUniqueID [1] IMPLICIT BIT STRING -- UniqueIdentifier -- OPTIONAL,
+ -- If present, version shall be v2 or v3
+ subjectUniqueID [2] IMPLICIT BIT STRING -- UniqueIdentifier -- OPTIONAL,
+ -- If present, version shall be v2 or v3
+ extensions [3] EXPLICIT Extensions OPTIONAL
+ -- If present, version shall be v3
+}
+
+Certificate ::= SEQUENCE {
+ tbsCertificate TBSCertificate,
+ signatureAlgorithm AlgorithmIdentifier,
+ signatureValue BIT STRING
+}
+
+Certificates ::= SEQUENCE OF Certificate
+
+ValidationParms ::= SEQUENCE {
+ seed BIT STRING,
+ pgenCounter INTEGER
+}
+
+DomainParameters ::= SEQUENCE {
+ p INTEGER, -- odd prime, p=jq +1
+ g INTEGER, -- generator, g
+ q INTEGER OPTIONAL, -- factor of p-1
+ j INTEGER OPTIONAL, -- subgroup factor
+ validationParms ValidationParms OPTIONAL -- ValidationParms
+}
+
+-- As defined by PKCS3
+DHParameter ::= SEQUENCE {
+ prime INTEGER, -- odd prime, p=jq +1
+ base INTEGER, -- generator, g
+ privateValueLength INTEGER OPTIONAL
+}
+
+DHPublicKey ::= INTEGER
+
+GeneralName ::= CHOICE {
+ otherName [0] IMPLICIT OtherName,
+ rfc822Name [1] IMPLICIT IA5String,
+ dNSName [2] IMPLICIT IA5String,
+-- x400Address [3] IMPLICIT ORAddress,--
+ directoryName [4] IMPLICIT Name,
+-- ediPartyName [5] IMPLICIT EDIPartyName, --
+ uniformResourceIdentifier [6] IMPLICIT IA5String,
+ iPAddress [7] IMPLICIT OCTET STRING,
+ registeredID [8] IMPLICIT OBJECT IDENTIFIER
+}
+
+GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
+
+id-x509-ce-keyUsage OBJECT IDENTIFIER ::= { id-x509-ce 15 }
+
+KeyUsage ::= BIT STRING {
+ digitalSignature (0),
+ nonRepudiation (1),
+ keyEncipherment (2),
+ dataEncipherment (3),
+ keyAgreement (4),
+ keyCertSign (5),
+ cRLSign (6),
+ encipherOnly (7),
+ decipherOnly (8)
+}
+
+-- private key usage period extension OID and syntax
+
+PrivateKeyUsagePeriod ::= SEQUENCE {
+ notBefore [0] IMPLICIT GeneralizedTime OPTIONAL,
+ notAfter [1] IMPLICIT GeneralizedTime OPTIONAL
+ -- either notBefore or notAfter MUST be present
+}
+
+-- certificate policies extension OID and syntax
+
+_POLICYQUALIFIERINFO ::= CLASS { -- Heimdal extension
+ &id OBJECT IDENTIFIER UNIQUE,
+ &Type
+}
+
+CertPolicyId ::= OBJECT IDENTIFIER
+PolicyQualifierId ::= OBJECT IDENTIFIER -- ( id-qt-cps | id-qt-unotice )
+
+PolicyQualifierInfo{_POLICYQUALIFIERINFO:PolicyQualifierSet} ::= SEQUENCE {
+ policyQualifierId _POLICYQUALIFIERINFO.&id({PolicyQualifierSet}),
+ qualifier _POLICYQUALIFIERINFO.&Type({PolicyQualifierSet}{@policyQualifierId})
+}
+
+PolicyQualifierInfos ::= SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo
+
+PolicyInformation ::= SEQUENCE {
+ policyIdentifier CertPolicyId,
+ policyQualifiers PolicyQualifierInfos OPTIONAL
+}
+
+CertificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation
+
+-- CPS pointer qualifier
+
+CPSuri ::= IA5String
+
+-- user notice qualifier
+
+DisplayText ::= CHOICE {
+ ia5String IA5String, --(SIZE (1..200))
+ visibleString VisibleString, --(SIZE (1..200))
+ bmpString BMPString, --(SIZE (1..200))
+ utf8String UTF8String --(SIZE (1..200))
+}
+
+NoticeReference ::= SEQUENCE {
+ organization DisplayText,
+ noticeNumbers SEQUENCE OF INTEGER
+}
+
+UserNotice ::= SEQUENCE {
+ noticeRef NoticeReference OPTIONAL,
+ explicitText DisplayText OPTIONAL
+}
+
+-- policy mapping extension OID and syntax
+
+PolicyMapping ::= SEQUENCE {
+ issuerDomainPolicy CertPolicyId,
+ subjectDomainPolicy CertPolicyId
+}
+
+PolicyMappings ::= SEQUENCE SIZE (1..MAX) OF PolicyMapping
+
+-- subject key identifier OID and syntax
+
+id-x509-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::= { id-x509-ce 35 }
+
+KeyIdentifier ::= OCTET STRING
+
+AuthorityKeyIdentifier ::= SEQUENCE {
+ keyIdentifier [0] IMPLICIT OCTET STRING OPTIONAL,
+ authorityCertIssuer [1] IMPLICIT -- GeneralName --
+ SEQUENCE -- SIZE (1..MAX) -- OF GeneralName OPTIONAL,
+ authorityCertSerialNumber [2] IMPLICIT INTEGER OPTIONAL
+}
+
+id-x509-ce-subjectKeyIdentifier OBJECT IDENTIFIER ::= { id-x509-ce 14 }
+
+SubjectKeyIdentifier ::= KeyIdentifier
+
+id-x509-ce-basicConstraints OBJECT IDENTIFIER ::= { id-x509-ce 19 }
+
+BasicConstraints ::= SEQUENCE {
+ cA BOOLEAN DEFAULT FALSE,
+ pathLenConstraint INTEGER (0..4294967295) OPTIONAL
+}
+
+id-x509-ce-nameConstraints OBJECT IDENTIFIER ::= { id-x509-ce 30 }
+
+BaseDistance ::= INTEGER (0..4294967295)
+
+GeneralSubtree ::= SEQUENCE {
+ base GeneralName,
+ minimum [0] IMPLICIT BaseDistance DEFAULT 0,
+ maximum [1] IMPLICIT BaseDistance OPTIONAL
+}
+
+GeneralSubtrees ::= SEQUENCE -- SIZE (1..MAX) -- OF GeneralSubtree
+
+NameConstraints ::= SEQUENCE {
+ permittedSubtrees [0] IMPLICIT -- GeneralSubtrees -- SEQUENCE OF GeneralSubtree OPTIONAL,
+ excludedSubtrees [1] IMPLICIT -- GeneralSubtrees -- SEQUENCE OF GeneralSubtree OPTIONAL
+}
+
+id-x509-ce-privateKeyUsagePeriod OBJECT IDENTIFIER ::= { id-x509-ce 16 }
+id-x509-ce-certificatePolicies OBJECT IDENTIFIER ::= { id-x509-ce 32 }
+id-x509-ce-certificatePolicies-anyPolicy OBJECT IDENTIFIER ::= { id-x509-ce-certificatePolicies 0 }
+id-x509-ce-policyMappings OBJECT IDENTIFIER ::= { id-x509-ce 33 }
+id-x509-ce-subjectAltName OBJECT IDENTIFIER ::= { id-x509-ce 17 }
+id-x509-ce-issuerAltName OBJECT IDENTIFIER ::= { id-x509-ce 18 }
+id-x509-ce-subjectDirectoryAttributes OBJECT IDENTIFIER ::= { id-x509-ce 9 }
+id-x509-ce-policyConstraints OBJECT IDENTIFIER ::= { id-x509-ce 36 }
+
+id-x509-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-x509-ce 37}
+id-x509-ce-anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-x509-ce-extKeyUsage 0 }
+
+ExtKeyUsage ::= SEQUENCE OF OBJECT IDENTIFIER
+
+id-x509-ce-cRLReasons OBJECT IDENTIFIER ::= { id-x509-ce 21 }
+id-x509-ce-cRLDistributionPoints OBJECT IDENTIFIER ::= { id-x509-ce 31 }
+id-x509-ce-deltaCRLIndicator OBJECT IDENTIFIER ::= { id-x509-ce 27 }
+id-x509-ce-issuingDistributionPoint OBJECT IDENTIFIER ::= { id-x509-ce 28 }
+id-x509-ce-holdInstructionCode OBJECT IDENTIFIER ::= { id-x509-ce 23 }
+id-x509-ce-invalidityDate OBJECT IDENTIFIER ::= { id-x509-ce 24 }
+id-x509-ce-certificateIssuer OBJECT IDENTIFIER ::= { id-x509-ce 29 }
+id-x509-ce-inhibitAnyPolicy OBJECT IDENTIFIER ::= { id-x509-ce 54 }
+
+-- Heimdal extension
+id-heim-ce-pkinit-princ-max-life OBJECT IDENTIFIER ::=
+ { iso(1) member-body(2) se(752) su(43) heim-pkix(16) 4 }
+
+
+DistributionPointReasonFlags ::= BIT STRING {
+ unused (0),
+ keyCompromise (1),
+ cACompromise (2),
+ affiliationChanged (3),
+ superseded (4),
+ cessationOfOperation (5),
+ certificateHold (6),
+ privilegeWithdrawn (7),
+ aACompromise (8)
+}
+
+DistributionPointName ::= CHOICE {
+ fullName [0] IMPLICIT -- GeneralNames -- SEQUENCE SIZE (1..MAX) OF GeneralName,
+ nameRelativeToCRLIssuer [1] RelativeDistinguishedName
+}
+
+DistributionPoint ::= SEQUENCE {
+ distributionPoint [0] IMPLICIT DistributionPointName OPTIONAL,
+ reasons [1] IMPLICIT DistributionPointReasonFlags OPTIONAL,
+ cRLIssuer [2] IMPLICIT GeneralNames OPTIONAL
+}
+
+CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
+
+
+-- rfc3279
+
+DSASigValue ::= SEQUENCE {
+ r INTEGER,
+ s INTEGER
+}
+
+DSAPublicKey ::= INTEGER
+
+DSAParams ::= SEQUENCE {
+ p INTEGER,
+ q INTEGER,
+ g INTEGER
+}
+
+-- draft-ietf-pkix-ecc-subpubkeyinfo-11
+
+ECPoint ::= OCTET STRING
+
+ECParameters ::= CHOICE {
+ namedCurve OBJECT IDENTIFIER
+ -- implicitCurve NULL
+ -- specifiedCurve SpecifiedECDomain
+}
+
+ECDSA-Sig-Value ::= SEQUENCE {
+ r INTEGER,
+ s INTEGER
+}
+
+-- really pkcs1
+
+RSAPublicKey ::= SEQUENCE {
+ modulus INTEGER, -- n
+ publicExponent INTEGER -- e
+}
+
+RSAPrivateKey ::= SEQUENCE {
+ version INTEGER (0..4294967295),
+ modulus INTEGER, -- n
+ publicExponent INTEGER, -- e
+ privateExponent INTEGER, -- d
+ prime1 INTEGER, -- p
+ prime2 INTEGER, -- q
+ exponent1 INTEGER, -- d mod (p-1)
+ exponent2 INTEGER, -- d mod (q-1)
+ coefficient INTEGER -- (inverse of q) mod p
+}
+
+DigestInfo ::= SEQUENCE {
+ digestAlgorithm AlgorithmIdentifier,
+ digest OCTET STRING
+}
+
+-- some ms ext
+
+-- szOID_ENROLL_CERTTYPE_EXTENSION "1.3.6.1.4.1.311.20.2" is Encoded as a
+
+-- UNICODESTRING (0x1E tag)
+
+-- szOID_CERTIFICATE_TEMPLATE "1.3.6.1.4.1.311.21.7" is Encoded as:
+
+-- TemplateVersion ::= INTEGER (0..4294967295)
+
+-- CertificateTemplate ::= SEQUENCE {
+-- templateID OBJECT IDENTIFIER,
+-- templateMajorVersion TemplateVersion,
+-- templateMinorVersion TemplateVersion OPTIONAL
+-- }
+
+
+--
+-- CRL
+--
+
+TBSCRLCertList ::= SEQUENCE {
+ version Version OPTIONAL, -- if present, MUST be v2
+ signature AlgorithmIdentifier,
+ issuer Name,
+ thisUpdate Time,
+ nextUpdate Time OPTIONAL,
+ revokedCertificates SEQUENCE OF SEQUENCE {
+ userCertificate CertificateSerialNumber,
+ revocationDate Time,
+ crlEntryExtensions Extensions OPTIONAL
+ -- if present, MUST be v2
+ } OPTIONAL,
+ crlExtensions [0] EXPLICIT Extensions OPTIONAL
+ -- if present, MUST be v2
+}
+
+
+CRLCertificateList ::= SEQUENCE {
+ tbsCertList TBSCRLCertList,
+ signatureAlgorithm AlgorithmIdentifier,
+ signatureValue BIT STRING
+}
+
+id-x509-ce-cRLNumber OBJECT IDENTIFIER ::= { id-x509-ce 20 }
+id-x509-ce-freshestCRL OBJECT IDENTIFIER ::= { id-x509-ce 46 }
+id-x509-ce-cRLReason OBJECT IDENTIFIER ::= { id-x509-ce 21 }
+
+CRLReason ::= ENUMERATED {
+ unspecified (0),
+ keyCompromise (1),
+ cACompromise (2),
+ affiliationChanged (3),
+ superseded (4),
+ cessationOfOperation (5),
+ certificateHold (6),
+ removeFromCRL (8),
+ privilegeWithdrawn (9),
+ aACompromise (10)
+}
+
+PKIXXmppAddr ::= UTF8String
+
+SRVName ::= IA5String -- (SIZE (1..MAX)), but our compiler doesn't do that
+
+id-pkix OBJECT IDENTIFIER ::= { iso(1) identified-organization(3)
+ dod(6) internet(1) security(5) mechanisms(5) pkix(7) }
+
+id-pkix-on OBJECT IDENTIFIER ::= { id-pkix 8 }
+id-pkix-on-xmppAddr OBJECT IDENTIFIER ::= { id-pkix-on 5 }
+id-pkix-on-dnsSRV OBJECT IDENTIFIER ::= { id-pkix-on 7 }
+
+-- From RFC4108
+id-pkix-on-hardwareModuleName OBJECT IDENTIFIER ::= { id-pkix-on 4 }
+HardwareModuleName ::= SEQUENCE {
+ hwType OBJECT IDENTIFIER,
+ hwSerialNum OCTET STRING
+}
+
+-- XXX Not really the right name
+id-pkix-on-pkinit-san OBJECT IDENTIFIER ::=
+ { iso(1) org(3) dod(6) internet(1) security(5) kerberosv5(2)
+ x509-sanan(2) }
+KRB5PrincipalName ::= SEQUENCE {
+ realm [0] Realm,
+ principalName [1] PrincipalName
+}
+
+-- From RFC4043:
+-- Permanent identifier Object Identifier and Syntax
+id-pkix-on-permanentIdentifier OBJECT IDENTIFIER ::= { id-pkix-on 3 }
+
+PermanentIdentifier ::= SEQUENCE {
+ identifierValue UTF8String OPTIONAL,
+ -- if absent, use the serialNumber attribute
+ -- if there is a single such attribute present
+ -- in the subject DN
+ assigner OBJECT IDENTIFIER OPTIONAL
+ -- if absent, the assigner is
+ -- the certificate issuer
+}
+
+-- EKUs
+id-pkix-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
+id-pkix-kp-serverAuth OBJECT IDENTIFIER ::= { id-pkix-kp 1 }
+id-pkix-kp-clientAuth OBJECT IDENTIFIER ::= { id-pkix-kp 2 }
+id-pkix-kp-codeSigning OBJECT IDENTIFIER ::= { id-pkix-kp 3 }
+id-pkix-kp-emailProtection OBJECT IDENTIFIER ::= { id-pkix-kp 4 }
+id-pkix-kp-ipsecEndSystem OBJECT IDENTIFIER ::= { id-pkix-kp 5 }
+id-pkix-kp-ipsecTunnel OBJECT IDENTIFIER ::= { id-pkix-kp 6 }
+id-pkix-kp-ipsecUser OBJECT IDENTIFIER ::= { id-pkix-kp 7 }
+id-pkix-kp-timeStamping OBJECT IDENTIFIER ::= { id-pkix-kp 8 }
+id-pkix-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-pkix-kp 9 }
+-- The following are taken from RFC7299 and others
+id-pkix-kp-DVCS OBJECT IDENTIFIER ::= { id-pkix-kp 10 }
+id-pkix-kp-ipsecIKE OBJECT IDENTIFIER ::= { id-pkix-kp 17 }
+id-pkix-kp-capwapAC OBJECT IDENTIFIER ::= { id-pkix-kp 18 }
+id-pkix-kp-capwapWTP OBJECT IDENTIFIER ::= { id-pkix-kp 19 }
+id-pkix-kp-sipDomain OBJECT IDENTIFIER ::= { id-pkix-kp 20 } -- RFC5924
+id-pkix-kp-secureShellClient OBJECT IDENTIFIER ::= { id-pkix-kp 21 }
+id-pkix-kp-secureShellServer OBJECT IDENTIFIER ::= { id-pkix-kp 22 }
+id-pkix-kp-sendRouter OBJECT IDENTIFIER ::= { id-pkix-kp 23 }
+id-pkix-kp-sendProxiedRouter OBJECT IDENTIFIER ::= { id-pkix-kp 24 }
+id-pkix-kp-sendOwner OBJECT IDENTIFIER ::= { id-pkix-kp 25 }
+id-pkix-kp-sendProxiedOwner OBJECT IDENTIFIER ::= { id-pkix-kp 26 }
+id-pkix-kp-cmcCA OBJECT IDENTIFIER ::= { id-pkix-kp 27 } -- RFC6402
+id-pkix-kp-cmcRA OBJECT IDENTIFIER ::= { id-pkix-kp 28 } -- RFC6402
+id-pkix-kp-cmcArchive OBJECT IDENTIFIER ::= { id-pkix-kp 29 } -- RFC6402
+id-pkix-kp-bgpsec-router OBJECT IDENTIFIER ::= { id-pkix-kp 30 } -- RFC8209
+-- The following are MSFT EKUs taken from OpenSSL
+id-msft OBJECT IDENTIFIER ::= { 1 3 6 1 4 1 311 }
+id-msft-kp-msCodeInd OBJECT IDENTIFIER ::= { id-msft 2 1 21 }
+id-msft-kp-msCodeCom OBJECT IDENTIFIER ::= { id-msft 2 1 22 }
+id-msft-kp-msCTLSign OBJECT IDENTIFIER ::= { id-msft 10 3 1 }
+id-msft-kp-msSGC OBJECT IDENTIFIER ::= { id-msft 10 3 3 }
+id-msft-kp-msEFS OBJECT IDENTIFIER ::= { id-msft 10 3 4 }
+id-msft-kp-msSmartcardLogin OBJECT IDENTIFIER ::= { id-msft 20 2 2 }
+id-msft-kp-msUPN OBJECT IDENTIFIER ::= { id-msft 20 2 3 }
+
+id-pkix-pe OBJECT IDENTIFIER ::= { id-pkix 1 }
+id-pkix-pe-authorityInfoAccess OBJECT IDENTIFIER ::= { id-pkix-pe 1 }
+
+AccessDescription ::= SEQUENCE {
+ accessMethod OBJECT IDENTIFIER,
+ accessLocation GeneralName
+}
+
+AuthorityInfoAccessSyntax ::= SEQUENCE SIZE (1..MAX) OF AccessDescription
+
+-- RFC 3820 Proxy Certificate Profile
+
+id-pkix-pe-proxyCertInfo OBJECT IDENTIFIER ::= { id-pkix-pe 14 }
+
+id-pkix-pe-subjectInfoAccess OBJECT IDENTIFIER ::= { id-pkix-pe 11 }
+
+SubjectInfoAccessSyntax ::=
+ SEQUENCE SIZE (1..MAX) OF AccessDescription
+
+id-pkix-ppl OBJECT IDENTIFIER ::= { id-pkix 21 }
+
+id-pkix-ppl-anyLanguage OBJECT IDENTIFIER ::= { id-pkix-ppl 0 }
+id-pkix-ppl-inheritAll OBJECT IDENTIFIER ::= { id-pkix-ppl 1 }
+id-pkix-ppl-independent OBJECT IDENTIFIER ::= { id-pkix-ppl 2 }
+
+ProxyPolicy ::= SEQUENCE {
+ policyLanguage OBJECT IDENTIFIER,
+ policy OCTET STRING OPTIONAL
+}
+
+ProxyCertInfo ::= SEQUENCE {
+ pCPathLenConstraint INTEGER (0..4294967295) OPTIONAL, -- really MAX
+ proxyPolicy ProxyPolicy
+}
+
+-- TCG contents:
+
+-- See tcg.asn1 for commentary.
+
+--TCG specific OIDs
+tcg OBJECT IDENTIFIER ::= {joint-iso-itu-t(2) international-organizations(23) tcg(133)}
+tcg-attribute OBJECT IDENTIFIER ::= {tcg 2}
+tcg-kp OBJECT IDENTIFIER ::= {tcg 8}
+
+--TCG Attribute OIDs
+tcg-at-tpmManufacturer OBJECT IDENTIFIER ::= {tcg-attribute 1}
+tcg-at-tpmModel OBJECT IDENTIFIER ::= {tcg-attribute 2}
+tcg-at-tpmVersion OBJECT IDENTIFIER ::= {tcg-attribute 3}
+tcg-at-tpmSpecification OBJECT IDENTIFIER ::= {tcg-attribute 16}
+tcg-at-tpmSecurityAssertions OBJECT IDENTIFIER ::= {tcg-attribute 18}
+
+--TCG Attribute objects
+at-TPMSecurityAssertions _ATTRIBUTE ::= { &Type TPMSecurityAssertions, &id tcg-at-tpmSecurityAssertions }
+at-TPMManufacturer _ATTRIBUTE ::= { &Type AliasUTF8String, --(SIZE (1..STRMAX))-- &id tcg-at-tpmManufacturer }
+at-TPMModel _ATTRIBUTE ::= { &Type AliasUTF8String, --(SIZE (1..STRMAX))-- &id tcg-at-tpmModel }
+at-TPMVersion _ATTRIBUTE ::= { &Type AliasUTF8String, --(SIZE (1..STRMAX))-- &id tcg-at-tpmVersion }
+at-TPMSpecification _ATTRIBUTE ::= { &Type TPMSpecification, &id tcg-at-tpmSpecification }
+
+--TCG Extended Key Usage OIDs
+tcg-kp-EKCertificate OBJECT IDENTIFIER ::= {tcg-kp 1}
+
+-- OIDs not in the module in TCG_IWG_EKCredentialProfile_v2p3_r2_pub but in
+-- TCG_IWG_DevID_v1r2_02dec2020 (missing arc names not mentioned in the TCG
+-- specs):
+tcg-tpm20 OBJECT IDENTIFIER ::= {tcg 1 2} -- this OID is not named in the TCG specs
+tcg-on-ekPermIdSha256 OBJECT IDENTIFIER ::= {tcg 12 1} -- assigner value for PermanentIdentifier SAN
+tcg-cap-verifiedTPMResidency OBJECT IDENTIFIER ::= {tcg 11 1 1} -- policy OID
+tcg-cap-verifiedTPMFixed OBJECT IDENTIFIER ::= {tcg 11 1 2} -- policy OID
+tcg-cap-verifiedTPMRestricted OBJECT IDENTIFIER ::= {tcg 11 1 3} -- policy OID
+
+EKGenerationType ::= ENUMERATED {
+ ekgt-internal (0),
+ ekgt-injected (1),
+ ekgt-internalRevocable(2),
+ ekgt-injectedRevocable(3)
+}
+EKGenerationLocation ::= ENUMERATED {
+ tpmManufacturer (0),
+ platformManufacturer (1),
+ ekCertSigner (2)
+}
+EKCertificateGenerationLocation ::= EKGenerationLocation -- XXX
+EvaluationAssuranceLevel ::= ENUMERATED {
+ ealevell (1),
+ ealevel2 (2),
+ ealevel3 (3),
+ ealevel4 (4),
+ ealevel5 (5),
+ ealevel6 (6),
+ ealevel7 (7)
+}
+SecurityLevel ::= ENUMERATED {
+ sllevel1 (1),
+ sllevel2 (2),
+ sllevel3 (3),
+ sllevel4 (4)
+}
+StrengthOfFunction ::= ENUMERATED {
+ sof-basic (0),
+ sof-medium (1),
+ sof-high (2)
+}
+URIReference ::= SEQUENCE {
+ uniformResourceIdentifier IA5String, -- (SIZE (1..URIMAX))
+ hashAlgorithm AlgorithmIdentifier OPTIONAL,
+ hashValue BIT STRING OPTIONAL
+}
+EvaluationStatus ::= ENUMERATED {
+ designedToMeet (0),
+ evaluationInProgress (1),
+ evaluationCompleted (2)
+}
+
+--tcg specification attributes for tpm
+TPMSpecification ::= SEQUENCE {
+ family UTF8String, -- (SIZE (1..STRMAX))
+ level INTEGER (0..4294967295),
+ revision INTEGER (0..4294967295),
+ ...
+}
+
+
+--common criteria evaluation
+CommonCriteriaMeasures ::= SEQUENCE {
+ version IA5String, -- (SIZE (1..STRMAX)) “2.2” or “3.1”;future syntax defined by CC
+ assurancelevel EvaluationAssuranceLevel,
+ evaluationStatus EvaluationStatus,
+ plus BOOLEAN DEFAULT FALSE,
+ strengthOfFunction [0] IMPLICIT StrengthOfFunction OPTIONAL,
+ profileOid [1] IMPLICIT OBJECT IDENTIFIER OPTIONAL,
+ profileUri [2] IMPLICIT URIReference OPTIONAL,
+ targetOid [3] IMPLICIT OBJECT IDENTIFIER OPTIONAL,
+ targetUri [4] IMPLICIT URIReference OPTIONAL,
+ ...
+}
+
+--fips evaluation
+FIPSLevel ::= SEQUENCE {
+ version IA5String, -- (SIZE (1..STRMAX)) “140-1” or “140-2”
+ level SecurityLevel,
+ plus BOOLEAN DEFAULT FALSE,
+ ...
+}
+
+--tpm security assertions
+TPMVersion ::= INTEGER { tpm-v1(0) }
+TPMSecurityAssertions ::= SEQUENCE {
+ version TPMVersion DEFAULT 0, -- v1
+ fieldUpgradable BOOLEAN DEFAULT FALSE,
+ -- The TCG EK cert profile spec says all these context tags are IMPLICIT,
+ -- but samples in the field have them as EXPLICIT.
+ ekGenerationType [0] EXPLICIT EKGenerationType OPTIONAL,
+ ekGenerationLocation [1] EXPLICIT EKGenerationLocation OPTIONAL,
+ ekCertificateGenerationLocation [2] EXPLICIT EKCertificateGenerationLocation OPTIONAL,
+ ccInfo [3] EXPLICIT CommonCriteriaMeasures OPTIONAL,
+ fipsLevel [4] EXPLICIT FIPSLevel OPTIONAL,
+ iso9000Certified [5] EXPLICIT BOOLEAN DEFAULT FALSE,
+ iso9000Uri IA5String OPTIONAL, -- (SIZE (1..URIMAX))
+ ...
+}
+
+-- Back to OtherName, SingleAttribute, AttributeSet, and Extension
+
+-- XXX Not really the right name for this OID:
+id-pkix-on-pkinit-ms-san OBJECT IDENTIFIER ::=
+ { iso(1) org(3) dod(6) internet(1) private(4)
+ enterprise(1) microsoft(311) 20 2 3 }
+
+-- XXX Work around bug (where we don't know the names of universal types in the
+-- template backend) by creating aliases for universal types we use in IOS
+-- objects.
+AliasUTF8String ::= UTF8String
+AliasIA5String ::= UTF8String
+AliasPrintableString ::= PrintableString
+on-xmppAddr _OTHER-NAME ::= { &id id-pkix-on-xmppAddr, &Type AliasUTF8String }
+on-dnsSRV _OTHER-NAME ::= { &id id-pkix-on-dnsSRV, &Type AliasIA5String }
+on-hardwareModuleName _OTHER-NAME ::= {
+ &id id-pkix-on-hardwareModuleName,
+ &Type HardwareModuleName
+}
+on-permanentIdentifier _OTHER-NAME ::= {
+ &id id-pkix-on-permanentIdentifier,
+ &Type PermanentIdentifier
+}
+on-krb5PrincipalName _OTHER-NAME ::= {
+ &id id-pkix-on-pkinit-san,
+ &Type KRB5PrincipalName
+}
+on-pkinit-ms-san _OTHER-NAME ::= {
+ &id id-pkix-on-pkinit-ms-san,
+ &Type AliasUTF8String
+}
+
+KnownOtherNameTypes _OTHER-NAME ::= {
+ on-xmppAddr
+ | on-dnsSRV
+ | on-hardwareModuleName
+ | on-permanentIdentifier
+ | on-krb5PrincipalName
+ | on-pkinit-ms-san
+}
+
+OtherName ::= OtherName{KnownOtherNameTypes}
+
+X520name ::= DirectoryString --{ub-name}
+X520CommonName ::= DirectoryString --{ub-common-name}
+X520LocalityName ::= DirectoryString --{ub-locality-name}
+X520OrganizationName ::= DirectoryString --{ub-organization-name}
+X520StateOrProvinceName ::= DirectoryString --{ub-state-name}
+X520OrganizationalUnitName ::= DirectoryString --{ub-organizational-unit-name}
+
+at-name _ATTRIBUTE ::= { &Type X520name, &id id-at-name }
+at-surname _ATTRIBUTE ::= { &Type X520name, &id id-at-surname }
+at-givenName _ATTRIBUTE ::= { &Type X520name, &id id-at-givenName }
+at-initials _ATTRIBUTE ::= { &Type X520name, &id id-at-initials }
+at-generationQualifier _ATTRIBUTE ::= { &Type X520name, &id id-at-generationQualifier }
+at-x520CommonName _ATTRIBUTE ::= {&Type X520CommonName, &id id-at-commonName }
+at-x520LocalityName _ATTRIBUTE ::= { &Type X520LocalityName, &id id-at-localityName }
+at-x520StateOrProvinceName _ATTRIBUTE ::= { &Type DirectoryString --{ub-state-name}--, &id id-at-stateOrProvinceName }
+at-x520OrganizationName _ATTRIBUTE ::= { &Type DirectoryString --{ub-organization-name}--, &id id-at-organizationName }
+at-x520OrganizationalUnitName _ATTRIBUTE ::= { &Type DirectoryString --{ub-organizational-unit-name}--, &id id-at-organizationalUnitName }
+at-x520Title _ATTRIBUTE ::= { &Type DirectoryString --{ub-title}--, &id id-at-title }
+at-x520dnQualifier _ATTRIBUTE ::= { &Type AliasPrintableString, &id id-at-dnQualifier }
+at-x520countryName _ATTRIBUTE ::= { &Type AliasPrintableString --(SIZE (2))--, &id id-at-countryName }
+at-x520SerialNumber _ATTRIBUTE ::= {&Type AliasPrintableString --(SIZE (1..ub-serial-number))--, &id id-at-serialNumber }
+at-x520Pseudonym _ATTRIBUTE ::= { &Type DirectoryString --{ub-pseudonym}--, &id id-at-pseudonym }
+at-domainComponent _ATTRIBUTE ::= { &Type AliasIA5String, &id id-domainComponent }
+at-emailAddress _ATTRIBUTE ::= { &Type AliasIA5String --(SIZE (1..ub-emailaddress-length))--, &id id-at-emailAddress }
+
+SupportedAttributes _ATTRIBUTE ::= {
+ at-name
+ | at-surname
+ | at-givenName
+ | at-initials
+ | at-generationQualifier
+ | at-x520CommonName
+ | at-x520LocalityName
+ | at-x520StateOrProvinceName
+ | at-x520OrganizationName
+ | at-x520OrganizationalUnitName
+ | at-x520Title
+ | at-x520dnQualifier
+ | at-x520countryName
+ | at-x520SerialNumber
+ | at-x520Pseudonym
+ | at-domainComponent
+ | at-emailAddress
+ | at-TPMSecurityAssertions
+ | at-TPMManufacturer
+ | at-TPMModel
+ | at-TPMVersion
+ | at-TPMSpecification
+}
+
+SingleAttribute ::= SingleAttribute{SupportedAttributes}
+AttributeSet ::= AttributeSet{SupportedAttributes}
+SubjectDirectoryAttributes ::= SEQUENCE SIZE (1..MAX) OF AttributeSet
+
+ext-AuthorityKeyIdentifier _EXTENSION ::= {
+ &id id-x509-ce-authorityKeyIdentifier,
+ &Critical FALSE,
+ &ExtnType AuthorityKeyIdentifier
+}
+ext-KeyUsage _EXTENSION ::= {
+ &id id-x509-ce-keyUsage,
+ &Critical FALSE,
+ &ExtnType KeyUsage
+}
+ext-SubjectKeyIdentifier _EXTENSION ::= {
+ &id id-x509-ce-subjectKeyIdentifier,
+ &Critical FALSE,
+ &ExtnType SubjectKeyIdentifier
+}
+ext-PrivateKeyUsagePeriod _EXTENSION ::= {
+ &id id-x509-ce-privateKeyUsagePeriod,
+ &Critical FALSE,
+ &ExtnType PrivateKeyUsagePeriod
+}
+ext-CertificatePolicies _EXTENSION ::= {
+ &id id-x509-ce-certificatePolicies,
+ &Critical FALSE,
+ &ExtnType CertificatePolicies
+}
+ext-PolicyMappings _EXTENSION ::= {
+ &id id-x509-ce-policyMappings,
+ &Critical FALSE,
+ &ExtnType PolicyMappings
+}
+ext-SubjectAltName _EXTENSION ::= {
+ &id id-x509-ce-subjectAltName,
+ &Critical FALSE,
+ &ExtnType GeneralNames
+}
+ext-IssuerAltName _EXTENSION ::= {
+ &id id-x509-ce-issuerAltName,
+ &Critical FALSE,
+ &ExtnType GeneralNames
+}
+ext-SubjectDirectoryAttributes _EXTENSION ::= {
+ &id id-x509-ce-subjectDirectoryAttributes,
+ &Critical FALSE,
+ &ExtnType SubjectDirectoryAttributes
+}
+ext-BasicConstraints _EXTENSION ::= {
+ &id id-x509-ce-basicConstraints,
+ &Critical FALSE,
+ &ExtnType BasicConstraints
+}
+ext-NameConstraints _EXTENSION ::= {
+ &id id-x509-ce-nameConstraints,
+ &Critical FALSE,
+ &ExtnType NameConstraints
+}
+SkipCerts ::= INTEGER (0..4294967295)
+PolicyConstraints ::= SEQUENCE {
+ requireExplicitPolicy [0] IMPLICIT SkipCerts OPTIONAL,
+ inhibitPolicyMapping [1] IMPLICIT SkipCerts OPTIONAL
+}
+ext-PolicyConstraints _EXTENSION ::= {
+ &id id-x509-ce-policyConstraints,
+ &Critical FALSE,
+ &ExtnType PolicyConstraints
+}
+ext-ExtKeyUsage _EXTENSION ::= {
+ &id id-x509-ce-extKeyUsage,
+ &Critical FALSE,
+ &ExtnType ExtKeyUsage
+}
+ext-CRLDistributionPoints _EXTENSION ::= {
+ &id id-x509-ce-cRLDistributionPoints,
+ &Critical FALSE,
+ &ExtnType CRLDistributionPoints
+}
+ext-InhibitAnyPolicy _EXTENSION ::= {
+ &id id-x509-ce-inhibitAnyPolicy,
+ &Critical FALSE,
+ &ExtnType SkipCerts
+}
+ext-FreshestCRL _EXTENSION ::= {
+ &id id-x509-ce-freshestCRL,
+ &Critical FALSE,
+ &ExtnType CRLDistributionPoints
+}
+ext-AuthorityInfoAccess _EXTENSION ::= {
+ &id id-pkix-pe-authorityInfoAccess,
+ &Critical FALSE,
+ &ExtnType AuthorityInfoAccessSyntax
+}
+ext-SubjectInfoAccessSyntax _EXTENSION ::= {
+ &id id-pkix-pe-subjectInfoAccess,
+ &Critical FALSE,
+ &ExtnType SubjectInfoAccessSyntax
+}
+ext-ProxyCertInfo _EXTENSION ::= {
+ &id id-pkix-pe-proxyCertInfo,
+ &Critical FALSE,
+ &ExtnType ProxyCertInfo
+}
+HeimPkinitPrincMaxLifeSecs ::= INTEGER (0..4294967295)
+ext-HeimPkinitPrincMaxLife _EXTENSION ::= {
+ &id id-heim-ce-pkinit-princ-max-life,
+ &Critical FALSE,
+ &ExtnType HeimPkinitPrincMaxLifeSecs
+}
+CertExtensions _EXTENSION ::= {
+ ext-AuthorityKeyIdentifier
+ | ext-SubjectKeyIdentifier
+ | ext-KeyUsage
+ | ext-PrivateKeyUsagePeriod
+ | ext-CertificatePolicies
+ | ext-PolicyMappings
+ | ext-SubjectAltName
+ | ext-IssuerAltName
+ | ext-SubjectDirectoryAttributes
+ | ext-BasicConstraints
+ | ext-NameConstraints
+ | ext-PolicyConstraints
+ | ext-ExtKeyUsage
+ | ext-CRLDistributionPoints
+ | ext-InhibitAnyPolicy
+ | ext-FreshestCRL
+ | ext-AuthorityInfoAccess
+ | ext-SubjectInfoAccessSyntax
+ | ext-ProxyCertInfo
+ | ext-HeimPkinitPrincMaxLife
+}
+
+Extension ::= Extension { CertExtensions }
+
+--- U.S. Federal PKI Common Policy Framework
+-- Card Authentication key
+id-uspkicommon-card-id OBJECT IDENTIFIER ::= { 2 16 840 1 101 3 6 6 }
+id-uspkicommon-piv-interim OBJECT IDENTIFIER ::= { 2 16 840 1 101 3 6 9 1 }
+
+--- Netscape extensions
+
+id-netscape OBJECT IDENTIFIER ::=
+ { joint-iso-itu-t(2) country(16) us(840) organization(1) netscape(113730) }
+id-netscape-cert-comment OBJECT IDENTIFIER ::= { id-netscape 1 13 }
+
+--- MS extensions
+
+id-ms-cert-enroll-domaincontroller OBJECT IDENTIFIER ::=
+ { 1 3 6 1 4 1 311 20 2 }
+
+-- This is a duplicate of id-pkix-kp-clientAuth
+-- id-ms-client-authentication OBJECT IDENTIFIER ::=
+-- { 1 3 6 1 5 5 7 3 2 }
+
+-- DER:1e:20:00:44:00:6f:00:6d:00:61:00:69:00:6e:00:43:00:6f:00:6e:00:74:00:72:00:6f:00:6c:00:6c:00:65:00:72
+
+-- Upper bounds:
+
+ub-name INTEGER ::= 32768
+ub-common-name INTEGER ::= 64
+ub-locality-name INTEGER ::= 128
+ub-state-name INTEGER ::= 128
+ub-organization-name INTEGER ::= 64
+ub-organizational-unit-name INTEGER ::= 64
+ub-title INTEGER ::= 64
+ub-serial-number INTEGER ::= 64
+ub-match INTEGER ::= 128
+ub-emailaddress-length INTEGER ::= 255
+ub-common-name-length INTEGER ::= 64
+ub-country-name-alpha-length INTEGER ::= 2
+ub-country-name-numeric-length INTEGER ::= 3
+ub-domain-defined-attributes INTEGER ::= 4
+ub-domain-defined-attribute-type-length INTEGER ::= 8
+ub-domain-defined-attribute-value-length INTEGER ::= 128
+ub-domain-name-length INTEGER ::= 16
+ub-extension-attributes INTEGER ::= 256
+ub-e163-4-number-length INTEGER ::= 15
+ub-e163-4-sub-address-length INTEGER ::= 40
+ub-generation-qualifier-length INTEGER ::= 3
+ub-given-name-length INTEGER ::= 16
+ub-initials-length INTEGER ::= 5
+ub-integer-options INTEGER ::= 256
+ub-numeric-user-id-length INTEGER ::= 32
+ub-organization-name-length INTEGER ::= 64
+ub-organizational-unit-name-length INTEGER ::= 32
+ub-organizational-units INTEGER ::= 4
+ub-pds-name-length INTEGER ::= 16
+ub-pds-parameter-length INTEGER ::= 30
+ub-pds-physical-address-lines INTEGER ::= 6
+ub-postal-code-length INTEGER ::= 16
+ub-pseudonym INTEGER ::= 128
+ub-surname-length INTEGER ::= 40
+ub-terminal-id-length INTEGER ::= 24
+ub-unformatted-address-length INTEGER ::= 180
+ub-x121-address-length INTEGER ::= 16
+
+-- Misc OIDs from RFC5280. We should add related types as well.
+
+-- Policy qualifiers
+id-pkix-qt OBJECT IDENTIFIER ::= { id-pkix 2 }
+id-pkix-qt-cps OBJECT IDENTIFIER ::= { id-pkix-qt 1 }
+id-pkix-qt-unotice OBJECT IDENTIFIER ::= { id-pkix-qt 2 }
+
+-- Access description
+id-pkix-ad OBJECT IDENTIFIER ::= { id-pkix 48 }
+id-pkix-ad-ocsp OBJECT IDENTIFIER ::= { id-pkix-ad 1 }
+id-pkix-ad-caIssuers OBJECT IDENTIFIER ::= { id-pkix-ad 2 }
+id-pkix-ad-timeStamping OBJECT IDENTIFIER ::= { id-pkix-ad 3 }
+id-pkix-ad-caRepository OBJECT IDENTIFIER ::= { id-pkix-ad 5 }
+
+pq-CPS _POLICYQUALIFIERINFO ::= {
+ &id id-pkix-qt-cps,
+ &Type AliasIA5String
+}
+pq-UserNotice _POLICYQUALIFIERINFO ::= {
+ &id id-pkix-qt-unotice,
+ &Type UserNotice
+}
+KnownPolicyQualifiers _POLICYQUALIFIERINFO ::= {
+ pq-CPS
+ | pq-UserNotice
+}
+PolicyQualifierInfo ::= PolicyQualifierInfo{KnownPolicyQualifiers}
+
+END
diff --git a/third_party/heimdal/lib/asn1/rfc2459.opt b/third_party/heimdal/lib/asn1/rfc2459.opt
new file mode 100644
index 0000000..2070568
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/rfc2459.opt
@@ -0,0 +1,12 @@
+--preserve-binary=Name
+--preserve-binary=TBSCertificate
+--preserve-binary=TBSCRLCertList
+--sequence=AttributeValues
+--sequence=CRLDistributionPoints
+--sequence=Extensions
+--sequence=GeneralNames
+--sequence=RDNSequence
+--sequence=Certificates
+--sequence=CertificatePolicies
+--sequence=PolicyQualifierInfos
+--sequence=PolicyMappings
diff --git a/third_party/heimdal/lib/asn1/rfc4108.asn1 b/third_party/heimdal/lib/asn1/rfc4108.asn1
new file mode 100644
index 0000000..34f9396
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/rfc4108.asn1
@@ -0,0 +1,207 @@
+CMSFirmwareWrapper
+ { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1)
+ pkcs-9(9) smime(16) modules(0) cms-firmware-wrap(22) }
+
+DEFINITIONS IMPLICIT TAGS ::= BEGIN
+
+IMPORTS
+ -- We moved HardwareModuleName to avoid circular dependencies if
+ -- we have to have rfc2459 import it from here so we can define an
+ -- object set of OTHER-NAME class.
+ EnvelopedData
+ FROM cms -- [CMS]
+ { iso(1) member-body(2) us(840) rsadsi(113549)
+ pkcs(1) pkcs-9(9) smime(16) modules(0) cms-2004(24) };
+
+
+-- Firmware Package Content Type and Object Identifier
+
+id-ct-firmwarePackage OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) ct(1) 16 }
+
+FirmwarePkgData ::= OCTET STRING
+
+
+-- Firmware Package Signed Attributes and Object Identifiers
+
+id-aa-firmwarePackageID OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) aa(2) 35 }
+
+PreferredPackageIdentifier ::= SEQUENCE {
+ fwPkgID OBJECT IDENTIFIER,
+ verNum INTEGER (0..MAX) }
+
+PreferredOrLegacyPackageIdentifier ::= CHOICE {
+ preferred PreferredPackageIdentifier,
+ legacy OCTET STRING }
+
+PreferredOrLegacyStalePackageIdentifier ::= CHOICE {
+ preferredStaleVerNum INTEGER (0..MAX),
+ legacyStaleVersion OCTET STRING }
+
+FirmwarePackageIdentifier ::= SEQUENCE {
+ name PreferredOrLegacyPackageIdentifier,
+ stale PreferredOrLegacyStalePackageIdentifier OPTIONAL }
+
+
+id-aa-targetHardwareIDs OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) aa(2) 36 }
+
+TargetHardwareIdentifiers ::= SEQUENCE OF OBJECT IDENTIFIER
+
+
+id-aa-decryptKeyID OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) aa(2) 37 }
+
+DecryptKeyIdentifier ::= OCTET STRING
+
+
+id-aa-implCryptoAlgs OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) aa(2) 38 }
+
+ImplementedCryptoAlgorithms ::= SEQUENCE OF OBJECT IDENTIFIER
+
+id-aa-implCompressAlgs OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) aa(2) 43 }
+
+ImplementedCompressAlgorithms ::= SEQUENCE OF OBJECT IDENTIFIER
+
+
+id-aa-communityIdentifiers OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) aa(2) 40 }
+
+HardwareSerialEntry ::= CHOICE {
+ all NULL,
+ single OCTET STRING,
+ block SEQUENCE {
+ low OCTET STRING,
+ high OCTET STRING } }
+
+HardwareModules ::= SEQUENCE {
+ hwType OBJECT IDENTIFIER,
+ hwSerialEntries SEQUENCE OF HardwareSerialEntry }
+
+CommunityIdentifier ::= CHOICE {
+ communityOID OBJECT IDENTIFIER,
+ hwModuleList HardwareModules }
+
+CommunityIdentifiers ::= SEQUENCE OF CommunityIdentifier
+
+id-aa-firmwarePackageInfo OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) aa(2) 42 }
+
+FirmwarePackageInfo ::= SEQUENCE {
+ fwPkgType INTEGER OPTIONAL,
+ dependencies SEQUENCE OF
+ PreferredOrLegacyPackageIdentifier OPTIONAL }
+
+
+-- Firmware Package Unsigned Attributes and Object Identifiers
+
+id-aa-wrappedFirmwareKey OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) aa(2) 39 }
+
+WrappedFirmwareKey ::= EnvelopedData
+
+
+-- Firmware Package Load Receipt Content Type and Object Identifier
+
+id-ct-firmwareLoadReceipt OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) ct(1) 17 }
+
+FWReceiptVersion ::= INTEGER { rfc4108-v1(1) }
+
+FirmwarePackageLoadReceipt ::= SEQUENCE {
+ version FWReceiptVersion DEFAULT 1, -- v1, but asn1_compile doesn't handle this
+ hwType OBJECT IDENTIFIER,
+ hwSerialNum OCTET STRING,
+ fwPkgName PreferredOrLegacyPackageIdentifier,
+ trustAnchorKeyID OCTET STRING OPTIONAL,
+ decryptKeyID [1] OCTET STRING OPTIONAL }
+
+-- Firmware Package Load Error Report Content Type
+-- and Object Identifier
+
+id-ct-firmwareLoadError OBJECT IDENTIFIER ::= {
+ iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) ct(1) 18 }
+
+FWErrorVersion ::= FWReceiptVersion
+
+FirmwarePackageLoadErrorCode ::= ENUMERATED {
+ decodeFailure (1),
+ badContentInfo (2),
+ badSignedData (3),
+ badEncapContent (4),
+ badCertificate (5),
+ badSignerInfo (6),
+ badSignedAttrs (7),
+ badUnsignedAttrs (8),
+ missingContent (9),
+ noTrustAnchor (10),
+ notAuthorized (11),
+ badDigestAlgorithm (12),
+ badSignatureAlgorithm (13),
+ unsupportedKeySize (14),
+ signatureFailure (15),
+ contentTypeMismatch (16),
+ badEncryptedData (17),
+ unprotectedAttrsPresent (18),
+ badEncryptContent (19),
+ badEncryptAlgorithm (20),
+ missingCiphertext (21),
+ noDecryptKey (22),
+ decryptFailure (23),
+ badCompressAlgorithm (24),
+ missingCompressedContent (25),
+ decompressFailure (26),
+ wrongHardware (27),
+ stalePackage (28),
+ notInCommunity (29),
+ unsupportedPackageType (30),
+ missingDependency (31),
+ wrongDependencyVersion (32),
+ insufficientMemory (33),
+ badFirmware (34),
+ unsupportedParameters (35),
+ breaksDependency (36),
+ otherError (99) }
+
+VendorLoadErrorCode ::= INTEGER
+
+CurrentFWConfig ::= SEQUENCE {
+ fwPkgType INTEGER OPTIONAL,
+ fwPkgName PreferredOrLegacyPackageIdentifier }
+
+FirmwarePackageLoadError ::= SEQUENCE {
+ version FWErrorVersion DEFAULT 1, -- v1, but see above
+ hwType OBJECT IDENTIFIER,
+ hwSerialNum OCTET STRING,
+ errorCode FirmwarePackageLoadErrorCode,
+ vendorErrorCode VendorLoadErrorCode OPTIONAL,
+ fwPkgName PreferredOrLegacyPackageIdentifier OPTIONAL,
+ config [1] SEQUENCE OF CurrentFWConfig OPTIONAL }
+
+-- Other Name syntax for Hardware Module Name
+
+id-on-hardwareModuleName OBJECT IDENTIFIER ::= {
+ iso(1) identified-organization(3) dod(6) internet(1) security(5)
+ mechanisms(5) pkix(7) on(8) 4 }
+
+-- Moved to rfc2459.asn1 so we can have the OtherName type decode it
+-- automatically:
+--HardwareModuleName ::= SEQUENCE {
+-- hwType OBJECT IDENTIFIER,
+-- hwSerialNum OCTET STRING }
+
+END
diff --git a/third_party/heimdal/lib/asn1/roken_rename.h b/third_party/heimdal/lib/asn1/roken_rename.h
new file mode 100644
index 0000000..76e108a
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/roken_rename.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __roken_rename_h__
+#define __roken_rename_h__
+
+#ifndef HAVE_STRTOLL
+#define strtoll rk_strtoll
+#endif
+#ifndef HAVE_STRTOULL
+#define strtoull rk_strtoull
+#endif
+
+#endif /* __roken_rename_h__ */
diff --git a/third_party/heimdal/lib/asn1/setchgpw2.asn1 b/third_party/heimdal/lib/asn1/setchgpw2.asn1
new file mode 100644
index 0000000..2f52cb1
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/setchgpw2.asn1
@@ -0,0 +1,193 @@
+-- $Id$
+
+SETCHGPW2 DEFINITIONS ::=
+BEGIN
+
+IMPORTS PrincipalName, Realm, ENCTYPE FROM krb5;
+
+ProtocolErrorCode ::= ENUMERATED {
+ generic-error(0),
+ unsupported-major-version(1),
+ unsupported-minor-version(2),
+ unsupported-operation(3),
+ authorization-failed(4),
+ initial-ticket-required(5),
+ target-principal-unknown(6),
+ ...
+}
+
+Key ::= SEQUENCE {
+ enc-type[0] INTEGER,
+ key[1] OCTET STRING,
+ ...
+}
+
+Language-Tag ::= UTF8String -- Constrained by RFC3066
+
+LangTaggedText ::= SEQUENCE {
+ language[0] Language-Tag OPTIONAL,
+ text[1] UTF8String,
+ ...
+}
+
+-- NULL Op
+
+Req-null ::= NULL
+Rep-null ::= NULL
+Err-null ::= NULL
+
+-- Change password
+Req-change-pw ::= SEQUENCE {
+ old-pw[0] UTF8String,
+ new-pw[1] UTF8String OPTIONAL,
+ etypes[2] SEQUENCE OF ENCTYPE OPTIONAL,
+ ...
+}
+
+Rep-change-pw ::= SEQUENCE {
+ info-text[0] UTF8String OPTIONAL,
+ new-pw[1] UTF8String OPTIONAL,
+ etypes[2] SEQUENCE OF ENCTYPE OPTIONAL
+}
+
+Err-change-pw ::= SEQUENCE {
+ help-text[0] UTF8String OPTIONAL,
+ code[1] ENUMERATED {
+ generic(0),
+ wont-generate-new-pw(1),
+ old-pw-incorrect(2),
+ new-pw-rejected-geneneric(3),
+ pw-change-too-short(4),
+ ...
+ },
+ suggested-new-pw[2] UTF8String OPTIONAL,
+ ...
+}
+
+-- Change/Set keys
+Req-set-keys ::= SEQUENCE {
+ etypes[0] SEQUENCE OF ENCTYPE,
+ entropy[1] OCTET STRING,
+ ...
+}
+
+Rep-set-keys ::= SEQUENCE {
+ info-text[0] UTF8String OPTIONAL,
+ kvno[1] INTEGER,
+ keys[2] SEQUENCE OF Key,
+ aliases[3] SEQUENCE OF SEQUENCE {
+ name[0] PrincipalName,
+ realm[1] Realm OPTIONAL,
+ ...
+ },
+ ...
+}
+
+Err-set-keys ::= SEQUENCE {
+ help-text[0] UTF8String OPTIONAL,
+ enctypes[1] SEQUENCE OF ENCTYPE OPTIONAL,
+ code[1] ENUMERATED {
+ etype-no-support(0),
+ ...
+ },
+ ...
+}
+
+-- Get password policy
+Req-get-pw-policy ::= NULL
+
+Rep-get-pw-policy ::= SEQUENCE {
+ help-text[0] UTF8String OPTIONAL,
+ policy-name[1] UTF8String OPTIONAL,
+ description[2] UTF8String OPTIONAL,
+ ...
+}
+
+Err-get-pw-policy ::= NULL
+
+-- Get principal aliases
+Req-get-princ-aliases ::= NULL
+
+Rep-get-princ-aliases ::= SEQUENCE {
+ help-text[0] UTF8String OPTIONAL,
+ aliases[1] SEQUENCE OF SEQUENCE {
+ name[0] PrincipalName,
+ realm[1] Realm OPTIONAL,
+ ...
+ } OPTIONAL,
+ ...
+}
+
+Err-get-princ-aliases ::= NULL
+
+-- Get list of encryption types supported by KDC for new types
+Req-get-supported-etypes ::= NULL
+
+Rep-get-supported-etypes ::= SEQUENCE OF ENCTYPE
+
+Err-get-supported-etypes ::= NULL
+
+-- Choice switch
+
+Op-req ::= CHOICE {
+ null[0] Req-null,
+ change-pw[1] Req-change-pw,
+ set-keys[2] Req-set-keys,
+ get-pw-policy[3] Req-get-pw-policy,
+ get-princ-aliases[4] Req-get-princ-aliases,
+ get-supported-etypes[5] Req-get-supported-etypes,
+ ...
+}
+
+Op-rep ::= CHOICE {
+ null[0] Rep-null,
+ change-pw[1] Rep-change-pw,
+ set-keys[2] Rep-set-keys,
+ get-pw-policy[3] Rep-get-pw-policy,
+ get-princ-aliases[4] Rep-get-princ-aliases,
+ get-supported-etypes[5] Rep-get-supported-etypes,
+ ...
+}
+
+Op-error ::= CHOICE {
+ null[0] Err-null,
+ change-pw[1] Err-change-pw,
+ set-keys[2] Err-set-keys,
+ get-pw-policy[3] Err-get-pw-policy,
+ get-princ-aliases[4] Err-get-princ-aliases,
+ get-supported-etypes[5] Err-get-supported-etypes,
+ ...
+}
+
+
+Request ::= [ APPLICATION 0 ] SEQUENCE {
+ pvno-major[0] INTEGER DEFAULT 2,
+ pvno-minor[1] INTEGER DEFAULT 0,
+ languages[2] SEQUENCE OF Language-Tag OPTIONAL,
+ targ-name[3] PrincipalName OPTIONAL,
+ targ-realm[4] Realm OPTIONAL,
+ operation[5] Op-Req,
+ ...
+}
+
+Response ::= [ APPLICATION 1 ] SEQUENCE {
+ pvno-major[0] INTEGER DEFAULT 2,
+ pvno-minor[1] INTEGER DEFAULT 0,
+ language[2] Language-Tag DEFAULT "i-default",
+ result[3] Op-rep OPTIONAL,
+ ...
+}
+
+Error-Response ::= [ APPLICATION 2 ] SEQUENCE {
+ pvno-major[0] INTEGER DEFAULT 2,
+ pvno-minor[1] INTEGER DEFAULT 0,
+ language[2] Language-Tag DEFAULT "i-default",
+ error-code[3] ProtocolErrorCode,
+ help-text[4] UTF8String OPTIONAL,
+ op-error[5] Op-error OP-ERROR,
+ ...
+}
+
+END
+
+-- etags -r '/\([A-Za-z][-A-Za-z0-9]*\).*::=/\1/' setchgpw2.asn1
diff --git a/third_party/heimdal/lib/asn1/symbol.c b/third_party/heimdal/lib/asn1/symbol.c
new file mode 100644
index 0000000..920ed16
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/symbol.c
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gen_locl.h"
+#include "lex.h"
+#include "lex.h"
+
+static Hashtab *htab;
+
+struct symhead symbols;
+
+static int
+cmp(void *a, void *b)
+{
+ Symbol *s1 = (Symbol *) a;
+ Symbol *s2 = (Symbol *) b;
+
+ return strcmp(s1->name, s2->name);
+}
+
+static unsigned
+hash(void *a)
+{
+ Symbol *s = (Symbol *) a;
+
+ return hashjpw(s->name);
+}
+
+void
+initsym(void)
+{
+ htab = hashtabnew(101, cmp, hash);
+}
+
+
+void
+output_name(char *s)
+{
+ char *p;
+
+ for (p = s; *p; ++p)
+ if (*p == '-' || *p == '.')
+ *p = '_';
+}
+
+Symbol *
+addsym(char *name)
+{
+ Symbol key, *s;
+
+ key.name = name;
+ s = (Symbol *) hashtabsearch(htab, (void *) &key);
+ if (s == NULL) {
+ s = (Symbol *) ecalloc(1, sizeof(*s));
+ s->name = name;
+ s->gen_name = estrdup(name);
+ output_name(s->gen_name);
+ s->stype = SUndefined;
+ hashtabadd(htab, s);
+ //HEIM_TAILQ_INSERT_TAIL(&symbols, s, symlist);
+ do {
+ if (((s)->symlist.tqe_next = (&symbols)->tqh_first) != NULL)
+ (&symbols)->tqh_first->symlist.tqe_prev = &(s)->symlist.tqe_next;
+ else
+ (&symbols)->tqh_last = &(s)->symlist.tqe_next;
+ (&symbols)->tqh_first = (s);
+ (s)->symlist.tqe_prev = &(&symbols)->tqh_first;
+ } while (0);
+ }
+ return s;
+}
+
+Symbol *
+getsym(char *name)
+{
+ Symbol key;
+
+ key.name = name;
+ return (Symbol *) hashtabsearch(htab, (void *) &key);
+}
+
+static int
+checkfunc(void *ptr, void *arg)
+{
+ Symbol *s = ptr;
+ if (s->stype == SUndefined) {
+ lex_error_message("%s is still undefined\n", s->name);
+ *(int *) arg = 1;
+ }
+ return 0;
+}
+
+int
+checkundefined(void)
+{
+ int f = 0;
+ hashtabforeach(htab, checkfunc, &f);
+ return f;
+}
+
+#if 0
+static int
+generate_1type(void *ptr, void *arg)
+{
+ Symbol *s = ptr;
+
+ if (s->stype == Stype && s->type)
+ generate_type(s);
+ return 0;
+}
+#endif
+
+void
+generate_types(void)
+{
+ Symbol *s;
+
+ if (checkundefined())
+ errx(1, "Some types are undefined");
+ HEIM_TAILQ_FOREACH_REVERSE(s, &symbols, symhead, symlist) {
+ if (s->stype == Stype && s->type)
+ generate_type(s);
+ }
+ //hashtabforeach(htab, generate_1type, NULL);
+}
+
+void
+emitted_declaration(const Symbol *s)
+{
+ ((Symbol *)(uintptr_t)s)->emitted_declaration = 1;
+}
+
+void
+emitted_definition(const Symbol *s)
+{
+ ((Symbol *)(uintptr_t)s)->emitted_definition = 1;
+}
+
+void
+emitted_tag_enums(const Symbol *s)
+{
+ ((Symbol *)(uintptr_t)s)->emitted_tag_enums = 1;
+}
diff --git a/third_party/heimdal/lib/asn1/symbol.h b/third_party/heimdal/lib/asn1/symbol.h
new file mode 100644
index 0000000..8a24e25
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/symbol.h
@@ -0,0 +1,265 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef _SYMBOL_H
+#define _SYMBOL_H
+
+#include <heimqueue.h>
+
+enum typetype {
+ TBitString,
+ TBoolean,
+ TChoice,
+ TEnumerated,
+ TGeneralString,
+ TTeletexString,
+ TGeneralizedTime,
+ TIA5String,
+ TInteger,
+ TNull,
+ TOID,
+ TOctetString,
+ TPrintableString,
+ TSequence,
+ TSequenceOf,
+ TSet,
+ TSetOf,
+ TTag,
+ TType,
+ TUTCTime,
+ TUTF8String,
+ TBMPString,
+ TUniversalString,
+ TVisibleString
+};
+
+typedef enum typetype Typetype;
+
+struct type;
+struct value;
+struct typereference;
+
+struct value {
+ enum { booleanvalue,
+ nullvalue,
+ integervalue,
+ stringvalue,
+ objectidentifiervalue
+ } type;
+ union {
+ int booleanvalue;
+ int64_t integervalue;
+ char *stringvalue;
+ struct objid *objectidentifiervalue;
+ } u;
+ struct symbol *s;
+};
+
+struct member {
+ char *name;
+ char *gen_name;
+ char *label;
+ int64_t val;
+ int optional;
+ int ellipsis;
+ struct type *type;
+ HEIM_TAILQ_ENTRY(member) members;
+ struct value *defval;
+};
+
+typedef struct member Member;
+
+HEIM_TAILQ_HEAD(memhead, member);
+
+struct symbol;
+
+struct tagtype {
+ int tagclass;
+ int tagvalue;
+ enum { TE_IMPLICIT, TE_EXPLICIT } tagenv;
+};
+
+struct range {
+ /*
+ * We can't represent unsigned 64-bit ranges because max might be
+ * negative...
+ */
+ int64_t min;
+ int64_t max;
+};
+
+enum ctype { CT_CONTENTS, CT_USER, CT_TABLE_CONSTRAINT, CT_RANGE } ;
+
+struct constraint_spec;
+
+struct iosclassfield {
+ char *name;
+ struct type *type;
+ struct value *defval;
+ HEIM_TAILQ_ENTRY(iosclassfield) fields;
+ unsigned long id;
+ unsigned int optional:1;
+ unsigned int unique:1;
+};
+
+typedef struct iosclassfield Field;
+HEIM_TAILQ_HEAD(fieldhead, iosclassfield);
+
+struct iosobjectfield {
+ char *name;
+ struct type *type;
+ struct value *value;
+ HEIM_TAILQ_ENTRY(iosobjectfield) objfields;
+ unsigned long id;
+};
+
+typedef struct iosobjectfield ObjectField;
+HEIM_TAILQ_HEAD(objfieldhead, iosobjectfield);
+
+struct iosclass {
+ struct symbol *symbol;
+ struct fieldhead *fields;
+ unsigned long id;
+};
+
+typedef struct iosclass IOSClass;
+
+struct iosobject {
+ struct symbol *symbol;
+ struct objfieldhead *objfields;
+ ObjectField *typeidf;
+ IOSClass *iosclass;
+ HEIM_TAILQ_ENTRY(iosobject) objects;
+ unsigned long id;
+ unsigned int ellipsis:1;
+ unsigned int optional:1;
+};
+
+typedef struct iosobject IOSObject;
+HEIM_TAILQ_HEAD(objectshead, iosobject);
+
+struct iosobjectset {
+ struct symbol *symbol;
+ IOSClass *iosclass;
+ struct objectshead *objects;
+ unsigned long id;
+};
+
+typedef struct iosobjectset IOSObjectSet;
+
+struct typereference {
+ /*
+ * For now we don't support link fields, so we don't support chains of more
+ * than one field.
+ */
+ IOSClass *iosclass;
+ Field *field;
+};
+
+struct type {
+ Typetype type;
+ struct memhead *members;
+ struct symbol *symbol;
+ struct type *subtype;
+ struct typereference typeref; /* For type fields */
+ IOSClass *formal_parameter;
+ IOSObjectSet *actual_parameter;
+ struct tagtype tag;
+ struct range *range;
+ struct constraint_spec *constraint;
+ unsigned long id;
+};
+
+typedef struct type Type;
+
+struct component_relation_constraint {
+ char *objectname;
+ char *membername;
+};
+
+struct constraint_spec {
+ enum ctype ctype;
+ union {
+ struct {
+ Type *type;
+ struct value *encoding;
+ struct component_relation_constraint crel;
+ } content;
+ struct range *range;
+ } u;
+};
+
+struct objid {
+ const char *label;
+ int value;
+ struct objid *next;
+};
+
+struct symbol {
+ char *name;
+ char *gen_name;
+ enum { SUndefined, SValue, Stype, Sparamtype, Sclass, Sobj, Sobjset } stype;
+ struct value *value;
+ Type *type;
+ IOSClass *iosclass;
+ IOSObject *object;
+ IOSObjectSet *objectset;
+ HEIM_TAILQ_ENTRY(symbol) symlist;
+ unsigned int emitted_declaration:1;
+ unsigned int emitted_definition:1;
+ unsigned int emitted_tag_enums:1;
+ unsigned int emitted_template:1;
+};
+
+typedef struct symbol Symbol;
+
+//HEIM_TAILQ_HEAD(symhead, symbol);
+struct symhead {
+ struct symbol *tqh_first;
+ struct symbol **tqh_last;
+};
+
+extern struct symhead symbols;
+
+void initsym (void);
+Symbol *addsym (char *);
+Symbol *getsym(char *name);
+void output_name (char *);
+int checkundefined(void);
+void generate_types(void);
+void emitted_declaration(const Symbol *);
+void emitted_definition(const Symbol *);
+void emitted_tag_enums(const Symbol *);
+#endif
diff --git a/third_party/heimdal/lib/asn1/tcg.asn1 b/third_party/heimdal/lib/asn1/tcg.asn1
new file mode 100644
index 0000000..14129b0
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/tcg.asn1
@@ -0,0 +1,42 @@
+TCG DEFINITIONS ::= BEGIN
+
+-- BEGIN Heimdal commentary
+--
+-- Copy-pasted from section 4 of
+-- https://trustedcomputinggroup.org/wp-content/uploads/TCG_IWG_EKCredentialProfile_v2p3_r2_pub.pdf
+-- https://trustedcomputinggroup.org/wp-content/uploads/Credential_Profile_EK_V2.0_R14_published.pdf
+-- and adjusted to compile as follows:
+--
+-- - Due to limitations of the Heimdal compiler we've moved all of this
+-- module's contents to rfc2459.asn1.
+--
+-- - Extensibility markers added to all SEQUENCEs as per the TCG's spec they
+-- reserve the right to add fields in the future.
+-- - Information Object System annotations commented out (Heimdal does not
+-- support them)
+--
+-- - Types sorted topologically (at the time I did that the Heimdal ASN.1
+-- compiler wouldn't do that on its own)
+--
+-- - Two otherwise equal ENUMERATED types share a definition now (at the time
+-- the Heimdal ASN.1 compiler did not prefix labels of ENUMERATED types)
+--
+-- A small note for anyone whoever finds this: do not add complex structures as
+-- DN attributes, or, indeed, never add DN attributes again. If some metadata
+-- is name-like, then add a subjectAlternativeName otherName for it, otherwise
+-- add a certificate extension to carry that metadata. And, for any name-like
+-- metadata, always always include query and display syntax for it.
+--
+-- Anyone designing anything but the simplest schema in ASN.1 should have to
+-- learn a bit more about ASN.1 and/or get a review from ASN.1 experts.
+--
+-- Anyone designing anything but the simplest x.509 extensions should have to
+-- learn a bit more about ASN.1 and x.509 and/or get a review from x.509
+-- experts.
+--
+-- Note that a module OID was not provided. Indeed, a valid, complete ASN.1
+-- module was not provided.
+--
+-- END Heimdal commentary (though some minor Heimdal commentary appears below)
+
+END
diff --git a/third_party/heimdal/lib/asn1/template.c b/third_party/heimdal/lib/asn1/template.c
new file mode 100644
index 0000000..7a19e74
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/template.c
@@ -0,0 +1,3075 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 - 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+#include <com_err.h>
+#include <vis.h>
+#include <vis-extras.h>
+#include <heimbase.h>
+
+#ifndef ENOTSUP
+/* Very old MSVC CRTs don't have ENOTSUP */
+#define ENOTSUP EINVAL
+#endif
+
+struct asn1_type_func asn1_template_prim[A1T_NUM_ENTRY] = {
+#define el(name, type) { \
+ (asn1_type_encode)der_put_##name, \
+ (asn1_type_decode)der_get_##name, \
+ (asn1_type_length)der_length_##name, \
+ (asn1_type_copy)der_copy_##name, \
+ (asn1_type_release)der_free_##name, \
+ (asn1_type_print)der_print_##name, \
+ sizeof(type) \
+ }
+#define elber(name, type) { \
+ (asn1_type_encode)der_put_##name, \
+ (asn1_type_decode)der_get_##name##_ber, \
+ (asn1_type_length)der_length_##name, \
+ (asn1_type_copy)der_copy_##name, \
+ (asn1_type_release)der_free_##name, \
+ (asn1_type_print)der_print_##name, \
+ sizeof(type) \
+ }
+ el(integer, int),
+ el(heim_integer, heim_integer),
+ el(integer, int),
+ el(integer64, int64_t),
+ el(unsigned, unsigned),
+ el(unsigned64, uint64_t),
+ el(general_string, heim_general_string),
+ el(octet_string, heim_octet_string),
+ elber(octet_string, heim_octet_string),
+ el(ia5_string, heim_ia5_string),
+ el(bmp_string, heim_bmp_string),
+ el(universal_string, heim_universal_string),
+ el(printable_string, heim_printable_string),
+ el(visible_string, heim_visible_string),
+ el(utf8string, heim_utf8_string),
+ el(generalized_time, time_t),
+ el(utctime, time_t),
+ el(bit_string, heim_bit_string),
+ { (asn1_type_encode)der_put_boolean, (asn1_type_decode)der_get_boolean,
+ (asn1_type_length)der_length_boolean, (asn1_type_copy)der_copy_integer,
+ (asn1_type_release)der_free_integer, (asn1_type_print)der_print_boolean,
+ sizeof(int)
+ },
+ el(oid, heim_oid),
+ el(general_string, heim_general_string),
+#undef el
+#undef elber
+};
+
+size_t
+_asn1_sizeofType(const struct asn1_template *t)
+{
+ return t->offset;
+}
+
+/*
+ * Here is abstraction to not so well evil fact of bit fields in C,
+ * they are endian dependent, so when getting and setting bits in the
+ * host local structure we need to know the endianness of the host.
+ *
+ * Its not the first time in Heimdal this have bitten us, and some day
+ * we'll grow up and use #defined constant, but bit fields are still
+ * so pretty and shiny.
+ */
+
+static void
+_asn1_bmember_get_bit(const unsigned char *p, void *data,
+ unsigned int bit, size_t size)
+{
+ unsigned int localbit = bit % 8;
+ if ((*p >> (7 - localbit)) & 1) {
+#ifdef WORDS_BIGENDIAN
+ *(unsigned int *)data |= (1u << ((size * 8) - bit - 1));
+#else
+ *(unsigned int *)data |= (1u << bit);
+#endif
+ }
+}
+
+int
+_asn1_bmember_isset_bit(const void *data, unsigned int bit, size_t size)
+{
+#ifdef WORDS_BIGENDIAN
+ if ((*(unsigned int *)data) & (1u << ((size * 8) - bit - 1)))
+ return 1;
+ return 0;
+#else
+ if ((*(unsigned int *)data) & (1u << bit))
+ return 1;
+ return 0;
+#endif
+}
+
+void
+_asn1_bmember_put_bit(unsigned char *p, const void *data, unsigned int bit,
+ size_t size, unsigned int *bitset)
+{
+ unsigned int localbit = bit % 8;
+
+ if (_asn1_bmember_isset_bit(data, bit, size)) {
+ *p |= (1u << (7 - localbit));
+ if (*bitset == 0)
+ *bitset = (7 - localbit) + 1;
+ }
+}
+
+/*
+ * Utility function to tell us if the encoding of some type per its template
+ * will have an outer tag. This is needed when the caller wants to slap on an
+ * IMPLICIT tag: if the inner type has a tag then we need to replace it.
+ */
+static int
+is_tagged(const struct asn1_template *t)
+{
+ size_t elements = A1_HEADER_LEN(t);
+
+ t += A1_HEADER_LEN(t);
+ if (elements != 1)
+ return 0;
+ switch (t->tt & A1_OP_MASK) {
+ case A1_OP_SEQOF: return 0;
+ case A1_OP_SETOF: return 0;
+ case A1_OP_BMEMBER: return 0;
+ case A1_OP_PARSE: return 0;
+ case A1_OP_TAG: return 1;
+ case A1_OP_CHOICE: return 1;
+ case A1_OP_TYPE: return 1;
+ case A1_OP_TYPE_EXTERN: {
+ const struct asn1_type_func *f = t->ptr;
+
+ /*
+ * XXX Add a boolean to struct asn1_type_func to tell us if the type is
+ * tagged or not. Basically, it's not tagged if it's primitive.
+ */
+ if (f->encode == (asn1_type_encode)encode_heim_any ||
+ f->encode == (asn1_type_encode)encode_HEIM_ANY)
+ return 0;
+ abort(); /* XXX */
+ }
+ default: abort();
+ }
+}
+
+static size_t
+inner_type_taglen(const struct asn1_template *t)
+{
+ size_t elements = A1_HEADER_LEN(t);
+
+ t += A1_HEADER_LEN(t);
+ if (elements != 1)
+ return 0;
+ switch (t->tt & A1_OP_MASK) {
+ case A1_OP_SEQOF: return 0;
+ case A1_OP_SETOF: return 0;
+ case A1_OP_BMEMBER: return 0;
+ case A1_OP_PARSE: return 0;
+ case A1_OP_CHOICE: return 1;
+ case A1_OP_TYPE: return inner_type_taglen(t->ptr);
+ case A1_OP_TAG: return der_length_tag(A1_TAG_TAG(t->tt));
+ case A1_OP_TYPE_EXTERN: {
+ const struct asn1_type_func *f = t->ptr;
+
+ /*
+ * XXX Add a boolean to struct asn1_type_func to tell us if the type is
+ * tagged or not. Basically, it's not tagged if it's primitive.
+ */
+ if (f->encode == (asn1_type_encode)encode_heim_any ||
+ f->encode == (asn1_type_encode)encode_HEIM_ANY)
+ return 0;
+ abort(); /* XXX */
+ }
+ default: abort();
+#ifdef WIN32
+ _exit(0); /* Quiet VC */
+#endif
+ }
+}
+
+/*
+ * Compare some int of unknown size in a type ID field to the int value in
+ * some IOS object's type ID template entry.
+ *
+ * This should be called with a `A1_TAG_T(ASN1_C_UNIV, PRIM, UT_Integer)'
+ * template as the `ttypeid'.
+ */
+static int
+typeid_int_cmp(const void *intp,
+ int64_t i,
+ const struct asn1_template *ttypeid)
+{
+ const struct asn1_template *tint = ttypeid->ptr;
+
+ if ((tint[1].tt & A1_OP_MASK) != A1_OP_PARSE)
+ return -1;
+ if (A1_PARSE_TYPE(tint[1].tt) != A1T_INTEGER &&
+ A1_PARSE_TYPE(tint[1].tt) != A1T_UNSIGNED &&
+ A1_PARSE_TYPE(tint[1].tt) != A1T_INTEGER64 &&
+ A1_PARSE_TYPE(tint[1].tt) != A1T_UNSIGNED64 &&
+ A1_PARSE_TYPE(tint[1].tt) != A1T_IMEMBER)
+ return -1;
+ switch (tint[0].offset) {
+ case 8: return i - *(const int64_t *)intp;
+ case 4: return i - *(const int32_t *)intp;
+ default: return -1;
+ }
+}
+
+/*
+ * Map a logical SET/SEQUENCE member to a template entry.
+ *
+ * This should really have been done by the compiler, but clearly it wasn't.
+ *
+ * The point is that a struct type's template may be littered with entries that
+ * don't directly correspond to a struct field (SET/SEQUENCE member), so we
+ * have to count just the ones that do to get to the one we want.
+ */
+static const struct asn1_template *
+template4member(const struct asn1_template *t, size_t f)
+{
+ size_t n = (uintptr_t)t->ptr;
+ size_t i;
+
+ for (i = 0, t++; i < n; t++, i++) {
+ switch (t->tt & A1_OP_MASK) {
+ case A1_OP_TAG:
+ case A1_OP_TYPE:
+ case A1_OP_TYPE_EXTERN:
+ if (f-- == 0)
+ return t;
+ continue;
+ case A1_OP_OPENTYPE_OBJSET:
+ case A1_OP_NAME:
+ return NULL;
+ default:
+ continue;
+ }
+ }
+ return NULL;
+}
+
+/*
+ * Attempt to decode known open type alternatives into a CHOICE-like
+ * discriminated union.
+ *
+ * Arguments:
+ *
+ * - object set template
+ * - decoder flags
+ * - pointer to memory object (C struct) to decode into
+ * - template for type ID field of `data'
+ * - template for open type field of `data' (an octet string or HEIM_ANY)
+ *
+ * Returns:
+ *
+ * - 0
+ * - ENOMEM
+ *
+ * Other errors in decoding open type values are ignored, but applications can
+ * note that an error must have occurred. (Perhaps we should generate a `ret'
+ * field for the discriminated union we decode into that we could use to
+ * indicate what went wrong with decoding an open type value? The application
+ * can always try to decode itself to find out what the error was, but the
+ * whole point is to save the developer the bother of writing code to decode
+ * open type values. Then again, the specific cause of any one decode failure
+ * is not usually very important to users, so it's not very important to
+ * applications either.)
+ *
+ * Here `data' is something like this:
+ *
+ * typedef struct SingleAttribute {
+ * heim_oid type; // <--- decoded already
+ * HEIM_ANY value; // <--- decoded already
+ * // We must set this:
+ * // vvvvvvvv
+ * struct {
+ * enum {
+ * choice_SingleAttribute_iosnumunknown = 0,
+ * choice_SingleAttribute_iosnum_id_at_name,
+ * ..
+ * choice_SingleAttribute_iosnum_id_at_emailAddress,
+ * } element; // <--- map type ID to enum
+ * union {
+ * X520name* at_name;
+ * X520name* at_surname;
+ * ..
+ * AliasIA5String* at_emailAddress;
+ * } u; // <--- alloc and decode val above into this
+ * } _ioschoice_value;
+ * } SingleAttribute;
+ *
+ * or
+ *
+ * typedef struct AttributeSet {
+ * heim_oid type; // <--- decoded already
+ * struct AttributeSet_values {
+ * unsigned int len; // <--- decoded already
+ * HEIM_ANY *val; // <--- decoded already
+ * } values;
+ * // We must set this:
+ * // vvvvvvvv
+ * struct {
+ * enum { choice_AttributeSet_iosnumunknown = 0,
+ * choice_AttributeSet_iosnum_id_at_name,
+ * choice_AttributeSet_iosnum_id_at_surname,
+ * ..
+ * choice_AttributeSet_iosnum_id_at_emailAddress,
+ * } element; // <--- map type ID to enum
+ * unsigned int len; // <--- set len to len as above
+ * union {
+ * X520name *at_name;
+ * X520name *at_surname;
+ * ..
+ * AliasIA5String *at_emailAddress;
+ * } *val; // <--- alloc and decode vals above into this
+ * } _ioschoice_values;
+ * } AttributeSet;
+ */
+static int
+_asn1_decode_open_type(const struct asn1_template *t,
+ unsigned flags,
+ void *data,
+ const struct asn1_template *ttypeid,
+ const struct asn1_template *topentype)
+{
+ const struct asn1_template *ttypeid_univ = ttypeid;
+ const struct asn1_template *tactual_type;
+ const struct asn1_template *tos = t->ptr;
+ size_t sz, n;
+ size_t i = 0;
+ unsigned int *lenp = NULL; /* Pointer to array length field */
+ unsigned int len = 1; /* Array length */
+ void **dp = NULL; /* Decoded open type struct pointer */
+ int *elementp; /* Choice enum pointer */
+ int typeid_is_oid = 0;
+ int typeid_is_int = 0;
+ int ret = 0;
+
+ /*
+ * NOTE: Here expressions like `DPO(data, t->offset + ...)' refer to parts
+ * of a _ioschoice_<fieldName> struct field of `data'.
+ *
+ * Expressions like `DPO(data, topentype->offset + ...)' refer to
+ * the open type field in `data', which is either a `heim_any', a
+ * `heim_octet_string', or an array of one of those.
+ *
+ * Expressions like `DPO(data, ttypeid->offset)' refer to the open
+ * type's type ID field in `data'.
+ */
+
+ /*
+ * Minimal setup:
+ *
+ * - set type choice to choice_<type>_iosnumunknown (zero).
+ * - set union value to zero
+ *
+ * We need a pointer to the choice ID:
+ *
+ * typedef struct AttributeSet {
+ * heim_oid type; // <--- decoded already
+ * struct AttributeSet_values {
+ * unsigned int len; // <--- decoded already
+ * HEIM_ANY *val; // <--- decoded already
+ * } values;
+ * struct {
+ * enum { choice_AttributeSet_iosnumunknown = 0,
+ * -----------> ...
+ * } element; // HERE
+ * ...
+ * } ...
+ * }
+ *
+ * XXX NOTE: We're assuming that sizeof(enum) == sizeof(int)!
+ */
+ elementp = DPO(data, t->offset);
+ *elementp = 0; /* Set the choice to choice_<type>_iosnumunknown */
+ if (t->tt & A1_OS_OT_IS_ARRAY) {
+ /*
+ * The open type is a SET OF / SEQUENCE OF -- an array.
+ *
+ * Get the number of elements to decode from:
+ *
+ * typedef struct AttributeSet {
+ * heim_oid type;
+ * struct AttributeSet_values {
+ * ------------>unsigned int len; // HERE
+ * HEIM_ANY *val;
+ * } values;
+ * ...
+ * }
+ */
+ len = *((unsigned int *)DPO(data, topentype->offset));
+
+ /*
+ * Set the number of decoded elements to zero for now:
+ *
+ * typedef struct AttributeSet {
+ * heim_oid type;
+ * struct AttributeSet_values {
+ * unsigned int len;
+ * HEIM_ANY *val;
+ * } values;
+ * struct {
+ * enum { ... } element;
+ * ------------>unsigned int len; // HERE
+ * ...
+ * } _ioschoice_values;
+ * }
+ */
+ lenp = DPO(data, t->offset + sizeof(*elementp));
+ *lenp = 0;
+ /*
+ * Get a pointer to the place where we must put the decoded value:
+ *
+ * typedef struct AttributeSet {
+ * heim_oid type;
+ * struct AttributeSet_values {
+ * unsigned int len;
+ * HEIM_ANY *val;
+ * } values;
+ * struct {
+ * enum { ... } element;
+ * unsigned int len;
+ * struct {
+ * union { SomeType *some_choice; ... } u;
+ * ------------>} *val; // HERE
+ * } _ioschoice_values;
+ * } AttributeSet;
+ */
+ dp = DPO(data, t->offset + sizeof(*elementp) + sizeof(*lenp));
+ } else {
+ /*
+ * Get a pointer to the place where we must put the decoded value:
+ *
+ * typedef struct SingleAttribute {
+ * heim_oid type;
+ * HEIM_ANY value;
+ * struct {
+ * enum { ... } element;
+ * ------------>union { SomeType *some_choice; ... } u; // HERE
+ * } _ioschoice_value;
+ * } SingleAttribute;
+ */
+ dp = DPO(data, t->offset + sizeof(*elementp));
+ }
+
+ /* Align `dp' */
+ while (sizeof(void *) != sizeof(*elementp) &&
+ ((uintptr_t)dp) % sizeof(void *) != 0)
+ dp = (void *)(((char *)dp) + sizeof(*elementp));
+ *dp = NULL;
+
+ /*
+ * Find out the type of the type ID member. We currently support only
+ * integers and OIDs.
+ *
+ * Chase through any tags to get to the type.
+ */
+ while (((ttypeid_univ->tt & A1_OP_MASK) == A1_OP_TAG &&
+ A1_TAG_CLASS(ttypeid_univ->tt) == ASN1_C_CONTEXT) ||
+ ((ttypeid_univ->tt & A1_OP_MASK) == A1_OP_TYPE)) {
+ ttypeid_univ = ttypeid_univ->ptr;
+ ttypeid_univ++;
+ }
+ switch (ttypeid_univ->tt & A1_OP_MASK) {
+ case A1_OP_TAG:
+ if (A1_TAG_CLASS(ttypeid_univ->tt) != ASN1_C_UNIV)
+ return 0; /* Do nothing, silently */
+ switch (A1_TAG_TAG(ttypeid_univ->tt)) {
+ case UT_OID:
+ typeid_is_oid = 1;
+ break;
+ case UT_Integer: {
+ const struct asn1_template *tint = ttypeid_univ->ptr;
+
+ tint++;
+
+ if ((tint->tt & A1_OP_MASK) != A1_OP_PARSE)
+ return 0; /* Do nothing, silently */
+ if (A1_PARSE_TYPE(tint->tt) != A1T_INTEGER &&
+ A1_PARSE_TYPE(tint->tt) != A1T_UNSIGNED &&
+ A1_PARSE_TYPE(tint->tt) != A1T_INTEGER64 &&
+ A1_PARSE_TYPE(tint->tt) != A1T_UNSIGNED64 &&
+ A1_PARSE_TYPE(tint->tt) != A1T_IMEMBER)
+ return 0; /* Do nothing, silently (maybe a large int) */
+ typeid_is_int = 1;
+ break;
+ }
+ /* It might be cool to support string types as type ID types */
+ default: return 0; /* Do nothing, silently */
+ }
+ break;
+ default: return 0; /* Do nothing, silently */
+ }
+
+ /*
+ * Find the type of the open type.
+ *
+ * An object set template looks like:
+ *
+ * const struct asn1_template asn1_ObjectSetName[] = {
+ * // Header entry (in this case it says there's 17 objects):
+ * { 0, 0, ((void*)17) },
+ *
+ * // here's the name of the object set:
+ * { A1_OP_NAME, 0, "ObjectSetName" },
+ *
+ * // then three entries per object: object name, object type ID,
+ * // object type:
+ * { A1_OP_NAME, 0, "ext-AuthorityInfoAccess" },
+ * { A1_OP_OPENTYPE_ID, 0, (const void*)&asn1_oid_oidName },
+ * { A1_OP_OPENTYPE, sizeof(SomeType), (const void*)&asn1_SomeType },
+ * ...
+ * };
+ *
+ * `i' being a logical object offset, i*3+3 would be the index of the
+ * A1_OP_OPENTYPE_ID entry for the current object, and i*3+4 the index of
+ * the A1_OP_OPENTYPE entry for the current object.
+ */
+ if (t->tt & A1_OS_IS_SORTED) {
+ size_t left = 0;
+ size_t right = A1_HEADER_LEN(tos);
+ const void *vp = DPO(data, ttypeid->offset);
+ int c = -1;
+
+ while (left < right) {
+ size_t mid = (left + right) >> 1;
+
+ if ((tos[3 + mid * 3].tt & A1_OP_MASK) != A1_OP_OPENTYPE_ID)
+ return 0;
+ if (typeid_is_int)
+ c = typeid_int_cmp(vp, (intptr_t)tos[3 + mid * 3].ptr,
+ ttypeid_univ);
+ else if (typeid_is_oid)
+ c = der_heim_oid_cmp(vp, tos[3 + mid * 3].ptr);
+ if (c < 0) {
+ right = mid;
+ } else if (c > 0) {
+ left = mid + 1;
+ } else {
+ i = mid;
+ break;
+ }
+ }
+ if (c)
+ return 0; /* No match */
+ } else {
+ for (i = 0, n = A1_HEADER_LEN(tos); i < n; i++) {
+ /* We add 1 to `i' because we're skipping the header */
+ if ((tos[3 + i*3].tt & A1_OP_MASK) != A1_OP_OPENTYPE_ID)
+ return 0;
+ if (typeid_is_int &&
+ typeid_int_cmp(DPO(data, ttypeid->offset),
+ (intptr_t)tos[3 + i*3].ptr,
+ ttypeid_univ))
+ continue;
+ if (typeid_is_oid &&
+ der_heim_oid_cmp(DPO(data, ttypeid->offset), tos[3 + i*3].ptr))
+ continue;
+ break;
+ }
+ if (i == n)
+ return 0; /* No match */
+ }
+
+ /* Match! */
+ *elementp = i+1; /* Zero is the "unknown" choice, so add 1 */
+
+ /*
+ * We want the A1_OP_OPENTYPE template entry. Its `offset' is the sizeof
+ * the object we'll be decoding into, and its `ptr' is the pointer to the
+ * template for decoding that type.
+ */
+ tactual_type = &tos[i*3 + 4];
+
+ /* Decode the encoded open type value(s) */
+ if (!(t->tt & A1_OS_OT_IS_ARRAY)) {
+ /*
+ * Not a SET OF/SEQUENCE OF open type, just singular.
+ *
+ * We need the address of the octet string / ANY field containing the
+ * encoded open type value:
+ *
+ * typedef struct SingleAttribute {
+ * heim_oid type;
+ * -------->HEIM_ANY value; // HERE
+ * struct {
+ * ...
+ * } ...
+ * }
+ */
+ const struct heim_base_data *d = DPOC(data, topentype->offset);
+ void *o;
+
+ if (d->data && d->length) {
+ if ((o = calloc(1, tactual_type->offset)) == NULL)
+ return ENOMEM;
+
+ /* Re-enter to decode the encoded open type value */
+ ret = _asn1_decode(tactual_type->ptr, flags, d->data, d->length, o, &sz);
+ /*
+ * Store the decoded object in the union:
+ *
+ * typedef struct SingleAttribute {
+ * heim_oid type;
+ * HEIM_ANY value;
+ * struct {
+ * enum { ... } element;
+ * ------------>union { SomeType *some_choice; ... } u; // HERE
+ * } _ioschoice_value;
+ * } SingleAttribute;
+ *
+ * All the union arms are pointers.
+ */
+ if (ret) {
+ _asn1_free(tactual_type->ptr, o);
+ free(o);
+ /*
+ * So we failed to decode the open type -- that should not be fatal
+ * to decoding the rest of the input. Only ENOMEM should be fatal.
+ */
+ ret = 0;
+ } else {
+ *dp = o;
+ }
+ }
+ return ret;
+ } else {
+ const struct heim_base_data * const *d;
+ void **val; /* Array of pointers */
+
+ /*
+ * A SET OF/SEQUENCE OF open type, plural.
+ *
+ * We need the address of the octet string / ANY array pointer field
+ * containing the encoded open type values:
+ *
+ * typedef struct AttributeSet {
+ * heim_oid type;
+ * struct AttributeSet_values {
+ * unsigned int len;
+ * ------------>HEIM_ANY *val; // HERE
+ * } values;
+ * ...
+ * }
+ *
+ * We already know the value of the `len' field.
+ */
+ d = DPOC(data, topentype->offset + sizeof(unsigned int));
+ while (sizeof(void *) != sizeof(len) &&
+ ((uintptr_t)d) % sizeof(void *) != 0)
+ d = (const void *)(((const char *)d) + sizeof(len));
+
+ if ((val = calloc(len, sizeof(*val))) == NULL)
+ ret = ENOMEM;
+
+ /* Increment the count of decoded values as we decode */
+ *lenp = len;
+ for (i = 0; ret != ENOMEM && i < len; i++) {
+ if ((val[i] = calloc(1, tactual_type->offset)) == NULL)
+ ret = ENOMEM;
+ if (ret == 0)
+ /* Re-enter to decode the encoded open type value */
+ ret = _asn1_decode(tactual_type->ptr, flags, d[0][i].data,
+ d[0][i].length, val[i], &sz);
+ if (ret) {
+ _asn1_free(tactual_type->ptr, val[i]);
+ free(val[i]);
+ val[i] = NULL;
+ }
+ }
+ if (ret != ENOMEM)
+ ret = 0; /* See above */
+ *dp = val;
+ return ret;
+ }
+}
+
+int
+_asn1_decode(const struct asn1_template *t, unsigned flags,
+ const unsigned char *p, size_t len, void *data, size_t *size)
+{
+ const struct asn1_template *tbase = t;
+ const struct asn1_template *tdefval = NULL;
+ size_t elements = A1_HEADER_LEN(t);
+ size_t oldlen = len;
+ int ret = 0;
+ const unsigned char *startp = NULL;
+ unsigned int template_flags = t->tt;
+
+ /*
+ * Important notes:
+ *
+ * - by and large we don't call _asn1_free() on error, except when we're
+ * decoding optional things or choices, then we do call _asn1_free()
+ * here
+ *
+ * instead we leave it to _asn1_decode_top() to call _asn1_free() on
+ * error
+ *
+ * - on error all fields of whatever we didn't _asn1_free() must have been
+ * initialized to sane values because _asn1_decode_top() will call
+ * _asn1_free() on error, so we must have left everything initialized
+ * that _asn1_free() could possibly look at
+ *
+ * - so we must initialize everything
+ *
+ * FIXME? but we mostly rely on calloc() to do this...
+ *
+ * - we don't use malloc() unless we're going to write over the whole
+ * thing with memcpy() or whatever
+ */
+
+ /* skip over header */
+ t++;
+
+ if (template_flags & A1_HF_PRESERVE)
+ startp = p;
+
+ while (elements) {
+ switch (t->tt & A1_OP_MASK) {
+ case A1_OP_OPENTYPE_OBJSET: {
+ size_t opentypeid = t->tt & ((1<<10)-1);
+ size_t opentype = (t->tt >> 10) & ((1<<10)-1);
+
+ /* Note that the only error returned here would be ENOMEM */
+ ret = _asn1_decode_open_type(t, flags, data,
+ template4member(tbase, opentypeid),
+ template4member(tbase, opentype));
+ if (ret)
+ return ret;
+ break;
+ }
+ case A1_OP_TYPE_DECORATE_EXTERN: break;
+ case A1_OP_TYPE_DECORATE: break;
+ case A1_OP_NAME: break;
+ case A1_OP_DEFVAL:
+ tdefval = t;
+ break;
+ case A1_OP_TYPE:
+ case A1_OP_TYPE_EXTERN: {
+ size_t newsize, elsize;
+ void *el = DPO(data, t->offset);
+ void **pel = (void **)el;
+
+ if ((t->tt & A1_OP_MASK) == A1_OP_TYPE) {
+ elsize = _asn1_sizeofType(t->ptr);
+ } else {
+ const struct asn1_type_func *f = t->ptr;
+ elsize = f->size;
+ }
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ *pel = calloc(1, elsize);
+ if (*pel == NULL)
+ return ENOMEM;
+ el = *pel;
+ if ((t->tt & A1_OP_MASK) == A1_OP_TYPE) {
+ ret = _asn1_decode(t->ptr, flags, p, len, el, &newsize);
+ } else {
+ const struct asn1_type_func *f = t->ptr;
+ ret = (f->decode)(p, len, el, &newsize);
+ }
+ if (ret) {
+ /*
+ * Optional field not present in encoding, presumably,
+ * though we should really look more carefully at `ret'.
+ */
+ if ((t->tt & A1_OP_MASK) == A1_OP_TYPE) {
+ _asn1_free(t->ptr, el);
+ } else {
+ const struct asn1_type_func *f = t->ptr;
+ f->release(el);
+ }
+ free(*pel);
+ *pel = NULL;
+ break;
+ }
+ } else {
+ if ((t->tt & A1_OP_MASK) == A1_OP_TYPE) {
+ ret = _asn1_decode(t->ptr, flags, p, len, el, &newsize);
+ } else {
+ const struct asn1_type_func *f = t->ptr;
+ ret = (f->decode)(p, len, el, &newsize);
+ }
+ }
+ if (ret) {
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ } else if (t->tt & A1_FLAG_DEFAULT) {
+ if (!tdefval)
+ return ASN1_PARSE_ERROR; /* Can't happen */
+ /*
+ * Defaulted field not present in encoding, presumably,
+ * though we should really look more carefully at `ret'.
+ */
+ if (tdefval->tt & A1_DV_BOOLEAN) {
+ int *i = (void *)(char *)el;
+
+ *i = tdefval->ptr ? 1 : 0;
+ } else if (tdefval->tt & A1_DV_INTEGER64) {
+ int64_t *i = (void *)(char *)el;
+
+ *i = (int64_t)(intptr_t)tdefval->ptr;
+ } else if (tdefval->tt & A1_DV_INTEGER32) {
+ int32_t *i = (void *)(char *)el;
+
+ *i = (int32_t)(intptr_t)tdefval->ptr;
+ } else if (tdefval->tt & A1_DV_INTEGER) {
+ struct heim_integer *i = (void *)(char *)el;
+
+ if ((ret = der_copy_heim_integer(tdefval->ptr, i)))
+ return ret;
+ } else if (tdefval->tt & A1_DV_UTF8STRING) {
+ char **s = el;
+
+ if ((*s = strdup(tdefval->ptr)) == NULL)
+ return ENOMEM;
+ } else {
+ abort();
+ }
+ break;
+ }
+ return ret; /* Error decoding required field */
+ }
+ p += newsize; len -= newsize;
+
+ break;
+ }
+ case A1_OP_TAG: {
+ Der_type dertype;
+ size_t newsize = 0;
+ size_t datalen, l = 0;
+ void *olddata = data;
+ int is_indefinite = 0;
+ int subflags = flags;
+ int replace_tag = (t->tt & A1_FLAG_IMPLICIT) && is_tagged(t->ptr);
+ void *el = data = DPO(data, t->offset);
+ void **pel = (void **)el;
+
+ /*
+ * XXX If this type (chasing t->ptr through IMPLICIT tags, if this
+ * one is too, till we find a non-TTag) is a [UNIVERSAL SET] type,
+ * then we have to accept fields out of order. For each field tag
+ * we see we'd have to do a linear search of the SET's template
+ * because it won't be sorted (or we could sort a copy and do a
+ * binary search on that, but these SETs will always be small so it
+ * won't be worthwhile). We'll need a utility function to do all
+ * of this.
+ */
+ ret = der_match_tag_and_length(p, len, A1_TAG_CLASS(t->tt),
+ &dertype, A1_TAG_TAG(t->tt),
+ &datalen, &l);
+ if (ret) {
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ data = olddata;
+ break;
+ } else if (t->tt & A1_FLAG_DEFAULT) {
+ if (!tdefval)
+ return ASN1_PARSE_ERROR; /* Can't happen */
+ /*
+ * Defaulted field not present in encoding, presumably,
+ * though we should really look more carefully at `ret'.
+ */
+ if (tdefval->tt & A1_DV_BOOLEAN) {
+ int *i = (void *)(char *)data;
+
+ *i = tdefval->ptr ? 1 : 0;
+ } else if (tdefval->tt & A1_DV_INTEGER64) {
+ int64_t *i = (void *)(char *)data;
+
+ *i = (int64_t)(intptr_t)tdefval->ptr;
+ } else if (tdefval->tt & A1_DV_INTEGER32) {
+ int32_t *i = (void *)(char *)data;
+
+ *i = (int32_t)(intptr_t)tdefval->ptr;
+ } else if (tdefval->tt & A1_DV_INTEGER) {
+ struct heim_integer *i = (void *)(char *)data;
+
+ if ((ret = der_copy_heim_integer(tdefval->ptr, i)))
+ return ret;
+ } else if (tdefval->tt & A1_DV_UTF8STRING) {
+ char **s = data;
+
+ if ((*s = strdup(tdefval->ptr)) == NULL)
+ return ENOMEM;
+ } else {
+ abort();
+ }
+ data = olddata;
+ break;
+ }
+ return ret; /* Error decoding required field */
+ }
+
+ p += l; len -= l;
+
+ /*
+ * Only allow indefinite encoding for OCTET STRING and BER
+ * for now. Should handle BIT STRING too.
+ */
+
+ if (dertype != A1_TAG_TYPE(t->tt) && (flags & A1_PF_ALLOW_BER)) {
+ const struct asn1_template *subtype = t->ptr;
+ subtype++; /* skip header */
+
+ if (((subtype->tt & A1_OP_MASK) == A1_OP_PARSE) &&
+ A1_PARSE_TYPE(subtype->tt) == A1T_OCTET_STRING)
+ subflags |= A1_PF_INDEFINTE;
+ }
+
+ if (datalen == ASN1_INDEFINITE) {
+ if ((flags & A1_PF_ALLOW_BER) == 0)
+ return ASN1_GOT_BER;
+ is_indefinite = 1;
+ datalen = len;
+ if (datalen < 2)
+ return ASN1_OVERRUN;
+ /* hide EndOfContent for sub-decoder, catching it below */
+ datalen -= 2;
+ } else if (datalen > len)
+ return ASN1_OVERRUN;
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ size_t ellen = _asn1_sizeofType(t->ptr);
+
+ *pel = calloc(1, ellen);
+ if (*pel == NULL)
+ return ENOMEM;
+ data = *pel;
+ }
+
+ if (replace_tag) {
+ const struct asn1_template *subtype = t->ptr;
+ int have_tag = 0;
+
+ /*
+ * So, we have an IMPLICIT tag. What we want to do is find the
+ * template for the body of the type so-tagged. That's going
+ * to be a template that has a tag that isn't itself IMPLICIT.
+ *
+ * So we chase the pointer in the template until we find such a
+ * thing, then decode using that template.
+ */
+ while (!have_tag) {
+ subtype++;
+ if ((subtype->tt & A1_OP_MASK) == A1_OP_TAG)
+ replace_tag = (subtype->tt & A1_FLAG_IMPLICIT) && is_tagged(t->ptr);
+ if (replace_tag) {
+ subtype = subtype->ptr;
+ continue;
+ }
+ if ((subtype->tt & A1_OP_MASK) == A1_OP_TAG) {
+ ret = _asn1_decode(subtype->ptr, subflags, p, datalen, data, &newsize);
+ have_tag = 1;
+ } else {
+ subtype = subtype->ptr;
+ }
+ }
+ } else {
+ ret = _asn1_decode(t->ptr, subflags, p, datalen, data, &newsize);
+ }
+ if (ret == 0 && !is_indefinite && newsize != datalen)
+ /* Hidden data */
+ ret = ASN1_EXTRA_DATA;
+
+ if (ret == 0) {
+ if (is_indefinite) {
+ /* If we use indefinite encoding, the newsize is the datasize. */
+ datalen = newsize;
+ }
+
+ len -= datalen;
+ p += datalen;
+
+ /*
+ * Indefinite encoding needs a trailing EndOfContent,
+ * check for that.
+ */
+ if (is_indefinite) {
+ ret = der_match_tag_and_length(p, len, ASN1_C_UNIV,
+ &dertype, UT_EndOfContent,
+ &datalen, &l);
+ if (ret == 0 && dertype != PRIM)
+ ret = ASN1_BAD_ID;
+ else if (ret == 0 && datalen != 0)
+ ret = ASN1_INDEF_EXTRA_DATA;
+ if (ret == 0) {
+ p += l; len -= l;
+ }
+ }
+ }
+ if (ret) {
+ if (!(t->tt & A1_FLAG_OPTIONAL))
+ return ret;
+
+ _asn1_free(t->ptr, data);
+ free(data);
+ *pel = NULL;
+ return ret;
+ }
+ data = olddata;
+
+ break;
+ }
+ case A1_OP_PARSE: {
+ unsigned int type = A1_PARSE_TYPE(t->tt);
+ size_t newsize;
+ void *el = DPO(data, t->offset);
+
+ /*
+ * INDEFINITE primitive types are one element after the
+ * same type but non-INDEFINITE version.
+ */
+ if (flags & A1_PF_INDEFINTE)
+ type++;
+
+ if (type >= sizeof(asn1_template_prim)/sizeof(asn1_template_prim[0])) {
+ ABORT_ON_ERROR();
+ return ASN1_PARSE_ERROR;
+ }
+
+ ret = (asn1_template_prim[type].decode)(p, len, el, &newsize);
+ if (ret)
+ return ret;
+ p += newsize; len -= newsize;
+
+ break;
+ }
+ case A1_OP_SETOF:
+ case A1_OP_SEQOF: {
+ struct template_of *el = DPO(data, t->offset);
+ size_t newsize;
+ size_t ellen = _asn1_sizeofType(t->ptr);
+ size_t vallength = 0;
+
+ while (len > 0) {
+ void *tmp;
+ size_t newlen = vallength + ellen;
+ if (vallength > newlen)
+ return ASN1_OVERFLOW;
+
+ /* XXX Slow */
+ tmp = realloc(el->val, newlen);
+ if (tmp == NULL)
+ return ENOMEM;
+
+ memset(DPO(tmp, vallength), 0, ellen);
+ el->val = tmp;
+
+ el->len++;
+ ret = _asn1_decode(t->ptr, flags & (~A1_PF_INDEFINTE), p, len,
+ DPO(el->val, vallength), &newsize);
+ if (ret)
+ return ret;
+ vallength = newlen;
+ p += newsize; len -= newsize;
+ }
+
+ break;
+ }
+ case A1_OP_BMEMBER: {
+ const struct asn1_template *bmember = t->ptr;
+ size_t bsize = bmember->offset;
+ size_t belements = A1_HEADER_LEN(bmember);
+ size_t pos = 0;
+
+ bmember++;
+
+ memset(data, 0, bsize);
+
+ if (len < 1)
+ return ASN1_OVERRUN;
+ p++; len--;
+
+ while (belements && len) {
+ while (bmember->offset / 8 > pos / 8) {
+ if (len < 1)
+ break;
+ p++; len--;
+ pos += 8;
+ }
+ if (len) {
+ _asn1_bmember_get_bit(p, data, bmember->offset, bsize);
+ belements--; bmember++;
+ }
+ }
+ len = 0;
+ break;
+ }
+ case A1_OP_CHOICE: {
+ const struct asn1_template *choice = t->ptr;
+ unsigned int *element = DPO(data, choice->offset);
+ size_t datalen;
+ unsigned int i;
+
+ /*
+ * CHOICE element IDs are assigned in monotonically increasing
+ * fashion. Therefore any unrealistic value is a suitable invalid
+ * CHOICE value. The largest binary value (or -1 if treating the
+ * enum as signed on a twos-complement system, or...) will do.
+ */
+ *element = ~0;
+
+ for (i = 1; i < A1_HEADER_LEN(choice) + 1 && choice[i].tt; i++) {
+ /*
+ * This is more permissive than is required. CHOICE
+ * alternatives must have different outer tags, so in principle
+ * we should just match the tag at `p' and `len' in sequence to
+ * the choice alternatives.
+ *
+ * Trying every alternative instead happens to do this anyways
+ * because each one will first match the tag at `p' and `len',
+ * but if there are CHOICE altnernatives with the same outer
+ * tag, then we'll allow it, and they had better be unambiguous
+ * in their internal details, otherwise there would be some
+ * aliasing.
+ *
+ * Arguably the *compiler* should detect ambiguous CHOICE types
+ * and raise an error, then we don't have to be concerned here
+ * at all.
+ */
+ ret = _asn1_decode(choice[i].ptr, 0, p, len,
+ DPO(data, choice[i].offset), &datalen);
+ if (ret == 0) {
+ *element = i;
+ p += datalen; len -= datalen;
+ break;
+ }
+ _asn1_free(choice[i].ptr, DPO(data, choice[i].offset));
+ if (ret != ASN1_BAD_ID && ret != ASN1_MISPLACED_FIELD &&
+ ret != ASN1_MISSING_FIELD)
+ return ret;
+ }
+ if (i >= A1_HEADER_LEN(choice) + 1 || !choice[i].tt) {
+ if (choice->tt == 0)
+ return ASN1_BAD_ID;
+
+ /* This is the ellipsis case */
+ *element = 0;
+ ret = der_get_octet_string(p, len,
+ DPO(data, choice->tt), &datalen);
+ if (ret)
+ return ret;
+ p += datalen; len -= datalen;
+ }
+
+ break;
+ }
+ default:
+ ABORT_ON_ERROR();
+ return ASN1_PARSE_ERROR;
+ }
+ t++;
+ elements--;
+ }
+ /* if we are using padding, eat up read of context */
+ if (template_flags & A1_HF_ELLIPSIS)
+ len = 0;
+
+ oldlen -= len;
+
+ if (size)
+ *size = oldlen;
+
+ /*
+ * saved the raw bits if asked for it, useful for signature
+ * verification.
+ */
+ if (startp) {
+ heim_octet_string *save = data;
+
+ save->data = malloc(oldlen);
+ if (save->data == NULL)
+ return ENOMEM;
+ else {
+ save->length = oldlen;
+ memcpy(save->data, startp, oldlen);
+ }
+ }
+ return 0;
+}
+
+/*
+ * This should be called with a `A1_TAG_T(ASN1_C_UNIV, PRIM, UT_Integer)'
+ * template as the `ttypeid'.
+ */
+static int
+typeid_int_copy(void *intp,
+ int64_t i,
+ const struct asn1_template *ttypeid)
+{
+ const struct asn1_template *tint = ttypeid->ptr;
+
+ if ((tint[1].tt & A1_OP_MASK) != A1_OP_PARSE)
+ return -1;
+ if (A1_PARSE_TYPE(tint[1].tt) != A1T_INTEGER)
+ return -1;
+ switch (tint[0].offset) {
+ case 8: *((int64_t *)intp) = i; return 0;
+ case 4: *((int32_t *)intp) = i; return 0;
+ default: memset(intp, 0, tint[0].offset); return 0;
+ }
+}
+
+/* See commentary in _asn1_decode_open_type() */
+static int
+_asn1_encode_open_type(const struct asn1_template *t,
+ const void *data, /* NOTE: Not really const */
+ const struct asn1_template *ttypeid,
+ const struct asn1_template *topentype)
+{
+ const struct asn1_template *ttypeid_univ = ttypeid;
+ const struct asn1_template *tactual_type;
+ const struct asn1_template *tos = t->ptr;
+ size_t sz, i;
+ unsigned int *lenp = NULL;
+ unsigned int len = 1;
+ int element = *(const int *)DPOC(data, t->offset);
+ int typeid_is_oid = 0;
+ int typeid_is_int = 0;
+ int enotsup = 0;
+ int ret = 0;
+
+ if (element == 0 || element >= A1_HEADER_LEN(tos) + 1)
+ return 0;
+
+ if (t->tt & A1_OS_OT_IS_ARRAY) {
+ /* The actual `len' is from the decoded open type field */
+ len = *(const unsigned int *)DPOC(data, t->offset + sizeof(element));
+
+ if (!len)
+ return 0; /* The app may be encoding the open type by itself */
+ }
+
+ /* Work out the type ID field's type */
+ while (((ttypeid_univ->tt & A1_OP_MASK) == A1_OP_TAG &&
+ A1_TAG_CLASS(ttypeid_univ->tt) == ASN1_C_CONTEXT) ||
+ ((ttypeid_univ->tt & A1_OP_MASK) == A1_OP_TYPE)) {
+ ttypeid_univ = ttypeid_univ->ptr;
+ ttypeid_univ++;
+ }
+ switch (ttypeid_univ->tt & A1_OP_MASK) {
+ case A1_OP_TAG:
+ if (A1_TAG_CLASS(ttypeid_univ->tt) != ASN1_C_UNIV) {
+ enotsup = 1;
+ break;
+ }
+ switch (A1_TAG_TAG(ttypeid_univ->tt)) {
+ case UT_OID:
+ typeid_is_oid = 1;
+ break;
+ case UT_Integer: {
+ const struct asn1_template *tint = ttypeid_univ->ptr;
+
+ tint++;
+ if ((tint->tt & A1_OP_MASK) != A1_OP_PARSE ||
+ A1_PARSE_TYPE(tint->tt) != A1T_INTEGER) {
+ enotsup = 1;
+ break;
+ }
+ typeid_is_int = 1;
+ break;
+ }
+ default: enotsup = 1; break;
+ }
+ break;
+ default: enotsup = 1; break;
+ }
+
+ /*
+ * The app may not be aware of our automatic open type handling, so if the
+ * open type already appears to have been encoded, then ignore the decoded
+ * values.
+ */
+ if (!(t->tt & A1_OS_OT_IS_ARRAY)) {
+ struct heim_base_data *os = DPO(data, topentype->offset);
+
+ if (os->length && os->data)
+ return 0;
+ } else {
+ struct heim_base_data **os = DPO(data, topentype->offset + sizeof(len));
+
+ while (sizeof(void *) != sizeof(unsigned int) &&
+ ((uintptr_t)os) % sizeof(void *) != 0)
+ os = (void *)(((char *)os) + sizeof(unsigned int));
+
+ lenp = DPO(data, topentype->offset);
+ if (*lenp == len && os[0]->length && os[0]->data)
+ return 0;
+ }
+
+ if (typeid_is_int) {
+ /*
+ * Copy the int from the type ID object field to the type ID struct
+ * field.
+ */
+ ret = typeid_int_copy(DPO(data, ttypeid->offset),
+ (intptr_t)tos[3 + (element-1)*3].ptr, ttypeid_univ);
+ } else if (typeid_is_oid) {
+ /*
+ * Copy the OID from the type ID object field to the type ID struct
+ * field.
+ */
+ ret = der_copy_oid(tos[3 + (element-1)*3].ptr, DPO(data, ttypeid->offset));
+ } else
+ enotsup = 1;
+
+ /*
+ * If the app did not already encode the open type, we can't help it if we
+ * don't know what it is.
+ */
+ if (enotsup)
+ return ENOTSUP;
+
+ tactual_type = &tos[(element-1)*3 + 4];
+
+ if (!(t->tt & A1_OS_OT_IS_ARRAY)) {
+ struct heim_base_data *os = DPO(data, topentype->offset);
+ const void * const *d = DPOC(data, t->offset + sizeof(element));
+
+ while (sizeof(void *) != sizeof(element) &&
+ ((uintptr_t)d) % sizeof(void *) != 0) {
+ d = (void *)(((char *)d) + sizeof(element));
+ }
+
+ os->length = _asn1_length(tactual_type->ptr, *d);
+ if ((os->data = malloc(os->length)) == NULL)
+ return ENOMEM;
+ ret = _asn1_encode(tactual_type->ptr, (os->length - 1) + (unsigned char *)os->data, os->length, *d, &sz);
+ } else {
+ struct heim_base_data *os;
+ const void * const *val =
+ DPOC(data, t->offset + sizeof(element) + sizeof(*lenp));
+
+ if ((os = calloc(len, sizeof(*os))) == NULL)
+ return ENOMEM;
+
+ *lenp = len;
+ for (i = 0; ret == 0 && i < len; i++) {
+ os[i].length = _asn1_length(tactual_type->ptr, val[i]);
+ if ((os[i].data = malloc(os[i].length)) == NULL)
+ ret = ENOMEM;
+ if (ret == 0)
+ ret = _asn1_encode(tactual_type->ptr, (os[i].length - 1) + (unsigned char *)os[i].data, os[i].length,
+ val[i], &sz);
+ }
+ if (ret) {
+ for (i = 0; i < (*lenp); i++)
+ free(os[i].data);
+ free(os);
+ *lenp = 0;
+ return ret;
+ }
+ *(struct heim_base_data **)DPO(data, topentype->offset + sizeof(len)) = os;
+ }
+ return ret;
+}
+
+int
+_asn1_encode(const struct asn1_template *t, unsigned char *p, size_t len, const void *data, size_t *size)
+{
+ const struct asn1_template *tbase = t;
+ size_t elements = A1_HEADER_LEN(t);
+ int ret = 0;
+ size_t oldlen = len;
+
+ t += A1_HEADER_LEN(t);
+
+ while (elements) {
+ switch (t->tt & A1_OP_MASK) {
+ case A1_OP_OPENTYPE_OBJSET: {
+ size_t opentypeid = t->tt & ((1<<10)-1);
+ size_t opentype = (t->tt >> 10) & ((1<<10)-1);
+ ret = _asn1_encode_open_type(t, data,
+ template4member(tbase, opentypeid),
+ template4member(tbase, opentype));
+ if (ret)
+ return ret;
+ break;
+ }
+ case A1_OP_NAME: break;
+ case A1_OP_DEFVAL: break;
+ case A1_OP_TYPE_DECORATE_EXTERN: break;
+ case A1_OP_TYPE_DECORATE: break;
+ case A1_OP_TYPE:
+ case A1_OP_TYPE_EXTERN: {
+ size_t newsize;
+ const void *el = DPOC(data, t->offset);
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ void **pel = (void **)el;
+ if (*pel == NULL)
+ break;
+ el = *pel;
+ } else if ((t->tt & A1_FLAG_DEFAULT) && elements > 1) {
+ const struct asn1_template *tdefval = t - 1;
+ /* Compare tdefval to whatever's at `el' */
+ if (tdefval->tt & A1_DV_BOOLEAN) {
+ const int *i = (void *)(char *)el;
+
+ if ((*i && tdefval->ptr) || (!*i && !tdefval->ptr))
+ break;
+ } else if (tdefval->tt & A1_DV_INTEGER64) {
+ const int64_t *i = (void *)(char *)el;
+
+ if (*i == (int64_t)(intptr_t)tdefval->ptr)
+ break;
+ } else if (tdefval->tt & A1_DV_INTEGER32) {
+ const int32_t *i = (void *)(char *)el;
+
+ if ((int64_t)(intptr_t)tdefval->ptr <= INT_MAX &&
+ (int64_t)(intptr_t)tdefval->ptr >= INT_MIN &&
+ *i == (int32_t)(intptr_t)tdefval->ptr)
+ break;
+ } else if (tdefval->tt & A1_DV_INTEGER) {
+ const struct heim_integer *i = (void *)(char *)el;
+
+ if (der_heim_integer_cmp(i, tdefval->ptr) == 0)
+ break;
+ } else if (tdefval->tt & A1_DV_UTF8STRING) {
+ const char * const *s = el;
+
+ if (*s && strcmp(*s, tdefval->ptr) == 0)
+ break;
+ } else {
+ abort();
+ }
+ }
+
+ if ((t->tt & A1_OP_MASK) == A1_OP_TYPE) {
+ ret = _asn1_encode(t->ptr, p, len, el, &newsize);
+ } else {
+ const struct asn1_type_func *f = t->ptr;
+ ret = (f->encode)(p, len, el, &newsize);
+ }
+
+ if (ret)
+ return ret;
+ p -= newsize; len -= newsize;
+
+ break;
+ }
+ case A1_OP_TAG: {
+ const void *olddata = data;
+ size_t l, datalen = 0;
+ int replace_tag = 0;
+
+ /*
+ * XXX If this type (chasing t->ptr through IMPLICIT tags, if this
+ * one is too) till we find a non-TTag) is a [UNIVERSAL SET] type,
+ * then we have to sort [a copy of] its template by tag, then
+ * encode the SET using that sorted template. These SETs will
+ * generally be small, so when they are we might want to allocate
+ * the copy on the stack and insertion sort it. We'll need a
+ * utility function to do all of this.
+ */
+
+ data = DPOC(data, t->offset);
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ void **el = (void **)data;
+ if (*el == NULL) {
+ data = olddata;
+ break;
+ }
+ data = *el;
+ } else if ((t->tt & A1_FLAG_DEFAULT) && elements > 1) {
+ const struct asn1_template *tdefval = t - 1;
+ int exclude = 0;
+
+ /* Compare tdefval to whatever's at `data' */
+ if (tdefval->tt & A1_DV_BOOLEAN) {
+ const int *i = (void *)(char *)data;
+
+ if ((*i && tdefval->ptr) || (!*i && !tdefval->ptr))
+ exclude = 1;
+ } else if (tdefval->tt & A1_DV_INTEGER64) {
+ const int64_t *i = (void *)(char *)data;
+
+ if (*i == (int64_t)(intptr_t)tdefval->ptr)
+ exclude = 1;
+ } else if (tdefval->tt & A1_DV_INTEGER32) {
+ const int32_t *i = (void *)(char *)data;
+
+ if ((int64_t)(intptr_t)tdefval->ptr <= INT_MAX &&
+ (int64_t)(intptr_t)tdefval->ptr >= INT_MIN &&
+ *i == (int32_t)(intptr_t)tdefval->ptr)
+ exclude = 1;
+ } else if (tdefval->tt & A1_DV_INTEGER) {
+ const struct heim_integer *i = (void *)(char *)data;
+
+ if (der_heim_integer_cmp(i, tdefval->ptr) == 0)
+ break;
+ } else if (tdefval->tt & A1_DV_UTF8STRING) {
+ const char * const *s = data;
+
+ if (*s && strcmp(*s, tdefval->ptr) == 0)
+ exclude = 1;
+ } else {
+ abort();
+ }
+ if (exclude) {
+ data = olddata;
+ break;
+ }
+ }
+
+ replace_tag = (t->tt & A1_FLAG_IMPLICIT) && is_tagged(t->ptr);
+
+ /* IMPLICIT tags need special handling (see gen_encode.c) */
+ if (replace_tag) {
+ unsigned char *pfree, *psave = p;
+ Der_class found_class;
+ Der_type found_type = 0;
+ unsigned int found_tag;
+ size_t lensave = len;
+ size_t oldtaglen = 0;
+ size_t taglen = der_length_tag(A1_TAG_TAG(t->tt));;
+
+ /* Allocate a buffer at least as big as we need */
+ len = _asn1_length(t->ptr, data) + taglen;
+ if ((p = pfree = malloc(len)) == NULL) {
+ ret = ENOMEM;
+ } else {
+ /*
+ * Encode into it (with the wrong tag, which we'll replace
+ * below).
+ */
+ p += len - 1;
+ ret = _asn1_encode(t->ptr, p, len, data, &datalen);
+ }
+ if (ret == 0) {
+ /* Get the old tag and, critically, its length */
+ len -= datalen; p -= datalen;
+ ret = der_get_tag(p + 1, datalen, &found_class, &found_type,
+ &found_tag, &oldtaglen);
+ }
+ if (ret == 0) {
+ /* Drop the old tag */
+ len += oldtaglen; p += oldtaglen;
+ /* Put the new tag */
+ ret = der_put_tag(p, len,
+ A1_TAG_CLASS(t->tt),
+ found_type,
+ A1_TAG_TAG(t->tt), &l);
+ }
+ if (ret == 0) {
+ /* Copy the encoding where it belongs */
+ psave -= (datalen + l - oldtaglen);
+ lensave -= (datalen + l - oldtaglen);
+ memcpy(psave + 1, p + 1 - l, datalen + l - oldtaglen);
+ p = psave;
+ len = lensave;
+ }
+ free(pfree);
+ } else {
+ /* Easy case */
+ ret = _asn1_encode(t->ptr, p, len, data, &datalen);
+ if (ret)
+ return ret;
+
+ len -= datalen; p -= datalen;
+
+ ret = der_put_length_and_tag(p, len, datalen,
+ A1_TAG_CLASS(t->tt),
+ A1_TAG_TYPE(t->tt),
+ A1_TAG_TAG(t->tt), &l);
+ if (ret == 0) {
+ p -= l; len -= l;
+ }
+ }
+ if (ret)
+ return ret;
+
+ data = olddata;
+
+ break;
+ }
+ case A1_OP_PARSE: {
+ unsigned int type = A1_PARSE_TYPE(t->tt);
+ size_t newsize;
+ const void *el = DPOC(data, t->offset);
+
+ if (type >= sizeof(asn1_template_prim)/sizeof(asn1_template_prim[0])) {
+ ABORT_ON_ERROR();
+ return ASN1_PARSE_ERROR;
+ }
+
+ ret = (asn1_template_prim[type].encode)(p, len, el, &newsize);
+ if (ret)
+ return ret;
+ p -= newsize; len -= newsize;
+
+ break;
+ }
+ case A1_OP_SETOF: {
+ const struct template_of *el = DPOC(data, t->offset);
+ size_t ellen = _asn1_sizeofType(t->ptr);
+ heim_octet_string *val;
+ unsigned char *elptr = el->val;
+ size_t i, totallen;
+
+ if (el->len == 0)
+ break;
+
+ if (el->len > UINT_MAX/sizeof(val[0]))
+ return ERANGE;
+
+ val = calloc(el->len, sizeof(val[0]));
+ if (val == NULL)
+ return ENOMEM;
+
+ for(totallen = 0, i = 0; i < el->len; i++) {
+ unsigned char *next;
+ size_t l;
+
+ val[i].length = _asn1_length(t->ptr, elptr);
+ if (val[i].length) {
+ val[i].data = malloc(val[i].length);
+ if (val[i].data == NULL) {
+ ret = ENOMEM;
+ break;
+ }
+ }
+
+ ret = _asn1_encode(t->ptr, DPO(val[i].data, val[i].length - 1),
+ val[i].length, elptr, &l);
+ if (ret)
+ break;
+
+ next = elptr + ellen;
+ if (next < elptr) {
+ ret = ASN1_OVERFLOW;
+ break;
+ }
+ elptr = next;
+ totallen += val[i].length;
+ }
+ if (ret == 0 && totallen > len)
+ ret = ASN1_OVERFLOW;
+ if (ret) {
+ for (i = 0; i < el->len; i++)
+ free(val[i].data);
+ free(val);
+ return ret;
+ }
+
+ len -= totallen;
+
+ qsort(val, el->len, sizeof(val[0]), _heim_der_set_sort);
+
+ i = el->len - 1;
+ do {
+ p -= val[i].length;
+ memcpy(p + 1, val[i].data, val[i].length);
+ free(val[i].data);
+ } while(i-- > 0);
+ free(val);
+
+ break;
+
+ }
+ case A1_OP_SEQOF: {
+ struct template_of *el = DPO(data, t->offset);
+ size_t ellen = _asn1_sizeofType(t->ptr);
+ size_t newsize;
+ unsigned int i;
+ unsigned char *elptr = el->val;
+
+ if (el->len == 0)
+ break;
+
+ elptr += ellen * (el->len - 1);
+
+ for (i = 0; i < el->len; i++) {
+ ret = _asn1_encode(t->ptr, p, len,
+ elptr,
+ &newsize);
+ if (ret)
+ return ret;
+ p -= newsize; len -= newsize;
+ elptr -= ellen;
+ }
+
+ break;
+ }
+ case A1_OP_BMEMBER: {
+ const struct asn1_template *bmember = t->ptr;
+ size_t bsize = bmember->offset;
+ size_t belements = A1_HEADER_LEN(bmember);
+ size_t pos;
+ unsigned char c = 0;
+ unsigned int bitset = 0;
+ int rfc1510 = (bmember->tt & A1_HBF_RFC1510);
+
+ bmember += belements;
+
+ if (rfc1510)
+ pos = 31;
+ else
+ pos = bmember->offset;
+
+ while (belements && len) {
+ while (bmember->offset / 8 < pos / 8) {
+ if (rfc1510 || bitset || c) {
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = c; len--;
+ }
+ c = 0;
+ pos -= 8;
+ }
+ _asn1_bmember_put_bit(&c, data, bmember->offset, bsize, &bitset);
+ belements--; bmember--;
+ }
+ if (rfc1510 || bitset) {
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ *p-- = c; len--;
+ }
+
+ if (len < 1)
+ return ASN1_OVERFLOW;
+ if (rfc1510 || bitset == 0)
+ *p-- = 0;
+ else
+ *p-- = bitset - 1;
+
+ len--;
+
+ break;
+ }
+ case A1_OP_CHOICE: {
+ const struct asn1_template *choice = t->ptr;
+ const unsigned int *element = DPOC(data, choice->offset);
+ size_t datalen;
+ const void *el;
+
+ if (*element > A1_HEADER_LEN(choice)) {
+ printf("element: %d\n", *element);
+ return ASN1_PARSE_ERROR;
+ }
+
+ if (*element == 0) {
+ ret += der_put_octet_string(p, len,
+ DPOC(data, choice->tt), &datalen);
+ } else {
+ choice += *element;
+ el = DPOC(data, choice->offset);
+ ret = _asn1_encode(choice->ptr, p, len, el, &datalen);
+ if (ret)
+ return ret;
+ }
+ len -= datalen; p -= datalen;
+
+ break;
+ }
+ default:
+ ABORT_ON_ERROR();
+ }
+ t--;
+ elements--;
+ }
+ if (size)
+ *size = oldlen - len;
+
+ return 0;
+}
+
+static size_t
+_asn1_length_open_type_helper(const struct asn1_template *t,
+ size_t sz)
+{
+ const struct asn1_template *tinner = t->ptr;
+
+ switch (t->tt & A1_OP_MASK) {
+ case A1_OP_TAG:
+ /* XXX Not tail-recursive :( */
+ sz = _asn1_length_open_type_helper(tinner, sz);
+ sz += der_length_len(sz);
+ sz += der_length_tag(A1_TAG_TAG(t->tt));
+ return sz;
+ default:
+ return sz;
+ }
+}
+
+static size_t
+_asn1_length_open_type_id(const struct asn1_template *t,
+ const void *data)
+{
+ struct asn1_template pretend[2] = {
+ { 0, 0, ((void*)(uintptr_t)1) },
+ };
+ pretend[1] = *t;
+ while ((t->tt & A1_OP_MASK) == A1_OP_TAG)
+ t = t->ptr;
+ pretend[0].offset = t->offset;
+ return _asn1_length(pretend, data);
+}
+
+/* See commentary in _asn1_encode_open_type() */
+static size_t
+_asn1_length_open_type(const struct asn1_template *tbase,
+ const struct asn1_template *t,
+ const void *data,
+ const struct asn1_template *ttypeid,
+ const struct asn1_template *topentype)
+{
+ const struct asn1_template *ttypeid_univ = ttypeid;
+ const struct asn1_template *tactual_type;
+ const struct asn1_template *tos = t->ptr;
+ const unsigned int *lenp = NULL;
+ unsigned int len = 1;
+ size_t sz = 0;
+ size_t i;
+ int element = *(const int *)DPOC(data, t->offset);
+ int typeid_is_oid = 0;
+ int typeid_is_int = 0;
+
+ /* If nothing to encode, we add nothing to the length */
+ if (element == 0 || element >= A1_HEADER_LEN(tos) + 1)
+ return 0;
+ if (t->tt & A1_OS_OT_IS_ARRAY) {
+ len = *(const unsigned int *)DPOC(data, t->offset + sizeof(element));
+ if (!len)
+ return 0;
+ }
+
+ /* Work out the type ID field's type */
+ while (((ttypeid_univ->tt & A1_OP_MASK) == A1_OP_TAG &&
+ A1_TAG_CLASS(ttypeid_univ->tt) == ASN1_C_CONTEXT) ||
+ ((ttypeid_univ->tt & A1_OP_MASK) == A1_OP_TYPE)) {
+ ttypeid_univ = ttypeid_univ->ptr;
+ ttypeid_univ++;
+ }
+ switch (ttypeid_univ->tt & A1_OP_MASK) {
+ case A1_OP_TAG:
+ if (A1_TAG_CLASS(ttypeid_univ->tt) != ASN1_C_UNIV)
+ return 0;
+ switch (A1_TAG_TAG(ttypeid_univ->tt)) {
+ case UT_OID:
+ typeid_is_oid = 1;
+ break;
+ case UT_Integer: {
+ const struct asn1_template *tint = ttypeid_univ->ptr;
+
+ tint++;
+ if ((tint->tt & A1_OP_MASK) != A1_OP_PARSE ||
+ A1_PARSE_TYPE(tint->tt) != A1T_INTEGER)
+ return 0;
+ typeid_is_int = 1;
+ break;
+ }
+ default: return 0;
+ }
+ break;
+ default: return 0;
+ }
+ if (!(t->tt & A1_OS_OT_IS_ARRAY)) {
+ struct heim_base_data *os = DPO(data, topentype->offset);
+
+ if (os->length && os->data)
+ return 0;
+ } else {
+ struct heim_base_data **os = DPO(data, topentype->offset + sizeof(len));
+
+ while (sizeof(void *) != sizeof(unsigned int) &&
+ ((uintptr_t)os) % sizeof(void *) != 0)
+ os = (void *)(((char *)os) + sizeof(unsigned int));
+
+ lenp = DPOC(data, topentype->offset);
+ if (*lenp == len && os[0]->length && os[0]->data)
+ return 0;
+ }
+
+ /* Compute the size of the type ID field */
+ if (typeid_is_int) {
+ int64_t i8;
+ int32_t i4;
+
+ switch (ttypeid_univ->offset) {
+ case 8:
+ i8 = (intptr_t)t->ptr;
+ sz = _asn1_length_open_type_id(ttypeid, &i8);
+ i8 = 0;
+ sz -= _asn1_length_open_type_id(ttypeid, &i8);
+ break;
+ case 4:
+ i4 = (intptr_t)t->ptr;
+ sz = _asn1_length_open_type_id(ttypeid, &i4);
+ i4 = 0;
+ sz -= _asn1_length_open_type_id(ttypeid, &i8);
+ break;
+ default:
+ return 0;
+ }
+ } else if (typeid_is_oid) {
+ heim_oid no_oid = { 0, 0 };
+
+ sz = _asn1_length_open_type_id(ttypeid, tos[3 + (element - 1)*3].ptr);
+ sz -= _asn1_length_open_type_id(ttypeid, &no_oid);
+ }
+
+ tactual_type = &tos[(element-1)*3 + 4];
+
+ /* Compute the size of the encoded value(s) */
+ if (!(t->tt & A1_OS_OT_IS_ARRAY)) {
+ const void * const *d = DPOC(data, t->offset + sizeof(element));
+
+ while (sizeof(void *) != sizeof(element) &&
+ ((uintptr_t)d) % sizeof(void *) != 0)
+ d = (void *)(((char *)d) + sizeof(element));
+ if (*d)
+ sz += _asn1_length(tactual_type->ptr, *d);
+ } else {
+ size_t bodysz;
+ const void * const * val =
+ DPOC(data, t->offset + sizeof(element) + sizeof(*lenp));
+
+ /* Compute the size of the encoded SET OF / SEQUENCE OF body */
+ for (i = 0, bodysz = 0; i < len; i++) {
+ if (val[i])
+ bodysz += _asn1_length(tactual_type->ptr, val[i]);
+ }
+
+ /*
+ * We now know the size of the body of the SET OF or SEQUENCE OF. Now
+ * we just need to count the length of all the TLs on the outside.
+ */
+ sz += _asn1_length_open_type_helper(topentype, bodysz);
+ }
+ return sz;
+}
+
+size_t
+_asn1_length(const struct asn1_template *t, const void *data)
+{
+ const struct asn1_template *tbase = t;
+ size_t elements = A1_HEADER_LEN(t);
+ size_t ret = 0;
+
+ t += A1_HEADER_LEN(t);
+
+ while (elements) {
+ switch (t->tt & A1_OP_MASK) {
+ case A1_OP_OPENTYPE_OBJSET: {
+ size_t opentypeid = t->tt & ((1<<10)-1);
+ size_t opentype = (t->tt >> 10) & ((1<<10)-1);
+ ret += _asn1_length_open_type(tbase, t, data,
+ template4member(tbase, opentypeid),
+ template4member(tbase, opentype));
+ break;
+ }
+ case A1_OP_NAME: break;
+ case A1_OP_DEFVAL: break;
+ case A1_OP_TYPE_DECORATE_EXTERN: break;
+ case A1_OP_TYPE_DECORATE: break;
+ case A1_OP_TYPE:
+ case A1_OP_TYPE_EXTERN: {
+ const void *el = DPOC(data, t->offset);
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ void **pel = (void **)el;
+ if (*pel == NULL)
+ break;
+ el = *pel;
+ } else if ((t->tt & A1_FLAG_DEFAULT) && elements > 1) {
+ const struct asn1_template *tdefval = t - 1;
+
+ /* Compare tdefval to whatever's at `el' */
+ if (tdefval->tt & A1_DV_BOOLEAN) {
+ const int *i = (void *)(char *)el;
+
+ if ((*i && tdefval->ptr) || (!*i && !tdefval->ptr))
+ break;
+ } else if (tdefval->tt & A1_DV_INTEGER64) {
+ const int64_t *i = (void *)(char *)el;
+
+ if (*i == (int64_t)(intptr_t)tdefval->ptr)
+ break;
+ } else if (tdefval->tt & A1_DV_INTEGER32) {
+ const int32_t *i = (void *)(char *)el;
+
+ if ((int64_t)(intptr_t)tdefval->ptr <= INT_MAX &&
+ (int64_t)(intptr_t)tdefval->ptr >= INT_MIN &&
+ *i == (int32_t)(intptr_t)tdefval->ptr)
+ break;
+ } else if (tdefval->tt & A1_DV_INTEGER) {
+ const struct heim_integer *i = (void *)(char *)el;
+
+ if (der_heim_integer_cmp(i, tdefval->ptr) == 0)
+ break;
+ } else if (tdefval->tt & A1_DV_UTF8STRING) {
+ const char * const *s = el;
+
+ if (*s && strcmp(*s, tdefval->ptr) == 0)
+ break;
+ } else {
+ abort();
+ }
+ }
+
+ if ((t->tt & A1_OP_MASK) == A1_OP_TYPE) {
+ ret += _asn1_length(t->ptr, el);
+ } else {
+ const struct asn1_type_func *f = t->ptr;
+ ret += (f->length)(el);
+ }
+ break;
+ }
+ case A1_OP_TAG: {
+ size_t datalen;
+ const void *olddata = data;
+ size_t oldtaglen = 0;
+
+ data = DPO(data, t->offset);
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ void **el = (void **)data;
+ if (*el == NULL) {
+ data = olddata;
+ break;
+ }
+ data = *el;
+ } else if ((t->tt & A1_FLAG_DEFAULT) && elements > 1) {
+ const struct asn1_template *tdefval = t - 1;
+ int exclude = 0;
+
+ /* Compare tdefval to whatever's at `data' */
+ if (tdefval->tt & A1_DV_BOOLEAN) {
+ const int *i = (void *)(char *)data;
+
+ if ((*i && tdefval->ptr) || (!*i && !tdefval->ptr))
+ exclude = 1;
+ } else if (tdefval->tt & A1_DV_INTEGER64) {
+ const int64_t *i = (void *)(char *)data;
+
+ if (*i == (int64_t)(intptr_t)tdefval->ptr)
+ exclude = 1;
+ } else if (tdefval->tt & A1_DV_INTEGER32) {
+ const int32_t *i = (void *)(char *)data;
+
+ if ((int64_t)(intptr_t)tdefval->ptr <= INT_MAX &&
+ (int64_t)(intptr_t)tdefval->ptr >= INT_MIN &&
+ *i == (int32_t)(intptr_t)tdefval->ptr)
+ exclude = 1;
+ } else if (tdefval->tt & A1_DV_INTEGER) {
+ const struct heim_integer *i = (void *)(char *)data;
+
+ if (der_heim_integer_cmp(i, tdefval->ptr) == 0)
+ exclude = 1;
+ } else if (tdefval->tt & A1_DV_UTF8STRING) {
+ const char * const *s = data;
+
+ if (*s && strcmp(*s, tdefval->ptr) == 0)
+ exclude = 1;
+ } else {
+ abort();
+ }
+ if (exclude) {
+ data = olddata;
+ break;
+ }
+ }
+
+ if (t->tt & A1_FLAG_IMPLICIT)
+ oldtaglen = inner_type_taglen(t->ptr);
+
+ datalen = _asn1_length(t->ptr, data);
+ ret += datalen;
+ ret += der_length_tag(A1_TAG_TAG(t->tt));
+ ret += oldtaglen ? -oldtaglen : der_length_len(datalen);
+ data = olddata;
+ break;
+ }
+ case A1_OP_PARSE: {
+ unsigned int type = A1_PARSE_TYPE(t->tt);
+ const void *el = DPOC(data, t->offset);
+
+ if (type >= sizeof(asn1_template_prim)/sizeof(asn1_template_prim[0])) {
+ ABORT_ON_ERROR();
+ break;
+ }
+ ret += (asn1_template_prim[type].length)(el);
+ break;
+ }
+ case A1_OP_SETOF:
+ case A1_OP_SEQOF: {
+ const struct template_of *el = DPOC(data, t->offset);
+ size_t ellen = _asn1_sizeofType(t->ptr);
+ const unsigned char *element = el->val;
+ unsigned int i;
+
+ for (i = 0; i < el->len; i++) {
+ ret += _asn1_length(t->ptr, element);
+ element += ellen;
+ }
+
+ break;
+ }
+ case A1_OP_BMEMBER: {
+ const struct asn1_template *bmember = t->ptr;
+ size_t size = bmember->offset;
+ size_t belements = A1_HEADER_LEN(bmember);
+ int rfc1510 = (bmember->tt & A1_HBF_RFC1510);
+
+ if (rfc1510) {
+ ret += 5;
+ } else {
+
+ ret += 1;
+
+ bmember += belements;
+
+ while (belements) {
+ if (_asn1_bmember_isset_bit(data, bmember->offset, size)) {
+ ret += (bmember->offset / 8) + 1;
+ break;
+ }
+ belements--; bmember--;
+ }
+ }
+ break;
+ }
+ case A1_OP_CHOICE: {
+ const struct asn1_template *choice = t->ptr;
+ const unsigned int *element = DPOC(data, choice->offset);
+
+ if (*element > A1_HEADER_LEN(choice))
+ break;
+
+ if (*element == 0) {
+ ret += der_length_octet_string(DPOC(data, choice->tt));
+ } else {
+ choice += *element;
+ ret += _asn1_length(choice->ptr, DPOC(data, choice->offset));
+ }
+ break;
+ }
+ default:
+ ABORT_ON_ERROR();
+ break;
+ }
+ elements--;
+ t--;
+ }
+ return ret;
+}
+
+/* See commentary in _asn1_decode_open_type() */
+static void
+_asn1_free_open_type(const struct asn1_template *t, /* object set template */
+ void *data)
+{
+ const struct asn1_template *tactual_type;
+ const struct asn1_template *tos = t->ptr;
+ unsigned int *lenp = NULL; /* Pointer to array length field */
+ unsigned int len = 1; /* Array length */
+ size_t i;
+ void **dp;
+ void **val;
+ int *elementp = DPO(data, t->offset); /* Choice enum pointer */
+
+ /* XXX We assume sizeof(enum) == sizeof(int) */
+ if (!*elementp || *elementp >= A1_HEADER_LEN(tos) + 1)
+ return; /* Unknown choice -> it's not decoded, nothing to free here */
+ tactual_type = tos[3*(*elementp - 1) + 4].ptr;
+
+ if (!(t->tt & A1_OS_OT_IS_ARRAY)) {
+ dp = DPO(data, t->offset + sizeof(*elementp));
+ while (sizeof(void *) != sizeof(*elementp) &&
+ ((uintptr_t)dp) % sizeof(void *) != 0)
+ dp = (void *)(((char *)dp) + sizeof(*elementp));
+ if (*dp) {
+ _asn1_free(tactual_type, *dp);
+ free(*dp);
+ *dp = NULL;
+ }
+ return;
+ }
+
+ lenp = DPO(data, t->offset + sizeof(*elementp));
+ len = *lenp;
+ dp = DPO(data, t->offset + sizeof(*elementp) + sizeof(*lenp));
+ while (sizeof(void *) != sizeof(*elementp) &&
+ ((uintptr_t)dp) % sizeof(void *) != 0)
+ dp = (void *)(((char *)dp) + sizeof(*elementp));
+ val = *dp;
+
+ for (i = 0; i < len; i++) {
+ if (val[i]) {
+ _asn1_free(tactual_type, val[i]);
+ free(val[i]);
+ }
+ }
+ free(val);
+ *lenp = 0;
+ *dp = NULL;
+}
+
+void
+_asn1_free(const struct asn1_template *t, void *data)
+{
+ size_t elements = A1_HEADER_LEN(t);
+
+ if (t->tt & A1_HF_PRESERVE)
+ der_free_octet_string(data);
+
+ t++;
+
+ while (elements) {
+ switch (t->tt & A1_OP_MASK) {
+ case A1_OP_OPENTYPE_OBJSET: {
+ _asn1_free_open_type(t, data);
+ break;
+ }
+ case A1_OP_NAME: break;
+ case A1_OP_DEFVAL: break;
+ case A1_OP_TYPE_DECORATE_EXTERN:
+ case A1_OP_TYPE_DECORATE:
+ case A1_OP_TYPE:
+ case A1_OP_TYPE_EXTERN: {
+ void *el = DPO(data, t->offset);
+ void **pel = (void **)el;
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ if (*pel == NULL)
+ break;
+ el = *pel;
+ }
+
+ if ((t->tt & A1_OP_MASK) == A1_OP_TYPE || (t->tt & A1_OP_MASK) == A1_OP_TYPE_DECORATE) {
+ _asn1_free(t->ptr, el);
+ } else if ((t->tt & A1_OP_MASK) == A1_OP_TYPE_EXTERN) {
+ const struct asn1_type_func *f = t->ptr;
+ (f->release)(el);
+ } else {
+ /* A1_OP_TYPE_DECORATE_EXTERN */
+ const struct asn1_type_func *f = t->ptr;
+
+ if (f && f->release)
+ (f->release)(el);
+ else if (f)
+ memset(el, 0, f->size);
+ }
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ free(el);
+ *pel = NULL;
+ }
+
+ break;
+ }
+ case A1_OP_PARSE: {
+ unsigned int type = A1_PARSE_TYPE(t->tt);
+ void *el = DPO(data, t->offset);
+
+ if (type >= sizeof(asn1_template_prim)/sizeof(asn1_template_prim[0])) {
+ ABORT_ON_ERROR();
+ break;
+ }
+ (asn1_template_prim[type].release)(el);
+ break;
+ }
+ case A1_OP_TAG: {
+ void *el = DPO(data, t->offset);
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ void **pel = (void **)el;
+
+ if (*pel == NULL)
+ break;
+ _asn1_free(t->ptr, *pel);
+ free(*pel);
+ *pel = NULL;
+ } else {
+ _asn1_free(t->ptr, el);
+ }
+
+ break;
+ }
+ case A1_OP_SETOF:
+ case A1_OP_SEQOF: {
+ struct template_of *el = DPO(data, t->offset);
+ size_t ellen = _asn1_sizeofType(t->ptr);
+ unsigned char *element = el->val;
+ unsigned int i;
+
+ for (i = 0; i < el->len; i++) {
+ _asn1_free(t->ptr, element);
+ element += ellen;
+ }
+ free(el->val);
+ el->val = NULL;
+ el->len = 0;
+
+ break;
+ }
+ case A1_OP_BMEMBER:
+ break;
+ case A1_OP_CHOICE: {
+ const struct asn1_template *choice = t->ptr;
+ const unsigned int *element = DPOC(data, choice->offset);
+
+ if (*element > A1_HEADER_LEN(choice))
+ break;
+
+ if (*element == 0) {
+ der_free_octet_string(DPO(data, choice->tt));
+ } else {
+ choice += *element;
+ _asn1_free(choice->ptr, DPO(data, choice->offset));
+ }
+ break;
+ }
+ default:
+ ABORT_ON_ERROR();
+ break;
+ }
+ t++;
+ elements--;
+ }
+}
+
+static char *
+getindent(int flags, unsigned int i)
+{
+ char *s;
+
+ if (!(flags & ASN1_PRINT_INDENT) || i == 0)
+ return NULL;
+ if (i > 128)
+ i = 128;
+ if ((s = malloc(i * 2 + 2)) == NULL)
+ return NULL;
+ s[0] = '\n';
+ s[i * 2 + 1] = '\0';
+ memset(s + 1, ' ', i * 2);
+ return s;
+}
+
+static struct rk_strpool *_asn1_print(const struct asn1_template *,
+ struct rk_strpool *,
+ int,
+ unsigned int,
+ const void *,
+ const heim_octet_string *);
+
+/* See commentary in _asn1_decode_open_type() */
+static struct rk_strpool *
+_asn1_print_open_type(const struct asn1_template *t, /* object set template */
+ struct rk_strpool *r,
+ int flags,
+ unsigned int indent,
+ const void *data,
+ const char *opentype_name)
+{
+ const struct asn1_template *tactual_type;
+ const struct asn1_template *tos = t->ptr;
+ const unsigned int *lenp = NULL; /* Pointer to array length field */
+ unsigned int len = 1; /* Array length */
+ size_t i;
+ const void * const *dp;
+ const void * const *val;
+ const int *elementp = DPOC(data, t->offset); /* Choice enum pointer */
+ char *indents = getindent(flags, indent);
+
+ /* XXX We assume sizeof(enum) == sizeof(int) */
+ if (!*elementp || *elementp >= A1_HEADER_LEN(tos) + 1) {
+ r = rk_strpoolprintf(r, ",%s\"_%s_choice\":\"_ERROR_DECODING_\"",
+ indents ? indents : "", opentype_name);
+ free(indents);
+ return r;
+ }
+ tactual_type = tos[3*(*elementp - 1) + 4].ptr;
+
+ r = rk_strpoolprintf(r, ",%s\"_%s_choice\":\"%s\"",
+ indents ? indents : "", opentype_name,
+ (const char *)tos[3*(*elementp - 1) + 2].ptr);
+ if (!r) {
+ free(indents);
+ return r;
+ }
+
+ if (!(t->tt & A1_OS_OT_IS_ARRAY)) {
+ dp = DPOC(data, t->offset + sizeof(*elementp));
+ while (sizeof(void *) != sizeof(*elementp) &&
+ ((uintptr_t)dp) % sizeof(void *) != 0)
+ dp = (void *)(((char *)dp) + sizeof(*elementp));
+ if (*dp) {
+ struct rk_strpool *r2 = NULL;
+ char *s = NULL;
+
+ r2 = _asn1_print(tactual_type, r2, flags, indent + 1, *dp, NULL);
+ if (r2 == NULL) {
+ r = rk_strpoolprintf(r, ",%s\"_%s\":\"_ERROR_FORMATTING_\"",
+ indents ? indents : "", opentype_name);
+ free(indents);
+ return r;
+ }
+ s = rk_strpoolcollect(r2);
+ if (s)
+ r = rk_strpoolprintf(r, ",%s\"_%s\":%s",
+ indents ? indents : "", opentype_name, s);
+ free(s);
+ }
+ free(indents);
+ return r;
+ }
+
+ lenp = DPOC(data, t->offset + sizeof(*elementp));
+ len = *lenp;
+ dp = DPOC(data, t->offset + sizeof(*elementp) + sizeof(*lenp));
+ while (sizeof(void *) != sizeof(*elementp) &&
+ ((uintptr_t)dp) % sizeof(void *) != 0)
+ dp = (void *)(((char *)dp) + sizeof(*elementp));
+ val = *dp;
+
+ r = rk_strpoolprintf(r, ",%s\"_%s\":[", indents ? indents : "",
+ opentype_name);
+ free(indents);
+ indents = getindent(flags, indent + 1);
+ r = rk_strpoolprintf(r, "%s", indents ? indents : "");
+ for (i = 0; r && i < len; i++) {
+ struct rk_strpool *r2 = NULL;
+ char *s = NULL;;
+
+ if (val[i]) {
+ r2 = _asn1_print(tactual_type, r2, flags, indent + 2, val[i], NULL);
+ if (r2 == NULL) {
+ rk_strpoolfree(r);
+ free(indents);
+ return NULL;
+ }
+ }
+ if (i)
+ r = rk_strpoolprintf(r, ",%s", indents ? indents : "");
+ if (r)
+ r = rk_strpoolprintf(r, "%s", (s = rk_strpoolcollect(r2)));
+ free(s);
+ }
+ free(indents);
+ return rk_strpoolprintf(r, "]");
+}
+
+static struct rk_strpool *
+_asn1_print(const struct asn1_template *t,
+ struct rk_strpool *r,
+ int flags,
+ unsigned int indent,
+ const void *data,
+ const heim_octet_string *saved)
+{
+ const struct asn1_template *tbase = t;
+ const struct asn1_template *tnames;
+ size_t nelements = A1_HEADER_LEN(t);
+ size_t elements = nelements;
+ size_t nnames = 0;
+ char *indents = getindent(flags, indent);
+
+ for (t += nelements; t > tbase && (t->tt & A1_OP_MASK) == A1_OP_NAME; t--)
+ nnames++;
+
+ tnames = tbase + nelements - nnames + 1;
+
+ if (!r)
+ r = rk_strpoolprintf(r, "%s", "");
+
+ if (nnames)
+ r = rk_strpoolprintf(r, "%s{\"_type\":\"%s\"",
+ indents ? indents : "",
+ (const char *)(tnames++)->ptr);
+ if (saved && r) {
+ char *s = der_print_octet_string(data, 0);
+
+ if (!s) {
+ rk_strpoolfree(r);
+ free(indents);
+ return NULL;
+ }
+ r = rk_strpoolprintf(r, ",%s\"_save\":\"%s\"",
+ indents ? indents : "", s);
+ free(s);
+ }
+ saved = NULL;
+ if (tbase->tt & A1_HF_PRESERVE)
+ saved = data;
+
+ t = tbase + 1;
+ while (r && elements && (t->tt & A1_OP_MASK) != A1_OP_NAME) {
+ switch (t->tt & A1_OP_MASK) {
+ case A1_OP_NAME:
+ continue;
+ case A1_OP_DEFVAL:
+ t++;
+ elements--;
+ continue;
+ case A1_OP_OPENTYPE_OBJSET: {
+ size_t opentype = (t->tt >> 10) & ((1<<10)-1);
+ r = _asn1_print_open_type(t, r, flags, indent + 1, data,
+ tbase[(nelements - nnames) + 2 + opentype].ptr);
+ t++;
+ elements--;
+ continue;
+ }
+ default: break;
+ }
+ if (nnames)
+ r = rk_strpoolprintf(r, ",%s\"%s\":",
+ indents ? indents : "",
+ (const char *)(tnames++)->ptr);
+ switch (t->tt & A1_OP_MASK) {
+ case A1_OP_OPENTYPE_OBJSET:
+ break;
+ case A1_OP_NAME: break;
+ case A1_OP_DEFVAL: break;
+ case A1_OP_TYPE_DECORATE_EXTERN: break;
+ case A1_OP_TYPE_DECORATE: break; /* We could probably print this though */
+ case A1_OP_TYPE:
+ case A1_OP_TYPE_EXTERN: {
+ const void *el = DPOC(data, t->offset);
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ const void * const *pel = (const void *const *)el;
+ if (*pel == NULL) {
+ r = rk_strpoolprintf(r, "null");
+ break;
+ }
+ el = *pel;
+ }
+
+ if ((t->tt & A1_OP_MASK) == A1_OP_TYPE) {
+ r = _asn1_print(t->ptr, r, flags, indent + 1, el, saved);
+ } else {
+ const struct asn1_type_func *f = t->ptr;
+ char *s = NULL;
+
+ s = (f->print)(el, 0);
+ if (s == NULL) {
+ rk_strpoolfree(r);
+ free(indents);
+ return NULL;
+ }
+ r = rk_strpoolprintf(r, "%s", s);
+ free(s);
+ }
+ break;
+ }
+ case A1_OP_PARSE: {
+ unsigned int type = A1_PARSE_TYPE(t->tt);
+ const void *el = DPOC(data, t->offset);
+ char *s = NULL;
+
+ if (type >= sizeof(asn1_template_prim)/sizeof(asn1_template_prim[0])) {
+ ABORT_ON_ERROR();
+ break;
+ }
+
+ if (type == A1T_IMEMBER && t->ptr) {
+ /* Enumeration. Use the symbolic name of this value */
+ const struct asn1_template *tenum = t->ptr;
+ size_t left = 0;
+ size_t right = A1_HEADER_LEN(tenum);
+ size_t mid;
+ uint32_t v = *(unsigned int *)el;
+ int c = -1;
+
+ while (left <= right) {
+ mid = (left + right) >> 1;
+
+ if ((tenum[mid].tt & A1_OP_MASK) != A1_OP_NAME)
+ break;
+ c = v - tenum[mid].offset;
+ if (c < 0) {
+ if (mid)
+ right = mid - 1;
+ else
+ break;
+ } else if (c > 0) {
+ left = mid + 1;
+ } else {
+ break;
+ }
+ }
+ if (c == 0) {
+ r = rk_strpoolprintf(r, "\"%s\"", (const char *)tenum[mid].ptr);
+ break;
+ }
+ }
+ s = (asn1_template_prim[type].print)(el, flags);
+ switch (type) {
+ case A1T_OID:
+ case A1T_IMEMBER:
+ case A1T_BOOLEAN:
+ case A1T_INTEGER:
+ case A1T_INTEGER64:
+ case A1T_UNSIGNED:
+ case A1T_UNSIGNED64:
+ if (s)
+ r = rk_strpoolprintf(r, "%s", s);
+ break;
+ default: {
+ char *s2 = NULL;
+
+ if (s)
+ (void) rk_strasvis(&s2, s, VIS_CSTYLE|VIS_TAB|VIS_NL, "\"");
+ free(s);
+ s = s2;
+ if (s)
+ r = rk_strpoolprintf(r, "\"%s\"", s);
+ }
+ }
+ if (!s) {
+ rk_strpoolfree(r);
+ free(indents);
+ return NULL;
+ }
+ free(s);
+ break;
+ }
+ case A1_OP_TAG: {
+ const void *el = DPOC(data, t->offset);
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ const void * const *pel = (const void * const *)el;
+ if (*pel == NULL) {
+ r = rk_strpoolprintf(r, "null");
+ break;
+ }
+ el = *pel;
+ }
+
+ r = _asn1_print(t->ptr, r, flags, indent + 1, el, saved);
+ break;
+ }
+ case A1_OP_SETOF:
+ case A1_OP_SEQOF: {
+ const struct template_of *el = DPOC(data, t->offset);
+ size_t ellen = _asn1_sizeofType(t->ptr);
+ const unsigned char *element = el->val;
+ unsigned int i;
+
+ r = rk_strpoolprintf(r, "%s[", indents ? indents : "");
+ for (i = 0; r && i < el->len; i++) {
+ if (i)
+ r = rk_strpoolprintf(r, ",%s", indents ? indents : "");
+ r = _asn1_print(t->ptr, r, flags, indent + 1, element, saved);
+ element += ellen;
+ }
+ if (r)
+ r = rk_strpoolprintf(r, "]");
+ break;
+ }
+ case A1_OP_BMEMBER: {
+ const struct asn1_template *bmember = t->ptr;
+ size_t size = bmember->offset;
+ size_t belements = A1_HEADER_LEN(bmember);
+ int first = 1;
+
+ bmember += belements;
+ r = rk_strpoolprintf(r, "%s[", indents ? indents : "");
+ while (r && belements) {
+ if (r && _asn1_bmember_isset_bit(data, bmember->offset, size)) {
+ if (!first)
+ r = rk_strpoolprintf(r, ",");
+ first = 0;
+ r = rk_strpoolprintf(r, "%s\"%s\"", indents ? indents : "",
+ (const char *)bmember->ptr);
+ }
+ belements--; bmember--;
+ }
+ if (r)
+ r = rk_strpoolprintf(r, "]");
+ break;
+ }
+ case A1_OP_CHOICE: {
+ const struct asn1_template *choice = t->ptr;
+ const unsigned int *element = DPOC(data, choice->offset);
+ unsigned int nchoices = ((uintptr_t)choice->ptr) >> 1;
+
+ if (*element > A1_HEADER_LEN(choice)) {
+ r = rk_strpoolprintf(r, "null");
+ } else if (*element == 0) {
+ r = rk_strpoolprintf(r, "null");
+ } else {
+ choice += *element;
+ r = rk_strpoolprintf(r, "%s{\"_choice\":\"%s\",%s\"value\":",
+ indents ? indents : "",
+ (const char *)choice[nchoices].ptr,
+ indents ? indents : "");
+ if (r)
+ r = _asn1_print(choice->ptr, r, flags, indent + 1,
+ DPOC(data, choice->offset), NULL);
+ if (r)
+ r = rk_strpoolprintf(r, "}");
+ }
+ break;
+ }
+ default:
+ ABORT_ON_ERROR();
+ break;
+ }
+ t++;
+ elements--;
+ }
+ free(indents);
+ if (nnames && r)
+ return rk_strpoolprintf(r, "}");
+ return r;
+}
+
+char *
+_asn1_print_top(const struct asn1_template *t,
+ int flags,
+ const void *data)
+{
+ struct rk_strpool *r = _asn1_print(t, NULL, flags, 0, data, NULL);
+
+ if (r == NULL)
+ return NULL;
+ return rk_strpoolcollect(r);
+}
+
+/* See commentary in _asn1_decode_open_type() */
+static int
+_asn1_copy_open_type(const struct asn1_template *t, /* object set template */
+ const void *from,
+ void *to)
+{
+ const struct asn1_template *tactual_type;
+ const struct asn1_template *tos = t->ptr;
+ size_t i;
+ const void * const *dfromp;
+ const void * const *valfrom;
+ const unsigned int *lenfromp;
+ void **dtop;
+ void **valto;
+ unsigned int *lentop;
+ unsigned int len;
+ const int *efromp = DPO(from, t->offset);
+ int *etop = DPO(to, t->offset);
+ int ret = 0;
+
+ /* XXX We assume sizeof(enum) == sizeof(int) */
+ if (!*efromp || *efromp >= A1_HEADER_LEN(tos) + 1) {
+ if ((t->tt & A1_OS_OT_IS_ARRAY))
+ memset(etop, 0, sizeof(int) + sizeof(unsigned int) + sizeof(void *));
+ else
+ memset(etop, 0, sizeof(int) + sizeof(void *));
+ return 0; /* Unknown choice -> not copied */
+ }
+ tactual_type = &tos[3*(*efromp - 1) + 4];
+
+ if (!(t->tt & A1_OS_OT_IS_ARRAY)) {
+ dfromp = DPO(from, t->offset + sizeof(*efromp));
+ while (sizeof(void *) != sizeof(*efromp) &&
+ ((uintptr_t)dfromp) % sizeof(void *) != 0)
+ dfromp = (void *)(((char *)dfromp) + sizeof(*efromp));
+ if (!*dfromp)
+ return 0;
+
+ dtop = DPO(to, t->offset + sizeof(*etop));
+ while (sizeof(void *) != sizeof(*etop) &&
+ ((uintptr_t)dtop) % sizeof(void *) != 0)
+ dtop = (void *)(((char *)dtop) + sizeof(*etop));
+
+ if ((*dtop = calloc(1, tactual_type->offset)) == NULL)
+ ret = ENOMEM;
+ if (ret == 0)
+ ret = _asn1_copy(tactual_type->ptr, *dfromp, *dtop);
+ if (ret == 0)
+ *etop = *efromp;
+ return ret;
+ }
+
+ lenfromp = DPO(from, t->offset + sizeof(*efromp));
+ dfromp = DPO(from, t->offset + sizeof(*efromp) + sizeof(*lenfromp));
+ valfrom = *dfromp;
+ lentop = DPO(to, t->offset + sizeof(*etop));
+ dtop = DPO(to, t->offset + sizeof(*etop) + sizeof(*lentop));
+
+ *etop = *efromp;
+
+ len = *lenfromp;
+ *lentop = 0;
+ *dtop = NULL;
+ if ((valto = calloc(len, sizeof(valto[0]))) == NULL)
+ ret = ENOMEM;
+ for (i = 0, len = *lenfromp; ret == 0 && i < len; i++) {
+ if (valfrom[i] == NULL) {
+ valto[i] = NULL;
+ continue;
+ }
+ if ((valto[i] = calloc(1, tactual_type->offset)) == NULL)
+ ret = ENOMEM;
+ else
+ ret = _asn1_copy(tactual_type->ptr, valfrom[i], valto[i]);
+ (*lentop)++;
+ }
+
+ for (i = 0; ret && i < (*lentop); i++) {
+ if (valto[i]) {
+ _asn1_free(tactual_type->ptr, valto[i]);
+ free(valto[i]);
+ }
+ }
+ if (ret) {
+ free(valto);
+ *lentop = 0;
+ } else
+ *dtop = valto;
+ return ret;
+}
+
+int
+_asn1_copy(const struct asn1_template *t, const void *from, void *to)
+{
+ size_t elements = A1_HEADER_LEN(t);
+ int ret = 0;
+ int preserve = (t->tt & A1_HF_PRESERVE);
+
+ t++;
+
+ if (preserve) {
+ ret = der_copy_octet_string(from, to);
+ if (ret)
+ return ret;
+ }
+
+ while (elements) {
+ switch (t->tt & A1_OP_MASK) {
+ case A1_OP_OPENTYPE_OBJSET: {
+ _asn1_copy_open_type(t, from, to);
+ break;
+ }
+ case A1_OP_NAME: break;
+ case A1_OP_DEFVAL: break;
+ case A1_OP_TYPE_DECORATE_EXTERN:
+ case A1_OP_TYPE_DECORATE:
+ case A1_OP_TYPE:
+ case A1_OP_TYPE_EXTERN: {
+ const void *fel = DPOC(from, t->offset);
+ void *tel = DPO(to, t->offset);
+ void **ptel = (void **)tel;
+ size_t size;
+
+ if ((t->tt & A1_OP_MASK) == A1_OP_TYPE ||
+ (t->tt & A1_OP_MASK) == A1_OP_TYPE_DECORATE) {
+ size = _asn1_sizeofType(t->ptr);
+ } else {
+ const struct asn1_type_func *f = t->ptr;
+ size = f->size;
+ }
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ void **pfel = (void **)fel;
+ if (*pfel == NULL)
+ break;
+ fel = *pfel;
+
+ tel = *ptel = calloc(1, size);
+ if (tel == NULL)
+ return ENOMEM;
+ }
+
+ if ((t->tt & A1_OP_MASK) == A1_OP_TYPE ||
+ (t->tt & A1_OP_MASK) == A1_OP_TYPE_DECORATE) {
+ ret = _asn1_copy(t->ptr, fel, tel);
+ } else if ((t->tt & A1_OP_MASK) == A1_OP_TYPE_EXTERN) {
+ const struct asn1_type_func *f = t->ptr;
+ ret = (f->copy)(fel, tel);
+ } else {
+ const struct asn1_type_func *f = t->ptr;
+
+ /* A1_OP_TYPE_DECORATE_EXTERN */
+ if (f && f->copy)
+ ret = (f->copy)(fel, tel);
+ else if (f)
+ memset(tel, 0, f->size);
+ }
+
+ if (ret) {
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ free(*ptel);
+ *ptel = NULL;
+ }
+ return ret;
+ }
+ break;
+ }
+ case A1_OP_PARSE: {
+ unsigned int type = A1_PARSE_TYPE(t->tt);
+ const void *fel = DPOC(from, t->offset);
+ void *tel = DPO(to, t->offset);
+
+ if (type >= sizeof(asn1_template_prim)/sizeof(asn1_template_prim[0])) {
+ ABORT_ON_ERROR();
+ return ASN1_PARSE_ERROR;
+ }
+ ret = (asn1_template_prim[type].copy)(fel, tel);
+ if (ret)
+ return ret;
+ break;
+ }
+ case A1_OP_TAG: {
+ const void *oldfrom = from;
+ void *oldto = to;
+ void **tel = NULL;
+
+ from = DPOC(from, t->offset);
+ to = DPO(to, t->offset);
+
+ if (t->tt & A1_FLAG_OPTIONAL) {
+ void **fel = (void **)from;
+ tel = (void **)to;
+ if (*fel == NULL) {
+ from = oldfrom;
+ to = oldto;
+ break;
+ }
+ from = *fel;
+
+ to = *tel = calloc(1, _asn1_sizeofType(t->ptr));
+ if (to == NULL)
+ return ENOMEM;
+ }
+
+ ret = _asn1_copy(t->ptr, from, to);
+ if (ret) {
+ if (tel) {
+ free(*tel);
+ *tel = NULL;
+ }
+ return ret;
+ }
+
+ from = oldfrom;
+ to = oldto;
+
+ break;
+ }
+ case A1_OP_SETOF:
+ case A1_OP_SEQOF: {
+ const struct template_of *fel = DPOC(from, t->offset);
+ struct template_of *tel = DPO(to, t->offset);
+ size_t ellen = _asn1_sizeofType(t->ptr);
+ unsigned int i;
+
+ tel->val = calloc(fel->len, ellen);
+ if (tel->val == NULL)
+ return ENOMEM;
+
+ tel->len = fel->len;
+
+ for (i = 0; i < fel->len; i++) {
+ ret = _asn1_copy(t->ptr,
+ DPOC(fel->val, (i * ellen)),
+ DPO(tel->val, (i *ellen)));
+ if (ret)
+ return ret;
+ }
+ break;
+ }
+ case A1_OP_BMEMBER: {
+ const struct asn1_template *bmember = t->ptr;
+ size_t size = bmember->offset;
+ memcpy(to, from, size);
+ break;
+ }
+ case A1_OP_CHOICE: {
+ const struct asn1_template *choice = t->ptr;
+ const unsigned int *felement = DPOC(from, choice->offset);
+ unsigned int *telement = DPO(to, choice->offset);
+
+ if (*felement > A1_HEADER_LEN(choice))
+ return ASN1_PARSE_ERROR;
+
+ *telement = *felement;
+
+ if (*felement == 0) {
+ ret = der_copy_octet_string(DPOC(from, choice->tt), DPO(to, choice->tt));
+ } else {
+ choice += *felement;
+ ret = _asn1_copy(choice->ptr,
+ DPOC(from, choice->offset),
+ DPO(to, choice->offset));
+ }
+ if (ret)
+ return ret;
+ break;
+ }
+ default:
+ ABORT_ON_ERROR();
+ break;
+ }
+ t++;
+ elements--;
+ }
+ return 0;
+}
+
+int
+_asn1_decode_top(const struct asn1_template *t, unsigned flags, const unsigned char *p, size_t len, void *data, size_t *size)
+{
+ int ret;
+ memset(data, 0, t->offset);
+ ret = _asn1_decode(t, flags, p, len, data, size);
+ if (ret)
+ _asn1_free_top(t, data);
+
+ return ret;
+}
+
+int
+_asn1_copy_top(const struct asn1_template *t, const void *from, void *to)
+{
+ int ret;
+ memset(to, 0, t->offset);
+ ret = _asn1_copy(t, from, to);
+ if (ret)
+ _asn1_free_top(t, to);
+
+ return ret;
+}
+
+void
+_asn1_free_top(const struct asn1_template *t, void *data)
+{
+ _asn1_free(t, data);
+ memset(data, 0, t->offset);
+}
diff --git a/third_party/heimdal/lib/asn1/test.asn1 b/third_party/heimdal/lib/asn1/test.asn1
new file mode 100644
index 0000000..08c7dcd
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/test.asn1
@@ -0,0 +1,309 @@
+-- $Id$ --
+
+TEST DEFINITIONS ::=
+
+BEGIN
+
+IMPORTS HEIM_ANY FROM heim;
+
+-- Check that we handle out of order definitions.
+-- The compiler should emit the definition of TESTOutOfOrderBar before that of
+-- TESTOutOfOrderFoo.
+TESTOutOfOrderFoo ::= SEQUENCE {
+ bar TESTOutOfOrderBar
+}
+
+TESTOutOfOrderBar ::= SEQUENCE {
+ aMember INTEGER
+}
+
+-- Check that we can handle rpc.mountd style "lists". This is unnecessarily
+-- inefficient in its encoding, and there's no point to using this over
+-- SEQUENCE OF (arrays), but it's neat that we can do this now that we can do
+-- out of order definitions.
+--
+-- This could be useful if we ever extend asn1_compile to also handle XDR,
+-- which we well might since XDR's syntax is a dual of a strict subset of
+-- ASN.1, and since XDR the encoding is fairly straightforward.
+--
+-- Note that the `next' member has to be OPTIONAL for this to work.
+TESTCircular ::= SEQUENCE {
+ name UTF8String,
+ next TESTCircular OPTIONAL
+}
+
+TESTDefault ::= SEQUENCE {
+ name UTF8String DEFAULT "Heimdal",
+ version [0] TESTuint32 DEFAULT 8,
+ maxint TESTuint64 DEFAULT 9223372036854775807,
+ works BOOLEAN DEFAULT TRUE
+}
+
+TESTuint32 ::= INTEGER (0..4294967295)
+TESTuint64 ::= INTEGER(0..9223372036854775807)
+TESTint64 ::= INTEGER(-9223372036854775808..9223372036854775807)
+
+TESTLargeTag ::= SEQUENCE {
+ foo[127] INTEGER (-2147483648..2147483647),
+ bar[128] INTEGER (-2147483648..2147483647)
+}
+
+TESTSeq ::= SEQUENCE {
+ tag0[0] INTEGER (-2147483648..2147483647),
+ tag1[1] TESTLargeTag,
+ tagless INTEGER (-2147483648..2147483647),
+ tag3[2] INTEGER (-2147483648..2147483647)
+}
+
+TESTChoice1 ::= CHOICE {
+ i1[1] INTEGER (-2147483648..2147483647),
+ i2[2] INTEGER (-2147483648..2147483647),
+ ...
+}
+
+TESTChoice2 ::= CHOICE {
+ i1[1] INTEGER (-2147483648..2147483647),
+ ...
+}
+
+TESTInteger ::= INTEGER (-2147483648..2147483647)
+
+TESTInteger2 ::= [4] IMPLICIT TESTInteger
+TESTInteger3 ::= [5] IMPLICIT TESTInteger2
+
+TESTImplicit ::= SEQUENCE {
+ ti1[0] IMPLICIT INTEGER (-2147483648..2147483647),
+ ti2[1] IMPLICIT SEQUENCE {
+ foo[127] INTEGER (-2147483648..2147483647)
+ },
+ ti3[2] IMPLICIT [5] IMPLICIT [4] IMPLICIT INTEGER (-2147483648..2147483647)
+}
+
+TESTImplicit2 ::= SEQUENCE {
+ ti1[0] IMPLICIT TESTInteger,
+-- ti2[1] IMPLICIT TESTLargeTag, this is disabled since the IMPLICT encoder does't get the types right when stepping inside an structure --
+ ti3[2] IMPLICIT TESTInteger3,
+ ti4[51] IMPLICIT TESTInteger OPTIONAL
+}
+
+TESTImplicit3 ::= CHOICE {
+ ti1[0] IMPLICIT INTEGER (-2147483648..2147483647),
+ ti2[5] IMPLICIT CHOICE { i1[1] INTEGER (-2147483648..2147483647) }
+}
+
+TESTImplicit4 ::= CHOICE {
+ ti1[0] IMPLICIT INTEGER (-2147483648..2147483647),
+ ti2[5] IMPLICIT TESTChoice2
+}
+
+TESTAllocInner ::= SEQUENCE {
+ ai[0] TESTInteger
+}
+
+TESTAlloc ::= SEQUENCE {
+ tagless TESTAllocInner OPTIONAL,
+ three [1] INTEGER (-2147483648..2147483647),
+ tagless2 HEIM_ANY OPTIONAL
+}
+
+TESTOptional ::= SEQUENCE {
+ zero [0] INTEGER (-2147483648..2147483647) OPTIONAL,
+ one [1] INTEGER (-2147483648..2147483647) OPTIONAL
+}
+
+
+TESTCONTAINING ::= OCTET STRING ( CONTAINING INTEGER )
+TESTENCODEDBY ::= OCTET STRING ( ENCODED BY
+ { joint-iso-itu-t(2) asn(1) ber-derived(2) distinguished-encoding(1) }
+)
+
+testDer OBJECT IDENTIFIER ::= {
+ joint-iso-itu-t(2) asn(1) ber-derived(2) distinguished-encoding(1)
+}
+
+testContainingEncodedBy ::= OCTET STRING ( CONTAINING INTEGER ENCODED BY
+ { joint-iso-itu-t(2) asn(1) ber-derived(2) distinguished-encoding(1) }
+)
+
+testContainingEncodedBy2 ::= OCTET STRING (
+ CONTAINING INTEGER ENCODED BY testDer
+)
+
+
+testValue1 INTEGER ::= 1
+
+testUserConstrained ::= OCTET STRING (CONSTRAINED BY { -- meh -- })
+-- TESTUSERCONSTRAINED2 ::= OCTET STRING (CONSTRAINED BY { TESTInteger })
+-- TESTUSERCONSTRAINED3 ::= OCTET STRING (CONSTRAINED BY { INTEGER })
+-- TESTUSERCONSTRAINED4 ::= OCTET STRING (CONSTRAINED BY { INTEGER : 1 })
+
+TESTSeqOf ::= SEQUENCE OF TESTInteger
+
+TESTSeqSizeOf1 ::= SEQUENCE SIZE (2) OF TESTInteger
+TESTSeqSizeOf2 ::= SEQUENCE SIZE (1..2) OF TESTInteger
+TESTSeqSizeOf3 ::= SEQUENCE SIZE (1..MAX) OF TESTInteger
+TESTSeqSizeOf4 ::= SEQUENCE SIZE (0..2) OF TESTInteger
+
+TESTOSSize1 ::= OCTET STRING SIZE (1..2)
+
+TESTSeqOfSeq ::= SEQUENCE OF SEQUENCE {
+ zero [0] TESTInteger
+}
+
+TESTSeqOfSeq2 ::= SEQUENCE OF SEQUENCE {
+ string [0] GeneralString
+}
+
+TESTSeqOfSeq3 ::= SEQUENCE OF SEQUENCE {
+ zero [0] TESTInteger,
+ string [0] GeneralString
+}
+
+TESTSeqOf2 ::= SEQUENCE {
+ strings SEQUENCE OF GeneralString
+}
+
+TESTSeqOf3 ::= SEQUENCE {
+ strings SEQUENCE OF GeneralString OPTIONAL
+}
+
+-- Larger/more complex to increase odds of out-of-bounds
+-- read/writes if miscoded
+
+TESTSeqOf4 ::= SEQUENCE {
+ b1 [0] SEQUENCE OF SEQUENCE {
+ s1 OCTET STRING,
+ s2 OCTET STRING,
+ u1 TESTuint64,
+ u2 TESTuint64
+ } OPTIONAL,
+ b2 [1] IMPLICIT SEQUENCE OF SEQUENCE {
+ u1 TESTuint64,
+ u2 TESTuint64,
+ u3 TESTuint64,
+ s1 OCTET STRING,
+ s2 OCTET STRING,
+ s3 OCTET STRING
+ } OPTIONAL,
+ b3 [2] IMPLICIT SEQUENCE OF SEQUENCE {
+ s1 OCTET STRING,
+ u1 TESTuint64,
+ s2 OCTET STRING,
+ u2 TESTuint64,
+ s3 OCTET STRING,
+ u3 TESTuint64,
+ s4 OCTET STRING,
+ u4 TESTuint64
+ } OPTIONAL
+}
+
+TESTSeqOf5 ::= SEQUENCE {
+ outer SEQUENCE {
+ inner SEQUENCE {
+ u0 TESTuint64,
+ s0 OCTET STRING,
+ u1 TESTuint64,
+ s1 OCTET STRING,
+ u2 TESTuint64,
+ s2 OCTET STRING,
+ u3 TESTuint64,
+ s3 OCTET STRING,
+ u4 TESTuint64,
+ s4 OCTET STRING,
+ u5 TESTuint64,
+ s5 OCTET STRING,
+ u6 TESTuint64,
+ s6 OCTET STRING,
+ u7 TESTuint64,
+ s7 OCTET STRING
+ }
+ }
+ OPTIONAL
+}
+
+TESTPreserve ::= SEQUENCE {
+ zero [0] TESTInteger,
+ one [1] TESTInteger
+}
+
+TESTBitString ::= BIT STRING {
+ zero(0),
+ eight(8),
+ thirtyone(31)
+}
+
+TESTBitString64 ::= BIT STRING {
+ zero(0),
+ eight(8),
+ thirtyone(31),
+ thirtytwo(32),
+ sixtythree(63)
+}
+
+TESTLargeBitString ::= BIT STRING {
+ zero(0),
+ eight(8),
+ thirtyone(31),
+ onehundredtwenty(120)
+}
+
+TESTMechType::= OBJECT IDENTIFIER
+TESTMechTypeList ::= SEQUENCE OF TESTMechType
+
+
+-- IOS stuff
+_EXTENSION ::= CLASS {
+ &id OBJECT IDENTIFIER UNIQUE,
+ &ExtnType,
+ &Critical BOOLEAN DEFAULT FALSE
+}
+
+TESTExtension{_EXTENSION:ExtensionSet} ::= SEQUENCE {
+ extnID _EXTENSION.&id({ExtensionSet}),
+ critical BOOLEAN
+-- (EXTENSION.&Critical({ExtensionSet}{@extnID}))
+ DEFAULT FALSE,
+ extnValue OCTET STRING (CONTAINING
+ _EXTENSION.&ExtnType({ExtensionSet}{@extnID}))
+}
+
+id-test-default OBJECT IDENTIFIER ::= { 1 2 3 4 }
+testext-TESTDefault _EXTENSION ::= {
+ &id id-test-default,
+ &Critical FALSE,
+ &ExtnType TESTDefault
+}
+
+-- And Here's an object set for the EXTENSION CLASS collecting a bunch of
+-- related extensions (here they are the extensions that certificates can
+-- carry in their extensions member):
+TestExtensions _EXTENSION ::= { testext-TESTDefault }
+
+TESTExtension ::= TESTExtension { TestExtensions }
+
+TESTExtensible ::= SEQUENCE {
+ version INTEGER,
+ extensions SEQUENCE OF TESTExtension
+}
+
+TESTDecorated ::= SEQUENCE {
+ version TESTuint32
+ -- gets decorated with varius fields (see test.opt)
+}
+
+TESTNotDecorated ::= SEQUENCE {
+ version TESTuint32
+ -- should have the same encoding as TESTDecorated
+}
+
+TESTDecoratedChoice ::= CHOICE {
+ version TESTuint32
+ -- gets decorated with varius fields (see test.opt)
+}
+
+TESTNotDecoratedChoice ::= CHOICE {
+ version TESTuint32
+ -- should have the same encoding as TESTDecoratedChoice
+}
+
+END
diff --git a/third_party/heimdal/lib/asn1/test.gen b/third_party/heimdal/lib/asn1/test.gen
new file mode 100644
index 0000000..bfb0486
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/test.gen
@@ -0,0 +1,14 @@
+# $Id$
+# Sample for TESTSeq in test.asn1
+#
+
+UNIV CONS Sequence 23
+ CONTEXT CONS 0 3
+ UNIV PRIM Integer 1 01
+ CONTEXT CONS 1 8
+ UNIV CONS Sequence 6
+ CONTEXT CONS 127 3
+ UNIV PRIM Integer 1 01
+ UNIV PRIM Integer 1 01
+ CONTEXT CONS 2 3
+ UNIV PRIM Integer 1 01
diff --git a/third_party/heimdal/lib/asn1/test.opt b/third_party/heimdal/lib/asn1/test.opt
new file mode 100644
index 0000000..755eba0
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/test.opt
@@ -0,0 +1,7 @@
+--sequence=TESTSeqOf
+--decorate=TESTDecorated:TESTuint32:version2?
+--decorate=TESTDecorated:my_vers:version3:my_copy_vers:my_free_vers:"check-gen.h"
+--decorate=TESTDecorated:void *:privthing
+--decorate=TESTDecoratedChoice:TESTuint32:version2?
+--decorate=TESTDecoratedChoice:my_vers:version3:my_copy_vers:my_free_vers:"check-gen.h"
+--decorate=TESTDecoratedChoice:void *:privthing
diff --git a/third_party/heimdal/lib/asn1/timegm.c b/third_party/heimdal/lib/asn1/timegm.c
new file mode 100644
index 0000000..4746fa8
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/timegm.c
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "der_locl.h"
+
+#define ASN1_MAX_YEAR 2000
+
+static int
+is_leap(unsigned y)
+{
+ y += 1900;
+ return (y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0);
+}
+
+static const unsigned ndays[2][12] ={
+ {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
+ {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
+
+/*
+ * This is a simplifed version of timegm(3) that doesn't accept out of
+ * bound values that timegm(3) normally accepts but those are not
+ * valid in asn1 encodings.
+ */
+
+time_t
+_der_timegm (struct tm *tm)
+{
+ time_t res = 0;
+ int i;
+
+ /*
+ * See comment in _der_gmtime
+ */
+ if (tm->tm_year > ASN1_MAX_YEAR)
+ return 0;
+
+ if (tm->tm_year < 0)
+ return -1;
+ if (tm->tm_mon < 0 || tm->tm_mon > 11)
+ return -1;
+ if (tm->tm_mday < 1 || tm->tm_mday > (int)ndays[is_leap(tm->tm_year)][tm->tm_mon])
+ return -1;
+ if (tm->tm_hour < 0 || tm->tm_hour > 23)
+ return -1;
+ if (tm->tm_min < 0 || tm->tm_min > 59)
+ return -1;
+ if (tm->tm_sec < 0 || tm->tm_sec > 59)
+ return -1;
+
+ for (i = 70; i < tm->tm_year; ++i)
+ res += is_leap(i) ? 366 : 365;
+
+ for (i = 0; i < tm->tm_mon; ++i)
+ res += ndays[is_leap(tm->tm_year)][i];
+ res += tm->tm_mday - 1;
+ res *= 24;
+ res += tm->tm_hour;
+ res *= 60;
+ res += tm->tm_min;
+ res *= 60;
+ res += tm->tm_sec;
+ return res;
+}
+
+struct tm *
+_der_gmtime(time_t t, struct tm *tm)
+{
+ time_t secday = t % (3600 * 24);
+ time_t days = t / (3600 * 24);
+
+ memset(tm, 0, sizeof(*tm));
+
+ tm->tm_sec = secday % 60;
+ tm->tm_min = (secday % 3600) / 60;
+ tm->tm_hour = (int)(secday / 3600);
+
+ /*
+ * Refuse to calculate time ~ 2000 years into the future, this is
+ * not possible for systems where time_t is a int32_t, however,
+ * when time_t is a int64_t, that can happen, and this becomes a
+ * denial of sevice.
+ */
+ if (days > (ASN1_MAX_YEAR * 365))
+ return NULL;
+
+ tm->tm_year = 70;
+ while(1) {
+ unsigned dayinyear = (is_leap(tm->tm_year) ? 366 : 365);
+ if (days < dayinyear)
+ break;
+ tm->tm_year += 1;
+ days -= dayinyear;
+ }
+ tm->tm_mon = 0;
+
+ while (1) {
+ unsigned daysinmonth = ndays[is_leap(tm->tm_year)][tm->tm_mon];
+ if (days < daysinmonth)
+ break;
+ days -= daysinmonth;
+ tm->tm_mon++;
+ }
+ tm->tm_mday = (int)(days + 1);
+
+ return tm;
+}
diff --git a/third_party/heimdal/lib/asn1/version-script.map b/third_party/heimdal/lib/asn1/version-script.map
new file mode 100644
index 0000000..67f9ff0
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/version-script.map
@@ -0,0 +1,6 @@
+# Export everything, but put a tag on is so that we make ourself incompatible with older versions
+
+HEIMDAL_ASN1_1.0 {
+ global:
+ *;
+};
diff --git a/third_party/heimdal/lib/asn1/x690sample.asn1 b/third_party/heimdal/lib/asn1/x690sample.asn1
new file mode 100644
index 0000000..18954a4
--- /dev/null
+++ b/third_party/heimdal/lib/asn1/x690sample.asn1
@@ -0,0 +1,181 @@
+x690sample DEFINITIONS ::= BEGIN
+
+-- This is taken from Appendix A of X.690. The same module is used by all
+-- X.690 series specifications of ASN.1 Encoding Rules.
+--
+-- This doesn't exercise every feature, like OPTIONAL, not really DEFAULT, not
+-- EXPLICIT tagging, extensibility markers, etc., but it exercises some hard
+-- ones like SET and IMPLICIT tagging.
+--
+-- Because we don't yet have an option to add a namespace prefix to generated
+-- symbols, to avoid conflicts with rfc2459's Name we're prefixing the type
+-- names here manually.
+--
+-- WARNING: The encoding rules used for the sample encoding given in Appendix A
+-- of X.690, and used in lib/asn1/check-gen.c, is not specified in
+-- X.690! It seems very likely that it is neither CER nor DER but BER
+-- because the tags in the X690SamplePersonnelRecord (a SET { ... })
+-- are not in canonical order:
+--
+-- APPL CONS tag 0 = 133 bytes [0]
+-- APPL CONS tag 1 = 16 bytes [1]
+-- UNIV PRIM VisibleString = "John"
+-- UNIV PRIM VisibleString = "P"
+-- UNIV PRIM VisibleString = "Smith"
+-- -> CONTEXT CONS tag 0 = 10 bytes [0]
+-- UNIV PRIM VisibleString = "Director"
+-- -> APPL PRIM tag 2 = 1 bytes [2] IMPLICIT content
+-- ...
+--
+-- The canonical ordering of members in SET { ... } types is by tag,
+-- with UNIVERSAL tags before APPLICATION tags, those before CONTEXT,
+-- and those before PRIVATE, and within each class from lowest to
+-- highest numeric tag value. See X.680, section 8.6, which is
+-- referenced from X.690, section 10.3.
+--
+-- Here we can see that the `title` member should come _after_ the
+-- `number` member, but it does not.
+--
+-- Our test relies on our compiler producing the same test data when
+-- encoding the structure that the given test data decodes to. That
+-- works here only because our compiler does NOT sort SET { ... }
+-- members as it should (since we always produce DER).
+--
+-- Sorting SET members in the compiler is hard currently because we
+-- don't parse imported modules, so we don't know the tags of imported
+-- types, so we can only sort at run-time, which we don't do.
+--
+-- There is an obvious workaround, however: sort the SET { ... }
+-- definition manually!
+
+X690SamplePersonnelRecord ::= [APPLICATION 0] IMPLICIT SET {
+ name X690SampleName,
+ title [0] VisibleString,
+ number X690SampleEmployeeNumber,
+ dateOfHire [1] X690SampleDate,
+ nameOfSpouse [2] X690SampleName,
+ -- Heimdal's ASN.1 compiler doesn't handle DEFAULT values for types for
+ -- which it doesn't support literal values.
+ children [3] IMPLICIT SEQUENCE OF X690SampleChildInformation -- DEFAULT {}
+}
+
+X690SampleChildInformation ::= SET {
+ name X690SampleName,
+ dateOfBirth [0] X690SampleDate
+}
+
+X690SampleName ::= [APPLICATION 1] IMPLICIT SEQUENCE {
+ givenName VisibleString,
+ initial VisibleString,
+ familyName VisibleString
+}
+
+-- Range added for test convenience.
+X690SampleEmployeeNumber ::= [APPLICATION 2] IMPLICIT INTEGER (0..4294967295)
+
+X690SampleDate::= [APPLICATION 3] IMPLICIT VisibleString --YYYYMMDD
+
+-- The following is value syntax for the above, but Heimdal's ASN.1 compiler
+-- does not yet support value syntax for anything other than OIDs, booleans,
+-- integers, and UTF-8 strings:
+--
+-- { name { givenName "John", initial "P", familyName "Smith" },
+-- title "Director",
+-- number 51,
+-- dateOfHire "19710917",
+-- nameOfSpouse {givenName "Mary", initial "T", familyName "Smith" },
+-- children {
+-- {name {givenName "Ralph", initial "T", familyName "Smith" },
+-- dateOfBirth "19571111"},
+-- {name {givenName "Susan", initial "B", familyName "Jones" },
+-- I dateOfBirth "19590717"}
+-- }
+-- }
+--
+-- The encoding of this value is supposed to be (all hex) (adapted from X.690
+-- Appendix A):
+--
+-- 60818561101A044A6F686E1A01501A05536D697468A00A1A084469726563746F
+-- 72420133A10A43083139373130393137A21261101A044D6172791A01541A0553
+-- 6D697468A342311F61111A0552616C70681A01541A05536D697468A00A430831
+-- 39353731313131311F61111A05537573616E1A01421A05536D697468A00A4308
+-- 3139353930373137
+--
+-- And a rough visualization of this is (adapted from X.690 Appendix A):
+--
+-- T L
+-- 60 8185 # 3
+-- Name
+-- T L
+-- 61 10 # 2
+-- T L "John"
+-- 1A 04 4A6F686E # 6
+-- T L "P"
+-- 1A 01 50 # 3
+-- T L "Smith"
+-- 1A 05 536D697468 # 7
+-- Title
+-- T L T L "Director"
+-- A0 0A 1A 08 4469726563746F72 #12
+-- Emp. #
+-- 42 01 33 # 3
+-- Date of hire
+-- A1 0A 43 08 3139373130393137 #12
+-- Spouse
+-- A2 12 # 2
+-- Name
+-- 61 10 # 2
+-- 1A 04 4D617279 # 6
+-- 1A 01 54 # 3
+-- 1A 05 536D697468 # 7
+-- Children
+-- A3 42 # 2
+-- 31 1F # 2
+-- Name
+-- 61 11 1A 05 52616C7068 # 9
+-- 1A 01 54 # 3
+-- 1A 05 536D697468 # 7
+-- DoB
+-- A0 0A 43 08 3139353731313131 #12
+-- 31 1F # 2 bytes
+-- 61 11 1A 05 537573616E # 9 bytes
+-- 1A 01 42 # 3 bytes
+-- 1A 05 536D697468 # 7 bytes
+-- A0 0A 43 08 3139353930373137 #12 bytes
+--
+-- Our asn1_print program dumps this as follows, which looks correct:
+--
+-- APPL CONS tag 0 = 133 bytes [0]
+-- APPL CONS tag 1 = 16 bytes [1]
+-- UNIV PRIM VisibleString = "John"
+-- UNIV PRIM VisibleString = "P"
+-- UNIV PRIM VisibleString = "Smith"
+-- CONTEXT CONS tag 0 = 10 bytes [0]
+-- UNIV PRIM VisibleString = "Director"
+-- APPL PRIM tag 2 = 1 bytes [2] IMPLICIT content
+-- CONTEXT CONS tag 1 = 10 bytes [1]
+-- APPL PRIM tag 3 = 8 bytes [3] IMPLICIT content
+-- CONTEXT CONS tag 2 = 18 bytes [2]
+-- APPL CONS tag 1 = 16 bytes [1]
+-- UNIV PRIM VisibleString = "Mary"
+-- UNIV PRIM VisibleString = "T"
+-- UNIV PRIM VisibleString = "Smith"
+-- CONTEXT CONS tag 3 = 66 bytes [3]
+-- UNIV CONS Set = 31 bytes {
+-- APPL CONS tag 1 = 17 bytes [1]
+-- UNIV PRIM VisibleString = "Ralph"
+-- UNIV PRIM VisibleString = "T"
+-- UNIV PRIM VisibleString = "Smith"
+-- CONTEXT CONS tag 0 = 10 bytes [0]
+-- APPL PRIM tag 3 = 8 bytes [3] IMPLICIT content
+-- }
+-- UNIV CONS Set = 31 bytes {
+-- APPL CONS tag 1 = 17 bytes [1]
+-- UNIV PRIM VisibleString = "Susan"
+-- UNIV PRIM VisibleString = "B"
+-- UNIV PRIM VisibleString = "Smith"
+-- CONTEXT CONS tag 0 = 10 bytes [0]
+-- APPL PRIM tag 3 = 8 bytes [3] IMPLICIT content
+-- }
+
+END
diff --git a/third_party/heimdal/lib/base/Makefile.am b/third_party/heimdal/lib/base/Makefile.am
new file mode 100644
index 0000000..18300b3
--- /dev/null
+++ b/third_party/heimdal/lib/base/Makefile.am
@@ -0,0 +1,95 @@
+
+include $(top_srcdir)/Makefile.am.common
+
+if do_roken_rename
+ES = base64.c
+endif
+
+IMPLEMENT_TLS=
+if MAINTAINER_MODE
+IMPLEMENT_TLS += dll.c
+AM_CPPFLAGS += -DHEIM_BASE_MAINTAINER
+endif
+
+AM_CPPFLAGS += $(ROKEN_RENAME) -I../com_err -I$(srcdir)/../com_err
+
+lib_LTLIBRARIES = libheimbase.la
+check_PROGRAMS = test_base
+
+libheimbase_la_LDFLAGS = -version-info 1:0:0
+
+if FRAMEWORK_COREFOUNDATION
+libheimbase_la_LDFLAGS += -framework CoreFoundation
+endif
+
+TESTS = test_base
+
+if versionscript
+libheimbase_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+endif
+
+libheimbase_la_LIBADD = $(PTHREAD_LIBADD) $(LIB_dlopen) $(LIB_com_err)
+
+include_HEADERS = heimbase.h common_plugin.h heimbase-atomics.h heimbase-svc.h
+
+ERR_FILES = heim_err.c
+
+dist_libheimbase_la_SOURCES = \
+ array.c \
+ baselocl.h \
+ bsearch.c \
+ bool.c \
+ common_plugin.h \
+ config_file.c \
+ context.c \
+ data.c \
+ db.c \
+ dict.c \
+ $(IMPLEMENT_TLS) \
+ error.c \
+ error_string.c \
+ expand_path.c \
+ heimbase.c \
+ heimbasepriv.h \
+ json.c \
+ log.c \
+ null.c \
+ number.c \
+ plugin.c \
+ roken_rename.h \
+ string.c \
+ warn.c
+
+nodist_libheimbase_la_SOURCES = $(ES) $(ERR_FILES)
+
+$(libheimbase_la_OBJECTS): $(srcdir)/heimbase-protos.h heim_err.h
+
+$(srcdir)/heimbase-protos.h: $(dist_libheimbase_la_SOURCES)
+ cd $(srcdir) && \
+ perl ../../cf/make-proto.pl -q -P comment -o heimbase-protos.h $(dist_libheimbase_la_SOURCES) || \
+ rm -f heimbase-protos.h
+
+$(srcdir)/heimbase-private.h: $(dist_libheimbase_la_SOURCES)
+ cd $(srcdir) && \
+ perl ../../cf/make-proto.pl -q -P comment -p heimbase-private.h $(dist_libheimbase_la_SOURCES) || \
+ rm -f heimbase-private.h
+
+# install these?
+
+libheimbase_la_DEPENDENCIES = version-script.map
+
+test_base_LDADD = libheimbase.la $(LIB_roken)
+
+CLEANFILES = base64.c test_db.json heim_err.c heim_err.h
+
+EXTRA_DIST = NTMakefile version-script.map config_reg.c heim_err.et
+
+dist_include_HEADERS = heimbase-protos.h
+
+nodist_include_HEADERS = heim_err.h
+
+heim_err.h: heim_err.et
+
+base64.c:
+ rm -f base64.c
+ $(LN_S) $(srcdir)/../roken/base64.c .
diff --git a/third_party/heimdal/lib/base/NTMakefile b/third_party/heimdal/lib/base/NTMakefile
new file mode 100644
index 0000000..49cd8b8
--- /dev/null
+++ b/third_party/heimdal/lib/base/NTMakefile
@@ -0,0 +1,134 @@
+########################################################################
+#
+# Copyright (c) 2010, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\base
+
+intcflags=-I$(SRCDIR) -I$(OBJ)
+
+!include ../../windows/NTMakefile.w32
+
+INCFILES= \
+ $(INCDIR)\heimbase.h \
+ $(INCDIR)\heimbase-protos.h \
+ $(INCDIR)\heimbase-atomics.h \
+ $(INCDIR)\heimbase-svc.h \
+ $(INCDIR)\heim_err.h \
+ $(INCDIR)\common_plugin.h
+
+test_binaries = $(OBJ)\test_base.exe
+
+libheimbase_SOURCES = \
+ array.c \
+ bool.c \
+ bsearch.c \
+ config_file.c \
+ config_reg.c \
+ context.c \
+ data.c \
+ db.c \
+ dict.c \
+ dll.c \
+ error.c \
+ error_string.c \
+ expand_path.c \
+ heimbase.c \
+ json.c \
+ log.c \
+ null.c \
+ number.c \
+ plugin.c \
+ string.c \
+ warn.c
+
+libheimbase_OBJS = \
+ $(OBJ)\array.obj \
+ $(OBJ)\bool.obj \
+ $(OBJ)\bsearch.obj \
+ $(OBJ)\config_file.obj \
+ $(OBJ)\config_reg.obj \
+ $(OBJ)\context.obj \
+ $(OBJ)\data.obj \
+ $(OBJ)\db.obj \
+ $(OBJ)\dict.obj \
+ $(OBJ)\dll.obj \
+ $(OBJ)\error.obj \
+ $(OBJ)\error_string.obj \
+ $(OBJ)\expand_path.obj \
+ $(OBJ)\heimbase.obj \
+ $(OBJ)\json.obj \
+ $(OBJ)\log.obj \
+ $(OBJ)\null.obj \
+ $(OBJ)\number.obj \
+ $(OBJ)\plugin.obj \
+ $(OBJ)\string.obj \
+ $(OBJ)\warn.obj
+
+libheimbase_gen_OBJS= $(OBJ)\heim_err.obj
+
+$(LIBHEIMBASE): $(libheimbase_OBJS) $(libheimbase_gen_OBJS)
+ $(LIBCON_C) -OUT:$@ $(LIBROKEN) $(LIBCOMERR) $(PTHREAD_LIB) Secur32.lib Shell32.lib Advapi32.lib Shlwapi.lib @<<
+$(libheimbase_OBJS: =
+)
+$(libheimbase_gen_OBJS: =
+)
+<<
+
+$(OBJ)\heimbase-protos.h: $(libheimbase_SOURCES)
+ $(PERL) ..\..\cf\make-proto.pl -E KRB5_LIB -q -P remove -o $(OBJ)\heimbase-protos.h $(libheimbase_SOURCES) || $(RM) -f $(OBJ)\heimbase-protos.h
+
+$(OBJ)\heimbase-private.h: $(libheimbase_SOURCES)
+ $(PERL) ..\..\cf\make-proto.pl -q -P remove -p $(OBJ)\heimbase-private.h $(libheimbase_SOURCES) || $(RM) -f $(OBJ)\heimbase-private.h
+
+$(OBJ)\heim_err.c $(OBJ)\heim_err.h: heim_err.et
+ cd $(OBJ)
+ $(BINDIR)\compile_et.exe $(SRCDIR)\heim_err.et
+ cd $(SRCDIR)
+
+test:: test-binaries test-run
+
+test-run:
+ cd $(OBJ)
+ -test_base.exe
+ cd $(SRCDIR)
+
+all:: $(INCFILES) $(LIBHEIMBASE)
+
+clean::
+ -$(RM) $(INCFILES)
+
+test-binaries: $(test_binaries)
+
+$(test_binaries): $$(@R).obj $(LIBHEIMBASE) $(LIBVERS) $(LIBROKEN)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(test_binaries:.exe=.obj): $$(@B).c
+ $(C2OBJ_C) -Fo$@ -Fd$(@D)\ $** -DBlah
diff --git a/third_party/heimdal/lib/base/array.c b/third_party/heimdal/lib/base/array.c
new file mode 100644
index 0000000..994fa7d
--- /dev/null
+++ b/third_party/heimdal/lib/base/array.c
@@ -0,0 +1,478 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+
+/*
+ *
+ */
+
+struct heim_array_data {
+ size_t len;
+ heim_object_t *val;
+ size_t allocated_len;
+ heim_object_t *allocated;
+};
+
+static void HEIM_CALLCONV
+array_dealloc(heim_object_t ptr)
+{
+ heim_array_t array = ptr;
+ size_t n;
+ for (n = 0; n < array->len; n++)
+ heim_release(array->val[n]);
+ free(array->allocated);
+}
+
+struct heim_type_data array_object = {
+ HEIM_TID_ARRAY,
+ "array-object",
+ NULL,
+ array_dealloc,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+/**
+ * Allocate an array
+ *
+ * @return A new allocated array, free with heim_release()
+ */
+
+heim_array_t
+heim_array_create(void)
+{
+ heim_array_t array;
+
+ array = _heim_alloc_object(&array_object, sizeof(*array));
+ if (array == NULL)
+ return NULL;
+
+ array->allocated = NULL;
+ array->allocated_len = 0;
+ array->val = NULL;
+ array->len = 0;
+
+ return array;
+}
+
+/**
+ * Get type id of an dict
+ *
+ * @return the type id
+ */
+
+heim_tid_t
+heim_array_get_type_id(void)
+{
+ return HEIM_TID_ARRAY;
+}
+
+/**
+ * Append object to array
+ *
+ * @param array array to add too
+ * @param object the object to add
+ *
+ * @return zero if added, errno otherwise
+ */
+
+int
+heim_array_append_value(heim_array_t array, heim_object_t object)
+{
+ heim_object_t *ptr;
+ size_t leading = array->val - array->allocated; /* unused leading slots */
+ size_t trailing = array->allocated_len - array->len - leading;
+ size_t new_len;
+
+ if (trailing > 0) {
+ /* We have pre-allocated space; use it */
+ array->val[array->len++] = heim_retain(object);
+ return 0;
+ }
+
+ if (leading > (array->len + 1)) {
+ /*
+ * We must have appending to, and deleting at index 0 from this
+ * array a lot; don't want to grow forever!
+ */
+ (void) memmove(&array->allocated[0], &array->val[0],
+ array->len * sizeof(array->val[0]));
+ array->val = array->allocated;
+
+ /* We have pre-allocated space; use it */
+ array->val[array->len++] = heim_retain(object);
+ return 0;
+ }
+
+ /* Pre-allocate extra .5 times number of used slots */
+ new_len = leading + array->len + 1 + (array->len >> 1);
+ ptr = realloc(array->allocated, new_len * sizeof(array->val[0]));
+ if (ptr == NULL)
+ return ENOMEM;
+ array->allocated = ptr;
+ array->allocated_len = new_len;
+ array->val = &ptr[leading];
+ array->val[array->len++] = heim_retain(object);
+
+ return 0;
+}
+
+/*
+ * Internal function to insert at index 0, taking care to optimize the
+ * case where we're always inserting at index 0, particularly the case
+ * where we insert at index 0 and delete from the right end.
+ */
+static int
+heim_array_prepend_value(heim_array_t array, heim_object_t object)
+{
+ heim_object_t *ptr;
+ size_t leading = array->val - array->allocated; /* unused leading slots */
+ size_t trailing = array->allocated_len - array->len - leading;
+ size_t new_len;
+
+ if (leading > 0) {
+ /* We have pre-allocated space; use it */
+ array->val--;
+ array->val[0] = heim_retain(object);
+ array->len++;
+ return 0;
+ }
+ if (trailing > (array->len + 1)) {
+ /*
+ * We must have prepending to, and deleting at index
+ * array->len - 1 from this array a lot; don't want to grow
+ * forever!
+ */
+ (void) memmove(&array->allocated[array->len], &array->val[0],
+ array->len * sizeof(array->val[0]));
+ array->val = &array->allocated[array->len];
+
+ /* We have pre-allocated space; use it */
+ array->val--;
+ array->val[0] = heim_retain(object);
+ array->len++;
+ return 0;
+ }
+ /* Pre-allocate extra .5 times number of used slots */
+ new_len = array->len + 1 + trailing + (array->len >> 1);
+ ptr = realloc(array->allocated, new_len * sizeof(array->val[0]));
+ if (ptr == NULL)
+ return ENOMEM;
+ (void) memmove(&ptr[1], &ptr[0], array->len * sizeof (array->val[0]));
+ array->allocated = ptr;
+ array->allocated_len = new_len;
+ array->val = &ptr[0];
+ array->val[0] = heim_retain(object);
+ array->len++;
+
+ return 0;
+}
+
+/**
+ * Insert an object at a given index in an array
+ *
+ * @param array array to add too
+ * @param idx index where to add element (-1 == append, -2 next to last, ...)
+ * @param object the object to add
+ *
+ * @return zero if added, errno otherwise
+ */
+
+int
+heim_array_insert_value(heim_array_t array, size_t idx, heim_object_t object)
+{
+ int ret;
+
+ if (idx == 0)
+ return heim_array_prepend_value(array, object);
+ else if (idx > array->len)
+ heim_abort("index too large");
+
+ /*
+ * We cheat: append this element then rotate elements around so we
+ * have this new element at the desired location, unless we're truly
+ * appending the new element. This means reusing array growth in
+ * heim_array_append_value() instead of duplicating that here.
+ */
+ ret = heim_array_append_value(array, object);
+ if (ret != 0 || idx == (array->len - 1))
+ return ret;
+ /*
+ * Shift to the right by one all the elements after idx, then set
+ * [idx] to the new object.
+ */
+ (void) memmove(&array->val[idx + 1], &array->val[idx],
+ (array->len - idx - 1) * sizeof(array->val[0]));
+ array->val[idx] = heim_retain(object);
+
+ return 0;
+}
+
+/**
+ * Iterate over all objects in array
+ *
+ * @param array array to iterate over
+ * @param ctx context passed to fn
+ * @param fn function to call on each object
+ */
+
+void
+heim_array_iterate_f(heim_array_t array, void *ctx, heim_array_iterator_f_t fn)
+{
+ size_t n;
+ int stop = 0;
+ for (n = 0; n < array->len; n++) {
+ fn(array->val[n], ctx, &stop);
+ if (stop)
+ return;
+ }
+}
+
+#ifdef __BLOCKS__
+/**
+ * Iterate over all objects in array
+ *
+ * @param array array to iterate over
+ * @param fn block to call on each object
+ */
+
+void
+heim_array_iterate(heim_array_t array, void (^fn)(heim_object_t, int *))
+{
+ size_t n;
+ int stop = 0;
+ for (n = 0; n < array->len; n++) {
+ fn(array->val[n], &stop);
+ if (stop)
+ return;
+ }
+}
+#endif
+
+/**
+ * Iterate over all objects in array, backwards
+ *
+ * @param array array to iterate over
+ * @param ctx context passed to fn
+ * @param fn function to call on each object
+ */
+
+void
+heim_array_iterate_reverse_f(heim_array_t array, void *ctx, heim_array_iterator_f_t fn)
+{
+ size_t n;
+ int stop = 0;
+
+ for (n = array->len; n > 0; n--) {
+ fn(array->val[n - 1], ctx, &stop);
+ if (stop)
+ return;
+ }
+}
+
+#ifdef __BLOCKS__
+/**
+ * Iterate over all objects in array, backwards
+ *
+ * @param array array to iterate over
+ * @param fn block to call on each object
+ */
+
+void
+heim_array_iterate_reverse(heim_array_t array, void (^fn)(heim_object_t, int *))
+{
+ size_t n;
+ int stop = 0;
+ for (n = array->len; n > 0; n--) {
+ fn(array->val[n - 1], &stop);
+ if (stop)
+ return;
+ }
+}
+#endif
+
+/**
+ * Get length of array
+ *
+ * @param array array to get length of
+ *
+ * @return length of array
+ */
+
+size_t
+heim_array_get_length(heim_array_t array)
+{
+ return array->len;
+}
+
+/**
+ * Get value of element at array index
+ *
+ * @param array array copy object from
+ * @param idx index of object, 0 based, must be smaller then
+ * heim_array_get_length()
+ *
+ * @return a not-retained copy of the object
+ */
+
+heim_object_t
+heim_array_get_value(heim_array_t array, size_t idx)
+{
+ if (idx >= array->len)
+ heim_abort("index too large");
+ return array->val[idx];
+}
+
+/**
+ * Get value of element at array index
+ *
+ * @param array array copy object from
+ * @param idx index of object, 0 based, must be smaller then
+ * heim_array_get_length()
+ *
+ * @return a retained copy of the object
+ */
+
+heim_object_t
+heim_array_copy_value(heim_array_t array, size_t idx)
+{
+ if (idx >= array->len)
+ heim_abort("index too large");
+ return heim_retain(array->val[idx]);
+}
+
+/**
+ * Set value at array index
+ *
+ * @param array array copy object from
+ * @param idx index of object, 0 based, must be smaller then
+ * heim_array_get_length()
+ * @param value value to set
+ *
+ */
+
+void
+heim_array_set_value(heim_array_t array, size_t idx, heim_object_t value)
+{
+ if (idx >= array->len)
+ heim_abort("index too large");
+ heim_release(array->val[idx]);
+ array->val[idx] = heim_retain(value);
+}
+
+/**
+ * Delete value at idx
+ *
+ * @param array the array to modify
+ * @param idx the key to delete
+ */
+
+void
+heim_array_delete_value(heim_array_t array, size_t idx)
+{
+ heim_object_t obj;
+ if (idx >= array->len)
+ heim_abort("index too large");
+ obj = array->val[idx];
+
+ array->len--;
+
+ /*
+ * Deleting the first or last elements is cheap, as we leave
+ * allocated space for opportunistic reuse later; no realloc(), no
+ * memmove(). All others require a memmove().
+ *
+ * If we ever need to optimize deletion of non-last/ non-first
+ * element we can use a tagged object type to signify "deleted
+ * value" so we can leave holes in the array, avoid memmove()s on
+ * delete, and opportunistically re-use those holes on insert.
+ */
+ if (idx == 0)
+ array->val++;
+ else if (idx < array->len)
+ (void) memmove(&array->val[idx], &array->val[idx + 1],
+ (array->len - idx) * sizeof(array->val[0]));
+
+ heim_release(obj);
+}
+
+/**
+ * Filter out entres of array when function return true
+ *
+ * @param array the array to modify
+ * @param fn filter function
+ */
+
+void
+heim_array_filter_f(heim_array_t array, void *ctx, heim_array_filter_f_t fn)
+{
+ size_t n = 0;
+
+ while (n < array->len) {
+ if (fn(array->val[n], ctx)) {
+ heim_array_delete_value(array, n);
+ } else {
+ n++;
+ }
+ }
+}
+
+#ifdef __BLOCKS__
+
+/**
+ * Filter out entres of array when block return true
+ *
+ * @param array the array to modify
+ * @param block filter block
+ */
+
+void
+heim_array_filter(heim_array_t array, int (^block)(heim_object_t))
+{
+ size_t n = 0;
+
+ while (n < array->len) {
+ if (block(array->val[n])) {
+ heim_array_delete_value(array, n);
+ } else {
+ n++;
+ }
+ }
+}
+
+#endif /* __BLOCKS__ */
diff --git a/third_party/heimdal/lib/base/baselocl.h b/third_party/heimdal/lib/base/baselocl.h
new file mode 100644
index 0000000..7ca6439
--- /dev/null
+++ b/third_party/heimdal/lib/base/baselocl.h
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2010 - 2011 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include <roken.h>
+
+#define ISTILDE(x) (x == '~')
+#ifdef _WIN32
+# define ISPATHSEP(x) (x == '/' || x =='\\')
+#else
+# define ISPATHSEP(x) (x == '/')
+#endif
+
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif
+
+#define HEIMDAL_TEXTDOMAIN "heimdal_krb5"
+
+#ifdef LIBINTL
+#include <libintl.h>
+#define N_(x,y) dgettext(HEIMDAL_TEXTDOMAIN, x)
+#else
+#define N_(x,y) (x)
+#define bindtextdomain(package, localedir)
+#endif
+
+#include "heimqueue.h"
+#include "heim_threads.h"
+#include "heimbase.h"
+#include "heimbasepriv.h"
+
+#ifdef HAVE_DISPATCH_DISPATCH_H
+#include <dispatch/dispatch.h>
+#endif
+
+/* tagged strings/object/XXX */
+#define heim_base_is_tagged(x) (((uintptr_t)(x)) & 0x3)
+
+#define heim_base_is_tagged_object(x) ((((uintptr_t)(x)) & 0x3) == 1)
+#define heim_base_make_tagged_object(x, tid) \
+ ((heim_object_t)((((uintptr_t)(x)) << 5) | ((tid) << 2) | 0x1))
+#define heim_base_tagged_object_tid(x) ((((uintptr_t)(x)) & 0x1f) >> 2)
+#define heim_base_tagged_object_value(x) (((uintptr_t)(x)) >> 5)
+
+/*
+ *
+ */
+
+#undef HEIMDAL_NORETURN_ATTRIBUTE
+#define HEIMDAL_NORETURN_ATTRIBUTE
+#undef HEIMDAL_PRINTF_ATTRIBUTE
+#define HEIMDAL_PRINTF_ATTRIBUTE(x)
+
+struct heim_context_s {
+ heim_log_facility *log_dest;
+ heim_log_facility *warn_dest;
+ heim_log_facility *debug_dest;
+ char *time_fmt;
+ unsigned int log_utc:1;
+ unsigned int homedir_access:1;
+ struct et_list *et_list;
+ char *error_string;
+ heim_error_code error_code;
+};
diff --git a/third_party/heimdal/lib/base/bool.c b/third_party/heimdal/lib/base/bool.c
new file mode 100644
index 0000000..f7b66ee
--- /dev/null
+++ b/third_party/heimdal/lib/base/bool.c
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+
+struct heim_type_data _heim_bool_object = {
+ HEIM_TID_BOOL,
+ "bool-object",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+heim_bool_t
+heim_bool_create(int val)
+{
+ return heim_base_make_tagged_object(!!val, HEIM_TID_BOOL);
+}
+
+int
+heim_bool_val(heim_bool_t ptr)
+{
+ return heim_base_tagged_object_value(ptr);
+}
diff --git a/third_party/heimdal/lib/base/bsearch.c b/third_party/heimdal/lib/base/bsearch.c
new file mode 100644
index 0000000..268cc01
--- /dev/null
+++ b/third_party/heimdal/lib/base/bsearch.c
@@ -0,0 +1,888 @@
+/*
+ * Copyright (c) 2011, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "baselocl.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef HAVE_IO_H
+#include <io.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <fcntl.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef HAVE_STRINGS_H
+#include <strings.h>
+#endif
+#include <errno.h>
+#include <assert.h>
+
+/*
+ * This file contains functions for binary searching flat text in memory
+ * and in text files where each line is a [variable length] record.
+ * Each record has a key and an optional value separated from the key by
+ * unquoted whitespace. Whitespace in the key, and leading whitespace
+ * for the value, can be quoted with backslashes (but CR and LF must be
+ * quoted in such a way that they don't appear in the quoted result).
+ *
+ * Binary searching a tree are normally a dead simple algorithm. It
+ * turns out that binary searching flat text with *variable* length
+ * records is... tricky. There's no indexes to record beginning bytes,
+ * thus any index selected during the search is likely to fall in the
+ * middle of a record. When deciding to search a left sub-tree one
+ * might fail to find the last record in that sub-tree on account of the
+ * right boundary falling in the middle of it -- the chosen solution to
+ * this makes left sub-tree searches slightly less efficient than right
+ * sub-tree searches.
+ *
+ * If binary searching flat text in memory is tricky, using block-wise
+ * I/O instead is trickier! But it's necessary in order to support
+ * large files (which we either can't or wouldn't want to read or map
+ * into memory). Each block we read has to be large enough that the
+ * largest record can fit in it. And each block might start and/or end
+ * in the middle of a record. Here it is the right sub-tree searches
+ * that are less efficient than left sub-tree searches.
+ *
+ * bsearch_common() contains the common text block binary search code.
+ *
+ * _bsearch_text() is the interface for searching in-core text.
+ * _bsearch_file() is the interface for block-wise searching files.
+ */
+
+struct bsearch_file_handle {
+ int fd; /* file descriptor */
+ char *cache; /* cache bytes */
+ char *page; /* one double-size page worth of bytes */
+ size_t file_sz; /* file size */
+ size_t cache_sz; /* cache size */
+ size_t page_sz; /* page size */
+};
+
+/* Find a new-line */
+static const char *
+find_line(const char *buf, size_t i, size_t right)
+{
+ if (i == 0)
+ return &buf[i];
+ for (; i < right; i++) {
+ if (buf[i] == '\n') {
+ if ((i + 1) < right)
+ return &buf[i + 1];
+ return NULL;
+ }
+ }
+ return NULL;
+}
+
+/*
+ * Common routine for binary searching text in core.
+ *
+ * Perform a binary search of a char array containing a block from a
+ * text file where each line is a record (LF and CRLF supported). Each
+ * record consists of a key followed by an optional value separated from
+ * the key by whitespace. Whitespace can be quoted with backslashes.
+ * It's the caller's responsibility to encode/decode keys/values if
+ * quoting is desired; newlines should be encoded such that a newline
+ * does not appear in the result.
+ *
+ * All output arguments are optional.
+ *
+ * Returns 0 if key is found, -1 if not found, or an error code such as
+ * ENOMEM in case of error.
+ *
+ * Inputs:
+ *
+ * @buf String to search
+ * @sz Size of string to search
+ * @key Key string to search for
+ * @buf_is_start True if the buffer starts with a record, false if it
+ * starts in the middle of a record or if the caller
+ * doesn't know.
+ *
+ * Outputs:
+ *
+ * @value Location to store a copy of the value (caller must free)
+ * @location Record location if found else the location where the
+ * record should be inserted (index into @buf)
+ * @cmp Set to less than or greater than 0 to indicate that a
+ * key not found would have fit in an earlier or later
+ * part of a file. Callers should use this to decide
+ * whether to read a block to the left or to the right and
+ * search that.
+ * @loops Location to store a count of bisections required for
+ * search (useful for confirming logarithmic performance)
+ */
+static int
+bsearch_common(const char *buf, size_t sz, const char *key,
+ int buf_is_start, char **value, size_t *location,
+ int *cmp, size_t *loops)
+{
+ const char *linep;
+ size_t key_start, key_len; /* key string in buf */
+ size_t val_start, val_len; /* value string in buf */
+ int key_cmp = -1;
+ size_t k;
+ size_t l; /* left side of buffer for binary search */
+ size_t r; /* right side of buffer for binary search */
+ size_t rmax; /* right side of buffer for binary search */
+ size_t i; /* index into buffer, typically in the middle of l and r */
+ size_t loop_count = 0;
+ int ret = -1;
+
+ if (value)
+ *value = NULL;
+ if (cmp)
+ *cmp = 0;
+ if (loops)
+ *loops = 0;
+
+ /* Binary search; file should be sorted */
+ for (l = 0, r = rmax = sz, i = sz >> 1; i >= l && i < rmax; loop_count++) {
+ heim_assert(i < sz, "invalid aname2lname db index");
+
+ /* buf[i] is likely in the middle of a line; find the next line */
+ linep = find_line(buf, i, rmax);
+ k = linep ? linep - buf : i;
+ if (linep == NULL || k >= rmax) {
+ /*
+ * No new line found to the right; search to the left then
+ * but don't change rmax (this isn't optimal, but it's
+ * simple).
+ */
+ if (i == l)
+ break;
+ r = i;
+ i = l + ((r - l) >> 1);
+ continue;
+ }
+ i = k;
+ heim_assert(i >= l && i < rmax, "invalid aname2lname db index");
+
+ /* Got a line; check it */
+
+ /* Search for and split on unquoted whitespace */
+ val_start = 0;
+ for (key_start = i, key_len = 0, val_len = 0, k = i; k < rmax; k++) {
+ if (buf[k] == '\\') {
+ k++;
+ continue;
+ }
+ if (buf[k] == '\r' || buf[k] == '\n') {
+ /* We now know where the key ends, and there's no value */
+ key_len = k - i;
+ break;
+ }
+ if (!isspace((unsigned char)buf[k]))
+ continue;
+
+ while (k < rmax && isspace((unsigned char)buf[k])) {
+ key_len = k - i;
+ k++;
+ }
+ if (k < rmax)
+ val_start = k;
+ /* Find end of value */
+ for (; k < rmax && buf[k] != '\0'; k++) {
+ if (buf[k] == '\r' || buf[k] == '\n') {
+ val_len = k - val_start;
+ break;
+ }
+ }
+ break;
+ }
+
+ /*
+ * The following logic is for dealing with partial buffers,
+ * which we use for block-wise binary searches of large files
+ */
+ if (key_start == 0 && !buf_is_start) {
+ /*
+ * We're at the beginning of a block that might have started
+ * in the middle of a record whose "key" might well compare
+ * as greater than the key we're looking for, so we don't
+ * bother comparing -- we know key_cmp must be -1 here.
+ */
+ key_cmp = -1;
+ break;
+ }
+ if ((val_len && buf[val_start + val_len] != '\n') ||
+ (!val_len && buf[key_start + key_len] != '\n')) {
+ /*
+ * We're at the end of a block that ends in the middle of a
+ * record whose "key" might well compare as less than the
+ * key we're looking for, so we don't bother comparing -- we
+ * know key_cmp must be >= 0 but we can't tell. Our caller
+ * will end up reading a double-size block to handle this.
+ */
+ key_cmp = 1;
+ break;
+ }
+
+ key_cmp = strncmp(key, &buf[key_start], key_len);
+ if (key_cmp == 0 && strlen(key) != key_len)
+ key_cmp = 1;
+ if (key_cmp < 0) {
+ /* search left */
+ r = rmax = (linep - buf);
+ i = l + ((r - l) >> 1);
+ if (location)
+ *location = key_start;
+ } else if (key_cmp > 0) {
+ /* search right */
+ if (l == i)
+ break; /* not found */
+ l = i;
+ i = l + ((r - l) >> 1);
+ if (location)
+ *location = val_start + val_len;
+ } else {
+ /* match! */
+ if (location)
+ *location = key_start;
+ ret = 0;
+ if (val_len && value) {
+ /* Avoid strndup() so we don't need libroken here yet */
+ if ((*value = malloc(val_len + 1))) {
+ (void) memcpy(*value, &buf[val_start], val_len);
+ (*value)[val_len] = '\0';
+ } else {
+ ret = errno;
+ }
+ }
+ break;
+ }
+ }
+
+ if (cmp)
+ *cmp = key_cmp;
+ if (loops)
+ *loops = loop_count;
+
+ return ret;
+}
+
+/*
+ * Binary search a char array containing sorted text records separated
+ * by new-lines (or CRLF). Each record consists of a key and an
+ * optional value following the key, separated from the key by unquoted
+ * whitespace.
+ *
+ * All output arguments are optional.
+ *
+ * Returns 0 if key is found, -1 if not found, or an error code such as
+ * ENOMEM in case of error.
+ *
+ * Inputs:
+ *
+ * @buf Char array pointer
+ * @buf_sz Size of buf
+ * @key Key to search for
+ *
+ * Outputs:
+ *
+ * @value Location where to put the value, if any (caller must free)
+ * @location Record location if found else the location where the record
+ * should be inserted (index into @buf)
+ * @loops Location where to put a number of loops (or comparisons)
+ * needed for the search (useful for benchmarking)
+ */
+int
+_bsearch_text(const char *buf, size_t buf_sz, const char *key,
+ char **value, size_t *location, size_t *loops)
+{
+ return bsearch_common(buf, buf_sz, key, 1, value, location, NULL, loops);
+}
+
+#define MAX_BLOCK_SIZE (1024 * 1024)
+#define DEFAULT_MAX_FILE_SIZE (1024 * 1024)
+/*
+ * Open a file for binary searching. The file will be read in entirely
+ * if it is smaller than @max_sz, else a cache of @max_sz bytes will be
+ * allocated.
+ *
+ * Returns 0 on success, else an error number or -1 if the file is empty.
+ *
+ * Inputs:
+ *
+ * @fname Name of file to open
+ * @max_sz Maximum size of cache to allocate, in bytes (if zero, default)
+ * @page_sz Page size (must be a power of two, larger than 256, smaller
+ * than 1MB; if zero use default)
+ *
+ * Outputs:
+ *
+ * @bfh Handle for use with _bsearch_file() and _bsearch_file_close()
+ * @reads Number of reads performed
+ */
+int
+_bsearch_file_open(const char *fname, size_t max_sz, size_t page_sz,
+ bsearch_file_handle *bfh, size_t *reads)
+{
+ bsearch_file_handle new_bfh = NULL;
+ struct stat st;
+ size_t i;
+ int fd;
+ int ret;
+
+ *bfh = NULL;
+
+ if (reads)
+ *reads = 0;
+
+ fd = open(fname, O_RDONLY);
+ if (fd == -1)
+ return errno;
+
+ if (fstat(fd, &st) == -1) {
+ ret = errno;
+ goto err;
+ }
+
+ if (st.st_size == 0) {
+ ret = -1; /* no data -> no binary search */
+ goto err;
+ }
+
+ /* Validate / default arguments */
+ if (max_sz == 0)
+ max_sz = DEFAULT_MAX_FILE_SIZE;
+ for (i = page_sz; i; i >>= 1) {
+ /* Make sure page_sz is a power of two */
+ if ((i % 2) && (i >> 1)) {
+ page_sz = 0;
+ break;
+ }
+ }
+ if (page_sz == 0)
+#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
+ page_sz = st.st_blksize;
+#else
+ page_sz = 4096;
+#endif
+ for (i = page_sz; i; i >>= 1) {
+ /* Make sure page_sz is a power of two */
+ if ((i % 2) && (i >> 1)) {
+ /* Can't happen! Filesystems always use powers of two! */
+ page_sz = 4096;
+ break;
+ }
+ }
+ if (page_sz > MAX_BLOCK_SIZE)
+ page_sz = MAX_BLOCK_SIZE;
+
+ new_bfh = calloc(1, sizeof (*new_bfh));
+ if (new_bfh == NULL) {
+ ret = ENOMEM;
+ goto err;
+ }
+
+ new_bfh->fd = fd;
+ new_bfh->page_sz = page_sz;
+ new_bfh->file_sz = st.st_size;
+
+ if (max_sz >= st.st_size) {
+ /* Whole-file method */
+ new_bfh->cache = malloc(st.st_size + 1);
+ if (new_bfh->cache) {
+ new_bfh->cache[st.st_size] = '\0';
+ new_bfh->cache_sz = st.st_size;
+ ret = read(fd, new_bfh->cache, st.st_size);
+ if (ret < 0) {
+ ret = errno;
+ goto err;
+ }
+ if (ret != st.st_size) {
+ ret = EIO; /* XXX ??? */
+ goto err;
+ }
+ if (reads)
+ *reads = 1;
+ (void) close(fd);
+ new_bfh->fd = -1;
+ *bfh = new_bfh;
+ return 0;
+ }
+ }
+
+ /* Block-size method, or above malloc() failed */
+ new_bfh->page = malloc(new_bfh->page_sz << 1);
+ if (new_bfh->page == NULL) {
+ /* Can't even allocate a single double-size page! */
+ ret = ENOMEM;
+ goto err;
+ }
+
+ new_bfh->cache_sz = max_sz < st.st_size ? max_sz : st.st_size;
+ new_bfh->cache = malloc(new_bfh->cache_sz);
+ *bfh = new_bfh;
+
+ /*
+ * malloc() may have failed because we were asking for a lot of
+ * memory, but we may still be able to operate without a cache,
+ * so let's not fail.
+ */
+ if (new_bfh->cache == NULL) {
+ new_bfh->cache_sz = 0;
+ return 0;
+ }
+
+ /* Initialize cache */
+ for (i = 0; i < new_bfh->cache_sz; i += new_bfh->page_sz)
+ new_bfh->cache[i] = '\0';
+ return 0;
+
+err:
+ (void) close(fd);
+ if (new_bfh) {
+ free(new_bfh->page);
+ free(new_bfh->cache);
+ free(new_bfh);
+ }
+ return ret;
+}
+
+/*
+ * Indicate whether the given binary search file handle will be searched
+ * with block-wise method.
+ */
+void
+_bsearch_file_info(bsearch_file_handle bfh,
+ size_t *page_sz, size_t *max_sz, int *blockwise)
+{
+ if (page_sz)
+ *page_sz = bfh->page_sz;
+ if (max_sz)
+ *max_sz = bfh->cache_sz;
+ if (blockwise)
+ *blockwise = (bfh->file_sz != bfh->cache_sz);
+}
+
+/*
+ * Close the given binary file search handle.
+ *
+ * Inputs:
+ *
+ * @bfh Pointer to variable containing handle to close.
+ */
+void
+_bsearch_file_close(bsearch_file_handle *bfh)
+{
+ if (!*bfh)
+ return;
+ if ((*bfh)->fd >= 0)
+ (void) close((*bfh)->fd);
+ if ((*bfh)->page)
+ free((*bfh)->page);
+ if ((*bfh)->cache)
+ free((*bfh)->cache);
+ free(*bfh);
+ *bfh = NULL;
+}
+
+/*
+ * Private function to get a page from a cache. The cache is a char
+ * array of 2^n - 1 double-size page worth of bytes, where n is the
+ * number of tree levels that the cache stores. The cache can be
+ * smaller than n implies.
+ *
+ * The page may or may not be valid. If the first byte of it is NUL
+ * then it's not valid, else it is.
+ *
+ * Returns 1 if page is in cache and valid, 0 if the cache is too small
+ * or the page is invalid. The page address is output in @buf if the
+ * cache is large enough to contain it regardless of whether the page is
+ * valid.
+ *
+ * Inputs:
+ *
+ * @bfh Binary search file handle
+ * @level Level in the tree that we want a page for
+ * @page_idx Page number in the given level (0..2^level - 1)
+ *
+ * Outputs:
+ *
+ * @buf Set to address of page if the cache is large enough
+ */
+static int
+get_page_from_cache(bsearch_file_handle bfh, size_t level, size_t page_idx,
+ char **buf)
+{
+ size_t idx = 0;
+ size_t page_sz;
+
+ page_sz = bfh->page_sz << 1; /* we use double-size pages in the cache */
+
+ *buf = NULL;
+
+ /*
+ * Compute index into cache. The cache is basically an array of
+ * double-size pages. The first (zeroth) double-size page in the
+ * cache will be the middle page of the file -- the root of the
+ * tree. The next two double-size pages will be the left and right
+ * pages of the second level in the tree. The next four double-size
+ * pages will be the four pages at the next level. And so on for as
+ * many pages as fit in the cache.
+ *
+ * The page index is the number of the page at the given level. We
+ * then compute (2^level - 1 + page index) * 2page size, check that
+ * we have that in the cache, check that the page has been read (it
+ * doesn't start with NUL).
+ */
+ if (level)
+ idx = (1 << level) - 1 + page_idx;
+ if (((idx + 1) * page_sz * 2) > bfh->cache_sz)
+ return 0;
+
+ *buf = &bfh->cache[idx * page_sz * 2];
+ if (bfh->cache[idx * page_sz * 2] == '\0')
+ return 0; /* cache[idx] == NUL -> page not loaded in cache */
+ return 1;
+}
+
+/*
+ * Private function to read a page of @page_sz from @fd at offset @off
+ * into @buf, outputing the number of bytes read, which will be the same
+ * as @page_sz unless the page being read is the last page, in which
+ * case the number of remaining bytes in the file will be output.
+ *
+ * Returns 0 on success or an errno value otherwise (EIO if reads are
+ * short).
+ *
+ * Inputs:
+ *
+ * @bfh Binary search file handle
+ * @level Level in the binary search tree that we're at
+ * @page_idx Page "index" at the @level of the tree that we want
+ * @page Actual page number that we want
+ * want_double Whether we need a page or double page read
+ *
+ * Outputs:
+ *
+ * @buf Page read or cached
+ * @bytes Bytes read (may be less than page or double page size in
+ * the case of the last page, of course)
+ */
+static int
+read_page(bsearch_file_handle bfh, size_t level, size_t page_idx, size_t page,
+ int want_double, const char **buf, size_t *bytes)
+{
+ int ret;
+ off_t off;
+ size_t expected;
+ size_t wanted;
+ char *page_buf;
+
+ /* Figure out where we're reading and how much */
+ off = page * bfh->page_sz;
+ if (off < 0)
+ return EOVERFLOW;
+
+ wanted = bfh->page_sz << want_double;
+ expected = ((bfh->file_sz - off) > wanted) ? wanted : bfh->file_sz - off;
+
+ if (get_page_from_cache(bfh, level, page_idx, &page_buf)) {
+ *buf = page_buf;
+ *bytes = expected;
+ return 0; /* found in cache */
+ }
+
+
+ *bytes = 0;
+ *buf = NULL;
+
+ /* OK, we have to read a page or double-size page */
+
+ if (page_buf)
+ want_double = 1; /* we'll be caching; we cache double-size pages */
+ else
+ page_buf = bfh->page; /* we won't cache this page */
+
+ wanted = bfh->page_sz << want_double;
+ expected = ((bfh->file_sz - off) > wanted) ? wanted : bfh->file_sz - off;
+
+#ifdef HAVE_PREAD
+ ret = pread(bfh->fd, page_buf, expected, off);
+#else
+ if (lseek(bfh->fd, off, SEEK_SET) == (off_t)-1)
+ return errno;
+ ret = read(bfh->fd, page_buf, expected);
+#endif
+ if (ret < 0)
+ return errno;
+
+ if (ret != expected)
+ return EIO; /* XXX ??? */
+
+ *buf = page_buf;
+ *bytes = expected;
+ return 0;
+}
+
+/*
+ * Perform a binary search of a file where each line is a record (LF and
+ * CRLF supported). Each record consists of a key followed by an
+ * optional value separated from the key by whitespace. Whitespace can
+ * be quoted with backslashes. It's the caller's responsibility to
+ * encode/decode keys/values if quoting is desired; newlines should be
+ * encoded such that a newline does not appear in the result.
+ *
+ * The search is done with block-wise I/O (i.e., the whole file is not
+ * read into memory).
+ *
+ * All output arguments are optional.
+ *
+ * Returns 0 if key is found, -1 if not found, or an error code such as
+ * ENOMEM in case of error.
+ *
+ * NOTE: We could improve this by not freeing the buffer, instead
+ * requiring that the caller provide it. Further, we could cache
+ * the top N levels of [double-size] pages (2^N - 1 pages), which
+ * should speed up most searches by reducing the number of reads
+ * by N.
+ *
+ * Inputs:
+ *
+ * @fd File descriptor (file to search)
+ * @page_sz Page size (if zero then the file's st_blksize will be used)
+ * @key Key string to search for
+ *
+ * Outputs:
+ *
+ * @value Location to store a copy of the value (caller must free)
+ * @location Record location if found else the location where the
+ * record should be inserted (index into @buf)
+ * @loops Location to store a count of bisections required for
+ * search (useful for confirming logarithmic performance)
+ * @reads Location to store a count of pages read during search
+ * (useful for confirming logarithmic performance)
+ */
+int
+_bsearch_file(bsearch_file_handle bfh, const char *key,
+ char **value, size_t *location, size_t *loops, size_t *reads)
+{
+ int ret;
+ const char *buf;
+ size_t buf_sz;
+ size_t page, l, r;
+ size_t my_reads = 0;
+ size_t my_loops_total = 0;
+ size_t my_loops;
+ size_t level; /* level in the tree */
+ size_t page_idx = 0; /* page number in the tree level */
+ size_t buf_location;
+ int cmp;
+ int buf_ends_in_eol = 0;
+ int buf_is_start = 0;
+
+ if (reads)
+ *reads = 0;
+ if (value)
+ *value = NULL;
+ if (loops)
+ *loops = 0;
+
+ /* If whole file is in memory then search that and we're done */
+ if (bfh->file_sz == bfh->cache_sz)
+ return _bsearch_text(bfh->cache, bfh->cache_sz, key, value, location, loops);
+
+ /* Else block-wise binary search */
+
+ l = 0;
+ r = (bfh->file_sz / bfh->page_sz) + 1;
+ for (level = 0, page = r >> 1; page >= l && page < r ; level++) {
+ ret = read_page(bfh, level, page_idx, page, 0, &buf, &buf_sz);
+ if (ret != 0)
+ return ret;
+ my_reads++;
+ if (buf[buf_sz - 1] == '\r' || buf[buf_sz - 1] == '\n')
+ buf_ends_in_eol = 1;
+ else
+ buf_ends_in_eol = 0;
+
+ buf_is_start = page == 0 ? 1 : 0;
+ ret = bsearch_common(buf, (size_t)buf_sz, key, buf_is_start,
+ value, &buf_location, &cmp, &my_loops);
+ if (ret > 0)
+ return ret;
+ /* Found or no we update stats */
+ my_loops_total += my_loops;
+ if (loops)
+ *loops = my_loops_total;
+ if (reads)
+ *reads = my_reads;
+ if (location)
+ *location = page * bfh->page_sz + buf_location;
+ if (ret == 0)
+ return 0; /* found! */
+ /* Not found */
+ if (cmp < 0) {
+ /* Search left */
+ page_idx <<= 1;
+ r = page;
+ page = l + ((r - l) >> 1);
+ continue;
+ } else {
+ /*
+ * Search right, but first search the current and next
+ * blocks in case that the record we're looking for either
+ * straddles the boundary between this and the next record,
+ * or in case the record starts exactly at the next page.
+ */
+ heim_assert(cmp > 0, "cmp > 0");
+
+ if (!buf_ends_in_eol || page == l || page == (r - 1)) {
+ ret = read_page(bfh, level, page_idx, page, 1, &buf, &buf_sz);
+ if (ret != 0)
+ return ret;
+ my_reads++;
+
+ buf_is_start = page == l ? 1 : 0;
+
+ ret = bsearch_common(buf, (size_t)buf_sz, key, buf_is_start,
+ value, &buf_location, &cmp, &my_loops);
+ if (ret > 0)
+ return ret;
+ my_loops_total += my_loops;
+ if (loops)
+ *loops = my_loops_total;
+ if (reads)
+ *reads = my_reads;
+ if (location)
+ *location = page * bfh->page_sz + buf_location;
+ if (ret == 0)
+ return 0;
+ }
+
+ /* Oh well, search right */
+ if (l == page && r == (l + 1))
+ break;
+ page_idx = (page_idx << 1) + 1;
+ l = page;
+ page = l + ((r - l) >> 1);
+ continue;
+ }
+ }
+ return -1;
+}
+
+
+static int
+stdb_open(void *plug, const char *dbtype, const char *dbname,
+ heim_dict_t options, void **db, heim_error_t *error)
+{
+ bsearch_file_handle bfh;
+ char *p;
+ int ret;
+
+ if (error)
+ *error = NULL;
+ if (dbname == NULL || *dbname == '\0') {
+ if (error)
+ *error = heim_error_create(EINVAL,
+ N_("DB name required for sorted-text DB "
+ "plugin", ""));
+ return EINVAL;
+ }
+ p = strrchr(dbname, '.');
+ if (p == NULL || strcmp(p, ".txt") != 0) {
+ if (error)
+ *error = heim_error_create(ENOTSUP,
+ N_("Text file (name ending in .txt) "
+ "required for sorted-text DB plugin",
+ ""));
+ return ENOTSUP;
+ }
+
+ ret = _bsearch_file_open(dbname, 0, 0, &bfh, NULL);
+ if (ret)
+ return ret;
+
+ *db = bfh;
+ return 0;
+}
+
+static int
+stdb_close(void *db, heim_error_t *error)
+{
+ bsearch_file_handle bfh = db;
+
+ if (error)
+ *error = NULL;
+ _bsearch_file_close(&bfh);
+ return 0;
+}
+
+static heim_data_t
+stdb_copy_value(void *db, heim_string_t table, heim_data_t key,
+ heim_error_t *error)
+{
+ bsearch_file_handle bfh = db;
+ const char *k;
+ char *v = NULL;
+ heim_data_t value;
+ int ret;
+
+ if (error)
+ *error = NULL;
+
+ if (table == NULL)
+ table = HSTR("");
+
+ if (table != HSTR(""))
+ return NULL;
+
+ if (heim_get_tid(key) == HEIM_TID_STRING)
+ k = heim_string_get_utf8((heim_string_t)key);
+ else
+ k = (const char *)heim_data_get_ptr(key);
+ ret = _bsearch_file(bfh, k, &v, NULL, NULL, NULL);
+ if (ret == 0 && v == NULL)
+ ret = -1; /* Quiet lint */
+ if (ret != 0) {
+ if (ret > 0 && error)
+ *error = heim_error_create(ret, "%s", strerror(ret));
+ return NULL;
+ }
+ value = heim_data_create(v, strlen(v));
+ free(v);
+ /* XXX Handle ENOMEM */
+ return value;
+}
+
+struct heim_db_type heim_sorted_text_file_dbtype = {
+ 1, stdb_open, NULL, stdb_close, NULL, NULL, NULL, NULL, NULL, NULL,
+ stdb_copy_value, NULL, NULL, NULL
+};
diff --git a/third_party/heimdal/lib/base/common_plugin.h b/third_party/heimdal/lib/base/common_plugin.h
new file mode 100644
index 0000000..ece1d28
--- /dev/null
+++ b/third_party/heimdal/lib/base/common_plugin.h
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2006 - 2020 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2018 AuriStor, Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef HEIMDAL_BASE_COMMON_PLUGIN_H
+#define HEIMDAL_BASE_COMMON_PLUGIN_H
+
+#include <heimbase-svc.h>
+
+#ifdef _WIN32
+# ifndef HEIM_CALLCONV
+# define HEIM_CALLCONV __stdcall
+# endif
+# ifndef HEIM_LIB_CALL
+# define HEIM_LIB_CALL __stdcall
+# endif
+#else
+# ifndef HEIM_CALLCONV
+# define HEIM_CALLCONV
+# endif
+# ifndef HEIM_LIB_CALL
+# define HEIM_LIB_CALL
+# endif
+#endif
+#ifndef KRB5_CALLCONV
+# define KRB5_CALLCONV HEIM_CALLCONV
+#endif
+#ifndef KRB5_LIB_CALL
+# define KRB5_LIB_CALL HEIM_LIB_CALL
+#endif
+
+/* For krb5 plugins, this is a krb5_context */
+typedef struct heim_pcontext_s *heim_pcontext;
+
+typedef uintptr_t
+(HEIM_LIB_CALL *heim_get_instance_func_t)(const char *);
+typedef heim_get_instance_func_t krb5_get_instance_t;
+
+/*
+ * All plugin function tables extend the following structure.
+ */
+struct heim_plugin_common_ftable_desc {
+ HEIM_PLUGIN_FTABLE_COMMON_ELEMENTS(heim_pcontext);
+};
+typedef struct heim_plugin_common_ftable_desc heim_plugin_common_ftable;
+typedef struct heim_plugin_common_ftable_desc *heim_plugin_common_ftable_p;
+typedef struct heim_plugin_common_ftable_desc * const heim_plugin_common_ftable_cp;
+
+typedef int
+(HEIM_CALLCONV heim_plugin_load_ft)(heim_pcontext context,
+ heim_get_instance_func_t *func,
+ size_t *n_ftables,
+ heim_plugin_common_ftable_cp **ftables);
+
+typedef heim_plugin_load_ft *heim_plugin_load_t;
+
+/* For source backwards-compatibility */
+typedef struct heim_plugin_common_ftable_desc krb5_plugin_common_ftable;
+typedef struct heim_plugin_common_ftable_desc *krb5_plugin_common_ftable_p;
+typedef struct heim_plugin_common_ftable_desc * const krb5_plugin_common_ftable_cp;
+typedef heim_plugin_load_ft krb5_plugin_load_ft;
+typedef heim_plugin_load_ft *krb5_plugin_load_t;
+
+/*
+ * All plugins must export a function named "<type>_plugin_load" with
+ * a signature of:
+ *
+ * int HEIM_CALLCONV
+ * <type>_plugin_load(heim_pcontext context,
+ * heim_get_instance_func_t *func,
+ * size_t *n_ftables,
+ * const heim_plugin_common_ftable *const **ftables);
+ */
+#endif /* HEIMDAL_BASE_COMMON_PLUGIN_H */
diff --git a/third_party/heimdal/lib/base/config_file.c b/third_party/heimdal/lib/base/config_file.c
new file mode 100644
index 0000000..963569c
--- /dev/null
+++ b/third_party/heimdal/lib/base/config_file.c
@@ -0,0 +1,1458 @@
+/*
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+#include <assert.h>
+#include <ctype.h>
+#include <parse_time.h>
+
+#if defined(HAVE_FRAMEWORK_COREFOUNDATION)
+#include <CoreFoundation/CoreFoundation.h>
+#endif
+
+/* Gaah! I want a portable funopen */
+struct fileptr {
+ heim_context context;
+ const char *s;
+ FILE *f;
+};
+
+static char *
+config_fgets(char *str, size_t len, struct fileptr *ptr)
+{
+ /* XXX this is not correct, in that they don't do the same if the
+ line is longer than len */
+ if(ptr->f != NULL)
+ return fgets(str, len, ptr->f);
+ else {
+ /* this is almost strsep_copy */
+ const char *p;
+ ssize_t l;
+ if(*ptr->s == '\0')
+ return NULL;
+ p = ptr->s + strcspn(ptr->s, "\n");
+ if(*p == '\n')
+ p++;
+ l = min(len, (size_t)(p - ptr->s));
+ if(len > 0) {
+ memcpy(str, ptr->s, l);
+ str[l] = '\0';
+ }
+ ptr->s = p;
+ return str;
+ }
+}
+
+static heim_error_code parse_section(char *p, heim_config_section **s,
+ heim_config_section **res,
+ const char **err_message);
+static heim_error_code parse_binding(struct fileptr *f, unsigned *lineno, char *p,
+ heim_config_binding **b,
+ heim_config_binding **parent,
+ const char **err_message);
+static heim_error_code parse_list(struct fileptr *f, unsigned *lineno,
+ heim_config_binding **parent,
+ const char **err_message);
+
+heim_config_section *
+heim_config_get_entry(heim_config_section **parent, const char *name, int type)
+{
+ heim_config_section **q;
+
+ for (q = parent; *q != NULL; q = &(*q)->next)
+ if (type == heim_config_list &&
+ (unsigned)type == (*q)->type &&
+ strcmp(name, (*q)->name) == 0)
+ return *q;
+ *q = calloc(1, sizeof(**q));
+ if (*q == NULL)
+ return NULL;
+ (*q)->name = strdup(name);
+ (*q)->type = type;
+ if ((*q)->name == NULL) {
+ free(*q);
+ *q = NULL;
+ return NULL;
+ }
+ return *q;
+}
+
+/*
+ * Parse a section:
+ *
+ * [section]
+ * foo = bar
+ * b = {
+ * a
+ * }
+ * ...
+ *
+ * starting at the line in `p', storing the resulting structure in
+ * `s' and hooking it into `parent'.
+ * Store the error message in `err_message'.
+ */
+
+static heim_error_code
+parse_section(char *p, heim_config_section **s, heim_config_section **parent,
+ const char **err_message)
+{
+ char *p1;
+ heim_config_section *tmp;
+
+ p1 = strchr (p + 1, ']');
+ if (p1 == NULL) {
+ *err_message = "missing ]";
+ return HEIM_ERR_CONFIG_BADFORMAT;
+ }
+ *p1 = '\0';
+ tmp = heim_config_get_entry(parent, p + 1, heim_config_list);
+ if(tmp == NULL) {
+ *err_message = "out of memory";
+ return HEIM_ERR_CONFIG_BADFORMAT;
+ }
+ *s = tmp;
+ return 0;
+}
+
+/*
+ * Parse a brace-enclosed list from `f', hooking in the structure at
+ * `parent'.
+ * Store the error message in `err_message'.
+ */
+
+static heim_error_code
+parse_list(struct fileptr *f, unsigned *lineno, heim_config_binding **parent,
+ const char **err_message)
+{
+ char buf[2048];
+ heim_error_code ret;
+ heim_config_binding *b = NULL;
+ unsigned beg_lineno = *lineno;
+
+ while(config_fgets(buf, sizeof(buf), f) != NULL) {
+ char *p;
+
+ ++*lineno;
+ buf[strcspn(buf, "\r\n")] = '\0';
+ p = buf;
+ while(isspace((unsigned char)*p))
+ ++p;
+ if (*p == '#' || *p == ';' || *p == '\0')
+ continue;
+ while(isspace((unsigned char)*p))
+ ++p;
+ if (*p == '}')
+ return 0;
+ if (*p == '\0')
+ continue;
+ ret = parse_binding (f, lineno, p, &b, parent, err_message);
+ if (ret)
+ return ret;
+ }
+ *lineno = beg_lineno;
+ *err_message = "unclosed {";
+ return HEIM_ERR_CONFIG_BADFORMAT;
+}
+
+/*
+ *
+ */
+
+static heim_error_code
+parse_binding(struct fileptr *f, unsigned *lineno, char *p,
+ heim_config_binding **b, heim_config_binding **parent,
+ const char **err_message)
+{
+ heim_config_binding *tmp;
+ char *p1, *p2;
+ heim_error_code ret = 0;
+
+ p1 = p;
+ while (*p && *p != '=' && !isspace((unsigned char)*p))
+ ++p;
+ if (*p == '\0') {
+ *err_message = "missing =";
+ return HEIM_ERR_CONFIG_BADFORMAT;
+ }
+ p2 = p;
+ while (isspace((unsigned char)*p))
+ ++p;
+ if (*p != '=') {
+ *err_message = "missing =";
+ return HEIM_ERR_CONFIG_BADFORMAT;
+ }
+ ++p;
+ while(isspace((unsigned char)*p))
+ ++p;
+ *p2 = '\0';
+ if (*p == '{') {
+ tmp = heim_config_get_entry(parent, p1, heim_config_list);
+ if (tmp == NULL) {
+ *err_message = "out of memory";
+ return HEIM_ERR_CONFIG_BADFORMAT;
+ }
+ ret = parse_list (f, lineno, &tmp->u.list, err_message);
+ } else {
+ tmp = heim_config_get_entry(parent, p1, heim_config_string);
+ if (tmp == NULL) {
+ *err_message = "out of memory";
+ return HEIM_ERR_CONFIG_BADFORMAT;
+ }
+ p1 = p;
+ p = p1 + strlen(p1);
+ while(p > p1 && isspace((unsigned char)*(p-1)))
+ --p;
+ *p = '\0';
+ tmp->u.string = strdup(p1);
+ }
+ *b = tmp;
+ return ret;
+}
+
+#if defined(HAVE_FRAMEWORK_COREFOUNDATION)
+
+#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
+#define HAVE_CFPROPERTYLISTCREATEWITHSTREAM 1
+#endif
+
+static char *
+cfstring2cstring(CFStringRef string)
+{
+ CFIndex len;
+ char *str;
+
+ str = (char *) CFStringGetCStringPtr(string, kCFStringEncodingUTF8);
+ if (str)
+ return strdup(str);
+
+ len = CFStringGetLength(string);
+ len = 1 + CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUTF8);
+ str = malloc(len);
+ if (str == NULL)
+ return NULL;
+
+ if (!CFStringGetCString (string, str, len, kCFStringEncodingUTF8)) {
+ free (str);
+ return NULL;
+ }
+ return str;
+}
+
+static void
+convert_content(const void *key, const void *value, void *context)
+{
+ heim_config_section *tmp, **parent = context;
+ char *k;
+
+ if (CFGetTypeID(key) != CFStringGetTypeID())
+ return;
+
+ k = cfstring2cstring(key);
+ if (k == NULL)
+ return;
+
+ if (CFGetTypeID(value) == CFStringGetTypeID()) {
+ tmp = heim_config_get_entry(parent, k, heim_config_string);
+ tmp->u.string = cfstring2cstring(value);
+ } else if (CFGetTypeID(value) == CFDictionaryGetTypeID()) {
+ tmp = heim_config_get_entry(parent, k, heim_config_list);
+ CFDictionaryApplyFunction(value, convert_content, &tmp->u.list);
+ } else {
+ /* log */
+ }
+ free(k);
+}
+
+static heim_error_code
+parse_plist_config(heim_context context, const char *path, heim_config_section **parent)
+{
+ CFReadStreamRef s;
+ CFDictionaryRef d;
+ CFURLRef url;
+
+ url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8 *)path, strlen(path), 0);
+ if (url == NULL) {
+ heim_clear_error_message(context);
+ return ENOMEM;
+ }
+
+ s = CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
+ CFRelease(url);
+ if (s == NULL) {
+ heim_clear_error_message(context);
+ return ENOMEM;
+ }
+
+ if (!CFReadStreamOpen(s)) {
+ CFRelease(s);
+ heim_clear_error_message(context);
+ return ENOENT;
+ }
+
+#ifdef HAVE_CFPROPERTYLISTCREATEWITHSTREAM
+ d = (CFDictionaryRef)CFPropertyListCreateWithStream(NULL, s, 0, kCFPropertyListImmutable, NULL, NULL);
+#else
+ d = (CFDictionaryRef)CFPropertyListCreateFromStream(NULL, s, 0, kCFPropertyListImmutable, NULL, NULL);
+#endif
+ CFRelease(s);
+ if (d == NULL) {
+ heim_clear_error_message(context);
+ return ENOENT;
+ }
+
+ CFDictionaryApplyFunction(d, convert_content, parent);
+ CFRelease(d);
+
+ return 0;
+}
+
+#endif
+
+static int
+is_absolute_path(const char *path)
+{
+ /*
+ * An absolute path is one that refers to an explicit object
+ * without ambiguity.
+ */
+#ifdef WIN32
+ size_t len = strlen(path);
+
+ /* UNC path is by definition absolute */
+ if (len > 2
+ && ISPATHSEP(path[0])
+ && ISPATHSEP(path[1]))
+ return 1;
+
+ /* A drive letter path might be absolute */
+ if (len > 3
+ && isalpha(path[0])
+ && path[1] == ':'
+ && ISPATHSEP(path[2]))
+ return 1;
+
+ /*
+ * if no drive letter but first char is a path
+ * separator then the drive letter must be obtained
+ * from the including file.
+ */
+#else
+ /* UNIX is easy, first char '/' is absolute */
+ if (ISPATHSEP(path[0]))
+ return 1;
+#endif
+ return 0;
+}
+
+/*
+ * Parse the config file `fname', generating the structures into `res'
+ * returning error messages in `err_message'
+ */
+
+static heim_error_code
+heim_config_parse_debug(struct fileptr *f,
+ heim_config_section **res,
+ unsigned *lineno,
+ const char **err_message)
+{
+ heim_config_section *s = NULL;
+ heim_config_binding *b = NULL;
+ char buf[2048];
+ heim_error_code ret;
+
+ *lineno = 0;
+ *err_message = "";
+
+ while (config_fgets(buf, sizeof(buf), f) != NULL) {
+ char *p;
+
+ ++*lineno;
+ buf[strcspn(buf, "\r\n")] = '\0';
+ p = buf;
+ while(isspace((unsigned char)*p))
+ ++p;
+ if (*p == '#' || *p == ';')
+ continue;
+ if (*p == '[') {
+ ret = parse_section(p, &s, res, err_message);
+ if (ret)
+ return ret;
+ b = NULL;
+ } else if (*p == '}') {
+ *err_message = "unmatched }";
+ return 2048;
+ } else if (strncmp(p, "include", sizeof("include") - 1) == 0 &&
+ isspace(p[sizeof("include") - 1])) {
+ p += sizeof("include");
+ while (isspace(*p))
+ p++;
+ if (!is_absolute_path(p)) {
+ heim_set_error_message(f->context, HEIM_ERR_CONFIG_BADFORMAT,
+ "Configuration include path must be "
+ "absolute");
+ return HEIM_ERR_CONFIG_BADFORMAT;
+ }
+ ret = heim_config_parse_file_multi(f->context, p, res);
+ if (ret)
+ return ret;
+ } else if (strncmp(p, "includedir", sizeof("includedir") - 1) == 0 &&
+ isspace(p[sizeof("includedir") - 1])) {
+ p += sizeof("includedir");
+ while (isspace(*p))
+ p++;
+ if (!is_absolute_path(p)) {
+ heim_set_error_message(f->context, HEIM_ERR_CONFIG_BADFORMAT,
+ "Configuration includedir path must be "
+ "absolute");
+ return HEIM_ERR_CONFIG_BADFORMAT;
+ }
+ ret = heim_config_parse_dir_multi(f->context, p, res);
+ if (ret)
+ return ret;
+ } else if(*p != '\0') {
+ if (s == NULL) {
+ *err_message = "binding before section";
+ return 2048;
+ }
+ ret = parse_binding(f, lineno, p, &b, &s->u.list, err_message);
+ if (ret)
+ return ret;
+ }
+ }
+ return 0;
+}
+
+static int
+is_plist_file(const char *fname)
+{
+ size_t len = strlen(fname);
+ char suffix[] = ".plist";
+ if (len < sizeof(suffix))
+ return 0;
+ if (strcasecmp(&fname[len - (sizeof(suffix) - 1)], suffix) != 0)
+ return 0;
+ return 1;
+}
+
+/**
+ * Parse configuration files in the given directory and add the result
+ * into res. Only files whose names consist only of alphanumeric
+ * characters, hyphen, and underscore, will be parsed, though files
+ * ending in ".conf" will also be parsed.
+ *
+ * This interface can be used to parse several configuration directories
+ * into one resulting heim_config_section by calling it repeatably.
+ *
+ * @param context a Kerberos 5 context.
+ * @param dname a directory name to a Kerberos configuration file
+ * @param res the returned result, must be free with heim_free_config_files().
+ * @return Return an error code or 0, see heim_get_error_message().
+ *
+ * @ingroup heim_support
+ */
+
+heim_error_code
+heim_config_parse_dir_multi(heim_context context,
+ const char *dname,
+ heim_config_section **res)
+{
+ struct dirent *entry;
+ heim_error_code ret;
+ DIR *d;
+
+ if ((d = opendir(dname)) == NULL)
+ return errno;
+
+ while ((entry = readdir(d)) != NULL) {
+ char *p = entry->d_name;
+ char *path;
+ int is_valid = 1;
+
+ while (*p) {
+ /*
+ * Here be dragons. The call to heim_config_parse_file_multi()
+ * below expands path tokens. Because of the limitations here
+ * on file naming, we can't have path tokens in the file name,
+ * so we're safe. Anyone changing this if condition here should
+ * be aware.
+ */
+ if (!isalnum(*p) && *p != '_' && *p != '-' &&
+ strcmp(p, ".conf") != 0) {
+ is_valid = 0;
+ break;
+ }
+ p++;
+ }
+ if (!is_valid)
+ continue;
+
+ if (asprintf(&path, "%s/%s", dname, entry->d_name) == -1 ||
+ path == NULL) {
+ (void) closedir(d);
+ return heim_enomem(context);
+ }
+ ret = heim_config_parse_file_multi(context, path, res);
+ free(path);
+ if (ret == ENOMEM) {
+ (void) closedir(d);
+ return ENOMEM;
+ }
+ /* Ignore malformed config files so we don't lock out admins, etc... */
+ }
+ (void) closedir(d);
+ return 0;
+}
+
+/**
+ * Parse a configuration file and add the result into res. This
+ * interface can be used to parse several configuration files into one
+ * resulting heim_config_section by calling it repeatably.
+ *
+ * @param context a Kerberos 5 context.
+ * @param fname a file name to a Kerberos configuration file
+ * @param res the returned result, must be free with heim_free_config_files().
+ * @return Return an error code or 0, see heim_get_error_message().
+ *
+ * @ingroup heim_support
+ */
+
+HEIMDAL_THREAD_LOCAL int config_include_depth = 0;
+
+heim_error_code
+heim_config_parse_file_multi(heim_context context,
+ const char *fname,
+ heim_config_section **res)
+{
+ const char *str;
+ char *newfname = NULL;
+ unsigned lineno = 0;
+ heim_error_code ret = 0;
+ struct fileptr f;
+ struct stat st;
+
+ if (config_include_depth > 5) {
+ heim_warnx(context, "Maximum config file include depth reached; "
+ "not including %s", fname);
+ return 0;
+ }
+ config_include_depth++;
+
+ /**
+ * If the fname starts with "~/" parse configuration file in the
+ * current users home directory. The behavior can be disabled and
+ * enabled by calling heim_set_home_dir_access().
+ */
+ if (ISTILDE(fname[0]) && ISPATHSEP(fname[1])) {
+ if (!heim_context_get_homedir_access(context)) {
+ heim_set_error_message(context, EPERM,
+ "Access to home directory not allowed");
+ ret = EPERM;
+ goto out;
+ }
+ if (asprintf(&newfname, "%%{USERCONFIG}%s", &fname[1]) < 0 ||
+ newfname == NULL) {
+ ret = heim_enomem(context);
+ goto out;
+ }
+ fname = newfname;
+ }
+
+ if (is_plist_file(fname)) {
+#if defined(HAVE_FRAMEWORK_COREFOUNDATION)
+ ret = parse_plist_config(context, fname, res);
+ if (ret) {
+ heim_set_error_message(context, ret,
+ "Failed to parse plist %s", fname);
+ goto out;
+ }
+#else
+ heim_set_error_message(context, ENOENT,
+ "no support for plist configuration files");
+ ret = ENOENT;
+ goto out;
+#endif
+ } else {
+ char *exp_fname = NULL;
+
+ /*
+ * Note that heim_config_parse_dir_multi() doesn't want tokens
+ * expanded here, but it happens to limit the names of files to
+ * include such that there can be no tokens to expand. Don't
+ * add token expansion for tokens using _, say.
+ */
+ ret = heim_expand_path_tokens(context, fname, 1, &exp_fname, NULL);
+ if (ret)
+ goto out;
+ free(newfname);
+ fname = newfname = exp_fname;
+
+ f.context = context;
+ f.f = fopen(fname, "r");
+ f.s = NULL;
+ if (f.f == NULL || fstat(fileno(f.f), &st) == -1) {
+ if (f.f != NULL)
+ (void) fclose(f.f);
+ ret = errno;
+ heim_set_error_message(context, ret, "open or stat %s: %s",
+ fname, strerror(ret));
+ goto out;
+ }
+
+ if (!S_ISREG(st.st_mode)) {
+ (void) fclose(f.f);
+ heim_set_error_message(context, EISDIR, "not a regular file %s: %s",
+ fname, strerror(EISDIR));
+ ret = EISDIR;
+ goto out;
+ }
+
+ ret = heim_config_parse_debug(&f, res, &lineno, &str);
+ fclose(f.f);
+ if (ret) {
+ if (ret != HEIM_ERR_CONFIG_BADFORMAT)
+ ret = HEIM_ERR_CONFIG_BADFORMAT;
+ heim_set_error_message(context, ret, "%s:%u: %s",
+ fname, lineno, str);
+ goto out;
+ }
+ }
+
+ out:
+ config_include_depth--;
+ if (ret == HEIM_ERR_CONFIG_BADFORMAT || (ret && config_include_depth > 0)) {
+ heim_warn(context, ret, "Ignoring");
+ if (config_include_depth > 0)
+ ret = 0;
+ }
+ free(newfname);
+ return ret;
+}
+
+heim_error_code
+heim_config_parse_file(heim_context context,
+ const char *fname,
+ heim_config_section **res)
+{
+ *res = NULL;
+ return heim_config_parse_file_multi(context, fname, res);
+}
+
+static void
+free_binding(heim_context context, heim_config_binding *b)
+{
+ heim_config_binding *next_b;
+
+ while (b) {
+ free (b->name);
+ assert(b->type == heim_config_string || b->type == heim_config_list);
+ if (b->type == heim_config_string)
+ free (b->u.string);
+ else
+ free_binding (context, b->u.list);
+ next_b = b->next;
+ free (b);
+ b = next_b;
+ }
+}
+
+/**
+ * Free configuration file section, the result of
+ * heim_config_parse_file() and heim_config_parse_file_multi().
+ *
+ * @param context A Kerberos 5 context
+ * @param s the configuration section to free
+ *
+ * @return returns 0 on successes, otherwise an error code, see
+ * heim_get_error_message()
+ *
+ * @ingroup heim_support
+ */
+
+heim_error_code
+heim_config_file_free(heim_context context, heim_config_section *s)
+{
+ free_binding (context, s);
+ return 0;
+}
+
+#ifndef HEIMDAL_SMALLER
+
+heim_error_code
+heim_config_copy(heim_context context,
+ heim_config_section *c,
+ heim_config_section **head)
+{
+ heim_config_binding *d, *previous = NULL;
+
+ *head = NULL;
+
+ while (c) {
+ d = calloc(1, sizeof(*d));
+
+ if (*head == NULL)
+ *head = d;
+
+ d->name = strdup(c->name);
+ d->type = c->type;
+ assert(d->type == heim_config_string || d->type == heim_config_list);
+ if (d->type == heim_config_string)
+ d->u.string = strdup(c->u.string);
+ else
+ heim_config_copy (context, c->u.list, &d->u.list);
+ if (previous)
+ previous->next = d;
+
+ previous = d;
+ c = c->next;
+ }
+ return 0;
+}
+
+#endif /* HEIMDAL_SMALLER */
+
+const void *
+heim_config_get_next(heim_context context,
+ const heim_config_section *c,
+ const heim_config_binding **pointer,
+ int type,
+ ...)
+{
+ const char *ret;
+ va_list args;
+
+ va_start(args, type);
+ ret = heim_config_vget_next(context, c, pointer, type, args);
+ va_end(args);
+ return ret;
+}
+
+static const void *
+vget_next(heim_context context,
+ const heim_config_binding *b,
+ const heim_config_binding **pointer,
+ int type,
+ const char *name,
+ va_list args)
+{
+ const char *p = va_arg(args, const char *);
+
+ while (b != NULL) {
+ if (strcmp(b->name, name) == 0) {
+ if (b->type == (unsigned)type && p == NULL) {
+ *pointer = b;
+ return b->u.generic;
+ } else if (b->type == heim_config_list && p != NULL) {
+ return vget_next(context, b->u.list, pointer, type, p, args);
+ }
+ }
+ b = b->next;
+ }
+ return NULL;
+}
+
+const void *
+heim_config_vget_next(heim_context context,
+ const heim_config_section *c,
+ const heim_config_binding **pointer,
+ int type,
+ va_list args)
+{
+ const heim_config_binding *b;
+ const char *p;
+
+ if (c == NULL)
+ return NULL;
+
+ if (*pointer == NULL) {
+ /* first time here, walk down the tree looking for the right
+ section */
+ p = va_arg(args, const char *);
+ if (p == NULL)
+ return NULL;
+ return vget_next(context, c, pointer, type, p, args);
+ }
+
+ /* we were called again, so just look for more entries with the
+ same name and type */
+ for (b = (*pointer)->next; b != NULL; b = b->next) {
+ if(strcmp(b->name, (*pointer)->name) == 0 && b->type == (unsigned)type) {
+ *pointer = b;
+ return b->u.generic;
+ }
+ }
+ return NULL;
+}
+
+const void *
+heim_config_get(heim_context context,
+ const heim_config_section *c,
+ int type,
+ ...)
+{
+ const void *ret;
+ va_list args;
+
+ va_start(args, type);
+ ret = heim_config_vget(context, c, type, args);
+ va_end(args);
+ return ret;
+}
+
+
+const void *
+heim_config_vget(heim_context context,
+ const heim_config_section *c,
+ int type,
+ va_list args)
+{
+ const heim_config_binding *foo = NULL;
+
+ return heim_config_vget_next(context, c, &foo, type, args);
+}
+
+/**
+ * Get a list of configuration binding list for more processing
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return NULL if configuration list is not found, a list otherwise
+ *
+ * @ingroup heim_support
+ */
+
+const heim_config_binding *
+heim_config_get_list(heim_context context,
+ const heim_config_section *c,
+ ...)
+{
+ const heim_config_binding *ret;
+ va_list args;
+
+ va_start(args, c);
+ ret = heim_config_vget_list(context, c, args);
+ va_end(args);
+ return ret;
+}
+
+/**
+ * Get a list of configuration binding list for more processing
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param args a va_list of arguments
+ *
+ * @return NULL if configuration list is not found, a list otherwise
+ *
+ * @ingroup heim_support
+ */
+
+const heim_config_binding *
+heim_config_vget_list(heim_context context,
+ const heim_config_section *c,
+ va_list args)
+{
+ return heim_config_vget(context, c, heim_config_list, args);
+}
+
+/**
+ * Returns a "const char *" to a string in the configuration database.
+ * The string may not be valid after a reload of the configuration
+ * database so a caller should make a local copy if it needs to keep
+ * the string.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return NULL if configuration string not found, a string otherwise
+ *
+ * @ingroup heim_support
+ */
+
+const char *
+heim_config_get_string(heim_context context,
+ const heim_config_section *c,
+ ...)
+{
+ const char *ret;
+ va_list args;
+
+ va_start(args, c);
+ ret = heim_config_vget_string(context, c, args);
+ va_end(args);
+ return ret;
+}
+
+/**
+ * Like heim_config_get_string(), but uses a va_list instead of ...
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param args a va_list of arguments
+ *
+ * @return NULL if configuration string not found, a string otherwise
+ *
+ * @ingroup heim_support
+ */
+
+const char *
+heim_config_vget_string(heim_context context,
+ const heim_config_section *c,
+ va_list args)
+{
+ return heim_config_vget(context, c, heim_config_string, args);
+}
+
+/**
+ * Like heim_config_vget_string(), but instead of returning NULL,
+ * instead return a default value.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param def_value the default value to return if no configuration
+ * found in the database.
+ * @param args a va_list of arguments
+ *
+ * @return a configuration string
+ *
+ * @ingroup heim_support
+ */
+
+const char *
+heim_config_vget_string_default(heim_context context,
+ const heim_config_section *c,
+ const char *def_value,
+ va_list args)
+{
+ const char *ret;
+
+ ret = heim_config_vget_string(context, c, args);
+ if (ret == NULL)
+ ret = def_value;
+ return ret;
+}
+
+/**
+ * Like heim_config_get_string(), but instead of returning NULL,
+ * instead return a default value.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param def_value the default value to return if no configuration
+ * found in the database.
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return a configuration string
+ *
+ * @ingroup heim_support
+ */
+
+const char *
+heim_config_get_string_default(heim_context context,
+ const heim_config_section *c,
+ const char *def_value,
+ ...)
+{
+ const char *ret;
+ va_list args;
+
+ va_start(args, def_value);
+ ret = heim_config_vget_string_default (context, c, def_value, args);
+ va_end(args);
+ return ret;
+}
+
+static char *
+next_component_string(char * begin, const char * delims, char **state)
+{
+ char * end;
+
+ if (begin == NULL)
+ begin = *state;
+
+ if (*begin == '\0')
+ return NULL;
+
+ end = begin;
+ while (*end == '"') {
+ char * t = strchr(end + 1, '"');
+
+ if (t)
+ end = ++t;
+ else
+ end += strlen(end);
+ }
+
+ if (*end != '\0') {
+ size_t pos;
+
+ pos = strcspn(end, delims);
+ end = end + pos;
+ }
+
+ if (*end != '\0') {
+ *end = '\0';
+ *state = end + 1;
+ if (*begin == '"' && *(end - 1) == '"' && begin + 1 < end) {
+ begin++; *(end - 1) = '\0';
+ }
+ return begin;
+ }
+
+ *state = end;
+ if (*begin == '"' && *(end - 1) == '"' && begin + 1 < end) {
+ begin++; *(end - 1) = '\0';
+ }
+ return begin;
+}
+
+/**
+ * Get a list of configuration strings, free the result with
+ * heim_config_free_strings().
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param args a va_list of arguments
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup heim_support
+ */
+
+char **
+heim_config_vget_strings(heim_context context,
+ const heim_config_section *c,
+ va_list args)
+{
+ char **strings = NULL;
+ size_t nstr = 0;
+ const heim_config_binding *b = NULL;
+ const char *p;
+
+ while((p = heim_config_vget_next(context, c, &b,
+ heim_config_string, args))) {
+ char *tmp = strdup(p);
+ char *pos = NULL;
+ char *s;
+ if(tmp == NULL)
+ goto cleanup;
+ s = next_component_string(tmp, " \t", &pos);
+ while(s){
+ char **tmp2 = realloc(strings, (nstr + 1) * sizeof(*strings));
+ if(tmp2 == NULL) {
+ free(tmp);
+ goto cleanup;
+ }
+ strings = tmp2;
+ strings[nstr] = strdup(s);
+ nstr++;
+ if(strings[nstr-1] == NULL) {
+ free(tmp);
+ goto cleanup;
+ }
+ s = next_component_string(NULL, " \t", &pos);
+ }
+ free(tmp);
+ }
+ if(nstr){
+ char **tmp = realloc(strings, (nstr + 1) * sizeof(*strings));
+ if(tmp == NULL)
+ goto cleanup;
+ strings = tmp;
+ strings[nstr] = NULL;
+ }
+ return strings;
+cleanup:
+ while(nstr--)
+ free(strings[nstr]);
+ free(strings);
+ return NULL;
+
+}
+
+/**
+ * Get a list of configuration strings, free the result with
+ * heim_config_free_strings().
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup heim_support
+ */
+
+char **
+heim_config_get_strings(heim_context context,
+ const heim_config_section *c,
+ ...)
+{
+ va_list ap;
+ char **ret;
+ va_start(ap, c);
+ ret = heim_config_vget_strings(context, c, ap);
+ va_end(ap);
+ return ret;
+}
+
+/**
+ * Free the resulting strings from heim_config-get_strings() and
+ * heim_config_vget_strings().
+ *
+ * @param strings strings to free
+ *
+ * @ingroup heim_support
+ */
+
+void
+heim_config_free_strings(char **strings)
+{
+ char **s = strings;
+
+ while (s && *s) {
+ free(*s);
+ s++;
+ }
+ free(strings);
+}
+
+/**
+ * Like heim_config_get_bool_default() but with a va_list list of
+ * configuration selection.
+ *
+ * Configuration value to a boolean value, where yes/true and any
+ * non-zero number means TRUE and other value is FALSE.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param def_value the default value to return if no configuration
+ * found in the database.
+ * @param args a va_list of arguments
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup heim_support
+ */
+
+int
+heim_config_vget_bool_default(heim_context context,
+ const heim_config_section *c,
+ int def_value,
+ va_list args)
+{
+ const char *str;
+ str = heim_config_vget_string(context, c, args);
+ if (str == NULL)
+ return def_value;
+ return !!(strcasecmp(str, "yes") == 0 ||
+ strcasecmp(str, "true") == 0 ||
+ atoi(str));
+}
+
+/**
+ * heim_config_get_bool() will convert the configuration
+ * option value to a boolean value, where yes/true and any non-zero
+ * number means TRUE and other value is FALSE.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param args a va_list of arguments
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup heim_support
+ */
+
+int
+heim_config_vget_bool(heim_context context,
+ const heim_config_section *c,
+ va_list args)
+{
+ return heim_config_vget_bool_default(context, c, 0, args);
+}
+
+/**
+ * heim_config_get_bool_default() will convert the configuration
+ * option value to a boolean value, where yes/true and any non-zero
+ * number means TRUE and other value is FALSE.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param def_value the default value to return if no configuration
+ * found in the database.
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup heim_support
+ */
+
+int
+heim_config_get_bool_default(heim_context context,
+ const heim_config_section *c,
+ int def_value,
+ ...)
+{
+ va_list ap;
+ int ret;
+
+ va_start(ap, def_value);
+ ret = heim_config_vget_bool_default(context, c, def_value, ap);
+ va_end(ap);
+ return ret;
+}
+
+/**
+ * Like heim_config_get_bool() but with a va_list list of
+ * configuration selection.
+ *
+ * Configuration value to a boolean value, where yes/true and any
+ * non-zero number means TRUE and other value is FALSE.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup heim_support
+ */
+
+int
+heim_config_get_bool(heim_context context,
+ const heim_config_section *c,
+ ...)
+{
+ va_list ap;
+ int ret;
+ va_start(ap, c);
+ ret = heim_config_vget_bool (context, c, ap);
+ va_end(ap);
+ return ret;
+}
+
+/**
+ * Get the time from the configuration file using a relative time.
+ *
+ * Like heim_config_get_time_default() but with a va_list list of
+ * configuration selection.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param def_value the default value to return if no configuration
+ * found in the database.
+ * @param args a va_list of arguments
+ *
+ * @return parsed the time (or def_value on parse error)
+ *
+ * @ingroup heim_support
+ */
+
+time_t
+heim_config_vget_time_default(heim_context context,
+ const heim_config_section *c,
+ int def_value,
+ va_list args)
+{
+ const char *str;
+ time_t t = -1;
+
+ if ((str = heim_config_vget_string(context, c, args)))
+ t = parse_time(str, "s");
+ return t != -1 ? t : def_value;
+}
+
+/**
+ * Get the time from the configuration file using a relative time, for example: 1h30s
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param args a va_list of arguments
+ *
+ * @return parsed the time or -1 on error
+ *
+ * @ingroup heim_support
+ */
+
+time_t
+heim_config_vget_time(heim_context context,
+ const heim_config_section *c,
+ va_list args)
+{
+ return heim_config_vget_time_default(context, c, -1, args);
+}
+
+/**
+ * Get the time from the configuration file using a relative time, for example: 1h30s
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param def_value the default value to return if no configuration
+ * found in the database.
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return parsed the time (or def_value on parse error)
+ *
+ * @ingroup heim_support
+ */
+
+time_t
+heim_config_get_time_default(heim_context context,
+ const heim_config_section *c,
+ int def_value,
+ ...)
+{
+ va_list ap;
+ time_t ret;
+
+ va_start(ap, def_value);
+ ret = heim_config_vget_time_default(context, c, def_value, ap);
+ va_end(ap);
+ return ret;
+}
+
+/**
+ * Get the time from the configuration file using a relative time, for example: 1h30s
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return parsed the time or -1 on error
+ *
+ * @ingroup heim_support
+ */
+
+time_t
+heim_config_get_time(heim_context context,
+ const heim_config_section *c,
+ ...)
+{
+ va_list ap;
+ int ret;
+ va_start(ap, c);
+ ret = heim_config_vget_time(context, c, ap);
+ va_end(ap);
+ return ret;
+}
+
+
+int
+heim_config_vget_int_default(heim_context context,
+ const heim_config_section *c,
+ int def_value,
+ va_list args)
+{
+ const char *str;
+ str = heim_config_vget_string (context, c, args);
+ if(str == NULL)
+ return def_value;
+ else {
+ char *endptr;
+ long l;
+ l = strtol(str, &endptr, 0);
+ if (endptr == str)
+ return def_value;
+ else
+ return l;
+ }
+}
+
+int
+heim_config_vget_int(heim_context context,
+ const heim_config_section *c,
+ va_list args)
+{
+ return heim_config_vget_int_default(context, c, -1, args);
+}
+
+int
+heim_config_get_int_default(heim_context context,
+ const heim_config_section *c,
+ int def_value,
+ ...)
+{
+ va_list ap;
+ int ret;
+
+ va_start(ap, def_value);
+ ret = heim_config_vget_int_default(context, c, def_value, ap);
+ va_end(ap);
+ return ret;
+}
+
+int
+heim_config_get_int(heim_context context,
+ const heim_config_section *c,
+ ...)
+{
+ va_list ap;
+ int ret;
+ va_start(ap, c);
+ ret = heim_config_vget_int (context, c, ap);
+ va_end(ap);
+ return ret;
+}
+
+#ifndef HEIMDAL_SMALLER
+heim_error_code
+heim_config_parse_string_multi(heim_context context,
+ const char *string,
+ heim_config_section **res)
+{
+ const char *str;
+ unsigned lineno = 0;
+ heim_error_code ret;
+ struct fileptr f;
+
+ f.context = context;
+ f.f = NULL;
+ f.s = string;
+
+ ret = heim_config_parse_debug(&f, res, &lineno, &str);
+ if (ret) {
+ if (ret != HEIM_ERR_CONFIG_BADFORMAT) {
+ ret = HEIM_ERR_CONFIG_BADFORMAT;
+ heim_set_error_message(context, ret, "%s:%u: %s",
+ "<constant>", lineno, str);
+ }
+ return ret;
+ }
+ return 0;
+}
+#endif
diff --git a/third_party/heimdal/lib/base/config_reg.c b/third_party/heimdal/lib/base/config_reg.c
new file mode 100644
index 0000000..cb24e50
--- /dev/null
+++ b/third_party/heimdal/lib/base/config_reg.c
@@ -0,0 +1,658 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include "baselocl.h"
+
+#ifndef _WIN32
+#error config_reg.c is only for Windows
+#endif
+
+#include <shlwapi.h>
+
+#ifndef MAX_DWORD
+#define MAX_DWORD 0xFFFFFFFF
+#endif
+
+/**
+ * Store a string as a registry value of the specified type
+ *
+ * The following registry types are handled:
+ *
+ * - REG_DWORD: The string is converted to a number.
+ *
+ * - REG_SZ: The string is stored as is.
+ *
+ * - REG_EXPAND_SZ: The string is stored as is.
+ *
+ * - REG_MULTI_SZ:
+ *
+ * . If a separator is specified, the input string is broken
+ * up into multiple strings and stored as a multi-sz.
+ *
+ * . If no separator is provided, the input string is stored
+ * as a multi-sz.
+ *
+ * - REG_NONE:
+ *
+ * . If the string is all numeric, it will be stored as a
+ * REG_DWORD.
+ *
+ * . Otherwise, the string is stored as a REG_SZ.
+ *
+ * Other types are rejected.
+ *
+ * If cb_data is MAX_DWORD, the string pointed to by data must be nul-terminated
+ * otherwise a buffer overrun will occur.
+ *
+ * @param [in]valuename Name of the registry value to be modified or created
+ * @param [in]type Type of the value. REG_NONE if unknown
+ * @param [in]data The input string to be stored in the registry.
+ * @param [in]cb_data Size of the input string in bytes. MAX_DWORD if unknown.
+ * @param [in]separator Separator character for parsing strings.
+ *
+ * @retval 0 if success or non-zero on error.
+ * If non-zero is returned, an error message has been set using
+ * heim_set_error_message().
+ *
+ */
+int
+heim_store_string_to_reg_value(heim_context context,
+ HKEY key, const char *valuename,
+ DWORD type, const char *data, DWORD cb_data,
+ const char *separator)
+{
+ LONG rcode;
+ int dwData;
+ BYTE static_buffer[16384];
+
+ if (data == NULL)
+ {
+ if (context)
+ heim_set_error_message(context, 0,
+ "'data' must not be NULL");
+ return -1;
+ }
+
+ if (cb_data == MAX_DWORD)
+ {
+ cb_data = (DWORD)strlen(data) + 1;
+ }
+ else if ((type == REG_MULTI_SZ && cb_data >= sizeof(static_buffer) - 1) ||
+ cb_data >= sizeof(static_buffer))
+ {
+ if (context)
+ heim_set_error_message(context, 0, "cb_data too big");
+ return -1;
+ }
+ else if (data[cb_data-1] != '\0')
+ {
+ memcpy(static_buffer, data, cb_data);
+ static_buffer[cb_data++] = '\0';
+ if (type == REG_MULTI_SZ)
+ static_buffer[cb_data++] = '\0';
+ data = static_buffer;
+ }
+
+ if (type == REG_NONE)
+ {
+ /*
+ * If input is all numeric, convert to DWORD and save as REG_DWORD.
+ * Otherwise, store as REG_SZ.
+ */
+ if ( StrToIntExA( data, STIF_SUPPORT_HEX, &dwData) )
+ {
+ type = REG_DWORD;
+ } else {
+ type = REG_SZ;
+ }
+ }
+
+ switch (type) {
+ case REG_SZ:
+ case REG_EXPAND_SZ:
+ rcode = RegSetValueEx(key, valuename, 0, type, data, cb_data);
+ if (rcode)
+ {
+ if (context)
+ heim_set_error_message(context, 0,
+ "Unexpected error when setting registry value %s gle 0x%x",
+ valuename,
+ GetLastError());
+ return -1;
+ }
+ break;
+ case REG_MULTI_SZ:
+ if (separator && *separator)
+ {
+ char *cp;
+
+ if (data != static_buffer)
+ static_buffer[cb_data++] = '\0';
+
+ for ( cp = static_buffer; cp < static_buffer+cb_data; cp++)
+ {
+ if (*cp == *separator)
+ *cp = '\0';
+ }
+
+ rcode = RegSetValueEx(key, valuename, 0, type, data, cb_data);
+ if (rcode)
+ {
+ if (context)
+ heim_set_error_message(context, 0,
+ "Unexpected error when setting registry value %s gle 0x%x",
+ valuename,
+ GetLastError());
+ return -1;
+ }
+ }
+ break;
+ case REG_DWORD:
+ if ( !StrToIntExA( data, STIF_SUPPORT_HEX, &dwData) )
+ {
+ if (context)
+ heim_set_error_message(context, 0,
+ "Unexpected error when parsing %s as number gle 0x%x",
+ data,
+ GetLastError());
+ }
+
+ rcode = RegSetValueEx(key, valuename, 0, type, (BYTE *)&dwData, sizeof(DWORD));
+ if (rcode)
+ {
+ if (context)
+ heim_set_error_message(context, 0,
+ "Unexpected error when setting registry value %s gle 0x%x",
+ valuename,
+ GetLastError());
+ return -1;
+ }
+ break;
+ default:
+ return -1;
+ }
+
+ return 0;
+}
+
+/**
+ * Parse a registry value as a string
+ *
+ * @see heim_parse_reg_value_as_multi_string()
+ */
+char *
+heim_parse_reg_value_as_string(heim_context context,
+ HKEY key, const char * valuename,
+ DWORD type, DWORD cb_data)
+{
+ return heim_parse_reg_value_as_multi_string(context, key, valuename,
+ type, cb_data, " ");
+}
+
+/**
+ * Parse a registry value as a multi string
+ *
+ * The following registry value types are handled:
+ *
+ * - REG_DWORD: The decimal string representation is used as the
+ * value.
+ *
+ * - REG_SZ: The string is used as-is.
+ *
+ * - REG_EXPAND_SZ: Environment variables in the string are expanded
+ * and the result is used as the value.
+ *
+ * - REG_MULTI_SZ: The list of strings is concatenated using the
+ * separator. No quoting is performed.
+ *
+ * Any other value type is rejected.
+ *
+ * @param [in]valuename Name of the registry value to be queried
+ * @param [in]type Type of the value. REG_NONE if unknown
+ * @param [in]cbdata Size of value. 0 if unknown.
+ * @param [in]separator Separator character for concatenating strings.
+ *
+ * @a type and @a cbdata are only considered valid if both are
+ * specified.
+ *
+ * @retval The registry value string, or NULL if there was an error.
+ * If NULL is returned, an error message has been set using
+ * heim_set_error_message().
+ */
+char *
+heim_parse_reg_value_as_multi_string(heim_context context,
+ HKEY key, const char * valuename,
+ DWORD type, DWORD cb_data, char *separator)
+{
+ LONG rcode = ERROR_MORE_DATA;
+
+ BYTE static_buffer[16384];
+ BYTE *pbuffer = &static_buffer[0];
+ DWORD cb_alloc = sizeof(static_buffer);
+ char *ret_string = NULL;
+
+ /* If we know a type and cb_data from a previous call to
+ * RegEnumValue(), we use it. Otherwise we use the
+ * static_buffer[] and query directly. We do this to minimize the
+ * number of queries. */
+
+ if (type == REG_NONE || cb_data == 0) {
+
+ pbuffer = &static_buffer[0];
+ cb_alloc = cb_data = sizeof(static_buffer);
+ rcode = RegQueryValueExA(key, valuename, NULL, &type, pbuffer, &cb_data);
+
+ if (rcode == ERROR_SUCCESS &&
+
+ ((type != REG_SZ &&
+ type != REG_EXPAND_SZ) || cb_data + 1 <= sizeof(static_buffer)) &&
+
+ (type != REG_MULTI_SZ || cb_data + 2 <= sizeof(static_buffer)))
+ goto have_data;
+
+ if (rcode != ERROR_MORE_DATA && rcode != ERROR_SUCCESS)
+ return NULL;
+ }
+
+ /* Either we don't have the data or we aren't sure of the size
+ * (due to potentially missing terminating NULs). */
+
+ switch (type) {
+ case REG_DWORD:
+ if (cb_data != sizeof(DWORD)) {
+ if (context)
+ heim_set_error_message(context, 0,
+ "Unexpected size while reading registry value %s",
+ valuename);
+ return NULL;
+ }
+ break;
+
+ case REG_SZ:
+ case REG_EXPAND_SZ:
+
+ if (rcode == ERROR_SUCCESS && cb_data > 0 && pbuffer[cb_data - 1] == '\0')
+ goto have_data;
+
+ cb_data += sizeof(char); /* Accout for potential missing NUL
+ * terminator. */
+ break;
+
+ case REG_MULTI_SZ:
+
+ if (rcode == ERROR_SUCCESS && cb_data > 0 && pbuffer[cb_data - 1] == '\0' &&
+ (cb_data == 1 || pbuffer[cb_data - 2] == '\0'))
+ goto have_data;
+
+ cb_data += sizeof(char) * 2; /* Potential missing double NUL
+ * terminator. */
+ break;
+
+ default:
+ if (context)
+ heim_set_error_message(context, 0,
+ "Unexpected type while reading registry value %s",
+ valuename);
+ return NULL;
+ }
+
+ if (cb_data <= sizeof(static_buffer))
+ pbuffer = &static_buffer[0];
+ else {
+ pbuffer = malloc(cb_data);
+ if (pbuffer == NULL)
+ return NULL;
+ }
+
+ cb_alloc = cb_data;
+ rcode = RegQueryValueExA(key, valuename, NULL, NULL, pbuffer, &cb_data);
+
+ if (rcode != ERROR_SUCCESS) {
+
+ /* This can potentially be from a race condition. I.e. some
+ * other process or thread went and modified the registry
+ * value between the time we queried its size and queried for
+ * its value. Ideally we would retry the query in a loop. */
+
+ if (context)
+ heim_set_error_message(context, 0,
+ "Unexpected error while reading registry value %s",
+ valuename);
+ goto done;
+ }
+
+ if (cb_data > cb_alloc || cb_data == 0) {
+ if (context)
+ heim_set_error_message(context, 0,
+ "Unexpected size while reading registry value %s",
+ valuename);
+ goto done;
+ }
+
+have_data:
+ switch (type) {
+ case REG_DWORD:
+ asprintf(&ret_string, "%d", *((DWORD *) pbuffer));
+ break;
+
+ case REG_SZ:
+ {
+ char * str = (char *) pbuffer;
+
+ if (str[cb_data - 1] != '\0') {
+ if (cb_data < cb_alloc)
+ str[cb_data] = '\0';
+ else
+ break;
+ }
+
+ if (pbuffer != static_buffer) {
+ ret_string = (char *) pbuffer;
+ pbuffer = NULL;
+ } else {
+ ret_string = strdup((char *) pbuffer);
+ }
+ }
+ break;
+
+ case REG_EXPAND_SZ:
+ {
+ char *str = (char *) pbuffer;
+ char expsz[32768]; /* Size of output buffer for
+ * ExpandEnvironmentStrings() is
+ * limited to 32K. */
+
+ if (str[cb_data - 1] != '\0') {
+ if (cb_data < cb_alloc)
+ str[cb_data] = '\0';
+ else
+ break;
+ }
+
+ if (ExpandEnvironmentStrings(str, expsz, sizeof(expsz)/sizeof(char)) != 0) {
+ ret_string = strdup(expsz);
+ } else {
+ if (context)
+ heim_set_error_message(context, 0,
+ "Overflow while expanding environment strings "
+ "for registry value %s", valuename);
+ }
+ }
+ break;
+
+ case REG_MULTI_SZ:
+ {
+ char * str = (char *) pbuffer;
+ char * iter;
+
+ str[cb_alloc - 1] = '\0';
+ str[cb_alloc - 2] = '\0';
+
+ for (iter = str; *iter;) {
+ size_t len = strlen(iter);
+
+ iter += len;
+ if (iter[1] != '\0')
+ *iter++ = *separator;
+ else
+ break;
+ }
+
+ if (pbuffer != static_buffer) {
+ ret_string = str;
+ pbuffer = NULL;
+ } else {
+ ret_string = strdup(str);
+ }
+ }
+ break;
+
+ default:
+ if (context)
+ heim_set_error_message(context, 0,
+ "Unexpected type while reading registry value %s",
+ valuename);
+ }
+
+done:
+ if (pbuffer != static_buffer && pbuffer != NULL)
+ free(pbuffer);
+
+ return ret_string;
+}
+
+/**
+ * Parse a registry value as a configuration value
+ *
+ * @see parse_reg_value_as_string()
+ */
+static heim_error_code
+parse_reg_value(heim_context context,
+ HKEY key, const char * valuename,
+ DWORD type, DWORD cbdata, heim_config_section ** parent)
+{
+ char *reg_string = NULL;
+ heim_config_section *value;
+ heim_error_code code = 0;
+
+ reg_string = heim_parse_reg_value_as_string(context, key, valuename, type, cbdata);
+
+ if (reg_string == NULL)
+ return HEIM_ERR_CONFIG_BADFORMAT;
+
+ value = heim_config_get_entry(parent, valuename, heim_config_string);
+ if (value == NULL) {
+ code = ENOMEM;
+ goto done;
+ }
+
+ if (value->u.string != NULL)
+ free(value->u.string);
+
+ value->u.string = reg_string;
+ reg_string = NULL;
+
+done:
+ if (reg_string != NULL)
+ free(reg_string);
+
+ return code;
+}
+
+static heim_error_code
+parse_reg_values(heim_context context,
+ HKEY key,
+ heim_config_section ** parent)
+{
+ DWORD index;
+ LONG rcode;
+
+ for (index = 0; ; index ++) {
+ char name[16385];
+ DWORD cch = sizeof(name)/sizeof(name[0]);
+ DWORD type;
+ DWORD cbdata = 0;
+ heim_error_code code;
+
+ rcode = RegEnumValue(key, index, name, &cch, NULL,
+ &type, NULL, &cbdata);
+ if (rcode != ERROR_SUCCESS)
+ break;
+
+ if (cbdata == 0)
+ continue;
+
+ code = parse_reg_value(context, key, name, type, cbdata, parent);
+ if (code != 0)
+ return code;
+ }
+
+ return 0;
+}
+
+static heim_error_code
+parse_reg_subkeys(heim_context context,
+ HKEY key,
+ heim_config_section ** parent)
+{
+ DWORD index;
+ LONG rcode;
+
+ for (index = 0; ; index ++) {
+ HKEY subkey = NULL;
+ char name[256];
+ DWORD cch = sizeof(name)/sizeof(name[0]);
+ heim_config_section *section = NULL;
+ heim_error_code code;
+
+ rcode = RegEnumKeyEx(key, index, name, &cch, NULL, NULL, NULL, NULL);
+ if (rcode != ERROR_SUCCESS)
+ break;
+
+ rcode = RegOpenKeyEx(key, name, 0, KEY_READ, &subkey);
+ if (rcode != ERROR_SUCCESS)
+ continue;
+
+ section = heim_config_get_entry(parent, name, heim_config_list);
+ if (section == NULL) {
+ RegCloseKey(subkey);
+ return ENOMEM;
+ }
+
+ code = parse_reg_values(context, subkey, &section->u.list);
+ if (code) {
+ RegCloseKey(subkey);
+ return code;
+ }
+
+ code = parse_reg_subkeys(context, subkey, &section->u.list);
+ if (code) {
+ RegCloseKey(subkey);
+ return code;
+ }
+
+ RegCloseKey(subkey);
+ }
+
+ return 0;
+}
+
+static heim_error_code
+parse_reg_root(heim_context context,
+ HKEY key,
+ heim_config_section ** parent)
+{
+ heim_config_section *libdefaults = NULL;
+ heim_error_code code = 0;
+
+ libdefaults = heim_config_get_entry(parent, "libdefaults", heim_config_list);
+ if (libdefaults == NULL)
+ return heim_enomem(context);
+
+ code = parse_reg_values(context, key, &libdefaults->u.list);
+ if (code)
+ return code;
+
+ return parse_reg_subkeys(context, key, parent);
+}
+
+static heim_error_code
+load_config_from_regpath(heim_context context,
+ HKEY hk_root,
+ const char* key_path,
+ heim_config_section ** res)
+{
+ HKEY key = NULL;
+ LONG rcode;
+ heim_error_code code = 0;
+
+ rcode = RegOpenKeyEx(hk_root, key_path, 0, KEY_READ, &key);
+ if (rcode == ERROR_SUCCESS) {
+ code = parse_reg_root(context, key, res);
+ RegCloseKey(key);
+ key = NULL;
+ }
+
+ return code;
+}
+
+/**
+ * Load configuration from registry
+ *
+ * The registry keys 'HKCU\Software\Heimdal' and
+ * 'HKLM\Software\Heimdal' are treated as krb5.conf files. Each
+ * registry key corresponds to a configuration section (or bound list)
+ * and each value in a registry key is treated as a bound value. The
+ * set of values that are directly under the Heimdal key are treated
+ * as if they were defined in the [libdefaults] section.
+ *
+ * @see parse_reg_value() for details about how each type of value is handled.
+ */
+heim_error_code
+heim_load_config_from_registry(heim_context context,
+ const char *path0,
+ const char *path1,
+ heim_config_section **res)
+{
+ heim_error_code code;
+
+ if (!path0 && !path1)
+ return EINVAL;
+
+ if (path0) {
+ code = load_config_from_regpath(context, HKEY_LOCAL_MACHINE,
+ path0, res);
+ if (code)
+ return code;
+ }
+
+ if (path1) {
+ code = load_config_from_regpath(context, HKEY_LOCAL_MACHINE,
+ path1, res);
+ if (code)
+ return code;
+ }
+
+ if (path0) {
+ code = load_config_from_regpath(context, HKEY_CURRENT_USER,
+ path0, res);
+ if (code)
+ return code;
+ }
+
+ if (path0) {
+ code = load_config_from_regpath(context, HKEY_CURRENT_USER,
+ path1, res);
+ if (code)
+ return code;
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/base/context.c b/third_party/heimdal/lib/base/context.c
new file mode 100644
index 0000000..fb9b442
--- /dev/null
+++ b/third_party/heimdal/lib/base/context.c
@@ -0,0 +1,394 @@
+/*
+ * Copyright (c) 2020 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+
+#undef __attribute__
+#define __attribute__(X)
+
+heim_context
+heim_context_init(void)
+{
+ heim_context context;
+
+ if ((context = calloc(1, sizeof(*context))) == NULL)
+ return NULL;
+
+ context->homedir_access = !issuid();
+ context->log_utc = 1;
+ context->error_string = NULL;
+ context->debug_dest = NULL;
+ context->warn_dest = NULL;
+ context->log_dest = NULL;
+ context->time_fmt = NULL;
+ context->et_list = NULL;
+ return context;
+}
+
+void
+heim_context_free(heim_context *contextp)
+{
+ heim_context context = *contextp;
+
+ *contextp = NULL;
+ if (!context)
+ return;
+ heim_closelog(context, context->debug_dest);
+ heim_closelog(context, context->warn_dest);
+ heim_closelog(context, context->log_dest);
+ free_error_table(context->et_list);
+ free(context->time_fmt);
+ free(context->error_string);
+ free(context);
+}
+
+heim_error_code
+heim_add_et_list(heim_context context, void (*func)(struct et_list **))
+{
+ (*func)(&context->et_list);
+ return 0;
+}
+
+heim_error_code
+heim_context_set_time_fmt(heim_context context, const char *fmt)
+{
+ char *s;
+
+ if (fmt == NULL) {
+ free(context->time_fmt);
+ return 0;
+ }
+ if ((s = strdup(fmt)) == NULL)
+ return heim_enomem(context);
+ free(context->time_fmt);
+ context->time_fmt = s;
+ return 0;
+}
+
+const char *
+heim_context_get_time_fmt(heim_context context)
+{
+ return context->time_fmt ? context->time_fmt : "%Y-%m-%dT%H:%M:%S";
+}
+
+unsigned int
+heim_context_set_log_utc(heim_context context, unsigned int log_utc)
+{
+ unsigned int old = context->log_utc;
+
+ context->log_utc = log_utc ? 1 : 0;
+ return old;
+}
+
+int
+heim_context_get_log_utc(heim_context context)
+{
+ return context->log_utc;
+}
+
+unsigned int
+heim_context_set_homedir_access(heim_context context, unsigned int homedir_access)
+{
+ unsigned int old = context->homedir_access;
+
+ context->homedir_access = homedir_access ? 1 : 0;
+ return old;
+}
+
+unsigned int
+heim_context_get_homedir_access(heim_context context)
+{
+ return context->homedir_access;
+}
+
+heim_error_code
+heim_enomem(heim_context context)
+{
+ heim_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+}
+
+heim_log_facility *
+heim_get_log_dest(heim_context context)
+{
+ return context->log_dest;
+}
+
+heim_log_facility *
+heim_get_warn_dest(heim_context context)
+{
+ return context->warn_dest;
+}
+
+heim_log_facility *
+heim_get_debug_dest(heim_context context)
+{
+ return context->debug_dest;
+}
+
+heim_error_code
+heim_set_log_dest(heim_context context, heim_log_facility *fac)
+{
+ context->log_dest = fac;
+ return 0;
+}
+
+heim_error_code
+heim_set_warn_dest(heim_context context, heim_log_facility *fac)
+{
+ context->warn_dest = fac;
+ return 0;
+}
+
+heim_error_code
+heim_set_debug_dest(heim_context context, heim_log_facility *fac)
+{
+ context->debug_dest = fac;
+ return 0;
+}
+
+#ifndef PATH_SEP
+# define PATH_SEP ":"
+#endif
+
+static heim_error_code
+add_file(char ***pfilenames, int *len, char *file)
+{
+ char **pp = *pfilenames;
+ int i;
+
+ for(i = 0; i < *len; i++) {
+ if(strcmp(pp[i], file) == 0) {
+ free(file);
+ return 0;
+ }
+ }
+
+ pp = realloc(*pfilenames, (*len + 2) * sizeof(*pp));
+ if (pp == NULL) {
+ free(file);
+ return ENOMEM;
+ }
+
+ pp[*len] = file;
+ pp[*len + 1] = NULL;
+ *pfilenames = pp;
+ *len += 1;
+ return 0;
+}
+
+#ifdef WIN32
+static char *
+get_default_config_config_files_from_registry(const char *envvar)
+{
+ static const char *KeyName = "Software\\Heimdal"; /* XXX #define this */
+ const char *ValueName;
+ char *config_file = NULL;
+ LONG rcode;
+ HKEY key;
+
+ if (stricmp(envvar, "KRB5_CONFIG") == 0)
+ ValueName = "config";
+ else
+ ValueName = envvar;
+
+ rcode = RegOpenKeyEx(HKEY_CURRENT_USER, KeyName, 0, KEY_READ, &key);
+ if (rcode == ERROR_SUCCESS) {
+ config_file = heim_parse_reg_value_as_multi_string(NULL, key, ValueName,
+ REG_NONE, 0, PATH_SEP);
+ RegCloseKey(key);
+ }
+
+ if (config_file)
+ return config_file;
+
+ rcode = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KeyName, 0, KEY_READ, &key);
+ if (rcode == ERROR_SUCCESS) {
+ config_file = heim_parse_reg_value_as_multi_string(NULL, key, ValueName,
+ REG_NONE, 0, PATH_SEP);
+ RegCloseKey(key);
+ }
+
+ return config_file;
+}
+#endif
+
+heim_error_code
+heim_prepend_config_files(const char *filelist,
+ char **pq,
+ char ***ret_pp)
+{
+ heim_error_code ret;
+ const char *p, *q;
+ char **pp;
+ int len;
+ char *fn;
+
+ pp = NULL;
+
+ len = 0;
+ p = filelist;
+ while(1) {
+ ssize_t l;
+ q = p;
+ l = strsep_copy(&q, PATH_SEP, NULL, 0);
+ if(l == -1)
+ break;
+ fn = malloc(l + 1);
+ if(fn == NULL) {
+ heim_free_config_files(pp);
+ return ENOMEM;
+ }
+ (void) strsep_copy(&p, PATH_SEP, fn, l + 1);
+ ret = add_file(&pp, &len, fn);
+ if (ret) {
+ heim_free_config_files(pp);
+ return ret;
+ }
+ }
+
+ if (pq != NULL) {
+ int i;
+
+ for (i = 0; pq[i] != NULL; i++) {
+ fn = strdup(pq[i]);
+ if (fn == NULL) {
+ heim_free_config_files(pp);
+ return ENOMEM;
+ }
+ ret = add_file(&pp, &len, fn);
+ if (ret) {
+ heim_free_config_files(pp);
+ return ret;
+ }
+ }
+ }
+
+ *ret_pp = pp;
+ return 0;
+}
+
+heim_error_code
+heim_prepend_config_files_default(const char *prepend,
+ const char *def,
+ const char *envvar,
+ char ***pfilenames)
+{
+ heim_error_code ret;
+ char **defpp, **pp = NULL;
+
+ ret = heim_get_default_config_files(def, envvar, &defpp);
+ if (ret)
+ return ret;
+
+ ret = heim_prepend_config_files(prepend, defpp, &pp);
+ heim_free_config_files(defpp);
+ if (ret) {
+ return ret;
+ }
+ *pfilenames = pp;
+ return 0;
+}
+
+heim_error_code
+heim_get_default_config_files(const char *def,
+ const char *envvar,
+ char ***pfilenames)
+{
+ const char *files = NULL;
+
+ files = secure_getenv(envvar);
+
+#ifdef _WIN32
+ if (files == NULL) {
+ char * reg_files;
+ reg_files = get_default_config_config_files_from_registry(envvar);
+ if (reg_files != NULL) {
+ heim_error_code code;
+
+ code = heim_prepend_config_files(reg_files, NULL, pfilenames);
+ free(reg_files);
+
+ return code;
+ }
+ }
+#endif
+
+ if (files == NULL)
+ files = def;
+ return heim_prepend_config_files(files, NULL, pfilenames);
+}
+
+#ifdef _WIN32
+#define REGPATH_KERBEROS "SOFTWARE\\Kerberos"
+#define REGPATH_HEIMDAL "SOFTWARE\\Heimdal"
+#endif
+
+heim_error_code
+heim_set_config_files(heim_context context, char **filenames,
+ heim_config_binding **res)
+{
+ heim_error_code ret = 0;
+
+ *res = NULL;
+ while (filenames != NULL && *filenames != NULL && **filenames != '\0') {
+ ret = heim_config_parse_file_multi(context, *filenames, res);
+ if (ret != 0 && ret != ENOENT && ret != EACCES && ret != EPERM
+ && ret != HEIM_ERR_CONFIG_BADFORMAT) {
+ heim_config_file_free(context, *res);
+ *res = NULL;
+ return ret;
+ }
+ filenames++;
+ }
+
+#ifdef _WIN32
+ /*
+ * We always ignored errors from loading from the registry, so we still do.
+ */
+ heim_load_config_from_registry(context, REGPATH_KERBEROS,
+ REGPATH_HEIMDAL, res);
+
+#endif
+ return 0;
+}
+
+void
+heim_free_config_files(char **filenames)
+{
+ char **p;
+
+ for (p = filenames; p && *p != NULL; p++)
+ free(*p);
+ free(filenames);
+}
diff --git a/third_party/heimdal/lib/base/data.c b/third_party/heimdal/lib/base/data.c
new file mode 100644
index 0000000..cefdde0
--- /dev/null
+++ b/third_party/heimdal/lib/base/data.c
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) 2011 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+#include <string.h>
+
+static void HEIM_CALLCONV
+data_dealloc(void *ptr)
+{
+ heim_data_t d = ptr;
+ heim_octet_string *os = (heim_octet_string *)d;
+ heim_data_free_f_t *deallocp;
+ heim_data_free_f_t dealloc;
+
+ if (os->data == NULL)
+ return;
+
+ /* Possible string ref */
+ deallocp = _heim_get_isaextra(os, 0);
+ dealloc = *deallocp;
+ if (dealloc != NULL)
+ dealloc(os->data);
+}
+
+static int
+data_cmp(void *a, void *b)
+{
+ heim_octet_string *osa = a, *osb = b;
+ if (osa->length != osb->length)
+ return osa->length - osb->length;
+ return memcmp(osa->data, osb->data, osa->length);
+}
+
+static uintptr_t
+data_hash(void *ptr)
+{
+ heim_octet_string *os = ptr;
+ const unsigned char *s = os->data;
+
+ if (os->length < 4)
+ return os->length;
+
+ return ((unsigned long)s[os->length - 1] << 24)
+ | (s[os->length - 2] << 16) | (s[1] << 8) | s[0];
+}
+
+struct heim_type_data _heim_data_object = {
+ HEIM_TID_DATA,
+ "data-object",
+ NULL,
+ data_dealloc,
+ NULL,
+ data_cmp,
+ data_hash,
+ NULL
+};
+
+/**
+ * Create a data object
+ *
+ * @param string the string to create, must be an utf8 string
+ *
+ * @return string object
+ */
+
+heim_data_t
+heim_data_create(const void *data, size_t length)
+{
+ heim_octet_string *os;
+
+ os = _heim_alloc_object(&_heim_data_object, sizeof(*os) + length);
+ if (os) {
+ os->data = (uint8_t *)os + sizeof(*os);
+ os->length = length;
+ memcpy(os->data, data, length);
+ }
+ return (heim_data_t)os;
+}
+
+heim_data_t
+heim_data_ref_create(const void *data, size_t length,
+ heim_data_free_f_t dealloc)
+{
+ heim_octet_string *os;
+ heim_data_free_f_t *deallocp;
+
+ os = _heim_alloc_object(&_heim_data_object, sizeof(*os) + length);
+ if (os) {
+ os->data = (void *)data;
+ os->length = length;
+ deallocp = _heim_get_isaextra(os, 0);
+ *deallocp = dealloc;
+ }
+ return (heim_data_t)os;
+}
+
+
+/**
+ * Return the type ID of data objects
+ *
+ * @return type id of data objects
+ */
+
+heim_tid_t
+heim_data_get_type_id(void)
+{
+ return HEIM_TID_DATA;
+}
+
+/**
+ * Get the data value of the content.
+ *
+ * @param data the data object to get the value from
+ *
+ * @return a heim_octet_string
+ */
+
+const heim_octet_string *
+heim_data_get_data(heim_data_t data)
+{
+ /* Note that this works for data and data_ref objects */
+ return (const heim_octet_string *)data;
+}
+
+const void *
+heim_data_get_ptr(heim_data_t data)
+{
+ /* Note that this works for data and data_ref objects */
+ return ((const heim_octet_string *)data)->data;
+}
+
+size_t heim_data_get_length(heim_data_t data)
+{
+ /* Note that this works for data and data_ref objects */
+ return ((const heim_octet_string *)data)->length;
+}
diff --git a/third_party/heimdal/lib/base/db.c b/third_party/heimdal/lib/base/db.c
new file mode 100644
index 0000000..b206ff6
--- /dev/null
+++ b/third_party/heimdal/lib/base/db.c
@@ -0,0 +1,1721 @@
+/*
+ * Copyright (c) 2011, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This is a pluggable simple DB abstraction, with a simple get/set/
+ * delete key/value pair interface.
+ *
+ * Plugins may provide any of the following optional features:
+ *
+ * - tables -- multiple attribute/value tables in one DB
+ * - locking
+ * - transactions (i.e., allow any heim_object_t as key or value)
+ * - transcoding of values
+ *
+ * Stackable plugins that provide missing optional features are
+ * possible.
+ *
+ * Any plugin that provides locking will also provide transactions, but
+ * those transactions will not be atomic in the face of failures (a
+ * memory-based rollback log is used).
+ */
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef WIN32
+#include <io.h>
+#else
+#include <sys/file.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <fcntl.h>
+
+#include "baselocl.h"
+#include <base64.h>
+
+#define HEIM_ENOMEM(ep) \
+ (((ep) && !*(ep)) ? \
+ heim_error_get_code((*(ep) = heim_error_create_enomem())) : ENOMEM)
+
+#define HEIM_ERROR_HELPER(ep, ec, args) \
+ (((ep) && !*(ep)) ? \
+ heim_error_get_code((*(ep) = heim_error_create args)) : (ec))
+
+#define HEIM_ERROR(ep, ec, args) \
+ (ec == ENOMEM) ? HEIM_ENOMEM(ep) : HEIM_ERROR_HELPER(ep, ec, args);
+
+static heim_string_t to_base64(heim_data_t, heim_error_t *);
+static heim_data_t from_base64(heim_string_t, heim_error_t *);
+
+static int open_file(const char *, int , int, int *, heim_error_t *);
+static int read_json(const char *, heim_object_t *, heim_error_t *);
+static struct heim_db_type json_dbt;
+
+static void HEIM_CALLCONV db_dealloc(void *ptr);
+
+struct heim_type_data db_object = {
+ HEIM_TID_DB,
+ "db-object",
+ NULL,
+ db_dealloc,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+
+static heim_base_once_t db_plugin_init_once = HEIM_BASE_ONCE_INIT;
+
+static heim_dict_t db_plugins;
+
+typedef struct db_plugin {
+ heim_string_t name;
+ heim_db_plug_open_f_t openf;
+ heim_db_plug_clone_f_t clonef;
+ heim_db_plug_close_f_t closef;
+ heim_db_plug_lock_f_t lockf;
+ heim_db_plug_unlock_f_t unlockf;
+ heim_db_plug_sync_f_t syncf;
+ heim_db_plug_begin_f_t beginf;
+ heim_db_plug_commit_f_t commitf;
+ heim_db_plug_rollback_f_t rollbackf;
+ heim_db_plug_copy_value_f_t copyf;
+ heim_db_plug_set_value_f_t setf;
+ heim_db_plug_del_key_f_t delf;
+ heim_db_plug_iter_f_t iterf;
+ void *data;
+} db_plugin_desc, *db_plugin;
+
+struct heim_db_data {
+ db_plugin plug;
+ heim_string_t dbtype;
+ heim_string_t dbname;
+ heim_dict_t options;
+ void *db_data;
+ heim_data_t to_release;
+ heim_error_t error;
+ int ret;
+ unsigned int in_transaction:1;
+ unsigned int ro:1;
+ unsigned int ro_tx:1;
+ heim_dict_t set_keys;
+ heim_dict_t del_keys;
+ heim_string_t current_table;
+};
+
+static int
+db_do_log_actions(heim_db_t db, heim_error_t *error);
+static int
+db_replay_log(heim_db_t db, heim_error_t *error);
+
+static HEIMDAL_MUTEX db_type_mutex = HEIMDAL_MUTEX_INITIALIZER;
+
+static void
+db_init_plugins_once(void *arg)
+{
+ db_plugins = heim_retain(arg);
+}
+
+static void HEIM_CALLCONV
+plugin_dealloc(void *arg)
+{
+ db_plugin plug = arg;
+
+ heim_release(plug->name);
+}
+
+/** heim_db_register
+ * @brief Registers a DB type for use with heim_db_create().
+ *
+ * @param dbtype Name of DB type
+ * @param data Private data argument to the dbtype's openf method
+ * @param plugin Structure with DB type methods (function pointers)
+ *
+ * Backends that provide begin/commit/rollback methods must provide ACID
+ * semantics.
+ *
+ * The registered DB type will have ACID semantics for backends that do
+ * not provide begin/commit/rollback methods but do provide lock/unlock
+ * and rdjournal/wrjournal methods (using a replay log journalling
+ * scheme).
+ *
+ * If the registered DB type does not natively provide read vs. write
+ * transaction isolation but does provide a lock method then the DB will
+ * provide read/write transaction isolation.
+ *
+ * @return ENOMEM on failure, else 0.
+ *
+ * @addtogroup heimbase
+ */
+int
+heim_db_register(const char *dbtype,
+ void *data,
+ struct heim_db_type *plugin)
+{
+ heim_dict_t plugins;
+ heim_string_t s;
+ db_plugin plug, plug2;
+ int ret = 0;
+
+ if ((plugin->beginf != NULL && plugin->commitf == NULL) ||
+ (plugin->beginf != NULL && plugin->rollbackf == NULL) ||
+ (plugin->lockf != NULL && plugin->unlockf == NULL) ||
+ plugin->copyf == NULL)
+ heim_abort("Invalid DB plugin; make sure methods are paired");
+
+ /* Initialize */
+ plugins = heim_dict_create(11);
+ if (plugins == NULL)
+ return ENOMEM;
+ heim_base_once_f(&db_plugin_init_once, plugins, db_init_plugins_once);
+ heim_release(plugins);
+ heim_assert(db_plugins != NULL, "heim_db plugin table initialized");
+
+ s = heim_string_create(dbtype);
+ if (s == NULL)
+ return ENOMEM;
+
+ plug = heim_alloc(sizeof (*plug), "db_plug", plugin_dealloc);
+ if (plug == NULL) {
+ heim_release(s);
+ return ENOMEM;
+ }
+
+ plug->name = heim_retain(s);
+ plug->openf = plugin->openf;
+ plug->clonef = plugin->clonef;
+ plug->closef = plugin->closef;
+ plug->lockf = plugin->lockf;
+ plug->unlockf = plugin->unlockf;
+ plug->syncf = plugin->syncf;
+ plug->beginf = plugin->beginf;
+ plug->commitf = plugin->commitf;
+ plug->rollbackf = plugin->rollbackf;
+ plug->copyf = plugin->copyf;
+ plug->setf = plugin->setf;
+ plug->delf = plugin->delf;
+ plug->iterf = plugin->iterf;
+ plug->data = data;
+
+ HEIMDAL_MUTEX_lock(&db_type_mutex);
+ plug2 = heim_dict_get_value(db_plugins, s);
+ if (plug2 == NULL)
+ ret = heim_dict_set_value(db_plugins, s, plug);
+ HEIMDAL_MUTEX_unlock(&db_type_mutex);
+ heim_release(plug);
+ heim_release(s);
+
+ return ret;
+}
+
+static void HEIM_CALLCONV
+db_dealloc(void *arg)
+{
+ heim_db_t db = arg;
+ heim_assert(!db->in_transaction,
+ "rollback or commit heim_db_t before releasing it");
+ if (db->db_data)
+ (void) db->plug->closef(db->db_data, NULL);
+ heim_release(db->to_release);
+ heim_release(db->dbtype);
+ heim_release(db->dbname);
+ heim_release(db->options);
+ heim_release(db->set_keys);
+ heim_release(db->del_keys);
+ heim_release(db->error);
+}
+
+struct dbtype_iter {
+ heim_db_t db;
+ const char *dbname;
+ heim_dict_t options;
+ heim_error_t *error;
+};
+
+/*
+ * Helper to create a DB handle with the first registered DB type that
+ * can open the given DB. This is useful when the app doesn't know the
+ * DB type a priori. This assumes that DB types can "taste" DBs, either
+ * from the filename extension or from the actual file contents.
+ */
+static void
+dbtype_iter2create_f(heim_object_t dbtype, heim_object_t junk, void *arg)
+{
+ struct dbtype_iter *iter_ctx = arg;
+
+ if (iter_ctx->db != NULL)
+ return;
+ iter_ctx->db = heim_db_create(heim_string_get_utf8(dbtype),
+ iter_ctx->dbname, iter_ctx->options,
+ iter_ctx->error);
+}
+
+/**
+ * Open a database of the given dbtype.
+ *
+ * Database type names can be composed of one or more pseudo-DB types
+ * and one concrete DB type joined with a '+' between each. For
+ * example: "transaction+bdb" might be a Berkeley DB with a layer above
+ * that provides transactions.
+ *
+ * Options may be provided via a dict (an associative array). Existing
+ * options include:
+ *
+ * - "create", with any value (create if DB doesn't exist)
+ * - "exclusive", with any value (exclusive create)
+ * - "truncate", with any value (truncate the DB)
+ * - "read-only", with any value (disallow writes)
+ * - "sync", with any value (make transactions durable)
+ * - "journal-name", with a string value naming a journal file name
+ *
+ * @param dbtype Name of DB type
+ * @param dbname Name of DB (likely a file path)
+ * @param options Options dict
+ * @param db Output open DB handle
+ * @param error Output error object
+ *
+ * @return a DB handle
+ *
+ * @addtogroup heimbase
+ */
+heim_db_t
+heim_db_create(const char *dbtype, const char *dbname,
+ heim_dict_t options, heim_error_t *error)
+{
+ heim_string_t s;
+ char *p;
+ db_plugin plug;
+ heim_db_t db;
+ int ret = 0;
+
+ if (options == NULL) {
+ options = heim_dict_create(11);
+ if (options == NULL) {
+ if (error)
+ *error = heim_error_create_enomem();
+ return NULL;
+ }
+ } else {
+ (void) heim_retain(options);
+ }
+
+ if (db_plugins == NULL) {
+ heim_release(options);
+ return NULL;
+ }
+
+ if (dbtype == NULL || *dbtype == '\0') {
+ struct dbtype_iter iter_ctx = { NULL, dbname, options, error};
+
+ /* Try all dbtypes */
+ heim_dict_iterate_f(db_plugins, &iter_ctx, dbtype_iter2create_f);
+ heim_release(options);
+ return iter_ctx.db;
+ } else if (strstr(dbtype, "json")) {
+ (void) heim_db_register(dbtype, NULL, &json_dbt);
+ }
+
+ /*
+ * Allow for dbtypes that are composed from pseudo-dbtypes chained
+ * to a real DB type with '+'. For example a pseudo-dbtype might
+ * add locking, transactions, transcoding of values, ...
+ */
+ p = strchr(dbtype, '+');
+ if (p != NULL)
+ s = heim_string_create_with_bytes(dbtype, p - dbtype);
+ else
+ s = heim_string_create(dbtype);
+ if (s == NULL) {
+ heim_release(options);
+ return NULL;
+ }
+
+ HEIMDAL_MUTEX_lock(&db_type_mutex);
+ plug = heim_dict_get_value(db_plugins, s);
+ HEIMDAL_MUTEX_unlock(&db_type_mutex);
+ heim_release(s);
+ if (plug == NULL) {
+ if (error)
+ *error = heim_error_create(ENOENT,
+ N_("Heimdal DB plugin not found: %s", ""),
+ dbtype);
+ heim_release(options);
+ return NULL;
+ }
+
+ db = _heim_alloc_object(&db_object, sizeof(*db));
+ if (db == NULL) {
+ heim_release(options);
+ return NULL;
+ }
+
+ db->in_transaction = 0;
+ db->ro_tx = 0;
+ db->set_keys = NULL;
+ db->del_keys = NULL;
+ db->plug = plug;
+ db->options = options;
+
+ ret = plug->openf(plug->data, dbtype, dbname, options, &db->db_data, error);
+ if (ret) {
+ heim_release(db);
+ if (error && *error == NULL)
+ *error = heim_error_create(ENOENT,
+ N_("Heimdal DB could not be opened: %s", ""),
+ dbname);
+ return NULL;
+ }
+
+ ret = db_replay_log(db, error);
+ if (ret) {
+ heim_release(db);
+ return NULL;
+ }
+
+ if (plug->clonef == NULL) {
+ db->dbtype = heim_string_create(dbtype);
+ db->dbname = heim_string_create(dbname);
+
+ if (!db->dbtype || ! db->dbname) {
+ heim_release(db);
+ if (error)
+ *error = heim_error_create_enomem();
+ return NULL;
+ }
+ }
+
+ return db;
+}
+
+/**
+ * Clone (duplicate) an open DB handle.
+ *
+ * This is useful for multi-threaded applications. Applications must
+ * synchronize access to any given DB handle.
+ *
+ * Returns EBUSY if there is an open transaction for the input db.
+ *
+ * @param db Open DB handle
+ * @param error Output error object
+ *
+ * @return a DB handle
+ *
+ * @addtogroup heimbase
+ */
+heim_db_t
+heim_db_clone(heim_db_t db, heim_error_t *error)
+{
+ heim_db_t result;
+ int ret;
+
+ if (heim_get_tid(db) != HEIM_TID_DB)
+ heim_abort("Expected a database");
+ if (db->in_transaction)
+ heim_abort("DB handle is busy");
+
+ if (db->plug->clonef == NULL) {
+ return heim_db_create(heim_string_get_utf8(db->dbtype),
+ heim_string_get_utf8(db->dbname),
+ db->options, error);
+ }
+
+ result = _heim_alloc_object(&db_object, sizeof(*result));
+ if (result == NULL) {
+ if (error)
+ *error = heim_error_create_enomem();
+ return NULL;
+ }
+
+ result->set_keys = NULL;
+ result->del_keys = NULL;
+ ret = db->plug->clonef(db->db_data, &result->db_data, error);
+ if (ret) {
+ heim_release(result);
+ if (error && !*error)
+ *error = heim_error_create(ENOENT,
+ N_("Could not re-open DB while cloning", ""));
+ return NULL;
+ }
+ db->db_data = NULL;
+ return result;
+}
+
+/**
+ * Open a transaction on the given db.
+ *
+ * @param db Open DB handle
+ * @param error Output error object
+ *
+ * @return 0 on success, system error otherwise
+ *
+ * @addtogroup heimbase
+ */
+int
+heim_db_begin(heim_db_t db, int read_only, heim_error_t *error)
+{
+ int ret;
+
+ if (heim_get_tid(db) != HEIM_TID_DB)
+ return EINVAL;
+
+ if (db->in_transaction && (read_only || !db->ro_tx || (!read_only && !db->ro_tx)))
+ heim_abort("DB already in transaction");
+
+ if (db->plug->setf == NULL || db->plug->delf == NULL)
+ return EINVAL;
+
+ if (db->plug->beginf) {
+ ret = db->plug->beginf(db->db_data, read_only, error);
+ if (ret)
+ return ret;
+ } else if (!db->in_transaction) {
+ /* Try to emulate transactions */
+
+ if (db->plug->lockf == NULL)
+ return EINVAL; /* can't lock? -> no transactions */
+
+ /* Assume unlock provides sync/durability */
+ ret = db->plug->lockf(db->db_data, read_only, error);
+ if (ret)
+ return ret;
+
+ ret = db_replay_log(db, error);
+ if (ret) {
+ ret = db->plug->unlockf(db->db_data, error);
+ return ret;
+ }
+
+ db->set_keys = heim_dict_create(11);
+ if (db->set_keys == NULL)
+ return ENOMEM;
+ db->del_keys = heim_dict_create(11);
+ if (db->del_keys == NULL) {
+ heim_release(db->set_keys);
+ db->set_keys = NULL;
+ return ENOMEM;
+ }
+ } else {
+ heim_assert(read_only == 0, "Internal error");
+ ret = db->plug->lockf(db->db_data, 0, error);
+ if (ret)
+ return ret;
+ }
+ db->in_transaction = 1;
+ db->ro_tx = !!read_only;
+ return 0;
+}
+
+/**
+ * Commit an open transaction on the given db.
+ *
+ * @param db Open DB handle
+ * @param error Output error object
+ *
+ * @return 0 on success, system error otherwise
+ *
+ * @addtogroup heimbase
+ */
+int
+heim_db_commit(heim_db_t db, heim_error_t *error)
+{
+ int ret, ret2;
+ heim_string_t journal_fname = NULL;
+
+ if (heim_get_tid(db) != HEIM_TID_DB)
+ return EINVAL;
+ if (!db->in_transaction)
+ return 0;
+ if (db->plug->commitf == NULL && db->plug->lockf == NULL)
+ return EINVAL;
+
+ if (db->plug->commitf != NULL) {
+ ret = db->plug->commitf(db->db_data, error);
+ if (ret)
+ (void) db->plug->rollbackf(db->db_data, error);
+
+ db->in_transaction = 0;
+ db->ro_tx = 0;
+ return ret;
+ }
+
+ if (db->ro_tx) {
+ ret = 0;
+ goto done;
+ }
+
+ if (db->options)
+ journal_fname = heim_dict_get_value(db->options, HSTR("journal-filename"));
+
+ if (journal_fname != NULL) {
+ heim_array_t a;
+ heim_string_t journal_contents;
+ size_t len, bytes;
+ int save_errno;
+
+ /* Create contents for replay log */
+ ret = ENOMEM;
+ a = heim_array_create();
+ if (a == NULL)
+ goto err;
+ ret = heim_array_append_value(a, db->set_keys);
+ if (ret) {
+ heim_release(a);
+ goto err;
+ }
+ ret = heim_array_append_value(a, db->del_keys);
+ if (ret) {
+ heim_release(a);
+ goto err;
+ }
+ journal_contents = heim_json_copy_serialize(a, 0, error);
+ heim_release(a);
+
+ /* Write replay log */
+ if (journal_fname != NULL) {
+ int fd;
+
+ ret = open_file(heim_string_get_utf8(journal_fname), 1, 0, &fd, error);
+ if (ret) {
+ heim_release(journal_contents);
+ goto err;
+ }
+ len = strlen(heim_string_get_utf8(journal_contents));
+ bytes = write(fd, heim_string_get_utf8(journal_contents), len);
+ save_errno = errno;
+ heim_release(journal_contents);
+ ret = close(fd);
+ if (bytes != len) {
+ /* Truncate replay log */
+ (void) open_file(heim_string_get_utf8(journal_fname), 1, 0, NULL, error);
+ ret = save_errno;
+ goto err;
+ }
+ if (ret)
+ goto err;
+ }
+ }
+
+ /* Apply logged actions */
+ ret = db_do_log_actions(db, error);
+ if (ret)
+ return ret;
+
+ if (db->plug->syncf != NULL) {
+ /* fsync() or whatever */
+ ret = db->plug->syncf(db->db_data, error);
+ if (ret)
+ return ret;
+ }
+
+ /* Truncate replay log and we're done */
+ if (journal_fname != NULL) {
+ int fd;
+
+ ret2 = open_file(heim_string_get_utf8(journal_fname), 1, 0, &fd, error);
+ if (ret2 == 0)
+ (void) close(fd);
+ }
+
+ /*
+ * Clean up; if we failed to remore the replay log that's OK, we'll
+ * handle that again in heim_db_commit()
+ */
+done:
+ heim_release(db->set_keys);
+ heim_release(db->del_keys);
+ db->set_keys = NULL;
+ db->del_keys = NULL;
+ db->in_transaction = 0;
+ db->ro_tx = 0;
+
+ ret2 = db->plug->unlockf(db->db_data, error);
+ if (ret == 0)
+ ret = ret2;
+
+ return ret;
+
+err:
+ return HEIM_ERROR(error, ret,
+ (ret, N_("Error while committing transaction: %s", ""),
+ strerror(ret)));
+}
+
+/**
+ * Rollback an open transaction on the given db.
+ *
+ * @param db Open DB handle
+ * @param error Output error object
+ *
+ * @return 0 on success, system error otherwise
+ *
+ * @addtogroup heimbase
+ */
+int
+heim_db_rollback(heim_db_t db, heim_error_t *error)
+{
+ int ret = 0;
+
+ if (heim_get_tid(db) != HEIM_TID_DB)
+ return EINVAL;
+ if (!db->in_transaction)
+ return 0;
+
+ if (db->plug->rollbackf != NULL)
+ ret = db->plug->rollbackf(db->db_data, error);
+ else if (db->plug->unlockf != NULL)
+ ret = db->plug->unlockf(db->db_data, error);
+
+ heim_release(db->set_keys);
+ heim_release(db->del_keys);
+ db->set_keys = NULL;
+ db->del_keys = NULL;
+ db->in_transaction = 0;
+ db->ro_tx = 0;
+
+ return ret;
+}
+
+/**
+ * Get type ID of heim_db_t objects.
+ *
+ * @addtogroup heimbase
+ */
+heim_tid_t
+heim_db_get_type_id(void)
+{
+ return HEIM_TID_DB;
+}
+
+heim_data_t
+_heim_db_get_value(heim_db_t db, heim_string_t table, heim_data_t key,
+ heim_error_t *error)
+{
+ heim_release(db->to_release);
+ db->to_release = heim_db_copy_value(db, table, key, error);
+ return db->to_release;
+}
+
+/**
+ * Lookup a key's value in the DB.
+ *
+ * Returns 0 on success, -1 if the key does not exist in the DB, or a
+ * system error number on failure.
+ *
+ * @param db Open DB handle
+ * @param key Key
+ * @param error Output error object
+ *
+ * @return the value (retained), if there is one for the given key
+ *
+ * @addtogroup heimbase
+ */
+heim_data_t
+heim_db_copy_value(heim_db_t db, heim_string_t table, heim_data_t key,
+ heim_error_t *error)
+{
+ heim_object_t v;
+ heim_data_t result;
+
+ if (heim_get_tid(db) != HEIM_TID_DB)
+ return NULL;
+
+ if (error != NULL)
+ *error = NULL;
+
+ if (table == NULL)
+ table = HSTR("");
+
+ if (db->in_transaction) {
+ heim_string_t key64;
+
+ key64 = to_base64(key, error);
+ if (key64 == NULL) {
+ if (error)
+ *error = heim_error_create_enomem();
+ return NULL;
+ }
+
+ v = heim_path_copy(db->set_keys, error, table, key64, NULL);
+ if (v != NULL) {
+ heim_release(key64);
+ return v;
+ }
+ v = heim_path_copy(db->del_keys, error, table, key64, NULL); /* can't be NULL */
+ heim_release(key64);
+ if (v != NULL)
+ return NULL;
+ }
+
+ result = db->plug->copyf(db->db_data, table, key, error);
+
+ return result;
+}
+
+/**
+ * Set a key's value in the DB.
+ *
+ * @param db Open DB handle
+ * @param key Key
+ * @param value Value (if NULL the key will be deleted, but empty is OK)
+ * @param error Output error object
+ *
+ * @return 0 on success, system error otherwise
+ *
+ * @addtogroup heimbase
+ */
+int
+heim_db_set_value(heim_db_t db, heim_string_t table,
+ heim_data_t key, heim_data_t value, heim_error_t *error)
+{
+ heim_string_t key64 = NULL;
+ int ret;
+
+ if (error != NULL)
+ *error = NULL;
+
+ if (table == NULL)
+ table = HSTR("");
+
+ if (value == NULL)
+ /* Use heim_null_t instead of NULL */
+ return heim_db_delete_key(db, table, key, error);
+
+ if (heim_get_tid(db) != HEIM_TID_DB)
+ return EINVAL;
+
+ if (heim_get_tid(key) != HEIM_TID_DATA)
+ return HEIM_ERROR(error, EINVAL,
+ (EINVAL, N_("DB keys must be data", "")));
+
+ if (db->plug->setf == NULL)
+ return EBADF;
+
+ if (!db->in_transaction) {
+ ret = heim_db_begin(db, 0, error);
+ if (ret)
+ goto err;
+ heim_assert(db->in_transaction, "Internal error");
+ ret = heim_db_set_value(db, table, key, value, error);
+ if (ret) {
+ (void) heim_db_rollback(db, NULL);
+ return ret;
+ }
+ return heim_db_commit(db, error);
+ }
+
+ /* Transaction emulation */
+ heim_assert(db->set_keys != NULL, "Internal error");
+ key64 = to_base64(key, error);
+ if (key64 == NULL)
+ return HEIM_ENOMEM(error);
+
+ if (db->ro_tx) {
+ ret = heim_db_begin(db, 0, error);
+ if (ret)
+ goto err;
+ }
+ ret = heim_path_create(db->set_keys, 29, value, error, table, key64, NULL);
+ if (ret)
+ goto err;
+ heim_path_delete(db->del_keys, error, table, key64, NULL);
+ heim_release(key64);
+
+ return 0;
+
+err:
+ heim_release(key64);
+ return HEIM_ERROR(error, ret,
+ (ret, N_("Could not set a dict value while while "
+ "setting a DB value", "")));
+}
+
+/**
+ * Delete a key and its value from the DB
+ *
+ *
+ * @param db Open DB handle
+ * @param key Key
+ * @param error Output error object
+ *
+ * @return 0 on success, system error otherwise
+ *
+ * @addtogroup heimbase
+ */
+int
+heim_db_delete_key(heim_db_t db, heim_string_t table, heim_data_t key,
+ heim_error_t *error)
+{
+ heim_string_t key64 = NULL;
+ int ret;
+
+ if (error != NULL)
+ *error = NULL;
+
+ if (table == NULL)
+ table = HSTR("");
+
+ if (heim_get_tid(db) != HEIM_TID_DB)
+ return EINVAL;
+
+ if (db->plug->delf == NULL)
+ return EBADF;
+
+ if (!db->in_transaction) {
+ ret = heim_db_begin(db, 0, error);
+ if (ret)
+ goto err;
+ heim_assert(db->in_transaction, "Internal error");
+ ret = heim_db_delete_key(db, table, key, error);
+ if (ret) {
+ (void) heim_db_rollback(db, NULL);
+ return ret;
+ }
+ return heim_db_commit(db, error);
+ }
+
+ /* Transaction emulation */
+ heim_assert(db->set_keys != NULL, "Internal error");
+ key64 = to_base64(key, error);
+ if (key64 == NULL)
+ return HEIM_ENOMEM(error);
+ if (db->ro_tx) {
+ ret = heim_db_begin(db, 0, error);
+ if (ret)
+ goto err;
+ }
+ ret = heim_path_create(db->del_keys, 29, heim_number_create(1), error, table, key64, NULL);
+ if (ret)
+ goto err;
+ heim_path_delete(db->set_keys, error, table, key64, NULL);
+ heim_release(key64);
+
+ return 0;
+
+err:
+ heim_release(key64);
+ return HEIM_ERROR(error, ret,
+ (ret, N_("Could not set a dict value while while "
+ "deleting a DB value", "")));
+}
+
+/**
+ * Iterate a callback function over keys and values from a DB.
+ *
+ * @param db Open DB handle
+ * @param iter_data Callback function's private data
+ * @param iter_f Callback function, called once per-key/value pair
+ * @param error Output error object
+ *
+ * @addtogroup heimbase
+ */
+void
+heim_db_iterate_f(heim_db_t db, heim_string_t table, void *iter_data,
+ heim_db_iterator_f_t iter_f, heim_error_t *error)
+{
+ if (error != NULL)
+ *error = NULL;
+
+ if (heim_get_tid(db) != HEIM_TID_DB)
+ return;
+
+ if (!db->in_transaction)
+ db->plug->iterf(db->db_data, table, iter_data, iter_f, error);
+}
+
+static void
+db_replay_log_table_set_keys_iter(heim_object_t key, heim_object_t value,
+ void *arg)
+{
+ heim_db_t db = arg;
+ heim_data_t k, v;
+
+ if (db->ret)
+ return;
+
+ k = from_base64((heim_string_t)key, &db->error);
+ if (k == NULL) {
+ db->ret = ENOMEM;
+ return;
+ }
+ v = (heim_data_t)value;
+
+ db->ret = db->plug->setf(db->db_data, db->current_table, k, v, &db->error);
+ heim_release(k);
+}
+
+static void
+db_replay_log_table_del_keys_iter(heim_object_t key, heim_object_t value,
+ void *arg)
+{
+ heim_db_t db = arg;
+ heim_data_t k;
+
+ if (db->ret) {
+ db->ret = ENOMEM;
+ return;
+ }
+
+ k = from_base64((heim_string_t)key, &db->error);
+ if (k == NULL)
+ return;
+
+ db->ret = db->plug->delf(db->db_data, db->current_table, k, &db->error);
+ heim_release(k);
+}
+
+static void
+db_replay_log_set_keys_iter(heim_object_t table, heim_object_t table_dict,
+ void *arg)
+{
+ heim_db_t db = arg;
+
+ if (db->ret)
+ return;
+
+ db->current_table = table;
+ heim_dict_iterate_f(table_dict, db, db_replay_log_table_set_keys_iter);
+}
+
+static void
+db_replay_log_del_keys_iter(heim_object_t table, heim_object_t table_dict,
+ void *arg)
+{
+ heim_db_t db = arg;
+
+ if (db->ret)
+ return;
+
+ db->current_table = table;
+ heim_dict_iterate_f(table_dict, db, db_replay_log_table_del_keys_iter);
+}
+
+static int
+db_do_log_actions(heim_db_t db, heim_error_t *error)
+{
+ int ret;
+
+ if (error)
+ *error = NULL;
+
+ db->ret = 0;
+ db->error = NULL;
+ if (db->set_keys != NULL)
+ heim_dict_iterate_f(db->set_keys, db, db_replay_log_set_keys_iter);
+ if (db->del_keys != NULL)
+ heim_dict_iterate_f(db->del_keys, db, db_replay_log_del_keys_iter);
+
+ ret = db->ret;
+ db->ret = 0;
+ if (error && db->error) {
+ *error = db->error;
+ db->error = NULL;
+ } else {
+ heim_release(db->error);
+ db->error = NULL;
+ }
+ return ret;
+}
+
+static int
+db_replay_log(heim_db_t db, heim_error_t *error)
+{
+ int ret;
+ heim_string_t journal_fname = NULL;
+ heim_object_t journal;
+ size_t len;
+
+ heim_assert(!db->in_transaction, "DB transaction not open");
+ heim_assert(db->set_keys == NULL && db->set_keys == NULL, "DB transaction not open");
+
+ if (error)
+ *error = NULL;
+
+ if (db->options == NULL)
+ return 0;
+
+ journal_fname = heim_dict_get_value(db->options, HSTR("journal-filename"));
+ if (journal_fname == NULL)
+ return 0;
+
+ ret = read_json(heim_string_get_utf8(journal_fname), &journal, error);
+ if (ret == ENOENT) {
+ heim_release(journal_fname);
+ return 0;
+ }
+ if (ret == 0 && journal == NULL) {
+ heim_release(journal_fname);
+ return 0;
+ }
+ if (ret != 0) {
+ heim_release(journal_fname);
+ return ret;
+ }
+
+ if (heim_get_tid(journal) != HEIM_TID_ARRAY) {
+ heim_release(journal_fname);
+ return HEIM_ERROR(error, EINVAL,
+ (ret, N_("Invalid journal contents; delete journal",
+ "")));
+ }
+
+ len = heim_array_get_length(journal);
+
+ if (len > 0)
+ db->set_keys = heim_array_get_value(journal, 0);
+ if (len > 1)
+ db->del_keys = heim_array_get_value(journal, 1);
+ ret = db_do_log_actions(db, error);
+ if (ret) {
+ heim_release(journal_fname);
+ return ret;
+ }
+
+ /* Truncate replay log and we're done */
+ ret = open_file(heim_string_get_utf8(journal_fname), 1, 0, NULL, error);
+ heim_release(journal_fname);
+ if (ret)
+ return ret;
+ heim_release(db->set_keys);
+ heim_release(db->del_keys);
+ db->set_keys = NULL;
+ db->del_keys = NULL;
+
+ return 0;
+}
+
+static
+heim_string_t to_base64(heim_data_t data, heim_error_t *error)
+{
+ char *b64 = NULL;
+ heim_string_t s = NULL;
+ const heim_octet_string *d;
+ int ret;
+
+ d = heim_data_get_data(data);
+ ret = rk_base64_encode(d->data, d->length, &b64);
+ if (ret < 0 || b64 == NULL)
+ goto enomem;
+ s = heim_string_ref_create(b64, free);
+ if (s == NULL)
+ goto enomem;
+ return s;
+
+enomem:
+ free(b64);
+ if (error)
+ *error = heim_error_create_enomem();
+ return NULL;
+}
+
+static
+heim_data_t from_base64(heim_string_t s, heim_error_t *error)
+{
+ ssize_t len = -1;
+ void *buf;
+ heim_data_t d;
+
+ buf = malloc(strlen(heim_string_get_utf8(s)));
+ if (buf)
+ len = rk_base64_decode(heim_string_get_utf8(s), buf);
+ if (len > -1 && (d = heim_data_ref_create(buf, len, free)))
+ return d;
+ free(buf);
+ if (error)
+ *error = heim_error_create_enomem();
+ return NULL;
+}
+
+
+static int
+open_file(const char *dbname, int for_write, int excl, int *fd_out, heim_error_t *error)
+{
+#ifdef WIN32
+ HANDLE hFile;
+ int ret = 0;
+
+ if (fd_out)
+ *fd_out = -1;
+
+ if (for_write)
+ hFile = CreateFile(dbname, GENERIC_WRITE | GENERIC_READ, 0,
+ NULL, /* we'll close as soon as we read */
+ CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+ else
+ hFile = CreateFile(dbname, GENERIC_READ, FILE_SHARE_READ,
+ NULL, /* we'll close as soon as we read */
+ OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
+ if (hFile == INVALID_HANDLE_VALUE) {
+ ret = GetLastError();
+ _set_errno(ret); /* CreateFile() does not set errno */
+ goto err;
+ }
+ if (fd_out == NULL) {
+ (void) CloseHandle(hFile);
+ return 0;
+ }
+
+ *fd_out = _open_osfhandle((intptr_t) hFile, 0);
+ if (*fd_out < 0) {
+ ret = errno;
+ (void) CloseHandle(hFile);
+ goto err;
+ }
+
+ /* No need to lock given share deny mode */
+ return 0;
+
+err:
+ if (error != NULL) {
+ char *s = NULL;
+ FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
+ 0, ret, 0, (LPTSTR) &s, 0, NULL);
+ *error = heim_error_create(ret, N_("Could not open JSON file %s: %s", ""),
+ dbname, s ? s : "<error formatting error>");
+ LocalFree(s);
+ }
+ return ret;
+#else
+ int ret = 0;
+ int fd;
+
+ if (fd_out)
+ *fd_out = -1;
+
+ if (for_write && excl)
+ fd = open(dbname, O_CREAT | O_EXCL | O_WRONLY, 0600);
+ else if (for_write)
+ fd = open(dbname, O_CREAT | O_TRUNC | O_WRONLY, 0600);
+ else
+ fd = open(dbname, O_RDONLY);
+ if (fd < 0) {
+ if (error != NULL)
+ *error = heim_error_create(ret, N_("Could not open JSON file %s: %s", ""),
+ dbname, strerror(errno));
+ return errno;
+ }
+
+ if (fd_out == NULL) {
+ (void) close(fd);
+ return 0;
+ }
+
+ ret = flock(fd, for_write ? LOCK_EX : LOCK_SH);
+ if (ret == -1) {
+ /* Note that we if O_EXCL we're leaving the [lock] file around */
+ (void) close(fd);
+ return HEIM_ERROR(error, errno,
+ (errno, N_("Could not lock JSON file %s: %s", ""),
+ dbname, strerror(errno)));
+ }
+
+ *fd_out = fd;
+
+ return 0;
+#endif
+}
+
+static int
+read_json(const char *dbname, heim_object_t *out, heim_error_t *error)
+{
+ struct stat st;
+ char *str = NULL;
+ int ret;
+ int fd = -1;
+ ssize_t bytes;
+
+ *out = NULL;
+ ret = open_file(dbname, 0, 0, &fd, error);
+ if (ret)
+ return ret;
+
+ ret = fstat(fd, &st);
+ if (ret == -1) {
+ (void) close(fd);
+ return HEIM_ERROR(error, errno,
+ (ret, N_("Could not stat JSON DB %s: %s", ""),
+ dbname, strerror(errno)));
+ }
+
+ if (st.st_size == 0) {
+ (void) close(fd);
+ return 0;
+ }
+
+ str = malloc(st.st_size + 1);
+ if (str == NULL) {
+ (void) close(fd);
+ return HEIM_ENOMEM(error);
+ }
+
+ bytes = read(fd, str, st.st_size);
+ (void) close(fd);
+ if (bytes != st.st_size) {
+ free(str);
+ if (bytes >= 0)
+ errno = EINVAL; /* ?? */
+ return HEIM_ERROR(error, errno,
+ (ret, N_("Could not read JSON DB %s: %s", ""),
+ dbname, strerror(errno)));
+ }
+ str[st.st_size] = '\0';
+ *out = heim_json_create(str, 10, 0, error);
+ free(str);
+ if (*out == NULL)
+ return (error && *error) ? heim_error_get_code(*error) : EINVAL;
+ return 0;
+}
+
+typedef struct json_db {
+ heim_dict_t dict;
+ heim_string_t dbname;
+ heim_string_t bkpname;
+ int fd;
+ time_t last_read_time;
+ unsigned int read_only:1;
+ unsigned int locked:1;
+ unsigned int locked_needs_unlink:1;
+} *json_db_t;
+
+static int
+json_db_open(void *plug, const char *dbtype, const char *dbname,
+ heim_dict_t options, void **db, heim_error_t *error)
+{
+ json_db_t jsondb;
+ heim_dict_t contents = NULL;
+ heim_string_t dbname_s = NULL;
+ heim_string_t bkpname_s = NULL;
+
+ if (error)
+ *error = NULL;
+ if (dbtype && *dbtype && strcmp(dbtype, "json") != 0)
+ return HEIM_ERROR(error, EINVAL, (EINVAL, N_("Wrong DB type", "")));
+ if (dbname && *dbname && strcmp(dbname, "MEMORY") != 0) {
+ char *ext = strrchr(dbname, '.');
+ char *bkpname;
+ size_t len;
+ int ret;
+
+ if (ext == NULL || strcmp(ext, ".json") != 0)
+ return HEIM_ERROR(error, EINVAL,
+ (EINVAL, N_("JSON DB files must end in .json",
+ "")));
+
+ if (options) {
+ heim_object_t vc, ve, vt;
+
+ vc = heim_dict_get_value(options, HSTR("create"));
+ ve = heim_dict_get_value(options, HSTR("exclusive"));
+ vt = heim_dict_get_value(options, HSTR("truncate"));
+ if (vc && vt) {
+ ret = open_file(dbname, 1, ve ? 1 : 0, NULL, error);
+ if (ret)
+ return ret;
+ } else if (vc || ve || vt) {
+ return HEIM_ERROR(error, EINVAL,
+ (EINVAL, N_("Invalid JSON DB open options",
+ "")));
+ }
+ /*
+ * We don't want cloned handles to truncate the DB, eh?
+ *
+ * We should really just create a copy of the options dict
+ * rather than modify the caller's! But for that it'd be
+ * nicer to have copy utilities in heimbase, something like
+ * this:
+ *
+ * heim_object_t heim_copy(heim_object_t src, int depth,
+ * heim_error_t *error);
+ *
+ * so that options = heim_copy(options, 1); means copy the
+ * dict but nothing else (whereas depth == 0 would mean
+ * heim_retain(), and depth > 1 would be copy that many
+ * levels).
+ */
+ heim_dict_delete_key(options, HSTR("create"));
+ heim_dict_delete_key(options, HSTR("exclusive"));
+ heim_dict_delete_key(options, HSTR("truncate"));
+ }
+ dbname_s = heim_string_create(dbname);
+ if (dbname_s == NULL)
+ return HEIM_ENOMEM(error);
+
+ len = snprintf(NULL, 0, "%s~", dbname);
+ bkpname = malloc(len + 2);
+ if (bkpname == NULL) {
+ heim_release(dbname_s);
+ return HEIM_ENOMEM(error);
+ }
+ (void) snprintf(bkpname, len + 1, "%s~", dbname);
+ bkpname_s = heim_string_create(bkpname);
+ free(bkpname);
+ if (bkpname_s == NULL) {
+ heim_release(dbname_s);
+ return HEIM_ENOMEM(error);
+ }
+
+ ret = read_json(dbname, (heim_object_t *)&contents, error);
+ if (ret) {
+ heim_release(bkpname_s);
+ heim_release(dbname_s);
+ return ret;
+ }
+
+ if (contents != NULL && heim_get_tid(contents) != HEIM_TID_DICT) {
+ heim_release(bkpname_s);
+ heim_release(dbname_s);
+ return HEIM_ERROR(error, EINVAL,
+ (EINVAL, N_("JSON DB contents not valid JSON",
+ "")));
+ }
+ }
+
+ jsondb = heim_alloc(sizeof (*jsondb), "json_db", NULL);
+ if (jsondb == NULL) {
+ heim_release(contents);
+ heim_release(dbname_s);
+ heim_release(bkpname_s);
+ return ENOMEM;
+ }
+
+ jsondb->last_read_time = time(NULL);
+ jsondb->fd = -1;
+ jsondb->dbname = dbname_s;
+ jsondb->bkpname = bkpname_s;
+ jsondb->read_only = 0;
+
+ if (contents != NULL)
+ jsondb->dict = contents;
+ else {
+ jsondb->dict = heim_dict_create(29);
+ if (jsondb->dict == NULL) {
+ heim_release(jsondb);
+ return ENOMEM;
+ }
+ }
+
+ *db = jsondb;
+ return 0;
+}
+
+static int
+json_db_close(void *db, heim_error_t *error)
+{
+ json_db_t jsondb = db;
+
+ if (error)
+ *error = NULL;
+ if (jsondb->fd > -1)
+ (void) close(jsondb->fd);
+ jsondb->fd = -1;
+ heim_release(jsondb->dbname);
+ heim_release(jsondb->bkpname);
+ heim_release(jsondb->dict);
+ heim_release(jsondb);
+ return 0;
+}
+
+static int
+json_db_lock(void *db, int read_only, heim_error_t *error)
+{
+ json_db_t jsondb = db;
+ int ret;
+
+ heim_assert(jsondb->fd == -1 || (jsondb->read_only && !read_only),
+ "DB locks are not recursive");
+
+ jsondb->read_only = read_only ? 1 : 0;
+ if (jsondb->fd > -1)
+ return 0;
+
+ ret = open_file(heim_string_get_utf8(jsondb->bkpname), 1, 1, &jsondb->fd, error);
+ if (ret == 0) {
+ jsondb->locked_needs_unlink = 1;
+ jsondb->locked = 1;
+ }
+ return ret;
+}
+
+static int
+json_db_unlock(void *db, heim_error_t *error)
+{
+ json_db_t jsondb = db;
+ int ret = 0;
+
+ heim_assert(jsondb->locked, "DB not locked when unlock attempted");
+ if (jsondb->fd > -1)
+ ret = close(jsondb->fd);
+ jsondb->fd = -1;
+ jsondb->read_only = 0;
+ jsondb->locked = 0;
+ if (jsondb->locked_needs_unlink)
+ unlink(heim_string_get_utf8(jsondb->bkpname));
+ jsondb->locked_needs_unlink = 0;
+ return ret;
+}
+
+static int
+json_db_sync(void *db, heim_error_t *error)
+{
+ json_db_t jsondb = db;
+ size_t len, bytes;
+ heim_error_t e;
+ heim_string_t json;
+ const char *json_text = NULL;
+ int ret = 0;
+ int fd = -1;
+#ifdef WIN32
+ int tries = 3;
+#endif
+
+ heim_assert(jsondb->fd > -1, "DB not locked when sync attempted");
+
+ json = heim_json_copy_serialize(jsondb->dict, 0, &e);
+ if (json == NULL) {
+ if (error)
+ *error = e;
+ else
+ heim_release(e);
+ return heim_error_get_code(e);
+ }
+
+ json_text = heim_string_get_utf8(json);
+ len = strlen(json_text);
+ errno = 0;
+
+#ifdef WIN32
+ while (tries--) {
+ ret = open_file(heim_string_get_utf8(jsondb->dbname), 1, 0, &fd, error);
+ if (ret == 0)
+ break;
+ sleep(1);
+ }
+ if (ret) {
+ heim_release(json);
+ return ret;
+ }
+#else
+ fd = jsondb->fd;
+#endif /* WIN32 */
+
+ bytes = write(fd, json_text, len);
+ heim_release(json);
+ if (bytes != len)
+ return errno ? errno : EIO;
+ ret = fsync(fd);
+ if (ret)
+ return ret;
+
+#ifdef WIN32
+ ret = close(fd);
+ if (ret)
+ return GetLastError();
+#else
+ ret = rename(heim_string_get_utf8(jsondb->bkpname), heim_string_get_utf8(jsondb->dbname));
+ if (ret == 0) {
+ jsondb->locked_needs_unlink = 0;
+ return 0;
+ }
+#endif /* WIN32 */
+
+ return errno;
+}
+
+static heim_data_t
+json_db_copy_value(void *db, heim_string_t table, heim_data_t key,
+ heim_error_t *error)
+{
+ json_db_t jsondb = db;
+ heim_string_t key_string;
+ const heim_octet_string *key_data = heim_data_get_data(key);
+ struct stat st;
+ heim_data_t result;
+
+ if (error)
+ *error = NULL;
+
+ if (strnlen(key_data->data, key_data->length) != key_data->length) {
+ HEIM_ERROR(error, EINVAL,
+ (EINVAL, N_("JSON DB requires keys that are actually "
+ "strings", "")));
+ return NULL;
+ }
+
+ if (stat(heim_string_get_utf8(jsondb->dbname), &st) == -1) {
+ HEIM_ERROR(error, errno,
+ (errno, N_("Could not stat JSON DB file", "")));
+ return NULL;
+ }
+
+ if (st.st_mtime > jsondb->last_read_time ||
+ st.st_ctime > jsondb->last_read_time) {
+ heim_dict_t contents = NULL;
+ int ret;
+
+ /* Ignore file is gone (ENOENT) */
+ ret = read_json(heim_string_get_utf8(jsondb->dbname),
+ (heim_object_t *)&contents, error);
+ if (ret)
+ return NULL;
+ if (contents == NULL)
+ contents = heim_dict_create(29);
+ heim_release(jsondb->dict);
+ jsondb->dict = contents;
+ jsondb->last_read_time = time(NULL);
+ }
+
+ key_string = heim_string_create_with_bytes(key_data->data,
+ key_data->length);
+ if (key_string == NULL) {
+ (void) HEIM_ENOMEM(error);
+ return NULL;
+ }
+
+ result = heim_path_copy(jsondb->dict, error, table, key_string, NULL);
+ heim_release(key_string);
+ return result;
+}
+
+static int
+json_db_set_value(void *db, heim_string_t table,
+ heim_data_t key, heim_data_t value, heim_error_t *error)
+{
+ json_db_t jsondb = db;
+ heim_string_t key_string;
+ const heim_octet_string *key_data = heim_data_get_data(key);
+ int ret;
+
+ if (error)
+ *error = NULL;
+
+ if (strnlen(key_data->data, key_data->length) != key_data->length)
+ return HEIM_ERROR(error, EINVAL,
+ (EINVAL,
+ N_("JSON DB requires keys that are actually strings",
+ "")));
+
+ key_string = heim_string_create_with_bytes(key_data->data,
+ key_data->length);
+ if (key_string == NULL)
+ return HEIM_ENOMEM(error);
+
+ if (table == NULL)
+ table = HSTR("");
+
+ ret = heim_path_create(jsondb->dict, 29, value, error, table, key_string, NULL);
+ heim_release(key_string);
+ return ret;
+}
+
+static int
+json_db_del_key(void *db, heim_string_t table, heim_data_t key,
+ heim_error_t *error)
+{
+ json_db_t jsondb = db;
+ heim_string_t key_string;
+ const heim_octet_string *key_data = heim_data_get_data(key);
+
+ if (error)
+ *error = NULL;
+
+ if (strnlen(key_data->data, key_data->length) != key_data->length)
+ return HEIM_ERROR(error, EINVAL,
+ (EINVAL,
+ N_("JSON DB requires keys that are actually strings",
+ "")));
+
+ key_string = heim_string_create_with_bytes(key_data->data,
+ key_data->length);
+ if (key_string == NULL)
+ return HEIM_ENOMEM(error);
+
+ if (table == NULL)
+ table = HSTR("");
+
+ heim_path_delete(jsondb->dict, error, table, key_string, NULL);
+ heim_release(key_string);
+ return 0;
+}
+
+struct json_db_iter_ctx {
+ heim_db_iterator_f_t iter_f;
+ void *iter_ctx;
+};
+
+static void json_db_iter_f(heim_object_t key, heim_object_t value, void *arg)
+{
+ struct json_db_iter_ctx *ctx = arg;
+ const char *key_string;
+ heim_data_t key_data;
+
+ key_string = heim_string_get_utf8((heim_string_t)key);
+ key_data = heim_data_ref_create(key_string, strlen(key_string), NULL);
+ ctx->iter_f(key_data, (heim_object_t)value, ctx->iter_ctx);
+ heim_release(key_data);
+}
+
+static void
+json_db_iter(void *db, heim_string_t table, void *iter_data,
+ heim_db_iterator_f_t iter_f, heim_error_t *error)
+{
+ json_db_t jsondb = db;
+ struct json_db_iter_ctx ctx;
+ heim_dict_t table_dict;
+
+ if (error)
+ *error = NULL;
+
+ if (table == NULL)
+ table = HSTR("");
+
+ table_dict = heim_dict_get_value(jsondb->dict, table);
+ if (table_dict == NULL)
+ return;
+
+ ctx.iter_ctx = iter_data;
+ ctx.iter_f = iter_f;
+
+ heim_dict_iterate_f(table_dict, &ctx, json_db_iter_f);
+}
+
+static struct heim_db_type json_dbt = {
+ 1, json_db_open, NULL, json_db_close,
+ json_db_lock, json_db_unlock, json_db_sync,
+ NULL, NULL, NULL,
+ json_db_copy_value, json_db_set_value,
+ json_db_del_key, json_db_iter
+};
+
diff --git a/third_party/heimdal/lib/base/dict.c b/third_party/heimdal/lib/base/dict.c
new file mode 100644
index 0000000..86be109
--- /dev/null
+++ b/third_party/heimdal/lib/base/dict.c
@@ -0,0 +1,305 @@
+/*
+ * Copyright (c) 2002, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+
+struct hashentry {
+ struct hashentry **prev;
+ struct hashentry *next;
+ heim_object_t key;
+ heim_object_t value;
+};
+
+struct heim_dict_data {
+ size_t size;
+ struct hashentry **tab;
+};
+
+static void HEIM_CALLCONV
+dict_dealloc(void *ptr)
+{
+ heim_dict_t dict = ptr;
+ struct hashentry **h, *g, *i;
+
+ for (h = dict->tab; h < &dict->tab[dict->size]; ++h) {
+ for (g = h[0]; g; g = i) {
+ i = g->next;
+ heim_release(g->key);
+ heim_release(g->value);
+ free(g);
+ }
+ }
+ free(dict->tab);
+}
+
+struct heim_type_data dict_object = {
+ HEIM_TID_DICT,
+ "dict-object",
+ NULL,
+ dict_dealloc,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+static size_t
+isprime(size_t p)
+{
+ size_t q, i;
+
+ for(i = 2 ; i < p; i++) {
+ q = p / i;
+
+ if (i * q == p)
+ return 0;
+ if (i * i > p)
+ return 1;
+ }
+ return 1;
+}
+
+static size_t
+findprime(size_t p)
+{
+ if (p % 2 == 0)
+ p++;
+
+ while (isprime(p) == 0)
+ p += 2;
+
+ return p;
+}
+
+/**
+ * Allocate an array
+ *
+ * @return A new allocated array, free with heim_release()
+ */
+
+heim_dict_t
+heim_dict_create(size_t size)
+{
+ heim_dict_t dict;
+
+ dict = _heim_alloc_object(&dict_object, sizeof(*dict));
+ if (dict == NULL)
+ return NULL;
+
+ dict->size = findprime(size);
+ if (dict->size == 0) {
+ heim_release(dict);
+ return NULL;
+ }
+
+ dict->tab = calloc(dict->size, sizeof(dict->tab[0]));
+ if (dict->tab == NULL) {
+ dict->size = 0;
+ heim_release(dict);
+ return NULL;
+ }
+
+ return dict;
+}
+
+/**
+ * Get type id of an dict
+ *
+ * @return the type id
+ */
+
+heim_tid_t
+heim_dict_get_type_id(void)
+{
+ return HEIM_TID_DICT;
+}
+
+/* Intern search function */
+
+static struct hashentry *
+_search(heim_dict_t dict, heim_object_t ptr)
+{
+ uintptr_t v = heim_get_hash(ptr);
+ struct hashentry *p;
+
+ for (p = dict->tab[v % dict->size]; p != NULL; p = p->next)
+ if (heim_cmp(ptr, p->key) == 0)
+ return p;
+
+ return NULL;
+}
+
+/**
+ * Search for element in hash table
+ *
+ * @value dict the dict to search in
+ * @value key the key to search for
+ *
+ * @return a not-retained copy of the value for key or NULL if not found
+ */
+
+heim_object_t
+heim_dict_get_value(heim_dict_t dict, heim_object_t key)
+{
+ struct hashentry *p;
+ p = _search(dict, key);
+ if (p == NULL)
+ return NULL;
+
+ return p->value;
+}
+
+/**
+ * Search for element in hash table
+ *
+ * @value dict the dict to search in
+ * @value key the key to search for
+ *
+ * @return a retained copy of the value for key or NULL if not found
+ */
+
+heim_object_t
+heim_dict_copy_value(heim_dict_t dict, heim_object_t key)
+{
+ struct hashentry *p;
+ p = _search(dict, key);
+ if (p == NULL)
+ return NULL;
+
+ return heim_retain(p->value);
+}
+
+/**
+ * Add key and value to dict
+ *
+ * @value dict the dict to add too
+ * @value key the key to add
+ * @value value the value to add
+ *
+ * @return 0 if added, errno if not
+ */
+
+int
+heim_dict_set_value(heim_dict_t dict, heim_object_t key, heim_object_t value)
+{
+ struct hashentry **tabptr, *h;
+
+ h = _search(dict, key);
+ if (h) {
+ heim_release(h->value);
+ h->value = heim_retain(value);
+ } else {
+ uintptr_t v;
+
+ h = malloc(sizeof(*h));
+ if (h == NULL)
+ return ENOMEM;
+
+ h->key = heim_retain(key);
+ h->value = heim_retain(value);
+
+ v = heim_get_hash(key);
+
+ tabptr = &dict->tab[v % dict->size];
+ h->next = *tabptr;
+ *tabptr = h;
+ h->prev = tabptr;
+ if (h->next)
+ h->next->prev = &h->next;
+ }
+
+ return 0;
+}
+
+/**
+ * Delete element with key key
+ *
+ * @value dict the dict to delete from
+ * @value key the key to delete
+ */
+
+void
+heim_dict_delete_key(heim_dict_t dict, heim_object_t key)
+{
+ struct hashentry *h = _search(dict, key);
+
+ if (h == NULL)
+ return;
+
+ heim_release(h->key);
+ heim_release(h->value);
+
+ if ((*(h->prev) = h->next) != NULL)
+ h->next->prev = h->prev;
+
+ free(h);
+}
+
+/**
+ * Do something for each element
+ *
+ * @value dict the dict to interate over
+ * @value func the function to search for
+ * @value arg argument to func
+ */
+
+void
+heim_dict_iterate_f(heim_dict_t dict, void *arg, heim_dict_iterator_f_t func)
+{
+ struct hashentry **h, *g;
+
+ for (h = dict->tab; h < &dict->tab[dict->size]; ++h)
+ for (g = *h; g; g = g->next)
+ func(g->key, g->value, arg);
+}
+
+#ifdef __BLOCKS__
+/**
+ * Do something for each element
+ *
+ * @value dict the dict to interate over
+ * @value func the function to search for
+ */
+
+void
+heim_dict_iterate(heim_dict_t dict, void (^func)(heim_object_t, heim_object_t))
+{
+ struct hashentry **h, *g;
+
+ for (h = dict->tab; h < &dict->tab[dict->size]; ++h)
+ for (g = *h; g; g = g->next)
+ func(g->key, g->value);
+}
+#endif
diff --git a/third_party/heimdal/lib/base/dll.c b/third_party/heimdal/lib/base/dll.c
new file mode 100644
index 0000000..59c3913
--- /dev/null
+++ b/third_party/heimdal/lib/base/dll.c
@@ -0,0 +1,325 @@
+/***********************************************************************
+ * Copyright (c) 2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+/*
+ * This is an implementation of thread-specific storage with
+ * destructors. WIN32 doesn't quite have this. Instead it has
+ * DllMain(), an entry point in every DLL that gets called to notify the
+ * DLL of thread/process "attach"/"detach" events.
+ *
+ * We use __thread (or __declspec(thread)) for the thread-local itself
+ * and DllMain() DLL_THREAD_DETACH events to drive destruction of
+ * thread-local values.
+ *
+ * When building in maintainer mode on non-Windows pthread systems this
+ * uses a single pthread key instead to implement multiple keys. This
+ * keeps the code from rotting when modified by non-Windows developers.
+ */
+
+#include "baselocl.h"
+
+#ifdef WIN32
+#include <windows.h>
+#endif
+
+#ifdef HEIM_WIN32_TLS
+#include <assert.h>
+#include <err.h>
+#include <heim_threads.h>
+
+#ifndef WIN32
+#include <pthread.h>
+#endif
+
+/* Logical array of keys that grows lock-lessly */
+typedef struct tls_keys tls_keys;
+struct tls_keys {
+ void (**keys_dtors)(void *); /* array of destructors */
+ size_t keys_start_idx; /* index of first destructor */
+ size_t keys_num;
+ tls_keys *keys_next;
+};
+
+/*
+ * Well, not quite locklessly. We need synchronization primitives to do
+ * this locklessly. An atomic CAS will do.
+ */
+static HEIMDAL_MUTEX tls_key_defs_lock = HEIMDAL_MUTEX_INITIALIZER;
+static tls_keys *tls_key_defs;
+
+/* Logical array of values (per-thread; no locking needed here) */
+struct tls_values {
+ void **values; /* realloc()ed */
+ size_t values_num;
+};
+
+static HEIMDAL_THREAD_LOCAL struct tls_values values;
+
+static char dead_key;
+#define DEAD_KEY ((void *)&dead_key)
+
+void
+heim_w32_service_thread_detach(void *unused)
+{
+ tls_keys *key_defs;
+ void (*dtor)(void*);
+ size_t i;
+
+ HEIMDAL_MUTEX_lock(&tls_key_defs_lock);
+ key_defs = tls_key_defs;
+ HEIMDAL_MUTEX_unlock(&tls_key_defs_lock);
+
+ if (key_defs == NULL)
+ return;
+
+ for (i = 0; i < values.values_num; i++) {
+ assert(i >= key_defs->keys_start_idx);
+ if (i >= key_defs->keys_start_idx + key_defs->keys_num) {
+ HEIMDAL_MUTEX_lock(&tls_key_defs_lock);
+ key_defs = key_defs->keys_next;
+ HEIMDAL_MUTEX_unlock(&tls_key_defs_lock);
+
+ assert(key_defs != NULL);
+ assert(i >= key_defs->keys_start_idx);
+ assert(i < key_defs->keys_start_idx + key_defs->keys_num);
+ }
+ dtor = key_defs->keys_dtors[i - key_defs->keys_start_idx];
+ if (values.values[i] != NULL && dtor != NULL && dtor != DEAD_KEY)
+ dtor(values.values[i]);
+ values.values[i] = NULL;
+ }
+}
+
+#if !defined(WIN32)
+static pthread_key_t pt_key;
+pthread_once_t pt_once = PTHREAD_ONCE_INIT;
+
+static void
+atexit_del_tls_for_thread(void)
+{
+ heim_w32_service_thread_detach(NULL);
+}
+
+static void
+create_pt_key(void)
+{
+ int ret;
+
+ /* The main thread may not execute TLS destructors */
+ atexit(atexit_del_tls_for_thread);
+ ret = pthread_key_create(&pt_key, heim_w32_service_thread_detach);
+ if (ret != 0)
+ err(1, "pthread_key_create() failed");
+}
+
+#endif
+
+int
+heim_w32_key_create(HEIM_PRIV_thread_key *key, void (*dtor)(void *))
+{
+ tls_keys *key_defs, *new_key_defs;
+ size_t i, k;
+ int ret = ENOMEM;
+
+#if !defined(WIN32)
+ (void) pthread_once(&pt_once, create_pt_key);
+ (void) pthread_setspecific(pt_key, DEAD_KEY);
+#endif
+
+ HEIMDAL_MUTEX_lock(&tls_key_defs_lock);
+ if (tls_key_defs == NULL) {
+ /* First key */
+ new_key_defs = calloc(1, sizeof(*new_key_defs));
+ if (new_key_defs == NULL) {
+ HEIMDAL_MUTEX_unlock(&tls_key_defs_lock);
+ return ENOMEM;
+ }
+ new_key_defs->keys_num = 8;
+ new_key_defs->keys_dtors = calloc(new_key_defs->keys_num,
+ sizeof(*new_key_defs->keys_dtors));
+ if (new_key_defs->keys_dtors == NULL) {
+ HEIMDAL_MUTEX_unlock(&tls_key_defs_lock);
+ free(new_key_defs);
+ return ENOMEM;
+ }
+ tls_key_defs = new_key_defs;
+ new_key_defs->keys_dtors[0] = dtor;
+ for (i = 1; i < new_key_defs->keys_num; i++)
+ new_key_defs->keys_dtors[i] = NULL;
+ HEIMDAL_MUTEX_unlock(&tls_key_defs_lock);
+ return 0;
+ }
+
+ for (key_defs = tls_key_defs;
+ key_defs != NULL;
+ key_defs = key_defs->keys_next) {
+ k = key_defs->keys_start_idx;
+ for (i = 0; i < key_defs->keys_num; i++, k++) {
+ if (key_defs->keys_dtors[i] == NULL) {
+ /* Found free slot; use it */
+ key_defs->keys_dtors[i] = dtor;
+ *key = k;
+ HEIMDAL_MUTEX_unlock(&tls_key_defs_lock);
+ return 0;
+ }
+ }
+ if (key_defs->keys_next != NULL)
+ continue;
+
+ /* Grow the registration array */
+ /* XXX DRY */
+ new_key_defs = calloc(1, sizeof(*new_key_defs));
+ if (new_key_defs == NULL)
+ break;
+
+ new_key_defs->keys_dtors =
+ calloc(key_defs->keys_num + key_defs->keys_num / 2,
+ sizeof(*new_key_defs->keys_dtors));
+ if (new_key_defs->keys_dtors == NULL) {
+ free(new_key_defs);
+ break;
+ }
+ new_key_defs->keys_start_idx = key_defs->keys_start_idx +
+ key_defs->keys_num;
+ new_key_defs->keys_num = key_defs->keys_num + key_defs->keys_num / 2;
+ new_key_defs->keys_dtors[i] = dtor;
+ for (i = 1; i < new_key_defs->keys_num; i++)
+ new_key_defs->keys_dtors[i] = NULL;
+ key_defs->keys_next = new_key_defs;
+ ret = 0;
+ break;
+ }
+ HEIMDAL_MUTEX_unlock(&tls_key_defs_lock);
+ return ret;
+}
+
+static void
+key_lookup(HEIM_PRIV_thread_key key, tls_keys **kd,
+ size_t *dtor_idx, void (**dtor)(void *))
+{
+ tls_keys *key_defs;
+
+ if (kd != NULL)
+ *kd = NULL;
+ if (dtor_idx != NULL)
+ *dtor_idx = 0;
+ if (dtor != NULL)
+ *dtor = NULL;
+
+ HEIMDAL_MUTEX_lock(&tls_key_defs_lock);
+ key_defs = tls_key_defs;
+ HEIMDAL_MUTEX_unlock(&tls_key_defs_lock);
+
+ while (key_defs != NULL) {
+ if (key >= key_defs->keys_start_idx &&
+ key < key_defs->keys_start_idx + key_defs->keys_num) {
+ if (kd != NULL)
+ *kd = key_defs;
+ if (dtor_idx != NULL)
+ *dtor_idx = key - key_defs->keys_start_idx;
+ if (dtor != NULL)
+ *dtor = key_defs->keys_dtors[key - key_defs->keys_start_idx];
+ return;
+ }
+
+ HEIMDAL_MUTEX_lock(&tls_key_defs_lock);
+ key_defs = key_defs->keys_next;
+ HEIMDAL_MUTEX_unlock(&tls_key_defs_lock);
+ assert(key_defs != NULL);
+ assert(key >= key_defs->keys_start_idx);
+ }
+}
+
+int
+heim_w32_delete_key(HEIM_PRIV_thread_key key)
+{
+ tls_keys *key_defs;
+ size_t dtor_idx;
+
+ key_lookup(key, &key_defs, &dtor_idx, NULL);
+ if (key_defs == NULL)
+ return EINVAL;
+ key_defs->keys_dtors[dtor_idx] = DEAD_KEY;
+ return 0;
+}
+
+int
+heim_w32_setspecific(HEIM_PRIV_thread_key key, void *value)
+{
+ void **new_values;
+ size_t new_num;
+ void (*dtor)(void *);
+ size_t i;
+
+#if !defined(WIN32)
+ (void) pthread_setspecific(pt_key, DEAD_KEY);
+#endif
+
+ key_lookup(key, NULL, NULL, &dtor);
+ if (dtor == NULL)
+ return EINVAL;
+
+ if (key >= values.values_num) {
+ if (values.values_num == 0) {
+ values.values = NULL;
+ new_num = 8;
+ } else {
+ new_num = (values.values_num + values.values_num / 2);
+ }
+ new_values = realloc(values.values, sizeof(void *) * new_num);
+ if (new_values == NULL)
+ return ENOMEM;
+ for (i = values.values_num; i < new_num; i++)
+ new_values[i] = NULL;
+ values.values = new_values;
+ values.values_num = new_num;
+ }
+
+ assert(key < values.values_num);
+
+ if (values.values[key] != NULL && dtor != NULL && dtor != DEAD_KEY)
+ dtor(values.values[key]);
+
+ values.values[key] = value;
+ return 0;
+}
+
+void *
+heim_w32_getspecific(HEIM_PRIV_thread_key key)
+{
+ if (key >= values.values_num)
+ return NULL;
+ return values.values[key];
+}
+
+#else
+static char dummy;
+#endif /* HEIM_WIN32_TLS */
diff --git a/third_party/heimdal/lib/base/error.c b/third_party/heimdal/lib/base/error.c
new file mode 100644
index 0000000..6ba3bea
--- /dev/null
+++ b/third_party/heimdal/lib/base/error.c
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+
+struct heim_error {
+ int error_code;
+ heim_string_t msg;
+ struct heim_error *next;
+};
+
+static void HEIM_CALLCONV
+error_dealloc(void *ptr)
+{
+ struct heim_error *p = ptr;
+ heim_release(p->msg);
+ heim_release(p->next);
+}
+
+static int
+error_cmp(void *a, void *b)
+{
+ struct heim_error *ap = a, *bp = b;
+ if (ap->error_code == bp->error_code)
+ return 0;
+ return heim_cmp(ap->msg, bp->msg);
+}
+
+static uintptr_t
+error_hash(void *ptr)
+{
+ struct heim_error *p = ptr;
+ return p->error_code;
+}
+
+struct heim_type_data _heim_error_object = {
+ HEIM_TID_ERROR,
+ "error-object",
+ NULL,
+ error_dealloc,
+ NULL,
+ error_cmp,
+ error_hash,
+ NULL
+};
+
+heim_error_t
+heim_error_create_enomem(void)
+{
+ /* This is an immediate object; see heim_number_create() */
+ return (heim_error_t)heim_number_create(ENOMEM);
+}
+
+
+void
+heim_error_create_opt(heim_error_t *error, int error_code, const char *fmt, ...)
+{
+ if (error) {
+ va_list ap;
+ va_start(ap, fmt);
+ *error = heim_error_createv(error_code, fmt, ap);
+ va_end(ap);
+ }
+}
+
+heim_error_t
+heim_error_create(int error_code, const char *fmt, ...)
+{
+ heim_error_t e;
+ va_list ap;
+
+ va_start(ap, fmt);
+ e = heim_error_createv(error_code, fmt, ap);
+ va_end(ap);
+
+ return e;
+}
+
+heim_error_t
+heim_error_createv(int error_code, const char *fmt, va_list ap)
+{
+ heim_error_t e;
+ char *str;
+ int len;
+ int save_errno = errno;
+
+ str = malloc(1024);
+ errno = save_errno;
+ if (str == NULL)
+ return heim_error_create_enomem();
+ len = vsnprintf(str, 1024, fmt, ap);
+ errno = save_errno;
+ if (len < 0) {
+ free(str);
+ return NULL; /* XXX We should have a special heim_error_t for this */
+ }
+
+ e = _heim_alloc_object(&_heim_error_object, sizeof(struct heim_error));
+ if (e) {
+ e->msg = heim_string_create(str);
+ e->error_code = error_code;
+ }
+ free(str);
+
+ errno = save_errno;
+ return e;
+}
+
+heim_string_t
+heim_error_copy_string(heim_error_t error)
+{
+ if (heim_get_tid(error) != HEIM_TID_ERROR) {
+ if (heim_get_tid(error) == heim_number_get_type_id())
+ return __heim_string_constant(strerror(heim_number_get_int((heim_number_t)error)));
+ heim_abort("invalid heim_error_t");
+ }
+ /* XXX concat all strings */
+ return heim_retain(error->msg);
+}
+
+int
+heim_error_get_code(heim_error_t error)
+{
+ if (error == NULL)
+ return -1;
+ if (heim_get_tid(error) != HEIM_TID_ERROR) {
+ if (heim_get_tid(error) == heim_number_get_type_id())
+ return heim_number_get_int((heim_number_t)error);
+ heim_abort("invalid heim_error_t");
+ }
+ return error->error_code;
+}
+
+heim_error_t
+heim_error_append(heim_error_t top, heim_error_t append)
+{
+ if (heim_get_tid(top) != HEIM_TID_ERROR) {
+ if (heim_get_tid(top) == heim_number_get_type_id())
+ return top;
+ heim_abort("invalid heim_error_t");
+ }
+ if (top->next)
+ heim_release(top->next);
+ top->next = heim_retain(append);
+ return top;
+}
diff --git a/third_party/heimdal/lib/base/error_string.c b/third_party/heimdal/lib/base/error_string.c
new file mode 100644
index 0000000..a562833
--- /dev/null
+++ b/third_party/heimdal/lib/base/error_string.c
@@ -0,0 +1,177 @@
+/*
+ * Copyright (c) 2001, 2003, 2005 - 2020 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+
+#undef __attribute__
+#define __attribute__(x)
+
+void
+heim_clear_error_message(heim_context context)
+{
+ if (!context)
+ return;
+ if (context->error_string)
+ free(context->error_string);
+ context->error_code = 0;
+ context->error_string = NULL;
+}
+
+void
+heim_set_error_message(heim_context context, heim_error_code ret,
+ const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 3, 4)))
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ if (context)
+ heim_vset_error_message(context, ret, fmt, ap);
+ va_end(ap);
+}
+
+void
+heim_vset_error_message(heim_context context, heim_error_code ret,
+ const char *fmt, va_list args)
+ __attribute__ ((__format__ (__printf__, 3, 0)))
+{
+ int r;
+
+ if (context == NULL)
+ return;
+ if (context->error_string) {
+ free(context->error_string);
+ context->error_string = NULL;
+ }
+ context->error_code = ret;
+ r = vasprintf(&context->error_string, fmt, args);
+ if (r < 0)
+ context->error_string = NULL;
+ if (context->error_string)
+ heim_debug(context, 200, "error message: %s: %d", context->error_string, ret);
+}
+
+void
+heim_prepend_error_message(heim_context context, heim_error_code ret,
+ const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 3, 4)))
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ heim_vprepend_error_message(context, ret, fmt, ap);
+ va_end(ap);
+}
+
+void
+heim_vprepend_error_message(heim_context context, heim_error_code ret,
+ const char *fmt, va_list args)
+ __attribute__ ((__format__ (__printf__, 3, 0)))
+{
+ char *str = NULL, *str2 = NULL;
+
+ if (context == NULL || context->error_code != ret ||
+ vasprintf(&str, fmt, args) < 0 || str == NULL)
+ return;
+ if (context->error_string) {
+ int e;
+
+ e = asprintf(&str2, "%s: %s", str, context->error_string);
+ free(context->error_string);
+ if (e < 0 || str2 == NULL)
+ context->error_string = NULL;
+ else
+ context->error_string = str2;
+ free(str);
+ } else
+ context->error_string = str;
+}
+
+const char *
+heim_get_error_message(heim_context context, heim_error_code code)
+{
+ const char *cstr = NULL;
+ char *str = NULL;
+ char buf[128];
+ int free_context = 0;
+
+ if (code == 0)
+ return strdup("Success");
+
+ /*
+ * The MIT version of this function ignores the krb5_context
+ * and several widely deployed applications call krb5_get_error_message()
+ * with a NULL context in order to translate an error code as a
+ * replacement for error_message(). Another reason a NULL context
+ * might be provided is if the krb5_init_context() call itself
+ * failed.
+ */
+ if (context &&
+ context->error_string &&
+ (code == context->error_code || context->error_code == 0) &&
+ (cstr = strdup(context->error_string)))
+ return cstr;
+
+ if (context == NULL && (context = heim_context_init()))
+ free_context = 1;
+ if (context)
+ cstr = com_right_r(context->et_list, code, buf, sizeof(buf));
+ if (free_context)
+ heim_context_free(&context);
+
+ if (cstr || (cstr = error_message(code)))
+ return strdup(cstr);
+ if (asprintf(&str, "<unknown error: %d>", (int)code) == -1 || str == NULL)
+ return NULL;
+ return str;
+}
+
+const char *
+heim_get_error_string(heim_context context)
+{
+ if (context && context->error_string)
+ return strdup(context->error_string);
+ return NULL;
+}
+
+int
+heim_have_error_string(heim_context context)
+{
+ return context && context->error_string != NULL;
+}
+
+void
+heim_free_error_message(heim_context context, const char *msg)
+{
+ free(rk_UNCONST(msg));
+}
diff --git a/third_party/heimdal/lib/base/expand_path.c b/third_party/heimdal/lib/base/expand_path.c
new file mode 100644
index 0000000..cf24991
--- /dev/null
+++ b/third_party/heimdal/lib/base/expand_path.c
@@ -0,0 +1,725 @@
+
+/***********************************************************************
+ * Copyright (c) 2009-2020, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include "baselocl.h"
+
+#include <stdarg.h>
+
+typedef int PTYPE;
+
+#ifdef _WIN32
+#include <shlobj.h>
+#include <sddl.h>
+
+/*
+ * Expand a %{TEMP} token
+ *
+ * The %{TEMP} token expands to the temporary path for the current
+ * user as returned by GetTempPath().
+ *
+ * @note: Since the GetTempPath() function relies on the TMP or TEMP
+ * environment variables, this function will failover to the system
+ * temporary directory until the user profile is loaded. In addition,
+ * the returned path may or may not exist.
+ */
+static heim_error_code
+expand_temp_folder(heim_context context, PTYPE param, const char *postfix,
+ const char *arg, char **ret)
+{
+ TCHAR tpath[MAX_PATH];
+ size_t len;
+
+ if (!GetTempPath(sizeof(tpath)/sizeof(tpath[0]), tpath)) {
+ heim_set_error_message(context, EINVAL,
+ "Failed to get temporary path (GLE=%d)",
+ GetLastError());
+ return EINVAL;
+ }
+
+ len = strlen(tpath);
+
+ if (len > 0 && tpath[len - 1] == '\\')
+ tpath[len - 1] = '\0';
+
+ *ret = strdup(tpath);
+
+ if (*ret == NULL)
+ return heim_enomem(context);
+
+ return 0;
+}
+
+EXTERN_C IMAGE_DOS_HEADER __ImageBase;
+
+/*
+ * Expand a %{BINDIR} token
+ *
+ * This is also used to expand a few other tokens on Windows, since
+ * most of the executable binaries end up in the same directory. The
+ * "bin" directory is considered to be the directory in which the
+ * containing DLL is located.
+ */
+static heim_error_code
+expand_bin_dir(heim_context context, PTYPE param, const char *postfix,
+ const char *arg, char **ret)
+{
+ TCHAR path[MAX_PATH];
+ TCHAR *lastSlash;
+ DWORD nc;
+
+ nc = GetModuleFileName((HINSTANCE)&__ImageBase, path,
+ sizeof(path)/sizeof(path[0]));
+ if (nc == 0 ||
+ nc == sizeof(path)/sizeof(path[0])) {
+ return EINVAL;
+ }
+
+ lastSlash = strrchr(path, '\\');
+ if (lastSlash != NULL) {
+ TCHAR *fslash = strrchr(lastSlash, '/');
+
+ if (fslash != NULL)
+ lastSlash = fslash;
+
+ *lastSlash = '\0';
+ }
+
+ if (postfix) {
+ if (strlcat(path, postfix, sizeof(path)/sizeof(path[0])) >= sizeof(path)/sizeof(path[0]))
+ return EINVAL;
+ }
+
+ *ret = strdup(path);
+ if (*ret == NULL)
+ return heim_enomem(context);
+
+ return 0;
+}
+
+/*
+ * Expand a %{USERID} token
+ *
+ * The %{USERID} token expands to the string representation of the
+ * user's SID. The user account that will be used is the account
+ * corresponding to the current thread's security token. This means
+ * that:
+ *
+ * - If the current thread token has the anonymous impersonation
+ * level, the call will fail.
+ *
+ * - If the current thread is impersonating a token at
+ * SecurityIdentification level the call will fail.
+ *
+ */
+static heim_error_code
+expand_userid(heim_context context, PTYPE param, const char *postfix,
+ const char *arg, char **ret)
+{
+ int rv = EINVAL;
+ HANDLE hThread = NULL;
+ HANDLE hToken = NULL;
+ PTOKEN_OWNER pOwner = NULL;
+ DWORD len = 0;
+ LPTSTR strSid = NULL;
+
+ hThread = GetCurrentThread();
+
+ if (!OpenThreadToken(hThread, TOKEN_QUERY,
+ FALSE, /* Open the thread token as the
+ current thread user. */
+ &hToken)) {
+
+ DWORD le = GetLastError();
+
+ if (le == ERROR_NO_TOKEN) {
+ HANDLE hProcess = GetCurrentProcess();
+
+ le = 0;
+ if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken))
+ le = GetLastError();
+ }
+
+ if (le != 0) {
+ heim_set_error_message(context, rv,
+ "Can't open thread token (GLE=%d)", le);
+ goto _exit;
+ }
+ }
+
+ if (!GetTokenInformation(hToken, TokenOwner, NULL, 0, &len)) {
+ if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
+ heim_set_error_message(context, rv,
+ "Unexpected error reading token information (GLE=%d)",
+ GetLastError());
+ goto _exit;
+ }
+
+ if (len == 0) {
+ heim_set_error_message(context, rv,
+ "GetTokenInformation() returned truncated buffer");
+ goto _exit;
+ }
+
+ pOwner = malloc(len);
+ if (pOwner == NULL) {
+ heim_set_error_message(context, rv, "Out of memory");
+ goto _exit;
+ }
+ } else {
+ heim_set_error_message(context, rv, "GetTokenInformation() returned truncated buffer");
+ goto _exit;
+ }
+
+ if (!GetTokenInformation(hToken, TokenOwner, pOwner, len, &len)) {
+ heim_set_error_message(context, rv,
+ "GetTokenInformation() failed. GLE=%d",
+ GetLastError());
+ goto _exit;
+ }
+
+ if (!ConvertSidToStringSid(pOwner->Owner, &strSid)) {
+ heim_set_error_message(context, rv,
+ "Can't convert SID to string. GLE=%d",
+ GetLastError());
+ goto _exit;
+ }
+
+ *ret = strdup(strSid);
+ if (*ret == NULL)
+ heim_set_error_message(context, rv, "Out of memory");
+
+ rv = 0;
+
+ _exit:
+ if (hToken != NULL)
+ CloseHandle(hToken);
+
+ if (pOwner != NULL)
+ free (pOwner);
+
+ if (strSid != NULL)
+ LocalFree(strSid);
+
+ return rv;
+}
+
+/*
+ * Expand a folder identified by a CSIDL
+ */
+
+static heim_error_code
+expand_csidl(heim_context context, PTYPE folder, const char *postfix,
+ const char *arg, char **ret)
+{
+ TCHAR path[MAX_PATH];
+ size_t len;
+
+ if (SHGetFolderPath(NULL, folder, NULL, SHGFP_TYPE_CURRENT, path) != S_OK) {
+ heim_set_error_message(context, EINVAL, "Unable to determine folder path");
+ return EINVAL;
+ }
+
+ len = strlen(path);
+
+ if (len > 0 && path[len - 1] == '\\')
+ path[len - 1] = '\0';
+
+ if (postfix &&
+ strlcat(path, postfix, sizeof(path)/sizeof(path[0])) >= sizeof(path)/sizeof(path[0]))
+ return heim_enomem(context);
+
+ *ret = strdup(path);
+ if (*ret == NULL)
+ return heim_enomem(context);
+ return 0;
+}
+
+#else
+
+static heim_error_code
+expand_path(heim_context context, PTYPE param, const char *postfix,
+ const char *arg, char **ret)
+{
+ *ret = strdup(postfix);
+ if (*ret == NULL)
+ return heim_enomem(context);
+ return 0;
+}
+
+static heim_error_code
+expand_temp_folder(heim_context context, PTYPE param, const char *postfix,
+ const char *arg, char **ret)
+{
+ const char *p = NULL;
+
+ p = secure_getenv("TEMP");
+
+ if (p)
+ *ret = strdup(p);
+ else
+ *ret = strdup("/tmp");
+ if (*ret == NULL)
+ return heim_enomem(context);
+ return 0;
+}
+
+static heim_error_code
+expand_userid(heim_context context, PTYPE param, const char *postfix,
+ const char *arg, char **str)
+{
+ int ret = asprintf(str, "%ld", (unsigned long)getuid());
+ if (ret < 0 || *str == NULL)
+ return heim_enomem(context);
+ return 0;
+}
+
+static heim_error_code
+expand_euid(heim_context context, PTYPE param, const char *postfix,
+ const char *arg, char **str)
+{
+ int ret = asprintf(str, "%ld", (unsigned long)geteuid());
+ if (ret < 0 || *str == NULL)
+ return heim_enomem(context);
+ return 0;
+}
+#endif /* _WIN32 */
+
+static heim_error_code
+expand_home(heim_context context, PTYPE param, const char *postfix,
+ const char *arg, char **str)
+{
+ char homedir[MAX_PATH];
+ int ret;
+
+ if (roken_get_homedir(homedir, sizeof(homedir)))
+ ret = asprintf(str, "%s", homedir);
+ else
+ ret = asprintf(str, "/unknown");
+ if (ret < 0 || *str == NULL)
+ return heim_enomem(context);
+ return 0;
+}
+
+static heim_error_code
+expand_username(heim_context context, PTYPE param, const char *postfix,
+ const char *arg, char **str)
+{
+ char user[128];
+ const char *username = roken_get_username(user, sizeof(user));
+
+ if (username == NULL) {
+ heim_set_error_message(context, ENOTTY,
+ N_("unable to figure out current principal",
+ ""));
+ return ENOTTY; /* XXX */
+ }
+
+ *str = strdup(username);
+ if (*str == NULL)
+ return heim_enomem(context);
+
+ return 0;
+}
+
+static heim_error_code
+expand_loginname(heim_context context, PTYPE param, const char *postfix,
+ const char *arg, char **str)
+{
+ char user[128];
+ const char *username = roken_get_loginname(user, sizeof(user));
+
+ if (username == NULL) {
+ heim_set_error_message(context, ENOTTY,
+ N_("unable to figure out current principal",
+ ""));
+ return ENOTTY; /* XXX */
+ }
+
+ *str = strdup(username);
+ if (*str == NULL)
+ return heim_enomem(context);
+
+ return 0;
+}
+
+static heim_error_code
+expand_strftime(heim_context context, PTYPE param, const char *postfix,
+ const char *arg, char **ret)
+{
+ size_t len;
+ time_t t;
+ char buf[1024];
+
+ t = time(NULL);
+ len = strftime(buf, sizeof(buf), arg, localtime(&t));
+ if (len == 0 || len >= sizeof(buf))
+ return heim_enomem(context);
+ *ret = strdup(buf);
+ return 0;
+}
+
+/**
+ * Expand an extra token
+ */
+
+static heim_error_code
+expand_extra_token(heim_context context, const char *value, char **ret)
+{
+ *ret = strdup(value);
+ if (*ret == NULL)
+ return heim_enomem(context);
+ return 0;
+}
+
+/**
+ * Expand a %{null} token
+ *
+ * The expansion of a %{null} token is always the empty string.
+ */
+
+static heim_error_code
+expand_null(heim_context context, PTYPE param, const char *postfix,
+ const char *arg, char **ret)
+{
+ *ret = strdup("");
+ if (*ret == NULL)
+ return heim_enomem(context);
+ return 0;
+}
+
+
+static const struct {
+ const char * tok;
+ int ftype;
+#define FTYPE_CSIDL 0
+#define FTYPE_SPECIAL 1
+
+ PTYPE param;
+ const char * postfix;
+
+ int (*exp_func)(heim_context, PTYPE, const char *, const char *, char **);
+
+#define SPECIALP(f, P) FTYPE_SPECIAL, 0, P, f
+#define SPECIAL(f) SPECIALP(f, NULL)
+
+} tokens[] = {
+#ifdef _WIN32
+#define CSIDLP(C,P) FTYPE_CSIDL, C, P, expand_csidl
+#define CSIDL(C) CSIDLP(C, NULL)
+
+ {"APPDATA", CSIDL(CSIDL_APPDATA)}, /* Roaming application data (for current user) */
+ {"COMMON_APPDATA", CSIDL(CSIDL_COMMON_APPDATA)}, /* Application data (all users) */
+ {"LOCAL_APPDATA", CSIDL(CSIDL_LOCAL_APPDATA)}, /* Local application data (for current user) */
+ {"SYSTEM", CSIDL(CSIDL_SYSTEM)}, /* Windows System folder (e.g. %WINDIR%\System32) */
+ {"WINDOWS", CSIDL(CSIDL_WINDOWS)}, /* Windows folder */
+ {"USERCONFIG", CSIDLP(CSIDL_APPDATA, "\\" PACKAGE)}, /* Per user Heimdal configuration file path */
+ {"COMMONCONFIG", CSIDLP(CSIDL_COMMON_APPDATA, "\\" PACKAGE)}, /* Common Heimdal configuration file path */
+ {"LIBDIR", SPECIAL(expand_bin_dir)},
+ {"BINDIR", SPECIAL(expand_bin_dir)},
+ {"LIBEXEC", SPECIAL(expand_bin_dir)},
+ {"SBINDIR", SPECIAL(expand_bin_dir)},
+#else
+ {"LOCALSTATEDIR", FTYPE_SPECIAL, 0, LOCALSTATEDIR, expand_path},
+ {"LIBDIR", FTYPE_SPECIAL, 0, LIBDIR, expand_path},
+ {"BINDIR", FTYPE_SPECIAL, 0, BINDIR, expand_path},
+ {"LIBEXEC", FTYPE_SPECIAL, 0, LIBEXECDIR, expand_path},
+ {"SBINDIR", FTYPE_SPECIAL, 0, SBINDIR, expand_path},
+ {"USERCONFIG", SPECIAL(expand_home)}, /* same as %{HOME} on not-Windows */
+ {"euid", SPECIAL(expand_euid)},
+ {"ruid", SPECIAL(expand_userid)},
+ {"loginname", SPECIAL(expand_loginname)},
+#endif
+ {"username", SPECIAL(expand_username)},
+ {"TEMP", SPECIAL(expand_temp_folder)},
+ {"USERID", SPECIAL(expand_userid)},
+ {"uid", SPECIAL(expand_userid)},
+ {"null", SPECIAL(expand_null)},
+ {"strftime", SPECIAL(expand_strftime)},
+ {"HOME", SPECIAL(expand_home)},
+};
+
+static heim_error_code
+expand_token(heim_context context,
+ const char *token,
+ const char *token_end,
+ char **extra_tokens,
+ char **ret)
+{
+ heim_error_code errcode;
+ size_t i;
+ char **p;
+ const char *colon;
+
+ *ret = NULL;
+
+ if (token[0] != '%' || token[1] != '{' || token_end[0] != '}' ||
+ token_end - token <= 2) {
+ heim_set_error_message(context, EINVAL,"Invalid token.");
+ return EINVAL;
+ }
+
+ for (p = extra_tokens; p && p[0]; p += 2) {
+ if (strncmp(token+2, p[0], (token_end - token) - 2) == 0)
+ return expand_extra_token(context, p[1], ret);
+ }
+
+ for (colon=token+2; colon < token_end; colon++)
+ if (*colon == ':')
+ break;
+
+ for (i = 0; i < sizeof(tokens)/sizeof(tokens[0]); i++)
+ if (!strncmp(token+2, tokens[i].tok, (colon - token) - 2)) {
+ char *arg = NULL;
+
+ errcode = 0;
+ if (*colon == ':') {
+ int asprintf_ret = asprintf(&arg, "%.*s",
+ (int)(token_end - colon - 1),
+ colon + 1);
+ if (asprintf_ret < 0 || !arg)
+ errcode = ENOMEM;
+ }
+ if (!errcode)
+ errcode = tokens[i].exp_func(context, tokens[i].param,
+ tokens[i].postfix, arg, ret);
+ free(arg);
+ return errcode;
+ }
+
+ heim_set_error_message(context, EINVAL, "Invalid token.");
+ return EINVAL;
+}
+
+/**
+ * Internal function to expand tokens in paths.
+ *
+ * Params:
+ *
+ * @context A heim_context
+ * @path_in The path to expand tokens from
+ * @filepath True if this is a filesystem path (converts slashes to
+ * backslashes on Windows)
+ * @ppath_out The expanded path
+ * @... Variable number of pairs of strings, the first of each
+ * being a token (e.g., "luser") and the second a string to
+ * replace it with. The list is terminated by a NULL.
+ */
+heim_error_code
+heim_expand_path_tokens(heim_context context,
+ const char *path_in,
+ int filepath,
+ char **ppath_out,
+ ...)
+{
+ heim_error_code ret;
+ va_list ap;
+
+ va_start(ap, ppath_out);
+ ret = heim_expand_path_tokensv(context, path_in, filepath, ppath_out, ap);
+ va_end(ap);
+
+ return ret;
+}
+
+static void
+free_extra_tokens(char **extra_tokens)
+{
+ char **p;
+
+ for (p = extra_tokens; p && *p; p++)
+ free(*p);
+ free(extra_tokens);
+}
+
+/**
+ * Internal function to expand tokens in paths.
+ *
+ * Inputs:
+ *
+ * @context A heim_context
+ * @path_in The path to expand tokens from
+ * @filepath True if this is a filesystem path (converts slashes to
+ * backslashes on Windows)
+ * @ppath_out The expanded path
+ * @ap A NULL-terminated va_list of pairs of strings, the first of each
+ * being a token (e.g., "luser") and the second a string to replace
+ * it with.
+ *
+ * Outputs:
+ *
+ * @ppath_out Path with expanded tokens (caller must free() this)
+ */
+heim_error_code
+heim_expand_path_tokensv(heim_context context,
+ const char *path_in,
+ int filepath,
+ char **ppath_out, va_list ap)
+{
+ char *tok_begin, *tok_end, *append;
+ char **extra_tokens = NULL;
+ const char *path_left;
+ size_t nargs = 0;
+ size_t len = 0;
+ va_list ap2;
+
+ if (path_in == NULL || *path_in == '\0') {
+ *ppath_out = strdup("");
+ return 0;
+ }
+
+ *ppath_out = NULL;
+
+#if defined(_MSC_VER)
+ ap2 = ap; /* Come on! See SO #558223 */
+#else
+ va_copy(ap2, ap);
+#endif
+ while (va_arg(ap2, const char *)) {
+ nargs++;
+ va_arg(ap2, const char *);
+ }
+ va_end(ap2);
+ nargs *= 2;
+
+ /* Get extra tokens */
+ if (nargs) {
+ size_t i;
+
+ extra_tokens = calloc(nargs + 1, sizeof (*extra_tokens));
+ if (extra_tokens == NULL)
+ return heim_enomem(context);
+ for (i = 0; i < nargs; i++) {
+ const char *s = va_arg(ap, const char *); /* token key */
+ if (s == NULL)
+ break;
+ extra_tokens[i] = strdup(s);
+ if (extra_tokens[i++] == NULL) {
+ free_extra_tokens(extra_tokens);
+ return heim_enomem(context);
+ }
+ s = va_arg(ap, const char *); /* token value */
+ if (s == NULL)
+ s = "";
+ extra_tokens[i] = strdup(s);
+ if (extra_tokens[i] == NULL) {
+ free_extra_tokens(extra_tokens);
+ return heim_enomem(context);
+ }
+ }
+ }
+
+ for (path_left = path_in; path_left && *path_left; ) {
+
+ tok_begin = strstr(path_left, "%{");
+
+ if (tok_begin && tok_begin != path_left) {
+
+ append = malloc((tok_begin - path_left) + 1);
+ if (append) {
+ memcpy(append, path_left, tok_begin - path_left);
+ append[tok_begin - path_left] = '\0';
+ }
+ path_left = tok_begin;
+
+ } else if (tok_begin) {
+
+ tok_end = strchr(tok_begin, '}');
+ if (tok_end == NULL) {
+ free_extra_tokens(extra_tokens);
+ if (*ppath_out)
+ free(*ppath_out);
+ *ppath_out = NULL;
+ heim_set_error_message(context, EINVAL, "variable missing }");
+ return EINVAL;
+ }
+
+ if (expand_token(context, tok_begin, tok_end, extra_tokens,
+ &append)) {
+ free_extra_tokens(extra_tokens);
+ if (*ppath_out)
+ free(*ppath_out);
+ *ppath_out = NULL;
+ return EINVAL;
+ }
+
+ path_left = tok_end + 1;
+ } else {
+
+ append = strdup(path_left);
+ path_left = NULL;
+
+ }
+
+ if (append == NULL) {
+
+ free_extra_tokens(extra_tokens);
+ if (*ppath_out)
+ free(*ppath_out);
+ *ppath_out = NULL;
+ return heim_enomem(context);
+
+ }
+
+ {
+ size_t append_len = strlen(append);
+ char * new_str = realloc(*ppath_out, len + append_len + 1);
+
+ if (new_str == NULL) {
+ free_extra_tokens(extra_tokens);
+ free(append);
+ if (*ppath_out)
+ free(*ppath_out);
+ *ppath_out = NULL;
+ return heim_enomem(context);
+ }
+
+ *ppath_out = new_str;
+ memcpy(*ppath_out + len, append, append_len + 1);
+ len = len + append_len;
+ free(append);
+ }
+ }
+
+#ifdef _WIN32
+ /* Also deal with slashes */
+ if (filepath && *ppath_out) {
+ char * c;
+
+ for (c = *ppath_out; *c; c++)
+ if (*c == '/')
+ *c = '\\';
+ }
+#endif
+
+ free_extra_tokens(extra_tokens);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/base/heim_err.et b/third_party/heimdal/lib/base/heim_err.et
new file mode 100644
index 0000000..5532d9b
--- /dev/null
+++ b/third_party/heimdal/lib/base/heim_err.et
@@ -0,0 +1,57 @@
+#
+# Error messages for the krb5 library
+#
+# This might look like a com_err file, but is not
+#
+id "$Id$"
+
+error_table heim
+
+prefix HEIM_ERR
+
+error_code LOG_PARSE, "Error parsing log destination"
+error_code V4_PRINC_NO_CONV, "Failed to convert v4 principal"
+error_code SALTTYPE_NOSUPP, "Salt type is not supported by enctype"
+error_code NOHOST, "Host not found"
+error_code OPNOTSUPP, "Operation not supported"
+error_code EOF, "End of file"
+error_code BAD_MKEY, "Failed to get the master key"
+error_code SERVICE_NOMATCH, "Unacceptable service used"
+error_code NOT_SEEKABLE, "File descriptor not seekable"
+error_code TOO_BIG, "Offset too large"
+error_code BAD_HDBENT_ENCODING, "Invalid HDB entry encoding"
+error_code RANDOM_OFFLINE, "No random source available"
+error_code CONFIG_BADFORMAT, "Improper format of configuration file"
+error_code PA_CONTINUE_NEEDED, "Need to continue preauth stepping"
+error_code PA_CANT_CONTINUE, "Can't continue with this preauth"
+error_code NO_MORE_PA_MECHS, "No more PA mechanisms available"
+
+index 64
+prefix HEIM_PKINIT
+error_code NO_CERTIFICATE, "Certificate missing"
+error_code NO_PRIVATE_KEY, "Private key missing"
+error_code NO_VALID_CA, "No valid certificate authority"
+error_code CERTIFICATE_INVALID, "Certificate invalid"
+error_code PRIVATE_KEY_INVALID, "Private key invalid"
+
+index 128
+prefix HEIM_EAI
+#error_code NOERROR, "no error"
+error_code UNKNOWN, "unknown error from getaddrinfo"
+error_code ADDRFAMILY, "address family for nodename not supported"
+error_code AGAIN, "temporary failure in name resolution"
+error_code BADFLAGS, "invalid value for ai_flags"
+error_code FAIL, "non-recoverable failure in name resolution"
+error_code FAMILY, "ai_family not supported"
+error_code MEMORY, "memory allocation failure"
+error_code NODATA, "no address associated with nodename"
+error_code NONAME, "nodename nor servname provided, or not known"
+error_code SERVICE, "servname not supported for ai_socktype"
+error_code SOCKTYPE, "ai_socktype not supported"
+error_code SYSTEM, "system error returned in errno"
+
+index 192
+prefix HEIM_NET
+error_code CONN_REFUSED, "connection refused"
+
+end
diff --git a/third_party/heimdal/lib/base/heimbase-atomics.h b/third_party/heimdal/lib/base/heimbase-atomics.h
new file mode 100644
index 0000000..58b72ac
--- /dev/null
+++ b/third_party/heimdal/lib/base/heimbase-atomics.h
@@ -0,0 +1,255 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef HEIM_BASE_ATOMICS_H
+#define HEIM_BASE_ATOMICS_H 1
+
+#include "config.h"
+
+/*
+ * Atomic operations
+ */
+
+#if defined(HAVE_STDATOMIC_H)
+
+#include <stdatomic.h>
+
+#define heim_base_atomic_init(t, v) atomic_init(t, v)
+#define heim_base_atomic_load(x) atomic_load((x))
+#define heim_base_atomic_store(t, v) atomic_store((t), (v))
+
+#define heim_base_atomic(T) _Atomic(T)
+
+#define heim_base_atomic_inc(x) (atomic_fetch_add((x), 1) + 1)
+#define heim_base_atomic_dec(x) (atomic_fetch_sub((x), 1) - 1)
+#define heim_base_atomic_integer_type heim_base_atomic(unsigned int)
+#define heim_base_atomic_integer_max UINT_MAX
+
+#define heim_base_exchange_pointer(t,v) atomic_exchange((t), (v))
+#define heim_base_exchange_32(t,v) atomic_exchange((t), (v))
+#define heim_base_exchange_64(t,v) atomic_exchange((t), (v))
+
+#elif defined(__GNUC__) && defined(HAVE___SYNC_ADD_AND_FETCH)
+
+#define heim_base_atomic_barrier() __sync_synchronize()
+
+#define heim_base_atomic_inc(x) __sync_add_and_fetch((x), 1)
+#define heim_base_atomic_dec(x) __sync_sub_and_fetch((x), 1)
+#define heim_base_atomic_integer_type unsigned int
+#define heim_base_atomic_integer_max UINT_MAX
+
+#ifndef __has_builtin
+#define __has_builtin(x) 0
+#endif
+
+#if __has_builtin(__sync_swap)
+#define heim_base_exchange_pointer(t,v) __sync_swap((t), (v))
+#else
+/* FIXME: some targets may only write the value 1 into *t */
+#define heim_base_exchange_pointer(t,v) __sync_lock_test_and_set((t), (v))
+#endif
+
+#define heim_base_exchange_32(t,v) heim_base_exchange_pointer((t), (v))
+#define heim_base_exchange_64(t,v) heim_base_exchange_pointer((t), (v))
+
+#elif defined(__sun)
+
+#include <sys/atomic.h>
+
+#define heim_base_atomic_barrier() __machine_rw_barrier()
+
+#define heim_base_atomic_inc(x) atomic_inc_uint_nv((volatile uint_t *)(x))
+#define heim_base_atomic_dec(x) atomic_dec_uint_nv((volatile uint_t *)(x))
+#define heim_base_atomic_integer_type uint_t
+#define heim_base_atomic_integer_max UINT_MAX
+
+#define heim_base_exchange_pointer(t,v) atomic_swap_ptr((volatile void *)(t), (void *)(v))
+#define heim_base_exchange_32(t,v) atomic_swap_32((volatile uint32_t *)(t), (v))
+#define heim_base_exchange_64(t,v) atomic_swap_64((volatile uint64_t *)(t), (v))
+
+#elif defined(_AIX)
+
+#include <sys/atomic_op.h>
+
+#define heim_base_atomic_barrier() __isync()
+
+#define heim_base_atomic_inc(x) (fetch_and_add((atomic_p)(x)) + 1)
+#define heim_base_atomic_dec(x) (fetch_and_add((atomic_p)(x)) - 1)
+#define heim_base_atomic_integer_type unsigned int
+#define heim_base_atomic_integer_max UINT_MAX
+
+static inline void *
+heim_base_exchange_pointer(void *p, void *newval)
+{
+ void *val = *(void **)p;
+
+ while (!compare_and_swaplp((atomic_l)p, (long *)&val, (long)newval))
+ ;
+
+ return val;
+}
+
+static inline uint32_t
+heim_base_exchange_32(uint32_t *p, uint32_t newval)
+{
+ uint32_t val = *p;
+
+ while (!compare_and_swap((atomic_p)p, (int *)&val, (int)newval))
+ ;
+
+ return val;
+}
+
+static inline uint64_t
+heim_base_exchange_64(uint64_t *p, uint64_t newval)
+{
+ uint64_t val = *p;
+
+ while (!compare_and_swaplp((atomic_l)p, (long *)&val, (long)newval))
+ ;
+
+ return val;
+}
+
+#elif defined(_WIN32)
+
+#define heim_base_atomic_barrier() MemoryBarrier()
+
+#define heim_base_atomic_inc(x) InterlockedIncrement(x)
+#define heim_base_atomic_dec(x) InterlockedDecrement(x)
+#define heim_base_atomic_integer_type LONG
+#define heim_base_atomic_integer_max MAXLONG
+
+#define heim_base_exchange_pointer(t,v) InterlockedExchangePointer((PVOID volatile *)(t), (PVOID)(v))
+#define heim_base_exchange_32(t,v) ((ULONG)InterlockedExchange((LONG volatile *)(t), (LONG)(v)))
+#define heim_base_exchange_64(t,v) ((ULONG64)InterlockedExchange64((LONG64 violatile *)(t), (LONG64)(v)))
+
+#else
+
+#include <heim_threads.h>
+
+#define HEIM_BASE_NEED_ATOMIC_MUTEX 1
+extern HEIMDAL_MUTEX _heim_base_mutex;
+
+#define heim_base_atomic_integer_type unsigned int
+#define heim_base_atomic_integer_max UINT_MAX
+
+static inline heim_base_atomic_integer_type
+heim_base_atomic_inc(heim_base_atomic_integer_type *x)
+{
+ heim_base_atomic_integer_type t;
+ HEIMDAL_MUTEX_lock(&_heim_base_mutex);
+ t = ++(*x);
+ HEIMDAL_MUTEX_unlock(&_heim_base_mutex);
+ return t;
+}
+
+static inline heim_base_atomic_integer_type
+heim_base_atomic_dec(heim_base_atomic_integer_type *x)
+{
+ heim_base_atomic_integer_type t;
+ HEIMDAL_MUTEX_lock(&_heim_base_mutex);
+ t = --(*x);
+ HEIMDAL_MUTEX_unlock(&_heim_base_mutex);
+ return t;
+}
+
+static inline void *
+heim_base_exchange_pointer(void *target, void *value)
+{
+ void *old;
+ HEIMDAL_MUTEX_lock(&_heim_base_mutex);
+ old = *(void **)target;
+ *(void **)target = value;
+ HEIMDAL_MUTEX_unlock(&_heim_base_mutex);
+ return old;
+}
+
+static inline uint32_t
+heim_base_exchange_32(uint32_t *p, uint32_t newval)
+{
+ uint32_t old;
+ HEIMDAL_MUTEX_lock(&_heim_base_mutex);
+ old = *p;
+ *p = newval;
+ HEIMDAL_MUTEX_unlock(&_heim_base_mutex);
+ return old;
+}
+
+static inline uint64_t
+heim_base_exchange_64(uint64_t *p, uint64_t newval)
+{
+ uint64_t old;
+ HEIMDAL_MUTEX_lock(&_heim_base_mutex);
+ old = *p;
+ *p = newval;
+ HEIMDAL_MUTEX_unlock(&_heim_base_mutex);
+ return old;
+}
+
+#endif /* defined(__GNUC__) && defined(HAVE___SYNC_ADD_AND_FETCH) */
+
+#ifndef heim_base_atomic
+#define heim_base_atomic(T) T
+#endif
+
+#ifndef heim_base_atomic_barrier
+#define heim_base_atomic_barrier()
+#endif
+
+#ifndef heim_base_atomic_load
+#define heim_base_atomic_load(x) (heim_base_atomic_barrier(), *(x))
+#endif
+
+#ifndef heim_base_atomic_init
+#define heim_base_atomic_init(t, v) do { (*(t) = (v)); } while (0)
+#endif
+
+#ifndef heim_base_atomic_store
+#define heim_base_atomic_store(t, v) do { \
+ (*(t) = (v)); \
+ heim_base_atomic_barrier(); \
+ } while (0)
+#endif
+
+#if SIZEOF_TIME_T == 8
+#define heim_base_exchange_time_t(t,v) heim_base_exchange_64((t), (v))
+#elif SIZEOF_TIME_T == 4
+#define heim_base_exchange_time_t(t,v) heim_base_exchange_32((t), (v))
+#else
+#error set SIZEOF_TIME_T for your platform
+#endif
+
+#endif /* HEIM_BASE_ATOMICS_H */
diff --git a/third_party/heimdal/lib/base/heimbase-svc.h b/third_party/heimdal/lib/base/heimbase-svc.h
new file mode 100644
index 0000000..0e7454c
--- /dev/null
+++ b/third_party/heimdal/lib/base/heimbase-svc.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef HEIMBASE_SVC_H
+#define HEIMBASE_SVC_H 1
+
+#include <heimbase.h>
+
+/*
+ * This file is meant to be included in services, which can
+ *
+ * #define heim_pcontext krb5_context
+ *
+ * or whatever is appropriate.
+ */
+
+#define HEIM_SVC_REQUEST_DESC_COMMON_ELEMENTS \
+ /* Input */ \
+ heim_pcontext context; \
+ heim_pconfig config; \
+ heim_context hcontext; \
+ heim_log_facility *logf; \
+ const char *from; \
+ struct sockaddr *addr; \
+ int datagram_reply; \
+ heim_octet_string request; \
+ \
+ /* Output */ \
+ heim_octet_string *reply; \
+ unsigned int use_request_t:1; \
+ \
+ /* Common state, to be freed in process.c */ \
+ struct timeval tv_start; \
+ struct timeval tv_end; \
+ const char *reqtype; \
+ char *cname; \
+ char *sname; \
+ const char *e_text; \
+ char *e_text_buf; \
+ heim_string_t reason; \
+ /* auditing key/value store */ \
+ heim_dict_t kv; \
+ heim_dict_t attributes; \
+ int32_t error_code
+
+#define HEIM_PLUGIN_FTABLE_COMMON_ELEMENTS(CONTEXT_TYPE) \
+ int minor_version; \
+ int (HEIM_LIB_CALL *init)(CONTEXT_TYPE, void **); \
+ void (HEIM_LIB_CALL *fini)(void *)
+
+#endif /* HEIMBASE_SVC_H */
diff --git a/third_party/heimdal/lib/base/heimbase.c b/third_party/heimdal/lib/base/heimbase.c
new file mode 100644
index 0000000..1e6805a
--- /dev/null
+++ b/third_party/heimdal/lib/base/heimbase.c
@@ -0,0 +1,1081 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+#include <syslog.h>
+
+static heim_base_atomic_integer_type tidglobal = HEIM_TID_USER;
+
+struct heim_base {
+ heim_type_t isa;
+ heim_base_atomic_integer_type ref_cnt;
+ HEIM_TAILQ_ENTRY(heim_base) autorel;
+ heim_auto_release_t autorelpool;
+ uintptr_t isaextra[3];
+};
+
+/* specialized version of base */
+struct heim_base_mem {
+ heim_type_t isa;
+ heim_base_atomic_integer_type ref_cnt;
+ HEIM_TAILQ_ENTRY(heim_base) autorel;
+ heim_auto_release_t autorelpool;
+ const char *name;
+ void (HEIM_CALLCONV *dealloc)(void *);
+ uintptr_t isaextra[1];
+};
+
+#define PTR2BASE(ptr) (((struct heim_base *)ptr) - 1)
+#define BASE2PTR(ptr) ((void *)(((struct heim_base *)ptr) + 1))
+
+#ifdef HEIM_BASE_NEED_ATOMIC_MUTEX
+HEIMDAL_MUTEX _heim_base_mutex = HEIMDAL_MUTEX_INITIALIZER;
+#endif
+
+/*
+ * Auto release structure
+ */
+
+struct heim_auto_release {
+ HEIM_TAILQ_HEAD(, heim_base) pool;
+ HEIMDAL_MUTEX pool_mutex;
+ struct heim_auto_release *parent;
+};
+
+
+/**
+ * Retain object (i.e., take a reference)
+ *
+ * @param object to be released, NULL is ok
+ *
+ * @return the same object as passed in
+ */
+
+heim_object_t
+heim_retain(heim_object_t ptr)
+{
+ struct heim_base *p;
+
+ if (ptr == NULL || heim_base_is_tagged(ptr))
+ return ptr;
+
+ p = PTR2BASE(ptr);
+
+ if (heim_base_atomic_load(&p->ref_cnt) == heim_base_atomic_integer_max)
+ return ptr;
+
+ if ((heim_base_atomic_inc(&p->ref_cnt) - 1) == 0)
+ heim_abort("resurection");
+ return ptr;
+}
+
+/**
+ * Release object, free if reference count reaches zero
+ *
+ * @param object to be released
+ */
+
+void
+heim_release(void *ptr)
+{
+ heim_base_atomic_integer_type old;
+ struct heim_base *p;
+
+ if (ptr == NULL || heim_base_is_tagged(ptr))
+ return;
+
+ p = PTR2BASE(ptr);
+
+ if (heim_base_atomic_load(&p->ref_cnt) == heim_base_atomic_integer_max)
+ return;
+
+ old = heim_base_atomic_dec(&p->ref_cnt) + 1;
+
+ if (old > 1)
+ return;
+
+ if (old == 1) {
+ heim_auto_release_t ar = p->autorelpool;
+ /* remove from autorel pool list */
+ if (ar) {
+ p->autorelpool = NULL;
+ HEIMDAL_MUTEX_lock(&ar->pool_mutex);
+ HEIM_TAILQ_REMOVE(&ar->pool, p, autorel);
+ HEIMDAL_MUTEX_unlock(&ar->pool_mutex);
+ }
+ if (p->isa->dealloc)
+ p->isa->dealloc(ptr);
+ free(p);
+ } else
+ heim_abort("over release");
+}
+
+/**
+ * If used require wrapped in autorelease pool
+ */
+
+heim_string_t
+heim_description(heim_object_t ptr)
+{
+ struct heim_base *p = PTR2BASE(ptr);
+ if (p->isa->desc == NULL)
+ return heim_auto_release(heim_string_ref_create(p->isa->name, NULL));
+ return heim_auto_release(p->isa->desc(ptr));
+}
+
+
+void
+_heim_make_permanent(heim_object_t ptr)
+{
+ struct heim_base *p = PTR2BASE(ptr);
+ heim_base_atomic_store(&p->ref_cnt, heim_base_atomic_integer_max);
+}
+
+
+static heim_type_t tagged_isa[9] = {
+ &_heim_number_object,
+ &_heim_null_object,
+ &_heim_bool_object,
+
+ NULL,
+ NULL,
+ NULL,
+
+ NULL,
+ NULL,
+ NULL
+};
+
+heim_type_t
+_heim_get_isa(heim_object_t ptr)
+{
+ struct heim_base *p;
+ if (heim_base_is_tagged(ptr)) {
+ if (heim_base_is_tagged_object(ptr))
+ return tagged_isa[heim_base_tagged_object_tid(ptr)];
+ heim_abort("not a supported tagged type");
+ }
+ p = PTR2BASE(ptr);
+ return p->isa;
+}
+
+/**
+ * Get type ID of object
+ *
+ * @param object object to get type id of
+ *
+ * @return type id of object
+ */
+
+heim_tid_t
+heim_get_tid(heim_object_t ptr)
+{
+ heim_type_t isa = _heim_get_isa(ptr);
+ return isa->tid;
+}
+
+/**
+ * Get hash value of object
+ *
+ * @param object object to get hash value for
+ *
+ * @return a hash value
+ */
+
+uintptr_t
+heim_get_hash(heim_object_t ptr)
+{
+ heim_type_t isa = _heim_get_isa(ptr);
+ if (isa->hash)
+ return isa->hash(ptr);
+ return (uintptr_t)ptr;
+}
+
+/**
+ * Compare two objects, returns 0 if equal, can use used for qsort()
+ * and friends.
+ *
+ * @param a first object to compare
+ * @param b first object to compare
+ *
+ * @return 0 if objects are equal
+ */
+
+int
+heim_cmp(heim_object_t a, heim_object_t b)
+{
+ heim_tid_t ta, tb;
+ heim_type_t isa;
+
+ ta = heim_get_tid(a);
+ tb = heim_get_tid(b);
+
+ if (ta != tb)
+ return ta - tb;
+
+ isa = _heim_get_isa(a);
+
+ if (isa->cmp)
+ return isa->cmp(a, b);
+
+ return (uintptr_t)a - (uintptr_t)b;
+}
+
+/*
+ * Private - allocates an memory object
+ */
+
+static void HEIM_CALLCONV
+memory_dealloc(void *ptr)
+{
+ struct heim_base_mem *p = (struct heim_base_mem *)PTR2BASE(ptr);
+ if (p->dealloc)
+ p->dealloc(ptr);
+}
+
+struct heim_type_data memory_object = {
+ HEIM_TID_MEMORY,
+ "memory-object",
+ NULL,
+ memory_dealloc,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+/**
+ * Allocate memory for an object of anonymous type
+ *
+ * @param size size of object to be allocated
+ * @param name name of ad-hoc type
+ * @param dealloc destructor function
+ *
+ * Objects allocated with this interface do not serialize.
+ *
+ * @return allocated object
+ */
+
+void *
+heim_alloc(size_t size, const char *name, heim_type_dealloc dealloc)
+{
+ /* XXX use posix_memalign */
+
+ struct heim_base_mem *p = calloc(1, size + sizeof(*p));
+ if (p == NULL)
+ return NULL;
+ p->isa = &memory_object;
+ p->ref_cnt = 1;
+ p->name = name;
+ p->dealloc = dealloc;
+ return BASE2PTR(p);
+}
+
+heim_type_t
+_heim_create_type(const char *name,
+ heim_type_init init,
+ heim_type_dealloc dealloc,
+ heim_type_copy copy,
+ heim_type_cmp cmp,
+ heim_type_hash hash,
+ heim_type_description desc)
+{
+ heim_type_t type;
+
+ type = calloc(1, sizeof(*type));
+ if (type == NULL)
+ return NULL;
+
+ type->tid = heim_base_atomic_inc(&tidglobal);
+ type->name = name;
+ type->init = init;
+ type->dealloc = dealloc;
+ type->copy = copy;
+ type->cmp = cmp;
+ type->hash = hash;
+ type->desc = desc;
+
+ return type;
+}
+
+heim_object_t
+_heim_alloc_object(heim_type_t type, size_t size)
+{
+ /* XXX should use posix_memalign */
+ struct heim_base *p = calloc(1, size + sizeof(*p));
+ if (p == NULL)
+ return NULL;
+ p->isa = type;
+ p->ref_cnt = 1;
+
+ return BASE2PTR(p);
+}
+
+void *
+_heim_get_isaextra(heim_object_t ptr, size_t idx)
+{
+ struct heim_base *p;
+
+ heim_assert(ptr != NULL, "internal error");
+ p = (struct heim_base *)PTR2BASE(ptr);
+ if (p->isa == &memory_object)
+ return NULL;
+ heim_assert(idx < 3, "invalid private heim_base extra data index");
+ return &p->isaextra[idx];
+}
+
+heim_tid_t
+_heim_type_get_tid(heim_type_t type)
+{
+ return type->tid;
+}
+
+#if !defined(WIN32) && !defined(HAVE_DISPATCH_DISPATCH_H) && defined(ENABLE_PTHREAD_SUPPORT)
+static pthread_once_t once_arg_key_once = PTHREAD_ONCE_INIT;
+static pthread_key_t once_arg_key;
+
+static void
+once_arg_key_once_init(void)
+{
+ errno = pthread_key_create(&once_arg_key, NULL);
+ if (errno != 0) {
+ fprintf(stderr,
+ "Error: pthread_key_create() failed, cannot continue: %s\n",
+ strerror(errno));
+ abort();
+ }
+}
+
+struct once_callback {
+ void (*fn)(void *);
+ void *data;
+};
+
+static void
+once_callback_caller(void)
+{
+ struct once_callback *once_callback = pthread_getspecific(once_arg_key);
+
+ if (once_callback == NULL) {
+ fprintf(stderr, "Error: pthread_once() calls callback on "
+ "different thread?! Cannot continue.\n");
+ abort();
+ }
+ once_callback->fn(once_callback->data);
+}
+#endif
+
+/**
+ * Call func once and only once
+ *
+ * @param once pointer to a heim_base_once_t
+ * @param ctx context passed to func
+ * @param func function to be called
+ */
+
+void
+heim_base_once_f(heim_base_once_t *once, void *ctx, void (*func)(void *))
+{
+#if defined(WIN32)
+ /*
+ * With a libroken wrapper for some CAS function and a libroken yield()
+ * wrapper we could make this the default implementation when we have
+ * neither Grand Central nor POSX threads.
+ *
+ * We could also adapt the double-checked lock pattern with CAS
+ * providing the necessary memory barriers in the absence of
+ * portable explicit memory barrier APIs.
+ */
+ /*
+ * We use CAS operations in large part to provide implied memory
+ * barriers.
+ *
+ * State 0 means that func() has never executed.
+ * State 1 means that func() is executing.
+ * State 2 means that func() has completed execution.
+ */
+ if (InterlockedCompareExchange(once, 1L, 0L) == 0L) {
+ /* State is now 1 */
+ (*func)(ctx);
+ (void)InterlockedExchange(once, 2L);
+ /* State is now 2 */
+ } else {
+ /*
+ * The InterlockedCompareExchange is being used to fetch
+ * the current state under a full memory barrier. As long
+ * as the current state is 1 continue to spin.
+ */
+ while (InterlockedCompareExchange(once, 2L, 0L) == 1L)
+ SwitchToThread();
+ }
+#elif defined(HAVE_DISPATCH_DISPATCH_H)
+ dispatch_once_f(once, ctx, func);
+#elif defined(ENABLE_PTHREAD_SUPPORT)
+ struct once_callback once_callback;
+
+ once_callback.fn = func;
+ once_callback.data = ctx;
+
+ errno = pthread_once(&once_arg_key_once, once_arg_key_once_init);
+ if (errno != 0) {
+ fprintf(stderr, "Error: pthread_once() failed, cannot continue: %s\n",
+ strerror(errno));
+ abort();
+ }
+ errno = pthread_setspecific(once_arg_key, &once_callback);
+ if (errno != 0) {
+ fprintf(stderr,
+ "Error: pthread_setspecific() failed, cannot continue: %s\n",
+ strerror(errno));
+ abort();
+ }
+ errno = pthread_once(once, once_callback_caller);
+ if (errno != 0) {
+ fprintf(stderr, "Error: pthread_once() failed, cannot continue: %s\n",
+ strerror(errno));
+ abort();
+ }
+#else
+ static HEIMDAL_MUTEX mutex = HEIMDAL_MUTEX_INITIALIZER;
+ HEIMDAL_MUTEX_lock(&mutex);
+ if (*once == 0) {
+ *once = 1;
+ HEIMDAL_MUTEX_unlock(&mutex);
+ func(ctx);
+ HEIMDAL_MUTEX_lock(&mutex);
+ *once = 2;
+ HEIMDAL_MUTEX_unlock(&mutex);
+ } else if (*once == 2) {
+ HEIMDAL_MUTEX_unlock(&mutex);
+ } else {
+ HEIMDAL_MUTEX_unlock(&mutex);
+ while (1) {
+ struct timeval tv = { 0, 1000 };
+ select(0, NULL, NULL, NULL, &tv);
+ HEIMDAL_MUTEX_lock(&mutex);
+ if (*once == 2)
+ break;
+ HEIMDAL_MUTEX_unlock(&mutex);
+ }
+ HEIMDAL_MUTEX_unlock(&mutex);
+ }
+#endif
+}
+
+/**
+ * Abort and log the failure (using syslog)
+ */
+
+void
+heim_abort(const char *fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ heim_abortv(fmt, ap);
+ va_end(ap);
+}
+
+/**
+ * Abort and log the failure (using syslog)
+ */
+
+void
+heim_abortv(const char *fmt, va_list ap)
+{
+ static char str[1024];
+
+ vsnprintf(str, sizeof(str), fmt, ap);
+ syslog(LOG_ERR, "heim_abort: %s", str);
+ abort();
+}
+
+/*
+ *
+ */
+
+static int ar_created = 0;
+static HEIMDAL_thread_key ar_key;
+
+struct ar_tls {
+ struct heim_auto_release *head;
+ struct heim_auto_release *current;
+ HEIMDAL_MUTEX tls_mutex;
+};
+
+static void
+ar_tls_delete(void *ptr)
+{
+ struct ar_tls *tls = ptr;
+ heim_auto_release_t next = NULL;
+
+ if (tls == NULL)
+ return;
+ for (; tls->current != NULL; tls->current = next) {
+ next = tls->current->parent;
+ heim_release(tls->current);
+ }
+ free(tls);
+}
+
+static void
+init_ar_tls(void *ptr)
+{
+ int ret;
+ HEIMDAL_key_create(&ar_key, ar_tls_delete, ret);
+ if (ret == 0)
+ ar_created = 1;
+}
+
+static struct ar_tls *
+autorel_tls(void)
+{
+ static heim_base_once_t once = HEIM_BASE_ONCE_INIT;
+ struct ar_tls *arp;
+ int ret;
+
+ heim_base_once_f(&once, NULL, init_ar_tls);
+ if (!ar_created)
+ return NULL;
+
+ arp = HEIMDAL_getspecific(ar_key);
+ if (arp == NULL) {
+
+ arp = calloc(1, sizeof(*arp));
+ if (arp == NULL)
+ return NULL;
+ HEIMDAL_setspecific(ar_key, arp, ret);
+ if (ret) {
+ free(arp);
+ return NULL;
+ }
+ }
+ return arp;
+
+}
+
+static void HEIM_CALLCONV
+autorel_dealloc(void *ptr)
+{
+ heim_auto_release_t ar = ptr;
+ struct ar_tls *tls;
+
+ tls = autorel_tls();
+ if (tls == NULL)
+ heim_abort("autorelease pool released on thread w/o autorelease inited");
+
+ heim_auto_release_drain(ar);
+
+ if (!HEIM_TAILQ_EMPTY(&ar->pool))
+ heim_abort("pool not empty after draining");
+
+ HEIMDAL_MUTEX_lock(&tls->tls_mutex);
+ if (tls->current != ptr)
+ heim_abort("autorelease not releaseing top pool");
+
+ tls->current = ar->parent;
+ HEIMDAL_MUTEX_unlock(&tls->tls_mutex);
+}
+
+static int
+autorel_cmp(void *a, void *b)
+{
+ return (a == b);
+}
+
+static uintptr_t
+autorel_hash(void *ptr)
+{
+ return (uintptr_t)ptr;
+}
+
+
+static struct heim_type_data _heim_autorel_object = {
+ HEIM_TID_AUTORELEASE,
+ "autorelease-pool",
+ NULL,
+ autorel_dealloc,
+ NULL,
+ autorel_cmp,
+ autorel_hash,
+ NULL
+};
+
+/**
+ * Create thread-specific object auto-release pool
+ *
+ * Objects placed on the per-thread auto-release pool (with
+ * heim_auto_release()) can be released in one fell swoop by calling
+ * heim_auto_release_drain().
+ */
+
+heim_auto_release_t
+heim_auto_release_create(void)
+{
+ struct ar_tls *tls = autorel_tls();
+ heim_auto_release_t ar;
+
+ if (tls == NULL)
+ heim_abort("Failed to create/get autorelease head");
+
+ ar = _heim_alloc_object(&_heim_autorel_object, sizeof(struct heim_auto_release));
+ if (ar) {
+ HEIMDAL_MUTEX_lock(&tls->tls_mutex);
+ if (tls->head == NULL)
+ tls->head = ar;
+ ar->parent = tls->current;
+ tls->current = ar;
+ HEIMDAL_MUTEX_unlock(&tls->tls_mutex);
+ }
+
+ return ar;
+}
+
+/**
+ * Place the current object on the thread's auto-release pool
+ *
+ * @param ptr object
+ */
+
+heim_object_t
+heim_auto_release(heim_object_t ptr)
+{
+ struct heim_base *p;
+ struct ar_tls *tls = autorel_tls();
+ heim_auto_release_t ar;
+
+ if (ptr == NULL || heim_base_is_tagged(ptr))
+ return ptr;
+
+ p = PTR2BASE(ptr);
+
+ /* drop from old pool */
+ if ((ar = p->autorelpool) != NULL) {
+ HEIMDAL_MUTEX_lock(&ar->pool_mutex);
+ HEIM_TAILQ_REMOVE(&ar->pool, p, autorel);
+ p->autorelpool = NULL;
+ HEIMDAL_MUTEX_unlock(&ar->pool_mutex);
+ }
+
+ if (tls == NULL || (ar = tls->current) == NULL)
+ heim_abort("no auto relase pool in place, would leak");
+
+ HEIMDAL_MUTEX_lock(&ar->pool_mutex);
+ HEIM_TAILQ_INSERT_HEAD(&ar->pool, p, autorel);
+ p->autorelpool = ar;
+ HEIMDAL_MUTEX_unlock(&ar->pool_mutex);
+
+ return ptr;
+}
+
+/**
+ * Release all objects on the given auto-release pool
+ */
+
+void
+heim_auto_release_drain(heim_auto_release_t autorel)
+{
+ heim_object_t obj;
+
+ /* release all elements on the tail queue */
+
+ HEIMDAL_MUTEX_lock(&autorel->pool_mutex);
+ while(!HEIM_TAILQ_EMPTY(&autorel->pool)) {
+ obj = HEIM_TAILQ_FIRST(&autorel->pool);
+ HEIMDAL_MUTEX_unlock(&autorel->pool_mutex);
+ heim_release(BASE2PTR(obj));
+ HEIMDAL_MUTEX_lock(&autorel->pool_mutex);
+ }
+ HEIMDAL_MUTEX_unlock(&autorel->pool_mutex);
+}
+
+/*
+ * Helper for heim_path_vget() and heim_path_delete(). On success
+ * outputs the node named by the path and the parent node and key
+ * (useful for heim_path_delete()).
+ */
+
+static heim_object_t
+heim_path_vget2(heim_object_t ptr, heim_object_t *parent, heim_object_t *key,
+ heim_error_t *error, va_list ap)
+{
+ heim_object_t path_element;
+ heim_object_t node, next_node;
+ heim_tid_t node_type;
+
+ *parent = NULL;
+ *key = NULL;
+ if (ptr == NULL)
+ return NULL;
+
+ for (node = ptr; node != NULL; ) {
+ path_element = va_arg(ap, heim_object_t);
+ if (path_element == NULL) {
+ *parent = node;
+ *key = path_element;
+ return node;
+ }
+
+ node_type = heim_get_tid(node);
+ switch (node_type) {
+ case HEIM_TID_ARRAY:
+ case HEIM_TID_DICT:
+ case HEIM_TID_DB:
+ break;
+ default:
+ if (node == ptr)
+ heim_abort("heim_path_get() only operates on container types");
+ return NULL;
+ }
+
+ if (node_type == HEIM_TID_DICT) {
+ next_node = heim_dict_get_value(node, path_element);
+ } else if (node_type == HEIM_TID_DB) {
+ next_node = _heim_db_get_value(node, NULL, path_element, NULL);
+ } else {
+ int idx = -1;
+
+ /* node_type == HEIM_TID_ARRAY */
+ if (heim_get_tid(path_element) == HEIM_TID_NUMBER)
+ idx = heim_number_get_int(path_element);
+ if (idx < 0) {
+ if (error)
+ *error = heim_error_create(EINVAL,
+ "heim_path_get() path elements "
+ "for array nodes must be "
+ "numeric and positive");
+ return NULL;
+ }
+ next_node = heim_array_get_value(node, idx);
+ }
+ node = next_node;
+ }
+ return NULL;
+}
+
+/**
+ * Get a node in a heim_object tree by path
+ *
+ * @param ptr tree
+ * @param error error (output)
+ * @param ap NULL-terminated va_list of heim_object_ts that form a path
+ *
+ * @return object (not retained) if found
+ *
+ * @addtogroup heimbase
+ */
+
+heim_object_t
+heim_path_vget(heim_object_t ptr, heim_error_t *error, va_list ap)
+{
+ heim_object_t p, k;
+
+ return heim_path_vget2(ptr, &p, &k, error, ap);
+}
+
+/**
+ * Get a node in a tree by path, with retained reference
+ *
+ * @param ptr tree
+ * @param error error (output)
+ * @param ap NULL-terminated va_list of heim_object_ts that form a path
+ *
+ * @return retained object if found
+ *
+ * @addtogroup heimbase
+ */
+
+heim_object_t
+heim_path_vcopy(heim_object_t ptr, heim_error_t *error, va_list ap)
+{
+ heim_object_t p, k;
+
+ return heim_retain(heim_path_vget2(ptr, &p, &k, error, ap));
+}
+
+/**
+ * Get a node in a tree by path
+ *
+ * @param ptr tree
+ * @param error error (output)
+ * @param ... NULL-terminated va_list of heim_object_ts that form a path
+ *
+ * @return object (not retained) if found
+ *
+ * @addtogroup heimbase
+ */
+
+heim_object_t
+heim_path_get(heim_object_t ptr, heim_error_t *error, ...)
+{
+ heim_object_t o;
+ heim_object_t p, k;
+ va_list ap;
+
+ if (ptr == NULL)
+ return NULL;
+
+ va_start(ap, error);
+ o = heim_path_vget2(ptr, &p, &k, error, ap);
+ va_end(ap);
+ return o;
+}
+
+/**
+ * Get a node in a tree by path, with retained reference
+ *
+ * @param ptr tree
+ * @param error error (output)
+ * @param ... NULL-terminated va_list of heim_object_ts that form a path
+ *
+ * @return retained object if found
+ *
+ * @addtogroup heimbase
+ */
+
+heim_object_t
+heim_path_copy(heim_object_t ptr, heim_error_t *error, ...)
+{
+ heim_object_t o;
+ heim_object_t p, k;
+ va_list ap;
+
+ if (ptr == NULL)
+ return NULL;
+
+ va_start(ap, error);
+ o = heim_retain(heim_path_vget2(ptr, &p, &k, error, ap));
+ va_end(ap);
+ return o;
+}
+
+/**
+ * Create a path in a heim_object_t tree
+ *
+ * @param ptr the tree
+ * @param size the size of the heim_dict_t nodes to be created
+ * @param leaf leaf node to be added, if any
+ * @param error error (output)
+ * @param ap NULL-terminated of path component objects
+ *
+ * Create a path of heim_dict_t interior nodes in a given heim_object_t
+ * tree, as necessary, and set/replace a leaf, if given (if leaf is NULL
+ * then the leaf is not deleted).
+ *
+ * @return 0 on success, else a system error
+ *
+ * @addtogroup heimbase
+ */
+
+int
+heim_path_vcreate(heim_object_t ptr, size_t size, heim_object_t leaf,
+ heim_error_t *error, va_list ap)
+{
+ heim_object_t path_element = va_arg(ap, heim_object_t);
+ heim_object_t next_path_element = NULL;
+ heim_object_t node = ptr;
+ heim_object_t next_node = NULL;
+ heim_tid_t node_type;
+ int ret = 0;
+
+ if (ptr == NULL)
+ heim_abort("heim_path_vcreate() does not create root nodes");
+
+ while (path_element != NULL) {
+ next_path_element = va_arg(ap, heim_object_t);
+ node_type = heim_get_tid(node);
+
+ if (node_type == HEIM_TID_DICT) {
+ next_node = heim_dict_get_value(node, path_element);
+ } else if (node_type == HEIM_TID_ARRAY) {
+ int idx = -1;
+
+ if (heim_get_tid(path_element) == HEIM_TID_NUMBER)
+ idx = heim_number_get_int(path_element);
+ if (idx < 0) {
+ if (error)
+ *error = heim_error_create(EINVAL,
+ "heim_path() path elements for "
+ "array nodes must be numeric "
+ "and positive");
+ return EINVAL;
+ }
+ if (idx < heim_array_get_length(node))
+ next_node = heim_array_get_value(node, idx);
+ else
+ next_node = NULL;
+ } else if (node_type == HEIM_TID_DB && next_path_element != NULL) {
+ if (error)
+ *error = heim_error_create(EINVAL, "Interior node is a DB");
+ return EINVAL;
+ }
+
+ if (next_path_element == NULL)
+ break;
+
+ /* Create missing interior node */
+ if (next_node == NULL) {
+ next_node = heim_dict_create(size); /* no arrays or DBs, just dicts */
+ if (next_node == NULL) {
+ ret = ENOMEM;
+ goto err;
+ }
+
+ if (node_type == HEIM_TID_DICT) {
+ ret = heim_dict_set_value(node, path_element, next_node);
+ } else if (node_type == HEIM_TID_ARRAY &&
+ heim_number_get_int(path_element) <= heim_array_get_length(node)) {
+ ret = heim_array_insert_value(node,
+ heim_number_get_int(path_element),
+ next_node);
+ } else {
+ ret = EINVAL;
+ if (error)
+ *error = heim_error_create(ret, "Node in path not a "
+ "container");
+ }
+ heim_release(next_node);
+ if (ret)
+ goto err;
+ }
+
+ path_element = next_path_element;
+ node = next_node;
+ next_node = NULL;
+ }
+
+ if (path_element == NULL)
+ goto err;
+
+ /* Add the leaf */
+ if (leaf != NULL) {
+ if (node_type == HEIM_TID_DICT)
+ ret = heim_dict_set_value(node, path_element, leaf);
+ else
+ ret = heim_array_insert_value(node,
+ heim_number_get_int(path_element),
+ leaf);
+ }
+ return ret;
+
+err:
+ if (error && !*error) {
+ if (ret == ENOMEM)
+ *error = heim_error_create_enomem();
+ else
+ *error = heim_error_create(ret, "Could not set "
+ "dict value");
+ }
+ return ret;
+}
+
+/**
+ * Create a path in a heim_object_t tree
+ *
+ * @param ptr the tree
+ * @param size the size of the heim_dict_t nodes to be created
+ * @param leaf leaf node to be added, if any
+ * @param error error (output)
+ * @param ... NULL-terminated list of path component objects
+ *
+ * Create a path of heim_dict_t interior nodes in a given heim_object_t
+ * tree, as necessary, and set/replace a leaf, if given (if leaf is NULL
+ * then the leaf is not deleted).
+ *
+ * @return 0 on success, else a system error
+ *
+ * @addtogroup heimbase
+ */
+
+int
+heim_path_create(heim_object_t ptr, size_t size, heim_object_t leaf,
+ heim_error_t *error, ...)
+{
+ va_list ap;
+ int ret;
+
+ va_start(ap, error);
+ ret = heim_path_vcreate(ptr, size, leaf, error, ap);
+ va_end(ap);
+ return ret;
+}
+
+/**
+ * Delete leaf node named by a path in a heim_object_t tree
+ *
+ * @param ptr the tree
+ * @param error error (output)
+ * @param ap NULL-terminated list of path component objects
+ *
+ * @addtogroup heimbase
+ */
+
+void
+heim_path_vdelete(heim_object_t ptr, heim_error_t *error, va_list ap)
+{
+ heim_object_t parent, key, child;
+
+ child = heim_path_vget2(ptr, &parent, &key, error, ap);
+ if (child != NULL) {
+ if (heim_get_tid(parent) == HEIM_TID_DICT)
+ heim_dict_delete_key(parent, key);
+ else if (heim_get_tid(parent) == HEIM_TID_DB)
+ heim_db_delete_key(parent, NULL, key, error);
+ else if (heim_get_tid(parent) == HEIM_TID_ARRAY)
+ heim_array_delete_value(parent, heim_number_get_int(key));
+ heim_release(child);
+ }
+}
+
+/**
+ * Delete leaf node named by a path in a heim_object_t tree
+ *
+ * @param ptr the tree
+ * @param error error (output)
+ * @param ap NULL-terminated list of path component objects
+ *
+ * @addtogroup heimbase
+ */
+
+void
+heim_path_delete(heim_object_t ptr, heim_error_t *error, ...)
+{
+ va_list ap;
+
+ va_start(ap, error);
+ heim_path_vdelete(ptr, error, ap);
+ va_end(ap);
+ return;
+}
+
diff --git a/third_party/heimdal/lib/base/heimbase.h b/third_party/heimdal/lib/base/heimbase.h
new file mode 100644
index 0000000..3706fc8
--- /dev/null
+++ b/third_party/heimdal/lib/base/heimbase.h
@@ -0,0 +1,527 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef HEIM_BASE_H
+#define HEIM_BASE_H 1
+
+#include "config.h"
+
+#include <sys/types.h>
+#ifndef _WIN32
+#include <sys/socket.h>
+#endif
+#if !defined(WIN32) && !defined(HAVE_DISPATCH_DISPATCH_H) && defined(ENABLE_PTHREAD_SUPPORT)
+#include <pthread.h>
+#endif
+#include <krb5-types.h>
+#include <stdarg.h>
+#ifdef _WIN32
+#include <winsock2.h>
+#endif
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#else
+#ifndef false
+#define false 0
+#endif
+#ifndef true
+#define true 1
+#endif
+#endif
+
+#include <stdint.h>
+
+#include <heim_err.h>
+
+#ifdef _WIN32
+#define HEIM_CALLCONV __stdcall
+#define HEIM_LIB_CALL __stdcall
+#else
+#define HEIM_CALLCONV
+#define HEIM_LIB_CALL
+#endif
+
+#if !defined(__GNUC__) && !defined(__attribute__)
+#define __attribute__(x)
+#endif
+
+#define HEIM_BASE_API_VERSION 20130210
+
+/*
+ * Generic facilities (moved from lib/krb5/.
+ */
+
+typedef int32_t heim_error_code;
+typedef struct heim_context_s *heim_context;
+typedef struct heim_pcontext_s *heim_pcontext;
+
+typedef void (HEIM_CALLCONV *heim_log_log_func_t)(heim_context,
+ const char *,
+ const char *,
+ void *);
+typedef void (HEIM_CALLCONV *heim_log_close_func_t)(void *);
+
+typedef struct heim_log_facility_s heim_log_facility;
+
+typedef uintptr_t
+(HEIM_LIB_CALL *heim_get_instance_func_t)(const char *);
+
+#define HEIM_PLUGIN_INVOKE_ALL 1
+
+struct heim_plugin_data {
+ const char *module;
+ const char *name;
+ int min_version;
+ const char **deps;
+ heim_get_instance_func_t get_instance;
+};
+
+/*
+ * heim_config_binding is identical to struct krb5_config_binding
+ * within krb5.h. Its format is public and used by callers of
+ * krb5_config_get_list() and krb5_config_vget_list().
+ */
+enum heim_config_type {
+ heim_config_string,
+ heim_config_list,
+};
+struct heim_config_binding {
+ enum heim_config_type type;
+ char *name;
+ struct heim_config_binding *next;
+ union {
+ char *string;
+ struct heim_config_binding *list;
+ void *generic;
+ } u;
+};
+typedef struct heim_config_binding heim_config_binding;
+typedef struct heim_config_binding heim_config_section;
+
+/*
+ * CF-like, JSON APIs
+ */
+
+typedef void * heim_object_t;
+typedef unsigned int heim_tid_t;
+typedef heim_object_t heim_bool_t;
+typedef heim_object_t heim_null_t;
+#ifdef WIN32
+typedef LONG heim_base_once_t;
+#define HEIM_BASE_ONCE_INIT 0
+#elif defined(HAVE_DISPATCH_DISPATCH_H)
+typedef long heim_base_once_t; /* XXX arch dependant */
+#define HEIM_BASE_ONCE_INIT 0
+#elif defined(ENABLE_PTHREAD_SUPPORT)
+typedef pthread_once_t heim_base_once_t;
+#define HEIM_BASE_ONCE_INIT PTHREAD_ONCE_INIT
+#else
+typedef long heim_base_once_t; /* XXX arch dependant */
+#define HEIM_BASE_ONCE_INIT 0
+#endif
+
+#if !defined(__has_extension)
+#define __has_extension(x) 0
+#endif
+
+#define HEIM_REQUIRE_GNUC(m,n,p) \
+ (((__GNUC__ * 10000) + (__GNUC_MINOR__ * 100) + __GNUC_PATCHLEVEL__) >= \
+ (((m) * 10000) + ((n) * 100) + (p)))
+
+
+#if __has_extension(__builtin_expect) || HEIM_REQUIRE_GNUC(3,0,0)
+#define heim_builtin_expect(_op,_res) __builtin_expect(_op,_res)
+#else
+#define heim_builtin_expect(_op,_res) (_op)
+#endif
+
+
+heim_object_t heim_retain(heim_object_t);
+void heim_release(heim_object_t);
+
+void heim_show(heim_object_t);
+
+typedef void (HEIM_CALLCONV *heim_type_dealloc)(void *);
+
+void *
+heim_alloc(size_t size, const char *name, heim_type_dealloc dealloc);
+
+heim_tid_t
+heim_get_tid(heim_object_t object);
+
+int
+heim_cmp(heim_object_t a, heim_object_t b);
+
+uintptr_t
+heim_get_hash(heim_object_t ptr);
+
+void
+heim_base_once_f(heim_base_once_t *, void *, void (*)(void *));
+
+void
+heim_abort(const char *fmt, ...)
+ HEIMDAL_NORETURN_ATTRIBUTE
+ HEIMDAL_PRINTF_ATTRIBUTE((__printf__, 1, 2));
+
+void
+heim_abortv(const char *fmt, va_list ap)
+ HEIMDAL_NORETURN_ATTRIBUTE
+ HEIMDAL_PRINTF_ATTRIBUTE((__printf__, 1, 0));
+
+#define heim_assert(e,t) \
+ (heim_builtin_expect(!(e), 0) ? heim_abort(t ":" #e) : (void)0)
+
+/*
+ *
+ */
+
+heim_null_t
+heim_null_create(void);
+
+heim_bool_t
+heim_bool_create(int);
+
+int
+heim_bool_val(heim_bool_t);
+
+/*
+ * Array
+ */
+
+typedef struct heim_array_data *heim_array_t;
+
+heim_array_t heim_array_create(void);
+heim_tid_t heim_array_get_type_id(void);
+
+typedef void (*heim_array_iterator_f_t)(heim_object_t, void *, int *);
+typedef int (*heim_array_filter_f_t)(heim_object_t, void *);
+
+int heim_array_append_value(heim_array_t, heim_object_t);
+int heim_array_insert_value(heim_array_t, size_t idx, heim_object_t);
+void heim_array_iterate_f(heim_array_t, void *, heim_array_iterator_f_t);
+void heim_array_iterate_reverse_f(heim_array_t, void *, heim_array_iterator_f_t);
+#ifdef __BLOCKS__
+void heim_array_iterate(heim_array_t, void (^)(heim_object_t, int *));
+void heim_array_iterate_reverse(heim_array_t, void (^)(heim_object_t, int *));
+#endif
+size_t heim_array_get_length(heim_array_t);
+heim_object_t
+ heim_array_get_value(heim_array_t, size_t);
+heim_object_t
+ heim_array_copy_value(heim_array_t, size_t);
+void heim_array_set_value(heim_array_t, size_t, heim_object_t);
+void heim_array_delete_value(heim_array_t, size_t);
+void heim_array_filter_f(heim_array_t, void *, heim_array_filter_f_t);
+#ifdef __BLOCKS__
+void heim_array_filter(heim_array_t, int (^)(heim_object_t));
+#endif
+
+/*
+ * Dict
+ */
+
+typedef struct heim_dict_data *heim_dict_t;
+
+heim_dict_t heim_dict_create(size_t size);
+heim_tid_t heim_dict_get_type_id(void);
+
+typedef void (*heim_dict_iterator_f_t)(heim_object_t, heim_object_t, void *);
+
+int heim_dict_set_value(heim_dict_t, heim_object_t, heim_object_t);
+void heim_dict_iterate_f(heim_dict_t, void *, heim_dict_iterator_f_t);
+#ifdef __BLOCKS__
+void heim_dict_iterate(heim_dict_t, void (^)(heim_object_t, heim_object_t));
+#endif
+
+heim_object_t
+ heim_dict_get_value(heim_dict_t, heim_object_t);
+heim_object_t
+ heim_dict_copy_value(heim_dict_t, heim_object_t);
+void heim_dict_delete_key(heim_dict_t, heim_object_t);
+
+/*
+ * String
+ */
+
+typedef struct heim_string_data *heim_string_t;
+typedef void (*heim_string_free_f_t)(void *);
+
+heim_string_t heim_string_create(const char *);
+heim_string_t heim_string_ref_create(const char *, heim_string_free_f_t);
+heim_string_t heim_string_create_with_bytes(const void *, size_t);
+heim_string_t heim_string_ref_create_with_bytes(const void *, size_t,
+ heim_string_free_f_t);
+heim_string_t heim_string_create_with_format(const char *, ...);
+heim_tid_t heim_string_get_type_id(void);
+const char * heim_string_get_utf8(heim_string_t);
+
+#define HSTR(_str) (__heim_string_constant("" _str ""))
+heim_string_t __heim_string_constant(const char *);
+
+/*
+ * Errors
+ */
+
+typedef struct heim_error * heim_error_t;
+
+heim_error_t heim_error_create_enomem(void);
+
+heim_error_t heim_error_create(int, const char *, ...)
+ HEIMDAL_PRINTF_ATTRIBUTE((__printf__, 2, 3));
+
+void heim_error_create_opt(heim_error_t *error, int error_code, const char *fmt, ...)
+ HEIMDAL_PRINTF_ATTRIBUTE((__printf__, 3, 4));
+
+heim_error_t heim_error_createv(int, const char *, va_list)
+ HEIMDAL_PRINTF_ATTRIBUTE((__printf__, 2, 0));
+
+heim_string_t heim_error_copy_string(heim_error_t);
+int heim_error_get_code(heim_error_t);
+
+heim_error_t heim_error_append(heim_error_t, heim_error_t);
+
+/*
+ * Path
+ */
+
+heim_object_t heim_path_get(heim_object_t ptr, heim_error_t *error, ...);
+heim_object_t heim_path_copy(heim_object_t ptr, heim_error_t *error, ...);
+heim_object_t heim_path_vget(heim_object_t ptr, heim_error_t *error,
+ va_list ap);
+heim_object_t heim_path_vcopy(heim_object_t ptr, heim_error_t *error,
+ va_list ap);
+
+int heim_path_vcreate(heim_object_t ptr, size_t size, heim_object_t leaf,
+ heim_error_t *error, va_list ap);
+int heim_path_create(heim_object_t ptr, size_t size, heim_object_t leaf,
+ heim_error_t *error, ...);
+
+void heim_path_vdelete(heim_object_t ptr, heim_error_t *error, va_list ap);
+void heim_path_delete(heim_object_t ptr, heim_error_t *error, ...);
+
+/*
+ * Data (octet strings)
+ */
+
+#ifndef __HEIM_BASE_DATA__
+#define __HEIM_BASE_DATA__
+struct heim_base_data {
+ size_t length;
+ void *data;
+};
+typedef struct heim_base_data heim_octet_string;
+#endif
+
+typedef struct heim_base_data * heim_data_t;
+typedef void (*heim_data_free_f_t)(void *);
+
+heim_data_t heim_data_create(const void *, size_t);
+heim_data_t heim_data_ref_create(const void *, size_t, heim_data_free_f_t);
+heim_tid_t heim_data_get_type_id(void);
+const heim_octet_string *
+ heim_data_get_data(heim_data_t);
+const void * heim_data_get_ptr(heim_data_t);
+size_t heim_data_get_length(heim_data_t);
+
+/*
+ * DB
+ */
+
+typedef struct heim_db_data *heim_db_t;
+
+typedef void (*heim_db_iterator_f_t)(heim_data_t, heim_data_t, void *);
+
+typedef int (*heim_db_plug_open_f_t)(void *, const char *, const char *,
+ heim_dict_t, void **, heim_error_t *);
+typedef int (*heim_db_plug_clone_f_t)(void *, void **, heim_error_t *);
+typedef int (*heim_db_plug_close_f_t)(void *, heim_error_t *);
+typedef int (*heim_db_plug_lock_f_t)(void *, int, heim_error_t *);
+typedef int (*heim_db_plug_unlock_f_t)(void *, heim_error_t *);
+typedef int (*heim_db_plug_sync_f_t)(void *, heim_error_t *);
+typedef int (*heim_db_plug_begin_f_t)(void *, int, heim_error_t *);
+typedef int (*heim_db_plug_commit_f_t)(void *, heim_error_t *);
+typedef int (*heim_db_plug_rollback_f_t)(void *, heim_error_t *);
+typedef heim_data_t (*heim_db_plug_copy_value_f_t)(void *, heim_string_t,
+ heim_data_t,
+ heim_error_t *);
+typedef int (*heim_db_plug_set_value_f_t)(void *, heim_string_t, heim_data_t,
+ heim_data_t, heim_error_t *);
+typedef int (*heim_db_plug_del_key_f_t)(void *, heim_string_t, heim_data_t,
+ heim_error_t *);
+typedef void (*heim_db_plug_iter_f_t)(void *, heim_string_t, void *,
+ heim_db_iterator_f_t, heim_error_t *);
+
+struct heim_db_type {
+ int version;
+ heim_db_plug_open_f_t openf;
+ heim_db_plug_clone_f_t clonef;
+ heim_db_plug_close_f_t closef;
+ heim_db_plug_lock_f_t lockf;
+ heim_db_plug_unlock_f_t unlockf;
+ heim_db_plug_sync_f_t syncf;
+ heim_db_plug_begin_f_t beginf;
+ heim_db_plug_commit_f_t commitf;
+ heim_db_plug_rollback_f_t rollbackf;
+ heim_db_plug_copy_value_f_t copyf;
+ heim_db_plug_set_value_f_t setf;
+ heim_db_plug_del_key_f_t delf;
+ heim_db_plug_iter_f_t iterf;
+};
+
+extern struct heim_db_type heim_sorted_text_file_dbtype;
+
+#define HEIM_DB_TYPE_VERSION_01 1
+
+int heim_db_register(const char *dbtype,
+ void *data,
+ struct heim_db_type *plugin);
+
+heim_db_t heim_db_create(const char *dbtype, const char *dbname,
+ heim_dict_t options, heim_error_t *error);
+heim_db_t heim_db_clone(heim_db_t, heim_error_t *);
+int heim_db_begin(heim_db_t, int, heim_error_t *);
+int heim_db_commit(heim_db_t, heim_error_t *);
+int heim_db_rollback(heim_db_t, heim_error_t *);
+heim_tid_t heim_db_get_type_id(void);
+
+int heim_db_set_value(heim_db_t, heim_string_t, heim_data_t, heim_data_t,
+ heim_error_t *);
+heim_data_t heim_db_copy_value(heim_db_t, heim_string_t, heim_data_t,
+ heim_error_t *);
+int heim_db_delete_key(heim_db_t, heim_string_t, heim_data_t,
+ heim_error_t *);
+void heim_db_iterate_f(heim_db_t, heim_string_t, void *,
+ heim_db_iterator_f_t, heim_error_t *);
+#ifdef __BLOCKS__
+void heim_db_iterate(heim_db_t, heim_string_t,
+ void (^)(heim_data_t, heim_data_t), heim_error_t *);
+#endif
+
+
+/*
+ * Number
+ */
+
+typedef struct heim_number_data *heim_number_t;
+
+heim_number_t heim_number_create(int64_t);
+heim_tid_t heim_number_get_type_id(void);
+int heim_number_get_int(heim_number_t);
+int64_t heim_number_get_long(heim_number_t);
+
+/*
+ *
+ */
+
+typedef struct heim_auto_release * heim_auto_release_t;
+
+heim_auto_release_t heim_auto_release_create(void);
+void heim_auto_release_drain(heim_auto_release_t);
+heim_object_t heim_auto_release(heim_object_t);
+
+/*
+ * JSON
+ */
+typedef enum heim_json_flags {
+ HEIM_JSON_F_NO_C_NULL = 1,
+ HEIM_JSON_F_STRICT_STRINGS = 2,
+ HEIM_JSON_F_NO_DATA = 4,
+ HEIM_JSON_F_NO_DATA_DICT = 8,
+ HEIM_JSON_F_STRICT_DICT = 16,
+ HEIM_JSON_F_STRICT = 31,
+ HEIM_JSON_F_CNULL2JSNULL = 32,
+ HEIM_JSON_F_TRY_DECODE_DATA = 64,
+ HEIM_JSON_F_ONE_LINE = 128
+} heim_json_flags_t;
+
+heim_object_t heim_json_create(const char *, size_t, heim_json_flags_t,
+ heim_error_t *);
+heim_object_t heim_json_create_with_bytes(const void *, size_t, size_t,
+ heim_json_flags_t,
+ heim_error_t *);
+heim_string_t heim_json_copy_serialize(heim_object_t, heim_json_flags_t,
+ heim_error_t *);
+
+
+/*
+ * Debug
+ */
+
+heim_string_t
+heim_description(heim_object_t ptr);
+
+/*
+ * Binary search.
+ *
+ * Note: these are private until integrated into the heimbase object system.
+ */
+typedef struct bsearch_file_handle *bsearch_file_handle;
+int _bsearch_text(const char *buf, size_t buf_sz, const char *key,
+ char **value, size_t *location, size_t *loops);
+int _bsearch_file_open(const char *fname, size_t max_sz, size_t page_sz,
+ bsearch_file_handle *bfh, size_t *reads);
+int _bsearch_file(bsearch_file_handle bfh, const char *key, char **value,
+ size_t *location, size_t *loops, size_t *reads);
+void _bsearch_file_info(bsearch_file_handle bfh, size_t *page_sz,
+ size_t *max_sz, int *blockwise);
+void _bsearch_file_close(bsearch_file_handle *bfh);
+
+/*
+ * Thread-specific keys
+ */
+
+int heim_w32_key_create(unsigned long *, void (*)(void *));
+int heim_w32_delete_key(unsigned long);
+int heim_w32_setspecific(unsigned long, void *);
+void *heim_w32_getspecific(unsigned long);
+void heim_w32_service_thread_detach(void *);
+
+#include <heim_threads.h>
+#include "heimbase-atomics.h"
+#include <com_err.h>
+
+/*
+ * Service logging facility (moved from kdc/).
+ */
+
+#define HEIM_SVC_AUDIT_EATWHITE 0x1
+#define HEIM_SVC_AUDIT_VIS 0x2
+#define HEIM_SVC_AUDIT_VISLAST 0x4
+
+typedef struct heim_svc_req_desc_common_s *heim_svc_req_desc;
+
+#include <heimbase-protos.h>
+
+#endif /* HEIM_BASE_H */
diff --git a/third_party/heimdal/lib/base/heimbasepriv.h b/third_party/heimdal/lib/base/heimbasepriv.h
new file mode 100644
index 0000000..b9f63e5
--- /dev/null
+++ b/third_party/heimdal/lib/base/heimbasepriv.h
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if defined(HEIM_BASE_MAINTAINER) && defined(ENABLE_PTHREAD_SUPPORT)
+#define HEIM_WIN32_TLS
+#elif defined(WIN32)
+#define HEIM_WIN32_TLS
+#endif
+
+typedef void (*heim_type_init)(void *);
+typedef heim_object_t (*heim_type_copy)(void *);
+typedef int (*heim_type_cmp)(void *, void *);
+typedef uintptr_t (*heim_type_hash)(void *);
+typedef heim_string_t (*heim_type_description)(void *);
+
+typedef struct heim_type_data *heim_type_t;
+
+enum {
+ HEIM_TID_NUMBER = 0,
+ HEIM_TID_NULL = 1,
+ HEIM_TID_BOOL = 2,
+ HEIM_TID_TAGGED_UNUSED2 = 3, /* reserved for tagged object types */
+ HEIM_TID_TAGGED_UNUSED3 = 4, /* reserved for tagged object types */
+ HEIM_TID_TAGGED_UNUSED4 = 5, /* reserved for tagged object types */
+ HEIM_TID_TAGGED_UNUSED5 = 6, /* reserved for tagged object types */
+ HEIM_TID_TAGGED_UNUSED6 = 7, /* reserved for tagged object types */
+ HEIM_TID_MEMORY = 128,
+ HEIM_TID_ARRAY = 129,
+ HEIM_TID_DICT = 130,
+ HEIM_TID_STRING = 131,
+ HEIM_TID_AUTORELEASE = 132,
+ HEIM_TID_ERROR = 133,
+ HEIM_TID_DATA = 134,
+ HEIM_TID_DB = 135,
+ HEIM_TID_PA_AUTH_MECH = 136,
+ HEIM_TID_PAC = 137,
+ HEIM_TID_USER = 255
+
+};
+
+struct heim_type_data {
+ heim_tid_t tid;
+ const char *name;
+ heim_type_init init;
+ heim_type_dealloc dealloc;
+ heim_type_copy copy;
+ heim_type_cmp cmp;
+ heim_type_hash hash;
+ heim_type_description desc;
+};
+
+heim_type_t _heim_get_isa(heim_object_t);
+
+heim_type_t
+_heim_create_type(const char *name,
+ heim_type_init init,
+ heim_type_dealloc dealloc,
+ heim_type_copy copy,
+ heim_type_cmp cmp,
+ heim_type_hash hash,
+ heim_type_description desc);
+
+heim_object_t
+_heim_alloc_object(heim_type_t type, size_t size);
+
+void *
+_heim_get_isaextra(heim_object_t o, size_t idx);
+
+heim_tid_t
+_heim_type_get_tid(heim_type_t type);
+
+void
+_heim_make_permanent(heim_object_t ptr);
+
+heim_data_t
+_heim_db_get_value(heim_db_t, heim_string_t, heim_data_t, heim_error_t *);
+
+
+/* tagged tid */
+extern struct heim_type_data _heim_null_object;
+extern struct heim_type_data _heim_bool_object;
+extern struct heim_type_data _heim_number_object;
+extern struct heim_type_data _heim_string_object;
diff --git a/third_party/heimdal/lib/base/json.c b/third_party/heimdal/lib/base/json.c
new file mode 100644
index 0000000..2ef371b
--- /dev/null
+++ b/third_party/heimdal/lib/base/json.c
@@ -0,0 +1,811 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+#include <ctype.h>
+#include <base64.h>
+
+static heim_base_once_t heim_json_once = HEIM_BASE_ONCE_INIT;
+static heim_string_t heim_tid_data_uuid_key = NULL;
+static const char base64_chars[] =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+static void
+json_init_once(void *arg)
+{
+ heim_tid_data_uuid_key = __heim_string_constant("heimdal-type-data-76d7fca2-d0da-4b20-a126-1a10f8a0eae6");
+}
+
+struct twojson {
+ void *ctx;
+ void (*out)(void *, const char *);
+ size_t indent;
+ heim_json_flags_t flags;
+ int ret;
+ int first;
+};
+
+struct heim_strbuf {
+ char *str;
+ size_t len;
+ size_t alloced;
+ int enomem;
+ heim_json_flags_t flags;
+};
+
+static int
+base2json(heim_object_t, struct twojson *);
+
+static void
+indent(struct twojson *j)
+{
+ size_t i = j->indent;
+ if (j->flags & HEIM_JSON_F_ONE_LINE)
+ return;
+ while (i--)
+ j->out(j->ctx, "\t");
+}
+
+static void
+array2json(heim_object_t value, void *ctx, int *stop)
+{
+ struct twojson *j = ctx;
+ if (j->ret)
+ return;
+ if (j->first) {
+ j->first = 0;
+ } else {
+ j->out(j->ctx, NULL); /* eat previous '\n' if possible */
+ j->out(j->ctx, ",\n");
+ }
+ j->ret = base2json(value, j);
+}
+
+static void
+dict2json(heim_object_t key, heim_object_t value, void *ctx)
+{
+ struct twojson *j = ctx;
+ if (j->ret)
+ return;
+ if (j->first) {
+ j->first = 0;
+ } else {
+ j->out(j->ctx, NULL); /* eat previous '\n' if possible */
+ j->out(j->ctx, ",\n");
+ }
+ j->ret = base2json(key, j);
+ if (j->ret)
+ return;
+ j->out(j->ctx, " : \n");
+ j->indent++;
+ j->ret = base2json(value, j);
+ if (j->ret)
+ return;
+ j->indent--;
+}
+
+static int
+base2json(heim_object_t obj, struct twojson *j)
+{
+ heim_tid_t type;
+ int first = 0;
+
+ if (obj == NULL) {
+ if (j->flags & HEIM_JSON_F_CNULL2JSNULL) {
+ obj = heim_null_create();
+ } else if (j->flags & HEIM_JSON_F_NO_C_NULL) {
+ return EINVAL;
+ } else {
+ indent(j);
+ j->out(j->ctx, "<NULL>\n"); /* This is NOT valid JSON! */
+ return 0;
+ }
+ }
+
+ type = heim_get_tid(obj);
+ switch (type) {
+ case HEIM_TID_ARRAY:
+ indent(j);
+ j->out(j->ctx, "[\n");
+ j->indent++;
+ first = j->first;
+ j->first = 1;
+ heim_array_iterate_f(obj, j, array2json);
+ j->indent--;
+ if (!j->first)
+ j->out(j->ctx, "\n");
+ indent(j);
+ j->out(j->ctx, "]\n");
+ j->first = first;
+ break;
+
+ case HEIM_TID_DICT:
+ indent(j);
+ j->out(j->ctx, "{\n");
+ j->indent++;
+ first = j->first;
+ j->first = 1;
+ heim_dict_iterate_f(obj, j, dict2json);
+ j->indent--;
+ if (!j->first)
+ j->out(j->ctx, "\n");
+ indent(j);
+ j->out(j->ctx, "}\n");
+ j->first = first;
+ break;
+
+ case HEIM_TID_STRING:
+ indent(j);
+ j->out(j->ctx, "\"");
+ j->out(j->ctx, heim_string_get_utf8(obj));
+ j->out(j->ctx, "\"");
+ break;
+
+ case HEIM_TID_DATA: {
+ heim_dict_t d;
+ heim_string_t v;
+ const heim_octet_string *data;
+ char *b64 = NULL;
+ int ret;
+
+ if (j->flags & HEIM_JSON_F_NO_DATA)
+ return EINVAL; /* JSON doesn't do binary */
+
+ data = heim_data_get_data(obj);
+ ret = rk_base64_encode(data->data, data->length, &b64);
+ if (ret < 0 || b64 == NULL)
+ return ENOMEM;
+
+ if (j->flags & HEIM_JSON_F_NO_DATA_DICT) {
+ indent(j);
+ j->out(j->ctx, "\"");
+ j->out(j->ctx, b64); /* base64-encode; hope there's no aliasing */
+ j->out(j->ctx, "\"");
+ free(b64);
+ } else {
+ /*
+ * JSON has no way to represent binary data, therefore the
+ * following is a Heimdal-specific convention.
+ *
+ * We encode binary data as a dict with a single very magic
+ * key with a base64-encoded value. The magic key includes
+ * a uuid, so we're not likely to alias accidentally.
+ */
+ d = heim_dict_create(2);
+ if (d == NULL) {
+ free(b64);
+ return ENOMEM;
+ }
+ v = heim_string_ref_create(b64, free);
+ if (v == NULL) {
+ free(b64);
+ heim_release(d);
+ return ENOMEM;
+ }
+ ret = heim_dict_set_value(d, heim_tid_data_uuid_key, v);
+ heim_release(v);
+ if (ret) {
+ heim_release(d);
+ return ENOMEM;
+ }
+ ret = base2json(d, j);
+ heim_release(d);
+ if (ret)
+ return ret;
+ }
+ break;
+ }
+
+ case HEIM_TID_NUMBER: {
+ char num[32];
+ indent(j);
+ snprintf(num, sizeof (num), "%d", heim_number_get_int(obj));
+ j->out(j->ctx, num);
+ break;
+ }
+ case HEIM_TID_NULL:
+ indent(j);
+ j->out(j->ctx, "null");
+ break;
+ case HEIM_TID_BOOL:
+ indent(j);
+ j->out(j->ctx, heim_bool_val(obj) ? "true" : "false");
+ break;
+ default:
+ return 1;
+ }
+ return 0;
+}
+
+static int
+heim_base2json(heim_object_t obj, void *ctx, heim_json_flags_t flags,
+ void (*out)(void *, const char *))
+{
+ struct twojson j;
+
+ if (flags & HEIM_JSON_F_STRICT_STRINGS)
+ return ENOTSUP; /* Sorry, not yet! */
+
+ heim_base_once_f(&heim_json_once, NULL, json_init_once);
+
+ j.indent = 0;
+ j.ctx = ctx;
+ j.out = out;
+ j.flags = flags;
+ j.ret = 0;
+ j.first = 1;
+
+ return base2json(obj, &j);
+}
+
+
+/*
+ *
+ */
+
+struct parse_ctx {
+ unsigned long lineno;
+ const uint8_t *p;
+ const uint8_t *pstart;
+ const uint8_t *pend;
+ heim_error_t error;
+ size_t depth;
+ heim_json_flags_t flags;
+};
+
+
+static heim_object_t
+parse_value(struct parse_ctx *ctx);
+
+/*
+ * This function eats whitespace, but, critically, it also succeeds
+ * only if there's anything left to parse.
+ */
+static int
+white_spaces(struct parse_ctx *ctx)
+{
+ while (ctx->p < ctx->pend) {
+ uint8_t c = *ctx->p;
+ if (c == ' ' || c == '\t' || c == '\r') {
+
+ } else if (c == '\n') {
+ ctx->lineno++;
+ } else
+ return 0;
+ (ctx->p)++;
+ }
+ return -1;
+}
+
+static int
+is_number(uint8_t n)
+{
+ return ('0' <= n && n <= '9');
+}
+
+static heim_number_t
+parse_number(struct parse_ctx *ctx)
+{
+ int number = 0, neg = 1;
+
+ if (ctx->p >= ctx->pend)
+ return NULL;
+
+ if (*ctx->p == '-') {
+ if (ctx->p + 1 >= ctx->pend)
+ return NULL;
+ neg = -1;
+ ctx->p += 1;
+ }
+
+ while (ctx->p < ctx->pend) {
+ if (is_number(*ctx->p)) {
+ number = (number * 10) + (*ctx->p - '0');
+ } else {
+ break;
+ }
+ ctx->p += 1;
+ }
+
+ return heim_number_create(number * neg);
+}
+
+static heim_string_t
+parse_string(struct parse_ctx *ctx)
+{
+ const uint8_t *start;
+ int quote = 0;
+
+ if (ctx->flags & HEIM_JSON_F_STRICT_STRINGS) {
+ ctx->error = heim_error_create(EINVAL, "Strict JSON string encoding "
+ "not yet supported");
+ return NULL;
+ }
+
+ if (*ctx->p != '"') {
+ ctx->error = heim_error_create(EINVAL, "Expected a JSON string but "
+ "found something else at line %lu",
+ ctx->lineno);
+ return NULL;
+ }
+ start = ++ctx->p;
+
+ while (ctx->p < ctx->pend) {
+ if (*ctx->p == '\n') {
+ ctx->lineno++;
+ } else if (*ctx->p == '\\') {
+ if (ctx->p + 1 == ctx->pend)
+ goto out;
+ ctx->p++;
+ quote = 1;
+ } else if (*ctx->p == '"') {
+ heim_object_t o;
+
+ if (quote) {
+ char *p0, *p;
+ p = p0 = malloc(ctx->p - start);
+ if (p == NULL)
+ goto out;
+ while (start < ctx->p) {
+ if (*start == '\\') {
+ start++;
+ /* XXX validate quoted char */
+ }
+ *p++ = *start++;
+ }
+ o = heim_string_create_with_bytes(p0, p - p0);
+ free(p0);
+ } else {
+ o = heim_string_create_with_bytes(start, ctx->p - start);
+ if (o == NULL) {
+ ctx->error = heim_error_create_enomem();
+ return NULL;
+ }
+
+ /* If we can decode as base64, then let's */
+ if (ctx->flags & HEIM_JSON_F_TRY_DECODE_DATA) {
+ void *buf;
+ size_t len;
+ const char *s;
+
+ s = heim_string_get_utf8(o);
+ len = strlen(s);
+
+ if (len >= 4 && strspn(s, base64_chars) >= len - 2) {
+ buf = malloc(len);
+ if (buf == NULL) {
+ heim_release(o);
+ ctx->error = heim_error_create_enomem();
+ return NULL;
+ }
+ len = rk_base64_decode(s, buf);
+ if (len == -1) {
+ free(buf);
+ return o;
+ }
+ heim_release(o);
+ o = heim_data_ref_create(buf, len, free);
+ }
+ }
+ }
+ ctx->p += 1;
+
+ return o;
+ }
+ ctx->p += 1;
+ }
+ out:
+ ctx->error = heim_error_create(EINVAL, "ran out of string");
+ return NULL;
+}
+
+static int
+parse_pair(heim_dict_t dict, struct parse_ctx *ctx)
+{
+ heim_string_t key;
+ heim_object_t value;
+
+ if (white_spaces(ctx))
+ return -1;
+
+ if (*ctx->p == '}') {
+ ctx->p++;
+ return 0;
+ }
+
+ if (ctx->flags & HEIM_JSON_F_STRICT_DICT)
+ /* JSON allows only string keys */
+ key = parse_string(ctx);
+ else
+ /* heim_dict_t allows any heim_object_t as key */
+ key = parse_value(ctx);
+ if (key == NULL)
+ /* Even heim_dict_t does not allow C NULLs as keys though! */
+ return -1;
+
+ if (white_spaces(ctx)) {
+ heim_release(key);
+ return -1;
+ }
+
+ if (*ctx->p != ':') {
+ heim_release(key);
+ return -1;
+ }
+
+ ctx->p += 1; /* safe because we call white_spaces() next */
+
+ if (white_spaces(ctx)) {
+ heim_release(key);
+ return -1;
+ }
+
+ value = parse_value(ctx);
+ if (value == NULL &&
+ (ctx->error != NULL || (ctx->flags & HEIM_JSON_F_NO_C_NULL))) {
+ if (ctx->error == NULL)
+ ctx->error = heim_error_create(EINVAL, "Invalid JSON encoding");
+ heim_release(key);
+ return -1;
+ }
+ heim_dict_set_value(dict, key, value);
+ heim_release(key);
+ heim_release(value);
+
+ if (white_spaces(ctx))
+ return -1;
+
+ if (*ctx->p == '}') {
+ /*
+ * Return 1 but don't consume the '}' so we can count the one
+ * pair in a one-pair dict
+ */
+ return 1;
+ } else if (*ctx->p == ',') {
+ ctx->p++;
+ return 1;
+ }
+ return -1;
+}
+
+static heim_dict_t
+parse_dict(struct parse_ctx *ctx)
+{
+ heim_dict_t dict;
+ size_t count = 0;
+ int ret;
+
+ heim_assert(*ctx->p == '{', "string doesn't start with {");
+
+ dict = heim_dict_create(11);
+ if (dict == NULL) {
+ ctx->error = heim_error_create_enomem();
+ return NULL;
+ }
+
+ ctx->p += 1; /* safe because parse_pair() calls white_spaces() first */
+
+ while ((ret = parse_pair(dict, ctx)) > 0)
+ count++;
+ if (ret < 0) {
+ heim_release(dict);
+ return NULL;
+ }
+ if (count == 1 && !(ctx->flags & HEIM_JSON_F_NO_DATA_DICT)) {
+ heim_object_t v = heim_dict_copy_value(dict, heim_tid_data_uuid_key);
+
+ /*
+ * Binary data encoded as a dict with a single magic key with
+ * base64-encoded value? Decode as heim_data_t.
+ */
+ if (v != NULL && heim_get_tid(v) == HEIM_TID_STRING) {
+ void *buf;
+ size_t len;
+
+ buf = malloc(strlen(heim_string_get_utf8(v)));
+ if (buf == NULL) {
+ heim_release(dict);
+ heim_release(v);
+ ctx->error = heim_error_create_enomem();
+ return NULL;
+ }
+ len = rk_base64_decode(heim_string_get_utf8(v), buf);
+ heim_release(v);
+ if (len == -1) {
+ free(buf);
+ return dict; /* assume aliasing accident */
+ }
+ heim_release(dict);
+ return (heim_dict_t)heim_data_ref_create(buf, len, free);
+ }
+ }
+ return dict;
+}
+
+static int
+parse_item(heim_array_t array, struct parse_ctx *ctx)
+{
+ heim_object_t value;
+
+ if (white_spaces(ctx))
+ return -1;
+
+ if (*ctx->p == ']') {
+ ctx->p++; /* safe because parse_value() calls white_spaces() first */
+ return 0;
+ }
+
+ value = parse_value(ctx);
+ if (value == NULL &&
+ (ctx->error || (ctx->flags & HEIM_JSON_F_NO_C_NULL)))
+ return -1;
+
+ heim_array_append_value(array, value);
+ heim_release(value);
+
+ if (white_spaces(ctx))
+ return -1;
+
+ if (*ctx->p == ']') {
+ ctx->p++;
+ return 0;
+ } else if (*ctx->p == ',') {
+ ctx->p++;
+ return 1;
+ }
+ return -1;
+}
+
+static heim_array_t
+parse_array(struct parse_ctx *ctx)
+{
+ heim_array_t array = heim_array_create();
+ int ret;
+
+ heim_assert(*ctx->p == '[', "array doesn't start with [");
+ ctx->p += 1;
+
+ while ((ret = parse_item(array, ctx)) > 0)
+ ;
+ if (ret < 0) {
+ heim_release(array);
+ return NULL;
+ }
+ return array;
+}
+
+static heim_object_t
+parse_value(struct parse_ctx *ctx)
+{
+ size_t len;
+ heim_object_t o;
+
+ if (white_spaces(ctx))
+ return NULL;
+
+ if (*ctx->p == '"') {
+ return parse_string(ctx);
+ } else if (*ctx->p == '{') {
+ if (ctx->depth-- == 1) {
+ ctx->error = heim_error_create(EINVAL, "JSON object too deep");
+ return NULL;
+ }
+ o = parse_dict(ctx);
+ ctx->depth++;
+ return o;
+ } else if (*ctx->p == '[') {
+ if (ctx->depth-- == 1) {
+ ctx->error = heim_error_create(EINVAL, "JSON object too deep");
+ return NULL;
+ }
+ o = parse_array(ctx);
+ ctx->depth++;
+ return o;
+ } else if (is_number(*ctx->p) || *ctx->p == '-') {
+ return parse_number(ctx);
+ }
+
+ len = ctx->pend - ctx->p;
+
+ if ((ctx->flags & HEIM_JSON_F_NO_C_NULL) == 0 &&
+ len >= 6 && memcmp(ctx->p, "<NULL>", 6) == 0) {
+ ctx->p += 6;
+ return heim_null_create();
+ } else if (len >= 4 && memcmp(ctx->p, "null", 4) == 0) {
+ ctx->p += 4;
+ return heim_null_create();
+ } else if (len >= 4 && strncasecmp((char *)ctx->p, "true", 4) == 0) {
+ ctx->p += 4;
+ return heim_bool_create(1);
+ } else if (len >= 5 && strncasecmp((char *)ctx->p, "false", 5) == 0) {
+ ctx->p += 5;
+ return heim_bool_create(0);
+ }
+
+ ctx->error = heim_error_create(EINVAL, "unknown char %c at %lu line %lu",
+ (char)*ctx->p,
+ (unsigned long)(ctx->p - ctx->pstart),
+ ctx->lineno);
+ return NULL;
+}
+
+
+heim_object_t
+heim_json_create(const char *string, size_t max_depth, heim_json_flags_t flags,
+ heim_error_t *error)
+{
+ return heim_json_create_with_bytes(string, strlen(string), max_depth, flags,
+ error);
+}
+
+heim_object_t
+heim_json_create_with_bytes(const void *data, size_t length, size_t max_depth,
+ heim_json_flags_t flags, heim_error_t *error)
+{
+ struct parse_ctx ctx;
+ heim_object_t o;
+
+ heim_base_once_f(&heim_json_once, NULL, json_init_once);
+
+ ctx.lineno = 1;
+ ctx.p = data;
+ ctx.pstart = data;
+ ctx.pend = ((uint8_t *)data) + length;
+ ctx.error = NULL;
+ ctx.flags = flags;
+ ctx.depth = max_depth;
+
+ o = parse_value(&ctx);
+
+ if (o == NULL && error) {
+ *error = ctx.error;
+ } else if (ctx.error) {
+ heim_release(ctx.error);
+ }
+
+ return o;
+}
+
+
+static void
+show_printf(void *ctx, const char *str)
+{
+ if (str == NULL)
+ return;
+ fprintf(ctx, "%s", str);
+}
+
+/**
+ * Dump a heimbase object to stderr (useful from the debugger!)
+ *
+ * @param obj object to dump using JSON or JSON-like format
+ *
+ * @addtogroup heimbase
+ */
+void
+heim_show(heim_object_t obj)
+{
+ heim_base2json(obj, stderr, HEIM_JSON_F_NO_DATA_DICT, show_printf);
+}
+
+static void
+strbuf_add(void *ctx, const char *str)
+{
+ struct heim_strbuf *strbuf = ctx;
+ size_t len;
+
+ if (strbuf->enomem)
+ return;
+
+ if (str == NULL) {
+ /*
+ * Eat the last '\n'; this is used when formatting dict pairs
+ * and array items so that the ',' separating them is never
+ * preceded by a '\n'.
+ */
+ if (strbuf->len > 0 && strbuf->str[strbuf->len - 1] == '\n')
+ strbuf->len--;
+ return;
+ }
+
+ len = strlen(str);
+ if ((len + 1) > (strbuf->alloced - strbuf->len)) {
+ size_t new_len = strbuf->alloced + (strbuf->alloced >> 2) + len + 1;
+ char *s;
+
+ s = realloc(strbuf->str, new_len);
+ if (s == NULL) {
+ strbuf->enomem = 1;
+ return;
+ }
+ strbuf->str = s;
+ strbuf->alloced = new_len;
+ }
+ /* +1 so we copy the NUL */
+ (void) memcpy(strbuf->str + strbuf->len, str, len + 1);
+ strbuf->len += len;
+ if (strbuf->str[strbuf->len - 1] == '\n' &&
+ strbuf->flags & HEIM_JSON_F_ONE_LINE)
+ strbuf->len--;
+}
+
+#define STRBUF_INIT_SZ 64
+
+heim_string_t
+heim_json_copy_serialize(heim_object_t obj, heim_json_flags_t flags, heim_error_t *error)
+{
+ heim_string_t str;
+ struct heim_strbuf strbuf;
+ int ret;
+
+ if (error)
+ *error = NULL;
+
+ memset(&strbuf, 0, sizeof (strbuf));
+ strbuf.str = malloc(STRBUF_INIT_SZ);
+ if (strbuf.str == NULL) {
+ if (error)
+ *error = heim_error_create_enomem();
+ return NULL;
+ }
+ strbuf.len = 0;
+ strbuf.alloced = STRBUF_INIT_SZ;
+ strbuf.str[0] = '\0';
+ strbuf.flags = flags;
+
+ ret = heim_base2json(obj, &strbuf, flags, strbuf_add);
+ if (ret || strbuf.enomem) {
+ if (error) {
+ if (strbuf.enomem || ret == ENOMEM)
+ *error = heim_error_create_enomem();
+ else
+ *error = heim_error_create(1, "Impossible to JSON-encode "
+ "object");
+ }
+ free(strbuf.str);
+ return NULL;
+ }
+ if (flags & HEIM_JSON_F_ONE_LINE) {
+ strbuf.flags &= ~HEIM_JSON_F_ONE_LINE;
+ strbuf_add(&strbuf, "\n");
+ }
+ str = heim_string_ref_create(strbuf.str, free);
+ if (str == NULL) {
+ if (error)
+ *error = heim_error_create_enomem();
+ free(strbuf.str);
+ }
+ return str;
+}
diff --git a/third_party/heimdal/lib/base/log.c b/third_party/heimdal/lib/base/log.c
new file mode 100644
index 0000000..24295b5
--- /dev/null
+++ b/third_party/heimdal/lib/base/log.c
@@ -0,0 +1,1074 @@
+/*
+ * Copyright (c) 1997-2020 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+#include "heim_threads.h"
+#include "heimbase.h"
+#include "heimbase-svc.h"
+#include <assert.h>
+#include <stdarg.h>
+#include <vis.h>
+#include <base64.h>
+
+struct heim_log_facility_internal {
+ int min;
+ int max;
+ heim_log_log_func_t log_func;
+ heim_log_close_func_t close_func;
+ void *data;
+};
+
+struct heim_log_facility_s {
+ char *program;
+ size_t refs;
+ size_t len;
+ struct heim_log_facility_internal *val;
+};
+
+typedef struct heim_pcontext_s *heim_pcontext;
+typedef struct heim_pconfig *heim_pconfig;
+struct heim_svc_req_desc_common_s {
+ HEIM_SVC_REQUEST_DESC_COMMON_ELEMENTS;
+};
+
+static struct heim_log_facility_internal *
+log_realloc(heim_log_facility *f)
+{
+ struct heim_log_facility_internal *fp;
+ fp = realloc(f->val, (f->len + 1) * sizeof(*f->val));
+ if (fp == NULL)
+ return NULL;
+ f->len++;
+ f->val = fp;
+ fp += f->len - 1;
+ return fp;
+}
+
+struct s2i {
+ const char *s;
+ int val;
+};
+
+#define L(X) { #X, LOG_ ## X }
+
+static struct s2i syslogvals[] = {
+ L(EMERG),
+ L(ALERT),
+ L(CRIT),
+ L(ERR),
+ L(WARNING),
+ L(NOTICE),
+ L(INFO),
+ L(DEBUG),
+
+ L(AUTH),
+#ifdef LOG_AUTHPRIV
+ L(AUTHPRIV),
+#endif
+#ifdef LOG_CRON
+ L(CRON),
+#endif
+ L(DAEMON),
+#ifdef LOG_FTP
+ L(FTP),
+#endif
+ L(KERN),
+ L(LPR),
+ L(MAIL),
+#ifdef LOG_NEWS
+ L(NEWS),
+#endif
+ L(SYSLOG),
+ L(USER),
+#ifdef LOG_UUCP
+ L(UUCP),
+#endif
+ L(LOCAL0),
+ L(LOCAL1),
+ L(LOCAL2),
+ L(LOCAL3),
+ L(LOCAL4),
+ L(LOCAL5),
+ L(LOCAL6),
+ L(LOCAL7),
+ { NULL, -1 }
+};
+
+static int
+find_value(const char *s, struct s2i *table)
+{
+ while (table->s && strcasecmp(table->s, s) != 0)
+ table++;
+ return table->val;
+}
+
+heim_error_code
+heim_initlog(heim_context context,
+ const char *program,
+ heim_log_facility **fac)
+{
+ heim_log_facility *f = calloc(1, sizeof(*f));
+ if (f == NULL)
+ return heim_enomem(context);
+ f->refs = 1;
+ f->program = strdup(program);
+ if (f->program == NULL) {
+ free(f);
+ return heim_enomem(context);
+ }
+ *fac = f;
+ return 0;
+}
+
+heim_log_facility *
+heim_log_ref(heim_log_facility *fac)
+{
+ if (fac)
+ fac->refs++;
+ return fac;
+}
+
+heim_error_code
+heim_addlog_func(heim_context context,
+ heim_log_facility *fac,
+ int min,
+ int max,
+ heim_log_log_func_t log_func,
+ heim_log_close_func_t close_func,
+ void *data)
+{
+ struct heim_log_facility_internal *fp = log_realloc(fac);
+ if (fp == NULL)
+ return heim_enomem(context);
+ fp->min = min;
+ fp->max = max;
+ fp->log_func = log_func;
+ fp->close_func = close_func;
+ fp->data = data;
+ return 0;
+}
+
+
+struct _heimdal_syslog_data{
+ int priority;
+};
+
+static void HEIM_CALLCONV
+log_syslog(heim_context context, const char *timestr,
+ const char *msg, void *data)
+{
+ struct _heimdal_syslog_data *s = data;
+ syslog(s->priority, "%s", msg);
+}
+
+static void HEIM_CALLCONV
+close_syslog(void *data)
+{
+ free(data);
+ closelog();
+}
+
+static heim_error_code
+open_syslog(heim_context context,
+ heim_log_facility *facility, int min, int max,
+ const char *sev, const char *fac)
+{
+ struct _heimdal_syslog_data *sd;
+ heim_error_code ret;
+ int i;
+
+ if (facility == NULL)
+ return EINVAL;
+ if ((sd = calloc(1, sizeof(*sd))) == NULL)
+ return heim_enomem(context);
+ i = find_value(sev, syslogvals);
+ if (i == -1)
+ i = LOG_ERR;
+ sd->priority = i;
+ i = find_value(fac, syslogvals);
+ if (i == -1)
+ i = LOG_AUTH;
+ sd->priority |= i;
+ roken_openlog(facility->program, LOG_PID | LOG_NDELAY, i);
+ ret = heim_addlog_func(context, facility, min, max, log_syslog,
+ close_syslog, sd);
+ if (ret)
+ free(sd);
+ return ret;
+}
+
+struct file_data {
+ char *filename;
+ const char *mode;
+ struct timeval tv;
+ FILE *fd;
+ int disp;
+#define FILEDISP_KEEPOPEN 0x1
+#define FILEDISP_REOPEN 0x2
+#define FILEDISP_IFEXISTS 0x4
+};
+
+#ifndef O_CLOEXEC
+#define O_CLOEXEC 0
+#endif
+
+static void HEIM_CALLCONV
+log_file(heim_context context, const char *timestr, const char *msg, void *data)
+{
+ struct timeval tv;
+ struct file_data *f = data;
+ FILE *logf = f->fd;
+ char *msgclean;
+ size_t i = 0;
+ size_t j;
+
+ if (f->filename && (logf == NULL || (f->disp & FILEDISP_REOPEN))) {
+ int flags = O_WRONLY|O_APPEND;
+ int fd;
+
+ if (f->mode[0] == 'e') {
+ flags |= O_CLOEXEC;
+ i = 1;
+ }
+ if (f->mode[i] == 'w')
+ flags |= O_TRUNC;
+ if (f->mode[i + 1] == '+')
+ flags |= O_RDWR;
+
+ if (f->disp & FILEDISP_IFEXISTS) {
+ /* Cache failure for 1s */
+ gettimeofday(&tv, NULL);
+ if (tv.tv_sec == f->tv.tv_sec)
+ return;
+ } else {
+ flags |= O_CREAT;
+ }
+
+ fd = open(f->filename, flags, 0666); /* umask best be set */
+ if (fd == -1) {
+ if (f->disp & FILEDISP_IFEXISTS)
+ gettimeofday(&f->tv, NULL);
+ return;
+ }
+ rk_cloexec(fd);
+ logf = fdopen(fd, f->mode);
+ }
+ if (f->fd == NULL && (f->disp & FILEDISP_KEEPOPEN))
+ f->fd = logf;
+ if (logf == NULL)
+ return;
+ /*
+ * make sure the log doesn't contain special chars:
+ * we used to use strvisx(3) to encode the log, but this is
+ * inconsistent with our syslog(3) code which does not do this.
+ * It also makes it inelegant to write data which has already
+ * been quoted such as what krb5_unparse_principal() gives us.
+ * So, we change here to eat the special characters, instead.
+ */
+ if (msg && (msgclean = strdup(msg))) {
+ for (i = 0, j = 0; msg[i]; i++)
+ if (msg[i] >= 32 || msg[i] == '\t')
+ msgclean[j++] = msg[i];
+ fprintf(logf, "%s %s\n", timestr ? timestr : "", msgclean);
+ free(msgclean);
+ }
+ if (logf != f->fd)
+ fclose(logf);
+}
+
+static void HEIM_CALLCONV
+close_file(void *data)
+{
+ struct file_data *f = data;
+ if (f->fd && f->fd != stdout && f->fd != stderr)
+ fclose(f->fd);
+ free(f->filename);
+ free(data);
+}
+
+static heim_error_code
+open_file(heim_context context, heim_log_facility *fac, int min, int max,
+ const char *filename, const char *mode, FILE *f, int disp,
+ int exp_tokens)
+{
+ heim_error_code ret = 0;
+ struct file_data *fd;
+
+ if ((fd = calloc(1, sizeof(*fd))) == NULL)
+ return heim_enomem(context);
+
+ fd->filename = NULL;
+ fd->mode = mode;
+ fd->fd = f;
+ fd->disp = disp;
+
+ if (filename) {
+ if (exp_tokens)
+ ret = heim_expand_path_tokens(context, filename, 1, &fd->filename, NULL);
+ else if ((fd->filename = strdup(filename)) == NULL)
+ ret = heim_enomem(context);
+ }
+ if (ret == 0)
+ ret = heim_addlog_func(context, fac, min, max, log_file, close_file, fd);
+ if (ret) {
+ free(fd->filename);
+ free(fd);
+ } else if (disp & FILEDISP_KEEPOPEN) {
+ log_file(context, NULL, NULL, fd);
+ }
+ return ret;
+}
+
+heim_error_code
+heim_addlog_dest(heim_context context, heim_log_facility *f, const char *orig)
+{
+ heim_error_code ret = 0;
+ int min = 0, max = 3, n;
+ char c;
+ const char *p = orig;
+#ifdef _WIN32
+ const char *q;
+#endif
+
+ n = sscanf(p, "%d%c%d/", &min, &c, &max);
+ if (n == 2) {
+ if (ISPATHSEP(c)) {
+ if (min < 0) {
+ max = -min;
+ min = 0;
+ } else {
+ max = min;
+ }
+ }
+ if (c == '-')
+ max = -1;
+ }
+ if (n) {
+#ifdef _WIN32
+ q = strrchr(p, '\\');
+ if (q != NULL)
+ p = q;
+ else
+#endif
+ p = strchr(p, '/');
+ if (p == NULL) {
+ heim_set_error_message(context, EINVAL /*XXX HEIM_ERR_LOG_PARSE*/,
+ N_("failed to parse \"%s\"", ""), orig);
+ return EINVAL /*XXX HEIM_ERR_LOG_PARSE*/;
+ }
+ p++;
+ }
+ if (strcmp(p, "STDERR") == 0) {
+ ret = open_file(context, f, min, max, NULL, "a", stderr,
+ FILEDISP_KEEPOPEN, 0);
+ } else if (strcmp(p, "CONSOLE") == 0) {
+ /* XXX WIN32 */
+ ret = open_file(context, f, min, max, "/dev/console", "w", NULL,
+ FILEDISP_KEEPOPEN, 0);
+ } else if (strncmp(p, "EFILE:", 5) == 0) {
+ ret = open_file(context, f, min, max, p + sizeof("EFILE:") - 1, "a",
+ NULL, FILEDISP_IFEXISTS | FILEDISP_REOPEN, 1);
+ } else if (strncmp(p, "EFILE=", 5) == 0) {
+ ret = open_file(context, f, min, max, p + sizeof("EFILE=") - 1, "a",
+ NULL, FILEDISP_IFEXISTS | FILEDISP_KEEPOPEN, 1);
+ } else if (strncmp(p, "FILE:", sizeof("FILE:") - 1) == 0) {
+ ret = open_file(context, f, min, max, p + sizeof("FILE:") - 1, "a",
+ NULL, FILEDISP_REOPEN, 1);
+ } else if (strncmp(p, "FILE=", sizeof("FILE=") - 1) == 0) {
+ ret = open_file(context, f, min, max, p + sizeof("FILE=") - 1, "a",
+ NULL, FILEDISP_KEEPOPEN, 1);
+ } else if (strncmp(p, "DEVICE:", sizeof("DEVICE:") - 1) == 0) {
+ ret = open_file(context, f, min, max, p + sizeof("DEVICE:") - 1, "a",
+ NULL, FILEDISP_REOPEN, 0);
+ } else if (strncmp(p, "DEVICE=", sizeof("DEVICE=") - 1) == 0) {
+ ret = open_file(context, f, min, max, p + sizeof("DEVICE=") - 1, "a",
+ NULL, FILEDISP_KEEPOPEN, 0);
+ } else if (strncmp(p, "SYSLOG", 6) == 0 && (p[6] == '\0' || p[6] == ':')) {
+ char severity[128] = "";
+ char facility[128] = "";
+ p += 6;
+ if (*p != '\0')
+ p++;
+ if (strsep_copy(&p, ":", severity, sizeof(severity)) != -1)
+ strsep_copy(&p, ":", facility, sizeof(facility));
+ if (*severity == '\0')
+ strlcpy(severity, "ERR", sizeof(severity));
+ if (*facility == '\0')
+ strlcpy(facility, "AUTH", sizeof(facility));
+ ret = open_syslog(context, f, min, max, severity, facility);
+ } else {
+ ret = EINVAL; /*XXX HEIM_ERR_LOG_PARSE*/
+ heim_set_error_message(context, ret,
+ N_("unknown log type: %s", ""), p);
+ }
+ return ret;
+}
+
+heim_error_code
+heim_openlog(heim_context context,
+ const char *program,
+ const char **specs,
+ heim_log_facility **fac)
+{
+ heim_error_code ret;
+
+ ret = heim_initlog(context, program, fac);
+ if (ret)
+ return ret;
+
+ if (specs) {
+ size_t i;
+ for (i = 0; specs[i] && ret == 0; i++)
+ ret = heim_addlog_dest(context, *fac, specs[i]);
+ } else {
+ ret = heim_addlog_dest(context, *fac, "SYSLOG");
+ }
+ return ret;
+}
+
+void
+heim_closelog(heim_context context, heim_log_facility *fac)
+{
+ int i;
+
+ if (!fac || --(fac->refs))
+ return;
+ for (i = 0; i < fac->len; i++)
+ (*fac->val[i].close_func)(fac->val[i].data);
+ free(fac->val);
+ free(fac->program);
+ fac->val = NULL;
+ fac->len = 0;
+ fac->program = NULL;
+ free(fac);
+ return;
+}
+
+static void
+format_time(heim_context context, time_t t, char *s, size_t len)
+{
+ struct tm *tm = heim_context_get_log_utc(context) ?
+ gmtime(&t) : localtime(&t);
+ if (tm && strftime(s, len, heim_context_get_time_fmt(context), tm))
+ return;
+ snprintf(s, len, "%ld", (long)t);
+}
+
+#undef __attribute__
+#define __attribute__(X)
+
+heim_error_code
+heim_vlog_msg(heim_context context,
+ heim_log_facility *fac,
+ char **reply,
+ int level,
+ const char *fmt,
+ va_list ap)
+__attribute__ ((__format__ (__printf__, 5, 0)))
+{
+
+ char *msg = NULL;
+ const char *actual = NULL;
+ char buf[64];
+ time_t t = 0;
+ int i;
+
+ if (!fac)
+ fac = context->log_dest;
+ for (i = 0; fac && i < fac->len; i++)
+ if (fac->val[i].min <= level &&
+ (fac->val[i].max < 0 || fac->val[i].max >= level)) {
+ if (t == 0) {
+ t = time(NULL);
+ format_time(context, t, buf, sizeof(buf));
+ }
+ if (actual == NULL) {
+ int ret = vasprintf(&msg, fmt, ap);
+ if (ret < 0 || msg == NULL)
+ actual = fmt;
+ else
+ actual = msg;
+ }
+ (*fac->val[i].log_func)(context, buf, actual, fac->val[i].data);
+ }
+ if (reply == NULL)
+ free(msg);
+ else
+ *reply = msg;
+ return 0;
+}
+
+heim_error_code
+heim_vlog(heim_context context,
+ heim_log_facility *fac,
+ int level,
+ const char *fmt,
+ va_list ap)
+__attribute__ ((__format__ (__printf__, 4, 0)))
+{
+ return heim_vlog_msg(context, fac, NULL, level, fmt, ap);
+}
+
+heim_error_code
+heim_log_msg(heim_context context,
+ heim_log_facility *fac,
+ int level,
+ char **reply,
+ const char *fmt,
+ ...)
+__attribute__ ((__format__ (__printf__, 5, 6)))
+{
+ va_list ap;
+ heim_error_code ret;
+
+ va_start(ap, fmt);
+ ret = heim_vlog_msg(context, fac, reply, level, fmt, ap);
+ va_end(ap);
+ return ret;
+}
+
+
+heim_error_code
+heim_log(heim_context context,
+ heim_log_facility *fac,
+ int level,
+ const char *fmt,
+ ...)
+__attribute__ ((__format__ (__printf__, 4, 5)))
+{
+ va_list ap;
+ heim_error_code ret;
+
+ va_start(ap, fmt);
+ ret = heim_vlog(context, fac, level, fmt, ap);
+ va_end(ap);
+ return ret;
+}
+
+void
+heim_debug(heim_context context,
+ int level,
+ const char *fmt,
+ ...)
+__attribute__ ((__format__ (__printf__, 3, 4)))
+{
+ heim_log_facility *fac;
+ va_list ap;
+
+ if (context == NULL ||
+ (fac = heim_get_debug_dest(context)) == NULL)
+ return;
+
+ va_start(ap, fmt);
+ heim_vlog(context, fac, level, fmt, ap);
+ va_end(ap);
+}
+
+void
+heim_vdebug(heim_context context,
+ int level,
+ const char *fmt,
+ va_list ap)
+__attribute__ ((__format__ (__printf__, 3, 0)))
+{
+ heim_log_facility *fac;
+
+ if (context == NULL ||
+ (fac = heim_get_debug_dest(context)) == NULL)
+ return;
+
+ heim_vlog(context, fac, level, fmt, ap);
+}
+
+heim_error_code
+heim_have_debug(heim_context context, int level)
+{
+ return (context != NULL && heim_get_debug_dest(context) != NULL);
+}
+
+heim_error_code
+heim_add_warn_dest(heim_context context, const char *program,
+ const char *log_spec)
+{
+ heim_log_facility *fac;
+
+ heim_error_code ret;
+
+ if ((fac = heim_get_warn_dest(context)) == NULL) {
+ ret = heim_initlog(context, program, &fac);
+ if (ret)
+ return ret;
+ heim_set_warn_dest(context, fac);
+ }
+
+ ret = heim_addlog_dest(context, fac, log_spec);
+ if (ret)
+ return ret;
+ return 0;
+}
+
+heim_error_code
+heim_add_debug_dest(heim_context context, const char *program,
+ const char *log_spec)
+{
+ heim_log_facility *fac;
+ heim_error_code ret;
+
+ if ((fac = heim_get_debug_dest(context)) == NULL) {
+ ret = heim_initlog(context, program, &fac);
+ if (ret)
+ return ret;
+ heim_set_debug_dest(context, fac);
+ }
+
+ ret = heim_addlog_dest(context, fac, log_spec);
+ if (ret)
+ return ret;
+ return 0;
+}
+
+struct heim_audit_kv_tuple {
+ heim_string_t key;
+ heim_object_t value;
+};
+
+static struct heim_audit_kv_tuple zero_tuple;
+
+static struct heim_audit_kv_tuple
+fmtkv(int flags, const char *k, const char *fmt, va_list ap)
+ __attribute__ ((__format__ (__printf__, 3, 0)))
+{
+ size_t i;
+ ssize_t j;
+ struct heim_audit_kv_tuple kv;
+ char *value;
+ char *value_vis;
+
+ j = vasprintf(&value, fmt, ap);
+ if (j < 0 || value == NULL)
+ return zero_tuple;
+
+ /* We optionally eat the whitespace. */
+
+ if (flags & HEIM_SVC_AUDIT_EATWHITE) {
+ for (i=0, j=0; value[i]; i++)
+ if (value[i] != ' ' && value[i] != '\t')
+ value[j++] = value[i];
+ value[j] = '\0';
+ }
+
+ if (flags & (HEIM_SVC_AUDIT_VIS | HEIM_SVC_AUDIT_VISLAST)) {
+ int vis_flags = VIS_CSTYLE | VIS_OCTAL | VIS_NL;
+
+ if (flags & HEIM_SVC_AUDIT_VIS)
+ vis_flags |= VIS_WHITE;
+ value_vis = malloc((j + 1) * 4 + 1);
+ if (value_vis)
+ strvisx(value_vis, value, j, vis_flags);
+ free(value);
+ if (value_vis == NULL)
+ return zero_tuple;
+ } else
+ value_vis = value;
+
+ if (k)
+ kv.key = heim_string_create(k);
+ else
+ kv.key = NULL;
+ kv.value = heim_string_ref_create(value_vis, free);
+
+ return kv;
+}
+
+void
+heim_audit_vaddreason(heim_svc_req_desc r, const char *fmt, va_list ap)
+ __attribute__ ((__format__ (__printf__, 2, 0)))
+{
+ struct heim_audit_kv_tuple kv;
+
+ kv = fmtkv(HEIM_SVC_AUDIT_VISLAST, NULL, fmt, ap);
+ if (kv.value == NULL) {
+ heim_log(r->hcontext, r->logf, 1, "heim_audit_vaddreason: "
+ "failed to add reason (out of memory)");
+ return;
+ }
+
+ heim_log(r->hcontext, r->logf, 7, "heim_audit_vaddreason(): "
+ "adding reason %s", heim_string_get_utf8(kv.value));
+ if (r->reason) {
+ heim_string_t str2;
+
+ str2 = heim_string_create_with_format("%s: %s",
+ heim_string_get_utf8(kv.value),
+ heim_string_get_utf8(r->reason));
+ if (str2) {
+ heim_release(kv.value);
+ kv.value = str2;
+ }
+ }
+ heim_release(r->reason);
+ r->reason = kv.value;
+}
+
+void
+heim_audit_addreason(heim_svc_req_desc r, const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 2, 3)))
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ heim_audit_vaddreason(r, fmt, ap);
+ va_end(ap);
+}
+
+size_t
+addkv(heim_svc_req_desc r, heim_object_t key, heim_object_t value)
+{
+ size_t index;
+ heim_object_t obj;
+
+ obj = heim_dict_get_value(r->kv, key);
+ if (obj) {
+ if (heim_get_tid(obj) == HEIM_TID_ARRAY) {
+ index = heim_array_get_length(obj);
+ heim_array_append_value(obj, value);
+ } else {
+ heim_array_t array = heim_array_create();
+
+ index = 1;
+ heim_array_append_value(array, obj);
+ heim_array_append_value(array, value);
+ heim_dict_set_value(r->kv, key, array);
+ heim_release(array); /* retained by r->kv */
+ }
+ } else {
+ index = 0;
+ heim_dict_set_value(r->kv, key, value);
+ }
+
+ return index;
+}
+
+/*
+ * add a key-value token. if the key already exists, the value is
+ * promoted to an array of values.
+ */
+
+void
+heim_audit_vaddkv(heim_svc_req_desc r, int flags, const char *k,
+ const char *fmt, va_list ap)
+ __attribute__ ((__format__ (__printf__, 4, 0)))
+{
+ struct heim_audit_kv_tuple kv;
+ size_t index;
+
+ kv = fmtkv(flags, k, fmt, ap);
+ if (kv.key == NULL || kv.value == NULL) {
+ heim_log(r->hcontext, r->logf, 1, "heim_audit_vaddkv: "
+ "failed to add kv pair (out of memory)");
+ heim_release(kv.key);
+ heim_release(kv.value);
+ return;
+ }
+
+ index = addkv(r, kv.key, kv.value);
+
+ heim_log(r->hcontext, r->logf, 7, "heim_audit_vaddkv(): "
+ "kv pair[%zu] %s=%s", index,
+ heim_string_get_utf8(kv.key), heim_string_get_utf8(kv.value));
+
+ heim_release(kv.key);
+ heim_release(kv.value);
+}
+
+void
+heim_audit_addkv(heim_svc_req_desc r, int flags, const char *k,
+ const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 4, 5)))
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ heim_audit_vaddkv(r, flags, k, fmt, ap);
+ va_end(ap);
+}
+
+void
+heim_audit_addkv_timediff(heim_svc_req_desc r, const char *k,
+ const struct timeval *start,
+ const struct timeval *end)
+{
+ time_t sec;
+ int usec;
+ const char *sign = "";
+
+ if (end->tv_sec > start->tv_sec ||
+ (end->tv_sec == start->tv_sec && end->tv_usec >= start->tv_usec)) {
+ sec = end->tv_sec - start->tv_sec;
+ usec = end->tv_usec - start->tv_usec;
+ } else {
+ sec = start->tv_sec - end->tv_sec;
+ usec = start->tv_usec - end->tv_usec;
+ sign = "-";
+ }
+
+ if (usec < 0) {
+ usec += 1000000;
+ sec -= 1;
+ }
+
+ heim_audit_addkv(r, 0, k, "%s%ld.%06d", sign, (long)sec, usec);
+}
+
+void
+heim_audit_setkv_bool(heim_svc_req_desc r, const char *k, int v)
+{
+ heim_string_t key = heim_string_create(k);
+ heim_number_t value;
+
+ if (key == NULL)
+ return;
+
+ heim_log(r->hcontext, r->logf, 7, "heim_audit_setkv_bool(): "
+ "setting kv pair %s=%s", k, v ? "true" : "false");
+
+ value = heim_bool_create(v);
+ heim_dict_set_value(r->kv, key, value);
+ heim_release(key);
+ heim_release(value);
+}
+
+void
+heim_audit_addkv_number(heim_svc_req_desc r, const char *k, int64_t v)
+{
+ heim_string_t key = heim_string_create(k);
+ heim_number_t value;
+
+ if (key == NULL)
+ return;
+
+ heim_log(r->hcontext, r->logf, 7, "heim_audit_addkv_number(): "
+ "adding kv pair %s=%lld", k, (long long)v);
+
+ value = heim_number_create(v);
+ addkv(r, key, value);
+ heim_release(key);
+ heim_release(value);
+}
+
+void
+heim_audit_setkv_number(heim_svc_req_desc r, const char *k, int64_t v)
+{
+ heim_string_t key = heim_string_create(k);
+ heim_number_t value;
+
+ if (key == NULL)
+ return;
+
+ heim_log(r->hcontext, r->logf, 7, "heim_audit_setkv_number(): "
+ "setting kv pair %s=%lld", k, (long long)v);
+
+ value = heim_number_create(v);
+ heim_dict_set_value(r->kv, key, value);
+ heim_release(key);
+ heim_release(value);
+}
+
+void
+heim_audit_addkv_object(heim_svc_req_desc r, const char *k, heim_object_t value)
+{
+ heim_string_t key = heim_string_create(k);
+ heim_string_t descr;
+
+ if (key == NULL)
+ return;
+
+ descr = heim_json_copy_serialize(value, HEIM_JSON_F_NO_DATA_DICT, NULL);
+ heim_log(r->hcontext, r->logf, 7, "heim_audit_addkv_object(): "
+ "adding kv pair %s=%s",
+ k, descr ? heim_string_get_utf8(descr) : "<unprintable>");
+ addkv(r, key, value);
+ heim_release(key);
+ heim_release(descr);
+}
+
+void
+heim_audit_setkv_object(heim_svc_req_desc r, const char *k, heim_object_t value)
+{
+ heim_string_t key = heim_string_create(k);
+ heim_string_t descr;
+
+ if (key == NULL)
+ return;
+
+ descr = heim_json_copy_serialize(value, HEIM_JSON_F_NO_DATA_DICT, NULL);
+ heim_log(r->hcontext, r->logf, 7, "heim_audit_setkv_object(): "
+ "setting kv pair %s=%s",
+ k, descr ? heim_string_get_utf8(descr) : "<unprintable>");
+ heim_dict_set_value(r->kv, key, value);
+ heim_release(key);
+ heim_release(descr);
+}
+
+heim_object_t
+heim_audit_getkv(heim_svc_req_desc r, const char *k)
+{
+ heim_string_t key;
+ heim_object_t value;
+
+ key = heim_string_create(k);
+ if (key == NULL)
+ return NULL;
+
+ value = heim_dict_get_value(r->kv, key);
+ heim_release(key);
+ return value;
+}
+
+struct heim_audit_kv_buf {
+ char buf[1024];
+ size_t pos;
+ heim_object_t iter;
+};
+
+static void
+audit_trail_iterator(heim_object_t key, heim_object_t value, void *arg);
+
+static void
+audit_trail_iterator_array(heim_object_t value, void *arg, int *stop)
+{
+ struct heim_audit_kv_buf *kvb = arg;
+
+ audit_trail_iterator(kvb->iter, value, kvb);
+}
+
+static void
+audit_trail_iterator(heim_object_t key, heim_object_t value, void *arg)
+{
+ struct heim_audit_kv_buf *kvb = arg;
+ char num[32];
+ const char *k = heim_string_get_utf8(key), *v = NULL;
+ char *b64 = NULL;
+
+ if (k == NULL || *k == '#') /* # keys are hidden */
+ return;
+
+ switch (heim_get_tid(value)) {
+ case HEIM_TID_STRING:
+ v = heim_string_get_utf8(value);
+ break;
+ case HEIM_TID_NUMBER:
+ snprintf(num, sizeof(num), "%lld", (long long)heim_number_get_long(value));
+ v = num;
+ break;
+ case HEIM_TID_NULL:
+ v = "null";
+ break;
+ case HEIM_TID_BOOL:
+ v = heim_bool_val(value) ? "true" : "false";
+ break;
+ case HEIM_TID_ARRAY:
+ if (kvb->iter)
+ break; /* arrays cannot be nested */
+
+ kvb->iter = key;
+ heim_array_iterate_f(value, kvb, audit_trail_iterator_array);
+ kvb->iter = NULL;
+ break;
+ case HEIM_TID_DATA: {
+ const heim_octet_string *data = heim_data_get_data(value);
+ if (rk_base64_encode(data->data, data->length, &b64) >= 0)
+ v = b64;
+ break;
+ }
+ default:
+ break;
+ }
+
+ if (v == NULL)
+ return;
+
+ if (kvb->pos < sizeof(kvb->buf) - 1)
+ kvb->buf[kvb->pos++] = ' ';
+ for (; *k && kvb->pos < sizeof(kvb->buf) - 1; kvb->pos++)
+ kvb->buf[kvb->pos] = *k++;
+ if (kvb->pos < sizeof(kvb->buf) - 1)
+ kvb->buf[kvb->pos++] = '=';
+ for (; *v && kvb->pos < sizeof(kvb->buf) - 1; kvb->pos++)
+ kvb->buf[kvb->pos] = *v++;
+
+ free(b64);
+}
+
+void
+heim_audit_trail(heim_svc_req_desc r, heim_error_code ret, const char *retname)
+{
+ const char *retval;
+ struct heim_audit_kv_buf kvb;
+ char retvalbuf[30]; /* Enough for UNKNOWN-%d */
+
+#define CASE(x) case x : retval = #x; break
+ if (retname) {
+ retval = retname;
+ } else switch (ret ? ret : r->error_code) {
+ CASE(ENOMEM);
+ CASE(ENOENT);
+ CASE(EACCES);
+ case 0:
+ retval = "SUCCESS";
+ break;
+ default:
+ /* Wish we had a com_err number->symbolic name function */
+ (void) snprintf(retvalbuf, sizeof(retvalbuf), "UNKNOWN-%d", ret);
+ retval = retvalbuf;
+ break;
+ }
+
+ heim_audit_addkv_timediff(r, "elapsed", &r->tv_start, &r->tv_end);
+ if (r->e_text && r->kv)
+ heim_audit_addkv(r, HEIM_SVC_AUDIT_VIS, "e-text", "%s", r->e_text);
+
+ memset(&kvb, 0, sizeof(kvb));
+ if (r->kv)
+ heim_dict_iterate_f(r->kv, &kvb, audit_trail_iterator);
+ kvb.buf[kvb.pos] = '\0';
+
+ heim_log(r->hcontext, r->logf, 3, "%s %s %s %s %s%s%s%s",
+ r->reqtype, retval, r->from,
+ r->cname ? r->cname : "<unknown>",
+ r->sname ? r->sname : "<unknown>",
+ kvb.buf, r->reason ? " reason=" : "",
+ r->reason ? heim_string_get_utf8(r->reason) : "");
+}
diff --git a/third_party/heimdal/lib/base/null.c b/third_party/heimdal/lib/base/null.c
new file mode 100644
index 0000000..43bde96
--- /dev/null
+++ b/third_party/heimdal/lib/base/null.c
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+
+struct heim_type_data _heim_null_object = {
+ HEIM_TID_NULL,
+ "null-object",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+heim_null_t
+heim_null_create(void)
+{
+ return heim_base_make_tagged_object(0, HEIM_TID_NULL);
+}
diff --git a/third_party/heimdal/lib/base/number.c b/third_party/heimdal/lib/base/number.c
new file mode 100644
index 0000000..8833c8b
--- /dev/null
+++ b/third_party/heimdal/lib/base/number.c
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+
+static void HEIM_CALLCONV
+number_dealloc(void *ptr)
+{
+}
+
+static int
+number_cmp(void *a, void *b)
+{
+ int na, nb;
+
+ if (heim_base_is_tagged_object(a))
+ na = heim_base_tagged_object_value(a);
+ else
+ na = *(int *)a;
+
+ if (heim_base_is_tagged_object(b))
+ nb = heim_base_tagged_object_value(b);
+ else
+ nb = *(int *)b;
+
+ return na - nb;
+}
+
+static uintptr_t
+number_hash(void *ptr)
+{
+ if (heim_base_is_tagged_object(ptr))
+ return heim_base_tagged_object_value(ptr);
+ return (uintptr_t)*(int64_t *)ptr;
+}
+
+struct heim_type_data _heim_number_object = {
+ HEIM_TID_NUMBER,
+ "number-object",
+ NULL,
+ number_dealloc,
+ NULL,
+ number_cmp,
+ number_hash,
+ NULL
+};
+
+/**
+ * Create a number object
+ *
+ * @param the number to contain in the object
+ *
+ * @return a number object
+ */
+
+heim_number_t
+heim_number_create(int64_t number)
+{
+ heim_number_t n;
+
+ if (number < 0xffffff && number >= 0)
+ return heim_base_make_tagged_object(number, HEIM_TID_NUMBER);
+
+ n = _heim_alloc_object(&_heim_number_object, sizeof(int64_t));
+ if (n)
+ *((int64_t *)n) = number;
+ return n;
+}
+
+/**
+ * Return the type ID of number objects
+ *
+ * @return type id of number objects
+ */
+
+heim_tid_t
+heim_number_get_type_id(void)
+{
+ return HEIM_TID_NUMBER;
+}
+
+/**
+ * Get the int value of the content
+ *
+ * @param number the number object to get the value from
+ *
+ * @return an int
+ */
+
+int
+heim_number_get_int(heim_number_t number)
+{
+ if (heim_base_is_tagged_object(number))
+ return heim_base_tagged_object_value(number);
+ return (int)(*(int64_t *)number);
+}
+
+int64_t
+heim_number_get_long(heim_number_t number)
+{
+ if (heim_base_is_tagged_object(number))
+ return heim_base_tagged_object_value(number);
+ return *(int64_t *)number;
+}
diff --git a/third_party/heimdal/lib/base/plugin.c b/third_party/heimdal/lib/base/plugin.c
new file mode 100644
index 0000000..355306d
--- /dev/null
+++ b/third_party/heimdal/lib/base/plugin.c
@@ -0,0 +1,785 @@
+/*
+ * Copyright (c) 2006 - 2020 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2018 AuriStor, Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+#include "common_plugin.h"
+
+/*
+ * Documentation for the Heimdal plugin system is in lib/krb5/plugin.c and
+ * lib/krb5/krb5-plugin.7.
+ */
+
+/*
+ * Definitions:
+ *
+ * module - a category of plugin module, identified by subsystem
+ * (e.g., "krb5")
+ * dso - a library for a module containing a map of plugin
+ * types to plugins (e.g. "service_locator")
+ * plugin - a set of callbacks and state that follows the
+ * common plugin module definition (version, init, fini)
+ *
+ * Obviously it would have been clearer to use the term "module" rather than
+ * "DSO" given there is an internal "DSO", but "module" was already taken...
+ *
+ * modules := { module: dsos }
+ * dsos := { path, dsohandle, plugins-by-name }
+ * plugins-by-name := { plugin-name: [plug] }
+ * plug := { ftable, ctx }
+ */
+
+/* global module use, use copy_modules() accessor to access */
+static heim_dict_t __modules;
+
+static HEIMDAL_MUTEX modules_mutex = HEIMDAL_MUTEX_INITIALIZER;
+
+static void
+copy_modules_once(void *context)
+{
+ heim_dict_t *modules = (heim_dict_t *)context;
+
+ *modules = heim_dict_create(11);
+ heim_assert(*modules, "plugin modules array allocation failure");
+}
+
+/* returns global modules list, refcount +1 */
+static heim_dict_t
+copy_modules(void)
+{
+ static heim_base_once_t modules_once = HEIM_BASE_ONCE_INIT;
+
+ heim_base_once_f(&modules_once, &__modules, copy_modules_once);
+
+ return heim_retain(__modules);
+}
+
+/* returns named module, refcount +1 */
+static heim_dict_t
+copy_module(const char *name)
+{
+ heim_string_t module_name = heim_string_create(name);
+ heim_dict_t modules = copy_modules();
+ heim_dict_t module;
+
+ module = heim_dict_copy_value(modules, module_name);
+ if (module == NULL) {
+ module = heim_dict_create(11);
+ heim_dict_set_value(modules, module_name, module);
+ }
+
+ heim_release(modules);
+ heim_release(module_name);
+
+ return module;
+}
+
+/* DSO helpers */
+struct heim_dso {
+ heim_string_t path;
+ heim_dict_t plugins_by_name;
+ void *dsohandle;
+};
+
+static void HEIM_CALLCONV
+dso_dealloc(void *ptr)
+{
+ struct heim_dso *p = ptr;
+
+ heim_release(p->path);
+ heim_release(p->plugins_by_name);
+#ifdef HAVE_DLOPEN
+ if (p->dsohandle)
+ dlclose(p->dsohandle);
+#endif
+}
+
+/* returns internal "DSO" for name, refcount +1 */
+static struct heim_dso *
+copy_internal_dso(const char *name)
+{
+ heim_string_t dso_name = HSTR("__HEIMDAL_INTERNAL_DSO__");
+ heim_dict_t module = copy_module(name);
+ struct heim_dso *dso;
+
+ if (module == NULL)
+ return NULL;
+
+ dso = heim_dict_copy_value(module, dso_name);
+ if (dso == NULL) {
+ dso = heim_alloc(sizeof(*dso), "heim-dso", dso_dealloc);
+
+ dso->path = dso_name;
+ dso->plugins_by_name = heim_dict_create(11);
+
+ heim_dict_set_value(module, dso_name, dso);
+ }
+
+ heim_release(module);
+
+ return dso;
+}
+
+struct heim_plugin {
+ heim_plugin_common_ftable_p ftable;
+ void *ctx;
+};
+
+static void HEIM_CALLCONV
+plugin_free(void *ptr)
+{
+ struct heim_plugin *pl = ptr;
+
+ if (pl->ftable && pl->ftable->fini)
+ pl->ftable->fini(pl->ctx);
+}
+
+struct heim_plugin_register_ctx {
+ void *symbol;
+ int is_dup;
+};
+
+static void
+plugin_register_check_dup(heim_object_t value, void *ctx, int *stop)
+{
+ struct heim_plugin_register_ctx *pc = ctx;
+ struct heim_plugin *pl = value;
+
+ if (pl->ftable == pc->symbol) {
+ pc->is_dup = 1;
+ *stop = 1;
+ }
+}
+
+/**
+ * Register a plugin symbol name of specific type.
+ * @param context a Keberos context
+ * @param module name of plugin module (e.g., "krb5")
+ * @param name name of plugin symbol (e.g., "krb5_plugin_kuserok")
+ * @param ftable a pointer to a function pointer table
+ * @return In case of error a non zero error com_err error is returned
+ * and the Kerberos error string is set.
+ *
+ * @ingroup heim_support
+ */
+
+heim_error_code
+heim_plugin_register(heim_context context,
+ heim_pcontext pcontext,
+ const char *module,
+ const char *name,
+ void *ftable)
+{
+ heim_error_code ret;
+ heim_array_t plugins;
+ heim_string_t hname;
+ struct heim_dso *dso;
+ struct heim_plugin_register_ctx ctx;
+
+ ctx.symbol = ftable;
+ ctx.is_dup = 0;
+
+ HEIMDAL_MUTEX_lock(&modules_mutex);
+
+ dso = copy_internal_dso(module);
+ hname = heim_string_create(name);
+ plugins = heim_dict_copy_value(dso->plugins_by_name, hname);
+ if (plugins != NULL)
+ heim_array_iterate_f(plugins, &ctx, plugin_register_check_dup);
+ else {
+ plugins = heim_array_create();
+ heim_dict_set_value(dso->plugins_by_name, hname, plugins);
+ }
+
+ ret = 0;
+ if (!ctx.is_dup) {
+ /* Note: refactored plugin API only supports common plugin layout */
+ struct heim_plugin *pl;
+
+ pl = heim_alloc(sizeof(*pl), "heim-plugin", plugin_free);
+ if (pl == NULL) {
+ ret = heim_enomem(context);
+ } else {
+ pl->ftable = ftable;
+ ret = pl->ftable->init(pcontext, &pl->ctx);
+ if (ret == 0) {
+ heim_array_append_value(plugins, pl);
+ heim_debug(context, 5, "Registered %s plugin", name);
+ }
+ heim_release(pl);
+ }
+ }
+
+ HEIMDAL_MUTEX_unlock(&modules_mutex);
+
+ heim_release(dso);
+ heim_release(hname);
+ heim_release(plugins);
+
+ return ret;
+}
+
+#ifdef HAVE_DLOPEN
+
+static char *
+resolve_origin(const char *di, const char *module)
+{
+#ifdef HAVE_DLADDR
+ Dl_info dl_info;
+ const char *dname;
+ char *path, *p;
+
+ if (strncmp(di, "$ORIGIN/", sizeof("$ORIGIN/") - 1) != 0 &&
+ strcmp(di, "$ORIGIN") != 0)
+ return strdup(di);
+
+ di += sizeof("$ORIGIN") - 1;
+
+ if (dladdr(heim_plugin_register, &dl_info) == 0) {
+ char *s = NULL;
+
+ /* dladdr() failed */
+ if (asprintf(&s, LIBDIR "/plugin/%s", module) == -1)
+ return NULL;
+ return s;
+ }
+
+ dname = dl_info.dli_fname;
+#ifdef _WIN32
+ p = strrchr(dname, '\\');
+ if (p == NULL)
+#endif
+ p = strrchr(dname, '/');
+ if (p) {
+ if (asprintf(&path, "%.*s%s", (int) (p - dname), dname, di) == -1)
+ return NULL;
+ } else {
+ if (asprintf(&path, "%s%s", dname, di) == -1)
+ return NULL;
+ }
+
+ return path;
+#else
+ char *s = NULL;
+
+ if (strncmp(di, "$ORIGIN/", sizeof("$ORIGIN/") - 1) != 0 &&
+ strcmp(di, "$ORIGIN") != 0)
+ return strdup(di);
+ if (asprintf(&s, LIBDIR "/plugin/%s", module) == -1)
+ return NULL;
+ return s;
+#endif /* HAVE_DLADDR */
+}
+
+#endif /* HAVE_DLOPEN */
+
+/**
+ * Load plugins (new system) for the given module @module from the given
+ * directory @paths.
+ *
+ * Inputs:
+ *
+ * @context A heim_context
+ * @module Name of plugin module (typically "krb5")
+ * @paths Array of directory paths where to look
+ */
+void
+heim_load_plugins(heim_context context,
+ const char *module,
+ const char **paths)
+{
+#ifdef HAVE_DLOPEN
+ heim_string_t s = heim_string_create(module);
+ heim_dict_t mod, modules;
+ struct dirent *entry;
+ heim_error_code ret;
+ const char **di;
+ char *dirname = NULL;
+ DIR *d;
+#ifdef _WIN32
+ char *plugin_prefix;
+ size_t plugin_prefix_len;
+
+ if (asprintf(&plugin_prefix, "plugin_%s_", module) == -1)
+ return;
+ plugin_prefix_len = (plugin_prefix ? strlen(plugin_prefix) : 0);
+#endif
+
+ HEIMDAL_MUTEX_lock(&modules_mutex);
+
+ modules = copy_modules();
+
+ mod = heim_dict_copy_value(modules, s);
+ if (mod == NULL) {
+ mod = heim_dict_create(11);
+ if (mod == NULL) {
+ HEIMDAL_MUTEX_unlock(&modules_mutex);
+ heim_release(s);
+ heim_release(modules);
+ heim_debug(context, 5, "Load plugins for module %s failed", module);
+ return;
+ }
+ heim_dict_set_value(modules, s, mod);
+ }
+ heim_release(s);
+ heim_release(modules);
+
+ for (di = paths; *di != NULL; di++) {
+ free(dirname);
+ dirname = resolve_origin(*di, module);
+ if (dirname == NULL) {
+ heim_debug(context, 10, "Could not resolve %s", *di);
+ continue;
+ }
+ d = opendir(dirname);
+ if (d == NULL) {
+ heim_debug(context, 10, "No such directory %s", dirname);
+ continue;
+ }
+ rk_cloexec_dir(d);
+
+ heim_debug(context, 10, "Load plugins for module %s; search %s (%s)",
+ module, *di, dirname);
+
+ while ((entry = readdir(d)) != NULL) {
+ char *n = entry->d_name;
+ char *path = NULL;
+ heim_string_t spath;
+ struct heim_dso *p;
+
+ /* skip . and .. */
+ if (n[0] == '.' && (n[1] == '\0' || (n[1] == '.' && n[2] == '\0')))
+ continue;
+
+ ret = 0;
+#ifdef _WIN32
+ /*
+ * On Windows, plugins must be loaded from the same directory as
+ * heimdal.dll (typically the assembly directory) and must have
+ * the name form "plugin_<module>_<name>.dll".
+ */
+ {
+ char *ext;
+
+ if (strnicmp(n, plugin_prefix, plugin_prefix_len) != 0)
+ continue;
+ ext = strrchr(n, '.');
+ if (ext == NULL || stricmp(ext, ".dll") != 0)
+ continue;
+
+ ret = asprintf(&path, "%s\\%s", dirname, n);
+ if (ret < 0 || path == NULL)
+ continue;
+ }
+#endif
+#ifdef __APPLE__
+ { /* support loading bundles on MacOS */
+ size_t len = strlen(n);
+ if (len > 7 && strcmp(&n[len - 7], ".bundle") == 0)
+ ret = asprintf(&path, "%s/%s/Contents/MacOS/%.*s", dirname, n, (int)(len - 7), n);
+ }
+#endif
+ if (ret < 0 || path == NULL)
+ ret = asprintf(&path, "%s/%s", dirname, n);
+
+ if (ret < 0 || path == NULL)
+ continue;
+
+ spath = heim_string_create(n);
+ if (spath == NULL) {
+ free(path);
+ continue;
+ }
+
+ /* check if already cached */
+ p = heim_dict_copy_value(mod, spath);
+ if (p == NULL) {
+ p = heim_alloc(sizeof(*p), "heim-dso", dso_dealloc);
+ if (p)
+ p->dsohandle = dlopen(path, RTLD_LOCAL|RTLD_LAZY|RTLD_GROUP);
+ if (p && p->dsohandle) {
+ p->path = heim_retain(spath);
+ p->plugins_by_name = heim_dict_create(11);
+ heim_dict_set_value(mod, spath, p);
+ heim_debug(context, 10, "Load plugins for module %s; "
+ "found DSO %s", module, path);
+ }
+ }
+ heim_release(p);
+ heim_release(spath);
+ free(path);
+ }
+ closedir(d);
+ }
+ free(dirname);
+ HEIMDAL_MUTEX_unlock(&modules_mutex);
+ heim_release(mod);
+#ifdef _WIN32
+ if (plugin_prefix)
+ free(plugin_prefix);
+#endif
+#endif /* HAVE_DLOPEN */
+}
+
+/**
+ * Unload plugins of the given @module name.
+ *
+ * Params:
+ *
+ * @module Name of module whose plusins to unload.
+ */
+void
+heim_unload_plugins(heim_context context, const char *module)
+{
+ heim_string_t sname = heim_string_create(module);
+ heim_dict_t modules;
+
+ HEIMDAL_MUTEX_lock(&modules_mutex);
+
+ modules = copy_modules();
+ heim_dict_delete_key(modules, sname);
+
+ HEIMDAL_MUTEX_unlock(&modules_mutex);
+
+ heim_release(modules);
+ heim_release(sname);
+}
+
+struct iter_ctx {
+ heim_context context;
+ heim_pcontext pcontext;
+ heim_string_t n;
+ struct heim_plugin_data *caller;
+ int flags;
+ heim_array_t result;
+ int32_t (HEIM_LIB_CALL *func)(void *, const void *, void *, void *);
+ void *userctx;
+ int32_t ret;
+ int32_t plugin_no_handle_retval;
+};
+
+#ifdef HAVE_DLOPEN
+/*
+ * Add plugin from a DSO that exports the plugin structure directly. This is
+ * provided for backwards compatibility with prior versions of Heimdal, but it
+ * does not allow a module to export multiple plugins, nor does it allow
+ * instance validation.
+ */
+static heim_array_t
+add_dso_plugin_struct(heim_context context,
+ heim_pcontext pcontext,
+ const char *dsopath,
+ void *dsohandle,
+ const char *name)
+{
+ heim_error_code ret;
+ heim_plugin_common_ftable_p cpm;
+ struct heim_plugin *pl;
+ heim_array_t plugins;
+
+ if (dsohandle == NULL)
+ return NULL;
+
+ /* suppress error here because we may be looking for a different plugin type */
+ cpm = (heim_plugin_common_ftable_p)dlsym(dsohandle, name);
+ if (cpm == NULL) {
+ heim_debug(context, 15, "Symbol %s not found in %s", name, dsopath);
+ return NULL;
+ }
+
+ heim_warnx(context, "plugin %s uses deprecated loading mechanism", dsopath);
+
+ pl = heim_alloc(sizeof(*pl), "heim-plugin", plugin_free);
+
+ ret = cpm->init(pcontext, &pl->ctx);
+ if (ret) {
+ heim_warn(context, ret, "plugin %s failed to initialize", dsopath);
+ heim_release(pl);
+ return NULL;
+ }
+
+ pl->ftable = cpm;
+
+ plugins = heim_array_create();
+ heim_array_append_value(plugins, pl);
+ heim_release(pl);
+
+ return plugins;
+}
+
+static int
+validate_plugin_deps(heim_context context,
+ struct heim_plugin_data *caller,
+ const char *dsopath,
+ heim_get_instance_func_t get_instance)
+{
+ size_t i;
+
+ if (get_instance == NULL) {
+ heim_warnx(context, "plugin %s omitted instance callback",
+ dsopath);
+ return FALSE;
+ }
+
+ for (i = 0; caller->deps[i] != NULL; i++) {
+ uintptr_t heim_instance, plugin_instance;
+
+ heim_instance = caller->get_instance(caller->deps[i]);
+ plugin_instance = get_instance(caller->deps[i]);
+
+ if (heim_instance == 0 || plugin_instance == 0)
+ continue;
+
+ if (heim_instance != plugin_instance) {
+ heim_warnx(context, "plugin %s library %s linked against different "
+ "instance of Heimdal (got %zu, us %zu)",
+ dsopath, caller->deps[i],
+ plugin_instance, heim_instance);
+ return FALSE;
+ }
+ heim_debug(context, 10, "Validated plugin library dependency %s for %s",
+ caller->deps[i], dsopath);
+ }
+
+ return TRUE;
+}
+
+/*
+ * New interface from Heimdal 8 where a DSO can export a load function
+ * that can return both a Heimdal instance identifier along with an
+ * array of plugins.
+ */
+static heim_array_t
+add_dso_plugins_load_fn(heim_context context,
+ heim_pcontext pcontext,
+ struct heim_plugin_data *caller,
+ const char *dsopath,
+ void *dsohandle)
+{
+ heim_error_code ret;
+ heim_array_t plugins;
+ heim_plugin_load_t load_fn;
+ char *sym = NULL;
+ size_t i;
+ heim_get_instance_func_t get_instance;
+ size_t n_ftables;
+ heim_plugin_common_ftable_cp *ftables;
+
+ if (asprintf(&sym, "%s_plugin_load", caller->name) == -1 || sym == NULL)
+ return NULL;
+
+ /* suppress error here because we may be looking for a different plugin type */
+ load_fn = (heim_plugin_load_t)dlsym(dsohandle, sym);
+ if (load_fn == NULL) {
+ heim_debug(context, 15, "Symbol %s not found in %s", sym, dsopath);
+ free(sym);
+ return NULL;
+ }
+
+ ret = load_fn(pcontext, &get_instance, &n_ftables, &ftables);
+ if (ret) {
+ heim_warn(context, ret, "plugin %s failed to load", dsopath);
+ free(sym);
+
+ /* fallback to loading structure directly */
+ return add_dso_plugin_struct(context, pcontext, dsopath,
+ dsohandle, caller->name);
+ }
+
+ if (!validate_plugin_deps(context, caller, dsopath, get_instance)) {
+ free(sym);
+ return NULL;
+ }
+
+ plugins = heim_array_create();
+
+ for (i = 0; i < n_ftables; i++) {
+ heim_plugin_common_ftable_cp cpm = ftables[i];
+ struct heim_plugin *pl;
+
+ pl = heim_alloc(sizeof(*pl), "heim-plugin", plugin_free);
+
+ ret = cpm->init(pcontext, &pl->ctx);
+ if (ret) {
+ heim_warn(context, ret, "plugin %s[%zu] failed to initialize",
+ dsopath, i);
+ } else {
+ pl->ftable = rk_UNCONST(cpm);
+ heim_array_append_value(plugins, pl);
+ }
+ heim_release(pl);
+ }
+
+ heim_debug(context, 15, "DSO %s loaded (%s)", dsopath, sym);
+ free(sym);
+ return plugins;
+}
+#endif /* HAVE_DLOPEN */
+
+static void
+reduce_by_version(heim_object_t value, void *ctx, int *stop)
+{
+ struct iter_ctx *s = ctx;
+ struct heim_plugin *pl = value;
+
+ if (pl->ftable && pl->ftable->minor_version >= s->caller->min_version)
+ heim_array_append_value(s->result, pl);
+}
+
+static void
+search_modules(heim_object_t key, heim_object_t value, void *ctx)
+{
+ struct iter_ctx *s = ctx;
+ struct heim_dso *p = value;
+ heim_array_t plugins = heim_dict_copy_value(p->plugins_by_name, s->n);
+
+#ifdef HAVE_DLOPEN
+ if (plugins == NULL && p->dsohandle) {
+ const char *path = heim_string_get_utf8(p->path);
+
+ plugins = add_dso_plugins_load_fn(s->context,
+ s->pcontext,
+ s->caller,
+ path,
+ p->dsohandle);
+ if (plugins) {
+ heim_dict_set_value(p->plugins_by_name, s->n, plugins);
+ heim_debug(s->context, 5, "Loaded %zu %s %s plugin%s from %s",
+ heim_array_get_length(plugins),
+ s->caller->module, s->caller->name,
+ heim_array_get_length(plugins) > 1 ? "s" : "",
+ path);
+ }
+ }
+#endif /* HAVE_DLOPEN */
+
+ if (plugins) {
+ heim_array_iterate_f(plugins, s, reduce_by_version);
+ heim_release(plugins);
+ }
+}
+
+static void
+eval_results(heim_object_t value, void *ctx, int *stop)
+{
+ struct heim_plugin *pl = value;
+ struct iter_ctx *s = ctx;
+
+ if (s->ret != s->plugin_no_handle_retval)
+ return;
+
+ s->ret = s->func(s->pcontext, pl->ftable, pl->ctx, s->userctx);
+ if (s->ret != s->plugin_no_handle_retval
+ && !(s->flags & HEIM_PLUGIN_INVOKE_ALL))
+ *stop = 1;
+}
+
+/**
+ * Run plugins for the given @module (e.g., "krb5") and @name (e.g.,
+ * "kuserok"). Specifically, the @func is invoked once per-plugin with
+ * four arguments: the @context, the plugin symbol value (a pointer to a
+ * struct whose first three fields are the same as common_plugin_ftable),
+ * a context value produced by the plugin's init method, and @userctx.
+ *
+ * @func should unpack arguments for a plugin function and invoke it
+ * with arguments taken from @userctx. @func should save plugin
+ * outputs, if any, in @userctx.
+ *
+ * All loaded and registered plugins are invoked via @func until @func
+ * returns something other than @nohandle. Plugins that have nothing to
+ * do for the given arguments should return the same value as @nohandle.
+ *
+ * Inputs:
+ *
+ * @context A heim_context
+ * @pcontext A context for the plugin, such as a krb5_context
+ * @module Name of module (typically "krb5")
+ * @name Name of pluggable interface (e.g., "kuserok")
+ * @min_version Lowest acceptable plugin minor version number
+ * @flags Flags (none defined at this time)
+ * @nohandle Flags (none defined at this time)
+ * @userctx Callback data for the callback function @func
+ * @func A callback function, invoked once per-plugin
+ *
+ * Outputs: None, other than the return value and such outputs as are
+ * gathered by @func.
+ */
+heim_error_code
+heim_plugin_run_f(heim_context context,
+ heim_pcontext pcontext,
+ struct heim_plugin_data *caller,
+ int flags,
+ int32_t nohandle,
+ void *userctx,
+ int32_t (HEIM_LIB_CALL *func)(void *, const void *, void *, void *))
+{
+ heim_string_t m = heim_string_create(caller->module);
+ heim_dict_t modules, dict = NULL;
+ struct iter_ctx s;
+
+ s.context = context;
+ s.pcontext = pcontext;
+ s.caller = caller;
+ s.n = heim_string_create(caller->name);
+ s.flags = flags;
+ s.result = heim_array_create();
+ s.func = func;
+ s.userctx = userctx;
+ s.plugin_no_handle_retval = nohandle;
+ s.ret = nohandle;
+
+ HEIMDAL_MUTEX_lock(&modules_mutex);
+
+ /* Get loaded plugins */
+ modules = copy_modules();
+ dict = heim_dict_copy_value(modules, m);
+
+ /* Add loaded plugins to s.result array */
+ if (dict)
+ heim_dict_iterate_f(dict, &s, search_modules);
+
+ /* We don't need to hold modules_mutex during plugin invocation */
+ HEIMDAL_MUTEX_unlock(&modules_mutex);
+
+ /* Invoke loaded plugins */
+ heim_array_iterate_f(s.result, &s, eval_results);
+
+ heim_release(s.result);
+ heim_release(s.n);
+ heim_release(dict);
+ heim_release(m);
+ heim_release(modules);
+
+ return s.ret;
+}
diff --git a/third_party/heimdal/lib/base/roken_rename.h b/third_party/heimdal/lib/base/roken_rename.h
new file mode 100644
index 0000000..ea72098
--- /dev/null
+++ b/third_party/heimdal/lib/base/roken_rename.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __heimbase_roken_rename_h__
+#define __heimbase_roken_rename_h__
+
+#ifndef HAVE_VSNPRINTF
+#define rk_vsnprintf heimbase_vsnprintf
+#endif
+#ifndef HAVE_ASPRINTF
+#define rk_asprintf heimbase_asprintf
+#endif
+#ifndef HAVE_ASNPRINTF
+#define rk_asnprintf heimbase_asnprintf
+#endif
+#ifndef HAVE_VASPRINTF
+#define rk_vasprintf heimbase_vasprintf
+#endif
+#ifndef HAVE_VASNPRINTF
+#define rk_vasnprintf heimbase_vasnprintf
+#endif
+#ifndef HAVE_STRDUP
+#define rk_strdup heimbase_strdup
+#endif
+#ifndef HAVE_STRNDUP
+#define rk_strndup heimbase_strndup
+#endif
+
+#endif /* __heimbase_roken_rename_h__ */
diff --git a/third_party/heimdal/lib/base/string.c b/third_party/heimdal/lib/base/string.c
new file mode 100644
index 0000000..f942447
--- /dev/null
+++ b/third_party/heimdal/lib/base/string.c
@@ -0,0 +1,260 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "baselocl.h"
+#include <string.h>
+
+static void HEIM_CALLCONV
+string_dealloc(void *ptr)
+{
+ heim_string_t s = ptr;
+ heim_string_free_f_t *deallocp;
+ heim_string_free_f_t dealloc;
+
+ if (*(const char *)ptr != '\0')
+ return;
+
+ /* Possible string ref */
+ deallocp = _heim_get_isaextra(s, 0);
+ dealloc = *deallocp;
+ if (dealloc != NULL) {
+ char **strp = _heim_get_isaextra(s, 1);
+ dealloc(*strp);
+ }
+}
+
+static int
+string_cmp(void *a, void *b)
+{
+ if (*(char *)a == '\0') {
+ char **strp = _heim_get_isaextra(a, 1);
+
+ if (*strp != NULL)
+ a = *strp; /* a is a string ref */
+ }
+ if (*(char *)b == '\0') {
+ char **strp = _heim_get_isaextra(b, 1);
+
+ if (*strp != NULL)
+ b = *strp; /* b is a string ref */
+ }
+ return strcmp(a, b);
+}
+
+static uintptr_t
+string_hash(void *ptr)
+{
+ const char *s = ptr;
+ uintptr_t n;
+
+ for (n = 0; *s; ++s)
+ n += *s;
+ return n;
+}
+
+struct heim_type_data _heim_string_object = {
+ HEIM_TID_STRING,
+ "string-object",
+ NULL,
+ string_dealloc,
+ NULL,
+ string_cmp,
+ string_hash,
+ NULL
+};
+
+/**
+ * Create a string object
+ *
+ * @param string the string to create, must be an utf8 string
+ *
+ * @return string object
+ */
+
+heim_string_t
+heim_string_create(const char *string)
+{
+ return heim_string_create_with_bytes(string, strlen(string));
+}
+
+/**
+ * Create a string object without copying the source.
+ *
+ * @param string the string to referenced, must be UTF-8
+ * @param dealloc the function to use to release the referece to the string
+ *
+ * @return string object
+ */
+
+heim_string_t
+heim_string_ref_create(const char *string, heim_string_free_f_t dealloc)
+{
+ heim_string_t s;
+ heim_string_free_f_t *deallocp;
+
+ s = _heim_alloc_object(&_heim_string_object, 1);
+ if (s) {
+ const char **strp;
+
+ ((char *)s)[0] = '\0';
+ deallocp = _heim_get_isaextra(s, 0);
+ *deallocp = dealloc;
+ strp = _heim_get_isaextra(s, 1);
+ *strp = string;
+ }
+ return s;
+}
+
+/**
+ * Create a string object
+ *
+ * @param string the string to create, must be an utf8 string
+ * @param len the length of the string
+ *
+ * @return string object
+ */
+
+heim_string_t
+heim_string_create_with_bytes(const void *data, size_t len)
+{
+ heim_string_t s;
+
+ s = _heim_alloc_object(&_heim_string_object, len + 1);
+ if (s) {
+ memcpy(s, data, len);
+ ((char *)s)[len] = '\0';
+ }
+ return s;
+}
+
+/**
+ * Create a string object using a format string
+ *
+ * @param fmt format string
+ * @param ...
+ *
+ * @return string object
+ */
+
+heim_string_t
+heim_string_create_with_format(const char *fmt, ...)
+{
+ heim_string_t s;
+ char *str = NULL;
+ va_list ap;
+ int ret;
+
+ va_start(ap, fmt);
+ ret = vasprintf(&str, fmt, ap);
+ va_end(ap);
+ if (ret < 0 || str == NULL)
+ return NULL;
+
+ s = heim_string_ref_create(str, free);
+ if (s == NULL)
+ free(str);
+ return s;
+}
+
+/**
+ * Return the type ID of string objects
+ *
+ * @return type id of string objects
+ */
+
+heim_tid_t
+heim_string_get_type_id(void)
+{
+ return HEIM_TID_STRING;
+}
+
+/**
+ * Get the string value of the content.
+ *
+ * @param string the string object to get the value from
+ *
+ * @return a utf8 string
+ */
+
+const char *
+heim_string_get_utf8(heim_string_t string)
+{
+ if (*(const char *)string == '\0') {
+ const char **strp;
+
+ /* String ref */
+ strp = _heim_get_isaextra(string, 1);
+ if (*strp != NULL)
+ return *strp;
+ }
+ return (const char *)string;
+}
+
+/*
+ *
+ */
+
+static void
+init_string(void *ptr)
+{
+ heim_dict_t *dict = ptr;
+ *dict = heim_dict_create(101);
+ heim_assert(*dict != NULL, "__heim_string_constant");
+}
+
+heim_string_t
+__heim_string_constant(const char *_str)
+{
+ static HEIMDAL_MUTEX mutex = HEIMDAL_MUTEX_INITIALIZER;
+ static heim_base_once_t once;
+ static heim_dict_t dict = NULL;
+ heim_string_t s, s2;
+
+ heim_base_once_f(&once, &dict, init_string);
+ s = heim_string_create(_str);
+
+ HEIMDAL_MUTEX_lock(&mutex);
+ s2 = heim_dict_get_value(dict, s);
+ if (s2) {
+ heim_release(s);
+ s = s2;
+ } else {
+ _heim_make_permanent(s);
+ heim_dict_set_value(dict, s, s);
+ }
+ HEIMDAL_MUTEX_unlock(&mutex);
+
+ return s;
+}
diff --git a/third_party/heimdal/lib/base/test_base.c b/third_party/heimdal/lib/base/test_base.c
new file mode 100644
index 0000000..be6c860
--- /dev/null
+++ b/third_party/heimdal/lib/base/test_base.c
@@ -0,0 +1,962 @@
+/*
+ * Copyright (c) 2010-2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * This is a test of libheimbase functionality. If you make any changes
+ * to libheimbase or to this test you should run it under valgrind with
+ * the following options:
+ *
+ * -v --track-fds=yes --num-callers=30 --leak-check=full
+ *
+ * and make sure that there are no leaks that don't have
+ * __heim_string_constant() or heim_db_register() in their stack trace.
+ */
+
+#include <err.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifndef WIN32
+#include <sys/file.h>
+#endif
+#ifdef HAVE_IO_H
+#include <io.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <fcntl.h>
+
+#include "baselocl.h"
+
+static void HEIM_CALLCONV
+memory_free(heim_object_t obj)
+{
+}
+
+static int
+test_memory(void)
+{
+ void *ptr;
+
+ ptr = heim_alloc(10, "memory", memory_free);
+
+ heim_retain(ptr);
+ heim_release(ptr);
+
+ heim_retain(ptr);
+ heim_release(ptr);
+
+ heim_release(ptr);
+
+ ptr = heim_alloc(10, "memory", NULL);
+ heim_release(ptr);
+
+ return 0;
+}
+
+static int
+test_mutex(void)
+{
+ HEIMDAL_MUTEX m = HEIMDAL_MUTEX_INITIALIZER;
+
+ HEIMDAL_MUTEX_lock(&m);
+ HEIMDAL_MUTEX_unlock(&m);
+ HEIMDAL_MUTEX_destroy(&m);
+
+ HEIMDAL_MUTEX_init(&m);
+ HEIMDAL_MUTEX_lock(&m);
+ HEIMDAL_MUTEX_unlock(&m);
+ HEIMDAL_MUTEX_destroy(&m);
+
+ return 0;
+}
+
+static int
+test_rwlock(void)
+{
+ HEIMDAL_RWLOCK l = HEIMDAL_RWLOCK_INITIALIZER;
+
+ HEIMDAL_RWLOCK_rdlock(&l);
+ HEIMDAL_RWLOCK_unlock(&l);
+ HEIMDAL_RWLOCK_wrlock(&l);
+ HEIMDAL_RWLOCK_unlock(&l);
+ if (HEIMDAL_RWLOCK_trywrlock(&l) != 0)
+ err(1, "HEIMDAL_RWLOCK_trywrlock() failed with lock not held");
+ HEIMDAL_RWLOCK_unlock(&l);
+ if (HEIMDAL_RWLOCK_tryrdlock(&l))
+ err(1, "HEIMDAL_RWLOCK_tryrdlock() failed with lock not held");
+ HEIMDAL_RWLOCK_unlock(&l);
+ HEIMDAL_RWLOCK_destroy(&l);
+
+ HEIMDAL_RWLOCK_init(&l);
+ HEIMDAL_RWLOCK_rdlock(&l);
+ HEIMDAL_RWLOCK_unlock(&l);
+ HEIMDAL_RWLOCK_wrlock(&l);
+ HEIMDAL_RWLOCK_unlock(&l);
+ if (HEIMDAL_RWLOCK_trywrlock(&l))
+ err(1, "HEIMDAL_RWLOCK_trywrlock() failed with lock not held");
+ HEIMDAL_RWLOCK_unlock(&l);
+ if (HEIMDAL_RWLOCK_tryrdlock(&l))
+ err(1, "HEIMDAL_RWLOCK_tryrdlock() failed with lock not held");
+ HEIMDAL_RWLOCK_unlock(&l);
+ HEIMDAL_RWLOCK_destroy(&l);
+
+ return 0;
+}
+
+static int
+test_dict(void)
+{
+ heim_dict_t dict;
+ heim_number_t a1 = heim_number_create(1);
+ heim_string_t a2 = heim_string_create("hejsan");
+ heim_number_t a3 = heim_number_create(3);
+ heim_string_t a4 = heim_string_create("foosan");
+
+ dict = heim_dict_create(10);
+
+ heim_dict_set_value(dict, a1, a2);
+ heim_dict_set_value(dict, a3, a4);
+
+ heim_dict_delete_key(dict, a3);
+ heim_dict_delete_key(dict, a1);
+
+ heim_release(a1);
+ heim_release(a2);
+ heim_release(a3);
+ heim_release(a4);
+
+ heim_release(dict);
+
+ return 0;
+}
+
+static int
+test_auto_release(void)
+{
+ heim_auto_release_t ar1, ar2;
+ heim_number_t n1;
+ heim_string_t s1;
+
+ ar1 = heim_auto_release_create();
+
+ s1 = heim_string_create("hejsan");
+ heim_auto_release(s1);
+
+ n1 = heim_number_create(1);
+ heim_auto_release(n1);
+
+ ar2 = heim_auto_release_create();
+
+ n1 = heim_number_create(1);
+ heim_auto_release(n1);
+
+ heim_release(ar2);
+ heim_release(ar1);
+
+ return 0;
+}
+
+static int
+test_string(void)
+{
+ heim_string_t s1, s2;
+ const char *string = "hejsan";
+
+ s1 = heim_string_create(string);
+ s2 = heim_string_create(string);
+
+ if (heim_cmp(s1, s2) != 0) {
+ printf("the same string is not the same\n");
+ exit(1);
+ }
+
+ heim_release(s1);
+ heim_release(s2);
+
+ return 0;
+}
+
+static int
+test_error(void)
+{
+ heim_error_t e;
+ heim_string_t s;
+
+ e = heim_error_create(10, "foo: %s", "bar");
+ heim_assert(heim_error_get_code(e) == 10, "error_code != 10");
+
+ s = heim_error_copy_string(e);
+ heim_assert(strcmp(heim_string_get_utf8(s), "foo: bar") == 0, "msg wrong");
+
+ heim_release(s);
+ heim_release(e);
+
+ return 0;
+}
+
+static int
+test_json(void)
+{
+ static char *j[] = {
+ "{ \"k1\" : \"s1\", \"k2\" : \"s2\" }",
+ "{ \"k1\" : [\"s1\", \"s2\", \"s3\"], \"k2\" : \"s3\" }",
+ "{ \"k1\" : {\"k2\":\"s1\",\"k3\":\"s2\",\"k4\":\"s3\"}, \"k5\" : \"s4\" }",
+ ("[ \"v1\", \"v2\", [\"v3\",\"v4\",[\"v 5\",\" v 7 \"]], -123456789, "
+ "null, true, false, 123456789, \"\"]"),
+ " -1"
+ };
+ char *s;
+ size_t i, k;
+ heim_object_t o, o2;
+ heim_string_t k1 = heim_string_create("k1");
+
+ o = heim_json_create("\"string\"", 10, 0, NULL);
+ heim_assert(o != NULL, "string");
+ heim_assert(heim_get_tid(o) == heim_string_get_type_id(), "string-tid");
+ heim_assert(strcmp("string", heim_string_get_utf8(o)) == 0, "wrong string");
+ heim_release(o);
+
+ o = heim_json_create(" \"foo\\\"bar\" ]", 10, 0, NULL);
+ heim_assert(o != NULL, "string");
+ heim_assert(heim_get_tid(o) == heim_string_get_type_id(), "string-tid");
+ heim_assert(strcmp("foo\"bar", heim_string_get_utf8(o)) == 0, "wrong string");
+ heim_release(o);
+
+ o = heim_json_create(" { \"key\" : \"value\" }", 10, 0, NULL);
+ heim_assert(o != NULL, "dict");
+ heim_assert(heim_get_tid(o) == heim_dict_get_type_id(), "dict-tid");
+ heim_release(o);
+
+ o = heim_json_create("{ { \"k1\" : \"s1\", \"k2\" : \"s2\" } : \"s3\", "
+ "{ \"k3\" : \"s4\" } : -1 }", 10, 0, NULL);
+ heim_assert(o != NULL, "dict");
+ heim_assert(heim_get_tid(o) == heim_dict_get_type_id(), "dict-tid");
+ heim_release(o);
+
+ o = heim_json_create("{ { \"k1\" : \"s1\", \"k2\" : \"s2\" } : \"s3\", "
+ "{ \"k3\" : \"s4\" } : -1 }", 10,
+ HEIM_JSON_F_STRICT_DICT, NULL);
+ heim_assert(o == NULL, "dict");
+
+ o = heim_json_create(" { \"k1\" : \"s1\", \"k2\" : \"s2\" }", 10, 0, NULL);
+ heim_assert(o != NULL, "dict");
+ heim_assert(heim_get_tid(o) == heim_dict_get_type_id(), "dict-tid");
+ o2 = heim_dict_copy_value(o, k1);
+ heim_assert(heim_get_tid(o2) == heim_string_get_type_id(), "string-tid");
+ heim_release(o2);
+ heim_release(o);
+
+ o = heim_json_create(" { \"k1\" : { \"k2\" : \"s2\" } }", 10, 0, NULL);
+ heim_assert(o != NULL, "dict");
+ heim_assert(heim_get_tid(o) == heim_dict_get_type_id(), "dict-tid");
+ o2 = heim_dict_copy_value(o, k1);
+ heim_assert(heim_get_tid(o2) == heim_dict_get_type_id(), "dict-tid");
+ heim_release(o2);
+ heim_release(o);
+
+ o = heim_json_create("{ \"k1\" : 1 }", 10, 0, NULL);
+ heim_assert(o != NULL, "array");
+ heim_assert(heim_get_tid(o) == heim_dict_get_type_id(), "dict-tid");
+ o2 = heim_dict_copy_value(o, k1);
+ heim_assert(heim_get_tid(o2) == heim_number_get_type_id(), "number-tid");
+ heim_release(o2);
+ heim_release(o);
+
+ o = heim_json_create("-10", 10, 0, NULL);
+ heim_assert(o != NULL, "number");
+ heim_assert(heim_get_tid(o) == heim_number_get_type_id(), "number-tid");
+ heim_release(o);
+
+ o = heim_json_create("99", 10, 0, NULL);
+ heim_assert(o != NULL, "number");
+ heim_assert(heim_get_tid(o) == heim_number_get_type_id(), "number-tid");
+ heim_release(o);
+
+ o = heim_json_create(" [ 1 ]", 10, 0, NULL);
+ heim_assert(o != NULL, "array");
+ heim_assert(heim_get_tid(o) == heim_array_get_type_id(), "array-tid");
+ heim_release(o);
+
+ o = heim_json_create(" [ -1 ]", 10, 0, NULL);
+ heim_assert(o != NULL, "array");
+ heim_assert(heim_get_tid(o) == heim_array_get_type_id(), "array-tid");
+ heim_release(o);
+
+ for (i = 0; i < (sizeof (j) / sizeof (j[0])); i++) {
+ o = heim_json_create(j[i], 10, 0, NULL);
+ if (o == NULL) {
+ fprintf(stderr, "Failed to parse this JSON: %s\n", j[i]);
+ return 1;
+ }
+ heim_release(o);
+ /* Simple fuzz test */
+ for (k = strlen(j[i]) - 1; k > 0; k--) {
+ o = heim_json_create_with_bytes(j[i], k, 10, 0, NULL);
+ if (o != NULL) {
+ fprintf(stderr, "Invalid JSON parsed: %.*s\n", (int)k, j[i]);
+ return EINVAL;
+ }
+ }
+ /* Again, but this time make it so valgrind can find invalid accesses */
+ for (k = strlen(j[i]) - 1; k > 0; k--) {
+ s = strndup(j[i], k);
+ if (s == NULL)
+ return ENOMEM;
+ o = heim_json_create(s, 10, 0, NULL);
+ free(s);
+ if (o != NULL) {
+ fprintf(stderr, "Invalid JSON parsed: %s\n", j[i]);
+ return EINVAL;
+ }
+ }
+ /* Again, but with no NUL termination */
+ for (k = strlen(j[i]) - 1; k > 0; k--) {
+ s = malloc(k);
+ if (s == NULL)
+ return ENOMEM;
+ memcpy(s, j[i], k);
+ o = heim_json_create_with_bytes(s, k, 10, 0, NULL);
+ free(s);
+ if (o != NULL) {
+ fprintf(stderr, "Invalid JSON parsed: %s\n", j[i]);
+ return EINVAL;
+ }
+ }
+ }
+
+ heim_release(k1);
+
+ return 0;
+}
+
+static int
+test_path(void)
+{
+ heim_dict_t dict = heim_dict_create(11);
+ heim_string_t p1 = heim_string_create("abc");
+ heim_string_t p2a = heim_string_create("def");
+ heim_string_t p2b = heim_string_create("DEF");
+ heim_number_t p3 = heim_number_create(0);
+ heim_string_t p4a = heim_string_create("ghi");
+ heim_string_t p4b = heim_string_create("GHI");
+ heim_array_t a = heim_array_create();
+ heim_number_t l1 = heim_number_create(42);
+ heim_number_t l2 = heim_number_create(813);
+ heim_number_t l3 = heim_number_create(1234);
+ heim_string_t k1 = heim_string_create("k1");
+ heim_string_t k2 = heim_string_create("k2");
+ heim_string_t k3 = heim_string_create("k3");
+ heim_string_t k2_1 = heim_string_create("k2-1");
+ heim_string_t k2_2 = heim_string_create("k2-2");
+ heim_string_t k2_3 = heim_string_create("k2-3");
+ heim_string_t k2_4 = heim_string_create("k2-4");
+ heim_string_t k2_5 = heim_string_create("k2-5");
+ heim_string_t k2_5_1 = heim_string_create("k2-5-1");
+ heim_object_t o;
+ heim_object_t neg_num;
+ int ret;
+
+ if (!dict || !p1 || !p2a || !p2b || !p4a || !p4b)
+ return ENOMEM;
+
+ ret = heim_path_create(dict, 11, a, NULL, p1, p2a, NULL);
+ heim_release(a);
+ if (ret)
+ return ret;
+ ret = heim_path_create(dict, 11, l3, NULL, p1, p2b, NULL);
+ if (ret)
+ return ret;
+ o = heim_path_get(dict, NULL, p1, p2b, NULL);
+ if (o != l3)
+ return 1;
+ ret = heim_path_create(dict, 11, NULL, NULL, p1, p2a, p3, NULL);
+ if (ret)
+ return ret;
+ ret = heim_path_create(dict, 11, l1, NULL, p1, p2a, p3, p4a, NULL);
+ if (ret)
+ return ret;
+ ret = heim_path_create(dict, 11, l2, NULL, p1, p2a, p3, p4b, NULL);
+ if (ret)
+ return ret;
+
+ o = heim_path_get(dict, NULL, p1, p2a, p3, p4a, NULL);
+ if (o != l1)
+ return 1;
+ o = heim_path_get(dict, NULL, p1, p2a, p3, p4b, NULL);
+ if (o != l2)
+ return 1;
+
+ heim_release(dict);
+
+ /* Test that JSON parsing works right by using heim_path_get() */
+ dict = heim_json_create("{\"k1\":1,"
+ "\"k2\":{\"k2-1\":21,"
+ "\"k2-2\":null,"
+ "\"k2-3\":true,"
+ "\"k2-4\":false,"
+ "\"k2-5\":[1,2,3,{\"k2-5-1\":-1},-2]},"
+ "\"k3\":[true,false,0,42]}", 10, 0, NULL);
+ heim_assert(dict != NULL, "dict");
+ o = heim_path_get(dict, NULL, k1, NULL);
+ if (heim_cmp(o, heim_number_create(1))) return 1;
+ o = heim_path_get(dict, NULL, k2, NULL);
+ if (heim_get_tid(o) != heim_dict_get_type_id()) return 1;
+ o = heim_path_get(dict, NULL, k2, k2_1, NULL);
+ if (heim_cmp(o, heim_number_create(21))) return 1;
+ o = heim_path_get(dict, NULL, k2, k2_2, NULL);
+ if (heim_cmp(o, heim_null_create())) return 1;
+ o = heim_path_get(dict, NULL, k2, k2_3, NULL);
+ if (heim_cmp(o, heim_bool_create(1))) return 1;
+ o = heim_path_get(dict, NULL, k2, k2_4, NULL);
+ if (heim_cmp(o, heim_bool_create(0))) return 1;
+ o = heim_path_get(dict, NULL, k2, k2_5, NULL);
+ if (heim_get_tid(o) != heim_array_get_type_id()) return 1;
+ o = heim_path_get(dict, NULL, k2, k2_5, heim_number_create(0), NULL);
+ if (heim_cmp(o, heim_number_create(1))) return 1;
+ o = heim_path_get(dict, NULL, k2, k2_5, heim_number_create(1), NULL);
+ if (heim_cmp(o, heim_number_create(2))) return 1;
+ o = heim_path_get(dict, NULL, k2, k2_5, heim_number_create(3), k2_5_1, NULL);
+ if (heim_cmp(o, neg_num = heim_number_create(-1))) return 1;
+ heim_release(neg_num);
+ o = heim_path_get(dict, NULL, k2, k2_5, heim_number_create(4), NULL);
+ if (heim_cmp(o, neg_num = heim_number_create(-2))) return 1;
+ heim_release(neg_num);
+ o = heim_path_get(dict, NULL, k3, heim_number_create(3), NULL);
+ if (heim_cmp(o, heim_number_create(42))) return 1;
+
+ heim_release(dict);
+ heim_release(p1);
+ heim_release(p2a);
+ heim_release(p2b);
+ heim_release(p4a);
+ heim_release(p4b);
+ heim_release(k1);
+ heim_release(k2);
+ heim_release(k3);
+ heim_release(k2_1);
+ heim_release(k2_2);
+ heim_release(k2_3);
+ heim_release(k2_4);
+ heim_release(k2_5);
+ heim_release(k2_5_1);
+
+ return 0;
+}
+
+typedef struct dict_db {
+ heim_dict_t dict;
+ int locked;
+} *dict_db_t;
+
+static int
+dict_db_open(void *plug, const char *dbtype, const char *dbname,
+ heim_dict_t options, void **db, heim_error_t *error)
+{
+ dict_db_t dictdb;
+ heim_dict_t contents = NULL;
+
+ if (error)
+ *error = NULL;
+ if (dbtype && *dbtype && strcmp(dbtype, "dictdb") != 0)
+ return EINVAL;
+ if (dbname && *dbname && strcmp(dbname, "MEMORY") != 0)
+ return EINVAL;
+ dictdb = heim_alloc(sizeof (*dictdb), "dict_db", NULL);
+ if (dictdb == NULL)
+ return ENOMEM;
+
+ if (contents != NULL)
+ dictdb->dict = contents;
+ else {
+ dictdb->dict = heim_dict_create(29);
+ if (dictdb->dict == NULL) {
+ heim_release(dictdb);
+ return ENOMEM;
+ }
+ }
+
+ *db = dictdb;
+ return 0;
+}
+
+static int
+dict_db_close(void *db, heim_error_t *error)
+{
+ dict_db_t dictdb = db;
+
+ if (error)
+ *error = NULL;
+ heim_release(dictdb->dict);
+ heim_release(dictdb);
+ return 0;
+}
+
+static int
+dict_db_lock(void *db, int read_only, heim_error_t *error)
+{
+ dict_db_t dictdb = db;
+
+ if (error)
+ *error = NULL;
+ if (dictdb->locked)
+ return EWOULDBLOCK;
+ dictdb->locked = 1;
+ return 0;
+}
+
+static int
+dict_db_unlock(void *db, heim_error_t *error)
+{
+ dict_db_t dictdb = db;
+
+ if (error)
+ *error = NULL;
+ dictdb->locked = 0;
+ return 0;
+}
+
+static heim_data_t
+dict_db_copy_value(void *db, heim_string_t table, heim_data_t key,
+ heim_error_t *error)
+{
+ dict_db_t dictdb = db;
+
+ if (error)
+ *error = NULL;
+
+ return heim_retain(heim_path_get(dictdb->dict, error, table, key, NULL));
+}
+
+static int
+dict_db_set_value(void *db, heim_string_t table,
+ heim_data_t key, heim_data_t value, heim_error_t *error)
+{
+ dict_db_t dictdb = db;
+
+ if (error)
+ *error = NULL;
+
+ if (table == NULL)
+ table = HSTR("");
+
+ return heim_path_create(dictdb->dict, 29, value, error, table, key, NULL);
+}
+
+static int
+dict_db_del_key(void *db, heim_string_t table, heim_data_t key,
+ heim_error_t *error)
+{
+ dict_db_t dictdb = db;
+
+ if (error)
+ *error = NULL;
+
+ if (table == NULL)
+ table = HSTR("");
+
+ heim_path_delete(dictdb->dict, error, table, key, NULL);
+ return 0;
+}
+
+struct dict_db_iter_ctx {
+ heim_db_iterator_f_t iter_f;
+ void *iter_ctx;
+};
+
+static void dict_db_iter_f(heim_object_t key, heim_object_t value, void *arg)
+{
+ struct dict_db_iter_ctx *ctx = arg;
+
+ ctx->iter_f((heim_object_t)key, (heim_object_t)value, ctx->iter_ctx);
+}
+
+static void
+dict_db_iter(void *db, heim_string_t table, void *iter_data,
+ heim_db_iterator_f_t iter_f, heim_error_t *error)
+{
+ dict_db_t dictdb = db;
+ struct dict_db_iter_ctx ctx;
+ heim_dict_t table_dict;
+
+ if (error)
+ *error = NULL;
+
+ if (table == NULL)
+ table = HSTR("");
+
+ table_dict = heim_dict_copy_value(dictdb->dict, table);
+ if (table_dict == NULL)
+ return;
+
+ ctx.iter_ctx = iter_data;
+ ctx.iter_f = iter_f;
+
+ heim_dict_iterate_f(table_dict, &ctx, dict_db_iter_f);
+ heim_release(table_dict);
+}
+
+static void
+test_db_iter(heim_data_t k, heim_data_t v, void *arg)
+{
+ int *ret = arg;
+ const void *kptr, *vptr;
+ size_t klen, vlen;
+
+ heim_assert(heim_get_tid(k) == heim_data_get_type_id(), "...");
+
+ kptr = heim_data_get_ptr(k);
+ klen = heim_data_get_length(k);
+ vptr = heim_data_get_ptr(v);
+ vlen = heim_data_get_length(v);
+
+ if (klen == strlen("msg") && strncmp(kptr, "msg", strlen("msg")) == 0 &&
+ vlen == strlen("abc") && strncmp(vptr, "abc", strlen("abc")) == 0)
+ *ret &= ~(1);
+ else if (klen == strlen("msg2") &&
+ strncmp(kptr, "msg2", strlen("msg2")) == 0 &&
+ vlen == strlen("FooBar") &&
+ strncmp(vptr, "FooBar", strlen("FooBar")) == 0)
+ *ret &= ~(2);
+ else
+ *ret |= 4;
+}
+
+static struct heim_db_type dbt = {
+ 1, dict_db_open, NULL, dict_db_close,
+ dict_db_lock, dict_db_unlock, NULL, NULL, NULL, NULL,
+ dict_db_copy_value, dict_db_set_value,
+ dict_db_del_key, dict_db_iter
+};
+
+static int
+test_db(const char *dbtype, const char *dbname)
+{
+ heim_data_t k1, k2, v, v1, v2, v3;
+ heim_db_t db;
+ int ret;
+
+ if (dbtype == NULL) {
+ ret = heim_db_register("dictdb", NULL, &dbt);
+ heim_assert(!ret, "...");
+ db = heim_db_create("dictdb", "foo", NULL, NULL);
+ heim_assert(!db, "...");
+ db = heim_db_create("foobar", "MEMORY", NULL, NULL);
+ heim_assert(!db, "...");
+ db = heim_db_create("dictdb", "MEMORY", NULL, NULL);
+ heim_assert(db, "...");
+ } else {
+ heim_dict_t options;
+
+ options = heim_dict_create(11);
+ if (options == NULL) return ENOMEM;
+ if (heim_dict_set_value(options, HSTR("journal-filename"),
+ HSTR("json-journal")))
+ return ENOMEM;
+ if (heim_dict_set_value(options, HSTR("create"), heim_null_create()))
+ return ENOMEM;
+ if (heim_dict_set_value(options, HSTR("truncate"), heim_null_create()))
+ return ENOMEM;
+ db = heim_db_create(dbtype, dbname, options, NULL);
+ heim_assert(db, "...");
+ heim_release(options);
+ }
+
+ k1 = heim_data_create("msg", strlen("msg"));
+ k2 = heim_data_create("msg2", strlen("msg2"));
+ v1 = heim_data_create("Hello world!", strlen("Hello world!"));
+ v2 = heim_data_create("FooBar", strlen("FooBar"));
+ v3 = heim_data_create("abc", strlen("abc"));
+
+ ret = heim_db_set_value(db, NULL, k1, v1, NULL);
+ heim_assert(!ret, "...");
+
+ v = heim_db_copy_value(db, NULL, k1, NULL);
+ heim_assert(v && !heim_cmp(v, v1), "...");
+ heim_release(v);
+
+ ret = heim_db_set_value(db, NULL, k2, v2, NULL);
+ heim_assert(!ret, "...");
+
+ v = heim_db_copy_value(db, NULL, k2, NULL);
+ heim_assert(v && !heim_cmp(v, v2), "...");
+ heim_release(v);
+
+ ret = heim_db_set_value(db, NULL, k1, v3, NULL);
+ heim_assert(!ret, "...");
+
+ v = heim_db_copy_value(db, NULL, k1, NULL);
+ heim_assert(v && !heim_cmp(v, v3), "...");
+ heim_release(v);
+
+ ret = 3;
+ heim_db_iterate_f(db, NULL, &ret, test_db_iter, NULL);
+ heim_assert(!ret, "...");
+
+ ret = heim_db_begin(db, 0, NULL);
+ heim_assert(!ret, "...");
+
+ ret = heim_db_commit(db, NULL);
+ heim_assert(!ret, "...");
+
+ ret = heim_db_begin(db, 0, NULL);
+ heim_assert(!ret, "...");
+
+ ret = heim_db_rollback(db, NULL);
+ heim_assert(!ret, "...");
+
+ ret = heim_db_begin(db, 0, NULL);
+ heim_assert(!ret, "...");
+
+ ret = heim_db_set_value(db, NULL, k1, v1, NULL);
+ heim_assert(!ret, "...");
+
+ v = heim_db_copy_value(db, NULL, k1, NULL);
+ heim_assert(v && !heim_cmp(v, v1), "...");
+ heim_release(v);
+
+ ret = heim_db_rollback(db, NULL);
+ heim_assert(!ret, "...");
+
+ v = heim_db_copy_value(db, NULL, k1, NULL);
+ heim_assert(v && !heim_cmp(v, v3), "...");
+ heim_release(v);
+
+ ret = heim_db_begin(db, 0, NULL);
+ heim_assert(!ret, "...");
+
+ ret = heim_db_set_value(db, NULL, k1, v1, NULL);
+ heim_assert(!ret, "...");
+
+ v = heim_db_copy_value(db, NULL, k1, NULL);
+ heim_assert(v && !heim_cmp(v, v1), "...");
+ heim_release(v);
+
+ ret = heim_db_commit(db, NULL);
+ heim_assert(!ret, "...");
+
+ v = heim_db_copy_value(db, NULL, k1, NULL);
+ heim_assert(v && !heim_cmp(v, v1), "...");
+ heim_release(v);
+
+ ret = heim_db_begin(db, 0, NULL);
+ heim_assert(!ret, "...");
+
+ ret = heim_db_delete_key(db, NULL, k1, NULL);
+ heim_assert(!ret, "...");
+
+ v = heim_db_copy_value(db, NULL, k1, NULL);
+ heim_assert(v == NULL, "...");
+ heim_release(v);
+
+ ret = heim_db_rollback(db, NULL);
+ heim_assert(!ret, "...");
+
+ v = heim_db_copy_value(db, NULL, k1, NULL);
+ heim_assert(v && !heim_cmp(v, v1), "...");
+ heim_release(v);
+
+ if (dbtype != NULL) {
+ heim_data_t k3 = heim_data_create("value-is-a-dict", strlen("value-is-a-dict"));
+ heim_dict_t vdict = heim_dict_create(11);
+ heim_db_t db2;
+
+ heim_assert(k3 && vdict, "...");
+ ret = heim_dict_set_value(vdict, HSTR("vdict-k1"), heim_number_create(11));
+ heim_assert(!ret, "...");
+ ret = heim_dict_set_value(vdict, HSTR("vdict-k2"), heim_null_create());
+ heim_assert(!ret, "...");
+ ret = heim_dict_set_value(vdict, HSTR("vdict-k3"), HSTR("a value"));
+ heim_assert(!ret, "...");
+ ret = heim_db_set_value(db, NULL, k3, (heim_data_t)vdict, NULL);
+ heim_assert(!ret, "...");
+
+ heim_release(vdict);
+
+ db2 = heim_db_create(dbtype, dbname, NULL, NULL);
+ heim_assert(db2, "...");
+
+ vdict = (heim_dict_t)heim_db_copy_value(db2, NULL, k3, NULL);
+ heim_release(db2);
+ heim_release(k3);
+ heim_assert(vdict, "...");
+ heim_assert(heim_get_tid(vdict) == heim_dict_get_type_id(), "...");
+
+ v = heim_dict_copy_value(vdict, HSTR("vdict-k1"));
+ heim_assert(v && !heim_cmp(v, heim_number_create(11)), "...");
+ heim_release(v);
+
+ v = heim_dict_copy_value(vdict, HSTR("vdict-k2"));
+ heim_assert(v && !heim_cmp(v, heim_null_create()), "...");
+ heim_release(v);
+
+ v = heim_dict_copy_value(vdict, HSTR("vdict-k3"));
+ heim_assert(v && !heim_cmp(v, HSTR("a value")), "...");
+ heim_release(v);
+
+ heim_release(vdict);
+ }
+
+ heim_release(db);
+ heim_release(k1);
+ heim_release(k2);
+ heim_release(v1);
+ heim_release(v2);
+ heim_release(v3);
+
+ return 0;
+}
+
+struct test_array_iter_ctx {
+ char buf[256];
+};
+
+static void test_array_iter(heim_object_t elt, void *arg, int *stop)
+{
+ struct test_array_iter_ctx *iter_ctx = arg;
+
+ strcat(iter_ctx->buf, heim_string_get_utf8((heim_string_t)elt));
+}
+
+static int
+test_array()
+{
+ struct test_array_iter_ctx iter_ctx;
+ heim_string_t s1 = heim_string_create("abc");
+ heim_string_t s2 = heim_string_create("def");
+ heim_string_t s3 = heim_string_create("ghi");
+ heim_string_t s4 = heim_string_create("jkl");
+ heim_string_t s5 = heim_string_create("mno");
+ heim_string_t s6 = heim_string_create("pqr");
+ heim_array_t a = heim_array_create();
+
+ if (!s1 || !s2 || !s3 || !s4 || !s5 || !s6 || !a)
+ return ENOMEM;
+
+ heim_array_append_value(a, s4);
+ heim_array_append_value(a, s5);
+ heim_array_insert_value(a, 0, s3);
+ heim_array_insert_value(a, 0, s2);
+ heim_array_append_value(a, s6);
+ heim_array_insert_value(a, 0, s1);
+
+ iter_ctx.buf[0] = '\0';
+ heim_array_iterate_f(a, &iter_ctx, test_array_iter);
+ if (strcmp(iter_ctx.buf, "abcdefghijklmnopqr") != 0)
+ return 1;
+
+ iter_ctx.buf[0] = '\0';
+ heim_array_delete_value(a, 2);
+ heim_array_iterate_f(a, &iter_ctx, test_array_iter);
+ if (strcmp(iter_ctx.buf, "abcdefjklmnopqr") != 0)
+ return 1;
+
+ iter_ctx.buf[0] = '\0';
+ heim_array_delete_value(a, 2);
+ heim_array_iterate_f(a, &iter_ctx, test_array_iter);
+ if (strcmp(iter_ctx.buf, "abcdefmnopqr") != 0)
+ return 1;
+
+ iter_ctx.buf[0] = '\0';
+ heim_array_delete_value(a, 0);
+ heim_array_iterate_f(a, &iter_ctx, test_array_iter);
+ if (strcmp(iter_ctx.buf, "defmnopqr") != 0)
+ return 1;
+
+ iter_ctx.buf[0] = '\0';
+ heim_array_delete_value(a, 2);
+ heim_array_iterate_f(a, &iter_ctx, test_array_iter);
+ if (strcmp(iter_ctx.buf, "defmno") != 0)
+ return 1;
+
+ heim_array_insert_value(a, 0, s1);
+ iter_ctx.buf[0] = '\0';
+ heim_array_iterate_f(a, &iter_ctx, test_array_iter);
+ if (strcmp(iter_ctx.buf, "abcdefmno") != 0)
+ return 1;
+
+ heim_array_insert_value(a, 0, s2);
+ iter_ctx.buf[0] = '\0';
+ heim_array_iterate_f(a, &iter_ctx, test_array_iter);
+ if (strcmp(iter_ctx.buf, "defabcdefmno") != 0)
+ return 1;
+
+ heim_array_append_value(a, s3);
+ iter_ctx.buf[0] = '\0';
+ heim_array_iterate_f(a, &iter_ctx, test_array_iter);
+ if (strcmp(iter_ctx.buf, "defabcdefmnoghi") != 0)
+ return 1;
+
+ heim_array_append_value(a, s6);
+ iter_ctx.buf[0] = '\0';
+ heim_array_iterate_f(a, &iter_ctx, test_array_iter);
+ if (strcmp(iter_ctx.buf, "defabcdefmnoghipqr") != 0)
+ return 1;
+
+ heim_release(s1);
+ heim_release(s2);
+ heim_release(s3);
+ heim_release(s4);
+ heim_release(s5);
+ heim_release(s6);
+ heim_release(a);
+
+ return 0;
+}
+
+int
+main(int argc, char **argv)
+{
+ int res = 0;
+
+ res |= test_memory();
+ res |= test_mutex();
+ res |= test_rwlock();
+ res |= test_dict();
+ res |= test_auto_release();
+ res |= test_string();
+ res |= test_error();
+ res |= test_json();
+ res |= test_path();
+ res |= test_db(NULL, NULL);
+ res |= test_db("json", argc > 1 ? argv[1] : "test_db.json");
+ res |= test_array();
+
+ return res ? 1 : 0;
+}
diff --git a/third_party/heimdal/lib/base/version-script.map b/third_party/heimdal/lib/base/version-script.map
new file mode 100644
index 0000000..928e861
--- /dev/null
+++ b/third_party/heimdal/lib/base/version-script.map
@@ -0,0 +1,208 @@
+HEIMDAL_BASE_1.0 {
+ global:
+ _bsearch_file;
+ _bsearch_file_close;
+ _bsearch_file_info;
+ _bsearch_file_open;
+ _bsearch_text;
+ DllMain;
+ et_heim_error_table;
+ heim_abort;
+ heim_abortv;
+ heim_add_debug_dest;
+ heim_add_et_list;
+ heim_addlog_dest;
+ heim_addlog_func;
+ heim_add_warn_dest;
+ heim_alloc;
+ _heim_alloc_object;
+ heim_array_append_value;
+ heim_array_copy_value;
+ heim_array_create;
+ heim_array_delete_value;
+ heim_array_filter_f;
+ heim_array_get_length;
+ heim_array_get_type_id;
+ heim_array_get_value;
+ heim_array_insert_value;
+ heim_array_iterate_f;
+ heim_array_iterate_reverse_f;
+ heim_array_set_value;
+ heim_audit_addkv;
+ heim_audit_addkv_number;
+ heim_audit_addkv_object;
+ heim_audit_addkv_timediff;
+ heim_audit_setkv_bool;
+ heim_audit_setkv_number;
+ heim_audit_setkv_object;
+ heim_audit_addreason;
+ heim_audit_getkv;
+ heim_audit_trail;
+ heim_audit_vaddkv;
+ heim_audit_vaddreason;
+ heim_auto_release;
+ heim_auto_release_create;
+ heim_auto_release_drain;
+ heim_base_once_f;
+ heim_bool_create;
+ heim_bool_val;
+ heim_clear_error_message;
+ heim_closelog;
+ heim_cmp;
+ heim_config_copy;
+ heim_config_file_free;
+ heim_config_free_strings;
+ heim_config_get;
+ heim_config_get_bool;
+ heim_config_get_bool_default;
+ heim_config_get_entry;
+ heim_config_get_int;
+ heim_config_get_int_default;
+ heim_config_get_list;
+ heim_config_get_next;
+ heim_config_get_string;
+ heim_config_get_string_default;
+ heim_config_get_strings;
+ heim_config_get_time;
+ heim_config_get_time_default;
+ heim_config_parse_dir_multi;
+ heim_config_parse_file;
+ heim_config_parse_file_multi;
+ heim_config_parse_string_multi;
+ heim_config_vget;
+ heim_config_vget_bool;
+ heim_config_vget_bool_default;
+ heim_config_vget_int;
+ heim_config_vget_int_default;
+ heim_config_vget_list;
+ heim_config_vget_next;
+ heim_config_vget_string;
+ heim_config_vget_string_default;
+ heim_config_vget_strings;
+ heim_config_vget_time;
+ heim_config_vget_time_default;
+ heim_context_free;
+ heim_context_get_homedir_access;
+ heim_context_get_log_utc;
+ heim_context_get_time_fmt;
+ heim_context_init;
+ heim_context_set_homedir_access;
+ heim_context_set_log_utc;
+ heim_context_set_time_fmt;
+ _heim_create_type;
+ heim_data_create;
+ heim_data_get_data;
+ heim_data_get_length;
+ heim_data_get_ptr;
+ heim_data_get_type_id;
+ heim_data_ref_create;
+ heim_data_ref_get_type_id;
+ heim_db_begin;
+ heim_db_clone;
+ heim_db_commit;
+ heim_db_copy_value;
+ heim_db_create;
+ heim_db_delete_key;
+ heim_db_get_type_id;
+ _heim_db_get_value;
+ heim_db_iterate_f;
+ heim_db_register;
+ heim_db_rollback;
+ heim_db_set_value;
+ heim_debug;
+ heim_description;
+ heim_dict_copy_value;
+ heim_dict_create;
+ heim_dict_delete_key;
+ heim_dict_get_type_id;
+ heim_dict_get_value;
+ heim_dict_iterate_f;
+ heim_dict_set_value;
+ heim_enomem;
+ heim_error_append;
+ heim_error_copy_string;
+ heim_error_create;
+ heim_error_create_enomem;
+ heim_error_create_opt;
+ heim_error_createv;
+ heim_error_get_code;
+ heim_expand_path_tokens;
+ heim_expand_path_tokensv;
+ heim_free_config_files;
+ heim_free_error_message;
+ heim_get_debug_dest;
+ heim_get_default_config_files;
+ heim_get_error_message;
+ heim_get_error_string;
+ heim_get_hash;
+ _heim_get_isa;
+ _heim_get_isaextra;
+ heim_get_log_dest;
+ heim_get_tid;
+ heim_get_warn_dest;
+ heim_have_debug;
+ heim_have_error_string;
+ heim_initlog;
+ heim_json_copy_serialize;
+ heim_json_create;
+ heim_json_create_with_bytes;
+ heim_load_plugins;
+ heim_log;
+ heim_log_msg;
+ _heim_make_permanent;
+ heim_null_create;
+ heim_number_create;
+ heim_number_get_int;
+ heim_number_get_long;
+ heim_number_get_type_id;
+ heim_openlog;
+ heim_path_copy;
+ heim_path_create;
+ heim_path_delete;
+ heim_path_get;
+ heim_path_vcopy;
+ heim_path_vcreate;
+ heim_path_vdelete;
+ heim_path_vget;
+ heim_plugin_register;
+ heim_plugin_run_f;
+ heim_prepend_config_files;
+ heim_prepend_config_files_default;
+ heim_prepend_error_message;
+ heim_release;
+ heim_retain;
+ heim_set_config_files;
+ heim_set_debug_dest;
+ heim_set_error_message;
+ heim_set_log_dest;
+ heim_set_warn_dest;
+ heim_show;
+ heim_sorted_text_file_dbtype;
+ __heim_string_constant;
+ heim_string_create;
+ heim_string_create_with_bytes;
+ heim_string_create_with_format;
+ heim_string_get_type_id;
+ heim_string_get_utf8;
+ heim_string_ref_create;
+ _heim_type_get_tid;
+ heim_unload_plugins;
+ heim_vdebug;
+ heim_vlog;
+ heim_vlog_msg;
+ heim_vprepend_error_message;
+ heim_vset_error_message;
+ heim_vwarn;
+ heim_vwarnx;
+ heim_w32_delete_key;
+ heim_w32_getspecific;
+ heim_w32_key_create;
+ heim_w32_service_thread_detach;
+ heim_w32_setspecific;
+ heim_warn;
+ heim_warnx;
+ initialize_heim_error_table;
+ initialize_heim_error_table_r;
+ local:
+ *;
+};
diff --git a/third_party/heimdal/lib/base/warn.c b/third_party/heimdal/lib/base/warn.c
new file mode 100644
index 0000000..2376a51
--- /dev/null
+++ b/third_party/heimdal/lib/base/warn.c
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) 1997 - 2020 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if defined(_MSC_VER)
+# pragma warning(disable: 4646)
+# pragma warning(disable: 4716)
+#endif
+
+#include "baselocl.h"
+#include <err.h>
+
+static heim_error_code _warnerr(heim_context context, int do_errtext,
+ heim_error_code code, int level, const char *fmt, va_list ap)
+ __attribute__ ((__format__ (__printf__, 5, 0)));
+
+static heim_error_code
+_warnerr(heim_context context, int do_errtext,
+ heim_error_code code, int level, const char *fmt, va_list ap)
+{
+ char xfmt[7] = "";
+ const char *args[2], **arg;
+ char *msg = NULL;
+ const char *err_str = NULL;
+ heim_error_code ret;
+
+ args[0] = args[1] = NULL;
+ arg = args;
+ if(fmt){
+ strlcat(xfmt, "%s", sizeof(xfmt));
+ if(do_errtext)
+ strlcat(xfmt, ": ", sizeof(xfmt));
+ ret = vasprintf(&msg, fmt, ap);
+ if(ret < 0 || msg == NULL)
+ return ENOMEM;
+ *arg++ = msg;
+ }
+ if (context && do_errtext) {
+ strlcat(xfmt, "%s", sizeof(xfmt));
+
+ err_str = heim_get_error_message(context, code);
+ if (err_str != NULL) {
+ *arg = err_str;
+ } else {
+ *arg= "<unknown error>";
+ }
+ }
+
+ if (context && heim_get_warn_dest(context))
+ heim_log(context, heim_get_warn_dest(context), level, xfmt, args[0],
+ args[1]);
+ else
+ warnx(xfmt, args[0], args[1]);
+ free(msg);
+ heim_free_error_message(context, err_str);
+ return 0;
+}
+
+#define FUNC(ETEXT, CODE, LEVEL) \
+ heim_error_code ret; \
+ va_list ap; \
+ va_start(ap, fmt); \
+ ret = _warnerr(context, ETEXT, CODE, LEVEL, fmt, ap); \
+ va_end(ap);
+
+#undef __attribute__
+#define __attribute__(X)
+
+/**
+ * Log a warning to the log, default stderr, include the error from
+ * the last failure.
+ *
+ * @param context A Kerberos 5 context.
+ * @param code error code of the last error
+ * @param fmt message to print
+ * @param ap arguments
+ *
+ * @ingroup heim_error
+ */
+
+heim_error_code
+heim_vwarn(heim_context context, heim_error_code code,
+ const char *fmt, va_list ap)
+ __attribute__ ((__format__ (__printf__, 3, 0)))
+{
+ return _warnerr(context, 1, code, 1, fmt, ap);
+}
+
+/**
+ * Log a warning to the log, default stderr, include the error from
+ * the last failure.
+ *
+ * @param context A Kerberos 5 context.
+ * @param code error code of the last error
+ * @param fmt message to print
+ *
+ * @ingroup heim_error
+ */
+
+heim_error_code
+heim_warn(heim_context context, heim_error_code code, const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 3, 4)))
+{
+ FUNC(1, code, 1);
+ return ret;
+}
+
+/**
+ * Log a warning to the log, default stderr.
+ *
+ * @param context A Kerberos 5 context.
+ * @param fmt message to print
+ * @param ap arguments
+ *
+ * @ingroup heim_error
+ */
+
+heim_error_code
+heim_vwarnx(heim_context context, const char *fmt, va_list ap)
+ __attribute__ ((__format__ (__printf__, 2, 0)))
+{
+ return _warnerr(context, 0, 0, 1, fmt, ap);
+}
+
+/**
+ * Log a warning to the log, default stderr.
+ *
+ * @param context A Kerberos 5 context.
+ * @param fmt message to print
+ *
+ * @ingroup heim_error
+ */
+
+heim_error_code
+heim_warnx(heim_context context, const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 2, 3)))
+{
+ FUNC(0, 0, 1);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/com_err/ChangeLog b/third_party/heimdal/lib/com_err/ChangeLog
new file mode 100644
index 0000000..ad8d3e9
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/ChangeLog
@@ -0,0 +1,235 @@
+2007-07-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: split source files in dist and nodist.
+
+2007-07-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Only do roken rename for the library.
+
+2007-07-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: use version script.
+
+ * version-script.map: use version script.
+
+2007-07-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: New library version.
+
+2006-10-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am (compile_et_SOURCES): add lex.h
+
+2005-12-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * com_err.3: Document the _r functions.
+
+2005-07-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * com_err.h: Include <stdarg.h> for va_list to help AIX 5.2.
+
+2005-06-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * parse.y: rename base to base_id since flex defines a function
+ with the argument base
+
+ * compile_et.h: rename base to base_id since flex defines a
+ function with the argument base
+
+ * compile_et.c: rename base to base_id since flex defines a
+ function with the argument base
+
+ * parse.y (name2number): rename base to num to avoid shadowing
+
+ * compile_et.c: rename optind to optidx
+
+2005-05-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * parse.y: check allocation errors
+
+ * lex.l: check allocation errors correctly
+
+ * compile_et.h: include <err.h>
+
+ * (main): compile_et.c: use strlcpy
+
+2005-04-29 Dave Love <fx@gnu.org>
+
+ * Makefile.am (LDADD): Add libcom_err.la
+
+2005-04-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * include strlcpy and *printf and use them
+
+2005-02-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * com_right.h: de-__P
+
+ * com_err.h: de-__P
+
+2002-08-20 Johan Danielsson <joda@pdc.kth.se>
+
+ * compile_et.c: don't add comma after last enum member
+
+2002-08-12 Johan Danielsson <joda@pdc.kth.se>
+
+ * compile_et.c: just declare er_list directly instead of including
+ com_right in generated header files
+
+2002-03-11 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libcom_err_la_LDFLAGS): set version to 2:1:1
+
+2002-03-10 Assar Westerlund <assar@sics.se>
+
+ * com_err.c (error_message): do not call strerror with a negative error
+
+2001-05-17 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 2:0:1
+
+2001-05-11 Assar Westerlund <assar@sics.se>
+
+ * com_err.h (add_to_error_table): add prototype
+ * com_err.c (add_to_error_table): new function, from Derrick J
+ Brashear <shadow@dementia.org>
+
+2001-05-06 Assar Westerlund <assar@sics.se>
+
+ * com_err.h: add printf formats for gcc
+
+2001-02-28 Johan Danielsson <joda@pdc.kth.se>
+
+ * error.c (initialize_error_table_r): put table at end of the list
+
+2001-02-15 Assar Westerlund <assar@sics.se>
+
+ * com_err.c (default_proc): add printf attributes
+
+2000-08-16 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 1:1:0
+
+2000-07-31 Assar Westerlund <assar@sics.se>
+
+ * com_right.h (initialize_error_table_r): fix prototype
+
+2000-04-05 Assar Westerlund <assar@sics.se>
+
+ * com_err.c (_et_lit): explicitly initialize it to NULL to make
+ dyld on Darwin/MacOS X happy
+
+2000-01-16 Assar Westerlund <assar@sics.se>
+
+ * com_err.h: remove __P definition (now in com_right.h). this
+ file always includes com_right.h so that's where it should reside.
+ * com_right.h: moved __P here and added it to the function
+ prototypes
+ * com_err.h (error_table_name): add __P
+
+1999-07-03 Assar Westerlund <assar@sics.se>
+
+ * parse.y (statement): use asprintf
+
+1999-06-13 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in: make it solaris make vpath-safe
+
+Thu Apr 1 11:13:53 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * compile_et.c: use getargs
+
+Sat Mar 20 00:16:30 1999 Assar Westerlund <assar@sics.se>
+
+ * compile_et.c: static-ize
+
+Thu Mar 18 11:22:13 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: include Makefile.am.common
+
+Tue Mar 16 22:30:05 1999 Assar Westerlund <assar@sics.se>
+
+ * parse.y: use YYACCEPT instead of return
+
+Sat Mar 13 22:22:56 1999 Assar Westerlund <assar@sics.se>
+
+ * compile_et.c (generate_h): cast when calling is* to get rid of a
+ warning
+
+Thu Mar 11 15:00:51 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * parse.y: prototype for error_message
+
+Sun Nov 22 10:39:02 1998 Assar Westerlund <assar@sics.se>
+
+ * compile_et.h: include ctype and roken
+
+ * compile_et.c: include err.h
+ (generate_h): remove unused variable
+
+ * Makefile.in (WFLAGS): set
+
+Fri Nov 20 06:58:59 1998 Assar Westerlund <assar@sics.se>
+
+ * lex.l: undef ECHO to work around AIX lex bug
+
+Sun Sep 27 02:23:59 1998 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * com_err.c (error_message): try to pass code to strerror, to see
+ if it might be an errno code (this if broken, but some MIT code
+ seems to expect this behaviour)
+
+Sat Sep 26 17:42:39 1998 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * compile_et.c: <foo_err.h> -> "foo_err.h"
+
+Tue Jun 30 17:17:36 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in: add str{cpy,cat}_truncate
+
+Mon May 25 05:24:39 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (clean): try to remove shared library debris
+
+Sun Apr 19 09:50:17 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in: add symlink magic for linux
+
+Sun Apr 5 09:22:11 1998 Assar Westerlund <assar@sics.se>
+
+ * parse.y: define alloca to malloc in case we're using bison but
+ don't have alloca
+
+Tue Mar 24 05:13:01 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in: link with snprintf (From Derrick J Brashear
+ <shadow@dementia.org>)
+
+Fri Feb 27 05:01:42 1998 Assar Westerlund <assar@sics.se>
+
+ * parse.y: initialize ec->next
+
+Thu Feb 26 02:22:25 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: @LEXLIB@
+
+Sat Feb 21 15:18:54 1998 assar westerlund <assar@sics.se>
+
+ * Makefile.in: set YACC and LEX
+
+Tue Feb 17 22:20:27 1998 Bjoern Groenvall <bg@sics.se>
+
+ * com_right.h: Change typedefs so that one may mix MIT compile_et
+ generated code with krb4 dito.
+
+Tue Feb 17 16:30:55 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * compile_et.c (generate): Always return a value.
+
+ * parse.y: Files don't have to end with `end'.
+
+Mon Feb 16 16:09:20 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * lex.l (getstring): Replace getc() with input().
+
+ * Makefile.am: Fixes for new compile_et.
diff --git a/third_party/heimdal/lib/com_err/Makefile.am b/third_party/heimdal/lib/com_err/Makefile.am
new file mode 100644
index 0000000..14e8e66
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/Makefile.am
@@ -0,0 +1,50 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+YFLAGS = -d -o parse.c
+LFLAGS = @FLEXNOUNPUTARGS@
+
+lib_LTLIBRARIES = libcom_err.la
+libcom_err_la_LDFLAGS = -version-info 2:3:1
+
+if versionscript
+libcom_err_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+endif
+
+libcom_err_la_LIBADD = $(LIB_libintl)
+
+noinst_PROGRAMS = compile_et
+
+include_HEADERS = com_err.h com_right.h
+
+compile_et_SOURCES = compile_et.c compile_et.h parse.y lex.l lex.h
+
+libcom_err_la_CPPFLAGS = $(ROKEN_RENAME) $(INCLUDE_libintl)
+dist_libcom_err_la_SOURCES = error.c com_err.c roken_rename.h
+
+if do_roken_rename
+nodist_libcom_err_la_SOURCES = snprintf.c strlcpy.c
+endif
+
+libcom_err_la_DEPENDENCIES = version-script.map
+
+$(compile_et_OBJECTS): parse.h parse.c ## XXX broken automake 1.4s
+
+compile_et_LDADD = \
+ libcom_err.la \
+ $(LIB_roken) \
+ $(LEXLIB)
+
+snprintf.c:
+ $(LN_S) $(srcdir)/../roken/snprintf.c .
+strlcpy.c:
+ $(LN_S) $(srcdir)/../roken/strlcpy.c .
+
+EXTRA_DIST = \
+ NTMakefile \
+ com_err.3 \
+ compile_et-version.rc \
+ libcom_err-version.rc \
+ libcom_err-exports.def \
+ version-script.map
diff --git a/third_party/heimdal/lib/com_err/NTMakefile b/third_party/heimdal/lib/com_err/NTMakefile
new file mode 100644
index 0000000..531b8ab
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/NTMakefile
@@ -0,0 +1,91 @@
+########################################################################
+#
+# Copyright (c) 2009, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR = lib\com_err
+
+intcflags=-DBUILD_KRB5_LIB
+
+!include ../../windows/NTMakefile.w32
+
+INCFILES=$(INCDIR)\com_err.h $(INCDIR)\com_right.h
+
+libcomerr_OBJs=$(OBJ)\error.obj $(OBJ)\com_err.obj
+
+COMERRDLL=$(BINDIR)\com_err.dll
+
+!ifdef STATICLIBS
+
+$(LIBCOMERR): $(libcomerr_OBJs)
+ $(LIBCON)
+
+!else
+
+$(LIBCOMERR): $(COMERRDLL)
+
+$(COMERRDLL): $(libcomerr_OBJs) $(OBJ)\libcom_err-version.res
+ $(DLLGUILINK_C) -out:$(COMERRDLL) -implib:$(LIBCOMERR) $** \
+ $(LIBROKEN) \
+ -def:libcom_err-exports.def
+ $(DLLPREP_NODIST)
+
+!endif
+
+$(BINDIR)\compile_et.exe: $(OBJ)\parse.obj $(OBJ)\lex.obj $(OBJ)\compile_et.obj $(OBJ)\compile_et-version.res
+ $(EXECONLINK) $(LIBROKEN) $(LIBVERS)
+ $(EXEPREP_NOHEIM)
+
+$(OBJ)\parse.obj: $(OBJ)\parse.c
+ $(C2OBJ) -I$(SRC)\$(RELDIR)
+
+$(OBJ)\lex.obj: $(OBJ)\lex.c
+ $(C2OBJ) -I$(SRC)\$(RELDIR) -DYY_NO_UNISTD_H
+
+$(OBJ)\compile_et.obj: compile_et.c
+ $(C2OBJ) -I$(OBJ)
+
+$(OBJ)\parse.c: parse.y
+ $(YACC) -o $@ --defines=$(OBJ)\parse.h parse.y
+
+$(OBJ)\lex.c: lex.l
+ $(LEX) -o$@ lex.l
+
+all:: $(INCFILES) $(LIBCOMERR) $(BINDIR)\compile_et.exe
+
+clean::
+ -$(RM) $(LIBCOMERR)
+ -$(RM) $(INCFILES)
+ -$(RM) $(COMERRDLL:.dll=.*)
+ -$(RM) $(BINDIR)\compile_et.*
+
+test-exports:
+ $(PERL) ..\..\cf\w32-check-exported-symbols.pl --vs version-script.map --def libcom_err-exports.def
+
+test:: test-exports
diff --git a/third_party/heimdal/lib/com_err/com_err.3 b/third_party/heimdal/lib/com_err/com_err.3
new file mode 100644
index 0000000..c768616
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/com_err.3
@@ -0,0 +1,246 @@
+.\" Copyright (c) 2005 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.\" This manpage was contributed by Gregory McGarry.
+.\"
+.Dd July 7, 2005
+.Dt COM_ERR 3
+.Os
+.Sh NAME
+.Nm com_err ,
+.Nm com_err_va ,
+.Nm error_message ,
+.Nm error_table_name ,
+.Nm init_error_table ,
+.Nm set_com_err_hook ,
+.Nm reset_com_err_hook ,
+.Nm add_to_error_table ,
+.Nm initialize_error_table_r ,
+.Nm free_error_table ,
+.Nm com_right
+.Nd common error display library
+.Sh LIBRARY
+Common Error Library (libcom_err, -lcom_err)
+.Sh SYNOPSIS
+.Fd #include <stdio.h>
+.Fd #include <stdarg.h>
+.Fd #include <krb5/com_err.h>
+.Fd #include \&"XXX_err.h\&"
+.Pp
+typedef void (*errf)(const char *, long, const char *, ...);
+.Ft void
+.Fn com_err "const char *whoami" "long code" "const char *format" "..."
+.Ft void
+.Fn com_err_va "const char *whoami" "long code" "const char *format" "..."
+.Ft const char *
+.Fn error_message "long code"
+.Ft const char *
+.Fn error_table_name "int num"
+.Ft int
+.Fn init_error_table "const char **msgs" "long base" "int count"
+.Ft errf
+.Fn set_com_err_hook "errf func"
+.Ft errf
+.Fn reset_com_err_hook ""
+.Ft void
+.Fn add_to_error_table "struct et_list *new_table"
+.Ft void
+.Fn initialize_error_table_r "struct et_list **et_list" "const char **msgs" "int base" "long count"
+.Ft void
+.Fn free_error_table "struct et_list *"
+.Ft const char *
+.Fn com_right "struct et_list *list" long code"
+.Sh DESCRIPTION
+The
+.Nm
+library provides a common error-reporting mechanism for defining and
+accessing error codes and descriptions for application software
+packages. Error descriptions are defined in a table and error codes
+are used to index the table. The error table, the descriptions and
+the error codes are generated using
+.Xr compile_et 1 .
+.Pp
+The error table is registered with the
+.Nm
+library by calling its initialisation function defined in its header
+file. The initialisation function is generally defined as
+.Fn initialize_<name>_error_table ,
+where
+.Em name
+is the name of the error table.
+.Pp
+If a thread-safe version of the library is needed
+.Fn initialize_<name>_error_table_r
+that internally calls
+.Fn initialize_error_table_r
+instead be used.
+.Pp
+Any variable which is to contain an error code should be declared
+.Em <name>_error_number
+where
+.Em name
+is the name of the error table.
+.Sh FUNCTIONS
+The following functions are available to the application developer:
+.Bl -tag -width compact
+.It Fn com_err "whoami" "code" "format" "..."
+Displays an error message on standard error composed of the
+.Fa whoami
+string, which should specify the program name, followed by an error
+message generated from
+.Fa code ,
+and a string produced using the
+.Xr printf 3
+.Fa format
+string and any following arguments. If
+.Fa format
+is NULL, the formatted message will not be
+printed. The argument
+.Fa format
+may not be omitted.
+.It Fn com_err_va "whoami" "code" "format" "va_list args"
+This routine provides an interface, equivalent to
+.Fn com_err ,
+which may be used by higher-level variadic functions (functions which
+accept variable numbers of arguments).
+.It Fn error_message "code"
+Returns the character string error message associated with
+.Fa code .
+If
+.Fa code
+is associated with an unknown error table, or if
+.Fa code
+is associated with a known error table but is not in the table, a
+string of the form `Unknown code XXXX NN' is returned, where XXXX is
+the error table name produced by reversing the compaction performed on
+the error table number implied by that error code, and NN is the
+offset from that base value.
+.Pp
+Although this routine is available for use when needed, its use should
+be left to circumstances which render
+.Fn com_err
+unusable.
+.Pp
+.Fn com_right
+returns the error string just like
+.Fa com_err
+but in a thread-safe way.
+.Pp
+.It Fn error_table_name "num"
+Convert a machine-independent error table number
+.Fa num
+into an error table name.
+.It Fn init_error_table "msgs" "base" "count"
+Initialise the internal error table with the array of character string
+error messages in
+.Fa msgs
+of length
+.Fa count .
+The error codes are assigned incrementally from
+.Fa base .
+This function is useful for using the error-reporting mechanism with
+custom error tables that have not been generated with
+.Xr compile_et 1 .
+Although this routine is available for use when needed, its use should
+be restricted.
+.Pp
+.Fn initialize_error_table_r
+initialize the
+.Fa et_list
+in the same way as
+.Fn init_error_table ,
+but in a thread-safe way.
+.Pp
+.It Fn set_com_err_hook "func"
+Provides a hook into the
+.Nm
+library to allow the routine
+.Fa func
+to be dynamically substituted for
+.Fn com_err .
+After
+.Fn set_com_err_hook
+ has been called, calls to
+.Fn com_err
+will turn into calls to the new hook routine. This function is
+intended to be used in daemons to use a routine which calls
+.Xr syslog 3 ,
+or in a window system application to pop up a dialogue box.
+.It Fn reset_com_err_hook ""
+Turns off the hook set in
+.Fn set_com_err_hook .
+.It Fn add_to_error_table "new_table"
+Add the error table, its messages strings and error codes in
+.Fa new_table
+to the internal error table.
+.El
+.Sh EXAMPLES
+The following is an example using the table defined in
+.Xr compile_et 1 :
+.Pp
+.Bd -literal
+ #include <stdio.h>
+ #include <stdarg.h>
+ #include <syslog.h>
+
+ #include "test_err.h"
+
+ void
+ hook(const char *whoami, long code,
+ const char *format, va_list args)
+ {
+ char buffer[BUFSIZ];
+ static int initialized = 0;
+
+ if (!initialized) {
+ openlog(whoami, LOG_NOWAIT, LOG_DAEMON);
+ initialized = 1;
+ }
+ vsprintf(buffer, format, args);
+ syslog(LOG_ERR, "%s %s", error_message(code), buffer);
+ }
+
+ int
+ main(int argc, char *argv[])
+ {
+ char *whoami = argv[0];
+
+ initialize_test_error_table();
+ com_err(whoami, TEST_INVAL, "before hook");
+ set_com_err_hook(hook);
+ com_err(whoami, TEST_IO, "after hook");
+ return (0);
+ }
+.Ed
+.Sh SEE ALSO
+.Xr compile_et 1
diff --git a/third_party/heimdal/lib/com_err/com_err.c b/third_party/heimdal/lib/com_err/com_err.c
new file mode 100644
index 0000000..52f6e2e
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/com_err.c
@@ -0,0 +1,172 @@
+/*
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+
+#include <config.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <roken.h>
+#include <heim_threads.h>
+#include "com_err.h"
+
+struct et_list *_et_list = NULL;
+
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+error_message (long code)
+{
+ static char msg[128];
+ const char *p = com_right(_et_list, code);
+ if (p == NULL) {
+ if (code < 0)
+ snprintf(msg, sizeof(msg), "Unknown error %ld", code);
+ else
+ p = strerror(code);
+ }
+ if (p != NULL && *p != '\0') {
+ strlcpy(msg, p, sizeof(msg));
+ } else
+ snprintf(msg, sizeof(msg), "Unknown error %ld", code);
+ return msg;
+}
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+init_error_table(const char **msgs, long base, int count)
+{
+ initialize_error_table_r(&_et_list, msgs, count, base);
+ return 0;
+}
+
+static void KRB5_CALLCONV
+default_proc (const char *whoami, long code, const char *fmt, va_list args)
+ __attribute__ ((__format__ (__printf__, 3, 0)));
+
+static void KRB5_CALLCONV
+default_proc (const char *whoami, long code, const char *fmt, va_list args)
+{
+ if (whoami)
+ fprintf(stderr, "%s: ", whoami);
+ if (code)
+ fprintf(stderr, "%s ", error_message(code));
+ if (fmt)
+ vfprintf(stderr, fmt, args);
+ fprintf(stderr, "\r\n"); /* ??? */
+}
+
+static errf com_err_hook = default_proc;
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+com_err_va (const char *whoami,
+ long code,
+ const char *fmt,
+ va_list args)
+{
+ (*com_err_hook) (whoami, code, fmt, args);
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+com_err (const char *whoami,
+ long code,
+ const char *fmt,
+ ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ com_err_va (whoami, code, fmt, ap);
+ va_end(ap);
+}
+
+KRB5_LIB_FUNCTION errf KRB5_LIB_CALL
+set_com_err_hook (errf new)
+{
+ errf old = com_err_hook;
+
+ if (new)
+ com_err_hook = new;
+ else
+ com_err_hook = default_proc;
+
+ return old;
+}
+
+KRB5_LIB_FUNCTION errf KRB5_LIB_CALL
+reset_com_err_hook (void)
+{
+ return set_com_err_hook(NULL);
+}
+
+#define ERRCODE_RANGE 8 /* # of bits to shift table number */
+#define BITS_PER_CHAR 6 /* # bits to shift per character in name */
+
+static const char char_set[] =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
+
+static HEIMDAL_THREAD_LOCAL char buf[6];
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+error_table_name(int num)
+{
+ int ch;
+ int i;
+ char *p;
+
+ /* num = aa aaa abb bbb bcc ccc cdd ddd d?? ??? ??? */
+ p = buf;
+ num >>= ERRCODE_RANGE;
+ /* num = ?? ??? ??? aaa aaa bbb bbb ccc ccc ddd ddd */
+ num &= 077777777;
+ /* num = 00 000 000 aaa aaa bbb bbb ccc ccc ddd ddd */
+ for (i = 4; i >= 0; i--) {
+ ch = (num >> BITS_PER_CHAR * i) & ((1 << BITS_PER_CHAR) - 1);
+ if (ch != 0)
+ *p++ = char_set[ch-1];
+ }
+ *p = '\0';
+ return(buf);
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+add_to_error_table(struct et_list *new_table)
+{
+ struct et_list *et;
+
+ for (et = _et_list; et; et = et->next) {
+ if (et->table->base == new_table->table->base)
+ return;
+ }
+
+ new_table->next = _et_list;
+ _et_list = new_table;
+}
diff --git a/third_party/heimdal/lib/com_err/com_err.h b/third_party/heimdal/lib/com_err/com_err.h
new file mode 100644
index 0000000..e71eabf
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/com_err.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+/* MIT compatible com_err library */
+
+#ifndef __COM_ERR_H__
+#define __COM_ERR_H__
+
+#include <com_right.h>
+#include <stdarg.h>
+
+#if !defined(__GNUC__) && !defined(__attribute__)
+#define __attribute__(X)
+#endif
+
+typedef void (KRB5_CALLCONV *errf) (const char *, long, const char *, va_list);
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+error_message (long);
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+init_error_table (const char**, long, int);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+com_err_va (const char *, long, const char *, va_list)
+ __attribute__ ((__format__ (__printf__, 3, 0)));
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+com_err (const char *, long, const char *, ...)
+ __attribute__ ((__format__ (__printf__, 3, 4)));
+
+KRB5_LIB_FUNCTION errf KRB5_LIB_CALL
+set_com_err_hook (errf);
+
+KRB5_LIB_FUNCTION errf KRB5_LIB_CALL
+reset_com_err_hook (void);
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+error_table_name (int num);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+add_to_error_table (struct et_list *new_table);
+
+#endif /* __COM_ERR_H__ */
diff --git a/third_party/heimdal/lib/com_err/com_right.h b/third_party/heimdal/lib/com_err/com_right.h
new file mode 100644
index 0000000..7741684
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/com_right.h
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __COM_RIGHT_H__
+#define __COM_RIGHT_H__
+
+#ifndef KRB5_LIB
+#ifndef KRB5_LIB_FUNCTION
+#if defined(_WIN32)
+#define KRB5_LIB_FUNCTION __declspec(dllimport)
+#define KRB5_LIB_CALL __stdcall
+#define KRB5_LIB_VARIABLE __declspec(dllimport)
+#else
+#define KRB5_LIB_FUNCTION
+#define KRB5_LIB_CALL
+#define KRB5_LIB_VARIABLE
+#endif
+#endif
+#endif
+
+#ifdef _WIN32
+#define KRB5_CALLCONV __stdcall
+#else
+#define KRB5_CALLCONV
+#endif
+
+#ifdef __STDC__
+#include <stdarg.h>
+#include <stddef.h>
+#endif
+
+struct error_table {
+ char const * const * msgs;
+ long base;
+ int n_msgs;
+};
+struct et_list {
+ struct et_list *next;
+ struct error_table *table;
+};
+extern struct et_list *_et_list;
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+com_right (struct et_list *list, long code);
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+com_right_r (struct et_list *list, long code, char *, size_t);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+initialize_error_table_r (struct et_list **, const char **, int, long);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+free_error_table (struct et_list *);
+
+#endif /* __COM_RIGHT_H__ */
diff --git a/third_party/heimdal/lib/com_err/compile_et-version.rc b/third_party/heimdal/lib/com_err/compile_et-version.rc
new file mode 100644
index 0000000..5b0b91a
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/compile_et-version.rc
@@ -0,0 +1,36 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#define RC_FILE_TYPE VFT_APP
+#define RC_FILE_DESC_0409 "Error Table Compiler"
+#define RC_FILE_ORIG_0409 "compile_et.exe"
+
+#include "../../windows/version.rc"
diff --git a/third_party/heimdal/lib/com_err/compile_et.c b/third_party/heimdal/lib/com_err/compile_et.c
new file mode 100644
index 0000000..84ebf0c
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/compile_et.c
@@ -0,0 +1,243 @@
+/*
+ * Copyright (c) 1998-2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#undef ROKEN_RENAME
+
+#include "config.h"
+
+#include "compile_et.h"
+#include <getarg.h>
+
+#include <roken.h>
+#include <err.h>
+#include "parse.h"
+
+int numerror;
+extern FILE *yyin;
+
+int yyparse(void);
+
+long base_id;
+int number;
+char *prefix;
+char *id_str;
+
+char name[128];
+char Basename[128];
+
+#ifdef YYDEBUG
+extern int yydebug;
+int yydebug = 1;
+#endif
+
+char *filename;
+char hfn[130];
+char cfn[130];
+
+struct error_code *codes = NULL;
+
+static int
+generate_c(void)
+{
+ int n;
+ struct error_code *ec;
+
+ FILE *c_file = fopen(cfn, "w");
+ if(c_file == NULL)
+ return 1;
+
+ fprintf(c_file, "/* Generated from %s */\n", filename);
+ if(id_str)
+ fprintf(c_file, "/* %s */\n", id_str);
+ fprintf(c_file, "\n");
+ fprintf(c_file, "#include <stddef.h>\n");
+ fprintf(c_file, "#include <com_err.h>\n");
+ fprintf(c_file, "#include \"%s\"\n", hfn);
+ fprintf(c_file, "\n");
+ fprintf(c_file, "#define N_(x) (x)\n");
+ fprintf(c_file, "\n");
+
+ fprintf(c_file, "static const char *%s_error_strings[] = {\n", name);
+
+ for(ec = codes, n = 0; ec; ec = ec->next, n++) {
+ while(n < ec->number) {
+ fprintf(c_file, "\t/* %03d */ \"Reserved %s error (%d)\",\n",
+ n, name, n);
+ n++;
+
+ }
+ fprintf(c_file, "\t/* %03d */ N_(\"%s\"),\n",
+ ec->number, ec->string);
+ }
+
+ fprintf(c_file, "\tNULL\n");
+ fprintf(c_file, "};\n");
+ fprintf(c_file, "\n");
+ fprintf(c_file, "#define num_errors %d\n", number);
+ fprintf(c_file, "\n");
+ fprintf(c_file,
+ "void initialize_%s_error_table_r(struct et_list **list)\n",
+ name);
+ fprintf(c_file, "{\n");
+ fprintf(c_file,
+ " initialize_error_table_r(list, %s_error_strings, "
+ "num_errors, ERROR_TABLE_BASE_%s);\n", name, name);
+ fprintf(c_file, "}\n");
+ fprintf(c_file, "\n");
+ fprintf(c_file, "void initialize_%s_error_table(void)\n", name);
+ fprintf(c_file, "{\n");
+ fprintf(c_file,
+ " init_error_table(%s_error_strings, ERROR_TABLE_BASE_%s, "
+ "num_errors);\n", name, name);
+ fprintf(c_file, "}\n");
+
+ fclose(c_file);
+ return 0;
+}
+
+static int
+generate_h(void)
+{
+ struct error_code *ec;
+ char fn[134];
+ FILE *h_file = fopen(hfn, "w");
+ char *p;
+
+ if(h_file == NULL)
+ return 1;
+
+ snprintf(fn, sizeof(fn), "__%s__", hfn);
+ for(p = fn; *p; p++)
+ if(!isalnum((unsigned char)*p))
+ *p = '_';
+
+ fprintf(h_file, "/* Generated from %s */\n", filename);
+ if(id_str)
+ fprintf(h_file, "/* %s */\n", id_str);
+ fprintf(h_file, "\n");
+ fprintf(h_file, "#ifndef %s\n", fn);
+ fprintf(h_file, "#define %s\n", fn);
+ fprintf(h_file, "\n");
+ fprintf(h_file, "struct et_list;\n");
+ fprintf(h_file, "\n");
+ fprintf(h_file,
+ "void initialize_%s_error_table_r(struct et_list **);\n",
+ name);
+ fprintf(h_file, "\n");
+ fprintf(h_file, "void initialize_%s_error_table(void);\n", name);
+ fprintf(h_file, "#define init_%s_err_tbl initialize_%s_error_table\n",
+ name, name);
+ fprintf(h_file, "\n");
+ fprintf(h_file, "typedef enum %s_error_number{\n", name);
+
+ for(ec = codes; ec; ec = ec->next) {
+ fprintf(h_file, "\t%s = %ld%s\n", ec->name, base_id + ec->number,
+ (ec->next != NULL) ? "," : "");
+ }
+
+ fprintf(h_file, "} %s_error_number;\n", name);
+ fprintf(h_file, "\n");
+ fprintf(h_file, "#define ERROR_TABLE_BASE_%s %ld\n", name, base_id);
+ fprintf(h_file, "\n");
+ fprintf(h_file, "#define COM_ERR_BINDDOMAIN_%s \"heim_com_err%ld\"\n", name, base_id);
+ fprintf(h_file, "\n");
+ fprintf(h_file, "#endif /* %s */\n", fn);
+
+
+ fclose(h_file);
+ return 0;
+}
+
+static int
+generate(void)
+{
+ return generate_c() || generate_h();
+}
+
+int version_flag;
+int help_flag;
+struct getargs args[] = {
+ { "version", 0, arg_flag, &version_flag, NULL, NULL },
+ { "help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+int num_args = sizeof(args) / sizeof(args[0]);
+
+static void
+usage(int code)
+{
+ arg_printusage(args, num_args, NULL, "error-table");
+ exit(code);
+}
+
+int
+main(int argc, char **argv)
+{
+ char *p;
+ int optidx = 0;
+
+ setprogname(argv[0]);
+ if(getarg(args, num_args, argc, argv, &optidx))
+ usage(1);
+ if(help_flag)
+ usage(0);
+ if(version_flag) {
+ print_version(NULL);
+ exit(0);
+ }
+
+ if(optidx == argc)
+ usage(1);
+ filename = argv[optidx];
+ yyin = fopen(filename, "r");
+ if(yyin == NULL)
+ err(1, "%s", filename);
+
+
+ p = strrchr(filename, rk_PATH_DELIM);
+ if(p)
+ p++;
+ else
+ p = filename;
+ strlcpy(Basename, p, sizeof(Basename));
+
+ Basename[strcspn(Basename, ".")] = '\0';
+
+ snprintf(hfn, sizeof(hfn), "%s.h", Basename);
+ snprintf(cfn, sizeof(cfn), "%s.c", Basename);
+
+ yyparse();
+ if(numerror)
+ return 1;
+
+ return generate();
+}
diff --git a/third_party/heimdal/lib/com_err/compile_et.h b/third_party/heimdal/lib/com_err/compile_et.h
new file mode 100644
index 0000000..b0b8e21
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/compile_et.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 1998 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __COMPILE_ET_H__
+#define __COMPILE_ET_H__
+
+#include <config.h>
+
+#include <err.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <ctype.h>
+#include <roken.h>
+
+extern long base_id;
+extern int number;
+extern char *prefix;
+extern char name[128];
+extern char *id_str;
+extern char *filename;
+extern int numerror;
+
+struct error_code {
+ unsigned number;
+ char *name;
+ char *string;
+ struct error_code *next, **tail;
+};
+
+extern struct error_code *codes;
+
+#define APPEND(L, V) \
+do { \
+ if((L) == NULL) { \
+ (L) = (V); \
+ (L)->tail = &(V)->next; \
+ (L)->next = NULL; \
+ }else{ \
+ *(L)->tail = (V); \
+ (L)->tail = &(V)->next; \
+ } \
+}while(0)
+
+#endif /* __COMPILE_ET_H__ */
diff --git a/third_party/heimdal/lib/com_err/error.c b/third_party/heimdal/lib/com_err/error.c
new file mode 100644
index 0000000..bf046da
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/error.c
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 1997, 1998, 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+
+#include <config.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <com_right.h>
+#include <roken.h>
+
+#ifdef LIBINTL
+#include <libintl.h>
+#else
+#define dgettext(d,s) (s)
+#endif
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+com_right(struct et_list *list, long code)
+{
+ struct et_list *p;
+ for (p = list; p; p = p->next)
+ if (code >= p->table->base && code < p->table->base + p->table->n_msgs)
+ return p->table->msgs[code - p->table->base];
+ return NULL;
+}
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+com_right_r(struct et_list *list, long code, char *str, size_t len)
+{
+ struct et_list *p;
+ for (p = list; p; p = p->next) {
+ if (code >= p->table->base && code < p->table->base + p->table->n_msgs) {
+ const char *msg = p->table->msgs[code - p->table->base];
+#ifdef LIBINTL
+ char domain[12 + 20];
+ snprintf(domain, sizeof(domain), "heim_com_err%ld", p->table->base);
+#endif
+ strlcpy(str, dgettext(domain, msg), len);
+ return str;
+ }
+ }
+ return NULL;
+}
+
+struct foobar {
+ struct et_list etl;
+ struct error_table et;
+};
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+initialize_error_table_r(struct et_list **list,
+ const char **messages,
+ int num_errors,
+ long base)
+{
+ struct et_list *et, **end;
+ struct foobar *f;
+ for (end = list, et = *list; et; end = &et->next, et = et->next)
+ if (et->table->msgs == messages)
+ return;
+ f = malloc(sizeof(*f));
+ if (f == NULL)
+ return;
+ et = &f->etl;
+ et->table = &f->et;
+ et->table->msgs = messages;
+ et->table->n_msgs = num_errors;
+ et->table->base = base;
+ et->next = NULL;
+ *end = et;
+}
+
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+free_error_table(struct et_list *et)
+{
+ while(et){
+ struct et_list *p = et;
+ et = et->next;
+ free(p);
+ }
+}
diff --git a/third_party/heimdal/lib/com_err/lex.h b/third_party/heimdal/lib/com_err/lex.h
new file mode 100644
index 0000000..dcf6e87
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/lex.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+void _lex_error_message (const char *, ...)
+__attribute__ ((__format__ (__printf__, 1, 2)));
+
+int yylex(void);
diff --git a/third_party/heimdal/lib/com_err/lex.l b/third_party/heimdal/lib/com_err/lex.l
new file mode 100644
index 0000000..e812b32
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/lex.l
@@ -0,0 +1,123 @@
+%{
+/*
+ * Copyright (c) 1998 - 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * This is to handle the definition of this symbol in some AIX
+ * headers, which will conflict with the definition that lex will
+ * generate for it. It's only a problem for AIX lex.
+ */
+
+#undef ECHO
+
+#include "compile_et.h"
+#include "parse.h"
+#include "lex.h"
+
+static unsigned lineno = 1;
+static int getstring(void);
+
+#define YY_NO_UNPUT
+
+#undef ECHO
+
+%}
+
+%%
+et { return ET; }
+error_table { return ET; }
+ec { return EC; }
+error_code { return EC; }
+prefix { return PREFIX; }
+index { return INDEX; }
+id { return ID; }
+end { return END; }
+[0-9]+ { yylval.number = atoi(yytext); return NUMBER; }
+#[^\n]* ;
+[ \t] ;
+\n { lineno++; }
+\" { return getstring(); }
+[a-zA-Z0-9_]+ { yylval.string = strdup(yytext); return STRING; }
+. { return *yytext; }
+%%
+
+int
+yywrap ()
+{
+ return 1;
+}
+
+static int
+getstring(void)
+{
+ char x[128];
+ int i = 0;
+ int c;
+ int quote = 0;
+ while(i < sizeof(x) - 1 && (c = input()) != EOF){
+ if(quote) {
+ x[i++] = c;
+ quote = 0;
+ continue;
+ }
+ if(c == '\n'){
+ _lex_error_message("unterminated string");
+ lineno++;
+ break;
+ }
+ if(c == '\\'){
+ quote++;
+ continue;
+ }
+ if(c == '\"')
+ break;
+ x[i++] = c;
+ }
+ x[i] = '\0';
+ yylval.string = strdup(x);
+ if (yylval.string == NULL)
+ err(1, "malloc");
+ return STRING;
+}
+
+void
+_lex_error_message (const char *format, ...)
+{
+ va_list args;
+
+ va_start (args, format);
+ fprintf (stderr, "%s:%d:", filename, lineno);
+ vfprintf (stderr, format, args);
+ va_end (args);
+ numerror++;
+}
diff --git a/third_party/heimdal/lib/com_err/libcom_err-exports.def b/third_party/heimdal/lib/com_err/libcom_err-exports.def
new file mode 100644
index 0000000..a4db194
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/libcom_err-exports.def
@@ -0,0 +1,14 @@
+EXPORTS
+ com_right
+ com_right_r
+ free_error_table
+ initialize_error_table_r
+ add_to_error_table
+ com_err
+ com_err_va
+ error_message
+ error_table_name
+ init_error_table
+ reset_com_err_hook
+ set_com_err_hook
+ _et_list DATA
diff --git a/third_party/heimdal/lib/com_err/libcom_err-version.rc b/third_party/heimdal/lib/com_err/libcom_err-version.rc
new file mode 100644
index 0000000..7fe6432
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/libcom_err-version.rc
@@ -0,0 +1,36 @@
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#define RC_FILE_TYPE VFT_DLL
+#define RC_FILE_DESC_0409 "Common Error Library"
+#define RC_FILE_ORIG_0409 "com_err.dll"
+
+#include "../../windows/version.rc"
diff --git a/third_party/heimdal/lib/com_err/parse.y b/third_party/heimdal/lib/com_err/parse.y
new file mode 100644
index 0000000..bcb9b05
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/parse.y
@@ -0,0 +1,175 @@
+%{
+/*
+ * Copyright (c) 1998 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "compile_et.h"
+#include "lex.h"
+
+void yyerror (const char *s);
+#define yyerror yyerror
+static long name2number(const char *str);
+
+extern char *yytext;
+
+/* This is for bison */
+
+#if !defined(alloca) && !defined(HAVE_ALLOCA)
+#define alloca(x) malloc(x)
+#endif
+
+#define YYMALLOC malloc
+#define YYFREE free
+
+%}
+
+%union {
+ char *string;
+ int number;
+}
+
+%token ET INDEX PREFIX EC ID END
+%token <string> STRING
+%token <number> NUMBER
+
+%%
+
+file : /* */
+ | header statements
+ ;
+
+header : id et
+ | et
+ ;
+
+id : ID STRING
+ {
+ id_str = $2;
+ }
+ ;
+
+et : ET STRING
+ {
+ base_id = name2number($2);
+ strlcpy(name, $2, sizeof(name));
+ free($2);
+ }
+ | ET STRING STRING
+ {
+ base_id = name2number($2);
+ strlcpy(name, $3, sizeof(name));
+ free($2);
+ free($3);
+ }
+ ;
+
+statements : statement
+ | statements statement
+ ;
+
+statement : INDEX NUMBER
+ {
+ number = $2;
+ }
+ | PREFIX STRING
+ {
+ free(prefix);
+ asprintf (&prefix, "%s_", $2);
+ if (prefix == NULL)
+ errx(1, "malloc");
+ free($2);
+ }
+ | PREFIX
+ {
+ prefix = realloc(prefix, 1);
+ if (prefix == NULL)
+ errx(1, "malloc");
+ *prefix = '\0';
+ }
+ | EC STRING ',' STRING
+ {
+ struct error_code *ec = malloc(sizeof(*ec));
+
+ if (ec == NULL)
+ errx(1, "malloc");
+
+ ec->next = NULL;
+ ec->number = number;
+ if(prefix && *prefix != '\0') {
+ asprintf (&ec->name, "%s%s", prefix, $2);
+ if (ec->name == NULL)
+ errx(1, "malloc");
+ free($2);
+ } else
+ ec->name = $2;
+ ec->string = $4;
+ APPEND(codes, ec);
+ number++;
+ }
+ | END
+ {
+ YYACCEPT;
+ }
+ ;
+
+%%
+
+static long
+name2number(const char *str)
+{
+ const char *p;
+ long num = 0;
+ const char *x = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz0123456789_";
+ if(strlen(str) > 4) {
+ yyerror("table name too long");
+ return 0;
+ }
+ for(p = str; *p; p++){
+ char *q = strchr(x, *p);
+ if(q == NULL) {
+ yyerror("invalid character in table name");
+ return 0;
+ }
+ num = (num << 6) + (q - x) + 1;
+ }
+ num <<= 8;
+ if(num > 0x7fffffff)
+ num = -(0xffffffff - num + 1);
+ return num;
+}
+
+void
+yyerror (const char *s)
+{
+ _lex_error_message ("%s\n", s);
+}
diff --git a/third_party/heimdal/lib/com_err/roken_rename.h b/third_party/heimdal/lib/com_err/roken_rename.h
new file mode 100644
index 0000000..3da2948
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/roken_rename.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __roken_rename_h__
+#define __roken_rename_h__
+
+#ifndef HAVE_SNPRINTF
+#define rk_snprintf _com_err_snprintf
+#endif
+#ifndef HAVE_VSNPRINTF
+#define rk_vsnprintf _com_err_vsnprintf
+#endif
+#ifndef HAVE_ASPRINTF
+#define rk_asprintf _com_err_asprintf
+#endif
+#ifndef HAVE_ASNPRINTF
+#define rk_asnprintf _com_err_asnprintf
+#endif
+#ifndef HAVE_VASPRINTF
+#define rk_vasprintf _com_err_vasprintf
+#endif
+#ifndef HAVE_VASNPRINTF
+#define rk_vasnprintf _com_err_vasnprintf
+#endif
+#ifndef HAVE_STRLCPY
+#define rk_strlcpy _com_err_strlcpy
+#endif
+
+
+#endif /* __roken_rename_h__ */
diff --git a/third_party/heimdal/lib/com_err/version-script.map b/third_party/heimdal/lib/com_err/version-script.map
new file mode 100644
index 0000000..8da2fef
--- /dev/null
+++ b/third_party/heimdal/lib/com_err/version-script.map
@@ -0,0 +1,20 @@
+# $Id$
+
+HEIMDAL_COM_ERR_1.0 {
+ global:
+ com_right;
+ com_right_r;
+ free_error_table;
+ initialize_error_table_r;
+ add_to_error_table;
+ com_err;
+ com_err_va;
+ error_message;
+ error_table_name;
+ init_error_table;
+ reset_com_err_hook;
+ set_com_err_hook;
+ _et_list;
+ local:
+ *;
+};
diff --git a/third_party/heimdal/lib/gss_preauth/Makefile.am b/third_party/heimdal/lib/gss_preauth/Makefile.am
new file mode 100644
index 0000000..6503119
--- /dev/null
+++ b/third_party/heimdal/lib/gss_preauth/Makefile.am
@@ -0,0 +1,25 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+AM_CPPFLAGS += \
+ -I$(srcdir)/../krb5 \
+ -I$(srcdir)/../gssapi \
+ -I$(srcdir)/../gssapi/mech \
+ -I$(top_srcdir)/include/gssapi \
+ -I$(top_builddir)/include/gssapi
+
+noinst_LTLIBRARIES = libgss_preauth.la
+include_HEADERS = $(srcdir)/gss-preauth-protos.h $(srcdir)/gss-preauth-private.h
+
+libgss_preauth_la_SOURCES = pa_client.c pa_common.c
+
+ALL_OBJECTS = $(include_HEADERS) $(libgss_preauth_la_OBJECTS)
+
+$(libgss_preauth_la_OBJECTS): $(include_HEADERS)
+
+$(srcdir)/gss-preauth-protos.h: $(libgss_preauth_la_SOURCES)
+ cd $(srcdir); perl ../../cf/make-proto.pl -q -P comment -o gss-preauth-protos.h $(libgss_preauth_la_SOURCES) || rm -f gss-preauth-protos.h
+
+$(srcdir)/gss-preauth-private.h: $(libgss_preauth_la_SOURCES)
+ cd $(srcdir); perl ../../cf/make-proto.pl -q -P comment -p gss-preauth-private.h $(libgss_preauth_la_SOURCES) || rm -f gss-preauth-private.h
diff --git a/third_party/heimdal/lib/gss_preauth/NTMakefile b/third_party/heimdal/lib/gss_preauth/NTMakefile
new file mode 100644
index 0000000..60c963b
--- /dev/null
+++ b/third_party/heimdal/lib/gss_preauth/NTMakefile
@@ -0,0 +1,70 @@
+########################################################################
+#
+# Copyright (c) 2021, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\gss_preauth
+
+intcflags=-I$(SRCDIR) \
+ -I$(SRCDIR)\..\krb5 \
+ -I$(SRCDIR)\..\gssapi \
+ -I$(SRCDIR)\..\gssapi\mech \
+ -I$(OBJ) \
+ -I$(OBJDIR)\lib\gssapi \
+ -I$(OBJDIR)\lib\gssapi\gssapi \
+ -I$(INCDIR) \
+ -I$(INCDIR)\gssapi \
+
+!include ../../windows/NTMakefile.w32
+
+INCFILES= \
+ $(OBJ)\gss-preauth-protos.h \
+ $(OBJ)\gss-preauth-private.h
+
+libgss_preauth_SOURCES = \
+ pa_client.c \
+ pa_common.c
+
+libgss_preauth_OBJS = \
+ $(OBJ)\pa_client.obj \
+ $(OBJ)\pa_common.obj
+
+$(LIBGSS_PREAUTH): $(libgss_preauth_OBJS)
+ $(LIBCON)
+
+$(OBJ)\gss-preauth-protos.h: $(libgss_preauth_SOURCES)
+ $(PERL) ..\..\cf\make-proto.pl -E KRB5_LIB -q -P remove -o $(OBJ)\gss-preauth-protos.h $(libgss_preauth_SOURCES) || $(RM) -f $(OBJ)\gss-preauth-protos.h
+
+$(OBJ)\gss-preauth-private.h: $(libgss_preauth_SOURCES)
+ $(PERL) ..\..\cf\make-proto.pl -q -P remove -p $(OBJ)\gss-preauth-private.h $(libgss_preauth_SOURCES) || $(RM) -f $(OBJ)\gss-preauth-private.h
+
+all:: $(INCFILES) $(LIBGSS_PREAUTH)
+
+clean::
+ -$(RM) $(INCFILES) $(LIBGSS_PREAUTH)
diff --git a/third_party/heimdal/lib/gss_preauth/README.md b/third_party/heimdal/lib/gss_preauth/README.md
new file mode 100644
index 0000000..2a3b142
--- /dev/null
+++ b/third_party/heimdal/lib/gss_preauth/README.md
@@ -0,0 +1,110 @@
+# GSS-API Pre-authentication in Heimdal
+
+GSS-API pre-authentication in Heimdal is based on
+[draft-perez-krb-wg-gss-preauth](https://datatracker.ietf.org/doc/html/draft-perez-krb-wg-gss-preauth)
+but with some simplifications to the protocol.
+
+The following text assumes the reader is familiar with the draft.
+
+## Client side
+
+Because libkrb5 cannot have a recursive dependency on libgssapi, it instead
+exports the function `_krb5_init_creds_init_gss()` which allows libgssapi to
+register a set of function pointers for:
+
+ - Generating context tokens
+ - Finalizing a context (inquiring the initiator name and reply key)
+ - Releasing context and credential handles
+
+This is a private API.
+
+This architecture also means that the libkrb5 implementation could be used with
+an alternative GSS-API implementation such as SSPI, without too much work. The
+bulk of the pre-authentication logic remains in libkrb5, however, in
+[`init_creds_pw.c`](../../krb5/init_creds_pw.c).
+
+libgssapi itself exports `krb5_gss_set_init_creds()`, which is the public
+interface for GSS-API pre-authentication.
+
+`krb5_gss_set_init_creds()` enables GSS-API pre-authentication on an initial
+credentials context, taking a GSS-API credential handle and mechanism. Both are
+optional; defaults will be used if absent. These two parameters are exposed as
+the `--gss-name` and `--gss-mech` options to `kinit` (see
+[kinit(1)](../../../kuser/kinit.1) for further details). `kinit` supports
+acquiring anonymous, keytab- and password-based GSS-API credentials using the
+same arguments as regular Kerberos.
+
+The selected GSS-API mechanism must support mutual authentication (ie.
+authenticating the KDC) as it replaces the AS-REP reply key, However, if FAST
+was used, and we know that the KDC was verified, then this requirement is
+removed.
+
+If the client does not know its initiator name, it can specify the last
+arugment to `kinit` as `@REALM`, and the initiator name will be filled in when
+the authentication is complete. (The realm is required to select a KDC.)
+
+## KDC side
+
+The KDC implements the acceptor side of the GSS-API authentication exchange.
+The selected GSS-API mechanism must allow `gss_export_sec_context()` to be
+called by the acceptor before the context is established, if it needs more than
+a single round trip of token exchanges.
+
+### Configuration
+
+Configuration directives live in the [kdc] section of
+[krb5.conf(5)](../../krb5/krb5.conf.5).
+
+The `enable_gss_preauth` krb5.conf option must be set in order to enable
+GSS-API pre-authentication in the KDC. When authenticating federated principals
+which may not exist in the KDC, the `synthetic_clients` option should also be
+set.
+
+The `gss_mechanisms_allowed` option can be used to limit the set of GSS-API
+mechanisms which are allowed to perform pre-authentication. Mechanisms are
+specified as dot-separated OIDs or by a short name, such as `sanon-x25519`.
+
+The `enable_gss_auth_data` option will include a composite GSS name in the
+authorization data of returned tickets.
+
+### Authorization
+
+The default is that the initiator is permitted to authenticate to the Kerberos
+principal that directly corresponds to it. The correspondence is governed as
+follows: if the authenticating mechanism is in the list of mechanisms in the
+`gss_cross_realm_mechanisms_allowed` configuration option, then the principal
+is mapped identically: an initiator named `lukeh@AAA.PADL.COM` will be mapped
+to the Kerberos principal `lukeh@AAA.PADL.COM`.
+
+If the authenticating mechanism is not in this list, then the initiator will be
+mapped to an enterprise principal in the service realm. For example,
+`lukeh@AAA.PADL.COM` might be mapped to `lukeh\@AAA.PADL.COM@PADL.COM`
+(enterprise principal name type);
+
+This mapping has no effect for principals that exist in the HDB, because
+enterprise principal names are always looked up by their first component (as if
+they were an ordinary principal name). This logic is instead useful when
+synthetic principals are enabled as we wish to avoid issuing tickets with a
+client name in a foreign Kerberos realm, as that would conflate GSS-API
+"realms" with Kerberos realms.
+
+A custom authorization plugin installed in `$prefix/lib/plugin/kdc` will
+replace this mapping and authorization logic. The plugin interface is defined in
+[`gss_preauth_authorizer_plugin.h`](../../../kdc/gss_preauth_authorizer_plugin.h)).
+
+### Anonymous authentication
+
+A further note on the interaction of anonymous GSS-API authentication and
+pre-authentication. Initiator contexts that set `GSS_C_ANON_FLAG` and a
+`GSS_C_NT_ANONYMOUS` name are mapped to the unauthenticated anonymous Kerberos
+principal, `WELLKNOWN/ANONYMOUS@WELLKNOWN:ANONYMOUS`. However, the local
+`WELLKNOWN/ANONYMOUS` HDB entry is used to perform any authorization decisions
+(as it would be for anonymous PKINIT). The AP-REP will contain the well-known
+anonymous realm.
+
+If `GSS_C_NT_ANONYMOUS` was set but a different name type was returned, then
+the initiator is treated as authenticated anonymous, and the client realm will
+be present in the AP-REP.
+
+The `request-anonymous` AP-REQ flag must also be set for GSS-API anonymous
+authentication to succeed.
diff --git a/third_party/heimdal/lib/gss_preauth/pa_client.c b/third_party/heimdal/lib/gss_preauth/pa_client.c
new file mode 100644
index 0000000..de2d7b5
--- /dev/null
+++ b/third_party/heimdal/lib/gss_preauth/pa_client.c
@@ -0,0 +1,252 @@
+/*
+ * Copyright (c) 2021, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <krb5_locl.h>
+#include <mech_locl.h>
+
+#include "gss-preauth-protos.h"
+#include "gss-preauth-private.h"
+
+static krb5_error_code
+pa_gss_acquire_initiator_cred(krb5_context context,
+ krb5_gss_init_ctx gssic,
+ const krb5_creds *kcred,
+ gss_cred_id_t *cred)
+{
+ krb5_error_code ret;
+
+ OM_uint32 major, minor;
+ gss_const_OID mech;
+ gss_OID_set_desc mechs;
+ gss_name_t initiator_name = GSS_C_NO_NAME;
+ OM_uint32 time_req;
+ krb5_timestamp now;
+
+ *cred = GSS_C_NO_CREDENTIAL;
+
+ mech = _krb5_init_creds_get_gss_mechanism(context, gssic);
+
+ mechs.count = 1;
+ mechs.elements = (gss_OID)mech;
+
+ ret = _krb5_gss_pa_unparse_name(context, kcred->client, &initiator_name);
+ if (ret)
+ return ret;
+
+ krb5_timeofday(context, &now);
+ if (kcred->times.endtime && kcred->times.endtime > now)
+ time_req = kcred->times.endtime - now;
+ else
+ time_req = GSS_C_INDEFINITE;
+
+ major = gss_acquire_cred(&minor, initiator_name, time_req, &mechs,
+ GSS_C_INITIATE, cred, NULL, NULL);
+ ret = _krb5_gss_map_error(major, minor);
+
+ gss_release_name(&major, &initiator_name);
+
+ return ret;
+}
+
+static krb5_error_code KRB5_LIB_CALL
+pa_gss_step(krb5_context context,
+ krb5_gss_init_ctx gssic,
+ const krb5_creds *kcred,
+ gss_ctx_id_t *ctx,
+ KDCOptions flags,
+ krb5_data *enc_as_req,
+ krb5_data *in,
+ krb5_data *out)
+{
+ krb5_error_code ret;
+ krb5_principal tgs_name = NULL;
+
+ OM_uint32 major, minor;
+ gss_cred_id_t cred;
+ gss_name_t target_name = GSS_C_NO_NAME;
+ OM_uint32 req_flags = GSS_C_MUTUAL_FLAG;
+ OM_uint32 ret_flags;
+ struct gss_channel_bindings_struct cb;
+ gss_buffer_desc input_token, output_token = GSS_C_EMPTY_BUFFER;
+
+ memset(&cb, 0, sizeof(cb));
+ krb5_data_zero(out);
+
+ if (flags.request_anonymous)
+ req_flags |= GSS_C_ANON_FLAG;
+
+ cred = (gss_cred_id_t)_krb5_init_creds_get_gss_cred(context, gssic);
+
+ if (cred == GSS_C_NO_CREDENTIAL) {
+ ret = pa_gss_acquire_initiator_cred(context, gssic, kcred, &cred);
+ if (ret)
+ goto out;
+
+ _krb5_init_creds_set_gss_cred(context, gssic, cred);
+ }
+
+ ret = krb5_make_principal(context, &tgs_name, kcred->server->realm,
+ KRB5_TGS_NAME, kcred->server->realm, NULL);
+ if (ret)
+ goto out;
+
+ ret = _krb5_gss_pa_unparse_name(context, tgs_name, &target_name);
+ if (ret)
+ goto out;
+
+ _krb5_gss_data_to_buffer(enc_as_req, &cb.application_data);
+ _krb5_gss_data_to_buffer(in, &input_token);
+
+ major = gss_init_sec_context(&minor,
+ cred,
+ ctx,
+ target_name,
+ (gss_OID)_krb5_init_creds_get_gss_mechanism(context, gssic),
+ req_flags,
+ GSS_C_INDEFINITE,
+ &cb,
+ &input_token,
+ NULL,
+ &output_token,
+ &ret_flags,
+ NULL);
+
+ _krb5_gss_buffer_to_data(&output_token, out);
+
+ if (major == GSS_S_COMPLETE) {
+ if ((ret_flags & GSS_C_MUTUAL_FLAG) == 0)
+ ret = KRB5_MUTUAL_FAILED;
+ else if ((ret_flags & req_flags) != req_flags)
+ ret = KRB5KDC_ERR_BADOPTION;
+ else
+ ret = 0;
+ } else
+ ret = _krb5_gss_map_error(major, minor);
+
+out:
+ gss_release_name(&minor, &target_name);
+ krb5_free_principal(context, tgs_name);
+
+ return ret;
+}
+
+static krb5_error_code KRB5_LIB_CALL
+pa_gss_finish(krb5_context context,
+ krb5_gss_init_ctx gssic,
+ const krb5_creds *kcred,
+ gss_ctx_id_t ctx,
+ krb5int32 nonce,
+ krb5_enctype enctype,
+ krb5_principal *client_p,
+ krb5_keyblock **reply_key_p)
+{
+ krb5_error_code ret;
+ krb5_principal client = NULL;
+ krb5_keyblock *reply_key = NULL;
+
+ OM_uint32 major, minor;
+ gss_name_t initiator_name = GSS_C_NO_NAME;
+
+ *client_p = NULL;
+ *reply_key_p = NULL;
+
+ major = gss_inquire_context(&minor,
+ ctx,
+ &initiator_name,
+ NULL, /* target_name */
+ NULL, /* lifetime_req */
+ NULL, /* mech_type */
+ NULL, /* ctx_flags */
+ NULL, /* locally_initiated */
+ NULL); /* open */
+
+ if (GSS_ERROR(major))
+ return _krb5_gss_map_error(major, minor);
+
+ ret = _krb5_gss_pa_parse_name(context, initiator_name, 0, &client);
+ if (ret)
+ goto out;
+
+ ret = _krb5_gss_pa_derive_key(context, ctx, nonce, enctype, &reply_key);
+ if (ret)
+ goto out;
+
+ *client_p = client;
+ client = NULL;
+
+ *reply_key_p = reply_key;
+ reply_key = NULL;
+
+out:
+ krb5_free_principal(context, client);
+ if (reply_key)
+ krb5_free_keyblock(context, reply_key);
+ gss_release_name(&minor, &initiator_name);
+
+ return ret;
+}
+
+static void KRB5_LIB_CALL
+pa_gss_delete_sec_context(krb5_context context,
+ krb5_gss_init_ctx gssic,
+ gss_ctx_id_t ctx)
+{
+ OM_uint32 minor;
+
+ gss_delete_sec_context(&minor, &ctx, GSS_C_NO_BUFFER);
+}
+
+static void KRB5_LIB_CALL
+pa_gss_release_cred(krb5_context context,
+ krb5_gss_init_ctx gssic,
+ gss_cred_id_t cred)
+{
+ OM_uint32 minor;
+
+ gss_release_cred(&minor, &cred);
+}
+
+krb5_error_code
+krb5_gss_set_init_creds(krb5_context context,
+ krb5_init_creds_context ctx,
+ gss_const_cred_id_t gss_cred,
+ gss_const_OID gss_mech)
+{
+ return _krb5_init_creds_init_gss(context,ctx,
+ pa_gss_step,
+ pa_gss_finish,
+ pa_gss_release_cred,
+ pa_gss_delete_sec_context,
+ gss_cred,
+ gss_mech,
+ 0);
+}
diff --git a/third_party/heimdal/lib/gss_preauth/pa_common.c b/third_party/heimdal/lib/gss_preauth/pa_common.c
new file mode 100644
index 0000000..00efde7
--- /dev/null
+++ b/third_party/heimdal/lib/gss_preauth/pa_common.c
@@ -0,0 +1,255 @@
+/*
+ * Copyright (c) 2021, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <krb5_locl.h>
+#include <mech_locl.h>
+#include <heimntlm.h>
+
+#include "gss-preauth-protos.h"
+#include "gss-preauth-private.h"
+
+krb5_error_code
+_krb5_gss_map_error(OM_uint32 major, OM_uint32 minor)
+{
+ krb5_error_code ret;
+
+ if (minor != 0)
+ return (krb5_error_code)minor;
+
+ switch (major) {
+ case GSS_S_COMPLETE:
+ ret = 0;
+ break;
+ case GSS_S_CONTINUE_NEEDED:
+ ret = HEIM_ERR_PA_CONTINUE_NEEDED;
+ break;
+ case GSS_S_BAD_NAME:
+ case GSS_S_BAD_NAMETYPE:
+ ret = KRB5_PRINC_NOMATCH;
+ break;
+ case GSS_S_NO_CRED:
+ ret = KRB5_CC_NOTFOUND;
+ break;
+ case GSS_S_BAD_MIC:
+ case GSS_S_DEFECTIVE_CREDENTIAL:
+ ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
+ break;
+ case GSS_S_FAILURE:
+ default:
+ ret = KRB5KDC_ERR_PREAUTH_FAILED;
+ break;
+ }
+
+ return ret;
+}
+
+krb5_error_code
+_krb5_gss_pa_derive_key(krb5_context context,
+ gss_ctx_id_t ctx,
+ krb5int32 nonce,
+ krb5_enctype enctype,
+ krb5_keyblock **keyblock)
+{
+ krb5_error_code ret;
+ u_char saltdata[12] = "KRB-GSS";
+ krb5_keyblock kdkey;
+ size_t keysize;
+
+ OM_uint32 major, minor;
+ gss_buffer_desc salt, dkey = GSS_C_EMPTY_BUFFER;
+
+ *keyblock = NULL;
+
+ ret = krb5_enctype_keysize(context, enctype, &keysize);
+ if (ret)
+ return ret;
+
+ saltdata[ 8] = (nonce >> 0 ) & 0xFF;
+ saltdata[ 9] = (nonce >> 8 ) & 0xFF;
+ saltdata[10] = (nonce >> 16) & 0xFF;
+ saltdata[11] = (nonce >> 24) & 0xFF;
+
+ salt.value = saltdata;
+ salt.length = sizeof(saltdata);
+
+ major = gss_pseudo_random(&minor, ctx, GSS_C_PRF_KEY_FULL,
+ &salt, keysize, &dkey);
+ if (GSS_ERROR(major))
+ return KRB5_PREAUTH_NO_KEY;
+
+ kdkey.keytype = enctype;
+ kdkey.keyvalue.data = dkey.value;
+ kdkey.keyvalue.length = dkey.length;
+
+ ret = krb5_copy_keyblock(context, &kdkey, keyblock);
+
+ if (dkey.value) {
+ memset_s(dkey.value, dkey.length, 0, dkey.length);
+ gss_release_buffer(&minor, &dkey);
+ }
+
+ return ret;
+}
+
+krb5_error_code
+_krb5_gss_pa_unparse_name(krb5_context context,
+ krb5_const_principal principal,
+ gss_name_t *namep)
+{
+ krb5_error_code ret;
+ char *name = NULL;
+
+ OM_uint32 major, minor;
+ gss_buffer_desc name_buf;
+
+ *namep = GSS_C_NO_NAME;
+
+ if (principal->name.name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
+ if (principal->name.name_string.len != 1)
+ return EINVAL;
+
+ name = principal->name.name_string.val[0];
+ } else {
+ ret = krb5_unparse_name(context, principal, &name);
+ if (ret)
+ return ret;
+ }
+
+ name_buf.length = strlen(name);
+ name_buf.value = name;
+
+ major = gss_import_name(&minor, &name_buf,
+ GSS_KRB5_NT_PRINCIPAL_NAME, namep);
+ if (major == GSS_S_BAD_NAMETYPE) {
+ gss_OID name_type = GSS_C_NO_OID;
+ int flags = 0;
+
+ if (principal->name.name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
+ name_type = GSS_C_NT_USER_NAME;
+ } else if (principal->name.name_type == KRB5_NT_PRINCIPAL) {
+ flags = KRB5_PRINCIPAL_UNPARSE_SHORT;
+ name_type = GSS_C_NT_USER_NAME;
+ } else if ((principal->name.name_type == KRB5_NT_SRV_HST ||
+ principal->name.name_type == KRB5_NT_SRV_INST) &&
+ principal->name.name_string.len == 2) {
+ flags = KRB5_PRINCIPAL_UNPARSE_NO_REALM;
+ name_type = GSS_C_NT_HOSTBASED_SERVICE;
+ }
+
+ if (flags) {
+ krb5_xfree(name);
+
+ ret = krb5_unparse_name_flags(context, principal, flags, &name);
+ if (ret)
+ return ret;
+
+ if (gss_oid_equal(name_type, GSS_C_NT_HOSTBASED_SERVICE)) {
+ char *inst = strchr(name, '/');
+ if (inst)
+ *inst = '@';
+ }
+
+ name_buf.length = strlen(name);
+ name_buf.value = name;
+ }
+
+ if (name_type)
+ major = gss_import_name(&minor, &name_buf, name_type, namep);
+ }
+
+ if (name != principal->name.name_string.val[0])
+ krb5_xfree(name);
+
+ return _krb5_gss_map_error(major, minor);
+}
+
+krb5_error_code
+_krb5_gss_pa_parse_name(krb5_context context,
+ gss_const_name_t name,
+ int flags,
+ krb5_principal *principal)
+{
+ krb5_error_code ret;
+ char *displayed_name0;
+
+ OM_uint32 major, minor;
+ gss_OID name_type = GSS_C_NO_OID;
+ gss_buffer_desc displayed_name = GSS_C_EMPTY_BUFFER;
+
+ major = gss_display_name(&minor, name, &displayed_name, &name_type);
+ if (GSS_ERROR(major))
+ return _krb5_gss_map_error(major, minor);
+
+ if (gss_oid_equal(name_type, GSS_C_NT_ANONYMOUS)) {
+ ret = krb5_make_principal(context, principal, KRB5_ANON_REALM,
+ KRB5_WELLKNOWN_NAME, KRB5_ANON_NAME, NULL);
+ if (ret == 0)
+ (*principal)->name.name_type = KRB5_NT_WELLKNOWN;
+ } else {
+ displayed_name0 = malloc(displayed_name.length + 1);
+ if (displayed_name0 == NULL)
+ return krb5_enomem(context);
+
+ memcpy(displayed_name0, displayed_name.value, displayed_name.length);
+ displayed_name0[displayed_name.length] = '\0';
+
+ ret = krb5_parse_name_flags(context, displayed_name0, flags, principal);
+ gss_release_buffer(&minor, &displayed_name);
+ free(displayed_name0);
+ }
+
+ gss_release_buffer(&minor, &displayed_name);
+
+ return ret;
+}
+
+void
+_krb5_gss_data_to_buffer(const krb5_data *data, gss_buffer_t buffer)
+{
+ if (data) {
+ buffer->length = data->length;
+ buffer->value = data->data;
+ } else {
+ _mg_buffer_zero(buffer);
+ }
+}
+
+void
+_krb5_gss_buffer_to_data(gss_const_buffer_t buffer, krb5_data *data)
+{
+ if (buffer) {
+ data->length = buffer->length;
+ data->data = buffer->value;
+ } else {
+ krb5_data_zero(data);
+ }
+}
diff --git a/third_party/heimdal/lib/gssapi/ChangeLog b/third_party/heimdal/lib/gssapi/ChangeLog
new file mode 100644
index 0000000..5c25d69
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ChangeLog
@@ -0,0 +1,2970 @@
+2008-08-14 Love Hornquist Astrand <lha@10a140laptop.local>
+
+ * krb5/accept_sec_context.c: If there is a initiator subkey, copy
+ that to acceptor subkey to match windows behavior. From Metze.
+
+2008-08-02 Love Hörnquist Åstrand <lha@h5l.org>
+
+ * ntlm/init_sec_context.c: Catch error
+
+ * krb5/inquire_sec_context_by_oid.c: Catch store failure.
+
+ * mech/gss_canonicalize_name.c: Not init m, return never
+ used (overwritten later).
+
+2008-07-25 Love Hörnquist Åstrand <lha@kth.se>
+
+ * ntlm/init_sec_context.c: Use krb5_cc_get_config.
+
+2008-07-25 Love Hörnquist Åstrand <lha@kth.se>
+
+ * krb5/init_sec_context.c: Match the orignal patch I got from
+ metze, seems that DCE-STYLE is even more weirer then what I though
+ when I merged the patch.
+
+2008-06-02 Love Hörnquist Åstrand <lha@kth.se>
+
+ * krb5/init_sec_context.c: Don't add asn1 wrapping to token when
+ using DCE_STYLE. Patch from Stefan Metzmacher.
+
+2008-05-27 Love Hörnquist Åstrand <lha@kth.se>
+
+ * ntlm/init_sec_context.c: use krb5_get_error_message
+
+2008-05-05 Love Hörnquist Åstrand <lha@kth.se>
+
+ * spnego/spnego_locl.h: Add back "mech/utils.h", its needed for
+ oid/buffer functions.
+
+2008-05-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * spnego: Changes from doug barton to make spnego indepedant of
+ the heimdal version of the plugin system.
+
+2008-04-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5: use DES_set_key_unchecked()
+
+2008-04-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * add __declspec() for windows.
+
+2008-04-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/import_sec_context.c: Use tmp to read ac->flags value to
+ avoid warning.
+
+2008-04-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_mech_switch.c: Use unsigned where appropriate.
+
+2008-03-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_context.c: Add test for gsskrb5_register_acceptor_identity.
+
+2008-03-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/init_sec_context.c (init_auth): use right variable to
+ detect if we want to free or not.
+
+2008-02-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add missing \
+
+ * Makefile.am: reshuffle depenencies
+
+ * Add flag to krb5 to not add GSS-API INT|CONF to the negotiation
+
+2008-02-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * make the SPNEGO mech store the error itself instead, works for
+ everything except other stackable mechs
+
+2008-02-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * spnego/init_sec_context.c (spnego_reply): if the reply token was
+ of length 0, make it the same as no token. Pointed out by Zeqing
+ Xia.
+
+ * krb5/acquire_cred.c (acquire_initiator_cred): handle the
+ credential cache better, use destroy/close when appriate and for
+ all cases. Thanks to Michael Allen for point out the memory-leak
+ that I also fixed.
+
+2008-02-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * spnego/accept_sec_context.c: Make error reporting somewhat more
+ correct for SPNEGO.
+
+2008-01-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_common.c: Improve the error message.
+
+2008-01-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/accept_sec_context.c: Avoid free-ing type1 message before
+ its allocated.
+
+2008-01-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_ntlm.c: Test source name (and make the acceptor in ntlm gss
+ mech useful).
+
+2007-12-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/init_sec_context.c: Don't confuse target name and source
+ name, make regressiont tests pass again.
+
+2007-12-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm: clean up name handling
+
+2007-12-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/init_sec_context.c: Use credential if it was passed in.
+
+ * ntlm/acquire_cred.c: Check if there is initial creds with
+ _gss_ntlm_get_user_cred().
+
+ * ntlm/init_sec_context.c: Add _gss_ntlm_get_user_info() that
+ return the user info so it can be used by external modules.
+
+ * ntlm/inquire_cred.c: use the right error code.
+
+ * ntlm/inquire_cred.c: Return GSS_C_NO_CREDENTIAL if there is no
+ credential, ntlm have (not yet) a default credential.
+
+ * mech/gss_release_oid_set.c: Avoid trying to deref NULL, from
+ Phil Fisher.
+
+2007-12-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_acquire_cred.c: Always try to fetch cred (even with
+ GSS_C_NO_NAME).
+
+2007-08-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_krb5.c: Readd gss_krb5_get_tkt_flags.
+
+2007-08-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * spnego/compat.c (_gss_spnego_internal_delete_sec_context):
+ release ctx->target_name too From Rafal Malinowski.
+
+2007-07-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_mech_switch.c: Don't try to do dlopen if system doesn't
+ have dlopen. From Rune of Chalmers.
+
+2007-07-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_duplicate_name.c: New signature of _gss_find_mn.
+
+ * mech/gss_init_sec_context.c: New signature of _gss_find_mn.
+
+ * mech/gss_acquire_cred.c: New signature of _gss_find_mn.
+
+ * mech/name.h: New signature of _gss_find_mn.
+
+ * mech/gss_canonicalize_name.c: New signature of _gss_find_mn.
+
+ * mech/gss_compare_name.c: New signature of _gss_find_mn.
+
+ * mech/gss_add_cred.c: New signature of _gss_find_mn.
+
+ * mech/gss_names.c (_gss_find_mn): Return an error code for
+ caller.
+
+ * spnego/accept_sec_context.c: remove checks that are done by the
+ previous function.
+
+ * Makefile.am: New library version.
+
+2007-07-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_oid_to_str.c: Refuse to print GSS_C_NULL_OID, from
+ Rafal Malinowski.
+
+ * spnego/spnego.asn1: Indent and make NegTokenInit and
+ NegTokenResp extendable.
+
+2007-06-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/inquire_cred.c: Implement _gss_ntlm_inquire_cred.
+
+ * mech/gss_display_status.c: Provide message for GSS_S_COMPLETE.
+
+ * mech/context.c: If the canned string is "", its no use to the
+ user, make it fall back to the default error string.
+
+2007-06-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_display_name.c (gss_display_name): no name ->
+ fail. From Rafal Malinswski.
+
+ * spnego/accept_sec_context.c: Wrap name in a spnego_name instead
+ of just a copy of the underlaying object. From Rafal Malinswski.
+
+ * spnego/accept_sec_context.c: Handle underlaying mech not
+ returning mn.
+
+ * mech/gss_accept_sec_context.c: Handle underlaying mech not
+ returning mn.
+
+ * spnego/accept_sec_context.c: Make sure src_name is always set to
+ GSS_C_NO_NAME when returning.
+
+ * krb5/acquire_cred.c (acquire_acceptor_cred): don't claim
+ everything is well on failure. From Phil Fisher.
+
+ * mech/gss_duplicate_name.c: catch error (and ignore it)
+
+ * ntlm/init_sec_context.c: Use heim_ntlm_calculate_ntlm2_sess.
+
+ * mech/gss_accept_sec_context.c: Only wrap the delegated cred if
+ we got a delegated mech cred. From Rafal Malinowski.
+
+ * spnego/accept_sec_context.c: Only wrap the delegated cred if we
+ are going to return it to the consumer. From Rafal Malinowski.
+
+ * spnego/accept_sec_context.c: Fixed memory leak pointed out by
+ Rafal Malinowski, also while here moved to use NegotiationToken
+ for decoding.
+
+2007-06-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/prf.c (_gsskrb5_pseudo_random): add missing break.
+
+ * krb5/release_name.c: Set *minor_status unconditionallty, its
+ done later anyway.
+
+ * spnego/accept_sec_context.c: Init get_mic to 0.
+
+ * mech/gss_set_cred_option.c: Free memory in failure case, found
+ by beam.
+
+ * mech/gss_inquire_context.c: Handle mech_type being NULL.
+
+ * mech/gss_inquire_cred_by_mech.c: Handle cred_name being NULL.
+
+ * mech/gss_krb5.c: Free memory in error case, found by beam.
+
+2007-06-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/inquire_context.c: Use ctx->gssflags for flags.
+
+ * krb5/display_name.c: Use KRB5_PRINCIPAL_UNPARSE_DISPLAY, this is
+ not ment for machine consumption.
+
+2007-06-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/digest.c (kdc_alloc): free memory on failure, pointed out
+ by Rafal Malinowski.
+
+ * ntlm/digest.c (kdc_destroy): free context when done, pointed out
+ by Rafal Malinowski.
+
+ * spnego/context_stubs.c (_gss_spnego_display_name): if input_name
+ is null, fail. From Rafal Malinowski.
+
+2007-06-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/digest.c: Free memory when done.
+
+2007-06-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_ntlm.c: Test both with and without keyex.
+
+ * ntlm/digest.c: If we didn't set session key, don't expect one
+ back.
+
+ * test_ntlm.c: Set keyex flag and calculate session key.
+
+2007-05-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * spnego/accept_sec_context.c: Use the return value before is
+ overwritten by later calls. From Rafal Malinowski
+
+ * krb5/release_cred.c: Give an minor_status argument to
+ gss_release_oid_set. From Rafal Malinowski
+
+2007-05-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/accept_sec_context.c: Catch errors and return the up the
+ stack.
+
+ * test_kcred.c: more testing of lifetimes
+
+2007-05-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Drop the gss oid_set function for the krb5 mech,
+ use the mech glue versions instead. Pointed out by Rafal
+ Malinowski.
+
+ * krb5: Use gss oid_set functions from mechglue
+
+2007-05-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/accept_sec_context.c: Set session key only if we are
+ returned a session key. Found by David Love.
+
+2007-05-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/prf.c: switched MIN to min to make compile on solaris,
+ pointed out by David Love.
+
+2007-05-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/inquire_cred_by_mech.c: Fill in all of the variables if
+ they are passed in. Pointed out by Phil Fisher.
+
+2007-05-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/inquire_cred.c: Fix copy and paste error, bug spotted by
+ from Phil Fisher.
+
+ * mech: dont keep track of gc_usage, just figure it out at
+ gss_inquire_cred() time
+
+ * mech/gss_mech_switch.c (add_builtin): ok for
+ __gss_mech_initialize() to return NULL
+
+ * test_kcred.c: more correct tests
+
+ * spnego/cred_stubs.c (gss_inquire_cred*): wrap the name with a
+ spnego_name.
+
+ * ntlm/inquire_cred.c: make ntlm gss_inquire_cred fail for now,
+ need to find default cred and friends.
+
+ * krb5/inquire_cred_by_mech.c: reimplement
+
+2007-05-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/acquire_cred.c: drop unused variable.
+
+ * ntlm/acquire_cred.c: Reimplement.
+
+ * Makefile.am: add ntlm/digest.c
+
+ * ntlm: split out backend ntlm server processing
+
+2007-04-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/delete_sec_context.c (_gss_ntlm_delete_sec_context): free
+ credcache when done
+
+2007-04-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/init_sec_context.c: ntlm-key credential entry is prefix with @
+
+ * ntlm/init_sec_context.c (get_user_ccache): pick up the ntlm
+ creds from the krb5 credential cache.
+
+2007-04-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/delete_sec_context.c: free the key stored in the context
+
+ * ntlm/ntlm.h: switch password for a key
+
+ * test_oid.c: Switch oid to one that is exported.
+
+2007-04-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/init_sec_context.c: move where hash is calculated to make
+ it easier to add ccache support.
+
+ * Makefile.am: Add version-script.map to EXTRA_DIST.
+
+2007-04-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Unconfuse newer versions of automake that doesn't
+ know the diffrence between depenences and setting variables. foo:
+ vs foo=.
+
+ * test_ntlm.c: delete sec context when done.
+
+ * version-script.map: export more symbols.
+
+ * Makefile.am: add version script if ld supports it
+
+ * version-script.map: add version script if ld supports it
+
+2007-04-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: test_acquire_cred need test_common.[ch]
+
+ * test_acquire_cred.c: add more test options.
+
+ * krb5/external.c: add GSS_KRB5_CCACHE_NAME_X
+
+ * gssapi/gssapi_krb5.h: add GSS_KRB5_CCACHE_NAME_X
+
+ * krb5/set_sec_context_option.c: refactor code, implement
+ GSS_KRB5_CCACHE_NAME_X
+
+ * mech/gss_krb5.c: reimplement gss_krb5_ccache_name
+
+2007-04-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * spnego/cred_stubs.c: Need to import spnego name before we can
+ use it as a gss_name_t.
+
+ * test_acquire_cred.c: use this test as part of the regression
+ suite.
+
+ * mech/gss_acquire_cred.c (gss_acquire_cred): dont init
+ cred->gc_mc every time in the loop.
+
+2007-04-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add test_common.h
+
+2007-02-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: Add link for
+ gsskrb5_register_acceptor_identity.
+
+2007-02-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/copy_ccache.c: Try to leak less memory in the failure case.
+
+2007-01-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_display_status.c: Use right printf formater.
+
+ * test_*.[ch]: split out the error printing function and try to
+ return better errors
+
+2007-01-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/init_sec_context.c: revert 1.75: (init_auth): only turn on
+ GSS_C_CONF_FLAG and GSS_C_INT_FLAG if the caller requseted it.
+
+ This is because Kerberos always support INT|CONF, matches behavior
+ with MS and MIT. The creates problems for the GSS-SPNEGO mech.
+
+2007-01-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/prf.c: constrain desired_output_len
+
+ * krb5/external.c (krb5_mech): add _gsskrb5_pseudo_random
+
+ * mech/gss_pseudo_random.c: Catch error from underlaying mech on
+ failure.
+
+ * Makefile.am: Add krb5/prf.c
+
+ * krb5/prf.c: gss_pseudo_random for krb5
+
+ * test_context.c: Checks for gss_pseudo_random.
+
+ * krb5/gkrb5_err.et: add KG_INPUT_TOO_LONG
+
+ * Makefile.am: Add mech/gss_pseudo_random.c
+
+ * gssapi/gssapi.h: try to load pseudo_random
+
+ * mech/gss_mech_switch.c: try to load pseudo_random
+
+ * mech/gss_pseudo_random.c: Add gss_pseudo_random.
+
+ * gssapi_mech.h: Add hook for gm_pseudo_random.
+
+2007-01-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_context.c: Don't assume bufer from gss_display_status is
+ ok.
+
+ * mech/gss_wrap_size_limit.c: Reset out variables.
+
+ * mech/gss_wrap.c: Reset out variables.
+
+ * mech/gss_verify_mic.c: Reset out variables.
+
+ * mech/gss_utils.c: Reset out variables.
+
+ * mech/gss_release_oid_set.c: Reset out variables.
+
+ * mech/gss_release_cred.c: Reset out variables.
+
+ * mech/gss_release_buffer.c: Reset variables.
+
+ * mech/gss_oid_to_str.c: Reset out variables.
+
+ * mech/gss_inquire_sec_context_by_oid.c: Fix reset out variables.
+
+ * mech/gss_mech_switch.c: Reset out variables.
+
+ * mech/gss_inquire_sec_context_by_oid.c: Reset out variables.
+
+ * mech/gss_inquire_names_for_mech.c: Reset out variables.
+
+ * mech/gss_inquire_cred_by_oid.c: Reset out variables.
+
+ * mech/gss_inquire_cred_by_oid.c: Reset out variables.
+
+ * mech/gss_inquire_cred_by_mech.c: Reset out variables.
+
+ * mech/gss_inquire_cred.c: Reset out variables, fix memory leak.
+
+ * mech/gss_inquire_context.c: Reset out variables.
+
+ * mech/gss_init_sec_context.c: Zero out outbuffer on failure.
+
+ * mech/gss_import_name.c: Reset out variables.
+
+ * mech/gss_import_name.c: Reset out variables.
+
+ * mech/gss_get_mic.c: Reset out variables.
+
+ * mech/gss_export_name.c: Reset out variables.
+
+ * mech/gss_encapsulate_token.c: Reset out variables.
+
+ * mech/gss_duplicate_oid.c: Reset out variables.
+
+ * mech/gss_duplicate_oid.c: Reset out variables.
+
+ * mech/gss_duplicate_name.c: Reset out variables.
+
+ * mech/gss_display_status.c: Reset out variables.
+
+ * mech/gss_display_name.c: Reset out variables.
+
+ * mech/gss_delete_sec_context.c: Reset out variables using propper
+ macros.
+
+ * mech/gss_decapsulate_token.c: Reset out variables using propper
+ macros.
+
+ * mech/gss_add_cred.c: Reset out variables.
+
+ * mech/gss_acquire_cred.c: Reset out variables.
+
+ * mech/gss_accept_sec_context.c: Reset out variables using propper
+ macros.
+
+ * mech/gss_init_sec_context.c: Reset out variables.
+
+ * mech/mech_locl.h (_mg_buffer_zero): new macro that zaps a
+ gss_buffer_t
+
+2007-01-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech: sprinkel _gss_mg_error
+
+ * mech/gss_display_status.c (gss_display_status): use
+ _gss_mg_get_error to fetch the error from underlaying mech, if it
+ failes, let do the regular dance for GSS-CODE version and a
+ generic print-the-error code for MECH-CODE.
+
+ * mech/gss_oid_to_str.c: Don't include the NUL in the length of
+ the string.
+
+ * mech/context.h: Protoypes for _gss_mg_.
+
+ * mech/context.c: Glue to catch the error from the lower gss-api
+ layer and save that for later so gss_display_status() can show the
+ error.
+
+ * gss.c: Detect NTLM.
+
+2007-01-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_accept_sec_context.c: spelling
+
+2007-01-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Include build (private) prototypes header files.
+
+ * Makefile.am (ntlmsrc): add ntlm/ntlm-private.h
+
+2006-12-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/accept_sec_context.c: Pass signseal argument to
+ _gss_ntlm_set_key.
+
+ * ntlm/init_sec_context.c: Pass signseal argument to
+ _gss_ntlm_set_key.
+
+ * ntlm/crypto.c (_gss_ntlm_set_key): add signseal argument
+
+ * test_ntlm.c: add ntlmv2 test
+
+ * ntlm/ntlm.h: break out struct ntlmv2_key;
+
+ * ntlm/crypto.c (_gss_ntlm_set_key): set ntlm v2 keys.
+
+ * ntlm/accept_sec_context.c: Set dummy ntlmv2 keys and Check TI.
+
+ * ntlm/ntlm.h: NTLMv2 keys.
+
+ * ntlm/crypto.c: NTLMv2 sign and verify.
+
+2006-12-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/accept_sec_context.c: Don't send targetinfo now.
+
+ * ntlm/init_sec_context.c: Build ntlmv2 answer buffer.
+
+ * ntlm/init_sec_context.c: Leak less memory.
+
+ * ntlm/init_sec_context.c: Announce that we support key exchange.
+
+ * ntlm/init_sec_context.c: Add NTLM_NEG_NTLM2_SESSION, NTLMv2
+ session security (disable because missing sign and seal).
+
+2006-12-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/accept_sec_context.c: split RC4 send and recv keystreams
+
+ * ntlm/init_sec_context.c: split RC4 send and recv keystreams
+
+ * ntlm/ntlm.h: split RC4 send and recv keystreams
+
+ * ntlm/crypto.c: Implement SEAL.
+
+ * ntlm/crypto.c: move gss_wrap/gss_unwrap here
+
+ * test_context.c: request INT and CONF from the gss layer, test
+ get and verify MIC.
+
+ * ntlm/ntlm.h: add crypto bits.
+
+ * ntlm/accept_sec_context.c: Save session master key.
+
+ * Makefile.am: Move get and verify mic to the same file (crypto.c)
+ since they share code.
+
+ * ntlm/crypto.c: Move get and verify mic to the same file since
+ they share code, implement NTLM v1 and dummy signatures.
+
+ * ntlm/init_sec_context.c: pass on GSS_C_CONF_FLAG and
+ GSS_C_INTEG_FLAG, save the session master key
+
+ * spnego/accept_sec_context.c: try using gss_accept_sec_context()
+ on the opportunistic token instead of guessing the acceptor name
+ and do gss_acquire_cred, this make SPNEGO work like before.
+
+2006-12-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/init_sec_context.c: Calculate the NTLM version 1 "master"
+ key.
+
+ * spnego/accept_sec_context.c: Resurect negHints for the acceptor
+ sends first packet.
+
+ * Makefile.am: Add "windows" versions of the NegTokenInitWin and
+ friends.
+
+ * test_context.c: add --wrapunwrap flag
+
+ * spnego/compat.c: move _gss_spnego_indicate_mechtypelist() to
+ compat.c, use the sequence types of MechTypeList, make
+ add_mech_type() static.
+
+ * spnego/accept_sec_context.c: move
+ _gss_spnego_indicate_mechtypelist() to compat.c
+
+ * Makefile.am: Generate sequence code for MechTypeList
+
+ * spnego: check that the generated acceptor mechlist is acceptable too
+
+ * spnego/init_sec_context.c: Abstract out the initiator filter
+ function, it will be needed for the acceptor too.
+
+ * spnego/accept_sec_context.c: Abstract out the initiator filter
+ function, it will be needed for the acceptor too. Remove negHints.
+
+ * test_context.c: allow asserting return mech
+
+ * ntlm/accept_sec_context.c: add _gss_ntlm_allocate_ctx
+
+ * ntlm/acquire_cred.c: Check that the KDC seem to there and
+ answering us, we can't do better then that wen checking if we will
+ accept the credential.
+
+ * ntlm/get_mic.c: return GSS_S_UNAVAILABLE
+
+ * mech/utils.h: add _gss_free_oid, reverse of _gss_copy_oid
+
+ * mech/gss_utils.c: add _gss_free_oid, reverse of _gss_copy_oid
+
+ * spnego/spnego.asn1: Its very sad, but NegHints its are not part
+ of the NegTokenInit, this makes SPNEGO acceptor life a lot harder.
+
+ * spnego: try harder to handle names better. handle missing
+ acceptor and initator creds better (ie dont propose/accept mech
+ that there are no credentials for) split NegTokenInit and
+ NegTokenResp in acceptor
+
+2006-12-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/import_name.c: Allocate the buffer from the right length.
+
+2006-12-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm/init_sec_context.c (init_sec_context): Tell the other side
+ what domain we think we are talking to.
+
+ * ntlm/delete_sec_context.c: free username and password
+
+ * ntlm/release_name.c (_gss_ntlm_release_name): free name.
+
+ * ntlm/import_name.c (_gss_ntlm_import_name): add support for
+ GSS_C_NT_HOSTBASED_SERVICE names
+
+ * ntlm/ntlm.h: Add ntlm_name.
+
+ * test_context.c: allow testing of ntlm.
+
+ * gssapi_mech.h: add __gss_ntlm_initialize
+
+ * ntlm/accept_sec_context.c (handle_type3): verify that the kdc
+ approved of the ntlm exchange too
+
+ * mech/gss_mech_switch.c: Add the builtin ntlm mech
+
+ * test_ntlm.c: NTLM test app.
+
+ * mech/gss_accept_sec_context.c: Add detection of NTLMSSP.
+
+ * gssapi/gssapi.h: add ntlm mech oid
+
+ * ntlm/external.c: Switch OID to the ms ntlmssp oid
+
+ * Makefile.am: Add ntlm gss-api module.
+
+ * ntlm/accept_sec_context.c: Catch more error errors.
+
+ * ntlm/accept_sec_context.c: Check after a credential to use.
+
+2006-12-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/set_sec_context_option.c (GSS_KRB5_SET_DEFAULT_REALM_X):
+ don't fail on success. Bug report from Stefan Metzmacher.
+
+2006-12-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/init_sec_context.c (init_auth): only turn on
+ GSS_C_CONF_FLAG and GSS_C_INT_FLAG if the caller requseted it.
+ From Stefan Metzmacher.
+
+2006-12-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am (libgssapi_la_OBJECTS): depends on gssapi_asn1.h
+ spnego_asn1.h.
+
+2006-11-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/acquire_cred.c: Make krb5_get_init_creds_opt_free take a
+ context argument.
+
+2006-11-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_context.c: Test that token keys are the same, return
+ actual_mech.
+
+2006-11-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * spnego/spnego_locl.h: Make bitfields unsigned, add maybe_open.
+
+ * spnego/accept_sec_context.c: Use ASN.1 encoder functions to
+ encode CHOICE structure now that we can handle it.
+
+ * spnego/init_sec_context.c: Use ASN.1 encoder functions to encode
+ CHOICE structure now that we can handle it.
+
+ * spnego/accept_sec_context.c (_gss_spnego_accept_sec_context):
+ send back ad accept_completed when the security context is ->open,
+ w/o this the client doesn't know that the server have completed
+ the transaction.
+
+ * test_context.c: Add delegate flag and check that the delegated
+ cred works.
+
+ * spnego/init_sec_context.c: Keep track of the opportunistic token
+ in the inital message, it might be a complete gss-api context, in
+ that case we'll get back accept_completed without any token. With
+ this change, krb5 w/o mutual authentication works.
+
+ * spnego/accept_sec_context.c: Use ASN.1 encoder functions to
+ encode CHOICE structure now that we can handle it.
+
+ * spnego/accept_sec_context.c: Filter out SPNEGO from the out
+ supported mechs list and make sure we don't select that for the
+ preferred mechamism.
+
+2006-11-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_init_sec_context.c (_gss_mech_cred_find): break out the
+ cred finding to its own function
+
+ * krb5/wrap.c: Better error strings, from Andrew Bartlet.
+
+2006-11-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_context.c: Create our own krb5_context.
+
+ * krb5: Switch from using a specific error message context in the
+ TLS to have a whole krb5_context in TLS. This have some
+ interestion side-effekts for the configruration setting options
+ since they operate on per-thread basis now.
+
+ * mech/gss_set_cred_option.c: When calling ->gm_set_cred_option
+ and checking for success, use GSS_S_COMPLETE. From Andrew Bartlet.
+
+2006-11-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Help solaris make even more.
+
+ * Makefile.am: Help solaris make.
+
+2006-11-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: remove include $(srcdir)/Makefile-digest.am for now
+
+ * mech/gss_accept_sec_context.c: Try better guessing what is mech
+ we are going to select by looking harder at the input_token, idea
+ from Luke Howard's mechglue branch.
+
+ * Makefile.am: libgssapi_la_OBJECTS: add depency on gkrb5_err.h
+
+ * gssapi/gssapi_krb5.h: add GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X
+
+ * mech/gss_krb5.c: implement gss_krb5_set_allowable_enctypes
+
+ * gssapi/gssapi.h: GSS_KRB5_S_
+
+ * krb5/gsskrb5_locl.h: Include <gkrb5_err.h>.
+
+ * gssapi/gssapi_krb5.h: Add gss_krb5_set_allowable_enctypes.
+
+ * Makefile.am: Build and install gkrb5_err.h
+
+ * krb5/gkrb5_err.et: Move the GSS_KRB5_S error here.
+
+2006-11-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_krb5.c: Add gsskrb5_set_default_realm.
+
+ * krb5/set_sec_context_option.c: Support
+ GSS_KRB5_SET_DEFAULT_REALM_X.
+
+ * gssapi/gssapi_krb5.h: add GSS_KRB5_SET_DEFAULT_REALM_X
+
+ * krb5/external.c: add GSS_KRB5_SET_DEFAULT_REALM_X
+
+2006-11-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_context.c: rename krb5_[gs]et_time_wrap to
+ krb5_[gs]et_max_time_skew
+
+ * krb5/copy_ccache.c: _gsskrb5_extract_authz_data_from_sec_context
+ no longer used, bye bye
+
+ * mech/gss_krb5.c: No depenency of the krb5 gssapi mech.
+
+ * mech/gss_krb5.c (gsskrb5_extract_authtime_from_sec_context): use
+ _gsskrb5_decode_om_uint32. From Andrew Bartlet.
+
+ * mech/gss_krb5.c: Add dummy gss_krb5_set_allowable_enctypes for
+ now.
+
+ * spnego/spnego_locl.h: Include <roken.h> for compatiblity.
+
+ * krb5/arcfour.c: Use IS_DCE_STYLE flag. There is no padding in
+ DCE-STYLE, don't try to use to. From Andrew Bartlett.
+
+ * test_context.c: test wrap/unwrap, add flag for dce-style and
+ mutual auth, also support multi-roundtrip sessions
+
+ * krb5/gsskrb5_locl.h: Add IS_DCE_STYLE macro.
+
+ * krb5/accept_sec_context.c (gsskrb5_acceptor_start): use
+ krb5_rd_req_ctx
+
+ * mech/gss_krb5.c (gsskrb5_get_subkey): return the per message
+ token subkey
+
+ * krb5/inquire_sec_context_by_oid.c: check if there is any key at
+ all
+
+2006-11-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/inquire_sec_context_by_oid.c: Set more error strings, use
+ right enum for acceptor subkey. From Andrew Bartlett.
+
+2006-11-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_context.c: Test gsskrb5_extract_service_keyblock, needed in
+ PAC valication. From Andrew Bartlett
+
+ * mech/gss_krb5.c: Add gsskrb5_extract_authz_data_from_sec_context
+ and keyblock extraction functions.
+
+ * gssapi/gssapi_krb5.h: Add extraction of keyblock function, from
+ Andrew Bartlett.
+
+ * krb5/external.c: Add GSS_KRB5_GET_SERVICE_KEYBLOCK_X
+
+2006-11-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_context.c: Rename various routines and constants from
+ canonize to canonicalize. From Andrew Bartlett
+
+ * mech/gss_krb5.c: Rename various routines and constants from
+ canonize to canonicalize. From Andrew Bartlett
+
+ * krb5/set_sec_context_option.c: Rename various routines and
+ constants from canonize to canonicalize. From Andrew Bartlett
+
+ * krb5/external.c: Rename various routines and constants from
+ canonize to canonicalize. From Andrew Bartlett
+
+ * gssapi/gssapi_krb5.h: Rename various routines and constants from
+ canonize to canonicalize. From Andrew Bartlett
+
+2006-10-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/accept_sec_context.c (gsskrb5_accept_delegated_token): need
+ to free ccache
+
+2006-10-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_context.c (loop): free target_name
+
+ * mech/gss_accept_sec_context.c: SLIST_INIT the ->gc_mc'
+
+ * mech/gss_acquire_cred.c : SLIST_INIT the ->gc_mc'
+
+ * krb5/init_sec_context.c: Avoid leaking memory.
+
+ * mech/gss_buffer_set.c (gss_release_buffer_set): don't leak the
+ ->elements memory.
+
+ * test_context.c: make compile
+
+ * krb5/cfx.c (_gssapi_verify_mic_cfx): always free crypto context.
+
+ * krb5/set_cred_option.c (import_cred): free sp
+
+2006-10-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_add_oid_set_member.c: Use old implementation of
+ gss_add_oid_set_member, it leaks less memory.
+
+ * krb5/test_cfx.c: free krb5_crypto.
+
+ * krb5/test_cfx.c: free krb5_context
+
+ * mech/gss_release_name.c (gss_release_name): free input_name
+ it-self.
+
+2006-10-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_context.c: Call setprogname.
+
+ * mech/gss_krb5.c: Add gsskrb5_extract_authtime_from_sec_context.
+
+ * gssapi/gssapi_krb5.h: add
+ gsskrb5_extract_authtime_from_sec_context
+
+2006-10-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/inquire_sec_context_by_oid.c: Add get_authtime.
+
+ * krb5/external.c: add GSS_KRB5_GET_AUTHTIME_X
+
+ * gssapi/gssapi_krb5.h: add GSS_KRB5_GET_AUTHTIME_X
+
+ * krb5/set_sec_context_option.c: Implement GSS_KRB5_SEND_TO_KDC_X.
+
+ * mech/gss_krb5.c: Add gsskrb5_set_send_to_kdc
+
+ * gssapi/gssapi_krb5.h: Add GSS_KRB5_SEND_TO_KDC_X and
+ gsskrb5_set_send_to_kdc
+
+ * krb5/external.c: add GSS_KRB5_SEND_TO_KDC_X
+
+ * Makefile.am: more files
+
+2006-10-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: remove spnego/gssapi_spnego.h, its now in gssapi/
+
+ * test_context.c: Allow specifing mech.
+
+ * krb5/external.c: add GSS_SASL_DIGEST_MD5_MECHANISM (for now)
+
+ * gssapi/gssapi.h: Rename GSS_DIGEST_MECHANISM to
+ GSS_SASL_DIGEST_MD5_MECHANISM
+
+2006-10-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gssapi.asn1: Make it into a heim_any_set, its doesn't
+ except a tag.
+
+ * mech/gssapi.asn1: GSSAPIContextToken is IMPLICIT SEQUENCE
+
+ * gssapi/gssapi_krb5.h: add GSS_KRB5_GET_ACCEPTOR_SUBKEY_X
+
+ * krb5/external.c: Add GSS_KRB5_GET_ACCEPTOR_SUBKEY_X.
+
+ * gssapi/gssapi_krb5.h: add GSS_KRB5_GET_INITIATOR_SUBKEY_X and
+ GSS_KRB5_GET_SUBKEY_X
+
+ * krb5/external.c: add GSS_KRB5_GET_INITIATOR_SUBKEY_X,
+ GSS_KRB5_GET_SUBKEY_X
+
+2006-10-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_context.c: Support switching on name type oid's
+
+ * test_context.c: add test for dns canon flag
+
+ * mech/gss_krb5.c: Add gsskrb5_set_dns_canonlize.
+
+ * gssapi/gssapi_krb5.h: remove gss_krb5_compat_des3_mic
+
+ * gssapi/gssapi_krb5.h: Add gsskrb5_set_dns_canonlize.
+
+ * krb5/set_sec_context_option.c: implement
+ GSS_KRB5_SET_DNS_CANONIZE_X
+
+ * gssapi/gssapi_krb5.h: add GSS_KRB5_SET_DNS_CANONIZE_X
+
+ * krb5/external.c: add GSS_KRB5_SET_DNS_CANONIZE_X
+
+ * mech/gss_krb5.c: add bits to make lucid context work
+
+2006-10-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_oid_to_str.c: Prefix der primitives with der_.
+
+ * krb5/inquire_sec_context_by_oid.c: Prefix der primitives with
+ der_.
+
+ * krb5/encapsulate.c: Prefix der primitives with der_.
+
+ * mech/gss_oid_to_str.c: New der_print_heim_oid signature.
+
+2006-10-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add test_context
+
+ * krb5/inquire_sec_context_by_oid.c: Make it work.
+
+ * test_oid.c: Test lucid oid.
+
+ * gssapi/gssapi.h: Add OM_uint64_t.
+
+ * krb5/inquire_sec_context_by_oid.c: Add lucid interface.
+
+ * krb5/external.c: Add lucid interface, renumber oids to my
+ delegated space.
+
+ * mech/gss_krb5.c: Add lucid interface.
+
+ * gssapi/gssapi_krb5.h: Add lucid interface.
+
+ * spnego/spnego_locl.h: Maybe include <netdb.h>.
+
+2006-10-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_mech_switch.c: define RTLD_LOCAL to 0 if not defined.
+
+2006-10-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: install gssapi_krb5.H and gssapi_spnego.h
+
+ * gssapi/gssapi_krb5.h: Move krb5 stuff to <gssapi/gssapi_krb5.h>.
+
+ * gssapi/gssapi.h: Move krb5 stuff to <gssapi/gssapi_krb5.h>.
+
+ * Makefile.am: Drop some -I no longer needed.
+
+ * gssapi/gssapi_spnego.h: Move gssapi_spengo.h over here.
+
+ * krb5: reference all include files using 'krb5/'
+
+2006-10-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi.h: Add file inclusion protection.
+
+ * gssapi/gssapi.h: Correct header file inclusion protection.
+
+ * gssapi/gssapi.h: Move the gssapi.h from lib/gssapi/ to
+ lib/gssapi/gssapi/ to please automake.
+
+ * spnego/spnego_locl.h: Maybe include <sys/types.h>.
+
+ * mech/mech_locl.h: Include <roken.h>.
+
+ * Makefile.am: split build files into dist_ and noinst_ SOURCES
+
+2006-10-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss.c: #if 0 out unused code.
+
+ * mech/gss_mech_switch.c: Cast argument to ctype(3) functions
+ to (unsigned char).
+
+2006-10-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/name.h: remove <sys/queue.h>
+
+ * mech/mech_switch.h: remove <sys/queue.h>
+
+ * mech/cred.h: remove <sys/queue.h>
+
+2006-10-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/arcfour.c: Thinker more with header lengths.
+
+ * krb5/arcfour.c: Improve the calcucation of header
+ lengths. DCE-STYLE data is also padded so remove if (1 || ...)
+ code.
+
+ * krb5/wrap.c (_gsskrb5_wrap_size_limit): use
+ _gssapi_wrap_size_arcfour for arcfour
+
+ * krb5/arcfour.c: Move _gssapi_wrap_size_arcfour here.
+
+ * Makefile.am: Split all mech to diffrent mechsrc variables.
+
+ * spnego/context_stubs.c: Make internal function static (and
+ rename).
+
+2006-10-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/inquire_cred.c: Fix "if (x) lock(y)" bug. From Harald
+ Barth.
+
+ * spnego/spnego_locl.h: Include <sys/param.h> for MAXHOSTNAMELEN.
+
+2006-09-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/arcfour.c: Add wrap support, interrop with itself but not
+ w2k3s-sp1
+
+ * krb5/gsskrb5_locl.h: move the arcfour specific stuff to the
+ arcfour header.
+
+ * krb5/arcfour.c: Support DCE-style unwrap, tested with
+ w2k3server-sp1.
+
+ * mech/gss_accept_sec_context.c (gss_accept_sec_context): if the
+ token doesn't start with [APPLICATION 0] SEQUENCE, lets assume its
+ a DCE-style kerberos 5 connection. XXX this needs to be made
+ better in cause we get another GSS-API protocol violating
+ protocol. It should be possible to detach the Kerberos DCE-style
+ since it starts with a AP-REQ PDU, but that have to wait for now.
+
+2006-09-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi.h: Add GSS_C flags from
+ draft-brezak-win2k-krb-rc4-hmac-04.txt.
+
+ * krb5/delete_sec_context.c: Free service_keyblock and fwd_data,
+ indent.
+
+ * krb5/accept_sec_context.c: Merge of the acceptor part from the
+ samba patch by Stefan Metzmacher and Andrew Bartlet.
+
+ * krb5/init_sec_context.c: Add GSS_C_DCE_STYLE.
+
+ * krb5/{init_sec_context.c,gsskrb5_locl.h}: merge most of the
+ initiator part from the samba patch by Stefan Metzmacher and
+ Andrew Bartlet (still missing DCE/RPC support)
+
+2006-08-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss.c (help): use sl_slc_help().
+
+2006-07-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss-commands.in: rename command to supported-mechanisms
+
+ * Makefile.am: Make gss objects depend on the slc built
+ gss-commands.h
+
+2006-07-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss-commands.in: add slc commands for gss
+
+ * krb5/gsskrb5_locl.h: Remove dup prototype of _gsskrb5_init()
+
+ * Makefile.am: Add test_cfx
+
+ * krb5/external.c: add GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X
+
+ * krb5/set_sec_context_option.c: catch
+ GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X
+
+ * krb5/accept_sec_context.c: reimplement
+ gsskrb5_register_acceptor_identity
+
+ * mech/gss_krb5.c: implement gsskrb5_register_acceptor_identity
+
+ * mech/gss_inquire_mechs_for_name.c: call _gss_load_mech
+
+ * mech/gss_inquire_cred.c (gss_inquire_cred): call _gss_load_mech
+
+ * mech/gss_mech_switch.c: Make _gss_load_mech() atomic and run
+ only once, this have the side effect that _gss_mechs and
+ _gss_mech_oids is only initialized once, so if just the users of
+ these two global variables calls _gss_load_mech() first, it will
+ act as a barrier and make sure the variables are never changed and
+ we don't need to lock them.
+
+ * mech/utils.h: no need to mark functions extern.
+
+ * mech/name.h: no need to mark _gss_find_mn extern.
+
+2006-07-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/cfx.c: Redo the wrap length calculations.
+
+ * krb5/test_cfx.c: test max_wrap_size in cfx.c
+
+ * mech/gss_display_status.c: Handle more error codes.
+
+2006-07-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/mech_locl.h: Include <krb5-types.h> and "mechqueue.h"
+
+ * mech/mechqueue.h: Add SLIST macros.
+
+ * krb5/inquire_context.c: Don't free return values on success.
+
+ * krb5/inquire_cred.c (_gsskrb5_inquire_cred): When cred provided
+ is the default cred, acquire the acceptor cred and initator cred
+ in two diffrent steps and then query them for the information,
+ this way, the code wont fail if there are no keytab, but there is
+ a credential cache.
+
+ * mech/gss_inquire_cred.c: move the check if we found any cred
+ where it matter for both cases
+ (default cred and provided cred)
+
+ * mech/gss_init_sec_context.c: If the desired mechanism can't
+ convert the name to a MN, fail with GSS_S_BAD_NAME rather then a
+ NULL de-reference.
+
+2006-07-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * spnego/external.c: readd gss_spnego_inquire_names_for_mech
+
+ * spnego/spnego_locl.h: reimplement
+ gss_spnego_inquire_names_for_mech add support function
+ _gss_spnego_supported_mechs
+
+ * spnego/context_stubs.h: reimplement
+ gss_spnego_inquire_names_for_mech add support function
+ _gss_spnego_supported_mechs
+
+ * spnego/context_stubs.c: drop gss_spnego_indicate_mechs
+
+ * mech/gss_indicate_mechs.c: if the underlaying mech doesn't
+ support gss_indicate_mechs, use the oid in the mechswitch
+ structure
+
+ * spnego/external.c: let the mech glue layer implement
+ gss_indicate_mechs
+
+ * spnego/cred_stubs.c (gss_spnego_acquire_cred): don't care about
+ desired_mechs, get our own list with indicate_mechs and remove
+ ourself.
+
+2006-07-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * spnego/external.c: remove gss_spnego_inquire_names_for_mech, let
+ the mechglue layer implement it
+
+ * spnego/context_stubs.c: remove gss_spnego_inquire_names_for_mech, let
+ the mechglue layer implement it
+
+ * spnego/spnego_locl.c: remove gss_spnego_inquire_names_for_mech, let
+ the mechglue layer implement it
+
+2006-07-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_set_cred_option.c: fix argument to gss_release_cred
+
+2006-06-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/init_sec_context.c: Make work on compilers that are
+ somewhat more picky then gcc4 (like gcc2.95)
+
+ * krb5/init_sec_context.c (do_delegation): use KDCOptions2int to
+ convert fwd_flags to an integer, since otherwise int2KDCOptions in
+ krb5_get_forwarded_creds wont do the right thing.
+
+ * mech/gss_set_cred_option.c (gss_set_cred_option): free memory on
+ failure
+
+ * krb5/set_sec_context_option.c (_gsskrb5_set_sec_context_option):
+ init global kerberos context
+
+ * krb5/set_cred_option.c (_gsskrb5_set_cred_option): init global
+ kerberos context
+
+ * mech/gss_accept_sec_context.c: Insert the delegated sub cred on
+ the delegated cred handle, not cred handle
+
+ * mech/gss_accept_sec_context.c (gss_accept_sec_context): handle
+ the case where ret_flags == NULL
+
+ * mech/gss_mech_switch.c (add_builtin): set
+ _gss_mech_switch->gm_mech_oid
+
+ * mech/gss_set_cred_option.c (gss_set_cred_option): laod mechs
+
+ * test_cred.c (gss_print_errors): don't try to print error when
+ gss_display_status failed
+
+ * Makefile.am: Add mech/gss_release_oid.c
+
+ * mech/gss_release_oid.c: Add gss_release_oid, reverse of
+ gss_duplicate_oid
+
+ * spnego/compat.c: preferred_mech_type was allocated with
+ gss_duplicate_oid in one place and assigned static varianbles a
+ the second place. change that static assignement to
+ gss_duplicate_oid and bring back gss_release_oid.
+
+ * spnego/compat.c (_gss_spnego_delete_sec_context): don't release
+ preferred_mech_type and negotiated_mech_type, they where never
+ allocated from the begining.
+
+2006-06-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mech/gss_import_name.c (gss_import_name): avoid
+ type-punned/strict aliasing rules
+
+ * mech/gss_add_cred.c: avoid type-punned/strict aliasing rules
+
+ * gssapi.h: Make gss_name_t an opaque type.
+
+ * krb5: make gss_name_t an opaque type
+
+ * krb5/set_cred_option.c: Add
+
+ * mech/gss_set_cred_option.c (gss_set_cred_option): support the
+ case where *cred_handle == NULL
+
+ * mech/gss_krb5.c (gss_krb5_import_cred): make sure cred is
+ GSS_C_NO_CREDENTIAL on failure.
+
+ * mech/gss_acquire_cred.c (gss_acquire_cred): if desired_mechs is
+ NO_OID_SET, there is a need to load the mechs, so always do that.
+
+2006-06-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * krb5/inquire_cred_by_oid.c: Reimplement GSS_KRB5_COPY_CCACHE_X
+ to instead pass a fullname to the credential, then resolve and
+ copy out the content, and then close the cred.
+
+ * mech/gss_krb5.c: Reimplement GSS_KRB5_COPY_CCACHE_X to instead
+ pass a fullname to the credential, then resolve and copy out the
+ content, and then close the cred.
+
+ * krb5/inquire_cred_by_oid.c: make "work", GSS_KRB5_COPY_CCACHE_X
+ interface needs to be re-done, currently its utterly broken.
+
+ * mech/gss_set_cred_option.c: Make work.
+
+ * krb5/external.c: Add _gsskrb5_set_{sec_context,cred}_option
+
+ * mech/gss_krb5.c (gss_krb5_import_cred): implement
+
+ * Makefile.am: Add gss_set_{sec_context,cred}_option and sort
+
+ * mech/gss_set_{sec_context,cred}_option.c: add
+
+ * gssapi.h: Add GSS_KRB5_IMPORT_CRED_X
+
+ * test_*.c: make compile again
+
+ * Makefile.am: Add lib dependencies and test programs
+
+ * spnego: remove dependency on libkrb5
+
+ * mech: Bug fixes, cleanup, compiler warnings, restructure code.
+
+ * spnego: Rename gss_context_id_t and gss_cred_id_t to local names
+
+ * krb5: repro copy the krb5 files here
+
+ * mech: import Doug Rabson mechglue from freebsd
+
+ * spnego: Import Luke Howard's SPNEGO from the mechglue branch
+
+2006-06-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi.h: Add oid_to_str.
+
+ * Makefile.am: add oid_to_str and test_oid
+
+ * oid_to_str.c: Add gss_oid_to_str
+
+ * test_oid.c: Add test for gss_oid_to_str()
+
+2006-05-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * verify_mic.c: Less pointer signedness warnings.
+
+ * unwrap.c: Less pointer signedness warnings.
+
+ * arcfour.c: Less pointer signedness warnings.
+
+ * gssapi_locl.h: Use const void * to instead of unsigned char * to
+ avoid pointer signedness warnings.
+
+ * encapsulate.c: Use const void * to instead of unsigned char * to
+ avoid pointer signedness warnings.
+
+ * decapsulate.c: Use const void * to instead of unsigned char * to
+ avoid pointer signedness warnings.
+
+ * decapsulate.c: Less pointer signedness warnings.
+
+ * cfx.c: Less pointer signedness warnings.
+
+ * init_sec_context.c: Less pointer signedness warnings (partly by
+ using the new asn.1 CHOICE decoder)
+
+ * import_sec_context.c: Less pointer signedness warnings.
+
+2006-05-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * accept_sec_context.c (gsskrb5_is_cfx): always set is_cfx. From
+ Andrew Abartlet.
+
+2006-05-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * get_mic.c (mic_des3): make sure message_buffer doesn't point to
+ free()ed memory on failure. Pointed out by IBM checker.
+
+2006-05-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Rename u_intXX_t to uintXX_t
+
+2006-05-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cfx.c: Less pointer signedness warnings.
+
+ * arcfour.c: Avoid pointer signedness warnings.
+
+ * gssapi_locl.h (gssapi_decode_*): make data argument const void *
+
+ * 8003.c (gssapi_decode_*): make data argument const void *
+
+2006-04-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * export_sec_context.c: Export sequence order element. From Wynn
+ Wilkes <wynn.wilkes@quest.com>.
+
+ * import_sec_context.c: Import sequence order element. From Wynn
+ Wilkes <wynn.wilkes@quest.com>.
+
+ * sequence.c (_gssapi_msg_order_import,_gssapi_msg_order_export):
+ New functions, used by {import,export}_sec_context. From Wynn
+ Wilkes <wynn.wilkes@quest.com>.
+
+ * test_sequence.c: Add test for import/export sequence.
+
+2006-04-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * add_cred.c: Check that cred != GSS_C_NO_CREDENTIAL, this is a
+ standard conformance failure, but much better then a crash.
+
+2006-04-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * get_mic.c (get_mic*)_: make sure message_token is cleaned on
+ error, found by IBM checker.
+
+ * wrap.c (wrap*): Reset output_buffer on error, found by IBM
+ checker.
+
+2006-02-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * import_name.c: Accept both GSS_C_NT_HOSTBASED_SERVICE and
+ GSS_C_NT_HOSTBASED_SERVICE_X as nametype for hostbased names.
+
+2006-01-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * delete_sec_context.c (gss_delete_sec_context): if the context
+ handle is GSS_C_NO_CONTEXT, don't fall over.
+
+2005-12-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: Replace gss_krb5_import_ccache with
+ gss_krb5_import_cred and add more references
+
+2005-12-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi.h: Change gss_krb5_import_ccache to gss_krb5_import_cred,
+ it can handle keytabs too.
+
+ * add_cred.c (gss_add_cred): avoid deadlock
+
+ * context_time.c (gssapi_lifetime_left): define the 0 lifetime as
+ GSS_C_INDEFINITE.
+
+2005-12-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * acquire_cred.c (acquire_acceptor_cred): only check if principal
+ exists if we got called with principal as an argument.
+
+ * acquire_cred.c (acquire_acceptor_cred): check that the acceptor
+ exists in the keytab before returning ok.
+
+2005-11-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * copy_ccache.c (gss_krb5_import_cred): fix buglet, from Andrew
+ Bartlett.
+
+2005-11-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_kcred.c: Rename gss_krb5_import_ccache to
+ gss_krb5_import_cred.
+
+ * copy_ccache.c: Rename gss_krb5_import_ccache to
+ gss_krb5_import_cred and let it grow code to handle keytabs too.
+
+2005-11-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_sec_context.c: Change sematics of ok-as-delegate to match
+ windows if
+ [gssapi]realm/ok-as-delegate=true is set, otherwise keep old
+ sematics.
+
+ * release_cred.c (gss_release_cred): use
+ GSS_CF_DESTROY_CRED_ON_RELEASE to decide if the cache should be
+ krb5_cc_destroy-ed
+
+ * acquire_cred.c (acquire_initiator_cred):
+ GSS_CF_DESTROY_CRED_ON_RELEASE on created credentials.
+
+ * accept_sec_context.c (gsskrb5_accept_delegated_token): rewrite
+ to use gss_krb5_import_ccache
+
+2005-11-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * arcfour.c: Remove signedness warnings.
+
+2005-10-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: Document that gss_krb5_import_ccache is copy
+ by reference.
+
+ * copy_ccache.c (gss_krb5_import_ccache): Instead of making a copy
+ of the ccache, make a reference by getting the name and resolving
+ the name. This way the cache is shared, this flipp side is of
+ course that if someone calls krb5_cc_destroy the cache is lost for
+ everyone.
+
+ * test_kcred.c: Remove memory leaks.
+
+2005-10-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: build test_kcred
+
+ * gss_acquire_cred.3: Document gss_krb5_import_ccache
+
+ * gssapi.3: Sort and add gss_krb5_import_ccache.
+
+ * acquire_cred.c (_gssapi_krb5_ccache_lifetime): break out code
+ used to extract lifetime from a credential cache
+
+ * gssapi_locl.h: Add _gssapi_krb5_ccache_lifetime, used to extract
+ lifetime from a credential cache.
+
+ * gssapi.h: add gss_krb5_import_ccache, reverse of
+ gss_krb5_copy_ccache
+
+ * copy_ccache.c: add gss_krb5_import_ccache, reverse of
+ gss_krb5_copy_ccache
+
+ * test_kcred.c: test gss_krb5_import_ccache
+
+2005-10-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * acquire_cred.c (acquire_initiator_cred): use krb5_cc_cache_match
+ to find a matching creditial cache, if that failes, fallback to
+ the default cache.
+
+2005-10-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi_locl.h: Add gssapi_krb5_set_status and
+ gssapi_krb5_clear_status
+
+ * init_sec_context.c (spnego_reply): Don't pass back raw Kerberos
+ errors, use GSS-API errors instead. From Michael B Allen.
+
+ * display_status.c: Add gssapi_krb5_clear_status,
+ gssapi_krb5_set_status for handling error messages.
+
+2005-08-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * external.c: Use rk_UNCONST to avoid const warning.
+
+ * display_status.c: Constify strings to avoid warnings.
+
+2005-08-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_sec_context.c: avoid warnings, update (c)
+
+2005-07-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_sec_context.c (spnego_initial): use NegotiationToken
+ encoder now that we have one with the new asn1. compiler.
+
+ * Makefile.am: the new asn.1 compiler includes the modules name in
+ the depend file
+
+2005-06-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * decapsulate.c: use rk_UNCONST
+
+ * ccache_name.c: rename to avoid shadowing
+
+ * gssapi_locl.h: give kret in GSSAPI_KRB5_INIT a more unique name
+
+ * process_context_token.c: use rk_UNCONST to unconstify
+
+ * test_cred.c: rename optind to optidx
+
+2005-05-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_sec_context.c (init_auth): honor ok-as-delegate if local
+ configuration approves
+
+ * gssapi_locl.h: prototype for _gss_check_compat
+
+ * compat.c: export check_compat as _gss_check_compat
+
+2005-05-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_sec_context.c: Prefix Der_class with ASN1_C_ to avoid
+ problems with system headerfiles that pollute the name space.
+
+ * accept_sec_context.c: Prefix Der_class with ASN1_C_ to avoid
+ problems with system headerfiles that pollute the name space.
+
+2005-05-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_sec_context.c (init_auth): set
+ KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED (for java compatibility),
+ also while here, use krb5_auth_con_addflags
+
+2005-05-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * arcfour.c (_gssapi_wrap_arcfour): fix calculating the encap
+ length. From: Tom Maher <tmaher@eecs.berkeley.edu>
+
+2005-05-02 Dave Love <fx@gnu.org>
+
+ * test_cred.c (main): Call setprogname.
+
+2005-04-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * prefix all sequence symbols with _, they are not part of the
+ GSS-API api. By comment from Wynn Wilkes <wynnw@vintela.com>
+
+2005-04-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * accept_sec_context.c: break out the processing of the delegated
+ credential to a separate function to make error handling easier,
+ move the credential handling to after other setup is done
+
+ * test_sequence.c: make less verbose in case of success
+
+ * Makefile.am: add test_sequence to TESTS
+
+2005-04-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * 8003.c (gssapi_krb5_verify_8003_checksum): check that cksum
+ isn't NULL From: Nicolas Pouvesle <npouvesle@tenablesecurity.com>
+
+2005-03-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: use $(LIB_roken)
+
+2005-03-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * display_status.c (gssapi_krb5_set_error_string): pass in the
+ krb5_context to krb5_free_error_string
+
+2005-03-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * display_status.c (gssapi_krb5_set_error_string): don't misuse
+ the krb5_get_error_string api
+
+2005-03-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * compat.c (_gss_DES3_get_mic_compat): don't unlock mutex
+ here. Bug reported by Stefan Metzmacher <metze@samba.org>
+
+2005-02-21 Luke Howard <lukeh@padl.com>
+
+ * init_sec_context.c: don't call krb5_get_credentials() with
+ KRB5_TC_MATCH_KEYTYPE, it can lead to the credentials cache
+ growing indefinitely as no key is found with KEYTYPE_NULL
+
+ * compat.c: remove GSS_C_EXPECTING_MECH_LIST_MIC_FLAG, it is
+ no longer used (however the mechListMIC behaviour is broken,
+ rfc2478bis support requires the code in the mechglue branch)
+
+ * init_sec_context.c: remove GSS_C_EXPECTING_MECH_LIST_MIC_FLAG
+
+ * gssapi.h: remove GSS_C_EXPECTING_MECH_LIST_MIC_FLAG
+
+2005-01-05 Luke Howard <lukeh@padl.com>
+
+ * 8003.c: use symbolic name for checksum type
+
+ * accept_sec_context.c: allow client to indicate
+ that subkey should be used
+
+ * acquire_cred.c: plug leak
+
+ * get_mic.c: use gss_krb5_get_subkey() instead
+ of gss_krb5_get_{local,remote}key(), support
+ KEYTYPE_ARCFOUR_56
+
+ * gssapi_local.c: use gss_krb5_get_subkey(),
+ support KEYTYPE_ARCFOUR_56
+
+ * import_sec_context.c: plug leak
+
+ * unwrap.c: use gss_krb5_get_subkey(),
+ support KEYTYPE_ARCFOUR_56
+
+ * verify_mic.c: use gss_krb5_get_subkey(),
+ support KEYTYPE_ARCFOUR_56
+
+ * wrap.c: use gss_krb5_get_subkey(),
+ support KEYTYPE_ARCFOUR_56
+
+2004-11-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * inquire_cred.c: Reverse order of HEIMDAL_MUTEX_unlock and
+ gss_release_cred to avoid deadlock, from Luke Howard
+ <lukeh@padl.com>.
+
+2004-09-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: gss_krb5_extract_authz_data_from_sec_context
+ was renamed to gsskrb5_extract_authz_data_from_sec_context
+
+2004-08-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * unwrap.c: mutex buglet, From: Luke Howard <lukeh@PADL.COM>
+
+ * arcfour.c: mutex buglet, From: Luke Howard <lukeh@PADL.COM>
+
+2004-05-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi.3: spelling from Josef El-Rayes <josef@FreeBSD.org> while
+ here, write some text about the SPNEGO situation
+
+2004-04-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cfx.c: s/CTXAcceptorSubkey/CFXAcceptorSubkey/
+
+2004-04-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi.h: add GSS_C_EXPECTING_MECH_LIST_MIC_FLAG From: Luke
+ Howard <lukeh@padl.com>
+
+ * init_sec_context.c (spnego_reply): use
+ _gss_spnego_require_mechlist_mic to figure out if we need to check
+ MechListMIC; From: Luke Howard <lukeh@padl.com>
+
+ * accept_sec_context.c (send_accept): use
+ _gss_spnego_require_mechlist_mic to figure out if we need to send
+ MechListMIC; From: Luke Howard <lukeh@padl.com>
+
+ * gssapi_locl.h: add _gss_spnego_require_mechlist_mic
+ From: Luke Howard <lukeh@padl.com>
+
+ * compat.c: add _gss_spnego_require_mechlist_mic for compatibility
+ with MS SPNEGO, From: Luke Howard <lukeh@padl.com>
+
+2004-04-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * accept_sec_context.c (gsskrb5_is_cfx): krb5_keyblock->keytype is
+ an enctype, not keytype
+
+ * accept_sec_context.c: use ASN1_MALLOC_ENCODE
+
+ * init_sec_context.c: avoid the malloc loop and just allocate the
+ propper amount of data
+
+ * init_sec_context.c (spnego_initial): handle mech_token better
+
+2004-03-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi.h: add gss_krb5_get_tkt_flags
+
+ * Makefile.am: add ticket_flags.c
+
+ * ticket_flags.c: Get ticket-flags from acceptor ticket From: Luke
+ Howard <lukeh@PADL.COM>
+
+ * gss_acquire_cred.3: document gss_krb5_get_tkt_flags
+
+2004-03-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * acquire_cred.c (gss_acquire_cred): check usage before even
+ bothering to process it, add both keytab and initial tgt if
+ requested
+
+ * wrap.c: support cfx, try to handle acceptor asserted subkey
+
+ * unwrap.c: support cfx, try to handle acceptor asserted subkey
+
+ * verify_mic.c: support cfx
+
+ * get_mic.c: support cfx
+
+ * test_sequence.c: handle changed signature of
+ gssapi_msg_order_create
+
+ * import_sec_context.c: handle acceptor asserted subkey
+
+ * init_sec_context.c: handle acceptor asserted subkey
+
+ * accept_sec_context.c: handle acceptor asserted subkey
+
+ * sequence.c: add dummy use_64 argument to gssapi_msg_order_create
+
+ * gssapi_locl.h: add partial support for CFX
+
+ * Makefile.am (noinst_PROGRAMS) += test_cred
+
+ * test_cred.c: gssapi credential testing
+
+ * test_acquire_cred.c: fix comment
+
+2004-03-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * arcfour.h: drop structures for message formats, no longer used
+
+ * arcfour.c: comment describing message formats
+
+ * accept_sec_context.c (spnego_accept_sec_context): make sure the
+ length of the choice element doesn't overrun us
+
+ * init_sec_context.c (spnego_reply): make sure the length of the
+ choice element doesn't overrun us
+
+ * spnego.asn1: move NegotiationToken to avoid warning
+
+ * spnego.asn1: uncomment NegotiationToken
+
+ * Makefile.am: spnego_files += asn1_NegotiationToken.x
+
+2004-01-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi.h: add gss_krb5_ccache_name
+
+ * Makefile.am (libgssapi_la_SOURCES): += ccache_name.c
+
+ * ccache_name.c (gss_krb5_ccache_name): help function enable to
+ set krb5 name, using out_name argument makes function no longer
+ thread-safe
+
+ * gssapi.3: add missing gss_krb5_ references
+
+ * gss_acquire_cred.3: document gss_krb5_ccache_name
+
+2003-12-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cfx.c: make rrc a modulus operation if its longer then the
+ length of the message, noticed by Sam Hartman
+
+2003-12-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * accept_sec_context.c: use krb5_auth_con_addflags
+
+2003-12-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cfx.c: Wrap token id was in wrong order, found by Sam Hartman
+
+2003-12-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cfx.c: add AcceptorSubkey (but no code understand it yet) ignore
+ unknown token flags
+
+2003-11-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * accept_sec_context.c: Don't require timestamp to be set on
+ delegated token, its already protected by the outer token (and
+ windows doesn't alway send it) Pointed out by Zi-Bin Yang
+ <zbyang@decru.com> on heimdal-discuss
+
+2003-11-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cfx.c: fix {} error, pointed out by Liqiang Zhu
+
+2003-11-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cfx.c: Sequence number should be stored in bigendian order From:
+ Luke Howard <lukeh@padl.com>
+
+2003-11-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * delete_sec_context.c (gss_delete_sec_context): don't free
+ ticket, krb5_free_ticket does that now
+
+2003-11-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cfx.c: checksum the header last in MIC token, update to -03
+ From: Luke Howard <lukeh@padl.com>
+
+2003-10-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * add_cred.c: If its a MEMORY cc, make a copy. We need to do this
+ since now gss_release_cred will destroy the cred. This should be
+ really be solved a better way.
+
+ * acquire_cred.c (gss_release_cred): if its a mcc, destroy it
+ rather the just release it Found by: "Zi-Bin Yang"
+ <zbyang@decru.com>
+
+ * acquire_cred.c (acquire_initiator_cred): use kret instead of ret
+ where appropriate
+
+2003-09-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: spelling
+ From: jmc <jmc@prioris.mini.pw.edu.pl>
+
+2003-09-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cfx.c: - EC and RRC are big-endian, not little-endian - The
+ default is now to rotate regardless of GSS_C_DCE_STYLE. There are
+ no longer any references to GSS_C_DCE_STYLE. - rrc_rotate()
+ avoids allocating memory on the heap if rrc <= 256
+ From: Luke Howard <lukeh@padl.com>
+
+2003-09-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cfx.[ch]: rrc_rotate() was untested and broken, fix it.
+ Set and verify wrap Token->Filler.
+ Correct token ID for wrap tokens,
+ were accidentally swapped with delete tokens.
+ From: Luke Howard <lukeh@PADL.COM>
+
+2003-09-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cfx.[ch]: no ASN.1-ish header on per-message tokens
+ From: Luke Howard <lukeh@PADL.COM>
+
+2003-09-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * arcfour.h: remove depenency on gss_arcfour_mic_token and
+ gss_arcfour_warp_token
+
+ * arcfour.c: remove depenency on gss_arcfour_mic_token and
+ gss_arcfour_warp_token
+
+2003-09-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * 8003.c: remove #if 0'ed code
+
+2003-09-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * accept_sec_context.c (gsskrb5_accept_sec_context): set sequence
+ number when not requesting mutual auth From: Luke Howard
+ <lukeh@PADL.COM>
+
+ * init_sec_context.c (init_auth): set sequence number when not
+ requesting mutual auth From: Luke Howard <lukeh@PADL.COM>
+
+2003-09-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * arcfour.c (*): set minor_status
+ (gss_wrap): set conf_state to conf_req_flags on success
+ From: Luke Howard <lukeh@PADL.COM>
+
+ * wrap.c (gss_wrap_size_limit): use existing function From: Luke
+ Howard <lukeh@PADL.COM>
+
+2003-09-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * indicate_mechs.c (gss_indicate_mechs): in case of error, free
+ mech_set
+
+ * indicate_mechs.c (gss_indicate_mechs): add SPNEGO
+
+2003-09-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_sec_context.c (spnego_initial): catch errors and return
+ them
+
+ * init_sec_context.c (spnego_initial): add #if 0 out version of
+ the CHOICE branch encoding, also where here, free no longer used
+ memory
+
+2003-09-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: support GSS_SPNEGO_MECHANISM
+
+ * accept_sec_context.c: SPNEGO doesn't include gss wrapping on
+ SubsequentContextToken like the Kerberos 5 mech does.
+
+ * init_sec_context.c (spnego_reply): SPNEGO doesn't include gss
+ wrapping on SubsequentContextToken like the Kerberos 5 mech
+ does. Lets check for it anyway.
+
+ * accept_sec_context.c: Add support for SPNEGO on the initator
+ side. Implementation initially from Assar Westerlund, passes
+ though quite a lot of hands before I commited it.
+
+ * init_sec_context.c: Add support for SPNEGO on the initator side.
+ Tested with ldap server on a Windows 2000 DC. Implementation
+ initially from Assar Westerlund, passes though quite a lot of
+ hands before I commited it.
+
+ * gssapi.h: export GSS_SPNEGO_MECHANISM
+
+ * gssapi_locl.h: include spnego_as.h add prototype for
+ gssapi_krb5_get_mech
+
+ * decapsulate.c (gssapi_krb5_get_mech): make non static
+
+ * Makefile.am: build SPNEGO file
+
+2003-09-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * external.c: SPENGO and IAKERB oids
+
+ * spnego.asn1: SPENGO ASN1
+
+2003-09-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cfx.c: RRC also need to be zero before wraping them
+ From: Luke Howard <lukeh@PADL.COM>
+
+2003-09-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * encapsulate.c (gssapi_krb5_encap_length): don't return void
+
+2003-09-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * verify_mic.c: switch from the des_ to the DES_ api
+
+ * get_mic.c: switch from the des_ to the DES_ api
+
+ * unwrap.c: switch from the des_ to the DES_ api
+
+ * wrap.c: switch from the des_ to the DES_ api
+
+ * cfx.c: EC is not included in the checksum since the length might
+ change depending on the data. From: Luke Howard <lukeh@PADL.COM>
+
+ * acquire_cred.c: use
+ krb5_get_init_creds_opt_alloc/krb5_get_init_creds_opt_free
+
+2003-09-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * copy_ccache.c: rename
+ gss_krb5_extract_authz_data_from_sec_context to
+ gsskrb5_extract_authz_data_from_sec_context
+
+ * gssapi.h: rename gss_krb5_extract_authz_data_from_sec_context to
+ gsskrb5_extract_authz_data_from_sec_context
+
+2003-08-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * copy_ccache.c (gss_krb5_extract_authz_data_from_sec_context):
+ check that we have a ticket before we start to use it
+
+ * gss_acquire_cred.3: document
+ gss_krb5_extract_authz_data_from_sec_context
+
+ * gssapi.h (gss_krb5_extract_authz_data_from_sec_context):
+ return the kerberos authorizationdata, from idea of Luke Howard
+
+ * copy_ccache.c (gss_krb5_extract_authz_data_from_sec_context):
+ return the kerberos authorizationdata, from idea of Luke Howard
+
+ * verify_mic.c (gss_verify_mic_internal): switch type and key
+ argument
+
+2003-08-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cfx.[ch]: draft-ietf-krb-wg-gssapi-cfx-01.txt implemetation
+ From: Luke Howard <lukeh@PADL.COM>
+
+2003-08-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * arcfour.c (arcfour_mic_cksum): use free_Checksum to free the
+ checksum
+
+ * arcfour.h: swap two last arguments to verify_mic for consistency
+ with des3
+
+ * wrap.c,unwrap.c,get_mic.c,verify_mic.c,cfx.c,cfx.h:
+ prefix cfx symbols with _gssapi_
+
+ * arcfour.c: release the right buffer
+
+ * arcfour.c: rename token structure in consistency with rest of
+ GSS-API From: Luke Howard <lukeh@PADL.COM>
+
+ * unwrap.c (unwrap_des3): use _gssapi_verify_pad
+ (unwrap_des): use _gssapi_verify_pad
+
+ * arcfour.c (_gssapi_wrap_arcfour): set the correct padding
+ (_gssapi_unwrap_arcfour): verify and strip padding
+
+ * gssapi_locl.h: added _gssapi_verify_pad
+
+ * decapsulate.c (_gssapi_verify_pad): verify padding of a gss
+ wrapped message and return its length
+
+ * arcfour.c: support KEYTYPE_ARCFOUR_56 keys, from Luke Howard
+ <lukeh@PADL.COM>
+
+ * arcfour.c: use right seal alg, inherit keytype from parent key
+
+ * arcfour.c: include the confounder in the checksum use the right
+ key usage number for warped/unwraped tokens
+
+ * gssapi.h: add gss_krb5_nt_general_name as an mit compat glue
+ (same as GSS_KRB5_NT_PRINCIPAL_NAME)
+
+ * unwrap.c: hook in arcfour unwrap
+
+ * wrap.c: hook in arcfour wrap
+
+ * verify_mic.c: hook in arcfour verify_mic
+
+ * get_mic.c: hook in arcfour get_mic
+
+ * arcfour.c: implement wrap/unwarp
+
+ * gssapi_locl.h: add gssapi_{en,de}code_be_om_uint32
+
+ * 8003.c: add gssapi_{en,de}code_be_om_uint32
+
+2003-08-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * arcfour.c (_gssapi_verify_mic_arcfour): Do the checksum on right
+ area. Swap filler check, it was reversed.
+
+ * Makefile.am (libgssapi_la_SOURCES): += arcfour.c
+
+ * gssapi_locl.h: include "arcfour.h"
+
+ * arcfour.c: arcfour gss-api mech, get_mic/verify_mic working
+
+ * arcfour.h: arcfour gss-api mech, get_mic/verify_mic working
+
+2003-08-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi_locl.h: always include cfx.h add prototype for
+ _gssapi_decapsulate
+
+ * cfx.[ch]: Implementation of draft-ietf-krb-wg-gssapi-cfx-00.txt
+ from Luke Howard <lukeh@PADL.COM>
+
+ * decapsulate.c: add _gssapi_decapsulate, from Luke Howard
+ <lukeh@PADL.COM>
+
+2003-08-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * unwrap.c: encap/decap now takes a oid if the enctype/keytype is
+ arcfour, return error add hook for cfx
+
+ * verify_mic.c: encap/decap now takes a oid if the enctype/keytype
+ is arcfour, return error add hook for cfx
+
+ * get_mic.c: encap/decap now takes a oid if the enctype/keytype is
+ arcfour, return error add hook for cfx
+
+ * accept_sec_context.c: encap/decap now takes a oid
+
+ * init_sec_context.c: encap/decap now takes a oid
+
+ * gssapi_locl.h: include cfx.h if we need it lifetime is a
+ OM_uint32, depend on gssapi interface add all new encap/decap
+ functions
+
+ * decapsulate.c: add decap functions that doesn't take the token
+ type also make all decap function take the oid mech that they
+ should use
+
+ * encapsulate.c: add encap functions that doesn't take the token
+ type also make all encap function take the oid mech that they
+ should use
+
+ * sequence.c (elem_insert): fix a off by one index counter
+
+ * inquire_cred.c (gss_inquire_cred): handle cred_handle being
+ GSS_C_NO_CREDENTIAL and use the default cred then.
+
+2003-08-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: break out extensions and document
+ gsskrb5_register_acceptor_identity
+
+2003-08-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_acquire_cred.c (print_time): time is returned in seconds
+ from now, not unix time
+
+2003-08-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * compat.c (check_compat): avoid leaking principal when finding a
+ match
+
+ * address_to_krb5addr.c: sa_size argument to krb5_addr2sockaddr is
+ a krb5_socklen_t
+
+ * acquire_cred.c (gss_acquire_cred): 4th argument to
+ gss_test_oid_set_member is a int
+
+2003-07-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_sec_context.c (repl_mutual): don't set kerberos error where
+ there was no kerberos error
+
+ * gssapi_locl.h: Add destruction/creation prototypes and structure
+ for the thread specific storage.
+
+ * display_status.c: use thread specific storage to set/get the
+ kerberos error message
+
+ * init.c: Provide locking around the creation of the global
+ krb5_context. Add destruction/creation functions for the thread
+ specific storage that the error string handling is using.
+
+2003-07-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: add missing prototype and missing .Ft
+ arguments
+
+2003-06-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * verify_mic.c: reorder code so sequence numbers can can be used
+
+ * unwrap.c: reorder code so sequence numbers can can be used
+
+ * sequence.c: remove unused function, indent, add
+ gssapi_msg_order_f that filter gss flags to gss_msg_order flags
+
+ * gssapi_locl.h: prototypes for
+ gssapi_{encode_om_uint32,decode_om_uint32} add sequence number
+ verifier prototypes
+
+ * delete_sec_context.c: destroy sequence number verifier
+
+ * init_sec_context.c: remember to free data use sequence number
+ verifier
+
+ * accept_sec_context.c: don't clear output_token twice remember to
+ free data use sequence number verifier
+
+ * 8003.c: export and rename encode_om_uint32/decode_om_uint32 and
+ start to use them
+
+2003-06-09 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: can't have sequence.c in two different places
+
+2003-06-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_sequence.c: check rollover, print summery
+
+ * wrap.c (sub_wrap_size): gss_wrap_size_limit() has
+ req_output_size and max_input_size around the wrong way -- it
+ returns the output token size for a given input size, rather than
+ the maximum input size for a given output token size.
+
+ From: Luke Howard <lukeh@PADL.COM>
+
+2003-06-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi_locl.h: add prototypes for sequence.c
+
+ * Makefile.am (libgssapi_la_SOURCES): add sequence.c
+ (test_sequence): build
+
+ * sequence.c: sequence number checks, order and replay
+ * test_sequence.c: sequence number checks, order and replay
+
+2003-06-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * accept_sec_context.c (gss_accept_sec_context): make sure time is
+ returned in seconds from now, not in kerberos time
+
+ * acquire_cred.c (gss_aquire_cred): make sure time is returned in
+ seconds from now, not in kerberos time
+
+ * init_sec_context.c (init_auth): if the cred is expired before we
+ tries to create a token, fail so the peer doesn't need reject us
+ (*): make sure time is returned in seconds from now,
+ not in kerberos time
+ (repl_mutual): remember to unlock the context mutex
+
+ * context_time.c (gss_context_time): remove unused variable
+
+ * verify_mic.c: make sure minor_status is always set, pointed out
+ by Luke Howard <lukeh@PADL.COM>
+
+2003-05-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * *.[ch]: do some basic locking (no reference counting so contexts
+ can be removed while still used)
+ - don't export gss_ctx_id_t_desc_struct and gss_cred_id_t_desc_struct
+ - make sure all lifetime are returned in seconds left until expired,
+ not in unix epoch
+
+ * gss_acquire_cred.3: document argument lifetime_rec to function
+ gss_inquire_context
+
+2003-05-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_acquire_cred.c: test gss_add_cred more then once
+
+2003-05-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi.h: if __cplusplus, wrap the extern variable (just to be
+ safe) and functions in extern "C" { }
+
+2003-04-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi.3: more about the des3 mic mess
+
+ * verify_mic.c (verify_mic_des3): always check if the mic is the
+ correct mic or the mic that old heimdal would have generated
+
+2003-04-28 Jacques Vidrine <nectar@kth.se>
+
+ * verify_mic.c (verify_mic_des3): If MIC verification fails,
+ retry using the `old' MIC computation (with zero IV).
+
+2003-04-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: more about difference between comparing IN
+ and MN
+
+ * gss_acquire_cred.3: more about name type and access control
+
+2003-04-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: document gss_context_time
+
+ * context_time.c: if lifetime of context have expired, set
+ time_rec to 0 and return GSS_S_CONTEXT_EXPIRED
+
+ * gssapi.3: document [gssapi]correct_des3_mic
+ [gssapi]broken_des3_mic
+
+ * gss_acquire_cred.3: document gss_krb5_compat_des3_mic
+
+ * compat.c (gss_krb5_compat_des3_mic): enable turning on/off des3
+ mic compat
+ (_gss_DES3_get_mic_compat): handle [gssapi]correct_des3_mic too
+
+ * gssapi.h (gss_krb5_compat_des3_mic): new function, turn on/off
+ des3 mic compat
+ (GSS_C_KRB5_COMPAT_DES3_MIC): cpp symbol that exists if
+ gss_krb5_compat_des3_mic exists
+
+2003-04-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: (libgssapi_la_LDFLAGS): update major
+ version of gssapi for incompatiblity in 3des getmic support
+
+2003-04-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: test_acquire_cred_LDADD: use libgssapi.la not
+ ./libgssapi.la (make make -jN work)
+
+2003-04-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi.3: spelling
+
+ * gss_acquire_cred.3: Change .Fd #include <header.h> to .In
+ header.h, from Thomas Klausner <wiz@netbsd.org>
+
+
+2003-04-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: spelling
+
+ * Makefile.am: remove stuff that sneaked in with last commit
+
+ * acquire_cred.c (acquire_initiator_cred): if the requested name
+ isn't in the ccache, also check keytab. Extact the krbtgt for the
+ default realm to check how long the credentials will last.
+
+ * add_cred.c (gss_add_cred): don't create a new ccache, just open
+ the old one; better check if output handle is compatible with new
+ (copied) handle
+
+ * test_acquire_cred.c: test gss_add_cred too
+
+2003-04-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: build test_acquire_cred
+
+ * test_acquire_cred.c: simple gss_acquire_cred test
+
+2003-04-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: s/gssapi/GSS-API/
+
+2003-03-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: document v1 interface (and that they are
+ obsolete)
+
+2003-03-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: list supported mechanism and nametypes
+
+2003-03-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_acquire_cred.3: text about gss_display_name
+
+ * Makefile.am (libgssapi_la_LDFLAGS): bump to 3:6:2
+ (libgssapi_la_SOURCES): add all new functions
+
+ * gssapi.3: now that we have a functions, uncomment the missing
+ ones
+
+ * gss_acquire_cred.3: now that we have a functions, uncomment the
+ missing ones
+
+ * process_context_token.c: implement gss_process_context_token
+
+ * inquire_names_for_mech.c: implement gss_inquire_names_for_mech
+
+ * inquire_mechs_for_name.c: implement gss_inquire_mechs_for_name
+
+ * inquire_cred_by_mech.c: implement gss_inquire_cred_by_mech
+
+ * add_cred.c: implement gss_add_cred
+
+ * acquire_cred.c (gss_acquire_cred): more testing of input
+ argument, make sure output arguments are ok, since we don't know
+ the time_rec (for now), set it to time_req
+
+ * export_sec_context.c: send lifetime, also set minor_status
+
+ * get_mic.c: set minor_status
+
+ * import_sec_context.c (gss_import_sec_context): add error
+ checking, pick up lifetime (if there is no lifetime, use
+ GSS_C_INDEFINITE)
+
+ * init_sec_context.c: take care to set export value to something
+ sane before we start so caller will have harmless values in them
+ if then function fails
+
+ * release_buffer.c (gss_release_buffer): set minor_status
+
+ * wrap.c: make sure minor_status get set
+
+ * verify_mic.c (gss_verify_mic_internal): rename verify_mic to
+ gss_verify_mic_internal and let it take the type as an argument,
+ (gss_verify_mic): call gss_verify_mic_internal
+ set minor_status
+
+ * unwrap.c: set minor_status
+
+ * test_oid_set_member.c (gss_test_oid_set_member): use
+ gss_oid_equal
+
+ * release_oid_set.c (gss_release_oid_set): set minor_status
+
+ * release_name.c (gss_release_name): set minor_status
+
+ * release_cred.c (gss_release_cred): set minor_status
+
+ * add_oid_set_member.c (gss_add_oid_set_member): set minor_status
+
+ * compare_name.c (gss_compare_name): set minor_status
+
+ * compat.c (check_compat): make sure ret have a defined value
+
+ * context_time.c (gss_context_time): set minor_status
+
+ * copy_ccache.c (gss_krb5_copy_ccache): set minor_status
+
+ * create_emtpy_oid_set.c (gss_create_empty_oid_set): set
+ minor_status
+
+ * delete_sec_context.c (gss_delete_sec_context): set minor_status
+
+ * display_name.c (gss_display_name): set minor_status
+
+ * display_status.c (gss_display_status): use gss_oid_equal, handle
+ supplementary errors
+
+ * duplicate_name.c (gss_duplicate_name): set minor_status
+
+ * inquire_context.c (gss_inquire_context): set lifetime_rec now
+ when we know it, set minor_status
+
+ * inquire_cred.c (gss_inquire_cred): take care to set export value
+ to something sane before we start so caller will have harmless
+ values in them if the function fails
+
+ * accept_sec_context.c (gss_accept_sec_context): take care to set
+ export value to something sane before we start so caller will have
+ harmless values in them if then function fails, set lifetime from
+ ticket expiration date
+
+ * indicate_mechs.c (gss_indicate_mechs): use
+ gss_create_empty_oid_set and gss_add_oid_set_member
+
+ * gssapi.h (gss_ctx_id_t_desc): store the lifetime in the cred,
+ since there is no ticket transfered in the exported context
+
+ * export_name.c (gss_export_name): export name with
+ GSS_C_NT_EXPORT_NAME wrapping, not just the principal
+
+ * import_name.c (import_export_name): new function, parses a
+ GSS_C_NT_EXPORT_NAME
+ (import_krb5_name): factor out common code of parsing krb5 name
+ (gss_oid_equal): rename from oid_equal
+
+ * gssapi_locl.h: add prototypes for gss_oid_equal and
+ gss_verify_mic_internal
+
+ * gssapi.h: comment out the argument names
+
+2003-03-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gssapi.3: add LIST OF FUNCTIONS and copyright/license
+
+ * Makefile.am: s/gss_aquire_cred.3/gss_acquire_cred.3/
+
+ * Makefile.am: man_MANS += gss_aquire_cred.3
+
+2003-03-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gss_aquire_cred.3: the gssapi api manpage
+
+2003-03-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * inquire_context.c: (gss_inquire_context): rename argument open
+ to open_context
+
+ * gssapi.h (gss_inquire_context): rename argument open to open_context
+
+2003-02-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_sec_context.c (do_delegation): remove unused variable
+ subkey
+
+ * gssapi.3: all 0.5.x version had broken token delegation
+
+2003-02-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * (init_auth): only generate one subkey
+
+2003-01-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * verify_mic.c (verify_mic_des3): fix 3des verify_mic to conform
+ to rfc (and mit kerberos), provide backward compat hook
+
+ * get_mic.c (mic_des3): fix 3des get_mic to conform to rfc (and
+ mit kerberos), provide backward compat hook
+
+ * init_sec_context.c (init_auth): check if we need compat for
+ older get_mic/verify_mic
+
+ * gssapi_locl.h: add prototype for _gss_DES3_get_mic_compat
+
+ * gssapi.h (more_flags): add COMPAT_OLD_DES3
+
+ * Makefile.am: add gssapi.3 and compat.c
+
+ * gssapi.3: add gssapi COMPATIBILITY documentation
+
+ * accept_sec_context.c (gss_accept_sec_context): check if we need
+ compat for older get_mic/verify_mic
+
+ * compat.c: check for compatiblity with other heimdal's 3des
+ get_mic/verify_mic
+
+2002-10-31 Johan Danielsson <joda@pdc.kth.se>
+
+ * check return value from gssapi_krb5_init
+
+ * 8003.c (gssapi_krb5_verify_8003_checksum): check size of input
+
+2002-09-03 Johan Danielsson <joda@pdc.kth.se>
+
+ * wrap.c (wrap_des3): use ETYPE_DES3_CBC_NONE
+
+ * unwrap.c (unwrap_des3): use ETYPE_DES3_CBC_NONE
+
+2002-09-02 Johan Danielsson <joda@pdc.kth.se>
+
+ * init_sec_context.c: we need to generate a local subkey here
+
+2002-08-20 Jacques Vidrine <n@nectar.com>
+
+ * acquire_cred.c, inquire_cred.c, release_cred.c: Use default
+ credential resolution if gss_acquire_cred is called with
+ GSS_C_NO_NAME.
+
+2002-06-20 Jacques Vidrine <n@nectar.com>
+
+ * import_name.c: Compare name types by value if pointers do
+ not match. Reported by: "Douglas E. Engert" <deengert@anl.gov>
+
+2002-05-20 Jacques Vidrine <n@nectar.com>
+
+ * verify_mic.c (gss_verify_mic), unwrap.c (gss_unwrap): initialize
+ the qop_state parameter. from Doug Rabson <dfr@nlsystems.com>
+
+2002-05-09 Jacques Vidrine <n@nectar.com>
+
+ * acquire_cred.c: handle GSS_C_INITIATE/GSS_C_ACCEPT/GSS_C_BOTH
+
+2002-05-08 Jacques Vidrine <n@nectar.com>
+
+ * acquire_cred.c: initialize gssapi; handle null desired_name
+
+2002-03-22 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: remove non-functional stuff accidentally committed
+
+2002-03-11 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libgssapi_la_LDFLAGS): bump version to 3:5:2
+ * 8003.c (gssapi_krb5_verify_8003_checksum): handle zero channel
+ bindings
+
+2001-10-31 Jacques Vidrine <n@nectar.com>
+
+ * get_mic.c (mic_des3): MIC computation using DES3/SHA1
+ was bogusly appending the message buffer to the result,
+ overwriting a heap buffer in the process.
+
+2001-08-29 Assar Westerlund <assar@sics.se>
+
+ * 8003.c (gssapi_krb5_verify_8003_checksum,
+ gssapi_krb5_create_8003_checksum): make more consistent by always
+ returning an gssapi error and setting minor status. update
+ callers
+
+2001-08-28 Jacques Vidrine <n@nectar.com>
+
+ * accept_sec_context.c: Create a cache for delegated credentials
+ when needed.
+
+2001-08-28 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libgssapi_la_LDFLAGS): set version to 3:4:2
+
+2001-08-23 Assar Westerlund <assar@sics.se>
+
+ * *.c: handle minor_status more consistently
+
+ * display_status.c (gss_display_status): handle krb5_get_err_text
+ failing
+
+2001-08-15 Johan Danielsson <joda@pdc.kth.se>
+
+ * gssapi_locl.h: fix prototype for gssapi_krb5_init
+
+2001-08-13 Johan Danielsson <joda@pdc.kth.se>
+
+ * accept_sec_context.c (gsskrb5_register_acceptor_identity): init
+ context and check return value from kt_resolve
+
+ * init.c: return error code
+
+2001-07-19 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libgssapi_la_LDFLAGS): update to 3:3:2
+
+2001-07-12 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libgssapi_la_LIBADD): add required library
+ dependencies
+
+2001-07-06 Assar Westerlund <assar@sics.se>
+
+ * accept_sec_context.c (gsskrb5_register_acceptor_identity): set
+ the keytab to be used for gss_acquire_cred too'
+
+2001-07-03 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libgssapi_la_LDFLAGS): set version to 3:2:2
+
+2001-06-18 Assar Westerlund <assar@sics.se>
+
+ * wrap.c: replace gss_krb5_getsomekey with gss_krb5_get_localkey
+ and gss_krb5_get_remotekey
+ * verify_mic.c: update krb5_auth_con function names use
+ gss_krb5_get_remotekey
+ * unwrap.c: replace gss_krb5_getsomekey with gss_krb5_get_localkey
+ and gss_krb5_get_remotekey
+ * gssapi_locl.h (gss_krb5_get_remotekey, gss_krb5_get_localkey):
+ add prototypes
+ * get_mic.c: update krb5_auth_con function names. use
+ gss_krb5_get_localkey
+ * accept_sec_context.c: update krb5_auth_con function names
+
+2001-05-17 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 3:1:2
+
+2001-05-14 Assar Westerlund <assar@sics.se>
+
+ * address_to_krb5addr.c: adapt to new address functions
+
+2001-05-11 Assar Westerlund <assar@sics.se>
+
+ * try to return the error string from libkrb5 where applicable
+
+2001-05-08 Assar Westerlund <assar@sics.se>
+
+ * delete_sec_context.c (gss_delete_sec_context): remember to free
+ the memory used by the ticket itself. from <tmartin@mirapoint.com>
+
+2001-05-04 Assar Westerlund <assar@sics.se>
+
+ * gssapi_locl.h: add config.h for completeness
+ * gssapi.h: remove config.h, this is an installed header file
+ sys/types.h is not needed either
+
+2001-03-12 Assar Westerlund <assar@sics.se>
+
+ * acquire_cred.c (gss_acquire_cred): remove memory leaks. from
+ Jason R Thorpe <thorpej@zembu.com>
+
+2001-02-18 Assar Westerlund <assar@sics.se>
+
+ * accept_sec_context.c (gss_accept_sec_context): either return
+ gss_name NULL-ed or set
+
+ * import_name.c: set minor_status in some cases where it was not
+ done
+
+2001-02-15 Assar Westerlund <assar@sics.se>
+
+ * wrap.c: use krb5_generate_random_block for the confounders
+
+2001-01-30 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libgssapi_la_LDFLAGS): bump version to 3:0:2
+ * acquire_cred.c, init_sec_context.c, release_cred.c: add support
+ for getting creds from a keytab, from fvdl@netbsd.org
+
+ * copy_ccache.c: add gss_krb5_copy_ccache
+
+2001-01-27 Assar Westerlund <assar@sics.se>
+
+ * get_mic.c: cast parameters to des function to non-const pointers
+ to handle the case where these functions actually take non-const
+ des_cblock *
+
+2001-01-09 Assar Westerlund <assar@sics.se>
+
+ * accept_sec_context.c (gss_accept_sec_context): use krb5_rd_cred2
+ instead of krb5_rd_cred
+
+2000-12-11 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libgssapi_la_LDFLAGS): bump to 2:3:1
+
+2000-12-08 Assar Westerlund <assar@sics.se>
+
+ * wrap.c (wrap_des3): use the checksum as ivec when encrypting the
+ sequence number
+ * unwrap.c (unwrap_des3): use the checksum as ivec when encrypting
+ the sequence number
+ * init_sec_context.c (init_auth): always zero fwd_data
+
+2000-12-06 Johan Danielsson <joda@pdc.kth.se>
+
+ * accept_sec_context.c: de-pointerise auth_context parameter to
+ krb5_mk_rep
+
+2000-11-15 Assar Westerlund <assar@sics.se>
+
+ * init_sec_context.c (init_auth): update to new
+ krb5_build_authenticator
+
+2000-09-19 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libgssapi_la_LDFLAGS): bump to 2:2:1
+
+2000-08-27 Assar Westerlund <assar@sics.se>
+
+ * init_sec_context.c: actually pay attention to `time_req'
+ * init_sec_context.c: re-organize. leak less memory.
+ * gssapi_locl.h (gssapi_krb5_encapsulate, gss_krb5_getsomekey):
+ update prototypes add assert.h
+ * gssapi.h (GSS_KRB5_CONF_C_QOP_DES, GSS_KRB5_CONF_C_QOP_DES3_KD):
+ add
+ * verify_mic.c: re-organize and add 3DES code
+ * wrap.c: re-organize and add 3DES code
+ * unwrap.c: re-organize and add 3DES code
+ * get_mic.c: re-organize and add 3DES code
+ * encapsulate.c (gssapi_krb5_encapsulate): do not free `in_data',
+ let the caller do that. fix the callers.
+
+2000-08-16 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 2:1:1
+
+2000-07-29 Assar Westerlund <assar@sics.se>
+
+ * decapsulate.c (gssapi_krb5_verify_header): sanity-check length
+
+2000-07-25 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: bump version to 2:0:1
+
+2000-07-22 Assar Westerlund <assar@sics.se>
+
+ * gssapi.h: update OID for GSS_C_NT_HOSTBASED_SERVICE and other
+ details from rfc2744
+
+2000-06-29 Assar Westerlund <assar@sics.se>
+
+ * address_to_krb5addr.c (gss_address_to_krb5addr): actually use
+ `int' instead of `sa_family_t' for the address family.
+
+2000-06-21 Assar Westerlund <assar@sics.se>
+
+ * add support for token delegation. From Daniel Kouril
+ <kouril@ics.muni.cz> and Miroslav Ruda <ruda@ics.muni.cz>
+
+2000-05-15 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libgssapi_la_LDFLAGS): set version to 1:1:1
+
+2000-04-12 Assar Westerlund <assar@sics.se>
+
+ * release_oid_set.c (gss_release_oid_set): clear set for
+ robustness. From GOMBAS Gabor <gombasg@inf.elte.hu>
+ * release_name.c (gss_release_name): reset input_name for
+ robustness. From GOMBAS Gabor <gombasg@inf.elte.hu>
+ * release_buffer.c (gss_release_buffer): set value to NULL to be
+ more robust. From GOMBAS Gabor <gombasg@inf.elte.hu>
+ * add_oid_set_member.c (gss_add_oid_set_member): actually check if
+ the oid is a member first. leave the oid_set unchanged if realloc
+ fails.
+
+2000-02-13 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 1:0:1
+
+2000-02-12 Assar Westerlund <assar@sics.se>
+
+ * gssapi_locl.h: add flags for import/export
+ * import_sec_context.c (import_sec_context: add flags for what
+ fields are included. do not include the authenticator for now.
+ * export_sec_context.c (export_sec_context: add flags for what
+ fields are included. do not include the authenticator for now.
+ * accept_sec_context.c (gss_accept_sec_context): set target in
+ context_handle
+
+2000-02-11 Assar Westerlund <assar@sics.se>
+
+ * delete_sec_context.c (gss_delete_sec_context): set context to
+ GSS_C_NO_CONTEXT
+
+ * Makefile.am: add {export,import}_sec_context.c
+ * export_sec_context.c: new file
+ * import_sec_context.c: new file
+ * accept_sec_context.c (gss_accept_sec_context): set trans flag
+
+2000-02-07 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 0:5:0
+
+2000-01-26 Assar Westerlund <assar@sics.se>
+
+ * delete_sec_context.c (gss_delete_sec_context): handle a NULL
+ output_token
+
+ * wrap.c: update to pseudo-standard APIs for md4,md5,sha. some
+ changes to libdes calls to make them more portable.
+ * verify_mic.c: update to pseudo-standard APIs for md4,md5,sha.
+ some changes to libdes calls to make them more portable.
+ * unwrap.c: update to pseudo-standard APIs for md4,md5,sha. some
+ changes to libdes calls to make them more portable.
+ * get_mic.c: update to pseudo-standard APIs for md4,md5,sha. some
+ changes to libdes calls to make them more portable.
+ * 8003.c: update to pseudo-standard APIs for md4,md5,sha.
+
+2000-01-06 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 0:4:0
+
+1999-12-26 Assar Westerlund <assar@sics.se>
+
+ * accept_sec_context.c (gss_accept_sec_context): always set
+ `output_token'
+ * init_sec_context.c (init_auth): always initialize `output_token'
+ * delete_sec_context.c (gss_delete_sec_context): always set
+ `output_token'
+
+1999-12-06 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 0:3:0
+
+1999-10-20 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 0:2:0
+
+1999-09-21 Assar Westerlund <assar@sics.se>
+
+ * init_sec_context.c (gss_init_sec_context): initialize `ticket'
+
+ * gssapi.h (gss_ctx_id_t_desc): add ticket in here. ick.
+
+ * delete_sec_context.c (gss_delete_sec_context): free ticket
+
+ * accept_sec_context.c (gss_accept_sec_context): stove away
+ `krb5_ticket' in context so that ugly programs such as
+ gss_nt_server can get at it. uck.
+
+1999-09-20 Johan Danielsson <joda@pdc.kth.se>
+
+ * accept_sec_context.c: set minor_status
+
+1999-08-04 Assar Westerlund <assar@sics.se>
+
+ * display_status.c (calling_error, routine_error): right shift the
+ code to make it possible to index into the arrays
+
+1999-07-28 Assar Westerlund <assar@sics.se>
+
+ * gssapi.h (GSS_C_AF_INET6): add
+
+ * import_name.c (import_hostbased_name): set minor_status
+
+1999-07-26 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 0:1:0
+
+Wed Apr 7 14:05:15 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * display_status.c: set minor_status
+
+ * init_sec_context.c: set minor_status
+
+ * lib/gssapi/init.c: remove donep (check gssapi_krb5_context
+ directly)
+
diff --git a/third_party/heimdal/lib/gssapi/Makefile.am b/third_party/heimdal/lib/gssapi/Makefile.am
new file mode 100644
index 0000000..a69ebff
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/Makefile.am
@@ -0,0 +1,468 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+WFLAGS += $(WFLAGS_ENUM_CONV)
+
+AUTOMAKE_OPTIONS = subdir-objects
+
+AM_CPPFLAGS += \
+ -I$(top_srcdir)/lib \
+ -I$(srcdir)/../krb5 \
+ -I$(srcdir) \
+ -I$(srcdir)/gssapi \
+ -I$(srcdir)/mech \
+ -I$(srcdir)/ntlm \
+ -I$(srcdir)/krb5 \
+ -I$(srcdir)/spnego \
+ -I$(srcdir)/sanon \
+ $(INCLUDE_libintl)
+
+lib_LTLIBRARIES = libgssapi.la test_negoex_mech.la
+
+krb5src = \
+ krb5/8003.c \
+ krb5/accept_sec_context.c \
+ krb5/acquire_cred.c \
+ krb5/add_cred.c \
+ krb5/address_to_krb5addr.c \
+ krb5/aeap.c \
+ krb5/arcfour.c \
+ krb5/canonicalize_name.c \
+ krb5/creds.c \
+ krb5/ccache_name.c \
+ krb5/cfx.c \
+ krb5/cfx.h \
+ krb5/compare_name.c \
+ krb5/compat.c \
+ krb5/context_time.c \
+ krb5/copy_ccache.c \
+ krb5/decapsulate.c \
+ krb5/delete_sec_context.c \
+ krb5/display_name.c \
+ krb5/display_status.c \
+ krb5/duplicate_cred.c \
+ krb5/duplicate_name.c \
+ krb5/encapsulate.c \
+ krb5/export_name.c \
+ krb5/export_sec_context.c \
+ krb5/external.c \
+ krb5/get_mic.c \
+ krb5/gsskrb5_locl.h \
+ $(srcdir)/krb5/gsskrb5-private.h \
+ krb5/import_name.c \
+ krb5/import_sec_context.c \
+ krb5/indicate_mechs.c \
+ krb5/init.c \
+ krb5/init_sec_context.c \
+ krb5/inquire_context.c \
+ krb5/inquire_cred.c \
+ krb5/inquire_cred_by_mech.c \
+ krb5/inquire_cred_by_oid.c \
+ krb5/inquire_mechs_for_name.c \
+ krb5/inquire_names_for_mech.c \
+ krb5/inquire_sec_context_by_oid.c \
+ krb5/name_attrs.c \
+ krb5/pname_to_uid.c \
+ krb5/process_context_token.c \
+ krb5/prf.c \
+ krb5/release_buffer.c \
+ krb5/release_cred.c \
+ krb5/release_name.c \
+ krb5/sequence.c \
+ krb5/store_cred.c \
+ krb5/set_cred_option.c \
+ krb5/set_sec_context_option.c \
+ krb5/ticket_flags.c \
+ krb5/unwrap.c \
+ krb5/authorize_localname.c \
+ krb5/verify_mic.c \
+ krb5/wrap.c
+
+mechsrc = \
+ mech/context.h \
+ mech/context.c \
+ mech/cred.h \
+ mech/cred.c \
+ mech/compat.h \
+ mech/doxygen.c \
+ mech/gss_accept_sec_context.c \
+ mech/gss_acquire_cred.c \
+ mech/gss_acquire_cred_from.c \
+ mech/gss_acquire_cred_impersonate_name.c \
+ mech/gss_acquire_cred_with_password.c \
+ mech/gss_add_cred.c \
+ mech/gss_add_cred_from.c \
+ mech/gss_add_cred_with_password.c \
+ mech/gss_add_oid_set_member.c \
+ mech/gss_aeap.c \
+ mech/gss_buffer_set.c \
+ mech/gss_canonicalize_name.c \
+ mech/gss_compare_name.c \
+ mech/gss_context_time.c \
+ mech/gss_create_empty_oid_set.c \
+ mech/gss_cred.c \
+ mech/gss_decapsulate_token.c \
+ mech/gss_delete_name_attribute.c \
+ mech/gss_delete_sec_context.c \
+ mech/gss_destroy_cred.c \
+ mech/gss_display_name.c \
+ mech/gss_display_name_ext.c \
+ mech/gss_display_status.c \
+ mech/gss_duplicate_cred.c \
+ mech/gss_duplicate_name.c \
+ mech/gss_duplicate_oid.c \
+ mech/gss_duplicate_oid_set.c \
+ mech/gss_encapsulate_token.c \
+ mech/gss_export_name.c \
+ mech/gss_export_name_composite.c \
+ mech/gss_export_sec_context.c \
+ mech/gss_get_mic.c \
+ mech/gss_get_neg_mechs.c \
+ mech/gss_get_name_attribute.c \
+ mech/gss_import_name.c \
+ mech/gss_import_sec_context.c \
+ mech/gss_indicate_mechs.c \
+ mech/gss_init_sec_context.c \
+ mech/gss_inquire_context.c \
+ mech/gss_inquire_cred.c \
+ mech/gss_inquire_cred_by_mech.c \
+ mech/gss_inquire_cred_by_oid.c \
+ mech/gss_inquire_mechs_for_name.c \
+ mech/gss_inquire_name.c \
+ mech/gss_inquire_names_for_mech.c \
+ mech/gss_krb5.c \
+ mech/gss_mech_switch.c \
+ mech/gss_mo.c \
+ mech/gss_names.c \
+ mech/gss_oid.c \
+ mech/gss_oid_equal.c \
+ mech/gss_oid_to_str.c \
+ mech/gss_pname_to_uid.c \
+ mech/gss_process_context_token.c \
+ mech/gss_pseudo_random.c \
+ mech/gss_release_buffer.c \
+ mech/gss_release_cred.c \
+ mech/gss_release_name.c \
+ mech/gss_release_oid.c \
+ mech/gss_release_oid_set.c \
+ mech/gss_rfc4121.c \
+ mech/gss_seal.c \
+ mech/gss_set_cred_option.c \
+ mech/gss_set_name_attribute.c \
+ mech/gss_set_neg_mechs.c \
+ mech/gss_set_sec_context_option.c \
+ mech/gss_sign.c \
+ mech/gss_store_cred.c \
+ mech/gss_store_cred_into.c \
+ mech/gss_test_oid_set_member.c \
+ mech/gss_unseal.c \
+ mech/gss_unwrap.c \
+ mech/gss_authorize_localname.c \
+ mech/gss_utils.c \
+ mech/gss_verify.c \
+ mech/gss_verify_mic.c \
+ mech/gss_wrap.c \
+ mech/gss_wrap_size_limit.c \
+ mech/gss_inquire_sec_context_by_oid.c \
+ mech/gssspi_exchange_meta_data.c \
+ mech/gssspi_query_mechanism_info.c \
+ mech/gssspi_query_meta_data.c \
+ mech/mech_switch.h \
+ mech/mech_locl.h \
+ mech/name.h \
+ mech/utils.h
+
+spnegosrc = \
+ spnego/accept_sec_context.c \
+ spnego/compat.c \
+ spnego/context_storage.c \
+ spnego/context_stubs.c \
+ spnego/external.c \
+ spnego/init_sec_context.c \
+ spnego/negoex_ctx.c \
+ spnego/negoex_util.c \
+ spnego/spnego_locl.h \
+ spnego/negoex_locl.h \
+ $(srcdir)/spnego/spnego-private.h
+
+ntlmsrc = \
+ ntlm/accept_sec_context.c \
+ ntlm/acquire_cred.c \
+ ntlm/add_cred.c \
+ ntlm/canonicalize_name.c \
+ ntlm/compare_name.c \
+ ntlm/context_time.c \
+ ntlm/creds.c \
+ ntlm/crypto.c \
+ ntlm/delete_sec_context.c \
+ ntlm/display_name.c \
+ ntlm/display_status.c \
+ ntlm/duplicate_name.c \
+ ntlm/export_name.c \
+ ntlm/export_sec_context.c \
+ ntlm/external.c \
+ ntlm/ntlm.h \
+ ntlm/import_name.c \
+ ntlm/import_sec_context.c \
+ ntlm/indicate_mechs.c \
+ ntlm/init_sec_context.c \
+ ntlm/inquire_context.c \
+ ntlm/inquire_cred_by_mech.c \
+ ntlm/inquire_mechs_for_name.c \
+ ntlm/inquire_names_for_mech.c \
+ ntlm/inquire_sec_context_by_oid.c \
+ ntlm/iter_cred.c \
+ ntlm/process_context_token.c \
+ ntlm/release_cred.c \
+ ntlm/release_name.c \
+ ntlm/set_sec_context_option.c \
+ ntlm/kdc.c
+
+$(srcdir)/ntlm/ntlm-private.h: $(ntlmsrc)
+ cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p ntlm/ntlm-private.h $(ntlmsrc) || rm -f ntlm/ntlm-private.h
+
+sanonsrc = \
+ sanon/accept_sec_context.c \
+ sanon/acquire_cred.c \
+ sanon/add_cred.c \
+ sanon/canonicalize_name.c \
+ sanon/compare_name.c \
+ sanon/context_time.c \
+ sanon/crypto.c \
+ sanon/delete_sec_context.c \
+ sanon/display_name.c \
+ sanon/display_status.c \
+ sanon/duplicate_cred.c \
+ sanon/duplicate_name.c \
+ sanon/export_name.c \
+ sanon/export_cred.c \
+ sanon/export_sec_context.c \
+ sanon/external.c \
+ sanon/import_cred.c \
+ sanon/import_name.c \
+ sanon/import_sec_context.c \
+ sanon/init_sec_context.c \
+ sanon/inquire_context.c \
+ sanon/inquire_cred.c \
+ sanon/inquire_cred_by_mech.c \
+ sanon/inquire_mechs_for_name.c \
+ sanon/inquire_names_for_mech.c \
+ sanon/inquire_sec_context_by_oid.c \
+ sanon/negoex.c \
+ sanon/process_context_token.c \
+ sanon/release_cred.c \
+ sanon/release_name.c \
+ sanon/sanon_locl.h \
+ sanon/sanon-private.h
+
+dist_libgssapi_la_SOURCES = \
+ $(krb5src) \
+ $(mechsrc) \
+ $(ntlmsrc) \
+ $(spnegosrc) \
+ $(sanonsrc)
+
+nodist_libgssapi_la_SOURCES = \
+ gkrb5_err.c \
+ gkrb5_err.h \
+ negoex_err.c \
+ negoex_err.h \
+ $(BUILT_SOURCES)
+
+libgssapi_la_DEPENDENCIES = version-script.map
+
+libgssapi_la_LDFLAGS = -version-info 3:0:0
+
+if versionscript
+libgssapi_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+endif
+
+libgssapi_la_LIBADD = \
+ $(top_builddir)/lib/ntlm/libheimntlm.la \
+ $(top_builddir)/lib/krb5/libkrb5.la \
+ $(top_builddir)/lib/asn1/libasn1.la \
+ $(LIB_com_err) \
+ $(LIB_hcrypto) \
+ $(LIBADD_roken)
+
+man_MANS = gssapi.3 gss_acquire_cred.3 mech/mech.5 gss-token.1
+
+include_HEADERS = gssapi.h
+noinst_HEADERS = \
+ gssapi_asn1.h \
+ gssapi_mech.h \
+ $(srcdir)/ntlm/ntlm-private.h \
+ $(srcdir)/spnego/spnego-private.h \
+ $(srcdir)/sanon/sanon-private.h \
+ $(srcdir)/krb5/gsskrb5-private.h
+
+nobase_include_HEADERS = \
+ gssapi/gssapi.h \
+ gssapi/gssapi_krb5.h \
+ gssapi/gssapi_ntlm.h \
+ gssapi/gssapi_oid.h \
+ gssapi/gssapi_spnego.h
+
+gssapidir = $(includedir)/gssapi
+nodist_gssapi_HEADERS = gkrb5_err.h negoex_err.h
+
+gssapi_files = \
+ asn1_GSSAPIContextToken.c
+
+spnego_files = \
+ asn1_ContextFlags.c \
+ asn1_MechType.c \
+ asn1_MechTypeList.c \
+ asn1_NegHints.c \
+ asn1_NegStateEnum.c \
+ asn1_NegTokenInit.c \
+ asn1_NegTokenInit2.c \
+ asn1_NegTokenResp.c \
+ asn1_NegotiationToken.c \
+ asn1_NegotiationToken2.c
+
+BUILTHEADERS = \
+ $(srcdir)/krb5/gsskrb5-private.h \
+ $(srcdir)/spnego/spnego-private.h \
+ $(srcdir)/sanon/sanon-private.h \
+ $(srcdir)/ntlm/ntlm-private.h
+
+$(libgssapi_la_OBJECTS): $(BUILTHEADERS)
+$(test_context_OBJECTS): $(BUILTHEADERS)
+
+$(libgssapi_la_OBJECTS): $(srcdir)/version-script.map
+
+BUILT_SOURCES = $(spnego_files) $(gssapi_files)
+
+$(libgssapi_la_OBJECTS): gkrb5_err.h negoex_err.h
+gkrb5_err.h: $(srcdir)/krb5/gkrb5_err.et
+negoex_err.h: $(srcdir)/spnego/negoex_err.et
+
+CLEANFILES = $(BUILT_SOURCES) \
+ gkrb5_err.[ch] negoex_err.[ch] \
+ $(spnego_files) spnego_asn1*.h* spnego_asn1_files spnego_asn1-template.[cx] \
+ $(gssapi_files) gssapi_asn1*.h* gssapi_asn1_files gssapi_asn1-template.[cx] \
+ gss-commands.h gss-commands.c \
+ gssapi_asn1.json gssapi_asn1_oids.c gssapi_asn1_syms.c \
+ spnego_asn1.json spnego_asn1_oids.c spnego_asn1_syms.c
+
+$(spnego_files) spnego_asn1.h spnego_asn1-priv.h: spnego_asn1_files
+ for genfile in '$(spnego_files)'; do \
+ $(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i $${genfile}; \
+ done
+
+$(gssapi_files) gssapi_asn1.h gssapi_asn1-priv.h: gssapi_asn1_files
+ for genfile in '$(gssapi_files)'; do \
+ $(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i $${genfile}; \
+ done
+
+spnego_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/spnego/spnego.asn1 $(srcdir)/spnego/spnego.opt
+ $(ASN1_COMPILE) --option-file=$(srcdir)/spnego/spnego.opt $(srcdir)/spnego/spnego.asn1 spnego_asn1
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i $$(cat spnego_asn1_files)
+
+gssapi_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/mech/gssapi.asn1
+ $(ASN1_COMPILE) $(srcdir)/mech/gssapi.asn1 gssapi_asn1
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i $$(cat gssapi_asn1_files)
+
+$(srcdir)/krb5/gsskrb5-private.h:
+ cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p krb5/gsskrb5-private.h $(krb5src) || rm -f krb5/gsskrb5-private.h
+
+$(srcdir)/spnego/spnego-private.h:
+ cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p spnego/spnego-private.h $(spnegosrc) || rm -f spnego/spnego-private.h
+
+$(srcdir)/sanon/sanon-private.h:
+ cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p sanon/sanon-private.h $(sanonsrc) || rm -f sanon/sanon-private.h
+
+TESTS = test_oid test_names test_cfx
+# test_sequence
+
+test_cfx_SOURCES = krb5/test_cfx.c
+
+check_PROGRAMS = test_acquire_cred $(TESTS)
+
+bin_PROGRAMS = gsstool gss-token
+noinst_PROGRAMS = test_cred test_kcred test_context test_ntlm test_add_store_cred
+
+test_context_SOURCES = test_context.c test_common.c test_common.h
+test_ntlm_SOURCES = test_ntlm.c test_common.c test_common.h
+test_acquire_cred_SOURCES = test_acquire_cred.c test_common.c test_common.h
+
+test_add_store_cred_SOURCES = test_add_store_cred.c
+
+test_ntlm_LDADD = \
+ $(top_builddir)/lib/ntlm/libheimntlm.la \
+ $(LDADD)
+
+LDADD = libgssapi.la \
+ $(top_builddir)/lib/krb5/libkrb5.la \
+ $(LIB_roken)
+
+test_names_LDADD = $(LDADD) $(top_builddir)/lib/asn1/libasn1.la
+test_context_LDADD = $(LDADD) $(top_builddir)/lib/asn1/libasn1.la $(top_builddir)/lib/wind/libwind.la
+
+# gss
+
+dist_gsstool_SOURCES = gsstool.c
+nodist_gsstool_SOURCES = gss-commands.c gss-commands.h
+dist_gss_token_SOURCES = gss-token.c
+
+gsstool_LDADD = libgssapi.la \
+ $(top_builddir)/lib/sl/libsl.la \
+ $(top_builddir)/lib/krb5/libkrb5.la \
+ $(LIB_readline) \
+ $(LIB_roken)
+
+gss_token_LDADD = libgssapi.la \
+ $(top_builddir)/lib/krb5/libkrb5.la \
+ $(LIB_roken)
+
+gss-commands.c gss-commands.h: gss-commands.in
+ $(SLC) $(srcdir)/gss-commands.in
+
+$(gsstool_OBJECTS): gss-commands.h
+
+EXTRA_DIST = \
+ NTMakefile \
+ libgssapi-version.rc \
+ libgssapi-exports.def \
+ $(man_MANS) \
+ gen-oid.pl \
+ gssapi/gssapi_netlogon.h \
+ krb5/test_acquire_cred.c \
+ krb5/test_cred.c \
+ krb5/test_kcred.c \
+ krb5/test_oid.c \
+ oid.txt \
+ krb5/gkrb5_err.et \
+ mech/gssapi.asn1 \
+ spnego/spnego.asn1 \
+ spnego/spnego.opt \
+ spnego/negoex_err.et \
+ test_negoex_mech.c \
+ version-script.map \
+ gss-commands.in
+
+$(libgssapi_la_OBJECTS): gkrb5_err.h gssapi_asn1.h gssapi_asn1-priv.h
+$(libgssapi_la_OBJECTS): spnego_asn1.h spnego_asn1-priv.h
+$(libgssapi_la_OBJECTS): $(srcdir)/gssapi/gssapi_oid.h
+
+gkrb5_err.h gkrb5_err.c: $(srcdir)/krb5/gkrb5_err.et
+ $(COMPILE_ET) $(srcdir)/krb5/gkrb5_err.et
+
+negoex_err.h negoex_err.c: $(srcdir)/spnego/negoex_err.et
+ $(COMPILE_ET) $(srcdir)/spnego/negoex_err.et
+
+$(srcdir)/gssapi/gssapi_oid.h $(srcdir)/mech/gss_oid.c:
+ perl $(srcdir)/gen-oid.pl -b base -h $(srcdir)/oid.txt > $(srcdir)/gssapi/gssapi_oid.h
+ perl $(srcdir)/gen-oid.pl -b base $(srcdir)/oid.txt > $(srcdir)/mech/gss_oid.c
+
+#
+# NegoEx test mechanism, uses decode_GSSAPIContextToken
+#
+
+test_negoex_mech_la_SOURCES = test_negoex_mech.c $(gssapi_files)
+test_negoex_mech_la_LDFLAGS = -module
+test_negoex_mech_la_LIBADD = \
+ $(top_builddir)/lib/asn1/libasn1.la \
+ libgssapi.la
diff --git a/third_party/heimdal/lib/gssapi/NTMakefile b/third_party/heimdal/lib/gssapi/NTMakefile
new file mode 100644
index 0000000..ffba9d5
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/NTMakefile
@@ -0,0 +1,747 @@
+########################################################################
+#
+# Copyright (c) 2009-2011 Secure Endpoints Inc.
+# Copyright (c) 2018 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\gssapi
+
+intcflags=-DASN1_LIB
+
+!include ../../windows/NTMakefile.w32
+
+krb5src = \
+ krb5/8003.c \
+ krb5/accept_sec_context.c \
+ krb5/acquire_cred.c \
+ krb5/add_cred.c \
+ krb5/address_to_krb5addr.c \
+ krb5/aeap.c \
+ krb5/arcfour.c \
+ krb5/authorize_localname.c \
+ krb5/canonicalize_name.c \
+ krb5/creds.c \
+ krb5/ccache_name.c \
+ krb5/cfx.c \
+ krb5/cfx.h \
+ krb5/compare_name.c \
+ krb5/compat.c \
+ krb5/context_time.c \
+ krb5/copy_ccache.c \
+ krb5/decapsulate.c \
+ krb5/delete_sec_context.c \
+ krb5/display_name.c \
+ krb5/display_status.c \
+ krb5/duplicate_name.c \
+ krb5/duplicate_cred.c \
+ krb5/encapsulate.c \
+ krb5/export_name.c \
+ krb5/export_sec_context.c \
+ krb5/external.c \
+ krb5/get_mic.c \
+ krb5/gsskrb5_locl.h \
+ krb5/import_name.c \
+ krb5/import_sec_context.c \
+ krb5/indicate_mechs.c \
+ krb5/init.c \
+ krb5/init_sec_context.c \
+ krb5/inquire_context.c \
+ krb5/inquire_cred.c \
+ krb5/inquire_cred_by_mech.c \
+ krb5/inquire_cred_by_oid.c \
+ krb5/inquire_mechs_for_name.c \
+ krb5/inquire_names_for_mech.c \
+ krb5/inquire_sec_context_by_oid.c \
+ krb5/name_attrs.c \
+ krb5/pname_to_uid.c \
+ krb5/process_context_token.c \
+ krb5/prf.c \
+ krb5/release_buffer.c \
+ krb5/release_cred.c \
+ krb5/release_name.c \
+ krb5/sequence.c \
+ krb5/store_cred.c \
+ krb5/set_cred_option.c \
+ krb5/set_sec_context_option.c \
+ krb5/ticket_flags.c \
+ krb5/unwrap.c \
+ krb5/verify_mic.c \
+ krb5/wrap.c
+
+mechsrc = \
+ mech/context.h \
+ mech/context.c \
+ mech/cred.h \
+ mech/cred.c \
+ mech/gss_accept_sec_context.c \
+ mech/gss_acquire_cred.c \
+ mech/gss_acquire_cred_from.c \
+ mech/gss_acquire_cred_impersonate_name.c \
+ mech/gss_acquire_cred_with_password.c \
+ mech/gss_add_cred.c \
+ mech/gss_add_cred_from.c \
+ mech/gss_add_cred_with_password.c \
+ mech/gss_add_oid_set_member.c \
+ mech/gss_aeap.c \
+ mech/gss_authorize_localname.c \
+ mech/gss_buffer_set.c \
+ mech/gss_canonicalize_name.c \
+ mech/gss_compare_name.c \
+ mech/gss_context_time.c \
+ mech/gss_create_empty_oid_set.c \
+ mech/gss_cred.c \
+ mech/gss_decapsulate_token.c \
+ mech/gss_delete_name_attribute.c \
+ mech/gss_delete_sec_context.c \
+ mech/gss_destroy_cred.c \
+ mech/gss_display_name.c \
+ mech/gss_display_name_ext.c \
+ mech/gss_display_status.c \
+ mech/gss_duplicate_name.c \
+ mech/gss_duplicate_cred.c \
+ mech/gss_duplicate_oid.c \
+ mech/gss_duplicate_oid_set.c \
+ mech/gss_encapsulate_token.c \
+ mech/gss_export_name.c \
+ mech/gss_export_name_composite.c \
+ mech/gss_export_sec_context.c \
+ mech/gss_get_mic.c \
+ mech/gss_get_neg_mechs.c \
+ mech/gss_get_name_attribute.c \
+ mech/gss_import_name.c \
+ mech/gss_import_sec_context.c \
+ mech/gss_indicate_mechs.c \
+ mech/gss_init_sec_context.c \
+ mech/gss_inquire_context.c \
+ mech/gss_inquire_cred.c \
+ mech/gss_inquire_cred_by_mech.c \
+ mech/gss_inquire_cred_by_oid.c \
+ mech/gss_inquire_mechs_for_name.c \
+ mech/gss_inquire_name.c \
+ mech/gss_inquire_names_for_mech.c \
+ mech/gss_krb5.c \
+ mech/gss_mech_switch.c \
+ mech/gss_mo.c \
+ mech/gss_names.c \
+ mech/gss_oid.c \
+ mech/gss_oid_equal.c \
+ mech/gss_oid_to_str.c \
+ mech/gss_pname_to_uid.c \
+ mech/gss_process_context_token.c \
+ mech/gss_pseudo_random.c \
+ mech/gss_release_buffer.c \
+ mech/gss_release_cred.c \
+ mech/gss_release_name.c \
+ mech/gss_release_oid.c \
+ mech/gss_release_oid_set.c \
+ mech/gss_rfc4121.c \
+ mech/gss_seal.c \
+ mech/gss_set_cred_option.c \
+ mech/gss_set_name_attribute.c \
+ mech/gss_set_neg_mechs.c \
+ mech/gss_set_sec_context_option.c \
+ mech/gss_sign.c \
+ mech/gss_store_cred.c \
+ mech/gss_store_cred_into.c \
+ mech/gss_test_oid_set_member.c \
+ mech/gss_unseal.c \
+ mech/gss_unwrap.c \
+ mech/gss_utils.c \
+ mech/gss_verify.c \
+ mech/gss_verify_mic.c \
+ mech/gss_wrap.c \
+ mech/gss_wrap_size_limit.c \
+ mech/gss_inquire_sec_context_by_oid.c \
+ mech/gssspi_exchange_meta_data.c \
+ mech/gssspi_query_mechanism_info.c \
+ mech/gssspi_query_meta_data.c \
+ mech/mech_switch.h \
+ mech/mech_locl.h \
+ mech/name.h \
+ mech/utils.h
+
+spnegosrc = \
+ spnego/accept_sec_context.c \
+ spnego/compat.c \
+ spnego/context_storage.c \
+ spnego/context_stubs.c \
+ spnego/external.c \
+ spnego/init_sec_context.c \
+ spnego/negoex_ctx.c \
+ spnego/negoex_util.c \
+ spnego/spnego_locl.h \
+ spnego/negoex_locl.h
+
+ntlmsrc = \
+ ntlm/accept_sec_context.c \
+ ntlm/acquire_cred.c \
+ ntlm/add_cred.c \
+ ntlm/canonicalize_name.c \
+ ntlm/compare_name.c \
+ ntlm/context_time.c \
+ ntlm/creds.c \
+ ntlm/crypto.c \
+ ntlm/delete_sec_context.c \
+ ntlm/display_name.c \
+ ntlm/display_status.c \
+ ntlm/duplicate_name.c \
+ ntlm/duplicate_cred.c \
+ ntlm/export_name.c \
+ ntlm/export_sec_context.c \
+ ntlm/external.c \
+ ntlm/ntlm.h \
+ ntlm/import_name.c \
+ ntlm/import_sec_context.c \
+ ntlm/indicate_mechs.c \
+ ntlm/init_sec_context.c \
+ ntlm/inquire_context.c \
+ ntlm/inquire_cred_by_mech.c \
+ ntlm/inquire_mechs_for_name.c \
+ ntlm/inquire_names_for_mech.c \
+ ntlm/inquire_sec_context_by_oid.c \
+ ntlm/iter_cred.c \
+ ntlm/process_context_token.c \
+ ntlm/release_cred.c \
+ ntlm/release_name.c \
+ ntlm/set_sec_context_option.c \
+ ntlm/kdc.c
+
+sanonsrc = \
+ sanon/accept_sec_context.c \
+ sanon/acquire_cred.c \
+ sanon/add_cred.c \
+ sanon/canonicalize_name.c \
+ sanon/compare_name.c \
+ sanon/context_time.c \
+ sanon/crypto.c \
+ sanon/delete_sec_context.c \
+ sanon/display_name.c \
+ sanon/display_status.c \
+ sanon/duplicate_cred.c \
+ sanon/duplicate_name.c \
+ sanon/export_cred.c \
+ sanon/export_name.c \
+ sanon/export_sec_context.c \
+ sanon/external.c \
+ sanon/import_cred.c \
+ sanon/import_name.c \
+ sanon/import_sec_context.c \
+ sanon/init_sec_context.c \
+ sanon/inquire_context.c \
+ sanon/inquire_cred.c \
+ sanon/inquire_cred_by_mech.c \
+ sanon/inquire_mechs_for_name.c \
+ sanon/inquire_names_for_mech.c \
+ sanon/inquire_sec_context_by_oid.c \
+ sanon/negoex.c \
+ sanon/process_context_token.c \
+ sanon/release_cred.c \
+ sanon/release_name.c
+
+$(OBJ)\ntlm\ntlm-private.h: $(ntlmsrc)
+ $(PERL) ../../cf/make-proto.pl -q -P remove -p $@ $(ntlmsrc)
+
+$(OBJ)\krb5\gsskrb5-private.h: $(krb5src)
+ $(PERL) ../../cf/make-proto.pl -q -P remove -p $@ $(krb5src)
+
+$(OBJ)\spnego\spnego-private.h: $(spnegosrc)
+ $(PERL) ../../cf/make-proto.pl -q -P remove -p $@ $(spnegosrc)
+
+$(OBJ)\sanon\sanon-private.h: $(sanonsrc)
+ $(PERL) ../../cf/make-proto.pl -q -P remove -p $@ $(sanonsrc)
+
+$(OBJ)\gssapi\asn1_gssapi_asn1.c $(OBJ)\gssapi\gssapi_asn1.h $(OBJ)\gssapi\gssapi_asn1-priv.h: \
+$(BINDIR)\asn1_compile.exe mech\gssapi.asn1
+ cd $(OBJ)\gssapi
+ $(BINDIR)\asn1_compile.exe --one-code-file $(SRCDIR)\mech\gssapi.asn1 gssapi_asn1 \
+ || ( $(RM) $(OBJ)\gssapi\gssapi_asn1.h ; exit /b 1 )
+ cd $(SRCDIR)
+
+$(OBJ)\spnego\asn1_spnego_asn1.c $(OBJ)\spnego\spnego_asn1.h $(OBJ)\spnego\spnego_asn1-priv.h: \
+$(BINDIR)\asn1_compile.exe spnego\spnego.asn1
+ cd $(OBJ)\spnego
+ $(BINDIR)\asn1_compile --one-code-file --sequence=MechTypeList \
+ $(SRCDIR)\spnego\spnego.asn1 spnego_asn1 \
+ || ( $(RM) $(OBJ)\spnego\spnego_asn1.h ; exit /b 1 )
+ cd $(SRCDIR)
+
+$(OBJ)\gkrb5_err.c $(OBJ)\gkrb5_err.h: krb5\gkrb5_err.et
+ cd $(OBJ)
+ $(BINDIR)\compile_et.exe $(SRCDIR)\krb5\gkrb5_err.et
+ cd $(SRCDIR)
+
+$(OBJ)\negoex_err.c $(OBJ)\negoex_err.h: spnego\negoex_err.et
+ cd $(OBJ)
+ $(BINDIR)\compile_et.exe $(SRCDIR)\spnego\negoex_err.et
+ cd $(SRCDIR)
+
+INCFILES= \
+ $(INCDIR)\gssapi.h \
+ $(INCDIR)\gssapi\gssapi.h \
+ $(INCDIR)\gssapi\gssapi_krb5.h \
+ $(INCDIR)\gssapi\gssapi_oid.h \
+ $(INCDIR)\gssapi\gssapi_ntlm.h \
+ $(INCDIR)\gssapi\gssapi_spnego.h \
+ $(INCDIR)\gssapi\gkrb5_err.h \
+ $(OBJ)\ntlm\ntlm-private.h \
+ $(OBJ)\spnego\spnego-private.h \
+ $(OBJ)\sanon\sanon-private.h \
+ $(OBJ)\krb5\gsskrb5-private.h \
+ $(OBJ)\gkrb5_err.h \
+ $(OBJ)\negoex_err.h \
+ $(OBJ)\gssapi\gssapi_asn1.h \
+ $(OBJ)\gssapi\gssapi_asn1-priv.h \
+ $(OBJ)\spnego\spnego_asn1.h \
+ $(OBJ)\spnego\spnego_asn1-priv.h
+
+all:: $(INCFILES)
+
+libgssapi_OBJs = \
+ $(OBJ)\krb5/8003.obj \
+ $(OBJ)\krb5/accept_sec_context.obj \
+ $(OBJ)\krb5/acquire_cred.obj \
+ $(OBJ)\krb5/add_cred.obj \
+ $(OBJ)\krb5/address_to_krb5addr.obj \
+ $(OBJ)\krb5/authorize_localname.obj \
+ $(OBJ)\krb5/aeap.obj \
+ $(OBJ)\krb5/arcfour.obj \
+ $(OBJ)\krb5/canonicalize_name.obj \
+ $(OBJ)\krb5/creds.obj \
+ $(OBJ)\krb5/ccache_name.obj \
+ $(OBJ)\krb5/cfx.obj \
+ $(OBJ)\krb5/compare_name.obj \
+ $(OBJ)\krb5/compat.obj \
+ $(OBJ)\krb5/context_time.obj \
+ $(OBJ)\krb5/copy_ccache.obj \
+ $(OBJ)\krb5/decapsulate.obj \
+ $(OBJ)\krb5/delete_sec_context.obj \
+ $(OBJ)\krb5/display_name.obj \
+ $(OBJ)\krb5/display_status.obj \
+ $(OBJ)\krb5/duplicate_cred.obj \
+ $(OBJ)\krb5/duplicate_name.obj \
+ $(OBJ)\krb5/encapsulate.obj \
+ $(OBJ)\krb5/export_name.obj \
+ $(OBJ)\krb5/export_sec_context.obj \
+ $(OBJ)\krb5/external.obj \
+ $(OBJ)\krb5/get_mic.obj \
+ $(OBJ)\krb5/import_name.obj \
+ $(OBJ)\krb5/import_sec_context.obj \
+ $(OBJ)\krb5/indicate_mechs.obj \
+ $(OBJ)\krb5/init.obj \
+ $(OBJ)\krb5/init_sec_context.obj \
+ $(OBJ)\krb5/inquire_context.obj \
+ $(OBJ)\krb5/inquire_cred.obj \
+ $(OBJ)\krb5/inquire_cred_by_mech.obj \
+ $(OBJ)\krb5/inquire_cred_by_oid.obj \
+ $(OBJ)\krb5/inquire_mechs_for_name.obj \
+ $(OBJ)\krb5/inquire_names_for_mech.obj \
+ $(OBJ)\krb5/inquire_sec_context_by_oid.obj \
+ $(OBJ)\krb5/name_attrs.obj \
+ $(OBJ)\krb5/pname_to_uid.obj \
+ $(OBJ)\krb5/process_context_token.obj \
+ $(OBJ)\krb5/prf.obj \
+ $(OBJ)\krb5/release_buffer.obj \
+ $(OBJ)\krb5/release_cred.obj \
+ $(OBJ)\krb5/release_name.obj \
+ $(OBJ)\krb5/sequence.obj \
+ $(OBJ)\krb5/store_cred.obj \
+ $(OBJ)\krb5/set_cred_option.obj \
+ $(OBJ)\krb5/set_sec_context_option.obj \
+ $(OBJ)\krb5/ticket_flags.obj \
+ $(OBJ)\krb5/unwrap.obj \
+ $(OBJ)\krb5/verify_mic.obj \
+ $(OBJ)\krb5/wrap.obj \
+ $(OBJ)\mech/context.obj \
+ $(OBJ)\mech/cred.obj \
+ $(OBJ)\mech/gss_accept_sec_context.obj \
+ $(OBJ)\mech/gss_acquire_cred.obj \
+ $(OBJ)\mech/gss_acquire_cred_from.obj \
+ $(OBJ)\mech/gss_acquire_cred_impersonate_name.obj \
+ $(OBJ)\mech/gss_acquire_cred_with_password.obj \
+ $(OBJ)\mech/gss_add_cred.obj \
+ $(OBJ)\mech/gss_add_cred_from.obj \
+ $(OBJ)\mech/gss_add_cred_with_password.obj \
+ $(OBJ)\mech/gss_add_oid_set_member.obj \
+ $(OBJ)\mech/gss_aeap.obj \
+ $(OBJ)\mech/gss_authorize_localname.obj \
+ $(OBJ)\mech/gss_buffer_set.obj \
+ $(OBJ)\mech/gss_canonicalize_name.obj \
+ $(OBJ)\mech/gss_compare_name.obj \
+ $(OBJ)\mech/gss_context_time.obj \
+ $(OBJ)\mech/gss_create_empty_oid_set.obj \
+ $(OBJ)\mech/gss_cred.obj \
+ $(OBJ)\mech/gss_decapsulate_token.obj \
+ $(OBJ)\mech/gss_delete_name_attribute.obj \
+ $(OBJ)\mech/gss_delete_sec_context.obj \
+ $(OBJ)\mech/gss_destroy_cred.obj \
+ $(OBJ)\mech/gss_display_name.obj \
+ $(OBJ)\mech/gss_display_name_ext.obj \
+ $(OBJ)\mech/gss_display_status.obj \
+ $(OBJ)\mech/gss_duplicate_cred.obj \
+ $(OBJ)\mech/gss_duplicate_name.obj \
+ $(OBJ)\mech/gss_duplicate_oid.obj \
+ $(OBJ)\mech/gss_duplicate_oid_set.obj \
+ $(OBJ)\mech/gss_encapsulate_token.obj \
+ $(OBJ)\mech/gss_export_name.obj \
+ $(OBJ)\mech/gss_export_name_composite.obj \
+ $(OBJ)\mech/gss_export_sec_context.obj \
+ $(OBJ)\mech/gss_get_mic.obj \
+ $(OBJ)\mech/gss_get_neg_mechs.obj \
+ $(OBJ)\mech/gss_get_name_attribute.obj \
+ $(OBJ)\mech/gss_import_name.obj \
+ $(OBJ)\mech/gss_import_sec_context.obj \
+ $(OBJ)\mech/gss_indicate_mechs.obj \
+ $(OBJ)\mech/gss_init_sec_context.obj \
+ $(OBJ)\mech/gss_inquire_context.obj \
+ $(OBJ)\mech/gss_inquire_cred.obj \
+ $(OBJ)\mech/gss_inquire_cred_by_mech.obj \
+ $(OBJ)\mech/gss_inquire_cred_by_oid.obj \
+ $(OBJ)\mech/gss_inquire_mechs_for_name.obj \
+ $(OBJ)\mech/gss_inquire_name.obj \
+ $(OBJ)\mech/gss_inquire_names_for_mech.obj \
+ $(OBJ)\mech/gss_krb5.obj \
+ $(OBJ)\mech/gss_mech_switch.obj \
+ $(OBJ)\mech/gss_mo.obj \
+ $(OBJ)\mech/gss_names.obj \
+ $(OBJ)\mech/gss_oid.obj \
+ $(OBJ)\mech/gss_oid_equal.obj \
+ $(OBJ)\mech/gss_oid_to_str.obj \
+ $(OBJ)\mech/gss_pname_to_uid.obj \
+ $(OBJ)\mech/gss_process_context_token.obj \
+ $(OBJ)\mech/gss_pseudo_random.obj \
+ $(OBJ)\mech/gss_release_buffer.obj \
+ $(OBJ)\mech/gss_release_cred.obj \
+ $(OBJ)\mech/gss_release_name.obj \
+ $(OBJ)\mech/gss_release_oid.obj \
+ $(OBJ)\mech/gss_release_oid_set.obj \
+ $(OBJ)\mech/gss_rfc4121.obj \
+ $(OBJ)\mech/gss_seal.obj \
+ $(OBJ)\mech/gss_set_cred_option.obj \
+ $(OBJ)\mech/gss_set_name_attribute.obj \
+ $(OBJ)\mech/gss_set_neg_mechs.obj \
+ $(OBJ)\mech/gss_set_sec_context_option.obj \
+ $(OBJ)\mech/gss_sign.obj \
+ $(OBJ)\mech/gss_store_cred.obj \
+ $(OBJ)\mech/gss_store_cred_into.obj \
+ $(OBJ)\mech/gss_test_oid_set_member.obj \
+ $(OBJ)\mech/gss_unseal.obj \
+ $(OBJ)\mech/gss_unwrap.obj \
+ $(OBJ)\mech/gss_utils.obj \
+ $(OBJ)\mech/gss_verify.obj \
+ $(OBJ)\mech/gss_verify_mic.obj \
+ $(OBJ)\mech/gss_wrap.obj \
+ $(OBJ)\mech/gss_wrap_size_limit.obj \
+ $(OBJ)\mech/gss_inquire_sec_context_by_oid.obj \
+ $(OBJ)\mech/gssspi_exchange_meta_data.obj \
+ $(OBJ)\mech/gssspi_query_mechanism_info.obj \
+ $(OBJ)\mech/gssspi_query_meta_data.obj \
+ $(OBJ)\spnego/accept_sec_context.obj \
+ $(OBJ)\spnego/compat.obj \
+ $(OBJ)\spnego/context_storage.obj \
+ $(OBJ)\spnego/context_stubs.obj \
+ $(OBJ)\spnego/external.obj \
+ $(OBJ)\spnego/init_sec_context.obj \
+ $(OBJ)\spnego/negoex_ctx.obj \
+ $(OBJ)\spnego/negoex_util.obj \
+ $(OBJ)\ntlm/accept_sec_context.obj \
+ $(OBJ)\ntlm/acquire_cred.obj \
+ $(OBJ)\ntlm/add_cred.obj \
+ $(OBJ)\ntlm/canonicalize_name.obj \
+ $(OBJ)\ntlm/compare_name.obj \
+ $(OBJ)\ntlm/context_time.obj \
+ $(OBJ)\ntlm/creds.obj \
+ $(OBJ)\ntlm/crypto.obj \
+ $(OBJ)\ntlm/delete_sec_context.obj \
+ $(OBJ)\ntlm/display_name.obj \
+ $(OBJ)\ntlm/display_status.obj \
+ $(OBJ)\ntlm/duplicate_cred.obj \
+ $(OBJ)\ntlm/duplicate_name.obj \
+ $(OBJ)\ntlm/export_name.obj \
+ $(OBJ)\ntlm/export_sec_context.obj \
+ $(OBJ)\ntlm/external.obj \
+ $(OBJ)\ntlm/import_name.obj \
+ $(OBJ)\ntlm/import_sec_context.obj \
+ $(OBJ)\ntlm/indicate_mechs.obj \
+ $(OBJ)\ntlm/init_sec_context.obj \
+ $(OBJ)\ntlm/inquire_context.obj \
+ $(OBJ)\ntlm/inquire_cred_by_mech.obj \
+ $(OBJ)\ntlm/inquire_mechs_for_name.obj \
+ $(OBJ)\ntlm/inquire_names_for_mech.obj \
+ $(OBJ)\ntlm/inquire_sec_context_by_oid.obj \
+ $(OBJ)\ntlm/iter_cred.obj \
+ $(OBJ)\ntlm/process_context_token.obj \
+ $(OBJ)\ntlm/release_cred.obj \
+ $(OBJ)\ntlm/release_name.obj \
+ $(OBJ)\ntlm/set_sec_context_option.obj \
+ $(OBJ)\ntlm/kdc.obj \
+ $(OBJ)\sanon/accept_sec_context.obj \
+ $(OBJ)\sanon/acquire_cred.obj \
+ $(OBJ)\sanon/add_cred.obj \
+ $(OBJ)\sanon/canonicalize_name.obj \
+ $(OBJ)\sanon/compare_name.obj \
+ $(OBJ)\sanon/context_time.obj \
+ $(OBJ)\sanon/crypto.obj \
+ $(OBJ)\sanon/delete_sec_context.obj \
+ $(OBJ)\sanon/display_name.obj \
+ $(OBJ)\sanon/display_status.obj \
+ $(OBJ)\sanon/duplicate_cred.obj \
+ $(OBJ)\sanon/duplicate_name.obj \
+ $(OBJ)\sanon/export_cred.obj \
+ $(OBJ)\sanon/export_name.obj \
+ $(OBJ)\sanon/export_sec_context.obj \
+ $(OBJ)\sanon/external.obj \
+ $(OBJ)\sanon/import_cred.obj \
+ $(OBJ)\sanon/import_name.obj \
+ $(OBJ)\sanon/import_sec_context.obj \
+ $(OBJ)\sanon/init_sec_context.obj \
+ $(OBJ)\sanon/inquire_context.obj \
+ $(OBJ)\sanon/inquire_cred.obj \
+ $(OBJ)\sanon/inquire_cred_by_mech.obj \
+ $(OBJ)\sanon/inquire_mechs_for_name.obj \
+ $(OBJ)\sanon/inquire_names_for_mech.obj \
+ $(OBJ)\sanon/inquire_sec_context_by_oid.obj \
+ $(OBJ)\sanon/negoex.obj \
+ $(OBJ)\sanon/process_context_token.obj \
+ $(OBJ)\sanon/release_cred.obj \
+ $(OBJ)\sanon/release_name.obj \
+ $(OBJ)\gkrb5_err.obj \
+ $(OBJ)\negoex_err.obj \
+ $(OBJ)\spnego\asn1_spnego_asn1.obj \
+ $(OBJ)\gssapi\asn1_gssapi_asn1.obj
+
+GCOPTS=-I$(SRCDIR) -I$(OBJ) -Igssapi -DBUILD_GSSAPI_LIB
+
+{$(OBJ)\krb5}.c{$(OBJ)\krb5}.obj::
+ $(C2OBJ_NP) -Fo$(OBJ)\krb5\ -Fd$(OBJ)\krb5\ -I$(OBJ)\krb5 $(GCOPTS)
+
+{krb5}.c{$(OBJ)\krb5}.obj::
+ $(C2OBJ_NP) -Fo$(OBJ)\krb5\ -Fd$(OBJ)\krb5\ -I$(OBJ)\krb5 $(GCOPTS) -DASN1_LIB
+
+{$(OBJ)\mech}.c{$(OBJ)\mech}.obj::
+ $(C2OBJ_NP) -Fo$(OBJ)\mech\ -Fd$(OBJ)\mech\ -I$(OBJ)\mech $(GCOPTS)
+
+{mech}.c{$(OBJ)\mech}.obj::
+ $(C2OBJ_NP) -Fo$(OBJ)\mech\ -Fd$(OBJ)\mech\ -I$(OBJ)\mech -I$(OBJ)\gssapi $(GCOPTS) -DASN1_LIB
+
+{$(OBJ)\ntlm}.c{$(OBJ)\ntlm}.obj::
+ $(C2OBJ_NP) -Fo$(OBJ)\ntlm\ -Fd$(OBJ)\ntlm\ -I$(OBJ)\ntlm $(GCOPTS)
+
+{ntlm}.c{$(OBJ)\ntlm}.obj::
+ $(C2OBJ_NP) -Fo$(OBJ)\ntlm\ -Fd$(OBJ)\ntlm\ -I$(OBJ)\ntlm $(GCOPTS) -DASN1_LIB
+
+{$(OBJ)\spnego}.c{$(OBJ)\spnego}.obj::
+ $(C2OBJ_NP) -Fo$(OBJ)\spnego\ -Fd$(OBJ)\spnego\ -I$(OBJ)\spnego $(GCOPTS)
+
+{spnego}.c{$(OBJ)\spnego}.obj::
+ $(C2OBJ_NP) -Fo$(OBJ)\spnego\ -Fd$(OBJ)\spnego\ -I$(OBJ)\spnego -Imech $(GCOPTS) -DASN1_LIB
+
+{$(OBJ)\sanon}.c{$(OBJ)\sanon}.obj::
+ $(C2OBJ_NP) -Fo$(OBJ)\sanon\ -Fd$(OBJ)\sanon\ -I$(OBJ)\sanon -I$(OBJ) -I$(OBJ)\krb5 -I$(OBJ)\gssapi -Ikrb5 -Imech -Igssapi $(GCOPTS)
+
+{sanon}.c{$(OBJ)\sanon}.obj::
+ $(C2OBJ_NP) -Fo$(OBJ)\sanon\ -Fd$(OBJ)\sanon\ -I$(OBJ)\sanon -I$(OBJ) -I$(OBJ)\krb5 -I$(OBJ)\gssapi -Ikrb5 -Imech -Igssapi $(GCOPTS) -DASN1_LIB
+
+{$(OBJ)\gssapi}.c{$(OBJ)\gssapi}.obj::
+ $(C2OBJ_NP) -Fo$(OBJ)\gssapi\ -Fd$(OBJ)\gssapi\ -I$(OBJ)\gssapi $(GCOPTS)
+
+{$(OBJ)}.c{$(OBJ)}.obj::
+ $(C2OBJ_P) $(GCOPTS)
+
+{gssapi}.h{$(INCDIR)\gssapi}.h:
+ $(CP) $** $@
+
+{$(OBJ)}.h{$(INCDIR)\gssapi}.h:
+ $(CP) $** $@
+
+LIBGSSAPI_LIBS=\
+ $(LIBHEIMBASE) \
+ $(LIBROKEN) \
+ $(LIBHEIMDAL) \
+ $(LIBHEIMNTLM) \
+ $(LIBCOMERR)
+
+LIBGSSAPI_SDKLIBS=\
+ $(PTHREAD_LIB) \
+ Secur32.lib Shell32.lib Advapi32.lib
+
+!ifndef STATICLIBS
+
+RES=$(OBJ)\libgssapi-version.res
+
+$(BINDIR)\gssapi.dll: $(libgssapi_OBJs) $(RES)
+ $(DLLGUILINK_C) -implib:$(LIBGSSAPI) \
+ -out:$(BINDIR)\gssapi.dll \
+ -def:libgssapi-exports.def \
+ $(LIBGSSAPI_LIBS) $(RES) $(LIBGSSAPI_SDKLIBS) @<<
+$(libgssapi_OBJs: =
+)
+<<
+ $(DLLPREP_NODIST)
+
+$(LIBGSSAPI): $(BINDIR)\gssapi.dll
+
+clean::
+ -$(RM) $(BINDIR)\gssapi.*
+
+!else
+
+$(LIBGSSAPI): $(libgssapi_OBJs)
+ $(LIBCON_C) -OUT:$@ $(LIBGSSAPI_LIBS) $(LIBGSSAPI_SDKLIBS) @<<
+$(libgssapi_OBJs: =
+)
+<<
+
+!endif
+
+all:: $(LIBGSSAPI)
+
+clean::
+ -$(RM) $(LIBGSSAPI)
+
+prep:: mkdirs-gss
+
+mkdirs-gss:
+!if !exist($(OBJ)\ntlm)
+ $(MKDIR) $(OBJ)\ntlm
+!endif
+!if !exist($(OBJ)\krb5)
+ $(MKDIR) $(OBJ)\krb5
+!endif
+!if !exist($(OBJ)\spnego)
+ $(MKDIR) $(OBJ)\spnego
+!endif
+!if !exist($(OBJ)\sanon)
+ $(MKDIR) $(OBJ)\sanon
+!endif
+!if !exist($(OBJ)\mech)
+ $(MKDIR) $(OBJ)\mech
+!endif
+!if !exist($(OBJ)\gssapi)
+ $(MKDIR) $(OBJ)\gssapi
+!endif
+
+clean::
+ -$(RM) $(OBJ)\ntlm\*.*
+ -$(RM) $(OBJ)\krb5\*.*
+ -$(RM) $(OBJ)\spnego\*.*
+ -$(RM) $(OBJ)\mech\*.*
+ -$(RM) $(OBJ)\sanon\*.*
+ -$(RM) $(OBJ)\gssapi\*.*
+
+all-tools:: $(BINDIR)\gsstool.exe
+
+$(BINDIR)\gsstool.exe: $(OBJ)\gsstool.obj $(OBJ)\gss-commands.obj $(LIBGSSAPI) $(LIBROKEN) $(LIBSL) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP)
+
+$(OBJ)\gss-commands.c $(OBJ)\gss-commands.h: gss-commands.in
+ cd $(OBJ)
+ $(CP) $(SRCDIR)\gss-commands.in gss-commands.in
+ $(BINDIR)\slc.exe gss-commands.in
+ cd $(SRCDIR)
+
+!ifdef ELISP
+# This macro invocation is used to update the libgssapi_OBJs
+# definition below (generate-obj-macro is defined in maint.el):
+
+(generate-obj-macro "libgssapi_OBJs"
+ (concat "\t$(OBJ)\\gkrb5_err.obj \\\n"
+ "\t$(OBJ)\\negoex_err.obj \\\n"
+ "\t$(OBJ)\\spnego\\asn1_spnego_asn1.obj \\\n"
+ "\t$(OBJ)\\gssapi\\asn1_gssapi_asn1.obj")
+ "krb5src" "mechsrc" "spnegosrc" "ntlmsrc")
+!endif
+
+test-exports:
+ $(PERL) ..\..\cf\w32-check-exported-symbols.pl --vs version-script.map --def libgssapi-exports.def
+
+test:: test-exports
+
+
+TEST_BINARIES=\
+ $(OBJ)\test_oid.exe \
+ $(OBJ)\test_names.exe \
+ $(OBJ)\test_cfx.exe \
+ $(OBJ)\test_acquire_cred.exe \
+ $(OBJ)\test_cred.exe \
+ $(OBJ)\test_kcred.exe \
+ $(OBJ)\test_context.exe \
+ $(OBJ)\test_ntlm.exe
+
+$(OBJ)\test_oid.exe: $(OBJ)\test_oid.obj $(LIBGSSAPI) $(LIBROKEN)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_names.exe: $(OBJ)\test_names.obj $(LIBGSSAPI) $(LIBHEIMDAL) $(LIBROKEN) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_cfx.exe: $(OBJ)\krb5\test_cfx.obj $(LIBHEIMDAL) $(LIBGSSAPI) $(LIBROKEN)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_acquire_cred.exe: $(OBJ)\test_acquire_cred.obj $(OBJ)\test_common.obj \
+ $(LIBGSSAPI) $(LIBROKEN) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_cred.exe: $(OBJ)\test_cred.obj $(LIBGSSAPI) $(LIBROKEN) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_kcred.exe: $(OBJ)\test_kcred.obj $(LIBGSSAPI) $(LIBHEIMDAL) \
+ $(LIBROKEN) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_context.exe: $(OBJ)\test_context.obj $(OBJ)\test_common.obj \
+ $(LIBGSSAPI) $(LIBHEIMDAL) $(LIBROKEN) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_ntlm.exe: $(OBJ)\test_ntlm.obj $(OBJ)\test_common.obj \
+ $(LIBGSSAPI) $(LIBHEIMNTLM) $(LIBROKEN) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+{}.c{$(OBJ)}.obj::
+ $(C2OBJ_P) -I$(OBJ)\krb5 -I$(OBJ) -I$(SRCDIR) -I$(SRCDIR)\gssapi
+
+test-binaries: $(LIBGSSAPI) $(TEST_BINARIES)
+
+run-test:
+ cd $(OBJ)
+ -test_oid
+ -test_names
+ -test_cfx
+ -test_kcred
+ cd $(SRCDIR)
+
+test:: test-binaries run-test
diff --git a/third_party/heimdal/lib/gssapi/gen-oid.pl b/third_party/heimdal/lib/gssapi/gen-oid.pl
new file mode 100644
index 0000000..d635f28
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gen-oid.pl
@@ -0,0 +1,149 @@
+#!/usr/bin/perl
+#
+# Copyright (c) 2010 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+use Getopt::Std;
+
+my $output;
+my $CFILE, $HFILE;
+my $onlybase;
+my $header = 0;
+
+getopts('b:h') || die "USAGE: ./gen-oid [-b BASE] [-h HEADER]";
+
+if($opt_b) {
+ $onlybase = $opt_b;
+}
+
+$header = 1 if ($opt_h);
+
+printf "/* Generated file */\n";
+if ($header) {
+ printf "#ifndef GSSAPI_GSSAPI_OID\n";
+ printf "#define GSSAPI_GSSAPI_OID 1\n\n";
+} else {
+ printf "#include \"mech_locl.h\"\n\n";
+}
+
+my %tables;
+my %types;
+
+while(<>) {
+
+ if (/^\w*#(.*)/) {
+ my $comment = $1;
+
+ if ($header) {
+ printf("$comment\n");
+ }
+
+ } elsif (/^oid\s+([\w\.]+)\s+(\w+)\s+([\w\.]+)/) {
+ my ($base, $name, $oid) = ($1, $2, $3);
+
+ next if (defined $onlybase and $onlybase ne $base);
+
+ my $store = "__" . lc($name) . "_oid_desc";
+
+ # encode oid
+
+ my @array = split(/\./, $oid);
+ my $length = 0;
+ my $data = "";
+
+ my $num;
+
+ $n = $#array;
+ while ($n > 1) {
+ $num = $array[$n];
+
+ my $p = int($num % 128);
+ $data = sprintf("\\x%02x", $p) . $data;
+
+ $num = int($num / 128);
+
+ $length += 1;
+
+ while ($num > 0) {
+ $p = int($num % 128) + 128;
+ $num = int($num / 128);
+ $data = sprintf("\\x%02x", $p) . $data;
+ $length += 1;
+ }
+ $n--;
+ }
+ $num = int($array[0] * 40 + $array[1]);
+
+ $data = sprintf("\\x%x", $num) . $data;
+ $length += 1;
+
+ if ($header) {
+ printf "extern GSSAPI_LIB_VARIABLE gss_OID_desc $store;\n";
+ printf "#define $name (&$store)\n\n";
+ } else {
+ printf "/* $name - $oid */\n";
+ printf "gss_OID_desc GSSAPI_LIB_VARIABLE $store = { $length, rk_UNCONST(\"$data\") };\n\n";
+ }
+ push(@oidstorage, $store);
+ } elsif (/^desc\s+([\w]+)\s+(\w+)\s+(\"[^\"]*\")\s+(\"[^\"]*\")/) {
+ my ($type, $oid, $short, $long) = ($1, $2, $3, $4);
+ my $object = { type=> $type, oid => $oid, short => $short, long => $long };
+
+ $tables{$oid} = \$object;
+ $types{$type} = 1;
+ }
+
+}
+
+foreach my $k (sort keys %types) {
+ if (!$header) {
+ print "struct _gss_oid_name_table _gss_ont_" . $k . "[] = {\n";
+ foreach my $m (sort {$$a->{oid} cmp $$b->{oid}} values %tables) {
+ if ($$m->{type} eq $k) {
+ printf " { %s, \"%s\", %s, %s },\n", $$m->{oid}, $$m->{oid}, $$m->{short}, $$m->{long};
+ }
+ }
+ printf " { NULL, NULL, NULL, NULL }\n";
+ printf "};\n\n";
+
+ }
+}
+
+if ($header) {
+ printf "#endif /* GSSAPI_GSSAPI_OID */\n";
+} else {
+ printf "gss_OID _gss_ot_internal[] = {\n";
+ foreach my $k (@oidstorage) {
+ print " &$k,\n";
+ }
+ printf "};\n\n";
+ printf "size_t _gss_ot_internal_count = sizeof(_gss_ot_internal) / sizeof(_gss_ot_internal[0]);\n";
+}
diff --git a/third_party/heimdal/lib/gssapi/gss-commands.in b/third_party/heimdal/lib/gssapi/gss-commands.in
new file mode 100644
index 0000000..25ec1c8
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gss-commands.in
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+/* $Id$ */
+
+command = {
+ name = "mechanisms"
+ name = "supported-mechanisms"
+ help = "Print the supported mechanisms"
+}
+command = {
+ name = "attributes"
+ name = "attrs-for-mech"
+ help = "Print the attributes for mechs"
+ option = {
+ long = "all"
+ type = "flag"
+ }
+ option = {
+ long = "mech"
+ type = "string"
+ argument = "mechanism"
+ }
+}
+command = {
+ name = "help"
+ name = "?"
+ argument = "[command]"
+ min_args = "0"
+ max_args = "1"
+ help = "Help! I need somebody."
+}
diff --git a/third_party/heimdal/lib/gssapi/gss-token.1 b/third_party/heimdal/lib/gssapi/gss-token.1
new file mode 100644
index 0000000..7bd50b0
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gss-token.1
@@ -0,0 +1,108 @@
+.\"
+.\"
+.Dd May 12, 2014
+.Os
+.Dt GSS-TOKEN 1
+.Sh NAME
+.Nm gss-token
+.Nd generate and consume base64 GSS tokens
+.Sh SYNOPSIS
+.Nm
+.Op Fl DNn
+.Op Fl c count
+.Ar service@host
+.Nm
+.Fl r
+.Op Fl MNln
+.Op Fl C Ar ccache
+.Op Fl S Ar maxsize
+.Op Fl c count
+.Op Fl m mech
+.Op Ar service@host
+.Sh DESCRIPTION
+.Nm
+generates and consumes base64 encoded GSS tokens.
+By default, it runs as an initiator and with the
+.Fl r
+flag it becomes an acceptor.
+.Pp
+.Nm
+supports the following options:
+.Bl -tag -width indentxxxx
+.It Fl C Ar ccache
+write an accepted delegated credential into
+.Ar ccache .
+This only makes sense if
+.Fl r
+is specified.
+.It Fl D
+delegate credentials.
+This only makes sense as a client, that is when
+.Fl r
+is not specified.
+.It Fl M
+copy the default ccache to a MEMORY: ccache before each
+separate write operation.
+The default ccache will not pick up any obtained service
+tickets.
+If specified with
+.Fl c ,
+the cache will revert to its original state before each
+new token is written.
+This can be used to load test the KDC.
+.It Fl N
+prepend
+.Dq Negotiate\
+to generated tokens and expect it on consumed tokens.
+.It Fl S Ar maxsize
+split each token that is generated into components of maximum
+size
+.Ar maxsize .
+Each token is base64 encoded and output separately.
+.It Fl c Ar count
+repeat the operation
+.Ar count
+times.
+This flag only changes the behaviour when operating in initiator mode.
+This is good for very basic benchmarking.
+.It Fl l
+loop indefinitely in acceptor mode.
+.It Fl m Ar mech
+specifies the GSS mechanism that will be used in initiator mode.
+If a mechanism name of
+.Do ? Dc
+is specified, a list of supported mechanisms will be output and
+.Nm
+will exit.
+.It Fl n
+do not output the generated tokens.
+.It Fl r
+run in acceptor mode.
+.El
+.Pp
+.Nm
+takes one argument, a
+.Ar host@service
+specifier.
+The argument is required when running as an initiator but is optional as
+an acceptor.
+.Pp
+.Nm
+will try to read a token whenever the GSS mechanism expects one
+and will output a token whenever the GSS mechanism provides one.
+Tokens are base64 encoded and terminated by either two successive
+newlines or one newline and EOF.
+The base64 encoding may be broken up by single newlines which will
+be ignored when read. No extra whitespace will be ignored.
+.Sh EXAMPLES
+To test a simple GSS mechanism which doesn't require a round trip,
+a single
+.Pa /bin/sh
+pipeline will suffice:
+.Bd -literal -offset indent
+$ export KRB5_KTNAME=/path/to/keytab
+$ gss-token HTTP@$(hostname) | gss-token -r
+.Ed
+.Sh SEE ALSO
+.Xr gssapi 3 ,
+.Xr kerberos 8 .
diff --git a/third_party/heimdal/lib/gssapi/gss-token.c b/third_party/heimdal/lib/gssapi/gss-token.c
new file mode 100644
index 0000000..844fa4d
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gss-token.c
@@ -0,0 +1,678 @@
+/* */
+
+/*-
+ * Copyright (c) 1997-2011 Roland C. Dowdeswell
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer and
+ * dedication in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+
+#include <errno.h>
+#ifdef __APPLE__
+#include <malloc/malloc.h>
+#elif HAVE_MALLOC_H
+#include <malloc.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <gssapi/gssapi.h>
+#include <gssapi/gssapi_krb5.h>
+#include <krb5.h>
+#include <base64.h>
+#include <getarg.h>
+#include <roken.h>
+#include <vers.h>
+
+#define GBAIL(x, _maj, _min) do { \
+ if (GSS_ERROR(_maj)) { \
+ char *the_gss_err; \
+ \
+ ret = 1; \
+ the_gss_err = gss_mk_err(_maj, _min, x); \
+ if (the_gss_err) \
+ fprintf(stderr, "%s\n", the_gss_err); \
+ else \
+ fprintf(stderr, "err making err\n"); \
+ free(the_gss_err); \
+ goto bail; \
+ } \
+ } while (0)
+
+#define K5BAIL(x) do { \
+ kret = x; \
+ if (kret) { \
+ const char *k5err; \
+ \
+ k5err = krb5_get_error_message(kctx, kret); \
+ if (k5err) { \
+ fprintf(stderr, "%s in %s:%s\n", k5err, \
+ #x, __func__); \
+ krb5_free_error_message(kctx, k5err); \
+ } else { \
+ fprintf(stderr, "unknown error %d in " \
+ "%s:%s\n", kret, #x, __func__); \
+ } \
+ exit(1); /* XXXrcd: shouldn't exit */ \
+ } \
+ } while (0)
+
+
+/*
+ * global variables
+ */
+
+int Sflag = 0;
+int nflag = 0;
+gss_OID global_mech = GSS_C_NO_OID;
+
+static char *
+gss_mk_err(OM_uint32 maj_stat, OM_uint32 min_stat, const char *preamble)
+{
+ gss_buffer_desc status;
+ OM_uint32 new_stat;
+ OM_uint32 cur_stat;
+ OM_uint32 msg_ctx = 0;
+ OM_uint32 ret;
+ int type;
+ size_t newlen;
+ char *str = NULL;
+ char *tmp = NULL;
+
+ cur_stat = maj_stat;
+ type = GSS_C_GSS_CODE;
+
+ for (;;) {
+
+ /*
+ * GSS_S_FAILURE produces a rather unhelpful message, so
+ * we skip straight to the mech specific error in this case.
+ */
+
+ if (type == GSS_C_GSS_CODE && cur_stat == GSS_S_FAILURE) {
+ type = GSS_C_MECH_CODE;
+ cur_stat = min_stat;
+ }
+
+ ret = gss_display_status(&new_stat, cur_stat, type,
+ GSS_C_NO_OID, &msg_ctx, &status);
+
+ if (GSS_ERROR(ret))
+ return str; /* XXXrcd: hmmm, not quite?? */
+
+ if (str)
+ newlen = strlen(str);
+ else
+ newlen = strlen(preamble);
+
+ newlen += status.length + 3;
+
+ tmp = str;
+ str = malloc(newlen);
+
+ if (!str) {
+ gss_release_buffer(&new_stat, &status);
+ return tmp; /* XXXrcd: hmmm, not quite?? */
+ }
+
+ snprintf(str, newlen, "%s%s%.*s", tmp?tmp:preamble,
+ tmp?", ":": ", (int)status.length, (char *)status.value);
+
+ gss_release_buffer(&new_stat, &status);
+ free(tmp);
+
+ /*
+ * If we are finished processing for maj_stat, then
+ * move onto min_stat.
+ */
+
+ if (msg_ctx == 0 && type == GSS_C_GSS_CODE && min_stat != 0) {
+ type = GSS_C_MECH_CODE;
+ cur_stat = min_stat;
+ continue;
+ }
+
+ if (msg_ctx == 0)
+ break;
+ }
+
+ return str;
+}
+
+static char *
+read_buffer(FILE *fp)
+{
+ char buf[65536];
+ char *p;
+ char *ret = NULL;
+ size_t buflen;
+ size_t retlen = 0;
+
+ while (fgets(buf, sizeof(buf), fp) != NULL) {
+ if ((p = strchr(buf, '\n')) == NULL) {
+ fprintf(stderr, "Long line, exiting.\n");
+ exit(1);
+ }
+ *p = '\0';
+ buflen = strlen(buf);
+ if (buflen == 0)
+ break;
+
+ ret = realloc(ret, retlen + buflen + 1);
+ if (!ret) {
+ perror("realloc");
+ exit(1);
+ }
+ memcpy(ret + retlen, buf, buflen);
+ ret[retlen + buflen] = '\0';
+ retlen += buflen;
+ }
+
+ if (ferror(stdin)) {
+ perror("fgets");
+ exit(1);
+ }
+
+ return ret;
+}
+
+static int
+write_and_free_token(gss_buffer_t out, int negotiate)
+{
+ OM_uint32 min;
+ char *outstr = NULL;
+ char *p = out->value;
+ size_t len = out->length;
+ size_t inc;
+ int ret = 0;
+ int first = 1;
+
+ if (nflag)
+ goto bail;
+
+ /*
+ * According to RFC 2744 page 25, we simply don't output
+ * zero length output tokens.
+ */
+ if (len == 0)
+ goto bail;
+
+ inc = len;
+ if (Sflag)
+ inc = Sflag;
+
+ do {
+ if (first)
+ first = 0;
+ else
+ printf("\n");
+ if (len < inc)
+ inc = len;
+ ret = rk_base64_encode(p, inc, &outstr);
+ if (ret < 0) {
+ fprintf(stderr, "Out of memory.\n");
+ ret = 1;
+ goto bail;
+ }
+ ret = 0;
+ printf("%s%s\n", negotiate?"Negotiate ":"", outstr);
+ free(outstr);
+ p += inc;
+ len -= inc;
+ } while (len > 0);
+
+bail:
+ gss_release_buffer(&min, out);
+ return ret;
+}
+
+static int
+read_token(gss_buffer_t in, int negotiate)
+{
+ char *inbuf = NULL;
+ char *tmp;
+ size_t len;
+ int ret = 0;
+
+ /* We must flush before we block wanting input */
+ fflush(stdout);
+
+ *in = (gss_buffer_desc)GSS_C_EMPTY_BUFFER;
+ inbuf = read_buffer(stdin);
+ if (!inbuf)
+ /* Just a couple of \n's in a row or EOF, no error. */
+ return 0;
+
+ tmp = inbuf;
+ if (negotiate) {
+ if (strncasecmp("Negotiate ", inbuf, 10) != 0) {
+ fprintf(stderr, "Token doesn't begin with "
+ "\"Negotiate \"\n");
+ ret = -1;
+ goto bail;
+ }
+
+ tmp += 10;
+ }
+
+ len = strlen(tmp);
+ in->value = malloc(len + 1);
+ if (!in->value) {
+ fprintf(stderr, "Out of memory.\n");
+ ret = -1;
+ goto bail;
+ }
+ ret = rk_base64_decode(tmp, in->value);
+ if (ret < 0) {
+ free(in->value);
+ in->value = NULL;
+ if (errno == EOVERFLOW)
+ fprintf(stderr, "Token is too big\n");
+ else
+ fprintf(stderr, "Token encoding is not valid "
+ "base64\n");
+ goto bail;
+ } else {
+ in->length = ret;
+ }
+ ret = 0;
+
+bail:
+ free(inbuf);
+ return ret;
+}
+
+static int
+initiate_one(gss_name_t service, int delegate, int negotiate)
+{
+ gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
+ gss_buffer_desc in;
+ gss_buffer_desc out;
+ OM_uint32 maj;
+ OM_uint32 min;
+ OM_uint32 flags = 0;
+ int first = 1;
+ int ret = 0;
+
+ if (delegate)
+ flags |= GSS_C_DELEG_FLAG;
+
+ do {
+ out.length = 0;
+ out.value = 0;
+
+ if (first) {
+ in.length = 0;
+ in.value = 0;
+ first = 0;
+ } else {
+ printf("\n");
+ ret = read_token(&in, negotiate);
+ if (ret)
+ return ret;
+ if (feof(stdin))
+ return -1;
+ }
+
+ maj = gss_init_sec_context(&min, GSS_C_NO_CREDENTIAL, &ctx,
+ service, global_mech, flags, 0,
+ GSS_C_NO_CHANNEL_BINDINGS, &in, NULL, &out,
+ NULL, NULL);
+
+ ret = write_and_free_token(&out, negotiate);
+ if (ret)
+ return ret;
+
+ GBAIL("gss_init_sec_context", maj, min);
+ } while (maj & GSS_S_CONTINUE_NEEDED);
+
+bail:
+ if (ctx != GSS_C_NO_CONTEXT) {
+ /*
+ * XXXrcd: here we ignore the fact that we might have an
+ * output token as this program doesn't do terribly
+ * well in that case.
+ */
+ gss_delete_sec_context(&min, &ctx, NULL);
+ }
+
+ return ret;
+}
+
+static krb5_error_code
+copy_cache(krb5_context kctx, krb5_ccache from, krb5_ccache to)
+{
+ krb5_error_code kret;
+ krb5_principal princ = NULL;
+ krb5_cc_cursor cursor;
+ krb5_creds cred;
+
+ K5BAIL(krb5_cc_get_principal(kctx, from, &princ));
+ K5BAIL(krb5_cc_initialize(kctx, to, princ));
+ K5BAIL(krb5_cc_start_seq_get(kctx, from, &cursor));
+ for (;;) {
+ kret = krb5_cc_next_cred(kctx, from, &cursor, &cred);
+ if (kret)
+ break;
+ kret = krb5_cc_store_cred(kctx, to, &cred);
+ krb5_free_cred_contents(kctx, &cred);
+ if (kret)
+ break;
+ }
+ krb5_cc_end_seq_get(kctx, from, &cursor);
+
+ if (kret == KRB5_CC_END)
+ kret = 0;
+ K5BAIL(kret);
+
+ if (princ)
+ krb5_free_principal(kctx, princ);
+
+ return kret;
+}
+
+static int
+initiate_many(gss_name_t service, int delegate, int negotiate, int memcache,
+ size_t count)
+{
+ krb5_error_code kret = 0;
+ krb5_context kctx = NULL;
+ krb5_ccache def_cache = NULL;
+ krb5_ccache mem_cache = NULL;
+ size_t i;
+
+ if (memcache) {
+ K5BAIL(krb5_init_context(&kctx));
+ K5BAIL(krb5_cc_default(kctx, &def_cache));
+ K5BAIL(krb5_cc_resolve(kctx, "MEMORY:mem_cache", &mem_cache));
+ putenv("KRB5CCNAME=MEMORY:mem_cache");
+ }
+
+ for (i=0; i < count; i++) {
+ if (memcache)
+ K5BAIL(copy_cache(kctx, def_cache, mem_cache));
+ kret = initiate_one(service, delegate, negotiate);
+
+ if (!nflag && i < count - 1)
+ printf("\n");
+ }
+
+ if (kctx)
+ krb5_free_context(kctx);
+ if (def_cache)
+ krb5_cc_close(kctx, def_cache);
+ if (mem_cache)
+ krb5_cc_close(kctx, mem_cache);
+
+ return kret;
+}
+
+static int
+accept_one(gss_name_t service, const char *ccname, int negotiate)
+{
+ gss_cred_id_t cred = NULL;
+ gss_cred_id_t deleg_creds = NULL;
+ gss_name_t client;
+ gss_OID mech_oid;
+ gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
+ gss_buffer_desc in = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc out;
+ gss_buffer_desc dname = GSS_C_EMPTY_BUFFER;
+ krb5_context kctx = NULL;
+ krb5_ccache ccache = NULL;
+ krb5_error_code kret;
+ OM_uint32 maj, min;
+ int ret = 0;
+
+ if (service) {
+ maj = gss_acquire_cred(&min, service, 0, NULL, GSS_C_ACCEPT,
+ &cred, NULL, NULL);
+ GBAIL("gss_acquire_cred", maj, min);
+ }
+
+ do {
+ if (feof(stdin))
+ return -1;
+ ret = read_token(&in, negotiate);
+ if (ret)
+ return ret;
+
+ out.length = 0;
+ out.value = 0;
+
+ maj = gss_accept_sec_context(&min, &ctx, cred, &in,
+ GSS_C_NO_CHANNEL_BINDINGS, &client, &mech_oid, &out,
+ NULL, NULL, &deleg_creds);
+
+ ret = write_and_free_token(&out, negotiate);
+ if (ret)
+ return ret;
+ GBAIL("gss_accept_sec_context", maj, min);
+ } while (maj & GSS_S_CONTINUE_NEEDED);
+
+ /*
+ * XXXrcd: not bothering to clean up because we're about to exit.
+ * Probably should fix this in case the code is used as
+ * an example by someone.
+ */
+
+ maj = gss_display_name(&min, client, &dname, NULL);
+ GBAIL("gss_display_name", maj, min);
+
+ if (!nflag)
+ printf("Authenticated: %.*s\n", (int)dname.length,
+ (char *)dname.value);
+ (void) gss_release_buffer(&min, &dname);
+ (void) gss_release_name(&min, &client);
+
+ if (ccname) {
+#ifdef HAVE_GSS_STORE_CRED_INTO
+ gss_key_value_set_desc store;
+ gss_key_value_element_desc elem;
+ int overwrite_cred = 1;
+ int default_cred = 0;
+
+ elem.key = "ccache";
+ elem.value = ccname;
+ store.count = 1;
+ store.elements = &elem;
+
+ maj = gss_store_cred_into(&min, deleg_creds, GSS_C_INITIATE,
+ GSS_C_NO_OID, overwrite_cred, default_cred, &store, NULL,
+ NULL);
+ GBAIL("gss_store_cred_into", maj, min);
+#else
+ K5BAIL(krb5_init_context(&kctx));
+ K5BAIL(krb5_cc_resolve(kctx, ccname, &ccache));
+
+ maj = gss_krb5_copy_ccache(&min, deleg_creds, ccache);
+ GBAIL("gss_krb5_copy_ccache", maj, min);
+#endif
+ }
+
+bail:
+ if (kctx)
+ krb5_free_context(kctx);
+ if (ccache)
+ krb5_cc_close(kctx, ccache);
+ if (cred)
+ gss_release_cred(&min, &cred);
+ if (deleg_creds)
+ gss_release_cred(&min, &deleg_creds);
+
+ free(in.value);
+
+ return ret;
+}
+
+static gss_name_t
+import_service(char *service)
+{
+ gss_buffer_desc name;
+ gss_name_t svc = NULL;
+ OM_uint32 maj;
+ OM_uint32 min;
+ int ret = 0;
+
+ name.length = strlen(service);
+ name.value = service;
+
+ maj = gss_import_name(&min, &name, GSS_C_NT_HOSTBASED_SERVICE, &svc);
+
+ GBAIL("gss_import_name", maj, min);
+
+bail:
+ if (ret)
+ exit(1);
+ return svc;
+}
+
+static void
+print_all_mechs(void)
+{
+ OM_uint32 maj, min;
+ gss_OID_set mech_set;
+ size_t i;
+ int ret = 0;
+
+ maj = gss_indicate_mechs(&min, &mech_set);
+ GBAIL("gss_indicate_mechs", maj, min);
+
+ for (i=0; i < mech_set->count; i++)
+ printf("%s\n", gss_oid_to_name(&mech_set->elements[i]));
+
+ (void) gss_release_oid_set(&min, &mech_set);
+
+bail:
+ exit(ret);
+}
+
+static void
+usage(int ecode)
+{
+ FILE *f = ecode == 0 ? stdout : stderr;
+ fprintf(f, "Usage: gss-token [-DNn] [-c count] service@host\n");
+ fprintf(f, " gss-token -r [-Nln] [-C ccache] [-c count] "
+ "[service@host]\n");
+ exit(ecode);
+}
+
+int
+main(int argc, char **argv)
+{
+ OM_uint32 min;
+ gss_name_t service = NULL;
+ size_t count = 1;
+ int Dflag = 0;
+ int Mflag = 0;
+ int Nflag = 0;
+ int hflag = 0;
+ int lflag = 0;
+ int rflag = 0;
+ int version_flag = 0;
+ int ret = 0;
+ int optidx = 0;
+ char *ccname = NULL;
+ char *mech = NULL;
+ struct getargs args[] = {
+ { "help", 'h', arg_flag, &hflag, NULL, NULL },
+ { "version", 0, arg_flag, &version_flag, NULL, NULL },
+ { NULL, 'C', arg_string, &ccname, NULL, NULL },
+ { NULL, 'D', arg_flag, &Dflag, NULL, NULL },
+ { NULL, 'M', arg_flag, &Mflag, NULL, NULL },
+ { NULL, 'N', arg_flag, &Nflag, NULL, NULL },
+ { NULL, 'S', arg_integer, &Sflag, NULL, NULL },
+ { NULL, 'c', arg_integer, &count, NULL, NULL },
+ { NULL, 'l', arg_flag, &lflag, NULL, NULL },
+ { NULL, 'm', arg_string, &mech, NULL, NULL },
+ { NULL, 'n', arg_flag, &nflag, NULL, NULL },
+ { NULL, 'r', arg_flag, &rflag, NULL, NULL },
+ };
+
+ setprogname(argv[0]);
+ if (argc == 1 ||
+ getarg(args, sizeof(args)/sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+ if (hflag)
+ usage(0);
+ if (version_flag) {
+ print_version(NULL);
+ return 0;
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (mech) {
+ if (mech[0] == '?' && mech[1] == '\0') {
+ print_all_mechs();
+ exit(0);
+ }
+ global_mech = gss_name_to_oid(mech);
+ if (!global_mech) {
+ fprintf(stderr, "Invalid mech \"%s\".\n", mech);
+ usage(1);
+ }
+ }
+
+ if (argc > 0)
+ service = import_service(*argv);
+
+ if (!rflag) {
+ if (!argc) {
+ fprintf(stderr, "Without -r, hostbased_service must "
+ "be provided.\n");
+ usage(1);
+ }
+ if (ccname) {
+ fprintf(stderr, "Specifying a target ccache doesn't "
+ "make sense without -r.\n");
+ usage(1);
+ }
+ ret = initiate_many(service, Dflag, Nflag, Mflag, count);
+ goto done;
+ }
+
+ if (Dflag) {
+ fprintf(stderr, "Delegating credentials (-D) doesn't make "
+ "sense when reading tokens (-r).\n");
+ usage(1);
+ }
+
+ do {
+ ret = accept_one(service, ccname, Nflag);
+ } while (lflag && !ret && !feof(stdin));
+
+done:
+ if (service)
+ gss_release_name(&min, &service);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/gss_acquire_cred.3 b/third_party/heimdal/lib/gssapi/gss_acquire_cred.3
new file mode 100644
index 0000000..de58ecd
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gss_acquire_cred.3
@@ -0,0 +1,688 @@
+.\" Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd October 26, 2005
+.Dt GSS_ACQUIRE_CRED 3
+.Os HEIMDAL
+.Sh NAME
+.Nm gss_accept_sec_context ,
+.Nm gss_acquire_cred ,
+.Nm gss_add_cred ,
+.Nm gss_add_oid_set_member ,
+.Nm gss_canonicalize_name ,
+.Nm gss_compare_name ,
+.Nm gss_context_time ,
+.Nm gss_create_empty_oid_set ,
+.Nm gss_delete_sec_context ,
+.Nm gss_display_name ,
+.Nm gss_display_status ,
+.Nm gss_duplicate_name ,
+.Nm gss_export_name ,
+.Nm gss_export_sec_context ,
+.Nm gss_get_mic ,
+.Nm gss_import_name ,
+.Nm gss_import_sec_context ,
+.Nm gss_indicate_mechs ,
+.Nm gss_init_sec_context ,
+.Nm gss_inquire_context ,
+.Nm gss_inquire_cred ,
+.Nm gss_inquire_cred_by_mech ,
+.Nm gss_inquire_mechs_for_name ,
+.Nm gss_inquire_names_for_mech ,
+.Nm gss_krb5_ccache_name ,
+.Nm gss_krb5_compat_des3_mic ,
+.Nm gss_krb5_copy_ccache ,
+.Nm gss_krb5_import_cred
+.Nm gsskrb5_extract_authz_data_from_sec_context ,
+.Nm gsskrb5_register_acceptor_identity ,
+.Nm gss_krb5_import_ccache ,
+.Nm gss_krb5_get_tkt_flags ,
+.Nm gss_process_context_token ,
+.Nm gss_release_buffer ,
+.Nm gss_release_cred ,
+.Nm gss_release_name ,
+.Nm gss_release_oid_set ,
+.Nm gss_seal ,
+.Nm gss_sign ,
+.Nm gss_test_oid_set_member ,
+.Nm gss_unseal ,
+.Nm gss_unwrap ,
+.Nm gss_verify ,
+.Nm gss_verify_mic ,
+.Nm gss_wrap ,
+.Nm gss_wrap_size_limit
+.Nd Generic Security Service Application Program Interface library
+.Sh LIBRARY
+GSS-API library (libgssapi, -lgssapi)
+.Sh SYNOPSIS
+.In gssapi.h
+.Pp
+.Ft OM_uint32
+.Fo gss_accept_sec_context
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_ctx_id_t * context_handle"
+.Fa "gss_const_cred_id_t acceptor_cred_handle"
+.Fa "const gss_buffer_t input_token_buffer"
+.Fa "const gss_channel_bindings_t input_chan_bindings"
+.Fa "gss_name_t * src_name"
+.Fa "gss_OID * mech_type"
+.Fa "gss_buffer_t output_token"
+.Fa "OM_uint32 * ret_flags"
+.Fa "OM_uint32 * time_rec"
+.Fa "gss_cred_id_t * delegated_cred_handle"
+.Fc
+.Pp
+.Ft OM_uint32
+.Fo gss_acquire_cred
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_name_t desired_name"
+.Fa "OM_uint32 time_req"
+.Fa "const gss_OID_set desired_mechs"
+.Fa "gss_cred_usage_t cred_usage"
+.Fa "gss_cred_id_t * output_cred_handle"
+.Fa "gss_OID_set * actual_mechs"
+.Fa "OM_uint32 * time_rec"
+.Fc
+.Ft OM_uint32
+.Fo gss_add_cred
+.Fa "OM_uint32 *minor_status"
+.Fa "gss_const_cred_id_t input_cred_handle"
+.Fa "gss_const_name_t desired_name"
+.Fa "const gss_OID desired_mech"
+.Fa "gss_cred_usage_t cred_usage"
+.Fa "OM_uint32 initiator_time_req"
+.Fa "OM_uint32 acceptor_time_req"
+.Fa "gss_cred_id_t *output_cred_handle"
+.Fa "gss_OID_set *actual_mechs"
+.Fa "OM_uint32 *initiator_time_rec"
+.Fa "OM_uint32 *acceptor_time_rec"
+.Fc
+.Ft OM_uint32
+.Fo gss_add_oid_set_member
+.Fa "OM_uint32 * minor_status"
+.Fa "const gss_OID member_oid"
+.Fa "gss_OID_set * oid_set"
+.Fc
+.Ft OM_uint32
+.Fo gss_canonicalize_name
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_name_t input_name"
+.Fa "const gss_OID mech_type"
+.Fa "gss_name_t * output_name"
+.Fc
+.Ft OM_uint32
+.Fo gss_compare_name
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_name_t name1"
+.Fa "gss_const_name_t name2"
+.Fa "int * name_equal"
+.Fc
+.Ft OM_uint32
+.Fo gss_context_time
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_ctx_id_t context_handle"
+.Fa "OM_uint32 * time_rec"
+.Fc
+.Ft OM_uint32
+.Fo gss_create_empty_oid_set
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_OID_set * oid_set"
+.Fc
+.Ft OM_uint32
+.Fo gss_delete_sec_context
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_ctx_id_t * context_handle"
+.Fa "gss_buffer_t output_token"
+.Fc
+.Ft OM_uint32
+.Fo gss_display_name
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_name_t input_name"
+.Fa "gss_buffer_t output_name_buffer"
+.Fa "gss_OID * output_name_type"
+.Fc
+.Ft OM_uint32
+.Fo gss_display_status
+.Fa "OM_uint32 *minor_status"
+.Fa "OM_uint32 status_value"
+.Fa "int status_type"
+.Fa "const gss_OID mech_type"
+.Fa "OM_uint32 *message_context"
+.Fa "gss_buffer_t status_string"
+.Fc
+.Ft OM_uint32
+.Fo gss_duplicate_name
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_name_t src_name"
+.Fa "gss_name_t * dest_name"
+.Fc
+.Ft OM_uint32
+.Fo gss_export_name
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_name_t input_name"
+.Fa "gss_buffer_t exported_name"
+.Fc
+.Ft OM_uint32
+.Fo gss_export_sec_context
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_ctx_id_t * context_handle"
+.Fa "gss_buffer_t interprocess_token"
+.Fc
+.Ft OM_uint32
+.Fo gss_get_mic
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_ctx_id_t context_handle"
+.Fa "gss_qop_t qop_req"
+.Fa "const gss_buffer_t message_buffer"
+.Fa "gss_buffer_t message_token"
+.Fc
+.Ft OM_uint32
+.Fo gss_import_name
+.Fa "OM_uint32 * minor_status"
+.Fa "const gss_buffer_t input_name_buffer"
+.Fa "const gss_OID input_name_type"
+.Fa "gss_name_t * output_name"
+.Fc
+.Ft OM_uint32
+.Fo gss_import_sec_context
+.Fa "OM_uint32 * minor_status"
+.Fa "const gss_buffer_t interprocess_token"
+.Fa "gss_ctx_id_t * context_handle"
+.Fc
+.Ft OM_uint32
+.Fo gss_indicate_mechs
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_OID_set * mech_set"
+.Fc
+.Ft OM_uint32
+.Fo gss_init_sec_context
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_cred_id_t initiator_cred_handle"
+.Fa "gss_ctx_id_t * context_handle"
+.Fa "gss_const_name_t target_name"
+.Fa "const gss_OID mech_type"
+.Fa "OM_uint32 req_flags"
+.Fa "OM_uint32 time_req"
+.Fa "const gss_channel_bindings_t input_chan_bindings"
+.Fa "const gss_buffer_t input_token"
+.Fa "gss_OID * actual_mech_type"
+.Fa "gss_buffer_t output_token"
+.Fa "OM_uint32 * ret_flags"
+.Fa "OM_uint32 * time_rec"
+.Fc
+.Ft OM_uint32
+.Fo gss_inquire_context
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_ctx_id_t context_handle"
+.Fa "gss_name_t * src_name"
+.Fa "gss_name_t * targ_name"
+.Fa "OM_uint32 * lifetime_rec"
+.Fa "gss_OID * mech_type"
+.Fa "OM_uint32 * ctx_flags"
+.Fa "int * locally_initiated"
+.Fa "int * open_context"
+.Fc
+.Ft OM_uint32
+.Fo gss_inquire_cred
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_cred_id_t cred_handle"
+.Fa "gss_name_t * name"
+.Fa "OM_uint32 * lifetime"
+.Fa "gss_cred_usage_t * cred_usage"
+.Fa "gss_OID_set * mechanisms"
+.Fc
+.Ft OM_uint32
+.Fo gss_inquire_cred_by_mech
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_cred_id_t cred_handle"
+.Fa "const gss_OID mech_type"
+.Fa "gss_name_t * name"
+.Fa "OM_uint32 * initiator_lifetime"
+.Fa "OM_uint32 * acceptor_lifetime"
+.Fa "gss_cred_usage_t * cred_usage"
+.Fc
+.Ft OM_uint32
+.Fo gss_inquire_mechs_for_name
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_name_t input_name"
+.Fa "gss_OID_set * mech_types"
+.Fc
+.Ft OM_uint32
+.Fo gss_inquire_names_for_mech
+.Fa "OM_uint32 * minor_status"
+.Fa "const gss_OID mechanism"
+.Fa "gss_OID_set * name_types"
+.Fc
+.Ft OM_uint32
+.Fo gss_krb5_ccache_name
+.Fa "OM_uint32 *minor"
+.Fa "const char *name"
+.Fa "const char **old_name"
+.Fc
+.Ft OM_uint32
+.Fo gss_krb5_copy_ccache
+.Fa "OM_uint32 *minor"
+.Fa "gss_cred_id_t cred"
+.Fa "krb5_ccache out"
+.Fc
+.Ft OM_uint32
+.Fo gss_krb5_import_cred
+.Fa "OM_uint32 *minor_status"
+.Fa "krb5_ccache id"
+.Fa "krb5_principal keytab_principal"
+.Fa "krb5_keytab keytab"
+.Fa "gss_cred_id_t *cred"
+.Fc
+.Ft OM_uint32
+.Fo gss_krb5_compat_des3_mic
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_ctx_id_t context_handle"
+.Fa "int onoff"
+.Fc
+.Ft OM_uint32
+.Fo gsskrb5_extract_authz_data_from_sec_context
+.Fa "OM_uint32 *minor_status"
+.Fa "gss_ctx_id_t context_handle"
+.Fa "int ad_type"
+.Fa "gss_buffer_t ad_data"
+.Fc
+.Ft OM_uint32
+.Fo gsskrb5_register_acceptor_identity
+.Fa "const char *identity"
+.Fc
+.Ft OM_uint32
+.Fo gss_krb5_import_cache
+.Fa "OM_uint32 *minor"
+.Fa "krb5_ccache id"
+.Fa "krb5_keytab keytab"
+.Fa "gss_cred_id_t *cred"
+.Fc
+.Ft OM_uint32
+.Fo gss_krb5_get_tkt_flags
+.Fa "OM_uint32 *minor_status"
+.Fa "gss_ctx_id_t context_handle"
+.Fa "OM_uint32 *tkt_flags"
+.Fc
+.Ft OM_uint32
+.Fo gss_process_context_token
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_ctx_id_t context_handle"
+.Fa "const gss_buffer_t token_buffer"
+.Fc
+.Ft OM_uint32
+.Fo gss_release_buffer
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_buffer_t buffer"
+.Fc
+.Ft OM_uint32
+.Fo gss_release_cred
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_cred_id_t * cred_handle"
+.Fc
+.Ft OM_uint32
+.Fo gss_release_name
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_name_t * input_name"
+.Fc
+.Ft OM_uint32
+.Fo gss_release_oid_set
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_OID_set * set"
+.Fc
+.Ft OM_uint32
+.Fo gss_seal
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_ctx_id_t context_handle"
+.Fa "int conf_req_flag"
+.Fa "int qop_req"
+.Fa "gss_buffer_t input_message_buffer"
+.Fa "int * conf_state"
+.Fa "gss_buffer_t output_message_buffer"
+.Fc
+.Ft OM_uint32
+.Fo gss_sign
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_ctx_id_t context_handle"
+.Fa "int qop_req"
+.Fa "gss_buffer_t message_buffer"
+.Fa "gss_buffer_t message_token"
+.Fc
+.Ft OM_uint32
+.Fo gss_test_oid_set_member
+.Fa "OM_uint32 * minor_status"
+.Fa "const gss_OID member"
+.Fa "const gss_OID_set set"
+.Fa "int * present"
+.Fc
+.Ft OM_uint32
+.Fo gss_unseal
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_ctx_id_t context_handle"
+.Fa "gss_buffer_t input_message_buffer"
+.Fa "gss_buffer_t output_message_buffer"
+.Fa "int * conf_state"
+.Fa "int * qop_state"
+.Fc
+.Ft OM_uint32
+.Fo gss_unwrap
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_ctx_id_t context_handle"
+.Fa "const gss_buffer_t input_message_buffer"
+.Fa "gss_buffer_t output_message_buffer"
+.Fa "int * conf_state"
+.Fa "gss_qop_t * qop_state"
+.Fc
+.Ft OM_uint32
+.Fo gss_verify
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_ctx_id_t context_handle"
+.Fa "gss_buffer_t message_buffer"
+.Fa "gss_buffer_t token_buffer"
+.Fa "int * qop_state"
+.Fc
+.Ft OM_uint32
+.Fo gss_verify_mic
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_ctx_id_t context_handle"
+.Fa "const gss_buffer_t message_buffer"
+.Fa "const gss_buffer_t token_buffer"
+.Fa "gss_qop_t * qop_state"
+.Fc
+.Ft OM_uint32
+.Fo gss_wrap
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_ctx_id_t context_handle"
+.Fa "int conf_req_flag"
+.Fa "gss_qop_t qop_req"
+.Fa "const gss_buffer_t input_message_buffer"
+.Fa "int * conf_state"
+.Fa "gss_buffer_t output_message_buffer"
+.Fc
+.Ft OM_uint32
+.Fo gss_wrap_size_limit
+.Fa "OM_uint32 * minor_status"
+.Fa "gss_const_ctx_id_t context_handle"
+.Fa "int conf_req_flag"
+.Fa "gss_qop_t qop_req"
+.Fa "OM_uint32 req_output_size"
+.Fa "OM_uint32 * max_input_size"
+.Fc
+.Sh DESCRIPTION
+Generic Security Service API (GSS-API) version 2, and its C binding,
+is described in
+.Li RFC2743
+and
+.Li RFC2744 .
+Version 1 (deprecated) of the C binding is described in
+.Li RFC1509 .
+.Pp
+Heimdals GSS-API implementation supports the following mechanisms
+.Bl -bullet
+.It
+.Li GSS_KRB5_MECHANISM
+.It
+.Li GSS_SPNEGO_MECHANISM
+.El
+.Pp
+GSS-API have generic name types that all mechanism are supposed to
+implement (if possible):
+.Bl -bullet
+.It
+.Li GSS_C_NT_USER_NAME
+.It
+.Li GSS_C_NT_MACHINE_UID_NAME
+.It
+.Li GSS_C_NT_STRING_UID_NAME
+.It
+.Li GSS_C_NT_HOSTBASED_SERVICE
+.It
+.Li GSS_C_NT_ANONYMOUS
+.It
+.Li GSS_C_NT_EXPORT_NAME
+.El
+.Pp
+GSS-API implementations that supports Kerberos 5 have some additional
+name types:
+.Bl -bullet
+.It
+.Li GSS_KRB5_NT_PRINCIPAL_NAME
+.It
+.Li GSS_KRB5_NT_USER_NAME
+.It
+.Li GSS_KRB5_NT_MACHINE_UID_NAME
+.It
+.Li GSS_KRB5_NT_STRING_UID_NAME
+.El
+.Pp
+In GSS-API, names have two forms, internal names and contiguous string
+names.
+.Bl -bullet
+.It
+.Li Internal name and mechanism name
+.Pp
+Internal names are implementation specific representation of
+a GSS-API name.
+.Li Mechanism names
+special form of internal names corresponds to one and only one mechanism.
+.Pp
+In GSS-API an internal name is stored in a
+.Dv gss_name_t .
+.It
+.Li Contiguous string name and exported name
+.Pp
+Contiguous string names are gssapi names stored in a
+.Dv OCTET STRING
+that together with a name type identifier (OID) uniquely specifies a
+gss-name.
+A special form of the contiguous string name is the exported name that
+have a OID embedded in the string to make it unique.
+Exported name have the nametype
+.Dv GSS_C_NT_EXPORT_NAME .
+.Pp
+In GSS-API an contiguous string name is stored in a
+.Dv gss_buffer_t .
+.Pp
+Exported names also have the property that they are specified by the
+mechanism itself and compatible between different GSS-API
+implementations.
+.El
+.Sh ACCESS CONTROL
+There are two ways of comparing GSS-API names, either comparing two
+internal names with each other or two contiguous string names with
+either other.
+.Pp
+To compare two internal names with each other, import (if needed) the
+names with
+.Fn gss_import_name
+into the GSS-API implementation and the compare the imported name with
+.Fn gss_compare_name .
+.Pp
+Importing names can be slow, so when its possible to store exported
+names in the access control list, comparing contiguous string name
+might be better.
+.Pp
+when comparing contiguous string name, first export them into a
+.Dv GSS_C_NT_EXPORT_NAME
+name with
+.Fn gss_export_name
+and then compare with
+.Xr memcmp 3 .
+.Pp
+Note that there are might be a difference between the two methods of
+comparing names.
+The first (using
+.Fn gss_compare_name )
+will compare to (unauthenticated) names are the same.
+The second will compare if a mechanism will authenticate them as the
+same principal.
+.Pp
+For example, if
+.Fn gss_import_name
+name was used with
+.Dv GSS_C_NO_OID
+the default syntax is used for all mechanism the GSS-API
+implementation supports.
+When compare the imported name of
+.Dv GSS_C_NO_OID
+it may match several mechanism names (MN).
+.Pp
+The resulting name from
+.Fn gss_display_name
+must not be used for access control.
+.Sh FUNCTIONS
+.Fn gss_display_name
+takes the gss name in
+.Fa input_name
+and puts a printable form in
+.Fa output_name_buffer .
+.Fa output_name_buffer
+should be freed when done using
+.Fn gss_release_buffer .
+.Fa output_name_type
+can either be
+.Dv NULL
+or a pointer to a
+.Li gss_OID
+and will in the latter case contain the OID type of the name.
+The name must only be used for printing.
+If access control is needed, see section
+.Sx ACCESS CONTROL .
+.Pp
+.Fn gss_inquire_context
+returns information about the context.
+Information is available even after the context have expired.
+.Fa lifetime_rec
+argument is set to
+.Dv GSS_C_INDEFINITE
+(don't expire) or the number of seconds that the context is still valid.
+A value of 0 means that the context is expired.
+.Fa mech_type
+argument should be considered readonly and must not be released.
+.Fa src_name
+and
+.Fn dest_name
+are both mechanims names and must be released with
+.Fn gss_release_name
+when no longer used.
+.Pp
+.Nm gss_context_time
+will return the amount of time (in seconds) of the context is still
+valid.
+If its expired
+.Fa time_rec
+will be set to 0 and
+.Dv GSS_S_CONTEXT_EXPIRED
+returned.
+.Pp
+.Fn gss_sign ,
+.Fn gss_verify ,
+.Fn gss_seal ,
+and
+.Fn gss_unseal
+are part of the GSS-API V1 interface and are obsolete.
+The functions should not be used for new applications.
+They are provided so that version 1 applications can link against the
+library.
+.Sh EXTENSIONS
+.Fn gss_krb5_ccache_name
+sets the internal kerberos 5 credential cache name to
+.Fa name .
+The old name is returned in
+.Fa old_name ,
+and must not be freed.
+The data allocated for
+.Fa old_name
+is free upon next call to
+.Fn gss_krb5_ccache_name .
+This function is not threadsafe if
+.Fa old_name
+argument is used.
+.Pp
+.Fn gss_krb5_copy_ccache
+will extract the krb5 credentials that are transferred from the
+initiator to the acceptor when using token delegation in the Kerberos
+mechanism.
+The acceptor receives the delegated token in the last argument to
+.Fn gss_accept_sec_context .
+.Pp
+.Fn gss_krb5_import_cred
+will import the krb5 credentials (both keytab and/or credential cache)
+into gss credential so it can be used withing GSS-API.
+The
+.Fa ccache
+is copied by reference and thus shared, so if the credential is destroyed
+with
+.Fa krb5_cc_destroy ,
+all users of thep
+.Fa gss_cred_id_t
+returned by
+.Fn gss_krb5_import_ccache
+will fail.
+.Pp
+.Fn gsskrb5_register_acceptor_identity
+sets the Kerberos 5 filebased keytab that the acceptor will use. The
+.Fa identifier
+is the file name.
+.Pp
+.Fn gsskrb5_extract_authz_data_from_sec_context
+extracts the Kerberos authorizationdata that may be stored within the
+context.
+Tha caller must free the returned buffer
+.Fa ad_data
+with
+.Fn gss_release_buffer
+upon success.
+.Pp
+.Fn gss_krb5_get_tkt_flags
+return the ticket flags for the kerberos ticket receive when
+authenticating the initiator.
+Only valid on the acceptor context.
+.Pp
+.Fn gss_krb5_compat_des3_mic
+turns on or off the compatibility with older version of Heimdal using
+des3 get and verify mic, this is way to programmatically set the
+[gssapi]broken_des3_mic and [gssapi]correct_des3_mic flags (see
+COMPATIBILITY section in
+.Xr gssapi 3 ) .
+If the CPP symbol
+.Dv GSS_C_KRB5_COMPAT_DES3_MIC
+is present,
+.Fn gss_krb5_compat_des3_mic
+exists.
+.Fn gss_krb5_compat_des3_mic
+will be removed in a later version of the GSS-API library.
+.Sh SEE ALSO
+.Xr gssapi 3 ,
+.Xr krb5 3 ,
+.Xr krb5_ccache 3 ,
+.Xr kerberos 8
diff --git a/third_party/heimdal/lib/gssapi/gssapi.3 b/third_party/heimdal/lib/gssapi/gssapi.3
new file mode 100644
index 0000000..089f751
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gssapi.3
@@ -0,0 +1,172 @@
+.\" Copyright (c) 2003 - 2005 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd April 20, 2005
+.Dt GSSAPI 3
+.Os
+.Sh NAME
+.Nm gssapi
+.Nd Generic Security Service Application Program Interface library
+.Sh LIBRARY
+GSS-API Library (libgssapi, -lgssapi)
+.Sh DESCRIPTION
+The Generic Security Service Application Program Interface (GSS-API)
+provides security services to callers in a generic fashion,
+supportable with a range of underlying mechanisms and technologies and
+hence allowing source-level portability of applications to different
+environments.
+.Pp
+The GSS-API implementation in Heimdal implements the Kerberos 5 and
+the SPNEGO GSS-API security mechanisms.
+.Sh LIST OF FUNCTIONS
+These functions constitute the gssapi library,
+.Em libgssapi .
+Declarations for these functions may be obtained from the include file
+.Pa gssapi.h .
+.Bl -column -compact
+.It Sy Name/Page
+.It Xr gss_accept_sec_context 3
+.It Xr gss_acquire_cred 3
+.It Xr gss_add_cred 3
+.It Xr gss_add_oid_set_member 3
+.It Xr gss_canonicalize_name 3
+.It Xr gss_compare_name 3
+.It Xr gss_context_time 3
+.It Xr gss_create_empty_oid_set 3
+.It Xr gss_delete_sec_context 3
+.It Xr gss_display_name 3
+.It Xr gss_display_status 3
+.It Xr gss_duplicate_name 3
+.It Xr gss_export_name 3
+.It Xr gss_export_sec_context 3
+.It Xr gss_get_mic 3
+.It Xr gss_import_name 3
+.It Xr gss_import_sec_context 3
+.It Xr gss_indicate_mechs 3
+.It Xr gss_init_sec_context 3
+.It Xr gss_inquire_context 3
+.It Xr gss_inquire_cred 3
+.It Xr gss_inquire_cred_by_mech 3
+.It Xr gss_inquire_mechs_for_name 3
+.It Xr gss_inquire_names_for_mech 3
+.It Xr gss_krb5_ccache_name 3
+.It Xr gss_krb5_compat_des3_mic 3
+.It Xr gss_krb5_copy_ccache 3
+.It Xr gss_krb5_extract_authz_data_from_sec_context 3
+.It Xr gss_krb5_import_ccache 3
+.It Xr gss_process_context_token 3
+.It Xr gss_release_buffer 3
+.It Xr gss_release_cred 3
+.It Xr gss_release_name 3
+.It Xr gss_release_oid_set 3
+.It Xr gss_seal 3
+.It Xr gss_sign 3
+.It Xr gss_test_oid_set_member 3
+.It Xr gss_unseal 3
+.It Xr gss_unwrap 3
+.It Xr gss_verify 3
+.It Xr gss_verify_mic 3
+.It Xr gss_wrap 3
+.It Xr gss_wrap_size_limit 3
+.El
+.Sh COMPATIBILITY
+The
+.Nm Heimdal
+GSS-API implementation had a bug in releases before 0.6 that made it
+fail to inter-operate when using DES3 with other GSS-API
+implementations when using
+.Fn gss_get_mic
+/
+.Fn gss_verify_mic .
+It is possible to modify the behavior of the generator of the MIC with
+the
+.Pa krb5.conf
+configuration file so that old clients/servers will still
+work.
+.Pp
+New clients/servers will try both the old and new MIC in Heimdal 0.6.
+In 0.7 it will check only if configured - the compatibility code will
+be removed in 0.8.
+.Pp
+Heimdal 0.6 still generates by default the broken GSS-API DES3 mic,
+this will change in 0.7 to generate correct des3 mic.
+.Pp
+To turn on compatibility with older clients and servers, change the
+.Nm [gssapi]
+.Ar broken_des3_mic
+in
+.Pa krb5.conf
+that contains a list of globbing expressions that will be matched
+against the server name.
+To turn off generation of the old (incompatible) mic of the MIC use
+.Nm [gssapi]
+.Ar correct_des3_mic .
+.Pp
+If a match for a entry is in both
+.Nm [gssapi]
+.Ar correct_des3_mic
+and
+.Nm [gssapi]
+.Ar broken_des3_mic ,
+the later will override.
+.Pp
+This config option modifies behaviour for both clients and servers.
+.Pp
+Microsoft implemented SPNEGO to Windows2000, however, they managed to
+get it wrong, their implementation didn't fill in the MechListMIC in
+the reply token with the right content.
+There is a work around for this problem, but not all implementation
+support it.
+.Pp
+Heimdal defaults to correct SPNEGO when the the kerberos
+implementation uses CFX, or when it is configured by the user.
+To turn on compatibility with peers, use option
+.Nm [gssapi]
+.Ar require_mechlist_mic .
+.Sh EXAMPLES
+.Bd -literal -offset indent
+[gssapi]
+ broken_des3_mic = cvs/*@SU.SE
+ broken_des3_mic = host/*@E.KTH.SE
+ correct_des3_mic = host/*@SU.SE
+ require_mechlist_mic = host/*@SU.SE
+.Ed
+.Sh BUGS
+All of 0.5.x versions of
+.Nm heimdal
+had broken token delegations in the client side, the server side was
+correct.
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5.conf 5 ,
+.Xr kerberos 8
diff --git a/third_party/heimdal/lib/gssapi/gssapi.h b/third_party/heimdal/lib/gssapi/gssapi.h
new file mode 100644
index 0000000..d2f039a
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gssapi.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef GSSAPI_H_
+#define GSSAPI_H_
+
+#include <gssapi/gssapi.h>
+
+#endif
diff --git a/third_party/heimdal/lib/gssapi/gssapi/gssapi.h b/third_party/heimdal/lib/gssapi/gssapi/gssapi.h
new file mode 100644
index 0000000..726543f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gssapi/gssapi.h
@@ -0,0 +1,1281 @@
+/*
+ * Copyright (c) 1997 - 2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef GSSAPI_GSSAPI_H_
+#define GSSAPI_GSSAPI_H_
+
+/*
+ * First, include stddef.h to get size_t defined.
+ */
+#include <stdarg.h>
+#include <stddef.h>
+
+#include <krb5-types.h>
+
+#ifndef BUILD_GSSAPI_LIB
+#if defined(_WIN32)
+#define GSSAPI_LIB_FUNCTION __declspec(dllimport)
+#define GSSAPI_LIB_CALL __stdcall
+#define GSSAPI_LIB_VARIABLE __declspec(dllimport)
+#else
+#define GSSAPI_LIB_FUNCTION
+#define GSSAPI_LIB_CALL
+#define GSSAPI_LIB_VARIABLE
+#endif
+#endif
+
+#ifndef GSSAPI_DEPRECATED_FUNCTION
+#if defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1 )))
+#define GSSAPI_DEPRECATED_FUNCTION(X) __attribute__((deprecated))
+#else
+#define GSSAPI_DEPRECATED_FUNCTION(X)
+#endif
+#endif
+
+/* Compatiblity with MIT Kerberos on the Mac */
+#if defined(__APPLE__) && (defined(__ppc__) || defined(__ppc64__) || defined(__i386__) || defined(__x86_64__))
+#pragma pack(push,2)
+#endif
+
+#ifdef __cplusplus
+#define GSSAPI_CPP_START extern "C" {
+#define GSSAPI_CPP_END }
+#else
+#define GSSAPI_CPP_START
+#define GSSAPI_CPP_END
+#endif
+
+#ifdef _WIN32
+#define GSSAPI_CALLCONV __stdcall
+#else
+#define GSSAPI_CALLCONV
+#endif
+
+/*
+ * Now define the three implementation-dependent types.
+ */
+
+typedef uint32_t OM_uint32;
+typedef uint64_t OM_uint64;
+
+typedef uint32_t gss_uint32;
+
+struct gss_name_t_desc_struct;
+typedef struct gss_name_t_desc_struct *gss_name_t;
+typedef const struct gss_name_t_desc_struct *gss_const_name_t;
+
+struct gss_ctx_id_t_desc_struct;
+typedef struct gss_ctx_id_t_desc_struct *gss_ctx_id_t;
+typedef const struct gss_ctx_id_t_desc_struct *gss_const_ctx_id_t;
+
+typedef struct gss_OID_desc_struct {
+ OM_uint32 length;
+ void *elements;
+} gss_OID_desc, *gss_OID;
+typedef const gss_OID_desc * gss_const_OID;
+
+typedef struct gss_OID_set_desc_struct {
+ size_t count;
+ gss_OID elements;
+} gss_OID_set_desc, *gss_OID_set;
+typedef const gss_OID_set_desc * gss_const_OID_set;
+
+typedef int gss_cred_usage_t;
+
+struct gss_cred_id_t_desc_struct;
+typedef struct gss_cred_id_t_desc_struct *gss_cred_id_t;
+typedef const struct gss_cred_id_t_desc_struct *gss_const_cred_id_t;
+
+typedef struct gss_buffer_desc_struct {
+ size_t length;
+ void *value;
+} gss_buffer_desc, *gss_buffer_t;
+typedef const gss_buffer_desc * gss_const_buffer_t;
+
+typedef struct gss_channel_bindings_struct {
+ OM_uint32 initiator_addrtype;
+ gss_buffer_desc initiator_address;
+ OM_uint32 acceptor_addrtype;
+ gss_buffer_desc acceptor_address;
+ gss_buffer_desc application_data;
+} *gss_channel_bindings_t;
+typedef const struct gss_channel_bindings_struct *gss_const_channel_bindings_t;
+
+/* GGF extension data types */
+typedef struct gss_buffer_set_desc_struct {
+ size_t count;
+ gss_buffer_desc *elements;
+} gss_buffer_set_desc, *gss_buffer_set_t;
+
+typedef struct gss_iov_buffer_desc_struct {
+ OM_uint32 type;
+ gss_buffer_desc buffer;
+} gss_iov_buffer_desc, *gss_iov_buffer_t;
+
+/* Credential store extensions */
+typedef struct gss_key_value_element_struct {
+ const char *key;
+ const char *value;
+} gss_key_value_element_desc;
+
+typedef struct gss_key_value_set_struct {
+ OM_uint32 count; /* should be size_t, but for MIT compat */
+ gss_key_value_element_desc *elements;
+} gss_key_value_set_desc, *gss_key_value_set_t;
+
+typedef const gss_key_value_set_desc *gss_const_key_value_set_t;
+
+/*
+ * For now, define a QOP-type as an OM_uint32
+ */
+typedef OM_uint32 gss_qop_t;
+
+
+/*
+ * Flag bits for context-level services.
+ */
+#define GSS_C_DELEG_FLAG 1
+#define GSS_C_MUTUAL_FLAG 2
+#define GSS_C_REPLAY_FLAG 4
+#define GSS_C_SEQUENCE_FLAG 8
+#define GSS_C_CONF_FLAG 16
+#define GSS_C_INTEG_FLAG 32
+#define GSS_C_ANON_FLAG 64
+#define GSS_C_PROT_READY_FLAG 128
+#define GSS_C_TRANS_FLAG 256
+
+#define GSS_C_CHANNEL_BOUND_FLAG 2048
+#define GSS_C_DCE_STYLE 4096
+#define GSS_C_IDENTIFY_FLAG 8192
+#define GSS_C_EXTENDED_ERROR_FLAG 16384
+#define GSS_C_DELEG_POLICY_FLAG 32768
+
+/*
+ * Credential usage options
+ */
+#define GSS_C_BOTH 0
+#define GSS_C_INITIATE 1
+#define GSS_C_ACCEPT 2
+
+/*
+ * Status code types for gss_display_status
+ */
+#define GSS_C_GSS_CODE 1
+#define GSS_C_MECH_CODE 2
+
+/*
+ * The constant definitions for channel-bindings address families
+ */
+#define GSS_C_AF_UNSPEC 0
+#define GSS_C_AF_LOCAL 1
+#define GSS_C_AF_INET 2
+#define GSS_C_AF_IMPLINK 3
+#define GSS_C_AF_PUP 4
+#define GSS_C_AF_CHAOS 5
+#define GSS_C_AF_NS 6
+#define GSS_C_AF_NBS 7
+#define GSS_C_AF_ECMA 8
+#define GSS_C_AF_DATAKIT 9
+#define GSS_C_AF_CCITT 10
+#define GSS_C_AF_SNA 11
+#define GSS_C_AF_DECnet 12
+#define GSS_C_AF_DLI 13
+#define GSS_C_AF_LAT 14
+#define GSS_C_AF_HYLINK 15
+#define GSS_C_AF_APPLETALK 16
+#define GSS_C_AF_BSC 17
+#define GSS_C_AF_DSS 18
+#define GSS_C_AF_OSI 19
+#define GSS_C_AF_X25 21
+#define GSS_C_AF_INET6 24
+
+#define GSS_C_AF_NULLADDR 255
+
+/*
+ * Various Null values
+ */
+#define GSS_C_NO_NAME ((gss_name_t) 0)
+#define GSS_C_NO_BUFFER ((gss_buffer_t) 0)
+#define GSS_C_NO_BUFFER_SET ((gss_buffer_set_t) 0)
+#define GSS_C_NO_OID ((gss_OID) 0)
+#define GSS_C_NO_OID_SET ((gss_OID_set) 0)
+#define GSS_C_NO_CONTEXT ((gss_ctx_id_t) 0)
+#define GSS_C_NO_CREDENTIAL ((gss_cred_id_t) 0)
+#define GSS_C_NO_CHANNEL_BINDINGS ((gss_channel_bindings_t) 0)
+#define GSS_C_EMPTY_BUFFER {0, NULL}
+#define GSS_C_EMPTY_BUFFER_SET {0, NULL}
+#define GSS_C_NO_IOV_BUFFER ((gss_iov_buffer_t)0)
+#define GSS_C_NO_CRED_STORE ((gss_key_value_set_t)0)
+
+/*
+ * Some alternate names for a couple of the above
+ * values. These are defined for V1 compatibility.
+ */
+#define GSS_C_NULL_OID GSS_C_NO_OID
+#define GSS_C_NULL_OID_SET GSS_C_NO_OID_SET
+
+/*
+ * Define the default Quality of Protection for per-message
+ * services. Note that an implementation that offers multiple
+ * levels of QOP may define GSS_C_QOP_DEFAULT to be either zero
+ * (as done here) to mean "default protection", or to a specific
+ * explicit QOP value. However, a value of 0 should always be
+ * interpreted by a GSSAPI implementation as a request for the
+ * default protection level.
+ */
+#define GSS_C_QOP_DEFAULT 0
+
+#define GSS_KRB5_CONF_C_QOP_DES 0x0100
+#define GSS_KRB5_CONF_C_QOP_DES3_KD 0x0200
+
+/*
+ * Expiration time of 2^32-1 seconds means infinite lifetime for a
+ * credential or security context
+ */
+#define GSS_C_INDEFINITE 0xfffffffful
+
+/*
+ * Type of gss_wrap_iov()/gss_unwrap_iov().
+ */
+
+#define GSS_IOV_BUFFER_TYPE_EMPTY 0
+#define GSS_IOV_BUFFER_TYPE_DATA 1
+#define GSS_IOV_BUFFER_TYPE_HEADER 2
+#define GSS_IOV_BUFFER_TYPE_MECH_PARAMS 3
+
+#define GSS_IOV_BUFFER_TYPE_TRAILER 7
+#define GSS_IOV_BUFFER_TYPE_PADDING 9
+#define GSS_IOV_BUFFER_TYPE_STREAM 10
+#define GSS_IOV_BUFFER_TYPE_SIGN_ONLY 11
+
+#define GSS_IOV_BUFFER_TYPE_FLAG_MASK 0xffff0000
+#define GSS_IOV_BUFFER_FLAG_ALLOCATE 0x00010000
+#define GSS_IOV_BUFFER_FLAG_ALLOCATED 0x00020000
+
+#define GSS_IOV_BUFFER_TYPE_FLAG_ALLOCATE 0x00010000 /* old name */
+#define GSS_IOV_BUFFER_TYPE_FLAG_ALLOCATED 0x00020000 /* old name */
+
+#define GSS_IOV_BUFFER_TYPE(_t) ((_t) & ~GSS_IOV_BUFFER_TYPE_FLAG_MASK)
+#define GSS_IOV_BUFFER_FLAGS(_t) ((_t) & GSS_IOV_BUFFER_TYPE_FLAG_MASK)
+
+GSSAPI_CPP_START
+
+#include <gssapi/gssapi_oid.h>
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {10, (void *)"\x2a\x86\x48\x86\xf7\x12"
+ * "\x01\x02\x01\x01"},
+ * corresponding to an object-identifier value of
+ * {iso(1) member-body(2) United States(840) mit(113554)
+ * infosys(1) gssapi(2) generic(1) user_name(1)}. The constant
+ * GSS_C_NT_USER_NAME should be initialized to point
+ * to that gss_OID_desc.
+ */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_user_name_oid_desc;
+#define GSS_C_NT_USER_NAME (&__gss_c_nt_user_name_oid_desc)
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {10, (void *)"\x2a\x86\x48\x86\xf7\x12"
+ * "\x01\x02\x01\x02"},
+ * corresponding to an object-identifier value of
+ * {iso(1) member-body(2) United States(840) mit(113554)
+ * infosys(1) gssapi(2) generic(1) machine_uid_name(2)}.
+ * The constant GSS_C_NT_MACHINE_UID_NAME should be
+ * initialized to point to that gss_OID_desc.
+ */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_machine_uid_name_oid_desc;
+#define GSS_C_NT_MACHINE_UID_NAME (&__gss_c_nt_machine_uid_name_oid_desc)
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {10, (void *)"\x2a\x86\x48\x86\xf7\x12"
+ * "\x01\x02\x01\x03"},
+ * corresponding to an object-identifier value of
+ * {iso(1) member-body(2) United States(840) mit(113554)
+ * infosys(1) gssapi(2) generic(1) string_uid_name(3)}.
+ * The constant GSS_C_NT_STRING_UID_NAME should be
+ * initialized to point to that gss_OID_desc.
+ */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_string_uid_name_oid_desc;
+#define GSS_C_NT_STRING_UID_NAME (&__gss_c_nt_string_uid_name_oid_desc)
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {6, (void *)"\x2b\x06\x01\x05\x06\x02"},
+ * corresponding to an object-identifier value of
+ * {iso(1) org(3) dod(6) internet(1) security(5)
+ * nametypes(6) gss-host-based-services(2)). The constant
+ * GSS_C_NT_HOSTBASED_SERVICE_X should be initialized to point
+ * to that gss_OID_desc. This is a deprecated OID value, and
+ * implementations wishing to support hostbased-service names
+ * should instead use the GSS_C_NT_HOSTBASED_SERVICE OID,
+ * defined below, to identify such names;
+ * GSS_C_NT_HOSTBASED_SERVICE_X should be accepted a synonym
+ * for GSS_C_NT_HOSTBASED_SERVICE when presented as an input
+ * parameter, but should not be emitted by GSS-API
+ * implementations
+ */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_hostbased_service_x_oid_desc;
+#define GSS_C_NT_HOSTBASED_SERVICE_X (&__gss_c_nt_hostbased_service_x_oid_desc)
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {10, (void *)"\x2a\x86\x48\x86\xf7\x12"
+ * "\x01\x02\x01\x04"}, corresponding to an
+ * object-identifier value of {iso(1) member-body(2)
+ * Unites States(840) mit(113554) infosys(1) gssapi(2)
+ * generic(1) service_name(4)}. The constant
+ * GSS_C_NT_HOSTBASED_SERVICE should be initialized
+ * to point to that gss_OID_desc.
+ */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_hostbased_service_oid_desc;
+#define GSS_C_NT_HOSTBASED_SERVICE (&__gss_c_nt_hostbased_service_oid_desc)
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {6, (void *)"\x2b\x06\01\x05\x06\x03"},
+ * corresponding to an object identifier value of
+ * {1(iso), 3(org), 6(dod), 1(internet), 5(security),
+ * 6(nametypes), 3(gss-anonymous-name)}. The constant
+ * and GSS_C_NT_ANONYMOUS should be initialized to point
+ * to that gss_OID_desc.
+ */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_anonymous_oid_desc;
+#define GSS_C_NT_ANONYMOUS (&__gss_c_nt_anonymous_oid_desc)
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {6, (void *)"\x2b\x06\x01\x05\x06\x04"},
+ * corresponding to an object-identifier value of
+ * {1(iso), 3(org), 6(dod), 1(internet), 5(security),
+ * 6(nametypes), 4(gss-api-exported-name)}. The constant
+ * GSS_C_NT_EXPORT_NAME should be initialized to point
+ * to that gss_OID_desc.
+ */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_export_name_oid_desc;
+#define GSS_C_NT_EXPORT_NAME (&__gss_c_nt_export_name_oid_desc)
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {6, (void *)"\x2b\x06\x01\x05\x06\x06"}, corresponding to an
+ * object-identifier value of {iso(1) identified-organization(3) dod(6)
+ * internet(1) security(5) nametypes(6) gss-composite-export(6)}.
+ * The constant GSS_C_NT_COMPOSITE_EXPORT [RFC6680] should be initialized to
+ * point to that gss_OID_desc.
+ */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_composite_export_oid_desc;
+#define GSS_C_NT_COMPOSITE_EXPORT (&__gss_c_nt_composite_export_oid_desc)
+
+/* Major status codes */
+
+#define GSS_S_COMPLETE 0
+
+/*
+ * Some "helper" definitions to make the status code macros obvious.
+ */
+#define GSS_C_CALLING_ERROR_OFFSET 24
+#define GSS_C_ROUTINE_ERROR_OFFSET 16
+#define GSS_C_SUPPLEMENTARY_OFFSET 0
+#define GSS_C_CALLING_ERROR_MASK 0377ul
+#define GSS_C_ROUTINE_ERROR_MASK 0377ul
+#define GSS_C_SUPPLEMENTARY_MASK 0177777ul
+
+/*
+ * The macros that test status codes for error conditions.
+ * Note that the GSS_ERROR() macro has changed slightly from
+ * the V1 GSSAPI so that it now evaluates its argument
+ * only once.
+ */
+#define GSS_CALLING_ERROR(x) \
+ (x & (GSS_C_CALLING_ERROR_MASK << GSS_C_CALLING_ERROR_OFFSET))
+#define GSS_ROUTINE_ERROR(x) \
+ (x & (GSS_C_ROUTINE_ERROR_MASK << GSS_C_ROUTINE_ERROR_OFFSET))
+#define GSS_SUPPLEMENTARY_INFO(x) \
+ (x & (GSS_C_SUPPLEMENTARY_MASK << GSS_C_SUPPLEMENTARY_OFFSET))
+#define GSS_ERROR(x) \
+ (x & ((GSS_C_CALLING_ERROR_MASK << GSS_C_CALLING_ERROR_OFFSET) | \
+ (GSS_C_ROUTINE_ERROR_MASK << GSS_C_ROUTINE_ERROR_OFFSET)))
+
+/*
+ * Now the actual status code definitions
+ */
+
+/*
+ * Calling errors:
+ */
+#define GSS_S_CALL_INACCESSIBLE_READ \
+ (1ul << GSS_C_CALLING_ERROR_OFFSET)
+#define GSS_S_CALL_INACCESSIBLE_WRITE \
+ (2ul << GSS_C_CALLING_ERROR_OFFSET)
+#define GSS_S_CALL_BAD_STRUCTURE \
+ (3ul << GSS_C_CALLING_ERROR_OFFSET)
+
+/*
+ * Routine errors:
+ */
+#define GSS_S_BAD_MECH (1ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_BAD_NAME (2ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_BAD_NAMETYPE (3ul << GSS_C_ROUTINE_ERROR_OFFSET)
+
+#define GSS_S_BAD_BINDINGS (4ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_BAD_STATUS (5ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_BAD_SIG (6ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_BAD_MIC GSS_S_BAD_SIG
+#define GSS_S_NO_CRED (7ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_NO_CONTEXT (8ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_DEFECTIVE_TOKEN (9ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_DEFECTIVE_CREDENTIAL (10ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_CREDENTIALS_EXPIRED (11ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_CONTEXT_EXPIRED (12ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_FAILURE (13ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_BAD_QOP (14ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_UNAUTHORIZED (15ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_UNAVAILABLE (16ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_DUPLICATE_ELEMENT (17ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_NAME_NOT_MN (18ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_BAD_MECH_ATTR (19ul << GSS_C_ROUTINE_ERROR_OFFSET)
+
+/*
+ * Apparently awating spec fix.
+ */
+#define GSS_S_CRED_UNAVAIL GSS_S_FAILURE
+
+/*
+ * Supplementary info bits:
+ */
+#define GSS_S_CONTINUE_NEEDED (1ul << (GSS_C_SUPPLEMENTARY_OFFSET + 0))
+#define GSS_S_DUPLICATE_TOKEN (1ul << (GSS_C_SUPPLEMENTARY_OFFSET + 1))
+#define GSS_S_OLD_TOKEN (1ul << (GSS_C_SUPPLEMENTARY_OFFSET + 2))
+#define GSS_S_UNSEQ_TOKEN (1ul << (GSS_C_SUPPLEMENTARY_OFFSET + 3))
+#define GSS_S_GAP_TOKEN (1ul << (GSS_C_SUPPLEMENTARY_OFFSET + 4))
+
+/*
+ * Finally, function prototypes for the GSS-API routines.
+ */
+
+#define GSS_C_OPTION_MASK 0xffff
+#define GSS_C_CRED_NO_UI 0x10000
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_acquire_cred
+ (OM_uint32 * /*minor_status*/,
+ gss_const_name_t /*desired_name*/,
+ OM_uint32 /*time_req*/,
+ const gss_OID_set /*desired_mechs*/,
+ gss_cred_usage_t /*cred_usage*/,
+ gss_cred_id_t * /*output_cred_handle*/,
+ gss_OID_set * /*actual_mechs*/,
+ OM_uint32 * /*time_rec*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_cred
+ (OM_uint32 * /*minor_status*/,
+ gss_cred_id_t * /*cred_handle*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_init_sec_context
+ (OM_uint32 * /*minor_status*/,
+ gss_const_cred_id_t /*initiator_cred_handle*/,
+ gss_ctx_id_t * /*context_handle*/,
+ gss_const_name_t /*target_name*/,
+ const gss_OID /*mech_type*/,
+ OM_uint32 /*req_flags*/,
+ OM_uint32 /*time_req*/,
+ const gss_channel_bindings_t /*input_chan_bindings*/,
+ const gss_buffer_t /*input_token*/,
+ gss_OID * /*actual_mech_type*/,
+ gss_buffer_t /*output_token*/,
+ OM_uint32 * /*ret_flags*/,
+ OM_uint32 * /*time_rec*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_accept_sec_context
+ (OM_uint32 * /*minor_status*/,
+ gss_ctx_id_t * /*context_handle*/,
+ gss_const_cred_id_t /*acceptor_cred_handle*/,
+ const gss_buffer_t /*input_token_buffer*/,
+ const gss_channel_bindings_t /*input_chan_bindings*/,
+ gss_name_t * /*src_name*/,
+ gss_OID * /*mech_type*/,
+ gss_buffer_t /*output_token*/,
+ OM_uint32 * /*ret_flags*/,
+ OM_uint32 * /*time_rec*/,
+ gss_cred_id_t * /*delegated_cred_handle*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_process_context_token
+ (OM_uint32 * /*minor_status*/,
+ gss_const_ctx_id_t /*context_handle*/,
+ const gss_buffer_t /*token_buffer*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_delete_sec_context
+ (OM_uint32 * /*minor_status*/,
+ gss_ctx_id_t * /*context_handle*/,
+ gss_buffer_t /*output_token*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_context_time
+ (OM_uint32 * /*minor_status*/,
+ gss_const_ctx_id_t /*context_handle*/,
+ OM_uint32 * /*time_rec*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_get_mic
+ (OM_uint32 * /*minor_status*/,
+ gss_const_ctx_id_t /*context_handle*/,
+ gss_qop_t /*qop_req*/,
+ const gss_buffer_t /*message_buffer*/,
+ gss_buffer_t /*message_token*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_verify_mic
+ (OM_uint32 * /*minor_status*/,
+ gss_const_ctx_id_t /*context_handle*/,
+ const gss_buffer_t /*message_buffer*/,
+ const gss_buffer_t /*token_buffer*/,
+ gss_qop_t * /*qop_state*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_wrap
+ (OM_uint32 * /*minor_status*/,
+ gss_const_ctx_id_t /*context_handle*/,
+ int /*conf_req_flag*/,
+ gss_qop_t /*qop_req*/,
+ const gss_buffer_t /*input_message_buffer*/,
+ int * /*conf_state*/,
+ gss_buffer_t /*output_message_buffer*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_unwrap
+ (OM_uint32 * /*minor_status*/,
+ gss_const_ctx_id_t /*context_handle*/,
+ const gss_buffer_t /*input_message_buffer*/,
+ gss_buffer_t /*output_message_buffer*/,
+ int * /*conf_state*/,
+ gss_qop_t * /*qop_state*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_display_status
+ (OM_uint32 * /*minor_status*/,
+ OM_uint32 /*status_value*/,
+ int /*status_type*/,
+ const gss_OID /*mech_type*/,
+ OM_uint32 * /*message_context*/,
+ gss_buffer_t /*status_string*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_indicate_mechs
+ (OM_uint32 * /*minor_status*/,
+ gss_OID_set * /*mech_set*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_compare_name
+ (OM_uint32 * /*minor_status*/,
+ gss_const_name_t /*name1*/,
+ gss_const_name_t /*name2*/,
+ int * /*name_equal*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_display_name
+ (OM_uint32 * /*minor_status*/,
+ gss_const_name_t /*input_name*/,
+ gss_buffer_t /*output_name_buffer*/,
+ gss_OID * /*output_name_type*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_import_name
+ (OM_uint32 * /*minor_status*/,
+ const gss_buffer_t /*input_name_buffer*/,
+ const gss_OID /*input_name_type*/,
+ gss_name_t * /*output_name*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_export_name
+ (OM_uint32 * /*minor_status*/,
+ gss_const_name_t /*input_name*/,
+ gss_buffer_t /*exported_name*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_name
+ (OM_uint32 * /*minor_status*/,
+ gss_name_t * /*input_name*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_buffer
+ (OM_uint32 * /*minor_status*/,
+ gss_buffer_t /*buffer*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_oid_set
+ (OM_uint32 * /*minor_status*/,
+ gss_OID_set * /*set*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_cred
+ (OM_uint32 * /*minor_status*/,
+ gss_const_cred_id_t /*cred_handle*/,
+ gss_name_t * /*name*/,
+ OM_uint32 * /*lifetime*/,
+ gss_cred_usage_t * /*cred_usage*/,
+ gss_OID_set * /*mechanisms*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_context (
+ OM_uint32 * /*minor_status*/,
+ gss_const_ctx_id_t /*context_handle*/,
+ gss_name_t * /*src_name*/,
+ gss_name_t * /*targ_name*/,
+ OM_uint32 * /*lifetime_rec*/,
+ gss_OID * /*mech_type*/,
+ OM_uint32 * /*ctx_flags*/,
+ int * /*locally_initiated*/,
+ int * /*open_context*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_wrap_size_limit (
+ OM_uint32 * /*minor_status*/,
+ gss_const_ctx_id_t /*context_handle*/,
+ int /*conf_req_flag*/,
+ gss_qop_t /*qop_req*/,
+ OM_uint32 /*req_output_size*/,
+ OM_uint32 * /*max_input_size*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_add_cred (
+ OM_uint32 * /*minor_status*/,
+ gss_const_cred_id_t /*input_cred_handle*/,
+ gss_const_name_t /*desired_name*/,
+ const gss_OID /*desired_mech*/,
+ gss_cred_usage_t /*cred_usage*/,
+ OM_uint32 /*initiator_time_req*/,
+ OM_uint32 /*acceptor_time_req*/,
+ gss_cred_id_t * /*output_cred_handle*/,
+ gss_OID_set * /*actual_mechs*/,
+ OM_uint32 * /*initiator_time_rec*/,
+ OM_uint32 * /*acceptor_time_rec*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_cred_by_mech (
+ OM_uint32 * /*minor_status*/,
+ gss_const_cred_id_t /*cred_handle*/,
+ const gss_OID /*mech_type*/,
+ gss_name_t * /*name*/,
+ OM_uint32 * /*initiator_lifetime*/,
+ OM_uint32 * /*acceptor_lifetime*/,
+ gss_cred_usage_t * /*cred_usage*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_export_sec_context (
+ OM_uint32 * /*minor_status*/,
+ gss_ctx_id_t * /*context_handle*/,
+ gss_buffer_t /*interprocess_token*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_import_sec_context (
+ OM_uint32 * /*minor_status*/,
+ const gss_buffer_t /*interprocess_token*/,
+ gss_ctx_id_t * /*context_handle*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_create_empty_oid_set (
+ OM_uint32 * /*minor_status*/,
+ gss_OID_set * /*oid_set*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_add_oid_set_member (
+ OM_uint32 * /*minor_status*/,
+ const gss_OID /*member_oid*/,
+ gss_OID_set * /*oid_set*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_test_oid_set_member (
+ OM_uint32 * /*minor_status*/,
+ const gss_OID /*member*/,
+ const gss_OID_set /*set*/,
+ int * /*present*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_names_for_mech (
+ OM_uint32 * /*minor_status*/,
+ const gss_OID /*mechanism*/,
+ gss_OID_set * /*name_types*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_mechs_for_name (
+ OM_uint32 * /*minor_status*/,
+ gss_const_name_t /*input_name*/,
+ gss_OID_set * /*mech_types*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_canonicalize_name (
+ OM_uint32 * /*minor_status*/,
+ gss_const_name_t /*input_name*/,
+ const gss_OID /*mech_type*/,
+ gss_name_t * /*output_name*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_duplicate_name (
+ OM_uint32 * /*minor_status*/,
+ gss_const_name_t /*src_name*/,
+ gss_name_t * /*dest_name*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_duplicate_oid (
+ OM_uint32 * /* minor_status */,
+ gss_OID /* src_oid */,
+ gss_OID * /* dest_oid */
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_duplicate_oid_set (
+ OM_uint32 * /* minor_status */,
+ gss_OID_set /* src_oid */,
+ gss_OID_set * /* dest_oid */
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_release_oid
+ (OM_uint32 * /*minor_status*/,
+ gss_OID * /* oid */
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_oid_to_str(
+ OM_uint32 * /*minor_status*/,
+ gss_OID /* oid */,
+ gss_buffer_t /* str */
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_sec_context_by_oid(
+ OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_OID desired_object,
+ gss_buffer_set_t *data_set
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_set_sec_context_option (OM_uint32 *minor_status,
+ gss_ctx_id_t *context_handle,
+ const gss_OID desired_object,
+ const gss_buffer_t value);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_set_cred_option (OM_uint32 *minor_status,
+ gss_cred_id_t *cred_handle,
+ const gss_OID object,
+ const gss_buffer_t value);
+
+GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL
+gss_oid_equal(gss_const_OID a, gss_const_OID b);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_create_empty_buffer_set
+ (OM_uint32 * minor_status,
+ gss_buffer_set_t *buffer_set);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_add_buffer_set_member
+ (OM_uint32 * minor_status,
+ const gss_buffer_t member_buffer,
+ gss_buffer_set_t *buffer_set);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_release_buffer_set
+ (OM_uint32 * minor_status,
+ gss_buffer_set_t *buffer_set);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_cred_by_oid(OM_uint32 *minor_status,
+ gss_const_cred_id_t cred_handle,
+ const gss_OID desired_object,
+ gss_buffer_set_t *data_set);
+
+/*
+ * RFC 4401
+ */
+
+#define GSS_C_PRF_KEY_FULL 0
+#define GSS_C_PRF_KEY_PARTIAL 1
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_pseudo_random
+ (OM_uint32 *minor_status,
+ gss_ctx_id_t context,
+ int prf_key,
+ const gss_buffer_t prf_in,
+ ssize_t desired_output_len,
+ gss_buffer_t prf_out
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_store_cred(OM_uint32 * /* minor_status */,
+ gss_cred_id_t /* input_cred_handle */,
+ gss_cred_usage_t /* cred_usage */,
+ const gss_OID /* desired_mech */,
+ OM_uint32 /* overwrite_cred */,
+ OM_uint32 /* default_cred */,
+ gss_OID_set * /* elements_stored */,
+ gss_cred_usage_t * /* cred_usage_stored */);
+
+
+/*
+ * Query functions
+ */
+
+typedef struct {
+ size_t header; /**< size of header */
+ size_t trailer; /**< size of trailer */
+ size_t max_msg_size; /**< maximum message size */
+ size_t buffers; /**< extra GSS_IOV_BUFFER_TYPE_EMPTY buffer to pass */
+ size_t blocksize; /**< Specificed optimal size of messages, also
+ is the maximum padding size
+ (GSS_IOV_BUFFER_TYPE_PADDING) */
+} gss_context_stream_sizes;
+
+extern gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_attr_stream_sizes_oid_desc;
+#define GSS_C_ATTR_STREAM_SIZES (&__gss_c_attr_stream_sizes_oid_desc)
+
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_context_query_attributes(OM_uint32 * /* minor_status */,
+ gss_const_ctx_id_t /* context_handle */,
+ const gss_OID /* attribute */,
+ void * /*data*/,
+ size_t /* len */);
+/*
+ * The following routines are obsolete variants of gss_get_mic,
+ * gss_verify_mic, gss_wrap and gss_unwrap. They should be
+ * provided by GSSAPI V2 implementations for backwards
+ * compatibility with V1 applications. Distinct entrypoints
+ * (as opposed to #defines) should be provided, both to allow
+ * GSSAPI V1 applications to link against GSSAPI V2 implementations,
+ * and to retain the slight parameter type differences between the
+ * obsolete versions of these routines and their current forms.
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_sign
+ (OM_uint32 * /*minor_status*/,
+ gss_ctx_id_t /*context_handle*/,
+ int /*qop_req*/,
+ gss_buffer_t /*message_buffer*/,
+ gss_buffer_t /*message_token*/
+ ) GSSAPI_DEPRECATED_FUNCTION("Use gss_get_mic");
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_verify
+ (OM_uint32 * /*minor_status*/,
+ gss_ctx_id_t /*context_handle*/,
+ gss_buffer_t /*message_buffer*/,
+ gss_buffer_t /*token_buffer*/,
+ int * /*qop_state*/
+ ) GSSAPI_DEPRECATED_FUNCTION("Use gss_verify_mic");
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_seal
+ (OM_uint32 * /*minor_status*/,
+ gss_ctx_id_t /*context_handle*/,
+ int /*conf_req_flag*/,
+ int /*qop_req*/,
+ gss_buffer_t /*input_message_buffer*/,
+ int * /*conf_state*/,
+ gss_buffer_t /*output_message_buffer*/
+ ) GSSAPI_DEPRECATED_FUNCTION("Use gss_wrap");
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_unseal
+ (OM_uint32 * /*minor_status*/,
+ gss_ctx_id_t /*context_handle*/,
+ gss_buffer_t /*input_message_buffer*/,
+ gss_buffer_t /*output_message_buffer*/,
+ int * /*conf_state*/,
+ int * /*qop_state*/
+ ) GSSAPI_DEPRECATED_FUNCTION("Use gss_unwrap");
+
+/**
+ *
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_encapsulate_token(gss_const_buffer_t /* input_token */,
+ gss_const_OID /* oid */,
+ gss_buffer_t /* output_token */);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_decapsulate_token(gss_const_buffer_t /* input_token */,
+ gss_const_OID /* oid */,
+ gss_buffer_t /* output_token */);
+
+
+
+/*
+ * AEAD support
+ */
+
+/*
+ * GSS_IOV
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_wrap_iov(OM_uint32 *, gss_ctx_id_t, int, gss_qop_t, int *,
+ gss_iov_buffer_desc *, int);
+
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_unwrap_iov(OM_uint32 *, gss_ctx_id_t, int *, gss_qop_t *,
+ gss_iov_buffer_desc *, int);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_wrap_iov_length(OM_uint32 *, gss_ctx_id_t, int, gss_qop_t, int *,
+ gss_iov_buffer_desc *, int);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_release_iov_buffer(OM_uint32 *, gss_iov_buffer_desc *, int);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_wrap_aead(OM_uint32 *, gss_ctx_id_t, int, gss_qop_t,
+ gss_buffer_t, gss_buffer_t, int *, gss_buffer_t);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_unwrap_aead(OM_uint32 *, gss_ctx_id_t, gss_buffer_t,
+ gss_buffer_t, gss_buffer_t, int *, gss_qop_t *);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_export_cred(OM_uint32 * /* minor_status */,
+ gss_cred_id_t /* cred_handle */,
+ gss_buffer_t /* cred_token */);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_import_cred(OM_uint32 * /* minor_status */,
+ gss_buffer_t /* cred_token */,
+ gss_cred_id_t * /* cred_handle */);
+
+/*
+ * mech option
+ */
+
+GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL
+gss_mo_set(gss_const_OID mech, gss_const_OID option,
+ int enable, gss_buffer_t value);
+
+GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL
+gss_mo_get(gss_const_OID mech, gss_const_OID option, gss_buffer_t value);
+
+GSSAPI_LIB_FUNCTION void GSSAPI_LIB_CALL
+gss_mo_list(gss_const_OID mech, gss_OID_set *options);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_mo_name(gss_const_OID mech, gss_const_OID options, gss_buffer_t name);
+
+/*
+ * SASL glue functions and mech inquire
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_saslname_for_mech(OM_uint32 *minor_status,
+ const gss_OID desired_mech,
+ gss_buffer_t sasl_mech_name,
+ gss_buffer_t mech_name,
+ gss_buffer_t mech_description);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_mech_for_saslname(OM_uint32 *minor_status,
+ const gss_buffer_t sasl_mech_name,
+ gss_OID *mech_type);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_indicate_mechs_by_attrs(OM_uint32 * minor_status,
+ gss_const_OID_set desired_mech_attrs,
+ gss_const_OID_set except_mech_attrs,
+ gss_const_OID_set critical_mech_attrs,
+ gss_OID_set *mechs);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_attrs_for_mech(OM_uint32 * minor_status,
+ gss_const_OID mech,
+ gss_OID_set *mech_attr,
+ gss_OID_set *known_mech_attrs);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_display_mech_attr(OM_uint32 * minor_status,
+ gss_const_OID mech_attr,
+ gss_buffer_t name,
+ gss_buffer_t short_desc,
+ gss_buffer_t long_desc);
+
+/*
+ * Solaris compat
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_acquire_cred_with_password
+ (OM_uint32 * /*minor_status*/,
+ gss_const_name_t /*desired_name*/,
+ const gss_buffer_t /*password*/,
+ OM_uint32 /*time_req*/,
+ const gss_OID_set /*desired_mechs*/,
+ gss_cred_usage_t /*cred_usage*/,
+ gss_cred_id_t * /*output_cred_handle*/,
+ gss_OID_set * /*actual_mechs*/,
+ OM_uint32 * /*time_rec*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_add_cred_with_password (
+ OM_uint32 * /*minor_status*/,
+ gss_const_cred_id_t /*input_cred_handle*/,
+ gss_const_name_t /*desired_name*/,
+ const gss_OID /*desired_mech*/,
+ const gss_buffer_t /*password*/,
+ gss_cred_usage_t /*cred_usage*/,
+ OM_uint32 /*initiator_time_req*/,
+ OM_uint32 /*acceptor_time_req*/,
+ gss_cred_id_t * /*output_cred_handle*/,
+ gss_OID_set * /*actual_mechs*/,
+ OM_uint32 * /*initiator_time_rec*/,
+ OM_uint32 * /*acceptor_time_rec*/
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_localname(
+ OM_uint32 *minor,
+ gss_const_name_t name,
+ const gss_OID mech_type,
+ gss_buffer_t localname);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_pname_to_uid(
+ OM_uint32 *minor,
+ gss_const_name_t name,
+ const gss_OID mech_type,
+ uid_t *uidOut);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_authorize_localname(
+ OM_uint32 *minor,
+ gss_const_name_t name,
+ gss_const_name_t user);
+
+GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL
+gss_userok(gss_const_name_t name,
+ const char *user);
+
+extern GSSAPI_LIB_VARIABLE gss_buffer_desc __gss_c_attr_local_login_user;
+#define GSS_C_ATTR_LOCAL_LOGIN_USER (&__gss_c_attr_local_login_user)
+
+/*
+ * Naming extensions
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_display_name_ext (
+ OM_uint32 *, /* minor_status */
+ gss_name_t, /* name */
+ gss_OID, /* display_as_name_type */
+ gss_buffer_t /* display_name */
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_name (
+ OM_uint32 *, /* minor_status */
+ gss_name_t, /* name */
+ int *, /* name_is_MN */
+ gss_OID *, /* MN_mech */
+ gss_buffer_set_t * /* attrs */
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_get_name_attribute (
+ OM_uint32 *, /* minor_status */
+ gss_name_t, /* name */
+ gss_buffer_t, /* attr */
+ int *, /* authenticated */
+ int *, /* complete */
+ gss_buffer_t, /* value */
+ gss_buffer_t, /* display_value */
+ int * /* more */
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_set_name_attribute (
+ OM_uint32 *, /* minor_status */
+ gss_name_t, /* name */
+ int, /* complete */
+ gss_buffer_t, /* attr */
+ gss_buffer_t /* value */
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_delete_name_attribute (
+ OM_uint32 *, /* minor_status */
+ gss_name_t, /* name */
+ gss_buffer_t /* attr */
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_export_name_composite (
+ OM_uint32 *, /* minor_status */
+ gss_name_t, /* name */
+ gss_buffer_t /* exp_composite_name */
+ );
+
+/*
+ * Other extensions
+ */
+
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_duplicate_cred (
+ OM_uint32 * /*minor_status*/,
+ gss_const_cred_id_t /*input_cred_handle*/,
+ gss_cred_id_t * /*output_cred_handle*/
+ );
+
+/* Return a mechanism short name from an OID */
+GSSAPI_LIB_FUNCTION const char * GSSAPI_LIB_CALL
+gss_oid_to_name(gss_const_OID oid);
+
+/* Return a mechanism OID from a short name or dotted OID */
+GSSAPI_LIB_FUNCTION gss_OID GSSAPI_LIB_CALL
+gss_name_to_oid(const char *name);
+
+/*
+ * Credential store extensions
+ */
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_acquire_cred_from(
+ OM_uint32 * /* minor_status */,
+ gss_const_name_t /* desired_name */,
+ OM_uint32 /* time_req */,
+ const gss_OID_set /* desired_mechs */,
+ gss_cred_usage_t /* cred_usage */,
+ gss_const_key_value_set_t /* cred_store */,
+ gss_cred_id_t * /* output_cred_handle */,
+ gss_OID_set * /* actual_mechs */,
+ OM_uint32 * /* time_rec */
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_add_cred_from(
+ OM_uint32 * /* minor_status */,
+ gss_cred_id_t /* input_cred_handle */,
+ gss_const_name_t /* desired_name */,
+ const gss_OID /* desired_mech */,
+ gss_cred_usage_t /* cred_usage */,
+ OM_uint32 /* initiator_time_req */,
+ OM_uint32 /* acceptor_time_req */,
+ gss_const_key_value_set_t /* cred_store */,
+ gss_cred_id_t * /* output_cred_handle */,
+ gss_OID_set * /* actual_mechs */,
+ OM_uint32 * /* initiator_time_rec */,
+ OM_uint32 * /*acceptor_time_rec */
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_store_cred_into(
+ OM_uint32 * /* minor_status */,
+ gss_const_cred_id_t /* input_cred_handle */,
+ gss_cred_usage_t /* input_usage */,
+ const gss_OID /* desired_mech */,
+ OM_uint32 /* overwrite_cred */,
+ OM_uint32 /* default_cred */,
+ gss_const_key_value_set_t /* cred_store */,
+ gss_OID_set * /* elements_stored */,
+ gss_cred_usage_t * /* cred_usage_stored */
+ );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_store_cred_into2(
+ OM_uint32 * /* minor_status */,
+ gss_const_cred_id_t /* input_cred_handle */,
+ gss_cred_usage_t /* input_usage */,
+ const gss_OID /* desired_mech */,
+ OM_uint32 /* store_cred_flags */,
+ gss_const_key_value_set_t /* cred_store */,
+ gss_OID_set * /* elements_stored */,
+ gss_cred_usage_t * /* cred_usage_stored */,
+ gss_buffer_set_t * /* env */
+ );
+
+enum gss_store_cred_flags {
+ GSS_C_STORE_CRED_DEFAULT = 1,
+ GSS_C_STORE_CRED_OVERWRITE = 2,
+ GSS_C_STORE_CRED_SET_PROCESS = 4,
+};
+#define GSS_C_STORE_CRED_DEFAULT GSS_C_STORE_CRED_DEFAULT
+#define GSS_C_STORE_CRED_OVERWRITE GSS_C_STORE_CRED_OVERWRITE
+#define GSS_C_STORE_CRED_SET_PROCESS GSS_C_STORE_CRED_SET_PROCESS
+
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_CALLCONV
+gss_set_neg_mechs(
+ OM_uint32 * /* minor_status */,
+ gss_cred_id_t /* cred_handle */,
+ const gss_OID_set /* mech_list */);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_CALLCONV
+gss_get_neg_mechs(
+ OM_uint32 * /* minor_status */,
+ gss_const_cred_id_t /* cred_handle */,
+ gss_OID_set * /* mech_list */);
+
+GSSAPI_LIB_FUNCTION void GSSAPI_LIB_CALL
+gss_set_log_function(void *ctx, void (*func)(void * ctx, int level, const char *fmt, va_list));
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_destroy_cred(OM_uint32 *minor_status,
+ gss_cred_id_t *cred_handle);
+
+/*
+ * S4UProxy and S4USelf extensions.
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_CALLCONV
+gss_acquire_cred_impersonate_name(
+ OM_uint32 * /* minor_status */,
+ gss_const_cred_id_t /* icred */,
+ gss_const_name_t /* desired_name */,
+ OM_uint32 /* time_req */,
+ gss_OID_set /* desired_mechs */,
+ gss_cred_usage_t /* cred_usage */,
+ gss_cred_id_t * /* output_cred */,
+ gss_OID_set * /* actual_mechs */,
+ OM_uint32 * /* time_rec */
+ );
+
+GSSAPI_CPP_END
+
+#if defined(__APPLE__) && (defined(__ppc__) || defined(__ppc64__) || defined(__i386__) || defined(__x86_64__))
+#pragma pack(pop)
+#endif
+
+#undef GSSAPI_DEPRECATED_FUNCTION
+
+#endif /* GSSAPI_GSSAPI_H_ */
diff --git a/third_party/heimdal/lib/gssapi/gssapi/gssapi_krb5.h b/third_party/heimdal/lib/gssapi/gssapi/gssapi_krb5.h
new file mode 100644
index 0000000..818042f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gssapi/gssapi_krb5.h
@@ -0,0 +1,225 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef GSSAPI_KRB5_H_
+#define GSSAPI_KRB5_H_
+
+#include <gssapi.h>
+#include <gssapi/gssapi_oid.h>
+
+GSSAPI_CPP_START
+
+#if !defined(__GNUC__) && !defined(__attribute__)
+#define __attribute__(x)
+#endif
+
+#ifndef GSSKRB5_FUNCTION_DEPRECATED
+#define GSSKRB5_FUNCTION_DEPRECATED __attribute__((deprecated))
+#endif
+
+
+/*
+ * This is for kerberos5 names.
+ */
+
+extern gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_nt_principal_name_oid_desc;
+#define GSS_KRB5_NT_PRINCIPAL_NAME (&__gss_krb5_nt_principal_name_oid_desc)
+
+#define GSS_KRB5_NT_USER_NAME (&__gss_c_nt_user_name_oid_desc)
+#define GSS_KRB5_NT_MACHINE_UID_NAME (&__gss_c_nt_machine_uid_name_oid_desc)
+#define GSS_KRB5_NT_STRING_UID_NAME (&__gss_c_nt_string_uid_name_oid_desc)
+
+/* for compatibility with MIT api */
+
+#define gss_mech_krb5 GSS_KRB5_MECHANISM
+#define gss_krb5_nt_general_name GSS_KRB5_NT_PRINCIPAL_NAME
+
+/*
+ * kerberos mechanism specific functions
+ */
+
+struct krb5_keytab_data;
+struct krb5_ccache_data;
+struct Principal;
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_ccache_name(OM_uint32 * /*minor_status*/,
+ const char * /*name */,
+ const char ** /*out_name */);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_register_acceptor_identity
+ (const char * /*identity*/);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL krb5_gss_register_acceptor_identity
+ (const char * /*identity*/);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_copy_ccache
+ (OM_uint32 * /*minor*/,
+ gss_cred_id_t /*cred*/,
+ struct krb5_ccache_data * /*out*/);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_import_cred(OM_uint32 * /*minor*/,
+ struct krb5_ccache_data * /*in*/,
+ struct Principal * /*keytab_principal*/,
+ struct krb5_keytab_data * /*keytab*/,
+ gss_cred_id_t * /*out*/);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_get_tkt_flags
+ (OM_uint32 * /*minor*/,
+ gss_ctx_id_t /*context_handle*/,
+ OM_uint32 * /*tkt_flags*/);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_extract_authz_data_from_sec_context
+ (OM_uint32 * /*minor_status*/,
+ gss_ctx_id_t /*context_handle*/,
+ int /*ad_type*/,
+ gss_buffer_t /*ad_data*/);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_set_dns_canonicalize(int);
+
+struct gsskrb5_send_to_kdc {
+ void *func;
+ void *ptr;
+};
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_set_send_to_kdc(struct gsskrb5_send_to_kdc *)
+ GSSKRB5_FUNCTION_DEPRECATED;
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_set_default_realm(const char *);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_extract_authtime_from_sec_context(OM_uint32 *, gss_ctx_id_t, time_t *);
+
+struct EncryptionKey;
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_extract_service_keyblock(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ struct EncryptionKey **out);
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_get_initiator_subkey(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ struct EncryptionKey **out);
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_get_subkey(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ struct EncryptionKey **out);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_set_time_offset(int);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_get_time_offset(int *);
+
+struct gsskrb5_krb5_plugin {
+ int type;
+ char *name;
+ void *symbol;
+};
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_plugin_register(struct gsskrb5_krb5_plugin *);
+
+
+/*
+ * Lucid - NFSv4 interface to GSS-API KRB5 to expose key material to
+ * do GSS content token handling in-kernel.
+ */
+
+typedef struct gss_krb5_lucid_key {
+ OM_uint32 type;
+ OM_uint32 length;
+ void * data;
+} gss_krb5_lucid_key_t;
+
+typedef struct gss_krb5_rfc1964_keydata {
+ OM_uint32 sign_alg;
+ OM_uint32 seal_alg;
+ gss_krb5_lucid_key_t ctx_key;
+} gss_krb5_rfc1964_keydata_t;
+
+typedef struct gss_krb5_cfx_keydata {
+ OM_uint32 have_acceptor_subkey;
+ gss_krb5_lucid_key_t ctx_key;
+ gss_krb5_lucid_key_t acceptor_subkey;
+} gss_krb5_cfx_keydata_t;
+
+typedef struct gss_krb5_lucid_context_v1 {
+ OM_uint32 version;
+ OM_uint32 initiate;
+ OM_uint32 endtime;
+ OM_uint64 send_seq;
+ OM_uint64 recv_seq;
+ OM_uint32 protocol;
+ gss_krb5_rfc1964_keydata_t rfc1964_kd;
+ gss_krb5_cfx_keydata_t cfx_kd;
+} gss_krb5_lucid_context_v1_t;
+
+typedef struct gss_krb5_lucid_context_version {
+ OM_uint32 version; /* Structure version number */
+} gss_krb5_lucid_context_version_t;
+
+/*
+ * Function declarations
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_export_lucid_sec_context(OM_uint32 *minor_status,
+ gss_ctx_id_t *context_handle,
+ OM_uint32 version,
+ void **kctx);
+
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_free_lucid_sec_context(OM_uint32 *minor_status,
+ void *kctx);
+
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_set_allowable_enctypes(OM_uint32 *minor_status,
+ gss_cred_id_t cred,
+ OM_uint32 num_enctypes,
+ int32_t *enctypes);
+
+#define GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "urn:ietf:kerberos:nameattr-"
+
+GSSAPI_CPP_END
+
+#endif /* GSSAPI_SPNEGO_H_ */
diff --git a/third_party/heimdal/lib/gssapi/gssapi/gssapi_netlogon.h b/third_party/heimdal/lib/gssapi/gssapi/gssapi_netlogon.h
new file mode 100644
index 0000000..52201a6
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gssapi/gssapi_netlogon.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2006 - 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef GSSAPI_NETLOGON_H_
+#define GSSAPI_NETLOGON_H_
+
+#include <gssapi.h>
+
+GSSAPI_CPP_START
+
+extern GSSAPI_LIB_VARIABLE gss_OID GSS_NETLOGON_MECHANISM;
+extern GSSAPI_LIB_VARIABLE gss_OID GSS_NETLOGON_NT_NETBIOS_DNS_NAME;
+extern GSSAPI_LIB_VARIABLE gss_OID GSS_NETLOGON_SET_SESSION_KEY_X;
+extern GSSAPI_LIB_VARIABLE gss_OID GSS_NETLOGON_SET_SIGN_ALGORITHM_X;
+
+GSSAPI_CPP_END
+
+#endif /* GSSAPI_NETLOGON_H_ */
diff --git a/third_party/heimdal/lib/gssapi/gssapi/gssapi_ntlm.h b/third_party/heimdal/lib/gssapi/gssapi/gssapi_ntlm.h
new file mode 100644
index 0000000..e37c003
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gssapi/gssapi_ntlm.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2006 - 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef GSSAPI_NTLM_H_
+#define GSSAPI_NTLM_H_
+
+#include <gssapi.h>
+
+#endif /* GSSAPI_NTLM_H_ */
diff --git a/third_party/heimdal/lib/gssapi/gssapi/gssapi_oid.h b/third_party/heimdal/lib/gssapi/gssapi/gssapi_oid.h
new file mode 100644
index 0000000..fabd090
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gssapi/gssapi_oid.h
@@ -0,0 +1,262 @@
+/* Generated file */
+#ifndef GSSAPI_GSSAPI_OID
+#define GSSAPI_GSSAPI_OID 1
+
+ /* contact Love Hörnquist Åstrand <lha@h5l.org> for new oid arcs */
+ /*
+ * 1.2.752.43.13 Heimdal GSS-API Extensions
+ */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_copy_ccache_x_oid_desc;
+#define GSS_KRB5_COPY_CCACHE_X (&__gss_krb5_copy_ccache_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_get_tkt_flags_x_oid_desc;
+#define GSS_KRB5_GET_TKT_FLAGS_X (&__gss_krb5_get_tkt_flags_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_extract_authz_data_from_sec_context_x_oid_desc;
+#define GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X (&__gss_krb5_extract_authz_data_from_sec_context_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_compat_des3_mic_x_oid_desc;
+#define GSS_KRB5_COMPAT_DES3_MIC_X (&__gss_krb5_compat_des3_mic_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_register_acceptor_identity_x_oid_desc;
+#define GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X (&__gss_krb5_register_acceptor_identity_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_export_lucid_context_x_oid_desc;
+#define GSS_KRB5_EXPORT_LUCID_CONTEXT_X (&__gss_krb5_export_lucid_context_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_export_lucid_context_v1_x_oid_desc;
+#define GSS_KRB5_EXPORT_LUCID_CONTEXT_V1_X (&__gss_krb5_export_lucid_context_v1_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_set_dns_canonicalize_x_oid_desc;
+#define GSS_KRB5_SET_DNS_CANONICALIZE_X (&__gss_krb5_set_dns_canonicalize_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_get_subkey_x_oid_desc;
+#define GSS_KRB5_GET_SUBKEY_X (&__gss_krb5_get_subkey_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_get_initiator_subkey_x_oid_desc;
+#define GSS_KRB5_GET_INITIATOR_SUBKEY_X (&__gss_krb5_get_initiator_subkey_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_get_acceptor_subkey_x_oid_desc;
+#define GSS_KRB5_GET_ACCEPTOR_SUBKEY_X (&__gss_krb5_get_acceptor_subkey_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_send_to_kdc_x_oid_desc;
+#define GSS_KRB5_SEND_TO_KDC_X (&__gss_krb5_send_to_kdc_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_get_authtime_x_oid_desc;
+#define GSS_KRB5_GET_AUTHTIME_X (&__gss_krb5_get_authtime_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_get_service_keyblock_x_oid_desc;
+#define GSS_KRB5_GET_SERVICE_KEYBLOCK_X (&__gss_krb5_get_service_keyblock_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_set_allowable_enctypes_x_oid_desc;
+#define GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X (&__gss_krb5_set_allowable_enctypes_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_set_default_realm_x_oid_desc;
+#define GSS_KRB5_SET_DEFAULT_REALM_X (&__gss_krb5_set_default_realm_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_ccache_name_x_oid_desc;
+#define GSS_KRB5_CCACHE_NAME_X (&__gss_krb5_ccache_name_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_set_time_offset_x_oid_desc;
+#define GSS_KRB5_SET_TIME_OFFSET_X (&__gss_krb5_set_time_offset_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_get_time_offset_x_oid_desc;
+#define GSS_KRB5_GET_TIME_OFFSET_X (&__gss_krb5_get_time_offset_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_plugin_register_x_oid_desc;
+#define GSS_KRB5_PLUGIN_REGISTER_X (&__gss_krb5_plugin_register_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_ntlm_get_session_key_x_oid_desc;
+#define GSS_NTLM_GET_SESSION_KEY_X (&__gss_ntlm_get_session_key_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_ntlm_oid_desc;
+#define GSS_C_NT_NTLM (&__gss_c_nt_ntlm_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_dn_oid_desc;
+#define GSS_C_NT_DN (&__gss_c_nt_dn_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_nt_principal_name_referral_oid_desc;
+#define GSS_KRB5_NT_PRINCIPAL_NAME_REFERRAL (&__gss_krb5_nt_principal_name_referral_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ntlm_avguest_oid_desc;
+#define GSS_C_NTLM_AVGUEST (&__gss_c_ntlm_avguest_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ntlm_v1_oid_desc;
+#define GSS_C_NTLM_V1 (&__gss_c_ntlm_v1_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ntlm_v2_oid_desc;
+#define GSS_C_NTLM_V2 (&__gss_c_ntlm_v2_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ntlm_session_key_oid_desc;
+#define GSS_C_NTLM_SESSION_KEY (&__gss_c_ntlm_session_key_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ntlm_force_v1_oid_desc;
+#define GSS_C_NTLM_FORCE_V1 (&__gss_c_ntlm_force_v1_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_cred_no_ci_flags_x_oid_desc;
+#define GSS_KRB5_CRED_NO_CI_FLAGS_X (&__gss_krb5_cred_no_ci_flags_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_import_cred_x_oid_desc;
+#define GSS_KRB5_IMPORT_CRED_X (&__gss_krb5_import_cred_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_import_rfc4121_context_x_oid_desc;
+#define GSS_KRB5_IMPORT_RFC4121_CONTEXT_X (&__gss_krb5_import_rfc4121_context_x_oid_desc)
+
+ /* glue for gss_inquire_saslname_for_mech */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_sasl_mech_name_oid_desc;
+#define GSS_C_MA_SASL_MECH_NAME (&__gss_c_ma_sasl_mech_name_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mech_name_oid_desc;
+#define GSS_C_MA_MECH_NAME (&__gss_c_ma_mech_name_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mech_description_oid_desc;
+#define GSS_C_MA_MECH_DESCRIPTION (&__gss_c_ma_mech_description_oid_desc)
+
+/* Heimdal mechanisms - 1.2.752.43.14 */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_sasl_digest_md5_mechanism_oid_desc;
+#define GSS_SASL_DIGEST_MD5_MECHANISM (&__gss_sasl_digest_md5_mechanism_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_netlogon_mechanism_oid_desc;
+#define GSS_NETLOGON_MECHANISM (&__gss_netlogon_mechanism_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_netlogon_set_session_key_x_oid_desc;
+#define GSS_NETLOGON_SET_SESSION_KEY_X (&__gss_netlogon_set_session_key_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_netlogon_set_sign_algorithm_x_oid_desc;
+#define GSS_NETLOGON_SET_SIGN_ALGORITHM_X (&__gss_netlogon_set_sign_algorithm_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_netlogon_nt_netbios_dns_name_oid_desc;
+#define GSS_NETLOGON_NT_NETBIOS_DNS_NAME (&__gss_netlogon_nt_netbios_dns_name_oid_desc)
+
+/* GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X.128 */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_inq_win2k_pac_x_oid_desc;
+#define GSS_C_INQ_WIN2K_PAC_X (&__gss_c_inq_win2k_pac_x_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_inq_sspi_session_key_oid_desc;
+#define GSS_C_INQ_SSPI_SESSION_KEY (&__gss_c_inq_sspi_session_key_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_inq_negoex_key_oid_desc;
+#define GSS_C_INQ_NEGOEX_KEY (&__gss_c_inq_negoex_key_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_inq_negoex_verify_key_oid_desc;
+#define GSS_C_INQ_NEGOEX_VERIFY_KEY (&__gss_c_inq_negoex_verify_key_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_inq_require_mechlist_mic_oid_desc;
+#define GSS_C_INQ_REQUIRE_MECHLIST_MIC (&__gss_c_inq_require_mechlist_mic_oid_desc)
+
+/*
+ * "Standard" mechs
+ */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_mechanism_oid_desc;
+#define GSS_KRB5_MECHANISM (&__gss_krb5_mechanism_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_ntlm_mechanism_oid_desc;
+#define GSS_NTLM_MECHANISM (&__gss_ntlm_mechanism_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_spnego_mechanism_oid_desc;
+#define GSS_SPNEGO_MECHANISM (&__gss_spnego_mechanism_oid_desc)
+
+ /* From Luke Howard */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_inq_peer_has_buggy_spnego_oid_desc;
+#define GSS_C_INQ_PEER_HAS_BUGGY_SPNEGO (&__gss_c_inq_peer_has_buggy_spnego_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ntlm_reset_crypto_oid_desc;
+#define GSS_C_NTLM_RESET_CRYPTO (&__gss_c_ntlm_reset_crypto_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_negoex_mechanism_oid_desc;
+#define GSS_NEGOEX_MECHANISM (&__gss_negoex_mechanism_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_sanon_x25519_mechanism_oid_desc;
+#define GSS_SANON_X25519_MECHANISM (&__gss_sanon_x25519_mechanism_oid_desc)
+
+/*
+ * OID mappings with name and short description and and slightly longer description
+ */
+/*
+ * RFC5587
+ */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mech_concrete_oid_desc;
+#define GSS_C_MA_MECH_CONCRETE (&__gss_c_ma_mech_concrete_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mech_pseudo_oid_desc;
+#define GSS_C_MA_MECH_PSEUDO (&__gss_c_ma_mech_pseudo_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mech_composite_oid_desc;
+#define GSS_C_MA_MECH_COMPOSITE (&__gss_c_ma_mech_composite_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mech_nego_oid_desc;
+#define GSS_C_MA_MECH_NEGO (&__gss_c_ma_mech_nego_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mech_glue_oid_desc;
+#define GSS_C_MA_MECH_GLUE (&__gss_c_ma_mech_glue_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_not_mech_oid_desc;
+#define GSS_C_MA_NOT_MECH (&__gss_c_ma_not_mech_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_deprecated_oid_desc;
+#define GSS_C_MA_DEPRECATED (&__gss_c_ma_deprecated_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_not_dflt_mech_oid_desc;
+#define GSS_C_MA_NOT_DFLT_MECH (&__gss_c_ma_not_dflt_mech_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_itok_framed_oid_desc;
+#define GSS_C_MA_ITOK_FRAMED (&__gss_c_ma_itok_framed_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_auth_init_oid_desc;
+#define GSS_C_MA_AUTH_INIT (&__gss_c_ma_auth_init_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_auth_targ_oid_desc;
+#define GSS_C_MA_AUTH_TARG (&__gss_c_ma_auth_targ_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_auth_init_init_oid_desc;
+#define GSS_C_MA_AUTH_INIT_INIT (&__gss_c_ma_auth_init_init_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_auth_targ_init_oid_desc;
+#define GSS_C_MA_AUTH_TARG_INIT (&__gss_c_ma_auth_targ_init_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_auth_init_anon_oid_desc;
+#define GSS_C_MA_AUTH_INIT_ANON (&__gss_c_ma_auth_init_anon_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_auth_targ_anon_oid_desc;
+#define GSS_C_MA_AUTH_TARG_ANON (&__gss_c_ma_auth_targ_anon_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_deleg_cred_oid_desc;
+#define GSS_C_MA_DELEG_CRED (&__gss_c_ma_deleg_cred_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_integ_prot_oid_desc;
+#define GSS_C_MA_INTEG_PROT (&__gss_c_ma_integ_prot_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_conf_prot_oid_desc;
+#define GSS_C_MA_CONF_PROT (&__gss_c_ma_conf_prot_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mic_oid_desc;
+#define GSS_C_MA_MIC (&__gss_c_ma_mic_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_wrap_oid_desc;
+#define GSS_C_MA_WRAP (&__gss_c_ma_wrap_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_prot_ready_oid_desc;
+#define GSS_C_MA_PROT_READY (&__gss_c_ma_prot_ready_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_replay_det_oid_desc;
+#define GSS_C_MA_REPLAY_DET (&__gss_c_ma_replay_det_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_oos_det_oid_desc;
+#define GSS_C_MA_OOS_DET (&__gss_c_ma_oos_det_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_cbindings_oid_desc;
+#define GSS_C_MA_CBINDINGS (&__gss_c_ma_cbindings_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_pfs_oid_desc;
+#define GSS_C_MA_PFS (&__gss_c_ma_pfs_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_compress_oid_desc;
+#define GSS_C_MA_COMPRESS (&__gss_c_ma_compress_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_ctx_trans_oid_desc;
+#define GSS_C_MA_CTX_TRANS (&__gss_c_ma_ctx_trans_oid_desc)
+
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_negoex_and_spnego_oid_desc;
+#define GSS_C_MA_NEGOEX_AND_SPNEGO (&__gss_c_ma_negoex_and_spnego_oid_desc)
+
+#endif /* GSSAPI_GSSAPI_OID */
diff --git a/third_party/heimdal/lib/gssapi/gssapi/gssapi_spnego.h b/third_party/heimdal/lib/gssapi/gssapi/gssapi_spnego.h
new file mode 100644
index 0000000..8b4519e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gssapi/gssapi_spnego.h
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef GSSAPI_SPNEGO_H_
+#define GSSAPI_SPNEGO_H_
+
+#include <gssapi.h>
+
+GSSAPI_CPP_START
+
+/*
+ * RFC2478, SPNEGO:
+ * The security mechanism of the initial
+ * negotiation token is identified by the Object Identifier
+ * iso.org.dod.internet.security.mechanism.snego (1.3.6.1.5.5.2).
+ */
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_spnego_mechanism_oid_desc;
+#define GSS_SPNEGO_MECHANISM (&__gss_spnego_mechanism_oid_desc)
+#define gss_mech_spnego GSS_SPNEGO_MECHANISM
+
+/*
+ * NegoEx extensions, to be implemented by mechanisms
+ */
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gssspi_query_mechanism_info(
+ OM_uint32 * /* minor_status */,
+ gss_const_OID /* mech_oid */,
+ unsigned char[16] /* auth_scheme */
+);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gssspi_query_meta_data(
+ OM_uint32 * /* minor_status */,
+ gss_const_OID /* mech_oid */,
+ gss_cred_id_t /* cred_handle */,
+ gss_ctx_id_t * /* context_handle */,
+ gss_const_name_t /* targ_name */,
+ OM_uint32 /* req_flags */,
+ gss_buffer_t /* meta_data */
+);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gssspi_exchange_meta_data(
+ OM_uint32 * /* minor_status */,
+ gss_const_OID /* mech_oid */,
+ gss_cred_id_t /* cred_handle */,
+ gss_ctx_id_t * /* context_handle */,
+ gss_const_name_t /* targ_name */,
+ OM_uint32 /* req_flags */,
+ gss_const_buffer_t /* meta_data */
+);
+
+GSSAPI_CPP_END
+
+#endif /* GSSAPI_SPNEGO_H_ */
diff --git a/third_party/heimdal/lib/gssapi/gssapi_mech.h b/third_party/heimdal/lib/gssapi/gssapi_mech.h
new file mode 100644
index 0000000..ced27b5
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gssapi_mech.h
@@ -0,0 +1,725 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * Copyright (c) 2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/mech_switch.h,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#ifndef GSSAPI_MECH_H
+#define GSSAPI_MECH_H 1
+
+#include <gssapi.h>
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_acquire_cred_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_name_t, /* desired_name */
+ OM_uint32, /* time_req */
+ const gss_OID_set, /* desired_mechs */
+ gss_cred_usage_t, /* cred_usage */
+ gss_cred_id_t *, /* output_cred_handle */
+ gss_OID_set *, /* actual_mechs */
+ OM_uint32 * /* time_rec */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_release_cred_t
+ (OM_uint32 *, /* minor_status */
+ gss_cred_id_t * /* cred_handle */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_init_sec_context_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_cred_id_t, /* initiator_cred_handle */
+ gss_ctx_id_t *, /* context_handle */
+ gss_const_name_t, /* target_name */
+ const gss_OID, /* mech_type */
+ OM_uint32, /* req_flags */
+ OM_uint32, /* time_req */
+ const gss_channel_bindings_t,
+ /* input_chan_bindings */
+ const gss_buffer_t, /* input_token */
+ gss_OID *, /* actual_mech_type */
+ gss_buffer_t, /* output_token */
+ OM_uint32 *, /* ret_flags */
+ OM_uint32 * /* time_rec */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_accept_sec_context_t
+ (OM_uint32 *, /* minor_status */
+ gss_ctx_id_t *, /* context_handle */
+ gss_const_cred_id_t, /* acceptor_cred_handle */
+ const gss_buffer_t, /* input_token_buffer */
+ const gss_channel_bindings_t,
+ /* input_chan_bindings */
+ gss_name_t *, /* src_name */
+ gss_OID *, /* mech_type */
+ gss_buffer_t, /* output_token */
+ OM_uint32 *, /* ret_flags */
+ OM_uint32 *, /* time_rec */
+ gss_cred_id_t * /* delegated_cred_handle */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_process_context_token_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_ctx_id_t, /* context_handle */
+ const gss_buffer_t /* token_buffer */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_delete_sec_context_t
+ (OM_uint32 *, /* minor_status */
+ gss_ctx_id_t *, /* context_handle */
+ gss_buffer_t /* output_token */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_context_time_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_ctx_id_t, /* context_handle */
+ OM_uint32 * /* time_rec */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_get_mic_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_ctx_id_t, /* context_handle */
+ gss_qop_t, /* qop_req */
+ const gss_buffer_t, /* message_buffer */
+ gss_buffer_t /* message_token */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_verify_mic_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_ctx_id_t, /* context_handle */
+ const gss_buffer_t, /* message_buffer */
+ const gss_buffer_t, /* token_buffer */
+ gss_qop_t * /* qop_state */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_wrap_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_ctx_id_t, /* context_handle */
+ int, /* conf_req_flag */
+ gss_qop_t, /* qop_req */
+ const gss_buffer_t, /* input_message_buffer */
+ int *, /* conf_state */
+ gss_buffer_t /* output_message_buffer */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_unwrap_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_ctx_id_t, /* context_handle */
+ const gss_buffer_t, /* input_message_buffer */
+ gss_buffer_t, /* output_message_buffer */
+ int *, /* conf_state */
+ gss_qop_t * /* qop_state */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_display_status_t
+ (OM_uint32 *, /* minor_status */
+ OM_uint32, /* status_value */
+ int, /* status_type */
+ const gss_OID, /* mech_type */
+ OM_uint32 *, /* message_context */
+ gss_buffer_t /* status_string */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_indicate_mechs_t
+ (OM_uint32 *, /* minor_status */
+ gss_OID_set * /* mech_set */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_compare_name_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_name_t, /* name1 */
+ gss_const_name_t, /* name2 */
+ int * /* name_equal */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_display_name_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_name_t, /* input_name */
+ gss_buffer_t, /* output_name_buffer */
+ gss_OID * /* output_name_type */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_import_name_t
+ (OM_uint32 *, /* minor_status */
+ const gss_buffer_t, /* input_name_buffer */
+ const gss_OID, /* input_name_type */
+ gss_name_t * /* output_name */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_export_name_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_name_t, /* input_name */
+ gss_buffer_t /* exported_name */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_release_name_t
+ (OM_uint32 *, /* minor_status */
+ gss_name_t * /* input_name */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_cred_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_cred_id_t, /* cred_handle */
+ gss_name_t *, /* name */
+ OM_uint32 *, /* lifetime */
+ gss_cred_usage_t *, /* cred_usage */
+ gss_OID_set * /* mechanisms */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_context_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_ctx_id_t, /* context_handle */
+ gss_name_t *, /* src_name */
+ gss_name_t *, /* targ_name */
+ OM_uint32 *, /* lifetime_rec */
+ gss_OID *, /* mech_type */
+ OM_uint32 *, /* ctx_flags */
+ int *, /* locally_initiated */
+ int * /* open */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_wrap_size_limit_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_ctx_id_t, /* context_handle */
+ int, /* conf_req_flag */
+ gss_qop_t, /* qop_req */
+ OM_uint32, /* req_output_size */
+ OM_uint32 * /* max_input_size */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_add_cred_t (
+ OM_uint32 *, /* minor_status */
+ gss_const_cred_id_t, /* input_cred_handle */
+ gss_const_name_t, /* desired_name */
+ const gss_OID, /* desired_mech */
+ gss_cred_usage_t, /* cred_usage */
+ OM_uint32, /* initiator_time_req */
+ OM_uint32, /* acceptor_time_req */
+ gss_cred_id_t *, /* output_cred_handle */
+ gss_OID_set *, /* actual_mechs */
+ OM_uint32 *, /* initiator_time_rec */
+ OM_uint32 * /* acceptor_time_rec */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_duplicate_cred_t (
+ OM_uint32 *, /* minor_status */
+ gss_const_cred_id_t, /* input_cred_handle */
+ gss_cred_id_t * /* output_cred_handle */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_cred_by_mech_t (
+ OM_uint32 *, /* minor_status */
+ gss_const_cred_id_t, /* cred_handle */
+ const gss_OID, /* mech_type */
+ gss_name_t *, /* name */
+ OM_uint32 *, /* initiator_lifetime */
+ OM_uint32 *, /* acceptor_lifetime */
+ gss_cred_usage_t * /* cred_usage */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_export_sec_context_t (
+ OM_uint32 *, /* minor_status */
+ gss_ctx_id_t *, /* context_handle */
+ gss_buffer_t /* interprocess_token */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_import_sec_context_t (
+ OM_uint32 *, /* minor_status */
+ const gss_buffer_t, /* interprocess_token */
+ gss_ctx_id_t * /* context_handle */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_names_for_mech_t (
+ OM_uint32 *, /* minor_status */
+ const gss_OID, /* mechanism */
+ gss_OID_set * /* name_types */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_mechs_for_name_t (
+ OM_uint32 *, /* minor_status */
+ gss_const_name_t, /* input_name */
+ gss_OID_set * /* mech_types */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_canonicalize_name_t (
+ OM_uint32 *, /* minor_status */
+ gss_const_name_t, /* input_name */
+ const gss_OID, /* mech_type */
+ gss_name_t * /* output_name */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_duplicate_name_t (
+ OM_uint32 *, /* minor_status */
+ gss_const_name_t, /* src_name */
+ gss_name_t * /* dest_name */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_sec_context_by_oid_t (
+ OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_OID desired_object,
+ gss_buffer_set_t *data_set
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_cred_by_oid_t (
+ OM_uint32 *minor_status,
+ gss_const_cred_id_t cred,
+ const gss_OID desired_object,
+ gss_buffer_set_t *data_set
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_set_sec_context_option_t (
+ OM_uint32 *minor_status,
+ gss_ctx_id_t *cred_handle,
+ const gss_OID desired_object,
+ const gss_buffer_t value
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_set_cred_option_t (
+ OM_uint32 *minor_status,
+ gss_cred_id_t *cred_handle,
+ const gss_OID desired_object,
+ const gss_buffer_t value
+ );
+
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_pseudo_random_t (
+ OM_uint32 *minor_status,
+ gss_ctx_id_t context,
+ int prf_key,
+ const gss_buffer_t prf_in,
+ ssize_t desired_output_len,
+ gss_buffer_t prf_out
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_wrap_iov_t(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ int * conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_unwrap_iov_t(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ int *conf_state,
+ gss_qop_t *qop_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_wrap_iov_length_t(OM_uint32 * minor_status,
+ gss_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ int *conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_store_cred_t(OM_uint32 *minor_status,
+ gss_cred_id_t input_cred_handle,
+ gss_cred_usage_t cred_usage,
+ const gss_OID desired_mech,
+ OM_uint32 overwrite_cred,
+ OM_uint32 default_cred,
+ gss_OID_set *elements_stored,
+ gss_cred_usage_t *cred_usage_stored);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_export_cred_t(OM_uint32 *minor_status,
+ gss_cred_id_t cred_handle,
+ gss_buffer_t cred_token);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_import_cred_t(OM_uint32 * minor_status,
+ gss_buffer_t cred_token,
+ gss_cred_id_t * cred_handle);
+
+typedef void GSSAPI_CALLCONV
+_gss_iter_creds_t(OM_uint32 /* flags */,
+ void * /* userctx */,
+ void (* /*cred_iter */ )(void *, gss_OID, gss_cred_id_t));
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_destroy_cred_t(OM_uint32 * /* minor_status */,
+ gss_cred_id_t * /* cred */);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_cred_hold_t(OM_uint32 * /* minor_status */,
+ gss_cred_id_t /* cred */);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_cred_unhold_t(OM_uint32 * /* minor_status */,
+ gss_cred_id_t /* cred */);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_cred_label_set_t(OM_uint32 * /* minor_status */,
+ gss_cred_id_t /* cred */,
+ const char * /* label */,
+ gss_buffer_t /* value */);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_cred_label_get_t(OM_uint32 * /* minor_status */,
+ gss_cred_id_t /* cred */,
+ const char * /* label */,
+ gss_buffer_t /* value */);
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_display_name_ext_t (
+ OM_uint32 *, /* minor_status */
+ gss_name_t, /* name */
+ gss_OID, /* display_as_name_type */
+ gss_buffer_t /* display_name */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_name_t (
+ OM_uint32 *, /* minor_status */
+ gss_name_t, /* name */
+ int *, /* name_is_MN */
+ gss_OID *, /* MN_mech */
+ gss_buffer_set_t * /* attrs */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_get_name_attribute_t (
+ OM_uint32 *, /* minor_status */
+ gss_name_t, /* name */
+ gss_buffer_t, /* attr */
+ int *, /* authenticated */
+ int *, /* complete */
+ gss_buffer_t, /* value */
+ gss_buffer_t, /* display_value */
+ int * /* more */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_set_name_attribute_t (
+ OM_uint32 *, /* minor_status */
+ gss_name_t, /* name */
+ int, /* complete */
+ gss_buffer_t, /* attr */
+ gss_buffer_t /* value */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_delete_name_attribute_t (
+ OM_uint32 *, /* minor_status */
+ gss_name_t, /* name */
+ gss_buffer_t /* attr */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_export_name_composite_t (
+ OM_uint32 *, /* minor_status */
+ gss_name_t, /* name */
+ gss_buffer_t /* exp_composite_name */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_acquire_cred_from_t(OM_uint32 *minor_status,
+ gss_const_name_t desired_name,
+ OM_uint32 time_req,
+ gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_const_key_value_set_t cred_store,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *time_rec);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_acquire_cred_impersonate_name_t(OM_uint32 *minor_status,
+ gss_const_cred_id_t icred,
+ gss_const_name_t desired_name,
+ OM_uint32 time_req,
+ gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *time_rec);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_add_cred_from_t(OM_uint32 *minor_status,
+ gss_cred_id_t input_cred_handle,
+ gss_const_name_t desired_name,
+ const gss_OID desired_mech,
+ gss_cred_usage_t cred_usage,
+ OM_uint32 initiator_time_req,
+ OM_uint32 acceptor_time_req,
+ gss_const_key_value_set_t cred_store,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *initiator_time_rec,
+ OM_uint32 *acceptor_time_rec);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_store_cred_into_t(OM_uint32 *minor_status,
+ gss_const_cred_id_t input_cred_handle,
+ gss_cred_usage_t input_usage,
+ gss_OID desired_mech,
+ OM_uint32 overwrite_cred,
+ OM_uint32 default_cred,
+ gss_const_key_value_set_t cred_store,
+ gss_OID_set *elements_stored,
+ gss_cred_usage_t *cred_usage_stored);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_store_cred_into2_t(OM_uint32 *minor_status,
+ gss_const_cred_id_t input_cred_handle,
+ gss_cred_usage_t input_usage,
+ gss_OID desired_mech,
+ OM_uint32 store_cred_flags,
+ gss_const_key_value_set_t cred_store,
+ gss_OID_set *elements_stored,
+ gss_cred_usage_t *cred_usage_stored,
+ gss_buffer_set_t *env);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_query_mechanism_info_t(OM_uint32 *minor_status,
+ gss_const_OID mech_oid,
+ unsigned char auth_scheme[16]);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_query_meta_data_t(OM_uint32 *minor_status,
+ gss_const_OID mech_oid,
+ gss_cred_id_t cred_handle,
+ gss_ctx_id_t *ctx_handle,
+ gss_const_name_t targ_name,
+ OM_uint32 req_flags,
+ gss_buffer_t meta_data);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_exchange_meta_data_t(OM_uint32 *minor_status,
+ gss_const_OID mech_oid,
+ gss_cred_id_t cred_handle,
+ gss_ctx_id_t *ctx_handle,
+ gss_const_name_t targ_name,
+ OM_uint32 req_flags,
+ gss_const_buffer_t meta_data);
+
+/*
+ *
+ */
+
+typedef struct gss_mo_desc_struct gss_mo_desc;
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_mo_init (OM_uint32 *, gss_OID, gss_mo_desc **, size_t *);
+
+
+struct gss_mo_desc_struct {
+ gss_OID option;
+ OM_uint32 flags;
+#define GSS_MO_MA 1
+#define GSS_MO_MA_CRITICAL 2
+ const char *name;
+ void *ctx;
+ int (*get)(gss_const_OID, gss_mo_desc *, gss_buffer_t);
+ int (*set)(gss_const_OID, gss_mo_desc *, int, gss_buffer_t);
+};
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_localname_t (
+ OM_uint32 *, /* minor_status */
+ gss_const_name_t, /* name */
+ const gss_OID, /* mech_type */
+ gss_buffer_t /* localname */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_authorize_localname_t (
+ OM_uint32 *, /* minor_status */
+ gss_const_name_t, /* name */
+ gss_const_buffer_t, /* user */
+ gss_const_OID /* user_name_type */
+ );
+
+struct _gss_name;
+struct _gss_cred;
+
+/* mechglue internal */
+struct gss_mech_compat_desc_struct;
+
+#define GMI_VERSION 6
+
+/* gm_flags */
+#define GM_USE_MG_CRED 1 /* uses mech glue credentials */
+#define GM_USE_MG_NAME 2 /* uses mech glue names */
+
+typedef struct gssapi_mech_interface_desc {
+ unsigned gm_version;
+ const char *gm_name;
+ gss_OID_desc gm_mech_oid;
+ unsigned gm_flags;
+ _gss_acquire_cred_t *gm_acquire_cred;
+ _gss_release_cred_t *gm_release_cred;
+ _gss_init_sec_context_t *gm_init_sec_context;
+ _gss_accept_sec_context_t *gm_accept_sec_context;
+ _gss_process_context_token_t *gm_process_context_token;
+ _gss_delete_sec_context_t *gm_delete_sec_context;
+ _gss_context_time_t *gm_context_time;
+ _gss_get_mic_t *gm_get_mic;
+ _gss_verify_mic_t *gm_verify_mic;
+ _gss_wrap_t *gm_wrap;
+ _gss_unwrap_t *gm_unwrap;
+ _gss_display_status_t *gm_display_status;
+ _gss_indicate_mechs_t *gm_indicate_mechs;
+ _gss_compare_name_t *gm_compare_name;
+ _gss_display_name_t *gm_display_name;
+ _gss_import_name_t *gm_import_name;
+ _gss_export_name_t *gm_export_name;
+ _gss_release_name_t *gm_release_name;
+ _gss_inquire_cred_t *gm_inquire_cred;
+ _gss_inquire_context_t *gm_inquire_context;
+ _gss_wrap_size_limit_t *gm_wrap_size_limit;
+ _gss_add_cred_t *gm_add_cred;
+ _gss_inquire_cred_by_mech_t *gm_inquire_cred_by_mech;
+ _gss_export_sec_context_t *gm_export_sec_context;
+ _gss_import_sec_context_t *gm_import_sec_context;
+ _gss_inquire_names_for_mech_t *gm_inquire_names_for_mech;
+ _gss_inquire_mechs_for_name_t *gm_inquire_mechs_for_name;
+ _gss_canonicalize_name_t *gm_canonicalize_name;
+ _gss_duplicate_name_t *gm_duplicate_name;
+ _gss_inquire_sec_context_by_oid_t *gm_inquire_sec_context_by_oid;
+ _gss_inquire_cred_by_oid_t *gm_inquire_cred_by_oid;
+ _gss_set_sec_context_option_t *gm_set_sec_context_option;
+ _gss_set_cred_option_t *gm_set_cred_option;
+ _gss_pseudo_random_t *gm_pseudo_random;
+ _gss_wrap_iov_t *gm_wrap_iov;
+ _gss_unwrap_iov_t *gm_unwrap_iov;
+ _gss_wrap_iov_length_t *gm_wrap_iov_length;
+ _gss_store_cred_t *gm_store_cred;
+ _gss_export_cred_t *gm_export_cred;
+ _gss_import_cred_t *gm_import_cred;
+ _gss_acquire_cred_from_t *gm_acquire_cred_from; /* was acquire_cred_ext */
+ _gss_acquire_cred_impersonate_name_t *gm_acquire_cred_impersonate_name;
+ _gss_iter_creds_t *gm_iter_creds;
+ _gss_destroy_cred_t *gm_destroy_cred;
+ _gss_cred_hold_t *gm_cred_hold;
+ _gss_cred_unhold_t *gm_cred_unhold;
+ _gss_cred_label_get_t *gm_cred_label_get;
+ _gss_cred_label_set_t *gm_cred_label_set;
+ gss_mo_desc *gm_mo;
+ size_t gm_mo_num;
+ _gss_localname_t *gm_localname;
+ _gss_authorize_localname_t *gm_authorize_localname;
+ _gss_display_name_ext_t *gm_display_name_ext;
+ _gss_inquire_name_t *gm_inquire_name;
+ _gss_get_name_attribute_t *gm_get_name_attribute;
+ _gss_set_name_attribute_t *gm_set_name_attribute;
+ _gss_delete_name_attribute_t *gm_delete_name_attribute;
+ _gss_export_name_composite_t *gm_export_name_composite;
+ _gss_duplicate_cred_t *gm_duplicate_cred;
+ _gss_add_cred_from_t *gm_add_cred_from;
+ _gss_store_cred_into_t *gm_store_cred_into;
+ _gss_query_mechanism_info_t *gm_query_mechanism_info;
+ _gss_query_meta_data_t *gm_query_meta_data;
+ _gss_exchange_meta_data_t *gm_exchange_meta_data;
+ _gss_store_cred_into2_t *gm_store_cred_into2;
+ struct gss_mech_compat_desc_struct *gm_compat;
+} gssapi_mech_interface_desc, *gssapi_mech_interface;
+
+gssapi_mech_interface
+__gss_get_mechanism(gss_const_OID /* oid */);
+
+gss_OID
+_gss_mg_support_mechanism(gss_const_OID mech);
+
+gssapi_mech_interface __gss_spnego_initialize(void);
+gssapi_mech_interface __gss_krb5_initialize(void);
+gssapi_mech_interface __gss_ntlm_initialize(void);
+gssapi_mech_interface __gss_sanon_initialize(void);
+
+void gss_mg_collect_error(gss_OID, OM_uint32, OM_uint32);
+
+int _gss_mo_get_option_1(gss_const_OID, gss_mo_desc *, gss_buffer_t);
+int _gss_mo_get_option_0(gss_const_OID, gss_mo_desc *, gss_buffer_t);
+int _gss_mo_get_ctx_as_string(gss_const_OID, gss_mo_desc *, gss_buffer_t);
+
+struct _gss_name_type {
+ gss_OID gnt_name_type;
+ OM_uint32 (*gnt_parse)(OM_uint32 *, gss_const_OID, const gss_buffer_t,
+ gss_const_OID, gss_name_t *);
+};
+
+struct _gss_oid_name_table {
+ gss_OID oid;
+ const char *name;
+ const char *short_desc;
+ const char *long_desc;
+};
+
+extern struct _gss_oid_name_table _gss_ont_mech[];
+extern struct _gss_oid_name_table _gss_ont_ma[];
+
+int
+_gss_mg_log_level(int level);
+
+void
+_gss_mg_log(int level, const char *fmt, ...)
+ HEIMDAL_PRINTF_ATTRIBUTE((printf, 2, 3));
+
+void
+_gss_mg_log_name(int level,
+ struct _gss_name *name,
+ gss_OID mech_type,
+ const char *fmt, ...);
+
+void
+_gss_mg_log_cred(int level,
+ struct _gss_cred *cred,
+ const char *fmt, ...);
+
+
+void
+_gss_load_plugins(void);
+
+gss_iov_buffer_desc *
+_gss_mg_find_buffer(gss_iov_buffer_desc *iov,
+ int iov_count,
+ OM_uint32 type);
+
+OM_uint32
+_gss_mg_allocate_buffer(OM_uint32 *minor_status,
+ gss_iov_buffer_desc *buffer,
+ size_t size);
+
+OM_uint32
+gss_mg_set_error_string(gss_OID mech,
+ OM_uint32 maj, OM_uint32 min,
+ const char *fmt, ...);
+
+gss_cred_id_t
+_gss_mg_find_mech_cred(gss_const_cred_id_t cred_handle,
+ gss_const_OID mech_type);
+
+#include <krb5.h>
+
+/*
+ * Mechglue krb5 context for use by NegoEx. This is not shared with the
+ * krb5 GSS mechanism so we don't clobber its error state.
+ */
+krb5_context
+_gss_mg_krb5_context(void);
+
+#endif /* GSSAPI_MECH_H */
diff --git a/third_party/heimdal/lib/gssapi/gsstool.c b/third_party/heimdal/lib/gssapi/gsstool.c
new file mode 100644
index 0000000..8df3953
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/gsstool.c
@@ -0,0 +1,264 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 - 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <stdio.h>
+#include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
+#include <gssapi_ntlm.h>
+#include <err.h>
+#include <getarg.h>
+#include <rtbl.h>
+#include <gss-commands.h>
+
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag, "print version", NULL },
+ {"help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args),
+ NULL, "service@host");
+ exit (ret);
+}
+
+#define COL_OID "OID"
+#define COL_NAME "Name"
+#define COL_DESC "Description"
+#define COL_VALUE "Value"
+#define COL_MECH "Mech"
+#define COL_EXPIRE "Expire"
+#define COL_SASL "SASL"
+
+int
+mechanisms(void *argptr, int argc, char **argv)
+{
+ OM_uint32 maj_stat, min_stat;
+ gss_OID_set mechs;
+ rtbl_t ct;
+ size_t i;
+
+ maj_stat = gss_indicate_mechs(&min_stat, &mechs);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_indicate_mechs failed");
+
+ printf("Supported mechanisms:\n");
+
+ ct = rtbl_create();
+ if (ct == NULL)
+ errx(1, "rtbl_create");
+
+ rtbl_set_separator(ct, " ");
+ rtbl_add_column(ct, COL_OID, 0);
+ rtbl_add_column(ct, COL_NAME, 0);
+ rtbl_add_column(ct, COL_DESC, 0);
+ rtbl_add_column(ct, COL_SASL, 0);
+
+ for (i = 0; i < mechs->count; i++) {
+ gss_buffer_desc str, sasl_name, mech_name, mech_desc;
+
+ maj_stat = gss_oid_to_str(&min_stat, &mechs->elements[i], &str);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_oid_to_str failed");
+
+ rtbl_add_column_entryv(ct, COL_OID, "%.*s",
+ (int)str.length, (char *)str.value);
+ gss_release_buffer(&min_stat, &str);
+
+ (void)gss_inquire_saslname_for_mech(&min_stat,
+ &mechs->elements[i],
+ &sasl_name,
+ &mech_name,
+ &mech_desc);
+
+ rtbl_add_column_entryv(ct, COL_NAME, "%.*s",
+ (int)mech_name.length, (char *)mech_name.value);
+ rtbl_add_column_entryv(ct, COL_DESC, "%.*s",
+ (int)mech_desc.length, (char *)mech_desc.value);
+ rtbl_add_column_entryv(ct, COL_SASL, "%.*s",
+ (int)sasl_name.length, (char *)sasl_name.value);
+
+ gss_release_buffer(&min_stat, &mech_name);
+ gss_release_buffer(&min_stat, &mech_desc);
+ gss_release_buffer(&min_stat, &sasl_name);
+
+ }
+ gss_release_oid_set(&min_stat, &mechs);
+
+ rtbl_format(ct, stdout);
+ rtbl_destroy(ct);
+
+ return 0;
+}
+
+static void
+print_mech_attr(const char *mechname, gss_const_OID mech, gss_OID_set set)
+{
+ gss_buffer_desc name, desc;
+ OM_uint32 major, minor;
+ rtbl_t ct;
+ size_t n;
+
+ ct = rtbl_create();
+ if (ct == NULL)
+ errx(1, "rtbl_create");
+
+ rtbl_set_separator(ct, " ");
+ rtbl_add_column(ct, COL_OID, 0);
+ rtbl_add_column(ct, COL_DESC, 0);
+ if (mech)
+ rtbl_add_column(ct, COL_VALUE, 0);
+
+ for (n = 0; n < set->count; n++) {
+ major = gss_display_mech_attr(&minor, &set->elements[n], &name, &desc, NULL);
+ if (major)
+ continue;
+
+ rtbl_add_column_entryv(ct, COL_OID, "%.*s",
+ (int)name.length, (char *)name.value);
+ rtbl_add_column_entryv(ct, COL_DESC, "%.*s",
+ (int)desc.length, (char *)desc.value);
+ if (mech) {
+ gss_buffer_desc value;
+
+ if (gss_mo_get(mech, &set->elements[n], &value) != 0)
+ value.length = 0;
+
+ if (value.length)
+ rtbl_add_column_entryv(ct, COL_VALUE, "%.*s",
+ (int)value.length, (char *)value.value);
+ else
+ rtbl_add_column_entryv(ct, COL_VALUE, "<>");
+ gss_release_buffer(&minor, &value);
+ }
+
+ gss_release_buffer(&minor, &name);
+ gss_release_buffer(&minor, &desc);
+ }
+
+ printf("attributes for: %s\n", mechname);
+ rtbl_format(ct, stdout);
+ rtbl_destroy(ct);
+}
+
+
+int
+attributes(struct attributes_options *opt, int argc, char **argv)
+{
+ gss_OID_set mech_attr = NULL, known_mech_attrs = NULL;
+ gss_OID mech = GSS_C_NO_OID;
+ OM_uint32 major, minor;
+
+ if (opt->mech_string) {
+ mech = gss_name_to_oid(opt->mech_string);
+ if (mech == NULL)
+ errx(1, "mech %s is unknown", opt->mech_string);
+ }
+
+ major = gss_inquire_attrs_for_mech(&minor, mech, &mech_attr, &known_mech_attrs);
+ if (major)
+ errx(1, "gss_inquire_attrs_for_mech");
+
+ if (mech) {
+ print_mech_attr(opt->mech_string, mech, mech_attr);
+ }
+
+ if (opt->all_flag) {
+ print_mech_attr("all mechs", NULL, known_mech_attrs);
+ }
+
+ gss_release_oid_set(&minor, &mech_attr);
+ gss_release_oid_set(&minor, &known_mech_attrs);
+
+ return 0;
+}
+
+
+/*
+ *
+ */
+
+int
+help(void *opt, int argc, char **argv)
+{
+ sl_slc_help(commands, argc, argv);
+ return 0;
+}
+
+int
+main(int argc, char **argv)
+{
+ int exit_status = 0, ret, optidx = 0;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (argc != 0) {
+ ret = sl_command(commands, argc, argv);
+ if(ret == -1)
+ sl_did_you_mean(commands, argv[0]);
+ else if (ret == -2)
+ ret = 0;
+ if(ret != 0)
+ exit_status = 1;
+ } else {
+ sl_slc_help(commands, argc, argv);
+ exit_status = 1;
+ }
+
+ return exit_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/8003.c b/third_party/heimdal/lib/gssapi/krb5/8003.c
new file mode 100644
index 0000000..3e21336
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/8003.c
@@ -0,0 +1,313 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+krb5_error_code
+_gsskrb5_encode_om_uint32(OM_uint32 n, u_char *p)
+{
+ p[0] = (n >> 0) & 0xFF;
+ p[1] = (n >> 8) & 0xFF;
+ p[2] = (n >> 16) & 0xFF;
+ p[3] = (n >> 24) & 0xFF;
+ return 0;
+}
+
+krb5_error_code
+_gsskrb5_encode_be_om_uint32(OM_uint32 n, u_char *p)
+{
+ p[0] = (n >> 24) & 0xFF;
+ p[1] = (n >> 16) & 0xFF;
+ p[2] = (n >> 8) & 0xFF;
+ p[3] = (n >> 0) & 0xFF;
+ return 0;
+}
+
+krb5_error_code
+_gsskrb5_decode_om_uint32(const void *ptr, OM_uint32 *n)
+{
+ const u_char *p = ptr;
+ *n = ((uint32_t)p[0])
+ | ((uint32_t)p[1] << 8)
+ | ((uint32_t)p[2] << 16)
+ | ((uint32_t)p[3] << 24);
+ return 0;
+}
+
+krb5_error_code
+_gsskrb5_decode_be_om_uint32(const void *ptr, OM_uint32 *n)
+{
+ const u_char *p = ptr;
+ *n = ((uint32_t)p[0] <<24)
+ | ((uint32_t)p[1] << 16)
+ | ((uint32_t)p[2] << 8)
+ | ((uint32_t)p[3]);
+ return 0;
+}
+
+static krb5_error_code
+hash_input_chan_bindings (const gss_channel_bindings_t b,
+ u_char *p)
+{
+ u_char num[4];
+ EVP_MD_CTX *ctx;
+
+ ctx = EVP_MD_CTX_create();
+ EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
+
+ _gsskrb5_encode_om_uint32 (b->initiator_addrtype, num);
+ EVP_DigestUpdate(ctx, num, sizeof(num));
+ _gsskrb5_encode_om_uint32 (b->initiator_address.length, num);
+ EVP_DigestUpdate(ctx, num, sizeof(num));
+ if (b->initiator_address.length)
+ EVP_DigestUpdate(ctx,
+ b->initiator_address.value,
+ b->initiator_address.length);
+ _gsskrb5_encode_om_uint32 (b->acceptor_addrtype, num);
+ EVP_DigestUpdate(ctx, num, sizeof(num));
+ _gsskrb5_encode_om_uint32 (b->acceptor_address.length, num);
+ EVP_DigestUpdate(ctx, num, sizeof(num));
+ if (b->acceptor_address.length)
+ EVP_DigestUpdate(ctx,
+ b->acceptor_address.value,
+ b->acceptor_address.length);
+ _gsskrb5_encode_om_uint32 (b->application_data.length, num);
+ EVP_DigestUpdate(ctx, num, sizeof(num));
+ if (b->application_data.length)
+ EVP_DigestUpdate(ctx,
+ b->application_data.value,
+ b->application_data.length);
+ EVP_DigestFinal_ex(ctx, p, NULL);
+ EVP_MD_CTX_destroy(ctx);
+
+ return 0;
+}
+
+/*
+ * create a checksum over the chanel bindings in
+ * `input_chan_bindings', `flags' and `fwd_data' and return it in
+ * `result'
+ */
+
+OM_uint32
+_gsskrb5_create_8003_checksum (
+ OM_uint32 *minor_status,
+ const gss_channel_bindings_t input_chan_bindings,
+ OM_uint32 flags,
+ const krb5_data *fwd_data,
+ Checksum *result)
+{
+ u_char *p;
+
+ /*
+ * see rfc1964 (section 1.1.1 (Initial Token), and the checksum value
+ * field's format) */
+ result->cksumtype = CKSUMTYPE_GSSAPI;
+ if (fwd_data->length > 0 && (flags & GSS_C_DELEG_FLAG))
+ result->checksum.length = 24 + 4 + fwd_data->length;
+ else
+ result->checksum.length = 24;
+ result->checksum.data = malloc (result->checksum.length);
+ if (result->checksum.data == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ p = result->checksum.data;
+ _gsskrb5_encode_om_uint32 (16, p);
+ p += 4;
+ if (input_chan_bindings == GSS_C_NO_CHANNEL_BINDINGS) {
+ memset (p, 0, 16);
+ } else {
+ hash_input_chan_bindings (input_chan_bindings, p);
+ }
+ p += 16;
+ _gsskrb5_encode_om_uint32 (flags, p);
+ p += 4;
+
+ if (fwd_data->length > 0 && (flags & GSS_C_DELEG_FLAG)) {
+
+ *p++ = (1 >> 0) & 0xFF; /* DlgOpt */ /* == 1 */
+ *p++ = (1 >> 8) & 0xFF; /* DlgOpt */ /* == 0 */
+ *p++ = (fwd_data->length >> 0) & 0xFF; /* Dlgth */
+ *p++ = (fwd_data->length >> 8) & 0xFF; /* Dlgth */
+ memcpy(p, (unsigned char *) fwd_data->data, fwd_data->length);
+
+ /* p += fwd_data->length; */ /* commented out to quiet warning */
+ }
+
+ return GSS_S_COMPLETE;
+}
+
+static krb5_error_code
+check_ap_options_cbt(void *ad_data, size_t ad_len,
+ krb5_boolean *client_asserted_cb)
+{
+ uint32_t ad_ap_options;
+
+ *client_asserted_cb = FALSE;
+
+ if (ad_len != sizeof(uint32_t))
+ return KRB5KRB_AP_ERR_MSG_TYPE;
+
+ _gss_mg_decode_le_uint32(ad_data, &ad_ap_options);
+
+ if (ad_ap_options & KERB_AP_OPTIONS_CBT)
+ *client_asserted_cb = TRUE;
+
+ return 0;
+}
+
+static krb5_error_code
+find_ap_options(krb5_context context,
+ krb5_authenticator authenticator,
+ krb5_boolean *client_asserted_cb)
+{
+ krb5_error_code ret;
+ krb5_authdata *ad;
+ krb5_data data;
+
+ *client_asserted_cb = FALSE;
+
+ ad = authenticator->authorization_data;
+ if (ad == NULL)
+ return 0;
+
+ ret = _krb5_get_ad(context, ad, NULL, KRB5_AUTHDATA_AP_OPTIONS, &data);
+ if (ret)
+ return ret == ENOENT ? 0 : ret;
+
+ ret = check_ap_options_cbt(data.data, data.length, client_asserted_cb);
+ krb5_data_free(&data);
+
+ return ret;
+}
+
+/*
+ * verify the checksum in `cksum' over `input_chan_bindings'
+ * returning `flags' and `fwd_data'
+ */
+
+OM_uint32
+_gsskrb5_verify_8003_checksum(
+ krb5_context context,
+ OM_uint32 *minor_status,
+ const gss_channel_bindings_t input_chan_bindings,
+ krb5_authenticator authenticator,
+ OM_uint32 *flags,
+ krb5_data *fwd_data)
+{
+ unsigned char hash[16];
+ unsigned char *p;
+ OM_uint32 length;
+ int DlgOpt;
+ static unsigned char zeros[16];
+ krb5_boolean channel_bound = FALSE;
+ const Checksum *cksum = authenticator->cksum;
+ krb5_boolean client_asserted_cb;
+ krb5_error_code ret;
+
+ /* XXX should handle checksums > 24 bytes */
+ if(cksum->cksumtype != CKSUMTYPE_GSSAPI || cksum->checksum.length < 24) {
+ *minor_status = 0;
+ return GSS_S_BAD_BINDINGS;
+ }
+
+ p = cksum->checksum.data;
+ _gsskrb5_decode_om_uint32(p, &length);
+ if(length != sizeof(hash)) {
+ *minor_status = 0;
+ return GSS_S_BAD_BINDINGS;
+ }
+
+ p += 4;
+
+ ret = find_ap_options(context, authenticator, &client_asserted_cb);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ if (input_chan_bindings != GSS_C_NO_CHANNEL_BINDINGS
+ && (memcmp(p, zeros, sizeof(zeros)) != 0 || client_asserted_cb)) {
+ if(hash_input_chan_bindings(input_chan_bindings, hash) != 0) {
+ *minor_status = 0;
+ return GSS_S_BAD_BINDINGS;
+ }
+ if(ct_memcmp(hash, p, sizeof(hash)) != 0) {
+ *minor_status = 0;
+ return GSS_S_BAD_BINDINGS;
+ }
+ channel_bound = TRUE;
+ }
+
+ p += sizeof(hash);
+
+ _gsskrb5_decode_om_uint32(p, flags);
+ p += 4;
+
+ if (cksum->checksum.length > 24 && (*flags & GSS_C_DELEG_FLAG)) {
+ if(cksum->checksum.length < 28) {
+ *minor_status = 0;
+ return GSS_S_BAD_BINDINGS;
+ }
+
+ DlgOpt = (p[0] << 0) | (p[1] << 8);
+ p += 2;
+ if (DlgOpt != 1) {
+ *minor_status = 0;
+ return GSS_S_BAD_BINDINGS;
+ }
+
+ fwd_data->length = (p[0] << 0) | (p[1] << 8);
+ p += 2;
+ if(cksum->checksum.length < 28 + fwd_data->length) {
+ *minor_status = 0;
+ return GSS_S_BAD_BINDINGS;
+ }
+ fwd_data->data = malloc(fwd_data->length);
+ if (fwd_data->data == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ memcpy(fwd_data->data, p, fwd_data->length);
+ }
+
+ if (channel_bound) {
+ *flags |= GSS_C_CHANNEL_BOUND_FLAG;
+ } else {
+ *flags &= ~GSS_C_CHANNEL_BOUND_FLAG;
+ }
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/accept_sec_context.c b/third_party/heimdal/lib/gssapi/krb5/accept_sec_context.c
new file mode 100644
index 0000000..3f8e274
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/accept_sec_context.c
@@ -0,0 +1,978 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+HEIMDAL_MUTEX gssapi_keytab_mutex = HEIMDAL_MUTEX_INITIALIZER;
+krb5_keytab _gsskrb5_keytab;
+
+static krb5_error_code
+validate_keytab(krb5_context context, const char *name, krb5_keytab *id)
+{
+ krb5_error_code ret;
+
+ ret = krb5_kt_resolve(context, name, id);
+ if (ret)
+ return ret;
+
+ ret = krb5_kt_have_content(context, *id);
+ if (ret) {
+ krb5_kt_close(context, *id);
+ *id = NULL;
+ }
+
+ return ret;
+}
+
+OM_uint32
+_gsskrb5_register_acceptor_identity(OM_uint32 *min_stat, const char *identity)
+{
+ krb5_context context;
+ krb5_error_code ret;
+
+ *min_stat = 0;
+
+ ret = _gsskrb5_init(&context);
+ if(ret)
+ return GSS_S_FAILURE;
+
+ HEIMDAL_MUTEX_lock(&gssapi_keytab_mutex);
+
+ if(_gsskrb5_keytab != NULL) {
+ krb5_kt_close(context, _gsskrb5_keytab);
+ _gsskrb5_keytab = NULL;
+ }
+ if (identity == NULL) {
+ ret = krb5_kt_default(context, &_gsskrb5_keytab);
+ } else {
+ /*
+ * First check if we can the keytab as is and if it has content...
+ */
+ ret = validate_keytab(context, identity, &_gsskrb5_keytab);
+ /*
+ * if it doesn't, lets prepend FILE: and try again
+ */
+ if (ret) {
+ char *p = NULL;
+ ret = asprintf(&p, "FILE:%s", identity);
+ if(ret < 0 || p == NULL) {
+ HEIMDAL_MUTEX_unlock(&gssapi_keytab_mutex);
+ return GSS_S_FAILURE;
+ }
+ ret = validate_keytab(context, p, &_gsskrb5_keytab);
+ free(p);
+ }
+ }
+ HEIMDAL_MUTEX_unlock(&gssapi_keytab_mutex);
+ if(ret) {
+ *min_stat = ret;
+ return GSS_S_FAILURE;
+ }
+ return GSS_S_COMPLETE;
+}
+
+void
+_gsskrb5i_is_cfx(krb5_context context, gsskrb5_ctx ctx, int acceptor)
+{
+ krb5_keyblock *key;
+
+ if (acceptor) {
+ if (ctx->auth_context->local_subkey)
+ key = ctx->auth_context->local_subkey;
+ else
+ key = ctx->auth_context->remote_subkey;
+ } else {
+ if (ctx->auth_context->remote_subkey)
+ key = ctx->auth_context->remote_subkey;
+ else
+ key = ctx->auth_context->local_subkey;
+ }
+ if (key == NULL)
+ key = ctx->auth_context->keyblock;
+
+ if (key == NULL)
+ return;
+
+ switch (key->keytype) {
+ case ETYPE_DES_CBC_CRC:
+ case ETYPE_DES_CBC_MD4:
+ case ETYPE_DES_CBC_MD5:
+ case ETYPE_DES3_CBC_MD5:
+ case ETYPE_OLD_DES3_CBC_SHA1:
+ case ETYPE_DES3_CBC_SHA1:
+ case ETYPE_ARCFOUR_HMAC_MD5:
+ case ETYPE_ARCFOUR_HMAC_MD5_56:
+ break;
+ default :
+ ctx->more_flags |= IS_CFX;
+
+ if ((acceptor && ctx->auth_context->local_subkey) ||
+ (!acceptor && ctx->auth_context->remote_subkey))
+ ctx->more_flags |= ACCEPTOR_SUBKEY;
+ break;
+ }
+ if (ctx->crypto)
+ krb5_crypto_destroy(context, ctx->crypto);
+ /* XXX We really shouldn't ignore this; will come back to this */
+ (void) krb5_crypto_init(context, key, 0, &ctx->crypto);
+}
+
+
+static OM_uint32
+gsskrb5_accept_delegated_token(OM_uint32 *minor_status,
+ gsskrb5_ctx ctx,
+ krb5_context context,
+ gss_cred_id_t *delegated_cred_handle)
+{
+ krb5_ccache ccache = NULL;
+ krb5_error_code kret;
+ int32_t ac_flags, ret = GSS_S_COMPLETE;
+ gsskrb5_cred handle;
+
+ *minor_status = 0;
+
+ /* XXX Create a new delegated_cred_handle? */
+ if (delegated_cred_handle == NULL)
+ return GSS_S_COMPLETE;
+
+ *delegated_cred_handle = NULL;
+ kret = krb5_cc_resolve(context, "MEMORY:anonymous", &ccache);
+ if (kret == 0)
+ kret = krb5_cc_initialize(context, ccache, ctx->source);
+ if (kret == 0) {
+ (void) krb5_auth_con_removeflags(context,
+ ctx->auth_context,
+ KRB5_AUTH_CONTEXT_DO_TIME,
+ &ac_flags);
+ kret = krb5_rd_cred2(context,
+ ctx->auth_context,
+ ccache,
+ &ctx->fwd_data);
+ (void) krb5_auth_con_setflags(context,
+ ctx->auth_context,
+ ac_flags);
+ }
+ if (kret) {
+ ctx->flags &= ~GSS_C_DELEG_FLAG;
+ ret = GSS_S_FAILURE;
+ *minor_status = kret;
+ goto out;
+ }
+
+ ret = _gsskrb5_krb5_import_cred(minor_status,
+ &ccache,
+ NULL,
+ NULL,
+ delegated_cred_handle);
+ if (ret != GSS_S_COMPLETE)
+ goto out;
+
+ handle = (gsskrb5_cred) *delegated_cred_handle;
+ handle->cred_flags |= GSS_CF_DESTROY_CRED_ON_RELEASE;
+
+ /*
+ * A root TGT is one of the form krbtgt/REALM@SAME-REALM.
+ *
+ * A destination TGT is a root TGT for the same realm as the acceptor
+ * service's realm.
+ *
+ * Normally clients delegate a root TGT for the client's realm.
+ *
+ * In some deployments clients may want to delegate destination TGTs as
+ * a form of constrained delegation: so that the destination service
+ * cannot use the delegated credential to impersonate the client
+ * principal to services in its home realm (due to KDC lineage/transit
+ * checks). In those deployments there may not even be a route back to
+ * the KDCs of the client's realm, and attempting to use a
+ * non-destination TGT might even lead to timeouts.
+ *
+ * We could simply pretend not to have obtained a credential, except
+ * that a) we don't (yet) have an app name here for the appdefault we
+ * need to check, b) the application really wants to be able to log a
+ * message about the delegated credential being no good.
+ *
+ * Thus we leave it to _gsskrb5_store_cred_into2() to decide what to do
+ * with non-destination TGTs. To do that, it needs the realm of the
+ * acceptor service, which we record here.
+ */
+ handle->destination_realm =
+ strdup(krb5_principal_get_realm(context, ctx->target));
+ if (handle->destination_realm == NULL) {
+ _gsskrb5_release_cred(minor_status, delegated_cred_handle);
+ *minor_status = krb5_enomem(context);
+ ret = GSS_S_FAILURE;
+ goto out;
+ }
+
+out:
+ if (ccache) {
+ krb5_cc_close(context, ccache);
+ }
+ return ret;
+}
+
+static OM_uint32
+gsskrb5_acceptor_ready(OM_uint32 * minor_status,
+ gsskrb5_ctx ctx,
+ krb5_context context,
+ gss_cred_id_t *delegated_cred_handle)
+{
+ OM_uint32 ret;
+ int32_t seq_number;
+ int is_cfx = 0;
+
+ krb5_auth_con_getremoteseqnumber (context,
+ ctx->auth_context,
+ &seq_number);
+
+ _gsskrb5i_is_cfx(context, ctx, 1);
+ is_cfx = (ctx->more_flags & IS_CFX);
+
+ ret = _gssapi_msg_order_create(minor_status,
+ &ctx->order,
+ _gssapi_msg_order_f(ctx->flags),
+ seq_number, 0, is_cfx);
+ if (ret)
+ return ret;
+
+ /*
+ * If requested, set local sequence num to remote sequence if this
+ * isn't a mutual authentication context
+ */
+ if (!(ctx->flags & GSS_C_MUTUAL_FLAG) && _gssapi_msg_order_f(ctx->flags)) {
+ krb5_auth_con_setlocalseqnumber(context,
+ ctx->auth_context,
+ seq_number);
+ }
+
+ /*
+ * We should handle the delegation ticket, in case it's there
+ */
+ if (ctx->fwd_data.length > 0 && (ctx->flags & GSS_C_DELEG_FLAG)) {
+ ret = gsskrb5_accept_delegated_token(minor_status,
+ ctx,
+ context,
+ delegated_cred_handle);
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+ } else {
+ /* Well, looks like it wasn't there after all */
+ ctx->flags &= ~GSS_C_DELEG_FLAG;
+ }
+
+ ctx->state = ACCEPTOR_READY;
+ ctx->more_flags |= OPEN;
+
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+send_error_token(OM_uint32 *minor_status,
+ krb5_context context,
+ krb5_error_code kret,
+ krb5_principal server,
+ krb5_data *indata,
+ gss_buffer_t output_token)
+{
+ krb5_principal ap_req_server = NULL;
+ krb5_error_code ret;
+ krb5_data outbuf;
+ /* this e_data value encodes KERB_AP_ERR_TYPE_SKEW_RECOVERY which
+ tells windows to try again with the corrected timestamp. See
+ [MS-KILE] 2.2.1 KERB-ERROR-DATA */
+ krb5_data e_data = { 7, rk_UNCONST("\x30\x05\xa1\x03\x02\x01\x02") };
+
+ /* build server from request if the acceptor had not selected one */
+ if (server == NULL) {
+ AP_REQ ap_req;
+
+ ret = krb5_decode_ap_req(context, indata, &ap_req);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ ret = _krb5_principalname2krb5_principal(context,
+ &ap_req_server,
+ ap_req.ticket.sname,
+ ap_req.ticket.realm);
+ free_AP_REQ(&ap_req);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ server = ap_req_server;
+ }
+
+ ret = krb5_mk_error(context, kret, NULL, &e_data, NULL,
+ server, NULL, NULL, &outbuf);
+ if (ap_req_server)
+ krb5_free_principal(context, ap_req_server);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = _gsskrb5_encapsulate(minor_status,
+ &outbuf,
+ output_token,
+ "\x03\x00",
+ GSS_KRB5_MECHANISM);
+ krb5_data_free (&outbuf);
+ if (ret)
+ return ret;
+
+ *minor_status = 0;
+ return GSS_S_CONTINUE_NEEDED;
+}
+
+
+static OM_uint32
+gsskrb5_acceptor_start(OM_uint32 * minor_status,
+ gsskrb5_ctx ctx,
+ krb5_context context,
+ gss_const_cred_id_t acceptor_cred_handle,
+ const gss_buffer_t input_token_buffer,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_name_t * src_name,
+ gss_OID * mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec,
+ gss_cred_id_t * delegated_cred_handle)
+{
+ krb5_error_code kret;
+ OM_uint32 ret = GSS_S_COMPLETE;
+ krb5_data indata;
+ krb5_flags ap_options;
+ krb5_keytab keytab = NULL;
+ int is_cfx = 0;
+ int close_kt = 0;
+ const gsskrb5_cred acceptor_cred = (gsskrb5_cred)acceptor_cred_handle;
+
+ /*
+ * We may, or may not, have an escapsulation.
+ */
+ ret = _gsskrb5_decapsulate (minor_status,
+ input_token_buffer,
+ &indata,
+ "\x01\x00",
+ GSS_KRB5_MECHANISM);
+
+ if (ret) {
+ /* Could be a raw AP-REQ (check for APPLICATION tag) */
+ if (input_token_buffer->length == 0 ||
+ ((const uint8_t *)input_token_buffer->value)[0] != 0x6E) {
+ *minor_status = ASN1_MISPLACED_FIELD;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ /* Assume that there is no OID wrapping. */
+ indata.length = input_token_buffer->length;
+ indata.data = input_token_buffer->value;
+ }
+
+ /*
+ * We need to get our keytab
+ */
+ if (acceptor_cred == NULL) {
+ HEIMDAL_MUTEX_lock(&gssapi_keytab_mutex);
+ if (_gsskrb5_keytab != NULL) {
+ char *name = NULL;
+ kret = krb5_kt_get_full_name(context, _gsskrb5_keytab, &name);
+ if (kret == 0) {
+ kret = krb5_kt_resolve(context, name, &keytab);
+ krb5_xfree(name);
+ }
+ if (kret == 0)
+ close_kt = 1;
+ else
+ keytab = NULL;
+ }
+ HEIMDAL_MUTEX_unlock(&gssapi_keytab_mutex);
+ } else if (acceptor_cred->keytab != NULL) {
+ keytab = acceptor_cred->keytab;
+ }
+
+ /*
+ * We need to check the ticket and create the AP-REP packet
+ */
+
+ {
+ krb5_rd_req_in_ctx in = NULL;
+ krb5_rd_req_out_ctx out = NULL;
+ krb5_principal server = NULL;
+
+ if (acceptor_cred)
+ server = acceptor_cred->principal;
+
+ kret = krb5_rd_req_in_ctx_alloc(context, &in);
+ if (kret == 0)
+ kret = krb5_rd_req_in_set_keytab(context, in, keytab);
+ if (kret) {
+ if (in)
+ krb5_rd_req_in_ctx_free(context, in);
+ if (close_kt)
+ krb5_kt_close(context, keytab);
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ kret = krb5_rd_req_ctx(context,
+ &ctx->auth_context,
+ &indata,
+ server,
+ in, &out);
+ krb5_rd_req_in_ctx_free(context, in);
+ if (close_kt)
+ krb5_kt_close(context, keytab);
+ if (kret == KRB5KRB_AP_ERR_SKEW || kret == KRB5KRB_AP_ERR_TKT_NYV) {
+ /*
+ * No reply in non-MUTUAL mode, but we don't know that its
+ * non-MUTUAL mode yet, thats inside the 8003 checksum, so
+ * lets only send the error token on clock skew, that
+ * limit when send error token for non-MUTUAL.
+ */
+ krb5_auth_con_free(context, ctx->auth_context);
+ krb5_auth_con_free(context, ctx->deleg_auth_context);
+ ctx->deleg_auth_context = NULL;
+ ctx->auth_context = NULL;
+ return send_error_token(minor_status, context, kret,
+ server, &indata, output_token);
+ } else if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ /*
+ * we need to remember some data on the context_handle.
+ */
+ kret = krb5_rd_req_out_get_ap_req_options(context, out,
+ &ap_options);
+ if (kret == 0)
+ kret = krb5_rd_req_out_get_ticket(context, out,
+ &ctx->ticket);
+ if (kret == 0)
+ kret = krb5_rd_req_out_get_keyblock(context, out,
+ &ctx->service_keyblock);
+ ctx->endtime = ctx->ticket->ticket.endtime;
+
+ krb5_rd_req_out_ctx_free(context, out);
+ if (kret) {
+ ret = GSS_S_FAILURE;
+ *minor_status = kret;
+ return ret;
+ }
+ }
+
+
+ /*
+ * We need to copy the principal names to the context and the
+ * calling layer.
+ */
+ kret = krb5_copy_principal(context,
+ ctx->ticket->client,
+ &ctx->source);
+ if (kret) {
+ ret = GSS_S_FAILURE;
+ *minor_status = kret;
+ return ret;
+ }
+
+ kret = krb5_copy_principal(context,
+ ctx->ticket->server,
+ &ctx->target);
+ if (kret) {
+ ret = GSS_S_FAILURE;
+ *minor_status = kret;
+ return ret;
+ }
+
+ /*
+ * We need to setup some compat stuff, this assumes that
+ * context_handle->target is already set.
+ */
+ ret = _gss_DES3_get_mic_compat(minor_status, ctx, context);
+ if (ret)
+ return ret;
+
+ if (src_name != NULL) {
+ kret = krb5_copy_principal (context,
+ ctx->ticket->client,
+ (gsskrb5_name*)src_name);
+ if (kret) {
+ ret = GSS_S_FAILURE;
+ *minor_status = kret;
+ return ret;
+ }
+ }
+
+ /*
+ * We need to get the flags out of the 8003 checksum.
+ */
+
+ {
+ krb5_authenticator authenticator;
+
+ kret = krb5_auth_con_getauthenticator(context,
+ ctx->auth_context,
+ &authenticator);
+ if(kret) {
+ ret = GSS_S_FAILURE;
+ *minor_status = kret;
+ return ret;
+ }
+
+ if (authenticator->cksum != NULL
+ && authenticator->cksum->cksumtype == CKSUMTYPE_GSSAPI) {
+ ret = _gsskrb5_verify_8003_checksum(context,
+ minor_status,
+ input_chan_bindings,
+ authenticator,
+ &ctx->flags,
+ &ctx->fwd_data);
+
+ if (ret) {
+ krb5_free_authenticator(context, &authenticator);
+ return ret;
+ }
+ } else {
+ if (authenticator->cksum != NULL) {
+ krb5_crypto crypto;
+
+ kret = krb5_crypto_init(context,
+ ctx->auth_context->keyblock,
+ 0, &crypto);
+ if (kret) {
+ krb5_free_authenticator(context, &authenticator);
+ ret = GSS_S_FAILURE;
+ *minor_status = kret;
+ return ret;
+ }
+
+ /*
+ * Windows accepts Samba3's use of a kerberos, rather than
+ * GSSAPI checksum here
+ */
+
+ _krb5_crypto_set_flags(context, crypto, KRB5_CRYPTO_FLAG_ALLOW_UNKEYED_CHECKSUM);
+ kret = krb5_verify_checksum(context,
+ crypto, KRB5_KU_AP_REQ_AUTH_CKSUM, NULL, 0,
+ authenticator->cksum);
+ krb5_crypto_destroy(context, crypto);
+
+ if (kret) {
+ krb5_free_authenticator(context, &authenticator);
+ ret = GSS_S_BAD_SIG;
+ *minor_status = kret;
+ return ret;
+ }
+ }
+
+ /*
+ * If there is no checksum or a kerberos checksum (which Windows
+ * and Samba accept), we use the ap_options to guess the mutual
+ * flag.
+ */
+
+ ctx->flags = GSS_C_REPLAY_FLAG | GSS_C_SEQUENCE_FLAG;
+ if (ap_options & AP_OPTS_MUTUAL_REQUIRED)
+ ctx->flags |= GSS_C_MUTUAL_FLAG;
+ }
+ krb5_free_authenticator(context, &authenticator);
+ }
+
+ if(ctx->flags & GSS_C_MUTUAL_FLAG) {
+ krb5_data outbuf;
+ int use_subkey = 0;
+
+ _gsskrb5i_is_cfx(context, ctx, 1);
+ is_cfx = (ctx->more_flags & IS_CFX);
+
+ if (is_cfx || (ap_options & AP_OPTS_USE_SUBKEY)) {
+ use_subkey = 1;
+ } else {
+ krb5_keyblock *rkey;
+
+ /*
+ * If there is a initiator subkey, copy that to acceptor
+ * subkey to match Windows behavior
+ */
+ kret = krb5_auth_con_getremotesubkey(context,
+ ctx->auth_context,
+ &rkey);
+ if (kret == 0) {
+ kret = krb5_auth_con_setlocalsubkey(context,
+ ctx->auth_context,
+ rkey);
+ if (kret == 0)
+ use_subkey = 1;
+ }
+ krb5_free_keyblock(context, rkey);
+ }
+ if (use_subkey) {
+ ctx->more_flags |= ACCEPTOR_SUBKEY;
+ krb5_auth_con_addflags(context, ctx->auth_context,
+ KRB5_AUTH_CONTEXT_USE_SUBKEY,
+ NULL);
+ }
+
+ kret = krb5_mk_rep(context,
+ ctx->auth_context,
+ &outbuf);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ if (IS_DCE_STYLE(ctx)) {
+ output_token->length = outbuf.length;
+ output_token->value = outbuf.data;
+ } else {
+ ret = _gsskrb5_encapsulate(minor_status,
+ &outbuf,
+ output_token,
+ "\x02\x00",
+ GSS_KRB5_MECHANISM);
+ krb5_data_free (&outbuf);
+ if (ret)
+ return ret;
+ }
+ }
+
+ ctx->flags |= GSS_C_TRANS_FLAG;
+
+ /* Remember the flags */
+
+ ctx->endtime = ctx->ticket->ticket.endtime;
+ ctx->more_flags |= OPEN;
+
+ if (mech_type)
+ *mech_type = GSS_KRB5_MECHANISM;
+
+ if (time_rec) {
+ ret = _gsskrb5_lifetime_left(minor_status,
+ context,
+ ctx->endtime,
+ time_rec);
+ if (ret) {
+ return ret;
+ }
+ }
+
+ /*
+ * When GSS_C_DCE_STYLE is in use, we need ask for a AP-REP from
+ * the client.
+ */
+ if (IS_DCE_STYLE(ctx)) {
+ /*
+ * Return flags to caller, but we haven't processed
+ * delgations yet
+ */
+ if (ret_flags)
+ *ret_flags = (ctx->flags & ~GSS_C_DELEG_FLAG);
+
+ ctx->state = ACCEPTOR_WAIT_FOR_DCESTYLE;
+ return GSS_S_CONTINUE_NEEDED;
+ }
+
+ ret = gsskrb5_acceptor_ready(minor_status, ctx, context,
+ delegated_cred_handle);
+
+ if (ret_flags)
+ *ret_flags = ctx->flags;
+
+ return ret;
+}
+
+static OM_uint32
+acceptor_wait_for_dcestyle(OM_uint32 * minor_status,
+ gsskrb5_ctx ctx,
+ krb5_context context,
+ gss_const_cred_id_t acceptor_cred_handle,
+ const gss_buffer_t input_token_buffer,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_name_t * src_name,
+ gss_OID * mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec,
+ gss_cred_id_t * delegated_cred_handle)
+{
+ OM_uint32 ret;
+ krb5_error_code kret;
+ krb5_data inbuf;
+ int32_t r_seq_number, l_seq_number;
+
+ /*
+ * We know it's GSS_C_DCE_STYLE so we don't need to decapsulate the AP_REP
+ */
+
+ inbuf.length = input_token_buffer->length;
+ inbuf.data = input_token_buffer->value;
+
+ /*
+ * We need to remeber the old remote seq_number, then check if the
+ * client has replied with our local seq_number, and then reset
+ * the remote seq_number to the old value
+ */
+ {
+ kret = krb5_auth_con_getlocalseqnumber(context,
+ ctx->auth_context,
+ &l_seq_number);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ kret = krb5_auth_con_getremoteseqnumber(context,
+ ctx->auth_context,
+ &r_seq_number);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ kret = krb5_auth_con_setremoteseqnumber(context,
+ ctx->auth_context,
+ l_seq_number);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+ }
+
+ /*
+ * We need to verify the AP_REP, but we need to flag that this is
+ * DCE_STYLE, so don't check the timestamps this time, but put the
+ * flag DO_TIME back afterward.
+ */
+ {
+ krb5_ap_rep_enc_part *repl;
+ int32_t auth_flags;
+
+ krb5_auth_con_removeflags(context,
+ ctx->auth_context,
+ KRB5_AUTH_CONTEXT_DO_TIME,
+ &auth_flags);
+
+ kret = krb5_rd_rep(context, ctx->auth_context, &inbuf, &repl);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+ krb5_free_ap_rep_enc_part(context, repl);
+ krb5_auth_con_setflags(context, ctx->auth_context, auth_flags);
+ }
+
+ /* We need to check the liftime */
+ {
+ OM_uint32 lifetime_rec;
+
+ ret = _gsskrb5_lifetime_left(minor_status,
+ context,
+ ctx->endtime,
+ &lifetime_rec);
+ if (ret) {
+ return ret;
+ }
+ if (lifetime_rec == 0) {
+ return GSS_S_CONTEXT_EXPIRED;
+ }
+
+ if (time_rec) *time_rec = lifetime_rec;
+ }
+
+ /* We need to give the caller the flags which are in use */
+ if (ret_flags) *ret_flags = ctx->flags;
+
+ if (src_name) {
+ kret = krb5_copy_principal(context,
+ ctx->source,
+ (gsskrb5_name*)src_name);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+ }
+
+ /*
+ * After the krb5_rd_rep() the remote and local seq_number should
+ * be the same, because the client just replies the seq_number
+ * from our AP-REP in its AP-REP, but then the client uses the
+ * seq_number from its AP-REQ for GSS_wrap()
+ */
+ {
+ int32_t tmp_r_seq_number, tmp_l_seq_number;
+
+ kret = krb5_auth_con_getremoteseqnumber(context,
+ ctx->auth_context,
+ &tmp_r_seq_number);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ kret = krb5_auth_con_getlocalseqnumber(context,
+ ctx->auth_context,
+ &tmp_l_seq_number);
+ if (kret) {
+
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ /*
+ * Here we check if the client has responsed with our local seq_number,
+ */
+ if (tmp_r_seq_number != tmp_l_seq_number) {
+ return GSS_S_UNSEQ_TOKEN;
+ }
+ }
+
+ /*
+ * We need to reset the remote seq_number, because the client will use,
+ * the old one for the GSS_wrap() calls
+ */
+ {
+ kret = krb5_auth_con_setremoteseqnumber(context,
+ ctx->auth_context,
+ r_seq_number);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+ }
+
+ return gsskrb5_acceptor_ready(minor_status, ctx, context,
+ delegated_cred_handle);
+}
+
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_accept_sec_context(OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ gss_const_cred_id_t acceptor_cred_handle,
+ const gss_buffer_t input_token_buffer,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_name_t * src_name,
+ gss_OID * mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec,
+ gss_cred_id_t * delegated_cred_handle)
+{
+ krb5_context context;
+ OM_uint32 ret;
+ gsskrb5_ctx ctx;
+
+ GSSAPI_KRB5_INIT(&context);
+
+ output_token->length = 0;
+ output_token->value = NULL;
+
+ if (src_name != NULL)
+ *src_name = NULL;
+ if (mech_type)
+ *mech_type = GSS_KRB5_MECHANISM;
+
+ if (*context_handle == GSS_C_NO_CONTEXT) {
+ ret = _gsskrb5_create_ctx(minor_status,
+ context_handle,
+ context,
+ input_chan_bindings,
+ ACCEPTOR_START);
+ if (ret)
+ return ret;
+ }
+
+ ctx = (gsskrb5_ctx)*context_handle;
+
+
+ /*
+ * TODO: check the channel_bindings
+ * (above just sets them to krb5 layer)
+ */
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+
+ switch (ctx->state) {
+ case ACCEPTOR_START:
+ ret = gsskrb5_acceptor_start(minor_status,
+ ctx,
+ context,
+ acceptor_cred_handle,
+ input_token_buffer,
+ input_chan_bindings,
+ src_name,
+ mech_type,
+ output_token,
+ ret_flags,
+ time_rec,
+ delegated_cred_handle);
+ break;
+ case ACCEPTOR_WAIT_FOR_DCESTYLE:
+ ret = acceptor_wait_for_dcestyle(minor_status,
+ ctx,
+ context,
+ acceptor_cred_handle,
+ input_token_buffer,
+ input_chan_bindings,
+ src_name,
+ mech_type,
+ output_token,
+ ret_flags,
+ time_rec,
+ delegated_cred_handle);
+ break;
+ case ACCEPTOR_READY:
+ /*
+ * If we get there, the caller have called
+ * gss_accept_sec_context() one time too many.
+ */
+ ret = GSS_S_BAD_STATUS;
+ break;
+ default:
+ /* TODO: is this correct here? --metze */
+ ret = GSS_S_BAD_STATUS;
+ break;
+ }
+
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ if (GSS_ERROR(ret)) {
+ OM_uint32 min2;
+ _gsskrb5_delete_sec_context(&min2, context_handle, GSS_C_NO_BUFFER);
+ }
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/acquire_cred.c b/third_party/heimdal/lib/gssapi/krb5/acquire_cred.c
new file mode 100644
index 0000000..211dcaa
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/acquire_cred.c
@@ -0,0 +1,686 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+/*
+ * Find an element in a cred store. Returns GSS_S_COMPLETE if the cred store
+ * is absent or well formed, irrespective of whether the element exists. The
+ * caller should check for *value != NULL before using; values are typically
+ * optional, hence this behavior. (The caller should validate the return
+ * value at least once though, to check it is well-formed.)
+ */
+OM_uint32
+__gsskrb5_cred_store_find(OM_uint32 *minor_status,
+ gss_const_key_value_set_t cred_store,
+ const char *key,
+ const char **value)
+{
+ size_t i;
+
+ *value = NULL;
+
+ if (cred_store == GSS_C_NO_CRED_STORE)
+ return GSS_S_COMPLETE;
+ else if (cred_store->count == 0) {
+ *minor_status = GSS_KRB5_S_G_BAD_USAGE;
+ return GSS_S_NO_CRED;
+ }
+
+ for (i = 0; i < cred_store->count; i++) {
+ if (strcmp(key, cred_store->elements[i].key) == 0) {
+ if (*value) {
+ *value = NULL;
+ *minor_status = GSS_KRB5_S_G_BAD_USAGE;
+ return GSS_S_DUPLICATE_ELEMENT;
+ }
+ *value = cred_store->elements[i].value;
+ }
+ }
+
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+__gsskrb5_ccache_lifetime(OM_uint32 *minor_status,
+ krb5_context context,
+ krb5_ccache id,
+ krb5_principal principal,
+ OM_uint32 *lifetime)
+{
+ krb5_error_code kret;
+ time_t left;
+
+ kret = krb5_cc_get_lifetime(context, id, &left);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ *lifetime = left;
+
+ return GSS_S_COMPLETE;
+}
+
+
+
+
+static krb5_error_code
+get_system_keytab(krb5_context context,
+ gss_const_key_value_set_t cred_store,
+ krb5_keytab *keytab)
+{
+ krb5_error_code kret;
+ const char *cs_ktname;
+ OM_uint32 tmp;
+
+ __gsskrb5_cred_store_find(&tmp, cred_store, "keytab", &cs_ktname);
+
+ HEIMDAL_MUTEX_lock(&gssapi_keytab_mutex);
+
+ if (cs_ktname)
+ kret = krb5_kt_resolve(context, cs_ktname, keytab);
+ else if (_gsskrb5_keytab != NULL) {
+ char *name = NULL;
+
+ kret = krb5_kt_get_full_name(context, _gsskrb5_keytab, &name);
+ if (kret == 0) {
+ kret = krb5_kt_resolve(context, name, keytab);
+ krb5_xfree(name);
+ }
+ } else
+ kret = krb5_kt_default(context, keytab);
+
+ HEIMDAL_MUTEX_unlock(&gssapi_keytab_mutex);
+
+ return (kret);
+}
+
+static krb5_error_code
+get_client_keytab(krb5_context context,
+ gss_const_key_value_set_t cred_store,
+ krb5_const_principal principal,
+ krb5_keytab *keytab)
+{
+ krb5_error_code ret;
+ const char *cs_ktname;
+ OM_uint32 tmp;
+
+ __gsskrb5_cred_store_find(&tmp, cred_store, "client_keytab", &cs_ktname);
+
+ if (cs_ktname)
+ ret = krb5_kt_resolve(context, cs_ktname, keytab);
+ else {
+ char *name = NULL;
+ ret = _krb5_kt_client_default_name(context, &name);
+ if (ret == 0)
+ ret = krb5_kt_resolve(context, name, keytab);
+ krb5_xfree(name);
+ }
+
+ if (ret == 0 && principal) {
+ krb5_keytab_entry entry;
+
+ ret = krb5_kt_get_entry(context, *keytab, principal,
+ 0, 0, &entry);
+ if (ret == 0)
+ krb5_kt_free_entry(context, &entry);
+ }
+
+ if (ret) {
+ if (*keytab) {
+ krb5_kt_close(context, *keytab);
+ *keytab = NULL;
+ }
+
+ ret = get_system_keytab(context, GSS_C_NO_CRED_STORE, keytab);
+ }
+
+ return ret;
+}
+
+static krb5_boolean
+is_valid_password_cred_store(gss_const_key_value_set_t cred_store)
+{
+ size_t i;
+
+ if (cred_store == GSS_C_NO_CRED_STORE)
+ return TRUE;
+
+ /* XXX don't check keytab, someday we will allow password+acceptor creds */
+ for (i = 0; i < cred_store->count; i++) {
+ if (strcmp(cred_store->elements[i].key, "ccache") == 0 ||
+ strcmp(cred_store->elements[i].key, "client_keytab") == 0)
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+/*
+ * This function produces a cred with a MEMORY ccache containing a TGT
+ * acquired with a password.
+ */
+static OM_uint32
+acquire_cred_with_password(OM_uint32 *minor_status,
+ krb5_context context,
+ const char *password,
+ OM_uint32 time_req,
+ gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_const_key_value_set_t cred_store,
+ gsskrb5_cred handle)
+{
+ OM_uint32 ret = GSS_S_FAILURE;
+ krb5_creds cred;
+ krb5_init_creds_context ctx = NULL;
+ krb5_get_init_creds_opt *opt = NULL;
+ krb5_ccache ccache = NULL;
+ krb5_error_code kret;
+ time_t now;
+ OM_uint32 left;
+ const char *realm;
+
+ if (!is_valid_password_cred_store(cred_store)) {
+ *minor_status = GSS_KRB5_S_G_BAD_PASSWORD_CRED_STORE;
+ return GSS_S_NO_CRED;
+ }
+
+ if (cred_usage == GSS_C_ACCEPT) {
+ /*
+ * TODO: Here we should eventually support user2user (when we get
+ * support for that via an extension to the mechanism
+ * allowing for more than two security context tokens),
+ * and/or new unique MEMORY keytabs (we have MEMORY keytab
+ * support, but we don't have a keytab equivalent of
+ * krb5_cc_new_unique()). Either way, for now we can't
+ * support this.
+ */
+ *minor_status = ENOTSUP; /* XXX Better error? */
+ return GSS_S_FAILURE;
+ }
+
+ memset(&cred, 0, sizeof(cred));
+
+ if (handle->principal == NULL) {
+ kret = krb5_get_default_principal(context, &handle->principal);
+ if (kret)
+ goto end;
+ }
+ realm = krb5_principal_get_realm(context, handle->principal);
+
+ kret = krb5_get_init_creds_opt_alloc(context, &opt);
+ if (kret == 0) {
+ krb5_get_init_creds_opt_set_default_flags(context, "gss_krb5", realm,
+ opt);
+ kret = krb5_init_creds_init(context, handle->principal, NULL, NULL, 0,
+ opt, &ctx);
+ }
+ if (kret == 0)
+ kret = _krb5_init_creds_set_fast_anon_pkinit_optimistic(context, ctx);
+ if (kret == 0)
+ kret = krb5_init_creds_set_password(context, ctx, password);
+
+ /*
+ * Get the current time before the AS exchange so we don't
+ * accidentally end up returning a value that puts advertised
+ * expiration past the real expiration.
+ *
+ * We need to do this because krb5_cc_get_lifetime() returns a
+ * relative time that we need to add to the current time. We ought
+ * to have a version of krb5_cc_get_lifetime() that returns absolute
+ * time...
+ */
+ krb5_timeofday(context, &now);
+
+ if (kret == 0)
+ kret = krb5_init_creds_get(context, ctx);
+ if (kret == 0)
+ kret = krb5_init_creds_get_creds(context, ctx, &cred);
+ if (kret == 0)
+ kret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &ccache);
+ if (kret == 0)
+ kret = krb5_cc_initialize(context, ccache, cred.client);
+ if (kret == 0)
+ kret = krb5_init_creds_store(context, ctx, ccache);
+ if (kret == 0)
+ kret = krb5_cc_store_cred(context, ccache, &cred);
+ if (kret)
+ goto end;
+
+ handle->cred_flags |= GSS_CF_DESTROY_CRED_ON_RELEASE;
+
+ ret = __gsskrb5_ccache_lifetime(minor_status, context, ccache,
+ handle->principal, &left);
+ if (ret != GSS_S_COMPLETE)
+ goto end;
+ handle->endtime = now + left;
+ handle->ccache = ccache;
+ ccache = NULL;
+ ret = GSS_S_COMPLETE;
+
+end:
+ krb5_get_init_creds_opt_free(context, opt);
+ if (ctx)
+ krb5_init_creds_free(context, ctx);
+ if (ccache != NULL)
+ krb5_cc_destroy(context, ccache);
+ if (cred.client != NULL)
+ krb5_free_cred_contents(context, &cred);
+ if (ret != GSS_S_COMPLETE)
+ *minor_status = kret;
+ return (ret);
+}
+
+/*
+ * Acquires an initiator credential from a ccache or using a keytab.
+ */
+static OM_uint32
+acquire_initiator_cred(OM_uint32 *minor_status,
+ krb5_context context,
+ OM_uint32 time_req,
+ gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_const_key_value_set_t cred_store,
+ gsskrb5_cred handle)
+{
+ OM_uint32 ret;
+ krb5_creds cred;
+ krb5_get_init_creds_opt *opt;
+ krb5_principal def_princ = NULL;
+ krb5_ccache def_ccache = NULL;
+ krb5_ccache ccache = NULL; /* we may store into this ccache */
+ krb5_keytab keytab = NULL;
+ krb5_error_code kret = 0;
+ OM_uint32 left;
+ const char *cs_ccache_name;
+ time_t lifetime = 0;
+ time_t now;
+
+ memset(&cred, 0, sizeof(cred));
+
+ ret = __gsskrb5_cred_store_find(minor_status, cred_store,
+ "ccache", &cs_ccache_name);
+ if (GSS_ERROR(ret))
+ return ret;
+
+ ret = GSS_S_FAILURE;
+
+ /*
+ * Get current time early so we can set handle->endtime to a value that
+ * cannot accidentally be past the real endtime. We need a variant of
+ * krb5_cc_get_lifetime() that returns absolute endtime.
+ */
+ krb5_timeofday(context, &now);
+
+ /*
+ * First look for a ccache that has the desired_name (which may be
+ * the default credential name), unless a specific credential cache
+ * was included in cred_store.
+ *
+ * If we don't have an unexpired credential, acquire one with a
+ * keytab.
+ *
+ * If we acquire one with a keytab, save it in the ccache we found
+ * with the expired credential, if any.
+ *
+ * If we don't have any such ccache, then use a MEMORY ccache.
+ */
+
+ if (handle->principal != NULL && cs_ccache_name == NULL) {
+ /*
+ * Not default credential case. See if we can find a ccache in
+ * the cccol for the desired_name.
+ */
+ kret = krb5_cc_cache_match(context,
+ handle->principal,
+ &ccache);
+ if (kret == 0) {
+ kret = krb5_cc_get_lifetime(context, ccache, &lifetime);
+ if (kret == 0) {
+ if (lifetime > 0)
+ goto found;
+ else
+ goto try_keytab;
+ }
+ }
+ /*
+ * Fall through. We shouldn't find this in the default ccache
+ * either, but we'll give it a try, then we'll try using a keytab.
+ */
+ }
+
+ /*
+ * Either desired_name was GSS_C_NO_NAME (default cred) or
+ * krb5_cc_cache_match() failed (or found expired).
+ */
+ if (cs_ccache_name)
+ kret = krb5_cc_resolve(context, cs_ccache_name, &def_ccache);
+ else
+ kret = krb5_cc_default(context, &def_ccache);
+ if (kret != 0)
+ goto try_keytab;
+ kret = krb5_cc_get_lifetime(context, def_ccache, &lifetime);
+ if (kret != 0)
+ lifetime = 0;
+ kret = krb5_cc_get_principal(context, def_ccache, &def_princ);
+ if (kret != 0)
+ goto try_keytab;
+ /*
+ * Have a default ccache; see if it matches desired_name.
+ */
+ if (handle->principal == NULL ||
+ krb5_principal_compare(context, handle->principal,
+ def_princ) == TRUE) {
+ /*
+ * It matches.
+ *
+ * If we end up trying a keytab then we can write the result to
+ * the default ccache.
+ */
+ if (handle->principal == NULL) {
+ kret = krb5_copy_principal(context, def_princ, &handle->principal);
+ if (kret)
+ goto end;
+ }
+ if (ccache != NULL)
+ krb5_cc_close(context, ccache);
+ ccache = def_ccache;
+ def_ccache = NULL;
+ if (lifetime > 0)
+ goto found;
+ /* else we fall through and try using a keytab */
+ }
+
+try_keytab:
+ if (handle->principal == NULL) {
+ /* We need to know what client principal to use */
+ kret = krb5_get_default_principal(context, &handle->principal);
+ if (kret)
+ goto end;
+ }
+ kret = get_client_keytab(context, cred_store, handle->principal, &keytab);
+ if (kret)
+ goto end;
+
+ kret = krb5_get_init_creds_opt_alloc(context, &opt);
+ if (kret)
+ goto end;
+ krb5_timeofday(context, &now);
+ kret = krb5_get_init_creds_keytab(context, &cred, handle->principal,
+ keytab, 0, NULL, opt);
+ krb5_get_init_creds_opt_free(context, opt);
+ if (kret)
+ goto end;
+
+ /*
+ * We got a credential with a keytab. Save it if we can.
+ */
+ if (ccache == NULL) {
+ /*
+ * There's no ccache we can overwrite with the credentials we acquired
+ * with a keytab. We'll use a MEMORY ccache then.
+ *
+ * Note that an application that falls into this repeatedly will do an
+ * AS exchange every time it acquires a credential handle. Hopefully
+ * this doesn't happen much. A workaround is to kinit -k once so that
+ * we always re-initialize the matched/default ccache here. I.e., once
+ * there's a FILE/DIR ccache, we'll keep it frash automatically if we
+ * have a keytab, but if there's no FILE/DIR ccache, then we'll
+ * get a fresh credential *every* time we're asked.
+ */
+ kret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &ccache);
+ if (kret)
+ goto end;
+ handle->cred_flags |= GSS_CF_DESTROY_CRED_ON_RELEASE;
+ } /* else we'll re-initialize whichever ccache we matched above */
+
+ kret = krb5_cc_initialize(context, ccache, cred.client);
+ if (kret)
+ goto end;
+ kret = krb5_cc_store_cred(context, ccache, &cred);
+ if (kret)
+ goto end;
+
+found:
+ assert(handle->principal != NULL);
+ ret = __gsskrb5_ccache_lifetime(minor_status, context, ccache,
+ handle->principal, &left);
+ if (ret != GSS_S_COMPLETE)
+ goto end;
+ handle->endtime = now + left;
+ handle->ccache = ccache;
+ ccache = NULL;
+ ret = GSS_S_COMPLETE;
+ kret = 0;
+
+end:
+ if (ccache != NULL) {
+ if ((handle->cred_flags & GSS_CF_DESTROY_CRED_ON_RELEASE) != 0)
+ krb5_cc_destroy(context, ccache);
+ else
+ krb5_cc_close(context, ccache);
+ }
+ if (def_ccache != NULL)
+ krb5_cc_close(context, def_ccache);
+ if (cred.client != NULL)
+ krb5_free_cred_contents(context, &cred);
+ if (def_princ != NULL)
+ krb5_free_principal(context, def_princ);
+ if (keytab != NULL)
+ krb5_kt_close(context, keytab);
+ if (ret != GSS_S_COMPLETE && kret != 0)
+ *minor_status = kret;
+ return (ret);
+}
+
+static OM_uint32
+acquire_acceptor_cred(OM_uint32 * minor_status,
+ krb5_context context,
+ OM_uint32 time_req,
+ gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_const_key_value_set_t cred_store,
+ gsskrb5_cred handle)
+{
+ OM_uint32 ret;
+ krb5_error_code kret;
+
+ ret = GSS_S_FAILURE;
+
+ kret = get_system_keytab(context, cred_store, &handle->keytab);
+ if (kret)
+ goto end;
+
+ /* check that the requested principal exists in the keytab */
+ if (handle->principal) {
+ krb5_keytab_entry entry;
+
+ kret = krb5_kt_get_entry(context, handle->keytab,
+ handle->principal, 0, 0, &entry);
+ if (kret)
+ goto end;
+ krb5_kt_free_entry(context, &entry);
+ ret = GSS_S_COMPLETE;
+ } else {
+ /*
+ * Check if there is at least one entry in the keytab before
+ * declaring it as an useful keytab.
+ */
+ krb5_keytab_entry tmp;
+ krb5_kt_cursor c;
+
+ kret = krb5_kt_start_seq_get (context, handle->keytab, &c);
+ if (kret)
+ goto end;
+ if (krb5_kt_next_entry(context, handle->keytab, &tmp, &c) == 0) {
+ krb5_kt_free_entry(context, &tmp);
+ ret = GSS_S_COMPLETE; /* ok found one entry */
+ }
+ krb5_kt_end_seq_get (context, handle->keytab, &c);
+ }
+end:
+ if (ret != GSS_S_COMPLETE) {
+ if (handle->keytab != NULL)
+ krb5_kt_close(context, handle->keytab);
+ if (kret != 0) {
+ *minor_status = kret;
+ }
+ }
+ return (ret);
+}
+
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_acquire_cred_from
+(OM_uint32 * minor_status,
+ gss_const_name_t desired_name,
+ OM_uint32 time_req,
+ gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_const_key_value_set_t cred_store,
+ gss_cred_id_t * output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *time_rec
+ )
+{
+ krb5_context context;
+ gsskrb5_cred handle;
+ OM_uint32 ret;
+ const char *password = NULL;
+
+ if (desired_mechs) {
+ int present = 0;
+
+ ret = gss_test_oid_set_member(minor_status, GSS_KRB5_MECHANISM,
+ desired_mechs, &present);
+ if (ret)
+ return ret;
+ if (!present) {
+ *minor_status = 0;
+ return GSS_S_BAD_MECH;
+ }
+ }
+
+ cred_usage &= GSS_C_OPTION_MASK;
+
+ if (cred_usage != GSS_C_ACCEPT && cred_usage != GSS_C_INITIATE &&
+ cred_usage != GSS_C_BOTH) {
+ *minor_status = GSS_KRB5_S_G_BAD_USAGE;
+ return GSS_S_FAILURE;
+ }
+
+ ret = __gsskrb5_cred_store_find(minor_status, cred_store,
+ "password", &password);
+ if (GSS_ERROR(ret))
+ return ret;
+
+ GSSAPI_KRB5_INIT(&context);
+
+ *output_cred_handle = GSS_C_NO_CREDENTIAL;
+
+ handle = calloc(1, sizeof(*handle));
+ if (handle == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ handle->destination_realm = NULL;
+ HEIMDAL_MUTEX_init(&handle->cred_id_mutex);
+
+ if (desired_name != GSS_C_NO_NAME) {
+ ret = _gsskrb5_canon_name(minor_status, context,
+ desired_name, &handle->principal);
+ if (ret) {
+ HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex);
+ free(handle);
+ return ret;
+ }
+ }
+
+ if (password) {
+ ret = acquire_cred_with_password(minor_status, context, password, time_req,
+ desired_mechs, cred_usage, cred_store, handle);
+ if (ret != GSS_S_COMPLETE) {
+ HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex);
+ krb5_free_principal(context, handle->principal);
+ free(handle);
+ return (ret);
+ }
+ } else {
+ /*
+ * Acquire a credential from the specified or background credential
+ * store (ccache, keytab).
+ */
+ if (cred_usage == GSS_C_INITIATE || cred_usage == GSS_C_BOTH) {
+ ret = acquire_initiator_cred(minor_status, context, time_req,
+ desired_mechs, cred_usage,
+ cred_store, handle);
+ if (ret != GSS_S_COMPLETE) {
+ HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex);
+ krb5_free_principal(context, handle->principal);
+ free(handle);
+ return (ret);
+ }
+ }
+ if (cred_usage == GSS_C_ACCEPT || cred_usage == GSS_C_BOTH) {
+ ret = acquire_acceptor_cred(minor_status, context, time_req,
+ desired_mechs, cred_usage,
+ cred_store, handle);
+ if (ret != GSS_S_COMPLETE) {
+ HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex);
+ krb5_free_principal(context, handle->principal);
+ free(handle);
+ return (ret);
+ }
+ }
+ }
+ ret = gss_create_empty_oid_set(minor_status, &handle->mechanisms);
+ if (ret == GSS_S_COMPLETE)
+ ret = gss_add_oid_set_member(minor_status, GSS_KRB5_MECHANISM,
+ &handle->mechanisms);
+ handle->usage = cred_usage;
+ if (ret == GSS_S_COMPLETE)
+ ret = _gsskrb5_inquire_cred(minor_status, (gss_cred_id_t)handle,
+ NULL, time_rec, NULL, actual_mechs);
+ if (ret != GSS_S_COMPLETE) {
+ if (handle->mechanisms != NULL)
+ gss_release_oid_set(NULL, &handle->mechanisms);
+ HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex);
+ krb5_free_principal(context, handle->principal);
+ free(handle);
+ return (ret);
+ }
+ *minor_status = 0;
+ *output_cred_handle = (gss_cred_id_t)handle;
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/add_cred.c b/third_party/heimdal/lib/gssapi/krb5/add_cred.c
new file mode 100644
index 0000000..0bc61a7
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/add_cred.c
@@ -0,0 +1,254 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_add_cred_from (
+ OM_uint32 *minor_status,
+ gss_cred_id_t input_cred_handle,
+ gss_const_name_t desired_name,
+ const gss_OID desired_mech,
+ gss_cred_usage_t cred_usage,
+ OM_uint32 initiator_time_req,
+ OM_uint32 acceptor_time_req,
+ gss_const_key_value_set_t cred_store,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *initiator_time_rec,
+ OM_uint32 *acceptor_time_rec)
+{
+ krb5_context context;
+ OM_uint32 major, lifetime;
+ gsskrb5_cred cred, handle;
+ krb5_const_principal dname;
+
+ handle = NULL;
+ cred = (gsskrb5_cred)input_cred_handle;
+ dname = (krb5_const_principal)desired_name;
+
+ if (cred == NULL && output_cred_handle == NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+ }
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (desired_mech != GSS_C_NO_OID &&
+ gss_oid_equal(desired_mech, GSS_KRB5_MECHANISM) == 0) {
+ *minor_status = 0;
+ return GSS_S_BAD_MECH;
+ }
+
+ if (cred == NULL) {
+ /*
+ * Acquire a credential; output_cred_handle can't be NULL, see above.
+ */
+ heim_assert(output_cred_handle != NULL,
+ "internal error in _gsskrb5_add_cred()");
+
+ major = _gsskrb5_acquire_cred_from(minor_status, desired_name,
+ min(initiator_time_req,
+ acceptor_time_req),
+ GSS_C_NO_OID_SET,
+ cred_usage,
+ cred_store,
+ output_cred_handle,
+ actual_mechs, &lifetime);
+ if (major != GSS_S_COMPLETE)
+ goto failure;
+
+ } else {
+ /*
+ * Check that we're done or copy input to output if
+ * output_cred_handle != NULL.
+ */
+
+ HEIMDAL_MUTEX_lock(&cred->cred_id_mutex);
+
+ /* Check if requested output usage is compatible with output usage */
+ if (cred->usage != cred_usage && cred->usage != GSS_C_BOTH) {
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+ *minor_status = GSS_KRB5_S_G_BAD_USAGE;
+ return(GSS_S_FAILURE);
+ }
+
+ /* Check that we have the same name */
+ if (dname != NULL &&
+ krb5_principal_compare(context, dname,
+ cred->principal) != FALSE) {
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+ *minor_status = 0;
+ return GSS_S_BAD_NAME;
+ }
+
+ if (output_cred_handle == NULL) {
+ /*
+ * This case is basically useless as we implement a single
+ * mechanism here, so we can't add elements to the
+ * input_cred_handle.
+ */
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+ }
+
+ /*
+ * Copy input to output -- this works as if we were a
+ * GSS_Duplicate_cred() for one mechanism element.
+ */
+
+ handle = calloc(1, sizeof(*handle));
+ if (handle == NULL) {
+ if (cred != NULL)
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+ *minor_status = ENOMEM;
+ return (GSS_S_FAILURE);
+ }
+
+ handle->usage = cred_usage;
+ handle->endtime = cred->endtime;
+ handle->principal = NULL;
+ handle->destination_realm = NULL;
+ handle->keytab = NULL;
+ handle->ccache = NULL;
+ handle->mechanisms = NULL;
+ HEIMDAL_MUTEX_init(&handle->cred_id_mutex);
+
+ major = GSS_S_FAILURE;
+
+ *minor_status = krb5_copy_principal(context, cred->principal,
+ &handle->principal);
+ if (*minor_status) {
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+ free(handle);
+ return GSS_S_FAILURE;
+ }
+
+ if (cred->keytab) {
+ char *name = NULL;
+
+ *minor_status = krb5_kt_get_full_name(context, cred->keytab,
+ &name);
+ if (*minor_status)
+ goto failure;
+
+ *minor_status = krb5_kt_resolve(context, name, &handle->keytab);
+ krb5_xfree(name);
+ if (*minor_status)
+ goto failure;
+ }
+
+ if (cred->ccache) {
+ const char *type, *name;
+ char *type_name = NULL;
+
+ type = krb5_cc_get_type(context, cred->ccache);
+ if (type == NULL){
+ *minor_status = ENOMEM;
+ goto failure;
+ }
+
+ if (strcmp(type, "MEMORY") == 0) {
+ *minor_status = krb5_cc_new_unique(context, type,
+ NULL, &handle->ccache);
+ if (*minor_status)
+ goto failure;
+
+ *minor_status = krb5_cc_copy_cache(context, cred->ccache,
+ handle->ccache);
+ if (*minor_status)
+ goto failure;
+
+ } else {
+ name = krb5_cc_get_name(context, cred->ccache);
+ if (name == NULL) {
+ *minor_status = ENOMEM;
+ goto failure;
+ }
+
+ if (asprintf(&type_name, "%s:%s", type, name) == -1 ||
+ type_name == NULL) {
+ *minor_status = ENOMEM;
+ goto failure;
+ }
+
+ *minor_status = krb5_cc_resolve(context, type_name,
+ &handle->ccache);
+ free(type_name);
+ if (*minor_status)
+ goto failure;
+ }
+ }
+ major = gss_create_empty_oid_set(minor_status, &handle->mechanisms);
+ if (major != GSS_S_COMPLETE)
+ goto failure;
+
+ major = gss_add_oid_set_member(minor_status, GSS_KRB5_MECHANISM,
+ &handle->mechanisms);
+ if (major != GSS_S_COMPLETE)
+ goto failure;
+
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+
+ major = _gsskrb5_inquire_cred(minor_status, (gss_cred_id_t)cred,
+ NULL, &lifetime, NULL, actual_mechs);
+ if (major != GSS_S_COMPLETE)
+ goto failure;
+
+ *output_cred_handle = (gss_cred_id_t)handle;
+ }
+
+ if (initiator_time_rec)
+ *initiator_time_rec = lifetime;
+ if (acceptor_time_rec)
+ *acceptor_time_rec = lifetime;
+
+ *minor_status = 0;
+ return major;
+
+failure:
+ if (handle) {
+ if (handle->principal)
+ krb5_free_principal(context, handle->principal);
+ if (handle->keytab)
+ krb5_kt_close(context, handle->keytab);
+ if (handle->ccache)
+ krb5_cc_destroy(context, handle->ccache);
+ if (handle->mechanisms)
+ gss_release_oid_set(NULL, &handle->mechanisms);
+ free(handle);
+ }
+ if (cred && output_cred_handle)
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+ return major;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/address_to_krb5addr.c b/third_party/heimdal/lib/gssapi/krb5/address_to_krb5addr.c
new file mode 100644
index 0000000..fa115d9
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/address_to_krb5addr.c
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2000 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+#include <roken.h>
+
+krb5_error_code
+_gsskrb5i_address_to_krb5addr(krb5_context context,
+ OM_uint32 gss_addr_type,
+ gss_buffer_desc *gss_addr,
+ int16_t port,
+ krb5_address *address)
+{
+ int addr_type;
+ struct sockaddr sa;
+ krb5_socklen_t sa_size = sizeof(sa);
+ krb5_error_code problem;
+
+ if (gss_addr == NULL)
+ return GSS_S_FAILURE;
+
+ switch (gss_addr_type) {
+#ifdef HAVE_IPV6
+ case GSS_C_AF_INET6: addr_type = AF_INET6;
+ break;
+#endif /* HAVE_IPV6 */
+
+ case GSS_C_AF_INET: addr_type = AF_INET;
+ break;
+ default:
+ return GSS_S_FAILURE;
+ }
+
+ problem = krb5_h_addr2sockaddr (context,
+ addr_type,
+ gss_addr->value,
+ &sa,
+ &sa_size,
+ port);
+ if (problem)
+ return GSS_S_FAILURE;
+
+ problem = krb5_sockaddr2address (context, &sa, address);
+
+ return problem;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/aeap.c b/third_party/heimdal/lib/gssapi/krb5/aeap.c
new file mode 100644
index 0000000..fe95ecf
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/aeap.c
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+#include <roken.h>
+
+OM_uint32 GSSAPI_CALLCONV
+_gk_wrap_iov(OM_uint32 * minor_status,
+ gss_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ int * conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle;
+ krb5_context context;
+ OM_uint32 ret;
+ krb5_keyblock *key;
+ krb5_keytype keytype;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (ctx->more_flags & IS_CFX)
+ return _gssapi_wrap_cfx_iov(minor_status, ctx, context,
+ conf_req_flag, conf_state,
+ iov, iov_count);
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ ret = _gsskrb5i_get_token_key(ctx, context, &key);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ krb5_enctype_to_keytype(context, key->keytype, &keytype);
+
+ switch (keytype) {
+ case KEYTYPE_ARCFOUR:
+ case KEYTYPE_ARCFOUR_56:
+ ret = _gssapi_wrap_iov_arcfour(minor_status, ctx, context,
+ conf_req_flag, conf_state,
+ iov, iov_count, key);
+ break;
+
+ default:
+ ret = GSS_S_FAILURE;
+ break;
+ }
+
+ krb5_free_keyblock(context, key);
+ return ret;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gk_unwrap_iov(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ int *conf_state,
+ gss_qop_t *qop_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle;
+ krb5_context context;
+ OM_uint32 ret;
+ krb5_keytype keytype;
+ krb5_keyblock *key;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (ctx->more_flags & IS_CFX)
+ return _gssapi_unwrap_cfx_iov(minor_status, ctx, context,
+ conf_state, qop_state, iov, iov_count);
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ ret = _gsskrb5i_get_token_key(ctx, context, &key);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ krb5_enctype_to_keytype(context, key->keytype, &keytype);
+
+ switch (keytype) {
+ case KEYTYPE_ARCFOUR:
+ case KEYTYPE_ARCFOUR_56:
+ ret = _gssapi_unwrap_iov_arcfour(minor_status, ctx, context,
+ conf_state, qop_state,
+ iov, iov_count, key);
+ break;
+
+ default:
+ ret = GSS_S_FAILURE;
+ break;
+ }
+
+ krb5_free_keyblock(context, key);
+ return ret;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gk_wrap_iov_length(OM_uint32 * minor_status,
+ gss_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ int *conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle;
+ krb5_context context;
+ OM_uint32 ret;
+ krb5_keytype keytype;
+ krb5_keyblock *key;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (ctx->more_flags & IS_CFX)
+ return _gssapi_wrap_iov_length_cfx(minor_status, ctx, context,
+ conf_req_flag, qop_req, conf_state,
+ iov, iov_count);
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ ret = _gsskrb5i_get_token_key(ctx, context, &key);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ krb5_enctype_to_keytype(context, key->keytype, &keytype);
+
+ switch (keytype) {
+ case KEYTYPE_ARCFOUR:
+ case KEYTYPE_ARCFOUR_56:
+ ret = _gssapi_wrap_iov_length_arcfour(minor_status, ctx, context,
+ conf_req_flag, qop_req, conf_state,
+ iov, iov_count);
+ break;
+
+ default:
+ ret = GSS_S_FAILURE;
+ break;
+ }
+
+ krb5_free_keyblock(context, key);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/arcfour.c b/third_party/heimdal/lib/gssapi/krb5/arcfour.c
new file mode 100644
index 0000000..5c754bc
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/arcfour.c
@@ -0,0 +1,1391 @@
+/*
+ * Copyright (c) 2003 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+/*
+ * Implements draft-brezak-win2k-krb-rc4-hmac-04.txt
+ *
+ * The arcfour message have the following formats:
+ *
+ * MIC token
+ * TOK_ID[2] = 01 01
+ * SGN_ALG[2] = 11 00
+ * Filler[4]
+ * SND_SEQ[8]
+ * SGN_CKSUM[8]
+ *
+ * WRAP token
+ * TOK_ID[2] = 02 01
+ * SGN_ALG[2];
+ * SEAL_ALG[2]
+ * Filler[2]
+ * SND_SEQ[2]
+ * SGN_CKSUM[8]
+ * Confounder[8]
+ */
+
+/*
+ * WRAP in DCE-style have a fixed size header, the oid and length over
+ * the WRAP header is a total of
+ * GSS_ARCFOUR_WRAP_TOKEN_DCE_DER_HEADER_SIZE +
+ * GSS_ARCFOUR_WRAP_TOKEN_SIZE byte (ie total of 45 bytes overhead,
+ * remember the 2 bytes from APPL [0] SEQ).
+ */
+
+#define GSS_ARCFOUR_WRAP_TOKEN_SIZE 32
+#define GSS_ARCFOUR_WRAP_TOKEN_DCE_DER_HEADER_SIZE 13
+
+
+static krb5_error_code
+arcfour_mic_key(krb5_context context, krb5_keyblock *key,
+ const void *cksum_data, size_t cksum_size,
+ void *key6_data, size_t key6_size)
+{
+ krb5_error_code ret;
+
+ Checksum cksum_k5;
+ krb5_keyblock key5;
+ char k5_data[16];
+
+ Checksum cksum_k6;
+
+ char T[4];
+
+ memset(T, 0, 4);
+ cksum_k5.checksum.data = k5_data;
+ cksum_k5.checksum.length = sizeof(k5_data);
+
+ if (key->keytype == KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56) {
+ char L40[14] = "fortybits";
+
+ memcpy(L40 + 10, T, sizeof(T));
+ ret = krb5_hmac(context, CKSUMTYPE_RSA_MD5,
+ L40, 14, 0, key, &cksum_k5);
+ memset(&k5_data[7], 0xAB, 9);
+ } else {
+ ret = krb5_hmac(context, CKSUMTYPE_RSA_MD5,
+ T, 4, 0, key, &cksum_k5);
+ }
+ if (ret)
+ return ret;
+
+ key5.keytype = KRB5_ENCTYPE_ARCFOUR_HMAC_MD5;
+ key5.keyvalue = cksum_k5.checksum;
+
+ cksum_k6.checksum.data = key6_data;
+ cksum_k6.checksum.length = key6_size;
+
+ return krb5_hmac(context, CKSUMTYPE_RSA_MD5,
+ cksum_data, cksum_size, 0, &key5, &cksum_k6);
+}
+
+
+static krb5_error_code
+arcfour_mic_cksum_iov(krb5_context context,
+ krb5_keyblock *key, unsigned usage,
+ u_char *sgn_cksum, size_t sgn_cksum_sz,
+ const u_char *v1, size_t l1,
+ const void *v2, size_t l2,
+ const gss_iov_buffer_desc *iov,
+ int iov_count,
+ const gss_iov_buffer_desc *padding)
+{
+ Checksum CKSUM;
+ u_char *ptr;
+ size_t len;
+ size_t ofs = 0;
+ int i;
+ krb5_crypto crypto;
+ krb5_error_code ret;
+
+ assert(sgn_cksum_sz == 8);
+
+ len = l1 + l2;
+
+ for (i=0; i < iov_count; i++) {
+ switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+ break;
+ default:
+ continue;
+ }
+
+ len += iov[i].buffer.length;
+ }
+
+ if (padding) {
+ len += padding->buffer.length;
+ }
+
+ ptr = malloc(len);
+ if (ptr == NULL)
+ return ENOMEM;
+
+ memcpy(ptr + ofs, v1, l1);
+ ofs += l1;
+ memcpy(ptr + ofs, v2, l2);
+ ofs += l2;
+
+ for (i=0; i < iov_count; i++) {
+ switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+ break;
+ default:
+ continue;
+ }
+
+ if (iov[i].buffer.length > 0) {
+ assert(iov[i].buffer.value != NULL);
+ memcpy(ptr + ofs,
+ iov[i].buffer.value,
+ iov[i].buffer.length);
+ ofs += iov[i].buffer.length;
+ }
+ }
+
+ if (padding) {
+ memcpy(ptr + ofs,
+ padding->buffer.value,
+ padding->buffer.length);
+ /* ofs += padding->buffer.length; */
+ }
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret) {
+ free(ptr);
+ return ret;
+ }
+
+ ret = krb5_create_checksum(context,
+ crypto,
+ usage,
+ 0,
+ ptr, len,
+ &CKSUM);
+ memset(ptr, 0, len);
+ free(ptr);
+ if (ret == 0) {
+ memcpy(sgn_cksum, CKSUM.checksum.data, sgn_cksum_sz);
+ free_Checksum(&CKSUM);
+ }
+ krb5_crypto_destroy(context, crypto);
+
+ return ret;
+}
+
+static krb5_error_code
+arcfour_mic_cksum(krb5_context context,
+ krb5_keyblock *key, unsigned usage,
+ u_char *sgn_cksum, size_t sgn_cksum_sz,
+ const u_char *v1, size_t l1,
+ const void *v2, size_t l2,
+ const void *v3, size_t l3)
+{
+ gss_iov_buffer_desc iov;
+
+ iov.type = GSS_IOV_BUFFER_TYPE_SIGN_ONLY;
+ iov.buffer.value = rk_UNCONST(v3);
+ iov.buffer.length = l3;
+
+ return arcfour_mic_cksum_iov(context, key, usage,
+ sgn_cksum, sgn_cksum_sz,
+ v1, l1, v2, l2,
+ &iov, 1, NULL);
+}
+
+
+OM_uint32
+_gssapi_get_mic_arcfour(OM_uint32 * minor_status,
+ const gsskrb5_ctx context_handle,
+ krb5_context context,
+ gss_qop_t qop_req,
+ const gss_buffer_t message_buffer,
+ gss_buffer_t message_token,
+ krb5_keyblock *key)
+{
+ krb5_error_code ret;
+ int32_t seq_number;
+ size_t len, total_len;
+ u_char k6_data[16], *p0, *p;
+ EVP_CIPHER_CTX rc4_key;
+
+ _gsskrb5_encap_length (22, &len, &total_len, GSS_KRB5_MECHANISM);
+
+ message_token->length = total_len;
+ message_token->value = malloc (total_len);
+ if (message_token->value == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ p0 = _gssapi_make_mech_header(message_token->value,
+ len,
+ GSS_KRB5_MECHANISM);
+ p = p0;
+
+ *p++ = 0x01; /* TOK_ID */
+ *p++ = 0x01;
+ *p++ = 0x11; /* SGN_ALG */
+ *p++ = 0x00;
+ *p++ = 0xff; /* Filler */
+ *p++ = 0xff;
+ *p++ = 0xff;
+ *p++ = 0xff;
+
+ p = NULL;
+
+ ret = arcfour_mic_cksum(context,
+ key, KRB5_KU_USAGE_SIGN,
+ p0 + 16, 8, /* SGN_CKSUM */
+ p0, 8, /* TOK_ID, SGN_ALG, Filer */
+ message_buffer->value, message_buffer->length,
+ NULL, 0);
+ if (ret) {
+ _gsskrb5_release_buffer(minor_status, message_token);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = arcfour_mic_key(context, key,
+ p0 + 16, 8, /* SGN_CKSUM */
+ k6_data, sizeof(k6_data));
+ if (ret) {
+ _gsskrb5_release_buffer(minor_status, message_token);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+ krb5_auth_con_getlocalseqnumber (context,
+ context_handle->auth_context,
+ &seq_number);
+ p = p0 + 8; /* SND_SEQ */
+ _gsskrb5_encode_be_om_uint32(seq_number, p);
+
+ krb5_auth_con_setlocalseqnumber (context,
+ context_handle->auth_context,
+ ++seq_number);
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+
+ memset (p + 4, (context_handle->more_flags & LOCAL) ? 0 : 0xff, 4);
+
+ EVP_CIPHER_CTX_init(&rc4_key);
+ EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1);
+ EVP_Cipher(&rc4_key, p, p, 8);
+ EVP_CIPHER_CTX_cleanup(&rc4_key);
+
+ memset_s(k6_data, sizeof(k6_data), 0, sizeof(k6_data));
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+
+OM_uint32
+_gssapi_verify_mic_arcfour(OM_uint32 * minor_status,
+ const gsskrb5_ctx context_handle,
+ krb5_context context,
+ const gss_buffer_t message_buffer,
+ const gss_buffer_t token_buffer,
+ gss_qop_t * qop_state,
+ krb5_keyblock *key,
+ const char *type)
+{
+ krb5_error_code ret;
+ uint32_t seq_number;
+ OM_uint32 omret;
+ u_char SND_SEQ[8], cksum_data[8], *p;
+ char k6_data[16];
+ int cmp;
+
+ if (qop_state)
+ *qop_state = 0;
+
+ p = token_buffer->value;
+ omret = _gsskrb5_verify_header (&p,
+ token_buffer->length,
+ type,
+ GSS_KRB5_MECHANISM);
+ if (omret)
+ return omret;
+
+ if (memcmp(p, "\x11\x00", 2) != 0) /* SGN_ALG = HMAC MD5 ARCFOUR */
+ return GSS_S_BAD_SIG;
+ p += 2;
+ if (memcmp (p, "\xff\xff\xff\xff", 4) != 0)
+ return GSS_S_BAD_MIC;
+ p += 4;
+
+ ret = arcfour_mic_cksum(context,
+ key, KRB5_KU_USAGE_SIGN,
+ cksum_data, sizeof(cksum_data),
+ p - 8, 8,
+ message_buffer->value, message_buffer->length,
+ NULL, 0);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = arcfour_mic_key(context, key,
+ cksum_data, sizeof(cksum_data),
+ k6_data, sizeof(k6_data));
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ cmp = (ct_memcmp(cksum_data, p + 8, 8) != 0);
+ if (cmp) {
+ *minor_status = 0;
+ return GSS_S_BAD_MIC;
+ }
+
+ {
+ EVP_CIPHER_CTX rc4_key;
+
+ EVP_CIPHER_CTX_init(&rc4_key);
+ EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, (void *)k6_data, NULL, 0);
+ EVP_Cipher(&rc4_key, SND_SEQ, p, 8);
+ EVP_CIPHER_CTX_cleanup(&rc4_key);
+
+ memset(k6_data, 0, sizeof(k6_data));
+ }
+
+ _gsskrb5_decode_be_om_uint32(SND_SEQ, &seq_number);
+
+ if (context_handle->more_flags & LOCAL)
+ cmp = (ct_memcmp(&SND_SEQ[4], "\xff\xff\xff\xff", 4) != 0);
+ else
+ cmp = (ct_memcmp(&SND_SEQ[4], "\x00\x00\x00\x00", 4) != 0);
+
+ memset_s(SND_SEQ, sizeof(SND_SEQ), 0, sizeof(SND_SEQ));
+ if (cmp != 0) {
+ *minor_status = 0;
+ return GSS_S_BAD_MIC;
+ }
+
+ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+ omret = _gssapi_msg_order_check(context_handle->order, seq_number);
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ if (omret)
+ return omret;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_gssapi_wrap_arcfour(OM_uint32 * minor_status,
+ const gsskrb5_ctx context_handle,
+ krb5_context context,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ const gss_buffer_t input_message_buffer,
+ int * conf_state,
+ gss_buffer_t output_message_buffer,
+ krb5_keyblock *key)
+{
+ u_char Klocaldata[16], k6_data[16], *p, *p0;
+ size_t len, total_len, datalen;
+ krb5_keyblock Klocal;
+ krb5_error_code ret;
+ int32_t seq_number;
+
+ if (conf_state)
+ *conf_state = 0;
+
+ datalen = input_message_buffer->length;
+
+ if (IS_DCE_STYLE(context_handle)) {
+ len = GSS_ARCFOUR_WRAP_TOKEN_SIZE;
+ _gssapi_encap_length(len, &len, &total_len, GSS_KRB5_MECHANISM);
+ total_len += datalen;
+ } else {
+ datalen += 1; /* padding */
+ len = datalen + GSS_ARCFOUR_WRAP_TOKEN_SIZE;
+ _gssapi_encap_length(len, &len, &total_len, GSS_KRB5_MECHANISM);
+ }
+
+ output_message_buffer->length = total_len;
+ output_message_buffer->value = malloc (total_len);
+ if (output_message_buffer->value == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ p0 = _gssapi_make_mech_header(output_message_buffer->value,
+ len,
+ GSS_KRB5_MECHANISM);
+ p = p0;
+
+ *p++ = 0x02; /* TOK_ID */
+ *p++ = 0x01;
+ *p++ = 0x11; /* SGN_ALG */
+ *p++ = 0x00;
+ if (conf_req_flag) {
+ *p++ = 0x10; /* SEAL_ALG */
+ *p++ = 0x00;
+ } else {
+ *p++ = 0xff; /* SEAL_ALG */
+ *p++ = 0xff;
+ }
+ *p++ = 0xff; /* Filler */
+ *p++ = 0xff;
+
+ p = NULL;
+
+ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+ krb5_auth_con_getlocalseqnumber (context,
+ context_handle->auth_context,
+ &seq_number);
+
+ _gsskrb5_encode_be_om_uint32(seq_number, p0 + 8);
+
+ krb5_auth_con_setlocalseqnumber (context,
+ context_handle->auth_context,
+ ++seq_number);
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+
+ memset (p0 + 8 + 4,
+ (context_handle->more_flags & LOCAL) ? 0 : 0xff,
+ 4);
+
+ krb5_generate_random_block(p0 + 24, 8); /* fill in Confounder */
+
+ /* p points to data */
+ p = p0 + GSS_ARCFOUR_WRAP_TOKEN_SIZE;
+ memcpy(p, input_message_buffer->value, input_message_buffer->length);
+
+ if (!IS_DCE_STYLE(context_handle))
+ p[input_message_buffer->length] = 1; /* padding */
+
+ ret = arcfour_mic_cksum(context,
+ key, KRB5_KU_USAGE_SEAL,
+ p0 + 16, 8, /* SGN_CKSUM */
+ p0, 8, /* TOK_ID, SGN_ALG, SEAL_ALG, Filler */
+ p0 + 24, 8, /* Confounder */
+ p0 + GSS_ARCFOUR_WRAP_TOKEN_SIZE,
+ datalen);
+ if (ret) {
+ *minor_status = ret;
+ _gsskrb5_release_buffer(minor_status, output_message_buffer);
+ return GSS_S_FAILURE;
+ }
+
+ {
+ int i;
+
+ Klocal.keytype = key->keytype;
+ Klocal.keyvalue.data = Klocaldata;
+ Klocal.keyvalue.length = sizeof(Klocaldata);
+
+ for (i = 0; i < 16; i++)
+ Klocaldata[i] = ((u_char *)key->keyvalue.data)[i] ^ 0xF0;
+ }
+ ret = arcfour_mic_key(context, &Klocal,
+ p0 + 8, 4, /* SND_SEQ */
+ k6_data, sizeof(k6_data));
+ memset_s(Klocaldata, sizeof(Klocaldata), 0, sizeof(Klocaldata));
+ if (ret) {
+ _gsskrb5_release_buffer(minor_status, output_message_buffer);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+
+ if(conf_req_flag) {
+ EVP_CIPHER_CTX rc4_key;
+
+ EVP_CIPHER_CTX_init(&rc4_key);
+ EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1);
+ EVP_Cipher(&rc4_key, p0 + 24, p0 + 24, 8 + datalen);
+ EVP_CIPHER_CTX_cleanup(&rc4_key);
+ }
+ memset(k6_data, 0, sizeof(k6_data));
+
+ ret = arcfour_mic_key(context, key,
+ p0 + 16, 8, /* SGN_CKSUM */
+ k6_data, sizeof(k6_data));
+ if (ret) {
+ _gsskrb5_release_buffer(minor_status, output_message_buffer);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ {
+ EVP_CIPHER_CTX rc4_key;
+
+ EVP_CIPHER_CTX_init(&rc4_key);
+ EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1);
+ EVP_Cipher(&rc4_key, p0 + 8, p0 + 8 /* SND_SEQ */, 8);
+ EVP_CIPHER_CTX_cleanup(&rc4_key);
+ memset_s(k6_data, sizeof(k6_data), 0, sizeof(k6_data));
+ }
+
+ if (conf_state)
+ *conf_state = conf_req_flag;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 _gssapi_unwrap_arcfour(OM_uint32 *minor_status,
+ const gsskrb5_ctx context_handle,
+ krb5_context context,
+ const gss_buffer_t input_message_buffer,
+ gss_buffer_t output_message_buffer,
+ int *conf_state,
+ gss_qop_t *qop_state,
+ krb5_keyblock *key)
+{
+ u_char Klocaldata[16];
+ krb5_keyblock Klocal;
+ krb5_error_code ret;
+ uint32_t seq_number;
+ size_t datalen;
+ OM_uint32 omret;
+ u_char k6_data[16], SND_SEQ[8], Confounder[8];
+ u_char cksum_data[8];
+ u_char *p, *p0;
+ int cmp;
+ int conf_flag;
+ size_t padlen = 0, len;
+
+ if (conf_state)
+ *conf_state = 0;
+ if (qop_state)
+ *qop_state = 0;
+
+ p0 = input_message_buffer->value;
+
+ if (IS_DCE_STYLE(context_handle)) {
+ len = GSS_ARCFOUR_WRAP_TOKEN_SIZE +
+ GSS_ARCFOUR_WRAP_TOKEN_DCE_DER_HEADER_SIZE;
+ if (input_message_buffer->length < len)
+ return GSS_S_BAD_MECH;
+ } else {
+ len = input_message_buffer->length;
+ }
+
+ omret = _gssapi_verify_mech_header(&p0,
+ len,
+ GSS_KRB5_MECHANISM);
+ if (omret)
+ return omret;
+
+ /* length of mech header */
+ len = (p0 - (u_char *)input_message_buffer->value) +
+ GSS_ARCFOUR_WRAP_TOKEN_SIZE;
+
+ if (len > input_message_buffer->length)
+ return GSS_S_BAD_MECH;
+
+ /* length of data */
+ datalen = input_message_buffer->length - len;
+
+ p = p0;
+
+ if (memcmp(p, "\x02\x01", 2) != 0)
+ return GSS_S_BAD_SIG;
+ p += 2;
+ if (memcmp(p, "\x11\x00", 2) != 0) /* SGN_ALG = HMAC MD5 ARCFOUR */
+ return GSS_S_BAD_SIG;
+ p += 2;
+
+ if (memcmp (p, "\x10\x00", 2) == 0)
+ conf_flag = 1;
+ else if (memcmp (p, "\xff\xff", 2) == 0)
+ conf_flag = 0;
+ else
+ return GSS_S_BAD_SIG;
+
+ p += 2;
+ if (memcmp (p, "\xff\xff", 2) != 0)
+ return GSS_S_BAD_MIC;
+ p = NULL;
+
+ ret = arcfour_mic_key(context, key,
+ p0 + 16, 8, /* SGN_CKSUM */
+ k6_data, sizeof(k6_data));
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ {
+ EVP_CIPHER_CTX rc4_key;
+
+ EVP_CIPHER_CTX_init(&rc4_key);
+ EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1);
+ EVP_Cipher(&rc4_key, SND_SEQ, p0 + 8, 8);
+ EVP_CIPHER_CTX_cleanup(&rc4_key);
+ memset_s(k6_data, sizeof(k6_data), 0, sizeof(k6_data));
+ }
+
+ _gsskrb5_decode_be_om_uint32(SND_SEQ, &seq_number);
+
+ if (context_handle->more_flags & LOCAL)
+ cmp = (ct_memcmp(&SND_SEQ[4], "\xff\xff\xff\xff", 4) != 0);
+ else
+ cmp = (ct_memcmp(&SND_SEQ[4], "\x00\x00\x00\x00", 4) != 0);
+
+ if (cmp != 0) {
+ *minor_status = 0;
+ return GSS_S_BAD_MIC;
+ }
+
+ {
+ int i;
+
+ Klocal.keytype = key->keytype;
+ Klocal.keyvalue.data = Klocaldata;
+ Klocal.keyvalue.length = sizeof(Klocaldata);
+
+ for (i = 0; i < 16; i++)
+ Klocaldata[i] = ((u_char *)key->keyvalue.data)[i] ^ 0xF0;
+ }
+ ret = arcfour_mic_key(context, &Klocal,
+ SND_SEQ, 4,
+ k6_data, sizeof(k6_data));
+ memset_s(Klocaldata, sizeof(Klocaldata), 0, sizeof(Klocaldata));
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ output_message_buffer->value = malloc(datalen);
+ if (output_message_buffer->value == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ output_message_buffer->length = datalen;
+
+ if(conf_flag) {
+ EVP_CIPHER_CTX rc4_key;
+
+ EVP_CIPHER_CTX_init(&rc4_key);
+ EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1);
+ EVP_Cipher(&rc4_key, Confounder, p0 + 24, 8);
+ EVP_Cipher(&rc4_key, output_message_buffer->value, p0 + GSS_ARCFOUR_WRAP_TOKEN_SIZE, datalen);
+ EVP_CIPHER_CTX_cleanup(&rc4_key);
+ } else {
+ memcpy(Confounder, p0 + 24, 8); /* Confounder */
+ memcpy(output_message_buffer->value,
+ p0 + GSS_ARCFOUR_WRAP_TOKEN_SIZE,
+ datalen);
+ }
+ memset(k6_data, 0, sizeof(k6_data));
+
+ if (!IS_DCE_STYLE(context_handle)) {
+ ret = _gssapi_verify_pad(output_message_buffer, datalen, &padlen);
+ if (ret) {
+ _gsskrb5_release_buffer(minor_status, output_message_buffer);
+ *minor_status = 0;
+ return ret;
+ }
+ output_message_buffer->length -= padlen;
+ }
+
+ ret = arcfour_mic_cksum(context,
+ key, KRB5_KU_USAGE_SEAL,
+ cksum_data, sizeof(cksum_data),
+ p0, 8,
+ Confounder, sizeof(Confounder),
+ output_message_buffer->value,
+ output_message_buffer->length + padlen);
+ if (ret) {
+ _gsskrb5_release_buffer(minor_status, output_message_buffer);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ cmp = ct_memcmp(cksum_data, p0 + 16, 8); /* SGN_CKSUM */
+ if (cmp) {
+ _gsskrb5_release_buffer(minor_status, output_message_buffer);
+ *minor_status = 0;
+ return GSS_S_BAD_MIC;
+ }
+
+ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+ omret = _gssapi_msg_order_check(context_handle->order, seq_number);
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ if (omret)
+ return omret;
+
+ if (conf_state)
+ *conf_state = conf_flag;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+max_wrap_length_arcfour(const gsskrb5_ctx ctx,
+ krb5_crypto crypto,
+ size_t input_length,
+ OM_uint32 *max_input_size)
+{
+ /*
+ * if GSS_C_DCE_STYLE is in use:
+ * - we only need to encapsulate the WRAP token
+ * However, since this is a fixed since, we just
+ */
+ if (IS_DCE_STYLE(ctx)) {
+ size_t len, total_len;
+
+ len = GSS_ARCFOUR_WRAP_TOKEN_SIZE;
+ _gssapi_encap_length(len, &len, &total_len, GSS_KRB5_MECHANISM);
+
+ if (input_length < len)
+ *max_input_size = 0;
+ else
+ *max_input_size = input_length - len;
+
+ } else {
+ size_t extrasize = GSS_ARCFOUR_WRAP_TOKEN_SIZE;
+ size_t blocksize = 8;
+ size_t len, total_len;
+
+ len = 8 + input_length + blocksize + extrasize;
+
+ _gsskrb5_encap_length(len, &len, &total_len, GSS_KRB5_MECHANISM);
+
+ total_len -= input_length; /* token length */
+ if (total_len < input_length) {
+ *max_input_size = (input_length - total_len);
+ (*max_input_size) &= (~(OM_uint32)(blocksize - 1));
+ } else {
+ *max_input_size = 0;
+ }
+ }
+
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_gssapi_wrap_size_arcfour(OM_uint32 *minor_status,
+ const gsskrb5_ctx ctx,
+ krb5_context context,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ OM_uint32 req_output_size,
+ OM_uint32 *max_input_size,
+ krb5_keyblock *key)
+{
+ krb5_error_code ret;
+ krb5_crypto crypto;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret != 0) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = max_wrap_length_arcfour(ctx, crypto,
+ req_output_size, max_input_size);
+ if (ret != 0) {
+ *minor_status = ret;
+ krb5_crypto_destroy(context, crypto);
+ return GSS_S_FAILURE;
+ }
+
+ krb5_crypto_destroy(context, crypto);
+
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_gssapi_wrap_iov_length_arcfour(OM_uint32 *minor_status,
+ gsskrb5_ctx ctx,
+ krb5_context context,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ int *conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ OM_uint32 major_status;
+ size_t data_len = 0;
+ int i;
+ gss_iov_buffer_desc *header = NULL;
+ gss_iov_buffer_desc *padding = NULL;
+ gss_iov_buffer_desc *trailer = NULL;
+
+ *minor_status = 0;
+
+ for (i = 0; i < iov_count; i++) {
+ switch(GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+ case GSS_IOV_BUFFER_TYPE_EMPTY:
+ break;
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ data_len += iov[i].buffer.length;
+ break;
+ case GSS_IOV_BUFFER_TYPE_HEADER:
+ if (header != NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ header = &iov[i];
+ break;
+ case GSS_IOV_BUFFER_TYPE_TRAILER:
+ if (trailer != NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ trailer = &iov[i];
+ break;
+ case GSS_IOV_BUFFER_TYPE_PADDING:
+ if (padding != NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ padding = &iov[i];
+ break;
+ case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+ break;
+ default:
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ }
+
+ if (header == NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ major_status = _gk_verify_buffers(minor_status, ctx, header,
+ padding, trailer, FALSE);
+ if (major_status != GSS_S_COMPLETE) {
+ return major_status;
+ }
+
+ if (IS_DCE_STYLE(ctx)) {
+ size_t len = GSS_ARCFOUR_WRAP_TOKEN_SIZE;
+ size_t total_len;
+ _gssapi_encap_length(len, &len, &total_len, GSS_KRB5_MECHANISM);
+ header->buffer.length = total_len;
+ } else {
+ size_t len;
+ size_t total_len;
+ if (padding) {
+ data_len += 1; /* padding */
+ }
+ len = data_len + GSS_ARCFOUR_WRAP_TOKEN_SIZE;
+ _gssapi_encap_length(len, &len, &total_len, GSS_KRB5_MECHANISM);
+ header->buffer.length = total_len - data_len;
+ }
+
+ if (trailer) {
+ trailer->buffer.length = 0;
+ }
+
+ if (padding) {
+ padding->buffer.length = 1;
+ }
+
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_gssapi_wrap_iov_arcfour(OM_uint32 *minor_status,
+ gsskrb5_ctx ctx,
+ krb5_context context,
+ int conf_req_flag,
+ int *conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count,
+ krb5_keyblock *key)
+{
+ OM_uint32 major_status, junk;
+ gss_iov_buffer_desc *header, *padding, *trailer;
+ krb5_error_code kret;
+ int32_t seq_number;
+ u_char Klocaldata[16], k6_data[16], *p, *p0;
+ size_t make_len = 0;
+ size_t header_len = 0;
+ size_t data_len = 0;
+ krb5_keyblock Klocal;
+ int i;
+
+ header = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER);
+ padding = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_PADDING);
+ trailer = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER);
+
+ major_status = _gk_verify_buffers(minor_status, ctx, header,
+ padding, trailer, FALSE);
+ if (major_status != GSS_S_COMPLETE) {
+ return major_status;
+ }
+
+ for (i = 0; i < iov_count; i++) {
+ switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ break;
+ default:
+ continue;
+ }
+
+ data_len += iov[i].buffer.length;
+ }
+
+ if (padding) {
+ data_len += 1;
+ }
+
+ if (IS_DCE_STYLE(ctx)) {
+ size_t unwrapped_len;
+ unwrapped_len = GSS_ARCFOUR_WRAP_TOKEN_SIZE;
+ _gssapi_encap_length(unwrapped_len,
+ &make_len,
+ &header_len,
+ GSS_KRB5_MECHANISM);
+ } else {
+ size_t unwrapped_len;
+ unwrapped_len = GSS_ARCFOUR_WRAP_TOKEN_SIZE + data_len;
+ _gssapi_encap_length(unwrapped_len,
+ &make_len,
+ &header_len,
+ GSS_KRB5_MECHANISM);
+ header_len -= data_len;
+ }
+
+ if (GSS_IOV_BUFFER_FLAGS(header->type) & GSS_IOV_BUFFER_FLAG_ALLOCATE) {
+ major_status = _gk_allocate_buffer(minor_status, header,
+ header_len);
+ if (major_status != GSS_S_COMPLETE)
+ goto failure;
+ } else if (header->buffer.length < header_len) {
+ *minor_status = KRB5_BAD_MSIZE;
+ major_status = GSS_S_FAILURE;
+ goto failure;
+ } else {
+ header->buffer.length = header_len;
+ }
+
+ if (padding) {
+ if (GSS_IOV_BUFFER_FLAGS(padding->type) & GSS_IOV_BUFFER_FLAG_ALLOCATE) {
+ major_status = _gk_allocate_buffer(minor_status, padding, 1);
+ if (major_status != GSS_S_COMPLETE)
+ goto failure;
+ } else if (padding->buffer.length < 1) {
+ *minor_status = KRB5_BAD_MSIZE;
+ major_status = GSS_S_FAILURE;
+ goto failure;
+ } else {
+ padding->buffer.length = 1;
+ }
+ memset(padding->buffer.value, 1, 1);
+ }
+
+ if (trailer) {
+ trailer->buffer.length = 0;
+ trailer->buffer.value = NULL;
+ }
+
+ p0 = _gssapi_make_mech_header(header->buffer.value,
+ make_len,
+ GSS_KRB5_MECHANISM);
+ p = p0;
+
+ *p++ = 0x02; /* TOK_ID */
+ *p++ = 0x01;
+ *p++ = 0x11; /* SGN_ALG */
+ *p++ = 0x00;
+ if (conf_req_flag) {
+ *p++ = 0x10; /* SEAL_ALG */
+ *p++ = 0x00;
+ } else {
+ *p++ = 0xff; /* SEAL_ALG */
+ *p++ = 0xff;
+ }
+ *p++ = 0xff; /* Filler */
+ *p++ = 0xff;
+
+ p = NULL;
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ krb5_auth_con_getlocalseqnumber(context,
+ ctx->auth_context,
+ &seq_number);
+ _gsskrb5_encode_be_om_uint32(seq_number, p0 + 8);
+
+ krb5_auth_con_setlocalseqnumber(context,
+ ctx->auth_context,
+ ++seq_number);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ memset(p0 + 8 + 4,
+ (ctx->more_flags & LOCAL) ? 0 : 0xff,
+ 4);
+
+ krb5_generate_random_block(p0 + 24, 8); /* fill in Confounder */
+
+ /* Sign Data */
+ kret = arcfour_mic_cksum_iov(context,
+ key, KRB5_KU_USAGE_SEAL,
+ p0 + 16, 8, /* SGN_CKSUM */
+ p0, 8, /* TOK_ID, SGN_ALG, SEAL_ALG, Filler */
+ p0 + 24, 8, /* Confounder */
+ iov, iov_count, /* Data + SignOnly */
+ padding); /* padding */
+ if (kret) {
+ *minor_status = kret;
+ major_status = GSS_S_FAILURE;
+ goto failure;
+ }
+
+ Klocal.keytype = key->keytype;
+ Klocal.keyvalue.data = Klocaldata;
+ Klocal.keyvalue.length = sizeof(Klocaldata);
+
+ for (i = 0; i < 16; i++) {
+ Klocaldata[i] = ((u_char *)key->keyvalue.data)[i] ^ 0xF0;
+ }
+ kret = arcfour_mic_key(context, &Klocal,
+ p0 + 8, 4, /* SND_SEQ */
+ k6_data, sizeof(k6_data));
+ memset_s(Klocaldata, sizeof(Klocaldata), 0, sizeof(Klocaldata));
+ if (kret) {
+ *minor_status = kret;
+ major_status = GSS_S_FAILURE;
+ goto failure;
+ }
+
+ if (conf_req_flag) {
+ EVP_CIPHER_CTX rc4_key;
+
+ EVP_CIPHER_CTX_init(&rc4_key);
+ EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1);
+
+ /* Confounder */
+ EVP_Cipher(&rc4_key, p0 + 24, p0 + 24, 8);
+
+ /* Seal Data */
+ for (i=0; i < iov_count; i++) {
+ switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ break;
+ default:
+ continue;
+ }
+
+ EVP_Cipher(&rc4_key, iov[i].buffer.value,
+ iov[i].buffer.value, iov[i].buffer.length);
+ }
+
+ /* Padding */
+ if (padding) {
+ EVP_Cipher(&rc4_key, padding->buffer.value,
+ padding->buffer.value, padding->buffer.length);
+ }
+
+ EVP_CIPHER_CTX_cleanup(&rc4_key);
+ }
+ memset(k6_data, 0, sizeof(k6_data));
+
+ kret = arcfour_mic_key(context, key,
+ p0 + 16, 8, /* SGN_CKSUM */
+ k6_data, sizeof(k6_data));
+ if (kret) {
+ *minor_status = kret;
+ major_status = GSS_S_FAILURE;
+ return major_status;
+ }
+
+ {
+ EVP_CIPHER_CTX rc4_key;
+
+ EVP_CIPHER_CTX_init(&rc4_key);
+ EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1);
+ EVP_Cipher(&rc4_key, p0 + 8, p0 + 8, 8); /* SND_SEQ */
+ EVP_CIPHER_CTX_cleanup(&rc4_key);
+
+ memset(k6_data, 0, sizeof(k6_data));
+ }
+
+ if (conf_state)
+ *conf_state = conf_req_flag;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+
+failure:
+
+ gss_release_iov_buffer(&junk, iov, iov_count);
+
+ return major_status;
+}
+
+OM_uint32
+_gssapi_unwrap_iov_arcfour(OM_uint32 *minor_status,
+ gsskrb5_ctx ctx,
+ krb5_context context,
+ int *pconf_state,
+ gss_qop_t *pqop_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count,
+ krb5_keyblock *key)
+{
+ OM_uint32 major_status;
+ gss_iov_buffer_desc *header, *padding, *trailer;
+ krb5_keyblock Klocal;
+ uint8_t Klocaldata[16];
+ uint8_t k6_data[16], snd_seq[8], Confounder[8];
+ uint8_t cksum_data[8];
+ uint8_t *_p = NULL;
+ const uint8_t *p, *p0;
+ size_t verify_len = 0;
+ uint32_t seq_number;
+ size_t hlen = 0;
+ int conf_state;
+ int cmp;
+ size_t i;
+ krb5_error_code kret;
+ OM_uint32 ret;
+
+ if (pconf_state != NULL) {
+ *pconf_state = 0;
+ }
+ if (pqop_state != NULL) {
+ *pqop_state = 0;
+ }
+
+ header = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER);
+ padding = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_PADDING);
+ trailer = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER);
+
+ /* Check if the packet is correct */
+ major_status = _gk_verify_buffers(minor_status,
+ ctx,
+ header,
+ padding,
+ trailer,
+ FALSE); /* behaves as stream cipher */
+ if (major_status != GSS_S_COMPLETE) {
+ return major_status;
+ }
+
+ if (padding != NULL && padding->buffer.length != 1) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ verify_len = header->buffer.length;
+
+ if (!IS_DCE_STYLE(ctx)) {
+ for (i = 0; i < iov_count; i++) {
+ /* length in header also includes data and padding */
+ if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_DATA)
+ verify_len += iov[i].buffer.length;
+ }
+
+ if (padding)
+ verify_len += padding->buffer.length;
+ }
+
+ _p = header->buffer.value;
+
+ ret = _gssapi_verify_mech_header(&_p,
+ verify_len,
+ GSS_KRB5_MECHANISM);
+ if (ret) {
+ return ret;
+ }
+ p0 = _p;
+
+ /* length of mech header */
+ hlen = (p0 - (uint8_t *)header->buffer.value);
+ hlen += GSS_ARCFOUR_WRAP_TOKEN_SIZE;
+
+ if (hlen > header->buffer.length) {
+ return GSS_S_BAD_MECH;
+ }
+
+ p = p0;
+
+ if (memcmp(p, "\x02\x01", 2) != 0)
+ return GSS_S_BAD_SIG;
+ p += 2;
+ if (memcmp(p, "\x11\x00", 2) != 0) /* SGN_ALG = HMAC MD5 ARCFOUR */
+ return GSS_S_BAD_SIG;
+ p += 2;
+
+ if (memcmp (p, "\x10\x00", 2) == 0)
+ conf_state = 1;
+ else if (memcmp (p, "\xff\xff", 2) == 0)
+ conf_state = 0;
+ else
+ return GSS_S_BAD_SIG;
+
+ p += 2;
+ if (memcmp (p, "\xff\xff", 2) != 0)
+ return GSS_S_BAD_MIC;
+ p = NULL;
+
+ kret = arcfour_mic_key(context,
+ key,
+ p0 + 16, /* SGN_CKSUM */
+ 8, /* SGN_CKSUM_LEN */
+ k6_data,
+ sizeof(k6_data));
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ {
+ EVP_CIPHER_CTX rc4_key;
+
+ EVP_CIPHER_CTX_init(&rc4_key);
+ EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1);
+ EVP_Cipher(&rc4_key, snd_seq, p0 + 8, 8); /* SND_SEQ */
+ EVP_CIPHER_CTX_cleanup(&rc4_key);
+
+ memset(k6_data, 0, sizeof(k6_data));
+ }
+
+ _gsskrb5_decode_be_om_uint32(snd_seq, &seq_number);
+
+ if (ctx->more_flags & LOCAL) {
+ cmp = (ct_memcmp(&snd_seq[4], "\xff\xff\xff\xff", 4) != 0);
+ } else {
+ cmp = (ct_memcmp(&snd_seq[4], "\x00\x00\x00\x00", 4) != 0);
+ }
+ if (cmp != 0) {
+ *minor_status = 0;
+ return GSS_S_BAD_MIC;
+ }
+
+ /* keyblock */
+ Klocal.keytype = key->keytype;
+ Klocal.keyvalue.data = Klocaldata;
+ Klocal.keyvalue.length = sizeof(Klocaldata);
+
+ for (i = 0; i < 16; i++) {
+ Klocaldata[i] = ((u_char *)key->keyvalue.data)[i] ^ 0xF0;
+ }
+
+ kret = arcfour_mic_key(context,
+ &Klocal,
+ snd_seq,
+ 4,
+ k6_data, sizeof(k6_data));
+ memset_s(Klocaldata, sizeof(Klocaldata), 0, sizeof(Klocaldata));
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ if (conf_state == 1) {
+ EVP_CIPHER_CTX rc4_key;
+
+ EVP_CIPHER_CTX_init(&rc4_key);
+ EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1);
+
+ /* Confounder */
+ EVP_Cipher(&rc4_key, Confounder, p0 + 24, 8);
+
+ /* Data */
+ for (i = 0; i < iov_count; i++) {
+ switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ break;
+ default:
+ continue;
+ }
+
+ EVP_Cipher(&rc4_key, iov[i].buffer.value,
+ iov[i].buffer.value, iov[i].buffer.length);
+ }
+
+ /* Padding */
+ if (padding) {
+ EVP_Cipher(&rc4_key, padding->buffer.value,
+ padding->buffer.value, padding->buffer.length);
+ }
+
+ EVP_CIPHER_CTX_cleanup(&rc4_key);
+ } else {
+ /* Confounder */
+ memcpy(Confounder, p0 + 24, 8);
+ }
+ memset(k6_data, 0, sizeof(k6_data));
+
+ /* Prepare the buffer for signing */
+ kret = arcfour_mic_cksum_iov(context,
+ key, KRB5_KU_USAGE_SEAL,
+ cksum_data, sizeof(cksum_data),
+ p0, 8,
+ Confounder, sizeof(Confounder),
+ iov, iov_count,
+ padding);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ cmp = (ct_memcmp(cksum_data, p0 + 16, 8) != 0); /* SGN_CKSUM */
+ if (cmp) {
+ *minor_status = 0;
+ return GSS_S_BAD_MIC;
+ }
+
+ if (padding) {
+ size_t plen;
+
+ ret = _gssapi_verify_pad(&padding->buffer, 1, &plen);
+ if (ret) {
+ *minor_status = 0;
+ return ret;
+ }
+ }
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ ret = _gssapi_msg_order_check(ctx->order, seq_number);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ if (ret != 0) {
+ return ret;
+ }
+
+ if (pconf_state) {
+ *pconf_state = conf_state;
+ }
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/authorize_localname.c b/third_party/heimdal/lib/gssapi/krb5/authorize_localname.c
new file mode 100644
index 0000000..5621c1f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/authorize_localname.c
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2011, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_authorize_localname(OM_uint32 *minor_status,
+ gss_const_name_t input_name,
+ gss_const_buffer_t user_name,
+ gss_const_OID user_name_type)
+{
+ krb5_context context;
+ krb5_principal princ = (krb5_principal)input_name;
+ char *user;
+ int user_ok;
+
+ if (!gss_oid_equal(user_name_type, GSS_C_NT_USER_NAME))
+ return GSS_S_BAD_NAMETYPE;
+
+ GSSAPI_KRB5_INIT(&context);
+
+ user = malloc(user_name->length + 1);
+ if (user == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ memcpy(user, user_name->value, user_name->length);
+ user[user_name->length] = '\0';
+
+ *minor_status = 0;
+ user_ok = krb5_kuserok(context, princ, user);
+
+ free(user);
+
+ return user_ok ? GSS_S_COMPLETE : GSS_S_UNAUTHORIZED;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/canonicalize_name.c b/third_party/heimdal/lib/gssapi/krb5/canonicalize_name.c
new file mode 100644
index 0000000..62de423
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/canonicalize_name.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_canonicalize_name (
+ OM_uint32 * minor_status,
+ gss_const_name_t input_name,
+ const gss_OID mech_type,
+ gss_name_t * output_name
+ )
+{
+ krb5_context context;
+ krb5_principal name;
+ OM_uint32 ret;
+
+ *output_name = NULL;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ ret = _gsskrb5_canon_name(minor_status, context, input_name, &name);
+ if (ret)
+ return ret;
+
+ *output_name = (gss_name_t)name;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/ccache_name.c b/third_party/heimdal/lib/gssapi/krb5/ccache_name.c
new file mode 100644
index 0000000..0a2d596
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/ccache_name.c
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+static heim_base_atomic(char *) last_out_name; /* XXX should be thread-specific */
+
+OM_uint32
+_gsskrb5_krb5_ccache_name(OM_uint32 *minor_status,
+ const char *name,
+ const char **out_name)
+{
+ krb5_context context;
+ krb5_error_code kret;
+
+ *minor_status = 0;
+
+ GSSAPI_KRB5_INIT(&context);
+
+ if (out_name) {
+ const char *def_name;
+
+ *out_name = NULL;
+
+ def_name = krb5_cc_default_name(context);
+ if (def_name) {
+ char *s = strdup(def_name);
+ if (s) {
+ s = heim_base_exchange_pointer(&last_out_name, s);
+ free(s);
+
+ *out_name = last_out_name;
+ }
+ }
+
+ if (*out_name == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ }
+
+ kret = krb5_cc_set_default_name(context, name);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/cfx.c b/third_party/heimdal/lib/gssapi/krb5/cfx.c
new file mode 100644
index 0000000..8d806f9
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/cfx.c
@@ -0,0 +1,1797 @@
+/*
+ * Copyright (c) 2003, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+/*
+ * Implementation of RFC 4121
+ */
+
+#define CFXSentByAcceptor (1 << 0)
+#define CFXSealed (1 << 1)
+#define CFXAcceptorSubkey (1 << 2)
+
+krb5_error_code
+_gsskrb5cfx_wrap_length_cfx(krb5_context context,
+ krb5_crypto crypto,
+ int conf_req_flag,
+ int dce_style,
+ size_t input_length,
+ size_t *output_length,
+ size_t *cksumsize,
+ uint16_t *padlength)
+{
+ krb5_error_code ret;
+ krb5_cksumtype type;
+
+ /* 16-byte header is always first */
+ *output_length = sizeof(gss_cfx_wrap_token_desc);
+ *padlength = 0;
+
+ ret = krb5_crypto_get_checksum_type(context, crypto, &type);
+ if (ret)
+ return ret;
+
+ ret = krb5_checksumsize(context, type, cksumsize);
+ if (ret)
+ return ret;
+
+ if (conf_req_flag) {
+ size_t padsize;
+
+ /* Header is concatenated with data before encryption */
+ input_length += sizeof(gss_cfx_wrap_token_desc);
+
+ if (dce_style) {
+ ret = krb5_crypto_getblocksize(context, crypto, &padsize);
+ } else {
+ ret = krb5_crypto_getpadsize(context, crypto, &padsize);
+ }
+ if (ret) {
+ return ret;
+ }
+ if (padsize > 1) {
+ /* XXX check this */
+ *padlength = padsize - (input_length % padsize);
+
+ /* We add the pad ourselves (noted here for completeness only) */
+ input_length += *padlength;
+ }
+
+ *output_length += krb5_get_wrapped_length(context,
+ crypto, input_length);
+ } else {
+ /* Checksum is concatenated with data */
+ *output_length += input_length + *cksumsize;
+ }
+
+ assert(*output_length > input_length);
+
+ return 0;
+}
+
+OM_uint32
+_gssapi_wrap_size_cfx(OM_uint32 *minor_status,
+ const gsskrb5_ctx ctx,
+ krb5_context context,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ OM_uint32 req_output_size,
+ OM_uint32 *max_input_size)
+{
+ krb5_error_code ret;
+
+ *max_input_size = 0;
+
+ /* 16-byte header is always first */
+ if (req_output_size < 16)
+ return 0;
+ req_output_size -= 16;
+
+ if (conf_req_flag) {
+ size_t wrapped_size, sz;
+
+ wrapped_size = req_output_size + 1;
+ do {
+ wrapped_size--;
+ sz = krb5_get_wrapped_length(context,
+ ctx->crypto, wrapped_size);
+ } while (wrapped_size && sz > req_output_size);
+ if (wrapped_size == 0)
+ return 0;
+
+ /* inner header */
+ if (wrapped_size < 16)
+ return 0;
+
+ wrapped_size -= 16;
+
+ *max_input_size = wrapped_size;
+ } else {
+ krb5_cksumtype type;
+ size_t cksumsize;
+
+ ret = krb5_crypto_get_checksum_type(context, ctx->crypto, &type);
+ if (ret)
+ return ret;
+
+ ret = krb5_checksumsize(context, type, &cksumsize);
+ if (ret)
+ return ret;
+
+ if (req_output_size < cksumsize)
+ return 0;
+
+ /* Checksum is concatenated with data */
+ *max_input_size = req_output_size - cksumsize;
+ }
+
+ return 0;
+}
+
+/*
+ * Rotate "rrc" bytes to the front or back
+ */
+
+static krb5_error_code
+rrc_rotate(void *data, size_t len, uint16_t rrc, krb5_boolean unrotate)
+{
+ u_char *tmp, buf[256];
+ size_t left;
+
+ if (len == 0)
+ return 0;
+
+ rrc %= len;
+
+ if (rrc == 0)
+ return 0;
+
+ left = len - rrc;
+
+ if (rrc <= sizeof(buf)) {
+ tmp = buf;
+ } else {
+ tmp = malloc(rrc);
+ if (tmp == NULL)
+ return ENOMEM;
+ }
+
+ if (unrotate) {
+ memcpy(tmp, data, rrc);
+ memmove(data, (u_char *)data + rrc, left);
+ memcpy((u_char *)data + left, tmp, rrc);
+ } else {
+ memcpy(tmp, (u_char *)data + left, rrc);
+ memmove((u_char *)data + rrc, data, left);
+ memcpy(data, tmp, rrc);
+ }
+
+ if (rrc > sizeof(buf))
+ free(tmp);
+
+ return 0;
+}
+
+gss_iov_buffer_desc *
+_gk_find_buffer(gss_iov_buffer_desc *iov, int iov_count, OM_uint32 type)
+{
+ int i;
+ gss_iov_buffer_t iovp = GSS_C_NO_IOV_BUFFER;
+
+ if (iov == GSS_C_NO_IOV_BUFFER)
+ return GSS_C_NO_IOV_BUFFER;
+
+ /*
+ * This function is used to find header, padding or trailer buffers
+ * which are singletons; return NULL if multiple instances are found.
+ */
+ for (i = 0; i < iov_count; i++) {
+ if (type == GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+ if (iovp == GSS_C_NO_IOV_BUFFER)
+ iovp = &iov[i];
+ else
+ return GSS_C_NO_IOV_BUFFER;
+ }
+ }
+
+ /*
+ * For compatibility with SSPI, an empty padding buffer is treated
+ * equivalent to an absent padding buffer (unless the caller is
+ * requesting that a padding buffer be allocated).
+ */
+ if (iovp &&
+ iovp->buffer.length == 0 &&
+ type == GSS_IOV_BUFFER_TYPE_PADDING &&
+ (GSS_IOV_BUFFER_FLAGS(iovp->type) & GSS_IOV_BUFFER_FLAG_ALLOCATE) == 0)
+ iovp = NULL;
+
+ return iovp;
+}
+
+OM_uint32
+_gk_allocate_buffer(OM_uint32 *minor_status, gss_iov_buffer_desc *buffer, size_t size)
+{
+ if (buffer->type & GSS_IOV_BUFFER_FLAG_ALLOCATED) {
+ if (buffer->buffer.length == size)
+ return GSS_S_COMPLETE;
+ free(buffer->buffer.value);
+ }
+
+ buffer->buffer.value = malloc(size);
+ buffer->buffer.length = size;
+ if (buffer->buffer.value == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ buffer->type |= GSS_IOV_BUFFER_FLAG_ALLOCATED;
+
+ return GSS_S_COMPLETE;
+}
+
+
+OM_uint32
+_gk_verify_buffers(OM_uint32 *minor_status,
+ const gsskrb5_ctx ctx,
+ const gss_iov_buffer_desc *header,
+ const gss_iov_buffer_desc *padding,
+ const gss_iov_buffer_desc *trailer,
+ int block_cipher)
+{
+ if (header == NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ if (IS_DCE_STYLE(ctx)) {
+ /*
+ * In DCE style mode we reject having a padding or trailer buffer
+ */
+ if (padding) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ if (trailer) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ } else {
+ /*
+ * In non-DCE style mode we require having a padding buffer for
+ * encryption types that do not behave as stream ciphers. This
+ * check is superfluous for now, as only RC4 and RFC4121 enctypes
+ * are presently implemented for the IOV APIs; be defensive.
+ */
+ if (block_cipher && padding == NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ }
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_gssapi_wrap_cfx_iov(OM_uint32 *minor_status,
+ gsskrb5_ctx ctx,
+ krb5_context context,
+ int conf_req_flag,
+ int *conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ OM_uint32 major_status, junk;
+ gss_iov_buffer_desc *header, *trailer, *padding;
+ size_t gsshsize, k5hsize;
+ size_t gsstsize, k5tsize;
+ size_t rrc = 0, ec = 0;
+ int i;
+ gss_cfx_wrap_token token;
+ krb5_error_code ret;
+ int32_t seq_number;
+ unsigned usage;
+ krb5_crypto_iov *data = NULL;
+
+ header = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER);
+ if (header == NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ padding = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_PADDING);
+ if (padding != NULL) {
+ padding->buffer.length = 0;
+ }
+
+ trailer = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER);
+
+ major_status = _gk_verify_buffers(minor_status, ctx, header,
+ padding, trailer, FALSE);
+ if (major_status != GSS_S_COMPLETE) {
+ return major_status;
+ }
+
+ if (conf_req_flag) {
+ size_t k5psize = 0;
+ size_t k5pbase = 0;
+ size_t k5bsize = 0;
+ size_t size = 0;
+
+ for (i = 0; i < iov_count; i++) {
+ switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ size += iov[i].buffer.length;
+ break;
+ default:
+ break;
+ }
+ }
+
+ size += sizeof(gss_cfx_wrap_token_desc);
+
+ *minor_status = krb5_crypto_length(context, ctx->crypto,
+ KRB5_CRYPTO_TYPE_HEADER,
+ &k5hsize);
+ if (*minor_status)
+ return GSS_S_FAILURE;
+
+ *minor_status = krb5_crypto_length(context, ctx->crypto,
+ KRB5_CRYPTO_TYPE_TRAILER,
+ &k5tsize);
+ if (*minor_status)
+ return GSS_S_FAILURE;
+
+ *minor_status = krb5_crypto_length(context, ctx->crypto,
+ KRB5_CRYPTO_TYPE_PADDING,
+ &k5pbase);
+ if (*minor_status)
+ return GSS_S_FAILURE;
+
+ if (k5pbase > 1) {
+ k5psize = k5pbase - (size % k5pbase);
+ } else {
+ k5psize = 0;
+ }
+
+ if (k5psize == 0 && IS_DCE_STYLE(ctx)) {
+ *minor_status = krb5_crypto_getblocksize(context, ctx->crypto,
+ &k5bsize);
+ if (*minor_status)
+ return GSS_S_FAILURE;
+ ec = k5bsize;
+ } else {
+ ec = k5psize;
+ }
+
+ gsshsize = sizeof(gss_cfx_wrap_token_desc) + k5hsize;
+ gsstsize = sizeof(gss_cfx_wrap_token_desc) + ec + k5tsize;
+ } else {
+ if (IS_DCE_STYLE(ctx)) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ k5hsize = 0;
+ *minor_status = krb5_crypto_length(context, ctx->crypto,
+ KRB5_CRYPTO_TYPE_CHECKSUM,
+ &k5tsize);
+ if (*minor_status)
+ return GSS_S_FAILURE;
+
+ gsshsize = sizeof(gss_cfx_wrap_token_desc);
+ gsstsize = k5tsize;
+ }
+
+ /*
+ *
+ */
+
+ if (trailer == NULL) {
+ rrc = gsstsize;
+ if (IS_DCE_STYLE(ctx))
+ rrc -= ec;
+ gsshsize += gsstsize;
+ } else if (GSS_IOV_BUFFER_FLAGS(trailer->type) & GSS_IOV_BUFFER_FLAG_ALLOCATE) {
+ major_status = _gk_allocate_buffer(minor_status, trailer, gsstsize);
+ if (major_status)
+ goto failure;
+ } else if (trailer->buffer.length < gsstsize) {
+ *minor_status = KRB5_BAD_MSIZE;
+ major_status = GSS_S_FAILURE;
+ goto failure;
+ } else
+ trailer->buffer.length = gsstsize;
+
+ /*
+ *
+ */
+
+ if (GSS_IOV_BUFFER_FLAGS(header->type) & GSS_IOV_BUFFER_FLAG_ALLOCATE) {
+ major_status = _gk_allocate_buffer(minor_status, header, gsshsize);
+ if (major_status != GSS_S_COMPLETE)
+ goto failure;
+ } else if (header->buffer.length < gsshsize) {
+ *minor_status = KRB5_BAD_MSIZE;
+ major_status = GSS_S_FAILURE;
+ goto failure;
+ } else
+ header->buffer.length = gsshsize;
+
+ token = (gss_cfx_wrap_token)header->buffer.value;
+
+ token->TOK_ID[0] = 0x05;
+ token->TOK_ID[1] = 0x04;
+ token->Flags = 0;
+ token->Filler = 0xFF;
+
+ if ((ctx->more_flags & LOCAL) == 0)
+ token->Flags |= CFXSentByAcceptor;
+
+ if (ctx->more_flags & ACCEPTOR_SUBKEY)
+ token->Flags |= CFXAcceptorSubkey;
+
+ if (ctx->more_flags & LOCAL)
+ usage = KRB5_KU_USAGE_INITIATOR_SEAL;
+ else
+ usage = KRB5_KU_USAGE_ACCEPTOR_SEAL;
+
+ if (conf_req_flag) {
+ /*
+ * In Wrap tokens with confidentiality, the EC field is
+ * used to encode the size (in bytes) of the random filler.
+ */
+ token->Flags |= CFXSealed;
+ token->EC[0] = (ec >> 8) & 0xFF;
+ token->EC[1] = (ec >> 0) & 0xFF;
+
+ } else {
+ /*
+ * In Wrap tokens without confidentiality, the EC field is
+ * used to encode the size (in bytes) of the trailing
+ * checksum.
+ *
+ * This is not used in the checksum calcuation itself,
+ * because the checksum length could potentially vary
+ * depending on the data length.
+ */
+ token->EC[0] = 0;
+ token->EC[1] = 0;
+ }
+
+ /*
+ * In Wrap tokens that provide for confidentiality, the RRC
+ * field in the header contains the hex value 00 00 before
+ * encryption.
+ *
+ * In Wrap tokens that do not provide for confidentiality,
+ * both the EC and RRC fields in the appended checksum
+ * contain the hex value 00 00 for the purpose of calculating
+ * the checksum.
+ */
+ token->RRC[0] = 0;
+ token->RRC[1] = 0;
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ krb5_auth_con_getlocalseqnumber(context,
+ ctx->auth_context,
+ &seq_number);
+ _gsskrb5_encode_be_om_uint32(0, &token->SND_SEQ[0]);
+ _gsskrb5_encode_be_om_uint32(seq_number, &token->SND_SEQ[4]);
+ krb5_auth_con_setlocalseqnumber(context,
+ ctx->auth_context,
+ ++seq_number);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ data = calloc(iov_count + 3, sizeof(data[0]));
+ if (data == NULL) {
+ *minor_status = ENOMEM;
+ major_status = GSS_S_FAILURE;
+ goto failure;
+ }
+
+ if (conf_req_flag) {
+ /*
+ plain packet:
+
+ {"header" | encrypt(plaintext-data | ec-padding | E"header")}
+
+ Expanded, this is with with RRC = 0:
+
+ {"header" | krb5-header | plaintext-data | ec-padding | E"header" | krb5-trailer }
+
+ In DCE-RPC mode == no trailer: RRC = gss "trailer" == length(ec-padding | E"header" | krb5-trailer)
+
+ {"header" | ec-padding | E"header" | krb5-trailer | krb5-header | plaintext-data }
+ */
+
+ i = 0;
+ data[i].flags = KRB5_CRYPTO_TYPE_HEADER;
+ data[i].data.data = ((uint8_t *)header->buffer.value) + header->buffer.length - k5hsize;
+ data[i].data.length = k5hsize;
+
+ for (i = 1; i < iov_count + 1; i++) {
+ switch (GSS_IOV_BUFFER_TYPE(iov[i - 1].type)) {
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ data[i].flags = KRB5_CRYPTO_TYPE_DATA;
+ break;
+ case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+ data[i].flags = KRB5_CRYPTO_TYPE_SIGN_ONLY;
+ break;
+ default:
+ data[i].flags = KRB5_CRYPTO_TYPE_EMPTY;
+ break;
+ }
+ data[i].data.length = iov[i - 1].buffer.length;
+ data[i].data.data = iov[i - 1].buffer.value;
+ }
+
+ /*
+ * Any necessary padding is added here to ensure that the
+ * encrypted token header is always at the end of the
+ * ciphertext.
+ */
+
+ /* encrypted CFX header in trailer (or after the header if in
+ DCE mode). Copy in header into E"header"
+ */
+ data[i].flags = KRB5_CRYPTO_TYPE_DATA;
+ if (trailer)
+ data[i].data.data = trailer->buffer.value;
+ else
+ data[i].data.data = ((uint8_t *)header->buffer.value) + sizeof(*token);
+
+ data[i].data.length = ec + sizeof(*token);
+ memset(data[i].data.data, 0xFF, ec);
+ memcpy(((uint8_t *)data[i].data.data) + ec, token, sizeof(*token));
+ i++;
+
+ /* Kerberos trailer comes after the gss trailer */
+ data[i].flags = KRB5_CRYPTO_TYPE_TRAILER;
+ data[i].data.data = ((uint8_t *)data[i-1].data.data) + ec + sizeof(*token);
+ data[i].data.length = k5tsize;
+ i++;
+
+ ret = krb5_encrypt_iov_ivec(context, ctx->crypto, usage, data, i, NULL);
+ if (ret != 0) {
+ *minor_status = ret;
+ major_status = GSS_S_FAILURE;
+ goto failure;
+ }
+
+ if (rrc) {
+ token->RRC[0] = (rrc >> 8) & 0xFF;
+ token->RRC[1] = (rrc >> 0) & 0xFF;
+ }
+
+ } else {
+ /*
+ plain packet:
+
+ {data | "header" | gss-trailer (krb5 checksum)
+
+ don't do RRC != 0
+
+ */
+
+ for (i = 0; i < iov_count; i++) {
+ switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ data[i].flags = KRB5_CRYPTO_TYPE_DATA;
+ break;
+ case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+ data[i].flags = KRB5_CRYPTO_TYPE_SIGN_ONLY;
+ break;
+ default:
+ data[i].flags = KRB5_CRYPTO_TYPE_EMPTY;
+ break;
+ }
+ data[i].data.length = iov[i].buffer.length;
+ data[i].data.data = iov[i].buffer.value;
+ }
+
+ data[i].flags = KRB5_CRYPTO_TYPE_DATA;
+ data[i].data.data = header->buffer.value;
+ data[i].data.length = sizeof(gss_cfx_wrap_token_desc);
+ i++;
+
+ data[i].flags = KRB5_CRYPTO_TYPE_CHECKSUM;
+ if (trailer) {
+ data[i].data.data = trailer->buffer.value;
+ } else {
+ data[i].data.data = (uint8_t *)header->buffer.value +
+ sizeof(gss_cfx_wrap_token_desc);
+ }
+ data[i].data.length = k5tsize;
+ i++;
+
+ ret = krb5_create_checksum_iov(context, ctx->crypto, usage, data, i, NULL);
+ if (ret) {
+ *minor_status = ret;
+ major_status = GSS_S_FAILURE;
+ goto failure;
+ }
+
+ if (rrc) {
+ token->RRC[0] = (rrc >> 8) & 0xFF;
+ token->RRC[1] = (rrc >> 0) & 0xFF;
+ }
+
+ token->EC[0] = (k5tsize >> 8) & 0xFF;
+ token->EC[1] = (k5tsize >> 0) & 0xFF;
+ }
+
+ if (conf_state != NULL)
+ *conf_state = conf_req_flag;
+
+ free(data);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+
+ failure:
+ if (data)
+ free(data);
+
+ gss_release_iov_buffer(&junk, iov, iov_count);
+
+ return major_status;
+}
+
+/* This is slowpath */
+static OM_uint32
+unrotate_iov(OM_uint32 *minor_status, size_t rrc, gss_iov_buffer_desc *iov, int iov_count)
+{
+ uint8_t *p, *q;
+ size_t len = 0, skip;
+ int i;
+
+ for (i = 0; i < iov_count; i++)
+ if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_DATA ||
+ GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_PADDING ||
+ GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_TRAILER)
+ len += iov[i].buffer.length;
+
+ p = malloc(len);
+ if (p == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ q = p;
+
+ /* copy up */
+
+ for (i = 0; i < iov_count; i++) {
+ if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_DATA ||
+ GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_PADDING ||
+ GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_TRAILER)
+ {
+ memcpy(q, iov[i].buffer.value, iov[i].buffer.length);
+ q += iov[i].buffer.length;
+ }
+ }
+ assert((size_t)(q - p) == len);
+
+ /* unrotate first part */
+ q = p + rrc;
+ skip = rrc;
+ for (i = 0; i < iov_count; i++) {
+ if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_DATA ||
+ GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_PADDING ||
+ GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_TRAILER)
+ {
+ if (iov[i].buffer.length <= skip) {
+ skip -= iov[i].buffer.length;
+ } else {
+ /* copy back to original buffer */
+ memcpy(((uint8_t *)iov[i].buffer.value) + skip, q, iov[i].buffer.length - skip);
+ q += iov[i].buffer.length - skip;
+ skip = 0;
+ }
+ }
+ }
+ /* copy trailer */
+ q = p;
+ skip = rrc;
+ for (i = 0; i < iov_count; i++) {
+ if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_DATA ||
+ GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_PADDING ||
+ GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_TRAILER)
+ {
+ memcpy(iov[i].buffer.value, q, min(iov[i].buffer.length, skip));
+ if (iov[i].buffer.length > skip)
+ break;
+ skip -= iov[i].buffer.length;
+ q += iov[i].buffer.length;
+ }
+ }
+ free(p);
+ return GSS_S_COMPLETE;
+}
+
+
+OM_uint32
+_gssapi_unwrap_cfx_iov(OM_uint32 *minor_status,
+ gsskrb5_ctx ctx,
+ krb5_context context,
+ int *conf_state,
+ gss_qop_t *qop_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ OM_uint32 seq_number_lo, seq_number_hi, major_status, junk;
+ gss_iov_buffer_desc *header, *trailer, *padding;
+ gss_cfx_wrap_token token, ttoken;
+ u_char token_flags;
+ krb5_error_code ret;
+ unsigned usage;
+ uint16_t ec, rrc;
+ krb5_crypto_iov *data = NULL;
+ int i, j;
+
+ *minor_status = 0;
+
+ header = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER);
+ if (header == NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ if (header->buffer.length < sizeof(*token)) /* we check exact below */
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ padding = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_PADDING);
+ if (padding != NULL && padding->buffer.length != 0) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ trailer = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER);
+
+ major_status = _gk_verify_buffers(minor_status, ctx, header,
+ padding, trailer, FALSE);
+ if (major_status != GSS_S_COMPLETE) {
+ return major_status;
+ }
+
+ token = (gss_cfx_wrap_token)header->buffer.value;
+
+ if (token->TOK_ID[0] != 0x05 || token->TOK_ID[1] != 0x04)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ /* Ignore unknown flags */
+ token_flags = token->Flags &
+ (CFXSentByAcceptor | CFXSealed | CFXAcceptorSubkey);
+
+ if (token_flags & CFXSentByAcceptor) {
+ if ((ctx->more_flags & LOCAL) == 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ if (ctx->more_flags & ACCEPTOR_SUBKEY) {
+ if ((token_flags & CFXAcceptorSubkey) == 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+ } else {
+ if (token_flags & CFXAcceptorSubkey)
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ if (token->Filler != 0xFF)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ if (conf_state != NULL)
+ *conf_state = (token_flags & CFXSealed) ? 1 : 0;
+
+ ec = (token->EC[0] << 8) | token->EC[1];
+ rrc = (token->RRC[0] << 8) | token->RRC[1];
+
+ /*
+ * Check sequence number
+ */
+ _gsskrb5_decode_be_om_uint32(&token->SND_SEQ[0], &seq_number_hi);
+ _gsskrb5_decode_be_om_uint32(&token->SND_SEQ[4], &seq_number_lo);
+ if (seq_number_hi) {
+ /* no support for 64-bit sequence numbers */
+ *minor_status = ERANGE;
+ return GSS_S_UNSEQ_TOKEN;
+ }
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ ret = _gssapi_msg_order_check(ctx->order, seq_number_lo);
+ if (ret != 0) {
+ *minor_status = 0;
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ return ret;
+ }
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ /*
+ * Decrypt and/or verify checksum
+ */
+
+ if (ctx->more_flags & LOCAL) {
+ usage = KRB5_KU_USAGE_ACCEPTOR_SEAL;
+ } else {
+ usage = KRB5_KU_USAGE_INITIATOR_SEAL;
+ }
+
+ data = calloc(iov_count + 3, sizeof(data[0]));
+ if (data == NULL) {
+ *minor_status = ENOMEM;
+ major_status = GSS_S_FAILURE;
+ goto failure;
+ }
+
+ if (token_flags & CFXSealed) {
+ size_t k5tsize, k5hsize;
+
+ krb5_crypto_length(context, ctx->crypto, KRB5_CRYPTO_TYPE_HEADER, &k5hsize);
+ krb5_crypto_length(context, ctx->crypto, KRB5_CRYPTO_TYPE_TRAILER, &k5tsize);
+
+ /* Rotate by RRC; bogus to do this in-place XXX */
+ /* Check RRC */
+
+ if (trailer == NULL) {
+ size_t gsstsize = k5tsize + sizeof(*token);
+ size_t gsshsize = k5hsize + sizeof(*token);
+
+ if (rrc != gsstsize) {
+ major_status = GSS_S_DEFECTIVE_TOKEN;
+ goto failure;
+ }
+
+ if (IS_DCE_STYLE(ctx))
+ gsstsize += ec;
+
+ gsshsize += gsstsize;
+
+ if (header->buffer.length != gsshsize) {
+ major_status = GSS_S_DEFECTIVE_TOKEN;
+ goto failure;
+ }
+ } else if (trailer->buffer.length != sizeof(*token) + k5tsize) {
+ major_status = GSS_S_DEFECTIVE_TOKEN;
+ goto failure;
+ } else if (header->buffer.length != sizeof(*token) + k5hsize) {
+ major_status = GSS_S_DEFECTIVE_TOKEN;
+ goto failure;
+ } else if (rrc != 0) {
+ /* go though slowpath */
+ major_status = unrotate_iov(minor_status, rrc, iov, iov_count);
+ if (major_status)
+ goto failure;
+ }
+
+ i = 0;
+ data[i].flags = KRB5_CRYPTO_TYPE_HEADER;
+ data[i].data.data = ((uint8_t *)header->buffer.value) + header->buffer.length - k5hsize;
+ data[i].data.length = k5hsize;
+ i++;
+
+ for (j = 0; j < iov_count; i++, j++) {
+ switch (GSS_IOV_BUFFER_TYPE(iov[j].type)) {
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ data[i].flags = KRB5_CRYPTO_TYPE_DATA;
+ break;
+ case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+ data[i].flags = KRB5_CRYPTO_TYPE_SIGN_ONLY;
+ break;
+ default:
+ data[i].flags = KRB5_CRYPTO_TYPE_EMPTY;
+ break;
+ }
+ data[i].data.length = iov[j].buffer.length;
+ data[i].data.data = iov[j].buffer.value;
+ }
+
+ /* encrypted CFX header in trailer (or after the header if in
+ DCE mode). Copy in header into E"header"
+ */
+ data[i].flags = KRB5_CRYPTO_TYPE_DATA;
+ if (trailer) {
+ data[i].data.data = trailer->buffer.value;
+ } else {
+ data[i].data.data = ((uint8_t *)header->buffer.value) +
+ header->buffer.length - k5hsize - k5tsize - ec- sizeof(*token);
+ }
+
+ data[i].data.length = ec + sizeof(*token);
+ ttoken = (gss_cfx_wrap_token)(((uint8_t *)data[i].data.data) + ec);
+ i++;
+
+ /* Kerberos trailer comes after the gss trailer */
+ data[i].flags = KRB5_CRYPTO_TYPE_TRAILER;
+ data[i].data.data = ((uint8_t *)data[i-1].data.data) + ec + sizeof(*token);
+ data[i].data.length = k5tsize;
+ i++;
+
+ ret = krb5_decrypt_iov_ivec(context, ctx->crypto, usage, data, i, NULL);
+ if (ret != 0) {
+ *minor_status = ret;
+ major_status = GSS_S_FAILURE;
+ goto failure;
+ }
+
+ ttoken->RRC[0] = token->RRC[0];
+ ttoken->RRC[1] = token->RRC[1];
+
+ /* Check the integrity of the header */
+ if (ct_memcmp(ttoken, token, sizeof(*token)) != 0) {
+ major_status = GSS_S_BAD_MIC;
+ goto failure;
+ }
+ } else {
+ size_t gsstsize = ec;
+ size_t gsshsize = sizeof(*token);
+
+ if (trailer == NULL) {
+ /* Check RRC */
+ if (rrc != gsstsize) {
+ *minor_status = EINVAL;
+ major_status = GSS_S_FAILURE;
+ goto failure;
+ }
+
+ gsshsize += gsstsize;
+ } else if (trailer->buffer.length != gsstsize) {
+ major_status = GSS_S_DEFECTIVE_TOKEN;
+ goto failure;
+ } else if (rrc != 0) {
+ /* Check RRC */
+ *minor_status = EINVAL;
+ major_status = GSS_S_FAILURE;
+ goto failure;
+ }
+
+ if (header->buffer.length != gsshsize) {
+ major_status = GSS_S_DEFECTIVE_TOKEN;
+ goto failure;
+ }
+
+ for (i = 0; i < iov_count; i++) {
+ switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ data[i].flags = KRB5_CRYPTO_TYPE_DATA;
+ break;
+ case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+ data[i].flags = KRB5_CRYPTO_TYPE_SIGN_ONLY;
+ break;
+ default:
+ data[i].flags = KRB5_CRYPTO_TYPE_EMPTY;
+ break;
+ }
+ data[i].data.length = iov[i].buffer.length;
+ data[i].data.data = iov[i].buffer.value;
+ }
+
+ data[i].flags = KRB5_CRYPTO_TYPE_DATA;
+ data[i].data.data = header->buffer.value;
+ data[i].data.length = sizeof(*token);
+ i++;
+
+ data[i].flags = KRB5_CRYPTO_TYPE_CHECKSUM;
+ if (trailer) {
+ data[i].data.data = trailer->buffer.value;
+ } else {
+ data[i].data.data = (uint8_t *)header->buffer.value +
+ sizeof(*token);
+ }
+ data[i].data.length = ec;
+ i++;
+
+ token = (gss_cfx_wrap_token)header->buffer.value;
+ token->EC[0] = 0;
+ token->EC[1] = 0;
+ token->RRC[0] = 0;
+ token->RRC[1] = 0;
+
+ ret = krb5_verify_checksum_iov(context, ctx->crypto, usage, data, i, NULL);
+ if (ret) {
+ *minor_status = ret;
+ major_status = GSS_S_FAILURE;
+ goto failure;
+ }
+ }
+
+ if (qop_state != NULL) {
+ *qop_state = GSS_C_QOP_DEFAULT;
+ }
+
+ free(data);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+
+ failure:
+ if (data)
+ free(data);
+
+ gss_release_iov_buffer(&junk, iov, iov_count);
+
+ return major_status;
+}
+
+OM_uint32
+_gssapi_wrap_iov_length_cfx(OM_uint32 *minor_status,
+ gsskrb5_ctx ctx,
+ krb5_context context,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ int *conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ OM_uint32 major_status;
+ size_t size;
+ int i;
+ gss_iov_buffer_desc *header = NULL;
+ gss_iov_buffer_desc *padding = NULL;
+ gss_iov_buffer_desc *trailer = NULL;
+ size_t gsshsize = 0;
+ size_t gsstsize = 0;
+ size_t k5hsize = 0;
+ size_t k5tsize = 0;
+
+ GSSAPI_KRB5_INIT (&context);
+ *minor_status = 0;
+
+ for (size = 0, i = 0; i < iov_count; i++) {
+ switch(GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+ case GSS_IOV_BUFFER_TYPE_EMPTY:
+ break;
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ size += iov[i].buffer.length;
+ break;
+ case GSS_IOV_BUFFER_TYPE_HEADER:
+ if (header != NULL) {
+ *minor_status = 0;
+ return GSS_S_FAILURE;
+ }
+ header = &iov[i];
+ break;
+ case GSS_IOV_BUFFER_TYPE_TRAILER:
+ if (trailer != NULL) {
+ *minor_status = 0;
+ return GSS_S_FAILURE;
+ }
+ trailer = &iov[i];
+ break;
+ case GSS_IOV_BUFFER_TYPE_PADDING:
+ if (padding != NULL) {
+ *minor_status = 0;
+ return GSS_S_FAILURE;
+ }
+ padding = &iov[i];
+ break;
+ case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+ break;
+ default:
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ }
+
+ major_status = _gk_verify_buffers(minor_status, ctx, header,
+ padding, trailer, FALSE);
+ if (major_status != GSS_S_COMPLETE) {
+ return major_status;
+ }
+
+ if (conf_req_flag) {
+ size_t k5psize = 0;
+ size_t k5pbase = 0;
+ size_t k5bsize = 0;
+ size_t ec = 0;
+
+ size += sizeof(gss_cfx_wrap_token_desc);
+
+ *minor_status = krb5_crypto_length(context, ctx->crypto,
+ KRB5_CRYPTO_TYPE_HEADER,
+ &k5hsize);
+ if (*minor_status)
+ return GSS_S_FAILURE;
+
+ *minor_status = krb5_crypto_length(context, ctx->crypto,
+ KRB5_CRYPTO_TYPE_TRAILER,
+ &k5tsize);
+ if (*minor_status)
+ return GSS_S_FAILURE;
+
+ *minor_status = krb5_crypto_length(context, ctx->crypto,
+ KRB5_CRYPTO_TYPE_PADDING,
+ &k5pbase);
+ if (*minor_status)
+ return GSS_S_FAILURE;
+
+ if (k5pbase > 1) {
+ k5psize = k5pbase - (size % k5pbase);
+ } else {
+ k5psize = 0;
+ }
+
+ if (k5psize == 0 && IS_DCE_STYLE(ctx)) {
+ *minor_status = krb5_crypto_getblocksize(context, ctx->crypto,
+ &k5bsize);
+ if (*minor_status)
+ return GSS_S_FAILURE;
+
+ ec = k5bsize;
+ } else {
+ ec = k5psize;
+ }
+
+ gsshsize = sizeof(gss_cfx_wrap_token_desc) + k5hsize;
+ gsstsize = sizeof(gss_cfx_wrap_token_desc) + ec + k5tsize;
+ } else {
+ *minor_status = krb5_crypto_length(context, ctx->crypto,
+ KRB5_CRYPTO_TYPE_CHECKSUM,
+ &k5tsize);
+ if (*minor_status)
+ return GSS_S_FAILURE;
+
+ gsshsize = sizeof(gss_cfx_wrap_token_desc);
+ gsstsize = k5tsize;
+ }
+
+ if (trailer != NULL) {
+ trailer->buffer.length = gsstsize;
+ } else {
+ gsshsize += gsstsize;
+ }
+
+ header->buffer.length = gsshsize;
+
+ if (padding) {
+ /* padding is done via EC and is contained in the header or trailer */
+ padding->buffer.length = 0;
+ }
+
+ if (conf_state) {
+ *conf_state = conf_req_flag;
+ }
+
+ return GSS_S_COMPLETE;
+}
+
+
+
+
+OM_uint32 _gssapi_wrap_cfx(OM_uint32 *minor_status,
+ const gsskrb5_ctx ctx,
+ krb5_context context,
+ int conf_req_flag,
+ const gss_buffer_t input_message_buffer,
+ int *conf_state,
+ gss_buffer_t output_message_buffer)
+{
+ gss_cfx_wrap_token token;
+ krb5_error_code ret;
+ unsigned usage;
+ krb5_data cipher;
+ size_t wrapped_len, cksumsize;
+ uint16_t padlength, rrc = 0;
+ int32_t seq_number;
+ u_char *p;
+
+ ret = _gsskrb5cfx_wrap_length_cfx(context,
+ ctx->crypto, conf_req_flag,
+ IS_DCE_STYLE(ctx),
+ input_message_buffer->length,
+ &wrapped_len, &cksumsize, &padlength);
+ if (ret != 0) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ /* Always rotate encrypted token (if any) and checksum to header */
+ rrc = (conf_req_flag ? sizeof(*token) : 0) + (uint16_t)cksumsize;
+
+ output_message_buffer->length = wrapped_len;
+ output_message_buffer->value = malloc(output_message_buffer->length);
+ if (output_message_buffer->value == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ p = output_message_buffer->value;
+ token = (gss_cfx_wrap_token)p;
+ token->TOK_ID[0] = 0x05;
+ token->TOK_ID[1] = 0x04;
+ token->Flags = 0;
+ token->Filler = 0xFF;
+ if ((ctx->more_flags & LOCAL) == 0)
+ token->Flags |= CFXSentByAcceptor;
+ if (ctx->more_flags & ACCEPTOR_SUBKEY)
+ token->Flags |= CFXAcceptorSubkey;
+ if (conf_req_flag) {
+ /*
+ * In Wrap tokens with confidentiality, the EC field is
+ * used to encode the size (in bytes) of the random filler.
+ */
+ token->Flags |= CFXSealed;
+ token->EC[0] = (padlength >> 8) & 0xFF;
+ token->EC[1] = (padlength >> 0) & 0xFF;
+ } else {
+ /*
+ * In Wrap tokens without confidentiality, the EC field is
+ * used to encode the size (in bytes) of the trailing
+ * checksum.
+ *
+ * This is not used in the checksum calcuation itself,
+ * because the checksum length could potentially vary
+ * depending on the data length.
+ */
+ token->EC[0] = 0;
+ token->EC[1] = 0;
+ }
+
+ /*
+ * In Wrap tokens that provide for confidentiality, the RRC
+ * field in the header contains the hex value 00 00 before
+ * encryption.
+ *
+ * In Wrap tokens that do not provide for confidentiality,
+ * both the EC and RRC fields in the appended checksum
+ * contain the hex value 00 00 for the purpose of calculating
+ * the checksum.
+ */
+ token->RRC[0] = 0;
+ token->RRC[1] = 0;
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ krb5_auth_con_getlocalseqnumber(context,
+ ctx->auth_context,
+ &seq_number);
+ _gsskrb5_encode_be_om_uint32(0, &token->SND_SEQ[0]);
+ _gsskrb5_encode_be_om_uint32(seq_number, &token->SND_SEQ[4]);
+ krb5_auth_con_setlocalseqnumber(context,
+ ctx->auth_context,
+ ++seq_number);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ /*
+ * If confidentiality is requested, the token header is
+ * appended to the plaintext before encryption; the resulting
+ * token is {"header" | encrypt(plaintext | pad | "header")}.
+ *
+ * If no confidentiality is requested, the checksum is
+ * calculated over the plaintext concatenated with the
+ * token header.
+ */
+ if (ctx->more_flags & LOCAL) {
+ usage = KRB5_KU_USAGE_INITIATOR_SEAL;
+ } else {
+ usage = KRB5_KU_USAGE_ACCEPTOR_SEAL;
+ }
+
+ if (conf_req_flag) {
+ /*
+ * Any necessary padding is added here to ensure that the
+ * encrypted token header is always at the end of the
+ * ciphertext.
+ *
+ * The specification does not require that the padding
+ * bytes are initialized.
+ */
+ p += sizeof(*token);
+ memcpy(p, input_message_buffer->value, input_message_buffer->length);
+ memset(p + input_message_buffer->length, 0xFF, padlength);
+ memcpy(p + input_message_buffer->length + padlength,
+ token, sizeof(*token));
+
+ ret = krb5_encrypt(context, ctx->crypto,
+ usage, p,
+ input_message_buffer->length + padlength +
+ sizeof(*token),
+ &cipher);
+ if (ret != 0) {
+ *minor_status = ret;
+ _gsskrb5_release_buffer(minor_status, output_message_buffer);
+ return GSS_S_FAILURE;
+ }
+ assert(sizeof(*token) + cipher.length == wrapped_len);
+ token->RRC[0] = (rrc >> 8) & 0xFF;
+ token->RRC[1] = (rrc >> 0) & 0xFF;
+
+ /*
+ * this is really ugly, but needed against windows
+ * for DCERPC, as windows rotates by EC+RRC.
+ */
+ if (IS_DCE_STYLE(ctx)) {
+ ret = rrc_rotate(cipher.data, cipher.length, rrc+padlength, FALSE);
+ } else {
+ ret = rrc_rotate(cipher.data, cipher.length, rrc, FALSE);
+ }
+ if (ret != 0) {
+ *minor_status = ret;
+ _gsskrb5_release_buffer(minor_status, output_message_buffer);
+ return GSS_S_FAILURE;
+ }
+ memcpy(p, cipher.data, cipher.length);
+ krb5_data_free(&cipher);
+ } else {
+ char *buf;
+ Checksum cksum;
+
+ buf = malloc(input_message_buffer->length + sizeof(*token));
+ if (buf == NULL) {
+ *minor_status = ENOMEM;
+ _gsskrb5_release_buffer(minor_status, output_message_buffer);
+ return GSS_S_FAILURE;
+ }
+ memcpy(buf, input_message_buffer->value, input_message_buffer->length);
+ memcpy(buf + input_message_buffer->length, token, sizeof(*token));
+
+ ret = krb5_create_checksum(context, ctx->crypto,
+ usage, 0, buf,
+ input_message_buffer->length +
+ sizeof(*token),
+ &cksum);
+ if (ret != 0) {
+ *minor_status = ret;
+ _gsskrb5_release_buffer(minor_status, output_message_buffer);
+ free(buf);
+ return GSS_S_FAILURE;
+ }
+
+ free(buf);
+
+ assert(cksum.checksum.length == cksumsize);
+ token->EC[0] = (cksum.checksum.length >> 8) & 0xFF;
+ token->EC[1] = (cksum.checksum.length >> 0) & 0xFF;
+ token->RRC[0] = (rrc >> 8) & 0xFF;
+ token->RRC[1] = (rrc >> 0) & 0xFF;
+
+ p += sizeof(*token);
+ memcpy(p, input_message_buffer->value, input_message_buffer->length);
+ memcpy(p + input_message_buffer->length,
+ cksum.checksum.data, cksum.checksum.length);
+
+ ret = rrc_rotate(p,
+ input_message_buffer->length + cksum.checksum.length, rrc, FALSE);
+ if (ret != 0) {
+ *minor_status = ret;
+ _gsskrb5_release_buffer(minor_status, output_message_buffer);
+ free_Checksum(&cksum);
+ return GSS_S_FAILURE;
+ }
+ free_Checksum(&cksum);
+ }
+
+ if (conf_state != NULL) {
+ *conf_state = conf_req_flag;
+ }
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 _gssapi_unwrap_cfx(OM_uint32 *minor_status,
+ const gsskrb5_ctx ctx,
+ krb5_context context,
+ const gss_buffer_t input_message_buffer,
+ gss_buffer_t output_message_buffer,
+ int *conf_state,
+ gss_qop_t *qop_state)
+{
+ gss_cfx_wrap_token token;
+ u_char token_flags;
+ krb5_error_code ret;
+ unsigned usage;
+ krb5_data data;
+ uint16_t ec, rrc;
+ OM_uint32 seq_number_lo, seq_number_hi;
+ size_t len;
+ u_char *p;
+
+ *minor_status = 0;
+
+ if (input_message_buffer->length < sizeof(*token)) {
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ p = input_message_buffer->value;
+
+ token = (gss_cfx_wrap_token)p;
+
+ if (token->TOK_ID[0] != 0x05 || token->TOK_ID[1] != 0x04) {
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ /* Ignore unknown flags */
+ token_flags = token->Flags &
+ (CFXSentByAcceptor | CFXSealed | CFXAcceptorSubkey);
+
+ if (token_flags & CFXSentByAcceptor) {
+ if ((ctx->more_flags & LOCAL) == 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ if (ctx->more_flags & ACCEPTOR_SUBKEY) {
+ if ((token_flags & CFXAcceptorSubkey) == 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+ } else {
+ if (token_flags & CFXAcceptorSubkey)
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ if (token->Filler != 0xFF) {
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ if (conf_state != NULL) {
+ *conf_state = (token_flags & CFXSealed) ? 1 : 0;
+ }
+
+ ec = (token->EC[0] << 8) | token->EC[1];
+ rrc = (token->RRC[0] << 8) | token->RRC[1];
+
+ /*
+ * Check sequence number
+ */
+ _gsskrb5_decode_be_om_uint32(&token->SND_SEQ[0], &seq_number_hi);
+ _gsskrb5_decode_be_om_uint32(&token->SND_SEQ[4], &seq_number_lo);
+ if (seq_number_hi) {
+ /* no support for 64-bit sequence numbers */
+ *minor_status = ERANGE;
+ return GSS_S_UNSEQ_TOKEN;
+ }
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ ret = _gssapi_msg_order_check(ctx->order, seq_number_lo);
+ if (ret != 0) {
+ *minor_status = 0;
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ _gsskrb5_release_buffer(minor_status, output_message_buffer);
+ return ret;
+ }
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ /*
+ * Decrypt and/or verify checksum
+ */
+
+ if (ctx->more_flags & LOCAL) {
+ usage = KRB5_KU_USAGE_ACCEPTOR_SEAL;
+ } else {
+ usage = KRB5_KU_USAGE_INITIATOR_SEAL;
+ }
+
+ p += sizeof(*token);
+ len = input_message_buffer->length;
+ len -= (p - (u_char *)input_message_buffer->value);
+
+ if (token_flags & CFXSealed) {
+ /*
+ * this is really ugly, but needed against windows
+ * for DCERPC, as windows rotates by EC+RRC.
+ */
+ if (IS_DCE_STYLE(ctx)) {
+ *minor_status = rrc_rotate(p, len, rrc+ec, TRUE);
+ } else {
+ *minor_status = rrc_rotate(p, len, rrc, TRUE);
+ }
+ if (*minor_status != 0) {
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_decrypt(context, ctx->crypto, usage,
+ p, len, &data);
+ if (ret != 0) {
+ *minor_status = ret;
+ return GSS_S_BAD_MIC;
+ }
+
+ /* Check that there is room for the pad and token header */
+ if (data.length < ec + sizeof(*token)) {
+ krb5_data_free(&data);
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+ p = data.data;
+ p += data.length - sizeof(*token);
+
+ /* RRC is unprotected; don't modify input buffer */
+ ((gss_cfx_wrap_token)p)->RRC[0] = token->RRC[0];
+ ((gss_cfx_wrap_token)p)->RRC[1] = token->RRC[1];
+
+ /* Check the integrity of the header */
+ if (ct_memcmp(p, token, sizeof(*token)) != 0) {
+ krb5_data_free(&data);
+ return GSS_S_BAD_MIC;
+ }
+
+ output_message_buffer->value = data.data;
+ output_message_buffer->length = data.length - ec - sizeof(*token);
+ } else {
+ Checksum cksum;
+
+ /* Rotate by RRC; bogus to do this in-place XXX */
+ *minor_status = rrc_rotate(p, len, rrc, TRUE);
+ if (*minor_status != 0) {
+ return GSS_S_FAILURE;
+ }
+
+ /* Determine checksum type */
+ ret = krb5_crypto_get_checksum_type(context,
+ ctx->crypto,
+ &cksum.cksumtype);
+ if (ret != 0) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ cksum.checksum.length = ec;
+
+ /* Check we have at least as much data as the checksum */
+ if (len < cksum.checksum.length) {
+ *minor_status = ERANGE;
+ return GSS_S_BAD_MIC;
+ }
+
+ /* Length now is of the plaintext only, no checksum */
+ len -= cksum.checksum.length;
+ cksum.checksum.data = p + len;
+
+ output_message_buffer->length = len; /* for later */
+ output_message_buffer->value = malloc(len + sizeof(*token));
+ if (output_message_buffer->value == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ /* Checksum is over (plaintext-data | "header") */
+ memcpy(output_message_buffer->value, p, len);
+ memcpy((u_char *)output_message_buffer->value + len,
+ token, sizeof(*token));
+
+ /* EC is not included in checksum calculation */
+ token = (gss_cfx_wrap_token)((u_char *)output_message_buffer->value +
+ len);
+ token->EC[0] = 0;
+ token->EC[1] = 0;
+ token->RRC[0] = 0;
+ token->RRC[1] = 0;
+
+ ret = krb5_verify_checksum(context, ctx->crypto,
+ usage,
+ output_message_buffer->value,
+ len + sizeof(*token),
+ &cksum);
+ if (ret != 0) {
+ *minor_status = ret;
+ _gsskrb5_release_buffer(minor_status, output_message_buffer);
+ return GSS_S_BAD_MIC;
+ }
+ }
+
+ if (qop_state != NULL) {
+ *qop_state = GSS_C_QOP_DEFAULT;
+ }
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 _gssapi_mic_cfx(OM_uint32 *minor_status,
+ const gsskrb5_ctx ctx,
+ krb5_context context,
+ gss_qop_t qop_req,
+ const gss_buffer_t message_buffer,
+ gss_buffer_t message_token)
+{
+ gss_cfx_mic_token token;
+ krb5_error_code ret;
+ unsigned usage;
+ Checksum cksum;
+ u_char *buf;
+ size_t len;
+ int32_t seq_number;
+
+ len = message_buffer->length + sizeof(*token);
+ buf = malloc(len);
+ if (buf == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ memcpy(buf, message_buffer->value, message_buffer->length);
+
+ token = (gss_cfx_mic_token)(buf + message_buffer->length);
+ token->TOK_ID[0] = 0x04;
+ token->TOK_ID[1] = 0x04;
+ token->Flags = 0;
+ if ((ctx->more_flags & LOCAL) == 0)
+ token->Flags |= CFXSentByAcceptor;
+ if (ctx->more_flags & ACCEPTOR_SUBKEY)
+ token->Flags |= CFXAcceptorSubkey;
+ memset(token->Filler, 0xFF, 5);
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ krb5_auth_con_getlocalseqnumber(context,
+ ctx->auth_context,
+ &seq_number);
+ _gsskrb5_encode_be_om_uint32(0, &token->SND_SEQ[0]);
+ _gsskrb5_encode_be_om_uint32(seq_number, &token->SND_SEQ[4]);
+ krb5_auth_con_setlocalseqnumber(context,
+ ctx->auth_context,
+ ++seq_number);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ if (ctx->more_flags & LOCAL) {
+ usage = KRB5_KU_USAGE_INITIATOR_SIGN;
+ } else {
+ usage = KRB5_KU_USAGE_ACCEPTOR_SIGN;
+ }
+
+ ret = krb5_create_checksum(context, ctx->crypto,
+ usage, 0, buf, len, &cksum);
+ if (ret != 0) {
+ *minor_status = ret;
+ free(buf);
+ return GSS_S_FAILURE;
+ }
+
+ /* Determine MIC length */
+ message_token->length = sizeof(*token) + cksum.checksum.length;
+ message_token->value = malloc(message_token->length);
+ if (message_token->value == NULL) {
+ *minor_status = ENOMEM;
+ free_Checksum(&cksum);
+ free(buf);
+ return GSS_S_FAILURE;
+ }
+
+ /* Token is { "header" | get_mic("header" | plaintext-data) } */
+ memcpy(message_token->value, token, sizeof(*token));
+ memcpy((u_char *)message_token->value + sizeof(*token),
+ cksum.checksum.data, cksum.checksum.length);
+
+ free_Checksum(&cksum);
+ free(buf);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 _gssapi_verify_mic_cfx(OM_uint32 *minor_status,
+ const gsskrb5_ctx ctx,
+ krb5_context context,
+ const gss_buffer_t message_buffer,
+ const gss_buffer_t token_buffer,
+ gss_qop_t *qop_state)
+{
+ gss_cfx_mic_token token;
+ u_char token_flags;
+ krb5_error_code ret;
+ unsigned usage;
+ OM_uint32 seq_number_lo, seq_number_hi;
+ u_char *buf, *p;
+ Checksum cksum;
+
+ *minor_status = 0;
+
+ if (token_buffer->length < sizeof(*token)) {
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ p = token_buffer->value;
+
+ token = (gss_cfx_mic_token)p;
+
+ if (token->TOK_ID[0] != 0x04 || token->TOK_ID[1] != 0x04) {
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ /* Ignore unknown flags */
+ token_flags = token->Flags & (CFXSentByAcceptor | CFXAcceptorSubkey);
+
+ if (token_flags & CFXSentByAcceptor) {
+ if ((ctx->more_flags & LOCAL) == 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+ if (ctx->more_flags & ACCEPTOR_SUBKEY) {
+ if ((token_flags & CFXAcceptorSubkey) == 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+ } else {
+ if (token_flags & CFXAcceptorSubkey)
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ if (ct_memcmp(token->Filler, "\xff\xff\xff\xff\xff", 5) != 0) {
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ /*
+ * Check sequence number
+ */
+ _gsskrb5_decode_be_om_uint32(&token->SND_SEQ[0], &seq_number_hi);
+ _gsskrb5_decode_be_om_uint32(&token->SND_SEQ[4], &seq_number_lo);
+ if (seq_number_hi) {
+ *minor_status = ERANGE;
+ return GSS_S_UNSEQ_TOKEN;
+ }
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ ret = _gssapi_msg_order_check(ctx->order, seq_number_lo);
+ if (ret != 0) {
+ *minor_status = 0;
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ return ret;
+ }
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ /*
+ * Verify checksum
+ */
+ ret = krb5_crypto_get_checksum_type(context, ctx->crypto,
+ &cksum.cksumtype);
+ if (ret != 0) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ cksum.checksum.data = p + sizeof(*token);
+ cksum.checksum.length = token_buffer->length - sizeof(*token);
+
+ if (ctx->more_flags & LOCAL) {
+ usage = KRB5_KU_USAGE_ACCEPTOR_SIGN;
+ } else {
+ usage = KRB5_KU_USAGE_INITIATOR_SIGN;
+ }
+
+ buf = malloc(message_buffer->length + sizeof(*token));
+ if (buf == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ memcpy(buf, message_buffer->value, message_buffer->length);
+ memcpy(buf + message_buffer->length, token, sizeof(*token));
+
+ ret = krb5_verify_checksum(context, ctx->crypto,
+ usage,
+ buf,
+ sizeof(*token) + message_buffer->length,
+ &cksum);
+ if (ret != 0) {
+ *minor_status = ret;
+ free(buf);
+ return GSS_S_BAD_MIC;
+ }
+
+ free(buf);
+
+ if (qop_state != NULL) {
+ *qop_state = GSS_C_QOP_DEFAULT;
+ }
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/cfx.h b/third_party/heimdal/lib/gssapi/krb5/cfx.h
new file mode 100644
index 0000000..c30ed07
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/cfx.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2003, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef GSSAPI_CFX_H_
+#define GSSAPI_CFX_H_ 1
+
+/*
+ * Implementation of draft-ietf-krb-wg-gssapi-cfx-01.txt
+ */
+
+typedef struct gss_cfx_mic_token_desc_struct {
+ u_char TOK_ID[2]; /* 04 04 */
+ u_char Flags;
+ u_char Filler[5];
+ u_char SND_SEQ[8];
+} gss_cfx_mic_token_desc, *gss_cfx_mic_token;
+
+typedef struct gss_cfx_wrap_token_desc_struct {
+ u_char TOK_ID[2]; /* 04 05 */
+ u_char Flags;
+ u_char Filler;
+ u_char EC[2];
+ u_char RRC[2];
+ u_char SND_SEQ[8];
+} gss_cfx_wrap_token_desc, *gss_cfx_wrap_token;
+
+typedef struct gss_cfx_delete_token_desc_struct {
+ u_char TOK_ID[2]; /* 05 04 */
+ u_char Flags;
+ u_char Filler[5];
+ u_char SND_SEQ[8];
+} gss_cfx_delete_token_desc, *gss_cfx_delete_token;
+
+#endif /* GSSAPI_CFX_H_ */
diff --git a/third_party/heimdal/lib/gssapi/krb5/compare_name.c b/third_party/heimdal/lib/gssapi/krb5/compare_name.c
new file mode 100644
index 0000000..4a37e87
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/compare_name.c
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 1997-2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_compare_name
+ (OM_uint32 * minor_status,
+ gss_const_name_t name1,
+ gss_const_name_t name2,
+ int * name_equal
+ )
+{
+ krb5_const_principal princ1 = (krb5_const_principal)name1;
+ krb5_const_principal princ2 = (krb5_const_principal)name2;
+ krb5_context context;
+
+ GSSAPI_KRB5_INIT(&context);
+
+ *name_equal = krb5_principal_compare (context,
+ princ1, princ2);
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/compat.c b/third_party/heimdal/lib/gssapi/krb5/compat.c
new file mode 100644
index 0000000..3381dff
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/compat.c
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2003 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+static krb5_error_code
+check_compat(OM_uint32 *minor_status,
+ krb5_context context, krb5_const_principal name,
+ const char *option, krb5_boolean *compat,
+ krb5_boolean match_val)
+{
+ krb5_error_code ret = 0;
+ char **p, **q;
+ krb5_principal match;
+
+
+ p = krb5_config_get_strings(context, NULL, "gssapi",
+ option, NULL);
+ if(p == NULL)
+ return 0;
+
+ match = NULL;
+ for(q = p; *q; q++) {
+ ret = krb5_parse_name(context, *q, &match);
+ if (ret)
+ break;
+
+ if (krb5_principal_match(context, name, match)) {
+ *compat = match_val;
+ break;
+ }
+
+ krb5_free_principal(context, match);
+ match = NULL;
+ }
+ if (match)
+ krb5_free_principal(context, match);
+ krb5_config_free_strings(p);
+
+ if (ret) {
+ if (minor_status)
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ return 0;
+}
+
+/*
+ * ctx->ctx_id_mutex is assumed to be locked
+ */
+
+OM_uint32
+_gss_DES3_get_mic_compat(OM_uint32 *minor_status,
+ gsskrb5_ctx ctx,
+ krb5_context context)
+{
+ krb5_boolean use_compat = FALSE;
+ OM_uint32 ret;
+
+ if ((ctx->more_flags & COMPAT_OLD_DES3_SELECTED) == 0) {
+ ret = check_compat(minor_status, context, ctx->target,
+ "broken_des3_mic", &use_compat, TRUE);
+ if (ret)
+ return ret;
+ ret = check_compat(minor_status, context, ctx->target,
+ "correct_des3_mic", &use_compat, FALSE);
+ if (ret)
+ return ret;
+
+ if (use_compat)
+ ctx->more_flags |= COMPAT_OLD_DES3;
+ ctx->more_flags |= COMPAT_OLD_DES3_SELECTED;
+ }
+ return 0;
+}
+
+#if 0
+OM_uint32
+gss_krb5_compat_des3_mic(OM_uint32 *minor_status, gss_ctx_id_t ctx, int on)
+{
+ *minor_status = 0;
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ if (on) {
+ ctx->more_flags |= COMPAT_OLD_DES3;
+ } else {
+ ctx->more_flags &= ~COMPAT_OLD_DES3;
+ }
+ ctx->more_flags |= COMPAT_OLD_DES3_SELECTED;
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ return 0;
+}
+#endif
diff --git a/third_party/heimdal/lib/gssapi/krb5/context_time.c b/third_party/heimdal/lib/gssapi/krb5/context_time.c
new file mode 100644
index 0000000..58249cb
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/context_time.c
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32
+_gsskrb5_lifetime_left(OM_uint32 *minor_status,
+ krb5_context context,
+ OM_uint32 endtime,
+ OM_uint32 *lifetime_rec)
+{
+ krb5_timestamp now;
+ krb5_error_code kret;
+
+ if (endtime == 0) {
+ *lifetime_rec = GSS_C_INDEFINITE;
+ return GSS_S_COMPLETE;
+ }
+
+ kret = krb5_timeofday(context, &now);
+ if (kret) {
+ *lifetime_rec = 0;
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ if (endtime < now)
+ *lifetime_rec = 0;
+ else
+ *lifetime_rec = endtime - now;
+
+ return GSS_S_COMPLETE;
+}
+
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_context_time
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ OM_uint32 * time_rec
+ )
+{
+ krb5_context context;
+ OM_uint32 endtime;
+ OM_uint32 major_status;
+ const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ endtime = ctx->endtime;
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ major_status = _gsskrb5_lifetime_left(minor_status, context,
+ endtime, time_rec);
+ if (major_status != GSS_S_COMPLETE)
+ return major_status;
+
+ *minor_status = 0;
+
+ if (*time_rec == 0)
+ return GSS_S_CONTEXT_EXPIRED;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/copy_ccache.c b/third_party/heimdal/lib/gssapi/krb5/copy_ccache.c
new file mode 100644
index 0000000..fc0b9b1
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/copy_ccache.c
@@ -0,0 +1,200 @@
+/*
+ * Copyright (c) 2000 - 2001, 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+#if 0
+OM_uint32
+gss_krb5_copy_ccache(OM_uint32 *minor_status,
+ krb5_context context,
+ gss_cred_id_t cred,
+ krb5_ccache out)
+{
+ krb5_error_code kret;
+
+ HEIMDAL_MUTEX_lock(&cred->cred_id_mutex);
+
+ if (cred->ccache == NULL) {
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ kret = krb5_cc_copy_cache(context, cred->ccache, out);
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+#endif
+
+
+/*
+ * WARNING: Takes ownership of `id'. Because MEMORY:anonymous is now not
+ * linked into to the MEMORY ccache namespace, we can't use krb5_cc_resolve()
+ * with the cache's name anymore. We need a krb5_cc_clone() or some such, with
+ * attendant new method for ccops. Or we could create a new MEMORY:anonymous
+ * ccache and copy all the creds from `id' into it. But we know callers of
+ * this function don't need `id' after calling it, so for now we'll just take
+ * ownershipd of it.
+ */
+OM_uint32
+_gsskrb5_krb5_import_cred(OM_uint32 *minor_status,
+ krb5_ccache *id,
+ krb5_principal keytab_principal,
+ krb5_keytab keytab,
+ gss_cred_id_t *cred)
+{
+ krb5_context context;
+ krb5_error_code kret;
+ gsskrb5_cred handle;
+ OM_uint32 ret;
+ int id_given = (*id != NULL);
+
+ *cred = NULL;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ handle = calloc(1, sizeof(*handle));
+ if (handle == NULL) {
+ _gsskrb5_clear_status ();
+ *minor_status = ENOMEM;
+ return (GSS_S_FAILURE);
+ }
+ HEIMDAL_MUTEX_init(&handle->cred_id_mutex);
+
+ handle->usage = 0;
+ handle->destination_realm = NULL;
+
+ if (*id) {
+ time_t now;
+ OM_uint32 left;
+
+ handle->usage |= GSS_C_INITIATE;
+
+ kret = krb5_cc_get_principal(context, *id,
+ &handle->principal);
+ if (kret) {
+ free(handle);
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ if (keytab_principal) {
+ krb5_boolean match;
+
+ match = krb5_principal_compare(context,
+ handle->principal,
+ keytab_principal);
+ if (match == FALSE) {
+ krb5_free_principal(context, handle->principal);
+ free(handle);
+ _gsskrb5_clear_status ();
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ }
+
+ krb5_timeofday(context, &now);
+ ret = __gsskrb5_ccache_lifetime(minor_status,
+ context,
+ *id,
+ handle->principal,
+ &left);
+ if (ret != GSS_S_COMPLETE) {
+ krb5_free_principal(context, handle->principal);
+ free(handle);
+ return ret;
+ }
+ handle->endtime = now + left;
+
+ handle->ccache = *id;
+ *id = NULL;
+ }
+
+
+ if (keytab) {
+ char *str;
+
+ handle->usage |= GSS_C_ACCEPT;
+
+ if (keytab_principal && handle->principal == NULL) {
+ kret = krb5_copy_principal(context,
+ keytab_principal,
+ &handle->principal);
+ if (kret)
+ goto out;
+ }
+
+ kret = krb5_kt_get_full_name(context, keytab, &str);
+ if (kret)
+ goto out;
+
+ kret = krb5_kt_resolve(context, str, &handle->keytab);
+ free(str);
+ if (kret)
+ goto out;
+ }
+
+
+ if (id_given || keytab) {
+ ret = gss_create_empty_oid_set(minor_status, &handle->mechanisms);
+ if (ret == GSS_S_COMPLETE)
+ ret = gss_add_oid_set_member(minor_status, GSS_KRB5_MECHANISM,
+ &handle->mechanisms);
+ if (ret != GSS_S_COMPLETE) {
+ kret = *minor_status;
+ goto out;
+ }
+ }
+
+ *minor_status = 0;
+ *cred = (gss_cred_id_t)handle;
+ return GSS_S_COMPLETE;
+
+out:
+ gss_release_oid_set(minor_status, &handle->mechanisms);
+ if (handle->ccache)
+ krb5_cc_close(context, handle->ccache);
+ if (handle->keytab)
+ krb5_kt_close(context, handle->keytab);
+ if (handle->principal)
+ krb5_free_principal(context, handle->principal);
+ HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex);
+ free(handle);
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/creds.c b/third_party/heimdal/lib/gssapi/krb5/creds.c
new file mode 100644
index 0000000..efb0a23
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/creds.c
@@ -0,0 +1,276 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_export_cred(OM_uint32 *minor_status,
+ gss_cred_id_t cred_handle,
+ gss_buffer_t cred_token)
+{
+ OM_uint32 major_status;
+ gsskrb5_cred handle = (gsskrb5_cred)cred_handle;
+ krb5_context context;
+ krb5_error_code ret;
+ krb5_storage *sp;
+ krb5_data data;
+ const char *type;
+ char *str;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (handle->usage != GSS_C_INITIATE && handle->usage != GSS_C_BOTH) {
+ *minor_status = GSS_KRB5_S_G_BAD_USAGE;
+ return GSS_S_FAILURE;
+ }
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ type = krb5_cc_get_type(context, handle->ccache);
+ if (strcmp(type, "MEMORY") == 0) {
+ krb5_creds *creds;
+ krb5_data config_start_realm;
+ char *start_realm;
+
+ ret = krb5_store_uint32(sp, 0);
+ if (ret) {
+ krb5_storage_free(sp);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_cc_get_config(context, handle->ccache, NULL, "start_realm",
+ &config_start_realm);
+ if (ret == 0) {
+ start_realm = strndup(config_start_realm.data,
+ config_start_realm.length);
+ krb5_data_free(&config_start_realm);
+ } else {
+ start_realm = strdup(krb5_principal_get_realm(context,
+ handle->principal));
+ }
+ if (start_realm == NULL) {
+ *minor_status = krb5_enomem(context);
+ krb5_storage_free(sp);
+ return GSS_S_FAILURE;
+ }
+
+ ret = _krb5_get_krbtgt(context, handle->ccache, start_realm, &creds);
+ free(start_realm);
+ start_realm = NULL;
+ if (ret) {
+ krb5_storage_free(sp);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_store_creds(sp, creds);
+ krb5_free_creds(context, creds);
+ if (ret) {
+ krb5_storage_free(sp);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ } else {
+ ret = krb5_store_uint32(sp, 1);
+ if (ret) {
+ krb5_storage_free(sp);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_cc_get_full_name(context, handle->ccache, &str);
+ if (ret) {
+ krb5_storage_free(sp);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_store_string(sp, str);
+ free(str);
+ if (ret) {
+ krb5_storage_free(sp);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ }
+ ret = krb5_storage_to_data(sp, &data);
+ krb5_storage_free(sp);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ krb5_data_free(&data);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ major_status = _gss_mg_store_oid(minor_status, sp, GSS_KRB5_MECHANISM);
+ if (major_status != GSS_S_COMPLETE) {
+ krb5_data_free(&data);
+ krb5_storage_free(sp);
+ return major_status;
+ }
+
+ ret = krb5_store_data(sp, data);
+ krb5_data_free(&data);
+ if (ret) {
+ krb5_storage_free(sp);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_storage_to_data(sp, &data);
+ krb5_storage_free(sp);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ cred_token->value = data.data;
+ cred_token->length = data.length;
+
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_import_cred(OM_uint32 * minor_status,
+ gss_buffer_t cred_token,
+ gss_cred_id_t * cred_handle)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ gsskrb5_cred handle;
+ krb5_ccache id;
+ krb5_storage *sp;
+ char *str;
+ uint32_t type;
+ int flags = 0;
+
+ *cred_handle = GSS_C_NO_CREDENTIAL;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ sp = krb5_storage_from_mem(cred_token->value, cred_token->length);
+ if (sp == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_ret_uint32(sp, &type);
+ if (ret) {
+ krb5_storage_free(sp);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ switch (type) {
+ case 0: {
+ krb5_creds creds;
+
+ ret = krb5_ret_creds(sp, &creds);
+ krb5_storage_free(sp);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_cc_new_unique(context, "MEMORY", NULL, &id);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_cc_initialize(context, id, creds.client);
+ if (ret) {
+ krb5_cc_destroy(context, id);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_cc_store_cred(context, id, &creds);
+ krb5_free_cred_contents(context, &creds);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ flags |= GSS_CF_DESTROY_CRED_ON_RELEASE;
+
+ break;
+ }
+ case 1:
+ ret = krb5_ret_string(sp, &str);
+ krb5_storage_free(sp);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_cc_resolve(context, str, &id);
+ krb5_xfree(str);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ break;
+
+ default:
+ krb5_storage_free(sp);
+ *minor_status = 0;
+ return GSS_S_NO_CRED;
+ }
+
+ handle = calloc(1, sizeof(*handle));
+ if (handle == NULL) {
+ krb5_cc_close(context, id);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ handle->usage = GSS_C_INITIATE;
+ handle->destination_realm = NULL;
+ krb5_cc_get_principal(context, id, &handle->principal);
+ handle->ccache = id;
+ handle->cred_flags = flags;
+
+ *cred_handle = (gss_cred_id_t)handle;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/decapsulate.c b/third_party/heimdal/lib/gssapi/krb5/decapsulate.c
new file mode 100644
index 0000000..d7b75a6
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/decapsulate.c
@@ -0,0 +1,216 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+/*
+ * return the length of the mechanism in token or -1
+ * (which implies that the token was bad - GSS_S_DEFECTIVE_TOKEN
+ */
+
+ssize_t
+_gsskrb5_get_mech (const u_char *ptr,
+ size_t total_len,
+ const u_char **mech_ret)
+{
+ size_t len, len_len, mech_len, foo;
+ const u_char *p = ptr;
+ int e;
+
+ if (total_len < 1)
+ return -1;
+ if (*p++ != 0x60)
+ return -1;
+ e = der_get_length (p, total_len - 1, &len, &len_len);
+ if (e || 1 + len_len + len != total_len)
+ return -1;
+ if (total_len < 1 + len_len + 1)
+ return -1;
+ p += len_len;
+ if (*p++ != 0x06)
+ return -1;
+ e = der_get_length (p, total_len - 1 - len_len - 1,
+ &mech_len, &foo);
+ if (e)
+ return -1;
+ p += foo;
+ *mech_ret = p;
+ return mech_len;
+}
+
+OM_uint32
+_gssapi_verify_mech_header(u_char **str,
+ size_t total_len,
+ gss_OID mech)
+{
+ const u_char *p;
+ ssize_t mech_len;
+
+ mech_len = _gsskrb5_get_mech (*str, total_len, &p);
+ if (mech_len < 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ if (mech_len != mech->length)
+ return GSS_S_BAD_MECH;
+ if (mech_len > total_len)
+ return GSS_S_BAD_MECH;
+ if (p - *str > total_len - mech_len)
+ return GSS_S_BAD_MECH;
+ if (ct_memcmp(p,
+ mech->elements,
+ mech->length) != 0)
+ return GSS_S_BAD_MECH;
+ p += mech_len;
+ *str = rk_UNCONST(p);
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_gsskrb5_verify_header(u_char **str,
+ size_t total_len,
+ const void *type,
+ gss_OID oid)
+{
+ OM_uint32 ret;
+ size_t len;
+ u_char *p = *str;
+
+ ret = _gssapi_verify_mech_header(str, total_len, oid);
+ if (ret)
+ return ret;
+
+ len = total_len - (*str - p);
+
+ if (len < 2)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ if (ct_memcmp (*str, type, 2) != 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+ *str += 2;
+
+ return 0;
+}
+
+/*
+ * Remove the GSS-API wrapping from `in_token' giving `out_data.
+ * Does not copy data, so just free `in_token'.
+ */
+
+OM_uint32
+_gssapi_decapsulate(
+ OM_uint32 *minor_status,
+ gss_buffer_t input_token_buffer,
+ krb5_data *out_data,
+ const gss_OID mech
+)
+{
+ u_char *p;
+ OM_uint32 ret;
+
+ p = input_token_buffer->value;
+ ret = _gssapi_verify_mech_header(&p,
+ input_token_buffer->length,
+ mech);
+ if (ret) {
+ *minor_status = 0;
+ return ret;
+ }
+
+ out_data->length = input_token_buffer->length -
+ (p - (u_char *)input_token_buffer->value);
+ out_data->data = p;
+ return GSS_S_COMPLETE;
+}
+
+/*
+ * Remove the GSS-API wrapping from `in_token' giving `out_data.
+ * Does not copy data, so just free `in_token'.
+ */
+
+OM_uint32
+_gsskrb5_decapsulate(OM_uint32 *minor_status,
+ gss_buffer_t input_token_buffer,
+ krb5_data *out_data,
+ const void *type,
+ gss_OID oid)
+{
+ u_char *p;
+ OM_uint32 ret;
+
+ p = input_token_buffer->value;
+ ret = _gsskrb5_verify_header(&p,
+ input_token_buffer->length,
+ type,
+ oid);
+ if (ret) {
+ *minor_status = 0;
+ return ret;
+ }
+
+ out_data->length = input_token_buffer->length -
+ (p - (u_char *)input_token_buffer->value);
+ out_data->data = p;
+ return GSS_S_COMPLETE;
+}
+
+/*
+ * Verify padding of a gss wrapped message and return its length.
+ */
+
+OM_uint32
+_gssapi_verify_pad(gss_buffer_t wrapped_token,
+ size_t datalen,
+ size_t *padlen)
+{
+ u_char *pad;
+ size_t padlength;
+ int i;
+
+ if (wrapped_token->length < 1)
+ return GSS_S_BAD_MECH;
+
+ pad = (u_char *)wrapped_token->value + wrapped_token->length;
+ padlength = pad[-1];
+
+ if (padlength > datalen)
+ return GSS_S_BAD_MECH;
+
+ for (i = padlength; i > 0 && *--pad == padlength; i--)
+ ;
+ if (i != 0)
+ return GSS_S_BAD_MIC;
+
+ *padlen = padlength;
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/delete_sec_context.c b/third_party/heimdal/lib/gssapi/krb5/delete_sec_context.c
new file mode 100644
index 0000000..a480079
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/delete_sec_context.c
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_delete_sec_context(OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ gss_buffer_t output_token)
+{
+ krb5_context context;
+ gsskrb5_ctx ctx;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ *minor_status = 0;
+
+ if (output_token) {
+ output_token->length = 0;
+ output_token->value = NULL;
+ }
+
+ if (*context_handle == GSS_C_NO_CONTEXT)
+ return GSS_S_COMPLETE;
+
+ ctx = (gsskrb5_ctx) *context_handle;
+ *context_handle = GSS_C_NO_CONTEXT;
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+
+ krb5_auth_con_free (context, ctx->auth_context);
+ krb5_auth_con_free (context, ctx->deleg_auth_context);
+ if (ctx->kcred)
+ krb5_free_creds(context, ctx->kcred);
+ if(ctx->source)
+ krb5_free_principal (context, ctx->source);
+ if(ctx->target)
+ krb5_free_principal (context, ctx->target);
+ if (ctx->ticket)
+ krb5_free_ticket (context, ctx->ticket);
+ if(ctx->order)
+ _gssapi_msg_order_destroy(&ctx->order);
+ if (ctx->service_keyblock)
+ krb5_free_keyblock (context, ctx->service_keyblock);
+ krb5_data_free(&ctx->fwd_data);
+ if (ctx->crypto)
+ krb5_crypto_destroy(context, ctx->crypto);
+ if (ctx->ccache && (ctx->more_flags & CLOSE_CCACHE))
+ krb5_cc_close(context, ctx->ccache);
+
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex);
+ memset(ctx, 0, sizeof(*ctx));
+ free (ctx);
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/display_name.c b/third_party/heimdal/lib/gssapi/krb5/display_name.c
new file mode 100644
index 0000000..67cb61e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/display_name.c
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_display_name
+ (OM_uint32 * minor_status,
+ gss_const_name_t input_name,
+ gss_buffer_t output_name_buffer,
+ gss_OID * output_name_type
+ )
+{
+ krb5_context context;
+ krb5_const_principal name = (krb5_const_principal)input_name;
+ krb5_error_code kret;
+ char *buf;
+ size_t len;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ kret = krb5_unparse_name_flags (context, name,
+ KRB5_PRINCIPAL_UNPARSE_DISPLAY, &buf);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+ len = strlen (buf);
+ output_name_buffer->length = len;
+ output_name_buffer->value = malloc(len + 1);
+ if (output_name_buffer->value == NULL) {
+ free (buf);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ memcpy (output_name_buffer->value, buf, len);
+ ((char *)output_name_buffer->value)[len] = '\0';
+ free (buf);
+ if (output_name_type)
+ *output_name_type = GSS_KRB5_NT_PRINCIPAL_NAME;
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/display_status.c b/third_party/heimdal/lib/gssapi/krb5/display_status.c
new file mode 100644
index 0000000..cca5f67
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/display_status.c
@@ -0,0 +1,198 @@
+/*
+ * Copyright (c) 1998 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+static const char *
+calling_error(OM_uint32 v)
+{
+ static const char *msgs[] = {
+ NULL, /* 0 */
+ "A required input parameter could not be read.", /* */
+ "A required output parameter could not be written.", /* */
+ "A parameter was malformed"
+ };
+
+ v >>= GSS_C_CALLING_ERROR_OFFSET;
+
+ if (v == 0)
+ return "";
+ else if (v >= sizeof(msgs)/sizeof(*msgs))
+ return "unknown calling error";
+ else
+ return msgs[v];
+}
+
+static const char *
+routine_error(OM_uint32 v)
+{
+ static const char *msgs[] = {
+ NULL, /* 0 */
+ "An unsupported mechanism was requested",
+ "An invalid name was supplied",
+ "A supplied name was of an unsupported type",
+ "Incorrect channel bindings were supplied",
+ "An invalid status code was supplied",
+ "A token had an invalid MIC",
+ "No credentials were supplied, or the credentials were unavailable or inaccessible.",
+ "No context has been established",
+ "A token was invalid",
+ "A credential was invalid",
+ "The referenced credentials have expired",
+ "The context has expired",
+ "Miscellaneous failure (see text)",
+ "The quality-of-protection requested could not be provide",
+ "The operation is forbidden by local security policy",
+ "The operation or option is not available",
+ "The requested credential element already exists",
+ "The provided name was not a mechanism name.",
+ };
+
+ v >>= GSS_C_ROUTINE_ERROR_OFFSET;
+
+ if (v == 0)
+ return "";
+ else if (v >= sizeof(msgs)/sizeof(*msgs))
+ return "unknown routine error";
+ else
+ return msgs[v];
+}
+
+static const char *
+supplementary_error(OM_uint32 v)
+{
+ static const char *msgs[] = {
+ "normal completion",
+ "continuation call to routine required",
+ "duplicate per-message token detected",
+ "timed-out per-message token detected",
+ "reordered (early) per-message token detected",
+ "skipped predecessor token(s) detected"
+ };
+
+ v >>= GSS_C_SUPPLEMENTARY_OFFSET;
+
+ if (v >= sizeof(msgs)/sizeof(*msgs))
+ return "unknown routine error";
+ else
+ return msgs[v];
+}
+
+void
+_gsskrb5_clear_status (void)
+{
+ krb5_context context;
+
+ if (_gsskrb5_init (&context) != 0)
+ return;
+ krb5_clear_error_message(context);
+}
+
+void
+_gsskrb5_set_status (int ret, const char *fmt, ...)
+{
+ krb5_context context;
+ va_list args;
+ char *str;
+ int e;
+
+ if (_gsskrb5_init (&context) != 0)
+ return;
+
+ va_start(args, fmt);
+ e = vasprintf(&str, fmt, args);
+ va_end(args);
+ if (e >= 0 && str) {
+ krb5_set_error_message(context, ret, "%s", str);
+ free(str);
+ }
+}
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_display_status
+(OM_uint32 *minor_status,
+ OM_uint32 status_value,
+ int status_type,
+ const gss_OID mech_type,
+ OM_uint32 *message_context,
+ gss_buffer_t status_string)
+{
+ krb5_context context;
+ char *buf = NULL;
+ int e = 0;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ status_string->length = 0;
+ status_string->value = NULL;
+
+ if (gss_oid_equal(mech_type, GSS_C_NO_OID) == 0 &&
+ gss_oid_equal(mech_type, GSS_KRB5_MECHANISM) == 0) {
+ *minor_status = 0;
+ return GSS_S_BAD_MECH;
+ }
+
+ if (status_type == GSS_C_GSS_CODE) {
+ if (GSS_SUPPLEMENTARY_INFO(status_value))
+ e = asprintf(&buf, "%s",
+ supplementary_error(GSS_SUPPLEMENTARY_INFO(status_value)));
+ else
+ e = asprintf (&buf, "%s %s",
+ calling_error(GSS_CALLING_ERROR(status_value)),
+ routine_error(GSS_ROUTINE_ERROR(status_value)));
+ } else if (status_type == GSS_C_MECH_CODE) {
+ const char *buf2 = krb5_get_error_message(context, status_value);
+ if (buf2) {
+ buf = strdup(buf2);
+ krb5_free_error_message(context, buf2);
+ } else {
+ e = asprintf(&buf, "unknown mech error-code %u",
+ (unsigned)status_value);
+ }
+ } else {
+ *minor_status = EINVAL;
+ return GSS_S_BAD_STATUS;
+ }
+
+ if (e < 0 || buf == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ *message_context = 0;
+ *minor_status = 0;
+
+ status_string->length = strlen(buf);
+ status_string->value = buf;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/duplicate_cred.c b/third_party/heimdal/lib/gssapi/krb5/duplicate_cred.c
new file mode 100644
index 0000000..f5b34c5
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/duplicate_cred.c
@@ -0,0 +1,168 @@
+/*
+ * Copyright (c) 2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_duplicate_cred (
+ OM_uint32 *minor_status,
+ gss_const_cred_id_t input_cred_handle,
+ gss_cred_id_t *output_cred_handle)
+{
+ krb5_context context;
+ gsskrb5_cred cred, dup;
+ OM_uint32 major, junk;
+
+ dup = NULL;
+
+ if (output_cred_handle == NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+ }
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (input_cred_handle == GSS_C_NO_CREDENTIAL) {
+ /* Duplicate the default credential */
+ return _gsskrb5_acquire_cred_from(minor_status, GSS_C_NO_NAME,
+ GSS_C_INDEFINITE,
+ GSS_C_NO_OID_SET,
+ GSS_C_BOTH,
+ GSS_C_NO_CRED_STORE,
+ output_cred_handle,
+ NULL, NULL);
+ }
+
+ /* Duplicate the input credential */
+
+ dup = calloc(1, sizeof(*dup));
+ if (dup == NULL) {
+ *minor_status = krb5_enomem(context);
+ return (GSS_S_FAILURE);
+ }
+
+ *output_cred_handle = (gss_cred_id_t)dup; /* making sure to release on error */
+
+ cred = (gsskrb5_cred)input_cred_handle;
+ HEIMDAL_MUTEX_lock(&cred->cred_id_mutex);
+
+ dup->destination_realm = NULL;
+ if (cred->destination_realm &&
+ (dup->destination_realm = strdup(cred->destination_realm)) == NULL) {
+ *minor_status = krb5_enomem(context);
+ free(dup);
+ return (GSS_S_FAILURE);
+ }
+ dup->usage = cred->usage;
+ dup->endtime = cred->endtime;
+ dup->principal = NULL;
+ dup->keytab = NULL;
+ dup->ccache = NULL;
+ dup->mechanisms = NULL;
+
+ major = GSS_S_FAILURE;
+
+ HEIMDAL_MUTEX_init(&dup->cred_id_mutex);
+ *minor_status = krb5_copy_principal(context, cred->principal,
+ &dup->principal);
+ if (*minor_status)
+ goto fail;
+
+ if (cred->keytab) {
+ char *name = NULL;
+
+ *minor_status = krb5_kt_get_full_name(context, cred->keytab, &name);
+ if (*minor_status)
+ goto fail;
+ *minor_status = krb5_kt_resolve(context, name, &dup->keytab);
+ krb5_xfree(name);
+ if (*minor_status)
+ goto fail;
+ }
+
+ if (cred->ccache) {
+ const char *type, *name;
+ char *type_name = NULL;
+
+ type = krb5_cc_get_type(context, cred->ccache); /* can't fail */
+ if (strcmp(type, "MEMORY") == 0) {
+ *minor_status = krb5_cc_new_unique(context, type, NULL,
+ &dup->ccache);
+ if (*minor_status)
+ goto fail;
+
+ *minor_status = krb5_cc_copy_cache(context, cred->ccache,
+ dup->ccache);
+ if (*minor_status)
+ goto fail;
+
+ } else {
+ name = krb5_cc_get_name(context, cred->ccache);
+ if (name == NULL) {
+ *minor_status = ENOMEM;
+ goto fail;
+ }
+
+ if (asprintf(&type_name, "%s:%s", type, name) == -1 ||
+ type_name == NULL) {
+ *minor_status = ENOMEM;
+ goto fail;
+ }
+
+ *minor_status = krb5_cc_resolve(context, type_name,
+ &dup->ccache);
+ free(type_name);
+ if (*minor_status)
+ goto fail;
+ }
+ }
+
+ major = gss_create_empty_oid_set(minor_status, &dup->mechanisms);
+ if (major != GSS_S_COMPLETE)
+ goto fail;
+
+ major = gss_add_oid_set_member(minor_status, GSS_KRB5_MECHANISM,
+ &dup->mechanisms);
+ if (major != GSS_S_COMPLETE)
+ goto fail;
+
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+ *output_cred_handle = (gss_cred_id_t)dup;
+ *minor_status = 0;
+ return major;
+
+fail:
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+ *output_cred_handle = (gss_cred_id_t)dup;
+ _gsskrb5_release_cred(&junk, output_cred_handle);
+ return major;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/duplicate_name.c b/third_party/heimdal/lib/gssapi/krb5/duplicate_name.c
new file mode 100644
index 0000000..43519d6
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/duplicate_name.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_duplicate_name (
+ OM_uint32 * minor_status,
+ gss_const_name_t src_name,
+ gss_name_t * dest_name
+ )
+{
+ krb5_const_principal src = (krb5_const_principal)src_name;
+ krb5_context context;
+ krb5_principal dest;
+ krb5_error_code kret;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ kret = krb5_copy_principal (context, src, &dest);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ } else {
+ *dest_name = (gss_name_t)dest;
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+ }
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/encapsulate.c b/third_party/heimdal/lib/gssapi/krb5/encapsulate.c
new file mode 100644
index 0000000..3b390ce
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/encapsulate.c
@@ -0,0 +1,153 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+void
+_gssapi_encap_length (size_t data_len,
+ size_t *len,
+ size_t *total_len,
+ const gss_OID mech)
+{
+ size_t len_len;
+
+ *len = 1 + 1 + mech->length + data_len;
+
+ len_len = der_length_len(*len);
+
+ *total_len = 1 + len_len + *len;
+}
+
+void
+_gsskrb5_encap_length (size_t data_len,
+ size_t *len,
+ size_t *total_len,
+ const gss_OID mech)
+{
+ _gssapi_encap_length(data_len + 2, len, total_len, mech);
+}
+
+void *
+_gssapi_make_mech_header(void *ptr,
+ size_t len,
+ const gss_OID mech)
+{
+ u_char *p = ptr;
+ int e;
+ size_t len_len, foo;
+
+ *p++ = 0x60;
+ len_len = der_length_len(len);
+ e = der_put_length (p + len_len - 1, len_len, len, &foo);
+ if(e || foo != len_len)
+ abort ();
+ p += len_len;
+ *p++ = 0x06;
+ *p++ = mech->length;
+ memcpy (p, mech->elements, mech->length);
+ p += mech->length;
+ return p;
+}
+
+void *
+_gsskrb5_make_header (void *ptr,
+ size_t len,
+ const void *type,
+ const gss_OID mech)
+{
+ u_char *p = ptr;
+ p = _gssapi_make_mech_header(p, len, mech);
+ memcpy (p, type, 2);
+ p += 2;
+ return p;
+}
+
+/*
+ * Give it a krb5_data and it will encapsulate with extra GSS-API wrappings.
+ */
+
+OM_uint32
+_gssapi_encapsulate(
+ OM_uint32 *minor_status,
+ const krb5_data *in_data,
+ gss_buffer_t output_token,
+ const gss_OID mech
+)
+{
+ size_t len, outer_len;
+ void *p;
+
+ _gssapi_encap_length (in_data->length, &len, &outer_len, mech);
+
+ output_token->length = outer_len;
+ output_token->value = malloc (outer_len);
+ if (output_token->value == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ p = _gssapi_make_mech_header (output_token->value, len, mech);
+ memcpy (p, in_data->data, in_data->length);
+ return GSS_S_COMPLETE;
+}
+
+/*
+ * Give it a krb5_data and it will encapsulate with extra GSS-API krb5
+ * wrappings.
+ */
+
+OM_uint32
+_gsskrb5_encapsulate(
+ OM_uint32 *minor_status,
+ const krb5_data *in_data,
+ gss_buffer_t output_token,
+ const void *type,
+ const gss_OID mech
+)
+{
+ size_t len, outer_len;
+ u_char *p;
+
+ _gsskrb5_encap_length (in_data->length, &len, &outer_len, mech);
+
+ output_token->length = outer_len;
+ output_token->value = malloc (outer_len);
+ if (output_token->value == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ p = _gsskrb5_make_header (output_token->value, len, type, mech);
+ memcpy (p, in_data->data, in_data->length);
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/export_name.c b/third_party/heimdal/lib/gssapi/krb5/export_name.c
new file mode 100644
index 0000000..1686a65
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/export_name.c
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 1997, 1999, 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_export_name
+ (OM_uint32 * minor_status,
+ gss_const_name_t input_name,
+ gss_buffer_t exported_name
+ )
+{
+ krb5_context context;
+ krb5_const_principal princ = (krb5_const_principal)input_name;
+ krb5_error_code kret;
+ char *buf, *name;
+ size_t len;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ kret = krb5_unparse_name (context, princ, &name);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+ len = strlen (name);
+
+ exported_name->length = 10 + len + GSS_KRB5_MECHANISM->length;
+ exported_name->value = malloc(exported_name->length);
+ if (exported_name->value == NULL) {
+ free (name);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ /* TOK, MECH_OID_LEN, DER(MECH_OID), NAME_LEN, NAME */
+
+ buf = exported_name->value;
+ memcpy(buf, "\x04\x01", 2);
+ buf += 2;
+ buf[0] = ((GSS_KRB5_MECHANISM->length + 2) >> 8) & 0xff;
+ buf[1] = (GSS_KRB5_MECHANISM->length + 2) & 0xff;
+ buf+= 2;
+ buf[0] = 0x06;
+ buf[1] = (GSS_KRB5_MECHANISM->length) & 0xFF;
+ buf+= 2;
+
+ memcpy(buf, GSS_KRB5_MECHANISM->elements, GSS_KRB5_MECHANISM->length);
+ buf += GSS_KRB5_MECHANISM->length;
+
+ buf[0] = (len >> 24) & 0xff;
+ buf[1] = (len >> 16) & 0xff;
+ buf[2] = (len >> 8) & 0xff;
+ buf[3] = (len) & 0xff;
+ buf += 4;
+
+ memcpy (buf, name, len);
+
+ free (name);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/export_sec_context.c b/third_party/heimdal/lib/gssapi/krb5/export_sec_context.c
new file mode 100644
index 0000000..c298415
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/export_sec_context.c
@@ -0,0 +1,257 @@
+/*
+ * Copyright (c) 1999 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_export_sec_context(
+ OM_uint32 *minor_status,
+ gss_ctx_id_t *context_handle,
+ gss_buffer_t interprocess_token
+ )
+{
+ krb5_context context;
+ const gsskrb5_ctx ctx = (const gsskrb5_ctx) *context_handle;
+ krb5_storage *sp;
+ krb5_auth_context ac;
+ OM_uint32 ret = GSS_S_COMPLETE;
+ krb5_data data;
+ int flags;
+ OM_uint32 minor;
+ krb5_error_code kret;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+
+ if (!(ctx->flags & GSS_C_TRANS_FLAG)) {
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ *minor_status = 0;
+ return GSS_S_UNAVAILABLE;
+ }
+
+ sp = krb5_storage_emem ();
+ if (sp == NULL) {
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ ac = ctx->auth_context;
+
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_PACKED);
+ krb5_storage_set_flags(sp, KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE);
+
+ /* flagging included fields */
+
+ flags = 0;
+ if (ac->local_address)
+ flags |= SC_LOCAL_ADDRESS;
+ if (ac->remote_address)
+ flags |= SC_REMOTE_ADDRESS;
+ if (ac->keyblock)
+ flags |= SC_KEYBLOCK;
+ if (ac->local_subkey)
+ flags |= SC_LOCAL_SUBKEY;
+ if (ac->remote_subkey)
+ flags |= SC_REMOTE_SUBKEY;
+ if (ac->authenticator)
+ flags |= SC_AUTHENTICATOR;
+ if (ctx->source)
+ flags |= SC_SOURCE_NAME;
+ if (ctx->target)
+ flags |= SC_TARGET_NAME;
+ if (ctx->order)
+ flags |= SC_ORDER;
+
+ kret = krb5_store_int32 (sp, flags);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+
+ /* marshall auth context */
+
+ kret = krb5_store_int32 (sp, ac->flags);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ if (ac->local_address) {
+ kret = krb5_store_address (sp, *ac->local_address);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ }
+ if (ac->remote_address) {
+ kret = krb5_store_address (sp, *ac->remote_address);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ }
+ kret = krb5_store_int16 (sp, ac->local_port);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ kret = krb5_store_int16 (sp, ac->remote_port);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ if (ac->keyblock) {
+ kret = krb5_store_keyblock (sp, *ac->keyblock);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ }
+ if (ac->local_subkey) {
+ kret = krb5_store_keyblock (sp, *ac->local_subkey);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ }
+ if (ac->remote_subkey) {
+ kret = krb5_store_keyblock (sp, *ac->remote_subkey);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ }
+ kret = krb5_store_int32 (sp, ac->local_seqnumber);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ kret = krb5_store_int32 (sp, ac->remote_seqnumber);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ if (ac->authenticator) {
+ kret = krb5_store_int64(sp, ac->authenticator->ctime);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ kret = krb5_store_int32(sp, ac->authenticator->cusec);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ }
+
+ kret = krb5_store_int32 (sp, ac->keytype);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ kret = krb5_store_int32 (sp, ac->cksumtype);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+
+ /* names */
+ if (ctx->source) {
+ kret = krb5_store_principal(sp, ctx->source);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ }
+
+ if (ctx->target) {
+ kret = krb5_store_principal(sp, ctx->target);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ }
+
+ kret = krb5_store_int32 (sp, ctx->flags);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ kret = krb5_store_int32 (sp, ctx->more_flags);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ kret = krb5_store_int32 (sp, ctx->state);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ /*
+ * XXX We should put a 64-bit int here, but we don't have a
+ * krb5_store_int64() yet.
+ */
+ kret = krb5_store_int32 (sp, ctx->endtime);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ if (ctx->order) {
+ kret = _gssapi_msg_order_export(sp, ctx->order);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ }
+
+ kret = krb5_storage_to_data (sp, &data);
+ krb5_storage_free (sp);
+ if (kret) {
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+ interprocess_token->length = data.length;
+ interprocess_token->value = data.data;
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ ret = _gsskrb5_delete_sec_context (minor_status, context_handle,
+ GSS_C_NO_BUFFER);
+ if (ret != GSS_S_COMPLETE)
+ _gss_secure_release_buffer (&minor, interprocess_token);
+ *minor_status = 0;
+ return ret;
+ failure:
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ krb5_storage_free (sp);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/external.c b/third_party/heimdal/lib/gssapi/krb5/external.c
new file mode 100644
index 0000000..e58df18
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/external.c
@@ -0,0 +1,413 @@
+/*
+ * Copyright (c) 1997 - 2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+#include <gssapi_mech.h>
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {10, (void *)"\x2a\x86\x48\x86\xf7\x12"
+ * "\x01\x02\x01\x01"},
+ * corresponding to an object-identifier value of
+ * {iso(1) member-body(2) United States(840) mit(113554)
+ * infosys(1) gssapi(2) generic(1) user_name(1)}. The constant
+ * GSS_C_NT_USER_NAME should be initialized to point
+ * to that gss_OID_desc.
+ */
+
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_user_name_oid_desc =
+ {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x01")};
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {10, (void *)"\x2a\x86\x48\x86\xf7\x12"
+ * "\x01\x02\x01\x02"},
+ * corresponding to an object-identifier value of
+ * {iso(1) member-body(2) United States(840) mit(113554)
+ * infosys(1) gssapi(2) generic(1) machine_uid_name(2)}.
+ * The constant GSS_C_NT_MACHINE_UID_NAME should be
+ * initialized to point to that gss_OID_desc.
+ */
+
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_machine_uid_name_oid_desc =
+ {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x02")};
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {10, (void *)"\x2a\x86\x48\x86\xf7\x12"
+ * "\x01\x02\x01\x03"},
+ * corresponding to an object-identifier value of
+ * {iso(1) member-body(2) United States(840) mit(113554)
+ * infosys(1) gssapi(2) generic(1) string_uid_name(3)}.
+ * The constant GSS_C_NT_STRING_UID_NAME should be
+ * initialized to point to that gss_OID_desc.
+ */
+
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_string_uid_name_oid_desc =
+ {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x03")};
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {6, (void *)"\x2b\x06\x01\x05\x06\x02"},
+ * corresponding to an object-identifier value of
+ * {iso(1) org(3) dod(6) internet(1) security(5)
+ * nametypes(6) gss-host-based-services(2)). The constant
+ * GSS_C_NT_HOSTBASED_SERVICE_X should be initialized to point
+ * to that gss_OID_desc. This is a deprecated OID value, and
+ * implementations wishing to support hostbased-service names
+ * should instead use the GSS_C_NT_HOSTBASED_SERVICE OID,
+ * defined below, to identify such names;
+ * GSS_C_NT_HOSTBASED_SERVICE_X should be accepted a synonym
+ * for GSS_C_NT_HOSTBASED_SERVICE when presented as an input
+ * parameter, but should not be emitted by GSS-API
+ * implementations
+ */
+
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_hostbased_service_x_oid_desc =
+ {6, rk_UNCONST("\x2b\x06\x01\x05\x06\x02")};
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {10, (void *)"\x2a\x86\x48\x86\xf7\x12"
+ * "\x01\x02\x01\x04"}, corresponding to an
+ * object-identifier value of {iso(1) member-body(2)
+ * Unites States(840) mit(113554) infosys(1) gssapi(2)
+ * generic(1) service_name(4)}. The constant
+ * GSS_C_NT_HOSTBASED_SERVICE should be initialized
+ * to point to that gss_OID_desc.
+ */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_hostbased_service_oid_desc =
+ {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x04")};
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {6, (void *)"\x2b\x06\01\x05\x06\x03"},
+ * corresponding to an object identifier value of
+ * {1(iso), 3(org), 6(dod), 1(internet), 5(security),
+ * 6(nametypes), 3(gss-anonymous-name)}. The constant
+ * and GSS_C_NT_ANONYMOUS should be initialized to point
+ * to that gss_OID_desc.
+ */
+
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_anonymous_oid_desc =
+ {6, rk_UNCONST("\x2b\x06\01\x05\x06\x03")};
+
+/*
+ * The implementation must reserve static storage for a
+ * gss_OID_desc object containing the value
+ * {6, (void *)"\x2b\x06\x01\x05\x06\x04"},
+ * corresponding to an object-identifier value of
+ * {1(iso), 3(org), 6(dod), 1(internet), 5(security),
+ * 6(nametypes), 4(gss-api-exported-name)}. The constant
+ * GSS_C_NT_EXPORT_NAME should be initialized to point
+ * to that gss_OID_desc.
+ */
+
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_export_name_oid_desc =
+ {6, rk_UNCONST("\x2b\x06\x01\x05\x06\x04") };
+
+/*
+ * This name form shall be represented by the Object Identifier {iso(1)
+ * member-body(2) United States(840) mit(113554) infosys(1) gssapi(2)
+ * krb5(2) krb5_name(1)}. The recommended symbolic name for this type
+ * is "GSS_KRB5_NT_PRINCIPAL_NAME".
+ */
+
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_nt_principal_name_oid_desc =
+ {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x01") };
+
+/*
+ * GSS_C_NT_COMPOSITE_EXPORT [RFC6680], OID {iso(1) identified-organization(3)
+ * dod(6) internet(1) security(5) nametypes(6) gss-composite-export(6)}.
+ */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_composite_export_oid_desc =
+ {6, rk_UNCONST("\x2b\x06\x01\x05\x06\x06")};
+
+/*
+ * draft-ietf-cat-iakerb-09, IAKERB:
+ * The mechanism ID for IAKERB proxy GSS-API Kerberos, in accordance
+ * with the mechanism proposed by SPNEGO [7] for negotiating protocol
+ * variations, is: {iso(1) org(3) dod(6) internet(1) security(5)
+ * mechanisms(5) iakerb(10) iakerbProxyProtocol(1)}. The proposed
+ * mechanism ID for IAKERB minimum messages GSS-API Kerberos, in
+ * accordance with the mechanism proposed by SPNEGO for negotiating
+ * protocol variations, is: {iso(1) org(3) dod(6) internet(1)
+ * security(5) mechanisms(5) iakerb(10)
+ * iakerbMinimumMessagesProtocol(2)}.
+ */
+
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_iakerb_proxy_mechanism_oid_desc =
+ {7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0a\x01")};
+
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_iakerb_min_msg_mechanism_oid_desc =
+ {7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0a\x02") };
+
+/*
+ * Context for krb5 calls.
+ */
+
+static gss_mo_desc krb5_mo[] = {
+ {
+ GSS_C_MA_SASL_MECH_NAME,
+ GSS_MO_MA,
+ "SASL mech name",
+ rk_UNCONST("GS2-KRB5"),
+ _gss_mo_get_ctx_as_string,
+ NULL
+ },
+ {
+ GSS_C_MA_MECH_NAME,
+ GSS_MO_MA,
+ "Mechanism name",
+ rk_UNCONST("KRB5"),
+ _gss_mo_get_ctx_as_string,
+ NULL
+ },
+ {
+ GSS_C_MA_MECH_DESCRIPTION,
+ GSS_MO_MA,
+ "Mechanism description",
+ rk_UNCONST("Heimdal Kerberos 5 mech"),
+ _gss_mo_get_ctx_as_string,
+ NULL
+ },
+ {
+ GSS_C_MA_MECH_CONCRETE,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_ITOK_FRAMED,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_AUTH_INIT,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_AUTH_TARG,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_DELEG_CRED,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_INTEG_PROT,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_CONF_PROT,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_MIC,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_WRAP,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_PROT_READY,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_REPLAY_DET,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_OOS_DET,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_CBINDINGS,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_PFS,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_CTX_TRANS,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ }
+};
+
+/*
+ *
+ */
+
+static gssapi_mech_interface_desc krb5_mech = {
+ GMI_VERSION,
+ "krb5",
+ {9, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02") },
+ 0,
+ NULL, /* gm_acquire_cred */
+ _gsskrb5_release_cred,
+ _gsskrb5_init_sec_context,
+ _gsskrb5_accept_sec_context,
+ _gsskrb5_process_context_token,
+ _gsskrb5_delete_sec_context,
+ _gsskrb5_context_time,
+ _gsskrb5_get_mic,
+ _gsskrb5_verify_mic,
+ _gsskrb5_wrap,
+ _gsskrb5_unwrap,
+ _gsskrb5_display_status,
+ _gsskrb5_indicate_mechs,
+ _gsskrb5_compare_name,
+ _gsskrb5_display_name,
+ _gsskrb5_import_name,
+ _gsskrb5_export_name,
+ _gsskrb5_release_name,
+ _gsskrb5_inquire_cred,
+ _gsskrb5_inquire_context,
+ _gsskrb5_wrap_size_limit,
+ NULL, /* gm_add_cred */
+ _gsskrb5_inquire_cred_by_mech,
+ _gsskrb5_export_sec_context,
+ _gsskrb5_import_sec_context,
+ _gsskrb5_inquire_names_for_mech,
+ _gsskrb5_inquire_mechs_for_name,
+ _gsskrb5_canonicalize_name,
+ _gsskrb5_duplicate_name,
+ _gsskrb5_inquire_sec_context_by_oid,
+ _gsskrb5_inquire_cred_by_oid,
+ _gsskrb5_set_sec_context_option,
+ _gsskrb5_set_cred_option,
+ _gsskrb5_pseudo_random,
+ _gk_wrap_iov,
+ _gk_unwrap_iov,
+ _gk_wrap_iov_length,
+ NULL, /* gm_store_cred */
+ _gsskrb5_export_cred,
+ _gsskrb5_import_cred,
+ _gsskrb5_acquire_cred_from,
+ NULL, /* gm_acquire_cred_impersonate_name */
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ krb5_mo,
+ sizeof(krb5_mo) / sizeof(krb5_mo[0]),
+ _gsskrb5_localname,
+ _gsskrb5_authorize_localname,
+ _gsskrb5_display_name_ext,
+ _gsskrb5_inquire_name,
+ _gsskrb5_get_name_attribute,
+ _gsskrb5_set_name_attribute,
+ _gsskrb5_delete_name_attribute,
+ _gsskrb5_export_name_composite,
+ _gsskrb5_duplicate_cred,
+ _gsskrb5_add_cred_from,
+ _gsskrb5_store_cred_into,
+ NULL, /* gm_query_mechanism_info */
+ NULL, /* gm_query_meta_data */
+ NULL, /* gm_exchange_meta_data */
+ _gsskrb5_store_cred_into2,
+ NULL /* gm_compat */
+};
+
+gssapi_mech_interface
+__gss_krb5_initialize(void)
+{
+ return &krb5_mech;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/get_mic.c b/third_party/heimdal/lib/gssapi/krb5/get_mic.c
new file mode 100644
index 0000000..d9cf9d7
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/get_mic.c
@@ -0,0 +1,330 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+#ifdef HEIM_WEAK_CRYPTO
+
+static OM_uint32
+mic_des
+ (OM_uint32 * minor_status,
+ const gsskrb5_ctx ctx,
+ krb5_context context,
+ gss_qop_t qop_req,
+ const gss_buffer_t message_buffer,
+ gss_buffer_t message_token,
+ krb5_keyblock *key
+ )
+{
+ u_char *p;
+ EVP_MD_CTX *md5;
+ u_char hash[16];
+ DES_key_schedule schedule;
+ EVP_CIPHER_CTX des_ctx;
+ DES_cblock deskey;
+ DES_cblock zero;
+ int32_t seq_number;
+ size_t len, total_len;
+
+ _gsskrb5_encap_length (22, &len, &total_len, GSS_KRB5_MECHANISM);
+
+ message_token->length = total_len;
+ message_token->value = malloc (total_len);
+ if (message_token->value == NULL) {
+ message_token->length = 0;
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ p = _gsskrb5_make_header(message_token->value,
+ len,
+ "\x01\x01", /* TOK_ID */
+ GSS_KRB5_MECHANISM);
+
+ memcpy (p, "\x00\x00", 2); /* SGN_ALG = DES MAC MD5 */
+ p += 2;
+
+ memcpy (p, "\xff\xff\xff\xff", 4); /* Filler */
+ p += 4;
+
+ /* Fill in later (SND-SEQ) */
+ memset (p, 0, 16);
+ p += 16;
+
+ /* checksum */
+ md5 = EVP_MD_CTX_create();
+ EVP_DigestInit_ex(md5, EVP_md5(), NULL);
+ EVP_DigestUpdate(md5, p - 24, 8);
+ EVP_DigestUpdate(md5, message_buffer->value, message_buffer->length);
+ EVP_DigestFinal_ex(md5, hash, NULL);
+ EVP_MD_CTX_destroy(md5);
+
+ memset (&zero, 0, sizeof(zero));
+ memcpy (&deskey, key->keyvalue.data, sizeof(deskey));
+ DES_set_key_unchecked (&deskey, &schedule);
+ DES_cbc_cksum ((void *)hash, (void *)hash, sizeof(hash),
+ &schedule, &zero);
+ memcpy (p - 8, hash, 8); /* SGN_CKSUM */
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ /* sequence number */
+ krb5_auth_con_getlocalseqnumber (context,
+ ctx->auth_context,
+ &seq_number);
+
+ p -= 16; /* SND_SEQ */
+ p[0] = (seq_number >> 0) & 0xFF;
+ p[1] = (seq_number >> 8) & 0xFF;
+ p[2] = (seq_number >> 16) & 0xFF;
+ p[3] = (seq_number >> 24) & 0xFF;
+ memset (p + 4,
+ (ctx->more_flags & LOCAL) ? 0 : 0xFF,
+ 4);
+
+ EVP_CIPHER_CTX_init(&des_ctx);
+ EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, key->keyvalue.data, p + 8, 1);
+ EVP_Cipher(&des_ctx, p, p, 8);
+ EVP_CIPHER_CTX_cleanup(&des_ctx);
+
+ krb5_auth_con_setlocalseqnumber (context,
+ ctx->auth_context,
+ ++seq_number);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ memset_s(deskey, sizeof(deskey), 0, sizeof(deskey));
+ memset_s(&schedule, sizeof(schedule), 0, sizeof(schedule));
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+#endif
+
+static OM_uint32
+mic_des3
+ (OM_uint32 * minor_status,
+ const gsskrb5_ctx ctx,
+ krb5_context context,
+ gss_qop_t qop_req,
+ const gss_buffer_t message_buffer,
+ gss_buffer_t message_token,
+ krb5_keyblock *key
+ )
+{
+ u_char *p;
+ Checksum cksum;
+ u_char seq[8];
+
+ int32_t seq_number;
+ size_t len, total_len;
+
+ krb5_crypto crypto;
+ krb5_error_code kret;
+ krb5_data encdata;
+ char *tmp;
+ char ivec[8];
+
+ _gsskrb5_encap_length (36, &len, &total_len, GSS_KRB5_MECHANISM);
+
+ message_token->length = total_len;
+ message_token->value = malloc (total_len);
+ if (message_token->value == NULL) {
+ message_token->length = 0;
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ p = _gsskrb5_make_header(message_token->value,
+ len,
+ "\x01\x01", /* TOK-ID */
+ GSS_KRB5_MECHANISM);
+
+ memcpy (p, "\x04\x00", 2); /* SGN_ALG = HMAC SHA1 DES3-KD */
+ p += 2;
+
+ memcpy (p, "\xff\xff\xff\xff", 4); /* filler */
+ p += 4;
+
+ /* this should be done in parts */
+
+ tmp = malloc (message_buffer->length + 8);
+ if (tmp == NULL) {
+ free (message_token->value);
+ message_token->value = NULL;
+ message_token->length = 0;
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ memcpy (tmp, p - 8, 8);
+ memcpy (tmp + 8, message_buffer->value, message_buffer->length);
+
+ kret = krb5_crypto_init(context, key, 0, &crypto);
+ if (kret) {
+ free (message_token->value);
+ message_token->value = NULL;
+ message_token->length = 0;
+ free (tmp);
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ kret = krb5_create_checksum (context,
+ crypto,
+ KRB5_KU_USAGE_SIGN,
+ 0,
+ tmp,
+ message_buffer->length + 8,
+ &cksum);
+ free (tmp);
+ krb5_crypto_destroy (context, crypto);
+ if (kret) {
+ free (message_token->value);
+ message_token->value = NULL;
+ message_token->length = 0;
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ memcpy (p + 8, cksum.checksum.data, cksum.checksum.length);
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ /* sequence number */
+ krb5_auth_con_getlocalseqnumber (context,
+ ctx->auth_context,
+ &seq_number);
+
+ seq[0] = (seq_number >> 0) & 0xFF;
+ seq[1] = (seq_number >> 8) & 0xFF;
+ seq[2] = (seq_number >> 16) & 0xFF;
+ seq[3] = (seq_number >> 24) & 0xFF;
+ memset (seq + 4,
+ (ctx->more_flags & LOCAL) ? 0 : 0xFF,
+ 4);
+
+ kret = krb5_crypto_init(context, key,
+ ETYPE_DES3_CBC_NONE, &crypto);
+ if (kret) {
+ free (message_token->value);
+ message_token->value = NULL;
+ message_token->length = 0;
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ if (ctx->more_flags & COMPAT_OLD_DES3)
+ memset(ivec, 0, 8);
+ else
+ memcpy(ivec, p + 8, 8);
+
+ kret = krb5_encrypt_ivec (context,
+ crypto,
+ KRB5_KU_USAGE_SEQ,
+ seq, 8, &encdata, ivec);
+ krb5_crypto_destroy (context, crypto);
+ if (kret) {
+ free (message_token->value);
+ message_token->value = NULL;
+ message_token->length = 0;
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ assert (encdata.length == 8);
+
+ memcpy (p, encdata.data, encdata.length);
+ krb5_data_free (&encdata);
+
+ krb5_auth_con_setlocalseqnumber (context,
+ ctx->auth_context,
+ ++seq_number);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ free_Checksum (&cksum);
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_get_mic
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ gss_qop_t qop_req,
+ const gss_buffer_t message_buffer,
+ gss_buffer_t message_token
+ )
+{
+ krb5_context context;
+ const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle;
+ krb5_keyblock *key;
+ OM_uint32 ret;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (ctx->more_flags & IS_CFX)
+ return _gssapi_mic_cfx (minor_status, ctx, context, qop_req,
+ message_buffer, message_token);
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ ret = _gsskrb5i_get_token_key(ctx, context, &key);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ switch (key->keytype) {
+ case KRB5_ENCTYPE_DES_CBC_CRC :
+ case KRB5_ENCTYPE_DES_CBC_MD4 :
+ case KRB5_ENCTYPE_DES_CBC_MD5 :
+#ifdef HEIM_WEAK_CRYPTO
+ ret = mic_des (minor_status, ctx, context, qop_req,
+ message_buffer, message_token, key);
+#else
+ ret = GSS_S_FAILURE;
+#endif
+ break;
+ case KRB5_ENCTYPE_DES3_CBC_MD5 :
+ case KRB5_ENCTYPE_DES3_CBC_SHA1 :
+ ret = mic_des3 (minor_status, ctx, context, qop_req,
+ message_buffer, message_token, key);
+ break;
+ case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5:
+ case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56:
+ ret = _gssapi_get_mic_arcfour (minor_status, ctx, context, qop_req,
+ message_buffer, message_token, key);
+ break;
+ default :
+ abort();
+ break;
+ }
+ krb5_free_keyblock (context, key);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/gkrb5_err.et b/third_party/heimdal/lib/gssapi/krb5/gkrb5_err.et
new file mode 100644
index 0000000..109876e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/gkrb5_err.et
@@ -0,0 +1,33 @@
+#
+# extended gss krb5 error messages
+#
+
+id "$Id$"
+
+error_table gk5
+
+prefix GSS_KRB5_S
+
+error_code G_BAD_SERVICE_NAME, "No @ in SERVICE-NAME name string"
+error_code G_BAD_STRING_UID, "STRING-UID-NAME contains nondigits"
+error_code G_NOUSER, "UID does not resolve to username"
+error_code G_VALIDATE_FAILED, "Validation error"
+error_code G_BUFFER_ALLOC, "Couldn't allocate gss_buffer_t data"
+error_code G_BAD_MSG_CTX, "Message context invalid"
+error_code G_WRONG_SIZE, "Buffer is the wrong size"
+error_code G_BAD_USAGE, "Credential usage type is unknown"
+error_code G_UNKNOWN_QOP, "Unknown quality of protection specified"
+error_code G_UNKNOWN_CRED_STORE_ELEMENT, "Credential store contained unknown elements"
+error_code G_BAD_PASSWORD_CRED_STORE, "Credential store cannot contain both a password and a credentials cache or client keytab"
+
+index 128
+
+error_code KG_CCACHE_NOMATCH, "Principal in credential cache does not match desired name"
+error_code KG_KEYTAB_NOMATCH, "No principal in keytab matches desired name"
+error_code KG_TGT_MISSING, "Credential cache has no TGT"
+error_code KG_NO_SUBKEY, "Authenticator has no subkey"
+error_code KG_CONTEXT_ESTABLISHED, "Context is already fully established"
+error_code KG_BAD_SIGN_TYPE, "Unknown signature type in token"
+error_code KG_BAD_LENGTH, "Invalid field length in token"
+error_code KG_CTX_INCOMPLETE, "Attempt to use incomplete security context"
+error_code KG_INPUT_TOO_LONG, "Input too long"
diff --git a/third_party/heimdal/lib/gssapi/krb5/gsskrb5_locl.h b/third_party/heimdal/lib/gssapi/krb5/gsskrb5_locl.h
new file mode 100644
index 0000000..fbbb168
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/gsskrb5_locl.h
@@ -0,0 +1,153 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef GSSKRB5_LOCL_H
+#define GSSKRB5_LOCL_H
+
+#include <config.h>
+
+#include <krb5_locl.h>
+#include <gkrb5_err.h>
+#include <gssapi.h>
+#include <gssapi_mech.h>
+#include <gssapi_krb5.h>
+#include <assert.h>
+#include <mech/utils.h>
+
+#include "cfx.h"
+
+/*
+ *
+ */
+
+struct gss_msg_order;
+
+typedef struct gsskrb5_ctx {
+ struct krb5_auth_context_data *auth_context;
+ struct krb5_auth_context_data *deleg_auth_context;
+ krb5_principal source, target;
+ OM_uint32 flags;
+ enum { LOCAL = 1, OPEN = 2,
+ COMPAT_OLD_DES3 = 4,
+ COMPAT_OLD_DES3_SELECTED = 8,
+ ACCEPTOR_SUBKEY = 16,
+ RETRIED = 32,
+ CLOSE_CCACHE = 64,
+ IS_CFX = 128
+ } more_flags;
+ enum gss_ctx_id_t_state {
+ /* initiator states */
+ INITIATOR_START,
+ INITIATOR_RESTART,
+ INITIATOR_WAIT_FOR_MUTUAL,
+ INITIATOR_READY,
+ /* acceptor states */
+ ACCEPTOR_START,
+ ACCEPTOR_WAIT_FOR_DCESTYLE,
+ ACCEPTOR_READY
+ } state;
+ krb5_creds *kcred;
+ krb5_ccache ccache;
+ struct krb5_ticket *ticket;
+ time_t endtime;
+ HEIMDAL_MUTEX ctx_id_mutex;
+ struct gss_msg_order *order;
+ krb5_keyblock *service_keyblock;
+ krb5_data fwd_data;
+ krb5_crypto crypto;
+} *gsskrb5_ctx;
+
+static inline krb5_boolean
+IS_DCE_STYLE(gsskrb5_ctx ctx)
+{
+ return (ctx->flags & GSS_C_DCE_STYLE) != 0;
+}
+
+typedef struct {
+ krb5_principal principal;
+ char *destination_realm; /* Realm of acceptor service, if delegated */
+ int cred_flags;
+#define GSS_CF_DESTROY_CRED_ON_RELEASE 1
+#define GSS_CF_NO_CI_FLAGS 2
+ struct krb5_keytab_data *keytab;
+ time_t endtime;
+ gss_cred_usage_t usage;
+ gss_OID_set mechanisms;
+ struct krb5_ccache_data *ccache;
+ HEIMDAL_MUTEX cred_id_mutex;
+ krb5_enctype *enctypes;
+} *gsskrb5_cred;
+
+typedef struct Principal *gsskrb5_name;
+
+/*
+ *
+ */
+
+extern krb5_keytab _gsskrb5_keytab;
+extern HEIMDAL_MUTEX gssapi_keytab_mutex;
+
+/*
+ * Prototypes
+ */
+
+#include "krb5/gsskrb5-private.h"
+
+#define GSSAPI_KRB5_INIT(ctx) do { \
+ krb5_error_code kret_gss_init; \
+ if((kret_gss_init = _gsskrb5_init (ctx)) != 0) { \
+ *minor_status = kret_gss_init; \
+ return GSS_S_FAILURE; \
+ } \
+} while (0)
+
+/* sec_context flags */
+
+#define SC_LOCAL_ADDRESS 0x0001
+#define SC_REMOTE_ADDRESS 0x0002
+#define SC_KEYBLOCK 0x0004
+#define SC_LOCAL_SUBKEY 0x0008
+#define SC_REMOTE_SUBKEY 0x0010
+#define SC_SOURCE_NAME 0x0020
+#define SC_TARGET_NAME 0x0040
+#define SC_ORDER 0x0080
+#define SC_AUTHENTICATOR 0x0100
+
+struct gsskrb5_ccache_name_args {
+ const char *name;
+ const char *out_name;
+};
+
+#endif
diff --git a/third_party/heimdal/lib/gssapi/krb5/import_name.c b/third_party/heimdal/lib/gssapi/krb5/import_name.c
new file mode 100644
index 0000000..f4ee231
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/import_name.c
@@ -0,0 +1,294 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+static OM_uint32
+parse_krb5_name (OM_uint32 *minor_status,
+ krb5_context context,
+ const char *name,
+ gss_name_t *output_name)
+{
+ krb5_principal princ;
+ krb5_error_code kerr;
+
+ kerr = krb5_parse_name (context, name, &princ);
+
+ if (kerr == 0) {
+ *output_name = (gss_name_t)princ;
+ return GSS_S_COMPLETE;
+ }
+ *minor_status = kerr;
+
+ if (kerr == KRB5_PARSE_ILLCHAR || kerr == KRB5_PARSE_MALFORMED)
+ return GSS_S_BAD_NAME;
+
+ return GSS_S_FAILURE;
+}
+
+static OM_uint32
+import_krb5_name (OM_uint32 *minor_status,
+ krb5_context context,
+ const gss_buffer_t input_name_buffer,
+ gss_name_t *output_name)
+{
+ OM_uint32 ret;
+ char *tmp;
+
+ tmp = malloc (input_name_buffer->length + 1);
+ if (tmp == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ memcpy (tmp,
+ input_name_buffer->value,
+ input_name_buffer->length);
+ tmp[input_name_buffer->length] = '\0';
+
+ ret = parse_krb5_name(minor_status, context, tmp, output_name);
+ free(tmp);
+
+ return ret;
+}
+
+OM_uint32
+_gsskrb5_canon_name(OM_uint32 *minor_status, krb5_context context,
+ gss_const_name_t targetname, krb5_principal *out)
+{
+ krb5_const_principal p = (krb5_const_principal)targetname;
+ krb5_error_code ret;
+ char *hostname = NULL, *service;
+ int type;
+ const char *comp;
+
+ *minor_status = 0;
+
+ /* If its not a hostname */
+ type = krb5_principal_get_type(context, p);
+ comp = krb5_principal_get_comp_string(context, p, 0);
+ if (type == KRB5_NT_SRV_HST || type == KRB5_NT_SRV_HST_NEEDS_CANON ||
+ (type == KRB5_NT_UNKNOWN && comp != NULL && strcmp(comp, "host") == 0)) {
+ if (p->name.name_string.len == 0)
+ return GSS_S_BAD_NAME;
+ else if (p->name.name_string.len > 1)
+ hostname = p->name.name_string.val[1];
+
+ service = p->name.name_string.val[0];
+
+ ret = krb5_sname_to_principal(context,
+ hostname,
+ service,
+ KRB5_NT_SRV_HST,
+ out);
+ if (ret == 0) {
+ const char *in_realm = krb5_principal_get_realm(context,
+ p);
+ const char *out_realm = krb5_principal_get_realm(context,
+ *out);
+
+ /*
+ * Avoid loss of information, check for the "referral
+ * realm" and set back what was specified.
+ */
+ if (out_realm != NULL && out_realm[0] == '\0') {
+ ret = krb5_principal_set_realm(context, *out, in_realm);
+ }
+ }
+ } else {
+ ret = krb5_copy_principal(context, p, out);
+ }
+
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ return 0;
+}
+
+
+static OM_uint32
+import_hostbased_name(OM_uint32 *minor_status,
+ krb5_context context,
+ const gss_buffer_t input_name_buffer,
+ gss_name_t *output_name)
+{
+ krb5_principal princ = NULL;
+ krb5_error_code kerr;
+ char *tmp, *p, *host = NULL;
+
+ tmp = malloc (input_name_buffer->length + 1);
+ if (tmp == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ memcpy (tmp,
+ input_name_buffer->value,
+ input_name_buffer->length);
+ tmp[input_name_buffer->length] = '\0';
+
+ p = strchr (tmp, '@');
+ if (p != NULL) {
+ *p = '\0';
+ host = p + 1;
+ }
+
+ kerr = krb5_make_principal(context, &princ, "", tmp, host, NULL);
+ free (tmp);
+ *minor_status = kerr;
+ if (kerr == KRB5_PARSE_ILLCHAR || kerr == KRB5_PARSE_MALFORMED)
+ return GSS_S_BAD_NAME;
+ else if (kerr)
+ return GSS_S_FAILURE;
+
+ krb5_principal_set_type(context, princ, KRB5_NT_SRV_HST);
+ *output_name = (gss_name_t)princ;
+
+ return 0;
+}
+
+static OM_uint32
+import_export_name (OM_uint32 *minor_status,
+ krb5_context context,
+ const gss_buffer_t input_name_buffer,
+ gss_name_t *output_name)
+{
+ CompositePrincipal *composite;
+ unsigned char *p;
+ uint32_t length;
+ size_t sz;
+ OM_uint32 ret;
+ int is_composite;
+ char *name;
+
+ if (input_name_buffer->length < 10 + GSS_KRB5_MECHANISM->length)
+ return GSS_S_BAD_NAME;
+
+ /* TOK, MECH_OID_LEN, DER(MECH_OID), NAME_LEN, NAME */
+
+ p = input_name_buffer->value;
+
+ if (p[0] != 0x04 ||
+ (p[1] != 0x01 && p[1] != 0x02) ||
+ p[2] != 0x00 ||
+ p[3] != GSS_KRB5_MECHANISM->length + 2 ||
+ p[4] != 0x06 ||
+ p[5] != GSS_KRB5_MECHANISM->length ||
+ memcmp(&p[6], GSS_KRB5_MECHANISM->elements,
+ GSS_KRB5_MECHANISM->length) != 0)
+ return GSS_S_BAD_NAME;
+
+ is_composite = p[1] == 0x02;
+
+ p += 6 + GSS_KRB5_MECHANISM->length;
+
+ length = p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3];
+ p += 4;
+
+ if (length > input_name_buffer->length - 10 - GSS_KRB5_MECHANISM->length)
+ return GSS_S_BAD_NAME;
+
+ if (is_composite) {
+ if ((composite = calloc(1, sizeof(*composite))) == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ ret = decode_CompositePrincipal(p, length, composite, &sz);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ if (sz != length) {
+ free_CompositePrincipal(composite);
+ free(composite);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ *output_name = (void *)composite;
+ return GSS_S_COMPLETE;
+ }
+
+ name = malloc(length + 1);
+ if (name == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ memcpy(name, p, length);
+ name[length] = '\0';
+
+ ret = parse_krb5_name(minor_status, context, name, output_name);
+ free(name);
+ return ret;
+}
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_import_name
+ (OM_uint32 * minor_status,
+ const gss_buffer_t input_name_buffer,
+ const gss_OID input_name_type,
+ gss_name_t * output_name
+ )
+{
+ krb5_context context;
+
+ *minor_status = 0;
+ *output_name = GSS_C_NO_NAME;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (gss_oid_equal(input_name_type, GSS_C_NT_HOSTBASED_SERVICE) ||
+ gss_oid_equal(input_name_type, GSS_C_NT_HOSTBASED_SERVICE_X))
+ return import_hostbased_name (minor_status,
+ context,
+ input_name_buffer,
+ output_name);
+ else if (input_name_type == GSS_C_NO_OID
+ || gss_oid_equal(input_name_type, GSS_C_NT_USER_NAME)
+ || gss_oid_equal(input_name_type, GSS_KRB5_NT_PRINCIPAL_NAME))
+ /* default printable syntax */
+ return import_krb5_name (minor_status,
+ context,
+ input_name_buffer,
+ output_name);
+ else if (gss_oid_equal(input_name_type, GSS_C_NT_EXPORT_NAME) ||
+ gss_oid_equal(input_name_type, GSS_C_NT_COMPOSITE_EXPORT)) {
+ return import_export_name(minor_status,
+ context,
+ input_name_buffer,
+ output_name);
+ } else {
+ *minor_status = 0;
+ return GSS_S_BAD_NAMETYPE;
+ }
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/import_sec_context.c b/third_party/heimdal/lib/gssapi/krb5/import_sec_context.c
new file mode 100644
index 0000000..2255a71
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/import_sec_context.c
@@ -0,0 +1,221 @@
+/*
+ * Copyright (c) 1999 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_import_sec_context (
+ OM_uint32 * minor_status,
+ const gss_buffer_t interprocess_token,
+ gss_ctx_id_t * context_handle
+ )
+{
+ OM_uint32 ret = GSS_S_FAILURE;
+ krb5_context context;
+ krb5_error_code kret;
+ krb5_storage *sp;
+ krb5_auth_context ac;
+ krb5_address local, remote;
+ krb5_address *localp, *remotep;
+ krb5_keyblock keyblock;
+ int32_t flags, tmp;
+ int64_t tmp64;
+ gsskrb5_ctx ctx;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ *context_handle = GSS_C_NO_CONTEXT;
+
+ localp = remotep = NULL;
+
+ sp = krb5_storage_from_mem (interprocess_token->value,
+ interprocess_token->length);
+ if (sp == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_PACKED);
+ krb5_storage_set_flags(sp, KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE);
+
+ ctx = calloc(1, sizeof(*ctx));
+ if (ctx == NULL) {
+ *minor_status = ENOMEM;
+ krb5_storage_free (sp);
+ return GSS_S_FAILURE;
+ }
+ HEIMDAL_MUTEX_init(&ctx->ctx_id_mutex);
+
+ kret = krb5_auth_con_init (context,
+ &ctx->auth_context);
+ if (kret) {
+ *minor_status = kret;
+ ret = GSS_S_FAILURE;
+ goto failure;
+ }
+
+ /* flags */
+
+ *minor_status = 0;
+
+ if (krb5_ret_int32 (sp, &flags) != 0)
+ goto failure;
+
+ /* retrieve the auth context */
+
+ ac = ctx->auth_context;
+ if (krb5_ret_int32 (sp, &tmp) != 0)
+ goto failure;
+ ac->flags = tmp;
+ if (flags & SC_LOCAL_ADDRESS) {
+ if (krb5_ret_address (sp, localp = &local) != 0)
+ goto failure;
+ }
+
+ if (flags & SC_REMOTE_ADDRESS) {
+ if (krb5_ret_address (sp, remotep = &remote) != 0)
+ goto failure;
+ }
+
+ krb5_auth_con_setaddrs (context, ac, localp, remotep);
+ if (localp)
+ krb5_free_address (context, localp);
+ if (remotep)
+ krb5_free_address (context, remotep);
+ localp = remotep = NULL;
+
+ if (krb5_ret_int16 (sp, &ac->local_port) != 0)
+ goto failure;
+
+ if (krb5_ret_int16 (sp, &ac->remote_port) != 0)
+ goto failure;
+ if (flags & SC_KEYBLOCK) {
+ if (krb5_ret_keyblock (sp, &keyblock) != 0)
+ goto failure;
+ krb5_auth_con_setkey (context, ac, &keyblock);
+ krb5_free_keyblock_contents (context, &keyblock);
+ }
+ if (flags & SC_LOCAL_SUBKEY) {
+ if (krb5_ret_keyblock (sp, &keyblock) != 0)
+ goto failure;
+ krb5_auth_con_setlocalsubkey (context, ac, &keyblock);
+ krb5_free_keyblock_contents (context, &keyblock);
+ }
+ if (flags & SC_REMOTE_SUBKEY) {
+ if (krb5_ret_keyblock (sp, &keyblock) != 0)
+ goto failure;
+ krb5_auth_con_setremotesubkey (context, ac, &keyblock);
+ krb5_free_keyblock_contents (context, &keyblock);
+ }
+ if (krb5_ret_uint32 (sp, &ac->local_seqnumber))
+ goto failure;
+ if (krb5_ret_uint32 (sp, &ac->remote_seqnumber))
+ goto failure;
+
+ if (flags & SC_AUTHENTICATOR) {
+ if (krb5_ret_int64(sp, &tmp64))
+ goto failure;
+ ac->authenticator->ctime = tmp64;
+ if (krb5_ret_int32(sp, &tmp))
+ goto failure;
+ ac->authenticator->cusec = tmp;
+ }
+
+ if (krb5_ret_int32 (sp, &tmp) != 0)
+ goto failure;
+ ac->keytype = tmp;
+ if (krb5_ret_int32 (sp, &tmp) != 0)
+ goto failure;
+ ac->cksumtype = tmp;
+
+ /* names */
+ if (flags & SC_SOURCE_NAME) {
+ if (krb5_ret_principal(sp, &ctx->source))
+ goto failure;
+ }
+
+ if (flags & SC_TARGET_NAME) {
+ if (krb5_ret_principal(sp, &ctx->target))
+ goto failure;
+ }
+
+ if (krb5_ret_int32 (sp, &tmp))
+ goto failure;
+ ctx->flags = tmp;
+ if (krb5_ret_int32 (sp, &tmp))
+ goto failure;
+ ctx->more_flags = tmp;
+ if (krb5_ret_int32 (sp, &tmp))
+ goto failure;
+ ctx->state = tmp;
+ /*
+ * XXX endtime should be a 64-bit int, but we don't have
+ * krb5_ret_int64() yet.
+ */
+ if (krb5_ret_int32 (sp, &tmp))
+ goto failure;
+ ctx->endtime = tmp;
+
+ if (flags & SC_ORDER) {
+ ret = _gssapi_msg_order_import(minor_status, sp, &ctx->order);
+ if (ret)
+ goto failure;
+ }
+
+ krb5_storage_free (sp);
+
+ _gsskrb5i_is_cfx(context, ctx, (ctx->more_flags & LOCAL) == 0);
+
+ *context_handle = (gss_ctx_id_t)ctx;
+
+ return GSS_S_COMPLETE;
+
+failure:
+ krb5_auth_con_free (context,
+ ctx->auth_context);
+ if (ctx->source != NULL)
+ krb5_free_principal(context, ctx->source);
+ if (ctx->target != NULL)
+ krb5_free_principal(context, ctx->target);
+ if (localp)
+ krb5_free_address (context, localp);
+ if (remotep)
+ krb5_free_address (context, remotep);
+ if(ctx->order)
+ _gssapi_msg_order_destroy(&ctx->order);
+ HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex);
+ krb5_storage_free (sp);
+ free (ctx);
+ *context_handle = GSS_C_NO_CONTEXT;
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/indicate_mechs.c b/third_party/heimdal/lib/gssapi/krb5/indicate_mechs.c
new file mode 100644
index 0000000..6201378
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/indicate_mechs.c
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 1997 - 2001, 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_indicate_mechs
+ (OM_uint32 * minor_status,
+ gss_OID_set * mech_set
+ )
+{
+ OM_uint32 ret, junk;
+
+ ret = gss_create_empty_oid_set(minor_status, mech_set);
+ if (ret)
+ return ret;
+
+ ret = gss_add_oid_set_member(minor_status, GSS_KRB5_MECHANISM, mech_set);
+ if (ret) {
+ gss_release_oid_set(&junk, mech_set);
+ return ret;
+ }
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/init.c b/third_party/heimdal/lib/gssapi/krb5/init.c
new file mode 100644
index 0000000..325b2c4
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/init.c
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 1997 - 2001, 2003, 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+static HEIMDAL_MUTEX context_mutex = HEIMDAL_MUTEX_INITIALIZER;
+static int created_key;
+static HEIMDAL_thread_key context_key;
+
+static void
+destroy_context(void *ptr)
+{
+ krb5_context context = ptr;
+
+ if (context == NULL)
+ return;
+ krb5_free_context(context);
+}
+
+krb5_error_code
+_gsskrb5_init (krb5_context *context)
+{
+ krb5_error_code ret = 0;
+
+ HEIMDAL_MUTEX_lock(&context_mutex);
+
+ if (!created_key) {
+ HEIMDAL_key_create(&context_key, destroy_context, ret);
+ if (ret) {
+ HEIMDAL_MUTEX_unlock(&context_mutex);
+ return ret;
+ }
+ created_key = 1;
+ }
+ HEIMDAL_MUTEX_unlock(&context_mutex);
+
+ *context = HEIMDAL_getspecific(context_key);
+ if (*context == NULL) {
+
+ ret = krb5_init_context(context);
+ if (ret == 0) {
+ krb5_add_et_list(*context, initialize_gk5_error_table_r);
+ HEIMDAL_setspecific(context_key, *context, ret);
+ if (ret) {
+ krb5_free_context(*context);
+ *context = NULL;
+ }
+ }
+ }
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/init_sec_context.c b/third_party/heimdal/lib/gssapi/krb5/init_sec_context.c
new file mode 100644
index 0000000..62b26ed
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/init_sec_context.c
@@ -0,0 +1,1021 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+static OM_uint32
+gsskrb5_set_authorization_data(OM_uint32 *,
+ krb5_context,
+ krb5_auth_context,
+ gss_const_name_t);
+
+/*
+ * copy the addresses from `input_chan_bindings' (if any) to
+ * the auth context `ac'
+ */
+
+static OM_uint32
+set_addresses (krb5_context context,
+ krb5_auth_context ac,
+ const gss_channel_bindings_t input_chan_bindings)
+{
+ /* Port numbers are expected to be in application_data.value,
+ * initator's port first */
+
+ krb5_address initiator_addr, acceptor_addr;
+ krb5_error_code kret;
+
+ if (input_chan_bindings == GSS_C_NO_CHANNEL_BINDINGS
+ || input_chan_bindings->application_data.length !=
+ 2 * sizeof(ac->local_port))
+ return 0;
+
+ memset(&initiator_addr, 0, sizeof(initiator_addr));
+ memset(&acceptor_addr, 0, sizeof(acceptor_addr));
+
+ ac->local_port =
+ *(int16_t *) input_chan_bindings->application_data.value;
+
+ ac->remote_port =
+ *((int16_t *) input_chan_bindings->application_data.value + 1);
+
+ kret = _gsskrb5i_address_to_krb5addr(context,
+ input_chan_bindings->acceptor_addrtype,
+ &input_chan_bindings->acceptor_address,
+ ac->remote_port,
+ &acceptor_addr);
+ if (kret)
+ return kret;
+
+ kret = _gsskrb5i_address_to_krb5addr(context,
+ input_chan_bindings->initiator_addrtype,
+ &input_chan_bindings->initiator_address,
+ ac->local_port,
+ &initiator_addr);
+ if (kret) {
+ krb5_free_address (context, &acceptor_addr);
+ return kret;
+ }
+
+ kret = krb5_auth_con_setaddrs(context,
+ ac,
+ &initiator_addr, /* local address */
+ &acceptor_addr); /* remote address */
+
+ krb5_free_address (context, &initiator_addr);
+ krb5_free_address (context, &acceptor_addr);
+
+#if 0
+ free(input_chan_bindings->application_data.value);
+ input_chan_bindings->application_data.value = NULL;
+ input_chan_bindings->application_data.length = 0;
+#endif
+
+ return kret;
+}
+
+OM_uint32
+_gsskrb5_create_ctx(
+ OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ krb5_context context,
+ const gss_channel_bindings_t input_chan_bindings,
+ enum gss_ctx_id_t_state state)
+{
+ krb5_error_code kret;
+ gsskrb5_ctx ctx;
+
+ *context_handle = NULL;
+
+ ctx = malloc(sizeof(*ctx));
+ if (ctx == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ ctx->auth_context = NULL;
+ ctx->deleg_auth_context = NULL;
+ ctx->source = NULL;
+ ctx->target = NULL;
+ ctx->kcred = NULL;
+ ctx->ccache = NULL;
+ ctx->state = state;
+ ctx->flags = 0;
+ ctx->more_flags = 0;
+ ctx->service_keyblock = NULL;
+ ctx->ticket = NULL;
+ krb5_data_zero(&ctx->fwd_data);
+ ctx->endtime = 0;
+ ctx->order = NULL;
+ ctx->crypto = NULL;
+ HEIMDAL_MUTEX_init(&ctx->ctx_id_mutex);
+
+ kret = krb5_auth_con_init (context, &ctx->auth_context);
+ if (kret) {
+ *minor_status = kret;
+ HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex);
+ free(ctx);
+ return GSS_S_FAILURE;
+ }
+
+ kret = krb5_auth_con_init (context, &ctx->deleg_auth_context);
+ if (kret) {
+ *minor_status = kret;
+ krb5_auth_con_free(context, ctx->auth_context);
+ HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex);
+ free(ctx);
+ return GSS_S_FAILURE;
+ }
+
+ kret = set_addresses(context, ctx->auth_context, input_chan_bindings);
+ if (kret) {
+ *minor_status = kret;
+
+ krb5_auth_con_free(context, ctx->auth_context);
+ krb5_auth_con_free(context, ctx->deleg_auth_context);
+
+ HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex);
+ free(ctx);
+ return GSS_S_BAD_BINDINGS;
+ }
+
+ kret = set_addresses(context, ctx->deleg_auth_context, input_chan_bindings);
+ if (kret) {
+ *minor_status = kret;
+
+ krb5_auth_con_free(context, ctx->auth_context);
+ krb5_auth_con_free(context, ctx->deleg_auth_context);
+
+ HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex);
+ free(ctx);
+ return GSS_S_BAD_BINDINGS;
+ }
+
+ /*
+ * We need a sequence number
+ */
+
+ krb5_auth_con_addflags(context,
+ ctx->auth_context,
+ KRB5_AUTH_CONTEXT_DO_SEQUENCE |
+ KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED,
+ NULL);
+
+ /*
+ * We need a sequence number
+ */
+
+ krb5_auth_con_addflags(context,
+ ctx->deleg_auth_context,
+ KRB5_AUTH_CONTEXT_DO_SEQUENCE |
+ KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED,
+ NULL);
+
+ *context_handle = (gss_ctx_id_t)ctx;
+
+ return GSS_S_COMPLETE;
+}
+
+
+static OM_uint32
+gsskrb5_get_creds(
+ OM_uint32 * minor_status,
+ krb5_context context,
+ krb5_ccache ccache,
+ gsskrb5_ctx ctx,
+ gss_const_name_t target_name,
+ OM_uint32 time_req,
+ OM_uint32 * time_rec)
+{
+ OM_uint32 ret;
+ krb5_error_code kret;
+ krb5_creds this_cred;
+ OM_uint32 lifetime_rec;
+
+ if (ctx->target) {
+ krb5_free_principal(context, ctx->target);
+ ctx->target = NULL;
+ }
+ if (ctx->kcred) {
+ krb5_free_creds(context, ctx->kcred);
+ ctx->kcred = NULL;
+ }
+
+ ret = _gsskrb5_canon_name(minor_status, context, target_name,
+ &ctx->target);
+ if (ret)
+ return ret;
+
+ memset(&this_cred, 0, sizeof(this_cred));
+ this_cred.client = ctx->source;
+ this_cred.server = ctx->target;
+
+ if (time_req && time_req != GSS_C_INDEFINITE) {
+ krb5_timestamp ts;
+
+ krb5_timeofday (context, &ts);
+ this_cred.times.endtime = ts + time_req;
+ } else {
+ this_cred.times.endtime = 0;
+ }
+
+ this_cred.session.keytype = KEYTYPE_NULL;
+
+ kret = krb5_get_credentials(context,
+ 0,
+ ccache,
+ &this_cred,
+ &ctx->kcred);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ krb5_free_principal(context, ctx->target);
+ kret = krb5_copy_principal(context, ctx->kcred->server, &ctx->target);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ ctx->endtime = ctx->kcred->times.endtime;
+
+ ret = _gsskrb5_lifetime_left(minor_status, context,
+ ctx->endtime, &lifetime_rec);
+ if (ret) return ret;
+
+ if (lifetime_rec == 0) {
+ *minor_status = 0;
+ return GSS_S_CONTEXT_EXPIRED;
+ }
+
+ if (time_rec) *time_rec = lifetime_rec;
+
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+gsskrb5_initiator_ready(
+ OM_uint32 * minor_status,
+ gsskrb5_ctx ctx,
+ krb5_context context)
+{
+ OM_uint32 ret;
+ int32_t seq_number;
+ int is_cfx = 0;
+ OM_uint32 flags = ctx->flags;
+
+ krb5_free_creds(context, ctx->kcred);
+ ctx->kcred = NULL;
+
+ if (ctx->more_flags & CLOSE_CCACHE)
+ krb5_cc_close(context, ctx->ccache);
+ ctx->ccache = NULL;
+
+ krb5_auth_con_getremoteseqnumber (context, ctx->auth_context, &seq_number);
+
+ _gsskrb5i_is_cfx(context, ctx, 0);
+ is_cfx = (ctx->more_flags & IS_CFX);
+
+ ret = _gssapi_msg_order_create(minor_status,
+ &ctx->order,
+ _gssapi_msg_order_f(flags),
+ seq_number, 0, is_cfx);
+ if (ret) return ret;
+
+ ctx->state = INITIATOR_READY;
+ ctx->more_flags |= OPEN;
+
+ return GSS_S_COMPLETE;
+}
+
+/*
+ * handle delegated creds in init-sec-context
+ */
+
+static void
+do_delegation (krb5_context context,
+ krb5_auth_context ac,
+ krb5_ccache ccache,
+ krb5_creds *cred,
+ krb5_data *fwd_data,
+ uint32_t flagmask,
+ uint32_t *flags)
+{
+ krb5_error_code kret;
+ krb5_principal client;
+ const char *host;
+
+ krb5_data_zero (fwd_data);
+
+ kret = krb5_cc_get_principal(context, ccache, &client);
+ if (kret)
+ goto out;
+
+ /* We can't generally enforce server.name_type == KRB5_NT_SRV_HST */
+ if (cred->server->name.name_string.len < 2)
+ goto out;
+ host = krb5_principal_get_comp_string(context, cred->server, 1);
+
+#define FWDABLE 1
+ kret = krb5_fwd_tgt_creds(context, ac, host, client, cred->server, ccache,
+ FWDABLE, fwd_data);
+
+ out:
+ if (kret)
+ *flags &= ~flagmask;
+ else
+ *flags |= flagmask;
+
+ if (client)
+ krb5_free_principal(context, client);
+}
+
+/*
+ * first stage of init-sec-context
+ */
+
+static OM_uint32
+init_auth
+(OM_uint32 * minor_status,
+ gsskrb5_cred cred,
+ gsskrb5_ctx ctx,
+ krb5_context context,
+ gss_const_name_t name,
+ const gss_OID mech_type,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_buffer_t input_token,
+ gss_OID * actual_mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec
+ )
+{
+ OM_uint32 ret = GSS_S_FAILURE;
+ krb5_error_code kret;
+ krb5_data fwd_data;
+ OM_uint32 lifetime_rec;
+
+ krb5_data_zero(&fwd_data);
+
+ *minor_status = 0;
+
+ if (actual_mech_type)
+ *actual_mech_type = GSS_KRB5_MECHANISM;
+
+ if (cred == NULL) {
+ kret = krb5_cc_default (context, &ctx->ccache);
+ if (kret) {
+ *minor_status = kret;
+ ret = GSS_S_FAILURE;
+ goto failure;
+ }
+ ctx->more_flags |= CLOSE_CCACHE;
+ } else
+ ctx->ccache = cred->ccache;
+
+ kret = krb5_cc_get_principal (context, ctx->ccache, &ctx->source);
+ if (kret) {
+ *minor_status = kret;
+ ret = GSS_S_FAILURE;
+ goto failure;
+ }
+
+ /*
+ * This is hideous glue for (NFS) clients that wants to limit the
+ * available enctypes to what it can support (encryption in
+ * kernel).
+ */
+ if (cred && cred->enctypes)
+ krb5_set_default_in_tkt_etypes(context, cred->enctypes);
+
+ ret = gsskrb5_get_creds(minor_status, context, ctx->ccache,
+ ctx, name, time_req, time_rec);
+ if (ret)
+ goto failure;
+
+ ret = gsskrb5_set_authorization_data(minor_status, context,
+ ctx->auth_context, name);
+ if (ret)
+ goto failure;
+
+ ctx->endtime = ctx->kcred->times.endtime;
+
+ ret = _gss_DES3_get_mic_compat(minor_status, ctx, context);
+ if (ret)
+ goto failure;
+
+ ret = _gsskrb5_lifetime_left(minor_status,
+ context,
+ ctx->endtime,
+ &lifetime_rec);
+ if (ret)
+ goto failure;
+
+ if (lifetime_rec == 0) {
+ *minor_status = 0;
+ ret = GSS_S_CONTEXT_EXPIRED;
+ goto failure;
+ }
+
+ krb5_auth_con_setkey(context,
+ ctx->auth_context,
+ &ctx->kcred->session);
+
+ kret = krb5_auth_con_generatelocalsubkey(context,
+ ctx->auth_context,
+ &ctx->kcred->session);
+ if(kret) {
+ *minor_status = kret;
+ ret = GSS_S_FAILURE;
+ goto failure;
+ }
+
+ return GSS_S_COMPLETE;
+
+failure:
+ if (ctx->ccache && (ctx->more_flags & CLOSE_CCACHE))
+ krb5_cc_close(context, ctx->ccache);
+ ctx->ccache = NULL;
+
+ return ret;
+
+}
+
+static OM_uint32
+init_auth_restart
+(OM_uint32 * minor_status,
+ gsskrb5_cred cred,
+ gsskrb5_ctx ctx,
+ krb5_context context,
+ OM_uint32 req_flags,
+ const gss_channel_bindings_t input_chan_bindings,
+ const gss_buffer_t input_token,
+ gss_OID * actual_mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec
+ )
+{
+ OM_uint32 ret = GSS_S_FAILURE;
+ krb5_error_code kret;
+ krb5_flags ap_options;
+ krb5_data outbuf;
+ uint32_t flags;
+ krb5_data authenticator;
+ Checksum cksum;
+ krb5_enctype enctype;
+ krb5_data fwd_data, timedata;
+ int32_t offset = 0, oldoffset = 0;
+ uint32_t flagmask;
+
+ krb5_data_zero(&outbuf);
+ krb5_data_zero(&fwd_data);
+
+ *minor_status = 0;
+
+ /*
+ * Check if our configuration requires us to follow the KDC's
+ * guidance. If so, we transmogrify the GSS_C_DELEG_FLAG into
+ * the GSS_C_DELEG_POLICY_FLAG.
+ */
+ if ((context->flags & KRB5_CTX_F_ENFORCE_OK_AS_DELEGATE)
+ && (req_flags & GSS_C_DELEG_FLAG)) {
+ req_flags &= ~GSS_C_DELEG_FLAG;
+ req_flags |= GSS_C_DELEG_POLICY_FLAG;
+ }
+
+ /*
+ * If the credential doesn't have ok-as-delegate, check if there
+ * is a realm setting and use that.
+ */
+ if (!ctx->kcred->flags.b.ok_as_delegate) {
+ krb5_data data;
+
+ ret = krb5_cc_get_config(context, ctx->ccache, NULL,
+ "realm-config", &data);
+ if (ret == 0) {
+ /* XXX 1 is use ok-as-delegate */
+ if (data.length < 1 || ((((unsigned char *)data.data)[0]) & 1) == 0)
+ req_flags &= ~(GSS_C_DELEG_FLAG|GSS_C_DELEG_POLICY_FLAG);
+ krb5_data_free(&data);
+ }
+ }
+
+ flagmask = 0;
+
+ /* if we used GSS_C_DELEG_POLICY_FLAG, trust KDC */
+ if ((req_flags & GSS_C_DELEG_POLICY_FLAG)
+ && ctx->kcred->flags.b.ok_as_delegate)
+ flagmask |= GSS_C_DELEG_FLAG | GSS_C_DELEG_POLICY_FLAG;
+ /* if there still is a GSS_C_DELEG_FLAG, use that */
+ if (req_flags & GSS_C_DELEG_FLAG)
+ flagmask |= GSS_C_DELEG_FLAG;
+
+
+ flags = 0;
+ ap_options = 0;
+ if (flagmask & GSS_C_DELEG_FLAG) {
+ do_delegation (context,
+ ctx->deleg_auth_context,
+ ctx->ccache, ctx->kcred,
+ &fwd_data, flagmask, &flags);
+ }
+
+ if (req_flags & GSS_C_MUTUAL_FLAG) {
+ flags |= GSS_C_MUTUAL_FLAG;
+ ap_options |= AP_OPTS_MUTUAL_REQUIRED;
+ }
+
+ if (req_flags & GSS_C_REPLAY_FLAG)
+ flags |= GSS_C_REPLAY_FLAG;
+ if (req_flags & GSS_C_SEQUENCE_FLAG)
+ flags |= GSS_C_SEQUENCE_FLAG;
+#if 0
+ if (req_flags & GSS_C_ANON_FLAG)
+ ; /* XXX */
+#endif
+ if (req_flags & GSS_C_DCE_STYLE) {
+ /* GSS_C_DCE_STYLE implies GSS_C_MUTUAL_FLAG */
+ flags |= GSS_C_DCE_STYLE | GSS_C_MUTUAL_FLAG;
+ ap_options |= AP_OPTS_MUTUAL_REQUIRED;
+ }
+ if (req_flags & GSS_C_IDENTIFY_FLAG)
+ flags |= GSS_C_IDENTIFY_FLAG;
+ if (req_flags & GSS_C_EXTENDED_ERROR_FLAG)
+ flags |= GSS_C_EXTENDED_ERROR_FLAG;
+
+ if (req_flags & GSS_C_CONF_FLAG) {
+ flags |= GSS_C_CONF_FLAG;
+ }
+ if (req_flags & GSS_C_INTEG_FLAG) {
+ flags |= GSS_C_INTEG_FLAG;
+ }
+ if (cred == NULL || !(cred->cred_flags & GSS_CF_NO_CI_FLAGS)) {
+ flags |= GSS_C_CONF_FLAG;
+ flags |= GSS_C_INTEG_FLAG;
+ }
+ flags |= GSS_C_TRANS_FLAG;
+
+ if (ret_flags)
+ *ret_flags = flags;
+ ctx->flags = flags;
+ ctx->more_flags |= LOCAL;
+
+ ret = _gsskrb5_create_8003_checksum (minor_status,
+ input_chan_bindings,
+ flags,
+ &fwd_data,
+ &cksum);
+ krb5_data_free (&fwd_data);
+ if (ret)
+ goto failure;
+
+ enctype = ctx->auth_context->keyblock->keytype;
+
+ ret = krb5_cc_get_config(context, ctx->ccache, ctx->target,
+ "time-offset", &timedata);
+ if (ret == 0) {
+ if (timedata.length == 4) {
+ const u_char *p = timedata.data;
+ offset = ((uint32_t)p[0] << 24)
+ | ((uint32_t)p[1] << 16)
+ | ((uint32_t)p[2] << 8)
+ | ((uint32_t)p[3] << 0);
+ }
+ krb5_data_free(&timedata);
+ }
+
+ if (offset) {
+ krb5_get_kdc_sec_offset (context, &oldoffset, NULL);
+ krb5_set_kdc_sec_offset (context, offset, -1);
+ }
+
+ kret = _krb5_build_authenticator(context,
+ ctx->auth_context,
+ enctype,
+ ctx->kcred,
+ &cksum,
+ &authenticator,
+ KRB5_KU_AP_REQ_AUTH);
+
+ if (kret) {
+ if (offset)
+ krb5_set_kdc_sec_offset (context, oldoffset, -1);
+ *minor_status = kret;
+ ret = GSS_S_FAILURE;
+ goto failure;
+ }
+
+ kret = krb5_build_ap_req (context,
+ enctype,
+ ctx->kcred,
+ ap_options,
+ authenticator,
+ &outbuf);
+ if (offset)
+ krb5_set_kdc_sec_offset (context, oldoffset, -1);
+ if (kret) {
+ *minor_status = kret;
+ ret = GSS_S_FAILURE;
+ goto failure;
+ }
+
+ if (flags & GSS_C_DCE_STYLE) {
+ output_token->value = outbuf.data;
+ output_token->length = outbuf.length;
+ } else {
+ ret = _gsskrb5_encapsulate (minor_status, &outbuf, output_token,
+ (u_char *)(intptr_t)"\x01\x00",
+ GSS_KRB5_MECHANISM);
+ krb5_data_free (&outbuf);
+ if (ret)
+ goto failure;
+ }
+
+ free_Checksum(&cksum);
+
+ if (flags & GSS_C_MUTUAL_FLAG) {
+ ctx->state = INITIATOR_WAIT_FOR_MUTUAL;
+ return GSS_S_CONTINUE_NEEDED;
+ }
+
+ return gsskrb5_initiator_ready(minor_status, ctx, context);
+failure:
+ if (ctx->ccache && (ctx->more_flags & CLOSE_CCACHE))
+ krb5_cc_close(context, ctx->ccache);
+ ctx->ccache = NULL;
+
+ return ret;
+}
+
+static krb5_error_code
+handle_error_packet(krb5_context context,
+ gsskrb5_ctx ctx,
+ krb5_data indata)
+{
+ krb5_error_code kret;
+ KRB_ERROR error;
+
+ kret = krb5_rd_error(context, &indata, &error);
+ if (kret == 0) {
+ kret = krb5_error_from_rd_error(context, &error, NULL);
+
+ /* save the time skrew for this host */
+ if (kret == KRB5KRB_AP_ERR_SKEW) {
+ krb5_data timedata;
+ unsigned char p[4];
+ int32_t t = error.stime - time(NULL);
+
+ p[0] = (t >> 24) & 0xFF;
+ p[1] = (t >> 16) & 0xFF;
+ p[2] = (t >> 8) & 0xFF;
+ p[3] = (t >> 0) & 0xFF;
+
+ timedata.data = p;
+ timedata.length = sizeof(p);
+
+ krb5_cc_set_config(context, ctx->ccache, ctx->target,
+ "time-offset", &timedata);
+
+ if ((ctx->more_flags & RETRIED) == 0)
+ ctx->state = INITIATOR_RESTART;
+ ctx->more_flags |= RETRIED;
+ }
+ free_KRB_ERROR (&error);
+ }
+ return kret;
+}
+
+
+static OM_uint32
+repl_mutual
+(OM_uint32 * minor_status,
+ gsskrb5_ctx ctx,
+ krb5_context context,
+ const gss_OID mech_type,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ const gss_buffer_t input_token,
+ gss_OID * actual_mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec
+ )
+{
+ OM_uint32 ret;
+ krb5_error_code kret;
+ krb5_data indata;
+ krb5_ap_rep_enc_part *repl;
+
+ output_token->length = 0;
+ output_token->value = NULL;
+
+ if (actual_mech_type)
+ *actual_mech_type = GSS_KRB5_MECHANISM;
+
+ if (IS_DCE_STYLE(ctx)) {
+ /* There is no OID wrapping. */
+ indata.length = input_token->length;
+ indata.data = input_token->value;
+ kret = krb5_rd_rep(context,
+ ctx->auth_context,
+ &indata,
+ &repl);
+ if (kret) {
+ ret = _gsskrb5_decapsulate(minor_status,
+ input_token,
+ &indata,
+ "\x03\x00",
+ GSS_KRB5_MECHANISM);
+ if (ret == GSS_S_COMPLETE) {
+ *minor_status = handle_error_packet(context, ctx, indata);
+ } else {
+ *minor_status = kret;
+ }
+ return GSS_S_FAILURE;
+ }
+ } else {
+ ret = _gsskrb5_decapsulate (minor_status,
+ input_token,
+ &indata,
+ "\x02\x00",
+ GSS_KRB5_MECHANISM);
+ if (ret == GSS_S_DEFECTIVE_TOKEN) {
+ /* check if there is an error token sent instead */
+ ret = _gsskrb5_decapsulate (minor_status,
+ input_token,
+ &indata,
+ "\x03\x00",
+ GSS_KRB5_MECHANISM);
+ if (ret == GSS_S_COMPLETE) {
+ *minor_status = handle_error_packet(context, ctx, indata);
+ return GSS_S_FAILURE;
+ }
+ }
+ kret = krb5_rd_rep (context,
+ ctx->auth_context,
+ &indata,
+ &repl);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+ }
+
+ krb5_free_ap_rep_enc_part (context,
+ repl);
+
+ *minor_status = 0;
+ if (time_rec)
+ _gsskrb5_lifetime_left(minor_status,
+ context,
+ ctx->endtime,
+ time_rec);
+ if (ret_flags)
+ *ret_flags = ctx->flags;
+
+ if (req_flags & GSS_C_DCE_STYLE) {
+ int32_t local_seq, remote_seq;
+ krb5_data outbuf;
+
+ /*
+ * So DCE_STYLE is strange. The client echos the seq number
+ * that the server used in the server's mk_rep in its own
+ * mk_rep(). After when done, it resets to it's own seq number
+ * for the gss_wrap calls.
+ */
+
+ krb5_auth_con_getremoteseqnumber(context, ctx->auth_context, &remote_seq);
+ krb5_auth_con_getlocalseqnumber(context, ctx->auth_context, &local_seq);
+ krb5_auth_con_setlocalseqnumber(context, ctx->auth_context, remote_seq);
+
+ kret = krb5_mk_rep(context, ctx->auth_context, &outbuf);
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ /* reset local seq number */
+ krb5_auth_con_setlocalseqnumber(context, ctx->auth_context, local_seq);
+
+ output_token->length = outbuf.length;
+ output_token->value = outbuf.data;
+ }
+
+ return gsskrb5_initiator_ready(minor_status, ctx, context);
+}
+
+/*
+ * gss_init_sec_context
+ */
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_init_sec_context
+(OM_uint32 * minor_status,
+ gss_const_cred_id_t cred_handle,
+ gss_ctx_id_t * context_handle,
+ gss_const_name_t target_name,
+ const gss_OID mech_type,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ const gss_buffer_t input_token,
+ gss_OID * actual_mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec
+ )
+{
+ krb5_context context;
+ gsskrb5_cred cred = (gsskrb5_cred)cred_handle;
+ gsskrb5_ctx ctx;
+ OM_uint32 ret;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ output_token->length = 0;
+ output_token->value = NULL;
+
+ if (context_handle == NULL) {
+ *minor_status = 0;
+ return GSS_S_FAILURE | GSS_S_CALL_BAD_STRUCTURE;
+ }
+
+ if (ret_flags)
+ *ret_flags = 0;
+ if (time_rec)
+ *time_rec = 0;
+
+ if (target_name == GSS_C_NO_NAME) {
+ if (actual_mech_type)
+ *actual_mech_type = GSS_C_NO_OID;
+ *minor_status = 0;
+ return GSS_S_BAD_NAME;
+ }
+
+ if (mech_type != GSS_C_NO_OID &&
+ !gss_oid_equal(mech_type, GSS_KRB5_MECHANISM))
+ return GSS_S_BAD_MECH;
+
+ if (input_token == GSS_C_NO_BUFFER || input_token->length == 0) {
+ OM_uint32 ret1;
+
+ if (*context_handle != GSS_C_NO_CONTEXT) {
+ *minor_status = 0;
+ return GSS_S_FAILURE | GSS_S_CALL_BAD_STRUCTURE;
+ }
+
+ ret1 = _gsskrb5_create_ctx(minor_status,
+ context_handle,
+ context,
+ input_chan_bindings,
+ INITIATOR_START);
+ if (ret1)
+ return ret1;
+ }
+
+ if (*context_handle == GSS_C_NO_CONTEXT) {
+ *minor_status = 0;
+ return GSS_S_FAILURE | GSS_S_CALL_BAD_STRUCTURE;
+ }
+
+ ctx = (gsskrb5_ctx) *context_handle;
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+
+ again:
+ switch (ctx->state) {
+ case INITIATOR_START:
+ ret = init_auth(minor_status,
+ cred,
+ ctx,
+ context,
+ target_name,
+ mech_type,
+ req_flags,
+ time_req,
+ input_token,
+ actual_mech_type,
+ output_token,
+ ret_flags,
+ time_rec);
+ if (ret != GSS_S_COMPLETE)
+ break;
+ fallthrough;
+ case INITIATOR_RESTART:
+ ret = init_auth_restart(minor_status,
+ cred,
+ ctx,
+ context,
+ req_flags,
+ input_chan_bindings,
+ input_token,
+ actual_mech_type,
+ output_token,
+ ret_flags,
+ time_rec);
+ break;
+ case INITIATOR_WAIT_FOR_MUTUAL:
+ ret = repl_mutual(minor_status,
+ ctx,
+ context,
+ mech_type,
+ req_flags,
+ time_req,
+ input_chan_bindings,
+ input_token,
+ actual_mech_type,
+ output_token,
+ ret_flags,
+ time_rec);
+ if (ctx->state == INITIATOR_RESTART)
+ goto again;
+ break;
+ case INITIATOR_READY:
+ /*
+ * If we get there, the caller have called
+ * gss_init_sec_context() one time too many.
+ */
+ _gsskrb5_set_status(EINVAL, "init_sec_context "
+ "called one time too many");
+ *minor_status = EINVAL;
+ ret = GSS_S_BAD_STATUS;
+ break;
+ default:
+ _gsskrb5_set_status(EINVAL, "init_sec_context "
+ "invalid state %d for client",
+ (int)ctx->state);
+ *minor_status = EINVAL;
+ ret = GSS_S_BAD_STATUS;
+ break;
+ }
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ /* destroy context in case of error */
+ if (GSS_ERROR(ret)) {
+ OM_uint32 min2;
+ _gsskrb5_delete_sec_context(&min2, context_handle, GSS_C_NO_BUFFER);
+ }
+
+ return ret;
+
+}
+
+static OM_uint32
+gsskrb5_set_authorization_data(OM_uint32 *minor_status,
+ krb5_context context,
+ krb5_auth_context auth_context,
+ gss_const_name_t gn)
+{
+ const CompositePrincipal *name = (const void *)gn;
+ AuthorizationData *ad;
+ krb5_error_code kret = 0;
+ size_t i;
+
+ if (name->nameattrs == NULL || name->nameattrs->want_ad == NULL)
+ return GSS_S_COMPLETE;
+
+ ad = name->nameattrs->want_ad;
+ for (i = 0; kret == 0 && i < ad->len; i++) {
+ kret = krb5_auth_con_add_AuthorizationData(context, auth_context,
+ ad->val[0].ad_type,
+ &ad->val[0].ad_data);
+ }
+
+ if (kret) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/inquire_context.c b/third_party/heimdal/lib/gssapi/krb5/inquire_context.c
new file mode 100644
index 0000000..e225c33
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/inquire_context.c
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 1997, 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_context (
+ OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ gss_name_t * src_name,
+ gss_name_t * targ_name,
+ OM_uint32 * lifetime_rec,
+ gss_OID * mech_type,
+ OM_uint32 * ctx_flags,
+ int * locally_initiated,
+ int * open_context
+ )
+{
+ krb5_context context;
+ OM_uint32 ret;
+ gsskrb5_ctx ctx = (gsskrb5_ctx)context_handle;
+ gss_name_t name;
+
+ if (src_name)
+ *src_name = GSS_C_NO_NAME;
+ if (targ_name)
+ *targ_name = GSS_C_NO_NAME;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+
+ if (src_name) {
+ name = (gss_name_t)ctx->source;
+ ret = _gsskrb5_duplicate_name (minor_status, name, src_name);
+ if (ret)
+ goto failed;
+ }
+
+ if (targ_name) {
+ name = (gss_name_t)ctx->target;
+ ret = _gsskrb5_duplicate_name (minor_status, name, targ_name);
+ if (ret)
+ goto failed;
+ }
+
+ if (lifetime_rec) {
+ ret = _gsskrb5_lifetime_left(minor_status,
+ context,
+ ctx->endtime,
+ lifetime_rec);
+ if (ret)
+ goto failed;
+ }
+
+ if (mech_type)
+ *mech_type = GSS_KRB5_MECHANISM;
+
+ if (ctx_flags)
+ *ctx_flags = ctx->flags;
+
+ if (locally_initiated)
+ *locally_initiated = ctx->more_flags & LOCAL;
+
+ if (open_context)
+ *open_context = ctx->more_flags & OPEN;
+
+ *minor_status = 0;
+
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ return GSS_S_COMPLETE;
+
+failed:
+ if (src_name)
+ _gsskrb5_release_name(NULL, src_name);
+ if (targ_name)
+ _gsskrb5_release_name(NULL, targ_name);
+
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/inquire_cred.c b/third_party/heimdal/lib/gssapi/krb5/inquire_cred.c
new file mode 100644
index 0000000..b7b67f7
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/inquire_cred.c
@@ -0,0 +1,225 @@
+/*
+ * Copyright (c) 1997, 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_cred
+(OM_uint32 * minor_status,
+ gss_const_cred_id_t cred_handle,
+ gss_name_t * output_name,
+ OM_uint32 * lifetime,
+ gss_cred_usage_t * cred_usage,
+ gss_OID_set * mechanisms
+ )
+{
+ krb5_context context;
+ gss_cred_id_t aqcred_init = GSS_C_NO_CREDENTIAL;
+ gss_cred_id_t aqcred_accept = GSS_C_NO_CREDENTIAL;
+ gsskrb5_cred cred = (gsskrb5_cred)cred_handle;
+ gss_OID_set amechs = GSS_C_NO_OID_SET;
+ gss_OID_set imechs = GSS_C_NO_OID_SET;
+ OM_uint32 junk;
+ OM_uint32 aminor;
+ OM_uint32 ret;
+ OM_uint32 aret;
+ OM_uint32 alife = GSS_C_INDEFINITE;
+ OM_uint32 ilife = GSS_C_INDEFINITE;
+
+ /*
+ * XXX This function is more complex than it has to be. It should call
+ * _gsskrb5_inquire_cred_by_mech() twice and merge the results in the
+ * cred_handle == GSS_C_NO_CREDENTIAL case, but since
+ * _gsskrb5_inquire_cred_by_mech() is implemented in terms of this
+ * function, first we must fix _gsskrb5_inquire_cred_by_mech().
+ */
+
+ *minor_status = 0;
+
+ if (output_name)
+ *output_name = GSS_C_NO_NAME;
+ if (cred_usage)
+ *cred_usage = GSS_C_BOTH; /* There's no NONE */
+ if (mechanisms)
+ *mechanisms = GSS_C_NO_OID_SET;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (cred_handle == GSS_C_NO_CREDENTIAL) {
+ /*
+ * From here to the end of this if we should refactor into a separate
+ * function.
+ */
+ /* Get the info for the default ACCEPT credential */
+ aret = _gsskrb5_acquire_cred_from(&aminor,
+ GSS_C_NO_NAME,
+ GSS_C_INDEFINITE,
+ GSS_C_NO_OID_SET,
+ GSS_C_ACCEPT,
+ GSS_C_NO_CRED_STORE,
+ &aqcred_accept,
+ NULL,
+ NULL);
+ if (aret == GSS_S_COMPLETE) {
+ aret = _gsskrb5_inquire_cred(&aminor,
+ aqcred_accept,
+ output_name,
+ &alife,
+ NULL,
+ &amechs);
+ (void) _gsskrb5_release_cred(&junk, &aqcred_accept);
+ if (aret == GSS_S_COMPLETE) {
+ output_name = NULL; /* Can't merge names; output only one */
+ if (cred_usage)
+ *cred_usage = GSS_C_ACCEPT;
+ if (lifetime)
+ *lifetime = alife;
+ if (mechanisms) {
+ *mechanisms = amechs;
+ amechs = GSS_C_NO_OID_SET;
+ }
+ (void) gss_release_oid_set(&junk, &amechs);
+ } else if (aret != GSS_S_NO_CRED) {
+ *minor_status = aminor;
+ return aret;
+ } else {
+ alife = GSS_C_INDEFINITE;
+ }
+ }
+
+ /* Get the info for the default INITIATE credential */
+ ret = _gsskrb5_acquire_cred_from(minor_status,
+ GSS_C_NO_NAME,
+ GSS_C_INDEFINITE,
+ GSS_C_NO_OID_SET,
+ GSS_C_INITIATE,
+ GSS_C_NO_CRED_STORE,
+ &aqcred_init,
+ NULL,
+ NULL);
+ if (ret == GSS_S_COMPLETE) {
+ ret = _gsskrb5_inquire_cred(minor_status,
+ aqcred_init,
+ output_name,
+ &ilife,
+ NULL,
+ &imechs);
+ (void) _gsskrb5_release_cred(&junk, &aqcred_init);
+ if (ret == GSS_S_COMPLETE) {
+ /*
+ * Merge results for INITIATE with ACCEPT if we had ACCEPT and
+ * for those outputs that are desired.
+ */
+ if (cred_usage) {
+ *cred_usage = (*cred_usage == GSS_C_ACCEPT) ?
+ GSS_C_BOTH : GSS_C_INITIATE;
+ }
+ if (lifetime)
+ *lifetime = min(alife, ilife);
+ if (mechanisms) {
+ /*
+ * This is just one mechanism (IAKERB and such would live
+ * elsewhere). imechs will be equal to amechs, though not
+ * ==.
+ */
+ if (aret != GSS_S_COMPLETE) {
+ *mechanisms = imechs;
+ imechs = GSS_C_NO_OID_SET;
+ }
+ }
+ (void) gss_release_oid_set(&junk, &amechs);
+ } else if (ret != GSS_S_NO_CRED) {
+ *minor_status = aminor;
+ return aret;
+ }
+ }
+
+ if (aret != GSS_S_COMPLETE && ret != GSS_S_COMPLETE) {
+ *minor_status = aminor;
+ return aret;
+ }
+ *minor_status = 0; /* Even though 0 is not specified to be special */
+ return GSS_S_COMPLETE;
+ }
+
+ HEIMDAL_MUTEX_lock(&cred->cred_id_mutex);
+
+ if (output_name != NULL) {
+ if (cred->principal != NULL) {
+ gss_name_t name = (gss_name_t)cred->principal;
+ ret = _gsskrb5_duplicate_name(minor_status, name, output_name);
+ if (ret)
+ goto out;
+ } else if (cred->usage == GSS_C_ACCEPT) {
+ /*
+ * Keytab case, princ may not be set (yet, ever, whatever).
+ *
+ * We used to unconditionally output the krb5_sname_to_principal()
+ * of the host service for the hostname, but we didn't know if we
+ * had keytab entries for it, so it was incorrect. We can't be
+ * breaking anything in tree by outputting GSS_C_NO_NAME, but we
+ * might be breaking other callers.
+ */
+ *output_name = GSS_C_NO_NAME;
+ } else {
+ /* This shouldn't happen */
+ *minor_status = KRB5_NOCREDS_SUPPLIED; /* XXX */
+ ret = GSS_S_NO_CRED;
+ goto out;
+ }
+ }
+ if (lifetime != NULL) {
+ ret = _gsskrb5_lifetime_left(minor_status,
+ context,
+ cred->endtime,
+ lifetime);
+ if (ret)
+ goto out;
+ }
+ if (cred_usage != NULL)
+ *cred_usage = cred->usage;
+ if (mechanisms != NULL) {
+ ret = gss_create_empty_oid_set(minor_status, mechanisms);
+ if (ret)
+ goto out;
+ ret = gss_add_oid_set_member(minor_status,
+ &cred->mechanisms->elements[0],
+ mechanisms);
+ if (ret)
+ goto out;
+ }
+ ret = GSS_S_COMPLETE;
+
+out:
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/inquire_cred_by_mech.c b/third_party/heimdal/lib/gssapi/krb5/inquire_cred_by_mech.c
new file mode 100644
index 0000000..6ce4994
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/inquire_cred_by_mech.c
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2003, 2006, 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_cred_by_mech (
+ OM_uint32 * minor_status,
+ gss_const_cred_id_t cred_handle,
+ const gss_OID mech_type,
+ gss_name_t * name,
+ OM_uint32 * initiator_lifetime,
+ OM_uint32 * acceptor_lifetime,
+ gss_cred_usage_t * cred_usage
+ )
+{
+ gss_cred_usage_t usage;
+ OM_uint32 maj_stat;
+ OM_uint32 lifetime;
+
+ /*
+ * XXX This is busted. _gsskrb5_inquire_cred() should be implemented in
+ * terms of _gsskrb5_inquire_cred_by_mech(), NOT the other way around.
+ */
+ maj_stat =
+ _gsskrb5_inquire_cred (minor_status, cred_handle,
+ name, &lifetime, &usage, NULL);
+ if (maj_stat)
+ return maj_stat;
+
+ if (initiator_lifetime) {
+ if (usage == GSS_C_INITIATE || usage == GSS_C_BOTH)
+ *initiator_lifetime = lifetime;
+ else
+ *initiator_lifetime = 0;
+ }
+
+ if (acceptor_lifetime) {
+ if (usage == GSS_C_ACCEPT || usage == GSS_C_BOTH)
+ *acceptor_lifetime = lifetime;
+ else
+ *acceptor_lifetime = 0;
+ }
+
+ if (cred_usage)
+ *cred_usage = usage;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/inquire_cred_by_oid.c b/third_party/heimdal/lib/gssapi/krb5/inquire_cred_by_oid.c
new file mode 100644
index 0000000..7dae3d2
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/inquire_cred_by_oid.c
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2004, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_cred_by_oid
+ (OM_uint32 * minor_status,
+ gss_const_cred_id_t cred_handle,
+ const gss_OID desired_object,
+ gss_buffer_set_t *data_set)
+{
+ krb5_context context;
+ gsskrb5_cred cred = (gsskrb5_cred)cred_handle;
+ krb5_error_code ret;
+ gss_buffer_desc buffer;
+ char *str;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (gss_oid_equal(desired_object, GSS_KRB5_COPY_CCACHE_X) == 0) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ HEIMDAL_MUTEX_lock(&cred->cred_id_mutex);
+
+ if (cred->ccache == NULL) {
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_cc_get_full_name(context, cred->ccache, &str);
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ buffer.value = str;
+ buffer.length = strlen(str);
+
+ ret = gss_add_buffer_set_member(minor_status, &buffer, data_set);
+ if (ret != GSS_S_COMPLETE)
+ _gsskrb5_clear_status ();
+
+ free(str);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/krb5/inquire_mechs_for_name.c b/third_party/heimdal/lib/gssapi/krb5/inquire_mechs_for_name.c
new file mode 100644
index 0000000..c6c6746
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/inquire_mechs_for_name.c
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_mechs_for_name (
+ OM_uint32 * minor_status,
+ gss_const_name_t input_name,
+ gss_OID_set * mech_types
+ )
+{
+ OM_uint32 ret;
+
+ ret = gss_create_empty_oid_set(minor_status, mech_types);
+ if (ret)
+ return ret;
+
+ ret = gss_add_oid_set_member(minor_status,
+ GSS_KRB5_MECHANISM,
+ mech_types);
+ if (ret)
+ gss_release_oid_set(NULL, mech_types);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/inquire_names_for_mech.c b/third_party/heimdal/lib/gssapi/krb5/inquire_names_for_mech.c
new file mode 100644
index 0000000..65bd49c
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/inquire_names_for_mech.c
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+static gss_OID name_list[] = {
+ GSS_C_NT_HOSTBASED_SERVICE,
+ GSS_C_NT_USER_NAME,
+ GSS_KRB5_NT_PRINCIPAL_NAME,
+ GSS_C_NT_EXPORT_NAME,
+ NULL
+};
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_names_for_mech (
+ OM_uint32 * minor_status,
+ const gss_OID mechanism,
+ gss_OID_set * name_types
+ )
+{
+ OM_uint32 ret;
+ int i;
+
+ *minor_status = 0;
+
+ if (gss_oid_equal(mechanism, GSS_KRB5_MECHANISM) == 0 &&
+ gss_oid_equal(mechanism, GSS_C_NULL_OID) == 0) {
+ *name_types = GSS_C_NO_OID_SET;
+ return GSS_S_BAD_MECH;
+ }
+
+ ret = gss_create_empty_oid_set(minor_status, name_types);
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+
+ for (i = 0; name_list[i] != NULL; i++) {
+ ret = gss_add_oid_set_member(minor_status,
+ name_list[i],
+ name_types);
+ if (ret != GSS_S_COMPLETE)
+ break;
+ }
+
+ if (ret != GSS_S_COMPLETE)
+ gss_release_oid_set(NULL, name_types);
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/inquire_sec_context_by_oid.c b/third_party/heimdal/lib/gssapi/krb5/inquire_sec_context_by_oid.c
new file mode 100644
index 0000000..f572774
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/inquire_sec_context_by_oid.c
@@ -0,0 +1,598 @@
+/*
+ * Copyright (c) 2004, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+static int
+oid_prefix_equal(gss_OID oid_enc, gss_OID prefix_enc, unsigned *suffix)
+{
+ int ret;
+ heim_oid oid;
+ heim_oid prefix;
+
+ *suffix = 0;
+
+ ret = der_get_oid(oid_enc->elements, oid_enc->length,
+ &oid, NULL);
+ if (ret) {
+ return 0;
+ }
+
+ ret = der_get_oid(prefix_enc->elements, prefix_enc->length,
+ &prefix, NULL);
+ if (ret) {
+ der_free_oid(&oid);
+ return 0;
+ }
+
+ ret = 0;
+
+ if (oid.length - 1 == prefix.length) {
+ *suffix = oid.components[oid.length - 1];
+ oid.length--;
+ ret = (der_heim_oid_cmp(&oid, &prefix) == 0);
+ oid.length++;
+ }
+
+ der_free_oid(&oid);
+ der_free_oid(&prefix);
+
+ return ret;
+}
+
+static OM_uint32 inquire_sec_context_tkt_flags
+ (OM_uint32 *minor_status,
+ const gsskrb5_ctx context_handle,
+ gss_buffer_set_t *data_set)
+{
+ OM_uint32 tkt_flags;
+ unsigned char buf[4];
+ gss_buffer_desc value;
+
+ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+
+ if (context_handle->ticket == NULL) {
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ _gsskrb5_set_status(EINVAL, "No ticket from which to obtain flags");
+ *minor_status = EINVAL;
+ return GSS_S_BAD_MECH;
+ }
+
+ tkt_flags = TicketFlags2int(context_handle->ticket->ticket.flags);
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+
+ _gsskrb5_encode_om_uint32(tkt_flags, buf);
+ value.length = sizeof(buf);
+ value.value = buf;
+
+ return gss_add_buffer_set_member(minor_status,
+ &value,
+ data_set);
+}
+
+enum keytype { ACCEPTOR_KEY, INITIATOR_KEY, TOKEN_KEY };
+
+static OM_uint32 inquire_sec_context_get_subkey
+ (OM_uint32 *minor_status,
+ const gsskrb5_ctx context_handle,
+ krb5_context context,
+ enum keytype keytype,
+ gss_buffer_set_t *data_set)
+{
+ krb5_keyblock *key = NULL;
+ krb5_storage *sp = NULL;
+ krb5_data data;
+ OM_uint32 maj_stat = GSS_S_COMPLETE;
+ krb5_error_code ret;
+
+ krb5_data_zero(&data);
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ _gsskrb5_clear_status();
+ ret = ENOMEM;
+ goto out;
+ }
+
+ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+ switch(keytype) {
+ case ACCEPTOR_KEY:
+ ret = _gsskrb5i_get_acceptor_subkey(context_handle, context, &key);
+ break;
+ case INITIATOR_KEY:
+ ret = _gsskrb5i_get_initiator_subkey(context_handle, context, &key);
+ break;
+ case TOKEN_KEY:
+ ret = _gsskrb5i_get_token_key(context_handle, context, &key);
+ break;
+ default:
+ _gsskrb5_set_status(EINVAL, "%d is not a valid subkey type", keytype);
+ ret = EINVAL;
+ break;
+ }
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ if (ret)
+ goto out;
+ if (key == NULL) {
+ _gsskrb5_set_status(EINVAL, "have no subkey of type %d", keytype);
+ ret = EINVAL;
+ goto out;
+ }
+
+ ret = krb5_store_keyblock(sp, *key);
+ if (ret)
+ goto out;
+
+ ret = krb5_storage_to_data(sp, &data);
+ if (ret)
+ goto out;
+
+ {
+ gss_buffer_desc value;
+
+ value.length = data.length;
+ value.value = data.data;
+
+ maj_stat = gss_add_buffer_set_member(minor_status,
+ &value,
+ data_set);
+ }
+
+out:
+ krb5_free_keyblock(context, key);
+ krb5_data_free(&data);
+ if (sp)
+ krb5_storage_free(sp);
+ if (ret) {
+ *minor_status = ret;
+ maj_stat = GSS_S_FAILURE;
+ }
+ return maj_stat;
+}
+
+static OM_uint32 inquire_sec_context_get_sspi_session_key
+ (OM_uint32 *minor_status,
+ const gsskrb5_ctx context_handle,
+ krb5_context context,
+ gss_buffer_set_t *data_set)
+{
+ krb5_keyblock *key;
+ OM_uint32 maj_stat = GSS_S_COMPLETE;
+ krb5_error_code ret;
+ gss_buffer_desc value;
+
+ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+ ret = _gsskrb5i_get_token_key(context_handle, context, &key);
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+
+ if (ret)
+ goto out;
+ if (key == NULL) {
+ ret = EINVAL;
+ goto out;
+ }
+
+ value.length = key->keyvalue.length;
+ value.value = key->keyvalue.data;
+
+ maj_stat = gss_add_buffer_set_member(minor_status,
+ &value,
+ data_set);
+ krb5_free_keyblock(context, key);
+
+ /* MIT also returns the enctype encoded as an OID in data_set[1] */
+
+out:
+ if (ret) {
+ *minor_status = ret;
+ maj_stat = GSS_S_FAILURE;
+ }
+ return maj_stat;
+}
+
+static OM_uint32 inquire_sec_context_authz_data
+ (OM_uint32 *minor_status,
+ const gsskrb5_ctx context_handle,
+ krb5_context context,
+ unsigned ad_type,
+ gss_buffer_set_t *data_set)
+{
+ krb5_data data;
+ gss_buffer_desc ad_data;
+ OM_uint32 ret;
+
+ *minor_status = 0;
+ *data_set = GSS_C_NO_BUFFER_SET;
+
+ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+ if (context_handle->ticket == NULL) {
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ *minor_status = EINVAL;
+ _gsskrb5_set_status(EINVAL, "No ticket to obtain authz data from");
+ return GSS_S_NO_CONTEXT;
+ }
+
+ ret = krb5_ticket_get_authorization_data_type(context,
+ context_handle->ticket,
+ ad_type,
+ &data);
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ad_data.value = data.data;
+ ad_data.length = data.length;
+
+ ret = gss_add_buffer_set_member(minor_status,
+ &ad_data,
+ data_set);
+
+ krb5_data_free(&data);
+
+ return ret;
+}
+
+static OM_uint32 inquire_sec_context_has_buggy_spnego
+ (OM_uint32 *minor_status,
+ const gsskrb5_ctx context_handle,
+ gss_buffer_set_t *data_set)
+{
+ uint8_t old_enctype;
+ gss_buffer_desc buffer;
+
+ *minor_status = 0;
+ *data_set = GSS_C_NO_BUFFER_SET;
+
+ /*
+ * For Windows SPNEGO implementations, the initiator or acceptor
+ * are presumed to be "buggy" (Windows 2003 or earlier) if an
+ * "older" (i.e. pre-AES per RFC 4121) encryption type was used.
+ */
+
+ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+ old_enctype = ((context_handle->more_flags & IS_CFX) == 0);
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+
+ buffer.value = &old_enctype;
+ buffer.length = sizeof(old_enctype);
+
+ return gss_add_buffer_set_member(minor_status, &buffer, data_set);
+}
+
+/*
+ *
+ */
+
+static OM_uint32
+export_lucid_sec_context_v1(OM_uint32 *minor_status,
+ gsskrb5_ctx context_handle,
+ krb5_context context,
+ gss_buffer_set_t *data_set)
+{
+ krb5_storage *sp = NULL;
+ OM_uint32 major_status = GSS_S_COMPLETE;
+ krb5_error_code ret;
+ krb5_keyblock *key = NULL;
+ int32_t number;
+ int is_cfx;
+ krb5_data data;
+
+ *minor_status = 0;
+
+ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+
+ is_cfx = (context_handle->more_flags & IS_CFX);
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ _gsskrb5_clear_status();
+ ret = ENOMEM;
+ goto out;
+ }
+
+ ret = krb5_store_int32(sp, 1);
+ if (ret) goto out;
+ ret = krb5_store_int32(sp, (context_handle->more_flags & LOCAL) ? 1 : 0);
+ if (ret) goto out;
+ /* XXX need krb5_store_int64() */
+ ret = krb5_store_int32(sp, context_handle->endtime);
+ if (ret) goto out;
+ krb5_auth_con_getlocalseqnumber (context,
+ context_handle->auth_context,
+ &number);
+ ret = krb5_store_uint32(sp, (uint32_t)0); /* store top half as zero */
+ if (ret) goto out;
+ ret = krb5_store_uint32(sp, (uint32_t)number);
+ if (ret) goto out;
+ krb5_auth_con_getremoteseqnumber (context,
+ context_handle->auth_context,
+ &number);
+ ret = krb5_store_uint32(sp, (uint32_t)0); /* store top half as zero */
+ if (ret) goto out;
+ ret = krb5_store_uint32(sp, (uint32_t)number);
+ if (ret) goto out;
+ ret = krb5_store_int32(sp, (is_cfx) ? 1 : 0);
+ if (ret) goto out;
+
+ ret = _gsskrb5i_get_token_key(context_handle, context, &key);
+ if (ret) goto out;
+
+ if (is_cfx == 0) {
+ int sign_alg, seal_alg;
+
+ switch (key->keytype) {
+ case ETYPE_DES_CBC_CRC:
+ case ETYPE_DES_CBC_MD4:
+ case ETYPE_DES_CBC_MD5:
+ sign_alg = 0;
+ seal_alg = 0;
+ break;
+ case ETYPE_DES3_CBC_MD5:
+ case ETYPE_DES3_CBC_SHA1:
+ sign_alg = 4;
+ seal_alg = 2;
+ break;
+ case ETYPE_ARCFOUR_HMAC_MD5:
+ case ETYPE_ARCFOUR_HMAC_MD5_56:
+ sign_alg = 17;
+ seal_alg = 16;
+ break;
+ default:
+ sign_alg = -1;
+ seal_alg = -1;
+ break;
+ }
+ ret = krb5_store_int32(sp, sign_alg);
+ if (ret) goto out;
+ ret = krb5_store_int32(sp, seal_alg);
+ if (ret) goto out;
+ /* ctx_key */
+ ret = krb5_store_keyblock(sp, *key);
+ if (ret) goto out;
+ } else {
+ int subkey_p = (context_handle->more_flags & ACCEPTOR_SUBKEY) ? 1 : 0;
+
+ /* have_acceptor_subkey */
+ ret = krb5_store_int32(sp, subkey_p);
+ if (ret) goto out;
+ /* ctx_key */
+ ret = krb5_store_keyblock(sp, *key);
+ if (ret) goto out;
+ /* acceptor_subkey */
+ if (subkey_p) {
+ ret = krb5_store_keyblock(sp, *key);
+ if (ret) goto out;
+ }
+ }
+ ret = krb5_storage_to_data(sp, &data);
+ if (ret) goto out;
+
+ {
+ gss_buffer_desc ad_data;
+
+ ad_data.value = data.data;
+ ad_data.length = data.length;
+
+ ret = gss_add_buffer_set_member(minor_status, &ad_data, data_set);
+ krb5_data_free(&data);
+ if (ret)
+ goto out;
+ }
+
+out:
+ if (key)
+ krb5_free_keyblock (context, key);
+ if (sp)
+ krb5_storage_free(sp);
+ if (ret) {
+ *minor_status = ret;
+ major_status = GSS_S_FAILURE;
+ }
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ return major_status;
+}
+
+static OM_uint32
+get_authtime(OM_uint32 *minor_status,
+ gsskrb5_ctx ctx,
+ gss_buffer_set_t *data_set)
+
+{
+ gss_buffer_desc value;
+ unsigned char buf[4];
+ OM_uint32 authtime;
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ if (ctx->ticket == NULL) {
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ _gsskrb5_set_status(EINVAL, "No ticket to obtain auth time from");
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ authtime = ctx->ticket->ticket.authtime;
+
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ _gsskrb5_encode_om_uint32(authtime, buf);
+ value.length = sizeof(buf);
+ value.value = buf;
+
+ return gss_add_buffer_set_member(minor_status,
+ &value,
+ data_set);
+}
+
+
+static OM_uint32
+get_service_keyblock
+ (OM_uint32 *minor_status,
+ gsskrb5_ctx ctx,
+ gss_buffer_set_t *data_set)
+{
+ krb5_storage *sp = NULL;
+ krb5_data data;
+ OM_uint32 maj_stat = GSS_S_COMPLETE;
+ krb5_error_code ret = EINVAL;
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ _gsskrb5_clear_status();
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ if (ctx->service_keyblock == NULL) {
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ krb5_storage_free(sp);
+ _gsskrb5_set_status(EINVAL, "No service keyblock on gssapi context");
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ krb5_data_zero(&data);
+
+ ret = krb5_store_keyblock(sp, *ctx->service_keyblock);
+
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ if (ret)
+ goto out;
+
+ ret = krb5_storage_to_data(sp, &data);
+ if (ret)
+ goto out;
+
+ {
+ gss_buffer_desc value;
+
+ value.length = data.length;
+ value.value = data.data;
+
+ maj_stat = gss_add_buffer_set_member(minor_status,
+ &value,
+ data_set);
+ }
+
+out:
+ krb5_data_free(&data);
+ if (sp)
+ krb5_storage_free(sp);
+ if (ret) {
+ *minor_status = ret;
+ maj_stat = GSS_S_FAILURE;
+ }
+ return maj_stat;
+}
+/*
+ *
+ */
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_sec_context_by_oid
+ (OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_OID desired_object,
+ gss_buffer_set_t *data_set)
+{
+ krb5_context context;
+ const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle;
+ unsigned suffix;
+
+ if (ctx == NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (gss_oid_equal(desired_object, GSS_KRB5_GET_TKT_FLAGS_X)) {
+ return inquire_sec_context_tkt_flags(minor_status,
+ ctx,
+ data_set);
+ } else if (gss_oid_equal(desired_object, GSS_C_INQ_PEER_HAS_BUGGY_SPNEGO)) {
+ return inquire_sec_context_has_buggy_spnego(minor_status,
+ ctx,
+ data_set);
+ } else if (gss_oid_equal(desired_object, GSS_KRB5_GET_SUBKEY_X)) {
+ return inquire_sec_context_get_subkey(minor_status,
+ ctx,
+ context,
+ TOKEN_KEY,
+ data_set);
+ } else if (gss_oid_equal(desired_object, GSS_KRB5_GET_INITIATOR_SUBKEY_X)) {
+ return inquire_sec_context_get_subkey(minor_status,
+ ctx,
+ context,
+ INITIATOR_KEY,
+ data_set);
+ } else if (gss_oid_equal(desired_object, GSS_KRB5_GET_ACCEPTOR_SUBKEY_X)) {
+ return inquire_sec_context_get_subkey(minor_status,
+ ctx,
+ context,
+ ACCEPTOR_KEY,
+ data_set);
+ } else if (gss_oid_equal(desired_object, GSS_C_INQ_SSPI_SESSION_KEY)) {
+ return inquire_sec_context_get_sspi_session_key(minor_status,
+ ctx,
+ context,
+ data_set);
+ } else if (gss_oid_equal(desired_object, GSS_KRB5_GET_AUTHTIME_X)) {
+ return get_authtime(minor_status, ctx, data_set);
+ } else if (oid_prefix_equal(desired_object,
+ GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X,
+ &suffix)) {
+ return inquire_sec_context_authz_data(minor_status,
+ ctx,
+ context,
+ suffix,
+ data_set);
+ } else if (oid_prefix_equal(desired_object,
+ GSS_KRB5_EXPORT_LUCID_CONTEXT_X,
+ &suffix)) {
+ if (suffix == 1)
+ return export_lucid_sec_context_v1(minor_status,
+ ctx,
+ context,
+ data_set);
+ *minor_status = 0;
+ return GSS_S_FAILURE;
+ } else if (gss_oid_equal(desired_object, GSS_KRB5_GET_SERVICE_KEYBLOCK_X)) {
+ return get_service_keyblock(minor_status, ctx, data_set);
+ } else {
+ *minor_status = 0;
+ return GSS_S_FAILURE;
+ }
+}
+
diff --git a/third_party/heimdal/lib/gssapi/krb5/name_attrs.c b/third_party/heimdal/lib/gssapi/krb5/name_attrs.c
new file mode 100644
index 0000000..11fc2ef
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/name_attrs.c
@@ -0,0 +1,1171 @@
+/*
+ * Copyright (c) 2021 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+/*
+ * (Not-yet-)Standard name attributes for Kerberos MNs,
+ * GSS_KRB5_NAME_ATTRIBUTE_BASE_URN + "...".
+ *
+ * I.e., "urn:ietf:kerberos:nameattr-...". (XXX Register this URN namespace
+ * with IANA.)
+ *
+ * Note that we do use URN fragments.
+ *
+ * Specific attributes below the base URN:
+ *
+ * - name access attributes:
+ * - "realm" -> realm of name
+ * - "name-ncomp" -> count of name components
+ * - "name-ncomp#<digit>" -> name component N (0 <= N <= 9)
+ *
+ * Ticket and Authenticator access attributes:
+ *
+ * - "transit-path" -> encoding of the transited path
+ * - "authenticator-authz-data" -> encoding of all of the authz-data from
+ * the AP-REQ's Authenticator
+ * - "ticket-authz-data" -> encoding of all of the authz-data from
+ * the AP-REQ's Ticket
+ * - "ticket-authz-data#pac" -> the PAC
+ * - "authz-data#<N>" -> encoding of all of a specific auth-data
+ * element type N (e.g., 2, meaning
+ * AD-INTENDED-FOR-SERVER)
+ *
+ * Misc. attributes:
+ *
+ * - "peer-realm" -> name of peer's realm (if this is an MN
+ * resulting for establishing a security
+ * context)
+ * - "canonical-name" -> exported name token and RFC1964 display
+ * syntax of the name's canonical name
+ *
+ * Compatibility with MIT:
+ *
+ * - "urn:mspac:" -> the PAC and its individual info buffers
+ *
+ * TODO:
+ *
+ * - Add some sort of display syntax for transit path
+ * - Add support for URN q-components or attribute prefixes to specify
+ * alternative raw and/or display value encodings (JSON?)
+ * - Add support for attributes for accessing other parts of the Ticket / KDC
+ * reply enc-parts, like auth times
+ * - Add support for getting PAC logon fields, including SIDs (one at a time)
+ * - Add support for CAMMAC?
+ */
+
+static int
+attr_eq(gss_const_buffer_t attr, const char *aname, size_t aname_len, \
+ int prefix_check)
+{
+ if (attr->length < aname_len)
+ return 0;
+
+ if (strncmp((char *)attr->value, aname, aname_len) != 0)
+ return 0;
+
+ return prefix_check || attr->length == aname_len;
+}
+
+#define ATTR_EQ(a, an) (attr_eq(a, an, sizeof(an) - 1, FALSE))
+#define ATTR_EQ_PREFIX(a, an) (attr_eq(a, an, sizeof(an) - 1, TRUE))
+
+/* Split attribute into prefix, suffix, and fragment. See RFC6680. */
+static void
+split_attr(gss_const_buffer_t orig,
+ gss_buffer_t prefix,
+ gss_buffer_t attr,
+ gss_buffer_t frag,
+ int *is_urn)
+{
+ char *last = NULL;
+ char *p = orig->value;
+
+ *attr = *orig;
+ prefix->value = orig->value;
+ prefix->length = 0;
+ frag->length = 0;
+ frag->value = NULL;
+
+ /* FIXME We don't have a memrchr() in lib/roken */
+ for (p = memchr(p, ' ', orig->length);
+ p;
+ p = memchr(p + 1, ' ', orig->length)) {
+ last = p;
+ prefix->length = last - (const char *)orig->value;
+ attr->value = last + 1;
+ attr->length = orig->length - (prefix->length + 1);
+ }
+ if (prefix->length == 0)
+ prefix->value = NULL;
+
+ if ((*is_urn = (strncmp(attr->value, "urn:", sizeof("urn:") - 1) == 0)) &&
+ (p = memchr((char *)attr->value + 1, '#', attr->length - 1))) {
+ frag->value = ++p;
+ frag->length = attr->length - (p - (const char *)attr->value);
+ attr->length = --p - (const char *)attr->value;
+ }
+}
+
+typedef OM_uint32 get_name_attr_f(OM_uint32 *,
+ const CompositePrincipal *,
+ gss_const_buffer_t,
+ gss_const_buffer_t,
+ gss_const_buffer_t,
+ int *,
+ int *,
+ gss_buffer_t,
+ gss_buffer_t,
+ int *);
+
+typedef OM_uint32 set_name_attr_f(OM_uint32 *,
+ CompositePrincipal *,
+ gss_const_buffer_t,
+ gss_const_buffer_t,
+ gss_const_buffer_t,
+ int,
+ gss_buffer_t);
+
+typedef OM_uint32 del_name_attr_f(OM_uint32 *,
+ CompositePrincipal *,
+ gss_const_buffer_t,
+ gss_const_buffer_t,
+ gss_const_buffer_t);
+typedef get_name_attr_f *get_name_attr_fp;
+typedef set_name_attr_f *set_name_attr_fp;
+typedef del_name_attr_f *del_name_attr_fp;
+
+static get_name_attr_f get_realm;
+static get_name_attr_f get_ncomps;
+static get_name_attr_f get_peer_realm;
+static get_name_attr_f get_pac;
+static get_name_attr_f get_pac_buffer;
+static get_name_attr_f get_authz_data;
+static get_name_attr_f get_ticket_authz_data;
+static get_name_attr_f get_authenticator_authz_data;
+static set_name_attr_f set_authenticator_authz_data;
+static get_name_attr_f get_transited;
+static get_name_attr_f get_canonical_name;
+
+#define NB(n) \
+ GSS_KRB5_NAME_ATTRIBUTE_BASE_URN n, n, \
+ sizeof(GSS_KRB5_NAME_ATTRIBUTE_BASE_URN n) - 1, \
+ sizeof(n) - 1
+#define NM(n) \
+ "urn:mspac:" n, n, sizeof("urn:mspac:" n) - 1, sizeof(n) - 1
+
+static struct krb5_name_attrs {
+ const char *fullname;
+ const char *name;
+ size_t fullnamelen;
+ size_t namelen;
+ get_name_attr_fp getter;
+ set_name_attr_fp setter;
+ del_name_attr_fp deleter;
+ unsigned int indicate:1;
+ unsigned int is_krb5_name_attr_urn:1;
+} name_attrs[] = {
+ /* XXX We should sort these so we can binary search them */
+ { NB("realm"), get_realm, NULL, NULL, 1, 1 },
+ { NB("name-ncomp"), get_ncomps, NULL, NULL, 1, 1 },
+ { NB("name-ncomp#0"), get_ncomps, NULL, NULL, 1, 1 },
+ { NB("name-ncomp#1"), get_ncomps, NULL, NULL, 1, 1 },
+ { NB("name-ncomp#2"), get_ncomps, NULL, NULL, 1, 1 },
+ { NB("name-ncomp#3"), get_ncomps, NULL, NULL, 1, 1 },
+ { NB("name-ncomp#4"), get_ncomps, NULL, NULL, 1, 1 },
+ { NB("name-ncomp#5"), get_ncomps, NULL, NULL, 1, 1 },
+ { NB("name-ncomp#6"), get_ncomps, NULL, NULL, 1, 1 },
+ { NB("name-ncomp#7"), get_ncomps, NULL, NULL, 1, 1 },
+ { NB("name-ncomp#8"), get_ncomps, NULL, NULL, 1, 1 },
+ { NB("name-ncomp#9"), get_ncomps, NULL, NULL, 1, 1 },
+ { NB("peer-realm"), get_peer_realm, NULL, NULL, 1, 1 },
+ { NB("ticket-authz-data#pac"), get_pac, NULL, NULL, 1, 1 },
+ { NM(""), get_pac, NULL, NULL, 1, 0 },
+ { NM("logon-info"), get_pac_buffer, NULL, NULL, 1, 0 },
+ { NM("credentials-info"), get_pac_buffer, NULL, NULL, 1, 0 },
+ { NM("server-checksum"), get_pac_buffer, NULL, NULL, 1, 0 },
+ { NM("privsvr-checksum"), get_pac_buffer, NULL, NULL, 1, 0 },
+ { NM("client-info"), get_pac_buffer, NULL, NULL, 1, 0 },
+ { NM("delegation-info"), get_pac_buffer, NULL, NULL, 1, 0 },
+ { NM("upn-dns-info"), get_pac_buffer, NULL, NULL, 1, 0 },
+ { NM("ticket-checksum"), get_pac_buffer, NULL, NULL, 1, 0 },
+ { NM("attributes-info"), get_pac_buffer, NULL, NULL, 1, 0 },
+ { NM("requestor-sid"), get_pac_buffer, NULL, NULL, 1, 0 },
+ { NB("ticket-authz-data#kdc-issued"),
+ get_ticket_authz_data, NULL, NULL, 1, 1 },
+ { NB("ticket-authz-data"),
+ get_ticket_authz_data, NULL, NULL, 1, 1 },
+ { NB("authenticator-authz-data"),
+ get_authenticator_authz_data,
+ set_authenticator_authz_data, NULL, 1, 1 },
+ { NB("authz-data"), get_authz_data, NULL, NULL, 1, 1 },
+ { NB("transit-path"), get_transited, NULL, NULL, 1, 1 },
+ { NB("canonical-name"), get_canonical_name, NULL, NULL, 1, 1 },
+};
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_get_name_attribute(OM_uint32 *minor_status,
+ gss_name_t name,
+ gss_buffer_t original_attr,
+ int *authenticated,
+ int *complete,
+ gss_buffer_t value,
+ gss_buffer_t display_value,
+ int *more)
+{
+ gss_buffer_desc prefix, attr, suffix, frag;
+ size_t i;
+ int is_krb5_name_attr_urn = 0;
+ int is_urn = 0;
+
+ *minor_status = 0;
+ if (authenticated)
+ *authenticated = 0;
+ if (complete)
+ *complete = 0;
+ if (more)
+ *more = 0;
+ if (value) {
+ value->length = 0;
+ value->value = NULL;
+ }
+ if (display_value) {
+ display_value->length = 0;
+ display_value->value = NULL;
+ }
+
+ suffix.value = NULL;
+ suffix.length = 0;
+
+ split_attr(original_attr, &prefix, &attr, &frag, &is_urn);
+
+ if (prefix.length || !is_urn)
+ return GSS_S_UNAVAILABLE;
+
+ is_krb5_name_attr_urn =
+ ATTR_EQ_PREFIX(&attr, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN);
+ if (is_krb5_name_attr_urn) {
+ suffix.value =
+ (char *)attr.value + sizeof(GSS_KRB5_NAME_ATTRIBUTE_BASE_URN) - 1;
+ suffix.length = attr.length - (sizeof(GSS_KRB5_NAME_ATTRIBUTE_BASE_URN) - 1);
+ }
+
+ for (i = 0; i < sizeof(name_attrs)/sizeof(name_attrs[0]); i++) {
+ if (!name_attrs[i].getter)
+ continue;
+ if (name_attrs[i].is_krb5_name_attr_urn && is_krb5_name_attr_urn) {
+ if (!attr_eq(&suffix, name_attrs[i].name, name_attrs[i].namelen, 0))
+ continue;
+ } else if (!name_attrs[i].is_krb5_name_attr_urn && !is_krb5_name_attr_urn) {
+ if (!attr_eq(&attr, name_attrs[i].fullname, name_attrs[i].fullnamelen, 0))
+ continue;
+ } else
+ continue;
+
+ return name_attrs[i].getter(minor_status,
+ (const CompositePrincipal *)name,
+ &prefix, &attr, &frag, authenticated,
+ complete, value, display_value, more);
+ }
+ return GSS_S_UNAVAILABLE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_set_name_attribute(OM_uint32 *minor_status,
+ gss_name_t name,
+ int complete,
+ gss_buffer_t original_attr,
+ gss_buffer_t value)
+{
+ gss_buffer_desc prefix, attr, suffix, frag;
+ size_t i;
+ int is_krb5_name_attr_urn = 0;
+ int is_urn = 0;
+
+ *minor_status = 0;
+
+ suffix.value = NULL;
+ suffix.length = 0;
+
+ split_attr(original_attr, &prefix, &attr, &frag, &is_urn);
+
+ if (prefix.length || !is_urn)
+ return GSS_S_UNAVAILABLE;
+
+ is_krb5_name_attr_urn =
+ ATTR_EQ_PREFIX(&attr, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN);
+ if (is_krb5_name_attr_urn) {
+ suffix.value =
+ (char *)attr.value + sizeof(GSS_KRB5_NAME_ATTRIBUTE_BASE_URN) - 1;
+ suffix.length = attr.length - (sizeof(GSS_KRB5_NAME_ATTRIBUTE_BASE_URN) - 1);
+ }
+
+ for (i = 0; i < sizeof(name_attrs)/sizeof(name_attrs[0]); i++) {
+ if (!name_attrs[i].setter)
+ continue;
+ if (name_attrs[i].is_krb5_name_attr_urn && is_krb5_name_attr_urn) {
+ if (!attr_eq(&suffix, name_attrs[i].name, name_attrs[i].namelen, 0))
+ continue;
+ } else if (!name_attrs[i].is_krb5_name_attr_urn && !is_krb5_name_attr_urn) {
+ if (!attr_eq(&attr, name_attrs[i].name, name_attrs[i].namelen, 0))
+ continue;
+ } else
+ continue;
+
+ return name_attrs[i].setter(minor_status, (CompositePrincipal *)name,
+ &prefix, &attr, &frag, complete, value);
+ }
+ return GSS_S_UNAVAILABLE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_delete_name_attribute(OM_uint32 *minor_status,
+ gss_name_t name,
+ gss_buffer_t original_attr)
+{
+ gss_buffer_desc prefix, attr, suffix, frag;
+ size_t i;
+ int is_krb5_name_attr_urn = 0;
+ int is_urn = 0;
+
+ *minor_status = 0;
+
+ suffix.value = NULL;
+ suffix.length = 0;
+
+ split_attr(original_attr, &prefix, &attr, &frag, &is_urn);
+
+ if (prefix.length || !is_urn)
+ return GSS_S_UNAVAILABLE;
+
+ is_krb5_name_attr_urn =
+ ATTR_EQ_PREFIX(&attr, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN);
+ if (is_krb5_name_attr_urn) {
+ suffix.value =
+ (char *)attr.value + sizeof(GSS_KRB5_NAME_ATTRIBUTE_BASE_URN) - 1;
+ suffix.length = attr.length - (sizeof(GSS_KRB5_NAME_ATTRIBUTE_BASE_URN) - 1);
+ }
+
+ for (i = 0; i < sizeof(name_attrs)/sizeof(name_attrs[0]); i++) {
+ if (!name_attrs[i].deleter)
+ continue;
+ if (name_attrs[i].is_krb5_name_attr_urn && is_krb5_name_attr_urn) {
+ if (!attr_eq(&suffix, name_attrs[i].name, name_attrs[i].namelen, 0))
+ continue;
+ } else if (!name_attrs[i].is_krb5_name_attr_urn && !is_krb5_name_attr_urn) {
+ if (!attr_eq(&attr, name_attrs[i].fullname, name_attrs[i].fullnamelen, 0))
+ continue;
+ } else
+ continue;
+
+ return name_attrs[i].deleter(minor_status, (CompositePrincipal *)name,
+ &prefix, &attr, &frag);
+ }
+ return GSS_S_UNAVAILABLE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_inquire_name(OM_uint32 *minor_status,
+ gss_name_t name,
+ int *name_is_MN,
+ gss_OID *MN_mech,
+ gss_buffer_set_t *attrs)
+{
+ gss_buffer_desc prefix, attr, frag, a;
+ OM_uint32 major = GSS_S_UNAVAILABLE;
+ size_t i;
+ int authenticated, is_urn;
+
+ *minor_status = 0;
+ if (name_is_MN)
+ *name_is_MN = 1;
+ if (MN_mech)
+ *MN_mech = GSS_KRB5_MECHANISM;
+ if (name == GSS_C_NO_NAME)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+ if (attrs == NULL)
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+
+ for (i = 0; i < sizeof(name_attrs)/sizeof(name_attrs[0]); i++) {
+ if (!name_attrs[i].indicate)
+ continue;
+ a.value = (void *)(uintptr_t)name_attrs[i].fullname;
+ a.length = name_attrs[i].fullnamelen;
+ split_attr(&a, &prefix, &attr, &frag, &is_urn);
+ major = name_attrs[i].getter(minor_status,
+ (const CompositePrincipal *)name,
+ &prefix, &attr, &frag, &authenticated,
+ NULL, NULL, NULL, NULL);
+ if (major == GSS_S_UNAVAILABLE)
+ continue;
+ if (major != GSS_S_COMPLETE)
+ break;
+ major = gss_add_buffer_set_member(minor_status, &a, attrs);
+ }
+ if (major == GSS_S_UNAVAILABLE)
+ major = GSS_S_COMPLETE;
+ return major;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_display_name_ext(OM_uint32 *minor_status,
+ gss_name_t name,
+ gss_OID display_as_name_type,
+ gss_buffer_t display_name)
+{
+ krb5_const_principal p = (void *)name;
+ char *s = NULL;
+
+ *minor_status = 0;
+ if (display_name == NULL)
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+ display_name->length = 0;
+ display_name->value = NULL;
+
+ if (gss_oid_equal(display_as_name_type, GSS_C_NT_USER_NAME)) {
+ if (p->name.name_string.len != 1)
+ return GSS_S_UNAVAILABLE;
+ return _gsskrb5_localname(minor_status, name, GSS_KRB5_MECHANISM,
+ display_name);
+ }
+ if (!gss_oid_equal(display_as_name_type, GSS_C_NT_HOSTBASED_SERVICE) ||
+ p->name.name_string.len != 2 ||
+ strchr(p->name.name_string.val[0], '@') ||
+ strchr(p->name.name_string.val[1], '.') == NULL)
+ return GSS_S_UNAVAILABLE;
+ if (asprintf(&s, "%s@%s", p->name.name_string.val[0],
+ p->name.name_string.val[1]) == -1 || s == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ display_name->length = strlen(s);
+ display_name->value = s;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_export_name_composite(OM_uint32 *minor_status,
+ gss_name_t name,
+ gss_buffer_t exported_name)
+{
+ krb5_error_code kret;
+ gss_buffer_desc inner = GSS_C_EMPTY_BUFFER;
+ unsigned char *buf;
+ size_t sz;
+
+ if (name == NULL)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+ if (exported_name == NULL)
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+
+ ASN1_MALLOC_ENCODE(CompositePrincipal, inner.value, inner.length,
+ (void *)name, &sz, kret);
+ if (kret != 0) {
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+ }
+
+ exported_name->length = 10 + inner.length + GSS_KRB5_MECHANISM->length;
+ exported_name->value = malloc(exported_name->length);
+ if (exported_name->value == NULL) {
+ free(inner.value);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ /* TOK, MECH_OID_LEN, DER(MECH_OID), NAME_LEN, NAME */
+
+ buf = exported_name->value;
+ buf[0] = 0x04;
+ buf[1] = 0x02;
+ buf[2] = ((GSS_KRB5_MECHANISM->length + 2) >> 8) & 0xff;
+ buf[3] = (GSS_KRB5_MECHANISM->length + 2) & 0xff;
+ buf[4] = 0x06;
+ buf[5] = (GSS_KRB5_MECHANISM->length) & 0xFF;
+
+ memcpy(buf + 6, GSS_KRB5_MECHANISM->elements, GSS_KRB5_MECHANISM->length);
+ buf += 6 + GSS_KRB5_MECHANISM->length;
+
+ buf[0] = (inner.length >> 24) & 0xff;
+ buf[1] = (inner.length >> 16) & 0xff;
+ buf[2] = (inner.length >> 8) & 0xff;
+ buf[3] = (inner.length) & 0xff;
+ buf += 4;
+
+ memcpy(buf, inner.value, inner.length);
+ free(inner.value);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+#define CHECK_ENOMEM(v, dv) \
+ do { \
+ if (((v) && !(v)->value) || ((dv) && !(dv)->value)) { \
+ if ((v) && (v)->value) { \
+ free((v)->value); \
+ (v)->length = 0; \
+ (v)->value = NULL; \
+ } \
+ *minor_status = ENOMEM; \
+ return GSS_S_FAILURE; \
+ } \
+ } while (0)
+
+static OM_uint32
+get_realm(OM_uint32 *minor_status,
+ const CompositePrincipal *name,
+ gss_const_buffer_t prefix,
+ gss_const_buffer_t attr,
+ gss_const_buffer_t frag,
+ int *authenticated,
+ int *complete,
+ gss_buffer_t value,
+ gss_buffer_t display_value,
+ int *more)
+{
+ PrincipalNameAttrs *nameattrs = name->nameattrs;
+
+ if (prefix->length || frag->length || !name->realm)
+ return GSS_S_UNAVAILABLE;
+ if (authenticated && nameattrs && nameattrs->authenticated)
+ *authenticated = 1;
+ if (complete)
+ *complete = 1;
+ if (value && (value->value = strdup(name->realm)))
+ value->length = strlen(name->realm);
+ if (display_value && (display_value->value = strdup(name->realm)))
+ display_value->length = strlen(name->realm);
+ CHECK_ENOMEM(value, display_value);
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+get_ncomps(OM_uint32 *minor_status,
+ const CompositePrincipal *name,
+ gss_const_buffer_t prefix,
+ gss_const_buffer_t attr,
+ gss_const_buffer_t frag,
+ int *authenticated,
+ int *complete,
+ gss_buffer_t value,
+ gss_buffer_t display_value,
+ int *more)
+{
+ PrincipalNameAttrs *nameattrs = name->nameattrs;
+ int n = -1;
+
+ if (authenticated && nameattrs && nameattrs->authenticated)
+ *authenticated = 1;
+ if (complete)
+ *complete = 1;
+
+ if (frag->length == 1 &&
+ ((const char *)frag->value)[0] >= '0' &&
+ ((const char *)frag->value)[0] <= '9') {
+ n = ((const char *)frag->value)[0] - '0';
+ } else if (frag->length == sizeof("all") - 1 &&
+ strncmp(frag->value, "all", sizeof("all") - 1) == 0) {
+ if (!more || *more < -1 || *more == 0 || *more > CHAR_MAX ||
+ *more > (int)name->name.name_string.len) {
+ *minor_status = EINVAL;
+ return GSS_S_UNAVAILABLE;
+ }
+ if (*more == -1) {
+ *more = name->name.name_string.len - 1;
+ n = 0;
+ } else {
+ n = name->name.name_string.len - *more;
+ (*more)--;
+ }
+ }
+
+ if (frag->length == 0) {
+ char *s = NULL;
+
+ /* Outut count of components */
+ if (value && (value->value = malloc(sizeof(size_t)))) {
+ *((size_t *)value->value) = name->name.name_string.len;
+ value->length = sizeof(size_t);
+ }
+ if (display_value &&
+ asprintf(&s, "%u", (unsigned int)name->name.name_string.len) > 0) {
+ display_value->value = s;
+ display_value->length = strlen(display_value->value);
+ }
+ } else {
+ /*
+ * Output a component. The value and the display value are the same in
+ * this case.
+ */
+ if (n < 0 || n >= name->name.name_string.len) {
+ *minor_status = EINVAL;
+ return GSS_S_UNAVAILABLE;
+ }
+ if (value && (value->value = strdup(name->name.name_string.val[n])))
+ value->length = strlen(name->name.name_string.val[n]);
+ if (display_value &&
+ (display_value->value = strdup(name->name.name_string.val[n])))
+ display_value->length = strlen(name->name.name_string.val[n]);
+ }
+
+ CHECK_ENOMEM(value, display_value);
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+get_peer_realm(OM_uint32 *minor_status,
+ const CompositePrincipal *name,
+ gss_const_buffer_t prefix,
+ gss_const_buffer_t attr,
+ gss_const_buffer_t frag,
+ int *authenticated,
+ int *complete,
+ gss_buffer_t value,
+ gss_buffer_t display_value,
+ int *more)
+{
+ PrincipalNameAttrs *nameattrs = name->nameattrs;
+
+ if (prefix->length || frag->length || !nameattrs || !nameattrs->peer_realm)
+ return GSS_S_UNAVAILABLE;
+ if (authenticated)
+ *authenticated = 1;
+ if (complete)
+ *complete = 1;
+ if (value && (value->value = strdup(nameattrs->peer_realm[0])))
+ value->length = strlen(value->value);
+ if (display_value &&
+ (display_value->value = strdup(nameattrs->peer_realm[0])))
+ display_value->length = strlen(display_value->value);
+
+ CHECK_ENOMEM(value, display_value);
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+get_pac(OM_uint32 *minor_status,
+ const CompositePrincipal *name,
+ gss_const_buffer_t prefix,
+ gss_const_buffer_t attr,
+ gss_const_buffer_t frag,
+ int *authenticated,
+ int *complete,
+ gss_buffer_t value,
+ gss_buffer_t display_value,
+ int *more)
+{
+ krb5_error_code kret;
+ krb5_context context;
+ krb5_data data;
+ PrincipalNameAttrs *nameattrs = name->nameattrs;
+ PrincipalNameAttrSrc *src = nameattrs ? nameattrs->source : NULL;
+ EncTicketPart *ticket = NULL;
+
+ krb5_data_zero(&data);
+
+ if (src == NULL ||
+ src->element != choice_PrincipalNameAttrSrc_enc_ticket_part)
+ return GSS_S_UNAVAILABLE;
+
+ ticket = &src->u.enc_ticket_part;
+
+ if (prefix->length || !authenticated || !ticket)
+ return GSS_S_UNAVAILABLE;
+
+ GSSAPI_KRB5_INIT(&context);
+
+ *authenticated = nameattrs->pac_verified;
+ if (complete)
+ *complete = 1;
+
+ kret = _krb5_get_ad(context, ticket->authorization_data,
+ NULL, KRB5_AUTHDATA_WIN2K_PAC,
+ value ? &data : NULL);
+
+ if (value) {
+ value->length = data.length;
+ value->value = data.data;
+ }
+
+ *minor_status = kret;
+ if (kret == ENOENT)
+ return GSS_S_UNAVAILABLE;
+ return kret == 0 ? GSS_S_COMPLETE : GSS_S_FAILURE;
+}
+
+static OM_uint32
+get_pac_buffer(OM_uint32 *minor_status,
+ const CompositePrincipal *name,
+ gss_const_buffer_t prefix,
+ gss_const_buffer_t attr,
+ gss_const_buffer_t frag,
+ int *authenticated,
+ int *complete,
+ gss_buffer_t value,
+ gss_buffer_t display_value,
+ int *more)
+{
+ krb5_error_code kret;
+ krb5_context context;
+ krb5_data data;
+ PrincipalNameAttrs *nameattrs = name->nameattrs;
+ krb5_data suffix;
+
+ krb5_data_zero(&data);
+
+ if (prefix->length || !authenticated ||
+ !nameattrs || !nameattrs->pac)
+ return GSS_S_UNAVAILABLE;
+
+ GSSAPI_KRB5_INIT(&context);
+
+ if (ATTR_EQ_PREFIX(attr, "urn:mspac:")) {
+ suffix.length = attr->length - (sizeof("urn:mspac:") - 1);
+ suffix.data = (char *)attr->value + sizeof("urn:mspac:") - 1;
+ } else if (ATTR_EQ_PREFIX(frag, "pac-")) {
+ suffix.length = frag->length - sizeof("pac-") - 1;
+ suffix.data = (char *)frag->value + sizeof("pac-") - 1;
+ } else
+ return GSS_S_UNAVAILABLE; /* should not be reached */
+
+ *authenticated = nameattrs->pac_verified;
+ if (complete)
+ *complete = 1;
+
+ kret = _krb5_pac_get_buffer_by_name(context, nameattrs->pac, &suffix,
+ value ? &data : NULL);
+
+ if (value) {
+ value->length = data.length;
+ value->value = data.data;
+ }
+
+ *minor_status = kret;
+ if (kret == ENOENT)
+ return GSS_S_UNAVAILABLE;
+ return kret == 0 ? GSS_S_COMPLETE : GSS_S_FAILURE;
+}
+
+static OM_uint32
+get_authz_data(OM_uint32 *minor_status,
+ const CompositePrincipal *name,
+ gss_const_buffer_t prefix,
+ gss_const_buffer_t attr,
+ gss_const_buffer_t frag,
+ int *authenticated,
+ int *complete,
+ gss_buffer_t value,
+ gss_buffer_t display_value,
+ int *more)
+{
+ krb5_error_code kret = 0;
+ PrincipalNameAttrs *nameattrs = name->nameattrs;
+ PrincipalNameAttrSrc *src = nameattrs ? nameattrs->source : NULL;
+ EncTicketPart *ticket = NULL;
+ krb5_context context;
+ krb5_data data;
+ char s[22];
+ char *end;
+ int64_t n;
+
+ if (src) switch (src->element) {
+ case choice_PrincipalNameAttrSrc_enc_ticket_part:
+ ticket = &src->u.enc_ticket_part;
+ break;
+ case choice_PrincipalNameAttrSrc_enc_kdc_rep_part:
+ default:
+ return GSS_S_UNAVAILABLE;
+ }
+
+ if (!nameattrs || !frag->length || frag->length > sizeof(s) - 1)
+ return GSS_S_UNAVAILABLE;
+
+ /* Output a specific AD element from the ticket or authenticator */
+ krb5_data_zero(&data);
+ memcpy(s, frag->value, frag->length);
+ s[frag->length] = '\0';
+ errno = 0;
+ n = strtoll(s, &end, 10);
+ if (end[0] == '\0' && (errno || n > INT_MAX || n < INT_MIN)) {
+ *minor_status = ERANGE;
+ return GSS_S_UNAVAILABLE;
+ }
+ if (end[0] != '\0') {
+ *minor_status = EINVAL;
+ return GSS_S_UNAVAILABLE;
+ }
+
+ if (authenticated)
+ *authenticated = 0;
+ if (complete)
+ *complete = 1;
+
+ GSSAPI_KRB5_INIT(&context);
+
+ kret = ENOENT;
+ if (ticket && ticket->authorization_data) {
+ kret = _krb5_get_ad(context, ticket->authorization_data,
+ NULL, n, value ? &data : NULL);
+
+ /* If it's from the ticket, it _may_ be authenticated: */
+ if (kret == 0 && authenticated) {
+ if (n == KRB5_AUTHDATA_KDC_ISSUED)
+ *authenticated = nameattrs->kdc_issued_verified;
+ else if (n == KRB5_AUTHDATA_WIN2K_PAC)
+ *authenticated = nameattrs->pac_verified;
+ }
+ }
+ if (kret == ENOENT && nameattrs->authenticator_ad &&
+ n != KRB5_AUTHDATA_KDC_ISSUED &&
+ n != KRB5_AUTHDATA_WIN2K_PAC) {
+ kret = _krb5_get_ad(context, nameattrs->authenticator_ad,
+ NULL, n, value ? &data : NULL);
+ }
+
+ if (value) {
+ value->length = data.length;
+ value->value = data.data;
+ }
+ *minor_status = kret;
+ if (kret == ENOENT)
+ return GSS_S_UNAVAILABLE;
+ return kret == 0 ? GSS_S_COMPLETE : GSS_S_FAILURE;
+}
+
+static OM_uint32
+get_ticket_authz_data(OM_uint32 *minor_status,
+ const CompositePrincipal *name,
+ gss_const_buffer_t prefix,
+ gss_const_buffer_t attr,
+ gss_const_buffer_t frag,
+ int *authenticated,
+ int *complete,
+ gss_buffer_t value,
+ gss_buffer_t display_value,
+ int *more)
+{
+ krb5_error_code kret = 0;
+ PrincipalNameAttrs *nameattrs = name->nameattrs;
+ PrincipalNameAttrSrc *src = nameattrs ? nameattrs->source : NULL;
+ EncTicketPart *ticket = NULL;
+ size_t sz;
+
+ if (src) switch (src->element) {
+ case choice_PrincipalNameAttrSrc_enc_ticket_part:
+ ticket = &src->u.enc_ticket_part;
+ break;
+ case choice_PrincipalNameAttrSrc_enc_kdc_rep_part:
+ default:
+ return GSS_S_UNAVAILABLE;
+ }
+
+ if (!ticket)
+ return GSS_S_UNAVAILABLE;
+
+ if (complete)
+ *complete = 1;
+
+ if (frag->length == sizeof("kdc-issued") - 1 &&
+ strncmp(frag->value, "kdc-issued", sizeof("kdc-issued") - 1) == 0) {
+ krb5_context context;
+ krb5_data data;
+
+ GSSAPI_KRB5_INIT(&context);
+ if (authenticated)
+ *authenticated = nameattrs->kdc_issued_verified;
+
+ kret = _krb5_get_ad(context, ticket->authorization_data,
+ NULL, KRB5_AUTHDATA_KDC_ISSUED,
+ value ? &data : NULL);
+ if (value) {
+ value->length = data.length;
+ value->value = data.data;
+ }
+ if (kret == ENOENT)
+ return GSS_S_UNAVAILABLE;
+ *minor_status = kret;
+ return kret == 0 ? GSS_S_COMPLETE : GSS_S_FAILURE;
+ } else if (frag->length) {
+ return GSS_S_UNAVAILABLE;
+ }
+
+ /* Just because it's in the Ticket doesn't make it authenticated */
+ if (authenticated)
+ *authenticated = 0;
+
+ if (value) {
+ ASN1_MALLOC_ENCODE(AuthorizationData, value->value, value->length,
+ ticket->authorization_data, &sz, kret);
+ *minor_status = kret;
+ }
+ return kret == 0 ? GSS_S_COMPLETE : GSS_S_FAILURE;
+}
+
+static OM_uint32
+get_authenticator_authz_data(OM_uint32 *minor_status,
+ const CompositePrincipal *name,
+ gss_const_buffer_t prefix,
+ gss_const_buffer_t attr,
+ gss_const_buffer_t frag,
+ int *authenticated,
+ int *complete,
+ gss_buffer_t value,
+ gss_buffer_t display_value,
+ int *more)
+{
+ krb5_error_code kret = 0;
+ PrincipalNameAttrs *nameattrs = name->nameattrs;
+ size_t sz;
+
+ if (!nameattrs || !nameattrs->authenticator_ad)
+ return GSS_S_UNAVAILABLE;
+ if (authenticated)
+ *authenticated = 0;
+ if (complete)
+ *complete = 1;
+
+ if (value) {
+ ASN1_MALLOC_ENCODE(AuthorizationData, value->value, value->length,
+ nameattrs->authenticator_ad, &sz, kret);
+ *minor_status = kret;
+ }
+ return kret == 0 ? GSS_S_COMPLETE : GSS_S_FAILURE;
+}
+
+static OM_uint32
+set_authenticator_authz_data(OM_uint32 *minor_status,
+ CompositePrincipal *name,
+ gss_const_buffer_t prefix,
+ gss_const_buffer_t attr,
+ gss_const_buffer_t frag,
+ int complete,
+ gss_buffer_t value)
+{
+ AuthorizationDataElement e;
+ krb5_error_code kret;
+ size_t sz;
+
+ if (!value)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+ if (frag->length &&
+ !ATTR_EQ(frag, "if-relevant"))
+ return GSS_S_UNAVAILABLE;
+
+ if ((name->nameattrs == NULL &&
+ (name->nameattrs = calloc(1, sizeof(*name->nameattrs))) == NULL) ||
+ (name->nameattrs->want_ad == NULL &&
+ (name->nameattrs->want_ad =
+ calloc(1, sizeof(*name->nameattrs->want_ad))) == NULL)) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ memset(&e, 0, sizeof(e));
+ kret = decode_AuthorizationDataElement(value->value, value->length, &e,
+ &sz);
+ if (kret == 0) {
+ if (frag->length) {
+ AuthorizationData ir;
+
+ ir.len = 0;
+ ir.val = NULL;
+ kret = add_AuthorizationData(&ir, &e);
+ free_AuthorizationDataElement(&e);
+ if (kret == 0) {
+ e.ad_type = KRB5_AUTHDATA_IF_RELEVANT;
+ ASN1_MALLOC_ENCODE(AuthorizationData, e.ad_data.data,
+ e.ad_data.length, &ir, &sz, kret);
+ kret = add_AuthorizationData(name->nameattrs->want_ad, &e);
+ }
+ free_AuthorizationData(&ir);
+ } else {
+ kret = add_AuthorizationData(name->nameattrs->want_ad, &e);
+ free_AuthorizationDataElement(&e);
+ }
+ }
+
+ *minor_status = kret;
+ return kret == 0 ? GSS_S_COMPLETE : GSS_S_FAILURE;
+}
+
+static OM_uint32
+get_transited(OM_uint32 *minor_status,
+ const CompositePrincipal *name,
+ gss_const_buffer_t prefix,
+ gss_const_buffer_t attr,
+ gss_const_buffer_t frag,
+ int *authenticated,
+ int *complete,
+ gss_buffer_t value,
+ gss_buffer_t display_value,
+ int *more)
+{
+ krb5_error_code kret = 0;
+ PrincipalNameAttrs *nameattrs = name->nameattrs;
+ PrincipalNameAttrSrc *src = nameattrs ? nameattrs->source : NULL;
+ EncTicketPart *ticket = NULL;
+ size_t sz;
+
+ if (src) switch (src->element) {
+ case choice_PrincipalNameAttrSrc_enc_kdc_rep_part:
+ break;
+ case choice_PrincipalNameAttrSrc_enc_ticket_part:
+ ticket = &src->u.enc_ticket_part;
+ break;
+ default:
+ return GSS_S_UNAVAILABLE;
+ }
+
+ if (!nameattrs && !ticket)
+ return GSS_S_UNAVAILABLE;
+ if (nameattrs && !nameattrs->transited && !ticket)
+ return GSS_S_UNAVAILABLE;
+
+ if (authenticated)
+ *authenticated = 1;
+ if (complete)
+ *complete = 1;
+
+ if (value && ticket)
+ ASN1_MALLOC_ENCODE(TransitedEncoding, value->value, value->length,
+ &ticket->transited, &sz, kret);
+ else if (value && nameattrs->transited)
+ ASN1_MALLOC_ENCODE(TransitedEncoding, value->value, value->length,
+ nameattrs->transited, &sz, kret);
+ *minor_status = kret;
+ return kret == 0 ? GSS_S_COMPLETE : GSS_S_FAILURE;
+}
+
+static OM_uint32
+get_canonical_name(OM_uint32 *minor_status,
+ const CompositePrincipal *name,
+ gss_const_buffer_t prefix,
+ gss_const_buffer_t attr,
+ gss_const_buffer_t frag,
+ int *authenticated,
+ int *complete,
+ gss_buffer_t value,
+ gss_buffer_t display_value,
+ int *more)
+{
+ krb5_error_code kret = 0;
+ PrincipalNameAttrs *nameattrs = name->nameattrs;
+ PrincipalNameAttrSrc *src = nameattrs ? nameattrs->source : NULL;
+ krb5_principal p = NULL;
+ krb5_context context;
+ EncTicketPart *ticket = NULL;
+ EncKDCRepPart *kdcrep = NULL;
+
+ if (src) switch (src->element) {
+ case choice_PrincipalNameAttrSrc_enc_kdc_rep_part:
+ kdcrep = &src->u.enc_kdc_rep_part;
+ break;
+ case choice_PrincipalNameAttrSrc_enc_ticket_part:
+ ticket = &src->u.enc_ticket_part;
+ break;
+ default:
+ return GSS_S_UNAVAILABLE;
+ }
+
+ GSSAPI_KRB5_INIT(&context);
+
+ if (authenticated)
+ *authenticated = 1;
+ if (complete)
+ *complete = 1;
+
+ if (kdcrep) {
+ kret = _krb5_principalname2krb5_principal(context, &p,
+ kdcrep->sname,
+ kdcrep->srealm);
+ } else if (nameattrs && nameattrs->pac &&
+ (_krb5_pac_get_canon_principal(context, nameattrs->pac, &p)) == 0) {
+ if (authenticated)
+ *authenticated = nameattrs->pac_verified;
+ } else if (ticket) {
+ krb5_data data;
+ krb5_pac pac = NULL;
+
+ krb5_data_zero(&data);
+
+ /* Use canonical name from PAC if available */
+ kret = _krb5_get_ad(context, ticket->authorization_data,
+ NULL, KRB5_AUTHDATA_WIN2K_PAC, &data);
+ if (kret == 0)
+ kret = krb5_pac_parse(context, data.data, data.length, &pac);
+ if (kret == 0)
+ kret = _krb5_pac_get_canon_principal(context, pac, &p);
+ if (kret == 0 && authenticated)
+ *authenticated = nameattrs->pac_verified;
+ else if (kret == ENOENT)
+ kret = _krb5_principalname2krb5_principal(context, &p,
+ ticket->cname,
+ ticket->crealm);
+
+ krb5_data_free(&data);
+ krb5_pac_free(context, pac);
+ } else
+ return GSS_S_UNAVAILABLE;
+ if (kret == 0 && value) {
+ OM_uint32 major;
+ /*
+ * Value is exported name token (exported composite name token
+ * should also work).
+ */
+ major = _gsskrb5_export_name(minor_status, (gss_name_t)p, value);
+ if (major != GSS_S_COMPLETE) {
+ krb5_free_principal(context, p);
+ return major;
+ }
+ }
+ if (kret == 0 && display_value) {
+ /* Display value is principal name display form */
+ kret = krb5_unparse_name(context, p,
+ (char **)&display_value->value);
+ if (kret == 0)
+ display_value->length = strlen(display_value->value);
+ }
+
+ krb5_free_principal(context, p);
+ if (kret) {
+ if (value) {
+ free(value->value);
+ value->length = 0;
+ value->value = NULL;
+ }
+ *minor_status = kret;
+ return GSS_S_UNAVAILABLE;
+ }
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/pname_to_uid.c b/third_party/heimdal/lib/gssapi/krb5/pname_to_uid.c
new file mode 100644
index 0000000..dca7464
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/pname_to_uid.c
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2011, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_localname(OM_uint32 *minor_status,
+ gss_const_name_t pname,
+ const gss_OID mech_type,
+ gss_buffer_t localname)
+{
+ krb5_error_code ret;
+ krb5_context context;
+ krb5_const_principal princ = (krb5_const_principal)pname;
+ char lnamebuf[256];
+
+ GSSAPI_KRB5_INIT(&context);
+
+ *minor_status = 0;
+
+ ret = krb5_aname_to_localname(context, princ,
+ sizeof(lnamebuf), lnamebuf);
+ if (ret != 0) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ localname->length = strlen(lnamebuf);
+
+ localname->value = malloc(localname->length + 1);
+ if (localname->value == NULL) {
+ localname->length = 0;
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ memcpy(localname->value, lnamebuf, localname->length + 1);
+ *minor_status = 0;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/prf.c b/third_party/heimdal/lib/gssapi/krb5/prf.c
new file mode 100644
index 0000000..671ab2c
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/prf.c
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_pseudo_random(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ int prf_key,
+ const gss_buffer_t prf_in,
+ ssize_t desired_output_len,
+ gss_buffer_t prf_out)
+{
+ gsskrb5_ctx ctx = (gsskrb5_ctx)context_handle;
+ krb5_context context;
+ krb5_error_code ret;
+ krb5_crypto crypto;
+ krb5_data input, output;
+ uint32_t num;
+ OM_uint32 junk;
+ unsigned char *p;
+ krb5_keyblock *key = NULL;
+ size_t dol;
+
+ if (ctx == NULL) {
+ *minor_status = 0;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ if (desired_output_len <= 0 || prf_in->length + 4 < prf_in->length) {
+ *minor_status = 0;
+ return GSS_S_FAILURE;
+ }
+ dol = desired_output_len;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ switch(prf_key) {
+ case GSS_C_PRF_KEY_FULL:
+ _gsskrb5i_get_acceptor_subkey(ctx, context, &key);
+ break;
+ case GSS_C_PRF_KEY_PARTIAL:
+ _gsskrb5i_get_initiator_subkey(ctx, context, &key);
+ break;
+ default:
+ _gsskrb5_set_status(EINVAL, "unknown kerberos prf_key");
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ if (key == NULL) {
+ _gsskrb5_set_status(EINVAL, "no prf_key found");
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ krb5_free_keyblock (context, key);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ prf_out->value = malloc(dol);
+ if (prf_out->value == NULL) {
+ _gsskrb5_set_status(GSS_KRB5_S_KG_INPUT_TOO_LONG, "Out of memory");
+ *minor_status = GSS_KRB5_S_KG_INPUT_TOO_LONG;
+ krb5_crypto_destroy(context, crypto);
+ return GSS_S_FAILURE;
+ }
+ prf_out->length = dol;
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+
+ input.length = prf_in->length + 4;
+ input.data = malloc(prf_in->length + 4);
+ if (input.data == NULL) {
+ _gsskrb5_set_status(GSS_KRB5_S_KG_INPUT_TOO_LONG, "Out of memory");
+ *minor_status = GSS_KRB5_S_KG_INPUT_TOO_LONG;
+ gss_release_buffer(&junk, prf_out);
+ krb5_crypto_destroy(context, crypto);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ return GSS_S_FAILURE;
+ }
+ memcpy(((uint8_t *)input.data) + 4, prf_in->value, prf_in->length);
+
+ num = 0;
+ p = prf_out->value;
+ while(dol > 0) {
+ size_t tsize;
+
+ _gsskrb5_encode_be_om_uint32(num, input.data);
+
+ ret = krb5_crypto_prf(context, crypto, &input, &output);
+ if (ret) {
+ *minor_status = ret;
+ free(input.data);
+ gss_release_buffer(&junk, prf_out);
+ krb5_crypto_destroy(context, crypto);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ return GSS_S_FAILURE;
+ }
+
+ tsize = min(dol, output.length);
+ memcpy(p, output.data, tsize);
+ p += tsize;
+ dol -= tsize;
+ krb5_data_free(&output);
+ num++;
+ }
+ free(input.data);
+
+ krb5_crypto_destroy(context, crypto);
+
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/process_context_token.c b/third_party/heimdal/lib/gssapi/krb5/process_context_token.c
new file mode 100644
index 0000000..601b0e8
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/process_context_token.c
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_process_context_token (
+ OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t token_buffer
+ )
+{
+ krb5_context context;
+ OM_uint32 ret = GSS_S_FAILURE;
+ gss_buffer_desc empty_buffer;
+
+ empty_buffer.length = 0;
+ empty_buffer.value = NULL;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ ret = _gsskrb5_verify_mic_internal(minor_status,
+ (gsskrb5_ctx)context_handle,
+ context,
+ token_buffer, &empty_buffer,
+ GSS_C_QOP_DEFAULT,
+ "\x01\x02");
+
+ if (ret == GSS_S_COMPLETE)
+ ret = _gsskrb5_delete_sec_context(minor_status,
+ rk_UNCONST(&context_handle),
+ GSS_C_NO_BUFFER);
+ if (ret == GSS_S_COMPLETE)
+ *minor_status = 0;
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/release_buffer.c b/third_party/heimdal/lib/gssapi/krb5/release_buffer.c
new file mode 100644
index 0000000..b704e00
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/release_buffer.c
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 1997 - 2000, 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 _gsskrb5_release_buffer
+ (OM_uint32 * minor_status,
+ gss_buffer_t buffer
+ )
+{
+ *minor_status = 0;
+ free (buffer->value);
+ buffer->value = NULL;
+ buffer->length = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/release_cred.c b/third_party/heimdal/lib/gssapi/krb5/release_cred.c
new file mode 100644
index 0000000..e1bb870
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/release_cred.c
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 1997-2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_release_cred
+ (OM_uint32 * minor_status,
+ gss_cred_id_t * cred_handle
+ )
+{
+ krb5_context context;
+ gsskrb5_cred cred;
+ OM_uint32 junk;
+
+ *minor_status = 0;
+
+ if (*cred_handle == NULL)
+ return GSS_S_COMPLETE;
+
+ cred = (gsskrb5_cred)*cred_handle;
+ *cred_handle = GSS_C_NO_CREDENTIAL;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ HEIMDAL_MUTEX_lock(&cred->cred_id_mutex);
+
+ free(cred->destination_realm);
+ if (cred->principal != NULL)
+ krb5_free_principal(context, cred->principal);
+ if (cred->keytab != NULL)
+ krb5_kt_close(context, cred->keytab);
+ if (cred->ccache != NULL) {
+ if (cred->cred_flags & GSS_CF_DESTROY_CRED_ON_RELEASE)
+ krb5_cc_destroy(context, cred->ccache);
+ else
+ krb5_cc_close(context, cred->ccache);
+ }
+ gss_release_oid_set(&junk, &cred->mechanisms);
+ if (cred->enctypes)
+ free(cred->enctypes);
+ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
+ HEIMDAL_MUTEX_destroy(&cred->cred_id_mutex);
+ memset(cred, 0, sizeof(*cred));
+ free(cred);
+ return GSS_S_COMPLETE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/krb5/release_name.c b/third_party/heimdal/lib/gssapi/krb5/release_name.c
new file mode 100644
index 0000000..57fc8a4
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/release_name.c
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_release_name
+ (OM_uint32 * minor_status,
+ gss_name_t * input_name
+ )
+{
+ krb5_context context;
+ krb5_principal name = (krb5_principal)*input_name;
+
+ *minor_status = 0;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ *input_name = GSS_C_NO_NAME;
+
+ krb5_free_principal(context, name);
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/sequence.c b/third_party/heimdal/lib/gssapi/krb5/sequence.c
new file mode 100644
index 0000000..2e0e7b2
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/sequence.c
@@ -0,0 +1,292 @@
+/*
+ * Copyright (c) 2003 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+#define DEFAULT_JITTER_WINDOW 20
+
+struct gss_msg_order {
+ OM_uint32 flags;
+ OM_uint32 start;
+ OM_uint32 length;
+ OM_uint32 jitter_window;
+ OM_uint32 first_seq;
+ OM_uint32 elem[1];
+};
+
+
+/*
+ *
+ */
+
+static OM_uint32
+msg_order_alloc(OM_uint32 *minor_status,
+ struct gss_msg_order **o,
+ OM_uint32 jitter_window)
+{
+ size_t len;
+
+ len = jitter_window * sizeof((*o)->elem[0]);
+ len += sizeof(**o);
+ len -= sizeof((*o)->elem[0]);
+
+ *o = calloc(1, len);
+ if (*o == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+/*
+ *
+ */
+
+OM_uint32
+_gssapi_msg_order_create(OM_uint32 *minor_status,
+ struct gss_msg_order **o,
+ OM_uint32 flags,
+ OM_uint32 seq_num,
+ OM_uint32 jitter_window,
+ int use_64)
+{
+ OM_uint32 ret;
+
+ if (jitter_window == 0)
+ jitter_window = DEFAULT_JITTER_WINDOW;
+
+ ret = msg_order_alloc(minor_status, o, jitter_window);
+ if(ret != GSS_S_COMPLETE)
+ return ret;
+
+ (*o)->flags = flags;
+ (*o)->length = 0;
+ (*o)->first_seq = seq_num;
+ (*o)->jitter_window = jitter_window;
+ (*o)->elem[0] = seq_num - 1;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_gssapi_msg_order_destroy(struct gss_msg_order **m)
+{
+ free(*m);
+ *m = NULL;
+ return GSS_S_COMPLETE;
+}
+
+static void
+elem_set(struct gss_msg_order *o, unsigned int slot, OM_uint32 val)
+{
+ o->elem[slot % o->jitter_window] = val;
+}
+
+static void
+elem_insert(struct gss_msg_order *o,
+ unsigned int after_slot,
+ OM_uint32 seq_num)
+{
+ assert(o->jitter_window > after_slot);
+
+ if (o->length > after_slot)
+ memmove(&o->elem[after_slot + 1], &o->elem[after_slot],
+ (o->length - after_slot - 1) * sizeof(o->elem[0]));
+
+ elem_set(o, after_slot, seq_num);
+
+ if (o->length < o->jitter_window)
+ o->length++;
+}
+
+/* rule 1: expected sequence number */
+/* rule 2: > expected sequence number */
+/* rule 3: seqnum < seqnum(first) */
+/* rule 4+5: seqnum in [seqnum(first),seqnum(last)] */
+
+OM_uint32
+_gssapi_msg_order_check(struct gss_msg_order *o, OM_uint32 seq_num)
+{
+ OM_uint32 r;
+ size_t i;
+
+ if (o == NULL)
+ return GSS_S_COMPLETE;
+
+ if ((o->flags & (GSS_C_REPLAY_FLAG|GSS_C_SEQUENCE_FLAG)) == 0)
+ return GSS_S_COMPLETE;
+
+ /* check if the packet is the next in order */
+ if (o->elem[0] == seq_num - 1) {
+ elem_insert(o, 0, seq_num);
+ return GSS_S_COMPLETE;
+ }
+
+ r = (o->flags & (GSS_C_REPLAY_FLAG|GSS_C_SEQUENCE_FLAG))==GSS_C_REPLAY_FLAG;
+
+ /* sequence number larger then largest sequence number
+ * or smaller then the first sequence number */
+ if (seq_num > o->elem[0]
+ || seq_num < o->first_seq
+ || o->length == 0)
+ {
+ elem_insert(o, 0, seq_num);
+ if (r) {
+ return GSS_S_COMPLETE;
+ } else {
+ return GSS_S_GAP_TOKEN;
+ }
+ }
+
+ assert(o->length > 0);
+
+ /* sequence number smaller the first sequence number */
+ if (seq_num < o->elem[o->length - 1]) {
+ if (r)
+ return(GSS_S_OLD_TOKEN);
+ else
+ return(GSS_S_UNSEQ_TOKEN);
+ }
+
+ if (seq_num == o->elem[o->length - 1]) {
+ return GSS_S_DUPLICATE_TOKEN;
+ }
+
+ for (i = 0; i < o->length - 1; i++) {
+ if (o->elem[i] == seq_num)
+ return GSS_S_DUPLICATE_TOKEN;
+ if (o->elem[i + 1] < seq_num && o->elem[i] < seq_num) {
+ elem_insert(o, i, seq_num);
+ if (r)
+ return GSS_S_COMPLETE;
+ else
+ return GSS_S_UNSEQ_TOKEN;
+ }
+ }
+
+ return GSS_S_FAILURE;
+}
+
+OM_uint32
+_gssapi_msg_order_f(OM_uint32 flags)
+{
+ return flags & (GSS_C_SEQUENCE_FLAG|GSS_C_REPLAY_FLAG);
+}
+
+/*
+ * Translate `o` into inter-process format and export in to `sp'.
+ */
+
+krb5_error_code
+_gssapi_msg_order_export(krb5_storage *sp, struct gss_msg_order *o)
+{
+ krb5_error_code kret;
+ OM_uint32 i;
+
+ kret = krb5_store_int32(sp, o->flags);
+ if (kret)
+ return kret;
+ kret = krb5_store_int32(sp, o->start);
+ if (kret)
+ return kret;
+ kret = krb5_store_int32(sp, o->length);
+ if (kret)
+ return kret;
+ kret = krb5_store_int32(sp, o->jitter_window);
+ if (kret)
+ return kret;
+ kret = krb5_store_int32(sp, o->first_seq);
+ if (kret)
+ return kret;
+
+ for (i = 0; i < o->jitter_window; i++) {
+ kret = krb5_store_int32(sp, o->elem[i]);
+ if (kret)
+ return kret;
+ }
+
+ return 0;
+}
+
+OM_uint32
+_gssapi_msg_order_import(OM_uint32 *minor_status,
+ krb5_storage *sp,
+ struct gss_msg_order **o)
+{
+ OM_uint32 ret;
+ krb5_error_code kret;
+ int32_t i, flags, start, length, jitter_window, first_seq;
+
+ kret = krb5_ret_int32(sp, &flags);
+ if (kret)
+ goto failed;
+ kret = krb5_ret_int32(sp, &start);
+ if (kret)
+ goto failed;
+ kret = krb5_ret_int32(sp, &length);
+ if (kret)
+ goto failed;
+ kret = krb5_ret_int32(sp, &jitter_window);
+ if (kret)
+ goto failed;
+ kret = krb5_ret_int32(sp, &first_seq);
+ if (kret)
+ goto failed;
+
+ ret = msg_order_alloc(minor_status, o, jitter_window);
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+
+ (*o)->flags = flags;
+ (*o)->start = start;
+ (*o)->length = length;
+ (*o)->jitter_window = jitter_window;
+ (*o)->first_seq = first_seq;
+
+ for( i = 0; i < jitter_window; i++ ) {
+ kret = krb5_ret_int32(sp, (int32_t*)&((*o)->elem[i]));
+ if (kret)
+ goto failed;
+ }
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+
+failed:
+ _gssapi_msg_order_destroy(o);
+ *minor_status = kret;
+ return GSS_S_FAILURE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/set_cred_option.c b/third_party/heimdal/lib/gssapi/krb5/set_cred_option.c
new file mode 100644
index 0000000..ef177a0
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/set_cred_option.c
@@ -0,0 +1,249 @@
+/*
+ * Copyright (c) 2004, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+static OM_uint32
+import_cred(OM_uint32 *minor_status,
+ krb5_context context,
+ gss_cred_id_t *cred_handle,
+ const gss_buffer_t value)
+{
+ OM_uint32 major_stat;
+ krb5_error_code ret;
+ krb5_principal keytab_principal = NULL;
+ krb5_keytab keytab = NULL;
+ krb5_storage *sp = NULL;
+ krb5_ccache id = NULL;
+ char *str;
+
+ if (cred_handle == NULL || *cred_handle != GSS_C_NO_CREDENTIAL) {
+ *minor_status = 0;
+ return GSS_S_FAILURE;
+ }
+
+ sp = krb5_storage_from_mem(value->value, value->length);
+ if (sp == NULL) {
+ *minor_status = 0;
+ return GSS_S_FAILURE;
+ }
+
+ /* credential cache name */
+ ret = krb5_ret_string(sp, &str);
+ if (ret) {
+ *minor_status = ret;
+ major_stat = GSS_S_FAILURE;
+ goto out;
+ }
+ if (str[0]) {
+ ret = krb5_cc_resolve(context, str, &id);
+ if (ret) {
+ *minor_status = ret;
+ major_stat = GSS_S_FAILURE;
+ goto out;
+ }
+ }
+ free(str);
+ str = NULL;
+
+ /* keytab principal name */
+ ret = krb5_ret_string(sp, &str);
+ if (ret == 0 && str[0])
+ ret = krb5_parse_name(context, str, &keytab_principal);
+ if (ret) {
+ *minor_status = ret;
+ major_stat = GSS_S_FAILURE;
+ goto out;
+ }
+ free(str);
+ str = NULL;
+
+ /* keytab principal */
+ ret = krb5_ret_string(sp, &str);
+ if (ret) {
+ *minor_status = ret;
+ major_stat = GSS_S_FAILURE;
+ goto out;
+ }
+ if (str[0]) {
+ ret = krb5_kt_resolve(context, str, &keytab);
+ if (ret) {
+ *minor_status = ret;
+ major_stat = GSS_S_FAILURE;
+ goto out;
+ }
+ }
+ free(str);
+ str = NULL;
+
+ major_stat = _gsskrb5_krb5_import_cred(minor_status, &id, keytab_principal,
+ keytab, cred_handle);
+out:
+ if (id)
+ krb5_cc_close(context, id);
+ if (keytab_principal)
+ krb5_free_principal(context, keytab_principal);
+ if (keytab)
+ krb5_kt_close(context, keytab);
+ if (str)
+ free(str);
+ if (sp)
+ krb5_storage_free(sp);
+
+ return major_stat;
+}
+
+
+static OM_uint32
+allowed_enctypes(OM_uint32 *minor_status,
+ krb5_context context,
+ gss_cred_id_t *cred_handle,
+ const gss_buffer_t value)
+{
+ OM_uint32 major_stat;
+ krb5_error_code ret;
+ size_t len, i;
+ krb5_enctype *enctypes = NULL;
+ krb5_storage *sp = NULL;
+ gsskrb5_cred cred;
+
+ if (cred_handle == NULL || *cred_handle == GSS_C_NO_CREDENTIAL) {
+ *minor_status = 0;
+ return GSS_S_FAILURE;
+ }
+
+ cred = (gsskrb5_cred)*cred_handle;
+
+ if ((value->length % 4) != 0) {
+ *minor_status = 0;
+ major_stat = GSS_S_FAILURE;
+ goto out;
+ }
+
+ /* serialized as int32_t[], but stored as krb5_enctype[] */
+ len = value->length / 4;
+ enctypes = malloc((len + 1) * sizeof(krb5_enctype));
+ if (enctypes == NULL) {
+ *minor_status = ENOMEM;
+ major_stat = GSS_S_FAILURE;
+ goto out;
+ }
+
+ sp = krb5_storage_from_mem(value->value, value->length);
+ if (sp == NULL) {
+ *minor_status = ENOMEM;
+ major_stat = GSS_S_FAILURE;
+ goto out;
+ }
+
+ for (i = 0; i < len; i++) {
+ int32_t e;
+
+ ret = krb5_ret_int32(sp, &e);
+ if (ret) {
+ *minor_status = ret;
+ major_stat = GSS_S_FAILURE;
+ goto out;
+ }
+ enctypes[i] = e;
+ }
+ enctypes[i] = KRB5_ENCTYPE_NULL;
+
+ if (cred->enctypes)
+ free(cred->enctypes);
+ cred->enctypes = enctypes;
+
+ krb5_storage_free(sp);
+
+ return GSS_S_COMPLETE;
+
+out:
+ if (sp)
+ krb5_storage_free(sp);
+ if (enctypes)
+ free(enctypes);
+
+ return major_stat;
+}
+
+static OM_uint32
+no_ci_flags(OM_uint32 *minor_status,
+ krb5_context context,
+ gss_cred_id_t *cred_handle,
+ const gss_buffer_t value)
+{
+ gsskrb5_cred cred;
+
+ if (cred_handle == NULL || *cred_handle == GSS_C_NO_CREDENTIAL) {
+ *minor_status = 0;
+ return GSS_S_FAILURE;
+ }
+
+ cred = (gsskrb5_cred)*cred_handle;
+ cred->cred_flags |= GSS_CF_NO_CI_FLAGS;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+
+}
+
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_set_cred_option
+ (OM_uint32 *minor_status,
+ gss_cred_id_t *cred_handle,
+ const gss_OID desired_object,
+ const gss_buffer_t value)
+{
+ krb5_context context;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (value == GSS_C_NO_BUFFER) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ if (gss_oid_equal(desired_object, GSS_KRB5_IMPORT_CRED_X))
+ return import_cred(minor_status, context, cred_handle, value);
+
+ if (gss_oid_equal(desired_object, GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X))
+ return allowed_enctypes(minor_status, context, cred_handle, value);
+
+ if (gss_oid_equal(desired_object, GSS_KRB5_CRED_NO_CI_FLAGS_X)) {
+ return no_ci_flags(minor_status, context, cred_handle, value);
+ }
+
+
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/set_sec_context_option.c b/third_party/heimdal/lib/gssapi/krb5/set_sec_context_option.c
new file mode 100644
index 0000000..3a6f86b
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/set_sec_context_option.c
@@ -0,0 +1,353 @@
+/*
+ * Copyright (c) 2004, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * glue routine for _gsskrb5_inquire_sec_context_by_oid
+ */
+
+#include "gsskrb5_locl.h"
+
+static OM_uint32
+get_bool(OM_uint32 *minor_status,
+ const gss_buffer_t value,
+ int *flag)
+{
+ if (value->value == NULL || value->length != 1) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ *flag = *((const char *)value->value) != 0;
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+get_string(OM_uint32 *minor_status,
+ const gss_buffer_t value,
+ char **str)
+{
+ if (value == NULL || value->length == 0) {
+ *str = NULL;
+ } else {
+ *str = malloc(value->length + 1);
+ if (*str == NULL) {
+ *minor_status = 0;
+ return GSS_S_UNAVAILABLE;
+ }
+ memcpy(*str, value->value, value->length);
+ (*str)[value->length] = '\0';
+ }
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+get_int32(OM_uint32 *minor_status,
+ const gss_buffer_t value,
+ OM_uint32 *ret)
+{
+ *minor_status = 0;
+ if (value == NULL || value->length == 0)
+ *ret = 0;
+ else if (value->length == sizeof(*ret))
+ memcpy(ret, value->value, sizeof(*ret));
+ else
+ return GSS_S_UNAVAILABLE;
+
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+set_int32(OM_uint32 *minor_status,
+ const gss_buffer_t value,
+ OM_uint32 set)
+{
+ *minor_status = 0;
+ if (value->length == sizeof(set))
+ memcpy(value->value, &set, sizeof(set));
+ else
+ return GSS_S_UNAVAILABLE;
+
+ return GSS_S_COMPLETE;
+}
+
+/*
+ * GSS_KRB5_IMPORT_RFC4121_CONTEXT_X is an internal, private interface
+ * to allow SAnon to create a skeletal context for using RFC4121 message
+ * protection services.
+ *
+ * rfc4121_args ::= initiator_flag || flags || enctype || session key
+ */
+static OM_uint32
+make_rfc4121_context(OM_uint32 *minor,
+ krb5_context context,
+ gss_ctx_id_t *context_handle,
+ gss_const_buffer_t rfc4121_args)
+{
+ OM_uint32 major = GSS_S_FAILURE, tmp;
+ krb5_error_code ret;
+ krb5_storage *sp = NULL;
+ gsskrb5_ctx ctx = NULL;
+ uint8_t initiator_flag;
+ int32_t enctype;
+ size_t keysize;
+ krb5_keyblock *key;
+
+ *minor = 0;
+
+ sp = krb5_storage_from_readonly_mem(rfc4121_args->value, rfc4121_args->length);
+ if (sp == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_HOST);
+
+ ctx = calloc(1, sizeof(*ctx));
+ if (ctx == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ ret = krb5_ret_uint8(sp, &initiator_flag);
+ if (ret != 0)
+ goto out;
+
+ ret = krb5_ret_uint32(sp, &ctx->flags);
+ if (ret != 0)
+ goto out;
+
+ ctx->more_flags = IS_CFX | ACCEPTOR_SUBKEY | OPEN;
+ if (initiator_flag)
+ ctx->more_flags |= LOCAL;
+
+ ctx->state = initiator_flag ? INITIATOR_READY : ACCEPTOR_READY;
+
+ ret = krb5_ret_int32(sp, &enctype);
+ if (ret != 0)
+ goto out;
+
+ ret = krb5_enctype_keysize(context, enctype, &keysize);
+ if (ret != 0)
+ goto out;
+
+ ctx->auth_context = calloc(1, sizeof(*ctx->auth_context));
+ if (ctx->auth_context == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ key = calloc(1, sizeof(*key));
+ if (key == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ if (initiator_flag)
+ ctx->auth_context->remote_subkey = key;
+ else
+ ctx->auth_context->local_subkey = key;
+
+ key->keytype = enctype;
+ key->keyvalue.data = malloc(keysize);
+ if (key->keyvalue.data == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ if (krb5_storage_read(sp, key->keyvalue.data, keysize) != keysize) {
+ ret = EINVAL;
+ goto out;
+ }
+ key->keyvalue.length = keysize;
+
+ ret = krb5_crypto_init(context, key, 0, &ctx->crypto);
+ if (ret != 0)
+ goto out;
+
+ major = _gssapi_msg_order_create(minor, &ctx->order,
+ _gssapi_msg_order_f(ctx->flags),
+ 0, 0, 1);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+
+out:
+ krb5_storage_free(sp);
+
+ if (major != GSS_S_COMPLETE) {
+ if (*minor == 0)
+ *minor = ret;
+ _gsskrb5_delete_sec_context(&tmp, (gss_ctx_id_t *)&ctx, GSS_C_NO_BUFFER);
+ } else {
+ *context_handle = (gss_ctx_id_t)ctx;
+ }
+
+ return major;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_set_sec_context_option
+ (OM_uint32 *minor_status,
+ gss_ctx_id_t *context_handle,
+ const gss_OID desired_object,
+ const gss_buffer_t value)
+{
+ krb5_context context;
+ OM_uint32 maj_stat;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (value == GSS_C_NO_BUFFER) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ if (gss_oid_equal(desired_object, GSS_KRB5_COMPAT_DES3_MIC_X)) {
+ gsskrb5_ctx ctx;
+ int flag;
+
+ if (*context_handle == GSS_C_NO_CONTEXT) {
+ *minor_status = EINVAL;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ maj_stat = get_bool(minor_status, value, &flag);
+ if (maj_stat != GSS_S_COMPLETE)
+ return maj_stat;
+
+ ctx = (gsskrb5_ctx)*context_handle;
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ if (flag)
+ ctx->more_flags |= COMPAT_OLD_DES3;
+ else
+ ctx->more_flags &= ~COMPAT_OLD_DES3;
+ ctx->more_flags |= COMPAT_OLD_DES3_SELECTED;
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ return GSS_S_COMPLETE;
+ } else if (gss_oid_equal(desired_object, GSS_KRB5_SET_DNS_CANONICALIZE_X)) {
+ int flag;
+
+ maj_stat = get_bool(minor_status, value, &flag);
+ if (maj_stat != GSS_S_COMPLETE)
+ return maj_stat;
+
+ krb5_set_dns_canonicalize_hostname(context, flag);
+ return GSS_S_COMPLETE;
+
+ } else if (gss_oid_equal(desired_object, GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X)) {
+ char *str;
+
+ maj_stat = get_string(minor_status, value, &str);
+ if (maj_stat != GSS_S_COMPLETE)
+ return maj_stat;
+
+ maj_stat = _gsskrb5_register_acceptor_identity(minor_status, str);
+ free(str);
+
+ return maj_stat;
+
+ } else if (gss_oid_equal(desired_object, GSS_KRB5_SET_DEFAULT_REALM_X)) {
+ char *str;
+
+ maj_stat = get_string(minor_status, value, &str);
+ if (maj_stat != GSS_S_COMPLETE)
+ return maj_stat;
+ if (str == NULL) {
+ *minor_status = 0;
+ return GSS_S_CALL_INACCESSIBLE_READ;
+ }
+
+ krb5_set_default_realm(context, str);
+ free(str);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+
+ } else if (gss_oid_equal(desired_object, GSS_KRB5_SEND_TO_KDC_X)) {
+
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+
+ } else if (gss_oid_equal(desired_object, GSS_KRB5_SET_TIME_OFFSET_X)) {
+ OM_uint32 offset;
+ time_t t;
+
+ maj_stat = get_int32(minor_status, value, &offset);
+ if (maj_stat != GSS_S_COMPLETE)
+ return maj_stat;
+
+ t = time(NULL) + offset;
+
+ krb5_set_real_time(context, t, 0);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+ } else if (gss_oid_equal(desired_object, GSS_KRB5_GET_TIME_OFFSET_X)) {
+ krb5_timestamp sec;
+ int32_t usec;
+ time_t t;
+
+ t = time(NULL);
+
+ krb5_us_timeofday (context, &sec, &usec);
+
+ maj_stat = set_int32(minor_status, value, sec - t);
+ if (maj_stat != GSS_S_COMPLETE)
+ return maj_stat;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+ } else if (gss_oid_equal(desired_object, GSS_KRB5_PLUGIN_REGISTER_X)) {
+ struct gsskrb5_krb5_plugin c;
+
+ if (value->length != sizeof(c)) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ memcpy(&c, value->value, sizeof(c));
+ krb5_plugin_register(context, c.type, c.name, c.symbol);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+ } else if (gss_oid_equal(desired_object, GSS_KRB5_CCACHE_NAME_X)) {
+ struct gsskrb5_ccache_name_args *args = value->value;
+
+ if (value->length != sizeof(*args)) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ return _gsskrb5_krb5_ccache_name(minor_status, args->name, &args->out_name);
+ } else if (gss_oid_equal(desired_object, GSS_KRB5_IMPORT_RFC4121_CONTEXT_X)) {
+ return make_rfc4121_context(minor_status, context, context_handle, value);
+ }
+
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/store_cred.c b/third_party/heimdal/lib/gssapi/krb5/store_cred.c
new file mode 100644
index 0000000..6d727b4
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/store_cred.c
@@ -0,0 +1,372 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+static int
+same_princ(krb5_context context, krb5_ccache id1, krb5_ccache id2)
+{
+ krb5_error_code ret;
+ krb5_principal p1 = NULL;
+ krb5_principal p2 = NULL;
+ int same = 0;
+
+ ret = krb5_cc_get_principal(context, id1, &p1);
+ if (ret == 0)
+ ret = krb5_cc_get_principal(context, id2, &p2);
+ /* If either principal is absent, it's the same for our purposes */
+ same = ret ? 1 : krb5_principal_compare(context, p1, p2);
+ krb5_free_principal(context, p1);
+ krb5_free_principal(context, p2);
+ return same;
+}
+
+static OM_uint32
+add_env(OM_uint32 *minor,
+ gss_buffer_set_t *env,
+ const char *var,
+ const char *val)
+{
+ OM_uint32 major;
+ gss_buffer_desc b;
+ char *varval = NULL;
+
+ if (asprintf(&varval, "%s=%s", var, val) == -1 || varval == NULL) {
+ *minor = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ b.value = varval;
+ b.length = strlen(varval) + 1;
+ major = gss_add_buffer_set_member(minor, &b, env);
+ free(varval);
+ return major;
+}
+
+static OM_uint32
+set_proc(OM_uint32 *minor, gss_buffer_set_t env)
+{
+ /*
+ * XXX On systems with setpag(), call setpag(). On WIN32... create a
+ * session, set the access token, ...?
+ */
+#ifndef WIN32
+ size_t i;
+
+ for (i = 0; i < env->count; i++)
+ putenv(env->elements[i].value);
+#endif
+ return GSS_S_COMPLETE;
+}
+
+/*
+ * A principal is the best principal for a user IFF
+ *
+ * - it has one component
+ * - the one component is the same as the user's name
+ * - the real is the user_realm from configuration
+ */
+static int
+principal_is_best_for_user(krb5_context context,
+ const char *app,
+ krb5_const_principal p,
+ const char *user)
+{
+ char *default_realm = NULL;
+ char *user_realm = NULL;
+ int ret;
+
+ (void) krb5_get_default_realm(context, &default_realm);
+ krb5_appdefault_string(context, app, NULL, "user_realm", default_realm,
+ &user_realm);
+ ret = user_realm &&
+ krb5_principal_get_num_comp(context, p) == 1 &&
+ strcmp(user_realm, krb5_principal_get_realm(context, p)) == 0 &&
+ (!user ||
+ strcmp(user, krb5_principal_get_comp_string(context, p, 0)) == 0);
+ free(default_realm);
+ free(user_realm);
+ return ret;
+}
+
+static krb5_error_code
+check_destination_tgt_policy(krb5_context context,
+ const char *appname,
+ gsskrb5_cred input_cred)
+{
+ krb5_error_code ret;
+ krb5_boolean want_dst_tgt = 0;
+ krb5_data v;
+
+ if (input_cred->destination_realm == NULL)
+ /*
+ * Not a delegated credential, so we can't check the destination TGT
+ * policy for the realm of the service -- we don't know the realm of
+ * the service.
+ */
+ return 0;
+
+ krb5_appdefault_boolean(context, appname, input_cred->destination_realm,
+ "require_delegate_destination_tgt", FALSE,
+ &want_dst_tgt);
+ if (!want_dst_tgt)
+ return 0;
+
+ krb5_data_zero(&v);
+ ret = krb5_cc_get_config(context, input_cred->ccache, NULL,
+ "start_realm", &v);
+ if (ret == 0 &&
+ v.length != strlen(input_cred->destination_realm))
+ ret = KRB5_CC_NOTFOUND;
+ if (ret == 0 &&
+ strncmp(input_cred->destination_realm, v.data, v.length) != 0)
+ ret = KRB5_CC_NOTFOUND;
+ if (ret)
+ krb5_set_error_message(context, ret,
+ "Delegated TGT is not a destination TGT for "
+ "realm \"%s\" but for \"%.*s\"",
+ input_cred->destination_realm,
+ (int)(v.length ? v.length : sizeof("<UNKNOWN>") - 1),
+ v.data ? (const char *)v.data : "<UNKNOWN>");
+ krb5_data_free(&v);
+ return ret;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_store_cred_into2(OM_uint32 *minor_status,
+ gss_const_cred_id_t input_cred_handle,
+ gss_cred_usage_t cred_usage,
+ const gss_OID desired_mech,
+ OM_uint32 store_cred_flags,
+ gss_const_key_value_set_t cred_store,
+ gss_OID_set *elements_stored,
+ gss_cred_usage_t *cred_usage_stored,
+ gss_buffer_set_t *envp)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ gsskrb5_cred input_cred;
+ krb5_ccache id = NULL;
+ time_t exp_current;
+ time_t exp_new;
+ gss_buffer_set_t env = GSS_C_NO_BUFFER_SET;
+ const char *cs_unique_ccache = NULL;
+ const char *cs_ccache_name = NULL;
+ const char *cs_user_name = NULL;
+ const char *cs_app_name = NULL;
+ char *ccache_name = NULL;
+ OM_uint32 major_status = GSS_S_FAILURE;
+ OM_uint32 junk;
+ OM_uint32 overwrite_cred = store_cred_flags & GSS_C_STORE_CRED_OVERWRITE;
+ int default_for = 0;
+
+ *minor_status = 0;
+
+ /* Sanity check inputs */
+ if (cred_usage != GSS_C_INITIATE) {
+ /* It'd be nice if we could also do accept, writing a keytab */
+ *minor_status = GSS_KRB5_S_G_BAD_USAGE;
+ return GSS_S_FAILURE;
+ }
+ if (desired_mech != GSS_C_NO_OID &&
+ gss_oid_equal(desired_mech, GSS_KRB5_MECHANISM) == 0)
+ return GSS_S_BAD_MECH;
+ if (input_cred_handle == GSS_C_NO_CREDENTIAL)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+ input_cred = (gsskrb5_cred)input_cred_handle;
+
+ /* Sanity check the input_cred */
+ if (input_cred->usage != cred_usage && input_cred->usage != GSS_C_BOTH) {
+ *minor_status = GSS_KRB5_S_G_BAD_USAGE;
+ return GSS_S_NO_CRED;
+ }
+ if (input_cred->principal == NULL) {
+ *minor_status = GSS_KRB5_S_KG_TGT_MISSING;
+ return GSS_S_NO_CRED;
+ }
+
+ /* Extract the ccache name from the store if given */
+ if (cred_store != GSS_C_NO_CRED_STORE) {
+ major_status = __gsskrb5_cred_store_find(minor_status, cred_store,
+ "unique_ccache_type",
+ &cs_unique_ccache);
+ if (GSS_ERROR(major_status))
+ return major_status;
+ major_status = __gsskrb5_cred_store_find(minor_status, cred_store,
+ "ccache", &cs_ccache_name);
+ if (GSS_ERROR(major_status))
+ return major_status;
+ major_status = __gsskrb5_cred_store_find(minor_status, cred_store,
+ "username", &cs_user_name);
+ if (GSS_ERROR(major_status))
+ return major_status;
+ major_status = __gsskrb5_cred_store_find(minor_status, cred_store,
+ "appname", &cs_app_name);
+ if (GSS_ERROR(major_status))
+ return major_status;
+ }
+
+ GSSAPI_KRB5_INIT (&context);
+ HEIMDAL_MUTEX_lock(&input_cred->cred_id_mutex);
+
+ if (cs_ccache_name && strchr(cs_ccache_name, '%')) {
+ ret = _krb5_expand_default_cc_name(context, cs_ccache_name,
+ &ccache_name);
+ if (ret) {
+ HEIMDAL_MUTEX_unlock(&input_cred->cred_id_mutex);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ cs_ccache_name = ccache_name;
+ }
+
+ /* More sanity checking of the input_cred (good to fail early) */
+ ret = krb5_cc_get_lifetime(context, input_cred->ccache, &exp_new);
+ if (ret) {
+ HEIMDAL_MUTEX_unlock(&input_cred->cred_id_mutex);
+ *minor_status = ret;
+ free(ccache_name);
+ return GSS_S_NO_CRED;
+ }
+
+ ret = check_destination_tgt_policy(context, cs_app_name, input_cred);
+ if (ret) {
+ HEIMDAL_MUTEX_unlock(&input_cred->cred_id_mutex);
+ *minor_status = ret;
+ free(ccache_name);
+ return GSS_S_NO_CRED;
+ }
+
+ /*
+ * Find an appropriate ccache, which will be one of:
+ *
+ * - the one given in the cred_store, if given
+ * - a new unique one for some ccache type in the cred_store, if given
+ * - a subsidiary cache named for the principal in the default collection,
+ * if the principal is the "best principal for the user"
+ * - the default ccache
+ */
+ if (cs_ccache_name) {
+ ret = krb5_cc_resolve(context, cs_ccache_name, &id);
+ } else if (cs_unique_ccache) {
+ overwrite_cred = 1;
+ ret = krb5_cc_new_unique(context, cs_unique_ccache, NULL, &id);
+ } else if (principal_is_best_for_user(context, cs_app_name,
+ input_cred->principal,
+ cs_user_name)) {
+ ret = krb5_cc_default(context, &id);
+ if (ret == 0 && !same_princ(context, id, input_cred->ccache)) {
+ krb5_cc_close(context, id);
+ ret = krb5_cc_default_for(context, input_cred->principal, &id);
+ default_for = 1;
+ }
+ } else {
+ ret = krb5_cc_default_for(context, input_cred->principal, &id);
+ default_for = 1;
+ }
+
+ if (ret || id == NULL) {
+ HEIMDAL_MUTEX_unlock(&input_cred->cred_id_mutex);
+ *minor_status = ret;
+ free(ccache_name);
+ return ret == 0 ? GSS_S_NO_CRED : GSS_S_FAILURE;
+ }
+
+ /*
+ * If we're using a subsidiary ccache for this principal and it has some
+ * other principal's tickets in it -> overwrite.
+ */
+ if (!overwrite_cred && default_for &&
+ !same_princ(context, id, input_cred->ccache))
+ overwrite_cred = 1;
+ if (!overwrite_cred && same_princ(context, id, input_cred->ccache)) {
+ /*
+ * If current creds are for the same princ as we already had creds for,
+ * and the new creds live longer than the old, overwrite.
+ */
+ ret = krb5_cc_get_lifetime(context, id, &exp_current);
+ if (ret != 0 || exp_new > exp_current)
+ overwrite_cred = 1;
+ }
+
+ if (overwrite_cred) {
+ ret = krb5_cc_initialize(context, id, input_cred->principal);
+ if (ret == 0)
+ ret = krb5_cc_copy_match_f(context, input_cred->ccache, id, NULL, NULL,
+ NULL);
+ }
+
+ if ((store_cred_flags & GSS_C_STORE_CRED_SET_PROCESS) && envp == NULL)
+ envp = &env;
+ if (envp != NULL) {
+ char *fullname = NULL;
+
+ if ((ret = krb5_cc_get_full_name(context, id, &fullname)) == 0) {
+ major_status = add_env(minor_status, envp, "KRB5CCNAME", fullname);
+ free(fullname);
+ if (major_status)
+ ret = *minor_status;
+ }
+ }
+ (void) krb5_cc_close(context, id);
+
+ HEIMDAL_MUTEX_unlock(&input_cred->cred_id_mutex);
+ if (ret == 0 && (store_cred_flags & GSS_C_STORE_CRED_SET_PROCESS) &&
+ (major_status = set_proc(minor_status, *envp)) != GSS_S_COMPLETE)
+ ret = *minor_status;
+ (void) gss_release_buffer_set(&junk, &env);
+ free(ccache_name);
+ *minor_status = ret;
+ return ret ? major_status : GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_store_cred_into(OM_uint32 *minor_status,
+ gss_const_cred_id_t input_cred_handle,
+ gss_cred_usage_t cred_usage,
+ const gss_OID desired_mech,
+ OM_uint32 overwrite_cred,
+ OM_uint32 default_cred,
+ gss_const_key_value_set_t cred_store,
+ gss_OID_set *elements_stored,
+ gss_cred_usage_t *cred_usage_stored)
+{
+ OM_uint32 store_cred_flags =
+ (overwrite_cred ? GSS_C_STORE_CRED_OVERWRITE : 0) |
+ (default_cred ? GSS_C_STORE_CRED_DEFAULT : 0);
+
+ return _gsskrb5_store_cred_into2(minor_status, input_cred_handle,
+ cred_usage, desired_mech,
+ store_cred_flags, cred_store,
+ elements_stored, cred_usage_stored, NULL);
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/test_acquire_cred.c b/third_party/heimdal/lib/gssapi/krb5/test_acquire_cred.c
new file mode 100644
index 0000000..812fce6
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/test_acquire_cred.c
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) 2003-2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+#include <err.h>
+
+static void
+print_time(OM_uint32 time_rec)
+{
+ if (time_rec == GSS_C_INDEFINITE) {
+ printf("cred never expire\n");
+ } else {
+ time_t t = time_rec + time(NULL);
+ printf("expiration time: %s", ctime(&t));
+ }
+}
+
+static void
+test_add(gss_cred_id_t cred_handle)
+{
+ OM_uint32 major_status, minor_status;
+ gss_cred_id_t copy_cred;
+ OM_uint32 time_rec;
+
+ major_status = gss_add_cred (&minor_status,
+ cred_handle,
+ GSS_C_NO_NAME,
+ GSS_KRB5_MECHANISM,
+ GSS_C_INITIATE,
+ 0,
+ 0,
+ &copy_cred,
+ NULL,
+ &time_rec,
+ NULL);
+
+ if (GSS_ERROR(major_status))
+ errx(1, "add_cred failed");
+
+ print_time(time_rec);
+
+ major_status = gss_release_cred(&minor_status,
+ &copy_cred);
+ if (GSS_ERROR(major_status))
+ errx(1, "release_cred failed");
+}
+
+static void
+test_add_mutate(gss_cred_id_t cred_handle)
+{
+ OM_uint32 major_status, minor_status;
+ OM_uint32 time_rec;
+
+ major_status = gss_add_cred (&minor_status,
+ cred_handle,
+ GSS_C_NO_NAME,
+ GSS_KRB5_MECHANISM,
+ GSS_C_INITIATE,
+ 0,
+ 0,
+ NULL,
+ NULL,
+ &time_rec,
+ NULL);
+
+ if (GSS_ERROR(major_status))
+ errx(1, "add_cred failed");
+
+ print_time(time_rec);
+}
+
+static void
+copy_cred(void)
+{
+ OM_uint32 major_status, minor_status;
+ gss_cred_id_t cred_handle;
+ OM_uint32 time_rec;
+
+ major_status = gss_acquire_cred(&minor_status,
+ GSS_C_NO_NAME,
+ 0,
+ NULL,
+ GSS_C_INITIATE,
+ &cred_handle,
+ NULL,
+ &time_rec);
+ if (GSS_ERROR(major_status))
+ errx(1, "acquire_cred failed");
+
+ print_time(time_rec);
+
+ test_add(cred_handle);
+ test_add(cred_handle);
+ test_add(cred_handle);
+ test_add_mutate(cred_handle);
+
+ major_status = gss_release_cred(&minor_status,
+ &cred_handle);
+ if (GSS_ERROR(major_status))
+ errx(1, "release_cred failed");
+}
+
+static void
+acquire_cred_service(const char *service)
+{
+ OM_uint32 major_status, minor_status;
+ gss_cred_id_t cred_handle;
+ OM_uint32 time_rec;
+ gss_buffer_desc name_buffer;
+ gss_name_t name;
+
+ name_buffer.value = rk_UNCONST(service);
+ name_buffer.length = strlen(service);
+
+ major_status = gss_import_name(&minor_status,
+ &name_buffer,
+ GSS_C_NT_HOSTBASED_SERVICE,
+ &name);
+ if (GSS_ERROR(major_status))
+ errx(1, "import_name failed");
+
+
+ major_status = gss_acquire_cred(&minor_status,
+ name,
+ 0,
+ NULL,
+ GSS_C_ACCEPT,
+ &cred_handle,
+ NULL,
+ &time_rec);
+ if (GSS_ERROR(major_status))
+ errx(1, "acquire_cred failed");
+
+ print_time(time_rec);
+
+ major_status = gss_release_cred(&minor_status,
+ &cred_handle);
+ if (GSS_ERROR(major_status))
+ errx(1, "release_cred failed");
+
+
+ major_status = gss_release_name(&minor_status,
+ &name);
+ if (GSS_ERROR(major_status))
+ errx(1, "release_name failed");
+
+}
+
+int
+main(int argc, char **argv)
+{
+ copy_cred();
+
+ acquire_cred_service("host@xen2-heimdal-linux.lab.it.su.se");
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/test_cfx.c b/third_party/heimdal/lib/gssapi/krb5/test_cfx.c
new file mode 100644
index 0000000..15f853c
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/test_cfx.c
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+struct range {
+ size_t lower;
+ size_t upper;
+};
+
+struct range tests[] = {
+ { 0, 1040 },
+ { 2040, 2080 },
+ { 4080, 5000 },
+ { 8180, 8292 },
+ { 9980, 10010 }
+};
+
+static void
+test_range(const struct range *r, int integ,
+ krb5_context context, krb5_crypto crypto)
+{
+ krb5_error_code ret;
+ size_t size, rsize;
+ struct gsskrb5_ctx ctx;
+
+ for (size = r->lower; size < r->upper; size++) {
+ size_t cksumsize;
+ uint16_t padsize;
+ OM_uint32 minor;
+ OM_uint32 max_wrap_size;
+
+ ctx.crypto = crypto;
+
+ ret = _gssapi_wrap_size_cfx(&minor,
+ &ctx,
+ context,
+ integ,
+ 0,
+ size,
+ &max_wrap_size);
+ if (ret)
+ krb5_errx(context, 1, "_gsskrb5cfx_max_wrap_length_cfx: %d", ret);
+ if (max_wrap_size == 0)
+ continue;
+
+ ret = _gsskrb5cfx_wrap_length_cfx(context,
+ crypto,
+ integ,
+ 0,
+ max_wrap_size,
+ &rsize, &cksumsize, &padsize);
+ if (ret)
+ krb5_errx(context, 1, "_gsskrb5cfx_wrap_length_cfx: %d", ret);
+
+ if (size < rsize)
+ krb5_errx(context, 1,
+ "size (%d) < rsize (%d) for max_wrap_size %d",
+ (int)size, (int)rsize, (int)max_wrap_size);
+ }
+}
+
+static void
+test_special(krb5_context context, krb5_crypto crypto,
+ int integ, size_t testsize)
+{
+ krb5_error_code ret;
+ size_t rsize;
+ OM_uint32 max_wrap_size;
+ size_t cksumsize;
+ uint16_t padsize;
+ struct gsskrb5_ctx ctx;
+ OM_uint32 minor;
+
+ ctx.crypto = crypto;
+
+ ret = _gssapi_wrap_size_cfx(&minor,
+ &ctx,
+ context,
+ integ,
+ 0,
+ testsize,
+ &max_wrap_size);
+ if (ret)
+ krb5_errx(context, 1, "_gsskrb5cfx_max_wrap_length_cfx: %d", ret);
+ if (ret)
+ krb5_errx(context, 1, "_gsskrb5cfx_max_wrap_length_cfx: %d", ret);
+
+ ret = _gsskrb5cfx_wrap_length_cfx(context,
+ crypto,
+ integ,
+ 0,
+ max_wrap_size,
+ &rsize, &cksumsize, &padsize);
+ if (ret)
+ krb5_errx(context, 1, "_gsskrb5cfx_wrap_length_cfx: %d", ret);
+
+ if (testsize < rsize)
+ krb5_errx(context, 1,
+ "testsize (%d) < rsize (%d) for max_wrap_size %d",
+ (int)testsize, (int)rsize, (int)max_wrap_size);
+}
+
+
+
+
+int
+main(int argc, char **argv)
+{
+ krb5_keyblock keyblock;
+ krb5_error_code ret;
+ krb5_context context;
+ krb5_crypto crypto;
+ int i;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_context_init: %d", ret);
+
+ ret = krb5_generate_random_keyblock(context,
+ KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96,
+ &keyblock);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_generate_random_keyblock");
+
+ ret = krb5_crypto_init(context, &keyblock, 0, &crypto);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_init");
+
+ test_special(context, crypto, 1, 60);
+ test_special(context, crypto, 0, 60);
+
+ for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
+ test_range(&tests[i], 1, context, crypto);
+ test_range(&tests[i], 0, context, crypto);
+ }
+
+ krb5_free_keyblock_contents(context, &keyblock);
+ krb5_crypto_destroy(context, crypto);
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/test_cred.c b/third_party/heimdal/lib/gssapi/krb5/test_cred.c
new file mode 100644
index 0000000..e0395f0
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/test_cred.c
@@ -0,0 +1,277 @@
+/*
+ * Copyright (c) 2003-2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+static void
+gss_print_errors (int min_stat)
+{
+ OM_uint32 new_stat;
+ OM_uint32 msg_ctx = 0;
+ gss_buffer_desc status_string;
+ OM_uint32 ret;
+
+ do {
+ ret = gss_display_status (&new_stat,
+ min_stat,
+ GSS_C_MECH_CODE,
+ GSS_C_NO_OID,
+ &msg_ctx,
+ &status_string);
+ fprintf (stderr, "%.*s\n", (int)status_string.length,
+ (char *)status_string.value);
+ gss_release_buffer (&new_stat, &status_string);
+ } while (!GSS_ERROR(ret) && msg_ctx != 0);
+}
+
+static void
+gss_err(int exitval, int status, const char *fmt, ...)
+{
+ va_list args;
+
+ va_start(args, fmt);
+ vwarnx (fmt, args);
+ gss_print_errors (status);
+ va_end(args);
+ exit (exitval);
+}
+
+static void
+acquire_release_loop(gss_name_t name, int counter, gss_cred_usage_t usage)
+{
+ OM_uint32 maj_stat, min_stat;
+ gss_cred_id_t cred;
+ int i;
+
+ for (i = 0; i < counter; i++) {
+ maj_stat = gss_acquire_cred(&min_stat, name,
+ GSS_C_INDEFINITE,
+ GSS_C_NO_OID_SET,
+ usage,
+ &cred,
+ NULL,
+ NULL);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "aquire %d %d != GSS_S_COMPLETE",
+ i, (int)maj_stat);
+
+ maj_stat = gss_release_cred(&min_stat, &cred);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "release %d %d != GSS_S_COMPLETE",
+ i, (int)maj_stat);
+ }
+}
+
+
+static void
+acquire_add_release_add(gss_name_t name, gss_cred_usage_t usage)
+{
+ OM_uint32 maj_stat, min_stat;
+ gss_cred_id_t cred, cred2, cred3;
+
+ maj_stat = gss_acquire_cred(&min_stat, name,
+ GSS_C_INDEFINITE,
+ GSS_C_NO_OID_SET,
+ usage,
+ &cred,
+ NULL,
+ NULL);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "aquire %d != GSS_S_COMPLETE", (int)maj_stat);
+
+ maj_stat = gss_add_cred(&min_stat,
+ cred,
+ GSS_C_NO_NAME,
+ GSS_KRB5_MECHANISM,
+ usage,
+ GSS_C_INDEFINITE,
+ GSS_C_INDEFINITE,
+ &cred2,
+ NULL,
+ NULL,
+ NULL);
+
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "add_cred %d != GSS_S_COMPLETE", (int)maj_stat);
+
+ maj_stat = gss_release_cred(&min_stat, &cred);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "release %d != GSS_S_COMPLETE", (int)maj_stat);
+
+ maj_stat = gss_add_cred(&min_stat,
+ cred2,
+ GSS_C_NO_NAME,
+ GSS_KRB5_MECHANISM,
+ GSS_C_BOTH,
+ GSS_C_INDEFINITE,
+ GSS_C_INDEFINITE,
+ &cred3,
+ NULL,
+ NULL,
+ NULL);
+
+ maj_stat = gss_release_cred(&min_stat, &cred2);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "release 2 %d != GSS_S_COMPLETE", (int)maj_stat);
+
+ maj_stat = gss_release_cred(&min_stat, &cred3);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "release 2 %d != GSS_S_COMPLETE", (int)maj_stat);
+}
+
+static void
+add_add_release_add(gss_name_t name, gss_cred_usage_t usage)
+{
+ OM_uint32 maj_stat, min_stat;
+ gss_cred_id_t cred, cred2;
+
+ maj_stat = gss_add_cred(&min_stat,
+ GSS_C_NO_CREDENTIAL,
+ name,
+ GSS_KRB5_MECHANISM,
+ usage,
+ GSS_C_INDEFINITE,
+ GSS_C_INDEFINITE,
+ &cred,
+ NULL,
+ NULL,
+ NULL);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "add_cred %d != GSS_S_COMPLETE", (int)maj_stat);
+
+ maj_stat = gss_add_cred(&min_stat,
+ cred,
+ GSS_C_NO_NAME,
+ GSS_KRB5_MECHANISM,
+ usage,
+ GSS_C_INDEFINITE,
+ GSS_C_INDEFINITE,
+ &cred2,
+ NULL,
+ NULL,
+ NULL);
+
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "add_cred %d != GSS_S_COMPLETE", (int)maj_stat);
+
+ maj_stat = gss_release_cred(&min_stat, &cred);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "release %d != GSS_S_COMPLETE", (int)maj_stat);
+
+ maj_stat = gss_add_cred(&min_stat,
+ cred2,
+ GSS_C_NO_NAME,
+ GSS_KRB5_MECHANISM,
+ GSS_C_BOTH,
+ GSS_C_INDEFINITE,
+ GSS_C_INDEFINITE,
+ NULL,
+ NULL,
+ NULL,
+ NULL);
+
+ maj_stat = gss_release_cred(&min_stat, &cred2);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "release 2 %d != GSS_S_COMPLETE", (int)maj_stat);
+}
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag, "print version", NULL },
+ {"help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args),
+ NULL, "service@host");
+ exit (ret);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ struct gss_buffer_desc_struct name_buffer;
+ OM_uint32 maj_stat, min_stat;
+ gss_name_t name;
+ int optidx = 0;
+
+ setprogname(argv[0]);
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (argc < 1)
+ errx(1, "argc < 1");
+
+ name_buffer.value = argv[0];
+ name_buffer.length = strlen(argv[0]);
+
+ maj_stat = gss_import_name(&min_stat, &name_buffer,
+ GSS_C_NT_HOSTBASED_SERVICE,
+ &name);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "import name error");
+
+ acquire_release_loop(name, 100, GSS_C_ACCEPT);
+ acquire_release_loop(name, 100, GSS_C_INITIATE);
+ acquire_release_loop(name, 100, GSS_C_BOTH);
+
+ acquire_add_release_add(name, GSS_C_ACCEPT);
+ acquire_add_release_add(name, GSS_C_INITIATE);
+ acquire_add_release_add(name, GSS_C_BOTH);
+
+ add_add_release_add(name, GSS_C_ACCEPT);
+ add_add_release_add(name, GSS_C_INITIATE);
+ add_add_release_add(name, GSS_C_BOTH);
+
+ gss_release_name(&min_stat, &name);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/test_kcred.c b/third_party/heimdal/lib/gssapi/krb5/test_kcred.c
new file mode 100644
index 0000000..c90a144
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/test_kcred.c
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 2003-2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static void
+copy_import(void)
+{
+ gss_cred_id_t cred1, cred2;
+ OM_uint32 maj_stat, min_stat;
+ gss_name_t name1, name2;
+ OM_uint32 lifetime1, lifetime2;
+ gss_cred_usage_t usage1, usage2;
+ gss_OID_set mechs1, mechs2;
+ krb5_ccache id;
+ krb5_error_code ret;
+ krb5_context context;
+ int equal;
+
+ maj_stat = gss_acquire_cred(&min_stat, GSS_C_NO_NAME, GSS_C_INDEFINITE,
+ GSS_C_NO_OID_SET, GSS_C_INITIATE,
+ &cred1, NULL, NULL);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_acquire_cred");
+
+ maj_stat = gss_inquire_cred(&min_stat, cred1, &name1, &lifetime1,
+ &usage1, &mechs1);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_inquire_cred");
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_init_context");
+
+ ret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_new_unique");
+
+ maj_stat = gss_krb5_copy_ccache(&min_stat, context, cred1, id);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_krb5_copy_ccache");
+
+ maj_stat = gss_krb5_import_cred(&min_stat, id, NULL, NULL, &cred2);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_krb5_import_cred");
+
+ maj_stat = gss_inquire_cred(&min_stat, cred2, &name2, &lifetime2,
+ &usage2, &mechs2);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_inquire_cred 2");
+
+ maj_stat = gss_compare_name(&min_stat, name1, name2, &equal);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_compare_name");
+ if (!equal)
+ errx(1, "names not equal");
+
+ /* This check is racy! */
+ if (getenv("TESTS_ENVIRONMENT") == NULL) && lifetime1 != lifetime2)
+ errx(1, "lifetime not equal");
+ if (lifetime1 != lifetime2)
+ warnx("lifetime not equal");
+
+ if (usage1 != usage1)
+ errx(1, "usage not equal");
+
+ gss_release_cred(&min_stat, &cred1);
+ gss_release_cred(&min_stat, &cred2);
+
+ gss_release_name(&min_stat, &name1);
+ gss_release_name(&min_stat, &name2);
+
+#if 0
+ compare(mechs1, mechs2);
+#endif
+
+ gss_release_oid_set(&min_stat, &mechs1);
+ gss_release_oid_set(&min_stat, &mechs2);
+
+ krb5_cc_destroy(context, id);
+ krb5_free_context(context);
+}
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag, "print version", NULL },
+ {"help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args),
+ NULL, "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ int optidx = 0;
+
+ setprogname(argv[0]);
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ copy_import();
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/test_oid.c b/third_party/heimdal/lib/gssapi/krb5/test_oid.c
new file mode 100644
index 0000000..00219b9
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/test_oid.c
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+int
+main(int argc, char **argv)
+{
+ OM_uint32 minor_status, maj_stat;
+ gss_buffer_desc data;
+ int ret;
+
+ maj_stat = gss_oid_to_str(&minor_status, GSS_KRB5_MECHANISM, &data);
+ if (GSS_ERROR(maj_stat))
+ errx(1, "gss_oid_to_str failed");
+ ret = strncmp(data.value, "1 2 840 113554 1 2 2", data.length);
+ gss_release_buffer(&maj_stat, &data);
+ if (ret)
+ return 1;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/test_sequence.c b/third_party/heimdal/lib/gssapi/krb5/test_sequence.c
new file mode 100644
index 0000000..33a4aac
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/test_sequence.c
@@ -0,0 +1,367 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+/* correct ordering */
+OM_uint32 pattern1[] = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
+};
+
+/* gap 10 */
+OM_uint32 pattern2[] = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13
+};
+
+/* dup 9 */
+OM_uint32 pattern3[] = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10, 11, 12, 13
+};
+
+/* gaps */
+OM_uint32 pattern4[] = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15, 16, 18, 100
+};
+
+/* 11 before 10 */
+OM_uint32 pattern5[] = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21
+};
+
+/* long */
+OM_uint32 pattern6[] = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
+ 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
+ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
+ 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
+ 50, 51, 52, 53, 54, 55, 56, 57, 58, 59
+};
+
+/* don't start at 0 */
+OM_uint32 pattern7[] = {
+ 11, 12, 13
+};
+
+/* wrap around */
+OM_uint32 pattern8[] = {
+ 4294967293U, 4294967294U, 4294967295U, 0, 1, 2
+};
+
+static int
+test_seq(int t, OM_uint32 flags, OM_uint32 start_seq,
+ OM_uint32 *pattern, int pattern_len, OM_uint32 expected_error)
+{
+ struct gss_msg_order *o;
+ OM_uint32 maj_stat, min_stat;
+ krb5_storage *sp;
+ int i;
+
+ maj_stat = _gssapi_msg_order_create(&min_stat, &o, flags,
+ start_seq, 20, 0);
+ if (maj_stat)
+ errx(1, "create: %d %d", maj_stat, min_stat);
+
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ errx(1, "krb5_storage_from_emem");
+
+ _gssapi_msg_order_export(sp, o);
+
+ for (i = 0; i < pattern_len; i++) {
+ maj_stat = _gssapi_msg_order_check(o, pattern[i]);
+ if (maj_stat)
+ break;
+ }
+ if (maj_stat != expected_error) {
+ printf("test pattern %d failed with %d (should have been %d)\n",
+ t, maj_stat, expected_error);
+ krb5_storage_free(sp);
+ _gssapi_msg_order_destroy(&o);
+ return 1;
+ }
+
+
+ _gssapi_msg_order_destroy(&o);
+
+ /* try again, now with export/imported blob */
+ krb5_storage_seek(sp, 0, SEEK_SET);
+
+ maj_stat = _gssapi_msg_order_import(&min_stat, sp, &o);
+ if (maj_stat)
+ errx(1, "import: %d %d", maj_stat, min_stat);
+
+ for (i = 0; i < pattern_len; i++) {
+ maj_stat = _gssapi_msg_order_check(o, pattern[i]);
+ if (maj_stat)
+ break;
+ }
+ if (maj_stat != expected_error) {
+ printf("import/export test pattern %d failed "
+ "with %d (should have been %d)\n",
+ t, maj_stat, expected_error);
+ _gssapi_msg_order_destroy(&o);
+ krb5_storage_free(sp);
+ return 1;
+ }
+
+ _gssapi_msg_order_destroy(&o);
+ krb5_storage_free(sp);
+
+ return 0;
+}
+
+struct {
+ OM_uint32 flags;
+ OM_uint32 *pattern;
+ int pattern_len;
+ OM_uint32 error_code;
+ OM_uint32 start_seq;
+} pl[] = {
+ {
+ GSS_C_REPLAY_FLAG|GSS_C_SEQUENCE_FLAG,
+ pattern1,
+ sizeof(pattern1)/sizeof(pattern1[0]),
+ 0
+ },
+ {
+ GSS_C_REPLAY_FLAG|GSS_C_SEQUENCE_FLAG,
+ pattern2,
+ sizeof(pattern2)/sizeof(pattern2[0]),
+ GSS_S_GAP_TOKEN
+ },
+ {
+ GSS_C_REPLAY_FLAG|GSS_C_SEQUENCE_FLAG,
+ pattern3,
+ sizeof(pattern3)/sizeof(pattern3[0]),
+ GSS_S_DUPLICATE_TOKEN
+ },
+ {
+ GSS_C_REPLAY_FLAG|GSS_C_SEQUENCE_FLAG,
+ pattern4,
+ sizeof(pattern4)/sizeof(pattern4[0]),
+ GSS_S_GAP_TOKEN
+ },
+ {
+ GSS_C_REPLAY_FLAG|GSS_C_SEQUENCE_FLAG,
+ pattern5,
+ sizeof(pattern5)/sizeof(pattern5[0]),
+ GSS_S_GAP_TOKEN
+ },
+ {
+ GSS_C_REPLAY_FLAG|GSS_C_SEQUENCE_FLAG,
+ pattern6,
+ sizeof(pattern6)/sizeof(pattern6[0]),
+ GSS_S_COMPLETE
+ },
+ {
+ GSS_C_REPLAY_FLAG|GSS_C_SEQUENCE_FLAG,
+ pattern7,
+ sizeof(pattern7)/sizeof(pattern7[0]),
+ GSS_S_GAP_TOKEN
+ },
+ {
+ GSS_C_REPLAY_FLAG|GSS_C_SEQUENCE_FLAG,
+ pattern8,
+ sizeof(pattern8)/sizeof(pattern8[0]),
+ GSS_S_COMPLETE,
+ 4294967293U
+ },
+ {
+ 0,
+ pattern1,
+ sizeof(pattern1)/sizeof(pattern1[0]),
+ GSS_S_COMPLETE
+ },
+ {
+ 0,
+ pattern2,
+ sizeof(pattern2)/sizeof(pattern2[0]),
+ GSS_S_COMPLETE
+ },
+ {
+ 0,
+ pattern3,
+ sizeof(pattern3)/sizeof(pattern3[0]),
+ GSS_S_COMPLETE
+ },
+ {
+ 0,
+ pattern4,
+ sizeof(pattern4)/sizeof(pattern4[0]),
+ GSS_S_COMPLETE
+ },
+ {
+ 0,
+ pattern5,
+ sizeof(pattern5)/sizeof(pattern5[0]),
+ GSS_S_COMPLETE
+ },
+ {
+ 0,
+ pattern6,
+ sizeof(pattern6)/sizeof(pattern6[0]),
+ GSS_S_COMPLETE
+ },
+ {
+ 0,
+ pattern7,
+ sizeof(pattern7)/sizeof(pattern7[0]),
+ GSS_S_COMPLETE
+ },
+ {
+ 0,
+ pattern8,
+ sizeof(pattern8)/sizeof(pattern8[0]),
+ GSS_S_COMPLETE,
+ 4294967293U
+
+ },
+ {
+ GSS_C_REPLAY_FLAG,
+ pattern1,
+ sizeof(pattern1)/sizeof(pattern1[0]),
+ GSS_S_COMPLETE
+ },
+ {
+ GSS_C_REPLAY_FLAG,
+ pattern2,
+ sizeof(pattern2)/sizeof(pattern2[0]),
+ GSS_S_COMPLETE
+ },
+ {
+ GSS_C_REPLAY_FLAG,
+ pattern3,
+ sizeof(pattern3)/sizeof(pattern3[0]),
+ GSS_S_DUPLICATE_TOKEN
+ },
+ {
+ GSS_C_REPLAY_FLAG,
+ pattern4,
+ sizeof(pattern4)/sizeof(pattern4[0]),
+ GSS_S_COMPLETE
+ },
+ {
+ GSS_C_REPLAY_FLAG,
+ pattern5,
+ sizeof(pattern5)/sizeof(pattern5[0]),
+ 0
+ },
+ {
+ GSS_C_REPLAY_FLAG,
+ pattern6,
+ sizeof(pattern6)/sizeof(pattern6[0]),
+ GSS_S_COMPLETE
+ },
+ {
+ GSS_C_REPLAY_FLAG,
+ pattern7,
+ sizeof(pattern7)/sizeof(pattern7[0]),
+ GSS_S_COMPLETE
+ },
+ {
+ GSS_C_SEQUENCE_FLAG,
+ pattern8,
+ sizeof(pattern8)/sizeof(pattern8[0]),
+ GSS_S_COMPLETE,
+ 4294967293U
+ },
+ {
+ GSS_C_SEQUENCE_FLAG,
+ pattern1,
+ sizeof(pattern1)/sizeof(pattern1[0]),
+ 0
+ },
+ {
+ GSS_C_SEQUENCE_FLAG,
+ pattern2,
+ sizeof(pattern2)/sizeof(pattern2[0]),
+ GSS_S_GAP_TOKEN
+ },
+ {
+ GSS_C_SEQUENCE_FLAG,
+ pattern3,
+ sizeof(pattern3)/sizeof(pattern3[0]),
+ GSS_S_DUPLICATE_TOKEN
+ },
+ {
+ GSS_C_SEQUENCE_FLAG,
+ pattern4,
+ sizeof(pattern4)/sizeof(pattern4[0]),
+ GSS_S_GAP_TOKEN
+ },
+ {
+ GSS_C_SEQUENCE_FLAG,
+ pattern5,
+ sizeof(pattern5)/sizeof(pattern5[0]),
+ GSS_S_GAP_TOKEN
+ },
+ {
+ GSS_C_SEQUENCE_FLAG,
+ pattern6,
+ sizeof(pattern6)/sizeof(pattern6[0]),
+ GSS_S_COMPLETE
+ },
+ {
+ GSS_C_SEQUENCE_FLAG,
+ pattern7,
+ sizeof(pattern7)/sizeof(pattern7[0]),
+ GSS_S_GAP_TOKEN
+ },
+ {
+ GSS_C_REPLAY_FLAG,
+ pattern8,
+ sizeof(pattern8)/sizeof(pattern8[0]),
+ GSS_S_COMPLETE,
+ 4294967293U
+ }
+};
+
+int
+main(int argc, char **argv)
+{
+ int i, failed = 0;
+
+ for (i = 0; i < sizeof(pl)/sizeof(pl[0]); i++) {
+ if (test_seq(i,
+ pl[i].flags,
+ pl[i].start_seq,
+ pl[i].pattern,
+ pl[i].pattern_len,
+ pl[i].error_code))
+ failed++;
+ }
+ if (failed)
+ printf("FAILED %d tests\n", failed);
+ return failed != 0;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/ticket_flags.c b/third_party/heimdal/lib/gssapi/krb5/ticket_flags.c
new file mode 100644
index 0000000..df5f11d
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/ticket_flags.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+OM_uint32
+_gsskrb5_get_tkt_flags(OM_uint32 *minor_status,
+ gsskrb5_ctx ctx,
+ OM_uint32 *tkt_flags)
+{
+ if (ctx == NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_NO_CONTEXT;
+ }
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+
+ if (ctx->ticket == NULL) {
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ *minor_status = EINVAL;
+ return GSS_S_BAD_MECH;
+ }
+
+ *tkt_flags = TicketFlags2int(ctx->ticket->ticket.flags);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/unwrap.c b/third_party/heimdal/lib/gssapi/krb5/unwrap.c
new file mode 100644
index 0000000..6461369
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/unwrap.c
@@ -0,0 +1,468 @@
+/*
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+#ifdef HEIM_WEAK_CRYPTO
+
+static OM_uint32
+unwrap_des
+ (OM_uint32 * minor_status,
+ const gsskrb5_ctx context_handle,
+ const gss_buffer_t input_message_buffer,
+ gss_buffer_t output_message_buffer,
+ int * conf_state,
+ gss_qop_t * qop_state,
+ krb5_keyblock *key
+ )
+{
+ u_char *p, *seq;
+ size_t len;
+ EVP_MD_CTX *md5;
+ u_char hash[16];
+ EVP_CIPHER_CTX des_ctx;
+ DES_key_schedule schedule;
+ DES_cblock deskey;
+ DES_cblock zero;
+ size_t i;
+ uint32_t seq_number;
+ size_t padlength;
+ OM_uint32 ret;
+ int cstate;
+ int cmp;
+ int token_len;
+
+ if (IS_DCE_STYLE(context_handle)) {
+ token_len = 22 + 8 + 15; /* 45 */
+ if (input_message_buffer->length < token_len)
+ return GSS_S_BAD_MECH;
+ } else {
+ token_len = input_message_buffer->length;
+ }
+
+ p = input_message_buffer->value;
+ ret = _gsskrb5_verify_header (&p,
+ token_len,
+ "\x02\x01",
+ GSS_KRB5_MECHANISM);
+ if (ret)
+ return ret;
+
+ len = (p - (u_char *)input_message_buffer->value)
+ + 22 + 8;
+ if (input_message_buffer->length < len)
+ return GSS_S_BAD_MECH;
+
+ if (memcmp (p, "\x00\x00", 2) != 0)
+ return GSS_S_BAD_SIG;
+ p += 2;
+ if (memcmp (p, "\x00\x00", 2) == 0) {
+ cstate = 1;
+ } else if (memcmp (p, "\xFF\xFF", 2) == 0) {
+ cstate = 0;
+ } else
+ return GSS_S_BAD_MIC;
+ p += 2;
+ if(conf_state != NULL)
+ *conf_state = cstate;
+ if (memcmp (p, "\xff\xff", 2) != 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+ p += 2;
+ p += 16;
+
+ len = p - (u_char *)input_message_buffer->value;
+
+ if(cstate) {
+ /* decrypt data */
+ memcpy (&deskey, key->keyvalue.data, sizeof(deskey));
+ memset (&zero, 0, sizeof(zero));
+
+ for (i = 0; i < sizeof(deskey); ++i)
+ deskey[i] ^= 0xf0;
+
+
+ EVP_CIPHER_CTX_init(&des_ctx);
+ EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, deskey, zero, 0);
+ EVP_Cipher(&des_ctx, p, p, input_message_buffer->length - len);
+ EVP_CIPHER_CTX_cleanup(&des_ctx);
+
+ memset (&deskey, 0, sizeof(deskey));
+ }
+
+ if (IS_DCE_STYLE(context_handle)) {
+ padlength = 0;
+ } else {
+ /* check pad */
+ ret = _gssapi_verify_pad(input_message_buffer,
+ input_message_buffer->length - len - 8,
+ &padlength);
+ if (ret)
+ return ret;
+ }
+
+ md5 = EVP_MD_CTX_create();
+ EVP_DigestInit_ex(md5, EVP_md5(), NULL);
+ EVP_DigestUpdate(md5, p - 24, 8);
+ EVP_DigestUpdate(md5, p, input_message_buffer->length - len);
+ EVP_DigestFinal_ex(md5, hash, NULL);
+ EVP_MD_CTX_destroy(md5);
+
+ memset (&zero, 0, sizeof(zero));
+ memcpy (&deskey, key->keyvalue.data, sizeof(deskey));
+ DES_set_key_unchecked (&deskey, &schedule);
+ DES_cbc_cksum ((void *)hash, (void *)hash, sizeof(hash),
+ &schedule, &zero);
+ if (ct_memcmp (p - 8, hash, 8) != 0) {
+ memset_s(&deskey, sizeof(deskey), 0, sizeof(deskey));
+ memset_s(&schedule, sizeof(schedule), 0, sizeof(schedule));
+ return GSS_S_BAD_MIC;
+ }
+
+ /* verify sequence number */
+
+ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+
+ p -= 16;
+
+ EVP_CIPHER_CTX_init(&des_ctx);
+ EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, key->keyvalue.data, hash, 0);
+ EVP_Cipher(&des_ctx, p, p, 8);
+ EVP_CIPHER_CTX_cleanup(&des_ctx);
+
+ memset (deskey, 0, sizeof(deskey));
+ memset (&schedule, 0, sizeof(schedule));
+
+ seq = p;
+ _gsskrb5_decode_om_uint32(seq, &seq_number);
+
+ if (context_handle->more_flags & LOCAL)
+ cmp = ct_memcmp(&seq[4], "\xff\xff\xff\xff", 4);
+ else
+ cmp = ct_memcmp(&seq[4], "\x00\x00\x00\x00", 4);
+
+ if (cmp != 0) {
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ return GSS_S_BAD_MIC;
+ }
+
+ ret = _gssapi_msg_order_check(context_handle->order, seq_number);
+ if (ret) {
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ return ret;
+ }
+
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+
+ /* copy out data */
+
+ output_message_buffer->length = input_message_buffer->length
+ - len - padlength - 8;
+ output_message_buffer->value = malloc(output_message_buffer->length);
+ if(output_message_buffer->length != 0 && output_message_buffer->value == NULL)
+ return GSS_S_FAILURE;
+ if (output_message_buffer->value != NULL)
+ memcpy (output_message_buffer->value,
+ p + 24,
+ output_message_buffer->length);
+ return GSS_S_COMPLETE;
+}
+#endif
+
+static OM_uint32
+unwrap_des3
+ (OM_uint32 * minor_status,
+ const gsskrb5_ctx context_handle,
+ krb5_context context,
+ const gss_buffer_t input_message_buffer,
+ gss_buffer_t output_message_buffer,
+ int * conf_state,
+ gss_qop_t * qop_state,
+ krb5_keyblock *key
+ )
+{
+ u_char *p;
+ size_t len;
+ u_char *seq;
+ krb5_data seq_data;
+ u_char cksum[20];
+ uint32_t seq_number;
+ size_t padlength;
+ OM_uint32 ret;
+ int cstate;
+ krb5_crypto crypto;
+ Checksum csum;
+ int cmp;
+ int token_len;
+
+ if (IS_DCE_STYLE(context_handle)) {
+ token_len = 34 + 8 + 15; /* 57 */
+ if (input_message_buffer->length < token_len)
+ return GSS_S_BAD_MECH;
+ } else {
+ token_len = input_message_buffer->length;
+ }
+
+ p = input_message_buffer->value;
+ ret = _gsskrb5_verify_header (&p,
+ token_len,
+ "\x02\x01",
+ GSS_KRB5_MECHANISM);
+ if (ret)
+ return ret;
+
+ len = (p - (u_char *)input_message_buffer->value)
+ + 34 + 8;
+ if (input_message_buffer->length < len)
+ return GSS_S_BAD_MECH;
+
+ if (ct_memcmp (p, "\x04\x00", 2) != 0) /* HMAC SHA1 DES3_KD */
+ return GSS_S_BAD_SIG;
+ p += 2;
+ if (ct_memcmp (p, "\x02\x00", 2) == 0) {
+ cstate = 1;
+ } else if (ct_memcmp (p, "\xff\xff", 2) == 0) {
+ cstate = 0;
+ } else
+ return GSS_S_BAD_MIC;
+ p += 2;
+ if(conf_state != NULL)
+ *conf_state = cstate;
+ if (ct_memcmp (p, "\xff\xff", 2) != 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+ p += 2;
+ p += 28;
+
+ len = p - (u_char *)input_message_buffer->value;
+
+ if(cstate) {
+ /* decrypt data */
+ krb5_data tmp;
+
+ ret = krb5_crypto_init(context, key,
+ ETYPE_DES3_CBC_NONE, &crypto);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ ret = krb5_decrypt(context, crypto, KRB5_KU_USAGE_SEAL,
+ p, input_message_buffer->length - len, &tmp);
+ krb5_crypto_destroy(context, crypto);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ assert (tmp.length == input_message_buffer->length - len);
+
+ memcpy (p, tmp.data, tmp.length);
+ krb5_data_free(&tmp);
+ }
+
+ if (IS_DCE_STYLE(context_handle)) {
+ padlength = 0;
+ } else {
+ /* check pad */
+ ret = _gssapi_verify_pad(input_message_buffer,
+ input_message_buffer->length - len - 8,
+ &padlength);
+ if (ret)
+ return ret;
+ }
+
+ /* verify sequence number */
+
+ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+
+ p -= 28;
+
+ ret = krb5_crypto_init(context, key,
+ ETYPE_DES3_CBC_NONE, &crypto);
+ if (ret) {
+ *minor_status = ret;
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ return GSS_S_FAILURE;
+ }
+ {
+ DES_cblock ivec;
+
+ memcpy(&ivec, p + 8, 8);
+ ret = krb5_decrypt_ivec (context,
+ crypto,
+ KRB5_KU_USAGE_SEQ,
+ p, 8, &seq_data,
+ &ivec);
+ }
+ krb5_crypto_destroy (context, crypto);
+ if (ret) {
+ *minor_status = ret;
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ return GSS_S_FAILURE;
+ }
+ if (seq_data.length != 8) {
+ krb5_data_free (&seq_data);
+ *minor_status = 0;
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ return GSS_S_BAD_MIC;
+ }
+
+ seq = seq_data.data;
+ _gsskrb5_decode_om_uint32(seq, &seq_number);
+
+ if (context_handle->more_flags & LOCAL)
+ cmp = ct_memcmp(&seq[4], "\xff\xff\xff\xff", 4);
+ else
+ cmp = ct_memcmp(&seq[4], "\x00\x00\x00\x00", 4);
+
+ krb5_data_free (&seq_data);
+ if (cmp != 0) {
+ *minor_status = 0;
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ return GSS_S_BAD_MIC;
+ }
+
+ ret = _gssapi_msg_order_check(context_handle->order, seq_number);
+ if (ret) {
+ *minor_status = 0;
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ return ret;
+ }
+
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+
+ /* verify checksum */
+
+ memcpy (cksum, p + 8, 20);
+
+ memcpy (p + 20, p - 8, 8);
+
+ csum.cksumtype = CKSUMTYPE_HMAC_SHA1_DES3;
+ csum.checksum.length = 20;
+ csum.checksum.data = cksum;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_verify_checksum (context, crypto,
+ KRB5_KU_USAGE_SIGN,
+ p + 20,
+ input_message_buffer->length - len + 8,
+ &csum);
+ krb5_crypto_destroy (context, crypto);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ /* copy out data */
+
+ output_message_buffer->length = input_message_buffer->length
+ - len - padlength - 8;
+ output_message_buffer->value = malloc(output_message_buffer->length);
+ if(output_message_buffer->length != 0 && output_message_buffer->value == NULL)
+ return GSS_S_FAILURE;
+ if (output_message_buffer->value != NULL)
+ memcpy (output_message_buffer->value,
+ p + 36,
+ output_message_buffer->length);
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_unwrap
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t input_message_buffer,
+ gss_buffer_t output_message_buffer,
+ int * conf_state,
+ gss_qop_t * qop_state
+ )
+{
+ krb5_keyblock *key;
+ krb5_context context;
+ OM_uint32 ret;
+ gsskrb5_ctx ctx = (gsskrb5_ctx) context_handle;
+
+ output_message_buffer->value = NULL;
+ output_message_buffer->length = 0;
+ if (qop_state != NULL)
+ *qop_state = GSS_C_QOP_DEFAULT;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (ctx->more_flags & IS_CFX)
+ return _gssapi_unwrap_cfx (minor_status, ctx, context,
+ input_message_buffer, output_message_buffer,
+ conf_state, qop_state);
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ ret = _gsskrb5i_get_token_key(ctx, context, &key);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ *minor_status = 0;
+
+ switch (key->keytype) {
+ case KRB5_ENCTYPE_DES_CBC_CRC :
+ case KRB5_ENCTYPE_DES_CBC_MD4 :
+ case KRB5_ENCTYPE_DES_CBC_MD5 :
+#ifdef HEIM_WEAK_CRYPTO
+ ret = unwrap_des (minor_status, ctx,
+ input_message_buffer, output_message_buffer,
+ conf_state, qop_state, key);
+#else
+ ret = GSS_S_FAILURE;
+#endif
+ break;
+ case KRB5_ENCTYPE_DES3_CBC_MD5 :
+ case KRB5_ENCTYPE_DES3_CBC_SHA1 :
+ ret = unwrap_des3 (minor_status, ctx, context,
+ input_message_buffer, output_message_buffer,
+ conf_state, qop_state, key);
+ break;
+ case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5:
+ case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56:
+ ret = _gssapi_unwrap_arcfour (minor_status, ctx, context,
+ input_message_buffer, output_message_buffer,
+ conf_state, qop_state, key);
+ break;
+ default :
+ abort();
+ break;
+ }
+ krb5_free_keyblock (context, key);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/verify_mic.c b/third_party/heimdal/lib/gssapi/krb5/verify_mic.c
new file mode 100644
index 0000000..7070f3d
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/verify_mic.c
@@ -0,0 +1,360 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+#ifdef HEIM_WEAK_CRYPTO
+
+static OM_uint32
+verify_mic_des
+ (OM_uint32 * minor_status,
+ const gsskrb5_ctx context_handle,
+ krb5_context context,
+ const gss_buffer_t message_buffer,
+ const gss_buffer_t token_buffer,
+ gss_qop_t * qop_state,
+ krb5_keyblock *key,
+ const char *type
+ )
+{
+ u_char *p;
+ EVP_MD_CTX *md5;
+ u_char hash[16], *seq;
+ DES_key_schedule schedule;
+ EVP_CIPHER_CTX des_ctx;
+ DES_cblock zero;
+ DES_cblock deskey;
+ uint32_t seq_number;
+ OM_uint32 ret;
+ int cmp;
+
+ p = token_buffer->value;
+ ret = _gsskrb5_verify_header (&p,
+ token_buffer->length,
+ type,
+ GSS_KRB5_MECHANISM);
+ if (ret)
+ return ret;
+
+ if (memcmp(p, "\x00\x00", 2) != 0)
+ return GSS_S_BAD_SIG;
+ p += 2;
+ if (memcmp (p, "\xff\xff\xff\xff", 4) != 0)
+ return GSS_S_BAD_MIC;
+ p += 4;
+ p += 16;
+
+ /* verify checksum */
+ md5 = EVP_MD_CTX_create();
+ EVP_DigestInit_ex(md5, EVP_md5(), NULL);
+ EVP_DigestUpdate(md5, p - 24, 8);
+ EVP_DigestUpdate(md5, message_buffer->value, message_buffer->length);
+ EVP_DigestFinal_ex(md5, hash, NULL);
+ EVP_MD_CTX_destroy(md5);
+
+ memset (&zero, 0, sizeof(zero));
+ memcpy (&deskey, key->keyvalue.data, sizeof(deskey));
+
+ DES_set_key_unchecked (&deskey, &schedule);
+ DES_cbc_cksum ((void *)hash, (void *)hash, sizeof(hash),
+ &schedule, &zero);
+ if (ct_memcmp (p - 8, hash, 8) != 0) {
+ memset_s(deskey, sizeof(deskey), 0, sizeof(deskey));
+ memset_s(&schedule, sizeof(schedule), 0, sizeof(schedule));
+ return GSS_S_BAD_MIC;
+ }
+
+ /* verify sequence number */
+
+ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+
+ p -= 16;
+
+ EVP_CIPHER_CTX_init(&des_ctx);
+ EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, key->keyvalue.data, hash, 0);
+ EVP_Cipher(&des_ctx, p, p, 8);
+ EVP_CIPHER_CTX_cleanup(&des_ctx);
+
+ memset_s(deskey, sizeof(deskey), 0, sizeof(deskey));
+ memset_s(&schedule, sizeof(schedule), 0, sizeof(schedule));
+
+ seq = p;
+ _gsskrb5_decode_om_uint32(seq, &seq_number);
+
+ if (context_handle->more_flags & LOCAL)
+ cmp = ct_memcmp(&seq[4], "\xff\xff\xff\xff", 4);
+ else
+ cmp = ct_memcmp(&seq[4], "\x00\x00\x00\x00", 4);
+
+ if (cmp != 0) {
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ return GSS_S_BAD_MIC;
+ }
+
+ ret = _gssapi_msg_order_check(context_handle->order, seq_number);
+ if (ret) {
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ return ret;
+ }
+
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+
+ return GSS_S_COMPLETE;
+}
+#endif
+
+static OM_uint32
+verify_mic_des3
+ (OM_uint32 * minor_status,
+ const gsskrb5_ctx context_handle,
+ krb5_context context,
+ const gss_buffer_t message_buffer,
+ const gss_buffer_t token_buffer,
+ gss_qop_t * qop_state,
+ krb5_keyblock *key,
+ const char *type
+ )
+{
+ u_char *p;
+ u_char *seq;
+ uint32_t seq_number;
+ OM_uint32 ret;
+ krb5_crypto crypto;
+ krb5_data seq_data;
+ int cmp, docompat;
+ Checksum csum;
+ char *tmp;
+ char ivec[8];
+
+ p = token_buffer->value;
+ ret = _gsskrb5_verify_header (&p,
+ token_buffer->length,
+ type,
+ GSS_KRB5_MECHANISM);
+ if (ret)
+ return ret;
+
+ if (memcmp(p, "\x04\x00", 2) != 0) /* SGN_ALG = HMAC SHA1 DES3-KD */
+ return GSS_S_BAD_SIG;
+ p += 2;
+ if (memcmp (p, "\xff\xff\xff\xff", 4) != 0)
+ return GSS_S_BAD_MIC;
+ p += 4;
+
+ ret = krb5_crypto_init(context, key,
+ ETYPE_DES3_CBC_NONE, &crypto);
+ if (ret){
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ /* verify sequence number */
+ docompat = 0;
+retry:
+ if (docompat)
+ memset(ivec, 0, 8);
+ else
+ memcpy(ivec, p + 8, 8);
+
+ ret = krb5_decrypt_ivec (context,
+ crypto,
+ KRB5_KU_USAGE_SEQ,
+ p, 8, &seq_data, ivec);
+ if (ret) {
+ if (docompat++) {
+ krb5_crypto_destroy (context, crypto);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ } else
+ goto retry;
+ }
+
+ if (seq_data.length != 8) {
+ krb5_data_free (&seq_data);
+ if (docompat++) {
+ krb5_crypto_destroy (context, crypto);
+ return GSS_S_BAD_MIC;
+ } else
+ goto retry;
+ }
+
+ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+
+ seq = seq_data.data;
+ _gsskrb5_decode_om_uint32(seq, &seq_number);
+
+ if (context_handle->more_flags & LOCAL)
+ cmp = ct_memcmp(&seq[4], "\xff\xff\xff\xff", 4);
+ else
+ cmp = ct_memcmp(&seq[4], "\x00\x00\x00\x00", 4);
+
+ krb5_data_free (&seq_data);
+ if (cmp != 0) {
+ krb5_crypto_destroy (context, crypto);
+ *minor_status = 0;
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ return GSS_S_BAD_MIC;
+ }
+
+ ret = _gssapi_msg_order_check(context_handle->order, seq_number);
+ if (ret) {
+ krb5_crypto_destroy (context, crypto);
+ *minor_status = 0;
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ return ret;
+ }
+
+ /* verify checksum */
+
+ tmp = malloc (message_buffer->length + 8);
+ if (tmp == NULL) {
+ krb5_crypto_destroy (context, crypto);
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ memcpy (tmp, p - 8, 8);
+ memcpy (tmp + 8, message_buffer->value, message_buffer->length);
+
+ csum.cksumtype = CKSUMTYPE_HMAC_SHA1_DES3;
+ csum.checksum.length = 20;
+ csum.checksum.data = p + 8;
+
+ krb5_crypto_destroy (context, crypto);
+ ret = krb5_crypto_init(context, key,
+ ETYPE_DES3_CBC_SHA1, &crypto);
+ if (ret == 0)
+ ret = krb5_verify_checksum(context, crypto,
+ KRB5_KU_USAGE_SIGN,
+ tmp, message_buffer->length + 8,
+ &csum);
+ free (tmp);
+ if (ret) {
+ krb5_crypto_destroy (context, crypto);
+ *minor_status = ret;
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+ return GSS_S_BAD_MIC;
+ }
+ HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+
+ krb5_crypto_destroy (context, crypto);
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_gsskrb5_verify_mic_internal
+ (OM_uint32 * minor_status,
+ const gsskrb5_ctx ctx,
+ krb5_context context,
+ const gss_buffer_t message_buffer,
+ const gss_buffer_t token_buffer,
+ gss_qop_t * qop_state,
+ const char * type
+ )
+{
+ krb5_keyblock *key;
+ OM_uint32 ret;
+
+ if (ctx->more_flags & IS_CFX)
+ return _gssapi_verify_mic_cfx (minor_status, ctx,
+ context, message_buffer, token_buffer,
+ qop_state);
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ ret = _gsskrb5i_get_token_key(ctx, context, &key);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ *minor_status = 0;
+
+ switch (key->keytype) {
+ case KRB5_ENCTYPE_DES_CBC_CRC :
+ case KRB5_ENCTYPE_DES_CBC_MD4 :
+ case KRB5_ENCTYPE_DES_CBC_MD5 :
+#ifdef HEIM_WEAK_CRYPTO
+ ret = verify_mic_des (minor_status, ctx, context,
+ message_buffer, token_buffer, qop_state, key,
+ type);
+#else
+ ret = GSS_S_FAILURE;
+#endif
+ break;
+ case KRB5_ENCTYPE_DES3_CBC_MD5 :
+ case KRB5_ENCTYPE_DES3_CBC_SHA1 :
+ ret = verify_mic_des3 (minor_status, ctx, context,
+ message_buffer, token_buffer, qop_state, key,
+ type);
+ break;
+ case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5:
+ case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56:
+ ret = _gssapi_verify_mic_arcfour (minor_status, ctx,
+ context,
+ message_buffer, token_buffer,
+ qop_state, key, type);
+ break;
+ default :
+ abort();
+ }
+ krb5_free_keyblock (context, key);
+
+ return ret;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_verify_mic
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t message_buffer,
+ const gss_buffer_t token_buffer,
+ gss_qop_t * qop_state
+ )
+{
+ krb5_context context;
+ OM_uint32 ret;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (qop_state != NULL)
+ *qop_state = GSS_C_QOP_DEFAULT;
+
+ ret = _gsskrb5_verify_mic_internal(minor_status,
+ (gsskrb5_ctx)context_handle,
+ context,
+ message_buffer, token_buffer,
+ qop_state, (void *)(intptr_t)"\x01\x01");
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/krb5/wrap.c b/third_party/heimdal/lib/gssapi/krb5/wrap.c
new file mode 100644
index 0000000..481e303
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/krb5/wrap.c
@@ -0,0 +1,592 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "gsskrb5_locl.h"
+
+/*
+ * Return initiator subkey, or if that doesn't exists, the subkey.
+ */
+
+krb5_error_code
+_gsskrb5i_get_initiator_subkey(const gsskrb5_ctx ctx,
+ krb5_context context,
+ krb5_keyblock **key)
+{
+ krb5_error_code ret;
+ *key = NULL;
+
+ if (ctx->more_flags & LOCAL) {
+ ret = krb5_auth_con_getlocalsubkey(context,
+ ctx->auth_context,
+ key);
+ } else {
+ ret = krb5_auth_con_getremotesubkey(context,
+ ctx->auth_context,
+ key);
+ }
+ if (ret == 0 && *key == NULL)
+ ret = krb5_auth_con_getkey(context,
+ ctx->auth_context,
+ key);
+ if (ret == 0 && *key == NULL) {
+ krb5_set_error_message(context, 0, "No initiator subkey available");
+ return GSS_KRB5_S_KG_NO_SUBKEY;
+ }
+ return ret;
+}
+
+krb5_error_code
+_gsskrb5i_get_acceptor_subkey(const gsskrb5_ctx ctx,
+ krb5_context context,
+ krb5_keyblock **key)
+{
+ krb5_error_code ret;
+ *key = NULL;
+
+ if (ctx->more_flags & LOCAL) {
+ ret = krb5_auth_con_getremotesubkey(context,
+ ctx->auth_context,
+ key);
+ } else {
+ ret = krb5_auth_con_getlocalsubkey(context,
+ ctx->auth_context,
+ key);
+ }
+ if (ret == 0 && *key == NULL) {
+ krb5_set_error_message(context, 0, "No acceptor subkey available");
+ return GSS_KRB5_S_KG_NO_SUBKEY;
+ }
+ return ret;
+}
+
+OM_uint32
+_gsskrb5i_get_token_key(const gsskrb5_ctx ctx,
+ krb5_context context,
+ krb5_keyblock **key)
+{
+ _gsskrb5i_get_acceptor_subkey(ctx, context, key);
+ if(*key == NULL) {
+ /*
+ * Only use the initiator subkey or ticket session key if an
+ * acceptor subkey was not required.
+ */
+ if ((ctx->more_flags & ACCEPTOR_SUBKEY) == 0)
+ _gsskrb5i_get_initiator_subkey(ctx, context, key);
+ }
+ if (*key == NULL) {
+ krb5_set_error_message(context, 0, "No token key available");
+ return GSS_KRB5_S_KG_NO_SUBKEY;
+ }
+ return 0;
+}
+
+static OM_uint32
+sub_wrap_size (
+ OM_uint32 req_output_size,
+ OM_uint32 * max_input_size,
+ int blocksize,
+ int extrasize
+ )
+{
+ size_t len, total_len;
+
+ len = 8 + req_output_size + blocksize + extrasize;
+
+ _gsskrb5_encap_length(len, &len, &total_len, GSS_KRB5_MECHANISM);
+
+ total_len -= req_output_size; /* token length */
+ if (total_len < req_output_size) {
+ *max_input_size = (req_output_size - total_len);
+ (*max_input_size) &= (~(OM_uint32)(blocksize - 1));
+ } else {
+ *max_input_size = 0;
+ }
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_wrap_size_limit (
+ OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ OM_uint32 req_output_size,
+ OM_uint32 * max_input_size
+ )
+{
+ krb5_context context;
+ krb5_keyblock *key;
+ OM_uint32 ret;
+ const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (ctx->more_flags & IS_CFX)
+ return _gssapi_wrap_size_cfx(minor_status, ctx, context,
+ conf_req_flag, qop_req,
+ req_output_size, max_input_size);
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ ret = _gsskrb5i_get_token_key(ctx, context, &key);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ switch (key->keytype) {
+ case KRB5_ENCTYPE_DES_CBC_CRC :
+ case KRB5_ENCTYPE_DES_CBC_MD4 :
+ case KRB5_ENCTYPE_DES_CBC_MD5 :
+#ifdef HEIM_WEAK_CRYPTO
+ ret = sub_wrap_size(req_output_size, max_input_size, 8, 22);
+#else
+ ret = GSS_S_FAILURE;
+#endif
+ break;
+ case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5:
+ case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56:
+ ret = _gssapi_wrap_size_arcfour(minor_status, ctx, context,
+ conf_req_flag, qop_req,
+ req_output_size, max_input_size, key);
+ break;
+ case KRB5_ENCTYPE_DES3_CBC_MD5 :
+ case KRB5_ENCTYPE_DES3_CBC_SHA1 :
+ ret = sub_wrap_size(req_output_size, max_input_size, 8, 34);
+ break;
+ default :
+ abort();
+ break;
+ }
+ krb5_free_keyblock (context, key);
+ *minor_status = 0;
+ return ret;
+}
+
+#ifdef HEIM_WEAK_CRYPTO
+
+static OM_uint32
+wrap_des
+ (OM_uint32 * minor_status,
+ const gsskrb5_ctx ctx,
+ krb5_context context,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ const gss_buffer_t input_message_buffer,
+ int * conf_state,
+ gss_buffer_t output_message_buffer,
+ krb5_keyblock *key
+ )
+{
+ u_char *p;
+ EVP_MD_CTX *md5;
+ u_char hash[16];
+ DES_key_schedule schedule;
+ EVP_CIPHER_CTX des_ctx;
+ DES_cblock deskey;
+ DES_cblock zero;
+ size_t i;
+ int32_t seq_number;
+ size_t len, total_len, padlength, datalen;
+
+ if (IS_DCE_STYLE(ctx)) {
+ padlength = 0;
+ datalen = input_message_buffer->length;
+ len = 22 + 8;
+ _gsskrb5_encap_length (len, &len, &total_len, GSS_KRB5_MECHANISM);
+ total_len += datalen;
+ datalen += 8;
+ } else {
+ padlength = 8 - (input_message_buffer->length % 8);
+ datalen = input_message_buffer->length + padlength + 8;
+ len = datalen + 22;
+ _gsskrb5_encap_length (len, &len, &total_len, GSS_KRB5_MECHANISM);
+ }
+
+ output_message_buffer->length = total_len;
+ output_message_buffer->value = malloc (total_len);
+ if (output_message_buffer->value == NULL) {
+ output_message_buffer->length = 0;
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ p = _gsskrb5_make_header(output_message_buffer->value,
+ len,
+ "\x02\x01", /* TOK_ID */
+ GSS_KRB5_MECHANISM);
+
+ /* SGN_ALG */
+ memcpy (p, "\x00\x00", 2);
+ p += 2;
+ /* SEAL_ALG */
+ if(conf_req_flag)
+ memcpy (p, "\x00\x00", 2);
+ else
+ memcpy (p, "\xff\xff", 2);
+ p += 2;
+ /* Filler */
+ memcpy (p, "\xff\xff", 2);
+ p += 2;
+
+ /* fill in later */
+ memset (p, 0, 16);
+ p += 16;
+
+ /* confounder + data + pad */
+ krb5_generate_random_block(p, 8);
+ memcpy (p + 8, input_message_buffer->value,
+ input_message_buffer->length);
+ memset (p + 8 + input_message_buffer->length, padlength, padlength);
+
+ /* checksum */
+ md5 = EVP_MD_CTX_create();
+ EVP_DigestInit_ex(md5, EVP_md5(), NULL);
+ EVP_DigestUpdate(md5, p - 24, 8);
+ EVP_DigestUpdate(md5, p, datalen);
+ EVP_DigestFinal_ex(md5, hash, NULL);
+ EVP_MD_CTX_destroy(md5);
+
+ memset (&zero, 0, sizeof(zero));
+ memcpy (&deskey, key->keyvalue.data, sizeof(deskey));
+ DES_set_key_unchecked (&deskey, &schedule);
+ DES_cbc_cksum ((void *)hash, (void *)hash, sizeof(hash),
+ &schedule, &zero);
+ memcpy (p - 8, hash, 8);
+
+ /* sequence number */
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ krb5_auth_con_getlocalseqnumber (context,
+ ctx->auth_context,
+ &seq_number);
+
+ p -= 16;
+ p[0] = (seq_number >> 0) & 0xFF;
+ p[1] = (seq_number >> 8) & 0xFF;
+ p[2] = (seq_number >> 16) & 0xFF;
+ p[3] = (seq_number >> 24) & 0xFF;
+ memset (p + 4,
+ (ctx->more_flags & LOCAL) ? 0 : 0xFF,
+ 4);
+
+ EVP_CIPHER_CTX_init(&des_ctx);
+ EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, key->keyvalue.data, p + 8, 1);
+ EVP_Cipher(&des_ctx, p, p, 8);
+ EVP_CIPHER_CTX_cleanup(&des_ctx);
+
+ krb5_auth_con_setlocalseqnumber (context,
+ ctx->auth_context,
+ ++seq_number);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ /* encrypt the data */
+ p += 16;
+
+ if(conf_req_flag) {
+ memcpy (&deskey, key->keyvalue.data, sizeof(deskey));
+
+ for (i = 0; i < sizeof(deskey); ++i)
+ deskey[i] ^= 0xf0;
+
+ EVP_CIPHER_CTX_init(&des_ctx);
+ EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, deskey, zero, 1);
+ EVP_Cipher(&des_ctx, p, p, datalen);
+ EVP_CIPHER_CTX_cleanup(&des_ctx);
+ }
+ memset (deskey, 0, sizeof(deskey));
+ memset (&schedule, 0, sizeof(schedule));
+
+ if(conf_state != NULL)
+ *conf_state = conf_req_flag;
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+#endif
+
+static OM_uint32
+wrap_des3
+ (OM_uint32 * minor_status,
+ const gsskrb5_ctx ctx,
+ krb5_context context,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ const gss_buffer_t input_message_buffer,
+ int * conf_state,
+ gss_buffer_t output_message_buffer,
+ krb5_keyblock *key
+ )
+{
+ u_char *p;
+ u_char seq[8];
+ int32_t seq_number;
+ size_t len, total_len, padlength, datalen;
+ uint32_t ret;
+ krb5_crypto crypto;
+ Checksum cksum;
+ krb5_data encdata;
+
+ if (IS_DCE_STYLE(ctx)) {
+ padlength = 0;
+ datalen = input_message_buffer->length;
+ len = 34 + 8;
+ _gsskrb5_encap_length (len, &len, &total_len, GSS_KRB5_MECHANISM);
+ total_len += datalen;
+ datalen += 8;
+ } else {
+ padlength = 8 - (input_message_buffer->length % 8);
+ datalen = input_message_buffer->length + padlength + 8;
+ len = datalen + 34;
+ _gsskrb5_encap_length (len, &len, &total_len, GSS_KRB5_MECHANISM);
+ }
+
+ output_message_buffer->length = total_len;
+ output_message_buffer->value = malloc (total_len);
+ if (output_message_buffer->value == NULL) {
+ output_message_buffer->length = 0;
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ p = _gsskrb5_make_header(output_message_buffer->value,
+ len,
+ "\x02\x01", /* TOK_ID */
+ GSS_KRB5_MECHANISM);
+
+ /* SGN_ALG */
+ memcpy (p, "\x04\x00", 2); /* HMAC SHA1 DES3-KD */
+ p += 2;
+ /* SEAL_ALG */
+ if(conf_req_flag)
+ memcpy (p, "\x02\x00", 2); /* DES3-KD */
+ else
+ memcpy (p, "\xff\xff", 2);
+ p += 2;
+ /* Filler */
+ memcpy (p, "\xff\xff", 2);
+ p += 2;
+
+ /* calculate checksum (the above + confounder + data + pad) */
+
+ memcpy (p + 20, p - 8, 8);
+ krb5_generate_random_block(p + 28, 8);
+ memcpy (p + 28 + 8, input_message_buffer->value,
+ input_message_buffer->length);
+ memset (p + 28 + 8 + input_message_buffer->length, padlength, padlength);
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret) {
+ free (output_message_buffer->value);
+ output_message_buffer->length = 0;
+ output_message_buffer->value = NULL;
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_create_checksum (context,
+ crypto,
+ KRB5_KU_USAGE_SIGN,
+ 0,
+ p + 20,
+ datalen + 8,
+ &cksum);
+ krb5_crypto_destroy (context, crypto);
+ if (ret) {
+ free (output_message_buffer->value);
+ output_message_buffer->length = 0;
+ output_message_buffer->value = NULL;
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ /* zero out SND_SEQ + SGN_CKSUM in case */
+ memset (p, 0, 28);
+
+ memcpy (p + 8, cksum.checksum.data, cksum.checksum.length);
+ free_Checksum (&cksum);
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ /* sequence number */
+ krb5_auth_con_getlocalseqnumber (context,
+ ctx->auth_context,
+ &seq_number);
+
+ seq[0] = (seq_number >> 0) & 0xFF;
+ seq[1] = (seq_number >> 8) & 0xFF;
+ seq[2] = (seq_number >> 16) & 0xFF;
+ seq[3] = (seq_number >> 24) & 0xFF;
+ memset (seq + 4,
+ (ctx->more_flags & LOCAL) ? 0 : 0xFF,
+ 4);
+
+
+ ret = krb5_crypto_init(context, key, ETYPE_DES3_CBC_NONE,
+ &crypto);
+ if (ret) {
+ free (output_message_buffer->value);
+ output_message_buffer->length = 0;
+ output_message_buffer->value = NULL;
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ {
+ DES_cblock ivec;
+
+ memcpy (&ivec, p + 8, 8);
+ ret = krb5_encrypt_ivec (context,
+ crypto,
+ KRB5_KU_USAGE_SEQ,
+ seq, 8, &encdata,
+ &ivec);
+ }
+ krb5_crypto_destroy (context, crypto);
+ if (ret) {
+ free (output_message_buffer->value);
+ output_message_buffer->length = 0;
+ output_message_buffer->value = NULL;
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ assert (encdata.length == 8);
+
+ memcpy (p, encdata.data, encdata.length);
+ krb5_data_free (&encdata);
+
+ krb5_auth_con_setlocalseqnumber (context,
+ ctx->auth_context,
+ ++seq_number);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ /* encrypt the data */
+ p += 28;
+
+ if(conf_req_flag) {
+ krb5_data tmp;
+
+ ret = krb5_crypto_init(context, key,
+ ETYPE_DES3_CBC_NONE, &crypto);
+ if (ret) {
+ free (output_message_buffer->value);
+ output_message_buffer->length = 0;
+ output_message_buffer->value = NULL;
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ ret = krb5_encrypt(context, crypto, KRB5_KU_USAGE_SEAL,
+ p, datalen, &tmp);
+ krb5_crypto_destroy(context, crypto);
+ if (ret) {
+ free (output_message_buffer->value);
+ output_message_buffer->length = 0;
+ output_message_buffer->value = NULL;
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ assert (tmp.length == datalen);
+
+ memcpy (p, tmp.data, datalen);
+ krb5_data_free(&tmp);
+ }
+ if(conf_state != NULL)
+ *conf_state = conf_req_flag;
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_wrap
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ const gss_buffer_t input_message_buffer,
+ int * conf_state,
+ gss_buffer_t output_message_buffer
+ )
+{
+ krb5_context context;
+ krb5_keyblock *key;
+ OM_uint32 ret;
+ const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle;
+
+ output_message_buffer->value = NULL;
+ output_message_buffer->length = 0;
+
+ GSSAPI_KRB5_INIT (&context);
+
+ if (ctx->more_flags & IS_CFX)
+ return _gssapi_wrap_cfx (minor_status, ctx, context, conf_req_flag,
+ input_message_buffer, conf_state,
+ output_message_buffer);
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+ ret = _gsskrb5i_get_token_key(ctx, context, &key);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ switch (key->keytype) {
+ case KRB5_ENCTYPE_DES_CBC_CRC :
+ case KRB5_ENCTYPE_DES_CBC_MD4 :
+ case KRB5_ENCTYPE_DES_CBC_MD5 :
+#ifdef HEIM_WEAK_CRYPTO
+ ret = wrap_des (minor_status, ctx, context, conf_req_flag,
+ qop_req, input_message_buffer, conf_state,
+ output_message_buffer, key);
+#else
+ ret = GSS_S_FAILURE;
+#endif
+ break;
+ case KRB5_ENCTYPE_DES3_CBC_MD5 :
+ case KRB5_ENCTYPE_DES3_CBC_SHA1 :
+ ret = wrap_des3 (minor_status, ctx, context, conf_req_flag,
+ qop_req, input_message_buffer, conf_state,
+ output_message_buffer, key);
+ break;
+ case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5:
+ case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56:
+ ret = _gssapi_wrap_arcfour (minor_status, ctx, context, conf_req_flag,
+ qop_req, input_message_buffer, conf_state,
+ output_message_buffer, key);
+ break;
+ default :
+ abort();
+ break;
+ }
+ krb5_free_keyblock (context, key);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/libgssapi-exports.def b/third_party/heimdal/lib/gssapi/libgssapi-exports.def
new file mode 100644
index 0000000..6077c8e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/libgssapi-exports.def
@@ -0,0 +1,203 @@
+EXPORTS
+ __gss_c_nt_anonymous_oid_desc DATA
+ __gss_c_nt_composite_export_oid_desc DATA
+ __gss_c_nt_export_name_oid_desc DATA
+ __gss_c_nt_hostbased_service_oid_desc DATA
+ __gss_c_nt_hostbased_service_x_oid_desc DATA
+ __gss_c_nt_machine_uid_name_oid_desc DATA
+ __gss_c_nt_string_uid_name_oid_desc DATA
+ __gss_c_nt_user_name_oid_desc DATA
+ __gss_krb5_nt_principal_name_oid_desc DATA
+ __gss_c_attr_stream_sizes_oid_desc DATA
+ __gss_c_attr_local_login_user DATA
+ gss_accept_sec_context
+ gss_acquire_cred
+ gss_acquire_cred_impersonate_name
+ gss_acquire_cred_from
+ gss_acquire_cred_with_password
+ gss_add_buffer_set_member
+ gss_add_cred
+ gss_add_cred_from
+ gss_add_cred_with_password
+ gss_add_oid_set_member
+ gss_authorize_localname
+ gss_canonicalize_name
+ gss_compare_name
+ gss_context_query_attributes
+ gss_context_time
+ gss_create_empty_buffer_set
+ gss_create_empty_oid_set
+ gss_decapsulate_token
+ gss_delete_name_attribute
+ gss_delete_sec_context
+ gss_display_mech_attr
+ gss_display_name
+ gss_display_name_ext
+ gss_display_status
+ gss_duplicate_name
+ gss_duplicate_oid
+ gss_duplicate_oid_set
+ gss_encapsulate_token
+ gss_export_cred
+ gss_export_name
+ gss_export_name_composite
+ gss_export_sec_context
+ gss_get_mic
+ gss_get_neg_mechs
+ gss_get_name_attribute
+ gss_import_cred
+ gss_import_name
+ gss_import_sec_context
+ gss_indicate_mechs
+ gss_indicate_mechs_by_attrs
+ gss_init_sec_context
+ gss_inquire_attrs_for_mech
+ gss_inquire_context
+ gss_inquire_cred
+ gss_inquire_cred_by_mech
+ gss_inquire_cred_by_oid
+ gss_inquire_mech_for_saslname
+ gss_inquire_mechs_for_name
+ gss_inquire_name
+ gss_inquire_names_for_mech
+ gss_inquire_saslname_for_mech
+ gss_inquire_sec_context_by_oid ;!
+ gss_krb5_ccache_name
+ gss_krb5_copy_ccache
+ gss_krb5_export_lucid_sec_context
+ gss_krb5_free_lucid_sec_context
+ gss_krb5_get_tkt_flags
+ gss_krb5_import_cred
+ gss_krb5_set_allowable_enctypes
+ gss_localname
+ gss_mg_collect_error
+ gss_mo_get
+ gss_mo_set
+ gss_mo_list
+ gss_mo_name
+ gss_name_to_oid
+ gss_oid_to_name
+ gss_oid_equal
+ gss_oid_to_str
+ gss_pname_to_uid
+ gss_process_context_token
+ gss_pseudo_random
+ gss_release_buffer
+ gss_release_buffer_set
+ gss_release_cred
+ gss_release_iov_buffer
+ gss_release_name
+ gss_release_oid
+ gss_release_oid_set
+ gss_seal
+ gss_set_cred_option
+ gss_set_name_attribute
+ gss_set_log_function
+ gss_set_neg_mechs
+ gss_set_sec_context_option
+ gss_sign
+ gss_store_cred
+ gss_store_cred_into
+ gss_store_cred_into2
+ gss_test_oid_set_member
+ gss_unseal
+ gss_unwrap
+ gss_unwrap_aead
+ gss_unwrap_iov
+ gss_userok
+ gss_verify
+ gss_verify_mic
+ gss_wrap
+ gss_wrap_aead
+ gss_wrap_iov
+ gss_wrap_iov_length
+ gss_wrap_size_limit
+ gsskrb5_extract_authtime_from_sec_context
+ gsskrb5_extract_authz_data_from_sec_context
+ gsskrb5_extract_service_keyblock
+ gsskrb5_get_initiator_subkey
+ gsskrb5_get_subkey
+ gsskrb5_get_time_offset
+ gsskrb5_register_acceptor_identity
+ gsskrb5_set_default_realm
+ gsskrb5_set_dns_canonicalize
+ gsskrb5_set_send_to_kdc
+ gsskrb5_set_time_offset
+ krb5_gss_register_acceptor_identity
+
+; _gsskrb5cfx_ are really internal symbols, but export
+; then now to make testing easier.
+ _gsskrb5cfx_wrap_length_cfx
+ _gssapi_wrap_size_cfx
+
+ initialize_gk5_error_table_r ;!
+
+ __gss_krb5_copy_ccache_x_oid_desc DATA
+ __gss_krb5_get_tkt_flags_x_oid_desc DATA
+ __gss_krb5_extract_authz_data_from_sec_context_x_oid_desc DATA
+ __gss_krb5_compat_des3_mic_x_oid_desc DATA
+ __gss_krb5_register_acceptor_identity_x_oid_desc DATA
+ __gss_krb5_export_lucid_context_x_oid_desc DATA
+ __gss_krb5_export_lucid_context_v1_x_oid_desc DATA
+ __gss_krb5_set_dns_canonicalize_x_oid_desc DATA
+ __gss_krb5_get_subkey_x_oid_desc DATA
+ __gss_krb5_get_initiator_subkey_x_oid_desc DATA
+ __gss_krb5_get_acceptor_subkey_x_oid_desc DATA
+ __gss_krb5_send_to_kdc_x_oid_desc DATA
+ __gss_krb5_get_authtime_x_oid_desc DATA
+ __gss_krb5_get_service_keyblock_x_oid_desc DATA
+ __gss_krb5_set_allowable_enctypes_x_oid_desc DATA
+ __gss_krb5_set_default_realm_x_oid_desc DATA
+ __gss_krb5_ccache_name_x_oid_desc DATA
+ __gss_krb5_set_time_offset_x_oid_desc DATA
+ __gss_krb5_get_time_offset_x_oid_desc DATA
+ __gss_krb5_plugin_register_x_oid_desc DATA
+ __gss_ntlm_get_session_key_x_oid_desc DATA
+ __gss_c_nt_ntlm_oid_desc DATA
+ __gss_c_nt_dn_oid_desc DATA
+ __gss_krb5_nt_principal_name_referral_oid_desc DATA
+ __gss_c_ntlm_avguest_oid_desc DATA
+ __gss_c_ntlm_v1_oid_desc DATA
+ __gss_c_ntlm_v2_oid_desc DATA
+ __gss_c_ntlm_session_key_oid_desc DATA
+ __gss_c_ntlm_force_v1_oid_desc DATA
+ __gss_krb5_cred_no_ci_flags_x_oid_desc DATA
+ __gss_krb5_import_cred_x_oid_desc DATA
+ __gss_c_ma_sasl_mech_name_oid_desc DATA
+ __gss_c_ma_mech_name_oid_desc DATA
+ __gss_c_ma_mech_description_oid_desc DATA
+ __gss_sasl_digest_md5_mechanism_oid_desc DATA
+ __gss_krb5_mechanism_oid_desc DATA
+ __gss_ntlm_mechanism_oid_desc DATA
+ __gss_spnego_mechanism_oid_desc DATA
+ __gss_sanon_x25519_mechanism_oid_desc DATA
+ __gss_c_ma_mech_concrete_oid_desc DATA
+ __gss_c_ma_mech_pseudo_oid_desc DATA
+ __gss_c_ma_mech_composite_oid_desc DATA
+ __gss_c_ma_mech_nego_oid_desc DATA
+ __gss_c_ma_mech_glue_oid_desc DATA
+ __gss_c_ma_not_mech_oid_desc DATA
+ __gss_c_ma_deprecated_oid_desc DATA
+ __gss_c_ma_not_dflt_mech_oid_desc DATA
+ __gss_c_ma_itok_framed_oid_desc DATA
+ __gss_c_ma_auth_init_oid_desc DATA
+ __gss_c_ma_auth_targ_oid_desc DATA
+ __gss_c_ma_auth_init_init_oid_desc DATA
+ __gss_c_ma_auth_targ_init_oid_desc DATA
+ __gss_c_ma_auth_init_anon_oid_desc DATA
+ __gss_c_ma_auth_targ_anon_oid_desc DATA
+ __gss_c_ma_deleg_cred_oid_desc DATA
+ __gss_c_ma_integ_prot_oid_desc DATA
+ __gss_c_ma_conf_prot_oid_desc DATA
+ __gss_c_ma_mic_oid_desc DATA
+ __gss_c_ma_wrap_oid_desc DATA
+ __gss_c_ma_prot_ready_oid_desc DATA
+ __gss_c_ma_replay_det_oid_desc DATA
+ __gss_c_ma_oos_det_oid_desc DATA
+ __gss_c_ma_cbindings_oid_desc DATA
+ __gss_c_ma_pfs_oid_desc DATA
+ __gss_c_ma_compress_oid_desc DATA
+ __gss_c_ma_ctx_trans_oid_desc DATA
+ __gss_c_ma_negoex_and_spnego_oid_desc DATA
+ __gss_c_inq_negoex_key_oid_desc DATA
+ __gss_c_inq_negoex_verify_key_oid_desc DATA
diff --git a/third_party/heimdal/lib/gssapi/libgssapi-version.rc b/third_party/heimdal/lib/gssapi/libgssapi-version.rc
new file mode 100644
index 0000000..074066f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/libgssapi-version.rc
@@ -0,0 +1,36 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#define RC_FILE_TYPE VFT_DLL
+#define RC_FILE_DESC_0409 "Generic Security Service Application Program Interface library"
+#define RC_FILE_ORIG_0409 "gssapi.dll"
+
+#include "../../windows/version.rc"
diff --git a/third_party/heimdal/lib/gssapi/mech/compat.h b/third_party/heimdal/lib/gssapi/mech/compat.h
new file mode 100644
index 0000000..d23a6e9
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/compat.h
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2010, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_saslname_for_mech_t (
+ OM_uint32 *, /* minor_status */
+ const gss_OID, /* desired_mech */
+ gss_buffer_t, /* sasl_mech_name */
+ gss_buffer_t, /* mech_name */
+ gss_buffer_t /* mech_description */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_mech_for_saslname_t (
+ OM_uint32 *, /* minor_status */
+ const gss_buffer_t, /* sasl_mech_name */
+ gss_OID * /* mech_type */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_attrs_for_mech_t (
+ OM_uint32 *, /* minor_status */
+ gss_const_OID, /* mech */
+ gss_OID_set *, /* mech_attrs */
+ gss_OID_set * /* known_mech_attrs */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_acquire_cred_with_password_t
+ (OM_uint32 *, /* minor_status */
+ gss_const_name_t, /* desired_name */
+ const gss_buffer_t, /* password */
+ OM_uint32, /* time_req */
+ const gss_OID_set, /* desired_mechs */
+ gss_cred_usage_t, /* cred_usage */
+ gss_cred_id_t *, /* output_cred_handle */
+ gss_OID_set *, /* actual_mechs */
+ OM_uint32 * /* time_rec */
+ );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_add_cred_with_password_t (
+ OM_uint32 *, /* minor_status */
+ gss_const_cred_id_t, /* input_cred_handle */
+ gss_const_name_t, /* desired_name */
+ const gss_OID, /* desired_mech */
+ const gss_buffer_t, /* password */
+ gss_cred_usage_t, /* cred_usage */
+ OM_uint32, /* initiator_time_req */
+ OM_uint32, /* acceptor_time_req */
+ gss_cred_id_t *, /* output_cred_handle */
+ gss_OID_set *, /* actual_mechs */
+ OM_uint32 *, /* initiator_time_rec */
+ OM_uint32 * /* acceptor_time_rec */
+ );
+
+/*
+ * API-as-SPI compatibility for compatibility with MIT mechanisms;
+ * native Heimdal mechanisms should not use these.
+ */
+struct gss_mech_compat_desc_struct {
+ _gss_inquire_saslname_for_mech_t *gmc_inquire_saslname_for_mech;
+ _gss_inquire_mech_for_saslname_t *gmc_inquire_mech_for_saslname;
+ _gss_inquire_attrs_for_mech_t *gmc_inquire_attrs_for_mech;
+ _gss_acquire_cred_with_password_t *gmc_acquire_cred_with_password;
+#if 0
+ _gss_add_cred_with_password_t *gmc_add_cred_with_password;
+#endif
+};
+
diff --git a/third_party/heimdal/lib/gssapi/mech/context.c b/third_party/heimdal/lib/gssapi/mech/context.c
new file mode 100644
index 0000000..83e2cef
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/context.c
@@ -0,0 +1,361 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+#include "heim_threads.h"
+#include <krb5.h>
+#include "krb5_locl.h"
+#include "negoex_err.h"
+
+struct mg_thread_ctx {
+ gss_OID mech;
+ OM_uint32 min_stat;
+ gss_buffer_desc min_error;
+ krb5_context context;
+};
+
+static HEIMDAL_MUTEX context_mutex = HEIMDAL_MUTEX_INITIALIZER;
+static int created_key;
+static HEIMDAL_thread_key context_key;
+
+
+static void
+destroy_context(void *ptr)
+{
+ struct mg_thread_ctx *mg = ptr;
+ OM_uint32 junk;
+
+ if (mg == NULL)
+ return;
+
+ gss_release_buffer(&junk, &mg->min_error);
+
+ if (mg->context)
+ krb5_free_context(mg->context);
+
+ free(mg);
+}
+
+
+static struct mg_thread_ctx *
+_gss_mechglue_thread(void)
+{
+ struct mg_thread_ctx *ctx;
+ int ret = 0;
+
+ HEIMDAL_MUTEX_lock(&context_mutex);
+
+ if (!created_key) {
+ HEIMDAL_key_create(&context_key, destroy_context, ret);
+ if (ret) {
+ HEIMDAL_MUTEX_unlock(&context_mutex);
+ return NULL;
+ }
+ created_key = 1;
+ }
+ HEIMDAL_MUTEX_unlock(&context_mutex);
+
+ ctx = HEIMDAL_getspecific(context_key);
+ if (ctx == NULL) {
+
+ ctx = calloc(1, sizeof(*ctx));
+ if (ctx == NULL)
+ return NULL;
+
+ ret = krb5_init_context(&ctx->context);
+ if (ret) {
+ free(ctx);
+ return NULL;
+ }
+
+ krb5_add_et_list(ctx->context, initialize_ngex_error_table_r);
+
+ HEIMDAL_setspecific(context_key, ctx, ret);
+ if (ret) {
+ krb5_free_context(ctx->context);
+ free(ctx);
+ return NULL;
+ }
+ }
+ return ctx;
+}
+
+krb5_context
+_gss_mg_krb5_context(void)
+{
+ struct mg_thread_ctx *mg;
+
+ mg = _gss_mechglue_thread();
+
+ return mg ? mg->context : NULL;
+}
+
+OM_uint32
+_gss_mg_get_error(const gss_OID mech,
+ OM_uint32 value,
+ gss_buffer_t string)
+{
+ struct mg_thread_ctx *mg;
+
+ mg = _gss_mechglue_thread();
+ if (mg == NULL)
+ return GSS_S_BAD_STATUS;
+
+ if (value != mg->min_stat || mg->min_error.length == 0) {
+ _mg_buffer_zero(string);
+ return GSS_S_BAD_STATUS;
+ }
+ string->value = malloc(mg->min_error.length);
+ if (string->value == NULL) {
+ _mg_buffer_zero(string);
+ return GSS_S_FAILURE;
+ }
+ string->length = mg->min_error.length;
+ memcpy(string->value, mg->min_error.value, mg->min_error.length);
+ return GSS_S_COMPLETE;
+}
+
+void
+_gss_mg_error(struct gssapi_mech_interface_desc *m, OM_uint32 min)
+{
+ OM_uint32 major_status, minor_status;
+ OM_uint32 message_content = 0;
+ struct mg_thread_ctx *mg;
+
+ /*
+ * Mechs without gss_display_status() does
+ * gss_mg_collect_error() by themself.
+ */
+ if (m->gm_display_status == NULL)
+ return ;
+
+ mg = _gss_mechglue_thread();
+ if (mg == NULL)
+ return;
+
+ gss_release_buffer(&minor_status, &mg->min_error);
+
+ mg->mech = &m->gm_mech_oid;
+ mg->min_stat = min;
+
+ major_status = m->gm_display_status(&minor_status,
+ min,
+ GSS_C_MECH_CODE,
+ &m->gm_mech_oid,
+ &message_content,
+ &mg->min_error);
+ if (major_status != GSS_S_COMPLETE) {
+ _mg_buffer_zero(&mg->min_error);
+ } else {
+ _gss_mg_log(5, "_gss_mg_error: captured %.*s (%d) from underlying mech %s",
+ (int)mg->min_error.length, (const char *)mg->min_error.value,
+ (int)min, m->gm_name);
+ }
+}
+
+void
+gss_mg_collect_error(gss_OID mech, OM_uint32 maj, OM_uint32 min)
+{
+ gssapi_mech_interface m = __gss_get_mechanism(mech);
+ if (m == NULL)
+ return;
+ _gss_mg_error(m, min);
+}
+
+OM_uint32
+gss_mg_set_error_string(gss_OID mech,
+ OM_uint32 maj, OM_uint32 min,
+ const char *fmt, ...)
+{
+ struct mg_thread_ctx *mg;
+ char *str = NULL;
+ OM_uint32 junk;
+ va_list ap;
+ int vasprintf_ret;
+
+ mg = _gss_mechglue_thread();
+ if (mg == NULL)
+ return maj;
+
+ va_start(ap, fmt);
+ vasprintf_ret = vasprintf(&str, fmt, ap);
+ va_end(ap);
+
+ if (vasprintf_ret >= 0 && str) {
+ gss_release_buffer(&junk, &mg->min_error);
+
+ mg->mech = mech;
+ mg->min_stat = min;
+
+ mg->min_error.value = str;
+ mg->min_error.length = strlen(str);
+
+ _gss_mg_log(5, "gss_mg_set_error_string: %.*s (%d/%d)",
+ (int)mg->min_error.length, (const char *)mg->min_error.value,
+ (int)maj, (int)min);
+ }
+ return maj;
+}
+
+static void *log_ctx = NULL;
+static void (*log_func)(void *ctx, int level, const char *fmt, va_list) = NULL;
+
+void GSSAPI_LIB_CALL
+gss_set_log_function(void *ctx, void (*func)(void * ctx, int level, const char *fmt, va_list))
+{
+ if (log_func == NULL) {
+ log_func = func;
+ log_ctx = ctx;
+ }
+}
+
+int
+_gss_mg_log_level(int level)
+{
+ struct mg_thread_ctx *mg;
+
+ mg = _gss_mechglue_thread();
+ if (mg == NULL)
+ return 0;
+
+ return _krb5_have_debug(mg->context, level);
+}
+
+/*
+ * TODO: refactor logging so that it no longer depends on libkrb5
+ * and can be configured independently.
+ */
+void
+_gss_mg_log(int level, const char *fmt, ...)
+{
+ struct mg_thread_ctx *mg;
+ va_list ap;
+
+ if (!_gss_mg_log_level(level))
+ return;
+
+ mg = _gss_mechglue_thread();
+ if (mg == NULL)
+ return;
+
+ if (mg->context && _krb5_have_debug(mg->context, level)) {
+ va_start(ap, fmt);
+ krb5_vlog(mg->context, heim_get_debug_dest(mg->context->hcontext),
+ level, fmt, ap);
+ va_end(ap);
+ }
+
+ if (log_func) {
+ va_start(ap, fmt);
+ log_func(log_ctx, level, fmt, ap);
+ va_end(ap);
+ }
+}
+
+void
+_gss_mg_log_name(int level,
+ struct _gss_name *name,
+ gss_OID mech_type,
+ const char *fmt, ...)
+{
+ struct _gss_mechanism_name *mn = NULL;
+ gssapi_mech_interface m;
+ OM_uint32 junk;
+
+ if (!_gss_mg_log_level(level))
+ return;
+
+ m = __gss_get_mechanism(mech_type);
+ if (m == NULL)
+ return;
+
+ if (_gss_find_mn(&junk, name, mech_type, &mn) == GSS_S_COMPLETE) {
+ OM_uint32 maj_stat = GSS_S_COMPLETE;
+ gss_buffer_desc namebuf;
+ int ret;
+
+ if (mn == NULL) {
+ namebuf.value = "no name";
+ namebuf.length = strlen((char *)namebuf.value);
+ } else {
+ maj_stat = m->gm_display_name(&junk, mn->gmn_name,
+ &namebuf, NULL);
+ }
+ if (maj_stat == GSS_S_COMPLETE) {
+ char *str = NULL;
+ va_list ap;
+
+ va_start(ap, fmt);
+ ret = vasprintf(&str, fmt, ap);
+ va_end(ap);
+
+ if (ret >= 0 && str)
+ _gss_mg_log(level, "%s %.*s", str,
+ (int)namebuf.length, (char *)namebuf.value);
+ free(str);
+ if (mn != NULL)
+ gss_release_buffer(&junk, &namebuf);
+ }
+ }
+
+}
+
+void
+_gss_mg_log_cred(int level,
+ struct _gss_cred *cred,
+ const char *fmt, ...)
+{
+ struct _gss_mechanism_cred *mc;
+ char *str;
+ va_list ap;
+ int ret;
+
+ if (!_gss_mg_log_level(level))
+ return;
+
+ va_start(ap, fmt);
+ ret = vasprintf(&str, fmt, ap);
+ va_end(ap);
+
+ if (ret >=0 && cred) {
+ HEIM_TAILQ_FOREACH(mc, &cred->gc_mc, gmc_link) {
+ _gss_mg_log(1, "%s: %s", str, mc->gmc_mech->gm_name);
+ }
+ } else {
+ _gss_mg_log(1, "%s: GSS_C_NO_CREDENTIAL", str);
+ }
+ free(str);
+}
+
diff --git a/third_party/heimdal/lib/gssapi/mech/context.h b/third_party/heimdal/lib/gssapi/mech/context.h
new file mode 100644
index 0000000..5029171
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/context.h
@@ -0,0 +1,51 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/context.h,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ * $Id$
+ */
+
+#include <gssapi_mech.h>
+
+struct _gss_context {
+ gss_buffer_desc gc_input;
+ char *gc_free_this;
+ size_t gc_target_len;
+ size_t gc_oid_offset;
+ gssapi_mech_interface gc_mech;
+ gss_ctx_id_t gc_ctx;
+ uint8_t gc_initial;
+};
+
+#define EXPORT_CONTEXT_VERSION_MASK 0x03
+#define EXPORT_CONTEXT_FLAGS_MASK 0xfc
+#define EXPORT_CONTEXT_FLAG_ACCUMULATING 0x04
+#define EXPORT_CONTEXT_FLAG_MECH_CTX 0x08
+
+void
+_gss_mg_error(gssapi_mech_interface, OM_uint32);
+
+OM_uint32
+_gss_mg_get_error(const gss_OID, OM_uint32, gss_buffer_t);
diff --git a/third_party/heimdal/lib/gssapi/mech/cred.c b/third_party/heimdal/lib/gssapi/mech/cred.c
new file mode 100644
index 0000000..92cc61a
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/cred.c
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2011 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2011 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+#include "heim_threads.h"
+#include "heimbase.h"
+
+static OM_uint32
+release_mech_cred(OM_uint32 *minor, struct _gss_mechanism_cred *mc)
+{
+ OM_uint32 major;
+
+ if (mc->gmc_mech->gm_release_cred != NULL)
+ major = mc->gmc_mech->gm_release_cred(minor, &mc->gmc_cred);
+ else
+ major = GSS_S_COMPLETE;
+
+ free(mc);
+
+ return major;
+}
+
+
+void
+_gss_mg_release_cred(struct _gss_cred *cred)
+{
+ struct _gss_mechanism_cred *mc, *next;
+ OM_uint32 junk;
+
+ HEIM_TAILQ_FOREACH_SAFE(mc, &cred->gc_mc, gmc_link, next) {
+ HEIM_TAILQ_REMOVE(&cred->gc_mc, mc, gmc_link);
+ release_mech_cred(&junk, mc);
+ }
+ gss_release_oid_set(&junk, &cred->gc_neg_mechs);
+ free(cred);
+}
+
+struct _gss_cred *
+_gss_mg_alloc_cred(void)
+{
+ struct _gss_cred *cred;
+ cred = calloc(1, sizeof(struct _gss_cred));
+ if (cred == NULL)
+ return NULL;
+ HEIM_TAILQ_INIT(&cred->gc_mc);
+
+ return cred;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/mech/cred.h b/third_party/heimdal/lib/gssapi/mech/cred.h
new file mode 100644
index 0000000..eed4a82
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/cred.h
@@ -0,0 +1,65 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/cred.h,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ * $Id$
+ */
+
+struct _gss_mechanism_cred {
+ HEIM_TAILQ_ENTRY(_gss_mechanism_cred) gmc_link;
+ gssapi_mech_interface gmc_mech; /* mechanism ops for MC */
+ gss_OID gmc_mech_oid; /* mechanism oid for MC */
+ gss_cred_id_t gmc_cred; /* underlying MC */
+};
+HEIM_TAILQ_HEAD(_gss_mechanism_cred_list, _gss_mechanism_cred);
+
+struct _gss_cred {
+ struct _gss_mechanism_cred_list gc_mc;
+ gss_OID_set gc_neg_mechs;
+};
+
+struct _gss_cred *
+_gss_mg_alloc_cred(void);
+
+void
+_gss_mg_release_cred(struct _gss_cred *cred);
+
+struct _gss_mechanism_cred *
+_gss_copy_cred(struct _gss_mechanism_cred *mc);
+
+struct _gss_mechanism_name;
+
+OM_uint32
+_gss_mg_add_mech_cred(OM_uint32 *minor_status,
+ gssapi_mech_interface m,
+ const struct _gss_mechanism_cred *mc,
+ const struct _gss_mechanism_name *mn,
+ gss_cred_usage_t cred_usage,
+ OM_uint32 initiator_time_req,
+ OM_uint32 acceptor_time_req,
+ gss_const_key_value_set_t cred_store,
+ struct _gss_mechanism_cred **output_cred_handle,
+ OM_uint32 *initiator_time_rec,
+ OM_uint32 *acceptor_time_rec);
diff --git a/third_party/heimdal/lib/gssapi/mech/doxygen.c b/third_party/heimdal/lib/gssapi/mech/doxygen.c
new file mode 100644
index 0000000..4ead9f1
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/doxygen.c
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*! @mainpage Heimdal GSS-API Library
+ *
+ * Heimdal implements the following mechanisms:
+ *
+ * - Kerberos 5
+ * - SPNEGO
+ * - NTLM
+ *
+ * @sa
+ *
+ * - @ref gssapi_services_intro
+ * - @ref gssapi_mechs
+ * - @ref gssapi_api_INvsMN
+ * - The project web page: http://www.h5l.org/
+ */
+
+/**
+ * @page gssapi_services_intro Introduction to GSS-API services
+ * @section gssapi_services GSS-API services
+ *
+ * @subsection gssapi_services_context Context creation
+ *
+ * - delegation
+ * - mutual authentication
+ * - anonymous
+ * - use per message before context creation has completed
+ *
+ * return status:
+ * - support conf
+ * - support int
+ *
+ * @subsection gssapi_context_flags Context creation flags
+ *
+ * - GSS_C_DELEG_FLAG
+ * - GSS_C_MUTUAL_FLAG
+ * - GSS_C_REPLAY_FLAG
+ * - GSS_C_SEQUENCE_FLAG
+ * - GSS_C_CONF_FLAG
+ * - GSS_C_INTEG_FLAG
+ * - GSS_C_ANON_FLAG
+ * - GSS_C_PROT_READY_FLAG
+ * - GSS_C_TRANS_FLAG
+ * - GSS_C_DCE_STYLE
+ * - GSS_C_IDENTIFY_FLAG
+ * - GSS_C_EXTENDED_ERROR_FLAG
+ * - GSS_C_DELEG_POLICY_FLAG
+ *
+ *
+ * @subsection gssapi_services_permessage Per-message services
+ *
+ * - conf
+ * - int
+ * - message integrity
+ * - replay detection
+ * - out of sequence
+ *
+ */
+
+/**
+ * @page gssapi_mechs_intro GSS-API mechanisms
+ * @section gssapi_mechs GSS-API mechanisms
+ *
+ * - Kerberos 5 - GSS_KRB5_MECHANISM
+ * - SPNEGO - GSS_SPNEGO_MECHANISM
+ * - NTLM - GSS_NTLM_MECHANISM
+
+ */
+
+
+/**
+ * @page internalVSmechname Internal names and mechanism names
+ * @section gssapi_api_INvsMN Name forms
+ *
+ * There are two name representations in GSS-API: Internal form and
+ * Contiguous string ("flat") form. Functions gss_export_name() and
+ * gss_import_name() can be used to convert between the two forms.
+ *
+ * - The contiguous string form is described by an oid specificing the
+ * type and an octet string. A special form of the contiguous
+ * string form is the exported name object. The exported name
+ * defined for each mechanism, is something that can be stored and
+ * compared later. The exported name is what should be used for
+ * ACLs comparisons.
+ *
+ * - The Internal form is opaque to the application programmer and
+ * is implementation-dependent.
+ *
+ * - There is also a special form of the Internal Name (IN), and that is
+ * the Mechanism Name (MN). In the mechanism name all the generic
+ * information is stripped of and only contain the information for
+ * one mechanism. In GSS-API some function return MN and some
+ * require MN as input. Each of these function is marked up as such.
+ *
+ * @FIXME Describe relationship between import_name, canonicalize_name,
+ * export_name and friends. Also, update for RFC2743 language
+ * ("contiguous" and "flat" are gone, leaving just "exported name
+ * token", "internal", and "MN").
+ */
+
+/** @defgroup gssapi Heimdal GSS-API functions */
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_accept_sec_context.c b/third_party/heimdal/lib/gssapi/mech/gss_accept_sec_context.c
new file mode 100644
index 0000000..1cb0b36
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_accept_sec_context.c
@@ -0,0 +1,519 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_accept_sec_context.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+/*
+ * accumulate_token() tries to assemble a complete GSS token which may
+ * be fed to it in pieces. Microsoft does this when tokens are too large
+ * in CIFS, e.g. It may occur in other places as well. It is specified in:
+ *
+ * [MS-SPNG]: Simple and Protected GSS-API Negotiation
+ * Mechanism (SPNEGO) Extension
+ *
+ * https://winprotocoldoc.blob.core.windows.net/
+ * productionwindowsarchives/MS-SPNG/%5bMS-SPNG%5d.pdf
+ *
+ * Sections 3.1.5.4 to 3.1.5.9.
+ *
+ * We only accumulate if we see the appropriate application tag in the
+ * first byte of 0x60 because in the absence of this, we cannot interpret
+ * the following bytes as a DER length.
+ *
+ * We only allocate an accumulating buffer if we detect that the token
+ * is split between multiple packets as this is the uncommon case and
+ * we want to optimise for the common case. If we aren't accumulating,
+ * we simply return success.
+ *
+ * Our return value is GSS_S_CONTINUE_NEEDED if we need more input.
+ * We return GSS_S_COMPLETE if we are either finished accumulating or
+ * if we decide that we do not understand this token. We only return
+ * an error if we think that we should understand the token and still
+ * fail to understand it.
+ */
+
+static OM_uint32
+accumulate_token(struct _gss_context *ctx, gss_buffer_t input_token)
+{
+ unsigned char *p = input_token->value;
+ size_t len = input_token->length;
+ gss_buffer_t gci;
+ size_t l;
+
+ /*
+ * Token must start with [APPLICATION 0] SEQUENCE.
+ * But if it doesn't assume it is DCE-STYLE Kerberos!
+ */
+ if (!ctx->gc_target_len) {
+ free(ctx->gc_free_this);
+ ctx->gc_free_this = NULL;
+ _mg_buffer_zero(&ctx->gc_input);
+
+ /*
+ * Let's prepare gc_input for the case where
+ * we aren't accumulating.
+ */
+
+ ctx->gc_input.length = len;
+ ctx->gc_input.value = p;
+
+ if (len == 0)
+ return GSS_S_COMPLETE;
+
+ /* Not our DER w/ a length */
+ if (*p != 0x60)
+ return GSS_S_COMPLETE;
+
+ if (der_get_length(p+1, len-1, &ctx->gc_target_len, &l) != 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ _gss_mg_log(10, "gss-asc: DER length: %zu",
+ ctx->gc_target_len);
+
+ ctx->gc_oid_offset = l + 1;
+ ctx->gc_target_len += ctx->gc_oid_offset;
+
+ _gss_mg_log(10, "gss-asc: total length: %zu",
+ ctx->gc_target_len);
+
+ if (ctx->gc_target_len == ASN1_INDEFINITE ||
+ ctx->gc_target_len < len)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ /* We've got it all, short-circuit the accumulating */
+ if (ctx->gc_target_len == len)
+ goto done;
+
+ _gss_mg_log(10, "gss-asc: accumulating partial token");
+
+ ctx->gc_input.length = 0;
+ ctx->gc_input.value = calloc(ctx->gc_target_len, 1);
+ if (!ctx->gc_input.value)
+ return GSS_S_FAILURE;
+ ctx->gc_free_this = ctx->gc_input.value;
+ }
+
+ if (len == 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ gci = &ctx->gc_input;
+
+ if (ctx->gc_target_len > gci->length) {
+ if (gci->length + len > ctx->gc_target_len) {
+ _gss_mg_log(10, "gss-asc: accumulation exceeded "
+ "target length: bailing");
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+ memcpy((char *)gci->value + gci->length, p, len);
+ gci->length += len;
+ }
+
+ if (gci->length != ctx->gc_target_len) {
+ _gss_mg_log(10, "gss-asc: collected %zu/%zu bytes",
+ gci->length, ctx->gc_target_len);
+ return GSS_S_CONTINUE_NEEDED;
+ }
+
+done:
+ _gss_mg_log(10, "gss-asc: received complete %zu byte token",
+ ctx->gc_target_len);
+ ctx->gc_target_len = 0;
+
+ return GSS_S_COMPLETE;
+}
+
+static void
+log_oid(const char *str, gss_OID mech)
+{
+ OM_uint32 maj, min;
+ gss_buffer_desc buf;
+
+ maj = gss_oid_to_str(&min, mech, &buf);
+ if (maj == GSS_S_COMPLETE) {
+ _gss_mg_log(10, "%s: %.*s", str, (int)buf.length,
+ (char *)buf.value);
+ gss_release_buffer(&min, &buf);
+ }
+}
+
+static OM_uint32
+choose_mech(struct _gss_context *ctx)
+{
+ gss_OID_desc mech;
+ gss_OID mech_oid;
+ unsigned char *p = ctx->gc_input.value;
+ size_t len = ctx->gc_input.length;
+
+ if (len == 0) {
+ /*
+ * There is the a wierd mode of SPNEGO (in CIFS and
+ * SASL GSS-SPENGO where the first token is zero
+ * length and the acceptor returns a mech_list, lets
+ * hope that is what is happening now.
+ *
+ * http://msdn.microsoft.com/en-us/library/cc213114.aspx
+ * "NegTokenInit2 Variation for Server-Initiation"
+ */
+ mech_oid = &__gss_spnego_mechanism_oid_desc;
+ goto gss_get_mechanism;
+ }
+
+ p += ctx->gc_oid_offset;
+ len -= ctx->gc_oid_offset;
+
+ /*
+ * Decode the OID for the mechanism. Simplify life by
+ * assuming that the OID length is less than 128 bytes.
+ */
+ if (len < 2 || *p != 0x06)
+ goto bail;
+ if ((p[1] & 0x80) || p[1] > (len - 2))
+ goto bail;
+ mech.length = p[1];
+ p += 2;
+ len -= 2;
+ mech.elements = p;
+
+ mech_oid = _gss_mg_support_mechanism(&mech);
+ if (mech_oid == GSS_C_NO_OID)
+ return GSS_S_COMPLETE;
+
+gss_get_mechanism:
+ /*
+ * If mech_oid == GSS_C_NO_OID then the mech is non-standard
+ * and we have to try all mechs (that we have a cred element
+ * for, if we have a cred).
+ */
+ if (mech_oid != GSS_C_NO_OID) {
+ log_oid("mech oid", mech_oid);
+ ctx->gc_mech = __gss_get_mechanism(mech_oid);
+ if (!ctx->gc_mech) {
+ _gss_mg_log(10, "mechanism client used is unknown");
+ return (GSS_S_BAD_MECH);
+ }
+ _gss_mg_log(10, "using mech \"%s\"", ctx->gc_mech->gm_name);
+ return GSS_S_COMPLETE;
+ }
+
+bail:
+ _gss_mg_log(10, "no mech oid found");
+ return GSS_S_COMPLETE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_accept_sec_context(OM_uint32 *minor_status,
+ gss_ctx_id_t *context_handle,
+ gss_const_cred_id_t acceptor_cred_handle,
+ const gss_buffer_t input_token,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_name_t *src_name,
+ gss_OID *mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 *ret_flags,
+ OM_uint32 *time_rec,
+ gss_cred_id_t *delegated_cred_handle)
+{
+ OM_uint32 major_status, mech_ret_flags, junk;
+ gssapi_mech_interface m = NULL;
+ struct _gss_context *ctx = (struct _gss_context *) *context_handle;
+ struct _gss_cred *cred = (struct _gss_cred *) acceptor_cred_handle;
+ struct _gss_mechanism_cred *mc;
+ gss_buffer_desc defective_token_error;
+ gss_const_cred_id_t acceptor_mc;
+ gss_cred_id_t delegated_mc = GSS_C_NO_CREDENTIAL;
+ gss_name_t src_mn = GSS_C_NO_NAME;
+ gss_OID mech_ret_type = GSS_C_NO_OID;
+ int initial;
+
+ defective_token_error.length = 0;
+ defective_token_error.value = NULL;
+
+ *minor_status = 0;
+ if (src_name)
+ *src_name = GSS_C_NO_NAME;
+ if (mech_type)
+ *mech_type = GSS_C_NO_OID;
+ if (ret_flags)
+ *ret_flags = 0;
+ if (time_rec)
+ *time_rec = 0;
+ if (delegated_cred_handle)
+ *delegated_cred_handle = GSS_C_NO_CREDENTIAL;
+ _mg_buffer_zero(output_token);
+
+ if (!*context_handle) {
+ ctx = calloc(sizeof(*ctx), 1);
+ if (!ctx) {
+ *minor_status = ENOMEM;
+ return (GSS_S_DEFECTIVE_TOKEN);
+ }
+ *context_handle = (gss_ctx_id_t)ctx;
+ ctx->gc_initial = 1;
+ }
+
+ major_status = accumulate_token(ctx, input_token);
+ if (major_status != GSS_S_COMPLETE)
+ return major_status;
+
+ /*
+ * If we get here, then we have a complete token. Please note
+ * that we may have a major_status of GSS_S_DEFECTIVE_TOKEN. This
+ *
+ */
+
+ initial = ctx->gc_initial;
+ ctx->gc_initial = 0;
+
+ if (major_status == GSS_S_COMPLETE && initial) {
+ major_status = choose_mech(ctx);
+ if (major_status != GSS_S_COMPLETE)
+ return major_status;
+ }
+ m = ctx->gc_mech;
+
+ if (initial && !m && acceptor_cred_handle == GSS_C_NO_CREDENTIAL) {
+ /*
+ * No header, not a standard mechanism. Try all the mechanisms
+ * (because default credential).
+ */
+ struct _gss_mech_switch *ms;
+
+ _gss_load_mech();
+ acceptor_mc = GSS_C_NO_CREDENTIAL;
+ HEIM_TAILQ_FOREACH(ms, &_gss_mechs, gm_link) {
+ m = &ms->gm_mech;
+ mech_ret_flags = 0;
+ major_status = m->gm_accept_sec_context(minor_status,
+ &ctx->gc_ctx,
+ acceptor_mc,
+ &ctx->gc_input,
+ input_chan_bindings,
+ &src_mn,
+ &mech_ret_type,
+ output_token,
+ &mech_ret_flags,
+ time_rec,
+ &delegated_mc);
+ if (major_status == GSS_S_DEFECTIVE_TOKEN) {
+ /*
+ * Try to retain and output one error token for
+ * GSS_S_DEFECTIVE_TOKEN. The first one.
+ */
+ if (output_token->length &&
+ defective_token_error.length == 0) {
+ defective_token_error = *output_token;
+ output_token->length = 0;
+ output_token->value = NULL;
+ }
+ gss_release_buffer(&junk, output_token);
+ continue;
+ }
+ gss_release_buffer(&junk, &defective_token_error);
+ ctx->gc_mech = m;
+ goto got_one;
+ }
+ m = NULL;
+ acceptor_mc = GSS_C_NO_CREDENTIAL;
+ } else if (initial && !m) {
+ /*
+ * No header, not a standard mechanism. Try all the mechanisms
+ * that we have a credential element for if we have a
+ * non-default credential.
+ */
+ HEIM_TAILQ_FOREACH(mc, &cred->gc_mc, gmc_link) {
+ m = mc->gmc_mech;
+ acceptor_mc = (m->gm_flags & GM_USE_MG_CRED) ?
+ acceptor_cred_handle : mc->gmc_cred;
+ mech_ret_flags = 0;
+ major_status = m->gm_accept_sec_context(minor_status,
+ &ctx->gc_ctx,
+ acceptor_mc,
+ &ctx->gc_input,
+ input_chan_bindings,
+ &src_mn,
+ &mech_ret_type,
+ output_token,
+ &mech_ret_flags,
+ time_rec,
+ &delegated_mc);
+ if (major_status == GSS_S_DEFECTIVE_TOKEN) {
+ if (output_token->length &&
+ defective_token_error.length == 0) {
+ defective_token_error = *output_token;
+ output_token->length = 0;
+ output_token->value = NULL;
+ }
+ gss_release_buffer(&junk, output_token);
+ continue;
+ }
+ gss_release_buffer(&junk, &defective_token_error);
+ ctx->gc_mech = m;
+ goto got_one;
+ }
+ m = NULL;
+ acceptor_mc = GSS_C_NO_CREDENTIAL;
+ }
+
+ if (m == NULL) {
+ gss_delete_sec_context(&junk, context_handle, NULL);
+ _gss_mg_log(10, "No mechanism accepted the non-standard initial security context token");
+ *output_token = defective_token_error;
+ return GSS_S_BAD_MECH;
+ }
+
+ if (m->gm_flags & GM_USE_MG_CRED) {
+ acceptor_mc = acceptor_cred_handle;
+ } else if (cred) {
+ HEIM_TAILQ_FOREACH(mc, &cred->gc_mc, gmc_link)
+ if (mc->gmc_mech == m)
+ break;
+ if (!mc) {
+ gss_delete_sec_context(&junk, context_handle, NULL);
+ _gss_mg_log(10, "gss-asc: client sent mech %s "
+ "but no credential was matching",
+ m->gm_name);
+ HEIM_TAILQ_FOREACH(mc, &cred->gc_mc, gmc_link)
+ _gss_mg_log(10, "gss-asc: available creds were %s", mc->gmc_mech->gm_name);
+ return (GSS_S_BAD_MECH);
+ }
+ acceptor_mc = mc->gmc_cred;
+ } else {
+ acceptor_mc = GSS_C_NO_CREDENTIAL;
+ }
+
+ mech_ret_flags = 0;
+ major_status = m->gm_accept_sec_context(minor_status,
+ &ctx->gc_ctx,
+ acceptor_mc,
+ &ctx->gc_input,
+ input_chan_bindings,
+ &src_mn,
+ &mech_ret_type,
+ output_token,
+ &mech_ret_flags,
+ time_rec,
+ &delegated_mc);
+
+got_one:
+ if (major_status != GSS_S_COMPLETE &&
+ major_status != GSS_S_CONTINUE_NEEDED)
+ {
+ _gss_mg_error(m, *minor_status);
+ gss_delete_sec_context(&junk, context_handle, NULL);
+ return (major_status);
+ }
+
+ if (mech_type)
+ *mech_type = mech_ret_type;
+
+ if (src_name && src_mn) {
+ if (ctx->gc_mech->gm_flags & GM_USE_MG_NAME) {
+ /* Negotiation mechanisms use mechglue names as names */
+ *src_name = src_mn;
+ src_mn = GSS_C_NO_NAME;
+ } else {
+ /*
+ * Make a new name and mark it as an MN.
+ *
+ * Note that _gss_create_name() consumes `src_mn' but doesn't
+ * take a pointer, so it can't set it to GSS_C_NO_NAME.
+ */
+ struct _gss_name *name = _gss_create_name(src_mn, m);
+
+ if (!name) {
+ m->gm_release_name(minor_status, &src_mn);
+ gss_delete_sec_context(&junk, context_handle, NULL);
+ return (GSS_S_FAILURE);
+ }
+ *src_name = (gss_name_t) name;
+ src_mn = GSS_C_NO_NAME;
+ }
+ } else if (src_mn) {
+ if (ctx->gc_mech->gm_flags & GM_USE_MG_NAME) {
+ _gss_mg_release_name((struct _gss_name *)src_mn);
+ src_mn = GSS_C_NO_NAME;
+ } else {
+ m->gm_release_name(minor_status, &src_mn);
+ }
+ }
+
+ if (mech_ret_flags & GSS_C_DELEG_FLAG) {
+ if (!delegated_cred_handle) {
+ if (m->gm_flags & GM_USE_MG_CRED)
+ gss_release_cred(minor_status, &delegated_mc);
+ else
+ m->gm_release_cred(minor_status, &delegated_mc);
+ mech_ret_flags &=
+ ~(GSS_C_DELEG_FLAG|GSS_C_DELEG_POLICY_FLAG);
+ } else if ((m->gm_flags & GM_USE_MG_CRED) != 0) {
+ /*
+ * If credential is uses mechglue cred, assume it
+ * returns one too.
+ */
+ *delegated_cred_handle = delegated_mc;
+ } else if (gss_oid_equal(mech_ret_type, &m->gm_mech_oid) == 0) {
+ /*
+ * If the returned mech_type is not the same
+ * as the mech, assume its pseudo mech type
+ * and the returned type is already a
+ * mech-glue object
+ */
+ *delegated_cred_handle = delegated_mc;
+
+ } else if (delegated_mc) {
+ struct _gss_cred *dcred;
+ struct _gss_mechanism_cred *dmc;
+
+ dcred = _gss_mg_alloc_cred();
+ if (!dcred) {
+ *minor_status = ENOMEM;
+ gss_delete_sec_context(&junk, context_handle, NULL);
+ return (GSS_S_FAILURE);
+ }
+ dmc = malloc(sizeof(struct _gss_mechanism_cred));
+ if (!dmc) {
+ free(dcred);
+ *minor_status = ENOMEM;
+ gss_delete_sec_context(&junk, context_handle, NULL);
+ return (GSS_S_FAILURE);
+ }
+ dmc->gmc_mech = m;
+ dmc->gmc_mech_oid = &m->gm_mech_oid;
+ dmc->gmc_cred = delegated_mc;
+ HEIM_TAILQ_INSERT_TAIL(&dcred->gc_mc, dmc, gmc_link);
+
+ *delegated_cred_handle = (gss_cred_id_t) dcred;
+ }
+ }
+
+ _gss_mg_log(10, "gss-asc: return %d/%d", (int)major_status, (int)*minor_status);
+
+ if (ret_flags)
+ *ret_flags = mech_ret_flags;
+ return (major_status);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_acquire_cred.c b/third_party/heimdal/lib/gssapi/mech/gss_acquire_cred.c
new file mode 100644
index 0000000..fd92a25
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_acquire_cred.c
@@ -0,0 +1,50 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_acquire_cred.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_acquire_cred(OM_uint32 *minor_status,
+ gss_const_name_t desired_name,
+ OM_uint32 time_req,
+ const gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *time_rec)
+{
+ return gss_acquire_cred_from(minor_status,
+ desired_name,
+ time_req,
+ desired_mechs,
+ cred_usage,
+ GSS_C_NO_CRED_STORE,
+ output_cred_handle,
+ actual_mechs,
+ time_rec);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_acquire_cred_from.c b/third_party/heimdal/lib/gssapi/mech/gss_acquire_cred_from.c
new file mode 100644
index 0000000..5bb956c
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_acquire_cred_from.c
@@ -0,0 +1,302 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ * Portions Copyright (c) 2011, 2018 PADL Software Pty Ltd.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_acquire_cred.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+/*
+ * Shim for gss_acquire_cred_with_password()
+ */
+static const char *
+find_password_in_cred_store(gss_const_key_value_set_t cred_store)
+{
+ size_t i;
+
+ if (cred_store == GSS_C_NO_CRED_STORE)
+ return NULL;
+
+ for (i = 0; i < cred_store->count; i++) {
+ if (strcmp(cred_store->elements[i].key, "password") == 0)
+ return cred_store->elements[i].value;
+ }
+
+ return NULL;
+}
+
+static OM_uint32
+acquire_mech_cred(OM_uint32 *minor_status,
+ gssapi_mech_interface m,
+ const struct _gss_mechanism_name *mn,
+ OM_uint32 time_req,
+ gss_cred_usage_t cred_usage,
+ gss_const_key_value_set_t cred_store,
+ struct _gss_mechanism_cred **out,
+ OM_uint32 *time_rec)
+{
+ OM_uint32 major_status;
+ struct _gss_mechanism_cred *mc;
+ gss_OID_set_desc mech;
+ const char *spassword;
+
+ *out = NULL;
+ if (time_rec)
+ *time_rec = 0;
+
+ mc = calloc(1, sizeof(struct _gss_mechanism_cred));
+ if (mc == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ mc->gmc_mech = m;
+ mc->gmc_mech_oid = &m->gm_mech_oid;
+
+ mech.count = 1;
+ mech.elements = mc->gmc_mech_oid;
+
+ if (m->gm_acquire_cred_from) {
+ major_status = m->gm_acquire_cred_from(minor_status,
+ mn ? mn->gmn_name : GSS_C_NO_NAME,
+ time_req,
+ &mech,
+ cred_usage,
+ cred_store,
+ &mc->gmc_cred,
+ NULL,
+ time_rec);
+ } else if ((cred_store == GSS_C_NO_CRED_STORE || cred_store->count == 0) &&
+ m->gm_acquire_cred) {
+ major_status = m->gm_acquire_cred(minor_status,
+ mn ? mn->gmn_name : GSS_C_NO_NAME,
+ time_req,
+ &mech,
+ cred_usage,
+ &mc->gmc_cred,
+ NULL,
+ time_rec);
+ } else if (m->gm_compat &&
+ m->gm_compat->gmc_acquire_cred_with_password &&
+ (spassword = find_password_in_cred_store(cred_store)) != NULL) {
+ gss_buffer_desc password;
+
+ password.length = strlen(spassword);
+ password.value = rk_UNCONST(spassword);
+
+ /* compat glue for loadable mechanisms that implement API-as-SPI */
+ major_status = m->gm_compat->gmc_acquire_cred_with_password(minor_status,
+ mn ? mn->gmn_name : GSS_C_NO_NAME,
+ &password,
+ time_req,
+ &mech,
+ cred_usage,
+ &mc->gmc_cred,
+ NULL,
+ time_rec);
+ } else
+ major_status = GSS_S_UNAVAILABLE;
+
+ heim_assert(major_status == GSS_S_COMPLETE || mc->gmc_cred == NULL,
+ "gss_acquire_cred_from: mech succeeded but did not return a credential");
+
+ if (major_status == GSS_S_COMPLETE)
+ *out = mc;
+ else
+ free(mc);
+
+ return major_status;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_acquire_cred_from(OM_uint32 *minor_status,
+ gss_const_name_t desired_name,
+ OM_uint32 time_req,
+ const gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_const_key_value_set_t cred_store,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *time_rec)
+{
+ OM_uint32 major_status, minor;
+ struct _gss_name *name = (struct _gss_name *)desired_name;
+ gssapi_mech_interface m;
+ struct _gss_cred *cred = NULL;
+ size_t i;
+ OM_uint32 min_time = GSS_C_INDEFINITE;
+ gss_OID_set mechs = GSS_C_NO_OID_SET;
+
+ *minor_status = 0;
+ if (output_cred_handle == NULL)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+ *output_cred_handle = GSS_C_NO_CREDENTIAL;
+ if (actual_mechs)
+ *actual_mechs = GSS_C_NO_OID_SET;
+ if (time_rec)
+ *time_rec = 0;
+
+ _gss_load_mech();
+
+ if (desired_mechs != GSS_C_NO_OID_SET) {
+ int only_mg_cred_mechs = -1;
+
+ for (i = 0; i < desired_mechs->count; i++) {
+ m = __gss_get_mechanism(&desired_mechs->elements[i]);
+ if (m != NULL) {
+ if ((m->gm_flags & GM_USE_MG_CRED) == 0)
+ only_mg_cred_mechs = 0;
+ else if (only_mg_cred_mechs == -1)
+ only_mg_cred_mechs = 1;
+ }
+ }
+ /*
+ * Now SPNEGO supports GM_USE_MG_CRED it's no longer necessary
+ * to specifically acquire SPNEGO credentials. If the caller
+ * did not specify any concrete mechanisms then we will acquire
+ * credentials for all of them.
+ */
+ if (only_mg_cred_mechs == -1) {
+ *minor_status = 0;
+ major_status = GSS_S_BAD_MECH;
+ goto cleanup;
+ } else if (only_mg_cred_mechs == 0)
+ mechs = desired_mechs;
+ else
+ mechs = _gss_mech_oids;
+ } else
+ mechs = _gss_mech_oids;
+
+ cred = _gss_mg_alloc_cred();
+ if (cred == NULL) {
+ *minor_status = ENOMEM;
+ major_status = GSS_S_FAILURE;
+ goto cleanup;
+ }
+
+ if (actual_mechs) {
+ major_status = gss_create_empty_oid_set(minor_status, actual_mechs);
+ if (GSS_ERROR(major_status))
+ goto cleanup;
+ }
+
+ major_status = GSS_S_UNAVAILABLE; /* in case of no mechs */
+
+ for (i = 0; i < mechs->count; i++) {
+ struct _gss_mechanism_name *mn = NULL;
+ struct _gss_mechanism_cred *mc = NULL;
+ OM_uint32 cred_time;
+
+ m = __gss_get_mechanism(&mechs->elements[i]);
+ if (m == NULL || (m->gm_flags & GM_USE_MG_CRED) != 0)
+ continue;
+
+ if (desired_name != GSS_C_NO_NAME) {
+ major_status = _gss_find_mn(minor_status, name,
+ &mechs->elements[i], &mn);
+ if (major_status != GSS_S_COMPLETE)
+ continue;
+ }
+
+ major_status = acquire_mech_cred(minor_status, m, mn,
+ time_req, cred_usage,
+ cred_store, &mc, &cred_time);
+ if (major_status != GSS_S_COMPLETE) {
+ if (mechs->count == 1)
+ _gss_mg_error(m, *minor_status);
+ continue;
+ }
+
+ _gss_mg_log_name(10, name, &mechs->elements[i],
+ "gss_acquire_cred %s name: %ld/%ld",
+ m->gm_name,
+ (long)major_status, (long)*minor_status);
+
+ HEIM_TAILQ_INSERT_TAIL(&cred->gc_mc, mc, gmc_link);
+
+ if (cred_time < min_time)
+ min_time = cred_time;
+ if (actual_mechs != NULL) {
+ major_status = gss_add_oid_set_member(minor_status,
+ mc->gmc_mech_oid,
+ actual_mechs);
+ if (GSS_ERROR(major_status))
+ goto cleanup;
+ }
+ }
+
+ /*
+ * If we didn't manage to create a single credential, return
+ * an error.
+ */
+ if (!HEIM_TAILQ_FIRST(&cred->gc_mc)) {
+ if (mechs->count > 1) {
+ *minor_status = 0;
+ major_status = GSS_S_NO_CRED;
+ }
+ heim_assert(major_status != GSS_S_COMPLETE,
+ "lack of credentials must result in an error");
+ goto cleanup;
+ }
+
+ /* add all GM_USE_MG_CRED mechs such as SPNEGO */
+ if (actual_mechs != NULL) {
+ struct _gss_mech_switch *ms;
+
+ HEIM_TAILQ_FOREACH(ms, &_gss_mechs, gm_link) {
+ m = &ms->gm_mech;
+
+ if ((m->gm_flags & GM_USE_MG_CRED) == 0)
+ continue;
+
+ major_status = gss_add_oid_set_member(minor_status,
+ &m->gm_mech_oid,
+ actual_mechs);
+ if (GSS_ERROR(major_status))
+ goto cleanup;
+ }
+ }
+
+ *minor_status = 0;
+ major_status = GSS_S_COMPLETE;
+
+ *output_cred_handle = (gss_cred_id_t)cred;
+ if (time_rec)
+ *time_rec = min_time;
+
+ _gss_mg_log_cred(10, cred, "gss_acquire_cred_from");
+
+cleanup:
+ if (major_status != GSS_S_COMPLETE) {
+ gss_release_cred(&minor, (gss_cred_id_t *)&cred);
+ if (actual_mechs)
+ gss_release_oid_set(&minor, actual_mechs);
+ }
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_acquire_cred_impersonate_name.c b/third_party/heimdal/lib/gssapi/mech/gss_acquire_cred_impersonate_name.c
new file mode 100644
index 0000000..ec027ed
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_acquire_cred_impersonate_name.c
@@ -0,0 +1,51 @@
+/*-
+ * Copyright 2021, Dr Robert Harvey Crowston. <crowston@protonmail.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_acquire_cred_impersonate_name(
+ OM_uint32 *minor_status,
+ gss_const_cred_id_t icred_handle,
+ gss_const_name_t desired_name,
+ OM_uint32 time_req,
+ gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_cred_id_t *ocred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *time_rec)
+{
+ *minor_status = 0;
+
+ if (ocred_handle == NULL)
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+
+ *ocred_handle = GSS_C_NO_CREDENTIAL;
+
+ /* Not implemented. */
+ return GSS_S_UNAVAILABLE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_acquire_cred_with_password.c b/third_party/heimdal/lib/gssapi/mech/gss_acquire_cred_with_password.c
new file mode 100644
index 0000000..4e6138b
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_acquire_cred_with_password.c
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2011, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_acquire_cred_with_password(OM_uint32 *minor_status,
+ gss_const_name_t desired_name,
+ const gss_buffer_t password,
+ OM_uint32 time_req,
+ const gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *time_rec)
+{
+ OM_uint32 major_status;
+ gss_key_value_element_desc kv;
+ gss_key_value_set_desc store;
+ char *spassword = NULL;
+
+ *output_cred_handle = GSS_C_NO_CREDENTIAL;
+
+ if (password == GSS_C_NO_BUFFER || password->value == NULL)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+
+ spassword = malloc(password->length + 1);
+ if (spassword == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ memcpy(spassword, password->value, password->length);
+ spassword[password->length] = '\0';
+
+ kv.key = "password";
+ kv.value = spassword;
+
+ store.count = 1;
+ store.elements = &kv;
+
+ major_status = gss_acquire_cred_from(minor_status,
+ desired_name,
+ time_req,
+ desired_mechs,
+ cred_usage,
+ &store,
+ output_cred_handle,
+ actual_mechs,
+ time_rec);
+ if (spassword) {
+ memset_s(spassword, password->length, 0, password->length);
+ free(spassword);
+ }
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_add_cred.c b/third_party/heimdal/lib/gssapi/mech/gss_add_cred.c
new file mode 100644
index 0000000..6d44f5c
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_add_cred.c
@@ -0,0 +1,58 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * Copyright (c) 2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_add_cred.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_add_cred(OM_uint32 *minor_status,
+ gss_const_cred_id_t input_cred_handle,
+ gss_const_name_t desired_name,
+ const gss_OID desired_mech,
+ gss_cred_usage_t cred_usage,
+ OM_uint32 initiator_time_req,
+ OM_uint32 acceptor_time_req,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *initiator_time_rec,
+ OM_uint32 *acceptor_time_rec)
+{
+ return gss_add_cred_from(minor_status,
+ rk_UNCONST(input_cred_handle),
+ desired_name,
+ desired_mech,
+ cred_usage,
+ initiator_time_req,
+ acceptor_time_req,
+ GSS_C_NO_CRED_STORE,
+ output_cred_handle,
+ actual_mechs,
+ initiator_time_rec,
+ acceptor_time_rec);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_add_cred_from.c b/third_party/heimdal/lib/gssapi/mech/gss_add_cred_from.c
new file mode 100644
index 0000000..9f761e8
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_add_cred_from.c
@@ -0,0 +1,292 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * Copyright (c) 2018 Kungliga Tekniska Högskolan
+ * Copyright (c) 2018 AuriStor, Inc.
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_add_cred.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+OM_uint32
+_gss_mg_add_mech_cred(OM_uint32 *minor_status,
+ gssapi_mech_interface m,
+ const struct _gss_mechanism_cred *mc,
+ const struct _gss_mechanism_name *mn,
+ gss_cred_usage_t cred_usage,
+ OM_uint32 initiator_time_req,
+ OM_uint32 acceptor_time_req,
+ gss_const_key_value_set_t cred_store,
+ struct _gss_mechanism_cred **out,
+ OM_uint32 *initiator_time_rec,
+ OM_uint32 *acceptor_time_rec)
+{
+ OM_uint32 major_status;
+ struct _gss_mechanism_cred *new_mc = NULL;
+
+ if (out) {
+ *out = NULL;
+
+ new_mc = calloc(1, sizeof(struct _gss_mechanism_cred));
+ if (new_mc == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ new_mc->gmc_mech = m;
+ new_mc->gmc_mech_oid = &m->gm_mech_oid;
+ }
+
+ if (m->gm_add_cred_from) {
+ major_status = m->gm_add_cred_from(minor_status,
+ mc ? mc->gmc_cred : GSS_C_NO_CREDENTIAL,
+ mn ? mn->gmn_name : GSS_C_NO_NAME,
+ &m->gm_mech_oid,
+ cred_usage,
+ initiator_time_req,
+ acceptor_time_req,
+ cred_store,
+ new_mc ? &new_mc->gmc_cred : NULL,
+ NULL,
+ initiator_time_rec,
+ acceptor_time_rec);
+ } else if (cred_store == GSS_C_NO_CRED_STORE && m->gm_add_cred) {
+ major_status = m->gm_add_cred(minor_status,
+ mc ? mc->gmc_cred : GSS_C_NO_CREDENTIAL,
+ mn ? mn->gmn_name : GSS_C_NO_NAME,
+ &m->gm_mech_oid,
+ cred_usage,
+ initiator_time_req,
+ acceptor_time_req,
+ new_mc ? &new_mc->gmc_cred : NULL,
+ NULL,
+ initiator_time_rec,
+ acceptor_time_rec);
+ } else
+ major_status = GSS_S_UNAVAILABLE;
+
+ if (major_status == GSS_S_COMPLETE && out) {
+ heim_assert(new_mc->gmc_cred != GSS_C_NO_CREDENTIAL,
+ "mechanism gss_add_cred did not return a cred");
+ *out = new_mc;
+ } else
+ free(new_mc);
+
+ return major_status;
+}
+
+static OM_uint32
+add_mech_cred_internal(OM_uint32 *minor_status,
+ gss_const_name_t desired_name,
+ gssapi_mech_interface m,
+ gss_cred_usage_t cred_usage,
+ OM_uint32 initiator_time_req,
+ OM_uint32 acceptor_time_req,
+ gss_const_key_value_set_t cred_store,
+ struct _gss_cred *mut_cred,
+ OM_uint32 *initiator_time_rec,
+ OM_uint32 *acceptor_time_rec)
+{
+ OM_uint32 major_status;
+ struct _gss_mechanism_cred *mc;
+ struct _gss_mechanism_name *mn;
+
+ heim_assert((m->gm_flags & GM_USE_MG_CRED) == 0,
+ "add_mech_cred_internal must be called with concrete mechanism");
+
+ if (desired_name != GSS_C_NO_NAME) {
+ major_status = _gss_find_mn(minor_status,
+ (struct _gss_name *)desired_name,
+ &m->gm_mech_oid, &mn);
+ if (major_status != GSS_S_COMPLETE)
+ return major_status;
+ } else
+ mn = NULL;
+
+ /*
+ * If we have an existing mechanism credential for mechanism m, then
+ * add the desired credential to it; otherwise, create a new one and
+ * add it to mut_cred.
+ */
+ HEIM_TAILQ_FOREACH(mc, &mut_cred->gc_mc, gmc_link) {
+ if (gss_oid_equal(&m->gm_mech_oid, mc->gmc_mech_oid))
+ break;
+ }
+
+ if (mc) {
+ major_status = _gss_mg_add_mech_cred(minor_status, m,
+ mc, mn, cred_usage,
+ initiator_time_req, acceptor_time_req,
+ cred_store, NULL,
+ initiator_time_rec, acceptor_time_rec);
+ } else {
+ struct _gss_mechanism_cred *new_mc = NULL;
+
+ major_status = _gss_mg_add_mech_cred(minor_status, m,
+ NULL, mn, cred_usage,
+ initiator_time_req, acceptor_time_req,
+ cred_store, &new_mc,
+ initiator_time_rec, acceptor_time_rec);
+ if (major_status == GSS_S_COMPLETE)
+ HEIM_TAILQ_INSERT_TAIL(&mut_cred->gc_mc, new_mc, gmc_link);
+ }
+
+ return major_status;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_add_cred_from(OM_uint32 *minor_status,
+ gss_cred_id_t input_cred_handle,
+ gss_const_name_t desired_name,
+ const gss_OID desired_mech,
+ gss_cred_usage_t cred_usage,
+ OM_uint32 initiator_time_req,
+ OM_uint32 acceptor_time_req,
+ gss_const_key_value_set_t cred_store,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *initiator_time_rec,
+ OM_uint32 *acceptor_time_rec)
+{
+ OM_uint32 major_status;
+ gssapi_mech_interface m;
+ gss_cred_id_t release_cred = GSS_C_NO_CREDENTIAL;
+ struct _gss_cred *mut_cred;
+ OM_uint32 junk;
+
+ *minor_status = 0;
+
+ /* Input validation */
+ if (output_cred_handle)
+ *output_cred_handle = GSS_C_NO_CREDENTIAL;
+ if (initiator_time_rec)
+ *initiator_time_rec = 0;
+ if (acceptor_time_rec)
+ *acceptor_time_rec = 0;
+ if (actual_mechs)
+ *actual_mechs = GSS_C_NO_OID_SET;
+ if ((m = __gss_get_mechanism(desired_mech)) == NULL)
+ return GSS_S_BAD_MECH;
+ if (input_cred_handle == GSS_C_NO_CREDENTIAL &&
+ output_cred_handle == NULL) {
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+ }
+
+ /* Setup mut_cred to be the credential we mutate */
+ if (input_cred_handle != GSS_C_NO_CREDENTIAL &&
+ output_cred_handle != NULL) {
+ gss_cred_id_t new_cred;
+
+ /* Duplicate the input credential */
+ major_status = gss_duplicate_cred(minor_status, input_cred_handle,
+ &new_cred);
+ if (major_status != GSS_S_COMPLETE)
+ return major_status;
+ mut_cred = (struct _gss_cred *)new_cred;
+ release_cred = (gss_cred_id_t)mut_cred;
+ } else if (input_cred_handle != GSS_C_NO_CREDENTIAL) {
+ /* Mutate the input credentials */
+ mut_cred = rk_UNCONST(input_cred_handle);
+ } else {
+ mut_cred = _gss_mg_alloc_cred();
+ if (mut_cred == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_UNAVAILABLE;
+ }
+ release_cred = (gss_cred_id_t)mut_cred;
+ }
+
+ if (m->gm_flags & GM_USE_MG_CRED) {
+ struct _gss_mech_switch *ms;
+ OM_uint32 initiator_time_min = GSS_C_INDEFINITE;
+ OM_uint32 acceptor_time_min = GSS_C_INDEFINITE;
+
+ major_status = GSS_S_UNAVAILABLE; /* in case of no mechs */
+
+ if (input_cred_handle == GSS_C_NO_CREDENTIAL) {
+ HEIM_TAILQ_FOREACH(ms, &_gss_mechs, gm_link) {
+ m = &ms->gm_mech; /* for _gss_mg_error() */
+
+ if (m->gm_flags & GM_USE_MG_CRED)
+ continue;
+
+ major_status = add_mech_cred_internal(minor_status, desired_name, m,
+ cred_usage,
+ initiator_time_req, acceptor_time_req,
+ cred_store, mut_cred,
+ initiator_time_rec, acceptor_time_rec);
+ if (major_status != GSS_S_COMPLETE)
+ continue;
+
+ if (initiator_time_rec && *initiator_time_rec < initiator_time_min)
+ initiator_time_min = *initiator_time_rec;
+ if (acceptor_time_rec && *acceptor_time_rec < acceptor_time_min)
+ acceptor_time_min = *acceptor_time_rec;
+ }
+ } else {
+ OM_uint32 lifetime;
+ gss_cred_usage_t usage = GSS_C_BOTH;
+
+ major_status = gss_inquire_cred(minor_status, input_cred_handle,
+ NULL, &lifetime, &usage, NULL);
+ if (major_status == GSS_S_COMPLETE) {
+ if (usage == GSS_C_BOTH || usage == GSS_C_INITIATE)
+ initiator_time_min = lifetime;
+ if (usage == GSS_C_BOTH || usage == GSS_C_ACCEPT)
+ acceptor_time_min = lifetime;
+ }
+ }
+
+ if (initiator_time_rec)
+ *initiator_time_rec = initiator_time_min;
+ if (acceptor_time_rec)
+ *acceptor_time_rec = acceptor_time_min;
+ } else {
+ major_status = add_mech_cred_internal(minor_status, desired_name, m,
+ cred_usage,
+ initiator_time_req, acceptor_time_req,
+ cred_store, mut_cred,
+ initiator_time_rec, acceptor_time_rec);
+ }
+
+ if (major_status != GSS_S_COMPLETE)
+ _gss_mg_error(m, *minor_status);
+
+ /* Lastly, we have to inquire the cred to get the actual_mechs */
+ if (major_status == GSS_S_COMPLETE && actual_mechs != NULL) {
+ major_status = gss_inquire_cred(minor_status,
+ (gss_const_cred_id_t)mut_cred, NULL,
+ NULL, NULL, actual_mechs);
+ }
+ if (major_status == GSS_S_COMPLETE) {
+ if (output_cred_handle != NULL)
+ *output_cred_handle = (gss_cred_id_t)mut_cred;
+ } else {
+ gss_release_cred(&junk, &release_cred);
+ }
+ return major_status;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_add_cred_with_password.c b/third_party/heimdal/lib/gssapi/mech/gss_add_cred_with_password.c
new file mode 100644
index 0000000..eeb5949
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_add_cred_with_password.c
@@ -0,0 +1,88 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_add_cred.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_add_cred_with_password(OM_uint32 *minor_status,
+ gss_const_cred_id_t input_cred_handle,
+ gss_const_name_t desired_name,
+ const gss_OID desired_mech,
+ const gss_buffer_t password,
+ gss_cred_usage_t cred_usage,
+ OM_uint32 initiator_time_req,
+ OM_uint32 acceptor_time_req,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *initiator_time_rec,
+ OM_uint32 *acceptor_time_rec)
+{
+ OM_uint32 major_status;
+ gss_key_value_element_desc kv;
+ gss_key_value_set_desc store;
+ char *spassword = NULL;
+
+ *output_cred_handle = GSS_C_NO_CREDENTIAL;
+
+ if (password == GSS_C_NO_BUFFER || password->value == NULL)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+
+ spassword = malloc(password->length + 1);
+ if (spassword == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ memcpy(spassword, password->value, password->length);
+ spassword[password->length] = '\0';
+
+ kv.key = "password";
+ kv.value = spassword;
+
+ store.count = 1;
+ store.elements = &kv;
+
+ major_status = gss_add_cred_from(minor_status,
+ rk_UNCONST(input_cred_handle),
+ desired_name,
+ desired_mech,
+ cred_usage,
+ initiator_time_req,
+ acceptor_time_req,
+ &store,
+ output_cred_handle,
+ actual_mechs,
+ initiator_time_rec,
+ acceptor_time_rec);
+
+ if (spassword) {
+ memset_s(spassword, password->length, 0, password->length);
+ free(spassword);
+ }
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_add_oid_set_member.c b/third_party/heimdal/lib/gssapi/mech/gss_add_oid_set_member.c
new file mode 100644
index 0000000..8574224
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_add_oid_set_member.c
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 1997 - 2001, 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+/**
+ * Add a oid to the oid set.
+ *
+ * If there is a duplicate member of the oid, the new member is not
+ * added to to the set.
+ *
+ * @param minor_status minor status code.
+ * @param member_oid member to add to the oid set
+ * @param oid_set oid set to add the member too
+ *
+ * @returns a gss_error code, see gss_display_status() about printing
+ * the error code.
+ *
+ * @ingroup gssapi
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_add_oid_set_member (OM_uint32 * minor_status,
+ const gss_OID member_oid,
+ gss_OID_set * oid_set)
+{
+ gss_OID tmp, interned_oid;
+ size_t n;
+ OM_uint32 res;
+ int present;
+
+ res = gss_test_oid_set_member(minor_status, member_oid, *oid_set, &present);
+ if (res != GSS_S_COMPLETE)
+ return res;
+
+ if (present) {
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+ }
+
+ n = (*oid_set)->count + 1;
+ tmp = realloc ((*oid_set)->elements, n * sizeof(gss_OID_desc));
+ if (tmp == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ (*oid_set)->elements = tmp;
+
+ res = _gss_intern_oid(minor_status, member_oid, &interned_oid);
+ if (res != GSS_S_COMPLETE)
+ return res;
+
+ (*oid_set)->count = n;
+ (*oid_set)->elements[n-1] = *interned_oid;
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_aeap.c b/third_party/heimdal/lib/gssapi/mech/gss_aeap.c
new file mode 100644
index 0000000..dbcd611
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_aeap.c
@@ -0,0 +1,334 @@
+/*
+ * AEAD support
+ */
+
+#include "mech_locl.h"
+
+/**
+ * Encrypts or sign the data.
+ *
+ * This is a more complicated version of gss_wrap(), it allows the
+ * caller to use AEAD data (signed header/trailer) and allow greater
+ * controll over where the encrypted data is placed.
+ *
+ * The maximum packet size is gss_context_stream_sizes.max_msg_size.
+ *
+ * The caller needs provide the folloing buffers when using in conf_req_flag=1 mode:
+ *
+ * - HEADER (of size gss_context_stream_sizes.header)
+ * { DATA or SIGN_ONLY } (optional, zero or more)
+ * PADDING (of size gss_context_stream_sizes.blocksize, if zero padding is zero, can be omitted)
+ * TRAILER (of size gss_context_stream_sizes.trailer)
+ *
+ * - on DCE-RPC mode, the caller can skip PADDING and TRAILER if the
+ * DATA elements is padded to a block bountry and header is of at
+ * least size gss_context_stream_sizes.header + gss_context_stream_sizes.trailer.
+ *
+ * HEADER, PADDING, TRAILER will be shrunken to the size required to transmit any of them too large.
+ *
+ * To generate gss_wrap() compatible packets, use: HEADER | DATA | PADDING | TRAILER
+ *
+ * When used in conf_req_flag=0,
+ *
+ * - HEADER (of size gss_context_stream_sizes.header)
+ * { DATA or SIGN_ONLY } (optional, zero or more)
+ * PADDING (of size gss_context_stream_sizes.blocksize, if zero padding is zero, can be omitted)
+ * TRAILER (of size gss_context_stream_sizes.trailer)
+ *
+ *
+ * The input sizes of HEADER, PADDING and TRAILER can be fetched using gss_wrap_iov_length() or
+ * gss_context_query_attributes().
+ *
+ * @ingroup gssapi
+ */
+
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_wrap_iov(OM_uint32 * minor_status,
+ gss_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ int * conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ struct _gss_context *ctx = (struct _gss_context *) context_handle;
+ gssapi_mech_interface m;
+
+ if (minor_status)
+ *minor_status = 0;
+ if (conf_state)
+ *conf_state = 0;
+ if (ctx == NULL)
+ return GSS_S_NO_CONTEXT;
+ if (iov == NULL && iov_count != 0)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+
+ m = ctx->gc_mech;
+
+ if (m->gm_wrap_iov == NULL)
+ return GSS_S_UNAVAILABLE;
+
+ return (m->gm_wrap_iov)(minor_status, ctx->gc_ctx,
+ conf_req_flag, qop_req, conf_state,
+ iov, iov_count);
+}
+
+/**
+ * Decrypt or verifies the signature on the data.
+ *
+ *
+ * @ingroup gssapi
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_unwrap_iov(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ int *conf_state,
+ gss_qop_t *qop_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ struct _gss_context *ctx = (struct _gss_context *) context_handle;
+ gssapi_mech_interface m;
+
+ if (minor_status)
+ *minor_status = 0;
+ if (conf_state)
+ *conf_state = 0;
+ if (qop_state)
+ *qop_state = 0;
+ if (ctx == NULL)
+ return GSS_S_NO_CONTEXT;
+ if (iov == NULL && iov_count != 0)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+
+ m = ctx->gc_mech;
+
+ if (m->gm_unwrap_iov == NULL)
+ return GSS_S_UNAVAILABLE;
+
+ return (m->gm_unwrap_iov)(minor_status, ctx->gc_ctx,
+ conf_state, qop_state,
+ iov, iov_count);
+}
+
+/**
+ * Update the length fields in iov buffer for the types:
+ * - GSS_IOV_BUFFER_TYPE_HEADER
+ * - GSS_IOV_BUFFER_TYPE_PADDING
+ * - GSS_IOV_BUFFER_TYPE_TRAILER
+ *
+ * Consider using gss_context_query_attributes() to fetch the data instead.
+ *
+ * @ingroup gssapi
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_wrap_iov_length(OM_uint32 * minor_status,
+ gss_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ int *conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ struct _gss_context *ctx = (struct _gss_context *) context_handle;
+ gssapi_mech_interface m;
+
+ if (minor_status)
+ *minor_status = 0;
+ if (conf_state)
+ *conf_state = 0;
+ if (ctx == NULL)
+ return GSS_S_NO_CONTEXT;
+ if (iov == NULL && iov_count != 0)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+
+ m = ctx->gc_mech;
+
+ if (m->gm_wrap_iov_length == NULL)
+ return GSS_S_UNAVAILABLE;
+
+ return (m->gm_wrap_iov_length)(minor_status, ctx->gc_ctx,
+ conf_req_flag, qop_req, conf_state,
+ iov, iov_count);
+}
+
+/**
+ * Free all buffer allocated by gss_wrap_iov() or gss_unwrap_iov() by
+ * looking at the GSS_IOV_BUFFER_FLAG_ALLOCATED flag.
+ *
+ * @ingroup gssapi
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_release_iov_buffer(OM_uint32 *minor_status,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ OM_uint32 junk;
+ int i;
+
+ if (minor_status)
+ *minor_status = 0;
+ if (iov == NULL && iov_count != 0)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+
+ for (i = 0; i < iov_count; i++) {
+ if ((iov[i].type & GSS_IOV_BUFFER_FLAG_ALLOCATED) == 0)
+ continue;
+ gss_release_buffer(&junk, &iov[i].buffer);
+ iov[i].type &= ~GSS_IOV_BUFFER_FLAG_ALLOCATED;
+ }
+ return GSS_S_COMPLETE;
+}
+
+/**
+ * Query the context for parameters.
+ *
+ * SSPI equivalent if this function is QueryContextAttributes.
+ *
+ * - GSS_C_ATTR_STREAM_SIZES data is a gss_context_stream_sizes.
+ *
+ * @ingroup gssapi
+ */
+
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_attr_stream_sizes_oid_desc =
+ {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x03")};
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_context_query_attributes(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_OID attribute,
+ void *data,
+ size_t len)
+{
+ if (minor_status)
+ *minor_status = 0;
+
+ if (gss_oid_equal(GSS_C_ATTR_STREAM_SIZES, attribute)) {
+ memset(data, 0, len);
+ return GSS_S_COMPLETE;
+ }
+
+ return GSS_S_FAILURE;
+}
+
+/*
+ * AEAD wrap API for a single piece of associated data, for compatibility
+ * with MIT and as specified by draft-howard-gssapi-aead-00.txt.
+ *
+ * @ingroup gssapi
+ */
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_wrap_aead(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ gss_buffer_t input_assoc_buffer,
+ gss_buffer_t input_payload_buffer,
+ int *conf_state,
+ gss_buffer_t output_message_buffer)
+{
+ OM_uint32 major_status, tmp, flags = 0;
+ gss_iov_buffer_desc iov[5];
+ size_t i;
+ unsigned char *p;
+
+ memset(iov, 0, sizeof(iov));
+
+ iov[0].type = GSS_IOV_BUFFER_TYPE_HEADER;
+
+ iov[1].type = GSS_IOV_BUFFER_TYPE_SIGN_ONLY;
+ if (input_assoc_buffer)
+ iov[1].buffer = *input_assoc_buffer;
+
+ iov[2].type = GSS_IOV_BUFFER_TYPE_DATA;
+ if (input_payload_buffer)
+ iov[2].buffer.length = input_payload_buffer->length;
+
+ gss_inquire_context(minor_status, context_handle, NULL, NULL,
+ NULL, NULL, &flags, NULL, NULL);
+
+ /* krb5 mech rejects padding/trailer if DCE-style is set */
+ iov[3].type = (flags & GSS_C_DCE_STYLE) ? GSS_IOV_BUFFER_TYPE_EMPTY
+ : GSS_IOV_BUFFER_TYPE_PADDING;
+ iov[4].type = (flags & GSS_C_DCE_STYLE) ? GSS_IOV_BUFFER_TYPE_EMPTY
+ : GSS_IOV_BUFFER_TYPE_TRAILER;
+
+ major_status = gss_wrap_iov_length(minor_status, context_handle,
+ conf_req_flag, qop_req, conf_state,
+ iov, 5);
+ if (GSS_ERROR(major_status))
+ return major_status;
+
+ for (i = 0, output_message_buffer->length = 0; i < 5; i++) {
+ if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_SIGN_ONLY)
+ continue;
+
+ output_message_buffer->length += iov[i].buffer.length;
+ }
+
+ output_message_buffer->value = malloc(output_message_buffer->length);
+ if (output_message_buffer->value == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ for (i = 0, p = output_message_buffer->value; i < 5; i++) {
+ if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_SIGN_ONLY)
+ continue;
+ else if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_DATA)
+ memcpy(p, input_payload_buffer->value, input_payload_buffer->length);
+
+ iov[i].buffer.value = p;
+ p += iov[i].buffer.length;
+ }
+
+ major_status = gss_wrap_iov(minor_status, context_handle, conf_req_flag,
+ qop_req, conf_state, iov, 5);
+ if (GSS_ERROR(major_status))
+ gss_release_buffer(&tmp, output_message_buffer);
+
+ return major_status;
+}
+
+/*
+ * AEAD unwrap for a single piece of associated data, for compatibility
+ * with MIT and as specified by draft-howard-gssapi-aead-00.txt.
+ *
+ * @ingroup gssapi
+ */
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_unwrap_aead(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ gss_buffer_t input_message_buffer,
+ gss_buffer_t input_assoc_buffer,
+ gss_buffer_t output_payload_buffer,
+ int *conf_state,
+ gss_qop_t *qop_state)
+{
+ OM_uint32 major_status, tmp;
+ gss_iov_buffer_desc iov[3];
+
+ memset(iov, 0, sizeof(iov));
+
+ iov[0].type = GSS_IOV_BUFFER_TYPE_STREAM;
+ iov[0].buffer = *input_message_buffer;
+
+ iov[1].type = GSS_IOV_BUFFER_TYPE_SIGN_ONLY;
+ if (input_assoc_buffer)
+ iov[1].buffer = *input_assoc_buffer;
+
+ iov[2].type = GSS_IOV_BUFFER_TYPE_DATA | GSS_IOV_BUFFER_FLAG_ALLOCATE;
+
+ major_status = gss_unwrap_iov(minor_status, context_handle, conf_state,
+ qop_state, iov, 3);
+ if (GSS_ERROR(major_status))
+ gss_release_iov_buffer(&tmp, &iov[2], 1);
+ else
+ *output_payload_buffer = iov[2].buffer;
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_authorize_localname.c b/third_party/heimdal/lib/gssapi/mech/gss_authorize_localname.c
new file mode 100644
index 0000000..b72b7bd
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_authorize_localname.c
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) 2011, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+gss_buffer_desc GSSAPI_LIB_VARIABLE __gss_c_attr_local_login_user = {
+ sizeof("local-login-user") - 1,
+ "local-login-user"
+};
+
+static OM_uint32
+mech_authorize_localname(OM_uint32 *minor_status,
+ const struct _gss_name *name,
+ const struct _gss_name *user)
+{
+ OM_uint32 major_status = GSS_S_NAME_NOT_MN;
+ struct _gss_mechanism_name *mn;
+
+ HEIM_TAILQ_FOREACH(mn, &name->gn_mn, gmn_link) {
+ gssapi_mech_interface m = mn->gmn_mech;
+
+ if (m->gm_authorize_localname == NULL) {
+ major_status = GSS_S_UNAVAILABLE;
+ continue;
+ }
+
+ major_status = m->gm_authorize_localname(minor_status,
+ mn->gmn_name,
+ &user->gn_value,
+ user->gn_type);
+ if (major_status != GSS_S_UNAUTHORIZED)
+ break;
+ }
+
+ return major_status;
+}
+
+/*
+ * Naming extensions based local login authorization.
+ */
+static OM_uint32
+attr_authorize_localname(OM_uint32 *minor_status,
+ const struct _gss_name *name,
+ const struct _gss_name *user)
+{
+ OM_uint32 major_status = GSS_S_UNAVAILABLE;
+ int more = -1;
+
+ if (!gss_oid_equal(user->gn_type, GSS_C_NT_USER_NAME))
+ return GSS_S_BAD_NAMETYPE;
+
+ while (more != 0 && major_status != GSS_S_COMPLETE) {
+ OM_uint32 tmpMajor, tmpMinor;
+ gss_buffer_desc value;
+ gss_buffer_desc display_value;
+ int authenticated = 0, complete = 0;
+
+ tmpMajor = gss_get_name_attribute(minor_status,
+ (gss_name_t)name,
+ GSS_C_ATTR_LOCAL_LOGIN_USER,
+ &authenticated,
+ &complete,
+ &value,
+ &display_value,
+ &more);
+ if (GSS_ERROR(tmpMajor)) {
+ major_status = tmpMajor;
+ break;
+ }
+
+ /* If attribute is present, return an authoritative error code. */
+ if (authenticated &&
+ value.length == user->gn_value.length &&
+ memcmp(value.value, user->gn_value.value, user->gn_value.length) == 0)
+ major_status = GSS_S_COMPLETE;
+ else
+ major_status = GSS_S_UNAUTHORIZED;
+
+ gss_release_buffer(&tmpMinor, &value);
+ gss_release_buffer(&tmpMinor, &display_value);
+ }
+
+ return major_status;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_authorize_localname(OM_uint32 *minor_status,
+ gss_const_name_t gss_name,
+ gss_const_name_t gss_user)
+
+{
+ OM_uint32 major_status;
+ const struct _gss_name *name = (const struct _gss_name *) gss_name;
+ const struct _gss_name *user = (const struct _gss_name *) gss_user;
+ int mechAvailable = 0;
+
+ *minor_status = 0;
+
+ if (gss_name == GSS_C_NO_NAME || gss_user == GSS_C_NO_NAME)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+
+ /*
+ * We should check that the user name is not a mechanism name, but
+ * as Heimdal always calls the mechanism's gss_import_name(), it's
+ * not possible to make this check.
+ */
+#if 0
+ if (HEIM_TAILQ_FIRST(&user->gn_mn) != NULL)
+ return GSS_S_BAD_NAME;
+#endif
+
+ /* If mech returns yes, we return yes */
+ major_status = mech_authorize_localname(minor_status, name, user);
+ if (major_status == GSS_S_COMPLETE)
+ return GSS_S_COMPLETE;
+ else if (major_status != GSS_S_UNAVAILABLE)
+ mechAvailable = 1;
+
+ /* If attribute exists, it is authoritative */
+ major_status = attr_authorize_localname(minor_status, name, user);
+ if (major_status == GSS_S_COMPLETE || major_status == GSS_S_UNAUTHORIZED)
+ return major_status;
+
+ /* If mechanism did not implement SPI, compare the local name */
+ if (mechAvailable == 0) {
+ int match = 0;
+
+ major_status = gss_compare_name(minor_status, gss_name,
+ gss_user, &match);
+ if (major_status == GSS_S_COMPLETE && match == 0)
+ major_status = GSS_S_UNAUTHORIZED;
+ }
+
+ return major_status;
+}
+
+GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL
+gss_userok(gss_const_name_t name,
+ const char *user)
+{
+ OM_uint32 major_status, minor_status;
+ gss_buffer_desc userBuf;
+ gss_name_t userName;
+
+ userBuf.value = (void *)user;
+ userBuf.length = strlen(user);
+
+ major_status = gss_import_name(&minor_status, &userBuf,
+ GSS_C_NT_USER_NAME, &userName);
+ if (GSS_ERROR(major_status))
+ return 0;
+
+ major_status = gss_authorize_localname(&minor_status, name, userName);
+
+ gss_release_name(&minor_status, &userName);
+
+ return (major_status == GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_buffer_set.c b/third_party/heimdal/lib/gssapi/mech/gss_buffer_set.c
new file mode 100644
index 0000000..48fb720
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_buffer_set.c
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2004, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_create_empty_buffer_set
+ (OM_uint32 * minor_status,
+ gss_buffer_set_t *buffer_set)
+{
+ gss_buffer_set_t set;
+
+ set = (gss_buffer_set_desc *) malloc(sizeof(*set));
+ if (set == GSS_C_NO_BUFFER_SET) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ set->count = 0;
+ set->elements = NULL;
+
+ *buffer_set = set;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_add_buffer_set_member
+ (OM_uint32 * minor_status,
+ const gss_buffer_t member_buffer,
+ gss_buffer_set_t *buffer_set)
+{
+ gss_buffer_set_t set;
+ gss_buffer_t p;
+ OM_uint32 ret;
+
+ if (*buffer_set == GSS_C_NO_BUFFER_SET) {
+ ret = gss_create_empty_buffer_set(minor_status,
+ buffer_set);
+ if (ret) {
+ return ret;
+ }
+ }
+
+ set = *buffer_set;
+ set->elements = realloc(set->elements,
+ (set->count + 1) * sizeof(set->elements[0]));
+ if (set->elements == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ p = &set->elements[set->count];
+
+ p->value = malloc(member_buffer->length);
+ if (p->value == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ memcpy(p->value, member_buffer->value, member_buffer->length);
+ p->length = member_buffer->length;
+
+ set->count++;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_release_buffer_set(OM_uint32 * minor_status,
+ gss_buffer_set_t *buffer_set)
+{
+ size_t i;
+ OM_uint32 minor;
+
+ *minor_status = 0;
+
+ if (*buffer_set == GSS_C_NO_BUFFER_SET)
+ return GSS_S_COMPLETE;
+
+ for (i = 0; i < (*buffer_set)->count; i++)
+ gss_release_buffer(&minor, &((*buffer_set)->elements[i]));
+
+ free((*buffer_set)->elements);
+
+ (*buffer_set)->elements = NULL;
+ (*buffer_set)->count = 0;
+
+ free(*buffer_set);
+ *buffer_set = GSS_C_NO_BUFFER_SET;
+
+ return GSS_S_COMPLETE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_canonicalize_name.c b/third_party/heimdal/lib/gssapi/mech/gss_canonicalize_name.c
new file mode 100644
index 0000000..859c688
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_canonicalize_name.c
@@ -0,0 +1,104 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_canonicalize_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+/**
+ * gss_canonicalize_name takes a Internal Name (IN) and converts in into a
+ * mechanism specific Mechanism Name (MN).
+ *
+ * The input name may multiple name, or generic name types.
+ *
+ * If the input_name if of the GSS_C_NT_USER_NAME, and the Kerberos
+ * mechanism is specified, the resulting MN type is a
+ * GSS_KRB5_NT_PRINCIPAL_NAME.
+ *
+ * For more information about @ref internalVSmechname.
+ *
+ * @param minor_status minor status code.
+ * @param input_name name to covert, unchanged by gss_canonicalize_name().
+ * @param mech_type the type to convert Name too.
+ * @param output_name the resulting type, release with
+ * gss_release_name(), independent of input_name.
+ *
+ * @returns a gss_error code, see gss_display_status() about printing
+ * the error code.
+ *
+ * @ingroup gssapi
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_canonicalize_name(OM_uint32 *minor_status,
+ gss_const_name_t input_name,
+ const gss_OID mech_type,
+ gss_name_t *output_name)
+{
+ OM_uint32 major_status;
+ struct _gss_name *name = (struct _gss_name *) input_name;
+ struct _gss_mechanism_name *mn;
+ gssapi_mech_interface m;
+ gss_name_t new_canonical_name;
+
+ *minor_status = 0;
+ *output_name = GSS_C_NO_NAME;
+
+ if ((m = __gss_get_mechanism(mech_type)) == NULL ||
+ (m->gm_flags & GM_USE_MG_NAME))
+ return GSS_S_BAD_MECH;
+
+ major_status = _gss_find_mn(minor_status, name, mech_type, &mn);
+ if (major_status)
+ return major_status;
+ if (mn == NULL)
+ return GSS_S_BAD_NAME;
+
+ m = mn->gmn_mech;
+ major_status = m->gm_canonicalize_name(minor_status,
+ mn->gmn_name, mech_type, &new_canonical_name);
+ if (major_status) {
+ _gss_mg_error(m, *minor_status);
+ return (major_status);
+ }
+
+ /*
+ * Now we make a new name and mark it as an MN.
+ */
+ *minor_status = 0;
+ name = _gss_create_name(new_canonical_name, m);
+ if (!name) {
+ m->gm_release_name(minor_status, &new_canonical_name);
+ *minor_status = ENOMEM;
+ return (GSS_S_FAILURE);
+ }
+
+ *output_name = (gss_name_t) name;
+
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_compare_name.c b/third_party/heimdal/lib/gssapi/mech/gss_compare_name.c
new file mode 100644
index 0000000..97ef578
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_compare_name.c
@@ -0,0 +1,102 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_compare_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_compare_name(OM_uint32 *minor_status,
+ gss_const_name_t name1_arg,
+ gss_const_name_t name2_arg,
+ int *name_equal)
+{
+ struct _gss_name *name1 = (struct _gss_name *) name1_arg;
+ struct _gss_name *name2 = (struct _gss_name *) name2_arg;
+
+ /*
+ * First check the implementation-independant name if both
+ * names have one. Otherwise, try to find common mechanism
+ * names and compare them.
+ */
+ if (name1->gn_value.value && name2->gn_value.value &&
+ name1->gn_type == GSS_C_NO_OID && name2->gn_type == GSS_C_NO_OID) {
+ *name_equal =
+ name1->gn_value.length == name2->gn_value.length &&
+ memcmp(name1->gn_value.value, name2->gn_value.value,
+ name1->gn_value.length) == 0;
+ } else if (name1->gn_value.value && name2->gn_value.value &&
+ name1->gn_type != GSS_C_NO_OID &&
+ name2->gn_type != GSS_C_NO_OID) {
+ *name_equal = 1;
+ /* RFC 2743: anonymous names always compare false */
+ if (gss_oid_equal(name1->gn_type, GSS_C_NT_ANONYMOUS) ||
+ gss_oid_equal(name2->gn_type, GSS_C_NT_ANONYMOUS) ||
+ !gss_oid_equal(name1->gn_type, name2->gn_type)) {
+ *name_equal = 0;
+ } else if (name1->gn_value.length != name2->gn_value.length ||
+ memcmp(name1->gn_value.value, name2->gn_value.value,
+ name1->gn_value.length) != 0) {
+ *name_equal = 0;
+ }
+ } else {
+ struct _gss_mechanism_name *mn1;
+ struct _gss_mechanism_name *mn2;
+
+ HEIM_TAILQ_FOREACH(mn1, &name1->gn_mn, gmn_link) {
+ OM_uint32 major_status;
+
+ major_status = _gss_find_mn(minor_status, name2,
+ mn1->gmn_mech_oid, &mn2);
+ if (major_status == GSS_S_COMPLETE && mn2) {
+ return (mn1->gmn_mech->gm_compare_name(
+ minor_status,
+ mn1->gmn_name,
+ mn2->gmn_name,
+ name_equal));
+ }
+ }
+ HEIM_TAILQ_FOREACH(mn2, &name2->gn_mn, gmn_link) {
+ OM_uint32 major_status;
+
+ major_status = _gss_find_mn(minor_status, name1,
+ mn2->gmn_mech_oid, &mn1);
+ if (major_status == GSS_S_COMPLETE && mn1) {
+ return (mn2->gmn_mech->gm_compare_name(
+ minor_status,
+ mn2->gmn_name,
+ mn1->gmn_name,
+ name_equal));
+ }
+ }
+ *name_equal = 0;
+ }
+
+ *minor_status = 0;
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_context_time.c b/third_party/heimdal/lib/gssapi/mech/gss_context_time.c
new file mode 100644
index 0000000..a5b646c
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_context_time.c
@@ -0,0 +1,40 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_context_time.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_context_time(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ OM_uint32 *time_rec)
+{
+ struct _gss_context *ctx = (struct _gss_context *) context_handle;
+ gssapi_mech_interface m = ctx->gc_mech;
+
+ return (m->gm_context_time(minor_status, ctx->gc_ctx, time_rec));
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_create_empty_oid_set.c b/third_party/heimdal/lib/gssapi/mech/gss_create_empty_oid_set.c
new file mode 100644
index 0000000..8d880f5
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_create_empty_oid_set.c
@@ -0,0 +1,51 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_create_empty_oid_set.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_create_empty_oid_set(OM_uint32 *minor_status,
+ gss_OID_set *oid_set)
+{
+ gss_OID_set set;
+
+ *minor_status = 0;
+ *oid_set = GSS_C_NO_OID_SET;
+
+ set = malloc(sizeof(gss_OID_set_desc));
+ if (!set) {
+ *minor_status = ENOMEM;
+ return (GSS_S_FAILURE);
+ }
+
+ set->count = 0;
+ set->elements = 0;
+ *oid_set = set;
+
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_cred.c b/third_party/heimdal/lib/gssapi/mech/gss_cred.c
new file mode 100644
index 0000000..00561ce
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_cred.c
@@ -0,0 +1,326 @@
+/*
+ * Copyright (c) 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+#include <krb5.h>
+
+static OM_uint32
+store_mech_oid_and_oid_set(OM_uint32 *minor_status,
+ krb5_storage *sp,
+ gss_const_OID mech,
+ gss_const_OID_set oids)
+{
+ OM_uint32 ret;
+ size_t i, len;
+
+ ret = _gss_mg_store_oid(minor_status, sp, mech);
+ if (ret)
+ return ret;
+
+ for (i = 0, len = 0; i < oids->count; i++)
+ len += 4 + oids->elements[i].length;
+
+ *minor_status = krb5_store_uint32(sp, len);
+ if (*minor_status)
+ return GSS_S_FAILURE;
+
+ for (i = 0; i < oids->count; i++) {
+ ret = _gss_mg_store_oid(minor_status, sp, &oids->elements[i]);
+ if (ret)
+ return ret;
+ }
+
+ return GSS_S_COMPLETE;
+}
+
+
+/*
+ * format: any number of:
+ * mech-len: int32
+ * mech-data: char * (not alligned)
+ * cred-len: int32
+ * cred-data char * (not alligned)
+ *
+ * where neg_mechs is encoded for GSS_SPNEGO_MECHANISM
+*/
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_export_cred(OM_uint32 * minor_status,
+ gss_cred_id_t cred_handle,
+ gss_buffer_t token)
+{
+ struct _gss_cred *cred = (struct _gss_cred *)cred_handle;
+ struct _gss_mechanism_cred *mc;
+ gss_buffer_desc buffer;
+ krb5_error_code ret;
+ krb5_ssize_t bytes;
+ krb5_storage *sp;
+ OM_uint32 major;
+ krb5_data data;
+
+ _mg_buffer_zero(token);
+
+ if (cred == NULL) {
+ *minor_status = 0;
+ return GSS_S_NO_CRED;
+ }
+
+ HEIM_TAILQ_FOREACH(mc, &cred->gc_mc, gmc_link) {
+ if (mc->gmc_mech->gm_export_cred == NULL) {
+ *minor_status = 0;
+ gss_mg_set_error_string(&mc->gmc_mech->gm_mech_oid,
+ GSS_S_NO_CRED, *minor_status,
+ "Credential doesn't support exporting");
+ return GSS_S_NO_CRED;
+ }
+ }
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ HEIM_TAILQ_FOREACH(mc, &cred->gc_mc, gmc_link) {
+ major = mc->gmc_mech->gm_export_cred(minor_status,
+ mc->gmc_cred, &buffer);
+ if (major) {
+ krb5_storage_free(sp);
+ return major;
+ }
+
+ if (buffer.length) {
+ bytes = krb5_storage_write(sp, buffer.value, buffer.length);
+ if (bytes < 0 || (size_t)bytes != buffer.length) {
+ _gss_secure_release_buffer(minor_status, &buffer);
+ krb5_storage_free(sp);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ }
+ _gss_secure_release_buffer(minor_status, &buffer);
+ }
+
+ if (cred->gc_neg_mechs != GSS_C_NO_OID_SET) {
+ major = store_mech_oid_and_oid_set(minor_status, sp,
+ GSS_SPNEGO_MECHANISM,
+ cred->gc_neg_mechs);
+ if (major != GSS_S_COMPLETE) {
+ krb5_storage_free(sp);
+ return major;
+ }
+ }
+
+ ret = krb5_storage_to_data(sp, &data);
+ krb5_storage_free(sp);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ if (data.length == 0) {
+ *minor_status = 0;
+ gss_mg_set_error_string(GSS_C_NO_OID,
+ GSS_S_NO_CRED, *minor_status,
+ "Credential was not exportable");
+ return GSS_S_NO_CRED;
+ }
+
+ token->value = data.data;
+ token->length = data.length;
+
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+import_oid_set(OM_uint32 *minor_status,
+ gss_const_buffer_t token,
+ gss_OID_set *oids)
+{
+ OM_uint32 major, junk;
+ krb5_storage *sp = NULL;
+
+ *oids = GSS_C_NO_OID_SET;
+
+ if (token->length == 0)
+ return GSS_S_COMPLETE;
+
+ major = gss_create_empty_oid_set(minor_status, oids);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+
+ sp = krb5_storage_from_readonly_mem(token->value, token->length);
+ if (sp == NULL) {
+ *minor_status = ENOMEM;
+ major = GSS_S_FAILURE;
+ goto out;
+ }
+
+ while (1) {
+ gss_OID oid;
+
+ major = _gss_mg_ret_oid(minor_status, sp, &oid);
+ if (*minor_status == (OM_uint32)HEIM_ERR_EOF)
+ break;
+ else if (major)
+ goto out;
+
+ major = gss_add_oid_set_member(minor_status, oid, oids);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+ }
+
+ major = GSS_S_COMPLETE;
+ *minor_status = 0;
+
+out:
+ if (major != GSS_S_COMPLETE)
+ gss_release_oid_set(&junk, oids);
+ krb5_storage_free(sp);
+
+ return major;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_import_cred(OM_uint32 * minor_status,
+ gss_buffer_t token,
+ gss_cred_id_t * cred_handle)
+{
+ gssapi_mech_interface m;
+ struct _gss_cred *cred;
+ krb5_storage *sp = NULL;
+ OM_uint32 major, junk;
+
+ *cred_handle = GSS_C_NO_CREDENTIAL;
+
+ if (token->length == 0) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ sp = krb5_storage_from_readonly_mem(token->value, token->length);
+ if (sp == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ cred = _gss_mg_alloc_cred();
+ if (cred == NULL) {
+ krb5_storage_free(sp);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ *cred_handle = (gss_cred_id_t)cred;
+
+ while(1) {
+ struct _gss_mechanism_cred *mc;
+ gss_buffer_desc buffer;
+ gss_cred_id_t mcred;
+ gss_OID oid;
+
+ major = _gss_mg_ret_oid(minor_status, sp, &oid);
+ if (*minor_status == (OM_uint32)HEIM_ERR_EOF)
+ break;
+ else if (major != GSS_S_COMPLETE)
+ goto out;
+
+ m = __gss_get_mechanism(oid);
+ if (!m) {
+ *minor_status = 0;
+ major = GSS_S_BAD_MECH;
+ goto out;
+ }
+
+ if (m->gm_import_cred == NULL) {
+ *minor_status = 0;
+ major = GSS_S_BAD_MECH;
+ goto out;
+ }
+
+ major = _gss_mg_ret_buffer(minor_status, sp, &buffer);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+
+ if (buffer.value == NULL) {
+ major = GSS_S_DEFECTIVE_TOKEN;
+ goto out;
+ }
+
+ if (gss_oid_equal(&m->gm_mech_oid, GSS_SPNEGO_MECHANISM)) {
+ major = import_oid_set(minor_status, &buffer, &cred->gc_neg_mechs);
+ gss_release_buffer(&junk, &buffer);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+ else
+ continue;
+ }
+
+ major = m->gm_import_cred(minor_status, &buffer, &mcred);
+ gss_release_buffer(&junk, &buffer);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+
+ mc = calloc(1, sizeof(struct _gss_mechanism_cred));
+ if (mc == NULL) {
+ *minor_status = EINVAL;
+ major = GSS_S_FAILURE;
+ goto out;
+ }
+
+ mc->gmc_mech = m;
+ mc->gmc_mech_oid = &m->gm_mech_oid;
+ mc->gmc_cred = mcred;
+
+ HEIM_TAILQ_INSERT_TAIL(&cred->gc_mc, mc, gmc_link);
+ }
+ krb5_storage_free(sp);
+ sp = NULL;
+
+ if (HEIM_TAILQ_EMPTY(&cred->gc_mc)) {
+ major = GSS_S_NO_CRED;
+ goto out;
+ }
+
+ return GSS_S_COMPLETE;
+
+ out:
+ if (sp)
+ krb5_storage_free(sp);
+
+ gss_release_cred(&junk, cred_handle);
+
+ return major;
+
+}
+
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_decapsulate_token.c b/third_party/heimdal/lib/gssapi/mech/gss_decapsulate_token.c
new file mode 100644
index 0000000..5d9eca0
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_decapsulate_token.c
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_decapsulate_token(gss_const_buffer_t input_token,
+ gss_const_OID oid,
+ gss_buffer_t output_token)
+{
+ GSSAPIContextToken ct;
+ heim_oid o;
+ OM_uint32 status;
+ int ret;
+ size_t size;
+
+ _mg_buffer_zero(output_token);
+
+ ret = der_get_oid (oid->elements, oid->length, &o, &size);
+ if (ret)
+ return GSS_S_FAILURE;
+
+ ret = decode_GSSAPIContextToken(input_token->value, input_token->length,
+ &ct, NULL);
+ if (ret) {
+ der_free_oid(&o);
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ if (der_heim_oid_cmp(&ct.thisMech, &o) == 0) {
+ status = GSS_S_COMPLETE;
+ output_token->value = ct.innerContextToken.data;
+ output_token->length = ct.innerContextToken.length;
+ der_free_oid(&ct.thisMech);
+ } else {
+ free_GSSAPIContextToken(&ct);
+ status = GSS_S_BAD_MECH;
+ }
+ der_free_oid(&o);
+
+ return status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_delete_name_attribute.c b/third_party/heimdal/lib/gssapi/mech/gss_delete_name_attribute.c
new file mode 100644
index 0000000..a1ca5da
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_delete_name_attribute.c
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2010, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_delete_name_attribute(OM_uint32 *minor_status,
+ gss_name_t input_name,
+ gss_buffer_t attr)
+{
+ OM_uint32 major_status = GSS_S_UNAVAILABLE;
+ struct _gss_name *name = (struct _gss_name *) input_name;
+ struct _gss_mechanism_name *mn;
+
+ *minor_status = 0;
+
+ if (input_name == GSS_C_NO_NAME)
+ return GSS_S_BAD_NAME;
+
+ HEIM_TAILQ_FOREACH(mn, &name->gn_mn, gmn_link) {
+ gssapi_mech_interface m = mn->gmn_mech;
+
+ if (!m->gm_delete_name_attribute)
+ continue;
+
+ major_status = m->gm_delete_name_attribute(minor_status,
+ mn->gmn_name,
+ attr);
+ if (GSS_ERROR(major_status))
+ _gss_mg_error(m, *minor_status);
+ else
+ break;
+ }
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_delete_sec_context.c b/third_party/heimdal/lib/gssapi/mech/gss_delete_sec_context.c
new file mode 100644
index 0000000..8e1f98c
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_delete_sec_context.c
@@ -0,0 +1,62 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_delete_sec_context.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_delete_sec_context(OM_uint32 *minor_status,
+ gss_ctx_id_t *context_handle,
+ gss_buffer_t output_token)
+{
+ OM_uint32 major_status;
+ struct _gss_context *ctx = (struct _gss_context *) *context_handle;
+
+ if (output_token)
+ _mg_buffer_zero(output_token);
+
+ *minor_status = 0;
+ major_status = GSS_S_COMPLETE;
+
+ if (!ctx)
+ return GSS_S_COMPLETE;
+
+ free(ctx->gc_free_this);
+
+ /*
+ * If we have an implementation ctx, delete it,
+ * otherwise fake an empty token.
+ */
+ if (ctx->gc_ctx) {
+ major_status = ctx->gc_mech->gm_delete_sec_context(
+ minor_status, &ctx->gc_ctx, output_token);
+ }
+ free(ctx);
+ *context_handle = GSS_C_NO_CONTEXT;
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_destroy_cred.c b/third_party/heimdal/lib/gssapi/mech/gss_destroy_cred.c
new file mode 100644
index 0000000..5b7fafc
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_destroy_cred.c
@@ -0,0 +1,74 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+#include <heim_threads.h>
+
+/**
+ * Destroy a credential
+ *
+ * gss_release_cred() frees the memory, gss_destroy_cred() removes the credentials from memory/disk and then call gss_release_cred() on the credential.
+ *
+ * @param min_stat minor status code
+ * @param cred_handle credentail to destory
+ *
+ * @returns a gss_error code, see gss_display_status() about printing
+ * the error code.
+ *
+ * @ingroup gssapi
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_destroy_cred(OM_uint32 *minor_status,
+ gss_cred_id_t *cred_handle)
+{
+ struct _gss_cred *cred;
+ struct _gss_mechanism_cred *mc, *next;
+
+ OM_uint32 junk;
+
+ if (cred_handle == NULL)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+ if (*cred_handle == GSS_C_NO_CREDENTIAL)
+ return GSS_S_COMPLETE;
+
+ cred = (struct _gss_cred *)*cred_handle;
+ *cred_handle = GSS_C_NO_CREDENTIAL;
+
+ HEIM_TAILQ_FOREACH_SAFE(mc, &cred->gc_mc, gmc_link, next) {
+ HEIM_TAILQ_REMOVE(&cred->gc_mc, mc, gmc_link);
+ if (mc->gmc_mech->gm_destroy_cred)
+ mc->gmc_mech->gm_destroy_cred(&junk, &mc->gmc_cred);
+ else
+ mc->gmc_mech->gm_release_cred(&junk, &mc->gmc_cred);
+ free(mc);
+ }
+ free(cred);
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_display_name.c b/third_party/heimdal/lib/gssapi/mech/gss_display_name.c
new file mode 100644
index 0000000..fadd68b
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_display_name.c
@@ -0,0 +1,82 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_display_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_display_name(OM_uint32 *minor_status,
+ gss_const_name_t input_name,
+ gss_buffer_t output_name_buffer,
+ gss_OID *output_name_type)
+{
+ OM_uint32 major_status;
+ struct _gss_name *name = (struct _gss_name *) input_name;
+ struct _gss_mechanism_name *mn;
+
+ _mg_buffer_zero(output_name_buffer);
+ if (output_name_type)
+ *output_name_type = GSS_C_NO_OID;
+
+ if (name == NULL) {
+ *minor_status = 0;
+ return (GSS_S_BAD_NAME);
+ }
+
+ /*
+ * If we know it, copy the buffer used to import the name in
+ * the first place. Otherwise, ask all the MNs in turn if
+ * they can display the thing.
+ */
+ if (name->gn_value.value) {
+ output_name_buffer->value = malloc(name->gn_value.length);
+ if (!output_name_buffer->value) {
+ *minor_status = ENOMEM;
+ return (GSS_S_FAILURE);
+ }
+ output_name_buffer->length = name->gn_value.length;
+ memcpy(output_name_buffer->value, name->gn_value.value,
+ output_name_buffer->length);
+ if (output_name_type)
+ *output_name_type = name->gn_type;
+
+ *minor_status = 0;
+ return (GSS_S_COMPLETE);
+ } else {
+ HEIM_TAILQ_FOREACH(mn, &name->gn_mn, gmn_link) {
+ major_status = mn->gmn_mech->gm_display_name(
+ minor_status, mn->gmn_name,
+ output_name_buffer,
+ output_name_type);
+ if (major_status == GSS_S_COMPLETE)
+ return (GSS_S_COMPLETE);
+ }
+ }
+
+ *minor_status = 0;
+ return (GSS_S_FAILURE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_display_name_ext.c b/third_party/heimdal/lib/gssapi/mech/gss_display_name_ext.c
new file mode 100644
index 0000000..80ea72b
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_display_name_ext.c
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2010, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_display_name_ext(OM_uint32 *minor_status,
+ gss_name_t input_name,
+ gss_OID display_as_name_type,
+ gss_buffer_t display_name)
+{
+ OM_uint32 major_status = GSS_S_UNAVAILABLE;
+ struct _gss_name *name = (struct _gss_name *) input_name;
+ struct _gss_mechanism_name *mn;
+
+ *minor_status = 0;
+ _mg_buffer_zero(display_name);
+
+ if (input_name == GSS_C_NO_NAME)
+ return GSS_S_BAD_NAME;
+
+ HEIM_TAILQ_FOREACH(mn, &name->gn_mn, gmn_link) {
+ gssapi_mech_interface m = mn->gmn_mech;
+
+ if (!m->gm_display_name_ext)
+ continue;
+
+ major_status = m->gm_display_name_ext(minor_status,
+ mn->gmn_name,
+ display_as_name_type,
+ display_name);
+ if (GSS_ERROR(major_status))
+ _gss_mg_error(m, *minor_status);
+ else
+ break;
+ }
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_display_status.c b/third_party/heimdal/lib/gssapi/mech/gss_display_status.c
new file mode 100644
index 0000000..dca5d1b
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_display_status.c
@@ -0,0 +1,227 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_display_status.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+/*
+ * Copyright (c) 1998 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+static const char *
+calling_error(OM_uint32 v)
+{
+ static const char *msgs[] = {
+ NULL, /* 0 */
+ "A required input parameter could not be read.", /* */
+ "A required output parameter could not be written.", /* */
+ "A parameter was malformed"
+ };
+
+ v >>= GSS_C_CALLING_ERROR_OFFSET;
+
+ if (v == 0)
+ return "";
+ else if (v >= sizeof(msgs)/sizeof(*msgs))
+ return "unknown calling error";
+ else
+ return msgs[v];
+}
+
+static const char *
+routine_error(OM_uint32 v)
+{
+ static const char *msgs[] = {
+ "Function completed successfully", /* 0 */
+ "An unsupported mechanism was requested",
+ "An invalid name was supplied",
+ "A supplied name was of an unsupported type",
+ "Incorrect channel bindings were supplied",
+ "An invalid status code was supplied",
+ "A token had an invalid MIC",
+ "No credentials were supplied, or the credentials were unavailable or inaccessible.",
+ "No context has been established",
+ "A token was invalid",
+ "A credential was invalid",
+ "The referenced credentials have expired",
+ "The context has expired",
+ "Miscellaneous failure (see text)",
+ "The quality-of-protection requested could not be provide",
+ "The operation is forbidden by local security policy",
+ "The operation or option is not available",
+ "The requested credential element already exists",
+ "The provided name was not a mechanism name.",
+ };
+
+ v >>= GSS_C_ROUTINE_ERROR_OFFSET;
+
+ if (v >= sizeof(msgs)/sizeof(*msgs))
+ return "unknown routine error";
+ else
+ return msgs[v];
+}
+
+static const char *
+supplementary_error(OM_uint32 v)
+{
+ static const char *msgs[] = {
+ "normal completion",
+ "continuation call to routine required",
+ "duplicate per-message token detected",
+ "timed-out per-message token detected",
+ "reordered (early) per-message token detected",
+ "skipped predecessor token(s) detected"
+ };
+
+ v >>= GSS_C_SUPPLEMENTARY_OFFSET;
+
+ if (v >= sizeof(msgs)/sizeof(*msgs))
+ return "unknown routine error";
+ else
+ return msgs[v];
+}
+
+/**
+ * Convert a GSS-API status code to text
+ *
+ * @param minor_status minor status code
+ * @param status_value status value to convert
+ * @param status_type One of:
+ * GSS_C_GSS_CODE - status_value is a GSS status code,
+ * GSS_C_MECH_CODE - status_value is a mechanism status code
+ * @param mech_type underlying mechanism. Use GSS_C_NO_OID to obtain the
+ * system default.
+ * @param message_context state information to extract further messages from the
+ * status_value
+ * @param status_string the allocated text representation. Release with
+ * gss_release_buffer()
+ *
+ * @returns a gss_error code.
+ *
+ * @ingroup gssapi
+ */
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_display_status(OM_uint32 *minor_status,
+ OM_uint32 status_value,
+ int status_type,
+ const gss_OID mech_type,
+ OM_uint32 *message_context,
+ gss_buffer_t status_string)
+{
+ OM_uint32 major_status;
+
+ _mg_buffer_zero(status_string);
+ *message_context = 0;
+
+ *minor_status = 0;
+ switch (status_type) {
+ case GSS_C_GSS_CODE: {
+ char *buf = NULL;
+ int e;
+
+ if (GSS_SUPPLEMENTARY_INFO(status_value))
+ e = asprintf(&buf, "%s", supplementary_error(
+ GSS_SUPPLEMENTARY_INFO(status_value)));
+ else
+ e = asprintf (&buf, "%s %s",
+ calling_error(GSS_CALLING_ERROR(status_value)),
+ routine_error(GSS_ROUTINE_ERROR(status_value)));
+
+ if (e < 0 || buf == NULL)
+ break;
+
+ status_string->length = strlen(buf);
+ status_string->value = buf;
+
+ return GSS_S_COMPLETE;
+ }
+ case GSS_C_MECH_CODE: {
+ OM_uint32 maj_junk, min_junk;
+ gss_buffer_desc oid;
+ char *buf = NULL;
+ int e;
+
+ major_status = _gss_mg_get_error(mech_type, status_value,
+ status_string);
+ if (major_status == GSS_S_COMPLETE) {
+ *message_context = 0;
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+ }
+
+ maj_junk = gss_oid_to_str(&min_junk, mech_type, &oid);
+ if (maj_junk != GSS_S_COMPLETE) {
+ oid.value = rk_UNCONST("unknown");
+ oid.length = 7;
+ }
+
+ e = asprintf (&buf, "unknown mech-code %lu for mech %.*s",
+ (unsigned long)status_value,
+ (int)oid.length, (char *)oid.value);
+ if (maj_junk == GSS_S_COMPLETE)
+ gss_release_buffer(&min_junk, &oid);
+
+ if (e < 0 || buf == NULL)
+ break;
+
+ status_string->length = strlen(buf);
+ status_string->value = buf;
+
+ return GSS_S_COMPLETE;
+ }
+ }
+ _mg_buffer_zero(status_string);
+ return (GSS_S_BAD_STATUS);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_duplicate_cred.c b/third_party/heimdal/lib/gssapi/mech/gss_duplicate_cred.c
new file mode 100644
index 0000000..0c25ce9
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_duplicate_cred.c
@@ -0,0 +1,153 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * Copyright (c) 2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_add_cred.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+static OM_uint32
+copy_cred_element(OM_uint32 *minor_status,
+ struct _gss_mechanism_cred *mc,
+ struct _gss_mechanism_cred **out)
+{
+ gssapi_mech_interface m = mc->gmc_mech;
+ OM_uint32 major_status, tmp;
+ struct _gss_mechanism_cred *new_mc;
+ OM_uint32 initiator_lifetime, acceptor_lifetime;
+ gss_cred_usage_t cred_usage;
+ gss_cred_id_t dup_cred = GSS_C_NO_CREDENTIAL;
+
+ *out = NULL;
+
+ if (m->gm_duplicate_cred) {
+ major_status = m->gm_duplicate_cred(minor_status,
+ mc->gmc_cred, &dup_cred);
+ } else if (m->gm_import_cred && m->gm_export_cred) {
+ gss_buffer_desc export;
+
+ major_status = m->gm_export_cred(minor_status, mc->gmc_cred, &export);
+ if (major_status == GSS_S_COMPLETE) {
+ major_status = m->gm_import_cred(minor_status, &export, &dup_cred);
+ _gss_secure_release_buffer(&tmp, &export);
+ }
+ } else {
+ struct _gss_mechanism_name mn;
+
+ mn.gmn_mech = m;
+ mn.gmn_mech_oid = mc->gmc_mech_oid;
+ mn.gmn_name = GSS_C_NO_NAME;
+
+ /* This path won't work for ephemeral creds or cred stores */
+ major_status = m->gm_inquire_cred_by_mech(minor_status, mc->gmc_cred,
+ mc->gmc_mech_oid, &mn.gmn_name,
+ &initiator_lifetime,
+ &acceptor_lifetime, &cred_usage);
+ if (major_status == GSS_S_COMPLETE) {
+ major_status = _gss_mg_add_mech_cred(minor_status,
+ m,
+ NULL, /* mc */
+ &mn,
+ cred_usage,
+ initiator_lifetime,
+ acceptor_lifetime,
+ GSS_C_NO_CRED_STORE,
+ &new_mc,
+ NULL,
+ NULL);
+ m->gm_release_name(&tmp, &mn.gmn_name);
+ }
+ }
+
+ if (major_status == GSS_S_COMPLETE) {
+ new_mc = calloc(1, sizeof(*new_mc));
+ if (new_mc == NULL) {
+ *minor_status = ENOMEM;
+ m->gm_release_cred(&tmp, &dup_cred);
+ return GSS_S_FAILURE;
+ }
+
+ new_mc->gmc_mech = m;
+ new_mc->gmc_mech_oid = mc->gmc_mech_oid;
+ new_mc->gmc_cred = dup_cred;
+
+ *out = new_mc;
+ } else
+ _gss_mg_error(m, *minor_status);
+
+ return major_status;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_duplicate_cred(OM_uint32 *minor_status,
+ gss_const_cred_id_t input_cred_handle,
+ gss_cred_id_t *output_cred_handle)
+{
+ struct _gss_mechanism_cred *mc;
+ struct _gss_cred *new_cred;
+ struct _gss_cred *cred = (struct _gss_cred *)input_cred_handle;
+ OM_uint32 major_status, junk;
+
+ if (input_cred_handle == GSS_C_NO_CREDENTIAL) {
+ /*
+ * "Copy" the default credential by acquiring a cred handle for the
+ * default credential's name, GSS_C_NO_NAME.
+ */
+ return gss_acquire_cred(minor_status, GSS_C_NO_NAME, GSS_C_INDEFINITE,
+ GSS_C_NO_OID_SET, GSS_C_BOTH,
+ output_cred_handle, NULL, NULL);
+ }
+
+ *output_cred_handle = GSS_C_NO_CREDENTIAL;
+ new_cred = _gss_mg_alloc_cred();
+ if (!new_cred) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ *minor_status = 0;
+ major_status = GSS_S_NO_CRED;
+
+ HEIM_TAILQ_FOREACH(mc, &cred->gc_mc, gmc_link) {
+ struct _gss_mechanism_cred *copy_mc;
+
+ major_status = copy_cred_element(minor_status, mc, &copy_mc);
+ if (major_status != GSS_S_COMPLETE)
+ break;
+
+ HEIM_TAILQ_INSERT_TAIL(&new_cred->gc_mc, copy_mc, gmc_link);
+ }
+
+ if (major_status != GSS_S_COMPLETE) {
+ gss_cred_id_t release_cred = (gss_cred_id_t)new_cred;
+ gss_release_cred(&junk, &release_cred);
+ new_cred = NULL;
+ }
+
+ *output_cred_handle = (gss_cred_id_t)new_cred;
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_duplicate_name.c b/third_party/heimdal/lib/gssapi/mech/gss_duplicate_name.c
new file mode 100644
index 0000000..e8d1e32
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_duplicate_name.c
@@ -0,0 +1,93 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_duplicate_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_duplicate_name(OM_uint32 *minor_status,
+ gss_const_name_t src_name,
+ gss_name_t *dest_name)
+{
+ OM_uint32 major_status;
+ struct _gss_name *name = (struct _gss_name *) src_name;
+ struct _gss_name *new_name;
+ struct _gss_mechanism_name *mn;
+
+ *minor_status = 0;
+ *dest_name = GSS_C_NO_NAME;
+
+ /*
+ * If this name has a value (i.e. it didn't come from
+ * gss_canonicalize_name(), we re-import the thing. Otherwise,
+ * we make copy of each mech names.
+ */
+ if (name->gn_value.value) {
+ major_status = gss_import_name(minor_status,
+ &name->gn_value, name->gn_type, dest_name);
+ if (major_status != GSS_S_COMPLETE)
+ return (major_status);
+ new_name = (struct _gss_name *) *dest_name;
+
+ HEIM_TAILQ_FOREACH(mn, &name->gn_mn, gmn_link) {
+ struct _gss_mechanism_name *mn2;
+ _gss_find_mn(minor_status, new_name,
+ mn->gmn_mech_oid, &mn2);
+ }
+ } else {
+ new_name = _gss_create_name(NULL, NULL);
+ if (!new_name) {
+ *minor_status = ENOMEM;
+ return (GSS_S_FAILURE);
+ }
+ *dest_name = (gss_name_t) new_name;
+
+ HEIM_TAILQ_FOREACH(mn, &name->gn_mn, gmn_link) {
+ struct _gss_mechanism_name *new_mn;
+
+ new_mn = malloc(sizeof(*new_mn));
+ if (!new_mn) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ new_mn->gmn_mech = mn->gmn_mech;
+ new_mn->gmn_mech_oid = mn->gmn_mech_oid;
+
+ major_status =
+ mn->gmn_mech->gm_duplicate_name(minor_status,
+ mn->gmn_name, &new_mn->gmn_name);
+ if (major_status != GSS_S_COMPLETE) {
+ free(new_mn);
+ continue;
+ }
+ HEIM_TAILQ_INSERT_TAIL(&new_name->gn_mn, new_mn, gmn_link);
+ }
+
+ }
+
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_duplicate_oid.c b/third_party/heimdal/lib/gssapi/mech/gss_duplicate_oid.c
new file mode 100644
index 0000000..29a9cf8
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_duplicate_oid.c
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_duplicate_oid (
+ OM_uint32 *minor_status,
+ gss_OID src_oid,
+ gss_OID *dest_oid
+ )
+{
+ *minor_status = 0;
+
+ if (src_oid == GSS_C_NO_OID) {
+ *dest_oid = GSS_C_NO_OID;
+ return GSS_S_COMPLETE;
+ }
+
+ return _gss_intern_oid(minor_status, src_oid, dest_oid);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_duplicate_oid_set.c b/third_party/heimdal/lib/gssapi/mech/gss_duplicate_oid_set.c
new file mode 100644
index 0000000..ae0ab8d
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_duplicate_oid_set.c
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2020 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_duplicate_oid_set(OM_uint32 *minor_status,
+ gss_OID_set src_oid_set,
+ gss_OID_set *dest_oid_set)
+{
+ OM_uint32 major_status, junk;
+ size_t i;
+
+ *dest_oid_set = GSS_C_NO_OID_SET;
+
+ major_status = gss_create_empty_oid_set(minor_status, dest_oid_set);
+
+ for (i = 0; major_status == GSS_S_COMPLETE && i < src_oid_set->count; i++)
+ major_status = gss_add_oid_set_member(minor_status,
+ &src_oid_set->elements[i],
+ dest_oid_set);
+
+ if (major_status != GSS_S_COMPLETE)
+ gss_release_oid_set(&junk, dest_oid_set);
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_encapsulate_token.c b/third_party/heimdal/lib/gssapi/mech/gss_encapsulate_token.c
new file mode 100644
index 0000000..1b1f973
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_encapsulate_token.c
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_encapsulate_token(gss_const_buffer_t input_token,
+ gss_const_OID oid,
+ gss_buffer_t output_token)
+{
+ GSSAPIContextToken ct;
+ int ret;
+ size_t size;
+
+ ret = der_get_oid (oid->elements, oid->length, &ct.thisMech, &size);
+ if (ret) {
+ _mg_buffer_zero(output_token);
+ return GSS_S_FAILURE;
+ }
+
+ ct.innerContextToken.data = input_token->value;
+ ct.innerContextToken.length = input_token->length;
+
+ ASN1_MALLOC_ENCODE(GSSAPIContextToken,
+ output_token->value, output_token->length,
+ &ct, &size, ret);
+ der_free_oid(&ct.thisMech);
+ if (ret) {
+ _mg_buffer_zero(output_token);
+ return GSS_S_FAILURE;
+ }
+ if (output_token->length != size)
+ abort();
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_export_name.c b/third_party/heimdal/lib/gssapi/mech/gss_export_name.c
new file mode 100644
index 0000000..92b7a8f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_export_name.c
@@ -0,0 +1,113 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_export_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+/**
+ * Convert a GGS-API name from internal form to contiguous string.
+ *
+ * @sa gss_import_name(), @ref internalVSmechname.
+ *
+ * @param minor_status minor status code
+ * @param input_name input name in internal name form
+ * @param exported_name output name in contiguos string form
+ *
+ * @returns a gss_error code, see gss_display_status() about printing
+ * the error code.
+ *
+ * @ingroup gssapi
+ */
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_export_name(OM_uint32 *minor_status,
+ gss_const_name_t input_name,
+ gss_buffer_t exported_name)
+{
+ struct _gss_name *name = (struct _gss_name *) input_name;
+ struct _gss_mechanism_name *mn;
+
+ _mg_buffer_zero(exported_name);
+
+ /*
+ * If this name already has any attached MNs, export the first
+ * one, otherwise export based on the first mechanism in our
+ * list.
+ */
+ mn = HEIM_TAILQ_FIRST(&name->gn_mn);
+ if (!mn) {
+ *minor_status = 0;
+ return (GSS_S_NAME_NOT_MN);
+ }
+
+ return mn->gmn_mech->gm_export_name(minor_status,
+ mn->gmn_name, exported_name);
+}
+
+OM_uint32
+gss_mg_export_name(OM_uint32 *minor_status,
+ const gss_const_OID mech,
+ const void *name,
+ size_t length,
+ gss_buffer_t exported_name)
+{
+ uint8_t *buf;
+
+ exported_name->length = 10 + length + mech->length;
+ exported_name->value = malloc(exported_name->length);
+ if (exported_name->value == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ /* TOK, MECH_OID_LEN, DER(MECH_OID), NAME_LEN, NAME */
+
+ buf = exported_name->value;
+ memcpy(buf, "\x04\x01", 2);
+ buf += 2;
+ buf[0] = ((mech->length + 2) >> 8) & 0xff;
+ buf[1] = (mech->length + 2) & 0xff;
+ buf+= 2;
+ buf[0] = 0x06;
+ buf[1] = (mech->length) & 0xFF;
+ buf+= 2;
+
+ memcpy(buf, mech->elements, mech->length);
+ buf += mech->length;
+
+ buf[0] = (length >> 24) & 0xff;
+ buf[1] = (length >> 16) & 0xff;
+ buf[2] = (length >> 8) & 0xff;
+ buf[3] = (length) & 0xff;
+ buf += 4;
+
+ memcpy (buf, name, length);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_export_name_composite.c b/third_party/heimdal/lib/gssapi/mech/gss_export_name_composite.c
new file mode 100644
index 0000000..d833ebb
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_export_name_composite.c
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2010, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_export_name_composite(OM_uint32 *minor_status,
+ gss_name_t input_name,
+ gss_buffer_t exp_composite_name)
+{
+ OM_uint32 major_status = GSS_S_UNAVAILABLE;
+ struct _gss_name *name = (struct _gss_name *) input_name;
+ struct _gss_mechanism_name *mn;
+
+ *minor_status = 0;
+ _mg_buffer_zero(exp_composite_name);
+
+ if (input_name == GSS_C_NO_NAME)
+ return GSS_S_BAD_NAME;
+
+ HEIM_TAILQ_FOREACH(mn, &name->gn_mn, gmn_link) {
+ gssapi_mech_interface m = mn->gmn_mech;
+
+ if (!m->gm_export_name_composite)
+ continue;
+
+ major_status = m->gm_export_name_composite(minor_status,
+ mn->gmn_name,
+ exp_composite_name);
+ if (GSS_ERROR(major_status))
+ _gss_mg_error(m, *minor_status);
+ else
+ break;
+ }
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_export_sec_context.c b/third_party/heimdal/lib/gssapi/mech/gss_export_sec_context.c
new file mode 100644
index 0000000..c030980
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_export_sec_context.c
@@ -0,0 +1,147 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_export_sec_context.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_export_sec_context(OM_uint32 *minor_status,
+ gss_ctx_id_t *context_handle,
+ gss_buffer_t interprocess_token)
+{
+ OM_uint32 major_status = GSS_S_FAILURE, tmp_minor;
+ krb5_storage *sp;
+ krb5_data data;
+ krb5_error_code kret;
+ struct _gss_context *ctx;
+ gssapi_mech_interface m;
+ gss_buffer_desc buf = GSS_C_EMPTY_BUFFER;
+ unsigned char verflags;
+
+ *minor_status = 0;
+
+ if (!interprocess_token)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+
+ _mg_buffer_zero(interprocess_token);
+
+ if (context_handle == NULL)
+ return GSS_S_NO_CONTEXT;
+
+ ctx = (struct _gss_context *) *context_handle;
+ if (ctx == NULL)
+ return GSS_S_NO_CONTEXT;
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ *minor_status = ENOMEM;
+ goto failure;
+ }
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_PACKED);
+
+ verflags = 0x00; /* Version 0 */
+
+ if (ctx->gc_target_len)
+ verflags |= EXPORT_CONTEXT_FLAG_ACCUMULATING;
+
+ if (ctx->gc_ctx)
+ verflags |= EXPORT_CONTEXT_FLAG_MECH_CTX;
+
+ kret = krb5_store_uint8(sp, verflags);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+
+ if (ctx->gc_target_len) {
+ _gss_mg_log(10, "gss-esc: exporting partial token %zu/%zu",
+ ctx->gc_input.length, ctx->gc_target_len);
+ kret = krb5_store_uint8(sp, ctx->gc_initial);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ kret = krb5_store_uint32(sp, ctx->gc_target_len);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+ major_status = _gss_mg_store_buffer(minor_status, sp,
+ &ctx->gc_input);
+ if (major_status != GSS_S_COMPLETE)
+ goto failure;
+ } else if (ctx->gc_ctx == GSS_C_NO_CONTEXT) {
+ gss_delete_sec_context(&tmp_minor, context_handle,
+ GSS_C_NO_BUFFER);
+ return GSS_S_NO_CONTEXT;
+ }
+
+ if (ctx->gc_ctx) {
+ m = ctx->gc_mech;
+
+ major_status = m->gm_export_sec_context(minor_status,
+ &ctx->gc_ctx, &buf);
+
+ if (major_status != GSS_S_COMPLETE) {
+ _gss_mg_error(m, *minor_status);
+ goto failure;
+ }
+
+ major_status = _gss_mg_store_oid(minor_status, sp,
+ &m->gm_mech_oid);
+ if (major_status != GSS_S_COMPLETE)
+ goto failure;
+
+ major_status = _gss_mg_store_buffer(minor_status, sp, &buf);
+ if (major_status != GSS_S_COMPLETE)
+ goto failure;
+ }
+
+ kret = krb5_storage_to_data(sp, &data);
+ if (kret) {
+ *minor_status = kret;
+ goto failure;
+ }
+
+ interprocess_token->length = data.length;
+ interprocess_token->value = data.data;
+
+ major_status = GSS_S_COMPLETE;
+
+ _gss_mg_log(1, "gss-esc: token length %zu", data.length);
+
+failure:
+ if (major_status == GSS_S_COMPLETE && *minor_status == 0)
+ gss_delete_sec_context(&tmp_minor, context_handle,
+ GSS_C_NO_BUFFER);
+ else if (*minor_status)
+ major_status = GSS_S_FAILURE;
+
+ _gss_secure_release_buffer(minor_status, &buf);
+ krb5_storage_free(sp);
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_get_mic.c b/third_party/heimdal/lib/gssapi/mech/gss_get_mic.c
new file mode 100644
index 0000000..8663053
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_get_mic.c
@@ -0,0 +1,51 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_get_mic.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_get_mic(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ gss_qop_t qop_req,
+ const gss_buffer_t message_buffer,
+ gss_buffer_t message_token)
+{
+ struct _gss_context *ctx = (struct _gss_context *) context_handle;
+ gssapi_mech_interface m;
+
+ _mg_buffer_zero(message_token);
+ if (ctx == NULL) {
+ *minor_status = 0;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ m = ctx->gc_mech;
+
+ return (m->gm_get_mic(minor_status, ctx->gc_ctx, qop_req,
+ message_buffer, message_token));
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_get_name_attribute.c b/third_party/heimdal/lib/gssapi/mech/gss_get_name_attribute.c
new file mode 100644
index 0000000..1b7bee5
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_get_name_attribute.c
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2010, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_get_name_attribute(OM_uint32 *minor_status,
+ gss_name_t input_name,
+ gss_buffer_t attr,
+ int *authenticated,
+ int *complete,
+ gss_buffer_t value,
+ gss_buffer_t display_value,
+ int *more)
+{
+ OM_uint32 major_status = GSS_S_UNAVAILABLE;
+ struct _gss_name *name = (struct _gss_name *) input_name;
+ struct _gss_mechanism_name *mn;
+
+ *minor_status = 0;
+ if (authenticated != NULL)
+ *authenticated = 0;
+ if (complete != NULL)
+ *complete = 0;
+ _mg_buffer_zero(value);
+ _mg_buffer_zero(display_value);
+
+ if (input_name == GSS_C_NO_NAME)
+ return GSS_S_BAD_NAME;
+
+ _gss_mg_check_name(input_name);
+
+ HEIM_TAILQ_FOREACH(mn, &name->gn_mn, gmn_link) {
+ gssapi_mech_interface m = mn->gmn_mech;
+
+ if (!m->gm_get_name_attribute)
+ continue;
+
+ major_status = m->gm_get_name_attribute(minor_status,
+ mn->gmn_name,
+ attr,
+ authenticated,
+ complete,
+ value,
+ display_value,
+ more);
+ if (GSS_ERROR(major_status))
+ _gss_mg_error(m, *minor_status);
+ else
+ break;
+ }
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_get_neg_mechs.c b/third_party/heimdal/lib/gssapi/mech/gss_get_neg_mechs.c
new file mode 100644
index 0000000..cbc3786
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_get_neg_mechs.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2018, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_get_neg_mechs(OM_uint32 *minor_status,
+ gss_const_cred_id_t cred_handle,
+ gss_OID_set *mechs)
+{
+ struct _gss_cred *cred = (struct _gss_cred *)cred_handle;
+
+ if (minor_status == NULL)
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+
+ *minor_status = 0;
+
+ if (mechs == NULL)
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+
+ if (cred->gc_neg_mechs != GSS_C_NO_OID_SET)
+ return gss_duplicate_oid_set(minor_status, cred->gc_neg_mechs, mechs);
+
+ return GSS_S_UNAVAILABLE;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_import_name.c b/third_party/heimdal/lib/gssapi/mech/gss_import_name.c
new file mode 100644
index 0000000..54930bf
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_import_name.c
@@ -0,0 +1,323 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_import_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+static OM_uint32
+_gss_import_export_name(OM_uint32 *minor_status,
+ const gss_buffer_t input_name_buffer,
+ const gss_OID name_type,
+ gss_name_t *output_name)
+{
+ OM_uint32 major_status;
+ unsigned char *p = input_name_buffer->value;
+ size_t len = input_name_buffer->length;
+ size_t t;
+ gss_OID_desc mech_oid;
+ gssapi_mech_interface m;
+ struct _gss_name *name;
+ gss_name_t new_canonical_name;
+ int composite = 0;
+
+ *minor_status = 0;
+ *output_name = 0;
+
+ /*
+ * Make sure that TOK_ID is {4, 1}.
+ */
+ if (len < 2)
+ return (GSS_S_BAD_NAME);
+ if (p[0] != 4)
+ return (GSS_S_BAD_NAME);
+ switch (p[1]) {
+ case 1: /* non-composite name */
+ break;
+ case 2: /* composite name */
+ composite = 1;
+ break;
+ default:
+ return (GSS_S_BAD_NAME);
+ }
+ p += 2;
+ len -= 2;
+
+ /*
+ * If the name token is a composite token (TOK_ID 0x04 0x02) then per
+ * RFC6680 everything after that is implementation-specific. This
+ * mech-glue is pluggable however, so we need the format of the rest of
+ * the header to be stable, otherwise we couldn't reliably determine
+ * what mechanism the token is for and we'd have to try all of them.
+ *
+ * So... we keep the same format for the exported composite name token
+ * as for normal exported name tokens (see RFC2743, section 3.2), with
+ * the TOK_ID 0x04 0x02, but only up to the mechanism OID. We don't
+ * enforce that there be a NAME_LEN in the exported composite name
+ * token, or that it match the length of the remainder of the token.
+ *
+ * FYI, at least one out-of-tree mechanism implements exported
+ * composite name tokens as the same as exported name tokens with
+ * attributes appended and the NAME_LEN not modified to match.
+ */
+
+ /*
+ * Get the mech length and the name length and sanity
+ * check the size of of the buffer.
+ */
+ if (len < 2)
+ return (GSS_S_BAD_NAME);
+ t = (p[0] << 8) + p[1];
+ p += 2;
+ len -= 2;
+
+ /*
+ * Check the DER encoded OID to make sure it agrees with the
+ * length we just decoded.
+ */
+ if (p[0] != 6) /* 6=OID */
+ return (GSS_S_BAD_NAME);
+ p++;
+ len--;
+ t--;
+ if (p[0] & 0x80) {
+ int digits = p[0];
+ p++;
+ len--;
+ t--;
+ mech_oid.length = 0;
+ while (digits--) {
+ mech_oid.length = (mech_oid.length << 8) | p[0];
+ p++;
+ len--;
+ t--;
+ }
+ } else {
+ mech_oid.length = p[0];
+ p++;
+ len--;
+ t--;
+ }
+ if (mech_oid.length != t)
+ return (GSS_S_BAD_NAME);
+
+ mech_oid.elements = p;
+
+ if (!composite) {
+ if (len < t + 4)
+ return (GSS_S_BAD_NAME);
+ p += t;
+ len -= t;
+
+ t = ((unsigned long)p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
+ /* p += 4; // we're done using `p' now */
+ len -= 4;
+
+ if (len != t)
+ return (GSS_S_BAD_NAME);
+ }
+
+ m = __gss_get_mechanism(&mech_oid);
+ if (!m || !m->gm_import_name)
+ return (GSS_S_BAD_MECH);
+
+ /*
+ * Ask the mechanism to import the name.
+ */
+ major_status = m->gm_import_name(minor_status,
+ input_name_buffer, name_type, &new_canonical_name);
+ if (major_status != GSS_S_COMPLETE) {
+ _gss_mg_error(m, *minor_status);
+ return major_status;
+ }
+
+ /*
+ * Now we make a new name and mark it as an MN.
+ */
+ name = _gss_create_name(new_canonical_name, m);
+ if (!name) {
+ m->gm_release_name(minor_status, &new_canonical_name);
+ return (GSS_S_FAILURE);
+ }
+
+ *output_name = (gss_name_t) name;
+
+ *minor_status = 0;
+ return (GSS_S_COMPLETE);
+}
+
+/**
+ * Convert a GGS-API name from contiguous string to internal form.
+ *
+ * Type of name and their format:
+ * - GSS_C_NO_OID
+ * - GSS_C_NT_USER_NAME
+ * - GSS_C_NT_HOSTBASED_SERVICE
+ * - GSS_C_NT_EXPORT_NAME
+ * - GSS_C_NT_COMPOSITE_EXPORT
+ * - GSS_C_NT_ANONYMOUS
+ * - GSS_KRB5_NT_PRINCIPAL_NAME
+ *
+ * @sa gss_export_name(), @ref internalVSmechname.
+ *
+ * @param minor_status minor status code
+ * @param input_name_buffer import name buffer
+ * @param input_name_type type of the import name buffer
+ * @param output_name the resulting type, release with
+ * gss_release_name(), independent of input_name
+ *
+ * @returns a gss_error code, see gss_display_status() about printing
+ * the error code.
+ *
+ * @ingroup gssapi
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_import_name(OM_uint32 *minor_status,
+ const gss_buffer_t input_name_buffer,
+ const gss_OID input_name_type,
+ gss_name_t *output_name)
+{
+ struct _gss_mechanism_name *mn;
+ gss_OID name_type = input_name_type;
+ OM_uint32 major_status, ms;
+ struct _gss_name *name;
+ struct _gss_mech_switch *m;
+ gss_name_t rname;
+
+ if (input_name_buffer == GSS_C_NO_BUFFER)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+ if (output_name == NULL)
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+
+ *output_name = GSS_C_NO_NAME;
+
+ /* Allow empty names since that's valid (ANONYMOUS for example) */
+
+ _gss_load_mech();
+
+ /*
+ * If this is an exported name, we need to parse it to find
+ * the mechanism and then import it as an MN. See RFC 2743
+ * section 3.2 for a description of the format.
+ */
+ if (gss_oid_equal(name_type, GSS_C_NT_EXPORT_NAME) ||
+ gss_oid_equal(name_type, GSS_C_NT_COMPOSITE_EXPORT)) {
+ return _gss_import_export_name(minor_status, input_name_buffer,
+ name_type, output_name);
+ }
+
+
+ *minor_status = 0;
+ name = _gss_create_name(NULL, NULL);
+ if (!name) {
+ *minor_status = ENOMEM;
+ return (GSS_S_FAILURE);
+ }
+
+ if (name_type != GSS_C_NO_OID) {
+ major_status = _gss_intern_oid(minor_status,
+ name_type, &name->gn_type);
+ if (major_status) {
+ rname = (gss_name_t)name;
+ gss_release_name(&ms, (gss_name_t *)&rname);
+ return (GSS_S_FAILURE);
+ }
+ } else
+ name->gn_type = GSS_C_NO_OID;
+
+ major_status = _gss_copy_buffer(minor_status,
+ input_name_buffer, &name->gn_value);
+ if (major_status)
+ goto out;
+
+ /*
+ * Walk over the mechs and import the name into a mech name
+ * for those supported this nametype.
+ */
+
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ int present = 0;
+
+ if ((m->gm_mech.gm_flags & GM_USE_MG_NAME))
+ continue;
+
+ if (name_type != GSS_C_NO_OID) {
+ major_status = gss_test_oid_set_member(minor_status,
+ name_type, m->gm_name_types, &present);
+
+ if (GSS_ERROR(major_status) || present == 0)
+ continue;
+ }
+
+ mn = malloc(sizeof(struct _gss_mechanism_name));
+ if (!mn) {
+ *minor_status = ENOMEM;
+ major_status = GSS_S_FAILURE;
+ goto out;
+ }
+
+ major_status = (*m->gm_mech.gm_import_name)(minor_status,
+ &name->gn_value,
+ name->gn_type,
+ &mn->gmn_name);
+ if (major_status != GSS_S_COMPLETE) {
+ _gss_mg_error(&m->gm_mech, *minor_status);
+ free(mn);
+ /**
+ * If we failed to import the name in a mechanism, it
+ * will be ignored as long as its possible to import
+ * name in some other mechanism. We will catch the
+ * failure later though in gss_init_sec_context() or
+ * another function.
+ */
+ continue;
+ }
+
+ mn->gmn_mech = &m->gm_mech;
+ mn->gmn_mech_oid = m->gm_mech_oid;
+ HEIM_TAILQ_INSERT_TAIL(&name->gn_mn, mn, gmn_link);
+ }
+
+ /*
+ * If we can't find a mn for the name, bail out already here.
+ */
+
+ mn = HEIM_TAILQ_FIRST(&name->gn_mn);
+ if (!mn) {
+ *minor_status = 0;
+ major_status = GSS_S_NAME_NOT_MN;
+ goto out;
+ }
+
+ *output_name = (gss_name_t) name;
+ return (GSS_S_COMPLETE);
+
+ out:
+ rname = (gss_name_t)name;
+ gss_release_name(&ms, &rname);
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_import_sec_context.c b/third_party/heimdal/lib/gssapi/mech/gss_import_sec_context.c
new file mode 100644
index 0000000..39b717e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_import_sec_context.c
@@ -0,0 +1,147 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_import_sec_context.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_import_sec_context(OM_uint32 *minor_status,
+ const gss_buffer_t interprocess_token,
+ gss_ctx_id_t *context_handle)
+{
+ OM_uint32 ret = GSS_S_FAILURE, tmp_minor;
+ krb5_storage *sp;
+ gssapi_mech_interface m;
+ struct _gss_context *ctx = NULL;
+ gss_buffer_desc buf = GSS_C_EMPTY_BUFFER;
+ unsigned char verflags;
+
+ _gss_mg_log(10, "gss-isc called");
+
+ if (!context_handle) {
+ *minor_status = EFAULT;
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+ }
+
+ *minor_status = 0;
+ *context_handle = GSS_C_NO_CONTEXT;
+
+ sp = krb5_storage_from_mem(interprocess_token->value,
+ interprocess_token->length);
+ if (!sp) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_PACKED);
+
+ ctx = calloc(1, sizeof(struct _gss_context));
+ if (!ctx) {
+ *minor_status = ENOMEM;
+ goto failure;
+ }
+
+ if (krb5_ret_uint8(sp, &verflags))
+ goto failure;
+
+ if ((verflags & EXPORT_CONTEXT_VERSION_MASK) != 0) {
+ _gss_mg_log(10, "gss-isc failed, token version %d not recognised",
+ (int)(verflags & EXPORT_CONTEXT_VERSION_MASK));
+ /* We don't recognise the version */
+ goto failure;
+ }
+
+ if (verflags & EXPORT_CONTEXT_FLAG_ACCUMULATING) {
+ uint32_t target_len;
+
+ if (krb5_ret_uint8(sp, &ctx->gc_initial))
+ goto failure;
+
+ if (krb5_ret_uint32(sp, &target_len))
+ goto failure;
+
+ ret = _gss_mg_ret_buffer(minor_status, sp, &buf);
+ if (ret != GSS_S_COMPLETE)
+ goto failure;
+
+ ctx->gc_free_this = ctx->gc_input.value = calloc(target_len, 1);
+ if (ctx->gc_input.value == NULL)
+ goto failure;
+
+ ctx->gc_target_len = target_len;
+ ctx->gc_input.length = buf.length;
+ if (buf.value)
+ memcpy(ctx->gc_input.value, buf.value, buf.length);
+
+ gss_release_buffer(&tmp_minor, &buf);
+ }
+
+ if (verflags & EXPORT_CONTEXT_FLAG_MECH_CTX) {
+ gss_OID mech_oid;
+
+ ret = _gss_mg_ret_oid(minor_status, sp, &mech_oid);
+ if (ret != GSS_S_COMPLETE)
+ goto failure;
+
+ if (mech_oid == GSS_C_NO_OID) {
+ ret = GSS_S_BAD_MECH;
+ goto failure;
+ }
+
+ m = __gss_get_mechanism(mech_oid);
+ if (m == NULL) {
+ ret = GSS_S_DEFECTIVE_TOKEN;
+ goto failure;
+ }
+ ctx->gc_mech = m;
+
+ ret = _gss_mg_ret_buffer(minor_status, sp, &buf);
+ if (ret != GSS_S_COMPLETE)
+ goto failure;
+
+ if (buf.value == NULL) {
+ ret = GSS_S_DEFECTIVE_TOKEN;
+ goto failure;
+ }
+
+ ret = m->gm_import_sec_context(minor_status, &buf, &ctx->gc_ctx);
+ if (ret != GSS_S_COMPLETE) {
+ _gss_mg_error(m, *minor_status);
+ goto failure;
+ }
+ }
+
+ *context_handle = (gss_ctx_id_t) ctx;
+ ctx = NULL;
+
+ ret = GSS_S_COMPLETE;
+
+failure:
+ free(ctx);
+ krb5_storage_free(sp);
+ _gss_secure_release_buffer(&tmp_minor, &buf);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_indicate_mechs.c b/third_party/heimdal/lib/gssapi/mech/gss_indicate_mechs.c
new file mode 100644
index 0000000..9eef62e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_indicate_mechs.c
@@ -0,0 +1,74 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_indicate_mechs.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_indicate_mechs(OM_uint32 *minor_status,
+ gss_OID_set *mech_set)
+{
+ struct _gss_mech_switch *m;
+ OM_uint32 major_status, junk;
+ gss_OID_set set;
+ size_t i;
+
+ _gss_load_mech();
+
+ major_status = gss_create_empty_oid_set(minor_status, mech_set);
+ if (major_status)
+ return (major_status);
+
+ /* XXX We ignore ENOMEM from gss_add_oid_set_member() */
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ if (m->gm_mech.gm_indicate_mechs) {
+ major_status = m->gm_mech.gm_indicate_mechs(
+ minor_status, &set);
+ if (major_status)
+ continue;
+ major_status = GSS_S_COMPLETE;
+ for (i = 0; i < set->count; i++) {
+ major_status = gss_add_oid_set_member(
+ minor_status, &set->elements[i], mech_set);
+ if (major_status)
+ break;
+ }
+ gss_release_oid_set(minor_status, &set);
+ } else {
+ major_status = gss_add_oid_set_member(
+ minor_status, m->gm_mech_oid, mech_set);
+ }
+ if (major_status)
+ break;
+ }
+
+ if (major_status)
+ gss_release_oid_set(&junk, mech_set);
+
+ *minor_status = 0;
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_init_sec_context.c b/third_party/heimdal/lib/gssapi/mech/gss_init_sec_context.c
new file mode 100644
index 0000000..6d28938
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_init_sec_context.c
@@ -0,0 +1,281 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_init_sec_context.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+gss_cred_id_t
+_gss_mg_find_mech_cred(
+ gss_const_cred_id_t cred_handle,
+ gss_const_OID mech_type)
+{
+ struct _gss_cred *cred = (struct _gss_cred *)cred_handle;
+ struct _gss_mechanism_cred *mc;
+
+ if (cred == NULL)
+ return GSS_C_NO_CREDENTIAL;
+
+ HEIM_TAILQ_FOREACH(mc, &cred->gc_mc, gmc_link) {
+ if (gss_oid_equal(mech_type, mc->gmc_mech_oid))
+ return mc->gmc_cred;
+ }
+ return GSS_C_NO_CREDENTIAL;
+}
+
+static void
+log_init_sec_context(struct _gss_context *ctx,
+ struct _gss_name *target,
+ OM_uint32 req_flags,
+ struct _gss_cred *cred,
+ gss_OID mech_type,
+ gss_buffer_t input_token)
+{
+ gssapi_mech_interface m;
+
+ if (ctx)
+ m = ctx->gc_mech;
+ else
+ m = __gss_get_mechanism(mech_type);
+ if (m == NULL)
+ return;
+
+ mech_type = &m->gm_mech_oid;
+
+ _gss_mg_log(1, "gss_isc: %s %sfirst flags %08x, %s cred, %stoken",
+ m->gm_name,
+ (ctx == NULL) ? "" : "not ",
+ req_flags,
+ (cred != NULL) ? "specific" : "default",
+ (input_token != NULL && input_token->length) ? "" : "no ");
+
+ _gss_mg_log_cred(1, cred, "gss_isc cred");
+
+ /* print target name */
+ _gss_mg_log_name(1, target, mech_type, "gss_isc: target");
+}
+
+/**
+ * As the initiator build a context with an acceptor.
+ *
+ * Returns in the major
+ * - GSS_S_COMPLETE - if the context if build
+ * - GSS_S_CONTINUE_NEEDED - if the caller needs to continue another
+ * round of gss_i nit_sec_context
+ * - error code - any other error code
+ *
+ * @param minor_status minor status code.
+ *
+ * @param initiator_cred_handle the credential to use when building
+ * the context, if GSS_C_NO_CREDENTIAL is passed, the default
+ * credential for the mechanism will be used.
+ *
+ * @param context_handle a pointer to a context handle, will be
+ * returned as long as there is not an error.
+ *
+ * @param target_name the target name of acceptor, created using
+ * gss_import_name(). The name is can be of any name types the
+ * mechanism supports, check supported name types with
+ * gss_inquire_names_for_mech().
+ *
+ * @param input_mech_type mechanism type to use, if GSS_C_NO_OID is
+ * used, Kerberos (GSS_KRB5_MECHANISM) will be tried. Other
+ * available mechanism are listed in the @ref gssapi_mechs_intro
+ * section.
+ *
+ * @param req_flags flags using when building the context, see @ref
+ * gssapi_context_flags
+ *
+ * @param time_req time requested this context should be valid in
+ * seconds, common used value is GSS_C_INDEFINITE
+ *
+ * @param input_chan_bindings Channel bindings used, if not exepected
+ * otherwise, used GSS_C_NO_CHANNEL_BINDINGS
+ *
+ * @param input_token input token sent from the acceptor, for the
+ * initial packet the buffer of { NULL, 0 } should be used.
+ *
+ * @param actual_mech_type the actual mech used, MUST NOT be freed
+ * since it pointing to static memory.
+ *
+ * @param output_token if there is an output token, regardless of
+ * complete, continue_needed, or error it should be sent to the
+ * acceptor
+ *
+ * @param ret_flags return what flags was negotitated, caller should
+ * check if they are accetable. For example, if
+ * GSS_C_MUTUAL_FLAG was negotiated with the acceptor or not.
+ *
+ * @param time_rec amount of time this context is valid for
+ *
+ * @returns a gss_error code, see gss_display_status() about printing
+ * the error code.
+ *
+ * @ingroup gssapi
+ */
+
+
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_init_sec_context(OM_uint32 * minor_status,
+ gss_const_cred_id_t initiator_cred_handle,
+ gss_ctx_id_t * context_handle,
+ gss_const_name_t target_name,
+ const gss_OID input_mech_type,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ const gss_buffer_t input_token,
+ gss_OID * actual_mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec)
+{
+ OM_uint32 major_status;
+ gssapi_mech_interface m;
+ gss_const_name_t mn_inner = GSS_C_NO_NAME;
+ struct _gss_name *name = (struct _gss_name *) target_name;
+ struct _gss_mechanism_name *mn;
+ struct _gss_context *ctx = (struct _gss_context *) *context_handle;
+ gss_const_cred_id_t cred_handle;
+ int allocated_ctx;
+ gss_OID mech_type = input_mech_type;
+
+ *minor_status = 0;
+
+ _mg_buffer_zero(output_token);
+ if (actual_mech_type)
+ *actual_mech_type = GSS_C_NO_OID;
+ if (ret_flags)
+ *ret_flags = 0;
+ if (time_rec)
+ *time_rec = 0;
+
+ if (mech_type == GSS_C_NO_OID)
+ mech_type = GSS_KRB5_MECHANISM;
+
+ _gss_mg_check_name(target_name);
+
+ if (_gss_mg_log_level(1))
+ log_init_sec_context(ctx, name, req_flags,
+ (struct _gss_cred *)initiator_cred_handle,
+ input_mech_type, input_token);
+
+ /*
+ * If we haven't allocated a context yet, do so now and lookup
+ * the mechanism switch table. If we have one already, make
+ * sure we use the same mechanism switch as before.
+ */
+ if (!ctx) {
+ ctx = malloc(sizeof(struct _gss_context));
+ if (!ctx) {
+ *minor_status = ENOMEM;
+ return (GSS_S_FAILURE);
+ }
+ memset(ctx, 0, sizeof(struct _gss_context));
+ m = ctx->gc_mech = __gss_get_mechanism(mech_type);
+ if (!m) {
+ free(ctx);
+ *minor_status = 0;
+ gss_mg_set_error_string(mech_type, GSS_S_BAD_MECH,
+ *minor_status,
+ "Unsupported mechanism requested");
+ return (GSS_S_BAD_MECH);
+ }
+ allocated_ctx = 1;
+ } else {
+ m = ctx->gc_mech;
+ mech_type = &ctx->gc_mech->gm_mech_oid;
+ allocated_ctx = 0;
+ }
+
+ /*
+ * Find the MN for this mechanism.
+ */
+ if ((m->gm_flags & GM_USE_MG_NAME)) {
+ mn_inner = target_name;
+ } else {
+ major_status = _gss_find_mn(minor_status, name, mech_type, &mn);
+ if (major_status != GSS_S_COMPLETE) {
+ if (allocated_ctx)
+ free(ctx);
+ return major_status;
+ }
+ if (mn)
+ mn_inner = mn->gmn_name;
+ }
+
+ /*
+ * If we have a cred, find the cred for this mechanism.
+ */
+ if (m->gm_flags & GM_USE_MG_CRED)
+ cred_handle = initiator_cred_handle;
+ else
+ cred_handle = _gss_mg_find_mech_cred(initiator_cred_handle, mech_type);
+
+ if (initiator_cred_handle != GSS_C_NO_CREDENTIAL &&
+ cred_handle == NULL) {
+ *minor_status = 0;
+ if (allocated_ctx)
+ free(ctx);
+ gss_mg_set_error_string(mech_type, GSS_S_UNAVAILABLE,
+ *minor_status,
+ "Credential for the requested mechanism "
+ "not found in credential handle");
+ return GSS_S_UNAVAILABLE;
+ }
+
+ major_status = m->gm_init_sec_context(minor_status,
+ cred_handle,
+ &ctx->gc_ctx,
+ mn_inner,
+ mech_type,
+ req_flags,
+ time_req,
+ input_chan_bindings,
+ input_token,
+ actual_mech_type,
+ output_token,
+ ret_flags,
+ time_rec);
+
+ if (major_status != GSS_S_COMPLETE
+ && major_status != GSS_S_CONTINUE_NEEDED) {
+ if (allocated_ctx)
+ free(ctx);
+ _mg_buffer_zero(output_token);
+ _gss_mg_error(m, *minor_status);
+ } else {
+ *context_handle = (gss_ctx_id_t) ctx;
+ }
+
+ _gss_mg_log(1, "gss_isc: %s maj_stat: %d/%d",
+ m->gm_name, (int)major_status, (int)*minor_status);
+
+ return (major_status);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_inquire_context.c b/third_party/heimdal/lib/gssapi/mech/gss_inquire_context.c
new file mode 100644
index 0000000..6140696
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_inquire_context.c
@@ -0,0 +1,120 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_inquire_context.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_context(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ gss_name_t *src_name,
+ gss_name_t *targ_name,
+ OM_uint32 *lifetime_rec,
+ gss_OID *mech_type,
+ OM_uint32 *ctx_flags,
+ int *locally_initiated,
+ int *xopen)
+{
+ OM_uint32 major_status;
+ struct _gss_context *ctx = (struct _gss_context *) context_handle;
+ gssapi_mech_interface m;
+ struct _gss_name *name;
+ gss_name_t src_mn, targ_mn;
+
+ if (locally_initiated)
+ *locally_initiated = 0;
+ if (xopen)
+ *xopen = 0;
+ if (lifetime_rec)
+ *lifetime_rec = 0;
+
+ if (src_name)
+ *src_name = GSS_C_NO_NAME;
+ if (targ_name)
+ *targ_name = GSS_C_NO_NAME;
+ if (mech_type)
+ *mech_type = GSS_C_NO_OID;
+ src_mn = targ_mn = GSS_C_NO_NAME;
+
+ if (ctx == NULL || ctx->gc_ctx == NULL) {
+ *minor_status = 0;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ m = ctx->gc_mech;
+
+ major_status = m->gm_inquire_context(minor_status,
+ ctx->gc_ctx,
+ src_name ? &src_mn : NULL,
+ targ_name ? &targ_mn : NULL,
+ lifetime_rec,
+ mech_type,
+ ctx_flags,
+ locally_initiated,
+ xopen);
+
+ if (major_status != GSS_S_COMPLETE) {
+ _gss_mg_error(m, *minor_status);
+ return (major_status);
+ }
+
+ if (src_name && (m->gm_flags & GM_USE_MG_NAME)) {
+ *src_name = src_mn;
+ src_mn = GSS_C_NO_NAME;
+ } else if (src_name && src_mn) {
+ /* _gss_create_name() consumes `src_mn' on success */
+ name = _gss_create_name(src_mn, m);
+ if (!name) {
+ if (mech_type)
+ *mech_type = GSS_C_NO_OID;
+ m->gm_release_name(minor_status, &src_mn);
+ *minor_status = 0;
+ return (GSS_S_FAILURE);
+ }
+ *src_name = (gss_name_t) name;
+ src_mn = GSS_C_NO_NAME;
+ }
+
+ if (targ_name && (m->gm_flags & GM_USE_MG_NAME)) {
+ *targ_name = targ_mn;
+ } else if (targ_name && targ_mn) {
+ name = _gss_create_name(targ_mn, m);
+ if (!name) {
+ if (mech_type)
+ *mech_type = GSS_C_NO_OID;
+ if (src_name)
+ gss_release_name(minor_status, src_name);
+ m->gm_release_name(minor_status, &targ_mn);
+ *minor_status = 0;
+ return (GSS_S_FAILURE);
+ }
+ *targ_name = (gss_name_t) name;
+ targ_mn = GSS_C_NO_NAME;
+ }
+
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_inquire_cred.c b/third_party/heimdal/lib/gssapi/mech/gss_inquire_cred.c
new file mode 100644
index 0000000..305cae2
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_inquire_cred.c
@@ -0,0 +1,218 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_inquire_cred.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+#define AUSAGE 1
+#define IUSAGE 2
+
+static void
+updateusage(gss_cred_usage_t usage, int *usagemask)
+{
+ if (usage == GSS_C_BOTH)
+ *usagemask |= AUSAGE | IUSAGE;
+ else if (usage == GSS_C_ACCEPT)
+ *usagemask |= AUSAGE;
+ else if (usage == GSS_C_INITIATE)
+ *usagemask |= IUSAGE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_cred(OM_uint32 *minor_status,
+ gss_const_cred_id_t cred_handle,
+ gss_name_t *name_ret,
+ OM_uint32 *lifetime,
+ gss_cred_usage_t *cred_usage,
+ gss_OID_set *mechanisms)
+{
+ OM_uint32 major_status;
+ struct _gss_mech_switch *m;
+ struct _gss_cred *cred = (struct _gss_cred *) cred_handle;
+ struct _gss_name *name;
+ struct _gss_mechanism_name *mn;
+ OM_uint32 min_lifetime;
+ int found = FALSE;
+ int usagemask = 0;
+ gss_cred_usage_t usage;
+
+ _gss_load_mech();
+
+ *minor_status = 0;
+ if (name_ret)
+ *name_ret = GSS_C_NO_NAME;
+ if (lifetime)
+ *lifetime = 0;
+ if (cred_usage)
+ *cred_usage = 0;
+ if (mechanisms)
+ *mechanisms = GSS_C_NO_OID_SET;
+
+ if (name_ret) {
+ name = _gss_create_name(NULL, NULL);
+ if (name == NULL) {
+ *minor_status = ENOMEM;
+ return (GSS_S_FAILURE);
+ }
+ } else {
+ name = NULL;
+ }
+
+ if (mechanisms) {
+ major_status = gss_create_empty_oid_set(minor_status,
+ mechanisms);
+ if (major_status) {
+ if (name) free(name);
+ return (major_status);
+ }
+ }
+
+ min_lifetime = GSS_C_INDEFINITE;
+ if (cred) {
+ struct _gss_mechanism_cred *mc;
+
+ HEIM_TAILQ_FOREACH(mc, &cred->gc_mc, gmc_link) {
+ gss_name_t mc_name = GSS_C_NO_NAME;
+ OM_uint32 mc_lifetime = GSS_C_INDEFINITE;
+
+ heim_assert((mc->gmc_mech->gm_flags & GM_USE_MG_CRED) == 0,
+ "should not have mech creds for GM_USE_MG_CRED mechs");
+
+ if (mc->gmc_mech->gm_inquire_cred == NULL)
+ continue;
+
+ major_status = mc->gmc_mech->gm_inquire_cred(minor_status,
+ mc->gmc_cred, &mc_name, &mc_lifetime, &usage, NULL);
+ if (major_status)
+ continue;
+
+ updateusage(usage, &usagemask);
+ if (name) {
+ mn = malloc(sizeof(struct _gss_mechanism_name));
+ if (!mn) {
+ mc->gmc_mech->gm_release_name(minor_status,
+ &mc_name);
+ continue;
+ }
+ mn->gmn_mech = mc->gmc_mech;
+ mn->gmn_mech_oid = mc->gmc_mech_oid;
+ mn->gmn_name = mc_name;
+ HEIM_TAILQ_INSERT_TAIL(&name->gn_mn, mn, gmn_link);
+ } else {
+ mc->gmc_mech->gm_release_name(minor_status,
+ &mc_name);
+ }
+
+ if (mc_lifetime < min_lifetime)
+ min_lifetime = mc_lifetime;
+
+ if (mechanisms)
+ gss_add_oid_set_member(minor_status,
+ mc->gmc_mech_oid, mechanisms);
+ found = TRUE;
+ }
+ } else {
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ gss_name_t mc_name;
+ OM_uint32 mc_lifetime;
+
+ if (m->gm_mech.gm_inquire_cred == NULL ||
+ (m->gm_mech.gm_flags & GM_USE_MG_CRED))
+ continue;
+
+ major_status = m->gm_mech.gm_inquire_cred(minor_status,
+ GSS_C_NO_CREDENTIAL, &mc_name, &mc_lifetime,
+ &usage, NULL);
+ if (major_status)
+ continue;
+
+ updateusage(usage, &usagemask);
+ if (name && mc_name) {
+ mn = malloc(
+ sizeof(struct _gss_mechanism_name));
+ if (!mn) {
+ m->gm_mech.gm_release_name(
+ minor_status, &mc_name);
+ continue;
+ }
+ mn->gmn_mech = &m->gm_mech;
+ mn->gmn_mech_oid = m->gm_mech_oid;
+ mn->gmn_name = mc_name;
+ HEIM_TAILQ_INSERT_TAIL(&name->gn_mn, mn, gmn_link);
+ } else if (mc_name) {
+ m->gm_mech.gm_release_name(minor_status,
+ &mc_name);
+ }
+
+ if (mc_lifetime < min_lifetime)
+ min_lifetime = mc_lifetime;
+
+ if (mechanisms)
+ gss_add_oid_set_member(minor_status,
+ m->gm_mech_oid, mechanisms);
+ found = TRUE;
+ }
+ }
+
+ if (found && mechanisms) {
+ /* GM_USE_MG_CRED mechs (SPNEGO) always can be used */
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ if ((m->gm_mech.gm_flags & GM_USE_MG_CRED) == 0)
+ continue;
+
+ gss_add_oid_set_member(minor_status,
+ m->gm_mech_oid, mechanisms);
+ }
+ }
+
+ if (found == FALSE || min_lifetime == 0) {
+ gss_name_t n = (gss_name_t)name;
+ if (n)
+ gss_release_name(minor_status, &n);
+ gss_release_oid_set(minor_status, mechanisms);
+ *minor_status = 0;
+ if (min_lifetime == 0)
+ return (GSS_S_CREDENTIALS_EXPIRED);
+
+ return (GSS_S_NO_CRED);
+ }
+
+ *minor_status = 0;
+ if (name_ret)
+ *name_ret = (gss_name_t) name;
+ if (lifetime)
+ *lifetime = min_lifetime;
+ if (cred_usage) {
+ if ((usagemask & (AUSAGE|IUSAGE)) == (AUSAGE|IUSAGE))
+ *cred_usage = GSS_C_BOTH;
+ else if (usagemask & IUSAGE)
+ *cred_usage = GSS_C_INITIATE;
+ else if (usagemask & AUSAGE)
+ *cred_usage = GSS_C_ACCEPT;
+ }
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_inquire_cred_by_mech.c b/third_party/heimdal/lib/gssapi/mech/gss_inquire_cred_by_mech.c
new file mode 100644
index 0000000..10ba9b7
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_inquire_cred_by_mech.c
@@ -0,0 +1,92 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_inquire_cred_by_mech.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_cred_by_mech(OM_uint32 *minor_status,
+ gss_const_cred_id_t cred_handle,
+ const gss_OID mech_type,
+ gss_name_t *cred_name,
+ OM_uint32 *initiator_lifetime,
+ OM_uint32 *acceptor_lifetime,
+ gss_cred_usage_t *cred_usage)
+{
+ OM_uint32 major_status;
+ gssapi_mech_interface m;
+ struct _gss_mechanism_cred *mcp;
+ gss_cred_id_t mc;
+ gss_name_t mn;
+ struct _gss_name *name;
+
+ *minor_status = 0;
+ if (cred_name)
+ *cred_name = GSS_C_NO_NAME;
+ if (initiator_lifetime)
+ *initiator_lifetime = 0;
+ if (acceptor_lifetime)
+ *acceptor_lifetime = 0;
+ if (cred_usage)
+ *cred_usage = 0;
+
+ m = __gss_get_mechanism(mech_type);
+ if (m == NULL || m->gm_inquire_cred_by_mech == NULL)
+ return (GSS_S_NO_CRED);
+
+ if (cred_handle != GSS_C_NO_CREDENTIAL) {
+ struct _gss_cred *cred = (struct _gss_cred *) cred_handle;
+ HEIM_TAILQ_FOREACH(mcp, &cred->gc_mc, gmc_link)
+ if (mcp->gmc_mech == m)
+ break;
+ if (!mcp)
+ return (GSS_S_NO_CRED);
+ mc = mcp->gmc_cred;
+ } else {
+ mc = GSS_C_NO_CREDENTIAL;
+ }
+
+ major_status = m->gm_inquire_cred_by_mech(minor_status, mc, mech_type,
+ &mn, initiator_lifetime, acceptor_lifetime, cred_usage);
+ if (major_status != GSS_S_COMPLETE) {
+ _gss_mg_error(m, *minor_status);
+ return (major_status);
+ }
+
+ if (cred_name) {
+ name = _gss_create_name(mn, m);
+ if (!name) {
+ m->gm_release_name(minor_status, &mn);
+ return (GSS_S_NO_CRED);
+ }
+ *cred_name = (gss_name_t) name;
+ } else
+ m->gm_release_name(minor_status, &mn);
+
+
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_inquire_cred_by_oid.c b/third_party/heimdal/lib/gssapi/mech/gss_inquire_cred_by_oid.c
new file mode 100644
index 0000000..4e7c73f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_inquire_cred_by_oid.c
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2004, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_cred_by_oid (OM_uint32 *minor_status,
+ gss_const_cred_id_t cred_handle,
+ const gss_OID desired_object,
+ gss_buffer_set_t *data_set)
+{
+ struct _gss_cred *cred = (struct _gss_cred *) cred_handle;
+ OM_uint32 status = GSS_S_COMPLETE;
+ struct _gss_mechanism_cred *mc;
+ gssapi_mech_interface m;
+ gss_buffer_set_t set = GSS_C_NO_BUFFER_SET;
+
+ *minor_status = 0;
+ *data_set = GSS_C_NO_BUFFER_SET;
+
+ if (cred == NULL)
+ return GSS_S_NO_CRED;
+
+ status = GSS_S_FAILURE;
+
+ HEIM_TAILQ_FOREACH(mc, &cred->gc_mc, gmc_link) {
+ gss_buffer_set_t rset = GSS_C_NO_BUFFER_SET;
+ size_t i;
+
+ m = mc->gmc_mech;
+ if (m == NULL) {
+ _gss_secure_release_buffer_set(minor_status, &set);
+ *minor_status = 0;
+ return GSS_S_BAD_MECH;
+ }
+
+ if (m->gm_inquire_cred_by_oid == NULL)
+ continue;
+
+ status = m->gm_inquire_cred_by_oid(minor_status,
+ mc->gmc_cred, desired_object, &rset);
+ if (status != GSS_S_COMPLETE) {
+ _gss_mg_error(m, *minor_status);
+ continue;
+ }
+
+ for (i = 0; rset != NULL && i < rset->count; i++) {
+ status = gss_add_buffer_set_member(minor_status,
+ &rset->elements[i], &set);
+ if (status != GSS_S_COMPLETE)
+ break;
+ }
+ _gss_secure_release_buffer_set(minor_status, &rset);
+ }
+ if (set == GSS_C_NO_BUFFER_SET && status == GSS_S_COMPLETE)
+ status = GSS_S_FAILURE;
+ *data_set = set;
+ *minor_status = 0;
+ return status;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_inquire_mechs_for_name.c b/third_party/heimdal/lib/gssapi/mech/gss_inquire_mechs_for_name.c
new file mode 100644
index 0000000..f75dbaa
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_inquire_mechs_for_name.c
@@ -0,0 +1,76 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_inquire_mechs_for_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_mechs_for_name(OM_uint32 *minor_status,
+ gss_const_name_t input_name,
+ gss_OID_set *mech_types)
+{
+ OM_uint32 major_status;
+ struct _gss_name *name = (struct _gss_name *) input_name;
+ struct _gss_mech_switch *m;
+ gss_OID_set name_types;
+ int present;
+
+ *minor_status = 0;
+
+ _gss_load_mech();
+
+ major_status = gss_create_empty_oid_set(minor_status, mech_types);
+ if (major_status)
+ return (major_status);
+
+ /*
+ * We go through all the loaded mechanisms and see if this
+ * name's type is supported by the mechanism. If it is, add
+ * the mechanism to the set.
+ */
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ major_status = gss_inquire_names_for_mech(minor_status,
+ m->gm_mech_oid, &name_types);
+ if (major_status) {
+ gss_release_oid_set(minor_status, mech_types);
+ return (major_status);
+ }
+ gss_test_oid_set_member(minor_status,
+ name->gn_type, name_types, &present);
+ gss_release_oid_set(minor_status, &name_types);
+ if (present) {
+ major_status = gss_add_oid_set_member(minor_status,
+ m->gm_mech_oid, mech_types);
+ if (major_status) {
+ gss_release_oid_set(minor_status, mech_types);
+ return (major_status);
+ }
+ }
+ }
+
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_inquire_name.c b/third_party/heimdal/lib/gssapi/mech/gss_inquire_name.c
new file mode 100644
index 0000000..f109a9f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_inquire_name.c
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2010, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_name(OM_uint32 *minor_status,
+ gss_name_t input_name,
+ int *name_is_MN,
+ gss_OID *MN_mech,
+ gss_buffer_set_t *attrs)
+{
+ OM_uint32 major_status = GSS_S_UNAVAILABLE;
+ struct _gss_name *name = (struct _gss_name *) input_name;
+ struct _gss_mechanism_name *mn;
+
+ *minor_status = 0;
+ if (name_is_MN != NULL)
+ *name_is_MN = 0;
+ if (MN_mech != NULL)
+ *MN_mech = GSS_C_NO_OID;
+ if (attrs != NULL)
+ *attrs = GSS_C_NO_BUFFER_SET;
+
+ if (input_name == GSS_C_NO_NAME)
+ return GSS_S_BAD_NAME;
+
+ HEIM_TAILQ_FOREACH(mn, &name->gn_mn, gmn_link) {
+ gssapi_mech_interface m = mn->gmn_mech;
+
+ if (!m->gm_inquire_name)
+ continue;
+
+ major_status = m->gm_inquire_name(minor_status,
+ mn->gmn_name,
+ NULL,
+ MN_mech,
+ attrs);
+ if (major_status == GSS_S_COMPLETE) {
+ if (name_is_MN != NULL)
+ *name_is_MN = 1;
+ if (MN_mech != NULL && *MN_mech == GSS_C_NO_OID)
+ *MN_mech = &m->gm_mech_oid;
+ break;
+ }
+ _gss_mg_error(m, *minor_status);
+ }
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_inquire_names_for_mech.c b/third_party/heimdal/lib/gssapi/mech/gss_inquire_names_for_mech.c
new file mode 100644
index 0000000..595ab73
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_inquire_names_for_mech.c
@@ -0,0 +1,73 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_inquire_names_for_mech.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_names_for_mech(OM_uint32 *minor_status,
+ const gss_OID mechanism,
+ gss_OID_set *name_types)
+{
+ OM_uint32 major_status;
+ gssapi_mech_interface m = __gss_get_mechanism(mechanism);
+
+ *minor_status = 0;
+ *name_types = GSS_C_NO_OID_SET;
+ if (!m)
+ return (GSS_S_BAD_MECH);
+
+ /*
+ * If the implementation can do it, ask it for a list of
+ * names, otherwise fake it.
+ */
+ if (m->gm_inquire_names_for_mech) {
+ return (m->gm_inquire_names_for_mech(minor_status,
+ mechanism, name_types));
+ } else {
+ major_status = gss_create_empty_oid_set(minor_status,
+ name_types);
+ if (major_status)
+ return (major_status);
+ major_status = gss_add_oid_set_member(minor_status,
+ GSS_C_NT_HOSTBASED_SERVICE, name_types);
+ if (major_status) {
+ OM_uint32 junk;
+ gss_release_oid_set(&junk, name_types);
+ return (major_status);
+ }
+ major_status = gss_add_oid_set_member(minor_status,
+ GSS_C_NT_USER_NAME, name_types);
+ if (major_status) {
+ OM_uint32 junk;
+ gss_release_oid_set(&junk, name_types);
+ return (major_status);
+ }
+ }
+
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_inquire_sec_context_by_oid.c b/third_party/heimdal/lib/gssapi/mech/gss_inquire_sec_context_by_oid.c
new file mode 100644
index 0000000..55ff671
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_inquire_sec_context_by_oid.c
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2004, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_sec_context_by_oid (OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_OID desired_object,
+ gss_buffer_set_t *data_set)
+{
+ struct _gss_context *ctx = (struct _gss_context *) context_handle;
+ OM_uint32 major_status;
+ gssapi_mech_interface m;
+
+ *minor_status = 0;
+ *data_set = GSS_C_NO_BUFFER_SET;
+ if (ctx == NULL)
+ return GSS_S_NO_CONTEXT;
+
+ /*
+ * select the approprate underlying mechanism routine and
+ * call it.
+ */
+
+ m = ctx->gc_mech;
+
+ if (m == NULL)
+ return GSS_S_BAD_MECH;
+
+ if (m->gm_inquire_sec_context_by_oid != NULL) {
+ major_status = m->gm_inquire_sec_context_by_oid(minor_status,
+ ctx->gc_ctx, desired_object, data_set);
+ if (major_status != GSS_S_COMPLETE)
+ _gss_mg_error(m, *minor_status);
+ } else
+ major_status = GSS_S_BAD_MECH;
+
+ return major_status;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_krb5.c b/third_party/heimdal/lib/gssapi/mech/gss_krb5.c
new file mode 100644
index 0000000..78c3056
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_krb5.c
@@ -0,0 +1,927 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_krb5.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+#include "krb5/gsskrb5_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_copy_ccache(OM_uint32 *minor_status,
+ gss_cred_id_t cred,
+ krb5_ccache out)
+{
+ gss_key_value_element_desc cred_store_kvs[1];
+ gss_key_value_set_desc cred_store;
+ krb5_context context;
+ OM_uint32 major = GSS_S_FAILURE;
+ char *fullname = NULL;
+
+ GSSAPI_KRB5_INIT(&context);
+ *minor_status = krb5_cc_get_full_name(context, out, &fullname);
+ if (*minor_status == 0) {
+ cred_store_kvs[0].key = "ccache";
+ cred_store_kvs[0].value = fullname;
+ cred_store.count = 1;
+ cred_store.elements = cred_store_kvs;
+ major = gss_store_cred_into2(minor_status, cred, GSS_C_INITIATE,
+ GSS_KRB5_MECHANISM,
+ GSS_C_STORE_CRED_OVERWRITE, &cred_store,
+ NULL, NULL, NULL);
+ free(fullname);
+ }
+ return major;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_import_cred(OM_uint32 *minor_status,
+ krb5_ccache id,
+ krb5_principal keytab_principal,
+ krb5_keytab keytab,
+ gss_cred_id_t *cred)
+{
+ gss_buffer_desc buffer;
+ OM_uint32 major_status;
+ krb5_context context;
+ krb5_error_code ret;
+ krb5_storage *sp;
+ krb5_data data;
+ char *str;
+
+ *cred = GSS_C_NO_CREDENTIAL;
+
+ ret = krb5_init_context(&context);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ *minor_status = ENOMEM;
+ major_status = GSS_S_FAILURE;
+ goto out;
+ }
+
+ if (id) {
+ ret = krb5_cc_get_full_name(context, id, &str);
+ if (ret == 0) {
+ ret = krb5_store_string(sp, str);
+ free(str);
+ }
+ } else
+ ret = krb5_store_string(sp, "");
+ if (ret) {
+ *minor_status = ret;
+ major_status = GSS_S_FAILURE;
+ goto out;
+ }
+
+ if (keytab_principal) {
+ ret = krb5_unparse_name(context, keytab_principal, &str);
+ if (ret == 0) {
+ ret = krb5_store_string(sp, str);
+ free(str);
+ }
+ } else
+ krb5_store_string(sp, "");
+ if (ret) {
+ *minor_status = ret;
+ major_status = GSS_S_FAILURE;
+ goto out;
+ }
+
+
+ if (keytab) {
+ ret = krb5_kt_get_full_name(context, keytab, &str);
+ if (ret == 0) {
+ ret = krb5_store_string(sp, str);
+ free(str);
+ }
+ } else
+ krb5_store_string(sp, "");
+ if (ret) {
+ *minor_status = ret;
+ major_status = GSS_S_FAILURE;
+ goto out;
+ }
+
+ ret = krb5_storage_to_data(sp, &data);
+ if (ret) {
+ *minor_status = ret;
+ major_status = GSS_S_FAILURE;
+ goto out;
+ }
+
+ buffer.value = data.data;
+ buffer.length = data.length;
+
+ major_status = gss_set_cred_option(minor_status,
+ cred,
+ GSS_KRB5_IMPORT_CRED_X,
+ &buffer);
+ krb5_data_free(&data);
+out:
+ if (sp)
+ krb5_storage_free(sp);
+ krb5_free_context(context);
+ return major_status;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_register_acceptor_identity(const char *identity)
+{
+ gssapi_mech_interface m;
+ gss_buffer_desc buffer;
+ OM_uint32 junk;
+
+ _gss_load_mech();
+
+ buffer.value = rk_UNCONST(identity);
+ buffer.length = strlen(identity);
+
+ m = __gss_get_mechanism(GSS_KRB5_MECHANISM);
+ if (m == NULL || m->gm_set_sec_context_option == NULL)
+ return GSS_S_FAILURE;
+
+ return m->gm_set_sec_context_option(&junk, NULL,
+ GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X, &buffer);
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+krb5_gss_register_acceptor_identity(const char *identity)
+{
+ return gsskrb5_register_acceptor_identity(identity);
+}
+
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_set_dns_canonicalize(int flag)
+{
+ struct _gss_mech_switch *m;
+ gss_buffer_desc buffer;
+ OM_uint32 junk;
+ char b = (flag != 0);
+
+ _gss_load_mech();
+
+ buffer.value = &b;
+ buffer.length = sizeof(b);
+
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ if (m->gm_mech.gm_set_sec_context_option == NULL)
+ continue;
+ m->gm_mech.gm_set_sec_context_option(&junk, NULL,
+ GSS_KRB5_SET_DNS_CANONICALIZE_X, &buffer);
+ }
+
+ return (GSS_S_COMPLETE);
+}
+
+
+
+static krb5_error_code
+set_key(krb5_keyblock *keyblock, gss_krb5_lucid_key_t *key)
+{
+ key->type = keyblock->keytype;
+ key->length = keyblock->keyvalue.length;
+ key->data = malloc(key->length);
+ if (key->data == NULL && key->length != 0)
+ return ENOMEM;
+ memcpy(key->data, keyblock->keyvalue.data, key->length);
+ return 0;
+}
+
+static void
+free_key(gss_krb5_lucid_key_t *key)
+{
+ memset(key->data, 0, key->length);
+ free(key->data);
+ memset(key, 0, sizeof(*key));
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_export_lucid_sec_context(OM_uint32 *minor_status,
+ gss_ctx_id_t *context_handle,
+ OM_uint32 version,
+ void **rctx)
+{
+ krb5_context context = NULL;
+ krb5_error_code ret;
+ gss_buffer_set_t data_set = GSS_C_NO_BUFFER_SET;
+ OM_uint32 major_status;
+ gss_krb5_lucid_context_v1_t *ctx = NULL;
+ krb5_storage *sp = NULL;
+ uint32_t num;
+
+ if (context_handle == NULL
+ || *context_handle == GSS_C_NO_CONTEXT
+ || version != 1)
+ {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ major_status =
+ gss_inquire_sec_context_by_oid (minor_status,
+ *context_handle,
+ GSS_KRB5_EXPORT_LUCID_CONTEXT_V1_X,
+ &data_set);
+ if (major_status)
+ return major_status;
+
+ if (data_set == GSS_C_NO_BUFFER_SET || data_set->count != 1) {
+ gss_release_buffer_set(minor_status, &data_set);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ goto out;
+
+ ctx = calloc(1, sizeof(*ctx));
+ if (ctx == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ sp = krb5_storage_from_mem(data_set->elements[0].value,
+ data_set->elements[0].length);
+ if (sp == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ ret = krb5_ret_uint32(sp, &num);
+ if (ret) goto out;
+ if (num != 1) {
+ ret = EINVAL;
+ goto out;
+ }
+ ctx->version = 1;
+ /* initiator */
+ ret = krb5_ret_uint32(sp, &ctx->initiate);
+ if (ret) goto out;
+ /* endtime */
+ ret = krb5_ret_uint32(sp, &ctx->endtime);
+ if (ret) goto out;
+ /* send_seq */
+ ret = krb5_ret_uint32(sp, &num);
+ if (ret) goto out;
+ ctx->send_seq = ((uint64_t)num) << 32;
+ ret = krb5_ret_uint32(sp, &num);
+ if (ret) goto out;
+ ctx->send_seq |= num;
+ /* recv_seq */
+ ret = krb5_ret_uint32(sp, &num);
+ if (ret) goto out;
+ ctx->recv_seq = ((uint64_t)num) << 32;
+ ret = krb5_ret_uint32(sp, &num);
+ if (ret) goto out;
+ ctx->recv_seq |= num;
+ /* protocol */
+ ret = krb5_ret_uint32(sp, &ctx->protocol);
+ if (ret) goto out;
+ if (ctx->protocol == 0) {
+ krb5_keyblock key;
+
+ /* sign_alg */
+ ret = krb5_ret_uint32(sp, &ctx->rfc1964_kd.sign_alg);
+ if (ret) goto out;
+ /* seal_alg */
+ ret = krb5_ret_uint32(sp, &ctx->rfc1964_kd.seal_alg);
+ if (ret) goto out;
+ /* ctx_key */
+ ret = krb5_ret_keyblock(sp, &key);
+ if (ret) goto out;
+ ret = set_key(&key, &ctx->rfc1964_kd.ctx_key);
+ krb5_free_keyblock_contents(context, &key);
+ if (ret) goto out;
+ } else if (ctx->protocol == 1) {
+ krb5_keyblock key;
+
+ /* acceptor_subkey */
+ ret = krb5_ret_uint32(sp, &ctx->cfx_kd.have_acceptor_subkey);
+ if (ret) goto out;
+ /* ctx_key */
+ ret = krb5_ret_keyblock(sp, &key);
+ if (ret) goto out;
+ ret = set_key(&key, &ctx->cfx_kd.ctx_key);
+ krb5_free_keyblock_contents(context, &key);
+ if (ret) goto out;
+ /* acceptor_subkey */
+ if (ctx->cfx_kd.have_acceptor_subkey) {
+ ret = krb5_ret_keyblock(sp, &key);
+ if (ret) goto out;
+ ret = set_key(&key, &ctx->cfx_kd.acceptor_subkey);
+ krb5_free_keyblock_contents(context, &key);
+ if (ret) goto out;
+ }
+ } else {
+ ret = EINVAL;
+ goto out;
+ }
+
+ *rctx = ctx;
+
+out:
+ _gss_secure_release_buffer_set(minor_status, &data_set);
+ if (sp)
+ krb5_storage_free(sp);
+ if (context)
+ krb5_free_context(context);
+
+ if (ret) {
+ OM_uint32 junk;
+ if (ctx)
+ gss_krb5_free_lucid_sec_context(&junk, ctx);
+
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_free_lucid_sec_context(OM_uint32 *minor_status, void *c)
+{
+ gss_krb5_lucid_context_v1_t *ctx = c;
+
+ if (ctx->version != 1) {
+ if (minor_status)
+ *minor_status = 0;
+ return GSS_S_FAILURE;
+ }
+
+ if (ctx->protocol == 0) {
+ free_key(&ctx->rfc1964_kd.ctx_key);
+ } else if (ctx->protocol == 1) {
+ free_key(&ctx->cfx_kd.ctx_key);
+ if (ctx->cfx_kd.have_acceptor_subkey)
+ free_key(&ctx->cfx_kd.acceptor_subkey);
+ }
+ free(ctx);
+ if (minor_status)
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+/*
+ *
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_set_allowable_enctypes(OM_uint32 *minor_status,
+ gss_cred_id_t cred,
+ OM_uint32 num_enctypes,
+ int32_t *enctypes)
+{
+ krb5_error_code ret;
+ OM_uint32 maj_status;
+ gss_buffer_desc buffer;
+ krb5_storage *sp;
+ krb5_data data;
+ size_t i;
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ *minor_status = ENOMEM;
+ maj_status = GSS_S_FAILURE;
+ goto out;
+ }
+
+ for (i = 0; i < num_enctypes; i++) {
+ ret = krb5_store_int32(sp, enctypes[i]);
+ if (ret) {
+ *minor_status = ret;
+ maj_status = GSS_S_FAILURE;
+ goto out;
+ }
+ }
+
+ ret = krb5_storage_to_data(sp, &data);
+ if (ret) {
+ *minor_status = ret;
+ maj_status = GSS_S_FAILURE;
+ goto out;
+ }
+
+ buffer.value = data.data;
+ buffer.length = data.length;
+
+ maj_status = gss_set_cred_option(minor_status,
+ &cred,
+ GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X,
+ &buffer);
+ krb5_data_free(&data);
+out:
+ if (sp)
+ krb5_storage_free(sp);
+ return maj_status;
+}
+
+/*
+ *
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_set_send_to_kdc(struct gsskrb5_send_to_kdc *c)
+{
+ struct _gss_mech_switch *m;
+ gss_buffer_desc buffer;
+ OM_uint32 junk;
+
+ _gss_load_mech();
+
+ if (c) {
+ buffer.value = c;
+ buffer.length = sizeof(*c);
+ } else {
+ buffer.value = NULL;
+ buffer.length = 0;
+ }
+
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ if (m->gm_mech.gm_set_sec_context_option == NULL)
+ continue;
+ m->gm_mech.gm_set_sec_context_option(&junk, NULL,
+ GSS_KRB5_SEND_TO_KDC_X, &buffer);
+ }
+
+ return (GSS_S_COMPLETE);
+}
+
+/*
+ *
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_ccache_name(OM_uint32 *minor_status,
+ const char *name,
+ const char **out_name)
+{
+ struct _gss_mech_switch *m;
+ gss_buffer_desc buffer = GSS_C_EMPTY_BUFFER;
+ OM_uint32 major_status;
+ struct gsskrb5_ccache_name_args args;
+
+ _gss_load_mech();
+
+ *minor_status = 0;
+
+ if (out_name)
+ *out_name = NULL;
+
+ args.name = name;
+ args.out_name = NULL;
+
+ buffer.value = &args;
+ buffer.length = sizeof(args);
+
+ major_status = GSS_S_UNAVAILABLE;
+
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ OM_uint32 mech_major, mech_minor;
+
+ if (m->gm_mech.gm_set_sec_context_option == NULL)
+ continue;
+
+ mech_major = m->gm_mech.gm_set_sec_context_option(&mech_minor,
+ NULL, GSS_KRB5_CCACHE_NAME_X, &buffer);
+ if (mech_major != GSS_S_UNAVAILABLE) {
+ major_status = mech_major;
+ *minor_status = mech_minor;
+ break;
+ }
+ }
+
+ if (out_name)
+ *out_name = args.out_name;
+
+ return major_status;
+}
+
+
+/*
+ *
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_extract_authtime_from_sec_context(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ time_t *authtime)
+{
+ gss_buffer_set_t data_set = GSS_C_NO_BUFFER_SET;
+ OM_uint32 maj_stat;
+
+ if (context_handle == GSS_C_NO_CONTEXT) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ maj_stat =
+ gss_inquire_sec_context_by_oid (minor_status,
+ context_handle,
+ GSS_KRB5_GET_AUTHTIME_X,
+ &data_set);
+ if (maj_stat)
+ return maj_stat;
+
+ if (data_set == GSS_C_NO_BUFFER_SET) {
+ gss_release_buffer_set(minor_status, &data_set);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ if (data_set->count != 1) {
+ gss_release_buffer_set(minor_status, &data_set);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ if (data_set->elements[0].length != 4) {
+ gss_release_buffer_set(minor_status, &data_set);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ {
+ unsigned char *buf = data_set->elements[0].value;
+ *authtime = ((unsigned long)buf[3] <<24) | (buf[2] << 16) |
+ (buf[1] << 8) | (buf[0] << 0);
+ }
+
+ gss_release_buffer_set(minor_status, &data_set);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+/*
+ *
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_extract_authz_data_from_sec_context(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ int ad_type,
+ gss_buffer_t ad_data)
+{
+ gss_buffer_set_t data_set = GSS_C_NO_BUFFER_SET;
+ OM_uint32 maj_stat, tmp;
+ gss_OID_desc oid_flat;
+ heim_oid baseoid, oid;
+ size_t size;
+
+ if (context_handle == GSS_C_NO_CONTEXT) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ /* All this to append an integer to an oid... */
+
+ if (der_get_oid(GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X->elements,
+ GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X->length,
+ &baseoid, NULL) != 0) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ oid.length = baseoid.length + 1;
+ oid.components = calloc(oid.length, sizeof(*oid.components));
+ if (oid.components == NULL) {
+ der_free_oid(&baseoid);
+
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ memcpy(oid.components, baseoid.components,
+ baseoid.length * sizeof(*baseoid.components));
+
+ der_free_oid(&baseoid);
+
+ oid.components[oid.length - 1] = ad_type;
+
+ oid_flat.length = (OM_uint32)der_length_oid(&oid);
+ oid_flat.elements = malloc(oid_flat.length);
+ if (oid_flat.elements == NULL) {
+ free(oid.components);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ if (der_put_oid((unsigned char *)oid_flat.elements + oid_flat.length - 1,
+ oid_flat.length, &oid, &size) != 0) {
+ free(oid.components);
+ _gss_free_oid(&tmp, &oid_flat);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ if (oid_flat.length != size)
+ abort();
+
+ free(oid.components);
+
+ /* FINALLY, we have the OID */
+
+ maj_stat = gss_inquire_sec_context_by_oid (minor_status,
+ context_handle,
+ &oid_flat,
+ &data_set);
+
+ _gss_free_oid(&tmp, &oid_flat);
+
+ if (maj_stat)
+ return maj_stat;
+
+ if (data_set == GSS_C_NO_BUFFER_SET || data_set->count != 1) {
+ gss_release_buffer_set(minor_status, &data_set);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ ad_data->value = malloc(data_set->elements[0].length);
+ if (ad_data->value == NULL) {
+ gss_release_buffer_set(minor_status, &data_set);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ ad_data->length = data_set->elements[0].length;
+ memcpy(ad_data->value, data_set->elements[0].value, ad_data->length);
+ gss_release_buffer_set(minor_status, &data_set);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+/*
+ *
+ */
+
+static OM_uint32
+gsskrb5_extract_key(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ const gss_OID oid,
+ krb5_keyblock **keyblock)
+{
+ krb5_error_code ret;
+ gss_buffer_set_t data_set = GSS_C_NO_BUFFER_SET;
+ OM_uint32 major_status;
+ krb5_context context = NULL;
+ krb5_storage *sp = NULL;
+
+ if (context_handle == GSS_C_NO_CONTEXT) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_init_context(&context);
+ if(ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ major_status =
+ gss_inquire_sec_context_by_oid (minor_status,
+ context_handle,
+ oid,
+ &data_set);
+ if (major_status)
+ return major_status;
+
+ if (data_set == GSS_C_NO_BUFFER_SET || data_set->count != 1) {
+ _gss_secure_release_buffer_set(minor_status, &data_set);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ sp = krb5_storage_from_mem(data_set->elements[0].value,
+ data_set->elements[0].length);
+ if (sp == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ *keyblock = calloc(1, sizeof(**keyblock));
+ if (*keyblock == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ ret = krb5_ret_keyblock(sp, *keyblock);
+
+out:
+ _gss_secure_release_buffer_set(minor_status, &data_set);
+ if (sp)
+ krb5_storage_free(sp);
+ if (ret && keyblock) {
+ krb5_free_keyblock(context, *keyblock);
+ *keyblock = NULL;
+ }
+ if (context)
+ krb5_free_context(context);
+
+ *minor_status = ret;
+ if (ret)
+ return GSS_S_FAILURE;
+
+ return GSS_S_COMPLETE;
+}
+
+/*
+ *
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_extract_service_keyblock(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ krb5_keyblock **keyblock)
+{
+ return gsskrb5_extract_key(minor_status,
+ context_handle,
+ GSS_KRB5_GET_SERVICE_KEYBLOCK_X,
+ keyblock);
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_get_initiator_subkey(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ krb5_keyblock **keyblock)
+{
+ return gsskrb5_extract_key(minor_status,
+ context_handle,
+ GSS_KRB5_GET_INITIATOR_SUBKEY_X,
+ keyblock);
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_get_subkey(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ krb5_keyblock **keyblock)
+{
+ return gsskrb5_extract_key(minor_status,
+ context_handle,
+ GSS_KRB5_GET_SUBKEY_X,
+ keyblock);
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_set_default_realm(const char *realm)
+{
+ struct _gss_mech_switch *m;
+ gss_buffer_desc buffer;
+ OM_uint32 junk;
+
+ _gss_load_mech();
+
+ buffer.value = rk_UNCONST(realm);
+ buffer.length = strlen(realm);
+
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ if (m->gm_mech.gm_set_sec_context_option == NULL)
+ continue;
+ m->gm_mech.gm_set_sec_context_option(&junk, NULL,
+ GSS_KRB5_SET_DEFAULT_REALM_X, &buffer);
+ }
+
+ return (GSS_S_COMPLETE);
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_get_tkt_flags(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ OM_uint32 *tkt_flags)
+{
+
+ OM_uint32 major_status;
+ gss_buffer_set_t data_set = GSS_C_NO_BUFFER_SET;
+
+ if (context_handle == GSS_C_NO_CONTEXT) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ major_status =
+ gss_inquire_sec_context_by_oid (minor_status,
+ context_handle,
+ GSS_KRB5_GET_TKT_FLAGS_X,
+ &data_set);
+ if (major_status)
+ return major_status;
+
+ if (data_set == GSS_C_NO_BUFFER_SET ||
+ data_set->count != 1 ||
+ data_set->elements[0].length < 4) {
+ gss_release_buffer_set(minor_status, &data_set);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ {
+ const u_char *p = data_set->elements[0].value;
+ *tkt_flags = (p[0] << 0) | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
+ }
+
+ gss_release_buffer_set(minor_status, &data_set);
+ return GSS_S_COMPLETE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_set_time_offset(int offset)
+{
+ struct _gss_mech_switch *m;
+ gss_buffer_desc buffer;
+ OM_uint32 junk;
+ int32_t o = offset;
+
+ _gss_load_mech();
+
+ buffer.value = &o;
+ buffer.length = sizeof(o);
+
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ if (m->gm_mech.gm_set_sec_context_option == NULL)
+ continue;
+ m->gm_mech.gm_set_sec_context_option(&junk, NULL,
+ GSS_KRB5_SET_TIME_OFFSET_X, &buffer);
+ }
+
+ return (GSS_S_COMPLETE);
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_get_time_offset(int *offset)
+{
+ struct _gss_mech_switch *m;
+ gss_buffer_desc buffer;
+ OM_uint32 maj_stat, junk;
+ int32_t o;
+
+ _gss_load_mech();
+
+ buffer.value = &o;
+ buffer.length = sizeof(o);
+
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ if (m->gm_mech.gm_set_sec_context_option == NULL)
+ continue;
+ maj_stat = m->gm_mech.gm_set_sec_context_option(&junk, NULL,
+ GSS_KRB5_GET_TIME_OFFSET_X, &buffer);
+
+ if (maj_stat == GSS_S_COMPLETE) {
+ *offset = o;
+ return maj_stat;
+ }
+ }
+
+ return (GSS_S_UNAVAILABLE);
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_plugin_register(struct gsskrb5_krb5_plugin *c)
+{
+ struct _gss_mech_switch *m;
+ gss_buffer_desc buffer;
+ OM_uint32 junk;
+
+ _gss_load_mech();
+
+ buffer.value = c;
+ buffer.length = sizeof(*c);
+
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ if (m->gm_mech.gm_set_sec_context_option == NULL)
+ continue;
+ m->gm_mech.gm_set_sec_context_option(&junk, NULL,
+ GSS_KRB5_PLUGIN_REGISTER_X, &buffer);
+ }
+
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_mech_switch.c b/third_party/heimdal/lib/gssapi/mech/gss_mech_switch.c
new file mode 100644
index 0000000..372e72d
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_mech_switch.c
@@ -0,0 +1,585 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_mech_switch.c,v 1.2 2006/02/04 09:40:21 dfr Exp $
+ */
+
+#include "mech_locl.h"
+#include <heim_threads.h>
+
+#ifndef _PATH_GSS_MECH
+#define _PATH_GSS_MECH "/etc/gss/mech"
+#endif
+
+struct _gss_mech_switch_list _gss_mechs = { NULL, NULL } ;
+gss_OID_set _gss_mech_oids;
+static HEIMDAL_MUTEX _gss_mech_mutex = HEIMDAL_MUTEX_INITIALIZER;
+
+/*
+ * Convert a string containing an OID in 'dot' form
+ * (e.g. 1.2.840.113554.1.2.2) to a gss_OID.
+ */
+static int
+_gss_string_to_oid(const char* s, gss_OID *oidp)
+{
+ int number_count, i, j;
+ size_t byte_count;
+ const char *p, *q;
+ char *res;
+ gss_OID_desc oid;
+
+ *oidp = GSS_C_NO_OID;
+
+ /*
+ * First figure out how many numbers in the oid, then
+ * calculate the compiled oid size.
+ */
+ number_count = 0;
+ for (p = s; p; p = q) {
+ q = strchr(p, '.');
+ if (q) q = q + 1;
+ number_count++;
+ }
+
+ /*
+ * The first two numbers are in the first byte and each
+ * subsequent number is encoded in a variable byte sequence.
+ */
+ if (number_count < 2)
+ return (EINVAL);
+
+ /*
+ * We do this in two passes. The first pass, we just figure
+ * out the size. Second time around, we actually encode the
+ * number.
+ */
+ res = 0;
+ for (i = 0; i < 2; i++) {
+ byte_count = 0;
+ for (p = s, j = 0; p; p = q, j++) {
+ unsigned int number = 0;
+
+ /*
+ * Find the end of this number.
+ */
+ q = strchr(p, '.');
+ if (q) q = q + 1;
+
+ /*
+ * Read the number of of the string. Don't
+ * bother with anything except base ten.
+ */
+ while (*p && *p != '.') {
+ number = 10 * number + (*p - '0');
+ p++;
+ }
+
+ /*
+ * Encode the number. The first two numbers
+ * are packed into the first byte. Subsequent
+ * numbers are encoded in bytes seven bits at
+ * a time with the last byte having the high
+ * bit set.
+ */
+ if (j == 0) {
+ if (res)
+ *res = number * 40;
+ } else if (j == 1) {
+ if (res) {
+ *res += number;
+ res++;
+ }
+ byte_count++;
+ } else if (j >= 2) {
+ /*
+ * The number is encoded in seven bit chunks.
+ */
+ unsigned int t;
+ unsigned int bytes;
+
+ bytes = 0;
+ for (t = number; t; t >>= 7)
+ bytes++;
+ if (bytes == 0) bytes = 1;
+ while (bytes) {
+ if (res) {
+ int bit = 7*(bytes-1);
+
+ *res = (number >> bit) & 0x7f;
+ if (bytes != 1)
+ *res |= 0x80;
+ res++;
+ }
+ byte_count++;
+ bytes--;
+ }
+ }
+ }
+ if (byte_count == 0)
+ return EINVAL;
+ if (!res) {
+ res = malloc(byte_count);
+ if (!res)
+ return (ENOMEM);
+ oid.length = byte_count;
+ oid.elements = res;
+ }
+ }
+
+ {
+ OM_uint32 minor_status, tmp;
+
+ if (GSS_ERROR(_gss_intern_oid(&minor_status, &oid, oidp))) {
+ _gss_free_oid(&tmp, &oid);
+ return (minor_status);
+ }
+
+ _gss_free_oid(&tmp, &oid);
+ }
+
+ return (0);
+}
+
+#define SYM(name) \
+do { \
+ m->gm_mech.gm_ ## name = (_gss_##name##_t *)dlsym(so, "gss_" #name); \
+ if (!m->gm_mech.gm_ ## name || \
+ m->gm_mech.gm_ ##name == gss_ ## name) { \
+ _gss_mg_log(1, "can't find symbol gss_" #name "\n"); \
+ goto bad; \
+ } \
+} while (0)
+
+#define OPTSYM(name) \
+do { \
+ m->gm_mech.gm_ ## name = (_gss_##name##_t *)dlsym(so, "gss_" #name); \
+ if (m->gm_mech.gm_ ## name == gss_ ## name) \
+ m->gm_mech.gm_ ## name = NULL; \
+} while (0)
+
+/* mech exports gssspi_XXX, internally referred to as gss_XXX */
+#define OPTSPISYM(name) \
+do { \
+ m->gm_mech.gm_ ## name = (_gss_##name##_t *)dlsym(so, "gssspi_" #name); \
+} while (0)
+
+/* mech exports gssspi_XXX, internally referred to as gssspi_XXX */
+#define OPTSPISPISYM(name) \
+do { \
+ m->gm_mech.gm_ ## name = (_gss_##name##_t *)dlsym(so, "gssspi_" #name); \
+ if (m->gm_mech.gm_ ## name == gssspi_ ## name) \
+ m->gm_mech.gm_ ## name = NULL; \
+} while (0)
+
+#define COMPATSYM(name) \
+do { \
+ m->gm_mech.gm_compat->gmc_ ## name = (_gss_##name##_t *)dlsym(so, "gss_" #name); \
+ if (m->gm_mech.gm_compat->gmc_ ## name == gss_ ## name) \
+ m->gm_mech.gm_compat->gmc_ ## name = NULL; \
+} while (0)
+
+#define COMPATSPISYM(name) \
+do { \
+ m->gm_mech.gm_compat->gmc_ ## name = (_gss_##name##_t *)dlsym(so, "gssspi_" #name); \
+ if (m->gm_mech.gm_compat->gmc_ ## name == gss_ ## name) \
+ m->gm_mech.gm_compat->gmc_ ## name = NULL; \
+} while (0)
+
+/*
+ *
+ */
+static int
+add_builtin(gssapi_mech_interface mech)
+{
+ struct _gss_mech_switch *m;
+ OM_uint32 minor_status;
+
+ /* not registering any mech is ok */
+ if (mech == NULL)
+ return 0;
+
+ m = calloc(1, sizeof(*m));
+ if (m == NULL)
+ return ENOMEM;
+ m->gm_so = NULL;
+ m->gm_mech = *mech;
+ _gss_intern_oid(&minor_status, &mech->gm_mech_oid, &m->gm_mech_oid);
+ if (minor_status) {
+ free(m);
+ return minor_status;
+ }
+
+ if (gss_add_oid_set_member(&minor_status, &m->gm_mech.gm_mech_oid,
+ &_gss_mech_oids) != GSS_S_COMPLETE) {
+ free(m);
+ return ENOMEM;
+ }
+
+ /* pick up the oid sets of names */
+
+ if (m->gm_mech.gm_inquire_names_for_mech)
+ (*m->gm_mech.gm_inquire_names_for_mech)(&minor_status,
+ &m->gm_mech.gm_mech_oid, &m->gm_name_types);
+
+ if (m->gm_name_types == NULL &&
+ gss_create_empty_oid_set(&minor_status,
+ &m->gm_name_types) != GSS_S_COMPLETE) {
+ free(m);
+ return ENOMEM;
+ }
+
+ HEIM_TAILQ_INSERT_TAIL(&_gss_mechs, m, gm_link);
+ return 0;
+}
+
+static void
+init_mech_switch_list(void *p)
+{
+ struct _gss_mech_switch_list *mechs = p;
+
+ HEIM_TAILQ_INIT(mechs);
+}
+
+/*
+ * Load the mechanisms file (/etc/gss/mech).
+ */
+void
+_gss_load_mech(void)
+{
+ OM_uint32 major_status, minor_status;
+ static heim_base_once_t once = HEIM_BASE_ONCE_INIT;
+#ifdef HAVE_DLOPEN
+ FILE *fp;
+ char buf[256];
+ char *p;
+ char *name, *oid, *lib, *kobj;
+ struct _gss_mech_switch *m;
+ void *so;
+ gss_OID mech_oid;
+ int found;
+ const char *conf = secure_getenv("GSS_MECH_CONFIG");
+#endif
+
+ heim_base_once_f(&once, &_gss_mechs, init_mech_switch_list);
+
+ HEIMDAL_MUTEX_lock(&_gss_mech_mutex);
+
+ if (!HEIM_TAILQ_EMPTY(&_gss_mechs)) {
+ HEIMDAL_MUTEX_unlock(&_gss_mech_mutex);
+ return;
+ }
+
+ major_status = gss_create_empty_oid_set(&minor_status,
+ &_gss_mech_oids);
+ if (major_status) {
+ HEIMDAL_MUTEX_unlock(&_gss_mech_mutex);
+ return;
+ }
+
+ if (add_builtin(__gss_krb5_initialize()))
+ _gss_mg_log(1, "Out of memory while adding builtin Kerberos GSS "
+ "mechanism to the GSS mechanism switch");
+ if (add_builtin(__gss_spnego_initialize()))
+ _gss_mg_log(1, "Out of memory while adding builtin SPNEGO "
+ "mechanism to the GSS mechanism switch");
+ if (add_builtin(__gss_ntlm_initialize()))
+ _gss_mg_log(1, "Out of memory while adding builtin NTLM "
+ "mechanism to the GSS mechanism switch");
+
+#ifdef HAVE_DLOPEN
+ fp = fopen(conf ? conf : _PATH_GSS_MECH, "r");
+ if (!fp)
+ goto out;
+ rk_cloexec_file(fp);
+
+ while (fgets(buf, sizeof(buf), fp)) {
+ _gss_mo_init *mi;
+
+ if (*buf == '#')
+ continue;
+ p = buf;
+ name = strsep(&p, "\t\n ");
+ if (p) while (isspace((unsigned char)*p)) p++;
+ oid = strsep(&p, "\t\n ");
+ if (p) while (isspace((unsigned char)*p)) p++;
+ lib = strsep(&p, "\t\n ");
+ if (p) while (isspace((unsigned char)*p)) p++;
+ kobj = strsep(&p, "\t\n ");
+ if (!name || !oid || !lib || !kobj)
+ continue;
+
+ if (_gss_string_to_oid(oid, &mech_oid))
+ continue;
+
+ /*
+ * Check for duplicates, already loaded mechs.
+ */
+ found = 0;
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ if (gss_oid_equal(&m->gm_mech.gm_mech_oid, mech_oid)) {
+ found = 1;
+ break;
+ }
+ }
+ if (found)
+ continue;
+
+ so = dlopen(lib, RTLD_LAZY | RTLD_LOCAL | RTLD_GROUP);
+ if (so == NULL) {
+ _gss_mg_log(1, "dlopen: %s\n", dlerror());
+ goto bad;
+ }
+
+ m = calloc(1, sizeof(*m));
+ if (m == NULL)
+ goto bad;
+
+ m->gm_so = so;
+ m->gm_mech_oid = mech_oid;
+ m->gm_mech.gm_name = strdup(name);
+ m->gm_mech.gm_mech_oid = *mech_oid;
+ m->gm_mech.gm_flags = 0;
+ m->gm_mech.gm_compat = calloc(1, sizeof(struct gss_mech_compat_desc_struct));
+ if (m->gm_mech.gm_compat == NULL)
+ goto bad;
+
+ major_status = gss_add_oid_set_member(&minor_status,
+ &m->gm_mech.gm_mech_oid, &_gss_mech_oids);
+ if (GSS_ERROR(major_status))
+ goto bad;
+
+ SYM(acquire_cred);
+ SYM(release_cred);
+ SYM(init_sec_context);
+ SYM(accept_sec_context);
+ SYM(process_context_token);
+ SYM(delete_sec_context);
+ SYM(context_time);
+ SYM(get_mic);
+ SYM(verify_mic);
+ SYM(wrap);
+ SYM(unwrap);
+ OPTSYM(display_status);
+ OPTSYM(indicate_mechs);
+ SYM(compare_name);
+ SYM(display_name);
+ SYM(import_name);
+ SYM(export_name);
+ SYM(release_name);
+ OPTSYM(inquire_cred);
+ SYM(inquire_context);
+ SYM(wrap_size_limit);
+ OPTSYM(add_cred);
+ OPTSYM(inquire_cred_by_mech);
+ SYM(export_sec_context);
+ SYM(import_sec_context);
+ OPTSYM(inquire_names_for_mech);
+ OPTSYM(inquire_mechs_for_name);
+ SYM(canonicalize_name);
+ SYM(duplicate_name);
+ OPTSYM(inquire_cred_by_oid);
+ OPTSYM(inquire_sec_context_by_oid);
+ OPTSYM(set_sec_context_option);
+ OPTSPISYM(set_cred_option);
+ OPTSYM(pseudo_random);
+ OPTSYM(wrap_iov);
+ OPTSYM(unwrap_iov);
+ OPTSYM(wrap_iov_length);
+ OPTSYM(store_cred);
+ OPTSYM(export_cred);
+ OPTSYM(import_cred);
+ OPTSYM(acquire_cred_from);
+ OPTSYM(acquire_cred_impersonate_name);
+#if 0
+ OPTSYM(iter_creds);
+ OPTSYM(destroy_cred);
+ OPTSYM(cred_hold);
+ OPTSYM(cred_unhold);
+ OPTSYM(cred_label_get);
+ OPTSYM(cred_label_set);
+#endif
+ OPTSYM(display_name_ext);
+ OPTSYM(inquire_name);
+ OPTSYM(get_name_attribute);
+ OPTSYM(set_name_attribute);
+ OPTSYM(delete_name_attribute);
+ OPTSYM(export_name_composite);
+ OPTSYM(localname);
+ OPTSYM(duplicate_cred);
+ OPTSYM(add_cred_from);
+ OPTSYM(store_cred_into);
+ OPTSPISYM(authorize_localname);
+ OPTSPISPISYM(query_mechanism_info);
+ OPTSPISPISYM(query_meta_data);
+ OPTSPISPISYM(exchange_meta_data);
+
+ mi = (_gss_mo_init *)dlsym(so, "gss_mo_init");
+ if (mi != NULL) {
+ major_status = mi(&minor_status, mech_oid,
+ &m->gm_mech.gm_mo, &m->gm_mech.gm_mo_num);
+ if (GSS_ERROR(major_status))
+ goto bad;
+ } else {
+ /* API-as-SPI compatibility */
+ COMPATSYM(inquire_saslname_for_mech);
+ COMPATSYM(inquire_mech_for_saslname);
+ COMPATSYM(inquire_attrs_for_mech);
+ COMPATSPISYM(acquire_cred_with_password);
+ }
+
+ /* pick up the oid sets of names */
+
+ if (m->gm_mech.gm_inquire_names_for_mech)
+ (*m->gm_mech.gm_inquire_names_for_mech)(&minor_status,
+ &m->gm_mech.gm_mech_oid, &m->gm_name_types);
+
+ if (m->gm_name_types == NULL)
+ gss_create_empty_oid_set(&minor_status, &m->gm_name_types);
+
+ HEIM_TAILQ_INSERT_TAIL(&_gss_mechs, m, gm_link);
+ continue;
+
+ bad:
+ if (m != NULL) {
+ free(m->gm_mech.gm_compat);
+ /* do not free OID, it has been interned */
+ free((char *)m->gm_mech.gm_name);
+ free(m);
+ }
+ if (so != NULL)
+ dlclose(so);
+ continue;
+ }
+ fclose(fp);
+
+out:
+
+#endif
+ if (add_builtin(__gss_sanon_initialize()))
+ _gss_mg_log(1, "Out of memory while adding builtin SANON "
+ "mechanism to the GSS mechanism switch");
+ HEIMDAL_MUTEX_unlock(&_gss_mech_mutex);
+}
+
+gssapi_mech_interface
+__gss_get_mechanism(gss_const_OID mech)
+{
+ struct _gss_mech_switch *m;
+
+ _gss_load_mech();
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ if (gss_oid_equal(&m->gm_mech.gm_mech_oid, mech))
+ return &m->gm_mech;
+ }
+ return NULL;
+}
+
+gss_OID
+_gss_mg_support_mechanism(gss_const_OID mech)
+{
+ struct _gss_mech_switch *m;
+
+ _gss_load_mech();
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ if (gss_oid_equal(&m->gm_mech.gm_mech_oid, mech))
+ return m->gm_mech_oid;
+ }
+ return NULL;
+}
+
+enum mech_name_match {
+ MATCH_NONE = 0,
+ MATCH_COMPLETE,
+ MATCH_PARTIAL
+};
+
+static enum mech_name_match
+match_mech_name(const char *gm_mech_name,
+ const char *name,
+ size_t namelen)
+{
+ if (gm_mech_name == NULL)
+ return MATCH_NONE;
+ else if (strcasecmp(gm_mech_name, name) == 0)
+ return MATCH_COMPLETE;
+ else if (strncasecmp(gm_mech_name, name, namelen) == 0)
+ return MATCH_PARTIAL;
+ else
+ return MATCH_NONE;
+}
+
+/*
+ * Return an OID for a built-in or dynamically loaded mechanism. For
+ * API compatibility with previous versions, we treat "Kerberos 5"
+ * as an alias for "krb5". Unique partial matches are supported.
+ */
+GSSAPI_LIB_FUNCTION gss_OID GSSAPI_CALLCONV
+gss_name_to_oid(const char *name)
+{
+ struct _gss_mech_switch *m, *partial = NULL;
+ gss_OID oid = GSS_C_NO_OID;
+ size_t namelen = strlen(name);
+
+ if (isdigit(name[0]) && _gss_string_to_oid(name, &oid) == 0)
+ return oid;
+
+ _gss_load_mech();
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ enum mech_name_match match;
+
+ match = match_mech_name(m->gm_mech.gm_name, name, namelen);
+ if (match == MATCH_NONE &&
+ gss_oid_equal(m->gm_mech_oid, GSS_KRB5_MECHANISM))
+ match = match_mech_name("Kerberos 5", name, namelen);
+
+ if (match == MATCH_COMPLETE)
+ return m->gm_mech_oid;
+ else if (match == MATCH_PARTIAL) {
+ if (partial)
+ return NULL;
+ else
+ partial = m;
+ }
+ }
+
+ if (partial)
+ return partial->gm_mech_oid;
+
+ return NULL;
+}
+
+GSSAPI_LIB_FUNCTION const char * GSSAPI_LIB_CALL
+gss_oid_to_name(gss_const_OID oid)
+{
+ struct _gss_mech_switch *m;
+
+ _gss_load_mech();
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ if (gss_oid_equal(m->gm_mech_oid, oid))
+ return m->gm_mech.gm_name;
+ }
+
+ return NULL;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_mo.c b/third_party/heimdal/lib/gssapi/mech/gss_mo.c
new file mode 100644
index 0000000..b6ae282
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_mo.c
@@ -0,0 +1,636 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ * Portions Copyright (c) 2010 PADL Software Pty Ltd. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+#include <crypto-headers.h>
+
+static int
+get_option_def(int def, gss_const_OID mech, gss_mo_desc *mo, gss_buffer_t value)
+{
+ return def;
+}
+
+int
+_gss_mo_get_option_1(gss_const_OID mech, gss_mo_desc *mo, gss_buffer_t value)
+{
+ return get_option_def(1, mech, mo, value);
+}
+
+int
+_gss_mo_get_option_0(gss_const_OID mech, gss_mo_desc *mo, gss_buffer_t value)
+{
+ return get_option_def(0, mech, mo, value);
+}
+
+int
+_gss_mo_get_ctx_as_string(gss_const_OID mech, gss_mo_desc *mo, gss_buffer_t value)
+{
+ if (value) {
+ value->value = strdup((char *)mo->ctx);
+ if (value->value == NULL)
+ return GSS_S_FAILURE;
+ value->length = strlen((char *)mo->ctx);
+ }
+ return GSS_S_COMPLETE;
+}
+
+GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL
+gss_mo_set(gss_const_OID mech, gss_const_OID option,
+ int enable, gss_buffer_t value)
+{
+ gssapi_mech_interface m;
+ size_t n;
+
+ if ((m = __gss_get_mechanism(mech)) == NULL)
+ return GSS_S_BAD_MECH;
+
+ for (n = 0; n < m->gm_mo_num; n++)
+ if (gss_oid_equal(option, m->gm_mo[n].option) && m->gm_mo[n].set)
+ return m->gm_mo[n].set(mech, &m->gm_mo[n], enable, value);
+
+ return GSS_S_UNAVAILABLE;
+}
+
+GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL
+gss_mo_get(gss_const_OID mech, gss_const_OID option, gss_buffer_t value)
+{
+ gssapi_mech_interface m;
+ size_t n;
+
+ _mg_buffer_zero(value);
+
+ if ((m = __gss_get_mechanism(mech)) == NULL)
+ return GSS_S_BAD_MECH;
+
+ for (n = 0; n < m->gm_mo_num; n++)
+ if (gss_oid_equal(option, m->gm_mo[n].option) && m->gm_mo[n].get)
+ return m->gm_mo[n].get(mech, &m->gm_mo[n], value);
+
+ return GSS_S_UNAVAILABLE;
+}
+
+static void
+add_all_mo(gssapi_mech_interface m, gss_OID_set *options, OM_uint32 mask)
+{
+ OM_uint32 minor;
+ size_t n;
+
+ for (n = 0; n < m->gm_mo_num; n++)
+ if ((m->gm_mo[n].flags & mask) == mask)
+ gss_add_oid_set_member(&minor, m->gm_mo[n].option, options);
+}
+
+GSSAPI_LIB_FUNCTION void GSSAPI_LIB_CALL
+gss_mo_list(gss_const_OID mech, gss_OID_set *options)
+{
+ gssapi_mech_interface m;
+ OM_uint32 major, minor;
+
+ if (options == NULL)
+ return;
+
+ *options = GSS_C_NO_OID_SET;
+
+ if ((m = __gss_get_mechanism(mech)) == NULL)
+ return;
+
+ major = gss_create_empty_oid_set(&minor, options);
+ if (major != GSS_S_COMPLETE)
+ return;
+
+ add_all_mo(m, options, 0);
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_mo_name(gss_const_OID mech, gss_const_OID option, gss_buffer_t name)
+{
+ gssapi_mech_interface m;
+ size_t n;
+
+ if (name == NULL)
+ return GSS_S_BAD_NAME;
+
+ if ((m = __gss_get_mechanism(mech)) == NULL)
+ return GSS_S_BAD_MECH;
+
+ for (n = 0; n < m->gm_mo_num; n++) {
+ if (gss_oid_equal(option, m->gm_mo[n].option)) {
+ /*
+ * If there is no name, its because its a GSS_C_MA and
+ * there is already a table for that.
+ */
+ if (m->gm_mo[n].name) {
+ name->value = strdup(m->gm_mo[n].name);
+ if (name->value == NULL)
+ return GSS_S_BAD_NAME;
+ name->length = strlen(m->gm_mo[n].name);
+ return GSS_S_COMPLETE;
+ } else {
+ OM_uint32 junk;
+ return gss_display_mech_attr(&junk, option,
+ NULL, name, NULL);
+ }
+ }
+ }
+ return GSS_S_BAD_NAME;
+}
+
+/*
+ * Helper function to allow NULL name
+ */
+
+static OM_uint32
+mo_value(const gss_const_OID mech, gss_const_OID option, gss_buffer_t name)
+{
+ if (name == NULL)
+ return GSS_S_COMPLETE;
+
+ return gss_mo_get(mech, option, name);
+}
+
+/* code derived from draft-ietf-cat-sasl-gssapi-01 */
+static char basis_32[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
+
+static OM_uint32
+make_sasl_name(OM_uint32 *minor, const gss_OID mech, char sasl_name[16])
+{
+ EVP_MD_CTX *ctx;
+ char *p = sasl_name;
+ u_char hdr[2], hash[20], *h = hash;
+
+ if (mech->length > 127)
+ return GSS_S_BAD_MECH;
+
+ hdr[0] = 0x06;
+ hdr[1] = mech->length;
+
+ ctx = EVP_MD_CTX_create();
+ EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
+ EVP_DigestUpdate(ctx, hdr, 2);
+ EVP_DigestUpdate(ctx, mech->elements, mech->length);
+ EVP_DigestFinal_ex(ctx, hash, NULL);
+ EVP_MD_CTX_destroy(ctx);
+
+ memcpy(p, "GS2-", 4);
+ p += 4;
+
+ *p++ = basis_32[(h[0] >> 3)];
+ *p++ = basis_32[((h[0] & 7) << 2) | (h[1] >> 6)];
+ *p++ = basis_32[(h[1] & 0x3f) >> 1];
+ *p++ = basis_32[((h[1] & 1) << 4) | (h[2] >> 4)];
+ *p++ = basis_32[((h[2] & 0xf) << 1) | (h[3] >> 7)];
+ *p++ = basis_32[(h[3] & 0x7f) >> 2];
+ *p++ = basis_32[((h[3] & 3) << 3) | (h[4] >> 5)];
+ *p++ = basis_32[(h[4] & 0x1f)];
+ *p++ = basis_32[(h[5] >> 3)];
+ *p++ = basis_32[((h[5] & 7) << 2) | (h[6] >> 6)];
+ *p++ = basis_32[(h[6] & 0x3f) >> 1];
+
+ *p = '\0';
+
+ return GSS_S_COMPLETE;
+}
+
+/*
+ * gss_inquire_saslname_for_mech() wrapper that uses MIT SPI
+ */
+static OM_uint32
+inquire_saslname_for_mech_compat(OM_uint32 *minor,
+ const gss_OID desired_mech,
+ gss_buffer_t sasl_mech_name,
+ gss_buffer_t mech_name,
+ gss_buffer_t mech_description)
+{
+ struct gss_mech_compat_desc_struct *gmc;
+ gssapi_mech_interface m;
+ OM_uint32 major;
+
+ m = __gss_get_mechanism(desired_mech);
+ if (m == NULL)
+ return GSS_S_BAD_MECH;
+
+ gmc = m->gm_compat;
+
+ if (gmc != NULL && gmc->gmc_inquire_saslname_for_mech != NULL) {
+ major = gmc->gmc_inquire_saslname_for_mech(minor,
+ desired_mech,
+ sasl_mech_name,
+ mech_name,
+ mech_description);
+ } else {
+ major = GSS_S_UNAVAILABLE;
+ }
+
+ return major;
+}
+
+/**
+ * Returns different protocol names and description of the mechanism.
+ *
+ * @param minor_status minor status code
+ * @param desired_mech mech list query
+ * @param sasl_mech_name SASL GS2 protocol name
+ * @param mech_name gssapi protocol name
+ * @param mech_description description of gssapi mech
+ *
+ * @return returns GSS_S_COMPLETE or a error code.
+ *
+ * @ingroup gssapi
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_saslname_for_mech(OM_uint32 *minor_status,
+ const gss_OID desired_mech,
+ gss_buffer_t sasl_mech_name,
+ gss_buffer_t mech_name,
+ gss_buffer_t mech_description)
+{
+ OM_uint32 major;
+
+ _mg_buffer_zero(sasl_mech_name);
+ _mg_buffer_zero(mech_name);
+ _mg_buffer_zero(mech_description);
+
+ if (minor_status)
+ *minor_status = 0;
+
+ if (desired_mech == NULL)
+ return GSS_S_BAD_MECH;
+
+ major = mo_value(desired_mech, GSS_C_MA_SASL_MECH_NAME, sasl_mech_name);
+ if (major == GSS_S_COMPLETE) {
+ /* Native SPI */
+ major = mo_value(desired_mech, GSS_C_MA_MECH_NAME, mech_name);
+ if (GSS_ERROR(major))
+ return major;
+
+ major = mo_value(desired_mech, GSS_C_MA_MECH_DESCRIPTION, mech_description);
+ if (GSS_ERROR(major))
+ return major;
+ }
+
+ if (GSS_ERROR(major)) {
+ /* API-as-SPI compatibility */
+ major = inquire_saslname_for_mech_compat(minor_status,
+ desired_mech,
+ sasl_mech_name,
+ mech_name,
+ mech_description);
+ }
+
+ if (GSS_ERROR(major)) {
+ /* Algorithmically dervied SASL mechanism name */
+ char buf[16];
+ gss_buffer_desc tmp = { sizeof(buf) - 1, buf };
+
+ major = make_sasl_name(minor_status, desired_mech, buf);
+ if (GSS_ERROR(major))
+ return major;
+
+ major = _gss_copy_buffer(minor_status, &tmp, sasl_mech_name);
+ if (GSS_ERROR(major))
+ return major;
+ }
+
+ return major;
+}
+
+/**
+ * Find a mech for a sasl name
+ *
+ * @param minor_status minor status code
+ * @param sasl_mech_name
+ * @param mech_type
+ *
+ * @return returns GSS_S_COMPLETE or an error code.
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_mech_for_saslname(OM_uint32 *minor_status,
+ const gss_buffer_t sasl_mech_name,
+ gss_OID *mech_type)
+{
+ struct _gss_mech_switch *m;
+ gss_buffer_desc name;
+ OM_uint32 major, junk;
+ char buf[16];
+
+ _gss_load_mech();
+
+ *mech_type = NULL;
+
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ struct gss_mech_compat_desc_struct *gmc;
+
+ /* Native SPI */
+ major = mo_value(m->gm_mech_oid, GSS_C_MA_SASL_MECH_NAME, &name);
+ if (major == GSS_S_COMPLETE &&
+ name.length == sasl_mech_name->length &&
+ memcmp(name.value, sasl_mech_name->value, name.length) == 0) {
+ gss_release_buffer(&junk, &name);
+ *mech_type = m->gm_mech_oid;
+ return GSS_S_COMPLETE;
+ }
+ gss_release_buffer(&junk, &name);
+
+ if (GSS_ERROR(major)) {
+ /* API-as-SPI compatibility */
+ gmc = m->gm_mech.gm_compat;
+ if (gmc && gmc->gmc_inquire_mech_for_saslname) {
+ major = gmc->gmc_inquire_mech_for_saslname(minor_status,
+ sasl_mech_name,
+ mech_type);
+ if (major == GSS_S_COMPLETE)
+ return GSS_S_COMPLETE;
+ }
+ }
+
+ if (GSS_ERROR(major)) {
+ /* Algorithmically dervied SASL mechanism name */
+ if (sasl_mech_name->length == 16 &&
+ make_sasl_name(minor_status, m->gm_mech_oid, buf) == GSS_S_COMPLETE &&
+ memcmp(buf, sasl_mech_name->value, 16) == 0) {
+ *mech_type = m->gm_mech_oid;
+ return GSS_S_COMPLETE;
+ }
+ }
+ }
+
+ return GSS_S_BAD_MECH;
+}
+
+/*
+ * Test mechanism against indicated attributes using both Heimdal and
+ * MIT SPIs.
+ */
+static int
+test_mech_attrs(gssapi_mech_interface mi,
+ gss_const_OID_set mech_attrs,
+ gss_const_OID_set against_attrs,
+ int except)
+{
+ size_t n, m;
+ int eq = 0;
+
+ if (against_attrs == GSS_C_NO_OID_SET)
+ return 1;
+
+ for (n = 0; n < against_attrs->count; n++) {
+ for (m = 0; m < mi->gm_mo_num; m++) {
+ eq = gss_oid_equal(mi->gm_mo[m].option,
+ &against_attrs->elements[n]);
+ if (eq)
+ break;
+ }
+ if (mech_attrs != GSS_C_NO_OID_SET) {
+ for (m = 0; m < mech_attrs->count; m++) {
+ eq = gss_oid_equal(&mech_attrs->elements[m],
+ &against_attrs->elements[n]);
+ if (eq)
+ break;
+ }
+ }
+ if (!eq ^ except)
+ return 0;
+ }
+
+ return 1;
+}
+
+/**
+ * Return set of mechanism that fullfill the criteria
+ *
+ * @param minor_status minor status code
+ * @param desired_mech_attrs
+ * @param except_mech_attrs
+ * @param critical_mech_attrs
+ * @param mechs returned mechs, free with gss_release_oid_set().
+ *
+ * @return returns GSS_S_COMPLETE or an error code.
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_indicate_mechs_by_attrs(OM_uint32 * minor_status,
+ gss_const_OID_set desired_mech_attrs,
+ gss_const_OID_set except_mech_attrs,
+ gss_const_OID_set critical_mech_attrs,
+ gss_OID_set *mechs)
+{
+ struct _gss_mech_switch *ms;
+ gss_OID_set mech_attrs = GSS_C_NO_OID_SET;
+ gss_OID_set known_mech_attrs = GSS_C_NO_OID_SET;
+ OM_uint32 major;
+
+ major = gss_create_empty_oid_set(minor_status, mechs);
+ if (GSS_ERROR(major))
+ return major;
+
+ _gss_load_mech();
+
+ HEIM_TAILQ_FOREACH(ms, &_gss_mechs, gm_link) {
+ gssapi_mech_interface mi = &ms->gm_mech;
+ struct gss_mech_compat_desc_struct *gmc = mi->gm_compat;
+ OM_uint32 tmp;
+
+ if (gmc && gmc->gmc_inquire_attrs_for_mech) {
+ major = gmc->gmc_inquire_attrs_for_mech(minor_status,
+ &mi->gm_mech_oid,
+ &mech_attrs,
+ &known_mech_attrs);
+ if (GSS_ERROR(major))
+ continue;
+ }
+
+ /*
+ * Test mechanism supports all of desired_mech_attrs;
+ * none of except_mech_attrs;
+ * and knows of all critical_mech_attrs.
+ */
+ if (test_mech_attrs(mi, mech_attrs, desired_mech_attrs, 0) &&
+ test_mech_attrs(mi, mech_attrs, except_mech_attrs, 1) &&
+ test_mech_attrs(mi, known_mech_attrs, critical_mech_attrs, 0)) {
+ major = gss_add_oid_set_member(minor_status, &mi->gm_mech_oid, mechs);
+ }
+
+ gss_release_oid_set(&tmp, &mech_attrs);
+ gss_release_oid_set(&tmp, &known_mech_attrs);
+
+ if (GSS_ERROR(major))
+ break;
+ }
+
+ return major;
+}
+
+/**
+ * List support attributes for a mech and/or all mechanisms.
+ *
+ * @param minor_status minor status code
+ * @param mech given together with mech_attr will return the list of
+ * attributes for mechanism, can optionally be GSS_C_NO_OID.
+ * @param mech_attr see mech parameter, can optionally be NULL,
+ * release with gss_release_oid_set().
+ * @param known_mech_attrs all attributes for mechanisms supported,
+ * release with gss_release_oid_set().
+ *
+ * @ingroup gssapi
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_attrs_for_mech(OM_uint32 * minor_status,
+ gss_const_OID mech,
+ gss_OID_set *mech_attr,
+ gss_OID_set *known_mech_attrs)
+{
+ OM_uint32 major, junk;
+
+ if (known_mech_attrs)
+ *known_mech_attrs = GSS_C_NO_OID_SET;
+
+ if (mech_attr && mech) {
+ gssapi_mech_interface m;
+ struct gss_mech_compat_desc_struct *gmc;
+
+ if ((m = __gss_get_mechanism(mech)) == NULL) {
+ *minor_status = 0;
+ return GSS_S_BAD_MECH;
+ }
+
+ gmc = m->gm_compat;
+
+ if (gmc && gmc->gmc_inquire_attrs_for_mech) {
+ major = gmc->gmc_inquire_attrs_for_mech(minor_status,
+ mech,
+ mech_attr,
+ known_mech_attrs);
+ } else {
+ major = gss_create_empty_oid_set(minor_status, mech_attr);
+ if (major == GSS_S_COMPLETE)
+ add_all_mo(m, mech_attr, GSS_MO_MA);
+ }
+ if (GSS_ERROR(major))
+ return major;
+ }
+
+ if (known_mech_attrs) {
+ struct _gss_mech_switch *m;
+
+ if (*known_mech_attrs == GSS_C_NO_OID_SET) {
+ major = gss_create_empty_oid_set(minor_status, known_mech_attrs);
+ if (GSS_ERROR(major)) {
+ if (mech_attr)
+ gss_release_oid_set(&junk, mech_attr);
+ return major;
+ }
+ }
+
+ _gss_load_mech();
+
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link)
+ add_all_mo(&m->gm_mech, known_mech_attrs, GSS_MO_MA);
+ }
+
+
+ return GSS_S_COMPLETE;
+}
+
+/**
+ * Return names and descriptions of mech attributes
+ *
+ * @param minor_status minor status code
+ * @param mech_attr
+ * @param name
+ * @param short_desc
+ * @param long_desc
+ *
+ * @return returns GSS_S_COMPLETE or an error code.
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_display_mech_attr(OM_uint32 * minor_status,
+ gss_const_OID mech_attr,
+ gss_buffer_t name,
+ gss_buffer_t short_desc,
+ gss_buffer_t long_desc)
+{
+ struct _gss_oid_name_table *ma = NULL;
+ OM_uint32 major;
+ size_t n;
+
+ _mg_buffer_zero(name);
+ _mg_buffer_zero(short_desc);
+ _mg_buffer_zero(long_desc);
+
+ if (minor_status)
+ *minor_status = 0;
+
+ for (n = 0; ma == NULL && _gss_ont_ma[n].oid; n++)
+ if (gss_oid_equal(mech_attr, _gss_ont_ma[n].oid))
+ ma = &_gss_ont_ma[n];
+
+ if (ma == NULL)
+ return GSS_S_BAD_MECH_ATTR;
+
+ if (name) {
+ gss_buffer_desc bd;
+ bd.value = rk_UNCONST(ma->name);
+ bd.length = strlen(ma->name);
+ major = _gss_copy_buffer(minor_status, &bd, name);
+ if (major != GSS_S_COMPLETE)
+ return major;
+ }
+
+ if (short_desc) {
+ gss_buffer_desc bd;
+ bd.value = rk_UNCONST(ma->short_desc);
+ bd.length = strlen(ma->short_desc);
+ major = _gss_copy_buffer(minor_status, &bd, short_desc);
+ if (major != GSS_S_COMPLETE)
+ return major;
+ }
+
+ if (long_desc) {
+ gss_buffer_desc bd;
+ bd.value = rk_UNCONST(ma->long_desc);
+ bd.length = strlen(ma->long_desc);
+ major = _gss_copy_buffer(minor_status, &bd, long_desc);
+ if (major != GSS_S_COMPLETE)
+ return major;
+ }
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_names.c b/third_party/heimdal/lib/gssapi/mech/gss_names.c
new file mode 100644
index 0000000..729e7f2
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_names.c
@@ -0,0 +1,262 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_names.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+gss_name_t
+_gss_mg_get_underlying_mech_name(gss_name_t name,
+ gss_const_OID mech)
+{
+ struct _gss_name *n = (struct _gss_name *)name;
+ struct _gss_mechanism_name *mn;
+
+ HEIM_TAILQ_FOREACH(mn, &n->gn_mn, gmn_link) {
+ if (gss_oid_equal(mech, mn->gmn_mech_oid))
+ return mn->gmn_name;
+ }
+ return GSS_C_NO_NAME;
+}
+
+OM_uint32
+_gss_find_mn(OM_uint32 *minor_status,
+ struct _gss_name *name,
+ gss_const_OID mech,
+ struct _gss_mechanism_name ** output_mn)
+{
+ OM_uint32 major_status;
+ gssapi_mech_interface m;
+ struct _gss_mechanism_name *mn;
+
+ *output_mn = NULL;
+
+ /* null names are ok, some mechs might not have names */
+ if (name == NULL)
+ return GSS_S_COMPLETE;
+
+ HEIM_TAILQ_FOREACH(mn, &name->gn_mn, gmn_link) {
+ if (gss_oid_equal(mech, mn->gmn_mech_oid))
+ break;
+ }
+
+ if (!mn) {
+ /*
+ * If this name is canonical (i.e. there is only an
+ * MN but it is from a different mech), give up now.
+ */
+ if (!name->gn_value.value)
+ return GSS_S_BAD_NAME;
+
+ m = __gss_get_mechanism(mech);
+ if (!m || !m->gm_import_name)
+ return (GSS_S_BAD_MECH);
+
+ mn = malloc(sizeof(struct _gss_mechanism_name));
+ if (!mn)
+ return GSS_S_FAILURE;
+
+ major_status = m->gm_import_name(minor_status,
+ &name->gn_value,
+ name->gn_type,
+ &mn->gmn_name);
+ if (major_status != GSS_S_COMPLETE) {
+ _gss_mg_error(m, *minor_status);
+ free(mn);
+ return major_status;
+ }
+
+ mn->gmn_mech = m;
+ mn->gmn_mech_oid = &m->gm_mech_oid;
+ HEIM_TAILQ_INSERT_TAIL(&name->gn_mn, mn, gmn_link);
+ }
+ *output_mn = mn;
+ return 0;
+}
+
+
+/*
+ * Make a name from an MN.
+ */
+struct _gss_name *
+_gss_create_name(gss_name_t new_mn,
+ struct gssapi_mech_interface_desc *m)
+{
+ struct _gss_name *name;
+ struct _gss_mechanism_name *mn;
+
+ name = calloc(1, sizeof(struct _gss_name));
+ if (!name)
+ return (0);
+
+ HEIM_TAILQ_INIT(&name->gn_mn);
+
+ if (new_mn) {
+ mn = malloc(sizeof(struct _gss_mechanism_name));
+ if (!mn) {
+ free(name);
+ return (0);
+ }
+
+ mn->gmn_mech = m;
+ mn->gmn_mech_oid = &m->gm_mech_oid;
+ mn->gmn_name = new_mn;
+ HEIM_TAILQ_INSERT_TAIL(&name->gn_mn, mn, gmn_link);
+ }
+
+ return (name);
+}
+
+/*
+ *
+ */
+
+void
+_gss_mg_release_name(struct _gss_name *name)
+{
+ OM_uint32 junk;
+ struct _gss_mechanism_name *mn, *next;
+
+ gss_release_oid(&junk, &name->gn_type);
+
+ HEIM_TAILQ_FOREACH_SAFE(mn, &name->gn_mn, gmn_link, next) {
+ HEIM_TAILQ_REMOVE(&name->gn_mn, mn, gmn_link);
+ mn->gmn_mech->gm_release_name(&junk, &mn->gmn_name);
+ free(mn);
+ }
+ gss_release_buffer(&junk, &name->gn_value);
+ free(name);
+}
+
+void
+_gss_mg_check_name(gss_const_name_t name)
+{
+ if (name == NULL) return;
+}
+
+/*
+ *
+ */
+
+OM_uint32
+_gss_mech_import_name(OM_uint32 * minor_status,
+ gss_const_OID mech,
+ struct _gss_name_type *names,
+ const gss_buffer_t input_name_buffer,
+ gss_const_OID input_name_type,
+ gss_name_t *output_name)
+{
+ struct _gss_name_type *name;
+ gss_buffer_t name_buffer = input_name_buffer;
+ gss_buffer_desc export_name;
+
+ *minor_status = 0;
+
+ if (output_name == NULL)
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+
+ *output_name = GSS_C_NO_NAME;
+
+ /*
+ * If its a exported name, strip of the mech glue.
+ */
+
+ if (gss_oid_equal(input_name_type, GSS_C_NT_EXPORT_NAME)) {
+ unsigned char *p;
+ uint32_t length;
+
+ if (name_buffer->length < 10 + mech->length)
+ return GSS_S_BAD_NAME;
+
+ /* TOK, MECH_OID_LEN, DER(MECH_OID), NAME_LEN, NAME */
+
+ p = name_buffer->value;
+
+ if (memcmp(&p[0], "\x04\x01\x00", 3) != 0 ||
+ p[3] != mech->length + 2 ||
+ p[4] != 0x06 ||
+ p[5] != mech->length ||
+ memcmp(&p[6], mech->elements, mech->length) != 0)
+ return GSS_S_BAD_NAME;
+
+ p += 6 + mech->length;
+
+ length = p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3];
+ p += 4;
+
+ if (length > name_buffer->length - 10 - mech->length)
+ return GSS_S_BAD_NAME;
+
+ /*
+ * Point this to the mech specific name part, don't modifity
+ * orignal input_name_buffer.
+ */
+
+ export_name.length = length;
+ export_name.value = p;
+
+ name_buffer = &export_name;
+ }
+
+ for (name = names; name->gnt_parse != NULL; name++) {
+ if (gss_oid_equal(input_name_type, name->gnt_name_type)
+ || (name->gnt_name_type == GSS_C_NO_OID && input_name_type == GSS_C_NO_OID))
+ return name->gnt_parse(minor_status, mech, name_buffer,
+ input_name_type, output_name);
+ }
+
+ return GSS_S_BAD_NAMETYPE;
+}
+
+OM_uint32
+_gss_mech_inquire_names_for_mech(OM_uint32 * minor_status,
+ struct _gss_name_type *names,
+ gss_OID_set *name_types)
+{
+ struct _gss_name_type *name;
+ OM_uint32 ret, junk;
+
+ ret = gss_create_empty_oid_set(minor_status, name_types);
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+
+ for (name = names; name->gnt_parse != NULL; name++) {
+ if (name->gnt_name_type == GSS_C_NO_OID)
+ continue;
+ ret = gss_add_oid_set_member(minor_status,
+ name->gnt_name_type,
+ name_types);
+ if (ret != GSS_S_COMPLETE)
+ break;
+ }
+
+ if (ret != GSS_S_COMPLETE)
+ gss_release_oid_set(&junk, name_types);
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_oid.c b/third_party/heimdal/lib/gssapi/mech/gss_oid.c
new file mode 100644
index 0000000..10ec22d
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_oid.c
@@ -0,0 +1,370 @@
+/* Generated file */
+#include "mech_locl.h"
+
+/* GSS_KRB5_COPY_CCACHE_X - 1.2.752.43.13.1 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_copy_ccache_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x01") };
+
+/* GSS_KRB5_GET_TKT_FLAGS_X - 1.2.752.43.13.2 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_get_tkt_flags_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x02") };
+
+/* GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X - 1.2.752.43.13.3 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_extract_authz_data_from_sec_context_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x03") };
+
+/* GSS_KRB5_COMPAT_DES3_MIC_X - 1.2.752.43.13.4 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_compat_des3_mic_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x04") };
+
+/* GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X - 1.2.752.43.13.5 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_register_acceptor_identity_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x05") };
+
+/* GSS_KRB5_EXPORT_LUCID_CONTEXT_X - 1.2.752.43.13.6 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_export_lucid_context_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x06") };
+
+/* GSS_KRB5_EXPORT_LUCID_CONTEXT_V1_X - 1.2.752.43.13.6.1 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_export_lucid_context_v1_x_oid_desc = { 7, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x06\x01") };
+
+/* GSS_KRB5_SET_DNS_CANONICALIZE_X - 1.2.752.43.13.7 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_set_dns_canonicalize_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x07") };
+
+/* GSS_KRB5_GET_SUBKEY_X - 1.2.752.43.13.8 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_get_subkey_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x08") };
+
+/* GSS_KRB5_GET_INITIATOR_SUBKEY_X - 1.2.752.43.13.9 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_get_initiator_subkey_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x09") };
+
+/* GSS_KRB5_GET_ACCEPTOR_SUBKEY_X - 1.2.752.43.13.10 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_get_acceptor_subkey_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0a") };
+
+/* GSS_KRB5_SEND_TO_KDC_X - 1.2.752.43.13.11 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_send_to_kdc_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0b") };
+
+/* GSS_KRB5_GET_AUTHTIME_X - 1.2.752.43.13.12 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_get_authtime_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0c") };
+
+/* GSS_KRB5_GET_SERVICE_KEYBLOCK_X - 1.2.752.43.13.13 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_get_service_keyblock_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0d") };
+
+/* GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X - 1.2.752.43.13.14 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_set_allowable_enctypes_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0e") };
+
+/* GSS_KRB5_SET_DEFAULT_REALM_X - 1.2.752.43.13.15 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_set_default_realm_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0f") };
+
+/* GSS_KRB5_CCACHE_NAME_X - 1.2.752.43.13.16 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_ccache_name_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x10") };
+
+/* GSS_KRB5_SET_TIME_OFFSET_X - 1.2.752.43.13.17 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_set_time_offset_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x11") };
+
+/* GSS_KRB5_GET_TIME_OFFSET_X - 1.2.752.43.13.18 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_get_time_offset_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x12") };
+
+/* GSS_KRB5_PLUGIN_REGISTER_X - 1.2.752.43.13.19 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_plugin_register_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x13") };
+
+/* GSS_NTLM_GET_SESSION_KEY_X - 1.2.752.43.13.20 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_ntlm_get_session_key_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x14") };
+
+/* GSS_C_NT_NTLM - 1.2.752.43.13.21 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_ntlm_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x15") };
+
+/* GSS_C_NT_DN - 1.2.752.43.13.22 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_dn_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x16") };
+
+/* GSS_KRB5_NT_PRINCIPAL_NAME_REFERRAL - 1.2.752.43.13.23 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_nt_principal_name_referral_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x17") };
+
+/* GSS_C_NTLM_AVGUEST - 1.2.752.43.13.24 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ntlm_avguest_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x18") };
+
+/* GSS_C_NTLM_V1 - 1.2.752.43.13.25 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ntlm_v1_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x19") };
+
+/* GSS_C_NTLM_V2 - 1.2.752.43.13.26 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ntlm_v2_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x1a") };
+
+/* GSS_C_NTLM_SESSION_KEY - 1.2.752.43.13.27 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ntlm_session_key_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x1b") };
+
+/* GSS_C_NTLM_FORCE_V1 - 1.2.752.43.13.28 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ntlm_force_v1_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x1c") };
+
+/* GSS_KRB5_CRED_NO_CI_FLAGS_X - 1.2.752.43.13.29 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_cred_no_ci_flags_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x1d") };
+
+/* GSS_KRB5_IMPORT_CRED_X - 1.2.752.43.13.30 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_import_cred_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x1e") };
+
+/* GSS_KRB5_IMPORT_RFC4121_CONTEXT_X - 1.2.752.43.13.31 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_import_rfc4121_context_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x1f") };
+
+/* GSS_C_MA_SASL_MECH_NAME - 1.2.752.43.13.100 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_sasl_mech_name_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x64") };
+
+/* GSS_C_MA_MECH_NAME - 1.2.752.43.13.101 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mech_name_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x65") };
+
+/* GSS_C_MA_MECH_DESCRIPTION - 1.2.752.43.13.102 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mech_description_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x66") };
+
+/* GSS_SASL_DIGEST_MD5_MECHANISM - 1.2.752.43.14.1 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_sasl_digest_md5_mechanism_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0e\x01") };
+
+/* GSS_NETLOGON_MECHANISM - 1.2.752.43.14.2 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_netlogon_mechanism_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0e\x02") };
+
+/* GSS_NETLOGON_SET_SESSION_KEY_X - 1.2.752.43.14.3 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_netlogon_set_session_key_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0e\x03") };
+
+/* GSS_NETLOGON_SET_SIGN_ALGORITHM_X - 1.2.752.43.14.4 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_netlogon_set_sign_algorithm_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0e\x04") };
+
+/* GSS_NETLOGON_NT_NETBIOS_DNS_NAME - 1.2.752.43.14.5 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_netlogon_nt_netbios_dns_name_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0e\x05") };
+
+/* GSS_C_INQ_WIN2K_PAC_X - 1.2.752.43.13.3.128 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_inq_win2k_pac_x_oid_desc = { 8, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x03\x81\x00") };
+
+/* GSS_C_INQ_SSPI_SESSION_KEY - 1.2.840.113554.1.2.2.5.5 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_inq_sspi_session_key_oid_desc = { 11, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x05\x05") };
+
+/* GSS_C_INQ_NEGOEX_KEY - 1.2.840.113554.1.2.2.5.16 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_inq_negoex_key_oid_desc = { 11, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x05\x10") };
+
+/* GSS_C_INQ_NEGOEX_VERIFY_KEY - 1.2.840.113554.1.2.2.5.17 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_inq_negoex_verify_key_oid_desc = { 11, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x05\x11") };
+
+/* GSS_C_INQ_REQUIRE_MECHLIST_MIC - 1.3.6.1.4.1.7165.655.1.2 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_inq_require_mechlist_mic_oid_desc = { 11, rk_UNCONST("\x2b\x06\x01\x04\x01\xb7\x7d\x85\x0f\x01\x02") };
+
+/* GSS_KRB5_MECHANISM - 1.2.840.113554.1.2.2 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_mechanism_oid_desc = { 9, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02") };
+
+/* GSS_NTLM_MECHANISM - 1.3.6.1.4.1.311.2.2.10 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_ntlm_mechanism_oid_desc = { 10, rk_UNCONST("\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a") };
+
+/* GSS_SPNEGO_MECHANISM - 1.3.6.1.5.5.2 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_spnego_mechanism_oid_desc = { 6, rk_UNCONST("\x2b\x06\x01\x05\x05\x02") };
+
+/* GSS_C_INQ_PEER_HAS_BUGGY_SPNEGO - 1.3.6.1.4.1.5322.19.6 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_inq_peer_has_buggy_spnego_oid_desc = { 9, rk_UNCONST("\x2b\x06\x01\x04\x01\xa9\x4a\x13\x06") };
+
+/* GSS_C_NTLM_RESET_CRYPTO - 1.3.6.1.4.1.7165.655.1.3 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ntlm_reset_crypto_oid_desc = { 11, rk_UNCONST("\x2b\x06\x01\x04\x01\xb7\x7d\x85\x0f\x01\x03") };
+
+/* GSS_NEGOEX_MECHANISM - 1.3.6.1.4.1.311.2.2.30 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_negoex_mechanism_oid_desc = { 10, rk_UNCONST("\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x1e") };
+
+/* GSS_SANON_X25519_MECHANISM - 1.3.6.1.4.1.5322.26.1.110 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_sanon_x25519_mechanism_oid_desc = { 10, rk_UNCONST("\x2b\x06\x01\x04\x01\xa9\x4a\x1a\x01\x6e") };
+
+/* GSS_C_MA_MECH_CONCRETE - 1.3.6.1.5.5.13.1 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mech_concrete_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x01") };
+
+/* GSS_C_MA_MECH_PSEUDO - 1.3.6.1.5.5.13.2 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mech_pseudo_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x02") };
+
+/* GSS_C_MA_MECH_COMPOSITE - 1.3.6.1.5.5.13.3 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mech_composite_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x03") };
+
+/* GSS_C_MA_MECH_NEGO - 1.3.6.1.5.5.13.4 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mech_nego_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x04") };
+
+/* GSS_C_MA_MECH_GLUE - 1.3.6.1.5.5.13.5 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mech_glue_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x05") };
+
+/* GSS_C_MA_NOT_MECH - 1.3.6.1.5.5.13.6 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_not_mech_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x06") };
+
+/* GSS_C_MA_DEPRECATED - 1.3.6.1.5.5.13.7 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_deprecated_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x07") };
+
+/* GSS_C_MA_NOT_DFLT_MECH - 1.3.6.1.5.5.13.8 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_not_dflt_mech_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x08") };
+
+/* GSS_C_MA_ITOK_FRAMED - 1.3.6.1.5.5.13.9 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_itok_framed_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x09") };
+
+/* GSS_C_MA_AUTH_INIT - 1.3.6.1.5.5.13.10 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_auth_init_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x0a") };
+
+/* GSS_C_MA_AUTH_TARG - 1.3.6.1.5.5.13.11 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_auth_targ_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x0b") };
+
+/* GSS_C_MA_AUTH_INIT_INIT - 1.3.6.1.5.5.13.12 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_auth_init_init_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x0c") };
+
+/* GSS_C_MA_AUTH_TARG_INIT - 1.3.6.1.5.5.13.13 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_auth_targ_init_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x0d") };
+
+/* GSS_C_MA_AUTH_INIT_ANON - 1.3.6.1.5.5.13.14 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_auth_init_anon_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x0e") };
+
+/* GSS_C_MA_AUTH_TARG_ANON - 1.3.6.1.5.5.13.15 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_auth_targ_anon_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x0f") };
+
+/* GSS_C_MA_DELEG_CRED - 1.3.6.1.5.5.13.16 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_deleg_cred_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x10") };
+
+/* GSS_C_MA_INTEG_PROT - 1.3.6.1.5.5.13.17 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_integ_prot_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x11") };
+
+/* GSS_C_MA_CONF_PROT - 1.3.6.1.5.5.13.18 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_conf_prot_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x12") };
+
+/* GSS_C_MA_MIC - 1.3.6.1.5.5.13.19 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mic_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x13") };
+
+/* GSS_C_MA_WRAP - 1.3.6.1.5.5.13.20 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_wrap_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x14") };
+
+/* GSS_C_MA_PROT_READY - 1.3.6.1.5.5.13.21 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_prot_ready_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x15") };
+
+/* GSS_C_MA_REPLAY_DET - 1.3.6.1.5.5.13.22 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_replay_det_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x16") };
+
+/* GSS_C_MA_OOS_DET - 1.3.6.1.5.5.13.23 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_oos_det_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x17") };
+
+/* GSS_C_MA_CBINDINGS - 1.3.6.1.5.5.13.24 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_cbindings_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x18") };
+
+/* GSS_C_MA_PFS - 1.3.6.1.5.5.13.25 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_pfs_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x19") };
+
+/* GSS_C_MA_COMPRESS - 1.3.6.1.5.5.13.26 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_compress_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x1a") };
+
+/* GSS_C_MA_CTX_TRANS - 1.3.6.1.5.5.13.27 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_ctx_trans_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x1b") };
+
+/* GSS_C_MA_NEGOEX_AND_SPNEGO - 1.2.840.113554.1.2.2.5.18 */
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_negoex_and_spnego_oid_desc = { 11, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x05\x12") };
+
+struct _gss_oid_name_table _gss_ont_ma[] = {
+ { GSS_C_MA_AUTH_INIT, "GSS_C_MA_AUTH_INIT", "auth-init-princ", "" },
+ { GSS_C_MA_AUTH_INIT_ANON, "GSS_C_MA_AUTH_INIT_ANON", "auth-init-princ-anon", "" },
+ { GSS_C_MA_AUTH_INIT_INIT, "GSS_C_MA_AUTH_INIT_INIT", "auth-init-princ-initial", "" },
+ { GSS_C_MA_AUTH_TARG, "GSS_C_MA_AUTH_TARG", "auth-targ-princ", "" },
+ { GSS_C_MA_AUTH_TARG_ANON, "GSS_C_MA_AUTH_TARG_ANON", "auth-targ-princ-anon", "" },
+ { GSS_C_MA_AUTH_TARG_INIT, "GSS_C_MA_AUTH_TARG_INIT", "auth-targ-princ-initial", "" },
+ { GSS_C_MA_CBINDINGS, "GSS_C_MA_CBINDINGS", "channel-bindings", "" },
+ { GSS_C_MA_COMPRESS, "GSS_C_MA_COMPRESS", "compress", "" },
+ { GSS_C_MA_CONF_PROT, "GSS_C_MA_CONF_PROT", "conf-prot", "" },
+ { GSS_C_MA_CTX_TRANS, "GSS_C_MA_CTX_TRANS", "context-transfer", "" },
+ { GSS_C_MA_DELEG_CRED, "GSS_C_MA_DELEG_CRED", "deleg-cred", "" },
+ { GSS_C_MA_DEPRECATED, "GSS_C_MA_DEPRECATED", "mech-deprecated", "" },
+ { GSS_C_MA_INTEG_PROT, "GSS_C_MA_INTEG_PROT", "integ-prot", "" },
+ { GSS_C_MA_ITOK_FRAMED, "GSS_C_MA_ITOK_FRAMED", "initial-is-framed", "" },
+ { GSS_C_MA_MECH_COMPOSITE, "GSS_C_MA_MECH_COMPOSITE", "composite-mech", "" },
+ { GSS_C_MA_MECH_CONCRETE, "GSS_C_MA_MECH_CONCRETE", "concrete-mech", "Indicates that a mech is neither a pseudo-mechanism nor a composite mechanism" },
+ { GSS_C_MA_MECH_DESCRIPTION, "GSS_C_MA_MECH_DESCRIPTION", "Mech description", "The long description of the mechanism" },
+ { GSS_C_MA_MECH_GLUE, "GSS_C_MA_MECH_GLUE", "mech-glue", "" },
+ { GSS_C_MA_MECH_NAME, "GSS_C_MA_MECH_NAME", "GSS mech name", "The name of the GSS-API mechanism" },
+ { GSS_C_MA_MECH_NEGO, "GSS_C_MA_MECH_NEGO", "mech-negotiation-mech", "" },
+ { GSS_C_MA_MECH_PSEUDO, "GSS_C_MA_MECH_PSEUDO", "pseudo-mech", "" },
+ { GSS_C_MA_MIC, "GSS_C_MA_MIC", "mic", "" },
+ { GSS_C_MA_NEGOEX_AND_SPNEGO, "GSS_C_MA_NEGOEX_AND_SPNEGO", "negoex-and-spnego", "Indicates that a mechanism supports both NegoEx and SPNEGO" },
+ { GSS_C_MA_NOT_DFLT_MECH, "GSS_C_MA_NOT_DFLT_MECH", "mech-not-default", "" },
+ { GSS_C_MA_NOT_MECH, "GSS_C_MA_NOT_MECH", "not-mech", "" },
+ { GSS_C_MA_OOS_DET, "GSS_C_MA_OOS_DET", "oos-detection", "" },
+ { GSS_C_MA_PFS, "GSS_C_MA_PFS", "pfs", "" },
+ { GSS_C_MA_PROT_READY, "GSS_C_MA_PROT_READY", "prot-ready", "" },
+ { GSS_C_MA_REPLAY_DET, "GSS_C_MA_REPLAY_DET", "replay-detection", "" },
+ { GSS_C_MA_SASL_MECH_NAME, "GSS_C_MA_SASL_MECH_NAME", "SASL mechanism name", "The name of the SASL mechanism" },
+ { GSS_C_MA_WRAP, "GSS_C_MA_WRAP", "wrap", "" },
+ { NULL, NULL, NULL, NULL }
+};
+
+struct _gss_oid_name_table _gss_ont_mech[] = {
+ { GSS_KRB5_MECHANISM, "GSS_KRB5_MECHANISM", "Kerberos 5", "Heimdal Kerberos 5 mechanism" },
+ { GSS_NTLM_MECHANISM, "GSS_NTLM_MECHANISM", "NTLM", "Heimdal NTLM mechanism" },
+ { GSS_SANON_X25519_MECHANISM, "GSS_SANON_X25519_MECHANISM", "SAnon-X25519", "Heimdal Simple Anonymous (X25519) mechanism" },
+ { GSS_SPNEGO_MECHANISM, "GSS_SPNEGO_MECHANISM", "SPNEGO", "Heimdal SPNEGO mechanism" },
+ { NULL, NULL, NULL, NULL }
+};
+
+gss_OID _gss_ot_internal[] = {
+ &__gss_krb5_copy_ccache_x_oid_desc,
+ &__gss_krb5_get_tkt_flags_x_oid_desc,
+ &__gss_krb5_extract_authz_data_from_sec_context_x_oid_desc,
+ &__gss_krb5_compat_des3_mic_x_oid_desc,
+ &__gss_krb5_register_acceptor_identity_x_oid_desc,
+ &__gss_krb5_export_lucid_context_x_oid_desc,
+ &__gss_krb5_export_lucid_context_v1_x_oid_desc,
+ &__gss_krb5_set_dns_canonicalize_x_oid_desc,
+ &__gss_krb5_get_subkey_x_oid_desc,
+ &__gss_krb5_get_initiator_subkey_x_oid_desc,
+ &__gss_krb5_get_acceptor_subkey_x_oid_desc,
+ &__gss_krb5_send_to_kdc_x_oid_desc,
+ &__gss_krb5_get_authtime_x_oid_desc,
+ &__gss_krb5_get_service_keyblock_x_oid_desc,
+ &__gss_krb5_set_allowable_enctypes_x_oid_desc,
+ &__gss_krb5_set_default_realm_x_oid_desc,
+ &__gss_krb5_ccache_name_x_oid_desc,
+ &__gss_krb5_set_time_offset_x_oid_desc,
+ &__gss_krb5_get_time_offset_x_oid_desc,
+ &__gss_krb5_plugin_register_x_oid_desc,
+ &__gss_ntlm_get_session_key_x_oid_desc,
+ &__gss_c_nt_ntlm_oid_desc,
+ &__gss_c_nt_dn_oid_desc,
+ &__gss_krb5_nt_principal_name_referral_oid_desc,
+ &__gss_c_ntlm_avguest_oid_desc,
+ &__gss_c_ntlm_v1_oid_desc,
+ &__gss_c_ntlm_v2_oid_desc,
+ &__gss_c_ntlm_session_key_oid_desc,
+ &__gss_c_ntlm_force_v1_oid_desc,
+ &__gss_krb5_cred_no_ci_flags_x_oid_desc,
+ &__gss_krb5_import_cred_x_oid_desc,
+ &__gss_krb5_import_rfc4121_context_x_oid_desc,
+ &__gss_c_ma_sasl_mech_name_oid_desc,
+ &__gss_c_ma_mech_name_oid_desc,
+ &__gss_c_ma_mech_description_oid_desc,
+ &__gss_sasl_digest_md5_mechanism_oid_desc,
+ &__gss_netlogon_mechanism_oid_desc,
+ &__gss_netlogon_set_session_key_x_oid_desc,
+ &__gss_netlogon_set_sign_algorithm_x_oid_desc,
+ &__gss_netlogon_nt_netbios_dns_name_oid_desc,
+ &__gss_c_inq_win2k_pac_x_oid_desc,
+ &__gss_c_inq_sspi_session_key_oid_desc,
+ &__gss_c_inq_negoex_key_oid_desc,
+ &__gss_c_inq_negoex_verify_key_oid_desc,
+ &__gss_c_inq_require_mechlist_mic_oid_desc,
+ &__gss_krb5_mechanism_oid_desc,
+ &__gss_ntlm_mechanism_oid_desc,
+ &__gss_spnego_mechanism_oid_desc,
+ &__gss_c_inq_peer_has_buggy_spnego_oid_desc,
+ &__gss_c_ntlm_reset_crypto_oid_desc,
+ &__gss_negoex_mechanism_oid_desc,
+ &__gss_sanon_x25519_mechanism_oid_desc,
+ &__gss_c_ma_mech_concrete_oid_desc,
+ &__gss_c_ma_mech_pseudo_oid_desc,
+ &__gss_c_ma_mech_composite_oid_desc,
+ &__gss_c_ma_mech_nego_oid_desc,
+ &__gss_c_ma_mech_glue_oid_desc,
+ &__gss_c_ma_not_mech_oid_desc,
+ &__gss_c_ma_deprecated_oid_desc,
+ &__gss_c_ma_not_dflt_mech_oid_desc,
+ &__gss_c_ma_itok_framed_oid_desc,
+ &__gss_c_ma_auth_init_oid_desc,
+ &__gss_c_ma_auth_targ_oid_desc,
+ &__gss_c_ma_auth_init_init_oid_desc,
+ &__gss_c_ma_auth_targ_init_oid_desc,
+ &__gss_c_ma_auth_init_anon_oid_desc,
+ &__gss_c_ma_auth_targ_anon_oid_desc,
+ &__gss_c_ma_deleg_cred_oid_desc,
+ &__gss_c_ma_integ_prot_oid_desc,
+ &__gss_c_ma_conf_prot_oid_desc,
+ &__gss_c_ma_mic_oid_desc,
+ &__gss_c_ma_wrap_oid_desc,
+ &__gss_c_ma_prot_ready_oid_desc,
+ &__gss_c_ma_replay_det_oid_desc,
+ &__gss_c_ma_oos_det_oid_desc,
+ &__gss_c_ma_cbindings_oid_desc,
+ &__gss_c_ma_pfs_oid_desc,
+ &__gss_c_ma_compress_oid_desc,
+ &__gss_c_ma_ctx_trans_oid_desc,
+ &__gss_c_ma_negoex_and_spnego_oid_desc,
+};
+
+size_t _gss_ot_internal_count = sizeof(_gss_ot_internal) / sizeof(_gss_ot_internal[0]);
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_oid_equal.c b/third_party/heimdal/lib/gssapi/mech/gss_oid_equal.c
new file mode 100644
index 0000000..b125ede
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_oid_equal.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+/**
+ * Compare two GSS-API OIDs with each other.
+ *
+ * GSS_C_NO_OID matches nothing, not even it-self.
+ *
+ * @param a first oid to compare
+ * @param b second oid to compare
+ *
+ * @return non-zero when both oid are the same OID, zero when they are
+ * not the same.
+ *
+ * @ingroup gssapi
+ */
+
+GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL
+gss_oid_equal(gss_const_OID a, gss_const_OID b)
+{
+ if (a == b && a != GSS_C_NO_OID)
+ return 1;
+ if (a == GSS_C_NO_OID || b == GSS_C_NO_OID || a->length != b->length)
+ return 0;
+ return memcmp(a->elements, b->elements, a->length) == 0;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_oid_to_str.c b/third_party/heimdal/lib/gssapi/mech/gss_oid_to_str.c
new file mode 100644
index 0000000..d8e188d
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_oid_to_str.c
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_oid_to_str(OM_uint32 *minor_status, gss_OID oid, gss_buffer_t oid_str)
+{
+ int ret;
+ size_t size;
+ heim_oid o;
+ char *p;
+
+ _mg_buffer_zero(oid_str);
+
+ if (oid == GSS_C_NULL_OID)
+ return GSS_S_FAILURE;
+
+ ret = der_get_oid (oid->elements, oid->length, &o, &size);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = der_print_heim_oid(&o, ' ', &p);
+ der_free_oid(&o);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ oid_str->value = p;
+ oid_str->length = strlen(p);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_pname_to_uid.c b/third_party/heimdal/lib/gssapi/mech/gss_pname_to_uid.c
new file mode 100644
index 0000000..5046fae
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_pname_to_uid.c
@@ -0,0 +1,197 @@
+/*
+ * Copyright (c) 2011, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+static OM_uint32
+mech_localname(OM_uint32 *minor_status,
+ struct _gss_mechanism_name *mn,
+ gss_buffer_t localname)
+{
+ OM_uint32 major_status = GSS_S_UNAVAILABLE;
+
+ *minor_status = 0;
+
+ if (mn->gmn_mech->gm_localname == NULL)
+ return GSS_S_UNAVAILABLE;
+
+ major_status = mn->gmn_mech->gm_localname(minor_status,
+ mn->gmn_name,
+ mn->gmn_mech_oid,
+ localname);
+ if (GSS_ERROR(major_status))
+ _gss_mg_error(mn->gmn_mech, *minor_status);
+
+ return major_status;
+}
+
+static OM_uint32
+attr_localname(OM_uint32 *minor_status,
+ struct _gss_mechanism_name *mn,
+ gss_buffer_t localname)
+{
+ OM_uint32 major_status = GSS_S_UNAVAILABLE;
+ OM_uint32 tmpMinor;
+ gss_buffer_desc value = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc display_value = GSS_C_EMPTY_BUFFER;
+ int authenticated = 0, complete = 0;
+ int more = -1;
+
+ *minor_status = 0;
+
+ localname->length = 0;
+ localname->value = NULL;
+
+ if (mn->gmn_mech->gm_get_name_attribute == NULL)
+ return GSS_S_UNAVAILABLE;
+
+ major_status = mn->gmn_mech->gm_get_name_attribute(minor_status,
+ mn->gmn_name,
+ GSS_C_ATTR_LOCAL_LOGIN_USER,
+ &authenticated,
+ &complete,
+ &value,
+ &display_value,
+ &more);
+ if (GSS_ERROR(major_status)) {
+ _gss_mg_error(mn->gmn_mech, *minor_status);
+ return major_status;
+ }
+
+ if (authenticated) {
+ *localname = value;
+ } else {
+ major_status = GSS_S_UNAVAILABLE;
+ gss_release_buffer(&tmpMinor, &value);
+ }
+
+ gss_release_buffer(&tmpMinor, &display_value);
+
+ return major_status;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_localname(OM_uint32 *minor_status,
+ gss_const_name_t pname,
+ const gss_OID mech_type,
+ gss_buffer_t localname)
+{
+ OM_uint32 major_status = GSS_S_UNAVAILABLE;
+ struct _gss_name *name = (struct _gss_name *) pname;
+ struct _gss_mechanism_name *mn = NULL;
+
+ *minor_status = 0;
+
+ if (mech_type != GSS_C_NO_OID) {
+ major_status = _gss_find_mn(minor_status, name, mech_type, &mn);
+ if (GSS_ERROR(major_status))
+ return major_status;
+
+ major_status = mech_localname(minor_status, mn, localname);
+ if (major_status != GSS_S_COMPLETE)
+ major_status = attr_localname(minor_status, mn, localname);
+ } else {
+ HEIM_TAILQ_FOREACH(mn, &name->gn_mn, gmn_link) {
+ major_status = mech_localname(minor_status, mn, localname);
+ if (major_status != GSS_S_COMPLETE)
+ major_status = attr_localname(minor_status, mn, localname);
+ if (major_status != GSS_S_UNAVAILABLE)
+ break;
+ }
+ }
+
+ if (major_status != GSS_S_COMPLETE && mn != NULL)
+ _gss_mg_error(mn->gmn_mech, *minor_status);
+
+ return major_status;
+}
+
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_pname_to_uid(OM_uint32 *minor_status,
+ gss_const_name_t pname,
+ const gss_OID mech_type,
+ uid_t *uidp)
+{
+#ifdef NO_LOCALNAME
+ return GSS_S_UNAVAILABLE;
+#else
+ OM_uint32 major, tmpMinor;
+ gss_buffer_desc localname = GSS_C_EMPTY_BUFFER;
+ char *szLocalname;
+#ifdef POSIX_GETPWNAM_R
+ char pwbuf[2048];
+ struct passwd pw, *pwd;
+#else
+ struct passwd *pwd;
+#endif
+
+ major = gss_localname(minor_status, pname, mech_type, &localname);
+ if (GSS_ERROR(major))
+ return major;
+ if (localname.length == 0) {
+ *minor_status = KRB5_NO_LOCALNAME;
+ return GSS_S_FAILURE;
+ }
+
+ szLocalname = malloc(localname.length + 1);
+ if (szLocalname == NULL) {
+ gss_release_buffer(&tmpMinor, &localname);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ memcpy(szLocalname, localname.value, localname.length);
+ szLocalname[localname.length] = '\0';
+
+#ifdef POSIX_GETPWNAM_R
+ if (getpwnam_r(szLocalname, &pw, pwbuf, sizeof(pwbuf), &pwd) != 0)
+ pwd = NULL;
+#else
+ pwd = getpwnam(szLocalname);
+#endif
+
+ gss_release_buffer(&tmpMinor, &localname);
+ free(szLocalname);
+
+ *minor_status = 0;
+
+ if (pwd != NULL) {
+ *uidp = pwd->pw_uid;
+ major = GSS_S_COMPLETE;
+ } else {
+ major = GSS_S_UNAVAILABLE;
+ }
+
+ return major;
+#endif
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_process_context_token.c b/third_party/heimdal/lib/gssapi/mech/gss_process_context_token.c
new file mode 100644
index 0000000..d10eb47
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_process_context_token.c
@@ -0,0 +1,41 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_process_context_token.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_process_context_token(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t token_buffer)
+{
+ struct _gss_context *ctx = (struct _gss_context *) context_handle;
+ gssapi_mech_interface m = ctx->gc_mech;
+
+ return (m->gm_process_context_token(minor_status, ctx->gc_ctx,
+ token_buffer));
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_pseudo_random.c b/third_party/heimdal/lib/gssapi/mech/gss_pseudo_random.c
new file mode 100644
index 0000000..1b7eb7e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_pseudo_random.c
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_pseudo_random(OM_uint32 *minor_status,
+ gss_ctx_id_t context,
+ int prf_key,
+ const gss_buffer_t prf_in,
+ ssize_t desired_output_len,
+ gss_buffer_t prf_out)
+{
+ struct _gss_context *ctx = (struct _gss_context *) context;
+ gssapi_mech_interface m;
+ OM_uint32 major_status;
+
+ _mg_buffer_zero(prf_out);
+ *minor_status = 0;
+
+ if (ctx == NULL) {
+ *minor_status = 0;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ m = ctx->gc_mech;
+
+ if (m->gm_pseudo_random == NULL)
+ return GSS_S_UNAVAILABLE;
+
+ major_status = (*m->gm_pseudo_random)(minor_status, ctx->gc_ctx,
+ prf_key, prf_in, desired_output_len,
+ prf_out);
+ if (major_status != GSS_S_COMPLETE)
+ _gss_mg_error(m, *minor_status);
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_release_buffer.c b/third_party/heimdal/lib/gssapi/mech/gss_release_buffer.c
new file mode 100644
index 0000000..c3dd457
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_release_buffer.c
@@ -0,0 +1,42 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_release_buffer.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_release_buffer(OM_uint32 *minor_status,
+ gss_buffer_t buffer)
+{
+
+ *minor_status = 0;
+ if (buffer->value)
+ free(buffer->value);
+ _mg_buffer_zero(buffer);
+
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_release_cred.c b/third_party/heimdal/lib/gssapi/mech/gss_release_cred.c
new file mode 100644
index 0000000..3a85de5
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_release_cred.c
@@ -0,0 +1,66 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_release_cred.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+/**
+ * Release a credentials
+ *
+ * Its ok to release the GSS_C_NO_CREDENTIAL/NULL credential, it will
+ * return a GSS_S_COMPLETE error code. On return cred_handle is set ot
+ * GSS_C_NO_CREDENTIAL.
+ *
+ * Example:
+ *
+ * @code
+ * gss_cred_id_t cred = GSS_C_NO_CREDENTIAL;
+ * major = gss_release_cred(&minor, &cred);
+ * @endcode
+ *
+ * @param minor_status minor status return code, mech specific
+ * @param cred_handle a pointer to the credential too release
+ *
+ * @return an gssapi error code
+ *
+ * @ingroup gssapi
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_release_cred(OM_uint32 *minor_status, gss_cred_id_t *cred_handle)
+{
+ struct _gss_cred *cred = (struct _gss_cred *) *cred_handle;
+
+ if (cred == NULL)
+ return (GSS_S_COMPLETE);
+
+ _gss_mg_release_cred(cred);
+
+ *minor_status = 0;
+ *cred_handle = GSS_C_NO_CREDENTIAL;
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_release_name.c b/third_party/heimdal/lib/gssapi/mech/gss_release_name.c
new file mode 100644
index 0000000..db1793e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_release_name.c
@@ -0,0 +1,63 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_release_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+/**
+ * Free a name
+ *
+ * import_name can point to NULL or be NULL, or a pointer to a
+ * gss_name_t structure. If it was a pointer to gss_name_t, the
+ * pointer will be set to NULL on success and failure.
+ *
+ * @param minor_status minor status code
+ * @param input_name name to free
+ *
+ * @returns a gss_error code, see gss_display_status() about printing
+ * the error code.
+ *
+ * @ingroup gssapi
+ */
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_release_name(OM_uint32 *minor_status,
+ gss_name_t *input_name)
+{
+ struct _gss_name *name;
+
+ *minor_status = 0;
+
+ if (input_name == NULL || *input_name == NULL)
+ return GSS_S_COMPLETE;
+
+ name = (struct _gss_name *) *input_name;
+ _gss_mg_release_name(name);
+
+ *input_name = GSS_C_NO_NAME;
+
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_release_oid.c b/third_party/heimdal/lib/gssapi/mech/gss_release_oid.c
new file mode 100644
index 0000000..4f674b0
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_release_oid.c
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_release_oid(OM_uint32 *minor_status, gss_OID *oid)
+{
+ *oid = GSS_C_NO_OID;
+
+ if (minor_status != NULL)
+ *minor_status = 0;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_release_oid_set.c b/third_party/heimdal/lib/gssapi/mech/gss_release_oid_set.c
new file mode 100644
index 0000000..183ddf8
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_release_oid_set.c
@@ -0,0 +1,44 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_release_oid_set.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_release_oid_set(OM_uint32 *minor_status,
+ gss_OID_set *set)
+{
+
+ *minor_status = 0;
+ if (set && *set) {
+ if ((*set)->elements)
+ free((*set)->elements);
+ free(*set);
+ *set = GSS_C_NO_OID_SET;
+ }
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_rfc4121.c b/third_party/heimdal/lib/gssapi/mech/gss_rfc4121.c
new file mode 100644
index 0000000..97a0833
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_rfc4121.c
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "mech_locl.h"
+
+/*
+ * An internal API (for now) to return a mechglue context handle given
+ * a session key that can provide RFC 4121 compatible message protection
+ * and PRF services. Used by SAnon. The implementation of those services
+ * is currently provided by the krb5 GSS mechanism but that is opaque to
+ * the caller (minor status codes notwithstanding).
+ */
+OM_uint32
+_gss_mg_import_rfc4121_context(OM_uint32 *minor,
+ uint8_t initiator_flag,
+ OM_uint32 gss_flags,
+ int32_t rfc3961_enctype,
+ gss_const_buffer_t session_key,
+ gss_ctx_id_t *rfc4121_context_handle)
+{
+ OM_uint32 major = GSS_S_FAILURE, tmpMinor;
+ krb5_storage *sp;
+ krb5_error_code ret;
+ krb5_data d;
+ gss_buffer_desc rfc4121_args = GSS_C_EMPTY_BUFFER;
+
+ krb5_data_zero(&d);
+
+ *minor = 0;
+ *rfc4121_context_handle = GSS_C_NO_CONTEXT;
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_HOST);
+
+ /*
+ * The arguments GSS_KRB5_IMPORT_RFC4121_CONTEXT_X are the serialized
+ * form of initiator_flag || flags || keytype || session_key. The session
+ * key length is inferred from the keytype.
+ */
+ ret = krb5_store_uint8(sp, initiator_flag);
+ if (ret != 0)
+ goto out;
+
+ ret = krb5_store_uint32(sp, gss_flags);
+ if (ret != 0)
+ goto out;
+
+ ret = krb5_store_int32(sp, rfc3961_enctype);
+ if (ret != 0)
+ goto out;
+
+ if (krb5_storage_write(sp, session_key->value, session_key->length)
+ != session_key->length) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ ret = krb5_storage_to_data(sp, &d);
+ if (ret != 0)
+ goto out;
+
+ rfc4121_args.length = d.length;
+ rfc4121_args.value = d.data;
+
+ major = gss_set_sec_context_option(minor, rfc4121_context_handle,
+ GSS_KRB5_IMPORT_RFC4121_CONTEXT_X,
+ &rfc4121_args);
+
+out:
+ _gss_secure_release_buffer(&tmpMinor, &rfc4121_args);
+ krb5_storage_free(sp);
+
+ if (major == GSS_S_FAILURE && *minor == 0)
+ *minor = ret;
+
+ return major;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_seal.c b/third_party/heimdal/lib/gssapi/mech/gss_seal.c
new file mode 100644
index 0000000..26c65da
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_seal.c
@@ -0,0 +1,45 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_seal.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_seal(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ int conf_req_flag,
+ int qop_req,
+ gss_buffer_t input_message_buffer,
+ int *conf_state,
+ gss_buffer_t output_message_buffer)
+{
+
+ return (gss_wrap(minor_status,
+ context_handle, conf_req_flag, qop_req,
+ input_message_buffer, conf_state,
+ output_message_buffer));
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_set_cred_option.c b/third_party/heimdal/lib/gssapi/mech/gss_set_cred_option.c
new file mode 100644
index 0000000..39b49e3
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_set_cred_option.c
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2004, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_set_cred_option (OM_uint32 *minor_status,
+ gss_cred_id_t *cred_handle,
+ const gss_OID object,
+ const gss_buffer_t value)
+{
+ struct _gss_cred *cred = (struct _gss_cred *) *cred_handle;
+ OM_uint32 major_status = GSS_S_COMPLETE;
+ struct _gss_mechanism_cred *mc;
+ int one_ok = 0;
+
+ *minor_status = 0;
+
+ _gss_load_mech();
+
+ if (cred == NULL) {
+ struct _gss_mech_switch *m;
+
+ cred = _gss_mg_alloc_cred();
+ if (cred == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+
+ if (m->gm_mech.gm_set_cred_option == NULL)
+ continue;
+
+ mc = malloc(sizeof(*mc));
+ if (mc == NULL) {
+ *cred_handle = (gss_cred_id_t)cred;
+ gss_release_cred(minor_status, cred_handle);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ mc->gmc_mech = &m->gm_mech;
+ mc->gmc_mech_oid = m->gm_mech_oid;
+ mc->gmc_cred = GSS_C_NO_CREDENTIAL;
+
+ major_status = m->gm_mech.gm_set_cred_option(
+ minor_status, &mc->gmc_cred, object, value);
+
+ if (major_status) {
+ free(mc);
+ continue;
+ }
+ one_ok = 1;
+ HEIM_TAILQ_INSERT_TAIL(&cred->gc_mc, mc, gmc_link);
+ }
+ *cred_handle = (gss_cred_id_t)cred;
+ if (!one_ok) {
+ OM_uint32 junk;
+ gss_release_cred(&junk, cred_handle);
+ }
+ } else {
+ gssapi_mech_interface m;
+
+ HEIM_TAILQ_FOREACH(mc, &cred->gc_mc, gmc_link) {
+ m = mc->gmc_mech;
+
+ if (m == NULL)
+ return GSS_S_BAD_MECH;
+
+ if (m->gm_set_cred_option == NULL)
+ continue;
+
+ major_status = m->gm_set_cred_option(minor_status,
+ &mc->gmc_cred, object, value);
+ if (major_status == GSS_S_COMPLETE)
+ one_ok = 1;
+ else
+ _gss_mg_error(m, *minor_status);
+
+ }
+ }
+ if (one_ok) {
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+ }
+ return major_status;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_set_name_attribute.c b/third_party/heimdal/lib/gssapi/mech/gss_set_name_attribute.c
new file mode 100644
index 0000000..4e963f3
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_set_name_attribute.c
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2010, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_set_name_attribute(OM_uint32 *minor_status,
+ gss_name_t input_name,
+ int complete,
+ gss_buffer_t attr,
+ gss_buffer_t value)
+{
+ OM_uint32 major_status = GSS_S_UNAVAILABLE;
+ struct _gss_name *name = (struct _gss_name *) input_name;
+ struct _gss_mechanism_name *mn;
+
+ *minor_status = 0;
+
+ if (input_name == GSS_C_NO_NAME)
+ return GSS_S_BAD_NAME;
+
+ HEIM_TAILQ_FOREACH(mn, &name->gn_mn, gmn_link) {
+ gssapi_mech_interface m = mn->gmn_mech;
+
+ if (!m->gm_set_name_attribute)
+ continue;
+
+ major_status = m->gm_set_name_attribute(minor_status,
+ mn->gmn_name,
+ complete,
+ attr,
+ value);
+ if (GSS_ERROR(major_status))
+ _gss_mg_error(m, *minor_status);
+ else
+ break;
+ }
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_set_neg_mechs.c b/third_party/heimdal/lib/gssapi/mech/gss_set_neg_mechs.c
new file mode 100644
index 0000000..7c527b2
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_set_neg_mechs.c
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2018, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_set_neg_mechs(OM_uint32 *minor_status,
+ gss_cred_id_t cred_handle,
+ const gss_OID_set mechs)
+{
+ struct _gss_cred *cred = (struct _gss_cred *)cred_handle;
+ OM_uint32 major_status, junk;
+ gss_OID_set tmp_mechs;
+
+ if (minor_status == NULL)
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+
+ *minor_status = 0;
+
+ if (cred_handle == GSS_C_NO_CREDENTIAL || mechs == GSS_C_NO_OID_SET)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+
+ major_status = gss_duplicate_oid_set(minor_status, mechs, &tmp_mechs);
+ if (major_status != GSS_S_COMPLETE)
+ return major_status;
+
+ gss_release_oid_set(&junk, &cred->gc_neg_mechs);
+ cred->gc_neg_mechs = tmp_mechs;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_set_sec_context_option.c b/third_party/heimdal/lib/gssapi/mech/gss_set_sec_context_option.c
new file mode 100644
index 0000000..5b92ac4
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_set_sec_context_option.c
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2004, 2020, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_set_sec_context_option (OM_uint32 *minor_status,
+ gss_ctx_id_t *context_handle,
+ const gss_OID object,
+ const gss_buffer_t value)
+{
+ struct _gss_context *ctx;
+ OM_uint32 major_status;
+ gssapi_mech_interface mi;
+ int allocated_ctx;
+
+ *minor_status = 0;
+
+ if (context_handle == NULL)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+
+ _gss_load_mech();
+
+ ctx = (struct _gss_context *) *context_handle;
+ if (ctx == NULL) {
+ ctx = calloc(1, sizeof(*ctx));
+ if (ctx == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ allocated_ctx = 1;
+ } else {
+ allocated_ctx = 0;
+ }
+
+ major_status = GSS_S_BAD_MECH;
+
+ if (allocated_ctx) {
+ struct _gss_mech_switch *m;
+
+ HEIM_TAILQ_FOREACH(m, &_gss_mechs, gm_link) {
+ mi = &m->gm_mech;
+
+ if (mi->gm_set_sec_context_option == NULL)
+ continue;
+ major_status = mi->gm_set_sec_context_option(minor_status,
+ &ctx->gc_ctx, object, value);
+ if (major_status == GSS_S_COMPLETE) {
+ ctx->gc_mech = mi;
+ break;
+ } else {
+ _gss_mg_error(mi, *minor_status);
+ }
+ }
+ } else {
+ mi = ctx->gc_mech;
+ if (mi->gm_set_sec_context_option != NULL) {
+ major_status = mi->gm_set_sec_context_option(minor_status,
+ &ctx->gc_ctx, object, value);
+ if (major_status != GSS_S_COMPLETE)
+ _gss_mg_error(mi, *minor_status);
+ }
+ }
+
+ if (allocated_ctx) {
+ if (major_status == GSS_S_COMPLETE)
+ *context_handle = (gss_ctx_id_t)ctx;
+ else
+ free(ctx);
+ }
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_sign.c b/third_party/heimdal/lib/gssapi/mech/gss_sign.c
new file mode 100644
index 0000000..4ef99c1
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_sign.c
@@ -0,0 +1,41 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_sign.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_sign(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ int qop_req,
+ gss_buffer_t message_buffer,
+ gss_buffer_t message_token)
+{
+
+ return gss_get_mic(minor_status,
+ context_handle, qop_req, message_buffer, message_token);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_store_cred.c b/third_party/heimdal/lib/gssapi/mech/gss_store_cred.c
new file mode 100644
index 0000000..7a9344a
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_store_cred.c
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+/* See RFC5588 */
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_store_cred(OM_uint32 *minor_status,
+ gss_cred_id_t input_cred_handle,
+ gss_cred_usage_t cred_usage,
+ const gss_OID desired_mech,
+ OM_uint32 overwrite_cred,
+ OM_uint32 default_cred,
+ gss_OID_set *elements_stored,
+ gss_cred_usage_t *cred_usage_stored)
+{
+ return gss_store_cred_into(minor_status,
+ input_cred_handle,
+ cred_usage,
+ desired_mech,
+ overwrite_cred,
+ default_cred,
+ GSS_C_NO_CRED_STORE,
+ elements_stored,
+ cred_usage_stored);
+}
+
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_store_cred_into.c b/third_party/heimdal/lib/gssapi/mech/gss_store_cred_into.c
new file mode 100644
index 0000000..1c739b0
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_store_cred_into.c
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+static OM_uint32
+store_mech_cred(OM_uint32 *minor_status,
+ gssapi_mech_interface m,
+ const struct _gss_mechanism_cred *mc,
+ gss_cred_usage_t input_usage,
+ OM_uint32 store_cred_flags,
+ gss_const_key_value_set_t cred_store,
+ gss_cred_usage_t *usage_stored,
+ gss_buffer_set_t *env)
+{
+ OM_uint32 major_status;
+ OM_uint32 overwrite_cred =
+ !!(store_cred_flags & GSS_C_STORE_CRED_OVERWRITE);
+ OM_uint32 default_cred = !!(store_cred_flags & GSS_C_STORE_CRED_DEFAULT);
+
+ if (m->gm_store_cred_into2)
+ major_status = m->gm_store_cred_into2(minor_status, mc->gmc_cred,
+ input_usage, &m->gm_mech_oid,
+ store_cred_flags, cred_store,
+ NULL, usage_stored,
+ env);
+ else if (m->gm_store_cred_into)
+ major_status = m->gm_store_cred_into(minor_status, mc->gmc_cred,
+ input_usage, &m->gm_mech_oid,
+ overwrite_cred, default_cred,
+ cred_store, NULL, usage_stored);
+ else if (cred_store == GSS_C_NO_CRED_STORE && m->gm_store_cred)
+ major_status = m->gm_store_cred(minor_status, mc->gmc_cred,
+ input_usage, &m->gm_mech_oid,
+ overwrite_cred, default_cred,
+ NULL, usage_stored);
+ else
+ major_status = GSS_S_UNAVAILABLE;
+
+ return major_status;
+}
+
+/*
+ * See RFC5588 for gss_store_cred(). This function is a variant that takes a
+ * const key/value hashmap-like thing that specifies a credential store in a
+ * mechanism- and implementation-specific way, though Heimdal and MIT agree on
+ * at least the following keys for the Kerberos mechanism: ccache, keytab, and
+ * client_keytab. A set of environment variables may be output as well
+ */
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_store_cred_into2(OM_uint32 *minor_status,
+ gss_const_cred_id_t input_cred_handle,
+ gss_cred_usage_t input_usage,
+ const gss_OID desired_mech,
+ OM_uint32 store_cred_flags,
+ gss_const_key_value_set_t cred_store,
+ gss_OID_set *elements_stored,
+ gss_cred_usage_t *cred_usage_stored,
+ gss_buffer_set_t *env)
+{
+ struct _gss_cred *cred = (struct _gss_cred *)input_cred_handle;
+ struct _gss_mechanism_cred *mc;
+ OM_uint32 major_status;
+ OM_uint32 minor;
+ size_t successes;
+
+ if (env != NULL)
+ *env = NULL;
+
+ if (input_cred_handle == NULL)
+ return GSS_S_CALL_INACCESSIBLE_READ;
+
+ if (minor_status == NULL)
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+ *minor_status = 0;
+
+ if (cred_usage_stored)
+ *cred_usage_stored = 0;
+
+ if (elements_stored) {
+ *elements_stored = GSS_C_NO_OID_SET;
+
+ major_status = gss_create_empty_oid_set(minor_status,
+ elements_stored);
+ if (major_status != GSS_S_COMPLETE)
+ return major_status;
+ }
+
+ major_status = GSS_S_NO_CRED;
+ successes = 0;
+
+ HEIM_TAILQ_FOREACH(mc, &cred->gc_mc, gmc_link) {
+ gssapi_mech_interface m = mc->gmc_mech;
+
+ if (m == NULL || (m->gm_flags & GM_USE_MG_CRED) != 0)
+ continue;
+
+ if (desired_mech != GSS_C_NO_OID &&
+ !gss_oid_equal(&m->gm_mech_oid, desired_mech))
+ continue;
+
+ major_status = store_mech_cred(minor_status, m, mc, input_usage,
+ store_cred_flags, cred_store,
+ cred_usage_stored, env);
+ if (major_status == GSS_S_COMPLETE) {
+ if (elements_stored && desired_mech != GSS_C_NO_OID)
+ gss_add_oid_set_member(&minor, desired_mech, elements_stored);
+ successes++;
+ } else if (desired_mech != GSS_C_NO_OID) {
+ _gss_mg_error(m, *minor_status);
+ gss_release_oid_set(&minor, elements_stored);
+ return major_status;
+ }
+ }
+
+ if (successes > 0) {
+ *minor_status = 0;
+ major_status = GSS_S_COMPLETE;
+ }
+
+ heim_assert(successes || major_status != GSS_S_COMPLETE,
+ "cred storage failed, but no error raised");
+
+ return major_status;
+}
+
+/*
+ * See RFC5588 for gss_store_cred(). This function is a variant that takes a
+ * const key/value hashmap-like thing that specifies a credential store in a
+ * mechanism- and implementation-specific way, though Heimdal and MIT agree on
+ * at least the following keys for the Kerberos mechanism: ccache, keytab, and
+ * client_keytab.
+ */
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_store_cred_into(OM_uint32 *minor_status,
+ gss_const_cred_id_t input_cred_handle,
+ gss_cred_usage_t input_usage,
+ const gss_OID desired_mech,
+ OM_uint32 overwrite_cred,
+ OM_uint32 default_cred,
+ gss_const_key_value_set_t cred_store,
+ gss_OID_set *elements_stored,
+ gss_cred_usage_t *cred_usage_stored)
+{
+ OM_uint32 store_cred_flags =
+ (overwrite_cred ? GSS_C_STORE_CRED_OVERWRITE : 0) |
+ (default_cred ? GSS_C_STORE_CRED_DEFAULT : 0);
+ return gss_store_cred_into2(minor_status, input_cred_handle, input_usage,
+ desired_mech, store_cred_flags, cred_store,
+ elements_stored, cred_usage_stored, NULL);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_test_oid_set_member.c b/third_party/heimdal/lib/gssapi/mech/gss_test_oid_set_member.c
new file mode 100644
index 0000000..715d34b
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_test_oid_set_member.c
@@ -0,0 +1,46 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_test_oid_set_member.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_test_oid_set_member(OM_uint32 *minor_status,
+ const gss_OID member,
+ const gss_OID_set set,
+ int *present)
+{
+ size_t i;
+
+ *present = 0;
+ for (i = 0; i < set->count; i++)
+ if (gss_oid_equal(member, &set->elements[i]))
+ *present = 1;
+
+ *minor_status = 0;
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_unseal.c b/third_party/heimdal/lib/gssapi/mech/gss_unseal.c
new file mode 100644
index 0000000..0add03d
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_unseal.c
@@ -0,0 +1,43 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_unseal.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_unseal(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ gss_buffer_t input_message_buffer,
+ gss_buffer_t output_message_buffer,
+ int *conf_state,
+ int *qop_state)
+{
+
+ return (gss_unwrap(minor_status,
+ context_handle, input_message_buffer,
+ output_message_buffer, conf_state, (gss_qop_t *)qop_state));
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_unwrap.c b/third_party/heimdal/lib/gssapi/mech/gss_unwrap.c
new file mode 100644
index 0000000..dd6363b
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_unwrap.c
@@ -0,0 +1,56 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_unwrap.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_unwrap(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t input_message_buffer,
+ gss_buffer_t output_message_buffer,
+ int *conf_state,
+ gss_qop_t *qop_state)
+{
+ struct _gss_context *ctx = (struct _gss_context *) context_handle;
+ gssapi_mech_interface m;
+
+ if (conf_state)
+ *conf_state = 0;
+ if (qop_state)
+ *qop_state = 0;
+
+ if (ctx == NULL) {
+ *minor_status = 0;
+ return GSS_S_NO_CONTEXT;
+ }
+ m = ctx->gc_mech;
+
+ return (m->gm_unwrap(minor_status, ctx->gc_ctx,
+ input_message_buffer, output_message_buffer,
+ conf_state, qop_state));
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_utils.c b/third_party/heimdal/lib/gssapi/mech/gss_utils.c
new file mode 100644
index 0000000..bb7e619
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_utils.c
@@ -0,0 +1,324 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_utils.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+static OM_uint32
+_gss_copy_oid(OM_uint32 *minor_status,
+ gss_const_OID from_oid,
+ gss_OID to_oid)
+{
+ size_t len = from_oid->length;
+
+ *minor_status = 0;
+ to_oid->elements = malloc(len);
+ if (!to_oid->elements) {
+ to_oid->length = 0;
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ to_oid->length = (OM_uint32)len;
+ memcpy(to_oid->elements, from_oid->elements, len);
+ return (GSS_S_COMPLETE);
+}
+
+OM_uint32
+_gss_free_oid(OM_uint32 *minor_status, gss_OID oid)
+{
+ *minor_status = 0;
+ if (oid->elements) {
+ free(oid->elements);
+ oid->elements = NULL;
+ oid->length = 0;
+ }
+ return (GSS_S_COMPLETE);
+}
+
+struct _gss_interned_oid {
+ HEIM_SLIST_ATOMIC_ENTRY(_gss_interned_oid) gio_link;
+ gss_OID_desc gio_oid;
+};
+
+static HEIM_SLIST_ATOMIC_HEAD(_gss_interned_oid_list, _gss_interned_oid) interned_oids =
+HEIM_SLIST_HEAD_INITIALIZER(interned_oids);
+
+extern gss_OID _gss_ot_internal[];
+extern size_t _gss_ot_internal_count;
+
+static OM_uint32
+intern_oid_static(OM_uint32 *minor_status,
+ gss_const_OID from_oid,
+ gss_OID *to_oid)
+{
+ size_t i;
+
+ /* statically allocated OIDs */
+ for (i = 0; i < _gss_ot_internal_count; i++) {
+ if (gss_oid_equal(_gss_ot_internal[i], from_oid)) {
+ *minor_status = 0;
+ *to_oid = _gss_ot_internal[i];
+ return GSS_S_COMPLETE;
+ }
+ }
+
+ return GSS_S_CONTINUE_NEEDED;
+}
+
+OM_uint32
+_gss_intern_oid(OM_uint32 *minor_status,
+ gss_const_OID from_oid,
+ gss_OID *to_oid)
+{
+ OM_uint32 major_status;
+ struct _gss_interned_oid *iop;
+
+ major_status = intern_oid_static(minor_status, from_oid, to_oid);
+ if (major_status != GSS_S_CONTINUE_NEEDED)
+ return major_status;
+
+ HEIM_SLIST_ATOMIC_FOREACH(iop, &interned_oids, gio_link) {
+ if (gss_oid_equal(&iop->gio_oid, from_oid)) {
+ *minor_status = 0;
+ *to_oid = &iop->gio_oid;
+ return GSS_S_COMPLETE;
+ }
+ }
+
+ iop = malloc(sizeof(*iop));
+ if (iop == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ major_status = _gss_copy_oid(minor_status, from_oid, &iop->gio_oid);
+ if (GSS_ERROR(major_status)) {
+ free(iop);
+ return major_status;
+ }
+
+ HEIM_SLIST_ATOMIC_INSERT_HEAD(&interned_oids, iop, gio_link);
+
+ *minor_status = 0;
+ *to_oid = &iop->gio_oid;
+
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_gss_copy_buffer(OM_uint32 *minor_status,
+ const gss_buffer_t from_buf, gss_buffer_t to_buf)
+{
+ size_t len = from_buf->length;
+
+ *minor_status = 0;
+ to_buf->value = malloc(len);
+ if (!to_buf->value) {
+ *minor_status = ENOMEM;
+ to_buf->length = 0;
+ return GSS_S_FAILURE;
+ }
+ to_buf->length = len;
+ memcpy(to_buf->value, from_buf->value, len);
+ return (GSS_S_COMPLETE);
+}
+
+OM_uint32
+_gss_secure_release_buffer(OM_uint32 *minor_status,
+ gss_buffer_t buffer)
+{
+ if (buffer->value)
+ memset_s(buffer->value, buffer->length, 0, buffer->length);
+
+ return gss_release_buffer(minor_status, buffer);
+}
+
+OM_uint32
+_gss_secure_release_buffer_set(OM_uint32 *minor_status,
+ gss_buffer_set_t *buffer_set)
+{
+ size_t i;
+ OM_uint32 minor;
+
+ *minor_status = 0;
+
+ if (*buffer_set == GSS_C_NO_BUFFER_SET)
+ return GSS_S_COMPLETE;
+
+ for (i = 0; i < (*buffer_set)->count; i++)
+ _gss_secure_release_buffer(&minor, &((*buffer_set)->elements[i]));
+
+ (*buffer_set)->count = 0;
+
+ return gss_release_buffer_set(minor_status, buffer_set);
+}
+
+void
+_gss_mg_encode_le_uint32(uint32_t n, uint8_t *p)
+{
+ p[0] = (n >> 0 ) & 0xFF;
+ p[1] = (n >> 8 ) & 0xFF;
+ p[2] = (n >> 16) & 0xFF;
+ p[3] = (n >> 24) & 0xFF;
+}
+
+void
+_gss_mg_decode_le_uint32(const void *ptr, uint32_t *n)
+{
+ const uint8_t *p = ptr;
+ *n = (p[0] << 0) | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
+}
+
+void
+_gss_mg_encode_be_uint32(uint32_t n, uint8_t *p)
+{
+ p[0] = (n >> 24) & 0xFF;
+ p[1] = (n >> 16) & 0xFF;
+ p[2] = (n >> 8 ) & 0xFF;
+ p[3] = (n >> 0 ) & 0xFF;
+}
+
+void
+_gss_mg_decode_be_uint32(const void *ptr, uint32_t *n)
+{
+ const uint8_t *p = ptr;
+ *n = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | (p[3] << 0);
+}
+
+void
+_gss_mg_encode_le_uint16(uint16_t n, uint8_t *p)
+{
+ p[0] = (n >> 0 ) & 0xFF;
+ p[1] = (n >> 8 ) & 0xFF;
+}
+
+void
+_gss_mg_decode_le_uint16(const void *ptr, uint16_t *n)
+{
+ const uint8_t *p = ptr;
+ *n = (p[0] << 0) | (p[1] << 8);
+}
+
+void
+_gss_mg_encode_be_uint16(uint16_t n, uint8_t *p)
+{
+ p[0] = (n >> 8) & 0xFF;
+ p[1] = (n >> 0) & 0xFF;
+}
+
+void
+_gss_mg_decode_be_uint16(const void *ptr, uint16_t *n)
+{
+ const uint8_t *p = ptr;
+ *n = (p[0] << 24) | (p[1] << 16);
+}
+
+OM_uint32
+_gss_mg_ret_oid(OM_uint32 *minor,
+ krb5_storage *sp,
+ gss_OID *oidp)
+{
+ krb5_data data;
+ gss_OID_desc oid;
+ OM_uint32 major;
+
+ *minor = 0;
+ *oidp = GSS_C_NO_OID;
+
+ *minor = krb5_ret_data(sp, &data);
+ if (*minor)
+ return GSS_S_FAILURE;
+
+ if (data.length) {
+ oid.length = data.length;
+ oid.elements = data.data;
+
+ major = _gss_intern_oid(minor, &oid, oidp);
+ } else
+ major = GSS_S_COMPLETE;
+
+ krb5_data_free(&data);
+
+ return major;
+}
+
+OM_uint32
+_gss_mg_store_oid(OM_uint32 *minor,
+ krb5_storage *sp,
+ gss_const_OID oid)
+{
+ krb5_data data;
+
+ if (oid) {
+ data.length = oid->length;
+ data.data = oid->elements;
+ } else
+ krb5_data_zero(&data);
+
+ *minor = krb5_store_data(sp, data);
+
+ return *minor ? GSS_S_FAILURE : GSS_S_COMPLETE;
+}
+
+OM_uint32
+_gss_mg_ret_buffer(OM_uint32 *minor,
+ krb5_storage *sp,
+ gss_buffer_t buffer)
+{
+ krb5_data data;
+
+ _mg_buffer_zero(buffer);
+
+ *minor = krb5_ret_data(sp, &data);
+ if (*minor == 0) {
+ if (data.length) {
+ buffer->length = data.length;
+ buffer->value = data.data;
+ } else
+ krb5_data_free(&data);
+ }
+
+ return *minor ? GSS_S_FAILURE : GSS_S_COMPLETE;
+}
+
+OM_uint32
+_gss_mg_store_buffer(OM_uint32 *minor,
+ krb5_storage *sp,
+ gss_const_buffer_t buffer)
+{
+ krb5_data data;
+
+ if (buffer) {
+ data.length = buffer->length;
+ data.data = buffer->value;
+ } else
+ krb5_data_zero(&data);
+
+ *minor = krb5_store_data(sp, data);
+
+ return *minor ? GSS_S_FAILURE : GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_verify.c b/third_party/heimdal/lib/gssapi/mech/gss_verify.c
new file mode 100644
index 0000000..dd53ddb
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_verify.c
@@ -0,0 +1,42 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_verify.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_verify(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ gss_buffer_t message_buffer,
+ gss_buffer_t token_buffer,
+ int *qop_state)
+{
+
+ return (gss_verify_mic(minor_status,
+ context_handle, message_buffer, token_buffer,
+ (gss_qop_t *)qop_state));
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_verify_mic.c b/third_party/heimdal/lib/gssapi/mech/gss_verify_mic.c
new file mode 100644
index 0000000..ae3b52f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_verify_mic.c
@@ -0,0 +1,52 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_verify_mic.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_verify_mic(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t message_buffer,
+ const gss_buffer_t token_buffer,
+ gss_qop_t *qop_state)
+{
+ struct _gss_context *ctx = (struct _gss_context *) context_handle;
+ gssapi_mech_interface m;
+
+ if (qop_state)
+ *qop_state = 0;
+ if (ctx == NULL) {
+ *minor_status = 0;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ m = ctx->gc_mech;
+
+ return (m->gm_verify_mic(minor_status, ctx->gc_ctx,
+ message_buffer, token_buffer, qop_state));
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_wrap.c b/third_party/heimdal/lib/gssapi/mech/gss_wrap.c
new file mode 100644
index 0000000..82378d3
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_wrap.c
@@ -0,0 +1,71 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_wrap.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+/**
+ * Wrap a message using either confidentiality (encryption +
+ * signature) or sealing (signature).
+ *
+ * @param minor_status minor status code.
+ * @param context_handle context handle.
+ * @param conf_req_flag if non zero, confidentiality is requestd.
+ * @param qop_req type of protection needed, in most cases it GSS_C_QOP_DEFAULT should be passed in.
+ * @param input_message_buffer messages to wrap
+ * @param conf_state returns non zero if confidentiality was honoured.
+ * @param output_message_buffer the resulting buffer, release with gss_release_buffer().
+ *
+ * @ingroup gssapi
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_wrap(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ const gss_buffer_t input_message_buffer,
+ int *conf_state,
+ gss_buffer_t output_message_buffer)
+{
+ struct _gss_context *ctx = (struct _gss_context *) context_handle;
+ gssapi_mech_interface m;
+
+ if (conf_state)
+ *conf_state = 0;
+ _mg_buffer_zero(output_message_buffer);
+ if (ctx == NULL) {
+ *minor_status = 0;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ m = ctx->gc_mech;
+
+ return (m->gm_wrap(minor_status, ctx->gc_ctx,
+ conf_req_flag, qop_req, input_message_buffer,
+ conf_state, output_message_buffer));
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gss_wrap_size_limit.c b/third_party/heimdal/lib/gssapi/mech/gss_wrap_size_limit.c
new file mode 100644
index 0000000..3bcd9ec
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gss_wrap_size_limit.c
@@ -0,0 +1,52 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/gss_wrap_size_limit.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_wrap_size_limit(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ OM_uint32 req_output_size,
+ OM_uint32 *max_input_size)
+{
+ struct _gss_context *ctx = (struct _gss_context *) context_handle;
+ gssapi_mech_interface m;
+
+ *max_input_size = 0;
+ if (ctx == NULL) {
+ *minor_status = 0;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ m = ctx->gc_mech;
+
+ return (m->gm_wrap_size_limit(minor_status, ctx->gc_ctx,
+ conf_req_flag, qop_req, req_output_size, max_input_size));
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gssapi.asn1 b/third_party/heimdal/lib/gssapi/mech/gssapi.asn1
new file mode 100644
index 0000000..96ca6bd
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gssapi.asn1
@@ -0,0 +1,12 @@
+-- $Id$
+
+GSS-API DEFINITIONS ::= BEGIN
+
+IMPORTS HEIM_ANY_SET FROM heim;
+
+GSSAPIContextToken ::= [APPLICATION 0] IMPLICIT SEQUENCE {
+ thisMech OBJECT IDENTIFIER,
+ innerContextToken HEIM_ANY_SET
+}
+
+END
diff --git a/third_party/heimdal/lib/gssapi/mech/gssspi_exchange_meta_data.c b/third_party/heimdal/lib/gssapi/mech/gssspi_exchange_meta_data.c
new file mode 100644
index 0000000..fa98cbd
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gssspi_exchange_meta_data.c
@@ -0,0 +1,115 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ * Portions Copyright (c) 2019 AuriStor, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gssspi_exchange_meta_data(
+ OM_uint32 *minor_status,
+ gss_const_OID input_mech_type,
+ gss_cred_id_t input_cred_handle,
+ gss_ctx_id_t *context_handle,
+ gss_const_name_t target_name,
+ OM_uint32 req_flags,
+ gss_const_buffer_t meta_data)
+{
+ OM_uint32 major_status, junk;
+ gssapi_mech_interface m;
+ struct _gss_name *name = (struct _gss_name *) target_name;
+ struct _gss_mechanism_name *mn;
+ struct _gss_context *ctx = (struct _gss_context *) *context_handle;
+ gss_cred_id_t cred_handle;
+ int allocated_ctx;
+ gss_const_OID mech_type = input_mech_type;
+
+ *minor_status = 0;
+
+ if (mech_type == GSS_C_NO_OID)
+ return GSS_S_BAD_MECH;
+
+ if (ctx == NULL) {
+ ctx = calloc(1, sizeof(struct _gss_context));
+ if (ctx == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ m = ctx->gc_mech = __gss_get_mechanism(mech_type);
+ if (m == NULL) {
+ free(ctx);
+ return GSS_S_BAD_MECH;
+ }
+ allocated_ctx = 1;
+ } else {
+ m = ctx->gc_mech;
+ mech_type = &m->gm_mech_oid;
+ allocated_ctx = 0;
+ }
+
+ if (m->gm_exchange_meta_data == NULL) {
+ major_status = GSS_S_BAD_MECH;
+ goto cleanup;
+ }
+
+ major_status = _gss_find_mn(minor_status, name, mech_type, &mn);
+ if (major_status != GSS_S_COMPLETE)
+ goto cleanup;
+
+ if (m->gm_flags & GM_USE_MG_CRED)
+ cred_handle = input_cred_handle;
+ else
+ cred_handle = _gss_mg_find_mech_cred(input_cred_handle, mech_type);
+
+ if (input_cred_handle != GSS_C_NO_CREDENTIAL &&
+ cred_handle == NULL) {
+ major_status = GSS_S_NO_CRED;
+ goto cleanup;
+ }
+
+ /* note: mechanism is not obligated to allocate a context on success */
+ major_status = m->gm_exchange_meta_data(minor_status,
+ mech_type,
+ cred_handle,
+ &ctx->gc_ctx,
+ mn ? mn->gmn_name : GSS_C_NO_NAME,
+ req_flags,
+ meta_data);
+ if (major_status != GSS_S_COMPLETE)
+ _gss_mg_error(m, *minor_status);
+
+cleanup:
+ if (allocated_ctx && major_status != GSS_S_COMPLETE)
+ gss_delete_sec_context(&junk, (gss_ctx_id_t *)&ctx, GSS_C_NO_BUFFER);
+
+ *context_handle = (gss_ctx_id_t) ctx;
+
+ _gss_mg_log(10, "gss-emd: return %d/%d", (int)major_status, (int)*minor_status);
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gssspi_query_mechanism_info.c b/third_party/heimdal/lib/gssapi/mech/gssspi_query_mechanism_info.c
new file mode 100644
index 0000000..82fe9d9
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gssspi_query_mechanism_info.c
@@ -0,0 +1,55 @@
+/*-
+ * Copyright (c) 2019 AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gssspi_query_mechanism_info(
+ OM_uint32 *minor_status,
+ gss_const_OID mech_type,
+ unsigned char auth_scheme[16])
+{
+ OM_uint32 major_status;
+ gssapi_mech_interface m;
+
+ *minor_status = 0;
+
+ if (mech_type == GSS_C_NO_OID)
+ return GSS_S_BAD_MECH;
+
+ m = __gss_get_mechanism(mech_type);
+ if (m == NULL || m->gm_query_mechanism_info == NULL)
+ return GSS_S_BAD_MECH;
+
+ major_status = m->gm_query_mechanism_info(minor_status,
+ mech_type,
+ auth_scheme);
+
+ if (major_status != GSS_S_COMPLETE)
+ _gss_mg_error(m, *minor_status);
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/gssspi_query_meta_data.c b/third_party/heimdal/lib/gssapi/mech/gssspi_query_meta_data.c
new file mode 100644
index 0000000..490bbc9
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/gssspi_query_meta_data.c
@@ -0,0 +1,117 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ * Portions Copyright (c) 2019 AuriStor, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "mech_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gssspi_query_meta_data(
+ OM_uint32 *minor_status,
+ gss_const_OID input_mech_type,
+ gss_cred_id_t input_cred_handle,
+ gss_ctx_id_t *context_handle,
+ gss_const_name_t target_name,
+ OM_uint32 req_flags,
+ gss_buffer_t meta_data)
+{
+ OM_uint32 major_status, junk;
+ gssapi_mech_interface m;
+ struct _gss_name *name = (struct _gss_name *) target_name;
+ struct _gss_mechanism_name *mn;
+ struct _gss_context *ctx = (struct _gss_context *) *context_handle;
+ gss_cred_id_t cred_handle;
+ int allocated_ctx;
+ gss_const_OID mech_type = input_mech_type;
+
+ *minor_status = 0;
+
+ _mg_buffer_zero(meta_data);
+
+ if (mech_type == GSS_C_NO_OID)
+ return GSS_S_BAD_MECH;
+
+ if (ctx == NULL) {
+ ctx = calloc(1, sizeof(struct _gss_context));
+ if (ctx == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ m = ctx->gc_mech = __gss_get_mechanism(mech_type);
+ if (m == NULL) {
+ free(ctx);
+ return GSS_S_BAD_MECH;
+ }
+ allocated_ctx = 1;
+ } else {
+ m = ctx->gc_mech;
+ mech_type = &m->gm_mech_oid;
+ allocated_ctx = 0;
+ }
+
+ if (m->gm_query_meta_data == NULL) {
+ major_status = GSS_S_BAD_MECH;
+ goto cleanup;
+ }
+
+ major_status = _gss_find_mn(minor_status, name, mech_type, &mn);
+ if (major_status != GSS_S_COMPLETE)
+ goto cleanup;
+
+ if (m->gm_flags & GM_USE_MG_CRED)
+ cred_handle = input_cred_handle;
+ else
+ cred_handle = _gss_mg_find_mech_cred(input_cred_handle, mech_type);
+
+ if (input_cred_handle != GSS_C_NO_CREDENTIAL &&
+ cred_handle == NULL) {
+ major_status = GSS_S_NO_CRED;
+ goto cleanup;
+ }
+
+ /* note: mechanism is not obligated to allocate a context on success */
+ major_status = m->gm_query_meta_data(minor_status,
+ mech_type,
+ cred_handle,
+ &ctx->gc_ctx,
+ mn ? mn->gmn_name : GSS_C_NO_NAME,
+ req_flags,
+ meta_data);
+ if (major_status != GSS_S_COMPLETE)
+ _gss_mg_error(m, *minor_status);
+
+cleanup:
+ if (allocated_ctx && major_status != GSS_S_COMPLETE)
+ gss_delete_sec_context(&junk, (gss_ctx_id_t *)&ctx, GSS_C_NO_BUFFER);
+
+ *context_handle = (gss_ctx_id_t) ctx;
+
+ _gss_mg_log(10, "gss-qmd: return %d/%d", (int)major_status, (int)*minor_status);
+
+ return major_status;
+}
diff --git a/third_party/heimdal/lib/gssapi/mech/mech.5 b/third_party/heimdal/lib/gssapi/mech/mech.5
new file mode 100644
index 0000000..56e916e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/mech.5
@@ -0,0 +1,94 @@
+.\" Copyright (c) 2005 Doug Rabson
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $FreeBSD: src/lib/libgssapi/mech.5,v 1.1 2005/12/29 14:40:20 dfr Exp $
+.Dd November 14, 2005
+.Dt MECH 5
+.Os
+.Sh NAME
+.Nm mech ,
+.Nm qop
+.Nd "GSS-API Mechanism and QOP files"
+.Sh SYNOPSIS
+.Pa "/etc/gss/mech"
+.Pa "/etc/gss/qop"
+.Sh DESCRIPTION
+The
+.Pa "/etc/gss/mech"
+file contains a list of installed GSS-API security mechanisms.
+Each line of the file either contains a comment if the first character
+is '#' or it contains five fields with the following meanings:
+.Bl -tag
+.It Name
+The name of this GSS-API mechanism.
+.It Object identifier
+The OID for this mechanism.
+.It Library
+A shared library containing the implementation of this mechanism.
+.It Kernel module (optional)
+A kernel module containing the implementation of this mechanism (not
+yet supported in FreeBSD).
+.It Library options (optional)
+Optionsal parameters interpreted by the mechanism. Library options
+must be enclosed in brackets ([ ]) to differentiate them from the
+optional kernel module entry.
+.El
+.Pp
+The
+.Pa "/etc/gss/qop"
+file contains a list of Quality of Protection values for use with
+GSS-API.
+Each line of the file either contains a comment if the first character
+is '#' or it contains three fields with the following meanings:
+.Bl -tag
+.It QOP string
+The name of this Quality of Protection algorithm.
+.It QOP value
+The numeric value used to select this algorithm for use with GSS-API
+functions such as
+.Xr gss_get_mic 3 .
+.It Mechanism name
+The GSS-API mechanism name that corresponds to this algorithm.
+.El
+.Sh EXAMPLES
+This is a typical entry from
+.Pa "/etc/gss/mech" :
+.Bd -literal
+kerberosv5 1.2.840.113554.1.2.2 /usr/lib/libgssapi_krb5.so.8 -
+.Ed
+.Pp
+This is a typical entry from
+.Pa "/etc/gss/qop" :
+.Bd -literal
+GSS_KRB5_CONF_C_QOP_DES 0x0100 kerberosv5
+.Ed
+.Sh HISTORY
+The
+.Nm
+manual page example first appeared in
+.Fx 7.0 .
+.Sh AUTHORS
+This
+manual page was written by
+.An Doug Rabson Aq Mt dfr@FreeBSD.org .
diff --git a/third_party/heimdal/lib/gssapi/mech/mech_locl.h b/third_party/heimdal/lib/gssapi/mech/mech_locl.h
new file mode 100644
index 0000000..d451b87
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/mech_locl.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#include <config.h>
+
+#include <roken.h>
+
+#include <krb5-types.h>
+
+#include <ctype.h>
+
+#include <heimbase.h>
+
+#include <gssapi_asn1.h>
+#include <der.h>
+
+#include <gssapi.h>
+#include <gssapi_mech.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
+
+#include <heimqueue.h>
+
+#include "context.h"
+#include "cred.h"
+#include "mech_switch.h"
+#include "name.h"
+#include "utils.h"
+#include "compat.h"
+
+#define _mg_buffer_zero(buffer) \
+ do { \
+ if (buffer) { \
+ (buffer)->value = NULL; \
+ (buffer)->length = 0; \
+ } \
+ } while(0)
+
+#define _mg_oid_set_zero(oid_set) \
+ do { \
+ if (oid_set) { \
+ (oid_set)->elements = NULL; \
+ (oid_set)->count = 0; \
+ } \
+ } while(0)
diff --git a/third_party/heimdal/lib/gssapi/mech/mech_switch.h b/third_party/heimdal/lib/gssapi/mech/mech_switch.h
new file mode 100644
index 0000000..abc89ae
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/mech_switch.h
@@ -0,0 +1,43 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/mech_switch.h,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ * $Id$
+ */
+
+#include <gssapi_mech.h>
+
+struct _gss_mech_switch {
+ HEIM_TAILQ_ENTRY(_gss_mech_switch) gm_link;
+ gss_OID gm_mech_oid;
+ gss_OID_set gm_name_types;
+ void *gm_so;
+ gssapi_mech_interface_desc gm_mech;
+};
+HEIM_TAILQ_HEAD(_gss_mech_switch_list, _gss_mech_switch);
+extern struct _gss_mech_switch_list _gss_mechs;
+extern gss_OID_set _gss_mech_oids;
+
+void _gss_load_mech(void);
diff --git a/third_party/heimdal/lib/gssapi/mech/name.h b/third_party/heimdal/lib/gssapi/mech/name.h
new file mode 100644
index 0000000..4a03486
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/name.h
@@ -0,0 +1,77 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/name.h,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ * $Id$
+ */
+
+struct _gss_mechanism_name {
+ HEIM_TAILQ_ENTRY(_gss_mechanism_name) gmn_link;
+ gssapi_mech_interface gmn_mech; /* mechanism ops for MN */
+ gss_OID gmn_mech_oid; /* mechanism oid for MN */
+ gss_name_t gmn_name; /* underlying MN */
+};
+HEIM_TAILQ_HEAD(_gss_mechanism_name_list, _gss_mechanism_name);
+
+struct _gss_name {
+ gss_OID gn_type; /* type of name */
+ gss_buffer_desc gn_value; /* value (as imported) */
+ struct _gss_mechanism_name_list gn_mn; /* list of MNs */
+};
+
+OM_uint32
+ _gss_find_mn(OM_uint32 *, struct _gss_name *, gss_const_OID,
+ struct _gss_mechanism_name **);
+struct _gss_name *
+ _gss_create_name(gss_name_t new_mn, gssapi_mech_interface m);
+void _gss_mg_release_name(struct _gss_name *);
+
+
+void _gss_mg_check_name(gss_const_name_t name);
+
+gss_name_t
+ _gss_mg_get_underlying_mech_name(gss_name_t name, gss_const_OID mech);
+
+OM_uint32
+_gss_mech_import_name(OM_uint32 * minor_status,
+ gss_const_OID mech,
+ struct _gss_name_type *names,
+ const gss_buffer_t input_name_buffer,
+ gss_const_OID input_name_type,
+ gss_name_t *output_name);
+
+OM_uint32
+gss_mg_export_name(OM_uint32 *minor_status,
+ const gss_const_OID mech,
+ const void *name,
+ size_t length,
+ gss_buffer_t exported_name);
+
+OM_uint32
+_gss_mech_inquire_names_for_mech(OM_uint32 * minor_status,
+ struct _gss_name_type *names,
+ gss_OID_set *name_types);
+
+
diff --git a/third_party/heimdal/lib/gssapi/mech/utils.h b/third_party/heimdal/lib/gssapi/mech/utils.h
new file mode 100644
index 0000000..208a59c
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/mech/utils.h
@@ -0,0 +1,82 @@
+/*-
+ * Copyright (c) 2005 Doug Rabson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD: src/lib/libgssapi/utils.h,v 1.1 2005/12/29 14:40:20 dfr Exp $
+ * $Id$
+ */
+
+OM_uint32 _gss_free_oid(OM_uint32 *, gss_OID);
+OM_uint32 _gss_intern_oid(OM_uint32 *, gss_const_OID, gss_OID *);
+OM_uint32 _gss_copy_buffer(OM_uint32 *minor_status,
+ const gss_buffer_t from_buf, gss_buffer_t to_buf);
+OM_uint32 _gss_secure_release_buffer(OM_uint32 *minor_status,
+ gss_buffer_t buffer);
+OM_uint32 _gss_secure_release_buffer_set(OM_uint32 *minor_status,
+ gss_buffer_set_t *buffer_set);
+
+void _gss_mg_encode_le_uint32(uint32_t n, uint8_t *p);
+void _gss_mg_decode_le_uint32(const void *ptr, uint32_t *n);
+void _gss_mg_encode_be_uint32(uint32_t n, uint8_t *p);
+void _gss_mg_decode_be_uint32(const void *ptr, uint32_t *n);
+
+void _gss_mg_encode_le_uint16(uint16_t n, uint8_t *p);
+void _gss_mg_decode_le_uint16(const void *ptr, uint16_t *n);
+void _gss_mg_encode_be_uint16(uint16_t n, uint8_t *p);
+void _gss_mg_decode_be_uint16(const void *ptr, uint16_t *n);
+
+OM_uint32
+_gss_mg_import_rfc4121_context(OM_uint32 *minor,
+ uint8_t initiator_flag,
+ OM_uint32 gss_flags,
+ int32_t rfc3961_enctype,
+ gss_const_buffer_t session_key,
+ gss_ctx_id_t *rfc4121_context_handle);
+
+#include <krb5.h>
+
+/*
+ * Note: functions below support zero-length OIDs and buffers and will
+ * return NULL values. Callers should handle accordingly.
+ */
+
+OM_uint32
+_gss_mg_ret_oid(OM_uint32 *minor,
+ krb5_storage *sp,
+ gss_OID *oidp);
+
+OM_uint32
+_gss_mg_store_oid(OM_uint32 *minor,
+ krb5_storage *sp,
+ gss_const_OID oid);
+
+OM_uint32
+_gss_mg_ret_buffer(OM_uint32 *minor,
+ krb5_storage *sp,
+ gss_buffer_t buffer);
+
+OM_uint32
+_gss_mg_store_buffer(OM_uint32 *minor,
+ krb5_storage *sp,
+ gss_const_buffer_t buffer);
diff --git a/third_party/heimdal/lib/gssapi/netlogon/accept_sec_context.c b/third_party/heimdal/lib/gssapi/netlogon/accept_sec_context.c
new file mode 100644
index 0000000..06ddfd5
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/accept_sec_context.c
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+/*
+ * Not implemented: this is needed only by domain controllers.
+ */
+
+OM_uint32
+_netlogon_accept_sec_context
+(OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ gss_const_cred_id_t acceptor_cred_handle,
+ const gss_buffer_t input_token_buffer,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_name_t * src_name,
+ gss_OID * mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec,
+ gss_cred_id_t * delegated_cred_handle
+ )
+{
+
+ output_token->value = NULL;
+ output_token->length = 0;
+
+ *minor_status = 0;
+
+ if (context_handle == NULL)
+ return GSS_S_FAILURE;
+
+ if (input_token_buffer == GSS_C_NO_BUFFER)
+ return GSS_S_FAILURE;
+
+ if (src_name)
+ *src_name = GSS_C_NO_NAME;
+ if (mech_type)
+ *mech_type = GSS_C_NO_OID;
+ if (ret_flags)
+ *ret_flags = 0;
+ if (time_rec)
+ *time_rec = 0;
+ if (delegated_cred_handle)
+ *delegated_cred_handle = GSS_C_NO_CREDENTIAL;
+
+ if (*context_handle == GSS_C_NO_CONTEXT) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ } else {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ return GSS_S_UNAVAILABLE;
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/acquire_cred.c b/third_party/heimdal/lib/gssapi/netlogon/acquire_cred.c
new file mode 100644
index 0000000..d790d08
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/acquire_cred.c
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+#include <gssapi_spi.h>
+
+OM_uint32
+_netlogon_acquire_cred(OM_uint32 * min_stat,
+ gss_const_name_t desired_name,
+ OM_uint32 time_req,
+ const gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_cred_id_t * output_cred_handle,
+ gss_OID_set * actual_mechs,
+ OM_uint32 * time_rec)
+{
+ OM_uint32 ret;
+ gssnetlogon_cred cred;
+
+ /* only initiator support so far */
+ if (cred_usage != GSS_C_INITIATE)
+ return GSS_S_FAILURE;
+
+ if (desired_name == GSS_C_NO_NAME)
+ return GSS_S_BAD_NAME;
+
+ cred = (gssnetlogon_cred)calloc(1, sizeof(*cred));
+ if (cred == NULL) {
+ *min_stat = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ cred->SignatureAlgorithm = NL_SIGN_ALG_HMAC_MD5;
+ cred->SealAlgorithm = NL_SEAL_ALG_RC4;
+
+ ret = _netlogon_duplicate_name(min_stat, desired_name,
+ (gss_name_t *)&cred->Name);
+ if (GSS_ERROR(ret)) {
+ free(cred);
+ return ret;
+ }
+
+ *output_cred_handle = (gss_cred_id_t)cred;
+ if (actual_mechs != NULL)
+ *actual_mechs = GSS_C_NO_OID_SET;
+ if (time_rec != NULL)
+ *time_rec = GSS_C_INDEFINITE;
+
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_netlogon_acquire_cred_ex(gss_status_id_t status,
+ gss_const_name_t desired_name,
+ OM_uint32 flags,
+ OM_uint32 time_req,
+ gss_cred_usage_t cred_usage,
+ gss_auth_identity_t identity,
+ void *ctx,
+ void (*complete)(void *, OM_uint32, gss_status_id_t, gss_cred_id_t, OM_uint32))
+{
+ return GSS_S_UNAVAILABLE;
+}
+
+/*
+ * value contains 16 byte session key
+ */
+static OM_uint32
+_netlogon_set_session_key(OM_uint32 *minor_status,
+ gss_cred_id_t *cred_handle,
+ const gss_buffer_t value)
+{
+ gssnetlogon_cred cred;
+
+ if (*cred_handle == GSS_C_NO_CREDENTIAL) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ cred = (gssnetlogon_cred)*cred_handle;
+
+ if (value->length != sizeof(cred->SessionKey)) {
+ *minor_status = ERANGE;
+ return GSS_S_FAILURE;
+ }
+
+ memcpy(cred->SessionKey, value->value, value->length);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+/*
+ * value contains 16 bit little endian encoded seal algorithm
+ */
+static OM_uint32
+_netlogon_set_sign_algorithm(OM_uint32 *minor_status,
+ gss_cred_id_t *cred_handle,
+ const gss_buffer_t value)
+{
+ gssnetlogon_cred cred;
+ uint16_t alg;
+ const uint8_t *p;
+
+ if (*cred_handle == GSS_C_NO_CREDENTIAL) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ cred = (gssnetlogon_cred)*cred_handle;
+
+ if (value->length != 2) {
+ *minor_status = ERANGE;
+ return GSS_S_FAILURE;
+ }
+
+ p = (const uint8_t *)value->value;
+ alg = (p[0] << 0) | (p[1] << 8);
+
+ if (alg != NL_SIGN_ALG_HMAC_MD5 && alg != NL_SIGN_ALG_SHA256) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ cred->SignatureAlgorithm = alg;
+ if (alg == NL_SIGN_ALG_SHA256)
+ cred->SealAlgorithm = NL_SEAL_ALG_AES128;
+ else
+ cred->SealAlgorithm = NL_SEAL_ALG_RC4;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_netlogon_set_cred_option
+ (OM_uint32 *minor_status,
+ gss_cred_id_t *cred_handle,
+ const gss_OID desired_object,
+ const gss_buffer_t value)
+{
+ if (value == GSS_C_NO_BUFFER) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ if (gss_oid_equal(desired_object, GSS_NETLOGON_SET_SESSION_KEY_X))
+ return _netlogon_set_session_key(minor_status, cred_handle, value);
+ else if (gss_oid_equal(desired_object, GSS_NETLOGON_SET_SIGN_ALGORITHM_X))
+ return _netlogon_set_sign_algorithm(minor_status, cred_handle, value);
+
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/netlogon/add_cred.c b/third_party/heimdal/lib/gssapi/netlogon/add_cred.c
new file mode 100644
index 0000000..0222303
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/add_cred.c
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_add_cred (
+ OM_uint32 *minor_status,
+ gss_const_cred_id_t input_cred_handle,
+ gss_const_name_t desired_name,
+ const gss_OID desired_mech,
+ gss_cred_usage_t cred_usage,
+ OM_uint32 initiator_time_req,
+ OM_uint32 acceptor_time_req,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *initiator_time_rec,
+ OM_uint32 *acceptor_time_rec)
+{
+ OM_uint32 ret;
+ int equal;
+ const gssnetlogon_cred src = (const gssnetlogon_cred)input_cred_handle;
+ gssnetlogon_cred dst;
+
+ if (desired_name != GSS_C_NO_NAME) {
+ if (input_cred_handle != GSS_C_NO_CREDENTIAL) {
+ ret = _netlogon_compare_name(minor_status, desired_name,
+ (gss_name_t)src->Name, &equal);
+ if (GSS_ERROR(ret))
+ return ret;
+
+ if (!equal)
+ return GSS_S_BAD_NAME;
+ }
+ }
+
+ ret = _netlogon_acquire_cred(minor_status,
+ input_cred_handle ? (gss_name_t)src->Name : desired_name,
+ initiator_time_req, GSS_C_NO_OID_SET, cred_usage,
+ output_cred_handle, actual_mechs, initiator_time_rec);
+ if (GSS_ERROR(ret))
+ return ret;
+
+ dst = (gssnetlogon_cred)*output_cred_handle;
+
+ if (src != NULL) {
+ dst->SignatureAlgorithm = src->SignatureAlgorithm;
+ dst->SealAlgorithm = src->SealAlgorithm;
+
+ memcpy(dst->SessionKey, src->SessionKey, sizeof(src->SessionKey));
+ }
+
+ if (acceptor_time_rec != NULL)
+ *acceptor_time_rec = 0;
+
+ return GSS_S_COMPLETE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/netlogon/canonicalize_name.c b/third_party/heimdal/lib/gssapi/netlogon/canonicalize_name.c
new file mode 100644
index 0000000..1e8087a
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/canonicalize_name.c
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_canonicalize_name (
+ OM_uint32 * minor_status,
+ gss_const_name_t input_name,
+ const gss_OID mech_type,
+ gss_name_t * output_name
+ )
+{
+ return _netlogon_duplicate_name(minor_status, input_name, output_name);
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/compare_name.c b/third_party/heimdal/lib/gssapi/netlogon/compare_name.c
new file mode 100644
index 0000000..986c3b0
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/compare_name.c
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_compare_name
+ (OM_uint32 * minor_status,
+ gss_const_name_t name1,
+ gss_const_name_t name2,
+ int * name_equal
+ )
+{
+ const gssnetlogon_name n1 = (const gssnetlogon_name)name1;
+ const gssnetlogon_name n2 = (const gssnetlogon_name)name2;
+
+ *name_equal = 0;
+
+ if (n1->NetbiosName.value != NULL && n2->NetbiosName.value != NULL)
+ *name_equal = (strcasecmp((char *)n1->NetbiosName.value,
+ (char *)n2->NetbiosName.value) == 0);
+
+ if (n1->DnsName.value != NULL && n2->DnsName.value != NULL)
+ *name_equal = (strcasecmp((char *)n1->DnsName.value,
+ (char *)n2->DnsName.value) == 0);
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/netlogon/context_time.c b/third_party/heimdal/lib/gssapi/netlogon/context_time.c
new file mode 100644
index 0000000..c7bf9eb
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/context_time.c
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_context_time
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ OM_uint32 * time_rec
+ )
+{
+ if (time_rec != NULL)
+ *time_rec = GSS_C_INDEFINITE;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/crypto.c b/third_party/heimdal/lib/gssapi/netlogon/crypto.c
new file mode 100644
index 0000000..0fc8f01
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/crypto.c
@@ -0,0 +1,733 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+static uint8_t zeros[4];
+
+static void
+_netlogon_encode_sequence_number(uint64_t SequenceNumber, uint8_t *p,
+ int initiatorFlag)
+{
+ uint32_t LowPart, HighPart;
+
+ LowPart = (SequenceNumber >> 0 ) & 0xFFFFFFFF;
+ HighPart = (SequenceNumber >> 32) & 0xFFFFFFFF;
+
+ _gss_mg_encode_be_uint32(LowPart, &p[0]);
+ _gss_mg_encode_be_uint32(HighPart, &p[4]);
+
+ if (initiatorFlag)
+ p[4] |= 0x80;
+}
+
+static int
+_netlogon_decode_sequence_number(void *ptr, uint64_t *n,
+ int initiatorFlag)
+{
+ uint8_t *p = ptr;
+ uint32_t LowPart, HighPart;
+ int gotInitiatorFlag;
+
+ gotInitiatorFlag = (p[4] & 0x80) != 0;
+ if (gotInitiatorFlag != initiatorFlag)
+ return -1;
+
+ p[4] &= 0x7F; /* clear initiator bit */
+
+ _gss_mg_decode_be_uint32(&p[0], &LowPart);
+ _gss_mg_decode_be_uint32(&p[4], &HighPart);
+
+ *n = (LowPart << 0) | ((uint64_t)HighPart << 32);
+
+ return 0;
+}
+
+static inline size_t
+_netlogon_checksum_length(NL_AUTH_SIGNATURE *sig)
+{
+#if 0
+ return (sig->SignatureAlgorithm == NL_SIGN_ALG_SHA256) ? 32 : 8;
+#else
+ /* Owing to a bug in Windows it always uses the old value */
+ return 8;
+#endif
+}
+
+static inline size_t
+_netlogon_signature_length(uint16_t alg, int conf_req_flag)
+{
+ return NL_AUTH_SIGNATURE_COMMON_LENGTH +
+ (alg == NL_SIGN_ALG_SHA256 ? 32 : 8) +
+ (conf_req_flag ? 8 : 0);
+}
+
+static inline uint8_t *
+_netlogon_confounder(NL_AUTH_SIGNATURE *sig)
+{
+ size_t cksumlen = _netlogon_checksum_length(sig);
+
+ return &sig->Checksum[cksumlen];
+}
+
+static int
+_netlogon_encode_NL_AUTH_SIGNATURE(NL_AUTH_SIGNATURE *sig,
+ uint8_t *p, size_t len)
+{
+ *p++ = (sig->SignatureAlgorithm >> 0) & 0xFF;
+ *p++ = (sig->SignatureAlgorithm >> 8) & 0xFF;
+ *p++ = (sig->SealAlgorithm >> 0) & 0xFF;
+ *p++ = (sig->SealAlgorithm >> 8) & 0xFF;
+ *p++ = (sig->Pad >> 0) & 0xFF;
+ *p++ = (sig->Pad >> 8) & 0xFF;
+ *p++ = (sig->Flags >> 0) & 0xFF;
+ *p++ = (sig->Flags >> 8) & 0xFF;
+
+ if (len > NL_AUTH_SIGNATURE_HEADER_LENGTH) {
+ memcpy(p, sig->SequenceNumber, 8);
+ p += 8;
+ }
+
+ if (len > NL_AUTH_SIGNATURE_COMMON_LENGTH) {
+ size_t cksumlen = _netlogon_checksum_length(sig);
+
+ memcpy(p, sig->Checksum, cksumlen);
+ p += cksumlen;
+
+ /* Confounder, if present, is immediately after checksum */
+ if (sig->SealAlgorithm != NL_SEAL_ALG_NONE) {
+ memcpy(p, &sig->Checksum[cksumlen], 8);
+ }
+ }
+
+ return 0;
+}
+
+static int
+_netlogon_decode_NL_AUTH_SIGNATURE(const uint8_t *ptr,
+ size_t len,
+ NL_AUTH_SIGNATURE *sig)
+{
+ const uint8_t *p = ptr;
+ size_t cksumlen;
+
+ if (len < NL_AUTH_SIGNATURE_COMMON_LENGTH)
+ return KRB5_BAD_MSIZE;
+
+ sig->SignatureAlgorithm = (p[0] << 0) | (p[1] << 8);
+ sig->SealAlgorithm = (p[2] << 0) | (p[3] << 8);
+ sig->Pad = (p[4] << 0) | (p[5] << 8);
+ sig->Flags = (p[6] << 0) | (p[7] << 8);
+ p += 8;
+
+ memcpy(sig->SequenceNumber, p, 8);
+ p += 8;
+
+ /* Validate signature algorithm is known and matches enctype */
+ switch (sig->SignatureAlgorithm) {
+ case NL_SIGN_ALG_HMAC_MD5:
+ cksumlen = NL_AUTH_SIGNATURE_LENGTH;
+ break;
+ case NL_SIGN_ALG_SHA256:
+ cksumlen = NL_AUTH_SHA2_SIGNATURE_LENGTH;
+ break;
+ default:
+ return EINVAL;
+ break;
+ }
+
+ if (sig->SealAlgorithm == NL_SEAL_ALG_NONE)
+ cksumlen -= 8; /* confounder is optional if no sealing */
+
+ if (len < cksumlen)
+ return KRB5_BAD_MSIZE;
+
+ /* Copy variable length checksum */
+ cksumlen = _netlogon_checksum_length(sig);
+ memcpy(sig->Checksum, p, cksumlen);
+ p += cksumlen;
+
+ /* Copy confounder in past checksum */
+ if (sig->SealAlgorithm != NL_SEAL_ALG_NONE)
+ memcpy(&sig->Checksum[cksumlen], p, 8);
+
+ return 0;
+}
+
+static void
+_netlogon_derive_rc4_hmac_key(uint8_t key[16],
+ uint8_t *salt,
+ size_t saltLength,
+ EVP_CIPHER_CTX *rc4Key,
+ int enc)
+{
+ uint8_t tmpData[MD5_DIGEST_LENGTH];
+ uint8_t derivedKey[MD5_DIGEST_LENGTH];
+ unsigned int len = MD5_DIGEST_LENGTH;
+
+ HMAC(EVP_md5(), key, 16, zeros, sizeof(zeros), tmpData, &len);
+ HMAC(EVP_md5(), tmpData, MD5_DIGEST_LENGTH,
+ salt, saltLength, derivedKey, &len);
+
+ assert(len == MD5_DIGEST_LENGTH);
+
+ EVP_CipherInit_ex(rc4Key, EVP_rc4(), NULL, derivedKey, NULL, enc);
+
+ memset(derivedKey, 0, sizeof(derivedKey));
+}
+
+static void
+_netlogon_derive_rc4_seal_key(gssnetlogon_ctx ctx,
+ NL_AUTH_SIGNATURE *sig,
+ EVP_CIPHER_CTX *sealkey,
+ int enc)
+{
+ uint8_t xorKey[16];
+ int i;
+
+ for (i = 0; i < sizeof(xorKey); i++) {
+ xorKey[i] = ctx->SessionKey[i] ^ 0xF0;
+ }
+
+ _netlogon_derive_rc4_hmac_key(xorKey,
+ sig->SequenceNumber, sizeof(sig->SequenceNumber), sealkey, enc);
+
+ memset(xorKey, 0, sizeof(xorKey));
+}
+
+static void
+_netlogon_derive_rc4_seq_key(gssnetlogon_ctx ctx,
+ NL_AUTH_SIGNATURE *sig,
+ EVP_CIPHER_CTX *seqkey,
+ int enc)
+{
+ _netlogon_derive_rc4_hmac_key(ctx->SessionKey,
+ sig->Checksum, sizeof(sig->Checksum), seqkey, enc);
+}
+
+static void
+_netlogon_derive_aes_seal_key(gssnetlogon_ctx ctx,
+ NL_AUTH_SIGNATURE *sig,
+ EVP_CIPHER_CTX *sealkey,
+ int enc)
+{
+ uint8_t encryptionKey[16];
+ uint8_t ivec[16];
+ int i;
+
+ for (i = 0; i < sizeof(encryptionKey); i++) {
+ encryptionKey[i] = ctx->SessionKey[i] ^ 0xF0;
+ }
+
+ memcpy(&ivec[0], sig->SequenceNumber, 8);
+ memcpy(&ivec[8], sig->SequenceNumber, 8);
+
+ EVP_CipherInit_ex(sealkey, EVP_aes_128_cfb8(),
+ NULL, encryptionKey, ivec, enc);
+
+ memset(encryptionKey, 0, sizeof(encryptionKey));
+}
+
+static void
+_netlogon_derive_aes_seq_key(gssnetlogon_ctx ctx,
+ NL_AUTH_SIGNATURE *sig,
+ EVP_CIPHER_CTX *seqkey,
+ int enc)
+{
+ uint8_t ivec[16];
+
+ memcpy(&ivec[0], sig->Checksum, 8);
+ memcpy(&ivec[8], sig->Checksum, 8);
+
+ EVP_CipherInit_ex(seqkey, EVP_aes_128_cfb8(),
+ NULL, ctx->SessionKey, ivec, enc);
+}
+
+static void
+_netlogon_seal(gssnetlogon_ctx ctx,
+ NL_AUTH_SIGNATURE *sig,
+ gss_iov_buffer_desc *iov,
+ int iov_count,
+ int enc)
+{
+ EVP_CIPHER_CTX sealkey;
+ int i;
+ uint8_t *confounder = _netlogon_confounder(sig);
+
+ EVP_CIPHER_CTX_init(&sealkey);
+
+ if (sig->SealAlgorithm == NL_SEAL_ALG_AES128)
+ _netlogon_derive_aes_seal_key(ctx, sig, &sealkey, enc);
+ else
+ _netlogon_derive_rc4_seal_key(ctx, sig, &sealkey, enc);
+
+ EVP_Cipher(&sealkey, confounder, confounder, 8);
+
+ /*
+ * For RC4, Windows resets the cipherstate after encrypting
+ * the confounder, thus defeating the purpose of the confounder
+ */
+ if (sig->SealAlgorithm == NL_SEAL_ALG_RC4) {
+ EVP_CipherFinal_ex(&sealkey, NULL, &i);
+ _netlogon_derive_rc4_seal_key(ctx, sig, &sealkey, enc);
+ }
+
+ for (i = 0; i < iov_count; i++) {
+ gss_iov_buffer_t iovp = &iov[i];
+
+ switch (GSS_IOV_BUFFER_TYPE(iovp->type)) {
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ case GSS_IOV_BUFFER_TYPE_PADDING:
+ EVP_Cipher(&sealkey, iovp->buffer.value, iovp->buffer.value,
+ iovp->buffer.length);
+ break;
+ default:
+ break;
+ }
+ }
+
+ EVP_CipherFinal_ex(&sealkey, NULL, &i);
+ EVP_CIPHER_CTX_cleanup(&sealkey);
+}
+
+static void
+_netlogon_seq(gssnetlogon_ctx ctx,
+ NL_AUTH_SIGNATURE *sig,
+ int enc)
+{
+ EVP_CIPHER_CTX seqkey;
+
+ EVP_CIPHER_CTX_init(&seqkey);
+
+ if (sig->SignatureAlgorithm == NL_SIGN_ALG_SHA256)
+ _netlogon_derive_aes_seq_key(ctx, sig, &seqkey, enc);
+ else
+ _netlogon_derive_rc4_seq_key(ctx, sig, &seqkey, enc);
+
+ EVP_Cipher(&seqkey, sig->SequenceNumber, sig->SequenceNumber, 8);
+
+ EVP_CIPHER_CTX_cleanup(&seqkey);
+}
+
+static void
+_netlogon_digest_md5(gssnetlogon_ctx ctx,
+ NL_AUTH_SIGNATURE *sig,
+ gss_iov_buffer_desc *iov,
+ int iov_count,
+ uint8_t *md)
+{
+ EVP_MD_CTX *md5;
+ uint8_t header[NL_AUTH_SIGNATURE_HEADER_LENGTH];
+ uint8_t digest[MD5_DIGEST_LENGTH];
+ unsigned int md_len = MD5_DIGEST_LENGTH;
+ int i;
+
+ _netlogon_encode_NL_AUTH_SIGNATURE(sig, header, sizeof(header));
+
+ md5 = EVP_MD_CTX_create();
+ EVP_DigestInit_ex(md5, EVP_md5(), NULL);
+ EVP_DigestUpdate(md5, zeros, sizeof(zeros));
+ EVP_DigestUpdate(md5, header, sizeof(header));
+
+ if (sig->SealAlgorithm != NL_SEAL_ALG_NONE) {
+ EVP_DigestUpdate(md5, sig->Confounder, sizeof(sig->Confounder));
+ }
+
+ for (i = 0; i < iov_count; i++) {
+ gss_iov_buffer_t iovp = &iov[i];
+
+ switch (GSS_IOV_BUFFER_TYPE(iovp->type)) {
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ case GSS_IOV_BUFFER_TYPE_PADDING:
+ case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+ EVP_DigestUpdate(md5, iovp->buffer.value, iovp->buffer.length);
+ break;
+ default:
+ break;
+ }
+ }
+
+ EVP_DigestFinal_ex(md5, digest, NULL);
+ EVP_MD_CTX_destroy(md5);
+
+ HMAC(EVP_md5(), ctx->SessionKey, sizeof(ctx->SessionKey),
+ digest, sizeof(digest), digest, &md_len);
+ memcpy(md, digest, 8);
+}
+
+static void
+_netlogon_digest_sha256(gssnetlogon_ctx ctx,
+ NL_AUTH_SIGNATURE *sig,
+ gss_iov_buffer_desc *iov,
+ int iov_count,
+ uint8_t *md)
+{
+ HMAC_CTX hmac;
+ uint8_t header[NL_AUTH_SIGNATURE_HEADER_LENGTH];
+ uint8_t digest[SHA256_DIGEST_LENGTH];
+ unsigned int md_len = SHA256_DIGEST_LENGTH;
+ int i;
+
+ /* Encode first 8 bytes of signature into header */
+ _netlogon_encode_NL_AUTH_SIGNATURE(sig, header, sizeof(header));
+
+ HMAC_CTX_init(&hmac);
+ HMAC_Init_ex(&hmac, ctx->SessionKey, sizeof(ctx->SessionKey),
+ EVP_sha256(), NULL);
+ HMAC_Update(&hmac, header, sizeof(header));
+
+ if (sig->SealAlgorithm != NL_SEAL_ALG_NONE) {
+ /*
+ * If the checksum length bug is ever fixed, then be sure to
+ * update this code to point to &sig->Checksum[32] as that is
+ * where the confounder is supposed to be.
+ */
+ HMAC_Update(&hmac, sig->Confounder, 8);
+ }
+
+ for (i = 0; i < iov_count; i++) {
+ gss_iov_buffer_t iovp = &iov[i];
+
+ switch (GSS_IOV_BUFFER_TYPE(iovp->type)) {
+ case GSS_IOV_BUFFER_TYPE_DATA:
+ case GSS_IOV_BUFFER_TYPE_PADDING:
+ case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+ HMAC_Update(&hmac, iovp->buffer.value, iovp->buffer.length);
+ break;
+ default:
+ break;
+ }
+ }
+
+ HMAC_Final(&hmac, digest, &md_len);
+ HMAC_CTX_cleanup(&hmac);
+ memcpy(md, digest, 8);
+}
+
+static void
+_netlogon_digest(gssnetlogon_ctx ctx,
+ NL_AUTH_SIGNATURE *sig,
+ gss_iov_buffer_desc *iov,
+ int iov_count,
+ uint8_t *md)
+{
+ if (sig->SignatureAlgorithm == NL_SIGN_ALG_SHA256)
+ _netlogon_digest_sha256(ctx, sig, iov, iov_count, md);
+ else
+ _netlogon_digest_md5(ctx, sig, iov, iov_count, md);
+}
+
+OM_uint32
+_netlogon_wrap_iov(OM_uint32 * minor_status,
+ gss_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ int *conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ OM_uint32 ret;
+ gss_iov_buffer_t header;
+ NL_AUTH_SIGNATURE_U sigbuf = { { 0 } };
+ NL_AUTH_SIGNATURE *sig = NL_AUTH_SIGNATURE_P(&sigbuf);
+ gssnetlogon_ctx ctx = (gssnetlogon_ctx)context_handle;
+ size_t size;
+ uint8_t *seqdata;
+
+ if (ctx->State != NL_AUTH_ESTABLISHED) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ header = _gss_mg_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER);
+ if (header == NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ size = _netlogon_signature_length(ctx->SignatureAlgorithm, conf_req_flag);
+
+ if (GSS_IOV_BUFFER_FLAGS(header->type) & GSS_IOV_BUFFER_FLAG_ALLOCATE) {
+ ret = _gss_mg_allocate_buffer(minor_status, header, size);
+ if (GSS_ERROR(ret))
+ return ret;
+ } else if (header->buffer.length < size) {
+ *minor_status = KRB5_BAD_MSIZE;
+ return GSS_S_FAILURE;
+ } else {
+ header->buffer.length = size;
+ }
+
+ memset(header->buffer.value, 0, header->buffer.length);
+
+ sig->SignatureAlgorithm = ctx->SignatureAlgorithm;
+ sig->SealAlgorithm = conf_req_flag ? ctx->SealAlgorithm : NL_SEAL_ALG_NONE;
+
+ if (conf_req_flag)
+ krb5_generate_random_block(_netlogon_confounder(sig), 8);
+
+ sig->Pad = 0xFFFF; /* [MS-NRPC] 3.3.4.2.1.3 */
+ sig->Flags = 0; /* [MS-NRPC] 3.3.4.2.1.4 */
+ HEIMDAL_MUTEX_lock(&ctx->Mutex);
+ _netlogon_encode_sequence_number(ctx->SequenceNumber, sig->SequenceNumber,
+ ctx->LocallyInitiated);
+ ctx->SequenceNumber++;
+ HEIMDAL_MUTEX_unlock(&ctx->Mutex);
+
+ /* [MS-NRPC] 3.3.4.2.1.7: sign header, optional confounder and data */
+ _netlogon_digest(ctx, sig, iov, iov_count, sig->Checksum);
+
+ /* [MS-NRPC] 3.3.4.2.1.8: optionally encrypt confounder and data */
+ if (conf_req_flag)
+ _netlogon_seal(ctx, sig, iov, iov_count, 1);
+
+ /* [MS-NRPC] 3.3.4.2.1.9: encrypt sequence number */
+ _netlogon_seq(ctx, sig, 1);
+
+ _netlogon_encode_NL_AUTH_SIGNATURE(sig, header->buffer.value,
+ header->buffer.length);
+
+ if (conf_state != NULL)
+ *conf_state = conf_req_flag;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_netlogon_unwrap_iov(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ int *conf_state,
+ gss_qop_t *qop_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ OM_uint32 ret;
+ gss_iov_buffer_t header;
+ NL_AUTH_SIGNATURE_U sigbuf;
+ NL_AUTH_SIGNATURE *sig = NL_AUTH_SIGNATURE_P(&sigbuf);
+ gssnetlogon_ctx ctx = (gssnetlogon_ctx)context_handle;
+ uint8_t checksum[SHA256_DIGEST_LENGTH];
+ uint64_t SequenceNumber;
+
+ if (ctx->State != NL_AUTH_ESTABLISHED) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ header = _gss_mg_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER);
+ if (header == NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ ret = _netlogon_decode_NL_AUTH_SIGNATURE(header->buffer.value,
+ header->buffer.length,
+ sig);
+ if (ret != 0) {
+ *minor_status = ret;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ /* [MS-NRPC] 3.3.4.2.2.1: verify signature algorithm selection */
+ if (sig->SignatureAlgorithm != ctx->SignatureAlgorithm)
+ return GSS_S_BAD_SIG;
+
+ /* [MS-NRPC] 3.3.4.2.2.2: verify encryption algorithm selection */
+ if (sig->SealAlgorithm != NL_SEAL_ALG_NONE &&
+ sig->SealAlgorithm != ctx->SealAlgorithm)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ /* [MS-NRPC] 3.3.4.2.2.3: verify Pad bytes */
+ if (sig->Pad != 0xFFFF)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ /* [MS-NRPC] 3.3.4.2.2.5: decrypt sequence number */
+ _netlogon_seq(ctx, sig, 0);
+
+ /* [MS-NRPC] 3.3.4.2.2.6: decode sequence number */
+ if (_netlogon_decode_sequence_number(sig->SequenceNumber, &SequenceNumber,
+ !ctx->LocallyInitiated) != 0)
+ return GSS_S_UNSEQ_TOKEN;
+
+ /* [MS-NRPC] 3.3.4.2.2.9: decrypt confounder and data */
+ if (sig->SealAlgorithm != NL_SEAL_ALG_NONE)
+ _netlogon_seal(ctx, sig, iov, iov_count, 0);
+
+ /* [MS-NRPC] 3.3.4.2.2.10: verify signature */
+ _netlogon_digest(ctx, sig, iov, iov_count, checksum);
+ if (memcmp(sig->Checksum, checksum, _netlogon_checksum_length(sig)) != 0)
+ return GSS_S_BAD_SIG;
+
+ HEIMDAL_MUTEX_lock(&ctx->Mutex);
+ if (SequenceNumber != ctx->SequenceNumber) {
+ /* [MS-NRPC] 3.3.4.2.2.7: check sequence number */
+ ret = GSS_S_UNSEQ_TOKEN;
+ } else {
+ /* [MS-NRPC] 3.3.4.2.2.8: increment sequence number */
+ ctx->SequenceNumber++;
+ ret = GSS_S_COMPLETE;
+ }
+ HEIMDAL_MUTEX_unlock(&ctx->Mutex);
+
+ if (conf_state != NULL)
+ *conf_state = (sig->SealAlgorithm != NL_SEAL_ALG_NONE);
+ if (qop_state != NULL)
+ *qop_state = GSS_C_QOP_DEFAULT;
+
+ *minor_status = 0;
+ return ret;
+}
+
+OM_uint32
+_netlogon_wrap_iov_length(OM_uint32 * minor_status,
+ gss_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ int *conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ OM_uint32 ret;
+ gss_iov_buffer_t iovp;
+ gssnetlogon_ctx ctx = (gssnetlogon_ctx)context_handle;
+ size_t len;
+
+ iovp = _gss_mg_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER);
+ if (iovp == NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ len = NL_AUTH_SIGNATURE_COMMON_LENGTH;
+ if (ctx->SignatureAlgorithm == NL_SIGN_ALG_SHA256)
+ len += 32; /* SHA2 checksum size */
+ else
+ len += 8; /* HMAC checksum size */
+ if (conf_req_flag)
+ len += 8; /* counfounder */
+
+ iovp->buffer.length = len;
+
+ iovp = _gss_mg_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_PADDING);
+ if (iovp != NULL)
+ iovp->buffer.length = 0;
+
+ iovp = _gss_mg_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER);
+ if (iovp != NULL)
+ iovp->buffer.length = 0;
+
+ if (conf_state != NULL)
+ *conf_state = conf_req_flag;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 _netlogon_get_mic
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ gss_qop_t qop_req,
+ const gss_buffer_t message_buffer,
+ gss_buffer_t message_token
+ )
+{
+ gss_iov_buffer_desc iov[2];
+ OM_uint32 ret;
+
+ iov[0].type = GSS_IOV_BUFFER_TYPE_DATA;
+ iov[0].buffer = *message_buffer;
+ iov[1].type = GSS_IOV_BUFFER_TYPE_HEADER | GSS_IOV_BUFFER_FLAG_ALLOCATE;
+ iov[1].buffer.length = 0;
+ iov[1].buffer.value = NULL;
+
+ ret = _netlogon_wrap_iov(minor_status, context_handle, 0,
+ qop_req, NULL, iov, 2);
+ if (ret == GSS_S_COMPLETE)
+ *message_token = iov[1].buffer;
+
+ return ret;
+}
+
+OM_uint32
+_netlogon_verify_mic
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t message_buffer,
+ const gss_buffer_t token_buffer,
+ gss_qop_t * qop_state
+ )
+{
+ gss_iov_buffer_desc iov[2];
+
+ iov[0].type = GSS_IOV_BUFFER_TYPE_DATA;
+ iov[0].buffer = *message_buffer;
+ iov[1].type = GSS_IOV_BUFFER_TYPE_HEADER;
+ iov[1].buffer = *token_buffer;
+
+ return _netlogon_unwrap_iov(minor_status, context_handle,
+ NULL, qop_state, iov, 2);
+}
+
+OM_uint32
+_netlogon_wrap_size_limit (
+ OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ OM_uint32 req_output_size,
+ OM_uint32 *max_input_size
+ )
+{
+ gss_iov_buffer_desc iov[1];
+ OM_uint32 ret;
+
+ iov[0].type = GSS_IOV_BUFFER_TYPE_HEADER;
+ iov[0].buffer.length = 0;
+
+ ret = _netlogon_wrap_iov_length(minor_status, context_handle,
+ conf_req_flag, qop_req, NULL,
+ iov, sizeof(iov)/sizeof(iov[0]));
+ if (GSS_ERROR(ret))
+ return ret;
+
+ if (req_output_size < iov[0].buffer.length)
+ *max_input_size = 0;
+ else
+ *max_input_size = req_output_size - iov[0].buffer.length;
+
+ return GSS_S_COMPLETE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/netlogon/delete_sec_context.c b/third_party/heimdal/lib/gssapi/netlogon/delete_sec_context.c
new file mode 100644
index 0000000..8710416
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/delete_sec_context.c
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32
+_netlogon_delete_sec_context(OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ gss_buffer_t output_token)
+{
+ if (context_handle != NULL && *context_handle != GSS_C_NO_CONTEXT) {
+ gssnetlogon_ctx ctx = (gssnetlogon_ctx)*context_handle;
+
+ *context_handle = GSS_C_NO_CONTEXT;
+
+ _netlogon_release_name(minor_status, (gss_name_t *)&ctx->SourceName);
+ _netlogon_release_name(minor_status, (gss_name_t *)&ctx->TargetName);
+ HEIMDAL_MUTEX_destroy(&ctx->Mutex);
+ memset(ctx, 0, sizeof(*ctx));
+ free(ctx);
+ }
+
+ if (output_token != GSS_C_NO_BUFFER) {
+ output_token->length = 0;
+ output_token->value = NULL;
+ }
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/display_name.c b/third_party/heimdal/lib/gssapi/netlogon/display_name.c
new file mode 100644
index 0000000..7b0e223
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/display_name.c
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_display_name
+ (OM_uint32 * minor_status,
+ gss_const_name_t input_name,
+ gss_buffer_t output_name_buffer,
+ gss_OID * output_name_type
+ )
+{
+ const gssnetlogon_name name = (const gssnetlogon_name)input_name;
+ gss_buffer_t namebuf;
+
+ if (output_name_type != NULL)
+ *output_name_type = GSS_C_NO_OID;
+
+ if (output_name_buffer != NULL) {
+ namebuf = name->DnsName.length ? &name->DnsName : &name->NetbiosName;
+
+ output_name_buffer->value = malloc(namebuf->length + 1);
+ if (output_name_buffer->value == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ memcpy(output_name_buffer->value, namebuf->value, namebuf->length);
+ ((char *)output_name_buffer->value)[namebuf->length] = '\0';
+ output_name_buffer->length = namebuf->length;
+ }
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/netlogon/display_status.c b/third_party/heimdal/lib/gssapi/netlogon/display_status.c
new file mode 100644
index 0000000..68946e5
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/display_status.c
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_display_status
+ (OM_uint32 *minor_status,
+ OM_uint32 status_value,
+ int status_type,
+ const gss_OID mech_type,
+ OM_uint32 *message_context,
+ gss_buffer_t status_string)
+{
+ if (minor_status)
+ *minor_status = 0;
+ if (status_string) {
+ status_string->length = 0;
+ status_string->value = NULL;
+ }
+ if (message_context)
+ *message_context = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/duplicate_cred.c b/third_party/heimdal/lib/gssapi/netlogon/duplicate_cred.c
new file mode 100644
index 0000000..0271fb2
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/duplicate_cred.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2010-2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32
+_netlogon_duplicate_cred(OM_uint32 *minor_status,
+ gss_const_cred_id_t input_cred_handle,
+ gss_cred_id_t *output_cred_handle)
+{
+ gssnetlogon_const_cred src = (gssnetlogon_const_cred)input_cred_handle;
+ gssnetlogon_cred dst;
+
+ dst = calloc(1, sizeof(*dst));
+ if (dst == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ *dst = *src;
+ return _netlogon_duplicate_name(minor_status, (gss_name_t)&src->Name, &dst->Name)
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/duplicate_name.c b/third_party/heimdal/lib/gssapi/netlogon/duplicate_name.c
new file mode 100644
index 0000000..1365e76
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/duplicate_name.c
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_duplicate_name (
+ OM_uint32 * minor_status,
+ gss_const_name_t src_name,
+ gss_name_t * dest_name
+ )
+{
+ const gssnetlogon_name src = (const gssnetlogon_name)src_name;
+ gssnetlogon_name dst = NULL;
+
+ dst = calloc(1, sizeof(*dst));
+ if (dst == NULL)
+ goto fail;
+
+ dst->NetbiosName.value = malloc(src->NetbiosName.length + 1);
+ if (dst->NetbiosName.value == NULL)
+ goto fail;
+ memcpy(dst->NetbiosName.value, src->NetbiosName.value,
+ src->NetbiosName.length);
+ dst->NetbiosName.length = src->NetbiosName.length;
+ ((char *)dst->NetbiosName.value)[dst->NetbiosName.length] = '\0';
+
+ if (src->DnsName.length != 0) {
+ dst->DnsName.value = malloc(src->DnsName.length + 1);
+ if (dst->DnsName.value == NULL)
+ goto fail;
+ memcpy(dst->DnsName.value, src->DnsName.value, src->DnsName.length);
+ dst->DnsName.length = src->DnsName.length;
+ ((char *)dst->DnsName.value)[dst->DnsName.length] = '\0';
+ }
+
+ *minor_status = 0;
+ *dest_name = (gss_name_t)dst;
+ return GSS_S_COMPLETE;
+
+fail:
+ _netlogon_release_name(minor_status, (gss_name_t *)&dst);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/netlogon/export_name.c b/third_party/heimdal/lib/gssapi/netlogon/export_name.c
new file mode 100644
index 0000000..9984f8b
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/export_name.c
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_export_name
+ (OM_uint32 * minor_status,
+ gss_const_name_t input_name,
+ gss_buffer_t exported_name
+ )
+{
+ return GSS_S_UNAVAILABLE;
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/export_sec_context.c b/third_party/heimdal/lib/gssapi/netlogon/export_sec_context.c
new file mode 100644
index 0000000..7e410aa
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/export_sec_context.c
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32
+_netlogon_export_sec_context (
+ OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ gss_buffer_t interprocess_token
+ )
+{
+ if (interprocess_token != GSS_C_NO_BUFFER) {
+ interprocess_token->length = 0;
+ interprocess_token->value = NULL;
+ }
+ return GSS_S_UNAVAILABLE;
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/external.c b/third_party/heimdal/lib/gssapi/netlogon/external.c
new file mode 100644
index 0000000..14f471e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/external.c
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2010-2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+static gssapi_mech_interface_desc netlogon_mech = {
+ GMI_VERSION,
+ "netlogon",
+ {6, rk_UNCONST("\x2a\x85\x70\x2b\x0e\x02") },
+ 0,
+ _netlogon_acquire_cred,
+ _netlogon_release_cred,
+ _netlogon_init_sec_context,
+ _netlogon_accept_sec_context,
+ _netlogon_process_context_token,
+ _netlogon_delete_sec_context,
+ _netlogon_context_time,
+ _netlogon_get_mic,
+ _netlogon_verify_mic,
+ NULL,
+ NULL,
+ _netlogon_display_status,
+ NULL,
+ _netlogon_compare_name,
+ _netlogon_display_name,
+ _netlogon_import_name,
+ _netlogon_export_name,
+ _netlogon_release_name,
+ _netlogon_inquire_cred,
+ _netlogon_inquire_context,
+ _netlogon_wrap_size_limit,
+ _netlogon_add_cred,
+ _netlogon_inquire_cred_by_mech,
+ _netlogon_export_sec_context,
+ _netlogon_import_sec_context,
+ _netlogon_inquire_names_for_mech,
+ _netlogon_inquire_mechs_for_name,
+ _netlogon_canonicalize_name,
+ _netlogon_duplicate_name,
+ NULL,
+ NULL,
+ NULL,
+ _netlogon_set_cred_option,
+ NULL,
+ _netlogon_wrap_iov,
+ _netlogon_unwrap_iov,
+ _netlogon_wrap_iov_length,
+ NULL, /* gm_store_cred */
+ NULL, /* gm_export_cred */
+ NULL, /* gm_import_cred */
+ NULL, /* gm_acquire_cred_from */
+ NULL, /* gm_acquire_cred_impersonate_name */
+ NULL, /* gm_iter_creds */
+ NULL, /* gm_destroy_cred */
+ NULL, /* gm_cred_hold */
+ NULL, /* gm_cred_unhold */
+ NULL, /* gm_cred_label_get */
+ NULL, /* gm_cred_label_set */
+ NULL, /* gm_mo */
+ 0, /* gm_mo_num */
+ NULL, /* gm_localname */
+ NULL, /* gm_authorize_localname */
+ NULL, /* gm_display_name_ext */
+ NULL, /* gm_inquire_name */
+ NULL, /* gm_get_name_attribute */
+ NULL, /* gm_set_name_attribute */
+ NULL, /* gm_delete_name_attribute */
+ NULL, /* gm_export_name_composite */
+ NULL, /* gm_duplicate_cred */
+ NULL, /* gm_add_cred_from */
+ NULL, /* gm_store_cred_into */
+ NULL /* gm_compat */
+};
+
+gssapi_mech_interface
+__gss_netlogon_initialize(void)
+{
+ return &netlogon_mech;
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/import_name.c b/third_party/heimdal/lib/gssapi/netlogon/import_name.c
new file mode 100644
index 0000000..aa9191f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/import_name.c
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+#include <ctype.h>
+
+OM_uint32 _netlogon_import_name
+ (OM_uint32 * minor_status,
+ const gss_buffer_t input_name_buffer,
+ const gss_OID input_name_type,
+ gss_name_t * output_name
+ )
+{
+ gssnetlogon_name name;
+ const char *netbiosName;
+ const char *dnsName = NULL;
+ size_t len, i;
+
+ if (!gss_oid_equal(input_name_type, GSS_NETLOGON_NT_NETBIOS_DNS_NAME)) {
+ return GSS_S_BAD_NAME;
+ }
+
+ /* encoding is NetBIOS name \0 DNS name \0 */
+
+ netbiosName = input_name_buffer->value;
+ len = strlen(netbiosName);
+ if (len < input_name_buffer->length)
+ dnsName = netbiosName + len + 1;
+
+ name = (gssnetlogon_name)calloc(1, sizeof(*name));
+ if (name == NULL)
+ goto cleanup;
+
+ name->NetbiosName.value = malloc(len + 1);
+ if (name->NetbiosName.value == NULL)
+ goto cleanup;
+ memcpy(name->NetbiosName.value, netbiosName, len + 1);
+ name->NetbiosName.length = len;
+
+ /* normalise name to uppercase XXX UTF-8 OK? */
+ for (i = 0; i < len; i++) {
+ ((char *)name->NetbiosName.value)[i] =
+ toupper(((char *)name->NetbiosName.value)[i]);
+ }
+
+ if (dnsName != NULL && dnsName[0] != '\0') {
+ name->DnsName.value = strdup(dnsName);
+ if (name->DnsName.value == NULL)
+ goto cleanup;
+ name->DnsName.length = strlen(dnsName);
+ }
+
+ *output_name = (gss_name_t)name;
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+
+cleanup:
+ _netlogon_release_name(minor_status, (gss_name_t *)&name);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/netlogon/import_sec_context.c b/third_party/heimdal/lib/gssapi/netlogon/import_sec_context.c
new file mode 100644
index 0000000..0415b39
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/import_sec_context.c
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32
+_netlogon_import_sec_context (
+ OM_uint32 * minor_status,
+ const gss_buffer_t interprocess_token,
+ gss_ctx_id_t * context_handle
+ )
+{
+ *minor_status = 0;
+ if (context_handle != NULL)
+ *context_handle = GSS_C_NO_CONTEXT;
+
+ return GSS_S_UNAVAILABLE;
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/indicate_mechs.c b/third_party/heimdal/lib/gssapi/netlogon/indicate_mechs.c
new file mode 100644
index 0000000..9192e42
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/indicate_mechs.c
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_indicate_mechs
+(OM_uint32 * minor_status,
+ gss_OID_set * mech_set
+ )
+{
+ *minor_status = 0;
+ if (mech_set != NULL)
+ *mech_set = GSS_C_NO_OID_SET;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/init_sec_context.c b/third_party/heimdal/lib/gssapi/netlogon/init_sec_context.c
new file mode 100644
index 0000000..906f457
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/init_sec_context.c
@@ -0,0 +1,289 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+#include <nameser.h>
+
+static OM_uint32
+_netlogon_encode_dns_string(OM_uint32 *minor_status,
+ const gss_buffer_t str,
+ gss_buffer_t buffer)
+{
+ int ret;
+
+ memset(buffer->value, 0, buffer->length);
+
+ ret = ns_name_compress((const char *)str->value,
+ (uint8_t *)buffer->value, buffer->length,
+ NULL, NULL);
+ if (ret < 0) {
+ *minor_status = errno;
+ return GSS_S_FAILURE;
+ }
+
+ buffer->length = ret;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+_netlogon_make_initial_auth_message(OM_uint32 *minor_status,
+ gssnetlogon_ctx ctx,
+ gss_buffer_t output_token)
+{
+ uint32_t flags = 0;
+#define MAX_NL_NAMES 5
+ gss_buffer_desc names[MAX_NL_NAMES];
+ uint8_t comp_names[3][MAXHOSTNAMELEN * 2];
+ size_t n = 0, i = 0, len;
+ OM_uint32 ret;
+ uint8_t *p;
+
+ if (ctx->TargetName->NetbiosName.length) {
+ flags |= NL_FLAG_NETBIOS_DOMAIN_NAME;
+ names[n] = ctx->TargetName->NetbiosName; /* OEM encoding */
+ names[n].length++;
+ n++;
+ }
+ if (ctx->SourceName->NetbiosName.length) {
+ flags |= NL_FLAG_NETBIOS_COMPUTER_NAME;
+ names[n] = ctx->SourceName->NetbiosName; /* OEM encoding */
+ names[n].length++;
+ n++;
+ }
+ if (ctx->TargetName->DnsName.length) {
+ flags |= NL_FLAG_DNS_DOMAIN_NAME;
+ names[n].value = comp_names[i++];
+ names[n].length = MAXHOSTNAMELEN * 2;
+ ret = _netlogon_encode_dns_string(minor_status,
+ &ctx->TargetName->DnsName,
+ &names[n]);
+ if (GSS_ERROR(ret))
+ return ret;
+ n++;
+ }
+ if (ctx->SourceName->DnsName.length) {
+ flags |= NL_FLAG_DNS_HOST_NAME;
+ names[n].value = comp_names[i++];
+ names[n].length = MAXHOSTNAMELEN * 2;
+ ret = _netlogon_encode_dns_string(minor_status,
+ &ctx->SourceName->DnsName,
+ &names[n]);
+ if (GSS_ERROR(ret))
+ return ret;
+ n++;
+ }
+ if (ctx->SourceName->NetbiosName.length) {
+ flags |= NL_FLAG_UTF8_COMPUTER_NAME;
+ names[n].value = comp_names[i++];
+ names[n].length = MAXHOSTNAMELEN * 2;
+ ret = _netlogon_encode_dns_string(minor_status,
+ &ctx->SourceName->NetbiosName,
+ &names[n]);
+ if (GSS_ERROR(ret))
+ return ret;
+ n++;
+ }
+
+ for (i = 0, len = NL_AUTH_MESSAGE_LENGTH; i < n; i++) {
+ len += names[i].length;
+ }
+
+ output_token->value = malloc(len);
+ if (output_token->value == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ p = (uint8_t *)output_token->value;
+ _gss_mg_encode_le_uint32(NL_NEGOTIATE_REQUEST_MESSAGE, p);
+ _gss_mg_encode_le_uint32(flags, p + 4);
+ p += 8;
+
+ for (i = 0; i < n; i++) {
+ assert(names[i].length != 0);
+ assert(((char *)names[i].value)[names[i].length - 1] == '\0');
+ memcpy(p, names[i].value, names[i].length);
+ p += names[i].length;
+ }
+
+ output_token->length = len;
+ assert(p == (uint8_t *)output_token->value + len);
+
+ *minor_status = 0;
+ return GSS_S_CONTINUE_NEEDED;
+}
+
+static OM_uint32
+_netlogon_read_initial_auth_message(OM_uint32 *minor_status,
+ gssnetlogon_ctx ctx,
+ const gss_buffer_t input_token)
+{
+ NL_AUTH_MESSAGE msg;
+ const uint8_t *p = (const uint8_t *)input_token->value;
+
+ if (ctx->State != NL_AUTH_NEGOTIATE) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ if (input_token->length < NL_AUTH_MESSAGE_LENGTH)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ _gss_mg_decode_le_uint32(&p[0], &msg.MessageType);
+ _gss_mg_decode_le_uint32(&p[4], &msg.Flags);
+
+ if (msg.MessageType != NL_NEGOTIATE_RESPONSE_MESSAGE ||
+ msg.Flags != 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ ctx->State = NL_AUTH_ESTABLISHED;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+_netlogon_alloc_context(OM_uint32 *minor_status,
+ gssnetlogon_ctx *pContext)
+{
+ gssnetlogon_ctx ctx;
+
+ ctx = (gssnetlogon_ctx)calloc(1, sizeof(*ctx));
+ if (ctx == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ ctx->State = NL_AUTH_NEGOTIATE;
+ ctx->LocallyInitiated = 1;
+ ctx->MessageBlockSize = 1;
+
+ HEIMDAL_MUTEX_init(&ctx->Mutex);
+
+ *pContext = ctx;
+
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_netlogon_init_sec_context(OM_uint32 * minor_status,
+ gss_const_cred_id_t initiator_cred_handle,
+ gss_ctx_id_t * context_handle,
+ gss_const_name_t target_name,
+ const gss_OID mech_type,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ const gss_buffer_t input_token,
+ gss_OID * actual_mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec)
+{
+ const gssnetlogon_cred cred = (const gssnetlogon_cred)initiator_cred_handle;
+ gssnetlogon_ctx ctx = (gssnetlogon_ctx)*context_handle;
+ const gssnetlogon_name target = (const gssnetlogon_name)target_name;
+ OM_uint32 ret;
+
+ *minor_status = 0;
+
+ output_token->value = NULL;
+ output_token->length = 0;
+
+ /* Validate arguments */
+ if (cred == NULL)
+ return GSS_S_NO_CRED;
+ else if (target == NULL)
+ return GSS_S_BAD_NAME;
+
+ if (ctx == NULL) {
+ if (input_token->length != 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ ret = _netlogon_alloc_context(minor_status, &ctx);
+ if (GSS_ERROR(ret))
+ goto cleanup;
+
+ HEIMDAL_MUTEX_lock(&ctx->Mutex);
+ *context_handle = (gss_ctx_id_t)ctx;
+
+ ctx->GssFlags = req_flags & (GSS_C_MUTUAL_FLAG | GSS_C_REPLAY_FLAG |
+ GSS_C_SEQUENCE_FLAG | GSS_C_CONF_FLAG |
+ GSS_C_INTEG_FLAG | GSS_C_DCE_STYLE);
+ ctx->SignatureAlgorithm = cred->SignatureAlgorithm;
+ ctx->SealAlgorithm = cred->SealAlgorithm;
+
+ ret = _netlogon_duplicate_name(minor_status, (gss_name_t)cred->Name,
+ (gss_name_t *)&ctx->SourceName);
+ if (GSS_ERROR(ret))
+ goto cleanup;
+
+ ret = _netlogon_duplicate_name(minor_status, (gss_name_t)target,
+ (gss_name_t *)&ctx->TargetName);
+ if (GSS_ERROR(ret))
+ goto cleanup;
+
+ memcpy(ctx->SessionKey, cred->SessionKey, sizeof(cred->SessionKey));
+
+ ret = _netlogon_make_initial_auth_message(minor_status, ctx,
+ output_token);
+ if (GSS_ERROR(ret))
+ goto cleanup;
+ } else {
+ HEIMDAL_MUTEX_lock(&ctx->Mutex);
+ ret = _netlogon_read_initial_auth_message(minor_status, ctx,
+ input_token);
+ }
+
+ if (ret_flags != NULL)
+ *ret_flags = ctx->GssFlags;
+ if (time_rec != NULL)
+ *time_rec = GSS_C_INDEFINITE;
+ if (actual_mech_type != NULL)
+ *actual_mech_type = GSS_NETLOGON_MECHANISM;
+
+cleanup:
+ HEIMDAL_MUTEX_unlock(&ctx->Mutex);
+
+ if (ret != GSS_S_COMPLETE && ret != GSS_S_CONTINUE_NEEDED) {
+ OM_uint32 tmp;
+ _netlogon_delete_sec_context(&tmp, context_handle, NULL);
+ }
+
+ return ret;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/netlogon/inquire_context.c b/third_party/heimdal/lib/gssapi/netlogon/inquire_context.c
new file mode 100644
index 0000000..24995c2
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/inquire_context.c
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_inquire_context (
+ OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ gss_name_t * src_name,
+ gss_name_t * targ_name,
+ OM_uint32 * lifetime_rec,
+ gss_OID * mech_type,
+ OM_uint32 * ctx_flags,
+ int * locally_initiated,
+ int * open_context
+ )
+{
+ const gssnetlogon_ctx ctx = (const gssnetlogon_ctx)context_handle;
+ OM_uint32 ret;
+
+ if (src_name != NULL) {
+ ret = _netlogon_duplicate_name(minor_status, (gss_name_t)ctx->SourceName,
+ (gss_name_t *)src_name);
+ if (GSS_ERROR(ret))
+ return ret;
+ }
+ if (targ_name != NULL) {
+ ret = _netlogon_duplicate_name(minor_status, (gss_name_t)ctx->TargetName,
+ (gss_name_t *)targ_name);
+ if (GSS_ERROR(ret))
+ return ret;
+ }
+ if (mech_type != NULL)
+ *mech_type = GSS_NETLOGON_MECHANISM;
+ if (ctx_flags != NULL)
+ *ctx_flags = ctx->GssFlags;
+ if (locally_initiated != NULL)
+ *locally_initiated = ctx->LocallyInitiated;
+ if (open_context != NULL)
+ *open_context = (ctx->State == NL_AUTH_ESTABLISHED);
+
+ return GSS_S_COMPLETE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/netlogon/inquire_cred.c b/third_party/heimdal/lib/gssapi/netlogon/inquire_cred.c
new file mode 100644
index 0000000..6c7ca34
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/inquire_cred.c
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_inquire_cred
+ (OM_uint32 * minor_status,
+ gss_const_cred_id_t cred_handle,
+ gss_name_t * name,
+ OM_uint32 * lifetime,
+ gss_cred_usage_t * cred_usage,
+ gss_OID_set * mechanisms
+ )
+{
+ OM_uint32 ret;
+ const gssnetlogon_cred cred = (const gssnetlogon_cred)cred_handle;
+
+ *minor_status = 0;
+
+ if (cred == NULL)
+ return GSS_S_NO_CRED;
+
+ if (name != NULL) {
+ ret = _netlogon_duplicate_name(minor_status,
+ (gss_const_name_t)cred->Name, name);
+ if (GSS_ERROR(ret))
+ return ret;
+ }
+ if (lifetime != NULL)
+ *lifetime = GSS_C_INDEFINITE;
+ if (cred_usage != NULL)
+ *cred_usage = GSS_C_INITIATE;
+ if (mechanisms != NULL)
+ *mechanisms = GSS_C_NO_OID_SET;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/inquire_cred_by_mech.c b/third_party/heimdal/lib/gssapi/netlogon/inquire_cred_by_mech.c
new file mode 100644
index 0000000..f36310f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/inquire_cred_by_mech.c
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_inquire_cred_by_mech (
+ OM_uint32 * minor_status,
+ gss_const_cred_id_t cred_handle,
+ const gss_OID mech_type,
+ gss_name_t * name,
+ OM_uint32 * initiator_lifetime,
+ OM_uint32 * acceptor_lifetime,
+ gss_cred_usage_t * cred_usage
+ )
+{
+ OM_uint32 ret;
+ const gssnetlogon_cred cred = (const gssnetlogon_cred)cred_handle;
+
+ if (name != NULL) {
+ ret = _netlogon_duplicate_name(minor_status,
+ (gss_const_name_t)cred->Name, name);
+ if (GSS_ERROR(ret))
+ return ret;
+ }
+ if (initiator_lifetime != NULL)
+ *initiator_lifetime = GSS_C_INDEFINITE;
+ if (acceptor_lifetime != NULL)
+ *acceptor_lifetime = GSS_C_INDEFINITE;
+ if (cred_usage != NULL)
+ *cred_usage = GSS_C_INITIATE;
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/netlogon/inquire_mechs_for_name.c b/third_party/heimdal/lib/gssapi/netlogon/inquire_mechs_for_name.c
new file mode 100644
index 0000000..dbf385c
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/inquire_mechs_for_name.c
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_inquire_mechs_for_name (
+ OM_uint32 * minor_status,
+ gss_const_name_t input_name,
+ gss_OID_set * mech_types
+ )
+{
+ if (mech_types != NULL)
+ *mech_types = GSS_C_NO_OID_SET;
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/inquire_names_for_mech.c b/third_party/heimdal/lib/gssapi/netlogon/inquire_names_for_mech.c
new file mode 100644
index 0000000..9802e53
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/inquire_names_for_mech.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_inquire_names_for_mech (
+ OM_uint32 * minor_status,
+ const gss_OID mechanism,
+ gss_OID_set * name_types
+ )
+{
+ OM_uint32 ret, tmp;
+
+ ret = gss_create_empty_oid_set(minor_status, name_types);
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+
+ ret = gss_add_oid_set_member(minor_status, GSS_NETLOGON_NT_NETBIOS_DNS_NAME, name_types);
+ if (ret != GSS_S_COMPLETE) {
+ gss_release_oid_set(&tmp, name_types);
+ return ret;
+ }
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/iter_cred.c b/third_party/heimdal/lib/gssapi/netlogon/iter_cred.c
new file mode 100644
index 0000000..93a8d59
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/iter_cred.c
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+#include <gssapi_spi.h>
+
+void
+_netlogon_iter_creds_f(OM_uint32 flags,
+ void *userctx ,
+ void (*cred_iter)(void *, gss_OID, gss_cred_id_t))
+{
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/netlogon.h b/third_party/heimdal/lib/gssapi/netlogon/netlogon.h
new file mode 100644
index 0000000..68573e2
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/netlogon.h
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2010-2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef NETLOGON_NETLOGON_H
+#define NETLOGON_NETLOGON_H
+
+#include <config.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <string.h>
+#include <errno.h>
+
+#include <gssapi.h>
+#include <gssapi_mech.h>
+#include <gssapi_netlogon.h>
+
+#include <krb5.h>
+
+#include <roken.h>
+#include <heim_threads.h>
+
+#define HC_DEPRECATED_CRYPTO
+#include "crypto-headers.h"
+
+/*
+ *
+ */
+
+typedef struct {
+#define NL_NEGOTIATE_REQUEST_MESSAGE 0x00000000
+#define NL_NEGOTIATE_RESPONSE_MESSAGE 0x00000001
+ uint32_t MessageType;
+#define NL_FLAG_NETBIOS_DOMAIN_NAME 0x00000001
+#define NL_FLAG_NETBIOS_COMPUTER_NAME 0x00000002
+#define NL_FLAG_DNS_DOMAIN_NAME 0x00000004
+#define NL_FLAG_DNS_HOST_NAME 0x00000008 /* not used */
+#define NL_FLAG_UTF8_COMPUTER_NAME 0x00000010
+ uint32_t Flags;
+ char *Buffer[0];
+} NL_AUTH_MESSAGE;
+
+#define NL_AUTH_MESSAGE_LENGTH 8
+
+/* SignatureAlgorithm */
+#define NL_SIGN_ALG_HMAC_MD5 0x0077
+#define NL_SIGN_ALG_SHA256 0x0013
+
+/* SealAlgorithm */
+#define NL_SEAL_ALG_RC4 0x007A
+#define NL_SEAL_ALG_AES128 0x001A
+#define NL_SEAL_ALG_NONE 0xFFFF
+
+typedef struct {
+ uint16_t SignatureAlgorithm;
+ uint16_t SealAlgorithm;
+ uint16_t Pad;
+ uint16_t Flags;
+ uint8_t SequenceNumber[8];
+ uint8_t Checksum[8];
+ uint8_t Confounder[8];
+} NL_AUTH_SIGNATURE;
+
+#define NL_AUTH_SIGNATURE_HEADER_LENGTH 8
+#define NL_AUTH_SIGNATURE_COMMON_LENGTH 16
+#define NL_AUTH_SIGNATURE_LENGTH 32
+
+typedef struct {
+ uint16_t SignatureAlgorithm;
+ uint16_t SealAlgorithm;
+ uint16_t Pad;
+ uint16_t Flags;
+ uint8_t SequenceNumber[8];
+ uint8_t Checksum[32];
+ uint8_t Confounder[8];
+} NL_AUTH_SHA2_SIGNATURE;
+
+#define NL_AUTH_SHA2_SIGNATURE_LENGTH 56
+
+typedef union {
+ NL_AUTH_SIGNATURE Signature;
+ NL_AUTH_SHA2_SIGNATURE SHA2Signature;
+} NL_AUTH_SIGNATURE_U;
+
+#define NL_AUTH_SIGNATURE_P(_u) (&(_u)->Signature)
+
+typedef struct gssnetlogon_name {
+ gss_buffer_desc NetbiosName;
+ gss_buffer_desc DnsName;
+} *gssnetlogon_name;
+typedef const struct gssnetlogon_name *gssnetlogon_const_name;
+
+typedef struct gssnetlogon_cred {
+ gssnetlogon_name *Name;
+ uint16_t SignatureAlgorithm;
+ uint16_t SealAlgorithm;
+ uint8_t SessionKey[16];
+} *gssnetlogon_cred;
+typedef const struct gssnetlogon_cred *gssnetlogon_const_cred;
+
+typedef struct gssnetlogon_ctx {
+ HEIMDAL_MUTEX Mutex;
+ enum { NL_AUTH_NEGOTIATE, NL_AUTH_ESTABLISHED } State;
+ OM_uint32 GssFlags;
+ uint8_t LocallyInitiated;
+ uint32_t MessageBlockSize;
+ uint16_t SignatureAlgorithm;
+ uint16_t SealAlgorithm;
+ uint64_t SequenceNumber;
+ gssnetlogon_name SourceName;
+ gssnetlogon_name TargetName;
+ uint8_t SessionKey[16];
+} *gssnetlogon_ctx;
+
+#include <netlogon-private.h>
+
+#endif /* NETLOGON_NETLOGON_H */
diff --git a/third_party/heimdal/lib/gssapi/netlogon/process_context_token.c b/third_party/heimdal/lib/gssapi/netlogon/process_context_token.c
new file mode 100644
index 0000000..0f83613
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/process_context_token.c
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_process_context_token (
+ OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t token_buffer
+ )
+{
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/netlogon/regen.sh b/third_party/heimdal/lib/gssapi/netlogon/regen.sh
new file mode 100644
index 0000000..b034dbf
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/regen.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+perl ../../../cf/make-proto.pl -q -P comment -p netlogon-private.h *.c
diff --git a/third_party/heimdal/lib/gssapi/netlogon/release_cred.c b/third_party/heimdal/lib/gssapi/netlogon/release_cred.c
new file mode 100644
index 0000000..7db71b6
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/release_cred.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_release_cred
+ (OM_uint32 * minor_status,
+ gss_cred_id_t * cred_handle
+ )
+{
+ gssnetlogon_cred cred = (gssnetlogon_cred)*cred_handle;
+
+ if (cred != NULL) {
+ _netlogon_release_name(minor_status, (gss_name_t *)&cred->Name);
+ memset(cred, 0, sizeof(*cred));
+ free(cred);
+ *cred_handle = GSS_C_NO_CREDENTIAL;
+ }
+
+ return GSS_S_COMPLETE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/netlogon/release_name.c b/third_party/heimdal/lib/gssapi/netlogon/release_name.c
new file mode 100644
index 0000000..27ca018
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/netlogon/release_name.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "netlogon.h"
+
+OM_uint32 _netlogon_release_name
+ (OM_uint32 * minor_status,
+ gss_name_t * input_name
+ )
+{
+ gssnetlogon_name name = (gssnetlogon_name)*input_name;
+
+ if (name != NULL) {
+ gss_release_buffer(minor_status, &name->NetbiosName);
+ gss_release_buffer(minor_status, &name->DnsName);
+ free(name);
+ *input_name = GSS_C_NO_NAME;
+ }
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/accept_sec_context.c b/third_party/heimdal/lib/gssapi/ntlm/accept_sec_context.c
new file mode 100644
index 0000000..6a3e889
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/accept_sec_context.c
@@ -0,0 +1,256 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+/*
+ *
+ */
+
+OM_uint32
+_gss_ntlm_allocate_ctx(OM_uint32 *minor_status, ntlm_ctx *ctx)
+{
+ OM_uint32 maj_stat;
+ struct ntlm_server_interface *ns_interface = NULL;
+
+#ifdef DIGEST
+ ns_interface = &ntlmsspi_kdc_digest;
+#endif
+ if (ns_interface == NULL)
+ return GSS_S_FAILURE;
+
+ *ctx = calloc(1, sizeof(**ctx));
+ if (*ctx == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ (*ctx)->server = ns_interface;
+
+ maj_stat = (*(*ctx)->server->nsi_init)(minor_status, &(*ctx)->ictx);
+ if (maj_stat == GSS_S_COMPLETE)
+ return GSS_S_COMPLETE;
+
+ if (*ctx)
+ free(*ctx);
+ (*ctx) = NULL;
+
+ return maj_stat;
+}
+
+/*
+ *
+ */
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_accept_sec_context
+(OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ gss_const_cred_id_t acceptor_cred_handle,
+ const gss_buffer_t input_token_buffer,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_name_t * src_name,
+ gss_OID * mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec,
+ gss_cred_id_t * delegated_cred_handle
+ )
+{
+ krb5_error_code ret;
+ struct ntlm_buf data;
+ OM_uint32 junk;
+ ntlm_ctx ctx;
+
+ output_token->value = NULL;
+ output_token->length = 0;
+
+ *minor_status = 0;
+
+ if (context_handle == NULL)
+ return GSS_S_FAILURE;
+
+ if (input_token_buffer == GSS_C_NO_BUFFER)
+ return GSS_S_FAILURE;
+
+ if (src_name)
+ *src_name = GSS_C_NO_NAME;
+ if (mech_type)
+ *mech_type = GSS_C_NO_OID;
+ if (ret_flags)
+ *ret_flags = 0;
+ if (time_rec)
+ *time_rec = 0;
+ if (delegated_cred_handle)
+ *delegated_cred_handle = GSS_C_NO_CREDENTIAL;
+
+ if (*context_handle == GSS_C_NO_CONTEXT) {
+ struct ntlm_type1 type1;
+ OM_uint32 major_status;
+ OM_uint32 retflags;
+ struct ntlm_buf out;
+
+ major_status = _gss_ntlm_allocate_ctx(minor_status, &ctx);
+ if (major_status)
+ return major_status;
+ *context_handle = (gss_ctx_id_t)ctx;
+
+ /* check if the mechs is allowed by remote service */
+ major_status = (*ctx->server->nsi_probe)(minor_status, ctx->ictx, NULL);
+ if (major_status) {
+ _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL);
+ return major_status;
+ }
+
+ data.data = input_token_buffer->value;
+ data.length = input_token_buffer->length;
+
+ ret = heim_ntlm_decode_type1(&data, &type1);
+ if (ret) {
+ _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL);
+ *minor_status = ret;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ if ((type1.flags & NTLM_NEG_UNICODE) == 0) {
+ heim_ntlm_free_type1(&type1);
+ _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ if (type1.flags & NTLM_NEG_SIGN)
+ ctx->gssflags |= GSS_C_CONF_FLAG;
+ if (type1.flags & NTLM_NEG_SIGN)
+ ctx->gssflags |= GSS_C_INTEG_FLAG;
+
+ major_status = (*ctx->server->nsi_type2)(minor_status,
+ ctx->ictx,
+ type1.flags,
+ type1.hostname,
+ type1.domain,
+ &retflags,
+ &out);
+ heim_ntlm_free_type1(&type1);
+ if (major_status != GSS_S_COMPLETE) {
+ OM_uint32 gunk;
+ _gss_ntlm_delete_sec_context(&gunk, context_handle, NULL);
+ return major_status;
+ }
+
+ output_token->value = malloc(out.length);
+ if (output_token->value == NULL && out.length != 0) {
+ OM_uint32 gunk;
+ heim_ntlm_free_buf(&out);
+ _gss_ntlm_delete_sec_context(&gunk, context_handle, NULL);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ memcpy(output_token->value, out.data, out.length);
+ output_token->length = out.length;
+ heim_ntlm_free_buf(&out);
+
+ ctx->flags = retflags;
+
+ return GSS_S_CONTINUE_NEEDED;
+ } else {
+ OM_uint32 maj_stat;
+ struct ntlm_type3 type3;
+ struct ntlm_buf session;
+
+ ctx = (ntlm_ctx)*context_handle;
+
+ data.data = input_token_buffer->value;
+ data.length = input_token_buffer->length;
+
+ ret = heim_ntlm_decode_type3(&data, 1, &type3);
+ if (ret) {
+ _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL);
+ *minor_status = ret;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ maj_stat = (*ctx->server->nsi_type3)(minor_status,
+ ctx->ictx,
+ &type3,
+ &session);
+ if (maj_stat) {
+ heim_ntlm_free_type3(&type3);
+ _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL);
+ return maj_stat;
+ }
+
+ if (src_name) {
+ ntlm_name n = calloc(1, sizeof(*n));
+ if (n) {
+ n->user = strdup(type3.username);
+ n->domain = strdup(type3.targetname);
+ }
+ if (n == NULL || n->user == NULL || n->domain == NULL) {
+ gss_name_t tempn = (gss_name_t)n;
+ _gss_ntlm_release_name(&junk, &tempn);
+ heim_ntlm_free_type3(&type3);
+ _gss_ntlm_delete_sec_context(minor_status,
+ context_handle, NULL);
+ return maj_stat;
+ }
+ *src_name = (gss_name_t)n;
+ }
+
+ heim_ntlm_free_type3(&type3);
+
+ ret = krb5_data_copy(&ctx->sessionkey,
+ session.data, session.length);
+ if (ret) {
+ if (src_name)
+ _gss_ntlm_release_name(&junk, src_name);
+ _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ _gss_ntlm_set_keys(ctx);
+
+ if (mech_type)
+ *mech_type = GSS_NTLM_MECHANISM;
+ if (time_rec)
+ *time_rec = GSS_C_INDEFINITE;
+
+ ctx->status |= STATUS_OPEN;
+
+ if (ret_flags)
+ *ret_flags = ctx->gssflags;
+
+ return GSS_S_COMPLETE;
+ }
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/acquire_cred.c b/third_party/heimdal/lib/gssapi/ntlm/acquire_cred.c
new file mode 100644
index 0000000..a6b151f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/acquire_cred.c
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_acquire_cred_from(OM_uint32 *min_stat,
+ gss_const_name_t desired_name,
+ OM_uint32 time_req,
+ const gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_const_key_value_set_t cred_store,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *time_rec)
+{
+ ntlm_name name = (ntlm_name) desired_name;
+ OM_uint32 maj_stat;
+ ntlm_ctx ctx;
+
+ *min_stat = 0;
+ *output_cred_handle = GSS_C_NO_CREDENTIAL;
+ if (actual_mechs)
+ *actual_mechs = GSS_C_NO_OID_SET;
+ if (time_rec)
+ *time_rec = GSS_C_INDEFINITE;
+
+ if (cred_usage == GSS_C_BOTH || cred_usage == GSS_C_ACCEPT) {
+ int ret;
+
+ maj_stat = _gss_ntlm_allocate_ctx(min_stat, &ctx);
+ if (maj_stat != GSS_S_COMPLETE)
+ return maj_stat;
+
+ ret = (*ctx->server->nsi_probe)(min_stat, ctx->ictx, NULL);
+ {
+ gss_ctx_id_t context = (gss_ctx_id_t)ctx;
+ OM_uint32 junk;
+ _gss_ntlm_delete_sec_context(&junk, &context, NULL);
+ }
+ if (ret) {
+ *min_stat = ret;
+ return GSS_S_NO_CRED;
+ }
+ }
+ if (cred_usage == GSS_C_BOTH || cred_usage == GSS_C_INITIATE) {
+ ntlm_cred cred;
+
+ *min_stat = _gss_ntlm_get_user_cred(name, &cred);
+ if (*min_stat)
+ return GSS_S_NO_CRED;
+ cred->usage = cred_usage;
+
+ *output_cred_handle = (gss_cred_id_t)cred;
+ }
+
+ return (GSS_S_COMPLETE);
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/add_cred.c b/third_party/heimdal/lib/gssapi/ntlm/add_cred.c
new file mode 100644
index 0000000..1517232
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/add_cred.c
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV _gss_ntlm_add_cred (
+ OM_uint32 *minor_status,
+ gss_const_cred_id_t input_cred_handle,
+ gss_const_name_t desired_name,
+ const gss_OID desired_mech,
+ gss_cred_usage_t cred_usage,
+ OM_uint32 initiator_time_req,
+ OM_uint32 acceptor_time_req,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *initiator_time_rec,
+ OM_uint32 *acceptor_time_rec)
+{
+ if (minor_status)
+ *minor_status = 0;
+ if (output_cred_handle)
+ *output_cred_handle = GSS_C_NO_CREDENTIAL;
+ if (actual_mechs)
+ *actual_mechs = GSS_C_NO_OID_SET;
+ if (initiator_time_rec)
+ *initiator_time_rec = 0;
+ if (acceptor_time_rec)
+ *acceptor_time_rec = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/canonicalize_name.c b/third_party/heimdal/lib/gssapi/ntlm/canonicalize_name.c
new file mode 100644
index 0000000..3409b3b
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/canonicalize_name.c
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_canonicalize_name (
+ OM_uint32 * minor_status,
+ gss_const_name_t input_name,
+ const gss_OID mech_type,
+ gss_name_t * output_name
+ )
+{
+ return gss_duplicate_name (minor_status, input_name, output_name);
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/compare_name.c b/third_party/heimdal/lib/gssapi/ntlm/compare_name.c
new file mode 100644
index 0000000..d185ab9
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/compare_name.c
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 1997-2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV _gss_ntlm_compare_name
+ (OM_uint32 * minor_status,
+ gss_const_name_t name1,
+ gss_const_name_t name2,
+ int * name_equal
+ )
+{
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/context_time.c b/third_party/heimdal/lib/gssapi/ntlm/context_time.c
new file mode 100644
index 0000000..589ee2a
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/context_time.c
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV _gss_ntlm_context_time
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ OM_uint32 * time_rec
+ )
+{
+ if (time_rec)
+ *time_rec = GSS_C_INDEFINITE;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/creds.c b/third_party/heimdal/lib/gssapi/ntlm/creds.c
new file mode 100644
index 0000000..5794015
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/creds.c
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_inquire_cred
+ (OM_uint32 * minor_status,
+ gss_const_cred_id_t cred_handle,
+ gss_name_t * name,
+ OM_uint32 * lifetime,
+ gss_cred_usage_t * cred_usage,
+ gss_OID_set * mechanisms
+ )
+{
+ OM_uint32 ret, junk;
+
+ *minor_status = 0;
+
+ if (cred_handle == NULL)
+ return GSS_S_NO_CRED;
+
+ if (name) {
+ ntlm_name n = calloc(1, sizeof(*n));
+ ntlm_cred c = (ntlm_cred)cred_handle;
+ if (n) {
+ n->user = strdup(c->username);
+ n->domain = strdup(c->domain);
+ }
+ if (n == NULL || n->user == NULL || n->domain == NULL) {
+ if (n) {
+ free(n->user);
+ free(n->domain);
+ free(n);
+ }
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ *name = (gss_name_t)n;
+ }
+ if (lifetime)
+ *lifetime = GSS_C_INDEFINITE;
+ if (cred_usage)
+ *cred_usage = 0;
+ if (mechanisms)
+ *mechanisms = GSS_C_NO_OID_SET;
+ if (mechanisms) {
+ ret = gss_create_empty_oid_set(minor_status, mechanisms);
+ if (ret)
+ goto out;
+ ret = gss_add_oid_set_member(minor_status,
+ GSS_NTLM_MECHANISM,
+ mechanisms);
+ if (ret)
+ goto out;
+ }
+
+ return GSS_S_COMPLETE;
+out:
+ gss_release_oid_set(&junk, mechanisms);
+ return ret;
+}
+
+#ifdef HAVE_KCM
+static OM_uint32
+_gss_ntlm_destroy_kcm_cred(gss_cred_id_t *cred_handle)
+{
+ krb5_storage *request, *response;
+ krb5_data response_data;
+ krb5_context context;
+ krb5_error_code ret;
+ ntlm_cred cred;
+
+ cred = (ntlm_cred)*cred_handle;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ return ret;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_DEL_NTLM_CRED, &request);
+ if (ret)
+ goto out;
+
+ ret = krb5_store_stringz(request, cred->username);
+ if (ret)
+ goto out;
+
+ ret = krb5_store_stringz(request, cred->domain);
+ if (ret)
+ goto out;
+
+ ret = krb5_kcm_call(context, request, &response, &response_data);
+ if (ret)
+ goto out;
+
+ krb5_storage_free(request);
+ krb5_storage_free(response);
+ krb5_data_free(&response_data);
+
+ out:
+ krb5_free_context(context);
+
+ return ret;
+}
+#endif /* HAVE_KCM */
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_destroy_cred(OM_uint32 *minor_status,
+ gss_cred_id_t *cred_handle)
+{
+#ifdef HAVE_KCM
+ krb5_error_code ret;
+#endif
+
+ if (cred_handle == NULL || *cred_handle == GSS_C_NO_CREDENTIAL)
+ return GSS_S_COMPLETE;
+
+#ifdef HAVE_KCM
+ ret = _gss_ntlm_destroy_kcm_cred(cred_handle);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+#endif
+
+ return _gss_ntlm_release_cred(minor_status, cred_handle);
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/crypto.c b/third_party/heimdal/lib/gssapi/ntlm/crypto.c
new file mode 100644
index 0000000..efa71d9
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/crypto.c
@@ -0,0 +1,636 @@
+/*
+ * Copyright (c) 2006-2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+struct hx509_certs_data;
+struct krb5_pk_identity;
+struct krb5_pk_cert;
+struct ContentInfo;
+struct AlgorithmIdentifier;
+struct _krb5_krb_auth_data;
+struct krb5_dh_moduli;
+struct _krb5_key_data;
+struct _krb5_encryption_type;
+struct _krb5_key_type;
+#include "krb5_locl.h"
+
+/*
+ *
+ */
+
+static void
+encode_le_uint32(uint32_t n, unsigned char *p)
+{
+ p[0] = (n >> 0) & 0xFF;
+ p[1] = (n >> 8) & 0xFF;
+ p[2] = (n >> 16) & 0xFF;
+ p[3] = (n >> 24) & 0xFF;
+}
+
+
+static void
+decode_le_uint32(const void *ptr, uint32_t *n)
+{
+ const unsigned char *p = ptr;
+ *n = (p[0] << 0) | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
+}
+
+/*
+ *
+ */
+
+const char a2i_signmagic[] =
+ "session key to server-to-client signing key magic constant";
+const char a2i_sealmagic[] =
+ "session key to server-to-client sealing key magic constant";
+const char i2a_signmagic[] =
+ "session key to client-to-server signing key magic constant";
+const char i2a_sealmagic[] =
+ "session key to client-to-server sealing key magic constant";
+
+
+void
+_gss_ntlm_set_key(struct ntlmv2_key *key, int acceptor, int sealsign,
+ unsigned char *data, size_t len)
+{
+ unsigned char out[16];
+ EVP_MD_CTX *ctx;
+ const char *signmagic;
+ const char *sealmagic;
+
+ if (acceptor) {
+ signmagic = a2i_signmagic;
+ sealmagic = a2i_sealmagic;
+ } else {
+ signmagic = i2a_signmagic;
+ sealmagic = i2a_sealmagic;
+ }
+
+ key->seq = 0;
+
+ ctx = EVP_MD_CTX_create();
+ EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
+ EVP_DigestUpdate(ctx, data, len);
+ EVP_DigestUpdate(ctx, signmagic, strlen(signmagic) + 1);
+ EVP_DigestFinal_ex(ctx, key->signkey, NULL);
+
+ EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
+ EVP_DigestUpdate(ctx, data, len);
+ EVP_DigestUpdate(ctx, sealmagic, strlen(sealmagic) + 1);
+ EVP_DigestFinal_ex(ctx, out, NULL);
+ EVP_MD_CTX_destroy(ctx);
+
+ RC4_set_key(&key->sealkey, 16, out);
+ if (sealsign)
+ key->signsealkey = &key->sealkey;
+}
+
+/*
+ * Set (or reset) keys
+ */
+
+void
+_gss_ntlm_set_keys(ntlm_ctx ctx)
+{
+ int acceptor;
+
+ if (ctx->sessionkey.length == 0)
+ return;
+
+ acceptor = !(ctx->status & STATUS_CLIENT);
+
+ ctx->status |= STATUS_SESSIONKEY;
+
+ if (ctx->flags & NTLM_NEG_NTLM2_SESSION) {
+ _gss_ntlm_set_key(&ctx->u.v2.send, acceptor,
+ (ctx->flags & NTLM_NEG_KEYEX),
+ ctx->sessionkey.data,
+ ctx->sessionkey.length);
+ _gss_ntlm_set_key(&ctx->u.v2.recv, !acceptor,
+ (ctx->flags & NTLM_NEG_KEYEX),
+ ctx->sessionkey.data,
+ ctx->sessionkey.length);
+ } else {
+ ctx->u.v1.crypto_send.seq = 0;
+ RC4_set_key(&ctx->u.v1.crypto_send.key,
+ ctx->sessionkey.length,
+ ctx->sessionkey.data);
+ ctx->u.v1.crypto_recv.seq = 0;
+ RC4_set_key(&ctx->u.v1.crypto_recv.key,
+ ctx->sessionkey.length,
+ ctx->sessionkey.data);
+ }
+}
+
+/*
+ *
+ */
+
+static OM_uint32
+v1_sign_message(gss_buffer_t in,
+ RC4_KEY *signkey,
+ uint32_t seq,
+ unsigned char out[16])
+{
+ unsigned char sigature[12];
+ uint32_t crc;
+
+ _krb5_crc_init_table();
+ crc = _krb5_crc_update(in->value, in->length, 0);
+
+ encode_le_uint32(0, &sigature[0]);
+ encode_le_uint32(crc, &sigature[4]);
+ encode_le_uint32(seq, &sigature[8]);
+
+ encode_le_uint32(1, out); /* version */
+ RC4(signkey, sizeof(sigature), sigature, out + 4);
+
+ if (RAND_bytes(out + 4, 4) != 1)
+ return GSS_S_UNAVAILABLE;
+
+ return 0;
+}
+
+
+static OM_uint32
+v2_sign_message(gss_buffer_t in,
+ unsigned char signkey[16],
+ RC4_KEY *sealkey,
+ uint32_t seq,
+ unsigned char out[16])
+{
+ unsigned char hmac[16];
+ unsigned int hmaclen;
+ HMAC_CTX c;
+
+ HMAC_CTX_init(&c);
+ if (HMAC_Init_ex(&c, signkey, 16, EVP_md5(), NULL) == 0) {
+ HMAC_CTX_cleanup(&c);
+ return GSS_S_FAILURE;
+ }
+
+ encode_le_uint32(seq, hmac);
+ HMAC_Update(&c, hmac, 4);
+ HMAC_Update(&c, in->value, in->length);
+ HMAC_Final(&c, hmac, &hmaclen);
+ HMAC_CTX_cleanup(&c);
+
+ encode_le_uint32(1, &out[0]);
+ if (sealkey)
+ RC4(sealkey, 8, hmac, &out[4]);
+ else
+ memcpy(&out[4], hmac, 8);
+
+ memset(&out[12], 0, 4);
+
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+v2_verify_message(gss_buffer_t in,
+ unsigned char signkey[16],
+ RC4_KEY *sealkey,
+ uint32_t seq,
+ const unsigned char checksum[16])
+{
+ OM_uint32 ret;
+ unsigned char out[16];
+
+ ret = v2_sign_message(in, signkey, sealkey, seq, out);
+ if (ret)
+ return ret;
+
+ if (memcmp(checksum, out, 16) != 0)
+ return GSS_S_BAD_MIC;
+
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+v2_seal_message(const gss_buffer_t in,
+ unsigned char signkey[16],
+ uint32_t seq,
+ RC4_KEY *sealkey,
+ gss_buffer_t out)
+{
+ unsigned char *p;
+ OM_uint32 ret;
+
+ if (in->length + 16 < in->length)
+ return EINVAL;
+
+ p = malloc(in->length + 16);
+ if (p == NULL)
+ return ENOMEM;
+
+ RC4(sealkey, in->length, in->value, p);
+
+ ret = v2_sign_message(in, signkey, sealkey, seq, &p[in->length]);
+ if (ret) {
+ free(p);
+ return ret;
+ }
+
+ out->value = p;
+ out->length = in->length + 16;
+
+ return 0;
+}
+
+static OM_uint32
+v2_unseal_message(gss_buffer_t in,
+ unsigned char signkey[16],
+ uint32_t seq,
+ RC4_KEY *sealkey,
+ gss_buffer_t out)
+{
+ OM_uint32 ret;
+
+ if (in->length < 16)
+ return GSS_S_BAD_MIC;
+
+ out->length = in->length - 16;
+ out->value = malloc(out->length);
+ if (out->value == NULL)
+ return GSS_S_BAD_MIC;
+
+ RC4(sealkey, out->length, in->value, out->value);
+
+ ret = v2_verify_message(out, signkey, sealkey, seq,
+ ((const unsigned char *)in->value) + out->length);
+ if (ret) {
+ OM_uint32 junk;
+ gss_release_buffer(&junk, out);
+ }
+ return ret;
+}
+
+/*
+ *
+ */
+
+#define CTX_FLAGS_ISSET(_ctx,_flags) \
+ (((_ctx)->flags & (_flags)) == (_flags))
+
+/*
+ *
+ */
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_get_mic
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ gss_qop_t qop_req,
+ const gss_buffer_t message_buffer,
+ gss_buffer_t message_token
+ )
+{
+ ntlm_ctx ctx = (ntlm_ctx)context_handle;
+ OM_uint32 junk;
+
+ *minor_status = 0;
+
+ message_token->value = malloc(16);
+ message_token->length = 16;
+ if (message_token->value == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SIGN|NTLM_NEG_NTLM2_SESSION)) {
+ OM_uint32 ret;
+
+ if ((ctx->status & STATUS_SESSIONKEY) == 0) {
+ gss_release_buffer(&junk, message_token);
+ return GSS_S_UNAVAILABLE;
+ }
+
+ ret = v2_sign_message(message_buffer,
+ ctx->u.v2.send.signkey,
+ ctx->u.v2.send.signsealkey,
+ ctx->u.v2.send.seq++,
+ message_token->value);
+ if (ret)
+ gss_release_buffer(&junk, message_token);
+ return ret;
+
+ } else if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SIGN)) {
+ OM_uint32 ret;
+
+ if ((ctx->status & STATUS_SESSIONKEY) == 0) {
+ gss_release_buffer(&junk, message_token);
+ return GSS_S_UNAVAILABLE;
+ }
+
+ ret = v1_sign_message(message_buffer,
+ &ctx->u.v1.crypto_send.key,
+ ctx->u.v1.crypto_send.seq++,
+ message_token->value);
+ if (ret)
+ gss_release_buffer(&junk, message_token);
+ return ret;
+
+ } else if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_ALWAYS_SIGN)) {
+ unsigned char *sigature;
+
+ sigature = message_token->value;
+
+ encode_le_uint32(1, &sigature[0]); /* version */
+ encode_le_uint32(0, &sigature[4]);
+ encode_le_uint32(0, &sigature[8]);
+ encode_le_uint32(0, &sigature[12]);
+
+ return GSS_S_COMPLETE;
+ }
+ gss_release_buffer(&junk, message_token);
+
+ return GSS_S_UNAVAILABLE;
+}
+
+/*
+ *
+ */
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_verify_mic
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t message_buffer,
+ const gss_buffer_t token_buffer,
+ gss_qop_t * qop_state
+ )
+{
+ ntlm_ctx ctx = (ntlm_ctx)context_handle;
+
+ if (qop_state != NULL)
+ *qop_state = GSS_C_QOP_DEFAULT;
+ *minor_status = 0;
+
+ if (token_buffer->length != 16)
+ return GSS_S_BAD_MIC;
+
+ if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SIGN|NTLM_NEG_NTLM2_SESSION)) {
+ OM_uint32 ret;
+
+ if ((ctx->status & STATUS_SESSIONKEY) == 0)
+ return GSS_S_UNAVAILABLE;
+
+ ret = v2_verify_message(message_buffer,
+ ctx->u.v2.recv.signkey,
+ ctx->u.v2.recv.signsealkey,
+ ctx->u.v2.recv.seq++,
+ token_buffer->value);
+ if (ret)
+ return ret;
+
+ return GSS_S_COMPLETE;
+ } else if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SIGN)) {
+
+ unsigned char sigature[12];
+ uint32_t crc, num;
+
+ if ((ctx->status & STATUS_SESSIONKEY) == 0)
+ return GSS_S_UNAVAILABLE;
+
+ decode_le_uint32(token_buffer->value, &num);
+ if (num != 1)
+ return GSS_S_BAD_MIC;
+
+ RC4(&ctx->u.v1.crypto_recv.key, sizeof(sigature),
+ ((unsigned char *)token_buffer->value) + 4, sigature);
+
+ _krb5_crc_init_table();
+ crc = _krb5_crc_update(message_buffer->value,
+ message_buffer->length, 0);
+ /* skip first 4 bytes in the encrypted checksum */
+ decode_le_uint32(&sigature[4], &num);
+ if (num != crc)
+ return GSS_S_BAD_MIC;
+ decode_le_uint32(&sigature[8], &num);
+ if (ctx->u.v1.crypto_recv.seq != num)
+ return GSS_S_BAD_MIC;
+ ctx->u.v1.crypto_recv.seq++;
+
+ return GSS_S_COMPLETE;
+ } else if (ctx->flags & NTLM_NEG_ALWAYS_SIGN) {
+ uint32_t num;
+ unsigned char *p;
+
+ p = (unsigned char*)(token_buffer->value);
+
+ decode_le_uint32(&p[0], &num); /* version */
+ if (num != 1) return GSS_S_BAD_MIC;
+ decode_le_uint32(&p[4], &num);
+ if (num != 0) return GSS_S_BAD_MIC;
+ decode_le_uint32(&p[8], &num);
+ if (num != 0) return GSS_S_BAD_MIC;
+ decode_le_uint32(&p[12], &num);
+ if (num != 0) return GSS_S_BAD_MIC;
+
+ return GSS_S_COMPLETE;
+ }
+
+ return GSS_S_UNAVAILABLE;
+}
+
+/*
+ *
+ */
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_wrap_size_limit (
+ OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ OM_uint32 req_output_size,
+ OM_uint32 * max_input_size
+ )
+{
+ ntlm_ctx ctx = (ntlm_ctx)context_handle;
+
+ *minor_status = 0;
+
+ if(ctx->flags & NTLM_NEG_SEAL) {
+
+ if (req_output_size < 16)
+ *max_input_size = 0;
+ else
+ *max_input_size = req_output_size - 16;
+
+ return GSS_S_COMPLETE;
+ }
+
+ return GSS_S_UNAVAILABLE;
+}
+
+/*
+ *
+ */
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_wrap
+(OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ const gss_buffer_t input_message_buffer,
+ int * conf_state,
+ gss_buffer_t output_message_buffer
+ )
+{
+ ntlm_ctx ctx = (ntlm_ctx)context_handle;
+ OM_uint32 ret;
+
+ *minor_status = 0;
+ if (conf_state)
+ *conf_state = 0;
+ if (output_message_buffer == GSS_C_NO_BUFFER)
+ return GSS_S_FAILURE;
+
+
+ if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SEAL|NTLM_NEG_NTLM2_SESSION)) {
+
+ return v2_seal_message(input_message_buffer,
+ ctx->u.v2.send.signkey,
+ ctx->u.v2.send.seq++,
+ &ctx->u.v2.send.sealkey,
+ output_message_buffer);
+
+ } else if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SEAL)) {
+ gss_buffer_desc trailer;
+ OM_uint32 junk;
+
+ output_message_buffer->length = input_message_buffer->length + 16;
+ output_message_buffer->value = malloc(output_message_buffer->length);
+ if (output_message_buffer->value == NULL) {
+ output_message_buffer->length = 0;
+ return GSS_S_FAILURE;
+ }
+
+
+ RC4(&ctx->u.v1.crypto_send.key, input_message_buffer->length,
+ input_message_buffer->value, output_message_buffer->value);
+
+ ret = _gss_ntlm_get_mic(minor_status, context_handle,
+ 0, input_message_buffer,
+ &trailer);
+ if (ret) {
+ gss_release_buffer(&junk, output_message_buffer);
+ return ret;
+ }
+ if (trailer.length != 16) {
+ gss_release_buffer(&junk, output_message_buffer);
+ gss_release_buffer(&junk, &trailer);
+ return GSS_S_FAILURE;
+ }
+ memcpy(((unsigned char *)output_message_buffer->value) +
+ input_message_buffer->length,
+ trailer.value, trailer.length);
+ gss_release_buffer(&junk, &trailer);
+
+ return GSS_S_COMPLETE;
+ }
+
+ return GSS_S_UNAVAILABLE;
+}
+
+/*
+ *
+ */
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_unwrap
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t input_message_buffer,
+ gss_buffer_t output_message_buffer,
+ int * conf_state,
+ gss_qop_t * qop_state
+ )
+{
+ ntlm_ctx ctx = (ntlm_ctx)context_handle;
+ OM_uint32 ret;
+
+ *minor_status = 0;
+ output_message_buffer->value = NULL;
+ output_message_buffer->length = 0;
+
+ if (conf_state)
+ *conf_state = 0;
+ if (qop_state)
+ *qop_state = 0;
+
+ if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SEAL|NTLM_NEG_NTLM2_SESSION)) {
+
+ return v2_unseal_message(input_message_buffer,
+ ctx->u.v2.recv.signkey,
+ ctx->u.v2.recv.seq++,
+ &ctx->u.v2.recv.sealkey,
+ output_message_buffer);
+
+ } else if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SEAL)) {
+
+ gss_buffer_desc trailer;
+ OM_uint32 junk;
+
+ if (input_message_buffer->length < 16)
+ return GSS_S_BAD_MIC;
+
+ output_message_buffer->length = input_message_buffer->length - 16;
+ output_message_buffer->value = malloc(output_message_buffer->length);
+ if (output_message_buffer->value == NULL) {
+ output_message_buffer->length = 0;
+ return GSS_S_FAILURE;
+ }
+
+ RC4(&ctx->u.v1.crypto_recv.key, output_message_buffer->length,
+ input_message_buffer->value, output_message_buffer->value);
+
+ trailer.value = ((unsigned char *)input_message_buffer->value) +
+ output_message_buffer->length;
+ trailer.length = 16;
+
+ ret = _gss_ntlm_verify_mic(minor_status, context_handle,
+ output_message_buffer,
+ &trailer, NULL);
+ if (ret) {
+ gss_release_buffer(&junk, output_message_buffer);
+ return ret;
+ }
+
+ return GSS_S_COMPLETE;
+ }
+
+ return GSS_S_UNAVAILABLE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/delete_sec_context.c b/third_party/heimdal/lib/gssapi/ntlm/delete_sec_context.c
new file mode 100644
index 0000000..57587a0
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/delete_sec_context.c
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV _gss_ntlm_delete_sec_context
+ (OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ gss_buffer_t output_token
+ )
+{
+ OM_uint32 min;
+
+ if (context_handle) {
+ ntlm_ctx ctx = (ntlm_ctx)*context_handle;
+ gss_cred_id_t cred = (gss_cred_id_t)ctx->client;
+
+ *context_handle = GSS_C_NO_CONTEXT;
+
+ if (ctx->server)
+ (*ctx->server->nsi_destroy)(minor_status, ctx->ictx);
+
+ _gss_ntlm_release_cred(NULL, &cred);
+ memset_s(ctx->sessionkey.data, ctx->sessionkey.length, 0,
+ ctx->sessionkey.length);
+ krb5_data_free(&ctx->sessionkey);
+ gss_release_buffer(&min, &ctx->pac);
+
+ memset(ctx, 0, sizeof(*ctx));
+ free(ctx);
+ }
+ if (output_token) {
+ output_token->length = 0;
+ output_token->value = NULL;
+ }
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/display_name.c b/third_party/heimdal/lib/gssapi/ntlm/display_name.c
new file mode 100644
index 0000000..59d2c84
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/display_name.c
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_display_name
+ (OM_uint32 * minor_status,
+ gss_const_name_t input_name,
+ gss_buffer_t output_name_buffer,
+ gss_OID * output_name_type
+ )
+{
+ *minor_status = 0;
+
+ if (output_name_type)
+ *output_name_type = GSS_NTLM_MECHANISM;
+
+ if (output_name_buffer) {
+ ntlm_name n = (ntlm_name)input_name;
+ char *str = NULL;
+ int len;
+
+ output_name_buffer->length = 0;
+ output_name_buffer->value = NULL;
+
+ if (n == NULL) {
+ *minor_status = 0;
+ return GSS_S_BAD_NAME;
+ }
+
+ len = asprintf(&str, "%s@%s", n->user, n->domain);
+ if (len < 0 || str == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ output_name_buffer->length = len;
+ output_name_buffer->value = str;
+ }
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/display_status.c b/third_party/heimdal/lib/gssapi/ntlm/display_status.c
new file mode 100644
index 0000000..c9e1792
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/display_status.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 1998 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_display_status
+ (OM_uint32 *minor_status,
+ OM_uint32 status_value,
+ int status_type,
+ const gss_OID mech_type,
+ OM_uint32 *message_context,
+ gss_buffer_t status_string)
+{
+ if (minor_status)
+ *minor_status = 0;
+ if (status_string) {
+ status_string->length = 0;
+ status_string->value = NULL;
+ }
+ if (message_context)
+ *message_context = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/duplicate_cred.c b/third_party/heimdal/lib/gssapi/ntlm/duplicate_cred.c
new file mode 100644
index 0000000..d05f9fa
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/duplicate_cred.c
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2006-2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_duplicate_cred(OM_uint32 *minor_status,
+ gss_const_cred_id_t input_cred_handle,
+ gss_cred_id_t *output_cred_handle)
+{
+ ntlm_const_cred cred = (ntlm_const_cred)input_cred_handle;
+ ntlm_cred new_cred;
+ OM_uint32 junk;
+
+ if (input_cred_handle == GSS_C_NO_CREDENTIAL)
+ return _gss_ntlm_acquire_cred_from(minor_status, GSS_C_NO_NAME,
+ GSS_C_INDEFINITE, GSS_C_NO_OID_SET,
+ GSS_C_BOTH, GSS_C_NO_CRED_STORE,
+ output_cred_handle, NULL, NULL);
+
+ *output_cred_handle = GSS_C_NO_CREDENTIAL;
+
+ *minor_status = _gss_ntlm_copy_cred((ntlm_cred)input_cred_handle,
+ (ntlm_cred *)output_cred_handle);
+
+ return *minor_status == 0 ? GSS_S_COMPLETE : GSS_S_FAILURE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/duplicate_name.c b/third_party/heimdal/lib/gssapi/ntlm/duplicate_name.c
new file mode 100644
index 0000000..060fa55
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/duplicate_name.c
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_duplicate_name (
+ OM_uint32 * minor_status,
+ gss_const_name_t src_name,
+ gss_name_t * dest_name
+ )
+{
+ if (minor_status)
+ *minor_status = 0;
+ if (dest_name)
+ *dest_name = NULL;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/export_name.c b/third_party/heimdal/lib/gssapi/ntlm/export_name.c
new file mode 100644
index 0000000..e5bdca4
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/export_name.c
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 1997, 1999, 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_export_name
+ (OM_uint32 * minor_status,
+ gss_const_name_t input_name,
+ gss_buffer_t exported_name
+ )
+{
+ if (minor_status)
+ *minor_status = 0;
+ if (exported_name) {
+ exported_name->length = 0;
+ exported_name->value = NULL;
+ }
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/export_sec_context.c b/third_party/heimdal/lib/gssapi/ntlm/export_sec_context.c
new file mode 100644
index 0000000..027a921
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/export_sec_context.c
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 1999 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_export_sec_context (
+ OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ gss_buffer_t interprocess_token
+ )
+{
+ if (minor_status)
+ *minor_status = 0;
+ if (interprocess_token) {
+ interprocess_token->length = 0;
+ interprocess_token->value = NULL;
+ }
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/external.c b/third_party/heimdal/lib/gssapi/ntlm/external.c
new file mode 100644
index 0000000..ff2cd2d
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/external.c
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2006-2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+static gss_mo_desc ntlm_mo[] = {
+ {
+ GSS_C_MA_SASL_MECH_NAME,
+ GSS_MO_MA,
+ "SASL mech name",
+ rk_UNCONST("NTLM"),
+ _gss_mo_get_ctx_as_string,
+ NULL
+ },
+ {
+ GSS_C_MA_MECH_NAME,
+ GSS_MO_MA,
+ "Mechanism name",
+ rk_UNCONST("NTLMSPP"),
+ _gss_mo_get_ctx_as_string,
+ NULL
+ },
+ {
+ GSS_C_MA_MECH_DESCRIPTION,
+ GSS_MO_MA,
+ "Mechanism description",
+ rk_UNCONST("Heimdal NTLMSSP Mechanism"),
+ _gss_mo_get_ctx_as_string,
+ NULL
+ }
+};
+
+static gssapi_mech_interface_desc ntlm_mech = {
+ GMI_VERSION,
+ "ntlm",
+ {10, rk_UNCONST("\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a") },
+ 0,
+ NULL,
+ _gss_ntlm_release_cred,
+ _gss_ntlm_init_sec_context,
+ _gss_ntlm_accept_sec_context,
+ _gss_ntlm_process_context_token,
+ _gss_ntlm_delete_sec_context,
+ _gss_ntlm_context_time,
+ _gss_ntlm_get_mic,
+ _gss_ntlm_verify_mic,
+ _gss_ntlm_wrap,
+ _gss_ntlm_unwrap,
+ _gss_ntlm_display_status,
+ NULL,
+ _gss_ntlm_compare_name,
+ _gss_ntlm_display_name,
+ _gss_ntlm_import_name,
+ _gss_ntlm_export_name,
+ _gss_ntlm_release_name,
+ _gss_ntlm_inquire_cred,
+ _gss_ntlm_inquire_context,
+ _gss_ntlm_wrap_size_limit,
+ _gss_ntlm_add_cred,
+ _gss_ntlm_inquire_cred_by_mech,
+ _gss_ntlm_export_sec_context,
+ _gss_ntlm_import_sec_context,
+ _gss_ntlm_inquire_names_for_mech,
+ _gss_ntlm_inquire_mechs_for_name,
+ _gss_ntlm_canonicalize_name,
+ _gss_ntlm_duplicate_name,
+ _gss_ntlm_inquire_sec_context_by_oid,
+ NULL,
+ _gss_ntlm_set_sec_context_option,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ _gss_ntlm_acquire_cred_from,
+ NULL, /* gm_acquire_cred_impersonate_name */
+ _gss_ntlm_iter_creds_f,
+ _gss_ntlm_destroy_cred,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ ntlm_mo,
+ sizeof(ntlm_mo) / sizeof(ntlm_mo[0]),
+ NULL, /* gm_localname */
+ NULL, /* gm_authorize_localname */
+ NULL, /* gm_display_name_ext */
+ NULL, /* gm_inquire_name */
+ NULL, /* gm_get_name_attribute */
+ NULL, /* gm_set_name_attribute */
+ NULL, /* gm_delete_name_attribute */
+ NULL, /* gm_export_name_composite */
+ NULL, /* gm_duplicate_cred */
+ NULL, /* gm_add_cred_from */
+ NULL, /* gm_store_cred_into */
+ NULL, /* gm_query_mechanism_info */
+ NULL, /* gm_query_meta_data */
+ NULL, /* gm_exchange_meta_data */
+ NULL, /* gm_store_cred_into2 */
+ NULL, /* gm_compat */
+};
+
+gssapi_mech_interface
+__gss_ntlm_initialize(void)
+{
+ return &ntlm_mech;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/import_name.c b/third_party/heimdal/lib/gssapi/ntlm/import_name.c
new file mode 100644
index 0000000..e75388d
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/import_name.c
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_import_name
+ (OM_uint32 * minor_status,
+ const gss_buffer_t input_name_buffer,
+ const gss_OID input_name_type,
+ gss_name_t * output_name
+ )
+{
+ char *name, *p, *p2;
+ int is_hostnamed;
+ int is_username;
+ ntlm_name n;
+
+ *minor_status = 0;
+
+ if (output_name == NULL)
+ return GSS_S_CALL_INACCESSIBLE_WRITE;
+
+ *output_name = GSS_C_NO_NAME;
+
+ is_hostnamed = gss_oid_equal(input_name_type, GSS_C_NT_HOSTBASED_SERVICE);
+ is_username = gss_oid_equal(input_name_type, GSS_C_NT_USER_NAME);
+
+ if (!is_hostnamed && !is_username)
+ return GSS_S_BAD_NAMETYPE;
+
+ name = malloc(input_name_buffer->length + 1);
+ if (name == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ memcpy(name, input_name_buffer->value, input_name_buffer->length);
+ name[input_name_buffer->length] = '\0';
+
+ /* find "domain" part of the name and uppercase it */
+ p = strchr(name, '@');
+ if (p == NULL) {
+ free(name);
+ return GSS_S_BAD_NAME;
+ }
+ p[0] = '\0';
+ p++;
+ p2 = strchr(p, '.');
+ if (p2 && p2[1] != '\0') {
+ if (is_hostnamed) {
+ p = p2 + 1;
+ p2 = strchr(p, '.');
+ }
+ if (p2)
+ *p2 = '\0';
+ }
+ strupr(p);
+
+ n = calloc(1, sizeof(*n));
+ if (n == NULL) {
+ free(name);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ n->user = strdup(name);
+ n->domain = strdup(p);
+
+ free(name);
+
+ if (n->user == NULL || n->domain == NULL) {
+ free(n->user);
+ free(n->domain);
+ free(n);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ *output_name = (gss_name_t)n;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/import_sec_context.c b/third_party/heimdal/lib/gssapi/ntlm/import_sec_context.c
new file mode 100644
index 0000000..fe637c0
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/import_sec_context.c
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 1999 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_import_sec_context (
+ OM_uint32 * minor_status,
+ const gss_buffer_t interprocess_token,
+ gss_ctx_id_t * context_handle
+ )
+{
+ if (minor_status)
+ *minor_status = 0;
+ if (context_handle)
+ *context_handle = GSS_C_NO_CONTEXT;
+ return GSS_S_FAILURE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/indicate_mechs.c b/third_party/heimdal/lib/gssapi/ntlm/indicate_mechs.c
new file mode 100644
index 0000000..7cda475
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/indicate_mechs.c
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 _gss_ntlm_indicate_mechs
+(OM_uint32 * minor_status,
+ gss_OID_set * mech_set
+ )
+{
+ if (minor_status)
+ *minor_status = 0;
+ if (mech_set)
+ *mech_set = GSS_C_NO_OID_SET;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/init_sec_context.c b/third_party/heimdal/lib/gssapi/ntlm/init_sec_context.c
new file mode 100644
index 0000000..be9c987
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/init_sec_context.c
@@ -0,0 +1,536 @@
+/*
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+static int
+from_file(const char *fn, const char *target_domain,
+ char **domainp, char **usernamep, struct ntlm_buf *key)
+{
+ char *str, buf[1024];
+ FILE *f;
+
+ *domainp = NULL;
+
+ f = fopen(fn, "r");
+ if (f == NULL)
+ return ENOENT;
+ rk_cloexec_file(f);
+
+ while (fgets(buf, sizeof(buf), f) != NULL) {
+ char *d, *u, *p;
+ buf[strcspn(buf, "\r\n")] = '\0';
+ if (buf[0] == '#')
+ continue;
+ str = NULL;
+ d = strtok_r(buf, ":", &str);
+ free(*domainp);
+ *domainp = NULL;
+ if (!d)
+ continue;
+ if (d && target_domain != NULL && strcasecmp(target_domain, d) != 0)
+ continue;
+ *domainp = strdup(d);
+ if (*domainp == NULL) {
+ fclose(f);
+ return ENOMEM;
+ }
+ u = strtok_r(NULL, ":", &str);
+ p = strtok_r(NULL, ":", &str);
+ if (u == NULL || p == NULL)
+ continue;
+
+ *usernamep = strdup(u);
+ if (*usernamep == NULL) {
+ fclose(f);
+ return ENOMEM;
+ }
+ heim_ntlm_nt_key(p, key);
+
+ memset_s(buf, sizeof(buf), 0, sizeof(buf));
+ fclose(f);
+ return 0;
+ }
+ memset_s(buf, sizeof(buf), 0, sizeof(buf));
+ fclose(f);
+ return ENOENT;
+}
+
+static int
+get_user_file(const ntlm_name target_name,
+ char **domainp, char **usernamep, struct ntlm_buf *key)
+{
+ const char *domain;
+ const char *fn;
+
+ *domainp = NULL;
+
+ domain = target_name != NULL ? target_name->domain : NULL;
+
+ fn = secure_getenv("NTLM_USER_FILE");
+ if (fn == NULL)
+ return ENOENT;
+ if (from_file(fn, domain, domainp, usernamep, key) == 0)
+ return 0;
+
+ return ENOENT;
+}
+
+/*
+ * Pick up the ntlm cred from the default krb5 credential cache.
+ */
+
+static int
+get_user_ccache(const ntlm_name name, char **domainp, char **usernamep, struct ntlm_buf *key)
+{
+ krb5_context context = NULL;
+ krb5_principal client;
+ krb5_ccache id = NULL;
+ krb5_error_code ret;
+ char *confname;
+ krb5_data data;
+ int aret;
+
+ *domainp = NULL;
+ *usernamep = NULL;
+ krb5_data_zero(&data);
+ key->length = 0;
+ key->data = NULL;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ return ret;
+
+ ret = krb5_cc_default(context, &id);
+ if (ret)
+ goto out;
+
+ ret = krb5_cc_get_principal(context, id, &client);
+ if (ret)
+ goto out;
+
+ ret = krb5_unparse_name_flags(context, client,
+ KRB5_PRINCIPAL_UNPARSE_NO_REALM,
+ usernamep);
+ krb5_free_principal(context, client);
+ if (ret)
+ goto out;
+
+ if (name != NULL) {
+ *domainp = strdup(name->domain);
+ } else {
+ krb5_data data_domain;
+
+ krb5_data_zero(&data_domain);
+ ret = krb5_cc_get_config(context, id, NULL, "default-ntlm-domain",
+ &data_domain);
+ if (ret)
+ goto out;
+
+ *domainp = strndup(data_domain.data, data_domain.length);
+ krb5_data_free(&data_domain);
+ }
+
+ if (*domainp == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ aret = asprintf(&confname, "ntlm-key-%s", *domainp);
+ if (aret == -1) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ ret = krb5_cc_get_config(context, id, NULL, confname, &data);
+ if (ret)
+ goto out;
+
+ key->data = malloc(data.length);
+ if (key->data == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ key->length = data.length;
+ memcpy(key->data, data.data, data.length);
+
+ out:
+ krb5_data_free(&data);
+ if (id)
+ krb5_cc_close(context, id);
+
+ krb5_free_context(context);
+
+ return ret;
+}
+
+int
+_gss_ntlm_get_user_cred(const ntlm_name target_name,
+ ntlm_cred *rcred)
+{
+ ntlm_cred cred;
+ int ret;
+
+ cred = calloc(1, sizeof(*cred));
+ if (cred == NULL)
+ return ENOMEM;
+
+ ret = get_user_file(target_name,
+ &cred->domain, &cred->username, &cred->key);
+ if (ret)
+ ret = get_user_ccache(target_name,
+ &cred->domain, &cred->username, &cred->key);
+ if (ret) {
+ OM_uint32 tmp;
+ _gss_ntlm_release_cred(&tmp, (gss_cred_id_t *)&cred);
+ return ret;
+ }
+
+ *rcred = cred;
+
+ return ret;
+}
+
+int
+_gss_ntlm_copy_cred(ntlm_cred from, ntlm_cred *to)
+{
+ *to = calloc(1, sizeof(**to));
+ if (*to == NULL)
+ return ENOMEM;
+ (*to)->usage = from->usage;
+ (*to)->username = strdup(from->username);
+ if ((*to)->username == NULL) {
+ free(*to);
+ return ENOMEM;
+ }
+ (*to)->domain = strdup(from->domain);
+ if ((*to)->domain == NULL) {
+ free((*to)->username);
+ free(*to);
+ return ENOMEM;
+ }
+ (*to)->key.data = malloc(from->key.length);
+ if ((*to)->key.data == NULL) {
+ free((*to)->domain);
+ free((*to)->username);
+ free(*to);
+ return ENOMEM;
+ }
+ memcpy((*to)->key.data, from->key.data, from->key.length);
+ (*to)->key.length = from->key.length;
+
+ return 0;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_init_sec_context
+ (OM_uint32 * minor_status,
+ gss_const_cred_id_t initiator_cred_handle,
+ gss_ctx_id_t * context_handle,
+ gss_const_name_t target_name,
+ const gss_OID mech_type,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ const gss_buffer_t input_token,
+ gss_OID * actual_mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec
+ )
+{
+ ntlm_ctx ctx;
+ ntlm_name name = (ntlm_name)target_name;
+
+ *minor_status = 0;
+
+ if (ret_flags)
+ *ret_flags = 0;
+ if (time_rec)
+ *time_rec = 0;
+ if (actual_mech_type)
+ *actual_mech_type = GSS_C_NO_OID;
+
+ if (*context_handle == GSS_C_NO_CONTEXT) {
+ struct ntlm_type1 type1;
+ struct ntlm_buf data;
+ uint32_t flags = 0;
+ int ret;
+
+ ctx = calloc(1, sizeof(*ctx));
+ if (ctx == NULL) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ ctx->status = STATUS_CLIENT;
+ *context_handle = (gss_ctx_id_t)ctx;
+
+ if (initiator_cred_handle != GSS_C_NO_CREDENTIAL) {
+ ntlm_cred cred = (ntlm_cred)initiator_cred_handle;
+ ret = _gss_ntlm_copy_cred(cred, &ctx->client);
+ } else
+ ret = _gss_ntlm_get_user_cred(name, &ctx->client);
+
+ if (ret) {
+ _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ if (req_flags & GSS_C_CONF_FLAG)
+ flags |= NTLM_NEG_SEAL;
+ if (req_flags & GSS_C_INTEG_FLAG)
+ flags |= NTLM_NEG_SIGN;
+ else
+ flags |= NTLM_NEG_ALWAYS_SIGN;
+
+ flags |= NTLM_NEG_UNICODE;
+ flags |= NTLM_NEG_NTLM;
+ flags |= NTLM_NEG_NTLM2_SESSION;
+ flags |= NTLM_NEG_KEYEX;
+
+ memset(&type1, 0, sizeof(type1));
+
+ type1.flags = flags;
+ type1.domain = name->domain;
+ type1.hostname = NULL;
+ type1.os[0] = 0;
+ type1.os[1] = 0;
+
+ ret = heim_ntlm_encode_type1(&type1, &data);
+ if (ret) {
+ _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ output_token->value = data.data;
+ output_token->length = data.length;
+
+ return GSS_S_CONTINUE_NEEDED;
+ } else {
+ krb5_error_code ret;
+ struct ntlm_type2 type2;
+ struct ntlm_type3 type3;
+ struct ntlm_buf data;
+
+ ctx = (ntlm_ctx)*context_handle;
+
+ data.data = input_token->value;
+ data.length = input_token->length;
+
+ ret = heim_ntlm_decode_type2(&data, &type2);
+ if (ret) {
+ _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL);
+ *minor_status = ret;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ ctx->flags = type2.flags;
+
+ /* XXX check that type2.targetinfo matches `target_name´ */
+ /* XXX check verify targetinfo buffer */
+
+ memset(&type3, 0, sizeof(type3));
+
+ type3.username = ctx->client->username;
+ type3.flags = type2.flags;
+ type3.targetname = type2.targetname;
+ type3.ws = rk_UNCONST("workstation");
+
+ /*
+ * NTLM Version 1 if no targetinfo buffer.
+ */
+
+ if (1 || type2.targetinfo.length == 0) {
+ struct ntlm_buf sessionkey;
+
+ if (type2.flags & NTLM_NEG_NTLM2_SESSION) {
+ unsigned char nonce[8];
+
+ if (RAND_bytes(nonce, sizeof(nonce)) != 1) {
+ _gss_ntlm_delete_sec_context(minor_status,
+ context_handle, NULL);
+ heim_ntlm_free_type2(&type2);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ ret = heim_ntlm_calculate_ntlm2_sess(nonce,
+ type2.challenge,
+ ctx->client->key.data,
+ &type3.lm,
+ &type3.ntlm);
+ } else {
+ ret = heim_ntlm_calculate_ntlm1(ctx->client->key.data,
+ ctx->client->key.length,
+ type2.challenge,
+ &type3.ntlm);
+
+ }
+ if (ret) {
+ _gss_ntlm_delete_sec_context(minor_status,context_handle,NULL);
+ heim_ntlm_free_type2(&type2);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = heim_ntlm_build_ntlm1_master(ctx->client->key.data,
+ ctx->client->key.length,
+ &sessionkey,
+ &type3.sessionkey);
+ if (ret) {
+ if (type3.lm.data)
+ free(type3.lm.data);
+ if (type3.ntlm.data)
+ free(type3.ntlm.data);
+ _gss_ntlm_delete_sec_context(minor_status,context_handle,NULL);
+ heim_ntlm_free_type2(&type2);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_data_copy(&ctx->sessionkey,
+ sessionkey.data, sessionkey.length);
+ free(sessionkey.data);
+ if (ret) {
+ if (type3.lm.data)
+ free(type3.lm.data);
+ if (type3.ntlm.data)
+ free(type3.ntlm.data);
+ _gss_ntlm_delete_sec_context(minor_status,context_handle,NULL);
+ heim_ntlm_free_type2(&type2);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ ctx->status |= STATUS_SESSIONKEY;
+
+ } else {
+ struct ntlm_buf sessionkey;
+ unsigned char ntlmv2[16];
+ struct ntlm_targetinfo ti;
+
+ /* verify infotarget */
+
+ ret = heim_ntlm_decode_targetinfo(&type2.targetinfo, 1, &ti);
+ if(ret) {
+ _gss_ntlm_delete_sec_context(minor_status,
+ context_handle, NULL);
+ heim_ntlm_free_type2(&type2);
+ *minor_status = ret;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ if (ti.domainname && strcmp(ti.domainname, name->domain) != 0) {
+ _gss_ntlm_delete_sec_context(minor_status,
+ context_handle, NULL);
+ heim_ntlm_free_type2(&type2);
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ ret = heim_ntlm_calculate_ntlm2(ctx->client->key.data,
+ ctx->client->key.length,
+ ctx->client->username,
+ name->domain,
+ type2.challenge,
+ &type2.targetinfo,
+ ntlmv2,
+ &type3.ntlm);
+ if (ret) {
+ _gss_ntlm_delete_sec_context(minor_status,
+ context_handle, NULL);
+ heim_ntlm_free_type2(&type2);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = heim_ntlm_build_ntlm1_master(ntlmv2, sizeof(ntlmv2),
+ &sessionkey,
+ &type3.sessionkey);
+ memset_s(ntlmv2, sizeof(ntlmv2), 0, sizeof(ntlmv2));
+ if (ret) {
+ _gss_ntlm_delete_sec_context(minor_status,
+ context_handle, NULL);
+ heim_ntlm_free_type2(&type2);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ctx->flags |= NTLM_NEG_NTLM2_SESSION;
+
+ ret = krb5_data_copy(&ctx->sessionkey,
+ sessionkey.data, sessionkey.length);
+ free(sessionkey.data);
+ if (ret) {
+ _gss_ntlm_delete_sec_context(minor_status,
+ context_handle, NULL);
+ heim_ntlm_free_type2(&type2);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ }
+
+
+ _gss_ntlm_set_keys(ctx);
+
+
+ ret = heim_ntlm_encode_type3(&type3, &data, NULL);
+ free(type3.sessionkey.data);
+ if (type3.lm.data)
+ free(type3.lm.data);
+ if (type3.ntlm.data)
+ free(type3.ntlm.data);
+ if (ret) {
+ _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL);
+ heim_ntlm_free_type2(&type2);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ output_token->length = data.length;
+ output_token->value = data.data;
+
+ if (actual_mech_type)
+ *actual_mech_type = GSS_NTLM_MECHANISM;
+ if (ret_flags)
+ *ret_flags = 0;
+ if (time_rec)
+ *time_rec = GSS_C_INDEFINITE;
+
+ ctx->status |= STATUS_OPEN;
+
+ heim_ntlm_free_type2(&type2);
+ return GSS_S_COMPLETE;
+ }
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/inquire_context.c b/third_party/heimdal/lib/gssapi/ntlm/inquire_context.c
new file mode 100644
index 0000000..741ad6e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/inquire_context.c
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_inquire_context (
+ OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ gss_name_t * src_name,
+ gss_name_t * targ_name,
+ OM_uint32 * lifetime_rec,
+ gss_OID * mech_type,
+ OM_uint32 * ctx_flags,
+ int * locally_initiated,
+ int * open_context
+ )
+{
+ ntlm_ctx ctx = (ntlm_ctx)context_handle;
+
+ *minor_status = 0;
+ if (src_name)
+ *src_name = GSS_C_NO_NAME;
+ if (targ_name)
+ *targ_name = GSS_C_NO_NAME;
+ if (lifetime_rec)
+ *lifetime_rec = GSS_C_INDEFINITE;
+ if (mech_type)
+ *mech_type = GSS_NTLM_MECHANISM;
+ if (ctx_flags)
+ *ctx_flags = ctx->gssflags;
+ if (locally_initiated)
+ *locally_initiated = (ctx->status & STATUS_CLIENT) ? 1 : 0;
+ if (open_context)
+ *open_context = (ctx->status & STATUS_OPEN) ? 1 : 0;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/inquire_cred_by_mech.c b/third_party/heimdal/lib/gssapi/ntlm/inquire_cred_by_mech.c
new file mode 100644
index 0000000..ed42094
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/inquire_cred_by_mech.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_inquire_cred_by_mech (
+ OM_uint32 * minor_status,
+ gss_const_cred_id_t cred_handle,
+ const gss_OID mech_type,
+ gss_name_t * name,
+ OM_uint32 * initiator_lifetime,
+ OM_uint32 * acceptor_lifetime,
+ gss_cred_usage_t * cred_usage
+ )
+{
+ if (minor_status)
+ *minor_status = 0;
+ if (name)
+ *name = GSS_C_NO_NAME;
+ if (initiator_lifetime)
+ *initiator_lifetime = 0;
+ if (acceptor_lifetime)
+ *acceptor_lifetime = 0;
+ if (cred_usage)
+ *cred_usage = 0;
+ return GSS_S_UNAVAILABLE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/inquire_mechs_for_name.c b/third_party/heimdal/lib/gssapi/ntlm/inquire_mechs_for_name.c
new file mode 100644
index 0000000..25450ab
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/inquire_mechs_for_name.c
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_inquire_mechs_for_name (
+ OM_uint32 * minor_status,
+ gss_const_name_t input_name,
+ gss_OID_set * mech_types
+ )
+{
+ if (minor_status)
+ *minor_status = 0;
+ if (mech_types)
+ *mech_types = GSS_C_NO_OID_SET;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/inquire_names_for_mech.c b/third_party/heimdal/lib/gssapi/ntlm/inquire_names_for_mech.c
new file mode 100644
index 0000000..7f49b33
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/inquire_names_for_mech.c
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_inquire_names_for_mech (
+ OM_uint32 * minor_status,
+ const gss_OID mechanism,
+ gss_OID_set * name_types
+ )
+{
+ OM_uint32 ret;
+
+ ret = gss_create_empty_oid_set(minor_status, name_types);
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/inquire_sec_context_by_oid.c b/third_party/heimdal/lib/gssapi/ntlm/inquire_sec_context_by_oid.c
new file mode 100644
index 0000000..2b42b1f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/inquire_sec_context_by_oid.c
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_inquire_sec_context_by_oid(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_OID desired_object,
+ gss_buffer_set_t *data_set)
+{
+ ntlm_ctx ctx = (ntlm_ctx)context_handle;
+
+ if (ctx == NULL) {
+ *minor_status = 0;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ if (gss_oid_equal(desired_object, GSS_NTLM_GET_SESSION_KEY_X) ||
+ gss_oid_equal(desired_object, GSS_C_INQ_SSPI_SESSION_KEY)) {
+ gss_buffer_desc value;
+
+ value.length = ctx->sessionkey.length;
+ value.value = ctx->sessionkey.data;
+
+ return gss_add_buffer_set_member(minor_status,
+ &value,
+ data_set);
+ } else if (gss_oid_equal(desired_object, GSS_C_INQ_WIN2K_PAC_X)) {
+ if (ctx->pac.length == 0) {
+ *minor_status = ENOENT;
+ return GSS_S_FAILURE;
+ }
+
+ return gss_add_buffer_set_member(minor_status,
+ &ctx->pac,
+ data_set);
+
+ } else if (gss_oid_equal(desired_object, GSS_C_NTLM_AVGUEST)) {
+ gss_buffer_desc value;
+ uint32_t num;
+
+ if (ctx->kcmflags & KCM_NTLM_FLAG_AV_GUEST)
+ num = 1;
+ else
+ num = 0;
+
+ value.length = sizeof(num);
+ value.value = &num;
+
+ return gss_add_buffer_set_member(minor_status,
+ &value,
+ data_set);
+ } else {
+ *minor_status = 0;
+ return GSS_S_FAILURE;
+ }
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/iter_cred.c b/third_party/heimdal/lib/gssapi/ntlm/iter_cred.c
new file mode 100644
index 0000000..ee5ec17
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/iter_cred.c
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+void GSSAPI_CALLCONV
+_gss_ntlm_iter_creds_f(OM_uint32 flags,
+ void *userctx ,
+ void (*cred_iter)(void *, gss_OID, gss_cred_id_t))
+{
+#ifdef HAVE_KCM
+ krb5_error_code ret;
+ krb5_context context = NULL;
+ krb5_storage *request, *response;
+ krb5_data response_data;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ goto done;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_GET_NTLM_USER_LIST, &request);
+ if (ret)
+ goto done;
+
+ ret = krb5_kcm_call(context, request, &response, &response_data);
+ krb5_storage_free(request);
+ if (ret)
+ goto done;
+
+ while (1) {
+ uint32_t morep;
+ char *user = NULL, *domain = NULL;
+ ntlm_cred dn;
+
+ ret = krb5_ret_uint32(response, &morep);
+ if (ret) goto out;
+
+ if (!morep) goto out;
+
+ ret = krb5_ret_stringz(response, &user);
+ if (ret) goto out;
+ ret = krb5_ret_stringz(response, &domain);
+ if (ret) {
+ free(user);
+ goto out;
+ }
+
+ dn = calloc(1, sizeof(*dn));
+ if (dn == NULL) {
+ free(user);
+ free(domain);
+ goto out;
+ }
+ dn->username = user;
+ dn->domain = domain;
+
+ cred_iter(userctx, GSS_NTLM_MECHANISM, (gss_cred_id_t)dn);
+ }
+ out:
+ krb5_storage_free(response);
+ krb5_data_free(&response_data);
+ done:
+ if (context)
+ krb5_free_context(context);
+#endif /* HAVE_KCM */
+ (*cred_iter)(userctx, NULL, NULL);
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/kdc.c b/third_party/heimdal/lib/gssapi/ntlm/kdc.c
new file mode 100644
index 0000000..1bce00f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/kdc.c
@@ -0,0 +1,435 @@
+/*
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+#ifdef DIGEST
+
+/*
+ *
+ */
+
+struct ntlmkrb5 {
+ krb5_context context;
+ krb5_ntlm ntlm;
+ krb5_realm kerberos_realm;
+ krb5_ccache id;
+ krb5_data opaque;
+ int destroy;
+ OM_uint32 flags;
+ struct ntlm_buf key;
+ krb5_data sessionkey;
+};
+
+static OM_uint32 kdc_destroy(OM_uint32 *, void *);
+
+/*
+ * Get credential cache that the ntlm code can use to talk to the KDC
+ * using the digest API.
+ */
+
+static krb5_error_code
+get_ccache(krb5_context context, int *destroy, krb5_ccache *id)
+{
+ krb5_principal principal = NULL;
+ krb5_error_code ret;
+ krb5_keytab kt = NULL;
+ const char *cache = secure_getenv("NTLM_ACCEPTOR_CCACHE");
+
+ *id = NULL;
+
+ if (cache) {
+ ret = krb5_cc_resolve(context, cache, id);
+ if (ret)
+ goto out;
+ return 0;
+ }
+
+ ret = krb5_sname_to_principal(context, NULL, "host",
+ KRB5_NT_SRV_HST, &principal);
+ if (ret)
+ goto out;
+
+ ret = krb5_cc_cache_match(context, principal, id);
+ if (ret == 0)
+ return 0;
+
+ /* did not find in default credcache, lets try default keytab */
+ ret = krb5_kt_default(context, &kt);
+ if (ret)
+ goto out;
+
+ /* XXX check in keytab */
+ {
+ krb5_get_init_creds_opt *opt;
+ krb5_creds cred;
+
+ memset(&cred, 0, sizeof(cred));
+
+ ret = krb5_cc_new_unique(context, "MEMORY", NULL, id);
+ if (ret)
+ goto out;
+ *destroy = 1;
+ ret = krb5_get_init_creds_opt_alloc(context, &opt);
+ if (ret)
+ goto out;
+ ret = krb5_get_init_creds_keytab (context,
+ &cred,
+ principal,
+ kt,
+ 0,
+ NULL,
+ opt);
+ krb5_get_init_creds_opt_free(context, opt);
+ if (ret)
+ goto out;
+ ret = krb5_cc_initialize (context, *id, cred.client);
+ if (ret) {
+ krb5_free_cred_contents (context, &cred);
+ goto out;
+ }
+ ret = krb5_cc_store_cred (context, *id, &cred);
+ krb5_free_cred_contents (context, &cred);
+ if (ret)
+ goto out;
+ }
+
+ krb5_kt_close(context, kt);
+
+ return 0;
+
+out:
+ if (*id) {
+ if (*destroy)
+ krb5_cc_destroy(context, *id);
+ else
+ krb5_cc_close(context, *id);
+ *id = NULL;
+ }
+
+ if (kt)
+ krb5_kt_close(context, kt);
+
+ if (principal)
+ krb5_free_principal(context, principal);
+ return ret;
+}
+
+/*
+ *
+ */
+
+static OM_uint32
+kdc_alloc(OM_uint32 *minor, void **ctx)
+{
+ krb5_error_code ret;
+ struct ntlmkrb5 *c;
+ OM_uint32 junk;
+
+ c = calloc(1, sizeof(*c));
+ if (c == NULL) {
+ *minor = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_init_context(&c->context);
+ if (ret) {
+ kdc_destroy(&junk, c);
+ *minor = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = get_ccache(c->context, &c->destroy, &c->id);
+ if (ret) {
+ kdc_destroy(&junk, c);
+ *minor = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_ntlm_alloc(c->context, &c->ntlm);
+ if (ret) {
+ kdc_destroy(&junk, c);
+ *minor = ret;
+ return GSS_S_FAILURE;
+ }
+
+ *ctx = c;
+
+ return GSS_S_COMPLETE;
+}
+
+static int
+kdc_probe(OM_uint32 *minor, void *ctx, const char *realm)
+{
+ struct ntlmkrb5 *c = ctx;
+ krb5_error_code ret;
+ unsigned flags;
+
+ ret = krb5_digest_probe(c->context, rk_UNCONST(realm), c->id, &flags);
+ if (ret)
+ return ret;
+
+ if ((flags & (1|2|4)) == 0)
+ return EINVAL;
+
+ return 0;
+}
+
+/*
+ *
+ */
+
+static OM_uint32
+kdc_destroy(OM_uint32 *minor, void *ctx)
+{
+ struct ntlmkrb5 *c = ctx;
+ krb5_data_free(&c->opaque);
+ krb5_data_free(&c->sessionkey);
+ if (c->ntlm)
+ krb5_ntlm_free(c->context, c->ntlm);
+ if (c->id) {
+ if (c->destroy)
+ krb5_cc_destroy(c->context, c->id);
+ else
+ krb5_cc_close(c->context, c->id);
+ }
+ if (c->context)
+ krb5_free_context(c->context);
+ memset(c, 0, sizeof(*c));
+ free(c);
+
+ return GSS_S_COMPLETE;
+}
+
+/*
+ *
+ */
+
+static OM_uint32
+kdc_type2(OM_uint32 *minor_status,
+ void *ctx,
+ uint32_t flags,
+ const char *hostname,
+ const char *domain,
+ uint32_t *ret_flags,
+ struct ntlm_buf *out)
+{
+ struct ntlmkrb5 *c = ctx;
+ krb5_error_code ret;
+ struct ntlm_type2 type2;
+ krb5_data challenge;
+ struct ntlm_buf data;
+ krb5_data ti;
+
+ memset(&type2, 0, sizeof(type2));
+ memset(out, 0, sizeof(*out));
+
+ /*
+ * Request data for type 2 packet from the KDC.
+ */
+ ret = krb5_ntlm_init_request(c->context,
+ c->ntlm,
+ NULL,
+ c->id,
+ flags,
+ hostname,
+ domain);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ /*
+ *
+ */
+
+ ret = krb5_ntlm_init_get_opaque(c->context, c->ntlm, &c->opaque);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ /*
+ *
+ */
+
+ ret = krb5_ntlm_init_get_flags(c->context, c->ntlm, &type2.flags);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ *ret_flags = type2.flags;
+
+ ret = krb5_ntlm_init_get_challenge(c->context, c->ntlm, &challenge);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ if (challenge.length != sizeof(type2.challenge)) {
+ *minor_status = EINVAL;
+ return GSS_S_FAILURE;
+ }
+ memcpy(type2.challenge, challenge.data, sizeof(type2.challenge));
+ krb5_data_free(&challenge);
+
+ ret = krb5_ntlm_init_get_targetname(c->context, c->ntlm,
+ &type2.targetname);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_ntlm_init_get_targetinfo(c->context, c->ntlm, &ti);
+ if (ret) {
+ free(type2.targetname);
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ type2.targetinfo.data = ti.data;
+ type2.targetinfo.length = ti.length;
+
+ ret = heim_ntlm_encode_type2(&type2, &data);
+ free(type2.targetname);
+ krb5_data_free(&ti);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ out->data = data.data;
+ out->length = data.length;
+
+ return GSS_S_COMPLETE;
+}
+
+/*
+ *
+ */
+
+static OM_uint32
+kdc_type3(OM_uint32 *minor_status,
+ void *ctx,
+ const struct ntlm_type3 *type3,
+ struct ntlm_buf *sessionkey)
+{
+ struct ntlmkrb5 *c = ctx;
+ krb5_error_code ret;
+
+ sessionkey->data = NULL;
+ sessionkey->length = 0;
+
+ ret = krb5_ntlm_req_set_flags(c->context, c->ntlm, type3->flags);
+ if (ret) goto out;
+ ret = krb5_ntlm_req_set_username(c->context, c->ntlm, type3->username);
+ if (ret) goto out;
+ ret = krb5_ntlm_req_set_targetname(c->context, c->ntlm,
+ type3->targetname);
+ if (ret) goto out;
+ ret = krb5_ntlm_req_set_lm(c->context, c->ntlm,
+ type3->lm.data, type3->lm.length);
+ if (ret) goto out;
+ ret = krb5_ntlm_req_set_ntlm(c->context, c->ntlm,
+ type3->ntlm.data, type3->ntlm.length);
+ if (ret) goto out;
+ ret = krb5_ntlm_req_set_opaque(c->context, c->ntlm, &c->opaque);
+ if (ret) goto out;
+
+ if (type3->sessionkey.length) {
+ ret = krb5_ntlm_req_set_session(c->context, c->ntlm,
+ type3->sessionkey.data,
+ type3->sessionkey.length);
+ if (ret) goto out;
+ }
+
+ /*
+ * Verify with the KDC the type3 packet is ok
+ */
+ ret = krb5_ntlm_request(c->context,
+ c->ntlm,
+ NULL,
+ c->id);
+ if (ret)
+ goto out;
+
+ if (krb5_ntlm_rep_get_status(c->context, c->ntlm) != TRUE) {
+ ret = EINVAL;
+ goto out;
+ }
+
+ if (type3->sessionkey.length) {
+ ret = krb5_ntlm_rep_get_sessionkey(c->context,
+ c->ntlm,
+ &c->sessionkey);
+ if (ret)
+ goto out;
+
+ sessionkey->data = c->sessionkey.data;
+ sessionkey->length = c->sessionkey.length;
+ }
+
+ return 0;
+
+ out:
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+}
+
+/*
+ *
+ */
+
+static void
+kdc_free_buffer(struct ntlm_buf *sessionkey)
+{
+ if (sessionkey->data)
+ free(sessionkey->data);
+ sessionkey->data = NULL;
+ sessionkey->length = 0;
+}
+
+/*
+ *
+ */
+
+struct ntlm_server_interface ntlmsspi_kdc_digest = {
+ kdc_alloc,
+ kdc_destroy,
+ kdc_probe,
+ kdc_type2,
+ kdc_type3,
+ kdc_free_buffer
+};
+
+#endif /* DIGEST */
diff --git a/third_party/heimdal/lib/gssapi/ntlm/ntlm.h b/third_party/heimdal/lib/gssapi/ntlm/ntlm.h
new file mode 100644
index 0000000..a0ad815
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/ntlm.h
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 2006-2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef NTLM_NTLM_H
+#define NTLM_NTLM_H
+
+#include <config.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <string.h>
+#include <errno.h>
+
+#include <roken.h>
+
+#include <gssapi.h>
+#include <gssapi_ntlm.h>
+#include <gssapi_mech.h>
+#include <gssapi_oid.h>
+
+#include <krb5.h>
+#include <kcm.h>
+#include <heim_threads.h>
+
+#include <heimntlm.h>
+
+#define HC_DEPRECATED_CRYPTO
+#include "crypto-headers.h"
+
+typedef OM_uint32
+(*ntlm_interface_init)(OM_uint32 *, void **);
+
+typedef OM_uint32
+(*ntlm_interface_destroy)(OM_uint32 *, void *);
+
+typedef int
+(*ntlm_interface_probe)(OM_uint32 *, void *, const char *);
+
+typedef OM_uint32
+(*ntlm_interface_type2)(OM_uint32 *, void *, uint32_t, const char *,
+ const char *, uint32_t *, struct ntlm_buf *);
+
+typedef OM_uint32
+(*ntlm_interface_type3)(OM_uint32 *, void *, const struct ntlm_type3 *,
+ struct ntlm_buf *);
+
+typedef void
+(*ntlm_interface_free_buffer)(struct ntlm_buf *);
+
+struct ntlm_server_interface {
+ ntlm_interface_init nsi_init;
+ ntlm_interface_destroy nsi_destroy;
+ ntlm_interface_probe nsi_probe;
+ ntlm_interface_type2 nsi_type2;
+ ntlm_interface_type3 nsi_type3;
+ ntlm_interface_free_buffer nsi_free_buffer;
+};
+
+
+struct ntlmv2_key {
+ uint32_t seq;
+ RC4_KEY sealkey;
+ RC4_KEY *signsealkey;
+ unsigned char signkey[16];
+};
+
+extern struct ntlm_server_interface ntlmsspi_kdc_digest;
+
+typedef struct ntlm_cred {
+ gss_cred_usage_t usage;
+ char *username;
+ char *domain;
+ struct ntlm_buf key;
+} *ntlm_cred;
+typedef const struct ntlm_cred *ntlm_const_cred;
+
+typedef struct {
+ struct ntlm_server_interface *server;
+ void *ictx;
+ ntlm_cred client;
+ OM_uint32 gssflags;
+ uint32_t kcmflags;
+ uint32_t flags;
+ uint32_t status;
+#define STATUS_OPEN 1
+#define STATUS_CLIENT 2
+#define STATUS_SESSIONKEY 4
+ krb5_data sessionkey;
+
+ gss_buffer_desc pac;
+
+ union {
+ struct {
+ struct {
+ uint32_t seq;
+ RC4_KEY key;
+ } crypto_send, crypto_recv;
+ } v1;
+ struct {
+ struct ntlmv2_key send, recv;
+ } v2;
+ } u;
+} *ntlm_ctx;
+
+typedef struct {
+ char *user;
+ char *domain;
+} *ntlm_name;
+
+#include <ntlm-private.h>
+
+
+#endif /* NTLM_NTLM_H */
diff --git a/third_party/heimdal/lib/gssapi/ntlm/process_context_token.c b/third_party/heimdal/lib/gssapi/ntlm/process_context_token.c
new file mode 100644
index 0000000..2add53b
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/process_context_token.c
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV _gss_ntlm_process_context_token (
+ OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t token_buffer
+ )
+{
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/release_cred.c b/third_party/heimdal/lib/gssapi/ntlm/release_cred.c
new file mode 100644
index 0000000..e31a316
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/release_cred.c
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV _gss_ntlm_release_cred
+ (OM_uint32 * minor_status,
+ gss_cred_id_t * cred_handle
+ )
+{
+ ntlm_cred cred;
+
+ if (minor_status)
+ *minor_status = 0;
+
+ if (cred_handle == NULL || *cred_handle == GSS_C_NO_CREDENTIAL)
+ return GSS_S_COMPLETE;
+
+ cred = (ntlm_cred)*cred_handle;
+ *cred_handle = GSS_C_NO_CREDENTIAL;
+
+ if (cred->username)
+ free(cred->username);
+ if (cred->domain)
+ free(cred->domain);
+ if (cred->key.data) {
+ memset(cred->key.data, 0, cred->key.length);
+ free(cred->key.data);
+ }
+
+ memset(cred, 0, sizeof(*cred));
+ free(cred);
+
+ return GSS_S_COMPLETE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/ntlm/release_name.c b/third_party/heimdal/lib/gssapi/ntlm/release_name.c
new file mode 100644
index 0000000..4a5c56d
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/release_name.c
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_release_name
+ (OM_uint32 * minor_status,
+ gss_name_t * input_name
+ )
+{
+ if (minor_status)
+ *minor_status = 0;
+ if (input_name && *input_name) {
+ ntlm_name n = (ntlm_name)*input_name;
+ *input_name = GSS_C_NO_NAME;
+ free(n->user);
+ free(n->domain);
+ free(n);
+ }
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/ntlm/set_sec_context_option.c b/third_party/heimdal/lib/gssapi/ntlm/set_sec_context_option.c
new file mode 100644
index 0000000..f97443d
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/ntlm/set_sec_context_option.c
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "ntlm.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_set_sec_context_option(OM_uint32 *minor_status,
+ gss_ctx_id_t *context_handle,
+ const gss_OID object,
+ const gss_buffer_t value)
+{
+ ntlm_ctx ctx;
+
+ if (context_handle == NULL)
+ return GSS_S_UNAVAILABLE;
+
+ *minor_status = 0;
+
+ ctx = (ntlm_ctx)*context_handle;
+ if (ctx == NULL)
+ return GSS_S_NO_CONTEXT;
+
+ if (gss_oid_equal(object, GSS_C_NTLM_RESET_CRYPTO)) {
+ _gss_ntlm_set_keys(ctx);
+ return GSS_S_COMPLETE;
+ } else
+ return GSS_S_UNAVAILABLE;
+}
diff --git a/third_party/heimdal/lib/gssapi/oid.txt b/third_party/heimdal/lib/gssapi/oid.txt
new file mode 100644
index 0000000..fa210d6
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/oid.txt
@@ -0,0 +1,173 @@
+# /*
+# * Contact Love Hörnquist Åstrand <lha at h5l.org> for new oid arcs */
+# */
+# /*
+# * 1.2.752.43 is SU's arc. SU's registry has arcs 13, 14, and 16
+# * below that registered for Heimdal to use. The Heimdal source tree
+# * is the authoritative registry for Heimdal's three arcs off of SU's arc.
+# * This file is the authoritative registry for 1.2.752.43.13 and 1.2.752.14.
+# * ASN.1 modules in lib/asn1/ are authoritative for 1.2.752.43.16.
+# *
+# * Confirmed by SU's erstwhile registrar, Leif Johansson <leifj at sunet.se>,
+# * as well as by SU's current registrar (through Leif), as:
+# *
+# * 1.2.752.43.13 Namn Heimdal GSS-API extentions
+# * Beskrivning OIDar för användning av Heimdal projektet
+# * 1.2.752.43.14 Namn Heimdal GSS-API mechs
+# * Beskrivning OIDar för användning av Heimdal projektet
+# * 1.2.752.43.16 Namn Heimdal Internal crypto ops
+# * Beskrivning OIDar för användning av Heimdal projektet
+# *
+# * 1.2.752.43.16 is now also used in Heimdal for PKIX-related things.
+# * See lib/asn1/ and lib/hx509/.
+# *
+# * Contact the SU registrar for new oid arcs if any are needed, or carve
+# * out an arc of one of the above, preferably off 1.2.752.43.16.
+# */
+
+# /*
+# * 1.2.752.43.13 Heimdal GSS-API Extensions
+# */
+
+oid base GSS_KRB5_COPY_CCACHE_X 1.2.752.43.13.1
+oid base GSS_KRB5_GET_TKT_FLAGS_X 1.2.752.43.13.2
+oid base GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X 1.2.752.43.13.3
+oid base GSS_KRB5_COMPAT_DES3_MIC_X 1.2.752.43.13.4
+oid base GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X 1.2.752.43.13.5
+oid base GSS_KRB5_EXPORT_LUCID_CONTEXT_X 1.2.752.43.13.6
+oid base GSS_KRB5_EXPORT_LUCID_CONTEXT_V1_X 1.2.752.43.13.6.1
+oid base GSS_KRB5_SET_DNS_CANONICALIZE_X 1.2.752.43.13.7
+oid base GSS_KRB5_GET_SUBKEY_X 1.2.752.43.13.8
+oid base GSS_KRB5_GET_INITIATOR_SUBKEY_X 1.2.752.43.13.9
+oid base GSS_KRB5_GET_ACCEPTOR_SUBKEY_X 1.2.752.43.13.10
+oid base GSS_KRB5_SEND_TO_KDC_X 1.2.752.43.13.11
+oid base GSS_KRB5_GET_AUTHTIME_X 1.2.752.43.13.12
+oid base GSS_KRB5_GET_SERVICE_KEYBLOCK_X 1.2.752.43.13.13
+oid base GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X 1.2.752.43.13.14
+oid base GSS_KRB5_SET_DEFAULT_REALM_X 1.2.752.43.13.15
+oid base GSS_KRB5_CCACHE_NAME_X 1.2.752.43.13.16
+oid base GSS_KRB5_SET_TIME_OFFSET_X 1.2.752.43.13.17
+oid base GSS_KRB5_GET_TIME_OFFSET_X 1.2.752.43.13.18
+oid base GSS_KRB5_PLUGIN_REGISTER_X 1.2.752.43.13.19
+oid base GSS_NTLM_GET_SESSION_KEY_X 1.2.752.43.13.20
+oid base GSS_C_NT_NTLM 1.2.752.43.13.21
+oid base GSS_C_NT_DN 1.2.752.43.13.22
+oid base GSS_KRB5_NT_PRINCIPAL_NAME_REFERRAL 1.2.752.43.13.23
+oid base GSS_C_NTLM_AVGUEST 1.2.752.43.13.24
+oid base GSS_C_NTLM_V1 1.2.752.43.13.25
+oid base GSS_C_NTLM_V2 1.2.752.43.13.26
+oid base GSS_C_NTLM_SESSION_KEY 1.2.752.43.13.27
+oid base GSS_C_NTLM_FORCE_V1 1.2.752.43.13.28
+oid base GSS_KRB5_CRED_NO_CI_FLAGS_X 1.2.752.43.13.29
+oid base GSS_KRB5_IMPORT_CRED_X 1.2.752.43.13.30
+oid base GSS_KRB5_IMPORT_RFC4121_CONTEXT_X 1.2.752.43.13.31
+
+# /* glue for gss_inquire_saslname_for_mech */
+oid base GSS_C_MA_SASL_MECH_NAME 1.2.752.43.13.100
+oid base GSS_C_MA_MECH_NAME 1.2.752.43.13.101
+oid base GSS_C_MA_MECH_DESCRIPTION 1.2.752.43.13.102
+
+#/* Heimdal mechanisms - 1.2.752.43.14 */
+
+oid base GSS_SASL_DIGEST_MD5_MECHANISM 1.2.752.43.14.1
+oid base GSS_NETLOGON_MECHANISM 1.2.752.43.14.2
+oid base GSS_NETLOGON_SET_SESSION_KEY_X 1.2.752.43.14.3
+oid base GSS_NETLOGON_SET_SIGN_ALGORITHM_X 1.2.752.43.14.4
+oid base GSS_NETLOGON_NT_NETBIOS_DNS_NAME 1.2.752.43.14.5
+
+#/* GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X.128 */
+oid base GSS_C_INQ_WIN2K_PAC_X 1.2.752.43.13.3.128
+oid base GSS_C_INQ_SSPI_SESSION_KEY 1.2.840.113554.1.2.2.5.5
+oid base GSS_C_INQ_NEGOEX_KEY 1.2.840.113554.1.2.2.5.16
+oid base GSS_C_INQ_NEGOEX_VERIFY_KEY 1.2.840.113554.1.2.2.5.17
+oid base GSS_C_INQ_REQUIRE_MECHLIST_MIC 1.3.6.1.4.1.7165.655.1.2
+
+#/*
+# * "Standard" mechs
+# */
+
+oid base GSS_KRB5_MECHANISM 1.2.840.113554.1.2.2
+oid base GSS_NTLM_MECHANISM 1.3.6.1.4.1.311.2.2.10
+oid base GSS_SPNEGO_MECHANISM 1.3.6.1.5.5.2
+
+# /* From Luke Howard */
+
+oid base GSS_C_INQ_PEER_HAS_BUGGY_SPNEGO 1.3.6.1.4.1.5322.19.6
+oid base GSS_C_NTLM_RESET_CRYPTO 1.3.6.1.4.1.7165.655.1.3
+oid base GSS_NEGOEX_MECHANISM 1.3.6.1.4.1.311.2.2.30
+oid base GSS_SANON_X25519_MECHANISM 1.3.6.1.4.1.5322.26.1.110
+
+#/*
+# * OID mappings with name and short description and and slightly longer description
+# */
+
+desc mech GSS_KRB5_MECHANISM "Kerberos 5" "Heimdal Kerberos 5 mechanism"
+desc mech GSS_NTLM_MECHANISM "NTLM" "Heimdal NTLM mechanism"
+desc mech GSS_SPNEGO_MECHANISM "SPNEGO" "Heimdal SPNEGO mechanism"
+desc mech GSS_SANON_X25519_MECHANISM "SAnon-X25519" "Heimdal Simple Anonymous (X25519) mechanism"
+
+desc ma GSS_C_MA_MECH_NAME "GSS mech name" "The name of the GSS-API mechanism"
+desc ma GSS_C_MA_SASL_MECH_NAME "SASL mechanism name" "The name of the SASL mechanism"
+desc ma GSS_C_MA_MECH_DESCRIPTION "Mech description" "The long description of the mechanism"
+
+#/*
+# * RFC5587
+# */
+
+oid base GSS_C_MA_MECH_CONCRETE 1.3.6.1.5.5.13.1
+oid base GSS_C_MA_MECH_PSEUDO 1.3.6.1.5.5.13.2
+oid base GSS_C_MA_MECH_COMPOSITE 1.3.6.1.5.5.13.3
+oid base GSS_C_MA_MECH_NEGO 1.3.6.1.5.5.13.4
+oid base GSS_C_MA_MECH_GLUE 1.3.6.1.5.5.13.5
+oid base GSS_C_MA_NOT_MECH 1.3.6.1.5.5.13.6
+oid base GSS_C_MA_DEPRECATED 1.3.6.1.5.5.13.7
+oid base GSS_C_MA_NOT_DFLT_MECH 1.3.6.1.5.5.13.8
+oid base GSS_C_MA_ITOK_FRAMED 1.3.6.1.5.5.13.9
+oid base GSS_C_MA_AUTH_INIT 1.3.6.1.5.5.13.10
+oid base GSS_C_MA_AUTH_TARG 1.3.6.1.5.5.13.11
+oid base GSS_C_MA_AUTH_INIT_INIT 1.3.6.1.5.5.13.12
+oid base GSS_C_MA_AUTH_TARG_INIT 1.3.6.1.5.5.13.13
+oid base GSS_C_MA_AUTH_INIT_ANON 1.3.6.1.5.5.13.14
+oid base GSS_C_MA_AUTH_TARG_ANON 1.3.6.1.5.5.13.15
+oid base GSS_C_MA_DELEG_CRED 1.3.6.1.5.5.13.16
+oid base GSS_C_MA_INTEG_PROT 1.3.6.1.5.5.13.17
+oid base GSS_C_MA_CONF_PROT 1.3.6.1.5.5.13.18
+oid base GSS_C_MA_MIC 1.3.6.1.5.5.13.19
+oid base GSS_C_MA_WRAP 1.3.6.1.5.5.13.20
+oid base GSS_C_MA_PROT_READY 1.3.6.1.5.5.13.21
+oid base GSS_C_MA_REPLAY_DET 1.3.6.1.5.5.13.22
+oid base GSS_C_MA_OOS_DET 1.3.6.1.5.5.13.23
+oid base GSS_C_MA_CBINDINGS 1.3.6.1.5.5.13.24
+oid base GSS_C_MA_PFS 1.3.6.1.5.5.13.25
+oid base GSS_C_MA_COMPRESS 1.3.6.1.5.5.13.26
+oid base GSS_C_MA_CTX_TRANS 1.3.6.1.5.5.13.27
+oid base GSS_C_MA_NEGOEX_AND_SPNEGO 1.2.840.113554.1.2.2.5.18
+
+desc ma GSS_C_MA_MECH_CONCRETE "concrete-mech" "Indicates that a mech is neither a pseudo-mechanism nor a composite mechanism"
+desc ma GSS_C_MA_MECH_PSEUDO "pseudo-mech" ""
+desc ma GSS_C_MA_MECH_COMPOSITE "composite-mech" ""
+desc ma GSS_C_MA_MECH_NEGO "mech-negotiation-mech" ""
+desc ma GSS_C_MA_MECH_GLUE "mech-glue" ""
+desc ma GSS_C_MA_NOT_MECH "not-mech" ""
+desc ma GSS_C_MA_DEPRECATED "mech-deprecated" ""
+desc ma GSS_C_MA_NOT_DFLT_MECH "mech-not-default" ""
+desc ma GSS_C_MA_ITOK_FRAMED "initial-is-framed" ""
+desc ma GSS_C_MA_AUTH_INIT "auth-init-princ" ""
+desc ma GSS_C_MA_AUTH_TARG "auth-targ-princ" ""
+desc ma GSS_C_MA_AUTH_INIT_INIT "auth-init-princ-initial" ""
+desc ma GSS_C_MA_AUTH_TARG_INIT "auth-targ-princ-initial" ""
+desc ma GSS_C_MA_AUTH_INIT_ANON "auth-init-princ-anon" ""
+desc ma GSS_C_MA_AUTH_TARG_ANON "auth-targ-princ-anon" ""
+desc ma GSS_C_MA_DELEG_CRED "deleg-cred" ""
+desc ma GSS_C_MA_INTEG_PROT "integ-prot" ""
+desc ma GSS_C_MA_CONF_PROT "conf-prot" ""
+desc ma GSS_C_MA_MIC "mic" ""
+desc ma GSS_C_MA_WRAP "wrap" ""
+desc ma GSS_C_MA_PROT_READY "prot-ready" ""
+desc ma GSS_C_MA_REPLAY_DET "replay-detection" ""
+desc ma GSS_C_MA_OOS_DET "oos-detection" ""
+desc ma GSS_C_MA_CBINDINGS "channel-bindings" ""
+desc ma GSS_C_MA_PFS "pfs" ""
+desc ma GSS_C_MA_COMPRESS "compress" ""
+desc ma GSS_C_MA_CTX_TRANS "context-transfer" ""
+desc ma GSS_C_MA_NEGOEX_AND_SPNEGO "negoex-and-spnego" "Indicates that a mechanism supports both NegoEx and SPNEGO"
diff --git a/third_party/heimdal/lib/gssapi/sanon/accept_sec_context.c b/third_party/heimdal/lib/gssapi/sanon/accept_sec_context.c
new file mode 100644
index 0000000..72cbe09
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/accept_sec_context.c
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_accept_sec_context(OM_uint32 *minor,
+ gss_ctx_id_t *context_handle,
+ gss_const_cred_id_t verifier_cred_handle,
+ const gss_buffer_t input_token,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_name_t *src_name,
+ gss_OID *mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 *ret_flags,
+ OM_uint32 *time_rec,
+ gss_cred_id_t *delegated_cred_handle)
+{
+ static gss_buffer_desc empty = GSS_C_EMPTY_BUFFER;
+ OM_uint32 major, tmp;
+ sanon_ctx sc = (sanon_ctx)*context_handle;
+ gss_buffer_desc mech_input_token = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc initiator_pk = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc hok_mic = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc session_key = GSS_C_EMPTY_BUFFER;
+ OM_uint32 req_flags = 0;
+
+ if (output_token == GSS_C_NO_BUFFER) {
+ *minor = EINVAL;
+ major = GSS_S_FAILURE;
+ goto out;
+ }
+
+ _mg_buffer_zero(output_token);
+
+ if (input_token == GSS_C_NO_BUFFER) {
+ major = GSS_S_DEFECTIVE_TOKEN;
+ goto out;
+ } else if (sc != NULL) {
+ major = GSS_S_BAD_STATUS;
+ goto out;
+ }
+
+ major = gss_decapsulate_token(input_token,
+ GSS_SANON_X25519_MECHANISM,
+ &mech_input_token);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+
+ sc = calloc(1, sizeof(*sc));
+ if (sc == NULL) {
+ *minor = ENOMEM;
+ major = GSS_S_FAILURE;
+ goto out;
+ }
+
+ /* initiator token can include optional 64-bit flags */
+ if (mech_input_token.length != crypto_scalarmult_curve25519_BYTES &&
+ mech_input_token.length != crypto_scalarmult_curve25519_BYTES + 8) {
+ *minor = 0;
+ major = GSS_S_DEFECTIVE_TOKEN;
+ goto out;
+ }
+
+ initiator_pk = mech_input_token;
+ initiator_pk.length = crypto_scalarmult_curve25519_BYTES;
+
+ /* compute public and secret keys */
+ major = _gss_sanon_curve25519_base(minor, sc);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+
+ if (mech_input_token.length > crypto_scalarmult_curve25519_BYTES) {
+ /* extra flags */
+ uint8_t *p = (uint8_t *)mech_input_token.value + crypto_scalarmult_curve25519_BYTES;
+ uint32_t dummy;
+
+ _gss_mg_decode_be_uint32(p, &dummy); /* upper 32 bits presently unused */
+ _gss_mg_decode_be_uint32(&p[4], &req_flags);
+ }
+
+ /* compute shared secret */
+ major = _gss_sanon_curve25519(minor, sc, &initiator_pk, req_flags,
+ input_chan_bindings, &session_key);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+
+ /* do not let initiator set any other flags */
+ req_flags &= SANON_PROTOCOL_FLAG_MASK;
+
+ req_flags |= GSS_C_REPLAY_FLAG | GSS_C_SEQUENCE_FLAG | GSS_C_CONF_FLAG |
+ GSS_C_INTEG_FLAG | GSS_C_ANON_FLAG | GSS_C_TRANS_FLAG |
+ GSS_C_CHANNEL_BOUND_FLAG; /* CB part of KDF, so always validated */
+
+ major = _gss_sanon_import_rfc4121_context(minor, sc, req_flags, &session_key);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+
+ major = _gss_sanon_get_mic(minor, (gss_const_ctx_id_t)sc,
+ GSS_C_QOP_DEFAULT, &empty, &hok_mic);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+
+ output_token->length = sizeof(sc->pk) + hok_mic.length;
+ output_token->value = malloc(output_token->length);
+ if (output_token->value == NULL) {
+ output_token->length = 0;
+ *minor = ENOMEM;
+ major = GSS_S_FAILURE;
+ goto out;
+ }
+
+ memcpy(output_token->value, sc->pk, sizeof(sc->pk));
+ memcpy((uint8_t *)output_token->value + sizeof(sc->pk), hok_mic.value, hok_mic.length);
+
+ major = GSS_S_COMPLETE;
+
+ *context_handle = (gss_ctx_id_t)sc;
+
+ if (src_name)
+ *src_name = _gss_sanon_anonymous_identity;
+ if (ret_flags)
+ *ret_flags = req_flags;
+ if (time_rec)
+ *time_rec = GSS_C_INDEFINITE;
+
+out:
+ if (mech_type)
+ *mech_type = GSS_SANON_X25519_MECHANISM;
+ if (delegated_cred_handle)
+ *delegated_cred_handle = GSS_C_NO_CREDENTIAL;
+ if (GSS_ERROR(major)) {
+ _gss_sanon_delete_sec_context(&tmp, (gss_ctx_id_t *)&sc, GSS_C_NO_BUFFER);
+ *context_handle = GSS_C_NO_CONTEXT;
+ }
+ gss_release_buffer(&tmp, &mech_input_token);
+ gss_release_buffer(&tmp, &hok_mic);
+ _gss_secure_release_buffer(&tmp, &session_key);
+
+ return major;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/acquire_cred.c b/third_party/heimdal/lib/gssapi/sanon/acquire_cred.c
new file mode 100644
index 0000000..7aedd3e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/acquire_cred.c
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+/* SAnon credential handles are aliases of their underyling name */
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_acquire_cred_from(OM_uint32 *minor,
+ gss_const_name_t desired_name,
+ OM_uint32 time_req,
+ const gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_const_key_value_set_t cred_stor,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *time_rec)
+{
+ *minor = 0;
+
+ if (desired_name == GSS_C_NO_NAME ||
+ desired_name == _gss_sanon_anonymous_identity)
+ *output_cred_handle = _gss_sanon_anonymous_cred;
+ else
+ *output_cred_handle = _gss_sanon_non_anonymous_cred;
+
+ if (time_rec)
+ *time_rec = GSS_C_INDEFINITE;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/add_cred.c b/third_party/heimdal/lib/gssapi/sanon/add_cred.c
new file mode 100644
index 0000000..f1dfeba
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/add_cred.c
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_add_cred_from(OM_uint32 *minor,
+ gss_cred_id_t input_cred_handle,
+ gss_const_name_t desired_name,
+ const gss_OID desired_mech,
+ gss_cred_usage_t cred_usage,
+ OM_uint32 initiator_time_req,
+ OM_uint32 acceptor_time_req,
+ gss_const_key_value_set_t cred_store,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs,
+ OM_uint32 *initiator_time_rec,
+ OM_uint32 *acceptor_time_rec)
+{
+ *minor = 0;
+
+ if (output_cred_handle != NULL) {
+ if (desired_name == GSS_C_NO_NAME ||
+ desired_name == _gss_sanon_anonymous_identity)
+ *output_cred_handle = _gss_sanon_anonymous_cred;
+ else
+ *output_cred_handle = _gss_sanon_non_anonymous_cred;
+ }
+
+ if (initiator_time_rec)
+ *initiator_time_rec = GSS_C_INDEFINITE;
+ if (acceptor_time_rec)
+ *acceptor_time_rec = GSS_C_INDEFINITE;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/canonicalize_name.c b/third_party/heimdal/lib/gssapi/sanon/canonicalize_name.c
new file mode 100644
index 0000000..fa1ade0
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/canonicalize_name.c
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_canonicalize_name(OM_uint32 *minor,
+ gss_const_name_t src_name,
+ const gss_OID mech_type,
+ gss_name_t *dest_name)
+{
+ *minor = 0;
+
+ if (src_name == GSS_C_NO_NAME)
+ return GSS_S_BAD_NAME;
+
+ *dest_name = (gss_name_t)src_name;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/compare_name.c b/third_party/heimdal/lib/gssapi/sanon/compare_name.c
new file mode 100644
index 0000000..85b13b2
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/compare_name.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_compare_name(OM_uint32 *minor,
+ gss_const_name_t name1,
+ gss_const_name_t name2,
+ int *name_equal)
+{
+ *minor = 0;
+
+ /*
+ * RFC 2743 Section 2.4.3:
+ * If either name presented to GSS_Compare_name() denotes
+ * an anonymous principal, GSS_Compare_name() shall indicate
+ * FALSE
+ *
+ * We also have to apply the same logic to non-anonymous
+ * names as we erase their contents.
+ */
+ *name_equal = FALSE;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/context_time.c b/third_party/heimdal/lib/gssapi/sanon/context_time.c
new file mode 100644
index 0000000..338f3ac
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/context_time.c
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_context_time(OM_uint32 *minor,
+ gss_const_ctx_id_t context_handle,
+ OM_uint32 *time_rec)
+{
+ const sanon_ctx sc = (const sanon_ctx)context_handle;
+
+ *minor = 0;
+ *time_rec = GSS_C_INDEFINITE;
+
+ if (sc == NULL)
+ return GSS_S_NO_CONTEXT;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/crypto.c b/third_party/heimdal/lib/gssapi/sanon/crypto.c
new file mode 100644
index 0000000..0c7a67f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/crypto.c
@@ -0,0 +1,333 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_wrap(OM_uint32 *minor,
+ gss_const_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ const gss_buffer_t input_message_buffer,
+ int *conf_state,
+ gss_buffer_t output_message_buffer)
+{
+ const sanon_ctx sc = (const sanon_ctx)context_handle;
+
+ if (sc->rfc4121 == GSS_C_NO_CONTEXT) {
+ *minor = GSS_KRB5_S_KG_CTX_INCOMPLETE;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_wrap(minor, sc->rfc4121,
+ conf_req_flag, qop_req,
+ input_message_buffer, conf_state,
+ output_message_buffer);
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_wrap_size_limit(OM_uint32 *minor,
+ gss_const_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ OM_uint32 req_output_size,
+ OM_uint32 *max_input_size)
+{
+ const sanon_ctx sc = (const sanon_ctx)context_handle;
+
+ if (sc->rfc4121 == GSS_C_NO_CONTEXT) {
+ *minor = GSS_KRB5_S_KG_CTX_INCOMPLETE;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_wrap_size_limit(minor, sc->rfc4121,
+ conf_req_flag, qop_req,
+ req_output_size, max_input_size);
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_wrap_iov(OM_uint32 *minor,
+ gss_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ int *conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ const sanon_ctx sc = (const sanon_ctx)context_handle;
+
+ if (sc->rfc4121 == GSS_C_NO_CONTEXT) {
+ *minor = GSS_KRB5_S_KG_CTX_INCOMPLETE;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_wrap_iov(minor, sc->rfc4121,
+ conf_req_flag, qop_req,
+ conf_state, iov, iov_count);
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_wrap_iov_length(OM_uint32 *minor,
+ gss_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ int *conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ const sanon_ctx sc = (const sanon_ctx)context_handle;
+
+ if (sc->rfc4121 == GSS_C_NO_CONTEXT) {
+ *minor = GSS_KRB5_S_KG_CTX_INCOMPLETE;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_wrap_iov_length(minor, sc->rfc4121,
+ conf_req_flag, qop_req,
+ conf_state, iov, iov_count);
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_unwrap(OM_uint32 *minor,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t input_message_buffer,
+ gss_buffer_t output_message_buffer,
+ int *conf_state,
+ gss_qop_t * qop_state)
+{
+ const sanon_ctx sc = (const sanon_ctx)context_handle;
+
+ if (sc->rfc4121 == GSS_C_NO_CONTEXT) {
+ *minor = GSS_KRB5_S_KG_CTX_INCOMPLETE;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_unwrap(minor, sc->rfc4121,
+ input_message_buffer, output_message_buffer,
+ conf_state, qop_state);
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_unwrap_iov(OM_uint32 *minor,
+ gss_ctx_id_t context_handle,
+ int *conf_state,
+ gss_qop_t *qop_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ const sanon_ctx sc = (const sanon_ctx)context_handle;
+
+ if (sc->rfc4121 == GSS_C_NO_CONTEXT) {
+ *minor = GSS_KRB5_S_KG_CTX_INCOMPLETE;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_unwrap_iov(minor, sc->rfc4121,
+ conf_state, qop_state,
+ iov, iov_count);
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_get_mic(OM_uint32 *minor,
+ gss_const_ctx_id_t context_handle,
+ gss_qop_t qop_req,
+ const gss_buffer_t message_buffer,
+ gss_buffer_t message_token)
+{
+ const sanon_ctx sc = (const sanon_ctx)context_handle;
+
+ if (sc->rfc4121 == GSS_C_NO_CONTEXT) {
+ *minor = GSS_KRB5_S_KG_CTX_INCOMPLETE;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_get_mic(minor, sc->rfc4121,
+ qop_req, message_buffer,
+ message_token);
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_verify_mic(OM_uint32 *minor,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t message_buffer,
+ const gss_buffer_t token_buffer,
+ gss_qop_t *qop_state)
+{
+ const sanon_ctx sc = (const sanon_ctx)context_handle;
+
+ if (sc->rfc4121 == GSS_C_NO_CONTEXT) {
+ *minor = GSS_KRB5_S_KG_CTX_INCOMPLETE;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_verify_mic(minor, sc->rfc4121,
+ message_buffer, token_buffer,
+ qop_state);
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_pseudo_random(OM_uint32 *minor,
+ gss_ctx_id_t context_handle,
+ int prf_key,
+ const gss_buffer_t prf_in,
+ ssize_t desired_output_len,
+ gss_buffer_t prf_out)
+{
+ const sanon_ctx sc = (const sanon_ctx)context_handle;
+
+ if (sc->rfc4121 == GSS_C_NO_CONTEXT) {
+ *minor = GSS_KRB5_S_KG_CTX_INCOMPLETE;
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_pseudo_random(minor, sc->rfc4121,
+ prf_key, prf_in, desired_output_len,
+ prf_out);
+}
+
+/*
+ * Generate a curve25519 secret and public key
+ */
+
+OM_uint32
+_gss_sanon_curve25519_base(OM_uint32 *minor, sanon_ctx sc)
+{
+ krb5_generate_random_block(sc->sk, crypto_scalarmult_curve25519_BYTES);
+
+ if (crypto_scalarmult_curve25519_base(sc->pk, sc->sk) != 0) {
+ *minor = EINVAL;
+ return GSS_S_FAILURE;
+ }
+
+ return GSS_S_COMPLETE;
+}
+
+/*
+ * Derive the context session key using SP800-108 KDF in HMAC mode
+ * and the public keys and channel binding data.
+ */
+
+OM_uint32
+_gss_sanon_curve25519(OM_uint32 *minor,
+ sanon_ctx sc,
+ gss_buffer_t pk,
+ OM_uint32 gss_flags,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_buffer_t session_key)
+{
+ uint8_t shared[crypto_scalarmult_curve25519_BYTES], *p;
+ krb5_error_code ret;
+ krb5_context context;
+ krb5_data kdf_K1, kdf_label, kdf_context, keydata;
+
+ _mg_buffer_zero(session_key);
+
+ if (pk == GSS_C_NO_BUFFER || pk->length != crypto_scalarmult_curve25519_BYTES)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ if (crypto_scalarmult_curve25519(shared, sc->sk, pk->value) != 0)
+ return GSS_S_FAILURE;
+
+ ret = krb5_init_context(&context);
+ if (ret != 0) {
+ *minor = ret;
+ return GSS_S_FAILURE;
+ }
+
+ kdf_K1.data = shared;
+ kdf_K1.length = sizeof(shared);
+
+ kdf_label.data = "sanon-x25519";
+ kdf_label.length = sizeof("sanon-x25519") - 1;
+
+ ret = krb5_data_alloc(&kdf_context,
+ 2 * crypto_scalarmult_curve25519_BYTES + 8 +
+ (input_chan_bindings ? input_chan_bindings->application_data.length : 0));
+ if (ret != 0) {
+ krb5_free_context(context);
+ *minor = ret;
+ return GSS_S_FAILURE;
+ }
+
+ p = kdf_context.data;
+
+ if (sc->is_initiator) {
+ memcpy(p, sc->pk, sizeof(sc->pk));
+ memcpy(&p[pk->length], pk->value, pk->length);
+ } else {
+ memcpy(p, pk->value, pk->length);
+ memcpy(&p[sizeof(sc->pk)], sc->pk, sizeof(sc->pk));
+ }
+ p += 2 * crypto_scalarmult_curve25519_BYTES;
+ _gss_mg_encode_be_uint32(0, p); /* upper 32 bits presently unused */
+ p += 4;
+ _gss_mg_encode_be_uint32(gss_flags, p);
+ p += 4;
+
+ if (input_chan_bindings != GSS_C_NO_CHANNEL_BINDINGS &&
+ input_chan_bindings->application_data.value != NULL) {
+ memcpy(p, input_chan_bindings->application_data.value,
+ input_chan_bindings->application_data.length);
+ }
+
+ ret = krb5_data_alloc(&keydata, 16);
+ if (ret == 0) {
+ ret = _krb5_SP800_108_HMAC_KDF(context, &kdf_K1, &kdf_label,
+ &kdf_context, EVP_sha256(), &keydata);
+
+ session_key->length = keydata.length;
+ session_key->value = keydata.data;
+ } else {
+ krb5_data_free(&keydata);
+ }
+
+ memset_s(kdf_context.data, kdf_context.length, 0, kdf_context.length);
+ krb5_data_free(&kdf_context);
+
+ memset_s(shared, sizeof(shared), 0, sizeof(shared));
+
+ krb5_free_context(context);
+
+ *minor = ret;
+ return ret != 0 ? GSS_S_FAILURE : GSS_S_COMPLETE;
+}
+
+OM_uint32
+_gss_sanon_import_rfc4121_context(OM_uint32 *minor,
+ sanon_ctx sc,
+ OM_uint32 gss_flags,
+ gss_const_buffer_t session_key)
+{
+ return _gss_mg_import_rfc4121_context(minor, sc->is_initiator, gss_flags,
+ KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128,
+ session_key, &sc->rfc4121);
+}
+
diff --git a/third_party/heimdal/lib/gssapi/sanon/delete_sec_context.c b/third_party/heimdal/lib/gssapi/sanon/delete_sec_context.c
new file mode 100644
index 0000000..fdb8a85
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/delete_sec_context.c
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_delete_sec_context(OM_uint32 *minor,
+ gss_ctx_id_t *context_handle,
+ gss_buffer_t output_token)
+{
+ sanon_ctx sc;
+
+ *minor = 0;
+
+ if (output_token != GSS_C_NO_BUFFER) {
+ output_token->length = 0;
+ output_token->value = NULL;
+ }
+
+ if (*context_handle == GSS_C_NO_CONTEXT)
+ return GSS_S_COMPLETE;
+
+ sc = (sanon_ctx)*context_handle;
+
+ *context_handle = GSS_C_NO_CONTEXT;
+
+ gss_delete_sec_context(minor, &sc->rfc4121, GSS_C_NO_BUFFER);
+
+ memset_s(sc, sizeof(*sc), 0, sizeof(*sc));
+ free(sc);
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/display_name.c b/third_party/heimdal/lib/gssapi/sanon/display_name.c
new file mode 100644
index 0000000..1bd55f3
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/display_name.c
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_display_name(OM_uint32 *minor,
+ gss_const_name_t input_name,
+ gss_buffer_t output_name_buffer,
+ gss_OID *output_name_type)
+{
+ *minor = 0;
+
+ if (input_name != _gss_sanon_anonymous_identity)
+ return GSS_S_BAD_NAME;
+
+ if (output_name_type)
+ *output_name_type = GSS_C_NT_ANONYMOUS;
+
+ return _gss_copy_buffer(minor, _gss_sanon_wellknown_user_name,
+ output_name_buffer);
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/display_status.c b/third_party/heimdal/lib/gssapi/sanon/display_status.c
new file mode 100644
index 0000000..4e039c6
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/display_status.c
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 1998 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_display_status(OM_uint32 *minor,
+ OM_uint32 status_value,
+ int status_type,
+ const gss_OID mech_type,
+ OM_uint32 *message_context,
+ gss_buffer_t status_string)
+{
+ _mg_buffer_zero(status_string);
+
+ if (gss_oid_equal(mech_type, GSS_C_NO_OID) == 0 &&
+ gss_oid_equal(mech_type, GSS_SANON_X25519_MECHANISM) == 0) {
+ *minor = 0;
+ return GSS_S_BAD_MECH;
+ }
+
+ if (status_type == GSS_C_MECH_CODE) {
+ return gss_display_status(minor, status_value,
+ GSS_C_MECH_CODE, GSS_KRB5_MECHANISM,
+ message_context, status_string);
+ } else {
+ *minor = EINVAL;
+ return GSS_S_BAD_STATUS;
+ }
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/duplicate_cred.c b/third_party/heimdal/lib/gssapi/sanon/duplicate_cred.c
new file mode 100644
index 0000000..8c5c5d8
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/duplicate_cred.c
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_duplicate_cred(OM_uint32 *minor,
+ gss_const_cred_id_t input_cred_handle,
+ gss_cred_id_t *output_cred_handle)
+{
+ *minor = 0;
+ *output_cred_handle = (gss_cred_id_t)input_cred_handle;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/duplicate_name.c b/third_party/heimdal/lib/gssapi/sanon/duplicate_name.c
new file mode 100644
index 0000000..698e83d
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/duplicate_name.c
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_duplicate_name(OM_uint32 *minor,
+ gss_const_name_t src_name,
+ gss_name_t *dest_name)
+{
+ *minor = 0;
+ *dest_name = (gss_name_t)src_name;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/export_cred.c b/third_party/heimdal/lib/gssapi/sanon/export_cred.c
new file mode 100644
index 0000000..06c2458
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/export_cred.c
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_export_cred(OM_uint32 *minor,
+ gss_cred_id_t input_cred,
+ gss_buffer_t token)
+{
+ return _gss_sanon_export_name(minor, (gss_name_t)input_cred, token);
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/export_name.c b/third_party/heimdal/lib/gssapi/sanon/export_name.c
new file mode 100644
index 0000000..474c58c
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/export_name.c
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_export_name(OM_uint32 *minor,
+ gss_const_name_t input_name,
+ gss_buffer_t exported_name)
+{
+ uint8_t is_anonymous;
+
+ *minor = 0;
+
+ if (input_name == GSS_C_NO_NAME)
+ return GSS_S_BAD_NAME;
+
+ is_anonymous = input_name == _gss_sanon_anonymous_identity;
+ if (!is_anonymous)
+ return GSS_S_BAD_NAME;
+
+ return gss_mg_export_name(minor, GSS_SANON_X25519_MECHANISM,
+ &is_anonymous, 1, exported_name);
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/export_sec_context.c b/third_party/heimdal/lib/gssapi/sanon/export_sec_context.c
new file mode 100644
index 0000000..52ba6fb
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/export_sec_context.c
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_export_sec_context(OM_uint32 *minor,
+ gss_ctx_id_t *context_handle,
+ gss_buffer_t interprocess_token)
+{
+ OM_uint32 major;
+ const sanon_ctx sc = (sanon_ctx)*context_handle;
+
+ if (sc->rfc4121 == GSS_C_NO_CONTEXT) {
+ _mg_buffer_zero(interprocess_token);
+ *minor = 0;
+ return GSS_S_UNAVAILABLE;
+ }
+
+ major = gss_export_sec_context(minor, &sc->rfc4121, interprocess_token);
+ if (major == GSS_S_COMPLETE)
+ _gss_sanon_delete_sec_context(minor, context_handle, GSS_C_NO_BUFFER);
+ return major;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/external.c b/third_party/heimdal/lib/gssapi/sanon/external.c
new file mode 100644
index 0000000..8812f9e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/external.c
@@ -0,0 +1,270 @@
+/*
+ * Copyright (c) 2006-2020 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "sanon_locl.h"
+
+static uint8_t anonymous_identity;
+gss_name_t
+_gss_sanon_anonymous_identity = (gss_name_t)&anonymous_identity;
+gss_cred_id_t
+_gss_sanon_anonymous_cred = (gss_cred_id_t)&anonymous_identity;
+
+static uint8_t non_anonymous_identity;
+gss_name_t
+_gss_sanon_non_anonymous_identity = (gss_name_t)&non_anonymous_identity;
+gss_cred_id_t
+_gss_sanon_non_anonymous_cred = (gss_cred_id_t)&non_anonymous_identity;
+
+static gss_buffer_desc wellknown_user_name = {
+ SANON_WELLKNOWN_USER_NAME_LEN,
+ SANON_WELLKNOWN_USER_NAME
+};
+gss_buffer_t
+_gss_sanon_wellknown_user_name = &wellknown_user_name;
+
+static gss_buffer_desc wellknown_service_name = {
+ SANON_WELLKNOWN_SERVICE_NAME_LEN,
+ SANON_WELLKNOWN_SERVICE_NAME
+};
+gss_buffer_t
+_gss_sanon_wellknown_service_name = &wellknown_service_name;
+
+static gss_mo_desc sanon_mo[] = {
+ {
+ GSS_C_MA_MECH_NAME,
+ GSS_MO_MA,
+ "Mechanism name",
+ rk_UNCONST("SANON-X25519"),
+ _gss_mo_get_ctx_as_string,
+ NULL
+ },
+ {
+ GSS_C_MA_MECH_DESCRIPTION,
+ GSS_MO_MA,
+ "Mechanism description",
+ rk_UNCONST("Heimdal Simple Anonymous (X25519) Mechanism"),
+ _gss_mo_get_ctx_as_string,
+ NULL
+ },
+ {
+ GSS_C_MA_MECH_CONCRETE,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_ITOK_FRAMED,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_AUTH_INIT_ANON,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_AUTH_TARG_ANON,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_INTEG_PROT,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_CONF_PROT,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_MIC,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_WRAP,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_REPLAY_DET,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_OOS_DET,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_CBINDINGS,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_PFS,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_CTX_TRANS,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_NEGOEX_AND_SPNEGO,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ }
+};
+
+static gssapi_mech_interface_desc sanon_mech = {
+ GMI_VERSION,
+ "sanon-x25519",
+ { 10, rk_UNCONST("\x2b\x06\x01\x04\x01\xa9\x4a\x1a\x01\x6e") },
+ 0,
+ NULL,
+ _gss_sanon_release_cred,
+ _gss_sanon_init_sec_context,
+ _gss_sanon_accept_sec_context,
+ _gss_sanon_process_context_token,
+ _gss_sanon_delete_sec_context,
+ _gss_sanon_context_time,
+ _gss_sanon_get_mic,
+ _gss_sanon_verify_mic,
+ _gss_sanon_wrap,
+ _gss_sanon_unwrap,
+ _gss_sanon_display_status,
+ NULL, /* gm_indicate_mechs */
+ _gss_sanon_compare_name,
+ _gss_sanon_display_name,
+ _gss_sanon_import_name,
+ _gss_sanon_export_name,
+ _gss_sanon_release_name,
+ _gss_sanon_inquire_cred,
+ _gss_sanon_inquire_context,
+ _gss_sanon_wrap_size_limit,
+ NULL, /* gm_add_cred */
+ _gss_sanon_inquire_cred_by_mech,
+ _gss_sanon_export_sec_context,
+ _gss_sanon_import_sec_context,
+ _gss_sanon_inquire_names_for_mech,
+ _gss_sanon_inquire_mechs_for_name,
+ _gss_sanon_canonicalize_name,
+ _gss_sanon_duplicate_name,
+ _gss_sanon_inquire_sec_context_by_oid,
+ NULL, /* gm_inquire_cred_by_oid */
+ NULL, /* gm_set_sec_context_option */
+ NULL, /* gm_set_cred_option */
+ _gss_sanon_pseudo_random,
+ _gss_sanon_wrap_iov,
+ _gss_sanon_unwrap_iov,
+ _gss_sanon_wrap_iov_length,
+ NULL, /* gm_store_cred */
+ _gss_sanon_export_cred,
+ _gss_sanon_import_cred,
+ _gss_sanon_acquire_cred_from,
+ NULL, /* gm_acquire_cred_impersonate_name */
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ sanon_mo,
+ sizeof(sanon_mo) / sizeof(sanon_mo[0]),
+ NULL, /* gm_localname */
+ NULL, /* gm_authorize_localname */
+ NULL, /* gm_display_name_ext */
+ NULL, /* gm_inquire_name */
+ NULL, /* gm_get_name_attribute */
+ NULL, /* gm_set_name_attribute */
+ NULL, /* gm_delete_name_attribute */
+ NULL, /* gm_export_name_composite */
+ _gss_sanon_duplicate_cred,
+ _gss_sanon_add_cred_from,
+ NULL, /* gm_store_cred_into */
+ _gssspi_sanon_query_mechanism_info,
+ _gssspi_sanon_query_meta_data,
+ _gssspi_sanon_exchange_meta_data,
+ NULL, /* gm_store_cred_into2 */
+ NULL, /* gm_compat */
+};
+
+gssapi_mech_interface
+__gss_sanon_initialize(void)
+{
+ return &sanon_mech;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/import_cred.c b/third_party/heimdal/lib/gssapi/sanon/import_cred.c
new file mode 100644
index 0000000..4266ef1
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/import_cred.c
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_import_cred(OM_uint32 *minor,
+ gss_buffer_t token,
+ gss_cred_id_t *cred_handle)
+{
+ return _gss_sanon_import_name(minor, token,
+ GSS_C_NT_EXPORT_NAME,
+ (gss_name_t *)cred_handle);
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/import_name.c b/third_party/heimdal/lib/gssapi/sanon/import_name.c
new file mode 100644
index 0000000..1a228b6
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/import_name.c
@@ -0,0 +1,163 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+static int
+is_anonymous_identity_p(gss_buffer_t name_string, gss_OID name_type)
+{
+ if (gss_oid_equal(name_type, GSS_C_NT_ANONYMOUS))
+ return TRUE;
+ else if ((name_type == GSS_C_NO_OID ||
+ gss_oid_equal(name_type, GSS_C_NT_USER_NAME) ||
+ gss_oid_equal(name_type, GSS_KRB5_NT_PRINCIPAL_NAME)) &&
+ buffer_equal_p(name_string, _gss_sanon_wellknown_user_name))
+ return TRUE;
+ else if (gss_oid_equal(name_type, GSS_C_NT_HOSTBASED_SERVICE) &&
+ buffer_equal_p(name_string, _gss_sanon_wellknown_service_name))
+ return TRUE;
+
+ return FALSE;
+}
+
+static krb5_error_code
+storage_ret_der_oid(krb5_storage *sp, gss_OID_desc *oid)
+{
+ krb5_error_code ret;
+ uint16_t der_oid_len;
+ uint8_t oid_len, tag;
+
+ oid->length = 0;
+ oid->elements = NULL;
+
+ ret = krb5_ret_uint16(sp, &der_oid_len);
+ if (ret == 0)
+ ret = krb5_ret_uint8(sp, &tag);
+ if (ret == 0)
+ ret = krb5_ret_uint8(sp, &oid_len);
+ if (ret)
+ return ret;
+ if (tag != 0x06)
+ return EINVAL;
+
+ if (der_oid_len != 2 + oid_len)
+ return EINVAL;
+
+ oid->elements = malloc(oid_len);
+ if (oid->elements == NULL)
+ return ENOMEM;
+
+ if (krb5_storage_read(sp, oid->elements, oid_len) != oid_len) {
+ free(oid->elements);
+ oid->elements = NULL;
+ oid->length = 0;
+ return EINVAL;
+ }
+
+ oid->length = oid_len;
+
+ return 0;
+}
+
+static OM_uint32
+import_export_name(OM_uint32 *minor,
+ const gss_buffer_t input_name_buffer,
+ gss_name_t *output_name)
+{
+ OM_uint32 major;
+ krb5_error_code ret;
+ krb5_storage *sp;
+ uint32_t name_len = 0;
+ uint16_t tok_id;
+ gss_OID_desc oid_buf = { 0, NULL };
+ uint8_t is_anonymous;
+
+ sp = krb5_storage_from_readonly_mem(input_name_buffer->value,
+ input_name_buffer->length);
+ if (sp == NULL) {
+ *minor = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_BE);
+
+ major = GSS_S_BAD_NAME;
+ *minor = 0;
+
+ ret = krb5_ret_uint16(sp, &tok_id);
+ if (ret == 0 && tok_id != 0x0401)
+ ret = EINVAL;
+ if (ret == 0)
+ ret = storage_ret_der_oid(sp, &oid_buf);
+ if (ret == 0) {
+ if (!gss_oid_equal(&oid_buf, GSS_SANON_X25519_MECHANISM))
+ ret = EINVAL;
+ free(oid_buf.elements);
+ }
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &name_len);
+ if (ret == 0)
+ ret = krb5_ret_uint8(sp, &is_anonymous);
+ if (ret == 0) {
+ if (name_len != 1)
+ ret = EINVAL;
+ if (is_anonymous == 1) {
+ *output_name = _gss_sanon_anonymous_identity;
+ major = GSS_S_COMPLETE;
+ } else {
+ major = GSS_S_BAD_NAME;
+ }
+ }
+
+ krb5_storage_free(sp);
+
+ if (*minor == 0)
+ *minor = ret;
+
+ return major;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_import_name(OM_uint32 *minor,
+ const gss_buffer_t input_name_buffer,
+ const gss_OID input_name_type,
+ gss_name_t *output_name)
+{
+ if (gss_oid_equal(input_name_type, GSS_C_NT_EXPORT_NAME))
+ return import_export_name(minor, input_name_buffer, output_name);
+
+ *minor = 0;
+ *output_name =
+ is_anonymous_identity_p(input_name_buffer, input_name_type) ?
+ _gss_sanon_anonymous_identity : _gss_sanon_non_anonymous_identity;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/import_sec_context.c b/third_party/heimdal/lib/gssapi/sanon/import_sec_context.c
new file mode 100644
index 0000000..9aa682a
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/import_sec_context.c
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_import_sec_context(OM_uint32 *minor,
+ const gss_buffer_t interprocess_token,
+ gss_ctx_id_t *context_handle)
+{
+ OM_uint32 major = GSS_S_FAILURE;
+ sanon_ctx sc;
+
+ *minor = ENOMEM;
+ *context_handle = GSS_C_NO_CONTEXT;
+
+ if ((sc = calloc(1, sizeof(*sc))) &&
+ (major = gss_import_sec_context(minor,
+ interprocess_token,
+ &sc->rfc4121)) == GSS_S_COMPLETE) {
+ *context_handle = (gss_ctx_id_t)sc;
+ sc = NULL;
+ }
+
+ free(sc);
+ return major;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/init_sec_context.c b/third_party/heimdal/lib/gssapi/sanon/init_sec_context.c
new file mode 100644
index 0000000..4c199ed
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/init_sec_context.c
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+int
+_gss_sanon_available_p(gss_const_cred_id_t claimant_cred_handle,
+ gss_const_name_t target_name,
+ OM_uint32 req_flags)
+{
+ OM_uint32 minor;
+ gss_name_t initiator_name = GSS_C_NO_NAME;
+ int available;
+
+ if (claimant_cred_handle != GSS_C_NO_CREDENTIAL) {
+ _gss_sanon_inquire_cred(&minor, claimant_cred_handle,
+ &initiator_name, NULL, NULL, NULL);
+ heim_assert(initiator_name != GSS_C_NO_NAME,
+ "Invalid null SAnon initiator name");
+ }
+
+ /*
+ * SAnon is available if one of the following is true:
+ *
+ * The caller set anon_req_flag (GSS_C_ANON_FLAG)
+ * The claimant_cred_handle identity is anonymous
+ * The claimant_cred_handle is the default credential
+ * and target_name is anonymous
+ */
+ if (req_flags & GSS_C_ANON_FLAG)
+ available = TRUE;
+ else if (initiator_name == _gss_sanon_anonymous_identity)
+ available = TRUE;
+ else if (claimant_cred_handle == GSS_C_NO_CREDENTIAL &&
+ target_name == _gss_sanon_anonymous_identity)
+ available = TRUE;
+ else
+ available = FALSE;
+
+ _gss_sanon_release_name(&minor, &initiator_name);
+ return available;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_init_sec_context(OM_uint32 *minor,
+ gss_const_cred_id_t cred_handle,
+ gss_ctx_id_t *context_handle,
+ gss_const_name_t target_name,
+ const gss_OID mech_type,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ const gss_buffer_t input_token,
+ gss_OID *actual_mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 *ret_flags,
+ OM_uint32 *time_rec)
+{
+ gss_buffer_desc mech_token = GSS_C_EMPTY_BUFFER;
+ OM_uint32 major, tmp;
+ sanon_ctx sc = (sanon_ctx)*context_handle;
+ OM_uint32 flags;
+ gss_buffer_desc session_key = GSS_C_EMPTY_BUFFER;
+
+ *minor = 0;
+ _mg_buffer_zero(output_token);
+
+ if (!_gss_sanon_available_p(cred_handle, target_name, req_flags)) {
+ major = GSS_S_UNAVAILABLE;
+ goto out;
+ }
+
+ /* we always support the following flags */
+ flags = GSS_C_REPLAY_FLAG | GSS_C_SEQUENCE_FLAG | GSS_C_CONF_FLAG |
+ GSS_C_INTEG_FLAG | GSS_C_ANON_FLAG;
+ /* we support the following optional flags */
+ flags |= req_flags & SANON_PROTOCOL_FLAG_MASK;
+
+ if (sc == NULL) {
+ uint8_t pk_and_flags[crypto_scalarmult_curve25519_BYTES + 8];
+
+ if (input_token != GSS_C_NO_BUFFER && input_token->length != 0) {
+ major = GSS_S_DEFECTIVE_TOKEN;
+ goto out;
+ }
+
+ sc = calloc(1, sizeof(*sc));
+ if (sc == NULL) {
+ *minor = ENOMEM;
+ major = GSS_S_FAILURE;
+ goto out;
+ }
+
+ sc->is_initiator = 1;
+
+ /* compute public and secret keys */
+ major = _gss_sanon_curve25519_base(minor, sc);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+
+ if (flags & SANON_PROTOCOL_FLAG_MASK) {
+ memcpy(pk_and_flags, sc->pk, sizeof(sc->pk));
+ _gss_mg_encode_be_uint32(0, &pk_and_flags[sizeof(sc->pk)]);
+ _gss_mg_encode_be_uint32(flags & SANON_PROTOCOL_FLAG_MASK,
+ &pk_and_flags[sizeof(sc->pk) + 4]);
+ mech_token.length = sizeof(pk_and_flags);
+ mech_token.value = pk_and_flags;
+ } else {
+ mech_token.length = sizeof(sc->pk);
+ mech_token.value = sc->pk;
+ }
+
+ /* send public key to acceptor */
+ major = gss_encapsulate_token(&mech_token,
+ GSS_SANON_X25519_MECHANISM,
+ output_token);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+
+ *context_handle = (gss_ctx_id_t)sc;
+ major = GSS_S_CONTINUE_NEEDED;
+ } else {
+ static gss_buffer_desc empty = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc pk, hok_mic;
+
+ if (input_token == GSS_C_NO_BUFFER ||
+ input_token->length < crypto_scalarmult_curve25519_BYTES) {
+ major = GSS_S_DEFECTIVE_TOKEN;
+ goto out;
+ } else if (sc->rfc4121 != GSS_C_NO_CONTEXT || !(sc->is_initiator)) {
+ major = GSS_S_BAD_STATUS;
+ goto out;
+ }
+
+ pk.length = crypto_scalarmult_curve25519_BYTES;
+ pk.value = input_token->value;
+
+ /* compute shared secret */
+ major = _gss_sanon_curve25519(minor, sc, &pk,
+ flags & SANON_PROTOCOL_FLAG_MASK,
+ input_chan_bindings, &session_key);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+
+ flags |= GSS_C_TRANS_FLAG;
+
+ major = _gss_sanon_import_rfc4121_context(minor, sc, flags, &session_key);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+
+ /* verify holder of key MIC */
+ hok_mic.length = input_token->length - pk.length;
+ hok_mic.value = (uint8_t *)input_token->value + pk.length;
+
+ major = _gss_sanon_verify_mic(minor, (gss_const_ctx_id_t)sc,
+ &empty, &hok_mic, NULL);
+ if (major != GSS_S_COMPLETE)
+ goto out;
+ }
+
+ if (ret_flags)
+ *ret_flags = flags;
+ if (time_rec)
+ *time_rec = GSS_C_INDEFINITE;
+
+out:
+ if (actual_mech_type)
+ *actual_mech_type = GSS_SANON_X25519_MECHANISM;
+
+ if (GSS_ERROR(major)) {
+ _gss_sanon_delete_sec_context(&tmp, (gss_ctx_id_t *)&sc, GSS_C_NO_BUFFER);
+ *context_handle = GSS_C_NO_CONTEXT;
+ }
+ _gss_secure_release_buffer(&tmp, &session_key);
+
+ return major;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/inquire_context.c b/third_party/heimdal/lib/gssapi/sanon/inquire_context.c
new file mode 100644
index 0000000..f5aa727
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/inquire_context.c
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_inquire_context(OM_uint32 *minor,
+ gss_const_ctx_id_t context_handle,
+ gss_name_t *src_name,
+ gss_name_t *targ_name,
+ OM_uint32 *lifetime_rec,
+ gss_OID *mech_type,
+ OM_uint32 *ctx_flags,
+ int *locally_initiated,
+ int *open_context)
+{
+ const sanon_ctx sc = (const sanon_ctx)context_handle;
+ OM_uint32 major = GSS_S_COMPLETE;
+
+ *minor = 0;
+
+ if (sc == NULL)
+ return GSS_S_NO_CONTEXT;
+
+ if (src_name)
+ *src_name = _gss_sanon_anonymous_identity;
+ if (targ_name)
+ *targ_name = _gss_sanon_anonymous_identity;
+ if (lifetime_rec)
+ *lifetime_rec = GSS_C_INDEFINITE;
+ if (mech_type)
+ *mech_type = GSS_SANON_X25519_MECHANISM;
+ if (sc->rfc4121 == GSS_C_NO_CONTEXT) {
+ if (locally_initiated)
+ *locally_initiated = sc->is_initiator;
+ if (open_context)
+ *open_context = 0;
+ if (ctx_flags)
+ *ctx_flags = GSS_C_REPLAY_FLAG | GSS_C_SEQUENCE_FLAG |
+ GSS_C_CONF_FLAG | GSS_C_INTEG_FLAG | GSS_C_ANON_FLAG;
+ } else {
+ major = gss_inquire_context(minor, sc->rfc4121, NULL, NULL, NULL,
+ NULL, ctx_flags, locally_initiated,
+ open_context);
+ }
+ return major;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/inquire_cred.c b/third_party/heimdal/lib/gssapi/sanon/inquire_cred.c
new file mode 100644
index 0000000..b25ff2f
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/inquire_cred.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+_gss_sanon_inquire_cred(OM_uint32 *minor,
+ gss_const_cred_id_t cred_handle,
+ gss_name_t *name_ret,
+ OM_uint32 *lifetime,
+ gss_cred_usage_t *cred_usage,
+ gss_OID_set *mechanisms)
+{
+ *minor = 0;
+
+ if (cred_handle == GSS_C_NO_CREDENTIAL)
+ return GSS_S_NO_CRED;
+
+ /* the credential handle is a reference to the cred name */
+ if (name_ret)
+ *name_ret = (gss_name_t)cred_handle;
+ if (lifetime)
+ *lifetime = GSS_C_INDEFINITE;
+ if (cred_usage)
+ *cred_usage = GSS_C_BOTH;
+ if (mechanisms)
+ *mechanisms = GSS_C_NO_OID_SET;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/inquire_cred_by_mech.c b/third_party/heimdal/lib/gssapi/sanon/inquire_cred_by_mech.c
new file mode 100644
index 0000000..4f8bf66
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/inquire_cred_by_mech.c
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2003, 2006, 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_inquire_cred_by_mech(OM_uint32 *minor,
+ gss_const_cred_id_t cred_handle,
+ const gss_OID mech_type,
+ gss_name_t *name,
+ OM_uint32 *initiator_lifetime,
+ OM_uint32 *acceptor_lifetime,
+ gss_cred_usage_t *cred_usage)
+{
+ gss_cred_usage_t usage;
+ OM_uint32 major;
+ OM_uint32 lifetime;
+
+ major = _gss_sanon_inquire_cred(minor, cred_handle,
+ name, &lifetime, &usage, NULL);
+ if (major)
+ return major;
+
+ if (initiator_lifetime) {
+ if (usage == GSS_C_INITIATE || usage == GSS_C_BOTH)
+ *initiator_lifetime = lifetime;
+ else
+ *initiator_lifetime = 0;
+ }
+
+ if (acceptor_lifetime) {
+ if (usage == GSS_C_ACCEPT || usage == GSS_C_BOTH)
+ *acceptor_lifetime = lifetime;
+ else
+ *acceptor_lifetime = 0;
+ }
+
+ if (cred_usage)
+ *cred_usage = usage;
+
+ *minor = 0;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/inquire_mechs_for_name.c b/third_party/heimdal/lib/gssapi/sanon/inquire_mechs_for_name.c
new file mode 100644
index 0000000..df7387c
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/inquire_mechs_for_name.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_inquire_mechs_for_name(OM_uint32 *minor_status,
+ gss_const_name_t input_name,
+ gss_OID_set *mech_types)
+{
+ OM_uint32 ret, tmp;
+
+ ret = gss_create_empty_oid_set(minor_status, mech_types);
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+
+ ret = gss_add_oid_set_member(minor_status,
+ GSS_SANON_X25519_MECHANISM,
+ mech_types);
+ if (ret != GSS_S_COMPLETE)
+ gss_release_oid_set(&tmp, mech_types);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/inquire_names_for_mech.c b/third_party/heimdal/lib/gssapi/sanon/inquire_names_for_mech.c
new file mode 100644
index 0000000..c8b7f23
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/inquire_names_for_mech.c
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "sanon_locl.h"
+
+static gss_OID name_list[] = {
+ GSS_C_NT_HOSTBASED_SERVICE,
+ GSS_C_NT_USER_NAME,
+ GSS_C_NT_EXPORT_NAME,
+ GSS_C_NT_ANONYMOUS,
+ GSS_KRB5_NT_PRINCIPAL_NAME,
+ NULL
+};
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_inquire_names_for_mech(OM_uint32 *minor,
+ const gss_OID mechanism,
+ gss_OID_set *name_types)
+{
+ OM_uint32 ret, tmp;
+ int i;
+
+ *minor = 0;
+
+ if (gss_oid_equal(mechanism, GSS_SANON_X25519_MECHANISM) == 0 &&
+ gss_oid_equal(mechanism, GSS_C_NULL_OID) == 0) {
+ *name_types = GSS_C_NO_OID_SET;
+ return GSS_S_BAD_MECH;
+ }
+
+ ret = gss_create_empty_oid_set(minor, name_types);
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+
+ for (i = 0; name_list[i] != NULL; i++) {
+ ret = gss_add_oid_set_member(minor,
+ name_list[i],
+ name_types);
+ if (ret != GSS_S_COMPLETE)
+ break;
+ }
+
+ if (ret != GSS_S_COMPLETE)
+ gss_release_oid_set(&tmp, name_types);
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/inquire_sec_context_by_oid.c b/third_party/heimdal/lib/gssapi/sanon/inquire_sec_context_by_oid.c
new file mode 100644
index 0000000..1d8bc4b
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/inquire_sec_context_by_oid.c
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_inquire_sec_context_by_oid(OM_uint32 *minor,
+ gss_const_ctx_id_t context_handle,
+ const gss_OID desired_object,
+ gss_buffer_set_t *data_set)
+{
+ const sanon_ctx sc = (const sanon_ctx)context_handle;
+
+ if (sc == NULL)
+ return GSS_S_NO_CONTEXT;
+
+ *data_set = GSS_C_NO_BUFFER_SET;
+
+ if (gss_oid_equal(desired_object, GSS_C_INQ_SSPI_SESSION_KEY) ||
+ gss_oid_equal(desired_object, GSS_KRB5_GET_SUBKEY_X) ||
+ gss_oid_equal(desired_object, GSS_KRB5_GET_INITIATOR_SUBKEY_X) ||
+ gss_oid_equal(desired_object, GSS_KRB5_GET_ACCEPTOR_SUBKEY_X) ||
+ gss_oid_equal(desired_object, GSS_KRB5_EXPORT_LUCID_CONTEXT_X))
+ return gss_inquire_sec_context_by_oid(minor, sc->rfc4121,
+ desired_object, data_set);
+ else if (gss_oid_equal(desired_object, GSS_C_INQ_NEGOEX_KEY) ||
+ gss_oid_equal(desired_object, GSS_C_INQ_NEGOEX_VERIFY_KEY))
+ return _gss_sanon_inquire_negoex_key(minor, sc, desired_object, data_set);
+ else {
+ *minor = EINVAL;
+ return GSS_S_UNAVAILABLE;
+ }
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/negoex.c b/third_party/heimdal/lib/gssapi/sanon/negoex.c
new file mode 100644
index 0000000..c6a21dd
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/negoex.c
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gssspi_sanon_query_mechanism_info(OM_uint32 *minor,
+ gss_const_OID mech_oid,
+ unsigned char auth_scheme[16])
+{
+ heim_assert(gss_oid_equal(mech_oid, GSS_SANON_X25519_MECHANISM),
+ "Invalid mechanism OID passed to query_mechanism_info");
+
+ *minor = 0;
+
+ /* {DEE384FF-1086-4E86-BE78-B94170BFD376} */
+ memcpy(auth_scheme,
+ "\xff\x84\xe3\xde\x86\x10\x86\x4e\xbe\x78\xb9\x41\x70\xbf\xd3\x76", 16);
+
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_gss_sanon_inquire_negoex_key(OM_uint32 *minor,
+ const sanon_ctx sc,
+ gss_const_OID desired_object,
+ gss_buffer_set_t *data_set)
+{
+ OM_uint32 major, tmpMinor;
+ int initiator_key;
+ uint8_t typebytes[4];
+ gss_buffer_desc salt, keyvalue = GSS_C_EMPTY_BUFFER, keytype;
+
+ if (sc->rfc4121 == GSS_C_NO_CONTEXT) {
+ *minor = KRB5KRB_AP_ERR_NOKEY;
+ return GSS_S_UNAVAILABLE;
+ }
+
+ initiator_key = !!(sc->is_initiator);
+
+ if (gss_oid_equal(desired_object, GSS_C_INQ_NEGOEX_VERIFY_KEY))
+ initiator_key ^= 1;
+ else if (!gss_oid_equal(desired_object, GSS_C_INQ_NEGOEX_KEY))
+ return GSS_S_UNAVAILABLE;
+
+ if (initiator_key) {
+ salt.length = sizeof("sanon-x25519-initiator-negoex-key") - 1;
+ salt.value = "sanon-x25519-initiator-negoex-key";
+ } else {
+ salt.length = sizeof("sanon-x25519-acceptor-negoex-key") - 1;
+ salt.value = "sanon-x25519-acceptor-negoex-key";
+ }
+
+ _gss_mg_encode_le_uint32(KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128, typebytes);
+
+ keytype.length = sizeof(typebytes);
+ keytype.value = typebytes;
+
+ major = gss_pseudo_random(minor, sc->rfc4121,
+ GSS_C_PRF_KEY_FULL, &salt,
+ 16, &keyvalue);
+ if (major == GSS_S_COMPLETE)
+ major = gss_add_buffer_set_member(minor, &keyvalue, data_set);
+ if (major == GSS_S_COMPLETE)
+ major = gss_add_buffer_set_member(minor, &keytype, data_set);
+
+ _gss_secure_release_buffer(&tmpMinor, &keyvalue);
+
+ return major;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gssspi_sanon_query_meta_data(OM_uint32 *minor,
+ gss_const_OID mech_oid,
+ gss_cred_id_t cred_handle,
+ gss_ctx_id_t *context_handle,
+ gss_const_name_t targ_name,
+ OM_uint32 req_flags,
+ gss_buffer_t meta_data)
+{
+ int is_initiator = (targ_name != GSS_C_NO_NAME);
+
+ *minor = 0;
+
+ if (is_initiator &&
+ !_gss_sanon_available_p(cred_handle, targ_name, req_flags))
+ return GSS_S_UNAVAILABLE;
+
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gssspi_sanon_exchange_meta_data(OM_uint32 *minor,
+ gss_const_OID mech_oid,
+ gss_cred_id_t cred_handle,
+ gss_ctx_id_t *context_handle,
+ gss_const_name_t targ_name,
+ OM_uint32 req_flags,
+ gss_const_buffer_t meta_data)
+{
+ *minor = 0;
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/process_context_token.c b/third_party/heimdal/lib/gssapi/sanon/process_context_token.c
new file mode 100644
index 0000000..077c8cb
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/process_context_token.c
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+_gss_sanon_process_context_token(OM_uint32 *minor,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t token_buffer)
+{
+ *minor = 0;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/release_cred.c b/third_party/heimdal/lib/gssapi/sanon/release_cred.c
new file mode 100644
index 0000000..aa95272
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/release_cred.c
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_release_cred(OM_uint32 *minor,
+ gss_cred_id_t *cred_handle)
+{
+ *minor = 0;
+ *cred_handle = GSS_C_NO_CREDENTIAL;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/release_name.c b/third_party/heimdal/lib/gssapi/sanon/release_name.c
new file mode 100644
index 0000000..7ba788c
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/release_name.c
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sanon_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_sanon_release_name(OM_uint32 *minor,
+ gss_name_t *input_name)
+{
+ *minor = 0;
+ *input_name = GSS_C_NO_NAME;
+
+ return GSS_S_COMPLETE;
+}
diff --git a/third_party/heimdal/lib/gssapi/sanon/sanon_locl.h b/third_party/heimdal/lib/gssapi/sanon/sanon_locl.h
new file mode 100644
index 0000000..93d6aa8
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/sanon/sanon_locl.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2019-2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef SANON_LOCL_H
+#define SANON_LOCL_H 1
+
+#include <config.h>
+
+#include <krb5_locl.h> /* for _krb5_SP800_108_HMAC_KDF() */
+
+#include <hcrypto/x25519_ref10.h>
+
+#include <gssapi.h>
+#include <gkrb5_err.h> /* for GSS_KRB5_S_XXX */
+
+#include "mech/mech_locl.h"
+
+typedef struct sanon_ctx_desc {
+ /* X25519 ECDH secret key */
+ uint8_t sk[crypto_scalarmult_curve25519_BYTES];
+ /* X25519 ECDH public key */
+ uint8_t pk[crypto_scalarmult_curve25519_BYTES];
+ /* krb5 context for message protection/PRF */
+ gss_ctx_id_t rfc4121;
+ unsigned is_initiator : 1;
+} *sanon_ctx;
+
+extern gss_name_t _gss_sanon_anonymous_identity;
+extern gss_name_t _gss_sanon_non_anonymous_identity;
+
+extern gss_cred_id_t _gss_sanon_anonymous_cred;
+extern gss_cred_id_t _gss_sanon_non_anonymous_cred;
+
+#include "sanon-private.h"
+
+#define SANON_WELLKNOWN_USER_NAME "WELLKNOWN/ANONYMOUS@WELLKNOWN:ANONYMOUS"
+#define SANON_WELLKNOWN_USER_NAME_LEN (sizeof(SANON_WELLKNOWN_USER_NAME) - 1)
+
+extern gss_buffer_t _gss_sanon_wellknown_user_name;
+
+#define SANON_WELLKNOWN_SERVICE_NAME "WELLKNOWN@ANONYMOUS"
+#define SANON_WELLKNOWN_SERVICE_NAME_LEN (sizeof(SANON_WELLKNOWN_SERVICE_NAME) - 1)
+
+extern gss_buffer_t _gss_sanon_wellknown_service_name;
+
+static inline int
+buffer_equal_p(gss_const_buffer_t b1, gss_const_buffer_t b2)
+{
+ return b1->length == b2->length &&
+ memcmp(b1->value, b2->value, b2->length) == 0;
+}
+
+/* flags that are valid to be sent from a SAnon initiator in the flags field */
+#define SANON_PROTOCOL_FLAG_MASK ( GSS_C_DCE_STYLE | GSS_C_IDENTIFY_FLAG | GSS_C_EXTENDED_ERROR_FLAG )
+
+#endif /* SANON_LOCL_H */
diff --git a/third_party/heimdal/lib/gssapi/spnego/accept_sec_context.c b/third_party/heimdal/lib/gssapi/spnego/accept_sec_context.c
new file mode 100644
index 0000000..c4ac745
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/spnego/accept_sec_context.c
@@ -0,0 +1,1024 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * Portions Copyright (c) 2004 PADL Software Pty Ltd.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "spnego_locl.h"
+
+static OM_uint32
+send_reject (OM_uint32 *minor_status,
+ gss_const_buffer_t mech_token,
+ gss_buffer_t output_token)
+{
+ NegotiationToken nt;
+ size_t size;
+ heim_octet_string responseToken;
+
+ nt.element = choice_NegotiationToken_negTokenResp;
+
+ ALLOC(nt.u.negTokenResp.negState, 1);
+ if (nt.u.negTokenResp.negState == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ *(nt.u.negTokenResp.negState) = reject;
+ nt.u.negTokenResp.supportedMech = NULL;
+ nt.u.negTokenResp.responseToken = NULL;
+
+ if (mech_token != GSS_C_NO_BUFFER && mech_token->value != NULL) {
+ responseToken.length = mech_token->length;
+ responseToken.data = mech_token->value;
+ nt.u.negTokenResp.responseToken = &responseToken;
+ } else
+ nt.u.negTokenResp.responseToken = NULL;
+ nt.u.negTokenResp.mechListMIC = NULL;
+
+ ASN1_MALLOC_ENCODE(NegotiationToken,
+ output_token->value, output_token->length, &nt,
+ &size, *minor_status);
+ nt.u.negTokenResp.responseToken = NULL; /* allocated on stack */
+ free_NegotiationToken(&nt);
+ if (*minor_status != 0)
+ return GSS_S_FAILURE;
+
+ return GSS_S_BAD_MECH;
+}
+
+static OM_uint32
+acceptor_approved(OM_uint32 *minor_status,
+ void *userptr,
+ gss_const_name_t target_name,
+ gss_const_cred_id_t cred_handle,
+ gss_OID mech)
+{
+ gss_cred_id_t cred = GSS_C_NO_CREDENTIAL;
+ gss_OID_set oidset = GSS_C_NO_OID_SET;
+ OM_uint32 junk, ret;
+
+ if (target_name == GSS_C_NO_NAME)
+ return GSS_S_COMPLETE;
+
+ if (gss_oid_equal(mech, GSS_NEGOEX_MECHANISM)) {
+ size_t i;
+
+ ret = _gss_spnego_indicate_mechs(minor_status, &oidset);
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+
+ /* before committing to NegoEx, check we can negotiate a mech */
+ for (i = 0; i < oidset->count; i++) {
+ gss_OID inner_mech = &oidset->elements[i];
+
+ if (_gss_negoex_mech_p(inner_mech)) {
+ ret = acceptor_approved(minor_status, userptr,
+ target_name, cred_handle,
+ inner_mech);
+ if (ret == GSS_S_COMPLETE)
+ break;
+ }
+ }
+ } else if (cred_handle != GSS_C_NO_CREDENTIAL) {
+ ret = gss_inquire_cred_by_mech(minor_status, cred_handle, mech,
+ NULL, NULL, NULL, NULL);
+ } else {
+ ret = gss_create_empty_oid_set(minor_status, &oidset);
+ if (ret == GSS_S_COMPLETE)
+ ret = gss_add_oid_set_member(minor_status, mech, &oidset);
+ if (ret == GSS_S_COMPLETE)
+ ret = gss_acquire_cred(minor_status, target_name,
+ GSS_C_INDEFINITE, oidset,
+ GSS_C_ACCEPT, &cred, NULL, NULL);
+ }
+
+ gss_release_oid_set(&junk, &oidset);
+ gss_release_cred(&junk, &cred);
+
+ return ret;
+}
+
+static OM_uint32
+send_supported_mechs (OM_uint32 *minor_status,
+ gssspnego_ctx ctx,
+ gss_const_cred_id_t acceptor_cred,
+ gss_buffer_t output_token)
+{
+ NegotiationToken2 nt;
+ size_t buf_len = 0;
+ gss_buffer_desc data;
+ OM_uint32 ret;
+
+ memset(&nt, 0, sizeof(nt));
+
+ nt.element = choice_NegotiationToken2_negTokenInit;
+ nt.u.negTokenInit.reqFlags = NULL;
+ nt.u.negTokenInit.mechToken = NULL;
+ nt.u.negTokenInit.negHints = NULL;
+
+ ret = _gss_spnego_indicate_mechtypelist(minor_status, GSS_C_NO_NAME, 0,
+ acceptor_approved, ctx, 1, acceptor_cred,
+ &nt.u.negTokenInit.mechTypes, NULL);
+ if (ret != GSS_S_COMPLETE) {
+ return ret;
+ }
+
+ ALLOC(nt.u.negTokenInit.negHints, 1);
+ if (nt.u.negTokenInit.negHints == NULL) {
+ *minor_status = ENOMEM;
+ free_NegotiationToken2(&nt);
+ return GSS_S_FAILURE;
+ }
+
+ ALLOC(nt.u.negTokenInit.negHints->hintName, 1);
+ if (nt.u.negTokenInit.negHints->hintName == NULL) {
+ *minor_status = ENOMEM;
+ free_NegotiationToken2(&nt);
+ return GSS_S_FAILURE;
+ }
+
+ *nt.u.negTokenInit.negHints->hintName = strdup("not_defined_in_RFC4178@please_ignore");
+ nt.u.negTokenInit.negHints->hintAddress = NULL;
+
+ ASN1_MALLOC_ENCODE(NegotiationToken2,
+ data.value, data.length, &nt, &buf_len, ret);
+ free_NegotiationToken2(&nt);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+ if (data.length != buf_len) {
+ abort();
+ UNREACHABLE(return GSS_S_FAILURE);
+ }
+
+ ret = gss_encapsulate_token(&data, GSS_SPNEGO_MECHANISM, output_token);
+
+ free (data.value);
+
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+
+ *minor_status = 0;
+
+ return GSS_S_CONTINUE_NEEDED;
+}
+
+static OM_uint32
+send_accept (OM_uint32 *minor_status,
+ gssspnego_ctx context_handle,
+ int optimistic_mech_ok,
+ gss_buffer_t mech_token,
+ gss_const_OID selected_mech, /* valid on initial response only */
+ gss_buffer_t mech_buf,
+ gss_buffer_t output_token)
+{
+ int initial_response = (selected_mech != GSS_C_NO_OID);
+ NegotiationToken nt;
+ OM_uint32 ret, minor;
+ gss_buffer_desc mech_mic_buf;
+ size_t size;
+
+ memset(&nt, 0, sizeof(nt));
+
+ nt.element = choice_NegotiationToken_negTokenResp;
+
+ ALLOC(nt.u.negTokenResp.negState, 1);
+ if (nt.u.negTokenResp.negState == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ if (context_handle->flags.open) {
+ if (mech_token != GSS_C_NO_BUFFER
+ && mech_token->length != 0
+ && mech_buf != GSS_C_NO_BUFFER)
+ *(nt.u.negTokenResp.negState) = accept_incomplete;
+ else
+ *(nt.u.negTokenResp.negState) = accept_completed;
+ } else {
+ if (initial_response && !optimistic_mech_ok)
+ *(nt.u.negTokenResp.negState) = request_mic;
+ else
+ *(nt.u.negTokenResp.negState) = accept_incomplete;
+ }
+
+ if (initial_response) {
+ ALLOC(nt.u.negTokenResp.supportedMech, 1);
+ if (nt.u.negTokenResp.supportedMech == NULL) {
+ *minor_status = ENOMEM;
+ ret = GSS_S_FAILURE;
+ goto out;
+ }
+
+ ret = der_get_oid(selected_mech->elements,
+ selected_mech->length,
+ nt.u.negTokenResp.supportedMech,
+ NULL);
+ if (ret) {
+ *minor_status = ENOMEM;
+ ret = GSS_S_FAILURE;
+ goto out;
+ }
+
+ _gss_spnego_log_mech("acceptor sending selected mech", selected_mech);
+ } else {
+ nt.u.negTokenResp.supportedMech = NULL;
+ }
+
+ if (mech_token != GSS_C_NO_BUFFER && mech_token->length != 0) {
+ ALLOC(nt.u.negTokenResp.responseToken, 1);
+ if (nt.u.negTokenResp.responseToken == NULL) {
+ *minor_status = ENOMEM;
+ ret = GSS_S_FAILURE;
+ goto out;
+ }
+ nt.u.negTokenResp.responseToken->length = mech_token->length;
+ nt.u.negTokenResp.responseToken->data = mech_token->value;
+ mech_token->length = 0;
+ mech_token->value = NULL;
+ } else {
+ nt.u.negTokenResp.responseToken = NULL;
+ }
+
+ if (mech_buf != GSS_C_NO_BUFFER) {
+ ret = gss_get_mic(minor_status,
+ context_handle->negotiated_ctx_id,
+ 0,
+ mech_buf,
+ &mech_mic_buf);
+ if (ret == GSS_S_COMPLETE) {
+ _gss_spnego_ntlm_reset_crypto(&minor, context_handle, FALSE);
+
+ ALLOC(nt.u.negTokenResp.mechListMIC, 1);
+ if (nt.u.negTokenResp.mechListMIC == NULL) {
+ gss_release_buffer(minor_status, &mech_mic_buf);
+ *minor_status = ENOMEM;
+ ret = GSS_S_FAILURE;
+ goto out;
+ }
+ nt.u.negTokenResp.mechListMIC->length = mech_mic_buf.length;
+ nt.u.negTokenResp.mechListMIC->data = mech_mic_buf.value;
+ } else if (ret == GSS_S_UNAVAILABLE) {
+ nt.u.negTokenResp.mechListMIC = NULL;
+ } else {
+ goto out;
+ }
+
+ } else
+ nt.u.negTokenResp.mechListMIC = NULL;
+
+ ASN1_MALLOC_ENCODE(NegotiationToken,
+ output_token->value, output_token->length,
+ &nt, &size, ret);
+ if (ret) {
+ *minor_status = ENOMEM;
+ ret = GSS_S_FAILURE;
+ goto out;
+ }
+
+ /*
+ * The response should not be encapsulated, because
+ * it is a SubsequentContextToken (note though RFC 1964
+ * specifies encapsulation for all _Kerberos_ tokens).
+ */
+
+ if (*(nt.u.negTokenResp.negState) == accept_completed)
+ ret = GSS_S_COMPLETE;
+ else
+ ret = GSS_S_CONTINUE_NEEDED;
+
+ out:
+ free_NegotiationToken(&nt);
+ return ret;
+}
+
+/*
+ * Return the default acceptor identity based on the local hostname
+ * or the GSSAPI_SPNEGO_NAME environment variable.
+ */
+
+static OM_uint32
+default_acceptor_name(OM_uint32 *minor_status,
+ gss_name_t *namep)
+{
+ OM_uint32 major_status;
+ gss_buffer_desc namebuf;
+ char *str = NULL, *host, hostname[MAXHOSTNAMELEN];
+
+ *namep = GSS_C_NO_NAME;
+
+ host = secure_getenv("GSSAPI_SPNEGO_NAME");
+ if (host == NULL) {
+ int rv;
+
+ if (gethostname(hostname, sizeof(hostname)) != 0) {
+ *minor_status = errno;
+ return GSS_S_FAILURE;
+ }
+
+ rv = asprintf(&str, "host@%s", hostname);
+ if (rv < 0 || str == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ host = str;
+ }
+
+ namebuf.length = strlen(host);
+ namebuf.value = host;
+
+ major_status = gss_import_name(minor_status, &namebuf,
+ GSS_C_NT_HOSTBASED_SERVICE, namep);
+
+ free(str);
+
+ return major_status;
+}
+
+/*
+ * Determine whether the mech in mechType can be negotiated. If the
+ * mech is NegoEx, make NegoEx mechanisms available for negotiation.
+ */
+
+static OM_uint32
+select_mech(OM_uint32 *minor_status,
+ gssspnego_ctx ctx,
+ gss_const_cred_id_t cred,
+ gss_const_OID_set supported_mechs,
+ MechType *mechType,
+ int verify_p, /* set on non-optimistic tokens */
+ gss_const_OID *advertised_mech_p)
+{
+ char mechbuf[64];
+ size_t mech_len;
+ gss_OID_desc oid;
+ gss_OID selected_mech = GSS_C_NO_OID;
+ OM_uint32 ret, junk;
+ int negoex_proposed = FALSE, negoex_selected = FALSE;
+ int includeMSCompatOID = FALSE;
+ size_t i;
+
+ *minor_status = 0;
+ *advertised_mech_p = GSS_C_NO_OID; /* deals with broken MS OID */
+
+ ctx->selected_mech_type = GSS_C_NO_OID;
+
+ ret = der_put_oid ((unsigned char *)mechbuf + sizeof(mechbuf) - 1,
+ sizeof(mechbuf),
+ mechType,
+ &mech_len);
+ if (ret)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ oid.length = (OM_uint32)mech_len;
+ oid.elements = mechbuf + sizeof(mechbuf) - mech_len;
+
+ if (gss_oid_equal(&oid, GSS_NEGOEX_MECHANISM))
+ negoex_proposed = TRUE;
+ else if (gss_oid_equal(&oid, &_gss_spnego_mskrb_mechanism_oid_desc))
+ includeMSCompatOID = TRUE;
+
+ for (i = 0; i < supported_mechs->count; i++) {
+ gss_OID iter = &supported_mechs->elements[i];
+ auth_scheme scheme;
+ int is_negoex_mech = /* mechanism is negotiable under NegoEx */
+ gssspi_query_mechanism_info(&junk, iter, scheme) == GSS_S_COMPLETE;
+
+ if (is_negoex_mech && negoex_proposed) {
+ ret = _gss_negoex_add_auth_mech(minor_status, ctx, iter, scheme);
+ if (ret != GSS_S_COMPLETE)
+ break;
+
+ negoex_selected = TRUE;
+ }
+
+ if (gss_oid_equal(includeMSCompatOID ? GSS_KRB5_MECHANISM : &oid, iter)) {
+ ret = _gss_intern_oid(minor_status, iter, &selected_mech);
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+
+ break;
+ }
+ }
+
+ /* always prefer NegoEx if a mechanism supported both */
+ if (negoex_selected)
+ selected_mech = GSS_NEGOEX_MECHANISM;
+ if (selected_mech == GSS_C_NO_OID)
+ ret = GSS_S_BAD_MECH;
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+
+ heim_assert(!gss_oid_equal(selected_mech, GSS_SPNEGO_MECHANISM),
+ "SPNEGO should not be able to negotiate itself");
+
+ if (verify_p) {
+ gss_name_t name = GSS_C_NO_NAME;
+
+ /*
+ * If we do not have a credential, acquire a default name as a hint
+ * to acceptor_approved() so it can attempt to acquire a default
+ * credential.
+ */
+ if (cred == GSS_C_NO_CREDENTIAL) {
+ ret = default_acceptor_name(minor_status, &name);
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+ }
+
+ ret = acceptor_approved(minor_status, ctx, name, cred, selected_mech);
+
+ gss_release_name(&junk, &name);
+ } else {
+ /* Stash optimistic mech for use by _gss_spnego_require_mechlist_mic() */
+ ret = gss_duplicate_oid(minor_status, &oid, &ctx->preferred_mech_type);
+ }
+
+ if (ret == GSS_S_COMPLETE) {
+ *minor_status = 0;
+
+ *advertised_mech_p = ctx->selected_mech_type = selected_mech;
+
+ /* if the initiator used the broken MS OID, send that instead */
+ if (includeMSCompatOID && gss_oid_equal(selected_mech, GSS_KRB5_MECHANISM))
+ *advertised_mech_p = &_gss_spnego_mskrb_mechanism_oid_desc;
+ }
+
+ return ret;
+}
+
+
+static OM_uint32
+acceptor_complete(OM_uint32 * minor_status,
+ gssspnego_ctx ctx,
+ int *get_mic,
+ gss_buffer_t mech_input_token,
+ gss_buffer_t mech_output_token,
+ heim_octet_string *mic,
+ gss_buffer_t output_token)
+{
+ gss_buffer_desc buf = GSS_C_EMPTY_BUFFER;
+ OM_uint32 ret;
+ int verify_mic;
+
+ ctx->flags.require_mic = 1;
+ ctx->flags.safe_omit = _gss_spnego_safe_omit_mechlist_mic(ctx);
+
+ if (ctx->flags.open) {
+ if (mech_input_token == GSS_C_NO_BUFFER) { /* Even/One */
+ verify_mic = 1;
+ *get_mic = 0;
+ } else if (mech_output_token != GSS_C_NO_BUFFER &&
+ mech_output_token->length == 0) { /* Odd */
+ *get_mic = verify_mic = 1;
+ } else { /* Even/One */
+ verify_mic = 0;
+ *get_mic = 1;
+ }
+
+ /*
+ * Change from previous versions: do not generate a MIC if not
+ * necessary. This conforms to RFC4178 s.5 ("if the accepted
+ * mechanism is the most preferred mechanism of both the initiator
+ * and acceptor, then the MIC token exchange... is OPTIONAL"),
+ * and is consistent with MIT and Windows behavior.
+ */
+ if (ctx->flags.safe_omit)
+ *get_mic = 0;
+
+ if (verify_mic && mic == NULL && ctx->flags.safe_omit) {
+ /*
+ * Peer is old and didn't send a mic while we expected
+ * one, but since it safe to omit, let do that
+ */
+ } else if (verify_mic) {
+ ret = _gss_spnego_verify_mechtypes_mic(minor_status, ctx, mic);
+ if (ret) {
+ if (*get_mic)
+ send_reject(minor_status, GSS_C_NO_BUFFER, output_token);
+ if (buf.value)
+ free(buf.value);
+ return ret;
+ }
+ }
+ } else
+ *get_mic = 0;
+
+ return GSS_S_COMPLETE;
+}
+
+/*
+ * Call gss_accept_sec_context() via mechglue or NegoEx, depending on
+ * whether mech_oid is NegoEx.
+ */
+
+static OM_uint32
+mech_accept(OM_uint32 *minor_status,
+ gssspnego_ctx ctx,
+ gss_const_cred_id_t acceptor_cred_handle,
+ gss_const_buffer_t input_token_buffer,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_buffer_t output_token,
+ gss_cred_id_t *delegated_cred_handle)
+{
+ OM_uint32 ret, junk;
+
+ heim_assert(ctx->selected_mech_type != GSS_C_NO_OID,
+ "mech_accept called with no selected mech");
+
+ if (gss_oid_equal(ctx->selected_mech_type, GSS_NEGOEX_MECHANISM)) {
+ ret = _gss_negoex_accept(minor_status,
+ ctx,
+ (gss_cred_id_t)acceptor_cred_handle,
+ input_token_buffer,
+ input_chan_bindings,
+ output_token,
+ delegated_cred_handle);
+ } else {
+ if (ctx->mech_src_name != GSS_C_NO_NAME)
+ gss_release_name(&junk, &ctx->mech_src_name);
+
+ ret = gss_accept_sec_context(minor_status,
+ &ctx->negotiated_ctx_id,
+ acceptor_cred_handle,
+ (gss_buffer_t)input_token_buffer,
+ input_chan_bindings,
+ &ctx->mech_src_name,
+ &ctx->negotiated_mech_type,
+ output_token,
+ &ctx->mech_flags,
+ &ctx->mech_time_rec,
+ delegated_cred_handle);
+ if (GSS_ERROR(ret))
+ gss_mg_collect_error(ctx->negotiated_mech_type, ret, *minor_status);
+ else if (ctx->negotiated_mech_type != GSS_C_NO_OID &&
+ !gss_oid_equal(ctx->negotiated_mech_type, ctx->selected_mech_type))
+ _gss_mg_log(1, "spnego client didn't send the mech they said they would");
+ }
+
+ return ret;
+}
+
+static OM_uint32 GSSAPI_CALLCONV
+acceptor_start
+ (OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ gss_const_cred_id_t acceptor_cred_handle,
+ const gss_buffer_t input_token_buffer,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_name_t * src_name,
+ gss_OID * mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec,
+ gss_cred_id_t *delegated_cred_handle
+ )
+{
+ OM_uint32 ret, junk;
+ NegotiationToken nt;
+ gss_OID_set supported_mechs = GSS_C_NO_OID_SET;
+ size_t size;
+ NegTokenInit *ni;
+ gss_buffer_desc data;
+ gss_buffer_t mech_input_token = GSS_C_NO_BUFFER;
+ gss_buffer_desc mech_output_token;
+ gssspnego_ctx ctx;
+ int get_mic = 0, first_ok = 0, canonical_order;
+ gss_const_OID advertised_mech = GSS_C_NO_OID;
+
+ memset(&nt, 0, sizeof(nt));
+
+ mech_output_token.value = NULL;
+ mech_output_token.length = 0;
+
+ if (input_token_buffer->length == 0)
+ return send_supported_mechs (minor_status, NULL,
+ acceptor_cred_handle, output_token);
+
+ ret = _gss_spnego_alloc_sec_context(minor_status, context_handle);
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+
+ ctx = (gssspnego_ctx)*context_handle;
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+
+ /*
+ * The GSS-API encapsulation is only present on the initial
+ * context token (negTokenInit).
+ */
+ ret = gss_decapsulate_token (input_token_buffer,
+ GSS_SPNEGO_MECHANISM,
+ &data);
+ if (ret)
+ goto out;
+
+ ret = decode_NegotiationToken(data.value, data.length, &nt, &size);
+ gss_release_buffer(minor_status, &data);
+ if (ret) {
+ *minor_status = ret;
+ ret = GSS_S_DEFECTIVE_TOKEN;
+ goto out;
+ }
+ if (nt.element != choice_NegotiationToken_negTokenInit) {
+ *minor_status = 0;
+ ret = GSS_S_DEFECTIVE_TOKEN;
+ goto out;
+ }
+ ni = &nt.u.negTokenInit;
+
+ if (ni->mechTypes.len < 1) {
+ free_NegotiationToken(&nt);
+ *minor_status = 0;
+ ret = GSS_S_DEFECTIVE_TOKEN;
+ goto out;
+ }
+
+ _gss_spnego_log_mechTypes(&ni->mechTypes);
+
+ {
+ MechTypeList mt;
+ int kret;
+
+ mt.len = ni->mechTypes.len;
+ mt.val = ni->mechTypes.val;
+
+ ASN1_MALLOC_ENCODE(MechTypeList,
+ ctx->NegTokenInit_mech_types.value,
+ ctx->NegTokenInit_mech_types.length,
+ &mt, &size, kret);
+ if (kret) {
+ *minor_status = kret;
+ ret = GSS_S_FAILURE;
+ goto out;
+ }
+ }
+
+ if (acceptor_cred_handle != GSS_C_NO_CREDENTIAL)
+ ret = _gss_spnego_inquire_cred_mechs(minor_status,
+ acceptor_cred_handle,
+ &supported_mechs,
+ &canonical_order);
+ else
+ ret = _gss_spnego_indicate_mechs(minor_status, &supported_mechs);
+ if (ret != GSS_S_COMPLETE)
+ goto out;
+
+ /*
+ * First we try the opportunistic token if we have support for it,
+ * don't try to verify we have credential for the token,
+ * gss_accept_sec_context() will (hopefully) tell us that.
+ * If that failes,
+ */
+
+ ret = select_mech(minor_status,
+ ctx,
+ acceptor_cred_handle,
+ supported_mechs,
+ &ni->mechTypes.val[0],
+ 0, /* optimistic token */
+ &advertised_mech);
+
+ if (ret == GSS_S_COMPLETE && ni->mechToken != NULL) {
+ gss_buffer_desc ibuf;
+
+ ibuf.length = ni->mechToken->length;
+ ibuf.value = ni->mechToken->data;
+ mech_input_token = &ibuf;
+
+ _gss_spnego_log_mech("acceptor selected opportunistic mech", ctx->selected_mech_type);
+
+ ret = mech_accept(&junk,
+ ctx,
+ acceptor_cred_handle,
+ mech_input_token,
+ input_chan_bindings,
+ &mech_output_token,
+ delegated_cred_handle);
+ if (ret == GSS_S_COMPLETE || ret == GSS_S_CONTINUE_NEEDED) {
+ first_ok = 1;
+ } else {
+ ctx->selected_mech_type = GSS_C_NO_OID;
+ }
+
+ if (ret == GSS_S_COMPLETE) {
+ ret = acceptor_complete(minor_status,
+ ctx,
+ &get_mic,
+ mech_input_token,
+ &mech_output_token,
+ ni->mechListMIC,
+ output_token);
+ if (ret != GSS_S_COMPLETE)
+ goto out;
+
+ ctx->flags.open = 1;
+ }
+ } else {
+ *minor_status = 0;
+ gss_release_oid_set(&junk, &supported_mechs);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ return gss_mg_set_error_string(GSS_C_NO_OID, GSS_S_NO_CONTEXT,
+ *minor_status,
+ "SPNEGO acceptor didn't find a prefered mechanism");
+ }
+
+ /*
+ * If opportunistic token failed, lets try the other mechs.
+ */
+
+ if (!first_ok) {
+ size_t j;
+
+ /* Call glue layer to find first mech we support */
+ for (j = 1; j < ni->mechTypes.len; ++j) {
+ ret = select_mech(&junk,
+ ctx,
+ acceptor_cred_handle,
+ supported_mechs,
+ &ni->mechTypes.val[j],
+ 1, /* not optimistic token */
+ &advertised_mech);
+ if (ret == GSS_S_COMPLETE) {
+ _gss_spnego_log_mech("acceptor selected non-opportunistic mech",
+ ctx->selected_mech_type);
+ break;
+ }
+ }
+ }
+ if (ctx->selected_mech_type == GSS_C_NO_OID) {
+ heim_assert(ret != GSS_S_COMPLETE, "no oid and no error code?");
+ *minor_status = junk;
+ goto out;
+ }
+
+ /* The initial token always has a response */
+ ret = send_accept(minor_status,
+ ctx,
+ first_ok,
+ &mech_output_token,
+ advertised_mech,
+ get_mic ? &ctx->NegTokenInit_mech_types : NULL,
+ output_token);
+ if (ret)
+ goto out;
+
+out:
+ gss_release_oid_set(&junk, &supported_mechs);
+ if (mech_output_token.value != NULL)
+ gss_release_buffer(&junk, &mech_output_token);
+ free_NegotiationToken(&nt);
+
+
+ if (ret == GSS_S_COMPLETE) {
+ if (src_name != NULL && ctx->mech_src_name != GSS_C_NO_NAME)
+ ret = gss_duplicate_name(minor_status,
+ ctx->mech_src_name,
+ src_name);
+ }
+
+ if (mech_type != NULL)
+ *mech_type = ctx->negotiated_mech_type;
+ if (ret_flags != NULL)
+ *ret_flags = ctx->mech_flags;
+ if (time_rec != NULL)
+ *time_rec = ctx->mech_time_rec;
+
+ if (ret == GSS_S_COMPLETE || ret == GSS_S_CONTINUE_NEEDED) {
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ return ret;
+ }
+
+ _gss_spnego_internal_delete_sec_context(&junk, context_handle,
+ GSS_C_NO_BUFFER);
+
+ return ret;
+}
+
+
+static OM_uint32 GSSAPI_CALLCONV
+acceptor_continue
+ (OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ gss_const_cred_id_t acceptor_cred_handle,
+ const gss_buffer_t input_token_buffer,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_name_t * src_name,
+ gss_OID * mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec,
+ gss_cred_id_t *delegated_cred_handle
+ )
+{
+ OM_uint32 ret, ret2, minor, junk;
+ NegotiationToken nt;
+ size_t nt_len;
+ NegTokenResp *na;
+ unsigned int negState = accept_incomplete;
+ gss_buffer_t mech_input_token = GSS_C_NO_BUFFER;
+ gss_buffer_t mech_output_token = GSS_C_NO_BUFFER;
+ gssspnego_ctx ctx;
+
+ ctx = (gssspnego_ctx)*context_handle;
+
+ /*
+ * The GSS-API encapsulation is only present on the initial
+ * context token (negTokenInit).
+ */
+
+ ret = decode_NegotiationToken(input_token_buffer->value,
+ input_token_buffer->length,
+ &nt, &nt_len);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+ if (nt.element != choice_NegotiationToken_negTokenResp) {
+ *minor_status = 0;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+ na = &nt.u.negTokenResp;
+
+ if (na->negState != NULL) {
+ negState = *(na->negState);
+ }
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+
+ {
+ gss_buffer_desc ibuf, obuf;
+ int get_mic = 0;
+ int require_response;
+
+ if (na->responseToken != NULL) {
+ ibuf.length = na->responseToken->length;
+ ibuf.value = na->responseToken->data;
+ mech_input_token = &ibuf;
+ } else {
+ ibuf.value = NULL;
+ ibuf.length = 0;
+ }
+
+ if (mech_input_token != GSS_C_NO_BUFFER) {
+
+ ret = mech_accept(minor_status,
+ ctx,
+ acceptor_cred_handle,
+ mech_input_token,
+ input_chan_bindings,
+ &obuf,
+ delegated_cred_handle);
+ mech_output_token = &obuf;
+ if (ret != GSS_S_COMPLETE && ret != GSS_S_CONTINUE_NEEDED) {
+ free_NegotiationToken(&nt);
+ send_reject(&junk, mech_output_token, output_token);
+ gss_release_buffer(&junk, mech_output_token);
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ return ret;
+ }
+ if (ret == GSS_S_COMPLETE)
+ ctx->flags.open = 1;
+ } else
+ ret = GSS_S_COMPLETE;
+
+ if (ret == GSS_S_COMPLETE)
+ ret = acceptor_complete(minor_status,
+ ctx,
+ &get_mic,
+ mech_input_token,
+ mech_output_token,
+ na->mechListMIC,
+ output_token);
+
+ if (ctx->mech_flags & GSS_C_DCE_STYLE)
+ require_response = (negState != accept_completed);
+ else
+ require_response = 0;
+
+ /*
+ * Check whether we need to send a result: there should be only
+ * one accept_completed response sent in the entire negotiation
+ */
+ if ((mech_output_token != GSS_C_NO_BUFFER &&
+ mech_output_token->length != 0)
+ || (ctx->flags.open && negState == accept_incomplete)
+ || require_response
+ || get_mic) {
+ ret2 = send_accept (minor_status,
+ ctx,
+ 0, /* ignored on subsequent tokens */
+ mech_output_token,
+ GSS_C_NO_OID,
+ get_mic ? &ctx->NegTokenInit_mech_types : NULL,
+ output_token);
+ if (ret2)
+ goto out;
+ } else
+ ret2 = GSS_S_COMPLETE;
+
+ out:
+ if (ret2 != GSS_S_COMPLETE)
+ ret = ret2;
+ if (mech_output_token != NULL)
+ gss_release_buffer(&minor, mech_output_token);
+ free_NegotiationToken(&nt);
+ }
+
+ if (ret == GSS_S_COMPLETE) {
+ if (src_name != NULL && ctx->mech_src_name != GSS_C_NO_NAME)
+ ret = gss_duplicate_name(minor_status,
+ ctx->mech_src_name,
+ src_name);
+ }
+
+ if (mech_type != NULL)
+ *mech_type = ctx->negotiated_mech_type;
+ if (ret_flags != NULL)
+ *ret_flags = ctx->mech_flags;
+ if (time_rec != NULL)
+ *time_rec = ctx->mech_time_rec;
+
+ if (ret == GSS_S_COMPLETE || ret == GSS_S_CONTINUE_NEEDED) {
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ return ret;
+ }
+
+ _gss_spnego_internal_delete_sec_context(&minor, context_handle,
+ GSS_C_NO_BUFFER);
+
+ return ret;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_accept_sec_context
+ (OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ gss_const_cred_id_t acceptor_cred_handle,
+ const gss_buffer_t input_token_buffer,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_name_t * src_name,
+ gss_OID * mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec,
+ gss_cred_id_t *delegated_cred_handle
+ )
+{
+ _gss_accept_sec_context_t *func;
+
+ *minor_status = 0;
+
+ output_token->length = 0;
+ output_token->value = NULL;
+
+ if (src_name != NULL)
+ *src_name = GSS_C_NO_NAME;
+ if (mech_type != NULL)
+ *mech_type = GSS_C_NO_OID;
+ if (ret_flags != NULL)
+ *ret_flags = 0;
+ if (time_rec != NULL)
+ *time_rec = 0;
+ if (delegated_cred_handle != NULL)
+ *delegated_cred_handle = GSS_C_NO_CREDENTIAL;
+
+
+ if (*context_handle == GSS_C_NO_CONTEXT)
+ func = acceptor_start;
+ else
+ func = acceptor_continue;
+
+
+ return (*func)(minor_status, context_handle, acceptor_cred_handle,
+ input_token_buffer, input_chan_bindings,
+ src_name, mech_type, output_token, ret_flags,
+ time_rec, delegated_cred_handle);
+}
diff --git a/third_party/heimdal/lib/gssapi/spnego/compat.c b/third_party/heimdal/lib/gssapi/spnego/compat.c
new file mode 100644
index 0000000..6cfe552
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/spnego/compat.c
@@ -0,0 +1,684 @@
+/*
+ * Copyright (c) 2004, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "spnego_locl.h"
+
+/*
+ * Apparently Microsoft got the OID wrong, and used
+ * 1.2.840.48018.1.2.2 instead. We need both this and
+ * the correct Kerberos OID here in order to deal with
+ * this. Because this is manifest in SPNEGO only I'd
+ * prefer to deal with this here rather than inside the
+ * Kerberos mechanism.
+ */
+gss_OID_desc _gss_spnego_mskrb_mechanism_oid_desc =
+ {9, rk_UNCONST("\x2a\x86\x48\x82\xf7\x12\x01\x02\x02")};
+
+/*
+ * Allocate a SPNEGO context handle
+ */
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_alloc_sec_context (OM_uint32 * minor_status,
+ gss_ctx_id_t *context_handle)
+{
+ gssspnego_ctx ctx;
+
+ ctx = calloc(1, sizeof(*ctx));
+ if (ctx == NULL) {
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ ctx->NegTokenInit_mech_types.value = NULL;
+ ctx->NegTokenInit_mech_types.length = 0;
+
+ ctx->preferred_mech_type = GSS_C_NO_OID;
+ ctx->selected_mech_type = GSS_C_NO_OID;
+ ctx->negotiated_mech_type = GSS_C_NO_OID;
+
+ ctx->negotiated_ctx_id = GSS_C_NO_CONTEXT;
+
+ ctx->mech_flags = 0;
+ ctx->mech_time_rec = 0;
+ ctx->mech_src_name = GSS_C_NO_NAME;
+
+ ctx->flags.open = 0;
+ ctx->flags.local = 0;
+ ctx->flags.peer_require_mic = 0;
+ ctx->flags.require_mic = 0;
+ ctx->flags.verified_mic = 0;
+
+ HEIMDAL_MUTEX_init(&ctx->ctx_id_mutex);
+
+ ctx->negoex_step = 0;
+ ctx->negoex_transcript = NULL;
+ ctx->negoex_seqnum = 0;
+ HEIM_TAILQ_INIT(&ctx->negoex_mechs);
+ memset(ctx->negoex_conv_id, 0, GUID_LENGTH);
+
+ *context_handle = (gss_ctx_id_t)ctx;
+
+ return GSS_S_COMPLETE;
+}
+
+/*
+ * Free a SPNEGO context handle. The caller must have acquired
+ * the lock before this is called.
+ */
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_internal_delete_sec_context
+ (OM_uint32 *minor_status,
+ gss_ctx_id_t *context_handle,
+ gss_buffer_t output_token
+ )
+{
+ gssspnego_ctx ctx;
+ OM_uint32 ret, minor;
+
+ *minor_status = 0;
+
+ if (context_handle == NULL) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ if (output_token != GSS_C_NO_BUFFER) {
+ output_token->length = 0;
+ output_token->value = NULL;
+ }
+
+ ctx = (gssspnego_ctx)*context_handle;
+ *context_handle = GSS_C_NO_CONTEXT;
+
+ if (ctx == NULL) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ if (ctx->NegTokenInit_mech_types.value)
+ free(ctx->NegTokenInit_mech_types.value);
+
+ ctx->preferred_mech_type = GSS_C_NO_OID;
+ ctx->negotiated_mech_type = GSS_C_NO_OID;
+ ctx->selected_mech_type = GSS_C_NO_OID;
+
+ gss_release_name(&minor, &ctx->target_name);
+ gss_release_name(&minor, &ctx->mech_src_name);
+
+ if (ctx->negotiated_ctx_id != GSS_C_NO_CONTEXT) {
+ ret = gss_delete_sec_context(minor_status,
+ &ctx->negotiated_ctx_id,
+ output_token);
+ ctx->negotiated_ctx_id = GSS_C_NO_CONTEXT;
+ } else {
+ ret = GSS_S_COMPLETE;
+ }
+
+ _gss_negoex_release_context(ctx);
+
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex);
+
+ free(ctx);
+
+ return ret;
+}
+
+static int
+inq_context_by_oid_bool(gssspnego_ctx ctx, gss_OID oid)
+{
+ OM_uint32 major, minor;
+ gss_buffer_set_t data_set = GSS_C_NO_BUFFER_SET;
+ uint8_t ret = 0;
+
+ major = gss_inquire_sec_context_by_oid(&minor, ctx->negotiated_ctx_id,
+ oid, &data_set);
+ if (major != GSS_S_COMPLETE)
+ return FALSE;
+
+ if (data_set != GSS_C_NO_BUFFER_SET &&
+ data_set->count == 1 &&
+ data_set->elements[0].length == 1)
+ ret = *((uint8_t *)data_set->elements[0].value);
+
+ gss_release_buffer_set(&minor, &data_set);
+
+ return ret != 0;
+}
+
+/*
+ * Returns TRUE if it is safe to omit mechListMIC.
+ */
+
+int
+_gss_spnego_safe_omit_mechlist_mic(gssspnego_ctx ctx)
+{
+ int safe_omit = FALSE;
+
+ if (ctx->flags.peer_require_mic) {
+ _gss_mg_log(10, "spnego: mechListMIC required by peer");
+ } else if (inq_context_by_oid_bool(ctx, GSS_C_INQ_PEER_HAS_BUGGY_SPNEGO)) {
+ /* [MS-SPNG] Appendix A <7> Section 3.1.5.1: may be old peer with buggy SPNEGO */
+ safe_omit = TRUE;
+ _gss_mg_log(10, "spnego: mechListMIC omitted for legacy interoperability");
+ } else if (inq_context_by_oid_bool(ctx, GSS_C_INQ_REQUIRE_MECHLIST_MIC)) {
+ /* [MS-SPNG] Appendix A <7> Section 3.1.5.1: allow NTLM to force MIC */
+ _gss_mg_log(10, "spnego: mechListMIC required by mechanism");
+ } else if (gss_oid_equal(ctx->selected_mech_type, ctx->preferred_mech_type)) {
+ safe_omit = TRUE;
+ _gss_mg_log(10, "spnego: mechListMIC omitted as preferred mechanism selected");
+ } else {
+ _gss_mg_log(10, "spnego: mechListMIC required by default");
+ }
+
+ return safe_omit;
+}
+
+/*
+ * A map between a GSS-API flag and a (mechanism attribute, weight)
+ * tuple. The list of mechanisms is re-ordered by aggregate weight
+ * (highest weight is more preferred, e.g. if GSS_C_MUTUAL_FLAG and
+ * GSS_C_ANON_FLAG are set, we prefer a mechanism that supports
+ * mutual authentication over one that only supports anonymous).
+ */
+static struct {
+ OM_uint32 flag;
+ gss_OID ma;
+ int weight;
+} flag_to_ma_map[] = {
+ { GSS_C_MUTUAL_FLAG, GSS_C_MA_AUTH_TARG, 2 },
+ { GSS_C_ANON_FLAG, GSS_C_MA_AUTH_INIT_ANON, 1 },
+};
+
+/*
+ * Returns a bitmask indicating GSS flags we can sort on.
+ */
+static inline OM_uint32
+mech_flag_mask(void)
+{
+ size_t i;
+ OM_uint32 mask = 0;
+
+ for (i = 0; i < sizeof(flag_to_ma_map)/sizeof(flag_to_ma_map[0]); i++)
+ mask |= flag_to_ma_map[i].flag;
+
+ return mask;
+}
+
+/*
+ * Returns an integer representing the preference weighting for a
+ * mechanism, based on the requested GSS flags.
+ */
+static int
+mech_weight(gss_const_OID mech, OM_uint32 req_flags)
+{
+ OM_uint32 major, minor;
+ gss_OID_set mech_attrs = GSS_C_NO_OID_SET;
+ int weight = 0;
+ size_t i, j;
+
+ major = gss_inquire_attrs_for_mech(&minor, mech, &mech_attrs, NULL);
+ if (GSS_ERROR(major))
+ return 0;
+
+ for (i = 0; i < sizeof(flag_to_ma_map)/sizeof(flag_to_ma_map[0]); i++) {
+ if ((req_flags & flag_to_ma_map[i].flag) == 0)
+ continue;
+
+ for (j = 0; j < mech_attrs->count; j++) {
+ if (gss_oid_equal(flag_to_ma_map[i].ma, &mech_attrs->elements[j])) {
+ weight += flag_to_ma_map[i].weight;
+ continue;
+ }
+ }
+ }
+
+ gss_release_oid_set(&minor, &mech_attrs);
+
+ return weight;
+}
+
+static int
+mech_compare(const void *mech1, const void *mech2, void *req_flags_p)
+{
+ OM_uint32 req_flags = *((OM_uint32 *)req_flags_p);
+ int mech1_weight = mech_weight(mech1, req_flags);
+ int mech2_weight = mech_weight(mech2, req_flags);
+
+ return mech2_weight - mech1_weight;
+}
+
+/*
+ * Order a list of mechanisms by weight based on requested GSS flags.
+ */
+static void
+order_mechs_by_flags(gss_OID_set mechs, OM_uint32 req_flags)
+{
+ if (req_flags & mech_flag_mask()) { /* skip if flags irrelevant */
+ /*
+ * NB: must be a stable sort to preserve the existing order
+ * of mechanisms that are equally weighted.
+ */
+ mergesort_r(mechs->elements, mechs->count,
+ sizeof(gss_OID_desc), mech_compare, &req_flags);
+ }
+}
+
+static OM_uint32
+add_mech_type(OM_uint32 *minor_status,
+ gss_OID mech_type,
+ MechTypeList *mechtypelist)
+{
+ MechType mech;
+ int ret;
+
+ heim_assert(!gss_oid_equal(mech_type, GSS_SPNEGO_MECHANISM),
+ "SPNEGO mechanism not filtered");
+
+ ret = der_get_oid(mech_type->elements, mech_type->length, &mech, NULL);
+ if (ret == 0) {
+ ret = add_MechTypeList(mechtypelist, &mech);
+ free_MechType(&mech);
+ }
+
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ return GSS_S_COMPLETE;
+}
+
+static int
+add_mech_if_approved(OM_uint32 *minor_status,
+ gss_const_name_t target_name,
+ OM_uint32 (*func)(OM_uint32 *, void *, gss_const_name_t, gss_const_cred_id_t, gss_OID),
+ void *userptr,
+ int includeMSCompatOID,
+ gss_const_cred_id_t cred_handle,
+ MechTypeList *mechtypelist,
+ gss_OID mech_oid,
+ gss_OID *first_mech,
+ OM_uint32 *first_major,
+ OM_uint32 *first_minor,
+ int *added_negoex)
+{
+ OM_uint32 major, minor;
+
+ /*
+ * Unapproved mechanisms are ignored, but we capture their result
+ * code in case we didn't find any other mechanisms, in which case
+ * we return that to the caller of _gss_spnego_indicate_mechtypelist().
+ */
+ major = (*func)(&minor, userptr, target_name, cred_handle, mech_oid);
+ if (major != GSS_S_COMPLETE) {
+ if (*first_mech == GSS_C_NO_OID) {
+ *first_major = major;
+ *first_minor = minor;
+ }
+ return GSS_S_COMPLETE;
+ }
+
+ if (_gss_negoex_mech_p(mech_oid)) {
+ if (*added_negoex == FALSE) {
+ major = add_mech_type(minor_status, GSS_NEGOEX_MECHANISM, mechtypelist);
+ if (major != GSS_S_COMPLETE)
+ return major;
+ *added_negoex = TRUE;
+ }
+
+ if (*first_mech == GSS_C_NO_OID)
+ *first_mech = GSS_NEGOEX_MECHANISM;
+
+ /* if NegoEx-only mech, we are done */
+ if (!_gss_negoex_and_spnego_mech_p(mech_oid))
+ return GSS_S_COMPLETE;
+ }
+
+ if (includeMSCompatOID && gss_oid_equal(mech_oid, GSS_KRB5_MECHANISM)) {
+ major = add_mech_type(minor_status,
+ &_gss_spnego_mskrb_mechanism_oid_desc,
+ mechtypelist);
+ if (major != GSS_S_COMPLETE)
+ return major;
+ }
+
+ major = add_mech_type(minor_status, mech_oid, mechtypelist);
+ if (major != GSS_S_COMPLETE)
+ return major;
+
+ if (*first_mech == GSS_C_NO_OID)
+ *first_mech = mech_oid;
+
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_indicate_mechtypelist (OM_uint32 *minor_status,
+ gss_const_name_t target_name,
+ OM_uint32 req_flags,
+ OM_uint32 (*func)(OM_uint32 *, void *, gss_const_name_t, gss_const_cred_id_t, gss_OID),
+ void *userptr,
+ int includeMSCompatOID,
+ gss_const_cred_id_t cred_handle,
+ MechTypeList *mechtypelist,
+ gss_OID *preferred_mech)
+{
+ gss_OID_set supported_mechs = GSS_C_NO_OID_SET;
+ gss_OID first_mech = GSS_C_NO_OID;
+ OM_uint32 ret, minor;
+ OM_uint32 first_major = GSS_S_BAD_MECH, first_minor = 0;
+ size_t i;
+ int added_negoex = FALSE, canonical_order = FALSE;
+
+ mechtypelist->len = 0;
+ mechtypelist->val = NULL;
+
+ if (cred_handle != GSS_C_NO_CREDENTIAL)
+ ret = _gss_spnego_inquire_cred_mechs(minor_status, cred_handle,
+ &supported_mechs, &canonical_order);
+ else
+ ret = _gss_spnego_indicate_mechs(minor_status, &supported_mechs);
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+
+ if (!canonical_order)
+ order_mechs_by_flags(supported_mechs, req_flags);
+
+ heim_assert(supported_mechs != GSS_C_NO_OID_SET,
+ "NULL mech set returned by SPNEGO inquire/indicate mechs");
+
+ /*
+ * Previously krb5 was tried explicitly, but now the internal mech
+ * list is reordered so that krb5 is first, this should no longer
+ * be required. This permits an application to specify another
+ * mechanism as preferred over krb5 using gss_set_neg_mechs().
+ */
+ for (i = 0; i < supported_mechs->count; i++) {
+ ret = add_mech_if_approved(minor_status, target_name,
+ func, userptr, includeMSCompatOID,
+ cred_handle, mechtypelist,
+ &supported_mechs->elements[i],
+ &first_mech,
+ &first_major, &first_minor,
+ &added_negoex);
+ if (ret != GSS_S_COMPLETE) {
+ gss_release_oid_set(&minor, &supported_mechs);
+ return ret;
+ }
+ }
+
+ heim_assert(mechtypelist->len == 0 || first_mech != GSS_C_NO_OID,
+ "mechtypelist non-empty but no mech selected");
+
+ if (first_mech != GSS_C_NO_OID)
+ ret = _gss_intern_oid(minor_status, first_mech, &first_mech);
+ else if (GSS_ERROR(first_major)) {
+ ret = first_major;
+ *minor_status = first_minor;
+ } else
+ ret = GSS_S_BAD_MECH;
+
+ if (preferred_mech != NULL)
+ *preferred_mech = first_mech;
+
+ gss_release_oid_set(&minor, &supported_mechs);
+
+ return ret;
+}
+
+/*
+ *
+ */
+
+OM_uint32
+_gss_spnego_verify_mechtypes_mic(OM_uint32 *minor_status,
+ gssspnego_ctx ctx,
+ heim_octet_string *mic)
+{
+ gss_buffer_desc mic_buf;
+ OM_uint32 major_status;
+
+ if (mic == NULL) {
+ *minor_status = 0;
+ return gss_mg_set_error_string(GSS_SPNEGO_MECHANISM,
+ GSS_S_DEFECTIVE_TOKEN, 0,
+ "SPNEGO peer failed to send mechListMIC");
+ }
+
+ if (ctx->flags.verified_mic) {
+ /* This doesn't make sense, we've already verified it? */
+ *minor_status = 0;
+ return GSS_S_DUPLICATE_TOKEN;
+ }
+
+ mic_buf.length = mic->length;
+ mic_buf.value = mic->data;
+
+ major_status = gss_verify_mic(minor_status,
+ ctx->negotiated_ctx_id,
+ &ctx->NegTokenInit_mech_types,
+ &mic_buf,
+ NULL);
+ if (major_status == GSS_S_COMPLETE) {
+ _gss_spnego_ntlm_reset_crypto(minor_status, ctx, TRUE);
+ } else if (major_status == GSS_S_UNAVAILABLE) {
+ _gss_mg_log(10, "mech doesn't support MIC, allowing anyway");
+ } else if (major_status) {
+ return gss_mg_set_error_string(GSS_SPNEGO_MECHANISM,
+ GSS_S_DEFECTIVE_TOKEN, *minor_status,
+ "SPNEGO peer sent invalid mechListMIC");
+ }
+ ctx->flags.verified_mic = 1;
+
+ *minor_status = 0;
+
+ return GSS_S_COMPLETE;
+}
+
+/*
+ * According to [MS-SPNG] 3.3.5.1 the crypto state for NTLM is reset
+ * before the completed context is returned to the application.
+ */
+
+OM_uint32
+_gss_spnego_ntlm_reset_crypto(OM_uint32 *minor_status,
+ gssspnego_ctx ctx,
+ OM_uint32 verify)
+{
+ if (gss_oid_equal(ctx->negotiated_mech_type, GSS_NTLM_MECHANISM)) {
+ gss_buffer_desc value;
+
+ value.length = sizeof(verify);
+ value.value = &verify;
+
+ return gss_set_sec_context_option(minor_status,
+ &ctx->negotiated_ctx_id,
+ GSS_C_NTLM_RESET_CRYPTO,
+ &value);
+ }
+
+ return GSS_S_COMPLETE;
+}
+
+void
+_gss_spnego_log_mech(const char *prefix, gss_const_OID oid)
+{
+ gss_buffer_desc oidbuf = GSS_C_EMPTY_BUFFER;
+ OM_uint32 junk;
+ const char *name = NULL;
+
+ if (!_gss_mg_log_level(10))
+ return;
+
+ if (oid == GSS_C_NO_OID ||
+ gss_oid_to_str(&junk, (gss_OID)oid, &oidbuf) != GSS_S_COMPLETE) {
+ _gss_mg_log(10, "spnego: %s (null)", prefix);
+ return;
+ }
+
+ if (gss_oid_equal(oid, GSS_NEGOEX_MECHANISM))
+ name = "negoex"; /* not a real mech */
+ else if (gss_oid_equal(oid, &_gss_spnego_mskrb_mechanism_oid_desc))
+ name = "mskrb";
+ else {
+ gssapi_mech_interface m = __gss_get_mechanism(oid);
+ if (m)
+ name = m->gm_name;
+ }
+
+ _gss_mg_log(10, "spnego: %s %s { %.*s }",
+ prefix,
+ name ? name : "unknown",
+ (int)oidbuf.length, (char *)oidbuf.value);
+ gss_release_buffer(&junk, &oidbuf);
+}
+
+void
+_gss_spnego_log_mechTypes(MechTypeList *mechTypes)
+{
+ size_t i;
+ char mechbuf[64];
+ size_t mech_len;
+ gss_OID_desc oid;
+ int ret;
+
+ if (!_gss_mg_log_level(10))
+ return;
+
+ for (i = 0; i < mechTypes->len; i++) {
+ ret = der_put_oid ((unsigned char *)mechbuf + sizeof(mechbuf) - 1,
+ sizeof(mechbuf),
+ &mechTypes->val[i],
+ &mech_len);
+ if (ret)
+ continue;
+
+ oid.length = (OM_uint32)mech_len;
+ oid.elements = mechbuf + sizeof(mechbuf) - mech_len;
+
+ _gss_spnego_log_mech("initiator proposed mech", &oid);
+ }
+}
+
+/*
+ * Indicate mechs negotiable by SPNEGO
+ */
+
+OM_uint32
+_gss_spnego_indicate_mechs(OM_uint32 *minor_status,
+ gss_OID_set *mechs_p)
+{
+ gss_OID_desc oids[3];
+ gss_OID_set_desc except;
+
+ *mechs_p = GSS_C_NO_OID_SET;
+
+ oids[0] = *GSS_C_MA_DEPRECATED;
+ oids[1] = *GSS_C_MA_NOT_DFLT_MECH;
+ oids[2] = *GSS_C_MA_MECH_NEGO;
+
+ except.count = sizeof(oids) / sizeof(oids[0]);
+ except.elements = oids;
+
+ return gss_indicate_mechs_by_attrs(minor_status,
+ GSS_C_NO_OID_SET,
+ &except,
+ GSS_C_NO_OID_SET,
+ mechs_p);
+}
+
+/*
+ * Indicate mechs in cred negotiatble by SPNEGO
+ */
+
+OM_uint32
+_gss_spnego_inquire_cred_mechs(OM_uint32 *minor_status,
+ gss_const_cred_id_t cred,
+ gss_OID_set *mechs_p,
+ int *canonical_order)
+{
+ OM_uint32 ret, junk;
+ gss_OID_set cred_mechs = GSS_C_NO_OID_SET;
+ gss_OID_set negotiable_mechs = GSS_C_NO_OID_SET;
+ size_t i;
+
+ *mechs_p = GSS_C_NO_OID_SET;
+ *canonical_order = FALSE;
+
+ heim_assert(cred != GSS_C_NO_CREDENTIAL, "Invalid null credential handle");
+
+ ret = gss_get_neg_mechs(minor_status, cred, &cred_mechs);
+ if (ret == GSS_S_COMPLETE) {
+ *canonical_order = TRUE;
+ } else {
+ ret = gss_inquire_cred(minor_status, cred, NULL, NULL, NULL, &cred_mechs);
+ if (ret != GSS_S_COMPLETE)
+ goto out;
+ }
+
+ heim_assert(cred_mechs != GSS_C_NO_OID_SET && cred_mechs->count > 0,
+ "gss_inquire_cred succeeded but returned no mechanisms");
+
+ ret = _gss_spnego_indicate_mechs(minor_status, &negotiable_mechs);
+ if (ret != GSS_S_COMPLETE)
+ goto out;
+
+ heim_assert(negotiable_mechs != GSS_C_NO_OID_SET,
+ "_gss_spnego_indicate_mechs succeeded but returned null OID set");
+
+ ret = gss_create_empty_oid_set(minor_status, mechs_p);
+ if (ret != GSS_S_COMPLETE)
+ goto out;
+
+ /* Filter credential mechs by negotiable mechs, order by credential mechs */
+ for (i = 0; i < cred_mechs->count; i++) {
+ gss_OID cred_mech = &cred_mechs->elements[i];
+ int present = 0;
+
+ gss_test_oid_set_member(&junk, cred_mech, negotiable_mechs, &present);
+ if (!present)
+ continue;
+
+ ret = gss_add_oid_set_member(minor_status, cred_mech, mechs_p);
+ if (ret != GSS_S_COMPLETE)
+ break;
+ }
+
+out:
+ if (ret != GSS_S_COMPLETE)
+ gss_release_oid_set(&junk, mechs_p);
+ gss_release_oid_set(&junk, &cred_mechs);
+ gss_release_oid_set(&junk, &negotiable_mechs);
+
+ return ret;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/spnego/context_storage.c b/third_party/heimdal/lib/gssapi/spnego/context_storage.c
new file mode 100644
index 0000000..13e20d7
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/spnego/context_storage.c
@@ -0,0 +1,492 @@
+/*
+ * Copyright (C) 2021, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "spnego_locl.h"
+
+#define SC_MECH_TYPES 0x0001
+#define SC_PREFERRED_MECH_TYPE 0x0002
+#define SC_SELECTED_MECH_TYPE 0x0004
+#define SC_NEGOTIATED_MECH_TYPE 0x0008
+#define SC_NEGOTIATED_CTX_ID 0x0010
+#define SC_MECH_FLAGS 0x0020
+#define SC_MECH_TIME_REC 0x0040
+#define SC_MECH_SRC_NAME 0x0080
+#define SC_TARGET_NAME 0x0100
+#define SC_NEGOEX 0x0200
+
+#define SNC_OID 0x01
+#define SNC_MECH_CONTEXT 0x02
+#define SNC_METADATA 0x04
+
+static krb5_error_code
+ret_spnego_context(krb5_storage *sp, gssspnego_ctx *ctxp);
+static krb5_error_code
+store_spnego_context(krb5_storage *sp, gssspnego_ctx ctx);
+
+static krb5_error_code
+ret_negoex_auth_mech(krb5_storage *sp, struct negoex_auth_mech **mechp);
+static krb5_error_code
+store_negoex_auth_mech(krb5_storage *sp, struct negoex_auth_mech *mech);
+
+static uint16_t
+spnego_flags_to_int(struct spnego_flags flags);
+static struct spnego_flags
+int_to_spnego_flags(uint16_t f);
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_import_sec_context_internal(OM_uint32 *minor,
+ gss_const_buffer_t buffer,
+ gssspnego_ctx *ctxp)
+{
+ krb5_error_code ret;
+ krb5_storage *sp;
+
+ sp = krb5_storage_from_readonly_mem(buffer->value, buffer->length);
+ if (sp == NULL) {
+ *minor = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_PACKED);
+
+ ret = ret_spnego_context(sp, ctxp);
+
+ krb5_storage_free(sp);
+
+ *minor = ret;
+ return ret ? GSS_S_FAILURE : GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_export_sec_context_internal(OM_uint32 *minor,
+ gssspnego_ctx ctx,
+ gss_buffer_t buffer)
+{
+ krb5_error_code ret;
+ krb5_storage *sp;
+ krb5_data data;
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ *minor = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ krb5_data_zero(&data);
+
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_PACKED);
+
+ ret = store_spnego_context(sp, ctx);
+ if (ret == 0)
+ ret = krb5_storage_to_data(sp, &data);
+ if (ret == 0) {
+ buffer->length = data.length;
+ buffer->value = data.data;
+ }
+
+ krb5_storage_free(sp);
+
+ *minor = ret;
+ return ret ? GSS_S_FAILURE : GSS_S_COMPLETE;
+}
+
+static krb5_error_code
+ret_spnego_context(krb5_storage *sp, gssspnego_ctx *ctxp)
+{
+ OM_uint32 major = GSS_S_COMPLETE, minor;
+ gssspnego_ctx ctx = NULL;
+ krb5_error_code ret = 0;
+ krb5_data data;
+ gss_buffer_desc buf = GSS_C_EMPTY_BUFFER;
+ uint16_t sc_flags, spnego_flags;
+
+ *ctxp = NULL;
+ krb5_data_zero(&data);
+
+ CHECK(major, _gss_spnego_alloc_sec_context(&minor, (gss_ctx_id_t *)&ctx));
+
+ CHECK(ret, krb5_ret_uint16(sp, &sc_flags));
+ CHECK(ret, krb5_ret_uint16(sp, &spnego_flags));
+ ctx->flags = int_to_spnego_flags(spnego_flags);
+
+ if (sc_flags & SC_MECH_TYPES)
+ CHECK(major, _gss_mg_ret_buffer(&minor, sp, &ctx->NegTokenInit_mech_types));
+ if (sc_flags & SC_PREFERRED_MECH_TYPE)
+ CHECK(major, _gss_mg_ret_oid(&minor, sp, &ctx->preferred_mech_type));
+ if (sc_flags & SC_SELECTED_MECH_TYPE)
+ CHECK(major, _gss_mg_ret_oid(&minor, sp, &ctx->selected_mech_type));
+ if (sc_flags & SC_NEGOTIATED_MECH_TYPE)
+ CHECK(major, _gss_mg_ret_oid(&minor, sp, &ctx->negotiated_mech_type));
+
+ if (sc_flags & SC_NEGOTIATED_CTX_ID) {
+ CHECK(major, _gss_mg_ret_buffer(&minor, sp, &buf));
+ CHECK(major, gss_import_sec_context(&minor, &buf,
+ &ctx->negotiated_ctx_id));
+ gss_release_buffer(&minor, &buf);
+ }
+
+ if (sc_flags & SC_MECH_FLAGS)
+ CHECK(ret, krb5_ret_uint32(sp, &ctx->mech_flags));
+ if (sc_flags & SC_MECH_TIME_REC)
+ CHECK(ret, krb5_ret_uint32(sp, &ctx->mech_time_rec));
+ else
+ ctx->mech_time_rec = GSS_C_INDEFINITE;
+
+ if (sc_flags & SC_MECH_SRC_NAME) {
+ CHECK(major, _gss_mg_ret_buffer(&minor, sp, &buf));
+ CHECK(major, gss_import_name(&minor, &buf, GSS_C_NT_EXPORT_NAME,
+ &ctx->mech_src_name));
+ gss_release_buffer(&minor, &buf);
+ }
+
+ if (sc_flags & SC_TARGET_NAME) {
+ CHECK(major, _gss_mg_ret_buffer(&minor, sp, &buf));
+ CHECK(major, gss_import_name(&minor, &buf, GSS_C_NT_EXPORT_NAME,
+ &ctx->target_name));
+ gss_release_buffer(&minor, &buf);
+ }
+
+ if (sc_flags & SC_NEGOEX) {
+ uint8_t i, nschemes;
+
+ CHECK(ret, krb5_ret_uint8(sp, &ctx->negoex_step));
+
+ CHECK(ret, krb5_ret_data(sp, &data));
+ ctx->negoex_transcript = krb5_storage_emem();
+ if (ctx->negoex_transcript == NULL) {
+ ret = ENOMEM;
+ goto fail;
+ }
+
+ krb5_storage_set_byteorder(ctx->negoex_transcript,
+ KRB5_STORAGE_BYTEORDER_LE);
+ if (krb5_storage_write(ctx->negoex_transcript,
+ data.data, data.length) != data.length) {
+ ret = ENOMEM;
+ goto fail;
+ }
+ krb5_data_free(&data);
+
+ CHECK(ret, krb5_ret_uint32(sp, &ctx->negoex_seqnum));
+
+ if (krb5_storage_read(sp, ctx->negoex_conv_id,
+ GUID_LENGTH) != GUID_LENGTH) {
+ ret = KRB5_BAD_MSIZE;
+ goto fail;
+ }
+
+ CHECK(ret, krb5_ret_uint8(sp, &nschemes));
+ for (i = 0; i < nschemes; i++) {
+ struct negoex_auth_mech *mech;
+
+ CHECK(ret, ret_negoex_auth_mech(sp, &mech));
+ HEIM_TAILQ_INSERT_TAIL(&ctx->negoex_mechs, mech, links);
+ }
+ }
+
+ *ctxp = ctx;
+
+fail:
+ if (ret == 0 && GSS_ERROR(major))
+ ret = minor ? minor : KRB5_BAD_MSIZE;
+ if (ret)
+ _gss_spnego_delete_sec_context(&minor, (gss_ctx_id_t *)&ctx,
+ GSS_C_NO_BUFFER);
+ krb5_data_free(&data);
+ gss_release_buffer(&minor, &buf);
+
+ return ret;
+}
+
+static krb5_error_code
+store_spnego_context(krb5_storage *sp, gssspnego_ctx ctx)
+{
+ OM_uint32 major = GSS_S_COMPLETE, minor;
+ krb5_error_code ret = 0;
+ krb5_data data;
+ gss_buffer_desc buf = GSS_C_EMPTY_BUFFER;
+ uint16_t sc_flags = 0, spnego_flags;
+
+ krb5_data_zero(&data);
+
+ if (ctx->NegTokenInit_mech_types.length)
+ sc_flags |= SC_MECH_TYPES;
+ if (ctx->preferred_mech_type)
+ sc_flags |= SC_PREFERRED_MECH_TYPE;
+ if (ctx->selected_mech_type)
+ sc_flags |= SC_SELECTED_MECH_TYPE;
+ if (ctx->negotiated_mech_type)
+ sc_flags |= SC_NEGOTIATED_MECH_TYPE;
+ if (ctx->negotiated_ctx_id)
+ sc_flags |= SC_NEGOTIATED_CTX_ID;
+ if (ctx->mech_flags)
+ sc_flags |= SC_MECH_FLAGS;
+ if (ctx->mech_time_rec != GSS_C_INDEFINITE)
+ sc_flags |= SC_MECH_TIME_REC;
+ if (ctx->mech_src_name)
+ sc_flags |= SC_MECH_SRC_NAME;
+ if (ctx->target_name)
+ sc_flags |= SC_TARGET_NAME;
+ if (ctx->negoex_step)
+ sc_flags |= SC_NEGOEX;
+
+ CHECK(ret, krb5_store_uint16(sp, sc_flags));
+ spnego_flags = spnego_flags_to_int(ctx->flags);
+ CHECK(ret, krb5_store_uint16(sp, spnego_flags));
+
+ if (sc_flags & SC_MECH_TYPES)
+ CHECK(major, _gss_mg_store_buffer(&minor, sp, &ctx->NegTokenInit_mech_types));
+ if (sc_flags & SC_PREFERRED_MECH_TYPE)
+ CHECK(major, _gss_mg_store_oid(&minor, sp, ctx->preferred_mech_type));
+ if (sc_flags & SC_SELECTED_MECH_TYPE)
+ CHECK(major, _gss_mg_store_oid(&minor, sp, ctx->selected_mech_type));
+ if (sc_flags & SC_NEGOTIATED_MECH_TYPE)
+ CHECK(major, _gss_mg_store_oid(&minor, sp, ctx->negotiated_mech_type));
+ if (sc_flags & SC_NEGOTIATED_CTX_ID) {
+ CHECK(major, gss_export_sec_context(&minor, &ctx->negotiated_ctx_id,
+ &buf));
+ CHECK(major, _gss_mg_store_buffer(&minor, sp, &buf));
+ gss_release_buffer(&minor, &buf);
+ }
+ if (sc_flags & SC_MECH_FLAGS)
+ CHECK(ret, krb5_store_uint32(sp, ctx->mech_flags));
+ if (sc_flags & SC_MECH_TIME_REC)
+ CHECK(ret, krb5_store_uint32(sp, ctx->mech_time_rec));
+ if (sc_flags & SC_MECH_SRC_NAME) {
+ CHECK(major, gss_export_name(&minor, ctx->mech_src_name, &buf));
+ CHECK(major, _gss_mg_store_buffer(&minor, sp, &buf));
+ gss_release_buffer(&minor, &buf);
+ }
+
+ if (sc_flags & SC_TARGET_NAME) {
+ CHECK(major, gss_export_name(&minor, ctx->target_name, &buf));
+ CHECK(major, _gss_mg_store_buffer(&minor, sp, &buf));
+ gss_release_buffer(&minor, &buf);
+ }
+
+ if (sc_flags & SC_NEGOEX) {
+ uint32_t nschemes;
+ struct negoex_auth_mech *mech;
+
+ CHECK(ret, krb5_store_uint8(sp, ctx->negoex_step));
+
+ if (ctx->negoex_transcript) {
+ CHECK(ret, krb5_storage_to_data(ctx->negoex_transcript, &data));
+ }
+ CHECK(ret, krb5_store_data(sp, data));
+ krb5_data_free(&data);
+
+ CHECK(ret, krb5_store_uint32(sp, ctx->negoex_seqnum));
+ CHECK(ret, krb5_store_bytes(sp, ctx->negoex_conv_id, GUID_LENGTH));
+
+ nschemes = 0;
+ HEIM_TAILQ_FOREACH(mech, &ctx->negoex_mechs, links)
+ nschemes++;
+
+ if (nschemes > 0xff) {
+ ret = ERANGE;
+ goto fail;
+ }
+ CHECK(ret, krb5_store_uint8(sp, nschemes));
+
+ HEIM_TAILQ_FOREACH(mech, &ctx->negoex_mechs, links)
+ CHECK(ret, store_negoex_auth_mech(sp, mech));
+ }
+
+fail:
+ if (ret == 0 && GSS_ERROR(major))
+ ret = minor ? minor : KRB5_BAD_MSIZE;
+ krb5_data_free(&data);
+ gss_release_buffer(&minor, &buf);
+
+ return ret;
+}
+
+static krb5_error_code
+ret_negoex_auth_mech(krb5_storage *sp, struct negoex_auth_mech **mechp)
+{
+ krb5_error_code ret;
+ OM_uint32 major = GSS_S_COMPLETE, minor;
+ gss_buffer_desc buf = GSS_C_EMPTY_BUFFER;
+ struct negoex_auth_mech *mech;
+ krb5_context context = _gss_mg_krb5_context();
+ uint8_t snc_flags, negoex_flags;
+
+ *mechp = NULL;
+
+ mech = calloc(1, sizeof(*mech));
+ if (mech == NULL) {
+ ret = ENOMEM;
+ goto fail;
+ }
+
+ CHECK(ret, krb5_ret_uint8(sp, &snc_flags));
+ CHECK(ret, krb5_ret_uint8(sp, &negoex_flags));
+ if (negoex_flags & (1 << 0))
+ mech->complete = 1;
+ if (negoex_flags & (1 << 1))
+ mech->sent_checksum = 1;
+ if (negoex_flags & (1 << 2))
+ mech->verified_checksum = 1;
+
+ if (snc_flags & SNC_OID)
+ CHECK(major, _gss_mg_ret_oid(&minor, sp, &mech->oid));
+
+ if (krb5_storage_read(sp, mech->scheme, GUID_LENGTH) != GUID_LENGTH) {
+ ret = KRB5_BAD_MSIZE;
+ goto fail;
+ }
+
+ if (snc_flags & SNC_MECH_CONTEXT) {
+ CHECK(major, _gss_mg_ret_buffer(&minor, sp, &buf));
+ CHECK(major, gss_import_sec_context(&minor, &buf,
+ &mech->mech_context));
+ gss_release_buffer(&minor, &buf);
+ }
+
+ if (snc_flags & SNC_METADATA)
+ CHECK(major, _gss_mg_ret_buffer(&minor, sp, &mech->metadata));
+
+ *mechp = mech;
+
+fail:
+ if (ret == 0 && GSS_ERROR(major))
+ ret = minor ? minor : KRB5_BAD_MSIZE;
+ if (ret)
+ _gss_negoex_release_auth_mech(context, mech);
+ gss_release_buffer(&minor, &buf);
+
+ return ret;
+}
+
+static krb5_error_code
+store_negoex_auth_mech(krb5_storage *sp, struct negoex_auth_mech *mech)
+{
+ krb5_error_code ret;
+ OM_uint32 major = GSS_S_COMPLETE, minor;
+ gss_buffer_desc buf = GSS_C_EMPTY_BUFFER;
+ uint8_t negoex_flags = 0, snc_flags = 0;
+
+ negoex_flags = 0;
+ if (mech->complete)
+ negoex_flags |= (1 << 0);
+ if (mech->sent_checksum)
+ negoex_flags |= (1 << 1);
+ if (mech->verified_checksum)
+ negoex_flags |= (1 << 2);
+
+ if (mech->oid)
+ snc_flags |= SNC_OID;
+ if (mech->mech_context)
+ snc_flags |= SNC_MECH_CONTEXT;
+ if (mech->metadata.length)
+ snc_flags |= SNC_METADATA;
+
+ CHECK(ret, krb5_store_uint8(sp, snc_flags));
+ CHECK(ret, krb5_store_uint8(sp, negoex_flags));
+
+ if (snc_flags & SNC_OID)
+ CHECK(major, _gss_mg_store_oid(&minor, sp, mech->oid));
+
+ CHECK(ret, krb5_store_bytes(sp, mech->scheme, GUID_LENGTH));
+
+ if (snc_flags & SNC_MECH_CONTEXT) {
+ CHECK(major, gss_export_sec_context(&minor, &mech->mech_context,
+ &buf));
+ CHECK(major, _gss_mg_store_buffer(&minor, sp, &buf));
+ gss_release_buffer(&minor, &buf);
+ }
+
+ if (snc_flags & SNC_METADATA)
+ CHECK(major, _gss_mg_store_buffer(&minor, sp, &mech->metadata));
+
+fail:
+ if (ret == 0 && GSS_ERROR(major))
+ ret = minor ? minor : KRB5_BAD_MSIZE;
+ gss_release_buffer(&minor, &buf);
+
+ return ret;
+}
+
+static uint16_t
+spnego_flags_to_int(struct spnego_flags flags)
+{
+ uint16_t f = 0;
+
+ if (flags.open)
+ f |= (1 << 0);
+ if (flags.local)
+ f |= (1 << 1);
+ if (flags.require_mic)
+ f |= (1 << 2);
+ if (flags.peer_require_mic)
+ f |= (1 << 3);
+ if (flags.sent_mic)
+ f |= (1 << 4);
+ if (flags.verified_mic)
+ f |= (1 << 5);
+ if (flags.safe_omit)
+ f |= (1 << 6);
+ if (flags.maybe_open)
+ f |= (1 << 7);
+ if (flags.seen_supported_mech)
+ f |= (1 << 8);
+
+ return f;
+}
+
+static struct spnego_flags
+int_to_spnego_flags(uint16_t f)
+{
+ struct spnego_flags flags;
+
+ memset(&flags, 0, sizeof(flags));
+
+ if (f & (1 << 0))
+ flags.open = 1;
+ if (f & (1 << 1))
+ flags.local = 1;
+ if (f & (1 << 2))
+ flags.require_mic = 1;
+ if (f & (1 << 3))
+ flags.peer_require_mic = 1;
+ if (f & (1 << 4))
+ flags.sent_mic = 1;
+ if (f & (1 << 5))
+ flags.verified_mic = 1;
+ if (f & (1 << 6))
+ flags.safe_omit = 1;
+ if (f & (1 << 7))
+ flags.maybe_open = 1;
+ if (f & (1 << 8))
+ flags.seen_supported_mech = 1;
+
+ return flags;
+}
diff --git a/third_party/heimdal/lib/gssapi/spnego/context_stubs.c b/third_party/heimdal/lib/gssapi/spnego/context_stubs.c
new file mode 100644
index 0000000..638e90d
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/spnego/context_stubs.c
@@ -0,0 +1,578 @@
+/*
+ * Copyright (c) 2004, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "spnego_locl.h"
+
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_process_context_token
+ (OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t token_buffer
+ )
+{
+ gss_ctx_id_t context;
+ gssspnego_ctx ctx;
+ OM_uint32 ret;
+
+ if (context_handle == GSS_C_NO_CONTEXT)
+ return GSS_S_NO_CONTEXT;
+
+ context = (gss_ctx_id_t)context_handle;
+ ctx = (gssspnego_ctx)context_handle;
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+
+ ret = gss_process_context_token(minor_status,
+ ctx->negotiated_ctx_id,
+ token_buffer);
+ if (ret != GSS_S_COMPLETE) {
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+ return ret;
+ }
+
+ ctx->negotiated_ctx_id = GSS_C_NO_CONTEXT;
+
+ return _gss_spnego_internal_delete_sec_context(minor_status,
+ &context,
+ GSS_C_NO_BUFFER);
+}
+
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_delete_sec_context
+ (OM_uint32 *minor_status,
+ gss_ctx_id_t *context_handle,
+ gss_buffer_t output_token
+ )
+{
+ gssspnego_ctx ctx;
+
+ if (context_handle == NULL || *context_handle == GSS_C_NO_CONTEXT)
+ return GSS_S_NO_CONTEXT;
+
+ ctx = (gssspnego_ctx)*context_handle;
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+
+ return _gss_spnego_internal_delete_sec_context(minor_status,
+ context_handle,
+ output_token);
+}
+
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_context_time
+ (OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ OM_uint32 *time_rec
+ )
+{
+ gssspnego_ctx ctx;
+ *minor_status = 0;
+
+ if (context_handle == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ ctx = (gssspnego_ctx)context_handle;
+
+ if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_context_time(minor_status,
+ ctx->negotiated_ctx_id,
+ time_rec);
+}
+
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_get_mic
+ (OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ gss_qop_t qop_req,
+ const gss_buffer_t message_buffer,
+ gss_buffer_t message_token
+ )
+{
+ gssspnego_ctx ctx;
+
+ *minor_status = 0;
+
+ if (context_handle == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ ctx = (gssspnego_ctx)context_handle;
+
+ if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_get_mic(minor_status, ctx->negotiated_ctx_id,
+ qop_req, message_buffer, message_token);
+}
+
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_verify_mic
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t message_buffer,
+ const gss_buffer_t token_buffer,
+ gss_qop_t * qop_state
+ )
+{
+ gssspnego_ctx ctx;
+
+ *minor_status = 0;
+
+ if (context_handle == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ ctx = (gssspnego_ctx)context_handle;
+
+ if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_verify_mic(minor_status,
+ ctx->negotiated_ctx_id,
+ message_buffer,
+ token_buffer,
+ qop_state);
+}
+
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_wrap
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ const gss_buffer_t input_message_buffer,
+ int * conf_state,
+ gss_buffer_t output_message_buffer
+ )
+{
+ gssspnego_ctx ctx;
+
+ *minor_status = 0;
+
+ if (context_handle == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ ctx = (gssspnego_ctx)context_handle;
+
+ if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_wrap(minor_status,
+ ctx->negotiated_ctx_id,
+ conf_req_flag,
+ qop_req,
+ input_message_buffer,
+ conf_state,
+ output_message_buffer);
+}
+
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_unwrap
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t input_message_buffer,
+ gss_buffer_t output_message_buffer,
+ int * conf_state,
+ gss_qop_t * qop_state
+ )
+{
+ gssspnego_ctx ctx;
+
+ *minor_status = 0;
+
+ if (context_handle == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ ctx = (gssspnego_ctx)context_handle;
+
+ if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_unwrap(minor_status,
+ ctx->negotiated_ctx_id,
+ input_message_buffer,
+ output_message_buffer,
+ conf_state,
+ qop_state);
+}
+
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_context (
+ OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ gss_name_t * src_name,
+ gss_name_t * targ_name,
+ OM_uint32 * lifetime_rec,
+ gss_OID * mech_type,
+ OM_uint32 * ctx_flags,
+ int * locally_initiated,
+ int * open_context
+ )
+{
+ gssspnego_ctx ctx;
+ OM_uint32 maj_stat;
+
+ *minor_status = 0;
+
+ if (context_handle == GSS_C_NO_CONTEXT)
+ return GSS_S_NO_CONTEXT;
+
+ ctx = (gssspnego_ctx)context_handle;
+
+ if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT)
+ return GSS_S_NO_CONTEXT;
+
+ maj_stat = gss_inquire_context(minor_status,
+ ctx->negotiated_ctx_id,
+ src_name,
+ targ_name,
+ lifetime_rec,
+ mech_type,
+ ctx_flags,
+ locally_initiated,
+ open_context);
+
+ if (open_context)
+ *open_context = gssspnego_ctx_complete_p(ctx);
+
+ return maj_stat;
+}
+
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_wrap_size_limit (
+ OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ OM_uint32 req_output_size,
+ OM_uint32 * max_input_size
+ )
+{
+ gssspnego_ctx ctx;
+
+ *minor_status = 0;
+
+ if (context_handle == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ ctx = (gssspnego_ctx)context_handle;
+
+ if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_wrap_size_limit(minor_status,
+ ctx->negotiated_ctx_id,
+ conf_req_flag,
+ qop_req,
+ req_output_size,
+ max_input_size);
+}
+
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_export_sec_context (
+ OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ gss_buffer_t interprocess_token
+ )
+{
+ gssspnego_ctx ctx;
+ OM_uint32 major_status;
+
+ *minor_status = 0;
+
+ if (context_handle == NULL)
+ return GSS_S_NO_CONTEXT;
+
+ ctx = (gssspnego_ctx)*context_handle;
+
+ if (ctx == NULL)
+ return GSS_S_NO_CONTEXT;
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+
+ /*
+ * Partial context export is only supported on the acceptor side, as we
+ * cannot represent the initiator function pointer state in an exported
+ * token, and also because it is mostly useful for acceptors which need
+ * to manage multiple initiator states.
+ */
+ if (ctx->flags.local && !gssspnego_ctx_complete_p(ctx)) {
+ major_status = GSS_S_NO_CONTEXT;
+ goto out;
+ }
+
+ major_status = _gss_spnego_export_sec_context_internal(minor_status,
+ ctx,
+ interprocess_token);
+
+out:
+ if (major_status == GSS_S_COMPLETE)
+ major_status = _gss_spnego_internal_delete_sec_context(minor_status,
+ context_handle,
+ GSS_C_NO_BUFFER);
+ else
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ return major_status;
+}
+
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_import_sec_context (
+ OM_uint32 * minor_status,
+ const gss_buffer_t interprocess_token,
+ gss_ctx_id_t *context_handle
+ )
+{
+ return _gss_spnego_import_sec_context_internal(minor_status,
+ interprocess_token,
+ (gssspnego_ctx *)context_handle);
+}
+
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_names_for_mech (
+ OM_uint32 * minor_status,
+ const gss_OID mechanism,
+ gss_OID_set * name_types
+ )
+{
+ gss_OID_set mechs, names, n;
+ OM_uint32 ret, junk;
+ size_t i, j;
+
+ *name_types = NULL;
+
+ ret = _gss_spnego_indicate_mechs(minor_status, &mechs);
+ if (ret != GSS_S_COMPLETE)
+ return ret;
+
+ ret = gss_create_empty_oid_set(minor_status, &names);
+ if (ret != GSS_S_COMPLETE)
+ goto out;
+
+ for (i = 0; i < mechs->count; i++) {
+ ret = gss_inquire_names_for_mech(minor_status,
+ &mechs->elements[i],
+ &n);
+ if (ret)
+ continue;
+
+ for (j = 0; j < n->count; j++)
+ gss_add_oid_set_member(minor_status,
+ &n->elements[j],
+ &names);
+ gss_release_oid_set(&junk, &n);
+ }
+
+ ret = GSS_S_COMPLETE;
+ *name_types = names;
+out:
+
+ gss_release_oid_set(&junk, &mechs);
+
+ return ret;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_wrap_iov(OM_uint32 * minor_status,
+ gss_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ int * conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ gssspnego_ctx ctx = (gssspnego_ctx)context_handle;
+
+ *minor_status = 0;
+
+ if (ctx == NULL || ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT)
+ return GSS_S_NO_CONTEXT;
+
+ return gss_wrap_iov(minor_status, ctx->negotiated_ctx_id,
+ conf_req_flag, qop_req, conf_state,
+ iov, iov_count);
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_unwrap_iov(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ int *conf_state,
+ gss_qop_t *qop_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ gssspnego_ctx ctx = (gssspnego_ctx)context_handle;
+
+ *minor_status = 0;
+
+ if (ctx == NULL || ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT)
+ return GSS_S_NO_CONTEXT;
+
+ return gss_unwrap_iov(minor_status,
+ ctx->negotiated_ctx_id,
+ conf_state, qop_state,
+ iov, iov_count);
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_wrap_iov_length(OM_uint32 * minor_status,
+ gss_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ int *conf_state,
+ gss_iov_buffer_desc *iov,
+ int iov_count)
+{
+ gssspnego_ctx ctx = (gssspnego_ctx)context_handle;
+
+ *minor_status = 0;
+
+ if (ctx == NULL || ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT)
+ return GSS_S_NO_CONTEXT;
+
+ return gss_wrap_iov_length(minor_status, ctx->negotiated_ctx_id,
+ conf_req_flag, qop_req, conf_state,
+ iov, iov_count);
+}
+
+#if 0
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_complete_auth_token
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ gss_buffer_t input_message_buffer)
+{
+ gssspnego_ctx ctx;
+
+ *minor_status = 0;
+
+ if (context_handle == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ ctx = (gssspnego_ctx)context_handle;
+
+ if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_complete_auth_token(minor_status,
+ ctx->negotiated_ctx_id,
+ input_message_buffer);
+}
+#endif
+
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_sec_context_by_oid
+ (OM_uint32 * minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_OID desired_object,
+ gss_buffer_set_t *data_set)
+{
+ gssspnego_ctx ctx;
+
+ *minor_status = 0;
+
+ if (context_handle == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ ctx = (gssspnego_ctx)context_handle;
+
+ if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_inquire_sec_context_by_oid(minor_status,
+ ctx->negotiated_ctx_id,
+ desired_object,
+ data_set);
+}
+
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_set_sec_context_option
+ (OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ const gss_OID desired_object,
+ const gss_buffer_t value)
+{
+ gssspnego_ctx ctx;
+
+ *minor_status = 0;
+
+ /*
+ * Return GSS_S_UNAVAILABLE with a NULL context handle as at
+ * present no context options can be set globally on SPNEGO
+ * itself. Global mechanism context options are set directly
+ * on the mechanism; per-context context options are set below
+ * if ctx->negotiated_ctx_id != GSS_C_NO_CONTEXT.
+ */
+ if (context_handle == NULL || *context_handle == GSS_C_NO_CONTEXT)
+ return GSS_S_UNAVAILABLE;
+
+ ctx = (gssspnego_ctx)*context_handle;
+
+ if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) {
+ return GSS_S_NO_CONTEXT;
+ }
+
+ return gss_set_sec_context_option(minor_status,
+ &ctx->negotiated_ctx_id,
+ desired_object,
+ value);
+}
+
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_pseudo_random(OM_uint32 *minor_status,
+ gss_ctx_id_t context_handle,
+ int prf_key,
+ const gss_buffer_t prf_in,
+ ssize_t desired_output_len,
+ gss_buffer_t prf_out)
+{
+ gssspnego_ctx ctx;
+
+ *minor_status = 0;
+
+ if (context_handle == GSS_C_NO_CONTEXT)
+ return GSS_S_NO_CONTEXT;
+
+ ctx = (gssspnego_ctx)context_handle;
+
+ if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT)
+ return GSS_S_NO_CONTEXT;
+
+ return gss_pseudo_random(minor_status,
+ ctx->negotiated_ctx_id,
+ prf_key,
+ prf_in,
+ desired_output_len,
+ prf_out);
+}
diff --git a/third_party/heimdal/lib/gssapi/spnego/external.c b/third_party/heimdal/lib/gssapi/spnego/external.c
new file mode 100644
index 0000000..2a5121e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/spnego/external.c
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) 2004, PADL Software Pty Ltd.
+ * Copyright (c) 2018 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "spnego_locl.h"
+#include <gssapi_mech.h>
+
+/*
+ * RFC2478, SPNEGO:
+ * The security mechanism of the initial
+ * negotiation token is identified by the Object Identifier
+ * iso.org.dod.internet.security.mechanism.snego (1.3.6.1.5.5.2).
+ */
+static gss_mo_desc spnego_mo[] = {
+ {
+ GSS_C_MA_SASL_MECH_NAME,
+ GSS_MO_MA,
+ "SASL mech name",
+ rk_UNCONST("SPNEGO"),
+ _gss_mo_get_ctx_as_string,
+ NULL
+ },
+ {
+ GSS_C_MA_MECH_NAME,
+ GSS_MO_MA,
+ "Mechanism name",
+ rk_UNCONST("SPNEGO"),
+ _gss_mo_get_ctx_as_string,
+ NULL
+ },
+ {
+ GSS_C_MA_MECH_DESCRIPTION,
+ GSS_MO_MA,
+ "Mechanism description",
+ rk_UNCONST("Heimdal SPNEGO Mechanism"),
+ _gss_mo_get_ctx_as_string,
+ NULL
+ },
+ {
+ GSS_C_MA_MECH_NEGO,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ },
+ {
+ GSS_C_MA_MECH_PSEUDO,
+ GSS_MO_MA,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ }
+};
+
+static gssapi_mech_interface_desc spnego_mech = {
+ GMI_VERSION,
+ "spnego",
+ {6, rk_UNCONST("\x2b\x06\x01\x05\x05\x02") },
+ GM_USE_MG_CRED | GM_USE_MG_NAME,
+ NULL, /* gm_acquire_cred */
+ NULL, /* gm_release_cred */
+ _gss_spnego_init_sec_context,
+ _gss_spnego_accept_sec_context,
+ _gss_spnego_process_context_token,
+ _gss_spnego_delete_sec_context,
+ _gss_spnego_context_time,
+ _gss_spnego_get_mic,
+ _gss_spnego_verify_mic,
+ _gss_spnego_wrap,
+ _gss_spnego_unwrap,
+ NULL, /* gm_display_status */
+ NULL, /* gm_indicate_mechs */
+ NULL, /* gm_compare_name */
+ NULL, /* gm_display_name */
+ NULL, /* gm_import_name */
+ NULL, /* gm_export_name */
+ NULL, /* gm_release_name */
+ NULL, /* gm_inquire_cred */
+ _gss_spnego_inquire_context,
+ _gss_spnego_wrap_size_limit,
+ NULL, /* gm_add_cred */
+ NULL, /* gm_inquire_cred_by_mech */
+ _gss_spnego_export_sec_context,
+ _gss_spnego_import_sec_context,
+ NULL, /* gm_spnego_inquire_names_for_mech */
+ NULL, /* gm_spnego_inquire_mechs_for_name */
+ NULL, /* gm_spnego_canonicalize_name */
+ NULL, /* gm_spnego_duplicate_name */
+ _gss_spnego_inquire_sec_context_by_oid,
+ NULL, /* gm_inquire_cred_by_oid */
+ _gss_spnego_set_sec_context_option,
+ NULL, /* gm_set_cred_option */
+ _gss_spnego_pseudo_random,
+ _gss_spnego_wrap_iov,
+ _gss_spnego_unwrap_iov,
+ _gss_spnego_wrap_iov_length,
+ NULL,
+ NULL, /* gm_export_cred */
+ NULL, /* gm_import_cred */
+ NULL, /* gm_acquire_cred_from */
+ NULL, /* gm_acquire_cred_impersonate_name */
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ spnego_mo,
+ sizeof(spnego_mo) / sizeof(spnego_mo[0]),
+ NULL, /* gm_localname */
+ NULL, /* gm_authorize_localname */
+ NULL, /* gm_display_name_ext */
+ NULL, /* gm_inquire_name */
+ NULL, /* gm_get_name_attribute */
+ NULL, /* gm_set_name_attribute */
+ NULL, /* gm_delete_name_attribute */
+ NULL, /* gm_export_name_composite */
+ NULL, /* gm_duplicate_cred */
+ NULL, /* gm_add_cred_from */
+ NULL, /* gm_store_cred_into */
+ NULL, /* gm_query_mechanism_info */
+ NULL, /* gm_query_meta_data */
+ NULL, /* gm_exchange_meta_data */
+ NULL, /* gm_store_cred_into2 */
+ NULL /* gm_compat */
+};
+
+gssapi_mech_interface
+__gss_spnego_initialize(void)
+{
+ return &spnego_mech;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/spnego/init_sec_context.c b/third_party/heimdal/lib/gssapi/spnego/init_sec_context.c
new file mode 100644
index 0000000..12ec0ea
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/spnego/init_sec_context.c
@@ -0,0 +1,841 @@
+/*
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * Portions Copyright (c) 2004 PADL Software Pty Ltd.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "spnego_locl.h"
+
+#define GSISC(name) \
+static \
+OM_uint32 name(OM_uint32 *, gss_const_cred_id_t, gssspnego_ctx, \
+ gss_const_name_t, gss_const_OID, \
+ OM_uint32, OM_uint32, const gss_channel_bindings_t, \
+ gss_const_buffer_t, gss_buffer_t, \
+ OM_uint32 *, OM_uint32 *)
+
+GSISC(spnego_initial);
+GSISC(spnego_reply);
+GSISC(wait_server_mic);
+GSISC(step_completed);
+
+
+ /*
+ * Is target_name an sane target for `mech´.
+ */
+
+static OM_uint32
+initiator_approved(OM_uint32 *minor_status,
+ void *userptr,
+ gss_const_name_t target_name,
+ gss_const_cred_id_t cred,
+ gss_OID mech)
+{
+ OM_uint32 min_stat, maj_stat;
+ gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
+ gss_buffer_desc out;
+ struct gssspnego_optimistic_ctx *sel = userptr;
+ gss_OID negotiated_mech_type = GSS_C_NO_OID;
+ OM_uint32 flags = 0, time_rec = 0;
+ auth_scheme scheme;
+ int negoex = 0;
+
+ maj_stat = gss_init_sec_context(&min_stat,
+ cred,
+ &ctx,
+ sel->target_name,
+ mech,
+ sel->req_flags,
+ sel->time_req,
+ sel->input_chan_bindings,
+ GSS_C_NO_BUFFER,
+ &negotiated_mech_type,
+ &out,
+ &flags,
+ &time_rec);
+ if (GSS_ERROR(maj_stat)) {
+ gss_mg_collect_error(mech, maj_stat, min_stat);
+ *minor_status = min_stat;
+ return maj_stat;
+ }
+
+ if (gssspi_query_mechanism_info(&min_stat, mech, scheme) == GSS_S_COMPLETE)
+ negoex = 1;
+
+ if (sel->preferred_mech_type == GSS_C_NO_OID) {
+ sel->preferred_mech_type = mech;
+ sel->negotiated_mech_type = negotiated_mech_type;
+ sel->optimistic_token = out;
+ sel->optimistic_flags = flags;
+ sel->optimistic_time_rec = time_rec;
+ sel->gssctx = ctx;
+ if (maj_stat == GSS_S_COMPLETE)
+ sel->complete = 1;
+ if (negoex)
+ memcpy(sel->scheme, scheme, GUID_LENGTH);
+ } else {
+ gss_release_buffer(&min_stat, &out);
+ gss_delete_sec_context(&min_stat, &ctx, NULL);
+ }
+
+ maj_stat = GSS_S_COMPLETE;
+
+ if (negoex) {
+ maj_stat = _gss_negoex_add_auth_mech(minor_status, sel->spnegoctx,
+ mech, scheme);
+ }
+
+ return maj_stat;
+}
+
+/*
+ * Send a reply. Note that we only need to send a reply if we
+ * need to send a MIC or a mechanism token. Otherwise, we can
+ * return an empty buffer.
+ *
+ * The return value of this will be returned to the API, so it
+ * must return GSS_S_CONTINUE_NEEDED if a token was generated.
+ */
+static OM_uint32
+make_reply(OM_uint32 *minor_status,
+ gssspnego_ctx ctx,
+ gss_buffer_t mech_token,
+ gss_buffer_t output_token)
+{
+ NegotiationToken nt;
+ gss_buffer_desc mic_buf;
+ OM_uint32 ret, minor;
+ size_t size;
+ NegStateEnum state;
+
+ memset(&nt, 0, sizeof(nt));
+
+ nt.element = choice_NegotiationToken_negTokenResp;
+
+ nt.u.negTokenResp.negState = NULL;
+ nt.u.negTokenResp.supportedMech = NULL;
+
+ output_token->length = 0;
+ output_token->value = NULL;
+
+ /* figure out our status */
+
+ if (ctx->flags.open) {
+ if (ctx->flags.verified_mic == 1 || ctx->flags.require_mic == 0)
+ state = accept_completed;
+ else
+ state = accept_incomplete;
+ } else {
+ state = accept_incomplete;
+ }
+
+ if (mech_token->length == 0) {
+ nt.u.negTokenResp.responseToken = NULL;
+ } else {
+ ALLOC(nt.u.negTokenResp.responseToken, 1);
+ if (nt.u.negTokenResp.responseToken == NULL) {
+ free_NegotiationToken(&nt);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ nt.u.negTokenResp.responseToken->length = mech_token->length;
+ nt.u.negTokenResp.responseToken->data = mech_token->value;
+ mech_token->length = 0;
+ mech_token->value = NULL;
+ }
+
+ /*
+ * XXX should limit when we send the MIC ?
+ */
+ if (ctx->flags.open && ctx->flags.sent_mic == 0) {
+
+ ctx->flags.sent_mic = 1;
+
+ ret = gss_get_mic(minor_status,
+ ctx->negotiated_ctx_id,
+ 0,
+ &ctx->NegTokenInit_mech_types,
+ &mic_buf);
+ if (ret == GSS_S_COMPLETE) {
+ _gss_spnego_ntlm_reset_crypto(&minor, ctx, FALSE);
+
+ ALLOC(nt.u.negTokenResp.mechListMIC, 1);
+ if (nt.u.negTokenResp.mechListMIC == NULL) {
+ gss_release_buffer(minor_status, &mic_buf);
+ free_NegotiationToken(&nt);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ nt.u.negTokenResp.mechListMIC->length = mic_buf.length;
+ nt.u.negTokenResp.mechListMIC->data = mic_buf.value;
+ /* mic_buf free()d with nt */
+ } else if (ret == GSS_S_UNAVAILABLE) {
+ /* lets hope that its ok to not send te mechListMIC for broken mechs */
+ nt.u.negTokenResp.mechListMIC = NULL;
+ ctx->flags.require_mic = 0;
+ } else {
+ free_NegotiationToken(&nt);
+ *minor_status = ENOMEM;
+ return gss_mg_set_error_string(GSS_SPNEGO_MECHANISM,
+ ret, *minor_status,
+ "SPNEGO failed to sign MIC");
+ }
+ } else {
+ nt.u.negTokenResp.mechListMIC = NULL;
+ }
+
+ ALLOC(nt.u.negTokenResp.negState, 1);
+ if (nt.u.negTokenResp.negState == NULL) {
+ free_NegotiationToken(&nt);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ *nt.u.negTokenResp.negState = state;
+
+ ASN1_MALLOC_ENCODE(NegotiationToken,
+ output_token->value, output_token->length,
+ &nt, &size, ret);
+ free_NegotiationToken(&nt);
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ if (state != accept_completed)
+ return GSS_S_CONTINUE_NEEDED;
+
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+spnego_initial(OM_uint32 * minor_status,
+ gss_const_cred_id_t cred,
+ gssspnego_ctx ctx,
+ gss_const_name_t target_name,
+ gss_const_OID mech_type,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_const_buffer_t input_token,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec)
+{
+ NegotiationToken nt;
+ int ret;
+ OM_uint32 sub, minor;
+ gss_buffer_desc mech_token;
+ size_t size = 0;
+ gss_buffer_desc data;
+ struct gssspnego_optimistic_ctx sel;
+
+ *minor_status = 0;
+
+ memset(&nt, 0, sizeof(nt));
+
+ if (target_name == GSS_C_NO_NAME)
+ return GSS_S_BAD_NAME;
+
+ sub = gss_duplicate_name(&minor, target_name, &ctx->target_name);
+ if (GSS_ERROR(sub)) {
+ *minor_status = minor;
+ return sub;
+ }
+
+ nt.element = choice_NegotiationToken_negTokenInit;
+
+ ctx->flags.local = 1;
+
+ memset(&sel, 0, sizeof(sel));
+
+ sel.spnegoctx = ctx;
+ sel.target_name = ctx->target_name;
+ sel.preferred_mech_type = GSS_C_NO_OID;
+ sel.req_flags = req_flags;
+ sel.time_req = time_req;
+ sel.input_chan_bindings = (gss_channel_bindings_t)input_chan_bindings;
+
+ sub = _gss_spnego_indicate_mechtypelist(&minor,
+ ctx->target_name,
+ req_flags,
+ initiator_approved,
+ &sel,
+ 0,
+ cred,
+ &nt.u.negTokenInit.mechTypes,
+ &ctx->preferred_mech_type);
+ if (GSS_ERROR(sub)) {
+ *minor_status = minor;
+ return sub;
+ }
+
+ _gss_spnego_log_mechTypes(&nt.u.negTokenInit.mechTypes);
+
+ nt.u.negTokenInit.reqFlags = NULL;
+
+ if (gss_oid_equal(ctx->preferred_mech_type, GSS_NEGOEX_MECHANISM)) {
+ struct negoex_auth_mech *mech;
+
+ sub = _gss_negoex_init(&minor,
+ &sel,
+ ctx,
+ (gss_cred_id_t)cred,
+ req_flags,
+ time_req,
+ input_chan_bindings,
+ GSS_C_NO_BUFFER,
+ &mech_token);
+ if (GSS_ERROR(sub)) {
+ free_NegotiationToken(&nt);
+ return gss_mg_set_error_string(GSS_C_NO_OID, sub, minor,
+ "NegoEx could not generate a context token");
+ }
+ mech = _gss_negoex_negotiated_mech(ctx);
+ ctx->flags.maybe_open = mech && mech->complete;
+ gss_release_buffer(&minor, &sel.optimistic_token);
+ } else {
+ /* optimistic token from selection context */
+ mech_token = sel.optimistic_token;
+ ctx->mech_flags = sel.optimistic_flags;
+ ctx->mech_time_rec = sel.optimistic_time_rec;
+ ctx->negotiated_mech_type = sel.negotiated_mech_type;
+ ctx->negotiated_ctx_id = sel.gssctx;
+ ctx->flags.maybe_open = sel.complete;
+ }
+
+ if (ctx->preferred_mech_type == GSS_C_NO_OID) {
+ free_NegotiationToken(&nt);
+ *minor_status = 0;
+ return gss_mg_set_error_string(GSS_C_NO_OID, GSS_S_NO_CONTEXT, 0,
+ "SPNEGO could not find a preferred mechanism");
+ }
+
+
+ if (mech_token.length != 0) {
+ ALLOC(nt.u.negTokenInit.mechToken, 1);
+ if (nt.u.negTokenInit.mechToken == NULL) {
+ free_NegotiationToken(&nt);
+ gss_release_buffer(&minor, &mech_token);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ nt.u.negTokenInit.mechToken->length = mech_token.length;
+ nt.u.negTokenInit.mechToken->data = malloc(mech_token.length);
+ if (nt.u.negTokenInit.mechToken->data == NULL && mech_token.length != 0) {
+ free_NegotiationToken(&nt);
+ gss_release_buffer(&minor, &mech_token);
+ *minor_status = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ memcpy(nt.u.negTokenInit.mechToken->data, mech_token.value, mech_token.length);
+ gss_release_buffer(&minor, &mech_token);
+ } else
+ nt.u.negTokenInit.mechToken = NULL;
+
+ nt.u.negTokenInit.mechListMIC = NULL;
+
+ {
+ MechTypeList mt;
+
+ mt.len = nt.u.negTokenInit.mechTypes.len;
+ mt.val = nt.u.negTokenInit.mechTypes.val;
+
+ ASN1_MALLOC_ENCODE(MechTypeList,
+ ctx->NegTokenInit_mech_types.value,
+ ctx->NegTokenInit_mech_types.length,
+ &mt, &size, ret);
+ if (ret) {
+ *minor_status = ret;
+ free_NegotiationToken(&nt);
+ return GSS_S_FAILURE;
+ }
+ }
+
+ ASN1_MALLOC_ENCODE(NegotiationToken, data.value, data.length, &nt, &size, ret);
+ free_NegotiationToken(&nt);
+ if (ret) {
+ return GSS_S_FAILURE;
+ }
+ if (data.length != size)
+ abort();
+
+ sub = gss_encapsulate_token(&data,
+ GSS_SPNEGO_MECHANISM,
+ output_token);
+ free (data.value);
+
+ if (sub) {
+ return sub;
+ }
+
+ if (ret_flags)
+ *ret_flags = ctx->mech_flags;
+ if (time_rec)
+ *time_rec = ctx->mech_time_rec;
+
+ ctx->initiator_state = spnego_reply;
+
+ return GSS_S_CONTINUE_NEEDED;
+}
+
+/*
+ *
+ */
+
+static OM_uint32
+spnego_reply(OM_uint32 * minor_status,
+ gss_const_cred_id_t cred,
+ gssspnego_ctx ctx,
+ gss_const_name_t target_name,
+ gss_const_OID mech_type,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_const_buffer_t input_token,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec)
+{
+ OM_uint32 ret, minor;
+ NegotiationToken resp;
+ gss_buffer_desc mech_output_token;
+ NegStateEnum negState;
+
+ *minor_status = 0;
+
+ output_token->length = 0;
+ output_token->value = NULL;
+
+ mech_output_token.length = 0;
+ mech_output_token.value = NULL;
+
+ ret = decode_NegotiationToken(input_token->value, input_token->length,
+ &resp, NULL);
+ if (ret)
+ return ret;
+
+ /* The SPNEGO token must be a negTokenResp */
+ if (resp.element != choice_NegotiationToken_negTokenResp) {
+ free_NegotiationToken(&resp);
+ *minor_status = 0;
+ return GSS_S_BAD_MECH;
+ }
+
+ /*
+ * When negState is absent, the actual state should be inferred from
+ * the state of the negotiated mechanism context. (RFC 4178 4.2.2.)
+ */
+ if (resp.u.negTokenResp.negState != NULL)
+ negState = *resp.u.negTokenResp.negState;
+ else
+ negState = accept_incomplete;
+
+ /*
+ * Pick up the mechanism that the acceptor selected, only pick up
+ * the first selection.
+ */
+
+ if (ctx->selected_mech_type == GSS_C_NO_OID && resp.u.negTokenResp.supportedMech) {
+ gss_OID_desc oid;
+ size_t len;
+
+ ctx->flags.seen_supported_mech = 1;
+
+ oid.length = (OM_uint32)der_length_oid(resp.u.negTokenResp.supportedMech);
+ oid.elements = malloc(oid.length);
+ if (oid.elements == NULL) {
+ free_NegotiationToken(&resp);
+ return GSS_S_BAD_MECH;
+ }
+ ret = der_put_oid(((uint8_t *)oid.elements) + oid.length - 1,
+ oid.length,
+ resp.u.negTokenResp.supportedMech,
+ &len);
+ if (ret || len != oid.length) {
+ free(oid.elements);
+ free_NegotiationToken(&resp);
+ return GSS_S_BAD_MECH;
+ }
+
+ if (gss_oid_equal(GSS_SPNEGO_MECHANISM, &oid)) {
+ free(oid.elements);
+ free_NegotiationToken(&resp);
+ return gss_mg_set_error_string(GSS_SPNEGO_MECHANISM,
+ GSS_S_BAD_MECH, (*minor_status = EINVAL),
+ "SPNEGO acceptor picked SPNEGO??");
+ }
+
+ /* check if the acceptor took our optimistic token */
+ if (gss_oid_equal(ctx->preferred_mech_type, &oid)) {
+ ctx->selected_mech_type = ctx->preferred_mech_type;
+ } else if (gss_oid_equal(ctx->preferred_mech_type, GSS_KRB5_MECHANISM) &&
+ gss_oid_equal(&oid, &_gss_spnego_mskrb_mechanism_oid_desc)) {
+ /* mis-encoded asn1 type from msft servers */
+ ctx->selected_mech_type = ctx->preferred_mech_type;
+ } else {
+ /* nope, lets start over */
+ gss_delete_sec_context(&minor, &ctx->negotiated_ctx_id,
+ GSS_C_NO_BUFFER);
+ ctx->negotiated_ctx_id = GSS_C_NO_CONTEXT;
+
+ if (gss_oid_equal(&oid, GSS_NEGOEX_MECHANISM))
+ ctx->selected_mech_type = GSS_NEGOEX_MECHANISM;
+ else
+ ctx->selected_mech_type = _gss_mg_support_mechanism(&oid);
+
+ /* XXX check that server pick a mechanism we proposed */
+ if (ctx->selected_mech_type == GSS_C_NO_OID) {
+ free(oid.elements);
+ free_NegotiationToken(&resp);
+ return gss_mg_set_error_string(GSS_SPNEGO_MECHANISM,
+ GSS_S_BAD_MECH, (*minor_status = EINVAL),
+ "SPNEGO acceptor sent unsupported supportedMech");
+ }
+ }
+
+ _gss_spnego_log_mech("initiator selected mechanism", ctx->selected_mech_type);
+
+ free(oid.elements);
+
+ } else if (ctx->selected_mech_type == NULL) {
+ free_NegotiationToken(&resp);
+ return gss_mg_set_error_string(GSS_SPNEGO_MECHANISM,
+ GSS_S_BAD_MECH, (*minor_status = EINVAL),
+ "SPNEGO acceptor didn't send supportedMech");
+ }
+
+ /* if a token (of non zero length) pass to underlaying mech */
+ if ((resp.u.negTokenResp.responseToken != NULL && resp.u.negTokenResp.responseToken->length) ||
+ ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) {
+ gss_buffer_desc mech_input_token;
+
+ if (resp.u.negTokenResp.responseToken) {
+ mech_input_token.length = resp.u.negTokenResp.responseToken->length;
+ mech_input_token.value = resp.u.negTokenResp.responseToken->data;
+ } else {
+ mech_input_token.length = 0;
+ mech_input_token.value = NULL;
+ }
+
+ /* Fall through as if the negotiated mechanism
+ was requested explicitly */
+ if (gss_oid_equal(ctx->selected_mech_type, GSS_NEGOEX_MECHANISM)) {
+ ret = _gss_negoex_init(&minor,
+ NULL, /* no optimistic token */
+ ctx,
+ (gss_cred_id_t)cred,
+ req_flags,
+ time_req,
+ input_chan_bindings,
+ &mech_input_token,
+ &mech_output_token);
+ } else {
+ ret = gss_init_sec_context(&minor,
+ cred,
+ &ctx->negotiated_ctx_id,
+ ctx->target_name,
+ ctx->selected_mech_type,
+ req_flags,
+ time_req,
+ input_chan_bindings,
+ &mech_input_token,
+ &ctx->negotiated_mech_type,
+ &mech_output_token,
+ &ctx->mech_flags,
+ &ctx->mech_time_rec);
+ if (GSS_ERROR(ret)) {
+ gss_mg_collect_error(ctx->selected_mech_type, ret, minor);
+ }
+ }
+ /*
+ * If the acceptor rejected, we're out even if the inner context is
+ * now complete. Note that the rejection is not integrity-protected.
+ */
+ if (negState == reject)
+ ret = GSS_S_BAD_MECH;
+ if (GSS_ERROR(ret)) {
+ free_NegotiationToken(&resp);
+ *minor_status = minor;
+ return ret;
+ }
+ if (ret == GSS_S_COMPLETE) {
+ ctx->flags.open = 1;
+ }
+ } else if (negState == reject) {
+ free_NegotiationToken(&resp);
+ return gss_mg_set_error_string(GSS_SPNEGO_MECHANISM,
+ GSS_S_BAD_MECH, (*minor_status = EPERM),
+ "SPNEGO acceptor rejected initiator token");
+ } else if (negState == accept_completed) {
+ /*
+ * Note that the accept_completed isn't integrity-protected, but
+ * ctx->maybe_open can only be true if the inner context is fully
+ * established.
+ */
+ if (ctx->flags.maybe_open)
+ ctx->flags.open = 1;
+
+ if (!ctx->flags.open) {
+ free_NegotiationToken(&resp);
+ return gss_mg_set_error_string(GSS_SPNEGO_MECHANISM,
+ GSS_S_BAD_MECH, (*minor_status = EINVAL),
+ "SPNEGO acceptor sent acceptor complete, "
+ "but we are not complete yet");
+ }
+ }
+
+ if (negState == request_mic) {
+ ctx->flags.peer_require_mic = 1;
+ }
+
+ if (ctx->flags.open && ctx->flags.verified_mic == 0) {
+
+ ctx->flags.require_mic = 1; /* default is to require a MIC */
+ ctx->flags.safe_omit = _gss_spnego_safe_omit_mechlist_mic(ctx);
+
+ /*
+ * If the peer sent mechListMIC, require it to verify ...
+ */
+ if (resp.u.negTokenResp.mechListMIC) {
+ heim_octet_string *m = resp.u.negTokenResp.mechListMIC;
+
+ /* ...unless its a windows 2000 server that sends the
+ * responseToken inside the mechListMIC too. We only
+ * accept this condition if would have been safe to omit
+ * anyway. */
+
+ if (ctx->flags.safe_omit
+ && resp.u.negTokenResp.responseToken
+ && der_heim_octet_string_cmp(m, resp.u.negTokenResp.responseToken) == 0)
+ {
+ ctx->flags.require_mic = 0;
+ }
+ }
+
+ } else {
+ ctx->flags.require_mic = 0;
+ }
+
+ /*
+ * If we are supposed to check mic and have it, force checking now.
+ */
+
+ if (ctx->flags.require_mic && resp.u.negTokenResp.mechListMIC) {
+
+ ret = _gss_spnego_verify_mechtypes_mic(minor_status, ctx,
+ resp.u.negTokenResp.mechListMIC);
+ if (ret) {
+ free_NegotiationToken(&resp);
+ return ret;
+ }
+ }
+
+ /*
+ * Now that underlaying mech is open (conncted), we can figure out
+ * what nexd step to go to.
+ */
+
+ if (ctx->flags.open) {
+
+ if (negState == accept_completed && ctx->flags.safe_omit) {
+ ctx->initiator_state = step_completed;
+ ret = GSS_S_COMPLETE;
+ } else if (ctx->flags.require_mic != 0 && ctx->flags.verified_mic == 0) {
+ ctx->initiator_state = wait_server_mic;
+ ret = GSS_S_CONTINUE_NEEDED;
+ } else {
+ ctx->initiator_state = step_completed;
+ ret = GSS_S_COMPLETE;
+ }
+ }
+
+ if (negState != accept_completed ||
+ ctx->initiator_state != step_completed ||
+ mech_output_token.length)
+ {
+ OM_uint32 ret2;
+ ret2 = make_reply(minor_status, ctx,
+ &mech_output_token,
+ output_token);
+ if (ret2)
+ ret = ret2;
+ }
+
+ free_NegotiationToken(&resp);
+
+ gss_release_buffer(&minor, &mech_output_token);
+
+ if (ret_flags)
+ *ret_flags = ctx->mech_flags;
+ if (time_rec)
+ *time_rec = ctx->mech_time_rec;
+
+ return ret;
+}
+
+static OM_uint32
+wait_server_mic(OM_uint32 * minor_status,
+ gss_const_cred_id_t cred,
+ gssspnego_ctx ctx,
+ gss_const_name_t target_name,
+ gss_const_OID mech_type,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_const_buffer_t input_token,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec)
+{
+ OM_uint32 major_status;
+ NegotiationToken resp;
+ int ret;
+
+ ret = decode_NegotiationToken(input_token->value, input_token->length, &resp, NULL);
+ if (ret)
+ return gss_mg_set_error_string(GSS_SPNEGO_MECHANISM,
+ GSS_S_BAD_MECH, ret,
+ "Failed to decode NegotiationToken");
+
+ if (resp.element != choice_NegotiationToken_negTokenResp
+ || resp.u.negTokenResp.negState == NULL
+ || *resp.u.negTokenResp.negState != accept_completed)
+ {
+ free_NegotiationToken(&resp);
+ return gss_mg_set_error_string(GSS_SPNEGO_MECHANISM,
+ GSS_S_BAD_MECH, (*minor_status = EINVAL),
+ "NegToken not accept_completed");
+ }
+
+ if (resp.u.negTokenResp.mechListMIC) {
+ major_status = _gss_spnego_verify_mechtypes_mic(minor_status, ctx,
+ resp.u.negTokenResp.mechListMIC);
+ } else if (ctx->flags.safe_omit == 0) {
+ free_NegotiationToken(&resp);
+ return gss_mg_set_error_string(GSS_SPNEGO_MECHANISM,
+ GSS_S_BAD_MECH, (*minor_status = EINVAL),
+ "Waiting for MIC, but its missing in server request");
+ } else {
+ major_status = GSS_S_COMPLETE;
+ }
+
+ free_NegotiationToken(&resp);
+ if (major_status != GSS_S_COMPLETE)
+ return major_status;
+
+ ctx->flags.verified_mic = 1;
+ ctx->initiator_state = step_completed;
+
+ if (ret_flags)
+ *ret_flags = ctx->mech_flags;
+ if (time_rec)
+ *time_rec = ctx->mech_time_rec;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+step_completed(OM_uint32 * minor_status,
+ gss_const_cred_id_t cred,
+ gssspnego_ctx ctx,
+ gss_const_name_t name,
+ gss_const_OID mech_type,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_const_buffer_t input_token,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec)
+{
+ return gss_mg_set_error_string(GSS_SPNEGO_MECHANISM,
+ GSS_S_BAD_STATUS, (*minor_status = EINVAL),
+ "SPNEGO called got ISC call one too many");
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_init_sec_context(OM_uint32 * minor_status,
+ gss_const_cred_id_t initiator_cred_handle,
+ gss_ctx_id_t * context_handle,
+ gss_const_name_t target_name,
+ const gss_OID mech_type,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ const gss_buffer_t input_token,
+ gss_OID * actual_mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec)
+{
+ gssspnego_ctx ctx;
+ OM_uint32 ret;
+
+ if (*context_handle == GSS_C_NO_CONTEXT) {
+ ret = _gss_spnego_alloc_sec_context(minor_status, context_handle);
+ if (GSS_ERROR(ret))
+ return ret;
+
+ ctx = (gssspnego_ctx)*context_handle;
+
+ ctx->initiator_state = spnego_initial;
+ } else {
+ ctx = (gssspnego_ctx)*context_handle;
+ }
+
+
+ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+
+ do {
+ ret = ctx->initiator_state(minor_status, initiator_cred_handle, ctx, target_name,
+ mech_type, req_flags, time_req, input_chan_bindings, input_token,
+ output_token, ret_flags, time_rec);
+
+ } while (ret == GSS_S_COMPLETE &&
+ ctx->initiator_state != step_completed &&
+ output_token->length == 0);
+
+ /* destroy context in case of error */
+ if (GSS_ERROR(ret)) {
+ OM_uint32 junk;
+ _gss_spnego_internal_delete_sec_context(&junk, context_handle, GSS_C_NO_BUFFER);
+ } else {
+
+ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+ if (actual_mech_type)
+ *actual_mech_type = ctx->negotiated_mech_type;
+ }
+
+ return ret;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/spnego/negoex_ctx.c b/third_party/heimdal/lib/gssapi/spnego/negoex_ctx.c
new file mode 100644
index 0000000..3f8aa5c
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/spnego/negoex_ctx.c
@@ -0,0 +1,1041 @@
+/*
+ * Copyright (C) 2011-2021 PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "spnego_locl.h"
+
+/*
+ * The initial context token emitted by the initiator is a INITIATOR_NEGO
+ * message followed by zero or more INITIATOR_META_DATA tokens, and zero
+ * or one AP_REQUEST tokens.
+ *
+ * Upon receiving this, the acceptor computes the list of mutually supported
+ * authentication mechanisms and performs the metadata exchange. The output
+ * token is ACCEPTOR_NEGO followed by zero or more ACCEPTOR_META_DATA tokens,
+ * and zero or one CHALLENGE tokens.
+ *
+ * Once the metadata exchange is complete and a mechanism is selected, the
+ * selected mechanism's context token exchange continues with AP_REQUEST and
+ * CHALLENGE messages.
+ *
+ * Once the context token exchange is complete, VERIFY messages are sent to
+ * authenticate the entire exchange.
+ */
+
+static OM_uint32
+buffer_set_to_crypto(OM_uint32 *minor,
+ krb5_context context,
+ gss_buffer_set_t buffers,
+ krb5_crypto *crypto)
+{
+ krb5_error_code ret;
+ krb5_keyblock keyblock;
+ OM_uint32 tmp;
+
+ /*
+ * Returned keys must be in two buffers, with the key contents in
+ * the first and the enctype as a 32-bit little-endian integer in
+ * the second.
+ */
+ if (buffers->count != 2 ||
+ buffers->elements[1].length != sizeof(tmp)) {
+ *minor = (OM_uint32)NEGOEX_NO_VERIFY_KEY;
+ return GSS_S_FAILURE;
+ }
+
+ if (*crypto != NULL) {
+ krb5_crypto_destroy(context, *crypto);
+ *crypto = NULL;
+ }
+
+ keyblock.keyvalue.data = buffers->elements[0].value;
+ keyblock.keyvalue.length = buffers->elements[0].length;
+ _gss_mg_decode_le_uint32(buffers->elements[1].value, &tmp);
+ keyblock.keytype = tmp;
+
+ ret = krb5_crypto_init(context, &keyblock, 0, crypto);
+ if (ret) {
+ *minor = ret;
+ return GSS_S_FAILURE;
+ }
+
+ return GSS_S_COMPLETE;
+}
+
+#define NEGOEX_SIGN_KEY 1
+#define NEGOEX_VERIFY_KEY 2
+#define NEGOEX_BOTH_KEYS (NEGOEX_SIGN_KEY|NEGOEX_VERIFY_KEY)
+
+static OM_uint32
+get_session_keys(OM_uint32 *minor,
+ krb5_context context,
+ OM_uint32 flags,
+ struct negoex_auth_mech *mech)
+{
+ OM_uint32 major, tmpMinor;
+ gss_buffer_set_t buffers = GSS_C_NO_BUFFER_SET;
+
+ if (flags & NEGOEX_SIGN_KEY) {
+ major = gss_inquire_sec_context_by_oid(&tmpMinor, mech->mech_context,
+ GSS_C_INQ_NEGOEX_KEY, &buffers);
+ if (major == GSS_S_COMPLETE) {
+ major = buffer_set_to_crypto(minor, context,
+ buffers, &mech->crypto);
+ _gss_secure_release_buffer_set(&tmpMinor, &buffers);
+ if (major != GSS_S_COMPLETE)
+ return major;
+ }
+ }
+
+ if (flags & NEGOEX_VERIFY_KEY) {
+ major = gss_inquire_sec_context_by_oid(&tmpMinor, mech->mech_context,
+ GSS_C_INQ_NEGOEX_VERIFY_KEY,
+ &buffers);
+ if (major == GSS_S_COMPLETE) {
+ major = buffer_set_to_crypto(minor, context,
+ buffers, &mech->verify_crypto);
+ _gss_secure_release_buffer_set(&tmpMinor, &buffers);
+ if (major != GSS_S_COMPLETE)
+ return major;
+ }
+ }
+
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+emit_initiator_nego(OM_uint32 *minor, gssspnego_ctx ctx)
+{
+ uint8_t random[32];
+ struct negoex_auth_mech *mech;
+ size_t i = 0;
+
+ krb5_generate_random_block(random, sizeof(random));
+
+ HEIM_TAILQ_FOREACH(mech, &ctx->negoex_mechs, links)
+ _gss_negoex_log_auth_scheme(ctx->flags.local, ++i, mech->scheme);
+
+ return _gss_negoex_add_nego_message(minor, ctx, INITIATOR_NEGO, random);
+}
+
+static OM_uint32
+process_initiator_nego(OM_uint32 *minor,
+ gssspnego_ctx ctx,
+ struct negoex_message *messages,
+ size_t nmessages)
+{
+ struct nego_message *msg;
+ size_t i;
+
+ heim_assert(!ctx->flags.local && ctx->negoex_step == 1,
+ "NegoEx INITIATOR_NEGO token received after first leg");
+
+ msg = _gss_negoex_locate_nego_message(messages, nmessages, INITIATOR_NEGO);
+ if (msg == NULL) {
+ *minor = (OM_uint32)NEGOEX_MISSING_NEGO_MESSAGE;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ for (i = 0; i < msg->nschemes; i++)
+ _gss_negoex_log_auth_scheme(ctx->flags.local, i + 1, &msg->schemes[i * GUID_LENGTH]);
+
+ _gss_negoex_restrict_auth_schemes(ctx, msg->schemes, msg->nschemes);
+
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+emit_acceptor_nego(OM_uint32 *minor, gssspnego_ctx ctx)
+{
+ uint8_t random[32];
+
+ krb5_generate_random_block(random, 32);
+
+ return _gss_negoex_add_nego_message(minor, ctx, ACCEPTOR_NEGO, random);
+}
+
+static OM_uint32
+process_acceptor_nego(OM_uint32 *minor,
+ gssspnego_ctx ctx,
+ struct negoex_message *messages,
+ size_t nmessages)
+{
+ struct nego_message *msg;
+
+ msg = _gss_negoex_locate_nego_message(messages, nmessages, ACCEPTOR_NEGO);
+ if (msg == NULL) {
+ *minor = (OM_uint32)NEGOEX_MISSING_NEGO_MESSAGE;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ /*
+ * Reorder and prune our mech list to match the acceptor's list (or a
+ * subset of it).
+ */
+ _gss_negoex_common_auth_schemes(ctx, msg->schemes, msg->nschemes);
+
+ return GSS_S_COMPLETE;
+}
+
+static void
+query_meta_data(gssspnego_ctx ctx,
+ struct gssspnego_optimistic_ctx *opt,
+ gss_cred_id_t cred,
+ OM_uint32 req_flags)
+{
+ OM_uint32 major, minor;
+ struct negoex_auth_mech *p, *next;
+
+ /*
+ * Note that if we received an optimistic context token from SPNEGO,
+ * then we will call QMD after ISC, rather than before. Mechanisms
+ * must be prepared to handle this and must not assume the context
+ * will be NULL on entry.
+ */
+ HEIM_TAILQ_FOREACH_SAFE(p, &ctx->negoex_mechs, links, next) {
+ if (opt != NULL && memcmp(opt->scheme, p->scheme, GUID_LENGTH) == 0)
+ p->mech_context = opt->gssctx;;
+
+ major = gssspi_query_meta_data(&minor, p->oid, cred, &p->mech_context,
+ ctx->target_name, req_flags, &p->metadata);
+ /* GSS_Query_meta_data failure removes mechanism from list. */
+ if (major != GSS_S_COMPLETE)
+ _gss_negoex_delete_auth_mech(ctx, p);
+ }
+}
+
+static void
+exchange_meta_data(gssspnego_ctx ctx,
+ gss_cred_id_t cred,
+ OM_uint32 req_flags,
+ struct negoex_message *messages,
+ size_t nmessages)
+{
+ OM_uint32 major, minor;
+ struct negoex_auth_mech *mech;
+ enum message_type type;
+ struct exchange_message *msg;
+ uint32_t i;
+
+ type = ctx->flags.local ? ACCEPTOR_META_DATA : INITIATOR_META_DATA;
+
+ for (i = 0; i < nmessages; i++) {
+ if (messages[i].type != type)
+ continue;
+ msg = &messages[i].u.e;
+
+ mech = _gss_negoex_locate_auth_scheme(ctx, msg->scheme);
+ if (mech == NULL)
+ continue;
+
+ major = gssspi_exchange_meta_data(&minor, mech->oid, cred,
+ &mech->mech_context,
+ ctx->target_name,
+ req_flags, &msg->token);
+ /* GSS_Exchange_meta_data failure removes mechanism from list. */
+ if (major != GSS_S_COMPLETE)
+ _gss_negoex_delete_auth_mech(ctx, mech);
+ }
+}
+
+static void
+release_mech_crypto(struct negoex_auth_mech *mech)
+{
+ krb5_context context = NULL;
+
+ if (mech->crypto || mech->verify_crypto)
+ context = _gss_mg_krb5_context();
+
+ if (mech->crypto) {
+ krb5_crypto_destroy(context, mech->crypto);
+ mech->crypto = NULL;
+ }
+
+ if (mech->verify_crypto) {
+ krb5_crypto_destroy(context, mech->verify_crypto);
+ mech->verify_crypto = NULL;
+ }
+
+ mech->sent_checksum = FALSE;
+}
+
+/*
+ * In the initiator, if we are processing the acceptor's first reply, discard
+ * the optimistic context if the acceptor ignored the optimistic token. If the
+ * acceptor continued the optimistic mech, discard all other mechs.
+ */
+static void
+check_optimistic_result(gssspnego_ctx ctx,
+ struct negoex_message *messages,
+ size_t nmessages)
+{
+ struct negoex_auth_mech *mech;
+ OM_uint32 tmpMinor;
+
+ heim_assert(ctx->flags.local && ctx->negoex_step == 2,
+ "NegoEx optimistic result should only be checked in second leg");
+
+ /* Do nothing if we didn't make an optimistic context. */
+ mech = HEIM_TAILQ_FIRST(&ctx->negoex_mechs);
+ if (mech == NULL || mech->mech_context == GSS_C_NO_CONTEXT)
+ return;
+
+ /*
+ * If the acceptor used the optimistic token, it will send an acceptor
+ * token or a checksum (or both) in its first reply.
+ */
+ if (_gss_negoex_locate_exchange_message(messages, nmessages,
+ CHALLENGE) != NULL ||
+ _gss_negoex_locate_verify_message(messages, nmessages) != NULL) {
+ /*
+ * The acceptor continued the optimistic mech, and metadata exchange
+ * didn't remove it. Commit to this mechanism.
+ */
+ _gss_negoex_select_auth_mech(ctx, mech);
+ } else {
+ /*
+ * The acceptor ignored the optimistic token. Restart the mech.
+ */
+ gss_delete_sec_context(&tmpMinor, &mech->mech_context, GSS_C_NO_BUFFER);
+ release_mech_crypto(mech);
+ mech->complete = FALSE;
+ }
+}
+
+/* Perform an initiator step of the underlying mechanism exchange. */
+static OM_uint32
+mech_init(OM_uint32 *minor,
+ struct gssspnego_optimistic_ctx *opt,
+ gssspnego_ctx ctx,
+ gss_cred_id_t cred,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ struct negoex_message *messages,
+ size_t nmessages,
+ gss_buffer_t output_token,
+ int *mech_error)
+{
+ OM_uint32 major, first_major = GSS_S_COMPLETE, first_minor = 0;
+ struct negoex_auth_mech *mech = NULL;
+ gss_buffer_t input_token = GSS_C_NO_BUFFER;
+ struct exchange_message *msg;
+ int first_mech;
+ krb5_context context = _gss_mg_krb5_context();
+
+ output_token->value = NULL;
+ output_token->length = 0;
+
+ *mech_error = FALSE;
+
+ /* Allow disabling of optimistic token for testing. */
+ if (ctx->negoex_step == 1 &&
+ secure_getenv("NEGOEX_NO_OPTIMISTIC_TOKEN") != NULL)
+ return GSS_S_COMPLETE;
+
+ if (HEIM_TAILQ_EMPTY(&ctx->negoex_mechs)) {
+ *minor = (OM_uint32)NEGOEX_NO_AVAILABLE_MECHS;
+ return GSS_S_FAILURE;
+ }
+
+ /*
+ * Get the input token. The challenge could be for the optimistic mech,
+ * which we might have discarded in metadata exchange, so ignore the
+ * challenge if it doesn't match the first auth mech.
+ */
+ mech = HEIM_TAILQ_FIRST(&ctx->negoex_mechs);
+ msg = _gss_negoex_locate_exchange_message(messages, nmessages, CHALLENGE);
+ if (msg != NULL && GUID_EQ(msg->scheme, mech->scheme))
+ input_token = &msg->token;
+
+ if (mech->complete)
+ return GSS_S_COMPLETE;
+
+ first_mech = TRUE;
+ major = GSS_S_BAD_MECH;
+
+ while (!HEIM_TAILQ_EMPTY(&ctx->negoex_mechs)) {
+ mech = HEIM_TAILQ_FIRST(&ctx->negoex_mechs);
+
+ /*
+ * If SPNEGO generated an optimistic token when probing available
+ * mechanisms, we can reuse it here. This avoids a potentially
+ * expensive and redundant call to GSS_Init_sec_context();
+ */
+ if (opt != NULL && memcmp(opt->scheme, mech->scheme, GUID_LENGTH) == 0) {
+ heim_assert(ctx->negoex_step == 1,
+ "SPNEGO optimistic token only valid for NegoEx first leg");
+
+ major = _gss_copy_buffer(minor, &opt->optimistic_token, output_token);
+ if (GSS_ERROR(major))
+ return major;
+
+ ctx->negotiated_mech_type = opt->negotiated_mech_type;
+ ctx->mech_flags = opt->optimistic_flags;
+ ctx->mech_time_rec = opt->optimistic_time_rec;
+
+ mech->mech_context = opt->gssctx;
+ opt->gssctx = NULL; /* steal it */
+
+ mech->complete = opt->complete;
+ major = GSS_S_COMPLETE;
+ } else {
+ major = gss_init_sec_context(minor, cred, &mech->mech_context,
+ ctx->target_name, mech->oid,
+ req_flags, time_req,
+ input_chan_bindings, input_token,
+ &ctx->negotiated_mech_type, output_token,
+ &ctx->mech_flags, &ctx->mech_time_rec);
+ if (major == GSS_S_COMPLETE)
+ mech->complete = 1;
+ else if (GSS_ERROR(major)) {
+ gss_mg_collect_error(mech->oid, major, *minor);
+ *mech_error = TRUE;
+ }
+ }
+ if (!GSS_ERROR(major))
+ return get_session_keys(minor, context, NEGOEX_BOTH_KEYS, mech);
+
+ /* Remember the error we got from the first mech. */
+ if (first_mech) {
+ first_major = major;
+ first_minor = *minor;
+ }
+
+ /* If we still have multiple mechs to try, move on to the next one. */
+ _gss_negoex_delete_auth_mech(ctx, mech);
+ first_mech = FALSE;
+ input_token = GSS_C_NO_BUFFER;
+ }
+
+ if (HEIM_TAILQ_EMPTY(&ctx->negoex_mechs)) {
+ major = first_major;
+ *minor = first_minor;
+ }
+
+ return major;
+}
+
+/* Perform an acceptor step of the underlying mechanism exchange. */
+static OM_uint32
+mech_accept(OM_uint32 *minor,
+ gssspnego_ctx ctx,
+ gss_cred_id_t cred,
+ const gss_channel_bindings_t input_chan_bindings,
+ struct negoex_message *messages,
+ size_t nmessages,
+ gss_buffer_t output_token,
+ gss_cred_id_t *deleg_cred,
+ int *mech_error)
+{
+ OM_uint32 major, tmpMinor;
+ struct negoex_auth_mech *mech;
+ struct exchange_message *msg;
+ krb5_context context = _gss_mg_krb5_context();
+
+ heim_assert(!ctx->flags.local && !HEIM_TAILQ_EMPTY(&ctx->negoex_mechs),
+ "Acceptor NegoEx function called in wrong sequence");
+
+ *mech_error = FALSE;
+
+ msg = _gss_negoex_locate_exchange_message(messages, nmessages, AP_REQUEST);
+ if (msg == NULL) {
+ /*
+ * No input token is okay on the first request or if the mech is
+ * complete.
+ */
+ if (ctx->negoex_step == 1 ||
+ HEIM_TAILQ_FIRST(&ctx->negoex_mechs)->complete)
+ return GSS_S_COMPLETE;
+ *minor = (OM_uint32)NEGOEX_MISSING_AP_REQUEST_MESSAGE;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ if (ctx->negoex_step == 1) {
+ /*
+ * Ignore the optimistic token if it isn't for our most preferred
+ * mech.
+ */
+ mech = HEIM_TAILQ_FIRST(&ctx->negoex_mechs);
+ if (!GUID_EQ(msg->scheme, mech->scheme)) {
+ _gss_mg_log(10, "negoex ignored optimistic token as not for preferred mech");
+ return GSS_S_COMPLETE;
+ }
+ } else {
+ /* The initiator has selected a mech; discard other entries. */
+ mech = _gss_negoex_locate_auth_scheme(ctx, msg->scheme);
+ if (mech == NULL) {
+ *minor = (OM_uint32)NEGOEX_NO_AVAILABLE_MECHS;
+ return GSS_S_FAILURE;
+ }
+ _gss_negoex_select_auth_mech(ctx, mech);
+ }
+
+ if (mech->complete)
+ return GSS_S_COMPLETE;
+
+ if (ctx->mech_src_name != GSS_C_NO_NAME)
+ gss_release_name(&tmpMinor, &ctx->mech_src_name);
+ if (deleg_cred && *deleg_cred != GSS_C_NO_CREDENTIAL)
+ gss_release_cred(&tmpMinor, deleg_cred);
+
+ major = gss_accept_sec_context(minor, &mech->mech_context, cred,
+ &msg->token, input_chan_bindings,
+ &ctx->mech_src_name, &ctx->negotiated_mech_type,
+ output_token, &ctx->mech_flags,
+ &ctx->mech_time_rec, deleg_cred);
+ if (major == GSS_S_COMPLETE)
+ mech->complete = 1;
+
+ if (!GSS_ERROR(major)) {
+ if (major == GSS_S_COMPLETE &&
+ !gss_oid_equal(ctx->negotiated_mech_type, mech->oid))
+ _gss_mg_log(1, "negoex client didn't send the mech they said they would");
+
+ major = get_session_keys(minor, context, NEGOEX_BOTH_KEYS, mech);
+ } else if (ctx->negoex_step == 1) {
+ gss_mg_collect_error(ctx->negotiated_mech_type, major, *minor);
+ *mech_error = TRUE;
+
+ /* This was an optimistic token; pretend this never happened. */
+ major = GSS_S_COMPLETE;
+ *minor = 0;
+ gss_release_buffer(&tmpMinor, output_token);
+ gss_delete_sec_context(&tmpMinor, &mech->mech_context, GSS_C_NO_BUFFER);
+ }
+
+ return major;
+}
+
+static krb5_keyusage
+verify_keyusage(gssspnego_ctx ctx, int make_checksum)
+{
+ /* Of course, these are the wrong way around in the spec. */
+ return (ctx->flags.local ^ !make_checksum) ?
+ NEGOEX_KEYUSAGE_ACCEPTOR_CHECKSUM : NEGOEX_KEYUSAGE_INITIATOR_CHECKSUM;
+}
+
+static OM_uint32
+verify_key_flags(gssspnego_ctx ctx, int make_checksum)
+{
+ return (ctx->flags.local ^ make_checksum) ?
+ NEGOEX_SIGN_KEY : NEGOEX_VERIFY_KEY;
+}
+
+static OM_uint32
+verify_checksum(OM_uint32 *minor,
+ gssspnego_ctx ctx,
+ struct negoex_message *messages,
+ size_t nmessages,
+ gss_const_buffer_t input_token,
+ int *send_alert_out)
+{
+ krb5_error_code ret;
+ struct negoex_auth_mech *mech = HEIM_TAILQ_FIRST(&ctx->negoex_mechs);
+ struct verify_message *msg;
+ krb5_context context = _gss_mg_krb5_context();
+ krb5_crypto_iov iov[3];
+ krb5_keyusage usage = verify_keyusage(ctx, FALSE);
+
+ *send_alert_out = FALSE;
+ heim_assert(mech != NULL, "Invalid null mech when verifying NegoEx checksum");
+
+ /*
+ * The other party may not be ready to send a verify token yet, or (in the
+ * first initiator step) may send one for a mechanism we don't support.
+ */
+ msg = _gss_negoex_locate_verify_message(messages, nmessages);
+ if (msg == NULL || !GUID_EQ(msg->scheme, mech->scheme))
+ return GSS_S_COMPLETE;
+
+ /*
+ * Last chance attempt to obtain session key for imported exported partial
+ * contexts (which do not carry the session key at the NegoEx layer).
+ */
+ if (mech->verify_crypto == NULL)
+ get_session_keys(minor, context, verify_key_flags(ctx, FALSE), mech);
+
+ /*
+ * A recoverable error may cause us to be unable to verify a token from the
+ * other party. In this case we should send an alert.
+ */
+ if (mech->verify_crypto == NULL) {
+ *send_alert_out = TRUE;
+ return GSS_S_COMPLETE;
+ }
+
+ if (!krb5_checksum_is_keyed(context, msg->cksum_type)) {
+ *minor = (OM_uint32)NEGOEX_INVALID_CHECKSUM;
+ return GSS_S_BAD_SIG;
+ }
+
+ /*
+ * Verify the checksum over the existing transcript and the portion of the
+ * input token leading up to the verify message.
+ */
+ iov[0].flags = KRB5_CRYPTO_TYPE_DATA;
+ ret = krb5_storage_to_data(ctx->negoex_transcript, &iov[0].data);
+ if (ret) {
+ *minor = ret;
+ return GSS_S_FAILURE;
+ }
+
+ iov[1].flags = KRB5_CRYPTO_TYPE_DATA;
+ iov[1].data.data = input_token->value;
+ iov[1].data.length = msg->offset_in_token;
+
+ iov[2].flags = KRB5_CRYPTO_TYPE_CHECKSUM;
+ iov[2].data.data = (uint8_t *)msg->cksum;
+ iov[2].data.length = msg->cksum_len;
+
+ ret = krb5_verify_checksum_iov(context, mech->verify_crypto, usage,
+ iov, sizeof(iov) / sizeof(iov[0]), NULL);
+ if (ret == 0)
+ mech->verified_checksum = TRUE;
+ else
+ *minor = ret;
+
+ krb5_data_free(&iov[0].data);
+
+ return (ret == 0) ? GSS_S_COMPLETE : GSS_S_FAILURE;
+}
+
+static OM_uint32
+make_checksum(OM_uint32 *minor, gssspnego_ctx ctx)
+{
+ krb5_error_code ret;
+ krb5_context context = _gss_mg_krb5_context();
+ krb5_data d;
+ krb5_keyusage usage = verify_keyusage(ctx, TRUE);
+ krb5_checksum cksum;
+ struct negoex_auth_mech *mech = HEIM_TAILQ_FIRST(&ctx->negoex_mechs);
+ OM_uint32 major;
+
+ heim_assert(mech != NULL, "Invalid null mech when making NegoEx checksum");
+
+ if (mech->crypto == NULL) {
+ if (mech->complete) {
+ /*
+ * Last chance attempt to obtain session key for imported exported partial
+ * contexts (which do not carry the session key at the NegoEx layer).
+ */
+ get_session_keys(minor, context, verify_key_flags(ctx, TRUE), mech);
+ if (mech->crypto == NULL) {
+ *minor = (OM_uint32)NEGOEX_NO_VERIFY_KEY;
+ return GSS_S_UNAVAILABLE;
+ }
+ } else {
+ return GSS_S_COMPLETE;
+ }
+ }
+
+ ret = krb5_storage_to_data(ctx->negoex_transcript, &d);
+ if (ret) {
+ *minor = ret;
+ return GSS_S_FAILURE;
+ }
+
+ ret = krb5_create_checksum(context, mech->crypto,
+ usage, 0, d.data, d.length, &cksum);
+ krb5_data_free(&d);
+ if (ret) {
+ *minor = ret;
+ return GSS_S_FAILURE;
+ }
+
+ major = _gss_negoex_add_verify_message(minor, ctx, mech->scheme,
+ cksum.cksumtype,
+ cksum.checksum.data,
+ cksum.checksum.length);
+ free_Checksum(&cksum);
+
+ if (major == GSS_S_COMPLETE)
+ mech->sent_checksum = TRUE;
+
+ return major;
+}
+
+/*
+ * If the other side sent a VERIFY_NO_KEY pulse alert, clear the checksum state
+ * on the mechanism so that we send another VERIFY message.
+ */
+static void
+process_alerts(gssspnego_ctx ctx,
+ struct negoex_message *messages,
+ uint32_t nmessages)
+{
+ struct alert_message *msg;
+ struct negoex_auth_mech *mech;
+
+ msg = _gss_negoex_locate_alert_message(messages, nmessages);
+ if (msg != NULL && msg->verify_no_key) {
+ mech = _gss_negoex_locate_auth_scheme(ctx, msg->scheme);
+ if (mech != NULL)
+ release_mech_crypto(mech);
+ }
+}
+
+static OM_uint32
+make_output_token(OM_uint32 *minor,
+ gssspnego_ctx ctx,
+ gss_buffer_t mech_output_token,
+ int send_alert,
+ gss_buffer_t output_token)
+{
+ OM_uint32 major, tmpMinor;
+ struct negoex_auth_mech *mech;
+ enum message_type type;
+ off_t old_transcript_len;
+
+ output_token->length = 0;
+ output_token->value = NULL;
+
+ old_transcript_len = krb5_storage_seek(ctx->negoex_transcript, 0, SEEK_CUR);
+
+ /*
+ * If the mech is complete and we previously sent a checksum, we just
+ * processed the last leg and don't need to send another token.
+ */
+ if (mech_output_token->length == 0 &&
+ HEIM_TAILQ_FIRST(&ctx->negoex_mechs)->sent_checksum)
+ return GSS_S_COMPLETE;
+
+ if (ctx->negoex_step == 1) {
+ if (ctx->flags.local)
+ major = emit_initiator_nego(minor, ctx);
+ else
+ major = emit_acceptor_nego(minor, ctx);
+ if (major != GSS_S_COMPLETE)
+ return major;
+
+ type = ctx->flags.local ? INITIATOR_META_DATA : ACCEPTOR_META_DATA;
+ HEIM_TAILQ_FOREACH(mech, &ctx->negoex_mechs, links) {
+ if (mech->metadata.length > 0) {
+ major = _gss_negoex_add_exchange_message(minor, ctx,
+ type, mech->scheme,
+ &mech->metadata);
+ if (major != GSS_S_COMPLETE)
+ return major;
+ }
+ }
+ }
+
+ mech = HEIM_TAILQ_FIRST(&ctx->negoex_mechs);
+
+ if (mech_output_token->length > 0) {
+ type = ctx->flags.local ? AP_REQUEST : CHALLENGE;
+ major = _gss_negoex_add_exchange_message(minor, ctx,
+ type, mech->scheme,
+ mech_output_token);
+ if (major != GSS_S_COMPLETE)
+ return major;
+ }
+
+ if (send_alert) {
+ major = _gss_negoex_add_verify_no_key_alert(minor, ctx, mech->scheme);
+ if (major != GSS_S_COMPLETE)
+ return major;
+ }
+
+ /* Try to add a VERIFY message if we haven't already done so. */
+ if (!mech->sent_checksum) {
+ major = make_checksum(minor, ctx);
+ if (major != GSS_S_COMPLETE)
+ return major;
+ }
+
+ heim_assert(ctx->negoex_transcript != NULL, "NegoEx context uninitialized");
+
+ output_token->length =
+ krb5_storage_seek(ctx->negoex_transcript, 0, SEEK_CUR) - old_transcript_len;
+ output_token->value = malloc(output_token->length);
+ if (output_token->value == NULL) {
+ *minor = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ krb5_storage_seek(ctx->negoex_transcript, old_transcript_len, SEEK_SET);
+
+ if (krb5_storage_read(ctx->negoex_transcript,
+ output_token->value,
+ output_token->length) != output_token->length) {
+ *minor = ERANGE;
+ gss_release_buffer(&tmpMinor, output_token);
+ return GSS_S_FAILURE;
+ }
+
+ krb5_storage_seek(ctx->negoex_transcript, 0, SEEK_END);
+
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32
+_gss_negoex_init(OM_uint32 *minor,
+ struct gssspnego_optimistic_ctx *opt,
+ gssspnego_ctx ctx,
+ gss_cred_id_t cred,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_const_buffer_t input_token,
+ gss_buffer_t output_token)
+{
+ OM_uint32 major, tmpMinor;
+ gss_buffer_desc mech_output_token = GSS_C_EMPTY_BUFFER;
+ struct negoex_message *messages = NULL;
+ struct negoex_auth_mech *mech;
+ size_t nmessages = 0;
+ int send_alert = FALSE, mech_error = FALSE;
+
+ output_token->length = 0;
+ output_token->value = NULL;
+
+ if (ctx->negoex_step == 0 && input_token != GSS_C_NO_BUFFER &&
+ input_token->length != 0)
+ return GSS_S_DEFECTIVE_TOKEN;
+
+ major = _gss_negoex_begin(minor, ctx);
+ if (major != GSS_S_COMPLETE)
+ goto cleanup;
+
+ ctx->negoex_step++;
+
+ if (input_token != GSS_C_NO_BUFFER && input_token->length > 0) {
+ major = _gss_negoex_parse_token(minor, ctx, input_token,
+ &messages, &nmessages);
+ if (major != GSS_S_COMPLETE)
+ goto cleanup;
+ }
+
+ process_alerts(ctx, messages, nmessages);
+
+ if (ctx->negoex_step == 1) {
+ /* Choose a random conversation ID. */
+ krb5_generate_random_block(ctx->negoex_conv_id, GUID_LENGTH);
+
+ /* Query each mech for its metadata (this may prune the mech list). */
+ query_meta_data(ctx, opt, cred, req_flags);
+ } else if (ctx->negoex_step == 2) {
+ /* See if the mech processed the optimistic token. */
+ check_optimistic_result(ctx, messages, nmessages);
+
+ /* Pass the acceptor metadata to each mech to prune the list. */
+ exchange_meta_data(ctx, cred, req_flags, messages, nmessages);
+
+ /* Process the ACCEPTOR_NEGO message. */
+ major = process_acceptor_nego(minor, ctx, messages, nmessages);
+ if (major != GSS_S_COMPLETE)
+ goto cleanup;
+ }
+
+ /*
+ * Process the input token and/or produce an output token. This may prune
+ * the mech list, but on success there will be at least one mech entry.
+ */
+ major = mech_init(minor, opt, ctx, cred, req_flags, time_req,
+ input_chan_bindings, messages, nmessages,
+ &mech_output_token, &mech_error);
+ if (major != GSS_S_COMPLETE)
+ goto cleanup;
+ heim_assert(!HEIM_TAILQ_EMPTY(&ctx->negoex_mechs),
+ "Invalid empty NegoEx mechanism list");
+
+ /*
+ * At this point in step 2 we have performed the metadata exchange and
+ * chosen a mech we can use, so discard any fallback mech entries.
+ */
+ if (ctx->negoex_step == 2)
+ _gss_negoex_select_auth_mech(ctx, HEIM_TAILQ_FIRST(&ctx->negoex_mechs));
+
+ major = verify_checksum(minor, ctx, messages, nmessages, input_token,
+ &send_alert);
+ if (major != GSS_S_COMPLETE)
+ goto cleanup;
+
+ if (input_token != GSS_C_NO_BUFFER) {
+ if (krb5_storage_write(ctx->negoex_transcript,
+ input_token->value,
+ input_token->length) != input_token->length) {
+ major = GSS_S_FAILURE;
+ *minor = ENOMEM;
+ goto cleanup;
+ }
+ }
+
+ major = make_output_token(minor, ctx, &mech_output_token, send_alert,
+ output_token);
+ if (major != GSS_S_COMPLETE)
+ goto cleanup;
+
+ mech = HEIM_TAILQ_FIRST(&ctx->negoex_mechs);
+ major = (mech->complete && mech->verified_checksum) ? GSS_S_COMPLETE :
+ GSS_S_CONTINUE_NEEDED;
+
+cleanup:
+ free(messages);
+ gss_release_buffer(&tmpMinor, &mech_output_token);
+ _gss_negoex_end(ctx);
+
+ if (GSS_ERROR(major)) {
+ if (!mech_error) {
+ krb5_context context = _gss_mg_krb5_context();
+ const char *emsg = krb5_get_error_message(context, *minor);
+
+ gss_mg_set_error_string(GSS_SPNEGO_MECHANISM,
+ major, *minor,
+ "NegoEx failed to initialize security context: %s",
+ emsg);
+ krb5_free_error_message(context, emsg);
+ }
+
+ _gss_negoex_release_context(ctx);
+ }
+
+ return major;
+}
+
+OM_uint32
+_gss_negoex_accept(OM_uint32 *minor,
+ gssspnego_ctx ctx,
+ gss_cred_id_t cred,
+ gss_const_buffer_t input_token,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_buffer_t output_token,
+ gss_cred_id_t *deleg_cred)
+{
+ OM_uint32 major, tmpMinor;
+ gss_buffer_desc mech_output_token = GSS_C_EMPTY_BUFFER;
+ struct negoex_message *messages = NULL;
+ struct negoex_auth_mech *mech;
+ size_t nmessages;
+ int send_alert = FALSE, mech_error = FALSE;
+
+ output_token->length = 0;
+ output_token->value = NULL;
+ if (deleg_cred)
+ *deleg_cred = GSS_C_NO_CREDENTIAL;
+
+ if (input_token == GSS_C_NO_BUFFER || input_token->length == 0) {
+ major = GSS_S_DEFECTIVE_TOKEN;
+ goto cleanup;
+ }
+
+ major = _gss_negoex_begin(minor, ctx);
+ if (major != GSS_S_COMPLETE)
+ goto cleanup;
+
+ ctx->negoex_step++;
+
+ major = _gss_negoex_parse_token(minor, ctx, input_token,
+ &messages, &nmessages);
+ if (major != GSS_S_COMPLETE)
+ goto cleanup;
+
+ process_alerts(ctx, messages, nmessages);
+
+ if (ctx->negoex_step == 1) {
+ /*
+ * Read the INITIATOR_NEGO message to prune the candidate mech list.
+ */
+ major = process_initiator_nego(minor, ctx, messages, nmessages);
+ if (major != GSS_S_COMPLETE)
+ goto cleanup;
+
+ /*
+ * Pass the initiator metadata to each mech to prune the list, and
+ * query each mech for its acceptor metadata (which may also prune the
+ * list).
+ */
+ exchange_meta_data(ctx, cred, 0, messages, nmessages);
+ query_meta_data(ctx, NULL, cred, 0);
+
+ if (HEIM_TAILQ_EMPTY(&ctx->negoex_mechs)) {
+ *minor = (OM_uint32)NEGOEX_NO_AVAILABLE_MECHS;
+ major = GSS_S_FAILURE;
+ goto cleanup;
+ }
+ }
+
+ /*
+ * Process the input token and possibly produce an output token. This may
+ * prune the list to a single mech. Continue on error if an output token
+ * is generated, so that we send the token to the initiator.
+ */
+ major = mech_accept(minor, ctx, cred, input_chan_bindings,
+ messages, nmessages, &mech_output_token,
+ deleg_cred, &mech_error);
+ if (major != GSS_S_COMPLETE && mech_output_token.length == 0)
+ goto cleanup;
+
+ if (major == GSS_S_COMPLETE) {
+ major = verify_checksum(minor, ctx, messages, nmessages, input_token,
+ &send_alert);
+ if (major != GSS_S_COMPLETE)
+ goto cleanup;
+ }
+
+ if (krb5_storage_write(ctx->negoex_transcript,
+ input_token->value,
+ input_token->length) != input_token->length) {
+ major = GSS_S_FAILURE;
+ *minor = ENOMEM;
+ goto cleanup;
+ }
+
+ major = make_output_token(minor, ctx, &mech_output_token, send_alert,
+ output_token);
+ if (major != GSS_S_COMPLETE)
+ goto cleanup;
+
+ mech = HEIM_TAILQ_FIRST(&ctx->negoex_mechs);
+ major = (mech->complete && mech->verified_checksum) ? GSS_S_COMPLETE :
+ GSS_S_CONTINUE_NEEDED;
+
+cleanup:
+ free(messages);
+ gss_release_buffer(&tmpMinor, &mech_output_token);
+ _gss_negoex_end(ctx);
+
+ if (GSS_ERROR(major)) {
+ if (!mech_error) {
+ krb5_context context = _gss_mg_krb5_context();
+ const char *emsg = krb5_get_error_message(context, *minor);
+
+ gss_mg_set_error_string(GSS_SPNEGO_MECHANISM,
+ major, *minor,
+ "NegoEx failed to accept security context: %s",
+ emsg);
+ krb5_free_error_message(context, emsg);
+ }
+
+ _gss_negoex_release_context(ctx);
+ }
+
+ return major;
+}
diff --git a/third_party/heimdal/lib/gssapi/spnego/negoex_err.et b/third_party/heimdal/lib/gssapi/spnego/negoex_err.et
new file mode 100644
index 0000000..99a8a2e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/spnego/negoex_err.et
@@ -0,0 +1,25 @@
+#
+# NegoEx error messages
+#
+
+id "$Id$"
+
+error_table ngex
+
+prefix NEGOEX
+
+error_code INVALID_MESSAGE_SIGNATURE, "Invalid NegoEx signature"
+error_code INVALID_MESSAGE_TYPE, "Invalid NegoEx message type"
+error_code INVALID_MESSAGE_SIZE, "Invalid NegoEx message size"
+error_code INVALID_CONVERSATION_ID, "Invalid NegoEx conversation ID"
+error_code AUTH_SCHEME_NOT_FOUND, "NegoEx authentication scheme not found"
+error_code MISSING_NEGO_MESSAGE, "Missing NegoEx negotiate message"
+error_code MISSING_AP_REQUEST_MESSAGE, "Missing NegoEx authentication protocol request message"
+error_code NO_AVAILABLE_MECHS, "No mutually supported NegoEx authentication schemes"
+error_code NO_VERIFY_KEY, "No NegoEx verify key"
+error_code UNKNOWN_CHECKSUM_SCHEME, "Unknown NegoEx checksum scheme"
+error_code INVALID_CHECKSUM, "Invalid NegoEx checksum"
+error_code UNSUPPORTED_CRITICAL_EXTENSION, "Unsupported critical NegoEx extension"
+error_code UNSUPPORTED_VERSION, "Unsupported NegoEx version"
+error_code MESSAGE_OUT_OF_SEQUENCE, "NegoEx message out of sequence"
+
diff --git a/third_party/heimdal/lib/gssapi/spnego/negoex_locl.h b/third_party/heimdal/lib/gssapi/spnego/negoex_locl.h
new file mode 100644
index 0000000..3e0d29a
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/spnego/negoex_locl.h
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2011-2019 PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef NEGOEX_LOCL_H
+#define NEGOEX_LOCL_H
+
+#include <negoex_err.h>
+
+struct gssspnego_ctx_desc;
+
+#define MESSAGE_SIGNATURE 0x535458454F47454EULL
+
+#define EXTENSION_LENGTH 12
+
+#define EXTENSION_FLAG_CRITICAL 0x80000000
+
+#define CHECKSUM_SCHEME_RFC3961 1
+
+#define NEGOEX_KEYUSAGE_INITIATOR_CHECKSUM 23
+#define NEGOEX_KEYUSAGE_ACCEPTOR_CHECKSUM 25
+
+#define CHECKSUM_HEADER_LENGTH 20
+
+#define GUID_LENGTH 16
+
+typedef uint8_t auth_scheme[GUID_LENGTH];
+typedef uint8_t conversation_id[GUID_LENGTH];
+#define GUID_EQ(a, b) (memcmp(a, b, GUID_LENGTH) == 0)
+
+#define NEGO_MESSAGE_HEADER_LENGTH 96
+#define EXCHANGE_MESSAGE_HEADER_LENGTH 64
+#define VERIFY_MESSAGE_HEADER_LENGTH 80
+#define ALERT_MESSAGE_HEADER_LENGTH 72
+#define ALERT_LENGTH 12
+#define ALERT_PULSE_LENGTH 8
+
+#define ALERT_TYPE_PULSE 1
+#define ALERT_VERIFY_NO_KEY 1
+
+enum message_type {
+ INITIATOR_NEGO = 0, /* NEGO_MESSAGE */
+ ACCEPTOR_NEGO, /* NEGO_MESSAGE */
+ INITIATOR_META_DATA, /* EXCHANGE_MESSAGE */
+ ACCEPTOR_META_DATA, /* EXCHANGE_MESSAGE */
+ CHALLENGE, /* EXCHANGE_MESSAGE */
+ AP_REQUEST, /* EXCHANGE_MESSAGE */
+ VERIFY, /* VERIFY_MESSAGE */
+ ALERT, /* ALERT */
+};
+
+struct nego_message {
+ uint8_t random[32];
+ const uint8_t *schemes;
+ uint16_t nschemes;
+};
+
+struct exchange_message {
+ auth_scheme scheme;
+ gss_buffer_desc token;
+};
+
+struct verify_message {
+ auth_scheme scheme;
+ uint32_t cksum_type;
+ const uint8_t *cksum;
+ size_t cksum_len;
+ size_t offset_in_token;
+};
+
+struct alert_message {
+ auth_scheme scheme;
+ int verify_no_key;
+};
+
+struct negoex_message {
+ uint32_t type;
+ union {
+ struct nego_message n;
+ struct exchange_message e;
+ struct verify_message v;
+ struct alert_message a;
+ } u;
+};
+
+struct negoex_auth_mech {
+ HEIM_TAILQ_ENTRY(negoex_auth_mech) links;
+ gss_OID oid;
+ auth_scheme scheme;
+ gss_ctx_id_t mech_context;
+ gss_buffer_desc metadata;
+ krb5_crypto crypto;
+ krb5_crypto verify_crypto;
+ int complete;
+ int sent_checksum;
+ int verified_checksum;
+};
+
+#define NEGOEX_LOG_LEVEL 10
+
+#endif /* NEGOEX_LOCL_H */
diff --git a/third_party/heimdal/lib/gssapi/spnego/negoex_util.c b/third_party/heimdal/lib/gssapi/spnego/negoex_util.c
new file mode 100644
index 0000000..aac09d4
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/spnego/negoex_util.c
@@ -0,0 +1,1042 @@
+/*
+ * Copyright (C) 2011-2019 PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "spnego_locl.h"
+
+/*
+ * SPNEGO expects to find the active mech context in ctx->negotiated_ctx_id,
+ * but the metadata exchange APIs force us to have one mech context per mech
+ * entry. To address this mismatch, move the active mech context (if we have
+ * one) to ctx->negotiated_ctx_id at the end of NegoEx processing.
+ */
+void
+_gss_negoex_end(gssspnego_ctx ctx)
+{
+ struct negoex_auth_mech *mech;
+
+ mech = HEIM_TAILQ_FIRST(&ctx->negoex_mechs);
+ if (mech == NULL || mech->mech_context == GSS_C_NO_CONTEXT)
+ return;
+
+ heim_assert(ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT,
+ "SPNEGO/NegoEx context mismatch");
+ ctx->negotiated_ctx_id = mech->mech_context;
+ mech->mech_context = GSS_C_NO_CONTEXT;
+}
+
+OM_uint32
+_gss_negoex_begin(OM_uint32 *minor, gssspnego_ctx ctx)
+{
+ struct negoex_auth_mech *mech;
+
+ if (ctx->negoex_transcript != NULL) {
+ /*
+ * The context is already initialized for NegoEx; undo what
+ * _gss_negoex_end() did, if applicable.
+ */
+ if (ctx->negotiated_ctx_id != GSS_C_NO_CONTEXT) {
+ mech = HEIM_TAILQ_FIRST(&ctx->negoex_mechs);
+ heim_assert(mech != NULL && mech->mech_context == GSS_C_NO_CONTEXT,
+ "NegoEx/SPNEGO context mismatch");
+ mech->mech_context = ctx->negotiated_ctx_id;
+ ctx->negotiated_ctx_id = GSS_C_NO_CONTEXT;
+ }
+ return GSS_S_COMPLETE;
+ }
+
+ ctx->negoex_transcript = krb5_storage_emem();
+ if (ctx->negoex_transcript == NULL) {
+ *minor = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ krb5_storage_set_byteorder(ctx->negoex_transcript,
+ KRB5_STORAGE_BYTEORDER_LE);
+
+ return GSS_S_COMPLETE;
+}
+
+static void
+release_all_mechs(gssspnego_ctx ctx, krb5_context context)
+{
+ struct negoex_auth_mech *mech, *next;
+
+ HEIM_TAILQ_FOREACH_SAFE(mech, &ctx->negoex_mechs, links, next) {
+ _gss_negoex_release_auth_mech(context, mech);
+ }
+
+ HEIM_TAILQ_INIT(&ctx->negoex_mechs);
+}
+
+void
+_gss_negoex_release_context(gssspnego_ctx ctx)
+{
+ krb5_context context = _gss_mg_krb5_context();
+
+ if (ctx->negoex_transcript != NULL) {
+ krb5_storage_free(ctx->negoex_transcript);
+ ctx->negoex_transcript = NULL;
+ }
+
+ release_all_mechs(ctx, context);
+}
+
+static int
+guid_to_string(const uint8_t guid[16], char *buffer, size_t bufsiz)
+{
+ uint32_t data1;
+ uint16_t data2, data3;
+
+ _gss_mg_decode_le_uint32(&guid[0], &data1);
+ _gss_mg_decode_le_uint16(&guid[4], &data2);
+ _gss_mg_decode_le_uint16(&guid[6], &data3);
+
+ return snprintf(buffer, bufsiz,
+ "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+ data1, data2, data3, guid[8], guid[9], guid[10], guid[11],
+ guid[12], guid[13], guid[14], guid[15]);
+}
+
+void
+_gss_negoex_log_auth_scheme(int initiator,
+ int index,
+ const auth_scheme scheme)
+{
+ char scheme_str[37];
+
+ guid_to_string(scheme, scheme_str, sizeof(scheme_str));
+
+ _gss_mg_log(NEGOEX_LOG_LEVEL,
+ "negoex: %s authentication scheme %d %s",
+ initiator ? "proposing" : "received", index, scheme_str);
+}
+
+void
+_gss_negoex_log_message(int direction,
+ enum message_type type,
+ const conversation_id conv_id,
+ unsigned int seqnum,
+ unsigned int header_len,
+ unsigned int msg_len)
+{
+ char conv_str[37];
+ char *typestr;
+
+ if (type == INITIATOR_NEGO)
+ typestr = "INITIATOR_NEGO";
+ else if (type == ACCEPTOR_NEGO)
+ typestr = "ACCEPTOR_NEGO";
+ else if (type == INITIATOR_META_DATA)
+ typestr = "INITIATOR_META_DATA";
+ else if (type == ACCEPTOR_META_DATA)
+ typestr = "ACCEPTOR_META_DATA";
+ else if (type == CHALLENGE)
+ typestr = "CHALLENGE";
+ else if (type == AP_REQUEST)
+ typestr = "AP_REQUEST";
+ else if (type == VERIFY)
+ typestr = "VERIFY";
+ else if (type == ALERT)
+ typestr = "ALERT";
+ else
+ typestr = "UNKNOWN";
+
+ guid_to_string(conv_id, conv_str, sizeof(conv_str));
+ _gss_mg_log(NEGOEX_LOG_LEVEL,
+ "negoex: %s (%d)%s conversation %s",
+ direction ? "received" : "sending",
+ seqnum, typestr, conv_str);
+}
+
+/*
+ * Check that the described vector lies within the message, and return a
+ * pointer to its first element.
+ */
+static inline const uint8_t *
+vector_base(size_t offset, size_t count, size_t width,
+ const uint8_t *msg_base, size_t msg_len)
+{
+ if (offset > msg_len || count > (msg_len - offset) / width)
+ return NULL;
+ return msg_base + offset;
+}
+
+static OM_uint32
+parse_nego_message(OM_uint32 *minor, krb5_storage *sp,
+ const uint8_t *msg_base, size_t msg_len,
+ struct nego_message *msg)
+{
+ krb5_error_code ret;
+ const uint8_t *p;
+ uint64_t protocol_version;
+ uint32_t extension_type, offset;
+ uint16_t count;
+ size_t i;
+
+ if (krb5_storage_read(sp, msg->random,
+ sizeof(msg->random)) != sizeof(msg->random)) {
+ *minor = (OM_uint32)NEGOEX_INVALID_MESSAGE_SIZE;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ ret = krb5_ret_uint64(sp, &protocol_version);
+ if (ret) {
+ *minor = ret;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ if (protocol_version != 0) {
+ *minor = (OM_uint32)NEGOEX_UNSUPPORTED_VERSION;
+ return GSS_S_UNAVAILABLE;
+ }
+
+ ret = krb5_ret_uint32(sp, &offset);
+ if (ret == 0)
+ ret = krb5_ret_uint16(sp, &count);
+ if (ret) {
+ *minor = ret;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ msg->schemes = vector_base(offset, count, GUID_LENGTH, msg_base, msg_len);
+ msg->nschemes = count;
+ if (msg->schemes == NULL) {
+ *minor = (OM_uint32)NEGOEX_INVALID_MESSAGE_SIZE;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ ret = krb5_ret_uint32(sp, &offset);
+ if (ret == 0)
+ ret = krb5_ret_uint16(sp, &count);
+ if (ret) {
+ *minor = ret;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+ p = vector_base(offset, count, EXTENSION_LENGTH, msg_base, msg_len);
+ for (i = 0; i < count; i++) {
+ _gss_mg_decode_le_uint32(p + i * EXTENSION_LENGTH, &extension_type);
+ if (extension_type & EXTENSION_FLAG_CRITICAL) {
+ *minor = (OM_uint32)NEGOEX_UNSUPPORTED_CRITICAL_EXTENSION;
+ return GSS_S_UNAVAILABLE;
+ }
+ }
+
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+parse_exchange_message(OM_uint32 *minor, krb5_storage *sp,
+ const uint8_t *msg_base, size_t msg_len,
+ struct exchange_message *msg)
+{
+ krb5_error_code ret;
+ const uint8_t *p;
+ uint32_t offset;
+ uint16_t len;
+
+ if (krb5_storage_read(sp, msg->scheme, GUID_LENGTH) != GUID_LENGTH) {
+ *minor = (OM_uint32)NEGOEX_INVALID_MESSAGE_SIZE;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ ret = krb5_ret_uint32(sp, &offset);
+ if (ret == 0)
+ ret = krb5_ret_uint16(sp, &len);
+ if (ret) {
+ *minor = (OM_uint32)NEGOEX_INVALID_MESSAGE_SIZE;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ p = vector_base(offset, len, 1, msg_base, msg_len);
+ if (p == NULL) {
+ *minor = (OM_uint32)NEGOEX_INVALID_MESSAGE_SIZE;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+ msg->token.value = (void *)p;
+ msg->token.length = len;
+
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+parse_verify_message(OM_uint32 *minor, krb5_storage *sp,
+ const uint8_t *msg_base, size_t msg_len,
+ size_t token_offset, struct verify_message *msg)
+{
+ krb5_error_code ret;
+ uint32_t hdrlen, cksum_scheme;
+ uint32_t offset, len;
+
+ if (krb5_storage_read(sp, msg->scheme, GUID_LENGTH) == GUID_LENGTH)
+ ret = 0;
+ else
+ ret = NEGOEX_INVALID_MESSAGE_SIZE;
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &hdrlen);
+ if (ret) {
+ *minor = ret;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ if (hdrlen != CHECKSUM_HEADER_LENGTH) {
+ *minor = (OM_uint32)NEGOEX_INVALID_MESSAGE_SIZE;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ ret = krb5_ret_uint32(sp, &cksum_scheme);
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &msg->cksum_type);
+ if (ret) {
+ *minor = ret;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ if (cksum_scheme != CHECKSUM_SCHEME_RFC3961) {
+ *minor = (OM_uint32)NEGOEX_UNKNOWN_CHECKSUM_SCHEME;
+ return GSS_S_UNAVAILABLE;
+ }
+
+ ret = krb5_ret_uint32(sp, &offset);
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &len);
+ if (ret) {
+ *minor = ret;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ msg->cksum = vector_base(offset, len, 1, msg_base, msg_len);
+ msg->cksum_len = len;
+ if (msg->cksum == NULL) {
+ *minor = (OM_uint32)NEGOEX_INVALID_MESSAGE_SIZE;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ msg->offset_in_token = token_offset;
+ return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+storage_from_memory(OM_uint32 *minor,
+ const uint8_t *data,
+ size_t length,
+ krb5_storage **sp)
+{
+ *sp = krb5_storage_from_readonly_mem(data, length);
+ if (sp == NULL) {
+ *minor = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ krb5_storage_set_byteorder(*sp, KRB5_STORAGE_BYTEORDER_LE);
+ krb5_storage_set_eof_code(*sp, NEGOEX_INVALID_MESSAGE_SIZE);
+
+ return 0;
+}
+
+static OM_uint32
+parse_alert_message(OM_uint32 *minor, krb5_storage *sp,
+ const uint8_t *msg_base, size_t msg_len,
+ struct alert_message *msg)
+{
+ OM_uint32 major;
+ krb5_error_code ret;
+ const uint8_t *p;
+ uint32_t error_code, atype;
+ uint32_t alerts_offset, nalerts, value_offset, value_len;
+ size_t i;
+ krb5_storage *alerts;
+
+ if (krb5_storage_read(sp, msg->scheme, GUID_LENGTH) == GUID_LENGTH)
+ ret = 0;
+ else
+ ret = NEGOEX_INVALID_MESSAGE_SIZE;
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &error_code);
+ if (ret) {
+ *minor = ret;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ ret = krb5_ret_uint32(sp, &alerts_offset);
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &nalerts);
+ if (ret) {
+ *minor = ret;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ p = vector_base(alerts_offset, nalerts, ALERT_LENGTH, msg_base, msg_len);
+ if (p == NULL) {
+ *minor = (OM_uint32)NEGOEX_INVALID_MESSAGE_SIZE;
+ return GSS_S_DEFECTIVE_TOKEN;
+ }
+
+ /* Look for a VERIFY_NO_KEY pulse alert in the alerts vector. */
+ msg->verify_no_key = FALSE;
+
+ major = storage_from_memory(minor, p, nalerts * ALERT_LENGTH, &alerts);
+ if (major != GSS_S_COMPLETE)
+ return major;
+
+ for (i = 0; i < nalerts; i++) {
+ ret = krb5_ret_uint32(alerts, &atype);
+ if (ret == 0)
+ ret = krb5_ret_uint32(alerts, &value_offset);
+ if (ret == 0)
+ ret = krb5_ret_uint32(alerts, &value_len);
+ if (ret) {
+ *minor = ret;
+ major = GSS_S_DEFECTIVE_TOKEN;
+ break;
+ }
+
+ p = vector_base(value_offset, value_len, 1, msg_base, msg_len);
+ if (p == NULL) {
+ *minor = (OM_uint32)NEGOEX_INVALID_MESSAGE_SIZE;
+ major = GSS_S_DEFECTIVE_TOKEN;
+ break;
+ }
+
+ if (atype == ALERT_TYPE_PULSE && value_len >= ALERT_PULSE_LENGTH) {
+ krb5_storage *pulse;
+ uint32_t hdrlen, reason;
+
+ major = storage_from_memory(minor, p, value_len, &pulse);
+ if (major != GSS_S_COMPLETE)
+ break;
+
+ ret = krb5_ret_uint32(pulse, &hdrlen);
+ if (ret == 0)
+ ret = krb5_ret_uint32(pulse, &reason);
+ krb5_storage_free(pulse);
+ if (ret) {
+ *minor = ret;
+ major = GSS_S_DEFECTIVE_TOKEN;
+ break;
+ }
+
+ if (reason == ALERT_VERIFY_NO_KEY)
+ msg->verify_no_key = TRUE;
+ }
+ }
+
+ krb5_storage_free(alerts);
+
+ return major;
+}
+
+static OM_uint32
+parse_message(OM_uint32 *minor,
+ gssspnego_ctx ctx,
+ gss_const_buffer_t token,
+ size_t *token_offset,
+ struct negoex_message *msg)
+{
+ OM_uint32 major;
+ krb5_error_code ret;
+ krb5_storage *sp;
+ uint64_t signature;
+ uint32_t header_len, msg_len;
+ uint32_t type, seqnum;
+ conversation_id conv_id;
+ size_t token_remaining = token->length - *token_offset;
+ const uint8_t *msg_base = (uint8_t *)token->value + *token_offset;
+
+ major = storage_from_memory(minor, msg_base, token_remaining, &sp);
+ if (major != GSS_S_COMPLETE)
+ return major;
+
+ major = GSS_S_DEFECTIVE_TOKEN;
+
+ ret = krb5_ret_uint64(sp, &signature);
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &type);
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &seqnum);
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &header_len);
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &msg_len);
+ if (ret == 0) {
+ if (krb5_storage_read(sp, conv_id, GUID_LENGTH) != GUID_LENGTH)
+ ret = NEGOEX_INVALID_MESSAGE_SIZE;
+ }
+ if (ret) {
+ *minor = ret;
+ goto cleanup;
+ }
+
+ if (msg_len > token_remaining || header_len > msg_len) {
+ *minor = (OM_uint32)NEGOEX_INVALID_MESSAGE_SIZE;
+ goto cleanup;
+ }
+ if (signature != MESSAGE_SIGNATURE) {
+ *minor = (OM_uint32)NEGOEX_INVALID_MESSAGE_SIGNATURE;
+ goto cleanup;
+ }
+ if (seqnum != ctx->negoex_seqnum) {
+ *minor = (OM_uint32)NEGOEX_MESSAGE_OUT_OF_SEQUENCE;
+ goto cleanup;
+ }
+ if (seqnum == 0) {
+ memcpy(ctx->negoex_conv_id, conv_id, GUID_LENGTH);
+ } else if (!GUID_EQ(conv_id, ctx->negoex_conv_id)) {
+ *minor = (OM_uint32)NEGOEX_INVALID_CONVERSATION_ID;
+ goto cleanup;
+ }
+
+ krb5_storage_truncate(sp, msg_len);
+
+ msg->type = type;
+ if (type == INITIATOR_NEGO || type == ACCEPTOR_NEGO) {
+ major = parse_nego_message(minor, sp, msg_base, msg_len, &msg->u.n);
+ } else if (type == INITIATOR_META_DATA || type == ACCEPTOR_META_DATA ||
+ type == CHALLENGE || type == AP_REQUEST) {
+ major = parse_exchange_message(minor, sp, msg_base, msg_len,
+ &msg->u.e);
+ } else if (type == VERIFY) {
+ major = parse_verify_message(minor, sp, msg_base, msg_len,
+ msg_base - (uint8_t *)token->value,
+ &msg->u.v);
+ } else if (type == ALERT) {
+ major = parse_alert_message(minor, sp, msg_base, msg_len, &msg->u.a);
+ } else {
+ *minor = (OM_uint32)NEGOEX_INVALID_MESSAGE_TYPE;
+ goto cleanup;
+ }
+
+cleanup:
+ krb5_storage_free(sp);
+
+ if (major == GSS_S_COMPLETE) {
+ _gss_negoex_log_message(1, msg->type,
+ ctx->negoex_conv_id, ctx->negoex_seqnum,
+ header_len, msg_len);
+ ctx->negoex_seqnum++;
+ *token_offset += msg_len;
+ }
+
+ return major;
+}
+
+/*
+ * Parse token into an array of negoex_message structures. All pointer fields
+ * within the parsed messages are aliases into token, so the result can be
+ * freed with free(). An unknown protocol version, a critical extension, or an
+ * unknown checksum scheme will cause a parsing failure. Increment the
+ * sequence number in ctx for each message, and record and check the
+ * conversation ID in ctx as appropriate.
+ */
+OM_uint32
+_gss_negoex_parse_token(OM_uint32 *minor,
+ gssspnego_ctx ctx,
+ gss_const_buffer_t token,
+ struct negoex_message **messages_out,
+ size_t *count_out)
+{
+ OM_uint32 major = GSS_S_DEFECTIVE_TOKEN;
+ size_t count = 0;
+ size_t token_offset = 0;
+ struct negoex_message *messages = NULL, *newptr;
+
+ *messages_out = NULL;
+ *count_out = 0;
+ heim_assert(token != GSS_C_NO_BUFFER, "Invalid null NegoEx input token");
+
+ while (token_offset < token->length) {
+ newptr = realloc(messages, (count + 1) * sizeof(*newptr));
+ if (newptr == NULL) {
+ free(messages);
+ *minor = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+ messages = newptr;
+
+ major = parse_message(minor, ctx, token, &token_offset,
+ &messages[count]);
+ if (major != GSS_S_COMPLETE)
+ break;
+
+ count++;
+ }
+
+ if (token_offset != token->length) {
+ *minor = (OM_uint32)NEGOEX_INVALID_MESSAGE_SIZE;
+ major = GSS_S_DEFECTIVE_TOKEN;
+ }
+ if (major != GSS_S_COMPLETE) {
+ free(messages);
+ return major;
+ }
+
+ *messages_out = messages;
+ *count_out = count;
+ return GSS_S_COMPLETE;
+}
+
+static struct negoex_message *
+locate_message(struct negoex_message *messages, size_t nmessages,
+ enum message_type type)
+{
+ uint32_t i;
+
+ for (i = 0; i < nmessages; i++) {
+ if (messages[i].type == type)
+ return &messages[i];
+ }
+
+ return NULL;
+}
+
+struct nego_message *
+_gss_negoex_locate_nego_message(struct negoex_message *messages,
+ size_t nmessages,
+ enum message_type type)
+{
+ struct negoex_message *msg = locate_message(messages, nmessages, type);
+
+ return (msg == NULL) ? NULL : &msg->u.n;
+}
+
+struct exchange_message *
+_gss_negoex_locate_exchange_message(struct negoex_message *messages,
+ size_t nmessages,
+ enum message_type type)
+{
+ struct negoex_message *msg = locate_message(messages, nmessages, type);
+
+ return (msg == NULL) ? NULL : &msg->u.e;
+}
+
+struct verify_message *
+_gss_negoex_locate_verify_message(struct negoex_message *messages,
+ size_t nmessages)
+{
+ struct negoex_message *msg = locate_message(messages, nmessages, VERIFY);
+
+ return (msg == NULL) ? NULL : &msg->u.v;
+}
+
+struct alert_message *
+_gss_negoex_locate_alert_message(struct negoex_message *messages,
+ size_t nmessages)
+{
+ struct negoex_message *msg = locate_message(messages, nmessages, ALERT);
+
+ return (msg == NULL) ? NULL : &msg->u.a;
+}
+
+/*
+ * Add the encoding of a MESSAGE_HEADER structure to buf, given the number of
+ * bytes of the payload following the full header. Increment the sequence
+ * number in ctx. Set *payload_start_out to the position of the payload within
+ * the message.
+ */
+static OM_uint32
+put_message_header(OM_uint32 *minor, gssspnego_ctx ctx,
+ enum message_type type, uint32_t payload_len,
+ uint32_t *payload_start_out)
+{
+ krb5_error_code ret;
+ size_t header_len = 0;
+
+ if (type == INITIATOR_NEGO || type == ACCEPTOR_NEGO)
+ header_len = NEGO_MESSAGE_HEADER_LENGTH;
+ else if (type == INITIATOR_META_DATA || type == ACCEPTOR_META_DATA ||
+ type == CHALLENGE || type == AP_REQUEST)
+ header_len = EXCHANGE_MESSAGE_HEADER_LENGTH;
+ else if (type == VERIFY)
+ header_len = VERIFY_MESSAGE_HEADER_LENGTH;
+ else if (type == ALERT)
+ header_len = ALERT_MESSAGE_HEADER_LENGTH;
+ else
+ heim_assert(0, "Invalid NegoEx message type");
+
+ /* Signature */
+ CHECK(ret, krb5_store_uint64(ctx->negoex_transcript, MESSAGE_SIGNATURE));
+ /* MessageType */
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, type));
+ /* SequenceNum */
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, ctx->negoex_seqnum));
+ /* cbHeaderLength */
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, header_len));
+ /* cbMessageLength */
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, header_len + payload_len));
+ /* ConversationId */
+ CHECK(ret, krb5_store_bytes(ctx->negoex_transcript, ctx->negoex_conv_id, GUID_LENGTH));
+
+ _gss_negoex_log_message(0, type,
+ ctx->negoex_conv_id, ctx->negoex_seqnum,
+ header_len,
+ header_len + payload_len);
+
+ ctx->negoex_seqnum++;
+
+ *payload_start_out = header_len;
+ return GSS_S_COMPLETE;
+
+fail:
+ *minor = ret;
+ return GSS_S_FAILURE;
+}
+
+OM_uint32
+_gss_negoex_add_nego_message(OM_uint32 *minor,
+ gssspnego_ctx ctx,
+ enum message_type type,
+ uint8_t random[32])
+{
+ OM_uint32 major;
+ krb5_error_code ret;
+ struct negoex_auth_mech *mech;
+ uint32_t payload_start;
+ uint16_t nschemes;
+
+ nschemes = 0;
+ HEIM_TAILQ_FOREACH(mech, &ctx->negoex_mechs, links)
+ nschemes++;
+
+ major = put_message_header(minor, ctx, type,
+ nschemes * GUID_LENGTH, &payload_start);
+ if (major != GSS_S_COMPLETE)
+ return major;
+
+ CHECK(ret, krb5_store_bytes(ctx->negoex_transcript, random, 32));
+ /* ProtocolVersion */
+ CHECK(ret, krb5_store_uint64(ctx->negoex_transcript, 0));
+ /* AuthSchemes vector */
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, payload_start));
+ CHECK(ret, krb5_store_uint16(ctx->negoex_transcript, nschemes));
+ /* Extensions vector */
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, payload_start));
+ CHECK(ret, krb5_store_uint16(ctx->negoex_transcript, 0));
+ /* Four bytes of padding to reach a multiple of 8 bytes. */
+ CHECK(ret, krb5_store_bytes(ctx->negoex_transcript, "\0\0\0\0", 4));
+
+ /* Payload (auth schemes) */
+ HEIM_TAILQ_FOREACH(mech, &ctx->negoex_mechs, links) {
+ CHECK(ret, krb5_store_bytes(ctx->negoex_transcript, mech->scheme, GUID_LENGTH));
+ }
+
+ return GSS_S_COMPLETE;
+
+fail:
+ *minor = ret;
+ return GSS_S_FAILURE;
+}
+
+OM_uint32
+_gss_negoex_add_exchange_message(OM_uint32 *minor,
+ gssspnego_ctx ctx,
+ enum message_type type,
+ const auth_scheme scheme,
+ gss_buffer_t token)
+{
+ OM_uint32 major;
+ krb5_error_code ret;
+ uint32_t payload_start;
+
+ major = put_message_header(minor, ctx, type, token->length, &payload_start);
+ if (major != GSS_S_COMPLETE)
+ return major;
+
+ CHECK(ret, krb5_store_bytes(ctx->negoex_transcript, scheme, GUID_LENGTH));
+ /* Exchange byte vector */
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, payload_start));
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, token->length));
+ /* Payload (token) */
+ CHECK(ret, krb5_store_bytes(ctx->negoex_transcript, token->value, token->length));
+
+ return GSS_S_COMPLETE;
+
+fail:
+ *minor = ret;
+ return GSS_S_FAILURE;
+}
+
+OM_uint32
+_gss_negoex_add_verify_message(OM_uint32 *minor,
+ gssspnego_ctx ctx,
+ const auth_scheme scheme,
+ uint32_t cksum_type,
+ const uint8_t *cksum,
+ uint32_t cksum_len)
+{
+ OM_uint32 major;
+ krb5_error_code ret;
+ uint32_t payload_start;
+
+ major = put_message_header(minor, ctx, VERIFY, cksum_len, &payload_start);
+ if (major != GSS_S_COMPLETE)
+ return major;
+
+ CHECK(ret, krb5_store_bytes(ctx->negoex_transcript, scheme, GUID_LENGTH));
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, CHECKSUM_HEADER_LENGTH));
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, CHECKSUM_SCHEME_RFC3961));
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, cksum_type));
+ /* ChecksumValue vector */
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, payload_start));
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, cksum_len));
+ /* Four bytes of padding to reach a multiple of 8 bytes. */
+ CHECK(ret, krb5_store_bytes(ctx->negoex_transcript, "\0\0\0\0", 4));
+ /* Payload (checksum contents) */
+ CHECK(ret, krb5_store_bytes(ctx->negoex_transcript, cksum, cksum_len));
+
+ return GSS_S_COMPLETE;
+
+fail:
+ *minor = ret;
+ return GSS_S_FAILURE;
+}
+
+/*
+ * Add an ALERT_MESSAGE containing a single ALERT_TYPE_PULSE alert with the
+ * reason ALERT_VERIFY_NO_KEY.
+ */
+OM_uint32
+_gss_negoex_add_verify_no_key_alert(OM_uint32 *minor,
+ gssspnego_ctx ctx,
+ const auth_scheme scheme)
+{
+ OM_uint32 major;
+ krb5_error_code ret;
+ uint32_t payload_start;
+
+ major = put_message_header(minor, ctx,
+ ALERT, ALERT_LENGTH + ALERT_PULSE_LENGTH,
+ &payload_start);
+ if (major != GSS_S_COMPLETE)
+ return major;
+
+ CHECK(ret, krb5_store_bytes(ctx->negoex_transcript, scheme, GUID_LENGTH));
+ /* ErrorCode */
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, 0));
+ /* Alerts vector */
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, payload_start));
+ CHECK(ret, krb5_store_uint16(ctx->negoex_transcript, 1));
+ /* Six bytes of padding to reach a multiple of 8 bytes. */
+ CHECK(ret, krb5_store_bytes(ctx->negoex_transcript, "\0\0\0\0\0\0", 6));
+ /* Payload part 1: a single ALERT element */
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, ALERT_TYPE_PULSE));
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript,
+ payload_start + ALERT_LENGTH));
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, ALERT_PULSE_LENGTH));
+ /* Payload part 2: ALERT_PULSE */
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, ALERT_PULSE_LENGTH));
+ CHECK(ret, krb5_store_uint32(ctx->negoex_transcript, ALERT_VERIFY_NO_KEY));
+
+ return GSS_S_COMPLETE;
+
+fail:
+ *minor = ret;
+ return GSS_S_FAILURE;
+}
+
+
+void
+_gss_negoex_release_auth_mech(krb5_context context,
+ struct negoex_auth_mech *mech)
+{
+ OM_uint32 tmpmin;
+
+ if (mech == NULL)
+ return;
+
+ gss_delete_sec_context(&tmpmin, &mech->mech_context, NULL);
+ gss_release_oid(&tmpmin, &mech->oid);
+ gss_release_buffer(&tmpmin, &mech->metadata);
+ if (mech->crypto)
+ krb5_crypto_destroy(context, mech->crypto);
+ if (mech->verify_crypto)
+ krb5_crypto_destroy(context, mech->verify_crypto);
+
+ free(mech);
+}
+
+void
+_gss_negoex_delete_auth_mech(gssspnego_ctx ctx,
+ struct negoex_auth_mech *mech)
+{
+ krb5_context context = _gss_mg_krb5_context();
+
+ HEIM_TAILQ_REMOVE(&ctx->negoex_mechs, mech, links);
+ _gss_negoex_release_auth_mech(context, mech);
+}
+
+/* Remove all auth mech entries except for mech from ctx->mechs. */
+void
+_gss_negoex_select_auth_mech(gssspnego_ctx ctx,
+ struct negoex_auth_mech *mech)
+{
+ krb5_context context = _gss_mg_krb5_context();
+
+ heim_assert(mech != NULL, "Invalid null NegoEx mech");
+ HEIM_TAILQ_REMOVE(&ctx->negoex_mechs, mech, links);
+ release_all_mechs(ctx, context);
+ HEIM_TAILQ_INSERT_HEAD(&ctx->negoex_mechs, mech, links);
+}
+
+OM_uint32
+_gss_negoex_add_auth_mech(OM_uint32 *minor,
+ gssspnego_ctx ctx,
+ gss_const_OID oid,
+ auth_scheme scheme)
+{
+ OM_uint32 major;
+ struct negoex_auth_mech *mech;
+
+ mech = calloc(1, sizeof(*mech));
+ if (mech == NULL) {
+ *minor = ENOMEM;
+ return GSS_S_FAILURE;
+ }
+
+ major = gss_duplicate_oid(minor, (gss_OID)oid, &mech->oid);
+ if (major != GSS_S_COMPLETE) {
+ free(mech);
+ return major;
+ }
+
+ memcpy(mech->scheme, scheme, GUID_LENGTH);
+
+ HEIM_TAILQ_INSERT_TAIL(&ctx->negoex_mechs, mech, links);
+
+ *minor = 0;
+ return GSS_S_COMPLETE;
+}
+
+struct negoex_auth_mech *
+_gss_negoex_locate_auth_scheme(gssspnego_ctx ctx,
+ const auth_scheme scheme)
+{
+ struct negoex_auth_mech *mech;
+
+ HEIM_TAILQ_FOREACH(mech, &ctx->negoex_mechs, links) {
+ if (GUID_EQ(mech->scheme, scheme))
+ return mech;
+ }
+
+ return NULL;
+}
+
+/*
+ * Prune ctx->mechs to the schemes present in schemes, and reorder them to
+ * match its order.
+ */
+void
+_gss_negoex_common_auth_schemes(gssspnego_ctx ctx,
+ const uint8_t *schemes,
+ uint16_t nschemes)
+{
+ struct negoex_mech_list list;
+ struct negoex_auth_mech *mech;
+ uint16_t i;
+ krb5_context context = _gss_mg_krb5_context();
+
+ /* Construct a new list in the order of schemes. */
+ HEIM_TAILQ_INIT(&list);
+ for (i = 0; i < nschemes; i++) {
+ mech = _gss_negoex_locate_auth_scheme(ctx, schemes + i * GUID_LENGTH);
+ if (mech == NULL)
+ continue;
+ HEIM_TAILQ_REMOVE(&ctx->negoex_mechs, mech, links);
+ HEIM_TAILQ_INSERT_TAIL(&list, mech, links);
+ }
+
+ /* Release any leftover entries and replace the context list. */
+ release_all_mechs(ctx, context);
+ HEIM_TAILQ_CONCAT(&ctx->negoex_mechs, &list, links);
+}
+
+/*
+ * Prune ctx->mechs to the schemes present in schemes, but do not change
+ * their order.
+ */
+void
+_gss_negoex_restrict_auth_schemes(gssspnego_ctx ctx,
+ const uint8_t *schemes,
+ uint16_t nschemes)
+{
+ struct negoex_auth_mech *mech, *next;
+ uint16_t i;
+ int found;
+
+ HEIM_TAILQ_FOREACH_SAFE(mech, &ctx->negoex_mechs, links, next) {
+ found = FALSE;
+ for (i = 0; i < nschemes && !found; i++) {
+ if (GUID_EQ(mech->scheme, schemes + i * GUID_LENGTH))
+ found = TRUE;
+ }
+
+ if (!found)
+ _gss_negoex_delete_auth_mech(ctx, mech);
+ }
+}
+
+/*
+ * Return the OID of the current NegoEx mechanism.
+ */
+struct negoex_auth_mech *
+_gss_negoex_negotiated_mech(gssspnego_ctx ctx)
+{
+ return HEIM_TAILQ_FIRST(&ctx->negoex_mechs);
+}
+
+/*
+ * Returns TRUE if mechanism can be negotiated by both NegoEx and SPNEGO
+ */
+
+int
+_gss_negoex_and_spnego_mech_p(gss_const_OID mech)
+{
+ OM_uint32 major, minor;
+ gss_OID_set attrs = GSS_C_NO_OID_SET;
+ int negoex_and_spnego = FALSE;
+
+ major = gss_inquire_attrs_for_mech(&minor, mech, &attrs, NULL);
+ if (major == GSS_S_COMPLETE) {
+ gss_test_oid_set_member(&minor, GSS_C_MA_NEGOEX_AND_SPNEGO,
+ attrs, &negoex_and_spnego);
+ gss_release_oid_set(&minor, &attrs);
+ }
+
+ return negoex_and_spnego;
+}
+
+int
+_gss_negoex_mech_p(gss_const_OID mech)
+{
+ OM_uint32 minor;
+ auth_scheme scheme;
+
+ return gssspi_query_mechanism_info(&minor, mech,
+ scheme) == GSS_S_COMPLETE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/spnego/spnego.asn1 b/third_party/heimdal/lib/gssapi/spnego/spnego.asn1
new file mode 100644
index 0000000..bd69a05
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/spnego/spnego.asn1
@@ -0,0 +1,66 @@
+-- $Id$
+
+SPNEGO DEFINITIONS ::=
+BEGIN
+
+MechType::= OBJECT IDENTIFIER
+
+MechTypeList ::= SEQUENCE OF MechType
+
+ContextFlags ::= BIT STRING {
+ delegFlag (0),
+ mutualFlag (1),
+ replayFlag (2),
+ sequenceFlag (3),
+ anonFlag (4),
+ confFlag (5),
+ integFlag (6)
+}
+
+NegHints ::= SEQUENCE {
+ hintName [0] GeneralString OPTIONAL,
+ hintAddress [1] OCTET STRING OPTIONAL
+}
+
+NegTokenInit2 ::= SEQUENCE {
+ mechTypes [0] MechTypeList,
+ reqFlags [1] ContextFlags OPTIONAL,
+ mechToken [2] OCTET STRING OPTIONAL,
+ negHints [3] NegHints OPTIONAL
+}
+
+NegTokenInit ::= SEQUENCE {
+ mechTypes [0] MechTypeList,
+ reqFlags [1] ContextFlags OPTIONAL,
+ mechToken [2] OCTET STRING OPTIONAL,
+ mechListMIC [3] OCTET STRING OPTIONAL,
+ ...
+}
+
+NegStateEnum ::= ENUMERATED {
+ accept-completed(0),
+ accept-incomplete(1),
+ reject(2),
+ request-mic(3)
+}
+
+-- NB: negState is not OPTIONAL in the new SPNEGO spec but
+-- Windows clients do not always send it
+NegTokenResp ::= SEQUENCE {
+ negState [0] NegStateEnum OPTIONAL,
+ supportedMech [1] MechType OPTIONAL,
+ responseToken [2] OCTET STRING OPTIONAL,
+ mechListMIC [3] OCTET STRING OPTIONAL,
+ ...
+}
+
+NegotiationToken ::= CHOICE {
+ negTokenInit[0] NegTokenInit,
+ negTokenResp[1] NegTokenResp
+}
+
+NegotiationToken2 ::= CHOICE {
+ negTokenInit[0] NegTokenInit2
+}
+
+END
diff --git a/third_party/heimdal/lib/gssapi/spnego/spnego.opt b/third_party/heimdal/lib/gssapi/spnego/spnego.opt
new file mode 100644
index 0000000..cbf2f23
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/spnego/spnego.opt
@@ -0,0 +1 @@
+--sequence=MechTypeList
diff --git a/third_party/heimdal/lib/gssapi/spnego/spnego_locl.h b/third_party/heimdal/lib/gssapi/spnego/spnego_locl.h
new file mode 100644
index 0000000..e3434f2
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/spnego/spnego_locl.h
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) 2004, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef SPNEGO_LOCL_H
+#define SPNEGO_LOCL_H
+
+#include <config.h>
+
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#include <roken.h>
+
+#ifdef HAVE_PTHREAD_H
+#include <pthread.h>
+#endif
+
+#include <krb5.h>
+#include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <ctype.h>
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+
+#include <heim_threads.h>
+#include <heimqueue.h>
+#include <asn1_err.h>
+
+#include <gssapi_mech.h>
+
+#include "spnego_asn1.h"
+#include "negoex_locl.h"
+#include "utils.h"
+#include <der.h>
+
+#include <heimbase.h>
+
+#define ALLOC(X, N) (X) = calloc((N), sizeof(*(X)))
+
+#define CHECK(ret, x) do { (ret) = (x); if (ret) goto fail; } while (0)
+
+struct gssspnego_ctx_desc;
+typedef struct gssspnego_ctx_desc *gssspnego_ctx;
+
+typedef OM_uint32
+(*gssspnego_initiator_state)(OM_uint32 * minor_status,
+ gss_const_cred_id_t cred,
+ gssspnego_ctx ctx,
+ gss_const_name_t name,
+ gss_const_OID mech_type,
+ OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_const_buffer_t input_token,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec);
+
+struct gssspnego_ctx_desc {
+ gss_buffer_desc NegTokenInit_mech_types;
+ gss_OID preferred_mech_type;
+ gss_OID selected_mech_type;
+ gss_OID negotiated_mech_type;
+ gss_ctx_id_t negotiated_ctx_id;
+ OM_uint32 mech_flags;
+ OM_uint32 mech_time_rec;
+ gss_name_t mech_src_name;
+ struct spnego_flags {
+ unsigned int open : 1;
+ unsigned int local : 1;
+ unsigned int require_mic : 1;
+ unsigned int peer_require_mic : 1;
+ unsigned int sent_mic : 1;
+ unsigned int verified_mic : 1;
+ unsigned int safe_omit : 1;
+ unsigned int maybe_open : 1;
+ unsigned int seen_supported_mech : 1;
+ } flags;
+ HEIMDAL_MUTEX ctx_id_mutex;
+
+ gss_name_t target_name;
+ gssspnego_initiator_state initiator_state;
+
+ uint8_t negoex_step;
+ krb5_storage *negoex_transcript;
+ uint32_t negoex_seqnum;
+ conversation_id negoex_conv_id;
+ HEIM_TAILQ_HEAD(negoex_mech_list, negoex_auth_mech) negoex_mechs;
+};
+
+extern gss_OID_desc _gss_spnego_mskrb_mechanism_oid_desc;
+
+struct gssspnego_optimistic_ctx {
+ gssspnego_ctx spnegoctx;
+ OM_uint32 req_flags;
+ gss_name_t target_name;
+ OM_uint32 time_req;
+ gss_channel_bindings_t input_chan_bindings;
+ /* out */
+ gss_OID preferred_mech_type;
+ gss_OID negotiated_mech_type;
+ gss_buffer_desc optimistic_token;
+ OM_uint32 optimistic_flags, optimistic_time_rec;
+ gss_ctx_id_t gssctx;
+ int complete;
+ auth_scheme scheme;
+};
+
+#include "spnego-private.h"
+
+static inline int
+gssspnego_ctx_complete_p(gssspnego_ctx ctx)
+{
+ return ctx->flags.open &&
+ (ctx->flags.safe_omit || (ctx->flags.sent_mic && ctx->flags.verified_mic));
+}
+
+#endif /* SPNEGO_LOCL_H */
diff --git a/third_party/heimdal/lib/gssapi/test_acquire_cred.c b/third_party/heimdal/lib/gssapi/test_acquire_cred.c
new file mode 100644
index 0000000..ef49311
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/test_acquire_cred.c
@@ -0,0 +1,344 @@
+/*
+ * Copyright (c) 2003-2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <roken.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
+#include <err.h>
+#include <getarg.h>
+
+#include "test_common.h"
+
+static void
+print_time(OM_uint32 time_rec)
+{
+ if (time_rec == GSS_C_INDEFINITE) {
+ printf("cred never expire\n");
+ } else {
+ time_t t = time_rec + time(NULL);
+ printf("expiration time: %s", ctime(&t));
+ }
+}
+
+#if 0
+
+static void
+test_add(gss_cred_id_t cred_handle)
+{
+ OM_uint32 major_status, minor_status;
+ gss_cred_id_t copy_cred;
+ OM_uint32 time_rec;
+
+ major_status = gss_add_cred (&minor_status,
+ cred_handle,
+ GSS_C_NO_NAME,
+ GSS_KRB5_MECHANISM,
+ GSS_C_INITIATE,
+ 0,
+ 0,
+ &copy_cred,
+ NULL,
+ &time_rec,
+ NULL);
+
+ if (GSS_ERROR(major_status))
+ errx(1, "add_cred failed");
+
+ print_time(time_rec);
+
+ major_status = gss_release_cred(&minor_status,
+ &copy_cred);
+ if (GSS_ERROR(major_status))
+ errx(1, "release_cred failed");
+}
+
+static void
+copy_cred(void)
+{
+ OM_uint32 major_status, minor_status;
+ gss_cred_id_t cred_handle;
+ OM_uint32 time_rec;
+
+ major_status = gss_acquire_cred(&minor_status,
+ GSS_C_NO_NAME,
+ 0,
+ NULL,
+ GSS_C_INITIATE,
+ &cred_handle,
+ NULL,
+ &time_rec);
+ if (GSS_ERROR(major_status))
+ errx(1, "acquire_cred failed");
+
+ print_time(time_rec);
+
+ test_add(cred_handle);
+ test_add(cred_handle);
+ test_add(cred_handle);
+
+ major_status = gss_release_cred(&minor_status,
+ &cred_handle);
+ if (GSS_ERROR(major_status))
+ errx(1, "release_cred failed");
+}
+#endif
+
+static gss_cred_id_t
+acquire_cred_service(const char *service,
+ gss_OID nametype,
+ gss_OID_set oidset,
+ gss_cred_usage_t usage,
+ gss_const_key_value_set_t cred_store)
+{
+ OM_uint32 major_status, minor_status;
+ gss_cred_id_t cred_handle;
+ OM_uint32 time_rec;
+ gss_buffer_desc name_buffer;
+ gss_name_t name = GSS_C_NO_NAME;
+
+ if (service) {
+ name_buffer.value = rk_UNCONST(service);
+ name_buffer.length = strlen(service);
+
+ major_status = gss_import_name(&minor_status,
+ &name_buffer,
+ nametype,
+ &name);
+ if (GSS_ERROR(major_status))
+ errx(1, "import_name failed");
+ }
+
+ major_status = gss_acquire_cred_from(&minor_status,
+ name,
+ 0,
+ oidset,
+ usage,
+ cred_store,
+ &cred_handle,
+ NULL,
+ &time_rec);
+ if (GSS_ERROR(major_status)) {
+ warnx("acquire_cred failed: %s",
+ gssapi_err(major_status, minor_status, GSS_C_NO_OID));
+ } else {
+ print_time(time_rec);
+ gss_release_cred(&minor_status, &cred_handle);
+ }
+
+ if (name != GSS_C_NO_NAME)
+ gss_release_name(&minor_status, &name);
+
+ if (GSS_ERROR(major_status))
+ exit(1);
+
+ return cred_handle;
+}
+
+static int version_flag = 0;
+static int help_flag = 0;
+static int kerberos_flag = 0;
+static int enctype = 0;
+static char *acquire_name;
+static char *acquire_type;
+static char *target_name;
+static char *name_type;
+static char *ccache;
+static char *client_keytab;
+static int num_loops = 1;
+
+static struct getargs args[] = {
+ {"acquire-name", 0, arg_string, &acquire_name, "name", NULL },
+ {"acquire-type", 0, arg_string, &acquire_type, "type", NULL },
+ {"enctype", 0, arg_integer, &enctype, "enctype-num", NULL },
+ {"loops", 0, arg_integer, &num_loops, "num-loops", NULL },
+ {"kerberos", 0, arg_flag, &kerberos_flag, NULL, NULL },
+ {"target-name", 0, arg_string, &target_name, "name", NULL },
+ {"ccache", 0, arg_string, &ccache, "name", NULL },
+ {"client-keytab", 0,arg_string, &client_keytab, "name", NULL },
+ {"name-type", 0, arg_string, &name_type, "type", NULL },
+ {"version", 0, arg_flag, &version_flag, "print version", NULL },
+ {"help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ gss_OID_set oidset = GSS_C_NULL_OID_SET;
+ gss_OID mechoid = GSS_C_NO_OID;
+ OM_uint32 maj_stat, min_stat;
+ gss_cred_id_t cred;
+ gss_name_t target = GSS_C_NO_NAME;
+ int i, optidx = 0;
+ gss_cred_usage_t cred_usage = GSS_C_BOTH;
+ gss_OID type = GSS_C_NT_HOSTBASED_SERVICE;
+ gss_key_value_set_desc store, *storep = GSS_C_NO_CRED_STORE;
+ gss_key_value_element_desc elements[2];
+
+ store.count = 0;
+ store.elements = elements;
+
+ setprogname(argv[0]);
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (argc != 0)
+ usage(1);
+
+ if (acquire_type) {
+ if (strcasecmp(acquire_type, "both") == 0)
+ cred_usage = GSS_C_BOTH;
+ else if (strcasecmp(acquire_type, "accept") == 0)
+ cred_usage = GSS_C_ACCEPT;
+ else if (strcasecmp(acquire_type, "initiate") == 0)
+ cred_usage = GSS_C_INITIATE;
+ else
+ errx(1, "unknown type %s", acquire_type);
+ }
+
+ if (name_type) {
+ if (strcasecmp("hostbased-service", name_type) == 0)
+ type = GSS_C_NT_HOSTBASED_SERVICE;
+ else if (strcasecmp("user-name", name_type) == 0)
+ type = GSS_C_NT_USER_NAME;
+ else
+ errx(1, "unknown name type %s", name_type);
+ }
+
+ if (ccache) {
+ store.elements[store.count].key = "ccache";
+ store.elements[store.count].value = ccache;
+ store.count++;
+ }
+ if (client_keytab) {
+ store.elements[store.count].key = "client_keytab";
+ store.elements[store.count].value = client_keytab;
+ store.count++;
+ }
+
+ if (store.count)
+ storep = &store;
+
+ if (kerberos_flag) {
+ mechoid = GSS_KRB5_MECHANISM;
+
+ maj_stat = gss_create_empty_oid_set(&min_stat, &oidset);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_create_empty_oid_set: %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+
+ maj_stat = gss_add_oid_set_member(&min_stat, GSS_KRB5_MECHANISM, &oidset);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_add_oid_set_member: %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+ }
+
+ if (target_name) {
+ gss_buffer_desc name;
+
+ name.value = target_name;
+ name.length = strlen(target_name);
+ maj_stat = gss_import_name(&min_stat, &name,
+ GSS_C_NT_HOSTBASED_SERVICE, &target);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_import_name: %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+ }
+
+ for (i = 0; i < num_loops; i++) {
+
+ cred = acquire_cred_service(acquire_name, type, oidset, cred_usage, storep);
+
+ if (enctype) {
+ int32_t enctypelist = enctype;
+
+ maj_stat = gss_krb5_set_allowable_enctypes(&min_stat, cred,
+ 1, &enctypelist);
+ if (maj_stat)
+ errx(1, "gss_krb5_set_allowable_enctypes: %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+ }
+
+ if (target) {
+ gss_ctx_id_t context = GSS_C_NO_CONTEXT;
+ gss_buffer_desc out;
+
+ out.length = 0;
+ out.value = NULL;
+
+ maj_stat = gss_init_sec_context(&min_stat,
+ cred, &context,
+ target, mechoid,
+ GSS_C_MUTUAL_FLAG, 0, NULL,
+ GSS_C_NO_BUFFER, NULL,
+ &out, NULL, NULL);
+ if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
+ errx(1, "init_sec_context failed: %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+
+ gss_release_buffer(&min_stat, &out);
+ gss_delete_sec_context(&min_stat, &context, NULL);
+ }
+ gss_release_cred(&min_stat, &cred);
+ }
+ gss_release_oid_set(&min_stat, &oidset);
+ gss_release_name(&min_stat, &target);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/gssapi/test_add_store_cred.c b/third_party/heimdal/lib/gssapi/test_add_store_cred.c
new file mode 100644
index 0000000..03c3dc9
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/test_add_store_cred.c
@@ -0,0 +1,219 @@
+/*
+ * Copyright (c) 2015 Cryptonector LLC.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. The name Cryptonector LLC may not be used to endorse or promote
+ * products derived from this software without specific prior written
+ * permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <roken.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <gssapi.h>
+#include <err.h>
+#include <getarg.h>
+
+static void
+print_gss_err(OM_uint32 stat, int status_type, gss_OID mech)
+{
+ gss_buffer_desc str;
+ OM_uint32 maj;
+ OM_uint32 min;
+ OM_uint32 msg_ctx = 0;
+ int first = 1;
+
+ do {
+ maj = gss_display_status(&min, stat, status_type, mech, &msg_ctx,
+ &str);
+ if (maj != GSS_S_COMPLETE) {
+ fprintf(stderr, "Error displaying GSS %s error (%lu): %lu, %lu",
+ status_type == GSS_C_GSS_CODE ? "major" : "minor",
+ (unsigned long)stat, (unsigned long)maj,
+ (unsigned long)min);
+ return;
+ }
+ if (first) {
+ fprintf(stderr, "GSS %s error: %.*s\n",
+ status_type == GSS_C_GSS_CODE ? "major" : "minor",
+ (int)str.length, (char *)str.value);
+ first = 0;
+ } else {
+ fprintf(stderr, "\t%.*s\n", (int)str.length, (char *)str.value);
+ }
+ gss_release_buffer(&min, &str);
+ } while (msg_ctx != 0);
+}
+
+static void
+print_gss_errs(OM_uint32 major, OM_uint32 minor, gss_OID mech)
+{
+ print_gss_err(major, GSS_C_GSS_CODE, GSS_C_NO_OID);
+ print_gss_err(major, GSS_C_MECH_CODE, mech);
+}
+
+static void
+gss_err(int exitval, OM_uint32 major, OM_uint32 minor, gss_OID mech,
+ const char *fmt, ...)
+{
+ va_list args;
+
+ va_start(args, fmt);
+ vwarnx(fmt, args);
+ va_end(args);
+ print_gss_errs(major, minor, mech);
+ exit(exitval);
+}
+
+static int version_flag = 0;
+static int help_flag = 0;
+static int env_flag = 0;
+static int def_flag = 0;
+static int overwrite_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag, "print version", NULL },
+ {"help", 0, arg_flag, &help_flag, NULL, NULL },
+ {"env", 'e', arg_flag, &env_flag,
+ "output env settings", NULL },
+ {"default", 0, arg_flag, &def_flag,
+ "switch credential store default principal", NULL },
+ {"overwrite", 0, arg_flag, &overwrite_flag,
+ "overwrite matching credential", NULL },
+};
+
+static void
+usage(int ret)
+{
+ arg_printusage(args, sizeof(args)/sizeof(*args),
+ NULL, "from_ccache to_ccache");
+ exit(ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ OM_uint32 major, minor;
+ gss_cred_id_t from_cred = GSS_C_NO_CREDENTIAL;
+ gss_cred_id_t to_cred = GSS_C_NO_CREDENTIAL;
+ gss_cred_id_t cred = GSS_C_NO_CREDENTIAL;
+ gss_key_value_element_desc from_elements, to_elements;
+ gss_key_value_set_desc from, to;
+ gss_buffer_set_t env = GSS_C_NO_BUFFER_SET;
+ OM_uint32 store_flags = 0;
+ int optidx = 0;
+
+ setprogname(argv[0]);
+ if (getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if (version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ if (def_flag)
+ store_flags |= GSS_C_STORE_CRED_DEFAULT;
+ if (overwrite_flag)
+ store_flags |= GSS_C_STORE_CRED_OVERWRITE;
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (argc < 2)
+ errx(1, "required arguments missing");
+ if (argc > 2)
+ errx(1, "too many arguments");
+
+ from_elements.key = "ccache";
+ from_elements.value = argv[0];
+ from.count = 1;
+ from.elements = &from_elements;
+
+ to_elements.key = "ccache";
+ to_elements.value = argv[1];
+ to.count = 1;
+ to.elements = &to_elements;
+
+ major = gss_add_cred_from(&minor, GSS_C_NO_CREDENTIAL, GSS_C_NO_NAME,
+ GSS_KRB5_MECHANISM, GSS_C_INITIATE,
+ GSS_C_INDEFINITE, GSS_C_INDEFINITE,
+ &from, &from_cred, NULL, NULL, NULL);
+ if (major != GSS_S_COMPLETE)
+ gss_err(1, major, minor, GSS_KRB5_MECHANISM,
+ "failed to acquire creds from %s", argv[0]);
+
+ major = gss_store_cred_into2(&minor, from_cred, GSS_C_INITIATE,
+ GSS_KRB5_MECHANISM, store_flags, &to, NULL,
+ NULL, env_flag ? &env : NULL);
+ if (major != GSS_S_COMPLETE)
+ gss_err(1, major, minor, GSS_KRB5_MECHANISM,
+ "failed to store creds into %s", argv[1]);
+
+ if (env_flag) {
+ size_t i;
+ int got_krb5ccname = 0;
+
+ if (env == GSS_C_NO_BUFFER_SET)
+ warnx("No environment settings");
+
+ for (i = 0; env != GSS_C_NO_BUFFER_SET && i < env->count; i++) {
+ got_krb5ccname = got_krb5ccname ||
+ (env->elements[i].length > sizeof("KRB5CCNAME=") &&
+ strncmp((const char *)env->elements[i].value, "KRB5CCNAME=",
+ sizeof("KRB5CCNAME=") - 1) == 0);
+ printf("%.*s\n", (int)env->elements[i].length,
+ (const char *)env->elements[i].value);
+ }
+ (void) gss_release_buffer_set(&minor, &env);
+
+ if (!got_krb5ccname)
+ errx(1, "KRB5CCNAME environment variable not set by "
+ "gss_store_cred_into2()");
+ }
+
+ (void) gss_release_cred(&minor, &from_cred);
+ (void) gss_release_cred(&minor, &to_cred);
+
+ major = gss_add_cred(&minor, GSS_C_NO_CREDENTIAL, GSS_C_NO_NAME,
+ GSS_KRB5_MECHANISM, GSS_C_INITIATE, GSS_C_INDEFINITE,
+ GSS_C_INDEFINITE, &cred, NULL, NULL, NULL);
+ if (major != GSS_S_COMPLETE)
+ gss_err(1, major, minor, GSS_KRB5_MECHANISM,
+ "failed to acquire creds from %s", argv[1]);
+ (void) gss_release_cred(&minor, &cred);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/gssapi/test_common.c b/third_party/heimdal/lib/gssapi/test_common.c
new file mode 100644
index 0000000..ebdcd71
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/test_common.c
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "krb5/gsskrb5_locl.h"
+#include <err.h>
+#include "test_common.h"
+
+char *
+gssapi_err(OM_uint32 maj_stat, OM_uint32 min_stat, gss_OID mech)
+{
+ OM_uint32 disp_min_stat;
+ gss_buffer_desc maj_error_message;
+ gss_buffer_desc min_error_message;
+ OM_uint32 msg_ctx = 0;
+
+ char *ret = NULL;
+
+ maj_error_message.length = 0;
+ maj_error_message.value = NULL;
+ min_error_message.length = 0;
+ min_error_message.value = NULL;
+
+ (void) gss_display_status(&disp_min_stat, maj_stat, GSS_C_GSS_CODE,
+ mech, &msg_ctx, &maj_error_message);
+ (void) gss_display_status(&disp_min_stat, min_stat, GSS_C_MECH_CODE,
+ mech, &msg_ctx, &min_error_message);
+ if (asprintf(&ret, "gss-code: %lu %.*s -- mech-code: %lu %.*s",
+ (unsigned long)maj_stat,
+ (int)maj_error_message.length,
+ (char *)maj_error_message.value,
+ (unsigned long)min_stat,
+ (int)min_error_message.length,
+ (char *)min_error_message.value) < 0 || ret == NULL)
+ errx(1, "malloc");
+
+ gss_release_buffer(&disp_min_stat, &maj_error_message);
+ gss_release_buffer(&disp_min_stat, &min_error_message);
+
+ return ret;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/test_common.h b/third_party/heimdal/lib/gssapi/test_common.h
new file mode 100644
index 0000000..fda2949
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/test_common.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+char * gssapi_err(OM_uint32, OM_uint32, gss_OID);
diff --git a/third_party/heimdal/lib/gssapi/test_context.c b/third_party/heimdal/lib/gssapi/test_context.c
new file mode 100644
index 0000000..7446d15
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/test_context.c
@@ -0,0 +1,1610 @@
+/*
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "krb5/gsskrb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+#include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
+#include <gssapi_ntlm.h>
+#include "test_common.h"
+
+#ifdef NOTYET
+/*
+ * export/import of sec contexts on the initiator side
+ * don't work properly, yet.
+ */
+#define DO_IMPORT_EXPORT_OF_CLIENT_CONTEXT 1
+#endif
+
+static char *type_string;
+static char *mech_string;
+static char *mechs_string;
+static char *ret_mech_string;
+static char *localname_string;
+static char *client_name;
+static char *client_password;
+static char *localname_string;
+static char *on_behalf_of_string;
+static int dns_canon_flag = -1;
+static int mutual_auth_flag = 0;
+static int dce_style_flag = 0;
+static int wrapunwrap_flag = 0;
+static int iov_flag = 0;
+static int aead_flag = 0;
+static int getverifymic_flag = 0;
+static int deleg_flag = 0;
+static int anon_flag = 0;
+static int policy_deleg_flag = 0;
+static int server_no_deleg_flag = 0;
+static int ei_cred_flag = 0;
+static int ei_ctx_flag = 0;
+static char *client_ccache = NULL;
+static char *client_keytab = NULL;
+static char *gsskrb5_acceptor_identity = NULL;
+static char *session_enctype_string = NULL;
+static int client_time_offset = 0;
+static int server_time_offset = 0;
+static int max_loops = 0;
+static char *limit_enctype_string = NULL;
+static int token_split = 0;
+static int version_flag = 0;
+static int verbose_flag = 0;
+static int help_flag = 0;
+static char *i_channel_bindings = NULL;
+static char *a_channel_bindings = NULL;
+
+static krb5_context context;
+static krb5_enctype limit_enctype = 0;
+
+static gss_OID
+string_to_oid(const char *name)
+{
+ gss_OID oid = gss_name_to_oid(name);
+
+ if (oid == GSS_C_NO_OID)
+ errx(1, "name '%s' not known", name);
+
+ return oid;
+}
+
+static void
+string_to_oids(gss_OID_set *oidsetp, char *names)
+{
+ OM_uint32 maj_stat, min_stat;
+ char *name;
+ char *s;
+
+ if (names[0] == '\0') {
+ *oidsetp = GSS_C_NO_OID_SET;
+ return;
+ }
+
+ if (strcasecmp(names, "all") == 0) {
+ maj_stat = gss_indicate_mechs(&min_stat, oidsetp);
+ if (GSS_ERROR(maj_stat))
+ errx(1, "gss_indicate_mechs: %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+ } else {
+ maj_stat = gss_create_empty_oid_set(&min_stat, oidsetp);
+ if (GSS_ERROR(maj_stat))
+ errx(1, "gss_create_empty_oid_set: %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+
+ for (name = strtok_r(names, ", ", &s);
+ name != NULL;
+ name = strtok_r(NULL, ", ", &s)) {
+ gss_OID oid = string_to_oid(name);
+
+ maj_stat = gss_add_oid_set_member(&min_stat, oid, oidsetp);
+ if (GSS_ERROR(maj_stat))
+ errx(1, "gss_add_oid_set_member: %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+ }
+ }
+}
+
+static void
+show_pac_client_info(gss_name_t n)
+{
+ gss_buffer_desc dv = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc v = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc a;
+ OM_uint32 maj, min;
+ int authenticated, complete, more, name_is_MN, found;
+ gss_OID MN_mech;
+ gss_buffer_set_t attrs = GSS_C_NO_BUFFER_SET;
+ size_t i;
+
+ krb5_error_code ret;
+ krb5_storage *sp = NULL;
+ uint16_t len = 0, *s;
+ uint64_t tmp;
+ char *logon_string = NULL;
+
+ maj = gss_inquire_name(&min, n, &name_is_MN, &MN_mech, &attrs);
+ if (maj != GSS_S_COMPLETE)
+ errx(1, "gss_inquire_name: %s",
+ gssapi_err(maj, min, GSS_KRB5_MECHANISM));
+
+ a.value = "urn:mspac:client-info";
+ a.length = sizeof("urn:mspac:client-info") - 1;
+
+ for (found = 0, i = 0; i < attrs->count; i++) {
+ gss_buffer_t attr = &attrs->elements[i];
+
+ if (attr->length == a.length &&
+ memcmp(attr->value, a.value, a.length) == 0) {
+ found++;
+ break;
+ }
+ }
+
+ gss_release_buffer_set(&min, &attrs);
+
+ if (!found)
+ errx(1, "gss_inquire_name: attribute %.*s not enumerated",
+ (int)a.length, (char *)a.value);
+
+ more = 0;
+ maj = gss_get_name_attribute(&min, n, &a, &authenticated, &complete, &v,
+ &dv, &more);
+ if (maj != GSS_S_COMPLETE)
+ errx(1, "gss_get_name_attribute: %s",
+ gssapi_err(maj, min, GSS_KRB5_MECHANISM));
+
+
+ sp = krb5_storage_from_readonly_mem(v.value, v.length);
+ if (sp == NULL)
+ errx(1, "show_pac_client_info: out of memory");
+
+ krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
+
+ ret = krb5_ret_uint64(sp, &tmp); /* skip over time */
+ if (ret == 0)
+ ret = krb5_ret_uint16(sp, &len);
+ if (ret || len == 0)
+ errx(1, "show_pac_client_info: invalid PAC logon info length");
+
+ s = malloc(len);
+ ret = krb5_storage_read(sp, s, len);
+ if (ret != len)
+ errx(1, "show_pac_client_info:, failed to read PAC logon name");
+
+ krb5_storage_free(sp);
+
+ {
+ size_t ucs2len = len / 2;
+ uint16_t *ucs2;
+ size_t u8len;
+ unsigned int flags = WIND_RW_LE;
+
+ ucs2 = malloc(sizeof(ucs2[0]) * ucs2len);
+ if (ucs2 == NULL)
+ errx(1, "show_pac_client_info: out of memory");
+
+ ret = wind_ucs2read(s, len, &flags, ucs2, &ucs2len);
+ free(s);
+ if (ret)
+ errx(1, "failed to convert string to UCS-2");
+
+ ret = wind_ucs2utf8_length(ucs2, ucs2len, &u8len);
+ if (ret)
+ errx(1, "failed to count length of UCS-2 string");
+
+ u8len += 1; /* Add space for NUL */
+ logon_string = malloc(u8len);
+ if (logon_string == NULL)
+ errx(1, "show_pac_client_info: out of memory");
+
+ ret = wind_ucs2utf8(ucs2, ucs2len, logon_string, &u8len);
+ free(ucs2);
+ if (ret)
+ errx(1, "failed to convert to UTF-8");
+ }
+
+ printf("logon name: %s\n", logon_string);
+ free(logon_string);
+
+ gss_release_buffer(&min, &dv);
+ gss_release_buffer(&min, &v);
+}
+
+static void
+loop(gss_OID mechoid,
+ gss_OID nameoid, const char *target,
+ gss_cred_id_t init_cred,
+ gss_ctx_id_t *sctx, gss_ctx_id_t *cctx,
+ gss_OID *actual_mech,
+ gss_cred_id_t *deleg_cred)
+{
+ int server_done = 0, client_done = 0;
+ int num_loops = 0;
+ OM_uint32 maj_stat, min_stat;
+ gss_name_t gss_target_name, src_name = GSS_C_NO_NAME;
+ gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
+#ifdef DO_IMPORT_EXPORT_OF_CLIENT_CONTEXT
+ gss_buffer_desc cctx_tok = GSS_C_EMPTY_BUFFER;
+#endif
+ gss_buffer_desc sctx_tok = GSS_C_EMPTY_BUFFER;
+ OM_uint32 flags = 0, ret_cflags = 0, ret_sflags = 0;
+ gss_OID actual_mech_client = GSS_C_NO_OID;
+ gss_OID actual_mech_server = GSS_C_NO_OID;
+ struct gss_channel_bindings_struct i_channel_bindings_data;
+ struct gss_channel_bindings_struct a_channel_bindings_data;
+ gss_channel_bindings_t i_channel_bindings_p = GSS_C_NO_CHANNEL_BINDINGS;
+ gss_channel_bindings_t a_channel_bindings_p = GSS_C_NO_CHANNEL_BINDINGS;
+ size_t offset = 0;
+
+ memset(&i_channel_bindings_data, 0, sizeof(i_channel_bindings_data));
+ memset(&a_channel_bindings_data, 0, sizeof(a_channel_bindings_data));
+
+ *actual_mech = GSS_C_NO_OID;
+
+ flags |= GSS_C_REPLAY_FLAG;
+ flags |= GSS_C_INTEG_FLAG;
+ flags |= GSS_C_CONF_FLAG;
+
+ if (mutual_auth_flag)
+ flags |= GSS_C_MUTUAL_FLAG;
+ if (anon_flag)
+ flags |= GSS_C_ANON_FLAG;
+ if (dce_style_flag)
+ flags |= GSS_C_DCE_STYLE;
+ if (deleg_flag)
+ flags |= GSS_C_DELEG_FLAG;
+ if (policy_deleg_flag)
+ flags |= GSS_C_DELEG_POLICY_FLAG;
+
+ input_token.value = rk_UNCONST(target);
+ input_token.length = strlen(target);
+
+ maj_stat = gss_import_name(&min_stat,
+ &input_token,
+ nameoid,
+ &gss_target_name);
+ if (GSS_ERROR(maj_stat))
+ err(1, "import name creds failed with: %d", maj_stat);
+
+ if (on_behalf_of_string) {
+ AuthorizationDataElement e;
+ gss_buffer_desc attr, value;
+ int32_t kret;
+ size_t sz;
+
+ memset(&e, 0, sizeof(e));
+ e.ad_type = KRB5_AUTHDATA_ON_BEHALF_OF;
+ e.ad_data.length = strlen(on_behalf_of_string);
+ e.ad_data.data = on_behalf_of_string;
+ ASN1_MALLOC_ENCODE(AuthorizationDataElement, value.value, value.length,
+ &e, &sz, kret);
+ if (kret)
+ errx(1, "Could not encode AD-ON-BEHALF-OF AuthorizationDataElement");
+ attr.value =
+ GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "authenticator-authz-data";
+ attr.length =
+ sizeof(GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "authenticator-authz-data") - 1;
+ maj_stat = gss_set_name_attribute(&min_stat, gss_target_name, 1, &attr,
+ &value);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_set_name_attribute() failed with: %s",
+ gssapi_err(maj_stat, min_stat, GSS_KRB5_MECHANISM));
+ free(value.value);
+ }
+
+ input_token.length = 0;
+ input_token.value = NULL;
+
+ if (i_channel_bindings) {
+ i_channel_bindings_data.application_data.length = strlen(i_channel_bindings);
+ i_channel_bindings_data.application_data.value = i_channel_bindings;
+ i_channel_bindings_p = &i_channel_bindings_data;
+ }
+ if (a_channel_bindings) {
+ a_channel_bindings_data.application_data.length = strlen(a_channel_bindings);
+ a_channel_bindings_data.application_data.value = a_channel_bindings;
+ a_channel_bindings_p = &a_channel_bindings_data;
+ }
+
+ /*
+ * This loop simulates both the initiator and acceptor sides of
+ * a GSS conversation. We also simulate tokens that are broken
+ * into pieces before handed to gss_accept_sec_context(). Each
+ * iteration of the loop optionally calls gss_init_sec_context()
+ * then optionally calls gss_accept_sec_context().
+ */
+
+ while (!server_done || !client_done) {
+ num_loops++;
+ if (verbose_flag)
+ printf("loop #%d: input_token.length=%zu client_done=%d\n",
+ num_loops, input_token.length, client_done);
+
+ /*
+ * First, we need to call gss_import_sec_context() if we are
+ * running through the loop the first time, or if we have been
+ * given a token (input_token) by gss_accept_sec_context().
+ * We aren't going to be called every time because when we are
+ * using split tokens, we may need to call gss_accept_sec_context()
+ * multiple times because it receives an entire token.
+ */
+ if ((num_loops == 1 || input_token.length > 0) && !client_done) {
+ gsskrb5_set_time_offset(client_time_offset);
+#ifdef DO_IMPORT_EXPORT_OF_CLIENT_CONTEXT
+ if (ei_ctx_flag && cctx_tok.length > 0) {
+ maj_stat = gss_import_sec_context(&min_stat, &cctx_tok, cctx);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "import client context failed: %s",
+ gssapi_err(maj_stat, min_stat, NULL));
+ gss_release_buffer(&min_stat, &cctx_tok);
+ }
+#endif
+
+ maj_stat = gss_init_sec_context(&min_stat, init_cred, cctx,
+ gss_target_name, mechoid,
+ flags, 0, i_channel_bindings_p,
+ &input_token, &actual_mech_client,
+ &output_token, &ret_cflags, NULL);
+ if (GSS_ERROR(maj_stat))
+ errx(1, "init_sec_context: %s",
+ gssapi_err(maj_stat, min_stat, mechoid));
+ client_done = !(maj_stat & GSS_S_CONTINUE_NEEDED);
+
+ gss_release_buffer(&min_stat, &input_token);
+ input_token.length = 0;
+ input_token.value = NULL;
+
+#if DO_IMPORT_EXPORT_OF_CLIENT_CONTEXT
+ if (!client_done && ei_ctx_flag) {
+ maj_stat = gss_export_sec_context(&min_stat, cctx, &cctx_tok);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "export server context failed: %s",
+ gssapi_err(maj_stat, min_stat, NULL));
+ if (*cctx != GSS_C_NO_CONTEXT)
+ errx(1, "export client context did not release it");
+ }
+#endif
+
+ if (verbose_flag)
+ printf("loop #%d: output_token.length=%zu\n", num_loops,
+ output_token.length);
+
+ offset = 0;
+ }
+
+ /*
+ * We now call gss_accept_sec_context(). To support split
+ * tokens, we keep track of the offset into the token that
+ * we have used and keep handing in chunks until we're done.
+ */
+
+ if (offset < output_token.length && !server_done) {
+ gss_buffer_desc tmp;
+
+ gsskrb5_get_time_offset(&client_time_offset);
+ gsskrb5_set_time_offset(server_time_offset);
+
+ if (output_token.length && ((uint8_t *)output_token.value)[0] == 0x60) {
+ tmp.length = output_token.length - offset;
+ if (token_split && tmp.length > token_split)
+ tmp.length = token_split;
+ tmp.value = (char *)output_token.value + offset;
+ } else
+ tmp = output_token;
+
+ if (verbose_flag)
+ printf("loop #%d: accept offset=%zu len=%zu\n", num_loops,
+ offset, tmp.length);
+
+ if (ei_ctx_flag && sctx_tok.length > 0) {
+ maj_stat = gss_import_sec_context(&min_stat, &sctx_tok, sctx);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "import server context failed: %s",
+ gssapi_err(maj_stat, min_stat, NULL));
+ gss_release_buffer(&min_stat, &sctx_tok);
+ }
+
+ maj_stat = gss_accept_sec_context(&min_stat, sctx,
+ GSS_C_NO_CREDENTIAL, &tmp,
+ a_channel_bindings_p, &src_name,
+ &actual_mech_server,
+ &input_token, &ret_sflags,
+ NULL, deleg_cred);
+ if (GSS_ERROR(maj_stat))
+ errx(1, "accept_sec_context: %s",
+ gssapi_err(maj_stat, min_stat, actual_mech_server));
+ offset += tmp.length;
+ if (maj_stat & GSS_S_CONTINUE_NEEDED)
+ gss_release_name(&min_stat, &src_name);
+ else
+ server_done = 1;
+
+ if (ei_ctx_flag && !server_done) {
+ maj_stat = gss_export_sec_context(&min_stat, sctx, &sctx_tok);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "export server context failed: %s",
+ gssapi_err(maj_stat, min_stat, NULL));
+ if (*sctx != GSS_C_NO_CONTEXT)
+ errx(1, "export server context did not release it");
+ }
+
+ gsskrb5_get_time_offset(&server_time_offset);
+
+ if (output_token.length == offset)
+ gss_release_buffer(&min_stat, &output_token);
+ }
+ if (verbose_flag)
+ printf("loop #%d: end\n", num_loops);
+ }
+ if (output_token.length != 0)
+ gss_release_buffer(&min_stat, &output_token);
+ if (input_token.length != 0)
+ gss_release_buffer(&min_stat, &input_token);
+ gss_release_name(&min_stat, &gss_target_name);
+
+ if (deleg_flag || policy_deleg_flag) {
+ if (server_no_deleg_flag) {
+ if (*deleg_cred != GSS_C_NO_CREDENTIAL)
+ errx(1, "got delegated cred but didn't expect one");
+ } else if (*deleg_cred == GSS_C_NO_CREDENTIAL)
+ errx(1, "asked for delegarated cred but did get one");
+ } else if (*deleg_cred != GSS_C_NO_CREDENTIAL)
+ errx(1, "got deleg_cred cred but didn't ask");
+
+ if (gss_oid_equal(actual_mech_server, actual_mech_client) == 0)
+ errx(1, "mech mismatch");
+ *actual_mech = actual_mech_server;
+
+ if (on_behalf_of_string) {
+ gss_buffer_desc attr, value;
+
+ attr.value =
+ GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "authz-data#580";
+ attr.length =
+ sizeof(GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "authz-data#580") - 1;
+ maj_stat = gss_get_name_attribute(&min_stat, src_name, &attr, NULL,
+ NULL, &value, NULL, NULL);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_get_name_attribute(authz-data#580) failed with %s",
+ gssapi_err(maj_stat, min_stat, GSS_KRB5_MECHANISM));
+
+ if (value.length != strlen(on_behalf_of_string) ||
+ strncmp(value.value, on_behalf_of_string,
+ strlen(on_behalf_of_string)) != 0)
+ errx(1, "AD-ON-BEHALF-OF did not match");
+ (void) gss_release_buffer(&min_stat, &value);
+ }
+ if (localname_string) {
+ gss_buffer_desc lname;
+
+ maj_stat = gss_localname(&min_stat, src_name, GSS_C_NO_OID, &lname);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "localname: %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+ if (verbose_flag)
+ printf("localname: %.*s\n", (int)lname.length,
+ (char *)lname.value);
+ if (lname.length != strlen(localname_string) ||
+ strncmp(localname_string, lname.value, lname.length) != 0)
+ errx(1, "localname: expected \"%s\", got \"%.*s\" (1)",
+ localname_string, (int)lname.length, (char *)lname.value);
+ gss_release_buffer(&min_stat, &lname);
+ maj_stat = gss_localname(&min_stat, src_name, actual_mech_server,
+ &lname);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "localname: %s",
+ gssapi_err(maj_stat, min_stat, actual_mech_server));
+ if (lname.length != strlen(localname_string) ||
+ strncmp(localname_string, lname.value, lname.length) != 0)
+ errx(1, "localname: expected \"%s\", got \"%.*s\" (2)",
+ localname_string, (int)lname.length, (char *)lname.value);
+ gss_release_buffer(&min_stat, &lname);
+
+ if (!gss_userok(src_name, localname_string))
+ errx(1, "localname is not userok");
+ if (gss_userok(src_name, "nosuchuser:no"))
+ errx(1, "gss_userok() appears broken");
+ }
+ if (verbose_flag) {
+ gss_buffer_desc iname;
+
+ maj_stat = gss_display_name(&min_stat, src_name, &iname, NULL);
+ if (maj_stat == GSS_S_COMPLETE) {
+ printf("client name: %.*s\n", (int)iname.length,
+ (char *)iname.value);
+ gss_release_buffer(&min_stat, &iname);
+ } else
+ warnx("display_name: %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+ if (!anon_flag &&
+ gss_oid_equal(actual_mech_server, GSS_KRB5_MECHANISM))
+ show_pac_client_info(src_name);
+ }
+ gss_release_name(&min_stat, &src_name);
+
+ if (max_loops && num_loops > max_loops)
+ errx(1, "num loops %d was lager then max loops %d",
+ num_loops, max_loops);
+
+ if (verbose_flag) {
+ printf("server time offset: %d\n", server_time_offset);
+ printf("client time offset: %d\n", client_time_offset);
+ printf("num loops %d\n", num_loops);
+ printf("cflags: ");
+ if (ret_cflags & GSS_C_DELEG_FLAG)
+ printf("deleg ");
+ if (ret_cflags & GSS_C_MUTUAL_FLAG)
+ printf("mutual ");
+ if (ret_cflags & GSS_C_REPLAY_FLAG)
+ printf("replay ");
+ if (ret_cflags & GSS_C_SEQUENCE_FLAG)
+ printf("sequence ");
+ if (ret_cflags & GSS_C_CONF_FLAG)
+ printf("conf ");
+ if (ret_cflags & GSS_C_INTEG_FLAG)
+ printf("integ ");
+ if (ret_cflags & GSS_C_ANON_FLAG)
+ printf("anon ");
+ if (ret_cflags & GSS_C_PROT_READY_FLAG)
+ printf("prot-ready ");
+ if (ret_cflags & GSS_C_TRANS_FLAG)
+ printf("trans ");
+ if (ret_cflags & GSS_C_DCE_STYLE)
+ printf("dce-style ");
+ if (ret_cflags & GSS_C_IDENTIFY_FLAG)
+ printf("identify " );
+ if (ret_cflags & GSS_C_EXTENDED_ERROR_FLAG)
+ printf("extended-error " );
+ if (ret_cflags & GSS_C_DELEG_POLICY_FLAG)
+ printf("deleg-policy " );
+ printf("\n");
+ printf("sflags: ");
+ if (ret_sflags & GSS_C_CHANNEL_BOUND_FLAG)
+ printf("channel-bound " );
+ printf("\n");
+ }
+}
+
+static void
+wrapunwrap(gss_ctx_id_t cctx, gss_ctx_id_t sctx, int flags, gss_OID mechoid)
+{
+ gss_buffer_desc input_token, output_token, output_token2;
+ OM_uint32 min_stat, maj_stat;
+ gss_qop_t qop_state;
+ int conf_state;
+
+ input_token.value = "foo";
+ input_token.length = 3;
+
+ maj_stat = gss_wrap(&min_stat, cctx, flags, 0, &input_token,
+ &conf_state, &output_token);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_wrap failed: %s",
+ gssapi_err(maj_stat, min_stat, mechoid));
+
+ maj_stat = gss_unwrap(&min_stat, sctx, &output_token,
+ &output_token2, &conf_state, &qop_state);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_unwrap failed: %s",
+ gssapi_err(maj_stat, min_stat, mechoid));
+
+ gss_release_buffer(&min_stat, &output_token);
+ gss_release_buffer(&min_stat, &output_token2);
+
+#if 0 /* doesn't work for NTLM yet */
+ if (!!conf_state != !!flags)
+ errx(1, "conf_state mismatch");
+#endif
+}
+
+#define USE_CONF 1
+#define USE_HEADER_ONLY 2
+#define USE_SIGN_ONLY 4
+#define FORCE_IOV 8
+/* NO_DATA comes from <netdb.h>; we don't use it here; we appropriate it */
+#ifdef NO_DATA
+#undef NO_DATA
+#endif
+#define NO_DATA 16
+
+static void
+wrapunwrap_iov(gss_ctx_id_t cctx, gss_ctx_id_t sctx, int flags, gss_OID mechoid)
+{
+ krb5_data token, header, trailer;
+ OM_uint32 min_stat, maj_stat;
+ gss_qop_t qop_state;
+ int conf_state, conf_state2;
+ gss_iov_buffer_desc iov[6];
+ unsigned char *p;
+ int iov_len;
+ char header_data[9] = "ABCheader";
+ char trailer_data[10] = "trailerXYZ";
+
+ char token_data[16] = "0123456789abcdef";
+
+ memset(&iov, 0, sizeof(iov));
+
+ if (flags & USE_SIGN_ONLY) {
+ header.data = header_data;
+ header.length = 9;
+ trailer.data = trailer_data;
+ trailer.length = 10;
+ } else {
+ header.data = NULL;
+ header.length = 0;
+ trailer.data = NULL;
+ trailer.length = 0;
+ }
+
+ token.data = token_data;
+ token.length = 16;
+
+ iov_len = sizeof(iov)/sizeof(iov[0]);
+
+ memset(iov, 0, sizeof(iov));
+
+ iov[0].type = GSS_IOV_BUFFER_TYPE_HEADER | GSS_IOV_BUFFER_FLAG_ALLOCATE;
+
+ if (header.length != 0) {
+ iov[1].type = GSS_IOV_BUFFER_TYPE_SIGN_ONLY;
+ iov[1].buffer.length = header.length;
+ iov[1].buffer.value = header.data;
+ } else {
+ iov[1].type = GSS_IOV_BUFFER_TYPE_EMPTY;
+ iov[1].buffer.length = 0;
+ iov[1].buffer.value = NULL;
+ }
+ iov[2].type = GSS_IOV_BUFFER_TYPE_DATA;
+ if (flags & NO_DATA) {
+ iov[2].buffer.length = 0;
+ } else {
+ iov[2].buffer.length = token.length;
+ }
+ iov[2].buffer.value = token.data;
+ if (trailer.length != 0) {
+ iov[3].type = GSS_IOV_BUFFER_TYPE_SIGN_ONLY;
+ iov[3].buffer.length = trailer.length;
+ iov[3].buffer.value = trailer.data;
+ } else {
+ iov[3].type = GSS_IOV_BUFFER_TYPE_EMPTY;
+ iov[3].buffer.length = 0;
+ iov[3].buffer.value = NULL;
+ }
+ if (dce_style_flag) {
+ iov[4].type = GSS_IOV_BUFFER_TYPE_EMPTY;
+ } else {
+ iov[4].type = GSS_IOV_BUFFER_TYPE_PADDING | GSS_IOV_BUFFER_FLAG_ALLOCATE;
+ }
+ iov[4].buffer.length = 0;
+ iov[4].buffer.value = 0;
+ if (dce_style_flag) {
+ iov[5].type = GSS_IOV_BUFFER_TYPE_EMPTY;
+ } else if (flags & USE_HEADER_ONLY) {
+ iov[5].type = GSS_IOV_BUFFER_TYPE_EMPTY;
+ } else {
+ iov[5].type = GSS_IOV_BUFFER_TYPE_TRAILER | GSS_IOV_BUFFER_FLAG_ALLOCATE;
+ }
+ iov[5].buffer.length = 0;
+ iov[5].buffer.value = 0;
+
+ maj_stat = gss_wrap_iov(&min_stat, cctx, dce_style_flag || flags & USE_CONF, 0, &conf_state,
+ iov, iov_len);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_wrap_iov failed");
+
+ token.length =
+ iov[0].buffer.length +
+ iov[1].buffer.length +
+ iov[2].buffer.length +
+ iov[3].buffer.length +
+ iov[4].buffer.length +
+ iov[5].buffer.length;
+ token.data = emalloc(token.length);
+
+ p = token.data;
+ memcpy(p, iov[0].buffer.value, iov[0].buffer.length);
+ p += iov[0].buffer.length;
+ memcpy(p, iov[1].buffer.value, iov[1].buffer.length);
+ p += iov[1].buffer.length;
+ memcpy(p, iov[2].buffer.value, iov[2].buffer.length);
+ p += iov[2].buffer.length;
+ memcpy(p, iov[3].buffer.value, iov[3].buffer.length);
+ p += iov[3].buffer.length;
+ memcpy(p, iov[4].buffer.value, iov[4].buffer.length);
+ p += iov[4].buffer.length;
+ memcpy(p, iov[5].buffer.value, iov[5].buffer.length);
+ p += iov[5].buffer.length;
+
+ assert(p - ((unsigned char *)token.data) == token.length);
+
+ if ((flags & (USE_SIGN_ONLY|FORCE_IOV)) == 0) {
+ gss_buffer_desc input, output;
+
+ input.value = token.data;
+ input.length = token.length;
+
+ maj_stat = gss_unwrap(&min_stat, sctx, &input,
+ &output, &conf_state2, &qop_state);
+
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_unwrap from gss_wrap_iov failed: %s",
+ gssapi_err(maj_stat, min_stat, mechoid));
+
+ gss_release_buffer(&min_stat, &output);
+ } else {
+ maj_stat = gss_unwrap_iov(&min_stat, sctx, &conf_state2, &qop_state,
+ iov, iov_len);
+
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_unwrap_iov failed: %x %s", flags,
+ gssapi_err(maj_stat, min_stat, mechoid));
+
+ }
+ if (conf_state2 != conf_state)
+ errx(1, "conf state wrong for iov: %x", flags);
+
+ gss_release_iov_buffer(&min_stat, iov, iov_len);
+
+ free(token.data);
+}
+
+static void
+wrapunwrap_aead(gss_ctx_id_t cctx, gss_ctx_id_t sctx, int flags, gss_OID mechoid)
+{
+ gss_buffer_desc token, assoc, message = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc output;
+ OM_uint32 min_stat, maj_stat;
+ gss_qop_t qop_state;
+ int conf_state, conf_state2;
+ char assoc_data[9] = "ABCheader";
+ char token_data[16] = "0123456789abcdef";
+
+ if (flags & USE_SIGN_ONLY) {
+ assoc.value = assoc_data;
+ assoc.length = 9;
+ } else {
+ assoc.value = NULL;
+ assoc.length = 0;
+ }
+
+ token.value = token_data;
+ token.length = 16;
+
+ maj_stat = gss_wrap_aead(&min_stat, cctx, dce_style_flag || flags & USE_CONF,
+ GSS_C_QOP_DEFAULT, &assoc, &token,
+ &conf_state, &message);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_wrap_aead failed");
+
+ if ((flags & (USE_SIGN_ONLY|FORCE_IOV)) == 0) {
+ maj_stat = gss_unwrap(&min_stat, sctx, &message,
+ &output, &conf_state2, &qop_state);
+
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_unwrap from gss_wrap_aead failed: %s",
+ gssapi_err(maj_stat, min_stat, mechoid));
+ } else {
+ maj_stat = gss_unwrap_aead(&min_stat, sctx, &message, &assoc,
+ &output, &conf_state2, &qop_state);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_unwrap_aead failed: %x %s", flags,
+ gssapi_err(maj_stat, min_stat, mechoid));
+ }
+
+ if (output.length != token.length)
+ errx(1, "plaintext length wrong for aead");
+ else if (memcmp(output.value, token.value, token.length) != 0)
+ errx(1, "plaintext wrong for aead");
+ if (conf_state2 != conf_state)
+ errx(1, "conf state wrong for aead: %x", flags);
+
+ gss_release_buffer(&min_stat, &message);
+ gss_release_buffer(&min_stat, &output);
+}
+
+static void
+getverifymic(gss_ctx_id_t cctx, gss_ctx_id_t sctx, gss_OID mechoid)
+{
+ gss_buffer_desc input_token, output_token;
+ OM_uint32 min_stat, maj_stat;
+ gss_qop_t qop_state;
+
+ input_token.value = "bar";
+ input_token.length = 3;
+
+ maj_stat = gss_get_mic(&min_stat, cctx, 0, &input_token,
+ &output_token);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_get_mic failed: %s",
+ gssapi_err(maj_stat, min_stat, mechoid));
+
+ maj_stat = gss_verify_mic(&min_stat, sctx, &input_token,
+ &output_token, &qop_state);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_verify_mic failed: %s",
+ gssapi_err(maj_stat, min_stat, mechoid));
+
+ gss_release_buffer(&min_stat, &output_token);
+}
+
+static void
+empty_release(void)
+{
+ gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
+ gss_cred_id_t cred = GSS_C_NO_CREDENTIAL;
+ gss_name_t name = GSS_C_NO_NAME;
+ gss_OID_set oidset = GSS_C_NO_OID_SET;
+ OM_uint32 junk;
+
+ gss_delete_sec_context(&junk, &ctx, NULL);
+ gss_release_cred(&junk, &cred);
+ gss_release_name(&junk, &name);
+ gss_release_oid_set(&junk, &oidset);
+}
+
+/*
+ *
+ */
+
+static struct getargs args[] = {
+ {"name-type",0, arg_string, &type_string, "type of name", NULL },
+ {"mech-type",0, arg_string, &mech_string, "mech type (name)", NULL },
+ {"mech-types",0, arg_string, &mechs_string, "mech types (names)", NULL },
+ {"ret-mech-type",0, arg_string, &ret_mech_string,
+ "type of return mech", NULL },
+ {"dns-canonicalize",0,arg_negative_flag, &dns_canon_flag,
+ "use dns to canonicalize", NULL },
+ {"mutual-auth",0, arg_flag, &mutual_auth_flag,"mutual auth", NULL },
+ {"client-ccache",0, arg_string, &client_ccache, "client credentials cache", NULL },
+ {"client-keytab",0, arg_string, &client_keytab, "client keytab", NULL },
+ {"client-name", 0, arg_string, &client_name, "client name", NULL },
+ {"client-password", 0, arg_string, &client_password, "client password", NULL },
+ {"anonymous", 0, arg_flag, &anon_flag, "anonymous auth", NULL },
+ {"i-channel-bindings", 0, arg_string, &i_channel_bindings, "initiator channel binding data", NULL },
+ {"a-channel-bindings", 0, arg_string, &a_channel_bindings, "acceptor channel binding data", NULL },
+ {"limit-enctype",0, arg_string, &limit_enctype_string, "enctype", NULL },
+ {"dce-style",0, arg_flag, &dce_style_flag, "dce-style", NULL },
+ {"wrapunwrap",0, arg_flag, &wrapunwrap_flag, "wrap/unwrap", NULL },
+ {"iov", 0, arg_flag, &iov_flag, "wrap/unwrap iov", NULL },
+ {"aead", 0, arg_flag, &aead_flag, "wrap/unwrap aead", NULL },
+ {"getverifymic",0, arg_flag, &getverifymic_flag,
+ "get and verify mic", NULL },
+ {"delegate",0, arg_flag, &deleg_flag, "delegate credential", NULL },
+ {"policy-delegate",0, arg_flag, &policy_deleg_flag, "policy delegate credential", NULL },
+ {"server-no-delegate",0, arg_flag, &server_no_deleg_flag,
+ "server should get a credential", NULL },
+ {"export-import-context",0, arg_flag, &ei_ctx_flag, "test export/import context", NULL },
+ {"export-import-cred",0, arg_flag, &ei_cred_flag, "test export/import cred", NULL },
+ {"localname",0, arg_string, &localname_string, "expected localname for client", "USERNAME"},
+ {"gsskrb5-acceptor-identity", 0, arg_string, &gsskrb5_acceptor_identity, "keytab", NULL },
+ {"session-enctype", 0, arg_string, &session_enctype_string, "enctype", NULL },
+ {"client-time-offset", 0, arg_integer, &client_time_offset, "time", NULL },
+ {"server-time-offset", 0, arg_integer, &server_time_offset, "time", NULL },
+ {"max-loops", 0, arg_integer, &max_loops, "time", NULL },
+ {"token-split", 0, arg_integer, &token_split, "bytes", NULL },
+ {"on-behalf-of", 0, arg_string, &on_behalf_of_string, "principal",
+ "send authenticator authz-data AD-ON-BEHALF-OF" },
+ {"version", 0, arg_flag, &version_flag, "print version", NULL },
+ {"verbose", 'v', arg_flag, &verbose_flag, "verbose", NULL },
+ {"help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args),
+ NULL, "service@host");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ int optidx = 0;
+ OM_uint32 min_stat, maj_stat;
+ gss_ctx_id_t cctx, sctx;
+ void *ctx;
+ gss_OID nameoid, mechoid, actual_mech, actual_mech2;
+ gss_cred_id_t client_cred = GSS_C_NO_CREDENTIAL, deleg_cred = GSS_C_NO_CREDENTIAL;
+ gss_name_t cname = GSS_C_NO_NAME;
+ gss_buffer_desc credential_data = GSS_C_EMPTY_BUFFER;
+ gss_OID_desc oids[7];
+ gss_OID_set_desc mechoid_descs;
+ gss_OID_set mechoids = GSS_C_NO_OID_SET;
+ gss_key_value_element_desc client_cred_elements[2];
+ gss_key_value_set_desc client_cred_store;
+ gss_OID_set actual_mechs = GSS_C_NO_OID_SET;
+
+ setprogname(argv[0]);
+
+ if (krb5_init_context(&context))
+ errx(1, "krb5_init_context");
+
+ cctx = sctx = GSS_C_NO_CONTEXT;
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (argc != 1)
+ usage(1);
+
+ if (dns_canon_flag != -1)
+ gsskrb5_set_dns_canonicalize(dns_canon_flag);
+
+ if (type_string == NULL)
+ nameoid = GSS_C_NT_HOSTBASED_SERVICE;
+ else if (strcmp(type_string, "hostbased-service") == 0)
+ nameoid = GSS_C_NT_HOSTBASED_SERVICE;
+ else if (strcmp(type_string, "krb5-principal-name") == 0)
+ nameoid = GSS_KRB5_NT_PRINCIPAL_NAME;
+ else
+ errx(1, "%s not supported", type_string);
+
+ if (mech_string == NULL)
+ mechoid = GSS_KRB5_MECHANISM;
+ else
+ mechoid = string_to_oid(mech_string);
+
+ if (mechs_string == NULL) {
+ /*
+ * We ought to be able to use the OID set of the one mechanism
+ * OID given. But there's some breakage that conspires to make
+ * that fail though it should succeed:
+ *
+ * - the NTLM gss_acquire_cred() refuses to work with
+ * desired_name == GSS_C_NO_NAME
+ * - gss_acquire_cred() with desired_mechs == GSS_C_NO_OID_SET
+ * does work here because we happen to have Kerberos
+ * credentials in check-ntlm, and the subsequent
+ * gss_init_sec_context() call finds no cred element for NTLM
+ * but plows on anyways, surprisingly enough, and then the
+ * NTLM gss_init_sec_context() just works.
+ *
+ * In summary, there's some breakage in gss_init_sec_context()
+ * and some breakage in NTLM that conspires against us here.
+ *
+ * We work around this in check-ntlm and check-spnego by adding
+ * --client-name=user1@${R} to the invocations of this test
+ * program that require it.
+ */
+ oids[0] = *mechoid;
+ mechoid_descs.elements = &oids[0];
+ mechoid_descs.count = 1;
+ mechoids = &mechoid_descs;
+ } else {
+ string_to_oids(&mechoids, mechs_string);
+ }
+
+ if (gsskrb5_acceptor_identity) {
+ /* XXX replace this with cred store, but test suites will need work */
+ maj_stat = gsskrb5_register_acceptor_identity(gsskrb5_acceptor_identity);
+ if (maj_stat)
+ errx(1, "gsskrb5_acceptor_identity: %s",
+ gssapi_err(maj_stat, 0, GSS_C_NO_OID));
+ }
+
+ if (client_password && (client_ccache || client_keytab)) {
+ errx(1, "password option mutually exclusive with ccache or keytab option");
+ }
+
+ if (client_password) {
+ credential_data.value = client_password;
+ credential_data.length = strlen(client_password);
+ }
+
+ client_cred_store.count = 0;
+ client_cred_store.elements = client_cred_elements;
+
+ if (client_ccache) {
+ client_cred_store.elements[client_cred_store.count].key = "ccache";
+ client_cred_store.elements[client_cred_store.count].value = client_ccache;
+
+ client_cred_store.count++;
+ }
+
+ if (client_keytab) {
+ client_cred_store.elements[client_cred_store.count].key = "client_keytab";
+ client_cred_store.elements[client_cred_store.count].value = client_keytab;
+
+ client_cred_store.count++;
+ }
+
+ if (client_name) {
+ gss_buffer_desc cn;
+
+ cn.value = client_name;
+ cn.length = strlen(client_name);
+
+ maj_stat = gss_import_name(&min_stat, &cn, GSS_C_NT_USER_NAME, &cname);
+ if (maj_stat)
+ errx(1, "gss_import_name: %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+ }
+
+ if (client_password) {
+ maj_stat = gss_acquire_cred_with_password(&min_stat,
+ cname,
+ &credential_data,
+ GSS_C_INDEFINITE,
+ mechoids,
+ GSS_C_INITIATE,
+ &client_cred,
+ &actual_mechs,
+ NULL);
+ if (GSS_ERROR(maj_stat)) {
+ if (mechoids != GSS_C_NO_OID_SET && mechoids->count == 1)
+ mechoid = &mechoids->elements[0];
+ else
+ mechoid = GSS_C_NO_OID;
+ errx(1, "gss_acquire_cred_with_password: %s",
+ gssapi_err(maj_stat, min_stat, mechoid));
+ }
+ } else {
+ maj_stat = gss_acquire_cred_from(&min_stat,
+ cname,
+ GSS_C_INDEFINITE,
+ mechoids,
+ GSS_C_INITIATE,
+ client_cred_store.count ? &client_cred_store
+ : GSS_C_NO_CRED_STORE,
+ &client_cred,
+ &actual_mechs,
+ NULL);
+ if (GSS_ERROR(maj_stat) && !anon_flag)
+ errx(1, "gss_acquire_cred: %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+ }
+
+ gss_release_name(&min_stat, &cname);
+
+ if (verbose_flag) {
+ size_t i;
+
+ printf("cred mechs:");
+ for (i = 0; i < actual_mechs->count; i++)
+ printf(" %s", gss_oid_to_name(&actual_mechs->elements[i]));
+ printf("\n");
+ }
+
+ if (gss_oid_equal(mechoid, GSS_SPNEGO_MECHANISM) && mechs_string) {
+ maj_stat = gss_set_neg_mechs(&min_stat, client_cred, mechoids);
+ if (GSS_ERROR(maj_stat))
+ errx(1, "gss_set_neg_mechs: %s",
+ gssapi_err(maj_stat, min_stat, GSS_SPNEGO_MECHANISM));
+
+ mechoid_descs.elements = GSS_SPNEGO_MECHANISM;
+ mechoid_descs.count = 1;
+ mechoids = &mechoid_descs;
+ }
+
+ if (ei_cred_flag) {
+ gss_cred_id_t cred2 = GSS_C_NO_CREDENTIAL;
+ gss_buffer_desc cb;
+
+ maj_stat = gss_export_cred(&min_stat, client_cred, &cb);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "export cred failed: %s",
+ gssapi_err(maj_stat, min_stat, NULL));
+
+ maj_stat = gss_import_cred(&min_stat, &cb, &cred2);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "import cred failed: %s",
+ gssapi_err(maj_stat, min_stat, NULL));
+
+ gss_release_buffer(&min_stat, &cb);
+ gss_release_cred(&min_stat, &client_cred);
+ client_cred = cred2;
+ }
+
+ if (limit_enctype_string) {
+ krb5_error_code ret;
+
+ ret = krb5_string_to_enctype(context,
+ limit_enctype_string,
+ &limit_enctype);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_string_to_enctype");
+ }
+
+
+ if (limit_enctype) {
+ if (client_cred == NULL)
+ errx(1, "client_cred missing");
+
+ maj_stat = gss_krb5_set_allowable_enctypes(&min_stat, client_cred,
+ 1, &limit_enctype);
+ if (maj_stat)
+ errx(1, "gss_krb5_set_allowable_enctypes: %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+ }
+
+ loop(mechoid, nameoid, argv[0], client_cred,
+ &sctx, &cctx, &actual_mech, &deleg_cred);
+
+ if (verbose_flag)
+ printf("resulting mech: %s\n", gss_oid_to_name(actual_mech));
+
+ if (ret_mech_string) {
+ gss_OID retoid;
+
+ retoid = string_to_oid(ret_mech_string);
+
+ if (gss_oid_equal(retoid, actual_mech) == 0)
+ errx(1, "actual_mech mech is not the expected type %s",
+ ret_mech_string);
+ }
+
+ /* XXX should be actual_mech */
+ if (gss_oid_equal(mechoid, GSS_KRB5_MECHANISM)) {
+ time_t sc_time;
+ gss_buffer_desc authz_data;
+ gss_buffer_desc in, out1, out2;
+ krb5_keyblock *keyblock, *keyblock2;
+ krb5_timestamp now;
+ krb5_error_code ret;
+
+ ret = krb5_timeofday(context, &now);
+ if (ret)
+ errx(1, "krb5_timeofday failed");
+
+ /* client */
+ maj_stat = gss_krb5_export_lucid_sec_context(&min_stat,
+ &cctx,
+ 1, /* version */
+ &ctx);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_krb5_export_lucid_sec_context failed: %s",
+ gssapi_err(maj_stat, min_stat, actual_mech));
+
+
+ maj_stat = gss_krb5_free_lucid_sec_context(&maj_stat, ctx);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_krb5_free_lucid_sec_context failed: %s",
+ gssapi_err(maj_stat, min_stat, actual_mech));
+
+ /* server */
+ maj_stat = gss_krb5_export_lucid_sec_context(&min_stat,
+ &sctx,
+ 1, /* version */
+ &ctx);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_krb5_export_lucid_sec_context failed: %s",
+ gssapi_err(maj_stat, min_stat, actual_mech));
+ maj_stat = gss_krb5_free_lucid_sec_context(&min_stat, ctx);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_krb5_free_lucid_sec_context failed: %s",
+ gssapi_err(maj_stat, min_stat, actual_mech));
+
+ maj_stat = gsskrb5_extract_authtime_from_sec_context(&min_stat,
+ sctx,
+ &sc_time);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gsskrb5_extract_authtime_from_sec_context failed: %s",
+ gssapi_err(maj_stat, min_stat, actual_mech));
+
+ if (sc_time > now)
+ errx(1, "gsskrb5_extract_authtime_from_sec_context failed: "
+ "time authtime is before now: %ld %ld",
+ (long)sc_time, (long)now);
+
+ maj_stat = gsskrb5_extract_service_keyblock(&min_stat,
+ sctx,
+ &keyblock);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gsskrb5_export_service_keyblock failed: %s",
+ gssapi_err(maj_stat, min_stat, actual_mech));
+
+ krb5_free_keyblock(context, keyblock);
+
+ maj_stat = gsskrb5_get_subkey(&min_stat,
+ sctx,
+ &keyblock);
+ if (maj_stat != GSS_S_COMPLETE
+ && (!(maj_stat == GSS_S_FAILURE && min_stat == GSS_KRB5_S_KG_NO_SUBKEY)))
+ errx(1, "gsskrb5_get_subkey server failed: %s",
+ gssapi_err(maj_stat, min_stat, actual_mech));
+
+ if (maj_stat != GSS_S_COMPLETE)
+ keyblock = NULL;
+ else if (limit_enctype && keyblock->keytype != limit_enctype)
+ errx(1, "gsskrb5_get_subkey wrong enctype");
+
+ maj_stat = gsskrb5_get_subkey(&min_stat,
+ cctx,
+ &keyblock2);
+ if (maj_stat != GSS_S_COMPLETE
+ && (!(maj_stat == GSS_S_FAILURE && min_stat == GSS_KRB5_S_KG_NO_SUBKEY)))
+ errx(1, "gsskrb5_get_subkey client failed: %s",
+ gssapi_err(maj_stat, min_stat, actual_mech));
+
+ if (maj_stat != GSS_S_COMPLETE)
+ keyblock2 = NULL;
+ else if (limit_enctype && keyblock && keyblock->keytype != limit_enctype)
+ errx(1, "gsskrb5_get_subkey wrong enctype");
+
+ if (keyblock || keyblock2) {
+ if (keyblock == NULL)
+ errx(1, "server missing token keyblock");
+ if (keyblock2 == NULL)
+ errx(1, "client missing token keyblock");
+
+ if (keyblock->keytype != keyblock2->keytype)
+ errx(1, "enctype mismatch");
+ if (keyblock->keyvalue.length != keyblock2->keyvalue.length)
+ errx(1, "key length mismatch");
+ if (memcmp(keyblock->keyvalue.data, keyblock2->keyvalue.data,
+ keyblock2->keyvalue.length) != 0)
+ errx(1, "key data mismatch");
+ }
+
+ if (session_enctype_string) {
+ krb5_enctype enctype;
+
+ ret = krb5_string_to_enctype(context,
+ session_enctype_string,
+ &enctype);
+
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_string_to_enctype");
+
+ if (keyblock && enctype != keyblock->keytype)
+ errx(1, "keytype is not the expected %d != %d",
+ (int)enctype, (int)keyblock2->keytype);
+ }
+
+ if (keyblock)
+ krb5_free_keyblock(context, keyblock);
+ if (keyblock2)
+ krb5_free_keyblock(context, keyblock2);
+
+ maj_stat = gsskrb5_get_initiator_subkey(&min_stat,
+ sctx,
+ &keyblock);
+ if (maj_stat != GSS_S_COMPLETE
+ && (!(maj_stat == GSS_S_FAILURE && min_stat == GSS_KRB5_S_KG_NO_SUBKEY)))
+ errx(1, "gsskrb5_get_initiator_subkey failed: %s",
+ gssapi_err(maj_stat, min_stat, actual_mech));
+
+ if (maj_stat == GSS_S_COMPLETE) {
+
+ if (limit_enctype && keyblock->keytype != limit_enctype)
+ errx(1, "gsskrb5_get_initiator_subkey wrong enctype");
+ krb5_free_keyblock(context, keyblock);
+ }
+
+ maj_stat = gsskrb5_extract_authz_data_from_sec_context(&min_stat,
+ sctx,
+ 128,
+ &authz_data);
+ if (maj_stat == GSS_S_COMPLETE)
+ gss_release_buffer(&min_stat, &authz_data);
+
+
+ memset(&out1, 0, sizeof(out1));
+ memset(&out2, 0, sizeof(out2));
+
+ in.value = "foo";
+ in.length = 3;
+
+ gss_pseudo_random(&min_stat, sctx, GSS_C_PRF_KEY_FULL, &in,
+ 100, &out1);
+ gss_pseudo_random(&min_stat, cctx, GSS_C_PRF_KEY_FULL, &in,
+ 100, &out2);
+
+ if (out1.length != out2.length)
+ errx(1, "prf len mismatch");
+ if (memcmp(out1.value, out2.value, out1.length) != 0)
+ errx(1, "prf data mismatch");
+
+ gss_release_buffer(&min_stat, &out1);
+
+ gss_pseudo_random(&min_stat, sctx, GSS_C_PRF_KEY_FULL, &in,
+ 100, &out1);
+
+ if (out1.length != out2.length)
+ errx(1, "prf len mismatch");
+ if (memcmp(out1.value, out2.value, out1.length) != 0)
+ errx(1, "prf data mismatch");
+
+ gss_release_buffer(&min_stat, &out1);
+ gss_release_buffer(&min_stat, &out2);
+
+ in.value = "bar";
+ in.length = 3;
+
+ gss_pseudo_random(&min_stat, sctx, GSS_C_PRF_KEY_PARTIAL, &in,
+ 100, &out1);
+ gss_pseudo_random(&min_stat, cctx, GSS_C_PRF_KEY_PARTIAL, &in,
+ 100, &out2);
+
+ if (out1.length != out2.length)
+ errx(1, "prf len mismatch");
+ if (memcmp(out1.value, out2.value, out1.length) != 0)
+ errx(1, "prf data mismatch");
+
+ gss_release_buffer(&min_stat, &out1);
+ gss_release_buffer(&min_stat, &out2);
+
+ wrapunwrap_flag = 1;
+ getverifymic_flag = 1;
+ }
+
+ if (ei_ctx_flag) {
+ gss_buffer_desc ctx_token = GSS_C_EMPTY_BUFFER;
+
+ maj_stat = gss_export_sec_context(&min_stat, &cctx, &ctx_token);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "export client context failed: %s",
+ gssapi_err(maj_stat, min_stat, NULL));
+
+ if (cctx != GSS_C_NO_CONTEXT)
+ errx(1, "export client context did not release it");
+
+ maj_stat = gss_import_sec_context(&min_stat, &ctx_token, &cctx);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "import client context failed: %s",
+ gssapi_err(maj_stat, min_stat, NULL));
+
+ gss_release_buffer(&min_stat, &ctx_token);
+
+ maj_stat = gss_export_sec_context(&min_stat, &sctx, &ctx_token);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "export server context failed: %s",
+ gssapi_err(maj_stat, min_stat, NULL));
+
+ if (sctx != GSS_C_NO_CONTEXT)
+ errx(1, "export server context did not release it");
+
+ maj_stat = gss_import_sec_context(&min_stat, &ctx_token, &sctx);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "import server context failed: %s",
+ gssapi_err(maj_stat, min_stat, NULL));
+
+ gss_release_buffer(&min_stat, &ctx_token);
+ }
+
+ if (wrapunwrap_flag) {
+ wrapunwrap(cctx, sctx, 0, actual_mech);
+ wrapunwrap(cctx, sctx, 1, actual_mech);
+ wrapunwrap(sctx, cctx, 0, actual_mech);
+ wrapunwrap(sctx, cctx, 1, actual_mech);
+ }
+
+ if (iov_flag) {
+ wrapunwrap_iov(cctx, sctx, 0, actual_mech);
+ wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY|FORCE_IOV, actual_mech);
+ wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY, actual_mech);
+ wrapunwrap_iov(cctx, sctx, USE_CONF, actual_mech);
+ wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, FORCE_IOV, actual_mech);
+ wrapunwrap_iov(cctx, sctx, USE_CONF|FORCE_IOV, actual_mech);
+ wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY|FORCE_IOV, actual_mech);
+ wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY|FORCE_IOV, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+ wrapunwrap_iov(cctx, sctx, USE_CONF|USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+ wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY|USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+
+/* works */
+ wrapunwrap_iov(cctx, sctx, 0, actual_mech);
+ wrapunwrap_iov(cctx, sctx, FORCE_IOV, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, USE_CONF, actual_mech);
+ wrapunwrap_iov(cctx, sctx, USE_CONF|FORCE_IOV, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, USE_SIGN_ONLY, actual_mech);
+ wrapunwrap_iov(cctx, sctx, USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, USE_CONF|USE_SIGN_ONLY, actual_mech);
+ wrapunwrap_iov(cctx, sctx, USE_CONF|USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY, actual_mech);
+ wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY|FORCE_IOV, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY, actual_mech);
+ wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY|FORCE_IOV, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, NO_DATA, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_HEADER_ONLY|FORCE_IOV, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_HEADER_ONLY, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_CONF, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_CONF|USE_HEADER_ONLY, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, NO_DATA|FORCE_IOV, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_CONF|FORCE_IOV, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_HEADER_ONLY|FORCE_IOV, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_CONF|USE_HEADER_ONLY|FORCE_IOV, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_CONF|USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_CONF|USE_HEADER_ONLY|USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+
+ /* works */
+ wrapunwrap_iov(cctx, sctx, NO_DATA, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|FORCE_IOV, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_CONF, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_CONF|FORCE_IOV, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_SIGN_ONLY, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_CONF|USE_SIGN_ONLY, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_CONF|USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_HEADER_ONLY, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_HEADER_ONLY|FORCE_IOV, actual_mech);
+
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_CONF|USE_HEADER_ONLY, actual_mech);
+ wrapunwrap_iov(cctx, sctx, NO_DATA|USE_CONF|USE_HEADER_ONLY|FORCE_IOV, actual_mech);
+ }
+
+ if (aead_flag) {
+ wrapunwrap_aead(cctx, sctx, 0, actual_mech);
+ wrapunwrap_aead(cctx, sctx, USE_CONF, actual_mech);
+
+ wrapunwrap_aead(cctx, sctx, FORCE_IOV, actual_mech);
+ wrapunwrap_aead(cctx, sctx, USE_CONF|FORCE_IOV, actual_mech);
+
+ wrapunwrap_aead(cctx, sctx, USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+ wrapunwrap_aead(cctx, sctx, USE_CONF|USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+
+ wrapunwrap_aead(cctx, sctx, 0, actual_mech);
+ wrapunwrap_aead(cctx, sctx, FORCE_IOV, actual_mech);
+
+ wrapunwrap_aead(cctx, sctx, USE_CONF, actual_mech);
+ wrapunwrap_aead(cctx, sctx, USE_CONF|FORCE_IOV, actual_mech);
+
+ wrapunwrap_aead(cctx, sctx, USE_SIGN_ONLY, actual_mech);
+ wrapunwrap_aead(cctx, sctx, USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+
+ wrapunwrap_aead(cctx, sctx, USE_CONF|USE_SIGN_ONLY, actual_mech);
+ wrapunwrap_aead(cctx, sctx, USE_CONF|USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+ }
+
+ if (getverifymic_flag) {
+ getverifymic(cctx, sctx, actual_mech);
+ getverifymic(cctx, sctx, actual_mech);
+ getverifymic(sctx, cctx, actual_mech);
+ getverifymic(sctx, cctx, actual_mech);
+ }
+
+ gss_delete_sec_context(&min_stat, &cctx, NULL);
+ gss_delete_sec_context(&min_stat, &sctx, NULL);
+
+ if (deleg_cred != GSS_C_NO_CREDENTIAL) {
+ gss_cred_id_t cred2 = GSS_C_NO_CREDENTIAL;
+ gss_buffer_desc cb;
+
+ if (verbose_flag)
+ printf("checking actual mech (%s) on delegated cred\n",
+ gss_oid_to_name(actual_mech));
+ loop(actual_mech, nameoid, argv[0], deleg_cred, &sctx, &cctx, &actual_mech2, &cred2);
+
+ gss_delete_sec_context(&min_stat, &cctx, NULL);
+ gss_delete_sec_context(&min_stat, &sctx, NULL);
+
+ gss_release_cred(&min_stat, &cred2);
+
+#if 0
+ /*
+ * XXX We can't do this. Delegated credentials only work with
+ * the actual_mech. We could gss_store_cred the delegated
+ * credentials *then* gss_add/acquire_cred() with SPNEGO, then
+ * we could try loop() with those credentials.
+ */
+ /* try again using SPNEGO */
+ if (verbose_flag)
+ printf("checking spnego on delegated cred\n");
+ loop(GSS_SPNEGO_MECHANISM, nameoid, argv[0], deleg_cred, &sctx, &cctx,
+ &actual_mech2, &cred2);
+
+ gss_delete_sec_context(&min_stat, &cctx, NULL);
+ gss_delete_sec_context(&min_stat, &sctx, NULL);
+
+ gss_release_cred(&min_stat, &cred2);
+#endif
+
+ /* check export/import */
+ if (ei_cred_flag) {
+
+ maj_stat = gss_export_cred(&min_stat, deleg_cred, &cb);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "export cred failed: %s",
+ gssapi_err(maj_stat, min_stat, NULL));
+
+ maj_stat = gss_import_cred(&min_stat, &cb, &cred2);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "import cred failed: %s",
+ gssapi_err(maj_stat, min_stat, NULL));
+
+ gss_release_buffer(&min_stat, &cb);
+ gss_release_cred(&min_stat, &deleg_cred);
+
+ if (verbose_flag)
+ printf("checking actual mech (%s) on export/imported cred\n",
+ gss_oid_to_name(actual_mech));
+ loop(actual_mech, nameoid, argv[0], cred2, &sctx, &cctx,
+ &actual_mech2, &deleg_cred);
+
+ gss_release_cred(&min_stat, &deleg_cred);
+
+ gss_delete_sec_context(&min_stat, &cctx, NULL);
+ gss_delete_sec_context(&min_stat, &sctx, NULL);
+
+#if 0
+ /* XXX See above */
+ /* try again using SPNEGO */
+ if (verbose_flag)
+ printf("checking SPNEGO on export/imported cred\n");
+ loop(GSS_SPNEGO_MECHANISM, nameoid, argv[0], cred2, &sctx, &cctx,
+ &actual_mech2, &deleg_cred);
+
+ gss_release_cred(&min_stat, &deleg_cred);
+
+ gss_delete_sec_context(&min_stat, &cctx, NULL);
+ gss_delete_sec_context(&min_stat, &sctx, NULL);
+#endif
+
+ gss_release_cred(&min_stat, &cred2);
+
+ } else {
+ gss_release_cred(&min_stat, &deleg_cred);
+ }
+
+ }
+
+ gss_release_cred(&min_stat, &client_cred);
+ gss_release_oid_set(&min_stat, &actual_mechs);
+ if (mechoids != GSS_C_NO_OID_SET && mechoids != &mechoid_descs)
+ gss_release_oid_set(&min_stat, &mechoids);
+ empty_release();
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/gssapi/test_cred.c b/third_party/heimdal/lib/gssapi/test_cred.c
new file mode 100644
index 0000000..9eaabda
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/test_cred.c
@@ -0,0 +1,236 @@
+/*
+ * Copyright (c) 2003-2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <roken.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
+#include <err.h>
+#include <getarg.h>
+
+static int anon_flag = 0;
+
+static void
+gss_print_errors (int min_stat)
+{
+ OM_uint32 new_stat;
+ OM_uint32 msg_ctx = 0;
+ gss_buffer_desc status_string;
+ OM_uint32 ret;
+
+ do {
+ ret = gss_display_status (&new_stat,
+ min_stat,
+ GSS_C_MECH_CODE,
+ GSS_C_NO_OID,
+ &msg_ctx,
+ &status_string);
+ if (!GSS_ERROR(ret)) {
+ fprintf (stderr, "%.*s\n", (int)status_string.length,
+ (char *)status_string.value);
+ gss_release_buffer (&new_stat, &status_string);
+ }
+ } while (!GSS_ERROR(ret) && msg_ctx != 0);
+}
+
+static void
+gss_err(int exitval, int status, const char *fmt, ...)
+{
+ va_list args;
+
+ va_start(args, fmt);
+ vwarnx (fmt, args);
+ gss_print_errors (status);
+ va_end(args);
+ exit (exitval);
+}
+
+static void
+acquire_release_loop(gss_name_t name, int counter, gss_cred_usage_t usage)
+{
+ OM_uint32 maj_stat, min_stat;
+ gss_cred_id_t cred;
+ int i;
+
+ for (i = 0; i < counter; i++) {
+ maj_stat = gss_acquire_cred(&min_stat, name,
+ GSS_C_INDEFINITE,
+ GSS_C_NO_OID_SET,
+ usage,
+ &cred,
+ NULL,
+ NULL);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "aquire %d %d != GSS_S_COMPLETE",
+ i, (int)maj_stat);
+
+ maj_stat = gss_release_cred(&min_stat, &cred);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "release %d %d != GSS_S_COMPLETE",
+ i, (int)maj_stat);
+ }
+}
+
+
+static void
+acquire_add_release_add(gss_name_t name, gss_cred_usage_t usage)
+{
+ OM_uint32 maj_stat, min_stat;
+ gss_cred_id_t cred, cred2, cred3;
+ gss_OID mech_oid = anon_flag ? GSS_SANON_X25519_MECHANISM : GSS_KRB5_MECHANISM;
+
+ maj_stat = gss_acquire_cred(&min_stat, name,
+ GSS_C_INDEFINITE,
+ GSS_C_NO_OID_SET,
+ usage,
+ &cred,
+ NULL,
+ NULL);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "aquire %d != GSS_S_COMPLETE", (int)maj_stat);
+
+ maj_stat = gss_add_cred(&min_stat,
+ cred,
+ GSS_C_NO_NAME,
+ mech_oid,
+ usage,
+ GSS_C_INDEFINITE,
+ GSS_C_INDEFINITE,
+ &cred2,
+ NULL,
+ NULL,
+ NULL);
+
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "add_cred %d != GSS_S_COMPLETE", (int)maj_stat);
+
+ maj_stat = gss_release_cred(&min_stat, &cred);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "release %d != GSS_S_COMPLETE", (int)maj_stat);
+
+ maj_stat = gss_add_cred(&min_stat,
+ cred2,
+ GSS_C_NO_NAME,
+ mech_oid,
+ GSS_C_BOTH,
+ GSS_C_INDEFINITE,
+ GSS_C_INDEFINITE,
+ &cred3,
+ NULL,
+ NULL,
+ NULL);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "add_cred 2 %d != GSS_S_COMPLETE", (int)maj_stat);
+
+ maj_stat = gss_release_cred(&min_stat, &cred2);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "release 2 %d != GSS_S_COMPLETE", (int)maj_stat);
+
+ maj_stat = gss_release_cred(&min_stat, &cred3);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, min_stat, "release 3 %d != GSS_S_COMPLETE", (int)maj_stat);
+}
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"anonymous", 0, arg_flag, &anon_flag, "try anonymous creds", NULL },
+ {"version", 0, arg_flag, &version_flag, "print version", NULL },
+ {"help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args),
+ NULL, "service@host");
+ exit (ret);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ struct gss_buffer_desc_struct name_buffer;
+ OM_uint32 maj_stat, min_stat;
+ gss_name_t name;
+ int optidx = 0;
+
+ setprogname(argv[0]);
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (argc < 1)
+ errx(1, "argc < 1");
+
+ name_buffer.value = argv[0];
+ name_buffer.length = strlen(argv[0]);
+
+ maj_stat = gss_import_name(&min_stat, &name_buffer,
+ GSS_C_NT_HOSTBASED_SERVICE,
+ &name);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "import name error");
+
+ acquire_release_loop(name, 100, GSS_C_ACCEPT);
+ acquire_release_loop(name, 100, GSS_C_INITIATE);
+ acquire_release_loop(name, 100, GSS_C_BOTH);
+
+ acquire_add_release_add(name, GSS_C_ACCEPT);
+ acquire_add_release_add(name, GSS_C_INITIATE);
+ acquire_add_release_add(name, GSS_C_BOTH);
+
+ gss_release_name(&min_stat, &name);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/gssapi/test_kcred.c b/third_party/heimdal/lib/gssapi/test_kcred.c
new file mode 100644
index 0000000..abfe390
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/test_kcred.c
@@ -0,0 +1,198 @@
+/*
+ * Copyright (c) 2003-2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <roken.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
+#include <krb5.h>
+#include <err.h>
+#include <getarg.h>
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static void
+copy_import(void)
+{
+ gss_cred_id_t cred1, cred2;
+ OM_uint32 maj_stat, min_stat;
+ gss_name_t name1, name2;
+ OM_uint32 lifetime1, lifetime2;
+ gss_cred_usage_t usage1, usage2;
+ gss_OID_set mechs1, mechs2;
+ krb5_ccache id;
+ krb5_error_code ret;
+ krb5_context context;
+ int equal;
+
+ maj_stat = gss_acquire_cred(&min_stat, GSS_C_NO_NAME, GSS_C_INDEFINITE,
+ GSS_C_NO_OID_SET, GSS_C_INITIATE,
+ &cred1, NULL, NULL);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_acquire_cred");
+
+ maj_stat = gss_inquire_cred(&min_stat, cred1, &name1, &lifetime1,
+ &usage1, &mechs1);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_inquire_cred");
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_init_context");
+
+ ret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_new_unique");
+
+ maj_stat = gss_krb5_copy_ccache(&min_stat, cred1, id);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_krb5_copy_ccache");
+
+ maj_stat = gss_krb5_import_cred(&min_stat, id, NULL, NULL, &cred2);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_krb5_import_cred");
+
+ maj_stat = gss_inquire_cred(&min_stat, cred2, &name2, &lifetime2,
+ &usage2, &mechs2);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_inquire_cred 2");
+
+ maj_stat = gss_compare_name(&min_stat, name1, name2, &equal);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_compare_name");
+ if (!equal)
+ errx(1, "names not equal");
+
+ /*
+ * This check is racy! It tends to fail when run with valgrind.
+ *
+ * make check-valgrind sets TESTS_ENVIRONMENT in the environment...
+ */
+ if (getenv("TESTS_ENVIRONMENT") == NULL && lifetime1 != lifetime2)
+ errx(1, "lifetime not equal %lu != %lu",
+ (unsigned long)lifetime1, (unsigned long)lifetime2);
+ if (lifetime1 != lifetime2)
+ warnx("lifetime not equal %lu != %lu",
+ (unsigned long)lifetime1, (unsigned long)lifetime2);
+
+ if (usage1 != usage2) {
+ /* as long any of them is both are everything it ok */
+ if (usage1 != GSS_C_BOTH && usage2 != GSS_C_BOTH)
+ errx(1, "usages disjoined");
+ }
+
+ gss_release_name(&min_stat, &name2);
+ gss_release_oid_set(&min_stat, &mechs2);
+
+ maj_stat = gss_inquire_cred(&min_stat, cred2, &name2, &lifetime2,
+ &usage2, &mechs2);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_inquire_cred");
+
+ maj_stat = gss_compare_name(&min_stat, name1, name2, &equal);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_compare_name");
+ if (!equal)
+ errx(1, "names not equal");
+
+ /* This check is racy! */
+ if (getenv("TESTS_ENVIRONMENT") == NULL && lifetime1 != lifetime2)
+ errx(1, "lifetime not equal %lu != %lu",
+ (unsigned long)lifetime1, (unsigned long)lifetime2);
+ if (lifetime1 != lifetime2)
+ warnx("lifetime not equal %lu != %lu",
+ (unsigned long)lifetime1, (unsigned long)lifetime2);
+
+ gss_release_cred(&min_stat, &cred1);
+ gss_release_cred(&min_stat, &cred2);
+
+ gss_release_name(&min_stat, &name1);
+ gss_release_name(&min_stat, &name2);
+
+#if 0
+ compare(mechs1, mechs2);
+#endif
+
+ gss_release_oid_set(&min_stat, &mechs1);
+ gss_release_oid_set(&min_stat, &mechs2);
+
+ krb5_cc_destroy(context, id);
+ krb5_free_context(context);
+}
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag, "print version", NULL },
+ {"help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args),
+ NULL, "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ int optidx = 0;
+
+ setprogname(argv[0]);
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ copy_import();
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/gssapi/test_names.c b/third_party/heimdal/lib/gssapi/test_names.c
new file mode 100644
index 0000000..933635e
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/test_names.c
@@ -0,0 +1,675 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <roken.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
+#include <krb5_asn1.h>
+#include <err.h>
+#include <getarg.h>
+
+static void make_composite_name(CompositePrincipal *, gss_name_t *);
+static void assert_attr(gss_name_t, const char *, OM_uint32, gss_buffer_t,
+ const char *, int, int, int);
+static void assert_attr_unavail(gss_name_t, const char *);
+static void assert_attr_set(gss_name_t, gss_buffer_set_t);
+
+static void
+gss_print_errors(OM_uint32 stat, gss_OID mech)
+{
+ OM_uint32 junk;
+ OM_uint32 more = 0;
+ gss_buffer_desc buf = GSS_C_EMPTY_BUFFER;
+ OM_uint32 ret;
+
+ if (mech) {
+ junk = gss_oid_to_str(&junk, mech, &buf);
+ if (junk == GSS_S_COMPLETE)
+ fprintf(stderr, "mech = %.*s\n", (int)buf.length, (char *)buf.value);
+ gss_release_buffer(&junk, &buf);
+ }
+ do {
+ ret = gss_display_status(&junk,
+ stat,
+ mech ? GSS_C_MECH_CODE : GSS_C_GSS_CODE,
+ mech,
+ &more,
+ &buf);
+ if (ret != GSS_S_COMPLETE)
+ errx(1, "gss_display_status() failed");
+ fprintf(stderr, "%.*s\n", (int)buf.length, (char *)buf.value);
+ gss_release_buffer(&junk, &buf);
+ } while (more);
+}
+
+static void
+ __attribute__ ((__format__ (__printf__, 5, 6)))
+gss_err(int exitval,
+ OM_uint32 maj,
+ OM_uint32 min,
+ gss_OID mech,
+ const char *fmt, ...)
+{
+ va_list args;
+
+ va_start(args, fmt);
+ vwarnx(fmt, args);
+ va_end(args);
+ gss_print_errors(maj, GSS_C_NO_OID);
+ if (mech)
+ gss_print_errors(min, mech);
+ exit(exitval);
+}
+
+#define MAKE_URN(tail) \
+ { sizeof(GSS_KRB5_NAME_ATTRIBUTE_BASE_URN tail) - 1, \
+ GSS_KRB5_NAME_ATTRIBUTE_BASE_URN tail }
+
+/*
+ * Test RFC6680 name attributes for Kerberos.
+ */
+static void
+check_name_attrs(void)
+{
+ CompositePrincipal p;
+ EncTicketPart *t;
+ gss_buffer_desc v = GSS_C_EMPTY_BUFFER;
+ gss_name_t n;
+ OM_uint32 maj, min;
+ int32_t ret;
+ gss_buffer_desc attrs[] = {
+ MAKE_URN("realm"),
+ MAKE_URN("name-ncomp"),
+ MAKE_URN("name-ncomp#0"),
+ MAKE_URN("peer-realm"),
+ MAKE_URN("ticket-authz-data"),
+ MAKE_URN("transit-path"),
+ MAKE_URN("canonical-name"),
+ }; /* Set of attributes we expect to see indicated */
+ gss_buffer_set_desc attr_set;
+ size_t i, sz;
+
+ memset(&p, 0, sizeof(p));
+ attr_set.elements = attrs;
+ /*
+ * attr_set.count is set in each of the following sections to ever more
+ * items.
+ */
+
+ /*
+ * Testing name attributes is pretty tricky.
+ *
+ * Our approach is to construct a composite name, construct an exported
+ * composite name token for it, import it, then test the gss_inquire_name()
+ * and gss_get_name_attribute() accessors, and then gss_display_name_ext().
+ *
+ * Ideally we'd test the accessors on names imported from query forms with
+ * gss_import_name(), and on names from established contexts. However,
+ * that belongs in the test_context program.
+ *
+ * TODO: Implement and test gss_set_name_attribute() and
+ * gss_delete_name_attribute().
+ */
+
+ /* First construct and test an unauthenticated name */
+ p.realm = estrdup("TEST.H5L.SE");
+ p.name.name_type = KRB5_NT_PRINCIPAL;
+ p.name.name_string.val = ecalloc(1, sizeof(p.name.name_string.val[0]));
+ p.name.name_string.len = 1;
+ p.name.name_string.val[0] = estrdup("someuser");
+ p.nameattrs = NULL;
+ make_composite_name(&p, &n);
+
+ /* Test the attributes we expect it to have */
+ v.length = sizeof("TEST.H5L.SE") - 1;
+ v.value = "TEST.H5L.SE";
+ assert_attr(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "realm", GSS_S_COMPLETE,
+ &v, "TEST.H5L.SE", 0, 1, 0);
+
+ i = 1;
+ v.length = sizeof(size_t);
+ v.value = &i;
+ assert_attr(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "name-ncomp",
+ GSS_S_COMPLETE, &v, "1", 0, 1, 0);
+
+ v.length = sizeof("someuser") - 1;
+ v.value = "someuser";
+ assert_attr(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "name-ncomp#0",
+ GSS_S_COMPLETE, &v, "someuser", 0, 1, 0);
+
+ attr_set.count = 3;
+ assert_attr_set(n, &attr_set);
+
+ /* Check that it does not have prefixed attributes */
+ assert_attr_unavail(n, "whatever " GSS_KRB5_NAME_ATTRIBUTE_BASE_URN
+ "realm");
+ assert_attr_unavail(n, "whatever " GSS_KRB5_NAME_ATTRIBUTE_BASE_URN
+ "name-ncomp");
+ assert_attr_unavail(n, "whatever " GSS_KRB5_NAME_ATTRIBUTE_BASE_URN
+ "name-ncomp#0");
+ assert_attr_unavail(n, "what ever " GSS_KRB5_NAME_ATTRIBUTE_BASE_URN
+ "name-ncomp#0");
+
+ /* Check that it does not have various other supported attributes */
+ assert_attr_unavail(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "peer-realm");
+ assert_attr_unavail(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "name-ncomp#1");
+ assert_attr_unavail(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "canonical-name");
+ assert_attr_unavail(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN
+ "ticket-authz-data#pac");
+ assert_attr_unavail(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN
+ "ticket-authz-data");
+ assert_attr_unavail(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "transit-path");
+
+ /* Exercise URN parser */
+ assert_attr_unavail(n, "urn:whatever");
+ assert_attr_unavail(n, "urn:whatever#");
+ assert_attr_unavail(n, "urn:what#ever");
+ assert_attr_unavail(n, "#");
+ assert_attr_unavail(n, "#whatever");
+ assert_attr_unavail(n, "whatever");
+ assert_attr_unavail(n, "what ever");
+ assert_attr_unavail(n, "what ever#");
+
+ /* Now test an authenticated name */
+ gss_release_name(&min, &n);
+ p.nameattrs = ecalloc(1, sizeof(p.nameattrs[0]));
+ p.nameattrs->authenticated = 1;
+ make_composite_name(&p, &n);
+
+ v.length = sizeof("TEST.H5L.SE") - 1;
+ v.value = "TEST.H5L.SE";
+ assert_attr(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "realm", GSS_S_COMPLETE,
+ &v, "TEST.H5L.SE", 1, 1, 0);
+
+ i = 1;
+ v.length = sizeof(size_t);
+ v.value = &i;
+ assert_attr(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "name-ncomp",
+ GSS_S_COMPLETE, &v, "1", 1, 1, 0);
+
+ v.length = sizeof("someuser") - 1;
+ v.value = "someuser";
+ assert_attr(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "name-ncomp#0",
+ GSS_S_COMPLETE, &v, "someuser", 1, 1, 0);
+
+ assert_attr_set(n, &attr_set);
+
+ /* Now add a peer realm */
+ gss_release_name(&min, &n);
+ p.nameattrs->peer_realm = ecalloc(1, sizeof(p.nameattrs->peer_realm[0]));
+ p.nameattrs->peer_realm[0] = estrdup("FOO.TEST.H5L.SE");
+ make_composite_name(&p, &n);
+
+ v.length = sizeof("FOO.TEST.H5L.SE") - 1;
+ v.value = "FOO.TEST.H5L.SE";
+ assert_attr(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "peer-realm",
+ GSS_S_COMPLETE, &v, "FOO.TEST.H5L.SE", 1, 1, 0);
+ attr_set.count = 4;
+ assert_attr_set(n, &attr_set);
+
+ /* Now add canonical name and an authz-data element */
+ gss_release_name(&min, &n);
+ p.nameattrs->source = ecalloc(1, sizeof(p.nameattrs->source[0]));
+ p.nameattrs->source->element = choice_PrincipalNameAttrSrc_enc_ticket_part;
+
+ t = &p.nameattrs->source->u.enc_ticket_part;
+ t->cname.name_type = KRB5_NT_PRINCIPAL;
+ t->cname.name_string.val = ecalloc(1, sizeof(t->cname.name_string.val[0]));
+ t->crealm = estrdup("TEST.H5L.SE");
+ t->cname.name_string.len = 1;
+ t->cname.name_string.val[0] = estrdup("realusername");
+ t->authorization_data = ecalloc(1, sizeof(t->authorization_data[0]));
+ t->authorization_data->val =
+ ecalloc(1, sizeof(t->authorization_data->val[0]));
+ t->authorization_data->len = 1;
+ t->authorization_data->val[0].ad_type =
+ KRB5_AUTHDATA_ON_BEHALF_OF; /* whatever */
+ t->authorization_data->val[0].ad_data.data =
+ estrdup("foobar@TEST.H5L.SE");
+ t->authorization_data->val[0].ad_data.length =
+ sizeof("foobar@TEST.H5L.SE") - 1;
+ make_composite_name(&p, &n);
+
+ assert_attr(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "canonical-name",
+ GSS_S_COMPLETE, GSS_C_NO_BUFFER, "realusername@TEST.H5L.SE", 1,
+ 1, 0);
+
+ ASN1_MALLOC_ENCODE(AuthorizationData, v.value, v.length,
+ t->authorization_data, &sz, ret);
+ if (ret)
+ errx(1, "Failed to encode AuthorizationData");
+
+ assert_attr(n, GSS_KRB5_NAME_ATTRIBUTE_BASE_URN "ticket-authz-data",
+ GSS_S_COMPLETE, &v, NULL, 0, 1, 0);
+ free(v.value);
+
+ attr_set.count = 7;
+ assert_attr_set(n, &attr_set);
+
+ gss_release_name(&min, &n);
+ free_CompositePrincipal(&p);
+
+ /*
+ * Test gss_display_name_ext() with a host-based service principal
+ * "host/somehost.test.h5l.se@TEST.H5L.SE".
+ *
+ * Where gss_display_name() would display this as a Kerberos principal
+ * name, gss_display_name_ext() with GSS_C_NT_HOSTBASED_SERVICE should
+ * display it as "host@somehost.test.h5l.se".
+ */
+ p.realm = estrdup("TEST.H5L.SE");
+ p.name.name_type = KRB5_NT_SRV_HST;
+ p.name.name_string.val = ecalloc(2, sizeof(p.name.name_string.val[0]));
+ p.name.name_string.len = 2;
+ p.name.name_string.val[0] = estrdup("host");
+ p.name.name_string.val[1] = estrdup("somehost.test.h5l.se");
+ p.nameattrs = NULL;
+ make_composite_name(&p, &n);
+
+ maj = gss_display_name_ext(&min, n, GSS_C_NT_HOSTBASED_SERVICE, &v);
+ if (maj)
+ gss_err(1, maj, min, GSS_KRB5_MECHANISM, "display name ext");
+ if (v.length != sizeof("host@somehost.test.h5l.se") - 1 ||
+ strncmp(v.value, "host@somehost.test.h5l.se", v.length) != 0)
+ errx(1, "display name ext");
+ gss_release_buffer(&min, &v);
+ gss_release_name(&min, &n);
+ free_CompositePrincipal(&p);
+
+ /*
+ * TODO:
+ *
+ * - test URN fragments for access to specific authorization data element
+ * types
+ * - test GSS_C_ATTR_LOCAL_LOGIN_USER support (requires configuration or
+ * that we register a plugin here)
+ */
+}
+
+static int version_flag = 0;
+static int help_flag = 0;
+static int anon_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag, "print version", NULL },
+ {"anonymous", 0, arg_flag, &anon_flag, "test anonymous names", NULL },
+ {"help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args),
+ NULL, "service@host");
+ exit (ret);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ gss_buffer_desc name_buffer;
+ OM_uint32 maj_stat, min_stat;
+ gss_name_t name, MNname, MNname2;
+ int optidx = 0;
+ char *str;
+ int len, equal;
+ gss_OID mech_oid;
+
+ setprogname(argv[0]);
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ gsskrb5_set_default_realm("MIT.EDU");
+
+ /*
+ * test import/export
+ */
+
+ str = NULL;
+ len = asprintf(&str, anon_flag ?
+ "WELLKNOWN@ANONYMOUS" : "ftp@freeze-arrow.mit.edu");
+ if (len < 0 || str == NULL)
+ errx(1, "asprintf");
+
+ name_buffer.value = str;
+ name_buffer.length = len;
+
+ maj_stat = gss_import_name(&min_stat, &name_buffer,
+ GSS_C_NT_HOSTBASED_SERVICE,
+ &name);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, maj_stat, min_stat, GSS_C_NO_OID, "import name error");
+ free(str);
+
+ if (anon_flag)
+ mech_oid = GSS_SANON_X25519_MECHANISM;
+ else
+ mech_oid = GSS_KRB5_MECHANISM;
+
+ maj_stat = gss_canonicalize_name (&min_stat,
+ name,
+ mech_oid,
+ &MNname);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, maj_stat, min_stat, mech_oid, "canonicalize name error");
+
+ maj_stat = gss_export_name(&min_stat,
+ MNname,
+ &name_buffer);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, maj_stat, min_stat, mech_oid, "export name error");
+
+ /*
+ * Import the exported name and compare
+ */
+
+ maj_stat = gss_import_name(&min_stat, &name_buffer,
+ GSS_C_NT_EXPORT_NAME,
+ &MNname2);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, maj_stat, min_stat, mech_oid, "export name error");
+
+
+ maj_stat = gss_compare_name(&min_stat, MNname, MNname2, &equal);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, maj_stat, min_stat, mech_oid, "compare name error");
+ if (equal && anon_flag)
+ errx(1, "names %s equal", anon_flag ? "incorrectly" : "not");
+
+ gss_release_name(&min_stat, &MNname2);
+ gss_release_buffer(&min_stat, &name_buffer);
+ gss_release_name(&min_stat, &MNname);
+ gss_release_name(&min_stat, &name);
+
+ /*
+ * Import oid less name and compare to mech name.
+ * Dovecot SASL lib does this.
+ */
+
+ str = NULL;
+ len = asprintf(&str, "lha");
+ if (len < 0 || str == NULL)
+ errx(1, "asprintf");
+
+ name_buffer.value = str;
+ name_buffer.length = len;
+
+ maj_stat = gss_import_name(&min_stat, &name_buffer,
+ GSS_C_NO_OID,
+ &name);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, maj_stat, min_stat, NULL, "import (no oid) name error");
+
+ maj_stat = gss_import_name(&min_stat, &name_buffer,
+ GSS_KRB5_NT_USER_NAME,
+ &MNname);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, maj_stat, min_stat, NULL, "import (krb5 mn) name error");
+
+ free(str);
+
+ maj_stat = gss_compare_name(&min_stat, name, MNname, &equal);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "gss_compare_name");
+ if (!equal)
+ errx(1, "names not equal");
+
+ gss_release_name(&min_stat, &MNname);
+ gss_release_name(&min_stat, &name);
+
+#if 0
+ maj_stat = gss_canonicalize_name (&min_stat,
+ name,
+ GSS_SPNEGO_MECHANISM,
+ &MNname);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, maj_stat, min_stat, GSS_SPNEGO_MECHANISM,
+ "canonicalize name error");
+
+
+ maj_stat = gss_export_name(&maj_stat,
+ MNname,
+ &name_buffer);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, maj_stat, min_stat, GSS_SPNEGO_MECHANISM,
+ "export name error (SPNEGO)");
+
+ gss_release_name(&min_stat, &MNname);
+ gss_release_buffer(&min_stat, &name_buffer);
+#endif
+
+ if (anon_flag) {
+ /* check anonymous name canonicalizes to well known name */
+ gss_OID name_type;
+
+ name_buffer.length = 0;
+ name_buffer.value = NULL;
+
+ maj_stat = gss_import_name(&min_stat, &name_buffer,
+ GSS_C_NT_ANONYMOUS, &name);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, maj_stat, min_stat, GSS_C_NO_OID,
+ "import (anon) name error");
+
+ maj_stat = gss_canonicalize_name(&min_stat, name,
+ GSS_SANON_X25519_MECHANISM,
+ &MNname);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, maj_stat, min_stat, GSS_SANON_X25519_MECHANISM,
+ "canonicalize (anon) name error");
+
+ maj_stat = gss_display_name(&min_stat, MNname,
+ &name_buffer, &name_type);
+ if (maj_stat != GSS_S_COMPLETE)
+ gss_err(1, maj_stat, min_stat, GSS_SANON_X25519_MECHANISM,
+ "display_name (anon) name error");
+
+ if (!gss_oid_equal(name_type, GSS_C_NT_ANONYMOUS))
+ errx(1, "display name type not anonymous");
+ if (memcmp(name_buffer.value, "WELLKNOWN/ANONYMOUS@WELLKNOWN:ANONYMOUS",
+ sizeof("WELLKNOWN/ANONYMOUS@WELLKNOWN:ANONYMOUS") - 1) != 0)
+ errx(1, "display name string not well known anonymous name");
+
+ gss_release_name(&min_stat, &MNname);
+ gss_release_name(&min_stat, &name);
+ gss_release_buffer(&min_stat, &name_buffer);
+ }
+
+ check_name_attrs();
+ return 0;
+}
+
+/* Copied from _gsskrb5_export_name_composite() */
+static void
+export_name_composite(CompositePrincipal *name, gss_buffer_t exported_name)
+{
+ gss_buffer_desc inner = GSS_C_EMPTY_BUFFER;
+ unsigned char *buf;
+ int32_t ret;
+ size_t sz;
+
+ ASN1_MALLOC_ENCODE(CompositePrincipal, inner.value, inner.length,
+ (void *)name, &sz, ret);
+ if (ret)
+ errx(1, "Failed to encode exported composite name token");
+
+ exported_name->length = 10 + inner.length + GSS_KRB5_MECHANISM->length;
+ exported_name->value = malloc(exported_name->length);
+ if (exported_name->value == NULL)
+ errx(1, "Failed to allocate exported composite name token");
+
+ /* TOK, MECH_OID_LEN, DER(MECH_OID), NAME_LEN, NAME */
+
+ buf = exported_name->value;
+ buf[0] = 0x04;
+ buf[1] = 0x02;
+ buf[2] = ((GSS_KRB5_MECHANISM->length + 2) >> 8) & 0xff;
+ buf[3] = (GSS_KRB5_MECHANISM->length + 2) & 0xff;
+ buf[4] = 0x06;
+ buf[5] = (GSS_KRB5_MECHANISM->length) & 0xFF;
+
+ memcpy(buf + 6, GSS_KRB5_MECHANISM->elements, GSS_KRB5_MECHANISM->length);
+ buf += 6 + GSS_KRB5_MECHANISM->length;
+
+ buf[0] = (inner.length >> 24) & 0xff;
+ buf[1] = (inner.length >> 16) & 0xff;
+ buf[2] = (inner.length >> 8) & 0xff;
+ buf[3] = (inner.length) & 0xff;
+ buf += 4;
+
+ memcpy(buf, inner.value, inner.length);
+ free(inner.value);
+}
+
+static void
+make_composite_name(CompositePrincipal *princ, gss_name_t *n)
+{
+ gss_buffer_desc token, exported;
+ OM_uint32 maj, min;
+
+ export_name_composite(princ, &token);
+ maj = gss_import_name(&min, &token, GSS_C_NT_COMPOSITE_EXPORT, n);
+ if (maj)
+ gss_err(1, maj, min, GSS_KRB5_MECHANISM, "import composite name");
+ maj = gss_export_name_composite(&min, *n, &exported);
+ if (maj)
+ gss_err(1, maj, min, GSS_KRB5_MECHANISM, "export composite name");
+ if (token.length != exported.length ||
+ memcmp(token.value, exported.value, token.length) != 0)
+ errx(1, "import/export composite token disagreement");
+ gss_release_buffer(&min, &exported);
+ free(token.value); /* Use free because we allocated this one */
+}
+
+static void
+assert_attr(gss_name_t n,
+ const char *aname,
+ OM_uint32 exp_maj,
+ gss_buffer_t exp_v,
+ const char *exp_dv,
+ int exp_authenticated,
+ int exp_complete,
+ int exp_multivalued)
+{
+ gss_buffer_desc dv = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc v = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc a;
+ OM_uint32 maj, min;
+ int authenticated, complete, more;
+
+ a.value = (void*)(uintptr_t)aname;
+ a.length = strlen(aname);
+ more = 0;
+ maj = gss_get_name_attribute(&min, n, &a, &authenticated, &complete, &v,
+ &dv, &more);
+ if (maj != GSS_S_COMPLETE && maj != exp_maj)
+ gss_err(1, maj, min, GSS_KRB5_MECHANISM,
+ "import composite name error");
+ if (maj == GSS_S_COMPLETE && maj != exp_maj)
+ errx(1, "unexpected name attribute %s", aname);
+ if (maj == GSS_S_COMPLETE) {
+ if (exp_v &&
+ (v.length != exp_v->length ||
+ memcmp(v.value, exp_v->value, exp_v->length) != 0))
+ errx(1, "import composite name: wrong %s value", aname);
+ if (exp_dv &&
+ (dv.length != strlen(exp_dv) ||
+ strncmp(dv.value, exp_dv, dv.length) != 0))
+ errx(1, "import composite name: wrong %s display value "
+ "(wanted %s, got %.*s)", aname, exp_dv,
+ (int)dv.length, (char *)dv.value);
+ if (authenticated != exp_authenticated)
+ errx(1, "import composite name: %s incorrectly marked "
+ "%sauthenticated", aname, authenticated ? "" : "un");
+ if (complete != exp_complete)
+ errx(1, "import composite name: %s incorrectly marked "
+ "%scomplete", aname, complete ? "" : "in");
+ if (more != exp_multivalued)
+ errx(1, "import composite name: %s incorrectly marked "
+ "%s-valued", aname, more ? "multi" : "single");
+ }
+ gss_release_buffer(&min, &dv);
+ gss_release_buffer(&min, &v);
+}
+
+static void
+assert_attr_unavail(gss_name_t n, const char *aname)
+{
+ assert_attr(n, aname, GSS_S_UNAVAILABLE, GSS_C_NO_BUFFER, NULL, 0, 0, 0);
+}
+
+static void
+assert_attr_set(gss_name_t n, gss_buffer_set_t exp_as)
+{
+ OM_uint32 maj, min;
+ gss_buffer_set_t as = NULL;
+ gss_OID MN_mech = GSS_C_NO_OID;
+ size_t i;
+ int name_is_MN = 0;
+
+ maj = gss_inquire_name(&min, n, &name_is_MN, &MN_mech, &as);
+ if (maj)
+ gss_err(1, maj, min, MN_mech, "inquire name");
+ for (i = 0; i < as->count && i < exp_as->count; i++) {
+ if (as->elements[i].length != exp_as->elements[i].length ||
+ memcmp(as->elements[i].value, exp_as->elements[i].value,
+ as->elements[i].length) != 0)
+ errx(1, "attribute sets differ");
+ }
+ if (i < as->count)
+ errx(1, "more attributes indicated than expected");
+ if (i < exp_as->count)
+ errx(1, "fewer attributes indicated than expected");
+ gss_release_buffer_set(&min, &as);
+}
diff --git a/third_party/heimdal/lib/gssapi/test_negoex_mech.c b/third_party/heimdal/lib/gssapi/test_negoex_mech.c
new file mode 100644
index 0000000..559c5de
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/test_negoex_mech.c
@@ -0,0 +1,592 @@
+/*
+ * Copyright (C) 2019 by the Massachusetts Institute of Technology.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <roken.h>
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+
+#include <krb5.h>
+#include <der.h>
+#include <gssapi_asn1.h>
+
+#include <gssapi/gssapi.h>
+#include <gssapi/gssapi_spnego.h>
+
+struct test_context {
+ int initiator;
+ uint8_t hops; /* hops remaining; 0 means established */
+};
+
+OM_uint32 GSSAPI_CALLCONV
+gss_init_sec_context(OM_uint32 *minor_status,
+ gss_const_cred_id_t claimant_cred_handle,
+ gss_ctx_id_t *context_handle, gss_const_name_t target_name,
+ const gss_OID mech_type, OM_uint32 req_flags,
+ OM_uint32 time_req,
+ const gss_channel_bindings_t input_chan_bindings,
+ const gss_buffer_t input_token, gss_OID *actual_mech,
+ gss_buffer_t output_token, OM_uint32 *ret_flags,
+ OM_uint32 *time_rec)
+{
+ struct test_context *ctx = (struct test_context *)*context_handle;
+ OM_uint32 major;
+ gss_buffer_desc tok;
+ const char *envstr;
+ uint8_t hops, mech_last_octet;
+
+ if (actual_mech)
+ *actual_mech = GSS_C_NO_OID;
+ if (ret_flags)
+ *ret_flags = 0;
+ if (time_rec)
+ *time_rec = 0;
+
+ major = gss_duplicate_oid(minor_status, mech_type, actual_mech);
+ if (major != GSS_S_COMPLETE)
+ return major;
+
+ if (input_token == GSS_C_NO_BUFFER || input_token->length == 0) {
+ envstr = getenv("HOPS");
+ hops = (envstr != NULL) ? atoi(envstr) : 1;
+ assert(hops > 0);
+ } else if (input_token->length == 4 &&
+ memcmp(input_token->value, "fail", 4) == 0) {
+ *minor_status = 12345;
+ return GSS_S_FAILURE;
+ } else {
+ hops = ((uint8_t *)input_token->value)[0];
+ }
+
+ mech_last_octet = ((uint8_t *)mech_type->elements)[mech_type->length - 1];
+ envstr = getenv("INIT_FAIL");
+ if (envstr != NULL && atoi(envstr) == mech_last_octet)
+ return GSS_S_FAILURE;
+
+ if (ctx == NULL) {
+ ctx = malloc(sizeof(*ctx));
+ assert(ctx != NULL);
+ ctx->initiator = 1;
+ ctx->hops = hops;
+ *context_handle = (gss_ctx_id_t)ctx;
+ } else if (ctx != NULL) {
+ assert(ctx->initiator);
+ ctx->hops--;
+ assert(ctx->hops == hops);
+ }
+
+ if (ctx->hops > 0) {
+ /* Generate a token containing the remaining hop count. */
+ ctx->hops--;
+ tok.value = &ctx->hops;
+ tok.length = 1;
+ major = gss_encapsulate_token(&tok, mech_type, output_token);
+ assert(major == GSS_S_COMPLETE);
+ }
+
+ return (ctx->hops > 0) ? GSS_S_CONTINUE_NEEDED : GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+gss_accept_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle,
+ gss_const_cred_id_t verifier_cred_handle,
+ const gss_buffer_t input_token,
+ const gss_channel_bindings_t input_chan_bindings,
+ gss_name_t *src_name, gss_OID *mech_type,
+ gss_buffer_t output_token, OM_uint32 *ret_flags,
+ OM_uint32 *time_rec,
+ gss_cred_id_t *delegated_cred_handle)
+{
+ struct test_context *ctx = (struct test_context *)*context_handle;
+ uint8_t hops, mech_last_octet;
+ const char *envstr;
+ unsigned char mechbuf[64];
+ GSSAPIContextToken ct;
+ gss_OID_desc oid;
+ int ret;
+ size_t mech_len;
+
+ if (src_name)
+ *src_name = GSS_C_NO_NAME;
+ if (mech_type)
+ *mech_type = GSS_C_NO_OID;
+ if (ret_flags)
+ *ret_flags = 0;
+ if (time_rec)
+ *time_rec = 0;
+ if (delegated_cred_handle)
+ *delegated_cred_handle = GSS_C_NO_CREDENTIAL;
+
+ ret = decode_GSSAPIContextToken(input_token->value, input_token->length,
+ &ct, NULL);
+ if (ret == 0) {
+ ret = der_put_oid ((unsigned char *)mechbuf + sizeof(mechbuf) - 1,
+ sizeof(mechbuf),
+ &ct.thisMech,
+ &mech_len);
+ free_GSSAPIContextToken(&ct);
+ }
+ if (ret) {
+ *minor_status = ret;
+ return GSS_S_FAILURE;
+ }
+
+ oid.length = (OM_uint32)mech_len;
+ oid.elements = mechbuf + sizeof(mechbuf) - mech_len;
+
+ if (mech_type)
+ gss_duplicate_oid(minor_status, &oid, mech_type);
+
+ /*
+ * The unwrapped token sits at the end and is just one byte giving the
+ * remaining number of hops. The final octet of the mech encoding should
+ * be just prior to it.
+ */
+ assert(input_token->length >= 2);
+ hops = ((uint8_t *)input_token->value)[input_token->length - 1];
+ mech_last_octet = ((uint8_t *)input_token->value)[input_token->length - 2];
+
+ envstr = getenv("ACCEPT_FAIL");
+ if (envstr != NULL && atoi(envstr) == mech_last_octet) {
+ output_token->value = strdup("fail");
+ assert(output_token->value != NULL);
+ output_token->length = 4;
+ return GSS_S_FAILURE;
+ }
+
+ if (*context_handle == GSS_C_NO_CONTEXT) {
+ ctx = malloc(sizeof(*ctx));
+ assert(ctx != NULL);
+ ctx->initiator = 0;
+ ctx->hops = hops;
+ *context_handle = (gss_ctx_id_t)ctx;
+ } else {
+ assert(!ctx->initiator);
+ ctx->hops--;
+ assert(ctx->hops == hops);
+ }
+
+ if (ctx->hops > 0) {
+ /* Generate a token containing the remaining hop count. */
+ ctx->hops--;
+ output_token->value = malloc(1);
+ assert(output_token->value != NULL);
+ memcpy(output_token->value, &ctx->hops, 1);
+ output_token->length = 1;
+ }
+
+ return (ctx->hops > 0) ? GSS_S_CONTINUE_NEEDED : GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+gss_delete_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle,
+ gss_buffer_t output_token)
+{
+ free(*context_handle);
+ *context_handle = GSS_C_NO_CONTEXT;
+ return GSS_S_COMPLETE;
+}
+
+static int dummy_cred;
+
+OM_uint32 GSSAPI_CALLCONV
+gss_acquire_cred(OM_uint32 *minor_status, gss_const_name_t desired_name,
+ OM_uint32 time_req, const gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_cred_id_t *output_cred_handle, gss_OID_set *actual_mechs,
+ OM_uint32 *time_rec)
+{
+ *minor_status = 0;
+ *output_cred_handle = (gss_cred_id_t)&dummy_cred;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+gss_acquire_cred_with_password(OM_uint32 *minor_status,
+ gss_const_name_t desired_name,
+ const gss_buffer_t password, OM_uint32 time_req,
+ const gss_OID_set desired_mechs,
+ gss_cred_usage_t cred_usage,
+ gss_cred_id_t *output_cred_handle,
+ gss_OID_set *actual_mechs, OM_uint32 *time_rec)
+{
+ *minor_status = 0;
+ *output_cred_handle = (gss_cred_id_t)&dummy_cred;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+gss_release_cred(OM_uint32 *minor_status, gss_cred_id_t *cred_handle)
+{
+ return GSS_S_COMPLETE;
+}
+
+static int dummy_name;
+
+OM_uint32 GSSAPI_CALLCONV
+gss_import_name(OM_uint32 *minor_status, gss_buffer_t input_name_buffer,
+ gss_OID input_name_type, gss_name_t *output_name)
+{
+ /*
+ * We don't need to remember anything about names, but we do need to
+ * distinguish them from GSS_C_NO_NAME (to determine the direction of
+ * gss_query_meta_data() and gss_exchange_meta_data()), so assign an
+ * arbitrary data pointer.
+ */
+ *output_name = (gss_name_t)&dummy_name;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+gss_release_name(OM_uint32 *minor_status, gss_name_t *input_name)
+{
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+gss_display_status(OM_uint32 *minor_status, OM_uint32 status_value,
+ int status_type, gss_OID mech_type,
+ OM_uint32 *message_context, gss_buffer_t status_string)
+{
+ if (status_type == GSS_C_MECH_CODE && status_value == 12345) {
+ status_string->value = strdup("failure from acceptor");
+ assert(status_string->value != NULL);
+ status_string->length = strlen(status_string->value);
+ return GSS_S_COMPLETE;
+ }
+ return GSS_S_BAD_STATUS;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+gssspi_query_meta_data(OM_uint32 *minor_status, gss_const_OID mech_oid,
+ gss_cred_id_t cred_handle, gss_ctx_id_t *context_handle,
+ gss_const_name_t targ_name, OM_uint32 req_flags,
+ gss_buffer_t meta_data)
+{
+ const char *envstr;
+ uint8_t mech_last_octet;
+ int initiator = (targ_name != GSS_C_NO_NAME);
+
+ mech_last_octet = ((uint8_t *)mech_oid->elements)[mech_oid->length - 1];
+ envstr = getenv(initiator ? "INIT_QUERY_FAIL" : "ACCEPT_QUERY_FAIL");
+ if (envstr != NULL && atoi(envstr) == mech_last_octet)
+ return GSS_S_FAILURE;
+ envstr = getenv(initiator ? "INIT_QUERY_NONE" : "ACCEPT_QUERY_NONE");
+ if (envstr != NULL && atoi(envstr) == mech_last_octet)
+ return GSS_S_COMPLETE;
+
+ meta_data->value = strdup("X");
+ meta_data->length = 1;
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+gssspi_exchange_meta_data(OM_uint32 *minor_status, gss_const_OID mech_oid,
+ gss_cred_id_t cred_handle,
+ gss_ctx_id_t *context_handle,
+ gss_const_name_t targ_name, OM_uint32 req_flags,
+ gss_const_buffer_t meta_data)
+{
+ const char *envstr;
+ uint8_t mech_last_octet;
+ int initiator = (targ_name != GSS_C_NO_NAME);
+
+ mech_last_octet = ((uint8_t *)mech_oid->elements)[mech_oid->length - 1];
+ envstr = getenv(initiator ? "INIT_EXCHANGE_FAIL" : "ACCEPT_EXCHANGE_FAIL");
+ if (envstr != NULL && atoi(envstr) == mech_last_octet)
+ return GSS_S_FAILURE;
+
+ assert(meta_data->length == 1 && memcmp(meta_data->value, "X", 1) == 0);
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+gssspi_query_mechanism_info(OM_uint32 *minor_status, gss_const_OID mech_oid,
+ unsigned char auth_scheme[16])
+{
+ /* Copy the mech OID encoding and right-pad it with zeros. */
+ memset(auth_scheme, 0, 16);
+ assert(mech_oid->length <= 16);
+ memcpy(auth_scheme, mech_oid->elements, mech_oid->length);
+ return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
+gss_inquire_sec_context_by_oid(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_OID desired_object,
+ gss_buffer_set_t *data_set)
+{
+ struct test_context *ctx = (struct test_context *)context_handle;
+ OM_uint32 major;
+ uint8_t keybytes[32] = { 0 };
+ uint8_t typebytes[4];
+ gss_buffer_desc key, type;
+ const char *envstr;
+ int ask_verify;
+
+ if (gss_oid_equal(desired_object, GSS_C_INQ_NEGOEX_KEY))
+ ask_verify = 0;
+ else if (gss_oid_equal(desired_object, GSS_C_INQ_NEGOEX_VERIFY_KEY))
+ ask_verify = 1;
+ else
+ return GSS_S_UNAVAILABLE;
+
+ /*
+ * By default, make a key available only if the context is established.
+ * This can be overridden to "always", "init-always", "accept-always",
+ * or "never".
+ */
+ envstr = getenv("KEY");
+ if (envstr != NULL && strcmp(envstr, "never") == 0) {
+ return GSS_S_UNAVAILABLE;
+ } else if (ctx->hops > 0) {
+ if (envstr == NULL)
+ return GSS_S_UNAVAILABLE;
+ else if (strcmp(envstr, "init-always") == 0 && !ctx->initiator)
+ return GSS_S_UNAVAILABLE;
+ else if (strcmp(envstr, "accept-always") == 0 && ctx->initiator)
+ return GSS_S_UNAVAILABLE;
+ }
+
+ /* Perturb the key so that each side's verifier key is equal to the other's
+ * checksum key. */
+ keybytes[0] = ask_verify ^ ctx->initiator;
+
+ /* Supply an all-zeros aes256-sha1 negoex key. */
+ if (gss_oid_equal(desired_object, GSS_C_INQ_NEGOEX_KEY) ||
+ gss_oid_equal(desired_object, GSS_C_INQ_NEGOEX_VERIFY_KEY)) {
+ OM_uint32 n = ENCTYPE_AES256_CTS_HMAC_SHA1_96;
+
+ typebytes[0] = (n >> 0 ) & 0xFF;
+ typebytes[1] = (n >> 8 ) & 0xFF;
+ typebytes[2] = (n >> 16) & 0xFF;
+ typebytes[3] = (n >> 24) & 0xFF;
+
+ key.value = keybytes;
+ key.length = sizeof(keybytes);
+ type.value = typebytes;
+ type.length = sizeof(typebytes);
+ major = gss_add_buffer_set_member(minor_status, &key, data_set);
+ if (major != GSS_S_COMPLETE)
+ return major;
+ return gss_add_buffer_set_member(minor_status, &type, data_set);
+ }
+
+ return GSS_S_UNAVAILABLE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_process_context_token(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t token_buffer)
+{
+ return GSS_S_COMPLETE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_context_time(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ OM_uint32 *time_rec)
+{
+ *time_rec = 0;
+ return GSS_S_COMPLETE;
+}
+
+/*
+ * We also need to supply a fake MIC in case SPNEGO test negotiates
+ * as non-default mechanism
+ */
+#define FAKE_MIC "negoex-fake-mic"
+#define FAKE_MIC_LEN (sizeof(FAKE_MIC) - 1)
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_get_mic(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ gss_qop_t qop_req,
+ const gss_buffer_t message_buffer,
+ gss_buffer_t message_token)
+{
+ message_token->value = strdup(FAKE_MIC);
+ message_token->length = FAKE_MIC_LEN;
+
+ *minor_status = 0;
+ return GSS_S_COMPLETE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_verify_mic(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t message_buffer,
+ const gss_buffer_t token_buffer,
+ gss_qop_t *qop_state)
+{
+ *minor_status = 0;
+ if (token_buffer->length == FAKE_MIC_LEN &&
+ memcmp(token_buffer->value, FAKE_MIC, FAKE_MIC_LEN) == 0)
+ return GSS_S_COMPLETE;
+ else
+ return GSS_S_BAD_MIC;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_wrap(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ const gss_buffer_t input_message_buffer,
+ int *conf_state,
+ gss_buffer_t output_message_buffer)
+{
+ return GSS_S_UNAVAILABLE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_unwrap(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ const gss_buffer_t input_message_buffer,
+ gss_buffer_t output_message_buffer,
+ int *conf_state,
+ gss_qop_t *qop_state)
+{
+ return GSS_S_UNAVAILABLE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_compare_name(OM_uint32 *minor_status,
+ gss_const_name_t name1_arg,
+ gss_const_name_t name2_arg,
+ int *name_equal)
+{
+ return GSS_S_UNAVAILABLE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_display_name(OM_uint32 *minor_status,
+ gss_const_name_t input_name,
+ gss_buffer_t output_name_buffer,
+ gss_OID *output_name_type)
+{
+ return GSS_S_UNAVAILABLE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_export_name(OM_uint32 *minor_status,
+ gss_const_name_t input_name,
+ gss_buffer_t exported_name)
+{
+ return GSS_S_UNAVAILABLE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_context(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ gss_name_t *src_name,
+ gss_name_t *targ_name,
+ OM_uint32 *lifetime_rec,
+ gss_OID *mech_type,
+ OM_uint32 *ctx_flags,
+ int *locally_initiated,
+ int *xopen)
+{
+ *lifetime_rec = GSS_C_INDEFINITE;
+ return GSS_S_UNAVAILABLE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_wrap_size_limit(OM_uint32 *minor_status,
+ gss_const_ctx_id_t context_handle,
+ int conf_req_flag,
+ gss_qop_t qop_req,
+ OM_uint32 req_output_size,
+ OM_uint32 *max_input_size)
+{
+ return GSS_S_UNAVAILABLE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_import_sec_context(OM_uint32 *minor_status,
+ const gss_buffer_t interprocess_token,
+ gss_ctx_id_t *context_handle)
+{
+ return GSS_S_UNAVAILABLE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_export_sec_context(OM_uint32 *minor_status,
+ gss_ctx_id_t *context_handle,
+ gss_buffer_t interprocess_token)
+{
+ return GSS_S_UNAVAILABLE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_canonicalize_name(OM_uint32 *minor_status,
+ gss_const_name_t input_name,
+ const gss_OID mech_type,
+ gss_name_t *output_name)
+{
+ return GSS_S_UNAVAILABLE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_duplicate_name(OM_uint32 *minor_status,
+ gss_const_name_t src_name,
+ gss_name_t *dest_name)
+{
+ return GSS_S_UNAVAILABLE;
+}
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_cred(OM_uint32 *minor_status,
+ gss_const_cred_id_t cred_handle,
+ gss_name_t *name_ret,
+ OM_uint32 *lifetime,
+ gss_cred_usage_t *cred_usage,
+ gss_OID_set *mechanisms)
+{
+ if (name_ret)
+ *name_ret = (gss_name_t)&dummy_name;
+ if (lifetime)
+ *lifetime = GSS_C_INDEFINITE;
+ if (cred_usage)
+ *cred_usage = GSS_C_BOTH;
+ if (mechanisms)
+ *mechanisms = GSS_C_NO_OID_SET;
+
+ return GSS_S_COMPLETE;
+}
+
diff --git a/third_party/heimdal/lib/gssapi/test_ntlm.c b/third_party/heimdal/lib/gssapi/test_ntlm.c
new file mode 100644
index 0000000..de3a8dd
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/test_ntlm.c
@@ -0,0 +1,337 @@
+/*
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include <roken.h>
+#include <stdio.h>
+#include <gssapi.h>
+#include <err.h>
+#include <getarg.h>
+#include "test_common.h"
+
+#include <krb5.h>
+#include <heimntlm.h>
+
+static int
+test_libntlm_v1(int flags)
+{
+ const char *user = "foo",
+ *domain = "mydomain",
+ *password = "digestpassword";
+ OM_uint32 maj_stat, min_stat;
+ gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
+ gss_buffer_desc input, output;
+ struct ntlm_type1 type1;
+ struct ntlm_type2 type2;
+ struct ntlm_type3 type3;
+ struct ntlm_buf data;
+ krb5_error_code ret;
+ gss_name_t src_name = GSS_C_NO_NAME;
+
+ memset(&type1, 0, sizeof(type1));
+ memset(&type2, 0, sizeof(type2));
+ memset(&type3, 0, sizeof(type3));
+
+ type1.flags = NTLM_NEG_UNICODE|NTLM_NEG_TARGET|NTLM_NEG_NTLM|flags;
+ type1.domain = strdup(domain);
+ type1.hostname = NULL;
+ type1.os[0] = 0;
+ type1.os[1] = 0;
+
+ ret = heim_ntlm_encode_type1(&type1, &data);
+ if (ret)
+ errx(1, "heim_ntlm_encode_type1");
+
+ input.value = data.data;
+ input.length = data.length;
+
+ output.length = 0;
+ output.value = NULL;
+
+ maj_stat = gss_accept_sec_context(&min_stat,
+ &ctx,
+ GSS_C_NO_CREDENTIAL,
+ &input,
+ GSS_C_NO_CHANNEL_BINDINGS,
+ NULL,
+ NULL,
+ &output,
+ NULL,
+ NULL,
+ NULL);
+ free(data.data);
+ if (GSS_ERROR(maj_stat))
+ errx(1, "accept_sec_context v1: %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+
+ if (output.length == 0)
+ errx(1, "output.length == 0");
+
+ data.data = output.value;
+ data.length = output.length;
+
+ ret = heim_ntlm_decode_type2(&data, &type2);
+ if (ret)
+ errx(1, "heim_ntlm_decode_type2");
+
+ gss_release_buffer(&min_stat, &output);
+
+ type3.flags = type2.flags;
+ type3.username = rk_UNCONST(user);
+ type3.targetname = type2.targetname;
+ type3.ws = rk_UNCONST("workstation");
+
+ {
+ struct ntlm_buf key;
+
+ heim_ntlm_nt_key(password, &key);
+
+ heim_ntlm_calculate_ntlm1(key.data, key.length,
+ type2.challenge,
+ &type3.ntlm);
+
+ if (flags & NTLM_NEG_KEYEX) {
+ struct ntlm_buf sessionkey;
+ heim_ntlm_build_ntlm1_master(key.data, key.length,
+ &sessionkey,
+ &type3.sessionkey);
+ free(sessionkey.data);
+ }
+ free(key.data);
+ }
+
+ ret = heim_ntlm_encode_type3(&type3, &data, NULL);
+ if (ret)
+ errx(1, "heim_ntlm_encode_type3");
+
+ input.length = data.length;
+ input.value = data.data;
+
+ maj_stat = gss_accept_sec_context(&min_stat,
+ &ctx,
+ GSS_C_NO_CREDENTIAL,
+ &input,
+ GSS_C_NO_CHANNEL_BINDINGS,
+ &src_name,
+ NULL,
+ &output,
+ NULL,
+ NULL,
+ NULL);
+ free(input.value);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "accept_sec_context v1 2 %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+
+ gss_release_buffer(&min_stat, &output);
+ gss_delete_sec_context(&min_stat, &ctx, NULL);
+
+ if (src_name == GSS_C_NO_NAME)
+ errx(1, "no source name!");
+
+ gss_display_name(&min_stat, src_name, &output, NULL);
+
+ printf("src_name: %.*s\n", (int)output.length, (char*)output.value);
+
+ gss_release_name(&min_stat, &src_name);
+ gss_release_buffer(&min_stat, &output);
+
+ return 0;
+}
+
+static int
+test_libntlm_v2(int flags)
+{
+ const char *user = "foo",
+ *domain = "mydomain",
+ *password = "digestpassword";
+ OM_uint32 maj_stat, min_stat;
+ gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
+ gss_buffer_desc input, output;
+ struct ntlm_type1 type1;
+ struct ntlm_type2 type2;
+ struct ntlm_type3 type3;
+ struct ntlm_buf data;
+ krb5_error_code ret;
+
+ memset(&type1, 0, sizeof(type1));
+ memset(&type2, 0, sizeof(type2));
+ memset(&type3, 0, sizeof(type3));
+
+ type1.flags = NTLM_NEG_UNICODE|NTLM_NEG_NTLM|flags;
+ type1.domain = strdup(domain);
+ type1.hostname = NULL;
+ type1.os[0] = 0;
+ type1.os[1] = 0;
+
+ ret = heim_ntlm_encode_type1(&type1, &data);
+ if (ret)
+ errx(1, "heim_ntlm_encode_type1");
+
+ input.value = data.data;
+ input.length = data.length;
+
+ output.length = 0;
+ output.value = NULL;
+
+ maj_stat = gss_accept_sec_context(&min_stat,
+ &ctx,
+ GSS_C_NO_CREDENTIAL,
+ &input,
+ GSS_C_NO_CHANNEL_BINDINGS,
+ NULL,
+ NULL,
+ &output,
+ NULL,
+ NULL,
+ NULL);
+ free(data.data);
+ if (GSS_ERROR(maj_stat))
+ errx(1, "accept_sec_context v2 %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+
+ if (output.length == 0)
+ errx(1, "output.length == 0");
+
+ data.data = output.value;
+ data.length = output.length;
+
+ ret = heim_ntlm_decode_type2(&data, &type2);
+ if (ret)
+ errx(1, "heim_ntlm_decode_type2");
+
+ type3.flags = type2.flags;
+ type3.username = rk_UNCONST(user);
+ type3.targetname = type2.targetname;
+ type3.ws = rk_UNCONST("workstation");
+
+ {
+ struct ntlm_buf key;
+ unsigned char ntlmv2[16];
+
+ heim_ntlm_nt_key(password, &key);
+
+ heim_ntlm_calculate_ntlm2(key.data, key.length,
+ user,
+ type2.targetname,
+ type2.challenge,
+ &type2.targetinfo,
+ ntlmv2,
+ &type3.ntlm);
+ free(key.data);
+
+ if (flags & NTLM_NEG_KEYEX) {
+ struct ntlm_buf sessionkey;
+ heim_ntlm_build_ntlm1_master(ntlmv2, sizeof(ntlmv2),
+ &sessionkey,
+ &type3.sessionkey);
+ free(sessionkey.data);
+ }
+ }
+
+ ret = heim_ntlm_encode_type3(&type3, &data, NULL);
+ if (ret)
+ errx(1, "heim_ntlm_encode_type3");
+
+ input.length = data.length;
+ input.value = data.data;
+
+ maj_stat = gss_accept_sec_context(&min_stat,
+ &ctx,
+ GSS_C_NO_CREDENTIAL,
+ &input,
+ GSS_C_NO_CHANNEL_BINDINGS,
+ NULL,
+ NULL,
+ &output,
+ NULL,
+ NULL,
+ NULL);
+ free(input.value);
+ if (maj_stat != GSS_S_COMPLETE)
+ errx(1, "accept_sec_context v2 2 %s",
+ gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+
+ gss_delete_sec_context(&min_stat, &ctx, NULL);
+
+ return 0;
+}
+
+
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag, "print version", NULL },
+ {"help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args),
+ NULL, "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ int ret = 0, optidx = 0;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ ret += test_libntlm_v1(0);
+ ret += test_libntlm_v1(NTLM_NEG_KEYEX);
+
+ ret += test_libntlm_v2(0);
+ ret += test_libntlm_v2(NTLM_NEG_KEYEX);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/gssapi/test_oid.c b/third_party/heimdal/lib/gssapi/test_oid.c
new file mode 100644
index 0000000..ced8a05
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/test_oid.c
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <roken.h>
+#include <stdio.h>
+#include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
+#include <err.h>
+
+int
+main(int argc, char **argv)
+{
+ OM_uint32 minor_status, maj_stat;
+ gss_buffer_desc data;
+ int ret;
+
+ maj_stat = gss_oid_to_str(&minor_status, GSS_KRB5_MECHANISM, &data);
+ if (GSS_ERROR(maj_stat))
+ errx(1, "gss_oid_to_str failed");
+
+ ret = strncmp(data.value, "1 2 840 113554 1 2 2", data.length);
+ gss_release_buffer(&maj_stat, &data);
+ if (ret != 0)
+ return 1;
+
+ maj_stat = gss_oid_to_str(&minor_status, GSS_C_NT_EXPORT_NAME, &data);
+ if (GSS_ERROR(maj_stat))
+ errx(1, "gss_oid_to_str failed");
+
+ ret = strncmp(data.value, "1 3 6 1 5 6 4", data.length);
+ gss_release_buffer(&maj_stat, &data);
+ if (ret != 0)
+ return 1;
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/gssapi/version-script.map b/third_party/heimdal/lib/gssapi/version-script.map
new file mode 100644
index 0000000..7f482b5
--- /dev/null
+++ b/third_party/heimdal/lib/gssapi/version-script.map
@@ -0,0 +1,210 @@
+# $Id$
+
+HEIMDAL_GSS_2.0 {
+ global:
+# __gss_c_nt_anonymous;
+ __gss_c_nt_anonymous_oid_desc;
+ __gss_c_nt_composite_export_oid_desc;
+ __gss_c_nt_export_name_oid_desc;
+ __gss_c_nt_hostbased_service_oid_desc;
+ __gss_c_nt_hostbased_service_x_oid_desc;
+ __gss_c_nt_machine_uid_name_oid_desc;
+ __gss_c_nt_string_uid_name_oid_desc;
+ __gss_c_nt_user_name_oid_desc;
+ __gss_krb5_nt_principal_name_oid_desc;
+ __gss_c_attr_stream_sizes_oid_desc;
+ __gss_c_attr_local_login_user;
+ gss_accept_sec_context;
+ gss_acquire_cred;
+ gss_acquire_cred_from;
+ gss_acquire_cred_impersonate_name;
+ gss_acquire_cred_with_password;
+ gss_add_buffer_set_member;
+ gss_add_cred;
+ gss_add_cred_from;
+ gss_add_cred_with_password;
+ gss_add_oid_set_member;
+ gss_authorize_localname;
+ gss_canonicalize_name;
+ gss_compare_name;
+ gss_context_query_attributes;
+ gss_context_time;
+ gss_create_empty_buffer_set;
+ gss_create_empty_oid_set;
+ gss_decapsulate_token;
+ gss_delete_name_attribute;
+ gss_delete_sec_context;
+ gss_display_name;
+ gss_display_name_ext;
+ gss_display_status;
+ gss_duplicate_name;
+ gss_duplicate_oid;
+ gss_duplicate_oid_set;
+ gss_encapsulate_token;
+ gss_export_cred;
+ gss_export_name;
+ gss_export_name_composite;
+ gss_export_sec_context;
+ gss_get_mic;
+ gss_get_neg_mechs;
+ gss_get_name_attribute;
+ gss_import_cred;
+ gss_import_name;
+ gss_import_sec_context;
+ gss_indicate_mechs;
+ gss_init_sec_context;
+ gss_inquire_context;
+ gss_inquire_cred;
+ gss_inquire_cred_by_mech;
+ gss_inquire_cred_by_oid;
+ gss_inquire_mechs_for_name;
+ gss_inquire_name;
+ gss_inquire_names_for_mech;
+ gss_inquire_sec_context_by_oid;
+ gss_inquire_sec_context_by_oid;
+ gss_krb5_ccache_name;
+ gss_krb5_copy_ccache;
+ gss_krb5_export_lucid_sec_context;
+ gss_krb5_free_lucid_sec_context;
+ gss_krb5_get_tkt_flags;
+ gss_krb5_import_cred;
+ gss_krb5_set_allowable_enctypes;
+ gss_localname;
+ gss_mg_collect_error;
+ gss_oid_equal;
+ gss_oid_to_str;
+ gss_pname_to_uid;
+ gss_process_context_token;
+ gss_pseudo_random;
+ gss_release_buffer;
+ gss_release_buffer_set;
+ gss_release_cred;
+ gss_release_iov_buffer;
+ gss_release_name;
+ gss_release_oid;
+ gss_release_oid_set;
+ gss_seal;
+ gss_set_cred_option;
+ gss_set_name_attribute;
+ gss_set_log_function;
+ gss_set_neg_mechs;
+ gss_set_sec_context_option;
+ gss_sign;
+ gss_store_cred;
+ gss_store_cred_into;
+ gss_store_cred_into2;
+ gss_test_oid_set_member;
+ gss_unseal;
+ gss_unwrap;
+ gss_unwrap_aead;
+ gss_unwrap_iov;
+ gss_userok;
+ gss_verify;
+ gss_verify_mic;
+ gss_wrap;
+ gss_wrap_aead;
+ gss_wrap_iov;
+ gss_wrap_iov_length;
+ gss_wrap_size_limit;
+ gsskrb5_extract_authtime_from_sec_context;
+ gsskrb5_extract_authz_data_from_sec_context;
+ gsskrb5_extract_service_keyblock;
+ gsskrb5_get_initiator_subkey;
+ gsskrb5_get_subkey;
+ gsskrb5_get_time_offset;
+ gsskrb5_register_acceptor_identity;
+ gsskrb5_set_default_realm;
+ gsskrb5_set_dns_canonicalize;
+ gsskrb5_set_send_to_kdc;
+ gsskrb5_set_time_offset;
+ krb5_gss_register_acceptor_identity;
+ gss_display_mech_attr;
+ gss_inquire_attrs_for_mech;
+ gss_indicate_mechs_by_attrs;
+ gss_inquire_mech_for_saslname;
+ gss_inquire_saslname_for_mech;
+ gss_mo_get;
+ gss_mo_set;
+ gss_mo_list;
+ gss_mo_name;
+ gss_name_to_oid;
+ gss_oid_to_name;
+
+ # _gsskrb5cfx_ are really internal symbols, but export
+ # then now to make testing easier.
+ _gsskrb5cfx_wrap_length_cfx;
+ _gssapi_wrap_size_cfx;
+
+ __gss_krb5_copy_ccache_x_oid_desc;
+ __gss_krb5_get_tkt_flags_x_oid_desc;
+ __gss_krb5_extract_authz_data_from_sec_context_x_oid_desc;
+ __gss_krb5_compat_des3_mic_x_oid_desc;
+ __gss_krb5_register_acceptor_identity_x_oid_desc;
+ __gss_krb5_export_lucid_context_x_oid_desc;
+ __gss_krb5_export_lucid_context_v1_x_oid_desc;
+ __gss_krb5_set_dns_canonicalize_x_oid_desc;
+ __gss_krb5_get_subkey_x_oid_desc;
+ __gss_krb5_get_initiator_subkey_x_oid_desc;
+ __gss_krb5_get_acceptor_subkey_x_oid_desc;
+ __gss_krb5_send_to_kdc_x_oid_desc;
+ __gss_krb5_get_authtime_x_oid_desc;
+ __gss_krb5_get_service_keyblock_x_oid_desc;
+ __gss_krb5_set_allowable_enctypes_x_oid_desc;
+ __gss_krb5_set_default_realm_x_oid_desc;
+ __gss_krb5_ccache_name_x_oid_desc;
+ __gss_krb5_set_time_offset_x_oid_desc;
+ __gss_krb5_get_time_offset_x_oid_desc;
+ __gss_krb5_plugin_register_x_oid_desc;
+ __gss_ntlm_get_session_key_x_oid_desc;
+ __gss_c_nt_ntlm_oid_desc;
+ __gss_c_nt_dn_oid_desc;
+ __gss_krb5_nt_principal_name_referral_oid_desc;
+ __gss_c_ntlm_avguest_oid_desc;
+ __gss_c_ntlm_v1_oid_desc;
+ __gss_c_ntlm_v2_oid_desc;
+ __gss_c_ntlm_session_key_oid_desc;
+ __gss_c_ntlm_force_v1_oid_desc;
+ __gss_krb5_cred_no_ci_flags_x_oid_desc;
+ __gss_krb5_import_cred_x_oid_desc;
+ __gss_c_ma_sasl_mech_name_oid_desc;
+ __gss_c_ma_mech_name_oid_desc;
+ __gss_c_ma_mech_description_oid_desc;
+ __gss_sasl_digest_md5_mechanism_oid_desc;
+ __gss_krb5_mechanism_oid_desc;
+ __gss_ntlm_mechanism_oid_desc;
+ __gss_spnego_mechanism_oid_desc;
+ __gss_sanon_x25519_mechanism_oid_desc;
+ __gss_c_ma_mech_concrete_oid_desc;
+ __gss_c_ma_mech_pseudo_oid_desc;
+ __gss_c_ma_mech_composite_oid_desc;
+ __gss_c_ma_mech_nego_oid_desc;
+ __gss_c_ma_mech_glue_oid_desc;
+ __gss_c_ma_not_mech_oid_desc;
+ __gss_c_ma_deprecated_oid_desc;
+ __gss_c_ma_not_dflt_mech_oid_desc;
+ __gss_c_ma_itok_framed_oid_desc;
+ __gss_c_ma_auth_init_oid_desc;
+ __gss_c_ma_auth_targ_oid_desc;
+ __gss_c_ma_auth_init_init_oid_desc;
+ __gss_c_ma_auth_targ_init_oid_desc;
+ __gss_c_ma_auth_init_anon_oid_desc;
+ __gss_c_ma_auth_targ_anon_oid_desc;
+ __gss_c_ma_deleg_cred_oid_desc;
+ __gss_c_ma_integ_prot_oid_desc;
+ __gss_c_ma_conf_prot_oid_desc;
+ __gss_c_ma_mic_oid_desc;
+ __gss_c_ma_wrap_oid_desc;
+ __gss_c_ma_prot_ready_oid_desc;
+ __gss_c_ma_replay_det_oid_desc;
+ __gss_c_ma_oos_det_oid_desc;
+ __gss_c_ma_cbindings_oid_desc;
+ __gss_c_ma_pfs_oid_desc;
+ __gss_c_ma_compress_oid_desc;
+ __gss_c_ma_ctx_trans_oid_desc;
+ __gss_c_ma_negoex_and_spnego_oid_desc;
+ __gss_c_inq_negoex_key_oid_desc;
+ __gss_c_inq_negoex_verify_key_oid_desc;
+
+ local:
+ *;
+};
diff --git a/third_party/heimdal/lib/hcrypto/ChangeLog b/third_party/heimdal/lib/hcrypto/ChangeLog
new file mode 100644
index 0000000..1a32025
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/ChangeLog
@@ -0,0 +1,1227 @@
+2008-06-26 Love Hörnquist Åstrand <lha@kth.se>
+
+ * ui.c: Send newline from use to stderr, just like the
+ prompt. From Ted Percival.
+
+2008-05-20 Love Hörnquist Åstrand <lha@kth.se>
+
+ * rand-fortuna.c: If we forked, force a reseed again. Add the pid
+ as part of the reseed().
+
+2008-04-29 Björn Sandell <biorn@chalmers.se>
+
+ * des.h: Add DES_set_key_unchecked
+
+ * version-script.map: Export DES_set_key_unchecked
+
+2008-04-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * evp.c: EVP_MD_CTX_init already implemented.
+
+2008-04-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * evp.[ch]: deprecate functions that are needed for exported
+ EVP_MD_CTX.
+
+ * evp.h: Internalize hc_EVP_MD_CTX.
+
+ * evp.c: Internalize hc_EVP_MD_CTX.
+
+ * mdtest.c: Use EVP_MD_CTX_create()/EVP_MD_CTX_destroy().
+
+ * test_cipher.c: unbreak des-test
+
+ * evp.c: Fixup key parity before going ahead and using the key.
+
+ * evp.c: use DES_set_key_unchecked().
+
+ * des.c: Remove inifinite loop in DES_set_key().
+
+2008-04-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * des.c: Document missing functions, add DES_check_key_parity().
+
+ * des.h: Add DES_check_key_parity, deprecate DES_set_key.
+
+ * version-script.map: Export DES_check_key_parity.
+
+ * des.h: DES_set_odd_parity "returns" void.
+
+ * rand.c: Drop const warnings.
+
+ * des.h: Sort options.
+
+2008-04-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * pkcs5.c: Document PKCS5_PBKDF2_HMAC_SHA1.
+
+ * des.c: DES is withdrawn.
+
+ * des.c: Document using doxygen.
+
+ * des.c: History of DES.
+
+ * doxygen.c: History of hcrypto.
+
+ * test_rand.c: do a head vs tail test on the random buffer.
+
+ * test_crypto.in: Use --file to test_rand.
+
+ * rand.c: Document, implement RAND_set_rand_engine().
+
+ * doxygen.c: Add reference to DES, more quick links.
+
+ * rnd_keys.c: Reimplement using RAND_ interface.
+
+ * des.h: Undeprecate DES_new_random_key.
+
+ * des.c: Add documentation.
+
+2008-04-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * camellia-ntt.h: Move the typedef u<num> to camellia-ntt.h header
+ file. Use u32 to define KEY_TABLE_TYPE, avoids warning on
+ platfors where u32 is not unsigned int.
+
+ * camellia-ntt.c: Move the typedef u<num> to camellia-ntt.h
+ header file.
+
+ * camellia.h: Drop need to camellia-ntt.h by including some more
+ defines.
+
+2008-04-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rnd_keys.c: deprecated.
+
+ * des.h: c++ wrappers + deprecated.
+
+ * aes.h: c++ wrappers
+
+ * des.h: c++ wrappers + deprecated
+
+ * rnd_keys.c: Use matching prototypes, prompted by bug report by
+ David Rosenstrauch.
+
+2008-03-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * camellia.h: Drop unused defined that originates from aes.
+
+2008-01-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add extra files missing from dist.
+
+2007-12-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa.c: ENGINE_get_default_RSA can return NULL.
+
+ * dh.c: more doxygen.
+
+2007-12-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * evp.c: Add last of the doxygen documentation for functions in
+ this module.
+
+ * evp.c: complete the EVP_MD functions doxygen.
+
+2007-12-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * version-script.map: export RSA_gmp_method.
+
+ * doxygen.c: More documentation.
+
+ * rsa.h: add RSA_gmp_method
+
+ * rsa-gmp.c: RSA implementation written using GMP.
+
+ * test_dh.c: Test of DH by Matthias Koenig.
+
+2007-12-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * bn.h (BN_is_negative): make argument const.
+
+2007-12-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rand.c: Can't call getpwuid(getuid()) at all since that causes
+ recursive lookups. Pointed out by Hai Zaar.
+
+2007-08-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_cipher.c: Use test from camellia samples.
+
+ * version-script.map: Export camellia.
+
+ * test_cipher.c: Make camellia-128-cbc tests pass.
+
+2007-08-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_cipher.c: Sprinkle EVP cipher names.
+
+2007-07-30 David Love <fx@gnu.org>
+
+ * camellia-ntt.c: Include <krb5-types.h>
+
+2007-07-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Add Camellia.
+
+2007-07-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: New library version.
+
+2007-06-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hmac.c (HMAC_Init_ex): also zero out key material on re-init.
+
+2007-06-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rand.c: Default to fortuna due to weired /dev/*random that
+ failes to deliver random data for us in hi load situations.
+
+ * rand-fortuna.c: Reseed the random generator now and then from
+ external sources.
+
+2007-06-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rand-egd.c: Avoid stoping unrelated memory.
+
+2007-06-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rand-fortuna.c: Use /etc/shadow, not /dev/shadow, pointed out by
+ Andrew Bartlett
+
+ * Makefile.am: add rand-timer.c
+
+ * rand-fortuna.c: Fall back to gattering data from timer and
+ secret files, this is really the last resort.
+
+ * rand-timer.c: Pick up timing diffrences in the timeing info from
+ realtime timer, only in use as a last resort.
+
+ * version-script.map: Add hc_RAND_timer_method.
+
+2007-06-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_bn.c: Add <rand.h>.
+
+ * test_crypto.in: Test for random device before running the tests.
+
+ * test_engine_dso.c: Test for random device.
+
+ * test_bn.c (test_BN_rand): skip this test if there is no random
+ device
+
+2007-06-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Include more ui.[ch] in libbctest.
+
+ * version-script.map: Unexport _hc_DES_ipfp_test now there is a
+ separate test lib.
+
+ * Makefile.am: Build library libhctest.la for testing and link
+ with that when testing.
+
+ * version-script.map: export _hc_DES_ipfp_test
+
+2007-06-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * imath: new update from Michael Fromberger
+
+ * test_imath.c: Try to find ABR in mp_int_mul.
+
+ * engine.c: Don't try to load gmp module.
+
+2007-06-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_bn.c: Plug memory leak.
+
+2007-05-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * imath/imath.[ch]: New snapshot for Michael Fromberger, lets see if
+ this corrupts memory less.
+
+2007-05-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * version-script.map: Don't prefix all symbols with _
+
+2007-05-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_pkcs12.c: test the difference between "" and NULL password.
+
+ * test_pkcs12.c: one more pkcs12-pbe-s2k check
+
+2007-04-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Add version-script
+
+ * test_crypto.in: try generate a couple of rsa keys of
+ diffrent (random) sizes, spelling.
+
+ * test_rsa.c: try generate a couple of rsa keys of
+ diffrent (random) sizes.
+
+2007-04-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * mdtest.c: stop leaking memory
+
+ * test_imath.c: fix warnings, make test into function.
+
+ * test_imath.c: shortest program causing the problem.
+
+ * test_imath.c: basic imath test
+
+2007-04-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_cipher.c (test_cipher): avoid leaking memory
+
+2007-04-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa.c: plug memory leak
+
+2007-04-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: CLEANFILES += test.file
+
+2007-04-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add randi.h.
+
+2007-04-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa.c: spelling.
+
+2007-02-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rand.c: Name the random file ~/.rnd, this is the same as
+ OpenSSL.
+
+2007-01-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rand-egd.c: Make get_bytes static.
+
+ * rand.c (RAND_write_file): default to failure.
+
+2007-01-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rand.c: Implement RAND_file_name.
+
+ * test_rand.c: test RAND_file_name().
+
+ * rand.c: Provide dummy implementation of RAND_file_name.
+
+ * rand.h: add RAND_file_name
+
+2007-01-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: clean more files
+
+ * rand-egd.c: access private functions though the RAND_METHOD
+ switch, move global egd function to rand-egd.c
+
+ * rand-fortuna.c: access private functions though the RAND_METHOD
+ switch
+
+ * rand-unix.c: unexport private functions.
+
+ * randi.h: Unexport internal functions.
+
+ * rand.c: access private functions though the RAND_METHOD switch,
+ don't truncate the seed-file, move global egd function to
+ rand-egd.c
+
+ * test_crypto.in: add basic random tests
+
+ * rand-egd.c: SGI cc doesn' like return void_returning_function();
+ in a void returning function.
+
+2007-01-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_rand.c: Allow select rand method.
+
+ * rand-unix.c: expose _hc_rand_unix_status
+
+ * randi.h: expose _hc_rand_unix_status and the internal
+ RAND_METHODs
+
+ * rand.c: Implement RAND_load_file and RAND_write_file. Select
+ UNIX random device if available, otherwise use Fortuna.
+
+ * Add EGD/PRNGD support
+
+2007-01-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * fortuna: Add fortuna based on Marko Kreen's pgcrypt, no enabled yet
+
+2007-01-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_rsa.c: if RAND is unhappy, don't run the tests.
+
+ * test_engine_dso.c: if RAND is unhappy, don't run the tests.
+
+ * imath/imath.c: Update to imath-1.8 from Michael Fromberger
+
+ Fixed a bug in s_udiv() affecting the computation of quotient
+ digits. Thanks to Love Åstrand for isolating this bug. Also in
+ this release, defining USELLONG=Y or USELLONG=N on the command
+ line for make will switch support for the "long long" data type on
+ or off without having to edit the Makefile. The default is still
+ to permit use of "long long", even though the type is not standard
+ ANSI C90.
+
+ * imath/imath.c (s_udiv): Allocate one more for q, remove debug
+ printfs
+
+2007-01-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * imath/imath.c (s_udiv): make a copy of a and b before we start
+ to make sure there is something un-tainted to print in cause of
+ failure. XXX remove this delta
+ (s_embar): make static
+
+2007-01-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa.c: Correct the test if the rsa is a complete RSA private
+ key.
+
+2007-01-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * imath/imath.c: More verbose debugging in case of assertion
+ failure. XXX temporary for AIX problem.
+
+2007-01-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa-imath.c: Fix a silly typo, and with that enable CRT since
+ now it works.
+
+ * rsa-imath.c: With this crt works, but something is wrong in the
+ key generation, so keep it turned off for now.
+
+ * test_rsa.c: Allow testing effect of key-blinding
+
+ * test_rsa.c: Add timing info to rsa keygen.
+
+ * rsa-imath.c: don't include <imath/rsamath.h>
+
+2007-01-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * imath: prune off stuff we dont use
+
+ * imath/import.sh: Prune off stuff we don't use from imathsource
+
+ * Makefile.am: Prune off stuff we don't use from imathsource
+
+ * rsa-imath.c: Use mp_int_exptmod directly.
+
+ * imath/iprime.c: Use a larger table of small primes, cut down
+ genenration in best cases to half compared to using a small table.
+
+ * rsa.h: add RSA_FLAG_NO_BLINDING
+
+ * rsa-imath.c: Add keyblinding, add a commented out CRT based RSA.
+
+ * rsa.c: Add iqmp.
+
+2007-01-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa.c: add missing ;
+
+ * rsa.c: Add i2d_RSAPrivateKey.
+
+ * rsa.h: Add i2d_RSAPrivateKey.
+
+ * test_rsa.c: test RSA_generate_key_ex
+
+ * rsa-imath.c: Add imath_rsa_generate_key.
+
+2006-12-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa.c: add RSA_generate_key_ex
+
+ * rsa.h: add RSA_generate_key_ex
+
+2006-12-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: CLEANFILES += test_crypto
+
+2006-12-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add rsakey.der to EXTRA_DIST.
+
+2006-12-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add test_crypto.in to EXTRA_DIST.
+
+ * test_crypto.in: Add more spaces to allow sh to parse this
+
+ * test_rsa.c: Explain what the fixed "sha1" checksum test tries to
+ test.
+
+ * test_crypto.in: test rsa, dh and engine code
+
+2006-12-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: rsa and crypto engine test cases
+
+ * test_rsa.c: Make faster and less verbose
+
+ * rsakey.der: test rsa key
+
+ * test_rsa.c: Test rsa operations
+
+ * rsa-imath.c: Fix the rsa-decrypt failed case that been hauting
+ me for a while.
+
+2006-12-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa-imath.c: Use mp_int_to_binary to encode bignums
+
+ * rsa-imath.c: Check if header is there
+
+2006-11-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa-imath.c: Return -1 for failure.
+
+ * rsa-imath.c: Its ok with smaller signatures.
+
+ * rsa-imath.c: Split error codes for now
+
+2006-10-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa.c: Try to not leak memory.
+
+2006-10-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rand-unix.c (unix_bytes): read until the other side give us all
+ or fail.
+
+ * imath: import imath-1.7, fixes buffer overrun problems
+
+ * rsa.c (RSA_free): free the whole key
+
+ * test_engine_dso.c: Add more dh tests.
+
+2006-10-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * imath/imath.c: Allocate more bits.
+
+ * dh-imath.c (dh_compute_key): fix signness test
+
+ * dh-imath.c: Try harder to generate a good keypair.
+
+ * dh-imath.c: Return -1 dh_compute_key on failure, pointed out by
+ Olga Kornievskaia.
+
+2006-10-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add hash.h and des-tables.h.
+
+ * dh.c (DH_compute_key): return -1 on bad public key.
+
+ * rsa.c: remove stray ;
+
+ * engine.c: Does function typecasts instead of void * type-casts.
+
+ * evp.c: Does function typecasts instead of void * type-casts.
+
+2006-10-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add rand-unix.c
+
+ * rand.c: Move out rand-unix functions from the core lib.
+
+ * rand-unix.c: Move out rand-unix functions from the core lib.
+
+2006-10-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hmac.c (HMAC_CTX_cleanup): destroy the EVP_MD_CTX, so it will be
+ freed.
+
+2006-10-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * bn.c: Drop heim_any.h, prefix der primitives with der_
+
+ * rsa.c: Drop heim_any.h.
+
+2006-10-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa.c (RSA_free): Call the meth->finish before releasing the
+ engine.
+
+2006-10-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * imath/imath.c: Cast argument to ctype(3) functions to (unsigned
+ char).
+
+ * imath/imrat.c: Cast argument to ctype(3) functions to (unsigned
+ char).
+
+2006-09-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ui.c (read_string): Try to not call signaction for signal 0 and
+ use NSIG if it exists to determin how many signals there exists,
+ also, only restore those signalhandlers that we got out.
+
+ Bug reported by and patch tested by Harald Barth.
+
+2006-09-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa-imath.c: Add commeted out test that exponent is > 3
+
+2006-05-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * bn.c (BN_rand): avoid shadowing.
+
+2006-05-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa-imath.c: Fix the last one of the asserts.
+
+2006-05-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rand.c (get_device_fd): use /dev/urandom first.
+
+ * rctest.c: Less "pointer targets in passing argument differ in
+ signedness" warnings.
+
+ * rc2test.c: Less "pointer targets in passing argument differ in
+ signedness" warnings.
+
+2006-05-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa-imath.c: Fix a off by one.
+
+ * test_engine_dso.c: print the lengths when they don't match.
+
+ * engine.c (ENGINE_load_builtin_engines): use RSA_imath_method for
+ the building engine.
+
+ * rsa.h: expose RSA_imath_method
+
+ * rsa.c (RSA_check_key): Do sign/verify instead.
+
+ * dsa.c: rename the DSA_METHOD
+
+ * dh.c: rename the DH_METHOD
+
+ * dh-imath.c: rename the DH_METHOD
+
+ * rsa.c: Default to use rsa-imath.
+
+ * Makefile.am: Add rsa-imath.c to libhcrypto
+
+ * rsa-imath.c: Add RSA support using imath.
+
+2006-05-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * imath: Add imath-1.1.9
+
+ * dh.h: Expose DH_imath_method.
+
+ * Makefile.am: Add imath source, add test_engine_dso to TESTS.
+
+ * engine.c: Lets say we have RSA_null_method(), not really
+ useable, but still.
+
+ * test_engine_dso.c: If there are no arguments, use the internal
+ engine.
+
+ * engine.h: Cpp rename some ENGINE symbols.
+
+ * engine.c (ENGINE_load_builtin_engines): Load the internal
+ engine.
+
+ * dh.c: Default to use DH-imath.
+
+ * dh.c (DH_check_pubkey): describe what the function do
+
+2006-05-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * dh.c (DH_compute_key): check return status value from
+ DH_check_pubkey
+
+ * Rename u_intXX_t to uintXX_t
+
+2006-04-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * pkcs5.c: include <krb5-types.h>
+
+ * evp.c: Sprinkel some assertions.
+
+ * des.c: Move assertion and add another restriction, used as hint
+ to beam that its ok
+
+2006-04-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa.c (RSA_check_key): don't do any checking if there is no
+ private key
+
+ * engine.c (add_engine): reassign engines variable after realloc
+
+2006-04-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * evp.h: Add EVP_get_cipherbyname, unbreak EVP_BytesToKey
+
+ * evp.h: Add prototype for EVP_BytesToKey
+
+ * evp.c: Add stub for EVP_BytesToKey
+
+2006-04-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * dh.h: Add cpp-rename for DH_check_pubkey
+
+2006-04-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rand.h: Add more RAND functions.
+
+ * rand.c: Split out unix /dev/random to a RAND_METHOD
+
+ * engine.h: add RAND support
+
+ * engine.c: add RAND support
+
+ * evp.h: s/rc4_64/rc2_64/
+
+ * rand.c: Add RAND_METHOD and some associated functions.
+
+ * rand.h: Add RAND_METHOD and some associated functions.
+
+ * test_bn.c: Test BN_rand
+
+2006-04-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * engine.c (ENGINE_by_dso): less printf
+
+ * rsa.h (i2d_RSAPublicKey): fix prototype
+
+ * rsa.c (i2d_RSAPublicKey): fix prototype
+
+2006-04-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * evp.h: Add EVP_rc2_64_cbc
+
+ * evp.c: Add EVP_rc2_64_cbc
+
+ * evp.h: Add SHA-256 symbols.
+
+ * evp.c: Add SHA-256.
+
+ * sha.h: Add SHA-256 symbols.
+
+ * mdtest.c: Test SHA-256.
+
+ * sha256.c: Inital (naive) SHA-256 implementation.
+
+2006-04-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * des.c (DES_cfb64_encrypt): add asserts that the *num pointers is
+ >= 0, because if it is, its a programmer error.
+
+2006-04-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rc2.c (RC2_set_key): abort on erroneous input (len <= 0) size
+ that will case out out bound indexing, and its invalid input.
+
+ * rsa.c: Make compile again.
+
+2006-04-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rsa.c: Implement i2d_RSAPublicKey
+
+ * rsa.h: Add i2d_RSAPublicKey
+
+2006-03-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: EVP interface depends on dlopen, add it to LIBFLAGS
+
+2006-02-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add pkcs5 files.
+
+ * test_pkcs5.c: Testcases for pkcs5 pbe2.
+
+ * pkcs5.c (PKCS5_PBKDF2_HMAC_SHA1): new function.
+
+ * hmac.c: Digest key when it exceeds block size, not when it
+ exceeds the size of the output block.
+
+2006-02-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rand.c (RAND_bytes): Don't abort() on failure, return error.
+
+ * bn.c (BN_rand): check return value from RAND_bytes
+
+2006-01-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * dh.c (DH_compute_key): check public key
+
+ * dh.h: Add DH_check_pubkey and defines it uses.
+
+ * dh.c (DH_check_pubkey): New function.
+
+ * bn.c: Remove unused fragment.
+
+ * test_bn.c: Compare numbers with BN_cmp().
+
+2006-01-17 David Love <fx@gnu.org>
+
+ * bn.c: Include <limits.h>.
+
+2006-01-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * *.h: use #include <hcrypto/...>
+
+ * Makefile.am: provide a symlink so the directory hcrypto/ seems
+ to exists
+
+ * engine.h: Expose dsa symbols
+
+ * Makefile.am: Rename library to hcrypto and install headerfiles
+ in hcrypto/.
+
+ * test_pkcs12.c: Test for PKCS12_key_gen.
+
+ * hmac.h: Drop HMAC_CTX_create and HMAC_CTX_destroy.
+
+ * engine.c (ENGINE_add_conf_module): Also load DH
+
+ * dh.h: Reorder includes to avoid compile errors, provide
+ DH_new_method().
+
+ * dh.c: Indent.
+
+ * bn.c: BN_get_negative was really named BN_is_negative, a comment
+ confused me.
+
+ * bn.h: BN_get_negative was really named BN_is_negative, a comment
+ confused me.
+
+ * pkcs12.h: Add PKCS12_key_gen().
+
+ * pkcs12.c: Add PKCS12_key_gen().
+
+ * Makefile.am: Add test_cipher, test_pkcs12, add pkcs12.[ch].
+
+ * evp.c: Rename rc2_40_cbc internal variable to something better.
+ Unbreak des-ede3-cbc.
+
+2006-01-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_bn.c: Test BN_uadd.
+
+ * bn.c (BN_rand): don't leak memory on failure, catch malloc(0)
+ case
+
+ * bn.c (BN_rand): clear the bits above the bits that user
+ requested.
+ (BN_uadd): new function.
+
+ * bn.h (BN_uadd): new function.
+
+2006-01-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * evp.c (EVP_CIPHER_CTX_cleanup): clean up less aggressively
+
+ * Makefile.am (check_PROGRAMS): add test_hmac
+
+ * test_hmac.c: Simple regression test for HMAC.
+
+ * hmac.c: Make hmac work.
+
+ * evp.c: return the right blocksize for digests.
+
+2006-01-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_engine_dso.c: Add test for DH.
+
+ * dh.c: Add DH_new_method, add ENGINE refcounting.
+
+ * engine.[ch]: Add ENGINE_set_default_DH and ENGINE_get_default_DH
+
+ * test_engine_dso.c: Add test for RSA encryption.
+
+2006-01-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_engine_dso.c: Add test for RSA.
+
+ * implement enough glue to support OpenSSLs EVP, RSA, DSA, DH,
+ HMAC, RAND and ENGINE interfaces for use in hx509. rename all
+ symbols to start with hc_ to avoid clobbering namespaces. contains
+ no RSA/DH/DSA code, just glue to support using dynamic
+ ENGINE. hx509 supports this via pkcs11 and there is a gmp ENGINE
+ module supporting RSA. Also contains a MD2 digest for completion.
+
+2005-07-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * des.c,des.h,rnd_keys.c: change unsigned char * to void *
+
+2005-06-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rnd_keys.c: const poision for unwriteable strings
+
+2005-06-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * des.c,aes.c,rc2.c: Rename parameter, as encrypt shadows a
+ global, from Andrew Bartlett
+
+2005-06-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rnd_keys.c: Include <stdlib.h> for srandom/random.
+
+2005-05-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * des.c (DES_cbc_cksum): init u to make sure it have a value in
+ case of the empty in data
+
+ * destest.c: add test for the empty password ""
+
+2005-05-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rctest.c (cipher3): used unsigned char to avoid problems with
+ platforms using "signed char"
+
+2005-05-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rc2.c: use unsigned char to avoid signess warning
+
+ * des.c: use unsigned char to avoid signess warning
+
+ * aes.c (AES_cbc_encrypt): use unsigned char to avoid signess
+ warning
+
+2005-05-03 Dave Love <fx@gnu.org>
+
+ * mdtest.c: Fix typo for HAVE_STDLIB_H.
+
+2005-05-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rnd_keys.c: Enabled to build on cygwin, based on patch from
+ David Love <fx@gnu.org>
+
+2005-05-02 Dave Love <fx@gnu.org>
+
+ * mdtest.c: Include <krb5-types.h>.
+
+2005-04-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ui.c: Include <des.h>.
+ (UI_UTIL_read_pw_string): make the prompt argument const.
+
+ * des.h (UI_UTIL_read_pw_string): make the prompt argument const
+
+ * ui.c (UI_UTIL_read_pw_string): remove unused variable plen
+
+ * des.c: replace <strings.h> with <string.h>
+
+2005-04-29 Dave Love <fx@gnu.org>
+
+ * Makefile.am: Add LIB_roken.
+
+2005-04-27 Dave Love <fx@gnu.org>
+
+ * sha.c: Include hash.h first.
+
+ * md4.c: Include hash.h first.
+
+ * md5.c: Include hash.h first.
+
+ * hash.h: Include krb5-types.h
+
+2005-04-26 Dave Love <fx@gnu.org>
+
+ * mdtest.c: Maybe include stdlib.h
+
+2005-04-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * sha.h,md5.h, md4.h: don't include bit types, the user must do
+ that #ifdef wrap
+
+ * aes.h: #ifdef wrap
+
+2005-03-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * des.h: fix prototype for DES_random_key
+
+ * rnd_keys.c: fix prototype for DES_random_key
+
+ * des.[ch]: provide compatibility function DES_key_sched, same as
+ DES_set_key
+
+2005-03-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * destest.c: include config.h and protect some headers
+
+ * rnd_keys.c: move <des.h> to after include <krb5-types.h> so the
+ C99 integer types exists
+
+2005-03-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * des.c: add DES_set_key_checked
+
+ * des.h: add DES_set_key_checked
+
+2005-03-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * des-tables.h: Add the missing file
+
+2005-02-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ui.c: remove dependency on asprintf
+
+ * Makefile.am: make destest only once
+
+ * Replace the eay DES code with key scheule setup code by me and DES
+ s-box and p permutation from Richard Outerbridge implemtation (in
+ public domain). The DES modes are implemented by me. ui.c code are
+ from appl/login.
+
+ The implementation is about 3 times slower then Eric for encryption,
+ and about the same speed for key setup.
+
+
+2004-08-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rnd_keys.c (DES_rand_data): also try /dev/arandom
+
+2004-06-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rnd_keys.c: don't include krb4 headers
+
+ * rijndael-alg-fst.c: don't include krb4 headers
+
+ * aes.c: don't include krb4 headers
+
+ * aes.h: define AES_{EN,DE}CRYPT; remove #ifdefs, this is an
+ installed file
+
+2004-04-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rc2.c: handle non blocksized cbc messages
+
+ * aes.[ch]: add AES_cbc_encrypt
+
+2004-04-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rc2test.c: test vectors from RFC2268
+
+ * rc2.c (RC2_set_key): rewrite the mask calculation
+
+ * rc2.c (RC2_set_key): handle keys where effective bits are
+ diffrent from keylength
+
+2004-04-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rc2.c: rc2 implementation
+
+ * rc2.h: rc2 implementation
+
+ * rc2test.c: rc2 implementation
+
+ * Makefile.am: rc2 implementation
+
+2004-03-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: new arcfour implementation
+
+ * rc4.c: implemented from description in
+ draft-kaukonen-cipher-arcfour-03.txt
+
+ * rc4.h: replace with new implementation
+
+ * rc4_enc.c rc4_skey.c: remove
+
+ * rctest.c: test for arcfour
+
+2003-12-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rnd_keys.c: uninitialized variable, from Panasas Inc
+
+2003-09-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * md4.c (MD4_Final): make the function threadsafe by removing
+ static on the local variable zeros
+
+ * md5.c (MD5_Final): make the function threadsafe by removing
+ static on the local variable zeros
+
+ * switch to the DES_ api, dont provide any compat glue
+
+2003-08-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * sha.c: make the function threadsafe by removing static on the
+ local variable zeros
+
+2003-07-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rijndael-alg-fst.h,rijndael-alg-fst.c,aes.c,aes.h:
+ Makefile.am: add AES support
+
+2003-03-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * des.1: sunOS -> SunOS, from jmc <jmc@prioris.mini.pw.edu.pl>
+
+2003-03-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * des.1: spelling, from <jmc@prioris.mini.pw.edu.pl>
+
+2002-08-28 Johan Danielsson <joda@pdc.kth.se>
+
+ * read_pwd.c: move NeXT SGTTY stuff here
+
+2001-05-17 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 3:1:0
+
+2001-05-11 Assar Westerlund <assar@sics.se>
+
+ * str2key.c (des_string_to_key, des_string_to_2keys): avoid weak
+ keys
+
+2001-02-16 Assar Westerlund <assar@sics.se>
+
+ * set_key.c: correct weak keys and update comment
+
+2001-02-14 Assar Westerlund <assar@sics.se>
+
+ * set_key.c: correct the two last weak keys in accordance with
+ FIPS 74. noted by <jhutz@cmu.edu>
+
+2001-01-30 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libdes_la_LDFLAGS): bump version to 3:0:0
+
+2000-10-19 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (LIBSRC, LIBOBJ): add rc4* and enc_{read,write}
+ files so that this library contains the same things as libdes in
+ Heimdal
+
+2000-08-16 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 2:1:0
+
+2000-08-03 Johan Danielsson <joda@pdc.kth.se>
+
+ * enc_writ.c: BSIZE -> des_BSIZE to avoid conflicts with AIX
+ jfs/fsparam.h
+
+ * enc_read.c: BSIZE -> des_BSIZE to avoid conflicts with AIX
+ jfs/fsparam.h
+
+ * des_locl.h: BSIZE -> des_BSIZE to avoid conflicts with AIX
+ jfs/fsparam.h
+
+2000-02-07 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 2:0:0
+
+2000-01-26 Assar Westerlund <assar@sics.se>
+
+ * mdtest.c: update to pseudo-standard APIs for md4,md5,sha.
+ * md4.c, md4.h, md5.c, md5.h, sha.c, sha.h: move to the
+ pseudo-standard APIs
+
+1999-12-06 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 1:0:1
+
+1999-11-29 Assar Westerlund <assar@sics.se>
+
+ * fcrypt.c (crypt_md5): add trailing $
+
+1999-11-13 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (include_HEADERS): add rc4.h
+ (libdes_la_SOURCES): add rc4_skey.c
+
+1999-10-28 Assar Westerlund <assar@sics.se>
+
+ * md5crypt_test.c: change the test case. apparently we should not
+ include $ after the salt. also make it print more useful stuff
+ when failing.
+
+1999-10-20 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 0:2:0
+
+1999-09-21 Johan Danielsson <joda@pdc.kth.se>
+
+ * des.h: make this work with mips 64-bit abi
+
+1999-08-14 Johan Danielsson <joda@pdc.kth.se>
+
+ * fcrypt.c (crypt_md5): don't use snprintf
+
+1999-08-13 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: add md5crypt_test
+
+ * Makefile.in: add md5crypt_test
+
+ * md5crypt_test.c: test md5 crypt
+
+ * fcrypt.c: always enable md5 crypt
+
+1999-07-26 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: bump version number (changes to md*, sha)
+
+1999-06-15 Assar Westerlund <assar@sics.se>
+
+ * sha.c (swap_u_int32_t): add _CRAY
+
+Sat Apr 10 23:02:30 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * destest.c: fixes for crays
+
+Thu Apr 1 11:26:38 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: noinst_PROGRAMS -> check_PROGRAMS; add TESTS; don't
+ build rpw, and speed
+
+Mon Mar 22 20:16:26 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: hash.h
+
+ * sha.c: use hash.h; fixes for crays
+
+ * md5.c: use hash.h; fixes for crays
+
+ * md4.c: use hash.h; fixes for crays
+
+ * hash.h: common stuff from md4, md5, and sha1
+
+Sat Mar 20 00:16:53 1999 Assar Westerlund <assar@sics.se>
+
+ * rnd_keys.c (des_rand_data): move declaration to get rid of
+ warning
+
+Thu Mar 18 11:22:28 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: include Makefile.am.common
+
+Mon Mar 15 17:36:41 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * rnd_keys.c (des_rand_data): if not using setitimer, block
+ SIGCHLD around fork(), also make sure we get the status of the
+ child process
+ (fake_signal): emulate signal using sigaction
+
+Tue Jan 12 05:06:54 1999 Assar Westerlund <assar@sics.se>
+
+ * des.h: sparcv9 is also 64 bits, use `unsigned int' instead of
+ `unsigned long'
+
+Sun Nov 22 10:40:09 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (WFLAGS): set
+
+Mon May 25 05:24:56 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (clean): try to remove shared library debris
+
+Sun Apr 19 09:50:53 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in: add symlink magic for linux
+
+Sun Nov 9 07:14:45 1997 Assar Westerlund <assar@sics.se>
+
+ * mdtest.c: print out old and new string
+
diff --git a/third_party/heimdal/lib/hcrypto/DESperate.txt b/third_party/heimdal/lib/hcrypto/DESperate.txt
new file mode 100644
index 0000000..3d793e9
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/DESperate.txt
@@ -0,0 +1,108 @@
+The hunt for getting a DES with plain BSD license w/o advertisement clause
+==========================================================================
+
+$Id$
+
+This all feels very silly given that DES is about 30 years old and now
+is deprecated.
+
+Helpful documents on the way:
+
+Schider's crypto wasn't that useful since it only told how to do DES,
+not how to do des fast or how to not use DES. I find this to be a
+common thread in the book, it explain each tool in great detail, but
+not its limitations.
+
+Dag Arne Osvik: Efficient Implementation of the Data Encryption Standard
+
+Some threads on sci.crypto was also useful.
+
+PC1 transformations
+===================
+
+
+Getting the PC1 bit mangling working was hard, I never got it to work.
+
+Printning out the bit usage made me realize a lookup table could be
+used since only 12 bits are used from the first half and 16 from the
+second.
+
+01110000 01110000 01110000 01110000 01111000 01111000 01111000 01111000
+00001111 00001111 00001111 00001111 00000111 00000111 00000111 00000111
+
+The pattern is getting more obvious if it's printed out where the bits
+are coming from.
+
+ 8 16 24 - - - - -
+ 7 15 23 - - - - -
+ 6 14 22 - - - - -
+ 5 13 21 - - - - -
+ 4 12 20 28 - - - -
+ 3 11 19 27 - - - -
+ 2 10 18 26 - - - -
+ 1 9 17 25 - - - -
+
+ - - - 60 56 48 40 -
+ - - - 59 55 47 39 -
+ - - - 58 54 46 38 -
+ - - - 57 53 45 37 -
+ - - - - 52 44 36 -
+ - - - - 51 43 35 -
+ - - - - 50 42 34 -
+ - - - - 49 41 33 -
+
+Only 3 bits-table is needed for the first half and 4 bits for the
+second half because they are on diffrent shift offsets.
+
+So to get the bitpattern bit-pattern
+
+gen_pattern("pc1_c_3", 7, [ 5, 13, 21 ], 0, 0x1000000);
+gen_pattern("pc1_c_4", 15, [ 1, 9, 17, 25 ], 0, 0x1000000);
+gen_pattern("pc1_d_3", 7, [ 49, 41, 33 ], 32, 0x1000000);
+gen_pattern("pc1_d_4", 15, [ 57, 53, 45, 37 ], 32, 0x1000000);
+
+PC2 transformations
+===================
+
+PC2 is also a table lookup, since it's a 24 bit field, I use 4 6-bit
+lookup tables. Printing the reverse of the PC2 table reveal that some
+of the bits are not used, namely (9, 18, 22, 25) from c and (7, 10,
+15, 26) from d.
+
+pc2 from c
+----------
+
+ 5 24 7 16 6 10 20
+18 - 12 3 15 23 1
+ 9 19 2 - 14 22 11
+ - 13 4 - 17 21 8
+
+pc2 from d
+----------
+
+51 35 31 52 39 45 -
+50 32 - 43 36 29 48
+ - 41 38 47 33 40 42
+49 37 30 46 - 34 44
+
+So we generate tables for that too.
+
+gen_pattern("pc2_c_1", 63, [ 5, 24, 7, 16, 6, 10 ], 0, 0x800000);
+gen_pattern("pc2_c_2", 63, [ 20, 18, 12, 3, 15, 23 ], 0, 0x800000);
+gen_pattern("pc2_c_3", 63, [ 1, 9, 19, 2, 14, 22 ], 0, 0x800000);
+gen_pattern("pc2_c_4", 63, [ 11, 13, 4, 17, 21, 8 ], 0, 0x800000);
+
+gen_pattern("pc2_d_1", 63, [ 51, 35, 31, 52, 39, 45 ], 28, 0x800000);
+gen_pattern("pc2_d_2", 63, [ 50, 32, 43, 36, 29, 48 ], 28, 0x800000);
+gen_pattern("pc2_d_3", 63, [ 41, 38, 47, 33, 40, 42 ], 28, 0x800000);
+gen_pattern("pc2_d_4", 63, [ 49, 37, 30, 46, 34, 44 ], 28, 0x800000);
+
+
+SBOX transformations
+====================
+
+The SBOX transformations are 6 bit to 4 bit transformations.
+
+Here I grew tired and used Richard Outerbridge SBOXes. Thank you
+Richard.
+
diff --git a/third_party/heimdal/lib/hcrypto/Makefile.am b/third_party/heimdal/lib/hcrypto/Makefile.am
new file mode 100644
index 0000000..bb36f74
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/Makefile.am
@@ -0,0 +1,427 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+AUTOMAKE_OPTIONS = subdir-objects
+
+if HAVE_HCRYPTO_W_OPENSSL
+AM_CPPFLAGS += $(INCLUDE_openssl_crypto)
+endif
+
+AM_CPPFLAGS += -I$(top_srcdir)/lib/hx509 \
+ -I$(srcdir)/libtommath -DUSE_HCRYPTO_LTM=1 \
+ -I$(srcdir)/x25519 \
+ -I$(srcdir)/..
+
+WFLAGS += $(WFLAGS_LITE) -Wno-error=unused-function
+# XXX: Make these not necessary:
+WFLAGS += -Wno-error=unused-result -Wno-error=deprecated-declarations
+WFLAGS += $(WFLAGS_UNUSED_BUT_SET_VAR)
+
+lib_LTLIBRARIES = libhcrypto.la
+check_LTLIBRARIES = libhctest.la
+
+libhcrypto_la_LDFLAGS = -version-info 5:0:1
+libhcrypto_la_LIBADD = \
+ $(top_builddir)/lib/asn1/libasn1.la \
+ $(LIB_dlopen) \
+ $(LIB_heimbase) \
+ $(LIBADD_roken)
+
+if HAVE_HCRYPTO_W_OPENSSL
+libhcrypto_la_LIBADD += $(LIB_openssl_crypto)
+endif
+
+hcryptoincludedir = $(includedir)/hcrypto
+buildhcryptoinclude = $(buildinclude)/hcrypto
+
+hcryptoinclude_HEADERS = \
+ aes.h \
+ bn.h \
+ des.h \
+ dh.h \
+ dsa.h \
+ ec.h \
+ ecdh.h \
+ ecdsa.h \
+ engine.h \
+ evp.h \
+ evp-hcrypto.h \
+ evp-cc.h \
+ evp-openssl.h \
+ evp-pkcs11.h \
+ hmac.h \
+ md2.h \
+ md4.h \
+ md5.h \
+ pkcs12.h \
+ rand.h \
+ rc2.h \
+ rc4.h \
+ rsa.h \
+ sha.h \
+ ui.h \
+ undef.h
+
+install-build-headers:: $(hcryptoinclude_HEADERS) $(x25519include_HEADERS)
+ @foo='$(hcryptoinclude_HEADERS)'; \
+ for f in $$foo; do \
+ f=`basename $$f`; \
+ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \
+ else file="$$f"; fi; \
+ if cmp -s $$file $(buildhcryptoinclude)/$$f 2> /dev/null ; then \
+ : ; else \
+ echo "cp $$file $(buildhcryptoinclude)/$$f";\
+ cp $$file $(buildhcryptoinclude)/$$f; \
+ fi ; \
+ done
+
+PROGRAM_TESTS = \
+ destest \
+ mdtest \
+ rc2test \
+ rctest \
+ test_bn \
+ test_bulk \
+ test_cipher \
+ test_engine_dso \
+ test_hmac \
+ test_pkcs12 \
+ test_pkcs5
+
+libhctest_la_SOURCES = \
+ des-tables.h \
+ des.c \
+ des.h \
+ ui.c \
+ ui.h
+
+destest_LDADD = libhctest.la $(LIB_roken)
+
+SCRIPT_TESTS = \
+ test_crypto
+
+noinst_PROGRAMS = test_rand
+
+noinst_HEADERS = \
+ x25519/ed25519_ref10_fe_51.h \
+ x25519/ed25519_ref10_fe_25_5.h \
+ x25519/ed25519_ref10.h \
+ x25519/fe_25_5/base.h \
+ x25519/fe_25_5/base2.h \
+ x25519/fe_25_5/constants.h \
+ x25519/fe_25_5/fe.h \
+ x25519/fe_51/base.h \
+ x25519/fe_51/base2.h \
+ x25519/fe_51/constants.h \
+ x25519/fe_51/fe.h \
+ x25519/align.h \
+ x25519_ref10.h
+
+
+check_PROGRAMS = $(PROGRAM_TESTS) test_rsa test_dh example_evp_cipher
+check_SCRIPTS = $(SCRIPT_TESTS)
+
+TESTS = $(PROGRAM_TESTS) $(SCRIPT_TESTS)
+
+LDADD = $(lib_LTLIBRARIES) $(LIB_roken) $(LIB_openssl_crypto)
+test_rand_LDADD = $(LDADD) -lm
+
+libhcrypto_la_SOURCES = \
+ $(ltmsources) \
+ $(x25519sources)\
+ aes.c \
+ aes.h \
+ bn.c \
+ bn.h \
+ common.c \
+ common.h \
+ camellia.h \
+ camellia.c \
+ camellia-ntt.c \
+ camellia-ntt.h \
+ des-tables.h \
+ des.c \
+ des.h \
+ dh.c \
+ dh.h \
+ dh-ltm.c \
+ dsa.c \
+ dsa.h \
+ doxygen.c \
+ evp.c \
+ evp.h \
+ evp-hcrypto.c \
+ evp-cc.c \
+ evp-openssl.c \
+ evp-pkcs11.c \
+ engine.c \
+ engine.h \
+ hash.h \
+ hmac.c \
+ hmac.h \
+ md2.c \
+ md2.h \
+ md4.c \
+ md4.h \
+ md5.c \
+ md5.h \
+ pkcs5.c \
+ pkcs12.c \
+ rand-fortuna.c \
+ rand-timer.c \
+ rand-unix.c \
+ rand.c \
+ rand.h \
+ randi.h \
+ rc2.c \
+ rc2.h \
+ rc4.c \
+ rc4.h \
+ rijndael-alg-fst.c \
+ rijndael-alg-fst.h \
+ rnd_keys.c \
+ rsa.c \
+ rsa-gmp.c \
+ rsa-ltm.c \
+ rsa.h \
+ sha.c \
+ sha.h \
+ sha256.c \
+ sha512.c \
+ validate.c \
+ ui.c \
+ ui.h \
+ undef.h
+
+ltmsources = \
+ libtommath/bn_cutoffs.c \
+ libtommath/bn_deprecated.c \
+ libtommath/bn_mp_2expt.c \
+ libtommath/bn_mp_abs.c \
+ libtommath/bn_mp_add.c \
+ libtommath/bn_mp_add_d.c \
+ libtommath/bn_mp_addmod.c \
+ libtommath/bn_mp_and.c \
+ libtommath/bn_mp_clamp.c \
+ libtommath/bn_mp_clear.c \
+ libtommath/bn_mp_clear_multi.c \
+ libtommath/bn_mp_cmp.c \
+ libtommath/bn_mp_cmp_d.c \
+ libtommath/bn_mp_cmp_mag.c \
+ libtommath/bn_mp_cnt_lsb.c \
+ libtommath/bn_mp_complement.c \
+ libtommath/bn_mp_copy.c \
+ libtommath/bn_mp_count_bits.c \
+ libtommath/bn_mp_decr.c \
+ libtommath/bn_mp_div.c \
+ libtommath/bn_mp_div_2.c \
+ libtommath/bn_mp_div_2d.c \
+ libtommath/bn_mp_div_3.c \
+ libtommath/bn_mp_div_d.c \
+ libtommath/bn_mp_dr_is_modulus.c \
+ libtommath/bn_mp_dr_reduce.c \
+ libtommath/bn_mp_dr_setup.c \
+ libtommath/bn_mp_error_to_string.c \
+ libtommath/bn_mp_exch.c \
+ libtommath/bn_mp_expt_u32.c \
+ libtommath/bn_mp_exptmod.c \
+ libtommath/bn_mp_exteuclid.c \
+ libtommath/bn_mp_fread.c \
+ libtommath/bn_mp_from_sbin.c \
+ libtommath/bn_mp_from_ubin.c \
+ libtommath/bn_mp_fwrite.c \
+ libtommath/bn_mp_gcd.c \
+ libtommath/bn_mp_get_double.c \
+ libtommath/bn_mp_get_i32.c \
+ libtommath/bn_mp_get_i64.c \
+ libtommath/bn_mp_get_l.c \
+ libtommath/bn_mp_get_ll.c \
+ libtommath/bn_mp_get_mag_u32.c \
+ libtommath/bn_mp_get_mag_u64.c \
+ libtommath/bn_mp_get_mag_ul.c \
+ libtommath/bn_mp_get_mag_ull.c \
+ libtommath/bn_mp_grow.c \
+ libtommath/bn_mp_incr.c \
+ libtommath/bn_mp_init.c \
+ libtommath/bn_mp_init_copy.c \
+ libtommath/bn_mp_init_i32.c \
+ libtommath/bn_mp_init_i64.c \
+ libtommath/bn_mp_init_l.c \
+ libtommath/bn_mp_init_ll.c \
+ libtommath/bn_mp_init_multi.c \
+ libtommath/bn_mp_init_set.c \
+ libtommath/bn_mp_init_size.c \
+ libtommath/bn_mp_init_u32.c \
+ libtommath/bn_mp_init_u64.c \
+ libtommath/bn_mp_init_ul.c \
+ libtommath/bn_mp_init_ull.c \
+ libtommath/bn_mp_invmod.c \
+ libtommath/bn_mp_is_square.c \
+ libtommath/bn_mp_iseven.c \
+ libtommath/bn_mp_isodd.c \
+ libtommath/bn_mp_kronecker.c \
+ libtommath/bn_mp_lcm.c \
+ libtommath/bn_mp_log_u32.c \
+ libtommath/bn_mp_lshd.c \
+ libtommath/bn_mp_mod.c \
+ libtommath/bn_mp_mod_2d.c \
+ libtommath/bn_mp_mod_d.c \
+ libtommath/bn_mp_montgomery_calc_normalization.c \
+ libtommath/bn_mp_montgomery_reduce.c \
+ libtommath/bn_mp_montgomery_setup.c \
+ libtommath/bn_mp_mul.c \
+ libtommath/bn_mp_mul_2.c \
+ libtommath/bn_mp_mul_2d.c \
+ libtommath/bn_mp_mul_d.c \
+ libtommath/bn_mp_mulmod.c \
+ libtommath/bn_mp_neg.c \
+ libtommath/bn_mp_or.c \
+ libtommath/bn_mp_pack.c \
+ libtommath/bn_mp_pack_count.c \
+ libtommath/bn_mp_prime_fermat.c \
+ libtommath/bn_mp_prime_frobenius_underwood.c \
+ libtommath/bn_mp_prime_is_prime.c \
+ libtommath/bn_mp_prime_miller_rabin.c \
+ libtommath/bn_mp_prime_next_prime.c \
+ libtommath/bn_mp_prime_rabin_miller_trials.c \
+ libtommath/bn_mp_prime_rand.c \
+ libtommath/bn_mp_prime_strong_lucas_selfridge.c \
+ libtommath/bn_mp_radix_size.c \
+ libtommath/bn_mp_radix_smap.c \
+ libtommath/bn_mp_rand.c \
+ libtommath/bn_mp_read_radix.c \
+ libtommath/bn_mp_reduce.c \
+ libtommath/bn_mp_reduce_2k.c \
+ libtommath/bn_mp_reduce_2k_l.c \
+ libtommath/bn_mp_reduce_2k_setup.c \
+ libtommath/bn_mp_reduce_2k_setup_l.c \
+ libtommath/bn_mp_reduce_is_2k.c \
+ libtommath/bn_mp_reduce_is_2k_l.c \
+ libtommath/bn_mp_reduce_setup.c \
+ libtommath/bn_mp_root_u32.c \
+ libtommath/bn_mp_rshd.c \
+ libtommath/bn_mp_sbin_size.c \
+ libtommath/bn_mp_set.c \
+ libtommath/bn_mp_set_double.c \
+ libtommath/bn_mp_set_i32.c \
+ libtommath/bn_mp_set_i64.c \
+ libtommath/bn_mp_set_l.c \
+ libtommath/bn_mp_set_ll.c \
+ libtommath/bn_mp_set_u32.c \
+ libtommath/bn_mp_set_u64.c \
+ libtommath/bn_mp_set_ul.c \
+ libtommath/bn_mp_set_ull.c \
+ libtommath/bn_mp_shrink.c \
+ libtommath/bn_mp_signed_rsh.c \
+ libtommath/bn_mp_sqr.c \
+ libtommath/bn_mp_sqrmod.c \
+ libtommath/bn_mp_sqrt.c \
+ libtommath/bn_mp_sqrtmod_prime.c \
+ libtommath/bn_mp_sub.c \
+ libtommath/bn_mp_sub_d.c \
+ libtommath/bn_mp_submod.c \
+ libtommath/bn_mp_to_radix.c \
+ libtommath/bn_mp_to_sbin.c \
+ libtommath/bn_mp_to_ubin.c \
+ libtommath/bn_mp_ubin_size.c \
+ libtommath/bn_mp_unpack.c \
+ libtommath/bn_mp_xor.c \
+ libtommath/bn_mp_zero.c \
+ libtommath/bn_prime_tab.c \
+ libtommath/bn_s_mp_add.c \
+ libtommath/bn_s_mp_balance_mul.c \
+ libtommath/bn_s_mp_exptmod.c \
+ libtommath/bn_s_mp_exptmod_fast.c \
+ libtommath/bn_s_mp_get_bit.c \
+ libtommath/bn_s_mp_invmod_fast.c \
+ libtommath/bn_s_mp_invmod_slow.c \
+ libtommath/bn_s_mp_karatsuba_mul.c \
+ libtommath/bn_s_mp_karatsuba_sqr.c \
+ libtommath/bn_s_mp_montgomery_reduce_fast.c \
+ libtommath/bn_s_mp_mul_digs.c \
+ libtommath/bn_s_mp_mul_digs_fast.c \
+ libtommath/bn_s_mp_mul_high_digs.c \
+ libtommath/bn_s_mp_mul_high_digs_fast.c \
+ libtommath/bn_s_mp_prime_is_divisible.c \
+ libtommath/bn_s_mp_rand_jenkins.c \
+ libtommath/bn_s_mp_rand_platform.c \
+ libtommath/bn_s_mp_reverse.c \
+ libtommath/bn_s_mp_sqr.c \
+ libtommath/bn_s_mp_sqr_fast.c \
+ libtommath/bn_s_mp_sub.c \
+ libtommath/bn_s_mp_toom_mul.c \
+ libtommath/bn_s_mp_toom_sqr.c \
+ libtommath/tommath_private.h \
+ libtommath/tommath_cutoffs.h \
+ libtommath/tommath_superclass.h \
+ libtommath/tommath_class.h \
+ libtommath/tommath.h
+
+x25519sources = \
+ x25519/ed25519_ref10.c \
+ x25519/x25519_ref10.c
+
+$(libhcrypto_la_OBJECTS) $(test_rand_OBJECTS): hcrypto-link
+
+libhcrypto_la_CPPFLAGS = -DBUILD_HCRYPTO_LIB $(AM_CPPFLAGS)
+
+if versionscript
+libhcrypto_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+endif
+$(libhcrypto_la_OBJECTS): $(srcdir)/version-script.map
+
+
+hcrypto-link:
+ $(LN_S) $(srcdir)/../hcrypto hcrypto
+ touch hcrypto-link
+
+do_subst = sed -e 's,[@]srcdir[@],$(srcdir),g' -e 's,[@]exeext[@],$(exeext),g'
+
+test_crypto: test_crypto.in Makefile
+ $(do_subst) < $(srcdir)/test_crypto.in > test_crypto.tmp
+ chmod +x test_crypto.tmp
+ mv test_crypto.tmp test_crypto
+
+CLEANFILES = \
+ crypto-test \
+ crypto-test2 \
+ error \
+ hcrypto \
+ hcrypto-link \
+ test.file \
+ test_crypto \
+ test-out* \
+ test_crypto.tmp \
+ test_crypto.tmp
+
+EXTRA_DIST = \
+ NTMakefile \
+ DESperate.txt \
+ passwd_dialog.rc \
+ libhcrypto-exports.def \
+ dh-tfm.c \
+ ec.h \
+ ecdh.h \
+ ecdsa.h \
+ evp-crypt.c \
+ evp-w32.c \
+ evp-w32.h \
+ evp-wincng.c \
+ evp-wincng.h \
+ gen-des.pl \
+ md5crypt_test.c \
+ passwd_dialog.aps \
+ passwd_dialog.clw \
+ passwd_dialog.rc \
+ passwd_dialog.res \
+ passwd_dlg.c \
+ passwd_dlg.h \
+ rand-w32.c \
+ resource.h \
+ rsa-tfm.c \
+ rsakey.der \
+ rsakey2048.der \
+ rsakey4096.der \
+ test_crypto.in \
+ version-script.map
diff --git a/third_party/heimdal/lib/hcrypto/NTMakefile b/third_party/heimdal/lib/hcrypto/NTMakefile
new file mode 100644
index 0000000..ec94500
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/NTMakefile
@@ -0,0 +1,274 @@
+########################################################################
+#
+# Copyright (c) 2009-2016, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+SUBDIRS=libtommath x25519
+
+RELDIR=lib\hcrypto
+
+!include ../../windows/NTMakefile.w32
+
+HCRYPTOINCLUDEDIR = $(INCDIR)\hcrypto
+
+HEIMBASEDIR = $(SRC)\lib\base
+
+HX509DIR = $(SRC)\lib\hx509
+
+!ifdef INCLUDE_openssl_crypto
+openssl_inc=-I$(INCLUDE_openssl_crypto)
+!endif
+
+intcflags=-DKRB5 -DASN1_LIB -I$(HCRYPTOINCLUDEDIR) -DUSE_HCRYPTO_LTM=1 \
+ -I$(HX509DIR) $(openssl_inc)
+
+# Do dependencies first
+
+all:: subdirs
+
+clean:: clean-subdirs
+
+test:: test-subdirs
+
+# Include files
+
+INCFILES= \
+ $(HCRYPTOINCLUDEDIR)\aes.h \
+ $(HCRYPTOINCLUDEDIR)\bn.h \
+ $(HCRYPTOINCLUDEDIR)\des.h \
+ $(HCRYPTOINCLUDEDIR)\dh.h \
+ $(HCRYPTOINCLUDEDIR)\dsa.h \
+ $(HCRYPTOINCLUDEDIR)\ec.h \
+ $(HCRYPTOINCLUDEDIR)\ecdh.h \
+ $(HCRYPTOINCLUDEDIR)\ecdsa.h \
+ $(HCRYPTOINCLUDEDIR)\engine.h \
+ $(HCRYPTOINCLUDEDIR)\evp.h \
+ $(HCRYPTOINCLUDEDIR)\evp-hcrypto.h \
+ $(HCRYPTOINCLUDEDIR)\evp-cc.h \
+ $(HCRYPTOINCLUDEDIR)\evp-openssl.h \
+ $(HCRYPTOINCLUDEDIR)\evp-pkcs11.h \
+ $(HCRYPTOINCLUDEDIR)\evp-wincng.h \
+ $(HCRYPTOINCLUDEDIR)\evp-w32.h \
+ $(HCRYPTOINCLUDEDIR)\hmac.h \
+ $(HCRYPTOINCLUDEDIR)\md2.h \
+ $(HCRYPTOINCLUDEDIR)\md4.h \
+ $(HCRYPTOINCLUDEDIR)\md5.h \
+ $(HCRYPTOINCLUDEDIR)\pkcs12.h \
+ $(HCRYPTOINCLUDEDIR)\rand.h \
+ $(HCRYPTOINCLUDEDIR)\randi.h \
+ $(HCRYPTOINCLUDEDIR)\rc2.h \
+ $(HCRYPTOINCLUDEDIR)\rc4.h \
+ $(HCRYPTOINCLUDEDIR)\rsa.h \
+ $(HCRYPTOINCLUDEDIR)\sha.h \
+ $(HCRYPTOINCLUDEDIR)\ui.h \
+ $(HCRYPTOINCLUDEDIR)\undef.h \
+ $(HCRYPTOINCLUDEDIR)\x25519_ref10.h \
+
+mkincdir:
+!if !exist($(HCRYPTOINCLUDEDIR))
+ $(MKDIR) $(HCRYPTOINCLUDEDIR)
+!endif
+
+{}.h{$(HCRYPTOINCLUDEDIR)}.h:
+ $(CP) $** $@
+
+all:: mkincdir
+
+all:: $(INCFILES)
+
+# libhcrypto
+
+libhcrypto_OBJs = \
+ $(OBJ)\aes.obj \
+ $(OBJ)\bn.obj \
+ $(OBJ)\camellia.obj \
+ $(OBJ)\camellia-ntt.obj \
+ $(OBJ)\common.obj \
+ $(OBJ)\des.obj \
+ $(OBJ)\dh.obj \
+ $(OBJ)\dh-ltm.obj \
+ $(OBJ)\dh-tfm.obj \
+ $(OBJ)\dsa.obj \
+ $(OBJ)\evp.obj \
+ $(OBJ)\evp-hcrypto.obj \
+ $(OBJ)\evp-cc.obj \
+ $(OBJ)\evp-openssl.obj \
+ $(OBJ)\evp-pkcs11.obj \
+ $(OBJ)\evp-wincng.obj \
+ $(OBJ)\evp-w32.obj \
+ $(OBJ)\engine.obj \
+ $(OBJ)\hmac.obj \
+ $(OBJ)\md2.obj \
+ $(OBJ)\md4.obj \
+ $(OBJ)\md5.obj \
+ $(OBJ)\pkcs5.obj \
+ $(OBJ)\pkcs12.obj \
+ $(OBJ)\rand-w32.obj \
+ $(OBJ)\rand.obj \
+ $(OBJ)\rc2.obj \
+ $(OBJ)\rc4.obj \
+ $(OBJ)\rijndael-alg-fst.obj \
+ $(OBJ)\rnd_keys.obj \
+ $(OBJ)\rsa.obj \
+ $(OBJ)\rsa-gmp.obj \
+ $(OBJ)\rsa-ltm.obj \
+ $(OBJ)\rsa-tfm.obj \
+ $(OBJ)\sha.obj \
+ $(OBJ)\sha256.obj \
+ $(OBJ)\sha512.obj \
+ $(OBJ)\ui.obj \
+ $(OBJ)\validate.obj
+
+$(LIBHCRYPTO): $(libhcrypto_OBJs)
+ $(LIBCON)
+
+all:: $(LIBHCRYPTO)
+
+clean::
+ -$(RM) $(LIBHCRYPTO)
+
+# Tests
+
+TESTLIB=$(OBJ)\libhctest.lib
+
+$(TESTLIB): \
+ $(OBJ)\des.obj \
+ $(OBJ)\ui.obj
+ $(LIBCON)
+
+test-binaries: \
+ $(OBJ)\destest.exe \
+ $(OBJ)\example_evp_cipher.exe \
+ $(OBJ)\mdtest.exe \
+ $(OBJ)\rc2test.exe \
+ $(OBJ)\rctest.exe \
+ $(OBJ)\test_bn.exe \
+ $(OBJ)\test_bulk.exe \
+ $(OBJ)\test_cipher.exe \
+ $(OBJ)\test_engine_dso.exe \
+ $(OBJ)\test_hmac.exe \
+ $(OBJ)\test_pkcs5.exe \
+ $(OBJ)\test_pkcs12.exe \
+ $(OBJ)\test_rsa.exe \
+ $(OBJ)\test_dh.exe \
+ $(OBJ)\test_rand.exe \
+ $(OBJ)\test_crypto.sh
+
+$(OBJ)\destest.exe: $(OBJ)\destest.obj $(TESTLIB) $(LIBROKEN) $(LIBHEIMBASE)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\example_evp_cipher.exe: $(OBJ)\example_evp_cipher.obj $(TESTLIB) $(LIBHEIMDAL) $(LIBROKEN) $(LIBHEIMBASE)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\mdtest.exe: $(OBJ)\mdtest.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBHEIMBASE) $(OBJ)\sha512.obj
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\rc2test.exe: $(OBJ)\rc2test.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBHEIMBASE)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\rctest.exe: $(OBJ)\rctest.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBHEIMBASE)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_bn.exe: $(OBJ)\test_bn.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBHEIMBASE)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_bulk.exe: $(OBJ)\test_bulk.obj $(TESTLIB) $(LIBHEIMDAL) $(LIBROKEN) $(LIBHEIMBASE) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_cipher.exe: $(OBJ)\test_cipher.obj $(TESTLIB) $(LIBHEIMDAL) $(LIBROKEN) $(LIBHEIMBASE) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_engine_dso.exe: $(OBJ)\test_engine_dso.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBHEIMBASE) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_hmac.exe: $(OBJ)\test_hmac.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBHEIMBASE)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_pkcs5.exe: $(OBJ)\test_pkcs5.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBHEIMBASE)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_pkcs12.exe: $(OBJ)\test_pkcs12.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBHEIMBASE)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_rsa.exe: $(OBJ)\test_rsa.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBHEIMBASE) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_dh.exe: $(OBJ)\test_dh.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBHEIMBASE) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_rand.exe: $(OBJ)\test_rand.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBHEIMBASE) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+SRCDIR2=$(SRCDIR:\=\\\\)
+
+$(OBJ)\test_crypto.sh: test_crypto.in NTMakefile
+ $(SED) -e "s,[@]srcdir[@],$(SRCDIR2),g" -e "s,[@]exeext[@],.exe,g" -e "s,\r,," < test_crypto.in > $@ || $(RM) $@
+
+test-run:
+ cd $(OBJ)
+!ifdef SH
+ -$(SH) test_crypto.sh
+!endif
+ -destest.exe
+ -mdtest.exe
+ -rc2test.exe
+ -rctest.exe
+ -test_bn.exe
+ -test_bulk.exe --provider=hcrypto
+ -test_bulk.exe --provider=w32crypto
+ -test_cipher.exe
+ -test_engine_dso.exe
+ -test_hmac.exe
+ -test_pkcs5.exe
+ -test_pkcs12.exe
+ -test_rsa.exe
+ -test_dh.exe
+ cd $(SRCDIR)
+
+test:: $(TESTLIB) test-binaries test-run
+
+test-exports:
+ $(PERL) ..\..\cf\w32-check-exported-symbols.pl --vs version-script.map --def libhcrypto-exports.def
+
+test:: test-exports
diff --git a/third_party/heimdal/lib/hcrypto/aes.c b/third_party/heimdal/lib/hcrypto/aes.c
new file mode 100644
index 0000000..2e15d5d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/aes.c
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#ifdef KRB5
+#include <krb5-types.h>
+#endif
+
+#include "rijndael-alg-fst.h"
+#include "aes.h"
+
+int
+AES_set_encrypt_key(const unsigned char *userkey, const int bits, AES_KEY *key)
+{
+ key->rounds = rijndaelKeySetupEnc(key->key, userkey, bits);
+ if (key->rounds == 0)
+ return -1;
+ return 0;
+}
+
+int
+AES_set_decrypt_key(const unsigned char *userkey, const int bits, AES_KEY *key)
+{
+ key->rounds = rijndaelKeySetupDec(key->key, userkey, bits);
+ if (key->rounds == 0)
+ return -1;
+ return 0;
+}
+
+void
+AES_encrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key)
+{
+ rijndaelEncrypt(key->key, key->rounds, in, out);
+}
+
+void
+AES_decrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key)
+{
+ rijndaelDecrypt(key->key, key->rounds, in, out);
+}
+
+void
+AES_cbc_encrypt(const unsigned char *in, unsigned char *out,
+ unsigned long size, const AES_KEY *key,
+ unsigned char *iv, int forward_encrypt)
+{
+ unsigned char tmp[AES_BLOCK_SIZE];
+ int i;
+
+ if (forward_encrypt) {
+ while (size >= AES_BLOCK_SIZE) {
+ for (i = 0; i < AES_BLOCK_SIZE; i++)
+ tmp[i] = in[i] ^ iv[i];
+ AES_encrypt(tmp, out, key);
+ memcpy(iv, out, AES_BLOCK_SIZE);
+ size -= AES_BLOCK_SIZE;
+ in += AES_BLOCK_SIZE;
+ out += AES_BLOCK_SIZE;
+ }
+ if (size) {
+ for (i = 0; i < size; i++)
+ tmp[i] = in[i] ^ iv[i];
+ for (i = size; i < AES_BLOCK_SIZE; i++)
+ tmp[i] = iv[i];
+ AES_encrypt(tmp, out, key);
+ memcpy(iv, out, AES_BLOCK_SIZE);
+ }
+ } else {
+ while (size >= AES_BLOCK_SIZE) {
+ memcpy(tmp, in, AES_BLOCK_SIZE);
+ AES_decrypt(tmp, out, key);
+ for (i = 0; i < AES_BLOCK_SIZE; i++)
+ out[i] ^= iv[i];
+ memcpy(iv, tmp, AES_BLOCK_SIZE);
+ size -= AES_BLOCK_SIZE;
+ in += AES_BLOCK_SIZE;
+ out += AES_BLOCK_SIZE;
+ }
+ if (size) {
+ memcpy(tmp, in, AES_BLOCK_SIZE);
+ AES_decrypt(tmp, out, key);
+ for (i = 0; i < size; i++)
+ out[i] ^= iv[i];
+ memcpy(iv, tmp, AES_BLOCK_SIZE);
+ }
+ }
+}
+
+void
+AES_cfb8_encrypt(const unsigned char *in, unsigned char *out,
+ unsigned long size, const AES_KEY *key,
+ unsigned char *iv, int forward_encrypt)
+{
+ int i;
+
+ for (i = 0; i < size; i++) {
+ unsigned char tmp[AES_BLOCK_SIZE + 1];
+
+ memcpy(tmp, iv, AES_BLOCK_SIZE);
+ AES_encrypt(iv, iv, key);
+ if (!forward_encrypt) {
+ tmp[AES_BLOCK_SIZE] = in[i];
+ }
+ out[i] = in[i] ^ iv[0];
+ if (forward_encrypt) {
+ tmp[AES_BLOCK_SIZE] = out[i];
+ }
+ memcpy(iv, &tmp[1], AES_BLOCK_SIZE);
+ }
+}
diff --git a/third_party/heimdal/lib/hcrypto/aes.h b/third_party/heimdal/lib/hcrypto/aes.h
new file mode 100644
index 0000000..4ba4516
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/aes.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2003-2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_AES_H
+#define HEIM_AES_H 1
+
+/* symbol renaming */
+#define AES_set_encrypt_key hc_AES_set_encrypt_key
+#define AES_set_decrypt_key hc_AES_decrypt_key
+#define AES_encrypt hc_AES_encrypt
+#define AES_decrypt hc_AES_decrypt
+#define AES_cbc_encrypt hc_AES_cbc_encrypt
+#define AES_cfb8_encrypt hc_AES_cfb8_encrypt
+
+/*
+ *
+ */
+
+#define AES_BLOCK_SIZE 16
+#define AES_MAXNR 14
+
+#define AES_ENCRYPT 1
+#define AES_DECRYPT 0
+
+typedef struct aes_key {
+ uint32_t key[(AES_MAXNR+1)*4];
+ int rounds;
+} AES_KEY;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int AES_set_encrypt_key(const unsigned char *, const int, AES_KEY *);
+int AES_set_decrypt_key(const unsigned char *, const int, AES_KEY *);
+
+void AES_encrypt(const unsigned char *, unsigned char *, const AES_KEY *);
+void AES_decrypt(const unsigned char *, unsigned char *, const AES_KEY *);
+
+void AES_cbc_encrypt(const unsigned char *, unsigned char *,
+ unsigned long, const AES_KEY *,
+ unsigned char *, int);
+void AES_cfb8_encrypt(const unsigned char *, unsigned char *,
+ unsigned long, const AES_KEY *,
+ unsigned char *, int);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* HEIM_AES_H */
diff --git a/third_party/heimdal/lib/hcrypto/bn.c b/third_party/heimdal/lib/hcrypto/bn.c
new file mode 100644
index 0000000..62297b1
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/bn.c
@@ -0,0 +1,529 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <krb5-types.h>
+#include <rfc2459_asn1.h> /* XXX */
+#include <der.h>
+
+#include <bn.h>
+#include <rand.h>
+#include <hex.h>
+
+BIGNUM *
+BN_new(void)
+{
+ heim_integer *hi;
+ hi = calloc(1, sizeof(*hi));
+ return (BIGNUM *)hi;
+}
+
+void
+BN_free(BIGNUM *bn)
+{
+ BN_clear(bn);
+ free(bn);
+}
+
+void
+BN_clear(BIGNUM *bn)
+{
+ heim_integer *hi = (heim_integer *)bn;
+ if (hi->data) {
+ memset(hi->data, 0, hi->length);
+ free(hi->data);
+ }
+ memset(hi, 0, sizeof(*hi));
+}
+
+void
+BN_clear_free(BIGNUM *bn)
+{
+ BN_free(bn);
+}
+
+BIGNUM *
+BN_dup(const BIGNUM *bn)
+{
+ BIGNUM *b = BN_new();
+ if (der_copy_heim_integer((const heim_integer *)bn, (heim_integer *)b)) {
+ BN_free(b);
+ return NULL;
+ }
+ return b;
+}
+
+/*
+ * If the caller really want to know the number of bits used, subtract
+ * one from the length, multiply by 8, and then lookup in the table
+ * how many bits the hightest byte uses.
+ */
+int
+BN_num_bits(const BIGNUM *bn)
+{
+ static unsigned char num2bits[256] = {
+ 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
+ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ };
+ const heim_integer *i = (const void *)bn;
+ if (i->length == 0)
+ return 0;
+ return (i->length - 1) * 8 + num2bits[((unsigned char *)i->data)[0]];
+}
+
+int
+BN_num_bytes(const BIGNUM *bn)
+{
+ return ((const heim_integer *)bn)->length;
+}
+
+/*
+ * Ignore negative flag.
+ */
+
+BIGNUM *
+BN_bin2bn(const void *s, int len, BIGNUM *bn)
+{
+ heim_integer *hi = (void *)bn;
+
+ if (len < 0)
+ return NULL;
+
+ if (hi == NULL) {
+ hi = (heim_integer *)BN_new();
+ if (hi == NULL)
+ return NULL;
+ }
+ if (hi->data)
+ BN_clear((BIGNUM *)hi);
+ hi->negative = 0;
+ hi->data = malloc(len);
+ if (hi->data == NULL && len != 0) {
+ if (bn == NULL)
+ BN_free((BIGNUM *)hi);
+ return NULL;
+ }
+ hi->length = len;
+ if (len)
+ memcpy(hi->data, s, len);
+ return (BIGNUM *)hi;
+}
+
+int
+BN_bn2bin(const BIGNUM *bn, void *to)
+{
+ const heim_integer *hi = (const void *)bn;
+ memcpy(to, hi->data, hi->length);
+ return hi->length;
+}
+
+int
+BN_hex2bn(BIGNUM **bnp, const char *in)
+{
+ int negative;
+ ssize_t ret;
+ size_t len;
+ void *data;
+
+ len = strlen(in);
+ data = malloc(len);
+ if (data == NULL)
+ return 0;
+
+ if (*in == '-') {
+ negative = 1;
+ in++;
+ } else
+ negative = 0;
+
+ ret = hex_decode(in, data, len);
+ if (ret < 0) {
+ free(data);
+ return 0;
+ }
+
+ *bnp = BN_bin2bn(data, ret, NULL);
+ free(data);
+ if (*bnp == NULL)
+ return 0;
+ BN_set_negative(*bnp, negative);
+ return 1;
+}
+
+char *
+BN_bn2hex(const BIGNUM *bn)
+{
+ ssize_t ret;
+ size_t len;
+ void *data;
+ char *str;
+
+ len = BN_num_bytes(bn);
+ data = malloc(len);
+ if (data == NULL)
+ return 0;
+
+ len = BN_bn2bin(bn, data);
+
+ ret = hex_encode(data, len, &str);
+ free(data);
+ if (ret < 0)
+ return 0;
+
+ return str;
+}
+
+int
+BN_cmp(const BIGNUM *bn1, const BIGNUM *bn2)
+{
+ return der_heim_integer_cmp((const heim_integer *)bn1,
+ (const heim_integer *)bn2);
+}
+
+void
+BN_set_negative(BIGNUM *bn, int flag)
+{
+ ((heim_integer *)bn)->negative = (flag ? 1 : 0);
+}
+
+int
+BN_is_negative(const BIGNUM *bn)
+{
+ return ((const heim_integer *)bn)->negative ? 1 : 0;
+}
+
+static const unsigned char is_set[8] = { 1, 2, 4, 8, 16, 32, 64, 128 };
+
+int
+BN_is_bit_set(const BIGNUM *bn, int bit)
+{
+ heim_integer *hi = (heim_integer *)bn;
+ unsigned char *p = hi->data;
+
+ if ((bit / 8) >= hi->length || hi->length == 0)
+ return 0;
+
+ return p[hi->length - 1 - (bit / 8)] & is_set[bit % 8];
+}
+
+int
+BN_set_bit(BIGNUM *bn, int bit)
+{
+ heim_integer *hi = (heim_integer *)bn;
+ unsigned char *p;
+
+ if ((bit / 8) > hi->length || hi->length == 0) {
+ size_t len = bit == 0 ? 1 : (bit + 7) / 8;
+ void *d = realloc(hi->data, len);
+ if (d == NULL)
+ return 0;
+ hi->data = d;
+ p = hi->data;
+ memset(&p[hi->length], 0, len);
+ hi->length = len;
+ } else
+ p = hi->data;
+
+ p[hi->length - 1 - (bit / 8)] |= is_set[bit % 8];
+ return 1;
+}
+
+int
+BN_clear_bit(BIGNUM *bn, int bit)
+{
+ heim_integer *hi = (heim_integer *)bn;
+ unsigned char *p = hi->data;
+
+ if ((bit / 8) > hi->length || hi->length == 0)
+ return 0;
+
+ p[hi->length - 1 - (bit / 8)] &= (unsigned char)(~(is_set[bit % 8]));
+
+ return 1;
+}
+
+int
+BN_set_word(BIGNUM *bn, unsigned long num)
+{
+ unsigned char p[sizeof(num)];
+ unsigned long num2;
+ int i, len;
+
+ if (bn == NULL)
+ return 0;
+
+ for (num2 = num, i = 0; num2 > 0; i++)
+ num2 = num2 >> 8;
+
+ len = i;
+ for (; i > 0; i--) {
+ p[i - 1] = (num & 0xff);
+ num = num >> 8;
+ }
+
+ bn = BN_bin2bn(p, len, bn);
+ return bn != NULL;
+}
+
+unsigned long
+BN_get_word(const BIGNUM *bn)
+{
+ heim_integer *hi = (heim_integer *)bn;
+ unsigned long num = 0;
+ int i;
+
+ if (hi->negative || hi->length > sizeof(num))
+ return ULONG_MAX;
+
+ for (i = 0; i < hi->length; i++)
+ num = ((unsigned char *)hi->data)[i] | (num << 8);
+ return num;
+}
+
+int
+BN_rand(BIGNUM *bn, int bits, int top, int bottom)
+{
+ size_t len = (bits + 7) / 8;
+ heim_integer *i = (heim_integer *)bn;
+
+ BN_clear(bn);
+
+ i->negative = 0;
+ i->data = malloc(len);
+ if (i->data == NULL && len != 0)
+ return 0;
+ i->length = len;
+
+ if (RAND_bytes(i->data, i->length) != 1) {
+ free(i->data);
+ i->data = NULL;
+ return 0;
+ }
+
+ {
+ size_t j = len * 8;
+ while(j > bits) {
+ BN_clear_bit(bn, j - 1);
+ j--;
+ }
+ }
+
+ if (top == -1) {
+ ;
+ } else if (top == 0 && bits > 0) {
+ BN_set_bit(bn, bits - 1);
+ } else if (top == 1 && bits > 1) {
+ BN_set_bit(bn, bits - 1);
+ BN_set_bit(bn, bits - 2);
+ } else {
+ BN_clear(bn);
+ return 0;
+ }
+
+ if (bottom && bits > 0)
+ BN_set_bit(bn, 0);
+
+ return 1;
+}
+
+/*
+ *
+ */
+
+int
+BN_uadd(BIGNUM *res, const BIGNUM *a, const BIGNUM *b)
+{
+ const heim_integer *ai = (const heim_integer *)a;
+ const heim_integer *bi = (const heim_integer *)b;
+ const unsigned char *ap, *bp;
+ unsigned char *cp;
+ heim_integer ci;
+ int carry = 0;
+ ssize_t len;
+
+ if (ai->negative && bi->negative)
+ return 0;
+ if (ai->length < bi->length) {
+ const heim_integer *si = bi;
+ bi = ai; ai = si;
+ }
+
+ ci.negative = 0;
+ ci.length = ai->length + 1;
+ ci.data = malloc(ci.length);
+ if (ci.data == NULL)
+ return 0;
+
+ ap = &((const unsigned char *)ai->data)[ai->length - 1];
+ bp = &((const unsigned char *)bi->data)[bi->length - 1];
+ cp = &((unsigned char *)ci.data)[ci.length - 1];
+
+ for (len = bi->length; len > 0; len--) {
+ carry = *ap + *bp + carry;
+ *cp = carry & 0xff;
+ carry = (carry & ~0xff) ? 1 : 0;
+ ap--; bp--; cp--;
+ }
+ for (len = ai->length - bi->length; len > 0; len--) {
+ carry = *ap + carry;
+ *cp = carry & 0xff;
+ carry = (carry & ~0xff) ? 1 : 0;
+ ap--; cp--;
+ }
+ if (!carry)
+ memmove(cp, cp + 1, --ci.length);
+ else
+ *cp = carry;
+
+ BN_clear(res);
+ *((heim_integer *)res) = ci;
+
+ return 1;
+}
+
+
+/*
+ * Callback when doing slow generation of numbers, like primes.
+ */
+
+void
+BN_GENCB_set(BN_GENCB *gencb, int (*cb_2)(int, int, BN_GENCB *), void *ctx)
+{
+ gencb->ver = 2;
+ gencb->cb.cb_2 = cb_2;
+ gencb->arg = ctx;
+}
+
+int
+BN_GENCB_call(BN_GENCB *cb, int a, int b)
+{
+ if (cb == NULL || cb->cb.cb_2 == NULL)
+ return 1;
+ return cb->cb.cb_2(a, b, cb);
+}
+
+/*
+ *
+ */
+
+struct BN_CTX {
+ struct {
+ BIGNUM **val;
+ size_t used;
+ size_t len;
+ } bn;
+ struct {
+ size_t *val;
+ size_t used;
+ size_t len;
+ } stack;
+};
+
+BN_CTX *
+BN_CTX_new(void)
+{
+ struct BN_CTX *c;
+ c = calloc(1, sizeof(*c));
+ return c;
+}
+
+void
+BN_CTX_free(BN_CTX *c)
+{
+ size_t i;
+ for (i = 0; i < c->bn.len; i++)
+ BN_free(c->bn.val[i]);
+ free(c->bn.val);
+ free(c->stack.val);
+}
+
+BIGNUM *
+BN_CTX_get(BN_CTX *c)
+{
+ if (c->bn.used == c->bn.len) {
+ void *ptr;
+ size_t i;
+ c->bn.len += 16;
+ ptr = realloc(c->bn.val, c->bn.len * sizeof(c->bn.val[0]));
+ if (ptr == NULL)
+ return NULL;
+ c->bn.val = ptr;
+ for (i = c->bn.used; i < c->bn.len; i++) {
+ c->bn.val[i] = BN_new();
+ if (c->bn.val[i] == NULL) {
+ c->bn.len = i;
+ return NULL;
+ }
+ }
+ }
+ return c->bn.val[c->bn.used++];
+}
+
+void
+BN_CTX_start(BN_CTX *c)
+{
+ if (c->stack.used == c->stack.len) {
+ void *ptr;
+ c->stack.len += 16;
+ ptr = realloc(c->stack.val, c->stack.len * sizeof(c->stack.val[0]));
+ if (ptr == NULL)
+ abort();
+ c->stack.val = ptr;
+ }
+ c->stack.val[c->stack.used++] = c->bn.used;
+}
+
+void
+BN_CTX_end(BN_CTX *c)
+{
+ const size_t prev = c->stack.val[c->stack.used - 1];
+ size_t i;
+
+ if (c->stack.used == 0)
+ abort();
+
+ for (i = prev; i < c->bn.used; i++)
+ BN_clear(c->bn.val[i]);
+
+ c->stack.used--;
+ c->bn.used = prev;
+}
+
diff --git a/third_party/heimdal/lib/hcrypto/bn.h b/third_party/heimdal/lib/hcrypto/bn.h
new file mode 100644
index 0000000..727b919
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/bn.h
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2006-2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef _HEIM_BN_H
+#define _HEIM_BN_H 1
+
+/* symbol renaming */
+#define BN_GENCB_call hc_BN_GENCB_call
+#define BN_GENCB_set hc_BN_GENCB_set
+#define BN_bin2bn hc_BN_bin2bn
+#define BN_bn2bin hc_BN_bn2bin
+#define BN_bn2hex hc_BN_bn2hex
+#define BN_clear hc_BN_clear
+#define BN_clear_bit hc_BN_clear_bit
+#define BN_clear_free hc_BN_clear_free
+#define BN_cmp hc_BN_cmp
+#define BN_dup hc_BN_dup
+#define BN_free hc_BN_free
+#define BN_is_negative hc_BN_is_negative
+#define BN_get_word hc_BN_get_word
+#define BN_hex2bn hc_BN_hex2bn
+#define BN_is_bit_set hc_BN_is_bit_set
+#define BN_new hc_BN_new
+#define BN_num_bits hc_BN_num_bits
+#define BN_num_bytes hc_BN_num_bytes
+#define BN_rand hc_BN_rand
+#define BN_set_bit hc_BN_set_bit
+#define BN_set_negative hc_BN_set_negative
+#define BN_set_word hc_BN_set_word
+#define BN_uadd hc_BN_uadd
+#define BN_CTX_new hc_BN_CTX_new
+#define BN_CTX_free hc_BN_CTX_free
+#define BN_CTX_get hc_BN_CTX_get
+#define BN_CTX_start hc_BN_CTX_start
+#define BN_CTX_end hc_BN_CTX_end
+
+#define BIGNUM hc_BIGNUM
+#define BN_GENCB hc_BN_GENCB
+#define BN_CTX hc_BN_CTX
+#define BN_BLINDING hc_BN_BLINDING
+#define BN_MONT_CTX hc_BN_MONT_CTX
+
+
+/*
+ *
+ */
+
+typedef struct BIGNUM BIGNUM;
+typedef struct BN_GENCB BN_GENCB;
+typedef struct BN_CTX BN_CTX;
+typedef struct BN_MONT_CTX BN_MONT_CTX;
+typedef struct BN_BLINDING BN_BLINDING;
+
+struct BN_GENCB {
+ unsigned int ver;
+ void *arg;
+ union {
+ int (*cb_2)(int, int, BN_GENCB *);
+ } cb;
+};
+
+/*
+ *
+ */
+
+BIGNUM *BN_new(void);
+void BN_free(BIGNUM *);
+void BN_clear_free(BIGNUM *);
+void BN_clear(BIGNUM *);
+BIGNUM *BN_dup(const BIGNUM *);
+
+int BN_num_bits(const BIGNUM *);
+int BN_num_bytes(const BIGNUM *);
+
+int BN_cmp(const BIGNUM *, const BIGNUM *);
+
+void BN_set_negative(BIGNUM *, int);
+int BN_is_negative(const BIGNUM *);
+
+int BN_is_bit_set(const BIGNUM *, int);
+int BN_set_bit(BIGNUM *, int);
+int BN_clear_bit(BIGNUM *, int);
+
+int BN_set_word(BIGNUM *, unsigned long);
+unsigned long BN_get_word(const BIGNUM *);
+
+BIGNUM *BN_bin2bn(const void *,int len,BIGNUM *);
+int BN_bn2bin(const BIGNUM *, void *);
+int BN_hex2bn(BIGNUM **, const char *);
+char * BN_bn2hex(const BIGNUM *);
+
+int BN_uadd(BIGNUM *, const BIGNUM *, const BIGNUM *);
+
+int BN_rand(BIGNUM *, int, int, int);
+
+void BN_GENCB_set(BN_GENCB *, int (*)(int, int, BN_GENCB *), void *);
+int BN_GENCB_call(BN_GENCB *, int, int);
+
+BN_CTX *BN_CTX_new(void);
+void BN_CTX_free(BN_CTX *);
+BIGNUM *BN_CTX_get(BN_CTX *);
+void BN_CTX_start(BN_CTX *);
+void BN_CTX_end(BN_CTX *);
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/camellia-ntt.c b/third_party/heimdal/lib/hcrypto/camellia-ntt.c
new file mode 100644
index 0000000..66873c2
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/camellia-ntt.c
@@ -0,0 +1,1458 @@
+/* camellia.h ver 1.2.0
+ *
+ * Copyright (C) 2006,2007
+ * NTT (Nippon Telegraph and Telephone Corporation).
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ */
+
+/*
+ * Algorithm Specification
+ * http://info.isl.ntt.co.jp/crypt/eng/camellia/specifications.html
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <krb5-types.h>
+#include "camellia-ntt.h"
+
+/* key constants */
+
+#define CAMELLIA_SIGMA1L (0xA09E667FL)
+#define CAMELLIA_SIGMA1R (0x3BCC908BL)
+#define CAMELLIA_SIGMA2L (0xB67AE858L)
+#define CAMELLIA_SIGMA2R (0x4CAA73B2L)
+#define CAMELLIA_SIGMA3L (0xC6EF372FL)
+#define CAMELLIA_SIGMA3R (0xE94F82BEL)
+#define CAMELLIA_SIGMA4L (0x54FF53A5L)
+#define CAMELLIA_SIGMA4R (0xF1D36F1CL)
+#define CAMELLIA_SIGMA5L (0x10E527FAL)
+#define CAMELLIA_SIGMA5R (0xDE682D1DL)
+#define CAMELLIA_SIGMA6L (0xB05688C2L)
+#define CAMELLIA_SIGMA6R (0xB3E6C1FDL)
+
+/*
+ * macros
+ */
+
+
+#if defined(_MSC_VER)
+
+# define SWAP(x) (_lrotl(x, 8) & 0x00ff00ff | _lrotr(x, 8) & 0xff00ff00)
+# define GETU32(p) SWAP(*((u32 *)(p)))
+# define PUTU32(ct, st) {*((u32 *)(ct)) = SWAP((st));}
+
+#else /* not MS-VC */
+
+# define GETU32(pt) \
+ (((u32)(pt)[0] << 24) \
+ ^ ((u32)(pt)[1] << 16) \
+ ^ ((u32)(pt)[2] << 8) \
+ ^ ((u32)(pt)[3]))
+
+# define PUTU32(ct, st) { \
+ (ct)[0] = (u8)((st) >> 24); \
+ (ct)[1] = (u8)((st) >> 16); \
+ (ct)[2] = (u8)((st) >> 8); \
+ (ct)[3] = (u8)(st); }
+
+#endif
+
+#define CamelliaSubkeyL(INDEX) (subkey[(INDEX)*2])
+#define CamelliaSubkeyR(INDEX) (subkey[(INDEX)*2 + 1])
+
+/* rotation right shift 1byte */
+#define CAMELLIA_RR8(x) (((x) >> 8) + ((x) << 24))
+/* rotation left shift 1bit */
+#define CAMELLIA_RL1(x) (((x) << 1) + ((x) >> 31))
+/* rotation left shift 1byte */
+#define CAMELLIA_RL8(x) (((x) << 8) + ((x) >> 24))
+
+#define CAMELLIA_ROLDQ(ll, lr, rl, rr, w0, w1, bits) \
+ do { \
+ w0 = ll; \
+ ll = (ll << bits) + (lr >> (32 - bits)); \
+ lr = (lr << bits) + (rl >> (32 - bits)); \
+ rl = (rl << bits) + (rr >> (32 - bits)); \
+ rr = (rr << bits) + (w0 >> (32 - bits)); \
+ } while(0)
+
+#define CAMELLIA_ROLDQo32(ll, lr, rl, rr, w0, w1, bits) \
+ do { \
+ w0 = ll; \
+ w1 = lr; \
+ ll = (lr << (bits - 32)) + (rl >> (64 - bits)); \
+ lr = (rl << (bits - 32)) + (rr >> (64 - bits)); \
+ rl = (rr << (bits - 32)) + (w0 >> (64 - bits)); \
+ rr = (w0 << (bits - 32)) + (w1 >> (64 - bits)); \
+ } while(0)
+
+#define CAMELLIA_SP1110(INDEX) (camellia_sp1110[(INDEX)])
+#define CAMELLIA_SP0222(INDEX) (camellia_sp0222[(INDEX)])
+#define CAMELLIA_SP3033(INDEX) (camellia_sp3033[(INDEX)])
+#define CAMELLIA_SP4404(INDEX) (camellia_sp4404[(INDEX)])
+
+#define CAMELLIA_F(xl, xr, kl, kr, yl, yr, il, ir, t0, t1) \
+ do { \
+ il = xl ^ kl; \
+ ir = xr ^ kr; \
+ t0 = il >> 16; \
+ t1 = ir >> 16; \
+ yl = CAMELLIA_SP1110(ir & 0xff) \
+ ^ CAMELLIA_SP0222((t1 >> 8) & 0xff) \
+ ^ CAMELLIA_SP3033(t1 & 0xff) \
+ ^ CAMELLIA_SP4404((ir >> 8) & 0xff); \
+ yr = CAMELLIA_SP1110((t0 >> 8) & 0xff) \
+ ^ CAMELLIA_SP0222(t0 & 0xff) \
+ ^ CAMELLIA_SP3033((il >> 8) & 0xff) \
+ ^ CAMELLIA_SP4404(il & 0xff); \
+ yl ^= yr; \
+ yr = CAMELLIA_RR8(yr); \
+ yr ^= yl; \
+ } while(0)
+
+
+/*
+ * for speed up
+ *
+ */
+#define CAMELLIA_FLS(ll, lr, rl, rr, kll, klr, krl, krr, t0, t1, t2, t3) \
+ do { \
+ t0 = kll; \
+ t0 &= ll; \
+ lr ^= CAMELLIA_RL1(t0); \
+ t1 = klr; \
+ t1 |= lr; \
+ ll ^= t1; \
+ \
+ t2 = krr; \
+ t2 |= rr; \
+ rl ^= t2; \
+ t3 = krl; \
+ t3 &= rl; \
+ rr ^= CAMELLIA_RL1(t3); \
+ } while(0)
+
+#define CAMELLIA_ROUNDSM(xl, xr, kl, kr, yl, yr, il, ir, t0, t1) \
+ do { \
+ ir = CAMELLIA_SP1110(xr & 0xff) \
+ ^ CAMELLIA_SP0222((xr >> 24) & 0xff) \
+ ^ CAMELLIA_SP3033((xr >> 16) & 0xff) \
+ ^ CAMELLIA_SP4404((xr >> 8) & 0xff); \
+ il = CAMELLIA_SP1110((xl >> 24) & 0xff) \
+ ^ CAMELLIA_SP0222((xl >> 16) & 0xff) \
+ ^ CAMELLIA_SP3033((xl >> 8) & 0xff) \
+ ^ CAMELLIA_SP4404(xl & 0xff); \
+ il ^= kl; \
+ ir ^= kr; \
+ ir ^= il; \
+ il = CAMELLIA_RR8(il); \
+ il ^= ir; \
+ yl ^= ir; \
+ yr ^= il; \
+ } while(0)
+
+
+static const u32 camellia_sp1110[256] = {
+ 0x70707000,0x82828200,0x2c2c2c00,0xececec00,
+ 0xb3b3b300,0x27272700,0xc0c0c000,0xe5e5e500,
+ 0xe4e4e400,0x85858500,0x57575700,0x35353500,
+ 0xeaeaea00,0x0c0c0c00,0xaeaeae00,0x41414100,
+ 0x23232300,0xefefef00,0x6b6b6b00,0x93939300,
+ 0x45454500,0x19191900,0xa5a5a500,0x21212100,
+ 0xededed00,0x0e0e0e00,0x4f4f4f00,0x4e4e4e00,
+ 0x1d1d1d00,0x65656500,0x92929200,0xbdbdbd00,
+ 0x86868600,0xb8b8b800,0xafafaf00,0x8f8f8f00,
+ 0x7c7c7c00,0xebebeb00,0x1f1f1f00,0xcecece00,
+ 0x3e3e3e00,0x30303000,0xdcdcdc00,0x5f5f5f00,
+ 0x5e5e5e00,0xc5c5c500,0x0b0b0b00,0x1a1a1a00,
+ 0xa6a6a600,0xe1e1e100,0x39393900,0xcacaca00,
+ 0xd5d5d500,0x47474700,0x5d5d5d00,0x3d3d3d00,
+ 0xd9d9d900,0x01010100,0x5a5a5a00,0xd6d6d600,
+ 0x51515100,0x56565600,0x6c6c6c00,0x4d4d4d00,
+ 0x8b8b8b00,0x0d0d0d00,0x9a9a9a00,0x66666600,
+ 0xfbfbfb00,0xcccccc00,0xb0b0b000,0x2d2d2d00,
+ 0x74747400,0x12121200,0x2b2b2b00,0x20202000,
+ 0xf0f0f000,0xb1b1b100,0x84848400,0x99999900,
+ 0xdfdfdf00,0x4c4c4c00,0xcbcbcb00,0xc2c2c200,
+ 0x34343400,0x7e7e7e00,0x76767600,0x05050500,
+ 0x6d6d6d00,0xb7b7b700,0xa9a9a900,0x31313100,
+ 0xd1d1d100,0x17171700,0x04040400,0xd7d7d700,
+ 0x14141400,0x58585800,0x3a3a3a00,0x61616100,
+ 0xdedede00,0x1b1b1b00,0x11111100,0x1c1c1c00,
+ 0x32323200,0x0f0f0f00,0x9c9c9c00,0x16161600,
+ 0x53535300,0x18181800,0xf2f2f200,0x22222200,
+ 0xfefefe00,0x44444400,0xcfcfcf00,0xb2b2b200,
+ 0xc3c3c300,0xb5b5b500,0x7a7a7a00,0x91919100,
+ 0x24242400,0x08080800,0xe8e8e800,0xa8a8a800,
+ 0x60606000,0xfcfcfc00,0x69696900,0x50505000,
+ 0xaaaaaa00,0xd0d0d000,0xa0a0a000,0x7d7d7d00,
+ 0xa1a1a100,0x89898900,0x62626200,0x97979700,
+ 0x54545400,0x5b5b5b00,0x1e1e1e00,0x95959500,
+ 0xe0e0e000,0xffffff00,0x64646400,0xd2d2d200,
+ 0x10101000,0xc4c4c400,0x00000000,0x48484800,
+ 0xa3a3a300,0xf7f7f700,0x75757500,0xdbdbdb00,
+ 0x8a8a8a00,0x03030300,0xe6e6e600,0xdadada00,
+ 0x09090900,0x3f3f3f00,0xdddddd00,0x94949400,
+ 0x87878700,0x5c5c5c00,0x83838300,0x02020200,
+ 0xcdcdcd00,0x4a4a4a00,0x90909000,0x33333300,
+ 0x73737300,0x67676700,0xf6f6f600,0xf3f3f300,
+ 0x9d9d9d00,0x7f7f7f00,0xbfbfbf00,0xe2e2e200,
+ 0x52525200,0x9b9b9b00,0xd8d8d800,0x26262600,
+ 0xc8c8c800,0x37373700,0xc6c6c600,0x3b3b3b00,
+ 0x81818100,0x96969600,0x6f6f6f00,0x4b4b4b00,
+ 0x13131300,0xbebebe00,0x63636300,0x2e2e2e00,
+ 0xe9e9e900,0x79797900,0xa7a7a700,0x8c8c8c00,
+ 0x9f9f9f00,0x6e6e6e00,0xbcbcbc00,0x8e8e8e00,
+ 0x29292900,0xf5f5f500,0xf9f9f900,0xb6b6b600,
+ 0x2f2f2f00,0xfdfdfd00,0xb4b4b400,0x59595900,
+ 0x78787800,0x98989800,0x06060600,0x6a6a6a00,
+ 0xe7e7e700,0x46464600,0x71717100,0xbababa00,
+ 0xd4d4d400,0x25252500,0xababab00,0x42424200,
+ 0x88888800,0xa2a2a200,0x8d8d8d00,0xfafafa00,
+ 0x72727200,0x07070700,0xb9b9b900,0x55555500,
+ 0xf8f8f800,0xeeeeee00,0xacacac00,0x0a0a0a00,
+ 0x36363600,0x49494900,0x2a2a2a00,0x68686800,
+ 0x3c3c3c00,0x38383800,0xf1f1f100,0xa4a4a400,
+ 0x40404000,0x28282800,0xd3d3d300,0x7b7b7b00,
+ 0xbbbbbb00,0xc9c9c900,0x43434300,0xc1c1c100,
+ 0x15151500,0xe3e3e300,0xadadad00,0xf4f4f400,
+ 0x77777700,0xc7c7c700,0x80808000,0x9e9e9e00,
+};
+
+static const u32 camellia_sp0222[256] = {
+ 0x00e0e0e0,0x00050505,0x00585858,0x00d9d9d9,
+ 0x00676767,0x004e4e4e,0x00818181,0x00cbcbcb,
+ 0x00c9c9c9,0x000b0b0b,0x00aeaeae,0x006a6a6a,
+ 0x00d5d5d5,0x00181818,0x005d5d5d,0x00828282,
+ 0x00464646,0x00dfdfdf,0x00d6d6d6,0x00272727,
+ 0x008a8a8a,0x00323232,0x004b4b4b,0x00424242,
+ 0x00dbdbdb,0x001c1c1c,0x009e9e9e,0x009c9c9c,
+ 0x003a3a3a,0x00cacaca,0x00252525,0x007b7b7b,
+ 0x000d0d0d,0x00717171,0x005f5f5f,0x001f1f1f,
+ 0x00f8f8f8,0x00d7d7d7,0x003e3e3e,0x009d9d9d,
+ 0x007c7c7c,0x00606060,0x00b9b9b9,0x00bebebe,
+ 0x00bcbcbc,0x008b8b8b,0x00161616,0x00343434,
+ 0x004d4d4d,0x00c3c3c3,0x00727272,0x00959595,
+ 0x00ababab,0x008e8e8e,0x00bababa,0x007a7a7a,
+ 0x00b3b3b3,0x00020202,0x00b4b4b4,0x00adadad,
+ 0x00a2a2a2,0x00acacac,0x00d8d8d8,0x009a9a9a,
+ 0x00171717,0x001a1a1a,0x00353535,0x00cccccc,
+ 0x00f7f7f7,0x00999999,0x00616161,0x005a5a5a,
+ 0x00e8e8e8,0x00242424,0x00565656,0x00404040,
+ 0x00e1e1e1,0x00636363,0x00090909,0x00333333,
+ 0x00bfbfbf,0x00989898,0x00979797,0x00858585,
+ 0x00686868,0x00fcfcfc,0x00ececec,0x000a0a0a,
+ 0x00dadada,0x006f6f6f,0x00535353,0x00626262,
+ 0x00a3a3a3,0x002e2e2e,0x00080808,0x00afafaf,
+ 0x00282828,0x00b0b0b0,0x00747474,0x00c2c2c2,
+ 0x00bdbdbd,0x00363636,0x00222222,0x00383838,
+ 0x00646464,0x001e1e1e,0x00393939,0x002c2c2c,
+ 0x00a6a6a6,0x00303030,0x00e5e5e5,0x00444444,
+ 0x00fdfdfd,0x00888888,0x009f9f9f,0x00656565,
+ 0x00878787,0x006b6b6b,0x00f4f4f4,0x00232323,
+ 0x00484848,0x00101010,0x00d1d1d1,0x00515151,
+ 0x00c0c0c0,0x00f9f9f9,0x00d2d2d2,0x00a0a0a0,
+ 0x00555555,0x00a1a1a1,0x00414141,0x00fafafa,
+ 0x00434343,0x00131313,0x00c4c4c4,0x002f2f2f,
+ 0x00a8a8a8,0x00b6b6b6,0x003c3c3c,0x002b2b2b,
+ 0x00c1c1c1,0x00ffffff,0x00c8c8c8,0x00a5a5a5,
+ 0x00202020,0x00898989,0x00000000,0x00909090,
+ 0x00474747,0x00efefef,0x00eaeaea,0x00b7b7b7,
+ 0x00151515,0x00060606,0x00cdcdcd,0x00b5b5b5,
+ 0x00121212,0x007e7e7e,0x00bbbbbb,0x00292929,
+ 0x000f0f0f,0x00b8b8b8,0x00070707,0x00040404,
+ 0x009b9b9b,0x00949494,0x00212121,0x00666666,
+ 0x00e6e6e6,0x00cecece,0x00ededed,0x00e7e7e7,
+ 0x003b3b3b,0x00fefefe,0x007f7f7f,0x00c5c5c5,
+ 0x00a4a4a4,0x00373737,0x00b1b1b1,0x004c4c4c,
+ 0x00919191,0x006e6e6e,0x008d8d8d,0x00767676,
+ 0x00030303,0x002d2d2d,0x00dedede,0x00969696,
+ 0x00262626,0x007d7d7d,0x00c6c6c6,0x005c5c5c,
+ 0x00d3d3d3,0x00f2f2f2,0x004f4f4f,0x00191919,
+ 0x003f3f3f,0x00dcdcdc,0x00797979,0x001d1d1d,
+ 0x00525252,0x00ebebeb,0x00f3f3f3,0x006d6d6d,
+ 0x005e5e5e,0x00fbfbfb,0x00696969,0x00b2b2b2,
+ 0x00f0f0f0,0x00313131,0x000c0c0c,0x00d4d4d4,
+ 0x00cfcfcf,0x008c8c8c,0x00e2e2e2,0x00757575,
+ 0x00a9a9a9,0x004a4a4a,0x00575757,0x00848484,
+ 0x00111111,0x00454545,0x001b1b1b,0x00f5f5f5,
+ 0x00e4e4e4,0x000e0e0e,0x00737373,0x00aaaaaa,
+ 0x00f1f1f1,0x00dddddd,0x00595959,0x00141414,
+ 0x006c6c6c,0x00929292,0x00545454,0x00d0d0d0,
+ 0x00787878,0x00707070,0x00e3e3e3,0x00494949,
+ 0x00808080,0x00505050,0x00a7a7a7,0x00f6f6f6,
+ 0x00777777,0x00939393,0x00868686,0x00838383,
+ 0x002a2a2a,0x00c7c7c7,0x005b5b5b,0x00e9e9e9,
+ 0x00eeeeee,0x008f8f8f,0x00010101,0x003d3d3d,
+};
+
+static const u32 camellia_sp3033[256] = {
+ 0x38003838,0x41004141,0x16001616,0x76007676,
+ 0xd900d9d9,0x93009393,0x60006060,0xf200f2f2,
+ 0x72007272,0xc200c2c2,0xab00abab,0x9a009a9a,
+ 0x75007575,0x06000606,0x57005757,0xa000a0a0,
+ 0x91009191,0xf700f7f7,0xb500b5b5,0xc900c9c9,
+ 0xa200a2a2,0x8c008c8c,0xd200d2d2,0x90009090,
+ 0xf600f6f6,0x07000707,0xa700a7a7,0x27002727,
+ 0x8e008e8e,0xb200b2b2,0x49004949,0xde00dede,
+ 0x43004343,0x5c005c5c,0xd700d7d7,0xc700c7c7,
+ 0x3e003e3e,0xf500f5f5,0x8f008f8f,0x67006767,
+ 0x1f001f1f,0x18001818,0x6e006e6e,0xaf00afaf,
+ 0x2f002f2f,0xe200e2e2,0x85008585,0x0d000d0d,
+ 0x53005353,0xf000f0f0,0x9c009c9c,0x65006565,
+ 0xea00eaea,0xa300a3a3,0xae00aeae,0x9e009e9e,
+ 0xec00ecec,0x80008080,0x2d002d2d,0x6b006b6b,
+ 0xa800a8a8,0x2b002b2b,0x36003636,0xa600a6a6,
+ 0xc500c5c5,0x86008686,0x4d004d4d,0x33003333,
+ 0xfd00fdfd,0x66006666,0x58005858,0x96009696,
+ 0x3a003a3a,0x09000909,0x95009595,0x10001010,
+ 0x78007878,0xd800d8d8,0x42004242,0xcc00cccc,
+ 0xef00efef,0x26002626,0xe500e5e5,0x61006161,
+ 0x1a001a1a,0x3f003f3f,0x3b003b3b,0x82008282,
+ 0xb600b6b6,0xdb00dbdb,0xd400d4d4,0x98009898,
+ 0xe800e8e8,0x8b008b8b,0x02000202,0xeb00ebeb,
+ 0x0a000a0a,0x2c002c2c,0x1d001d1d,0xb000b0b0,
+ 0x6f006f6f,0x8d008d8d,0x88008888,0x0e000e0e,
+ 0x19001919,0x87008787,0x4e004e4e,0x0b000b0b,
+ 0xa900a9a9,0x0c000c0c,0x79007979,0x11001111,
+ 0x7f007f7f,0x22002222,0xe700e7e7,0x59005959,
+ 0xe100e1e1,0xda00dada,0x3d003d3d,0xc800c8c8,
+ 0x12001212,0x04000404,0x74007474,0x54005454,
+ 0x30003030,0x7e007e7e,0xb400b4b4,0x28002828,
+ 0x55005555,0x68006868,0x50005050,0xbe00bebe,
+ 0xd000d0d0,0xc400c4c4,0x31003131,0xcb00cbcb,
+ 0x2a002a2a,0xad00adad,0x0f000f0f,0xca00caca,
+ 0x70007070,0xff00ffff,0x32003232,0x69006969,
+ 0x08000808,0x62006262,0x00000000,0x24002424,
+ 0xd100d1d1,0xfb00fbfb,0xba00baba,0xed00eded,
+ 0x45004545,0x81008181,0x73007373,0x6d006d6d,
+ 0x84008484,0x9f009f9f,0xee00eeee,0x4a004a4a,
+ 0xc300c3c3,0x2e002e2e,0xc100c1c1,0x01000101,
+ 0xe600e6e6,0x25002525,0x48004848,0x99009999,
+ 0xb900b9b9,0xb300b3b3,0x7b007b7b,0xf900f9f9,
+ 0xce00cece,0xbf00bfbf,0xdf00dfdf,0x71007171,
+ 0x29002929,0xcd00cdcd,0x6c006c6c,0x13001313,
+ 0x64006464,0x9b009b9b,0x63006363,0x9d009d9d,
+ 0xc000c0c0,0x4b004b4b,0xb700b7b7,0xa500a5a5,
+ 0x89008989,0x5f005f5f,0xb100b1b1,0x17001717,
+ 0xf400f4f4,0xbc00bcbc,0xd300d3d3,0x46004646,
+ 0xcf00cfcf,0x37003737,0x5e005e5e,0x47004747,
+ 0x94009494,0xfa00fafa,0xfc00fcfc,0x5b005b5b,
+ 0x97009797,0xfe00fefe,0x5a005a5a,0xac00acac,
+ 0x3c003c3c,0x4c004c4c,0x03000303,0x35003535,
+ 0xf300f3f3,0x23002323,0xb800b8b8,0x5d005d5d,
+ 0x6a006a6a,0x92009292,0xd500d5d5,0x21002121,
+ 0x44004444,0x51005151,0xc600c6c6,0x7d007d7d,
+ 0x39003939,0x83008383,0xdc00dcdc,0xaa00aaaa,
+ 0x7c007c7c,0x77007777,0x56005656,0x05000505,
+ 0x1b001b1b,0xa400a4a4,0x15001515,0x34003434,
+ 0x1e001e1e,0x1c001c1c,0xf800f8f8,0x52005252,
+ 0x20002020,0x14001414,0xe900e9e9,0xbd00bdbd,
+ 0xdd00dddd,0xe400e4e4,0xa100a1a1,0xe000e0e0,
+ 0x8a008a8a,0xf100f1f1,0xd600d6d6,0x7a007a7a,
+ 0xbb00bbbb,0xe300e3e3,0x40004040,0x4f004f4f,
+};
+
+static const u32 camellia_sp4404[256] = {
+ 0x70700070,0x2c2c002c,0xb3b300b3,0xc0c000c0,
+ 0xe4e400e4,0x57570057,0xeaea00ea,0xaeae00ae,
+ 0x23230023,0x6b6b006b,0x45450045,0xa5a500a5,
+ 0xeded00ed,0x4f4f004f,0x1d1d001d,0x92920092,
+ 0x86860086,0xafaf00af,0x7c7c007c,0x1f1f001f,
+ 0x3e3e003e,0xdcdc00dc,0x5e5e005e,0x0b0b000b,
+ 0xa6a600a6,0x39390039,0xd5d500d5,0x5d5d005d,
+ 0xd9d900d9,0x5a5a005a,0x51510051,0x6c6c006c,
+ 0x8b8b008b,0x9a9a009a,0xfbfb00fb,0xb0b000b0,
+ 0x74740074,0x2b2b002b,0xf0f000f0,0x84840084,
+ 0xdfdf00df,0xcbcb00cb,0x34340034,0x76760076,
+ 0x6d6d006d,0xa9a900a9,0xd1d100d1,0x04040004,
+ 0x14140014,0x3a3a003a,0xdede00de,0x11110011,
+ 0x32320032,0x9c9c009c,0x53530053,0xf2f200f2,
+ 0xfefe00fe,0xcfcf00cf,0xc3c300c3,0x7a7a007a,
+ 0x24240024,0xe8e800e8,0x60600060,0x69690069,
+ 0xaaaa00aa,0xa0a000a0,0xa1a100a1,0x62620062,
+ 0x54540054,0x1e1e001e,0xe0e000e0,0x64640064,
+ 0x10100010,0x00000000,0xa3a300a3,0x75750075,
+ 0x8a8a008a,0xe6e600e6,0x09090009,0xdddd00dd,
+ 0x87870087,0x83830083,0xcdcd00cd,0x90900090,
+ 0x73730073,0xf6f600f6,0x9d9d009d,0xbfbf00bf,
+ 0x52520052,0xd8d800d8,0xc8c800c8,0xc6c600c6,
+ 0x81810081,0x6f6f006f,0x13130013,0x63630063,
+ 0xe9e900e9,0xa7a700a7,0x9f9f009f,0xbcbc00bc,
+ 0x29290029,0xf9f900f9,0x2f2f002f,0xb4b400b4,
+ 0x78780078,0x06060006,0xe7e700e7,0x71710071,
+ 0xd4d400d4,0xabab00ab,0x88880088,0x8d8d008d,
+ 0x72720072,0xb9b900b9,0xf8f800f8,0xacac00ac,
+ 0x36360036,0x2a2a002a,0x3c3c003c,0xf1f100f1,
+ 0x40400040,0xd3d300d3,0xbbbb00bb,0x43430043,
+ 0x15150015,0xadad00ad,0x77770077,0x80800080,
+ 0x82820082,0xecec00ec,0x27270027,0xe5e500e5,
+ 0x85850085,0x35350035,0x0c0c000c,0x41410041,
+ 0xefef00ef,0x93930093,0x19190019,0x21210021,
+ 0x0e0e000e,0x4e4e004e,0x65650065,0xbdbd00bd,
+ 0xb8b800b8,0x8f8f008f,0xebeb00eb,0xcece00ce,
+ 0x30300030,0x5f5f005f,0xc5c500c5,0x1a1a001a,
+ 0xe1e100e1,0xcaca00ca,0x47470047,0x3d3d003d,
+ 0x01010001,0xd6d600d6,0x56560056,0x4d4d004d,
+ 0x0d0d000d,0x66660066,0xcccc00cc,0x2d2d002d,
+ 0x12120012,0x20200020,0xb1b100b1,0x99990099,
+ 0x4c4c004c,0xc2c200c2,0x7e7e007e,0x05050005,
+ 0xb7b700b7,0x31310031,0x17170017,0xd7d700d7,
+ 0x58580058,0x61610061,0x1b1b001b,0x1c1c001c,
+ 0x0f0f000f,0x16160016,0x18180018,0x22220022,
+ 0x44440044,0xb2b200b2,0xb5b500b5,0x91910091,
+ 0x08080008,0xa8a800a8,0xfcfc00fc,0x50500050,
+ 0xd0d000d0,0x7d7d007d,0x89890089,0x97970097,
+ 0x5b5b005b,0x95950095,0xffff00ff,0xd2d200d2,
+ 0xc4c400c4,0x48480048,0xf7f700f7,0xdbdb00db,
+ 0x03030003,0xdada00da,0x3f3f003f,0x94940094,
+ 0x5c5c005c,0x02020002,0x4a4a004a,0x33330033,
+ 0x67670067,0xf3f300f3,0x7f7f007f,0xe2e200e2,
+ 0x9b9b009b,0x26260026,0x37370037,0x3b3b003b,
+ 0x96960096,0x4b4b004b,0xbebe00be,0x2e2e002e,
+ 0x79790079,0x8c8c008c,0x6e6e006e,0x8e8e008e,
+ 0xf5f500f5,0xb6b600b6,0xfdfd00fd,0x59590059,
+ 0x98980098,0x6a6a006a,0x46460046,0xbaba00ba,
+ 0x25250025,0x42420042,0xa2a200a2,0xfafa00fa,
+ 0x07070007,0x55550055,0xeeee00ee,0x0a0a000a,
+ 0x49490049,0x68680068,0x38380038,0xa4a400a4,
+ 0x28280028,0x7b7b007b,0xc9c900c9,0xc1c100c1,
+ 0xe3e300e3,0xf4f400f4,0xc7c700c7,0x9e9e009e,
+};
+
+
+/**
+ * Stuff related to the Camellia key schedule
+ */
+#define subl(x) subL[(x)]
+#define subr(x) subR[(x)]
+
+static void camellia_setup128(const unsigned char *key, u32 *subkey)
+{
+ u32 kll, klr, krl, krr;
+ u32 il, ir, t0, t1, w0, w1;
+ u32 kw4l, kw4r, dw, tl, tr;
+ u32 subL[26];
+ u32 subR[26];
+
+ /**
+ * k == kll || klr || krl || krr (|| is concatination)
+ */
+ kll = GETU32(key );
+ klr = GETU32(key + 4);
+ krl = GETU32(key + 8);
+ krr = GETU32(key + 12);
+ /**
+ * generate KL dependent subkeys
+ */
+ subl(0) = kll; subr(0) = klr;
+ subl(1) = krl; subr(1) = krr;
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 15);
+ subl(4) = kll; subr(4) = klr;
+ subl(5) = krl; subr(5) = krr;
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 30);
+ subl(10) = kll; subr(10) = klr;
+ subl(11) = krl; subr(11) = krr;
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 15);
+ subl(13) = krl; subr(13) = krr;
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 17);
+ subl(16) = kll; subr(16) = klr;
+ subl(17) = krl; subr(17) = krr;
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 17);
+ subl(18) = kll; subr(18) = klr;
+ subl(19) = krl; subr(19) = krr;
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 17);
+ subl(22) = kll; subr(22) = klr;
+ subl(23) = krl; subr(23) = krr;
+
+ /* generate KA */
+ kll = subl(0); klr = subr(0);
+ krl = subl(1); krr = subr(1);
+ CAMELLIA_F(kll, klr,
+ CAMELLIA_SIGMA1L, CAMELLIA_SIGMA1R,
+ w0, w1, il, ir, t0, t1);
+ krl ^= w0; krr ^= w1;
+ CAMELLIA_F(krl, krr,
+ CAMELLIA_SIGMA2L, CAMELLIA_SIGMA2R,
+ kll, klr, il, ir, t0, t1);
+ CAMELLIA_F(kll, klr,
+ CAMELLIA_SIGMA3L, CAMELLIA_SIGMA3R,
+ krl, krr, il, ir, t0, t1);
+ krl ^= w0; krr ^= w1;
+ CAMELLIA_F(krl, krr,
+ CAMELLIA_SIGMA4L, CAMELLIA_SIGMA4R,
+ w0, w1, il, ir, t0, t1);
+ kll ^= w0; klr ^= w1;
+
+ /* generate KA dependent subkeys */
+ subl(2) = kll; subr(2) = klr;
+ subl(3) = krl; subr(3) = krr;
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 15);
+ subl(6) = kll; subr(6) = klr;
+ subl(7) = krl; subr(7) = krr;
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 15);
+ subl(8) = kll; subr(8) = klr;
+ subl(9) = krl; subr(9) = krr;
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 15);
+ subl(12) = kll; subr(12) = klr;
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 15);
+ subl(14) = kll; subr(14) = klr;
+ subl(15) = krl; subr(15) = krr;
+ CAMELLIA_ROLDQo32(kll, klr, krl, krr, w0, w1, 34);
+ subl(20) = kll; subr(20) = klr;
+ subl(21) = krl; subr(21) = krr;
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 17);
+ subl(24) = kll; subr(24) = klr;
+ subl(25) = krl; subr(25) = krr;
+
+
+ /* absorb kw2 to other subkeys */
+ subl(3) ^= subl(1); subr(3) ^= subr(1);
+ subl(5) ^= subl(1); subr(5) ^= subr(1);
+ subl(7) ^= subl(1); subr(7) ^= subr(1);
+ subl(1) ^= subr(1) & ~subr(9);
+ dw = subl(1) & subl(9), subr(1) ^= CAMELLIA_RL1(dw);
+ subl(11) ^= subl(1); subr(11) ^= subr(1);
+ subl(13) ^= subl(1); subr(13) ^= subr(1);
+ subl(15) ^= subl(1); subr(15) ^= subr(1);
+ subl(1) ^= subr(1) & ~subr(17);
+ dw = subl(1) & subl(17), subr(1) ^= CAMELLIA_RL1(dw);
+ subl(19) ^= subl(1); subr(19) ^= subr(1);
+ subl(21) ^= subl(1); subr(21) ^= subr(1);
+ subl(23) ^= subl(1); subr(23) ^= subr(1);
+ subl(24) ^= subl(1); subr(24) ^= subr(1);
+
+ /* absorb kw4 to other subkeys */
+ kw4l = subl(25); kw4r = subr(25);
+ subl(22) ^= kw4l; subr(22) ^= kw4r;
+ subl(20) ^= kw4l; subr(20) ^= kw4r;
+ subl(18) ^= kw4l; subr(18) ^= kw4r;
+ kw4l ^= kw4r & ~subr(16);
+ dw = kw4l & subl(16), kw4r ^= CAMELLIA_RL1(dw);
+ subl(14) ^= kw4l; subr(14) ^= kw4r;
+ subl(12) ^= kw4l; subr(12) ^= kw4r;
+ subl(10) ^= kw4l; subr(10) ^= kw4r;
+ kw4l ^= kw4r & ~subr(8);
+ dw = kw4l & subl(8), kw4r ^= CAMELLIA_RL1(dw);
+ subl(6) ^= kw4l; subr(6) ^= kw4r;
+ subl(4) ^= kw4l; subr(4) ^= kw4r;
+ subl(2) ^= kw4l; subr(2) ^= kw4r;
+ subl(0) ^= kw4l; subr(0) ^= kw4r;
+
+ /* key XOR is end of F-function */
+ CamelliaSubkeyL(0) = subl(0) ^ subl(2);
+ CamelliaSubkeyR(0) = subr(0) ^ subr(2);
+ CamelliaSubkeyL(2) = subl(3);
+ CamelliaSubkeyR(2) = subr(3);
+ CamelliaSubkeyL(3) = subl(2) ^ subl(4);
+ CamelliaSubkeyR(3) = subr(2) ^ subr(4);
+ CamelliaSubkeyL(4) = subl(3) ^ subl(5);
+ CamelliaSubkeyR(4) = subr(3) ^ subr(5);
+ CamelliaSubkeyL(5) = subl(4) ^ subl(6);
+ CamelliaSubkeyR(5) = subr(4) ^ subr(6);
+ CamelliaSubkeyL(6) = subl(5) ^ subl(7);
+ CamelliaSubkeyR(6) = subr(5) ^ subr(7);
+ tl = subl(10) ^ (subr(10) & ~subr(8));
+ dw = tl & subl(8), tr = subr(10) ^ CAMELLIA_RL1(dw);
+ CamelliaSubkeyL(7) = subl(6) ^ tl;
+ CamelliaSubkeyR(7) = subr(6) ^ tr;
+ CamelliaSubkeyL(8) = subl(8);
+ CamelliaSubkeyR(8) = subr(8);
+ CamelliaSubkeyL(9) = subl(9);
+ CamelliaSubkeyR(9) = subr(9);
+ tl = subl(7) ^ (subr(7) & ~subr(9));
+ dw = tl & subl(9), tr = subr(7) ^ CAMELLIA_RL1(dw);
+ CamelliaSubkeyL(10) = tl ^ subl(11);
+ CamelliaSubkeyR(10) = tr ^ subr(11);
+ CamelliaSubkeyL(11) = subl(10) ^ subl(12);
+ CamelliaSubkeyR(11) = subr(10) ^ subr(12);
+ CamelliaSubkeyL(12) = subl(11) ^ subl(13);
+ CamelliaSubkeyR(12) = subr(11) ^ subr(13);
+ CamelliaSubkeyL(13) = subl(12) ^ subl(14);
+ CamelliaSubkeyR(13) = subr(12) ^ subr(14);
+ CamelliaSubkeyL(14) = subl(13) ^ subl(15);
+ CamelliaSubkeyR(14) = subr(13) ^ subr(15);
+ tl = subl(18) ^ (subr(18) & ~subr(16));
+ dw = tl & subl(16), tr = subr(18) ^ CAMELLIA_RL1(dw);
+ CamelliaSubkeyL(15) = subl(14) ^ tl;
+ CamelliaSubkeyR(15) = subr(14) ^ tr;
+ CamelliaSubkeyL(16) = subl(16);
+ CamelliaSubkeyR(16) = subr(16);
+ CamelliaSubkeyL(17) = subl(17);
+ CamelliaSubkeyR(17) = subr(17);
+ tl = subl(15) ^ (subr(15) & ~subr(17));
+ dw = tl & subl(17), tr = subr(15) ^ CAMELLIA_RL1(dw);
+ CamelliaSubkeyL(18) = tl ^ subl(19);
+ CamelliaSubkeyR(18) = tr ^ subr(19);
+ CamelliaSubkeyL(19) = subl(18) ^ subl(20);
+ CamelliaSubkeyR(19) = subr(18) ^ subr(20);
+ CamelliaSubkeyL(20) = subl(19) ^ subl(21);
+ CamelliaSubkeyR(20) = subr(19) ^ subr(21);
+ CamelliaSubkeyL(21) = subl(20) ^ subl(22);
+ CamelliaSubkeyR(21) = subr(20) ^ subr(22);
+ CamelliaSubkeyL(22) = subl(21) ^ subl(23);
+ CamelliaSubkeyR(22) = subr(21) ^ subr(23);
+ CamelliaSubkeyL(23) = subl(22);
+ CamelliaSubkeyR(23) = subr(22);
+ CamelliaSubkeyL(24) = subl(24) ^ subl(23);
+ CamelliaSubkeyR(24) = subr(24) ^ subr(23);
+
+ /* apply the inverse of the last half of P-function */
+ dw = CamelliaSubkeyL(2) ^ CamelliaSubkeyR(2), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(2) = CamelliaSubkeyL(2) ^ dw, CamelliaSubkeyL(2) = dw;
+ dw = CamelliaSubkeyL(3) ^ CamelliaSubkeyR(3), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(3) = CamelliaSubkeyL(3) ^ dw, CamelliaSubkeyL(3) = dw;
+ dw = CamelliaSubkeyL(4) ^ CamelliaSubkeyR(4), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(4) = CamelliaSubkeyL(4) ^ dw, CamelliaSubkeyL(4) = dw;
+ dw = CamelliaSubkeyL(5) ^ CamelliaSubkeyR(5), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(5) = CamelliaSubkeyL(5) ^ dw, CamelliaSubkeyL(5) = dw;
+ dw = CamelliaSubkeyL(6) ^ CamelliaSubkeyR(6), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(6) = CamelliaSubkeyL(6) ^ dw, CamelliaSubkeyL(6) = dw;
+ dw = CamelliaSubkeyL(7) ^ CamelliaSubkeyR(7), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(7) = CamelliaSubkeyL(7) ^ dw, CamelliaSubkeyL(7) = dw;
+ dw = CamelliaSubkeyL(10) ^ CamelliaSubkeyR(10), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(10) = CamelliaSubkeyL(10) ^ dw, CamelliaSubkeyL(10) = dw;
+ dw = CamelliaSubkeyL(11) ^ CamelliaSubkeyR(11), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(11) = CamelliaSubkeyL(11) ^ dw, CamelliaSubkeyL(11) = dw;
+ dw = CamelliaSubkeyL(12) ^ CamelliaSubkeyR(12), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(12) = CamelliaSubkeyL(12) ^ dw, CamelliaSubkeyL(12) = dw;
+ dw = CamelliaSubkeyL(13) ^ CamelliaSubkeyR(13), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(13) = CamelliaSubkeyL(13) ^ dw, CamelliaSubkeyL(13) = dw;
+ dw = CamelliaSubkeyL(14) ^ CamelliaSubkeyR(14), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(14) = CamelliaSubkeyL(14) ^ dw, CamelliaSubkeyL(14) = dw;
+ dw = CamelliaSubkeyL(15) ^ CamelliaSubkeyR(15), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(15) = CamelliaSubkeyL(15) ^ dw, CamelliaSubkeyL(15) = dw;
+ dw = CamelliaSubkeyL(18) ^ CamelliaSubkeyR(18), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(18) = CamelliaSubkeyL(18) ^ dw, CamelliaSubkeyL(18) = dw;
+ dw = CamelliaSubkeyL(19) ^ CamelliaSubkeyR(19), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(19) = CamelliaSubkeyL(19) ^ dw, CamelliaSubkeyL(19) = dw;
+ dw = CamelliaSubkeyL(20) ^ CamelliaSubkeyR(20), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(20) = CamelliaSubkeyL(20) ^ dw, CamelliaSubkeyL(20) = dw;
+ dw = CamelliaSubkeyL(21) ^ CamelliaSubkeyR(21), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(21) = CamelliaSubkeyL(21) ^ dw, CamelliaSubkeyL(21) = dw;
+ dw = CamelliaSubkeyL(22) ^ CamelliaSubkeyR(22), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(22) = CamelliaSubkeyL(22) ^ dw, CamelliaSubkeyL(22) = dw;
+ dw = CamelliaSubkeyL(23) ^ CamelliaSubkeyR(23), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(23) = CamelliaSubkeyL(23) ^ dw, CamelliaSubkeyL(23) = dw;
+
+ return;
+}
+
+static void camellia_setup256(const unsigned char *key, u32 *subkey)
+{
+ u32 kll,klr,krl,krr; /* left half of key */
+ u32 krll,krlr,krrl,krrr; /* right half of key */
+ u32 il, ir, t0, t1, w0, w1; /* temporary variables */
+ u32 kw4l, kw4r, dw, tl, tr;
+ u32 subL[34];
+ u32 subR[34];
+
+ /**
+ * key = (kll || klr || krl || krr || krll || krlr || krrl || krrr)
+ * (|| is concatination)
+ */
+
+ kll = GETU32(key );
+ klr = GETU32(key + 4);
+ krl = GETU32(key + 8);
+ krr = GETU32(key + 12);
+ krll = GETU32(key + 16);
+ krlr = GETU32(key + 20);
+ krrl = GETU32(key + 24);
+ krrr = GETU32(key + 28);
+
+ /* generate KL dependent subkeys */
+ subl(0) = kll; subr(0) = klr;
+ subl(1) = krl; subr(1) = krr;
+ CAMELLIA_ROLDQo32(kll, klr, krl, krr, w0, w1, 45);
+ subl(12) = kll; subr(12) = klr;
+ subl(13) = krl; subr(13) = krr;
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 15);
+ subl(16) = kll; subr(16) = klr;
+ subl(17) = krl; subr(17) = krr;
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 17);
+ subl(22) = kll; subr(22) = klr;
+ subl(23) = krl; subr(23) = krr;
+ CAMELLIA_ROLDQo32(kll, klr, krl, krr, w0, w1, 34);
+ subl(30) = kll; subr(30) = klr;
+ subl(31) = krl; subr(31) = krr;
+
+ /* generate KR dependent subkeys */
+ CAMELLIA_ROLDQ(krll, krlr, krrl, krrr, w0, w1, 15);
+ subl(4) = krll; subr(4) = krlr;
+ subl(5) = krrl; subr(5) = krrr;
+ CAMELLIA_ROLDQ(krll, krlr, krrl, krrr, w0, w1, 15);
+ subl(8) = krll; subr(8) = krlr;
+ subl(9) = krrl; subr(9) = krrr;
+ CAMELLIA_ROLDQ(krll, krlr, krrl, krrr, w0, w1, 30);
+ subl(18) = krll; subr(18) = krlr;
+ subl(19) = krrl; subr(19) = krrr;
+ CAMELLIA_ROLDQo32(krll, krlr, krrl, krrr, w0, w1, 34);
+ subl(26) = krll; subr(26) = krlr;
+ subl(27) = krrl; subr(27) = krrr;
+ CAMELLIA_ROLDQo32(krll, krlr, krrl, krrr, w0, w1, 34);
+
+ /* generate KA */
+ kll = subl(0) ^ krll; klr = subr(0) ^ krlr;
+ krl = subl(1) ^ krrl; krr = subr(1) ^ krrr;
+ CAMELLIA_F(kll, klr,
+ CAMELLIA_SIGMA1L, CAMELLIA_SIGMA1R,
+ w0, w1, il, ir, t0, t1);
+ krl ^= w0; krr ^= w1;
+ CAMELLIA_F(krl, krr,
+ CAMELLIA_SIGMA2L, CAMELLIA_SIGMA2R,
+ kll, klr, il, ir, t0, t1);
+ kll ^= krll; klr ^= krlr;
+ CAMELLIA_F(kll, klr,
+ CAMELLIA_SIGMA3L, CAMELLIA_SIGMA3R,
+ krl, krr, il, ir, t0, t1);
+ krl ^= w0 ^ krrl; krr ^= w1 ^ krrr;
+ CAMELLIA_F(krl, krr,
+ CAMELLIA_SIGMA4L, CAMELLIA_SIGMA4R,
+ w0, w1, il, ir, t0, t1);
+ kll ^= w0; klr ^= w1;
+
+ /* generate KB */
+ krll ^= kll; krlr ^= klr;
+ krrl ^= krl; krrr ^= krr;
+ CAMELLIA_F(krll, krlr,
+ CAMELLIA_SIGMA5L, CAMELLIA_SIGMA5R,
+ w0, w1, il, ir, t0, t1);
+ krrl ^= w0; krrr ^= w1;
+ CAMELLIA_F(krrl, krrr,
+ CAMELLIA_SIGMA6L, CAMELLIA_SIGMA6R,
+ w0, w1, il, ir, t0, t1);
+ krll ^= w0; krlr ^= w1;
+
+ /* generate KA dependent subkeys */
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 15);
+ subl(6) = kll; subr(6) = klr;
+ subl(7) = krl; subr(7) = krr;
+ CAMELLIA_ROLDQ(kll, klr, krl, krr, w0, w1, 30);
+ subl(14) = kll; subr(14) = klr;
+ subl(15) = krl; subr(15) = krr;
+ subl(24) = klr; subr(24) = krl;
+ subl(25) = krr; subr(25) = kll;
+ CAMELLIA_ROLDQo32(kll, klr, krl, krr, w0, w1, 49);
+ subl(28) = kll; subr(28) = klr;
+ subl(29) = krl; subr(29) = krr;
+
+ /* generate KB dependent subkeys */
+ subl(2) = krll; subr(2) = krlr;
+ subl(3) = krrl; subr(3) = krrr;
+ CAMELLIA_ROLDQ(krll, krlr, krrl, krrr, w0, w1, 30);
+ subl(10) = krll; subr(10) = krlr;
+ subl(11) = krrl; subr(11) = krrr;
+ CAMELLIA_ROLDQ(krll, krlr, krrl, krrr, w0, w1, 30);
+ subl(20) = krll; subr(20) = krlr;
+ subl(21) = krrl; subr(21) = krrr;
+ CAMELLIA_ROLDQo32(krll, krlr, krrl, krrr, w0, w1, 51);
+ subl(32) = krll; subr(32) = krlr;
+ subl(33) = krrl; subr(33) = krrr;
+
+ /* absorb kw2 to other subkeys */
+ subl(3) ^= subl(1); subr(3) ^= subr(1);
+ subl(5) ^= subl(1); subr(5) ^= subr(1);
+ subl(7) ^= subl(1); subr(7) ^= subr(1);
+ subl(1) ^= subr(1) & ~subr(9);
+ dw = subl(1) & subl(9), subr(1) ^= CAMELLIA_RL1(dw);
+ subl(11) ^= subl(1); subr(11) ^= subr(1);
+ subl(13) ^= subl(1); subr(13) ^= subr(1);
+ subl(15) ^= subl(1); subr(15) ^= subr(1);
+ subl(1) ^= subr(1) & ~subr(17);
+ dw = subl(1) & subl(17), subr(1) ^= CAMELLIA_RL1(dw);
+ subl(19) ^= subl(1); subr(19) ^= subr(1);
+ subl(21) ^= subl(1); subr(21) ^= subr(1);
+ subl(23) ^= subl(1); subr(23) ^= subr(1);
+ subl(1) ^= subr(1) & ~subr(25);
+ dw = subl(1) & subl(25), subr(1) ^= CAMELLIA_RL1(dw);
+ subl(27) ^= subl(1); subr(27) ^= subr(1);
+ subl(29) ^= subl(1); subr(29) ^= subr(1);
+ subl(31) ^= subl(1); subr(31) ^= subr(1);
+ subl(32) ^= subl(1); subr(32) ^= subr(1);
+
+ /* absorb kw4 to other subkeys */
+ kw4l = subl(33); kw4r = subr(33);
+ subl(30) ^= kw4l; subr(30) ^= kw4r;
+ subl(28) ^= kw4l; subr(28) ^= kw4r;
+ subl(26) ^= kw4l; subr(26) ^= kw4r;
+ kw4l ^= kw4r & ~subr(24);
+ dw = kw4l & subl(24), kw4r ^= CAMELLIA_RL1(dw);
+ subl(22) ^= kw4l; subr(22) ^= kw4r;
+ subl(20) ^= kw4l; subr(20) ^= kw4r;
+ subl(18) ^= kw4l; subr(18) ^= kw4r;
+ kw4l ^= kw4r & ~subr(16);
+ dw = kw4l & subl(16), kw4r ^= CAMELLIA_RL1(dw);
+ subl(14) ^= kw4l; subr(14) ^= kw4r;
+ subl(12) ^= kw4l; subr(12) ^= kw4r;
+ subl(10) ^= kw4l; subr(10) ^= kw4r;
+ kw4l ^= kw4r & ~subr(8);
+ dw = kw4l & subl(8), kw4r ^= CAMELLIA_RL1(dw);
+ subl(6) ^= kw4l; subr(6) ^= kw4r;
+ subl(4) ^= kw4l; subr(4) ^= kw4r;
+ subl(2) ^= kw4l; subr(2) ^= kw4r;
+ subl(0) ^= kw4l; subr(0) ^= kw4r;
+
+ /* key XOR is end of F-function */
+ CamelliaSubkeyL(0) = subl(0) ^ subl(2);
+ CamelliaSubkeyR(0) = subr(0) ^ subr(2);
+ CamelliaSubkeyL(2) = subl(3);
+ CamelliaSubkeyR(2) = subr(3);
+ CamelliaSubkeyL(3) = subl(2) ^ subl(4);
+ CamelliaSubkeyR(3) = subr(2) ^ subr(4);
+ CamelliaSubkeyL(4) = subl(3) ^ subl(5);
+ CamelliaSubkeyR(4) = subr(3) ^ subr(5);
+ CamelliaSubkeyL(5) = subl(4) ^ subl(6);
+ CamelliaSubkeyR(5) = subr(4) ^ subr(6);
+ CamelliaSubkeyL(6) = subl(5) ^ subl(7);
+ CamelliaSubkeyR(6) = subr(5) ^ subr(7);
+ tl = subl(10) ^ (subr(10) & ~subr(8));
+ dw = tl & subl(8), tr = subr(10) ^ CAMELLIA_RL1(dw);
+ CamelliaSubkeyL(7) = subl(6) ^ tl;
+ CamelliaSubkeyR(7) = subr(6) ^ tr;
+ CamelliaSubkeyL(8) = subl(8);
+ CamelliaSubkeyR(8) = subr(8);
+ CamelliaSubkeyL(9) = subl(9);
+ CamelliaSubkeyR(9) = subr(9);
+ tl = subl(7) ^ (subr(7) & ~subr(9));
+ dw = tl & subl(9), tr = subr(7) ^ CAMELLIA_RL1(dw);
+ CamelliaSubkeyL(10) = tl ^ subl(11);
+ CamelliaSubkeyR(10) = tr ^ subr(11);
+ CamelliaSubkeyL(11) = subl(10) ^ subl(12);
+ CamelliaSubkeyR(11) = subr(10) ^ subr(12);
+ CamelliaSubkeyL(12) = subl(11) ^ subl(13);
+ CamelliaSubkeyR(12) = subr(11) ^ subr(13);
+ CamelliaSubkeyL(13) = subl(12) ^ subl(14);
+ CamelliaSubkeyR(13) = subr(12) ^ subr(14);
+ CamelliaSubkeyL(14) = subl(13) ^ subl(15);
+ CamelliaSubkeyR(14) = subr(13) ^ subr(15);
+ tl = subl(18) ^ (subr(18) & ~subr(16));
+ dw = tl & subl(16), tr = subr(18) ^ CAMELLIA_RL1(dw);
+ CamelliaSubkeyL(15) = subl(14) ^ tl;
+ CamelliaSubkeyR(15) = subr(14) ^ tr;
+ CamelliaSubkeyL(16) = subl(16);
+ CamelliaSubkeyR(16) = subr(16);
+ CamelliaSubkeyL(17) = subl(17);
+ CamelliaSubkeyR(17) = subr(17);
+ tl = subl(15) ^ (subr(15) & ~subr(17));
+ dw = tl & subl(17), tr = subr(15) ^ CAMELLIA_RL1(dw);
+ CamelliaSubkeyL(18) = tl ^ subl(19);
+ CamelliaSubkeyR(18) = tr ^ subr(19);
+ CamelliaSubkeyL(19) = subl(18) ^ subl(20);
+ CamelliaSubkeyR(19) = subr(18) ^ subr(20);
+ CamelliaSubkeyL(20) = subl(19) ^ subl(21);
+ CamelliaSubkeyR(20) = subr(19) ^ subr(21);
+ CamelliaSubkeyL(21) = subl(20) ^ subl(22);
+ CamelliaSubkeyR(21) = subr(20) ^ subr(22);
+ CamelliaSubkeyL(22) = subl(21) ^ subl(23);
+ CamelliaSubkeyR(22) = subr(21) ^ subr(23);
+ tl = subl(26) ^ (subr(26) & ~subr(24));
+ dw = tl & subl(24), tr = subr(26) ^ CAMELLIA_RL1(dw);
+ CamelliaSubkeyL(23) = subl(22) ^ tl;
+ CamelliaSubkeyR(23) = subr(22) ^ tr;
+ CamelliaSubkeyL(24) = subl(24);
+ CamelliaSubkeyR(24) = subr(24);
+ CamelliaSubkeyL(25) = subl(25);
+ CamelliaSubkeyR(25) = subr(25);
+ tl = subl(23) ^ (subr(23) & ~subr(25));
+ dw = tl & subl(25), tr = subr(23) ^ CAMELLIA_RL1(dw);
+ CamelliaSubkeyL(26) = tl ^ subl(27);
+ CamelliaSubkeyR(26) = tr ^ subr(27);
+ CamelliaSubkeyL(27) = subl(26) ^ subl(28);
+ CamelliaSubkeyR(27) = subr(26) ^ subr(28);
+ CamelliaSubkeyL(28) = subl(27) ^ subl(29);
+ CamelliaSubkeyR(28) = subr(27) ^ subr(29);
+ CamelliaSubkeyL(29) = subl(28) ^ subl(30);
+ CamelliaSubkeyR(29) = subr(28) ^ subr(30);
+ CamelliaSubkeyL(30) = subl(29) ^ subl(31);
+ CamelliaSubkeyR(30) = subr(29) ^ subr(31);
+ CamelliaSubkeyL(31) = subl(30);
+ CamelliaSubkeyR(31) = subr(30);
+ CamelliaSubkeyL(32) = subl(32) ^ subl(31);
+ CamelliaSubkeyR(32) = subr(32) ^ subr(31);
+
+ /* apply the inverse of the last half of P-function */
+ dw = CamelliaSubkeyL(2) ^ CamelliaSubkeyR(2), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(2) = CamelliaSubkeyL(2) ^ dw, CamelliaSubkeyL(2) = dw;
+ dw = CamelliaSubkeyL(3) ^ CamelliaSubkeyR(3), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(3) = CamelliaSubkeyL(3) ^ dw, CamelliaSubkeyL(3) = dw;
+ dw = CamelliaSubkeyL(4) ^ CamelliaSubkeyR(4), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(4) = CamelliaSubkeyL(4) ^ dw, CamelliaSubkeyL(4) = dw;
+ dw = CamelliaSubkeyL(5) ^ CamelliaSubkeyR(5), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(5) = CamelliaSubkeyL(5) ^ dw, CamelliaSubkeyL(5) = dw;
+ dw = CamelliaSubkeyL(6) ^ CamelliaSubkeyR(6), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(6) = CamelliaSubkeyL(6) ^ dw, CamelliaSubkeyL(6) = dw;
+ dw = CamelliaSubkeyL(7) ^ CamelliaSubkeyR(7), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(7) = CamelliaSubkeyL(7) ^ dw, CamelliaSubkeyL(7) = dw;
+ dw = CamelliaSubkeyL(10) ^ CamelliaSubkeyR(10), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(10) = CamelliaSubkeyL(10) ^ dw, CamelliaSubkeyL(10) = dw;
+ dw = CamelliaSubkeyL(11) ^ CamelliaSubkeyR(11), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(11) = CamelliaSubkeyL(11) ^ dw, CamelliaSubkeyL(11) = dw;
+ dw = CamelliaSubkeyL(12) ^ CamelliaSubkeyR(12), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(12) = CamelliaSubkeyL(12) ^ dw, CamelliaSubkeyL(12) = dw;
+ dw = CamelliaSubkeyL(13) ^ CamelliaSubkeyR(13), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(13) = CamelliaSubkeyL(13) ^ dw, CamelliaSubkeyL(13) = dw;
+ dw = CamelliaSubkeyL(14) ^ CamelliaSubkeyR(14), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(14) = CamelliaSubkeyL(14) ^ dw, CamelliaSubkeyL(14) = dw;
+ dw = CamelliaSubkeyL(15) ^ CamelliaSubkeyR(15), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(15) = CamelliaSubkeyL(15) ^ dw, CamelliaSubkeyL(15) = dw;
+ dw = CamelliaSubkeyL(18) ^ CamelliaSubkeyR(18), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(18) = CamelliaSubkeyL(18) ^ dw, CamelliaSubkeyL(18) = dw;
+ dw = CamelliaSubkeyL(19) ^ CamelliaSubkeyR(19), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(19) = CamelliaSubkeyL(19) ^ dw, CamelliaSubkeyL(19) = dw;
+ dw = CamelliaSubkeyL(20) ^ CamelliaSubkeyR(20), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(20) = CamelliaSubkeyL(20) ^ dw, CamelliaSubkeyL(20) = dw;
+ dw = CamelliaSubkeyL(21) ^ CamelliaSubkeyR(21), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(21) = CamelliaSubkeyL(21) ^ dw, CamelliaSubkeyL(21) = dw;
+ dw = CamelliaSubkeyL(22) ^ CamelliaSubkeyR(22), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(22) = CamelliaSubkeyL(22) ^ dw, CamelliaSubkeyL(22) = dw;
+ dw = CamelliaSubkeyL(23) ^ CamelliaSubkeyR(23), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(23) = CamelliaSubkeyL(23) ^ dw, CamelliaSubkeyL(23) = dw;
+ dw = CamelliaSubkeyL(26) ^ CamelliaSubkeyR(26), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(26) = CamelliaSubkeyL(26) ^ dw, CamelliaSubkeyL(26) = dw;
+ dw = CamelliaSubkeyL(27) ^ CamelliaSubkeyR(27), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(27) = CamelliaSubkeyL(27) ^ dw, CamelliaSubkeyL(27) = dw;
+ dw = CamelliaSubkeyL(28) ^ CamelliaSubkeyR(28), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(28) = CamelliaSubkeyL(28) ^ dw, CamelliaSubkeyL(28) = dw;
+ dw = CamelliaSubkeyL(29) ^ CamelliaSubkeyR(29), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(29) = CamelliaSubkeyL(29) ^ dw, CamelliaSubkeyL(29) = dw;
+ dw = CamelliaSubkeyL(30) ^ CamelliaSubkeyR(30), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(30) = CamelliaSubkeyL(30) ^ dw, CamelliaSubkeyL(30) = dw;
+ dw = CamelliaSubkeyL(31) ^ CamelliaSubkeyR(31), dw = CAMELLIA_RL8(dw);
+ CamelliaSubkeyR(31) = CamelliaSubkeyL(31) ^ dw,CamelliaSubkeyL(31) = dw;
+
+ return;
+}
+
+static void camellia_setup192(const unsigned char *key, u32 *subkey)
+{
+ unsigned char kk[32];
+ u32 krll, krlr, krrl,krrr;
+
+ memcpy(kk, key, 24);
+ memcpy((unsigned char *)&krll, key+16,4);
+ memcpy((unsigned char *)&krlr, key+20,4);
+ krrl = ~krll;
+ krrr = ~krlr;
+ memcpy(kk+24, (unsigned char *)&krrl, 4);
+ memcpy(kk+28, (unsigned char *)&krrr, 4);
+ camellia_setup256(kk, subkey);
+ return;
+}
+
+
+/**
+ * Stuff related to camellia encryption/decryption
+ *
+ * "io" must be 4byte aligned and big-endian data.
+ */
+static void camellia_encrypt128(const u32 *subkey, u32 *io)
+{
+ u32 il, ir, t0, t1;
+
+ /* pre whitening but absorb kw2*/
+ io[0] ^= CamelliaSubkeyL(0);
+ io[1] ^= CamelliaSubkeyR(0);
+ /* main iteration */
+
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(2),CamelliaSubkeyR(2),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(3),CamelliaSubkeyR(3),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(4),CamelliaSubkeyR(4),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(5),CamelliaSubkeyR(5),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(6),CamelliaSubkeyR(6),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(7),CamelliaSubkeyR(7),
+ io[0],io[1],il,ir,t0,t1);
+
+ CAMELLIA_FLS(io[0],io[1],io[2],io[3],
+ CamelliaSubkeyL(8),CamelliaSubkeyR(8),
+ CamelliaSubkeyL(9),CamelliaSubkeyR(9),
+ t0,t1,il,ir);
+
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(10),CamelliaSubkeyR(10),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(11),CamelliaSubkeyR(11),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(12),CamelliaSubkeyR(12),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(13),CamelliaSubkeyR(13),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(14),CamelliaSubkeyR(14),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(15),CamelliaSubkeyR(15),
+ io[0],io[1],il,ir,t0,t1);
+
+ CAMELLIA_FLS(io[0],io[1],io[2],io[3],
+ CamelliaSubkeyL(16),CamelliaSubkeyR(16),
+ CamelliaSubkeyL(17),CamelliaSubkeyR(17),
+ t0,t1,il,ir);
+
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(18),CamelliaSubkeyR(18),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(19),CamelliaSubkeyR(19),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(20),CamelliaSubkeyR(20),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(21),CamelliaSubkeyR(21),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(22),CamelliaSubkeyR(22),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(23),CamelliaSubkeyR(23),
+ io[0],io[1],il,ir,t0,t1);
+
+ /* post whitening but kw4 */
+ io[2] ^= CamelliaSubkeyL(24);
+ io[3] ^= CamelliaSubkeyR(24);
+
+ t0 = io[0];
+ t1 = io[1];
+ io[0] = io[2];
+ io[1] = io[3];
+ io[2] = t0;
+ io[3] = t1;
+
+ return;
+}
+
+static void camellia_decrypt128(const u32 *subkey, u32 *io)
+{
+ u32 il,ir,t0,t1; /* temporary valiables */
+
+ /* pre whitening but absorb kw2*/
+ io[0] ^= CamelliaSubkeyL(24);
+ io[1] ^= CamelliaSubkeyR(24);
+
+ /* main iteration */
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(23),CamelliaSubkeyR(23),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(22),CamelliaSubkeyR(22),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(21),CamelliaSubkeyR(21),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(20),CamelliaSubkeyR(20),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(19),CamelliaSubkeyR(19),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(18),CamelliaSubkeyR(18),
+ io[0],io[1],il,ir,t0,t1);
+
+ CAMELLIA_FLS(io[0],io[1],io[2],io[3],
+ CamelliaSubkeyL(17),CamelliaSubkeyR(17),
+ CamelliaSubkeyL(16),CamelliaSubkeyR(16),
+ t0,t1,il,ir);
+
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(15),CamelliaSubkeyR(15),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(14),CamelliaSubkeyR(14),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(13),CamelliaSubkeyR(13),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(12),CamelliaSubkeyR(12),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(11),CamelliaSubkeyR(11),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(10),CamelliaSubkeyR(10),
+ io[0],io[1],il,ir,t0,t1);
+
+ CAMELLIA_FLS(io[0],io[1],io[2],io[3],
+ CamelliaSubkeyL(9),CamelliaSubkeyR(9),
+ CamelliaSubkeyL(8),CamelliaSubkeyR(8),
+ t0,t1,il,ir);
+
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(7),CamelliaSubkeyR(7),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(6),CamelliaSubkeyR(6),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(5),CamelliaSubkeyR(5),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(4),CamelliaSubkeyR(4),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(3),CamelliaSubkeyR(3),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(2),CamelliaSubkeyR(2),
+ io[0],io[1],il,ir,t0,t1);
+
+ /* post whitening but kw4 */
+ io[2] ^= CamelliaSubkeyL(0);
+ io[3] ^= CamelliaSubkeyR(0);
+
+ t0 = io[0];
+ t1 = io[1];
+ io[0] = io[2];
+ io[1] = io[3];
+ io[2] = t0;
+ io[3] = t1;
+
+ return;
+}
+
+/**
+ * stuff for 192 and 256bit encryption/decryption
+ */
+static void camellia_encrypt256(const u32 *subkey, u32 *io)
+{
+ u32 il,ir,t0,t1; /* temporary valiables */
+
+ /* pre whitening but absorb kw2*/
+ io[0] ^= CamelliaSubkeyL(0);
+ io[1] ^= CamelliaSubkeyR(0);
+
+ /* main iteration */
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(2),CamelliaSubkeyR(2),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(3),CamelliaSubkeyR(3),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(4),CamelliaSubkeyR(4),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(5),CamelliaSubkeyR(5),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(6),CamelliaSubkeyR(6),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(7),CamelliaSubkeyR(7),
+ io[0],io[1],il,ir,t0,t1);
+
+ CAMELLIA_FLS(io[0],io[1],io[2],io[3],
+ CamelliaSubkeyL(8),CamelliaSubkeyR(8),
+ CamelliaSubkeyL(9),CamelliaSubkeyR(9),
+ t0,t1,il,ir);
+
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(10),CamelliaSubkeyR(10),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(11),CamelliaSubkeyR(11),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(12),CamelliaSubkeyR(12),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(13),CamelliaSubkeyR(13),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(14),CamelliaSubkeyR(14),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(15),CamelliaSubkeyR(15),
+ io[0],io[1],il,ir,t0,t1);
+
+ CAMELLIA_FLS(io[0],io[1],io[2],io[3],
+ CamelliaSubkeyL(16),CamelliaSubkeyR(16),
+ CamelliaSubkeyL(17),CamelliaSubkeyR(17),
+ t0,t1,il,ir);
+
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(18),CamelliaSubkeyR(18),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(19),CamelliaSubkeyR(19),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(20),CamelliaSubkeyR(20),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(21),CamelliaSubkeyR(21),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(22),CamelliaSubkeyR(22),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(23),CamelliaSubkeyR(23),
+ io[0],io[1],il,ir,t0,t1);
+
+ CAMELLIA_FLS(io[0],io[1],io[2],io[3],
+ CamelliaSubkeyL(24),CamelliaSubkeyR(24),
+ CamelliaSubkeyL(25),CamelliaSubkeyR(25),
+ t0,t1,il,ir);
+
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(26),CamelliaSubkeyR(26),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(27),CamelliaSubkeyR(27),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(28),CamelliaSubkeyR(28),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(29),CamelliaSubkeyR(29),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(30),CamelliaSubkeyR(30),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(31),CamelliaSubkeyR(31),
+ io[0],io[1],il,ir,t0,t1);
+
+ /* post whitening but kw4 */
+ io[2] ^= CamelliaSubkeyL(32);
+ io[3] ^= CamelliaSubkeyR(32);
+
+ t0 = io[0];
+ t1 = io[1];
+ io[0] = io[2];
+ io[1] = io[3];
+ io[2] = t0;
+ io[3] = t1;
+
+ return;
+}
+
+static void camellia_decrypt256(const u32 *subkey, u32 *io)
+{
+ u32 il,ir,t0,t1; /* temporary valiables */
+
+ /* pre whitening but absorb kw2*/
+ io[0] ^= CamelliaSubkeyL(32);
+ io[1] ^= CamelliaSubkeyR(32);
+
+ /* main iteration */
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(31),CamelliaSubkeyR(31),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(30),CamelliaSubkeyR(30),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(29),CamelliaSubkeyR(29),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(28),CamelliaSubkeyR(28),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(27),CamelliaSubkeyR(27),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(26),CamelliaSubkeyR(26),
+ io[0],io[1],il,ir,t0,t1);
+
+ CAMELLIA_FLS(io[0],io[1],io[2],io[3],
+ CamelliaSubkeyL(25),CamelliaSubkeyR(25),
+ CamelliaSubkeyL(24),CamelliaSubkeyR(24),
+ t0,t1,il,ir);
+
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(23),CamelliaSubkeyR(23),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(22),CamelliaSubkeyR(22),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(21),CamelliaSubkeyR(21),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(20),CamelliaSubkeyR(20),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(19),CamelliaSubkeyR(19),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(18),CamelliaSubkeyR(18),
+ io[0],io[1],il,ir,t0,t1);
+
+ CAMELLIA_FLS(io[0],io[1],io[2],io[3],
+ CamelliaSubkeyL(17),CamelliaSubkeyR(17),
+ CamelliaSubkeyL(16),CamelliaSubkeyR(16),
+ t0,t1,il,ir);
+
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(15),CamelliaSubkeyR(15),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(14),CamelliaSubkeyR(14),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(13),CamelliaSubkeyR(13),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(12),CamelliaSubkeyR(12),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(11),CamelliaSubkeyR(11),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(10),CamelliaSubkeyR(10),
+ io[0],io[1],il,ir,t0,t1);
+
+ CAMELLIA_FLS(io[0],io[1],io[2],io[3],
+ CamelliaSubkeyL(9),CamelliaSubkeyR(9),
+ CamelliaSubkeyL(8),CamelliaSubkeyR(8),
+ t0,t1,il,ir);
+
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(7),CamelliaSubkeyR(7),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(6),CamelliaSubkeyR(6),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(5),CamelliaSubkeyR(5),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(4),CamelliaSubkeyR(4),
+ io[0],io[1],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[0],io[1],
+ CamelliaSubkeyL(3),CamelliaSubkeyR(3),
+ io[2],io[3],il,ir,t0,t1);
+ CAMELLIA_ROUNDSM(io[2],io[3],
+ CamelliaSubkeyL(2),CamelliaSubkeyR(2),
+ io[0],io[1],il,ir,t0,t1);
+
+ /* post whitening but kw4 */
+ io[2] ^= CamelliaSubkeyL(0);
+ io[3] ^= CamelliaSubkeyR(0);
+
+ t0 = io[0];
+ t1 = io[1];
+ io[0] = io[2];
+ io[1] = io[3];
+ io[2] = t0;
+ io[3] = t1;
+
+ return;
+}
+
+/***
+ *
+ * API for compatibility
+ */
+
+void Camellia_Ekeygen(const int keyBitLength,
+ const unsigned char *rawKey,
+ KEY_TABLE_TYPE keyTable)
+{
+ switch(keyBitLength) {
+ case 128:
+ camellia_setup128(rawKey, keyTable);
+ break;
+ case 192:
+ camellia_setup192(rawKey, keyTable);
+ break;
+ case 256:
+ camellia_setup256(rawKey, keyTable);
+ break;
+ default:
+ break;
+ }
+}
+
+
+void Camellia_EncryptBlock(const int keyBitLength,
+ const unsigned char *plaintext,
+ const KEY_TABLE_TYPE keyTable,
+ unsigned char *ciphertext)
+{
+ u32 tmp[4];
+
+ tmp[0] = GETU32(plaintext);
+ tmp[1] = GETU32(plaintext + 4);
+ tmp[2] = GETU32(plaintext + 8);
+ tmp[3] = GETU32(plaintext + 12);
+
+ switch (keyBitLength) {
+ case 128:
+ camellia_encrypt128(keyTable, tmp);
+ break;
+ case 192:
+ /* fall through */
+ case 256:
+ camellia_encrypt256(keyTable, tmp);
+ break;
+ default:
+ break;
+ }
+
+ PUTU32(ciphertext, tmp[0]);
+ PUTU32(ciphertext + 4, tmp[1]);
+ PUTU32(ciphertext + 8, tmp[2]);
+ PUTU32(ciphertext + 12, tmp[3]);
+}
+
+void Camellia_DecryptBlock(const int keyBitLength,
+ const unsigned char *ciphertext,
+ const KEY_TABLE_TYPE keyTable,
+ unsigned char *plaintext)
+{
+ u32 tmp[4];
+
+ tmp[0] = GETU32(ciphertext);
+ tmp[1] = GETU32(ciphertext + 4);
+ tmp[2] = GETU32(ciphertext + 8);
+ tmp[3] = GETU32(ciphertext + 12);
+
+ switch (keyBitLength) {
+ case 128:
+ camellia_decrypt128(keyTable, tmp);
+ break;
+ case 192:
+ /* fall through */
+ case 256:
+ camellia_decrypt256(keyTable, tmp);
+ break;
+ default:
+ break;
+ }
+ PUTU32(plaintext, tmp[0]);
+ PUTU32(plaintext + 4, tmp[1]);
+ PUTU32(plaintext + 8, tmp[2]);
+ PUTU32(plaintext + 12, tmp[3]);
+}
diff --git a/third_party/heimdal/lib/hcrypto/camellia-ntt.h b/third_party/heimdal/lib/hcrypto/camellia-ntt.h
new file mode 100644
index 0000000..cc0b70d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/camellia-ntt.h
@@ -0,0 +1,63 @@
+/* camellia.h ver 1.2.0
+ *
+ * Copyright (C) 2006,2007
+ * NTT (Nippon Telegraph and Telephone Corporation).
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ */
+
+#ifndef HEADER_CAMELLIA_H
+#define HEADER_CAMELLIA_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* symbol renaming */
+#define Camellia_DecryptBlock hc_Camellia_DecryptBlock
+#define Camellia_Ekeygen hc_Camellia_Ekeygen
+#define Camellia_EncryptBlock hc_Camellia_EncryptBlock
+
+#define CAMELLIA_BLOCK_SIZE 16
+#define CAMELLIA_TABLE_BYTE_LEN 272
+#define CAMELLIA_TABLE_WORD_LEN (CAMELLIA_TABLE_BYTE_LEN / 4)
+
+/* u32 must be 32bit word */
+typedef uint32_t u32;
+typedef unsigned char u8;
+
+typedef u32 KEY_TABLE_TYPE[CAMELLIA_TABLE_WORD_LEN];
+
+
+void Camellia_Ekeygen(const int keyBitLength,
+ const unsigned char *rawKey,
+ KEY_TABLE_TYPE keyTable);
+
+void Camellia_EncryptBlock(const int keyBitLength,
+ const unsigned char *plaintext,
+ const KEY_TABLE_TYPE keyTable,
+ unsigned char *cipherText);
+
+void Camellia_DecryptBlock(const int keyBitLength,
+ const unsigned char *cipherText,
+ const KEY_TABLE_TYPE keyTable,
+ unsigned char *plaintext);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* HEADER_CAMELLIA_H */
diff --git a/third_party/heimdal/lib/hcrypto/camellia.c b/third_party/heimdal/lib/hcrypto/camellia.c
new file mode 100644
index 0000000..bc861a0
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/camellia.c
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#ifdef KRB5
+#include <krb5-types.h>
+#endif
+
+#include "camellia-ntt.h"
+#include "camellia.h"
+
+int
+CAMELLIA_set_key(const unsigned char *userkey,
+ const int bits, CAMELLIA_KEY *key)
+{
+ key->bits = bits;
+ Camellia_Ekeygen(bits, userkey, key->key);
+ return 1;
+}
+
+void
+CAMELLIA_encrypt(const unsigned char *in, unsigned char *out,
+ const CAMELLIA_KEY *key)
+{
+ Camellia_EncryptBlock(key->bits, in, key->key, out);
+
+}
+
+void
+CAMELLIA_decrypt(const unsigned char *in, unsigned char *out,
+ const CAMELLIA_KEY *key)
+{
+ Camellia_DecryptBlock(key->bits, in, key->key, out);
+}
+
+void
+CAMELLIA_cbc_encrypt(const unsigned char *in, unsigned char *out,
+ unsigned long size, const CAMELLIA_KEY *key,
+ unsigned char *iv, int mode_encrypt)
+{
+ unsigned char tmp[CAMELLIA_BLOCK_SIZE];
+ int i;
+
+ if (mode_encrypt) {
+ while (size >= CAMELLIA_BLOCK_SIZE) {
+ for (i = 0; i < CAMELLIA_BLOCK_SIZE; i++)
+ tmp[i] = in[i] ^ iv[i];
+ CAMELLIA_encrypt(tmp, out, key);
+ memcpy(iv, out, CAMELLIA_BLOCK_SIZE);
+ size -= CAMELLIA_BLOCK_SIZE;
+ in += CAMELLIA_BLOCK_SIZE;
+ out += CAMELLIA_BLOCK_SIZE;
+ }
+ if (size) {
+ for (i = 0; i < size; i++)
+ tmp[i] = in[i] ^ iv[i];
+ for (i = size; i < CAMELLIA_BLOCK_SIZE; i++)
+ tmp[i] = iv[i];
+ CAMELLIA_encrypt(tmp, out, key);
+ memcpy(iv, out, CAMELLIA_BLOCK_SIZE);
+ }
+ } else {
+ while (size >= CAMELLIA_BLOCK_SIZE) {
+ memcpy(tmp, in, CAMELLIA_BLOCK_SIZE);
+ CAMELLIA_decrypt(tmp, out, key);
+ for (i = 0; i < CAMELLIA_BLOCK_SIZE; i++)
+ out[i] ^= iv[i];
+ memcpy(iv, tmp, CAMELLIA_BLOCK_SIZE);
+ size -= CAMELLIA_BLOCK_SIZE;
+ in += CAMELLIA_BLOCK_SIZE;
+ out += CAMELLIA_BLOCK_SIZE;
+ }
+ if (size) {
+ memcpy(tmp, in, CAMELLIA_BLOCK_SIZE);
+ CAMELLIA_decrypt(tmp, out, key);
+ for (i = 0; i < size; i++)
+ out[i] ^= iv[i];
+ memcpy(iv, tmp, CAMELLIA_BLOCK_SIZE);
+ }
+ }
+}
diff --git a/third_party/heimdal/lib/hcrypto/camellia.h b/third_party/heimdal/lib/hcrypto/camellia.h
new file mode 100644
index 0000000..6661f3b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/camellia.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_CAMELLIA_H
+#define HEIM_CAMELLIA_H 1
+
+/* symbol renaming */
+#define CAMELLIA_set_key hc_CAMELLIA_set_encrypt_key
+#define CAMELLIA_encrypt hc_CAMELLIA_encrypt
+#define CAMELLIA_decrypt hc_CAMELLIA_decrypt
+#define CAMELLIA_cbc_encrypt hc_CAMELLIA_cbc_encrypt
+
+/*
+ *
+ */
+
+#define CAMELLIA_BLOCK_SIZE 16
+#define CAMELLIA_TABLE_BYTE_LEN 272
+#define CAMELLIA_TABLE_WORD_LEN (CAMELLIA_TABLE_BYTE_LEN / 4)
+
+#define CAMELLIA_ENCRYPT 1
+#define CAMELLIA_DECRYPT 0
+
+typedef struct camellia_key {
+ unsigned int bits;
+ uint32_t key[CAMELLIA_TABLE_WORD_LEN];
+} CAMELLIA_KEY;
+
+int CAMELLIA_set_key(const unsigned char *, const int, CAMELLIA_KEY *);
+
+void CAMELLIA_encrypt(const unsigned char *, unsigned char *,
+ const CAMELLIA_KEY *);
+void CAMELLIA_decrypt(const unsigned char *, unsigned char *,
+ const CAMELLIA_KEY *);
+
+void CAMELLIA_cbc_encrypt(const unsigned char *, unsigned char *,
+ unsigned long, const CAMELLIA_KEY *,
+ unsigned char *, int);
+
+#endif /* HEIM_CAMELLIA_H */
diff --git a/third_party/heimdal/lib/hcrypto/common.c b/third_party/heimdal/lib/hcrypto/common.c
new file mode 100644
index 0000000..cf30304
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/common.c
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <krb5-types.h>
+#include <rfc2459_asn1.h>
+#include <hcrypto/bn.h>
+
+
+#include "common.h"
+
+int
+_hc_BN_to_integer(BIGNUM *bn, heim_integer *integer)
+{
+ integer->length = BN_num_bytes(bn);
+ integer->data = malloc(integer->length);
+ if (integer->data == NULL)
+ return ENOMEM;
+ BN_bn2bin(bn, integer->data);
+ integer->negative = BN_is_negative(bn);
+ return 0;
+}
+
+BIGNUM *
+_hc_integer_to_BN(const heim_integer *i, BIGNUM *bn)
+{
+ bn = BN_bin2bn(i->data, i->length, bn);
+ if (bn)
+ BN_set_negative(bn, i->negative);
+ return bn;
+}
diff --git a/third_party/heimdal/lib/hcrypto/common.h b/third_party/heimdal/lib/hcrypto/common.h
new file mode 100644
index 0000000..f78f544
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/common.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef HCRYPTO_COMMON_H
+#define HCRYPTO_COMMON_H 1
+
+int
+_hc_BN_to_integer(BIGNUM *, heim_integer *);
+
+BIGNUM *
+_hc_integer_to_BN(const heim_integer *i, BIGNUM *bn);
+
+#endif /* HCRYPTO_COMMON_H */
diff --git a/third_party/heimdal/lib/hcrypto/des-tables.h b/third_party/heimdal/lib/hcrypto/des-tables.h
new file mode 100644
index 0000000..95f3711
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/des-tables.h
@@ -0,0 +1,196 @@
+/* GENERATE FILE from gen-des.pl, do not edit */
+
+/* pc1_c_3 bit pattern 5 13 21 */
+static int pc1_c_3[8] = {
+ 0x00000000, 0x00000010, 0x00001000, 0x00001010,
+ 0x00100000, 0x00100010, 0x00101000, 0x00101010
+};
+/* pc1_c_4 bit pattern 1 9 17 25 */
+static int pc1_c_4[16] = {
+ 0x00000000, 0x00000001, 0x00000100, 0x00000101,
+ 0x00010000, 0x00010001, 0x00010100, 0x00010101,
+ 0x01000000, 0x01000001, 0x01000100, 0x01000101,
+ 0x01010000, 0x01010001, 0x01010100, 0x01010101
+};
+/* pc1_d_3 bit pattern 49 41 33 */
+static int pc1_d_3[8] = {
+ 0x00000000, 0x01000000, 0x00010000, 0x01010000,
+ 0x00000100, 0x01000100, 0x00010100, 0x01010100
+};
+/* pc1_d_4 bit pattern 57 53 45 37 */
+static int pc1_d_4[16] = {
+ 0x00000000, 0x00100000, 0x00001000, 0x00101000,
+ 0x00000010, 0x00100010, 0x00001010, 0x00101010,
+ 0x00000001, 0x00100001, 0x00001001, 0x00101001,
+ 0x00000011, 0x00100011, 0x00001011, 0x00101011
+};
+/* pc2_c_1 bit pattern 5 24 7 16 6 10 */
+static int pc2_c_1[64] = {
+ 0x00000000, 0x00004000, 0x00040000, 0x00044000,
+ 0x00000100, 0x00004100, 0x00040100, 0x00044100,
+ 0x00020000, 0x00024000, 0x00060000, 0x00064000,
+ 0x00020100, 0x00024100, 0x00060100, 0x00064100,
+ 0x00000001, 0x00004001, 0x00040001, 0x00044001,
+ 0x00000101, 0x00004101, 0x00040101, 0x00044101,
+ 0x00020001, 0x00024001, 0x00060001, 0x00064001,
+ 0x00020101, 0x00024101, 0x00060101, 0x00064101,
+ 0x00080000, 0x00084000, 0x000c0000, 0x000c4000,
+ 0x00080100, 0x00084100, 0x000c0100, 0x000c4100,
+ 0x000a0000, 0x000a4000, 0x000e0000, 0x000e4000,
+ 0x000a0100, 0x000a4100, 0x000e0100, 0x000e4100,
+ 0x00080001, 0x00084001, 0x000c0001, 0x000c4001,
+ 0x00080101, 0x00084101, 0x000c0101, 0x000c4101,
+ 0x000a0001, 0x000a4001, 0x000e0001, 0x000e4001,
+ 0x000a0101, 0x000a4101, 0x000e0101, 0x000e4101
+};
+/* pc2_c_2 bit pattern 20 18 12 3 15 23 */
+static int pc2_c_2[64] = {
+ 0x00000000, 0x00000002, 0x00000200, 0x00000202,
+ 0x00200000, 0x00200002, 0x00200200, 0x00200202,
+ 0x00001000, 0x00001002, 0x00001200, 0x00001202,
+ 0x00201000, 0x00201002, 0x00201200, 0x00201202,
+ 0x00000040, 0x00000042, 0x00000240, 0x00000242,
+ 0x00200040, 0x00200042, 0x00200240, 0x00200242,
+ 0x00001040, 0x00001042, 0x00001240, 0x00001242,
+ 0x00201040, 0x00201042, 0x00201240, 0x00201242,
+ 0x00000010, 0x00000012, 0x00000210, 0x00000212,
+ 0x00200010, 0x00200012, 0x00200210, 0x00200212,
+ 0x00001010, 0x00001012, 0x00001210, 0x00001212,
+ 0x00201010, 0x00201012, 0x00201210, 0x00201212,
+ 0x00000050, 0x00000052, 0x00000250, 0x00000252,
+ 0x00200050, 0x00200052, 0x00200250, 0x00200252,
+ 0x00001050, 0x00001052, 0x00001250, 0x00001252,
+ 0x00201050, 0x00201052, 0x00201250, 0x00201252
+};
+/* pc2_c_3 bit pattern 1 9 19 2 14 22 */
+static int pc2_c_3[64] = {
+ 0x00000000, 0x00000004, 0x00000400, 0x00000404,
+ 0x00400000, 0x00400004, 0x00400400, 0x00400404,
+ 0x00000020, 0x00000024, 0x00000420, 0x00000424,
+ 0x00400020, 0x00400024, 0x00400420, 0x00400424,
+ 0x00008000, 0x00008004, 0x00008400, 0x00008404,
+ 0x00408000, 0x00408004, 0x00408400, 0x00408404,
+ 0x00008020, 0x00008024, 0x00008420, 0x00008424,
+ 0x00408020, 0x00408024, 0x00408420, 0x00408424,
+ 0x00800000, 0x00800004, 0x00800400, 0x00800404,
+ 0x00c00000, 0x00c00004, 0x00c00400, 0x00c00404,
+ 0x00800020, 0x00800024, 0x00800420, 0x00800424,
+ 0x00c00020, 0x00c00024, 0x00c00420, 0x00c00424,
+ 0x00808000, 0x00808004, 0x00808400, 0x00808404,
+ 0x00c08000, 0x00c08004, 0x00c08400, 0x00c08404,
+ 0x00808020, 0x00808024, 0x00808420, 0x00808424,
+ 0x00c08020, 0x00c08024, 0x00c08420, 0x00c08424
+};
+/* pc2_c_4 bit pattern 11 13 4 17 21 8 */
+static int pc2_c_4[64] = {
+ 0x00000000, 0x00010000, 0x00000008, 0x00010008,
+ 0x00000080, 0x00010080, 0x00000088, 0x00010088,
+ 0x00100000, 0x00110000, 0x00100008, 0x00110008,
+ 0x00100080, 0x00110080, 0x00100088, 0x00110088,
+ 0x00000800, 0x00010800, 0x00000808, 0x00010808,
+ 0x00000880, 0x00010880, 0x00000888, 0x00010888,
+ 0x00100800, 0x00110800, 0x00100808, 0x00110808,
+ 0x00100880, 0x00110880, 0x00100888, 0x00110888,
+ 0x00002000, 0x00012000, 0x00002008, 0x00012008,
+ 0x00002080, 0x00012080, 0x00002088, 0x00012088,
+ 0x00102000, 0x00112000, 0x00102008, 0x00112008,
+ 0x00102080, 0x00112080, 0x00102088, 0x00112088,
+ 0x00002800, 0x00012800, 0x00002808, 0x00012808,
+ 0x00002880, 0x00012880, 0x00002888, 0x00012888,
+ 0x00102800, 0x00112800, 0x00102808, 0x00112808,
+ 0x00102880, 0x00112880, 0x00102888, 0x00112888
+};
+/* pc2_d_1 bit pattern 51 35 31 52 39 45 */
+static int pc2_d_1[64] = {
+ 0x00000000, 0x00000080, 0x00002000, 0x00002080,
+ 0x00000001, 0x00000081, 0x00002001, 0x00002081,
+ 0x00200000, 0x00200080, 0x00202000, 0x00202080,
+ 0x00200001, 0x00200081, 0x00202001, 0x00202081,
+ 0x00020000, 0x00020080, 0x00022000, 0x00022080,
+ 0x00020001, 0x00020081, 0x00022001, 0x00022081,
+ 0x00220000, 0x00220080, 0x00222000, 0x00222080,
+ 0x00220001, 0x00220081, 0x00222001, 0x00222081,
+ 0x00000002, 0x00000082, 0x00002002, 0x00002082,
+ 0x00000003, 0x00000083, 0x00002003, 0x00002083,
+ 0x00200002, 0x00200082, 0x00202002, 0x00202082,
+ 0x00200003, 0x00200083, 0x00202003, 0x00202083,
+ 0x00020002, 0x00020082, 0x00022002, 0x00022082,
+ 0x00020003, 0x00020083, 0x00022003, 0x00022083,
+ 0x00220002, 0x00220082, 0x00222002, 0x00222082,
+ 0x00220003, 0x00220083, 0x00222003, 0x00222083
+};
+/* pc2_d_2 bit pattern 50 32 43 36 29 48 */
+static int pc2_d_2[64] = {
+ 0x00000000, 0x00000010, 0x00800000, 0x00800010,
+ 0x00010000, 0x00010010, 0x00810000, 0x00810010,
+ 0x00000200, 0x00000210, 0x00800200, 0x00800210,
+ 0x00010200, 0x00010210, 0x00810200, 0x00810210,
+ 0x00100000, 0x00100010, 0x00900000, 0x00900010,
+ 0x00110000, 0x00110010, 0x00910000, 0x00910010,
+ 0x00100200, 0x00100210, 0x00900200, 0x00900210,
+ 0x00110200, 0x00110210, 0x00910200, 0x00910210,
+ 0x00000004, 0x00000014, 0x00800004, 0x00800014,
+ 0x00010004, 0x00010014, 0x00810004, 0x00810014,
+ 0x00000204, 0x00000214, 0x00800204, 0x00800214,
+ 0x00010204, 0x00010214, 0x00810204, 0x00810214,
+ 0x00100004, 0x00100014, 0x00900004, 0x00900014,
+ 0x00110004, 0x00110014, 0x00910004, 0x00910014,
+ 0x00100204, 0x00100214, 0x00900204, 0x00900214,
+ 0x00110204, 0x00110214, 0x00910204, 0x00910214
+};
+/* pc2_d_3 bit pattern 41 38 47 33 40 42 */
+static int pc2_d_3[64] = {
+ 0x00000000, 0x00000400, 0x00001000, 0x00001400,
+ 0x00080000, 0x00080400, 0x00081000, 0x00081400,
+ 0x00000020, 0x00000420, 0x00001020, 0x00001420,
+ 0x00080020, 0x00080420, 0x00081020, 0x00081420,
+ 0x00004000, 0x00004400, 0x00005000, 0x00005400,
+ 0x00084000, 0x00084400, 0x00085000, 0x00085400,
+ 0x00004020, 0x00004420, 0x00005020, 0x00005420,
+ 0x00084020, 0x00084420, 0x00085020, 0x00085420,
+ 0x00000800, 0x00000c00, 0x00001800, 0x00001c00,
+ 0x00080800, 0x00080c00, 0x00081800, 0x00081c00,
+ 0x00000820, 0x00000c20, 0x00001820, 0x00001c20,
+ 0x00080820, 0x00080c20, 0x00081820, 0x00081c20,
+ 0x00004800, 0x00004c00, 0x00005800, 0x00005c00,
+ 0x00084800, 0x00084c00, 0x00085800, 0x00085c00,
+ 0x00004820, 0x00004c20, 0x00005820, 0x00005c20,
+ 0x00084820, 0x00084c20, 0x00085820, 0x00085c20
+};
+/* pc2_d_4 bit pattern 49 37 30 46 34 44 */
+static int pc2_d_4[64] = {
+ 0x00000000, 0x00000100, 0x00040000, 0x00040100,
+ 0x00000040, 0x00000140, 0x00040040, 0x00040140,
+ 0x00400000, 0x00400100, 0x00440000, 0x00440100,
+ 0x00400040, 0x00400140, 0x00440040, 0x00440140,
+ 0x00008000, 0x00008100, 0x00048000, 0x00048100,
+ 0x00008040, 0x00008140, 0x00048040, 0x00048140,
+ 0x00408000, 0x00408100, 0x00448000, 0x00448100,
+ 0x00408040, 0x00408140, 0x00448040, 0x00448140,
+ 0x00000008, 0x00000108, 0x00040008, 0x00040108,
+ 0x00000048, 0x00000148, 0x00040048, 0x00040148,
+ 0x00400008, 0x00400108, 0x00440008, 0x00440108,
+ 0x00400048, 0x00400148, 0x00440048, 0x00440148,
+ 0x00008008, 0x00008108, 0x00048008, 0x00048108,
+ 0x00008048, 0x00008148, 0x00048048, 0x00048148,
+ 0x00408008, 0x00408108, 0x00448008, 0x00448108,
+ 0x00408048, 0x00408148, 0x00448048, 0x00448148
+};
+static unsigned char odd_parity[256] = {
+ 1, 1, 2, 2, 4, 4, 7, 7, 8, 8, 11, 11, 13, 13, 14, 14,
+ 16, 16, 19, 19, 21, 21, 22, 22, 25, 25, 26, 26, 28, 28, 31, 31,
+ 32, 32, 35, 35, 37, 37, 38, 38, 41, 41, 42, 42, 44, 44, 47, 47,
+ 49, 49, 50, 50, 52, 52, 55, 55, 56, 56, 59, 59, 61, 61, 62, 62,
+ 64, 64, 67, 67, 69, 69, 70, 70, 73, 73, 74, 74, 76, 76, 79, 79,
+ 81, 81, 82, 82, 84, 84, 87, 87, 88, 88, 91, 91, 93, 93, 94, 94,
+ 97, 97, 98, 98,100,100,103,103,104,104,107,107,109,109,110,110,
+112,112,115,115,117,117,118,118,121,121,122,122,124,124,127,127,
+128,128,131,131,133,133,134,134,137,137,138,138,140,140,143,143,
+145,145,146,146,148,148,151,151,152,152,155,155,157,157,158,158,
+161,161,162,162,164,164,167,167,168,168,171,171,173,173,174,174,
+176,176,179,179,181,181,182,182,185,185,186,186,188,188,191,191,
+193,193,194,194,196,196,199,199,200,200,203,203,205,205,206,206,
+208,208,211,211,213,213,214,214,217,217,218,218,220,220,223,223,
+224,224,227,227,229,229,230,230,233,233,234,234,236,236,239,239,
+241,241,242,242,244,244,247,247,248,248,251,251,253,253,254,254,
+ };
diff --git a/third_party/heimdal/lib/hcrypto/des.c b/third_party/heimdal/lib/hcrypto/des.c
new file mode 100644
index 0000000..ac17418
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/des.c
@@ -0,0 +1,1186 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/**
+ * @page page_des DES - Data Encryption Standard crypto interface
+ *
+ * See the library functions here: @ref hcrypto_des
+ *
+ * DES was created by IBM, modififed by NSA and then adopted by NBS
+ * (now NIST) and published ad FIPS PUB 46 (updated by FIPS 46-1).
+ *
+ * Since the 19th May 2005 DES was withdrawn by NIST and should no
+ * longer be used. See @ref page_evp for replacement encryption
+ * algorithms and interfaces.
+ *
+ * Read more the iteresting history of DES on Wikipedia
+ * http://www.wikipedia.org/wiki/Data_Encryption_Standard .
+ *
+ * @section des_keygen DES key generation
+ *
+ * To generate a DES key safely you have to use the code-snippet
+ * below. This is because the DES_random_key() can fail with an
+ * abort() in case of and failure to start the random generator.
+ *
+ * There is a replacement function DES_new_random_key(), however that
+ * function does not exists in OpenSSL.
+ *
+ * @code
+ * DES_cblock key;
+ * do {
+ * if (RAND_rand(&key, sizeof(key)) != 1)
+ * goto failure;
+ * DES_set_odd_parity(key);
+ * } while (DES_is_weak_key(&key));
+ * @endcode
+ *
+ * @section des_impl DES implementation history
+ *
+ * There was no complete BSD licensed, fast, GPL compatible
+ * implementation of DES, so Love wrote the part that was missing,
+ * fast key schedule setup and adapted the interface to the orignal
+ * libdes.
+ *
+ * The document that got me started for real was "Efficient
+ * Implementation of the Data Encryption Standard" by Dag Arne Osvik.
+ * I never got to the PC1 transformation was working, instead I used
+ * table-lookup was used for all key schedule setup. The document was
+ * very useful since it de-mystified other implementations for me.
+ *
+ * The core DES function (SBOX + P transformation) is from Richard
+ * Outerbridge public domain DES implementation. My sanity is saved
+ * thanks to his work. Thank you Richard.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#define HC_DEPRECATED
+#include <krb5-types.h>
+#include <assert.h>
+
+#include "des.h"
+#include "ui.h"
+
+static void desx(uint32_t [2], DES_key_schedule *, int);
+static void IP(uint32_t [2]);
+static void FP(uint32_t [2]);
+
+#include "des-tables.h"
+
+#define ROTATE_LEFT28(x,one) \
+ if (one) { \
+ x = ( ((x)<<(1)) & 0xffffffe) | ((x) >> 27); \
+ } else { \
+ x = ( ((x)<<(2)) & 0xffffffc) | ((x) >> 26); \
+ }
+
+/**
+ * Set the parity of the key block, used to generate a des key from a
+ * random key. See @ref des_keygen.
+ *
+ * @param key key to fixup the parity for.
+ * @ingroup hcrypto_des
+ */
+
+void
+DES_set_odd_parity(DES_cblock *key)
+{
+ unsigned int i;
+ for (i = 0; i < DES_CBLOCK_LEN; i++)
+ (*key)[i] = odd_parity[(*key)[i]];
+}
+
+/**
+ * Check if the key have correct parity.
+ *
+ * @param key key to check the parity.
+ * @return 1 on success, 0 on failure.
+ * @ingroup hcrypto_des
+ */
+
+int HC_DEPRECATED
+DES_check_key_parity(DES_cblock *key)
+{
+ unsigned int i;
+
+ for (i = 0; i < DES_CBLOCK_LEN; i++)
+ if ((*key)[i] != odd_parity[(*key)[i]])
+ return 0;
+ return 1;
+}
+
+/*
+ *
+ */
+
+/* FIPS 74 */
+static DES_cblock weak_keys[] = {
+ {0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01}, /* weak keys */
+ {0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE},
+ {0x1F,0x1F,0x1F,0x1F,0x0E,0x0E,0x0E,0x0E},
+ {0xE0,0xE0,0xE0,0xE0,0xF1,0xF1,0xF1,0xF1},
+ {0x01,0xFE,0x01,0xFE,0x01,0xFE,0x01,0xFE}, /* semi-weak keys */
+ {0xFE,0x01,0xFE,0x01,0xFE,0x01,0xFE,0x01},
+ {0x1F,0xE0,0x1F,0xE0,0x0E,0xF1,0x0E,0xF1},
+ {0xE0,0x1F,0xE0,0x1F,0xF1,0x0E,0xF1,0x0E},
+ {0x01,0xE0,0x01,0xE0,0x01,0xF1,0x01,0xF1},
+ {0xE0,0x01,0xE0,0x01,0xF1,0x01,0xF1,0x01},
+ {0x1F,0xFE,0x1F,0xFE,0x0E,0xFE,0x0E,0xFE},
+ {0xFE,0x1F,0xFE,0x1F,0xFE,0x0E,0xFE,0x0E},
+ {0x01,0x1F,0x01,0x1F,0x01,0x0E,0x01,0x0E},
+ {0x1F,0x01,0x1F,0x01,0x0E,0x01,0x0E,0x01},
+ {0xE0,0xFE,0xE0,0xFE,0xF1,0xFE,0xF1,0xFE},
+ {0xFE,0xE0,0xFE,0xE0,0xFE,0xF1,0xFE,0xF1}
+};
+
+/**
+ * Checks if the key is any of the weaks keys that makes DES attacks
+ * trival.
+ *
+ * @param key key to check.
+ *
+ * @return 1 if the key is weak, 0 otherwise.
+ * @ingroup hcrypto_des
+ */
+
+int
+DES_is_weak_key(DES_cblock *key)
+{
+ int weak = 0;
+ int i;
+
+ for (i = 0; i < sizeof(weak_keys)/sizeof(weak_keys[0]); i++)
+ weak ^= (ct_memcmp(weak_keys[i], key, DES_CBLOCK_LEN) == 0);
+
+ return !!weak;
+}
+
+/**
+ * Setup a des key schedule from a key. Deprecated function, use
+ * DES_set_key_unchecked() or DES_set_key_checked() instead.
+ *
+ * @param key a key to initialize the key schedule with.
+ * @param ks a key schedule to initialize.
+ *
+ * @return 0 on success
+ * @ingroup hcrypto_des
+ */
+
+int HC_DEPRECATED
+DES_set_key(DES_cblock *key, DES_key_schedule *ks)
+{
+ return DES_set_key_checked(key, ks);
+}
+
+/**
+ * Setup a des key schedule from a key. The key is no longer needed
+ * after this transaction and can cleared.
+ *
+ * Does NOT check that the key is weak for or have wrong parity.
+ *
+ * @param key a key to initialize the key schedule with.
+ * @param ks a key schedule to initialize.
+ *
+ * @return 0 on success
+ * @ingroup hcrypto_des
+ */
+
+int
+DES_set_key_unchecked(DES_cblock *key, DES_key_schedule *ks)
+{
+ uint32_t t1, t2;
+ uint32_t c, d;
+ int shifts[16] = { 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 };
+ uint32_t *k = &ks->ks[0];
+ int i;
+
+ t1 = (uint32_t)((*key)[0]) << 24
+ | (uint32_t)((*key)[1]) << 16
+ | (uint32_t)((*key)[2]) << 8
+ | (*key)[3];
+ t2 = (uint32_t)((*key)[4]) << 24
+ | (uint32_t)((*key)[5]) << 16
+ | (uint32_t)((*key)[6]) << 8
+ | (*key)[7];
+
+ c = (pc1_c_3[(t1 >> (5 )) & 0x7] << 3)
+ | (pc1_c_3[(t1 >> (5 + 8 )) & 0x7] << 2)
+ | (pc1_c_3[(t1 >> (5 + 8 + 8 )) & 0x7] << 1)
+ | (pc1_c_3[(t1 >> (5 + 8 + 8 + 8)) & 0x7] << 0)
+ | (pc1_c_4[(t2 >> (4 )) & 0xf] << 3)
+ | (pc1_c_4[(t2 >> (4 + 8 )) & 0xf] << 2)
+ | (pc1_c_4[(t2 >> (4 + 8 + 8 )) & 0xf] << 1)
+ | (pc1_c_4[(t2 >> (4 + 8 + 8 + 8)) & 0xf] << 0);
+
+
+ d = (pc1_d_3[(t2 >> (1 )) & 0x7] << 3)
+ | (pc1_d_3[(t2 >> (1 + 8 )) & 0x7] << 2)
+ | (pc1_d_3[(t2 >> (1 + 8 + 8 )) & 0x7] << 1)
+ | (pc1_d_3[(t2 >> (1 + 8 + 8 + 8)) & 0x7] << 0)
+ | (pc1_d_4[(t1 >> (1 )) & 0xf] << 3)
+ | (pc1_d_4[(t1 >> (1 + 8 )) & 0xf] << 2)
+ | (pc1_d_4[(t1 >> (1 + 8 + 8 )) & 0xf] << 1)
+ | (pc1_d_4[(t1 >> (1 + 8 + 8 + 8)) & 0xf] << 0);
+
+ for (i = 0; i < 16; i++) {
+ uint32_t kc, kd;
+
+ ROTATE_LEFT28(c, shifts[i]);
+ ROTATE_LEFT28(d, shifts[i]);
+
+ kc = pc2_c_1[(c >> 22) & 0x3f] |
+ pc2_c_2[((c >> 16) & 0x30) | ((c >> 15) & 0xf)] |
+ pc2_c_3[((c >> 9 ) & 0x3c) | ((c >> 8 ) & 0x3)] |
+ pc2_c_4[((c >> 2 ) & 0x20) | ((c >> 1) & 0x18) | (c & 0x7)];
+ kd = pc2_d_1[(d >> 22) & 0x3f] |
+ pc2_d_2[((d >> 15) & 0x30) | ((d >> 14) & 0xf)] |
+ pc2_d_3[ (d >> 7 ) & 0x3f] |
+ pc2_d_4[((d >> 1 ) & 0x3c) | ((d ) & 0x3)];
+
+ /* Change to byte order used by the S boxes */
+ *k = (kc & 0x00fc0000L) << 6;
+ *k |= (kc & 0x00000fc0L) << 10;
+ *k |= (kd & 0x00fc0000L) >> 10;
+ *k++ |= (kd & 0x00000fc0L) >> 6;
+ *k = (kc & 0x0003f000L) << 12;
+ *k |= (kc & 0x0000003fL) << 16;
+ *k |= (kd & 0x0003f000L) >> 4;
+ *k++ |= (kd & 0x0000003fL);
+ }
+
+ return 0;
+}
+
+/**
+ * Just like DES_set_key_unchecked() except checking that the key is
+ * not weak for or have correct parity.
+ *
+ * @param key a key to initialize the key schedule with.
+ * @param ks a key schedule to initialize.
+ *
+ * @return 0 on success, -1 on invalid parity, -2 on weak key.
+ * @ingroup hcrypto_des
+ */
+
+int
+DES_set_key_checked(DES_cblock *key, DES_key_schedule *ks)
+{
+ if (!DES_check_key_parity(key)) {
+ memset(ks, 0, sizeof(*ks));
+ return -1;
+ }
+ if (DES_is_weak_key(key)) {
+ memset(ks, 0, sizeof(*ks));
+ return -2;
+ }
+ return DES_set_key_unchecked(key, ks);
+}
+
+/**
+ * Compatibility function for eay libdes, works just like
+ * DES_set_key_checked().
+ *
+ * @param key a key to initialize the key schedule with.
+ * @param ks a key schedule to initialize.
+ *
+ * @return 0 on success, -1 on invalid parity, -2 on weak key.
+ * @ingroup hcrypto_des
+ */
+
+int
+DES_key_sched(DES_cblock *key, DES_key_schedule *ks)
+{
+ return DES_set_key_checked(key, ks);
+}
+
+/*
+ *
+ */
+
+static void
+load(const unsigned char *b, uint32_t v[2])
+{
+ v[0] = (uint32_t)(b[0]) << 24;
+ v[0] |= (uint32_t)(b[1]) << 16;
+ v[0] |= (uint32_t)(b[2]) << 8;
+ v[0] |= b[3];
+ v[1] = (uint32_t)(b[4]) << 24;
+ v[1] |= (uint32_t)(b[5]) << 16;
+ v[1] |= (uint32_t)(b[6]) << 8;
+ v[1] |= b[7];
+}
+
+static void
+store(const uint32_t v[2], unsigned char *b)
+{
+ b[0] = (v[0] >> 24) & 0xff;
+ b[1] = (v[0] >> 16) & 0xff;
+ b[2] = (v[0] >> 8) & 0xff;
+ b[3] = (v[0] >> 0) & 0xff;
+ b[4] = (v[1] >> 24) & 0xff;
+ b[5] = (v[1] >> 16) & 0xff;
+ b[6] = (v[1] >> 8) & 0xff;
+ b[7] = (v[1] >> 0) & 0xff;
+}
+
+/**
+ * Encrypt/decrypt a block using DES. Also called ECB mode
+ *
+ * @param u data to encrypt
+ * @param ks key schedule to use
+ * @param encp if non zero, encrypt. if zero, decrypt.
+ *
+ * @ingroup hcrypto_des
+ */
+
+void
+DES_encrypt(uint32_t u[2], DES_key_schedule *ks, int encp)
+{
+ IP(u);
+ desx(u, ks, encp);
+ FP(u);
+}
+
+/**
+ * Encrypt/decrypt a block using DES.
+ *
+ * @param input data to encrypt
+ * @param output data to encrypt
+ * @param ks key schedule to use
+ * @param encp if non zero, encrypt. if zero, decrypt.
+ *
+ * @ingroup hcrypto_des
+ */
+
+void
+DES_ecb_encrypt(DES_cblock *input, DES_cblock *output,
+ DES_key_schedule *ks, int encp)
+{
+ uint32_t u[2];
+ load(*input, u);
+ DES_encrypt(u, ks, encp);
+ store(u, *output);
+}
+
+/**
+ * Encrypt/decrypt a block using DES in Chain Block Cipher mode (cbc).
+ *
+ * The IV must always be diffrent for diffrent input data blocks.
+ *
+ * @param in data to encrypt
+ * @param out data to encrypt
+ * @param length length of data
+ * @param ks key schedule to use
+ * @param iv initial vector to use
+ * @param encp if non zero, encrypt. if zero, decrypt.
+ *
+ * @ingroup hcrypto_des
+ */
+
+void
+DES_cbc_encrypt(const void *in, void *out, long length,
+ DES_key_schedule *ks, DES_cblock *iv, int encp)
+{
+ const unsigned char *input = in;
+ unsigned char *output = out;
+ uint32_t u[2];
+ uint32_t uiv[2];
+
+ load(*iv, uiv);
+
+ if (encp) {
+ while (length >= DES_CBLOCK_LEN) {
+ load(input, u);
+ u[0] ^= uiv[0]; u[1] ^= uiv[1];
+ DES_encrypt(u, ks, 1);
+ uiv[0] = u[0]; uiv[1] = u[1];
+ store(u, output);
+
+ length -= DES_CBLOCK_LEN;
+ input += DES_CBLOCK_LEN;
+ output += DES_CBLOCK_LEN;
+ }
+ if (length) {
+ unsigned char tmp[DES_CBLOCK_LEN];
+ memcpy(tmp, input, length);
+ memset(tmp + length, 0, DES_CBLOCK_LEN - length);
+ load(tmp, u);
+ u[0] ^= uiv[0]; u[1] ^= uiv[1];
+ DES_encrypt(u, ks, 1);
+ store(u, output);
+ }
+ } else {
+ uint32_t t[2];
+ while (length >= DES_CBLOCK_LEN) {
+ load(input, u);
+ t[0] = u[0]; t[1] = u[1];
+ DES_encrypt(u, ks, 0);
+ u[0] ^= uiv[0]; u[1] ^= uiv[1];
+ store(u, output);
+ uiv[0] = t[0]; uiv[1] = t[1];
+
+ length -= DES_CBLOCK_LEN;
+ input += DES_CBLOCK_LEN;
+ output += DES_CBLOCK_LEN;
+ }
+ if (length) {
+ unsigned char tmp[DES_CBLOCK_LEN];
+ memcpy(tmp, input, length);
+ memset(tmp + length, 0, DES_CBLOCK_LEN - length);
+ load(tmp, u);
+ DES_encrypt(u, ks, 0);
+ u[0] ^= uiv[0]; u[1] ^= uiv[1];
+ store(u, output);
+ }
+ }
+ uiv[0] = 0; u[0] = 0; uiv[1] = 0; u[1] = 0;
+}
+
+/**
+ * Encrypt/decrypt a block using DES in Propagating Cipher Block
+ * Chaining mode. This mode is only used for Kerberos 4, and it should
+ * stay that way.
+ *
+ * The IV must always be diffrent for diffrent input data blocks.
+ *
+ * @param in data to encrypt
+ * @param out data to encrypt
+ * @param length length of data
+ * @param ks key schedule to use
+ * @param iv initial vector to use
+ * @param encp if non zero, encrypt. if zero, decrypt.
+ *
+ * @ingroup hcrypto_des
+ */
+
+void
+DES_pcbc_encrypt(const void *in, void *out, long length,
+ DES_key_schedule *ks, DES_cblock *iv, int encp)
+{
+ const unsigned char *input = in;
+ unsigned char *output = out;
+ uint32_t u[2];
+ uint32_t uiv[2];
+
+ load(*iv, uiv);
+
+ if (encp) {
+ uint32_t t[2];
+ while (length >= DES_CBLOCK_LEN) {
+ load(input, u);
+ t[0] = u[0]; t[1] = u[1];
+ u[0] ^= uiv[0]; u[1] ^= uiv[1];
+ DES_encrypt(u, ks, 1);
+ uiv[0] = u[0] ^ t[0]; uiv[1] = u[1] ^ t[1];
+ store(u, output);
+
+ length -= DES_CBLOCK_LEN;
+ input += DES_CBLOCK_LEN;
+ output += DES_CBLOCK_LEN;
+ }
+ if (length) {
+ unsigned char tmp[DES_CBLOCK_LEN];
+ memcpy(tmp, input, length);
+ memset(tmp + length, 0, DES_CBLOCK_LEN - length);
+ load(tmp, u);
+ u[0] ^= uiv[0]; u[1] ^= uiv[1];
+ DES_encrypt(u, ks, 1);
+ store(u, output);
+ }
+ } else {
+ uint32_t t[2];
+ while (length >= DES_CBLOCK_LEN) {
+ load(input, u);
+ t[0] = u[0]; t[1] = u[1];
+ DES_encrypt(u, ks, 0);
+ u[0] ^= uiv[0]; u[1] ^= uiv[1];
+ store(u, output);
+ uiv[0] = t[0] ^ u[0]; uiv[1] = t[1] ^ u[1];
+
+ length -= DES_CBLOCK_LEN;
+ input += DES_CBLOCK_LEN;
+ output += DES_CBLOCK_LEN;
+ }
+ if (length) {
+ unsigned char tmp[DES_CBLOCK_LEN];
+ memcpy(tmp, input, length);
+ memset(tmp + length, 0, DES_CBLOCK_LEN - length);
+ load(tmp, u);
+ DES_encrypt(u, ks, 0);
+ u[0] ^= uiv[0]; u[1] ^= uiv[1];
+ }
+ }
+ uiv[0] = 0; u[0] = 0; uiv[1] = 0; u[1] = 0;
+}
+
+/*
+ *
+ */
+
+static void
+_des3_encrypt(uint32_t u[2], DES_key_schedule *ks1, DES_key_schedule *ks2,
+ DES_key_schedule *ks3, int encp)
+{
+ IP(u);
+ if (encp) {
+ desx(u, ks1, 1); /* IP + FP cancel out each other */
+ desx(u, ks2, 0);
+ desx(u, ks3, 1);
+ } else {
+ desx(u, ks3, 0);
+ desx(u, ks2, 1);
+ desx(u, ks1, 0);
+ }
+ FP(u);
+}
+
+/**
+ * Encrypt/decrypt a block using triple DES using EDE mode,
+ * encrypt/decrypt/encrypt.
+ *
+ * @param input data to encrypt
+ * @param output data to encrypt
+ * @param ks1 key schedule to use
+ * @param ks2 key schedule to use
+ * @param ks3 key schedule to use
+ * @param encp if non zero, encrypt. if zero, decrypt.
+ *
+ * @ingroup hcrypto_des
+ */
+
+void
+DES_ecb3_encrypt(DES_cblock *input,
+ DES_cblock *output,
+ DES_key_schedule *ks1,
+ DES_key_schedule *ks2,
+ DES_key_schedule *ks3,
+ int encp)
+{
+ uint32_t u[2];
+ load(*input, u);
+ _des3_encrypt(u, ks1, ks2, ks3, encp);
+ store(u, *output);
+ return;
+}
+
+/**
+ * Encrypt/decrypt using Triple DES in Chain Block Cipher mode (cbc).
+ *
+ * The IV must always be diffrent for diffrent input data blocks.
+ *
+ * @param in data to encrypt
+ * @param out data to encrypt
+ * @param length length of data
+ * @param ks1 key schedule to use
+ * @param ks2 key schedule to use
+ * @param ks3 key schedule to use
+ * @param iv initial vector to use
+ * @param encp if non zero, encrypt. if zero, decrypt.
+ *
+ * @ingroup hcrypto_des
+ */
+
+void
+DES_ede3_cbc_encrypt(const void *in, void *out,
+ long length, DES_key_schedule *ks1,
+ DES_key_schedule *ks2, DES_key_schedule *ks3,
+ DES_cblock *iv, int encp)
+{
+ const unsigned char *input = in;
+ unsigned char *output = out;
+ uint32_t u[2];
+ uint32_t uiv[2];
+
+ load(*iv, uiv);
+
+ if (encp) {
+ while (length >= DES_CBLOCK_LEN) {
+ load(input, u);
+ u[0] ^= uiv[0]; u[1] ^= uiv[1];
+ _des3_encrypt(u, ks1, ks2, ks3, 1);
+ uiv[0] = u[0]; uiv[1] = u[1];
+ store(u, output);
+
+ length -= DES_CBLOCK_LEN;
+ input += DES_CBLOCK_LEN;
+ output += DES_CBLOCK_LEN;
+ }
+ if (length) {
+ unsigned char tmp[DES_CBLOCK_LEN];
+ memcpy(tmp, input, length);
+ memset(tmp + length, 0, DES_CBLOCK_LEN - length);
+ load(tmp, u);
+ u[0] ^= uiv[0]; u[1] ^= uiv[1];
+ _des3_encrypt(u, ks1, ks2, ks3, 1);
+ store(u, output);
+ }
+ } else {
+ uint32_t t[2];
+ while (length >= DES_CBLOCK_LEN) {
+ load(input, u);
+ t[0] = u[0]; t[1] = u[1];
+ _des3_encrypt(u, ks1, ks2, ks3, 0);
+ u[0] ^= uiv[0]; u[1] ^= uiv[1];
+ store(u, output);
+ uiv[0] = t[0]; uiv[1] = t[1];
+
+ length -= DES_CBLOCK_LEN;
+ input += DES_CBLOCK_LEN;
+ output += DES_CBLOCK_LEN;
+ }
+ if (length) {
+ unsigned char tmp[DES_CBLOCK_LEN];
+ memcpy(tmp, input, length);
+ memset(tmp + length, 0, DES_CBLOCK_LEN - length);
+ load(tmp, u);
+ _des3_encrypt(u, ks1, ks2, ks3, 0);
+ u[0] ^= uiv[0]; u[1] ^= uiv[1];
+ store(u, output);
+ }
+ }
+ store(uiv, *iv);
+ uiv[0] = 0; u[0] = 0; uiv[1] = 0; u[1] = 0;
+}
+
+/**
+ * Encrypt/decrypt using DES in cipher feedback mode with 64 bit
+ * feedback.
+ *
+ * The IV must always be diffrent for diffrent input data blocks.
+ *
+ * @param in data to encrypt
+ * @param out data to encrypt
+ * @param length length of data
+ * @param ks key schedule to use
+ * @param iv initial vector to use
+ * @param num offset into in cipher block encryption/decryption stop last time.
+ * @param encp if non zero, encrypt. if zero, decrypt.
+ *
+ * @ingroup hcrypto_des
+ */
+
+void
+DES_cfb64_encrypt(const void *in, void *out,
+ long length, DES_key_schedule *ks, DES_cblock *iv,
+ int *num, int encp)
+{
+ const unsigned char *input = in;
+ unsigned char *output = out;
+ unsigned char tmp[DES_CBLOCK_LEN];
+ uint32_t uiv[2];
+
+ load(*iv, uiv);
+
+ assert(*num >= 0 && *num < DES_CBLOCK_LEN);
+
+ if (encp) {
+ int i = *num;
+
+ while (length > 0) {
+ if (i == 0)
+ DES_encrypt(uiv, ks, 1);
+ store(uiv, tmp);
+ for (; i < DES_CBLOCK_LEN && i < length; i++) {
+ output[i] = tmp[i] ^ input[i];
+ }
+ if (i == DES_CBLOCK_LEN)
+ load(output, uiv);
+ output += i;
+ input += i;
+ length -= i;
+ if (i == DES_CBLOCK_LEN)
+ i = 0;
+ }
+ store(uiv, *iv);
+ *num = i;
+ } else {
+ int i = *num;
+ unsigned char c;
+
+ memset(tmp, 0, DES_CBLOCK_LEN);
+ while (length > 0) {
+ if (i == 0) {
+ DES_encrypt(uiv, ks, 1);
+ store(uiv, tmp);
+ }
+ for (; i < DES_CBLOCK_LEN && i < length; i++) {
+ c = input[i];
+ output[i] = tmp[i] ^ input[i];
+ (*iv)[i] = c;
+ }
+ output += i;
+ input += i;
+ length -= i;
+ if (i == DES_CBLOCK_LEN) {
+ i = 0;
+ load(*iv, uiv);
+ }
+ }
+ store(uiv, *iv);
+ *num = i;
+ }
+}
+
+/**
+ * Crete a checksum using DES in CBC encryption mode. This mode is
+ * only used for Kerberos 4, and it should stay that way.
+ *
+ * The IV must always be diffrent for diffrent input data blocks.
+ *
+ * @param in data to checksum
+ * @param output the checksum
+ * @param length length of data
+ * @param ks key schedule to use
+ * @param iv initial vector to use
+ *
+ * @ingroup hcrypto_des
+ */
+
+uint32_t
+DES_cbc_cksum(const void *in, DES_cblock *output,
+ long length, DES_key_schedule *ks, DES_cblock *iv)
+{
+ const unsigned char *input = in;
+ uint32_t uiv[2];
+ uint32_t u[2] = { 0, 0 };
+
+ load(*iv, uiv);
+
+ while (length >= DES_CBLOCK_LEN) {
+ load(input, u);
+ u[0] ^= uiv[0]; u[1] ^= uiv[1];
+ DES_encrypt(u, ks, 1);
+ uiv[0] = u[0]; uiv[1] = u[1];
+
+ length -= DES_CBLOCK_LEN;
+ input += DES_CBLOCK_LEN;
+ }
+ if (length) {
+ unsigned char tmp[DES_CBLOCK_LEN];
+ memcpy(tmp, input, length);
+ memset(tmp + length, 0, DES_CBLOCK_LEN - length);
+ load(tmp, u);
+ u[0] ^= uiv[0]; u[1] ^= uiv[1];
+ DES_encrypt(u, ks, 1);
+ }
+ if (output)
+ store(u, *output);
+
+ uiv[0] = 0; u[0] = 0; uiv[1] = 0;
+ return u[1];
+}
+
+/*
+ *
+ */
+
+static unsigned char
+bitswap8(unsigned char b)
+{
+ unsigned char r = 0;
+ int i;
+ for (i = 0; i < 8; i++) {
+ r = r << 1 | (b & 1);
+ b = b >> 1;
+ }
+ return r;
+}
+
+/**
+ * Convert a string to a DES key. Use something like
+ * PKCS5_PBKDF2_HMAC_SHA1() to create key from passwords.
+ *
+ * @param str The string to convert to a key
+ * @param key the resulting key
+ *
+ * @ingroup hcrypto_des
+ */
+
+void
+DES_string_to_key(const char *str, DES_cblock *key)
+{
+ const unsigned char *s;
+ unsigned char *k;
+ DES_key_schedule ks;
+ size_t i, len;
+
+ memset(key, 0, sizeof(*key));
+ k = *key;
+ s = (const unsigned char *)str;
+
+ len = strlen(str);
+ for (i = 0; i < len; i++) {
+ if ((i % 16) < 8)
+ k[i % 8] ^= s[i] << 1;
+ else
+ k[7 - (i % 8)] ^= bitswap8(s[i]);
+ }
+ DES_set_odd_parity(key);
+ if (DES_is_weak_key(key))
+ k[7] ^= 0xF0;
+ DES_set_key(key, &ks);
+ DES_cbc_cksum(s, key, len, &ks, key);
+ memset(&ks, 0, sizeof(ks));
+ DES_set_odd_parity(key);
+ if (DES_is_weak_key(key))
+ k[7] ^= 0xF0;
+}
+
+/**
+ * Read password from prompt and create a DES key. Internal uses
+ * DES_string_to_key(). Really, go use a really string2key function
+ * like PKCS5_PBKDF2_HMAC_SHA1().
+ *
+ * @param key key to convert to
+ * @param prompt prompt to display user
+ * @param verify prompt twice.
+ *
+ * @return 1 on success, non 1 on failure.
+ */
+
+int
+DES_read_password(DES_cblock *key, char *prompt, int verify)
+{
+ char buf[512];
+ int ret;
+
+ ret = UI_UTIL_read_pw_string(buf, sizeof(buf) - 1, prompt, verify);
+ if (ret == 1)
+ DES_string_to_key(buf, key);
+ return ret;
+}
+
+/*
+ *
+ */
+
+
+void
+_DES_ipfp_test(void)
+{
+ DES_cblock k = "\x01\x02\x04\x08\x10\x20\x40\x80", k2;
+ uint32_t u[2] = { 1, 0 };
+ IP(u);
+ FP(u);
+ IP(u);
+ FP(u);
+ if (u[0] != 1 || u[1] != 0)
+ abort();
+
+ load(k, u);
+ store(u, k2);
+ if (memcmp(k, k2, 8) != 0)
+ abort();
+}
+
+/* D3DES (V5.09) -
+ *
+ * A portable, public domain, version of the Data Encryption Standard.
+ *
+ * Written with Symantec's THINK (Lightspeed) C by Richard Outerbridge.
+ * Thanks to: Dan Hoey for his excellent Initial and Inverse permutation
+ * code; Jim Gillogly & Phil Karn for the DES key schedule code; Dennis
+ * Ferguson, Eric Young and Dana How for comparing notes; and Ray Lau,
+ * for humouring me on.
+ *
+ * Copyright (c) 1988,1989,1990,1991,1992 by Richard Outerbridge.
+ * (GEnie : OUTER; CIS : [71755,204]) Graven Imagery, 1992.
+ */
+
+static uint32_t SP1[64] = {
+ 0x01010400L, 0x00000000L, 0x00010000L, 0x01010404L,
+ 0x01010004L, 0x00010404L, 0x00000004L, 0x00010000L,
+ 0x00000400L, 0x01010400L, 0x01010404L, 0x00000400L,
+ 0x01000404L, 0x01010004L, 0x01000000L, 0x00000004L,
+ 0x00000404L, 0x01000400L, 0x01000400L, 0x00010400L,
+ 0x00010400L, 0x01010000L, 0x01010000L, 0x01000404L,
+ 0x00010004L, 0x01000004L, 0x01000004L, 0x00010004L,
+ 0x00000000L, 0x00000404L, 0x00010404L, 0x01000000L,
+ 0x00010000L, 0x01010404L, 0x00000004L, 0x01010000L,
+ 0x01010400L, 0x01000000L, 0x01000000L, 0x00000400L,
+ 0x01010004L, 0x00010000L, 0x00010400L, 0x01000004L,
+ 0x00000400L, 0x00000004L, 0x01000404L, 0x00010404L,
+ 0x01010404L, 0x00010004L, 0x01010000L, 0x01000404L,
+ 0x01000004L, 0x00000404L, 0x00010404L, 0x01010400L,
+ 0x00000404L, 0x01000400L, 0x01000400L, 0x00000000L,
+ 0x00010004L, 0x00010400L, 0x00000000L, 0x01010004L };
+
+static uint32_t SP2[64] = {
+ 0x80108020L, 0x80008000L, 0x00008000L, 0x00108020L,
+ 0x00100000L, 0x00000020L, 0x80100020L, 0x80008020L,
+ 0x80000020L, 0x80108020L, 0x80108000L, 0x80000000L,
+ 0x80008000L, 0x00100000L, 0x00000020L, 0x80100020L,
+ 0x00108000L, 0x00100020L, 0x80008020L, 0x00000000L,
+ 0x80000000L, 0x00008000L, 0x00108020L, 0x80100000L,
+ 0x00100020L, 0x80000020L, 0x00000000L, 0x00108000L,
+ 0x00008020L, 0x80108000L, 0x80100000L, 0x00008020L,
+ 0x00000000L, 0x00108020L, 0x80100020L, 0x00100000L,
+ 0x80008020L, 0x80100000L, 0x80108000L, 0x00008000L,
+ 0x80100000L, 0x80008000L, 0x00000020L, 0x80108020L,
+ 0x00108020L, 0x00000020L, 0x00008000L, 0x80000000L,
+ 0x00008020L, 0x80108000L, 0x00100000L, 0x80000020L,
+ 0x00100020L, 0x80008020L, 0x80000020L, 0x00100020L,
+ 0x00108000L, 0x00000000L, 0x80008000L, 0x00008020L,
+ 0x80000000L, 0x80100020L, 0x80108020L, 0x00108000L };
+
+static uint32_t SP3[64] = {
+ 0x00000208L, 0x08020200L, 0x00000000L, 0x08020008L,
+ 0x08000200L, 0x00000000L, 0x00020208L, 0x08000200L,
+ 0x00020008L, 0x08000008L, 0x08000008L, 0x00020000L,
+ 0x08020208L, 0x00020008L, 0x08020000L, 0x00000208L,
+ 0x08000000L, 0x00000008L, 0x08020200L, 0x00000200L,
+ 0x00020200L, 0x08020000L, 0x08020008L, 0x00020208L,
+ 0x08000208L, 0x00020200L, 0x00020000L, 0x08000208L,
+ 0x00000008L, 0x08020208L, 0x00000200L, 0x08000000L,
+ 0x08020200L, 0x08000000L, 0x00020008L, 0x00000208L,
+ 0x00020000L, 0x08020200L, 0x08000200L, 0x00000000L,
+ 0x00000200L, 0x00020008L, 0x08020208L, 0x08000200L,
+ 0x08000008L, 0x00000200L, 0x00000000L, 0x08020008L,
+ 0x08000208L, 0x00020000L, 0x08000000L, 0x08020208L,
+ 0x00000008L, 0x00020208L, 0x00020200L, 0x08000008L,
+ 0x08020000L, 0x08000208L, 0x00000208L, 0x08020000L,
+ 0x00020208L, 0x00000008L, 0x08020008L, 0x00020200L };
+
+static uint32_t SP4[64] = {
+ 0x00802001L, 0x00002081L, 0x00002081L, 0x00000080L,
+ 0x00802080L, 0x00800081L, 0x00800001L, 0x00002001L,
+ 0x00000000L, 0x00802000L, 0x00802000L, 0x00802081L,
+ 0x00000081L, 0x00000000L, 0x00800080L, 0x00800001L,
+ 0x00000001L, 0x00002000L, 0x00800000L, 0x00802001L,
+ 0x00000080L, 0x00800000L, 0x00002001L, 0x00002080L,
+ 0x00800081L, 0x00000001L, 0x00002080L, 0x00800080L,
+ 0x00002000L, 0x00802080L, 0x00802081L, 0x00000081L,
+ 0x00800080L, 0x00800001L, 0x00802000L, 0x00802081L,
+ 0x00000081L, 0x00000000L, 0x00000000L, 0x00802000L,
+ 0x00002080L, 0x00800080L, 0x00800081L, 0x00000001L,
+ 0x00802001L, 0x00002081L, 0x00002081L, 0x00000080L,
+ 0x00802081L, 0x00000081L, 0x00000001L, 0x00002000L,
+ 0x00800001L, 0x00002001L, 0x00802080L, 0x00800081L,
+ 0x00002001L, 0x00002080L, 0x00800000L, 0x00802001L,
+ 0x00000080L, 0x00800000L, 0x00002000L, 0x00802080L };
+
+static uint32_t SP5[64] = {
+ 0x00000100L, 0x02080100L, 0x02080000L, 0x42000100L,
+ 0x00080000L, 0x00000100L, 0x40000000L, 0x02080000L,
+ 0x40080100L, 0x00080000L, 0x02000100L, 0x40080100L,
+ 0x42000100L, 0x42080000L, 0x00080100L, 0x40000000L,
+ 0x02000000L, 0x40080000L, 0x40080000L, 0x00000000L,
+ 0x40000100L, 0x42080100L, 0x42080100L, 0x02000100L,
+ 0x42080000L, 0x40000100L, 0x00000000L, 0x42000000L,
+ 0x02080100L, 0x02000000L, 0x42000000L, 0x00080100L,
+ 0x00080000L, 0x42000100L, 0x00000100L, 0x02000000L,
+ 0x40000000L, 0x02080000L, 0x42000100L, 0x40080100L,
+ 0x02000100L, 0x40000000L, 0x42080000L, 0x02080100L,
+ 0x40080100L, 0x00000100L, 0x02000000L, 0x42080000L,
+ 0x42080100L, 0x00080100L, 0x42000000L, 0x42080100L,
+ 0x02080000L, 0x00000000L, 0x40080000L, 0x42000000L,
+ 0x00080100L, 0x02000100L, 0x40000100L, 0x00080000L,
+ 0x00000000L, 0x40080000L, 0x02080100L, 0x40000100L };
+
+static uint32_t SP6[64] = {
+ 0x20000010L, 0x20400000L, 0x00004000L, 0x20404010L,
+ 0x20400000L, 0x00000010L, 0x20404010L, 0x00400000L,
+ 0x20004000L, 0x00404010L, 0x00400000L, 0x20000010L,
+ 0x00400010L, 0x20004000L, 0x20000000L, 0x00004010L,
+ 0x00000000L, 0x00400010L, 0x20004010L, 0x00004000L,
+ 0x00404000L, 0x20004010L, 0x00000010L, 0x20400010L,
+ 0x20400010L, 0x00000000L, 0x00404010L, 0x20404000L,
+ 0x00004010L, 0x00404000L, 0x20404000L, 0x20000000L,
+ 0x20004000L, 0x00000010L, 0x20400010L, 0x00404000L,
+ 0x20404010L, 0x00400000L, 0x00004010L, 0x20000010L,
+ 0x00400000L, 0x20004000L, 0x20000000L, 0x00004010L,
+ 0x20000010L, 0x20404010L, 0x00404000L, 0x20400000L,
+ 0x00404010L, 0x20404000L, 0x00000000L, 0x20400010L,
+ 0x00000010L, 0x00004000L, 0x20400000L, 0x00404010L,
+ 0x00004000L, 0x00400010L, 0x20004010L, 0x00000000L,
+ 0x20404000L, 0x20000000L, 0x00400010L, 0x20004010L };
+
+static uint32_t SP7[64] = {
+ 0x00200000L, 0x04200002L, 0x04000802L, 0x00000000L,
+ 0x00000800L, 0x04000802L, 0x00200802L, 0x04200800L,
+ 0x04200802L, 0x00200000L, 0x00000000L, 0x04000002L,
+ 0x00000002L, 0x04000000L, 0x04200002L, 0x00000802L,
+ 0x04000800L, 0x00200802L, 0x00200002L, 0x04000800L,
+ 0x04000002L, 0x04200000L, 0x04200800L, 0x00200002L,
+ 0x04200000L, 0x00000800L, 0x00000802L, 0x04200802L,
+ 0x00200800L, 0x00000002L, 0x04000000L, 0x00200800L,
+ 0x04000000L, 0x00200800L, 0x00200000L, 0x04000802L,
+ 0x04000802L, 0x04200002L, 0x04200002L, 0x00000002L,
+ 0x00200002L, 0x04000000L, 0x04000800L, 0x00200000L,
+ 0x04200800L, 0x00000802L, 0x00200802L, 0x04200800L,
+ 0x00000802L, 0x04000002L, 0x04200802L, 0x04200000L,
+ 0x00200800L, 0x00000000L, 0x00000002L, 0x04200802L,
+ 0x00000000L, 0x00200802L, 0x04200000L, 0x00000800L,
+ 0x04000002L, 0x04000800L, 0x00000800L, 0x00200002L };
+
+static uint32_t SP8[64] = {
+ 0x10001040L, 0x00001000L, 0x00040000L, 0x10041040L,
+ 0x10000000L, 0x10001040L, 0x00000040L, 0x10000000L,
+ 0x00040040L, 0x10040000L, 0x10041040L, 0x00041000L,
+ 0x10041000L, 0x00041040L, 0x00001000L, 0x00000040L,
+ 0x10040000L, 0x10000040L, 0x10001000L, 0x00001040L,
+ 0x00041000L, 0x00040040L, 0x10040040L, 0x10041000L,
+ 0x00001040L, 0x00000000L, 0x00000000L, 0x10040040L,
+ 0x10000040L, 0x10001000L, 0x00041040L, 0x00040000L,
+ 0x00041040L, 0x00040000L, 0x10041000L, 0x00001000L,
+ 0x00000040L, 0x10040040L, 0x00001000L, 0x00041040L,
+ 0x10001000L, 0x00000040L, 0x10000040L, 0x10040000L,
+ 0x10040040L, 0x10000000L, 0x00040000L, 0x10001040L,
+ 0x00000000L, 0x10041040L, 0x00040040L, 0x10000040L,
+ 0x10040000L, 0x10001000L, 0x10001040L, 0x00000000L,
+ 0x10041040L, 0x00041000L, 0x00041000L, 0x00001040L,
+ 0x00001040L, 0x00040040L, 0x10000000L, 0x10041000L };
+
+static void
+IP(uint32_t v[2])
+{
+ uint32_t work;
+
+ work = ((v[0] >> 4) ^ v[1]) & 0x0f0f0f0fL;
+ v[1] ^= work;
+ v[0] ^= (work << 4);
+ work = ((v[0] >> 16) ^ v[1]) & 0x0000ffffL;
+ v[1] ^= work;
+ v[0] ^= (work << 16);
+ work = ((v[1] >> 2) ^ v[0]) & 0x33333333L;
+ v[0] ^= work;
+ v[1] ^= (work << 2);
+ work = ((v[1] >> 8) ^ v[0]) & 0x00ff00ffL;
+ v[0] ^= work;
+ v[1] ^= (work << 8);
+ v[1] = ((v[1] << 1) | ((v[1] >> 31) & 1L)) & 0xffffffffL;
+ work = (v[0] ^ v[1]) & 0xaaaaaaaaL;
+ v[0] ^= work;
+ v[1] ^= work;
+ v[0] = ((v[0] << 1) | ((v[0] >> 31) & 1L)) & 0xffffffffL;
+}
+
+static void
+FP(uint32_t v[2])
+{
+ uint32_t work;
+
+ v[0] = (v[0] << 31) | (v[0] >> 1);
+ work = (v[1] ^ v[0]) & 0xaaaaaaaaL;
+ v[1] ^= work;
+ v[0] ^= work;
+ v[1] = (v[1] << 31) | (v[1] >> 1);
+ work = ((v[1] >> 8) ^ v[0]) & 0x00ff00ffL;
+ v[0] ^= work;
+ v[1] ^= (work << 8);
+ work = ((v[1] >> 2) ^ v[0]) & 0x33333333L;
+ v[0] ^= work;
+ v[1] ^= (work << 2);
+ work = ((v[0] >> 16) ^ v[1]) & 0x0000ffffL;
+ v[1] ^= work;
+ v[0] ^= (work << 16);
+ work = ((v[0] >> 4) ^ v[1]) & 0x0f0f0f0fL;
+ v[1] ^= work;
+ v[0] ^= (work << 4);
+}
+
+static void
+desx(uint32_t block[2], DES_key_schedule *ks, int encp)
+{
+ uint32_t *keys;
+ uint32_t fval, work, right, left;
+ int round;
+
+ left = block[0];
+ right = block[1];
+
+ if (encp) {
+ keys = &ks->ks[0];
+
+ for( round = 0; round < 8; round++ ) {
+ work = (right << 28) | (right >> 4);
+ work ^= *keys++;
+ fval = SP7[ work & 0x3fL];
+ fval |= SP5[(work >> 8) & 0x3fL];
+ fval |= SP3[(work >> 16) & 0x3fL];
+ fval |= SP1[(work >> 24) & 0x3fL];
+ work = right ^ *keys++;
+ fval |= SP8[ work & 0x3fL];
+ fval |= SP6[(work >> 8) & 0x3fL];
+ fval |= SP4[(work >> 16) & 0x3fL];
+ fval |= SP2[(work >> 24) & 0x3fL];
+ left ^= fval;
+ work = (left << 28) | (left >> 4);
+ work ^= *keys++;
+ fval = SP7[ work & 0x3fL];
+ fval |= SP5[(work >> 8) & 0x3fL];
+ fval |= SP3[(work >> 16) & 0x3fL];
+ fval |= SP1[(work >> 24) & 0x3fL];
+ work = left ^ *keys++;
+ fval |= SP8[ work & 0x3fL];
+ fval |= SP6[(work >> 8) & 0x3fL];
+ fval |= SP4[(work >> 16) & 0x3fL];
+ fval |= SP2[(work >> 24) & 0x3fL];
+ right ^= fval;
+ }
+ } else {
+ keys = &ks->ks[30];
+
+ for( round = 0; round < 8; round++ ) {
+ work = (right << 28) | (right >> 4);
+ work ^= *keys++;
+ fval = SP7[ work & 0x3fL];
+ fval |= SP5[(work >> 8) & 0x3fL];
+ fval |= SP3[(work >> 16) & 0x3fL];
+ fval |= SP1[(work >> 24) & 0x3fL];
+ work = right ^ *keys++;
+ fval |= SP8[ work & 0x3fL];
+ fval |= SP6[(work >> 8) & 0x3fL];
+ fval |= SP4[(work >> 16) & 0x3fL];
+ fval |= SP2[(work >> 24) & 0x3fL];
+ left ^= fval;
+ work = (left << 28) | (left >> 4);
+ keys -= 4;
+ work ^= *keys++;
+ fval = SP7[ work & 0x3fL];
+ fval |= SP5[(work >> 8) & 0x3fL];
+ fval |= SP3[(work >> 16) & 0x3fL];
+ fval |= SP1[(work >> 24) & 0x3fL];
+ work = left ^ *keys++;
+ fval |= SP8[ work & 0x3fL];
+ fval |= SP6[(work >> 8) & 0x3fL];
+ fval |= SP4[(work >> 16) & 0x3fL];
+ fval |= SP2[(work >> 24) & 0x3fL];
+ right ^= fval;
+ keys -= 4;
+ }
+ }
+ block[0] = right;
+ block[1] = left;
+}
diff --git a/third_party/heimdal/lib/hcrypto/des.h b/third_party/heimdal/lib/hcrypto/des.h
new file mode 100644
index 0000000..0824408
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/des.h
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef _DESperate_H
+#define _DESperate_H 1
+
+/* symbol renaming */
+#define _DES_ipfp_test _hc_DES_ipfp_test
+#define DES_cbc_cksum hc_DES_cbc_cksum
+#define DES_cbc_encrypt hc_DES_cbc_encrypt
+#define DES_cfb64_encrypt hc_DES_cfb64_encrypt
+#define DES_check_key_parity hc_DES_check_key_parity
+#define DES_ecb3_encrypt hc_DES_ecb3_encrypt
+#define DES_ecb_encrypt hc_DES_ecb_encrypt
+#define DES_ede3_cbc_encrypt hc_DES_ede3_cbc_encrypt
+#define DES_encrypt hc_DES_encrypt
+#define DES_generate_random_block hc_DES_generate_random_block
+#define DES_init_random_number_generator hc_DES_init_random_number_generator
+#define DES_is_weak_key hc_DES_is_weak_key
+#define DES_key_sched hc_DES_key_sched
+#define DES_new_random_key hc_DES_new_random_key
+#define DES_pcbc_encrypt hc_DES_pcbc_encrypt
+#define DES_rand_data hc_DES_rand_data
+#define DES_random_key hc_DES_random_key
+#define DES_read_password hc_DES_read_password
+#define DES_set_key hc_DES_set_key
+#define DES_set_key_checked hc_DES_set_key_checked
+#define DES_set_key_unchecked hc_DES_set_key_unchecked
+#define DES_set_key_sched hc_DES_set_key_sched
+#define DES_set_odd_parity hc_DES_set_odd_parity
+#define DES_set_random_generator_seed hc_DES_set_random_generator_seed
+#define DES_set_sequence_number hc_DES_set_sequence_number
+#define DES_string_to_key hc_DES_string_to_key
+
+/*
+ *
+ */
+
+#define DES_CBLOCK_LEN 8
+#define DES_KEY_SZ 8
+
+#define DES_ENCRYPT 1
+#define DES_DECRYPT 0
+
+typedef unsigned char DES_cblock[DES_CBLOCK_LEN];
+typedef struct DES_key_schedule
+{
+ uint32_t ks[32];
+} DES_key_schedule;
+
+/*
+ *
+ */
+
+#ifndef HC_DEPRECATED
+#if defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1 )))
+#define HC_DEPRECATED __attribute__((deprecated))
+#elif defined(_MSC_VER) && (_MSC_VER>1200)
+#define HC_DEPRECATED __declspec(deprecated)
+#else
+#define HC_DEPRECATED
+#endif
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void DES_set_odd_parity(DES_cblock *);
+int DES_check_key_parity(DES_cblock *);
+int DES_is_weak_key(DES_cblock *);
+int HC_DEPRECATED DES_set_key(DES_cblock *, DES_key_schedule *);
+int DES_set_key_checked(DES_cblock *, DES_key_schedule *);
+int DES_set_key_unchecked(DES_cblock *, DES_key_schedule *);
+int DES_key_sched(DES_cblock *, DES_key_schedule *);
+void DES_string_to_key(const char *, DES_cblock *);
+int DES_read_password(DES_cblock *, char *, int);
+
+void HC_DEPRECATED DES_rand_data(void *, int);
+void HC_DEPRECATED DES_set_random_generator_seed(DES_cblock *);
+void HC_DEPRECATED DES_generate_random_block(DES_cblock *);
+void HC_DEPRECATED DES_set_sequence_number(void *);
+void HC_DEPRECATED DES_init_random_number_generator(DES_cblock *);
+void HC_DEPRECATED DES_random_key(DES_cblock *);
+int HC_DEPRECATED DES_new_random_key(DES_cblock *);
+
+
+void DES_encrypt(uint32_t [2], DES_key_schedule *, int);
+void DES_ecb_encrypt(DES_cblock *, DES_cblock *, DES_key_schedule *, int);
+void DES_ecb3_encrypt(DES_cblock *,DES_cblock *, DES_key_schedule *,
+ DES_key_schedule *, DES_key_schedule *, int);
+void DES_pcbc_encrypt(const void *, void *, long,
+ DES_key_schedule *, DES_cblock *, int);
+void DES_cbc_encrypt(const void *, void *, long,
+ DES_key_schedule *, DES_cblock *, int);
+void DES_ede3_cbc_encrypt(const void *, void *, long,
+ DES_key_schedule *, DES_key_schedule *,
+ DES_key_schedule *, DES_cblock *, int);
+void DES_cfb64_encrypt(const void *, void *, long,
+ DES_key_schedule *, DES_cblock *, int *, int);
+
+
+uint32_t DES_cbc_cksum(const void *, DES_cblock *,
+ long, DES_key_schedule *, DES_cblock *);
+
+
+void _DES_ipfp_test(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* _DESperate_H */
diff --git a/third_party/heimdal/lib/hcrypto/destest.c b/third_party/heimdal/lib/hcrypto/destest.c
new file mode 100644
index 0000000..0761ded
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/destest.c
@@ -0,0 +1,621 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#ifdef KRB5
+#include <krb5-types.h>
+#endif
+
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#include <err.h>
+
+#include "des.h"
+
+static void
+ecb_test(char key[8], char in[8], char out[8])
+{
+ unsigned char k[8], indata[8], outdata[8], outdata2[8], ansdata[8];
+ DES_key_schedule s;
+
+ memcpy(k, key, 8);
+ memcpy(indata, in, 8);
+ memcpy(ansdata, out, 8);
+ DES_set_odd_parity(&k);
+ DES_set_key_unchecked(&k, &s);
+ DES_ecb_encrypt(&indata, &outdata, &s, 1);
+ if (memcmp(outdata, ansdata, sizeof(ansdata)) != 0)
+ errx(1, "des: encrypt");
+ DES_ecb_encrypt(&outdata, &outdata2, &s, 0);
+ if (memcmp(indata, outdata2, sizeof(outdata2)) != 0)
+ errx(1, "des: decrypt");
+}
+
+static void
+ebc3_test(char key1[8], char key2[8], char key3[8], char in[8], char out[8])
+{
+ unsigned char k1[8], k2[8], k3[8],
+ indata[8], outdata[8], outdata2[8], ansdata[8];
+ DES_key_schedule s1, s2, s3;
+
+ memcpy(k1, key1, 8);
+ memcpy(k2, key2, 8);
+ memcpy(k3, key3, 8);
+ memcpy(indata, in, 8);
+ memcpy(ansdata, out, 8);
+ DES_set_odd_parity(&k1);
+ DES_set_odd_parity(&k2);
+ DES_set_odd_parity(&k3);
+ DES_set_key_unchecked(&k1, &s1);
+ DES_set_key_unchecked(&k2, &s2);
+ DES_set_key_unchecked(&k3, &s3);
+ DES_ecb3_encrypt(&indata, &outdata, &s1, &s2, &s3, 1);
+ if (memcmp(outdata, ansdata, sizeof(ansdata)) != 0)
+ errx(1, "des3: encrypt");
+ DES_ecb3_encrypt(&outdata, &outdata2, &s1, &s2, &s3, 0);
+ if (memcmp(indata, outdata2, sizeof(outdata2)) != 0)
+ errx(1, "des3: decrypt");
+}
+
+static void
+cbc_test(char key1[8], char iv[8], char in[24], char out[24])
+{
+ unsigned char k1[8],
+ indata[24], outdata[24], outdata2[24], ansdata[24];
+ DES_key_schedule s1;
+ DES_cblock ivdata;
+
+ memcpy(k1, key1, 8);
+ memcpy(ivdata, iv, 8);
+ memcpy(indata, in, 24);
+ memcpy(ansdata, out, 24);
+ DES_set_odd_parity(&k1);
+ DES_set_key_unchecked(&k1, &s1);
+ DES_cbc_encrypt(indata, outdata, 24, &s1, &ivdata, 1);
+ if (memcmp(outdata, ansdata, sizeof(ansdata)) != 0)
+ errx(1, "cbc: encrypt");
+ DES_cbc_encrypt(outdata, outdata2, 24, &s1, &ivdata, 0);
+ if (memcmp(indata, outdata2, sizeof(outdata2)) != 0)
+ errx(1, "cbc: decrypt");
+}
+
+static void
+cfb64_test(char key1[8], char iv[8], char in[23], char out[23])
+{
+ unsigned char k1[8],
+ indata[23], outdata[23], outdata2[23], ansdata[23];
+ DES_key_schedule s1;
+ DES_cblock ivdata;
+ int num;
+
+ memcpy(k1, key1, 8);
+ memcpy(indata, in, 23);
+ memcpy(ansdata, out, 23);
+ DES_set_odd_parity(&k1);
+ DES_set_key_unchecked(&k1, &s1);
+ num = 0;
+ memcpy(ivdata, iv, 8);
+ DES_cfb64_encrypt(indata, outdata, 23, &s1, &ivdata, &num, 1);
+ if (memcmp(outdata, ansdata, sizeof(ansdata)) != 0)
+ errx(1, "cfb64: encrypt");
+ num = 0;
+ memcpy(ivdata, iv, 8);
+ DES_cfb64_encrypt(outdata, outdata2, 23, &s1, &ivdata, &num, 0);
+ if (memcmp(indata, outdata2, sizeof(outdata2)) != 0)
+ errx(1, "cfb64: decrypt");
+}
+
+static void
+cbc3_test(char key1[8], char key2[8], char key3[8],
+ char iv[8], char in[24], char out[24])
+{
+ unsigned char k1[8], k2[8], k3[8],
+ indata[24], outdata[24], outdata2[24], ansdata[24];
+ DES_key_schedule s1, s2, s3;
+ DES_cblock ivdata, ivec_copy;
+
+ memcpy(k1, key1, 8);
+ memcpy(k2, key2, 8);
+ memcpy(k3, key3, 8);
+ memcpy(ivdata, iv, 8);
+ memcpy(indata, in, 24);
+ memcpy(ansdata, out, 24);
+ DES_set_odd_parity(&k1);
+ DES_set_odd_parity(&k2);
+ DES_set_odd_parity(&k3);
+ DES_set_key_unchecked(&k1, &s1);
+ DES_set_key_unchecked(&k2, &s2);
+ DES_set_key_unchecked(&k3, &s3);
+ memcpy(&ivec_copy, &ivdata, sizeof(ivec_copy));
+ DES_ede3_cbc_encrypt(indata, outdata, 24,
+ &s1, &s2, &s3, &ivec_copy, 1);
+ if (memcmp(outdata, ansdata, sizeof(ansdata)) != 0)
+ errx(1, "cbc3: encrypt");
+ memcpy(&ivec_copy, &ivdata, sizeof(ivec_copy));
+ DES_ede3_cbc_encrypt(outdata, outdata2, 24,
+ &s1, &s2, &s3, &ivec_copy, 0);
+ if (memcmp(indata, outdata2, sizeof(outdata2)) != 0)
+ errx(1, "cbc3: decrypt");
+}
+
+
+static void
+pcbc_test(char key1[8], char iv[8], char in[24], char out[24])
+{
+ unsigned char k1[8],
+ indata[24], outdata[24], outdata2[24], ansdata[24];
+ DES_key_schedule s1;
+ DES_cblock ivdata;
+
+ memcpy(k1, key1, 8);
+ memcpy(ivdata, iv, 8);
+ memcpy(indata, in, 24);
+ memcpy(ansdata, out, 24);
+ DES_set_odd_parity(&k1);
+ DES_set_key_unchecked(&k1, &s1);
+ DES_pcbc_encrypt(indata, outdata, 24, &s1, &ivdata, 1);
+ if (memcmp(outdata, ansdata, sizeof(ansdata)) != 0)
+ errx(1, "pcbc: encrypt");
+ DES_pcbc_encrypt(outdata, outdata2, 24, &s1, &ivdata, 0);
+ if (memcmp(indata, outdata2, sizeof(outdata2)) != 0)
+ errx(1, "pcbc: decrypt");
+}
+
+static void
+cbc_cksum(char key1[8], char iv[8], char *in, size_t len,
+ uint32_t ret, char out[8])
+{
+ unsigned char k1[8], indata[24], ansdata[8];
+ DES_key_schedule s1;
+ DES_cblock ivdata, outdata;
+ uint32_t r;
+
+ memcpy(k1, key1, 8);
+ memcpy(ivdata, iv, 8);
+ memcpy(indata, in, len);
+ memcpy(ansdata, out, 8);
+ DES_set_odd_parity(&k1);
+ DES_set_key_unchecked(&k1, &s1);
+ r = DES_cbc_cksum(indata, &outdata, len, &s1, &ivdata);
+ if (ret != r)
+ errx(1, "cbc_cksum: cksum error");
+ if (memcmp(outdata, ansdata, sizeof(ansdata)) != 0)
+ errx(1, "cbc_cksum: checksum");
+}
+
+static void
+s2k(char *password, const char *salt, char akey[8])
+{
+ DES_cblock k;
+ size_t l = strlen(password) + strlen(salt);
+ char *pw = malloc(l + 1);
+ strcpy(pw, password);
+ strcat(pw, salt);
+
+ DES_string_to_key(pw, &k);
+ if (memcmp(akey, &k, 8) != 0)
+ errx(1, "key wrong for '%s'", pw);
+ free(pw);
+}
+
+static void
+weak_test(int is_weak, const char akey[8])
+{
+ DES_cblock key;
+ memcpy(&key, akey, sizeof(key));
+ if (DES_is_weak_key(&key) != is_weak)
+ errx(1, "weakness is wrong");
+}
+
+/*
+ *
+ */
+
+int
+main(int argc, char **argv)
+{
+ _DES_ipfp_test();
+
+ ecb_test("\x31\x16\xe3\x57\x97\xa8\x68\xe5",
+ "\xbb\xe4\x48\x6e\xdf\x9a\x05\x4f",
+ "\xa8\x82\xa0\x15\x76\xeb\xfd\xc7");
+ ecb_test("\xfe\x4a\x19\xa1\x45\xa7\xb9\xd0",
+ "\x2a\x67\x3c\x07\x59\x4d\xde\xb8",
+ "\x9d\x61\xd5\x1c\xd7\xd0\xd3\x8b");
+ ecb_test("\xbf\x13\x25\xec\xa4\xbc\x1a\x54",
+ "\x16\xa5\xd9\x30\x0f\x55\x20\x71",
+ "\x04\x44\x6c\xe0\x32\x32\x78\xd2");
+
+ ebc3_test("\x7c\x2f\x79\xd5\xb5\x37\x01\xcb",
+ "\xb9\xbc\x86\xea\x04\x45\xab\x2c",
+ "\x19\x1c\xcd\x83\x8a\x29\x97\x3e",
+ "\x87\x03\x59\xdd\xf4\xc6\xeb\xb7",
+ "\xcc\x72\x66\x85\xed\xa2\xee\x09");
+ ebc3_test("\x10\x34\x32\x4c\xc4\x9b\x57\x5b",
+ "\xb0\x6e\xb6\x26\xd6\x52\x2c\x15",
+ "\xa7\x64\xf8\x20\xc1\x89\x73\xc1",
+ "\x37\xa4\xad\x4d\x76\xee\x7c\x02",
+ "\xdf\xb9\x2b\x99\x59\x71\xc4\x89");
+ ebc3_test("\xf8\xa7\xfd\xe6\x6d\x73\x34\x26",
+ "\x4c\xbf\x40\x5d\x5d\xf4\x31\xef",
+ "\x04\xdf\xf2\x58\xd0\x5e\x54\x68",
+ "\x44\x2a\xa2\x19\xbd\x0a\x2b\x61",
+ "\x17\x26\x39\xd5\xd5\xd9\x40\x71");
+ ebc3_test("\x13\x5e\x23\x07\x2c\x16\x0d\x25",
+ "\x64\x6d\x2f\xe0\x68\xa8\x16\x75",
+ "\x7c\x7c\x19\x64\xbc\xae\xe0\x0e",
+ "\x7b\x8c\x76\x76\xb0\x95\x7f\xed",
+ "\xe2\x6e\x05\x1d\xdc\x74\xc1\xb7");
+ ebc3_test("\xbc\x92\x32\xb6\x68\x0d\x73\x19",
+ "\x70\xef\x98\x19\xe9\xec\x04\x1c",
+ "\x02\x4c\x75\x08\xce\xc4\x34\x16",
+ "\x73\xab\x28\x69\x6a\x20\x2f\x99",
+ "\x3b\xb1\x2d\xb6\x21\x0a\x44\xca");
+ ebc3_test("\x01\x98\x16\xea\x85\xd5\x3b\x8a",
+ "\x73\x23\xb5\x49\xd9\x10\x5b\xea",
+ "\xb6\xc4\xce\xc4\x89\x92\x0e\x15",
+ "\xd9\x35\xcf\x21\x47\x7b\xdf\xb5",
+ "\xa1\x71\x57\x1f\x1e\x84\x08\xac");
+ ebc3_test("\x58\x6d\xbc\x04\x70\x4f\xe6\x3e",
+ "\xcd\x76\x26\x01\xae\xce\x0b\xe5",
+ "\xf2\x4f\x64\x16\x8f\x0d\x4f\x6b",
+ "\xa7\x0d\xa0\x56\xa0\x8b\x2a\x77",
+ "\xe5\x12\x9b\x8a\x92\xc8\xdd\xe1");
+ ebc3_test("\x40\xd6\xad\x43\x52\x23\xa7\xcd",
+ "\x04\x19\xae\x94\xce\x46\x31\xd3",
+ "\x45\x6e\x3b\xb5\x4f\x37\x5e\x9d",
+ "\xbd\xb0\x60\x75\x91\x02\x48\xf4",
+ "\xb5\xa1\xe6\x4b\x4e\xa3\x8c\x4b");
+ ebc3_test("\x91\xab\x80\x9b\x97\xf4\x58\x5e",
+ "\xc2\x68\x46\x61\x9e\x04\xa1\x29",
+ "\xc7\xe5\x5b\x32\xcb\x43\xc8\xa4",
+ "\x31\x38\x90\x1c\xc8\x78\x12\x50",
+ "\xf8\x65\xae\xa1\xdf\x4e\xbf\xa8");
+
+ cbc_test("\x57\x98\x7a\x8a\x29\x7c\xc1\xad",
+ "\xe1\x28\x69\x58\xd6\x91\x9f\x4e",
+ "\xa0\x11\x1a\xdd\xeb\x62\xb8\x9e\x28\x08\x6e\x0b\x6d\x6d\x57\x31\x1b\x4c\x82\x4c\xc3\x19\xe0\x93",
+ "\x42\xa5\x2f\x26\xbb\x92\x3a\x6b\x64\xe0\x3b\x1a\x33\x5a\x9c\x2b\xc8\xd9\x41\x37\x8d\x3e\x58\xbf");
+ cbc_test("\x23\xd6\xec\x86\x86\x4f\x02\xcd",
+ "\xfe\x8e\xa4\x07\x35\x41\x14\x99",
+ "\xe3\xc2\x5d\x6e\x81\xae\xa0\xe8\xc8\xdd\xd2\x0d\xf4\x26\x90\x10\xca\x8c\x07\x58\xb2\x17\xcc\x1a",
+ "\x97\xb9\xbc\xa6\xd1\x98\xc1\x7f\x4b\xac\x61\x8a\x16\xec\x1f\xee\x28\x6f\xe8\x25\xf0\x41\xbc\xde");
+ cbc_test("\x07\xe5\xc8\x52\xba\x3d\xef\xcd",
+ "\xa9\x21\x3e\x84\x44\x7c\xce\x1a",
+ "\xfc\x03\x72\x30\xb0\xcb\xe8\x99\x21\x54\x4d\xfa\x86\xdd\x99\xe1\x96\xe7\x7c\xb5\xbd\x5b\x6f\xd0",
+ "\x27\x76\x66\x62\x1f\xcf\x48\xdb\x15\x11\x73\x8b\xe0\xc9\xbd\x2b\x40\xae\x0c\x35\xeb\x93\xa3\x1c");
+ cbc_test("\xef\x2f\x07\xd6\x2f\x70\x4f\x68",
+ "\x16\x1e\xaf\x87\x3a\x83\x9f\x33",
+ "\xb8\x4c\xb3\xbf\xfa\x5d\xa9\xc7\x1c\x15\x8d\x39\xf2\x29\xf5\x5a\x3d\x21\x0d\x61\x05\xaa\x48\x92",
+ "\x51\x85\x2f\xad\x67\xb6\x0a\x15\xb8\x73\x15\xf1\x79\x9d\xed\xf5\x6c\x11\x22\xe5\x48\x51\xab\xae");
+ cbc_test("\xd0\x2c\x68\xc1\xe6\xb0\x76\x98",
+ "\xc7\x4f\x31\xa9\x5d\xd5\x5b\xcc",
+ "\x9d\x4b\x2a\x54\x60\xf1\xb0\x10\x34\x87\xdc\x25\xa5\x80\x6c\x4d\x0c\x7f\x53\x37\x58\x42\xc7\x26",
+ "\x79\xc5\xf0\x21\x0d\x7a\x38\xc0\x66\x9a\x07\x2f\xa4\x9c\x1f\xbb\x66\x4d\x6c\x86\x5b\x47\x44\x60");
+ cbc_test("\xd6\xe3\x75\x92\xb0\x8f\x45\x70",
+ "\xdc\xc6\xab\x3e\xf2\x7e\x13\xd6",
+ "\x38\x57\x27\x0a\xef\x74\x94\x82\x92\xfa\x28\xed\xff\x24\x1e\x0e\x8f\xaa\x9e\x24\x2f\x41\x65\x78",
+ "\x1d\xcc\x07\x55\xe8\xea\xd1\x08\x55\x11\x72\xfe\xdb\xdf\xa0\xc9\xb6\x3a\x2e\xdf\xf0\x67\xd3\xf4");
+ cbc_test("\xb3\xbc\xb5\x61\x04\xda\x1a\x34",
+ "\x8e\x4e\xa5\x8a\xeb\x6a\xea\xbb",
+ "\x72\x73\x51\xe0\x58\xc5\x2e\xe1\x64\x10\x05\x59\x64\x70\x3f\xbe\x43\xa2\xed\x7a\x5d\x1b\x9c\xc7",
+ "\xa6\xb2\xf2\xea\x96\x62\xfb\x2f\x2a\x6a\xa1\x2f\x8e\xe1\x12\xd2\xe4\x82\x4c\xc1\x00\x74\x9c\x8f");
+ cbc_test("\x8f\xdf\x01\x89\xfe\x13\x9b\x2c",
+ "\x66\x18\xf8\x80\xa1\x3b\x1b\x91",
+ "\x32\xdb\xae\xa7\x3b\x77\xb2\x6e\xcc\xa5\xa1\x2e\x15\x19\x49\x83\x2f\xfb\x94\xcc\xd1\xa1\x4b\x02",
+ "\x47\x31\xca\x04\x4d\x1a\x24\x39\xda\x71\xc5\xb8\x7f\xea\x79\xf5\x43\xa6\x53\x15\x78\x84\x34\x75");
+ cbc_test("\xe5\x34\xb6\x75\x68\x07\x70\x85",
+ "\x73\x98\x29\xf7\x7a\xe7\xe7\xb7",
+ "\x9c\x9e\x4c\xa6\x62\x21\xc4\x15\x47\x43\xd5\xf2\x3a\xf3\xfd\xb5\x53\xa7\x16\x9e\xa6\x4f\x0d\xac",
+ "\x81\x2d\xa4\x99\x60\xbf\x9c\xf4\x46\x1d\xee\xc6\xb0\xe1\x4a\x29\xea\xfd\xce\x4b\xa1\x45\x93\x7b");
+
+ cbc3_test("\x61\xcb\x8c\xb0\x32\x2a\xc2\x5d",
+ "\x98\xe3\x49\xc1\x0d\xb5\x67\xce",
+ "\xf2\x43\x10\x61\x85\x6b\xa7\x15",
+ "\x65\xf5\x8f\x1a\x2b\x33\xf2\xb5",
+ "\x8c\x06\xe0\x60\x68\x25\x9c\x95\x81\x46\xda\x41\x9d\xa8\x9c\x49\x2f\xee\x33\x35\x95\x11\xbd\xa0",
+ "\x93\x27\xed\xc7\x35\xb9\xe5\x3c\x7b\x10\x3e\x39\x01\x41\x61\x04\xe7\xf2\xd9\x63\x96\xca\x57\xf1");
+ cbc3_test("\x15\x61\x6b\x76\xae\x0e\x98\x01",
+ "\x76\xce\x9d\x94\xa7\xe3\x73\xa4",
+ "\x19\xd9\x15\x98\x9b\xba\x83\x40",
+ "\x60\xef\xc2\xc6\xa2\x40\x01\xc7",
+ "\x8b\x4d\xf4\x37\xad\x1c\xc2\x4e\xcc\xc4\x4b\x17\x67\xf7\xfa\xec\xf8\x94\x6f\x7a\x84\x56\x81\x09",
+ "\x68\xdf\x82\xcb\xd9\xcd\x3d\xca\x12\x0e\x2e\x39\xba\xf7\x5a\x8c\x41\xbd\x6f\x9d\x85\xfe\x1b\x1d");
+ cbc3_test("\xd5\x2a\x4f\xa4\x13\x9e\x73\x15",
+ "\x6d\x75\xa8\x15\x07\xd3\x7c\x79",
+ "\xd5\xe0\xa7\x91\xf8\xf2\x9d\xcd",
+ "\x4c\xdb\x56\xb8\x6f\x0e\x2a\x59",
+ "\xbe\x64\x20\x24\x7d\x2b\x6b\xf4\xd9\xc0\xa0\x9b\x8d\x88\x6e\x50\x6f\xf8\xb6\x4a\x7e\x52\x52\x93",
+ "\x01\x83\x75\x7b\xd6\x03\xff\xd8\xe9\x6d\x6c\x92\x24\x25\x35\xfa\x43\x4c\x40\xff\xec\xb0\x8b\x50");
+ cbc3_test("\x02\xad\x13\x31\xd5\xd6\xef\x7c",
+ "\x86\x3e\x02\xce\x94\x97\x37\xba",
+ "\x01\x07\x20\x04\xf8\x92\xb6\xb3",
+ "\x26\x79\x1b\xef\x90\x54\xd6\xc1",
+ "\x55\xee\xea\x81\x42\x8b\xbf\xfb\x6c\x14\xec\xbd\xba\x55\x0d\xc4\xd2\xd6\xf0\xea\xd1\x03\xde\x5b",
+ "\x69\x49\xc5\x48\x4f\xda\x03\x90\x84\xef\x86\xd2\x98\xa7\xae\xfa\x17\x35\x7e\x06\xbd\xd3\x51\x0b");
+ cbc3_test("\x3d\x9b\xae\x5b\x7f\x91\x85\xe0",
+ "\xdf\x07\xb3\xdf\x97\x0b\x43\x80",
+ "\xe3\x46\x58\xd9\x68\x79\xb3\xae",
+ "\xd4\x27\xee\x5d\x73\xb1\x82\xf5",
+ "\x44\x86\x9a\xa6\x79\x2d\x9e\x94\x11\x6c\x7b\xc6\xe8\xef\x63\x95\x71\xc6\x62\x20\x43\x87\xaf\x65",
+ "\xc2\xf5\xbc\x91\xc5\x7c\x69\xb2\x05\xcc\x28\x92\xc1\x96\x5a\xc2\xcb\x0c\x71\xc7\x51\x7d\x0c\xcc");
+ cbc3_test("\x43\x8c\x23\x92\xd5\x92\x67\xfb",
+ "\x5b\x5e\xb0\x31\x1c\x9d\x5d\x10",
+ "\x8a\xa2\x16\x64\xd6\xa4\xc4\x5b",
+ "\x06\xc5\xdd\xa3\x4a\x2b\x37\xb7",
+ "\x99\xd5\x76\xee\x7c\x4d\xcc\x18\x39\x78\x16\x7c\xcc\x1a\x0a\x27\xdb\xf1\x5f\xe1\x87\x86\xb7\x2c",
+ "\x91\xbe\xaf\x79\xd0\x14\x7c\x05\x60\x1c\x7e\xd6\x22\x15\xac\xed\xf3\x78\xa5\xc7\x52\xa0\x60\x49");
+ cbc3_test("\x80\xc2\x86\x7a\x51\x45\x29\x1c",
+ "\xc7\xfd\xad\xd0\x7c\x4a\xd0\x3e",
+ "\xe6\x89\x98\xfe\x01\x67\x20\x89",
+ "\x5c\x23\xe4\x26\x82\x27\xad\xeb",
+ "\xa1\x38\x4e\xf1\x07\x1a\xdd\x25\x47\xe6\xda\x9d\xa9\xfe\x98\x55\x05\x95\x75\xc2\x59\x18\xcf\xf1",
+ "\x36\x58\xea\xc5\xf8\x41\xa7\x49\xe8\x22\x75\xfe\xb6\x8b\xdd\x0d\xf0\x66\x42\xe6\x84\x23\x29\xff");
+ cbc3_test("\xbc\x68\x54\x85\x2c\xc1\xe0\x07",
+ "\x7c\x6e\x34\x04\x6b\x91\xc4\x54",
+ "\x9d\xa4\xda\xa1\xda\x6d\xdc\xd3",
+ "\x1c\x3d\xa9\x41\xa2\xe5\xff\x8a",
+ "\x0a\x58\xff\x5a\xec\xc1\x7e\x94\x24\xf4\x4f\xdc\x5b\x29\xe2\x78\x62\x8a\xd2\xe2\xd7\x45\x54\x17",
+ "\x80\x68\xa6\xed\x87\x40\xd5\x32\xd2\xb8\x32\x61\x35\xae\xae\xf7\x14\x1f\x98\xdb\xba\x21\x4f\x9f");
+ cbc3_test("\xa1\x2a\x7a\x67\xfe\xea\xd3\xe3",
+ "\x70\xe5\xd5\x4c\xf1\xce\x4c\x26",
+ "\x75\x4c\x85\x16\xb5\xc8\x07\xe9",
+ "\x4c\xa4\xb5\xdd\x86\x86\x70\x5a",
+ "\x0d\x07\xfd\x23\xc1\x1d\x65\xd8\xb2\x79\xb8\xa3\xc5\x8e\x47\xbe\x0f\xed\x7b\x15\x43\xe9\x7c\x5e",
+ "\xde\x17\xfe\x05\x43\x80\x85\xd0\x9c\x60\xe0\xbe\x8d\xa2\x65\x0e\x63\x02\x72\xb6\xf3\x7d\xda\x90");
+
+
+ pcbc_test("\xe3\xf2\xb0\x26\x7c\x4a\x94\x80",
+ "\x40\x08\x4c\x44\xa3\xb5\xf7\x97",
+ "\xe7\xbd\x54\xa1\xbb\x48\x67\xcd\xe0\xee\xff\x8d\x3d\x25\x2b\xf0\x61\x48\xbe\xf2\x63\x5d\xce\x4a",
+ "\xf5\xe9\x48\xdc\xb8\x61\x39\xa9\x90\x27\xec\x09\x23\x50\xe0\xa9\x78\xb2\x1c\x29\x3c\xa7\x6c\x88");
+ pcbc_test("\xfd\x54\x2a\x5b\x97\xa4\x5b\x52",
+ "\x37\x36\x6e\x22\x7e\x66\x08\x8c",
+ "\xe4\x2d\x81\x88\x86\xb2\x44\x55\x80\x3d\x3c\xbd\x42\x9f\x5d\xdb\x4b\x63\x23\x1c\x31\x13\xa6\x0f",
+ "\x9c\x9f\x65\x05\x79\x91\x71\x96\x82\x2a\xc0\xe5\xa0\x6f\x71\xab\x68\x32\xd4\xd7\x5e\x38\x38\xf6");
+ pcbc_test("\x25\x91\x08\xe5\x57\x85\xb6\x20",
+ "\x47\x6e\xbe\x9f\xb9\x6b\x55\xe9",
+ "\x44\xfd\xdd\x42\x07\x99\xf0\x8f\xdb\xa5\x14\x1e\x76\x07\x90\x5b\x29\x10\x21\xb9\x7e\xac\xc7\x77",
+ "\x88\x4f\xdc\x6e\x37\x5e\x4e\xac\x8d\x3f\x9d\xd1\x82\x51\x65\xf5\xf9\x08\xa7\xac\x01\x61\x19\x85");
+ pcbc_test("\x6d\x43\xc7\x9d\x6b\x97\x64\x40",
+ "\x56\xfb\xcb\xb3\x97\xb5\x70\x13",
+ "\x54\x67\xa9\x42\x86\x85\x81\x8f\xb4\x72\xa2\x5f\x2d\x90\xbb\x5c\xb5\xb9\x9b\x71\x8f\x2b\xae\x05",
+ "\x2c\xd1\x63\x6f\x11\x1d\x5e\x40\x8c\x47\x49\x12\x31\x48\xb7\x12\x4c\xc1\x6a\xaf\x0e\x33\x11\xe1");
+ pcbc_test("\x3b\xa2\xbc\xd5\x5d\x9d\xdf\x73",
+ "\x43\xb7\x26\x71\xce\x6d\x97\xac",
+ "\x4e\xf6\x7d\xd7\xfc\x6b\x35\x54\xae\xc9\xfe\xf7\xb7\x1e\x47\xa5\x61\x44\x50\xb3\xe4\xe8\x7d\xdc",
+ "\x4d\xda\xbd\xad\xc4\xde\xdc\xf4\xfc\xbd\xfc\xa7\xbd\xe4\x7e\x73\x28\xc5\x5c\xd0\x9a\x35\x39\xa6");
+ pcbc_test("\x46\x9e\xda\xdf\x0d\x97\x8a\xd3",
+ "\x6c\x9f\xdf\xc0\x48\x3b\xa5\x17",
+ "\xb9\xd8\x99\x61\x67\xf3\xec\xa9\xc1\x29\xa3\x8b\x63\xe2\xc2\x28\xaf\x56\x2d\x39\x1d\xeb\x7c\xbc",
+ "\x70\x5d\xd4\x54\x90\xb9\x6c\x0c\x93\x96\x6a\x4a\x4e\xb8\x80\xce\xb3\xcd\x64\xa7\x6c\xb2\xe4\xc9");
+ pcbc_test("\x31\x89\x51\x38\x2f\x97\xfe\xef",
+ "\x17\xdc\xf8\xde\xcc\x8f\x40\x3e",
+ "\xef\xcf\xe9\x9e\x11\xd8\x35\xdf\x58\x11\xd0\x0a\x68\xce\xe1\x6b\xb5\xca\x68\x47\xb7\xb9\x9a\x34",
+ "\x3a\x93\x47\x3c\x1b\xa9\xeb\x88\x13\xfd\x1b\xd8\x76\xb5\xd3\xe2\xb8\x83\x10\x56\x68\xab\xe1\x28");
+ pcbc_test("\xba\x1c\x70\x94\x62\x10\x19\xda",
+ "\x7a\x8b\xc0\x9e\x00\xbb\x7e\xcb",
+ "\x30\x74\x6b\xa6\xd6\x07\xae\x44\xd6\x5c\xe6\x18\x97\x90\xaa\x08\xcb\xa8\xf4\x8b\xea\x8b\x4f\xe6",
+ "\x0a\x77\x24\x7c\xcd\xf8\x06\x01\x20\x02\x14\x33\xd6\xf4\x4e\x89\xc0\x38\x65\x44\x6b\x9c\x92\x16");
+ pcbc_test("\xfe\x97\xf2\x6d\x8f\x0d\x86\x94",
+ "\x30\x8a\x7d\x9b\xf4\x28\x6e\x84",
+ "\x82\xb0\x9b\x42\xf6\xdc\x38\x41\x41\x03\x60\x28\x7f\x90\x08\x8b\x6c\x55\xe7\x76\xcd\xa7\xae\xbc",
+ "\x35\x0b\xf1\xc0\x56\x64\x6f\x7b\x3e\x1f\xd1\x90\xbd\xda\x10\xb1\xd1\x49\xc6\x62\x5f\xf9\x6c\xf9");
+
+
+ cbc_cksum("\x58\x83\x67\xfb\xdf\x51\x7c\xfd",
+ "\x46\x0a\xa5\x94\x6b\xd6\xaa\x91",
+ "\x15\x0b\x16\x3a\x56\x79\x33\xdf\x6e\xa0\xd9\x54\x14\x7b\x37\xa9\xb1\x15\xe1\x28\xfe\x35\xe9\x34",
+ 24,
+ 0x16466788,
+ "\xa7\xbd\x2a\x1b\x16\x46\x67\x88");
+ cbc_cksum("\xf1\xe0\x91\x1c\xfe\x10\xe5\xb5",
+ "\x9c\xc6\x7d\xf3\x3e\x58\x40\x06",
+ "\x9c\x90\x88\xfe\x9c\x38\xc0\xd5\xaa\xc6\xf2\xc2\x7d\x00\xf6\x5f\xbd\x87\x25\xbe\x41\x64\x9f\xb7",
+ 24,
+ 0xd8a127cc,
+ "\x93\x5d\x75\x62\xd8\xa1\x27\xcc");
+ cbc_cksum("\x20\xbf\xdc\xd5\x5b\x9d\xc8\x79",
+ "\x68\xdc\xe2\xfa\x18\xb3\xa9\xe0",
+ "\xef\xba\xc4\x8b\x78\xc2\x02\xc2\x74\x71\x9f\xfa\x4b\xa2\x8a\xe5\xfb\x82\x3d\x48\xcf\x28\x08\x42",
+ 24,
+ 0x45236285,
+ "\xc0\xb9\x2c\x86\x45\x23\x62\x85");
+ cbc_cksum("\x31\x6d\xa8\xc2\x43\x16\x64\xea",
+ "\x7b\x5e\x9f\x7c\xb8\xa3\xbd\x89",
+ "\x8a\xd4\xe4\x77\xbb\x45\x17\x3d\xd2\xef\xe6\xb9\x65\x8b\xb3\xa9\x28\xef\xd7\x0c\xa8\x47\x5d\xb8",
+ 24,
+ 0x3f021cb2,
+ "\x10\x94\x4c\x2f\x3f\x02\x1c\xb2");
+ cbc_cksum("\xd5\x75\x51\x8f\xc8\x97\x1a\xc4",
+ "\xbc\x7a\x70\x58\xae\x29\x60\x3a",
+ "\x8d\x2c\x70\xdb\x53\xda\x0f\x50\xd9\xb5\x81\x18\x26\x66\x84\xda\xf6\x32\xa0\xe5\xf9\x09\xfd\x35",
+ 24,
+ 0x2f64dd4f,
+ "\x89\xe4\x70\x0d\x2f\x64\xdd\x4f");
+ cbc_cksum("\xda\x6e\x32\x80\x20\xbc\x67\x54",
+ "\xf4\x93\x86\x43\x29\x57\x6e\xec",
+ "\xfe\xd8\xfe\xad\x4e\x05\xd8\xb8\x9b\x9f\xaa\xa5\x90\x6d\xcb\xff\x40\xab\xc5\x25\x2b\xda\xa7\x09",
+ 24,
+ 0x6281ce23,
+ "\xa1\x88\xc2\x3d\x62\x81\xce\x23");
+ cbc_cksum("\xb6\xc7\x75\x8a\xfb\xd3\xf8\xad",
+ "\xf1\x4f\xd7\x39\x4b\xec\xa3\x99",
+ "\x31\xd0\x45\x9d\x62\xe3\x49\xbb\x58\xc2\x58\xbe\x13\x51\x1e\x3f\x54\xe5\x31\x7d\xd0\x94\x57\x7a",
+ 24,
+ 0x09c7ee4e,
+ "\x2f\x40\xb3\xd2\x09\xc7\xee\x4e");
+ cbc_cksum("\xa8\x4f\x16\xf4\x89\x3d\xf7\xec",
+ "\x04\x78\xbc\xd3\x4f\x32\xfd\x46",
+ "\xe5\x44\x30\x5e\x55\xa3\x08\xe9\xcd\xd1\xbe\x63\x66\x26\x27\x62\xc3\x4f\x2a\x50\x69\x21\x24\xde",
+ 24,
+ 0xdf3357c7,
+ "\xa8\x6e\x80\x3b\xdf\x33\x57\xc7");
+ cbc_cksum("\xd6\x4f\x40\xef\x8a\x2a\xf1\x20",
+ "\xd5\x40\xe7\x86\x36\x26\x79\xc9",
+ "\xcc\x74\x2b\x78\xca\x47\xb0\xd3\xe6\x72\x42\x76\xee\x80\xb0\xe5\x78\x12\x3b\x4e\x76\x91\xda\x1a",
+ 24,
+ 0x14a5029a,
+ "\x33\xd2\xb5\x8a\x14\xa5\x02\x9a");
+
+ cbc_cksum("\xfb\x89\xa1\x9d\xa7\xec\xc1\x5e",
+ "\x9c\x7f\x47\xd0\x79\x5d\x4b\x97",
+ "\xb6\x8b\x48\xe0\x01\x78\xec\x50\x7f\xf1\xfd\xd2\x87\x76\xba\x4b\x9c\x5c\xc7\x25",
+ 20,
+ 0xa1471604,
+ "\x39\x5b\x7d\xb1\xa1\x47\x16\x04");
+ cbc_cksum("\x70\xb3\xc4\x0b\x5b\x4f\x98\xe5",
+ "\x86\xc0\x05\x1a\xd5\x8f\x78\x2c",
+ "\xef\x01\x7b\xd8\xff\x68\x5d\x66\xb6\xbe\xd8\xf5\xb9\xed\x4e\xec\xe3\x3c\x12\xc5",
+ 20,
+ 0xc4b74f9a,
+ "\x2b\x07\xe3\x90\xc4\xb7\x4f\x9a");
+ cbc_cksum("\xfe\x04\xcb\xfe\xef\x34\xe9\x58",
+ "\xd9\x28\xae\xc0\x2c\xd3\xf6\xb0",
+ "\x24\x25\x9b\x67\xda\x76\xa6\x64\x6f\x31\x94\x18\x2e\x06\x71\x82\xaf\xbd\x86\x63",
+ 20,
+ 0xbd7c84e6,
+ "\x70\x3e\x91\xf5\xbd\x7c\x84\xe6");
+ cbc_cksum("\x10\xc2\x70\x94\x9b\x16\x20\x1c",
+ "\x62\xed\x5a\x48\x6c\xf3\x51\xa0",
+ "\x90\x3e\x06\xc1\x63\x6a\x1f\x1a\xfe\x9d\x74\xb6\x13\xde\x62\xd2\x6f\x19\x37\x25",
+ 20,
+ 0x26761f96,
+ "\x8b\x6a\x9c\x85\x26\x76\x1f\x96");
+ cbc_cksum("\x61\x32\x7c\x7f\x31\xc7\x98\xe6",
+ "\xd9\xba\x0d\x9d\x9e\xa3\xcc\x66",
+ "\x98\x8f\xc6\x5a\x54\x04\x63\xd9\x53\x86\x5d\x75\x53\x48\xcc\xa3\x00\x7a\x12\xe5",
+ 20,
+ 0xf0f6ad33,
+ "\x6a\xfb\xed\xd3\xf0\xf6\xad\x33");
+ cbc_cksum("\x85\xdf\x01\x2c\xab\x3b\xec\x13",
+ "\xc6\x44\x87\x5b\x78\x2a\x74\x92",
+ "\x8b\xf5\x0d\xff\x5c\xb3\xc1\xcd\x9e\xf7\xb8\x8e\x3b\xf8\x61\x4d\x26\x6a\x7b\xe8",
+ 20,
+ 0x7acfe214,
+ "\x52\xb7\x05\xe9\x7a\xcf\xe2\x14");
+ cbc_cksum("\x49\xdf\xb0\x16\x7f\xec\x10\x52",
+ "\x09\xa3\x36\x8f\xe9\xe0\x06\x19",
+ "\x3a\x0f\x66\xf7\x7a\x47\x34\xe4\xaa\x09\x36\x90\xe9\x90\x19\xff\x99\x94\x92\x04",
+ 20,
+ 0x9a3a59bb,
+ "\xd3\xe2\xce\xfc\x9a\x3a\x59\xbb");
+ cbc_cksum("\x5b\xbf\x4c\xc8\xce\xf4\x51\x1a",
+ "\x7c\xee\xc0\x5a\x20\x2b\x10\x22",
+ "\x05\x1d\xec\xdb\x30\x73\xf2\x21\xbf\x64\xe0\x5f\xdf\x02\x79\xe9\x47\xf2\x9c\x4e",
+ 20,
+ 0xaf9d3602,
+ "\xaa\xf3\xa2\x5a\xaf\x9d\x36\x02");
+ cbc_cksum("\xad\xda\xa2\x19\x6d\x37\xda\x67",
+ "\xb2\x10\x0f\xd5\xda\xdd\x17\xfc",
+ "\x44\x02\x6b\xd6\xd4\x8c\x42\x58\x8b\x59\x35\xce\xd7\x04\x6b\x35\xa6\x5f\x28\x97",
+ 20,
+ 0xd112a978,
+ "\xb2\x5f\x6a\x07\xd1\x12\xa9\x78");
+
+
+ s2k("potatoe", "WHITEHOUSE.GOVdanny",
+ "\xdf\x3d\x32\xa7\x4f\xd9\x2a\x01");
+ s2k("password", "ATHENA.MIT.EDUraeburn",
+ "\xCB\xC2\x2F\xAE\x23\x52\x98\xE3");
+ s2k("\xf0\x9d\x84\x9e", "EXAMPLE.COMpianist",
+ "\x4f\xfb\x26\xba\xb0\xcd\x94\x13");
+ s2k("NNNN6666", "FFFFAAAA",
+ "\xc4\xbf\x6b\x25\xad\xf7\xa4\xf8");
+ s2k("", "",
+ "\x01\x01\x01\x01\x01\x01\x01\xf1");
+
+ cfb64_test("\x45\xc2\x0b\x01\x40\x08\x13\x8a",
+ "\x9a\xef\xf4\x37\x41\x69\x0b\xd6",
+ "\x5d\x12\x5d\xf5\xae\x1d\xc6\x47\x21\xd3\x16\xba\x45\x0e\x9d\x4c\x00\xfd\xf8\x64\xca\x69\x67",
+ "\xff\x99\x06\xd8\xe9\xbc\xae\x7e\xde\x49\x7b\x34\x5d\xa0\x74\x61\x9b\x6f\x70\x38\x40\x40\xba");
+ cfb64_test("\xdc\xe9\x51\xc4\x0b\xad\x85\xa8",
+ "\xf5\x56\x6c\xef\x42\xed\x9f\xa8",
+ "\x7d\xe5\xeb\x04\x5c\xaf\x8c\x5b\xf4\x88\xba\x4a\x99\x6a\x3a\x79\xc0\x88\x01\x05\xac\x98\x3c",
+ "\x53\x87\x11\xc4\xa6\xf3\x1e\x67\x56\xfc\x8c\x63\xf0\x2e\xd9\x0e\x4a\x86\x8e\x5b\xa7\xde\xcf");
+ cfb64_test("\x25\xf7\xa7\x0e\x85\x4f\x5b\xb6",
+ "\x83\xae\x73\x03\xea\xeb\x82\x05",
+ "\x1b\x80\x23\xdc\x61\x23\xa7\xde\x80\xf6\xec\xb1\xc1\x6d\x3e\x59\x1f\x76\x6d\xdf\xfa\x42\xc7",
+ "\xe2\xf7\x8d\x2f\x86\xce\x1f\xfc\xdb\x82\xb9\xb5\x9c\xa9\xf4\x9c\x2b\x3f\x34\x6c\x83\xf7\x7e");
+ cfb64_test("\xab\xd5\xd3\x68\xf1\x2c\x0e\x0d",
+ "\x8a\xea\xe8\xc0\xad\xb9\x51\x83",
+ "\x3d\xcb\x7d\xcf\x57\xa6\xf6\x16\x4f\x34\xb6\x5f\xc2\xa9\xf0\xec\x90\xc5\x43\xa0\x19\xfc\x3f",
+ "\xe9\x2c\x22\x20\xd4\x27\x90\x89\x40\x08\x4a\x23\x4d\x41\x05\x67\xe1\xde\xf5\x0b\x8b\x96\xb1");
+ cfb64_test("\x92\x38\xd3\xfd\x61\x83\x92\x0e",
+ "\x25\xb6\x34\x51\x6d\x6a\x35\xa2",
+ "\x98\x55\xab\x2a\xa2\x9e\xcf\xf4\x92\xdf\xb4\xc6\xc1\x34\x55\xf6\x13\x85\x4c\x50\xdc\x82\x1e",
+ "\x87\x96\x47\xa6\xcd\xff\xda\xd2\xad\x88\xaa\x25\xbd\xcd\x72\x61\x37\x14\x42\x14\xc7\x4b\x7f");
+ cfb64_test("\xf4\xcb\x97\xad\xef\x7f\x80\xb0",
+ "\xfc\xa0\x7d\xb6\x75\xb8\x48\xea",
+ "\xc2\x1e\x16\x2b\xb7\xcf\xc6\xa0\x4b\x76\x75\x61\x49\x66\x0d\xce\xd2\x12\xf2\x98\x07\x2f\xac",
+ "\xe2\x20\xbf\x29\x5b\x34\x20\x2a\x2e\x99\xa5\x50\x97\x1b\x4b\x18\xb4\xd6\x87\x35\x7b\x5f\x43");
+ cfb64_test("\x3b\x1c\x15\xec\xb9\x5e\xe0\xda",
+ "\x7d\x94\x23\x76\x96\x72\x62\xf4",
+ "\x5d\x83\xdb\x76\x52\x46\xa7\x84\x0a\x71\x2c\x09\x40\xbd\x3d\x75\x73\x28\x0b\x22\x07\x6f\x8a",
+ "\xf1\x01\x8f\xe2\x32\x35\xe6\x06\xcf\xbb\xe4\x15\x9e\x4e\xf0\xe8\x2e\xcd\xac\xbf\xa6\xc2\xec");
+ cfb64_test("\xc2\xcd\x76\x79\x7f\x51\xce\x86",
+ "\x38\xcf\x55\x7d\x0c\xd5\x35\xfe",
+ "\xc7\xe5\xe8\x1d\x19\x09\x9f\xd5\xdb\x89\x26\xc1\xf1\xc1\x18\x50\xcf\x8b\xf2\xe1\x87\xeb\xe6",
+ "\xd4\x5d\xca\x30\xb9\x41\xfa\x36\x83\xfc\x40\x2d\xd2\xe8\x94\x38\x49\xc8\xa3\x35\xb7\x5d\x9c");
+ cfb64_test("\x67\xfd\xc4\x31\x45\x40\xf7\xea",
+ "\xb9\x29\xe6\x78\xdd\x1a\x13\x84",
+ "\x12\x9b\xe5\xb3\xdd\x42\x6f\x45\x86\x97\x25\x87\x05\xee\x7e\x57\x8f\x22\x79\xb3\x22\xa2\x95",
+ "\x38\xef\x49\xbc\xdd\xbb\x6b\x73\xc0\xd7\xa6\x70\xe0\x1b\xde\x8d\xe6\xb4\xc6\x69\xca\x5e\x1e");
+
+ weak_test(1, "\x01\x01\x01\x01\x01\x01\x01\x01"); /* weak keys */
+ weak_test(1, "\x01\x01\x01\x01\x01\x01\x01\x01");
+ weak_test(1, "\xFE\xFE\xFE\xFE\xFE\xFE\xFE\xFE");
+ weak_test(1, "\x1F\x1F\x1F\x1F\x0E\x0E\x0E\x0E");
+ weak_test(1, "\xE0\xE0\xE0\xE0\xF1\xF1\xF1\xF1");
+ weak_test(1, "\x01\xFE\x01\xFE\x01\xFE\x01\xFE"); /* semi-weak keys */
+ weak_test(1, "\xFE\x01\xFE\x01\xFE\x01\xFE\x01");
+ weak_test(1, "\x1F\xE0\x1F\xE0\x0E\xF1\x0E\xF1");
+ weak_test(1, "\xE0\x1F\xE0\x1F\xF1\x0E\xF1\x0E");
+ weak_test(1, "\x01\xE0\x01\xE0\x01\xF1\x01\xF1");
+ weak_test(1, "\xE0\x01\xE0\x01\xF1\x01\xF1\x01");
+ weak_test(1, "\x1F\xFE\x1F\xFE\x0E\xFE\x0E\xFE");
+ weak_test(1, "\xFE\x1F\xFE\x1F\xFE\x0E\xFE\x0E");
+ weak_test(1, "\x01\x1F\x01\x1F\x01\x0E\x01\x0E");
+ weak_test(1, "\x1F\x01\x1F\x01\x0E\x01\x0E\x01");
+ weak_test(1, "\xE0\xFE\xE0\xFE\xF1\xFE\xF1\xFE");
+ weak_test(1, "\xFE\xE0\xFE\xE0\xFE\xF1\xFE\xF1");
+
+ weak_test(0, "\x01\x01\x01\x01\x01\x01\x01\x02");
+ weak_test(0, "\xFF\xE0\xFE\xE0\xFE\xF1\xFE\xF1");
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hcrypto/dh-ltm.c b/third_party/heimdal/lib/hcrypto/dh-ltm.c
new file mode 100644
index 0000000..7206621
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/dh-ltm.c
@@ -0,0 +1,264 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <roken.h>
+
+#include <dh.h>
+
+#include "tommath.h"
+
+static int
+BN2mpz(mp_int *s, const BIGNUM *bn)
+{
+ size_t len;
+ void *p;
+
+ len = BN_num_bytes(bn);
+ p = malloc(len);
+ BN_bn2bin(bn, p);
+ if (mp_from_ubin(s, p, len) != MP_OKAY) {
+ free(p);
+ return -1;
+ }
+ free(p);
+ return 0;
+}
+
+
+static BIGNUM *
+mpz2BN(mp_int *s)
+{
+ size_t size;
+ BIGNUM *bn;
+ void *p;
+
+ size = mp_ubin_size(s);
+ p = malloc(size);
+ if (p == NULL)
+ return NULL;
+ if (mp_to_ubin(s, p, SIZE_MAX, NULL) != MP_OKAY) {
+ free(p);
+ return NULL;
+ };
+
+ bn = BN_bin2bn(p, size, NULL);
+ free(p);
+ return bn;
+}
+
+/*
+ *
+ */
+
+#define DH_NUM_TRIES 10
+
+static int
+ltm_dh_generate_key(DH *dh)
+{
+ mp_int pub, priv_key, g, p;
+ int have_private_key = (dh->priv_key != NULL);
+ int codes, times = 0;
+ int res;
+
+ if (dh->p == NULL || dh->g == NULL)
+ return 0;
+
+ while (times++ < DH_NUM_TRIES) {
+ if (!have_private_key) {
+ size_t bits = BN_num_bits(dh->p);
+
+ if (dh->priv_key)
+ BN_free(dh->priv_key);
+
+ dh->priv_key = BN_new();
+ if (dh->priv_key == NULL)
+ return 0;
+ if (!BN_rand(dh->priv_key, bits - 1, 0, 0)) {
+ BN_clear_free(dh->priv_key);
+ dh->priv_key = NULL;
+ return 0;
+ }
+ }
+ if (dh->pub_key) {
+ BN_free(dh->pub_key);
+ dh->pub_key = NULL;
+ }
+
+ if (mp_init_multi(&pub, &priv_key, &g, &p, NULL) != MP_OKAY)
+ continue;
+
+ if (BN2mpz(&priv_key, dh->priv_key) != 0)
+ continue;
+
+ if (BN2mpz(&g, dh->g) != 0)
+ continue;
+
+ if (BN2mpz(&p, dh->p) != 0)
+ continue;
+
+ res = mp_exptmod(&g, &priv_key, &p, &pub);
+
+ mp_clear_multi(&priv_key, &g, &p, NULL);
+ if (res != 0)
+ continue;
+
+ dh->pub_key = mpz2BN(&pub);
+ mp_clear(&pub);
+ if (dh->pub_key == NULL)
+ return 0;
+
+ if (DH_check_pubkey(dh, dh->pub_key, &codes) && codes == 0)
+ break;
+ if (have_private_key)
+ return 0;
+ }
+
+ if (times >= DH_NUM_TRIES) {
+ if (!have_private_key && dh->priv_key) {
+ BN_free(dh->priv_key);
+ dh->priv_key = NULL;
+ }
+ if (dh->pub_key) {
+ BN_free(dh->pub_key);
+ dh->pub_key = NULL;
+ }
+ return 0;
+ }
+
+ return 1;
+}
+
+static int
+ltm_dh_compute_key(unsigned char *shared, const BIGNUM * pub, DH *dh)
+{
+ mp_int s, priv_key, p, peer_pub;
+ int ret;
+
+ if (dh->pub_key == NULL || dh->g == NULL || dh->priv_key == NULL)
+ return -1;
+
+ if (mp_init_multi(&s, &priv_key, &p, &peer_pub, NULL) != MP_OKAY)
+ return -1;
+
+ if (BN2mpz(&p, dh->p) != 0) {
+ ret = -1;
+ goto out;
+ }
+
+ if (BN2mpz(&peer_pub, pub) != 0) {
+ ret = 1;
+ goto out;
+ }
+
+ /* check if peers pubkey is reasonable */
+ if (mp_isneg(&peer_pub)
+ || mp_cmp(&peer_pub, &p) >= 0
+ || mp_cmp_d(&peer_pub, 1) <= 0)
+ {
+ ret = -1;
+ goto out;
+ }
+
+ if (BN2mpz(&priv_key, dh->priv_key) != 0) {
+ ret = -1;
+ goto out;
+ }
+
+ ret = mp_exptmod(&peer_pub, &priv_key, &p, &s);
+ if (ret != 0) {
+ ret = -1;
+ goto out;
+ }
+
+ ret = mp_ubin_size(&s);
+ if (mp_to_ubin(&s, shared, SIZE_MAX, NULL) != MP_OKAY)
+ ret = -1;
+
+ out:
+ mp_clear_multi(&s, &priv_key, &p, &peer_pub, NULL);
+
+ return ret;
+}
+
+static int
+ltm_dh_generate_params(DH *dh, int a, int b, BN_GENCB *callback)
+{
+ /* groups should already be known, we don't care about this */
+ return 0;
+}
+
+static int
+ltm_dh_init(DH *dh)
+{
+ return 1;
+}
+
+static int
+ltm_dh_finish(DH *dh)
+{
+ return 1;
+}
+
+
+/*
+ *
+ */
+
+const DH_METHOD _hc_dh_ltm_method = {
+ "hcrypto ltm DH",
+ ltm_dh_generate_key,
+ ltm_dh_compute_key,
+ NULL,
+ ltm_dh_init,
+ ltm_dh_finish,
+ 0,
+ NULL,
+ ltm_dh_generate_params
+};
+
+/**
+ * DH implementation using libtommath.
+ *
+ * @return the DH_METHOD for the DH implementation using libtommath.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+const DH_METHOD *
+DH_ltm_method(void)
+{
+ return &_hc_dh_ltm_method;
+}
diff --git a/third_party/heimdal/lib/hcrypto/dh-tfm.c b/third_party/heimdal/lib/hcrypto/dh-tfm.c
new file mode 100644
index 0000000..dce8a9f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/dh-tfm.c
@@ -0,0 +1,248 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <dh.h>
+
+#ifdef USE_HCRYPTO_TFM
+
+#include "tfm.h"
+
+static void
+BN2mpz(fp_int *s, const BIGNUM *bn)
+{
+ size_t len;
+ void *p;
+
+ len = BN_num_bytes(bn);
+ p = malloc(len);
+ BN_bn2bin(bn, p);
+ fp_read_unsigned_bin(s, p, len);
+ free(p);
+}
+
+
+static BIGNUM *
+mpz2BN(fp_int *s)
+{
+ size_t size;
+ BIGNUM *bn;
+ void *p;
+
+ size = fp_unsigned_bin_size(s);
+ p = malloc(size);
+ if (p == NULL && size != 0)
+ return NULL;
+ fp_to_unsigned_bin(s, p);
+
+ bn = BN_bin2bn(p, size, NULL);
+ free(p);
+ return bn;
+}
+
+/*
+ *
+ */
+
+#define DH_NUM_TRIES 10
+
+static int
+tfm_dh_generate_key(DH *dh)
+{
+ fp_int pub, priv_key, g, p;
+ int have_private_key = (dh->priv_key != NULL);
+ int codes, times = 0;
+ int res;
+
+ if (dh->p == NULL || dh->g == NULL)
+ return 0;
+
+ while (times++ < DH_NUM_TRIES) {
+ if (!have_private_key) {
+ size_t bits = BN_num_bits(dh->p);
+
+ if (dh->priv_key)
+ BN_free(dh->priv_key);
+
+ dh->priv_key = BN_new();
+ if (dh->priv_key == NULL)
+ return 0;
+ if (!BN_rand(dh->priv_key, bits - 1, 0, 0)) {
+ BN_clear_free(dh->priv_key);
+ dh->priv_key = NULL;
+ return 0;
+ }
+ }
+ if (dh->pub_key)
+ BN_free(dh->pub_key);
+
+ fp_init_multi(&pub, &priv_key, &g, &p, NULL);
+
+ BN2mpz(&priv_key, dh->priv_key);
+ BN2mpz(&g, dh->g);
+ BN2mpz(&p, dh->p);
+
+ res = fp_exptmod(&g, &priv_key, &p, &pub);
+
+ fp_zero(&priv_key);
+ fp_zero(&g);
+ fp_zero(&p);
+ if (res != 0)
+ continue;
+
+ dh->pub_key = mpz2BN(&pub);
+ fp_zero(&pub);
+ if (dh->pub_key == NULL)
+ return 0;
+
+ if (DH_check_pubkey(dh, dh->pub_key, &codes) && codes == 0)
+ break;
+ if (have_private_key)
+ return 0;
+ }
+
+ if (times >= DH_NUM_TRIES) {
+ if (!have_private_key && dh->priv_key) {
+ BN_free(dh->priv_key);
+ dh->priv_key = NULL;
+ }
+ if (dh->pub_key) {
+ BN_free(dh->pub_key);
+ dh->pub_key = NULL;
+ }
+ return 0;
+ }
+
+ return 1;
+}
+
+static int
+tfm_dh_compute_key(unsigned char *shared, const BIGNUM * pub, DH *dh)
+{
+ fp_int s, priv_key, p, peer_pub;
+ size_t size = 0;
+ int ret;
+
+ if (dh->pub_key == NULL || dh->g == NULL || dh->priv_key == NULL)
+ return -1;
+
+ fp_init(&p);
+ BN2mpz(&p, dh->p);
+
+ fp_init(&peer_pub);
+ BN2mpz(&peer_pub, pub);
+
+ /* check if peers pubkey is reasonable */
+ if (fp_isneg(&peer_pub)
+ || fp_cmp(&peer_pub, &p) >= 0
+ || fp_cmp_d(&peer_pub, 1) <= 0)
+ {
+ fp_zero(&p);
+ fp_zero(&peer_pub);
+ return -1;
+ }
+
+ fp_init(&priv_key);
+ BN2mpz(&priv_key, dh->priv_key);
+
+ fp_init(&s);
+
+ ret = fp_exptmod(&peer_pub, &priv_key, &p, &s);
+
+ fp_zero(&p);
+ fp_zero(&peer_pub);
+ fp_zero(&priv_key);
+
+ if (ret != 0)
+ return -1;
+
+ size = fp_unsigned_bin_size(&s);
+ fp_to_unsigned_bin(&s, shared);
+ fp_zero(&s);
+
+ return size;
+}
+
+static int
+tfm_dh_generate_params(DH *dh, int a, int b, BN_GENCB *callback)
+{
+ /* groups should already be known, we don't care about this */
+ return 0;
+}
+
+static int
+tfm_dh_init(DH *dh)
+{
+ return 1;
+}
+
+static int
+tfm_dh_finish(DH *dh)
+{
+ return 1;
+}
+
+
+/*
+ *
+ */
+
+const DH_METHOD _hc_dh_tfm_method = {
+ "hcrypto tfm DH",
+ tfm_dh_generate_key,
+ tfm_dh_compute_key,
+ NULL,
+ tfm_dh_init,
+ tfm_dh_finish,
+ 0,
+ NULL,
+ tfm_dh_generate_params
+};
+
+/**
+ * DH implementation using tfm.
+ *
+ * @return the DH_METHOD for the DH implementation using tfm.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+const DH_METHOD *
+DH_tfm_method(void)
+{
+ return &_hc_dh_tfm_method;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/dh.c b/third_party/heimdal/lib/hcrypto/dh.c
new file mode 100644
index 0000000..5d2d214
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/dh.c
@@ -0,0 +1,551 @@
+/*
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <roken.h>
+
+#include <krb5-types.h>
+#include <rfc2459_asn1.h>
+
+#include <dh.h>
+
+/**
+ * @page page_dh DH - Diffie-Hellman key exchange
+ *
+ * Diffie-Hellman key exchange is a protocol that allows two parties
+ * to establish a shared secret key.
+ *
+ * Include and example how to use DH_new() and friends here.
+ *
+ * See the library functions here: @ref hcrypto_dh
+ */
+
+/**
+ * Create a new DH object using DH_new_method(NULL), see DH_new_method().
+ *
+ * @return a newly allocated DH object.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+DH *
+DH_new(void)
+{
+ return DH_new_method(NULL);
+}
+
+/**
+ * Create a new DH object from the given engine, if the NULL is used,
+ * the default engine is used. Free the DH object with DH_free().
+ *
+ * @param engine The engine to use to allocate the DH object.
+ *
+ * @return a newly allocated DH object.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+DH *
+DH_new_method(ENGINE *engine)
+{
+ DH *dh;
+
+ dh = calloc(1, sizeof(*dh));
+ if (dh == NULL)
+ return NULL;
+
+ dh->references = 1;
+
+ if (engine) {
+ ENGINE_up_ref(engine);
+ dh->engine = engine;
+ } else {
+ dh->engine = ENGINE_get_default_DH();
+ }
+
+ if (dh->engine) {
+ dh->meth = ENGINE_get_DH(dh->engine);
+ if (dh->meth == NULL) {
+ ENGINE_finish(dh->engine);
+ free(dh);
+ return 0;
+ }
+ }
+
+ if (dh->meth == NULL)
+ dh->meth = DH_get_default_method();
+
+ (*dh->meth->init)(dh);
+
+ return dh;
+}
+
+/**
+ * Free a DH object and release related resources, like ENGINE, that
+ * the object was using.
+ *
+ * @param dh object to be freed.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+void
+DH_free(DH *dh)
+{
+ if (dh->references <= 0)
+ abort();
+
+ if (--dh->references > 0)
+ return;
+
+ (*dh->meth->finish)(dh);
+
+ if (dh->engine)
+ ENGINE_finish(dh->engine);
+
+#define free_if(f) if (f) { BN_free(f); }
+ free_if(dh->p);
+ free_if(dh->g);
+ free_if(dh->pub_key);
+ free_if(dh->priv_key);
+ free_if(dh->q);
+ free_if(dh->j);
+ free_if(dh->counter);
+#undef free_if
+
+ memset(dh, 0, sizeof(*dh));
+ free(dh);
+}
+
+/**
+ * Add a reference to the DH object. The object should be free with
+ * DH_free() to drop the reference.
+ *
+ * @param dh the object to increase the reference count too.
+ *
+ * @return the updated reference count, can't safely be used except
+ * for debug printing.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+int
+DH_up_ref(DH *dh)
+{
+ return ++dh->references;
+}
+
+/**
+ * The maximum output size of the DH_compute_key() function.
+ *
+ * @param dh The DH object to get the size from.
+ *
+ * @return the maximum size in bytes of the out data.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+int
+DH_size(const DH *dh)
+{
+ return BN_num_bytes(dh->p);
+}
+
+/**
+ * Set the data index idx in the DH object to data.
+ *
+ * @param dh DH object.
+ * @param idx index to set the data for.
+ * @param data data to store for the index idx.
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+int
+DH_set_ex_data(DH *dh, int idx, void *data)
+{
+ dh->ex_data.sk = data;
+ return 1;
+}
+
+/**
+ * Get the data for index idx in the DH object.
+ *
+ * @param dh DH object.
+ * @param idx index to get the data for.
+ *
+ * @return the object store in index idx
+ *
+ * @ingroup hcrypto_dh
+ */
+
+void *
+DH_get_ex_data(DH *dh, int idx)
+{
+ return dh->ex_data.sk;
+}
+
+/**
+ * Generate DH parameters for the DH object give parameters.
+ *
+ * @param dh The DH object to generate parameters for.
+ * @param prime_len length of the prime
+ * @param generator generator, g
+ * @param cb Callback parameters to show progress, can be NULL.
+ *
+ * @return the maximum size in bytes of the out data.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+int
+DH_generate_parameters_ex(DH *dh, int prime_len, int generator, BN_GENCB *cb)
+{
+ if (dh->meth->generate_params)
+ return dh->meth->generate_params(dh, prime_len, generator, cb);
+ return 0;
+}
+
+/**
+ * Check that the public key is sane.
+ *
+ * @param dh the local peer DH parameters.
+ * @param pub_key the remote peer public key parameters.
+ * @param codes return that the failures of the pub_key are.
+ *
+ * @return 1 on success, 0 on failure and *codes is set the the
+ * combined fail check for the public key
+ *
+ * @ingroup hcrypto_dh
+ */
+
+int
+DH_check_pubkey(const DH *dh, const BIGNUM *pub_key, int *codes)
+{
+ BIGNUM *bn = NULL, *sum = NULL;
+ int ret = 0;
+
+ *codes = 0;
+
+ /**
+ * Checks that the function performs are:
+ * - pub_key is not negative
+ */
+
+ if (BN_is_negative(pub_key))
+ goto out;
+
+ /**
+ * - pub_key > 1 and pub_key < p - 1,
+ * to avoid small subgroups attack.
+ */
+
+ bn = BN_new();
+ if (bn == NULL)
+ goto out;
+
+ if (!BN_set_word(bn, 1))
+ goto out;
+
+ if (BN_cmp(bn, pub_key) >= 0)
+ *codes |= DH_CHECK_PUBKEY_TOO_SMALL;
+
+ sum = BN_new();
+ if (sum == NULL)
+ goto out;
+
+ BN_uadd(sum, pub_key, bn);
+
+ if (BN_cmp(sum, dh->p) >= 0)
+ *codes |= DH_CHECK_PUBKEY_TOO_LARGE;
+
+ /**
+ * - if g == 2, pub_key have more then one bit set,
+ * if bits set is 1, log_2(pub_key) is trival
+ */
+
+ if (!BN_set_word(bn, 2))
+ goto out;
+
+ if (BN_cmp(bn, dh->g) == 0) {
+ unsigned i, n = BN_num_bits(pub_key);
+ unsigned bits = 0;
+
+ for (i = 0; i < n; i++)
+ if (BN_is_bit_set(pub_key, i))
+ bits++;
+
+ if (bits < 2) {
+ *codes |= DH_CHECK_PUBKEY_TOO_SMALL;
+ goto out;
+ }
+ }
+
+ ret = 1;
+out:
+ if (bn)
+ BN_free(bn);
+ if (sum)
+ BN_free(sum);
+
+ return ret;
+}
+
+/**
+ * Generate a new DH private-public key pair. The dh parameter must be
+ * allocted first with DH_new(). dh->p and dp->g must be set.
+ *
+ * @param dh dh parameter.
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+int
+DH_generate_key(DH *dh)
+{
+ return dh->meth->generate_key(dh);
+}
+
+/**
+ * Complute the shared secret key.
+ *
+ * @param shared_key the resulting shared key, need to be at least
+ * DH_size() large.
+ * @param peer_pub_key the peer's public key.
+ * @param dh the dh key pair.
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+int
+DH_compute_key(unsigned char *shared_key,
+ const BIGNUM *peer_pub_key, DH *dh)
+{
+ int codes;
+
+ /**
+ * Checks that the pubkey passed in is valid using
+ * DH_check_pubkey().
+ */
+
+ if (!DH_check_pubkey(dh, peer_pub_key, &codes) || codes != 0)
+ return -1;
+
+ return dh->meth->compute_key(shared_key, peer_pub_key, dh);
+}
+
+/**
+ * Set a new method for the DH keypair.
+ *
+ * @param dh dh parameter.
+ * @param method the new method for the DH parameter.
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+int
+DH_set_method(DH *dh, const DH_METHOD *method)
+{
+ (*dh->meth->finish)(dh);
+ if (dh->engine) {
+ ENGINE_finish(dh->engine);
+ dh->engine = NULL;
+ }
+ dh->meth = method;
+ (*dh->meth->init)(dh);
+ return 1;
+}
+
+/*
+ *
+ */
+
+static int
+dh_null_generate_key(DH *dh)
+{
+ return 0;
+}
+
+static int
+dh_null_compute_key(unsigned char *shared,const BIGNUM *pub, DH *dh)
+{
+ return 0;
+}
+
+static int
+dh_null_init(DH *dh)
+{
+ return 1;
+}
+
+static int
+dh_null_finish(DH *dh)
+{
+ return 1;
+}
+
+static int
+dh_null_generate_params(DH *dh, int prime_num, int len, BN_GENCB *cb)
+{
+ return 0;
+}
+
+static const DH_METHOD dh_null_method = {
+ "hcrypto null DH",
+ dh_null_generate_key,
+ dh_null_compute_key,
+ NULL,
+ dh_null_init,
+ dh_null_finish,
+ 0,
+ NULL,
+ dh_null_generate_params
+};
+
+extern const DH_METHOD _hc_dh_ltm_method;
+static const DH_METHOD *dh_default_method = &_hc_dh_ltm_method;
+
+/**
+ * Return the dummy DH implementation.
+ *
+ * @return pointer to a DH_METHOD.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+const DH_METHOD *
+DH_null_method(void)
+{
+ return &dh_null_method;
+}
+
+/**
+ * Set the default DH implementation.
+ *
+ * @param meth pointer to a DH_METHOD.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+void
+DH_set_default_method(const DH_METHOD *meth)
+{
+ dh_default_method = meth;
+}
+
+/**
+ * Return the default DH implementation.
+ *
+ * @return pointer to a DH_METHOD.
+ *
+ * @ingroup hcrypto_dh
+ */
+
+const DH_METHOD *
+DH_get_default_method(void)
+{
+ return dh_default_method;
+}
+
+/*
+ *
+ */
+
+static int
+bn2heim_int(BIGNUM *bn, heim_integer *integer)
+{
+ integer->length = BN_num_bytes(bn);
+ integer->data = malloc(integer->length);
+ if (integer->data == NULL) {
+ integer->length = 0;
+ return ENOMEM;
+ }
+ BN_bn2bin(bn, integer->data);
+ integer->negative = BN_is_negative(bn);
+ return 0;
+}
+
+/**
+ *
+ */
+
+int
+i2d_DHparams(DH *dh, unsigned char **pp)
+{
+ DHParameter data;
+ size_t size;
+ int ret;
+
+ memset(&data, 0, sizeof(data));
+
+ if (bn2heim_int(dh->p, &data.prime) ||
+ bn2heim_int(dh->g, &data.base))
+ {
+ free_DHParameter(&data);
+ return -1;
+ }
+
+ if (pp == NULL) {
+ size = length_DHParameter(&data);
+ free_DHParameter(&data);
+ } else {
+ void *p;
+ size_t len;
+
+ ASN1_MALLOC_ENCODE(DHParameter, p, len, &data, &size, ret);
+ free_DHParameter(&data);
+ if (ret)
+ return -1;
+ if (len != size) {
+ abort();
+ return -1;
+ }
+
+ memcpy(*pp, p, size);
+ free(p);
+
+ *pp += size;
+ }
+
+ return size;
+}
diff --git a/third_party/heimdal/lib/hcrypto/dh.h b/third_party/heimdal/lib/hcrypto/dh.h
new file mode 100644
index 0000000..6186805
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/dh.h
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef _HEIM_DH_H
+#define _HEIM_DH_H 1
+
+/* symbol renaming */
+#define DH hc_DH
+#define DH_METHOD hc_DH_METHOD
+#define DH_null_method hc_DH_null_method
+#define DH_tfm_method hc_DH_tfm_method
+#define DH_ltm_method hc_DH_ltm_method
+#define DH_new hc_DH_new
+#define DH_new_method hc_DH_new_method
+#define DH_free hc_DH_free
+#define DH_up_ref hc_DH_up_ref
+#define DH_size hc_DH_size
+#define DH_set_default_method hc_DH_set_default_method
+#define DH_get_default_method hc_DH_get_default_method
+#define DH_set_method hc_DH_set_method
+#define DH_get_method hc_DH_get_method
+#define DH_set_ex_data hc_DH_set_ex_data
+#define DH_get_ex_data hc_DH_get_ex_data
+#define DH_generate_parameters_ex hc_DH_generate_parameters_ex
+#define DH_check_pubkey hc_DH_check_pubkey
+#define DH_generate_key hc_DH_generate_key
+#define DH_compute_key hc_DH_compute_key
+#define i2d_DHparams hc_i2d_DHparams
+
+/*
+ *
+ */
+
+typedef struct DH DH;
+typedef struct DH_METHOD DH_METHOD;
+
+#include <hcrypto/bn.h>
+#include <hcrypto/engine.h>
+
+struct DH_METHOD {
+ const char *name;
+ int (*generate_key)(DH *);
+ int (*compute_key)(unsigned char *,const BIGNUM *,DH *);
+ int (*bn_mod_exp)(const DH *, BIGNUM *, const BIGNUM *,
+ const BIGNUM *, const BIGNUM *, BN_CTX *,
+ BN_MONT_CTX *);
+ int (*init)(DH *);
+ int (*finish)(DH *);
+ int flags;
+ void *app_data;
+ int (*generate_params)(DH *, int, int, BN_GENCB *);
+};
+
+struct DH {
+ int pad;
+ int version;
+ BIGNUM *p;
+ BIGNUM *g;
+ long length;
+ BIGNUM *pub_key;
+ BIGNUM *priv_key;
+ int flags;
+ void *method_mont_p;
+ BIGNUM *q;
+ BIGNUM *j;
+ void *seed;
+ int seedlen;
+ BIGNUM *counter;
+ int references;
+ struct CRYPTO_EX_DATA {
+ void *sk;
+ int dummy;
+ } ex_data;
+ const DH_METHOD *meth;
+ ENGINE *engine;
+};
+
+/* DH_check_pubkey return codes in `codes' argument. */
+#define DH_CHECK_PUBKEY_TOO_SMALL 1
+#define DH_CHECK_PUBKEY_TOO_LARGE 2
+
+/*
+ *
+ */
+
+const DH_METHOD *DH_null_method(void);
+const DH_METHOD *DH_tfm_method(void);
+const DH_METHOD *DH_ltm_method(void);
+
+DH * DH_new(void);
+DH * DH_new_method(ENGINE *);
+void DH_free(DH *);
+int DH_up_ref(DH *);
+
+int DH_size(const DH *);
+
+
+void DH_set_default_method(const DH_METHOD *);
+const DH_METHOD *
+ DH_get_default_method(void);
+int DH_set_method(DH *, const DH_METHOD *);
+
+int DH_set_ex_data(DH *, int, void *);
+void * DH_get_ex_data(DH *, int);
+
+int DH_generate_parameters_ex(DH *, int, int, BN_GENCB *);
+int DH_check_pubkey(const DH *, const BIGNUM *, int *);
+int DH_generate_key(DH *);
+int DH_compute_key(unsigned char *,const BIGNUM *,DH *);
+
+int i2d_DHparams(DH *, unsigned char **);
+
+#endif /* _HEIM_DH_H */
+
diff --git a/third_party/heimdal/lib/hcrypto/doxygen.c b/third_party/heimdal/lib/hcrypto/doxygen.c
new file mode 100644
index 0000000..8311dbd
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/doxygen.c
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/**
+ *
+ */
+
+/*! @mainpage Heimdal crypto library
+ *
+ * @section intro Introduction
+ *
+ * Heimdal libhcrypto library is a implementation many crypto
+ * algorithms, among others: AES, SHA, DES, RSA, Camellia and many
+ * help function.
+ *
+ * hcrypto provies a OpenSSL compatible interface libcrypto interface
+ * and is licensed under a 3 clause BSD license (GPL compatible).
+ *
+ * The project web page: http://www.h5l.org/
+ *
+ * Sections of this manual:
+ *
+ * - @subpage page_evp, @ref hcrypto_evp
+ * - @subpage page_rand, @ref hcrypto_rand
+ * - @subpage page_dh, @ref hcrypto_dh
+ * - @subpage page_rsa, @ref hcrypto_rsa
+ * - @ref hcrypto_misc
+ *
+ * Older interfaces that you should not use:
+ *
+ * - @subpage page_des, @ref hcrypto_des
+ *
+ * @subsection control_functions Control functions
+ *
+ * Functions controlling general behavior, like adding algorithms, are
+ * documented in this module: @ref hcrypto_core .
+ *
+ * @subsection return_values Return values
+ *
+ * Return values are diffrent in this module to be compatible with
+ * OpenSSL interface. The diffrence is that on success 1 is returned
+ * instead of the customary 0.
+
+ * @subsection History
+ *
+ * Eric Young implemented DES in the library libdes, that grew into
+ * libcrypto in the ssleay package. ssleay went into recession and
+ * then got picked up by the OpenSSL (htp://www.openssl.org/)
+ * project.
+ *
+ * libhcrypto is an independent implementation with no code decended
+ * from ssleay/openssl. Both includes some common imported code, for
+ * example the AES implementation.
+ */
+
+/** @defgroup hcrypto_dh Diffie-Hellman functions
+ * See the @ref page_dh for description and examples.
+ */
+/** @defgroup hcrypto_rsa RSA functions
+ * See the @ref page_rsa for description and examples.
+ */
+/** @defgroup hcrypto_evp EVP generic crypto functions
+ * See the @ref page_evp for description and examples.
+ */
+/** @defgroup hcrypto_rand RAND crypto functions
+ * See the @ref page_rand for description and examples.
+ */
+/** @defgroup hcrypto_des DES crypto functions
+ * See the @ref page_des for description and examples.
+ */
+/** @defgroup hcrypto_core hcrypto function controlling behavior */
+/** @defgroup hcrypto_misc hcrypto miscellaneous functions */
diff --git a/third_party/heimdal/lib/hcrypto/dsa.c b/third_party/heimdal/lib/hcrypto/dsa.c
new file mode 100644
index 0000000..bbb3460
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/dsa.c
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <dsa.h>
+
+/*
+ *
+ */
+
+DSA *
+DSA_new(void)
+{
+ DSA *dsa = calloc(1, sizeof(*dsa));
+ dsa->meth = rk_UNCONST(DSA_get_default_method());
+ dsa->references = 1;
+ return dsa;
+}
+
+void
+DSA_free(DSA *dsa)
+{
+ if (dsa->references <= 0)
+ abort();
+
+ if (--dsa->references > 0)
+ return;
+
+ (*dsa->meth->finish)(dsa);
+
+#define free_if(f) if (f) { BN_free(f); }
+ free_if(dsa->p);
+ free_if(dsa->q);
+ free_if(dsa->g);
+ free_if(dsa->pub_key);
+ free_if(dsa->priv_key);
+ free_if(dsa->kinv);
+ free_if(dsa->r);
+#undef free_if
+
+ memset(dsa, 0, sizeof(*dsa));
+ free(dsa);
+
+}
+
+int
+DSA_up_ref(DSA *dsa)
+{
+ return ++dsa->references;
+}
+
+/*
+ *
+ */
+
+static const DSA_METHOD dsa_null_method = {
+ "hcrypto null DSA",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ 0,
+ NULL
+};
+
+const DSA_METHOD *
+DSA_null_method(void)
+{
+ return &dsa_null_method;
+}
+
+
+const DSA_METHOD *dsa_default_mech = &dsa_null_method;
+
+void
+DSA_set_default_method(const DSA_METHOD *mech)
+{
+ dsa_default_mech = mech;
+}
+
+const DSA_METHOD *
+DSA_get_default_method(void)
+{
+ return dsa_default_mech;
+}
+
+int
+DSA_verify(int type, const unsigned char * digest, int digest_len,
+ const unsigned char *sig, int sig_len, DSA *dsa)
+{
+ return -1;
+}
diff --git a/third_party/heimdal/lib/hcrypto/dsa.h b/third_party/heimdal/lib/hcrypto/dsa.h
new file mode 100644
index 0000000..a8f087f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/dsa.h
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef _HEIM_DSA_H
+#define _HEIM_DSA_H 1
+
+#include <hcrypto/bn.h>
+
+/* symbol renaming */
+#define DSA hc_DSA
+#define DSA_METHOD hc_DSA_METHOD
+#define DSA_null_method hc_DSA_null_method
+#define DSA_new hc_DSA_new
+#define DSA_free hc_DSA_free
+#define DSA_up_ref hc_DSA_up_ref
+#define DSA_set_default_method hc_DSA_set_default_method
+#define DSA_get_default_method hc_DSA_get_default_method
+#define DSA_set_method hc_DSA_set_method
+#define DSA_get_method hc_DSA_get_method
+#define DSA_set_app_data hc_DSA_set_app_data
+#define DSA_get_app_data hc_DSA_get_app_data
+#define DSA_size hc_DSA_size
+#define DSA_verify hc_DSA_verify
+
+/*
+ *
+ */
+
+
+typedef struct DSA DSA;
+typedef struct DSA_METHOD DSA_METHOD;
+typedef struct DSA_SIG DSA_SIG;
+
+struct DSA_SIG {
+ BIGNUM *r;
+ BIGNUM *s;
+};
+
+struct DSA_METHOD {
+ const char *name;
+ DSA_SIG * (*dsa_do_sign)(const unsigned char *, int, DSA *);
+ int (*dsa_sign_setup)(DSA *, BN_CTX *, BIGNUM **, BIGNUM **);
+ int (*dsa_do_verify)(const unsigned char *, int, DSA_SIG *, DSA *);
+ int (*dsa_mod_exp)(DSA *, BIGNUM *, BIGNUM *, BIGNUM *,
+ BIGNUM *, BIGNUM *, BIGNUM *, BN_CTX *,
+ BN_MONT_CTX *);
+ int (*bn_mod_exp)(DSA *, BIGNUM *, BIGNUM *, const BIGNUM *,
+ const BIGNUM *, BN_CTX *,
+ BN_MONT_CTX *);
+ int (*init)(DSA *);
+ int (*finish)(DSA *);
+ int flags;
+ void *app_data;
+};
+
+struct DSA {
+ int pad;
+ long version;
+ int write_params;
+ BIGNUM *p;
+ BIGNUM *q;
+ BIGNUM *g;
+
+ BIGNUM *pub_key;
+ BIGNUM *priv_key;
+
+ BIGNUM *kinv;
+ BIGNUM *r;
+ int flags;
+ void *method_mont_p;
+ int references;
+ struct dsa_CRYPTO_EX_DATA {
+ void *sk;
+ int dummy;
+ } ex_data;
+ const DSA_METHOD *meth;
+ void *engine;
+};
+
+/*
+ *
+ */
+
+const DSA_METHOD *DSA_null_method(void);
+
+/*
+ *
+ */
+
+DSA * DSA_new(void);
+void DSA_free(DSA *);
+int DSA_up_ref(DSA *);
+
+void DSA_set_default_method(const DSA_METHOD *);
+const DSA_METHOD * DSA_get_default_method(void);
+
+const DSA_METHOD * DSA_get_method(const DSA *);
+int DSA_set_method(DSA *, const DSA_METHOD *);
+
+void DSA_set_app_data(DSA *, void *arg);
+void * DSA_get_app_data(DSA *);
+
+int DSA_size(const DSA *);
+
+int DSA_verify(int, const unsigned char *, int,
+ const unsigned char *, int, DSA *);
+
+#endif /* _HEIM_DSA_H */
diff --git a/third_party/heimdal/lib/hcrypto/ec.c b/third_party/heimdal/lib/hcrypto/ec.c
new file mode 100644
index 0000000..5a5c3c7
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/ec.c
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include "ec.h"
+
+struct EC_POINT {
+ int inf;
+ mp_int x;
+ mp_int y;
+ mp_int z;
+};
+
+struct EC_GROUP {
+ size_t size;
+ mp_int prime;
+ mp_int order;
+ mp_int Gx;
+ mp_int Gy;
+};
+
+struct EC_KEY {
+ int type;
+ EC_GROUP *group;
+ EC_POINT *pubkey;
+ mp_int privkey;
+};
+
+
+unsigned long
+EC_GROUP_get_degree(EC_GROUP *)
+{
+}
+
+EC_GROUP *
+EC_KEY_get0_group(EC_KEY *)
+{
+}
+
+int
+EC_GROUP_get_order(EC_GROUP *, BIGNUM *, BN_CTX *)
+{
+}
+
+EC_KEY *
+o2i_ECPublicKey(EC_KEY **key, unsigned char **, size_t)
+{
+}
+
+void
+EC_KEY_free(EC_KEY *)
+{
+
+}
+
+EC_GROUP *
+EC_GROUP_new_by_curve_name(int nid)
+{
+}
+
+EC_KEY *
+EC_KEY_new_by_curve_name(EC_GROUP_ID nid)
+{
+ EC_KEY *key;
+
+ key = calloc(1, sizeof(*key));
+ return key;
+}
+
+void
+EC_POINT_free(EC_POINT *p)
+{
+ mp_clear_multi(&p->x, p->y, p->z, NULL);
+ free(p);
+}
+
+static int
+ec_point_mul(EC_POINT *res, const EC_GROUP *group, const mp_int *point)
+{
+}
+
+EC_POINT *
+EC_POINT_new(void)
+{
+ EC_POINT *p;
+
+ p = calloc(1, sizeof(*p));
+
+ if (mp_init_multi(&p->x, &p->y, &p->z, NULL) != 0) {
+ EC_POINT_free(p);
+ return NULL;
+ }
+
+ return p;
+}
+
+int
+EC_KEY_generate_key(EC_KEY *key)
+{
+ int ret = 0;
+
+ if (key->group == NULL)
+ return 0;
+
+ do {
+ random(key->privkey, key->group->size);
+ } while(mp_cmp(key->privkey, key->group->order) >= 0);
+
+ if (key->pubkey == NULL)
+ key->pubkey = EC_POINT_new();
+
+ if (ec_point_mul(&key->pubkey, key->group, key->privkey) != 1)
+ goto error;
+
+ ret = 1;
+ error:
+ ECPOINT_free(&base);
+
+ return ret;
+}
+
+void
+EC_KEY_set_group(EC_KEY *, EC_GROUP *)
+{
+
+}
+
+void
+EC_GROUP_free(EC_GROUP *)
+{
+}
+
+int
+EC_KEY_check_key(const EC_KEY *)
+{
+}
+
+const BIGNUM *
+EC_KEY_get0_private_key(const EC_KEY *key)
+{
+}
+
+int
+EC_KEY_set_private_key(EC_KEY *key, const BIGNUM *bn)
+{
+}
diff --git a/third_party/heimdal/lib/hcrypto/ec.h b/third_party/heimdal/lib/hcrypto/ec.h
new file mode 100644
index 0000000..8fa4d11
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/ec.h
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2009-2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef HEIM_EC_H
+#define HEIM_EC_H 1
+
+#define EC_KEY hc_EC_KEY
+#define EC_GROUP hc_EC_GROUP
+#define EC_GROUP_ID hc_EC_GROUP_ID
+#define EC_GROUP_ID_s hc_EC_GROUP_ID_s
+#define EC_GROUP_get_degree hc_EC_GROUP_get_degree
+#define EC_KEY_get0_group hc_EC_KEY_get0_group
+#define EC_GROUP_get_order hc_EC_GROUP_get_order
+#define o2i_ECPublicKey hc_o2i_ECPublicKey
+#define EC_KEY_free hc_EC_KEY_free
+#define EC_GROUP_new_by_curve_name hc_EC_GROUP_new_by_curve_name
+#define EC_KEY_set_group hc_EC_KEY_set_group
+#define EC_GROUP_free hc_EC_GROUP_free
+#define EC_KEY_check_key hc_EC_KEY_check_key
+#define EC_KEY_get0_private_key hc_EC_KEY_get0_private_key
+#define EC_KEY_set_private_key hc_EC_KEY_set_private_key
+
+#include <hcrypto/bn.h>
+#include <hcrypto/engine.h>
+
+typedef struct EC_KEY EC_KEY;
+typedef struct EC_GROUP EC_GROUP;
+typedef struct EC_GROUP_ID_s *EC_GROUP_ID;
+
+unsigned long
+EC_GROUP_get_degree(EC_GROUP *);
+
+EC_GROUP *
+EC_KEY_get0_group(EC_KEY *);
+
+int
+EC_GROUP_get_order(EC_GROUP *, BIGNUM *, BN_CTX *);
+
+EC_KEY *
+o2i_ECPublicKey(EC_KEY **key, unsigned char **, size_t);
+
+EC_KEY *
+EC_KEY_new_by_curve_name(EC_GROUP_ID);
+
+int
+EC_KEY_generate_key(EC_KEY *);
+
+void
+EC_KEY_free(EC_KEY *);
+
+EC_GROUP *
+EC_GROUP_new_by_curve_name(int nid);
+
+void
+EC_KEY_set_group(EC_KEY *, EC_GROUP *);
+
+void
+EC_GROUP_free(EC_GROUP *);
+
+int
+EC_KEY_check_key(const EC_KEY *);
+
+const BIGNUM *EC_KEY_get0_private_key(const EC_KEY *);
+
+int EC_KEY_set_private_key(EC_KEY *, const BIGNUM *);
+
+#endif /* HEIM_EC_H */
diff --git a/third_party/heimdal/lib/hcrypto/ecdh.h b/third_party/heimdal/lib/hcrypto/ecdh.h
new file mode 100644
index 0000000..f224afd
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/ecdh.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef HEIM_ECDH_H
+#define HEIM_ECDH_H 1
+
+#define ECDH_compute_key hc_ECDH_compute_key
+
+#include <hcrypto/ec.h>
+
+int
+ECDH_compute_key(void *, size_t,
+ const EC_KEY *, const EC_KEY *,
+ void *(*KDF)(const void *, size_t, void *, size_t *));
+
+
+#endif /* HEIM_ECDH_H */
diff --git a/third_party/heimdal/lib/hcrypto/ecdsa.h b/third_party/heimdal/lib/hcrypto/ecdsa.h
new file mode 100644
index 0000000..ffae17b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/ecdsa.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef HEIM_ECDSA_H
+#define HEIM_ECDSA_H 1
+
+#define ECDSA_verify hc_ECDSA_verify
+#define ECDSA_sign hc_ECDSA_sign
+#define ECDSA_size hc_ECDSA_size
+
+#include <hcrypto/ec.h>
+
+int ECDSA_verify(int, const unsigned char *, unsigned int,
+ unsigned char *, unsigned int, EC_KEY *);
+
+int ECDSA_sign(int, const unsigned char *, unsigned int,
+ unsigned char *, unsigned int *, EC_KEY *);
+
+int ECDSA_size(EC_KEY *);
+
+
+#endif /* HEIM_ECDSA_H */
diff --git a/third_party/heimdal/lib/hcrypto/engine.c b/third_party/heimdal/lib/hcrypto/engine.c
new file mode 100644
index 0000000..3dae960
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/engine.c
@@ -0,0 +1,396 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <engine.h>
+
+struct hc_engine {
+ int references;
+ char *name;
+ char *id;
+ void (*destroy)(ENGINE *);
+ const RSA_METHOD *rsa;
+ const DH_METHOD *dh;
+ const RAND_METHOD *rand;
+ void *dso_handle;
+};
+
+ENGINE *
+ENGINE_new(void)
+{
+ ENGINE *engine;
+
+ engine = calloc(1, sizeof(*engine));
+ if (engine == NULL)
+ return NULL;
+ engine->references = 1;
+ engine->destroy = 0;
+ engine->dh = 0;
+ engine->rand = 0;
+ engine->dso_handle = 0;
+
+ return engine;
+}
+
+int
+ENGINE_free(ENGINE *engine)
+{
+ return ENGINE_finish(engine);
+}
+
+int
+ENGINE_finish(ENGINE *engine)
+{
+ if (engine->references-- <= 0)
+ abort();
+ if (engine->references > 0)
+ return 1;
+
+ if (engine->name)
+ free(engine->name);
+ if (engine->id)
+ free(engine->id);
+ if(engine->destroy)
+ (*engine->destroy)(engine);
+ if (engine->dso_handle)
+ dlclose(engine->dso_handle);
+
+ memset(engine, 0, sizeof(*engine));
+ engine->references = -1;
+
+
+ free(engine);
+ return 1;
+}
+
+int
+ENGINE_up_ref(ENGINE *engine)
+{
+ if (engine->references < 0)
+ abort();
+ engine->references++;
+ return 1;
+}
+
+int
+ENGINE_set_id(ENGINE *engine, const char *id)
+{
+ engine->id = strdup(id);
+ return (engine->id == NULL) ? 0 : 1;
+}
+
+int
+ENGINE_set_name(ENGINE *engine, const char *name)
+{
+ engine->name = strdup(name);
+ return (engine->name == NULL) ? 0 : 1;
+}
+
+int
+ENGINE_set_RSA(ENGINE *engine, const RSA_METHOD *method)
+{
+ engine->rsa = method;
+ return 1;
+}
+
+int
+ENGINE_set_DH(ENGINE *engine, const DH_METHOD *method)
+{
+ engine->dh = method;
+ return 1;
+}
+
+int
+ENGINE_set_destroy_function(ENGINE *e, void (*destroy)(ENGINE *))
+{
+ e->destroy = destroy;
+ return 1;
+}
+
+const char *
+ENGINE_get_id(const ENGINE *engine)
+{
+ return engine->id;
+}
+
+const char *
+ENGINE_get_name(const ENGINE *engine)
+{
+ return engine->name;
+}
+
+const RSA_METHOD *
+ENGINE_get_RSA(const ENGINE *engine)
+{
+ return engine->rsa;
+}
+
+const DH_METHOD *
+ENGINE_get_DH(const ENGINE *engine)
+{
+ return engine->dh;
+}
+
+const RAND_METHOD *
+ENGINE_get_RAND(const ENGINE *engine)
+{
+ return engine->rand;
+}
+
+/*
+ *
+ */
+
+#define SG_default_engine(type) \
+static ENGINE *type##_engine; \
+int \
+ENGINE_set_default_##type(ENGINE *engine) \
+{ \
+ if (type##_engine) \
+ ENGINE_finish(type##_engine); \
+ type##_engine = engine; \
+ if (type##_engine) \
+ ENGINE_up_ref(type##_engine); \
+ return 1; \
+} \
+ENGINE * \
+ENGINE_get_default_##type(void) \
+{ \
+ if (type##_engine) \
+ ENGINE_up_ref(type##_engine); \
+ return type##_engine; \
+}
+
+SG_default_engine(RSA)
+SG_default_engine(DH)
+
+#undef SG_default_engine
+
+/*
+ *
+ */
+
+static ENGINE **engines;
+static unsigned int num_engines;
+
+static int
+add_engine(ENGINE *engine)
+{
+ ENGINE **d, *dup;
+
+ dup = ENGINE_by_id(engine->id);
+ if (dup)
+ return 0;
+
+ d = realloc(engines, (num_engines + 1) * sizeof(*engines));
+ if (d == NULL)
+ return 1;
+ engines = d;
+ engines[num_engines++] = engine;
+
+ return 1;
+}
+
+void
+ENGINE_load_builtin_engines(void)
+{
+ ENGINE *engine;
+ int ret;
+
+ engine = ENGINE_new();
+ if (engine == NULL)
+ return;
+
+ ENGINE_set_id(engine, "builtin");
+ ENGINE_set_name(engine,
+ "Heimdal crypto builtin (ltm) engine version " PACKAGE_VERSION);
+ ENGINE_set_RSA(engine, RSA_ltm_method());
+ ENGINE_set_DH(engine, DH_ltm_method());
+
+ ret = add_engine(engine);
+ if (ret != 1)
+ ENGINE_finish(engine);
+
+#ifdef USE_HCRYPTO_TFM
+ /*
+ * TFM
+ */
+
+ engine = ENGINE_new();
+ if (engine == NULL)
+ return;
+
+ ENGINE_set_id(engine, "tfm");
+ ENGINE_set_name(engine,
+ "Heimdal crypto tfm engine version " PACKAGE_VERSION);
+ ENGINE_set_RSA(engine, RSA_tfm_method());
+ ENGINE_set_DH(engine, DH_tfm_method());
+
+ ret = add_engine(engine);
+ if (ret != 1)
+ ENGINE_finish(engine);
+#endif /* USE_HCRYPTO_TFM */
+
+#ifdef USE_HCRYPTO_LTM
+ /*
+ * ltm
+ */
+
+ engine = ENGINE_new();
+ if (engine == NULL)
+ return;
+
+ ENGINE_set_id(engine, "ltm");
+ ENGINE_set_name(engine,
+ "Heimdal crypto ltm engine version " PACKAGE_VERSION);
+ ENGINE_set_RSA(engine, RSA_ltm_method());
+ ENGINE_set_DH(engine, DH_ltm_method());
+
+ ret = add_engine(engine);
+ if (ret != 1)
+ ENGINE_finish(engine);
+#endif
+
+#ifdef HAVE_GMP
+ /*
+ * gmp
+ */
+
+ engine = ENGINE_new();
+ if (engine == NULL)
+ return;
+
+ ENGINE_set_id(engine, "gmp");
+ ENGINE_set_name(engine,
+ "Heimdal crypto gmp engine version " PACKAGE_VERSION);
+ ENGINE_set_RSA(engine, RSA_gmp_method());
+
+ ret = add_engine(engine);
+ if (ret != 1)
+ ENGINE_finish(engine);
+#endif
+}
+
+ENGINE *
+ENGINE_by_dso(const char *path, const char *id)
+{
+#ifdef HAVE_DLOPEN
+ ENGINE *engine;
+ int ret;
+
+ engine = calloc(1, sizeof(*engine));
+ if (engine == NULL)
+ return NULL;
+ engine->references = 0; /* ref will be added below */
+ engine->destroy = 0;
+ engine->dh = 0;
+ engine->rand = 0;
+ engine->dso_handle = dlopen(path, RTLD_NOW | RTLD_LOCAL | RTLD_GROUP);
+ if (engine->dso_handle == NULL) {
+ /* printf("error: %s\n", dlerror()); */
+ free(engine);
+ return NULL;
+ }
+
+ {
+ unsigned long version;
+ openssl_v_check v_check;
+
+ v_check = (openssl_v_check)dlsym(engine->dso_handle, "v_check");
+ if (v_check == NULL) {
+ dlclose(engine->dso_handle);
+ free(engine);
+ return NULL;
+ }
+
+ version = (*v_check)(OPENSSL_DYNAMIC_VERSION);
+ if (version == 0) {
+ dlclose(engine->dso_handle);
+ free(engine);
+ return NULL;
+ }
+ }
+
+ {
+ openssl_bind_engine bind_engine;
+
+ bind_engine =
+ (openssl_bind_engine)dlsym(engine->dso_handle, "bind_engine");
+ if (bind_engine == NULL) {
+ dlclose(engine->dso_handle);
+ free(engine);
+ return NULL;
+ }
+
+ ret = (*bind_engine)(engine, id, NULL); /* XXX fix third arg */
+ if (ret != 1) {
+ dlclose(engine->dso_handle);
+ free(engine);
+ return NULL;
+ }
+ }
+
+ ENGINE_up_ref(engine);
+
+ ret = add_engine(engine);
+ if (ret != 1) {
+ ENGINE_finish(engine);
+ return NULL;
+ }
+
+ return engine;
+#else
+ return NULL;
+#endif
+}
+
+ENGINE *
+ENGINE_by_id(const char *id)
+{
+ int i;
+
+ for (i = 0; i < num_engines; i++) {
+ if (strcmp(id, engines[i]->id) == 0) {
+ ENGINE_up_ref(engines[i]);
+ return engines[i];
+ }
+ }
+ return NULL;
+}
+
+void
+ENGINE_add_conf_module(void)
+{
+}
diff --git a/third_party/heimdal/lib/hcrypto/engine.h b/third_party/heimdal/lib/hcrypto/engine.h
new file mode 100644
index 0000000..e6fc5b9
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/engine.h
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2006-2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef _HEIM_ENGINE_H
+#define _HEIM_ENGINE_H 1
+
+/* symbol renaming */
+#define ENGINE_add_conf_module hc_ENGINE_add_conf_module
+#define ENGINE_by_dso hc_ENGINE_by_dso
+#define ENGINE_by_id hc_ENGINE_by_id
+#define ENGINE_finish hc_ENGINE_finish
+#define ENGINE_get_DH hc_ENGINE_get_DH
+#define ENGINE_get_RSA hc_ENGINE_get_RSA
+#define ENGINE_get_RAND hc_ENGINE_get_RAND
+#define ENGINE_get_id hc_ENGINE_get_id
+#define ENGINE_get_name hc_ENGINE_get_name
+#define ENGINE_load_builtin_engines hc_ENGINE_load_builtin_engines
+#define ENGINE_set_DH hc_ENGINE_set_DH
+#define ENGINE_set_RSA hc_ENGINE_set_RSA
+#define ENGINE_set_id hc_ENGINE_set_id
+#define ENGINE_set_name hc_ENGINE_set_name
+#define ENGINE_set_destroy_function hc_ENGINE_set_destroy_function
+#define ENGINE_new hc_ENGINE_new
+#define ENGINE_free hc_ENGINE_free
+#define ENGINE_up_ref hc_ENGINE_up_ref
+#define ENGINE_get_default_DH hc_ENGINE_get_default_DH
+#define ENGINE_get_default_RSA hc_ENGINE_get_default_RSA
+#define ENGINE_set_default_DH hc_ENGINE_set_default_DH
+#define ENGINE_set_default_RSA hc_ENGINE_set_default_RSA
+
+#define ENGINE hc_ENGINE
+
+/*
+ *
+ */
+
+typedef struct hc_engine ENGINE;
+
+#define NID_md2 0
+#define NID_md4 1
+#define NID_md5 2
+#define NID_sha1 4
+#define NID_sha256 5
+
+/*
+ *
+ */
+
+#include <hcrypto/rsa.h>
+#include <hcrypto/dsa.h>
+#include <hcrypto/dh.h>
+#include <hcrypto/rand.h>
+
+#define OPENSSL_DYNAMIC_VERSION (unsigned long)0x00020000
+
+typedef int (*openssl_bind_engine)(ENGINE *, const char *, const void *);
+typedef unsigned long (*openssl_v_check)(unsigned long);
+
+ENGINE *
+ ENGINE_new(void);
+int ENGINE_free(ENGINE *);
+void ENGINE_add_conf_module(void);
+void ENGINE_load_builtin_engines(void);
+ENGINE *ENGINE_by_id(const char *);
+ENGINE *ENGINE_by_dso(const char *, const char *);
+int ENGINE_finish(ENGINE *);
+int ENGINE_up_ref(ENGINE *);
+int ENGINE_set_id(ENGINE *, const char *);
+int ENGINE_set_name(ENGINE *, const char *);
+int ENGINE_set_RSA(ENGINE *, const RSA_METHOD *);
+int ENGINE_set_DH(ENGINE *, const DH_METHOD *);
+int ENGINE_set_destroy_function(ENGINE *, void (*)(ENGINE *));
+
+const char * ENGINE_get_id(const ENGINE *);
+const char * ENGINE_get_name(const ENGINE *);
+const RSA_METHOD * ENGINE_get_RSA(const ENGINE *);
+const DH_METHOD * ENGINE_get_DH(const ENGINE *);
+const RAND_METHOD * ENGINE_get_RAND(const ENGINE *);
+
+int ENGINE_set_default_RSA(ENGINE *);
+ENGINE * ENGINE_get_default_RSA(void);
+int ENGINE_set_default_DH(ENGINE *);
+ENGINE * ENGINE_get_default_DH(void);
+
+
+#endif /* _HEIM_ENGINE_H */
diff --git a/third_party/heimdal/lib/hcrypto/evp-cc.c b/third_party/heimdal/lib/hcrypto/evp-cc.c
new file mode 100644
index 0000000..4a377f1
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp-cc.c
@@ -0,0 +1,943 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* CommonCrypto provider */
+
+#ifdef __APPLE__
+
+#include <config.h>
+#include <roken.h>
+
+#include <assert.h>
+
+#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H
+#include <CommonCrypto/CommonDigest.h>
+#endif
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+#include <CommonCrypto/CommonCryptor.h>
+#endif
+
+#include <evp.h>
+#include <evp-hcrypto.h>
+#include <evp-cc.h>
+
+/*
+ *
+ */
+
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+
+struct cc_key {
+ CCCryptorRef href;
+};
+
+static int
+cc_do_cipher(EVP_CIPHER_CTX *ctx,
+ unsigned char *out,
+ const unsigned char *in,
+ unsigned int size)
+{
+ struct cc_key *cc = ctx->cipher_data;
+ CCCryptorStatus ret;
+ size_t moved;
+
+ memcpy(out, in, size);
+
+ ret = CCCryptorUpdate(cc->href, in, size, out, size, &moved);
+ if (ret)
+ return 0;
+
+ if (moved != size)
+ return 0;
+
+ return 1;
+}
+
+static int
+cc_cleanup(EVP_CIPHER_CTX *ctx)
+{
+ struct cc_key *cc = ctx->cipher_data;
+ if (cc->href)
+ CCCryptorRelease(cc->href);
+ return 1;
+}
+
+static int
+init_cc_key(int encp, unsigned long flags,
+ CCAlgorithm alg, const void *key, size_t keylen,
+ const void *iv, CCCryptorRef *ref)
+{
+ CCOperation op = encp ? kCCEncrypt : kCCDecrypt;
+ CCMode mode;
+ CCModeOptions options = 0;
+ CCCryptorStatus ret;
+
+ if (*ref) {
+ if (key == NULL && iv) {
+ CCCryptorReset(*ref, iv);
+ return 1;
+ }
+ CCCryptorRelease(*ref);
+ }
+
+ if (key) {
+ switch (flags & EVP_CIPH_MODE) {
+ case EVP_CIPH_STREAM_CIPHER:
+ mode = kCCModeRC4;
+ break;
+ case EVP_CIPH_CFB8_MODE:
+ mode = kCCModeCFB8;
+ break;
+ default:
+ mode = kCCModeCBC;
+ break;
+ }
+
+ ret = CCCryptorCreateWithMode(op, mode, alg, ccNoPadding,
+ iv, key, keylen, NULL, 0, 0,
+ options, ref);
+ if (ret)
+ return 0;
+ }
+
+ return 1;
+}
+
+static int
+cc_des_ede3_cbc_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char * key,
+ const unsigned char * iv,
+ int encp)
+{
+ struct cc_key *cc = ctx->cipher_data;
+ return init_cc_key(encp, ctx->cipher->flags, kCCAlgorithm3DES,
+ key, kCCKeySize3DES, iv, &cc->href);
+}
+
+#endif /* HAVE_COMMONCRYPTO_COMMONCRYPTOR_H */
+
+/**
+ * The triple DES cipher type (Apple CommonCrypto provider)
+ *
+ * @return the DES-EDE3-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_cc_des_ede3_cbc(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+ static const EVP_CIPHER des_ede3_cbc = {
+ 0,
+ 8,
+ 24,
+ 8,
+ EVP_CIPH_CBC_MODE|EVP_CIPH_ALWAYS_CALL_INIT,
+ cc_des_ede3_cbc_init,
+ cc_do_cipher,
+ cc_cleanup,
+ sizeof(struct cc_key),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &des_ede3_cbc;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_des_ede3_cbc();
+#else
+ return NULL;
+#endif
+}
+
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+/*
+ *
+ */
+
+static int
+cc_des_cbc_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char * key,
+ const unsigned char * iv,
+ int encp)
+{
+ struct cc_key *cc = ctx->cipher_data;
+ return init_cc_key(encp, ctx->cipher->flags, kCCAlgorithmDES,
+ key, kCCBlockSizeDES, iv, &cc->href);
+}
+#endif
+
+/**
+ * The DES cipher type (Apple CommonCrypto provider)
+ *
+ * @return the DES-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_cc_des_cbc(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+ static const EVP_CIPHER des_ede3_cbc = {
+ 0,
+ kCCBlockSizeDES,
+ kCCBlockSizeDES,
+ kCCBlockSizeDES,
+ EVP_CIPH_CBC_MODE|EVP_CIPH_ALWAYS_CALL_INIT,
+ cc_des_cbc_init,
+ cc_do_cipher,
+ cc_cleanup,
+ sizeof(struct cc_key),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &des_ede3_cbc;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_des_cbc();
+#else
+ return NULL;
+#endif
+}
+
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+/*
+ *
+ */
+
+static int
+cc_aes_cbc_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char * key,
+ const unsigned char * iv,
+ int encp)
+{
+ struct cc_key *cc = ctx->cipher_data;
+ return init_cc_key(encp, ctx->cipher->flags, kCCAlgorithmAES128,
+ key, ctx->cipher->key_len, iv, &cc->href);
+}
+#endif
+
+/**
+ * The AES-128 cipher type (Apple CommonCrypto provider)
+ *
+ * @return the AES-128-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_cc_aes_128_cbc(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+ static const EVP_CIPHER c = {
+ 0,
+ kCCBlockSizeAES128,
+ kCCKeySizeAES128,
+ kCCBlockSizeAES128,
+ EVP_CIPH_CBC_MODE|EVP_CIPH_ALWAYS_CALL_INIT,
+ cc_aes_cbc_init,
+ cc_do_cipher,
+ cc_cleanup,
+ sizeof(struct cc_key),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &c;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_aes_128_cbc();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The AES-192 cipher type (Apple CommonCrypto provider)
+ *
+ * @return the AES-192-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_cc_aes_192_cbc(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+ static const EVP_CIPHER c = {
+ 0,
+ kCCBlockSizeAES128,
+ kCCKeySizeAES192,
+ kCCBlockSizeAES128,
+ EVP_CIPH_CBC_MODE|EVP_CIPH_ALWAYS_CALL_INIT,
+ cc_aes_cbc_init,
+ cc_do_cipher,
+ cc_cleanup,
+ sizeof(struct cc_key),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &c;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_aes_192_cbc();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The AES-256 cipher type (Apple CommonCrypto provider)
+ *
+ * @return the AES-256-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_cc_aes_256_cbc(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+ static const EVP_CIPHER c = {
+ 0,
+ kCCBlockSizeAES128,
+ kCCKeySizeAES256,
+ kCCBlockSizeAES128,
+ EVP_CIPH_CBC_MODE|EVP_CIPH_ALWAYS_CALL_INIT,
+ cc_aes_cbc_init,
+ cc_do_cipher,
+ cc_cleanup,
+ sizeof(struct cc_key),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &c;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_aes_256_cbc();
+#else
+ return NULL;
+#endif
+}
+
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+/*
+ *
+ */
+
+static int
+cc_aes_cfb8_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char * key,
+ const unsigned char * iv,
+ int encp)
+{
+ struct cc_key *cc = ctx->cipher_data;
+ return init_cc_key(encp, ctx->cipher->flags, kCCAlgorithmAES128,
+ key, ctx->cipher->key_len, NULL, &cc->href);
+}
+#endif
+
+/**
+ * The AES-128 CFB8 cipher type (Apple CommonCrypto provider)
+ *
+ * @return the AES-128-CFB8 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_cc_aes_128_cfb8(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+ static const EVP_CIPHER c = {
+ 0,
+ 1,
+ kCCKeySizeAES128,
+ kCCBlockSizeAES128,
+ EVP_CIPH_CFB8_MODE|EVP_CIPH_ALWAYS_CALL_INIT,
+ cc_aes_cfb8_init,
+ cc_do_cipher,
+ cc_cleanup,
+ sizeof(struct cc_key),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &c;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_aes_128_cfb8();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The AES-192 CFB8 cipher type (Apple CommonCrypto provider)
+ *
+ * @return the AES-192-CFB8 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_cc_aes_192_cfb8(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+ static const EVP_CIPHER c = {
+ 0,
+ 1,
+ kCCKeySizeAES192,
+ kCCBlockSizeAES128,
+ EVP_CIPH_CFB8_MODE|EVP_CIPH_ALWAYS_CALL_INIT,
+ cc_aes_cfb8_init,
+ cc_do_cipher,
+ cc_cleanup,
+ sizeof(struct cc_key),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &c;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_aes_192_cfb8();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The AES-256 CFB8 cipher type (Apple CommonCrypto provider)
+ *
+ * @return the AES-256-CFB8 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_cc_aes_256_cfb8(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+ static const EVP_CIPHER c = {
+ 0,
+ kCCBlockSizeAES128,
+ kCCKeySizeAES256,
+ kCCBlockSizeAES128,
+ EVP_CIPH_CFB8_MODE|EVP_CIPH_ALWAYS_CALL_INIT,
+ cc_aes_cfb8_init,
+ cc_do_cipher,
+ cc_cleanup,
+ sizeof(struct cc_key),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &c;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_aes_256_cfb8();
+#else
+ return NULL;
+#endif
+}
+
+/*
+ *
+ */
+
+#ifdef COMMONCRYPTO_SUPPORTS_RC2
+static int
+cc_rc2_cbc_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char * key,
+ const unsigned char * iv,
+ int encp)
+{
+ struct cc_key *cc = ctx->cipher_data;
+ return init_cc_key(encp, ctx->cipher->flags, kCCAlgorithmRC2,
+ key, ctx->cipher->key_len, iv, &cc->href);
+}
+#endif
+
+/**
+ * The RC2 cipher type - common crypto
+ *
+ * @return the RC2 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+
+const EVP_CIPHER *
+EVP_cc_rc2_cbc(void)
+{
+#ifdef COMMONCRYPTO_SUPPORTS_RC2
+ static const EVP_CIPHER rc2_cbc = {
+ 0,
+ kCCBlockSizeRC2,
+ 16,
+ kCCBlockSizeRC2,
+ EVP_CIPH_CBC_MODE|EVP_CIPH_ALWAYS_CALL_INIT,
+ cc_rc2_cbc_init,
+ cc_do_cipher,
+ cc_cleanup,
+ sizeof(struct cc_key),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &rc2_cbc;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_rc2_cbc();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The RC2-40 cipher type - common crypto
+ *
+ * @return the RC2-40 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+
+const EVP_CIPHER *
+EVP_cc_rc2_40_cbc(void)
+{
+#ifdef COMMONCRYPTO_SUPPORTS_RC2
+ static const EVP_CIPHER rc2_40_cbc = {
+ 0,
+ kCCBlockSizeRC2,
+ 5,
+ kCCBlockSizeRC2,
+ EVP_CIPH_CBC_MODE|EVP_CIPH_ALWAYS_CALL_INIT,
+ cc_rc2_cbc_init,
+ cc_do_cipher,
+ cc_cleanup,
+ sizeof(struct cc_key),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &rc2_40_cbc;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_rc2_40_cbc();
+#else
+ return NULL;
+#endif
+}
+
+
+/**
+ * The RC2-64 cipher type - common crypto
+ *
+ * @return the RC2-64 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+
+const EVP_CIPHER *
+EVP_cc_rc2_64_cbc(void)
+{
+#ifdef COMMONCRYPTO_SUPPORTS_RC2
+ static const EVP_CIPHER rc2_64_cbc = {
+ 0,
+ kCCBlockSizeRC2,
+ 8,
+ kCCBlockSizeRC2,
+ EVP_CIPH_CBC_MODE|EVP_CIPH_ALWAYS_CALL_INIT,
+ cc_rc2_cbc_init,
+ cc_do_cipher,
+ cc_cleanup,
+ sizeof(struct cc_key),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &rc2_64_cbc;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_rc2_64_cbc();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The CommonCrypto md2 provider
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_cc_md2(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H
+ static const struct hc_evp_md md2 = {
+ CC_MD2_DIGEST_LENGTH,
+ CC_MD2_BLOCK_BYTES,
+ sizeof(CC_MD2_CTX),
+ (hc_evp_md_init)CC_MD2_Init,
+ (hc_evp_md_update)CC_MD2_Update,
+ (hc_evp_md_final)CC_MD2_Final,
+ (hc_evp_md_cleanup)NULL
+ };
+ return &md2;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_md2();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The CommonCrypto md4 provider
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_cc_md4(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H
+ static const struct hc_evp_md md4 = {
+ CC_MD4_DIGEST_LENGTH,
+ CC_MD4_BLOCK_BYTES,
+ sizeof(CC_MD4_CTX),
+ (hc_evp_md_init)CC_MD4_Init,
+ (hc_evp_md_update)CC_MD4_Update,
+ (hc_evp_md_final)CC_MD4_Final,
+ (hc_evp_md_cleanup)NULL
+ };
+ return &md4;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_md4();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The CommonCrypto md5 provider
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_cc_md5(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H
+ static const struct hc_evp_md md5 = {
+ CC_MD5_DIGEST_LENGTH,
+ CC_MD5_BLOCK_BYTES,
+ sizeof(CC_MD5_CTX),
+ (hc_evp_md_init)CC_MD5_Init,
+ (hc_evp_md_update)CC_MD5_Update,
+ (hc_evp_md_final)CC_MD5_Final,
+ (hc_evp_md_cleanup)NULL
+ };
+ return &md5;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_md5();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The CommonCrypto sha1 provider
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_cc_sha1(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H
+ static const struct hc_evp_md sha1 = {
+ CC_SHA1_DIGEST_LENGTH,
+ CC_SHA1_BLOCK_BYTES,
+ sizeof(CC_SHA1_CTX),
+ (hc_evp_md_init)CC_SHA1_Init,
+ (hc_evp_md_update)CC_SHA1_Update,
+ (hc_evp_md_final)CC_SHA1_Final,
+ (hc_evp_md_cleanup)NULL
+ };
+ return &sha1;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_sha1();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The CommonCrypto sha256 provider
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_cc_sha256(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H
+ static const struct hc_evp_md sha256 = {
+ CC_SHA256_DIGEST_LENGTH,
+ CC_SHA256_BLOCK_BYTES,
+ sizeof(CC_SHA256_CTX),
+ (hc_evp_md_init)CC_SHA256_Init,
+ (hc_evp_md_update)CC_SHA256_Update,
+ (hc_evp_md_final)CC_SHA256_Final,
+ (hc_evp_md_cleanup)NULL
+ };
+ return &sha256;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_sha256();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The CommonCrypto sha384 provider
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_cc_sha384(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H
+ static const struct hc_evp_md sha384 = {
+ CC_SHA384_DIGEST_LENGTH,
+ CC_SHA384_BLOCK_BYTES,
+ sizeof(CC_SHA512_CTX),
+ (hc_evp_md_init)CC_SHA384_Init,
+ (hc_evp_md_update)CC_SHA384_Update,
+ (hc_evp_md_final)CC_SHA384_Final,
+ (hc_evp_md_cleanup)NULL
+ };
+ return &sha384;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_sha384();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The CommonCrypto sha512 provider
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_cc_sha512(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H
+ static const struct hc_evp_md sha512 = {
+ CC_SHA512_DIGEST_LENGTH,
+ CC_SHA512_BLOCK_BYTES,
+ sizeof(CC_SHA512_CTX),
+ (hc_evp_md_init)CC_SHA512_Init,
+ (hc_evp_md_update)CC_SHA512_Update,
+ (hc_evp_md_final)CC_SHA512_Final,
+ (hc_evp_md_cleanup)NULL
+ };
+ return &sha512;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_sha512();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The Camellia-128 cipher type - CommonCrypto
+ *
+ * @return the Camellia-128 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_cc_camellia_128_cbc(void)
+{
+#if HCRYPTO_FALLBACK
+ return EVP_hcrypto_camellia_128_cbc();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The Camellia-198 cipher type - CommonCrypto
+ *
+ * @return the Camellia-198 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_cc_camellia_192_cbc(void)
+{
+#if HCRYPTO_FALLBACK
+ return EVP_hcrypto_camellia_192_cbc();
+#else
+ return NULL;
+#endif
+}
+
+/**
+ * The Camellia-256 cipher type - CommonCrypto
+ *
+ * @return the Camellia-256 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_cc_camellia_256_cbc(void)
+{
+#if HCRYPTO_FALLBACK
+ return EVP_hcrypto_camellia_256_cbc();
+#else
+ return NULL;
+#endif
+}
+
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+
+/*
+ *
+ */
+
+static int
+cc_rc4_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char * key,
+ const unsigned char * iv,
+ int encp)
+{
+ struct cc_key *cc = ctx->cipher_data;
+ return init_cc_key(encp, ctx->cipher->flags, kCCAlgorithmRC4,
+ key, ctx->key_len, iv, &cc->href);
+}
+
+#endif
+
+/**
+
+ * The RC4 cipher type (Apple CommonCrypto provider)
+ *
+ * @return the RC4 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_cc_rc4(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+ static const EVP_CIPHER rc4 = {
+ 0,
+ 1,
+ 16,
+ 0,
+ EVP_CIPH_STREAM_CIPHER|EVP_CIPH_VARIABLE_LENGTH,
+ cc_rc4_init,
+ cc_do_cipher,
+ cc_cleanup,
+ sizeof(struct cc_key),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &rc4;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_rc4();
+#else
+ return NULL;
+#endif
+}
+
+
+/**
+ * The RC4-40 cipher type (Apple CommonCrypto provider)
+ *
+ * @return the RC4 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_cc_rc4_40(void)
+{
+#ifdef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+ static const EVP_CIPHER rc4_40 = {
+ 0,
+ 1,
+ 5,
+ 0,
+ EVP_CIPH_STREAM_CIPHER|EVP_CIPH_VARIABLE_LENGTH,
+ cc_rc4_init,
+ cc_do_cipher,
+ cc_cleanup,
+ sizeof(struct cc_key),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &rc4_40;
+#elif HCRYPTO_FALLBACK
+ return EVP_hcrypto_rc4_40();
+#else
+ return NULL;
+#endif
+}
+
+#endif /* __APPLE__ */
+
diff --git a/third_party/heimdal/lib/hcrypto/evp-cc.h b/third_party/heimdal/lib/hcrypto/evp-cc.h
new file mode 100644
index 0000000..4d131de
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp-cc.h
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_EVP_CC_H
+#define HEIM_EVP_CC_H 1
+
+/* symbol renaming */
+#define EVP_cc_md2 hc_EVP_cc_md2
+#define EVP_cc_md4 hc_EVP_cc_md4
+#define EVP_cc_md5 hc_EVP_cc_md5
+#define EVP_cc_sha1 hc_EVP_cc_sha1
+#define EVP_cc_sha256 hc_EVP_cc_sha256
+#define EVP_cc_sha384 hc_EVP_cc_sha384
+#define EVP_cc_sha512 hc_EVP_cc_sha512
+#define EVP_cc_des_cbc hc_EVP_cc_des_cbc
+#define EVP_cc_des_ede3_cbc hc_EVP_cc_des_ede3_cbc
+#define EVP_cc_aes_128_cbc hc_EVP_cc_aes_128_cbc
+#define EVP_cc_aes_192_cbc hc_EVP_cc_aes_192_cbc
+#define EVP_cc_aes_256_cbc hc_EVP_cc_aes_256_cbc
+#define EVP_cc_aes_128_cfb8 hc_EVP_cc_aes_128_cfb8
+#define EVP_cc_aes_192_cfb8 hc_EVP_cc_aes_192_cfb8
+#define EVP_cc_aes_256_cfb8 hc_EVP_cc_aes_256_cfb8
+#define EVP_cc_rc4 hc_EVP_cc_rc4
+#define EVP_cc_rc4_40 hc_EVP_cc_rc4_40
+#define EVP_cc_rc2_40_cbc hc_EVP_cc_rc2_40_cbc
+#define EVP_cc_rc2_64_cbc hc_EVP_cc_rc2_64_cbc
+#define EVP_cc_rc2_cbc hc_EVP_cc_rc2_cbc
+#define EVP_cc_camellia_128_cbc hc_EVP_cc_camellia_128_cbc
+#define EVP_cc_camellia_192_cbc hc_EVP_cc_camellia_192_cbc
+#define EVP_cc_camellia_256_cbc hc_EVP_cc_camellia_256_cbc
+
+/*
+ *
+ */
+
+HC_CPP_BEGIN
+
+const EVP_MD * EVP_cc_md2(void);
+const EVP_MD * EVP_cc_md4(void);
+const EVP_MD * EVP_cc_md5(void);
+const EVP_MD * EVP_cc_sha1(void);
+const EVP_MD * EVP_cc_sha256(void);
+const EVP_MD * EVP_cc_sha384(void);
+const EVP_MD * EVP_cc_sha512(void);
+
+const EVP_CIPHER * EVP_cc_rc2_cbc(void);
+const EVP_CIPHER * EVP_cc_rc2_40_cbc(void);
+const EVP_CIPHER * EVP_cc_rc2_64_cbc(void);
+
+const EVP_CIPHER * EVP_cc_rc4(void);
+const EVP_CIPHER * EVP_cc_rc4_40(void);
+
+const EVP_CIPHER * EVP_cc_des_cbc(void);
+const EVP_CIPHER * EVP_cc_des_ede3_cbc(void);
+
+const EVP_CIPHER * EVP_cc_aes_128_cbc(void);
+const EVP_CIPHER * EVP_cc_aes_192_cbc(void);
+const EVP_CIPHER * EVP_cc_aes_256_cbc(void);
+
+const EVP_CIPHER * EVP_cc_aes_128_cfb8(void);
+const EVP_CIPHER * EVP_cc_aes_192_cfb8(void);
+const EVP_CIPHER * EVP_cc_aes_256_cfb8(void);
+
+const EVP_CIPHER * EVP_cc_camellia_128_cbc(void);
+const EVP_CIPHER * EVP_cc_camellia_192_cbc(void);
+const EVP_CIPHER * EVP_cc_camellia_256_cbc(void);
+
+HC_CPP_END
+
+#endif /* HEIM_EVP_CC_H */
diff --git a/third_party/heimdal/lib/hcrypto/evp-crypt.c b/third_party/heimdal/lib/hcrypto/evp-crypt.c
new file mode 100644
index 0000000..4e8489e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp-crypt.c
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* Windows crypto provider plugin, sample */
+
+#include <config.h>
+#include <roken.h>
+
+#define HC_DEPRECATED
+
+#include <assert.h>
+
+#include <evp.h>
+
+#include <crypt.h>
+
+
+static HCRYPTPROV hCryptProv = NULL;
+
+/*
+ *
+ */
+
+struct generic_key {
+ HCRYPTKEY *hKey;
+};
+
+static int
+generic_cbc_do_cipher(EVP_CIPHER_CTX *ctx,
+ unsigned char *out,
+ const unsigned char *in,
+ unsigned int size)
+{
+ struct generic_key *gk = ctx->cipher_data;
+ BOOL bResult;
+ DWORD length = size;
+
+ bResult = CryptSetKeyParam(gk->hKey, KP_IV, ctx->iv, 0);
+ _ASSERT(bResult);
+
+ memcpy(out, in, size);
+
+ if (ctx->encrypt)
+ bResult = CryptEncrypt(gk->hKey, 0, TRUE, 0, out, &length, size);
+ else
+ bResult = CryptDecrypt(gk->hKey, 0, TRUE, 0, out, &length);
+ _ASSERT(bResult);
+
+ return 1;
+}
+
+static int
+generic_cleanup(EVP_CIPHER_CTX *ctx)
+{
+ struct generic_key *gk = ctx->cipher_data;
+ CryptDestroyKey(gk->hKey);
+ gk->hKey = NULL;
+ return 1;
+}
+
+static HCRYPTKEY
+import_key(int alg, const unsigned char *key, size_t keylen)
+{
+ struct {
+ BLOBHEADER hdr;
+ DWORD len;
+ BYTE key[1];
+ } *key_blob;
+ size_t bloblen = sizeof(*key_blob) - 1 + keylen;
+
+ key_blob = malloc(bloblen);
+
+ key_blob->hdr.bType = PLAINTEXTKEYBLOB;
+ key_blob->hdr.bVersion = CUR_BLOB_VERSION;
+ key_blob->hdr.reserved = 0;
+ key_blob->hdr.aiKeyAlg = alg;
+ key_blob->len = 24;
+ memcpy(key_blob->key, key, keylen);
+
+ bResult = CryptImportKey(hCryptProv,
+ (void *)key_blob, bloblen, 0, 0,
+ &gk->hKey);
+ free(key_blob);
+ _ASSERT(bResult);
+
+ return hKey;
+}
+
+static int
+crypto_des_ede3_cbc_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char * key,
+ const unsigned char * iv,
+ int encp)
+{
+ struct generic_key *gk = ctx->cipher_data;
+ DWORD paramData;
+
+ gk->hKey = import_key(CALG_3DES,
+ key->key->keyvalue.data,
+ key->key->keyvalue.len);
+
+ return 1;
+}
+
+/**
+ * The triple DES cipher type (Micrsoft crypt provider)
+ *
+ * @return the DES-EDE3-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_wincrypt_des_ede3_cbc(void)
+{
+ static const EVP_CIPHER des_ede3_cbc = {
+ 0,
+ 8,
+ 24,
+ 8,
+ EVP_CIPH_CBC_MODE,
+ crypto_des_ede3_cbc_init,
+ generic_cbc_do_cipher,
+ generic_cleanup,
+ sizeof(struct generic_key),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &des_ede3_cbc;
+}
+
+/*
+ *
+ */
+
+struct generic_hash {
+ HCRYPTHASH hHash;
+};
+
+static void
+crypto_md5_init(struct generic_hash *m);
+{
+ BOOL bResult;
+ bResult = CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &m->hHash);
+ _ASSERT(bResult);
+}
+
+static void
+generic_hash_update (struct generic_hash *m, const void *p, size_t len)
+{
+ BOOL bResult;
+ bResult = CryptHashData(m->hHash, data, ( DWORD )len, 0 );
+ _ASSERT(bResult);
+}
+
+static void
+generic_hash_final (void *res, struct generic_hash *m);
+{
+ DWORD length;
+ BOOL bResult;
+ bResult = CryptGetHashParam(m->hHash, HP_HASHVAL, res, &length, 0)
+ _ASSERT(bResult);
+}
+
+static void
+generic_hash_cleanup(struct generic_hash *m)
+{
+ CryptDestroyHash(m->hHash);
+ m->hHash = NULL;
+}
+
+const EVP_MD *
+EVP_wincrypt_md5(void)
+{
+ static const struct hc_evp_md md5 = {
+ 16,
+ 64,
+ sizeof(struct generic_hash),
+ (hc_evp_md_init)crypto_md5_init,
+ (hc_evp_md_update)generic_hash_update,
+ (hc_evp_md_final)generic_hash_final,
+ (hc_evp_md_cleanup)generic_hash_cleanup
+ };
+ return &md5;
+}
diff --git a/third_party/heimdal/lib/hcrypto/evp-hcrypto.c b/third_party/heimdal/lib/hcrypto/evp-hcrypto.c
new file mode 100644
index 0000000..321efb0
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp-hcrypto.c
@@ -0,0 +1,854 @@
+/*
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#define HC_DEPRECATED
+
+#include <assert.h>
+
+#include <evp.h>
+#include <evp-hcrypto.h>
+
+#include <krb5-types.h>
+
+#include <des.h>
+#include "camellia.h"
+#include <aes.h>
+
+#include <rc2.h>
+#include <rc4.h>
+
+#include <sha.h>
+#include <md2.h>
+#include <md4.h>
+#include <md5.h>
+
+/*
+ *
+ */
+
+static int
+aes_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char * key,
+ const unsigned char * iv,
+ int encp)
+{
+ AES_KEY *k = ctx->cipher_data;
+ if (ctx->encrypt || EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_CFB8_MODE)
+ AES_set_encrypt_key(key, ctx->cipher->key_len * 8, k);
+ else
+ AES_set_decrypt_key(key, ctx->cipher->key_len * 8, k);
+ return 1;
+}
+
+static int
+aes_do_cipher(EVP_CIPHER_CTX *ctx,
+ unsigned char *out,
+ const unsigned char *in,
+ unsigned int size)
+{
+ AES_KEY *k = ctx->cipher_data;
+ if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_CFB8_MODE)
+ AES_cfb8_encrypt(in, out, size, k, ctx->iv, ctx->encrypt);
+ else
+ AES_cbc_encrypt(in, out, size, k, ctx->iv, ctx->encrypt);
+ return 1;
+}
+
+/**
+ * The AES-128 cipher type (hcrypto)
+ *
+ * @return the AES-128 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_hcrypto_aes_128_cbc(void)
+{
+ static const EVP_CIPHER aes_128_cbc = {
+ 0,
+ 16,
+ 16,
+ 16,
+ EVP_CIPH_CBC_MODE,
+ aes_init,
+ aes_do_cipher,
+ NULL,
+ sizeof(AES_KEY),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+
+ return &aes_128_cbc;
+}
+
+/**
+ * The AES-192 cipher type (hcrypto)
+ *
+ * @return the AES-192 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_hcrypto_aes_192_cbc(void)
+{
+ static const EVP_CIPHER aes_192_cbc = {
+ 0,
+ 16,
+ 24,
+ 16,
+ EVP_CIPH_CBC_MODE,
+ aes_init,
+ aes_do_cipher,
+ NULL,
+ sizeof(AES_KEY),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &aes_192_cbc;
+}
+
+/**
+ * The AES-256 cipher type (hcrypto)
+ *
+ * @return the AES-256 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_hcrypto_aes_256_cbc(void)
+{
+ static const EVP_CIPHER aes_256_cbc = {
+ 0,
+ 16,
+ 32,
+ 16,
+ EVP_CIPH_CBC_MODE,
+ aes_init,
+ aes_do_cipher,
+ NULL,
+ sizeof(AES_KEY),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &aes_256_cbc;
+}
+
+/**
+ * The AES-128 CFB8 cipher type (hcrypto)
+ *
+ * @return the AES-128 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_hcrypto_aes_128_cfb8(void)
+{
+ static const EVP_CIPHER aes_128_cfb8 = {
+ 0,
+ 1,
+ 16,
+ 16,
+ EVP_CIPH_CFB8_MODE,
+ aes_init,
+ aes_do_cipher,
+ NULL,
+ sizeof(AES_KEY),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+
+ return &aes_128_cfb8;
+}
+
+/**
+ * The AES-192 CFB8 cipher type (hcrypto)
+ *
+ * @return the AES-192 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_hcrypto_aes_192_cfb8(void)
+{
+ static const EVP_CIPHER aes_192_cfb8 = {
+ 0,
+ 1,
+ 24,
+ 16,
+ EVP_CIPH_CFB8_MODE,
+ aes_init,
+ aes_do_cipher,
+ NULL,
+ sizeof(AES_KEY),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &aes_192_cfb8;
+}
+
+/**
+ * The AES-256 CFB8 cipher type (hcrypto)
+ *
+ * @return the AES-256 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_hcrypto_aes_256_cfb8(void)
+{
+ static const EVP_CIPHER aes_256_cfb8 = {
+ 0,
+ 1,
+ 32,
+ 16,
+ EVP_CIPH_CFB8_MODE,
+ aes_init,
+ aes_do_cipher,
+ NULL,
+ sizeof(AES_KEY),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &aes_256_cfb8;
+}
+
+/**
+ * The message digest SHA256 - hcrypto
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_hcrypto_sha256(void)
+{
+ static const struct hc_evp_md sha256 = {
+ 32,
+ 64,
+ sizeof(SHA256_CTX),
+ (hc_evp_md_init)SHA256_Init,
+ (hc_evp_md_update)SHA256_Update,
+ (hc_evp_md_final)SHA256_Final,
+ NULL
+ };
+ return &sha256;
+}
+
+/**
+ * The message digest SHA384 - hcrypto
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_hcrypto_sha384(void)
+{
+ static const struct hc_evp_md sha384 = {
+ 48,
+ 128,
+ sizeof(SHA384_CTX),
+ (hc_evp_md_init)SHA384_Init,
+ (hc_evp_md_update)SHA384_Update,
+ (hc_evp_md_final)SHA384_Final,
+ NULL
+ };
+ return &sha384;
+}
+
+/**
+ * The message digest SHA512 - hcrypto
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_hcrypto_sha512(void)
+{
+ static const struct hc_evp_md sha512 = {
+ 64,
+ 128,
+ sizeof(SHA512_CTX),
+ (hc_evp_md_init)SHA512_Init,
+ (hc_evp_md_update)SHA512_Update,
+ (hc_evp_md_final)SHA512_Final,
+ NULL
+ };
+ return &sha512;
+}
+
+/**
+ * The message digest SHA1 - hcrypto
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_hcrypto_sha1(void)
+{
+ static const struct hc_evp_md sha1 = {
+ 20,
+ 64,
+ sizeof(SHA_CTX),
+ (hc_evp_md_init)SHA1_Init,
+ (hc_evp_md_update)SHA1_Update,
+ (hc_evp_md_final)SHA1_Final,
+ NULL
+ };
+ return &sha1;
+}
+
+/**
+ * The message digest MD5 - hcrypto
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_hcrypto_md5(void)
+{
+ static const struct hc_evp_md md5 = {
+ 16,
+ 64,
+ sizeof(MD5_CTX),
+ (hc_evp_md_init)MD5_Init,
+ (hc_evp_md_update)MD5_Update,
+ (hc_evp_md_final)MD5_Final,
+ NULL
+ };
+ return &md5;
+}
+
+/**
+ * The message digest MD4 - hcrypto
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_hcrypto_md4(void)
+{
+ static const struct hc_evp_md md4 = {
+ 16,
+ 64,
+ sizeof(MD4_CTX),
+ (hc_evp_md_init)MD4_Init,
+ (hc_evp_md_update)MD4_Update,
+ (hc_evp_md_final)MD4_Final,
+ NULL
+ };
+ return &md4;
+}
+
+/**
+ * The message digest MD2 - hcrypto
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_hcrypto_md2(void)
+{
+ static const struct hc_evp_md md2 = {
+ 16,
+ 16,
+ sizeof(MD2_CTX),
+ (hc_evp_md_init)MD2_Init,
+ (hc_evp_md_update)MD2_Update,
+ (hc_evp_md_final)MD2_Final,
+ NULL
+ };
+ return &md2;
+}
+
+/*
+ *
+ */
+
+static int
+des_cbc_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char * key,
+ const unsigned char * iv,
+ int encp)
+{
+ DES_key_schedule *k = ctx->cipher_data;
+ DES_cblock deskey;
+ memcpy(&deskey, key, sizeof(deskey));
+ DES_set_key_unchecked(&deskey, k);
+ return 1;
+}
+
+static int
+des_cbc_do_cipher(EVP_CIPHER_CTX *ctx,
+ unsigned char *out,
+ const unsigned char *in,
+ unsigned int size)
+{
+ DES_key_schedule *k = ctx->cipher_data;
+ DES_cbc_encrypt(in, out, size,
+ k, (DES_cblock *)ctx->iv, ctx->encrypt);
+ return 1;
+}
+
+/**
+ * The DES cipher type
+ *
+ * @return the DES-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_hcrypto_des_cbc(void)
+{
+ static const EVP_CIPHER des_cbc = {
+ 0,
+ 8,
+ 8,
+ 8,
+ EVP_CIPH_CBC_MODE,
+ des_cbc_init,
+ des_cbc_do_cipher,
+ NULL,
+ sizeof(DES_key_schedule),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &des_cbc;
+}
+
+/*
+ *
+ */
+
+struct des_ede3_cbc {
+ DES_key_schedule ks[3];
+};
+
+static int
+des_ede3_cbc_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char * key,
+ const unsigned char * iv,
+ int encp)
+{
+ struct des_ede3_cbc *k = ctx->cipher_data;
+ DES_cblock deskey;
+
+ memcpy(&deskey, key, sizeof(deskey));
+ DES_set_odd_parity(&deskey);
+ DES_set_key_unchecked(&deskey, &k->ks[0]);
+
+ memcpy(&deskey, key + 8, sizeof(deskey));
+ DES_set_odd_parity(&deskey);
+ DES_set_key_unchecked(&deskey, &k->ks[1]);
+
+ memcpy(&deskey, key + 16, sizeof(deskey));
+ DES_set_odd_parity(&deskey);
+ DES_set_key_unchecked(&deskey, &k->ks[2]);
+
+ return 1;
+}
+
+static int
+des_ede3_cbc_do_cipher(EVP_CIPHER_CTX *ctx,
+ unsigned char *out,
+ const unsigned char *in,
+ unsigned int size)
+{
+ struct des_ede3_cbc *k = ctx->cipher_data;
+ DES_ede3_cbc_encrypt(in, out, size,
+ &k->ks[0], &k->ks[1], &k->ks[2],
+ (DES_cblock *)ctx->iv, ctx->encrypt);
+ return 1;
+}
+
+/**
+ * The triple DES cipher type - hcrypto
+ *
+ * @return the DES-EDE3-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_hcrypto_des_ede3_cbc(void)
+{
+ static const EVP_CIPHER des_ede3_cbc = {
+ 0,
+ 8,
+ 24,
+ 8,
+ EVP_CIPH_CBC_MODE,
+ des_ede3_cbc_init,
+ des_ede3_cbc_do_cipher,
+ NULL,
+ sizeof(struct des_ede3_cbc),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &des_ede3_cbc;
+}
+
+/*
+ *
+ */
+
+struct rc2_cbc {
+ unsigned int maximum_effective_key;
+ RC2_KEY key;
+};
+
+static int
+rc2_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char * key,
+ const unsigned char * iv,
+ int encp)
+{
+ struct rc2_cbc *k = ctx->cipher_data;
+ k->maximum_effective_key = EVP_CIPHER_CTX_key_length(ctx) * 8;
+ RC2_set_key(&k->key,
+ EVP_CIPHER_CTX_key_length(ctx),
+ key,
+ k->maximum_effective_key);
+ return 1;
+}
+
+static int
+rc2_do_cipher(EVP_CIPHER_CTX *ctx,
+ unsigned char *out,
+ const unsigned char *in,
+ unsigned int size)
+{
+ struct rc2_cbc *k = ctx->cipher_data;
+ RC2_cbc_encrypt(in, out, size, &k->key, ctx->iv, ctx->encrypt);
+ return 1;
+}
+
+/**
+ * The RC2 cipher type - hcrypto
+ *
+ * @return the RC2 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_hcrypto_rc2_cbc(void)
+{
+ static const EVP_CIPHER rc2_cbc = {
+ 0,
+ RC2_BLOCK_SIZE,
+ RC2_KEY_LENGTH,
+ RC2_BLOCK_SIZE,
+ EVP_CIPH_CBC_MODE|EVP_CIPH_VARIABLE_LENGTH,
+ rc2_init,
+ rc2_do_cipher,
+ NULL,
+ sizeof(struct rc2_cbc),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &rc2_cbc;
+}
+
+/**
+ * The RC2-40 cipher type
+ *
+ * @return the RC2-40 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_hcrypto_rc2_40_cbc(void)
+{
+ static const EVP_CIPHER rc2_40_cbc = {
+ 0,
+ RC2_BLOCK_SIZE,
+ 5,
+ RC2_BLOCK_SIZE,
+ EVP_CIPH_CBC_MODE,
+ rc2_init,
+ rc2_do_cipher,
+ NULL,
+ sizeof(struct rc2_cbc),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &rc2_40_cbc;
+}
+
+/**
+ * The RC2-64 cipher type
+ *
+ * @return the RC2-64 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_hcrypto_rc2_64_cbc(void)
+{
+ static const EVP_CIPHER rc2_64_cbc = {
+ 0,
+ RC2_BLOCK_SIZE,
+ 8,
+ RC2_BLOCK_SIZE,
+ EVP_CIPH_CBC_MODE,
+ rc2_init,
+ rc2_do_cipher,
+ NULL,
+ sizeof(struct rc2_cbc),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &rc2_64_cbc;
+}
+
+static int
+camellia_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char * key,
+ const unsigned char * iv,
+ int encp)
+{
+ CAMELLIA_KEY *k = ctx->cipher_data;
+ k->bits = ctx->cipher->key_len * 8;
+ CAMELLIA_set_key(key, ctx->cipher->key_len * 8, k);
+ return 1;
+}
+
+static int
+camellia_do_cipher(EVP_CIPHER_CTX *ctx,
+ unsigned char *out,
+ const unsigned char *in,
+ unsigned int size)
+{
+ CAMELLIA_KEY *k = ctx->cipher_data;
+ CAMELLIA_cbc_encrypt(in, out, size, k, ctx->iv, ctx->encrypt);
+ return 1;
+}
+
+/**
+ * The Camellia-128 cipher type - hcrypto
+ *
+ * @return the Camellia-128 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_hcrypto_camellia_128_cbc(void)
+{
+ static const EVP_CIPHER cipher = {
+ 0,
+ 16,
+ 16,
+ 16,
+ EVP_CIPH_CBC_MODE,
+ camellia_init,
+ camellia_do_cipher,
+ NULL,
+ sizeof(CAMELLIA_KEY),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &cipher;
+}
+
+/**
+ * The Camellia-198 cipher type - hcrypto
+ *
+ * @return the Camellia-198 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_hcrypto_camellia_192_cbc(void)
+{
+ static const EVP_CIPHER cipher = {
+ 0,
+ 16,
+ 24,
+ 16,
+ EVP_CIPH_CBC_MODE,
+ camellia_init,
+ camellia_do_cipher,
+ NULL,
+ sizeof(CAMELLIA_KEY),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &cipher;
+}
+
+/**
+ * The Camellia-256 cipher type - hcrypto
+ *
+ * @return the Camellia-256 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_hcrypto_camellia_256_cbc(void)
+{
+ static const EVP_CIPHER cipher = {
+ 0,
+ 16,
+ 32,
+ 16,
+ EVP_CIPH_CBC_MODE,
+ camellia_init,
+ camellia_do_cipher,
+ NULL,
+ sizeof(CAMELLIA_KEY),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &cipher;
+}
+
+static int
+rc4_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char *key,
+ const unsigned char *iv,
+ int enc)
+{
+ RC4_KEY *k = ctx->cipher_data;
+ RC4_set_key(k, ctx->key_len, key);
+ return 1;
+}
+
+static int
+rc4_do_cipher(EVP_CIPHER_CTX *ctx,
+ unsigned char *out,
+ const unsigned char *in,
+ unsigned int size)
+{
+ RC4_KEY *k = ctx->cipher_data;
+ RC4(k, size, in, out);
+ return 1;
+}
+
+const EVP_CIPHER *
+EVP_hcrypto_rc4(void)
+{
+ static const EVP_CIPHER rc4 = {
+ 0,
+ 1,
+ 16,
+ 0,
+ EVP_CIPH_STREAM_CIPHER|EVP_CIPH_VARIABLE_LENGTH,
+ rc4_init,
+ rc4_do_cipher,
+ NULL,
+ sizeof(RC4_KEY),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &rc4;
+}
+
+
+const EVP_CIPHER *
+EVP_hcrypto_rc4_40(void)
+{
+ static const EVP_CIPHER rc4_40 = {
+ 0,
+ 1,
+ 5,
+ 0,
+ EVP_CIPH_STREAM_CIPHER|EVP_CIPH_VARIABLE_LENGTH,
+ rc4_init,
+ rc4_do_cipher,
+ NULL,
+ sizeof(RC4_KEY),
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &rc4_40;
+}
diff --git a/third_party/heimdal/lib/hcrypto/evp-hcrypto.h b/third_party/heimdal/lib/hcrypto/evp-hcrypto.h
new file mode 100644
index 0000000..b7876c6
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp-hcrypto.h
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_EVP_HCRYPTO_H
+#define HEIM_EVP_HCRYPTO_H 1
+
+/* symbol renaming */
+#define EVP_hcrypto_md2 hc_EVP_hcrypto_md2
+#define EVP_hcrypto_md4 hc_EVP_hcrypto_md4
+#define EVP_hcrypto_md5 hc_EVP_hcrypto_md5
+#define EVP_hcrypto_sha1 hc_EVP_hcrypto_sha1
+#define EVP_hcrypto_sha256 hc_EVP_hcrypto_sha256
+#define EVP_hcrypto_sha384 hc_EVP_hcrypto_sha384
+#define EVP_hcrypto_sha512 hc_EVP_hcrypto_sha512
+#define EVP_hcrypto_des_cbc hc_EVP_hcrypto_des_cbc
+#define EVP_hcrypto_des_ede3_cbc hc_EVP_hcrypto_des_ede3_cbc
+#define EVP_hcrypto_aes_128_cbc hc_EVP_hcrypto_aes_128_cbc
+#define EVP_hcrypto_aes_192_cbc hc_EVP_hcrypto_aes_192_cbc
+#define EVP_hcrypto_aes_256_cbc hc_EVP_hcrypto_aes_256_cbc
+#define EVP_hcrypto_aes_128_cfb8 hc_EVP_hcrypto_aes_128_cfb8
+#define EVP_hcrypto_aes_192_cfb8 hc_EVP_hcrypto_aes_192_cfb8
+#define EVP_hcrypto_aes_256_cfb8 hc_EVP_hcrypto_aes_256_cfb8
+#define EVP_hcrypto_rc4 hc_EVP_hcrypto_rc4
+#define EVP_hcrypto_rc4_40 hc_EVP_hcrypto_rc4_40
+#define EVP_hcrypto_rc2_40_cbc hc_EVP_hcrypto_rc2_40_cbc
+#define EVP_hcrypto_rc2_64_cbc hc_EVP_hcrypto_rc2_64_cbc
+#define EVP_hcrypto_rc2_cbc hc_EVP_hcrypto_rc2_cbc
+#define EVP_hcrypto_camellia_128_cbc hc_EVP_hcrypto_camellia_128_cbc
+#define EVP_hcrypto_camellia_192_cbc hc_EVP_hcrypto_camellia_192_cbc
+#define EVP_hcrypto_camellia_256_cbc hc_EVP_hcrypto_camellia_256_cbc
+
+/*
+ *
+ */
+
+HC_CPP_BEGIN
+
+const EVP_MD * EVP_hcrypto_md2(void);
+const EVP_MD * EVP_hcrypto_md4(void);
+const EVP_MD * EVP_hcrypto_md5(void);
+const EVP_MD * EVP_hcrypto_sha1(void);
+const EVP_MD * EVP_hcrypto_sha256(void);
+const EVP_MD * EVP_hcrypto_sha384(void);
+const EVP_MD * EVP_hcrypto_sha512(void);
+
+const EVP_CIPHER * EVP_hcrypto_rc4(void);
+const EVP_CIPHER * EVP_hcrypto_rc4_40(void);
+
+const EVP_CIPHER * EVP_hcrypto_rc2_cbc(void);
+const EVP_CIPHER * EVP_hcrypto_rc2_40_cbc(void);
+const EVP_CIPHER * EVP_hcrypto_rc2_64_cbc(void);
+
+const EVP_CIPHER * EVP_hcrypto_des_cbc(void);
+const EVP_CIPHER * EVP_hcrypto_des_ede3_cbc(void);
+
+const EVP_CIPHER * EVP_hcrypto_aes_128_cbc(void);
+const EVP_CIPHER * EVP_hcrypto_aes_192_cbc(void);
+const EVP_CIPHER * EVP_hcrypto_aes_256_cbc(void);
+
+const EVP_CIPHER * EVP_hcrypto_aes_128_cfb8(void);
+const EVP_CIPHER * EVP_hcrypto_aes_192_cfb8(void);
+const EVP_CIPHER * EVP_hcrypto_aes_256_cfb8(void);
+
+const EVP_CIPHER * EVP_hcrypto_camellia_128_cbc(void);
+const EVP_CIPHER * EVP_hcrypto_camellia_192_cbc(void);
+const EVP_CIPHER * EVP_hcrypto_camellia_256_cbc(void);
+
+
+HC_CPP_END
+
+#endif /* HEIM_EVP_HCRYPTO_H */
diff --git a/third_party/heimdal/lib/hcrypto/evp-openssl.c b/third_party/heimdal/lib/hcrypto/evp-openssl.c
new file mode 100644
index 0000000..a651184
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp-openssl.c
@@ -0,0 +1,644 @@
+/*
+ * Copyright (c) 2016, Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* OpenSSL provider */
+
+#include "config.h"
+#include <roken.h>
+#include <heimbase.h>
+
+#include <assert.h>
+#include <evp.h>
+
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+
+/*
+ * This is the OpenSSL 1.x backend for hcrypto. It has been tested with
+ * OpenSSL 1.0.1f and OpenSSL 1.1.0-pre3-dev.
+ *
+ * NOTE: In order for this to work with OpenSSL 1.1.x and up, it is
+ * critical to use opaque OpenSSL type accessors everywhere /
+ * never use knowledge of opaque OpenSSL type internals.
+ */
+
+#include <evp-openssl.h>
+
+/*
+ * This being an OpenSSL backend for hcrypto... we need to be able to
+ * refer to types and objects (functions) from both, OpenSSL and
+ * hcrypto.
+ *
+ * The hcrypto API is *very* similar to the OpenSSL 1.0.x API, with the
+ * same type and symbol names in many cases, except that the hcrypto
+ * names are prefixed with hc_*. hcrypto has convenience macros that
+ * provide OpenSSL aliases for the hcrypto interfaces, and hcrypto
+ * applications are expected to use the OpenSSL names.
+ *
+ * Since here we must be able to refer to types and objects from both
+ * OpenSSL and from hcrypto, we disable the hcrypto renaming for the
+ * rest of this file. These #undefs could be collected into an
+ * <hcrypto/undef.h> for the purpose of permitting other applications to
+ * use both, hcrypto and OpenSSL in the same source files (provided that
+ * such applications refer to hcrypto types and objects by their proper
+ * hc_-prefixed names).
+ */
+#include <undef.h>
+
+/* Now it's safe to include OpenSSL headers */
+#include <openssl/evp.h>
+
+#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
+#define EVP_MD_CTX_new EVP_MD_CTX_create
+#define EVP_MD_CTX_free EVP_MD_CTX_destroy
+#endif
+
+/* A HEIM_BASE_ONCE argument struct for per-EVP one-time initialization */
+struct once_init_cipher_ctx {
+ const hc_EVP_CIPHER **hc_memoizep;
+ hc_EVP_CIPHER *hc_memoize;
+ const hc_EVP_CIPHER *fallback;
+ unsigned long flags;
+ int nid;
+};
+
+/* Our wrapper for OpenSSL EVP_CIPHER_CTXs */
+struct ossl_cipher_ctx {
+ EVP_CIPHER_CTX *ossl_cipher_ctx; /* OpenSSL cipher ctx */
+ const EVP_CIPHER *ossl_cipher; /* OpenSSL cipher */
+ int initialized;
+};
+
+/*
+ * Our hc_EVP_CIPHER init() method; wraps around OpenSSL
+ * EVP_CipherInit_ex().
+ *
+ * This is very similar to the init() function pointer in an OpenSSL
+ * EVP_CIPHER, but a) we can't access them in 1.1, and b) the method
+ * invocation protocols in hcrypto and OpenSSL are similar but not the
+ * same, thus we must have this wrapper.
+ */
+static int
+cipher_ctx_init(hc_EVP_CIPHER_CTX *ctx, const unsigned char *key,
+ const unsigned char *iv, int enc)
+{
+ struct ossl_cipher_ctx *ossl_ctx = ctx->cipher_data; /* EVP_CIPHER_CTX wrapper */
+ const EVP_CIPHER *c;
+
+ assert(ossl_ctx != NULL);
+ assert(ctx->cipher != NULL);
+ assert(ctx->cipher->app_data != NULL);
+
+ /*
+ * Here be dragons.
+ *
+ * We need to make sure that the OpenSSL EVP_CipherInit_ex() is
+ * called with cipher!=NULL just once per EVP_CIPHER_CTX, otherwise
+ * state in the OpenSSL EVP_CIPHER_CTX will get cleaned up and then
+ * we'll segfault.
+ *
+ * hcrypto applications can re-initialize an (hc_)EVP_CIPHER_CTX as
+ * usual by calling (hc)EVP_CipherInit_ex() with a non-NULL cipher
+ * argument, and that will cause cipher_cleanup() (below) to be
+ * called.
+ */
+ c = ossl_ctx->ossl_cipher = ctx->cipher->app_data; /* OpenSSL's EVP_CIPHER * */
+ if (!ossl_ctx->initialized) {
+ ossl_ctx->ossl_cipher_ctx = EVP_CIPHER_CTX_new();
+ if (ossl_ctx->ossl_cipher_ctx == NULL)
+ return 0;
+ /*
+ * So we always call EVP_CipherInit_ex() with c!=NULL, but other
+ * things NULL...
+ */
+ if (!EVP_CipherInit_ex(ossl_ctx->ossl_cipher_ctx, c, NULL, NULL, NULL, enc))
+ return 0;
+ ossl_ctx->initialized = 1;
+ }
+
+ /* ...and from here on always call EVP_CipherInit_ex() with c=NULL */
+ if ((ctx->cipher->flags & hc_EVP_CIPH_VARIABLE_LENGTH) &&
+ ctx->key_len > 0)
+ EVP_CIPHER_CTX_set_key_length(ossl_ctx->ossl_cipher_ctx, ctx->key_len);
+
+ return EVP_CipherInit_ex(ossl_ctx->ossl_cipher_ctx, NULL, NULL, key, iv, enc);
+}
+
+static int
+cipher_do_cipher(hc_EVP_CIPHER_CTX *ctx, unsigned char *out,
+ const unsigned char *in, unsigned int len)
+{
+ struct ossl_cipher_ctx *ossl_ctx = ctx->cipher_data;
+
+ assert(ossl_ctx != NULL);
+ return EVP_Cipher(ossl_ctx->ossl_cipher_ctx, out, in, len);
+}
+
+static int
+cipher_cleanup(hc_EVP_CIPHER_CTX *ctx)
+{
+ struct ossl_cipher_ctx *ossl_ctx = ctx->cipher_data;
+
+ if (ossl_ctx == NULL || !ossl_ctx->initialized)
+ return 1;
+
+ if (ossl_ctx->ossl_cipher_ctx != NULL)
+ EVP_CIPHER_CTX_free(ossl_ctx->ossl_cipher_ctx);
+
+ ossl_ctx->ossl_cipher_ctx = NULL;
+ ossl_ctx->ossl_cipher = NULL;
+ ossl_ctx->initialized = 0;
+ return 1;
+}
+
+static int
+cipher_ctrl(hc_EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
+{
+ struct ossl_cipher_ctx *ossl_ctx = ctx->cipher_data;
+
+ assert(ossl_ctx != NULL);
+ return EVP_CIPHER_CTX_ctrl(ossl_ctx->ossl_cipher_ctx, type, arg, ptr);
+}
+
+
+static void
+get_EVP_CIPHER_once_cb(void *d)
+{
+ struct once_init_cipher_ctx *arg = d;
+ const EVP_CIPHER *ossl_evp;
+ hc_EVP_CIPHER *hc_evp;
+
+ hc_evp = arg->hc_memoize;
+
+ /*
+ * We lookup EVP_CIPHER *s by NID so that we don't fail to find a
+ * symbol such as EVP_aes...() when libcrypto changes after build
+ * time (e.g., updates, LD_LIBRARY_PATH/LD_PRELOAD).
+ */
+ ossl_evp = EVP_get_cipherbynid(arg->nid);
+ if (ossl_evp == NULL) {
+ (void) memset(hc_evp, 0, sizeof(*hc_evp));
+#if HCRYPTO_FALLBACK
+ *arg->hc_memoizep = arg->fallback;
+#endif
+ return;
+ }
+
+ /* Build the hc_EVP_CIPHER */
+ hc_evp->nid = EVP_CIPHER_nid(ossl_evp); /* We would an hcrypto NIDs if we had them */
+ hc_evp->block_size = EVP_CIPHER_block_size(ossl_evp);
+ hc_evp->key_len = EVP_CIPHER_key_length(ossl_evp);
+ hc_evp->iv_len = EVP_CIPHER_iv_length(ossl_evp);
+
+ /*
+ * We force hc_EVP_CipherInit_ex to always call our init() function,
+ * otherwise we don't get a chance to call EVP_CipherInit_ex()
+ * correctly.
+ */
+ hc_evp->flags = hc_EVP_CIPH_ALWAYS_CALL_INIT | arg->flags;
+
+ /* Our cipher context */
+ hc_evp->ctx_size = sizeof(struct ossl_cipher_ctx);
+
+ /* Our wrappers */
+ hc_evp->init = cipher_ctx_init;
+ hc_evp->do_cipher = cipher_do_cipher;
+ hc_evp->cleanup = cipher_cleanup;
+ hc_evp->set_asn1_parameters = NULL;
+ hc_evp->get_asn1_parameters = NULL;
+ hc_evp->ctrl = cipher_ctrl;
+
+ /* Our link to the OpenSSL EVP_CIPHER */
+ hc_evp->app_data = (void *)ossl_evp;
+
+ /* Finally, set the static hc_EVP_CIPHER * to the one we just built */
+ *arg->hc_memoizep = hc_evp;
+}
+
+static const hc_EVP_CIPHER *
+get_EVP_CIPHER(heim_base_once_t *once, hc_EVP_CIPHER *hc_memoize,
+ const hc_EVP_CIPHER **hc_memoizep,
+ const hc_EVP_CIPHER *fallback,
+ unsigned long flags, int nid)
+{
+ struct once_init_cipher_ctx arg;
+
+ arg.flags = flags;
+ arg.hc_memoizep = hc_memoizep;
+ arg.hc_memoize = hc_memoize;
+ arg.fallback = fallback;
+ arg.nid = nid;
+ heim_base_once_f(once, &arg, get_EVP_CIPHER_once_cb);
+ return *hc_memoizep; /* May be NULL */
+}
+
+#define OSSL_CIPHER_ALGORITHM(name, flags) \
+ extern const hc_EVP_CIPHER *hc_EVP_hcrypto_##name(void); \
+ const hc_EVP_CIPHER *hc_EVP_ossl_##name(void) \
+ { \
+ static hc_EVP_CIPHER ossl_##name##_st; \
+ static const hc_EVP_CIPHER *ossl_##name; \
+ static heim_base_once_t once = HEIM_BASE_ONCE_INIT; \
+ return get_EVP_CIPHER(&once, &ossl_##name##_st, &ossl_##name, \
+ hc_EVP_hcrypto_##name(), \
+ flags, NID_##name); \
+ }
+
+/* As above, but for EVP_MDs */
+
+struct ossl_md_ctx {
+ EVP_MD_CTX *ossl_md_ctx; /* OpenSSL md ctx */
+ const EVP_MD *ossl_md; /* OpenSSL md */
+ int initialized;
+};
+
+static int
+ossl_md_init(struct ossl_md_ctx *ctx, const EVP_MD *md)
+{
+ if (ctx->initialized)
+ EVP_MD_CTX_free(ctx->ossl_md_ctx);
+ ctx->initialized = 0;
+
+ ctx->ossl_md = md;
+ ctx->ossl_md_ctx = EVP_MD_CTX_new();
+ if (!EVP_DigestInit(ctx->ossl_md_ctx, md)) {
+ EVP_MD_CTX_free(ctx->ossl_md_ctx);
+ ctx->ossl_md_ctx = NULL;
+ ctx->ossl_md = NULL;
+ return 0;
+ }
+ ctx->initialized = 1;
+ return 1;
+}
+
+static int
+ossl_md_update(hc_EVP_MD_CTX *d, const void *data, size_t count)
+{
+ struct ossl_md_ctx *ctx = (void *)d;
+
+ return EVP_DigestUpdate(ctx->ossl_md_ctx, data, count);
+}
+
+static int
+ossl_md_final(void *md_data, hc_EVP_MD_CTX *d)
+{
+ struct ossl_md_ctx *ctx = (void *)d;
+
+ return EVP_DigestFinal(ctx->ossl_md_ctx, md_data, NULL);
+}
+
+static int
+ossl_md_cleanup(hc_EVP_MD_CTX *d)
+{
+ struct ossl_md_ctx *ctx = (void *)d;
+
+ if (!ctx->initialized)
+ return 1;
+ EVP_MD_CTX_free(ctx->ossl_md_ctx);
+ ctx->ossl_md = NULL;
+ ctx->initialized = 0;
+
+ return 1;
+}
+
+struct once_init_md_ctx {
+ const EVP_MD **ossl_memoizep;
+ const hc_EVP_MD **hc_memoizep;
+ hc_EVP_MD *hc_memoize;
+ const hc_EVP_MD *fallback;
+ hc_evp_md_init md_init;
+ int nid;
+};
+
+static void
+get_EVP_MD_once_cb(void *d)
+{
+ struct once_init_md_ctx *arg = d;
+ const EVP_MD *ossl_evp;
+ hc_EVP_MD *hc_evp;
+
+ hc_evp = arg->hc_memoize;
+ *arg->ossl_memoizep = ossl_evp = EVP_get_digestbynid(arg->nid);
+
+ if (ossl_evp == NULL) {
+ (void) memset(hc_evp, 0, sizeof(*hc_evp));
+#if HCRYPTO_FALLBACK
+ *arg->hc_memoizep = arg->fallback;
+#endif
+ return;
+ }
+
+ /* Build the hc_EVP_MD */
+ hc_evp->block_size = EVP_MD_block_size(ossl_evp);
+ hc_evp->hash_size = EVP_MD_size(ossl_evp);
+ hc_evp->ctx_size = sizeof(struct ossl_md_ctx);
+ hc_evp->init = arg->md_init;
+ hc_evp->update = ossl_md_update;
+ hc_evp->final = ossl_md_final;
+ hc_evp->cleanup = ossl_md_cleanup;
+
+ *arg->hc_memoizep = hc_evp;
+}
+
+static const hc_EVP_MD *
+get_EVP_MD(heim_base_once_t *once, hc_EVP_MD *hc_memoize,
+ const hc_EVP_MD **hc_memoizep, const EVP_MD **ossl_memoizep,
+ const hc_EVP_MD *fallback,
+ hc_evp_md_init md_init, int nid)
+{
+ struct once_init_md_ctx ctx;
+
+ ctx.ossl_memoizep = ossl_memoizep;
+ ctx.hc_memoizep = hc_memoizep;
+ ctx.hc_memoize = hc_memoize;
+ ctx.fallback = fallback;
+ ctx.md_init = md_init;
+ ctx.nid = nid;
+ heim_base_once_f(once, &ctx, get_EVP_MD_once_cb);
+ return *hc_memoizep; /* May be NULL */
+}
+
+#define OSSL_MD_ALGORITHM(name) \
+ extern const hc_EVP_MD *hc_EVP_hcrypto_##name(void); \
+ static const EVP_MD *ossl_EVP_##name; \
+ static const hc_EVP_MD *ossl_##name; \
+ static int ossl_init_##name(hc_EVP_MD_CTX *d) \
+ { \
+ return ossl_md_init((void *)d, ossl_EVP_##name); \
+ } \
+ const hc_EVP_MD *hc_EVP_ossl_##name(void) \
+ { \
+ static hc_EVP_MD ossl_##name##_st; \
+ static heim_base_once_t once = HEIM_BASE_ONCE_INIT; \
+ return get_EVP_MD(&once, &ossl_##name##_st, &ossl_##name, \
+ &ossl_EVP_##name, hc_EVP_hcrypto_##name(), \
+ ossl_init_##name, NID_##name); \
+ }
+
+#else /* HAVE_HCRYPTO_W_OPENSSL */
+
+#include "evp-hcrypto.h"
+
+#define OSSL_CIPHER_ALGORITHM(name, flags) \
+ extern const hc_EVP_CIPHER *hc_EVP_ossl_##name(void); \
+ const hc_EVP_CIPHER *hc_EVP_ossl_##name(void) \
+ { \
+ return hc_EVP_hcrypto_##name(); \
+ }
+
+#define OSSL_MD_ALGORITHM(name) \
+ extern const hc_EVP_MD *hc_EVP_ossl_##name(void); \
+ const hc_EVP_MD *hc_EVP_ossl_##name(void) \
+ { \
+ return hc_EVP_hcrypto_##name(); \
+ }
+
+#endif /* HAVE_HCRYPTO_W_OPENSSL */
+
+/**
+ * The triple DES cipher type (OpenSSL provider)
+ *
+ * @return the DES-EDE3-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(des_ede3_cbc, hc_EVP_CIPH_CBC_MODE)
+
+/**
+ * The DES cipher type (OpenSSL provider)
+ *
+ * @return the DES-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(des_cbc, hc_EVP_CIPH_CBC_MODE)
+
+/**
+ * The AES-128 cipher type (OpenSSL provider)
+ *
+ * @return the AES-128-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(aes_128_cbc, hc_EVP_CIPH_CBC_MODE)
+
+/**
+ * The AES-192 cipher type (OpenSSL provider)
+ *
+ * @return the AES-192-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(aes_192_cbc, hc_EVP_CIPH_CBC_MODE)
+
+/**
+ * The AES-256 cipher type (OpenSSL provider)
+ *
+ * @return the AES-256-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(aes_256_cbc, hc_EVP_CIPH_CBC_MODE)
+
+/**
+ * The AES-128 CFB8 cipher type (OpenSSL provider)
+ *
+ * @return the AES-128-CFB8 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(aes_128_cfb8, hc_EVP_CIPH_CFB8_MODE)
+
+/**
+ * The AES-192 CFB8 cipher type (OpenSSL provider)
+ *
+ * @return the AES-192-CFB8 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(aes_192_cfb8, hc_EVP_CIPH_CFB8_MODE)
+
+/**
+ * The AES-256 CFB8 cipher type (OpenSSL provider)
+ *
+ * @return the AES-256-CFB8 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(aes_256_cfb8, hc_EVP_CIPH_CFB8_MODE)
+
+/*
+ * RC2 is only needed for tests of PKCS#12 support, which currently uses
+ * the RC2 PBE. So no RC2 -> tests fail.
+ */
+
+/**
+ * The RC2 cipher type - OpenSSL
+ *
+ * @return the RC2 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(rc2_cbc,
+ hc_EVP_CIPH_CBC_MODE |
+ hc_EVP_CIPH_VARIABLE_LENGTH)
+
+/**
+ * The RC2-40 cipher type - OpenSSL
+ *
+ * @return the RC2-40 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(rc2_40_cbc,
+ hc_EVP_CIPH_CBC_MODE)
+
+/**
+ * The RC2-64 cipher type - OpenSSL
+ *
+ * @return the RC2-64 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(rc2_64_cbc,
+ hc_EVP_CIPH_CBC_MODE |
+ hc_EVP_CIPH_VARIABLE_LENGTH)
+
+/**
+ * The Camellia-128 cipher type - OpenSSL
+ *
+ * @return the Camellia-128 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(camellia_128_cbc, hc_EVP_CIPH_CBC_MODE)
+
+/**
+ * The Camellia-198 cipher type - OpenSSL
+ *
+ * @return the Camellia-198 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(camellia_192_cbc, hc_EVP_CIPH_CBC_MODE)
+
+/**
+ * The Camellia-256 cipher type - OpenSSL
+ *
+ * @return the Camellia-256 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(camellia_256_cbc, hc_EVP_CIPH_CBC_MODE)
+
+/**
+ * The RC4 cipher type (OpenSSL provider)
+ *
+ * @return the RC4 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(rc4,
+ hc_EVP_CIPH_STREAM_CIPHER |
+ hc_EVP_CIPH_VARIABLE_LENGTH)
+
+/**
+ * The RC4-40 cipher type (OpenSSL provider)
+ *
+ * @return the RC4 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_CIPHER_ALGORITHM(rc4_40,
+ hc_EVP_CIPH_STREAM_CIPHER |
+ hc_EVP_CIPH_VARIABLE_LENGTH)
+
+/**
+ * The MD2 hash algorithm (OpenSSL provider)
+ *
+ * @return the MD2 EVP_MD pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_MD_ALGORITHM(md2)
+
+/**
+ * The MD4 hash algorithm (OpenSSL provider)
+ *
+ * @return the MD4 EVP_MD pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_MD_ALGORITHM(md4)
+
+/**
+ * The MD5 hash algorithm (OpenSSL provider)
+ *
+ * @return the MD5 EVP_MD pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_MD_ALGORITHM(md5)
+
+/**
+ * The SHA-1 hash algorithm (OpenSSL provider)
+ *
+ * @return the SHA-1 EVP_MD pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_MD_ALGORITHM(sha1)
+
+/**
+ * The SHA-256 hash algorithm (OpenSSL provider)
+ *
+ * @return the SHA-256 EVP_MD pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_MD_ALGORITHM(sha256)
+
+/**
+ * The SHA-384 hash algorithm (OpenSSL provider)
+ *
+ * @return the SHA-384 EVP_MD pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_MD_ALGORITHM(sha384)
+
+/**
+ * The SHA-512 hash algorithm (OpenSSL provider)
+ *
+ * @return the SHA-512 EVP_MD pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+OSSL_MD_ALGORITHM(sha512)
diff --git a/third_party/heimdal/lib/hcrypto/evp-openssl.h b/third_party/heimdal/lib/hcrypto/evp-openssl.h
new file mode 100644
index 0000000..225ff45
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp-openssl.h
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2009-2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_EVP_OSSL_H
+#define HEIM_EVP_OSSL_H 1
+
+/* symbol renaming */
+#define EVP_ossl_md2 hc_EVP_ossl_md2
+#define EVP_ossl_md4 hc_EVP_ossl_md4
+#define EVP_ossl_md5 hc_EVP_ossl_md5
+#define EVP_ossl_sha1 hc_EVP_ossl_sha1
+#define EVP_ossl_sha256 hc_EVP_ossl_sha256
+#define EVP_ossl_sha384 hc_EVP_ossl_sha384
+#define EVP_ossl_sha512 hc_EVP_ossl_sha512
+#define EVP_ossl_des_cbc hc_EVP_ossl_des_cbc
+#define EVP_ossl_des_ede3_cbc hc_EVP_ossl_des_ede3_cbc
+#define EVP_ossl_aes_128_cbc hc_EVP_ossl_aes_128_cbc
+#define EVP_ossl_aes_192_cbc hc_EVP_ossl_aes_192_cbc
+#define EVP_ossl_aes_256_cbc hc_EVP_ossl_aes_256_cbc
+#define EVP_ossl_aes_128_cfb8 hc_EVP_ossl_aes_128_cfb8
+#define EVP_ossl_aes_192_cfb8 hc_EVP_ossl_aes_192_cfb8
+#define EVP_ossl_aes_256_cfb8 hc_EVP_ossl_aes_256_cfb8
+#define EVP_ossl_rc4 hc_EVP_ossl_rc4
+#define EVP_ossl_rc4_40 hc_EVP_ossl_rc4_40
+#define EVP_ossl_rc2_40_cbc hc_EVP_ossl_rc2_40_cbc
+#define EVP_ossl_rc2_64_cbc hc_EVP_ossl_rc2_64_cbc
+#define EVP_ossl_rc2_cbc hc_EVP_ossl_rc2_cbc
+#define EVP_ossl_camellia_128_cbc hc_EVP_ossl_camellia_128_cbc
+#define EVP_ossl_camellia_192_cbc hc_EVP_ossl_camellia_192_cbc
+#define EVP_ossl_camellia_256_cbc hc_EVP_ossl_camellia_256_cbc
+
+/*
+ *
+ */
+
+HC_CPP_BEGIN
+
+const hc_EVP_MD * hc_EVP_ossl_md2(void);
+const hc_EVP_MD * hc_EVP_ossl_md4(void);
+const hc_EVP_MD * hc_EVP_ossl_md5(void);
+const hc_EVP_MD * hc_EVP_ossl_sha1(void);
+const hc_EVP_MD * hc_EVP_ossl_sha256(void);
+const hc_EVP_MD * hc_EVP_ossl_sha384(void);
+const hc_EVP_MD * hc_EVP_ossl_sha512(void);
+
+const hc_EVP_CIPHER * hc_EVP_ossl_rc2_cbc(void);
+const hc_EVP_CIPHER * hc_EVP_ossl_rc2_40_cbc(void);
+const hc_EVP_CIPHER * hc_EVP_ossl_rc2_64_cbc(void);
+
+const hc_EVP_CIPHER * hc_EVP_ossl_rc4(void);
+const hc_EVP_CIPHER * hc_EVP_ossl_rc4_40(void);
+
+const hc_EVP_CIPHER * hc_EVP_ossl_des_cbc(void);
+const hc_EVP_CIPHER * hc_EVP_ossl_des_ede3_cbc(void);
+
+const hc_EVP_CIPHER * hc_EVP_ossl_aes_128_cbc(void);
+const hc_EVP_CIPHER * hc_EVP_ossl_aes_192_cbc(void);
+const hc_EVP_CIPHER * hc_EVP_ossl_aes_256_cbc(void);
+
+const hc_EVP_CIPHER * hc_EVP_ossl_aes_128_cfb8(void);
+const hc_EVP_CIPHER * hc_EVP_ossl_aes_192_cfb8(void);
+const hc_EVP_CIPHER * hc_EVP_ossl_aes_256_cfb8(void);
+
+const hc_EVP_CIPHER * hc_EVP_ossl_camellia_128_cbc(void);
+const hc_EVP_CIPHER * hc_EVP_ossl_camellia_192_cbc(void);
+const hc_EVP_CIPHER * hc_EVP_ossl_camellia_256_cbc(void);
+
+HC_CPP_END
+
+#endif /* HEIM_EVP_OSSL_H */
diff --git a/third_party/heimdal/lib/hcrypto/evp-pkcs11.c b/third_party/heimdal/lib/hcrypto/evp-pkcs11.c
new file mode 100644
index 0000000..b44871f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp-pkcs11.c
@@ -0,0 +1,832 @@
+/*
+ * Copyright (c) 2015-2016, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* PKCS#11 provider */
+
+#include <config.h>
+#include <roken.h>
+#include <assert.h>
+
+#ifndef HAVE_DLFCN_H
+#error PKCS11 support requires dlfcn.h
+#endif
+
+#include <heimbase.h>
+
+#include <evp.h>
+#include <evp-hcrypto.h>
+#include <evp-pkcs11.h>
+
+#include <ref/pkcs11.h>
+
+#if __sun && !defined(PKCS11_MODULE_PATH)
+# ifdef _LP64
+# define PKCS11_MODULE_PATH "/usr/lib/64/libpkcs11.so"
+# else
+# define PKCS11_MODULE_PATH "/usr/lib/libpkcs11.so"
+# endif
+#elif defined(__linux__)
+/*
+ * XXX We should have an autoconf check for OpenCryptoki and such
+ * things. However, there's no AC_CHECK_OBJECT(), and we'd have to
+ * write one. Today I'm feeling lazy. Another possibility would be to
+ * have a symlink from the libdir we'll install into, and then we could
+ * dlopen() that on all platforms.
+ *
+ * XXX Also, we should pick an appropriate shared object based on 32- vs
+ * 64-bits.
+ */
+# define PKCS11_MODULE_PATH "/usr/lib/pkcs11/PKCS11_API.so"
+#endif
+
+static CK_FUNCTION_LIST_PTR p11_module;
+
+static int
+p11_cleanup(EVP_CIPHER_CTX *ctx);
+
+struct pkcs11_cipher_ctx {
+ CK_SESSION_HANDLE hSession;
+ CK_OBJECT_HANDLE hSecret;
+};
+
+struct pkcs11_md_ctx {
+ CK_SESSION_HANDLE hSession;
+};
+
+static void *pkcs11_module_handle;
+
+static CK_RV
+p11_module_load(CK_FUNCTION_LIST_PTR_PTR ppFunctionList)
+{
+ CK_RV rv;
+ CK_RV (*C_GetFunctionList_fn)(CK_FUNCTION_LIST_PTR_PTR);
+ char *pkcs11ModulePath = secure_getenv("PKCS11_MODULE_PATH");
+
+ *ppFunctionList = NULL;
+
+ if (pkcs11ModulePath != NULL) {
+ pkcs11_module_handle =
+ dlopen(pkcs11ModulePath,
+ RTLD_LAZY | RTLD_LOCAL | RTLD_GROUP | RTLD_NODELETE);
+ if (pkcs11_module_handle == NULL)
+ fprintf(stderr, "p11_module_load(%s): %s\n", pkcs11ModulePath, dlerror());
+ }
+#ifdef PKCS11_MODULE_PATH
+ if (pkcs11_module_handle == NULL) {
+ pkcs11_module_handle =
+ dlopen(PKCS11_MODULE_PATH,
+ RTLD_LAZY | RTLD_LOCAL | RTLD_GROUP | RTLD_NODELETE);
+ if (pkcs11_module_handle == NULL)
+ fprintf(stderr, "p11_module_load(%s): %s\n", PKCS11_MODULE_PATH, dlerror());
+ }
+#endif
+ if (pkcs11_module_handle == NULL)
+ return CKR_LIBRARY_LOAD_FAILED;
+
+ C_GetFunctionList_fn = (CK_RV (*)(CK_FUNCTION_LIST_PTR_PTR))
+ dlsym(pkcs11_module_handle, "C_GetFunctionList");
+ if (C_GetFunctionList_fn == NULL) {
+ dlclose(pkcs11_module_handle);
+ return CKR_LIBRARY_LOAD_FAILED;
+ }
+
+ rv = C_GetFunctionList_fn(ppFunctionList);
+ if (rv != CKR_OK) {
+ dlclose(pkcs11_module_handle);
+ return rv;
+ }
+
+ return CKR_OK;
+}
+
+static void
+p11_module_load_once(void *context)
+{
+ p11_module_load((CK_FUNCTION_LIST_PTR_PTR)context);
+}
+
+static CK_RV
+p11_module_init(void)
+{
+ static heim_base_once_t once = HEIM_BASE_ONCE_INIT;
+ CK_RV rv;
+
+ heim_base_once_f(&once, &p11_module, p11_module_load_once);
+
+ if (p11_module == NULL)
+ return CKR_LIBRARY_LOAD_FAILED;
+
+ /*
+ * Call C_Initialize() on every call, because it will be invalid after fork().
+ * Caching the initialization status using a once control and invalidating it
+ * on fork provided no measurable performance benefit on Solaris 11. Other
+ * approaches would not be thread-safe or would involve more intrusive code
+ * changes, such as exposing heimbase's atomics.
+ */
+ rv = p11_module->C_Initialize(NULL);
+ if (rv == CKR_CRYPTOKI_ALREADY_INITIALIZED)
+ rv = CKR_OK;
+
+ return rv;
+}
+
+static CK_RV
+p11_session_init(CK_MECHANISM_TYPE mechanismType,
+ CK_SESSION_HANDLE_PTR phSession,
+ CK_FLAGS *pFlags)
+{
+ CK_RV rv;
+ CK_ULONG i, ulSlotCount = 0;
+ CK_SLOT_ID_PTR pSlotList = NULL;
+ CK_MECHANISM_INFO info;
+
+ if (phSession != NULL)
+ *phSession = CK_INVALID_HANDLE;
+
+ *pFlags = 0;
+
+ rv = p11_module_init();
+ if (rv != CKR_OK)
+ goto cleanup;
+
+ assert(p11_module != NULL);
+
+ rv = p11_module->C_GetSlotList(CK_FALSE, NULL, &ulSlotCount);
+ if (rv != CKR_OK)
+ goto cleanup;
+
+ pSlotList = (CK_SLOT_ID_PTR)calloc(ulSlotCount, sizeof(CK_SLOT_ID));
+ if (pSlotList == NULL) {
+ rv = CKR_HOST_MEMORY;
+ goto cleanup;
+ }
+
+ rv = p11_module->C_GetSlotList(CK_FALSE, pSlotList, &ulSlotCount);
+ if (rv != CKR_OK)
+ goto cleanup;
+
+ /*
+ * Note that this approach of using the first slot that supports the desired
+ * mechanism may not always be what the user wants (for example it may prefer
+ * software to hardware crypto). We're going to assume that this code will be
+ * principally used on Solaris (which has a meta-slot provider that sorts by
+ * hardware first) or in situations where the user can configure the slots in
+ * order of provider preference. In the future we should make this configurable.
+ */
+ for (i = 0; i < ulSlotCount; i++) {
+ rv = p11_module->C_GetMechanismInfo(pSlotList[i], mechanismType, &info);
+ if (rv == CKR_OK) {
+ *pFlags = info.flags;
+ break;
+ }
+ }
+
+ if (i == ulSlotCount) {
+ rv = CKR_MECHANISM_INVALID;
+ goto cleanup;
+ }
+
+ if (phSession != NULL) {
+ rv = p11_module->C_OpenSession(pSlotList[i], CKF_SERIAL_SESSION, NULL, NULL, phSession);
+ if (rv != CKR_OK)
+ goto cleanup;
+ }
+
+cleanup:
+ free(pSlotList);
+
+ return rv;
+}
+
+static int
+p11_mech_available_p(CK_MECHANISM_TYPE mechanismType, CK_FLAGS reqFlags)
+{
+ CK_RV rv;
+ CK_FLAGS flags;
+
+ rv = p11_session_init(mechanismType, NULL, &flags);
+ if (rv != CKR_OK)
+ return 0;
+
+ return (flags & reqFlags) == reqFlags;
+}
+
+static CK_KEY_TYPE
+p11_key_type_for_mech(CK_MECHANISM_TYPE mechanismType)
+{
+ CK_KEY_TYPE keyType = 0;
+
+ switch (mechanismType) {
+ case CKM_RC2_CBC:
+ keyType = CKK_RC2;
+ break;
+ case CKM_RC4:
+ keyType = CKK_RC4;
+ break;
+ case CKM_DES_CBC:
+ keyType = CKK_DES;
+ break;
+ case CKM_DES3_CBC:
+ keyType = CKK_DES3;
+ break;
+ case CKM_AES_CBC:
+ case CKM_AES_CFB8:
+ keyType = CKK_AES;
+ break;
+ case CKM_CAMELLIA_CBC:
+ keyType = CKK_CAMELLIA;
+ break;
+ default:
+ assert(0 && "Unknown PKCS#11 mechanism type");
+ break;
+ }
+
+ return keyType;
+}
+
+static int
+p11_key_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char *key,
+ const unsigned char *iv,
+ int encp)
+{
+ CK_RV rv;
+ CK_BBOOL bFalse = CK_FALSE;
+ CK_BBOOL bTrue = CK_TRUE;
+ CK_MECHANISM_TYPE mechanismType = (CK_MECHANISM_TYPE)ctx->cipher->app_data;
+ CK_KEY_TYPE keyType = p11_key_type_for_mech(mechanismType);
+ CK_OBJECT_CLASS objectClass = CKO_SECRET_KEY;
+ CK_ATTRIBUTE_TYPE op = encp ? CKA_ENCRYPT : CKA_DECRYPT;
+ CK_ATTRIBUTE attributes[] = {
+ { CKA_EXTRACTABLE, &bFalse, sizeof(bFalse) },
+ { CKA_CLASS, &objectClass, sizeof(objectClass) },
+ { CKA_KEY_TYPE, &keyType, sizeof(keyType) },
+ { CKA_TOKEN, &bFalse, sizeof(bFalse) },
+ { CKA_PRIVATE, &bFalse, sizeof(bFalse) },
+ { CKA_SENSITIVE, &bTrue, sizeof(bTrue) },
+ { CKA_VALUE, (void *)key, ctx->key_len },
+ { op, &bTrue, sizeof(bTrue) }
+ };
+ CK_MECHANISM mechanism = {
+ mechanismType,
+ ctx->cipher->iv_len ? ctx->iv : NULL,
+ ctx->cipher->iv_len
+ };
+ struct pkcs11_cipher_ctx *p11ctx = (struct pkcs11_cipher_ctx *)ctx->cipher_data;
+ CK_FLAGS flags;
+
+ rv = CKR_OK;
+
+ if (p11ctx->hSession != CK_INVALID_HANDLE && key != NULL)
+ p11_cleanup(ctx); /* refresh session with new key */
+
+ if (p11ctx->hSession == CK_INVALID_HANDLE) {
+ rv = p11_session_init(mechanismType, &p11ctx->hSession, &flags);
+ if (rv != CKR_OK)
+ goto cleanup;
+
+ if ((flags & (CKF_ENCRYPT|CKF_DECRYPT)) != (CKF_ENCRYPT|CKF_DECRYPT)) {
+ rv = CKR_MECHANISM_INVALID;
+ goto cleanup;
+ }
+ }
+
+ if (key != NULL) {
+ assert(p11_module != NULL);
+ assert(p11ctx->hSecret == CK_INVALID_HANDLE);
+
+ rv = p11_module->C_CreateObject(p11ctx->hSession, attributes,
+ sizeof(attributes) / sizeof(attributes[0]),
+ &p11ctx->hSecret);
+ if (rv != CKR_OK)
+ goto cleanup;
+ }
+
+ if (p11ctx->hSecret != CK_INVALID_HANDLE) {
+ if (op == CKA_ENCRYPT)
+ rv = p11_module->C_EncryptInit(p11ctx->hSession, &mechanism, p11ctx->hSecret);
+ else
+ rv = p11_module->C_DecryptInit(p11ctx->hSession, &mechanism, p11ctx->hSecret);
+ if (rv != CKR_OK)
+ goto cleanup;
+ }
+
+cleanup:
+ if (rv != CKR_OK)
+ p11_cleanup(ctx);
+
+ return rv == CKR_OK;
+}
+
+static int
+p11_do_cipher(EVP_CIPHER_CTX *ctx,
+ unsigned char *out,
+ const unsigned char *in,
+ unsigned int size)
+{
+ struct pkcs11_cipher_ctx *p11ctx = (struct pkcs11_cipher_ctx *)ctx->cipher_data;
+ CK_RV rv;
+ CK_ULONG ulCipherTextLen = size;
+
+ assert(p11_module != NULL);
+ assert(EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_STREAM_CIPHER ||
+ (size % ctx->cipher->block_size) == 0);
+
+ if (ctx->encrypt)
+ rv = p11_module->C_EncryptUpdate(p11ctx->hSession, (unsigned char *)in, size, out, &ulCipherTextLen);
+ else
+ rv = p11_module->C_DecryptUpdate(p11ctx->hSession, (unsigned char *)in, size, out, &ulCipherTextLen);
+
+ return rv == CKR_OK;
+}
+
+static int
+p11_cleanup(EVP_CIPHER_CTX *ctx)
+{
+ struct pkcs11_cipher_ctx *p11ctx = (struct pkcs11_cipher_ctx *)ctx->cipher_data;
+
+ if (p11ctx->hSecret != CK_INVALID_HANDLE) {
+ p11_module->C_DestroyObject(p11ctx->hSession, p11ctx->hSecret);
+ p11ctx->hSecret = CK_INVALID_HANDLE;
+ }
+ if (p11ctx->hSession != CK_INVALID_HANDLE) {
+ p11_module->C_CloseSession(p11ctx->hSession);
+ p11ctx->hSession = CK_INVALID_HANDLE;
+ }
+
+ return 1;
+}
+
+static int
+p11_md_cleanup(EVP_MD_CTX *ctx);
+
+static int
+p11_md_hash_init(CK_MECHANISM_TYPE mechanismType, EVP_MD_CTX *ctx)
+{
+ struct pkcs11_md_ctx *p11ctx = (struct pkcs11_md_ctx *)ctx;
+ CK_RV rv;
+ CK_FLAGS flags;
+ CK_MECHANISM mechanism = { mechanismType, NULL, 0 };
+
+ if (p11ctx->hSession != CK_INVALID_HANDLE)
+ p11_md_cleanup(ctx);
+
+ rv = p11_session_init(mechanismType, &p11ctx->hSession, &flags);
+ if (rv != CKR_OK)
+ goto cleanup;
+
+ if ((flags & CKF_DIGEST) != CKF_DIGEST) {
+ rv = CKR_MECHANISM_INVALID;
+ goto cleanup;
+ }
+
+ assert(p11_module != NULL);
+
+ rv = p11_module->C_DigestInit(p11ctx->hSession, &mechanism);
+
+ cleanup:
+ return rv == CKR_OK;
+}
+
+static int
+p11_md_update(EVP_MD_CTX *ctx, const void *data, size_t length)
+{
+ struct pkcs11_md_ctx *p11ctx = (struct pkcs11_md_ctx *)ctx;
+ CK_RV rv;
+
+ assert(p11_module != NULL);
+ assert(data != NULL || length == 0);
+
+ rv = p11_module->C_DigestUpdate(p11ctx->hSession,
+ data ? (CK_BYTE_PTR)data : (CK_BYTE_PTR)"",
+ length);
+
+ return rv == CKR_OK;
+}
+
+static int
+p11_md_final(void *digest, EVP_MD_CTX *ctx)
+{
+ struct pkcs11_md_ctx *p11ctx = (struct pkcs11_md_ctx *)ctx;
+ CK_RV rv;
+ CK_ULONG digestLen = 0;
+
+ assert(p11_module != NULL);
+
+ rv = p11_module->C_DigestFinal(p11ctx->hSession, NULL, &digestLen);
+ if (rv == CKR_OK)
+ rv = p11_module->C_DigestFinal(p11ctx->hSession, digest, &digestLen);
+
+ return rv == CKR_OK;
+}
+
+static int
+p11_md_cleanup(EVP_MD_CTX *ctx)
+{
+ struct pkcs11_md_ctx *p11ctx = (struct pkcs11_md_ctx *)ctx;
+ CK_RV rv;
+
+ assert(p11_module != NULL);
+
+ rv = p11_module->C_CloseSession(p11ctx->hSession);
+ if (rv == CKR_OK)
+ p11ctx->hSession = CK_INVALID_HANDLE;
+
+ return rv == CKR_OK;
+}
+
+#define PKCS11_CIPHER_ALGORITHM(name, mechanismType, block_size, \
+ key_len, iv_len, flags) \
+ \
+ static EVP_CIPHER \
+ pkcs11_##name = { \
+ 0, \
+ block_size, \
+ key_len, \
+ iv_len, \
+ (flags) | EVP_CIPH_ALWAYS_CALL_INIT, \
+ p11_key_init, \
+ p11_do_cipher, \
+ p11_cleanup, \
+ sizeof(struct pkcs11_cipher_ctx), \
+ NULL, \
+ NULL, \
+ NULL, \
+ (void *)mechanismType \
+ }; \
+ \
+ const EVP_CIPHER * \
+ hc_EVP_pkcs11_##name(void) \
+ { \
+ if (p11_mech_available_p(mechanismType, CKF_ENCRYPT|CKF_DECRYPT)) \
+ return &pkcs11_##name; \
+ else \
+ return NULL; \
+ } \
+ \
+ static void \
+ pkcs11_hcrypto_##name##_init_once(void *context) \
+ { \
+ const EVP_CIPHER *cipher; \
+ \
+ cipher = hc_EVP_pkcs11_ ##name(); \
+ if (cipher == NULL && HCRYPTO_FALLBACK) \
+ cipher = hc_EVP_hcrypto_ ##name(); \
+ \
+ *((const EVP_CIPHER **)context) = cipher; \
+ } \
+ \
+ const EVP_CIPHER * \
+ hc_EVP_pkcs11_hcrypto_##name(void) \
+ { \
+ static const EVP_CIPHER *__cipher; \
+ static heim_base_once_t __init = HEIM_BASE_ONCE_INIT; \
+ \
+ heim_base_once_f(&__init, &__cipher, \
+ pkcs11_hcrypto_##name##_init_once); \
+ \
+ return __cipher; \
+ }
+
+#define PKCS11_MD_ALGORITHM(name, mechanismType, hash_size, block_size) \
+ \
+ static int p11_##name##_init(EVP_MD_CTX *ctx) \
+ { \
+ return p11_md_hash_init(mechanismType, ctx); \
+ } \
+ \
+ const EVP_MD * \
+ hc_EVP_pkcs11_##name(void) \
+ { \
+ static struct hc_evp_md name = { \
+ hash_size, \
+ block_size, \
+ sizeof(struct pkcs11_md_ctx), \
+ p11_##name##_init, \
+ p11_md_update, \
+ p11_md_final, \
+ p11_md_cleanup \
+ }; \
+ \
+ if (p11_mech_available_p(mechanismType, CKF_DIGEST)) \
+ return &name; \
+ else \
+ return NULL; \
+ } \
+ \
+ static void \
+ pkcs11_hcrypto_##name##_init_once(void *context) \
+ { \
+ const EVP_MD *md; \
+ \
+ md = hc_EVP_pkcs11_ ##name(); \
+ if (md == NULL && HCRYPTO_FALLBACK) \
+ md = hc_EVP_hcrypto_ ##name(); \
+ \
+ *((const EVP_MD **)context) = md; \
+ } \
+ \
+ const EVP_MD * \
+ hc_EVP_pkcs11_hcrypto_##name(void) \
+ { \
+ static const EVP_MD *__md; \
+ static heim_base_once_t __init = HEIM_BASE_ONCE_INIT; \
+ \
+ heim_base_once_f(&__init, &__md, \
+ pkcs11_hcrypto_##name##_init_once); \
+ \
+ return __md; \
+ }
+
+#define PKCS11_MD_ALGORITHM_UNAVAILABLE(name) \
+ \
+ const EVP_MD * \
+ hc_EVP_pkcs11_##name(void) \
+ { \
+ return NULL; \
+ } \
+ \
+ const EVP_MD * \
+ hc_EVP_pkcs11_hcrypto_##name(void) \
+ { \
+ return hc_EVP_hcrypto_ ##name(); \
+ }
+
+/**
+ * The triple DES cipher type (PKCS#11 provider)
+ *
+ * @return the DES-EDE3-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(des_ede3_cbc,
+ CKM_DES3_CBC,
+ 8,
+ 24,
+ 8,
+ EVP_CIPH_CBC_MODE)
+
+/**
+ * The DES cipher type (PKCS#11 provider)
+ *
+ * @return the DES-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(des_cbc,
+ CKM_DES_CBC,
+ 8,
+ 8,
+ 8,
+ EVP_CIPH_CBC_MODE)
+
+/**
+ * The AES-128 cipher type (PKCS#11 provider)
+ *
+ * @return the AES-128-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(aes_128_cbc,
+ CKM_AES_CBC,
+ 16,
+ 16,
+ 16,
+ EVP_CIPH_CBC_MODE)
+
+/**
+ * The AES-192 cipher type (PKCS#11 provider)
+ *
+ * @return the AES-192-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(aes_192_cbc,
+ CKM_AES_CBC,
+ 16,
+ 24,
+ 16,
+ EVP_CIPH_CBC_MODE)
+
+/**
+ * The AES-256 cipher type (PKCS#11 provider)
+ *
+ * @return the AES-256-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(aes_256_cbc,
+ CKM_AES_CBC,
+ 16,
+ 32,
+ 16,
+ EVP_CIPH_CBC_MODE)
+
+/**
+ * The AES-128 CFB8 cipher type (PKCS#11 provider)
+ *
+ * @return the AES-128-CFB8 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(aes_128_cfb8,
+ CKM_AES_CFB8,
+ 16,
+ 16,
+ 16,
+ EVP_CIPH_CFB8_MODE)
+
+/**
+ * The AES-192 CFB8 cipher type (PKCS#11 provider)
+ *
+ * @return the AES-192-CFB8 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(aes_192_cfb8,
+ CKM_AES_CFB8,
+ 16,
+ 24,
+ 16,
+ EVP_CIPH_CFB8_MODE)
+
+/**
+ * The AES-256 CFB8 cipher type (PKCS#11 provider)
+ *
+ * @return the AES-256-CFB8 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(aes_256_cfb8,
+ CKM_AES_CFB8,
+ 16,
+ 32,
+ 16,
+ EVP_CIPH_CFB8_MODE)
+
+/**
+ * The RC2 cipher type - PKCS#11
+ *
+ * @return the RC2 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(rc2_cbc,
+ CKM_RC2_CBC,
+ 8,
+ 16,
+ 8,
+ EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH)
+
+/**
+ * The RC2-40 cipher type - PKCS#11
+ *
+ * @return the RC2-40 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(rc2_40_cbc,
+ CKM_RC2_CBC,
+ 8,
+ 5,
+ 8,
+ EVP_CIPH_CBC_MODE)
+
+/**
+ * The RC2-64 cipher type - PKCS#11
+ *
+ * @return the RC2-64 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(rc2_64_cbc,
+ CKM_RC2_CBC,
+ 8,
+ 8,
+ 8,
+ EVP_CIPH_CBC_MODE)
+
+/**
+ * The Camellia-128 cipher type - PKCS#11
+ *
+ * @return the Camellia-128 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(camellia_128_cbc,
+ CKM_CAMELLIA_CBC,
+ 16,
+ 16,
+ 16,
+ EVP_CIPH_CBC_MODE)
+
+/**
+ * The Camellia-198 cipher type - PKCS#11
+ *
+ * @return the Camellia-198 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(camellia_192_cbc,
+ CKM_CAMELLIA_CBC,
+ 16,
+ 24,
+ 16,
+ EVP_CIPH_CBC_MODE)
+
+/**
+ * The Camellia-256 cipher type - PKCS#11
+ *
+ * @return the Camellia-256 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(camellia_256_cbc,
+ CKM_CAMELLIA_CBC,
+ 16,
+ 32,
+ 16,
+ EVP_CIPH_CBC_MODE)
+
+/**
+ * The RC4 cipher type (PKCS#11 provider)
+ *
+ * @return the RC4 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(rc4,
+ CKM_RC4,
+ 1,
+ 16,
+ 0,
+ EVP_CIPH_STREAM_CIPHER | EVP_CIPH_VARIABLE_LENGTH)
+
+/**
+ * The RC4-40 cipher type (PKCS#11 provider)
+ *
+ * @return the RC4 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+PKCS11_CIPHER_ALGORITHM(rc4_40,
+ CKM_RC4,
+ 1,
+ 5,
+ 0,
+ EVP_CIPH_STREAM_CIPHER | EVP_CIPH_VARIABLE_LENGTH)
+
+PKCS11_MD_ALGORITHM(md2, CKM_MD2, 16, 16)
+#ifdef CKM_MD4 /* non-standard extension */
+PKCS11_MD_ALGORITHM(md4, CKM_MD4, 16, 64)
+#else
+PKCS11_MD_ALGORITHM_UNAVAILABLE(md4)
+#endif
+PKCS11_MD_ALGORITHM(md5, CKM_MD5, 16, 64)
+PKCS11_MD_ALGORITHM(sha1, CKM_SHA_1, 20, 64)
+PKCS11_MD_ALGORITHM(sha256, CKM_SHA256, 32, 64)
+PKCS11_MD_ALGORITHM(sha384, CKM_SHA384, 48, 128)
+PKCS11_MD_ALGORITHM(sha512, CKM_SHA512, 64, 128)
diff --git a/third_party/heimdal/lib/hcrypto/evp-pkcs11.h b/third_party/heimdal/lib/hcrypto/evp-pkcs11.h
new file mode 100644
index 0000000..6d8a21f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp-pkcs11.h
@@ -0,0 +1,157 @@
+/*
+ * Copyright (c) 2015, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_EVP_PKCS11_H
+#define HEIM_EVP_PKCS11_H 1
+
+/* symbol renaming */
+
+#define EVP_pkcs11_md2() hc_EVP_pkcs11_md2()
+#define EVP_pkcs11_md4() hc_EVP_pkcs11_md4()
+#define EVP_pkcs11_md5() hc_EVP_pkcs11_md5()
+#define EVP_pkcs11_sha1() hc_EVP_pkcs11_sha1()
+#define EVP_pkcs11_sha256() hc_EVP_pkcs11_sha256()
+#define EVP_pkcs11_sha384() hc_EVP_pkcs11_sha384()
+#define EVP_pkcs11_sha512() hc_EVP_pkcs11_sha512()
+#define EVP_pkcs11_des_cbc() hc_EVP_pkcs11_des_cbc()
+#define EVP_pkcs11_des_ede3_cbc() hc_EVP_pkcs11_des_ede3_cbc()
+#define EVP_pkcs11_aes_128_cbc() hc_EVP_pkcs11_aes_128_cbc()
+#define EVP_pkcs11_aes_192_cbc() hc_EVP_pkcs11_aes_192_cbc()
+#define EVP_pkcs11_aes_256_cbc() hc_EVP_pkcs11_aes_256_cbc()
+#define EVP_pkcs11_aes_128_cfb8() hc_EVP_pkcs11_aes_128_cfb8()
+#define EVP_pkcs11_aes_192_cfb8() hc_EVP_pkcs11_aes_192_cfb8()
+#define EVP_pkcs11_aes_256_cfb8() hc_EVP_pkcs11_aes_256_cfb8()
+#define EVP_pkcs11_rc4() hc_EVP_pkcs11_rc4()
+#define EVP_pkcs11_rc4_40() hc_EVP_pkcs11_rc4_40()
+#define EVP_pkcs11_rc2_40_cbc() hc_EVP_pkcs11_rc2_40_cbc()
+#define EVP_pkcs11_rc2_64_cbc() hc_EVP_pkcs11_rc2_64_cbc()
+#define EVP_pkcs11_rc2_cbc() hc_EVP_pkcs11_rc2_cbc()
+#define EVP_pkcs11_camellia_128_cbc() hc_EVP_pkcs11_camellia_128_cbc()
+#define EVP_pkcs11_camellia_192_cbc() hc_EVP_pkcs11_camellia_192_cbc()
+#define EVP_pkcs11_camellia_256_cbc() hc_EVP_pkcs11_camellia_256_cbc()
+
+#define EVP_pkcs11_hcrypto_md2() hc_EVP_pkcs11_hcrypto_md2()
+#define EVP_pkcs11_hcrypto_md4() hc_EVP_pkcs11_hcrypto_md4()
+#define EVP_pkcs11_hcrypto_md5() hc_EVP_pkcs11_hcrypto_md5()
+#define EVP_pkcs11_hcrypto_sha1() hc_EVP_pkcs11_hcrypto_sha1()
+#define EVP_pkcs11_hcrypto_sha256() hc_EVP_pkcs11_hcrypto_sha256()
+#define EVP_pkcs11_hcrypto_sha384() hc_EVP_pkcs11_hcrypto_sha384()
+#define EVP_pkcs11_hcrypto_sha512() hc_EVP_pkcs11_hcrypto_sha512()
+#define EVP_pkcs11_hcrypto_des_cbc() hc_EVP_pkcs11_hcrypto_des_cbc()
+#define EVP_pkcs11_hcrypto_des_ede3_cbc() hc_EVP_pkcs11_hcrypto_des_ede3_cbc()
+#define EVP_pkcs11_hcrypto_aes_128_cbc() hc_EVP_pkcs11_hcrypto_aes_128_cbc()
+#define EVP_pkcs11_hcrypto_aes_192_cbc() hc_EVP_pkcs11_hcrypto_aes_192_cbc()
+#define EVP_pkcs11_hcrypto_aes_256_cbc() hc_EVP_pkcs11_hcrypto_aes_256_cbc()
+#define EVP_pkcs11_hcrypto_aes_128_cfb8() hc_EVP_pkcs11_hcrypto_aes_128_cfb8()
+#define EVP_pkcs11_hcrypto_aes_192_cfb8() hc_EVP_pkcs11_hcrypto_aes_192_cfb8()
+#define EVP_pkcs11_hcrypto_aes_256_cfb8() hc_EVP_pkcs11_hcrypto_aes_256_cfb8()
+#define EVP_pkcs11_hcrypto_rc4() hc_EVP_pkcs11_hcrypto_rc4()
+#define EVP_pkcs11_hcrypto_rc4_40() hc_EVP_pkcs11_hcrypto_rc4_40()
+#define EVP_pkcs11_hcrypto_rc2_40_cbc() hc_EVP_pkcs11_hcrypto_rc2_40_cbc()
+#define EVP_pkcs11_hcrypto_rc2_64_cbc() hc_EVP_pkcs11_hcrypto_rc2_64_cbc()
+#define EVP_pkcs11_hcrypto_rc2_cbc() hc_EVP_pkcs11_hcrypto_rc2_cbc()
+#define EVP_pkcs11_hcrypto_camellia_128_cbc() hc_EVP_pkcs11_hcrypto_camellia_128_cbc()
+#define EVP_pkcs11_hcrypto_camellia_192_cbc() hc_EVP_pkcs11_hcrypto_camellia_192_cbc()
+#define EVP_pkcs11_hcrypto_camellia_256_cbc() hc_EVP_pkcs11_hcrypto_camellia_256_cbc()
+
+HC_CPP_BEGIN
+
+/*
+ * Strict PKCS#11 implementations (these will return NULL if the underlying
+ * PKCS#11 implementation does not implement the cipher or hash).
+ */
+const EVP_MD * hc_EVP_pkcs11_md2(void);
+const EVP_MD * hc_EVP_pkcs11_md4(void);
+const EVP_MD * hc_EVP_pkcs11_md5(void);
+const EVP_MD * hc_EVP_pkcs11_sha1(void);
+const EVP_MD * hc_EVP_pkcs11_sha256(void);
+const EVP_MD * hc_EVP_pkcs11_sha384(void);
+const EVP_MD * hc_EVP_pkcs11_sha512(void);
+
+const EVP_CIPHER * hc_EVP_pkcs11_rc2_cbc(void);
+const EVP_CIPHER * hc_EVP_pkcs11_rc2_40_cbc(void);
+const EVP_CIPHER * hc_EVP_pkcs11_rc2_64_cbc(void);
+
+const EVP_CIPHER * hc_EVP_pkcs11_rc4(void);
+const EVP_CIPHER * hc_EVP_pkcs11_rc4_40(void);
+
+const EVP_CIPHER * hc_EVP_pkcs11_des_cbc(void);
+const EVP_CIPHER * hc_EVP_pkcs11_des_ede3_cbc(void);
+
+const EVP_CIPHER * hc_EVP_pkcs11_aes_128_cbc(void);
+const EVP_CIPHER * hc_EVP_pkcs11_aes_192_cbc(void);
+const EVP_CIPHER * hc_EVP_pkcs11_aes_256_cbc(void);
+
+const EVP_CIPHER * hc_EVP_pkcs11_aes_128_cfb8(void);
+const EVP_CIPHER * hc_EVP_pkcs11_aes_192_cfb8(void);
+const EVP_CIPHER * hc_EVP_pkcs11_aes_256_cfb8(void);
+
+const EVP_CIPHER * hc_EVP_pkcs11_camellia_128_cbc(void);
+const EVP_CIPHER * hc_EVP_pkcs11_camellia_192_cbc(void);
+const EVP_CIPHER * hc_EVP_pkcs11_camellia_256_cbc(void);
+
+/*
+ * PKCS#11 implementations with fallback to hcrypto.
+ */
+const EVP_MD * hc_EVP_pkcs11_hcrypto_md2(void);
+const EVP_MD * hc_EVP_pkcs11_hcrypto_md4(void);
+const EVP_MD * hc_EVP_pkcs11_hcrypto_md5(void);
+const EVP_MD * hc_EVP_pkcs11_hcrypto_sha1(void);
+const EVP_MD * hc_EVP_pkcs11_hcrypto_sha256(void);
+const EVP_MD * hc_EVP_pkcs11_hcrypto_sha384(void);
+const EVP_MD * hc_EVP_pkcs11_hcrypto_sha512(void);
+
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_rc2_cbc(void);
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_rc2_40_cbc(void);
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_rc2_64_cbc(void);
+
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_rc4(void);
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_rc4_40(void);
+
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_des_cbc(void);
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_des_ede3_cbc(void);
+
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_aes_128_cbc(void);
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_aes_192_cbc(void);
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_aes_256_cbc(void);
+
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_aes_128_cfb8(void);
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_aes_192_cfb8(void);
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_aes_256_cfb8(void);
+
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_camellia_128_cbc(void);
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_camellia_192_cbc(void);
+const EVP_CIPHER * hc_EVP_pkcs11_hcrypto_camellia_256_cbc(void);
+
+HC_CPP_END
+
+#endif /* HEIM_EVP_PKCS11_H */
diff --git a/third_party/heimdal/lib/hcrypto/evp-w32.c b/third_party/heimdal/lib/hcrypto/evp-w32.c
new file mode 100644
index 0000000..7d14d1f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp-w32.c
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2015, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Windows fallback provider: decides whether to use hcrypto or
+ * wincng depending on whether bcrypt.dll is available (i.e. it
+ * is runtime compatible back to XP, but will use the native
+ * crypto APIs from Vista onwards).
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <assert.h>
+
+#include <evp.h>
+#include <evp-w32.h>
+#include <evp-hcrypto.h>
+
+#include <evp-wincng.h>
+
+static LONG wincng_available = -1;
+
+static __inline int
+wincng_check_availability(void)
+{
+ if (wincng_available == -1) {
+ char szBCryptDllPath[MAX_PATH];
+ UINT cbBCryptDllPath;
+
+ cbBCryptDllPath = GetSystemDirectory(szBCryptDllPath,
+ sizeof(szBCryptDllPath));
+ if (cbBCryptDllPath > 0 &&
+ cbBCryptDllPath < sizeof(szBCryptDllPath) &&
+ strncat_s(szBCryptDllPath,
+ sizeof(szBCryptDllPath), "\\bcrypt.dll", 11) == 0) {
+ HANDLE hBCryptDll = LoadLibrary(szBCryptDllPath);
+
+ InterlockedCompareExchangeRelease(&wincng_available,
+ !!hBCryptDll, -1);
+ if (hBCryptDll)
+ FreeLibrary(hBCryptDll);
+ }
+ }
+
+ return wincng_available == 1;
+}
+
+BOOL WINAPI
+_hc_w32crypto_DllMain(HINSTANCE hinstDLL,
+ DWORD fdwReason,
+ LPVOID lpvReserved)
+{
+ if (fdwReason == DLL_PROCESS_DETACH) {
+ /*
+ * Don't bother cleaning up on process exit, only on
+ * FreeLibrary() (in which case lpvReserved will be NULL).
+ */
+ if (lpvReserved == NULL)
+ _hc_wincng_cleanup();
+ }
+
+ return TRUE;
+}
+
+#define EVP_W32CRYPTO_PROVIDER(type, name) \
+ \
+ const type *hc_EVP_w32crypto_ ##name (void) \
+ { \
+ if (wincng_check_availability()) \
+ return hc_EVP_wincng_ ##name (); \
+ else if (HCRYPTO_FALLBACK) \
+ return hc_EVP_hcrypto_ ##name (); \
+ else \
+ return NULL; \
+ }
+
+#define EVP_W32CRYPTO_PROVIDER_CNG_UNAVAILABLE(type, name) \
+ \
+ const type *hc_EVP_w32crypto_ ##name (void) \
+ { \
+ return hc_EVP_hcrypto_ ##name (); \
+ }
+
+EVP_W32CRYPTO_PROVIDER(EVP_MD, md2)
+EVP_W32CRYPTO_PROVIDER(EVP_MD, md4)
+EVP_W32CRYPTO_PROVIDER(EVP_MD, md5)
+EVP_W32CRYPTO_PROVIDER(EVP_MD, sha1)
+EVP_W32CRYPTO_PROVIDER(EVP_MD, sha256)
+EVP_W32CRYPTO_PROVIDER(EVP_MD, sha384)
+EVP_W32CRYPTO_PROVIDER(EVP_MD, sha512)
+
+EVP_W32CRYPTO_PROVIDER(EVP_CIPHER, rc2_cbc)
+EVP_W32CRYPTO_PROVIDER(EVP_CIPHER, rc2_40_cbc)
+EVP_W32CRYPTO_PROVIDER(EVP_CIPHER, rc2_64_cbc)
+
+EVP_W32CRYPTO_PROVIDER(EVP_CIPHER, rc4)
+EVP_W32CRYPTO_PROVIDER(EVP_CIPHER, rc4_40)
+
+EVP_W32CRYPTO_PROVIDER(EVP_CIPHER, des_cbc)
+EVP_W32CRYPTO_PROVIDER(EVP_CIPHER, des_ede3_cbc)
+
+EVP_W32CRYPTO_PROVIDER(EVP_CIPHER, aes_128_cbc)
+EVP_W32CRYPTO_PROVIDER(EVP_CIPHER, aes_192_cbc)
+EVP_W32CRYPTO_PROVIDER(EVP_CIPHER, aes_256_cbc)
+
+EVP_W32CRYPTO_PROVIDER(EVP_CIPHER, aes_128_cfb8)
+EVP_W32CRYPTO_PROVIDER(EVP_CIPHER, aes_192_cfb8)
+EVP_W32CRYPTO_PROVIDER(EVP_CIPHER, aes_256_cfb8)
+
+EVP_W32CRYPTO_PROVIDER_CNG_UNAVAILABLE(EVP_CIPHER, camellia_128_cbc)
+EVP_W32CRYPTO_PROVIDER_CNG_UNAVAILABLE(EVP_CIPHER, camellia_192_cbc)
+EVP_W32CRYPTO_PROVIDER_CNG_UNAVAILABLE(EVP_CIPHER, camellia_256_cbc)
diff --git a/third_party/heimdal/lib/hcrypto/evp-w32.h b/third_party/heimdal/lib/hcrypto/evp-w32.h
new file mode 100644
index 0000000..89bfa4d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp-w32.h
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2015, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_EVP_W32_H
+#define HEIM_EVP_W32_H 1
+
+/* symbol renaming */
+#define EVP_w32crypto_md2() hc_EVP_w32crypto_md2()
+#define EVP_w32crypto_md4() hc_EVP_w32crypto_md4()
+#define EVP_w32crypto_md5() hc_EVP_w32crypto_md5()
+#define EVP_w32crypto_sha1() hc_EVP_w32crypto_sha1()
+#define EVP_w32crypto_sha256() hc_EVP_w32crypto_sha256()
+#define EVP_w32crypto_sha384() hc_EVP_w32crypto_sha384()
+#define EVP_w32crypto_sha512() hc_EVP_w32crypto_sha512()
+#define EVP_w32crypto_des_cbc() hc_EVP_w32crypto_des_cbc()
+#define EVP_w32crypto_des_ede3_cbc() hc_EVP_w32crypto_des_ede3_cbc()
+#define EVP_w32crypto_aes_128_cbc() hc_EVP_w32crypto_aes_128_cbc()
+#define EVP_w32crypto_aes_192_cbc() hc_EVP_w32crypto_aes_192_cbc()
+#define EVP_w32crypto_aes_256_cbc() hc_EVP_w32crypto_aes_256_cbc()
+#define EVP_w32crypto_aes_128_cfb8() hc_EVP_w32crypto_aes_128_cfb8()
+#define EVP_w32crypto_aes_192_cfb8() hc_EVP_w32crypto_aes_192_cfb8()
+#define EVP_w32crypto_aes_256_cfb8() hc_EVP_w32crypto_aes_256_cfb8()
+#define EVP_w32crypto_rc4() hc_EVP_w32crypto_rc4()
+#define EVP_w32crypto_rc4_40() hc_EVP_w32crypto_rc4_40()
+#define EVP_w32crypto_rc2_40_cbc() hc_EVP_w32crypto_rc2_40_cbc()
+#define EVP_w32crypto_rc2_64_cbc() hc_EVP_w32crypto_rc2_64_cbc()
+#define EVP_w32crypto_rc2_cbc() hc_EVP_w32crypto_rc2_cbc()
+#define EVP_w32crypto_camellia_128_cbc() hc_EVP_w32crypto_camellia_128_cbc()
+#define EVP_w32crypto_camellia_192_cbc() hc_EVP_w32crypto_camellia_192_cbc()
+#define EVP_w32crypto_camellia_256_cbc() hc_EVP_w32crypto_camellia_256_cbc()
+
+/*
+ * This provider dynamically selects between Windows CNG (if running
+ * on Vista or above) or the inbuilt provider (if running on XP).
+ */
+
+HC_CPP_BEGIN
+
+const EVP_MD * hc_EVP_w32crypto_md2(void);
+const EVP_MD * hc_EVP_w32crypto_md4(void);
+const EVP_MD * hc_EVP_w32crypto_md5(void);
+const EVP_MD * hc_EVP_w32crypto_sha1(void);
+const EVP_MD * hc_EVP_w32crypto_sha256(void);
+const EVP_MD * hc_EVP_w32crypto_sha384(void);
+const EVP_MD * hc_EVP_w32crypto_sha512(void);
+
+const EVP_CIPHER * hc_EVP_w32crypto_des_cbc(void);
+const EVP_CIPHER * hc_EVP_w32crypto_des_ede3_cbc(void);
+
+const EVP_CIPHER * hc_EVP_w32crypto_aes_128_cbc(void);
+const EVP_CIPHER * hc_EVP_w32crypto_aes_192_cbc(void);
+const EVP_CIPHER * hc_EVP_w32crypto_aes_256_cbc(void);
+
+const EVP_CIPHER * hc_EVP_w32crypto_aes_128_cfb8(void);
+const EVP_CIPHER * hc_EVP_w32crypto_aes_192_cfb8(void);
+const EVP_CIPHER * hc_EVP_w32crypto_aes_256_cfb8(void);
+
+const EVP_CIPHER * hc_EVP_w32crypto_rc4(void);
+const EVP_CIPHER * hc_EVP_w32crypto_rc4_40(void);
+
+const EVP_CIPHER * hc_EVP_w32crypto_rc2_cbc(void);
+const EVP_CIPHER * hc_EVP_w32crypto_rc2_40_cbc(void);
+const EVP_CIPHER * hc_EVP_w32crypto_rc2_64_cbc(void);
+
+const EVP_CIPHER * hc_EVP_w32crypto_camellia_128_cbc(void);
+const EVP_CIPHER * hc_EVP_w32crypto_camellia_192_cbc(void);
+const EVP_CIPHER * hc_EVP_w32crypto_camellia_256_cbc(void);
+
+HC_CPP_END
+
+#endif /* HEIM_EVP_W32_H */
diff --git a/third_party/heimdal/lib/hcrypto/evp-wincng.c b/third_party/heimdal/lib/hcrypto/evp-wincng.c
new file mode 100644
index 0000000..92974a9
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp-wincng.c
@@ -0,0 +1,727 @@
+/*
+ * Copyright (c) 2015, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* Windows CNG provider */
+
+#include <config.h>
+#include <roken.h>
+#include <assert.h>
+#include <versionsupport.h>
+
+#include <evp.h>
+#include <evp-wincng.h>
+
+#include <bcrypt.h>
+
+#ifndef BCRYPT_HASH_REUSABLE_FLAG
+#define BCRYPT_HASH_REUSABLE_FLAG 0x00000020
+#endif
+
+/*
+ * CNG cipher provider
+ */
+
+struct wincng_key {
+ BCRYPT_KEY_HANDLE hKey;
+ UCHAR rgbKeyObject[1];
+};
+
+#define WINCNG_KEY_OBJECT_SIZE(ctx) \
+ ((ctx)->cipher->ctx_size - sizeof(struct wincng_key) + 1)
+
+static int
+wincng_do_cipher(EVP_CIPHER_CTX *ctx,
+ unsigned char *out,
+ const unsigned char *in,
+ unsigned int size)
+{
+ struct wincng_key *cng = ctx->cipher_data;
+ NTSTATUS status;
+ ULONG cbResult;
+
+ assert(EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_STREAM_CIPHER ||
+ (size % ctx->cipher->block_size) == 0);
+
+ if (ctx->encrypt) {
+ status = BCryptEncrypt(cng->hKey,
+ (PUCHAR)in,
+ size,
+ NULL, /* pPaddingInfo */
+ ctx->cipher->iv_len ? ctx->iv : NULL,
+ ctx->cipher->iv_len,
+ out,
+ size,
+ &cbResult,
+ 0);
+ } else {
+ status = BCryptDecrypt(cng->hKey,
+ (PUCHAR)in,
+ size,
+ NULL, /* pPaddingInfo */
+ ctx->cipher->iv_len ? ctx->iv : NULL,
+ ctx->cipher->iv_len,
+ out,
+ size,
+ &cbResult,
+ 0);
+ }
+
+ return BCRYPT_SUCCESS(status) && cbResult == size;
+}
+
+static int
+wincng_cleanup(EVP_CIPHER_CTX *ctx)
+{
+ struct wincng_key *cng = ctx->cipher_data;
+
+ if (cng->hKey) {
+ BCryptDestroyKey(cng->hKey);
+ cng->hKey = (BCRYPT_KEY_HANDLE)0;
+ }
+ SecureZeroMemory(cng->rgbKeyObject, WINCNG_KEY_OBJECT_SIZE(ctx));
+
+ return 1;
+}
+
+static int
+wincng_cipher_algorithm_init(EVP_CIPHER *cipher,
+ LPWSTR pszAlgId)
+{
+ BCRYPT_ALG_HANDLE hAlgorithm = NULL;
+ NTSTATUS status;
+ LPCWSTR pszChainingMode;
+ ULONG cbKeyObject, cbChainingMode, cbData;
+
+ if (cipher->app_data)
+ return 1;
+
+ status = BCryptOpenAlgorithmProvider(&hAlgorithm,
+ pszAlgId,
+ NULL,
+ 0);
+ if (!BCRYPT_SUCCESS(status))
+ return 0;
+
+ status = BCryptGetProperty(hAlgorithm,
+ BCRYPT_OBJECT_LENGTH,
+ (PUCHAR)&cbKeyObject,
+ sizeof(ULONG),
+ &cbData,
+ 0);
+ if (!BCRYPT_SUCCESS(status)) {
+ BCryptCloseAlgorithmProvider(hAlgorithm, 0);
+ return 0;
+ }
+
+ cipher->ctx_size = sizeof(struct wincng_key) + cbKeyObject - 1;
+
+ switch (cipher->flags & EVP_CIPH_MODE) {
+ case EVP_CIPH_CBC_MODE:
+ pszChainingMode = BCRYPT_CHAIN_MODE_CBC;
+ cbChainingMode = sizeof(BCRYPT_CHAIN_MODE_CBC);
+ break;
+ case EVP_CIPH_CFB8_MODE:
+ pszChainingMode = BCRYPT_CHAIN_MODE_CFB;
+ cbChainingMode = sizeof(BCRYPT_CHAIN_MODE_CFB);
+ break;
+ default:
+ pszChainingMode = NULL;
+ cbChainingMode = 0;
+ break;
+ }
+
+ if (cbChainingMode) {
+ status = BCryptSetProperty(hAlgorithm,
+ BCRYPT_CHAINING_MODE,
+ (PUCHAR)pszChainingMode,
+ cbChainingMode,
+ 0);
+ if (!BCRYPT_SUCCESS(status)) {
+ BCryptCloseAlgorithmProvider(hAlgorithm, 0);
+ return 0;
+ }
+ }
+
+ if (wcscmp(pszAlgId, BCRYPT_RC2_ALGORITHM) == 0) {
+ ULONG cbEffectiveKeyLength = EVP_CIPHER_key_length(cipher) * 8;
+
+ status = BCryptSetProperty(hAlgorithm,
+ BCRYPT_EFFECTIVE_KEY_LENGTH,
+ (PUCHAR)&cbEffectiveKeyLength,
+ sizeof(cbEffectiveKeyLength),
+ 0);
+ if (!BCRYPT_SUCCESS(status)) {
+ BCryptCloseAlgorithmProvider(hAlgorithm, 0);
+ return 0;
+ }
+ }
+
+ InterlockedCompareExchangePointerRelease(&cipher->app_data,
+ hAlgorithm, NULL);
+ return 1;
+}
+
+static int
+wincng_key_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char *key,
+ const unsigned char *iv,
+ int encp)
+{
+ struct wincng_key *cng = ctx->cipher_data;
+ NTSTATUS status;
+
+ assert(cng != NULL);
+ assert(ctx->cipher != NULL);
+
+ if (ctx->cipher->app_data == NULL)
+ return 0;
+
+ wincng_cleanup(ctx);
+
+ /*
+ * Note: ctx->key_len not EVP_CIPHER_CTX_key_length() for
+ * variable length key support.
+ */
+ status = BCryptGenerateSymmetricKey(ctx->cipher->app_data,
+ &cng->hKey,
+ cng->rgbKeyObject,
+ WINCNG_KEY_OBJECT_SIZE(ctx),
+ (PUCHAR)key,
+ ctx->key_len,
+ 0);
+
+ return BCRYPT_SUCCESS(status);
+}
+
+#define WINCNG_CIPHER_ALGORITHM(name, alg_id, block_size, key_len, \
+ iv_len, flags) \
+ \
+ static EVP_CIPHER \
+ wincng_##name = { \
+ 0, \
+ block_size, \
+ key_len, \
+ iv_len, \
+ flags, \
+ wincng_key_init, \
+ wincng_do_cipher, \
+ wincng_cleanup, \
+ 0, \
+ NULL, \
+ NULL, \
+ NULL, \
+ NULL \
+ }; \
+ \
+ const EVP_CIPHER * \
+ hc_EVP_wincng_##name(void) \
+ { \
+ wincng_cipher_algorithm_init(&wincng_##name, alg_id); \
+ return wincng_##name.app_data ? &wincng_##name : NULL; \
+ }
+
+#define WINCNG_CIPHER_ALGORITHM_CLEANUP(name) do { \
+ if (wincng_##name.app_data) { \
+ BCryptCloseAlgorithmProvider(wincng_##name.app_data, 0); \
+ wincng_##name.app_data = NULL; \
+ } \
+ } while (0)
+
+#define WINCNG_CIPHER_ALGORITHM_UNAVAILABLE(name) \
+ \
+ const EVP_CIPHER * \
+ hc_EVP_wincng_##name(void) \
+ { \
+ return NULL; \
+ }
+
+/**
+ * The triple DES cipher type (Windows CNG provider)
+ *
+ * @return the DES-EDE3-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM(des_ede3_cbc,
+ BCRYPT_3DES_ALGORITHM,
+ 8,
+ 24,
+ 8,
+ EVP_CIPH_CBC_MODE);
+
+/**
+ * The DES cipher type (Windows CNG provider)
+ *
+ * @return the DES-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM(des_cbc,
+ BCRYPT_DES_ALGORITHM,
+ 8,
+ 8,
+ 8,
+ EVP_CIPH_CBC_MODE);
+
+/**
+ * The AES-128 cipher type (Windows CNG provider)
+ *
+ * @return the AES-128-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM(aes_128_cbc,
+ BCRYPT_AES_ALGORITHM,
+ 16,
+ 16,
+ 16,
+ EVP_CIPH_CBC_MODE);
+
+/**
+ * The AES-192 cipher type (Windows CNG provider)
+ *
+ * @return the AES-192-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM(aes_192_cbc,
+ BCRYPT_AES_ALGORITHM,
+ 16,
+ 24,
+ 16,
+ EVP_CIPH_CBC_MODE);
+
+/**
+ * The AES-256 cipher type (Windows CNG provider)
+ *
+ * @return the AES-256-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM(aes_256_cbc,
+ BCRYPT_AES_ALGORITHM,
+ 16,
+ 32,
+ 16,
+ EVP_CIPH_CBC_MODE);
+
+/**
+ * The AES-128 CFB8 cipher type (Windows CNG provider)
+ *
+ * @return the AES-128-CFB8 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM(aes_128_cfb8,
+ BCRYPT_AES_ALGORITHM,
+ 16,
+ 16,
+ 16,
+ EVP_CIPH_CFB8_MODE);
+
+/**
+ * The AES-192 CFB8 cipher type (Windows CNG provider)
+ *
+ * @return the AES-192-CFB8 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM(aes_192_cfb8,
+ BCRYPT_AES_ALGORITHM,
+ 16,
+ 24,
+ 16,
+ EVP_CIPH_CFB8_MODE);
+
+/**
+ * The AES-256 CFB8 cipher type (Windows CNG provider)
+ *
+ * @return the AES-256-CFB8 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM(aes_256_cfb8,
+ BCRYPT_AES_ALGORITHM,
+ 16,
+ 32,
+ 16,
+ EVP_CIPH_CFB8_MODE);
+
+/**
+ * The RC2 cipher type - Windows CNG
+ *
+ * @return the RC2 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM(rc2_cbc,
+ BCRYPT_RC2_ALGORITHM,
+ 8,
+ 16,
+ 8,
+ EVP_CIPH_CBC_MODE);
+
+/**
+ * The RC2-40 cipher type - Windows CNG
+ *
+ * @return the RC2-40 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM(rc2_40_cbc,
+ BCRYPT_RC2_ALGORITHM,
+ 8,
+ 5,
+ 8,
+ EVP_CIPH_CBC_MODE);
+
+/**
+ * The RC2-64 cipher type - Windows CNG
+ *
+ * @return the RC2-64 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM(rc2_64_cbc,
+ BCRYPT_RC2_ALGORITHM,
+ 8,
+ 8,
+ 8,
+ EVP_CIPH_CBC_MODE);
+
+/**
+ * The Camellia-128 cipher type - CommonCrypto
+ *
+ * @return the Camellia-128 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM_UNAVAILABLE(camellia_128_cbc);
+
+/**
+ * The Camellia-198 cipher type - CommonCrypto
+ *
+ * @return the Camellia-198 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM_UNAVAILABLE(camellia_192_cbc);
+
+/**
+ * The Camellia-256 cipher type - CommonCrypto
+ *
+ * @return the Camellia-256 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM_UNAVAILABLE(camellia_256_cbc);
+
+/**
+ * The RC4 cipher type (Windows CNG provider)
+ *
+ * @return the RC4 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM(rc4,
+ BCRYPT_RC4_ALGORITHM,
+ 1,
+ 16,
+ 0,
+ EVP_CIPH_STREAM_CIPHER | EVP_CIPH_VARIABLE_LENGTH);
+
+/**
+ * The RC4-40 cipher type (Windows CNG provider)
+ *
+ * @return the RC4 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+WINCNG_CIPHER_ALGORITHM(rc4_40,
+ BCRYPT_RC4_ALGORITHM,
+ 1,
+ 5,
+ 0,
+ EVP_CIPH_STREAM_CIPHER | EVP_CIPH_VARIABLE_LENGTH);
+
+static void
+wincng_cipher_algorithm_cleanup(void)
+{
+ WINCNG_CIPHER_ALGORITHM_CLEANUP(des_ede3_cbc);
+ WINCNG_CIPHER_ALGORITHM_CLEANUP(des_cbc);
+ WINCNG_CIPHER_ALGORITHM_CLEANUP(aes_128_cbc);
+ WINCNG_CIPHER_ALGORITHM_CLEANUP(aes_192_cbc);
+ WINCNG_CIPHER_ALGORITHM_CLEANUP(aes_256_cbc);
+ WINCNG_CIPHER_ALGORITHM_CLEANUP(aes_128_cfb8);
+ WINCNG_CIPHER_ALGORITHM_CLEANUP(aes_192_cfb8);
+ WINCNG_CIPHER_ALGORITHM_CLEANUP(aes_256_cfb8);
+ WINCNG_CIPHER_ALGORITHM_CLEANUP(rc2_cbc);
+ WINCNG_CIPHER_ALGORITHM_CLEANUP(rc2_40_cbc);
+ WINCNG_CIPHER_ALGORITHM_CLEANUP(rc2_64_cbc);
+ WINCNG_CIPHER_ALGORITHM_CLEANUP(rc4);
+ WINCNG_CIPHER_ALGORITHM_CLEANUP(rc4_40);
+}
+
+/*
+ * CNG digest provider
+ */
+
+struct wincng_md_ctx {
+ BCRYPT_HASH_HANDLE hHash;
+ ULONG cbHashObject;
+ UCHAR rgbHashObject[1];
+};
+
+static BCRYPT_ALG_HANDLE
+wincng_md_algorithm_init(EVP_MD *md,
+ LPCWSTR pszAlgId)
+{
+ BCRYPT_ALG_HANDLE hAlgorithm;
+ NTSTATUS status;
+ ULONG cbHashObject, cbData;
+ ULONG cbHash = 0, cbBlock = 0;
+
+ status = BCryptOpenAlgorithmProvider(&hAlgorithm,
+ pszAlgId,
+ NULL,
+ 0);
+ if (!BCRYPT_SUCCESS(status))
+ return NULL;
+
+ status = BCryptGetProperty(hAlgorithm,
+ BCRYPT_HASH_LENGTH,
+ (PUCHAR)&cbHash,
+ sizeof(ULONG),
+ &cbData,
+ 0);
+ if (!BCRYPT_SUCCESS(status)) {
+ BCryptCloseAlgorithmProvider(hAlgorithm, 0);
+ return NULL;
+ }
+
+ status = BCryptGetProperty(hAlgorithm,
+ BCRYPT_HASH_BLOCK_LENGTH,
+ (PUCHAR)&cbBlock,
+ sizeof(ULONG),
+ &cbData,
+ 0);
+ if (!BCRYPT_SUCCESS(status)) {
+ BCryptCloseAlgorithmProvider(hAlgorithm, 0);
+ return NULL;
+ }
+
+ status = BCryptGetProperty(hAlgorithm,
+ BCRYPT_OBJECT_LENGTH,
+ (PUCHAR)&cbHashObject,
+ sizeof(ULONG),
+ &cbData,
+ 0);
+ if (!BCRYPT_SUCCESS(status)) {
+ BCryptCloseAlgorithmProvider(hAlgorithm, 0);
+ return NULL;
+ }
+
+ md->hash_size = cbHash;
+ md->block_size = cbBlock;
+ md->ctx_size = sizeof(struct wincng_md_ctx) + cbHashObject - 1;
+
+ return hAlgorithm;
+}
+
+static int
+wincng_md_cleanup(EVP_MD_CTX *ctx);
+
+static int
+wincng_md_hash_init(BCRYPT_ALG_HANDLE hAlgorithm,
+ EVP_MD_CTX *ctx)
+{
+ struct wincng_md_ctx *cng = (struct wincng_md_ctx *)ctx;
+ NTSTATUS status;
+ ULONG cbData, dwFlags = 0;
+
+ if (IsWindows8OrGreaterCached()) {
+ if (cng->hHash)
+ return 1;
+ else
+ dwFlags |= BCRYPT_HASH_REUSABLE_FLAG;
+ } else
+ wincng_md_cleanup(ctx);
+
+ status = BCryptGetProperty(hAlgorithm,
+ BCRYPT_OBJECT_LENGTH,
+ (PUCHAR)&cng->cbHashObject,
+ sizeof(ULONG),
+ &cbData,
+ 0);
+ if (!BCRYPT_SUCCESS(status))
+ return 0;
+
+ status = BCryptCreateHash(hAlgorithm,
+ &cng->hHash,
+ cng->rgbHashObject,
+ cng->cbHashObject,
+ NULL,
+ 0,
+ dwFlags);
+
+ return BCRYPT_SUCCESS(status);
+}
+
+static int
+wincng_md_update(EVP_MD_CTX *ctx,
+ const void *data,
+ size_t length)
+{
+ struct wincng_md_ctx *cng = (struct wincng_md_ctx *)ctx;
+ NTSTATUS status;
+
+ status = BCryptHashData(cng->hHash, (PUCHAR)data, length, 0);
+
+ return BCRYPT_SUCCESS(status);
+}
+
+static int
+wincng_md_final(void *digest,
+ EVP_MD_CTX *ctx)
+{
+ struct wincng_md_ctx *cng = (struct wincng_md_ctx *)ctx;
+ NTSTATUS status;
+ ULONG cbHash, cbData;
+
+ status = BCryptGetProperty(cng->hHash,
+ BCRYPT_HASH_LENGTH,
+ (PUCHAR)&cbHash,
+ sizeof(DWORD),
+ &cbData,
+ 0);
+ if (!BCRYPT_SUCCESS(status))
+ return 0;
+
+ status = BCryptFinishHash(cng->hHash,
+ digest,
+ cbHash,
+ 0);
+
+ return BCRYPT_SUCCESS(status);
+}
+
+static int
+wincng_md_cleanup(EVP_MD_CTX *ctx)
+{
+ struct wincng_md_ctx *cng = (struct wincng_md_ctx *)ctx;
+
+ if (cng->hHash) {
+ BCryptDestroyHash(cng->hHash);
+ cng->hHash = (BCRYPT_HASH_HANDLE)0;
+ }
+ SecureZeroMemory(cng->rgbHashObject, cng->cbHashObject);
+
+ return 1;
+}
+
+#define WINCNG_MD_ALGORITHM(name, alg_id) \
+ \
+ static BCRYPT_ALG_HANDLE wincng_hAlgorithm_##name; \
+ \
+ static int wincng_##name##_init(EVP_MD_CTX *ctx) \
+ { \
+ return wincng_md_hash_init(wincng_hAlgorithm_##name, ctx); \
+ } \
+ \
+ const EVP_MD * \
+ hc_EVP_wincng_##name(void) \
+ { \
+ static struct hc_evp_md name = { \
+ 0, \
+ 0, \
+ 0, \
+ wincng_##name##_init, \
+ wincng_md_update, \
+ wincng_md_final, \
+ wincng_md_cleanup \
+ }; \
+ \
+ if (wincng_hAlgorithm_##name == NULL) { \
+ BCRYPT_ALG_HANDLE hAlgorithm = \
+ wincng_md_algorithm_init(&name, alg_id); \
+ InterlockedCompareExchangePointerRelease( \
+ &wincng_hAlgorithm_##name, hAlgorithm, NULL); \
+ } \
+ return wincng_hAlgorithm_##name ? &name : NULL; \
+ }
+
+#define WINCNG_MD_ALGORITHM_CLEANUP(name) do { \
+ if (wincng_hAlgorithm_##name) { \
+ BCryptCloseAlgorithmProvider(wincng_hAlgorithm_##name, 0); \
+ wincng_hAlgorithm_##name = NULL; \
+ } \
+ } while (0)
+
+WINCNG_MD_ALGORITHM(md2, BCRYPT_MD2_ALGORITHM);
+WINCNG_MD_ALGORITHM(md4, BCRYPT_MD4_ALGORITHM);
+WINCNG_MD_ALGORITHM(md5, BCRYPT_MD5_ALGORITHM);
+WINCNG_MD_ALGORITHM(sha1, BCRYPT_SHA1_ALGORITHM);
+WINCNG_MD_ALGORITHM(sha256, BCRYPT_SHA256_ALGORITHM);
+WINCNG_MD_ALGORITHM(sha384, BCRYPT_SHA384_ALGORITHM);
+WINCNG_MD_ALGORITHM(sha512, BCRYPT_SHA512_ALGORITHM);
+
+static void
+wincng_md_algorithm_cleanup(void)
+{
+ WINCNG_MD_ALGORITHM_CLEANUP(md2);
+ WINCNG_MD_ALGORITHM_CLEANUP(md4);
+ WINCNG_MD_ALGORITHM_CLEANUP(md5);
+ WINCNG_MD_ALGORITHM_CLEANUP(sha1);
+ WINCNG_MD_ALGORITHM_CLEANUP(sha256);
+ WINCNG_MD_ALGORITHM_CLEANUP(sha384);
+ WINCNG_MD_ALGORITHM_CLEANUP(sha512);
+}
+
+void _hc_wincng_cleanup(void)
+{
+ wincng_md_algorithm_cleanup();
+ wincng_cipher_algorithm_cleanup();
+}
diff --git a/third_party/heimdal/lib/hcrypto/evp-wincng.h b/third_party/heimdal/lib/hcrypto/evp-wincng.h
new file mode 100644
index 0000000..ed7037a
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp-wincng.h
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2015, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_EVP_WINCNG_H
+#define HEIM_EVP_WINCNG_H 1
+
+/* symbol renaming */
+#define EVP_wincng_md2() EVP_wincng_md2()
+#define EVP_wincng_md4() EVP_wincng_md4()
+#define EVP_wincng_md5() EVP_wincng_md5()
+#define EVP_wincng_sha1() EVP_wincng_sha1()
+#define EVP_wincng_sha256() EVP_wincng_sha256()
+#define EVP_wincng_sha384() EVP_wincng_sha384()
+#define EVP_wincng_sha512() EVP_wincng_sha512()
+#define EVP_wincng_des_cbc() EVP_wincng_des_cbc()
+#define EVP_wincng_des_ede3_cbc() EVP_wincng_des_ede3_cbc()
+#define EVP_wincng_aes_128_cbc() EVP_wincng_aes_128_cbc()
+#define EVP_wincng_aes_192_cbc() EVP_wincng_aes_192_cbc()
+#define EVP_wincng_aes_256_cbc() EVP_wincng_aes_256_cbc()
+#define EVP_wincng_aes_128_cfb8() EVP_wincng_aes_128_cfb8()
+#define EVP_wincng_aes_192_cfb8() EVP_wincng_aes_192_cfb8()
+#define EVP_wincng_aes_256_cfb8() EVP_wincng_aes_256_cfb8()
+#define EVP_wincng_rc4() EVP_wincng_rc4()
+#define EVP_wincng_rc4_40() EVP_wincng_rc4_40()
+#define EVP_wincng_rc2_40_cbc() EVP_wincng_rc2_40_cbc()
+#define EVP_wincng_rc2_64_cbc() EVP_wincng_rc2_64_cbc()
+#define EVP_wincng_rc2_cbc() EVP_wincng_rc2_cbc()
+#define EVP_wincng_camellia_128_cbc() EVP_wincng_camellia_128_cbc()
+#define EVP_wincng_camellia_192_cbc() EVP_wincng_camellia_192_cbc()
+#define EVP_wincng_camellia_256_cbc() EVP_wincng_camellia_256_cbc()
+
+/*
+ *
+ */
+
+HC_CPP_BEGIN
+
+const EVP_MD * hc_EVP_wincng_md2(void);
+const EVP_MD * hc_EVP_wincng_md4(void);
+const EVP_MD * hc_EVP_wincng_md5(void);
+const EVP_MD * hc_EVP_wincng_sha1(void);
+const EVP_MD * hc_EVP_wincng_sha256(void);
+const EVP_MD * hc_EVP_wincng_sha384(void);
+const EVP_MD * hc_EVP_wincng_sha512(void);
+
+const EVP_CIPHER * hc_EVP_wincng_rc2_cbc(void);
+const EVP_CIPHER * hc_EVP_wincng_rc2_40_cbc(void);
+const EVP_CIPHER * hc_EVP_wincng_rc2_64_cbc(void);
+
+const EVP_CIPHER * hc_EVP_wincng_rc4(void);
+const EVP_CIPHER * hc_EVP_wincng_rc4_40(void);
+
+const EVP_CIPHER * hc_EVP_wincng_des_cbc(void);
+const EVP_CIPHER * hc_EVP_wincng_des_ede3_cbc(void);
+
+const EVP_CIPHER * hc_EVP_wincng_aes_128_cbc(void);
+const EVP_CIPHER * hc_EVP_wincng_aes_192_cbc(void);
+const EVP_CIPHER * hc_EVP_wincng_aes_256_cbc(void);
+
+const EVP_CIPHER * hc_EVP_wincng_aes_128_cfb8(void);
+const EVP_CIPHER * hc_EVP_wincng_aes_192_cfb8(void);
+const EVP_CIPHER * hc_EVP_wincng_aes_256_cfb8(void);
+
+void _hc_wincng_cleanup(void);
+
+HC_CPP_END
+
+#endif /* HEIM_EVP_WINCNG_H */
diff --git a/third_party/heimdal/lib/hcrypto/evp.c b/third_party/heimdal/lib/hcrypto/evp.c
new file mode 100644
index 0000000..9cced4c
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp.c
@@ -0,0 +1,1521 @@
+/*
+ * Copyright (c) 2006 - 2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <roken.h>
+
+#define HC_DEPRECATED
+#define HC_DEPRECATED_CRYPTO
+
+#include <assert.h>
+
+#include <evp.h>
+#include <evp-hcrypto.h>
+#include <evp-cc.h>
+#if defined(_WIN32)
+#include <evp-w32.h>
+#endif
+#include <evp-pkcs11.h>
+#include <evp-openssl.h>
+
+#include <krb5-types.h>
+
+#ifndef HCRYPTO_DEF_PROVIDER
+# ifdef __APPLE__
+# define HCRYPTO_DEF_PROVIDER cc
+# elif __sun
+# define HCRYPTO_DEF_PROVIDER pkcs11_hcrypto
+# elif HAVE_HCRYPTO_W_OPENSSL
+# define HCRYPTO_DEF_PROVIDER ossl
+# else
+# define HCRYPTO_DEF_PROVIDER hcrypto
+# endif
+#endif
+
+#define HC_CONCAT4(x,y,z,aa) x ## y ## z ## aa
+
+
+#define EVP_DEF_OP(_prov,_op) HC_CONCAT4(EVP_,_prov,_,_op)()
+
+/**
+ * @page page_evp EVP - generic crypto interface
+ *
+ * See the library functions here: @ref hcrypto_evp
+ *
+ * @section evp_cipher EVP Cipher
+ *
+ * The use of EVP_CipherInit_ex() and EVP_Cipher() is pretty easy to
+ * understand forward, then EVP_CipherUpdate() and
+ * EVP_CipherFinal_ex() really needs an example to explain @ref
+ * example_evp_cipher.c .
+ *
+ * @example example_evp_cipher.c
+ *
+ * This is an example how to use EVP_CipherInit_ex(),
+ * EVP_CipherUpdate() and EVP_CipherFinal_ex().
+ */
+
+struct hc_EVP_MD_CTX {
+ const EVP_MD *md;
+ ENGINE *engine;
+ void *ptr;
+};
+
+
+/**
+ * Return the output size of the message digest function.
+ *
+ * @param md the evp message
+ *
+ * @return size output size of the message digest function.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+size_t
+EVP_MD_size(const EVP_MD *md)
+{
+ return md->hash_size;
+}
+
+/**
+ * Return the blocksize of the message digest function.
+ *
+ * @param md the evp message
+ *
+ * @return size size of the message digest block size
+ *
+ * @ingroup hcrypto_evp
+ */
+
+size_t
+EVP_MD_block_size(const EVP_MD *md)
+{
+ return md->block_size;
+}
+
+/**
+ * Allocate a messsage digest context object. Free with
+ * EVP_MD_CTX_destroy().
+ *
+ * @return a newly allocated message digest context object.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+EVP_MD_CTX *
+EVP_MD_CTX_create(void)
+{
+ return calloc(1, sizeof(EVP_MD_CTX));
+}
+
+/**
+ * Initiate a messsage digest context object. Deallocate with
+ * EVP_MD_CTX_cleanup(). Please use EVP_MD_CTX_create() instead.
+ *
+ * @param ctx variable to initiate.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+void
+EVP_MD_CTX_init(EVP_MD_CTX *ctx) HC_DEPRECATED
+{
+ memset(ctx, 0, sizeof(*ctx));
+}
+
+/**
+ * Free a messsage digest context object.
+ *
+ * @param ctx context to free.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+void
+EVP_MD_CTX_destroy(EVP_MD_CTX *ctx)
+{
+ EVP_MD_CTX_cleanup(ctx);
+ free(ctx);
+}
+
+/**
+ * Free the resources used by the EVP_MD context.
+ *
+ * @param ctx the context to free the resources from.
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+int
+EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx) HC_DEPRECATED
+{
+ if (ctx->md && ctx->md->cleanup) {
+ int ret = (ctx->md->cleanup)(ctx->ptr);
+ if (!ret)
+ return ret;
+ } else if (ctx->md) {
+ memset(ctx->ptr, 0, ctx->md->ctx_size);
+ }
+ ctx->md = NULL;
+ ctx->engine = NULL;
+ free(ctx->ptr);
+ memset(ctx, 0, sizeof(*ctx));
+ return 1;
+}
+
+/**
+ * Get the EVP_MD use for a specified context.
+ *
+ * @param ctx the EVP_MD context to get the EVP_MD for.
+ *
+ * @return the EVP_MD used for the context.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_MD_CTX_md(EVP_MD_CTX *ctx)
+{
+ return ctx->md;
+}
+
+/**
+ * Return the output size of the message digest function.
+ *
+ * @param ctx the evp message digest context
+ *
+ * @return size output size of the message digest function.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+size_t
+EVP_MD_CTX_size(EVP_MD_CTX *ctx)
+{
+ return EVP_MD_size(ctx->md);
+}
+
+/**
+ * Return the blocksize of the message digest function.
+ *
+ * @param ctx the evp message digest context
+ *
+ * @return size size of the message digest block size
+ *
+ * @ingroup hcrypto_evp
+ */
+
+size_t
+EVP_MD_CTX_block_size(EVP_MD_CTX *ctx)
+{
+ return EVP_MD_block_size(ctx->md);
+}
+
+/**
+ * Init a EVP_MD_CTX for use a specific message digest and engine.
+ *
+ * @param ctx the message digest context to init.
+ * @param md the message digest to use.
+ * @param engine the engine to use, NULL to use the default engine.
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+int
+EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *md, ENGINE *engine)
+{
+ if (ctx->md != md || ctx->engine != engine) {
+ EVP_MD_CTX_cleanup(ctx);
+ ctx->md = md;
+ ctx->engine = engine;
+ if (md == NULL)
+ return 0;
+
+ ctx->ptr = calloc(1, md->ctx_size);
+ if (ctx->ptr == NULL)
+ return 0;
+ }
+ if (ctx->md == 0)
+ return 0;
+ return (ctx->md->init)(ctx->ptr);
+}
+
+/**
+ * Update the digest with some data.
+ *
+ * @param ctx the context to update
+ * @param data the data to update the context with
+ * @param size length of data
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+int
+EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, size_t size)
+{
+ (ctx->md->update)(ctx->ptr, data, size);
+ return 1;
+}
+
+/**
+ * Complete the message digest.
+ *
+ * @param ctx the context to complete.
+ * @param hash the output of the message digest function. At least
+ * EVP_MD_size().
+ * @param size the output size of hash.
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+int
+EVP_DigestFinal_ex(EVP_MD_CTX *ctx, void *hash, unsigned int *size)
+{
+ (ctx->md->final)(hash, ctx->ptr);
+ if (size)
+ *size = ctx->md->hash_size;
+ return 1;
+}
+
+/**
+ * Do the whole EVP_MD_CTX_create(), EVP_DigestInit_ex(),
+ * EVP_DigestUpdate(), EVP_DigestFinal_ex(), EVP_MD_CTX_destroy()
+ * dance in one call.
+ *
+ * @param data the data to update the context with
+ * @param dsize length of data
+ * @param hash output data of at least EVP_MD_size() length.
+ * @param hsize output length of hash.
+ * @param md message digest to use
+ * @param engine engine to use, NULL for default engine.
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+int
+EVP_Digest(const void *data, size_t dsize, void *hash, unsigned int *hsize,
+ const EVP_MD *md, ENGINE *engine)
+{
+ EVP_MD_CTX *ctx;
+ int ret;
+
+ ctx = EVP_MD_CTX_create();
+ if (ctx == NULL)
+ return 0;
+ ret = EVP_DigestInit_ex(ctx, md, engine);
+ if (ret != 1) {
+ EVP_MD_CTX_destroy(ctx);
+ return ret;
+ }
+ ret = EVP_DigestUpdate(ctx, data, dsize);
+ if (ret != 1) {
+ EVP_MD_CTX_destroy(ctx);
+ return ret;
+ }
+ ret = EVP_DigestFinal_ex(ctx, hash, hsize);
+ EVP_MD_CTX_destroy(ctx);
+ return ret;
+}
+
+/**
+ * The message digest SHA256
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_sha256(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, sha256);
+}
+
+/**
+ * The message digest SHA384
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_sha384(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, sha384);
+}
+
+/**
+ * The message digest SHA512
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_sha512(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, sha512);
+}
+
+/**
+ * The message digest SHA1
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_sha1(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, sha1);
+}
+
+/**
+ * The message digest SHA1
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_sha(void) HC_DEPRECATED
+
+{
+ hcrypto_validate();
+ return EVP_sha1();
+}
+
+/**
+ * The message digest MD5
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_md5(void) HC_DEPRECATED_CRYPTO
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, md5);
+}
+
+/**
+ * The message digest MD4
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_md4(void) HC_DEPRECATED_CRYPTO
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, md4);
+}
+
+/**
+ * The message digest MD2
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_md2(void) HC_DEPRECATED_CRYPTO
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, md2);
+}
+
+/*
+ *
+ */
+
+static int
+null_Init (void *m)
+{
+ return 1;
+}
+static int
+null_Update (void *m, const void * data, size_t size)
+{
+ return 1;
+}
+static int
+null_Final(void *res, void *m)
+{
+ return 1;
+}
+
+/**
+ * The null message digest
+ *
+ * @return the message digest type.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_MD *
+EVP_md_null(void)
+{
+ static const struct hc_evp_md null = {
+ 0,
+ 0,
+ 0,
+ (hc_evp_md_init)null_Init,
+ (hc_evp_md_update)null_Update,
+ (hc_evp_md_final)null_Final,
+ NULL
+ };
+ return &null;
+}
+
+/**
+ * Return the block size of the cipher.
+ *
+ * @param c cipher to get the block size from.
+ *
+ * @return the block size of the cipher.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+size_t
+EVP_CIPHER_block_size(const EVP_CIPHER *c)
+{
+ return c->block_size;
+}
+
+/**
+ * Return the key size of the cipher.
+ *
+ * @param c cipher to get the key size from.
+ *
+ * @return the key size of the cipher.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+size_t
+EVP_CIPHER_key_length(const EVP_CIPHER *c)
+{
+ return c->key_len;
+}
+
+/**
+ * Return the IV size of the cipher.
+ *
+ * @param c cipher to get the IV size from.
+ *
+ * @return the IV size of the cipher.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+size_t
+EVP_CIPHER_iv_length(const EVP_CIPHER *c)
+{
+ return c->iv_len;
+}
+
+/**
+ * Initiate a EVP_CIPHER_CTX context. Clean up with
+ * EVP_CIPHER_CTX_cleanup().
+ *
+ * @param c the cipher initiate.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+void
+EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *c)
+{
+ memset(c, 0, sizeof(*c));
+}
+
+/**
+ * Clean up the EVP_CIPHER_CTX context.
+ *
+ * @param c the cipher to clean up.
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+int
+EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *c)
+{
+ if (c->cipher && c->cipher->cleanup) {
+ int ret = c->cipher->cleanup(c);
+ if (!ret)
+ return ret;
+ }
+ if (c->cipher_data) {
+ if (c->cipher)
+ memset(c->cipher_data, 0, c->cipher->ctx_size);
+ free(c->cipher_data);
+ c->cipher_data = NULL;
+ }
+ return 1;
+}
+
+/**
+ * If the cipher type supports it, change the key length
+ *
+ * @param c the cipher context to change the key length for
+ * @param length new key length
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+int
+EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int length)
+{
+ if ((c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH) && length > 0) {
+ c->key_len = length;
+ return 1;
+ }
+ return 0;
+}
+
+#if 0
+int
+EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *c, int pad)
+{
+ return 0;
+}
+#endif
+
+/**
+ * Return the EVP_CIPHER for a EVP_CIPHER_CTX context.
+ *
+ * @param ctx the context to get the cipher type from.
+ *
+ * @return the EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_CIPHER_CTX_cipher(EVP_CIPHER_CTX *ctx)
+{
+ return ctx->cipher;
+}
+
+/**
+ * Return the block size of the cipher context.
+ *
+ * @param ctx cipher context to get the block size from.
+ *
+ * @return the block size of the cipher context.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+size_t
+EVP_CIPHER_CTX_block_size(const EVP_CIPHER_CTX *ctx)
+{
+ return EVP_CIPHER_block_size(ctx->cipher);
+}
+
+/**
+ * Return the key size of the cipher context.
+ *
+ * @param ctx cipher context to get the key size from.
+ *
+ * @return the key size of the cipher context.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+size_t
+EVP_CIPHER_CTX_key_length(const EVP_CIPHER_CTX *ctx)
+{
+ return EVP_CIPHER_key_length(ctx->cipher);
+}
+
+/**
+ * Return the IV size of the cipher context.
+ *
+ * @param ctx cipher context to get the IV size from.
+ *
+ * @return the IV size of the cipher context.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+size_t
+EVP_CIPHER_CTX_iv_length(const EVP_CIPHER_CTX *ctx)
+{
+ return EVP_CIPHER_iv_length(ctx->cipher);
+}
+
+/**
+ * Get the flags for an EVP_CIPHER_CTX context.
+ *
+ * @param ctx the EVP_CIPHER_CTX to get the flags from
+ *
+ * @return the flags for an EVP_CIPHER_CTX.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+unsigned long
+EVP_CIPHER_CTX_flags(const EVP_CIPHER_CTX *ctx)
+{
+ return ctx->cipher->flags;
+}
+
+/**
+ * Get the mode for an EVP_CIPHER_CTX context.
+ *
+ * @param ctx the EVP_CIPHER_CTX to get the mode from
+ *
+ * @return the mode for an EVP_CIPHER_CTX.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+int
+EVP_CIPHER_CTX_mode(const EVP_CIPHER_CTX *ctx)
+{
+ return EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_MODE;
+}
+
+/**
+ * Get the app data for an EVP_CIPHER_CTX context.
+ *
+ * @param ctx the EVP_CIPHER_CTX to get the app data from
+ *
+ * @return the app data for an EVP_CIPHER_CTX.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+void *
+EVP_CIPHER_CTX_get_app_data(EVP_CIPHER_CTX *ctx)
+{
+ return ctx->app_data;
+}
+
+/**
+ * Set the app data for an EVP_CIPHER_CTX context.
+ *
+ * @param ctx the EVP_CIPHER_CTX to set the app data for
+ * @param data the app data to set for an EVP_CIPHER_CTX.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+void
+EVP_CIPHER_CTX_set_app_data(EVP_CIPHER_CTX *ctx, void *data)
+{
+ ctx->app_data = data;
+}
+
+/**
+ * Initiate the EVP_CIPHER_CTX context to encrypt or decrypt data.
+ * Clean up with EVP_CIPHER_CTX_cleanup().
+ *
+ * @param ctx context to initiate
+ * @param c cipher to use.
+ * @param engine crypto engine to use, NULL to select default.
+ * @param key the crypto key to use, NULL will use the previous value.
+ * @param iv the IV to use, NULL will use the previous value.
+ * @param encp non zero will encrypt, -1 use the previous value.
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+int
+EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *c, ENGINE *engine,
+ const void *key, const void *iv, int encp)
+{
+ ctx->buf_len = 0;
+
+ if (encp == -1)
+ encp = ctx->encrypt;
+ else
+ ctx->encrypt = (encp ? 1 : 0);
+
+ if (c && (c != ctx->cipher)) {
+ EVP_CIPHER_CTX_cleanup(ctx);
+ ctx->cipher = c;
+ ctx->key_len = c->key_len;
+
+ ctx->cipher_data = calloc(1, c->ctx_size);
+ if (ctx->cipher_data == NULL && c->ctx_size != 0)
+ return 0;
+
+ /* assume block size is a multiple of 2 */
+ ctx->block_mask = EVP_CIPHER_block_size(c) - 1;
+
+ if ((ctx->cipher->flags & EVP_CIPH_CTRL_INIT) &&
+ !EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL))
+ return 0;
+
+ } else if (ctx->cipher == NULL) {
+ /* reuse of cipher, but not any cipher ever set! */
+ return 0;
+ }
+
+ switch (EVP_CIPHER_CTX_mode(ctx)) {
+ case EVP_CIPH_CBC_MODE:
+
+ assert(EVP_CIPHER_CTX_iv_length(ctx) <= sizeof(ctx->iv));
+
+ if (iv)
+ memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
+ memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
+ break;
+
+ case EVP_CIPH_STREAM_CIPHER:
+ break;
+ case EVP_CIPH_CFB8_MODE:
+ if (iv)
+ memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
+ break;
+
+ default:
+ return 0;
+ }
+
+ if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT))
+ return ctx->cipher->init(ctx, key, iv, encp);
+
+ return 1;
+}
+
+/**
+ * Encipher/decipher partial data
+ *
+ * @param ctx the cipher context.
+ * @param out output data from the operation.
+ * @param outlen output length
+ * @param in input data to the operation.
+ * @param inlen length of data.
+ *
+ * The output buffer length should at least be EVP_CIPHER_block_size()
+ * byte longer then the input length.
+ *
+ * See @ref evp_cipher for an example how to use this function.
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+int
+EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, void *out, int *outlen,
+ void *in, size_t inlen)
+{
+ int ret, left, blocksize;
+
+ *outlen = 0;
+
+ /**
+ * If there in no spare bytes in the left from last Update and the
+ * input length is on the block boundery, the EVP_CipherUpdate()
+ * function can take a shortcut (and preformance gain) and
+ * directly encrypt the data, otherwise we hav to fix it up and
+ * store extra it the EVP_CIPHER_CTX.
+ */
+ if (ctx->buf_len == 0 && (inlen & ctx->block_mask) == 0) {
+ ret = (*ctx->cipher->do_cipher)(ctx, out, in, inlen);
+ if (ret == 1)
+ *outlen = inlen;
+ else
+ *outlen = 0;
+ return ret;
+ }
+
+
+ blocksize = EVP_CIPHER_CTX_block_size(ctx);
+ left = blocksize - ctx->buf_len;
+ assert(left > 0);
+
+ if (ctx->buf_len) {
+
+ /* if total buffer is smaller then input, store locally */
+ if (inlen < left) {
+ memcpy(ctx->buf + ctx->buf_len, in, inlen);
+ ctx->buf_len += inlen;
+ return 1;
+ }
+
+ /* fill in local buffer and encrypt */
+ memcpy(ctx->buf + ctx->buf_len, in, left);
+ ret = (*ctx->cipher->do_cipher)(ctx, out, ctx->buf, blocksize);
+ memset(ctx->buf, 0, blocksize);
+ if (ret != 1)
+ return ret;
+
+ *outlen += blocksize;
+ inlen -= left;
+ in = ((unsigned char *)in) + left;
+ out = ((unsigned char *)out) + blocksize;
+ ctx->buf_len = 0;
+ }
+
+ if (inlen) {
+ ctx->buf_len = (inlen & ctx->block_mask);
+ inlen &= ~ctx->block_mask;
+
+ ret = (*ctx->cipher->do_cipher)(ctx, out, in, inlen);
+ if (ret != 1)
+ return ret;
+
+ *outlen += inlen;
+
+ in = ((unsigned char *)in) + inlen;
+ memcpy(ctx->buf, in, ctx->buf_len);
+ }
+
+ return 1;
+}
+
+/**
+ * Encipher/decipher final data
+ *
+ * @param ctx the cipher context.
+ * @param out output data from the operation.
+ * @param outlen output length
+ *
+ * The input length needs to be at least EVP_CIPHER_block_size() bytes
+ * long.
+ *
+ * See @ref evp_cipher for an example how to use this function.
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+int
+EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, void *out, int *outlen)
+{
+ *outlen = 0;
+
+ if (ctx->buf_len) {
+ int ret, left, blocksize;
+
+ blocksize = EVP_CIPHER_CTX_block_size(ctx);
+
+ left = blocksize - ctx->buf_len;
+ assert(left > 0);
+
+ /* zero fill local buffer */
+ memset(ctx->buf + ctx->buf_len, 0, left);
+ ret = (*ctx->cipher->do_cipher)(ctx, out, ctx->buf, blocksize);
+ memset(ctx->buf, 0, blocksize);
+ if (ret != 1)
+ return ret;
+
+ *outlen += blocksize;
+ }
+
+ return 1;
+}
+
+/**
+ * Encipher/decipher data
+ *
+ * @param ctx the cipher context.
+ * @param out out data from the operation.
+ * @param in in data to the operation.
+ * @param size length of data.
+ *
+ * @return 1 on success.
+ */
+
+int
+EVP_Cipher(EVP_CIPHER_CTX *ctx, void *out, const void *in,size_t size)
+{
+ return ctx->cipher->do_cipher(ctx, out, in, size);
+}
+
+/*
+ *
+ */
+
+static int
+enc_null_init(EVP_CIPHER_CTX *ctx,
+ const unsigned char * key,
+ const unsigned char * iv,
+ int encp)
+{
+ return 1;
+}
+
+static int
+enc_null_do_cipher(EVP_CIPHER_CTX *ctx,
+ unsigned char *out,
+ const unsigned char *in,
+ unsigned int size)
+{
+ memmove(out, in, size);
+ return 1;
+}
+
+static int
+enc_null_cleanup(EVP_CIPHER_CTX *ctx)
+{
+ return 1;
+}
+
+/**
+ * The NULL cipher type, does no encryption/decryption.
+ *
+ * @return the null EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_enc_null(void)
+{
+ static const EVP_CIPHER enc_null = {
+ 0,
+ 0,
+ 0,
+ 0,
+ EVP_CIPH_CBC_MODE,
+ enc_null_init,
+ enc_null_do_cipher,
+ enc_null_cleanup,
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ };
+ return &enc_null;
+}
+
+/**
+ * The RC2 cipher type
+ *
+ * @return the RC2 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_rc2_cbc(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, rc2_cbc);
+}
+
+/**
+ * The RC2 cipher type
+ *
+ * @return the RC2 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_rc2_40_cbc(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, rc2_40_cbc);
+}
+
+/**
+ * The RC2 cipher type
+ *
+ * @return the RC2 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_rc2_64_cbc(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, rc2_64_cbc);
+}
+
+/**
+ * The RC4 cipher type
+ *
+ * @return the RC4 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_rc4(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, rc4);
+}
+
+/**
+ * The RC4-40 cipher type
+ *
+ * @return the RC4-40 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_rc4_40(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, rc4_40);
+}
+
+/**
+ * The DES cipher type
+ *
+ * @return the DES-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_des_cbc(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, des_cbc);
+}
+
+/**
+ * The triple DES cipher type
+ *
+ * @return the DES-EDE3-CBC EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_des_ede3_cbc(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, des_ede3_cbc);
+}
+
+/**
+ * The AES-128 cipher type
+ *
+ * @return the AES-128 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_aes_128_cbc(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, aes_128_cbc);
+}
+
+/**
+ * The AES-192 cipher type
+ *
+ * @return the AES-192 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_aes_192_cbc(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, aes_192_cbc);
+}
+
+/**
+ * The AES-256 cipher type
+ *
+ * @return the AES-256 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_aes_256_cbc(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, aes_256_cbc);
+}
+
+/**
+ * The AES-128 cipher type
+ *
+ * @return the AES-128 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_aes_128_cfb8(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, aes_128_cfb8);
+}
+
+/**
+ * The AES-192 cipher type
+ *
+ * @return the AES-192 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_aes_192_cfb8(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, aes_192_cfb8);
+}
+
+/**
+ * The AES-256 cipher type
+ *
+ * @return the AES-256 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_aes_256_cfb8(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, aes_256_cfb8);
+}
+
+/**
+ * The Camellia-128 cipher type
+ *
+ * @return the Camellia-128 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_camellia_128_cbc(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, camellia_128_cbc);
+}
+
+/**
+ * The Camellia-198 cipher type
+ *
+ * @return the Camellia-198 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_camellia_192_cbc(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, camellia_192_cbc);
+}
+
+/**
+ * The Camellia-256 cipher type
+ *
+ * @return the Camellia-256 EVP_CIPHER pointer.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_camellia_256_cbc(void)
+{
+ hcrypto_validate();
+ return EVP_DEF_OP(HCRYPTO_DEF_PROVIDER, camellia_256_cbc);
+}
+
+/*
+ *
+ */
+
+static const struct cipher_name {
+ const char *name;
+ const EVP_CIPHER *(*func)(void);
+} cipher_name[] = {
+ { "des-ede3-cbc", EVP_des_ede3_cbc },
+ { "aes-128-cbc", EVP_aes_128_cbc },
+ { "aes-192-cbc", EVP_aes_192_cbc },
+ { "aes-256-cbc", EVP_aes_256_cbc },
+ { "aes-128-cfb8", EVP_aes_128_cfb8 },
+ { "aes-192-cfb8", EVP_aes_192_cfb8 },
+ { "aes-256-cfb8", EVP_aes_256_cfb8 },
+ { "camellia-128-cbc", EVP_camellia_128_cbc },
+ { "camellia-192-cbc", EVP_camellia_192_cbc },
+ { "camellia-256-cbc", EVP_camellia_256_cbc }
+};
+
+/**
+ * Get the cipher type using their name.
+ *
+ * @param name the name of the cipher.
+ *
+ * @return the selected EVP_CIPHER pointer or NULL if not found.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+const EVP_CIPHER *
+EVP_get_cipherbyname(const char *name)
+{
+ int i;
+ for (i = 0; i < sizeof(cipher_name)/sizeof(cipher_name[0]); i++) {
+ if (strcasecmp(cipher_name[i].name, name) == 0)
+ return (*cipher_name[i].func)();
+ }
+ return NULL;
+}
+
+
+/*
+ *
+ */
+
+#ifndef min
+#define min(a,b) (((a)>(b))?(b):(a))
+#endif
+
+/**
+ * Provides a legancy string to key function, used in PEM files.
+ *
+ * New protocols should use new string to key functions like NIST
+ * SP56-800A or PKCS#5 v2.0 (see PKCS5_PBKDF2_HMAC_SHA1()).
+ *
+ * @param type type of cipher to use
+ * @param md message digest to use
+ * @param salt salt salt string, should be an binary 8 byte buffer.
+ * @param data the password/input key string.
+ * @param datalen length of data parameter.
+ * @param count iteration counter.
+ * @param keydata output keydata, needs to of the size EVP_CIPHER_key_length().
+ * @param ivdata output ivdata, needs to of the size EVP_CIPHER_block_size().
+ *
+ * @return the size of derived key.
+ *
+ * @ingroup hcrypto_evp
+ */
+
+int
+EVP_BytesToKey(const EVP_CIPHER *type,
+ const EVP_MD *md,
+ const void *salt,
+ const void *data, size_t datalen,
+ unsigned int count,
+ void *keydata,
+ void *ivdata)
+{
+ unsigned int ivlen, keylen;
+ int first = 0;
+ unsigned int mds = 0, i;
+ unsigned char *key = keydata;
+ unsigned char *iv = ivdata;
+ unsigned char *buf;
+ EVP_MD_CTX c;
+
+ keylen = EVP_CIPHER_key_length(type);
+ ivlen = EVP_CIPHER_iv_length(type);
+
+ if (data == NULL)
+ return keylen;
+
+ buf = malloc(EVP_MD_size(md));
+ if (buf == NULL)
+ return -1;
+
+ EVP_MD_CTX_init(&c);
+
+ first = 1;
+ while (1) {
+ EVP_DigestInit_ex(&c, md, NULL);
+ if (!first)
+ EVP_DigestUpdate(&c, buf, mds);
+ first = 0;
+ EVP_DigestUpdate(&c,data,datalen);
+
+#define PKCS5_SALT_LEN 8
+
+ if (salt)
+ EVP_DigestUpdate(&c, salt, PKCS5_SALT_LEN);
+
+ EVP_DigestFinal_ex(&c, buf, &mds);
+ assert(mds == EVP_MD_size(md));
+
+ for (i = 1; i < count; i++) {
+ EVP_DigestInit_ex(&c, md, NULL);
+ EVP_DigestUpdate(&c, buf, mds);
+ EVP_DigestFinal_ex(&c, buf, &mds);
+ assert(mds == EVP_MD_size(md));
+ }
+
+ i = 0;
+ if (keylen) {
+ size_t sz = min(keylen, mds);
+ if (key) {
+ memcpy(key, buf, sz);
+ key += sz;
+ }
+ keylen -= sz;
+ i += sz;
+ }
+ if (ivlen && mds > i) {
+ size_t sz = min(ivlen, (mds - i));
+ if (iv) {
+ memcpy(iv, &buf[i], sz);
+ iv += sz;
+ }
+ ivlen -= sz;
+ }
+ if (keylen == 0 && ivlen == 0)
+ break;
+ }
+
+ EVP_MD_CTX_cleanup(&c);
+ free(buf);
+
+ return EVP_CIPHER_key_length(type);
+}
+
+/**
+ * Generate a random key for the specificed EVP_CIPHER.
+ *
+ * @param ctx EVP_CIPHER_CTX type to build the key for.
+ * @param key return key, must be at least EVP_CIPHER_key_length() byte long.
+ *
+ * @return 1 for success, 0 for failure.
+ *
+ * @ingroup hcrypto_core
+ */
+
+int
+EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, void *key)
+{
+ if (ctx->cipher->flags & EVP_CIPH_RAND_KEY)
+ return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key);
+ if (RAND_bytes(key, ctx->key_len) != 1)
+ return 0;
+ return 1;
+}
+
+/**
+ * Perform a operation on a ctx
+ *
+ * @param ctx context to perform operation on.
+ * @param type type of operation.
+ * @param arg argument to operation.
+ * @param data addition data to operation.
+
+ * @return 1 for success, 0 for failure.
+ *
+ * @ingroup hcrypto_core
+ */
+
+int
+EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *data)
+{
+ if (ctx->cipher == NULL || ctx->cipher->ctrl == NULL)
+ return 0;
+ return (*ctx->cipher->ctrl)(ctx, type, arg, data);
+}
+
+/**
+ * Add all algorithms to the crypto core.
+ *
+ * @ingroup hcrypto_core
+ */
+
+void
+OpenSSL_add_all_algorithms(void)
+{
+ return;
+}
+
+/**
+ * Add all algorithms to the crypto core using configuration file.
+ *
+ * @ingroup hcrypto_core
+ */
+
+void
+OpenSSL_add_all_algorithms_conf(void)
+{
+ return;
+}
+
+/**
+ * Add all algorithms to the crypto core, but don't use the
+ * configuration file.
+ *
+ * @ingroup hcrypto_core
+ */
+
+void
+OpenSSL_add_all_algorithms_noconf(void)
+{
+ return;
+}
diff --git a/third_party/heimdal/lib/hcrypto/evp.h b/third_party/heimdal/lib/hcrypto/evp.h
new file mode 100644
index 0000000..8893362
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/evp.h
@@ -0,0 +1,361 @@
+/*
+ * Copyright (c) 2005 - 2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_EVP_H
+#define HEIM_EVP_H 1
+
+#include <hcrypto/engine.h>
+
+/* symbol renaming */
+#define EVP_CIPHER_CTX_block_size hc_EVP_CIPHER_CTX_block_size
+#define EVP_CIPHER_CTX_cipher hc_EVP_CIPHER_CTX_cipher
+#define EVP_CIPHER_CTX_cleanup hc_EVP_CIPHER_CTX_cleanup
+#define EVP_CIPHER_CTX_flags hc_EVP_CIPHER_CTX_flags
+#define EVP_CIPHER_CTX_get_app_data hc_EVP_CIPHER_CTX_get_app_data
+#define EVP_CIPHER_CTX_init hc_EVP_CIPHER_CTX_init
+#define EVP_CIPHER_CTX_iv_length hc_EVP_CIPHER_CTX_iv_length
+#define EVP_CIPHER_CTX_key_length hc_EVP_CIPHER_CTX_key_length
+#define EVP_CIPHER_CTX_mode hc_EVP_CIPHER_CTX_mode
+#define EVP_CIPHER_CTX_set_app_data hc_EVP_CIPHER_CTX_set_app_data
+#define EVP_CIPHER_CTX_set_key_length hc_EVP_CIPHER_CTX_set_key_length
+#define EVP_CIPHER_CTX_set_padding hc_EVP_CIPHER_CTX_set_padding
+#define EVP_CIPHER_block_size hc_EVP_CIPHER_block_size
+#define EVP_CIPHER_iv_length hc_EVP_CIPHER_iv_length
+#define EVP_CIPHER_key_length hc_EVP_CIPHER_key_length
+#define EVP_Cipher hc_EVP_Cipher
+#define EVP_CipherInit_ex hc_EVP_CipherInit_ex
+#define EVP_CipherUpdate hc_EVP_CipherUpdate
+#define EVP_CipherFinal_ex hc_EVP_CipherFinal_ex
+#define EVP_Digest hc_EVP_Digest
+#define EVP_DigestFinal_ex hc_EVP_DigestFinal_ex
+#define EVP_DigestInit_ex hc_EVP_DigestInit_ex
+#define EVP_DigestUpdate hc_EVP_DigestUpdate
+#define EVP_MD_CTX_block_size hc_EVP_MD_CTX_block_size
+#define EVP_MD_CTX_cleanup hc_EVP_MD_CTX_cleanup
+#define EVP_MD_CTX_create hc_EVP_MD_CTX_create
+#define EVP_MD_CTX_init hc_EVP_MD_CTX_init
+#define EVP_MD_CTX_destroy hc_EVP_MD_CTX_destroy
+#define EVP_MD_CTX_md hc_EVP_MD_CTX_md
+#define EVP_MD_CTX_size hc_EVP_MD_CTX_size
+#define EVP_MD_block_size hc_EVP_MD_block_size
+#define EVP_MD_size hc_EVP_MD_size
+#define EVP_aes_128_cbc hc_EVP_aes_128_cbc
+#define EVP_aes_192_cbc hc_EVP_aes_192_cbc
+#define EVP_aes_256_cbc hc_EVP_aes_256_cbc
+#define EVP_aes_128_cfb8 hc_EVP_aes_128_cfb8
+#define EVP_aes_192_cfb8 hc_EVP_aes_192_cfb8
+#define EVP_aes_256_cfb8 hc_EVP_aes_256_cfb8
+
+#define EVP_des_cbc hc_EVP_des_cbc
+#define EVP_des_ede3_cbc hc_EVP_des_ede3_cbc
+#define EVP_enc_null hc_EVP_enc_null
+#define EVP_md2 hc_EVP_md2
+#define EVP_md4 hc_EVP_md4
+#define EVP_md5 hc_EVP_md5
+#define EVP_md_null hc_EVP_md_null
+#define EVP_rc2_40_cbc hc_EVP_rc2_40_cbc
+#define EVP_rc2_64_cbc hc_EVP_rc2_64_cbc
+#define EVP_rc2_cbc hc_EVP_rc2_cbc
+#define EVP_rc4 hc_EVP_rc4
+#define EVP_rc4_40 hc_EVP_rc4_40
+#define EVP_camellia_128_cbc hc_EVP_camellia_128_cbc
+#define EVP_camellia_192_cbc hc_EVP_camellia_192_cbc
+#define EVP_camellia_256_cbc hc_EVP_camellia_256_cbc
+#define EVP_sha hc_EVP_sha
+#define EVP_sha1 hc_EVP_sha1
+#define EVP_sha256 hc_EVP_sha256
+#define EVP_sha384 hc_EVP_sha384
+#define EVP_sha512 hc_EVP_sha512
+#define PKCS5_PBKDF2_HMAC hc_PKCS5_PBKDF2_HMAC
+#define PKCS5_PBKDF2_HMAC_SHA1 hc_PKCS5_PBKDF2_HMAC_SHA1
+#define EVP_BytesToKey hc_EVP_BytesToKey
+#define EVP_get_cipherbyname hc_EVP_get_cipherbyname
+#define OpenSSL_add_all_algorithms hc_OpenSSL_add_all_algorithms
+#define OpenSSL_add_all_algorithms_conf hc_OpenSSL_add_all_algorithms_conf
+#define OpenSSL_add_all_algorithms_noconf hc_OpenSSL_add_all_algorithms_noconf
+#define EVP_CIPHER_CTX_ctrl hc_EVP_CIPHER_CTX_ctrl
+#define EVP_CIPHER_CTX_rand_key hc_EVP_CIPHER_CTX_rand_key
+#define hcrypto_validate hc_hcrypto_validate
+
+/* Type name renaming */
+#define EVP_MD_CTX hc_EVP_MD_CTX
+#define EVP_PKEY hc_EVP_PKEY
+#define EVP_MD hc_EVP_MD
+#define EVP_CIPHER hc_EVP_CIPHER
+#define EVP_CIPHER_CTX hc_EVP_CIPHER_CTX
+
+/* Constant renaming */
+#define EVP_CIPH_STREAM_CIPHER hc_EVP_CIPH_STREAM_CIPHER
+#define EVP_CIPH_CBC_MODE hc_EVP_CIPH_CBC_MODE
+#define EVP_CIPH_CFB8_MODE hc_EVP_CIPH_CFB8_MODE
+#define EVP_CIPH_MODE hc_EVP_CIPH_MODE
+#define EVP_CIPH_CTRL_INIT hc_EVP_CIPH_CTRL_INIT
+
+#define EVP_CIPH_VARIABLE_LENGTH hc_EVP_CIPH_VARIABLE_LENGTH
+#define EVP_CIPH_ALWAYS_CALL_INIT hc_EVP_CIPH_ALWAYS_CALL_INIT
+#define EVP_CIPH_RAND_KEY hc_EVP_CIPH_RAND_KEY
+
+#define EVP_CTRL_INIT hc_EVP_CTRL_INIT
+
+
+/*
+ *
+ */
+
+typedef struct hc_EVP_MD_CTX EVP_MD_CTX;
+typedef struct hc_evp_pkey EVP_PKEY;
+typedef struct hc_evp_md EVP_MD;
+typedef struct hc_CIPHER EVP_CIPHER;
+typedef struct hc_CIPHER_CTX EVP_CIPHER_CTX;
+
+#define EVP_MAX_IV_LENGTH 16
+#define EVP_MAX_BLOCK_LENGTH 32
+
+#define EVP_MAX_MD_SIZE 64
+
+struct hc_CIPHER {
+ int nid;
+ int block_size;
+ int key_len;
+ int iv_len;
+ unsigned long flags;
+ /* The lowest 3 bits is used as integer field for the mode the
+ * cipher is used in (use EVP_CIPHER.._mode() to extract the
+ * mode). The rest of the flag field is a bitfield.
+ */
+#define hc_EVP_CIPH_STREAM_CIPHER 0
+#define hc_EVP_CIPH_CBC_MODE 2
+#define hc_EVP_CIPH_CFB8_MODE 4
+#define hc_EVP_CIPH_MODE 0x7
+#define hc_EVP_CIPH_CTRL_INIT 0x40
+
+#define hc_EVP_CTRL_INIT 0x0
+
+#define hc_EVP_CIPH_VARIABLE_LENGTH 0x008 /* variable key length */
+#define hc_EVP_CIPH_ALWAYS_CALL_INIT 0x020 /* backend maintains own cipherstate */
+#define hc_EVP_CIPH_RAND_KEY 0x200
+
+ int (*init)(EVP_CIPHER_CTX*,const unsigned char*,const unsigned char*,int);
+ int (*do_cipher)(EVP_CIPHER_CTX *, unsigned char *,
+ const unsigned char *, unsigned int);
+ int (*cleanup)(EVP_CIPHER_CTX *);
+ int ctx_size;
+ int (*set_asn1_parameters)(void);
+ int (*get_asn1_parameters)(void);
+ int (*ctrl)(EVP_CIPHER_CTX *, int type, int arg, void *ptr);
+#define EVP_CTRL_RAND_KEY 0x6
+
+ void *app_data;
+};
+
+struct hc_CIPHER_CTX {
+ const EVP_CIPHER *cipher;
+ ENGINE *engine;
+ int encrypt;
+ int buf_len; /* bytes stored in buf for EVP_CipherUpdate */
+ unsigned char oiv[EVP_MAX_IV_LENGTH];
+ unsigned char iv[EVP_MAX_IV_LENGTH];
+ unsigned char buf[EVP_MAX_BLOCK_LENGTH];
+ int num;
+ void *app_data;
+ int key_len;
+ unsigned long flags;
+ void *cipher_data;
+ int final_used;
+ int block_mask;
+ unsigned char final[EVP_MAX_BLOCK_LENGTH];
+};
+
+/*
+ * LIES. It's not an EVP_MD_CTX that gets passed to these functions
+ * here in hcrypto, but an object of ctx_size.
+ */
+typedef int (*hc_evp_md_init)(EVP_MD_CTX *);
+typedef int (*hc_evp_md_update)(EVP_MD_CTX *,const void *, size_t);
+typedef int (*hc_evp_md_final)(void *, EVP_MD_CTX *);
+typedef int (*hc_evp_md_cleanup)(EVP_MD_CTX *);
+
+struct hc_evp_md {
+ int hash_size;
+ int block_size;
+ int ctx_size;
+ hc_evp_md_init init;
+ hc_evp_md_update update;
+ hc_evp_md_final final;
+ hc_evp_md_cleanup cleanup;
+};
+
+#if !defined(__GNUC__) && !defined(__attribute__)
+#define __attribute__(x)
+#endif
+
+#ifndef HC_DEPRECATED
+#if defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1 )))
+#define HC_DEPRECATED __attribute__((deprecated))
+#elif defined(_MSC_VER) && (_MSC_VER>1200)
+#define HC_DEPRECATED __declspec(deprecated)
+#else
+#define HC_DEPRECATED
+#endif
+#endif
+
+#ifndef HC_DEPRECATED_CRYPTO
+#define HC_DEPRECATED_CRYPTO HC_DEPRECATED
+#endif
+
+#ifdef __cplusplus
+#define HC_CPP_BEGIN extern "C" {
+#define HC_CPP_END }
+#else
+#define HC_CPP_BEGIN
+#define HC_CPP_END
+#endif
+
+HC_CPP_BEGIN
+
+/*
+ * Avaible crypto algs
+ */
+
+const EVP_MD *EVP_md_null(void);
+HC_DEPRECATED_CRYPTO const EVP_MD *EVP_md2(void);
+HC_DEPRECATED_CRYPTO const EVP_MD *EVP_md4(void);
+HC_DEPRECATED_CRYPTO const EVP_MD *EVP_md5(void);
+const EVP_MD *EVP_sha(void);
+const EVP_MD *EVP_sha1(void);
+const EVP_MD *EVP_sha256(void);
+const EVP_MD *EVP_sha384(void);
+const EVP_MD *EVP_sha512(void);
+
+const EVP_CIPHER * EVP_aes_128_cbc(void);
+const EVP_CIPHER * EVP_aes_192_cbc(void);
+const EVP_CIPHER * EVP_aes_256_cbc(void);
+const EVP_CIPHER * EVP_aes_128_cfb8(void);
+const EVP_CIPHER * EVP_aes_192_cfb8(void);
+const EVP_CIPHER * EVP_aes_256_cfb8(void);
+HC_DEPRECATED_CRYPTO const EVP_CIPHER * EVP_des_cbc(void);
+const EVP_CIPHER * EVP_des_ede3_cbc(void);
+const EVP_CIPHER * EVP_enc_null(void);
+HC_DEPRECATED_CRYPTO const EVP_CIPHER * EVP_rc2_40_cbc(void);
+HC_DEPRECATED_CRYPTO const EVP_CIPHER * EVP_rc2_64_cbc(void);
+HC_DEPRECATED_CRYPTO const EVP_CIPHER * EVP_rc2_cbc(void);
+const EVP_CIPHER * EVP_rc4(void);
+HC_DEPRECATED_CRYPTO const EVP_CIPHER * EVP_rc4_40(void);
+const EVP_CIPHER * EVP_camellia_128_cbc(void);
+const EVP_CIPHER * EVP_camellia_192_cbc(void);
+const EVP_CIPHER * EVP_camellia_256_cbc(void);
+
+size_t EVP_MD_size(const EVP_MD *);
+size_t EVP_MD_block_size(const EVP_MD *);
+
+const EVP_MD *
+ EVP_MD_CTX_md(EVP_MD_CTX *);
+size_t EVP_MD_CTX_size(EVP_MD_CTX *);
+size_t EVP_MD_CTX_block_size(EVP_MD_CTX *);
+
+EVP_MD_CTX *
+ EVP_MD_CTX_create(void);
+void HC_DEPRECATED EVP_MD_CTX_init(EVP_MD_CTX *);
+void EVP_MD_CTX_destroy(EVP_MD_CTX *);
+int HC_DEPRECATED EVP_MD_CTX_cleanup(EVP_MD_CTX *);
+
+int EVP_DigestInit_ex(EVP_MD_CTX *, const EVP_MD *, ENGINE *);
+int EVP_DigestUpdate(EVP_MD_CTX *,const void *, size_t);
+int EVP_DigestFinal_ex(EVP_MD_CTX *, void *, unsigned int *);
+int EVP_Digest(const void *, size_t, void *, unsigned int *,
+ const EVP_MD *, ENGINE *);
+/*
+ *
+ */
+
+const EVP_CIPHER *
+ EVP_get_cipherbyname(const char *);
+
+size_t EVP_CIPHER_block_size(const EVP_CIPHER *);
+size_t EVP_CIPHER_key_length(const EVP_CIPHER *);
+size_t EVP_CIPHER_iv_length(const EVP_CIPHER *);
+
+void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *);
+int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *);
+int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *, int);
+int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *, int);
+unsigned long
+ EVP_CIPHER_CTX_flags(const EVP_CIPHER_CTX *);
+int EVP_CIPHER_CTX_mode(const EVP_CIPHER_CTX *);
+
+const EVP_CIPHER *
+ EVP_CIPHER_CTX_cipher(EVP_CIPHER_CTX *);
+size_t EVP_CIPHER_CTX_block_size(const EVP_CIPHER_CTX *);
+size_t EVP_CIPHER_CTX_key_length(const EVP_CIPHER_CTX *);
+size_t EVP_CIPHER_CTX_iv_length(const EVP_CIPHER_CTX *);
+void * EVP_CIPHER_CTX_get_app_data(EVP_CIPHER_CTX *);
+void EVP_CIPHER_CTX_set_app_data(EVP_CIPHER_CTX *, void *);
+
+int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *, int, int, void *);
+int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *, void *);
+
+
+int EVP_CipherInit_ex(EVP_CIPHER_CTX *,const EVP_CIPHER *, ENGINE *,
+ const void *, const void *, int);
+int EVP_CipherUpdate(EVP_CIPHER_CTX *, void *, int *, void *, size_t);
+int EVP_CipherFinal_ex(EVP_CIPHER_CTX *, void *, int *);
+
+int EVP_Cipher(EVP_CIPHER_CTX *,void *,const void *,size_t);
+
+int PKCS5_PBKDF2_HMAC(const void *, size_t, const void *, size_t,
+ unsigned long, const EVP_MD *, size_t, void *);
+
+int PKCS5_PBKDF2_HMAC_SHA1(const void *, size_t, const void *, size_t,
+ unsigned long, size_t, void *);
+
+int EVP_BytesToKey(const EVP_CIPHER *, const EVP_MD *,
+ const void *, const void *, size_t,
+ unsigned int, void *, void *);
+
+
+/*
+ *
+ */
+
+void OpenSSL_add_all_algorithms(void);
+void OpenSSL_add_all_algorithms_conf(void);
+void OpenSSL_add_all_algorithms_noconf(void);
+
+void
+hcrypto_validate(void);
+
+HC_CPP_END
+
+#endif /* HEIM_EVP_H */
diff --git a/third_party/heimdal/lib/hcrypto/example_evp_cipher.c b/third_party/heimdal/lib/hcrypto/example_evp_cipher.c
new file mode 100644
index 0000000..3bf76b9
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/example_evp_cipher.c
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <krb5-types.h> /* should really be stdint.h */
+#include <hcrypto/evp.h>
+#include <hcrypto/evp-pkcs11.h>
+#ifdef __APPLE__
+#include <hcrypto/evp-cc.h>
+#endif
+#ifdef _WIN32
+#include <hcrypto/evp-w32.h>
+#endif
+
+#include <err.h>
+#include <assert.h>
+
+/* key and initial vector */
+static char key[16] =
+ "\xaa\xbb\x45\xd4\xaa\xbb\x45\xd4"
+ "\xaa\xbb\x45\xd4\xaa\xbb\x45\xd4";
+static char ivec[16] =
+ "\xaa\xbb\x45\xd4\xaa\xbb\x45\xd4"
+ "\xaa\xbb\x45\xd4\xaa\xbb\x45\xd4";
+
+static void
+usage(int exit_code) __attribute__((noreturn));
+
+static void
+usage(int exit_code)
+{
+ printf("usage: %s in out [pkcs11 | cc | w32]\n", getprogname());
+ exit(exit_code);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ int encryptp = 1;
+ const char *ifn = NULL, *ofn = NULL;
+ FILE *in, *out;
+ void *ibuf, *obuf;
+ int ilen, olen;
+ size_t block_size = 0;
+ const EVP_CIPHER *c = EVP_aes_128_cbc();
+ EVP_CIPHER_CTX ctx;
+ int ret;
+
+ setprogname(argv[0]);
+
+ if (argc == 2) {
+ if (strcmp(argv[1], "--version") == 0) {
+ printf("version");
+ exit(0);
+ }
+ if (strcmp(argv[1], "--help") == 0)
+ usage(0);
+ usage(1);
+ } else if (argc == 4 || argc == 5) {
+ block_size = atoi(argv[1]);
+ if (block_size == 0)
+ errx(1, "invalid blocksize %s", argv[1]);
+ ifn = argv[2];
+ ofn = argv[3];
+ if (argc == 5) {
+ if (strcmp(argv[4], "pkcs11") == 0)
+ c = hc_EVP_pkcs11_aes_128_cbc();
+#ifdef __APPLE__
+ else if (strcmp(argv[4], "cc") == 0)
+ c = hc_EVP_cc_aes_128_cbc();
+#endif
+#ifdef _WIN32
+ else if (strcmp(argv[4], "w32") == 0)
+ c = hc_EVP_w32crypto_aes_128_cbc();
+#endif
+ else
+ usage(1);
+ }
+ } else
+ usage(1);
+
+ in = fopen(ifn, "r");
+ if (in == NULL)
+ errx(1, "failed to open input file");
+ out = fopen(ofn, "w+");
+ if (out == NULL)
+ errx(1, "failed to open output file");
+
+ /* Check that key and ivec are long enough */
+ assert(EVP_CIPHER_key_length(c) <= sizeof(key));
+ assert(EVP_CIPHER_iv_length(c) <= sizeof(ivec));
+
+ /*
+ * Allocate buffer, the output buffer is at least
+ * EVP_CIPHER_block_size() longer
+ */
+ ibuf = malloc(block_size);
+ obuf = malloc(block_size + EVP_CIPHER_block_size(c));
+
+ /*
+ * Init the memory used for EVP_CIPHER_CTX and set the key and
+ * ivec.
+ */
+ EVP_CIPHER_CTX_init(&ctx);
+ EVP_CipherInit_ex(&ctx, c, NULL, key, ivec, encryptp);
+
+ /* read in buffer */
+ while ((ilen = fread(ibuf, 1, block_size, in)) > 0) {
+ /* encrypto/decrypt */
+ ret = EVP_CipherUpdate(&ctx, obuf, &olen, ibuf, ilen);
+ if (ret != 1) {
+ EVP_CIPHER_CTX_cleanup(&ctx);
+ errx(1, "EVP_CipherUpdate failed");
+ }
+ /* write out to output file */
+ fwrite(obuf, 1, olen, out);
+ }
+ /* done reading */
+ fclose(in);
+
+ /* clear up any last bytes left in the output buffer */
+ ret = EVP_CipherFinal_ex(&ctx, obuf, &olen);
+ EVP_CIPHER_CTX_cleanup(&ctx);
+ if (ret != 1)
+ errx(1, "EVP_CipherFinal_ex failed");
+
+ /* write the last bytes out and close */
+ fwrite(obuf, 1, olen, out);
+ fclose(out);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hcrypto/gen-des.pl b/third_party/heimdal/lib/hcrypto/gen-des.pl
new file mode 100644
index 0000000..a71a682
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/gen-des.pl
@@ -0,0 +1,217 @@
+#!/usr/pkg/bin/perl
+#
+# $Id$
+
+use strict;
+
+print "/* GENERATE FILE from gen-des.pl, do not edit */\n\n";
+
+my $gen = 1;
+
+sub gen_pattern
+{
+ my $n = shift;
+ my $r = shift;
+ my $a = shift;
+ my $o = shift;
+ my $s = shift;
+ print "/* $n bit pattern ";
+ foreach my $k (@$a) {
+ print "$k ";
+ }
+ print "*/\n";
+ print "static int $n\[", $r + 1, "\] = {\n ";
+ foreach my $i (0..$r) {
+ my $j = 0;
+ my $b = 1;
+ foreach my $k (reverse @$a) {
+ if ($i & $b) {
+ $j |= ($s >>($k - $o - 1));
+ }
+ $b = $b << 1;
+ }
+ printf "0x%08x", $j;
+ print ", " if ($i != $r);
+ if (($i % 4) == 3) {
+ print "\n";
+ print " " if ($i != $r);
+ }
+ }
+ print "};\n";
+}
+
+if ($gen) {
+ gen_pattern("pc1_c_3", 7, [ 5, 13, 21 ], 0, 0x1000000);
+ gen_pattern("pc1_c_4", 15, [ 1, 9, 17, 25 ], 0, 0x1000000);
+ gen_pattern("pc1_d_3", 7, [ 49, 41, 33 ], 32, 0x1000000);
+ gen_pattern("pc1_d_4", 15, [ 57, 53, 45, 37 ], 32, 0x1000000);
+
+ gen_pattern("pc2_c_1", 63, [ 5, 24, 7, 16, 6, 10 ], 0, 0x800000);
+ gen_pattern("pc2_c_2", 63, [ 20, 18, 12, 3, 15, 23 ], 0, 0x800000);
+ gen_pattern("pc2_c_3", 63, [ 1, 9, 19, 2, 14, 22 ], 0, 0x800000);
+ gen_pattern("pc2_c_4", 63, [ 11, 13, 4, 17, 21, 8 ], 0, 0x800000);
+
+ gen_pattern("pc2_d_1", 63, [ 51, 35, 31, 52, 39, 45 ], 28, 0x800000);
+ gen_pattern("pc2_d_2", 63, [ 50, 32, 43, 36, 29, 48 ], 28, 0x800000);
+ gen_pattern("pc2_d_3", 63, [ 41, 38, 47, 33, 40, 42 ], 28, 0x800000);
+ gen_pattern("pc2_d_4", 63, [ 49, 37, 30, 46, 34, 44 ], 28, 0x800000);
+}
+
+sub
+pbox_mutation
+{
+ my $n = shift;
+ my $res = 0;
+
+ my @pbox = (
+ 16, 7, 20, 21,
+ 29, 12, 28, 17,
+ 1, 15, 23, 26,
+ 5, 18, 31, 10,
+ 2, 8, 24, 14,
+ 32, 27, 3, 9,
+ 19, 13, 30, 6,
+ 22, 11, 4, 25
+ );
+
+ foreach my $i (0..31) {
+ if ($n & (1 << ($pbox[$i] - 1))) {
+# print "$i ", ($pbox[$i] - 1), "\n";
+ $res |= 1 << $i;
+ }
+ }
+
+ return $res;
+}
+
+
+my @S1 = (
+ 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
+ 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
+ 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
+ 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13,
+ );
+my @S2 = (
+ 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
+ 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
+ 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
+ 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9,
+ );
+my @S3 = (
+ 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
+ 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
+ 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
+ 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12,
+ );
+my @S4 = (
+ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
+ 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
+ 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
+ 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14,
+ );
+my @S5 = (
+ 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
+ 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
+ 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
+ 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3,
+ );
+my @S6 = (
+ 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
+ 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
+ 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
+ 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13,
+ );
+my @S7 = (
+ 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
+ 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
+ 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
+ 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12,
+ );
+
+my @S8 = (
+ 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
+ 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
+ 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
+ 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11,
+ );
+
+my @SBox = ( \@S1, \@S2, \@S3, \@S4, \@S5, \@S6, \@S7, \@S8 );
+
+sub
+one_num_in_one_sbox
+{
+ my $i = shift;
+ my $n = shift;
+ my $r = shift;
+
+ my $index = (($n & 1) << 4) | (($n & 0x20)) |
+ (($n >> 1) & 0x1) << 0 |
+ (($n >> 2) & 0x1) << 1 |
+ (($n >> 3) & 0x1) << 2 |
+ (($n >> 4) & 0x1) << 3;
+
+ die "argh" if ($index > 63 || $index < 0);
+
+ my $S = $SBox[$i - 1];
+ my $val = $$S[$index];
+
+ my $res = $val << (($i - 1) * 4);
+
+ my $p = &pbox_mutation($res);
+
+ print " $r ";
+
+# $p = ($p >> $r) | ($p << (32 - $r - 1));
+
+ printf "0x%08x", $p;
+ print ", " if ($n != 63 or 1);
+ if (($n % 4) == 3) {
+ print " /* $i */" if ($n == 3);
+ print "\n";
+ print "\t" if ($n != 63);
+ }
+}
+
+sub
+one_sbox
+{
+ my $i = shift;
+ my $s = 0;
+
+# print "static uint32_t sbox". $i ."[] = {\n\t";
+ print "\t";
+ foreach my $n (0..63) {
+ one_num_in_one_sbox($i, $n, $s);
+ }
+ print "\n";
+# print "};\n";
+}
+
+if ($gen and 0) {
+ foreach my $sbox (7, 1, 3, 5, 4, 6, 8, 2) {
+ one_sbox($sbox, 1);
+ }
+}
+
+#my $num = 1;
+#printf "pbox: %d -> 0x%08x\n", $num, pbox_mutation($num);
+#$num = 0xc000000;
+#printf "pbox: 0x%08x -> 0x%08x\n", $num, pbox_mutation($num);
+
+print "static unsigned char odd_parity[256] = { \n";
+foreach my $i (0..255) {
+ my $num = 0;
+ foreach my $b (1..7) {
+ $num++ if (($i >> $b) & 1);
+ }
+ my $t;
+ if (($num & 1) == 0) {
+ $t = $i | 1;
+ } else {
+ $t = 0xfe & $i;
+ }
+ printf "%3d,", $t;
+ printf "\n" if (($i % 16) == 15);
+
+};
+print " };\n";
diff --git a/third_party/heimdal/lib/hcrypto/hash.h b/third_party/heimdal/lib/hcrypto/hash.h
new file mode 100644
index 0000000..0190814
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/hash.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/* $Id$ */
+
+/* stuff in common between md4, md5, and sha1 */
+
+#ifndef __hash_h__
+#define __hash_h__
+
+#ifdef KRB5
+#include <krb5-types.h>
+#endif
+
+#ifndef min
+#define min(a,b) (((a)>(b))?(b):(a))
+#endif
+
+/* Vector Crays doesn't have a good 32-bit type, or more precisely,
+ int32_t as defined by <bind/bitypes.h> isn't 32 bits, and we don't
+ want to depend in being able to redefine this type. To cope with
+ this we have to clamp the result in some places to [0,2^32); no
+ need to do this on other machines. Did I say this was a mess?
+ */
+
+#ifdef _CRAY
+#define CRAYFIX(X) ((X) & 0xffffffff)
+#else
+#define CRAYFIX(X) (X)
+#endif
+
+static inline uint32_t
+cshift (uint32_t x, unsigned int n)
+{
+ x = CRAYFIX(x);
+ return CRAYFIX((x << n) | (x >> (32 - n)));
+}
+
+static inline uint64_t
+cshift64 (uint64_t x, unsigned int n)
+{
+ return ((uint64_t)x << (uint64_t)n) | ((uint64_t)x >> ((uint64_t)64 - (uint64_t)n));
+}
+
+#endif /* __hash_h__ */
diff --git a/third_party/heimdal/lib/hcrypto/hmac.c b/third_party/heimdal/lib/hcrypto/hmac.c
new file mode 100644
index 0000000..6b387ae
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/hmac.c
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <hmac.h>
+
+void
+HMAC_CTX_init(HMAC_CTX *ctx)
+{
+ memset(ctx, 0, sizeof(*ctx));
+}
+
+void
+HMAC_CTX_cleanup(HMAC_CTX *ctx)
+{
+ if (ctx->buf) {
+ memset(ctx->buf, 0, ctx->key_length);
+ free(ctx->buf);
+ ctx->buf = NULL;
+ }
+ if (ctx->opad) {
+ memset(ctx->opad, 0, EVP_MD_block_size(ctx->md));
+ free(ctx->opad);
+ ctx->opad = NULL;
+ }
+ if (ctx->ipad) {
+ memset(ctx->ipad, 0, EVP_MD_block_size(ctx->md));
+ free(ctx->ipad);
+ ctx->ipad = NULL;
+ }
+ if (ctx->ctx) {
+ EVP_MD_CTX_destroy(ctx->ctx);
+ ctx->ctx = NULL;
+ }
+}
+
+HMAC_CTX *
+HMAC_CTX_new(void)
+{
+ return calloc(1, sizeof(HMAC_CTX));
+}
+
+void
+HMAC_CTX_free(HMAC_CTX *ctx)
+{
+ HMAC_CTX_cleanup(ctx);
+ free(ctx);
+}
+
+size_t
+HMAC_size(const HMAC_CTX *ctx)
+{
+ return EVP_MD_size(ctx->md);
+}
+
+int
+HMAC_Init_ex(HMAC_CTX *ctx,
+ const void *key,
+ size_t keylen,
+ const EVP_MD *md,
+ ENGINE *engine)
+{
+ unsigned char *p;
+ size_t i, blockSize;
+
+ blockSize = EVP_MD_block_size(md);
+
+ if (ctx->md != md) {
+ if (ctx->md != NULL)
+ HMAC_CTX_cleanup(ctx);
+
+ ctx->md = md;
+ ctx->key_length = EVP_MD_size(ctx->md);
+ ctx->opad = NULL;
+ ctx->ipad = NULL;
+ ctx->ctx = NULL;
+ ctx->buf = malloc(ctx->key_length);
+ if (ctx->buf)
+ ctx->opad = malloc(blockSize);
+ if (ctx->opad)
+ ctx->ipad = malloc(blockSize);
+ if (ctx->ipad)
+ ctx->ctx = EVP_MD_CTX_create();
+ if (!ctx->buf || !ctx->opad || !ctx->ipad || !ctx->ctx)
+ return 0;
+ }
+#if 0
+ ctx->engine = engine;
+#endif
+
+ if (keylen > blockSize) {
+ if (EVP_Digest(key, keylen, ctx->buf, NULL, ctx->md, engine) == 0)
+ return 0;
+ key = ctx->buf;
+ keylen = EVP_MD_size(ctx->md);
+ }
+
+ memset(ctx->ipad, 0x36, blockSize);
+ memset(ctx->opad, 0x5c, blockSize);
+
+ for (i = 0, p = ctx->ipad; i < keylen; i++)
+ p[i] ^= ((const unsigned char *)key)[i];
+ for (i = 0, p = ctx->opad; i < keylen; i++)
+ p[i] ^= ((const unsigned char *)key)[i];
+
+ if (EVP_DigestInit_ex(ctx->ctx, ctx->md, ctx->engine) == 0)
+ return 0;
+ EVP_DigestUpdate(ctx->ctx, ctx->ipad, EVP_MD_block_size(ctx->md));
+ return 1;
+}
+
+void
+HMAC_Update(HMAC_CTX *ctx, const void *data, size_t len)
+{
+ EVP_DigestUpdate(ctx->ctx, data, len);
+}
+
+void
+HMAC_Final(HMAC_CTX *ctx, void *md, unsigned int *len)
+{
+ EVP_DigestFinal_ex(ctx->ctx, ctx->buf, NULL);
+
+ EVP_DigestInit_ex(ctx->ctx, ctx->md, ctx->engine);
+ EVP_DigestUpdate(ctx->ctx, ctx->opad, EVP_MD_block_size(ctx->md));
+ EVP_DigestUpdate(ctx->ctx, ctx->buf, ctx->key_length);
+ EVP_DigestFinal_ex(ctx->ctx, md, len);
+}
+
+void *
+HMAC(const EVP_MD *md,
+ const void *key, size_t key_size,
+ const void *data, size_t data_size,
+ void *hash, unsigned int *hash_len)
+{
+ HMAC_CTX ctx;
+
+ HMAC_CTX_init(&ctx);
+ if (HMAC_Init_ex(&ctx, key, key_size, md, NULL) == 0) {
+ HMAC_CTX_cleanup(&ctx);
+ return NULL;
+ }
+ HMAC_Update(&ctx, data, data_size);
+ HMAC_Final(&ctx, hash, hash_len);
+ HMAC_CTX_cleanup(&ctx);
+ return hash;
+}
diff --git a/third_party/heimdal/lib/hcrypto/hmac.h b/third_party/heimdal/lib/hcrypto/hmac.h
new file mode 100644
index 0000000..cc99c87
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/hmac.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_HMAC_H
+#define HEIM_HMAC_H 1
+
+#include <hcrypto/evp.h>
+
+/* symbol renaming */
+#define HMAC_CTX_new hc_HMAC_CTX_new
+#define HMAC_CTX_free hc_HMAC_CTX_free
+#define HMAC_CTX_init hc_HMAC_CTX_init
+#define HMAC_CTX_cleanup hc_HMAC_CTX_cleanup
+#define HMAC_size hc_HMAC_size
+#define HMAC_Init_ex hc_HMAC_Init_ex
+#define HMAC_Update hc_HMAC_Update
+#define HMAC_Final hc_HMAC_Final
+#define HMAC hc_HMAC
+
+/*
+ *
+ */
+
+#define HMAC_MAX_MD_CBLOCK 64
+
+typedef struct hc_HMAC_CTX HMAC_CTX;
+
+struct hc_HMAC_CTX {
+ const EVP_MD *md;
+ ENGINE *engine;
+ EVP_MD_CTX *ctx;
+ size_t key_length;
+ void *opad;
+ void *ipad;
+ void *buf;
+};
+
+
+void HMAC_CTX_init(HMAC_CTX *);
+void HMAC_CTX_cleanup(HMAC_CTX *ctx);
+HMAC_CTX *HMAC_CTX_new(void);
+void HMAC_CTX_free(HMAC_CTX *ctx);
+
+size_t HMAC_size(const HMAC_CTX *ctx);
+
+int HMAC_Init_ex(HMAC_CTX *, const void *, size_t,
+ const EVP_MD *, ENGINE *);
+void HMAC_Update(HMAC_CTX *ctx, const void *data, size_t len);
+void HMAC_Final(HMAC_CTX *ctx, void *md, unsigned int *len);
+
+void * HMAC(const EVP_MD *evp_md, const void *key, size_t key_len,
+ const void *data, size_t n, void *md, unsigned int *md_len);
+
+#endif /* HEIM_HMAC_H */
diff --git a/third_party/heimdal/lib/hcrypto/libhcrypto-exports.def b/third_party/heimdal/lib/hcrypto/libhcrypto-exports.def
new file mode 100644
index 0000000..9ce7082
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libhcrypto-exports.def
@@ -0,0 +1,354 @@
+EXPORTS
+ hc_AES_cbc_encrypt
+ hc_AES_cfb8_encrypt
+ hc_AES_decrypt
+ hc_AES_decrypt_key
+ hc_BN_CTX_end
+ hc_BN_CTX_free
+ hc_BN_CTX_get
+ hc_BN_CTX_new
+ hc_BN_CTX_start
+ hc_AES_encrypt
+ hc_AES_set_encrypt_key
+ hc_BN_GENCB_call
+ hc_BN_GENCB_set
+ hc_BN_bin2bn
+ hc_BN_bn2bin
+ hc_BN_bn2hex
+ hc_BN_clear
+ hc_BN_clear_bit
+ hc_BN_clear_free
+ hc_BN_cmp
+ hc_BN_dup
+ hc_BN_free
+ hc_BN_get_word
+ hc_BN_hex2bn
+ hc_BN_is_bit_set
+ hc_BN_is_negative
+ hc_BN_new
+ hc_BN_num_bits
+ hc_BN_num_bytes
+ hc_BN_rand
+ hc_BN_set_bit
+ hc_BN_set_negative
+ hc_BN_set_word
+ hc_BN_uadd
+ hc_DES_cbc_cksum
+ hc_DES_cbc_encrypt
+ hc_DES_cfb64_encrypt
+ hc_DES_check_key_parity
+ hc_DES_ecb3_encrypt
+ hc_DES_ecb_encrypt
+ hc_DES_ede3_cbc_encrypt
+ hc_DES_encrypt
+ hc_DES_generate_random_block
+ hc_DES_init_random_number_generator
+ hc_DES_is_weak_key
+ hc_DES_key_sched
+;! hc_DES_mem_rand8
+ hc_DES_new_random_key
+ hc_DES_pcbc_encrypt
+ hc_DES_rand_data
+ hc_DES_rand_data_key
+ hc_DES_random_key
+ hc_DES_read_password
+ hc_DES_set_key
+ hc_DES_set_key_checked
+ hc_DES_set_key_unchecked
+ hc_DES_set_odd_parity
+ hc_DES_set_random_generator_seed
+ hc_DES_set_sequence_number
+ hc_DES_string_to_key
+ hc_DH_check_pubkey
+ hc_DH_compute_key
+ hc_DH_free
+ hc_DH_generate_key
+ hc_DH_generate_parameters_ex
+ hc_DH_get_default_method
+ hc_DH_get_ex_data
+ hc_DH_ltm_method
+;! hc_DH_gmp_method
+ hc_DH_new
+ hc_DH_new_method
+ hc_DH_null_method
+ hc_DH_set_default_method
+ hc_DH_set_ex_data
+ hc_DH_set_method
+ hc_DH_size
+ hc_DH_up_ref
+ hc_DSA_free
+ hc_DSA_get_default_method
+ hc_DSA_new
+ hc_DSA_null_method
+ hc_DSA_set_default_method
+ hc_DSA_up_ref
+ hc_DSA_verify
+ hc_ENGINE_add_conf_module
+ hc_ENGINE_by_dso
+ hc_ENGINE_by_id
+ hc_ENGINE_finish
+ hc_ENGINE_free
+ hc_ENGINE_get_DH
+ hc_ENGINE_get_RAND
+ hc_ENGINE_get_RSA
+ hc_ENGINE_get_default_DH
+ hc_ENGINE_get_default_RSA
+ hc_ENGINE_get_id
+ hc_ENGINE_get_name
+ hc_ENGINE_load_builtin_engines
+ hc_ENGINE_new
+ hc_ENGINE_set_DH
+ hc_ENGINE_set_RSA
+ hc_ENGINE_set_default_DH
+ hc_ENGINE_set_default_RSA
+ hc_ENGINE_set_destroy_function
+ hc_ENGINE_set_id
+ hc_ENGINE_set_name
+ hc_ENGINE_up_ref
+ hc_EVP_BytesToKey
+ hc_EVP_CIPHER_CTX_block_size
+ hc_EVP_CIPHER_CTX_cipher
+ hc_EVP_CIPHER_CTX_cleanup
+ hc_EVP_CIPHER_CTX_flags
+ hc_EVP_CIPHER_CTX_get_app_data
+ hc_EVP_CIPHER_CTX_init
+ hc_EVP_CIPHER_CTX_iv_length
+ hc_EVP_CIPHER_CTX_key_length
+ hc_EVP_CIPHER_CTX_mode
+ hc_EVP_CIPHER_CTX_set_app_data
+ hc_EVP_CIPHER_block_size
+ hc_EVP_CIPHER_iv_length
+ hc_EVP_CIPHER_key_length
+ hc_EVP_Cipher
+ hc_EVP_CipherInit_ex
+ hc_EVP_Digest
+ hc_EVP_DigestFinal_ex
+ hc_EVP_DigestInit_ex
+ hc_EVP_DigestUpdate
+ hc_EVP_MD_CTX_block_size
+ hc_EVP_MD_CTX_cleanup
+ hc_EVP_MD_CTX_create
+ hc_EVP_MD_CTX_destroy
+ hc_EVP_MD_CTX_init
+ hc_EVP_MD_CTX_md
+ hc_EVP_MD_CTX_size
+ hc_EVP_MD_block_size
+ hc_EVP_MD_size
+ hc_EVP_aes_128_cbc
+ hc_EVP_aes_128_cfb8
+ hc_EVP_aes_192_cbc
+ hc_EVP_aes_192_cfb8
+ hc_EVP_aes_256_cbc
+ hc_EVP_aes_256_cfb8
+ hc_EVP_des_cbc
+ hc_EVP_des_ede3_cbc
+ hc_EVP_camellia_128_cbc
+ hc_EVP_camellia_192_cbc
+ hc_EVP_camellia_256_cbc
+ hc_EVP_enc_null
+ hc_EVP_get_cipherbyname
+ hc_EVP_md2
+ hc_EVP_md4
+ hc_EVP_md5
+ hc_EVP_md_null
+ hc_EVP_rc2_40_cbc
+ hc_EVP_rc2_64_cbc
+ hc_EVP_rc2_cbc
+ hc_EVP_rc4
+ hc_EVP_rc4_40
+ hc_EVP_sha
+ hc_EVP_sha1
+ hc_EVP_sha256
+ hc_EVP_sha384
+ hc_EVP_sha512
+
+;! hc_EVP_cc_md2
+;! hc_EVP_cc_md4
+;! hc_EVP_cc_md5
+;! hc_EVP_cc_sha1
+;! hc_EVP_cc_sha256
+;! hc_EVP_cc_sha384
+;! hc_EVP_cc_sha512
+;! hc_EVP_cc_des_ede3_cbc
+;! hc_EVP_cc_aes_128_cbc
+;! hc_EVP_cc_aes_192_cbc
+;! hc_EVP_cc_aes_256_cbc
+;! hc_EVP_cc_aes_128_cfb8
+;! hc_EVP_cc_aes_192_cfb8
+;! hc_EVP_cc_aes_256_cfb8
+
+ hc_EVP_ossl_md2
+ hc_EVP_ossl_md4
+ hc_EVP_ossl_md5
+ hc_EVP_ossl_sha1
+ hc_EVP_ossl_sha256
+ hc_EVP_ossl_sha384
+ hc_EVP_ossl_sha512
+ hc_EVP_ossl_des_ede3_cbc
+ hc_EVP_ossl_aes_128_cbc
+ hc_EVP_ossl_aes_192_cbc
+ hc_EVP_ossl_aes_256_cbc
+ hc_EVP_ossl_aes_128_cfb8
+ hc_EVP_ossl_aes_192_cfb8
+ hc_EVP_ossl_aes_256_cfb8
+ hc_EVP_ossl_rc2_cbc
+ hc_EVP_ossl_rc2_40_cbc
+ hc_EVP_ossl_rc4
+ hc_EVP_ossl_rc4_40
+
+ hc_EVP_pkcs11_md2
+ hc_EVP_pkcs11_md4
+ hc_EVP_pkcs11_md5
+ hc_EVP_pkcs11_sha1
+ hc_EVP_pkcs11_sha256
+ hc_EVP_pkcs11_des_ede3_cbc
+ hc_EVP_pkcs11_aes_128_cbc
+ hc_EVP_pkcs11_aes_192_cbc
+ hc_EVP_pkcs11_aes_256_cbc
+ hc_EVP_pkcs11_aes_128_cfb8
+ hc_EVP_pkcs11_aes_192_cfb8
+ hc_EVP_pkcs11_aes_256_cfb8
+ hc_EVP_pkcs11_rc2_40_cbc
+ hc_EVP_pkcs11_rc2_64_cbc
+ hc_EVP_pkcs11_rc2_cbc
+ hc_EVP_pkcs11_rc4
+ hc_EVP_pkcs11_rc4_40
+
+ hc_EVP_w32crypto_md2 ;!
+ hc_EVP_w32crypto_md4 ;!
+ hc_EVP_w32crypto_md5 ;!
+ hc_EVP_w32crypto_sha1 ;!
+ hc_EVP_w32crypto_sha256 ;!
+ hc_EVP_w32crypto_sha384 ;!
+ hc_EVP_w32crypto_sha512 ;!
+ hc_EVP_w32crypto_des_ede3_cbc ;!
+ hc_EVP_w32crypto_aes_128_cbc ;!
+ hc_EVP_w32crypto_aes_192_cbc ;!
+ hc_EVP_w32crypto_aes_256_cbc ;!
+ hc_EVP_w32crypto_rc2_40_cbc ;!
+ hc_EVP_w32crypto_rc2_cbc ;!
+ hc_EVP_w32crypto_rc4 ;!
+ hc_EVP_w32crypto_rc4_40 ;!
+
+ hc_EVP_w32crypto_aes_128_cfb8 ;!
+ hc_EVP_w32crypto_aes_192_cfb8 ;!
+ hc_EVP_w32crypto_aes_256_cfb8 ;!
+
+ hc_EVP_hcrypto_md2
+ hc_EVP_hcrypto_md4
+ hc_EVP_hcrypto_md5
+ hc_EVP_hcrypto_sha1
+ hc_EVP_hcrypto_sha256
+ hc_EVP_hcrypto_sha384
+ hc_EVP_hcrypto_sha512
+ hc_EVP_hcrypto_des_ede3_cbc
+ hc_EVP_hcrypto_aes_128_cbc
+ hc_EVP_hcrypto_aes_192_cbc
+ hc_EVP_hcrypto_aes_256_cbc
+ hc_EVP_hcrypto_rc4
+ hc_EVP_hcrypto_rc4_40
+
+ hc_EVP_hcrypto_aes_128_cfb8
+ hc_EVP_hcrypto_aes_192_cfb8
+ hc_EVP_hcrypto_aes_256_cfb8
+
+;! hc_EVP_hcrypto_aes_128_cts
+;! hc_EVP_hcrypto_aes_192_cts
+;! hc_EVP_hcrypto_aes_256_cts
+
+ hc_HMAC
+ hc_HMAC_CTX_cleanup
+ hc_HMAC_CTX_init
+ hc_HMAC_CTX_free
+ hc_HMAC_CTX_new
+ hc_HMAC_Final
+ hc_HMAC_Init_ex
+ hc_HMAC_Update
+ hc_HMAC_size
+ hc_MD2_Final
+ hc_MD2_Init
+ hc_MD2_Update
+ hc_MD4_Final
+ hc_MD4_Init
+ hc_MD4_Update
+ hc_MD5_Final
+ hc_MD5_Init
+ hc_MD5_Update
+ hc_OpenSSL_add_all_algorithms
+ hc_OpenSSL_add_all_algorithms_conf
+ hc_OpenSSL_add_all_algorithms_noconf
+ hc_PKCS12_key_gen
+ hc_PKCS5_PBKDF2_HMAC
+ hc_PKCS5_PBKDF2_HMAC_SHA1
+ hc_RAND_add
+ hc_RAND_bytes
+ hc_RAND_cleanup
+ hc_RAND_file_name
+;! hc_RAND_fortuna_method
+ hc_RAND_get_rand_method
+ hc_RAND_load_file
+ hc_RAND_pseudo_bytes
+ hc_RAND_seed
+ hc_RAND_set_rand_engine
+ hc_RAND_set_rand_method
+ hc_RAND_status
+;! hc_RAND_unix_method
+;! hc_RAND_timer_method
+ hc_RAND_w32crypto_method ;!
+ hc_RAND_write_file
+ hc_RC2_cbc_encrypt
+ hc_RC2_decryptc
+ hc_RC2_encryptc
+ hc_RC2_set_key
+ hc_RC4
+ hc_RC4_set_key
+ hc_RSA_check_key
+ hc_RSA_free
+ hc_RSA_generate_key_ex
+ hc_RSA_get_app_data
+ hc_RSA_get_default_method
+ hc_RSA_get_method
+ hc_RSA_new
+ hc_RSA_new_method
+ hc_RSA_null_method
+ hc_RSA_private_decrypt
+ hc_RSA_private_encrypt
+ hc_RSA_public_decrypt
+ hc_RSA_public_encrypt
+ hc_RSA_set_app_data
+ hc_RSA_set_default_method
+ hc_RSA_set_method
+ hc_RSA_sign
+ hc_RSA_size
+ hc_RSA_up_ref
+ hc_RSA_verify
+ hc_SHA1_Final
+ hc_SHA1_Init
+ hc_SHA1_Update
+ hc_SHA256_Final
+ hc_SHA256_Init
+ hc_SHA256_Update
+ hc_SHA384_Final
+ hc_SHA384_Init
+ hc_SHA384_Update
+ hc_SHA512_Final
+ hc_SHA512_Init
+ hc_SHA512_Update
+ hc_UI_UTIL_read_pw_string
+ hc_i2d_DHparams
+ hc_d2i_RSAPrivateKey
+ hc_i2d_RSAPrivateKey
+ hc_i2d_RSAPublicKey
+ hc_d2i_RSAPublicKey
+ hc_EVP_CIPHER_CTX_ctrl
+ hc_EVP_CIPHER_CTX_rand_key
+ hc_EVP_CIPHER_CTX_set_key_length
+ hc_EVP_hcrypto_rc2_cbc
+ hc_EVP_hcrypto_rc2_40_cbc
+ hc_EVP_hcrypto_camellia_128_cbc
+ hc_EVP_CipherUpdate
+ hc_EVP_CipherFinal_ex
+
+ hc_hcrypto_validate
+ hc_hcrypto_scalarmult_curve25519
+ hc_hcrypto_scalarmult_curve25519_base
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/LICENSE b/third_party/heimdal/lib/hcrypto/libtommath/LICENSE
new file mode 100644
index 0000000..b23b3c8
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/LICENSE
@@ -0,0 +1,26 @@
+ The LibTom license
+
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+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 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.
+
+For more information, please refer to <http://unlicense.org/>
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/NTMakefile b/third_party/heimdal/lib/hcrypto/libtommath/NTMakefile
new file mode 100644
index 0000000..082054a
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/NTMakefile
@@ -0,0 +1,203 @@
+########################################################################
+#
+# Copyright (c) 2009, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\hcrypto\libtommath
+
+!include ../../../windows/NTMakefile.w32
+
+INCFILES= \
+ $(INCDIR)\tommath.h \
+ $(INCDIR)\tommath_class.h \
+ $(INCDIR)\tommath_superclass.h
+
+libltm_OBJs= \
+ $(OBJ)\bn_cutoffs.obj \
+ $(OBJ)\bn_deprecated.obj \
+ $(OBJ)\bn_mp_2expt.obj \
+ $(OBJ)\bn_mp_abs.obj \
+ $(OBJ)\bn_mp_add.obj \
+ $(OBJ)\bn_mp_add_d.obj \
+ $(OBJ)\bn_mp_addmod.obj \
+ $(OBJ)\bn_mp_and.obj \
+ $(OBJ)\bn_mp_clamp.obj \
+ $(OBJ)\bn_mp_clear.obj \
+ $(OBJ)\bn_mp_clear_multi.obj \
+ $(OBJ)\bn_mp_cmp.obj \
+ $(OBJ)\bn_mp_cmp_d.obj \
+ $(OBJ)\bn_mp_cmp_mag.obj \
+ $(OBJ)\bn_mp_cnt_lsb.obj \
+ $(OBJ)\bn_mp_complement.obj \
+ $(OBJ)\bn_mp_copy.obj \
+ $(OBJ)\bn_mp_count_bits.obj \
+ $(OBJ)\bn_mp_decr.obj \
+ $(OBJ)\bn_mp_div.obj \
+ $(OBJ)\bn_mp_div_2.obj \
+ $(OBJ)\bn_mp_div_2d.obj \
+ $(OBJ)\bn_mp_div_3.obj \
+ $(OBJ)\bn_mp_div_d.obj \
+ $(OBJ)\bn_mp_dr_is_modulus.obj \
+ $(OBJ)\bn_mp_dr_reduce.obj \
+ $(OBJ)\bn_mp_dr_setup.obj \
+ $(OBJ)\bn_mp_error_to_string.obj\
+ $(OBJ)\bn_mp_exch.obj \
+ $(OBJ)\bn_mp_expt_u32.obj \
+ $(OBJ)\bn_mp_exptmod.obj \
+ $(OBJ)\bn_mp_exteuclid.obj \
+ $(OBJ)\bn_mp_fread.obj \
+ $(OBJ)\bn_mp_from_sbin.obj \
+ $(OBJ)\bn_mp_from_ubin.obj \
+ $(OBJ)\bn_mp_fwrite.obj \
+ $(OBJ)\bn_mp_gcd.obj \
+ $(OBJ)\bn_mp_get_double.obj \
+ $(OBJ)\bn_mp_get_i32.obj \
+ $(OBJ)\bn_mp_get_i64.obj \
+ $(OBJ)\bn_mp_get_l.obj \
+ $(OBJ)\bn_mp_get_ll.obj \
+ $(OBJ)\bn_mp_get_mag_u32.obj \
+ $(OBJ)\bn_mp_get_mag_u64.obj \
+ $(OBJ)\bn_mp_get_mag_ul.obj \
+ $(OBJ)\bn_mp_get_mag_ull.obj \
+ $(OBJ)\bn_mp_grow.obj \
+ $(OBJ)\bn_mp_incr.obj \
+ $(OBJ)\bn_mp_init.obj \
+ $(OBJ)\bn_mp_init_copy.obj \
+ $(OBJ)\bn_mp_init_i32.obj \
+ $(OBJ)\bn_mp_init_i64.obj \
+ $(OBJ)\bn_mp_init_l.obj \
+ $(OBJ)\bn_mp_init_ll.obj \
+ $(OBJ)\bn_mp_init_multi.obj \
+ $(OBJ)\bn_mp_init_set.obj \
+ $(OBJ)\bn_mp_init_size.obj \
+ $(OBJ)\bn_mp_init_u32.obj \
+ $(OBJ)\bn_mp_init_u64.obj \
+ $(OBJ)\bn_mp_init_ul.obj \
+ $(OBJ)\bn_mp_init_ull.obj \
+ $(OBJ)\bn_mp_invmod.obj \
+ $(OBJ)\bn_mp_is_square.obj \
+ $(OBJ)\bn_mp_iseven.obj \
+ $(OBJ)\bn_mp_isodd.obj \
+ $(OBJ)\bn_mp_kronecker.obj \
+ $(OBJ)\bn_mp_lcm.obj \
+ $(OBJ)\bn_mp_log_u32.obj \
+ $(OBJ)\bn_mp_lshd.obj \
+ $(OBJ)\bn_mp_mod.obj \
+ $(OBJ)\bn_mp_mod_2d.obj \
+ $(OBJ)\bn_mp_mod_d.obj \
+ $(OBJ)\bn_mp_montgomery_calc_normalization.obj \
+ $(OBJ)\bn_mp_montgomery_reduce.obj \
+ $(OBJ)\bn_mp_montgomery_setup.obj \
+ $(OBJ)\bn_mp_mul.obj \
+ $(OBJ)\bn_mp_mul_2.obj \
+ $(OBJ)\bn_mp_mul_2d.obj \
+ $(OBJ)\bn_mp_mul_d.obj \
+ $(OBJ)\bn_mp_mulmod.obj \
+ $(OBJ)\bn_mp_neg.obj \
+ $(OBJ)\bn_mp_or.obj \
+ $(OBJ)\bn_mp_pack.obj \
+ $(OBJ)\bn_mp_pack_count.obj \
+ $(OBJ)\bn_mp_prime_fermat.obj \
+ $(OBJ)\bn_mp_prime_frobenius_underwood.obj \
+ $(OBJ)\bn_mp_prime_is_prime.obj \
+ $(OBJ)\bn_mp_prime_miller_rabin.obj \
+ $(OBJ)\bn_mp_prime_next_prime.obj \
+ $(OBJ)\bn_mp_prime_rabin_miller_trials.obj \
+ $(OBJ)\bn_mp_prime_rand.obj \
+ $(OBJ)\bn_mp_prime_strong_lucas_selfridge.obj \
+ $(OBJ)\bn_mp_radix_size.obj \
+ $(OBJ)\bn_mp_radix_smap.obj \
+ $(OBJ)\bn_mp_rand.obj \
+ $(OBJ)\bn_mp_read_radix.obj \
+ $(OBJ)\bn_mp_reduce.obj \
+ $(OBJ)\bn_mp_reduce_2k.obj \
+ $(OBJ)\bn_mp_reduce_2k_l.obj \
+ $(OBJ)\bn_mp_reduce_2k_setup.obj \
+ $(OBJ)\bn_mp_reduce_2k_setup_l.obj \
+ $(OBJ)\bn_mp_reduce_is_2k.obj \
+ $(OBJ)\bn_mp_reduce_is_2k_l.obj \
+ $(OBJ)\bn_mp_reduce_setup.obj \
+ $(OBJ)\bn_mp_root_u32.obj \
+ $(OBJ)\bn_mp_rshd.obj \
+ $(OBJ)\bn_mp_sbin_size.obj \
+ $(OBJ)\bn_mp_set.obj \
+ $(OBJ)\bn_mp_set_double.obj \
+ $(OBJ)\bn_mp_set_i32.obj \
+ $(OBJ)\bn_mp_set_i64.obj \
+ $(OBJ)\bn_mp_set_l.obj \
+ $(OBJ)\bn_mp_set_ll.obj \
+ $(OBJ)\bn_mp_set_u32.obj \
+ $(OBJ)\bn_mp_set_u64.obj \
+ $(OBJ)\bn_mp_set_ul.obj \
+ $(OBJ)\bn_mp_set_ull.obj \
+ $(OBJ)\bn_mp_shrink.obj \
+ $(OBJ)\bn_mp_signed_rsh.obj \
+ $(OBJ)\bn_mp_sqr.obj \
+ $(OBJ)\bn_mp_sqrmod.obj \
+ $(OBJ)\bn_mp_sqrt.obj \
+ $(OBJ)\bn_mp_sqrtmod_prime.obj \
+ $(OBJ)\bn_mp_sub.obj \
+ $(OBJ)\bn_mp_sub_d.obj \
+ $(OBJ)\bn_mp_submod.obj \
+ $(OBJ)\bn_mp_to_radix.obj \
+ $(OBJ)\bn_mp_to_sbin.obj \
+ $(OBJ)\bn_mp_to_ubin.obj \
+ $(OBJ)\bn_mp_ubin_size.obj \
+ $(OBJ)\bn_mp_unpack.obj \
+ $(OBJ)\bn_mp_xor.obj \
+ $(OBJ)\bn_mp_zero.obj \
+ $(OBJ)\bn_prime_tab.obj \
+ $(OBJ)\bn_s_mp_add.obj \
+ $(OBJ)\bn_s_mp_balance_mul.obj \
+ $(OBJ)\bn_s_mp_exptmod.obj \
+ $(OBJ)\bn_s_mp_exptmod_fast.obj \
+ $(OBJ)\bn_s_mp_get_bit.obj \
+ $(OBJ)\bn_s_mp_invmod_fast.obj \
+ $(OBJ)\bn_s_mp_invmod_slow.obj \
+ $(OBJ)\bn_s_mp_karatsuba_mul.obj\
+ $(OBJ)\bn_s_mp_karatsuba_sqr.obj\
+ $(OBJ)\bn_s_mp_montgomery_reduce_fast.obj \
+ $(OBJ)\bn_s_mp_mul_digs.obj \
+ $(OBJ)\bn_s_mp_mul_digs_fast.obj\
+ $(OBJ)\bn_s_mp_mul_high_digs.obj\
+ $(OBJ)\bn_s_mp_mul_high_digs_fast.obj \
+ $(OBJ)\bn_s_mp_prime_is_divisible.obj \
+ $(OBJ)\bn_s_mp_rand_jenkins.obj \
+ $(OBJ)\bn_s_mp_rand_platform.obj\
+ $(OBJ)\bn_s_mp_reverse.obj \
+ $(OBJ)\bn_s_mp_sqr.obj \
+ $(OBJ)\bn_s_mp_sqr_fast.obj \
+ $(OBJ)\bn_s_mp_sub.obj \
+ $(OBJ)\bn_s_mp_toom_mul.obj \
+ $(OBJ)\bn_s_mp_toom_sqr.obj
+
+$(LIBLTM): $(libltm_OBJs)
+ $(LIBCON)
+
+all:: $(INCFILES) $(LIBLTM)
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/README.md b/third_party/heimdal/lib/hcrypto/libtommath/README.md
new file mode 100644
index 0000000..be5b207
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/README.md
@@ -0,0 +1,44 @@
+# libtommath
+
+This is the git repository for [LibTomMath](http://www.libtom.net/LibTomMath/), a free open source portable number theoretic multiple-precision integer (MPI) library written entirely in C.
+
+## Build Status
+
+### Travis CI
+
+master: [![Build Status](https://api.travis-ci.org/libtom/libtommath.png?branch=master)](https://travis-ci.org/libtom/libtommath)
+
+develop: [![Build Status](https://api.travis-ci.org/libtom/libtommath.png?branch=develop)](https://travis-ci.org/libtom/libtommath)
+
+### AppVeyor
+
+master: [![Build status](https://ci.appveyor.com/api/projects/status/b80lpolw3i8m6hsh/branch/master?svg=true)](https://ci.appveyor.com/project/libtom/libtommath/branch/master)
+
+develop: [![Build status](https://ci.appveyor.com/api/projects/status/b80lpolw3i8m6hsh/branch/develop?svg=true)](https://ci.appveyor.com/project/libtom/libtommath/branch/develop)
+
+### ABI Laboratory
+
+API/ABI changes: [check here](https://abi-laboratory.pro/tracker/timeline/libtommath/)
+
+## Summary
+
+The `develop` branch contains the in-development version. Stable releases are tagged.
+
+Documentation is built from the LaTeX file `bn.tex`. There is also limited documentation in `tommath.h`.
+There is also a document, `tommath.pdf`, which describes the goals of the project and many of the algorithms used.
+
+The project can be build by using `make`. Along with the usual `make`, `make clean` and `make install`,
+there are several other build targets, see the makefile for details.
+There are also makefiles for certain specific platforms.
+
+## Testing
+
+Tests are located in `demo/` and can be built in two flavors.
+* `make test` creates a stand-alone test binary that executes several test routines.
+* `make mtest_opponent` creates a test binary that is intended to be run against `mtest`.
+ `mtest` can be built with `make mtest` and test execution is done like `./mtest/mtest | ./mtest_opponent`.
+ `mtest` is creating test vectors using an alternative MPI library and `test` is consuming these vectors to verify correct behavior of ltm
+
+## Building and Installing
+
+Building is straightforward for GNU Linux only, the section "Building LibTomMath" in the documentation in `doc/bn.pdf` has the details.
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/appveyor.yml b/third_party/heimdal/lib/hcrypto/libtommath/appveyor.yml
new file mode 100644
index 0000000..efe4568
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/appveyor.yml
@@ -0,0 +1,20 @@
+version: 1.2.0-{build}
+branches:
+ only:
+ - master
+ - develop
+ - /^release/
+ - /^travis/
+image:
+- Visual Studio 2019
+- Visual Studio 2017
+- Visual Studio 2015
+build_script:
+- cmd: >-
+ if "Visual Studio 2019"=="%APPVEYOR_BUILD_WORKER_IMAGE%" call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"
+ if "Visual Studio 2017"=="%APPVEYOR_BUILD_WORKER_IMAGE%" call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat"
+ if "Visual Studio 2015"=="%APPVEYOR_BUILD_WORKER_IMAGE%" call "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64
+ if "Visual Studio 2015"=="%APPVEYOR_BUILD_WORKER_IMAGE%" call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86_amd64
+ nmake -f makefile.msvc all
+test_script:
+- cmd: test.exe
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/astylerc b/third_party/heimdal/lib/hcrypto/libtommath/astylerc
new file mode 100644
index 0000000..c5ff779
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/astylerc
@@ -0,0 +1,30 @@
+# Artistic Style, see http://astyle.sourceforge.net/
+# full documentation, see: http://astyle.sourceforge.net/astyle.html
+#
+# usage:
+# astyle --options=astylerc *.[ch]
+
+# Do not create backup, annonying in the times of git
+suffix=none
+
+## Bracket Style Options
+style=kr
+
+## Tab Options
+indent=spaces=3
+
+## Bracket Modify Options
+
+## Indentation Options
+min-conditional-indent=0
+
+## Padding Options
+pad-header
+unpad-paren
+align-pointer=name
+
+## Formatting Options
+break-after-logical
+max-code-length=120
+convert-tabs
+mode=c
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_cutoffs.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_cutoffs.c
new file mode 100644
index 0000000..b02ab71
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_cutoffs.c
@@ -0,0 +1,14 @@
+#include "tommath_private.h"
+#ifdef BN_CUTOFFS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#ifndef MP_FIXED_CUTOFFS
+#include "tommath_cutoffs.h"
+int KARATSUBA_MUL_CUTOFF = MP_DEFAULT_KARATSUBA_MUL_CUTOFF,
+ KARATSUBA_SQR_CUTOFF = MP_DEFAULT_KARATSUBA_SQR_CUTOFF,
+ TOOM_MUL_CUTOFF = MP_DEFAULT_TOOM_MUL_CUTOFF,
+ TOOM_SQR_CUTOFF = MP_DEFAULT_TOOM_SQR_CUTOFF;
+#endif
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_deprecated.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_deprecated.c
new file mode 100644
index 0000000..2056b20
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_deprecated.c
@@ -0,0 +1,321 @@
+#include "tommath_private.h"
+#ifdef BN_DEPRECATED_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#ifdef BN_MP_GET_BIT_C
+int mp_get_bit(const mp_int *a, int b)
+{
+ if (b < 0) {
+ return MP_VAL;
+ }
+ return (s_mp_get_bit(a, (unsigned int)b) == MP_YES) ? MP_YES : MP_NO;
+}
+#endif
+#ifdef BN_MP_JACOBI_C
+mp_err mp_jacobi(const mp_int *a, const mp_int *n, int *c)
+{
+ if (a->sign == MP_NEG) {
+ return MP_VAL;
+ }
+ if (mp_cmp_d(n, 0uL) != MP_GT) {
+ return MP_VAL;
+ }
+ return mp_kronecker(a, n, c);
+}
+#endif
+#ifdef BN_MP_PRIME_RANDOM_EX_C
+mp_err mp_prime_random_ex(mp_int *a, int t, int size, int flags, private_mp_prime_callback cb, void *dat)
+{
+ return s_mp_prime_random_ex(a, t, size, flags, cb, dat);
+}
+#endif
+#ifdef BN_MP_RAND_DIGIT_C
+mp_err mp_rand_digit(mp_digit *r)
+{
+ mp_err err = s_mp_rand_source(r, sizeof(mp_digit));
+ *r &= MP_MASK;
+ return err;
+}
+#endif
+#ifdef BN_FAST_MP_INVMOD_C
+mp_err fast_mp_invmod(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return s_mp_invmod_fast(a, b, c);
+}
+#endif
+#ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
+mp_err fast_mp_montgomery_reduce(mp_int *x, const mp_int *n, mp_digit rho)
+{
+ return s_mp_montgomery_reduce_fast(x, n, rho);
+}
+#endif
+#ifdef BN_FAST_S_MP_MUL_DIGS_C
+mp_err fast_s_mp_mul_digs(const mp_int *a, const mp_int *b, mp_int *c, int digs)
+{
+ return s_mp_mul_digs_fast(a, b, c, digs);
+}
+#endif
+#ifdef BN_FAST_S_MP_MUL_HIGH_DIGS_C
+mp_err fast_s_mp_mul_high_digs(const mp_int *a, const mp_int *b, mp_int *c, int digs)
+{
+ return s_mp_mul_high_digs_fast(a, b, c, digs);
+}
+#endif
+#ifdef BN_FAST_S_MP_SQR_C
+mp_err fast_s_mp_sqr(const mp_int *a, mp_int *b)
+{
+ return s_mp_sqr_fast(a, b);
+}
+#endif
+#ifdef BN_MP_BALANCE_MUL_C
+mp_err mp_balance_mul(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return s_mp_balance_mul(a, b, c);
+}
+#endif
+#ifdef BN_MP_EXPTMOD_FAST_C
+mp_err mp_exptmod_fast(const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y, int redmode)
+{
+ return s_mp_exptmod_fast(G, X, P, Y, redmode);
+}
+#endif
+#ifdef BN_MP_INVMOD_SLOW_C
+mp_err mp_invmod_slow(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return s_mp_invmod_slow(a, b, c);
+}
+#endif
+#ifdef BN_MP_KARATSUBA_MUL_C
+mp_err mp_karatsuba_mul(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return s_mp_karatsuba_mul(a, b, c);
+}
+#endif
+#ifdef BN_MP_KARATSUBA_SQR_C
+mp_err mp_karatsuba_sqr(const mp_int *a, mp_int *b)
+{
+ return s_mp_karatsuba_sqr(a, b);
+}
+#endif
+#ifdef BN_MP_TOOM_MUL_C
+mp_err mp_toom_mul(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return s_mp_toom_mul(a, b, c);
+}
+#endif
+#ifdef BN_MP_TOOM_SQR_C
+mp_err mp_toom_sqr(const mp_int *a, mp_int *b)
+{
+ return s_mp_toom_sqr(a, b);
+}
+#endif
+#ifdef S_MP_REVERSE_C
+void bn_reverse(unsigned char *s, int len)
+{
+ if (len > 0) {
+ s_mp_reverse(s, (size_t)len);
+ }
+}
+#endif
+#ifdef BN_MP_TC_AND_C
+mp_err mp_tc_and(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return mp_and(a, b, c);
+}
+#endif
+#ifdef BN_MP_TC_OR_C
+mp_err mp_tc_or(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return mp_or(a, b, c);
+}
+#endif
+#ifdef BN_MP_TC_XOR_C
+mp_err mp_tc_xor(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return mp_xor(a, b, c);
+}
+#endif
+#ifdef BN_MP_TC_DIV_2D_C
+mp_err mp_tc_div_2d(const mp_int *a, int b, mp_int *c)
+{
+ return mp_signed_rsh(a, b, c);
+}
+#endif
+#ifdef BN_MP_INIT_SET_INT_C
+mp_err mp_init_set_int(mp_int *a, unsigned long b)
+{
+ return mp_init_u32(a, (uint32_t)b);
+}
+#endif
+#ifdef BN_MP_SET_INT_C
+mp_err mp_set_int(mp_int *a, unsigned long b)
+{
+ mp_set_u32(a, (uint32_t)b);
+ return MP_OKAY;
+}
+#endif
+#ifdef BN_MP_SET_LONG_C
+mp_err mp_set_long(mp_int *a, unsigned long b)
+{
+ mp_set_u64(a, b);
+ return MP_OKAY;
+}
+#endif
+#ifdef BN_MP_SET_LONG_LONG_C
+mp_err mp_set_long_long(mp_int *a, unsigned long long b)
+{
+ mp_set_u64(a, b);
+ return MP_OKAY;
+}
+#endif
+#ifdef BN_MP_GET_INT_C
+unsigned long mp_get_int(const mp_int *a)
+{
+ return (unsigned long)mp_get_mag_u32(a);
+}
+#endif
+#ifdef BN_MP_GET_LONG_C
+unsigned long mp_get_long(const mp_int *a)
+{
+ return (unsigned long)mp_get_mag_ul(a);
+}
+#endif
+#ifdef BN_MP_GET_LONG_LONG_C
+unsigned long long mp_get_long_long(const mp_int *a)
+{
+ return mp_get_mag_ull(a);
+}
+#endif
+#ifdef BN_MP_PRIME_IS_DIVISIBLE_C
+mp_err mp_prime_is_divisible(const mp_int *a, mp_bool *result)
+{
+ return s_mp_prime_is_divisible(a, result);
+}
+#endif
+#ifdef BN_MP_EXPT_D_EX_C
+mp_err mp_expt_d_ex(const mp_int *a, mp_digit b, mp_int *c, int fast)
+{
+ (void)fast;
+ if (b > MP_MIN(MP_DIGIT_MAX, UINT32_MAX)) {
+ return MP_VAL;
+ }
+ return mp_expt_u32(a, (uint32_t)b, c);
+}
+#endif
+#ifdef BN_MP_EXPT_D_C
+mp_err mp_expt_d(const mp_int *a, mp_digit b, mp_int *c)
+{
+ if (b > MP_MIN(MP_DIGIT_MAX, UINT32_MAX)) {
+ return MP_VAL;
+ }
+ return mp_expt_u32(a, (uint32_t)b, c);
+}
+#endif
+#ifdef BN_MP_N_ROOT_EX_C
+mp_err mp_n_root_ex(const mp_int *a, mp_digit b, mp_int *c, int fast)
+{
+ (void)fast;
+ if (b > MP_MIN(MP_DIGIT_MAX, UINT32_MAX)) {
+ return MP_VAL;
+ }
+ return mp_root_u32(a, (uint32_t)b, c);
+}
+#endif
+#ifdef BN_MP_N_ROOT_C
+mp_err mp_n_root(const mp_int *a, mp_digit b, mp_int *c)
+{
+ if (b > MP_MIN(MP_DIGIT_MAX, UINT32_MAX)) {
+ return MP_VAL;
+ }
+ return mp_root_u32(a, (uint32_t)b, c);
+}
+#endif
+#ifdef BN_MP_UNSIGNED_BIN_SIZE_C
+int mp_unsigned_bin_size(const mp_int *a)
+{
+ return (int)mp_ubin_size(a);
+}
+#endif
+#ifdef BN_MP_READ_UNSIGNED_BIN_C
+mp_err mp_read_unsigned_bin(mp_int *a, const unsigned char *b, int c)
+{
+ return mp_from_ubin(a, b, (size_t) c);
+}
+#endif
+#ifdef BN_MP_TO_UNSIGNED_BIN_C
+mp_err mp_to_unsigned_bin(const mp_int *a, unsigned char *b)
+{
+ return mp_to_ubin(a, b, SIZE_MAX, NULL);
+}
+#endif
+#ifdef BN_MP_TO_UNSIGNED_BIN_N_C
+mp_err mp_to_unsigned_bin_n(const mp_int *a, unsigned char *b, unsigned long *outlen)
+{
+ size_t n = mp_ubin_size(a);
+ if (*outlen < (unsigned long)n) {
+ return MP_VAL;
+ }
+ *outlen = (unsigned long)n;
+ return mp_to_ubin(a, b, n, NULL);
+}
+#endif
+#ifdef BN_MP_SIGNED_BIN_SIZE_C
+int mp_signed_bin_size(const mp_int *a)
+{
+ return (int)mp_sbin_size(a);
+}
+#endif
+#ifdef BN_MP_READ_SIGNED_BIN_C
+mp_err mp_read_signed_bin(mp_int *a, const unsigned char *b, int c)
+{
+ return mp_from_sbin(a, b, (size_t) c);
+}
+#endif
+#ifdef BN_MP_TO_SIGNED_BIN_C
+mp_err mp_to_signed_bin(const mp_int *a, unsigned char *b)
+{
+ return mp_to_sbin(a, b, SIZE_MAX, NULL);
+}
+#endif
+#ifdef BN_MP_TO_SIGNED_BIN_N_C
+mp_err mp_to_signed_bin_n(const mp_int *a, unsigned char *b, unsigned long *outlen)
+{
+ size_t n = mp_sbin_size(a);
+ if (*outlen < (unsigned long)n) {
+ return MP_VAL;
+ }
+ *outlen = (unsigned long)n;
+ return mp_to_sbin(a, b, n, NULL);
+}
+#endif
+#ifdef BN_MP_TORADIX_N_C
+mp_err mp_toradix_n(const mp_int *a, char *str, int radix, int maxlen)
+{
+ if (maxlen < 0) {
+ return MP_VAL;
+ }
+ return mp_to_radix(a, str, (size_t)maxlen, NULL, radix);
+}
+#endif
+#ifdef BN_MP_TORADIX_C
+mp_err mp_toradix(const mp_int *a, char *str, int radix)
+{
+ return mp_to_radix(a, str, SIZE_MAX, NULL, radix);
+}
+#endif
+#ifdef BN_MP_IMPORT_C
+mp_err mp_import(mp_int *rop, size_t count, int order, size_t size, int endian, size_t nails,
+ const void *op)
+{
+ return mp_unpack(rop, count, order, size, endian, nails, op);
+}
+#endif
+#ifdef BN_MP_EXPORT_C
+mp_err mp_export(void *rop, size_t *countp, int order, size_t size,
+ int endian, size_t nails, const mp_int *op)
+{
+ return mp_pack(rop, SIZE_MAX, countp, order, size, endian, nails, op);
+}
+#endif
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_2expt.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_2expt.c
new file mode 100644
index 0000000..0ae3df1
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_2expt.c
@@ -0,0 +1,31 @@
+#include "tommath_private.h"
+#ifdef BN_MP_2EXPT_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* computes a = 2**b
+ *
+ * Simple algorithm which zeroes the int, grows it then just sets one bit
+ * as required.
+ */
+mp_err mp_2expt(mp_int *a, int b)
+{
+ mp_err err;
+
+ /* zero a as per default */
+ mp_zero(a);
+
+ /* grow a to accomodate the single bit */
+ if ((err = mp_grow(a, (b / MP_DIGIT_BIT) + 1)) != MP_OKAY) {
+ return err;
+ }
+
+ /* set the used count of where the bit will go */
+ a->used = (b / MP_DIGIT_BIT) + 1;
+
+ /* put the single bit in its place */
+ a->dp[b / MP_DIGIT_BIT] = (mp_digit)1 << (mp_digit)(b % MP_DIGIT_BIT);
+
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_abs.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_abs.c
new file mode 100644
index 0000000..00900bb
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_abs.c
@@ -0,0 +1,26 @@
+#include "tommath_private.h"
+#ifdef BN_MP_ABS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* b = |a|
+ *
+ * Simple function copies the input and fixes the sign to positive
+ */
+mp_err mp_abs(const mp_int *a, mp_int *b)
+{
+ mp_err err;
+
+ /* copy a to b */
+ if (a != b) {
+ if ((err = mp_copy(a, b)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* force the sign of b to positive */
+ b->sign = MP_ZPOS;
+
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_add.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_add.c
new file mode 100644
index 0000000..dfa78de
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_add.c
@@ -0,0 +1,38 @@
+#include "tommath_private.h"
+#ifdef BN_MP_ADD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* high level addition (handles signs) */
+mp_err mp_add(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_sign sa, sb;
+ mp_err err;
+
+ /* get sign of both inputs */
+ sa = a->sign;
+ sb = b->sign;
+
+ /* handle two cases, not four */
+ if (sa == sb) {
+ /* both positive or both negative */
+ /* add their magnitudes, copy the sign */
+ c->sign = sa;
+ err = s_mp_add(a, b, c);
+ } else {
+ /* one positive, the other negative */
+ /* subtract the one with the greater magnitude from */
+ /* the one of the lesser magnitude. The result gets */
+ /* the sign of the one with the greater magnitude. */
+ if (mp_cmp_mag(a, b) == MP_LT) {
+ c->sign = sb;
+ err = s_mp_sub(b, a, c);
+ } else {
+ c->sign = sa;
+ err = s_mp_sub(a, b, c);
+ }
+ }
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_add_d.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_add_d.c
new file mode 100644
index 0000000..f301575
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_add_d.c
@@ -0,0 +1,89 @@
+#include "tommath_private.h"
+#ifdef BN_MP_ADD_D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* single digit addition */
+mp_err mp_add_d(const mp_int *a, mp_digit b, mp_int *c)
+{
+ mp_err err;
+ int ix, oldused;
+ mp_digit *tmpa, *tmpc;
+
+ /* grow c as required */
+ if (c->alloc < (a->used + 1)) {
+ if ((err = mp_grow(c, a->used + 1)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* if a is negative and |a| >= b, call c = |a| - b */
+ if ((a->sign == MP_NEG) && ((a->used > 1) || (a->dp[0] >= b))) {
+ mp_int a_ = *a;
+ /* temporarily fix sign of a */
+ a_.sign = MP_ZPOS;
+
+ /* c = |a| - b */
+ err = mp_sub_d(&a_, b, c);
+
+ /* fix sign */
+ c->sign = MP_NEG;
+
+ /* clamp */
+ mp_clamp(c);
+
+ return err;
+ }
+
+ /* old number of used digits in c */
+ oldused = c->used;
+
+ /* source alias */
+ tmpa = a->dp;
+
+ /* destination alias */
+ tmpc = c->dp;
+
+ /* if a is positive */
+ if (a->sign == MP_ZPOS) {
+ /* add digits, mu is carry */
+ mp_digit mu = b;
+ for (ix = 0; ix < a->used; ix++) {
+ *tmpc = *tmpa++ + mu;
+ mu = *tmpc >> MP_DIGIT_BIT;
+ *tmpc++ &= MP_MASK;
+ }
+ /* set final carry */
+ ix++;
+ *tmpc++ = mu;
+
+ /* setup size */
+ c->used = a->used + 1;
+ } else {
+ /* a was negative and |a| < b */
+ c->used = 1;
+
+ /* the result is a single digit */
+ if (a->used == 1) {
+ *tmpc++ = b - a->dp[0];
+ } else {
+ *tmpc++ = b;
+ }
+
+ /* setup count so the clearing of oldused
+ * can fall through correctly
+ */
+ ix = 1;
+ }
+
+ /* sign always positive */
+ c->sign = MP_ZPOS;
+
+ /* now zero to oldused */
+ MP_ZERO_DIGITS(tmpc, oldused - ix);
+ mp_clamp(c);
+
+ return MP_OKAY;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_addmod.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_addmod.c
new file mode 100644
index 0000000..1dcfb67
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_addmod.c
@@ -0,0 +1,25 @@
+#include "tommath_private.h"
+#ifdef BN_MP_ADDMOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* d = a + b (mod c) */
+mp_err mp_addmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d)
+{
+ mp_err err;
+ mp_int t;
+
+ if ((err = mp_init(&t)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_add(a, b, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ err = mp_mod(&t, c, d);
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_and.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_and.c
new file mode 100644
index 0000000..c259f8d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_and.c
@@ -0,0 +1,56 @@
+#include "tommath_private.h"
+#ifdef BN_MP_AND_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* two complement and */
+mp_err mp_and(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ int used = MP_MAX(a->used, b->used) + 1, i;
+ mp_err err;
+ mp_digit ac = 1, bc = 1, cc = 1;
+ mp_sign csign = ((a->sign == MP_NEG) && (b->sign == MP_NEG)) ? MP_NEG : MP_ZPOS;
+
+ if (c->alloc < used) {
+ if ((err = mp_grow(c, used)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ for (i = 0; i < used; i++) {
+ mp_digit x, y;
+
+ /* convert to two complement if negative */
+ if (a->sign == MP_NEG) {
+ ac += (i >= a->used) ? MP_MASK : (~a->dp[i] & MP_MASK);
+ x = ac & MP_MASK;
+ ac >>= MP_DIGIT_BIT;
+ } else {
+ x = (i >= a->used) ? 0uL : a->dp[i];
+ }
+
+ /* convert to two complement if negative */
+ if (b->sign == MP_NEG) {
+ bc += (i >= b->used) ? MP_MASK : (~b->dp[i] & MP_MASK);
+ y = bc & MP_MASK;
+ bc >>= MP_DIGIT_BIT;
+ } else {
+ y = (i >= b->used) ? 0uL : b->dp[i];
+ }
+
+ c->dp[i] = x & y;
+
+ /* convert to to sign-magnitude if negative */
+ if (csign == MP_NEG) {
+ cc += ~c->dp[i] & MP_MASK;
+ c->dp[i] = cc & MP_MASK;
+ cc >>= MP_DIGIT_BIT;
+ }
+ }
+
+ c->used = used;
+ c->sign = csign;
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_clamp.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_clamp.c
new file mode 100644
index 0000000..ac23bfd
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_clamp.c
@@ -0,0 +1,27 @@
+#include "tommath_private.h"
+#ifdef BN_MP_CLAMP_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* trim unused digits
+ *
+ * This is used to ensure that leading zero digits are
+ * trimed and the leading "used" digit will be non-zero
+ * Typically very fast. Also fixes the sign if there
+ * are no more leading digits
+ */
+void mp_clamp(mp_int *a)
+{
+ /* decrease used while the most significant digit is
+ * zero.
+ */
+ while ((a->used > 0) && (a->dp[a->used - 1] == 0u)) {
+ --(a->used);
+ }
+
+ /* reset the sign flag if used == 0 */
+ if (a->used == 0) {
+ a->sign = MP_ZPOS;
+ }
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_clear.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_clear.c
new file mode 100644
index 0000000..ff78324
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_clear.c
@@ -0,0 +1,20 @@
+#include "tommath_private.h"
+#ifdef BN_MP_CLEAR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* clear one (frees) */
+void mp_clear(mp_int *a)
+{
+ /* only do anything if a hasn't been freed previously */
+ if (a->dp != NULL) {
+ /* free ram */
+ MP_FREE_DIGITS(a->dp, a->alloc);
+
+ /* reset members to make debugging easier */
+ a->dp = NULL;
+ a->alloc = a->used = 0;
+ a->sign = MP_ZPOS;
+ }
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_clear_multi.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_clear_multi.c
new file mode 100644
index 0000000..794e45f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_clear_multi.c
@@ -0,0 +1,19 @@
+#include "tommath_private.h"
+#ifdef BN_MP_CLEAR_MULTI_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#include <stdarg.h>
+
+void mp_clear_multi(mp_int *mp, ...)
+{
+ mp_int *next_mp = mp;
+ va_list args;
+ va_start(args, mp);
+ while (next_mp != NULL) {
+ mp_clear(next_mp);
+ next_mp = va_arg(args, mp_int *);
+ }
+ va_end(args);
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cmp.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cmp.c
new file mode 100644
index 0000000..ced4840
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cmp.c
@@ -0,0 +1,26 @@
+#include "tommath_private.h"
+#ifdef BN_MP_CMP_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* compare two ints (signed)*/
+mp_ord mp_cmp(const mp_int *a, const mp_int *b)
+{
+ /* compare based on sign */
+ if (a->sign != b->sign) {
+ if (a->sign == MP_NEG) {
+ return MP_LT;
+ } else {
+ return MP_GT;
+ }
+ }
+
+ /* compare digits */
+ if (a->sign == MP_NEG) {
+ /* if negative compare opposite direction */
+ return mp_cmp_mag(b, a);
+ } else {
+ return mp_cmp_mag(a, b);
+ }
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cmp_d.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cmp_d.c
new file mode 100644
index 0000000..5a8337b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cmp_d.c
@@ -0,0 +1,28 @@
+#include "tommath_private.h"
+#ifdef BN_MP_CMP_D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* compare a digit */
+mp_ord mp_cmp_d(const mp_int *a, mp_digit b)
+{
+ /* compare based on sign */
+ if (a->sign == MP_NEG) {
+ return MP_LT;
+ }
+
+ /* compare based on magnitude */
+ if (a->used > 1) {
+ return MP_GT;
+ }
+
+ /* compare the only digit of a to b */
+ if (a->dp[0] > b) {
+ return MP_GT;
+ } else if (a->dp[0] < b) {
+ return MP_LT;
+ } else {
+ return MP_EQ;
+ }
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cmp_mag.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cmp_mag.c
new file mode 100644
index 0000000..f144ea9
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cmp_mag.c
@@ -0,0 +1,39 @@
+#include "tommath_private.h"
+#ifdef BN_MP_CMP_MAG_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* compare maginitude of two ints (unsigned) */
+mp_ord mp_cmp_mag(const mp_int *a, const mp_int *b)
+{
+ int n;
+ const mp_digit *tmpa, *tmpb;
+
+ /* compare based on # of non-zero digits */
+ if (a->used > b->used) {
+ return MP_GT;
+ }
+
+ if (a->used < b->used) {
+ return MP_LT;
+ }
+
+ /* alias for a */
+ tmpa = a->dp + (a->used - 1);
+
+ /* alias for b */
+ tmpb = b->dp + (a->used - 1);
+
+ /* compare based on digits */
+ for (n = 0; n < a->used; ++n, --tmpa, --tmpb) {
+ if (*tmpa > *tmpb) {
+ return MP_GT;
+ }
+
+ if (*tmpa < *tmpb) {
+ return MP_LT;
+ }
+ }
+ return MP_EQ;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cnt_lsb.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cnt_lsb.c
new file mode 100644
index 0000000..4b2d206
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_cnt_lsb.c
@@ -0,0 +1,37 @@
+#include "tommath_private.h"
+#ifdef BN_MP_CNT_LSB_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+static const int lnz[16] = {
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0
+};
+
+/* Counts the number of lsbs which are zero before the first zero bit */
+int mp_cnt_lsb(const mp_int *a)
+{
+ int x;
+ mp_digit q, qq;
+
+ /* easy out */
+ if (MP_IS_ZERO(a)) {
+ return 0;
+ }
+
+ /* scan lower digits until non-zero */
+ for (x = 0; (x < a->used) && (a->dp[x] == 0u); x++) {}
+ q = a->dp[x];
+ x *= MP_DIGIT_BIT;
+
+ /* now scan this digit until a 1 is found */
+ if ((q & 1u) == 0u) {
+ do {
+ qq = q & 15u;
+ x += lnz[qq];
+ q >>= 4;
+ } while (qq == 0u);
+ }
+ return x;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_complement.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_complement.c
new file mode 100644
index 0000000..fef1423
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_complement.c
@@ -0,0 +1,12 @@
+#include "tommath_private.h"
+#ifdef BN_MP_COMPLEMENT_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* b = ~a */
+mp_err mp_complement(const mp_int *a, mp_int *b)
+{
+ mp_err err = mp_neg(a, b);
+ return (err == MP_OKAY) ? mp_sub_d(b, 1uL, b) : err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_copy.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_copy.c
new file mode 100644
index 0000000..e72fcf6
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_copy.c
@@ -0,0 +1,47 @@
+#include "tommath_private.h"
+#ifdef BN_MP_COPY_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* copy, b = a */
+mp_err mp_copy(const mp_int *a, mp_int *b)
+{
+ int n;
+ mp_digit *tmpa, *tmpb;
+ mp_err err;
+
+ /* if dst == src do nothing */
+ if (a == b) {
+ return MP_OKAY;
+ }
+
+ /* grow dest */
+ if (b->alloc < a->used) {
+ if ((err = mp_grow(b, a->used)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* zero b and copy the parameters over */
+ /* pointer aliases */
+
+ /* source */
+ tmpa = a->dp;
+
+ /* destination */
+ tmpb = b->dp;
+
+ /* copy all the digits */
+ for (n = 0; n < a->used; n++) {
+ *tmpb++ = *tmpa++;
+ }
+
+ /* clear high digits */
+ MP_ZERO_DIGITS(tmpb, b->used - n);
+
+ /* copy used count and sign */
+ b->used = a->used;
+ b->sign = a->sign;
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_count_bits.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_count_bits.c
new file mode 100644
index 0000000..b7c2cad
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_count_bits.c
@@ -0,0 +1,28 @@
+#include "tommath_private.h"
+#ifdef BN_MP_COUNT_BITS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* returns the number of bits in an int */
+int mp_count_bits(const mp_int *a)
+{
+ int r;
+ mp_digit q;
+
+ /* shortcut */
+ if (MP_IS_ZERO(a)) {
+ return 0;
+ }
+
+ /* get number of digits and add that */
+ r = (a->used - 1) * MP_DIGIT_BIT;
+
+ /* take the last digit and count the bits in it */
+ q = a->dp[a->used - 1];
+ while (q > 0u) {
+ ++r;
+ q >>= 1u;
+ }
+ return r;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_decr.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_decr.c
new file mode 100644
index 0000000..c6a1572
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_decr.c
@@ -0,0 +1,34 @@
+#include "tommath_private.h"
+#ifdef BN_MP_DECR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Decrement "a" by one like "a--". Changes input! */
+mp_err mp_decr(mp_int *a)
+{
+ if (MP_IS_ZERO(a)) {
+ mp_set(a,1uL);
+ a->sign = MP_NEG;
+ return MP_OKAY;
+ } else if (a->sign == MP_NEG) {
+ mp_err err;
+ a->sign = MP_ZPOS;
+ if ((err = mp_incr(a)) != MP_OKAY) {
+ return err;
+ }
+ /* There is no -0 in LTM */
+ if (!MP_IS_ZERO(a)) {
+ a->sign = MP_NEG;
+ }
+ return MP_OKAY;
+ } else if (a->dp[0] > 1uL) {
+ a->dp[0]--;
+ if (a->dp[0] == 0u) {
+ mp_zero(a);
+ }
+ return MP_OKAY;
+ } else {
+ return mp_sub_d(a, 1uL,a);
+ }
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div.c
new file mode 100644
index 0000000..71de55b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div.c
@@ -0,0 +1,250 @@
+#include "tommath_private.h"
+#ifdef BN_MP_DIV_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#ifdef BN_MP_DIV_SMALL
+
+/* slower bit-bang division... also smaller */
+mp_err mp_div(const mp_int *a, const mp_int *b, mp_int *c, mp_int *d)
+{
+ mp_int ta, tb, tq, q;
+ int n, n2;
+ mp_err err;
+
+ /* is divisor zero ? */
+ if (MP_IS_ZERO(b)) {
+ return MP_VAL;
+ }
+
+ /* if a < b then q=0, r = a */
+ if (mp_cmp_mag(a, b) == MP_LT) {
+ if (d != NULL) {
+ err = mp_copy(a, d);
+ } else {
+ err = MP_OKAY;
+ }
+ if (c != NULL) {
+ mp_zero(c);
+ }
+ return err;
+ }
+
+ /* init our temps */
+ if ((err = mp_init_multi(&ta, &tb, &tq, &q, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+
+ mp_set(&tq, 1uL);
+ n = mp_count_bits(a) - mp_count_bits(b);
+ if ((err = mp_abs(a, &ta)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_abs(b, &tb)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_mul_2d(&tb, n, &tb)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_mul_2d(&tq, n, &tq)) != MP_OKAY) goto LBL_ERR;
+
+ while (n-- >= 0) {
+ if (mp_cmp(&tb, &ta) != MP_GT) {
+ if ((err = mp_sub(&ta, &tb, &ta)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(&q, &tq, &q)) != MP_OKAY) goto LBL_ERR;
+ }
+ if ((err = mp_div_2d(&tb, 1, &tb, NULL)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_div_2d(&tq, 1, &tq, NULL)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* now q == quotient and ta == remainder */
+ n = a->sign;
+ n2 = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
+ if (c != NULL) {
+ mp_exch(c, &q);
+ c->sign = MP_IS_ZERO(c) ? MP_ZPOS : n2;
+ }
+ if (d != NULL) {
+ mp_exch(d, &ta);
+ d->sign = MP_IS_ZERO(d) ? MP_ZPOS : n;
+ }
+LBL_ERR:
+ mp_clear_multi(&ta, &tb, &tq, &q, NULL);
+ return err;
+}
+
+#else
+
+/* integer signed division.
+ * c*b + d == a [e.g. a/b, c=quotient, d=remainder]
+ * HAC pp.598 Algorithm 14.20
+ *
+ * Note that the description in HAC is horribly
+ * incomplete. For example, it doesn't consider
+ * the case where digits are removed from 'x' in
+ * the inner loop. It also doesn't consider the
+ * case that y has fewer than three digits, etc..
+ *
+ * The overall algorithm is as described as
+ * 14.20 from HAC but fixed to treat these cases.
+*/
+mp_err mp_div(const mp_int *a, const mp_int *b, mp_int *c, mp_int *d)
+{
+ mp_int q, x, y, t1, t2;
+ int n, t, i, norm;
+ mp_sign neg;
+ mp_err err;
+
+ /* is divisor zero ? */
+ if (MP_IS_ZERO(b)) {
+ return MP_VAL;
+ }
+
+ /* if a < b then q=0, r = a */
+ if (mp_cmp_mag(a, b) == MP_LT) {
+ if (d != NULL) {
+ err = mp_copy(a, d);
+ } else {
+ err = MP_OKAY;
+ }
+ if (c != NULL) {
+ mp_zero(c);
+ }
+ return err;
+ }
+
+ if ((err = mp_init_size(&q, a->used + 2)) != MP_OKAY) {
+ return err;
+ }
+ q.used = a->used + 2;
+
+ if ((err = mp_init(&t1)) != MP_OKAY) goto LBL_Q;
+
+ if ((err = mp_init(&t2)) != MP_OKAY) goto LBL_T1;
+
+ if ((err = mp_init_copy(&x, a)) != MP_OKAY) goto LBL_T2;
+
+ if ((err = mp_init_copy(&y, b)) != MP_OKAY) goto LBL_X;
+
+ /* fix the sign */
+ neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
+ x.sign = y.sign = MP_ZPOS;
+
+ /* normalize both x and y, ensure that y >= b/2, [b == 2**MP_DIGIT_BIT] */
+ norm = mp_count_bits(&y) % MP_DIGIT_BIT;
+ if (norm < (MP_DIGIT_BIT - 1)) {
+ norm = (MP_DIGIT_BIT - 1) - norm;
+ if ((err = mp_mul_2d(&x, norm, &x)) != MP_OKAY) goto LBL_Y;
+ if ((err = mp_mul_2d(&y, norm, &y)) != MP_OKAY) goto LBL_Y;
+ } else {
+ norm = 0;
+ }
+
+ /* note hac does 0 based, so if used==5 then its 0,1,2,3,4, e.g. use 4 */
+ n = x.used - 1;
+ t = y.used - 1;
+
+ /* while (x >= y*b**n-t) do { q[n-t] += 1; x -= y*b**{n-t} } */
+ /* y = y*b**{n-t} */
+ if ((err = mp_lshd(&y, n - t)) != MP_OKAY) goto LBL_Y;
+
+ while (mp_cmp(&x, &y) != MP_LT) {
+ ++(q.dp[n - t]);
+ if ((err = mp_sub(&x, &y, &x)) != MP_OKAY) goto LBL_Y;
+ }
+
+ /* reset y by shifting it back down */
+ mp_rshd(&y, n - t);
+
+ /* step 3. for i from n down to (t + 1) */
+ for (i = n; i >= (t + 1); i--) {
+ if (i > x.used) {
+ continue;
+ }
+
+ /* step 3.1 if xi == yt then set q{i-t-1} to b-1,
+ * otherwise set q{i-t-1} to (xi*b + x{i-1})/yt */
+ if (x.dp[i] == y.dp[t]) {
+ q.dp[(i - t) - 1] = ((mp_digit)1 << (mp_digit)MP_DIGIT_BIT) - (mp_digit)1;
+ } else {
+ mp_word tmp;
+ tmp = (mp_word)x.dp[i] << (mp_word)MP_DIGIT_BIT;
+ tmp |= (mp_word)x.dp[i - 1];
+ tmp /= (mp_word)y.dp[t];
+ if (tmp > (mp_word)MP_MASK) {
+ tmp = MP_MASK;
+ }
+ q.dp[(i - t) - 1] = (mp_digit)(tmp & (mp_word)MP_MASK);
+ }
+
+ /* while (q{i-t-1} * (yt * b + y{t-1})) >
+ xi * b**2 + xi-1 * b + xi-2
+
+ do q{i-t-1} -= 1;
+ */
+ q.dp[(i - t) - 1] = (q.dp[(i - t) - 1] + 1uL) & (mp_digit)MP_MASK;
+ do {
+ q.dp[(i - t) - 1] = (q.dp[(i - t) - 1] - 1uL) & (mp_digit)MP_MASK;
+
+ /* find left hand */
+ mp_zero(&t1);
+ t1.dp[0] = ((t - 1) < 0) ? 0u : y.dp[t - 1];
+ t1.dp[1] = y.dp[t];
+ t1.used = 2;
+ if ((err = mp_mul_d(&t1, q.dp[(i - t) - 1], &t1)) != MP_OKAY) goto LBL_Y;
+
+ /* find right hand */
+ t2.dp[0] = ((i - 2) < 0) ? 0u : x.dp[i - 2];
+ t2.dp[1] = x.dp[i - 1]; /* i >= 1 always holds */
+ t2.dp[2] = x.dp[i];
+ t2.used = 3;
+ } while (mp_cmp_mag(&t1, &t2) == MP_GT);
+
+ /* step 3.3 x = x - q{i-t-1} * y * b**{i-t-1} */
+ if ((err = mp_mul_d(&y, q.dp[(i - t) - 1], &t1)) != MP_OKAY) goto LBL_Y;
+
+ if ((err = mp_lshd(&t1, (i - t) - 1)) != MP_OKAY) goto LBL_Y;
+
+ if ((err = mp_sub(&x, &t1, &x)) != MP_OKAY) goto LBL_Y;
+
+ /* if x < 0 then { x = x + y*b**{i-t-1}; q{i-t-1} -= 1; } */
+ if (x.sign == MP_NEG) {
+ if ((err = mp_copy(&y, &t1)) != MP_OKAY) goto LBL_Y;
+ if ((err = mp_lshd(&t1, (i - t) - 1)) != MP_OKAY) goto LBL_Y;
+ if ((err = mp_add(&x, &t1, &x)) != MP_OKAY) goto LBL_Y;
+
+ q.dp[(i - t) - 1] = (q.dp[(i - t) - 1] - 1uL) & MP_MASK;
+ }
+ }
+
+ /* now q is the quotient and x is the remainder
+ * [which we have to normalize]
+ */
+
+ /* get sign before writing to c */
+ x.sign = (x.used == 0) ? MP_ZPOS : a->sign;
+
+ if (c != NULL) {
+ mp_clamp(&q);
+ mp_exch(&q, c);
+ c->sign = neg;
+ }
+
+ if (d != NULL) {
+ if ((err = mp_div_2d(&x, norm, &x, NULL)) != MP_OKAY) goto LBL_Y;
+ mp_exch(&x, d);
+ }
+
+ err = MP_OKAY;
+
+LBL_Y:
+ mp_clear(&y);
+LBL_X:
+ mp_clear(&x);
+LBL_T2:
+ mp_clear(&t2);
+LBL_T1:
+ mp_clear(&t1);
+LBL_Q:
+ mp_clear(&q);
+ return err;
+}
+
+#endif
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_2.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_2.c
new file mode 100644
index 0000000..f56ea81
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_2.c
@@ -0,0 +1,49 @@
+#include "tommath_private.h"
+#ifdef BN_MP_DIV_2_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* b = a/2 */
+mp_err mp_div_2(const mp_int *a, mp_int *b)
+{
+ int x, oldused;
+ mp_digit r, rr, *tmpa, *tmpb;
+ mp_err err;
+
+ /* copy */
+ if (b->alloc < a->used) {
+ if ((err = mp_grow(b, a->used)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ oldused = b->used;
+ b->used = a->used;
+
+ /* source alias */
+ tmpa = a->dp + b->used - 1;
+
+ /* dest alias */
+ tmpb = b->dp + b->used - 1;
+
+ /* carry */
+ r = 0;
+ for (x = b->used - 1; x >= 0; x--) {
+ /* get the carry for the next iteration */
+ rr = *tmpa & 1u;
+
+ /* shift the current digit, add in carry and store */
+ *tmpb-- = (*tmpa-- >> 1) | (r << (MP_DIGIT_BIT - 1));
+
+ /* forward carry to next iteration */
+ r = rr;
+ }
+
+ /* zero excess digits */
+ MP_ZERO_DIGITS(b->dp + b->used, oldused - b->used);
+
+ b->sign = a->sign;
+ mp_clamp(b);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_2d.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_2d.c
new file mode 100644
index 0000000..c47d5ce
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_2d.c
@@ -0,0 +1,71 @@
+#include "tommath_private.h"
+#ifdef BN_MP_DIV_2D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* shift right by a certain bit count (store quotient in c, optional remainder in d) */
+mp_err mp_div_2d(const mp_int *a, int b, mp_int *c, mp_int *d)
+{
+ mp_digit D, r, rr;
+ int x;
+ mp_err err;
+
+ /* if the shift count is <= 0 then we do no work */
+ if (b <= 0) {
+ err = mp_copy(a, c);
+ if (d != NULL) {
+ mp_zero(d);
+ }
+ return err;
+ }
+
+ /* copy */
+ if ((err = mp_copy(a, c)) != MP_OKAY) {
+ return err;
+ }
+ /* 'a' should not be used after here - it might be the same as d */
+
+ /* get the remainder */
+ if (d != NULL) {
+ if ((err = mp_mod_2d(a, b, d)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* shift by as many digits in the bit count */
+ if (b >= MP_DIGIT_BIT) {
+ mp_rshd(c, b / MP_DIGIT_BIT);
+ }
+
+ /* shift any bit count < MP_DIGIT_BIT */
+ D = (mp_digit)(b % MP_DIGIT_BIT);
+ if (D != 0u) {
+ mp_digit *tmpc, mask, shift;
+
+ /* mask */
+ mask = ((mp_digit)1 << D) - 1uL;
+
+ /* shift for lsb */
+ shift = (mp_digit)MP_DIGIT_BIT - D;
+
+ /* alias */
+ tmpc = c->dp + (c->used - 1);
+
+ /* carry */
+ r = 0;
+ for (x = c->used - 1; x >= 0; x--) {
+ /* get the lower bits of this word in a temp */
+ rr = *tmpc & mask;
+
+ /* shift the current word and mix in the carry bits from the previous word */
+ *tmpc = (*tmpc >> D) | (r << shift);
+ --tmpc;
+
+ /* set the carry to the carry bits of the current word found above */
+ r = rr;
+ }
+ }
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_3.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_3.c
new file mode 100644
index 0000000..3a23fdf
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_3.c
@@ -0,0 +1,63 @@
+#include "tommath_private.h"
+#ifdef BN_MP_DIV_3_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* divide by three (based on routine from MPI and the GMP manual) */
+mp_err mp_div_3(const mp_int *a, mp_int *c, mp_digit *d)
+{
+ mp_int q;
+ mp_word w, t;
+ mp_digit b;
+ mp_err err;
+ int ix;
+
+ /* b = 2**MP_DIGIT_BIT / 3 */
+ b = ((mp_word)1 << (mp_word)MP_DIGIT_BIT) / (mp_word)3;
+
+ if ((err = mp_init_size(&q, a->used)) != MP_OKAY) {
+ return err;
+ }
+
+ q.used = a->used;
+ q.sign = a->sign;
+ w = 0;
+ for (ix = a->used - 1; ix >= 0; ix--) {
+ w = (w << (mp_word)MP_DIGIT_BIT) | (mp_word)a->dp[ix];
+
+ if (w >= 3u) {
+ /* multiply w by [1/3] */
+ t = (w * (mp_word)b) >> (mp_word)MP_DIGIT_BIT;
+
+ /* now subtract 3 * [w/3] from w, to get the remainder */
+ w -= t+t+t;
+
+ /* fixup the remainder as required since
+ * the optimization is not exact.
+ */
+ while (w >= 3u) {
+ t += 1u;
+ w -= 3u;
+ }
+ } else {
+ t = 0;
+ }
+ q.dp[ix] = (mp_digit)t;
+ }
+
+ /* [optional] store the remainder */
+ if (d != NULL) {
+ *d = (mp_digit)w;
+ }
+
+ /* [optional] store the quotient */
+ if (c != NULL) {
+ mp_clamp(&q);
+ mp_exch(&q, c);
+ }
+ mp_clear(&q);
+
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_d.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_d.c
new file mode 100644
index 0000000..b9d718b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_div_d.c
@@ -0,0 +1,84 @@
+#include "tommath_private.h"
+#ifdef BN_MP_DIV_D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* single digit division (based on routine from MPI) */
+mp_err mp_div_d(const mp_int *a, mp_digit b, mp_int *c, mp_digit *d)
+{
+ mp_int q;
+ mp_word w;
+ mp_digit t;
+ mp_err err;
+ int ix;
+
+ /* cannot divide by zero */
+ if (b == 0u) {
+ return MP_VAL;
+ }
+
+ /* quick outs */
+ if ((b == 1u) || MP_IS_ZERO(a)) {
+ if (d != NULL) {
+ *d = 0;
+ }
+ if (c != NULL) {
+ return mp_copy(a, c);
+ }
+ return MP_OKAY;
+ }
+
+ /* power of two ? */
+ if ((b & (b - 1u)) == 0u) {
+ ix = 1;
+ while ((ix < MP_DIGIT_BIT) && (b != (((mp_digit)1)<<ix))) {
+ ix++;
+ }
+ if (d != NULL) {
+ *d = a->dp[0] & (((mp_digit)1<<(mp_digit)ix) - 1uL);
+ }
+ if (c != NULL) {
+ return mp_div_2d(a, ix, c, NULL);
+ }
+ return MP_OKAY;
+ }
+
+ /* three? */
+ if (MP_HAS(MP_DIV_3) && (b == 3u)) {
+ return mp_div_3(a, c, d);
+ }
+
+ /* no easy answer [c'est la vie]. Just division */
+ if ((err = mp_init_size(&q, a->used)) != MP_OKAY) {
+ return err;
+ }
+
+ q.used = a->used;
+ q.sign = a->sign;
+ w = 0;
+ for (ix = a->used - 1; ix >= 0; ix--) {
+ w = (w << (mp_word)MP_DIGIT_BIT) | (mp_word)a->dp[ix];
+
+ if (w >= b) {
+ t = (mp_digit)(w / b);
+ w -= (mp_word)t * (mp_word)b;
+ } else {
+ t = 0;
+ }
+ q.dp[ix] = t;
+ }
+
+ if (d != NULL) {
+ *d = (mp_digit)w;
+ }
+
+ if (c != NULL) {
+ mp_clamp(&q);
+ mp_exch(&q, c);
+ }
+ mp_clear(&q);
+
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_dr_is_modulus.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_dr_is_modulus.c
new file mode 100644
index 0000000..83760ea
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_dr_is_modulus.c
@@ -0,0 +1,27 @@
+#include "tommath_private.h"
+#ifdef BN_MP_DR_IS_MODULUS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* determines if a number is a valid DR modulus */
+mp_bool mp_dr_is_modulus(const mp_int *a)
+{
+ int ix;
+
+ /* must be at least two digits */
+ if (a->used < 2) {
+ return MP_NO;
+ }
+
+ /* must be of the form b**k - a [a <= b] so all
+ * but the first digit must be equal to -1 (mod b).
+ */
+ for (ix = 1; ix < a->used; ix++) {
+ if (a->dp[ix] != MP_MASK) {
+ return MP_NO;
+ }
+ }
+ return MP_YES;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_dr_reduce.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_dr_reduce.c
new file mode 100644
index 0000000..ffc33a6
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_dr_reduce.c
@@ -0,0 +1,78 @@
+#include "tommath_private.h"
+#ifdef BN_MP_DR_REDUCE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* reduce "x" in place modulo "n" using the Diminished Radix algorithm.
+ *
+ * Based on algorithm from the paper
+ *
+ * "Generating Efficient Primes for Discrete Log Cryptosystems"
+ * Chae Hoon Lim, Pil Joong Lee,
+ * POSTECH Information Research Laboratories
+ *
+ * The modulus must be of a special format [see manual]
+ *
+ * Has been modified to use algorithm 7.10 from the LTM book instead
+ *
+ * Input x must be in the range 0 <= x <= (n-1)**2
+ */
+mp_err mp_dr_reduce(mp_int *x, const mp_int *n, mp_digit k)
+{
+ mp_err err;
+ int i, m;
+ mp_word r;
+ mp_digit mu, *tmpx1, *tmpx2;
+
+ /* m = digits in modulus */
+ m = n->used;
+
+ /* ensure that "x" has at least 2m digits */
+ if (x->alloc < (m + m)) {
+ if ((err = mp_grow(x, m + m)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* top of loop, this is where the code resumes if
+ * another reduction pass is required.
+ */
+top:
+ /* aliases for digits */
+ /* alias for lower half of x */
+ tmpx1 = x->dp;
+
+ /* alias for upper half of x, or x/B**m */
+ tmpx2 = x->dp + m;
+
+ /* set carry to zero */
+ mu = 0;
+
+ /* compute (x mod B**m) + k * [x/B**m] inline and inplace */
+ for (i = 0; i < m; i++) {
+ r = ((mp_word)*tmpx2++ * (mp_word)k) + *tmpx1 + mu;
+ *tmpx1++ = (mp_digit)(r & MP_MASK);
+ mu = (mp_digit)(r >> ((mp_word)MP_DIGIT_BIT));
+ }
+
+ /* set final carry */
+ *tmpx1++ = mu;
+
+ /* zero words above m */
+ MP_ZERO_DIGITS(tmpx1, (x->used - m) - 1);
+
+ /* clamp, sub and return */
+ mp_clamp(x);
+
+ /* if x >= n then subtract and reduce again
+ * Each successive "recursion" makes the input smaller and smaller.
+ */
+ if (mp_cmp_mag(x, n) != MP_LT) {
+ if ((err = s_mp_sub(x, n, x)) != MP_OKAY) {
+ return err;
+ }
+ goto top;
+ }
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_dr_setup.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_dr_setup.c
new file mode 100644
index 0000000..32d5f38
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_dr_setup.c
@@ -0,0 +1,15 @@
+#include "tommath_private.h"
+#ifdef BN_MP_DR_SETUP_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* determines the setup value */
+void mp_dr_setup(const mp_int *a, mp_digit *d)
+{
+ /* the casts are required if MP_DIGIT_BIT is one less than
+ * the number of bits in a mp_digit [e.g. MP_DIGIT_BIT==31]
+ */
+ *d = (mp_digit)(((mp_word)1 << (mp_word)MP_DIGIT_BIT) - (mp_word)a->dp[0]);
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_error_to_string.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_error_to_string.c
new file mode 100644
index 0000000..2e2adb0
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_error_to_string.c
@@ -0,0 +1,27 @@
+#include "tommath_private.h"
+#ifdef BN_MP_ERROR_TO_STRING_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* return a char * string for a given code */
+const char *mp_error_to_string(mp_err code)
+{
+ switch (code) {
+ case MP_OKAY:
+ return "Successful";
+ case MP_ERR:
+ return "Unknown error";
+ case MP_MEM:
+ return "Out of heap";
+ case MP_VAL:
+ return "Value out of range";
+ case MP_ITER:
+ return "Max. iterations reached";
+ case MP_BUF:
+ return "Buffer overflow";
+ default:
+ return "Invalid error code";
+ }
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_exch.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_exch.c
new file mode 100644
index 0000000..552094c
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_exch.c
@@ -0,0 +1,17 @@
+#include "tommath_private.h"
+#ifdef BN_MP_EXCH_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* swap the elements of two integers, for cases where you can't simply swap the
+ * mp_int pointers around
+ */
+void mp_exch(mp_int *a, mp_int *b)
+{
+ mp_int t;
+
+ t = *a;
+ *a = *b;
+ *b = t;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_expt_u32.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_expt_u32.c
new file mode 100644
index 0000000..2ab67ba
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_expt_u32.c
@@ -0,0 +1,46 @@
+#include "tommath_private.h"
+#ifdef BN_MP_EXPT_U32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* calculate c = a**b using a square-multiply algorithm */
+mp_err mp_expt_u32(const mp_int *a, uint32_t b, mp_int *c)
+{
+ mp_err err;
+
+ mp_int g;
+
+ if ((err = mp_init_copy(&g, a)) != MP_OKAY) {
+ return err;
+ }
+
+ /* set initial result */
+ mp_set(c, 1uL);
+
+ while (b > 0u) {
+ /* if the bit is set multiply */
+ if ((b & 1u) != 0u) {
+ if ((err = mp_mul(c, &g, c)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ }
+
+ /* square */
+ if (b > 1u) {
+ if ((err = mp_sqr(&g, &g)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ }
+
+ /* shift to next bit */
+ b >>= 1;
+ }
+
+ err = MP_OKAY;
+
+LBL_ERR:
+ mp_clear(&g);
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_exptmod.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_exptmod.c
new file mode 100644
index 0000000..5f811eb
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_exptmod.c
@@ -0,0 +1,76 @@
+#include "tommath_private.h"
+#ifdef BN_MP_EXPTMOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* this is a shell function that calls either the normal or Montgomery
+ * exptmod functions. Originally the call to the montgomery code was
+ * embedded in the normal function but that wasted alot of stack space
+ * for nothing (since 99% of the time the Montgomery code would be called)
+ */
+mp_err mp_exptmod(const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y)
+{
+ int dr;
+
+ /* modulus P must be positive */
+ if (P->sign == MP_NEG) {
+ return MP_VAL;
+ }
+
+ /* if exponent X is negative we have to recurse */
+ if (X->sign == MP_NEG) {
+ mp_int tmpG, tmpX;
+ mp_err err;
+
+ if (!MP_HAS(MP_INVMOD)) {
+ return MP_VAL;
+ }
+
+ if ((err = mp_init_multi(&tmpG, &tmpX, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* first compute 1/G mod P */
+ if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ /* now get |X| */
+ if ((err = mp_abs(X, &tmpX)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ /* and now compute (1/G)**|X| instead of G**X [X < 0] */
+ err = mp_exptmod(&tmpG, &tmpX, P, Y);
+LBL_ERR:
+ mp_clear_multi(&tmpG, &tmpX, NULL);
+ return err;
+ }
+
+ /* modified diminished radix reduction */
+ if (MP_HAS(MP_REDUCE_IS_2K_L) && MP_HAS(MP_REDUCE_2K_L) && MP_HAS(S_MP_EXPTMOD) &&
+ (mp_reduce_is_2k_l(P) == MP_YES)) {
+ return s_mp_exptmod(G, X, P, Y, 1);
+ }
+
+ /* is it a DR modulus? default to no */
+ dr = (MP_HAS(MP_DR_IS_MODULUS) && (mp_dr_is_modulus(P) == MP_YES)) ? 1 : 0;
+
+ /* if not, is it a unrestricted DR modulus? */
+ if (MP_HAS(MP_REDUCE_IS_2K) && (dr == 0)) {
+ dr = (mp_reduce_is_2k(P) == MP_YES) ? 2 : 0;
+ }
+
+ /* if the modulus is odd or dr != 0 use the montgomery method */
+ if (MP_HAS(S_MP_EXPTMOD_FAST) && (MP_IS_ODD(P) || (dr != 0))) {
+ return s_mp_exptmod_fast(G, X, P, Y, dr);
+ } else if (MP_HAS(S_MP_EXPTMOD)) {
+ /* otherwise use the generic Barrett reduction technique */
+ return s_mp_exptmod(G, X, P, Y, 0);
+ } else {
+ /* no exptmod for evens */
+ return MP_VAL;
+ }
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_exteuclid.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_exteuclid.c
new file mode 100644
index 0000000..faf47ba
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_exteuclid.c
@@ -0,0 +1,73 @@
+#include "tommath_private.h"
+#ifdef BN_MP_EXTEUCLID_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Extended euclidean algorithm of (a, b) produces
+ a*u1 + b*u2 = u3
+ */
+mp_err mp_exteuclid(const mp_int *a, const mp_int *b, mp_int *U1, mp_int *U2, mp_int *U3)
+{
+ mp_int u1, u2, u3, v1, v2, v3, t1, t2, t3, q, tmp;
+ mp_err err;
+
+ if ((err = mp_init_multi(&u1, &u2, &u3, &v1, &v2, &v3, &t1, &t2, &t3, &q, &tmp, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* initialize, (u1,u2,u3) = (1,0,a) */
+ mp_set(&u1, 1uL);
+ if ((err = mp_copy(a, &u3)) != MP_OKAY) goto LBL_ERR;
+
+ /* initialize, (v1,v2,v3) = (0,1,b) */
+ mp_set(&v2, 1uL);
+ if ((err = mp_copy(b, &v3)) != MP_OKAY) goto LBL_ERR;
+
+ /* loop while v3 != 0 */
+ while (!MP_IS_ZERO(&v3)) {
+ /* q = u3/v3 */
+ if ((err = mp_div(&u3, &v3, &q, NULL)) != MP_OKAY) goto LBL_ERR;
+
+ /* (t1,t2,t3) = (u1,u2,u3) - (v1,v2,v3)q */
+ if ((err = mp_mul(&v1, &q, &tmp)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_sub(&u1, &tmp, &t1)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_mul(&v2, &q, &tmp)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_sub(&u2, &tmp, &t2)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_mul(&v3, &q, &tmp)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_sub(&u3, &tmp, &t3)) != MP_OKAY) goto LBL_ERR;
+
+ /* (u1,u2,u3) = (v1,v2,v3) */
+ if ((err = mp_copy(&v1, &u1)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_copy(&v2, &u2)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_copy(&v3, &u3)) != MP_OKAY) goto LBL_ERR;
+
+ /* (v1,v2,v3) = (t1,t2,t3) */
+ if ((err = mp_copy(&t1, &v1)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_copy(&t2, &v2)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_copy(&t3, &v3)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* make sure U3 >= 0 */
+ if (u3.sign == MP_NEG) {
+ if ((err = mp_neg(&u1, &u1)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_neg(&u2, &u2)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_neg(&u3, &u3)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* copy result out */
+ if (U1 != NULL) {
+ mp_exch(U1, &u1);
+ }
+ if (U2 != NULL) {
+ mp_exch(U2, &u2);
+ }
+ if (U3 != NULL) {
+ mp_exch(U3, &u3);
+ }
+
+ err = MP_OKAY;
+LBL_ERR:
+ mp_clear_multi(&u1, &u2, &u3, &v1, &v2, &v3, &t1, &t2, &t3, &q, &tmp, NULL);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_fread.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_fread.c
new file mode 100644
index 0000000..52ea773
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_fread.c
@@ -0,0 +1,60 @@
+#include "tommath_private.h"
+#ifdef BN_MP_FREAD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#ifndef MP_NO_FILE
+/* read a bigint from a file stream in ASCII */
+mp_err mp_fread(mp_int *a, int radix, FILE *stream)
+{
+ mp_err err;
+ mp_sign neg;
+
+ /* if first digit is - then set negative */
+ int ch = fgetc(stream);
+ if (ch == (int)'-') {
+ neg = MP_NEG;
+ ch = fgetc(stream);
+ } else {
+ neg = MP_ZPOS;
+ }
+
+ /* no digits, return error */
+ if (ch == EOF) {
+ return MP_ERR;
+ }
+
+ /* clear a */
+ mp_zero(a);
+
+ do {
+ int y;
+ unsigned pos = (unsigned)(ch - (int)'(');
+ if (mp_s_rmap_reverse_sz < pos) {
+ break;
+ }
+
+ y = (int)mp_s_rmap_reverse[pos];
+
+ if ((y == 0xff) || (y >= radix)) {
+ break;
+ }
+
+ /* shift up and add */
+ if ((err = mp_mul_d(a, (mp_digit)radix, a)) != MP_OKAY) {
+ return err;
+ }
+ if ((err = mp_add_d(a, (mp_digit)y, a)) != MP_OKAY) {
+ return err;
+ }
+ } while ((ch = fgetc(stream)) != EOF);
+
+ if (a->used != 0) {
+ a->sign = neg;
+ }
+
+ return MP_OKAY;
+}
+#endif
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_from_sbin.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_from_sbin.c
new file mode 100644
index 0000000..20e4597
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_from_sbin.c
@@ -0,0 +1,25 @@
+#include "tommath_private.h"
+#ifdef BN_MP_FROM_SBIN_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* read signed bin, big endian, first byte is 0==positive or 1==negative */
+mp_err mp_from_sbin(mp_int *a, const unsigned char *buf, size_t size)
+{
+ mp_err err;
+
+ /* read magnitude */
+ if ((err = mp_from_ubin(a, buf + 1, size - 1u)) != MP_OKAY) {
+ return err;
+ }
+
+ /* first byte is 0 for positive, non-zero for negative */
+ if (buf[0] == (unsigned char)0) {
+ a->sign = MP_ZPOS;
+ } else {
+ a->sign = MP_NEG;
+ }
+
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_from_ubin.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_from_ubin.c
new file mode 100644
index 0000000..7f73cbc
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_from_ubin.c
@@ -0,0 +1,39 @@
+#include "tommath_private.h"
+#ifdef BN_MP_FROM_UBIN_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* reads a unsigned char array, assumes the msb is stored first [big endian] */
+mp_err mp_from_ubin(mp_int *a, const unsigned char *buf, size_t size)
+{
+ mp_err err;
+
+ /* make sure there are at least two digits */
+ if (a->alloc < 2) {
+ if ((err = mp_grow(a, 2)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* zero the int */
+ mp_zero(a);
+
+ /* read the bytes in */
+ while (size-- > 0u) {
+ if ((err = mp_mul_2d(a, 8, a)) != MP_OKAY) {
+ return err;
+ }
+
+#ifndef MP_8BIT
+ a->dp[0] |= *buf++;
+ a->used += 1;
+#else
+ a->dp[0] = (*buf & MP_MASK);
+ a->dp[1] |= ((*buf++ >> 7) & 1u);
+ a->used += 2;
+#endif
+ }
+ mp_clamp(a);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_fwrite.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_fwrite.c
new file mode 100644
index 0000000..abe2e67
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_fwrite.c
@@ -0,0 +1,45 @@
+#include "tommath_private.h"
+#ifdef BN_MP_FWRITE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#ifndef MP_NO_FILE
+mp_err mp_fwrite(const mp_int *a, int radix, FILE *stream)
+{
+ char *buf;
+ mp_err err;
+ int len;
+ size_t written;
+
+ /* TODO: this function is not in this PR */
+ if (MP_HAS(MP_RADIX_SIZE_OVERESTIMATE)) {
+ /* if ((err = mp_radix_size_overestimate(&t, base, &len)) != MP_OKAY) goto LBL_ERR; */
+ } else {
+ if ((err = mp_radix_size(a, radix, &len)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ buf = (char *) MP_MALLOC((size_t)len);
+ if (buf == NULL) {
+ return MP_MEM;
+ }
+
+ if ((err = mp_to_radix(a, buf, (size_t)len, &written, radix)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ if (fwrite(buf, written, 1uL, stream) != 1uL) {
+ err = MP_ERR;
+ goto LBL_ERR;
+ }
+ err = MP_OKAY;
+
+
+LBL_ERR:
+ MP_FREE_BUFFER(buf, (size_t)len);
+ return err;
+}
+#endif
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_gcd.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_gcd.c
new file mode 100644
index 0000000..53029ba
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_gcd.c
@@ -0,0 +1,92 @@
+#include "tommath_private.h"
+#ifdef BN_MP_GCD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Greatest Common Divisor using the binary method */
+mp_err mp_gcd(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_int u, v;
+ int k, u_lsb, v_lsb;
+ mp_err err;
+
+ /* either zero than gcd is the largest */
+ if (MP_IS_ZERO(a)) {
+ return mp_abs(b, c);
+ }
+ if (MP_IS_ZERO(b)) {
+ return mp_abs(a, c);
+ }
+
+ /* get copies of a and b we can modify */
+ if ((err = mp_init_copy(&u, a)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_init_copy(&v, b)) != MP_OKAY) {
+ goto LBL_U;
+ }
+
+ /* must be positive for the remainder of the algorithm */
+ u.sign = v.sign = MP_ZPOS;
+
+ /* B1. Find the common power of two for u and v */
+ u_lsb = mp_cnt_lsb(&u);
+ v_lsb = mp_cnt_lsb(&v);
+ k = MP_MIN(u_lsb, v_lsb);
+
+ if (k > 0) {
+ /* divide the power of two out */
+ if ((err = mp_div_2d(&u, k, &u, NULL)) != MP_OKAY) {
+ goto LBL_V;
+ }
+
+ if ((err = mp_div_2d(&v, k, &v, NULL)) != MP_OKAY) {
+ goto LBL_V;
+ }
+ }
+
+ /* divide any remaining factors of two out */
+ if (u_lsb != k) {
+ if ((err = mp_div_2d(&u, u_lsb - k, &u, NULL)) != MP_OKAY) {
+ goto LBL_V;
+ }
+ }
+
+ if (v_lsb != k) {
+ if ((err = mp_div_2d(&v, v_lsb - k, &v, NULL)) != MP_OKAY) {
+ goto LBL_V;
+ }
+ }
+
+ while (!MP_IS_ZERO(&v)) {
+ /* make sure v is the largest */
+ if (mp_cmp_mag(&u, &v) == MP_GT) {
+ /* swap u and v to make sure v is >= u */
+ mp_exch(&u, &v);
+ }
+
+ /* subtract smallest from largest */
+ if ((err = s_mp_sub(&v, &u, &v)) != MP_OKAY) {
+ goto LBL_V;
+ }
+
+ /* Divide out all factors of two */
+ if ((err = mp_div_2d(&v, mp_cnt_lsb(&v), &v, NULL)) != MP_OKAY) {
+ goto LBL_V;
+ }
+ }
+
+ /* multiply by 2**k which we divided out at the beginning */
+ if ((err = mp_mul_2d(&u, k, c)) != MP_OKAY) {
+ goto LBL_V;
+ }
+ c->sign = MP_ZPOS;
+ err = MP_OKAY;
+LBL_V:
+ mp_clear(&u);
+LBL_U:
+ mp_clear(&v);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_double.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_double.c
new file mode 100644
index 0000000..c9b1b19
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_double.c
@@ -0,0 +1,18 @@
+#include "tommath_private.h"
+#ifdef BN_MP_GET_DOUBLE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+double mp_get_double(const mp_int *a)
+{
+ int i;
+ double d = 0.0, fac = 1.0;
+ for (i = 0; i < MP_DIGIT_BIT; ++i) {
+ fac *= 2.0;
+ }
+ for (i = a->used; i --> 0;) {
+ d = (d * fac) + (double)a->dp[i];
+ }
+ return (a->sign == MP_NEG) ? -d : d;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_i32.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_i32.c
new file mode 100644
index 0000000..030b657
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_i32.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_GET_I32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_SIGNED(mp_get_i32, mp_get_mag_u32, int32_t, uint32_t)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_i64.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_i64.c
new file mode 100644
index 0000000..969c8d2
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_i64.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_GET_I64_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_SIGNED(mp_get_i64, mp_get_mag_u64, int64_t, uint64_t)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_l.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_l.c
new file mode 100644
index 0000000..55d78ec
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_l.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_GET_L_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_SIGNED(mp_get_l, mp_get_mag_ul, long, unsigned long)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_ll.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_ll.c
new file mode 100644
index 0000000..2687534
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_ll.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_GET_LL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_SIGNED(mp_get_ll, mp_get_mag_ull, long long, unsigned long long)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_u32.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_u32.c
new file mode 100644
index 0000000..d77189b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_u32.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_GET_MAG_U32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_MAG(mp_get_mag_u32, uint32_t)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_u64.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_u64.c
new file mode 100644
index 0000000..36dd73f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_u64.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_GET_MAG_U64_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_MAG(mp_get_mag_u64, uint64_t)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_ul.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_ul.c
new file mode 100644
index 0000000..e8819ae
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_ul.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_GET_MAG_UL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_MAG(mp_get_mag_ul, unsigned long)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_ull.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_ull.c
new file mode 100644
index 0000000..63a2741
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_get_mag_ull.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_GET_MAG_ULL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_MAG(mp_get_mag_ull, unsigned long long)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_grow.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_grow.c
new file mode 100644
index 0000000..9e904c5
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_grow.c
@@ -0,0 +1,38 @@
+#include "tommath_private.h"
+#ifdef BN_MP_GROW_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* grow as required */
+mp_err mp_grow(mp_int *a, int size)
+{
+ int i;
+ mp_digit *tmp;
+
+ /* if the alloc size is smaller alloc more ram */
+ if (a->alloc < size) {
+ /* reallocate the array a->dp
+ *
+ * We store the return in a temporary variable
+ * in case the operation failed we don't want
+ * to overwrite the dp member of a.
+ */
+ tmp = (mp_digit *) MP_REALLOC(a->dp,
+ (size_t)a->alloc * sizeof(mp_digit),
+ (size_t)size * sizeof(mp_digit));
+ if (tmp == NULL) {
+ /* reallocation failed but "a" is still valid [can be freed] */
+ return MP_MEM;
+ }
+
+ /* reallocation succeeded so set a->dp */
+ a->dp = tmp;
+
+ /* zero excess digits */
+ i = a->alloc;
+ a->alloc = size;
+ MP_ZERO_DIGITS(a->dp + i, a->alloc - i);
+ }
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_incr.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_incr.c
new file mode 100644
index 0000000..7695ac7
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_incr.c
@@ -0,0 +1,30 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INCR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Increment "a" by one like "a++". Changes input! */
+mp_err mp_incr(mp_int *a)
+{
+ if (MP_IS_ZERO(a)) {
+ mp_set(a,1uL);
+ return MP_OKAY;
+ } else if (a->sign == MP_NEG) {
+ mp_err err;
+ a->sign = MP_ZPOS;
+ if ((err = mp_decr(a)) != MP_OKAY) {
+ return err;
+ }
+ /* There is no -0 in LTM */
+ if (!MP_IS_ZERO(a)) {
+ a->sign = MP_NEG;
+ }
+ return MP_OKAY;
+ } else if (a->dp[0] < MP_DIGIT_MAX) {
+ a->dp[0]++;
+ return MP_OKAY;
+ } else {
+ return mp_add_d(a, 1uL,a);
+ }
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init.c
new file mode 100644
index 0000000..2eb7924
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init.c
@@ -0,0 +1,23 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* init a new mp_int */
+mp_err mp_init(mp_int *a)
+{
+ /* allocate memory required and clear it */
+ a->dp = (mp_digit *) MP_CALLOC((size_t)MP_PREC, sizeof(mp_digit));
+ if (a->dp == NULL) {
+ return MP_MEM;
+ }
+
+ /* set the used to zero, allocated digits to the default precision
+ * and sign to positive */
+ a->used = 0;
+ a->alloc = MP_PREC;
+ a->sign = MP_ZPOS;
+
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_copy.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_copy.c
new file mode 100644
index 0000000..1888203
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_copy.c
@@ -0,0 +1,21 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_COPY_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* creates "a" then copies b into it */
+mp_err mp_init_copy(mp_int *a, const mp_int *b)
+{
+ mp_err err;
+
+ if ((err = mp_init_size(a, b->used)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_copy(b, a)) != MP_OKAY) {
+ mp_clear(a);
+ }
+
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_i32.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_i32.c
new file mode 100644
index 0000000..bc4de8d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_i32.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_I32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_i32, mp_set_i32, int32_t)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_i64.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_i64.c
new file mode 100644
index 0000000..2fa1516
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_i64.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_I64_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_i64, mp_set_i64, int64_t)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_l.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_l.c
new file mode 100644
index 0000000..bc380b5
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_l.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_L_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_l, mp_set_l, long)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_ll.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_ll.c
new file mode 100644
index 0000000..dc7c4a4
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_ll.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_LL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_ll, mp_set_ll, long long)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_multi.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_multi.c
new file mode 100644
index 0000000..d8390b5
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_multi.c
@@ -0,0 +1,41 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_MULTI_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#include <stdarg.h>
+
+mp_err mp_init_multi(mp_int *mp, ...)
+{
+ mp_err err = MP_OKAY; /* Assume ok until proven otherwise */
+ int n = 0; /* Number of ok inits */
+ mp_int *cur_arg = mp;
+ va_list args;
+
+ va_start(args, mp); /* init args to next argument from caller */
+ while (cur_arg != NULL) {
+ if (mp_init(cur_arg) != MP_OKAY) {
+ /* Oops - error! Back-track and mp_clear what we already
+ succeeded in init-ing, then return error.
+ */
+ va_list clean_args;
+
+ /* now start cleaning up */
+ cur_arg = mp;
+ va_start(clean_args, mp);
+ while (n-- != 0) {
+ mp_clear(cur_arg);
+ cur_arg = va_arg(clean_args, mp_int *);
+ }
+ va_end(clean_args);
+ err = MP_MEM;
+ break;
+ }
+ n++;
+ cur_arg = va_arg(args, mp_int *);
+ }
+ va_end(args);
+ return err; /* Assumed ok, if error flagged above. */
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_set.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_set.c
new file mode 100644
index 0000000..5068f2b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_set.c
@@ -0,0 +1,16 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_SET_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* initialize and set a digit */
+mp_err mp_init_set(mp_int *a, mp_digit b)
+{
+ mp_err err;
+ if ((err = mp_init(a)) != MP_OKAY) {
+ return err;
+ }
+ mp_set(a, b);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_size.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_size.c
new file mode 100644
index 0000000..d622687
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_size.c
@@ -0,0 +1,24 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_SIZE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* init an mp_init for a given size */
+mp_err mp_init_size(mp_int *a, int size)
+{
+ size = MP_MAX(MP_MIN_PREC, size);
+
+ /* alloc mem */
+ a->dp = (mp_digit *) MP_CALLOC((size_t)size, sizeof(mp_digit));
+ if (a->dp == NULL) {
+ return MP_MEM;
+ }
+
+ /* set the members */
+ a->used = 0;
+ a->alloc = size;
+ a->sign = MP_ZPOS;
+
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_u32.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_u32.c
new file mode 100644
index 0000000..015d89b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_u32.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_U32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_u32, mp_set_u32, uint32_t)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_u64.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_u64.c
new file mode 100644
index 0000000..2b35f7e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_u64.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_U64_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_u64, mp_set_u64, uint64_t)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_ul.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_ul.c
new file mode 100644
index 0000000..5164f72
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_ul.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_UL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_ul, mp_set_ul, unsigned long)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_ull.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_ull.c
new file mode 100644
index 0000000..84110c0
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_init_ull.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_ULL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_ull, mp_set_ull, unsigned long long)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_invmod.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_invmod.c
new file mode 100644
index 0000000..7b35a24
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_invmod.c
@@ -0,0 +1,23 @@
+#include "tommath_private.h"
+#ifdef BN_MP_INVMOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* hac 14.61, pp608 */
+mp_err mp_invmod(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ /* b cannot be negative and has to be >1 */
+ if ((b->sign == MP_NEG) || (mp_cmp_d(b, 1uL) != MP_GT)) {
+ return MP_VAL;
+ }
+
+ /* if the modulus is odd we can use a faster routine instead */
+ if (MP_HAS(S_MP_INVMOD_FAST) && MP_IS_ODD(b)) {
+ return s_mp_invmod_fast(a, b, c);
+ }
+
+ return MP_HAS(S_MP_INVMOD_SLOW)
+ ? s_mp_invmod_slow(a, b, c)
+ : MP_VAL;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_is_square.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_is_square.c
new file mode 100644
index 0000000..69e77a2
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_is_square.c
@@ -0,0 +1,93 @@
+#include "tommath_private.h"
+#ifdef BN_MP_IS_SQUARE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Check if remainders are possible squares - fast exclude non-squares */
+static const char rem_128[128] = {
+ 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
+ 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
+ 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
+ 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
+ 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
+ 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
+ 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
+ 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1
+};
+
+static const char rem_105[105] = {
+ 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,
+ 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1,
+ 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1,
+ 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
+ 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1,
+ 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1,
+ 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1
+};
+
+/* Store non-zero to ret if arg is square, and zero if not */
+mp_err mp_is_square(const mp_int *arg, mp_bool *ret)
+{
+ mp_err err;
+ mp_digit c;
+ mp_int t;
+ unsigned long r;
+
+ /* Default to Non-square :) */
+ *ret = MP_NO;
+
+ if (arg->sign == MP_NEG) {
+ return MP_VAL;
+ }
+
+ if (MP_IS_ZERO(arg)) {
+ return MP_OKAY;
+ }
+
+ /* First check mod 128 (suppose that MP_DIGIT_BIT is at least 7) */
+ if (rem_128[127u & arg->dp[0]] == (char)1) {
+ return MP_OKAY;
+ }
+
+ /* Next check mod 105 (3*5*7) */
+ if ((err = mp_mod_d(arg, 105uL, &c)) != MP_OKAY) {
+ return err;
+ }
+ if (rem_105[c] == (char)1) {
+ return MP_OKAY;
+ }
+
+
+ if ((err = mp_init_u32(&t, 11u*13u*17u*19u*23u*29u*31u)) != MP_OKAY) {
+ return err;
+ }
+ if ((err = mp_mod(arg, &t, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ r = mp_get_u32(&t);
+ /* Check for other prime modules, note it's not an ERROR but we must
+ * free "t" so the easiest way is to goto LBL_ERR. We know that err
+ * is already equal to MP_OKAY from the mp_mod call
+ */
+ if (((1uL<<(r%11uL)) & 0x5C4uL) != 0uL) goto LBL_ERR;
+ if (((1uL<<(r%13uL)) & 0x9E4uL) != 0uL) goto LBL_ERR;
+ if (((1uL<<(r%17uL)) & 0x5CE8uL) != 0uL) goto LBL_ERR;
+ if (((1uL<<(r%19uL)) & 0x4F50CuL) != 0uL) goto LBL_ERR;
+ if (((1uL<<(r%23uL)) & 0x7ACCA0uL) != 0uL) goto LBL_ERR;
+ if (((1uL<<(r%29uL)) & 0xC2EDD0CuL) != 0uL) goto LBL_ERR;
+ if (((1uL<<(r%31uL)) & 0x6DE2B848uL) != 0uL) goto LBL_ERR;
+
+ /* Final check - is sqr(sqrt(arg)) == arg ? */
+ if ((err = mp_sqrt(arg, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if ((err = mp_sqr(&t, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ *ret = (mp_cmp_mag(&t, arg) == MP_EQ) ? MP_YES : MP_NO;
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_iseven.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_iseven.c
new file mode 100644
index 0000000..5cb9622
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_iseven.c
@@ -0,0 +1,10 @@
+#include "tommath_private.h"
+#ifdef BN_MP_ISEVEN_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+mp_bool mp_iseven(const mp_int *a)
+{
+ return MP_IS_EVEN(a) ? MP_YES : MP_NO;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_isodd.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_isodd.c
new file mode 100644
index 0000000..bf17646
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_isodd.c
@@ -0,0 +1,10 @@
+#include "tommath_private.h"
+#ifdef BN_MP_ISODD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+mp_bool mp_isodd(const mp_int *a)
+{
+ return MP_IS_ODD(a) ? MP_YES : MP_NO;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_kronecker.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_kronecker.c
new file mode 100644
index 0000000..525a820
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_kronecker.c
@@ -0,0 +1,129 @@
+#include "tommath_private.h"
+#ifdef BN_MP_KRONECKER_C
+
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/*
+ Kronecker symbol (a|p)
+ Straightforward implementation of algorithm 1.4.10 in
+ Henri Cohen: "A Course in Computational Algebraic Number Theory"
+
+ @book{cohen2013course,
+ title={A course in computational algebraic number theory},
+ author={Cohen, Henri},
+ volume={138},
+ year={2013},
+ publisher={Springer Science \& Business Media}
+ }
+ */
+mp_err mp_kronecker(const mp_int *a, const mp_int *p, int *c)
+{
+ mp_int a1, p1, r;
+ mp_err err;
+ int v, k;
+
+ static const int table[8] = {0, 1, 0, -1, 0, -1, 0, 1};
+
+ if (MP_IS_ZERO(p)) {
+ if ((a->used == 1) && (a->dp[0] == 1u)) {
+ *c = 1;
+ } else {
+ *c = 0;
+ }
+ return MP_OKAY;
+ }
+
+ if (MP_IS_EVEN(a) && MP_IS_EVEN(p)) {
+ *c = 0;
+ return MP_OKAY;
+ }
+
+ if ((err = mp_init_copy(&a1, a)) != MP_OKAY) {
+ return err;
+ }
+ if ((err = mp_init_copy(&p1, p)) != MP_OKAY) {
+ goto LBL_KRON_0;
+ }
+
+ v = mp_cnt_lsb(&p1);
+ if ((err = mp_div_2d(&p1, v, &p1, NULL)) != MP_OKAY) {
+ goto LBL_KRON_1;
+ }
+
+ if ((v & 1) == 0) {
+ k = 1;
+ } else {
+ k = table[a->dp[0] & 7u];
+ }
+
+ if (p1.sign == MP_NEG) {
+ p1.sign = MP_ZPOS;
+ if (a1.sign == MP_NEG) {
+ k = -k;
+ }
+ }
+
+ if ((err = mp_init(&r)) != MP_OKAY) {
+ goto LBL_KRON_1;
+ }
+
+ for (;;) {
+ if (MP_IS_ZERO(&a1)) {
+ if (mp_cmp_d(&p1, 1uL) == MP_EQ) {
+ *c = k;
+ goto LBL_KRON;
+ } else {
+ *c = 0;
+ goto LBL_KRON;
+ }
+ }
+
+ v = mp_cnt_lsb(&a1);
+ if ((err = mp_div_2d(&a1, v, &a1, NULL)) != MP_OKAY) {
+ goto LBL_KRON;
+ }
+
+ if ((v & 1) == 1) {
+ k = k * table[p1.dp[0] & 7u];
+ }
+
+ if (a1.sign == MP_NEG) {
+ /*
+ * Compute k = (-1)^((a1)*(p1-1)/4) * k
+ * a1.dp[0] + 1 cannot overflow because the MSB
+ * of the type mp_digit is not set by definition
+ */
+ if (((a1.dp[0] + 1u) & p1.dp[0] & 2u) != 0u) {
+ k = -k;
+ }
+ } else {
+ /* compute k = (-1)^((a1-1)*(p1-1)/4) * k */
+ if ((a1.dp[0] & p1.dp[0] & 2u) != 0u) {
+ k = -k;
+ }
+ }
+
+ if ((err = mp_copy(&a1, &r)) != MP_OKAY) {
+ goto LBL_KRON;
+ }
+ r.sign = MP_ZPOS;
+ if ((err = mp_mod(&p1, &r, &a1)) != MP_OKAY) {
+ goto LBL_KRON;
+ }
+ if ((err = mp_copy(&r, &p1)) != MP_OKAY) {
+ goto LBL_KRON;
+ }
+ }
+
+LBL_KRON:
+ mp_clear(&r);
+LBL_KRON_1:
+ mp_clear(&p1);
+LBL_KRON_0:
+ mp_clear(&a1);
+
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_lcm.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_lcm.c
new file mode 100644
index 0000000..c32b269
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_lcm.c
@@ -0,0 +1,44 @@
+#include "tommath_private.h"
+#ifdef BN_MP_LCM_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* computes least common multiple as |a*b|/(a, b) */
+mp_err mp_lcm(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_err err;
+ mp_int t1, t2;
+
+
+ if ((err = mp_init_multi(&t1, &t2, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* t1 = get the GCD of the two inputs */
+ if ((err = mp_gcd(a, b, &t1)) != MP_OKAY) {
+ goto LBL_T;
+ }
+
+ /* divide the smallest by the GCD */
+ if (mp_cmp_mag(a, b) == MP_LT) {
+ /* store quotient in t2 such that t2 * b is the LCM */
+ if ((err = mp_div(a, &t1, &t2, NULL)) != MP_OKAY) {
+ goto LBL_T;
+ }
+ err = mp_mul(b, &t2, c);
+ } else {
+ /* store quotient in t2 such that t2 * a is the LCM */
+ if ((err = mp_div(b, &t1, &t2, NULL)) != MP_OKAY) {
+ goto LBL_T;
+ }
+ err = mp_mul(a, &t2, c);
+ }
+
+ /* fix the sign to positive */
+ c->sign = MP_ZPOS;
+
+LBL_T:
+ mp_clear_multi(&t1, &t2, NULL);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_log_u32.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_log_u32.c
new file mode 100644
index 0000000..f7bca01
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_log_u32.c
@@ -0,0 +1,180 @@
+#include "tommath_private.h"
+#ifdef BN_MP_LOG_U32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Compute log_{base}(a) */
+static mp_word s_pow(mp_word base, mp_word exponent)
+{
+ mp_word result = 1uLL;
+ while (exponent != 0u) {
+ if ((exponent & 1u) == 1u) {
+ result *= base;
+ }
+ exponent >>= 1;
+ base *= base;
+ }
+
+ return result;
+}
+
+static mp_digit s_digit_ilogb(mp_digit base, mp_digit n)
+{
+ mp_word bracket_low = 1uLL, bracket_mid, bracket_high, N;
+ mp_digit ret, high = 1uL, low = 0uL, mid;
+
+ if (n < base) {
+ return 0uL;
+ }
+ if (n == base) {
+ return 1uL;
+ }
+
+ bracket_high = (mp_word) base ;
+ N = (mp_word) n;
+
+ while (bracket_high < N) {
+ low = high;
+ bracket_low = bracket_high;
+ high <<= 1;
+ bracket_high *= bracket_high;
+ }
+
+ while (((mp_digit)(high - low)) > 1uL) {
+ mid = (low + high) >> 1;
+ bracket_mid = bracket_low * s_pow(base, (mp_word)(mid - low));
+
+ if (N < bracket_mid) {
+ high = mid ;
+ bracket_high = bracket_mid ;
+ }
+ if (N > bracket_mid) {
+ low = mid ;
+ bracket_low = bracket_mid ;
+ }
+ if (N == bracket_mid) {
+ return (mp_digit) mid;
+ }
+ }
+
+ if (bracket_high == N) {
+ ret = high;
+ } else {
+ ret = low;
+ }
+
+ return ret;
+}
+
+/* TODO: output could be "int" because the output of mp_radix_size is int, too,
+ as is the output of mp_bitcount.
+ With the same problem: max size is INT_MAX * MP_DIGIT not INT_MAX only!
+*/
+mp_err mp_log_u32(const mp_int *a, uint32_t base, uint32_t *c)
+{
+ mp_err err;
+ mp_ord cmp;
+ uint32_t high, low, mid;
+ mp_int bracket_low, bracket_high, bracket_mid, t, bi_base;
+
+ err = MP_OKAY;
+
+ if (a->sign == MP_NEG) {
+ return MP_VAL;
+ }
+
+ if (MP_IS_ZERO(a)) {
+ return MP_VAL;
+ }
+
+ if (base < 2u) {
+ return MP_VAL;
+ }
+
+ /* A small shortcut for bases that are powers of two. */
+ if ((base & (base - 1u)) == 0u) {
+ int y, bit_count;
+ for (y=0; (y < 7) && ((base & 1u) == 0u); y++) {
+ base >>= 1;
+ }
+ bit_count = mp_count_bits(a) - 1;
+ *c = (uint32_t)(bit_count/y);
+ return MP_OKAY;
+ }
+
+ if (a->used == 1) {
+ *c = (uint32_t)s_digit_ilogb(base, a->dp[0]);
+ return err;
+ }
+
+ cmp = mp_cmp_d(a, base);
+ if ((cmp == MP_LT) || (cmp == MP_EQ)) {
+ *c = cmp == MP_EQ;
+ return err;
+ }
+
+ if ((err =
+ mp_init_multi(&bracket_low, &bracket_high,
+ &bracket_mid, &t, &bi_base, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ low = 0u;
+ mp_set(&bracket_low, 1uL);
+ high = 1u;
+
+ mp_set(&bracket_high, base);
+
+ /*
+ A kind of Giant-step/baby-step algorithm.
+ Idea shamelessly stolen from https://programmingpraxis.com/2010/05/07/integer-logarithms/2/
+ The effect is asymptotic, hence needs benchmarks to test if the Giant-step should be skipped
+ for small n.
+ */
+ while (mp_cmp(&bracket_high, a) == MP_LT) {
+ low = high;
+ if ((err = mp_copy(&bracket_high, &bracket_low)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ high <<= 1;
+ if ((err = mp_sqr(&bracket_high, &bracket_high)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ }
+ mp_set(&bi_base, base);
+
+ while ((high - low) > 1u) {
+ mid = (high + low) >> 1;
+
+ if ((err = mp_expt_u32(&bi_base, (uint32_t)(mid - low), &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if ((err = mp_mul(&bracket_low, &t, &bracket_mid)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ cmp = mp_cmp(a, &bracket_mid);
+ if (cmp == MP_LT) {
+ high = mid;
+ mp_exch(&bracket_mid, &bracket_high);
+ }
+ if (cmp == MP_GT) {
+ low = mid;
+ mp_exch(&bracket_mid, &bracket_low);
+ }
+ if (cmp == MP_EQ) {
+ *c = mid;
+ goto LBL_END;
+ }
+ }
+
+ *c = (mp_cmp(&bracket_high, a) == MP_EQ) ? high : low;
+
+LBL_END:
+LBL_ERR:
+ mp_clear_multi(&bracket_low, &bracket_high, &bracket_mid,
+ &t, &bi_base, NULL);
+ return err;
+}
+
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_lshd.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_lshd.c
new file mode 100644
index 0000000..8234580
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_lshd.c
@@ -0,0 +1,51 @@
+#include "tommath_private.h"
+#ifdef BN_MP_LSHD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* shift left a certain amount of digits */
+mp_err mp_lshd(mp_int *a, int b)
+{
+ int x;
+ mp_err err;
+ mp_digit *top, *bottom;
+
+ /* if its less than zero return */
+ if (b <= 0) {
+ return MP_OKAY;
+ }
+ /* no need to shift 0 around */
+ if (MP_IS_ZERO(a)) {
+ return MP_OKAY;
+ }
+
+ /* grow to fit the new digits */
+ if (a->alloc < (a->used + b)) {
+ if ((err = mp_grow(a, a->used + b)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* increment the used by the shift amount then copy upwards */
+ a->used += b;
+
+ /* top */
+ top = a->dp + a->used - 1;
+
+ /* base */
+ bottom = (a->dp + a->used - 1) - b;
+
+ /* much like mp_rshd this is implemented using a sliding window
+ * except the window goes the otherway around. Copying from
+ * the bottom to the top. see bn_mp_rshd.c for more info.
+ */
+ for (x = a->used - 1; x >= b; x--) {
+ *top-- = *bottom--;
+ }
+
+ /* zero the lower digits */
+ MP_ZERO_DIGITS(a->dp, b);
+
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mod.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mod.c
new file mode 100644
index 0000000..8fbfe08
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mod.c
@@ -0,0 +1,31 @@
+#include "tommath_private.h"
+#ifdef BN_MP_MOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* c = a mod b, 0 <= c < b if b > 0, b < c <= 0 if b < 0 */
+mp_err mp_mod(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_int t;
+ mp_err err;
+
+ if ((err = mp_init_size(&t, b->used)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_div(a, b, NULL, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ if (MP_IS_ZERO(&t) || (t.sign == b->sign)) {
+ err = MP_OKAY;
+ mp_exch(&t, c);
+ } else {
+ err = mp_add(b, &t, c);
+ }
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mod_2d.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mod_2d.c
new file mode 100644
index 0000000..5bf57a1
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mod_2d.c
@@ -0,0 +1,38 @@
+#include "tommath_private.h"
+#ifdef BN_MP_MOD_2D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* calc a value mod 2**b */
+mp_err mp_mod_2d(const mp_int *a, int b, mp_int *c)
+{
+ int x;
+ mp_err err;
+
+ /* if b is <= 0 then zero the int */
+ if (b <= 0) {
+ mp_zero(c);
+ return MP_OKAY;
+ }
+
+ /* if the modulus is larger than the value than return */
+ if (b >= (a->used * MP_DIGIT_BIT)) {
+ return mp_copy(a, c);
+ }
+
+ /* copy */
+ if ((err = mp_copy(a, c)) != MP_OKAY) {
+ return err;
+ }
+
+ /* zero digits above the last digit of the modulus */
+ x = (b / MP_DIGIT_BIT) + (((b % MP_DIGIT_BIT) == 0) ? 0 : 1);
+ MP_ZERO_DIGITS(c->dp + x, c->used - x);
+
+ /* clear the digit that is not completely outside/inside the modulus */
+ c->dp[b / MP_DIGIT_BIT] &=
+ ((mp_digit)1 << (mp_digit)(b % MP_DIGIT_BIT)) - (mp_digit)1;
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mod_d.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mod_d.c
new file mode 100644
index 0000000..0b6c12a
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mod_d.c
@@ -0,0 +1,10 @@
+#include "tommath_private.h"
+#ifdef BN_MP_MOD_D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+mp_err mp_mod_d(const mp_int *a, mp_digit b, mp_digit *c)
+{
+ return mp_div_d(a, b, NULL, c);
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_montgomery_calc_normalization.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_montgomery_calc_normalization.c
new file mode 100644
index 0000000..8379789
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_montgomery_calc_normalization.c
@@ -0,0 +1,44 @@
+#include "tommath_private.h"
+#ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/*
+ * shifts with subtractions when the result is greater than b.
+ *
+ * The method is slightly modified to shift B unconditionally upto just under
+ * the leading bit of b. This saves alot of multiple precision shifting.
+ */
+mp_err mp_montgomery_calc_normalization(mp_int *a, const mp_int *b)
+{
+ int x, bits;
+ mp_err err;
+
+ /* how many bits of last digit does b use */
+ bits = mp_count_bits(b) % MP_DIGIT_BIT;
+
+ if (b->used > 1) {
+ if ((err = mp_2expt(a, ((b->used - 1) * MP_DIGIT_BIT) + bits - 1)) != MP_OKAY) {
+ return err;
+ }
+ } else {
+ mp_set(a, 1uL);
+ bits = 1;
+ }
+
+
+ /* now compute C = A * B mod b */
+ for (x = bits - 1; x < (int)MP_DIGIT_BIT; x++) {
+ if ((err = mp_mul_2(a, a)) != MP_OKAY) {
+ return err;
+ }
+ if (mp_cmp_mag(a, b) != MP_LT) {
+ if ((err = s_mp_sub(a, b, a)) != MP_OKAY) {
+ return err;
+ }
+ }
+ }
+
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_montgomery_reduce.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_montgomery_reduce.c
new file mode 100644
index 0000000..ffe8341
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_montgomery_reduce.c
@@ -0,0 +1,102 @@
+#include "tommath_private.h"
+#ifdef BN_MP_MONTGOMERY_REDUCE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* computes xR**-1 == x (mod N) via Montgomery Reduction */
+mp_err mp_montgomery_reduce(mp_int *x, const mp_int *n, mp_digit rho)
+{
+ int ix, digs;
+ mp_err err;
+ mp_digit mu;
+
+ /* can the fast reduction [comba] method be used?
+ *
+ * Note that unlike in mul you're safely allowed *less*
+ * than the available columns [255 per default] since carries
+ * are fixed up in the inner loop.
+ */
+ digs = (n->used * 2) + 1;
+ if ((digs < MP_WARRAY) &&
+ (x->used <= MP_WARRAY) &&
+ (n->used < MP_MAXFAST)) {
+ return s_mp_montgomery_reduce_fast(x, n, rho);
+ }
+
+ /* grow the input as required */
+ if (x->alloc < digs) {
+ if ((err = mp_grow(x, digs)) != MP_OKAY) {
+ return err;
+ }
+ }
+ x->used = digs;
+
+ for (ix = 0; ix < n->used; ix++) {
+ /* mu = ai * rho mod b
+ *
+ * The value of rho must be precalculated via
+ * montgomery_setup() such that
+ * it equals -1/n0 mod b this allows the
+ * following inner loop to reduce the
+ * input one digit at a time
+ */
+ mu = (mp_digit)(((mp_word)x->dp[ix] * (mp_word)rho) & MP_MASK);
+
+ /* a = a + mu * m * b**i */
+ {
+ int iy;
+ mp_digit *tmpn, *tmpx, u;
+ mp_word r;
+
+ /* alias for digits of the modulus */
+ tmpn = n->dp;
+
+ /* alias for the digits of x [the input] */
+ tmpx = x->dp + ix;
+
+ /* set the carry to zero */
+ u = 0;
+
+ /* Multiply and add in place */
+ for (iy = 0; iy < n->used; iy++) {
+ /* compute product and sum */
+ r = ((mp_word)mu * (mp_word)*tmpn++) +
+ (mp_word)u + (mp_word)*tmpx;
+
+ /* get carry */
+ u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
+
+ /* fix digit */
+ *tmpx++ = (mp_digit)(r & (mp_word)MP_MASK);
+ }
+ /* At this point the ix'th digit of x should be zero */
+
+
+ /* propagate carries upwards as required*/
+ while (u != 0u) {
+ *tmpx += u;
+ u = *tmpx >> MP_DIGIT_BIT;
+ *tmpx++ &= MP_MASK;
+ }
+ }
+ }
+
+ /* at this point the n.used'th least
+ * significant digits of x are all zero
+ * which means we can shift x to the
+ * right by n.used digits and the
+ * residue is unchanged.
+ */
+
+ /* x = x/b**n.used */
+ mp_clamp(x);
+ mp_rshd(x, n->used);
+
+ /* if x >= n then x = x - n */
+ if (mp_cmp_mag(x, n) != MP_LT) {
+ return s_mp_sub(x, n, x);
+ }
+
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_montgomery_setup.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_montgomery_setup.c
new file mode 100644
index 0000000..39f6e9d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_montgomery_setup.c
@@ -0,0 +1,42 @@
+#include "tommath_private.h"
+#ifdef BN_MP_MONTGOMERY_SETUP_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* setups the montgomery reduction stuff */
+mp_err mp_montgomery_setup(const mp_int *n, mp_digit *rho)
+{
+ mp_digit x, b;
+
+ /* fast inversion mod 2**k
+ *
+ * Based on the fact that
+ *
+ * XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n)
+ * => 2*X*A - X*X*A*A = 1
+ * => 2*(1) - (1) = 1
+ */
+ b = n->dp[0];
+
+ if ((b & 1u) == 0u) {
+ return MP_VAL;
+ }
+
+ x = (((b + 2u) & 4u) << 1) + b; /* here x*a==1 mod 2**4 */
+ x *= 2u - (b * x); /* here x*a==1 mod 2**8 */
+#if !defined(MP_8BIT)
+ x *= 2u - (b * x); /* here x*a==1 mod 2**16 */
+#endif
+#if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT))
+ x *= 2u - (b * x); /* here x*a==1 mod 2**32 */
+#endif
+#ifdef MP_64BIT
+ x *= 2u - (b * x); /* here x*a==1 mod 2**64 */
+#endif
+
+ /* rho = -1/m mod b */
+ *rho = (mp_digit)(((mp_word)1 << (mp_word)MP_DIGIT_BIT) - x) & MP_MASK;
+
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul.c
new file mode 100644
index 0000000..561913a
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul.c
@@ -0,0 +1,52 @@
+#include "tommath_private.h"
+#ifdef BN_MP_MUL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* high level multiplication (handles sign) */
+mp_err mp_mul(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_err err;
+ int min_len = MP_MIN(a->used, b->used),
+ max_len = MP_MAX(a->used, b->used),
+ digs = a->used + b->used + 1;
+ mp_sign neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
+
+ if (MP_HAS(S_MP_BALANCE_MUL) &&
+ /* Check sizes. The smaller one needs to be larger than the Karatsuba cut-off.
+ * The bigger one needs to be at least about one MP_KARATSUBA_MUL_CUTOFF bigger
+ * to make some sense, but it depends on architecture, OS, position of the
+ * stars... so YMMV.
+ * Using it to cut the input into slices small enough for fast_s_mp_mul_digs
+ * was actually slower on the author's machine, but YMMV.
+ */
+ (min_len >= MP_KARATSUBA_MUL_CUTOFF) &&
+ ((max_len / 2) >= MP_KARATSUBA_MUL_CUTOFF) &&
+ /* Not much effect was observed below a ratio of 1:2, but again: YMMV. */
+ (max_len >= (2 * min_len))) {
+ err = s_mp_balance_mul(a,b,c);
+ } else if (MP_HAS(S_MP_TOOM_MUL) &&
+ (min_len >= MP_TOOM_MUL_CUTOFF)) {
+ err = s_mp_toom_mul(a, b, c);
+ } else if (MP_HAS(S_MP_KARATSUBA_MUL) &&
+ (min_len >= MP_KARATSUBA_MUL_CUTOFF)) {
+ err = s_mp_karatsuba_mul(a, b, c);
+ } else if (MP_HAS(S_MP_MUL_DIGS_FAST) &&
+ /* can we use the fast multiplier?
+ *
+ * The fast multiplier can be used if the output will
+ * have less than MP_WARRAY digits and the number of
+ * digits won't affect carry propagation
+ */
+ (digs < MP_WARRAY) &&
+ (min_len <= MP_MAXFAST)) {
+ err = s_mp_mul_digs_fast(a, b, c, digs);
+ } else if (MP_HAS(S_MP_MUL_DIGS)) {
+ err = s_mp_mul_digs(a, b, c, digs);
+ } else {
+ err = MP_VAL;
+ }
+ c->sign = (c->used > 0) ? neg : MP_ZPOS;
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul_2.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul_2.c
new file mode 100644
index 0000000..bc0691a
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul_2.c
@@ -0,0 +1,64 @@
+#include "tommath_private.h"
+#ifdef BN_MP_MUL_2_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* b = a*2 */
+mp_err mp_mul_2(const mp_int *a, mp_int *b)
+{
+ int x, oldused;
+ mp_err err;
+
+ /* grow to accomodate result */
+ if (b->alloc < (a->used + 1)) {
+ if ((err = mp_grow(b, a->used + 1)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ oldused = b->used;
+ b->used = a->used;
+
+ {
+ mp_digit r, rr, *tmpa, *tmpb;
+
+ /* alias for source */
+ tmpa = a->dp;
+
+ /* alias for dest */
+ tmpb = b->dp;
+
+ /* carry */
+ r = 0;
+ for (x = 0; x < a->used; x++) {
+
+ /* get what will be the *next* carry bit from the
+ * MSB of the current digit
+ */
+ rr = *tmpa >> (mp_digit)(MP_DIGIT_BIT - 1);
+
+ /* now shift up this digit, add in the carry [from the previous] */
+ *tmpb++ = ((*tmpa++ << 1uL) | r) & MP_MASK;
+
+ /* copy the carry that would be from the source
+ * digit into the next iteration
+ */
+ r = rr;
+ }
+
+ /* new leading digit? */
+ if (r != 0u) {
+ /* add a MSB which is always 1 at this point */
+ *tmpb = 1;
+ ++(b->used);
+ }
+
+ /* now zero any excess digits on the destination
+ * that we didn't write to
+ */
+ MP_ZERO_DIGITS(b->dp + b->used, oldused - b->used);
+ }
+ b->sign = a->sign;
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul_2d.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul_2d.c
new file mode 100644
index 0000000..87354de
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul_2d.c
@@ -0,0 +1,69 @@
+#include "tommath_private.h"
+#ifdef BN_MP_MUL_2D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* shift left by a certain bit count */
+mp_err mp_mul_2d(const mp_int *a, int b, mp_int *c)
+{
+ mp_digit d;
+ mp_err err;
+
+ /* copy */
+ if (a != c) {
+ if ((err = mp_copy(a, c)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ if (c->alloc < (c->used + (b / MP_DIGIT_BIT) + 1)) {
+ if ((err = mp_grow(c, c->used + (b / MP_DIGIT_BIT) + 1)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* shift by as many digits in the bit count */
+ if (b >= MP_DIGIT_BIT) {
+ if ((err = mp_lshd(c, b / MP_DIGIT_BIT)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* shift any bit count < MP_DIGIT_BIT */
+ d = (mp_digit)(b % MP_DIGIT_BIT);
+ if (d != 0u) {
+ mp_digit *tmpc, shift, mask, r, rr;
+ int x;
+
+ /* bitmask for carries */
+ mask = ((mp_digit)1 << d) - (mp_digit)1;
+
+ /* shift for msbs */
+ shift = (mp_digit)MP_DIGIT_BIT - d;
+
+ /* alias */
+ tmpc = c->dp;
+
+ /* carry */
+ r = 0;
+ for (x = 0; x < c->used; x++) {
+ /* get the higher bits of the current word */
+ rr = (*tmpc >> shift) & mask;
+
+ /* shift the current word and OR in the carry */
+ *tmpc = ((*tmpc << d) | r) & MP_MASK;
+ ++tmpc;
+
+ /* set the carry to the carry bits of the current word */
+ r = rr;
+ }
+
+ /* set final carry */
+ if (r != 0u) {
+ c->dp[(c->used)++] = r;
+ }
+ }
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul_d.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul_d.c
new file mode 100644
index 0000000..b56dfa3
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mul_d.c
@@ -0,0 +1,61 @@
+#include "tommath_private.h"
+#ifdef BN_MP_MUL_D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* multiply by a digit */
+mp_err mp_mul_d(const mp_int *a, mp_digit b, mp_int *c)
+{
+ mp_digit u, *tmpa, *tmpc;
+ mp_word r;
+ mp_err err;
+ int ix, olduse;
+
+ /* make sure c is big enough to hold a*b */
+ if (c->alloc < (a->used + 1)) {
+ if ((err = mp_grow(c, a->used + 1)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* get the original destinations used count */
+ olduse = c->used;
+
+ /* set the sign */
+ c->sign = a->sign;
+
+ /* alias for a->dp [source] */
+ tmpa = a->dp;
+
+ /* alias for c->dp [dest] */
+ tmpc = c->dp;
+
+ /* zero carry */
+ u = 0;
+
+ /* compute columns */
+ for (ix = 0; ix < a->used; ix++) {
+ /* compute product and carry sum for this term */
+ r = (mp_word)u + ((mp_word)*tmpa++ * (mp_word)b);
+
+ /* mask off higher bits to get a single digit */
+ *tmpc++ = (mp_digit)(r & (mp_word)MP_MASK);
+
+ /* send carry into next iteration */
+ u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
+ }
+
+ /* store final carry [if any] and increment ix offset */
+ *tmpc++ = u;
+ ++ix;
+
+ /* now zero digits above the top */
+ MP_ZERO_DIGITS(tmpc, olduse - ix);
+
+ /* set used count */
+ c->used = a->used + 1;
+ mp_clamp(c);
+
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mulmod.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mulmod.c
new file mode 100644
index 0000000..160d162
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_mulmod.c
@@ -0,0 +1,25 @@
+#include "tommath_private.h"
+#ifdef BN_MP_MULMOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* d = a * b (mod c) */
+mp_err mp_mulmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d)
+{
+ mp_err err;
+ mp_int t;
+
+ if ((err = mp_init_size(&t, c->used)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_mul(a, b, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ err = mp_mod(&t, c, d);
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_neg.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_neg.c
new file mode 100644
index 0000000..264d900
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_neg.c
@@ -0,0 +1,24 @@
+#include "tommath_private.h"
+#ifdef BN_MP_NEG_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* b = -a */
+mp_err mp_neg(const mp_int *a, mp_int *b)
+{
+ mp_err err;
+ if (a != b) {
+ if ((err = mp_copy(a, b)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ if (!MP_IS_ZERO(b)) {
+ b->sign = (a->sign == MP_ZPOS) ? MP_NEG : MP_ZPOS;
+ } else {
+ b->sign = MP_ZPOS;
+ }
+
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_or.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_or.c
new file mode 100644
index 0000000..cdacbfb
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_or.c
@@ -0,0 +1,56 @@
+#include "tommath_private.h"
+#ifdef BN_MP_OR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* two complement or */
+mp_err mp_or(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ int used = MP_MAX(a->used, b->used) + 1, i;
+ mp_err err;
+ mp_digit ac = 1, bc = 1, cc = 1;
+ mp_sign csign = ((a->sign == MP_NEG) || (b->sign == MP_NEG)) ? MP_NEG : MP_ZPOS;
+
+ if (c->alloc < used) {
+ if ((err = mp_grow(c, used)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ for (i = 0; i < used; i++) {
+ mp_digit x, y;
+
+ /* convert to two complement if negative */
+ if (a->sign == MP_NEG) {
+ ac += (i >= a->used) ? MP_MASK : (~a->dp[i] & MP_MASK);
+ x = ac & MP_MASK;
+ ac >>= MP_DIGIT_BIT;
+ } else {
+ x = (i >= a->used) ? 0uL : a->dp[i];
+ }
+
+ /* convert to two complement if negative */
+ if (b->sign == MP_NEG) {
+ bc += (i >= b->used) ? MP_MASK : (~b->dp[i] & MP_MASK);
+ y = bc & MP_MASK;
+ bc >>= MP_DIGIT_BIT;
+ } else {
+ y = (i >= b->used) ? 0uL : b->dp[i];
+ }
+
+ c->dp[i] = x | y;
+
+ /* convert to to sign-magnitude if negative */
+ if (csign == MP_NEG) {
+ cc += ~c->dp[i] & MP_MASK;
+ c->dp[i] = cc & MP_MASK;
+ cc >>= MP_DIGIT_BIT;
+ }
+ }
+
+ c->used = used;
+ c->sign = csign;
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_pack.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_pack.c
new file mode 100644
index 0000000..6e00b6f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_pack.c
@@ -0,0 +1,69 @@
+#include "tommath_private.h"
+#ifdef BN_MP_PACK_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* based on gmp's mpz_export.
+ * see http://gmplib.org/manual/Integer-Import-and-Export.html
+ */
+mp_err mp_pack(void *rop, size_t maxcount, size_t *written, mp_order order, size_t size,
+ mp_endian endian, size_t nails, const mp_int *op)
+{
+ mp_err err;
+ size_t odd_nails, nail_bytes, i, j, count;
+ unsigned char odd_nail_mask;
+
+ mp_int t;
+
+ count = mp_pack_count(op, nails, size);
+
+ if (count > maxcount) {
+ return MP_BUF;
+ }
+
+ if ((err = mp_init_copy(&t, op)) != MP_OKAY) {
+ return err;
+ }
+
+ if (endian == MP_NATIVE_ENDIAN) {
+ MP_GET_ENDIANNESS(endian);
+ }
+
+ odd_nails = (nails % 8u);
+ odd_nail_mask = 0xff;
+ for (i = 0u; i < odd_nails; ++i) {
+ odd_nail_mask ^= (unsigned char)(1u << (7u - i));
+ }
+ nail_bytes = nails / 8u;
+
+ for (i = 0u; i < count; ++i) {
+ for (j = 0u; j < size; ++j) {
+ unsigned char *byte = (unsigned char *)rop +
+ (((order == MP_LSB_FIRST) ? i : ((count - 1u) - i)) * size) +
+ ((endian == MP_LITTLE_ENDIAN) ? j : ((size - 1u) - j));
+
+ if (j >= (size - nail_bytes)) {
+ *byte = 0;
+ continue;
+ }
+
+ *byte = (unsigned char)((j == ((size - nail_bytes) - 1u)) ? (t.dp[0] & odd_nail_mask) : (t.dp[0] & 0xFFuL));
+
+ if ((err = mp_div_2d(&t, (j == ((size - nail_bytes) - 1u)) ? (int)(8u - odd_nails) : 8, &t, NULL)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ }
+ }
+
+ if (written != NULL) {
+ *written = count;
+ }
+ err = MP_OKAY;
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_pack_count.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_pack_count.c
new file mode 100644
index 0000000..dfecdf9
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_pack_count.c
@@ -0,0 +1,12 @@
+#include "tommath_private.h"
+#ifdef BN_MP_PACK_COUNT_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+size_t mp_pack_count(const mp_int *a, size_t nails, size_t size)
+{
+ size_t bits = (size_t)mp_count_bits(a);
+ return ((bits / ((size * 8u) - nails)) + (((bits % ((size * 8u) - nails)) != 0u) ? 1u : 0u));
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_fermat.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_fermat.c
new file mode 100644
index 0000000..af3e884
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_fermat.c
@@ -0,0 +1,47 @@
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_FERMAT_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* performs one Fermat test.
+ *
+ * If "a" were prime then b**a == b (mod a) since the order of
+ * the multiplicative sub-group would be phi(a) = a-1. That means
+ * it would be the same as b**(a mod (a-1)) == b**1 == b (mod a).
+ *
+ * Sets result to 1 if the congruence holds, or zero otherwise.
+ */
+mp_err mp_prime_fermat(const mp_int *a, const mp_int *b, mp_bool *result)
+{
+ mp_int t;
+ mp_err err;
+
+ /* default to composite */
+ *result = MP_NO;
+
+ /* ensure b > 1 */
+ if (mp_cmp_d(b, 1uL) != MP_GT) {
+ return MP_VAL;
+ }
+
+ /* init t */
+ if ((err = mp_init(&t)) != MP_OKAY) {
+ return err;
+ }
+
+ /* compute t = b**a mod a */
+ if ((err = mp_exptmod(b, a, a, &t)) != MP_OKAY) {
+ goto LBL_T;
+ }
+
+ /* is it equal to b? */
+ if (mp_cmp(&t, b) == MP_EQ) {
+ *result = MP_YES;
+ }
+
+ err = MP_OKAY;
+LBL_T:
+ mp_clear(&t);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_frobenius_underwood.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_frobenius_underwood.c
new file mode 100644
index 0000000..253e8d5
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_frobenius_underwood.c
@@ -0,0 +1,132 @@
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_FROBENIUS_UNDERWOOD_C
+
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/*
+ * See file bn_mp_prime_is_prime.c or the documentation in doc/bn.tex for the details
+ */
+#ifndef LTM_USE_ONLY_MR
+
+#ifdef MP_8BIT
+/*
+ * floor of positive solution of
+ * (2^16)-1 = (a+4)*(2*a+5)
+ * TODO: Both values are smaller than N^(1/4), would have to use a bigint
+ * for a instead but any a biger than about 120 are already so rare that
+ * it is possible to ignore them and still get enough pseudoprimes.
+ * But it is still a restriction of the set of available pseudoprimes
+ * which makes this implementation less secure if used stand-alone.
+ */
+#define LTM_FROBENIUS_UNDERWOOD_A 177
+#else
+#define LTM_FROBENIUS_UNDERWOOD_A 32764
+#endif
+mp_err mp_prime_frobenius_underwood(const mp_int *N, mp_bool *result)
+{
+ mp_int T1z, T2z, Np1z, sz, tz;
+
+ int a, ap2, length, i, j;
+ mp_err err;
+
+ *result = MP_NO;
+
+ if ((err = mp_init_multi(&T1z, &T2z, &Np1z, &sz, &tz, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ for (a = 0; a < LTM_FROBENIUS_UNDERWOOD_A; a++) {
+ /* TODO: That's ugly! No, really, it is! */
+ if ((a==2) || (a==4) || (a==7) || (a==8) || (a==10) ||
+ (a==14) || (a==18) || (a==23) || (a==26) || (a==28)) {
+ continue;
+ }
+ /* (32764^2 - 4) < 2^31, no bigint for >MP_8BIT needed) */
+ mp_set_u32(&T1z, (uint32_t)a);
+
+ if ((err = mp_sqr(&T1z, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+
+ if ((err = mp_sub_d(&T1z, 4uL, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+
+ if ((err = mp_kronecker(&T1z, N, &j)) != MP_OKAY) goto LBL_FU_ERR;
+
+ if (j == -1) {
+ break;
+ }
+
+ if (j == 0) {
+ /* composite */
+ goto LBL_FU_ERR;
+ }
+ }
+ /* Tell it a composite and set return value accordingly */
+ if (a >= LTM_FROBENIUS_UNDERWOOD_A) {
+ err = MP_ITER;
+ goto LBL_FU_ERR;
+ }
+ /* Composite if N and (a+4)*(2*a+5) are not coprime */
+ mp_set_u32(&T1z, (uint32_t)((a+4)*((2*a)+5)));
+
+ if ((err = mp_gcd(N, &T1z, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+
+ if (!((T1z.used == 1) && (T1z.dp[0] == 1u))) goto LBL_FU_ERR;
+
+ ap2 = a + 2;
+ if ((err = mp_add_d(N, 1uL, &Np1z)) != MP_OKAY) goto LBL_FU_ERR;
+
+ mp_set(&sz, 1uL);
+ mp_set(&tz, 2uL);
+ length = mp_count_bits(&Np1z);
+
+ for (i = length - 2; i >= 0; i--) {
+ /*
+ * temp = (sz*(a*sz+2*tz))%N;
+ * tz = ((tz-sz)*(tz+sz))%N;
+ * sz = temp;
+ */
+ if ((err = mp_mul_2(&tz, &T2z)) != MP_OKAY) goto LBL_FU_ERR;
+
+ /* a = 0 at about 50% of the cases (non-square and odd input) */
+ if (a != 0) {
+ if ((err = mp_mul_d(&sz, (mp_digit)a, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_add(&T1z, &T2z, &T2z)) != MP_OKAY) goto LBL_FU_ERR;
+ }
+
+ if ((err = mp_mul(&T2z, &sz, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_sub(&tz, &sz, &T2z)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_add(&sz, &tz, &sz)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_mul(&sz, &T2z, &tz)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_mod(&tz, N, &tz)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_mod(&T1z, N, &sz)) != MP_OKAY) goto LBL_FU_ERR;
+ if (s_mp_get_bit(&Np1z, (unsigned int)i) == MP_YES) {
+ /*
+ * temp = (a+2) * sz + tz
+ * tz = 2 * tz - sz
+ * sz = temp
+ */
+ if (a == 0) {
+ if ((err = mp_mul_2(&sz, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+ } else {
+ if ((err = mp_mul_d(&sz, (mp_digit)ap2, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+ }
+ if ((err = mp_add(&T1z, &tz, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_mul_2(&tz, &T2z)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_sub(&T2z, &sz, &tz)) != MP_OKAY) goto LBL_FU_ERR;
+ mp_exch(&sz, &T1z);
+ }
+ }
+
+ mp_set_u32(&T1z, (uint32_t)((2 * a) + 5));
+ if ((err = mp_mod(&T1z, N, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+ if (MP_IS_ZERO(&sz) && (mp_cmp(&tz, &T1z) == MP_EQ)) {
+ *result = MP_YES;
+ }
+
+LBL_FU_ERR:
+ mp_clear_multi(&tz, &sz, &Np1z, &T2z, &T1z, NULL);
+ return err;
+}
+
+#endif
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_is_prime.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_is_prime.c
new file mode 100644
index 0000000..7f9fc0b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_is_prime.c
@@ -0,0 +1,314 @@
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_IS_PRIME_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* portable integer log of two with small footprint */
+static unsigned int s_floor_ilog2(int value)
+{
+ unsigned int r = 0;
+ while ((value >>= 1) != 0) {
+ r++;
+ }
+ return r;
+}
+
+
+mp_err mp_prime_is_prime(const mp_int *a, int t, mp_bool *result)
+{
+ mp_int b;
+ int ix, p_max = 0, size_a, len;
+ mp_bool res;
+ mp_err err;
+ unsigned int fips_rand, mask;
+
+ /* default to no */
+ *result = MP_NO;
+
+ /* Some shortcuts */
+ /* N > 3 */
+ if (a->used == 1) {
+ if ((a->dp[0] == 0u) || (a->dp[0] == 1u)) {
+ *result = MP_NO;
+ return MP_OKAY;
+ }
+ if (a->dp[0] == 2u) {
+ *result = MP_YES;
+ return MP_OKAY;
+ }
+ }
+
+ /* N must be odd */
+ if (MP_IS_EVEN(a)) {
+ return MP_OKAY;
+ }
+ /* N is not a perfect square: floor(sqrt(N))^2 != N */
+ if ((err = mp_is_square(a, &res)) != MP_OKAY) {
+ return err;
+ }
+ if (res != MP_NO) {
+ return MP_OKAY;
+ }
+
+ /* is the input equal to one of the primes in the table? */
+ for (ix = 0; ix < PRIVATE_MP_PRIME_TAB_SIZE; ix++) {
+ if (mp_cmp_d(a, s_mp_prime_tab[ix]) == MP_EQ) {
+ *result = MP_YES;
+ return MP_OKAY;
+ }
+ }
+#ifdef MP_8BIT
+ /* The search in the loop above was exhaustive in this case */
+ if ((a->used == 1) && (PRIVATE_MP_PRIME_TAB_SIZE >= 31)) {
+ return MP_OKAY;
+ }
+#endif
+
+ /* first perform trial division */
+ if ((err = s_mp_prime_is_divisible(a, &res)) != MP_OKAY) {
+ return err;
+ }
+
+ /* return if it was trivially divisible */
+ if (res == MP_YES) {
+ return MP_OKAY;
+ }
+
+ /*
+ Run the Miller-Rabin test with base 2 for the BPSW test.
+ */
+ if ((err = mp_init_set(&b, 2uL)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_prime_miller_rabin(a, &b, &res)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ if (res == MP_NO) {
+ goto LBL_B;
+ }
+ /*
+ Rumours have it that Mathematica does a second M-R test with base 3.
+ Other rumours have it that their strong L-S test is slightly different.
+ It does not hurt, though, beside a bit of extra runtime.
+ */
+ b.dp[0]++;
+ if ((err = mp_prime_miller_rabin(a, &b, &res)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ if (res == MP_NO) {
+ goto LBL_B;
+ }
+
+ /*
+ * Both, the Frobenius-Underwood test and the the Lucas-Selfridge test are quite
+ * slow so if speed is an issue, define LTM_USE_ONLY_MR to use M-R tests with
+ * bases 2, 3 and t random bases.
+ */
+#ifndef LTM_USE_ONLY_MR
+ if (t >= 0) {
+ /*
+ * Use a Frobenius-Underwood test instead of the Lucas-Selfridge test for
+ * MP_8BIT (It is unknown if the Lucas-Selfridge test works with 16-bit
+ * integers but the necesssary analysis is on the todo-list).
+ */
+#if defined (MP_8BIT) || defined (LTM_USE_FROBENIUS_TEST)
+ err = mp_prime_frobenius_underwood(a, &res);
+ if ((err != MP_OKAY) && (err != MP_ITER)) {
+ goto LBL_B;
+ }
+ if (res == MP_NO) {
+ goto LBL_B;
+ }
+#else
+ if ((err = mp_prime_strong_lucas_selfridge(a, &res)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ if (res == MP_NO) {
+ goto LBL_B;
+ }
+#endif
+ }
+#endif
+
+ /* run at least one Miller-Rabin test with a random base */
+ if (t == 0) {
+ t = 1;
+ }
+
+ /*
+ Only recommended if the input range is known to be < 3317044064679887385961981
+
+ It uses the bases necessary for a deterministic M-R test if the input is
+ smaller than 3317044064679887385961981
+ The caller has to check the size.
+ TODO: can be made a bit finer grained but comparing is not free.
+ */
+ if (t < 0) {
+ /*
+ Sorenson, Jonathan; Webster, Jonathan (2015).
+ "Strong Pseudoprimes to Twelve Prime Bases".
+ */
+ /* 0x437ae92817f9fc85b7e5 = 318665857834031151167461 */
+ if ((err = mp_read_radix(&b, "437ae92817f9fc85b7e5", 16)) != MP_OKAY) {
+ goto LBL_B;
+ }
+
+ if (mp_cmp(a, &b) == MP_LT) {
+ p_max = 12;
+ } else {
+ /* 0x2be6951adc5b22410a5fd = 3317044064679887385961981 */
+ if ((err = mp_read_radix(&b, "2be6951adc5b22410a5fd", 16)) != MP_OKAY) {
+ goto LBL_B;
+ }
+
+ if (mp_cmp(a, &b) == MP_LT) {
+ p_max = 13;
+ } else {
+ err = MP_VAL;
+ goto LBL_B;
+ }
+ }
+
+ /* we did bases 2 and 3 already, skip them */
+ for (ix = 2; ix < p_max; ix++) {
+ mp_set(&b, s_mp_prime_tab[ix]);
+ if ((err = mp_prime_miller_rabin(a, &b, &res)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ if (res == MP_NO) {
+ goto LBL_B;
+ }
+ }
+ }
+ /*
+ Do "t" M-R tests with random bases between 3 and "a".
+ See Fips 186.4 p. 126ff
+ */
+ else if (t > 0) {
+ /*
+ * The mp_digit's have a defined bit-size but the size of the
+ * array a.dp is a simple 'int' and this library can not assume full
+ * compliance to the current C-standard (ISO/IEC 9899:2011) because
+ * it gets used for small embeded processors, too. Some of those MCUs
+ * have compilers that one cannot call standard compliant by any means.
+ * Hence the ugly type-fiddling in the following code.
+ */
+ size_a = mp_count_bits(a);
+ mask = (1u << s_floor_ilog2(size_a)) - 1u;
+ /*
+ Assuming the General Rieman hypothesis (never thought to write that in a
+ comment) the upper bound can be lowered to 2*(log a)^2.
+ E. Bach, "Explicit bounds for primality testing and related problems,"
+ Math. Comp. 55 (1990), 355-380.
+
+ size_a = (size_a/10) * 7;
+ len = 2 * (size_a * size_a);
+
+ E.g.: a number of size 2^2048 would be reduced to the upper limit
+
+ floor(2048/10)*7 = 1428
+ 2 * 1428^2 = 4078368
+
+ (would have been ~4030331.9962 with floats and natural log instead)
+ That number is smaller than 2^28, the default bit-size of mp_digit.
+ */
+
+ /*
+ How many tests, you might ask? Dana Jacobsen of Math::Prime::Util fame
+ does exactly 1. In words: one. Look at the end of _GMP_is_prime() in
+ Math-Prime-Util-GMP-0.50/primality.c if you do not believe it.
+
+ The function mp_rand() goes to some length to use a cryptographically
+ good PRNG. That also means that the chance to always get the same base
+ in the loop is non-zero, although very low.
+ If the BPSW test and/or the addtional Frobenious test have been
+ performed instead of just the Miller-Rabin test with the bases 2 and 3,
+ a single extra test should suffice, so such a very unlikely event
+ will not do much harm.
+
+ To preemptivly answer the dangling question: no, a witness does not
+ need to be prime.
+ */
+ for (ix = 0; ix < t; ix++) {
+ /* mp_rand() guarantees the first digit to be non-zero */
+ if ((err = mp_rand(&b, 1)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ /*
+ * Reduce digit before casting because mp_digit might be bigger than
+ * an unsigned int and "mask" on the other side is most probably not.
+ */
+ fips_rand = (unsigned int)(b.dp[0] & (mp_digit) mask);
+#ifdef MP_8BIT
+ /*
+ * One 8-bit digit is too small, so concatenate two if the size of
+ * unsigned int allows for it.
+ */
+ if ((MP_SIZEOF_BITS(unsigned int)/2) >= MP_SIZEOF_BITS(mp_digit)) {
+ if ((err = mp_rand(&b, 1)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ fips_rand <<= MP_SIZEOF_BITS(mp_digit);
+ fips_rand |= (unsigned int) b.dp[0];
+ fips_rand &= mask;
+ }
+#endif
+ if (fips_rand > (unsigned int)(INT_MAX - MP_DIGIT_BIT)) {
+ len = INT_MAX / MP_DIGIT_BIT;
+ } else {
+ len = (((int)fips_rand + MP_DIGIT_BIT) / MP_DIGIT_BIT);
+ }
+ /* Unlikely. */
+ if (len < 0) {
+ ix--;
+ continue;
+ }
+ /*
+ * As mentioned above, one 8-bit digit is too small and
+ * although it can only happen in the unlikely case that
+ * an "unsigned int" is smaller than 16 bit a simple test
+ * is cheap and the correction even cheaper.
+ */
+#ifdef MP_8BIT
+ /* All "a" < 2^8 have been caught before */
+ if (len == 1) {
+ len++;
+ }
+#endif
+ if ((err = mp_rand(&b, len)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ /*
+ * That number might got too big and the witness has to be
+ * smaller than "a"
+ */
+ len = mp_count_bits(&b);
+ if (len >= size_a) {
+ len = (len - size_a) + 1;
+ if ((err = mp_div_2d(&b, len, &b, NULL)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ }
+ /* Although the chance for b <= 3 is miniscule, try again. */
+ if (mp_cmp_d(&b, 3uL) != MP_GT) {
+ ix--;
+ continue;
+ }
+ if ((err = mp_prime_miller_rabin(a, &b, &res)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ if (res == MP_NO) {
+ goto LBL_B;
+ }
+ }
+ }
+
+ /* passed the test */
+ *result = MP_YES;
+LBL_B:
+ mp_clear(&b);
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_miller_rabin.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_miller_rabin.c
new file mode 100644
index 0000000..96470db
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_miller_rabin.c
@@ -0,0 +1,91 @@
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_MILLER_RABIN_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Miller-Rabin test of "a" to the base of "b" as described in
+ * HAC pp. 139 Algorithm 4.24
+ *
+ * Sets result to 0 if definitely composite or 1 if probably prime.
+ * Randomly the chance of error is no more than 1/4 and often
+ * very much lower.
+ */
+mp_err mp_prime_miller_rabin(const mp_int *a, const mp_int *b, mp_bool *result)
+{
+ mp_int n1, y, r;
+ mp_err err;
+ int s, j;
+
+ /* default */
+ *result = MP_NO;
+
+ /* ensure b > 1 */
+ if (mp_cmp_d(b, 1uL) != MP_GT) {
+ return MP_VAL;
+ }
+
+ /* get n1 = a - 1 */
+ if ((err = mp_init_copy(&n1, a)) != MP_OKAY) {
+ return err;
+ }
+ if ((err = mp_sub_d(&n1, 1uL, &n1)) != MP_OKAY) {
+ goto LBL_N1;
+ }
+
+ /* set 2**s * r = n1 */
+ if ((err = mp_init_copy(&r, &n1)) != MP_OKAY) {
+ goto LBL_N1;
+ }
+
+ /* count the number of least significant bits
+ * which are zero
+ */
+ s = mp_cnt_lsb(&r);
+
+ /* now divide n - 1 by 2**s */
+ if ((err = mp_div_2d(&r, s, &r, NULL)) != MP_OKAY) {
+ goto LBL_R;
+ }
+
+ /* compute y = b**r mod a */
+ if ((err = mp_init(&y)) != MP_OKAY) {
+ goto LBL_R;
+ }
+ if ((err = mp_exptmod(b, &r, a, &y)) != MP_OKAY) {
+ goto LBL_Y;
+ }
+
+ /* if y != 1 and y != n1 do */
+ if ((mp_cmp_d(&y, 1uL) != MP_EQ) && (mp_cmp(&y, &n1) != MP_EQ)) {
+ j = 1;
+ /* while j <= s-1 and y != n1 */
+ while ((j <= (s - 1)) && (mp_cmp(&y, &n1) != MP_EQ)) {
+ if ((err = mp_sqrmod(&y, a, &y)) != MP_OKAY) {
+ goto LBL_Y;
+ }
+
+ /* if y == 1 then composite */
+ if (mp_cmp_d(&y, 1uL) == MP_EQ) {
+ goto LBL_Y;
+ }
+
+ ++j;
+ }
+
+ /* if y != n1 then composite */
+ if (mp_cmp(&y, &n1) != MP_EQ) {
+ goto LBL_Y;
+ }
+ }
+
+ /* probably prime now */
+ *result = MP_YES;
+LBL_Y:
+ mp_clear(&y);
+LBL_R:
+ mp_clear(&r);
+LBL_N1:
+ mp_clear(&n1);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_next_prime.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_next_prime.c
new file mode 100644
index 0000000..d656565
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_next_prime.c
@@ -0,0 +1,132 @@
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_NEXT_PRIME_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* finds the next prime after the number "a" using "t" trials
+ * of Miller-Rabin.
+ *
+ * bbs_style = 1 means the prime must be congruent to 3 mod 4
+ */
+mp_err mp_prime_next_prime(mp_int *a, int t, int bbs_style)
+{
+ int x, y;
+ mp_ord cmp;
+ mp_err err;
+ mp_bool res = MP_NO;
+ mp_digit res_tab[PRIVATE_MP_PRIME_TAB_SIZE], step, kstep;
+ mp_int b;
+
+ /* force positive */
+ a->sign = MP_ZPOS;
+
+ /* simple algo if a is less than the largest prime in the table */
+ if (mp_cmp_d(a, s_mp_prime_tab[PRIVATE_MP_PRIME_TAB_SIZE-1]) == MP_LT) {
+ /* find which prime it is bigger than "a" */
+ for (x = 0; x < PRIVATE_MP_PRIME_TAB_SIZE; x++) {
+ cmp = mp_cmp_d(a, s_mp_prime_tab[x]);
+ if (cmp == MP_EQ) {
+ continue;
+ }
+ if (cmp != MP_GT) {
+ if ((bbs_style == 1) && ((s_mp_prime_tab[x] & 3u) != 3u)) {
+ /* try again until we get a prime congruent to 3 mod 4 */
+ continue;
+ } else {
+ mp_set(a, s_mp_prime_tab[x]);
+ return MP_OKAY;
+ }
+ }
+ }
+ /* fall through to the sieve */
+ }
+
+ /* generate a prime congruent to 3 mod 4 or 1/3 mod 4? */
+ if (bbs_style == 1) {
+ kstep = 4;
+ } else {
+ kstep = 2;
+ }
+
+ /* at this point we will use a combination of a sieve and Miller-Rabin */
+
+ if (bbs_style == 1) {
+ /* if a mod 4 != 3 subtract the correct value to make it so */
+ if ((a->dp[0] & 3u) != 3u) {
+ if ((err = mp_sub_d(a, (a->dp[0] & 3u) + 1u, a)) != MP_OKAY) {
+ return err;
+ }
+ }
+ } else {
+ if (MP_IS_EVEN(a)) {
+ /* force odd */
+ if ((err = mp_sub_d(a, 1uL, a)) != MP_OKAY) {
+ return err;
+ }
+ }
+ }
+
+ /* generate the restable */
+ for (x = 1; x < PRIVATE_MP_PRIME_TAB_SIZE; x++) {
+ if ((err = mp_mod_d(a, s_mp_prime_tab[x], res_tab + x)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* init temp used for Miller-Rabin Testing */
+ if ((err = mp_init(&b)) != MP_OKAY) {
+ return err;
+ }
+
+ for (;;) {
+ /* skip to the next non-trivially divisible candidate */
+ step = 0;
+ do {
+ /* y == 1 if any residue was zero [e.g. cannot be prime] */
+ y = 0;
+
+ /* increase step to next candidate */
+ step += kstep;
+
+ /* compute the new residue without using division */
+ for (x = 1; x < PRIVATE_MP_PRIME_TAB_SIZE; x++) {
+ /* add the step to each residue */
+ res_tab[x] += kstep;
+
+ /* subtract the modulus [instead of using division] */
+ if (res_tab[x] >= s_mp_prime_tab[x]) {
+ res_tab[x] -= s_mp_prime_tab[x];
+ }
+
+ /* set flag if zero */
+ if (res_tab[x] == 0u) {
+ y = 1;
+ }
+ }
+ } while ((y == 1) && (step < (((mp_digit)1 << MP_DIGIT_BIT) - kstep)));
+
+ /* add the step */
+ if ((err = mp_add_d(a, step, a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ /* if didn't pass sieve and step == MP_MAX then skip test */
+ if ((y == 1) && (step >= (((mp_digit)1 << MP_DIGIT_BIT) - kstep))) {
+ continue;
+ }
+
+ if ((err = mp_prime_is_prime(a, t, &res)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (res == MP_YES) {
+ break;
+ }
+ }
+
+ err = MP_OKAY;
+LBL_ERR:
+ mp_clear(&b);
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_rabin_miller_trials.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_rabin_miller_trials.c
new file mode 100644
index 0000000..8bbaf6c
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_rabin_miller_trials.c
@@ -0,0 +1,47 @@
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_RABIN_MILLER_TRIALS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+static const struct {
+ int k, t;
+} sizes[] = {
+ { 80, -1 }, /* Use deterministic algorithm for size <= 80 bits */
+ { 81, 37 }, /* max. error = 2^(-96)*/
+ { 96, 32 }, /* max. error = 2^(-96)*/
+ { 128, 40 }, /* max. error = 2^(-112)*/
+ { 160, 35 }, /* max. error = 2^(-112)*/
+ { 256, 27 }, /* max. error = 2^(-128)*/
+ { 384, 16 }, /* max. error = 2^(-128)*/
+ { 512, 18 }, /* max. error = 2^(-160)*/
+ { 768, 11 }, /* max. error = 2^(-160)*/
+ { 896, 10 }, /* max. error = 2^(-160)*/
+ { 1024, 12 }, /* max. error = 2^(-192)*/
+ { 1536, 8 }, /* max. error = 2^(-192)*/
+ { 2048, 6 }, /* max. error = 2^(-192)*/
+ { 3072, 4 }, /* max. error = 2^(-192)*/
+ { 4096, 5 }, /* max. error = 2^(-256)*/
+ { 5120, 4 }, /* max. error = 2^(-256)*/
+ { 6144, 4 }, /* max. error = 2^(-256)*/
+ { 8192, 3 }, /* max. error = 2^(-256)*/
+ { 9216, 3 }, /* max. error = 2^(-256)*/
+ { 10240, 2 } /* For bigger keysizes use always at least 2 Rounds */
+};
+
+/* returns # of RM trials required for a given bit size */
+int mp_prime_rabin_miller_trials(int size)
+{
+ int x;
+
+ for (x = 0; x < (int)(sizeof(sizes)/(sizeof(sizes[0]))); x++) {
+ if (sizes[x].k == size) {
+ return sizes[x].t;
+ } else if (sizes[x].k > size) {
+ return (x == 0) ? sizes[0].t : sizes[x - 1].t;
+ }
+ }
+ return sizes[x-1].t;
+}
+
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_rand.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_rand.c
new file mode 100644
index 0000000..4530e9a
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_rand.c
@@ -0,0 +1,141 @@
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_RAND_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* makes a truly random prime of a given size (bits),
+ *
+ * Flags are as follows:
+ *
+ * MP_PRIME_BBS - make prime congruent to 3 mod 4
+ * MP_PRIME_SAFE - make sure (p-1)/2 is prime as well (implies MP_PRIME_BBS)
+ * MP_PRIME_2MSB_ON - make the 2nd highest bit one
+ *
+ * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can
+ * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself
+ * so it can be NULL
+ *
+ */
+
+/* This is possibly the mother of all prime generation functions, muahahahahaha! */
+mp_err s_mp_prime_random_ex(mp_int *a, int t, int size, int flags, private_mp_prime_callback cb, void *dat)
+{
+ unsigned char *tmp, maskAND, maskOR_msb, maskOR_lsb;
+ int bsize, maskOR_msb_offset;
+ mp_bool res;
+ mp_err err;
+
+ /* sanity check the input */
+ if ((size <= 1) || (t <= 0)) {
+ return MP_VAL;
+ }
+
+ /* MP_PRIME_SAFE implies MP_PRIME_BBS */
+ if ((flags & MP_PRIME_SAFE) != 0) {
+ flags |= MP_PRIME_BBS;
+ }
+
+ /* calc the byte size */
+ bsize = (size>>3) + ((size&7)?1:0);
+
+ /* we need a buffer of bsize bytes */
+ tmp = (unsigned char *) MP_MALLOC((size_t)bsize);
+ if (tmp == NULL) {
+ return MP_MEM;
+ }
+
+ /* calc the maskAND value for the MSbyte*/
+ maskAND = ((size&7) == 0) ? 0xFFu : (unsigned char)(0xFFu >> (8 - (size & 7)));
+
+ /* calc the maskOR_msb */
+ maskOR_msb = 0;
+ maskOR_msb_offset = ((size & 7) == 1) ? 1 : 0;
+ if ((flags & MP_PRIME_2MSB_ON) != 0) {
+ maskOR_msb |= (unsigned char)(0x80 >> ((9 - size) & 7));
+ }
+
+ /* get the maskOR_lsb */
+ maskOR_lsb = 1u;
+ if ((flags & MP_PRIME_BBS) != 0) {
+ maskOR_lsb |= 3u;
+ }
+
+ do {
+ /* read the bytes */
+ if (cb(tmp, bsize, dat) != bsize) {
+ err = MP_VAL;
+ goto error;
+ }
+
+ /* work over the MSbyte */
+ tmp[0] &= maskAND;
+ tmp[0] |= (unsigned char)(1 << ((size - 1) & 7));
+
+ /* mix in the maskORs */
+ tmp[maskOR_msb_offset] |= maskOR_msb;
+ tmp[bsize-1] |= maskOR_lsb;
+
+ /* read it in */
+ /* TODO: casting only for now until all lengths have been changed to the type "size_t"*/
+ if ((err = mp_from_ubin(a, tmp, (size_t)bsize)) != MP_OKAY) {
+ goto error;
+ }
+
+ /* is it prime? */
+ if ((err = mp_prime_is_prime(a, t, &res)) != MP_OKAY) {
+ goto error;
+ }
+ if (res == MP_NO) {
+ continue;
+ }
+
+ if ((flags & MP_PRIME_SAFE) != 0) {
+ /* see if (a-1)/2 is prime */
+ if ((err = mp_sub_d(a, 1uL, a)) != MP_OKAY) {
+ goto error;
+ }
+ if ((err = mp_div_2(a, a)) != MP_OKAY) {
+ goto error;
+ }
+
+ /* is it prime? */
+ if ((err = mp_prime_is_prime(a, t, &res)) != MP_OKAY) {
+ goto error;
+ }
+ }
+ } while (res == MP_NO);
+
+ if ((flags & MP_PRIME_SAFE) != 0) {
+ /* restore a to the original value */
+ if ((err = mp_mul_2(a, a)) != MP_OKAY) {
+ goto error;
+ }
+ if ((err = mp_add_d(a, 1uL, a)) != MP_OKAY) {
+ goto error;
+ }
+ }
+
+ err = MP_OKAY;
+error:
+ MP_FREE_BUFFER(tmp, (size_t)bsize);
+ return err;
+}
+
+static int s_mp_rand_cb(unsigned char *dst, int len, void *dat)
+{
+ (void)dat;
+ if (len <= 0) {
+ return len;
+ }
+ if (s_mp_rand_source(dst, (size_t)len) != MP_OKAY) {
+ return 0;
+ }
+ return len;
+}
+
+mp_err mp_prime_rand(mp_int *a, int t, int size, int flags)
+{
+ return s_mp_prime_random_ex(a, t, size, flags, s_mp_rand_cb, NULL);
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_strong_lucas_selfridge.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_strong_lucas_selfridge.c
new file mode 100644
index 0000000..b50bbcd
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_prime_strong_lucas_selfridge.c
@@ -0,0 +1,289 @@
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_STRONG_LUCAS_SELFRIDGE_C
+
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/*
+ * See file bn_mp_prime_is_prime.c or the documentation in doc/bn.tex for the details
+ */
+#ifndef LTM_USE_ONLY_MR
+
+/*
+ * 8-bit is just too small. You can try the Frobenius test
+ * but that frobenius test can fail, too, for the same reason.
+ */
+#ifndef MP_8BIT
+
+/*
+ * multiply bigint a with int d and put the result in c
+ * Like mp_mul_d() but with a signed long as the small input
+ */
+static mp_err s_mp_mul_si(const mp_int *a, int32_t d, mp_int *c)
+{
+ mp_int t;
+ mp_err err;
+
+ if ((err = mp_init(&t)) != MP_OKAY) {
+ return err;
+ }
+
+ /*
+ * mp_digit might be smaller than a long, which excludes
+ * the use of mp_mul_d() here.
+ */
+ mp_set_i32(&t, d);
+ err = mp_mul(a, &t, c);
+ mp_clear(&t);
+ return err;
+}
+/*
+ Strong Lucas-Selfridge test.
+ returns MP_YES if it is a strong L-S prime, MP_NO if it is composite
+
+ Code ported from Thomas Ray Nicely's implementation of the BPSW test
+ at http://www.trnicely.net/misc/bpsw.html
+
+ Freeware copyright (C) 2016 Thomas R. Nicely <http://www.trnicely.net>.
+ Released into the public domain by the author, who disclaims any legal
+ liability arising from its use
+
+ The multi-line comments are made by Thomas R. Nicely and are copied verbatim.
+ Additional comments marked "CZ" (without the quotes) are by the code-portist.
+
+ (If that name sounds familiar, he is the guy who found the fdiv bug in the
+ Pentium (P5x, I think) Intel processor)
+*/
+mp_err mp_prime_strong_lucas_selfridge(const mp_int *a, mp_bool *result)
+{
+ /* CZ TODO: choose better variable names! */
+ mp_int Dz, gcd, Np1, Uz, Vz, U2mz, V2mz, Qmz, Q2mz, Qkdz, T1z, T2z, T3z, T4z, Q2kdz;
+ /* CZ TODO: Some of them need the full 32 bit, hence the (temporary) exclusion of MP_8BIT */
+ int32_t D, Ds, J, sign, P, Q, r, s, u, Nbits;
+ mp_err err;
+ mp_bool oddness;
+
+ *result = MP_NO;
+ /*
+ Find the first element D in the sequence {5, -7, 9, -11, 13, ...}
+ such that Jacobi(D,N) = -1 (Selfridge's algorithm). Theory
+ indicates that, if N is not a perfect square, D will "nearly
+ always" be "small." Just in case, an overflow trap for D is
+ included.
+ */
+
+ if ((err = mp_init_multi(&Dz, &gcd, &Np1, &Uz, &Vz, &U2mz, &V2mz, &Qmz, &Q2mz, &Qkdz, &T1z, &T2z, &T3z, &T4z, &Q2kdz,
+ NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ D = 5;
+ sign = 1;
+
+ for (;;) {
+ Ds = sign * D;
+ sign = -sign;
+ mp_set_u32(&Dz, (uint32_t)D);
+ if ((err = mp_gcd(a, &Dz, &gcd)) != MP_OKAY) goto LBL_LS_ERR;
+
+ /* if 1 < GCD < N then N is composite with factor "D", and
+ Jacobi(D,N) is technically undefined (but often returned
+ as zero). */
+ if ((mp_cmp_d(&gcd, 1uL) == MP_GT) && (mp_cmp(&gcd, a) == MP_LT)) {
+ goto LBL_LS_ERR;
+ }
+ if (Ds < 0) {
+ Dz.sign = MP_NEG;
+ }
+ if ((err = mp_kronecker(&Dz, a, &J)) != MP_OKAY) goto LBL_LS_ERR;
+
+ if (J == -1) {
+ break;
+ }
+ D += 2;
+
+ if (D > (INT_MAX - 2)) {
+ err = MP_VAL;
+ goto LBL_LS_ERR;
+ }
+ }
+
+
+
+ P = 1; /* Selfridge's choice */
+ Q = (1 - Ds) / 4; /* Required so D = P*P - 4*Q */
+
+ /* NOTE: The conditions (a) N does not divide Q, and
+ (b) D is square-free or not a perfect square, are included by
+ some authors; e.g., "Prime numbers and computer methods for
+ factorization," Hans Riesel (2nd ed., 1994, Birkhauser, Boston),
+ p. 130. For this particular application of Lucas sequences,
+ these conditions were found to be immaterial. */
+
+ /* Now calculate N - Jacobi(D,N) = N + 1 (even), and calculate the
+ odd positive integer d and positive integer s for which
+ N + 1 = 2^s*d (similar to the step for N - 1 in Miller's test).
+ The strong Lucas-Selfridge test then returns N as a strong
+ Lucas probable prime (slprp) if any of the following
+ conditions is met: U_d=0, V_d=0, V_2d=0, V_4d=0, V_8d=0,
+ V_16d=0, ..., etc., ending with V_{2^(s-1)*d}=V_{(N+1)/2}=0
+ (all equalities mod N). Thus d is the highest index of U that
+ must be computed (since V_2m is independent of U), compared
+ to U_{N+1} for the standard Lucas-Selfridge test; and no
+ index of V beyond (N+1)/2 is required, just as in the
+ standard Lucas-Selfridge test. However, the quantity Q^d must
+ be computed for use (if necessary) in the latter stages of
+ the test. The result is that the strong Lucas-Selfridge test
+ has a running time only slightly greater (order of 10 %) than
+ that of the standard Lucas-Selfridge test, while producing
+ only (roughly) 30 % as many pseudoprimes (and every strong
+ Lucas pseudoprime is also a standard Lucas pseudoprime). Thus
+ the evidence indicates that the strong Lucas-Selfridge test is
+ more effective than the standard Lucas-Selfridge test, and a
+ Baillie-PSW test based on the strong Lucas-Selfridge test
+ should be more reliable. */
+
+ if ((err = mp_add_d(a, 1uL, &Np1)) != MP_OKAY) goto LBL_LS_ERR;
+ s = mp_cnt_lsb(&Np1);
+
+ /* CZ
+ * This should round towards zero because
+ * Thomas R. Nicely used GMP's mpz_tdiv_q_2exp()
+ * and mp_div_2d() is equivalent. Additionally:
+ * dividing an even number by two does not produce
+ * any leftovers.
+ */
+ if ((err = mp_div_2d(&Np1, s, &Dz, NULL)) != MP_OKAY) goto LBL_LS_ERR;
+ /* We must now compute U_d and V_d. Since d is odd, the accumulated
+ values U and V are initialized to U_1 and V_1 (if the target
+ index were even, U and V would be initialized instead to U_0=0
+ and V_0=2). The values of U_2m and V_2m are also initialized to
+ U_1 and V_1; the FOR loop calculates in succession U_2 and V_2,
+ U_4 and V_4, U_8 and V_8, etc. If the corresponding bits
+ (1, 2, 3, ...) of t are on (the zero bit having been accounted
+ for in the initialization of U and V), these values are then
+ combined with the previous totals for U and V, using the
+ composition formulas for addition of indices. */
+
+ mp_set(&Uz, 1uL); /* U=U_1 */
+ mp_set(&Vz, (mp_digit)P); /* V=V_1 */
+ mp_set(&U2mz, 1uL); /* U_1 */
+ mp_set(&V2mz, (mp_digit)P); /* V_1 */
+
+ mp_set_i32(&Qmz, Q);
+ if ((err = mp_mul_2(&Qmz, &Q2mz)) != MP_OKAY) goto LBL_LS_ERR;
+ /* Initializes calculation of Q^d */
+ mp_set_i32(&Qkdz, Q);
+
+ Nbits = mp_count_bits(&Dz);
+
+ for (u = 1; u < Nbits; u++) { /* zero bit off, already accounted for */
+ /* Formulas for doubling of indices (carried out mod N). Note that
+ * the indices denoted as "2m" are actually powers of 2, specifically
+ * 2^(ul-1) beginning each loop and 2^ul ending each loop.
+ *
+ * U_2m = U_m*V_m
+ * V_2m = V_m*V_m - 2*Q^m
+ */
+
+ if ((err = mp_mul(&U2mz, &V2mz, &U2mz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mod(&U2mz, a, &U2mz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_sqr(&V2mz, &V2mz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_sub(&V2mz, &Q2mz, &V2mz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mod(&V2mz, a, &V2mz)) != MP_OKAY) goto LBL_LS_ERR;
+
+ /* Must calculate powers of Q for use in V_2m, also for Q^d later */
+ if ((err = mp_sqr(&Qmz, &Qmz)) != MP_OKAY) goto LBL_LS_ERR;
+
+ /* prevents overflow */ /* CZ still necessary without a fixed prealloc'd mem.? */
+ if ((err = mp_mod(&Qmz, a, &Qmz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mul_2(&Qmz, &Q2mz)) != MP_OKAY) goto LBL_LS_ERR;
+
+ if (s_mp_get_bit(&Dz, (unsigned int)u) == MP_YES) {
+ /* Formulas for addition of indices (carried out mod N);
+ *
+ * U_(m+n) = (U_m*V_n + U_n*V_m)/2
+ * V_(m+n) = (V_m*V_n + D*U_m*U_n)/2
+ *
+ * Be careful with division by 2 (mod N)!
+ */
+ if ((err = mp_mul(&U2mz, &Vz, &T1z)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mul(&Uz, &V2mz, &T2z)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mul(&V2mz, &Vz, &T3z)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mul(&U2mz, &Uz, &T4z)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = s_mp_mul_si(&T4z, Ds, &T4z)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_add(&T1z, &T2z, &Uz)) != MP_OKAY) goto LBL_LS_ERR;
+ if (MP_IS_ODD(&Uz)) {
+ if ((err = mp_add(&Uz, a, &Uz)) != MP_OKAY) goto LBL_LS_ERR;
+ }
+ /* CZ
+ * This should round towards negative infinity because
+ * Thomas R. Nicely used GMP's mpz_fdiv_q_2exp().
+ * But mp_div_2() does not do so, it is truncating instead.
+ */
+ oddness = MP_IS_ODD(&Uz) ? MP_YES : MP_NO;
+ if ((err = mp_div_2(&Uz, &Uz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((Uz.sign == MP_NEG) && (oddness != MP_NO)) {
+ if ((err = mp_sub_d(&Uz, 1uL, &Uz)) != MP_OKAY) goto LBL_LS_ERR;
+ }
+ if ((err = mp_add(&T3z, &T4z, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+ if (MP_IS_ODD(&Vz)) {
+ if ((err = mp_add(&Vz, a, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+ }
+ oddness = MP_IS_ODD(&Vz) ? MP_YES : MP_NO;
+ if ((err = mp_div_2(&Vz, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((Vz.sign == MP_NEG) && (oddness != MP_NO)) {
+ if ((err = mp_sub_d(&Vz, 1uL, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+ }
+ if ((err = mp_mod(&Uz, a, &Uz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mod(&Vz, a, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+
+ /* Calculating Q^d for later use */
+ if ((err = mp_mul(&Qkdz, &Qmz, &Qkdz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mod(&Qkdz, a, &Qkdz)) != MP_OKAY) goto LBL_LS_ERR;
+ }
+ }
+
+ /* If U_d or V_d is congruent to 0 mod N, then N is a prime or a
+ strong Lucas pseudoprime. */
+ if (MP_IS_ZERO(&Uz) || MP_IS_ZERO(&Vz)) {
+ *result = MP_YES;
+ goto LBL_LS_ERR;
+ }
+
+ /* NOTE: Ribenboim ("The new book of prime number records," 3rd ed.,
+ 1995/6) omits the condition V0 on p.142, but includes it on
+ p. 130. The condition is NECESSARY; otherwise the test will
+ return false negatives---e.g., the primes 29 and 2000029 will be
+ returned as composite. */
+
+ /* Otherwise, we must compute V_2d, V_4d, V_8d, ..., V_{2^(s-1)*d}
+ by repeated use of the formula V_2m = V_m*V_m - 2*Q^m. If any of
+ these are congruent to 0 mod N, then N is a prime or a strong
+ Lucas pseudoprime. */
+
+ /* Initialize 2*Q^(d*2^r) for V_2m */
+ if ((err = mp_mul_2(&Qkdz, &Q2kdz)) != MP_OKAY) goto LBL_LS_ERR;
+
+ for (r = 1; r < s; r++) {
+ if ((err = mp_sqr(&Vz, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_sub(&Vz, &Q2kdz, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mod(&Vz, a, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+ if (MP_IS_ZERO(&Vz)) {
+ *result = MP_YES;
+ goto LBL_LS_ERR;
+ }
+ /* Calculate Q^{d*2^r} for next r (final iteration irrelevant). */
+ if (r < (s - 1)) {
+ if ((err = mp_sqr(&Qkdz, &Qkdz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mod(&Qkdz, a, &Qkdz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mul_2(&Qkdz, &Q2kdz)) != MP_OKAY) goto LBL_LS_ERR;
+ }
+ }
+LBL_LS_ERR:
+ mp_clear_multi(&Q2kdz, &T4z, &T3z, &T2z, &T1z, &Qkdz, &Q2mz, &Qmz, &V2mz, &U2mz, &Vz, &Uz, &Np1, &gcd, &Dz, NULL);
+ return err;
+}
+#endif
+#endif
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_radix_size.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_radix_size.c
new file mode 100644
index 0000000..b96f487
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_radix_size.c
@@ -0,0 +1,65 @@
+#include "tommath_private.h"
+#ifdef BN_MP_RADIX_SIZE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* returns size of ASCII representation */
+mp_err mp_radix_size(const mp_int *a, int radix, int *size)
+{
+ mp_err err;
+ int digs;
+ mp_int t;
+ mp_digit d;
+
+ *size = 0;
+
+ /* make sure the radix is in range */
+ if ((radix < 2) || (radix > 64)) {
+ return MP_VAL;
+ }
+
+ if (MP_IS_ZERO(a)) {
+ *size = 2;
+ return MP_OKAY;
+ }
+
+ /* special case for binary */
+ if (radix == 2) {
+ *size = (mp_count_bits(a) + ((a->sign == MP_NEG) ? 1 : 0) + 1);
+ return MP_OKAY;
+ }
+
+ /* digs is the digit count */
+ digs = 0;
+
+ /* if it's negative add one for the sign */
+ if (a->sign == MP_NEG) {
+ ++digs;
+ }
+
+ /* init a copy of the input */
+ if ((err = mp_init_copy(&t, a)) != MP_OKAY) {
+ return err;
+ }
+
+ /* force temp to positive */
+ t.sign = MP_ZPOS;
+
+ /* fetch out all of the digits */
+ while (!MP_IS_ZERO(&t)) {
+ if ((err = mp_div_d(&t, (mp_digit)radix, &t, &d)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ ++digs;
+ }
+
+ /* return digs + 1, the 1 is for the NULL byte that would be required. */
+ *size = digs + 1;
+ err = MP_OKAY;
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_radix_smap.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_radix_smap.c
new file mode 100644
index 0000000..a16128d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_radix_smap.c
@@ -0,0 +1,22 @@
+#include "tommath_private.h"
+#ifdef BN_MP_RADIX_SMAP_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* chars used in radix conversions */
+const char *const mp_s_rmap = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
+const uint8_t mp_s_rmap_reverse[] = {
+ 0xff, 0xff, 0xff, 0x3e, 0xff, 0xff, 0xff, 0x3f, /* ()*+,-./ */
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 01234567 */
+ 0x08, 0x09, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 89:;<=>? */
+ 0xff, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, /* @ABCDEFG */
+ 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, /* HIJKLMNO */
+ 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, /* PQRSTUVW */
+ 0x21, 0x22, 0x23, 0xff, 0xff, 0xff, 0xff, 0xff, /* XYZ[\]^_ */
+ 0xff, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, /* `abcdefg */
+ 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, /* hijklmno */
+ 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, /* pqrstuvw */
+ 0x3b, 0x3c, 0x3d, 0xff, 0xff, 0xff, 0xff, 0xff, /* xyz{|}~. */
+};
+const size_t mp_s_rmap_reverse_sz = sizeof(mp_s_rmap_reverse);
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_rand.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_rand.c
new file mode 100644
index 0000000..7e9052c
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_rand.c
@@ -0,0 +1,46 @@
+#include "tommath_private.h"
+#ifdef BN_MP_RAND_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+mp_err(*s_mp_rand_source)(void *out, size_t size) = s_mp_rand_platform;
+
+void mp_rand_source(mp_err(*source)(void *out, size_t size))
+{
+ s_mp_rand_source = (source == NULL) ? s_mp_rand_platform : source;
+}
+
+mp_err mp_rand(mp_int *a, int digits)
+{
+ int i;
+ mp_err err;
+
+ mp_zero(a);
+
+ if (digits <= 0) {
+ return MP_OKAY;
+ }
+
+ if ((err = mp_grow(a, digits)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = s_mp_rand_source(a->dp, (size_t)digits * sizeof(mp_digit))) != MP_OKAY) {
+ return err;
+ }
+
+ /* TODO: We ensure that the highest digit is nonzero. Should this be removed? */
+ while ((a->dp[digits - 1] & MP_MASK) == 0u) {
+ if ((err = s_mp_rand_source(a->dp + digits - 1, sizeof(mp_digit))) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ a->used = digits;
+ for (i = 0; i < digits; ++i) {
+ a->dp[i] &= MP_MASK;
+ }
+
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_read_radix.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_read_radix.c
new file mode 100644
index 0000000..de18e06
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_read_radix.c
@@ -0,0 +1,79 @@
+#include "tommath_private.h"
+#ifdef BN_MP_READ_RADIX_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#define MP_TOUPPER(c) ((((c) >= 'a') && ((c) <= 'z')) ? (((c) + 'A') - 'a') : (c))
+
+/* read a string [ASCII] in a given radix */
+mp_err mp_read_radix(mp_int *a, const char *str, int radix)
+{
+ mp_err err;
+ int y;
+ mp_sign neg;
+ unsigned pos;
+ char ch;
+
+ /* zero the digit bignum */
+ mp_zero(a);
+
+ /* make sure the radix is ok */
+ if ((radix < 2) || (radix > 64)) {
+ return MP_VAL;
+ }
+
+ /* if the leading digit is a
+ * minus set the sign to negative.
+ */
+ if (*str == '-') {
+ ++str;
+ neg = MP_NEG;
+ } else {
+ neg = MP_ZPOS;
+ }
+
+ /* set the integer to the default of zero */
+ mp_zero(a);
+
+ /* process each digit of the string */
+ while (*str != '\0') {
+ /* if the radix <= 36 the conversion is case insensitive
+ * this allows numbers like 1AB and 1ab to represent the same value
+ * [e.g. in hex]
+ */
+ ch = (radix <= 36) ? (char)MP_TOUPPER((int)*str) : *str;
+ pos = (unsigned)(ch - '(');
+ if (mp_s_rmap_reverse_sz < pos) {
+ break;
+ }
+ y = (int)mp_s_rmap_reverse[pos];
+
+ /* if the char was found in the map
+ * and is less than the given radix add it
+ * to the number, otherwise exit the loop.
+ */
+ if ((y == 0xff) || (y >= radix)) {
+ break;
+ }
+ if ((err = mp_mul_d(a, (mp_digit)radix, a)) != MP_OKAY) {
+ return err;
+ }
+ if ((err = mp_add_d(a, (mp_digit)y, a)) != MP_OKAY) {
+ return err;
+ }
+ ++str;
+ }
+
+ /* if an illegal character was found, fail. */
+ if (!((*str == '\0') || (*str == '\r') || (*str == '\n'))) {
+ mp_zero(a);
+ return MP_VAL;
+ }
+
+ /* set the sign only if a != 0 */
+ if (!MP_IS_ZERO(a)) {
+ a->sign = neg;
+ }
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce.c
new file mode 100644
index 0000000..3c669d4
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce.c
@@ -0,0 +1,83 @@
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* reduces x mod m, assumes 0 < x < m**2, mu is
+ * precomputed via mp_reduce_setup.
+ * From HAC pp.604 Algorithm 14.42
+ */
+mp_err mp_reduce(mp_int *x, const mp_int *m, const mp_int *mu)
+{
+ mp_int q;
+ mp_err err;
+ int um = m->used;
+
+ /* q = x */
+ if ((err = mp_init_copy(&q, x)) != MP_OKAY) {
+ return err;
+ }
+
+ /* q1 = x / b**(k-1) */
+ mp_rshd(&q, um - 1);
+
+ /* according to HAC this optimization is ok */
+ if ((mp_digit)um > ((mp_digit)1 << (MP_DIGIT_BIT - 1))) {
+ if ((err = mp_mul(&q, mu, &q)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+ } else if (MP_HAS(S_MP_MUL_HIGH_DIGS)) {
+ if ((err = s_mp_mul_high_digs(&q, mu, &q, um)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+ } else if (MP_HAS(S_MP_MUL_HIGH_DIGS_FAST)) {
+ if ((err = s_mp_mul_high_digs_fast(&q, mu, &q, um)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+ } else {
+ err = MP_VAL;
+ goto CLEANUP;
+ }
+
+ /* q3 = q2 / b**(k+1) */
+ mp_rshd(&q, um + 1);
+
+ /* x = x mod b**(k+1), quick (no division) */
+ if ((err = mp_mod_2d(x, MP_DIGIT_BIT * (um + 1), x)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+
+ /* q = q * m mod b**(k+1), quick (no division) */
+ if ((err = s_mp_mul_digs(&q, m, &q, um + 1)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+
+ /* x = x - q */
+ if ((err = mp_sub(x, &q, x)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+
+ /* If x < 0, add b**(k+1) to it */
+ if (mp_cmp_d(x, 0uL) == MP_LT) {
+ mp_set(&q, 1uL);
+ if ((err = mp_lshd(&q, um + 1)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+ if ((err = mp_add(x, &q, x)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+ }
+
+ /* Back off if it's too big */
+ while (mp_cmp(x, m) != MP_LT) {
+ if ((err = s_mp_sub(x, m, x)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+ }
+
+CLEANUP:
+ mp_clear(&q);
+
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k.c
new file mode 100644
index 0000000..1cea6cb
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k.c
@@ -0,0 +1,48 @@
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_2K_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* reduces a modulo n where n is of the form 2**p - d */
+mp_err mp_reduce_2k(mp_int *a, const mp_int *n, mp_digit d)
+{
+ mp_int q;
+ mp_err err;
+ int p;
+
+ if ((err = mp_init(&q)) != MP_OKAY) {
+ return err;
+ }
+
+ p = mp_count_bits(n);
+top:
+ /* q = a/2**p, a = a mod 2**p */
+ if ((err = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ if (d != 1u) {
+ /* q = q * d */
+ if ((err = mp_mul_d(&q, d, &q)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ }
+
+ /* a = a + q */
+ if ((err = s_mp_add(a, &q, a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ if (mp_cmp_mag(a, n) != MP_LT) {
+ if ((err = s_mp_sub(a, n, a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ goto top;
+ }
+
+LBL_ERR:
+ mp_clear(&q);
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k_l.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k_l.c
new file mode 100644
index 0000000..6a9f3d3
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k_l.c
@@ -0,0 +1,49 @@
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_2K_L_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* reduces a modulo n where n is of the form 2**p - d
+ This differs from reduce_2k since "d" can be larger
+ than a single digit.
+*/
+mp_err mp_reduce_2k_l(mp_int *a, const mp_int *n, const mp_int *d)
+{
+ mp_int q;
+ mp_err err;
+ int p;
+
+ if ((err = mp_init(&q)) != MP_OKAY) {
+ return err;
+ }
+
+ p = mp_count_bits(n);
+top:
+ /* q = a/2**p, a = a mod 2**p */
+ if ((err = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ /* q = q * d */
+ if ((err = mp_mul(&q, d, &q)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ /* a = a + q */
+ if ((err = s_mp_add(a, &q, a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ if (mp_cmp_mag(a, n) != MP_LT) {
+ if ((err = s_mp_sub(a, n, a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ goto top;
+ }
+
+LBL_ERR:
+ mp_clear(&q);
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k_setup.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k_setup.c
new file mode 100644
index 0000000..2eaf7ad
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k_setup.c
@@ -0,0 +1,32 @@
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_2K_SETUP_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* determines the setup value */
+mp_err mp_reduce_2k_setup(const mp_int *a, mp_digit *d)
+{
+ mp_err err;
+ mp_int tmp;
+ int p;
+
+ if ((err = mp_init(&tmp)) != MP_OKAY) {
+ return err;
+ }
+
+ p = mp_count_bits(a);
+ if ((err = mp_2expt(&tmp, p)) != MP_OKAY) {
+ mp_clear(&tmp);
+ return err;
+ }
+
+ if ((err = s_mp_sub(&tmp, a, &tmp)) != MP_OKAY) {
+ mp_clear(&tmp);
+ return err;
+ }
+
+ *d = tmp.dp[0];
+ mp_clear(&tmp);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k_setup_l.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k_setup_l.c
new file mode 100644
index 0000000..4f9aa14
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_2k_setup_l.c
@@ -0,0 +1,28 @@
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_2K_SETUP_L_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* determines the setup value */
+mp_err mp_reduce_2k_setup_l(const mp_int *a, mp_int *d)
+{
+ mp_err err;
+ mp_int tmp;
+
+ if ((err = mp_init(&tmp)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_2expt(&tmp, mp_count_bits(a))) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ if ((err = s_mp_sub(&tmp, a, d)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+LBL_ERR:
+ mp_clear(&tmp);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_is_2k.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_is_2k.c
new file mode 100644
index 0000000..a9f4f9f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_is_2k.c
@@ -0,0 +1,38 @@
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_IS_2K_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* determines if mp_reduce_2k can be used */
+mp_bool mp_reduce_is_2k(const mp_int *a)
+{
+ int ix, iy, iw;
+ mp_digit iz;
+
+ if (a->used == 0) {
+ return MP_NO;
+ } else if (a->used == 1) {
+ return MP_YES;
+ } else if (a->used > 1) {
+ iy = mp_count_bits(a);
+ iz = 1;
+ iw = 1;
+
+ /* Test every bit from the second digit up, must be 1 */
+ for (ix = MP_DIGIT_BIT; ix < iy; ix++) {
+ if ((a->dp[iw] & iz) == 0u) {
+ return MP_NO;
+ }
+ iz <<= 1;
+ if (iz > MP_DIGIT_MAX) {
+ ++iw;
+ iz = 1;
+ }
+ }
+ return MP_YES;
+ } else {
+ return MP_YES;
+ }
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_is_2k_l.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_is_2k_l.c
new file mode 100644
index 0000000..4bc69be
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_is_2k_l.c
@@ -0,0 +1,28 @@
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_IS_2K_L_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* determines if reduce_2k_l can be used */
+mp_bool mp_reduce_is_2k_l(const mp_int *a)
+{
+ int ix, iy;
+
+ if (a->used == 0) {
+ return MP_NO;
+ } else if (a->used == 1) {
+ return MP_YES;
+ } else if (a->used > 1) {
+ /* if more than half of the digits are -1 we're sold */
+ for (iy = ix = 0; ix < a->used; ix++) {
+ if (a->dp[ix] == MP_DIGIT_MAX) {
+ ++iy;
+ }
+ }
+ return (iy >= (a->used/2)) ? MP_YES : MP_NO;
+ } else {
+ return MP_NO;
+ }
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_setup.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_setup.c
new file mode 100644
index 0000000..f02160f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_reduce_setup.c
@@ -0,0 +1,17 @@
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_SETUP_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* pre-calculate the value required for Barrett reduction
+ * For a given modulus "b" it calulates the value required in "a"
+ */
+mp_err mp_reduce_setup(mp_int *a, const mp_int *b)
+{
+ mp_err err;
+ if ((err = mp_2expt(a, b->used * 2 * MP_DIGIT_BIT)) != MP_OKAY) {
+ return err;
+ }
+ return mp_div(a, b, a, NULL);
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_root_u32.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_root_u32.c
new file mode 100644
index 0000000..ba65549
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_root_u32.c
@@ -0,0 +1,139 @@
+#include "tommath_private.h"
+#ifdef BN_MP_ROOT_U32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* find the n'th root of an integer
+ *
+ * Result found such that (c)**b <= a and (c+1)**b > a
+ *
+ * This algorithm uses Newton's approximation
+ * x[i+1] = x[i] - f(x[i])/f'(x[i])
+ * which will find the root in log(N) time where
+ * each step involves a fair bit.
+ */
+mp_err mp_root_u32(const mp_int *a, uint32_t b, mp_int *c)
+{
+ mp_int t1, t2, t3, a_;
+ mp_ord cmp;
+ int ilog2;
+ mp_err err;
+
+ /* input must be positive if b is even */
+ if (((b & 1u) == 0u) && (a->sign == MP_NEG)) {
+ return MP_VAL;
+ }
+
+ if ((err = mp_init_multi(&t1, &t2, &t3, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* if a is negative fudge the sign but keep track */
+ a_ = *a;
+ a_.sign = MP_ZPOS;
+
+ /* Compute seed: 2^(log_2(n)/b + 2)*/
+ ilog2 = mp_count_bits(a);
+
+ /*
+ If "b" is larger than INT_MAX it is also larger than
+ log_2(n) because the bit-length of the "n" is measured
+ with an int and hence the root is always < 2 (two).
+ */
+ if (b > (uint32_t)(INT_MAX/2)) {
+ mp_set(c, 1uL);
+ c->sign = a->sign;
+ err = MP_OKAY;
+ goto LBL_ERR;
+ }
+
+ /* "b" is smaller than INT_MAX, we can cast safely */
+ if (ilog2 < (int)b) {
+ mp_set(c, 1uL);
+ c->sign = a->sign;
+ err = MP_OKAY;
+ goto LBL_ERR;
+ }
+ ilog2 = ilog2 / ((int)b);
+ if (ilog2 == 0) {
+ mp_set(c, 1uL);
+ c->sign = a->sign;
+ err = MP_OKAY;
+ goto LBL_ERR;
+ }
+ /* Start value must be larger than root */
+ ilog2 += 2;
+ if ((err = mp_2expt(&t2,ilog2)) != MP_OKAY) goto LBL_ERR;
+ do {
+ /* t1 = t2 */
+ if ((err = mp_copy(&t2, &t1)) != MP_OKAY) goto LBL_ERR;
+
+ /* t2 = t1 - ((t1**b - a) / (b * t1**(b-1))) */
+
+ /* t3 = t1**(b-1) */
+ if ((err = mp_expt_u32(&t1, b - 1u, &t3)) != MP_OKAY) goto LBL_ERR;
+
+ /* numerator */
+ /* t2 = t1**b */
+ if ((err = mp_mul(&t3, &t1, &t2)) != MP_OKAY) goto LBL_ERR;
+
+ /* t2 = t1**b - a */
+ if ((err = mp_sub(&t2, &a_, &t2)) != MP_OKAY) goto LBL_ERR;
+
+ /* denominator */
+ /* t3 = t1**(b-1) * b */
+ if ((err = mp_mul_d(&t3, b, &t3)) != MP_OKAY) goto LBL_ERR;
+
+ /* t3 = (t1**b - a)/(b * t1**(b-1)) */
+ if ((err = mp_div(&t2, &t3, &t3, NULL)) != MP_OKAY) goto LBL_ERR;
+
+ if ((err = mp_sub(&t1, &t3, &t2)) != MP_OKAY) goto LBL_ERR;
+
+ /*
+ Number of rounds is at most log_2(root). If it is more it
+ got stuck, so break out of the loop and do the rest manually.
+ */
+ if (ilog2-- == 0) {
+ break;
+ }
+ } while (mp_cmp(&t1, &t2) != MP_EQ);
+
+ /* result can be off by a few so check */
+ /* Loop beneath can overshoot by one if found root is smaller than actual root */
+ for (;;) {
+ if ((err = mp_expt_u32(&t1, b, &t2)) != MP_OKAY) goto LBL_ERR;
+ cmp = mp_cmp(&t2, &a_);
+ if (cmp == MP_EQ) {
+ err = MP_OKAY;
+ goto LBL_ERR;
+ }
+ if (cmp == MP_LT) {
+ if ((err = mp_add_d(&t1, 1uL, &t1)) != MP_OKAY) goto LBL_ERR;
+ } else {
+ break;
+ }
+ }
+ /* correct overshoot from above or from recurrence */
+ for (;;) {
+ if ((err = mp_expt_u32(&t1, b, &t2)) != MP_OKAY) goto LBL_ERR;
+ if (mp_cmp(&t2, &a_) == MP_GT) {
+ if ((err = mp_sub_d(&t1, 1uL, &t1)) != MP_OKAY) goto LBL_ERR;
+ } else {
+ break;
+ }
+ }
+
+ /* set the result */
+ mp_exch(&t1, c);
+
+ /* set the sign of the result */
+ c->sign = a->sign;
+
+ err = MP_OKAY;
+
+LBL_ERR:
+ mp_clear_multi(&t1, &t2, &t3, NULL);
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_rshd.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_rshd.c
new file mode 100644
index 0000000..bb8743e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_rshd.c
@@ -0,0 +1,51 @@
+#include "tommath_private.h"
+#ifdef BN_MP_RSHD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* shift right a certain amount of digits */
+void mp_rshd(mp_int *a, int b)
+{
+ int x;
+ mp_digit *bottom, *top;
+
+ /* if b <= 0 then ignore it */
+ if (b <= 0) {
+ return;
+ }
+
+ /* if b > used then simply zero it and return */
+ if (a->used <= b) {
+ mp_zero(a);
+ return;
+ }
+
+ /* shift the digits down */
+
+ /* bottom */
+ bottom = a->dp;
+
+ /* top [offset into digits] */
+ top = a->dp + b;
+
+ /* this is implemented as a sliding window where
+ * the window is b-digits long and digits from
+ * the top of the window are copied to the bottom
+ *
+ * e.g.
+
+ b-2 | b-1 | b0 | b1 | b2 | ... | bb | ---->
+ /\ | ---->
+ \-------------------/ ---->
+ */
+ for (x = 0; x < (a->used - b); x++) {
+ *bottom++ = *top++;
+ }
+
+ /* zero the top digits */
+ MP_ZERO_DIGITS(bottom, a->used - x);
+
+ /* remove excess digits */
+ a->used -= b;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sbin_size.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sbin_size.c
new file mode 100644
index 0000000..e0993d6
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sbin_size.c
@@ -0,0 +1,11 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SBIN_SIZE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* get the size for an signed equivalent */
+size_t mp_sbin_size(const mp_int *a)
+{
+ return 1u + mp_ubin_size(a);
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set.c
new file mode 100644
index 0000000..44ac6df
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set.c
@@ -0,0 +1,14 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SET_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* set to a digit */
+void mp_set(mp_int *a, mp_digit b)
+{
+ a->dp[0] = b & MP_MASK;
+ a->sign = MP_ZPOS;
+ a->used = (a->dp[0] != 0u) ? 1 : 0;
+ MP_ZERO_DIGITS(a->dp + a->used, a->alloc - a->used);
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_double.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_double.c
new file mode 100644
index 0000000..6f91b64
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_double.c
@@ -0,0 +1,47 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SET_DOUBLE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#if defined(__STDC_IEC_559__) || defined(__GCC_IEC_559) || defined(__x86_64__) || defined(_M_X64) || defined(_M_AMD64) || defined(__i386__) || defined(_M_X86) || defined(__aarch64__) || defined(__arm__)
+mp_err mp_set_double(mp_int *a, double b)
+{
+ uint64_t frac;
+ int exp;
+ mp_err err;
+ union {
+ double dbl;
+ uint64_t bits;
+ } cast;
+ cast.dbl = b;
+
+ exp = (int)((unsigned)(cast.bits >> 52) & 0x7FFu);
+ frac = (cast.bits & ((1uLL << 52) - 1uLL)) | (1uLL << 52);
+
+ if (exp == 0x7FF) { /* +-inf, NaN */
+ return MP_VAL;
+ }
+ exp -= 1023 + 52;
+
+ mp_set_u64(a, frac);
+
+ err = (exp < 0) ? mp_div_2d(a, -exp, a, NULL) : mp_mul_2d(a, exp, a);
+ if (err != MP_OKAY) {
+ return err;
+ }
+
+ if (((cast.bits >> 63) != 0uLL) && !MP_IS_ZERO(a)) {
+ a->sign = MP_NEG;
+ }
+
+ return MP_OKAY;
+}
+#else
+/* pragma message() not supported by several compilers (in mostly older but still used versions) */
+# ifdef _MSC_VER
+# pragma message("mp_set_double implementation is only available on platforms with IEEE754 floating point format")
+# else
+# warning "mp_set_double implementation is only available on platforms with IEEE754 floating point format"
+# endif
+#endif
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_i32.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_i32.c
new file mode 100644
index 0000000..df4513d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_i32.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SET_I32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_SIGNED(mp_set_i32, mp_set_u32, int32_t, uint32_t)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_i64.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_i64.c
new file mode 100644
index 0000000..395103b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_i64.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SET_I64_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_SIGNED(mp_set_i64, mp_set_u64, int64_t, uint64_t)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_l.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_l.c
new file mode 100644
index 0000000..1e445fb
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_l.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SET_L_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_SIGNED(mp_set_l, mp_set_ul, long, unsigned long)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_ll.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_ll.c
new file mode 100644
index 0000000..3e2324f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_ll.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SET_LL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_SIGNED(mp_set_ll, mp_set_ull, long long, unsigned long long)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_u32.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_u32.c
new file mode 100644
index 0000000..18ba5e1
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_u32.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SET_U32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_UNSIGNED(mp_set_u32, uint32_t)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_u64.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_u64.c
new file mode 100644
index 0000000..88fab6c
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_u64.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SET_U64_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_UNSIGNED(mp_set_u64, uint64_t)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_ul.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_ul.c
new file mode 100644
index 0000000..adfd85c
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_ul.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SET_UL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_UNSIGNED(mp_set_ul, unsigned long)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_ull.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_ull.c
new file mode 100644
index 0000000..8fbc1bd
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_set_ull.c
@@ -0,0 +1,7 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SET_ULL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_UNSIGNED(mp_set_ull, unsigned long long)
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_shrink.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_shrink.c
new file mode 100644
index 0000000..cf27ed9
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_shrink.c
@@ -0,0 +1,22 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SHRINK_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* shrink a bignum */
+mp_err mp_shrink(mp_int *a)
+{
+ mp_digit *tmp;
+ int alloc = MP_MAX(MP_MIN_PREC, a->used);
+ if (a->alloc != alloc) {
+ if ((tmp = (mp_digit *) MP_REALLOC(a->dp,
+ (size_t)a->alloc * sizeof(mp_digit),
+ (size_t)alloc * sizeof(mp_digit))) == NULL) {
+ return MP_MEM;
+ }
+ a->dp = tmp;
+ a->alloc = alloc;
+ }
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_signed_rsh.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_signed_rsh.c
new file mode 100644
index 0000000..8d8d841
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_signed_rsh.c
@@ -0,0 +1,22 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SIGNED_RSH_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* shift right by a certain bit count with sign extension */
+mp_err mp_signed_rsh(const mp_int *a, int b, mp_int *c)
+{
+ mp_err res;
+ if (a->sign == MP_ZPOS) {
+ return mp_div_2d(a, b, c, NULL);
+ }
+
+ res = mp_add_d(a, 1uL, c);
+ if (res != MP_OKAY) {
+ return res;
+ }
+
+ res = mp_div_2d(c, b, c, NULL);
+ return (res == MP_OKAY) ? mp_sub_d(c, 1uL, c) : res;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqr.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqr.c
new file mode 100644
index 0000000..e0d0a73
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqr.c
@@ -0,0 +1,28 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SQR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* computes b = a*a */
+mp_err mp_sqr(const mp_int *a, mp_int *b)
+{
+ mp_err err;
+ if (MP_HAS(S_MP_TOOM_SQR) && /* use Toom-Cook? */
+ (a->used >= MP_TOOM_SQR_CUTOFF)) {
+ err = s_mp_toom_sqr(a, b);
+ } else if (MP_HAS(S_MP_KARATSUBA_SQR) && /* Karatsuba? */
+ (a->used >= MP_KARATSUBA_SQR_CUTOFF)) {
+ err = s_mp_karatsuba_sqr(a, b);
+ } else if (MP_HAS(S_MP_SQR_FAST) && /* can we use the fast comba multiplier? */
+ (((a->used * 2) + 1) < MP_WARRAY) &&
+ (a->used < (MP_MAXFAST / 2))) {
+ err = s_mp_sqr_fast(a, b);
+ } else if (MP_HAS(S_MP_SQR)) {
+ err = s_mp_sqr(a, b);
+ } else {
+ err = MP_VAL;
+ }
+ b->sign = MP_ZPOS;
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqrmod.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqrmod.c
new file mode 100644
index 0000000..626ea2c
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqrmod.c
@@ -0,0 +1,25 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SQRMOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* c = a * a (mod b) */
+mp_err mp_sqrmod(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_err err;
+ mp_int t;
+
+ if ((err = mp_init(&t)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_sqr(a, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ err = mp_mod(&t, b, c);
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqrt.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqrt.c
new file mode 100644
index 0000000..82d6824
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqrt.c
@@ -0,0 +1,67 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SQRT_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* this function is less generic than mp_n_root, simpler and faster */
+mp_err mp_sqrt(const mp_int *arg, mp_int *ret)
+{
+ mp_err err;
+ mp_int t1, t2;
+
+ /* must be positive */
+ if (arg->sign == MP_NEG) {
+ return MP_VAL;
+ }
+
+ /* easy out */
+ if (MP_IS_ZERO(arg)) {
+ mp_zero(ret);
+ return MP_OKAY;
+ }
+
+ if ((err = mp_init_copy(&t1, arg)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_init(&t2)) != MP_OKAY) {
+ goto E2;
+ }
+
+ /* First approx. (not very bad for large arg) */
+ mp_rshd(&t1, t1.used/2);
+
+ /* t1 > 0 */
+ if ((err = mp_div(arg, &t1, &t2, NULL)) != MP_OKAY) {
+ goto E1;
+ }
+ if ((err = mp_add(&t1, &t2, &t1)) != MP_OKAY) {
+ goto E1;
+ }
+ if ((err = mp_div_2(&t1, &t1)) != MP_OKAY) {
+ goto E1;
+ }
+ /* And now t1 > sqrt(arg) */
+ do {
+ if ((err = mp_div(arg, &t1, &t2, NULL)) != MP_OKAY) {
+ goto E1;
+ }
+ if ((err = mp_add(&t1, &t2, &t1)) != MP_OKAY) {
+ goto E1;
+ }
+ if ((err = mp_div_2(&t1, &t1)) != MP_OKAY) {
+ goto E1;
+ }
+ /* t1 >= sqrt(arg) >= t2 at this point */
+ } while (mp_cmp_mag(&t1, &t2) == MP_GT);
+
+ mp_exch(&t1, ret);
+
+E1:
+ mp_clear(&t2);
+E2:
+ mp_clear(&t1);
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqrtmod_prime.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqrtmod_prime.c
new file mode 100644
index 0000000..a833ed7
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sqrtmod_prime.c
@@ -0,0 +1,118 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SQRTMOD_PRIME_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Tonelli-Shanks algorithm
+ * https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm
+ * https://gmplib.org/list-archives/gmp-discuss/2013-April/005300.html
+ *
+ */
+
+mp_err mp_sqrtmod_prime(const mp_int *n, const mp_int *prime, mp_int *ret)
+{
+ mp_err err;
+ int legendre;
+ mp_int t1, C, Q, S, Z, M, T, R, two;
+ mp_digit i;
+
+ /* first handle the simple cases */
+ if (mp_cmp_d(n, 0uL) == MP_EQ) {
+ mp_zero(ret);
+ return MP_OKAY;
+ }
+ if (mp_cmp_d(prime, 2uL) == MP_EQ) return MP_VAL; /* prime must be odd */
+ if ((err = mp_kronecker(n, prime, &legendre)) != MP_OKAY) return err;
+ if (legendre == -1) return MP_VAL; /* quadratic non-residue mod prime */
+
+ if ((err = mp_init_multi(&t1, &C, &Q, &S, &Z, &M, &T, &R, &two, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* SPECIAL CASE: if prime mod 4 == 3
+ * compute directly: err = n^(prime+1)/4 mod prime
+ * Handbook of Applied Cryptography algorithm 3.36
+ */
+ if ((err = mp_mod_d(prime, 4uL, &i)) != MP_OKAY) goto cleanup;
+ if (i == 3u) {
+ if ((err = mp_add_d(prime, 1uL, &t1)) != MP_OKAY) goto cleanup;
+ if ((err = mp_div_2(&t1, &t1)) != MP_OKAY) goto cleanup;
+ if ((err = mp_div_2(&t1, &t1)) != MP_OKAY) goto cleanup;
+ if ((err = mp_exptmod(n, &t1, prime, ret)) != MP_OKAY) goto cleanup;
+ err = MP_OKAY;
+ goto cleanup;
+ }
+
+ /* NOW: Tonelli-Shanks algorithm */
+
+ /* factor out powers of 2 from prime-1, defining Q and S as: prime-1 = Q*2^S */
+ if ((err = mp_copy(prime, &Q)) != MP_OKAY) goto cleanup;
+ if ((err = mp_sub_d(&Q, 1uL, &Q)) != MP_OKAY) goto cleanup;
+ /* Q = prime - 1 */
+ mp_zero(&S);
+ /* S = 0 */
+ while (MP_IS_EVEN(&Q)) {
+ if ((err = mp_div_2(&Q, &Q)) != MP_OKAY) goto cleanup;
+ /* Q = Q / 2 */
+ if ((err = mp_add_d(&S, 1uL, &S)) != MP_OKAY) goto cleanup;
+ /* S = S + 1 */
+ }
+
+ /* find a Z such that the Legendre symbol (Z|prime) == -1 */
+ mp_set_u32(&Z, 2u);
+ /* Z = 2 */
+ for (;;) {
+ if ((err = mp_kronecker(&Z, prime, &legendre)) != MP_OKAY) goto cleanup;
+ if (legendre == -1) break;
+ if ((err = mp_add_d(&Z, 1uL, &Z)) != MP_OKAY) goto cleanup;
+ /* Z = Z + 1 */
+ }
+
+ if ((err = mp_exptmod(&Z, &Q, prime, &C)) != MP_OKAY) goto cleanup;
+ /* C = Z ^ Q mod prime */
+ if ((err = mp_add_d(&Q, 1uL, &t1)) != MP_OKAY) goto cleanup;
+ if ((err = mp_div_2(&t1, &t1)) != MP_OKAY) goto cleanup;
+ /* t1 = (Q + 1) / 2 */
+ if ((err = mp_exptmod(n, &t1, prime, &R)) != MP_OKAY) goto cleanup;
+ /* R = n ^ ((Q + 1) / 2) mod prime */
+ if ((err = mp_exptmod(n, &Q, prime, &T)) != MP_OKAY) goto cleanup;
+ /* T = n ^ Q mod prime */
+ if ((err = mp_copy(&S, &M)) != MP_OKAY) goto cleanup;
+ /* M = S */
+ mp_set_u32(&two, 2u);
+
+ for (;;) {
+ if ((err = mp_copy(&T, &t1)) != MP_OKAY) goto cleanup;
+ i = 0;
+ for (;;) {
+ if (mp_cmp_d(&t1, 1uL) == MP_EQ) break;
+ if ((err = mp_exptmod(&t1, &two, prime, &t1)) != MP_OKAY) goto cleanup;
+ i++;
+ }
+ if (i == 0u) {
+ if ((err = mp_copy(&R, ret)) != MP_OKAY) goto cleanup;
+ err = MP_OKAY;
+ goto cleanup;
+ }
+ if ((err = mp_sub_d(&M, i, &t1)) != MP_OKAY) goto cleanup;
+ if ((err = mp_sub_d(&t1, 1uL, &t1)) != MP_OKAY) goto cleanup;
+ if ((err = mp_exptmod(&two, &t1, prime, &t1)) != MP_OKAY) goto cleanup;
+ /* t1 = 2 ^ (M - i - 1) */
+ if ((err = mp_exptmod(&C, &t1, prime, &t1)) != MP_OKAY) goto cleanup;
+ /* t1 = C ^ (2 ^ (M - i - 1)) mod prime */
+ if ((err = mp_sqrmod(&t1, prime, &C)) != MP_OKAY) goto cleanup;
+ /* C = (t1 * t1) mod prime */
+ if ((err = mp_mulmod(&R, &t1, prime, &R)) != MP_OKAY) goto cleanup;
+ /* R = (R * t1) mod prime */
+ if ((err = mp_mulmod(&T, &C, prime, &T)) != MP_OKAY) goto cleanup;
+ /* T = (T * C) mod prime */
+ mp_set(&M, i);
+ /* M = i */
+ }
+
+cleanup:
+ mp_clear_multi(&t1, &C, &Q, &S, &Z, &M, &T, &R, &two, NULL);
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sub.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sub.c
new file mode 100644
index 0000000..c1ea39e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sub.c
@@ -0,0 +1,40 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SUB_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* high level subtraction (handles signs) */
+mp_err mp_sub(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_sign sa = a->sign, sb = b->sign;
+ mp_err err;
+
+ if (sa != sb) {
+ /* subtract a negative from a positive, OR */
+ /* subtract a positive from a negative. */
+ /* In either case, ADD their magnitudes, */
+ /* and use the sign of the first number. */
+ c->sign = sa;
+ err = s_mp_add(a, b, c);
+ } else {
+ /* subtract a positive from a positive, OR */
+ /* subtract a negative from a negative. */
+ /* First, take the difference between their */
+ /* magnitudes, then... */
+ if (mp_cmp_mag(a, b) != MP_LT) {
+ /* Copy the sign from the first */
+ c->sign = sa;
+ /* The first has a larger or equal magnitude */
+ err = s_mp_sub(a, b, c);
+ } else {
+ /* The result has the *opposite* sign from */
+ /* the first number. */
+ c->sign = (sa == MP_ZPOS) ? MP_NEG : MP_ZPOS;
+ /* The second has a larger magnitude */
+ err = s_mp_sub(b, a, c);
+ }
+ }
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sub_d.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sub_d.c
new file mode 100644
index 0000000..3ebf9b4
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_sub_d.c
@@ -0,0 +1,74 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SUB_D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* single digit subtraction */
+mp_err mp_sub_d(const mp_int *a, mp_digit b, mp_int *c)
+{
+ mp_digit *tmpa, *tmpc;
+ mp_err err;
+ int ix, oldused;
+
+ /* grow c as required */
+ if (c->alloc < (a->used + 1)) {
+ if ((err = mp_grow(c, a->used + 1)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* if a is negative just do an unsigned
+ * addition [with fudged signs]
+ */
+ if (a->sign == MP_NEG) {
+ mp_int a_ = *a;
+ a_.sign = MP_ZPOS;
+ err = mp_add_d(&a_, b, c);
+ c->sign = MP_NEG;
+
+ /* clamp */
+ mp_clamp(c);
+
+ return err;
+ }
+
+ /* setup regs */
+ oldused = c->used;
+ tmpa = a->dp;
+ tmpc = c->dp;
+
+ /* if a <= b simply fix the single digit */
+ if (((a->used == 1) && (a->dp[0] <= b)) || (a->used == 0)) {
+ if (a->used == 1) {
+ *tmpc++ = b - *tmpa;
+ } else {
+ *tmpc++ = b;
+ }
+ ix = 1;
+
+ /* negative/1digit */
+ c->sign = MP_NEG;
+ c->used = 1;
+ } else {
+ mp_digit mu = b;
+
+ /* positive/size */
+ c->sign = MP_ZPOS;
+ c->used = a->used;
+
+ /* subtract digits, mu is carry */
+ for (ix = 0; ix < a->used; ix++) {
+ *tmpc = *tmpa++ - mu;
+ mu = *tmpc >> (MP_SIZEOF_BITS(mp_digit) - 1u);
+ *tmpc++ &= MP_MASK;
+ }
+ }
+
+ /* zero excess digits */
+ MP_ZERO_DIGITS(tmpc, oldused - ix);
+
+ mp_clamp(c);
+ return MP_OKAY;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_submod.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_submod.c
new file mode 100644
index 0000000..5ebd374
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_submod.c
@@ -0,0 +1,25 @@
+#include "tommath_private.h"
+#ifdef BN_MP_SUBMOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* d = a - b (mod c) */
+mp_err mp_submod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d)
+{
+ mp_err err;
+ mp_int t;
+
+ if ((err = mp_init(&t)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_sub(a, b, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ err = mp_mod(&t, c, d);
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_to_radix.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_to_radix.c
new file mode 100644
index 0000000..7fa86ca
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_to_radix.c
@@ -0,0 +1,84 @@
+#include "tommath_private.h"
+#ifdef BN_MP_TO_RADIX_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* stores a bignum as a ASCII string in a given radix (2..64)
+ *
+ * Stores upto "size - 1" chars and always a NULL byte, puts the number of characters
+ * written, including the '\0', in "written".
+ */
+mp_err mp_to_radix(const mp_int *a, char *str, size_t maxlen, size_t *written, int radix)
+{
+ size_t digs;
+ mp_err err;
+ mp_int t;
+ mp_digit d;
+ char *_s = str;
+
+ /* check range of radix and size*/
+ if (maxlen < 2u) {
+ return MP_BUF;
+ }
+ if ((radix < 2) || (radix > 64)) {
+ return MP_VAL;
+ }
+
+ /* quick out if its zero */
+ if (MP_IS_ZERO(a)) {
+ *str++ = '0';
+ *str = '\0';
+ if (written != NULL) {
+ *written = 2u;
+ }
+ return MP_OKAY;
+ }
+
+ if ((err = mp_init_copy(&t, a)) != MP_OKAY) {
+ return err;
+ }
+
+ /* if it is negative output a - */
+ if (t.sign == MP_NEG) {
+ /* we have to reverse our digits later... but not the - sign!! */
+ ++_s;
+
+ /* store the flag and mark the number as positive */
+ *str++ = '-';
+ t.sign = MP_ZPOS;
+
+ /* subtract a char */
+ --maxlen;
+ }
+ digs = 0u;
+ while (!MP_IS_ZERO(&t)) {
+ if (--maxlen < 1u) {
+ /* no more room */
+ err = MP_BUF;
+ goto LBL_ERR;
+ }
+ if ((err = mp_div_d(&t, (mp_digit)radix, &t, &d)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ *str++ = mp_s_rmap[d];
+ ++digs;
+ }
+ /* reverse the digits of the string. In this case _s points
+ * to the first digit [exluding the sign] of the number
+ */
+ s_mp_reverse((unsigned char *)_s, digs);
+
+ /* append a NULL so the string is properly terminated */
+ *str = '\0';
+ digs++;
+
+ if (written != NULL) {
+ *written = (a->sign == MP_NEG) ? (digs + 1u): digs;
+ }
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_to_sbin.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_to_sbin.c
new file mode 100644
index 0000000..dbaf53e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_to_sbin.c
@@ -0,0 +1,22 @@
+#include "tommath_private.h"
+#ifdef BN_MP_TO_SBIN_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* store in signed [big endian] format */
+mp_err mp_to_sbin(const mp_int *a, unsigned char *buf, size_t maxlen, size_t *written)
+{
+ mp_err err;
+ if (maxlen == 0u) {
+ return MP_BUF;
+ }
+ if ((err = mp_to_ubin(a, buf + 1, maxlen - 1u, written)) != MP_OKAY) {
+ return err;
+ }
+ if (written != NULL) {
+ (*written)++;
+ }
+ buf[0] = (a->sign == MP_ZPOS) ? (unsigned char)0 : (unsigned char)1;
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_to_ubin.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_to_ubin.c
new file mode 100644
index 0000000..1681ca7
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_to_ubin.c
@@ -0,0 +1,41 @@
+#include "tommath_private.h"
+#ifdef BN_MP_TO_UBIN_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* store in unsigned [big endian] format */
+mp_err mp_to_ubin(const mp_int *a, unsigned char *buf, size_t maxlen, size_t *written)
+{
+ size_t x, count;
+ mp_err err;
+ mp_int t;
+
+ count = mp_ubin_size(a);
+ if (count > maxlen) {
+ return MP_BUF;
+ }
+
+ if ((err = mp_init_copy(&t, a)) != MP_OKAY) {
+ return err;
+ }
+
+ for (x = count; x --> 0u;) {
+#ifndef MP_8BIT
+ buf[x] = (unsigned char)(t.dp[0] & 255u);
+#else
+ buf[x] = (unsigned char)(t.dp[0] | ((t.dp[1] & 1u) << 7));
+#endif
+ if ((err = mp_div_2d(&t, 8, &t, NULL)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ }
+
+ if (written != NULL) {
+ *written = count;
+ }
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_ubin_size.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_ubin_size.c
new file mode 100644
index 0000000..21230b4
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_ubin_size.c
@@ -0,0 +1,12 @@
+#include "tommath_private.h"
+#ifdef BN_MP_UBIN_SIZE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* get the size for an unsigned equivalent */
+size_t mp_ubin_size(const mp_int *a)
+{
+ size_t size = (size_t)mp_count_bits(a);
+ return (size / 8u) + (((size & 7u) != 0u) ? 1u : 0u);
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_unpack.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_unpack.c
new file mode 100644
index 0000000..d4eb90e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_unpack.c
@@ -0,0 +1,49 @@
+#include "tommath_private.h"
+#ifdef BN_MP_UNPACK_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* based on gmp's mpz_import.
+ * see http://gmplib.org/manual/Integer-Import-and-Export.html
+ */
+mp_err mp_unpack(mp_int *rop, size_t count, mp_order order, size_t size,
+ mp_endian endian, size_t nails, const void *op)
+{
+ mp_err err;
+ size_t odd_nails, nail_bytes, i, j;
+ unsigned char odd_nail_mask;
+
+ mp_zero(rop);
+
+ if (endian == MP_NATIVE_ENDIAN) {
+ MP_GET_ENDIANNESS(endian);
+ }
+
+ odd_nails = (nails % 8u);
+ odd_nail_mask = 0xff;
+ for (i = 0; i < odd_nails; ++i) {
+ odd_nail_mask ^= (unsigned char)(1u << (7u - i));
+ }
+ nail_bytes = nails / 8u;
+
+ for (i = 0; i < count; ++i) {
+ for (j = 0; j < (size - nail_bytes); ++j) {
+ unsigned char byte = *((const unsigned char *)op +
+ (((order == MP_MSB_FIRST) ? i : ((count - 1u) - i)) * size) +
+ ((endian == MP_BIG_ENDIAN) ? (j + nail_bytes) : (((size - 1u) - j) - nail_bytes)));
+
+ if ((err = mp_mul_2d(rop, (j == 0u) ? (int)(8u - odd_nails) : 8, rop)) != MP_OKAY) {
+ return err;
+ }
+
+ rop->dp[0] |= (j == 0u) ? (mp_digit)(byte & odd_nail_mask) : (mp_digit)byte;
+ rop->used += 1;
+ }
+ }
+
+ mp_clamp(rop);
+
+ return MP_OKAY;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_xor.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_xor.c
new file mode 100644
index 0000000..71e7ca1
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_xor.c
@@ -0,0 +1,56 @@
+#include "tommath_private.h"
+#ifdef BN_MP_XOR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* two complement xor */
+mp_err mp_xor(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ int used = MP_MAX(a->used, b->used) + 1, i;
+ mp_err err;
+ mp_digit ac = 1, bc = 1, cc = 1;
+ mp_sign csign = (a->sign != b->sign) ? MP_NEG : MP_ZPOS;
+
+ if (c->alloc < used) {
+ if ((err = mp_grow(c, used)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ for (i = 0; i < used; i++) {
+ mp_digit x, y;
+
+ /* convert to two complement if negative */
+ if (a->sign == MP_NEG) {
+ ac += (i >= a->used) ? MP_MASK : (~a->dp[i] & MP_MASK);
+ x = ac & MP_MASK;
+ ac >>= MP_DIGIT_BIT;
+ } else {
+ x = (i >= a->used) ? 0uL : a->dp[i];
+ }
+
+ /* convert to two complement if negative */
+ if (b->sign == MP_NEG) {
+ bc += (i >= b->used) ? MP_MASK : (~b->dp[i] & MP_MASK);
+ y = bc & MP_MASK;
+ bc >>= MP_DIGIT_BIT;
+ } else {
+ y = (i >= b->used) ? 0uL : b->dp[i];
+ }
+
+ c->dp[i] = x ^ y;
+
+ /* convert to to sign-magnitude if negative */
+ if (csign == MP_NEG) {
+ cc += ~c->dp[i] & MP_MASK;
+ c->dp[i] = cc & MP_MASK;
+ cc >>= MP_DIGIT_BIT;
+ }
+ }
+
+ c->used = used;
+ c->sign = csign;
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_zero.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_zero.c
new file mode 100644
index 0000000..72a255e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_mp_zero.c
@@ -0,0 +1,13 @@
+#include "tommath_private.h"
+#ifdef BN_MP_ZERO_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* set to zero */
+void mp_zero(mp_int *a)
+{
+ a->sign = MP_ZPOS;
+ a->used = 0;
+ MP_ZERO_DIGITS(a->dp, a->alloc);
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_prime_tab.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_prime_tab.c
new file mode 100644
index 0000000..a6c07f8
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_prime_tab.c
@@ -0,0 +1,61 @@
+#include "tommath_private.h"
+#ifdef BN_PRIME_TAB_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+const mp_digit ltm_prime_tab[] = {
+ 0x0002, 0x0003, 0x0005, 0x0007, 0x000B, 0x000D, 0x0011, 0x0013,
+ 0x0017, 0x001D, 0x001F, 0x0025, 0x0029, 0x002B, 0x002F, 0x0035,
+ 0x003B, 0x003D, 0x0043, 0x0047, 0x0049, 0x004F, 0x0053, 0x0059,
+ 0x0061, 0x0065, 0x0067, 0x006B, 0x006D, 0x0071, 0x007F,
+#ifndef MP_8BIT
+ 0x0083,
+ 0x0089, 0x008B, 0x0095, 0x0097, 0x009D, 0x00A3, 0x00A7, 0x00AD,
+ 0x00B3, 0x00B5, 0x00BF, 0x00C1, 0x00C5, 0x00C7, 0x00D3, 0x00DF,
+ 0x00E3, 0x00E5, 0x00E9, 0x00EF, 0x00F1, 0x00FB, 0x0101, 0x0107,
+ 0x010D, 0x010F, 0x0115, 0x0119, 0x011B, 0x0125, 0x0133, 0x0137,
+
+ 0x0139, 0x013D, 0x014B, 0x0151, 0x015B, 0x015D, 0x0161, 0x0167,
+ 0x016F, 0x0175, 0x017B, 0x017F, 0x0185, 0x018D, 0x0191, 0x0199,
+ 0x01A3, 0x01A5, 0x01AF, 0x01B1, 0x01B7, 0x01BB, 0x01C1, 0x01C9,
+ 0x01CD, 0x01CF, 0x01D3, 0x01DF, 0x01E7, 0x01EB, 0x01F3, 0x01F7,
+ 0x01FD, 0x0209, 0x020B, 0x021D, 0x0223, 0x022D, 0x0233, 0x0239,
+ 0x023B, 0x0241, 0x024B, 0x0251, 0x0257, 0x0259, 0x025F, 0x0265,
+ 0x0269, 0x026B, 0x0277, 0x0281, 0x0283, 0x0287, 0x028D, 0x0293,
+ 0x0295, 0x02A1, 0x02A5, 0x02AB, 0x02B3, 0x02BD, 0x02C5, 0x02CF,
+
+ 0x02D7, 0x02DD, 0x02E3, 0x02E7, 0x02EF, 0x02F5, 0x02F9, 0x0301,
+ 0x0305, 0x0313, 0x031D, 0x0329, 0x032B, 0x0335, 0x0337, 0x033B,
+ 0x033D, 0x0347, 0x0355, 0x0359, 0x035B, 0x035F, 0x036D, 0x0371,
+ 0x0373, 0x0377, 0x038B, 0x038F, 0x0397, 0x03A1, 0x03A9, 0x03AD,
+ 0x03B3, 0x03B9, 0x03C7, 0x03CB, 0x03D1, 0x03D7, 0x03DF, 0x03E5,
+ 0x03F1, 0x03F5, 0x03FB, 0x03FD, 0x0407, 0x0409, 0x040F, 0x0419,
+ 0x041B, 0x0425, 0x0427, 0x042D, 0x043F, 0x0443, 0x0445, 0x0449,
+ 0x044F, 0x0455, 0x045D, 0x0463, 0x0469, 0x047F, 0x0481, 0x048B,
+
+ 0x0493, 0x049D, 0x04A3, 0x04A9, 0x04B1, 0x04BD, 0x04C1, 0x04C7,
+ 0x04CD, 0x04CF, 0x04D5, 0x04E1, 0x04EB, 0x04FD, 0x04FF, 0x0503,
+ 0x0509, 0x050B, 0x0511, 0x0515, 0x0517, 0x051B, 0x0527, 0x0529,
+ 0x052F, 0x0551, 0x0557, 0x055D, 0x0565, 0x0577, 0x0581, 0x058F,
+ 0x0593, 0x0595, 0x0599, 0x059F, 0x05A7, 0x05AB, 0x05AD, 0x05B3,
+ 0x05BF, 0x05C9, 0x05CB, 0x05CF, 0x05D1, 0x05D5, 0x05DB, 0x05E7,
+ 0x05F3, 0x05FB, 0x0607, 0x060D, 0x0611, 0x0617, 0x061F, 0x0623,
+ 0x062B, 0x062F, 0x063D, 0x0641, 0x0647, 0x0649, 0x064D, 0x0653
+#endif
+};
+
+#if defined(__GNUC__) && __GNUC__ >= 4
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+const mp_digit *s_mp_prime_tab = ltm_prime_tab;
+#pragma GCC diagnostic pop
+#elif defined(_MSC_VER) && _MSC_VER >= 1500
+#pragma warning(push)
+#pragma warning(disable: 4996)
+const mp_digit *s_mp_prime_tab = ltm_prime_tab;
+#pragma warning(pop)
+#else
+const mp_digit *s_mp_prime_tab = ltm_prime_tab;
+#endif
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_add.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_add.c
new file mode 100644
index 0000000..c946aa8
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_add.c
@@ -0,0 +1,91 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_ADD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* low level addition, based on HAC pp.594, Algorithm 14.7 */
+mp_err s_mp_add(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ const mp_int *x;
+ mp_err err;
+ int olduse, min, max;
+
+ /* find sizes, we let |a| <= |b| which means we have to sort
+ * them. "x" will point to the input with the most digits
+ */
+ if (a->used > b->used) {
+ min = b->used;
+ max = a->used;
+ x = a;
+ } else {
+ min = a->used;
+ max = b->used;
+ x = b;
+ }
+
+ /* init result */
+ if (c->alloc < (max + 1)) {
+ if ((err = mp_grow(c, max + 1)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* get old used digit count and set new one */
+ olduse = c->used;
+ c->used = max + 1;
+
+ {
+ mp_digit u, *tmpa, *tmpb, *tmpc;
+ int i;
+
+ /* alias for digit pointers */
+
+ /* first input */
+ tmpa = a->dp;
+
+ /* second input */
+ tmpb = b->dp;
+
+ /* destination */
+ tmpc = c->dp;
+
+ /* zero the carry */
+ u = 0;
+ for (i = 0; i < min; i++) {
+ /* Compute the sum at one digit, T[i] = A[i] + B[i] + U */
+ *tmpc = *tmpa++ + *tmpb++ + u;
+
+ /* U = carry bit of T[i] */
+ u = *tmpc >> (mp_digit)MP_DIGIT_BIT;
+
+ /* take away carry bit from T[i] */
+ *tmpc++ &= MP_MASK;
+ }
+
+ /* now copy higher words if any, that is in A+B
+ * if A or B has more digits add those in
+ */
+ if (min != max) {
+ for (; i < max; i++) {
+ /* T[i] = X[i] + U */
+ *tmpc = x->dp[i] + u;
+
+ /* U = carry bit of T[i] */
+ u = *tmpc >> (mp_digit)MP_DIGIT_BIT;
+
+ /* take away carry bit from T[i] */
+ *tmpc++ &= MP_MASK;
+ }
+ }
+
+ /* add carry */
+ *tmpc++ = u;
+
+ /* clear digits above oldused */
+ MP_ZERO_DIGITS(tmpc, olduse - c->used);
+ }
+
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_balance_mul.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_balance_mul.c
new file mode 100644
index 0000000..7ece5d7
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_balance_mul.c
@@ -0,0 +1,81 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_BALANCE_MUL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* single-digit multiplication with the smaller number as the single-digit */
+mp_err s_mp_balance_mul(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ int count, len_a, len_b, nblocks, i, j, bsize;
+ mp_int a0, tmp, A, B, r;
+ mp_err err;
+
+ len_a = a->used;
+ len_b = b->used;
+
+ nblocks = MP_MAX(a->used, b->used) / MP_MIN(a->used, b->used);
+ bsize = MP_MIN(a->used, b->used) ;
+
+ if ((err = mp_init_size(&a0, bsize + 2)) != MP_OKAY) {
+ return err;
+ }
+ if ((err = mp_init_multi(&tmp, &r, NULL)) != MP_OKAY) {
+ mp_clear(&a0);
+ return err;
+ }
+
+ /* Make sure that A is the larger one*/
+ if (len_a < len_b) {
+ B = *a;
+ A = *b;
+ } else {
+ A = *a;
+ B = *b;
+ }
+
+ for (i = 0, j=0; i < nblocks; i++) {
+ /* Cut a slice off of a */
+ a0.used = 0;
+ for (count = 0; count < bsize; count++) {
+ a0.dp[count] = A.dp[ j++ ];
+ a0.used++;
+ }
+ mp_clamp(&a0);
+ /* Multiply with b */
+ if ((err = mp_mul(&a0, &B, &tmp)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ /* Shift tmp to the correct position */
+ if ((err = mp_lshd(&tmp, bsize * i)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ /* Add to output. No carry needed */
+ if ((err = mp_add(&r, &tmp, &r)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ }
+ /* The left-overs; there are always left-overs */
+ if (j < A.used) {
+ a0.used = 0;
+ for (count = 0; j < A.used; count++) {
+ a0.dp[count] = A.dp[ j++ ];
+ a0.used++;
+ }
+ mp_clamp(&a0);
+ if ((err = mp_mul(&a0, &B, &tmp)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if ((err = mp_lshd(&tmp, bsize * i)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if ((err = mp_add(&r, &tmp, &r)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ }
+
+ mp_exch(&r,c);
+LBL_ERR:
+ mp_clear_multi(&a0, &tmp, &r,NULL);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_exptmod.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_exptmod.c
new file mode 100644
index 0000000..c3bfa95
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_exptmod.c
@@ -0,0 +1,198 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_EXPTMOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#ifdef MP_LOW_MEM
+# define TAB_SIZE 32
+# define MAX_WINSIZE 5
+#else
+# define TAB_SIZE 256
+# define MAX_WINSIZE 0
+#endif
+
+mp_err s_mp_exptmod(const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y, int redmode)
+{
+ mp_int M[TAB_SIZE], res, mu;
+ mp_digit buf;
+ mp_err err;
+ int bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
+ mp_err(*redux)(mp_int *x, const mp_int *m, const mp_int *mu);
+
+ /* find window size */
+ x = mp_count_bits(X);
+ if (x <= 7) {
+ winsize = 2;
+ } else if (x <= 36) {
+ winsize = 3;
+ } else if (x <= 140) {
+ winsize = 4;
+ } else if (x <= 450) {
+ winsize = 5;
+ } else if (x <= 1303) {
+ winsize = 6;
+ } else if (x <= 3529) {
+ winsize = 7;
+ } else {
+ winsize = 8;
+ }
+
+ winsize = MAX_WINSIZE ? MP_MIN(MAX_WINSIZE, winsize) : winsize;
+
+ /* init M array */
+ /* init first cell */
+ if ((err = mp_init(&M[1])) != MP_OKAY) {
+ return err;
+ }
+
+ /* now init the second half of the array */
+ for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
+ if ((err = mp_init(&M[x])) != MP_OKAY) {
+ for (y = 1<<(winsize-1); y < x; y++) {
+ mp_clear(&M[y]);
+ }
+ mp_clear(&M[1]);
+ return err;
+ }
+ }
+
+ /* create mu, used for Barrett reduction */
+ if ((err = mp_init(&mu)) != MP_OKAY) goto LBL_M;
+
+ if (redmode == 0) {
+ if ((err = mp_reduce_setup(&mu, P)) != MP_OKAY) goto LBL_MU;
+ redux = mp_reduce;
+ } else {
+ if ((err = mp_reduce_2k_setup_l(P, &mu)) != MP_OKAY) goto LBL_MU;
+ redux = mp_reduce_2k_l;
+ }
+
+ /* create M table
+ *
+ * The M table contains powers of the base,
+ * e.g. M[x] = G**x mod P
+ *
+ * The first half of the table is not
+ * computed though accept for M[0] and M[1]
+ */
+ if ((err = mp_mod(G, P, &M[1])) != MP_OKAY) goto LBL_MU;
+
+ /* compute the value at M[1<<(winsize-1)] by squaring
+ * M[1] (winsize-1) times
+ */
+ if ((err = mp_copy(&M[1], &M[(size_t)1 << (winsize - 1)])) != MP_OKAY) goto LBL_MU;
+
+ for (x = 0; x < (winsize - 1); x++) {
+ /* square it */
+ if ((err = mp_sqr(&M[(size_t)1 << (winsize - 1)],
+ &M[(size_t)1 << (winsize - 1)])) != MP_OKAY) goto LBL_MU;
+
+ /* reduce modulo P */
+ if ((err = redux(&M[(size_t)1 << (winsize - 1)], P, &mu)) != MP_OKAY) goto LBL_MU;
+ }
+
+ /* create upper table, that is M[x] = M[x-1] * M[1] (mod P)
+ * for x = (2**(winsize - 1) + 1) to (2**winsize - 1)
+ */
+ for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
+ if ((err = mp_mul(&M[x - 1], &M[1], &M[x])) != MP_OKAY) goto LBL_MU;
+ if ((err = redux(&M[x], P, &mu)) != MP_OKAY) goto LBL_MU;
+ }
+
+ /* setup result */
+ if ((err = mp_init(&res)) != MP_OKAY) goto LBL_MU;
+ mp_set(&res, 1uL);
+
+ /* set initial mode and bit cnt */
+ mode = 0;
+ bitcnt = 1;
+ buf = 0;
+ digidx = X->used - 1;
+ bitcpy = 0;
+ bitbuf = 0;
+
+ for (;;) {
+ /* grab next digit as required */
+ if (--bitcnt == 0) {
+ /* if digidx == -1 we are out of digits */
+ if (digidx == -1) {
+ break;
+ }
+ /* read next digit and reset the bitcnt */
+ buf = X->dp[digidx--];
+ bitcnt = (int)MP_DIGIT_BIT;
+ }
+
+ /* grab the next msb from the exponent */
+ y = (buf >> (mp_digit)(MP_DIGIT_BIT - 1)) & 1uL;
+ buf <<= (mp_digit)1;
+
+ /* if the bit is zero and mode == 0 then we ignore it
+ * These represent the leading zero bits before the first 1 bit
+ * in the exponent. Technically this opt is not required but it
+ * does lower the # of trivial squaring/reductions used
+ */
+ if ((mode == 0) && (y == 0)) {
+ continue;
+ }
+
+ /* if the bit is zero and mode == 1 then we square */
+ if ((mode == 1) && (y == 0)) {
+ if ((err = mp_sqr(&res, &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, &mu)) != MP_OKAY) goto LBL_RES;
+ continue;
+ }
+
+ /* else we add it to the window */
+ bitbuf |= (y << (winsize - ++bitcpy));
+ mode = 2;
+
+ if (bitcpy == winsize) {
+ /* ok window is filled so square as required and multiply */
+ /* square first */
+ for (x = 0; x < winsize; x++) {
+ if ((err = mp_sqr(&res, &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, &mu)) != MP_OKAY) goto LBL_RES;
+ }
+
+ /* then multiply */
+ if ((err = mp_mul(&res, &M[bitbuf], &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, &mu)) != MP_OKAY) goto LBL_RES;
+
+ /* empty window and reset */
+ bitcpy = 0;
+ bitbuf = 0;
+ mode = 1;
+ }
+ }
+
+ /* if bits remain then square/multiply */
+ if ((mode == 2) && (bitcpy > 0)) {
+ /* square then multiply if the bit is set */
+ for (x = 0; x < bitcpy; x++) {
+ if ((err = mp_sqr(&res, &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, &mu)) != MP_OKAY) goto LBL_RES;
+
+ bitbuf <<= 1;
+ if ((bitbuf & (1 << winsize)) != 0) {
+ /* then multiply */
+ if ((err = mp_mul(&res, &M[1], &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, &mu)) != MP_OKAY) goto LBL_RES;
+ }
+ }
+ }
+
+ mp_exch(&res, Y);
+ err = MP_OKAY;
+LBL_RES:
+ mp_clear(&res);
+LBL_MU:
+ mp_clear(&mu);
+LBL_M:
+ mp_clear(&M[1]);
+ for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
+ mp_clear(&M[x]);
+ }
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_exptmod_fast.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_exptmod_fast.c
new file mode 100644
index 0000000..682ded8
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_exptmod_fast.c
@@ -0,0 +1,254 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_EXPTMOD_FAST_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* computes Y == G**X mod P, HAC pp.616, Algorithm 14.85
+ *
+ * Uses a left-to-right k-ary sliding window to compute the modular exponentiation.
+ * The value of k changes based on the size of the exponent.
+ *
+ * Uses Montgomery or Diminished Radix reduction [whichever appropriate]
+ */
+
+#ifdef MP_LOW_MEM
+# define TAB_SIZE 32
+# define MAX_WINSIZE 5
+#else
+# define TAB_SIZE 256
+# define MAX_WINSIZE 0
+#endif
+
+mp_err s_mp_exptmod_fast(const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y, int redmode)
+{
+ mp_int M[TAB_SIZE], res;
+ mp_digit buf, mp;
+ int bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
+ mp_err err;
+
+ /* use a pointer to the reduction algorithm. This allows us to use
+ * one of many reduction algorithms without modding the guts of
+ * the code with if statements everywhere.
+ */
+ mp_err(*redux)(mp_int *x, const mp_int *n, mp_digit rho);
+
+ /* find window size */
+ x = mp_count_bits(X);
+ if (x <= 7) {
+ winsize = 2;
+ } else if (x <= 36) {
+ winsize = 3;
+ } else if (x <= 140) {
+ winsize = 4;
+ } else if (x <= 450) {
+ winsize = 5;
+ } else if (x <= 1303) {
+ winsize = 6;
+ } else if (x <= 3529) {
+ winsize = 7;
+ } else {
+ winsize = 8;
+ }
+
+ winsize = MAX_WINSIZE ? MP_MIN(MAX_WINSIZE, winsize) : winsize;
+
+ /* init M array */
+ /* init first cell */
+ if ((err = mp_init_size(&M[1], P->alloc)) != MP_OKAY) {
+ return err;
+ }
+
+ /* now init the second half of the array */
+ for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
+ if ((err = mp_init_size(&M[x], P->alloc)) != MP_OKAY) {
+ for (y = 1<<(winsize-1); y < x; y++) {
+ mp_clear(&M[y]);
+ }
+ mp_clear(&M[1]);
+ return err;
+ }
+ }
+
+ /* determine and setup reduction code */
+ if (redmode == 0) {
+ if (MP_HAS(MP_MONTGOMERY_SETUP)) {
+ /* now setup montgomery */
+ if ((err = mp_montgomery_setup(P, &mp)) != MP_OKAY) goto LBL_M;
+ } else {
+ err = MP_VAL;
+ goto LBL_M;
+ }
+
+ /* automatically pick the comba one if available (saves quite a few calls/ifs) */
+ if (MP_HAS(S_MP_MONTGOMERY_REDUCE_FAST) &&
+ (((P->used * 2) + 1) < MP_WARRAY) &&
+ (P->used < MP_MAXFAST)) {
+ redux = s_mp_montgomery_reduce_fast;
+ } else if (MP_HAS(MP_MONTGOMERY_REDUCE)) {
+ /* use slower baseline Montgomery method */
+ redux = mp_montgomery_reduce;
+ } else {
+ err = MP_VAL;
+ goto LBL_M;
+ }
+ } else if (redmode == 1) {
+ if (MP_HAS(MP_DR_SETUP) && MP_HAS(MP_DR_REDUCE)) {
+ /* setup DR reduction for moduli of the form B**k - b */
+ mp_dr_setup(P, &mp);
+ redux = mp_dr_reduce;
+ } else {
+ err = MP_VAL;
+ goto LBL_M;
+ }
+ } else if (MP_HAS(MP_REDUCE_2K_SETUP) && MP_HAS(MP_REDUCE_2K)) {
+ /* setup DR reduction for moduli of the form 2**k - b */
+ if ((err = mp_reduce_2k_setup(P, &mp)) != MP_OKAY) goto LBL_M;
+ redux = mp_reduce_2k;
+ } else {
+ err = MP_VAL;
+ goto LBL_M;
+ }
+
+ /* setup result */
+ if ((err = mp_init_size(&res, P->alloc)) != MP_OKAY) goto LBL_M;
+
+ /* create M table
+ *
+
+ *
+ * The first half of the table is not computed though accept for M[0] and M[1]
+ */
+
+ if (redmode == 0) {
+ if (MP_HAS(MP_MONTGOMERY_CALC_NORMALIZATION)) {
+ /* now we need R mod m */
+ if ((err = mp_montgomery_calc_normalization(&res, P)) != MP_OKAY) goto LBL_RES;
+
+ /* now set M[1] to G * R mod m */
+ if ((err = mp_mulmod(G, &res, P, &M[1])) != MP_OKAY) goto LBL_RES;
+ } else {
+ err = MP_VAL;
+ goto LBL_RES;
+ }
+ } else {
+ mp_set(&res, 1uL);
+ if ((err = mp_mod(G, P, &M[1])) != MP_OKAY) goto LBL_RES;
+ }
+
+ /* compute the value at M[1<<(winsize-1)] by squaring M[1] (winsize-1) times */
+ if ((err = mp_copy(&M[1], &M[(size_t)1 << (winsize - 1)])) != MP_OKAY) goto LBL_RES;
+
+ for (x = 0; x < (winsize - 1); x++) {
+ if ((err = mp_sqr(&M[(size_t)1 << (winsize - 1)], &M[(size_t)1 << (winsize - 1)])) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&M[(size_t)1 << (winsize - 1)], P, mp)) != MP_OKAY) goto LBL_RES;
+ }
+
+ /* create upper table */
+ for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
+ if ((err = mp_mul(&M[x - 1], &M[1], &M[x])) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&M[x], P, mp)) != MP_OKAY) goto LBL_RES;
+ }
+
+ /* set initial mode and bit cnt */
+ mode = 0;
+ bitcnt = 1;
+ buf = 0;
+ digidx = X->used - 1;
+ bitcpy = 0;
+ bitbuf = 0;
+
+ for (;;) {
+ /* grab next digit as required */
+ if (--bitcnt == 0) {
+ /* if digidx == -1 we are out of digits so break */
+ if (digidx == -1) {
+ break;
+ }
+ /* read next digit and reset bitcnt */
+ buf = X->dp[digidx--];
+ bitcnt = (int)MP_DIGIT_BIT;
+ }
+
+ /* grab the next msb from the exponent */
+ y = (mp_digit)(buf >> (MP_DIGIT_BIT - 1)) & 1uL;
+ buf <<= (mp_digit)1;
+
+ /* if the bit is zero and mode == 0 then we ignore it
+ * These represent the leading zero bits before the first 1 bit
+ * in the exponent. Technically this opt is not required but it
+ * does lower the # of trivial squaring/reductions used
+ */
+ if ((mode == 0) && (y == 0)) {
+ continue;
+ }
+
+ /* if the bit is zero and mode == 1 then we square */
+ if ((mode == 1) && (y == 0)) {
+ if ((err = mp_sqr(&res, &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, mp)) != MP_OKAY) goto LBL_RES;
+ continue;
+ }
+
+ /* else we add it to the window */
+ bitbuf |= (y << (winsize - ++bitcpy));
+ mode = 2;
+
+ if (bitcpy == winsize) {
+ /* ok window is filled so square as required and multiply */
+ /* square first */
+ for (x = 0; x < winsize; x++) {
+ if ((err = mp_sqr(&res, &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, mp)) != MP_OKAY) goto LBL_RES;
+ }
+
+ /* then multiply */
+ if ((err = mp_mul(&res, &M[bitbuf], &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, mp)) != MP_OKAY) goto LBL_RES;
+
+ /* empty window and reset */
+ bitcpy = 0;
+ bitbuf = 0;
+ mode = 1;
+ }
+ }
+
+ /* if bits remain then square/multiply */
+ if ((mode == 2) && (bitcpy > 0)) {
+ /* square then multiply if the bit is set */
+ for (x = 0; x < bitcpy; x++) {
+ if ((err = mp_sqr(&res, &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, mp)) != MP_OKAY) goto LBL_RES;
+
+ /* get next bit of the window */
+ bitbuf <<= 1;
+ if ((bitbuf & (1 << winsize)) != 0) {
+ /* then multiply */
+ if ((err = mp_mul(&res, &M[1], &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, mp)) != MP_OKAY) goto LBL_RES;
+ }
+ }
+ }
+
+ if (redmode == 0) {
+ /* fixup result if Montgomery reduction is used
+ * recall that any value in a Montgomery system is
+ * actually multiplied by R mod n. So we have
+ * to reduce one more time to cancel out the factor
+ * of R.
+ */
+ if ((err = redux(&res, P, mp)) != MP_OKAY) goto LBL_RES;
+ }
+
+ /* swap res with Y */
+ mp_exch(&res, Y);
+ err = MP_OKAY;
+LBL_RES:
+ mp_clear(&res);
+LBL_M:
+ mp_clear(&M[1]);
+ for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
+ mp_clear(&M[x]);
+ }
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_get_bit.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_get_bit.c
new file mode 100644
index 0000000..28598df
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_get_bit.c
@@ -0,0 +1,21 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_GET_BIT_C
+
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Get bit at position b and return MP_YES if the bit is 1, MP_NO if it is 0 */
+mp_bool s_mp_get_bit(const mp_int *a, unsigned int b)
+{
+ mp_digit bit;
+ int limb = (int)(b / MP_DIGIT_BIT);
+
+ if (limb >= a->used) {
+ return MP_NO;
+ }
+
+ bit = (mp_digit)1 << (b % MP_DIGIT_BIT);
+ return ((a->dp[limb] & bit) != 0u) ? MP_YES : MP_NO;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_invmod_fast.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_invmod_fast.c
new file mode 100644
index 0000000..677d7ab
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_invmod_fast.c
@@ -0,0 +1,118 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_INVMOD_FAST_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* computes the modular inverse via binary extended euclidean algorithm,
+ * that is c = 1/a mod b
+ *
+ * Based on slow invmod except this is optimized for the case where b is
+ * odd as per HAC Note 14.64 on pp. 610
+ */
+mp_err s_mp_invmod_fast(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_int x, y, u, v, B, D;
+ mp_sign neg;
+ mp_err err;
+
+ /* 2. [modified] b must be odd */
+ if (MP_IS_EVEN(b)) {
+ return MP_VAL;
+ }
+
+ /* init all our temps */
+ if ((err = mp_init_multi(&x, &y, &u, &v, &B, &D, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* x == modulus, y == value to invert */
+ if ((err = mp_copy(b, &x)) != MP_OKAY) goto LBL_ERR;
+
+ /* we need y = |a| */
+ if ((err = mp_mod(a, b, &y)) != MP_OKAY) goto LBL_ERR;
+
+ /* if one of x,y is zero return an error! */
+ if (MP_IS_ZERO(&x) || MP_IS_ZERO(&y)) {
+ err = MP_VAL;
+ goto LBL_ERR;
+ }
+
+ /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
+ if ((err = mp_copy(&x, &u)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_copy(&y, &v)) != MP_OKAY) goto LBL_ERR;
+ mp_set(&D, 1uL);
+
+top:
+ /* 4. while u is even do */
+ while (MP_IS_EVEN(&u)) {
+ /* 4.1 u = u/2 */
+ if ((err = mp_div_2(&u, &u)) != MP_OKAY) goto LBL_ERR;
+
+ /* 4.2 if B is odd then */
+ if (MP_IS_ODD(&B)) {
+ if ((err = mp_sub(&B, &x, &B)) != MP_OKAY) goto LBL_ERR;
+ }
+ /* B = B/2 */
+ if ((err = mp_div_2(&B, &B)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* 5. while v is even do */
+ while (MP_IS_EVEN(&v)) {
+ /* 5.1 v = v/2 */
+ if ((err = mp_div_2(&v, &v)) != MP_OKAY) goto LBL_ERR;
+
+ /* 5.2 if D is odd then */
+ if (MP_IS_ODD(&D)) {
+ /* D = (D-x)/2 */
+ if ((err = mp_sub(&D, &x, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+ /* D = D/2 */
+ if ((err = mp_div_2(&D, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* 6. if u >= v then */
+ if (mp_cmp(&u, &v) != MP_LT) {
+ /* u = u - v, B = B - D */
+ if ((err = mp_sub(&u, &v, &u)) != MP_OKAY) goto LBL_ERR;
+
+ if ((err = mp_sub(&B, &D, &B)) != MP_OKAY) goto LBL_ERR;
+ } else {
+ /* v - v - u, D = D - B */
+ if ((err = mp_sub(&v, &u, &v)) != MP_OKAY) goto LBL_ERR;
+
+ if ((err = mp_sub(&D, &B, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* if not zero goto step 4 */
+ if (!MP_IS_ZERO(&u)) {
+ goto top;
+ }
+
+ /* now a = C, b = D, gcd == g*v */
+
+ /* if v != 1 then there is no inverse */
+ if (mp_cmp_d(&v, 1uL) != MP_EQ) {
+ err = MP_VAL;
+ goto LBL_ERR;
+ }
+
+ /* b is now the inverse */
+ neg = a->sign;
+ while (D.sign == MP_NEG) {
+ if ((err = mp_add(&D, b, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* too big */
+ while (mp_cmp_mag(&D, b) != MP_LT) {
+ if ((err = mp_sub(&D, b, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ mp_exch(&D, c);
+ c->sign = neg;
+ err = MP_OKAY;
+
+LBL_ERR:
+ mp_clear_multi(&x, &y, &u, &v, &B, &D, NULL);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_invmod_slow.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_invmod_slow.c
new file mode 100644
index 0000000..4c5db33
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_invmod_slow.c
@@ -0,0 +1,119 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_INVMOD_SLOW_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* hac 14.61, pp608 */
+mp_err s_mp_invmod_slow(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_int x, y, u, v, A, B, C, D;
+ mp_err err;
+
+ /* b cannot be negative */
+ if ((b->sign == MP_NEG) || MP_IS_ZERO(b)) {
+ return MP_VAL;
+ }
+
+ /* init temps */
+ if ((err = mp_init_multi(&x, &y, &u, &v,
+ &A, &B, &C, &D, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* x = a, y = b */
+ if ((err = mp_mod(a, b, &x)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_copy(b, &y)) != MP_OKAY) goto LBL_ERR;
+
+ /* 2. [modified] if x,y are both even then return an error! */
+ if (MP_IS_EVEN(&x) && MP_IS_EVEN(&y)) {
+ err = MP_VAL;
+ goto LBL_ERR;
+ }
+
+ /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
+ if ((err = mp_copy(&x, &u)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_copy(&y, &v)) != MP_OKAY) goto LBL_ERR;
+ mp_set(&A, 1uL);
+ mp_set(&D, 1uL);
+
+top:
+ /* 4. while u is even do */
+ while (MP_IS_EVEN(&u)) {
+ /* 4.1 u = u/2 */
+ if ((err = mp_div_2(&u, &u)) != MP_OKAY) goto LBL_ERR;
+
+ /* 4.2 if A or B is odd then */
+ if (MP_IS_ODD(&A) || MP_IS_ODD(&B)) {
+ /* A = (A+y)/2, B = (B-x)/2 */
+ if ((err = mp_add(&A, &y, &A)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_sub(&B, &x, &B)) != MP_OKAY) goto LBL_ERR;
+ }
+ /* A = A/2, B = B/2 */
+ if ((err = mp_div_2(&A, &A)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_div_2(&B, &B)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* 5. while v is even do */
+ while (MP_IS_EVEN(&v)) {
+ /* 5.1 v = v/2 */
+ if ((err = mp_div_2(&v, &v)) != MP_OKAY) goto LBL_ERR;
+
+ /* 5.2 if C or D is odd then */
+ if (MP_IS_ODD(&C) || MP_IS_ODD(&D)) {
+ /* C = (C+y)/2, D = (D-x)/2 */
+ if ((err = mp_add(&C, &y, &C)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_sub(&D, &x, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+ /* C = C/2, D = D/2 */
+ if ((err = mp_div_2(&C, &C)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_div_2(&D, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* 6. if u >= v then */
+ if (mp_cmp(&u, &v) != MP_LT) {
+ /* u = u - v, A = A - C, B = B - D */
+ if ((err = mp_sub(&u, &v, &u)) != MP_OKAY) goto LBL_ERR;
+
+ if ((err = mp_sub(&A, &C, &A)) != MP_OKAY) goto LBL_ERR;
+
+ if ((err = mp_sub(&B, &D, &B)) != MP_OKAY) goto LBL_ERR;
+ } else {
+ /* v - v - u, C = C - A, D = D - B */
+ if ((err = mp_sub(&v, &u, &v)) != MP_OKAY) goto LBL_ERR;
+
+ if ((err = mp_sub(&C, &A, &C)) != MP_OKAY) goto LBL_ERR;
+
+ if ((err = mp_sub(&D, &B, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* if not zero goto step 4 */
+ if (!MP_IS_ZERO(&u)) {
+ goto top;
+ }
+
+ /* now a = C, b = D, gcd == g*v */
+
+ /* if v != 1 then there is no inverse */
+ if (mp_cmp_d(&v, 1uL) != MP_EQ) {
+ err = MP_VAL;
+ goto LBL_ERR;
+ }
+
+ /* if its too low */
+ while (mp_cmp_d(&C, 0uL) == MP_LT) {
+ if ((err = mp_add(&C, b, &C)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* too big */
+ while (mp_cmp_mag(&C, b) != MP_LT) {
+ if ((err = mp_sub(&C, b, &C)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* C is now the inverse */
+ mp_exch(&C, c);
+ err = MP_OKAY;
+LBL_ERR:
+ mp_clear_multi(&x, &y, &u, &v, &A, &B, &C, &D, NULL);
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_karatsuba_mul.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_karatsuba_mul.c
new file mode 100644
index 0000000..85899fb
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_karatsuba_mul.c
@@ -0,0 +1,174 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_KARATSUBA_MUL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* c = |a| * |b| using Karatsuba Multiplication using
+ * three half size multiplications
+ *
+ * Let B represent the radix [e.g. 2**MP_DIGIT_BIT] and
+ * let n represent half of the number of digits in
+ * the min(a,b)
+ *
+ * a = a1 * B**n + a0
+ * b = b1 * B**n + b0
+ *
+ * Then, a * b =>
+ a1b1 * B**2n + ((a1 + a0)(b1 + b0) - (a0b0 + a1b1)) * B + a0b0
+ *
+ * Note that a1b1 and a0b0 are used twice and only need to be
+ * computed once. So in total three half size (half # of
+ * digit) multiplications are performed, a0b0, a1b1 and
+ * (a1+b1)(a0+b0)
+ *
+ * Note that a multiplication of half the digits requires
+ * 1/4th the number of single precision multiplications so in
+ * total after one call 25% of the single precision multiplications
+ * are saved. Note also that the call to mp_mul can end up back
+ * in this function if the a0, a1, b0, or b1 are above the threshold.
+ * This is known as divide-and-conquer and leads to the famous
+ * O(N**lg(3)) or O(N**1.584) work which is asymptopically lower than
+ * the standard O(N**2) that the baseline/comba methods use.
+ * Generally though the overhead of this method doesn't pay off
+ * until a certain size (N ~ 80) is reached.
+ */
+mp_err s_mp_karatsuba_mul(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_int x0, x1, y0, y1, t1, x0y0, x1y1;
+ int B;
+ mp_err err = MP_MEM; /* default the return code to an error */
+
+ /* min # of digits */
+ B = MP_MIN(a->used, b->used);
+
+ /* now divide in two */
+ B = B >> 1;
+
+ /* init copy all the temps */
+ if (mp_init_size(&x0, B) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (mp_init_size(&x1, a->used - B) != MP_OKAY) {
+ goto X0;
+ }
+ if (mp_init_size(&y0, B) != MP_OKAY) {
+ goto X1;
+ }
+ if (mp_init_size(&y1, b->used - B) != MP_OKAY) {
+ goto Y0;
+ }
+
+ /* init temps */
+ if (mp_init_size(&t1, B * 2) != MP_OKAY) {
+ goto Y1;
+ }
+ if (mp_init_size(&x0y0, B * 2) != MP_OKAY) {
+ goto T1;
+ }
+ if (mp_init_size(&x1y1, B * 2) != MP_OKAY) {
+ goto X0Y0;
+ }
+
+ /* now shift the digits */
+ x0.used = y0.used = B;
+ x1.used = a->used - B;
+ y1.used = b->used - B;
+
+ {
+ int x;
+ mp_digit *tmpa, *tmpb, *tmpx, *tmpy;
+
+ /* we copy the digits directly instead of using higher level functions
+ * since we also need to shift the digits
+ */
+ tmpa = a->dp;
+ tmpb = b->dp;
+
+ tmpx = x0.dp;
+ tmpy = y0.dp;
+ for (x = 0; x < B; x++) {
+ *tmpx++ = *tmpa++;
+ *tmpy++ = *tmpb++;
+ }
+
+ tmpx = x1.dp;
+ for (x = B; x < a->used; x++) {
+ *tmpx++ = *tmpa++;
+ }
+
+ tmpy = y1.dp;
+ for (x = B; x < b->used; x++) {
+ *tmpy++ = *tmpb++;
+ }
+ }
+
+ /* only need to clamp the lower words since by definition the
+ * upper words x1/y1 must have a known number of digits
+ */
+ mp_clamp(&x0);
+ mp_clamp(&y0);
+
+ /* now calc the products x0y0 and x1y1 */
+ /* after this x0 is no longer required, free temp [x0==t2]! */
+ if (mp_mul(&x0, &y0, &x0y0) != MP_OKAY) {
+ goto X1Y1; /* x0y0 = x0*y0 */
+ }
+ if (mp_mul(&x1, &y1, &x1y1) != MP_OKAY) {
+ goto X1Y1; /* x1y1 = x1*y1 */
+ }
+
+ /* now calc x1+x0 and y1+y0 */
+ if (s_mp_add(&x1, &x0, &t1) != MP_OKAY) {
+ goto X1Y1; /* t1 = x1 - x0 */
+ }
+ if (s_mp_add(&y1, &y0, &x0) != MP_OKAY) {
+ goto X1Y1; /* t2 = y1 - y0 */
+ }
+ if (mp_mul(&t1, &x0, &t1) != MP_OKAY) {
+ goto X1Y1; /* t1 = (x1 + x0) * (y1 + y0) */
+ }
+
+ /* add x0y0 */
+ if (mp_add(&x0y0, &x1y1, &x0) != MP_OKAY) {
+ goto X1Y1; /* t2 = x0y0 + x1y1 */
+ }
+ if (s_mp_sub(&t1, &x0, &t1) != MP_OKAY) {
+ goto X1Y1; /* t1 = (x1+x0)*(y1+y0) - (x1y1 + x0y0) */
+ }
+
+ /* shift by B */
+ if (mp_lshd(&t1, B) != MP_OKAY) {
+ goto X1Y1; /* t1 = (x0y0 + x1y1 - (x1-x0)*(y1-y0))<<B */
+ }
+ if (mp_lshd(&x1y1, B * 2) != MP_OKAY) {
+ goto X1Y1; /* x1y1 = x1y1 << 2*B */
+ }
+
+ if (mp_add(&x0y0, &t1, &t1) != MP_OKAY) {
+ goto X1Y1; /* t1 = x0y0 + t1 */
+ }
+ if (mp_add(&t1, &x1y1, c) != MP_OKAY) {
+ goto X1Y1; /* t1 = x0y0 + t1 + x1y1 */
+ }
+
+ /* Algorithm succeeded set the return code to MP_OKAY */
+ err = MP_OKAY;
+
+X1Y1:
+ mp_clear(&x1y1);
+X0Y0:
+ mp_clear(&x0y0);
+T1:
+ mp_clear(&t1);
+Y1:
+ mp_clear(&y1);
+Y0:
+ mp_clear(&y0);
+X1:
+ mp_clear(&x1);
+X0:
+ mp_clear(&x0);
+LBL_ERR:
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_karatsuba_sqr.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_karatsuba_sqr.c
new file mode 100644
index 0000000..f132d07
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_karatsuba_sqr.c
@@ -0,0 +1,110 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_KARATSUBA_SQR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Karatsuba squaring, computes b = a*a using three
+ * half size squarings
+ *
+ * See comments of karatsuba_mul for details. It
+ * is essentially the same algorithm but merely
+ * tuned to perform recursive squarings.
+ */
+mp_err s_mp_karatsuba_sqr(const mp_int *a, mp_int *b)
+{
+ mp_int x0, x1, t1, t2, x0x0, x1x1;
+ int B;
+ mp_err err = MP_MEM;
+
+ /* min # of digits */
+ B = a->used;
+
+ /* now divide in two */
+ B = B >> 1;
+
+ /* init copy all the temps */
+ if (mp_init_size(&x0, B) != MP_OKAY)
+ goto LBL_ERR;
+ if (mp_init_size(&x1, a->used - B) != MP_OKAY)
+ goto X0;
+
+ /* init temps */
+ if (mp_init_size(&t1, a->used * 2) != MP_OKAY)
+ goto X1;
+ if (mp_init_size(&t2, a->used * 2) != MP_OKAY)
+ goto T1;
+ if (mp_init_size(&x0x0, B * 2) != MP_OKAY)
+ goto T2;
+ if (mp_init_size(&x1x1, (a->used - B) * 2) != MP_OKAY)
+ goto X0X0;
+
+ {
+ int x;
+ mp_digit *dst, *src;
+
+ src = a->dp;
+
+ /* now shift the digits */
+ dst = x0.dp;
+ for (x = 0; x < B; x++) {
+ *dst++ = *src++;
+ }
+
+ dst = x1.dp;
+ for (x = B; x < a->used; x++) {
+ *dst++ = *src++;
+ }
+ }
+
+ x0.used = B;
+ x1.used = a->used - B;
+
+ mp_clamp(&x0);
+
+ /* now calc the products x0*x0 and x1*x1 */
+ if (mp_sqr(&x0, &x0x0) != MP_OKAY)
+ goto X1X1; /* x0x0 = x0*x0 */
+ if (mp_sqr(&x1, &x1x1) != MP_OKAY)
+ goto X1X1; /* x1x1 = x1*x1 */
+
+ /* now calc (x1+x0)**2 */
+ if (s_mp_add(&x1, &x0, &t1) != MP_OKAY)
+ goto X1X1; /* t1 = x1 - x0 */
+ if (mp_sqr(&t1, &t1) != MP_OKAY)
+ goto X1X1; /* t1 = (x1 - x0) * (x1 - x0) */
+
+ /* add x0y0 */
+ if (s_mp_add(&x0x0, &x1x1, &t2) != MP_OKAY)
+ goto X1X1; /* t2 = x0x0 + x1x1 */
+ if (s_mp_sub(&t1, &t2, &t1) != MP_OKAY)
+ goto X1X1; /* t1 = (x1+x0)**2 - (x0x0 + x1x1) */
+
+ /* shift by B */
+ if (mp_lshd(&t1, B) != MP_OKAY)
+ goto X1X1; /* t1 = (x0x0 + x1x1 - (x1-x0)*(x1-x0))<<B */
+ if (mp_lshd(&x1x1, B * 2) != MP_OKAY)
+ goto X1X1; /* x1x1 = x1x1 << 2*B */
+
+ if (mp_add(&x0x0, &t1, &t1) != MP_OKAY)
+ goto X1X1; /* t1 = x0x0 + t1 */
+ if (mp_add(&t1, &x1x1, b) != MP_OKAY)
+ goto X1X1; /* t1 = x0x0 + t1 + x1x1 */
+
+ err = MP_OKAY;
+
+X1X1:
+ mp_clear(&x1x1);
+X0X0:
+ mp_clear(&x0x0);
+T2:
+ mp_clear(&t2);
+T1:
+ mp_clear(&t1);
+X1:
+ mp_clear(&x1);
+X0:
+ mp_clear(&x0);
+LBL_ERR:
+ return err;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_montgomery_reduce_fast.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_montgomery_reduce_fast.c
new file mode 100644
index 0000000..3f0c672
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_montgomery_reduce_fast.c
@@ -0,0 +1,159 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_MONTGOMERY_REDUCE_FAST_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* computes xR**-1 == x (mod N) via Montgomery Reduction
+ *
+ * This is an optimized implementation of montgomery_reduce
+ * which uses the comba method to quickly calculate the columns of the
+ * reduction.
+ *
+ * Based on Algorithm 14.32 on pp.601 of HAC.
+*/
+mp_err s_mp_montgomery_reduce_fast(mp_int *x, const mp_int *n, mp_digit rho)
+{
+ int ix, olduse;
+ mp_err err;
+ mp_word W[MP_WARRAY];
+
+ if (x->used > MP_WARRAY) {
+ return MP_VAL;
+ }
+
+ /* get old used count */
+ olduse = x->used;
+
+ /* grow a as required */
+ if (x->alloc < (n->used + 1)) {
+ if ((err = mp_grow(x, n->used + 1)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* first we have to get the digits of the input into
+ * an array of double precision words W[...]
+ */
+ {
+ mp_word *_W;
+ mp_digit *tmpx;
+
+ /* alias for the W[] array */
+ _W = W;
+
+ /* alias for the digits of x*/
+ tmpx = x->dp;
+
+ /* copy the digits of a into W[0..a->used-1] */
+ for (ix = 0; ix < x->used; ix++) {
+ *_W++ = *tmpx++;
+ }
+
+ /* zero the high words of W[a->used..m->used*2] */
+ if (ix < ((n->used * 2) + 1)) {
+ MP_ZERO_BUFFER(_W, sizeof(mp_word) * (size_t)(((n->used * 2) + 1) - ix));
+ }
+ }
+
+ /* now we proceed to zero successive digits
+ * from the least significant upwards
+ */
+ for (ix = 0; ix < n->used; ix++) {
+ /* mu = ai * m' mod b
+ *
+ * We avoid a double precision multiplication (which isn't required)
+ * by casting the value down to a mp_digit. Note this requires
+ * that W[ix-1] have the carry cleared (see after the inner loop)
+ */
+ mp_digit mu;
+ mu = ((W[ix] & MP_MASK) * rho) & MP_MASK;
+
+ /* a = a + mu * m * b**i
+ *
+ * This is computed in place and on the fly. The multiplication
+ * by b**i is handled by offseting which columns the results
+ * are added to.
+ *
+ * Note the comba method normally doesn't handle carries in the
+ * inner loop In this case we fix the carry from the previous
+ * column since the Montgomery reduction requires digits of the
+ * result (so far) [see above] to work. This is
+ * handled by fixing up one carry after the inner loop. The
+ * carry fixups are done in order so after these loops the
+ * first m->used words of W[] have the carries fixed
+ */
+ {
+ int iy;
+ mp_digit *tmpn;
+ mp_word *_W;
+
+ /* alias for the digits of the modulus */
+ tmpn = n->dp;
+
+ /* Alias for the columns set by an offset of ix */
+ _W = W + ix;
+
+ /* inner loop */
+ for (iy = 0; iy < n->used; iy++) {
+ *_W++ += (mp_word)mu * (mp_word)*tmpn++;
+ }
+ }
+
+ /* now fix carry for next digit, W[ix+1] */
+ W[ix + 1] += W[ix] >> (mp_word)MP_DIGIT_BIT;
+ }
+
+ /* now we have to propagate the carries and
+ * shift the words downward [all those least
+ * significant digits we zeroed].
+ */
+ {
+ mp_digit *tmpx;
+ mp_word *_W, *_W1;
+
+ /* nox fix rest of carries */
+
+ /* alias for current word */
+ _W1 = W + ix;
+
+ /* alias for next word, where the carry goes */
+ _W = W + ++ix;
+
+ for (; ix < ((n->used * 2) + 1); ix++) {
+ *_W++ += *_W1++ >> (mp_word)MP_DIGIT_BIT;
+ }
+
+ /* copy out, A = A/b**n
+ *
+ * The result is A/b**n but instead of converting from an
+ * array of mp_word to mp_digit than calling mp_rshd
+ * we just copy them in the right order
+ */
+
+ /* alias for destination word */
+ tmpx = x->dp;
+
+ /* alias for shifted double precision result */
+ _W = W + n->used;
+
+ for (ix = 0; ix < (n->used + 1); ix++) {
+ *tmpx++ = *_W++ & (mp_word)MP_MASK;
+ }
+
+ /* zero oldused digits, if the input a was larger than
+ * m->used+1 we'll have to clear the digits
+ */
+ MP_ZERO_DIGITS(tmpx, olduse - ix);
+ }
+
+ /* set the max used and clamp */
+ x->used = n->used + 1;
+ mp_clamp(x);
+
+ /* if A >= m then A = A - m */
+ if (mp_cmp_mag(x, n) != MP_LT) {
+ return s_mp_sub(x, n, x);
+ }
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_digs.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_digs.c
new file mode 100644
index 0000000..64509d4
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_digs.c
@@ -0,0 +1,74 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_MUL_DIGS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* multiplies |a| * |b| and only computes upto digs digits of result
+ * HAC pp. 595, Algorithm 14.12 Modified so you can control how
+ * many digits of output are created.
+ */
+mp_err s_mp_mul_digs(const mp_int *a, const mp_int *b, mp_int *c, int digs)
+{
+ mp_int t;
+ mp_err err;
+ int pa, pb, ix, iy;
+ mp_digit u;
+ mp_word r;
+ mp_digit tmpx, *tmpt, *tmpy;
+
+ /* can we use the fast multiplier? */
+ if ((digs < MP_WARRAY) &&
+ (MP_MIN(a->used, b->used) < MP_MAXFAST)) {
+ return s_mp_mul_digs_fast(a, b, c, digs);
+ }
+
+ if ((err = mp_init_size(&t, digs)) != MP_OKAY) {
+ return err;
+ }
+ t.used = digs;
+
+ /* compute the digits of the product directly */
+ pa = a->used;
+ for (ix = 0; ix < pa; ix++) {
+ /* set the carry to zero */
+ u = 0;
+
+ /* limit ourselves to making digs digits of output */
+ pb = MP_MIN(b->used, digs - ix);
+
+ /* setup some aliases */
+ /* copy of the digit from a used within the nested loop */
+ tmpx = a->dp[ix];
+
+ /* an alias for the destination shifted ix places */
+ tmpt = t.dp + ix;
+
+ /* an alias for the digits of b */
+ tmpy = b->dp;
+
+ /* compute the columns of the output and propagate the carry */
+ for (iy = 0; iy < pb; iy++) {
+ /* compute the column as a mp_word */
+ r = (mp_word)*tmpt +
+ ((mp_word)tmpx * (mp_word)*tmpy++) +
+ (mp_word)u;
+
+ /* the new column is the lower part of the result */
+ *tmpt++ = (mp_digit)(r & (mp_word)MP_MASK);
+
+ /* get the carry word from the result */
+ u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
+ }
+ /* set carry if it is placed below digs */
+ if ((ix + iy) < digs) {
+ *tmpt = u;
+ }
+ }
+
+ mp_clamp(&t);
+ mp_exch(&t, c);
+
+ mp_clear(&t);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_digs_fast.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_digs_fast.c
new file mode 100644
index 0000000..b2a287b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_digs_fast.c
@@ -0,0 +1,90 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_MUL_DIGS_FAST_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Fast (comba) multiplier
+ *
+ * This is the fast column-array [comba] multiplier. It is
+ * designed to compute the columns of the product first
+ * then handle the carries afterwards. This has the effect
+ * of making the nested loops that compute the columns very
+ * simple and schedulable on super-scalar processors.
+ *
+ * This has been modified to produce a variable number of
+ * digits of output so if say only a half-product is required
+ * you don't have to compute the upper half (a feature
+ * required for fast Barrett reduction).
+ *
+ * Based on Algorithm 14.12 on pp.595 of HAC.
+ *
+ */
+mp_err s_mp_mul_digs_fast(const mp_int *a, const mp_int *b, mp_int *c, int digs)
+{
+ int olduse, pa, ix, iz;
+ mp_err err;
+ mp_digit W[MP_WARRAY];
+ mp_word _W;
+
+ /* grow the destination as required */
+ if (c->alloc < digs) {
+ if ((err = mp_grow(c, digs)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* number of output digits to produce */
+ pa = MP_MIN(digs, a->used + b->used);
+
+ /* clear the carry */
+ _W = 0;
+ for (ix = 0; ix < pa; ix++) {
+ int tx, ty;
+ int iy;
+ mp_digit *tmpx, *tmpy;
+
+ /* get offsets into the two bignums */
+ ty = MP_MIN(b->used-1, ix);
+ tx = ix - ty;
+
+ /* setup temp aliases */
+ tmpx = a->dp + tx;
+ tmpy = b->dp + ty;
+
+ /* this is the number of times the loop will iterrate, essentially
+ while (tx++ < a->used && ty-- >= 0) { ... }
+ */
+ iy = MP_MIN(a->used-tx, ty+1);
+
+ /* execute loop */
+ for (iz = 0; iz < iy; ++iz) {
+ _W += (mp_word)*tmpx++ * (mp_word)*tmpy--;
+
+ }
+
+ /* store term */
+ W[ix] = (mp_digit)_W & MP_MASK;
+
+ /* make next carry */
+ _W = _W >> (mp_word)MP_DIGIT_BIT;
+ }
+
+ /* setup dest */
+ olduse = c->used;
+ c->used = pa;
+
+ {
+ mp_digit *tmpc;
+ tmpc = c->dp;
+ for (ix = 0; ix < pa; ix++) {
+ /* now extract the previous digit [below the carry] */
+ *tmpc++ = W[ix];
+ }
+
+ /* clear unused digits [that existed in the old copy of c] */
+ MP_ZERO_DIGITS(tmpc, olduse - ix);
+ }
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_high_digs.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_high_digs.c
new file mode 100644
index 0000000..2bb2a50
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_high_digs.c
@@ -0,0 +1,64 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_MUL_HIGH_DIGS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* multiplies |a| * |b| and does not compute the lower digs digits
+ * [meant to get the higher part of the product]
+ */
+mp_err s_mp_mul_high_digs(const mp_int *a, const mp_int *b, mp_int *c, int digs)
+{
+ mp_int t;
+ int pa, pb, ix, iy;
+ mp_err err;
+ mp_digit u;
+ mp_word r;
+ mp_digit tmpx, *tmpt, *tmpy;
+
+ /* can we use the fast multiplier? */
+ if (MP_HAS(S_MP_MUL_HIGH_DIGS_FAST)
+ && ((a->used + b->used + 1) < MP_WARRAY)
+ && (MP_MIN(a->used, b->used) < MP_MAXFAST)) {
+ return s_mp_mul_high_digs_fast(a, b, c, digs);
+ }
+
+ if ((err = mp_init_size(&t, a->used + b->used + 1)) != MP_OKAY) {
+ return err;
+ }
+ t.used = a->used + b->used + 1;
+
+ pa = a->used;
+ pb = b->used;
+ for (ix = 0; ix < pa; ix++) {
+ /* clear the carry */
+ u = 0;
+
+ /* left hand side of A[ix] * B[iy] */
+ tmpx = a->dp[ix];
+
+ /* alias to the address of where the digits will be stored */
+ tmpt = &(t.dp[digs]);
+
+ /* alias for where to read the right hand side from */
+ tmpy = b->dp + (digs - ix);
+
+ for (iy = digs - ix; iy < pb; iy++) {
+ /* calculate the double precision result */
+ r = (mp_word)*tmpt +
+ ((mp_word)tmpx * (mp_word)*tmpy++) +
+ (mp_word)u;
+
+ /* get the lower part */
+ *tmpt++ = (mp_digit)(r & (mp_word)MP_MASK);
+
+ /* carry the carry */
+ u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
+ }
+ *tmpt = u;
+ }
+ mp_clamp(&t);
+ mp_exch(&t, c);
+ mp_clear(&t);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_high_digs_fast.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_high_digs_fast.c
new file mode 100644
index 0000000..a2c4fb6
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_mul_high_digs_fast.c
@@ -0,0 +1,81 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_MUL_HIGH_DIGS_FAST_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* this is a modified version of fast_s_mul_digs that only produces
+ * output digits *above* digs. See the comments for fast_s_mul_digs
+ * to see how it works.
+ *
+ * This is used in the Barrett reduction since for one of the multiplications
+ * only the higher digits were needed. This essentially halves the work.
+ *
+ * Based on Algorithm 14.12 on pp.595 of HAC.
+ */
+mp_err s_mp_mul_high_digs_fast(const mp_int *a, const mp_int *b, mp_int *c, int digs)
+{
+ int olduse, pa, ix, iz;
+ mp_err err;
+ mp_digit W[MP_WARRAY];
+ mp_word _W;
+
+ /* grow the destination as required */
+ pa = a->used + b->used;
+ if (c->alloc < pa) {
+ if ((err = mp_grow(c, pa)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* number of output digits to produce */
+ pa = a->used + b->used;
+ _W = 0;
+ for (ix = digs; ix < pa; ix++) {
+ int tx, ty, iy;
+ mp_digit *tmpx, *tmpy;
+
+ /* get offsets into the two bignums */
+ ty = MP_MIN(b->used-1, ix);
+ tx = ix - ty;
+
+ /* setup temp aliases */
+ tmpx = a->dp + tx;
+ tmpy = b->dp + ty;
+
+ /* this is the number of times the loop will iterrate, essentially its
+ while (tx++ < a->used && ty-- >= 0) { ... }
+ */
+ iy = MP_MIN(a->used-tx, ty+1);
+
+ /* execute loop */
+ for (iz = 0; iz < iy; iz++) {
+ _W += (mp_word)*tmpx++ * (mp_word)*tmpy--;
+ }
+
+ /* store term */
+ W[ix] = (mp_digit)_W & MP_MASK;
+
+ /* make next carry */
+ _W = _W >> (mp_word)MP_DIGIT_BIT;
+ }
+
+ /* setup dest */
+ olduse = c->used;
+ c->used = pa;
+
+ {
+ mp_digit *tmpc;
+
+ tmpc = c->dp + digs;
+ for (ix = digs; ix < pa; ix++) {
+ /* now extract the previous digit [below the carry] */
+ *tmpc++ = W[ix];
+ }
+
+ /* clear unused digits [that existed in the old copy of c] */
+ MP_ZERO_DIGITS(tmpc, olduse - ix);
+ }
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_prime_is_divisible.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_prime_is_divisible.c
new file mode 100644
index 0000000..ffd5093
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_prime_is_divisible.c
@@ -0,0 +1,35 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_PRIME_IS_DIVISIBLE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* determines if an integers is divisible by one
+ * of the first PRIME_SIZE primes or not
+ *
+ * sets result to 0 if not, 1 if yes
+ */
+mp_err s_mp_prime_is_divisible(const mp_int *a, mp_bool *result)
+{
+ int ix;
+ mp_err err;
+ mp_digit res;
+
+ /* default to not */
+ *result = MP_NO;
+
+ for (ix = 0; ix < PRIVATE_MP_PRIME_TAB_SIZE; ix++) {
+ /* what is a mod LBL_prime_tab[ix] */
+ if ((err = mp_mod_d(a, s_mp_prime_tab[ix], &res)) != MP_OKAY) {
+ return err;
+ }
+
+ /* is the residue zero? */
+ if (res == 0u) {
+ *result = MP_YES;
+ return MP_OKAY;
+ }
+ }
+
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_rand_jenkins.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_rand_jenkins.c
new file mode 100644
index 0000000..da0771c
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_rand_jenkins.c
@@ -0,0 +1,52 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_RAND_JENKINS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Bob Jenkins' http://burtleburtle.net/bob/rand/smallprng.html */
+/* Chosen for speed and a good "mix" */
+typedef struct {
+ uint64_t a;
+ uint64_t b;
+ uint64_t c;
+ uint64_t d;
+} ranctx;
+
+static ranctx jenkins_x;
+
+#define rot(x,k) (((x)<<(k))|((x)>>(64-(k))))
+static uint64_t s_rand_jenkins_val(void)
+{
+ uint64_t e = jenkins_x.a - rot(jenkins_x.b, 7);
+ jenkins_x.a = jenkins_x.b ^ rot(jenkins_x.c, 13);
+ jenkins_x.b = jenkins_x.c + rot(jenkins_x.d, 37);
+ jenkins_x.c = jenkins_x.d + e;
+ jenkins_x.d = e + jenkins_x.a;
+ return jenkins_x.d;
+}
+
+void s_mp_rand_jenkins_init(uint64_t seed)
+{
+ uint64_t i;
+ jenkins_x.a = 0xf1ea5eedULL;
+ jenkins_x.b = jenkins_x.c = jenkins_x.d = seed;
+ for (i = 0uLL; i < 20uLL; ++i) {
+ (void)s_rand_jenkins_val();
+ }
+}
+
+mp_err s_mp_rand_jenkins(void *p, size_t n)
+{
+ char *q = (char *)p;
+ while (n > 0u) {
+ int i;
+ uint64_t x = s_rand_jenkins_val();
+ for (i = 0; (i < 8) && (n > 0u); ++i, --n) {
+ *q++ = (char)(x & 0xFFuLL);
+ x >>= 8;
+ }
+ }
+ return MP_OKAY;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_rand_platform.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_rand_platform.c
new file mode 100644
index 0000000..79879c3
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_rand_platform.c
@@ -0,0 +1,168 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_RAND_PLATFORM_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* First the OS-specific special cases
+ * - *BSD
+ * - Windows
+ */
+#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
+#define BN_S_READ_ARC4RANDOM_C
+static mp_err s_read_arc4random(void *p, size_t n)
+{
+ arc4random_buf(p, n);
+ return MP_OKAY;
+}
+#endif
+
+#if defined(_WIN32) || defined(_WIN32_WCE)
+#define BN_S_READ_WINCSP_C
+
+#ifndef _WIN32_WINNT
+#define _WIN32_WINNT 0x0400
+#endif
+#ifdef _WIN32_WCE
+#define UNDER_CE
+#define ARM
+#endif
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <wincrypt.h>
+
+static mp_err s_read_wincsp(void *p, size_t n)
+{
+ static HCRYPTPROV hProv = 0;
+ if (hProv == 0) {
+ HCRYPTPROV h = 0;
+ if (!CryptAcquireContext(&h, NULL, MS_DEF_PROV, PROV_RSA_FULL,
+ (CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET)) &&
+ !CryptAcquireContext(&h, NULL, MS_DEF_PROV, PROV_RSA_FULL,
+ CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET | CRYPT_NEWKEYSET)) {
+ return MP_ERR;
+ }
+ hProv = h;
+ }
+ return CryptGenRandom(hProv, (DWORD)n, (BYTE *)p) == TRUE ? MP_OKAY : MP_ERR;
+}
+#endif /* WIN32 */
+
+#if !defined(BN_S_READ_WINCSP_C) && defined(__linux__) && defined(__GLIBC_PREREQ)
+#if __GLIBC_PREREQ(2, 25)
+#define BN_S_READ_GETRANDOM_C
+#include <sys/random.h>
+#include <errno.h>
+
+static mp_err s_read_getrandom(void *p, size_t n)
+{
+ char *q = (char *)p;
+ while (n > 0u) {
+ ssize_t ret = getrandom(q, n, 0);
+ if (ret < 0) {
+ if (errno == EINTR) {
+ continue;
+ }
+ return MP_ERR;
+ }
+ q += ret;
+ n -= (size_t)ret;
+ }
+ return MP_OKAY;
+}
+#endif
+#endif
+
+/* We assume all platforms besides windows provide "/dev/urandom".
+ * In case yours doesn't, define MP_NO_DEV_URANDOM at compile-time.
+ */
+#if !defined(BN_S_READ_WINCSP_C) && !defined(MP_NO_DEV_URANDOM)
+#define BN_S_READ_URANDOM_C
+#ifndef MP_DEV_URANDOM
+#define MP_DEV_URANDOM "/dev/urandom"
+#endif
+#include <fcntl.h>
+#include <errno.h>
+#include <unistd.h>
+
+static mp_err s_read_urandom(void *p, size_t n)
+{
+ int fd;
+ char *q = (char *)p;
+
+ do {
+ fd = open(MP_DEV_URANDOM, O_RDONLY);
+ } while ((fd == -1) && (errno == EINTR));
+ if (fd == -1) return MP_ERR;
+
+ while (n > 0u) {
+ ssize_t ret = read(fd, q, n);
+ if (ret < 0) {
+ if (errno == EINTR) {
+ continue;
+ }
+ close(fd);
+ return MP_ERR;
+ }
+ q += ret;
+ n -= (size_t)ret;
+ }
+
+ close(fd);
+ return MP_OKAY;
+}
+#endif
+
+#if defined(MP_PRNG_ENABLE_LTM_RNG)
+#define BN_S_READ_LTM_RNG
+unsigned long (*ltm_rng)(unsigned char *out, unsigned long outlen, void (*callback)(void));
+void (*ltm_rng_callback)(void);
+
+static mp_err s_read_ltm_rng(void *p, size_t n)
+{
+ unsigned long res;
+ if (ltm_rng == NULL) return MP_ERR;
+ res = ltm_rng(p, n, ltm_rng_callback);
+ if (res != n) return MP_ERR;
+ return MP_OKAY;
+}
+#endif
+
+#ifdef BN_S_READ_ARC4RANDOM_C
+mp_err s_read_arc4random(void *p, size_t n);
+#endif
+#ifdef BN_S_READ_WINCSP_C
+mp_err s_read_wincsp(void *p, size_t n);
+#endif
+#ifdef BN_S_READ_GETRANDOM_C
+mp_err s_read_getrandom(void *p, size_t n);
+#endif
+#ifdef BN_S_READ_URANDOM_C
+mp_err s_read_urandom(void *p, size_t n);
+#endif
+#ifdef BN_S_READ_LTM_RNG
+mp_err s_read_ltm_rng(void *p, size_t n);
+#endif
+
+mp_err s_mp_rand_platform(void *p, size_t n)
+{
+ mp_err err = MP_ERR;
+#ifdef BN_S_READ_ARC4RANDOM_C
+ if ((err != MP_OKAY) && MP_HAS(S_READ_ARC4RANDOM)) err = s_read_arc4random(p, n);
+#endif
+#ifdef BN_S_READ_WINCSP_C
+ if ((err != MP_OKAY) && MP_HAS(S_READ_WINCSP)) err = s_read_wincsp(p, n);
+#endif
+#ifdef BN_S_READ_GETRANDOM_C
+ if ((err != MP_OKAY) && MP_HAS(S_READ_GETRANDOM)) err = s_read_getrandom(p, n);
+#endif
+#ifdef BN_S_READ_URANDOM_C
+ if ((err != MP_OKAY) && MP_HAS(S_READ_URANDOM)) err = s_read_urandom(p, n);
+#endif
+#ifdef BN_S_READ_LTM_RNG
+ if ((err != MP_OKAY) && MP_HAS(S_READ_LTM_RNG)) err = s_read_ltm_rng(p, n);
+#endif
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_reverse.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_reverse.c
new file mode 100644
index 0000000..c549e60
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_reverse.c
@@ -0,0 +1,22 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_REVERSE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* reverse an array, used for radix code */
+void s_mp_reverse(unsigned char *s, size_t len)
+{
+ size_t ix, iy;
+ unsigned char t;
+
+ ix = 0u;
+ iy = len - 1u;
+ while (ix < iy) {
+ t = s[ix];
+ s[ix] = s[iy];
+ s[iy] = t;
+ ++ix;
+ --iy;
+ }
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_sqr.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_sqr.c
new file mode 100644
index 0000000..505c9f0
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_sqr.c
@@ -0,0 +1,69 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_SQR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */
+mp_err s_mp_sqr(const mp_int *a, mp_int *b)
+{
+ mp_int t;
+ int ix, iy, pa;
+ mp_err err;
+ mp_word r;
+ mp_digit u, tmpx, *tmpt;
+
+ pa = a->used;
+ if ((err = mp_init_size(&t, (2 * pa) + 1)) != MP_OKAY) {
+ return err;
+ }
+
+ /* default used is maximum possible size */
+ t.used = (2 * pa) + 1;
+
+ for (ix = 0; ix < pa; ix++) {
+ /* first calculate the digit at 2*ix */
+ /* calculate double precision result */
+ r = (mp_word)t.dp[2*ix] +
+ ((mp_word)a->dp[ix] * (mp_word)a->dp[ix]);
+
+ /* store lower part in result */
+ t.dp[ix+ix] = (mp_digit)(r & (mp_word)MP_MASK);
+
+ /* get the carry */
+ u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
+
+ /* left hand side of A[ix] * A[iy] */
+ tmpx = a->dp[ix];
+
+ /* alias for where to store the results */
+ tmpt = t.dp + ((2 * ix) + 1);
+
+ for (iy = ix + 1; iy < pa; iy++) {
+ /* first calculate the product */
+ r = (mp_word)tmpx * (mp_word)a->dp[iy];
+
+ /* now calculate the double precision result, note we use
+ * addition instead of *2 since it's easier to optimize
+ */
+ r = (mp_word)*tmpt + r + r + (mp_word)u;
+
+ /* store lower part */
+ *tmpt++ = (mp_digit)(r & (mp_word)MP_MASK);
+
+ /* get carry */
+ u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
+ }
+ /* propagate upwards */
+ while (u != 0uL) {
+ r = (mp_word)*tmpt + (mp_word)u;
+ *tmpt++ = (mp_digit)(r & (mp_word)MP_MASK);
+ u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
+ }
+ }
+
+ mp_clamp(&t);
+ mp_exch(&t, b);
+ mp_clear(&t);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_sqr_fast.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_sqr_fast.c
new file mode 100644
index 0000000..4a8a891
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_sqr_fast.c
@@ -0,0 +1,97 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_SQR_FAST_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* the jist of squaring...
+ * you do like mult except the offset of the tmpx [one that
+ * starts closer to zero] can't equal the offset of tmpy.
+ * So basically you set up iy like before then you min it with
+ * (ty-tx) so that it never happens. You double all those
+ * you add in the inner loop
+
+After that loop you do the squares and add them in.
+*/
+
+mp_err s_mp_sqr_fast(const mp_int *a, mp_int *b)
+{
+ int olduse, pa, ix, iz;
+ mp_digit W[MP_WARRAY], *tmpx;
+ mp_word W1;
+ mp_err err;
+
+ /* grow the destination as required */
+ pa = a->used + a->used;
+ if (b->alloc < pa) {
+ if ((err = mp_grow(b, pa)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* number of output digits to produce */
+ W1 = 0;
+ for (ix = 0; ix < pa; ix++) {
+ int tx, ty, iy;
+ mp_word _W;
+ mp_digit *tmpy;
+
+ /* clear counter */
+ _W = 0;
+
+ /* get offsets into the two bignums */
+ ty = MP_MIN(a->used-1, ix);
+ tx = ix - ty;
+
+ /* setup temp aliases */
+ tmpx = a->dp + tx;
+ tmpy = a->dp + ty;
+
+ /* this is the number of times the loop will iterrate, essentially
+ while (tx++ < a->used && ty-- >= 0) { ... }
+ */
+ iy = MP_MIN(a->used-tx, ty+1);
+
+ /* now for squaring tx can never equal ty
+ * we halve the distance since they approach at a rate of 2x
+ * and we have to round because odd cases need to be executed
+ */
+ iy = MP_MIN(iy, ((ty-tx)+1)>>1);
+
+ /* execute loop */
+ for (iz = 0; iz < iy; iz++) {
+ _W += (mp_word)*tmpx++ * (mp_word)*tmpy--;
+ }
+
+ /* double the inner product and add carry */
+ _W = _W + _W + W1;
+
+ /* even columns have the square term in them */
+ if (((unsigned)ix & 1u) == 0u) {
+ _W += (mp_word)a->dp[ix>>1] * (mp_word)a->dp[ix>>1];
+ }
+
+ /* store it */
+ W[ix] = (mp_digit)_W & MP_MASK;
+
+ /* make next carry */
+ W1 = _W >> (mp_word)MP_DIGIT_BIT;
+ }
+
+ /* setup dest */
+ olduse = b->used;
+ b->used = a->used+a->used;
+
+ {
+ mp_digit *tmpb;
+ tmpb = b->dp;
+ for (ix = 0; ix < pa; ix++) {
+ *tmpb++ = W[ix] & MP_MASK;
+ }
+
+ /* clear unused digits [that existed in the old copy of c] */
+ MP_ZERO_DIGITS(tmpb, olduse - ix);
+ }
+ mp_clamp(b);
+ return MP_OKAY;
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_sub.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_sub.c
new file mode 100644
index 0000000..5672dab
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_sub.c
@@ -0,0 +1,71 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_SUB_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* low level subtraction (assumes |a| > |b|), HAC pp.595 Algorithm 14.9 */
+mp_err s_mp_sub(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ int olduse, min, max;
+ mp_err err;
+
+ /* find sizes */
+ min = b->used;
+ max = a->used;
+
+ /* init result */
+ if (c->alloc < max) {
+ if ((err = mp_grow(c, max)) != MP_OKAY) {
+ return err;
+ }
+ }
+ olduse = c->used;
+ c->used = max;
+
+ {
+ mp_digit u, *tmpa, *tmpb, *tmpc;
+ int i;
+
+ /* alias for digit pointers */
+ tmpa = a->dp;
+ tmpb = b->dp;
+ tmpc = c->dp;
+
+ /* set carry to zero */
+ u = 0;
+ for (i = 0; i < min; i++) {
+ /* T[i] = A[i] - B[i] - U */
+ *tmpc = (*tmpa++ - *tmpb++) - u;
+
+ /* U = carry bit of T[i]
+ * Note this saves performing an AND operation since
+ * if a carry does occur it will propagate all the way to the
+ * MSB. As a result a single shift is enough to get the carry
+ */
+ u = *tmpc >> (MP_SIZEOF_BITS(mp_digit) - 1u);
+
+ /* Clear carry from T[i] */
+ *tmpc++ &= MP_MASK;
+ }
+
+ /* now copy higher words if any, e.g. if A has more digits than B */
+ for (; i < max; i++) {
+ /* T[i] = A[i] - U */
+ *tmpc = *tmpa++ - u;
+
+ /* U = carry bit of T[i] */
+ u = *tmpc >> (MP_SIZEOF_BITS(mp_digit) - 1u);
+
+ /* Clear carry from T[i] */
+ *tmpc++ &= MP_MASK;
+ }
+
+ /* clear digits above used (since we may not have grown result above) */
+ MP_ZERO_DIGITS(tmpc, olduse - c->used);
+ }
+
+ mp_clamp(c);
+ return MP_OKAY;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_toom_mul.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_toom_mul.c
new file mode 100644
index 0000000..86901b0
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_toom_mul.c
@@ -0,0 +1,215 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_TOOM_MUL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* multiplication using the Toom-Cook 3-way algorithm
+ *
+ * Much more complicated than Karatsuba but has a lower
+ * asymptotic running time of O(N**1.464). This algorithm is
+ * only particularly useful on VERY large inputs
+ * (we're talking 1000s of digits here...).
+*/
+
+/*
+ This file contains code from J. Arndt's book "Matters Computational"
+ and the accompanying FXT-library with permission of the author.
+*/
+
+/*
+ Setup from
+
+ Chung, Jaewook, and M. Anwar Hasan. "Asymmetric squaring formulae."
+ 18th IEEE Symposium on Computer Arithmetic (ARITH'07). IEEE, 2007.
+
+ The interpolation from above needed one temporary variable more
+ than the interpolation here:
+
+ Bodrato, Marco, and Alberto Zanoni. "What about Toom-Cook matrices optimality."
+ Centro Vito Volterra Universita di Roma Tor Vergata (2006)
+*/
+
+mp_err s_mp_toom_mul(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_int S1, S2, T1, a0, a1, a2, b0, b1, b2;
+ int B, count;
+ mp_err err;
+
+ /* init temps */
+ if ((err = mp_init_multi(&S1, &S2, &T1, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* B */
+ B = MP_MIN(a->used, b->used) / 3;
+
+ /** a = a2 * x^2 + a1 * x + a0; */
+ if ((err = mp_init_size(&a0, B)) != MP_OKAY) goto LBL_ERRa0;
+
+ for (count = 0; count < B; count++) {
+ a0.dp[count] = a->dp[count];
+ a0.used++;
+ }
+ mp_clamp(&a0);
+ if ((err = mp_init_size(&a1, B)) != MP_OKAY) goto LBL_ERRa1;
+ for (; count < (2 * B); count++) {
+ a1.dp[count - B] = a->dp[count];
+ a1.used++;
+ }
+ mp_clamp(&a1);
+ if ((err = mp_init_size(&a2, B + (a->used - (3 * B)))) != MP_OKAY) goto LBL_ERRa2;
+ for (; count < a->used; count++) {
+ a2.dp[count - (2 * B)] = a->dp[count];
+ a2.used++;
+ }
+ mp_clamp(&a2);
+
+ /** b = b2 * x^2 + b1 * x + b0; */
+ if ((err = mp_init_size(&b0, B)) != MP_OKAY) goto LBL_ERRb0;
+ for (count = 0; count < B; count++) {
+ b0.dp[count] = b->dp[count];
+ b0.used++;
+ }
+ mp_clamp(&b0);
+ if ((err = mp_init_size(&b1, B)) != MP_OKAY) goto LBL_ERRb1;
+ for (; count < (2 * B); count++) {
+ b1.dp[count - B] = b->dp[count];
+ b1.used++;
+ }
+ mp_clamp(&b1);
+ if ((err = mp_init_size(&b2, B + (b->used - (3 * B)))) != MP_OKAY) goto LBL_ERRb2;
+ for (; count < b->used; count++) {
+ b2.dp[count - (2 * B)] = b->dp[count];
+ b2.used++;
+ }
+ mp_clamp(&b2);
+
+ /** \\ S1 = (a2+a1+a0) * (b2+b1+b0); */
+ /** T1 = a2 + a1; */
+ if ((err = mp_add(&a2, &a1, &T1)) != MP_OKAY) goto LBL_ERR;
+
+ /** S2 = T1 + a0; */
+ if ((err = mp_add(&T1, &a0, &S2)) != MP_OKAY) goto LBL_ERR;
+
+ /** c = b2 + b1; */
+ if ((err = mp_add(&b2, &b1, c)) != MP_OKAY) goto LBL_ERR;
+
+ /** S1 = c + b0; */
+ if ((err = mp_add(c, &b0, &S1)) != MP_OKAY) goto LBL_ERR;
+
+ /** S1 = S1 * S2; */
+ if ((err = mp_mul(&S1, &S2, &S1)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\S2 = (4*a2+2*a1+a0) * (4*b2+2*b1+b0); */
+ /** T1 = T1 + a2; */
+ if ((err = mp_add(&T1, &a2, &T1)) != MP_OKAY) goto LBL_ERR;
+
+ /** T1 = T1 << 1; */
+ if ((err = mp_mul_2(&T1, &T1)) != MP_OKAY) goto LBL_ERR;
+
+ /** T1 = T1 + a0; */
+ if ((err = mp_add(&T1, &a0, &T1)) != MP_OKAY) goto LBL_ERR;
+
+ /** c = c + b2; */
+ if ((err = mp_add(c, &b2, c)) != MP_OKAY) goto LBL_ERR;
+
+ /** c = c << 1; */
+ if ((err = mp_mul_2(c, c)) != MP_OKAY) goto LBL_ERR;
+
+ /** c = c + b0; */
+ if ((err = mp_add(c, &b0, c)) != MP_OKAY) goto LBL_ERR;
+
+ /** S2 = T1 * c; */
+ if ((err = mp_mul(&T1, c, &S2)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\S3 = (a2-a1+a0) * (b2-b1+b0); */
+ /** a1 = a2 - a1; */
+ if ((err = mp_sub(&a2, &a1, &a1)) != MP_OKAY) goto LBL_ERR;
+
+ /** a1 = a1 + a0; */
+ if ((err = mp_add(&a1, &a0, &a1)) != MP_OKAY) goto LBL_ERR;
+
+ /** b1 = b2 - b1; */
+ if ((err = mp_sub(&b2, &b1, &b1)) != MP_OKAY) goto LBL_ERR;
+
+ /** b1 = b1 + b0; */
+ if ((err = mp_add(&b1, &b0, &b1)) != MP_OKAY) goto LBL_ERR;
+
+ /** a1 = a1 * b1; */
+ if ((err = mp_mul(&a1, &b1, &a1)) != MP_OKAY) goto LBL_ERR;
+
+ /** b1 = a2 * b2; */
+ if ((err = mp_mul(&a2, &b2, &b1)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\S2 = (S2 - S3)/3; */
+ /** S2 = S2 - a1; */
+ if ((err = mp_sub(&S2, &a1, &S2)) != MP_OKAY) goto LBL_ERR;
+
+ /** S2 = S2 / 3; \\ this is an exact division */
+ if ((err = mp_div_3(&S2, &S2, NULL)) != MP_OKAY) goto LBL_ERR;
+
+ /** a1 = S1 - a1; */
+ if ((err = mp_sub(&S1, &a1, &a1)) != MP_OKAY) goto LBL_ERR;
+
+ /** a1 = a1 >> 1; */
+ if ((err = mp_div_2(&a1, &a1)) != MP_OKAY) goto LBL_ERR;
+
+ /** a0 = a0 * b0; */
+ if ((err = mp_mul(&a0, &b0, &a0)) != MP_OKAY) goto LBL_ERR;
+
+ /** S1 = S1 - a0; */
+ if ((err = mp_sub(&S1, &a0, &S1)) != MP_OKAY) goto LBL_ERR;
+
+ /** S2 = S2 - S1; */
+ if ((err = mp_sub(&S2, &S1, &S2)) != MP_OKAY) goto LBL_ERR;
+
+ /** S2 = S2 >> 1; */
+ if ((err = mp_div_2(&S2, &S2)) != MP_OKAY) goto LBL_ERR;
+
+ /** S1 = S1 - a1; */
+ if ((err = mp_sub(&S1, &a1, &S1)) != MP_OKAY) goto LBL_ERR;
+
+ /** S1 = S1 - b1; */
+ if ((err = mp_sub(&S1, &b1, &S1)) != MP_OKAY) goto LBL_ERR;
+
+ /** T1 = b1 << 1; */
+ if ((err = mp_mul_2(&b1, &T1)) != MP_OKAY) goto LBL_ERR;
+
+ /** S2 = S2 - T1; */
+ if ((err = mp_sub(&S2, &T1, &S2)) != MP_OKAY) goto LBL_ERR;
+
+ /** a1 = a1 - S2; */
+ if ((err = mp_sub(&a1, &S2, &a1)) != MP_OKAY) goto LBL_ERR;
+
+
+ /** P = b1*x^4+ S2*x^3+ S1*x^2+ a1*x + a0; */
+ if ((err = mp_lshd(&b1, 4 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_lshd(&S2, 3 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(&b1, &S2, &b1)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_lshd(&S1, 2 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(&b1, &S1, &b1)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_lshd(&a1, 1 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(&b1, &a1, &b1)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(&b1, &a0, c)) != MP_OKAY) goto LBL_ERR;
+
+ /** a * b - P */
+
+
+LBL_ERR:
+ mp_clear(&b2);
+LBL_ERRb2:
+ mp_clear(&b1);
+LBL_ERRb1:
+ mp_clear(&b0);
+LBL_ERRb0:
+ mp_clear(&a2);
+LBL_ERRa2:
+ mp_clear(&a1);
+LBL_ERRa1:
+ mp_clear(&a0);
+LBL_ERRa0:
+ mp_clear_multi(&S1, &S2, &T1, NULL);
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_toom_sqr.c b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_toom_sqr.c
new file mode 100644
index 0000000..f2ffb30
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/bn_s_mp_toom_sqr.c
@@ -0,0 +1,147 @@
+#include "tommath_private.h"
+#ifdef BN_S_MP_TOOM_SQR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* squaring using Toom-Cook 3-way algorithm */
+
+/*
+ This file contains code from J. Arndt's book "Matters Computational"
+ and the accompanying FXT-library with permission of the author.
+*/
+
+/* squaring using Toom-Cook 3-way algorithm */
+/*
+ Setup and interpolation from algorithm SQR_3 in
+
+ Chung, Jaewook, and M. Anwar Hasan. "Asymmetric squaring formulae."
+ 18th IEEE Symposium on Computer Arithmetic (ARITH'07). IEEE, 2007.
+
+*/
+mp_err s_mp_toom_sqr(const mp_int *a, mp_int *b)
+{
+ mp_int S0, a0, a1, a2;
+ mp_digit *tmpa, *tmpc;
+ int B, count;
+ mp_err err;
+
+
+ /* init temps */
+ if ((err = mp_init(&S0)) != MP_OKAY) {
+ return err;
+ }
+
+ /* B */
+ B = a->used / 3;
+
+ /** a = a2 * x^2 + a1 * x + a0; */
+ if ((err = mp_init_size(&a0, B)) != MP_OKAY) goto LBL_ERRa0;
+
+ a0.used = B;
+ if ((err = mp_init_size(&a1, B)) != MP_OKAY) goto LBL_ERRa1;
+ a1.used = B;
+ if ((err = mp_init_size(&a2, B + (a->used - (3 * B)))) != MP_OKAY) goto LBL_ERRa2;
+
+ tmpa = a->dp;
+ tmpc = a0.dp;
+ for (count = 0; count < B; count++) {
+ *tmpc++ = *tmpa++;
+ }
+ tmpc = a1.dp;
+ for (; count < (2 * B); count++) {
+ *tmpc++ = *tmpa++;
+ }
+ tmpc = a2.dp;
+ for (; count < a->used; count++) {
+ *tmpc++ = *tmpa++;
+ a2.used++;
+ }
+ mp_clamp(&a0);
+ mp_clamp(&a1);
+ mp_clamp(&a2);
+
+ /** S0 = a0^2; */
+ if ((err = mp_sqr(&a0, &S0)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\S1 = (a2 + a1 + a0)^2 */
+ /** \\S2 = (a2 - a1 + a0)^2 */
+ /** \\S1 = a0 + a2; */
+ /** a0 = a0 + a2; */
+ if ((err = mp_add(&a0, &a2, &a0)) != MP_OKAY) goto LBL_ERR;
+ /** \\S2 = S1 - a1; */
+ /** b = a0 - a1; */
+ if ((err = mp_sub(&a0, &a1, b)) != MP_OKAY) goto LBL_ERR;
+ /** \\S1 = S1 + a1; */
+ /** a0 = a0 + a1; */
+ if ((err = mp_add(&a0, &a1, &a0)) != MP_OKAY) goto LBL_ERR;
+ /** \\S1 = S1^2; */
+ /** a0 = a0^2; */
+ if ((err = mp_sqr(&a0, &a0)) != MP_OKAY) goto LBL_ERR;
+ /** \\S2 = S2^2; */
+ /** b = b^2; */
+ if ((err = mp_sqr(b, b)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\ S3 = 2 * a1 * a2 */
+ /** \\S3 = a1 * a2; */
+ /** a1 = a1 * a2; */
+ if ((err = mp_mul(&a1, &a2, &a1)) != MP_OKAY) goto LBL_ERR;
+ /** \\S3 = S3 << 1; */
+ /** a1 = a1 << 1; */
+ if ((err = mp_mul_2(&a1, &a1)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\S4 = a2^2; */
+ /** a2 = a2^2; */
+ if ((err = mp_sqr(&a2, &a2)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\ tmp = (S1 + S2)/2 */
+ /** \\tmp = S1 + S2; */
+ /** b = a0 + b; */
+ if ((err = mp_add(&a0, b, b)) != MP_OKAY) goto LBL_ERR;
+ /** \\tmp = tmp >> 1; */
+ /** b = b >> 1; */
+ if ((err = mp_div_2(b, b)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\ S1 = S1 - tmp - S3 */
+ /** \\S1 = S1 - tmp; */
+ /** a0 = a0 - b; */
+ if ((err = mp_sub(&a0, b, &a0)) != MP_OKAY) goto LBL_ERR;
+ /** \\S1 = S1 - S3; */
+ /** a0 = a0 - a1; */
+ if ((err = mp_sub(&a0, &a1, &a0)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\S2 = tmp - S4 -S0 */
+ /** \\S2 = tmp - S4; */
+ /** b = b - a2; */
+ if ((err = mp_sub(b, &a2, b)) != MP_OKAY) goto LBL_ERR;
+ /** \\S2 = S2 - S0; */
+ /** b = b - S0; */
+ if ((err = mp_sub(b, &S0, b)) != MP_OKAY) goto LBL_ERR;
+
+
+ /** \\P = S4*x^4 + S3*x^3 + S2*x^2 + S1*x + S0; */
+ /** P = a2*x^4 + a1*x^3 + b*x^2 + a0*x + S0; */
+
+ if ((err = mp_lshd(&a2, 4 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_lshd(&a1, 3 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_lshd(b, 2 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_lshd(&a0, 1 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(&a2, &a1, &a2)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(&a2, b, b)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(b, &a0, b)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(b, &S0, b)) != MP_OKAY) goto LBL_ERR;
+ /** a^2 - P */
+
+
+LBL_ERR:
+ mp_clear(&a2);
+LBL_ERRa2:
+ mp_clear(&a1);
+LBL_ERRa1:
+ mp_clear(&a0);
+LBL_ERRa0:
+ mp_clear(&S0);
+
+ return err;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/changes.txt b/third_party/heimdal/lib/hcrypto/libtommath/changes.txt
new file mode 100644
index 0000000..ebf7382
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/changes.txt
@@ -0,0 +1,497 @@
+XXX XXth, 2019
+v1.2.0
+ -- A huge refactoring of the library happened - renaming,
+ deprecating and replacing existing functions by improved API's.
+
+ All deprecated functions, macros and symbols are only marked as such
+ so this version is still API and ABI compatible to v1.x.
+
+ -- Daniel Mendler was pushing for those changes and contributing a load of patches,
+ refactorings, code reviews and whatnotelse.
+ -- Christoph Zurnieden re-worked internals of the library, improved the performance,
+ did code reviews and wrote documentation.
+ -- Francois Perrad did some refactoring and took again care of linting the sources and
+ provided all fixes.
+ -- Jan Nijtmans, Karel Miko and Joachim Breitner contributed various patches.
+
+ -- Private symbols can now be hidden for the shared library builds, disabled by default.
+ -- All API's follow a single code style, are prefixed the same etc.
+ -- Unified, safer and improved API's
+ -- Less magic numbers - return values (where appropriate) and most flags are now enums,
+ this was implemented in a backwards compatible way where return values were int.
+ -- API's with return values are now by default marked as "warn on unsused result", this
+ can be disabled if required (which will most likely hide bugs), c.f. MP_WUR in tommath.h
+ -- Provide a whole set of setters&getters for different primitive types (long, uint32_t, etc.)
+ -- All those primitive setters are now optimized.
+ -- It's possible to automatically tune the cutoff values for Karatsuba&Toom-Cook
+ -- The custom allocators which were formerly known as XMALLOC(), XFREE() etc. are now available
+ as MP_MALLOC(), MP_REALLOC(), MP_CALLOC() and MP_FREE(). MP_REALLOC() and MP_FREE() now also
+ provide the allocated size to ease the usage of simple allocators without tracking.
+ -- Building is now also possible with MSVC 2015, 2017 and 2019 (use makefile.msvc)
+ -- Added mp_decr() and mp_incr()
+ -- Added mp_log_u32()
+ -- Improved prime-checking
+ -- Improved Toom-Cook multiplication
+ -- Removed the LTM book (`make docs` now builds the user manual)
+
+
+Jan 28th, 2019
+v1.1.0
+ -- Christoph Zurnieden contributed FIPS 186.4 compliant
+ prime-checking (PR #113), several other fixes and a load of documentation
+ -- Daniel Mendler provided two's-complement functions (PR #124)
+ and mp_{set,get}_double() (PR #123)
+ -- Francois Perrad took care of linting the sources, provided all fixes and
+ a astylerc to auto-format the sources.
+ -- A bunch of patches by Kevin B Kenny have been back-ported from TCL
+ -- Jan Nijtmans provided the patches to `const`ify all API
+ function arguments (also from TCL)
+ -- mp_rand() has now several native random provider implementations
+ and doesn't rely on `rand()` anymore
+ -- Karel Miko provided fixes when building for MS Windows
+ and re-worked the makefile generating process
+ -- The entire environment and build logic has been extended and improved
+ regarding auto-detection of platforms, libtool and a lot more
+ -- Prevent some potential BOF cases
+ -- Improved/fixed mp_lshd() and mp_invmod()
+ -- A load more bugs were fixed by various contributors
+
+
+Aug 29th, 2017
+v1.0.1
+ -- Dmitry Kovalenko provided fixes to mp_add_d() and mp_init_copy()
+ -- Matt Johnston contributed some improvements to mp_div_2d(),
+ mp_exptmod_fast(), mp_mod() and mp_mulmod()
+ -- Julien Nabet provided a fix to the error handling in mp_init_multi()
+ -- Ben Gardner provided a fix regarding usage of reserved keywords
+ -- Fixed mp_rand() to fill the correct number of bits
+ -- Fixed mp_invmod()
+ -- Use the same 64-bit detection code as in libtomcrypt
+ -- Correct usage of DESTDIR, PREFIX, etc. when installing the library
+ -- Francois Perrad updated all the perl scripts to an actual perl version
+
+
+Feb 5th, 2016
+v1.0
+ -- Bump to 1.0
+ -- Dirkjan Bussink provided a faster version of mp_expt_d()
+ -- Moritz Lenz contributed a fix to mp_mod()
+ and provided mp_get_long() and mp_set_long()
+ -- Fixed bugs in mp_read_radix(), mp_radix_size
+ Thanks to shameister, Gerhard R,
+ -- Christopher Brown provided mp_export() and mp_import()
+ -- Improvements in the code of mp_init_copy()
+ Thanks to ramkumarkoppu,
+ -- lomereiter provided mp_balance_mul()
+ -- Alexander Boström from the heimdal project contributed patches to
+ mp_prime_next_prime() and mp_invmod() and added a mp_isneg() macro
+ -- Fix build issues for Linux x32 ABI
+ -- Added mp_get_long_long() and mp_set_long_long()
+ -- Carlin provided a patch to use arc4random() instead of rand()
+ on platforms where it is supported
+ -- Karel Miko provided mp_sqrtmod_prime()
+
+
+July 23rd, 2010
+v0.42.0
+ -- Fix for mp_prime_next_prime() bug when checking generated prime
+ -- allow mp_shrink to shrink initialized, but empty MPI's
+ -- Added project and solution files for Visual Studio 2005 and Visual Studio 2008.
+
+March 10th, 2007
+v0.41 -- Wolfgang Ehrhardt suggested a quick fix to mp_div_d() which makes the detection of powers of two quicker.
+ -- [CRI] Added libtommath.dsp for Visual C++ users.
+
+December 24th, 2006
+v0.40 -- Updated makefile to properly support LIBNAME
+ -- Fixed bug in fast_s_mp_mul_high_digs() which overflowed (line 83), thanks Valgrind!
+
+April 4th, 2006
+v0.39 -- Jim Wigginton pointed out my Montgomery examples in figures 6.4 and 6.6 were off by one, k should be 9 not 8
+ -- Bruce Guenter suggested I use --tag=CC for libtool builds where the compiler may think it's C++.
+ -- "mm" from sci.crypt pointed out that my mp_gcd was sub-optimal (I also updated and corrected the book)
+ -- updated some of the @@ tags in tommath.src to reflect source changes.
+ -- updated email and url info in all source files
+
+Jan 26th, 2006
+v0.38 -- broken makefile.shared fixed
+ -- removed some carry stores that were not required [updated text]
+
+November 18th, 2005
+v0.37 -- [Don Porter] reported on a TCL list [HEY SEND ME BUGREPORTS ALREADY!!!] that mp_add_d() would compute -0 with some inputs. Fixed.
+ -- [rinick@gmail.com] reported the makefile.bcc was messed up. Fixed.
+ -- [Kevin Kenny] reported some issues with mp_toradix_n(). Now it doesn't require a min of 3 chars of output.
+ -- Made the make command renamable. Wee
+
+August 1st, 2005
+v0.36 -- LTM_PRIME_2MSB_ON was fixed and the "OFF" flag was removed.
+ -- [Peter LaDow] found a typo in the XREALLOC macro
+ -- [Peter LaDow] pointed out that mp_read_(un)signed_bin should have "const" on the input
+ -- Ported LTC patch to fix the prime_random_ex() function to get the bitsize correct [and the maskOR flags]
+ -- Kevin Kenny pointed out a stray //
+ -- David Hulton pointed out a typo in the textbook [mp_montgomery_setup() pseudo-code]
+ -- Neal Hamilton (Elliptic Semiconductor) pointed out that my Karatsuba notation was backwards and that I could use
+ unsigned operations in the routine.
+ -- Paul Schmidt pointed out a linking error in mp_exptmod() when BN_S_MP_EXPTMOD_C is undefined (and another for read_radix)
+ -- Updated makefiles to be way more flexible
+
+March 12th, 2005
+v0.35 -- Stupid XOR function missing line again... oops.
+ -- Fixed bug in invmod not handling negative inputs correctly [Wolfgang Ehrhardt]
+ -- Made exteuclid always give positive u3 output...[ Wolfgang Ehrhardt ]
+ -- [Wolfgang Ehrhardt] Suggested a fix for mp_reduce() which avoided underruns. ;-)
+ -- mp_rand() would emit one too many digits and it was possible to get a 0 out of it ... oops
+ -- Added montgomery to the testing to make sure it handles 1..10 digit moduli correctly
+ -- Fixed bug in comba that would lead to possible erroneous outputs when "pa < digs"
+ -- Fixed bug in mp_toradix_size for "0" [Kevin Kenny]
+ -- Updated chapters 1-5 of the textbook ;-) It now talks about the new comba code!
+
+February 12th, 2005
+v0.34 -- Fixed two more small errors in mp_prime_random_ex()
+ -- Fixed overflow in mp_mul_d() [Kevin Kenny]
+ -- Added mp_to_(un)signed_bin_n() functions which do bounds checking for ya [and report the size]
+ -- Added "large" diminished radix support. Speeds up things like DSA where the moduli is of the form 2^k - P for some P < 2^(k/2) or so
+ Actually is faster than Montgomery on my AMD64 (and probably much faster on a P4)
+ -- Updated the manual a bit
+ -- Ok so I haven't done the textbook work yet... My current freelance gig has landed me in France till the
+ end of Feb/05. Once I get back I'll have tons of free time and I plan to go to town on the book.
+ As of this release the API will freeze. At least until the book catches up with all the changes. I welcome
+ bug reports but new algorithms will have to wait.
+
+December 23rd, 2004
+v0.33 -- Fixed "small" variant for mp_div() which would munge with negative dividends...
+ -- Fixed bug in mp_prime_random_ex() which would set the most significant byte to zero when
+ no special flags were set
+ -- Fixed overflow [minor] bug in fast_s_mp_sqr()
+ -- Made the makefiles easier to configure the group/user that ltm will install as
+ -- Fixed "final carry" bug in comba multipliers. (Volkan Ceylan)
+ -- Matt Johnston pointed out a missing semi-colon in mp_exptmod
+
+October 29th, 2004
+v0.32 -- Added "makefile.shared" for shared object support
+ -- Added more to the build options/configs in the manual
+ -- Started the Depends framework, wrote dep.pl to scan deps and
+ produce "callgraph.txt" ;-)
+ -- Wrote SC_RSA_1 which will enable close to the minimum required to perform
+ RSA on 32-bit [or 64-bit] platforms with LibTomCrypt
+ -- Merged in the small/slower mp_div replacement. You can now toggle which
+ you want to use as your mp_div() at build time. Saves roughly 8KB or so.
+ -- Renamed a few files and changed some comments to make depends system work better.
+ (No changes to function names)
+ -- Merged in new Combas that perform 2 reads per inner loop instead of the older
+ 3reads/2writes per inner loop of the old code. Really though if you want speed
+ learn to use TomsFastMath ;-)
+
+August 9th, 2004
+v0.31 -- "profiled" builds now :-) new timings for Intel Northwoods
+ -- Added "pretty" build target
+ -- Update mp_init() to actually assign 0's instead of relying on calloc()
+ -- "Wolfgang Ehrhardt" <Wolfgang.Ehrhardt@munich.netsurf.de> found a bug in mp_mul() where if
+ you multiply a negative by zero you get negative zero as the result. Oops.
+ -- J Harper from PeerSec let me toy with his AMD64 and I got 60-bit digits working properly
+ [this also means that I fixed a bug where if sizeof(int) < sizeof(mp_digit) it would bug]
+
+April 11th, 2004
+v0.30 -- Added "mp_toradix_n" which stores upto "n-1" least significant digits of an mp_int
+ -- Johan Lindh sent a patch so MSVC wouldn't whine about redefining malloc [in weird dll modes]
+ -- Henrik Goldman spotted a missing OPT_CAST in mp_fwrite()
+ -- Tuned tommath.h so that when MP_LOW_MEM is defined MP_PREC shall be reduced.
+ [I also allow MP_PREC to be externally defined now]
+ -- Sped up mp_cnt_lsb() by using a 4x4 table [e.g. 4x speedup]
+ -- Added mp_prime_random_ex() which is a more versatile prime generator accurate to
+ exact bit lengths (unlike the deprecated but still available mp_prime_random() which
+ is only accurate to byte lengths). See the new LTM_PRIME_* flags ;-)
+ -- Alex Polushin contributed an optimized mp_sqrt() as well as mp_get_int() and mp_is_square().
+ I've cleaned them all up to be a little more consistent [along with one bug fix] for this release.
+ -- Added mp_init_set and mp_init_set_int to initialize and set small constants with one function
+ call.
+ -- Removed /etclib directory [um LibTomPoly deprecates this].
+ -- Fixed mp_mod() so the sign of the result agrees with the sign of the modulus.
+ ++ N.B. My semester is almost up so expect updates to the textbook to be posted to the libtomcrypt.org
+ website.
+
+Jan 25th, 2004
+v0.29 ++ Note: "Henrik" from the v0.28 changelog refers to Henrik Goldman ;-)
+ -- Added fix to mp_shrink to prevent a realloc when used == 0 [e.g. realloc zero bytes???]
+ -- Made the mp_prime_rabin_miller_trials() function internal table smaller and also
+ set the minimum number of tests to two (sounds a bit safer).
+ -- Added a mp_exteuclid() which computes the extended euclidean algorithm.
+ -- Fixed a memory leak in s_mp_exptmod() [called when Barrett reduction is to be used] which would arise
+ if a multiplication or subsequent reduction failed [would not free the temp result].
+ -- Made an API change to mp_radix_size(). It now returns an error code and stores the required size
+ through an "int star" passed to it.
+
+Dec 24th, 2003
+v0.28 -- Henrik Goldman suggested I add casts to the montomgery code [stores into mu...] so compilers wouldn't
+ spew [erroneous] diagnostics... fixed.
+ -- Henrik Goldman also spotted two typos. One in mp_radix_size() and another in mp_toradix().
+ -- Added fix to mp_shrink() to avoid a memory leak.
+ -- Added mp_prime_random() which requires a callback to make truly random primes of a given nature
+ (idea from chat with Niels Ferguson at Crypto'03)
+ -- Picked up a second wind. I'm filled with Gooo. Mission Gooo!
+ -- Removed divisions from mp_reduce_is_2k()
+ -- Sped up mp_div_d() [general case] to use only one division per digit instead of two.
+ -- Added the heap macros from LTC to LTM. Now you can easily [by editing four lines of tommath.h]
+ change the name of the heap functions used in LTM [also compatible with LTC via MPI mode]
+ -- Added bn_prime_rabin_miller_trials() which gives the number of Rabin-Miller trials to achieve
+ a failure rate of less than 2^-96
+ -- fixed bug in fast_mp_invmod(). The initial testing logic was wrong. An invalid input is not when
+ "a" and "b" are even it's when "b" is even [the algo is for odd moduli only].
+ -- Started a new manual [finally]. It is incomplete and will be finished as time goes on. I had to stop
+ adding full demos around half way in chapter three so I could at least get a good portion of the
+ manual done. If you really need help using the library you can always email me!
+ -- My Textbook is now included as part of the package [all Public Domain]
+
+Sept 19th, 2003
+v0.27 -- Removed changes.txt~ which was made by accident since "kate" decided it was
+ a good time to re-enable backups... [kde is fun!]
+ -- In mp_grow() "a->dp" is not overwritten by realloc call [re: memory leak]
+ Now if mp_grow() fails the mp_int is still valid and can be cleared via
+ mp_clear() to reclaim the memory.
+ -- Henrik Goldman found a buffer overflow bug in mp_add_d(). Fixed.
+ -- Cleaned up mp_mul_d() to be much easier to read and follow.
+
+Aug 29th, 2003
+v0.26 -- Fixed typo that caused warning with GCC 3.2
+ -- Martin Marcel noticed a bug in mp_neg() that allowed negative zeroes.
+ Also, Martin is the fellow who noted the bugs in mp_gcd() of 0.24/0.25.
+ -- Martin Marcel noticed an optimization [and slight bug] in mp_lcm().
+ -- Added fix to mp_read_unsigned_bin to prevent a buffer overflow.
+ -- Beefed up the comments in the baseline multipliers [and montgomery]
+ -- Added "mont" demo to the makefile.msvc in etc/
+ -- Optimized sign compares in mp_cmp from 4 to 2 cases.
+
+Aug 4th, 2003
+v0.25 -- Fix to mp_gcd again... oops (0,-a) == (-a, 0) == a
+ -- Fix to mp_clear which didn't reset the sign [Greg Rose]
+ -- Added mp_error_to_string() to convert return codes to strings. [Greg Rose]
+ -- Optimized fast_mp_invmod() to do the test for invalid inputs [both even]
+ first so temps don't have to be initialized if it's going to fail.
+ -- Optimized mp_gcd() by removing mp_div_2d calls for when one of the inputs
+ is odd.
+ -- Tons of new comments, some indentation fixups, etc.
+ -- mp_jacobi() returns MP_VAL if the modulus is less than or equal to zero.
+ -- fixed two typos in the header of each file :-)
+ -- LibTomMath is officially Public Domain [see LICENSE]
+
+July 15th, 2003
+v0.24 -- Optimized mp_add_d and mp_sub_d to not allocate temporary variables
+ -- Fixed mp_gcd() so the gcd of 0,0 is 0. Allows the gcd operation to be chained
+ e.g. (0,0,a) == a [instead of 1]
+ -- Should be one of the last release for a while. Working on LibTomMath book now.
+ -- optimized the pprime demo [/etc/pprime.c] to first make a huge table of single
+ digit primes then it reads them randomly instead of randomly choosing/testing single
+ digit primes.
+
+July 12th, 2003
+v0.23 -- Optimized mp_prime_next_prime() to not use mp_mod [via is_divisible()] in each
+ iteration. Instead now a smaller table is kept of the residues which can be updated
+ without division.
+ -- Fixed a bug in next_prime() where an input of zero would be treated as odd and
+ have two added to it [to move to the next odd].
+ -- fixed a bug in prime_fermat() and prime_miller_rabin() which allowed the base
+ to be negative, zero or one. Normally the test is only valid if the base is
+ greater than one.
+ -- changed the next_prime() prototype to accept a new parameter "bbs_style" which
+ will find the next prime congruent to 3 mod 4. The default [bbs_style==0] will
+ make primes which are either congruent to 1 or 3 mod 4.
+ -- fixed mp_read_unsigned_bin() so that it doesn't include both code for
+ the case DIGIT_BIT < 8 and >= 8
+ -- optimized div_d() to easy out on division by 1 [or if a == 0] and use
+ logical shifts if the divisor is a power of two.
+ -- the default DIGIT_BIT type was not int for non-default builds. Fixed.
+
+July 2nd, 2003
+v0.22 -- Fixed up mp_invmod so the result is properly in range now [was always congruent to the inverse...]
+ -- Fixed up s_mp_exptmod and mp_exptmod_fast so the lower half of the pre-computed table isn't allocated
+ which makes the algorithm use half as much ram.
+ -- Fixed the install script not to make the book :-) [which isn't included anyways]
+ -- added mp_cnt_lsb() which counts how many of the lsbs are zero
+ -- optimized mp_gcd() to use the new mp_cnt_lsb() to replace multiple divisions by two by a single division.
+ -- applied similar optimization to mp_prime_miller_rabin().
+ -- Fixed a bug in both mp_invmod() and fast_mp_invmod() which tested for odd
+ via "mp_iseven() == 0" which is not valid [since zero is not even either].
+
+June 19th, 2003
+v0.21 -- Fixed bug in mp_mul_d which would not handle sign correctly [would not always forward it]
+ -- Removed the #line lines from gen.pl [was in violation of ISO C]
+
+June 8th, 2003
+v0.20 -- Removed the book from the package. Added the TDCAL license document.
+ -- This release is officially pure-bred TDCAL again [last officially TDCAL based release was v0.16]
+
+June 6th, 2003
+v0.19 -- Fixed a bug in mp_montgomery_reduce() which was introduced when I tweaked mp_rshd() in the previous release.
+ Essentially the digits were not trimmed before the compare which cause a subtraction to occur all the time.
+ -- Fixed up etc/tune.c a bit to stop testing new cutoffs after 16 failures [to find more optimal points].
+ Brute force ho!
+
+
+May 29th, 2003
+v0.18 -- Fixed a bug in s_mp_sqr which would handle carries properly just not very elegantly.
+ (e.g. correct result, just bad looking code)
+ -- Fixed bug in mp_sqr which still had a 512 constant instead of MP_WARRAY
+ -- Added Toom-Cook multipliers [needs tuning!]
+ -- Added efficient divide by 3 algorithm mp_div_3
+ -- Re-wrote mp_div_d to be faster than calling mp_div
+ -- Added in a donated BCC makefile and a single page LTM poster (ahalhabsi@sbcglobal.net)
+ -- Added mp_reduce_2k which reduces an input modulo n = 2**p - k for any single digit k
+ -- Made the exptmod system be aware of the 2k reduction algorithms.
+ -- Rewrote mp_dr_reduce to be smaller, simpler and easier to understand.
+
+May 17th, 2003
+v0.17 -- Benjamin Goldberg submitted optimized mp_add and mp_sub routines. A new gen.pl as well
+ as several smaller suggestions. Thanks!
+ -- removed call to mp_cmp in inner loop of mp_div and put mp_cmp_mag in its place :-)
+ -- Fixed bug in mp_exptmod that would cause it to fail for odd moduli when DIGIT_BIT != 28
+ -- mp_exptmod now also returns errors if the modulus is negative and will handle negative exponents
+ -- mp_prime_is_prime will now return true if the input is one of the primes in the prime table
+ -- Damian M Gryski (dgryski@uwaterloo.ca) found a index out of bounds error in the
+ mp_fast_s_mp_mul_high_digs function which didn't come up before. (fixed)
+ -- Refactored the DR reduction code so there is only one function per file.
+ -- Fixed bug in the mp_mul() which would erroneously avoid the faster multiplier [comba] when it was
+ allowed. The bug would not cause the incorrect value to be produced just less efficient (fixed)
+ -- Fixed similar bug in the Montgomery reduction code.
+ -- Added tons of (mp_digit) casts so the 7/15/28/31 bit digit code will work flawlessly out of the box.
+ Also added limited support for 64-bit machines with a 60-bit digit. Both thanks to Tom Wu (tom@arcot.com)
+ -- Added new comments here and there, cleaned up some code [style stuff]
+ -- Fixed a lingering typo in mp_exptmod* that would set bitcnt to zero then one. Very silly stuff :-)
+ -- Fixed up mp_exptmod_fast so it would set "redux" to the comba Montgomery reduction if allowed. This
+ saves quite a few calls and if statements.
+ -- Added etc/mont.c a test of the Montgomery reduction [assuming all else works :-| ]
+ -- Fixed up etc/tune.c to use a wider test range [more appropriate] also added a x86 based addition which
+ uses RDTSC for high precision timing.
+ -- Updated demo/demo.c to remove MPI stuff [won't work anyways], made the tests run for 2 seconds each so its
+ not so insanely slow. Also made the output space delimited [and fixed up various errors]
+ -- Added logs directory, logs/graph.dem which will use gnuplot to make a series of PNG files
+ that go with the pre-made index.html. You have to build [via make timing] and run ltmtest first in the
+ root of the package.
+ -- Fixed a bug in mp_sub and mp_add where "-a - -a" or "-a + a" would produce -0 as the result [obviously invalid].
+ -- Fixed a bug in mp_rshd. If the count == a.used it should zero/return [instead of shifting]
+ -- Fixed a "off-by-one" bug in mp_mul2d. The initial size check on alloc would be off by one if the residue
+ shifting caused a carry.
+ -- Fixed a bug where s_mp_mul_digs() would not call the Comba based routine if allowed. This made Barrett reduction
+ slower than it had to be.
+
+Mar 29th, 2003
+v0.16 -- Sped up mp_div by making normalization one shift call
+ -- Sped up mp_mul_2d/mp_div_2d by aliasing pointers :-)
+ -- Cleaned up mp_gcd to use the macros for odd/even detection
+ -- Added comments here and there, mostly there but occasionally here too.
+
+Mar 22nd, 2003
+v0.15 -- Added series of prime testing routines to lib
+ -- Fixed up etc/tune.c
+ -- Added DR reduction algorithm
+ -- Beefed up the manual more.
+ -- Fixed up demo/demo.c so it doesn't have so many warnings and it does the full series of
+ tests
+ -- Added "pre-gen" directory which will hold a "gen.pl"'ed copy of the entire lib [done at
+ zipup time so its always the latest]
+ -- Added conditional casts for C++ users [boo!]
+
+Mar 15th, 2003
+v0.14 -- Tons of manual updates
+ -- cleaned up the directory
+ -- added MSVC makefiles
+ -- source changes [that I don't recall]
+ -- Fixed up the lshd/rshd code to use pointer aliasing
+ -- Fixed up the mul_2d and div_2d to not call rshd/lshd unless needed
+ -- Fixed up etc/tune.c a tad
+ -- fixed up demo/demo.c to output comma-delimited results of timing
+ also fixed up timing demo to use a finer granularity for various functions
+ -- fixed up demo/demo.c testing to pause during testing so my Duron won't catch on fire
+ [stays around 31-35C during testing :-)]
+
+Feb 13th, 2003
+v0.13 -- tons of minor speed-ups in low level add, sub, mul_2 and div_2 which propagate
+ to other functions like mp_invmod, mp_div, etc...
+ -- Sped up mp_exptmod_fast by using new code to find R mod m [e.g. B^n mod m]
+ -- minor fixes
+
+Jan 17th, 2003
+v0.12 -- re-wrote the majority of the makefile so its more portable and will
+ install via "make install" on most *nix platforms
+ -- Re-packaged all the source as seperate files. Means the library a single
+ file packagage any more. Instead of just adding "bn.c" you have to add
+ libtommath.a
+ -- Renamed "bn.h" to "tommath.h"
+ -- Changes to the manual to reflect all of this
+ -- Used GNU Indent to clean up the source
+
+Jan 15th, 2003
+v0.11 -- More subtle fixes
+ -- Moved to gentoo linux [hurrah!] so made *nix specific fixes to the make process
+ -- Sped up the montgomery reduction code quite a bit
+ -- fixed up demo so when building timing for the x86 it assumes ELF format now
+
+Jan 9th, 2003
+v0.10 -- Pekka Riikonen suggested fixes to the radix conversion code.
+ -- Added baseline montgomery and comba montgomery reductions, sped up exptmods
+ [to a point, see bn.h for MONTGOMERY_EXPT_CUTOFF]
+
+Jan 6th, 2003
+v0.09 -- Updated the manual to reflect recent changes. :-)
+ -- Added Jacobi function (mp_jacobi) to supplement the number theory side of the lib
+ -- Added a Mersenne prime finder demo in ./etc/mersenne.c
+
+Jan 2nd, 2003
+v0.08 -- Sped up the multipliers by moving the inner loop variables into a smaller scope
+ -- Corrected a bunch of small "warnings"
+ -- Added more comments
+ -- Made "mtest" be able to use /dev/random, /dev/urandom or stdin for RNG data
+ -- Corrected some bugs where error messages were potentially ignored
+ -- add etc/pprime.c program which makes numbers which are provably prime.
+
+Jan 1st, 2003
+v0.07 -- Removed alot of heap operations from core functions to speed them up
+ -- Added a root finding function [and mp_sqrt macro like from MPI]
+ -- Added more to manual
+
+Dec 31st, 2002
+v0.06 -- Sped up the s_mp_add, s_mp_sub which inturn sped up mp_invmod, mp_exptmod, etc...
+ -- Cleaned up the header a bit more
+
+Dec 30th, 2002
+v0.05 -- Builds with MSVC out of the box
+ -- Fixed a bug in mp_invmod w.r.t. even moduli
+ -- Made mp_toradix and mp_read_radix use char instead of unsigned char arrays
+ -- Fixed up exptmod to use fewer multiplications
+ -- Fixed up mp_init_size to use only one heap operation
+ -- Note there is a slight "off-by-one" bug in the library somewhere
+ without the padding (see the source for comment) the library
+ crashes in libtomcrypt. Anyways a reasonable workaround is to pad the
+ numbers which will always correct it since as the numbers grow the padding
+ will still be beyond the end of the number
+ -- Added more to the manual
+
+Dec 29th, 2002
+v0.04 -- Fixed a memory leak in mp_to_unsigned_bin
+ -- optimized invmod code
+ -- Fixed bug in mp_div
+ -- use exchange instead of copy for results
+ -- added a bit more to the manual
+
+Dec 27th, 2002
+v0.03 -- Sped up s_mp_mul_high_digs by not computing the carries of the lower digits
+ -- Fixed a bug where mp_set_int wouldn't zero the value first and set the used member.
+ -- fixed a bug in s_mp_mul_high_digs where the limit placed on the result digits was not calculated properly
+ -- fixed bugs in add/sub/mul/sqr_mod functions where if the modulus and dest were the same it wouldn't work
+ -- fixed a bug in mp_mod and mp_mod_d concerning negative inputs
+ -- mp_mul_d didn't preserve sign
+ -- Many many many many fixes
+ -- Works in LibTomCrypt now :-)
+ -- Added iterations to the timing demos... more accurate.
+ -- Tom needs a job.
+
+Dec 26th, 2002
+v0.02 -- Fixed a few "slips" in the manual. This is "LibTomMath" afterall :-)
+ -- Added mp_cmp_mag, mp_neg, mp_abs and mp_radix_size that were missing.
+ -- Sped up the fast [comba] multipliers more [yahoo!]
+
+Dec 25th,2002
+v0.01 -- Initial release. Gimme a break.
+ -- Todo list,
+ add details to manual [e.g. algorithms]
+ more comments in code
+ example programs
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/demo/mtest_opponent.c b/third_party/heimdal/lib/hcrypto/libtommath/demo/mtest_opponent.c
new file mode 100644
index 0000000..7fbd35e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/demo/mtest_opponent.c
@@ -0,0 +1,402 @@
+#include "shared.h"
+
+#ifdef LTM_MTEST_REAL_RAND
+#define LTM_MTEST_RAND_SEED time(NULL)
+#else
+#define LTM_MTEST_RAND_SEED 23
+#endif
+
+static void draw(mp_int *a)
+{
+ ndraw(a, "");
+}
+
+#define FGETS(str, size, stream) \
+ { \
+ char *ret = fgets(str, size, stream); \
+ if (!ret) { fprintf(stderr, "\n%d: fgets failed\n", __LINE__); goto LBL_ERR; } \
+ }
+
+static int mtest_opponent(void)
+{
+ char cmd[4096];
+ char buf[4096];
+ int ix;
+ unsigned rr;
+ mp_int a, b, c, d, e, f;
+ unsigned long expt_n, add_n, sub_n, mul_n, div_n, sqr_n, mul2d_n, div2d_n,
+ gcd_n, lcm_n, inv_n, div2_n, mul2_n, add_d_n, sub_d_n;
+
+ srand(LTM_MTEST_RAND_SEED);
+
+ if (mp_init_multi(&a, &b, &c, &d, &e, &f, NULL)!= MP_OKAY)
+ return EXIT_FAILURE;
+
+ div2_n = mul2_n = inv_n = expt_n = lcm_n = gcd_n = add_n =
+ sub_n = mul_n = div_n = sqr_n = mul2d_n = div2d_n = add_d_n = sub_d_n = 0;
+
+#ifndef MP_FIXED_CUTOFFS
+ /* force KARA and TOOM to enable despite cutoffs */
+ KARATSUBA_SQR_CUTOFF = KARATSUBA_MUL_CUTOFF = 8;
+ TOOM_SQR_CUTOFF = TOOM_MUL_CUTOFF = 16;
+#endif
+
+ for (;;) {
+ /* randomly clear and re-init one variable, this has the affect of triming the alloc space */
+ switch (abs(rand()) % 7) {
+ case 0:
+ mp_clear(&a);
+ mp_init(&a);
+ break;
+ case 1:
+ mp_clear(&b);
+ mp_init(&b);
+ break;
+ case 2:
+ mp_clear(&c);
+ mp_init(&c);
+ break;
+ case 3:
+ mp_clear(&d);
+ mp_init(&d);
+ break;
+ case 4:
+ mp_clear(&e);
+ mp_init(&e);
+ break;
+ case 5:
+ mp_clear(&f);
+ mp_init(&f);
+ break;
+ case 6:
+ break; /* don't clear any */
+ }
+
+
+ printf("%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu ",
+ add_n, sub_n, mul_n, div_n, sqr_n, mul2d_n, div2d_n, gcd_n, lcm_n,
+ expt_n, inv_n, div2_n, mul2_n, add_d_n, sub_d_n);
+ FGETS(cmd, 4095, stdin);
+ cmd[strlen(cmd) - 1u] = '\0';
+ printf("%-6s ]\r", cmd);
+ fflush(stdout);
+ if (strcmp(cmd, "mul2d") == 0) {
+ ++mul2d_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ sscanf(buf, "%u", &rr);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+
+ mp_mul_2d(&a, (int)rr, &a);
+ a.sign = b.sign;
+ if (mp_cmp(&a, &b) != MP_EQ) {
+ printf("mul2d failed, rr == %u\n", rr);
+ draw(&a);
+ draw(&b);
+ goto LBL_ERR;
+ }
+ } else if (strcmp(cmd, "div2d") == 0) {
+ ++div2d_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ sscanf(buf, "%u", &rr);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+
+ mp_div_2d(&a, (int)rr, &a, &e);
+ a.sign = b.sign;
+ if ((a.used == b.used) && (a.used == 0)) {
+ a.sign = b.sign = MP_ZPOS;
+ }
+ if (mp_cmp(&a, &b) != MP_EQ) {
+ printf("div2d failed, rr == %u\n", rr);
+ draw(&a);
+ draw(&b);
+ goto LBL_ERR;
+ }
+ } else if (strcmp(cmd, "add") == 0) {
+ ++add_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&c, buf, 64);
+ mp_copy(&a, &d);
+ mp_add(&d, &b, &d);
+ if (mp_cmp(&c, &d) != MP_EQ) {
+ printf("add %lu failure!\n", add_n);
+ draw(&a);
+ draw(&b);
+ draw(&c);
+ draw(&d);
+ goto LBL_ERR;
+ }
+
+ /* test the sign/unsigned storage functions */
+
+ rr = (unsigned)mp_sbin_size(&c);
+ mp_to_sbin(&c, (unsigned char *) cmd, (size_t)rr, NULL);
+ memset(cmd + rr, rand() & 0xFF, sizeof(cmd) - rr);
+ mp_from_sbin(&d, (unsigned char *) cmd, (size_t)rr);
+ if (mp_cmp(&c, &d) != MP_EQ) {
+ printf("mp_signed_bin failure!\n");
+ draw(&c);
+ draw(&d);
+ goto LBL_ERR;
+ }
+
+ rr = (unsigned)mp_ubin_size(&c);
+ mp_to_ubin(&c, (unsigned char *) cmd, (size_t)rr, NULL);
+ memset(cmd + rr, rand() & 0xFF, sizeof(cmd) - rr);
+ mp_from_ubin(&d, (unsigned char *) cmd, (size_t)rr);
+ if (mp_cmp_mag(&c, &d) != MP_EQ) {
+ printf("mp_unsigned_bin failure!\n");
+ draw(&c);
+ draw(&d);
+ goto LBL_ERR;
+ }
+
+ } else if (strcmp(cmd, "sub") == 0) {
+ ++sub_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&c, buf, 64);
+ mp_copy(&a, &d);
+ mp_sub(&d, &b, &d);
+ if (mp_cmp(&c, &d) != MP_EQ) {
+ printf("sub %lu failure!\n", sub_n);
+ draw(&a);
+ draw(&b);
+ draw(&c);
+ draw(&d);
+ goto LBL_ERR;
+ }
+ } else if (strcmp(cmd, "mul") == 0) {
+ ++mul_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&c, buf, 64);
+ mp_copy(&a, &d);
+ mp_mul(&d, &b, &d);
+ if (mp_cmp(&c, &d) != MP_EQ) {
+ printf("mul %lu failure!\n", mul_n);
+ draw(&a);
+ draw(&b);
+ draw(&c);
+ draw(&d);
+ goto LBL_ERR;
+ }
+ } else if (strcmp(cmd, "div") == 0) {
+ ++div_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&c, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&d, buf, 64);
+
+ mp_div(&a, &b, &e, &f);
+ if ((mp_cmp(&c, &e) != MP_EQ) || (mp_cmp(&d, &f) != MP_EQ)) {
+ printf("div %lu %d, %d, failure!\n", div_n, mp_cmp(&c, &e),
+ mp_cmp(&d, &f));
+ draw(&a);
+ draw(&b);
+ draw(&c);
+ draw(&d);
+ draw(&e);
+ draw(&f);
+ goto LBL_ERR;
+ }
+
+ } else if (strcmp(cmd, "sqr") == 0) {
+ ++sqr_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+ mp_copy(&a, &c);
+ mp_sqr(&c, &c);
+ if (mp_cmp(&b, &c) != MP_EQ) {
+ printf("sqr %lu failure!\n", sqr_n);
+ draw(&a);
+ draw(&b);
+ draw(&c);
+ goto LBL_ERR;
+ }
+ } else if (strcmp(cmd, "gcd") == 0) {
+ ++gcd_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&c, buf, 64);
+ mp_copy(&a, &d);
+ mp_gcd(&d, &b, &d);
+ d.sign = c.sign;
+ if (mp_cmp(&c, &d) != MP_EQ) {
+ printf("gcd %lu failure!\n", gcd_n);
+ draw(&a);
+ draw(&b);
+ draw(&c);
+ draw(&d);
+ goto LBL_ERR;
+ }
+ } else if (strcmp(cmd, "lcm") == 0) {
+ ++lcm_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&c, buf, 64);
+ mp_copy(&a, &d);
+ mp_lcm(&d, &b, &d);
+ d.sign = c.sign;
+ if (mp_cmp(&c, &d) != MP_EQ) {
+ printf("lcm %lu failure!\n", lcm_n);
+ draw(&a);
+ draw(&b);
+ draw(&c);
+ draw(&d);
+ goto LBL_ERR;
+ }
+ } else if (strcmp(cmd, "expt") == 0) {
+ ++expt_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&c, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&d, buf, 64);
+ mp_copy(&a, &e);
+ mp_exptmod(&e, &b, &c, &e);
+ if (mp_cmp(&d, &e) != MP_EQ) {
+ printf("expt %lu failure!\n", expt_n);
+ draw(&a);
+ draw(&b);
+ draw(&c);
+ draw(&d);
+ draw(&e);
+ goto LBL_ERR;
+ }
+ } else if (strcmp(cmd, "invmod") == 0) {
+ ++inv_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&c, buf, 64);
+ mp_invmod(&a, &b, &d);
+ mp_mulmod(&d, &a, &b, &e);
+ if (mp_cmp_d(&e, 1uL) != MP_EQ) {
+ printf("inv [wrong value from MPI?!] failure\n");
+ draw(&a);
+ draw(&b);
+ draw(&c);
+ draw(&d);
+ draw(&e);
+ mp_gcd(&a, &b, &e);
+ draw(&e);
+ goto LBL_ERR;
+ }
+
+ } else if (strcmp(cmd, "div2") == 0) {
+ ++div2_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+ mp_div_2(&a, &c);
+ if (mp_cmp(&c, &b) != MP_EQ) {
+ printf("div_2 %lu failure\n", div2_n);
+ draw(&a);
+ draw(&b);
+ draw(&c);
+ goto LBL_ERR;
+ }
+ } else if (strcmp(cmd, "mul2") == 0) {
+ ++mul2_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+ mp_mul_2(&a, &c);
+ if (mp_cmp(&c, &b) != MP_EQ) {
+ printf("mul_2 %lu failure\n", mul2_n);
+ draw(&a);
+ draw(&b);
+ draw(&c);
+ goto LBL_ERR;
+ }
+ } else if (strcmp(cmd, "add_d") == 0) {
+ ++add_d_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ sscanf(buf, "%d", &ix);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+ mp_add_d(&a, (mp_digit)ix, &c);
+ if (mp_cmp(&b, &c) != MP_EQ) {
+ printf("add_d %lu failure\n", add_d_n);
+ draw(&a);
+ draw(&b);
+ draw(&c);
+ printf("d == %d\n", ix);
+ goto LBL_ERR;
+ }
+ } else if (strcmp(cmd, "sub_d") == 0) {
+ ++sub_d_n;
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&a, buf, 64);
+ FGETS(buf, 4095, stdin);
+ sscanf(buf, "%d", &ix);
+ FGETS(buf, 4095, stdin);
+ mp_read_radix(&b, buf, 64);
+ mp_sub_d(&a, (mp_digit)ix, &c);
+ if (mp_cmp(&b, &c) != MP_EQ) {
+ printf("sub_d %lu failure\n", sub_d_n);
+ draw(&a);
+ draw(&b);
+ draw(&c);
+ printf("d == %d\n", ix);
+ goto LBL_ERR;
+ }
+ } else if (strcmp(cmd, "exit") == 0) {
+ printf("\nokay, exiting now\n");
+ break;
+ }
+ }
+
+ mp_clear_multi(&a, &b, &c, &d, &e, &f, NULL);
+ printf("\n");
+ return 0;
+
+LBL_ERR:
+ mp_clear_multi(&a, &b, &c, &d, &e, &f, NULL);
+ printf("\n");
+ return EXIT_FAILURE;
+}
+
+int main(void)
+{
+ print_header();
+
+ return mtest_opponent();
+}
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/demo/shared.c b/third_party/heimdal/lib/hcrypto/libtommath/demo/shared.c
new file mode 100644
index 0000000..dc8e05a
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/demo/shared.c
@@ -0,0 +1,42 @@
+#include "shared.h"
+
+void ndraw(mp_int *a, const char *name)
+{
+ char *buf = NULL;
+ int size;
+
+ mp_radix_size(a, 10, &size);
+ buf = (char *)malloc((size_t) size);
+ if (buf == NULL) {
+ fprintf(stderr, "\nndraw: malloc(%d) failed\n", size);
+ exit(EXIT_FAILURE);
+ }
+
+ printf("%s: ", name);
+ mp_to_decimal(a, buf, (size_t) size);
+ printf("%s\n", buf);
+ mp_to_hex(a, buf, (size_t) size);
+ printf("0x%s\n", buf);
+
+ free(buf);
+}
+
+void print_header(void)
+{
+#ifdef MP_8BIT
+ printf("Digit size 8 Bit \n");
+#endif
+#ifdef MP_16BIT
+ printf("Digit size 16 Bit \n");
+#endif
+#ifdef MP_32BIT
+ printf("Digit size 32 Bit \n");
+#endif
+#ifdef MP_64BIT
+ printf("Digit size 64 Bit \n");
+#endif
+ printf("Size of mp_digit: %u\n", (unsigned int)sizeof(mp_digit));
+ printf("Size of mp_word: %u\n", (unsigned int)sizeof(mp_word));
+ printf("MP_DIGIT_BIT: %d\n", MP_DIGIT_BIT);
+ printf("MP_PREC: %d\n", MP_PREC);
+}
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/demo/shared.h b/third_party/heimdal/lib/hcrypto/libtommath/demo/shared.h
new file mode 100644
index 0000000..4d5eb53
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/demo/shared.h
@@ -0,0 +1,21 @@
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+
+/*
+ * Configuration
+ */
+#ifndef LTM_DEMO_TEST_REDUCE_2K_L
+/* This test takes a moment so we disable it by default, but it can be:
+ * 0 to disable testing
+ * 1 to make the test with P = 2^1024 - 0x2A434 B9FDEC95 D8F9D550 FFFFFFFF FFFFFFFF
+ * 2 to make the test with P = 2^2048 - 0x1 00000000 00000000 00000000 00000000 4945DDBF 8EA2A91D 5776399B B83E188F
+ */
+#define LTM_DEMO_TEST_REDUCE_2K_L 0
+#endif
+
+#define MP_WUR /* TODO: result checks disabled for now */
+#include "tommath_private.h"
+
+extern void ndraw(mp_int* a, const char* name);
+extern void print_header(void);
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/demo/test.c b/third_party/heimdal/lib/hcrypto/libtommath/demo/test.c
new file mode 100644
index 0000000..9049fa8
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/demo/test.c
@@ -0,0 +1,2522 @@
+#include <inttypes.h>
+#include "shared.h"
+
+static long rand_long(void)
+{
+ long x;
+ if (s_mp_rand_source(&x, sizeof(x)) != MP_OKAY) {
+ fprintf(stderr, "s_mp_rand_source failed\n");
+ exit(EXIT_FAILURE);
+ }
+ return x;
+}
+
+static int rand_int(void)
+{
+ int x;
+ if (s_mp_rand_source(&x, sizeof(x)) != MP_OKAY) {
+ fprintf(stderr, "s_mp_rand_source failed\n");
+ exit(EXIT_FAILURE);
+ }
+ return x;
+}
+
+static int32_t rand_int32(void)
+{
+ int32_t x;
+ if (s_mp_rand_source(&x, sizeof(x)) != MP_OKAY) {
+ fprintf(stderr, "s_mp_rand_source failed\n");
+ exit(EXIT_FAILURE);
+ }
+ return x;
+}
+
+static int64_t rand_int64(void)
+{
+ int64_t x;
+ if (s_mp_rand_source(&x, sizeof(x)) != MP_OKAY) {
+ fprintf(stderr, "s_mp_rand_source failed\n");
+ exit(EXIT_FAILURE);
+ }
+ return x;
+}
+
+static uint32_t uabs32(int32_t x)
+{
+ return x > 0 ? (uint32_t)x : -(uint32_t)x;
+}
+
+static uint64_t uabs64(int64_t x)
+{
+ return x > 0 ? (uint64_t)x : -(uint64_t)x;
+}
+
+/* This function prototype is needed
+ * to test dead code elimination
+ * which is used for feature detection.
+ *
+ * If the feature detection does not
+ * work as desired we will get a linker error.
+ */
+void does_not_exist(void);
+
+static int test_feature_detection(void)
+{
+#define BN_TEST_FEATURE1_C
+ if (!MP_HAS(TEST_FEATURE1)) {
+ does_not_exist();
+ return EXIT_FAILURE;
+ }
+
+#define BN_TEST_FEATURE2_C 1
+ if (MP_HAS(TEST_FEATURE2)) {
+ does_not_exist();
+ return EXIT_FAILURE;
+ }
+
+#define BN_TEST_FEATURE3_C 0
+ if (MP_HAS(TEST_FEATURE3)) {
+ does_not_exist();
+ return EXIT_FAILURE;
+ }
+
+#define BN_TEST_FEATURE4_C something
+ if (MP_HAS(TEST_FEATURE4)) {
+ does_not_exist();
+ return EXIT_FAILURE;
+ }
+
+ if (MP_HAS(TEST_FEATURE5)) {
+ does_not_exist();
+ return EXIT_FAILURE;
+ }
+
+ return EXIT_SUCCESS;
+}
+
+static int test_trivial_stuff(void)
+{
+ mp_int a, b, c, d;
+ mp_err e;
+ if ((e = mp_init_multi(&a, &b, &c, &d, NULL)) != MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+ (void)mp_error_to_string(e);
+
+ /* a: 0->5 */
+ mp_set(&a, 5u);
+ /* a: 5-> b: -5 */
+ mp_neg(&a, &b);
+ if (mp_cmp(&a, &b) != MP_GT) {
+ goto LBL_ERR;
+ }
+ if (mp_cmp(&b, &a) != MP_LT) {
+ goto LBL_ERR;
+ }
+ /* a: 5-> a: -5 */
+ mp_neg(&a, &a);
+ if (mp_cmp(&b, &a) != MP_EQ) {
+ goto LBL_ERR;
+ }
+ /* a: -5-> b: 5 */
+ mp_abs(&a, &b);
+ if (mp_isneg(&b) != MP_NO) {
+ goto LBL_ERR;
+ }
+ /* a: -5-> b: -4 */
+ mp_add_d(&a, 1uL, &b);
+ if (mp_isneg(&b) != MP_YES) {
+ goto LBL_ERR;
+ }
+ if (mp_get_i32(&b) != -4) {
+ goto LBL_ERR;
+ }
+ if (mp_get_u32(&b) != (uint32_t)-4) {
+ goto LBL_ERR;
+ }
+ if (mp_get_mag_u32(&b) != 4) {
+ goto LBL_ERR;
+ }
+ /* a: -5-> b: 1 */
+ mp_add_d(&a, 6uL, &b);
+ if (mp_get_u32(&b) != 1) {
+ goto LBL_ERR;
+ }
+ /* a: -5-> a: 1 */
+ mp_add_d(&a, 6uL, &a);
+ if (mp_get_u32(&a) != 1) {
+ goto LBL_ERR;
+ }
+ mp_zero(&a);
+ /* a: 0-> a: 6 */
+ mp_add_d(&a, 6uL, &a);
+ if (mp_get_u32(&a) != 6) {
+ goto LBL_ERR;
+ }
+
+ mp_set(&a, 42u);
+ mp_set(&b, 1u);
+ mp_neg(&b, &b);
+ mp_set(&c, 1u);
+ mp_exptmod(&a, &b, &c, &d);
+
+ mp_set(&c, 7u);
+ mp_exptmod(&a, &b, &c, &d);
+
+ if (mp_iseven(&a) == mp_isodd(&a)) {
+ goto LBL_ERR;
+ }
+
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_FAILURE;
+}
+
+static int check_get_set_i32(mp_int *a, int32_t b)
+{
+ mp_clear(a);
+ if (mp_shrink(a) != MP_OKAY) return EXIT_FAILURE;
+
+ mp_set_i32(a, b);
+ if (mp_shrink(a) != MP_OKAY) return EXIT_FAILURE;
+ if (mp_get_i32(a) != b) return EXIT_FAILURE;
+ if (mp_get_u32(a) != (uint32_t)b) return EXIT_FAILURE;
+ if (mp_get_mag_u32(a) != uabs32(b)) return EXIT_FAILURE;
+
+ mp_set_u32(a, (uint32_t)b);
+ if (mp_get_u32(a) != (uint32_t)b) return EXIT_FAILURE;
+ if (mp_get_i32(a) != (int32_t)(uint32_t)b) return EXIT_FAILURE;
+
+ return EXIT_SUCCESS;
+}
+
+static int test_mp_get_set_i32(void)
+{
+ int i;
+ mp_int a;
+
+ if (mp_init(&a) != MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ check_get_set_i32(&a, 0);
+ check_get_set_i32(&a, -1);
+ check_get_set_i32(&a, 1);
+ check_get_set_i32(&a, INT32_MIN);
+ check_get_set_i32(&a, INT32_MAX);
+
+ for (i = 0; i < 1000; ++i) {
+ int32_t b = rand_int32();
+ if (check_get_set_i32(&a, b) != EXIT_SUCCESS) {
+ goto LBL_ERR;
+ }
+ }
+
+ mp_clear(&a);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear(&a);
+ return EXIT_FAILURE;
+}
+
+static int check_get_set_i64(mp_int *a, int64_t b)
+{
+ mp_clear(a);
+ if (mp_shrink(a) != MP_OKAY) return EXIT_FAILURE;
+
+ mp_set_i64(a, b);
+ if (mp_shrink(a) != MP_OKAY) return EXIT_FAILURE;
+ if (mp_get_i64(a) != b) return EXIT_FAILURE;
+ if (mp_get_u64(a) != (uint64_t)b) return EXIT_FAILURE;
+ if (mp_get_mag_u64(a) != uabs64(b)) return EXIT_FAILURE;
+
+ mp_set_u64(a, (uint64_t)b);
+ if (mp_get_u64(a) != (uint64_t)b) return EXIT_FAILURE;
+ if (mp_get_i64(a) != (int64_t)(uint64_t)b) return EXIT_FAILURE;
+
+ return EXIT_SUCCESS;
+}
+
+static int test_mp_get_set_i64(void)
+{
+ int i;
+ mp_int a;
+
+ if (mp_init(&a) != MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ check_get_set_i64(&a, 0);
+ check_get_set_i64(&a, -1);
+ check_get_set_i64(&a, 1);
+ check_get_set_i64(&a, INT64_MIN);
+ check_get_set_i64(&a, INT64_MAX);
+
+ for (i = 0; i < 1000; ++i) {
+ int64_t b = rand_int64();
+ if (check_get_set_i64(&a, b) != EXIT_SUCCESS) {
+ goto LBL_ERR;
+ }
+ }
+
+ mp_clear(&a);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear(&a);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_fread_fwrite(void)
+{
+ mp_int a, b;
+ mp_err e;
+ FILE *tmp = NULL;
+ if ((e = mp_init_multi(&a, &b, NULL)) != MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ mp_set_ul(&a, 123456uL);
+ tmp = tmpfile();
+ if ((e = mp_fwrite(&a, 64, tmp)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ rewind(tmp);
+ if ((e = mp_fread(&b, 64, tmp)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (mp_get_u32(&b) != 123456uL) {
+ goto LBL_ERR;
+ }
+ fclose(tmp);
+
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ if (tmp != NULL) fclose(tmp);
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_FAILURE;
+}
+
+static mp_err very_random_source(void *out, size_t size)
+{
+ memset(out, 0xff, size);
+ return MP_OKAY;
+}
+
+static int test_mp_rand(void)
+{
+ mp_int a, b;
+ int n;
+ mp_err err;
+ if (mp_init_multi(&a, &b, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+ mp_rand_source(very_random_source);
+ for (n = 1; n < 1024; ++n) {
+ if ((err = mp_rand(&a, n)) != MP_OKAY) {
+ printf("Failed mp_rand() %s.\n", mp_error_to_string(err));
+ break;
+ }
+ if ((err = mp_incr(&a)) != MP_OKAY) {
+ printf("Failed mp_incr() %s.\n", mp_error_to_string(err));
+ break;
+ }
+ if ((err = mp_div_2d(&a, n * MP_DIGIT_BIT, &b, NULL)) != MP_OKAY) {
+ printf("Failed mp_div_2d() %s.\n", mp_error_to_string(err));
+ break;
+ }
+ if (mp_cmp_d(&b, 1) != MP_EQ) {
+ ndraw(&a, "mp_rand() a");
+ ndraw(&b, "mp_rand() b");
+ err = MP_ERR;
+ break;
+ }
+ }
+ mp_rand_source(s_mp_rand_jenkins);
+ mp_clear_multi(&a, &b, NULL);
+ return err == MP_OKAY ? EXIT_SUCCESS : EXIT_FAILURE;
+}
+
+static int test_mp_kronecker(void)
+{
+ struct mp_kronecker_st {
+ long n;
+ int c[21];
+ };
+ static struct mp_kronecker_st kronecker[] = {
+ /*-10, -9, -8, -7,-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10*/
+ { -10, { 0, -1, 0, -1, 0, 0, 0, 1, 0, -1, 0, 1, 0, -1, 0, 0, 0, 1, 0, 1, 0 } },
+ { -9, { -1, 0, -1, 1, 0, -1, -1, 0, -1, -1, 0, 1, 1, 0, 1, 1, 0, -1, 1, 0, 1 } },
+ { -8, { 0, -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, 1, 0 } },
+ { -7, { 1, -1, -1, 0, 1, 1, -1, 1, -1, -1, 0, 1, 1, -1, 1, -1, -1, 0, 1, 1, -1 } },
+ { -6, { 0, 0, 0, -1, 0, -1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0 } },
+ { -5, { 0, -1, 1, -1, 1, 0, -1, -1, 1, -1, 0, 1, -1, 1, 1, 0, -1, 1, -1, 1, 0 } },
+ { -4, { 0, -1, 0, 1, 0, -1, 0, 1, 0, -1, 0, 1, 0, -1, 0, 1, 0, -1, 0, 1, 0 } },
+ { -3, { -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1 } },
+ { -2, { 0, -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, 1, 0 } },
+ { -1, { -1, -1, -1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1 } },
+ { 0, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
+ { 1, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } },
+ { 2, { 0, 1, 0, 1, 0, -1, 0, -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, 1, 0, 1, 0 } },
+ { 3, { 1, 0, -1, -1, 0, -1, 1, 0, -1, 1, 0, 1, -1, 0, 1, -1, 0, -1, -1, 0, 1 } },
+ { 4, { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 } },
+ { 5, { 0, 1, -1, -1, 1, 0, 1, -1, -1, 1, 0, 1, -1, -1, 1, 0, 1, -1, -1, 1, 0 } },
+ { 6, { 0, 0, 0, -1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, -1, 0, 0, 0 } },
+ { 7, { -1, 1, 1, 0, 1, -1, 1, 1, 1, 1, 0, 1, 1, 1, 1, -1, 1, 0, 1, 1, -1 } },
+ { 8, { 0, 1, 0, 1, 0, -1, 0, -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, 1, 0, 1, 0 } },
+ { 9, { 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1 } },
+ { 10, { 0, 1, 0, -1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0 } }
+ };
+
+ long k, m;
+ int i, cnt;
+ mp_err err;
+ mp_int a, b;
+ if (mp_init_multi(&a, &b, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ mp_set_ul(&a, 0uL);
+ mp_set_ul(&b, 1uL);
+ if ((err = mp_kronecker(&a, &b, &i)) != MP_OKAY) {
+ printf("Failed executing mp_kronecker(0 | 1) %s.\n", mp_error_to_string(err));
+ goto LBL_ERR;
+ }
+ if (i != 1) {
+ printf("Failed trivial mp_kronecker(0 | 1) %d != 1\n", i);
+ goto LBL_ERR;
+ }
+ for (cnt = 0; cnt < (int)(sizeof(kronecker)/sizeof(kronecker[0])); ++cnt) {
+ k = kronecker[cnt].n;
+ mp_set_l(&a, k);
+ /* only test positive values of a */
+ for (m = -10; m <= 10; m++) {
+ mp_set_l(&b, m);
+ if ((err = mp_kronecker(&a, &b, &i)) != MP_OKAY) {
+ printf("Failed executing mp_kronecker(%ld | %ld) %s.\n", kronecker[cnt].n, m, mp_error_to_string(err));
+ goto LBL_ERR;
+ }
+ if ((err == MP_OKAY) && (i != kronecker[cnt].c[m + 10])) {
+ printf("Failed trivial mp_kronecker(%ld | %ld) %d != %d\n", kronecker[cnt].n, m, i, kronecker[cnt].c[m + 10]);
+ goto LBL_ERR;
+ }
+ }
+ }
+
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_complement(void)
+{
+ int i;
+
+ mp_int a, b, c;
+ if (mp_init_multi(&a, &b, &c, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ for (i = 0; i < 1000; ++i) {
+ long l = rand_long();
+ mp_set_l(&a, l);
+ mp_complement(&a, &b);
+
+ l = ~l;
+ mp_set_l(&c, l);
+
+ if (mp_cmp(&b, &c) != MP_EQ) {
+ printf("\nmp_complement() bad result!");
+ goto LBL_ERR;
+ }
+ }
+
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_signed_rsh(void)
+{
+ int i;
+
+ mp_int a, b, d;
+ if (mp_init_multi(&a, &b, &d, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ for (i = 0; i < 1000; ++i) {
+ long l;
+ int em;
+
+ l = rand_long();
+ mp_set_l(&a, l);
+
+ em = abs(rand_int()) % 32;
+
+ mp_set_l(&d, l >> em);
+
+ mp_signed_rsh(&a, em, &b);
+ if (mp_cmp(&b, &d) != MP_EQ) {
+ printf("\nmp_signed_rsh() bad result!");
+ goto LBL_ERR;
+ }
+ }
+
+ mp_clear_multi(&a, &b, &d, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, &d, NULL);
+ return EXIT_FAILURE;
+
+}
+
+static int test_mp_xor(void)
+{
+ int i;
+
+ mp_int a, b, c, d;
+ if (mp_init_multi(&a, &b, &c, &d, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ for (i = 0; i < 1000; ++i) {
+ long l, em;
+
+ l = rand_long();
+ mp_set_l(&a,l);
+
+ em = rand_long();
+ mp_set_l(&b, em);
+
+ mp_set_l(&d, l ^ em);
+
+ mp_xor(&a, &b, &c);
+ if (mp_cmp(&c, &d) != MP_EQ) {
+ printf("\nmp_xor() bad result!");
+ goto LBL_ERR;
+ }
+ }
+
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_FAILURE;
+
+}
+
+static int test_mp_or(void)
+{
+ int i;
+
+ mp_int a, b, c, d;
+ if (mp_init_multi(&a, &b, &c, &d, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ for (i = 0; i < 1000; ++i) {
+ long l, em;
+
+ l = rand_long();
+ mp_set_l(&a, l);
+
+ em = rand_long();
+ mp_set_l(&b, em);
+
+ mp_set_l(&d, l | em);
+
+ mp_or(&a, &b, &c);
+ if (mp_cmp(&c, &d) != MP_EQ) {
+ printf("\nmp_or() bad result!");
+ goto LBL_ERR;
+ }
+ }
+
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_and(void)
+{
+ int i;
+
+ mp_int a, b, c, d;
+ if (mp_init_multi(&a, &b, &c, &d, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ for (i = 0; i < 1000; ++i) {
+ long l, em;
+
+ l = rand_long();
+ mp_set_l(&a, l);
+
+ em = rand_long();
+ mp_set_l(&b, em);
+
+ mp_set_l(&d, l & em);
+
+ mp_and(&a, &b, &c);
+ if (mp_cmp(&c, &d) != MP_EQ) {
+ printf("\nmp_and() bad result!");
+ goto LBL_ERR;
+ }
+ }
+
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_invmod(void)
+{
+ mp_int a, b, c, d;
+ if (mp_init_multi(&a, &b, &c, &d, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ /* mp_invmod corner-case of https://github.com/libtom/libtommath/issues/118 */
+ {
+ const char *a_ = "47182BB8DF0FFE9F61B1F269BACC066B48BA145D35137D426328DC3F88A5EA44";
+ const char *b_ = "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF";
+ const char *should_ = "0521A82E10376F8E4FDEF9A32A427AC2A0FFF686E00290D39E3E4B5522409596";
+
+ if (mp_read_radix(&a, a_, 16) != MP_OKAY) {
+ printf("\nmp_read_radix(a) failed!");
+ goto LBL_ERR;
+ }
+ if (mp_read_radix(&b, b_, 16) != MP_OKAY) {
+ printf("\nmp_read_radix(b) failed!");
+ goto LBL_ERR;
+ }
+ if (mp_read_radix(&c, should_, 16) != MP_OKAY) {
+ printf("\nmp_read_radix(should) failed!");
+ goto LBL_ERR;
+ }
+
+ if (mp_invmod(&a, &b, &d) != MP_OKAY) {
+ printf("\nmp_invmod() failed!");
+ goto LBL_ERR;
+ }
+
+ if (mp_cmp(&c, &d) != MP_EQ) {
+ printf("\nmp_invmod() bad result!");
+ goto LBL_ERR;
+ }
+ }
+
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_FAILURE;
+
+}
+
+#if defined(__STDC_IEC_559__) || defined(__GCC_IEC_559) || defined(__x86_64__) || defined(_M_X64) || defined(_M_AMD64) || defined(__i386__) || defined(_M_X86) || defined(__aarch64__) || defined(__arm__)
+static int test_mp_set_double(void)
+{
+ int i;
+
+ mp_int a, b;
+ if (mp_init_multi(&a, &b, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ /* test mp_get_double/mp_set_double */
+ if (mp_set_double(&a, +1.0/0.0) != MP_VAL) {
+ printf("\nmp_set_double should return MP_VAL for +inf");
+ goto LBL_ERR;
+ }
+ if (mp_set_double(&a, -1.0/0.0) != MP_VAL) {
+ printf("\nmp_set_double should return MP_VAL for -inf");
+ goto LBL_ERR;
+ }
+ if (mp_set_double(&a, +0.0/0.0) != MP_VAL) {
+ printf("\nmp_set_double should return MP_VAL for NaN");
+ goto LBL_ERR;
+ }
+ if (mp_set_double(&a, -0.0/0.0) != MP_VAL) {
+ printf("\nmp_set_double should return MP_VAL for NaN");
+ goto LBL_ERR;
+ }
+
+ for (i = 0; i < 1000; ++i) {
+ int tmp = rand_int();
+ double dbl = (double)tmp * rand_int() + 1;
+ if (mp_set_double(&a, dbl) != MP_OKAY) {
+ printf("\nmp_set_double() failed");
+ goto LBL_ERR;
+ }
+ if (dbl != mp_get_double(&a)) {
+ printf("\nmp_get_double() bad result!");
+ goto LBL_ERR;
+ }
+ if (mp_set_double(&a, -dbl) != MP_OKAY) {
+ printf("\nmp_set_double() failed");
+ goto LBL_ERR;
+ }
+ if (-dbl != mp_get_double(&a)) {
+ printf("\nmp_get_double() bad result!");
+ goto LBL_ERR;
+ }
+ }
+
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_FAILURE;
+
+}
+#endif
+
+static int test_mp_get_u32(void)
+{
+ unsigned long t;
+ int i;
+
+ mp_int a, b;
+ if (mp_init_multi(&a, &b, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ for (i = 0; i < 1000; ++i) {
+ t = (unsigned long)rand_long() & 0xFFFFFFFFuL;
+ mp_set_ul(&a, t);
+ if (t != mp_get_u32(&a)) {
+ printf("\nmp_get_u32() bad result!");
+ goto LBL_ERR;
+ }
+ }
+ mp_set_ul(&a, 0uL);
+ if (mp_get_u32(&a) != 0) {
+ printf("\nmp_get_u32() bad result!");
+ goto LBL_ERR;
+ }
+ mp_set_ul(&a, 0xFFFFFFFFuL);
+ if (mp_get_u32(&a) != 0xFFFFFFFFuL) {
+ printf("\nmp_get_u32() bad result!");
+ goto LBL_ERR;
+ }
+
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_get_ul(void)
+{
+ unsigned long s, t;
+ int i;
+
+ mp_int a, b;
+ if (mp_init_multi(&a, &b, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ for (i = 0; i < ((int)MP_SIZEOF_BITS(unsigned long) - 1); ++i) {
+ t = (1UL << (i+1)) - 1;
+ if (!t)
+ t = ~0UL;
+ printf(" t = 0x%lx i = %d\r", t, i);
+ do {
+ mp_set_ul(&a, t);
+ s = mp_get_ul(&a);
+ if (s != t) {
+ printf("\nmp_get_ul() bad result! 0x%lx != 0x%lx", s, t);
+ goto LBL_ERR;
+ }
+ t <<= 1;
+ } while (t != 0uL);
+ }
+
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_get_u64(void)
+{
+ unsigned long long q, r;
+ int i;
+
+ mp_int a, b;
+ if (mp_init_multi(&a, &b, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ for (i = 0; i < (int)(MP_SIZEOF_BITS(unsigned long long) - 1); ++i) {
+ r = (1ULL << (i+1)) - 1;
+ if (!r)
+ r = ~0ULL;
+ printf(" r = 0x%llx i = %d\r", r, i);
+ do {
+ mp_set_u64(&a, r);
+ q = mp_get_u64(&a);
+ if (q != r) {
+ printf("\nmp_get_u64() bad result! 0x%llx != 0x%llx", q, r);
+ goto LBL_ERR;
+ }
+ r <<= 1;
+ } while (r != 0uLL);
+ }
+
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_FAILURE;
+
+}
+
+static int test_mp_sqrt(void)
+{
+ int i, n;
+
+ mp_int a, b, c;
+ if (mp_init_multi(&a, &b, &c, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ for (i = 0; i < 1000; ++i) {
+ printf("%6d\r", i);
+ fflush(stdout);
+ n = (rand_int() & 15) + 1;
+ mp_rand(&a, n);
+ if (mp_sqrt(&a, &b) != MP_OKAY) {
+ printf("\nmp_sqrt() error!");
+ goto LBL_ERR;
+ }
+ mp_root_u32(&a, 2uL, &c);
+ if (mp_cmp_mag(&b, &c) != MP_EQ) {
+ printf("mp_sqrt() bad result!\n");
+ goto LBL_ERR;
+ }
+ }
+
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_is_square(void)
+{
+ int i, n;
+
+ mp_int a, b;
+ mp_bool res;
+
+ if (mp_init_multi(&a, &b, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ for (i = 0; i < 1000; ++i) {
+ printf("%6d\r", i);
+ fflush(stdout);
+
+ /* test mp_is_square false negatives */
+ n = (rand_int() & 7) + 1;
+ mp_rand(&a, n);
+ mp_sqr(&a, &a);
+ if (mp_is_square(&a, &res) != MP_OKAY) {
+ printf("\nfn:mp_is_square() error!");
+ goto LBL_ERR;
+ }
+ if (res == MP_NO) {
+ printf("\nfn:mp_is_square() bad result!");
+ goto LBL_ERR;
+ }
+
+ /* test for false positives */
+ mp_add_d(&a, 1uL, &a);
+ if (mp_is_square(&a, &res) != MP_OKAY) {
+ printf("\nfp:mp_is_square() error!");
+ goto LBL_ERR;
+ }
+ if (res == MP_YES) {
+ printf("\nfp:mp_is_square() bad result!");
+ goto LBL_ERR;
+ }
+
+ }
+ printf("\n\n");
+
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_sqrtmod_prime(void)
+{
+ struct mp_sqrtmod_prime_st {
+ unsigned long p;
+ unsigned long n;
+ mp_digit r;
+ };
+
+ static struct mp_sqrtmod_prime_st sqrtmod_prime[] = {
+ { 5, 14, 3 },
+ { 7, 9, 4 },
+ { 113, 2, 62 }
+ };
+ int i;
+
+ mp_int a, b, c;
+ if (mp_init_multi(&a, &b, &c, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ /* r^2 = n (mod p) */
+ for (i = 0; i < (int)(sizeof(sqrtmod_prime)/sizeof(sqrtmod_prime[0])); ++i) {
+ mp_set_ul(&a, sqrtmod_prime[i].p);
+ mp_set_ul(&b, sqrtmod_prime[i].n);
+ if (mp_sqrtmod_prime(&b, &a, &c) != MP_OKAY) {
+ printf("Failed executing %d. mp_sqrtmod_prime\n", (i+1));
+ goto LBL_ERR;
+ }
+ if (mp_cmp_d(&c, sqrtmod_prime[i].r) != MP_EQ) {
+ printf("Failed %d. trivial mp_sqrtmod_prime\n", (i+1));
+ ndraw(&c, "r");
+ goto LBL_ERR;
+ }
+ }
+
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_prime_rand(void)
+{
+ int ix;
+ mp_err err;
+ mp_int a, b;
+ if (mp_init_multi(&a, &b, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ /* test for size */
+ for (ix = 10; ix < 128; ix++) {
+ printf("Testing (not safe-prime): %9d bits \r", ix);
+ fflush(stdout);
+ err = mp_prime_rand(&a, 8, ix, (rand_int() & 1) ? 0 : MP_PRIME_2MSB_ON);
+ if (err != MP_OKAY) {
+ printf("\nfailed with error: %s\n", mp_error_to_string(err));
+ goto LBL_ERR;
+ }
+ if (mp_count_bits(&a) != ix) {
+ printf("Prime is %d not %d bits!!!\n", mp_count_bits(&a), ix);
+ goto LBL_ERR;
+ }
+ }
+ printf("\n");
+
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_prime_is_prime(void)
+{
+ int ix;
+ mp_err err;
+ mp_bool cnt, fu;
+
+ mp_int a, b;
+ if (mp_init_multi(&a, &b, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ /* strong Miller-Rabin pseudoprime to the first 200 primes (F. Arnault) */
+ puts("Testing mp_prime_is_prime() with Arnault's pseudoprime 803...901 \n");
+ mp_read_radix(&a,
+ "91xLNF3roobhzgTzoFIG6P13ZqhOVYSN60Fa7Cj2jVR1g0k89zdahO9/kAiRprpfO1VAp1aBHucLFV/qLKLFb+zonV7R2Vxp1K13ClwUXStpV0oxTNQVjwybmFb5NBEHImZ6V7P6+udRJuH8VbMEnS0H8/pSqQrg82OoQQ2fPpAk6G1hkjqoCv5s/Yr",
+ 64);
+ mp_prime_is_prime(&a, mp_prime_rabin_miller_trials(mp_count_bits(&a)), &cnt);
+ if (cnt == MP_YES) {
+ printf("Arnault's pseudoprime is not prime but mp_prime_is_prime says it is.\n");
+ goto LBL_ERR;
+ }
+ /* About the same size as Arnault's pseudoprime */
+ puts("Testing mp_prime_is_prime() with certified prime 2^1119 + 53\n");
+ mp_set(&a, 1uL);
+ mp_mul_2d(&a,1119,&a);
+ mp_add_d(&a, 53uL, &a);
+ err = mp_prime_is_prime(&a, mp_prime_rabin_miller_trials(mp_count_bits(&a)), &cnt);
+ /* small problem */
+ if (err != MP_OKAY) {
+ printf("\nfailed with error: %s\n", mp_error_to_string(err));
+ }
+ /* large problem */
+ if (cnt == MP_NO) {
+ printf("A certified prime is a prime but mp_prime_is_prime says it is not.\n");
+ }
+ if ((err != MP_OKAY) || (cnt == MP_NO)) {
+ printf("prime tested was: 0x");
+ mp_fwrite(&a,16,stdout);
+ putchar('\n');
+ goto LBL_ERR;
+ }
+ for (ix = 16; ix < 128; ix++) {
+ printf("Testing ( safe-prime): %9d bits \r", ix);
+ fflush(stdout);
+ err = mp_prime_rand(&a, 8, ix, ((rand_int() & 1) ? 0 : MP_PRIME_2MSB_ON) | MP_PRIME_SAFE);
+ if (err != MP_OKAY) {
+ printf("\nfailed with error: %s\n", mp_error_to_string(err));
+ goto LBL_ERR;
+ }
+ if (mp_count_bits(&a) != ix) {
+ printf("Prime is %d not %d bits!!!\n", mp_count_bits(&a), ix);
+ goto LBL_ERR;
+ }
+ /* let's see if it's really a safe prime */
+ mp_sub_d(&a, 1uL, &b);
+ mp_div_2(&b, &b);
+ err = mp_prime_is_prime(&b, mp_prime_rabin_miller_trials(mp_count_bits(&b)), &cnt);
+ /* small problem */
+ if (err != MP_OKAY) {
+ printf("\nfailed with error: %s\n", mp_error_to_string(err));
+ }
+ /* large problem */
+ if (cnt == MP_NO) {
+ printf("\nsub is not prime!\n");
+ }
+ mp_prime_frobenius_underwood(&b, &fu);
+ if (fu == MP_NO) {
+ printf("\nfrobenius-underwood says sub is not prime!\n");
+ }
+ if ((err != MP_OKAY) || (cnt == MP_NO)) {
+ printf("prime tested was: 0x");
+ mp_fwrite(&a,16,stdout);
+ putchar('\n');
+ printf("sub tested was: 0x");
+ mp_fwrite(&b,16,stdout);
+ putchar('\n');
+ goto LBL_ERR;
+ }
+
+ }
+ /* Check regarding problem #143 */
+#ifndef MP_8BIT
+ mp_read_radix(&a,
+ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A3620FFFFFFFFFFFFFFFF",
+ 16);
+ err = mp_prime_strong_lucas_selfridge(&a, &cnt);
+ /* small problem */
+ if (err != MP_OKAY) {
+ printf("\nmp_prime_strong_lucas_selfridge failed with error: %s\n", mp_error_to_string(err));
+ }
+ /* large problem */
+ if (cnt == MP_NO) {
+ printf("\n\nissue #143 - mp_prime_strong_lucas_selfridge FAILED!\n");
+ }
+ if ((err != MP_OKAY) || (cnt == MP_NO)) {
+ printf("prime tested was: 0x");
+ mp_fwrite(&a,16,stdout);
+ putchar('\n');
+ goto LBL_ERR;
+ }
+#endif
+
+ printf("\n\n");
+
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_FAILURE;
+
+}
+
+
+static int test_mp_prime_next_prime(void)
+{
+ mp_err err;
+ mp_int a, b, c;
+
+ mp_init_multi(&a, &b, &c, NULL);
+
+
+ /* edge cases */
+ mp_set(&a, 0u);
+ if ((err = mp_prime_next_prime(&a, 5, 0)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (mp_cmp_d(&a, 2u) != MP_EQ) {
+ printf("mp_prime_next_prime: output should have been 2 but was: ");
+ mp_fwrite(&a,10,stdout);
+ putchar('\n');
+ goto LBL_ERR;
+ }
+
+ mp_set(&a, 0u);
+ if ((err = mp_prime_next_prime(&a, 5, 1)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (mp_cmp_d(&a, 3u) != MP_EQ) {
+ printf("mp_prime_next_prime: output should have been 3 but was: ");
+ mp_fwrite(&a,10,stdout);
+ putchar('\n');
+ goto LBL_ERR;
+ }
+
+ mp_set(&a, 2u);
+ if ((err = mp_prime_next_prime(&a, 5, 0)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (mp_cmp_d(&a, 3u) != MP_EQ) {
+ printf("mp_prime_next_prime: output should have been 3 but was: ");
+ mp_fwrite(&a,10,stdout);
+ putchar('\n');
+ goto LBL_ERR;
+ }
+
+ mp_set(&a, 2u);
+ if ((err = mp_prime_next_prime(&a, 5, 1)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (mp_cmp_d(&a, 3u) != MP_EQ) {
+ printf("mp_prime_next_prime: output should have been 3 but was: ");
+ mp_fwrite(&a,10,stdout);
+ putchar('\n');
+ goto LBL_ERR;
+ }
+ mp_set(&a, 8);
+ if ((err = mp_prime_next_prime(&a, 5, 1)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (mp_cmp_d(&a, 11u) != MP_EQ) {
+ printf("mp_prime_next_prime: output should have been 11 but was: ");
+ mp_fwrite(&a,10,stdout);
+ putchar('\n');
+ goto LBL_ERR;
+ }
+ /* 2^300 + 157 is a 300 bit large prime to guarantee a multi-limb bigint */
+ if ((err = mp_2expt(&a, 300)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ mp_set_u32(&b, 157);
+ if ((err = mp_add(&a, &b, &a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if ((err = mp_copy(&a, &b)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ /* 2^300 + 385 is the next prime */
+ mp_set_u32(&c, 228);
+ if ((err = mp_add(&b, &c, &b)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if ((err = mp_prime_next_prime(&a, 5, 0)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (mp_cmp(&a, &b) != MP_EQ) {
+ printf("mp_prime_next_prime: output should have been\n");
+ mp_fwrite(&b,10,stdout);
+ putchar('\n');
+ printf("but was:\n");
+ mp_fwrite(&a,10,stdout);
+ putchar('\n');
+ goto LBL_ERR;
+ }
+
+ /* Use another temporary variable or recompute? Mmh... */
+ if ((err = mp_2expt(&a, 300)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ mp_set_u32(&b, 157);
+ if ((err = mp_add(&a, &b, &a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if ((err = mp_copy(&a, &b)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ /* 2^300 + 631 is the next prime congruent to 3 mod 4*/
+ mp_set_u32(&c, 474);
+ if ((err = mp_add(&b, &c, &b)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if ((err = mp_prime_next_prime(&a, 5, 1)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (mp_cmp(&a, &b) != MP_EQ) {
+ printf("mp_prime_next_prime (bbs): output should have been\n");
+ mp_fwrite(&b,10,stdout);
+ putchar('\n');
+ printf("but was:\n");
+ mp_fwrite(&a,10,stdout);
+ putchar('\n');
+ goto LBL_ERR;
+ }
+
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_montgomery_reduce(void)
+{
+ mp_digit mp;
+ int ix, i, n;
+ char buf[4096];
+
+ /* size_t written; */
+
+ mp_int a, b, c, d, e;
+ if (mp_init_multi(&a, &b, &c, &d, &e, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ /* test montgomery */
+ for (i = 1; i <= 10; i++) {
+ if (i == 10)
+ i = 1000;
+ printf(" digit size: %2d\r", i);
+ fflush(stdout);
+ for (n = 0; n < 1000; n++) {
+ mp_rand(&a, i);
+ a.dp[0] |= 1;
+
+ /* let's see if R is right */
+ mp_montgomery_calc_normalization(&b, &a);
+ mp_montgomery_setup(&a, &mp);
+
+ /* now test a random reduction */
+ for (ix = 0; ix < 100; ix++) {
+ mp_rand(&c, 1 + abs(rand_int()) % (2*i));
+ mp_copy(&c, &d);
+ mp_copy(&c, &e);
+
+ mp_mod(&d, &a, &d);
+ mp_montgomery_reduce(&c, &a, mp);
+ mp_mulmod(&c, &b, &a, &c);
+
+ if (mp_cmp(&c, &d) != MP_EQ) {
+/* *INDENT-OFF* */
+ printf("d = e mod a, c = e MOD a\n");
+ mp_to_decimal(&a, buf, sizeof(buf)); printf("a = %s\n", buf);
+ mp_to_decimal(&e, buf, sizeof(buf)); printf("e = %s\n", buf);
+ mp_to_decimal(&d, buf, sizeof(buf)); printf("d = %s\n", buf);
+ mp_to_decimal(&c, buf, sizeof(buf)); printf("c = %s\n", buf);
+
+ printf("compare no compare!\n"); goto LBL_ERR;
+/* *INDENT-ON* */
+ }
+ /* only one big montgomery reduction */
+ if (i > 10) {
+ n = 1000;
+ ix = 100;
+ }
+ }
+ }
+ }
+
+ printf("\n\n");
+
+ mp_clear_multi(&a, &b, &c, &d, &e, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, &c, &d, &e, NULL);
+ return EXIT_FAILURE;
+
+}
+
+static int test_mp_read_radix(void)
+{
+ char buf[4096];
+ size_t written;
+ mp_err err;
+
+ mp_int a;
+ if (mp_init_multi(&a, NULL)!= MP_OKAY) goto LTM_ERR;
+
+ if ((err = mp_read_radix(&a, "123456", 10)) != MP_OKAY) goto LTM_ERR;
+
+ if ((err = mp_to_radix(&a, buf, SIZE_MAX, &written, 10)) != MP_OKAY) goto LTM_ERR;
+ printf(" '123456' a == %s, length = %zu\n", buf, written);
+
+ /* See comment in bn_mp_to_radix.c */
+ /*
+ if( (err = mp_to_radix(&a, buf, 3u, &written, 10) ) != MP_OKAY) goto LTM_ERR;
+ printf(" '56' a == %s, length = %zu\n", buf, written);
+
+ if( (err = mp_to_radix(&a, buf, 4u, &written, 10) ) != MP_OKAY) goto LTM_ERR;
+ printf(" '456' a == %s, length = %zu\n", buf, written);
+ if( (err = mp_to_radix(&a, buf, 30u, &written, 10) ) != MP_OKAY) goto LTM_ERR;
+ printf(" '123456' a == %s, length = %zu, error = %s\n",
+ buf, written, mp_error_to_string(err));
+ */
+ if ((err = mp_read_radix(&a, "-123456", 10)) != MP_OKAY) goto LTM_ERR;
+ if ((err = mp_to_radix(&a, buf, SIZE_MAX, &written, 10)) != MP_OKAY) goto LTM_ERR;
+ printf(" '-123456' a == %s, length = %zu\n", buf, written);
+
+ if ((err = mp_read_radix(&a, "0", 10)) != MP_OKAY) goto LTM_ERR;
+ if ((err = mp_to_radix(&a, buf, SIZE_MAX, &written, 10)) != MP_OKAY) goto LTM_ERR;
+ printf(" '0' a == %s, length = %zu\n", buf, written);
+
+
+
+ /* Although deprecated it needs to function as long as it isn't dropped */
+ /*
+ printf("Testing deprecated mp_toradix_n\n");
+ if( (err = mp_read_radix(&a, "-123456", 10) ) != MP_OKAY) goto LTM_ERR;
+ if( (err = mp_toradix_n(&a, buf, 10, 3) ) != MP_OKAY) goto LTM_ERR;
+ printf("a == %s\n", buf);
+ if( (err = mp_toradix_n(&a, buf, 10, 4) ) != MP_OKAY) goto LTM_ERR;
+ printf("a == %s\n", buf);
+ if( (err = mp_toradix_n(&a, buf, 10, 30) ) != MP_OKAY) goto LTM_ERR;
+ printf("a == %s\n", buf);
+ */
+
+
+ while (0) {
+ char *s = fgets(buf, sizeof(buf), stdin);
+ if (s != buf) break;
+ mp_read_radix(&a, buf, 10);
+ mp_prime_next_prime(&a, 5, 1);
+ mp_to_radix(&a, buf, sizeof(buf), NULL, 10);
+ printf("%s, %lu\n", buf, (unsigned long)a.dp[0] & 3uL);
+ }
+
+ mp_clear(&a);
+ return EXIT_SUCCESS;
+LTM_ERR:
+ mp_clear(&a);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_cnt_lsb(void)
+{
+ int ix;
+
+ mp_int a, b;
+ if (mp_init_multi(&a, &b, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ mp_set(&a, 1uL);
+ for (ix = 0; ix < 1024; ix++) {
+ if (mp_cnt_lsb(&a) != ix) {
+ printf("Failed at %d, %d\n", ix, mp_cnt_lsb(&a));
+ goto LBL_ERR;
+ }
+ mp_mul_2(&a, &a);
+ }
+
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_FAILURE;
+
+}
+
+static int test_mp_reduce_2k(void)
+{
+ int ix, cnt;
+
+ mp_int a, b, c, d;
+ if (mp_init_multi(&a, &b, &c, &d, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ /* test mp_reduce_2k */
+ for (cnt = 3; cnt <= 128; ++cnt) {
+ mp_digit tmp;
+
+ mp_2expt(&a, cnt);
+ mp_sub_d(&a, 2uL, &a); /* a = 2**cnt - 2 */
+
+ printf("\r %4d bits", cnt);
+ printf("(%d)", mp_reduce_is_2k(&a));
+ mp_reduce_2k_setup(&a, &tmp);
+ printf("(%lu)", (unsigned long) tmp);
+ for (ix = 0; ix < 1000; ix++) {
+ if (!(ix & 127)) {
+ printf(".");
+ fflush(stdout);
+ }
+ mp_rand(&b, (cnt / MP_DIGIT_BIT + 1) * 2);
+ mp_copy(&c, &b);
+ mp_mod(&c, &a, &c);
+ mp_reduce_2k(&b, &a, 2uL);
+ if (mp_cmp(&c, &b) != MP_EQ) {
+ printf("FAILED\n");
+ goto LBL_ERR;
+ }
+ }
+ }
+
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_div_3(void)
+{
+ int cnt;
+
+ mp_int a, b, c, d, e;
+ if (mp_init_multi(&a, &b, &c, &d, &e, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ /* test mp_div_3 */
+ mp_set(&d, 3uL);
+ for (cnt = 0; cnt < 10000;) {
+ mp_digit r2;
+
+ if (!(++cnt & 127)) {
+ printf("%9d\r", cnt);
+ fflush(stdout);
+ }
+ mp_rand(&a, abs(rand_int()) % 128 + 1);
+ mp_div(&a, &d, &b, &e);
+ mp_div_3(&a, &c, &r2);
+
+ if (mp_cmp(&b, &c) || mp_cmp_d(&e, r2)) {
+ printf("\nmp_div_3 => Failure\n");
+ goto LBL_ERR;
+ }
+ }
+ printf("\nPassed div_3 testing");
+
+ mp_clear_multi(&a, &b, &c, &d, &e, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, &c, &d, &e, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_dr_reduce(void)
+{
+ mp_digit mp;
+ int cnt;
+ unsigned rr;
+ int ix;
+
+ mp_int a, b, c;
+ if (mp_init_multi(&a, &b, &c, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+
+ /* test the DR reduction */
+ for (cnt = 2; cnt < 32; cnt++) {
+ printf("\r%d digit modulus", cnt);
+ mp_grow(&a, cnt);
+ mp_zero(&a);
+ for (ix = 1; ix < cnt; ix++) {
+ a.dp[ix] = MP_MASK;
+ }
+ a.used = cnt;
+ a.dp[0] = 3;
+
+ mp_rand(&b, cnt - 1);
+ mp_copy(&b, &c);
+
+ rr = 0;
+ do {
+ if (!(rr & 127)) {
+ printf(".");
+ fflush(stdout);
+ }
+ mp_sqr(&b, &b);
+ mp_add_d(&b, 1uL, &b);
+ mp_copy(&b, &c);
+
+ mp_mod(&b, &a, &b);
+ mp_dr_setup(&a, &mp);
+ mp_dr_reduce(&c, &a, mp);
+
+ if (mp_cmp(&b, &c) != MP_EQ) {
+ printf("Failed on trial %u\n", rr);
+ goto LBL_ERR;
+ }
+ } while (++rr < 500);
+ printf(" passed");
+ fflush(stdout);
+ }
+
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_reduce_2k_l(void)
+{
+# if LTM_DEMO_TEST_REDUCE_2K_L
+ mp_int a, b, c, d;
+ int cnt;
+ char buf[4096];
+ size_t length[1];
+ if (mp_init_multi(&a, &b, NULL)!= MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+ /* test the mp_reduce_2k_l code */
+# if LTM_DEMO_TEST_REDUCE_2K_L == 1
+ /* first load P with 2^1024 - 0x2A434 B9FDEC95 D8F9D550 FFFFFFFF FFFFFFFF */
+ mp_2expt(&a, 1024);
+ mp_read_radix(&b, "2A434B9FDEC95D8F9D550FFFFFFFFFFFFFFFF", 16);
+ mp_sub(&a, &b, &a);
+# elif LTM_DEMO_TEST_REDUCE_2K_L == 2
+ /* p = 2^2048 - 0x1 00000000 00000000 00000000 00000000 4945DDBF 8EA2A91D 5776399B B83E188F */
+ mp_2expt(&a, 2048);
+ mp_read_radix(&b,
+ "1000000000000000000000000000000004945DDBF8EA2A91D5776399BB83E188F",
+ 16);
+ mp_sub(&a, &b, &a);
+# else
+# error oops
+# endif
+ *length = sizeof(buf);
+ mp_to_radix(&a, buf, length, 10);
+ printf("\n\np==%s, length = %zu\n", buf, *length);
+ /* now mp_reduce_is_2k_l() should return */
+ if (mp_reduce_is_2k_l(&a) != 1) {
+ printf("mp_reduce_is_2k_l() return 0, should be 1\n");
+ goto LBL_ERR;
+ }
+ mp_reduce_2k_setup_l(&a, &d);
+ /* now do a million square+1 to see if it varies */
+ mp_rand(&b, 64);
+ mp_mod(&b, &a, &b);
+ mp_copy(&b, &c);
+ printf("Testing: mp_reduce_2k_l...");
+ fflush(stdout);
+ for (cnt = 0; cnt < (int)(1uL << 20); cnt++) {
+ mp_sqr(&b, &b);
+ mp_add_d(&b, 1uL, &b);
+ mp_reduce_2k_l(&b, &a, &d);
+ mp_sqr(&c, &c);
+ mp_add_d(&c, 1uL, &c);
+ mp_mod(&c, &a, &c);
+ if (mp_cmp(&b, &c) != MP_EQ) {
+ printf("mp_reduce_2k_l() failed at step %d\n", cnt);
+ mp_to_hex(&b, buf, sizeof(buf));
+ printf("b == %s\n", buf);
+ mp_to_hex(&c, buf, sizeof(buf));
+ printf("c == %s\n", buf);
+ goto LBL_ERR;
+ }
+ }
+
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_FAILURE;
+#else
+ return EXIT_SUCCESS;
+# endif /* LTM_DEMO_TEST_REDUCE_2K_L */
+}
+/* stripped down version of mp_radix_size. The faster version can be off by up t
+o +3 */
+/* TODO: This function should be removed, replaced by mp_radix_size, mp_radix_size_overestimate in 2.0 */
+static mp_err s_rs(const mp_int *a, int radix, uint32_t *size)
+{
+ mp_err res;
+ uint32_t digs = 0u;
+ mp_int t;
+ mp_digit d;
+ *size = 0u;
+ if (mp_iszero(a) == MP_YES) {
+ *size = 2u;
+ return MP_OKAY;
+ }
+ if (radix == 2) {
+ *size = (uint32_t)mp_count_bits(a) + 1u;
+ return MP_OKAY;
+ }
+ if ((res = mp_init_copy(&t, a)) != MP_OKAY) {
+ return res;
+ }
+ t.sign = MP_ZPOS;
+ while (mp_iszero(&t) == MP_NO) {
+ if ((res = mp_div_d(&t, (mp_digit)radix, &t, &d)) != MP_OKAY) {
+ mp_clear(&t);
+ return res;
+ }
+ ++digs;
+ }
+ mp_clear(&t);
+ *size = digs + 1;
+ return MP_OKAY;
+}
+static int test_mp_log_u32(void)
+{
+ mp_int a;
+ mp_digit d;
+ uint32_t base, lb, size;
+ const uint32_t max_base = MP_MIN(UINT32_MAX, MP_DIGIT_MAX);
+
+ if (mp_init(&a) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ /*
+ base a result
+ 0 x MP_VAL
+ 1 x MP_VAL
+ */
+ mp_set(&a, 42uL);
+ base = 0u;
+ if (mp_log_u32(&a, base, &lb) != MP_VAL) {
+ goto LBL_ERR;
+ }
+ base = 1u;
+ if (mp_log_u32(&a, base, &lb) != MP_VAL) {
+ goto LBL_ERR;
+ }
+ /*
+ base a result
+ 2 0 MP_VAL
+ 2 1 0
+ 2 2 1
+ 2 3 1
+ */
+ base = 2u;
+ mp_zero(&a);
+ if (mp_log_u32(&a, base, &lb) != MP_VAL) {
+ goto LBL_ERR;
+ }
+
+ for (d = 1; d < 4; d++) {
+ mp_set(&a, d);
+ if (mp_log_u32(&a, base, &lb) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (lb != ((d == 1)?0uL:1uL)) {
+ goto LBL_ERR;
+ }
+ }
+ /*
+ base a result
+ 3 0 MP_VAL
+ 3 1 0
+ 3 2 0
+ 3 3 1
+ */
+ base = 3u;
+ mp_zero(&a);
+ if (mp_log_u32(&a, base, &lb) != MP_VAL) {
+ goto LBL_ERR;
+ }
+ for (d = 1; d < 4; d++) {
+ mp_set(&a, d);
+ if (mp_log_u32(&a, base, &lb) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (lb != ((d < base)?0uL:1uL)) {
+ goto LBL_ERR;
+ }
+ }
+
+ /*
+ bases 2..64 with "a" a random large constant.
+ The range of bases tested allows to check with
+ radix_size.
+ */
+ if (mp_rand(&a, 10) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ for (base = 2u; base < 65u; base++) {
+ if (mp_log_u32(&a, base, &lb) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (s_rs(&a,(int)base, &size) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ /* radix_size includes the memory needed for '\0', too*/
+ size -= 2;
+ if (lb != size) {
+ goto LBL_ERR;
+ }
+ }
+
+ /*
+ bases 2..64 with "a" a random small constant to
+ test the part of mp_ilogb that uses native types.
+ */
+ if (mp_rand(&a, 1) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ for (base = 2u; base < 65u; base++) {
+ if (mp_log_u32(&a, base, &lb) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (s_rs(&a,(int)base, &size) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ size -= 2;
+ if (lb != size) {
+ goto LBL_ERR;
+ }
+ }
+
+ /*Test upper edgecase with base UINT32_MAX and number (UINT32_MAX/2)*UINT32_MAX^10 */
+ mp_set(&a, max_base);
+ if (mp_expt_u32(&a, 10uL, &a) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (mp_add_d(&a, max_base / 2, &a) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (mp_log_u32(&a, max_base, &lb) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (lb != 10u) {
+ goto LBL_ERR;
+ }
+
+ mp_clear(&a);
+ return EXIT_SUCCESS;
+LBL_ERR:
+ mp_clear(&a);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_incr(void)
+{
+ mp_int a, b;
+ mp_err e = MP_OKAY;
+
+ if ((e = mp_init_multi(&a, &b, NULL)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+
+ /* Does it increment inside the limits of a MP_xBIT limb? */
+ mp_set(&a, MP_MASK/2);
+ if ((e = mp_incr(&a)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if (mp_cmp_d(&a, (MP_MASK/2uL) + 1uL) != MP_EQ) {
+ goto LTM_ERR;
+ }
+
+ /* Does it increment outside of the limits of a MP_xBIT limb? */
+ mp_set(&a, MP_MASK);
+ mp_set(&b, MP_MASK);
+ if ((e = mp_incr(&a)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((e = mp_add_d(&b, 1uL, &b)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if (mp_cmp(&a, &b) != MP_EQ) {
+ goto LTM_ERR;
+ }
+
+ /* Does it increment from -1 to 0? */
+ mp_set(&a, 1uL);
+ a.sign = MP_NEG;
+ if ((e = mp_incr(&a)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if (mp_cmp_d(&a, 0uL) != MP_EQ) {
+ goto LTM_ERR;
+ }
+
+ /* Does it increment from -(MP_MASK + 1) to -MP_MASK? */
+ mp_set(&a, MP_MASK);
+ if ((e = mp_add_d(&a, 1uL, &a)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ a.sign = MP_NEG;
+ if ((e = mp_incr(&a)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if (a.sign != MP_NEG) {
+ goto LTM_ERR;
+ }
+ a.sign = MP_ZPOS;
+ if (mp_cmp_d(&a, MP_MASK) != MP_EQ) {
+ goto LTM_ERR;
+ }
+
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_SUCCESS;
+LTM_ERR:
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_decr(void)
+{
+ mp_int a, b;
+ mp_err e = MP_OKAY;
+
+ if ((e = mp_init_multi(&a, &b, NULL)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+
+ /* Does it decrement inside the limits of a MP_xBIT limb? */
+ mp_set(&a, MP_MASK/2);
+ if ((e = mp_decr(&a)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if (mp_cmp_d(&a, (MP_MASK/2uL) - 1uL) != MP_EQ) {
+ goto LTM_ERR;
+ }
+
+ /* Does it decrement outside of the limits of a MP_xBIT limb? */
+ mp_set(&a, MP_MASK);
+ if ((e = mp_add_d(&a, 1uL, &a)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((e = mp_decr(&a)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if (mp_cmp_d(&a, MP_MASK) != MP_EQ) {
+ goto LTM_ERR;
+ }
+
+ /* Does it decrement from 0 to -1? */
+ mp_zero(&a);
+ if ((e = mp_decr(&a)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if (a.sign == MP_NEG) {
+ a.sign = MP_ZPOS;
+ if (mp_cmp_d(&a, 1uL) != MP_EQ) {
+ goto LTM_ERR;
+ }
+ } else {
+ goto LTM_ERR;
+ }
+
+
+ /* Does it decrement from -MP_MASK to -(MP_MASK + 1)? */
+ mp_set(&a, MP_MASK);
+ a.sign = MP_NEG;
+ mp_set(&b, MP_MASK);
+ b.sign = MP_NEG;
+ if ((e = mp_sub_d(&b, 1uL, &b)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((e = mp_decr(&a)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if (mp_cmp(&a, &b) != MP_EQ) {
+ goto LTM_ERR;
+ }
+
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_SUCCESS;
+LTM_ERR:
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_FAILURE;
+}
+
+/*
+ Cannot test mp_exp(_d) without mp_root and vice versa.
+ So one of the two has to be tested from scratch.
+
+ Numbers generated by
+ for i in {1..10}
+ do
+ seed=$(head -c 10000 /dev/urandom | tr -dc '[:digit:]' | head -c 120);
+ echo $seed;
+ convertbase $seed 10 64;
+ done
+
+ (The program "convertbase" uses libtommath's to/from_radix functions)
+
+ Roots were precalculated with Pari/GP
+
+ default(realprecision,1000);
+ for(n=3,100,r = floor(a^(1/n));printf("\"" r "\", "))
+
+ All numbers as strings to simplifiy things, especially for the
+ low-mp branch.
+*/
+
+static int test_mp_root_u32(void)
+{
+ mp_int a, c, r;
+ mp_err e;
+ int i, j;
+
+ const char *input[] = {
+ "4n9cbk886QtLQmofprid3l2Q0GD8Yv979Lh8BdZkFE8g2pDUUSMBET/+M/YFyVZ3mBp",
+ "5NlgzHhmIX05O5YoW5yW5reAlVNtRAlIcN2dfoATnNdc1Cw5lHZUTwNthmK6/ZLKfY6",
+ "3gweiHDX+ji5utraSe46IJX+uuh7iggs63xIpMP5MriU4Np+LpHI5are8RzS9pKh9xP",
+ "5QOJUSKMrfe7LkeyJOlupS8h7bjT+TXmZkDzOjZtfj7mdA7cbg0lRX3CuafhjIrpK8S",
+ "4HtYFldVkyVbrlg/s7kmaA7j45PvLQm+1bbn6ehgP8tVoBmGbv2yDQI1iQQze4AlHyN",
+ "3bwCUx79NAR7c68OPSp5ZabhZ9aBEr7rWNTO2oMY7zhbbbw7p6shSMxqE9K9nrTNucf",
+ "4j5RGb78TfuYSzrXn0z6tiAoWiRI81hGY3el9AEa9S+gN4x/AmzotHT2Hvj6lyBpE7q",
+ "4lwg30SXqZhEHNsl5LIXdyu7UNt0VTWebP3m7+WUL+hsnFW9xJe7UnzYngZsvWh14IE",
+ "1+tcqFeRuGqjRADRoRUJ8gL4UUSFQVrVVoV6JpwVcKsuBq5G0pABn0dLcQQQMViiVRj",
+ "hXwxuFySNSFcmbrs/coz4FUAaUYaOEt+l4V5V8vY71KyBvQPxRq/6lsSrG2FHvWDax"
+ };
+ /* roots 3-100 of the above */
+ const char *root[10][100] = {
+ {
+ "9163694094944489658600517465135586130944",
+ "936597377180979771960755204040", "948947857956884030956907",
+ "95727185767390496595", "133844854039712620", "967779611885360",
+ "20926191452627", "974139547476", "79203891950", "9784027073",
+ "1667309744", "365848129", "98268452", "31109156", "11275351",
+ "4574515", "2040800", "986985", "511525", "281431", "163096",
+ "98914", "62437", "40832", "27556", "19127", "13614", "9913",
+ "7367", "5577", "4294", "3357", "2662", "2138", "1738", "1428",
+ "1185", "993", "839", "715", "613", "530", "461", "403", "355",
+ "314", "279", "249", "224", "202", "182", "166", "151", "138",
+ "126", "116", "107", "99", "92", "85", "79", "74", "69", "65", "61",
+ "57", "54", "51", "48", "46", "43", "41", "39", "37", "36", "34",
+ "32", "31", "30", "28", "27", "26", "25", "24", "23", "23", "22",
+ "21", "20", "20", "19", "18", "18", "17", "17", "16", "16", "15"
+ }, {
+ "9534798256755061606359588498764080011382",
+ "964902943621813525741417593772", "971822399862464674540423",
+ "97646291566833512831", "136141536090599560", "982294733581430",
+ "21204945933335", "985810529393", "80066084985", "9881613813",
+ "1682654547", "368973625", "99051783", "31341581", "11354620",
+ "4604882", "2053633", "992879", "514434", "282959", "163942",
+ "99406", "62736", "41020", "27678", "19208", "13670", "9952",
+ "7395", "5598", "4310", "3369", "2671", "2145", "1744", "1433",
+ "1189", "996", "842", "717", "615", "531", "462", "404", "356",
+ "315", "280", "250", "224", "202", "183", "166", "151", "138",
+ "127", "116", "107", "99", "92", "85", "80", "74", "70", "65", "61",
+ "58", "54", "51", "48", "46", "43", "41", "39", "37", "36", "34",
+ "32", "31", "30", "29", "27", "26", "25", "24", "23", "23", "22",
+ "21", "20", "20", "19", "18", "18", "17", "17", "16", "16", "15"
+ }, {
+ "8398539113202579297642815367509019445624",
+ "877309458945432597462853440936", "900579899458998599215071",
+ "91643543761699761637", "128935656335800903", "936647990947203",
+ "20326748623514", "948988882684", "77342677787", "9573063447",
+ "1634096832", "359076114", "96569670", "30604705", "11103188",
+ "4508519", "2012897", "974160", "505193", "278105", "161251",
+ "97842", "61788", "40423", "27291", "18949", "13492", "9826",
+ "7305", "5532", "4260", "3332", "2642", "2123", "1726", "1418",
+ "1177", "986", "834", "710", "610", "527", "458", "401", "353",
+ "312", "278", "248", "223", "201", "181", "165", "150", "137",
+ "126", "116", "107", "99", "91", "85", "79", "74", "69", "65", "61",
+ "57", "54", "51", "48", "46", "43", "41", "39", "37", "35", "34",
+ "32", "31", "30", "28", "27", "26", "25", "24", "23", "22", "22",
+ "21", "20", "20", "19", "18", "18", "17", "17", "16", "16", "15"
+ }, {
+ "9559098494021810340217797724866627755195",
+ "966746709063325235560830083787", "973307706084821682248292",
+ "97770642291138756434", "136290128605981259", "983232784778520",
+ "21222944848922", "986563584410", "80121684894", "9887903837",
+ "1683643206", "369174929", "99102220", "31356542", "11359721",
+ "4606836", "2054458", "993259", "514621", "283057", "163997",
+ "99437", "62755", "41032", "27686", "19213", "13674", "9955",
+ "7397", "5599", "4311", "3370", "2672", "2146", "1744", "1433",
+ "1189", "996", "842", "717", "615", "532", "462", "404", "356",
+ "315", "280", "250", "224", "202", "183", "166", "151", "138",
+ "127", "116", "107", "99", "92", "86", "80", "74", "70", "65", "61",
+ "58", "54", "51", "48", "46", "43", "41", "39", "37", "36", "34",
+ "32", "31", "30", "29", "27", "26", "25", "24", "23", "23", "22",
+ "21", "20", "20", "19", "18", "18", "17", "17", "16", "16", "15"
+ }, {
+ "8839202025813295923132694443541993309220",
+ "911611499784863252820288596270", "928640961450376817534853",
+ "94017030509441723821", "131792686685970629", "954783483196511",
+ "20676214073400", "963660189823", "78428929840", "9696237956",
+ "1653495486", "363032624", "97562430", "30899570", "11203842",
+ "4547110", "2029216", "981661", "508897", "280051", "162331",
+ "98469", "62168", "40663", "27446", "19053", "13563", "9877",
+ "7341", "5558", "4280", "3347", "2654", "2132", "1733", "1424",
+ "1182", "990", "837", "713", "612", "529", "460", "402", "354",
+ "313", "279", "249", "223", "201", "182", "165", "150", "138",
+ "126", "116", "107", "99", "92", "85", "79", "74", "69", "65", "61",
+ "57", "54", "51", "48", "46", "43", "41", "39", "37", "36", "34",
+ "32", "31", "30", "28", "27", "26", "25", "24", "23", "23", "22",
+ "21", "20", "20", "19", "18", "18", "17", "17", "16", "16", "15"
+ }, {
+ "8338442683973420410660145045849076963795",
+ "872596990706967613912664152945", "896707843885562730147307",
+ "91315073695274540969", "128539440806486007", "934129001105825",
+ "20278149285734", "946946589774", "77191347471", "9555892093",
+ "1631391010", "358523975", "96431070", "30563524", "11089126",
+ "4503126", "2010616", "973111", "504675", "277833", "161100",
+ "97754", "61734", "40390", "27269", "18934", "13482", "9819",
+ "7300", "5528", "4257", "3330", "2641", "2122", "1725", "1417",
+ "1177", "986", "833", "710", "609", "527", "458", "401", "353",
+ "312", "278", "248", "222", "200", "181", "165", "150", "137",
+ "126", "116", "107", "99", "91", "85", "79", "74", "69", "65", "61",
+ "57", "54", "51", "48", "46", "43", "41", "39", "37", "35", "34",
+ "32", "31", "30", "28", "27", "26", "25", "24", "23", "22", "22",
+ "21", "20", "20", "19", "18", "18", "17", "17", "16", "16", "15"
+ }, {
+ "9122818552483814953977703257848970704164",
+ "933462289569511464780529972314", "946405863353935713909178",
+ "95513446972056321834", "133588658082928446",
+ "966158521967027", "20895030642048", "972833934108",
+ "79107381638", "9773098125", "1665590516", "365497822",
+ "98180628", "31083090", "11266459", "4571108", "2039360",
+ "986323", "511198", "281260", "163001", "98858",
+ "62404", "40811", "27543", "19117", "13608", "9908",
+ "7363", "5575", "4292", "3356", "2661", "2138",
+ "1737", "1428", "1185", "993", "839", "714", "613",
+ "530", "461", "403", "355", "314", "279", "249",
+ "224", "202", "182", "165", "151", "138", "126",
+ "116", "107", "99", "92", "85", "79", "74", "69",
+ "65", "61", "57", "54", "51", "48", "46", "43",
+ "41", "39", "37", "36", "34", "32", "31", "30",
+ "28", "27", "26", "25", "24", "23", "23", "22",
+ "21", "20", "20", "19", "18", "18", "17", "17",
+ "16", "16", "15"
+ }, {
+ "9151329724083804100369546479681933027521",
+ "935649419557299174433860420387", "948179413831316112751907",
+ "95662582675170358900", "133767426788182384",
+ "967289728859610", "20916775466497", "973745045600",
+ "79174731802", "9780725058", "1666790321", "365742295",
+ "98241919", "31101281", "11272665", "4573486", "2040365",
+ "986785", "511426", "281380", "163067", "98897",
+ "62427", "40826", "27552", "19124", "13612", "9911",
+ "7366", "5576", "4294", "3357", "2662", "2138",
+ "1738", "1428", "1185", "993", "839", "715", "613",
+ "530", "461", "403", "355", "314", "279", "249",
+ "224", "202", "182", "165", "151", "138", "126",
+ "116", "107", "99", "92", "85", "79", "74", "69",
+ "65", "61", "57", "54", "51", "48", "46", "43",
+ "41", "39", "37", "36", "34", "32", "31", "30",
+ "28", "27", "26", "25", "24", "23", "23", "22",
+ "21", "20", "20", "19", "18", "18", "17", "17",
+ "16", "16", "15"
+ }, {
+ "6839396355168045468586008471269923213531",
+ "752078770083218822016981965090", "796178899357307807726034",
+ "82700643015444840424", "118072966296549115",
+ "867224751770392", "18981881485802", "892288574037",
+ "73130030771", "9093989389", "1558462688", "343617470",
+ "92683740", "29448679", "10708016", "4356820", "1948676",
+ "944610", "490587", "270425", "156989", "95362",
+ "60284", "39477", "26675", "18536", "13208", "9627",
+ "7161", "5426", "4181", "3272", "2596", "2087",
+ "1697", "1395", "1159", "971", "821", "700", "601",
+ "520", "452", "396", "348", "308", "274", "245",
+ "220", "198", "179", "163", "148", "136", "124",
+ "114", "106", "98", "91", "84", "78", "73", "68",
+ "64", "60", "57", "53", "50", "48", "45", "43",
+ "41", "39", "37", "35", "34", "32", "31", "29",
+ "28", "27", "26", "25", "24", "23", "22", "22",
+ "21", "20", "19", "19", "18", "18", "17", "17",
+ "16", "16", "15"
+ }, {
+ "4788090721380022347683138981782307670424",
+ "575601315594614059890185238256", "642831903229558719812840",
+ "69196031110028430211", "101340693763170691",
+ "758683936560287", "16854690815260", "801767985909",
+ "66353290503", "8318415180", "1435359033", "318340531",
+ "86304307", "27544217", "10054988", "4105446", "1841996",
+ "895414", "466223", "257591", "149855", "91205",
+ "57758", "37886", "25639", "17842", "12730", "9290",
+ "6918", "5248", "4048", "3170", "2518", "2026",
+ "1649", "1357", "1128", "946", "800", "682", "586",
+ "507", "441", "387", "341", "302", "268", "240",
+ "215", "194", "176", "160", "146", "133", "122",
+ "112", "104", "96", "89", "83", "77", "72", "67",
+ "63", "59", "56", "53", "50", "47", "45", "42",
+ "40", "38", "36", "35", "33", "32", "30", "29",
+ "28", "27", "26", "25", "24", "23", "22", "21",
+ "21", "20", "19", "19", "18", "17", "17", "16",
+ "16", "15", "15"
+ }
+ };
+
+ if ((e = mp_init_multi(&a, &c, &r, NULL)) != MP_OKAY) {
+ return EXIT_FAILURE;
+ }
+#ifdef MP_8BIT
+ for (i = 0; i < 1; i++) {
+#else
+ for (i = 0; i < 10; i++) {
+#endif
+ mp_read_radix(&a, input[i], 64);
+#ifdef MP_8BIT
+ for (j = 3; j < 10; j++) {
+#else
+ for (j = 3; j < 100; j++) {
+#endif
+ mp_root_u32(&a, (uint32_t)j, &c);
+ mp_read_radix(&r, root[i][j-3], 10);
+ if (mp_cmp(&r, &c) != MP_EQ) {
+ fprintf(stderr, "mp_root_u32 failed at input #%d, root #%d\n", i, j);
+ goto LTM_ERR;
+ }
+ }
+ }
+ mp_clear_multi(&a, &c, &r, NULL);
+ return EXIT_SUCCESS;
+LTM_ERR:
+ mp_clear_multi(&a, &c, &r, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_s_mp_balance_mul(void)
+{
+ mp_int a, b, c;
+ mp_err e = MP_OKAY;
+
+ const char *na =
+ "4b0I5uMTujCysw+1OOuOyH2FX2WymrHUqi8BBDb7XpkV/4i7vXTbEYUy/kdIfCKu5jT5JEqYkdmnn3jAYo8XShPzNLxZx9yoLjxYRyptSuOI2B1DspvbIVYXY12sxPZ4/HCJ4Usm2MU5lO/006KnDMxuxiv1rm6YZJZ0eZU";
+ const char *nb = "3x9vs0yVi4hIq7poAeVcggC3WoRt0zRLKO";
+ const char *nc =
+ "HzrSq9WVt1jDTVlwUxSKqxctu2GVD+N8+SVGaPFRqdxyld6IxDBbj27BPJzYUdR96k3sWpkO8XnDBvupGPnehpQe4KlO/KmN1PjFov/UTZYM+LYzkFcBPyV6hkkL8ePC1rlFLAHzgJMBCXVp4mRqtkQrDsZXXlcqlbTFu69wF6zDEysiX2cAtn/kP9ldblJiwYPCD8hG";
+
+ if ((e = mp_init_multi(&a, &b, &c, NULL)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+
+ if ((e = mp_read_radix(&a, na, 64)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((e = mp_read_radix(&b, nb, 64)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+
+ if ((e = s_mp_balance_mul(&a, &b, &c)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+
+ if ((e = mp_read_radix(&b, nc, 64)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+
+ if (mp_cmp(&b, &c) != MP_EQ) {
+ goto LTM_ERR;
+ }
+
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_SUCCESS;
+LTM_ERR:
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_FAILURE;
+}
+
+#define s_mp_mul(a, b, c) s_mp_mul_digs(a, b, c, (a)->used + (b)->used + 1)
+static int test_s_mp_karatsuba_mul(void)
+{
+ mp_int a, b, c, d;
+ int size, err;
+
+ if ((err = mp_init_multi(&a, &b, &c, &d, NULL)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ for (size = MP_KARATSUBA_MUL_CUTOFF; size < MP_KARATSUBA_MUL_CUTOFF + 20; size++) {
+ if ((err = mp_rand(&a, size)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = mp_rand(&b, size)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = s_mp_karatsuba_mul(&a, &b, &c)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = s_mp_mul(&a,&b,&d)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if (mp_cmp(&c, &d) != MP_EQ) {
+ fprintf(stderr, "Karatsuba multiplication failed at size %d\n", size);
+ goto LTM_ERR;
+ }
+ }
+
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_SUCCESS;
+LTM_ERR:
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_s_mp_karatsuba_sqr(void)
+{
+ mp_int a, b, c;
+ int size, err;
+
+ if ((err = mp_init_multi(&a, &b, &c, NULL)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ for (size = MP_KARATSUBA_SQR_CUTOFF; size < MP_KARATSUBA_SQR_CUTOFF + 20; size++) {
+ if ((err = mp_rand(&a, size)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = s_mp_karatsuba_sqr(&a, &b)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = s_mp_sqr(&a, &c)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if (mp_cmp(&b, &c) != MP_EQ) {
+ fprintf(stderr, "Karatsuba squaring failed at size %d\n", size);
+ goto LTM_ERR;
+ }
+ }
+
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_SUCCESS;
+LTM_ERR:
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_s_mp_toom_mul(void)
+{
+ mp_int a, b, c, d;
+ int size, err;
+
+#if (MP_DIGIT_BIT == 60)
+ int tc_cutoff;
+#endif
+
+ if ((err = mp_init_multi(&a, &b, &c, &d, NULL)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ /* This number construction is limb-size specific */
+#if (MP_DIGIT_BIT == 60)
+ if ((err = mp_rand(&a, 1196)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = mp_mul_2d(&a,71787 - mp_count_bits(&a), &a)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+
+ if ((err = mp_rand(&b, 1338)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = mp_mul_2d(&b, 80318 - mp_count_bits(&b), &b)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = mp_mul_2d(&b, 6310, &b)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = mp_2expt(&c, 99000 - 1000)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = mp_add(&b, &c, &b)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+
+ tc_cutoff = TOOM_MUL_CUTOFF;
+ TOOM_MUL_CUTOFF = INT_MAX;
+ if ((err = mp_mul(&a, &b, &c)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ TOOM_MUL_CUTOFF = tc_cutoff;
+ if ((err = mp_mul(&a, &b, &d)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if (mp_cmp(&c, &d) != MP_EQ) {
+ fprintf(stderr, "Toom-Cook 3-way multiplication failed for edgecase f1 * f2\n");
+ goto LTM_ERR;
+ }
+#endif
+
+ for (size = MP_TOOM_MUL_CUTOFF; size < MP_TOOM_MUL_CUTOFF + 20; size++) {
+ if ((err = mp_rand(&a, size)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = mp_rand(&b, size)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = s_mp_toom_mul(&a, &b, &c)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = s_mp_mul(&a,&b,&d)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if (mp_cmp(&c, &d) != MP_EQ) {
+ fprintf(stderr, "Toom-Cook 3-way multiplication failed at size %d\n", size);
+ goto LTM_ERR;
+ }
+ }
+
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_SUCCESS;
+LTM_ERR:
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_s_mp_toom_sqr(void)
+{
+ mp_int a, b, c;
+ int size, err;
+
+ if ((err = mp_init_multi(&a, &b, &c, NULL)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ for (size = MP_TOOM_SQR_CUTOFF; size < MP_TOOM_SQR_CUTOFF + 20; size++) {
+ if ((err = mp_rand(&a, size)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = s_mp_toom_sqr(&a, &b)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if ((err = s_mp_sqr(&a, &c)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+ if (mp_cmp(&b, &c) != MP_EQ) {
+ fprintf(stderr, "Toom-Cook 3-way squaring failed at size %d\n", size);
+ goto LTM_ERR;
+ }
+ }
+
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_SUCCESS;
+LTM_ERR:
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_read_write_ubin(void)
+{
+ mp_int a, b, c;
+ int err;
+ size_t size, len;
+ unsigned char *buf = NULL;
+
+ if ((err = mp_init_multi(&a, &b, &c, NULL)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+
+ if ((err = mp_rand(&a, 15)) != MP_OKAY) goto LTM_ERR;
+ if ((err = mp_neg(&a, &b)) != MP_OKAY) goto LTM_ERR;
+
+ size = mp_ubin_size(&a);
+ printf("mp_to_ubin_size %zu\n", size);
+ buf = malloc(sizeof(*buf) * size);
+ if (buf == NULL) {
+ fprintf(stderr, "test_read_write_binaries (u) failed to allocate %zu bytes\n",
+ sizeof(*buf) * size);
+ goto LTM_ERR;
+ }
+
+ if ((err = mp_to_ubin(&a, buf, size, &len)) != MP_OKAY) goto LTM_ERR;
+ printf("mp_to_ubin len = %zu\n", len);
+
+ if ((err = mp_from_ubin(&c, buf, len)) != MP_OKAY) goto LTM_ERR;
+
+ if (mp_cmp(&a, &c) != MP_EQ) {
+ fprintf(stderr, "to/from ubin cycle failed\n");
+ goto LTM_ERR;
+ }
+ free(buf);
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_SUCCESS;
+LTM_ERR:
+ free(buf);
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_read_write_sbin(void)
+{
+ mp_int a, b, c;
+ int err;
+ size_t size, len;
+ unsigned char *buf = NULL;
+
+ if ((err = mp_init_multi(&a, &b, &c, NULL)) != MP_OKAY) {
+ goto LTM_ERR;
+ }
+
+ if ((err = mp_rand(&a, 15)) != MP_OKAY) goto LTM_ERR;
+ if ((err = mp_neg(&a, &b)) != MP_OKAY) goto LTM_ERR;
+
+ size = mp_sbin_size(&a);
+ printf("mp_to_sbin_size %zu\n", size);
+ buf = malloc(sizeof(*buf) * size);
+ if (buf == NULL) {
+ fprintf(stderr, "test_read_write_binaries (s) failed to allocate %zu bytes\n",
+ sizeof(*buf) * size);
+ goto LTM_ERR;
+ }
+
+ if ((err = mp_to_sbin(&b, buf, size, &len)) != MP_OKAY) goto LTM_ERR;
+ printf("mp_to_sbin len = %zu\n", len);
+
+ if ((err = mp_from_sbin(&c, buf, len)) != MP_OKAY) goto LTM_ERR;
+
+ if (mp_cmp(&b, &c) != MP_EQ) {
+ fprintf(stderr, "to/from ubin cycle failed\n");
+ goto LTM_ERR;
+ }
+
+ free(buf);
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_SUCCESS;
+LTM_ERR:
+ free(buf);
+ mp_clear_multi(&a, &b, &c, NULL);
+ return EXIT_FAILURE;
+}
+
+static int test_mp_pack_unpack(void)
+{
+ mp_int a, b;
+ int err;
+ size_t written, count;
+ unsigned char *buf = NULL;
+
+ mp_order order = MP_LSB_FIRST;
+ mp_endian endianess = MP_NATIVE_ENDIAN;
+
+ if ((err = mp_init_multi(&a, &b, NULL)) != MP_OKAY) goto LTM_ERR;
+ if ((err = mp_rand(&a, 15)) != MP_OKAY) goto LTM_ERR;
+
+ count = mp_pack_count(&a, 0, 1);
+
+ buf = malloc(count);
+ if (buf == NULL) {
+ fprintf(stderr, "test_pack_unpack failed to allocate\n");
+ goto LTM_ERR;
+ }
+
+ if ((err = mp_pack((void *)buf, count, &written, order, 1,
+ endianess, 0, &a)) != MP_OKAY) goto LTM_ERR;
+ if ((err = mp_unpack(&b, count, order, 1,
+ endianess, 0, (const void *)buf)) != MP_OKAY) goto LTM_ERR;
+
+ if (mp_cmp(&a, &b) != MP_EQ) {
+ fprintf(stderr, "pack/unpack cycle failed\n");
+ goto LTM_ERR;
+ }
+
+ free(buf);
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_SUCCESS;
+LTM_ERR:
+ free(buf);
+ mp_clear_multi(&a, &b, NULL);
+ return EXIT_FAILURE;
+}
+
+static int unit_tests(int argc, char **argv)
+{
+ static const struct {
+ const char *name;
+ int (*fn)(void);
+ } test[] = {
+#define T0(n) { #n, test_##n }
+#define T1(n, o) { #n, MP_HAS(o) ? test_##n : NULL }
+#define T2(n, o1, o2) { #n, MP_HAS(o1) && MP_HAS(o2) ? test_##n : NULL }
+ T0(feature_detection),
+ T0(trivial_stuff),
+ T2(mp_get_set_i32, MP_GET_I32, MP_GET_MAG_U32),
+ T2(mp_get_set_i64, MP_GET_I64, MP_GET_MAG_U64),
+ T1(mp_and, MP_AND),
+ T1(mp_cnt_lsb, MP_CNT_LSB),
+ T1(mp_complement, MP_COMPLEMENT),
+ T1(mp_decr, MP_DECR),
+ T1(mp_div_3, MP_DIV_3),
+ T1(mp_dr_reduce, MP_DR_REDUCE),
+ T2(mp_pack_unpack,MP_PACK, MP_UNPACK),
+ T2(mp_fread_fwrite, MP_FREAD, MP_FWRITE),
+ T1(mp_get_u32, MP_GET_I32),
+ T1(mp_get_u64, MP_GET_I64),
+ T1(mp_get_ul, MP_GET_L),
+ T1(mp_log_u32, MP_LOG_U32),
+ T1(mp_incr, MP_INCR),
+ T1(mp_invmod, MP_INVMOD),
+ T1(mp_is_square, MP_IS_SQUARE),
+ T1(mp_kronecker, MP_KRONECKER),
+ T1(mp_montgomery_reduce, MP_MONTGOMERY_REDUCE),
+ T1(mp_root_u32, MP_ROOT_U32),
+ T1(mp_or, MP_OR),
+ T1(mp_prime_is_prime, MP_PRIME_IS_PRIME),
+ T1(mp_prime_next_prime, MP_PRIME_NEXT_PRIME),
+ T1(mp_prime_rand, MP_PRIME_RAND),
+ T1(mp_rand, MP_RAND),
+ T1(mp_read_radix, MP_READ_RADIX),
+ T1(mp_read_write_ubin, MP_TO_UBIN),
+ T1(mp_read_write_sbin, MP_TO_SBIN),
+ T1(mp_reduce_2k, MP_REDUCE_2K),
+ T1(mp_reduce_2k_l, MP_REDUCE_2K_L),
+#if defined(__STDC_IEC_559__) || defined(__GCC_IEC_559)
+ T1(mp_set_double, MP_SET_DOUBLE),
+#endif
+ T1(mp_signed_rsh, MP_SIGNED_RSH),
+ T1(mp_sqrt, MP_SQRT),
+ T1(mp_sqrtmod_prime, MP_SQRTMOD_PRIME),
+ T1(mp_xor, MP_XOR),
+ T1(s_mp_balance_mul, S_MP_BALANCE_MUL),
+ T1(s_mp_karatsuba_mul, S_MP_KARATSUBA_MUL),
+ T1(s_mp_karatsuba_sqr, S_MP_KARATSUBA_SQR),
+ T1(s_mp_toom_mul, S_MP_TOOM_MUL),
+ T1(s_mp_toom_sqr, S_MP_TOOM_SQR)
+#undef T2
+#undef T1
+ };
+ unsigned long i, ok, fail, nop;
+ uint64_t t;
+ int j;
+
+ ok = fail = nop = 0;
+
+ t = (uint64_t)time(NULL);
+ printf("SEED: 0x%"PRIx64"\n\n", t);
+ s_mp_rand_jenkins_init(t);
+ mp_rand_source(s_mp_rand_jenkins);
+
+ for (i = 0; i < sizeof(test) / sizeof(test[0]); ++i) {
+ if (argc > 1) {
+ for (j = 1; j < argc; ++j) {
+ if (strstr(test[i].name, argv[j]) != NULL) {
+ break;
+ }
+ }
+ if (j == argc) continue;
+ }
+ printf("TEST %s\n\n", test[i].name);
+ if (test[i].fn == NULL) {
+ nop++;
+ printf("NOP %s\n\n", test[i].name);
+ } else if (test[i].fn() == EXIT_SUCCESS) {
+ ok++;
+ printf("\n\n");
+ } else {
+ fail++;
+ printf("\n\nFAIL %s\n\n", test[i].name);
+ }
+ }
+ printf("Tests OK/NOP/FAIL: %lu/%lu/%lu\n", ok, nop, fail);
+
+ if (fail != 0) return EXIT_FAILURE;
+ else return EXIT_SUCCESS;
+}
+
+int main(int argc, char **argv)
+{
+ print_header();
+
+ return unit_tests(argc, argv);
+}
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/demo/timing.c b/third_party/heimdal/lib/hcrypto/libtommath/demo/timing.c
new file mode 100644
index 0000000..f620b8c
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/demo/timing.c
@@ -0,0 +1,406 @@
+#include <time.h>
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <inttypes.h>
+
+#define MP_WUR
+#include <tommath.h>
+
+#ifdef IOWNANATHLON
+#include <unistd.h>
+#define SLEEP sleep(4)
+#else
+#define SLEEP
+#endif
+
+#ifdef LTM_TIMING_REAL_RAND
+#define LTM_TIMING_RAND_SEED time(NULL)
+#else
+#define LTM_TIMING_RAND_SEED 23
+#endif
+
+
+static void ndraw(mp_int *a, const char *name)
+{
+ char buf[4096];
+
+ printf("%s: ", name);
+ mp_to_radix(a, buf, sizeof(buf), NULL, 64);
+ printf("%s\n", buf);
+}
+
+static void draw(mp_int *a)
+{
+ ndraw(a, "");
+}
+
+
+static unsigned long lfsr = 0xAAAAAAAAuL;
+
+static unsigned int lbit(void)
+{
+ if ((lfsr & 0x80000000uL) != 0uL) {
+ lfsr = ((lfsr << 1) ^ 0x8000001BuL) & 0xFFFFFFFFuL;
+ return 1u;
+ } else {
+ lfsr <<= 1;
+ return 0u;
+ }
+}
+
+/* RDTSC from Scott Duplichan */
+static uint64_t TIMFUNC(void)
+{
+#if defined __GNUC__
+#if defined(__i386__) || defined(__x86_64__)
+ /* version from http://www.mcs.anl.gov/~kazutomo/rdtsc.html
+ * the old code always got a warning issued by gcc, clang did not complain...
+ */
+ unsigned hi, lo;
+ __asm__ __volatile__("rdtsc" : "=a"(lo), "=d"(hi));
+ return ((uint64_t)lo)|(((uint64_t)hi)<<32);
+#else /* gcc-IA64 version */
+ unsigned long result;
+ __asm__ __volatile__("mov %0=ar.itc":"=r"(result)::"memory");
+
+ while (__builtin_expect((int) result == -1, 0))
+ __asm__ __volatile__("mov %0=ar.itc":"=r"(result)::"memory");
+
+ return result;
+#endif
+
+ /* Microsoft and Intel Windows compilers */
+#elif defined _M_IX86
+ __asm rdtsc
+#elif defined _M_AMD64
+ return __rdtsc();
+#elif defined _M_IA64
+#if defined __INTEL_COMPILER
+#include <ia64intrin.h>
+#endif
+ return __getReg(3116);
+#else
+#error need rdtsc function for this build
+#endif
+}
+
+#if 1
+#define DO(x) x; x;
+#else
+#define DO2(x) x; x;
+#define DO4(x) DO2(x); DO2(x);
+#define DO8(x) DO4(x); DO4(x);
+#define DO(x) DO8(x); DO8(x);
+#endif
+
+#ifdef TIMING_NO_LOGS
+#define FOPEN(a, b) NULL
+#define FPRINTF(a,b,c,d)
+#define FFLUSH(a)
+#define FCLOSE(a) (void)(a)
+#else
+#define FOPEN(a,b) fopen(a,b)
+#define FPRINTF(a,b,c,d) fprintf(a,b,c,d)
+#define FFLUSH(a) fflush(a)
+#define FCLOSE(a) fclose(a)
+#endif
+
+static int should_test(const char *test, int argc, char **argv)
+{
+ int j;
+ if (argc > 1) {
+ for (j = 1; j < argc; ++j) {
+ if (strstr(test, argv[j]) != NULL) {
+ return 1;
+ }
+ }
+ if (j == argc) return 0;
+ }
+ return 1;
+}
+
+int main(int argc, char **argv)
+{
+ uint64_t tt, gg, CLK_PER_SEC;
+ FILE *log, *logb, *logc, *logd;
+ mp_int a, b, c, d, e, f;
+#ifdef LTM_TIMING_PRIME_IS_PRIME
+ const char *name;
+ int m;
+#endif
+ int n, cnt, ix, old_kara_m, old_kara_s, old_toom_m, old_toom_s;
+ unsigned rr;
+
+ mp_init(&a);
+ mp_init(&b);
+ mp_init(&c);
+ mp_init(&d);
+ mp_init(&e);
+ mp_init(&f);
+
+ srand(LTM_TIMING_RAND_SEED);
+
+
+ CLK_PER_SEC = TIMFUNC();
+ sleep(1);
+ CLK_PER_SEC = TIMFUNC() - CLK_PER_SEC;
+
+ printf("CLK_PER_SEC == %" PRIu64 "\n", CLK_PER_SEC);
+
+#ifdef LTM_TIMING_PRIME_IS_PRIME
+ if (should_test("prime", argc, argv)) {
+ for (m = 0; m < 2; ++m) {
+ if (m == 0) {
+ name = " Arnault";
+ mp_read_radix(&a,
+ "91xLNF3roobhzgTzoFIG6P13ZqhOVYSN60Fa7Cj2jVR1g0k89zdahO9/kAiRprpfO1VAp1aBHucLFV/qLKLFb+zonV7R2Vxp1K13ClwUXStpV0oxTNQVjwybmFb5NBEHImZ6V7P6+udRJuH8VbMEnS0H8/pSqQrg82OoQQ2fPpAk6G1hkjqoCv5s/Yr",
+ 64);
+ } else {
+ name = "2^1119 + 53";
+ mp_set(&a,1u);
+ mp_mul_2d(&a,1119,&a);
+ mp_add_d(&a,53,&a);
+ }
+ cnt = mp_prime_rabin_miller_trials(mp_count_bits(&a));
+ ix = -cnt;
+ for (; cnt >= ix; cnt += ix) {
+ rr = 0u;
+ tt = UINT64_MAX;
+ do {
+ gg = TIMFUNC();
+ DO(mp_prime_is_prime(&a, cnt, &n));
+ gg = (TIMFUNC() - gg) >> 1;
+ if (tt > gg)
+ tt = gg;
+ if ((m == 0) && (n == MP_YES)) {
+ printf("Arnault's pseudoprime is not prime but mp_prime_is_prime says it is.\n");
+ return EXIT_FAILURE;
+ }
+ } while (++rr < 100u);
+ printf("Prime-check\t%s(%2d) => %9" PRIu64 "/sec, %9" PRIu64 " cycles\n",
+ name, cnt, CLK_PER_SEC / tt, tt);
+ }
+ }
+ }
+#endif
+
+ if (should_test("add", argc, argv)) {
+ log = FOPEN("logs/add.log", "w");
+ for (cnt = 8; cnt <= 128; cnt += 8) {
+ SLEEP;
+ mp_rand(&a, cnt);
+ mp_rand(&b, cnt);
+ rr = 0u;
+ tt = UINT64_MAX;
+ do {
+ gg = TIMFUNC();
+ DO(mp_add(&a, &b, &c));
+ gg = (TIMFUNC() - gg) >> 1;
+ if (tt > gg)
+ tt = gg;
+ } while (++rr < 100000u);
+ printf("Adding\t\t%4d-bit => %9" PRIu64 "/sec, %9" PRIu64 " cycles\n",
+ mp_count_bits(&a), CLK_PER_SEC / tt, tt);
+ FPRINTF(log, "%6d %9" PRIu64 "\n", cnt * MP_DIGIT_BIT, tt);
+ FFLUSH(log);
+ }
+ FCLOSE(log);
+ }
+
+ if (should_test("sub", argc, argv)) {
+ log = FOPEN("logs/sub.log", "w");
+ for (cnt = 8; cnt <= 128; cnt += 8) {
+ SLEEP;
+ mp_rand(&a, cnt);
+ mp_rand(&b, cnt);
+ rr = 0u;
+ tt = UINT64_MAX;
+ do {
+ gg = TIMFUNC();
+ DO(mp_sub(&a, &b, &c));
+ gg = (TIMFUNC() - gg) >> 1;
+ if (tt > gg)
+ tt = gg;
+ } while (++rr < 100000u);
+
+ printf("Subtracting\t\t%4d-bit => %9" PRIu64 "/sec, %9" PRIu64 " cycles\n",
+ mp_count_bits(&a), CLK_PER_SEC / tt, tt);
+ FPRINTF(log, "%6d %9" PRIu64 "\n", cnt * MP_DIGIT_BIT, tt);
+ FFLUSH(log);
+ }
+ FCLOSE(log);
+ }
+
+ if (should_test("mulsqr", argc, argv)) {
+ /* do mult/square twice, first without karatsuba and second with */
+ old_kara_m = KARATSUBA_MUL_CUTOFF;
+ old_kara_s = KARATSUBA_SQR_CUTOFF;
+ /* currently toom-cook cut-off is too high to kick in, so we just use the karatsuba values */
+ old_toom_m = old_kara_m;
+ old_toom_s = old_kara_s;
+ for (ix = 0; ix < 3; ix++) {
+ printf("With%s Karatsuba, With%s Toom\n", (ix == 1) ? "" : "out", (ix == 2) ? "" : "out");
+
+ KARATSUBA_MUL_CUTOFF = (ix == 1) ? old_kara_m : 9999;
+ KARATSUBA_SQR_CUTOFF = (ix == 1) ? old_kara_s : 9999;
+ TOOM_MUL_CUTOFF = (ix == 2) ? old_toom_m : 9999;
+ TOOM_SQR_CUTOFF = (ix == 2) ? old_toom_s : 9999;
+
+ log = FOPEN((ix == 0) ? "logs/mult.log" : (ix == 1) ? "logs/mult_kara.log" : "logs/mult_toom.log", "w");
+ for (cnt = 4; cnt <= (10240 / MP_DIGIT_BIT); cnt += 2) {
+ SLEEP;
+ mp_rand(&a, cnt);
+ mp_rand(&b, cnt);
+ rr = 0u;
+ tt = UINT64_MAX;
+ do {
+ gg = TIMFUNC();
+ DO(mp_mul(&a, &b, &c));
+ gg = (TIMFUNC() - gg) >> 1;
+ if (tt > gg)
+ tt = gg;
+ } while (++rr < 100u);
+ printf("Multiplying\t%4d-bit => %9" PRIu64 "/sec, %9" PRIu64 " cycles\n",
+ mp_count_bits(&a), CLK_PER_SEC / tt, tt);
+ FPRINTF(log, "%6d %9" PRIu64 "\n", mp_count_bits(&a), tt);
+ FFLUSH(log);
+ }
+ FCLOSE(log);
+
+ log = FOPEN((ix == 0) ? "logs/sqr.log" : (ix == 1) ? "logs/sqr_kara.log" : "logs/sqr_toom.log", "w");
+ for (cnt = 4; cnt <= (10240 / MP_DIGIT_BIT); cnt += 2) {
+ SLEEP;
+ mp_rand(&a, cnt);
+ rr = 0u;
+ tt = UINT64_MAX;
+ do {
+ gg = TIMFUNC();
+ DO(mp_sqr(&a, &b));
+ gg = (TIMFUNC() - gg) >> 1;
+ if (tt > gg)
+ tt = gg;
+ } while (++rr < 100u);
+ printf("Squaring\t%4d-bit => %9" PRIu64 "/sec, %9" PRIu64 " cycles\n",
+ mp_count_bits(&a), CLK_PER_SEC / tt, tt);
+ FPRINTF(log, "%6d %9" PRIu64 "\n", mp_count_bits(&a), tt);
+ FFLUSH(log);
+ }
+ FCLOSE(log);
+
+ }
+ }
+
+ if (should_test("expt", argc, argv)) {
+ const char *primes[] = {
+ /* 2K large moduli */
+ "179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586239334100047359817950870678242457666208137217",
+ "32317006071311007300714876688669951960444102669715484032130345427524655138867890893197201411522913463688717960921898019494119559150490921095088152386448283120630877367300996091750197750389652106796057638384067568276792218642619756161838094338476170470581645852036305042887575891541065808607552399123930385521914333389668342420684974786564569494856176035326322058077805659331026192708460314150258592864177116725943603718461857357598351152301645904403697613233287231227125684710820209725157101726931323469678542580656697935045997268352998638099733077152121140120031150424541696791951097529546801429027668869927491725169",
+ "1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085902995208257421855249796721729039744118165938433694823325696642096892124547425283",
+ /* 2K moduli mersenne primes */
+ "6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151",
+ "531137992816767098689588206552468627329593117727031923199444138200403559860852242739162502265229285668889329486246501015346579337652707239409519978766587351943831270835393219031728127",
+ "10407932194664399081925240327364085538615262247266704805319112350403608059673360298012239441732324184842421613954281007791383566248323464908139906605677320762924129509389220345773183349661583550472959420547689811211693677147548478866962501384438260291732348885311160828538416585028255604666224831890918801847068222203140521026698435488732958028878050869736186900714720710555703168729087",
+ "1475979915214180235084898622737381736312066145333169775147771216478570297878078949377407337049389289382748507531496480477281264838760259191814463365330269540496961201113430156902396093989090226259326935025281409614983499388222831448598601834318536230923772641390209490231836446899608210795482963763094236630945410832793769905399982457186322944729636418890623372171723742105636440368218459649632948538696905872650486914434637457507280441823676813517852099348660847172579408422316678097670224011990280170474894487426924742108823536808485072502240519452587542875349976558572670229633962575212637477897785501552646522609988869914013540483809865681250419497686697771007",
+ "259117086013202627776246767922441530941818887553125427303974923161874019266586362086201209516800483406550695241733194177441689509238807017410377709597512042313066624082916353517952311186154862265604547691127595848775610568757931191017711408826252153849035830401185072116424747461823031471398340229288074545677907941037288235820705892351068433882986888616658650280927692080339605869308790500409503709875902119018371991620994002568935113136548829739112656797303241986517250116412703509705427773477972349821676443446668383119322540099648994051790241624056519054483690809616061625743042361721863339415852426431208737266591962061753535748892894599629195183082621860853400937932839420261866586142503251450773096274235376822938649407127700846077124211823080804139298087057504713825264571448379371125032081826126566649084251699453951887789613650248405739378594599444335231188280123660406262468609212150349937584782292237144339628858485938215738821232393687046160677362909315071",
+ "190797007524439073807468042969529173669356994749940177394741882673528979787005053706368049835514900244303495954950709725762186311224148828811920216904542206960744666169364221195289538436845390250168663932838805192055137154390912666527533007309292687539092257043362517857366624699975402375462954490293259233303137330643531556539739921926201438606439020075174723029056838272505051571967594608350063404495977660656269020823960825567012344189908927956646011998057988548630107637380993519826582389781888135705408653045219655801758081251164080554609057468028203308718724654081055323215860189611391296030471108443146745671967766308925858547271507311563765171008318248647110097614890313562856541784154881743146033909602737947385055355960331855614540900081456378659068370317267696980001187750995491090350108417050917991562167972281070161305972518044872048331306383715094854938415738549894606070722584737978176686422134354526989443028353644037187375385397838259511833166416134323695660367676897722287918773420968982326089026150031515424165462111337527431154890666327374921446276833564519776797633875503548665093914556482031482248883127023777039667707976559857333357013727342079099064400455741830654320379350833236245819348824064783585692924881021978332974949906122664421376034687815350484991",
+
+ /* DR moduli */
+ "14059105607947488696282932836518693308967803494693489478439861164411992439598399594747002144074658928593502845729752797260025831423419686528151609940203368612079",
+ "101745825697019260773923519755878567461315282017759829107608914364075275235254395622580447400994175578963163918967182013639660669771108475957692810857098847138903161308502419410142185759152435680068435915159402496058513611411688900243039",
+ "736335108039604595805923406147184530889923370574768772191969612422073040099331944991573923112581267542507986451953227192970402893063850485730703075899286013451337291468249027691733891486704001513279827771740183629161065194874727962517148100775228363421083691764065477590823919364012917984605619526140821797602431",
+ "38564998830736521417281865696453025806593491967131023221754800625044118265468851210705360385717536794615180260494208076605798671660719333199513807806252394423283413430106003596332513246682903994829528690198205120921557533726473585751382193953592127439965050261476810842071573684505878854588706623484573925925903505747545471088867712185004135201289273405614415899438276535626346098904241020877974002916168099951885406379295536200413493190419727789712076165162175783",
+ "542189391331696172661670440619180536749994166415993334151601745392193484590296600979602378676624808129613777993466242203025054573692562689251250471628358318743978285860720148446448885701001277560572526947619392551574490839286458454994488665744991822837769918095117129546414124448777033941223565831420390846864429504774477949153794689948747680362212954278693335653935890352619041936727463717926744868338358149568368643403037768649616778526013610493696186055899318268339432671541328195724261329606699831016666359440874843103020666106568222401047720269951530296879490444224546654729111504346660859907296364097126834834235287147",
+ "1487259134814709264092032648525971038895865645148901180585340454985524155135260217788758027400478312256339496385275012465661575576202252063145698732079880294664220579764848767704076761853197216563262660046602703973050798218246170835962005598561669706844469447435461092542265792444947706769615695252256130901271870341005768912974433684521436211263358097522726462083917939091760026658925757076733484173202927141441492573799914240222628795405623953109131594523623353044898339481494120112723445689647986475279242446083151413667587008191682564376412347964146113898565886683139407005941383669325997475076910488086663256335689181157957571445067490187939553165903773554290260531009121879044170766615232300936675369451260747671432073394867530820527479172464106442450727640226503746586340279816318821395210726268291535648506190714616083163403189943334431056876038286530365757187367147446004855912033137386225053275419626102417236133948503",
+ "1095121115716677802856811290392395128588168592409109494900178008967955253005183831872715423151551999734857184538199864469605657805519106717529655044054833197687459782636297255219742994736751541815269727940751860670268774903340296040006114013971309257028332849679096824800250742691718610670812374272414086863715763724622797509437062518082383056050144624962776302147890521249477060215148275163688301275847155316042279405557632639366066847442861422164832655874655824221577849928863023018366835675399949740429332468186340518172487073360822220449055340582568461568645259954873303616953776393853174845132081121976327462740354930744487429617202585015510744298530101547706821590188733515880733527449780963163909830077616357506845523215289297624086914545378511082534229620116563260168494523906566709418166011112754529766183554579321224940951177394088465596712620076240067370589036924024728375076210477267488679008016579588696191194060127319035195370137160936882402244399699172017835144537488486396906144217720028992863941288217185353914991583400421682751000603596655790990815525126154394344641336397793791497068253936771017031980867706707490224041075826337383538651825493679503771934836094655802776331664261631740148281763487765852746577808019633679",
+
+ /* generic unrestricted moduli */
+ "17933601194860113372237070562165128350027320072176844226673287945873370751245439587792371960615073855669274087805055507977323024886880985062002853331424203",
+ "2893527720709661239493896562339544088620375736490408468011883030469939904368086092336458298221245707898933583190713188177399401852627749210994595974791782790253946539043962213027074922559572312141181787434278708783207966459019479487",
+ "347743159439876626079252796797422223177535447388206607607181663903045907591201940478223621722118173270898487582987137708656414344685816179420855160986340457973820182883508387588163122354089264395604796675278966117567294812714812796820596564876450716066283126720010859041484786529056457896367683122960411136319",
+ "47266428956356393164697365098120418976400602706072312735924071745438532218237979333351774907308168340693326687317443721193266215155735814510792148768576498491199122744351399489453533553203833318691678263241941706256996197460424029012419012634671862283532342656309677173602509498417976091509154360039893165037637034737020327399910409885798185771003505320583967737293415979917317338985837385734747478364242020380416892056650841470869294527543597349250299539682430605173321029026555546832473048600327036845781970289288898317888427517364945316709081173840186150794397479045034008257793436817683392375274635794835245695887",
+ "436463808505957768574894870394349739623346440601945961161254440072143298152040105676491048248110146278752857839930515766167441407021501229924721335644557342265864606569000117714935185566842453630868849121480179691838399545644365571106757731317371758557990781880691336695584799313313687287468894148823761785582982549586183756806449017542622267874275103877481475534991201849912222670102069951687572917937634467778042874315463238062009202992087620963771759666448266532858079402669920025224220613419441069718482837399612644978839925207109870840278194042158748845445131729137117098529028886770063736487420613144045836803985635654192482395882603511950547826439092832800532152534003936926017612446606135655146445620623395788978726744728503058670046885876251527122350275750995227",
+ "11424167473351836398078306042624362277956429440521137061889702611766348760692206243140413411077394583180726863277012016602279290144126785129569474909173584789822341986742719230331946072730319555984484911716797058875905400999504305877245849119687509023232790273637466821052576859232452982061831009770786031785669030271542286603956118755585683996118896215213488875253101894663403069677745948305893849505434201763745232895780711972432011344857521691017896316861403206449421332243658855453435784006517202894181640562433575390821384210960117518650374602256601091379644034244332285065935413233557998331562749140202965844219336298970011513882564935538704289446968322281451907487362046511461221329799897350993370560697505809686438782036235372137015731304779072430260986460269894522159103008260495503005267165927542949439526272736586626709581721032189532726389643625590680105784844246152702670169304203783072275089194754889511973916207",
+ "1214855636816562637502584060163403830270705000634713483015101384881871978446801224798536155406895823305035467591632531067547890948695117172076954220727075688048751022421198712032848890056357845974246560748347918630050853933697792254955890439720297560693579400297062396904306270145886830719309296352765295712183040773146419022875165382778007040109957609739589875590885701126197906063620133954893216612678838507540777138437797705602453719559017633986486649523611975865005712371194067612263330335590526176087004421363598470302731349138773205901447704682181517904064735636518462452242791676541725292378925568296858010151852326316777511935037531017413910506921922450666933202278489024521263798482237150056835746454842662048692127173834433089016107854491097456725016327709663199738238442164843147132789153725513257167915555162094970853584447993125488607696008169807374736711297007473812256272245489405898470297178738029484459690836250560495461579533254473316340608217876781986188705928270735695752830825527963838355419762516246028680280988020401914551825487349990306976304093109384451438813251211051597392127491464898797406789175453067960072008590614886532333015881171367104445044718144312416815712216611576221546455968770801413440778423979",
+ NULL
+ };
+ log = FOPEN("logs/expt.log", "w");
+ logb = FOPEN("logs/expt_dr.log", "w");
+ logc = FOPEN("logs/expt_2k.log", "w");
+ logd = FOPEN("logs/expt_2kl.log", "w");
+ for (n = 0; primes[n] != NULL; n++) {
+ SLEEP;
+ mp_read_radix(&a, primes[n], 10);
+ mp_zero(&b);
+ for (rr = 0; rr < (unsigned) mp_count_bits(&a); rr++) {
+ mp_mul_2(&b, &b);
+ b.dp[0] |= lbit();
+ b.used += 1;
+ }
+ mp_sub_d(&a, 1uL, &c);
+ mp_mod(&b, &c, &b);
+ mp_set(&c, 3uL);
+ rr = 0u;
+ tt = UINT64_MAX;
+ do {
+ gg = TIMFUNC();
+ DO(mp_exptmod(&c, &b, &a, &d));
+ gg = (TIMFUNC() - gg) >> 1;
+ if (tt > gg)
+ tt = gg;
+ } while (++rr < 10u);
+ mp_sub_d(&a, 1uL, &e);
+ mp_sub(&e, &b, &b);
+ mp_exptmod(&c, &b, &a, &e); /* c^(p-1-b) mod a */
+ mp_mulmod(&e, &d, &a, &d); /* c^b * c^(p-1-b) == c^p-1 == 1 */
+ if (mp_cmp_d(&d, 1uL) != MP_EQ) {
+ printf("Different (%d)!!!\n", mp_count_bits(&a));
+ draw(&d);
+ exit(0);
+ }
+ printf("Exponentiating\t%4d-bit => %9" PRIu64 "/sec, %9" PRIu64 " cycles\n",
+ mp_count_bits(&a), CLK_PER_SEC / tt, tt);
+ FPRINTF((n < 3) ? logd : (n < 9) ? logc : (n < 16) ? logb : log,
+ "%6d %9" PRIu64 "\n", mp_count_bits(&a), tt);
+ }
+ FCLOSE(log);
+ FCLOSE(logb);
+ FCLOSE(logc);
+ FCLOSE(logd);
+ }
+
+ if (should_test("invmod", argc, argv)) {
+ log = FOPEN("logs/invmod.log", "w");
+ for (cnt = 4; cnt <= 32; cnt += 4) {
+ SLEEP;
+ mp_rand(&a, cnt);
+ mp_rand(&b, cnt);
+
+ do {
+ mp_add_d(&b, 1uL, &b);
+ mp_gcd(&a, &b, &c);
+ } while (mp_cmp_d(&c, 1uL) != MP_EQ);
+
+ rr = 0u;
+ tt = UINT64_MAX;
+ do {
+ gg = TIMFUNC();
+ DO(mp_invmod(&b, &a, &c));
+ gg = (TIMFUNC() - gg) >> 1;
+ if (tt > gg)
+ tt = gg;
+ } while (++rr < 1000u);
+ mp_mulmod(&b, &c, &a, &d);
+ if (mp_cmp_d(&d, 1uL) != MP_EQ) {
+ printf("Failed to invert\n");
+ return 0;
+ }
+ printf("Inverting mod\t%4d-bit => %9" PRIu64 "/sec, %9" PRIu64 " cycles\n",
+ mp_count_bits(&a), CLK_PER_SEC / tt, tt);
+ FPRINTF(log, "%6d %9" PRIu64 "\n", cnt * MP_DIGIT_BIT, tt);
+ }
+ FCLOSE(log);
+ }
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/doc/bn.pdf b/third_party/heimdal/lib/hcrypto/libtommath/doc/bn.pdf
new file mode 100644
index 0000000..fbf05ea
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/doc/bn.pdf
Binary files differ
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/doc/bn.tex b/third_party/heimdal/lib/hcrypto/libtommath/doc/bn.tex
new file mode 100644
index 0000000..5937fee
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/doc/bn.tex
@@ -0,0 +1,2507 @@
+\documentclass[synpaper]{book}
+\usepackage{hyperref}
+\usepackage{makeidx}
+\usepackage{amssymb}
+\usepackage{color}
+\usepackage{alltt}
+\usepackage{graphicx}
+\usepackage{layout}
+\usepackage{appendix}
+\def\union{\cup}
+\def\intersect{\cap}
+\def\getsrandom{\stackrel{\rm R}{\gets}}
+\def\cross{\times}
+\def\cat{\hspace{0.5em} \| \hspace{0.5em}}
+\def\catn{$\|$}
+\def\divides{\hspace{0.3em} | \hspace{0.3em}}
+\def\nequiv{\not\equiv}
+\def\approx{\raisebox{0.2ex}{\mbox{\small $\sim$}}}
+\def\lcm{{\rm lcm}}
+\def\gcd{{\rm gcd}}
+\def\log{{\rm log}}
+\def\ord{{\rm ord}}
+\def\abs{{\mathit abs}}
+\def\rep{{\mathit rep}}
+\def\mod{{\mathit\ mod\ }}
+\renewcommand{\pmod}[1]{\ ({\rm mod\ }{#1})}
+\newcommand{\floor}[1]{\left\lfloor{#1}\right\rfloor}
+\newcommand{\ceil}[1]{\left\lceil{#1}\right\rceil}
+\def\Or{{\rm\ or\ }}
+\def\And{{\rm\ and\ }}
+\def\iff{\hspace{1em}\Longleftrightarrow\hspace{1em}}
+\def\implies{\Rightarrow}
+\def\undefined{{\rm ``undefined"}}
+\def\Proof{\vspace{1ex}\noindent {\bf Proof:}\hspace{1em}}
+\let\oldphi\phi
+\def\phi{\varphi}
+\def\Pr{{\rm Pr}}
+\newcommand{\str}[1]{{\mathbf{#1}}}
+\def\F{{\mathbb F}}
+\def\N{{\mathbb N}}
+\def\Z{{\mathbb Z}}
+\def\R{{\mathbb R}}
+\def\C{{\mathbb C}}
+\def\Q{{\mathbb Q}}
+\definecolor{DGray}{gray}{0.5}
+\newcommand{\emailaddr}[1]{\mbox{$<${#1}$>$}}
+\def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}}
+\def\gap{\vspace{0.5ex}}
+\makeindex
+\begin{document}
+\frontmatter
+\pagestyle{empty}
+\title{LibTomMath User Manual \\ v1.2.0}
+\author{LibTom Projects \\ www.libtom.net}
+\maketitle
+This text, the library and the accompanying textbook are all hereby placed in the public domain. This book has been
+formatted for B5 [176x250] paper using the \LaTeX{} {\em book} macro package.
+
+\vspace{10cm}
+
+\begin{flushright}Open Source. Open Academia. Open Minds.
+
+\mbox{ }
+LibTom Projects
+
+\& originally
+
+Tom St Denis,
+
+Ontario, Canada
+\end{flushright}
+
+\tableofcontents
+\listoffigures
+\mainmatter
+\pagestyle{headings}
+\chapter{Introduction}
+\section{What is LibTomMath?}
+LibTomMath is a library of source code which provides a series of efficient and carefully written functions for manipulating
+large integer numbers. It was written in portable ISO C source code so that it will build on any platform with a conforming
+C compiler.
+
+In a nutshell the library was written from scratch with verbose comments to help instruct computer science students how
+to implement ``bignum'' math. However, the resulting code has proven to be very useful. It has been used by numerous
+universities, commercial and open source software developers. It has been used on a variety of platforms ranging from
+Linux and Windows based x86 to ARM based Gameboys and PPC based MacOS machines.
+
+\section{License}
+As of the v0.25 the library source code has been placed in the public domain with every new release. As of the v0.28
+release the textbook ``Implementing Multiple Precision Arithmetic'' has been placed in the public domain with every new
+release as well. This textbook is meant to compliment the project by providing a more solid walkthrough of the development
+algorithms used in the library.
+
+Since both\footnote{Note that the MPI files under mtest/ are copyrighted by Michael Fromberger. They are not required to use LibTomMath.} are in the
+public domain everyone is entitled to do with them as they see fit.
+
+\section{Building LibTomMath}
+
+LibTomMath is meant to be very ``GCC friendly'' as it comes with a makefile well suited for GCC. However, the library will
+also build in MSVC, Borland C out of the box. For any other ISO C compiler a makefile will have to be made by the end
+developer. Please consider to commit such a makefile to the LibTomMath developers, currently residing at
+\url{http://github.com/libtom/libtommath}, if successfully done so.
+
+Intel's C-compiler (ICC) is sufficiently compatible with GCC, at least the newer versions, to replace GCC for building the static and the shared library. Editing the makefiles is not needed, just set the shell variable \texttt{CC} as shown below.
+\begin{alltt}
+CC=/home/czurnieden/intel/bin/icc make
+\end{alltt}
+
+ICC does not know all options available for GCC and LibTomMath uses two diagnostics \texttt{-Wbad-function-cast} and \texttt{-Wcast-align} that are not supported by ICC resulting in the warnings:
+\begin{alltt}
+icc: command line warning #10148: option '-Wbad-function-cast' not supported
+icc: command line warning #10148: option '-Wcast-align' not supported
+\end{alltt}
+It is possible to mute this ICC warning with the compiler flag \texttt{-diag-disable=10148}\footnote{It is not recommended to suppress warnings without a very good reason but there is no harm in doing so in this very special case.}.
+
+\subsection{Static Libraries}
+To build as a static library for GCC issue the following
+\begin{alltt}
+make
+\end{alltt}
+
+command. This will build the library and archive the object files in ``libtommath.a''. Now you link against
+that and include ``tommath.h'' within your programs. Alternatively to build with MSVC issue the following
+\begin{alltt}
+nmake -f makefile.msvc
+\end{alltt}
+
+This will build the library and archive the object files in ``tommath.lib''. This has been tested with MSVC
+version 6.00 with service pack 5.
+
+To run a program to adapt the Toom-Cook cut-off values to your architecture type
+\begin{alltt}
+make tune
+\end{alltt}
+This will take some time.
+
+\subsection{Shared Libraries}
+\subsubsection{GNU based Operating Systems}
+To build as a shared library for GCC issue the following
+\begin{alltt}
+make -f makefile.shared
+\end{alltt}
+This requires the ``libtool'' package (common on most Linux/BSD systems). It will build LibTomMath as both shared
+and static then install (by default) into /usr/lib as well as install the header files in /usr/include. The shared
+library (resource) will be called ``libtommath.la'' while the static library called ``libtommath.a''. Generally
+you use libtool to link your application against the shared object.
+
+To run a program to adapt the Toom-Cook cut-off values to your architecture type
+\begin{alltt}
+make -f makefile.shared tune
+\end{alltt}
+This will take some time.
+
+\subsubsection{Microsoft Windows based Operating Systems}
+There is limited support for making a ``DLL'' in windows via the ``makefile.cygwin\_dll'' makefile. It requires
+Cygwin to work with since it requires the auto-export/import functionality. The resulting DLL and import library
+``libtommath.dll.a'' can be used to link LibTomMath dynamically to any Windows program using Cygwin.
+\subsubsection{OpenBSD}
+OpenBSD replaced some of their GNU-tools, especially \texttt{libtool} with their own, slightly different versions. To ease the workload of LibTomMath's developer team, only a static library can be build with the included \texttt{makefile.unix}.
+
+The wrong \texttt{make} will result in errors like:
+\begin{alltt}
+*** Parse error in /home/user/GITHUB/libtommath: Need an operator in 'LIBNAME' )
+*** Parse error: Need an operator in 'endif' (makefile.shared:8)
+*** Parse error: Need an operator in 'CROSS_COMPILE' (makefile_include.mk:16)
+*** Parse error: Need an operator in 'endif' (makefile_include.mk:18)
+*** Parse error: Missing dependency operator (makefile_include.mk:22)
+*** Parse error: Missing dependency operator (makefile_include.mk:23)
+...
+\end{alltt}
+The wrong \texttt{libtool} will build it all fine but when it comes to the final linking fails with
+\begin{alltt}
+...
+cc -I./ -Wall -Wsign-compare -Wextra -Wshadow -Wsystem-headers -Wdeclaration-afo...
+cc -I./ -Wall -Wsign-compare -Wextra -Wshadow -Wsystem-headers -Wdeclaration-afo...
+cc -I./ -Wall -Wsign-compare -Wextra -Wshadow -Wsystem-headers -Wdeclaration-afo...
+libtool --mode=link --tag=CC cc bn_error.lo bn_s_mp_invmod_fast.lo bn_fast_mp_mo
+libtool: link: cc bn_error.lo bn_s_mp_invmod_fast.lo bn_s_mp_montgomery_reduce_fast0
+bn_error.lo: file not recognized: File format not recognized
+cc: error: linker command failed with exit code 1 (use -v to see invocation)
+Error while executing cc bn_error.lo bn_s_mp_invmod_fast.lo bn_fast_mp_montgomery0
+gmake: *** [makefile.shared:64: libtommath.la] Error 1
+\end{alltt}
+
+To build a shared library with OpenBSD\footnote{Tested with OpenBSD version 6.4} the GNU versions of \texttt{make} and \texttt{libtool} are needed.
+\begin{alltt}
+$ sudo pkg_add gmake libtool
+\end{alltt}
+At this time two versions of \texttt{libtool} are installed and both are named \texttt{libtool}, unfortunately but GNU \texttt{libtool} has been placed in \texttt{/usr/local/bin/} and the native version in \texttt{/usr/bin/}. The path might be different in other versions of OpenBSD but both programms differ in the output of \texttt{libtool --version}
+\begin{alltt}
+$ /usr/local/bin/libtool --version
+libtool (GNU libtool) 2.4.2
+Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
+
+Copyright (C) 2011 Free Software Foundation, Inc.
+This is free software; see the source for copying conditions. There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+$ libtool --version
+libtool (not (GNU libtool)) 1.5.26
+\end{alltt}
+
+The shared library should build now with
+\begin{alltt}
+LIBTOOL="/usr/local/bin/libtool" gmake -f makefile.shared
+\end{alltt}
+You might need to run a \texttt{gmake -f makefile.shared clean} first.
+
+\subsubsection{NetBSD}
+NetBSD is not as strict as OpenBSD but still needs \texttt{gmake} to build the shared library. \texttt{libtool} may also not exist in a fresh install.
+\begin{alltt}
+pkg_add gmake libtool
+\end{alltt}
+Please check with \texttt{libtool --version} that installed libtool is indeed a GNU libtool.
+Build the shared library by typing:
+\begin{alltt}
+gmake -f makefile.shared
+\end{alltt}
+
+\subsection{Testing}
+To build the library and the test harness type
+
+\begin{alltt}
+make test
+\end{alltt}
+
+This will build the library, ``test'' and ``mtest/mtest''. The ``test'' program will accept test vectors and verify the
+results. ``mtest/mtest'' will generate test vectors using the MPI library by Michael Fromberger\footnote{A copy of MPI
+is included in the package}. Simply pipe mtest into test using
+
+\begin{alltt}
+mtest/mtest | test
+\end{alltt}
+
+If you do not have a ``/dev/urandom'' style RNG source you will have to write your own PRNG and simply pipe that into
+mtest. For example, if your PRNG program is called ``myprng'' simply invoke
+
+\begin{alltt}
+myprng | mtest/mtest | test
+\end{alltt}
+
+This will output a row of numbers that are increasing. Each column is a different test (such as addition, multiplication, etc)
+that is being performed. The numbers represent how many times the test was invoked. If an error is detected the program
+will exit with a dump of the relevant numbers it was working with.
+
+\section{Build Configuration}
+LibTomMath can configured at build time in three phases we shall call ``depends'', ``tweaks'' and ``trims''.
+Each phase changes how the library is built and they are applied one after another respectively.
+
+To make the system more powerful you can tweak the build process. Classes are defined in the file
+``tommath\_superclass.h''. By default, the symbol ``LTM\_ALL'' shall be defined which simply
+instructs the system to build all of the functions. This is how LibTomMath used to be packaged. This will give you
+access to every function LibTomMath offers.
+
+However, there are cases where such a build is not optional. For instance, you want to perform RSA operations. You
+don't need the vast majority of the library to perform these operations. Aside from LTM\_ALL there is
+another pre--defined class ``SC\_RSA\_1'' which works in conjunction with the RSA from LibTomCrypt. Additional
+classes can be defined base on the need of the user.
+
+\subsection{Build Depends}
+In the file tommath\_class.h you will see a large list of C ``defines'' followed by a series of ``ifdefs''
+which further define symbols. All of the symbols (technically they're macros $\ldots$) represent a given C source
+file. For instance, BN\_MP\_ADD\_C represents the file ``bn\_mp\_add.c''. When a define has been enabled the
+function in the respective file will be compiled and linked into the library. Accordingly when the define
+is absent the file will not be compiled and not contribute any size to the library.
+
+You will also note that the header tommath\_class.h is actually recursively included (it includes itself twice).
+This is to help resolve as many dependencies as possible. In the last pass the symbol LTM\_LAST will be defined.
+This is useful for ``trims''.
+
+\subsection{Build Tweaks}
+A tweak is an algorithm ``alternative''. For example, to provide tradeoffs (usually between size and space).
+They can be enabled at any pass of the configuration phase.
+
+\begin{small}
+\begin{center}
+\begin{tabular}{|l|l|}
+\hline \textbf{Define} & \textbf{Purpose} \\
+\hline BN\_MP\_DIV\_SMALL & Enables a slower, smaller and equally \\
+ & functional mp\_div() function \\
+\hline
+\end{tabular}
+\end{center}
+\end{small}
+
+\subsection{Build Trims}
+A trim is a manner of removing functionality from a function that is not required. For instance, to perform
+RSA cryptography you only require exponentiation with odd moduli so even moduli support can be safely removed.
+Build trims are meant to be defined on the last pass of the configuration which means they are to be defined
+only if LTM\_LAST has been defined.
+
+\subsubsection{Moduli Related}
+\begin{small}
+\begin{center}
+\begin{tabular}{|l|l|}
+\hline \textbf{Restriction} & \textbf{Undefine} \\
+\hline Exponentiation with odd moduli only & BN\_S\_MP\_EXPTMOD\_C \\
+ & BN\_MP\_REDUCE\_C \\
+ & BN\_MP\_REDUCE\_SETUP\_C \\
+ & BN\_S\_MP\_MUL\_HIGH\_DIGS\_C \\
+ & BN\_FAST\_S\_MP\_MUL\_HIGH\_DIGS\_C \\
+\hline Exponentiation with random odd moduli & (The above plus the following) \\
+ & BN\_MP\_REDUCE\_2K\_C \\
+ & BN\_MP\_REDUCE\_2K\_SETUP\_C \\
+ & BN\_MP\_REDUCE\_IS\_2K\_C \\
+ & BN\_MP\_DR\_IS\_MODULUS\_C \\
+ & BN\_MP\_DR\_REDUCE\_C \\
+ & BN\_MP\_DR\_SETUP\_C \\
+\hline Modular inverse odd moduli only & BN\_MP\_INVMOD\_SLOW\_C \\
+\hline Modular inverse (both, smaller/slower) & BN\_FAST\_MP\_INVMOD\_C \\
+\hline
+\end{tabular}
+\end{center}
+\end{small}
+
+\subsubsection{Operand Size Related}
+\begin{small}
+\begin{center}
+\begin{tabular}{|l|l|}
+\hline \textbf{Restriction} & \textbf{Undefine} \\
+\hline Moduli $\le 2560$ bits & BN\_MP\_MONTGOMERY\_REDUCE\_C \\
+ & BN\_S\_MP\_MUL\_DIGS\_C \\
+ & BN\_S\_MP\_MUL\_HIGH\_DIGS\_C \\
+ & BN\_S\_MP\_SQR\_C \\
+\hline Polynomial Schmolynomial & BN\_MP\_KARATSUBA\_MUL\_C \\
+ & BN\_MP\_KARATSUBA\_SQR\_C \\
+ & BN\_MP\_TOOM\_MUL\_C \\
+ & BN\_MP\_TOOM\_SQR\_C \\
+
+\hline
+\end{tabular}
+\end{center}
+\end{small}
+
+
+\section{Purpose of LibTomMath}
+Unlike GNU MP (GMP) Library, LIP, OpenSSL or various other commercial kits (Miracl), LibTomMath was not written with
+bleeding edge performance in mind. First and foremost LibTomMath was written to be entirely open. Not only is the
+source code public domain (unlike various other GPL/etc licensed code), not only is the code freely downloadable but the
+source code is also accessible for computer science students attempting to learn ``BigNum'' or multiple precision
+arithmetic techniques.
+
+LibTomMath was written to be an instructive collection of source code. This is why there are many comments, only one
+function per source file and often I use a ``middle-road'' approach where I don't cut corners for an extra 2\% speed
+increase.
+
+Source code alone cannot really teach how the algorithms work which is why I also wrote a textbook that accompanies
+the library (beat that!).
+
+So you may be thinking ``should I use LibTomMath?'' and the answer is a definite maybe. Let me tabulate what I think
+are the pros and cons of LibTomMath by comparing it to the math routines from GnuPG\footnote{GnuPG v1.2.3 versus LibTomMath v0.28}.
+
+\newpage\begin{figure}[h]
+\begin{small}
+\begin{center}
+\begin{tabular}{|l|c|c|l|}
+\hline \textbf{Criteria} & \textbf{Pro} & \textbf{Con} & \textbf{Notes} \\
+\hline Few lines of code per file & X & & GnuPG $ = 300.9$, LibTomMath $ = 71.97$ \\
+\hline Commented function prototypes & X && GnuPG function names are cryptic. \\
+\hline Speed && X & LibTomMath is slower. \\
+\hline Totally free & X & & GPL has unfavourable restrictions.\\
+\hline Large function base & X & & GnuPG is barebones. \\
+\hline Five modular reduction algorithms & X & & Faster modular exponentiation for a variety of moduli. \\
+\hline Portable & X & & GnuPG requires configuration to build. \\
+\hline
+\end{tabular}
+\end{center}
+\end{small}
+\caption{LibTomMath Valuation}
+\end{figure}
+
+It may seem odd to compare LibTomMath to GnuPG since the math in GnuPG is only a small portion of the entire application.
+However, LibTomMath was written with cryptography in mind. It provides essentially all of the functions a cryptosystem
+would require when working with large integers.
+
+So it may feel tempting to just rip the math code out of GnuPG (or GnuMP where it was taken from originally) in your
+own application but I think there are reasons not to. While LibTomMath is slower than libraries such as GnuMP it is
+not normally significantly slower. On x86 machines the difference is normally a factor of two when performing modular
+exponentiations. It depends largely on the processor, compiler and the moduli being used.
+
+Essentially the only time you wouldn't use LibTomMath is when blazing speed is the primary concern. However,
+on the other side of the coin LibTomMath offers you a totally free (public domain) well structured math library
+that is very flexible, complete and performs well in resource constrained environments. Fast RSA for example can
+be performed with as little as 8KB of ram for data (again depending on build options).
+
+\chapter{Getting Started with LibTomMath}
+\section{Building Programs}
+In order to use LibTomMath you must include ``tommath.h'' and link against the appropriate library file (typically
+libtommath.a). There is no library initialization required and the entire library is thread safe.
+
+\section{Return Codes}
+There are three possible return codes a function may return.
+
+\index{MP\_OKAY}\index{MP\_YES}\index{MP\_NO}\index{MP\_VAL}\index{MP\_MEM}
+\begin{figure}[h!]
+\begin{center}
+\begin{small}
+\begin{tabular}{|l|l|}
+\hline \textbf{Code} & \textbf{Meaning} \\
+\hline MP\_OKAY & The function succeeded. \\
+\hline MP\_VAL & The function input was invalid. \\
+\hline MP\_MEM & Heap memory exhausted. \\
+\hline &\\
+\hline MP\_YES & Response is yes. \\
+\hline MP\_NO & Response is no. \\
+\hline
+\end{tabular}
+\end{small}
+\end{center}
+\caption{Return Codes}
+\end{figure}
+
+The last two codes listed are not actually ``return'ed'' by a function. They are placed in an integer (the caller must
+provide the address of an integer it can store to) which the caller can access. To convert one of the three return codes
+to a string use the following function.
+
+\index{mp\_error\_to\_string}
+\begin{alltt}
+char *mp_error_to_string(int code);
+\end{alltt}
+
+This will return a pointer to a string which describes the given error code. It will not work for the return codes
+MP\_YES and MP\_NO.
+
+\section{Data Types}
+The basic ``multiple precision integer'' type is known as the ``mp\_int'' within LibTomMath. This data type is used to
+organize all of the data required to manipulate the integer it represents. Within LibTomMath it has been prototyped
+as the following.
+
+\index{mp\_int}
+\begin{alltt}
+typedef struct \{
+ int used, alloc, sign;
+ mp_digit *dp;
+\} mp_int;
+\end{alltt}
+
+Where ``mp\_digit'' is a data type that represents individual digits of the integer. By default, an mp\_digit is the
+ISO C ``unsigned long'' data type and each digit is $28-$bits long. The mp\_digit type can be configured to suit other
+platforms by defining the appropriate macros.
+
+All LTM functions that use the mp\_int type will expect a pointer to mp\_int structure. You must allocate memory to
+hold the structure itself by yourself (whether off stack or heap it doesn't matter). The very first thing that must be
+done to use an mp\_int is that it must be initialized.
+
+\section{Function Organization}
+
+The arithmetic functions of the library are all organized to have the same style prototype. That is source operands
+are passed on the left and the destination is on the right. For instance,
+
+\begin{alltt}
+mp_add(&a, &b, &c); /* c = a + b */
+mp_mul(&a, &a, &c); /* c = a * a */
+mp_div(&a, &b, &c, &d); /* c = [a/b], d = a mod b */
+\end{alltt}
+
+Another feature of the way the functions have been implemented is that source operands can be destination operands as well.
+For instance,
+
+\begin{alltt}
+mp_add(&a, &b, &b); /* b = a + b */
+mp_div(&a, &b, &a, &c); /* a = [a/b], c = a mod b */
+\end{alltt}
+
+This allows operands to be re-used which can make programming simpler.
+
+\section{Initialization}
+\subsection{Single Initialization}
+A single mp\_int can be initialized with the ``mp\_init'' function.
+
+\index{mp\_init}
+\begin{alltt}
+int mp_init (mp_int * a);
+\end{alltt}
+
+This function expects a pointer to an mp\_int structure and will initialize the members of the structure so the mp\_int
+represents the default integer which is zero. If the functions returns MP\_OKAY then the mp\_int is ready to be used
+by the other LibTomMath functions.
+
+\begin{small} \begin{alltt}
+int main(void)
+\{
+ mp_int number;
+ int result;
+
+ if ((result = mp_init(&number)) != MP_OKAY) \{
+ printf("Error initializing the number. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* use the number */
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt} \end{small}
+
+\subsection{Single Free}
+When you are finished with an mp\_int it is ideal to return the heap it used back to the system. The following function
+provides this functionality.
+
+\index{mp\_clear}
+\begin{alltt}
+void mp_clear (mp_int * a);
+\end{alltt}
+
+The function expects a pointer to a previously initialized mp\_int structure and frees the heap it uses. It sets the
+pointer\footnote{The ``dp'' member.} within the mp\_int to \textbf{NULL} which is used to prevent double free situations.
+Is is legal to call mp\_clear() twice on the same mp\_int in a row.
+
+\begin{small} \begin{alltt}
+int main(void)
+\{
+ mp_int number;
+ int result;
+
+ if ((result = mp_init(&number)) != MP_OKAY) \{
+ printf("Error initializing the number. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* use the number */
+
+ /* We're done with it. */
+ mp_clear(&number);
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt} \end{small}
+
+\subsection{Multiple Initializations}
+Certain algorithms require more than one large integer. In these instances it is ideal to initialize all of the mp\_int
+variables in an ``all or nothing'' fashion. That is, they are either all initialized successfully or they are all
+not initialized.
+
+The mp\_init\_multi() function provides this functionality.
+
+\index{mp\_init\_multi} \index{mp\_clear\_multi}
+\begin{alltt}
+int mp_init_multi(mp_int *mp, ...);
+\end{alltt}
+
+It accepts a \textbf{NULL} terminated list of pointers to mp\_int structures. It will attempt to initialize them all
+at once. If the function returns MP\_OKAY then all of the mp\_int variables are ready to use, otherwise none of them
+are available for use. A complementary mp\_clear\_multi() function allows multiple mp\_int variables to be free'd
+from the heap at the same time.
+
+\begin{small} \begin{alltt}
+int main(void)
+\{
+ mp_int num1, num2, num3;
+ int result;
+
+ if ((result = mp_init_multi(&num1,
+ &num2,
+ &num3, NULL)) != MP\_OKAY) \{
+ printf("Error initializing the numbers. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* use the numbers */
+
+ /* We're done with them. */
+ mp_clear_multi(&num1, &num2, &num3, NULL);
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt} \end{small}
+
+\subsection{Other Initializers}
+To initialized and make a copy of an mp\_int the mp\_init\_copy() function has been provided.
+
+\index{mp\_init\_copy}
+\begin{alltt}
+int mp_init_copy (mp_int * a, mp_int * b);
+\end{alltt}
+
+This function will initialize $a$ and make it a copy of $b$ if all goes well.
+
+\begin{small} \begin{alltt}
+int main(void)
+\{
+ mp_int num1, num2;
+ int result;
+
+ /* initialize and do work on num1 ... */
+
+ /* We want a copy of num1 in num2 now */
+ if ((result = mp_init_copy(&num2, &num1)) != MP_OKAY) \{
+ printf("Error initializing the copy. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* now num2 is ready and contains a copy of num1 */
+
+ /* We're done with them. */
+ mp_clear_multi(&num1, &num2, NULL);
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt} \end{small}
+
+Another less common initializer is mp\_init\_size() which allows the user to initialize an mp\_int with a given
+default number of digits. By default, all initializers allocate \textbf{MP\_PREC} digits. This function lets
+you override this behaviour.
+
+\index{mp\_init\_size}
+\begin{alltt}
+int mp_init_size (mp_int * a, int size);
+\end{alltt}
+
+The $size$ parameter must be greater than zero. If the function succeeds the mp\_int $a$ will be initialized
+to have $size$ digits (which are all initially zero).
+
+\begin{small} \begin{alltt}
+int main(void)
+\{
+ mp_int number;
+ int result;
+
+ /* we need a 60-digit number */
+ if ((result = mp_init_size(&number, 60)) != MP_OKAY) \{
+ printf("Error initializing the number. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* use the number */
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt} \end{small}
+
+\section{Maintenance Functions}
+\subsection{Clear Leading Zeros}
+
+This is used to ensure that leading zero digits are trimed and the leading "used" digit will be non-zero.
+It also fixes the sign if there are no more leading digits.
+
+\index{mp\_clamp}
+\begin{alltt}
+void mp_clamp(mp_int *a);
+\end{alltt}
+
+\subsection{Zero Out}
+
+This function will set the ``bigint'' to zeros without changing the amount of allocated memory.
+
+\index{mp\_zero}
+\begin{alltt}
+void mp_zero(mp_int *a);
+\end{alltt}
+
+
+\subsection{Reducing Memory Usage}
+When an mp\_int is in a state where it won't be changed again\footnote{A Diffie-Hellman modulus for instance.} excess
+digits can be removed to return memory to the heap with the mp\_shrink() function.
+
+\index{mp\_shrink}
+\begin{alltt}
+int mp_shrink (mp_int * a);
+\end{alltt}
+
+This will remove excess digits of the mp\_int $a$. If the operation fails the mp\_int should be intact without the
+excess digits being removed. Note that you can use a shrunk mp\_int in further computations, however, such operations
+will require heap operations which can be slow. It is not ideal to shrink mp\_int variables that you will further
+modify in the system (unless you are seriously low on memory).
+
+\begin{small} \begin{alltt}
+int main(void)
+\{
+ mp_int number;
+ int result;
+
+ if ((result = mp_init(&number)) != MP_OKAY) \{
+ printf("Error initializing the number. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* use the number [e.g. pre-computation] */
+
+ /* We're done with it for now. */
+ if ((result = mp_shrink(&number)) != MP_OKAY) \{
+ printf("Error shrinking the number. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* use it .... */
+
+
+ /* we're done with it. */
+ mp_clear(&number);
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt} \end{small}
+
+\subsection{Adding additional digits}
+
+Within the mp\_int structure are two parameters which control the limitations of the array of digits that represent
+the integer the mp\_int is meant to equal. The \textit{used} parameter dictates how many digits are significant, that is,
+contribute to the value of the mp\_int. The \textit{alloc} parameter dictates how many digits are currently available in
+the array. If you need to perform an operation that requires more digits you will have to mp\_grow() the mp\_int to
+your desired size.
+
+\index{mp\_grow}
+\begin{alltt}
+int mp_grow (mp_int * a, int size);
+\end{alltt}
+
+This will grow the array of digits of $a$ to $size$. If the \textit{alloc} parameter is already bigger than
+$size$ the function will not do anything.
+
+\begin{small} \begin{alltt}
+int main(void)
+\{
+ mp_int number;
+ int result;
+
+ if ((result = mp_init(&number)) != MP_OKAY) \{
+ printf("Error initializing the number. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* use the number */
+
+ /* We need to add 20 digits to the number */
+ if ((result = mp_grow(&number, number.alloc + 20)) != MP_OKAY) \{
+ printf("Error growing the number. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+
+ /* use the number */
+
+ /* we're done with it. */
+ mp_clear(&number);
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt} \end{small}
+
+\chapter{Basic Operations}
+\section{Copying}
+
+A so called ``deep copy'', where new memory is allocated and all contents of $a$ are copied verbatim into $b$ such that $b = a$ at the end.
+
+\index{mp\_copy}
+\begin{alltt}
+int mp_copy (mp_int * a, mp_int *b);
+\end{alltt}
+
+You can also just swap $a$ and $b$. It does the normal pointer changing with a temporary pointer variable, just that you do not have to.
+
+\index{mp\_exch}
+\begin{alltt}
+void mp_exch (mp_int * a, mp_int *b);
+\end{alltt}
+
+\section{Bit Counting}
+
+To get the position of the lowest bit set (LSB, the Lowest Significant Bit; the number of bits which are zero before the first zero bit )
+
+\index{mp\_cnt\_lsb}
+\begin{alltt}
+int mp_cnt_lsb(const mp_int *a);
+\end{alltt}
+
+To get the position of the highest bit set (MSB, the Most Significant Bit; the number of bits in teh ``bignum'')
+
+\index{mp\_count\_bits}
+\begin{alltt}
+int mp_count_bits(const mp_int *a);
+\end{alltt}
+
+
+\section{Small Constants}
+Setting mp\_ints to small constants is a relatively common operation. To accommodate these instances there is a
+small constant assignment function. This function is used to set a single digit constant.
+The reason for this function is efficiency. Setting a single digit is quick but the
+domain of a digit can change (it's always at least $0 \ldots 127$).
+
+\subsection{Single Digit}
+
+Setting a single digit can be accomplished with the following function.
+
+\index{mp\_set}
+\begin{alltt}
+void mp_set (mp_int * a, mp_digit b);
+\end{alltt}
+
+This will zero the contents of $a$ and make it represent an integer equal to the value of $b$. Note that this
+function has a return type of \textbf{void}. It cannot cause an error so it is safe to assume the function
+succeeded.
+
+\begin{small} \begin{alltt}
+int main(void)
+\{
+ mp_int number;
+ int result;
+
+ if ((result = mp_init(&number)) != MP_OKAY) \{
+ printf("Error initializing the number. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* set the number to 5 */
+ mp_set(&number, 5);
+
+ /* we're done with it. */
+ mp_clear(&number);
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt} \end{small}
+
+\subsection{Int32 and Int64 Constants}
+
+These functions can be used to set a constant with 32 or 64 bits.
+
+\index{mp\_set\_i32} \index{mp\_set\_u32}
+\index{mp\_set\_i64} \index{mp\_set\_u64}
+\begin{alltt}
+void mp_set_i32 (mp_int * a, int32_t b);
+void mp_set_u32 (mp_int * a, uint32_t b);
+void mp_set_i64 (mp_int * a, int64_t b);
+void mp_set_u64 (mp_int * a, uint64_t b);
+\end{alltt}
+
+These functions assign the sign and value of the input \texttt{b} to \texttt{mp\_int a}.
+The value can be obtained again by calling the following functions.
+
+\index{mp\_get\_i32} \index{mp\_get\_u32} \index{mp\_get\_mag\_u32}
+\index{mp\_get\_i64} \index{mp\_get\_u64} \index{mp\_get\_mag\_u64}
+\begin{alltt}
+int32_t mp_get_i32 (mp_int * a);
+uint32_t mp_get_u32 (mp_int * a);
+uint32_t mp_get_mag_u32 (mp_int * a);
+int64_t mp_get_i64 (mp_int * a);
+uint64_t mp_get_u64 (mp_int * a);
+uint64_t mp_get_mag_u64 (mp_int * a);
+\end{alltt}
+
+These functions return the 32 or 64 least significant bits of $a$ respectively. The unsigned functions
+return negative values in a twos complement representation. The absolute value or magnitude can be obtained using the mp\_get\_mag functions.
+
+\begin{small} \begin{alltt}
+int main(void)
+\{
+ mp_int number;
+ int result;
+
+ if ((result = mp_init(&number)) != MP_OKAY) \{
+ printf("Error initializing the number. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* set the number to 654321 (note this is bigger than 127) */
+ mp_set_u32(&number, 654321);
+
+ printf("number == \%" PRIi32, mp_get_i32(&number));
+
+ /* we're done with it. */
+ mp_clear(&number);
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt} \end{small}
+
+This should output the following if the program succeeds.
+
+\begin{alltt}
+number == 654321
+\end{alltt}
+
+\subsection{Long Constants - platform dependant}
+
+\index{mp\_set\_l} \index{mp\_set\_ul}
+\begin{alltt}
+void mp_set_l (mp_int * a, long b);
+void mp_set_ul (mp_int * a, unsigned long b);
+\end{alltt}
+
+This will assign the value of the platform-dependent sized variable $b$ to the mp\_int $a$.
+
+To retrieve the value, the following functions can be used.
+
+\index{mp\_get\_l} \index{mp\_get\_ul} \index{mp\_get\_mag\_ul}
+\begin{alltt}
+long mp_get_l (mp_int * a);
+unsigned long mp_get_ul (mp_int * a);
+unsigned long mp_get_mag_ul (mp_int * a);
+\end{alltt}
+
+This will return the least significant bits of the mp\_int $a$ that fit into a ``long''.
+
+\subsection{Long Long Constants - platform dependant}
+
+\index{mp\_set\_ll} \index{mp\_set\_ull}
+\begin{alltt}
+void mp_set_ll (mp_int * a, long long b);
+void mp_set_ull (mp_int * a, unsigned long long b);
+\end{alltt}
+
+This will assign the value of the platform-dependent sized variable $b$ to the mp\_int $a$.
+
+To retrieve the value, the following functions can be used.
+
+\index{mp\_get\_ll}
+\index{mp\_get\_ull}
+\index{mp\_get\_mag\_ull}
+\begin{alltt}
+long long mp_get_ll (mp_int * a);
+unsigned long long mp_get_ull (mp_int * a);
+unsigned long long mp_get_mag_ull (mp_int * a);
+\end{alltt}
+
+This will return the least significant bits of the mp\_int $a$ that fit into a ``long long''.
+
+\subsection{Initialize and Setting Constants}
+To both initialize and set small constants the following two functions are available.
+\index{mp\_init\_set} \index{mp\_init\_set\_int}
+\begin{alltt}
+int mp_init_set (mp_int * a, mp_digit b);
+int mp_init_i32 (mp_int * a, int32_t b);
+int mp_init_u32 (mp_int * a, uint32_t b);
+int mp_init_i64 (mp_int * a, int64_t b);
+int mp_init_u64 (mp_int * a, uint64_t b);
+int mp_init_l (mp_int * a, long b);
+int mp_init_ul (mp_int * a, unsigned long b);
+int mp_init_ll (mp_int * a, long long b);
+int mp_init_ull (mp_int * a, unsigned long long b);
+\end{alltt}
+
+Both functions work like the previous counterparts except they first mp\_init $a$ before setting the values.
+
+\begin{alltt}
+int main(void)
+\{
+ mp_int number1, number2;
+ int result;
+
+ /* initialize and set a single digit */
+ if ((result = mp_init_set(&number1, 100)) != MP_OKAY) \{
+ printf("Error setting number1: \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* initialize and set a long */
+ if ((result = mp_init_l(&number2, 1023)) != MP_OKAY) \{
+ printf("Error setting number2: \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* display */
+ printf("Number1, Number2 == \%" PRIi32 ", \%" PRIi32,
+ mp_get_i32(&number1), mp_get_i32(&number2));
+
+ /* clear */
+ mp_clear_multi(&number1, &number2, NULL);
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt}
+
+If this program succeeds it shall output.
+\begin{alltt}
+Number1, Number2 == 100, 1023
+\end{alltt}
+
+\section{Comparisons}
+
+Comparisons in LibTomMath are always performed in a ``left to right'' fashion. There are three possible return codes
+for any comparison.
+
+\index{MP\_GT} \index{MP\_EQ} \index{MP\_LT}
+\begin{figure}[h]
+\begin{center}
+\begin{tabular}{|c|c|}
+\hline \textbf{Result Code} & \textbf{Meaning} \\
+\hline MP\_GT & $a > b$ \\
+\hline MP\_EQ & $a = b$ \\
+\hline MP\_LT & $a < b$ \\
+\hline
+\end{tabular}
+\end{center}
+\caption{Comparison Codes for $a, b$}
+\label{fig:CMP}
+\end{figure}
+
+In figure \ref{fig:CMP} two integers $a$ and $b$ are being compared. In this case $a$ is said to be ``to the left'' of
+$b$.
+
+\subsection{Unsigned comparison}
+
+An unsigned comparison considers only the digits themselves and not the associated \textit{sign} flag of the
+mp\_int structures. This is analogous to an absolute comparison. The function mp\_cmp\_mag() will compare two
+mp\_int variables based on their digits only.
+
+\index{mp\_cmp\_mag}
+\begin{alltt}
+int mp_cmp_mag(mp_int * a, mp_int * b);
+\end{alltt}
+This will compare $a$ to $b$ placing $a$ to the left of $b$. This function cannot fail and will return one of the
+three compare codes listed in figure \ref{fig:CMP}.
+
+\begin{small} \begin{alltt}
+int main(void)
+\{
+ mp_int number1, number2;
+ int result;
+
+ if ((result = mp_init_multi(&number1, &number2, NULL)) != MP_OKAY) \{
+ printf("Error initializing the numbers. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* set the number1 to 5 */
+ mp_set(&number1, 5);
+
+ /* set the number2 to -6 */
+ mp_set(&number2, 6);
+ if ((result = mp_neg(&number2, &number2)) != MP_OKAY) \{
+ printf("Error negating number2. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ switch(mp_cmp_mag(&number1, &number2)) \{
+ case MP_GT: printf("|number1| > |number2|"); break;
+ case MP_EQ: printf("|number1| = |number2|"); break;
+ case MP_LT: printf("|number1| < |number2|"); break;
+ \}
+
+ /* we're done with it. */
+ mp_clear_multi(&number1, &number2, NULL);
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt} \end{small}
+
+If this program\footnote{This function uses the mp\_neg() function which is discussed in section \ref{sec:NEG}.} completes
+successfully it should print the following.
+
+\begin{alltt}
+|number1| < |number2|
+\end{alltt}
+
+This is because $\vert -6 \vert = 6$ and obviously $5 < 6$.
+
+\subsection{Signed comparison}
+
+To compare two mp\_int variables based on their signed value the mp\_cmp() function is provided.
+
+\index{mp\_cmp}
+\begin{alltt}
+int mp_cmp(mp_int * a, mp_int * b);
+\end{alltt}
+
+This will compare $a$ to the left of $b$. It will first compare the signs of the two mp\_int variables. If they
+differ it will return immediately based on their signs. If the signs are equal then it will compare the digits
+individually. This function will return one of the compare conditions codes listed in figure \ref{fig:CMP}.
+
+\begin{small} \begin{alltt}
+int main(void)
+\{
+ mp_int number1, number2;
+ int result;
+
+ if ((result = mp_init_multi(&number1, &number2, NULL)) != MP_OKAY) \{
+ printf("Error initializing the numbers. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* set the number1 to 5 */
+ mp_set(&number1, 5);
+
+ /* set the number2 to -6 */
+ mp_set(&number2, 6);
+ if ((result = mp_neg(&number2, &number2)) != MP_OKAY) \{
+ printf("Error negating number2. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ switch(mp_cmp(&number1, &number2)) \{
+ case MP_GT: printf("number1 > number2"); break;
+ case MP_EQ: printf("number1 = number2"); break;
+ case MP_LT: printf("number1 < number2"); break;
+ \}
+
+ /* we're done with it. */
+ mp_clear_multi(&number1, &number2, NULL);
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt} \end{small}
+
+If this program\footnote{This function uses the mp\_neg() function which is discussed in section \ref{sec:NEG}.} completes
+successfully it should print the following.
+
+\begin{alltt}
+number1 > number2
+\end{alltt}
+
+\subsection{Single Digit}
+
+To compare a single digit against an mp\_int the following function has been provided.
+
+\index{mp\_cmp\_d}
+\begin{alltt}
+int mp_cmp_d(mp_int * a, mp_digit b);
+\end{alltt}
+
+This will compare $a$ to the left of $b$ using a signed comparison. Note that it will always treat $b$ as
+positive. This function is rather handy when you have to compare against small values such as $1$ (which often
+comes up in cryptography). The function cannot fail and will return one of the tree compare condition codes
+listed in figure \ref{fig:CMP}.
+
+
+\begin{small} \begin{alltt}
+int main(void)
+\{
+ mp_int number;
+ int result;
+
+ if ((result = mp_init(&number)) != MP_OKAY) \{
+ printf("Error initializing the number. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* set the number to 5 */
+ mp_set(&number, 5);
+
+ switch(mp_cmp_d(&number, 7)) \{
+ case MP_GT: printf("number > 7"); break;
+ case MP_EQ: printf("number = 7"); break;
+ case MP_LT: printf("number < 7"); break;
+ \}
+
+ /* we're done with it. */
+ mp_clear(&number);
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt} \end{small}
+
+If this program functions properly it will print out the following.
+
+\begin{alltt}
+number < 7
+\end{alltt}
+
+\section{Logical Operations}
+
+Logical operations are operations that can be performed either with simple shifts or boolean operators such as
+AND, XOR and OR directly. These operations are very quick.
+
+\subsection{Multiplication by two}
+
+Multiplications and divisions by any power of two can be performed with quick logical shifts either left or
+right depending on the operation.
+
+When multiplying or dividing by two a special case routine can be used which are as follows.
+\index{mp\_mul\_2} \index{mp\_div\_2}
+\begin{alltt}
+int mp_mul_2(mp_int * a, mp_int * b);
+int mp_div_2(mp_int * a, mp_int * b);
+\end{alltt}
+
+The former will assign twice $a$ to $b$ while the latter will assign half $a$ to $b$. These functions are fast
+since the shift counts and maskes are hardcoded into the routines.
+
+\begin{small} \begin{alltt}
+int main(void)
+\{
+ mp_int number;
+ int result;
+
+ if ((result = mp_init(&number)) != MP_OKAY) \{
+ printf("Error initializing the number. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* set the number to 5 */
+ mp_set(&number, 5);
+
+ /* multiply by two */
+ if ((result = mp\_mul\_2(&number, &number)) != MP_OKAY) \{
+ printf("Error multiplying the number. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+ switch(mp_cmp_d(&number, 7)) \{
+ case MP_GT: printf("2*number > 7"); break;
+ case MP_EQ: printf("2*number = 7"); break;
+ case MP_LT: printf("2*number < 7"); break;
+ \}
+
+ /* now divide by two */
+ if ((result = mp\_div\_2(&number, &number)) != MP_OKAY) \{
+ printf("Error dividing the number. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+ switch(mp_cmp_d(&number, 7)) \{
+ case MP_GT: printf("2*number/2 > 7"); break;
+ case MP_EQ: printf("2*number/2 = 7"); break;
+ case MP_LT: printf("2*number/2 < 7"); break;
+ \}
+
+ /* we're done with it. */
+ mp_clear(&number);
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt} \end{small}
+
+If this program is successful it will print out the following text.
+
+\begin{alltt}
+2*number > 7
+2*number/2 < 7
+\end{alltt}
+
+Since $10 > 7$ and $5 < 7$.
+
+To multiply by a power of two the following function can be used.
+
+\index{mp\_mul\_2d}
+\begin{alltt}
+int mp_mul_2d(mp_int * a, int b, mp_int * c);
+\end{alltt}
+
+This will multiply $a$ by $2^b$ and store the result in ``c''. If the value of $b$ is less than or equal to
+zero the function will copy $a$ to ``c'' without performing any further actions. The multiplication itself
+is implemented as a right-shift operation of $a$ by $b$ bits.
+
+To divide by a power of two use the following.
+
+\index{mp\_div\_2d}
+\begin{alltt}
+int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d);
+\end{alltt}
+Which will divide $a$ by $2^b$, store the quotient in ``c'' and the remainder in ``d'. If $b \le 0$ then the
+function simply copies $a$ over to ``c'' and zeroes $d$. The variable $d$ may be passed as a \textbf{NULL}
+value to signal that the remainder is not desired. The division itself is implemented as a left-shift
+operation of $a$ by $b$ bits.
+
+It is also not very uncommon to need just the power of two $2^b$; for example the startvalue for the Newton method.
+
+\index{mp\_2expt}
+\begin{alltt}
+int mp_2expt(mp_int *a, int b);
+\end{alltt}
+It is faster than doing it by shifting $1$ with \texttt{mp\_mul\_2d}.
+
+\subsection{Polynomial Basis Operations}
+
+Strictly speaking the organization of the integers within the mp\_int structures is what is known as a
+``polynomial basis''. This simply means a field element is stored by divisions of a radix. For example, if
+$f(x) = \sum_{i=0}^{k} y_ix^k$ for any vector $\vec y$ then the array of digits in $\vec y$ are said to be
+the polynomial basis representation of $z$ if $f(\beta) = z$ for a given radix $\beta$.
+
+To multiply by the polynomial $g(x) = x$ all you have todo is shift the digits of the basis left one place. The
+following function provides this operation.
+
+\index{mp\_lshd}
+\begin{alltt}
+int mp_lshd (mp_int * a, int b);
+\end{alltt}
+
+This will multiply $a$ in place by $x^b$ which is equivalent to shifting the digits left $b$ places and inserting zeroes
+in the least significant digits. Similarly to divide by a power of $x$ the following function is provided.
+
+\index{mp\_rshd}
+\begin{alltt}
+void mp_rshd (mp_int * a, int b)
+\end{alltt}
+This will divide $a$ in place by $x^b$ and discard the remainder. This function cannot fail as it performs the operations
+in place and no new digits are required to complete it.
+
+\subsection{AND, OR, XOR and COMPLEMENT Operations}
+
+While AND, OR and XOR operations compute arbitrary-precision bitwise operations. Negative numbers
+are treated as if they are in two-complement representation, while internally they are sign-magnitude however.
+
+\index{mp\_or} \index{mp\_and} \index{mp\_xor} \index{mp\_complement}
+\begin{alltt}
+int mp_or (mp_int * a, mp_int * b, mp_int * c);
+int mp_and (mp_int * a, mp_int * b, mp_int * c);
+int mp_xor (mp_int * a, mp_int * b, mp_int * c);
+int mp_complement(const mp_int *a, mp_int *b);
+int mp_signed_rsh(mp_int * a, int b, mp_int * c, mp_int * d);
+\end{alltt}
+
+The function \texttt{mp\_complement} computes a two-complement $b = \sim a$. The function \texttt{mp\_signed\_rsh} performs
+sign extending right shift. For positive numbers it is equivalent to \texttt{mp\_div\_2d}.
+
+\subsection{Bit Picking}
+\index{mp\_get\_bit}
+\begin{alltt}
+int mp_get_bit(mp_int *a, int b)
+\end{alltt}
+
+Pick a bit: returns \texttt{MP\_YES} if the bit at position $b$ (0-index) is set, that is if it is 1 (one), \texttt{MP\_NO}
+if the bit is 0 (zero) and \texttt{MP\_VAL} if $b < 0$.
+
+\section{Addition and Subtraction}
+
+To compute an addition or subtraction the following two functions can be used.
+
+\index{mp\_add} \index{mp\_sub}
+\begin{alltt}
+int mp_add (mp_int * a, mp_int * b, mp_int * c);
+int mp_sub (mp_int * a, mp_int * b, mp_int * c)
+\end{alltt}
+
+Which perform $c = a \odot b$ where $\odot$ is one of signed addition or subtraction. The operations are fully sign
+aware.
+
+\section{Sign Manipulation}
+\subsection{Negation}
+\label{sec:NEG}
+Simple integer negation can be performed with the following.
+
+\index{mp\_neg}
+\begin{alltt}
+int mp_neg (mp_int * a, mp_int * b);
+\end{alltt}
+
+Which assigns $-a$ to $b$.
+
+\subsection{Absolute}
+Simple integer absolutes can be performed with the following.
+
+\index{mp\_abs}
+\begin{alltt}
+int mp_abs (mp_int * a, mp_int * b);
+\end{alltt}
+
+Which assigns $\vert a \vert$ to $b$.
+
+\section{Integer Division and Remainder}
+To perform a complete and general integer division with remainder use the following function.
+
+\index{mp\_div}
+\begin{alltt}
+int mp_div (mp_int * a, mp_int * b, mp_int * c, mp_int * d);
+\end{alltt}
+
+This divides $a$ by $b$ and stores the quotient in $c$ and $d$. The signed quotient is computed such that
+$bc + d = a$. Note that either of $c$ or $d$ can be set to \textbf{NULL} if their value is not required. If
+$b$ is zero the function returns \textbf{MP\_VAL}.
+
+
+\chapter{Multiplication and Squaring}
+\section{Multiplication}
+A full signed integer multiplication can be performed with the following.
+\index{mp\_mul}
+\begin{alltt}
+int mp_mul (mp_int * a, mp_int * b, mp_int * c);
+\end{alltt}
+Which assigns the full signed product $ab$ to $c$. This function actually breaks into one of four cases which are
+specific multiplication routines optimized for given parameters. First there are the Toom-Cook multiplications which
+should only be used with very large inputs. This is followed by the Karatsuba multiplications which are for moderate
+sized inputs. Then followed by the Comba and baseline multipliers.
+
+Fortunately for the developer you don't really need to know this unless you really want to fine tune the system. mp\_mul()
+will determine on its own\footnote{Some tweaking may be required but \texttt{make tune} will put some reasonable values in \texttt{bncore.c}} what routine to use automatically when it is called.
+
+\begin{alltt}
+int main(void)
+\{
+ mp_int number1, number2;
+ int result;
+
+ /* Initialize the numbers */
+ if ((result = mp_init_multi(&number1,
+ &number2, NULL)) != MP_OKAY) \{
+ printf("Error initializing the numbers. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* set the terms */
+ mp_set_i32(&number, 257);
+ mp_set_i32(&number2, 1023);
+
+ /* multiply them */
+ if ((result = mp_mul(&number1, &number2,
+ &number1)) != MP_OKAY) \{
+ printf("Error multiplying terms. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* display */
+ printf("number1 * number2 == \%" PRIi32, mp_get_i32(&number1));
+
+ /* free terms and return */
+ mp_clear_multi(&number1, &number2, NULL);
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt}
+
+If this program succeeds it shall output the following.
+
+\begin{alltt}
+number1 * number2 == 262911
+\end{alltt}
+
+\section{Squaring}
+Since squaring can be performed faster than multiplication it is performed it's own function instead of just using
+mp\_mul().
+
+\index{mp\_sqr}
+\begin{alltt}
+int mp_sqr (mp_int * a, mp_int * b);
+\end{alltt}
+
+Will square $a$ and store it in $b$. Like the case of multiplication there are four different squaring
+algorithms all which can be called from mp\_sqr(). It is ideal to use mp\_sqr over mp\_mul when squaring terms because
+of the speed difference.
+
+\section{Tuning Polynomial Basis Routines}
+
+Both of the Toom-Cook and Karatsuba multiplication algorithms are faster than the traditional $O(n^2)$ approach that
+the Comba and baseline algorithms use. At $O(n^{1.464973})$ and $O(n^{1.584962})$ running times respectively they require
+considerably less work. For example, a 10000-digit multiplication would take roughly 724,000 single precision
+multiplications with Toom-Cook or 100,000,000 single precision multiplications with the standard Comba (a factor
+of 138).
+
+So why not always use Karatsuba or Toom-Cook? The simple answer is that they have so much overhead that they're not
+actually faster than Comba until you hit distinct ``cutoff'' points. For Karatsuba with the default configuration,
+GCC 3.3.1 and an Athlon XP processor the cutoff point is roughly 110 digits (about 70 for the Intel P4). That is, at
+110 digits Karatsuba and Comba multiplications just about break even and for 110+ digits Karatsuba is faster.
+
+Toom-Cook has incredible overhead and is probably only useful for very large inputs. So far no known cutoff points
+exist and for the most part I just set the cutoff points very high to make sure they're not called.
+
+To get reasonable values for the cut-off points for your architecture, type
+
+\begin{alltt}
+make tune
+\end{alltt}
+
+This will run a benchmark, computes the medians, rewrites \texttt{bncore.c}, and recompiles \texttt{bncore.c} and relinks the library.
+
+The benchmark itself can be fine-tuned in the file \texttt{etc/tune\_it.sh}.
+
+The program \texttt{etc/tune} is also able to print a list of values for printing curves with e.g.: \texttt{gnuplot}. type \texttt{./etc/tune -h} to get a list of all available options.
+
+\chapter{Modular Reduction}
+
+Modular reduction is process of taking the remainder of one quantity divided by another. Expressed
+as (\ref{eqn:mod}) the modular reduction is equivalent to the remainder of $b$ divided by $c$.
+
+\begin{equation}
+a \equiv b \mbox{ (mod }c\mbox{)}
+\label{eqn:mod}
+\end{equation}
+
+Of particular interest to cryptography are reductions where $b$ is limited to the range $0 \le b < c^2$ since particularly
+fast reduction algorithms can be written for the limited range.
+
+Note that one of the four optimized reduction algorithms are automatically chosen in the modular exponentiation
+algorithm mp\_exptmod when an appropriate modulus is detected.
+
+\section{Straight Division}
+In order to effect an arbitrary modular reduction the following algorithm is provided.
+
+\index{mp\_mod}
+\begin{alltt}
+int mp_mod(mp_int *a, mp_int *b, mp_int *c);
+\end{alltt}
+
+This reduces $a$ modulo $b$ and stores the result in $c$. The sign of $c$ shall agree with the sign
+of $b$. This algorithm accepts an input $a$ of any range and is not limited by $0 \le a < b^2$.
+
+\section{Barrett Reduction}
+
+Barrett reduction is a generic optimized reduction algorithm that requires pre--computation to achieve
+a decent speedup over straight division. First a $\mu$ value must be precomputed with the following function.
+
+\index{mp\_reduce\_setup}
+\begin{alltt}
+int mp_reduce_setup(mp_int *a, mp_int *b);
+\end{alltt}
+
+Given a modulus in $b$ this produces the required $\mu$ value in $a$. For any given modulus this only has to
+be computed once. Modular reduction can now be performed with the following.
+
+\index{mp\_reduce}
+\begin{alltt}
+int mp_reduce(mp_int *a, mp_int *b, mp_int *c);
+\end{alltt}
+
+This will reduce $a$ in place modulo $b$ with the precomputed $\mu$ value in $c$. $a$ must be in the range
+$0 \le a < b^2$.
+
+\begin{alltt}
+int main(void)
+\{
+ mp_int a, b, c, mu;
+ int result;
+
+ /* initialize a,b to desired values, mp_init mu,
+ * c and set c to 1...we want to compute a^3 mod b
+ */
+
+ /* get mu value */
+ if ((result = mp_reduce_setup(&mu, b)) != MP_OKAY) \{
+ printf("Error getting mu. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* square a to get c = a^2 */
+ if ((result = mp_sqr(&a, &c)) != MP_OKAY) \{
+ printf("Error squaring. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* now reduce `c' modulo b */
+ if ((result = mp_reduce(&c, &b, &mu)) != MP_OKAY) \{
+ printf("Error reducing. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* multiply a to get c = a^3 */
+ if ((result = mp_mul(&a, &c, &c)) != MP_OKAY) \{
+ printf("Error reducing. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* now reduce `c' modulo b */
+ if ((result = mp_reduce(&c, &b, &mu)) != MP_OKAY) \{
+ printf("Error reducing. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* c now equals a^3 mod b */
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt}
+
+This program will calculate $a^3 \mbox{ mod }b$ if all the functions succeed.
+
+\section{Montgomery Reduction}
+
+Montgomery is a specialized reduction algorithm for any odd moduli. Like Barrett reduction a pre--computation
+step is required. This is accomplished with the following.
+
+\index{mp\_montgomery\_setup}
+\begin{alltt}
+int mp_montgomery_setup(mp_int *a, mp_digit *mp);
+\end{alltt}
+
+For the given odd moduli $a$ the precomputation value is placed in $mp$. The reduction is computed with the
+following.
+
+\index{mp\_montgomery\_reduce}
+\begin{alltt}
+int mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp);
+\end{alltt}
+This reduces $a$ in place modulo $m$ with the pre--computed value $mp$. $a$ must be in the range
+$0 \le a < b^2$.
+
+Montgomery reduction is faster than Barrett reduction for moduli smaller than the ``comba'' limit. With the default
+setup for instance, the limit is $127$ digits ($3556$--bits). Note that this function is not limited to
+$127$ digits just that it falls back to a baseline algorithm after that point.
+
+An important observation is that this reduction does not return $a \mbox{ mod }m$ but $aR^{-1} \mbox{ mod }m$
+where $R = \beta^n$, $n$ is the n number of digits in $m$ and $\beta$ is radix used (default is $2^{28}$).
+
+To quickly calculate $R$ the following function was provided.
+
+\index{mp\_montgomery\_calc\_normalization}
+\begin{alltt}
+int mp_montgomery_calc_normalization(mp_int *a, mp_int *b);
+\end{alltt}
+Which calculates $a = R$ for the odd moduli $b$ without using multiplication or division.
+
+The normal modus operandi for Montgomery reductions is to normalize the integers before entering the system. For
+example, to calculate $a^3 \mbox { mod }b$ using Montgomery reduction the value of $a$ can be normalized by
+multiplying it by $R$. Consider the following code snippet.
+
+\begin{alltt}
+int main(void)
+\{
+ mp_int a, b, c, R;
+ mp_digit mp;
+ int result;
+
+ /* initialize a,b to desired values,
+ * mp_init R, c and set c to 1....
+ */
+
+ /* get normalization */
+ if ((result = mp_montgomery_calc_normalization(&R, b)) != MP_OKAY) \{
+ printf("Error getting norm. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* get mp value */
+ if ((result = mp_montgomery_setup(&c, &mp)) != MP_OKAY) \{
+ printf("Error setting up montgomery. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* normalize `a' so now a is equal to aR */
+ if ((result = mp_mulmod(&a, &R, &b, &a)) != MP_OKAY) \{
+ printf("Error computing aR. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* square a to get c = a^2R^2 */
+ if ((result = mp_sqr(&a, &c)) != MP_OKAY) \{
+ printf("Error squaring. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* now reduce `c' back down to c = a^2R^2 * R^-1 == a^2R */
+ if ((result = mp_montgomery_reduce(&c, &b, mp)) != MP_OKAY) \{
+ printf("Error reducing. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* multiply a to get c = a^3R^2 */
+ if ((result = mp_mul(&a, &c, &c)) != MP_OKAY) \{
+ printf("Error reducing. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* now reduce `c' back down to c = a^3R^2 * R^-1 == a^3R */
+ if ((result = mp_montgomery_reduce(&c, &b, mp)) != MP_OKAY) \{
+ printf("Error reducing. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* now reduce (again) `c' back down to c = a^3R * R^-1 == a^3 */
+ if ((result = mp_montgomery_reduce(&c, &b, mp)) != MP_OKAY) \{
+ printf("Error reducing. \%s",
+ mp_error_to_string(result));
+ return EXIT_FAILURE;
+ \}
+
+ /* c now equals a^3 mod b */
+
+ return EXIT_SUCCESS;
+\}
+\end{alltt}
+
+This particular example does not look too efficient but it demonstrates the point of the algorithm. By
+normalizing the inputs the reduced results are always of the form $aR$ for some variable $a$. This allows
+a single final reduction to correct for the normalization and the fast reduction used within the algorithm.
+
+For more details consider examining the file \textit{bn\_mp\_exptmod\_fast.c}.
+
+\section{Restricted Diminished Radix}
+
+``Diminished Radix'' reduction refers to reduction with respect to moduli that are amenable to simple
+digit shifting and small multiplications. In this case the ``restricted'' variant refers to moduli of the
+form $\beta^k - p$ for some $k \ge 0$ and $0 < p < \beta$ where $\beta$ is the radix (default to $2^{28}$).
+
+As in the case of Montgomery reduction there is a pre--computation phase required for a given modulus.
+
+\index{mp\_dr\_setup}
+\begin{alltt}
+void mp_dr_setup(mp_int *a, mp_digit *d);
+\end{alltt}
+
+This computes the value required for the modulus $a$ and stores it in $d$. This function cannot fail
+and does not return any error codes. After the pre--computation a reduction can be performed with the
+following.
+
+\index{mp\_dr\_reduce}
+\begin{alltt}
+int mp_dr_reduce(mp_int *a, mp_int *b, mp_digit mp);
+\end{alltt}
+
+This reduces $a$ in place modulo $b$ with the pre--computed value $mp$. $b$ must be of a restricted
+diminished radix form and $a$ must be in the range $0 \le a < b^2$. Diminished radix reductions are
+much faster than both Barrett and Montgomery reductions as they have a much lower asymptotic running time.
+
+Since the moduli are restricted this algorithm is not particularly useful for something like Rabin, RSA or
+BBS cryptographic purposes. This reduction algorithm is useful for Diffie-Hellman and ECC where fixed
+primes are acceptable.
+
+Note that unlike Montgomery reduction there is no normalization process. The result of this function is
+equal to the correct residue.
+
+\section{Unrestricted Diminished Radix}
+
+Unrestricted reductions work much like the restricted counterparts except in this case the moduli is of the
+form $2^k - p$ for $0 < p < \beta$. In this sense the unrestricted reductions are more flexible as they
+can be applied to a wider range of numbers.
+
+\index{mp\_reduce\_2k\_setup}
+\begin{alltt}
+int mp_reduce_2k_setup(mp_int *a, mp_digit *d);
+\end{alltt}
+
+This will compute the required $d$ value for the given moduli $a$.
+
+\index{mp\_reduce\_2k}
+\begin{alltt}
+int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d);
+\end{alltt}
+
+This will reduce $a$ in place modulo $n$ with the pre--computed value $d$. From my experience this routine is
+slower than mp\_dr\_reduce but faster for most moduli sizes than the Montgomery reduction.
+
+\section{Combined Modular Reduction}
+
+Some of the combinations of an arithmetic operations followed by a modular reduction can be done in a faster way. The ones implemented are:
+
+Addition $d = (a + b) \mod c$
+\index{mp\_addmod}
+\begin{alltt}
+int mp_addmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
+\end{alltt}
+
+Subtraction $d = (a - b) \mod c$
+\begin{alltt}
+int mp_submod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
+\end{alltt}
+
+Multiplication $d = (ab) \mod c$
+\begin{alltt}
+int mp_mulmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
+\end{alltt}
+
+Squaring $d = (a^2) \mod c$
+\begin{alltt}
+int mp_sqrmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
+\end{alltt}
+
+
+
+\chapter{Exponentiation}
+\section{Single Digit Exponentiation}
+\index{mp\_expt\_d}
+\begin{alltt}
+int mp_expt_d (mp_int * a, mp_digit b, mp_int * c)
+\end{alltt}
+This function computes $c = a^b$.
+
+\section{Modular Exponentiation}
+\index{mp\_exptmod}
+\begin{alltt}
+int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
+\end{alltt}
+This computes $Y \equiv G^X \mbox{ (mod }P\mbox{)}$ using a variable width sliding window algorithm. This function
+will automatically detect the fastest modular reduction technique to use during the operation. For negative values of
+$X$ the operation is performed as $Y \equiv (G^{-1} \mbox{ mod }P)^{\vert X \vert} \mbox{ (mod }P\mbox{)}$ provided that
+$gcd(G, P) = 1$.
+
+This function is actually a shell around the two internal exponentiation functions. This routine will automatically
+detect when Barrett, Montgomery, Restricted and Unrestricted Diminished Radix based exponentiation can be used. Generally
+moduli of the a ``restricted diminished radix'' form lead to the fastest modular exponentiations. Followed by Montgomery
+and the other two algorithms.
+
+\section{Modulus a Power of Two}
+\index{mp\_mod\_2d}
+\begin{alltt}
+int mp_mod_2d(const mp_int *a, int b, mp_int *c)
+\end{alltt}
+It calculates $c = a \mod 2^b$.
+
+\section{Root Finding}
+\index{mp\_n\_root}
+\begin{alltt}
+int mp_n_root (mp_int * a, mp_digit b, mp_int * c)
+\end{alltt}
+This computes $c = a^{1/b}$ such that $c^b \le a$ and $(c+1)^b > a$. Will return a positive root only for even roots and return
+a root with the sign of the input for odd roots. For example, performing $4^{1/2}$ will return $2$ whereas $(-8)^{1/3}$
+will return $-2$.
+
+This algorithm uses the ``Newton Approximation'' method and will converge on the correct root fairly quickly.
+
+The square root $c = a^{1/2}$ (with the same conditions $c^2 \le a$ and $(c+1)^2 > a$) is implemented with a faster algorithm.
+
+\index{mp\_sqrt}
+\begin{alltt}
+int mp_sqrt (mp_int * a, mp_digit b, mp_int * c)
+\end{alltt}
+
+
+\chapter{Logarithm}
+\section{Integer Logarithm}
+A logarithm function for positive integer input \texttt{a, base} computing $\floor{\log_bx}$ such that $(\log_b x)^b \le x$.
+\index{mp\_ilogb}
+\begin{alltt}
+int mp_ilogb(mp_int *a, mp_digit base, mp_int *c)
+\end{alltt}
+\subsection{Example}
+\begin{alltt}
+#include <stdlib.h>
+#include <stdio.h>
+#include <errno.h>
+
+#include <tommath.h>
+
+int main(int argc, char **argv)
+{
+ mp_int x, output;
+ mp_digit base;
+ int e;
+
+ if (argc != 3) {
+ fprintf(stderr,"Usage %s base x\textbackslash{}n", argv[0]);
+ exit(EXIT_FAILURE);
+ }
+ if ((e = mp_init_multi(&x, &output, NULL)) != MP_OKAY) {
+ fprintf(stderr,"mp_init failed: \textbackslash{}"%s\textbackslash{}"\textbackslash{}n",
+ mp_error_to_string(e));
+ exit(EXIT_FAILURE);
+ }
+ errno = 0;
+#ifdef MP_64BIT
+ base = (mp_digit)strtoull(argv[1], NULL, 10);
+#else
+ base = (mp_digit)strtoul(argv[1], NULL, 10);
+#endif
+ if ((errno == ERANGE) || (base > (base & MP_MASK))) {
+ fprintf(stderr,"strtoul(l) failed: input out of range\textbackslash{}n");
+ exit(EXIT_FAILURE);
+ }
+ if ((e = mp_read_radix(&x, argv[2], 10)) != MP_OKAY) {
+ fprintf(stderr,"mp_read_radix failed: \textbackslash{}"%s\textbackslash{}"\textbackslash{}n",
+ mp_error_to_string(e));
+ exit(EXIT_FAILURE);
+ }
+ if ((e = mp_ilogb(&x, base, &output)) != MP_OKAY) {
+ fprintf(stderr,"mp_ilogb failed: \textbackslash{}"%s\textbackslash{}"\textbackslash{}n",
+ mp_error_to_string(e));
+ exit(EXIT_FAILURE);
+ }
+
+ if ((e = mp_fwrite(&output, 10, stdout)) != MP_OKAY) {
+ fprintf(stderr,"mp_fwrite failed: \textbackslash{}"%s\textbackslash{}"\textbackslash{}n",
+ mp_error_to_string(e));
+ exit(EXIT_FAILURE);
+ }
+ putchar('\textbackslash{}n');
+
+ mp_clear_multi(&x, &output, NULL);
+ exit(EXIT_SUCCESS);
+}
+\end{alltt}
+
+
+
+\chapter{Prime Numbers}
+\section{Trial Division}
+\index{mp\_prime\_is\_divisible}
+\begin{alltt}
+int mp_prime_is_divisible (mp_int * a, int *result)
+\end{alltt}
+This will attempt to evenly divide $a$ by a list of primes\footnote{Default is the first 256 primes.} and store the
+outcome in ``result''. That is if $result = 0$ then $a$ is not divisible by the primes, otherwise it is. Note that
+if the function does not return \textbf{MP\_OKAY} the value in ``result'' should be considered undefined\footnote{Currently
+the default is to set it to zero first.}.
+
+\section{Fermat Test}
+\index{mp\_prime\_fermat}
+\begin{alltt}
+int mp_prime_fermat (mp_int * a, mp_int * b, int *result)
+\end{alltt}
+Performs a Fermat primality test to the base $b$. That is it computes $b^a \mbox{ mod }a$ and tests whether the value is
+equal to $b$ or not. If the values are equal then $a$ is probably prime and $result$ is set to one. Otherwise $result$
+is set to zero.
+
+\section{Miller-Rabin Test}
+\index{mp\_prime\_miller\_rabin}
+\begin{alltt}
+int mp_prime_miller_rabin (mp_int * a, mp_int * b, int *result)
+\end{alltt}
+Performs a Miller-Rabin test to the base $b$ of $a$. This test is much stronger than the Fermat test and is very hard to
+fool (besides with Carmichael numbers). If $a$ passes the test (therefore is probably prime) $result$ is set to one.
+Otherwise $result$ is set to zero.
+
+Note that is suggested that you use the Miller-Rabin test instead of the Fermat test since all of the failures of
+Miller-Rabin are a subset of the failures of the Fermat test.
+
+\subsection{Required Number of Tests}
+Generally to ensure a number is very likely to be prime you have to perform the Miller-Rabin with at least a half-dozen
+or so unique bases. However, it has been proven that the probability of failure goes down as the size of the input goes up.
+This is why a simple function has been provided to help out.
+
+\index{mp\_prime\_rabin\_miller\_trials}
+\begin{alltt}
+int mp_prime_rabin_miller_trials(int size)
+\end{alltt}
+This returns the number of trials required for a low probability of failure for a given ``size'' expressed in bits. This comes in handy specially since larger numbers are slower to test. For example, a 512-bit number would require 18 tests for a probability of $2^{-160}$ whereas a 1024-bit number would only require 12 tests for a probability of $2^{-192}$. The exact values as implemented are listed in table \ref{table:millerrabinrunsimpl}.
+
+\begin{table}[h]
+\begin{center}
+\begin{tabular}{c c c}
+\textbf{bits} & \textbf{Rounds} & \textbf{Error}\\
+ 80 & -1 & Use deterministic algorithm for size <= 80 bits \\
+ 81 & 37 & $2^{-96}$ \\
+ 96 & 32 & $2^{-96}$ \\
+ 128 & 40 & $2^{-112}$ \\
+ 160 & 35 & $2^{-112}$ \\
+ 256 & 27 & $2^{-128}$ \\
+ 384 & 16 & $2^{-128}$ \\
+ 512 & 18 & $2^{-160}$ \\
+ 768 & 11 & $2^{-160}$ \\
+ 896 & 10 & $2^{-160}$ \\
+ 1024 & 12 & $2^{-192}$ \\
+ 1536 & 8 & $2^{-192}$ \\
+ 2048 & 6 & $2^{-192}$ \\
+ 3072 & 4 & $2^{-192}$ \\
+ 4096 & 5 & $2^{-256}$ \\
+ 5120 & 4 & $2^{-256}$ \\
+ 6144 & 4 & $2^{-256}$ \\
+ 8192 & 3 & $2^{-256}$ \\
+ 9216 & 3 & $2^{-256}$ \\
+ 10240 & 2 & $2^{-256}$
+\end{tabular}
+\caption{ Number of Miller-Rabin rounds as implemented } \label{table:millerrabinrunsimpl}
+\end{center}
+\end{table}
+
+You should always still perform a trial division before a Miller-Rabin test though.
+
+A small table, broke in two for typographical reasons, with the number of rounds of Miller-Rabin tests is shown below. The numbers have been compute with a PARI/GP script listed in appendix \ref{app:numberofmrcomp}.
+The first column is the number of bits $b$ in the prime $p = 2^b$, the numbers in the first row represent the
+probability that the number that all of the Miller-Rabin tests deemed a pseudoprime is actually a composite. There is a deterministic test for numbers smaller than $2^{80}$.
+
+\begin{table}[h]
+\begin{center}
+\begin{tabular}{c c c c c c c}
+\textbf{bits} & $\mathbf{2^{-80}}$ & $\mathbf{2^{-96}}$ & $\mathbf{2^{-112}}$ & $\mathbf{2^{-128}}$ & $\mathbf{2^{-160}}$ & $\mathbf{2^{-192}}$ \\
+80 & 31 & 39 & 47 & 55 & 71 & 87 \\
+96 & 29 & 37 & 45 & 53 & 69 & 85 \\
+128 & 24 & 32 & 40 & 48 & 64 & 80 \\
+160 & 19 & 27 & 35 & 43 & 59 & 75 \\
+192 & 15 & 21 & 29 & 37 & 53 & 69 \\
+256 & 10 & 15 & 20 & 27 & 43 & 59 \\
+384 & 7 & 9 & 12 & 16 & 25 & 38 \\
+512 & 5 & 7 & 9 & 12 & 18 & 26 \\
+768 & 4 & 5 & 6 & 8 & 11 & 16 \\
+1024 & 3 & 4 & 5 & 6 & 9 & 12 \\
+1536 & 2 & 3 & 3 & 4 & 6 & 8 \\
+2048 & 2 & 2 & 3 & 3 & 4 & 6 \\
+3072 & 1 & 2 & 2 & 2 & 3 & 4 \\
+4096 & 1 & 1 & 2 & 2 & 2 & 3 \\
+6144 & 1 & 1 & 1 & 1 & 2 & 2 \\
+8192 & 1 & 1 & 1 & 1 & 2 & 2 \\
+12288 & 1 & 1 & 1 & 1 & 1 & 1 \\
+16384 & 1 & 1 & 1 & 1 & 1 & 1 \\
+24576 & 1 & 1 & 1 & 1 & 1 & 1 \\
+32768 & 1 & 1 & 1 & 1 & 1 & 1
+\end{tabular}
+\caption{ Number of Miller-Rabin rounds. Part I } \label{table:millerrabinrunsp1}
+\end{center}
+\end{table}
+\newpage
+\begin{table}[h]
+\begin{center}
+\begin{tabular}{c c c c c c c c}
+\textbf{bits} &$\mathbf{2^{-224}}$ & $\mathbf{2^{-256}}$ & $\mathbf{2^{-288}}$ & $\mathbf{2^{-320}}$ & $\mathbf{2^{-352}}$ & $\mathbf{2^{-384}}$ & $\mathbf{2^{-416}}$\\
+80 & 103 & 119 & 135 & 151 & 167 & 183 & 199 \\
+96 & 101 & 117 & 133 & 149 & 165 & 181 & 197 \\
+128 & 96 & 112 & 128 & 144 & 160 & 176 & 192 \\
+160 & 91 & 107 & 123 & 139 & 155 & 171 & 187 \\
+192 & 85 & 101 & 117 & 133 & 149 & 165 & 181 \\
+256 & 75 & 91 & 107 & 123 & 139 & 155 & 171 \\
+384 & 54 & 70 & 86 & 102 & 118 & 134 & 150 \\
+512 & 36 & 49 & 65 & 81 & 97 & 113 & 129 \\
+768 & 22 & 29 & 37 & 47 & 58 & 70 & 86 \\
+1024 & 16 & 21 & 26 & 33 & 40 & 48 & 58 \\
+1536 & 10 & 13 & 17 & 21 & 25 & 30 & 35 \\
+2048 & 8 & 10 & 13 & 15 & 18 & 22 & 26 \\
+3072 & 5 & 7 & 8 & 10 & 12 & 14 & 17 \\
+4096 & 4 & 5 & 6 & 8 & 9 & 11 & 12 \\
+6144 & 3 & 4 & 4 & 5 & 6 & 7 & 8 \\
+8192 & 2 & 3 & 3 & 4 & 5 & 6 & 6 \\
+12288 & 2 & 2 & 2 & 3 & 3 & 4 & 4 \\
+16384 & 1 & 2 & 2 & 2 & 3 & 3 & 3 \\
+24576 & 1 & 1 & 2 & 2 & 2 & 2 & 2 \\
+32768 & 1 & 1 & 1 & 1 & 2 & 2 & 2
+\end{tabular}
+\caption{ Number of Miller-Rabin rounds. Part II } \label{table:millerrabinrunsp2}
+\end{center}
+\end{table}
+
+Determining the probability needed to pick the right column is a bit harder. Fips 186.4, for example has $2^{-80}$ for $512$ bit large numbers, $2^{-112}$ for $1024$ bits, and $2^{128}$ for $1536$ bits. It can be seen in table \ref{table:millerrabinrunsp1} that those combinations follow the diagonal from $(512,2^{-80})$ downwards and to the right to gain a lower probabilty of getting a composite declared a pseudoprime for the same amount of work or less.
+
+If this version of the library has the strong Lucas-Selfridge and/or the Frobenius-Underwood test implemented only one or two rounds of the Miller-Rabin test with a random base is necesssary for numbers larger than or equal to $1024$ bits.
+
+This function is meant for RSA. The number of rounds for DSA is $\lceil -log_2(p)/2\rceil$ with $p$ the probability which is just the half of the absolute value of $p$ if given as a power of two. E.g.: with $p = 2^{-128}$, $\lceil -log_2(p)/2\rceil = 64$.
+
+This function can be used to test a DSA prime directly if these rounds are followed by a Lucas test.
+
+See also table C.1 in FIPS 186-4.
+
+\section{Strong Lucas-Selfridge Test}
+\index{mp\_prime\_strong\_lucas\_selfridge}
+\begin{alltt}
+int mp_prime_strong_lucas_selfridge(const mp_int *a, int *result)
+\end{alltt}
+Performs a strong Lucas-Selfridge test. The strong Lucas-Selfridge test together with the Rabin-Miler test with bases $2$ and $3$ resemble the BPSW test. The single internal use is a compile-time option in \texttt{mp\_prime\_is\_prime} and can be excluded
+from the Libtommath build if not needed.
+
+\section{Frobenius (Underwood) Test}
+\index{mp\_prime\_frobenius\_underwood}
+\begin{alltt}
+int mp_prime_frobenius_underwood(const mp_int *N, int *result)
+\end{alltt}
+Performs the variant of the Frobenius test as described by Paul Underwood. The single internal use is in
+\texttt{mp\_prime\_is\_prime} for \texttt{MP\_8BIT} only but can be included at build-time for all other sizes
+if the preprocessor macro \texttt{LTM\_USE\_FROBENIUS\_TEST} is defined.
+
+It returns \texttt{MP\_ITER} if the number of iterations is exhausted, assumes a composite as the input and sets \texttt{result} accordingly. This will reduce the set of available pseudoprimes by a very small amount: test with large datasets (more than $10^{10}$ numbers, both randomly chosen and sequences of odd numbers with a random start point) found only 31 (thirty-one) numbers with $a > 120$ and none at all with just an additional simple check for divisors $d < 2^8$.
+
+\section{Primality Testing}
+Testing if a number is a square can be done a bit faster than just by calculating the square root. It is used by the primality testing function described below.
+\index{mp\_is\_square}
+\begin{alltt}
+int mp_is_square(const mp_int *arg, int *ret);
+\end{alltt}
+
+
+\index{mp\_prime\_is\_prime}
+\begin{alltt}
+int mp_prime_is_prime (mp_int * a, int t, int *result)
+\end{alltt}
+This will perform a trial division followed by two rounds of Miller-Rabin with bases 2 and 3 and a Lucas-Selfridge test. The Lucas-Selfridge test is replaced with a Frobenius-Underwood for \texttt{MP\_8BIT}. The Frobenius-Underwood test for all other sizes is available as a compile-time option with the preprocessor macro \texttt{LTM\_USE\_FROBENIUS\_TEST}. See file
+\texttt{bn\_mp\_prime\_is\_prime.c} for the necessary details. It shall be noted that both functions are much slower than
+the Miller-Rabin test and if speed is an essential issue, the macro \texttt{LTM\_USE\_ONLY\_MR} switches both functions, the Frobenius-Underwood test and the Lucas-Selfridge test off and their code will not even be compiled into the library.
+
+If $t$ is set to a positive value $t$ additional rounds of the Miller-Rabin test with random bases will be performed to allow for Fips 186.4 (vid.~p.~126ff) compliance. The function \texttt{mp\_prime\_rabin\_miller\_trials} can be used to determine the number of rounds. It is vital that the function \texttt{mp\_rand()} has a cryptographically strong random number generator available.
+
+One Miller-Rabin tests with a random base will be run automatically, so by setting $t$ to a positive value this function will run $t + 1$ Miller-Rabin tests with random bases.
+
+If $t$ is set to a negative value the test will run the deterministic Miller-Rabin test for the primes up to $3317044064679887385961981$. That limit has to be checked by the caller.
+
+If $a$ passes all of the tests $result$ is set to one, otherwise it is set to zero.
+
+\section{Next Prime}
+\index{mp\_prime\_next\_prime}
+\begin{alltt}
+int mp_prime_next_prime(mp_int *a, int t, int bbs_style)
+\end{alltt}
+This finds the next prime after $a$ that passes mp\_prime\_is\_prime() with $t$ tests but see the documentation for
+mp\_prime\_is\_prime for details regarding the use of the argument $t$. Set $bbs\_style$ to one if you
+want only the next prime congruent to $3 \mbox{ mod } 4$, otherwise set it to zero to find any next prime.
+
+\section{Random Primes}
+\index{mp\_prime\_rand}
+\begin{alltt}
+int mp_prime_rand(mp_int *a, int t,
+ int size, int flags);
+\end{alltt}
+This will generate a prime in $a$ using $t$ tests of the primality testing algorithms.
+See the documentation for mp\_prime\_is\_prime for details regarding the use of the argument $t$.
+The variable $size$ specifies the bit length of the prime desired.
+The variable $flags$ specifies one of several options available
+(see fig. \ref{fig:primeopts}) which can be OR'ed together.
+
+The function mp\_prime\_rand() is suitable for generating primes which must be secret (as in the case of RSA) since there
+is no skew on the least significant bits.
+
+\textit{Note:} This function replaces the deprecated mp\_prime\_random and mp\_prime\_random\_ex functions.
+
+\begin{figure}[h]
+\begin{center}
+\begin{small}
+\begin{tabular}{|r|l|}
+\hline \textbf{Flag} & \textbf{Meaning} \\
+\hline LTM\_PRIME\_BBS & Make the prime congruent to $3$ modulo $4$ \\
+\hline LTM\_PRIME\_SAFE & Make a prime $p$ such that $(p - 1)/2$ is also prime. \\
+ & This option implies LTM\_PRIME\_BBS as well. \\
+\hline LTM\_PRIME\_2MSB\_OFF & Makes sure that the bit adjacent to the most significant bit \\
+ & Is forced to zero. \\
+\hline LTM\_PRIME\_2MSB\_ON & Makes sure that the bit adjacent to the most significant bit \\
+ & Is forced to one. \\
+\hline
+\end{tabular}
+\end{small}
+\end{center}
+\caption{Primality Generation Options}
+\label{fig:primeopts}
+\end{figure}
+
+\chapter{Random Number Generation}
+\section{PRNG}
+\index{mp\_rand\_digit}
+\begin{alltt}
+int mp_rand_digit(mp_digit *r)
+\end{alltt}
+This function generates a random number in \texttt{r} of the size given in \texttt{r} (that is, the variable is used for in- and output) but not more than \texttt{MP\_MASK} bits.
+
+\index{mp\_rand}
+\begin{alltt}
+int mp_rand(mp_int *a, int digits)
+\end{alltt}
+This function generates a random number of \texttt{digits} bits.
+
+The random number generated with these two functions is cryptographically secure if the source of random numbers the operating systems offers is cryptographically secure. It will use \texttt{arc4random()} if the OS is a BSD flavor, Wincrypt on Windows, or \texttt{/dev/urandom} on all operating systems that have it.
+
+
+\chapter{Input and Output}
+\section{ASCII Conversions}
+\subsection{To ASCII}
+\index{mp\_to\_radix}
+\begin{alltt}
+int mp_to_radix (mp_int *a, char *str, size_t maxlen, size_t *written, int radix);
+\end{alltt}
+This stores $a$ in \texttt{str} of maximum length \texttt{maxlen} as a base-\texttt{radix} string of ASCII chars and appends a \texttt{NUL} character to terminate the string.
+
+Valid values of \texttt{radix} line in the range $[2, 64]$.
+
+The exact number of characters in \texttt{str} plus the \texttt{NUL} will be put in \texttt{written} if that variable is not set to \texttt{NULL}.
+
+If \texttt{str} is not big enough to hold $a$, \texttt{str} will be filled with the least-significant digits
+of length \texttt{maxlen-1}, then \texttt{str} will be \texttt{NUL} terminated and the error \texttt{MP\_VAL} is returned.
+
+Please be aware that this function cannot evaluate the actual size of the buffer, it relies on the correctness of \texttt{maxlen}!
+
+
+\index{mp\_radix\_size}
+\begin{alltt}
+int mp_radix_size (mp_int * a, int radix, int *size)
+\end{alltt}
+This stores in ``size'' the number of characters (including space for the NUL terminator) required. Upon error this
+function returns an error code and ``size'' will be zero.
+
+If \texttt{LTM\_NO\_FILE} is not defined a function to write to a file is also available.
+\index{mp\_fwrite}
+\begin{alltt}
+int mp_fwrite(const mp_int *a, int radix, FILE *stream);
+\end{alltt}
+
+
+\subsection{From ASCII}
+\index{mp\_read\_radix}
+\begin{alltt}
+int mp_read_radix (mp_int * a, char *str, int radix);
+\end{alltt}
+This will read the base-``radix'' NUL terminated string from ``str'' into $a$. It will stop reading when it reads a
+character it does not recognize (which happens to include th NUL char... imagine that...). A single leading $-$ sign
+can be used to denote a negative number.
+
+If \texttt{LTM\_NO\_FILE} is not defined a function to read from a file is also available.
+\index{mp\_fread}
+\begin{alltt}
+int mp_fread(mp_int *a, int radix, FILE *stream);
+\end{alltt}
+
+
+\section{Binary Conversions}
+
+Converting an mp\_int to and from binary is another keen idea.
+
+\index{mp\_ubin\_size}
+\begin{alltt}
+size_t mp_ubin_size(mp_int *a);
+\end{alltt}
+
+This will return the number of bytes (octets) required to store the unsigned copy of the integer $a$.
+
+\index{mp\_to\_ubin}
+\begin{alltt}
+int mp_to_unsigned_bin(mp_int *a, unsigned char *b, size_t maxlen, size_t *len);
+\end{alltt}
+This will store $a$ into the buffer $b$ of size \texttt{maxlen} in big--endian format storing the number of bytes written in \texttt{len}. Fortunately this is exactly what DER (or is it ASN?) requires. It does not store the sign of the integer.
+
+\index{mp\_from\_ubin}
+\begin{alltt}
+int mp_from_ubin(mp_int *a, unsigned char *b, size_t size);
+\end{alltt}
+This will read in an unsigned big--endian array of bytes (octets) from $b$ of length \texttt{size} into $a$. The resulting big-integer $a$ will always be positive.
+
+For those who acknowledge the existence of negative numbers (heretic!) there are ``signed'' versions of the
+previous functions.
+\index{mp\_signed\_bin\_size} \index{mp\_to\_signed\_bin} \index{mp\_read\_signed\_bin}
+\begin{alltt}
+int mp_sbin_size(mp_int *a);
+int mp_from_sbin(mp_int *a, unsigned char *b, size_t size);
+int mp_to_sbin(mp_int *a, unsigned char *b, size_t maxsize, size_t *len);
+\end{alltt}
+They operate essentially the same as the unsigned copies except they prefix the data with zero or non--zero
+byte depending on the sign. If the sign is zpos (e.g. not negative) the prefix is zero, otherwise the prefix
+is non--zero.
+
+The two functions \texttt{mp\_unpack} (get your gifts out of the box, import binary data) and \texttt{mp\_pack} (put your gifts into the box, export binary data) implement the similarly working GMP functions as described at \url{http://gmplib.org/manual/Integer-Import-and-Export.html} with the exception that \texttt{mp\_pack} will not allocate memory if \texttt{rop} is \texttt{NULL}.
+\index{mp\_unpack} \index{mp\_pack}
+\begin{alltt}
+int mp_unpack(mp_int *rop, size_t count, mp_order order, size_t size,
+ mp_endian endian, size_t nails, const void *op, size_t maxsize);
+int mp_pack(void *rop, size_t *countp, mp_order order, size_t size,
+ mp_endian endian, size_t nails, const mp_int *op);
+\end{alltt}
+The function \texttt{mp\_pack} has the additional variable \texttt{maxsize} which must hold the size of the buffer \texttt{rop} in bytes. Use
+\begin{alltt}
+/* Parameters "nails" and "size" are the same as in mp_pack */
+size_t mp_pack_size(mp_int *a, size_t nails, size_t size);
+\end{alltt}
+To get the size in bytes necessary to be put in \texttt{maxsize}).
+
+To enhance the readability of your code, the following enums have been wrought for your convenience.
+\begin{alltt}
+typedef enum {
+ MP_LSB_FIRST = -1,
+ MP_MSB_FIRST = 1
+} mp_order;
+typedef enum {
+ MP_LITTLE_ENDIAN = -1,
+ MP_NATIVE_ENDIAN = 0,
+ MP_BIG_ENDIAN = 1
+} mp_endian;
+\end{alltt}
+
+\chapter{Algebraic Functions}
+\section{Extended Euclidean Algorithm}
+\index{mp\_exteuclid}
+\begin{alltt}
+int mp_exteuclid(mp_int *a, mp_int *b,
+ mp_int *U1, mp_int *U2, mp_int *U3);
+\end{alltt}
+
+This finds the triple U1/U2/U3 using the Extended Euclidean algorithm such that the following equation holds.
+
+\begin{equation}
+a \cdot U1 + b \cdot U2 = U3
+\end{equation}
+
+Any of the U1/U2/U3 parameters can be set to \textbf{NULL} if they are not desired.
+
+\section{Greatest Common Divisor}
+\index{mp\_gcd}
+\begin{alltt}
+int mp_gcd (mp_int * a, mp_int * b, mp_int * c)
+\end{alltt}
+This will compute the greatest common divisor of $a$ and $b$ and store it in $c$.
+
+\section{Least Common Multiple}
+\index{mp\_lcm}
+\begin{alltt}
+int mp_lcm (mp_int * a, mp_int * b, mp_int * c)
+\end{alltt}
+This will compute the least common multiple of $a$ and $b$ and store it in $c$.
+
+\section{Jacobi Symbol}
+\index{mp\_jacobi}
+\begin{alltt}
+int mp_jacobi (mp_int * a, mp_int * p, int *c)
+\end{alltt}
+This will compute the Jacobi symbol for $a$ with respect to $p$. If $p$ is prime this essentially computes the Legendre
+symbol. The result is stored in $c$ and can take on one of three values $\lbrace -1, 0, 1 \rbrace$. If $p$ is prime
+then the result will be $-1$ when $a$ is not a quadratic residue modulo $p$. The result will be $0$ if $a$ divides $p$
+and the result will be $1$ if $a$ is a quadratic residue modulo $p$.
+
+\section{Kronecker Symbol}
+\index{mp\_kronecker}
+\begin{alltt}
+int mp_kronecker (mp_int * a, mp_int * p, int *c)
+\end{alltt}
+Extension of the Jacoby symbol to all $\lbrace a, p \rbrace \in \mathbb{Z}$ .
+
+
+\section{Modular square root}
+\index{mp\_sqrtmod\_prime}
+\begin{alltt}
+int mp_sqrtmod_prime(mp_int *n, mp_int *p, mp_int *r)
+\end{alltt}
+
+This will solve the modular equatioon $r^2 = n \mod p$ where $p$ is a prime number greater than 2 (odd prime).
+The result is returned in the third argument $r$, the function returns \textbf{MP\_OKAY} on success,
+other return values indicate failure.
+
+The implementation is split for two different cases:
+
+1. if $p \mod 4 == 3$ we apply \href{http://cacr.uwaterloo.ca/hac/}{Handbook of Applied Cryptography algorithm 3.36} and compute $r$ directly as
+$r = n^{(p+1)/4} \mod p$
+
+2. otherwise we use \href{https://en.wikipedia.org/wiki/Tonelli-Shanks_algorithm}{Tonelli-Shanks algorithm}
+
+The function does not check the primality of parameter $p$ thus it is up to the caller to assure that this parameter
+is a prime number. When $p$ is a composite the function behaviour is undefined, it may even return a false-positive
+\textbf{MP\_OKAY}.
+
+\section{Modular Inverse}
+\index{mp\_invmod}
+\begin{alltt}
+int mp_invmod (mp_int * a, mp_int * b, mp_int * c)
+\end{alltt}
+Computes the multiplicative inverse of $a$ modulo $b$ and stores the result in $c$ such that $ac \equiv 1 \mbox{ (mod }b\mbox{)}$.
+
+\section{Single Digit Functions}
+
+For those using small numbers (\textit{snicker snicker}) there are several ``helper'' functions
+
+\index{mp\_add\_d} \index{mp\_sub\_d} \index{mp\_mul\_d} \index{mp\_div\_d} \index{mp\_mod\_d}
+\begin{alltt}
+int mp_add_d(mp_int *a, mp_digit b, mp_int *c);
+int mp_sub_d(mp_int *a, mp_digit b, mp_int *c);
+int mp_mul_d(mp_int *a, mp_digit b, mp_int *c);
+int mp_div_d(mp_int *a, mp_digit b, mp_int *c, mp_digit *d);
+int mp_mod_d(mp_int *a, mp_digit b, mp_digit *c);
+\end{alltt}
+
+These work like the full mp\_int capable variants except the second parameter $b$ is a mp\_digit. These
+functions fairly handy if you have to work with relatively small numbers since you will not have to allocate
+an entire mp\_int to store a number like $1$ or $2$.
+
+The functions \texttt{mp\_incr} and \texttt{mp\_decr} mimic the postfix operators \texttt{++} and \texttt{--} respectively, to increment the input by one. They call the full single-digit functions if the addition would carry. Both functions need to be included in a minimized library because they call each other in case of a negative input, These functions change the inputs!
+\begin{alltt}
+int mp_incr(mp_int *a);
+int mp_decr(mp_int *a);
+\end{alltt}
+
+
+The division by three can be made faster by replacing the division with a multiplication by the multiplicative inverse of three.
+
+\index{mp\_div\_3}
+\begin{alltt}
+int mp_div_3(const mp_int *a, mp_int *c, mp_digit *d);
+\end{alltt}
+
+\chapter{Little Helpers}
+It is never wrong to have some useful little shortcuts at hand.
+\section{Function Macros}
+To make this overview simpler the macros are given as function prototypes. The return of logic macros is \texttt{MP\_NO} or \texttt{MP\_YES} respectively.
+
+\index{mp\_iseven}
+\begin{alltt}
+int mp_iseven(mp_int *a)
+\end{alltt}
+Checks if $a = 0 mod 2$
+
+\index{mp\_isodd}
+\begin{alltt}
+int mp_isodd(mp_int *a)
+\end{alltt}
+Checks if $a = 1 mod 2$
+
+\index{mp\_isneg}
+\begin{alltt}
+int mp_isneg(mp_int *a)
+\end{alltt}
+Checks if $a < 0$
+
+
+\index{mp\_iszero}
+\begin{alltt}
+int mp_iszero(mp_int *a)
+\end{alltt}
+Checks if $a = 0$. It does not check if the amount of memory allocated for $a$ is also minimal.
+
+
+Other macros which are either shortcuts to normal functions or just other names for them do have their place in a programmer's life, too!
+
+\subsection{Renamings}
+\index{mp\_mag\_size}
+\begin{alltt}
+#define mp_mag_size(mp) mp_unsigned_bin_size(mp)
+\end{alltt}
+
+
+\index{mp\_raw\_size}
+\begin{alltt}
+#define mp_raw_size(mp) mp_signed_bin_size(mp)
+\end{alltt}
+
+
+\index{mp\_read\_mag}
+\begin{alltt}
+#define mp_read_mag(mp, str, len) mp_read_unsigned_bin((mp), (str), (len))
+\end{alltt}
+
+
+\index{mp\_read\_raw}
+\begin{alltt}
+ #define mp_read_raw(mp, str, len) mp_read_signed_bin((mp), (str), (len))
+\end{alltt}
+
+
+\index{mp\_tomag}
+\begin{alltt}
+#define mp_tomag(mp, str) mp_to_unsigned_bin((mp), (str))
+\end{alltt}
+
+
+\index{mp\_toraw}
+\begin{alltt}
+#define mp_toraw(mp, str) mp_to_signed_bin((mp), (str))
+\end{alltt}
+
+
+
+\subsection{Shortcuts}
+
+\index{mp\_to\_binary}
+\begin{alltt}
+#define mp_to_binary(M, S, N) mp_to_radix((M), (S), (N), 2)
+\end{alltt}
+
+
+\index{mp\_to\_octal}
+\begin{alltt}
+#define mp_to_octal(M, S, N) mp_to_radix((M), (S), (N), 8)
+\end{alltt}
+
+
+\index{mp\_to\_decimal}
+\begin{alltt}
+#define mp_to_decimal(M, S, N) mp_to_radix((M), (S), (N), 10)
+\end{alltt}
+
+
+\index{mp\_to\_hex}
+\begin{alltt}
+#define mp_to_hex(M, S, N) mp_to_radix((M), (S), (N), 16)
+\end{alltt}
+
+\begin{appendices}
+\appendixpage
+%\noappendicestocpagenum
+\addappheadtotoc
+\chapter{Computing Number of Miller-Rabin Trials}\label{app:numberofmrcomp}
+The number of Miller-Rabin rounds in the tables \ref{millerrabinrunsimpl}, \ref{millerrabinrunsp1}, and \ref{millerrabinrunsp2} have been calculated with the formula in FIPS 186-4 appendix F.1 (page 117) implemented as a PARI/GP script.
+\begin{alltt}
+log2(x) = log(x)/log(2)
+
+fips_f1_sums(k, M, t) = {
+ local(s = 0);
+ s = sum(m=3,M,
+ 2^(m-t*(m-1)) *
+ sum(j=2,m,
+ 1/ ( 2^( j + (k-1)/j ) )
+ )
+ );
+ return(s);
+}
+
+fips_f1_2(k, t, M) = {
+ local(common_factor, t1, t2, f1, f2, ds, res);
+
+ common_factor = 2.00743 * log(2) * k * 2^(-k);
+ t1 = 2^(k - 2 - M*t);
+ f1 = (8 * ((Pi^2) - 6))/3;
+ f2 = 2^(k - 2);
+ ds = t1 + f1 * f2 * fips_f1_sums(k, M, t);
+ res = common_factor * ds;
+ return(res);
+}
+
+fips_f1_1(prime_length, ptarget)={
+ local(t, t_end, M, M_end, pkt);
+
+ t_end = ceil(-log2(ptarget)/2);
+ M_end = floor(2 * sqrt(prime_length-1) - 1);
+
+ for(t = 1, t_end,
+ for(M = 3, M_end,
+ pkt = fips_f1_2(prime_length, t, M);
+ if(pkt <= ptarget,
+ return(t);
+ );
+ );
+ );
+}
+\end{alltt}
+
+To get the number of rounds for a $1024$ bit large prime with a probability of $2^{-160}$:
+\begin{alltt}
+? fips_f1_1(1024,2^(-160))
+%1 = 9
+\end{alltt}
+\end{appendices}
+\input{bn.ind}
+
+\end{document}
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/2kprime.1 b/third_party/heimdal/lib/hcrypto/libtommath/etc/2kprime.1
new file mode 100644
index 0000000..c41ded1
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/2kprime.1
@@ -0,0 +1,2 @@
+256-bits (k = 36113) = 115792089237316195423570985008687907853269984665640564039457584007913129603823
+512-bits (k = 38117) = 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006045979
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/2kprime.c b/third_party/heimdal/lib/hcrypto/libtommath/etc/2kprime.c
new file mode 100644
index 0000000..95ed2de
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/2kprime.c
@@ -0,0 +1,81 @@
+/* Makes safe primes of a 2k nature */
+#include <tommath.h>
+#include <time.h>
+
+static int sizes[] = {256, 512, 768, 1024, 1536, 2048, 3072, 4096};
+
+int main(void)
+{
+ char buf[2000];
+ size_t x;
+ mp_bool y;
+ mp_int q, p;
+ FILE *out;
+ clock_t t1;
+ mp_digit z;
+
+ mp_init_multi(&q, &p, NULL);
+
+ out = fopen("2kprime.1", "w");
+ if (out != NULL) {
+ for (x = 0; x < (sizeof(sizes) / sizeof(sizes[0])); x++) {
+top:
+ mp_2expt(&q, sizes[x]);
+ mp_add_d(&q, 3uL, &q);
+ z = -3;
+
+ t1 = clock();
+ for (;;) {
+ mp_sub_d(&q, 4uL, &q);
+ z += 4uL;
+
+ if (z > MP_MASK) {
+ printf("No primes of size %d found\n", sizes[x]);
+ break;
+ }
+
+ if ((clock() - t1) > CLOCKS_PER_SEC) {
+ printf(".");
+ fflush(stdout);
+ /* sleep((clock() - t1 + CLOCKS_PER_SEC/2)/CLOCKS_PER_SEC); */
+ t1 = clock();
+ }
+
+ /* quick test on q */
+ mp_prime_is_prime(&q, 1, &y);
+ if (y == MP_NO) {
+ continue;
+ }
+
+ /* find (q-1)/2 */
+ mp_sub_d(&q, 1uL, &p);
+ mp_div_2(&p, &p);
+ mp_prime_is_prime(&p, 3, &y);
+ if (y == MP_NO) {
+ continue;
+ }
+
+ /* test on q */
+ mp_prime_is_prime(&q, 3, &y);
+ if (y == MP_NO) {
+ continue;
+ }
+
+ break;
+ }
+
+ if (y == MP_NO) {
+ ++sizes[x];
+ goto top;
+ }
+
+ mp_to_decimal(&q, buf, sizeof(buf));
+ printf("\n\n%d-bits (k = %lu) = %s\n", sizes[x], z, buf);
+ fprintf(out, "%d-bits (k = %lu) = %s\n", sizes[x], z, buf);
+ fflush(out);
+ }
+ fclose(out);
+ }
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/drprime.c b/third_party/heimdal/lib/hcrypto/libtommath/etc/drprime.c
new file mode 100644
index 0000000..64e31ef
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/drprime.c
@@ -0,0 +1,67 @@
+/* Makes safe primes of a DR nature */
+#include <tommath.h>
+
+static int sizes[] = { 1+256/MP_DIGIT_BIT, 1+512/MP_DIGIT_BIT, 1+768/MP_DIGIT_BIT, 1+1024/MP_DIGIT_BIT, 1+2048/MP_DIGIT_BIT, 1+4096/MP_DIGIT_BIT };
+
+int main(void)
+{
+ mp_bool res;
+ int x, y;
+ char buf[4096];
+ FILE *out;
+ mp_int a, b;
+
+ mp_init(&a);
+ mp_init(&b);
+
+ out = fopen("drprimes.txt", "w");
+ if (out != NULL) {
+ for (x = 0; x < (int)(sizeof(sizes)/sizeof(sizes[0])); x++) {
+top:
+ printf("Seeking a %d-bit safe prime\n", sizes[x] * MP_DIGIT_BIT);
+ mp_grow(&a, sizes[x]);
+ mp_zero(&a);
+ for (y = 1; y < sizes[x]; y++) {
+ a.dp[y] = MP_MASK;
+ }
+
+ /* make a DR modulus */
+ a.dp[0] = -1;
+ a.used = sizes[x];
+
+ /* now loop */
+ res = MP_NO;
+ for (;;) {
+ a.dp[0] += 4uL;
+ if (a.dp[0] >= MP_MASK) break;
+ mp_prime_is_prime(&a, 1, &res);
+ if (res == MP_NO) continue;
+ printf(".");
+ fflush(stdout);
+ mp_sub_d(&a, 1uL, &b);
+ mp_div_2(&b, &b);
+ mp_prime_is_prime(&b, 3, &res);
+ if (res == MP_NO) continue;
+ mp_prime_is_prime(&a, 3, &res);
+ if (res == MP_YES) break;
+ }
+
+ if (res != MP_YES) {
+ printf("Error not DR modulus\n");
+ sizes[x] += 1;
+ goto top;
+ } else {
+ mp_to_decimal(&a, buf, sizeof(buf));
+ printf("\n\np == %s\n\n", buf);
+ fprintf(out, "%d-bit prime:\np == %s\n\n", mp_count_bits(&a), buf);
+ fflush(out);
+ }
+ }
+ fclose(out);
+ }
+
+ mp_clear(&a);
+ mp_clear(&b);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/drprimes.28 b/third_party/heimdal/lib/hcrypto/libtommath/etc/drprimes.28
new file mode 100644
index 0000000..9d438ad
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/drprimes.28
@@ -0,0 +1,25 @@
+DR safe primes for 28-bit digits.
+
+224-bit prime:
+p == 26959946667150639794667015087019630673637144422540572481103341844143
+
+532-bit prime:
+p == 14059105607947488696282932836518693308967803494693489478439861164411992439598399594747002144074658928593502845729752797260025831423419686528151609940203368691747
+
+784-bit prime:
+p == 101745825697019260773923519755878567461315282017759829107608914364075275235254395622580447400994175578963163918967182013639660669771108475957692810857098847138903161308502419410142185759152435680068435915159402496058513611411688900243039
+
+1036-bit prime:
+p == 736335108039604595805923406147184530889923370574768772191969612422073040099331944991573923112581267542507986451953227192970402893063850485730703075899286013451337291468249027691733891486704001513279827771740183629161065194874727962517148100775228363421083691764065477590823919364012917984605619526140821798437127
+
+1540-bit prime:
+p == 38564998830736521417281865696453025806593491967131023221754800625044118265468851210705360385717536794615180260494208076605798671660719333199513807806252394423283413430106003596332513246682903994829528690198205120921557533726473585751382193953592127439965050261476810842071573684505878854588706623484573925925903505747545471088867712185004135201289273405614415899438276535626346098904241020877974002916168099951885406379295536200413493190419727789712076165162175783
+
+2072-bit prime:
+p == 542189391331696172661670440619180536749994166415993334151601745392193484590296600979602378676624808129613777993466242203025054573692562689251250471628358318743978285860720148446448885701001277560572526947619392551574490839286458454994488665744991822837769918095117129546414124448777033941223565831420390846864429504774477949153794689948747680362212954278693335653935890352619041936727463717926744868338358149568368643403037768649616778526013610493696186055899318268339432671541328195724261329606699831016666359440874843103020666106568222401047720269951530296879490444224546654729111504346660859907296364097126834834235287147
+
+3080-bit prime:
+p == 1487259134814709264092032648525971038895865645148901180585340454985524155135260217788758027400478312256339496385275012465661575576202252063145698732079880294664220579764848767704076761853197216563262660046602703973050798218246170835962005598561669706844469447435461092542265792444947706769615695252256130901271870341005768912974433684521436211263358097522726462083917939091760026658925757076733484173202927141441492573799914240222628795405623953109131594523623353044898339481494120112723445689647986475279242446083151413667587008191682564376412347964146113898565886683139407005941383669325997475076910488086663256335689181157957571445067490187939553165903773554290260531009121879044170766615232300936675369451260747671432073394867530820527479172464106442450727640226503746586340279816318821395210726268291535648506190714616083163403189943334431056876038286530365757187367147446004855912033137386225053275419626102417236133948503
+
+4116-bit prime:
+p == 1095121115716677802856811290392395128588168592409109494900178008967955253005183831872715423151551999734857184538199864469605657805519106717529655044054833197687459782636297255219742994736751541815269727940751860670268774903340296040006114013971309257028332849679096824800250742691718610670812374272414086863715763724622797509437062518082383056050144624962776302147890521249477060215148275163688301275847155316042279405557632639366066847442861422164832655874655824221577849928863023018366835675399949740429332468186340518172487073360822220449055340582568461568645259954873303616953776393853174845132081121976327462740354930744487429617202585015510744298530101547706821590188733515880733527449780963163909830077616357506845523215289297624086914545378511082534229620116563260168494523906566709418166011112754529766183554579321224940951177394088465596712620076240067370589036924024728375076210477267488679008016579588696191194060127319035195370137160936882402244399699172017835144537488486396906144217720028992863941288217185353914991583400421682751000603596655790990815525126154394344641336397793791497068253936771017031980867706707490224041075826337383538651825493679503771934836094655802776331664261631740148281763487765852746577808019633679
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/drprimes.txt b/third_party/heimdal/lib/hcrypto/libtommath/etc/drprimes.txt
new file mode 100644
index 0000000..7c97f67
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/drprimes.txt
@@ -0,0 +1,9 @@
+300-bit prime:
+p == 2037035976334486086268445688409378161051468393665936250636140449354381298610415201576637819
+
+540-bit prime:
+p == 3599131035634557106248430806148785487095757694641533306480604458089470064537190296255232548883112685719936728506816716098566612844395439751206810991770626477344739
+
+780-bit prime:
+p == 6359114106063703798370219984742410466332205126109989319225557147754704702203399726411277962562135973685197744935448875852478791860694279747355800678568677946181447581781401213133886609947027230004277244697462656003655947791725966271167
+
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/makefile b/third_party/heimdal/lib/hcrypto/libtommath/etc/makefile
new file mode 100644
index 0000000..85bb09e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/makefile
@@ -0,0 +1,44 @@
+LTM_CFLAGS += -Wall -W -Wextra -Wshadow -O3 -I../
+LTM_CFLAGS += $(CFLAGS)
+
+# default lib name (requires install with root)
+# LIBNAME=-ltommath
+
+# libname when you can't install the lib with install
+LIBNAME=../libtommath.a
+
+#provable primes
+pprime: pprime.o
+ $(CC) $(LTM_CFLAGS) pprime.o $(LIBNAME) -o pprime
+
+# portable [well requires clock()] tuning app
+tune: tune.o
+ $(CC) $(LTM_CFLAGS) tune.o $(LIBNAME) -o tune
+ ./tune_it.sh
+
+test_standalone: tune.o
+ # The benchmark program works as a testtool, too
+ $(CC) $(LTM_CFLAGS) tune.o $(LIBNAME) -o test
+
+# spits out mersenne primes
+mersenne: mersenne.o
+ $(CC) $(LTM_CFLAGS) mersenne.o $(LIBNAME) -o mersenne
+
+# finds DR safe primes for the given config
+drprime: drprime.o
+ $(CC) $(LTM_CFLAGS) drprime.o $(LIBNAME) -o drprime
+
+# finds 2k safe primes for the given config
+2kprime: 2kprime.o
+ $(CC) $(LTM_CFLAGS) 2kprime.o $(LIBNAME) -o 2kprime
+
+mont: mont.o
+ $(CC) $(LTM_CFLAGS) mont.o $(LIBNAME) -o mont
+
+
+clean:
+ rm -f *.log *.o *.obj *.exe pprime tune mersenne drprime mont 2kprime pprime.dat \
+ tuning_list multiplying squaring test *.da *.dyn *.dpi *~
+ rm -rf .libs
+
+.PHONY: tune
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/makefile.icc b/third_party/heimdal/lib/hcrypto/libtommath/etc/makefile.icc
new file mode 100644
index 0000000..9217f7b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/makefile.icc
@@ -0,0 +1,67 @@
+CC = icc
+
+CFLAGS += -I../
+
+# optimize for SPEED
+#
+# -mcpu= can be pentium, pentiumpro (covers PII through PIII) or pentium4
+# -ax? specifies make code specifically for ? but compatible with IA-32
+# -x? specifies compile solely for ? [not specifically IA-32 compatible]
+#
+# where ? is
+# K - PIII
+# W - first P4 [Williamette]
+# N - P4 Northwood
+# P - P4 Prescott
+# B - Blend of P4 and PM [mobile]
+#
+# Default to just generic max opts
+CFLAGS += -O3 -xP -ip
+
+# default lib name (requires install with root)
+# LIBNAME=-ltommath
+
+# libname when you can't install the lib with install
+LIBNAME=../libtommath.a
+
+#provable primes
+pprime: pprime.o
+ $(CC) pprime.o $(LIBNAME) -o pprime
+
+tune: tune.o
+ $(CC) $(CFLAGS) tune.o $(LIBNAME) -o tune
+ ./tune_it.sh
+
+# same app but using RDTSC for higher precision [requires 80586+], coff based gcc installs [e.g. ming, cygwin, djgpp]
+tune86: tune.c
+ nasm -f coff timer.asm
+ $(CC) -DX86_TIMER $(CFLAGS) tune.c timer.o $(LIBNAME) -o tune86
+
+# for cygwin
+tune86c: tune.c
+ nasm -f gnuwin32 timer.asm
+ $(CC) -DX86_TIMER $(CFLAGS) tune.c timer.o $(LIBNAME) -o tune86
+
+#make tune86 for linux or any ELF format
+tune86l: tune.c
+ nasm -f elf -DUSE_ELF timer.asm
+ $(CC) -DX86_TIMER $(CFLAGS) tune.c timer.o $(LIBNAME) -o tune86l
+
+# spits out mersenne primes
+mersenne: mersenne.o
+ $(CC) mersenne.o $(LIBNAME) -o mersenne
+
+# fines DR safe primes for the given config
+drprime: drprime.o
+ $(CC) drprime.o $(LIBNAME) -o drprime
+
+# fines 2k safe primes for the given config
+2kprime: 2kprime.o
+ $(CC) 2kprime.o $(LIBNAME) -o 2kprime
+
+mont: mont.o
+ $(CC) mont.o $(LIBNAME) -o mont
+
+
+clean:
+ rm -f *.log *.o *.obj *.exe pprime tune mersenne drprime tune86 tune86l mont 2kprime pprime.dat *.il tuning_list
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/makefile.msvc b/third_party/heimdal/lib/hcrypto/libtommath/etc/makefile.msvc
new file mode 100644
index 0000000..592a437
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/makefile.msvc
@@ -0,0 +1,24 @@
+#MSVC Makefile
+#
+#Tom St Denis
+
+CFLAGS = /I../ /Ox /DWIN32 /W3
+
+pprime: pprime.obj
+ cl pprime.obj ../tommath.lib
+
+mersenne: mersenne.obj
+ cl mersenne.obj ../tommath.lib
+
+tune: tune.obj
+ cl tune.obj ../tommath.lib
+
+
+mont: mont.obj
+ cl mont.obj ../tommath.lib
+
+drprime: drprime.obj
+ cl drprime.obj ../tommath.lib
+
+2kprime: 2kprime.obj
+ cl 2kprime.obj ../tommath.lib
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/mersenne.c b/third_party/heimdal/lib/hcrypto/libtommath/etc/mersenne.c
new file mode 100644
index 0000000..0c9f52f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/mersenne.c
@@ -0,0 +1,138 @@
+/* Finds Mersenne primes using the Lucas-Lehmer test
+ *
+ * Tom St Denis, tomstdenis@gmail.com
+ */
+#include <time.h>
+#include <tommath.h>
+
+static mp_err is_mersenne(long s, mp_bool *pp)
+{
+ mp_int n, u;
+ mp_err res;
+ int k;
+
+ *pp = MP_NO;
+
+ if ((res = mp_init(&n)) != MP_OKAY) {
+ return res;
+ }
+
+ if ((res = mp_init(&u)) != MP_OKAY) {
+ goto LBL_N;
+ }
+
+ /* n = 2^s - 1 */
+ if ((res = mp_2expt(&n, (int)s)) != MP_OKAY) {
+ goto LBL_MU;
+ }
+ if ((res = mp_sub_d(&n, 1uL, &n)) != MP_OKAY) {
+ goto LBL_MU;
+ }
+
+ /* set u=4 */
+ mp_set(&u, 4uL);
+
+ /* for k=1 to s-2 do */
+ for (k = 1; k <= (s - 2); k++) {
+ /* u = u^2 - 2 mod n */
+ if ((res = mp_sqr(&u, &u)) != MP_OKAY) {
+ goto LBL_MU;
+ }
+ if ((res = mp_sub_d(&u, 2uL, &u)) != MP_OKAY) {
+ goto LBL_MU;
+ }
+
+ /* make sure u is positive */
+ while (u.sign == MP_NEG) {
+ if ((res = mp_add(&u, &n, &u)) != MP_OKAY) {
+ goto LBL_MU;
+ }
+ }
+
+ /* reduce */
+ if ((res = mp_reduce_2k(&u, &n, 1uL)) != MP_OKAY) {
+ goto LBL_MU;
+ }
+ }
+
+ /* if u == 0 then its prime */
+ if (mp_iszero(&u) == MP_YES) {
+ mp_prime_is_prime(&n, 8, pp);
+ if (*pp != MP_YES) printf("FAILURE\n");
+ }
+
+ res = MP_OKAY;
+LBL_MU:
+ mp_clear(&u);
+LBL_N:
+ mp_clear(&n);
+ return res;
+}
+
+/* square root of a long < 65536 */
+static long i_sqrt(long x)
+{
+ long x1, x2;
+
+ x2 = 16;
+ do {
+ x1 = x2;
+ x2 = x1 - ((x1 * x1) - x) / (2 * x1);
+ } while (x1 != x2);
+
+ if ((x1 * x1) > x) {
+ --x1;
+ }
+
+ return x1;
+}
+
+/* is the long prime by brute force */
+static int isprime(long k)
+{
+ long y, z;
+
+ y = i_sqrt(k);
+ for (z = 2; z <= y; z++) {
+ if ((k % z) == 0)
+ return 0;
+ }
+ return 1;
+}
+
+
+int main(void)
+{
+ mp_bool pp;
+ long k;
+ clock_t tt;
+
+ k = 3;
+
+ for (;;) {
+ /* start time */
+ tt = clock();
+
+ /* test if 2^k - 1 is prime */
+ if (is_mersenne(k, &pp) != MP_OKAY) {
+ printf("Whoa error\n");
+ return -1;
+ }
+
+ if (pp == MP_YES) {
+ /* count time */
+ tt = clock() - tt;
+
+ /* display if prime */
+ printf("2^%-5ld - 1 is prime, test took %ld ticks\n", k, (long)tt);
+ }
+
+ /* goto next odd exponent */
+ k += 2;
+
+ /* but make sure its prime */
+ while (isprime(k) == 0) {
+ k += 2;
+ }
+ }
+}
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/mont.c b/third_party/heimdal/lib/hcrypto/libtommath/etc/mont.c
new file mode 100644
index 0000000..4652410
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/mont.c
@@ -0,0 +1,44 @@
+/* tests the montgomery routines */
+#include <tommath.h>
+#include <stdlib.h>
+#include <time.h>
+
+int main(void)
+{
+ mp_int modulus, R, p, pp;
+ mp_digit mp;
+ int x, y;
+
+ srand(time(NULL));
+ mp_init_multi(&modulus, &R, &p, &pp, NULL);
+
+ /* loop through various sizes */
+ for (x = 4; x < 256; x++) {
+ printf("DIGITS == %3d...", x);
+ fflush(stdout);
+
+ /* make up the odd modulus */
+ mp_rand(&modulus, x);
+ modulus.dp[0] |= 1uL;
+
+ /* now find the R value */
+ mp_montgomery_calc_normalization(&R, &modulus);
+ mp_montgomery_setup(&modulus, &mp);
+
+ /* now run through a bunch tests */
+ for (y = 0; y < 1000; y++) {
+ mp_rand(&p, x/2); /* p = random */
+ mp_mul(&p, &R, &pp); /* pp = R * p */
+ mp_montgomery_reduce(&pp, &modulus, mp);
+
+ /* should be equal to p */
+ if (mp_cmp(&pp, &p) != MP_EQ) {
+ printf("FAILURE!\n");
+ exit(-1);
+ }
+ }
+ printf("PASSED\n");
+ }
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/pprime.c b/third_party/heimdal/lib/hcrypto/libtommath/etc/pprime.c
new file mode 100644
index 0000000..009a18c
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/pprime.c
@@ -0,0 +1,411 @@
+/* Generates provable primes
+ *
+ * See http://gmail.com:8080/papers/pp.pdf for more info.
+ *
+ * Tom St Denis, tomstdenis@gmail.com, http://tom.gmail.com
+ */
+#include <stdlib.h>
+#include <time.h>
+#include "tommath.h"
+
+static int n_prime;
+static FILE *primes;
+
+/* fast square root */
+static mp_digit i_sqrt(mp_word x)
+{
+ mp_word x1, x2;
+
+ x2 = x;
+ do {
+ x1 = x2;
+ x2 = x1 - ((x1 * x1) - x) / (2u * x1);
+ } while (x1 != x2);
+
+ if ((x1 * x1) > x) {
+ --x1;
+ }
+
+ return x1;
+}
+
+
+/* generates a prime digit */
+static void gen_prime(void)
+{
+ mp_digit r, x, y, next;
+ FILE *out;
+
+ out = fopen("pprime.dat", "wb");
+ if (out != NULL) {
+
+ /* write first set of primes */
+ /* *INDENT-OFF* */
+ r = 3uL; fwrite(&r, 1uL, sizeof(mp_digit), out);
+ r = 5uL; fwrite(&r, 1uL, sizeof(mp_digit), out);
+ r = 7uL; fwrite(&r, 1uL, sizeof(mp_digit), out);
+ r = 11uL; fwrite(&r, 1uL, sizeof(mp_digit), out);
+ r = 13uL; fwrite(&r, 1uL, sizeof(mp_digit), out);
+ r = 17uL; fwrite(&r, 1uL, sizeof(mp_digit), out);
+ r = 19uL; fwrite(&r, 1uL, sizeof(mp_digit), out);
+ r = 23uL; fwrite(&r, 1uL, sizeof(mp_digit), out);
+ r = 29uL; fwrite(&r, 1uL, sizeof(mp_digit), out);
+ r = 31uL; fwrite(&r, 1uL, sizeof(mp_digit), out);
+ /* *INDENT-ON* */
+
+ /* get square root, since if 'r' is composite its factors must be < than this */
+ y = i_sqrt(r);
+ next = (y + 1uL) * (y + 1uL);
+
+ for (;;) {
+ do {
+ r += 2uL; /* next candidate */
+ r &= MP_MASK;
+ if (r < 31uL) break;
+
+ /* update sqrt ? */
+ if (next <= r) {
+ ++y;
+ next = (y + 1uL) * (y + 1uL);
+ }
+
+ /* loop if divisible by 3,5,7,11,13,17,19,23,29 */
+ if ((r % 3uL) == 0uL) {
+ x = 0uL;
+ continue;
+ }
+ if ((r % 5uL) == 0uL) {
+ x = 0uL;
+ continue;
+ }
+ if ((r % 7uL) == 0uL) {
+ x = 0uL;
+ continue;
+ }
+ if ((r % 11uL) == 0uL) {
+ x = 0uL;
+ continue;
+ }
+ if ((r % 13uL) == 0uL) {
+ x = 0uL;
+ continue;
+ }
+ if ((r % 17uL) == 0uL) {
+ x = 0uL;
+ continue;
+ }
+ if ((r % 19uL) == 0uL) {
+ x = 0uL;
+ continue;
+ }
+ if ((r % 23uL) == 0uL) {
+ x = 0uL;
+ continue;
+ }
+ if ((r % 29uL) == 0uL) {
+ x = 0uL;
+ continue;
+ }
+
+ /* now check if r is divisible by x + k={1,7,11,13,17,19,23,29} */
+ for (x = 30uL; x <= y; x += 30uL) {
+ if ((r % (x + 1uL)) == 0uL) {
+ x = 0uL;
+ break;
+ }
+ if ((r % (x + 7uL)) == 0uL) {
+ x = 0uL;
+ break;
+ }
+ if ((r % (x + 11uL)) == 0uL) {
+ x = 0uL;
+ break;
+ }
+ if ((r % (x + 13uL)) == 0uL) {
+ x = 0uL;
+ break;
+ }
+ if ((r % (x + 17uL)) == 0uL) {
+ x = 0uL;
+ break;
+ }
+ if ((r % (x + 19uL)) == 0uL) {
+ x = 0uL;
+ break;
+ }
+ if ((r % (x + 23uL)) == 0uL) {
+ x = 0uL;
+ break;
+ }
+ if ((r % (x + 29uL)) == 0uL) {
+ x = 0uL;
+ break;
+ }
+ }
+ } while (x == 0uL);
+ if (r > 31uL) {
+ fwrite(&r, 1uL, sizeof(mp_digit), out);
+ printf("%9lu\r", r);
+ fflush(stdout);
+ }
+ if (r < 31uL) break;
+ }
+
+ fclose(out);
+ }
+}
+
+static void load_tab(void)
+{
+ primes = fopen("pprime.dat", "rb");
+ if (primes == NULL) {
+ gen_prime();
+ primes = fopen("pprime.dat", "rb");
+ }
+ fseek(primes, 0L, SEEK_END);
+ n_prime = ftell(primes) / sizeof(mp_digit);
+}
+
+static mp_digit prime_digit(void)
+{
+ int n;
+ mp_digit d;
+
+ n = abs(rand()) % n_prime;
+ fseek(primes, n * sizeof(mp_digit), SEEK_SET);
+ fread(&d, 1uL, sizeof(mp_digit), primes);
+ return d;
+}
+
+
+/* makes a prime of at least k bits */
+static mp_err pprime(int k, int li, mp_int *p, mp_int *q)
+{
+ mp_int a, b, c, n, x, y, z, v;
+ mp_err res;
+ int ii;
+ static const mp_digit bases[] = { 2, 3, 5, 7, 11, 13, 17, 19 };
+
+ /* single digit ? */
+ if (k <= (int) MP_DIGIT_BIT) {
+ mp_set(p, prime_digit());
+ return MP_OKAY;
+ }
+
+ if ((res = mp_init(&c)) != MP_OKAY) {
+ return res;
+ }
+
+ if ((res = mp_init(&v)) != MP_OKAY) {
+ goto LBL_C;
+ }
+
+ /* product of first 50 primes */
+ if ((res =
+ mp_read_radix(&v,
+ "19078266889580195013601891820992757757219839668357012055907516904309700014933909014729740190",
+ 10)) != MP_OKAY) {
+ goto LBL_V;
+ }
+
+ if ((res = mp_init(&a)) != MP_OKAY) {
+ goto LBL_V;
+ }
+
+ /* set the prime */
+ mp_set(&a, prime_digit());
+
+ if ((res = mp_init(&b)) != MP_OKAY) {
+ goto LBL_A;
+ }
+
+ if ((res = mp_init(&n)) != MP_OKAY) {
+ goto LBL_B;
+ }
+
+ if ((res = mp_init(&x)) != MP_OKAY) {
+ goto LBL_N;
+ }
+
+ if ((res = mp_init(&y)) != MP_OKAY) {
+ goto LBL_X;
+ }
+
+ if ((res = mp_init(&z)) != MP_OKAY) {
+ goto LBL_Y;
+ }
+
+ /* now loop making the single digit */
+ while (mp_count_bits(&a) < k) {
+ fprintf(stderr, "prime has %4d bits left\r", k - mp_count_bits(&a));
+ fflush(stderr);
+top:
+ mp_set(&b, prime_digit());
+
+ /* now compute z = a * b * 2 */
+ if ((res = mp_mul(&a, &b, &z)) != MP_OKAY) { /* z = a * b */
+ goto LBL_Z;
+ }
+
+ if ((res = mp_copy(&z, &c)) != MP_OKAY) { /* c = a * b */
+ goto LBL_Z;
+ }
+
+ if ((res = mp_mul_2(&z, &z)) != MP_OKAY) { /* z = 2 * a * b */
+ goto LBL_Z;
+ }
+
+ /* n = z + 1 */
+ if ((res = mp_add_d(&z, 1uL, &n)) != MP_OKAY) { /* n = z + 1 */
+ goto LBL_Z;
+ }
+
+ /* check (n, v) == 1 */
+ if ((res = mp_gcd(&n, &v, &y)) != MP_OKAY) { /* y = (n, v) */
+ goto LBL_Z;
+ }
+
+ if (mp_cmp_d(&y, 1uL) != MP_EQ)
+ goto top;
+
+ /* now try base x=bases[ii] */
+ for (ii = 0; ii < li; ii++) {
+ mp_set(&x, bases[ii]);
+
+ /* compute x^a mod n */
+ if ((res = mp_exptmod(&x, &a, &n, &y)) != MP_OKAY) { /* y = x^a mod n */
+ goto LBL_Z;
+ }
+
+ /* if y == 1 loop */
+ if (mp_cmp_d(&y, 1uL) == MP_EQ)
+ continue;
+
+ /* now x^2a mod n */
+ if ((res = mp_sqrmod(&y, &n, &y)) != MP_OKAY) { /* y = x^2a mod n */
+ goto LBL_Z;
+ }
+
+ if (mp_cmp_d(&y, 1uL) == MP_EQ)
+ continue;
+
+ /* compute x^b mod n */
+ if ((res = mp_exptmod(&x, &b, &n, &y)) != MP_OKAY) { /* y = x^b mod n */
+ goto LBL_Z;
+ }
+
+ /* if y == 1 loop */
+ if (mp_cmp_d(&y, 1uL) == MP_EQ)
+ continue;
+
+ /* now x^2b mod n */
+ if ((res = mp_sqrmod(&y, &n, &y)) != MP_OKAY) { /* y = x^2b mod n */
+ goto LBL_Z;
+ }
+
+ if (mp_cmp_d(&y, 1uL) == MP_EQ)
+ continue;
+
+ /* compute x^c mod n == x^ab mod n */
+ if ((res = mp_exptmod(&x, &c, &n, &y)) != MP_OKAY) { /* y = x^ab mod n */
+ goto LBL_Z;
+ }
+
+ /* if y == 1 loop */
+ if (mp_cmp_d(&y, 1uL) == MP_EQ)
+ continue;
+
+ /* now compute (x^c mod n)^2 */
+ if ((res = mp_sqrmod(&y, &n, &y)) != MP_OKAY) { /* y = x^2ab mod n */
+ goto LBL_Z;
+ }
+
+ /* y should be 1 */
+ if (mp_cmp_d(&y, 1uL) != MP_EQ)
+ continue;
+ break;
+ }
+
+ /* no bases worked? */
+ if (ii == li)
+ goto top;
+
+ {
+ char buf[4096];
+
+ mp_to_decimal(&n, buf, sizeof(buf));
+ printf("Certificate of primality for:\n%s\n\n", buf);
+ mp_to_decimal(&a, buf, sizeof(buf));
+ printf("A == \n%s\n\n", buf);
+ mp_to_decimal(&b, buf, sizeof(buf));
+ printf("B == \n%s\n\nG == %lu\n", buf, bases[ii]);
+ printf("----------------------------------------------------------------\n");
+ }
+
+ /* a = n */
+ mp_copy(&n, &a);
+ }
+
+ /* get q to be the order of the large prime subgroup */
+ mp_sub_d(&n, 1uL, q);
+ mp_div_2(q, q);
+ mp_div(q, &b, q, NULL);
+
+ mp_exch(&n, p);
+
+ res = MP_OKAY;
+LBL_Z:
+ mp_clear(&z);
+LBL_Y:
+ mp_clear(&y);
+LBL_X:
+ mp_clear(&x);
+LBL_N:
+ mp_clear(&n);
+LBL_B:
+ mp_clear(&b);
+LBL_A:
+ mp_clear(&a);
+LBL_V:
+ mp_clear(&v);
+LBL_C:
+ mp_clear(&c);
+ return res;
+}
+
+
+int main(void)
+{
+ mp_int p, q;
+ char buf[4096];
+ int k, li;
+ clock_t t1;
+
+ srand(time(NULL));
+ load_tab();
+
+ printf("Enter # of bits: \n");
+ fgets(buf, sizeof(buf), stdin);
+ sscanf(buf, "%d", &k);
+
+ printf("Enter number of bases to try (1 to 8):\n");
+ fgets(buf, sizeof(buf), stdin);
+ sscanf(buf, "%d", &li);
+
+
+ mp_init(&p);
+ mp_init(&q);
+
+ t1 = clock();
+ pprime(k, li, &p, &q);
+ t1 = clock() - t1;
+
+ printf("\n\nTook %d ticks, %d bits\n", t1, mp_count_bits(&p));
+
+ mp_to_decimal(&p, buf, sizeof(buf));
+ printf("P == %s\n", buf);
+ mp_to_decimal(&q, buf, sizeof(buf));
+ printf("Q == %s\n", buf);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/prime.1024 b/third_party/heimdal/lib/hcrypto/libtommath/etc/prime.1024
new file mode 100644
index 0000000..5636e2d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/prime.1024
@@ -0,0 +1,414 @@
+Enter # of bits:
+Enter number of bases to try (1 to 8):
+Certificate of primality for:
+36360080703173363
+
+A ==
+89963569
+
+B ==
+202082249
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+4851595597739856136987139
+
+A ==
+36360080703173363
+
+B ==
+66715963
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+19550639734462621430325731591027
+
+A ==
+4851595597739856136987139
+
+B ==
+2014867
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+10409036141344317165691858509923818734539
+
+A ==
+19550639734462621430325731591027
+
+B ==
+266207047
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+1049829549988285012736475602118094726647504414203
+
+A ==
+10409036141344317165691858509923818734539
+
+B ==
+50428759
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+77194737385528288387712399596835459931920358844586615003
+
+A ==
+1049829549988285012736475602118094726647504414203
+
+B ==
+36765367
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+35663756695365208574443215955488689578374232732893628896541201763
+
+A ==
+77194737385528288387712399596835459931920358844586615003
+
+B ==
+230998627
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+16711831463502165169495622246023119698415848120292671294127567620396469803
+
+A ==
+35663756695365208574443215955488689578374232732893628896541201763
+
+B ==
+234297127
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+6163534781560285962890718925972249753147470953579266394395432475622345597103528739
+
+A ==
+16711831463502165169495622246023119698415848120292671294127567620396469803
+
+B ==
+184406323
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+814258256205243497704094951432575867360065658372158511036259934640748088306764553488803787
+
+A ==
+6163534781560285962890718925972249753147470953579266394395432475622345597103528739
+
+B ==
+66054487
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+176469695533271657902814176811660357049007467856432383037590673407330246967781451723764079581998187
+
+A ==
+814258256205243497704094951432575867360065658372158511036259934640748088306764553488803787
+
+B ==
+108362239
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+44924492859445516541759485198544012102424796403707253610035148063863073596051272171194806669756971406400419
+
+A ==
+176469695533271657902814176811660357049007467856432383037590673407330246967781451723764079581998187
+
+B ==
+127286707
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+20600996927219343383225424320134474929609459588323857796871086845924186191561749519858600696159932468024710985371059
+
+A ==
+44924492859445516541759485198544012102424796403707253610035148063863073596051272171194806669756971406400419
+
+B ==
+229284691
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+6295696427695493110141186605837397185848992307978456138112526915330347715236378041486547994708748840844217371233735072572979
+
+A ==
+20600996927219343383225424320134474929609459588323857796871086845924186191561749519858600696159932468024710985371059
+
+B ==
+152800771
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+3104984078042317488749073016454213579257792635142218294052134804187631661145261015102617582090263808696699966840735333252107678792123
+
+A ==
+6295696427695493110141186605837397185848992307978456138112526915330347715236378041486547994708748840844217371233735072572979
+
+B ==
+246595759
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+26405175827665701256325699315126705508919255051121452292124404943796947287968603975320562847910946802396632302209435206627913466015741799499
+
+A ==
+3104984078042317488749073016454213579257792635142218294052134804187631661145261015102617582090263808696699966840735333252107678792123
+
+B ==
+4252063
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+11122146237908413610034600609460545703591095894418599759742741406628055069007082998134905595800236452010905900391505454890446585211975124558601770163
+
+A ==
+26405175827665701256325699315126705508919255051121452292124404943796947287968603975320562847910946802396632302209435206627913466015741799499
+
+B ==
+210605419
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+1649861642047798890580354082088712649911849362201343649289384923147797960364736011515757482030049342943790127685185806092659832129486307035500638595572396187
+
+A ==
+11122146237908413610034600609460545703591095894418599759742741406628055069007082998134905595800236452010905900391505454890446585211975124558601770163
+
+B ==
+74170111
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+857983367126266717607389719637086684134462613006415859877666235955788392464081914127715967940968197765042399904117392707518175220864852816390004264107201177394565363
+
+A ==
+1649861642047798890580354082088712649911849362201343649289384923147797960364736011515757482030049342943790127685185806092659832129486307035500638595572396187
+
+B ==
+260016763
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+175995909353623703257072120479340610010337144085688850745292031336724691277374210929188442230237711063783727092685448718515661641054886101716698390145283196296702450566161283
+
+A ==
+857983367126266717607389719637086684134462613006415859877666235955788392464081914127715967940968197765042399904117392707518175220864852816390004264107201177394565363
+
+B ==
+102563707
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+48486002551155667224487059713350447239190772068092630563272168418880661006593537218144160068395218642353495339720640699721703003648144463556291315694787862009052641640656933232794283
+
+A ==
+175995909353623703257072120479340610010337144085688850745292031336724691277374210929188442230237711063783727092685448718515661641054886101716698390145283196296702450566161283
+
+B ==
+137747527
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+13156468011529105025061495011938518171328604045212410096476697450506055664012861932372156505805788068791146986282263016790631108386790291275939575123375304599622623328517354163964228279867403
+
+A ==
+48486002551155667224487059713350447239190772068092630563272168418880661006593537218144160068395218642353495339720640699721703003648144463556291315694787862009052641640656933232794283
+
+B ==
+135672847
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+6355194692790533601105154341731997464407930009404822926832136060319955058388106456084549316415200519472481147942263916585428906582726749131479465958107142228236909665306781538860053107680830113869123
+
+A ==
+13156468011529105025061495011938518171328604045212410096476697450506055664012861932372156505805788068791146986282263016790631108386790291275939575123375304599622623328517354163964228279867403
+
+B ==
+241523587
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+3157116676535430302794438027544146642863331358530722860333745617571010460905857862561870488000265751138954271040017454405707755458702044884023184574412221802502351503929935224995314581932097706874819348858083
+
+A ==
+6355194692790533601105154341731997464407930009404822926832136060319955058388106456084549316415200519472481147942263916585428906582726749131479465958107142228236909665306781538860053107680830113869123
+
+B ==
+248388667
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+390533129219992506725320633489467713907837370444962163378727819939092929448752905310115311180032249230394348337568973177802874166228132778126338883671958897238722734394783244237133367055422297736215754829839364158067
+
+A ==
+3157116676535430302794438027544146642863331358530722860333745617571010460905857862561870488000265751138954271040017454405707755458702044884023184574412221802502351503929935224995314581932097706874819348858083
+
+B ==
+61849651
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+48583654555070224891047847050732516652910250240135992225139515777200432486685999462997073444468380434359929499498804723793106565291183220444221080449740542884172281158126259373095216435009661050109711341419005972852770440739
+
+A ==
+390533129219992506725320633489467713907837370444962163378727819939092929448752905310115311180032249230394348337568973177802874166228132778126338883671958897238722734394783244237133367055422297736215754829839364158067
+
+B ==
+62201707
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+25733035251905120039135866524384525138869748427727001128764704499071378939227862068500633813538831598776578372709963673670934388213622433800015759585470542686333039614931682098922935087822950084908715298627996115185849260703525317419
+
+A ==
+48583654555070224891047847050732516652910250240135992225139515777200432486685999462997073444468380434359929499498804723793106565291183220444221080449740542884172281158126259373095216435009661050109711341419005972852770440739
+
+B ==
+264832231
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+2804594464939948901906623499531073917980499195397462605359913717827014360538186518540781517129548650937632008683280555602633122170458773895504894807182664540529077836857897972175530148107545939211339044386106111633510166695386323426241809387
+
+A ==
+25733035251905120039135866524384525138869748427727001128764704499071378939227862068500633813538831598776578372709963673670934388213622433800015759585470542686333039614931682098922935087822950084908715298627996115185849260703525317419
+
+B ==
+54494047
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+738136612083433720096707308165797114449914259256979340471077690416567237592465306112484843530074782721390528773594351482384711900456440808251196845265132086486672447136822046628407467459921823150600138073268385534588238548865012638209515923513516547
+
+A ==
+2804594464939948901906623499531073917980499195397462605359913717827014360538186518540781517129548650937632008683280555602633122170458773895504894807182664540529077836857897972175530148107545939211339044386106111633510166695386323426241809387
+
+B ==
+131594179
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+392847529056126766528615419937165193421166694172790666626558750047057558168124866940509180171236517681470100877687445134633784815352076138790217228749332398026714192707447855731679485746120589851992221508292976900578299504461333767437280988393026452846013683
+
+A ==
+738136612083433720096707308165797114449914259256979340471077690416567237592465306112484843530074782721390528773594351482384711900456440808251196845265132086486672447136822046628407467459921823150600138073268385534588238548865012638209515923513516547
+
+B ==
+266107603
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+168459393231883505975876919268398655632763956627405508859662408056221544310200546265681845397346956580604208064328814319465940958080244889692368602591598503944015835190587740756859842792554282496742843600573336023639256008687581291233481455395123454655488735304365627
+
+A ==
+392847529056126766528615419937165193421166694172790666626558750047057558168124866940509180171236517681470100877687445134633784815352076138790217228749332398026714192707447855731679485746120589851992221508292976900578299504461333767437280988393026452846013683
+
+B ==
+214408111
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+14865774288636941404884923981945833072113667565310054952177860608355263252462409554658728941191929400198053290113492910272458441655458514080123870132092365833472436407455910185221474386718838138135065780840839893113912689594815485706154461164071775481134379794909690501684643
+
+A ==
+168459393231883505975876919268398655632763956627405508859662408056221544310200546265681845397346956580604208064328814319465940958080244889692368602591598503944015835190587740756859842792554282496742843600573336023639256008687581291233481455395123454655488735304365627
+
+B ==
+44122723
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+1213301773203241614897109856134894783021668292000023984098824423682568173639394290886185366993108292039068940333907505157813934962357206131450244004178619265868614859794316361031904412926604138893775068853175215502104744339658944443630407632290152772487455298652998368296998719996019
+
+A ==
+14865774288636941404884923981945833072113667565310054952177860608355263252462409554658728941191929400198053290113492910272458441655458514080123870132092365833472436407455910185221474386718838138135065780840839893113912689594815485706154461164071775481134379794909690501684643
+
+B ==
+40808563
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+186935245989515158127969129347464851990429060640910951266513740972248428651109062997368144722015290092846666943896556191257222521203647606911446635194198213436423080005867489516421559330500722264446765608763224572386410155413161172707802334865729654109050873820610813855041667633843601286843
+
+A ==
+1213301773203241614897109856134894783021668292000023984098824423682568173639394290886185366993108292039068940333907505157813934962357206131450244004178619265868614859794316361031904412926604138893775068853175215502104744339658944443630407632290152772487455298652998368296998719996019
+
+B ==
+77035759
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+83142661079751490510739960019112406284111408348732592580459037404394946037094409915127399165633756159385609671956087845517678367844901424617866988187132480585966721962585586730693443536100138246516868613250009028187662080828012497191775172228832247706080044971423654632146928165751885302331924491683
+
+A ==
+186935245989515158127969129347464851990429060640910951266513740972248428651109062997368144722015290092846666943896556191257222521203647606911446635194198213436423080005867489516421559330500722264446765608763224572386410155413161172707802334865729654109050873820610813855041667633843601286843
+
+B ==
+222383587
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+3892354773803809855317742245039794448230625839512638747643814927766738642436392673485997449586432241626440927010641564064764336402368634186618250134234189066179771240232458249806850838490410473462391401438160528157981942499581634732706904411807195259620779379274017704050790865030808501633772117217899534443
+
+A ==
+83142661079751490510739960019112406284111408348732592580459037404394946037094409915127399165633756159385609671956087845517678367844901424617866988187132480585966721962585586730693443536100138246516868613250009028187662080828012497191775172228832247706080044971423654632146928165751885302331924491683
+
+B ==
+23407687
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+1663606652988091811284014366560171522582683318514519379924950390627250155440313691226744227787921928894551755219495501365555370027257568506349958010457682898612082048959464465369892842603765280317696116552850664773291371490339084156052244256635115997453399761029567033971998617303988376172539172702246575225837054723
+
+A ==
+3892354773803809855317742245039794448230625839512638747643814927766738642436392673485997449586432241626440927010641564064764336402368634186618250134234189066179771240232458249806850838490410473462391401438160528157981942499581634732706904411807195259620779379274017704050790865030808501633772117217899534443
+
+B ==
+213701827
+
+G == 2
+----------------------------------------------------------------
+
+
+Took 33057 ticks, 1048 bits
+P == 1663606652988091811284014366560171522582683318514519379924950390627250155440313691226744227787921928894551755219495501365555370027257568506349958010457682898612082048959464465369892842603765280317696116552850664773291371490339084156052244256635115997453399761029567033971998617303988376172539172702246575225837054723
+Q == 3892354773803809855317742245039794448230625839512638747643814927766738642436392673485997449586432241626440927010641564064764336402368634186618250134234189066179771240232458249806850838490410473462391401438160528157981942499581634732706904411807195259620779379274017704050790865030808501633772117217899534443
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/prime.512 b/third_party/heimdal/lib/hcrypto/libtommath/etc/prime.512
new file mode 100644
index 0000000..cb6ec30
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/prime.512
@@ -0,0 +1,205 @@
+Enter # of bits:
+Enter number of bases to try (1 to 8):
+Certificate of primality for:
+85933926807634727
+
+A ==
+253758023
+
+B ==
+169322581
+
+G == 5
+----------------------------------------------------------------
+Certificate of primality for:
+23930198825086241462113799
+
+A ==
+85933926807634727
+
+B ==
+139236037
+
+G == 11
+----------------------------------------------------------------
+Certificate of primality for:
+6401844647261612602378676572510019
+
+A ==
+23930198825086241462113799
+
+B ==
+133760791
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+269731366027728777712034888684015329354259
+
+A ==
+6401844647261612602378676572510019
+
+B ==
+21066691
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+37942338209025571690075025099189467992329684223707
+
+A ==
+269731366027728777712034888684015329354259
+
+B ==
+70333567
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+15306904714258982484473490774101705363308327436988160248323
+
+A ==
+37942338209025571690075025099189467992329684223707
+
+B ==
+201712723
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+1616744757018513392810355191503853040357155275733333124624513530099
+
+A ==
+15306904714258982484473490774101705363308327436988160248323
+
+B ==
+52810963
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+464222094814208047161771036072622485188658077940154689939306386289983787983
+
+A ==
+1616744757018513392810355191503853040357155275733333124624513530099
+
+B ==
+143566909
+
+G == 5
+----------------------------------------------------------------
+Certificate of primality for:
+187429931674053784626487560729643601208757374994177258429930699354770049369025096447
+
+A ==
+464222094814208047161771036072622485188658077940154689939306386289983787983
+
+B ==
+201875281
+
+G == 5
+----------------------------------------------------------------
+Certificate of primality for:
+100579220846502621074093727119851331775052664444339632682598589456666938521976625305832917563
+
+A ==
+187429931674053784626487560729643601208757374994177258429930699354770049369025096447
+
+B ==
+268311523
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+1173616081309758475197022137833792133815753368965945885089720153370737965497134878651384030219765163
+
+A ==
+100579220846502621074093727119851331775052664444339632682598589456666938521976625305832917563
+
+B ==
+5834287
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+191456913489905913185935197655672585713573070349044195411728114905691721186574907738081340754373032735283623
+
+A ==
+1173616081309758475197022137833792133815753368965945885089720153370737965497134878651384030219765163
+
+B ==
+81567097
+
+G == 5
+----------------------------------------------------------------
+Certificate of primality for:
+57856530489201750164178576399448868489243874083056587683743345599898489554401618943240901541005080049321706789987519
+
+A ==
+191456913489905913185935197655672585713573070349044195411728114905691721186574907738081340754373032735283623
+
+B ==
+151095433
+
+G == 7
+----------------------------------------------------------------
+Certificate of primality for:
+13790529750452576698109671710773784949185621244122040804792403407272729038377767162233653248852099545134831722512085881814803
+
+A ==
+57856530489201750164178576399448868489243874083056587683743345599898489554401618943240901541005080049321706789987519
+
+B ==
+119178679
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+7075985989000817742677547821106534174334812111605018857703825637170140040509067704269696198231266351631132464035671858077052876058979
+
+A ==
+13790529750452576698109671710773784949185621244122040804792403407272729038377767162233653248852099545134831722512085881814803
+
+B ==
+256552363
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+1227273006232588072907488910282307435921226646895131225407452056677899411162892829564455154080310937471747140942360789623819327234258162420463
+
+A ==
+7075985989000817742677547821106534174334812111605018857703825637170140040509067704269696198231266351631132464035671858077052876058979
+
+B ==
+86720989
+
+G == 5
+----------------------------------------------------------------
+Certificate of primality for:
+446764896913554613686067036908702877942872355053329937790398156069936255759889884246832779737114032666318220500106499161852193765380831330106375235763
+
+A ==
+1227273006232588072907488910282307435921226646895131225407452056677899411162892829564455154080310937471747140942360789623819327234258162420463
+
+B ==
+182015287
+
+G == 2
+----------------------------------------------------------------
+Certificate of primality for:
+5290203010849586596974953717018896543907195901082056939587768479377028575911127944611236020459652034082251335583308070846379514569838984811187823420951275243
+
+A ==
+446764896913554613686067036908702877942872355053329937790398156069936255759889884246832779737114032666318220500106499161852193765380831330106375235763
+
+B ==
+5920567
+
+G == 2
+----------------------------------------------------------------
+
+
+Took 3454 ticks, 521 bits
+P == 5290203010849586596974953717018896543907195901082056939587768479377028575911127944611236020459652034082251335583308070846379514569838984811187823420951275243
+Q == 446764896913554613686067036908702877942872355053329937790398156069936255759889884246832779737114032666318220500106499161852193765380831330106375235763
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/timer.asm b/third_party/heimdal/lib/hcrypto/libtommath/etc/timer.asm
new file mode 100644
index 0000000..35890d9
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/timer.asm
@@ -0,0 +1,37 @@
+; x86 timer in NASM
+;
+; Tom St Denis, tomstdenis@iahu.ca
+[bits 32]
+[section .data]
+time dd 0, 0
+
+[section .text]
+
+%ifdef USE_ELF
+[global t_start]
+t_start:
+%else
+[global _t_start]
+_t_start:
+%endif
+ push edx
+ push eax
+ rdtsc
+ mov [time+0],edx
+ mov [time+4],eax
+ pop eax
+ pop edx
+ ret
+
+%ifdef USE_ELF
+[global t_read]
+t_read:
+%else
+[global _t_read]
+_t_read:
+%endif
+ rdtsc
+ sub eax,[time+4]
+ sbb edx,[time+0]
+ ret
+ \ No newline at end of file
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/tune.c b/third_party/heimdal/lib/hcrypto/libtommath/etc/tune.c
new file mode 100644
index 0000000..e7b99fc
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/tune.c
@@ -0,0 +1,542 @@
+/* Tune the Karatsuba parameters
+ *
+ * Tom St Denis, tstdenis82@gmail.com
+ */
+#include "../tommath.h"
+#include "../tommath_private.h"
+#include <time.h>
+#include <inttypes.h>
+#include <errno.h>
+
+/*
+ Please take in mind that both multiplicands are of the same size. The balancing
+ mechanism in mp_balance works well but has some overhead itself. You can test
+ the behaviour of it with the option "-o" followed by a (small) positive number 'x'
+ to generate ratios of the form 1:x.
+*/
+
+static uint64_t s_timer_function(void);
+static void s_timer_start(void);
+static uint64_t s_timer_stop(void);
+static uint64_t s_time_mul(int size);
+static uint64_t s_time_sqr(int size);
+static void s_usage(char *s);
+
+static uint64_t s_timer_function(void)
+{
+#if _POSIX_C_SOURCE >= 199309L
+#define LTM_BILLION 1000000000
+ struct timespec ts;
+
+ /* TODO: Sets errno in case of error. Use? */
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return (((uint64_t)ts.tv_sec) * LTM_BILLION + (uint64_t)ts.tv_nsec);
+#else
+ clock_t t;
+ t = clock();
+ if (t < (clock_t)(0)) {
+ return (uint64_t)(0);
+ }
+ return (uint64_t)(t);
+#endif
+}
+
+/* generic ISO C timer */
+static uint64_t s_timer_tmp;
+static void s_timer_start(void)
+{
+ s_timer_tmp = s_timer_function();
+}
+static uint64_t s_timer_stop(void)
+{
+ return s_timer_function() - s_timer_tmp;
+}
+
+
+static int s_check_result;
+static int s_number_of_test_loops;
+static int s_stabilization_extra;
+static int s_offset = 1;
+
+#define s_mp_mul(a, b, c) s_mp_mul_digs(a, b, c, (a)->used + (b)->used + 1)
+static uint64_t s_time_mul(int size)
+{
+ int x;
+ mp_err e;
+ mp_int a, b, c, d;
+ uint64_t t1;
+
+ if ((e = mp_init_multi(&a, &b, &c, &d, NULL)) != MP_OKAY) {
+ t1 = UINT64_MAX;
+ goto LTM_ERR;
+ }
+
+ if ((e = mp_rand(&a, size * s_offset)) != MP_OKAY) {
+ t1 = UINT64_MAX;
+ goto LTM_ERR;
+ }
+ if ((e = mp_rand(&b, size)) != MP_OKAY) {
+ t1 = UINT64_MAX;
+ goto LTM_ERR;
+ }
+
+ s_timer_start();
+ for (x = 0; x < s_number_of_test_loops; x++) {
+ if ((e = mp_mul(&a,&b,&c)) != MP_OKAY) {
+ t1 = UINT64_MAX;
+ goto LTM_ERR;
+ }
+ if (s_check_result == 1) {
+ if ((e = s_mp_mul(&a,&b,&d)) != MP_OKAY) {
+ t1 = UINT64_MAX;
+ goto LTM_ERR;
+ }
+ if (mp_cmp(&c, &d) != MP_EQ) {
+ /* Time of 0 cannot happen (famous last words?) */
+ t1 = 0uLL;
+ goto LTM_ERR;
+ }
+ }
+ }
+
+ t1 = s_timer_stop();
+LTM_ERR:
+ mp_clear_multi(&a, &b, &c, &d, NULL);
+ return t1;
+}
+
+static uint64_t s_time_sqr(int size)
+{
+ int x;
+ mp_err e;
+ mp_int a, b, c;
+ uint64_t t1;
+
+ if ((e = mp_init_multi(&a, &b, &c, NULL)) != MP_OKAY) {
+ t1 = UINT64_MAX;
+ goto LTM_ERR;
+ }
+
+ if ((e = mp_rand(&a, size)) != MP_OKAY) {
+ t1 = UINT64_MAX;
+ goto LTM_ERR;
+ }
+
+ s_timer_start();
+ for (x = 0; x < s_number_of_test_loops; x++) {
+ if ((e = mp_sqr(&a,&b)) != MP_OKAY) {
+ t1 = UINT64_MAX;
+ goto LTM_ERR;
+ }
+ if (s_check_result == 1) {
+ if ((e = s_mp_sqr(&a,&c)) != MP_OKAY) {
+ t1 = UINT64_MAX;
+ goto LTM_ERR;
+ }
+ if (mp_cmp(&c, &b) != MP_EQ) {
+ t1 = 0uLL;
+ goto LTM_ERR;
+ }
+ }
+ }
+
+ t1 = s_timer_stop();
+LTM_ERR:
+ mp_clear_multi(&a, &b, &c, NULL);
+ return t1;
+}
+
+struct tune_args {
+ int testmode;
+ int verbose;
+ int print;
+ int bncore;
+ int terse;
+ int upper_limit_print;
+ int increment_print;
+} args;
+
+static void s_run(const char *name, uint64_t (*op)(int), int *cutoff)
+{
+ int x, count = 0;
+ uint64_t t1, t2;
+ if ((args.verbose == 1) || (args.testmode == 1)) {
+ printf("# %s.\n", name);
+ }
+ for (x = 8; x < args.upper_limit_print; x += args.increment_print) {
+ *cutoff = INT_MAX;
+ t1 = op(x);
+ if ((t1 == 0uLL) || (t1 == UINT64_MAX)) {
+ fprintf(stderr,"%s failed at x = INT_MAX (%s)\n", name,
+ (t1 == 0uLL)?"wrong result":"internal error");
+ exit(EXIT_FAILURE);
+ }
+ *cutoff = x;
+ t2 = op(x);
+ if ((t2 == 0uLL) || (t2 == UINT64_MAX)) {
+ fprintf(stderr,"%s failed (%s)\n", name,
+ (t2 == 0uLL)?"wrong result":"internal error");
+ exit(EXIT_FAILURE);
+ }
+ if (args.verbose == 1) {
+ printf("%d: %9"PRIu64" %9"PRIu64", %9"PRIi64"\n", x, t1, t2, (int64_t)t2 - (int64_t)t1);
+ }
+ if (t2 < t1) {
+ if (count == s_stabilization_extra) {
+ count = 0;
+ break;
+ } else if (count < s_stabilization_extra) {
+ count++;
+ }
+ } else if (count > 0) {
+ count--;
+ }
+ }
+ *cutoff = x - s_stabilization_extra * args.increment_print;
+}
+
+static long s_strtol(const char *str, char **endptr, const char *err)
+{
+ const int base = 10;
+ char *_endptr;
+ long val;
+ errno = 0;
+ val = strtol(str, &_endptr, base);
+ if ((val > INT_MAX || val < 0) || (errno != 0)) {
+ fprintf(stderr, "Value %s not usable\n", str);
+ exit(EXIT_FAILURE);
+ }
+ if (_endptr == str) {
+ fprintf(stderr, "%s\n", err);
+ exit(EXIT_FAILURE);
+ }
+ if (endptr) *endptr = _endptr;
+ return val;
+}
+
+static int s_exit_code = EXIT_FAILURE;
+static void s_usage(char *s)
+{
+ fprintf(stderr,"Usage: %s [TvcpGbtrSLFfMmosh]\n",s);
+ fprintf(stderr," -T testmode, for use with testme.sh\n");
+ fprintf(stderr," -v verbose, print all timings\n");
+ fprintf(stderr," -c check results\n");
+ fprintf(stderr," -p print benchmark of final cutoffs in files \"multiplying\"\n");
+ fprintf(stderr," and \"squaring\"\n");
+ fprintf(stderr," -G [string] suffix for the filenames listed above\n");
+ fprintf(stderr," Implies '-p'\n");
+ fprintf(stderr," -b print benchmark of bncore.c\n");
+ fprintf(stderr," -t prints space (0x20) separated results\n");
+ fprintf(stderr," -r [64] number of rounds\n");
+ fprintf(stderr," -S [0xdeadbeef] seed for PRNG\n");
+ fprintf(stderr," -L [3] number of negative values accumulated until the result is accepted\n");
+ fprintf(stderr," -M [3000] upper limit of T-C tests/prints\n");
+ fprintf(stderr," -m [1] increment of T-C tests/prints\n");
+ fprintf(stderr," -o [1] multiplier for the second multiplicand\n");
+ fprintf(stderr," (Not for computing the cut-offs!)\n");
+ fprintf(stderr," -s 'preset' use values in 'preset' for printing.\n");
+ fprintf(stderr," 'preset' is a comma separated string with cut-offs for\n");
+ fprintf(stderr," ksm, kss, tc3m, tc3s in that order\n");
+ fprintf(stderr," ksm = karatsuba multiplication\n");
+ fprintf(stderr," kss = karatsuba squaring\n");
+ fprintf(stderr," tc3m = Toom-Cook 3-way multiplication\n");
+ fprintf(stderr," tc3s = Toom-Cook 3-way squaring\n");
+ fprintf(stderr," Implies '-p'\n");
+ fprintf(stderr," -h this message\n");
+ exit(s_exit_code);
+}
+
+struct cutoffs {
+ int KARATSUBA_MUL, KARATSUBA_SQR;
+ int TOOM_MUL, TOOM_SQR;
+};
+
+const struct cutoffs max_cutoffs =
+{ INT_MAX, INT_MAX, INT_MAX, INT_MAX };
+
+static void set_cutoffs(const struct cutoffs *c)
+{
+ KARATSUBA_MUL_CUTOFF = c->KARATSUBA_MUL;
+ KARATSUBA_SQR_CUTOFF = c->KARATSUBA_SQR;
+ TOOM_MUL_CUTOFF = c->TOOM_MUL;
+ TOOM_SQR_CUTOFF = c->TOOM_SQR;
+}
+
+static void get_cutoffs(struct cutoffs *c)
+{
+ c->KARATSUBA_MUL = KARATSUBA_MUL_CUTOFF;
+ c->KARATSUBA_SQR = KARATSUBA_SQR_CUTOFF;
+ c->TOOM_MUL = TOOM_MUL_CUTOFF;
+ c->TOOM_SQR = TOOM_SQR_CUTOFF;
+
+}
+
+int main(int argc, char **argv)
+{
+ uint64_t t1, t2;
+ int x, i, j;
+ size_t n;
+
+ int printpreset = 0;
+ /*int preset[8];*/
+ char *endptr, *str;
+
+ uint64_t seed = 0xdeadbeef;
+
+ int opt;
+ struct cutoffs orig, updated;
+
+ FILE *squaring, *multiplying;
+ char mullog[256] = "multiplying";
+ char sqrlog[256] = "squaring";
+ s_number_of_test_loops = 64;
+ s_stabilization_extra = 3;
+
+ MP_ZERO_BUFFER(&args, sizeof(args));
+
+ args.testmode = 0;
+ args.verbose = 0;
+ args.print = 0;
+ args.bncore = 0;
+ args.terse = 0;
+
+ args.upper_limit_print = 3000;
+ args.increment_print = 1;
+
+ /* Very simple option parser, please treat it nicely. */
+ if (argc != 1) {
+ for (opt = 1; (opt < argc) && (argv[opt][0] == '-'); opt++) {
+ switch (argv[opt][1]) {
+ case 'T':
+ args.testmode = 1;
+ s_check_result = 1;
+ args.upper_limit_print = 1000;
+ args.increment_print = 11;
+ s_number_of_test_loops = 1;
+ s_stabilization_extra = 1;
+ s_offset = 1;
+ break;
+ case 'v':
+ args.verbose = 1;
+ break;
+ case 'c':
+ s_check_result = 1;
+ break;
+ case 'p':
+ args.print = 1;
+ break;
+ case 'G':
+ args.print = 1;
+ opt++;
+ if (opt >= argc) {
+ s_usage(argv[0]);
+ }
+ /* manual strcat() */
+ for (i = 0; i < 255; i++) {
+ if (mullog[i] == '\0') {
+ break;
+ }
+ }
+ for (j = 0; i < 255; j++, i++) {
+ mullog[i] = argv[opt][j];
+ if (argv[opt][j] == '\0') {
+ break;
+ }
+ }
+ for (i = 0; i < 255; i++) {
+ if (sqrlog[i] == '\0') {
+ break;
+ }
+ }
+ for (j = 0; i < 255; j++, i++) {
+ sqrlog[i] = argv[opt][j];
+ if (argv[opt][j] == '\0') {
+ break;
+ }
+ }
+ break;
+ case 'b':
+ args.bncore = 1;
+ break;
+ case 't':
+ args.terse = 1;
+ break;
+ case 'S':
+ opt++;
+ if (opt >= argc) {
+ s_usage(argv[0]);
+ }
+ str = argv[opt];
+ errno = 0;
+ seed = (uint64_t)s_strtol(argv[opt], NULL, "No seed given?\n");
+ break;
+ case 'L':
+ opt++;
+ if (opt >= argc) {
+ s_usage(argv[0]);
+ }
+ s_stabilization_extra = (int)s_strtol(argv[opt], NULL, "No value for option \"-L\"given");
+ break;
+ case 'o':
+ opt++;
+ if (opt >= argc) {
+ s_usage(argv[0]);
+ }
+ s_offset = (int)s_strtol(argv[opt], NULL, "No value for the offset given");
+ break;
+ case 'r':
+ opt++;
+ if (opt >= argc) {
+ s_usage(argv[0]);
+ }
+ s_number_of_test_loops = (int)s_strtol(argv[opt], NULL, "No value for the number of rounds given");
+ break;
+
+ case 'M':
+ opt++;
+ if (opt >= argc) {
+ s_usage(argv[0]);
+ }
+ args.upper_limit_print = (int)s_strtol(argv[opt], NULL, "No value for the upper limit of T-C tests given");
+ break;
+ case 'm':
+ opt++;
+ if (opt >= argc) {
+ s_usage(argv[0]);
+ }
+ args.increment_print = (int)s_strtol(argv[opt], NULL, "No value for the increment for the T-C tests given");
+ break;
+ case 's':
+ printpreset = 1;
+ args.print = 1;
+ opt++;
+ if (opt >= argc) {
+ s_usage(argv[0]);
+ }
+ str = argv[opt];
+ KARATSUBA_MUL_CUTOFF = (int)s_strtol(str, &endptr, "[1/4] No value for KARATSUBA_MUL_CUTOFF given");
+ str = endptr + 1;
+ KARATSUBA_SQR_CUTOFF = (int)s_strtol(str, &endptr, "[2/4] No value for KARATSUBA_SQR_CUTOFF given");
+ str = endptr + 1;
+ TOOM_MUL_CUTOFF = (int)s_strtol(str, &endptr, "[3/4] No value for TOOM_MUL_CUTOFF given");
+ str = endptr + 1;
+ TOOM_SQR_CUTOFF = (int)s_strtol(str, &endptr, "[4/4] No value for TOOM_SQR_CUTOFF given");
+ break;
+ case 'h':
+ s_exit_code = EXIT_SUCCESS;
+ /* FALLTHROUGH */
+ default:
+ s_usage(argv[0]);
+ }
+ }
+ }
+
+ /*
+ mp_rand uses the cryptographically secure
+ source of the OS by default. That is too expensive, too slow and
+ most important for a benchmark: it is not repeatable.
+ */
+ s_mp_rand_jenkins_init(seed);
+ mp_rand_source(s_mp_rand_jenkins);
+
+ get_cutoffs(&orig);
+
+ updated = max_cutoffs;
+ if ((args.bncore == 0) && (printpreset == 0)) {
+ struct {
+ const char *name;
+ int *cutoff, *update;
+ uint64_t (*fn)(int);
+ } test[] = {
+#define T_MUL_SQR(n, o, f) { #n, &o##_CUTOFF, &(updated.o), MP_HAS(S_MP_##o) ? f : NULL }
+ /*
+ The influence of the Comba multiplication cannot be
+ eradicated programmatically. It depends on the size
+ of the macro MP_WPARRAY in tommath.h which needs to
+ be changed manually (to 0 (zero)).
+ */
+ T_MUL_SQR("Karatsuba multiplication", KARATSUBA_MUL, s_time_mul),
+ T_MUL_SQR("Karatsuba squaring", KARATSUBA_SQR, s_time_sqr),
+ T_MUL_SQR("Toom-Cook 3-way multiplying", TOOM_MUL, s_time_mul),
+ T_MUL_SQR("Toom-Cook 3-way squaring", TOOM_SQR, s_time_sqr),
+#undef T_MUL_SQR
+ };
+ /* Turn all limits from bncore.c to the max */
+ set_cutoffs(&max_cutoffs);
+ for (n = 0; n < sizeof(test)/sizeof(test[0]); ++n) {
+ if (test[n].fn) {
+ s_run(test[n].name, test[n].fn, test[n].cutoff);
+ *test[n].update = *test[n].cutoff;
+ *test[n].cutoff = INT_MAX;
+ }
+ }
+ }
+ if (args.terse == 1) {
+ printf("%d %d %d %d\n",
+ updated.KARATSUBA_MUL,
+ updated.KARATSUBA_SQR,
+ updated.TOOM_MUL,
+ updated.TOOM_SQR);
+ } else {
+ printf("KARATSUBA_MUL_CUTOFF = %d\n", updated.KARATSUBA_MUL);
+ printf("KARATSUBA_SQR_CUTOFF = %d\n", updated.KARATSUBA_SQR);
+ printf("TOOM_MUL_CUTOFF = %d\n", updated.TOOM_MUL);
+ printf("TOOM_SQR_CUTOFF = %d\n", updated.TOOM_SQR);
+ }
+
+ if (args.print == 1) {
+ printf("Printing data for graphing to \"%s\" and \"%s\"\n",mullog, sqrlog);
+
+ multiplying = fopen(mullog, "w+");
+ if (multiplying == NULL) {
+ fprintf(stderr, "Opening file \"%s\" failed\n", mullog);
+ exit(EXIT_FAILURE);
+ }
+
+ squaring = fopen(sqrlog, "w+");
+ if (squaring == NULL) {
+ fprintf(stderr, "Opening file \"%s\" failed\n",sqrlog);
+ exit(EXIT_FAILURE);
+ }
+
+ for (x = 8; x < args.upper_limit_print; x += args.increment_print) {
+ set_cutoffs(&max_cutoffs);
+ t1 = s_time_mul(x);
+ set_cutoffs(&orig);
+ t2 = s_time_mul(x);
+ fprintf(multiplying, "%d: %9"PRIu64" %9"PRIu64", %9"PRIi64"\n", x, t1, t2, (int64_t)t2 - (int64_t)t1);
+ fflush(multiplying);
+ if (args.verbose == 1) {
+ printf("MUL %d: %9"PRIu64" %9"PRIu64", %9"PRIi64"\n", x, t1, t2, (int64_t)t2 - (int64_t)t1);
+ fflush(stdout);
+ }
+ set_cutoffs(&max_cutoffs);
+ t1 = s_time_sqr(x);
+ set_cutoffs(&orig);
+ t2 = s_time_sqr(x);
+ fprintf(squaring,"%d: %9"PRIu64" %9"PRIu64", %9"PRIi64"\n", x, t1, t2, (int64_t)t2 - (int64_t)t1);
+ fflush(squaring);
+ if (args.verbose == 1) {
+ printf("SQR %d: %9"PRIu64" %9"PRIu64", %9"PRIi64"\n", x, t1, t2, (int64_t)t2 - (int64_t)t1);
+ fflush(stdout);
+ }
+ }
+ printf("Finished. Data for graphing in \"%s\" and \"%s\"\n",mullog, sqrlog);
+ if (args.verbose == 1) {
+ set_cutoffs(&orig);
+ if (args.terse == 1) {
+ printf("%d %d %d %d\n",
+ KARATSUBA_MUL_CUTOFF,
+ KARATSUBA_SQR_CUTOFF,
+ TOOM_MUL_CUTOFF,
+ TOOM_SQR_CUTOFF);
+ } else {
+ printf("KARATSUBA_MUL_CUTOFF = %d\n", KARATSUBA_MUL_CUTOFF);
+ printf("KARATSUBA_SQR_CUTOFF = %d\n", KARATSUBA_SQR_CUTOFF);
+ printf("TOOM_MUL_CUTOFF = %d\n", TOOM_MUL_CUTOFF);
+ printf("TOOM_SQR_CUTOFF = %d\n", TOOM_SQR_CUTOFF);
+ }
+ }
+ }
+ exit(EXIT_SUCCESS);
+}
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/etc/tune_it.sh b/third_party/heimdal/lib/hcrypto/libtommath/etc/tune_it.sh
new file mode 100755
index 0000000..5e0fe7c
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/etc/tune_it.sh
@@ -0,0 +1,107 @@
+#!/bin/sh
+
+die() {
+ echo "$1 failed"
+ echo "Exiting"
+ exit $2
+}
+# A linear congruential generator is sufficient for the purpose.
+SEED=3735928559
+LCG() {
+ SEED=$(((1103515245 * $SEED + 12345) % 2147483648))
+ echo $SEED
+}
+median() {
+# read everything besides the header from file $1
+# | cut-out the required column $2
+# | sort all the entries numerically
+# | show only the first $3 entries
+# | show only the last entry
+ tail -n +2 $1 | cut -d' ' -f$2 | sort -n | head -n $3 | tail -n 1
+}
+
+MPWD=$(dirname $(readlink -f "$0"))
+FILE_NAME="tuning_list"
+TOMMATH_CUTOFFS_H="$MPWD/../tommath_cutoffs.h"
+BACKUP_SUFFIX=".orig"
+RNUM=0
+
+#############################################################################
+# It would be a good idea to isolate these processes (with e.g.: cpuset) #
+# #
+# It is not a good idea to e.g: watch high resolution videos while this #
+# test are running if you do not have enough memory to avoid page faults. #
+#############################################################################
+
+# Number of rounds overall.
+LIMIT=100
+# Number of loops for each input.
+RLOOPS=10
+# Offset ( > 0 ) . Runs tests with asymmetric input of the form 1:OFFSET
+# Please use another destination for TOMMATH_CUTOFFS_H if you change OFFSET, because the numbers
+# with an offset different from 1 (one) are not usable as the general cut-off values
+# in "tommath_cutoffs.h".
+OFFSET=1
+# Number ( >= 3 ) of positive results (TC-is-faster) accumulated until it is accepted.
+# Due to the algorithm used to compute the median in this Posix compliant shell script
+# the value needs to be 3 (three), not less, to keep the variation small.
+LAG=3
+# Keep the temporary file $FILE_NAME. Set to 0 (zero) to remove it at the end.
+# The file is in a format fit to feed into R directly. If you do it and find the median
+# of this program to be off by more than a couple: please contact the authors and report
+# the numbers from this program and R and the standard deviation. This program is known
+# to get larger errors if the standard deviation is larger than ~50.
+KEEP_TEMP=1
+
+echo "You might like to watch the numbers go up to $LIMIT but it will take a long time!"
+
+# Might not have sufficient rights or disc full.
+echo "km ks tc3m tc3s" > $FILE_NAME || die "Writing header to $FILE_NAME" $?
+i=1
+while [ $i -le $LIMIT ]; do
+ RNUM=$(LCG)
+ printf "\r%d" $i
+ "$MPWD"/tune -t -r $RLOOPS -L $LAG -S "$RNUM" -o $OFFSET >> $FILE_NAME || die "tune" $?
+ i=$((i + 1))
+done
+
+if [ $KEEP_TEMP -eq 0 ]; then
+ rm -v $FILE_NAME || die "Removing $KEEP_TEMP" $?
+fi
+
+echo "Writing cut-off values to \"$TOMMATH_CUTOFFS_H\"."
+echo "In case of failure: a copy of \"$TOMMATH_CUTOFFS_H\" is in \"$TOMMATH_CUTOFFS_H$BACKUP_SUFFIX\""
+
+cp -v $TOMMATH_CUTOFFS_H $TOMMATH_CUTOFFS_H$BACKUP_SUFFIX || die "Making backup copy of $TOMMATH_CUTOFFS_H" $?
+
+cat << END_OF_INPUT > $TOMMATH_CUTOFFS_H || die "Writing header to $TOMMATH_CUTOFFS_H" $?
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+/*
+ Current values evaluated on an AMD A8-6600K (64-bit).
+ Type "make tune" to optimize them for your machine but
+ be aware that it may take a long time. It took 2:30 minutes
+ on the aforementioned machine for example.
+ */
+END_OF_INPUT
+
+# The Posix shell does not offer an array data type so we create
+# the median with 'standard tools'^TM
+
+# read the file (without the first line) and count the lines
+i=$(tail -n +2 $FILE_NAME | wc -l)
+# our median point will be at $i entries
+i=$(( (i / 2) + 1 ))
+TMP=$(median $FILE_NAME 1 $i)
+echo "#define MP_DEFAULT_KARATSUBA_MUL_CUTOFF $TMP"
+echo "#define MP_DEFAULT_KARATSUBA_MUL_CUTOFF $TMP" >> $TOMMATH_CUTOFFS_H || die "(km) Appending to $TOMMATH_CUTOFFS_H" $?
+TMP=$(median $FILE_NAME 2 $i)
+echo "#define MP_DEFAULT_KARATSUBA_SQR_CUTOFF $TMP"
+echo "#define MP_DEFAULT_KARATSUBA_SQR_CUTOFF $TMP" >> $TOMMATH_CUTOFFS_H || die "(ks) Appending to $TOMMATH_CUTOFFS_H" $?
+TMP=$(median $FILE_NAME 3 $i)
+echo "#define MP_DEFAULT_TOOM_MUL_CUTOFF $TMP"
+echo "#define MP_DEFAULT_TOOM_MUL_CUTOFF $TMP" >> $TOMMATH_CUTOFFS_H || die "(tc3m) Appending to $TOMMATH_CUTOFFS_H" $?
+TMP=$(median $FILE_NAME 4 $i)
+echo "#define MP_DEFAULT_TOOM_SQR_CUTOFF $TMP"
+echo "#define MP_DEFAULT_TOOM_SQR_CUTOFF $TMP" >> $TOMMATH_CUTOFFS_H || die "(tc3s) Appending to $TOMMATH_CUTOFFS_H" $?
+
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/gen.pl b/third_party/heimdal/lib/hcrypto/libtommath/gen.pl
new file mode 100644
index 0000000..332994d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/gen.pl
@@ -0,0 +1,20 @@
+#!/usr/bin/perl -w
+#
+# Generates a "single file" you can use to quickly
+# add the whole source without any makefile troubles
+#
+use strict;
+use warnings;
+
+open(my $out, '>', 'mpi.c') or die "Couldn't open mpi.c for writing: $!";
+foreach my $filename (glob 'bn*.c') {
+ open(my $src, '<', $filename) or die "Couldn't open $filename for reading: $!";
+ print {$out} "/* Start: $filename */\n";
+ print {$out} $_ while <$src>;
+ print {$out} "\n/* End: $filename */\n\n";
+ close $src or die "Error closing $filename after reading: $!";
+}
+print {$out} "\n/* EOF */\n";
+close $out or die "Error closing mpi.c after writing: $!";
+
+system('perl -pli -e "s/\s*$//" mpi.c');
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/helper.pl b/third_party/heimdal/lib/hcrypto/libtommath/helper.pl
new file mode 100755
index 0000000..e60c1a7
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/helper.pl
@@ -0,0 +1,482 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+
+use Getopt::Long;
+use File::Find 'find';
+use File::Basename 'basename';
+use File::Glob 'bsd_glob';
+
+sub read_file {
+ my $f = shift;
+ open my $fh, "<", $f or die "FATAL: read_rawfile() cannot open file '$f': $!";
+ binmode $fh;
+ return do { local $/; <$fh> };
+}
+
+sub write_file {
+ my ($f, $data) = @_;
+ die "FATAL: write_file() no data" unless defined $data;
+ open my $fh, ">", $f or die "FATAL: write_file() cannot open file '$f': $!";
+ binmode $fh;
+ print $fh $data or die "FATAL: write_file() cannot write to '$f': $!";
+ close $fh or die "FATAL: write_file() cannot close '$f': $!";
+ return;
+}
+
+sub sanitize_comments {
+ my($content) = @_;
+ $content =~ s{/\*(.*?)\*/}{my $x=$1; $x =~ s/\w/x/g; "/*$x*/";}egs;
+ return $content;
+}
+
+sub check_source {
+ my @all_files = (
+ bsd_glob("makefile*"),
+ bsd_glob("*.{h,c,sh,pl}"),
+ bsd_glob("*/*.{h,c,sh,pl}"),
+ );
+
+ my $fails = 0;
+ for my $file (sort @all_files) {
+ my $troubles = {};
+ my $lineno = 1;
+ my $content = read_file($file);
+ $content = sanitize_comments $content;
+ push @{$troubles->{crlf_line_end}}, '?' if $content =~ /\r/;
+ for my $l (split /\n/, $content) {
+ push @{$troubles->{merge_conflict}}, $lineno if $l =~ /^(<<<<<<<|=======|>>>>>>>)([^<=>]|$)/;
+ push @{$troubles->{trailing_space}}, $lineno if $l =~ / $/;
+ push @{$troubles->{tab}}, $lineno if $l =~ /\t/ && basename($file) !~ /^makefile/i;
+ push @{$troubles->{non_ascii_char}}, $lineno if $l =~ /[^[:ascii:]]/;
+ push @{$troubles->{cpp_comment}}, $lineno if $file =~ /\.(c|h)$/ && ($l =~ /\s\/\// || $l =~ /\/\/\s/);
+ # we prefer using XMALLOC, XFREE, XREALLOC, XCALLOC ...
+ push @{$troubles->{unwanted_malloc}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\bmalloc\s*\(/;
+ push @{$troubles->{unwanted_realloc}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\brealloc\s*\(/;
+ push @{$troubles->{unwanted_calloc}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\bcalloc\s*\(/;
+ push @{$troubles->{unwanted_free}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\bfree\s*\(/;
+ # and we probably want to also avoid the following
+ push @{$troubles->{unwanted_memcpy}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\bmemcpy\s*\(/;
+ push @{$troubles->{unwanted_memset}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\bmemset\s*\(/;
+ push @{$troubles->{unwanted_memcpy}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\bmemcpy\s*\(/;
+ push @{$troubles->{unwanted_memmove}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\bmemmove\s*\(/;
+ push @{$troubles->{unwanted_memcmp}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\bmemcmp\s*\(/;
+ push @{$troubles->{unwanted_strcmp}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\bstrcmp\s*\(/;
+ push @{$troubles->{unwanted_strcpy}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\bstrcpy\s*\(/;
+ push @{$troubles->{unwanted_strncpy}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\bstrncpy\s*\(/;
+ push @{$troubles->{unwanted_clock}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\bclock\s*\(/;
+ push @{$troubles->{unwanted_qsort}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\bqsort\s*\(/;
+ push @{$troubles->{sizeof_no_brackets}}, $lineno if $file =~ /^[^\/]+\.c$/ && $l =~ /\bsizeof\s*[^\(]/;
+ if ($file =~ m|^[^\/]+\.c$| && $l =~ /^static(\s+[a-zA-Z0-9_]+)+\s+([a-zA-Z0-9_]+)\s*\(/) {
+ my $funcname = $2;
+ # static functions should start with s_
+ push @{$troubles->{staticfunc_name}}, "$lineno($funcname)" if $funcname !~ /^s_/;
+ }
+ $lineno++;
+ }
+ for my $k (sort keys %$troubles) {
+ warn "[$k] $file line:" . join(",", @{$troubles->{$k}}) . "\n";
+ $fails++;
+ }
+ }
+
+ warn( $fails > 0 ? "check-source: FAIL $fails\n" : "check-source: PASS\n" );
+ return $fails;
+}
+
+sub check_comments {
+ my $fails = 0;
+ my $first_comment = <<'MARKER';
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+MARKER
+ #my @all_files = (bsd_glob("*.{h,c}"), bsd_glob("*/*.{h,c}"));
+ my @all_files = (bsd_glob("*.{h,c}"));
+ for my $f (@all_files) {
+ my $txt = read_file($f);
+ if ($txt !~ /\Q$first_comment\E/s) {
+ warn "[first_comment] $f\n";
+ $fails++;
+ }
+ }
+ warn( $fails > 0 ? "check-comments: FAIL $fails\n" : "check-comments: PASS\n" );
+ return $fails;
+}
+
+sub check_doc {
+ my $fails = 0;
+ my $tex = read_file('doc/bn.tex');
+ my $tmh = read_file('tommath.h');
+ my @functions = $tmh =~ /\n\s*[a-zA-Z0-9_* ]+?(mp_[a-z0-9_]+)\s*\([^\)]+\)\s*;/sg;
+ my @macros = $tmh =~ /\n\s*#define\s+([a-z0-9_]+)\s*\([^\)]+\)/sg;
+ for my $n (sort @functions) {
+ (my $nn = $n) =~ s/_/\\_/g; # mp_sub_d >> mp\_sub\_d
+ if ($tex !~ /index\Q{$nn}\E/) {
+ warn "[missing_doc_for_function] $n\n";
+ $fails++
+ }
+ }
+ for my $n (sort @macros) {
+ (my $nn = $n) =~ s/_/\\_/g; # mp_iszero >> mp\_iszero
+ if ($tex !~ /index\Q{$nn}\E/) {
+ warn "[missing_doc_for_macro] $n\n";
+ $fails++
+ }
+ }
+ warn( $fails > 0 ? "check_doc: FAIL $fails\n" : "check-doc: PASS\n" );
+ return $fails;
+}
+
+sub prepare_variable {
+ my ($varname, @list) = @_;
+ my $output = "$varname=";
+ my $len = length($output);
+ foreach my $obj (sort @list) {
+ $len = $len + length $obj;
+ $obj =~ s/\*/\$/;
+ if ($len > 100) {
+ $output .= "\\\n";
+ $len = length $obj;
+ }
+ $output .= $obj . ' ';
+ }
+ $output =~ s/ $//;
+ return $output;
+}
+
+sub prepare_msvc_files_xml {
+ my ($all, $exclude_re, $targets) = @_;
+ my $last = [];
+ my $depth = 2;
+
+ # sort files in the same order as visual studio (ugly, I know)
+ my @parts = ();
+ for my $orig (@$all) {
+ my $p = $orig;
+ $p =~ s|/|/~|g;
+ $p =~ s|/~([^/]+)$|/$1|g;
+ my @l = map { sprintf "% -99s", $_ } split /\//, $p;
+ push @parts, [ $orig, join(':', @l) ];
+ }
+ my @sorted = map { $_->[0] } sort { $a->[1] cmp $b->[1] } @parts;
+
+ my $files = "<Files>\r\n";
+ for my $full (@sorted) {
+ my @items = split /\//, $full; # split by '/'
+ $full =~ s|/|\\|g; # replace '/' bt '\'
+ shift @items; # drop first one (src)
+ pop @items; # drop last one (filename.ext)
+ my $current = \@items;
+ if (join(':', @$current) ne join(':', @$last)) {
+ my $common = 0;
+ $common++ while ($last->[$common] && $current->[$common] && $last->[$common] eq $current->[$common]);
+ my $back = @$last - $common;
+ if ($back > 0) {
+ $files .= ("\t" x --$depth) . "</Filter>\r\n" for (1..$back);
+ }
+ my $fwd = [ @$current ]; splice(@$fwd, 0, $common);
+ for my $i (0..scalar(@$fwd) - 1) {
+ $files .= ("\t" x $depth) . "<Filter\r\n";
+ $files .= ("\t" x $depth) . "\tName=\"$fwd->[$i]\"\r\n";
+ $files .= ("\t" x $depth) . "\t>\r\n";
+ $depth++;
+ }
+ $last = $current;
+ }
+ $files .= ("\t" x $depth) . "<File\r\n";
+ $files .= ("\t" x $depth) . "\tRelativePath=\"$full\"\r\n";
+ $files .= ("\t" x $depth) . "\t>\r\n";
+ if ($full =~ $exclude_re) {
+ for (@$targets) {
+ $files .= ("\t" x $depth) . "\t<FileConfiguration\r\n";
+ $files .= ("\t" x $depth) . "\t\tName=\"$_\"\r\n";
+ $files .= ("\t" x $depth) . "\t\tExcludedFromBuild=\"true\"\r\n";
+ $files .= ("\t" x $depth) . "\t\t>\r\n";
+ $files .= ("\t" x $depth) . "\t\t<Tool\r\n";
+ $files .= ("\t" x $depth) . "\t\t\tName=\"VCCLCompilerTool\"\r\n";
+ $files .= ("\t" x $depth) . "\t\t\tAdditionalIncludeDirectories=\"\"\r\n";
+ $files .= ("\t" x $depth) . "\t\t\tPreprocessorDefinitions=\"\"\r\n";
+ $files .= ("\t" x $depth) . "\t\t/>\r\n";
+ $files .= ("\t" x $depth) . "\t</FileConfiguration>\r\n";
+ }
+ }
+ $files .= ("\t" x $depth) . "</File>\r\n";
+ }
+ $files .= ("\t" x --$depth) . "</Filter>\r\n" for (@$last);
+ $files .= "\t</Files>";
+ return $files;
+}
+
+sub patch_file {
+ my ($content, @variables) = @_;
+ for my $v (@variables) {
+ if ($v =~ /^([A-Z0-9_]+)\s*=.*$/si) {
+ my $name = $1;
+ $content =~ s/\n\Q$name\E\b.*?[^\\]\n/\n$v\n/s;
+ }
+ else {
+ die "patch_file failed: " . substr($v, 0, 30) . "..";
+ }
+ }
+ return $content;
+}
+
+sub process_makefiles {
+ my $write = shift;
+ my $changed_count = 0;
+ my @o = map { my $x = $_; $x =~ s/\.c$/.o/; $x } bsd_glob("*.c");
+ my @all = bsd_glob("*.{c,h}");
+
+ my $var_o = prepare_variable("OBJECTS", @o);
+ (my $var_obj = $var_o) =~ s/\.o\b/.obj/sg;
+
+ # update MSVC project files
+ my $msvc_files = prepare_msvc_files_xml(\@all, qr/NOT_USED_HERE/, ['Debug|Win32', 'Release|Win32', 'Debug|x64', 'Release|x64']);
+ for my $m (qw/libtommath_VS2008.vcproj/) {
+ my $old = read_file($m);
+ my $new = $old;
+ $new =~ s|<Files>.*</Files>|$msvc_files|s;
+ if ($old ne $new) {
+ write_file($m, $new) if $write;
+ warn "changed: $m\n";
+ $changed_count++;
+ }
+ }
+
+ # update OBJECTS + HEADERS in makefile*
+ for my $m (qw/ makefile makefile.shared makefile_include.mk makefile.msvc makefile.unix makefile.mingw /) {
+ my $old = read_file($m);
+ my $new = $m eq 'makefile.msvc' ? patch_file($old, $var_obj)
+ : patch_file($old, $var_o);
+ if ($old ne $new) {
+ write_file($m, $new) if $write;
+ warn "changed: $m\n";
+ $changed_count++;
+ }
+ }
+
+ if ($write) {
+ return 0; # no failures
+ }
+ else {
+ warn( $changed_count > 0 ? "check-makefiles: FAIL $changed_count\n" : "check-makefiles: PASS\n" );
+ return $changed_count;
+ }
+}
+
+sub draw_func
+{
+ my ($deplist, $depmap, $out, $indent, $funcslist) = @_;
+ my @funcs = split ',', $funcslist;
+ # try this if you want to have a look at a minimized version of the callgraph without all the trivial functions
+ #if ($deplist =~ /$funcs[0]/ || $funcs[0] =~ /BN_MP_(ADD|SUB|CLEAR|CLEAR_\S+|DIV|MUL|COPY|ZERO|GROW|CLAMP|INIT|INIT_\S+|SET|ABS|CMP|CMP_D|EXCH)_C/) {
+ if ($deplist =~ /$funcs[0]/) {
+ return $deplist;
+ } else {
+ $deplist = $deplist . $funcs[0];
+ }
+ if ($indent == 0) {
+ } elsif ($indent >= 1) {
+ print {$out} '| ' x ($indent - 1) . '+--->';
+ }
+ print {$out} $funcs[0] . "\n";
+ shift @funcs;
+ my $olddeplist = $deplist;
+ foreach my $i (@funcs) {
+ $deplist = draw_func($deplist, $depmap, $out, $indent + 1, ${$depmap}{$i}) if exists ${$depmap}{$i};
+ }
+ return $olddeplist;
+}
+
+sub update_dep
+{
+ #open class file and write preamble
+ open(my $class, '>', 'tommath_class.h') or die "Couldn't open tommath_class.h for writing\n";
+ print {$class} << 'EOS';
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#if !(defined(LTM1) && defined(LTM2) && defined(LTM3))
+#define LTM_INSIDE
+#if defined(LTM2)
+# define LTM3
+#endif
+#if defined(LTM1)
+# define LTM2
+#endif
+#define LTM1
+#if defined(LTM_ALL)
+EOS
+
+ foreach my $filename (glob 'bn*.c') {
+ my $define = $filename;
+
+ print "Processing $filename\n";
+
+ # convert filename to upper case so we can use it as a define
+ $define =~ tr/[a-z]/[A-Z]/;
+ $define =~ tr/\./_/;
+ print {$class} "# define $define\n";
+
+ # now copy text and apply #ifdef as required
+ my $apply = 0;
+ open(my $src, '<', $filename);
+ open(my $out, '>', 'tmp');
+
+ # first line will be the #ifdef
+ my $line = <$src>;
+ if ($line =~ /include/) {
+ print {$out} $line;
+ } else {
+ print {$out} << "EOS";
+#include "tommath_private.h"
+#ifdef $define
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+$line
+EOS
+ $apply = 1;
+ }
+ while (<$src>) {
+ if ($_ !~ /tommath\.h/) {
+ print {$out} $_;
+ }
+ }
+ if ($apply == 1) {
+ print {$out} "#endif\n";
+ }
+ close $src;
+ close $out;
+
+ unlink $filename;
+ rename 'tmp', $filename;
+ }
+ print {$class} "#endif\n#endif\n";
+
+ # now do classes
+ my %depmap;
+ foreach my $filename (glob 'bn*.c') {
+ my $content;
+ if ($filename =~ "bn_deprecated.c") {
+ open(my $src, '<', $filename) or die "Can't open source file!\n";
+ read $src, $content, -s $src;
+ close $src;
+ } else {
+ my $cc = $ENV{'CC'} || 'gcc';
+ $content = `$cc -E -x c -DLTM_ALL $filename`;
+ $content =~ s/^# 1 "$filename".*?^# 2 "$filename"//ms;
+ }
+
+ # convert filename to upper case so we can use it as a define
+ $filename =~ tr/[a-z]/[A-Z]/;
+ $filename =~ tr/\./_/;
+
+ print {$class} "#if defined($filename)\n";
+ my $list = $filename;
+
+ # strip comments
+ $content =~ s{/\*.*?\*/}{}gs;
+
+ # scan for mp_* and make classes
+ my @deps = ();
+ foreach my $line (split /\n/, $content) {
+ while ($line =~ /(fast_)?(s_)?mp\_[a-z_0-9]*((?=\;)|(?=\())|(?<=\()mp\_[a-z_0-9]*(?=\()/g) {
+ my $a = $&;
+ next if $a eq "mp_err";
+ $a =~ tr/[a-z]/[A-Z]/;
+ $a = 'BN_' . $a . '_C';
+ push @deps, $a;
+ }
+ }
+ @deps = sort(@deps);
+ foreach my $a (@deps) {
+ if ($list !~ /$a/) {
+ print {$class} "# define $a\n";
+ }
+ $list = $list . ',' . $a;
+ }
+ $depmap{$filename} = $list;
+
+ print {$class} "#endif\n\n";
+ }
+
+ print {$class} << 'EOS';
+#ifdef LTM_INSIDE
+#undef LTM_INSIDE
+#ifdef LTM3
+# define LTM_LAST
+#endif
+
+#include "tommath_superclass.h"
+#include "tommath_class.h"
+#else
+# define LTM_LAST
+#endif
+EOS
+ close $class;
+
+ #now let's make a cool call graph...
+
+ open(my $out, '>', 'callgraph.txt');
+ foreach (sort keys %depmap) {
+ draw_func("", \%depmap, $out, 0, $depmap{$_});
+ print {$out} "\n\n";
+ }
+ close $out;
+
+ return 0;
+}
+
+sub generate_def {
+ my @files = split /\n/, `git ls-files`;
+ @files = grep(/\.c/, @files);
+ @files = map { my $x = $_; $x =~ s/^bn_|\.c$//g; $x; } @files;
+ @files = grep(!/mp_radix_smap/, @files);
+
+ push(@files, qw(mp_set_int mp_set_long mp_set_long_long mp_get_int mp_get_long mp_get_long_long mp_init_set_int));
+
+ my $files = join("\n ", sort(grep(/^mp_/, @files)));
+ write_file "tommath.def", "; libtommath
+;
+; Use this command to produce a 32-bit .lib file, for use in any MSVC version
+; lib -machine:X86 -name:libtommath.dll -def:tommath.def -out:tommath.lib
+; Use this command to produce a 64-bit .lib file, for use in any MSVC version
+; lib -machine:X64 -name:libtommath.dll -def:tommath.def -out:tommath.lib
+;
+EXPORTS
+ $files
+";
+ return 0;
+}
+
+sub die_usage {
+ die <<"MARKER";
+usage: $0 -s OR $0 --check-source
+ $0 -o OR $0 --check-comments
+ $0 -m OR $0 --check-makefiles
+ $0 -a OR $0 --check-all
+ $0 -u OR $0 --update-files
+MARKER
+}
+
+GetOptions( "s|check-source" => \my $check_source,
+ "o|check-comments" => \my $check_comments,
+ "m|check-makefiles" => \my $check_makefiles,
+ "d|check-doc" => \my $check_doc,
+ "a|check-all" => \my $check_all,
+ "u|update-files" => \my $update_files,
+ "h|help" => \my $help
+ ) or die_usage;
+
+my $failure;
+$failure ||= check_source() if $check_all || $check_source;
+$failure ||= check_comments() if $check_all || $check_comments;
+$failure ||= check_doc() if $check_doc; # temporarily excluded from --check-all
+$failure ||= process_makefiles(0) if $check_all || $check_makefiles;
+$failure ||= process_makefiles(1) if $update_files;
+$failure ||= update_dep() if $update_files;
+$failure ||= generate_def() if $update_files;
+
+die_usage unless defined $failure;
+exit $failure ? 1 : 0;
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/libtommath.pc.in b/third_party/heimdal/lib/hcrypto/libtommath/libtommath.pc.in
new file mode 100644
index 0000000..099b1cd
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/libtommath.pc.in
@@ -0,0 +1,10 @@
+prefix=@to-be-replaced@
+exec_prefix=${prefix}
+libdir=${exec_prefix}/lib
+includedir=${prefix}/include
+
+Name: LibTomMath
+Description: public domain library for manipulating large integer numbers
+Version: @to-be-replaced@
+Libs: -L${libdir} -ltommath
+Cflags: -I${includedir}
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/libtommath_VS2008.sln b/third_party/heimdal/lib/hcrypto/libtommath/libtommath_VS2008.sln
new file mode 100644
index 0000000..6bfc159
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/libtommath_VS2008.sln
@@ -0,0 +1,29 @@
+
+Microsoft Visual Studio Solution File, Format Version 10.00
+# Visual Studio 2008
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tommath", "libtommath_VS2008.vcproj", "{42109FEE-B0B9-4FCD-9E56-2863BF8C55D2}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Win32 = Debug|Win32
+ Debug|x64 = Debug|x64
+ Release|Win32 = Release|Win32
+ Release|x64 = Release|x64
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {42109FEE-B0B9-4FCD-9E56-2863BF8C55D2}.Debug|Win32.ActiveCfg = Debug|Win32
+ {42109FEE-B0B9-4FCD-9E56-2863BF8C55D2}.Debug|Win32.Build.0 = Debug|Win32
+ {42109FEE-B0B9-4FCD-9E56-2863BF8C55D2}.Debug|x64.ActiveCfg = Debug|x64
+ {42109FEE-B0B9-4FCD-9E56-2863BF8C55D2}.Debug|x64.Build.0 = Debug|x64
+ {42109FEE-B0B9-4FCD-9E56-2863BF8C55D2}.Release|Win32.ActiveCfg = Release|Win32
+ {42109FEE-B0B9-4FCD-9E56-2863BF8C55D2}.Release|Win32.Build.0 = Release|Win32
+ {42109FEE-B0B9-4FCD-9E56-2863BF8C55D2}.Release|x64.ActiveCfg = Release|x64
+ {42109FEE-B0B9-4FCD-9E56-2863BF8C55D2}.Release|x64.Build.0 = Release|x64
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {83B84178-7B4F-4B78-9C5D-17B8201D5B61}
+ EndGlobalSection
+EndGlobal
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/libtommath_VS2008.vcproj b/third_party/heimdal/lib/hcrypto/libtommath/libtommath_VS2008.vcproj
new file mode 100644
index 0000000..67cc89b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/libtommath_VS2008.vcproj
@@ -0,0 +1,966 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="9.00"
+ Name="tommath"
+ ProjectGUID="{42109FEE-B0B9-4FCD-9E56-2863BF8C55D2}"
+ RootNamespace="tommath"
+ TargetFrameworkVersion="0"
+ >
+ <Platforms>
+ <Platform
+ Name="Win32"
+ />
+ <Platform
+ Name="x64"
+ />
+ </Platforms>
+ <ToolFiles>
+ </ToolFiles>
+ <Configurations>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory="MSVC_$(PlatformName)_$(ConfigurationName)"
+ IntermediateDirectory="MSVC_$(PlatformName)_$(ConfigurationName)\Intermediate"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="0"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories="."
+ PreprocessorDefinitions="WIN32;_DEBUG;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_DEPRECATE"
+ MinimalRebuild="true"
+ ExceptionHandling="0"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ PrecompiledHeaderFile="$(IntDir)\libtomcrypt.pch"
+ AssemblerListingLocation="$(IntDir)\"
+ ObjectFile="$(IntDir)\"
+ ProgramDataBaseFileName="$(IntDir)\"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ DebugInformationFormat="4"
+ CompileAs="1"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile="$(OutDir)\tommath.lib"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile="$(OutDir)\tommath.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Debug|x64"
+ OutputDirectory="MSVC_$(PlatformName)_$(ConfigurationName)"
+ IntermediateDirectory="MSVC_$(PlatformName)_$(ConfigurationName)\Intermediate"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="0"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ TargetEnvironment="3"
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories="."
+ PreprocessorDefinitions="WIN32;_DEBUG;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_DEPRECATE"
+ MinimalRebuild="true"
+ ExceptionHandling="0"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ PrecompiledHeaderFile="$(IntDir)\libtomcrypt.pch"
+ AssemblerListingLocation="$(IntDir)\"
+ ObjectFile="$(IntDir)\"
+ ProgramDataBaseFileName="$(IntDir)\"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ DebugInformationFormat="3"
+ CompileAs="1"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile="$(OutDir)\tommath.lib"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile="$(OutDir)\tommath.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory="MSVC_$(PlatformName)_$(ConfigurationName)"
+ IntermediateDirectory="MSVC_$(PlatformName)_$(ConfigurationName)\Intermediate"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="0"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="."
+ PreprocessorDefinitions="WIN32;NDEBUG;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_DEPRECATE"
+ StringPooling="true"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="true"
+ PrecompiledHeaderFile="$(IntDir)\libtomcrypt.pch"
+ AssemblerListingLocation="$(IntDir)\"
+ ObjectFile="$(IntDir)\"
+ ProgramDataBaseFileName="$(IntDir)\"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile="$(OutDir)\tommath.lib"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile="$(OutDir)\tommath.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Release|x64"
+ OutputDirectory="MSVC_$(PlatformName)_$(ConfigurationName)"
+ IntermediateDirectory="MSVC_$(PlatformName)_$(ConfigurationName)\Intermediate"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="0"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ TargetEnvironment="3"
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="."
+ PreprocessorDefinitions="WIN32;NDEBUG;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_DEPRECATE"
+ StringPooling="true"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="true"
+ PrecompiledHeaderFile="$(IntDir)\libtomcrypt.pch"
+ AssemblerListingLocation="$(IntDir)\"
+ ObjectFile="$(IntDir)\"
+ ProgramDataBaseFileName="$(IntDir)\"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile="$(OutDir)\tommath.lib"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile="$(OutDir)\tommath.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <File
+ RelativePath="bn_cutoffs.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_deprecated.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_2expt.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_abs.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_add.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_add_d.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_addmod.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_and.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_clamp.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_clear.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_clear_multi.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_cmp.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_cmp_d.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_cmp_mag.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_cnt_lsb.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_complement.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_copy.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_count_bits.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_decr.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_div.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_div_2.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_div_2d.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_div_3.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_div_d.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_dr_is_modulus.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_dr_reduce.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_dr_setup.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_error_to_string.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_exch.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_expt_u32.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_exptmod.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_exteuclid.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_fread.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_from_sbin.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_from_ubin.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_fwrite.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_gcd.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_get_double.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_get_i32.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_get_i64.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_get_l.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_get_ll.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_get_mag_u32.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_get_mag_u64.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_get_mag_ul.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_get_mag_ull.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_grow.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_incr.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_init.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_init_copy.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_init_i32.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_init_i64.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_init_l.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_init_ll.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_init_multi.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_init_set.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_init_size.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_init_u32.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_init_u64.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_init_ul.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_init_ull.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_invmod.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_is_square.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_iseven.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_isodd.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_kronecker.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_lcm.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_log_u32.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_lshd.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_mod.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_mod_2d.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_mod_d.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_montgomery_calc_normalization.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_montgomery_reduce.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_montgomery_setup.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_mul.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_mul_2.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_mul_2d.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_mul_d.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_mulmod.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_neg.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_or.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_pack.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_pack_count.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_prime_fermat.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_prime_frobenius_underwood.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_prime_is_prime.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_prime_miller_rabin.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_prime_next_prime.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_prime_rabin_miller_trials.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_prime_rand.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_prime_strong_lucas_selfridge.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_radix_size.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_radix_smap.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_rand.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_read_radix.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_reduce.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_reduce_2k.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_reduce_2k_l.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_reduce_2k_setup.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_reduce_2k_setup_l.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_reduce_is_2k.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_reduce_is_2k_l.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_reduce_setup.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_root_u32.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_rshd.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_sbin_size.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_set.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_set_double.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_set_i32.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_set_i64.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_set_l.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_set_ll.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_set_u32.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_set_u64.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_set_ul.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_set_ull.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_shrink.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_signed_rsh.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_sqr.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_sqrmod.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_sqrt.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_sqrtmod_prime.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_sub.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_sub_d.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_submod.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_to_radix.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_to_sbin.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_to_ubin.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_ubin_size.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_unpack.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_xor.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_mp_zero.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_prime_tab.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_add.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_balance_mul.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_exptmod.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_exptmod_fast.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_get_bit.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_invmod_fast.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_invmod_slow.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_karatsuba_mul.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_karatsuba_sqr.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_montgomery_reduce_fast.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_mul_digs.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_mul_digs_fast.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_mul_high_digs.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_mul_high_digs_fast.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_prime_is_divisible.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_rand_jenkins.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_rand_platform.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_reverse.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_sqr.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_sqr_fast.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_sub.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_toom_mul.c"
+ >
+ </File>
+ <File
+ RelativePath="bn_s_mp_toom_sqr.c"
+ >
+ </File>
+ <File
+ RelativePath="tommath.h"
+ >
+ </File>
+ <File
+ RelativePath="tommath_class.h"
+ >
+ </File>
+ <File
+ RelativePath="tommath_cutoffs.h"
+ >
+ </File>
+ <File
+ RelativePath="tommath_private.h"
+ >
+ </File>
+ <File
+ RelativePath="tommath_superclass.h"
+ >
+ </File>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/README b/third_party/heimdal/lib/hcrypto/libtommath/logs/README
new file mode 100644
index 0000000..ea20c81
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/README
@@ -0,0 +1,13 @@
+To use the pretty graphs you have to first build/run the ltmtest from the root directory of the package.
+Todo this type
+
+make timing ; ltmtest
+
+in the root. It will run for a while [about ten minutes on most PCs] and produce a series of .log files in logs/.
+
+After doing that run "gnuplot graphs.dem" to make the PNGs. If you managed todo that all so far just open index.html to view
+them all :-)
+
+Have fun
+
+Tom \ No newline at end of file
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/add.log b/third_party/heimdal/lib/hcrypto/libtommath/logs/add.log
new file mode 100644
index 0000000..0ed7b70
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/add.log
@@ -0,0 +1,16 @@
+ 480 48
+ 960 61
+ 1440 82
+ 1920 97
+ 2400 106
+ 2880 112
+ 3360 127
+ 3840 130
+ 4320 146
+ 4800 157
+ 5280 174
+ 5760 185
+ 6240 200
+ 6720 214
+ 7200 230
+ 7680 244
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/addsub.png b/third_party/heimdal/lib/hcrypto/libtommath/logs/addsub.png
new file mode 100644
index 0000000..b8ffef7
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/addsub.png
Binary files differ
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/expt.log b/third_party/heimdal/lib/hcrypto/libtommath/logs/expt.log
new file mode 100644
index 0000000..2e5ee30
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/expt.log
@@ -0,0 +1,7 @@
+ 513 446633
+ 769 1110301
+ 1025 2414927
+ 2049 14870787
+ 2561 26299761
+ 3073 44323310
+ 4097 98934292
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/expt.png b/third_party/heimdal/lib/hcrypto/libtommath/logs/expt.png
new file mode 100644
index 0000000..27c53ee
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/expt.png
Binary files differ
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/expt_2k.log b/third_party/heimdal/lib/hcrypto/libtommath/logs/expt_2k.log
new file mode 100644
index 0000000..140b92f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/expt_2k.log
@@ -0,0 +1,6 @@
+ 521 533515
+ 607 675230
+ 1279 2560713
+ 2203 7468422
+ 3217 17314246
+ 4253 33899969
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/expt_2kl.log b/third_party/heimdal/lib/hcrypto/libtommath/logs/expt_2kl.log
new file mode 100644
index 0000000..1dc495f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/expt_2kl.log
@@ -0,0 +1,3 @@
+ 1024 2210287
+ 2048 7940364
+ 4096 35903891
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/expt_dr.log b/third_party/heimdal/lib/hcrypto/libtommath/logs/expt_dr.log
new file mode 100644
index 0000000..3752ea8
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/expt_dr.log
@@ -0,0 +1,7 @@
+ 532 642330
+ 784 1138699
+ 1036 1972796
+ 1540 3912241
+ 2072 7075836
+ 3080 16420867
+ 4116 32477173
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/graphs.dem b/third_party/heimdal/lib/hcrypto/libtommath/logs/graphs.dem
new file mode 100644
index 0000000..538e5c0
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/graphs.dem
@@ -0,0 +1,16 @@
+set terminal png
+set ylabel "Cycles per Operation"
+set xlabel "Operand size (bits)"
+
+set output "addsub.png"
+plot 'add.log' smooth bezier title "Addition", 'sub.log' smooth bezier title "Subtraction"
+
+set output "mult.png"
+plot 'sqr.log' smooth bezier title "Squaring (without Karatsuba)", 'sqr_kara.log' smooth bezier title "Squaring (Karatsuba)", 'mult.log' smooth bezier title "Multiplication (without Karatsuba)", 'mult_kara.log' smooth bezier title "Multiplication (Karatsuba)"
+
+set output "expt.png"
+plot 'expt.log' smooth bezier title "Exptmod (Montgomery)", 'expt_dr.log' smooth bezier title "Exptmod (Dimminished Radix)", 'expt_2k.log' smooth bezier title "Exptmod (2k Reduction)"
+
+set output "invmod.png"
+plot 'invmod.log' smooth bezier title "Modular Inverse"
+
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/index.html b/third_party/heimdal/lib/hcrypto/libtommath/logs/index.html
new file mode 100644
index 0000000..4b68c25
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/index.html
@@ -0,0 +1,27 @@
+<html>
+<head>
+<title>LibTomMath Log Plots</title>
+</head>
+<body>
+
+<h1>Addition and Subtraction</h1>
+<center><img src=addsub.png></center>
+<hr>
+
+<h1>Multipliers</h1>
+<center><img src=mult.png></center>
+<hr>
+
+<h1>Exptmod</h1>
+<center><img src=expt.png></center>
+<hr>
+
+<h1>Modular Inverse</h1>
+<center><img src=invmod.png></center>
+<hr>
+
+</body>
+</html>
+/* $Source: /cvs/libtom/libtommath/logs/index.html,v $ */
+/* $Revision: 1.2 $ */
+/* $Date: 2005/05/05 14:38:47 $ */
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/invmod.log b/third_party/heimdal/lib/hcrypto/libtommath/logs/invmod.log
new file mode 100644
index 0000000..7d22449
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/invmod.log
@@ -0,0 +1,8 @@
+ 240 58197
+ 480 86617
+ 720 255279
+ 960 399626
+ 1200 533330
+ 1440 470046
+ 1680 906754
+ 1920 1132009
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/invmod.png b/third_party/heimdal/lib/hcrypto/libtommath/logs/invmod.png
new file mode 100644
index 0000000..5c09e90
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/invmod.png
Binary files differ
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/mult.log b/third_party/heimdal/lib/hcrypto/libtommath/logs/mult.log
new file mode 100644
index 0000000..841b40b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/mult.log
@@ -0,0 +1,84 @@
+ 240 114
+ 360 182
+ 480 273
+ 600 364
+ 717 471
+ 840 597
+ 960 737
+ 1080 881
+ 1196 1041
+ 1318 1215
+ 1438 1405
+ 1559 1600
+ 1679 1812
+ 1800 2045
+ 1918 2289
+ 2040 2534
+ 2160 2800
+ 2280 3067
+ 2397 3375
+ 2520 3678
+ 2640 4007
+ 2759 4325
+ 2880 4851
+ 3000 5200
+ 3117 5557
+ 3239 5938
+ 3356 6332
+ 3480 6741
+ 3600 7168
+ 3720 7597
+ 3840 8054
+ 3960 8514
+ 4079 8956
+ 4198 9451
+ 4320 9976
+ 4440 10457
+ 4560 10973
+ 4679 11535
+ 4797 12085
+ 4920 12639
+ 5040 13235
+ 5160 13832
+ 5279 14454
+ 5400 15063
+ 5519 15657
+ 5640 16339
+ 5760 16992
+ 5879 17676
+ 6000 18380
+ 6120 18022
+ 6237 18567
+ 6360 19259
+ 6479 19929
+ 6599 20686
+ 6719 21180
+ 6840 22121
+ 6960 22741
+ 7080 23664
+ 7200 24315
+ 7320 25107
+ 7439 25945
+ 7560 26557
+ 7680 27527
+ 7799 28341
+ 7920 30761
+ 8040 31648
+ 8159 32628
+ 8280 33498
+ 8400 34508
+ 8520 33657
+ 8640 34566
+ 8758 35203
+ 8878 36356
+ 9000 37379
+ 9119 38072
+ 9240 39390
+ 9360 48931
+ 9475 66682
+ 9600 72564
+ 9719 51493
+ 9840 52637
+ 9960 48247
+ 10080 49030
+ 10195 50592
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/mult.png b/third_party/heimdal/lib/hcrypto/libtommath/logs/mult.png
new file mode 100644
index 0000000..9681183
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/mult.png
Binary files differ
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/mult_kara.log b/third_party/heimdal/lib/hcrypto/libtommath/logs/mult_kara.log
new file mode 100644
index 0000000..91b59cb
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/mult_kara.log
@@ -0,0 +1,84 @@
+ 240 133
+ 360 250
+ 474 396
+ 599 585
+ 720 637
+ 840 1045
+ 960 1212
+ 1080 1543
+ 1196 1780
+ 1320 2005
+ 1436 2274
+ 1560 2446
+ 1680 1985
+ 1800 2368
+ 1920 2791
+ 2038 3620
+ 2160 3763
+ 2278 3444
+ 2400 4158
+ 2516 5869
+ 2640 6368
+ 2753 5384
+ 2876 7449
+ 3000 6471
+ 3114 8540
+ 3240 7217
+ 3360 9685
+ 3476 6759
+ 3599 8518
+ 3714 8911
+ 3840 12345
+ 3960 9787
+ 4079 11018
+ 4196 12033
+ 4319 12740
+ 4440 12471
+ 4558 15251
+ 4678 13353
+ 4798 15998
+ 4920 13395
+ 5040 13699
+ 5160 14552
+ 5280 14972
+ 5400 15825
+ 5520 16512
+ 5639 17379
+ 5757 17596
+ 5879 18350
+ 6000 18976
+ 6115 19601
+ 6240 20076
+ 6354 20515
+ 6480 21670
+ 6600 22312
+ 6716 22647
+ 6839 23437
+ 6960 24164
+ 7080 24723
+ 7199 25454
+ 7320 26092
+ 7440 26912
+ 7557 27521
+ 7677 28015
+ 7800 28885
+ 7919 29483
+ 8040 30115
+ 8160 31236
+ 8280 31975
+ 8400 30835
+ 8520 31565
+ 8639 32380
+ 8760 32760
+ 8879 33590
+ 8996 34553
+ 9119 35185
+ 9239 36146
+ 9358 36815
+ 9480 39630
+ 9596 43022
+ 9720 41219
+ 9840 41596
+ 9960 42354
+ 10080 43352
+ 10200 43915
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/sqr.log b/third_party/heimdal/lib/hcrypto/libtommath/logs/sqr.log
new file mode 100644
index 0000000..93234a1
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/sqr.log
@@ -0,0 +1,84 @@
+ 240 114
+ 359 174
+ 478 241
+ 600 311
+ 720 399
+ 840 494
+ 960 599
+ 1080 799
+ 1200 931
+ 1320 911
+ 1440 1016
+ 1560 1143
+ 1680 1281
+ 1800 1459
+ 1918 1617
+ 2039 1763
+ 2159 1913
+ 2279 2071
+ 2399 2240
+ 2518 2412
+ 2640 2600
+ 2760 2792
+ 2877 3008
+ 2999 3220
+ 3119 3405
+ 3239 3637
+ 3359 3859
+ 3480 4094
+ 3600 4328
+ 3717 4571
+ 3838 4840
+ 3960 5098
+ 4080 5349
+ 4200 5617
+ 4320 5891
+ 4440 6147
+ 4560 6444
+ 4680 6745
+ 4800 7057
+ 4918 7317
+ 5039 7637
+ 5160 12833
+ 5280 10098
+ 5397 8666
+ 5520 8999
+ 5639 9376
+ 5758 9727
+ 5880 9996
+ 6000 10427
+ 6118 10868
+ 6240 12218
+ 6359 14010
+ 6478 14838
+ 6593 16135
+ 6719 16503
+ 6840 13267
+ 6960 13648
+ 7080 14118
+ 7199 14525
+ 7320 14803
+ 7439 15378
+ 7558 15871
+ 7680 57530
+ 7800 59550
+ 7916 61091
+ 8039 63004
+ 8160 61136
+ 8279 62803
+ 8398 68671
+ 8520 71001
+ 8638 71537
+ 8759 74757
+ 8880 77164
+ 9000 78963
+ 9119 80982
+ 9239 83142
+ 9357 85292
+ 9480 88190
+ 9600 90343
+ 9718 86710
+ 9840 88818
+ 9954 91034
+ 10079 93350
+ 10197 95592
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/sqr_kara.log b/third_party/heimdal/lib/hcrypto/libtommath/logs/sqr_kara.log
new file mode 100644
index 0000000..da10897
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/sqr_kara.log
@@ -0,0 +1,84 @@
+ 240 115
+ 360 175
+ 480 241
+ 600 312
+ 719 397
+ 839 494
+ 960 597
+ 1080 696
+ 1200 794
+ 1320 908
+ 1439 1022
+ 1560 1141
+ 1678 1284
+ 1797 1461
+ 1918 1590
+ 2040 1764
+ 2160 1911
+ 2278 2072
+ 2399 2263
+ 2516 2425
+ 2640 2627
+ 2756 2809
+ 2880 3017
+ 3000 3220
+ 3119 3413
+ 3239 3627
+ 3359 3864
+ 3479 4087
+ 3600 4327
+ 3720 4603
+ 3840 4867
+ 3957 5095
+ 4079 5079
+ 4200 5623
+ 4319 5878
+ 4439 6177
+ 4560 6467
+ 4679 6749
+ 4800 7056
+ 4920 7384
+ 5039 7681
+ 5159 8004
+ 5280 8332
+ 5399 8664
+ 5520 8929
+ 5638 9340
+ 5760 9631
+ 5879 10109
+ 5999 10458
+ 6118 10816
+ 6240 11215
+ 6359 11550
+ 6478 11958
+ 6600 12390
+ 6718 12801
+ 6838 13197
+ 6959 13609
+ 7079 14033
+ 7199 16182
+ 7320 16539
+ 7440 16952
+ 7559 16255
+ 7679 17593
+ 7800 17107
+ 7920 17362
+ 8037 17723
+ 8159 18072
+ 8280 19804
+ 8399 18966
+ 8519 19510
+ 8640 19958
+ 8760 20364
+ 8878 20674
+ 9000 21682
+ 9120 21665
+ 9237 21945
+ 9359 22394
+ 9480 23105
+ 9598 23334
+ 9718 25301
+ 9840 26053
+ 9960 26565
+ 10079 26812
+ 10200 27300
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/logs/sub.log b/third_party/heimdal/lib/hcrypto/libtommath/logs/sub.log
new file mode 100644
index 0000000..87c0160
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/logs/sub.log
@@ -0,0 +1,16 @@
+ 480 36
+ 960 51
+ 1440 64
+ 1920 78
+ 2400 90
+ 2880 105
+ 3360 118
+ 3840 133
+ 4320 146
+ 4800 161
+ 5280 182
+ 5760 201
+ 6240 201
+ 6720 214
+ 7200 228
+ 7680 243
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/makefile b/third_party/heimdal/lib/hcrypto/libtommath/makefile
new file mode 100644
index 0000000..be9fac6
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/makefile
@@ -0,0 +1,165 @@
+#Makefile for GCC
+#
+#Tom St Denis
+
+ifeq ($V,1)
+silent=
+else
+silent=@
+endif
+
+#default files to install
+ifndef LIBNAME
+ LIBNAME=libtommath.a
+endif
+
+coverage: LIBNAME:=-Wl,--whole-archive $(LIBNAME) -Wl,--no-whole-archive
+
+include makefile_include.mk
+
+%.o: %.c $(HEADERS)
+ifneq ($V,1)
+ @echo " * ${CC} $@"
+endif
+ ${silent} ${CC} -c ${LTM_CFLAGS} $< -o $@
+
+LCOV_ARGS=--directory .
+
+#START_INS
+OBJECTS=bn_cutoffs.o bn_deprecated.o bn_mp_2expt.o bn_mp_abs.o bn_mp_add.o bn_mp_add_d.o bn_mp_addmod.o \
+bn_mp_and.o bn_mp_clamp.o bn_mp_clear.o bn_mp_clear_multi.o bn_mp_cmp.o bn_mp_cmp_d.o bn_mp_cmp_mag.o \
+bn_mp_cnt_lsb.o bn_mp_complement.o bn_mp_copy.o bn_mp_count_bits.o bn_mp_decr.o bn_mp_div.o bn_mp_div_2.o \
+bn_mp_div_2d.o bn_mp_div_3.o bn_mp_div_d.o bn_mp_dr_is_modulus.o bn_mp_dr_reduce.o bn_mp_dr_setup.o \
+bn_mp_error_to_string.o bn_mp_exch.o bn_mp_expt_u32.o bn_mp_exptmod.o bn_mp_exteuclid.o bn_mp_fread.o \
+bn_mp_from_sbin.o bn_mp_from_ubin.o bn_mp_fwrite.o bn_mp_gcd.o bn_mp_get_double.o bn_mp_get_i32.o \
+bn_mp_get_i64.o bn_mp_get_l.o bn_mp_get_ll.o bn_mp_get_mag_u32.o bn_mp_get_mag_u64.o bn_mp_get_mag_ul.o \
+bn_mp_get_mag_ull.o bn_mp_grow.o bn_mp_incr.o bn_mp_init.o bn_mp_init_copy.o bn_mp_init_i32.o \
+bn_mp_init_i64.o bn_mp_init_l.o bn_mp_init_ll.o bn_mp_init_multi.o bn_mp_init_set.o bn_mp_init_size.o \
+bn_mp_init_u32.o bn_mp_init_u64.o bn_mp_init_ul.o bn_mp_init_ull.o bn_mp_invmod.o bn_mp_is_square.o \
+bn_mp_iseven.o bn_mp_isodd.o bn_mp_kronecker.o bn_mp_lcm.o bn_mp_log_u32.o bn_mp_lshd.o bn_mp_mod.o \
+bn_mp_mod_2d.o bn_mp_mod_d.o bn_mp_montgomery_calc_normalization.o bn_mp_montgomery_reduce.o \
+bn_mp_montgomery_setup.o bn_mp_mul.o bn_mp_mul_2.o bn_mp_mul_2d.o bn_mp_mul_d.o bn_mp_mulmod.o bn_mp_neg.o \
+bn_mp_or.o bn_mp_pack.o bn_mp_pack_count.o bn_mp_prime_fermat.o bn_mp_prime_frobenius_underwood.o \
+bn_mp_prime_is_prime.o bn_mp_prime_miller_rabin.o bn_mp_prime_next_prime.o \
+bn_mp_prime_rabin_miller_trials.o bn_mp_prime_rand.o bn_mp_prime_strong_lucas_selfridge.o \
+bn_mp_radix_size.o bn_mp_radix_smap.o bn_mp_rand.o bn_mp_read_radix.o bn_mp_reduce.o bn_mp_reduce_2k.o \
+bn_mp_reduce_2k_l.o bn_mp_reduce_2k_setup.o bn_mp_reduce_2k_setup_l.o bn_mp_reduce_is_2k.o \
+bn_mp_reduce_is_2k_l.o bn_mp_reduce_setup.o bn_mp_root_u32.o bn_mp_rshd.o bn_mp_sbin_size.o bn_mp_set.o \
+bn_mp_set_double.o bn_mp_set_i32.o bn_mp_set_i64.o bn_mp_set_l.o bn_mp_set_ll.o bn_mp_set_u32.o \
+bn_mp_set_u64.o bn_mp_set_ul.o bn_mp_set_ull.o bn_mp_shrink.o bn_mp_signed_rsh.o bn_mp_sqr.o \
+bn_mp_sqrmod.o bn_mp_sqrt.o bn_mp_sqrtmod_prime.o bn_mp_sub.o bn_mp_sub_d.o bn_mp_submod.o \
+bn_mp_to_radix.o bn_mp_to_sbin.o bn_mp_to_ubin.o bn_mp_ubin_size.o bn_mp_unpack.o bn_mp_xor.o bn_mp_zero.o \
+bn_prime_tab.o bn_s_mp_add.o bn_s_mp_balance_mul.o bn_s_mp_exptmod.o bn_s_mp_exptmod_fast.o \
+bn_s_mp_get_bit.o bn_s_mp_invmod_fast.o bn_s_mp_invmod_slow.o bn_s_mp_karatsuba_mul.o \
+bn_s_mp_karatsuba_sqr.o bn_s_mp_montgomery_reduce_fast.o bn_s_mp_mul_digs.o bn_s_mp_mul_digs_fast.o \
+bn_s_mp_mul_high_digs.o bn_s_mp_mul_high_digs_fast.o bn_s_mp_prime_is_divisible.o \
+bn_s_mp_rand_jenkins.o bn_s_mp_rand_platform.o bn_s_mp_reverse.o bn_s_mp_sqr.o bn_s_mp_sqr_fast.o \
+bn_s_mp_sub.o bn_s_mp_toom_mul.o bn_s_mp_toom_sqr.o
+
+#END_INS
+
+$(LIBNAME): $(OBJECTS)
+ $(AR) $(ARFLAGS) $@ $(OBJECTS)
+ $(RANLIB) $@
+
+#make a profiled library (takes a while!!!)
+#
+# This will build the library with profile generation
+# then run the test demo and rebuild the library.
+#
+# So far I've seen improvements in the MP math
+profiled:
+ make CFLAGS="$(CFLAGS) -fprofile-arcs -DTESTING" timing
+ ./timing
+ rm -f *.a *.o timing
+ make CFLAGS="$(CFLAGS) -fbranch-probabilities"
+
+#make a single object profiled library
+profiled_single:
+ perl gen.pl
+ $(CC) $(LTM_CFLAGS) -fprofile-arcs -DTESTING -c mpi.c -o mpi.o
+ $(CC) $(LTM_CFLAGS) -DTESTING -DTIMER demo/timing.c mpi.o -lgcov -o timing
+ ./timing
+ rm -f *.o timing
+ $(CC) $(LTM_CFLAGS) -fbranch-probabilities -DTESTING -c mpi.c -o mpi.o
+ $(AR) $(ARFLAGS) $(LIBNAME) mpi.o
+ ranlib $(LIBNAME)
+
+install: $(LIBNAME)
+ install -d $(DESTDIR)$(LIBPATH)
+ install -d $(DESTDIR)$(INCPATH)
+ install -m 644 $(LIBNAME) $(DESTDIR)$(LIBPATH)
+ install -m 644 $(HEADERS_PUB) $(DESTDIR)$(INCPATH)
+
+uninstall:
+ rm $(DESTDIR)$(LIBPATH)/$(LIBNAME)
+ rm $(HEADERS_PUB:%=$(DESTDIR)$(INCPATH)/%)
+
+test_standalone: test
+ @echo "test_standalone is deprecated, please use make-target 'test'"
+
+DEMOS=test mtest_opponent
+
+define DEMO_template
+$(1): demo/$(1).o demo/shared.o $$(LIBNAME)
+ $$(CC) $$(LTM_CFLAGS) $$(LTM_LFLAGS) $$^ -o $$@
+endef
+
+$(foreach demo, $(strip $(DEMOS)), $(eval $(call DEMO_template,$(demo))))
+
+.PHONY: mtest
+mtest:
+ cd mtest ; $(CC) $(LTM_CFLAGS) -O0 mtest.c $(LTM_LFLAGS) -o mtest
+
+timing: $(LIBNAME) demo/timing.c
+ $(CC) $(LTM_CFLAGS) -DTIMER demo/timing.c $(LIBNAME) $(LTM_LFLAGS) -o timing
+
+tune: $(LIBNAME)
+ $(MAKE) -C etc tune CFLAGS="$(LTM_CFLAGS)"
+ $(MAKE)
+
+# You have to create a file .coveralls.yml with the content "repo_token: <the token>"
+# in the base folder to be able to submit to coveralls
+coveralls: lcov
+ coveralls-lcov
+
+docs manual:
+ $(MAKE) -C doc/ $@ V=$(V)
+
+.PHONY: pre_gen
+pre_gen:
+ mkdir -p pre_gen
+ perl gen.pl
+ sed -e 's/[[:blank:]]*$$//' mpi.c > pre_gen/mpi.c
+ rm mpi.c
+
+zipup: clean astyle new_file docs
+ @# Update the index, so diff-index won't fail in case the pdf has been created.
+ @# As the pdf creation modifies the tex files, git sometimes detects the
+ @# modified files, but misses that it's put back to its original version.
+ @git update-index --refresh
+ @git diff-index --quiet HEAD -- || ( echo "FAILURE: uncommited changes or not a git" && exit 1 )
+ rm -rf libtommath-$(VERSION) ltm-$(VERSION).*
+ @# files/dirs excluded from "git archive" are defined in .gitattributes
+ git archive --format=tar --prefix=libtommath-$(VERSION)/ HEAD | tar x
+ @echo 'fixme check'
+ -@(find libtommath-$(VERSION)/ -type f | xargs grep 'FIXM[E]') && echo '############## BEWARE: the "fixme" marker was found !!! ##############' || true
+ mkdir -p libtommath-$(VERSION)/doc
+ cp doc/bn.pdf libtommath-$(VERSION)/doc/
+ $(MAKE) -C libtommath-$(VERSION)/ pre_gen
+ tar -c libtommath-$(VERSION)/ | xz -6e -c - > ltm-$(VERSION).tar.xz
+ zip -9rq ltm-$(VERSION).zip libtommath-$(VERSION)
+ cp doc/bn.pdf bn-$(VERSION).pdf
+ rm -rf libtommath-$(VERSION)
+ gpg -b -a ltm-$(VERSION).tar.xz
+ gpg -b -a ltm-$(VERSION).zip
+
+new_file:
+ perl helper.pl --update-files
+
+perlcritic:
+ perlcritic *.pl doc/*.pl
+
+astyle:
+ @echo " * run astyle on all sources"
+ @astyle --options=astylerc --formatted $(OBJECTS:.o=.c) tommath*.h demo/*.c etc/*.c mtest/mtest.c
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/makefile.mingw b/third_party/heimdal/lib/hcrypto/libtommath/makefile.mingw
new file mode 100644
index 0000000..7eee57d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/makefile.mingw
@@ -0,0 +1,109 @@
+# MAKEFILE for MS Windows (mingw + gcc + gmake)
+#
+# BEWARE: variable OBJECTS is updated via helper.pl
+
+### USAGE:
+# Open a command prompt with gcc + gmake in PATH and start:
+#
+# gmake -f makefile.mingw all
+# test.exe
+# gmake -f makefile.mingw PREFIX=c:\devel\libtom install
+
+#The following can be overridden from command line e.g. make -f makefile.mingw CC=gcc ARFLAGS=rcs
+PREFIX = c:\mingw
+CC = gcc
+AR = ar
+ARFLAGS = r
+RANLIB = ranlib
+STRIP = strip
+CFLAGS = -O2
+LDFLAGS =
+
+#Compilation flags
+LTM_CFLAGS = -I. $(CFLAGS)
+LTM_LDFLAGS = $(LDFLAGS) -static-libgcc
+
+#Libraries to be created
+LIBMAIN_S =libtommath.a
+LIBMAIN_I =libtommath.dll.a
+LIBMAIN_D =libtommath.dll
+
+#List of objects to compile (all goes to libtommath.a)
+OBJECTS=bn_cutoffs.o bn_deprecated.o bn_mp_2expt.o bn_mp_abs.o bn_mp_add.o bn_mp_add_d.o bn_mp_addmod.o \
+bn_mp_and.o bn_mp_clamp.o bn_mp_clear.o bn_mp_clear_multi.o bn_mp_cmp.o bn_mp_cmp_d.o bn_mp_cmp_mag.o \
+bn_mp_cnt_lsb.o bn_mp_complement.o bn_mp_copy.o bn_mp_count_bits.o bn_mp_decr.o bn_mp_div.o bn_mp_div_2.o \
+bn_mp_div_2d.o bn_mp_div_3.o bn_mp_div_d.o bn_mp_dr_is_modulus.o bn_mp_dr_reduce.o bn_mp_dr_setup.o \
+bn_mp_error_to_string.o bn_mp_exch.o bn_mp_expt_u32.o bn_mp_exptmod.o bn_mp_exteuclid.o bn_mp_fread.o \
+bn_mp_from_sbin.o bn_mp_from_ubin.o bn_mp_fwrite.o bn_mp_gcd.o bn_mp_get_double.o bn_mp_get_i32.o \
+bn_mp_get_i64.o bn_mp_get_l.o bn_mp_get_ll.o bn_mp_get_mag_u32.o bn_mp_get_mag_u64.o bn_mp_get_mag_ul.o \
+bn_mp_get_mag_ull.o bn_mp_grow.o bn_mp_incr.o bn_mp_init.o bn_mp_init_copy.o bn_mp_init_i32.o \
+bn_mp_init_i64.o bn_mp_init_l.o bn_mp_init_ll.o bn_mp_init_multi.o bn_mp_init_set.o bn_mp_init_size.o \
+bn_mp_init_u32.o bn_mp_init_u64.o bn_mp_init_ul.o bn_mp_init_ull.o bn_mp_invmod.o bn_mp_is_square.o \
+bn_mp_iseven.o bn_mp_isodd.o bn_mp_kronecker.o bn_mp_lcm.o bn_mp_log_u32.o bn_mp_lshd.o bn_mp_mod.o \
+bn_mp_mod_2d.o bn_mp_mod_d.o bn_mp_montgomery_calc_normalization.o bn_mp_montgomery_reduce.o \
+bn_mp_montgomery_setup.o bn_mp_mul.o bn_mp_mul_2.o bn_mp_mul_2d.o bn_mp_mul_d.o bn_mp_mulmod.o bn_mp_neg.o \
+bn_mp_or.o bn_mp_pack.o bn_mp_pack_count.o bn_mp_prime_fermat.o bn_mp_prime_frobenius_underwood.o \
+bn_mp_prime_is_prime.o bn_mp_prime_miller_rabin.o bn_mp_prime_next_prime.o \
+bn_mp_prime_rabin_miller_trials.o bn_mp_prime_rand.o bn_mp_prime_strong_lucas_selfridge.o \
+bn_mp_radix_size.o bn_mp_radix_smap.o bn_mp_rand.o bn_mp_read_radix.o bn_mp_reduce.o bn_mp_reduce_2k.o \
+bn_mp_reduce_2k_l.o bn_mp_reduce_2k_setup.o bn_mp_reduce_2k_setup_l.o bn_mp_reduce_is_2k.o \
+bn_mp_reduce_is_2k_l.o bn_mp_reduce_setup.o bn_mp_root_u32.o bn_mp_rshd.o bn_mp_sbin_size.o bn_mp_set.o \
+bn_mp_set_double.o bn_mp_set_i32.o bn_mp_set_i64.o bn_mp_set_l.o bn_mp_set_ll.o bn_mp_set_u32.o \
+bn_mp_set_u64.o bn_mp_set_ul.o bn_mp_set_ull.o bn_mp_shrink.o bn_mp_signed_rsh.o bn_mp_sqr.o \
+bn_mp_sqrmod.o bn_mp_sqrt.o bn_mp_sqrtmod_prime.o bn_mp_sub.o bn_mp_sub_d.o bn_mp_submod.o \
+bn_mp_to_radix.o bn_mp_to_sbin.o bn_mp_to_ubin.o bn_mp_ubin_size.o bn_mp_unpack.o bn_mp_xor.o bn_mp_zero.o \
+bn_prime_tab.o bn_s_mp_add.o bn_s_mp_balance_mul.o bn_s_mp_exptmod.o bn_s_mp_exptmod_fast.o \
+bn_s_mp_get_bit.o bn_s_mp_invmod_fast.o bn_s_mp_invmod_slow.o bn_s_mp_karatsuba_mul.o \
+bn_s_mp_karatsuba_sqr.o bn_s_mp_montgomery_reduce_fast.o bn_s_mp_mul_digs.o bn_s_mp_mul_digs_fast.o \
+bn_s_mp_mul_high_digs.o bn_s_mp_mul_high_digs_fast.o bn_s_mp_prime_is_divisible.o \
+bn_s_mp_rand_jenkins.o bn_s_mp_rand_platform.o bn_s_mp_reverse.o bn_s_mp_sqr.o bn_s_mp_sqr_fast.o \
+bn_s_mp_sub.o bn_s_mp_toom_mul.o bn_s_mp_toom_sqr.o
+
+HEADERS_PUB=tommath.h
+HEADERS=tommath_private.h tommath_class.h tommath_superclass.h tommath_cutoffs.h $(HEADERS_PUB)
+
+#The default rule for make builds the libtommath.a library (static)
+default: $(LIBMAIN_S)
+
+#Dependencies on *.h
+$(OBJECTS): $(HEADERS)
+
+.c.o:
+ $(CC) $(LTM_CFLAGS) -c $< -o $@
+
+#Create libtommath.a
+$(LIBMAIN_S): $(OBJECTS)
+ $(AR) $(ARFLAGS) $@ $(OBJECTS)
+ $(RANLIB) $@
+
+#Create DLL + import library libtommath.dll.a
+$(LIBMAIN_D) $(LIBMAIN_I): $(OBJECTS)
+ $(CC) -s -shared -o $(LIBMAIN_D) $^ -Wl,--enable-auto-import,--export-all -Wl,--out-implib=$(LIBMAIN_I) $(LTM_LDFLAGS)
+ $(STRIP) -S $(LIBMAIN_D)
+
+#Build test suite
+test.exe: demo/shared.o demo/test.o $(LIBMAIN_S)
+ $(CC) $(LTM_CFLAGS) $(LTM_LDFLAGS) $^ -o $@
+ @echo NOTICE: start the tests by launching test.exe
+
+test_standalone: test.exe
+ @echo test_standalone is deprecated, please use make-target 'test.exe'
+
+all: $(LIBMAIN_S) test.exe
+
+tune: $(LIBNAME_S)
+ $(MAKE) -C etc tune
+ $(MAKE)
+
+clean:
+ @-cmd /c del /Q /S *.o *.a *.exe *.dll 2>nul
+
+#Install the library + headers
+install: $(LIBMAIN_S) $(LIBMAIN_I) $(LIBMAIN_D)
+ cmd /c if not exist "$(PREFIX)\bin" mkdir "$(PREFIX)\bin"
+ cmd /c if not exist "$(PREFIX)\lib" mkdir "$(PREFIX)\lib"
+ cmd /c if not exist "$(PREFIX)\include" mkdir "$(PREFIX)\include"
+ copy /Y $(LIBMAIN_S) "$(PREFIX)\lib"
+ copy /Y $(LIBMAIN_I) "$(PREFIX)\lib"
+ copy /Y $(LIBMAIN_D) "$(PREFIX)\bin"
+ copy /Y tommath*.h "$(PREFIX)\include"
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/makefile.msvc b/third_party/heimdal/lib/hcrypto/libtommath/makefile.msvc
new file mode 100644
index 0000000..aa8d8be
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/makefile.msvc
@@ -0,0 +1,93 @@
+# MAKEFILE for MS Windows (nmake + Windows SDK)
+#
+# BEWARE: variable OBJECTS is updated via helper.pl
+
+### USAGE:
+# Open a command prompt with WinSDK variables set and start:
+#
+# nmake -f makefile.msvc all
+# test.exe
+# nmake -f makefile.msvc PREFIX=c:\devel\libtom install
+
+#The following can be overridden from command line e.g. make -f makefile.msvc CC=gcc ARFLAGS=rcs
+PREFIX = c:\devel
+CFLAGS = /Ox
+
+#Compilation flags
+LTM_CFLAGS = /nologo /I./ /D_CRT_SECURE_NO_WARNINGS /D_CRT_NONSTDC_NO_DEPRECATE /D__STDC_WANT_SECURE_LIB__=1 /D_CRT_HAS_CXX17=0 /Wall /wd4146 /wd4127 /wd4668 /wd4710 /wd4711 /wd4820 /wd5045 /WX $(CFLAGS)
+LTM_LDFLAGS = advapi32.lib
+
+#Libraries to be created (this makefile builds only static libraries)
+LIBMAIN_S =tommath.lib
+
+#List of objects to compile (all goes to tommath.lib)
+OBJECTS=bn_cutoffs.obj bn_deprecated.obj bn_mp_2expt.obj bn_mp_abs.obj bn_mp_add.obj bn_mp_add_d.obj bn_mp_addmod.obj \
+bn_mp_and.obj bn_mp_clamp.obj bn_mp_clear.obj bn_mp_clear_multi.obj bn_mp_cmp.obj bn_mp_cmp_d.obj bn_mp_cmp_mag.obj \
+bn_mp_cnt_lsb.obj bn_mp_complement.obj bn_mp_copy.obj bn_mp_count_bits.obj bn_mp_decr.obj bn_mp_div.obj bn_mp_div_2.obj \
+bn_mp_div_2d.obj bn_mp_div_3.obj bn_mp_div_d.obj bn_mp_dr_is_modulus.obj bn_mp_dr_reduce.obj bn_mp_dr_setup.obj \
+bn_mp_error_to_string.obj bn_mp_exch.obj bn_mp_expt_u32.obj bn_mp_exptmod.obj bn_mp_exteuclid.obj bn_mp_fread.obj \
+bn_mp_from_sbin.obj bn_mp_from_ubin.obj bn_mp_fwrite.obj bn_mp_gcd.obj bn_mp_get_double.obj bn_mp_get_i32.obj \
+bn_mp_get_i64.obj bn_mp_get_l.obj bn_mp_get_ll.obj bn_mp_get_mag_u32.obj bn_mp_get_mag_u64.obj bn_mp_get_mag_ul.obj \
+bn_mp_get_mag_ull.obj bn_mp_grow.obj bn_mp_incr.obj bn_mp_init.obj bn_mp_init_copy.obj bn_mp_init_i32.obj \
+bn_mp_init_i64.obj bn_mp_init_l.obj bn_mp_init_ll.obj bn_mp_init_multi.obj bn_mp_init_set.obj bn_mp_init_size.obj \
+bn_mp_init_u32.obj bn_mp_init_u64.obj bn_mp_init_ul.obj bn_mp_init_ull.obj bn_mp_invmod.obj bn_mp_is_square.obj \
+bn_mp_iseven.obj bn_mp_isodd.obj bn_mp_kronecker.obj bn_mp_lcm.obj bn_mp_log_u32.obj bn_mp_lshd.obj bn_mp_mod.obj \
+bn_mp_mod_2d.obj bn_mp_mod_d.obj bn_mp_montgomery_calc_normalization.obj bn_mp_montgomery_reduce.obj \
+bn_mp_montgomery_setup.obj bn_mp_mul.obj bn_mp_mul_2.obj bn_mp_mul_2d.obj bn_mp_mul_d.obj bn_mp_mulmod.obj bn_mp_neg.obj \
+bn_mp_or.obj bn_mp_pack.obj bn_mp_pack_count.obj bn_mp_prime_fermat.obj bn_mp_prime_frobenius_underwood.obj \
+bn_mp_prime_is_prime.obj bn_mp_prime_miller_rabin.obj bn_mp_prime_next_prime.obj \
+bn_mp_prime_rabin_miller_trials.obj bn_mp_prime_rand.obj bn_mp_prime_strong_lucas_selfridge.obj \
+bn_mp_radix_size.obj bn_mp_radix_smap.obj bn_mp_rand.obj bn_mp_read_radix.obj bn_mp_reduce.obj bn_mp_reduce_2k.obj \
+bn_mp_reduce_2k_l.obj bn_mp_reduce_2k_setup.obj bn_mp_reduce_2k_setup_l.obj bn_mp_reduce_is_2k.obj \
+bn_mp_reduce_is_2k_l.obj bn_mp_reduce_setup.obj bn_mp_root_u32.obj bn_mp_rshd.obj bn_mp_sbin_size.obj bn_mp_set.obj \
+bn_mp_set_double.obj bn_mp_set_i32.obj bn_mp_set_i64.obj bn_mp_set_l.obj bn_mp_set_ll.obj bn_mp_set_u32.obj \
+bn_mp_set_u64.obj bn_mp_set_ul.obj bn_mp_set_ull.obj bn_mp_shrink.obj bn_mp_signed_rsh.obj bn_mp_sqr.obj \
+bn_mp_sqrmod.obj bn_mp_sqrt.obj bn_mp_sqrtmod_prime.obj bn_mp_sub.obj bn_mp_sub_d.obj bn_mp_submod.obj \
+bn_mp_to_radix.obj bn_mp_to_sbin.obj bn_mp_to_ubin.obj bn_mp_ubin_size.obj bn_mp_unpack.obj bn_mp_xor.obj bn_mp_zero.obj \
+bn_prime_tab.obj bn_s_mp_add.obj bn_s_mp_balance_mul.obj bn_s_mp_exptmod.obj bn_s_mp_exptmod_fast.obj \
+bn_s_mp_get_bit.obj bn_s_mp_invmod_fast.obj bn_s_mp_invmod_slow.obj bn_s_mp_karatsuba_mul.obj \
+bn_s_mp_karatsuba_sqr.obj bn_s_mp_montgomery_reduce_fast.obj bn_s_mp_mul_digs.obj bn_s_mp_mul_digs_fast.obj \
+bn_s_mp_mul_high_digs.obj bn_s_mp_mul_high_digs_fast.obj bn_s_mp_prime_is_divisible.obj \
+bn_s_mp_rand_jenkins.obj bn_s_mp_rand_platform.obj bn_s_mp_reverse.obj bn_s_mp_sqr.obj bn_s_mp_sqr_fast.obj \
+bn_s_mp_sub.obj bn_s_mp_toom_mul.obj bn_s_mp_toom_sqr.obj
+
+HEADERS_PUB=tommath.h
+HEADERS=tommath_private.h tommath_class.h tommath_superclass.h tommath_cutoffs.h $(HEADERS_PUB)
+
+#The default rule for make builds the tommath.lib library (static)
+default: $(LIBMAIN_S)
+
+#Dependencies on *.h
+$(OBJECTS): $(HEADERS)
+
+.c.obj:
+ $(CC) $(LTM_CFLAGS) /c $< /Fo$@
+
+#Create tommath.lib
+$(LIBMAIN_S): $(OBJECTS)
+ lib /out:$(LIBMAIN_S) $(OBJECTS)
+
+#Build test suite
+test.exe: $(LIBMAIN_S) demo/shared.obj demo/test.obj
+ cl $(LTM_CFLAGS) $(TOBJECTS) $(LIBMAIN_S) $(LTM_LDFLAGS) demo/shared.c demo/test.c /Fe$@
+ @echo NOTICE: start the tests by launching test.exe
+
+test_standalone: test.exe
+ @echo test_standalone is deprecated, please use make-target 'test.exe'
+
+all: $(LIBMAIN_S) test.exe
+
+tune: $(LIBMAIN_S)
+ $(MAKE) -C etc tune
+ $(MAKE)
+
+clean:
+ @-cmd /c del /Q /S *.OBJ *.LIB *.EXE *.DLL 2>nul
+
+#Install the library + headers
+install: $(LIBMAIN_S)
+ cmd /c if not exist "$(PREFIX)\bin" mkdir "$(PREFIX)\bin"
+ cmd /c if not exist "$(PREFIX)\lib" mkdir "$(PREFIX)\lib"
+ cmd /c if not exist "$(PREFIX)\include" mkdir "$(PREFIX)\include"
+ copy /Y $(LIBMAIN_S) "$(PREFIX)\lib"
+ copy /Y tommath*.h "$(PREFIX)\include"
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/makefile.shared b/third_party/heimdal/lib/hcrypto/libtommath/makefile.shared
new file mode 100644
index 0000000..6802107
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/makefile.shared
@@ -0,0 +1,99 @@
+#Makefile for GCC
+#
+#Tom St Denis
+
+#default files to install
+ifndef LIBNAME
+ LIBNAME=libtommath.la
+endif
+
+include makefile_include.mk
+
+
+ifndef LIBTOOL
+ ifeq ($(PLATFORM), Darwin)
+ LIBTOOL:=glibtool
+ else
+ LIBTOOL:=libtool
+ endif
+endif
+LTCOMPILE = $(LIBTOOL) --mode=compile --tag=CC $(CC)
+LTLINK = $(LIBTOOL) --mode=link --tag=CC $(CC)
+
+LCOV_ARGS=--directory .libs --directory .
+
+#START_INS
+OBJECTS=bn_cutoffs.o bn_deprecated.o bn_mp_2expt.o bn_mp_abs.o bn_mp_add.o bn_mp_add_d.o bn_mp_addmod.o \
+bn_mp_and.o bn_mp_clamp.o bn_mp_clear.o bn_mp_clear_multi.o bn_mp_cmp.o bn_mp_cmp_d.o bn_mp_cmp_mag.o \
+bn_mp_cnt_lsb.o bn_mp_complement.o bn_mp_copy.o bn_mp_count_bits.o bn_mp_decr.o bn_mp_div.o bn_mp_div_2.o \
+bn_mp_div_2d.o bn_mp_div_3.o bn_mp_div_d.o bn_mp_dr_is_modulus.o bn_mp_dr_reduce.o bn_mp_dr_setup.o \
+bn_mp_error_to_string.o bn_mp_exch.o bn_mp_expt_u32.o bn_mp_exptmod.o bn_mp_exteuclid.o bn_mp_fread.o \
+bn_mp_from_sbin.o bn_mp_from_ubin.o bn_mp_fwrite.o bn_mp_gcd.o bn_mp_get_double.o bn_mp_get_i32.o \
+bn_mp_get_i64.o bn_mp_get_l.o bn_mp_get_ll.o bn_mp_get_mag_u32.o bn_mp_get_mag_u64.o bn_mp_get_mag_ul.o \
+bn_mp_get_mag_ull.o bn_mp_grow.o bn_mp_incr.o bn_mp_init.o bn_mp_init_copy.o bn_mp_init_i32.o \
+bn_mp_init_i64.o bn_mp_init_l.o bn_mp_init_ll.o bn_mp_init_multi.o bn_mp_init_set.o bn_mp_init_size.o \
+bn_mp_init_u32.o bn_mp_init_u64.o bn_mp_init_ul.o bn_mp_init_ull.o bn_mp_invmod.o bn_mp_is_square.o \
+bn_mp_iseven.o bn_mp_isodd.o bn_mp_kronecker.o bn_mp_lcm.o bn_mp_log_u32.o bn_mp_lshd.o bn_mp_mod.o \
+bn_mp_mod_2d.o bn_mp_mod_d.o bn_mp_montgomery_calc_normalization.o bn_mp_montgomery_reduce.o \
+bn_mp_montgomery_setup.o bn_mp_mul.o bn_mp_mul_2.o bn_mp_mul_2d.o bn_mp_mul_d.o bn_mp_mulmod.o bn_mp_neg.o \
+bn_mp_or.o bn_mp_pack.o bn_mp_pack_count.o bn_mp_prime_fermat.o bn_mp_prime_frobenius_underwood.o \
+bn_mp_prime_is_prime.o bn_mp_prime_miller_rabin.o bn_mp_prime_next_prime.o \
+bn_mp_prime_rabin_miller_trials.o bn_mp_prime_rand.o bn_mp_prime_strong_lucas_selfridge.o \
+bn_mp_radix_size.o bn_mp_radix_smap.o bn_mp_rand.o bn_mp_read_radix.o bn_mp_reduce.o bn_mp_reduce_2k.o \
+bn_mp_reduce_2k_l.o bn_mp_reduce_2k_setup.o bn_mp_reduce_2k_setup_l.o bn_mp_reduce_is_2k.o \
+bn_mp_reduce_is_2k_l.o bn_mp_reduce_setup.o bn_mp_root_u32.o bn_mp_rshd.o bn_mp_sbin_size.o bn_mp_set.o \
+bn_mp_set_double.o bn_mp_set_i32.o bn_mp_set_i64.o bn_mp_set_l.o bn_mp_set_ll.o bn_mp_set_u32.o \
+bn_mp_set_u64.o bn_mp_set_ul.o bn_mp_set_ull.o bn_mp_shrink.o bn_mp_signed_rsh.o bn_mp_sqr.o \
+bn_mp_sqrmod.o bn_mp_sqrt.o bn_mp_sqrtmod_prime.o bn_mp_sub.o bn_mp_sub_d.o bn_mp_submod.o \
+bn_mp_to_radix.o bn_mp_to_sbin.o bn_mp_to_ubin.o bn_mp_ubin_size.o bn_mp_unpack.o bn_mp_xor.o bn_mp_zero.o \
+bn_prime_tab.o bn_s_mp_add.o bn_s_mp_balance_mul.o bn_s_mp_exptmod.o bn_s_mp_exptmod_fast.o \
+bn_s_mp_get_bit.o bn_s_mp_invmod_fast.o bn_s_mp_invmod_slow.o bn_s_mp_karatsuba_mul.o \
+bn_s_mp_karatsuba_sqr.o bn_s_mp_montgomery_reduce_fast.o bn_s_mp_mul_digs.o bn_s_mp_mul_digs_fast.o \
+bn_s_mp_mul_high_digs.o bn_s_mp_mul_high_digs_fast.o bn_s_mp_prime_is_divisible.o \
+bn_s_mp_rand_jenkins.o bn_s_mp_rand_platform.o bn_s_mp_reverse.o bn_s_mp_sqr.o bn_s_mp_sqr_fast.o \
+bn_s_mp_sub.o bn_s_mp_toom_mul.o bn_s_mp_toom_sqr.o
+
+#END_INS
+
+objs: $(OBJECTS)
+
+.c.o: $(HEADERS)
+ $(LTCOMPILE) $(LTM_CFLAGS) $(LTM_LDFLAGS) -o $@ -c $<
+
+LOBJECTS = $(OBJECTS:.o=.lo)
+
+$(LIBNAME): $(OBJECTS)
+ $(LTLINK) $(LTM_LDFLAGS) $(LOBJECTS) -o $(LIBNAME) -rpath $(LIBPATH) -version-info $(VERSION_SO) $(LTM_LIBTOOLFLAGS)
+
+install: $(LIBNAME)
+ install -d $(DESTDIR)$(LIBPATH)
+ install -d $(DESTDIR)$(INCPATH)
+ $(LIBTOOL) --mode=install install -m 644 $(LIBNAME) $(DESTDIR)$(LIBPATH)/$(LIBNAME)
+ install -m 644 $(HEADERS_PUB) $(DESTDIR)$(INCPATH)
+ sed -e 's,^prefix=.*,prefix=$(PREFIX),' -e 's,^Version:.*,Version: $(VERSION_PC),' libtommath.pc.in > libtommath.pc
+ install -d $(DESTDIR)$(LIBPATH)/pkgconfig
+ install -m 644 libtommath.pc $(DESTDIR)$(LIBPATH)/pkgconfig/
+
+uninstall:
+ $(LIBTOOL) --mode=uninstall rm $(DESTDIR)$(LIBPATH)/$(LIBNAME)
+ rm $(HEADERS_PUB:%=$(DESTDIR)$(INCPATH)/%)
+ rm $(DESTDIR)$(LIBPATH)/pkgconfig/libtommath.pc
+
+test_standalone: test
+ @echo "test_standalone is deprecated, please use make-target 'test'"
+
+test mtest_opponent: demo/shared.o $(LIBNAME) | demo/test.o demo/mtest_opponent.o
+ $(LTLINK) $(LTM_LDFLAGS) demo/$@.o $^ -o $@
+
+.PHONY: mtest
+mtest:
+ cd mtest ; $(CC) $(LTM_CFLAGS) -O0 mtest.c $(LTM_LDFLAGS) -o mtest
+
+timing: $(LIBNAME) demo/timing.c
+ $(LTLINK) $(LTM_CFLAGS) $(LTM_LDFLAGS) -DTIMER demo/timing.c $(LIBNAME) -o timing
+
+tune: $(LIBNAME)
+ $(LTCOMPILE) $(LTM_CFLAGS) -c etc/tune.c -o etc/tune.o
+ $(LTLINK) $(LTM_LDFLAGS) -o etc/tune etc/tune.o $(LIBNAME)
+ cd etc/; /bin/sh tune_it.sh; cd ..
+ $(MAKE) -f makefile.shared
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/makefile.unix b/third_party/heimdal/lib/hcrypto/libtommath/makefile.unix
new file mode 100644
index 0000000..4cefc7e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/makefile.unix
@@ -0,0 +1,106 @@
+# MAKEFILE that is intended to be compatible with any kind of make (GNU make, BSD make, ...)
+# works on: Linux, *BSD, Cygwin, AIX, HP-UX and hopefully other UNIX systems
+#
+# Please do not use here neither any special make syntax nor any unusual tools/utilities!
+
+# using ICC compiler:
+# make -f makefile.unix CC=icc CFLAGS="-O3 -xP -ip"
+
+# using Borland C++Builder:
+# make -f makefile.unix CC=bcc32
+
+#The following can be overridden from command line e.g. "make -f makefile.unix CC=gcc ARFLAGS=rcs"
+DESTDIR =
+PREFIX = /usr/local
+LIBPATH = $(PREFIX)/lib
+INCPATH = $(PREFIX)/include
+CC = cc
+AR = ar
+ARFLAGS = r
+RANLIB = ranlib
+CFLAGS = -O2
+LDFLAGS =
+
+VERSION = 1.2.0
+
+#Compilation flags
+LTM_CFLAGS = -I. $(CFLAGS)
+LTM_LDFLAGS = $(LDFLAGS)
+
+#Library to be created (this makefile builds only static library)
+LIBMAIN_S = libtommath.a
+
+OBJECTS=bn_cutoffs.o bn_deprecated.o bn_mp_2expt.o bn_mp_abs.o bn_mp_add.o bn_mp_add_d.o bn_mp_addmod.o \
+bn_mp_and.o bn_mp_clamp.o bn_mp_clear.o bn_mp_clear_multi.o bn_mp_cmp.o bn_mp_cmp_d.o bn_mp_cmp_mag.o \
+bn_mp_cnt_lsb.o bn_mp_complement.o bn_mp_copy.o bn_mp_count_bits.o bn_mp_decr.o bn_mp_div.o bn_mp_div_2.o \
+bn_mp_div_2d.o bn_mp_div_3.o bn_mp_div_d.o bn_mp_dr_is_modulus.o bn_mp_dr_reduce.o bn_mp_dr_setup.o \
+bn_mp_error_to_string.o bn_mp_exch.o bn_mp_expt_u32.o bn_mp_exptmod.o bn_mp_exteuclid.o bn_mp_fread.o \
+bn_mp_from_sbin.o bn_mp_from_ubin.o bn_mp_fwrite.o bn_mp_gcd.o bn_mp_get_double.o bn_mp_get_i32.o \
+bn_mp_get_i64.o bn_mp_get_l.o bn_mp_get_ll.o bn_mp_get_mag_u32.o bn_mp_get_mag_u64.o bn_mp_get_mag_ul.o \
+bn_mp_get_mag_ull.o bn_mp_grow.o bn_mp_incr.o bn_mp_init.o bn_mp_init_copy.o bn_mp_init_i32.o \
+bn_mp_init_i64.o bn_mp_init_l.o bn_mp_init_ll.o bn_mp_init_multi.o bn_mp_init_set.o bn_mp_init_size.o \
+bn_mp_init_u32.o bn_mp_init_u64.o bn_mp_init_ul.o bn_mp_init_ull.o bn_mp_invmod.o bn_mp_is_square.o \
+bn_mp_iseven.o bn_mp_isodd.o bn_mp_kronecker.o bn_mp_lcm.o bn_mp_log_u32.o bn_mp_lshd.o bn_mp_mod.o \
+bn_mp_mod_2d.o bn_mp_mod_d.o bn_mp_montgomery_calc_normalization.o bn_mp_montgomery_reduce.o \
+bn_mp_montgomery_setup.o bn_mp_mul.o bn_mp_mul_2.o bn_mp_mul_2d.o bn_mp_mul_d.o bn_mp_mulmod.o bn_mp_neg.o \
+bn_mp_or.o bn_mp_pack.o bn_mp_pack_count.o bn_mp_prime_fermat.o bn_mp_prime_frobenius_underwood.o \
+bn_mp_prime_is_prime.o bn_mp_prime_miller_rabin.o bn_mp_prime_next_prime.o \
+bn_mp_prime_rabin_miller_trials.o bn_mp_prime_rand.o bn_mp_prime_strong_lucas_selfridge.o \
+bn_mp_radix_size.o bn_mp_radix_smap.o bn_mp_rand.o bn_mp_read_radix.o bn_mp_reduce.o bn_mp_reduce_2k.o \
+bn_mp_reduce_2k_l.o bn_mp_reduce_2k_setup.o bn_mp_reduce_2k_setup_l.o bn_mp_reduce_is_2k.o \
+bn_mp_reduce_is_2k_l.o bn_mp_reduce_setup.o bn_mp_root_u32.o bn_mp_rshd.o bn_mp_sbin_size.o bn_mp_set.o \
+bn_mp_set_double.o bn_mp_set_i32.o bn_mp_set_i64.o bn_mp_set_l.o bn_mp_set_ll.o bn_mp_set_u32.o \
+bn_mp_set_u64.o bn_mp_set_ul.o bn_mp_set_ull.o bn_mp_shrink.o bn_mp_signed_rsh.o bn_mp_sqr.o \
+bn_mp_sqrmod.o bn_mp_sqrt.o bn_mp_sqrtmod_prime.o bn_mp_sub.o bn_mp_sub_d.o bn_mp_submod.o \
+bn_mp_to_radix.o bn_mp_to_sbin.o bn_mp_to_ubin.o bn_mp_ubin_size.o bn_mp_unpack.o bn_mp_xor.o bn_mp_zero.o \
+bn_prime_tab.o bn_s_mp_add.o bn_s_mp_balance_mul.o bn_s_mp_exptmod.o bn_s_mp_exptmod_fast.o \
+bn_s_mp_get_bit.o bn_s_mp_invmod_fast.o bn_s_mp_invmod_slow.o bn_s_mp_karatsuba_mul.o \
+bn_s_mp_karatsuba_sqr.o bn_s_mp_montgomery_reduce_fast.o bn_s_mp_mul_digs.o bn_s_mp_mul_digs_fast.o \
+bn_s_mp_mul_high_digs.o bn_s_mp_mul_high_digs_fast.o bn_s_mp_prime_is_divisible.o \
+bn_s_mp_rand_jenkins.o bn_s_mp_rand_platform.o bn_s_mp_reverse.o bn_s_mp_sqr.o bn_s_mp_sqr_fast.o \
+bn_s_mp_sub.o bn_s_mp_toom_mul.o bn_s_mp_toom_sqr.o
+
+HEADERS_PUB=tommath.h
+HEADERS=tommath_private.h tommath_class.h tommath_superclass.h tommath_cutoffs.h $(HEADERS_PUB)
+
+#The default rule for make builds the libtommath.a library (static)
+default: $(LIBMAIN_S)
+
+#Dependencies on *.h
+$(OBJECTS): $(HEADERS)
+
+#This is necessary for compatibility with BSD make (namely on OpenBSD)
+.SUFFIXES: .o .c
+.c.o:
+ $(CC) $(LTM_CFLAGS) -c $< -o $@
+
+#Create libtommath.a
+$(LIBMAIN_S): $(OBJECTS)
+ $(AR) $(ARFLAGS) $@ $(OBJECTS)
+ $(RANLIB) $@
+
+#Build test_standalone suite
+test: demo/shared.o demo/test.o $(LIBMAIN_S)
+ $(CC) $(LTM_CFLAGS) $(LTM_LDFLAGS) $^ -o $@
+ @echo "NOTICE: start the tests by: ./test"
+
+test_standalone: test
+ @echo "test_standalone is deprecated, please use make-target 'test'"
+
+all: $(LIBMAIN_S) test
+
+tune: $(LIBMAIN_S)
+ $(MAKE) -C etc tune
+ $(MAKE)
+
+#NOTE: this makefile works also on cygwin, thus we need to delete *.exe
+clean:
+ -@rm -f $(OBJECTS) $(LIBMAIN_S)
+ -@rm -f demo/main.o demo/opponent.o demo/test.o test test.exe
+
+#Install the library + headers
+install: $(LIBMAIN_S)
+ @mkdir -p $(DESTDIR)$(INCPATH) $(DESTDIR)$(LIBPATH)/pkgconfig
+ @cp $(LIBMAIN_S) $(DESTDIR)$(LIBPATH)/
+ @cp $(HEADERS_PUB) $(DESTDIR)$(INCPATH)/
+ @sed -e 's,^prefix=.*,prefix=$(PREFIX),' -e 's,^Version:.*,Version: $(VERSION),' libtommath.pc.in > $(DESTDIR)$(LIBPATH)/pkgconfig/libtommath.pc
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/makefile_include.mk b/third_party/heimdal/lib/hcrypto/libtommath/makefile_include.mk
new file mode 100644
index 0000000..7b025e8
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/makefile_include.mk
@@ -0,0 +1,166 @@
+#
+# Include makefile for libtommath
+#
+
+#version of library
+VERSION=1.2.0
+VERSION_PC=1.2.0
+VERSION_SO=3:0:2
+
+PLATFORM := $(shell uname | sed -e 's/_.*//')
+
+# default make target
+default: ${LIBNAME}
+
+# Compiler and Linker Names
+ifndef CROSS_COMPILE
+ CROSS_COMPILE=
+endif
+
+# We only need to go through this dance of determining the right compiler if we're using
+# cross compilation, otherwise $(CC) is fine as-is.
+ifneq (,$(CROSS_COMPILE))
+ifeq ($(origin CC),default)
+CSTR := "\#ifdef __clang__\nCLANG\n\#endif\n"
+ifeq ($(PLATFORM),FreeBSD)
+ # XXX: FreeBSD needs extra escaping for some reason
+ CSTR := $$$(CSTR)
+endif
+ifneq (,$(shell echo $(CSTR) | $(CC) -E - | grep CLANG))
+ CC := $(CROSS_COMPILE)clang
+else
+ CC := $(CROSS_COMPILE)gcc
+endif # Clang
+endif # cc is Make's default
+endif # CROSS_COMPILE non-empty
+
+LD=$(CROSS_COMPILE)ld
+AR=$(CROSS_COMPILE)ar
+RANLIB=$(CROSS_COMPILE)ranlib
+
+ifndef MAKE
+# BSDs refer to GNU Make as gmake
+ifneq (,$(findstring $(PLATFORM),FreeBSD OpenBSD DragonFly NetBSD))
+ MAKE=gmake
+else
+ MAKE=make
+endif
+endif
+
+LTM_CFLAGS += -I./ -Wall -Wsign-compare -Wextra -Wshadow
+
+ifdef SANITIZER
+LTM_CFLAGS += -fsanitize=undefined -fno-sanitize-recover=all -fno-sanitize=float-divide-by-zero
+endif
+
+ifndef NO_ADDTL_WARNINGS
+# additional warnings
+LTM_CFLAGS += -Wdeclaration-after-statement -Wbad-function-cast -Wcast-align
+LTM_CFLAGS += -Wstrict-prototypes -Wpointer-arith
+endif
+
+ifdef CONV_WARNINGS
+LTM_CFLAGS += -std=c89 -Wconversion -Wsign-conversion
+ifeq ($(CONV_WARNINGS), strict)
+LTM_CFLAGS += -DMP_USE_ENUMS -Wc++-compat
+endif
+else
+LTM_CFLAGS += -Wsystem-headers
+endif
+
+ifdef COMPILE_DEBUG
+#debug
+LTM_CFLAGS += -g3
+endif
+
+ifdef COMPILE_SIZE
+#for size
+LTM_CFLAGS += -Os
+else
+
+ifndef IGNORE_SPEED
+#for speed
+LTM_CFLAGS += -O3 -funroll-loops
+
+#x86 optimizations [should be valid for any GCC install though]
+LTM_CFLAGS += -fomit-frame-pointer
+endif
+
+endif # COMPILE_SIZE
+
+ifneq ($(findstring clang,$(CC)),)
+LTM_CFLAGS += -Wno-typedef-redefinition -Wno-tautological-compare -Wno-builtin-requires-header
+endif
+ifneq ($(findstring mingw,$(CC)),)
+LTM_CFLAGS += -Wno-shadow
+endif
+ifeq ($(PLATFORM), Darwin)
+LTM_CFLAGS += -Wno-nullability-completeness
+endif
+ifeq ($(PLATFORM), CYGWIN)
+LIBTOOLFLAGS += -no-undefined
+endif
+
+# add in the standard FLAGS
+LTM_CFLAGS += $(CFLAGS)
+LTM_LFLAGS += $(LFLAGS)
+LTM_LDFLAGS += $(LDFLAGS)
+LTM_LIBTOOLFLAGS += $(LIBTOOLFLAGS)
+
+
+ifeq ($(PLATFORM),FreeBSD)
+ _ARCH := $(shell sysctl -b hw.machine_arch)
+else
+ _ARCH := $(shell uname -m)
+endif
+
+# adjust coverage set
+ifneq ($(filter $(_ARCH), i386 i686 x86_64 amd64 ia64),)
+ COVERAGE = test_standalone timing
+ COVERAGE_APP = ./test && ./timing
+else
+ COVERAGE = test_standalone
+ COVERAGE_APP = ./test
+endif
+
+HEADERS_PUB=tommath.h
+HEADERS=tommath_private.h tommath_class.h tommath_superclass.h tommath_cutoffs.h $(HEADERS_PUB)
+
+#LIBPATH The directory for libtommath to be installed to.
+#INCPATH The directory to install the header files for libtommath.
+#DATAPATH The directory to install the pdf docs.
+DESTDIR ?=
+PREFIX ?= /usr/local
+LIBPATH ?= $(PREFIX)/lib
+INCPATH ?= $(PREFIX)/include
+DATAPATH ?= $(PREFIX)/share/doc/libtommath/pdf
+
+#make the code coverage of the library
+#
+coverage: LTM_CFLAGS += -fprofile-arcs -ftest-coverage -DTIMING_NO_LOGS
+coverage: LTM_LFLAGS += -lgcov
+coverage: LTM_LDFLAGS += -lgcov
+
+coverage: $(COVERAGE)
+ $(COVERAGE_APP)
+
+lcov: coverage
+ rm -f coverage.info
+ lcov --capture --no-external --no-recursion $(LCOV_ARGS) --output-file coverage.info -q
+ genhtml coverage.info --output-directory coverage -q
+
+# target that removes all coverage output
+cleancov-clean:
+ rm -f `find . -type f -name "*.info" | xargs`
+ rm -rf coverage/
+
+# cleans everything - coverage output and standard 'clean'
+cleancov: cleancov-clean clean
+
+clean:
+ rm -f *.gcda *.gcno *.gcov *.bat *.o *.a *.obj *.lib *.exe *.dll etclib/*.o \
+ demo/*.o test timing mtest_opponent mtest/mtest mtest/mtest.exe tuning_list \
+ *.s mpi.c *.da *.dyn *.dpi tommath.tex `find . -type f | grep [~] | xargs` *.lo *.la
+ rm -rf .libs/ demo/.libs
+ ${MAKE} -C etc/ clean MAKE=${MAKE}
+ ${MAKE} -C doc/ clean MAKE=${MAKE}
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/mtest/logtab.h b/third_party/heimdal/lib/hcrypto/libtommath/mtest/logtab.h
new file mode 100644
index 0000000..dae3344
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/mtest/logtab.h
@@ -0,0 +1,24 @@
+const float s_logv_2[] = {
+ 0.000000000, 0.000000000, 1.000000000, 0.630929754, /* 0 1 2 3 */
+ 0.500000000, 0.430676558, 0.386852807, 0.356207187, /* 4 5 6 7 */
+ 0.333333333, 0.315464877, 0.301029996, 0.289064826, /* 8 9 10 11 */
+ 0.278942946, 0.270238154, 0.262649535, 0.255958025, /* 12 13 14 15 */
+ 0.250000000, 0.244650542, 0.239812467, 0.235408913, /* 16 17 18 19 */
+ 0.231378213, 0.227670249, 0.224243824, 0.221064729, /* 20 21 22 23 */
+ 0.218104292, 0.215338279, 0.212746054, 0.210309918, /* 24 25 26 27 */
+ 0.208014598, 0.205846832, 0.203795047, 0.201849087, /* 28 29 30 31 */
+ 0.200000000, 0.198239863, 0.196561632, 0.194959022, /* 32 33 34 35 */
+ 0.193426404, 0.191958720, 0.190551412, 0.189200360, /* 36 37 38 39 */
+ 0.187901825, 0.186652411, 0.185449023, 0.184288833, /* 40 41 42 43 */
+ 0.183169251, 0.182087900, 0.181042597, 0.180031327, /* 44 45 46 47 */
+ 0.179052232, 0.178103594, 0.177183820, 0.176291434, /* 48 49 50 51 */
+ 0.175425064, 0.174583430, 0.173765343, 0.172969690, /* 52 53 54 55 */
+ 0.172195434, 0.171441601, 0.170707280, 0.169991616, /* 56 57 58 59 */
+ 0.169293808, 0.168613099, 0.167948779, 0.167300179, /* 60 61 62 63 */
+ 0.166666667
+};
+
+
+/* $Source$ */
+/* $Revision$ */
+/* $Date$ */
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi-config.h b/third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi-config.h
new file mode 100644
index 0000000..ea576e5
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi-config.h
@@ -0,0 +1,90 @@
+/* Default configuration for MPI library */
+/* $Id$ */
+
+#ifndef MPI_CONFIG_H_
+#define MPI_CONFIG_H_
+
+/*
+ For boolean options,
+ 0 = no
+ 1 = yes
+
+ Other options are documented individually.
+
+ */
+
+#ifndef MP_IOFUNC
+#define MP_IOFUNC 0 /* include mp_print() ? */
+#endif
+
+#ifndef MP_MODARITH
+#define MP_MODARITH 1 /* include modular arithmetic ? */
+#endif
+
+#ifndef MP_NUMTH
+#define MP_NUMTH 1 /* include number theoretic functions? */
+#endif
+
+#ifndef MP_LOGTAB
+#define MP_LOGTAB 1 /* use table of logs instead of log()? */
+#endif
+
+#ifndef MP_MEMSET
+#define MP_MEMSET 1 /* use memset() to zero buffers? */
+#endif
+
+#ifndef MP_MEMCPY
+#define MP_MEMCPY 1 /* use memcpy() to copy buffers? */
+#endif
+
+#ifndef MP_CRYPTO
+#define MP_CRYPTO 1 /* erase memory on free? */
+#endif
+
+#ifndef MP_ARGCHK
+/*
+ 0 = no parameter checks
+ 1 = runtime checks, continue execution and return an error to caller
+ 2 = assertions; dump core on parameter errors
+ */
+#define MP_ARGCHK 2 /* how to check input arguments */
+#endif
+
+#ifndef MP_DEBUG
+#define MP_DEBUG 0 /* print diagnostic output? */
+#endif
+
+#ifndef MP_DEFPREC
+#define MP_DEFPREC 64 /* default precision, in digits */
+#endif
+
+#ifndef MP_MACRO
+#define MP_MACRO 1 /* use macros for frequent calls? */
+#endif
+
+#ifndef MP_SQUARE
+#define MP_SQUARE 1 /* use separate squaring code? */
+#endif
+
+#ifndef MP_PTAB_SIZE
+/*
+ When building mpprime.c, we build in a table of small prime
+ values to use for primality testing. The more you include,
+ the more space they take up. See primes.c for the possible
+ values (currently 16, 32, 64, 128, 256, and 6542)
+ */
+#define MP_PTAB_SIZE 128 /* how many built-in primes? */
+#endif
+
+#ifndef MP_COMPAT_MACROS
+#define MP_COMPAT_MACROS 1 /* define compatibility macros? */
+#endif
+
+#endif /* ifndef MPI_CONFIG_H_ */
+
+
+/* crc==3287762869, version==2, Sat Feb 02 06:43:53 2002 */
+
+/* $Source$ */
+/* $Revision$ */
+/* $Date$ */
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi-types.h b/third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi-types.h
new file mode 100644
index 0000000..f99d7ee
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi-types.h
@@ -0,0 +1,20 @@
+/* Type definitions generated by 'types.pl' */
+typedef char mp_sign;
+typedef unsigned short mp_digit; /* 2 byte type */
+typedef unsigned int mp_word; /* 4 byte type */
+typedef unsigned int mp_size;
+typedef int mp_err;
+
+#define MP_DIGIT_BIT (CHAR_BIT*sizeof(mp_digit))
+#define MP_DIGIT_MAX USHRT_MAX
+#define MP_WORD_BIT (CHAR_BIT*sizeof(mp_word))
+#define MP_WORD_MAX UINT_MAX
+
+#define MP_DIGIT_SIZE 2
+#define DIGIT_FMT "%04X"
+#define RADIX (MP_DIGIT_MAX+1)
+
+
+/* $Source$ */
+/* $Revision$ */
+/* $Date$ */
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi.c b/third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi.c
new file mode 100644
index 0000000..7e71ad6
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi.c
@@ -0,0 +1,3987 @@
+/*
+ mpi.c
+
+ by Michael J. Fromberger <sting@linguist.dartmouth.edu>
+ Copyright (C) 1998 Michael J. Fromberger
+
+ Arbitrary precision integer arithmetic library
+
+ SPDX-License-Identifier: Unlicense
+
+ $Id$
+ */
+
+#include "mpi.h"
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+
+#if MP_DEBUG
+#include <stdio.h>
+
+#define DIAG(T,V) {fprintf(stderr,T);mp_print(V,stderr);fputc('\n',stderr);}
+#else
+#define DIAG(T,V)
+#endif
+
+/*
+ If MP_LOGTAB is not defined, use the math library to compute the
+ logarithms on the fly. Otherwise, use the static table below.
+ Pick which works best for your system.
+ */
+#if MP_LOGTAB
+
+/* {{{ s_logv_2[] - log table for 2 in various bases */
+
+/*
+ A table of the logs of 2 for various bases (the 0 and 1 entries of
+ this table are meaningless and should not be referenced).
+
+ This table is used to compute output lengths for the mp_toradix()
+ function. Since a number n in radix r takes up about log_r(n)
+ digits, we estimate the output size by taking the least integer
+ greater than log_r(n), where:
+
+ log_r(n) = log_2(n) * log_r(2)
+
+ This table, therefore, is a table of log_r(2) for 2 <= r <= 36,
+ which are the output bases supported.
+ */
+
+#include "logtab.h"
+
+/* }}} */
+#define LOG_V_2(R) s_logv_2[(R)]
+
+#else
+
+#include <math.h>
+#define LOG_V_2(R) (log(2.0)/log(R))
+
+#endif
+
+/* Default precision for newly created mp_int's */
+static unsigned int s_mp_defprec = MP_DEFPREC;
+
+/* {{{ Digit arithmetic macros */
+
+/*
+ When adding and multiplying digits, the results can be larger than
+ can be contained in an mp_digit. Thus, an mp_word is used. These
+ macros mask off the upper and lower digits of the mp_word (the
+ mp_word may be more than 2 mp_digits wide, but we only concern
+ ourselves with the low-order 2 mp_digits)
+
+ If your mp_word DOES have more than 2 mp_digits, you need to
+ uncomment the first line, and comment out the second.
+ */
+
+/* #define CARRYOUT(W) (((W)>>DIGIT_BIT)&MP_DIGIT_MAX) */
+#define CARRYOUT(W) ((W)>>DIGIT_BIT)
+#define ACCUM(W) ((W)&MP_DIGIT_MAX)
+
+/* }}} */
+
+/* {{{ Comparison constants */
+
+#define MP_LT -1
+#define MP_EQ 0
+#define MP_GT 1
+
+/* }}} */
+
+/* {{{ Constant strings */
+
+/* Constant strings returned by mp_strerror() */
+static const char *mp_err_string[] = {
+ "unknown result code", /* say what? */
+ "boolean true", /* MP_OKAY, MP_YES */
+ "boolean false", /* MP_NO */
+ "out of memory", /* MP_MEM */
+ "argument out of range", /* MP_RANGE */
+ "invalid input parameter", /* MP_BADARG */
+ "result is undefined" /* MP_UNDEF */
+};
+
+/* Value to digit maps for radix conversion */
+
+/* s_dmap_1 - standard digits and letters */
+static const char *s_dmap_1 =
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
+
+#if 0
+/* s_dmap_2 - base64 ordering for digits */
+static const char *s_dmap_2 =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+#endif
+
+/* }}} */
+
+/* {{{ Static function declarations */
+
+/*
+ If MP_MACRO is false, these will be defined as actual functions;
+ otherwise, suitable macro definitions will be used. This works
+ around the fact that ANSI C89 doesn't support an 'inline' keyword
+ (although I hear C9x will ... about bloody time). At present, the
+ macro definitions are identical to the function bodies, but they'll
+ expand in place, instead of generating a function call.
+
+ I chose these particular functions to be made into macros because
+ some profiling showed they are called a lot on a typical workload,
+ and yet they are primarily housekeeping.
+ */
+#if MP_MACRO == 0
+ void s_mp_setz(mp_digit *dp, mp_size count); /* zero digits */
+ void s_mp_copy(mp_digit *sp, mp_digit *dp, mp_size count); /* copy */
+ void *s_mp_alloc(size_t nb, size_t ni); /* general allocator */
+ void s_mp_free(void *ptr); /* general free function */
+#else
+
+ /* Even if these are defined as macros, we need to respect the settings
+ of the MP_MEMSET and MP_MEMCPY configuration options...
+ */
+ #if MP_MEMSET == 0
+ #define s_mp_setz(dp, count) \
+ {int ix;for(ix=0;ix<(count);ix++)(dp)[ix]=0;}
+ #else
+ #define s_mp_setz(dp, count) memset(dp, 0, (count) * sizeof(mp_digit))
+ #endif /* MP_MEMSET */
+
+ #if MP_MEMCPY == 0
+ #define s_mp_copy(sp, dp, count) \
+ {int ix;for(ix=0;ix<(count);ix++)(dp)[ix]=(sp)[ix];}
+ #else
+ #define s_mp_copy(sp, dp, count) memcpy(dp, sp, (count) * sizeof(mp_digit))
+ #endif /* MP_MEMCPY */
+
+ #define s_mp_alloc(nb, ni) calloc(nb, ni)
+ #define s_mp_free(ptr) {if(ptr) free(ptr);}
+#endif /* MP_MACRO */
+
+mp_err s_mp_grow(mp_int *mp, mp_size min); /* increase allocated size */
+mp_err s_mp_pad(mp_int *mp, mp_size min); /* left pad with zeroes */
+
+void s_mp_clamp(mp_int *mp); /* clip leading zeroes */
+
+void s_mp_exch(mp_int *a, mp_int *b); /* swap a and b in place */
+
+mp_err s_mp_lshd(mp_int *mp, mp_size p); /* left-shift by p digits */
+void s_mp_rshd(mp_int *mp, mp_size p); /* right-shift by p digits */
+void s_mp_div_2d(mp_int *mp, mp_digit d); /* divide by 2^d in place */
+void s_mp_mod_2d(mp_int *mp, mp_digit d); /* modulo 2^d in place */
+mp_err s_mp_mul_2d(mp_int *mp, mp_digit d); /* multiply by 2^d in place*/
+void s_mp_div_2(mp_int *mp); /* divide by 2 in place */
+mp_err s_mp_mul_2(mp_int *mp); /* multiply by 2 in place */
+mp_digit s_mp_norm(mp_int *a, mp_int *b); /* normalize for division */
+mp_err s_mp_add_d(mp_int *mp, mp_digit d); /* unsigned digit addition */
+mp_err s_mp_sub_d(mp_int *mp, mp_digit d); /* unsigned digit subtract */
+mp_err s_mp_mul_d(mp_int *mp, mp_digit d); /* unsigned digit multiply */
+mp_err s_mp_div_d(mp_int *mp, mp_digit d, mp_digit *r);
+ /* unsigned digit divide */
+mp_err s_mp_reduce(mp_int *x, mp_int *m, mp_int *mu);
+ /* Barrett reduction */
+mp_err s_mp_add(mp_int *a, mp_int *b); /* magnitude addition */
+mp_err s_mp_sub(mp_int *a, mp_int *b); /* magnitude subtract */
+mp_err s_mp_mul(mp_int *a, mp_int *b); /* magnitude multiply */
+#if 0
+void s_mp_kmul(mp_digit *a, mp_digit *b, mp_digit *out, mp_size len);
+ /* multiply buffers in place */
+#endif
+#if MP_SQUARE
+mp_err s_mp_sqr(mp_int *a); /* magnitude square */
+#else
+#define s_mp_sqr(a) s_mp_mul(a, a)
+#endif
+mp_err s_mp_div(mp_int *a, mp_int *b); /* magnitude divide */
+mp_err s_mp_2expt(mp_int *a, mp_digit k); /* a = 2^k */
+int s_mp_cmp(mp_int *a, mp_int *b); /* magnitude comparison */
+int s_mp_cmp_d(mp_int *a, mp_digit d); /* magnitude digit compare */
+int s_mp_ispow2(mp_int *v); /* is v a power of 2? */
+int s_mp_ispow2d(mp_digit d); /* is d a power of 2? */
+
+int s_mp_tovalue(char ch, int r); /* convert ch to value */
+char s_mp_todigit(int val, int r, int low); /* convert val to digit */
+int s_mp_outlen(int bits, int r); /* output length in bytes */
+
+/* }}} */
+
+/* {{{ Default precision manipulation */
+
+unsigned int mp_get_prec(void)
+{
+ return s_mp_defprec;
+
+} /* end mp_get_prec() */
+
+void mp_set_prec(unsigned int prec)
+{
+ if(prec == 0)
+ s_mp_defprec = MP_DEFPREC;
+ else
+ s_mp_defprec = prec;
+
+} /* end mp_set_prec() */
+
+/* }}} */
+
+/*------------------------------------------------------------------------*/
+/* {{{ mp_init(mp) */
+
+/*
+ mp_init(mp)
+
+ Initialize a new zero-valued mp_int. Returns MP_OKAY if successful,
+ MP_MEM if memory could not be allocated for the structure.
+ */
+
+mp_err mp_init(mp_int *mp)
+{
+ return mp_init_size(mp, s_mp_defprec);
+
+} /* end mp_init() */
+
+/* }}} */
+
+/* {{{ mp_init_array(mp[], count) */
+
+mp_err mp_init_array(mp_int mp[], int count)
+{
+ mp_err res;
+ int pos;
+
+ ARGCHK(mp !=NULL && count > 0, MP_BADARG);
+
+ for(pos = 0; pos < count; ++pos) {
+ if((res = mp_init(&mp[pos])) != MP_OKAY)
+ goto CLEANUP;
+ }
+
+ return MP_OKAY;
+
+ CLEANUP:
+ while(--pos >= 0)
+ mp_clear(&mp[pos]);
+
+ return res;
+
+} /* end mp_init_array() */
+
+/* }}} */
+
+/* {{{ mp_init_size(mp, prec) */
+
+/*
+ mp_init_size(mp, prec)
+
+ Initialize a new zero-valued mp_int with at least the given
+ precision; returns MP_OKAY if successful, or MP_MEM if memory could
+ not be allocated for the structure.
+ */
+
+mp_err mp_init_size(mp_int *mp, mp_size prec)
+{
+ ARGCHK(mp != NULL && prec > 0, MP_BADARG);
+
+ if((DIGITS(mp) = s_mp_alloc(prec, sizeof(mp_digit))) == NULL)
+ return MP_MEM;
+
+ SIGN(mp) = MP_ZPOS;
+ USED(mp) = 1;
+ ALLOC(mp) = prec;
+
+ return MP_OKAY;
+
+} /* end mp_init_size() */
+
+/* }}} */
+
+/* {{{ mp_init_copy(mp, from) */
+
+/*
+ mp_init_copy(mp, from)
+
+ Initialize mp as an exact copy of from. Returns MP_OKAY if
+ successful, MP_MEM if memory could not be allocated for the new
+ structure.
+ */
+
+mp_err mp_init_copy(mp_int *mp, mp_int *from)
+{
+ ARGCHK(mp != NULL && from != NULL, MP_BADARG);
+
+ if(mp == from)
+ return MP_OKAY;
+
+ if((DIGITS(mp) = s_mp_alloc(USED(from), sizeof(mp_digit))) == NULL)
+ return MP_MEM;
+
+ s_mp_copy(DIGITS(from), DIGITS(mp), USED(from));
+ USED(mp) = USED(from);
+ ALLOC(mp) = USED(from);
+ SIGN(mp) = SIGN(from);
+
+ return MP_OKAY;
+
+} /* end mp_init_copy() */
+
+/* }}} */
+
+/* {{{ mp_copy(from, to) */
+
+/*
+ mp_copy(from, to)
+
+ Copies the mp_int 'from' to the mp_int 'to'. It is presumed that
+ 'to' has already been initialized (if not, use mp_init_copy()
+ instead). If 'from' and 'to' are identical, nothing happens.
+ */
+
+mp_err mp_copy(mp_int *from, mp_int *to)
+{
+ ARGCHK(from != NULL && to != NULL, MP_BADARG);
+
+ if(from == to)
+ return MP_OKAY;
+
+ { /* copy */
+ mp_digit *tmp;
+
+ /*
+ If the allocated buffer in 'to' already has enough space to hold
+ all the used digits of 'from', we'll re-use it to avoid hitting
+ the memory allocater more than necessary; otherwise, we'd have
+ to grow anyway, so we just allocate a hunk and make the copy as
+ usual
+ */
+ if(ALLOC(to) >= USED(from)) {
+ s_mp_setz(DIGITS(to) + USED(from), ALLOC(to) - USED(from));
+ s_mp_copy(DIGITS(from), DIGITS(to), USED(from));
+
+ } else {
+ if((tmp = s_mp_alloc(USED(from), sizeof(mp_digit))) == NULL)
+ return MP_MEM;
+
+ s_mp_copy(DIGITS(from), tmp, USED(from));
+
+ if(DIGITS(to) != NULL) {
+#if MP_CRYPTO
+ s_mp_setz(DIGITS(to), ALLOC(to));
+#endif
+ s_mp_free(DIGITS(to));
+ }
+
+ DIGITS(to) = tmp;
+ ALLOC(to) = USED(from);
+ }
+
+ /* Copy the precision and sign from the original */
+ USED(to) = USED(from);
+ SIGN(to) = SIGN(from);
+ } /* end copy */
+
+ return MP_OKAY;
+
+} /* end mp_copy() */
+
+/* }}} */
+
+/* {{{ mp_exch(mp1, mp2) */
+
+/*
+ mp_exch(mp1, mp2)
+
+ Exchange mp1 and mp2 without allocating any intermediate memory
+ (well, unless you count the stack space needed for this call and the
+ locals it creates...). This cannot fail.
+ */
+
+void mp_exch(mp_int *mp1, mp_int *mp2)
+{
+#if MP_ARGCHK == 2
+ assert(mp1 != NULL && mp2 != NULL);
+#else
+ if(mp1 == NULL || mp2 == NULL)
+ return;
+#endif
+
+ s_mp_exch(mp1, mp2);
+
+} /* end mp_exch() */
+
+/* }}} */
+
+/* {{{ mp_clear(mp) */
+
+/*
+ mp_clear(mp)
+
+ Release the storage used by an mp_int, and void its fields so that
+ if someone calls mp_clear() again for the same int later, we won't
+ get tollchocked.
+ */
+
+void mp_clear(mp_int *mp)
+{
+ if(mp == NULL)
+ return;
+
+ if(DIGITS(mp) != NULL) {
+#if MP_CRYPTO
+ s_mp_setz(DIGITS(mp), ALLOC(mp));
+#endif
+ s_mp_free(DIGITS(mp));
+ DIGITS(mp) = NULL;
+ }
+
+ USED(mp) = 0;
+ ALLOC(mp) = 0;
+
+} /* end mp_clear() */
+
+/* }}} */
+
+/* {{{ mp_clear_array(mp[], count) */
+
+void mp_clear_array(mp_int mp[], int count)
+{
+ ARGCHK(mp != NULL && count > 0, MP_BADARG);
+
+ while(--count >= 0)
+ mp_clear(&mp[count]);
+
+} /* end mp_clear_array() */
+
+/* }}} */
+
+/* {{{ mp_zero(mp) */
+
+/*
+ mp_zero(mp)
+
+ Set mp to zero. Does not change the allocated size of the structure,
+ and therefore cannot fail (except on a bad argument, which we ignore)
+ */
+void mp_zero(mp_int *mp)
+{
+ if(mp == NULL)
+ return;
+
+ s_mp_setz(DIGITS(mp), ALLOC(mp));
+ USED(mp) = 1;
+ SIGN(mp) = MP_ZPOS;
+
+} /* end mp_zero() */
+
+/* }}} */
+
+/* {{{ mp_set(mp, d) */
+
+void mp_set(mp_int *mp, mp_digit d)
+{
+ if(mp == NULL)
+ return;
+
+ mp_zero(mp);
+ DIGIT(mp, 0) = d;
+
+} /* end mp_set() */
+
+/* }}} */
+
+/* {{{ mp_set_int(mp, z) */
+
+mp_err mp_set_int(mp_int *mp, long z)
+{
+ int ix;
+ unsigned long v = labs(z);
+ mp_err res;
+
+ ARGCHK(mp != NULL, MP_BADARG);
+
+ mp_zero(mp);
+ if(z == 0)
+ return MP_OKAY; /* shortcut for zero */
+
+ for(ix = sizeof(long) - 1; ix >= 0; ix--) {
+
+ if((res = s_mp_mul_2d(mp, CHAR_BIT)) != MP_OKAY)
+ return res;
+
+ res = s_mp_add_d(mp,
+ (mp_digit)((v >> (ix * CHAR_BIT)) & UCHAR_MAX));
+ if(res != MP_OKAY)
+ return res;
+
+ }
+
+ if(z < 0)
+ SIGN(mp) = MP_NEG;
+
+ return MP_OKAY;
+
+} /* end mp_set_int() */
+
+/* }}} */
+
+/*------------------------------------------------------------------------*/
+/* {{{ Digit arithmetic */
+
+/* {{{ mp_add_d(a, d, b) */
+
+/*
+ mp_add_d(a, d, b)
+
+ Compute the sum b = a + d, for a single digit d. Respects the sign of
+ its primary addend (single digits are unsigned anyway).
+ */
+
+mp_err mp_add_d(mp_int *a, mp_digit d, mp_int *b)
+{
+ mp_err res = MP_OKAY;
+
+ ARGCHK(a != NULL && b != NULL, MP_BADARG);
+
+ if((res = mp_copy(a, b)) != MP_OKAY)
+ return res;
+
+ if(SIGN(b) == MP_ZPOS) {
+ res = s_mp_add_d(b, d);
+ } else if(s_mp_cmp_d(b, d) >= 0) {
+ res = s_mp_sub_d(b, d);
+ } else {
+ SIGN(b) = MP_ZPOS;
+
+ DIGIT(b, 0) = d - DIGIT(b, 0);
+ }
+
+ return res;
+
+} /* end mp_add_d() */
+
+/* }}} */
+
+/* {{{ mp_sub_d(a, d, b) */
+
+/*
+ mp_sub_d(a, d, b)
+
+ Compute the difference b = a - d, for a single digit d. Respects the
+ sign of its subtrahend (single digits are unsigned anyway).
+ */
+
+mp_err mp_sub_d(mp_int *a, mp_digit d, mp_int *b)
+{
+ mp_err res;
+
+ ARGCHK(a != NULL && b != NULL, MP_BADARG);
+
+ if((res = mp_copy(a, b)) != MP_OKAY)
+ return res;
+
+ if(SIGN(b) == MP_NEG) {
+ if((res = s_mp_add_d(b, d)) != MP_OKAY)
+ return res;
+
+ } else if(s_mp_cmp_d(b, d) >= 0) {
+ if((res = s_mp_sub_d(b, d)) != MP_OKAY)
+ return res;
+
+ } else {
+ mp_neg(b, b);
+
+ DIGIT(b, 0) = d - DIGIT(b, 0);
+ SIGN(b) = MP_NEG;
+ }
+
+ if(s_mp_cmp_d(b, 0) == 0)
+ SIGN(b) = MP_ZPOS;
+
+ return MP_OKAY;
+
+} /* end mp_sub_d() */
+
+/* }}} */
+
+/* {{{ mp_mul_d(a, d, b) */
+
+/*
+ mp_mul_d(a, d, b)
+
+ Compute the product b = a * d, for a single digit d. Respects the sign
+ of its multiplicand (single digits are unsigned anyway)
+ */
+
+mp_err mp_mul_d(mp_int *a, mp_digit d, mp_int *b)
+{
+ mp_err res;
+
+ ARGCHK(a != NULL && b != NULL, MP_BADARG);
+
+ if(d == 0) {
+ mp_zero(b);
+ return MP_OKAY;
+ }
+
+ if((res = mp_copy(a, b)) != MP_OKAY)
+ return res;
+
+ res = s_mp_mul_d(b, d);
+
+ return res;
+
+} /* end mp_mul_d() */
+
+/* }}} */
+
+/* {{{ mp_mul_2(a, c) */
+
+mp_err mp_mul_2(mp_int *a, mp_int *c)
+{
+ mp_err res;
+
+ ARGCHK(a != NULL && c != NULL, MP_BADARG);
+
+ if((res = mp_copy(a, c)) != MP_OKAY)
+ return res;
+
+ return s_mp_mul_2(c);
+
+} /* end mp_mul_2() */
+
+/* }}} */
+
+/* {{{ mp_div_d(a, d, q, r) */
+
+/*
+ mp_div_d(a, d, q, r)
+
+ Compute the quotient q = a / d and remainder r = a mod d, for a
+ single digit d. Respects the sign of its divisor (single digits are
+ unsigned anyway).
+ */
+
+mp_err mp_div_d(mp_int *a, mp_digit d, mp_int *q, mp_digit *r)
+{
+ mp_err res;
+ mp_digit rem;
+ int pow;
+
+ ARGCHK(a != NULL, MP_BADARG);
+
+ if(d == 0)
+ return MP_RANGE;
+
+ /* Shortcut for powers of two ... */
+ if((pow = s_mp_ispow2d(d)) >= 0) {
+ mp_digit mask;
+
+ mask = (1 << pow) - 1;
+ rem = DIGIT(a, 0) & mask;
+
+ if(q) {
+ mp_copy(a, q);
+ s_mp_div_2d(q, pow);
+ }
+
+ if(r)
+ *r = rem;
+
+ return MP_OKAY;
+ }
+
+ /*
+ If the quotient is actually going to be returned, we'll try to
+ avoid hitting the memory allocator by copying the dividend into it
+ and doing the division there. This can't be any _worse_ than
+ always copying, and will sometimes be better (since it won't make
+ another copy)
+
+ If it's not going to be returned, we need to allocate a temporary
+ to hold the quotient, which will just be discarded.
+ */
+ if(q) {
+ if((res = mp_copy(a, q)) != MP_OKAY)
+ return res;
+
+ res = s_mp_div_d(q, d, &rem);
+ if(s_mp_cmp_d(q, 0) == MP_EQ)
+ SIGN(q) = MP_ZPOS;
+
+ } else {
+ mp_int qp;
+
+ if((res = mp_init_copy(&qp, a)) != MP_OKAY)
+ return res;
+
+ res = s_mp_div_d(&qp, d, &rem);
+ if(s_mp_cmp_d(&qp, 0) == 0)
+ SIGN(&qp) = MP_ZPOS;
+
+ mp_clear(&qp);
+ }
+
+ if(r)
+ *r = rem;
+
+ return res;
+
+} /* end mp_div_d() */
+
+/* }}} */
+
+/* {{{ mp_div_2(a, c) */
+
+/*
+ mp_div_2(a, c)
+
+ Compute c = a / 2, disregarding the remainder.
+ */
+
+mp_err mp_div_2(mp_int *a, mp_int *c)
+{
+ mp_err res;
+
+ ARGCHK(a != NULL && c != NULL, MP_BADARG);
+
+ if((res = mp_copy(a, c)) != MP_OKAY)
+ return res;
+
+ s_mp_div_2(c);
+
+ return MP_OKAY;
+
+} /* end mp_div_2() */
+
+/* }}} */
+
+/* {{{ mp_expt_d(a, d, b) */
+
+mp_err mp_expt_d(mp_int *a, mp_digit d, mp_int *c)
+{
+ mp_int s, x;
+ mp_err res;
+
+ ARGCHK(a != NULL && c != NULL, MP_BADARG);
+
+ if((res = mp_init(&s)) != MP_OKAY)
+ return res;
+ if((res = mp_init_copy(&x, a)) != MP_OKAY)
+ goto X;
+
+ DIGIT(&s, 0) = 1;
+
+ while(d != 0) {
+ if(d & 1) {
+ if((res = s_mp_mul(&s, &x)) != MP_OKAY)
+ goto CLEANUP;
+ }
+
+ d >>= 1;
+
+ if((res = s_mp_sqr(&x)) != MP_OKAY)
+ goto CLEANUP;
+ }
+
+ s_mp_exch(&s, c);
+
+CLEANUP:
+ mp_clear(&x);
+X:
+ mp_clear(&s);
+
+ return res;
+
+} /* end mp_expt_d() */
+
+/* }}} */
+
+/* }}} */
+
+/*------------------------------------------------------------------------*/
+/* {{{ Full arithmetic */
+
+/* {{{ mp_abs(a, b) */
+
+/*
+ mp_abs(a, b)
+
+ Compute b = |a|. 'a' and 'b' may be identical.
+ */
+
+mp_err mp_abs(mp_int *a, mp_int *b)
+{
+ mp_err res;
+
+ ARGCHK(a != NULL && b != NULL, MP_BADARG);
+
+ if((res = mp_copy(a, b)) != MP_OKAY)
+ return res;
+
+ SIGN(b) = MP_ZPOS;
+
+ return MP_OKAY;
+
+} /* end mp_abs() */
+
+/* }}} */
+
+/* {{{ mp_neg(a, b) */
+
+/*
+ mp_neg(a, b)
+
+ Compute b = -a. 'a' and 'b' may be identical.
+ */
+
+mp_err mp_neg(mp_int *a, mp_int *b)
+{
+ mp_err res;
+
+ ARGCHK(a != NULL && b != NULL, MP_BADARG);
+
+ if((res = mp_copy(a, b)) != MP_OKAY)
+ return res;
+
+ if(s_mp_cmp_d(b, 0) == MP_EQ)
+ SIGN(b) = MP_ZPOS;
+ else
+ SIGN(b) = (SIGN(b) == MP_NEG) ? MP_ZPOS : MP_NEG;
+
+ return MP_OKAY;
+
+} /* end mp_neg() */
+
+/* }}} */
+
+/* {{{ mp_add(a, b, c) */
+
+/*
+ mp_add(a, b, c)
+
+ Compute c = a + b. All parameters may be identical.
+ */
+
+mp_err mp_add(mp_int *a, mp_int *b, mp_int *c)
+{
+ mp_err res;
+ int cmp;
+
+ ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG);
+
+ if(SIGN(a) == SIGN(b)) { /* same sign: add values, keep sign */
+
+ /* Commutativity of addition lets us do this in either order,
+ so we avoid having to use a temporary even if the result
+ is supposed to replace the output
+ */
+ if(c == b) {
+ if((res = s_mp_add(c, a)) != MP_OKAY)
+ return res;
+ } else {
+ if(c != a && (res = mp_copy(a, c)) != MP_OKAY)
+ return res;
+
+ if((res = s_mp_add(c, b)) != MP_OKAY)
+ return res;
+ }
+
+ } else if((cmp = s_mp_cmp(a, b)) > 0) { /* different sign: a > b */
+
+ /* If the output is going to be clobbered, we will use a temporary
+ variable; otherwise, we'll do it without touching the memory
+ allocator at all, if possible
+ */
+ if(c == b) {
+ mp_int tmp;
+
+ if((res = mp_init_copy(&tmp, a)) != MP_OKAY)
+ return res;
+ if((res = s_mp_sub(&tmp, b)) != MP_OKAY) {
+ mp_clear(&tmp);
+ return res;
+ }
+
+ s_mp_exch(&tmp, c);
+ mp_clear(&tmp);
+
+ } else {
+
+ if(c != a && (res = mp_copy(a, c)) != MP_OKAY)
+ return res;
+ if((res = s_mp_sub(c, b)) != MP_OKAY)
+ return res;
+
+ }
+
+ } else if(cmp == 0) { /* different sign, a == b */
+
+ mp_zero(c);
+ return MP_OKAY;
+
+ } else { /* different sign: a < b */
+
+ /* See above... */
+ if(c == a) {
+ mp_int tmp;
+
+ if((res = mp_init_copy(&tmp, b)) != MP_OKAY)
+ return res;
+ if((res = s_mp_sub(&tmp, a)) != MP_OKAY) {
+ mp_clear(&tmp);
+ return res;
+ }
+
+ s_mp_exch(&tmp, c);
+ mp_clear(&tmp);
+
+ } else {
+
+ if(c != b && (res = mp_copy(b, c)) != MP_OKAY)
+ return res;
+ if((res = s_mp_sub(c, a)) != MP_OKAY)
+ return res;
+
+ }
+ }
+
+ if(USED(c) == 1 && DIGIT(c, 0) == 0)
+ SIGN(c) = MP_ZPOS;
+
+ return MP_OKAY;
+
+} /* end mp_add() */
+
+/* }}} */
+
+/* {{{ mp_sub(a, b, c) */
+
+/*
+ mp_sub(a, b, c)
+
+ Compute c = a - b. All parameters may be identical.
+ */
+
+mp_err mp_sub(mp_int *a, mp_int *b, mp_int *c)
+{
+ mp_err res;
+ int cmp;
+
+ ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG);
+
+ if(SIGN(a) != SIGN(b)) {
+ if(c == a) {
+ if((res = s_mp_add(c, b)) != MP_OKAY)
+ return res;
+ } else {
+ if(c != b && ((res = mp_copy(b, c)) != MP_OKAY))
+ return res;
+ if((res = s_mp_add(c, a)) != MP_OKAY)
+ return res;
+ SIGN(c) = SIGN(a);
+ }
+
+ } else if((cmp = s_mp_cmp(a, b)) > 0) { /* Same sign, a > b */
+ if(c == b) {
+ mp_int tmp;
+
+ if((res = mp_init_copy(&tmp, a)) != MP_OKAY)
+ return res;
+ if((res = s_mp_sub(&tmp, b)) != MP_OKAY) {
+ mp_clear(&tmp);
+ return res;
+ }
+ s_mp_exch(&tmp, c);
+ mp_clear(&tmp);
+
+ } else {
+ if(c != a && ((res = mp_copy(a, c)) != MP_OKAY))
+ return res;
+
+ if((res = s_mp_sub(c, b)) != MP_OKAY)
+ return res;
+ }
+
+ } else if(cmp == 0) { /* Same sign, equal magnitude */
+ mp_zero(c);
+ return MP_OKAY;
+
+ } else { /* Same sign, b > a */
+ if(c == a) {
+ mp_int tmp;
+
+ if((res = mp_init_copy(&tmp, b)) != MP_OKAY)
+ return res;
+
+ if((res = s_mp_sub(&tmp, a)) != MP_OKAY) {
+ mp_clear(&tmp);
+ return res;
+ }
+ s_mp_exch(&tmp, c);
+ mp_clear(&tmp);
+
+ } else {
+ if(c != b && ((res = mp_copy(b, c)) != MP_OKAY))
+ return res;
+
+ if((res = s_mp_sub(c, a)) != MP_OKAY)
+ return res;
+ }
+
+ SIGN(c) = !SIGN(b);
+ }
+
+ if(USED(c) == 1 && DIGIT(c, 0) == 0)
+ SIGN(c) = MP_ZPOS;
+
+ return MP_OKAY;
+
+} /* end mp_sub() */
+
+/* }}} */
+
+/* {{{ mp_mul(a, b, c) */
+
+/*
+ mp_mul(a, b, c)
+
+ Compute c = a * b. All parameters may be identical.
+ */
+
+mp_err mp_mul(mp_int *a, mp_int *b, mp_int *c)
+{
+ mp_err res;
+ mp_sign sgn;
+
+ ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG);
+
+ sgn = (SIGN(a) == SIGN(b)) ? MP_ZPOS : MP_NEG;
+
+ if(c == b) {
+ if((res = s_mp_mul(c, a)) != MP_OKAY)
+ return res;
+
+ } else {
+ if((res = mp_copy(a, c)) != MP_OKAY)
+ return res;
+
+ if((res = s_mp_mul(c, b)) != MP_OKAY)
+ return res;
+ }
+
+ if(sgn == MP_ZPOS || s_mp_cmp_d(c, 0) == MP_EQ)
+ SIGN(c) = MP_ZPOS;
+ else
+ SIGN(c) = sgn;
+
+ return MP_OKAY;
+
+} /* end mp_mul() */
+
+/* }}} */
+
+/* {{{ mp_mul_2d(a, d, c) */
+
+/*
+ mp_mul_2d(a, d, c)
+
+ Compute c = a * 2^d. a may be the same as c.
+ */
+
+mp_err mp_mul_2d(mp_int *a, mp_digit d, mp_int *c)
+{
+ mp_err res;
+
+ ARGCHK(a != NULL && c != NULL, MP_BADARG);
+
+ if((res = mp_copy(a, c)) != MP_OKAY)
+ return res;
+
+ if(d == 0)
+ return MP_OKAY;
+
+ return s_mp_mul_2d(c, d);
+
+} /* end mp_mul() */
+
+/* }}} */
+
+/* {{{ mp_sqr(a, b) */
+
+#if MP_SQUARE
+mp_err mp_sqr(mp_int *a, mp_int *b)
+{
+ mp_err res;
+
+ ARGCHK(a != NULL && b != NULL, MP_BADARG);
+
+ if((res = mp_copy(a, b)) != MP_OKAY)
+ return res;
+
+ if((res = s_mp_sqr(b)) != MP_OKAY)
+ return res;
+
+ SIGN(b) = MP_ZPOS;
+
+ return MP_OKAY;
+
+} /* end mp_sqr() */
+#endif
+
+/* }}} */
+
+/* {{{ mp_div(a, b, q, r) */
+
+/*
+ mp_div(a, b, q, r)
+
+ Compute q = a / b and r = a mod b. Input parameters may be re-used
+ as output parameters. If q or r is NULL, that portion of the
+ computation will be discarded (although it will still be computed)
+
+ Pay no attention to the hacker behind the curtain.
+ */
+
+mp_err mp_div(mp_int *a, mp_int *b, mp_int *q, mp_int *r)
+{
+ mp_err res;
+ mp_int qtmp, rtmp;
+ int cmp;
+
+ ARGCHK(a != NULL && b != NULL, MP_BADARG);
+
+ if(mp_cmp_z(b) == MP_EQ)
+ return MP_RANGE;
+
+ /* If a <= b, we can compute the solution without division, and
+ avoid any memory allocation
+ */
+ if((cmp = s_mp_cmp(a, b)) < 0) {
+ if(r) {
+ if((res = mp_copy(a, r)) != MP_OKAY)
+ return res;
+ }
+
+ if(q)
+ mp_zero(q);
+
+ return MP_OKAY;
+
+ } else if(cmp == 0) {
+
+ /* Set quotient to 1, with appropriate sign */
+ if(q) {
+ int qneg = (SIGN(a) != SIGN(b));
+
+ mp_set(q, 1);
+ if(qneg)
+ SIGN(q) = MP_NEG;
+ }
+
+ if(r)
+ mp_zero(r);
+
+ return MP_OKAY;
+ }
+
+ /* If we get here, it means we actually have to do some division */
+
+ /* Set up some temporaries... */
+ if((res = mp_init_copy(&qtmp, a)) != MP_OKAY)
+ return res;
+ if((res = mp_init_copy(&rtmp, b)) != MP_OKAY)
+ goto CLEANUP;
+
+ if((res = s_mp_div(&qtmp, &rtmp)) != MP_OKAY)
+ goto CLEANUP;
+
+ /* Compute the signs for the output */
+ SIGN(&rtmp) = SIGN(a); /* Sr = Sa */
+ if(SIGN(a) == SIGN(b))
+ SIGN(&qtmp) = MP_ZPOS; /* Sq = MP_ZPOS if Sa = Sb */
+ else
+ SIGN(&qtmp) = MP_NEG; /* Sq = MP_NEG if Sa != Sb */
+
+ if(s_mp_cmp_d(&qtmp, 0) == MP_EQ)
+ SIGN(&qtmp) = MP_ZPOS;
+ if(s_mp_cmp_d(&rtmp, 0) == MP_EQ)
+ SIGN(&rtmp) = MP_ZPOS;
+
+ /* Copy output, if it is needed */
+ if(q)
+ s_mp_exch(&qtmp, q);
+
+ if(r)
+ s_mp_exch(&rtmp, r);
+
+CLEANUP:
+ mp_clear(&rtmp);
+ mp_clear(&qtmp);
+
+ return res;
+
+} /* end mp_div() */
+
+/* }}} */
+
+/* {{{ mp_div_2d(a, d, q, r) */
+
+mp_err mp_div_2d(mp_int *a, mp_digit d, mp_int *q, mp_int *r)
+{
+ mp_err res;
+
+ ARGCHK(a != NULL, MP_BADARG);
+
+ if(q) {
+ if((res = mp_copy(a, q)) != MP_OKAY)
+ return res;
+
+ s_mp_div_2d(q, d);
+ }
+
+ if(r) {
+ if((res = mp_copy(a, r)) != MP_OKAY)
+ return res;
+
+ s_mp_mod_2d(r, d);
+ }
+
+ return MP_OKAY;
+
+} /* end mp_div_2d() */
+
+/* }}} */
+
+/* {{{ mp_expt(a, b, c) */
+
+/*
+ mp_expt(a, b, c)
+
+ Compute c = a ** b, that is, raise a to the b power. Uses a
+ standard iterative square-and-multiply technique.
+ */
+
+mp_err mp_expt(mp_int *a, mp_int *b, mp_int *c)
+{
+ mp_int s, x;
+ mp_err res;
+ mp_digit d;
+ unsigned int bit, dig;
+
+ ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG);
+
+ if(mp_cmp_z(b) < 0)
+ return MP_RANGE;
+
+ if((res = mp_init(&s)) != MP_OKAY)
+ return res;
+
+ mp_set(&s, 1);
+
+ if((res = mp_init_copy(&x, a)) != MP_OKAY)
+ goto X;
+
+ /* Loop over low-order digits in ascending order */
+ for(dig = 0; dig < (USED(b) - 1); dig++) {
+ d = DIGIT(b, dig);
+
+ /* Loop over bits of each non-maximal digit */
+ for(bit = 0; bit < DIGIT_BIT; bit++) {
+ if(d & 1) {
+ if((res = s_mp_mul(&s, &x)) != MP_OKAY)
+ goto CLEANUP;
+ }
+
+ d >>= 1;
+
+ if((res = s_mp_sqr(&x)) != MP_OKAY)
+ goto CLEANUP;
+ }
+ }
+
+ /* Consider now the last digit... */
+ d = DIGIT(b, dig);
+
+ while(d) {
+ if(d & 1) {
+ if((res = s_mp_mul(&s, &x)) != MP_OKAY)
+ goto CLEANUP;
+ }
+
+ d >>= 1;
+
+ if((res = s_mp_sqr(&x)) != MP_OKAY)
+ goto CLEANUP;
+ }
+
+ if(mp_iseven(b))
+ SIGN(&s) = SIGN(a);
+
+ res = mp_copy(&s, c);
+
+CLEANUP:
+ mp_clear(&x);
+X:
+ mp_clear(&s);
+
+ return res;
+
+} /* end mp_expt() */
+
+/* }}} */
+
+/* {{{ mp_2expt(a, k) */
+
+/* Compute a = 2^k */
+
+mp_err mp_2expt(mp_int *a, mp_digit k)
+{
+ ARGCHK(a != NULL, MP_BADARG);
+
+ return s_mp_2expt(a, k);
+
+} /* end mp_2expt() */
+
+/* }}} */
+
+/* {{{ mp_mod(a, m, c) */
+
+/*
+ mp_mod(a, m, c)
+
+ Compute c = a (mod m). Result will always be 0 <= c < m.
+ */
+
+mp_err mp_mod(mp_int *a, mp_int *m, mp_int *c)
+{
+ mp_err res;
+ int mag;
+
+ ARGCHK(a != NULL && m != NULL && c != NULL, MP_BADARG);
+
+ if(SIGN(m) == MP_NEG)
+ return MP_RANGE;
+
+ /*
+ If |a| > m, we need to divide to get the remainder and take the
+ absolute value.
+
+ If |a| < m, we don't need to do any division, just copy and adjust
+ the sign (if a is negative).
+
+ If |a| == m, we can simply set the result to zero.
+
+ This order is intended to minimize the average path length of the
+ comparison chain on common workloads -- the most frequent cases are
+ that |a| != m, so we do those first.
+ */
+ if((mag = s_mp_cmp(a, m)) > 0) {
+ if((res = mp_div(a, m, NULL, c)) != MP_OKAY)
+ return res;
+
+ if(SIGN(c) == MP_NEG) {
+ if((res = mp_add(c, m, c)) != MP_OKAY)
+ return res;
+ }
+
+ } else if(mag < 0) {
+ if((res = mp_copy(a, c)) != MP_OKAY)
+ return res;
+
+ if(mp_cmp_z(a) < 0) {
+ if((res = mp_add(c, m, c)) != MP_OKAY)
+ return res;
+
+ }
+
+ } else {
+ mp_zero(c);
+
+ }
+
+ return MP_OKAY;
+
+} /* end mp_mod() */
+
+/* }}} */
+
+/* {{{ mp_mod_d(a, d, c) */
+
+/*
+ mp_mod_d(a, d, c)
+
+ Compute c = a (mod d). Result will always be 0 <= c < d
+ */
+mp_err mp_mod_d(mp_int *a, mp_digit d, mp_digit *c)
+{
+ mp_err res;
+ mp_digit rem;
+
+ ARGCHK(a != NULL && c != NULL, MP_BADARG);
+
+ if(s_mp_cmp_d(a, d) > 0) {
+ if((res = mp_div_d(a, d, NULL, &rem)) != MP_OKAY)
+ return res;
+
+ } else {
+ if(SIGN(a) == MP_NEG)
+ rem = d - DIGIT(a, 0);
+ else
+ rem = DIGIT(a, 0);
+ }
+
+ if(c)
+ *c = rem;
+
+ return MP_OKAY;
+
+} /* end mp_mod_d() */
+
+/* }}} */
+
+/* {{{ mp_sqrt(a, b) */
+
+/*
+ mp_sqrt(a, b)
+
+ Compute the integer square root of a, and store the result in b.
+ Uses an integer-arithmetic version of Newton's iterative linear
+ approximation technique to determine this value; the result has the
+ following two properties:
+
+ b^2 <= a
+ (b+1)^2 >= a
+
+ It is a range error to pass a negative value.
+ */
+mp_err mp_sqrt(mp_int *a, mp_int *b)
+{
+ mp_int x, t;
+ mp_err res;
+
+ ARGCHK(a != NULL && b != NULL, MP_BADARG);
+
+ /* Cannot take square root of a negative value */
+ if(SIGN(a) == MP_NEG)
+ return MP_RANGE;
+
+ /* Special cases for zero and one, trivial */
+ if(mp_cmp_d(a, 0) == MP_EQ || mp_cmp_d(a, 1) == MP_EQ)
+ return mp_copy(a, b);
+
+ /* Initialize the temporaries we'll use below */
+ if((res = mp_init_size(&t, USED(a))) != MP_OKAY)
+ return res;
+
+ /* Compute an initial guess for the iteration as a itself */
+ if((res = mp_init_copy(&x, a)) != MP_OKAY)
+ goto X;
+
+s_mp_rshd(&x, (USED(&x)/2)+1);
+mp_add_d(&x, 1, &x);
+
+ for(;;) {
+ /* t = (x * x) - a */
+ mp_copy(&x, &t); /* can't fail, t is big enough for original x */
+ if((res = mp_sqr(&t, &t)) != MP_OKAY ||
+ (res = mp_sub(&t, a, &t)) != MP_OKAY)
+ goto CLEANUP;
+
+ /* t = t / 2x */
+ s_mp_mul_2(&x);
+ if((res = mp_div(&t, &x, &t, NULL)) != MP_OKAY)
+ goto CLEANUP;
+ s_mp_div_2(&x);
+
+ /* Terminate the loop, if the quotient is zero */
+ if(mp_cmp_z(&t) == MP_EQ)
+ break;
+
+ /* x = x - t */
+ if((res = mp_sub(&x, &t, &x)) != MP_OKAY)
+ goto CLEANUP;
+
+ }
+
+ /* Copy result to output parameter */
+ mp_sub_d(&x, 1, &x);
+ s_mp_exch(&x, b);
+
+ CLEANUP:
+ mp_clear(&x);
+ X:
+ mp_clear(&t);
+
+ return res;
+
+} /* end mp_sqrt() */
+
+/* }}} */
+
+/* }}} */
+
+/*------------------------------------------------------------------------*/
+/* {{{ Modular arithmetic */
+
+#if MP_MODARITH
+/* {{{ mp_addmod(a, b, m, c) */
+
+/*
+ mp_addmod(a, b, m, c)
+
+ Compute c = (a + b) mod m
+ */
+
+mp_err mp_addmod(mp_int *a, mp_int *b, mp_int *m, mp_int *c)
+{
+ mp_err res;
+
+ ARGCHK(a != NULL && b != NULL && m != NULL && c != NULL, MP_BADARG);
+
+ if((res = mp_add(a, b, c)) != MP_OKAY)
+ return res;
+ if((res = mp_mod(c, m, c)) != MP_OKAY)
+ return res;
+
+ return MP_OKAY;
+
+}
+
+/* }}} */
+
+/* {{{ mp_submod(a, b, m, c) */
+
+/*
+ mp_submod(a, b, m, c)
+
+ Compute c = (a - b) mod m
+ */
+
+mp_err mp_submod(mp_int *a, mp_int *b, mp_int *m, mp_int *c)
+{
+ mp_err res;
+
+ ARGCHK(a != NULL && b != NULL && m != NULL && c != NULL, MP_BADARG);
+
+ if((res = mp_sub(a, b, c)) != MP_OKAY)
+ return res;
+ if((res = mp_mod(c, m, c)) != MP_OKAY)
+ return res;
+
+ return MP_OKAY;
+
+}
+
+/* }}} */
+
+/* {{{ mp_mulmod(a, b, m, c) */
+
+/*
+ mp_mulmod(a, b, m, c)
+
+ Compute c = (a * b) mod m
+ */
+
+mp_err mp_mulmod(mp_int *a, mp_int *b, mp_int *m, mp_int *c)
+{
+ mp_err res;
+
+ ARGCHK(a != NULL && b != NULL && m != NULL && c != NULL, MP_BADARG);
+
+ if((res = mp_mul(a, b, c)) != MP_OKAY)
+ return res;
+ if((res = mp_mod(c, m, c)) != MP_OKAY)
+ return res;
+
+ return MP_OKAY;
+
+}
+
+/* }}} */
+
+/* {{{ mp_sqrmod(a, m, c) */
+
+#if MP_SQUARE
+mp_err mp_sqrmod(mp_int *a, mp_int *m, mp_int *c)
+{
+ mp_err res;
+
+ ARGCHK(a != NULL && m != NULL && c != NULL, MP_BADARG);
+
+ if((res = mp_sqr(a, c)) != MP_OKAY)
+ return res;
+ if((res = mp_mod(c, m, c)) != MP_OKAY)
+ return res;
+
+ return MP_OKAY;
+
+} /* end mp_sqrmod() */
+#endif
+
+/* }}} */
+
+/* {{{ mp_exptmod(a, b, m, c) */
+
+/*
+ mp_exptmod(a, b, m, c)
+
+ Compute c = (a ** b) mod m. Uses a standard square-and-multiply
+ method with modular reductions at each step. (This is basically the
+ same code as mp_expt(), except for the addition of the reductions)
+
+ The modular reductions are done using Barrett's algorithm (see
+ s_mp_reduce() below for details)
+ */
+
+mp_err mp_exptmod(mp_int *a, mp_int *b, mp_int *m, mp_int *c)
+{
+ mp_int s, x, mu;
+ mp_err res;
+ mp_digit d, *db = DIGITS(b);
+ mp_size ub = USED(b);
+ unsigned int bit, dig;
+
+ ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG);
+
+ if(mp_cmp_z(b) < 0 || mp_cmp_z(m) <= 0)
+ return MP_RANGE;
+
+ if((res = mp_init(&s)) != MP_OKAY)
+ return res;
+ if((res = mp_init_copy(&x, a)) != MP_OKAY)
+ goto X;
+ if((res = mp_mod(&x, m, &x)) != MP_OKAY ||
+ (res = mp_init(&mu)) != MP_OKAY)
+ goto MU;
+
+ mp_set(&s, 1);
+
+ /* mu = b^2k / m */
+ s_mp_add_d(&mu, 1);
+ s_mp_lshd(&mu, 2 * USED(m));
+ if((res = mp_div(&mu, m, &mu, NULL)) != MP_OKAY)
+ goto CLEANUP;
+
+ /* Loop over digits of b in ascending order, except highest order */
+ for(dig = 0; dig < (ub - 1); dig++) {
+ d = *db++;
+
+ /* Loop over the bits of the lower-order digits */
+ for(bit = 0; bit < DIGIT_BIT; bit++) {
+ if(d & 1) {
+ if((res = s_mp_mul(&s, &x)) != MP_OKAY)
+ goto CLEANUP;
+ if((res = s_mp_reduce(&s, m, &mu)) != MP_OKAY)
+ goto CLEANUP;
+ }
+
+ d >>= 1;
+
+ if((res = s_mp_sqr(&x)) != MP_OKAY)
+ goto CLEANUP;
+ if((res = s_mp_reduce(&x, m, &mu)) != MP_OKAY)
+ goto CLEANUP;
+ }
+ }
+
+ /* Now do the last digit... */
+ d = *db;
+
+ while(d) {
+ if(d & 1) {
+ if((res = s_mp_mul(&s, &x)) != MP_OKAY)
+ goto CLEANUP;
+ if((res = s_mp_reduce(&s, m, &mu)) != MP_OKAY)
+ goto CLEANUP;
+ }
+
+ d >>= 1;
+
+ if((res = s_mp_sqr(&x)) != MP_OKAY)
+ goto CLEANUP;
+ if((res = s_mp_reduce(&x, m, &mu)) != MP_OKAY)
+ goto CLEANUP;
+ }
+
+ s_mp_exch(&s, c);
+
+ CLEANUP:
+ mp_clear(&mu);
+ MU:
+ mp_clear(&x);
+ X:
+ mp_clear(&s);
+
+ return res;
+
+} /* end mp_exptmod() */
+
+/* }}} */
+
+/* {{{ mp_exptmod_d(a, d, m, c) */
+
+mp_err mp_exptmod_d(mp_int *a, mp_digit d, mp_int *m, mp_int *c)
+{
+ mp_int s, x;
+ mp_err res;
+
+ ARGCHK(a != NULL && c != NULL, MP_BADARG);
+
+ if((res = mp_init(&s)) != MP_OKAY)
+ return res;
+ if((res = mp_init_copy(&x, a)) != MP_OKAY)
+ goto X;
+
+ mp_set(&s, 1);
+
+ while(d != 0) {
+ if(d & 1) {
+ if((res = s_mp_mul(&s, &x)) != MP_OKAY ||
+ (res = mp_mod(&s, m, &s)) != MP_OKAY)
+ goto CLEANUP;
+ }
+
+ d /= 2;
+
+ if((res = s_mp_sqr(&x)) != MP_OKAY ||
+ (res = mp_mod(&x, m, &x)) != MP_OKAY)
+ goto CLEANUP;
+ }
+
+ s_mp_exch(&s, c);
+
+CLEANUP:
+ mp_clear(&x);
+X:
+ mp_clear(&s);
+
+ return res;
+
+} /* end mp_exptmod_d() */
+
+/* }}} */
+#endif /* if MP_MODARITH */
+
+/* }}} */
+
+/*------------------------------------------------------------------------*/
+/* {{{ Comparison functions */
+
+/* {{{ mp_cmp_z(a) */
+
+/*
+ mp_cmp_z(a)
+
+ Compare a <=> 0. Returns <0 if a<0, 0 if a=0, >0 if a>0.
+ */
+
+int mp_cmp_z(mp_int *a)
+{
+ if(SIGN(a) == MP_NEG)
+ return MP_LT;
+ else if(USED(a) == 1 && DIGIT(a, 0) == 0)
+ return MP_EQ;
+ else
+ return MP_GT;
+
+} /* end mp_cmp_z() */
+
+/* }}} */
+
+/* {{{ mp_cmp_d(a, d) */
+
+/*
+ mp_cmp_d(a, d)
+
+ Compare a <=> d. Returns <0 if a<d, 0 if a=d, >0 if a>d
+ */
+
+int mp_cmp_d(mp_int *a, mp_digit d)
+{
+ ARGCHK(a != NULL, MP_EQ);
+
+ if(SIGN(a) == MP_NEG)
+ return MP_LT;
+
+ return s_mp_cmp_d(a, d);
+
+} /* end mp_cmp_d() */
+
+/* }}} */
+
+/* {{{ mp_cmp(a, b) */
+
+int mp_cmp(mp_int *a, mp_int *b)
+{
+ ARGCHK(a != NULL && b != NULL, MP_EQ);
+
+ if(SIGN(a) == SIGN(b)) {
+ int mag;
+
+ if((mag = s_mp_cmp(a, b)) == MP_EQ)
+ return MP_EQ;
+
+ if(SIGN(a) == MP_ZPOS)
+ return mag;
+ else
+ return -mag;
+
+ } else if(SIGN(a) == MP_ZPOS) {
+ return MP_GT;
+ } else {
+ return MP_LT;
+ }
+
+} /* end mp_cmp() */
+
+/* }}} */
+
+/* {{{ mp_cmp_mag(a, b) */
+
+/*
+ mp_cmp_mag(a, b)
+
+ Compares |a| <=> |b|, and returns an appropriate comparison result
+ */
+
+int mp_cmp_mag(mp_int *a, mp_int *b)
+{
+ ARGCHK(a != NULL && b != NULL, MP_EQ);
+
+ return s_mp_cmp(a, b);
+
+} /* end mp_cmp_mag() */
+
+/* }}} */
+
+/* {{{ mp_cmp_int(a, z) */
+
+/*
+ This just converts z to an mp_int, and uses the existing comparison
+ routines. This is sort of inefficient, but it's not clear to me how
+ frequently this wil get used anyway. For small positive constants,
+ you can always use mp_cmp_d(), and for zero, there is mp_cmp_z().
+ */
+int mp_cmp_int(mp_int *a, long z)
+{
+ mp_int tmp;
+ int out;
+
+ ARGCHK(a != NULL, MP_EQ);
+
+ mp_init(&tmp); mp_set_int(&tmp, z);
+ out = mp_cmp(a, &tmp);
+ mp_clear(&tmp);
+
+ return out;
+
+} /* end mp_cmp_int() */
+
+/* }}} */
+
+/* {{{ mp_isodd(a) */
+
+/*
+ mp_isodd(a)
+
+ Returns a true (non-zero) value if a is odd, false (zero) otherwise.
+ */
+int mp_isodd(mp_int *a)
+{
+ ARGCHK(a != NULL, 0);
+
+ return (DIGIT(a, 0) & 1);
+
+} /* end mp_isodd() */
+
+/* }}} */
+
+/* {{{ mp_iseven(a) */
+
+int mp_iseven(mp_int *a)
+{
+ return !mp_isodd(a);
+
+} /* end mp_iseven() */
+
+/* }}} */
+
+/* }}} */
+
+/*------------------------------------------------------------------------*/
+/* {{{ Number theoretic functions */
+
+#if MP_NUMTH
+/* {{{ mp_gcd(a, b, c) */
+
+/*
+ Like the old mp_gcd() function, except computes the GCD using the
+ binary algorithm due to Josef Stein in 1961 (via Knuth).
+ */
+mp_err mp_gcd(mp_int *a, mp_int *b, mp_int *c)
+{
+ mp_err res;
+ mp_int u, v, t;
+ mp_size k = 0;
+
+ ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG);
+
+ if(mp_cmp_z(a) == MP_EQ && mp_cmp_z(b) == MP_EQ)
+ return MP_RANGE;
+ if(mp_cmp_z(a) == MP_EQ) {
+ return mp_copy(b, c);
+ } else if(mp_cmp_z(b) == MP_EQ) {
+ return mp_copy(a, c);
+ }
+
+ if((res = mp_init(&t)) != MP_OKAY)
+ return res;
+ if((res = mp_init_copy(&u, a)) != MP_OKAY)
+ goto U;
+ if((res = mp_init_copy(&v, b)) != MP_OKAY)
+ goto V;
+
+ SIGN(&u) = MP_ZPOS;
+ SIGN(&v) = MP_ZPOS;
+
+ /* Divide out common factors of 2 until at least 1 of a, b is even */
+ while(mp_iseven(&u) && mp_iseven(&v)) {
+ s_mp_div_2(&u);
+ s_mp_div_2(&v);
+ ++k;
+ }
+
+ /* Initialize t */
+ if(mp_isodd(&u)) {
+ if((res = mp_copy(&v, &t)) != MP_OKAY)
+ goto CLEANUP;
+
+ /* t = -v */
+ if(SIGN(&v) == MP_ZPOS)
+ SIGN(&t) = MP_NEG;
+ else
+ SIGN(&t) = MP_ZPOS;
+
+ } else {
+ if((res = mp_copy(&u, &t)) != MP_OKAY)
+ goto CLEANUP;
+
+ }
+
+ for(;;) {
+ while(mp_iseven(&t)) {
+ s_mp_div_2(&t);
+ }
+
+ if(mp_cmp_z(&t) == MP_GT) {
+ if((res = mp_copy(&t, &u)) != MP_OKAY)
+ goto CLEANUP;
+
+ } else {
+ if((res = mp_copy(&t, &v)) != MP_OKAY)
+ goto CLEANUP;
+
+ /* v = -t */
+ if(SIGN(&t) == MP_ZPOS)
+ SIGN(&v) = MP_NEG;
+ else
+ SIGN(&v) = MP_ZPOS;
+ }
+
+ if((res = mp_sub(&u, &v, &t)) != MP_OKAY)
+ goto CLEANUP;
+
+ if(s_mp_cmp_d(&t, 0) == MP_EQ)
+ break;
+ }
+
+ s_mp_2expt(&v, k); /* v = 2^k */
+ res = mp_mul(&u, &v, c); /* c = u * v */
+
+ CLEANUP:
+ mp_clear(&v);
+ V:
+ mp_clear(&u);
+ U:
+ mp_clear(&t);
+
+ return res;
+
+} /* end mp_bgcd() */
+
+/* }}} */
+
+/* {{{ mp_lcm(a, b, c) */
+
+/* We compute the least common multiple using the rule:
+
+ ab = [a, b](a, b)
+
+ ... by computing the product, and dividing out the gcd.
+ */
+
+mp_err mp_lcm(mp_int *a, mp_int *b, mp_int *c)
+{
+ mp_int gcd, prod;
+ mp_err res;
+
+ ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG);
+
+ /* Set up temporaries */
+ if((res = mp_init(&gcd)) != MP_OKAY)
+ return res;
+ if((res = mp_init(&prod)) != MP_OKAY)
+ goto GCD;
+
+ if((res = mp_mul(a, b, &prod)) != MP_OKAY)
+ goto CLEANUP;
+ if((res = mp_gcd(a, b, &gcd)) != MP_OKAY)
+ goto CLEANUP;
+
+ res = mp_div(&prod, &gcd, c, NULL);
+
+ CLEANUP:
+ mp_clear(&prod);
+ GCD:
+ mp_clear(&gcd);
+
+ return res;
+
+} /* end mp_lcm() */
+
+/* }}} */
+
+/* {{{ mp_xgcd(a, b, g, x, y) */
+
+/*
+ mp_xgcd(a, b, g, x, y)
+
+ Compute g = (a, b) and values x and y satisfying Bezout's identity
+ (that is, ax + by = g). This uses the extended binary GCD algorithm
+ based on the Stein algorithm used for mp_gcd()
+ */
+
+mp_err mp_xgcd(mp_int *a, mp_int *b, mp_int *g, mp_int *x, mp_int *y)
+{
+ mp_int gx, xc, yc, u, v, A, B, C, D;
+ mp_int *clean[9];
+ mp_err res;
+ int last = -1;
+
+ if(mp_cmp_z(b) == 0)
+ return MP_RANGE;
+
+ /* Initialize all these variables we need */
+ if((res = mp_init(&u)) != MP_OKAY) goto CLEANUP;
+ clean[++last] = &u;
+ if((res = mp_init(&v)) != MP_OKAY) goto CLEANUP;
+ clean[++last] = &v;
+ if((res = mp_init(&gx)) != MP_OKAY) goto CLEANUP;
+ clean[++last] = &gx;
+ if((res = mp_init(&A)) != MP_OKAY) goto CLEANUP;
+ clean[++last] = &A;
+ if((res = mp_init(&B)) != MP_OKAY) goto CLEANUP;
+ clean[++last] = &B;
+ if((res = mp_init(&C)) != MP_OKAY) goto CLEANUP;
+ clean[++last] = &C;
+ if((res = mp_init(&D)) != MP_OKAY) goto CLEANUP;
+ clean[++last] = &D;
+ if((res = mp_init_copy(&xc, a)) != MP_OKAY) goto CLEANUP;
+ clean[++last] = &xc;
+ mp_abs(&xc, &xc);
+ if((res = mp_init_copy(&yc, b)) != MP_OKAY) goto CLEANUP;
+ clean[++last] = &yc;
+ mp_abs(&yc, &yc);
+
+ mp_set(&gx, 1);
+
+ /* Divide by two until at least one of them is even */
+ while(mp_iseven(&xc) && mp_iseven(&yc)) {
+ s_mp_div_2(&xc);
+ s_mp_div_2(&yc);
+ if((res = s_mp_mul_2(&gx)) != MP_OKAY)
+ goto CLEANUP;
+ }
+
+ mp_copy(&xc, &u);
+ mp_copy(&yc, &v);
+ mp_set(&A, 1); mp_set(&D, 1);
+
+ /* Loop through binary GCD algorithm */
+ for(;;) {
+ while(mp_iseven(&u)) {
+ s_mp_div_2(&u);
+
+ if(mp_iseven(&A) && mp_iseven(&B)) {
+ s_mp_div_2(&A); s_mp_div_2(&B);
+ } else {
+ if((res = mp_add(&A, &yc, &A)) != MP_OKAY) goto CLEANUP;
+ s_mp_div_2(&A);
+ if((res = mp_sub(&B, &xc, &B)) != MP_OKAY) goto CLEANUP;
+ s_mp_div_2(&B);
+ }
+ }
+
+ while(mp_iseven(&v)) {
+ s_mp_div_2(&v);
+
+ if(mp_iseven(&C) && mp_iseven(&D)) {
+ s_mp_div_2(&C); s_mp_div_2(&D);
+ } else {
+ if((res = mp_add(&C, &yc, &C)) != MP_OKAY) goto CLEANUP;
+ s_mp_div_2(&C);
+ if((res = mp_sub(&D, &xc, &D)) != MP_OKAY) goto CLEANUP;
+ s_mp_div_2(&D);
+ }
+ }
+
+ if(mp_cmp(&u, &v) >= 0) {
+ if((res = mp_sub(&u, &v, &u)) != MP_OKAY) goto CLEANUP;
+ if((res = mp_sub(&A, &C, &A)) != MP_OKAY) goto CLEANUP;
+ if((res = mp_sub(&B, &D, &B)) != MP_OKAY) goto CLEANUP;
+
+ } else {
+ if((res = mp_sub(&v, &u, &v)) != MP_OKAY) goto CLEANUP;
+ if((res = mp_sub(&C, &A, &C)) != MP_OKAY) goto CLEANUP;
+ if((res = mp_sub(&D, &B, &D)) != MP_OKAY) goto CLEANUP;
+
+ }
+
+ /* If we're done, copy results to output */
+ if(mp_cmp_z(&u) == 0) {
+ if(x)
+ if((res = mp_copy(&C, x)) != MP_OKAY) goto CLEANUP;
+
+ if(y)
+ if((res = mp_copy(&D, y)) != MP_OKAY) goto CLEANUP;
+
+ if(g)
+ if((res = mp_mul(&gx, &v, g)) != MP_OKAY) goto CLEANUP;
+
+ break;
+ }
+ }
+
+ CLEANUP:
+ while(last >= 0)
+ mp_clear(clean[last--]);
+
+ return res;
+
+} /* end mp_xgcd() */
+
+/* }}} */
+
+/* {{{ mp_invmod(a, m, c) */
+
+/*
+ mp_invmod(a, m, c)
+
+ Compute c = a^-1 (mod m), if there is an inverse for a (mod m).
+ This is equivalent to the question of whether (a, m) = 1. If not,
+ MP_UNDEF is returned, and there is no inverse.
+ */
+
+mp_err mp_invmod(mp_int *a, mp_int *m, mp_int *c)
+{
+ mp_int g, x;
+ mp_err res;
+
+ ARGCHK(a && m && c, MP_BADARG);
+
+ if(mp_cmp_z(a) == 0 || mp_cmp_z(m) == 0)
+ return MP_RANGE;
+
+ if((res = mp_init(&g)) != MP_OKAY)
+ return res;
+ if((res = mp_init(&x)) != MP_OKAY)
+ goto X;
+
+ if((res = mp_xgcd(a, m, &g, &x, NULL)) != MP_OKAY)
+ goto CLEANUP;
+
+ if(mp_cmp_d(&g, 1) != MP_EQ) {
+ res = MP_UNDEF;
+ goto CLEANUP;
+ }
+
+ res = mp_mod(&x, m, c);
+ SIGN(c) = SIGN(a);
+
+CLEANUP:
+ mp_clear(&x);
+X:
+ mp_clear(&g);
+
+ return res;
+
+} /* end mp_invmod() */
+
+/* }}} */
+#endif /* if MP_NUMTH */
+
+/* }}} */
+
+/*------------------------------------------------------------------------*/
+/* {{{ mp_print(mp, ofp) */
+
+#if MP_IOFUNC
+/*
+ mp_print(mp, ofp)
+
+ Print a textual representation of the given mp_int on the output
+ stream 'ofp'. Output is generated using the internal radix.
+ */
+
+void mp_print(mp_int *mp, FILE *ofp)
+{
+ int ix;
+
+ if(mp == NULL || ofp == NULL)
+ return;
+
+ fputc((SIGN(mp) == MP_NEG) ? '-' : '+', ofp);
+
+ for(ix = USED(mp) - 1; ix >= 0; ix--) {
+ fprintf(ofp, DIGIT_FMT, DIGIT(mp, ix));
+ }
+
+} /* end mp_print() */
+
+#endif /* if MP_IOFUNC */
+
+/* }}} */
+
+/*------------------------------------------------------------------------*/
+/* {{{ More I/O Functions */
+
+/* {{{ mp_read_signed_bin(mp, str, len) */
+
+/*
+ mp_read_signed_bin(mp, str, len)
+
+ Read in a raw value (base 256) into the given mp_int
+ */
+
+mp_err mp_read_signed_bin(mp_int *mp, unsigned char *str, int len)
+{
+ mp_err res;
+
+ ARGCHK(mp != NULL && str != NULL && len > 0, MP_BADARG);
+
+ if((res = mp_read_unsigned_bin(mp, str + 1, len - 1)) == MP_OKAY) {
+ /* Get sign from first byte */
+ if(str[0])
+ SIGN(mp) = MP_NEG;
+ else
+ SIGN(mp) = MP_ZPOS;
+ }
+
+ return res;
+
+} /* end mp_read_signed_bin() */
+
+/* }}} */
+
+/* {{{ mp_signed_bin_size(mp) */
+
+int mp_signed_bin_size(mp_int *mp)
+{
+ ARGCHK(mp != NULL, 0);
+
+ return mp_unsigned_bin_size(mp) + 1;
+
+} /* end mp_signed_bin_size() */
+
+/* }}} */
+
+/* {{{ mp_to_signed_bin(mp, str) */
+
+mp_err mp_to_signed_bin(mp_int *mp, unsigned char *str)
+{
+ ARGCHK(mp != NULL && str != NULL, MP_BADARG);
+
+ /* Caller responsible for allocating enough memory (use mp_raw_size(mp)) */
+ str[0] = (char)SIGN(mp);
+
+ return mp_to_unsigned_bin(mp, str + 1);
+
+} /* end mp_to_signed_bin() */
+
+/* }}} */
+
+/* {{{ mp_read_unsigned_bin(mp, str, len) */
+
+/*
+ mp_read_unsigned_bin(mp, str, len)
+
+ Read in an unsigned value (base 256) into the given mp_int
+ */
+
+mp_err mp_read_unsigned_bin(mp_int *mp, unsigned char *str, int len)
+{
+ int ix;
+ mp_err res;
+
+ ARGCHK(mp != NULL && str != NULL && len > 0, MP_BADARG);
+
+ mp_zero(mp);
+
+ for(ix = 0; ix < len; ix++) {
+ if((res = s_mp_mul_2d(mp, CHAR_BIT)) != MP_OKAY)
+ return res;
+
+ if((res = mp_add_d(mp, str[ix], mp)) != MP_OKAY)
+ return res;
+ }
+
+ return MP_OKAY;
+
+} /* end mp_read_unsigned_bin() */
+
+/* }}} */
+
+/* {{{ mp_unsigned_bin_size(mp) */
+
+int mp_unsigned_bin_size(mp_int *mp)
+{
+ mp_digit topdig;
+ int count;
+
+ ARGCHK(mp != NULL, 0);
+
+ /* Special case for the value zero */
+ if(USED(mp) == 1 && DIGIT(mp, 0) == 0)
+ return 1;
+
+ count = (USED(mp) - 1) * sizeof(mp_digit);
+ topdig = DIGIT(mp, USED(mp) - 1);
+
+ while(topdig != 0) {
+ ++count;
+ topdig >>= CHAR_BIT;
+ }
+
+ return count;
+
+} /* end mp_unsigned_bin_size() */
+
+/* }}} */
+
+/* {{{ mp_to_unsigned_bin(mp, str) */
+
+mp_err mp_to_unsigned_bin(mp_int *mp, unsigned char *str)
+{
+ mp_digit *dp, *end, d;
+ unsigned char *spos;
+
+ ARGCHK(mp != NULL && str != NULL, MP_BADARG);
+
+ dp = DIGITS(mp);
+ end = dp + USED(mp) - 1;
+ spos = str;
+
+ /* Special case for zero, quick test */
+ if(dp == end && *dp == 0) {
+ *str = '\0';
+ return MP_OKAY;
+ }
+
+ /* Generate digits in reverse order */
+ while(dp < end) {
+ unsigned int ix;
+
+ d = *dp;
+ for(ix = 0; ix < sizeof(mp_digit); ++ix) {
+ *spos = d & UCHAR_MAX;
+ d >>= CHAR_BIT;
+ ++spos;
+ }
+
+ ++dp;
+ }
+
+ /* Now handle last digit specially, high order zeroes are not written */
+ d = *end;
+ while(d != 0) {
+ *spos = d & UCHAR_MAX;
+ d >>= CHAR_BIT;
+ ++spos;
+ }
+
+ /* Reverse everything to get digits in the correct order */
+ while(--spos > str) {
+ unsigned char t = *str;
+ *str = *spos;
+ *spos = t;
+
+ ++str;
+ }
+
+ return MP_OKAY;
+
+} /* end mp_to_unsigned_bin() */
+
+/* }}} */
+
+/* {{{ mp_count_bits(mp) */
+
+int mp_count_bits(mp_int *mp)
+{
+ int len;
+ mp_digit d;
+
+ ARGCHK(mp != NULL, MP_BADARG);
+
+ len = DIGIT_BIT * (USED(mp) - 1);
+ d = DIGIT(mp, USED(mp) - 1);
+
+ while(d != 0) {
+ ++len;
+ d >>= 1;
+ }
+
+ return len;
+
+} /* end mp_count_bits() */
+
+/* }}} */
+
+/* {{{ mp_read_radix(mp, str, radix) */
+
+/*
+ mp_read_radix(mp, str, radix)
+
+ Read an integer from the given string, and set mp to the resulting
+ value. The input is presumed to be in base 10. Leading non-digit
+ characters are ignored, and the function reads until a non-digit
+ character or the end of the string.
+ */
+
+mp_err mp_read_radix(mp_int *mp, unsigned char *str, int radix)
+{
+ int ix = 0, val = 0;
+ mp_err res;
+ mp_sign sig = MP_ZPOS;
+
+ ARGCHK(mp != NULL && str != NULL && radix >= 2 && radix <= MAX_RADIX,
+ MP_BADARG);
+
+ mp_zero(mp);
+
+ /* Skip leading non-digit characters until a digit or '-' or '+' */
+ while(str[ix] &&
+ (s_mp_tovalue(str[ix], radix) < 0) &&
+ str[ix] != '-' &&
+ str[ix] != '+') {
+ ++ix;
+ }
+
+ if(str[ix] == '-') {
+ sig = MP_NEG;
+ ++ix;
+ } else if(str[ix] == '+') {
+ sig = MP_ZPOS; /* this is the default anyway... */
+ ++ix;
+ }
+
+ while((val = s_mp_tovalue(str[ix], radix)) >= 0) {
+ if((res = s_mp_mul_d(mp, radix)) != MP_OKAY)
+ return res;
+ if((res = s_mp_add_d(mp, val)) != MP_OKAY)
+ return res;
+ ++ix;
+ }
+
+ if(s_mp_cmp_d(mp, 0) == MP_EQ)
+ SIGN(mp) = MP_ZPOS;
+ else
+ SIGN(mp) = sig;
+
+ return MP_OKAY;
+
+} /* end mp_read_radix() */
+
+/* }}} */
+
+/* {{{ mp_radix_size(mp, radix) */
+
+int mp_radix_size(mp_int *mp, int radix)
+{
+ int len;
+ ARGCHK(mp != NULL, 0);
+
+ len = s_mp_outlen(mp_count_bits(mp), radix) + 1; /* for NUL terminator */
+
+ if(mp_cmp_z(mp) < 0)
+ ++len; /* for sign */
+
+ return len;
+
+} /* end mp_radix_size() */
+
+/* }}} */
+
+/* {{{ mp_value_radix_size(num, qty, radix) */
+
+/* num = number of digits
+ qty = number of bits per digit
+ radix = target base
+
+ Return the number of digits in the specified radix that would be
+ needed to express 'num' digits of 'qty' bits each.
+ */
+int mp_value_radix_size(int num, int qty, int radix)
+{
+ ARGCHK(num >= 0 && qty > 0 && radix >= 2 && radix <= MAX_RADIX, 0);
+
+ return s_mp_outlen(num * qty, radix);
+
+} /* end mp_value_radix_size() */
+
+/* }}} */
+
+/* {{{ mp_toradix(mp, str, radix) */
+
+mp_err mp_toradix(mp_int *mp, char *str, int radix)
+{
+ int ix, pos = 0;
+
+ ARGCHK(mp != NULL && str != NULL, MP_BADARG);
+ ARGCHK(radix > 1 && radix <= MAX_RADIX, MP_RANGE);
+
+ if(mp_cmp_z(mp) == MP_EQ) {
+ str[0] = '0';
+ str[1] = '\0';
+ } else {
+ mp_err res;
+ mp_int tmp;
+ mp_sign sgn;
+ mp_digit rem, rdx = (mp_digit)radix;
+ char ch;
+
+ if((res = mp_init_copy(&tmp, mp)) != MP_OKAY)
+ return res;
+
+ /* Save sign for later, and take absolute value */
+ sgn = SIGN(&tmp); SIGN(&tmp) = MP_ZPOS;
+
+ /* Generate output digits in reverse order */
+ while(mp_cmp_z(&tmp) != 0) {
+ if((res = s_mp_div_d(&tmp, rdx, &rem)) != MP_OKAY) {
+ mp_clear(&tmp);
+ return res;
+ }
+
+ /* Generate digits, use capital letters */
+ ch = s_mp_todigit(rem, radix, 0);
+
+ str[pos++] = ch;
+ }
+
+ /* Add - sign if original value was negative */
+ if(sgn == MP_NEG)
+ str[pos++] = '-';
+
+ /* Add trailing NUL to end the string */
+ str[pos--] = '\0';
+
+ /* Reverse the digits and sign indicator */
+ ix = 0;
+ while(ix < pos) {
+ char _tmp = str[ix];
+
+ str[ix] = str[pos];
+ str[pos] = _tmp;
+ ++ix;
+ --pos;
+ }
+
+ mp_clear(&tmp);
+ }
+
+ return MP_OKAY;
+
+} /* end mp_toradix() */
+
+/* }}} */
+
+/* {{{ mp_char2value(ch, r) */
+
+int mp_char2value(char ch, int r)
+{
+ return s_mp_tovalue(ch, r);
+
+} /* end mp_tovalue() */
+
+/* }}} */
+
+/* }}} */
+
+/* {{{ mp_strerror(ec) */
+
+/*
+ mp_strerror(ec)
+
+ Return a string describing the meaning of error code 'ec'. The
+ string returned is allocated in static memory, so the caller should
+ not attempt to modify or free the memory associated with this
+ string.
+ */
+const char *mp_strerror(mp_err ec)
+{
+ int aec = (ec < 0) ? -ec : ec;
+
+ /* Code values are negative, so the senses of these comparisons
+ are accurate */
+ if(ec < MP_LAST_CODE || ec > MP_OKAY) {
+ return mp_err_string[0]; /* unknown error code */
+ } else {
+ return mp_err_string[aec + 1];
+ }
+
+} /* end mp_strerror() */
+
+/* }}} */
+
+/*========================================================================*/
+/*------------------------------------------------------------------------*/
+/* Static function definitions (internal use only) */
+
+/* {{{ Memory management */
+
+/* {{{ s_mp_grow(mp, min) */
+
+/* Make sure there are at least 'min' digits allocated to mp */
+mp_err s_mp_grow(mp_int *mp, mp_size min)
+{
+ if(min > ALLOC(mp)) {
+ mp_digit *tmp;
+
+ /* Set min to next nearest default precision block size */
+ min = ((min + (s_mp_defprec - 1)) / s_mp_defprec) * s_mp_defprec;
+
+ if((tmp = s_mp_alloc(min, sizeof(mp_digit))) == NULL)
+ return MP_MEM;
+
+ s_mp_copy(DIGITS(mp), tmp, USED(mp));
+
+#if MP_CRYPTO
+ s_mp_setz(DIGITS(mp), ALLOC(mp));
+#endif
+ s_mp_free(DIGITS(mp));
+ DIGITS(mp) = tmp;
+ ALLOC(mp) = min;
+ }
+
+ return MP_OKAY;
+
+} /* end s_mp_grow() */
+
+/* }}} */
+
+/* {{{ s_mp_pad(mp, min) */
+
+/* Make sure the used size of mp is at least 'min', growing if needed */
+mp_err s_mp_pad(mp_int *mp, mp_size min)
+{
+ if(min > USED(mp)) {
+ mp_err res;
+
+ /* Make sure there is room to increase precision */
+ if(min > ALLOC(mp) && (res = s_mp_grow(mp, min)) != MP_OKAY)
+ return res;
+
+ /* Increase precision; should already be 0-filled */
+ USED(mp) = min;
+ }
+
+ return MP_OKAY;
+
+} /* end s_mp_pad() */
+
+/* }}} */
+
+/* {{{ s_mp_setz(dp, count) */
+
+#if MP_MACRO == 0
+/* Set 'count' digits pointed to by dp to be zeroes */
+void s_mp_setz(mp_digit *dp, mp_size count)
+{
+#if MP_MEMSET == 0
+ int ix;
+
+ for(ix = 0; ix < count; ix++)
+ dp[ix] = 0;
+#else
+ memset(dp, 0, count * sizeof(mp_digit));
+#endif
+
+} /* end s_mp_setz() */
+#endif
+
+/* }}} */
+
+/* {{{ s_mp_copy(sp, dp, count) */
+
+#if MP_MACRO == 0
+/* Copy 'count' digits from sp to dp */
+void s_mp_copy(mp_digit *sp, mp_digit *dp, mp_size count)
+{
+#if MP_MEMCPY == 0
+ int ix;
+
+ for(ix = 0; ix < count; ix++)
+ dp[ix] = sp[ix];
+#else
+ memcpy(dp, sp, count * sizeof(mp_digit));
+#endif
+
+} /* end s_mp_copy() */
+#endif
+
+/* }}} */
+
+/* {{{ s_mp_alloc(nb, ni) */
+
+#if MP_MACRO == 0
+/* Allocate ni records of nb bytes each, and return a pointer to that */
+void *s_mp_alloc(size_t nb, size_t ni)
+{
+ return calloc(nb, ni);
+
+} /* end s_mp_alloc() */
+#endif
+
+/* }}} */
+
+/* {{{ s_mp_free(ptr) */
+
+#if MP_MACRO == 0
+/* Free the memory pointed to by ptr */
+void s_mp_free(void *ptr)
+{
+ if(ptr)
+ free(ptr);
+
+} /* end s_mp_free() */
+#endif
+
+/* }}} */
+
+/* {{{ s_mp_clamp(mp) */
+
+/* Remove leading zeroes from the given value */
+void s_mp_clamp(mp_int *mp)
+{
+ mp_size du = USED(mp);
+ mp_digit *zp = DIGITS(mp) + du - 1;
+
+ while(du > 1 && !*zp--)
+ --du;
+
+ USED(mp) = du;
+
+} /* end s_mp_clamp() */
+
+
+/* }}} */
+
+/* {{{ s_mp_exch(a, b) */
+
+/* Exchange the data for a and b; (b, a) = (a, b) */
+void s_mp_exch(mp_int *a, mp_int *b)
+{
+ mp_int tmp;
+
+ tmp = *a;
+ *a = *b;
+ *b = tmp;
+
+} /* end s_mp_exch() */
+
+/* }}} */
+
+/* }}} */
+
+/* {{{ Arithmetic helpers */
+
+/* {{{ s_mp_lshd(mp, p) */
+
+/*
+ Shift mp leftward by p digits, growing if needed, and zero-filling
+ the in-shifted digits at the right end. This is a convenient
+ alternative to multiplication by powers of the radix
+ */
+
+mp_err s_mp_lshd(mp_int *mp, mp_size p)
+{
+ mp_err res;
+ mp_size pos;
+ mp_digit *dp;
+ int ix;
+
+ if(p == 0)
+ return MP_OKAY;
+
+ if((res = s_mp_pad(mp, USED(mp) + p)) != MP_OKAY)
+ return res;
+
+ pos = USED(mp) - 1;
+ dp = DIGITS(mp);
+
+ /* Shift all the significant figures over as needed */
+ for(ix = pos - p; ix >= 0; ix--)
+ dp[ix + p] = dp[ix];
+
+ /* Fill the bottom digits with zeroes */
+ for(ix = 0; (unsigned)ix < p; ix++)
+ dp[ix] = 0;
+
+ return MP_OKAY;
+
+} /* end s_mp_lshd() */
+
+/* }}} */
+
+/* {{{ s_mp_rshd(mp, p) */
+
+/*
+ Shift mp rightward by p digits. Maintains the invariant that
+ digits above the precision are all zero. Digits shifted off the
+ end are lost. Cannot fail.
+ */
+
+void s_mp_rshd(mp_int *mp, mp_size p)
+{
+ mp_size ix;
+ mp_digit *dp;
+
+ if(p == 0)
+ return;
+
+ /* Shortcut when all digits are to be shifted off */
+ if(p >= USED(mp)) {
+ s_mp_setz(DIGITS(mp), ALLOC(mp));
+ USED(mp) = 1;
+ SIGN(mp) = MP_ZPOS;
+ return;
+ }
+
+ /* Shift all the significant figures over as needed */
+ dp = DIGITS(mp);
+ for(ix = p; ix < USED(mp); ix++)
+ dp[ix - p] = dp[ix];
+
+ /* Fill the top digits with zeroes */
+ ix -= p;
+ while(ix < USED(mp))
+ dp[ix++] = 0;
+
+ /* Strip off any leading zeroes */
+ s_mp_clamp(mp);
+
+} /* end s_mp_rshd() */
+
+/* }}} */
+
+/* {{{ s_mp_div_2(mp) */
+
+/* Divide by two -- take advantage of radix properties to do it fast */
+void s_mp_div_2(mp_int *mp)
+{
+ s_mp_div_2d(mp, 1);
+
+} /* end s_mp_div_2() */
+
+/* }}} */
+
+/* {{{ s_mp_mul_2(mp) */
+
+mp_err s_mp_mul_2(mp_int *mp)
+{
+ unsigned int ix;
+ mp_digit kin = 0, kout, *dp = DIGITS(mp);
+ mp_err res;
+
+ /* Shift digits leftward by 1 bit */
+ for(ix = 0; ix < USED(mp); ix++) {
+ kout = (dp[ix] >> (DIGIT_BIT - 1)) & 1;
+ dp[ix] = (dp[ix] << 1) | kin;
+
+ kin = kout;
+ }
+
+ /* Deal with rollover from last digit */
+ if(kin) {
+ if(ix >= ALLOC(mp)) {
+ if((res = s_mp_grow(mp, ALLOC(mp) + 1)) != MP_OKAY)
+ return res;
+ dp = DIGITS(mp);
+ }
+
+ dp[ix] = kin;
+ USED(mp) += 1;
+ }
+
+ return MP_OKAY;
+
+} /* end s_mp_mul_2() */
+
+/* }}} */
+
+/* {{{ s_mp_mod_2d(mp, d) */
+
+/*
+ Remainder the integer by 2^d, where d is a number of bits. This
+ amounts to a bitwise AND of the value, and does not require the full
+ division code
+ */
+void s_mp_mod_2d(mp_int *mp, mp_digit d)
+{
+ unsigned int ndig = (d / DIGIT_BIT), nbit = (d % DIGIT_BIT);
+ unsigned int ix;
+ mp_digit dmask, *dp = DIGITS(mp);
+
+ if(ndig >= USED(mp))
+ return;
+
+ /* Flush all the bits above 2^d in its digit */
+ dmask = (1 << nbit) - 1;
+ dp[ndig] &= dmask;
+
+ /* Flush all digits above the one with 2^d in it */
+ for(ix = ndig + 1; ix < USED(mp); ix++)
+ dp[ix] = 0;
+
+ s_mp_clamp(mp);
+
+} /* end s_mp_mod_2d() */
+
+/* }}} */
+
+/* {{{ s_mp_mul_2d(mp, d) */
+
+/*
+ Multiply by the integer 2^d, where d is a number of bits. This
+ amounts to a bitwise shift of the value, and does not require the
+ full multiplication code.
+ */
+mp_err s_mp_mul_2d(mp_int *mp, mp_digit d)
+{
+ mp_err res;
+ mp_digit save, next, mask, *dp;
+ mp_size used;
+ unsigned int ix;
+
+ if((res = s_mp_lshd(mp, d / DIGIT_BIT)) != MP_OKAY)
+ return res;
+
+ dp = DIGITS(mp); used = USED(mp);
+ d %= DIGIT_BIT;
+
+ mask = (1 << d) - 1;
+
+ /* If the shift requires another digit, make sure we've got one to
+ work with */
+ if((dp[used - 1] >> (DIGIT_BIT - d)) & mask) {
+ if((res = s_mp_grow(mp, used + 1)) != MP_OKAY)
+ return res;
+ dp = DIGITS(mp);
+ }
+
+ /* Do the shifting... */
+ save = 0;
+ for(ix = 0; ix < used; ix++) {
+ next = (dp[ix] >> (DIGIT_BIT - d)) & mask;
+ dp[ix] = (dp[ix] << d) | save;
+ save = next;
+ }
+
+ /* If, at this point, we have a nonzero carryout into the next
+ digit, we'll increase the size by one digit, and store it...
+ */
+ if(save) {
+ dp[used] = save;
+ USED(mp) += 1;
+ }
+
+ s_mp_clamp(mp);
+ return MP_OKAY;
+
+} /* end s_mp_mul_2d() */
+
+/* }}} */
+
+/* {{{ s_mp_div_2d(mp, d) */
+
+/*
+ Divide the integer by 2^d, where d is a number of bits. This
+ amounts to a bitwise shift of the value, and does not require the
+ full division code (used in Barrett reduction, see below)
+ */
+void s_mp_div_2d(mp_int *mp, mp_digit d)
+{
+ int ix;
+ mp_digit save, next, mask, *dp = DIGITS(mp);
+
+ s_mp_rshd(mp, d / DIGIT_BIT);
+ d %= DIGIT_BIT;
+
+ mask = (1 << d) - 1;
+
+ save = 0;
+ for(ix = USED(mp) - 1; ix >= 0; ix--) {
+ next = dp[ix] & mask;
+ dp[ix] = (dp[ix] >> d) | (save << (DIGIT_BIT - d));
+ save = next;
+ }
+
+ s_mp_clamp(mp);
+
+} /* end s_mp_div_2d() */
+
+/* }}} */
+
+/* {{{ s_mp_norm(a, b) */
+
+/*
+ s_mp_norm(a, b)
+
+ Normalize a and b for division, where b is the divisor. In order
+ that we might make good guesses for quotient digits, we want the
+ leading digit of b to be at least half the radix, which we
+ accomplish by multiplying a and b by a constant. This constant is
+ returned (so that it can be divided back out of the remainder at the
+ end of the division process).
+
+ We multiply by the smallest power of 2 that gives us a leading digit
+ at least half the radix. By choosing a power of 2, we simplify the
+ multiplication and division steps to simple shifts.
+ */
+mp_digit s_mp_norm(mp_int *a, mp_int *b)
+{
+ mp_digit t, d = 0;
+
+ t = DIGIT(b, USED(b) - 1);
+ while(t < (RADIX / 2)) {
+ t <<= 1;
+ ++d;
+ }
+
+ if(d != 0) {
+ s_mp_mul_2d(a, d);
+ s_mp_mul_2d(b, d);
+ }
+
+ return d;
+
+} /* end s_mp_norm() */
+
+/* }}} */
+
+/* }}} */
+
+/* {{{ Primitive digit arithmetic */
+
+/* {{{ s_mp_add_d(mp, d) */
+
+/* Add d to |mp| in place */
+mp_err s_mp_add_d(mp_int *mp, mp_digit d) /* unsigned digit addition */
+{
+ mp_word w, k = 0;
+ mp_size ix = 1, used = USED(mp);
+ mp_digit *dp = DIGITS(mp);
+
+ w = dp[0] + d;
+ dp[0] = ACCUM(w);
+ k = CARRYOUT(w);
+
+ while(ix < used && k) {
+ w = dp[ix] + k;
+ dp[ix] = ACCUM(w);
+ k = CARRYOUT(w);
+ ++ix;
+ }
+
+ if(k != 0) {
+ mp_err res;
+
+ if((res = s_mp_pad(mp, USED(mp) + 1)) != MP_OKAY)
+ return res;
+
+ DIGIT(mp, ix) = k;
+ }
+
+ return MP_OKAY;
+
+} /* end s_mp_add_d() */
+
+/* }}} */
+
+/* {{{ s_mp_sub_d(mp, d) */
+
+/* Subtract d from |mp| in place, assumes |mp| > d */
+mp_err s_mp_sub_d(mp_int *mp, mp_digit d) /* unsigned digit subtract */
+{
+ mp_word w, b = 0;
+ mp_size ix = 1, used = USED(mp);
+ mp_digit *dp = DIGITS(mp);
+
+ /* Compute initial subtraction */
+ w = (RADIX + dp[0]) - d;
+ b = CARRYOUT(w) ? 0 : 1;
+ dp[0] = ACCUM(w);
+
+ /* Propagate borrows leftward */
+ while(b && ix < used) {
+ w = (RADIX + dp[ix]) - b;
+ b = CARRYOUT(w) ? 0 : 1;
+ dp[ix] = ACCUM(w);
+ ++ix;
+ }
+
+ /* Remove leading zeroes */
+ s_mp_clamp(mp);
+
+ /* If we have a borrow out, it's a violation of the input invariant */
+ if(b)
+ return MP_RANGE;
+ else
+ return MP_OKAY;
+
+} /* end s_mp_sub_d() */
+
+/* }}} */
+
+/* {{{ s_mp_mul_d(a, d) */
+
+/* Compute a = a * d, single digit multiplication */
+mp_err s_mp_mul_d(mp_int *a, mp_digit d)
+{
+ mp_word w, k = 0;
+ mp_size ix, max;
+ mp_err res;
+ mp_digit *dp = DIGITS(a);
+
+ /*
+ Single-digit multiplication will increase the precision of the
+ output by at most one digit. However, we can detect when this
+ will happen -- if the high-order digit of a, times d, gives a
+ two-digit result, then the precision of the result will increase;
+ otherwise it won't. We use this fact to avoid calling s_mp_pad()
+ unless absolutely necessary.
+ */
+ max = USED(a);
+ w = dp[max - 1] * d;
+ if(CARRYOUT(w) != 0) {
+ if((res = s_mp_pad(a, max + 1)) != MP_OKAY)
+ return res;
+ dp = DIGITS(a);
+ }
+
+ for(ix = 0; ix < max; ix++) {
+ w = (dp[ix] * d) + k;
+ dp[ix] = ACCUM(w);
+ k = CARRYOUT(w);
+ }
+
+ /* If there is a precision increase, take care of it here; the above
+ test guarantees we have enough storage to do this safely.
+ */
+ if(k) {
+ dp[max] = k;
+ USED(a) = max + 1;
+ }
+
+ s_mp_clamp(a);
+
+ return MP_OKAY;
+
+} /* end s_mp_mul_d() */
+
+/* }}} */
+
+/* {{{ s_mp_div_d(mp, d, r) */
+
+/*
+ s_mp_div_d(mp, d, r)
+
+ Compute the quotient mp = mp / d and remainder r = mp mod d, for a
+ single digit d. If r is null, the remainder will be discarded.
+ */
+
+mp_err s_mp_div_d(mp_int *mp, mp_digit d, mp_digit *r)
+{
+ mp_word w = 0, t;
+ mp_int quot;
+ mp_err res;
+ mp_digit *dp = DIGITS(mp), *qp;
+ int ix;
+
+ if(d == 0)
+ return MP_RANGE;
+
+ /* Make room for the quotient */
+ if((res = mp_init_size(&quot, USED(mp))) != MP_OKAY)
+ return res;
+
+ USED(&quot) = USED(mp); /* so clamping will work below */
+ qp = DIGITS(&quot);
+
+ /* Divide without subtraction */
+ for(ix = USED(mp) - 1; ix >= 0; ix--) {
+ w = (w << DIGIT_BIT) | dp[ix];
+
+ if(w >= d) {
+ t = w / d;
+ w = w % d;
+ } else {
+ t = 0;
+ }
+
+ qp[ix] = t;
+ }
+
+ /* Deliver the remainder, if desired */
+ if(r)
+ *r = w;
+
+ s_mp_clamp(&quot);
+ mp_exch(&quot, mp);
+ mp_clear(&quot);
+
+ return MP_OKAY;
+
+} /* end s_mp_div_d() */
+
+/* }}} */
+
+/* }}} */
+
+/* {{{ Primitive full arithmetic */
+
+/* {{{ s_mp_add(a, b) */
+
+/* Compute a = |a| + |b| */
+mp_err s_mp_add(mp_int *a, mp_int *b) /* magnitude addition */
+{
+ mp_word w = 0;
+ mp_digit *pa, *pb;
+ mp_size ix, used = USED(b);
+ mp_err res;
+
+ /* Make sure a has enough precision for the output value */
+ if((used > USED(a)) && (res = s_mp_pad(a, used)) != MP_OKAY)
+ return res;
+
+ /*
+ Add up all digits up to the precision of b. If b had initially
+ the same precision as a, or greater, we took care of it by the
+ padding step above, so there is no problem. If b had initially
+ less precision, we'll have to make sure the carry out is duly
+ propagated upward among the higher-order digits of the sum.
+ */
+ pa = DIGITS(a);
+ pb = DIGITS(b);
+ for(ix = 0; ix < used; ++ix) {
+ w += *pa + *pb++;
+ *pa++ = ACCUM(w);
+ w = CARRYOUT(w);
+ }
+
+ /* If we run out of 'b' digits before we're actually done, make
+ sure the carries get propagated upward...
+ */
+ used = USED(a);
+ while(w && ix < used) {
+ w += *pa;
+ *pa++ = ACCUM(w);
+ w = CARRYOUT(w);
+ ++ix;
+ }
+
+ /* If there's an overall carry out, increase precision and include
+ it. We could have done this initially, but why touch the memory
+ allocator unless we're sure we have to?
+ */
+ if(w) {
+ if((res = s_mp_pad(a, used + 1)) != MP_OKAY)
+ return res;
+
+ DIGIT(a, ix) = w; /* pa may not be valid after s_mp_pad() call */
+ }
+
+ return MP_OKAY;
+
+} /* end s_mp_add() */
+
+/* }}} */
+
+/* {{{ s_mp_sub(a, b) */
+
+/* Compute a = |a| - |b|, assumes |a| >= |b| */
+mp_err s_mp_sub(mp_int *a, mp_int *b) /* magnitude subtract */
+{
+ mp_word w = 0;
+ mp_digit *pa, *pb;
+ mp_size ix, used = USED(b);
+
+ /*
+ Subtract and propagate borrow. Up to the precision of b, this
+ accounts for the digits of b; after that, we just make sure the
+ carries get to the right place. This saves having to pad b out to
+ the precision of a just to make the loops work right...
+ */
+ pa = DIGITS(a);
+ pb = DIGITS(b);
+
+ for(ix = 0; ix < used; ++ix) {
+ w = (RADIX + *pa) - w - *pb++;
+ *pa++ = ACCUM(w);
+ w = CARRYOUT(w) ? 0 : 1;
+ }
+
+ used = USED(a);
+ while(ix < used) {
+ w = RADIX + *pa - w;
+ *pa++ = ACCUM(w);
+ w = CARRYOUT(w) ? 0 : 1;
+ ++ix;
+ }
+
+ /* Clobber any leading zeroes we created */
+ s_mp_clamp(a);
+
+ /*
+ If there was a borrow out, then |b| > |a| in violation
+ of our input invariant. We've already done the work,
+ but we'll at least complain about it...
+ */
+ if(w)
+ return MP_RANGE;
+ else
+ return MP_OKAY;
+
+} /* end s_mp_sub() */
+
+/* }}} */
+
+mp_err s_mp_reduce(mp_int *x, mp_int *m, mp_int *mu)
+{
+ mp_int q;
+ mp_err res;
+ mp_size um = USED(m);
+
+ if((res = mp_init_copy(&q, x)) != MP_OKAY)
+ return res;
+
+ s_mp_rshd(&q, um - 1); /* q1 = x / b^(k-1) */
+ s_mp_mul(&q, mu); /* q2 = q1 * mu */
+ s_mp_rshd(&q, um + 1); /* q3 = q2 / b^(k+1) */
+
+ /* x = x mod b^(k+1), quick (no division) */
+ s_mp_mod_2d(x, (mp_digit)(DIGIT_BIT * (um + 1)));
+
+ /* q = q * m mod b^(k+1), quick (no division), uses the short multiplier */
+#ifndef SHRT_MUL
+ s_mp_mul(&q, m);
+ s_mp_mod_2d(&q, (mp_digit)(DIGIT_BIT * (um + 1)));
+#else
+ s_mp_mul_dig(&q, m, um + 1);
+#endif
+
+ /* x = x - q */
+ if((res = mp_sub(x, &q, x)) != MP_OKAY)
+ goto CLEANUP;
+
+ /* If x < 0, add b^(k+1) to it */
+ if(mp_cmp_z(x) < 0) {
+ mp_set(&q, 1);
+ if((res = s_mp_lshd(&q, um + 1)) != MP_OKAY)
+ goto CLEANUP;
+ if((res = mp_add(x, &q, x)) != MP_OKAY)
+ goto CLEANUP;
+ }
+
+ /* Back off if it's too big */
+ while(mp_cmp(x, m) >= 0) {
+ if((res = s_mp_sub(x, m)) != MP_OKAY)
+ break;
+ }
+
+ CLEANUP:
+ mp_clear(&q);
+
+ return res;
+
+} /* end s_mp_reduce() */
+
+
+
+/* {{{ s_mp_mul(a, b) */
+
+/* Compute a = |a| * |b| */
+mp_err s_mp_mul(mp_int *a, mp_int *b)
+{
+ mp_word w, k = 0;
+ mp_int tmp;
+ mp_err res;
+ mp_size ix, jx, ua = USED(a), ub = USED(b);
+ mp_digit *pa, *pb, *pt, *pbt;
+
+ if((res = mp_init_size(&tmp, ua + ub)) != MP_OKAY)
+ return res;
+
+ /* This has the effect of left-padding with zeroes... */
+ USED(&tmp) = ua + ub;
+
+ /* We're going to need the base value each iteration */
+ pbt = DIGITS(&tmp);
+
+ /* Outer loop: Digits of b */
+
+ pb = DIGITS(b);
+ for(ix = 0; ix < ub; ++ix, ++pb) {
+ if(*pb == 0)
+ continue;
+
+ /* Inner product: Digits of a */
+ pa = DIGITS(a);
+ for(jx = 0; jx < ua; ++jx, ++pa) {
+ pt = pbt + ix + jx;
+ w = *pb * *pa + k + *pt;
+ *pt = ACCUM(w);
+ k = CARRYOUT(w);
+ }
+
+ pbt[ix + jx] = k;
+ k = 0;
+ }
+
+ s_mp_clamp(&tmp);
+ s_mp_exch(&tmp, a);
+
+ mp_clear(&tmp);
+
+ return MP_OKAY;
+
+} /* end s_mp_mul() */
+
+/* }}} */
+
+/* {{{ s_mp_kmul(a, b, out, len) */
+
+#if 0
+void s_mp_kmul(mp_digit *a, mp_digit *b, mp_digit *out, mp_size len)
+{
+ mp_word w, k = 0;
+ mp_size ix, jx;
+ mp_digit *pa, *pt;
+
+ for(ix = 0; ix < len; ++ix, ++b) {
+ if(*b == 0)
+ continue;
+
+ pa = a;
+ for(jx = 0; jx < len; ++jx, ++pa) {
+ pt = out + ix + jx;
+ w = *b * *pa + k + *pt;
+ *pt = ACCUM(w);
+ k = CARRYOUT(w);
+ }
+
+ out[ix + jx] = k;
+ k = 0;
+ }
+
+} /* end s_mp_kmul() */
+#endif
+
+/* }}} */
+
+/* {{{ s_mp_sqr(a) */
+
+/*
+ Computes the square of a, in place. This can be done more
+ efficiently than a general multiplication, because many of the
+ computation steps are redundant when squaring. The inner product
+ step is a bit more complicated, but we save a fair number of
+ iterations of the multiplication loop.
+ */
+#if MP_SQUARE
+mp_err s_mp_sqr(mp_int *a)
+{
+ mp_word w, k = 0;
+ mp_int tmp;
+ mp_err res;
+ mp_size ix, jx, kx, used = USED(a);
+ mp_digit *pa1, *pa2, *pt, *pbt;
+
+ if((res = mp_init_size(&tmp, 2 * used)) != MP_OKAY)
+ return res;
+
+ /* Left-pad with zeroes */
+ USED(&tmp) = 2 * used;
+
+ /* We need the base value each time through the loop */
+ pbt = DIGITS(&tmp);
+
+ pa1 = DIGITS(a);
+ for(ix = 0; ix < used; ++ix, ++pa1) {
+ if(*pa1 == 0)
+ continue;
+
+ w = DIGIT(&tmp, ix + ix) + (*pa1 * *pa1);
+
+ pbt[ix + ix] = ACCUM(w);
+ k = CARRYOUT(w);
+
+ /*
+ The inner product is computed as:
+
+ (C, S) = t[i,j] + 2 a[i] a[j] + C
+
+ This can overflow what can be represented in an mp_word, and
+ since C arithmetic does not provide any way to check for
+ overflow, we have to check explicitly for overflow conditions
+ before they happen.
+ */
+ for(jx = ix + 1, pa2 = DIGITS(a) + jx; jx < used; ++jx, ++pa2) {
+ mp_word u = 0, v;
+
+ /* Store this in a temporary to avoid indirections later */
+ pt = pbt + ix + jx;
+
+ /* Compute the multiplicative step */
+ w = *pa1 * *pa2;
+
+ /* If w is more than half MP_WORD_MAX, the doubling will
+ overflow, and we need to record a carry out into the next
+ word */
+ u = (w >> (MP_WORD_BIT - 1)) & 1;
+
+ /* Double what we've got, overflow will be ignored as defined
+ for C arithmetic (we've already noted if it is to occur)
+ */
+ w *= 2;
+
+ /* Compute the additive step */
+ v = *pt + k;
+
+ /* If we do not already have an overflow carry, check to see
+ if the addition will cause one, and set the carry out if so
+ */
+ u |= ((MP_WORD_MAX - v) < w);
+
+ /* Add in the rest, again ignoring overflow */
+ w += v;
+
+ /* Set the i,j digit of the output */
+ *pt = ACCUM(w);
+
+ /* Save carry information for the next iteration of the loop.
+ This is why k must be an mp_word, instead of an mp_digit */
+ k = CARRYOUT(w) | (u << DIGIT_BIT);
+
+ } /* for(jx ...) */
+
+ /* Set the last digit in the cycle and reset the carry */
+ k = DIGIT(&tmp, ix + jx) + k;
+ pbt[ix + jx] = ACCUM(k);
+ k = CARRYOUT(k);
+
+ /* If we are carrying out, propagate the carry to the next digit
+ in the output. This may cascade, so we have to be somewhat
+ circumspect -- but we will have enough precision in the output
+ that we won't overflow
+ */
+ kx = 1;
+ while(k) {
+ k = pbt[ix + jx + kx] + 1;
+ pbt[ix + jx + kx] = ACCUM(k);
+ k = CARRYOUT(k);
+ ++kx;
+ }
+ } /* for(ix ...) */
+
+ s_mp_clamp(&tmp);
+ s_mp_exch(&tmp, a);
+
+ mp_clear(&tmp);
+
+ return MP_OKAY;
+
+} /* end s_mp_sqr() */
+#endif
+
+/* }}} */
+
+/* {{{ s_mp_div(a, b) */
+
+/*
+ s_mp_div(a, b)
+
+ Compute a = a / b and b = a mod b. Assumes b > a.
+ */
+
+mp_err s_mp_div(mp_int *a, mp_int *b)
+{
+ mp_int quot, rem, t;
+ mp_word q;
+ mp_err res;
+ mp_digit d;
+ int ix;
+
+ if(mp_cmp_z(b) == 0)
+ return MP_RANGE;
+
+ /* Shortcut if b is power of two */
+ if((ix = s_mp_ispow2(b)) >= 0) {
+ mp_copy(a, b); /* need this for remainder */
+ s_mp_div_2d(a, (mp_digit)ix);
+ s_mp_mod_2d(b, (mp_digit)ix);
+
+ return MP_OKAY;
+ }
+
+ /* Allocate space to store the quotient */
+ if((res = mp_init_size(&quot, USED(a))) != MP_OKAY)
+ return res;
+
+ /* A working temporary for division */
+ if((res = mp_init_size(&t, USED(a))) != MP_OKAY)
+ goto T;
+
+ /* Allocate space for the remainder */
+ if((res = mp_init_size(&rem, USED(a))) != MP_OKAY)
+ goto REM;
+
+ /* Normalize to optimize guessing */
+ d = s_mp_norm(a, b);
+
+ /* Perform the division itself...woo! */
+ ix = USED(a) - 1;
+
+ while(ix >= 0) {
+ /* Find a partial substring of a which is at least b */
+ while(s_mp_cmp(&rem, b) < 0 && ix >= 0) {
+ if((res = s_mp_lshd(&rem, 1)) != MP_OKAY)
+ goto CLEANUP;
+
+ if((res = s_mp_lshd(&quot, 1)) != MP_OKAY)
+ goto CLEANUP;
+
+ DIGIT(&rem, 0) = DIGIT(a, ix);
+ s_mp_clamp(&rem);
+ --ix;
+ }
+
+ /* If we didn't find one, we're finished dividing */
+ if(s_mp_cmp(&rem, b) < 0)
+ break;
+
+ /* Compute a guess for the next quotient digit */
+ q = DIGIT(&rem, USED(&rem) - 1);
+ if(q <= DIGIT(b, USED(b) - 1) && USED(&rem) > 1)
+ q = (q << DIGIT_BIT) | DIGIT(&rem, USED(&rem) - 2);
+
+ q /= DIGIT(b, USED(b) - 1);
+
+ /* The guess can be as much as RADIX + 1 */
+ if(q >= RADIX)
+ q = RADIX - 1;
+
+ /* See what that multiplies out to */
+ mp_copy(b, &t);
+ if((res = s_mp_mul_d(&t, q)) != MP_OKAY)
+ goto CLEANUP;
+
+ /*
+ If it's too big, back it off. We should not have to do this
+ more than once, or, in rare cases, twice. Knuth describes a
+ method by which this could be reduced to a maximum of once, but
+ I didn't implement that here.
+ */
+ while(s_mp_cmp(&t, &rem) > 0) {
+ --q;
+ s_mp_sub(&t, b);
+ }
+
+ /* At this point, q should be the right next digit */
+ if((res = s_mp_sub(&rem, &t)) != MP_OKAY)
+ goto CLEANUP;
+
+ /*
+ Include the digit in the quotient. We allocated enough memory
+ for any quotient we could ever possibly get, so we should not
+ have to check for failures here
+ */
+ DIGIT(&quot, 0) = q;
+ }
+
+ /* Denormalize remainder */
+ if(d != 0)
+ s_mp_div_2d(&rem, d);
+
+ s_mp_clamp(&quot);
+ s_mp_clamp(&rem);
+
+ /* Copy quotient back to output */
+ s_mp_exch(&quot, a);
+
+ /* Copy remainder back to output */
+ s_mp_exch(&rem, b);
+
+CLEANUP:
+ mp_clear(&rem);
+REM:
+ mp_clear(&t);
+T:
+ mp_clear(&quot);
+
+ return res;
+
+} /* end s_mp_div() */
+
+/* }}} */
+
+/* {{{ s_mp_2expt(a, k) */
+
+mp_err s_mp_2expt(mp_int *a, mp_digit k)
+{
+ mp_err res;
+ mp_size dig, bit;
+
+ dig = k / DIGIT_BIT;
+ bit = k % DIGIT_BIT;
+
+ mp_zero(a);
+ if((res = s_mp_pad(a, dig + 1)) != MP_OKAY)
+ return res;
+
+ DIGIT(a, dig) |= (1 << bit);
+
+ return MP_OKAY;
+
+} /* end s_mp_2expt() */
+
+/* }}} */
+
+
+/* }}} */
+
+/* }}} */
+
+/* {{{ Primitive comparisons */
+
+/* {{{ s_mp_cmp(a, b) */
+
+/* Compare |a| <=> |b|, return 0 if equal, <0 if a<b, >0 if a>b */
+int s_mp_cmp(mp_int *a, mp_int *b)
+{
+ mp_size ua = USED(a), ub = USED(b);
+
+ if(ua > ub)
+ return MP_GT;
+ else if(ua < ub)
+ return MP_LT;
+ else {
+ int ix = ua - 1;
+ mp_digit *ap = DIGITS(a) + ix, *bp = DIGITS(b) + ix;
+
+ while(ix >= 0) {
+ if(*ap > *bp)
+ return MP_GT;
+ else if(*ap < *bp)
+ return MP_LT;
+
+ --ap; --bp; --ix;
+ }
+
+ return MP_EQ;
+ }
+
+} /* end s_mp_cmp() */
+
+/* }}} */
+
+/* {{{ s_mp_cmp_d(a, d) */
+
+/* Compare |a| <=> d, return 0 if equal, <0 if a<d, >0 if a>d */
+int s_mp_cmp_d(mp_int *a, mp_digit d)
+{
+ mp_size ua = USED(a);
+ mp_digit *ap = DIGITS(a);
+
+ if(ua > 1)
+ return MP_GT;
+
+ if(*ap < d)
+ return MP_LT;
+ else if(*ap > d)
+ return MP_GT;
+ else
+ return MP_EQ;
+
+} /* end s_mp_cmp_d() */
+
+/* }}} */
+
+/* {{{ s_mp_ispow2(v) */
+
+/*
+ Returns -1 if the value is not a power of two; otherwise, it returns
+ k such that v = 2^k, i.e. lg(v).
+ */
+int s_mp_ispow2(mp_int *v)
+{
+ mp_digit d, *dp;
+ mp_size uv = USED(v);
+ int extra = 0, ix;
+
+ d = DIGIT(v, uv - 1); /* most significant digit of v */
+
+ while(d && ((d & 1) == 0)) {
+ d >>= 1;
+ ++extra;
+ }
+
+ if(d == 1) {
+ ix = uv - 2;
+ dp = DIGITS(v) + ix;
+
+ while(ix >= 0) {
+ if(*dp)
+ return -1; /* not a power of two */
+
+ --dp; --ix;
+ }
+
+ return ((uv - 1) * DIGIT_BIT) + extra;
+ }
+
+ return -1;
+
+} /* end s_mp_ispow2() */
+
+/* }}} */
+
+/* {{{ s_mp_ispow2d(d) */
+
+int s_mp_ispow2d(mp_digit d)
+{
+ int pow = 0;
+
+ while((d & 1) == 0) {
+ ++pow; d >>= 1;
+ }
+
+ if(d == 1)
+ return pow;
+
+ return -1;
+
+} /* end s_mp_ispow2d() */
+
+/* }}} */
+
+/* }}} */
+
+/* {{{ Primitive I/O helpers */
+
+/* {{{ s_mp_tovalue(ch, r) */
+
+/*
+ Convert the given character to its digit value, in the given radix.
+ If the given character is not understood in the given radix, -1 is
+ returned. Otherwise the digit's numeric value is returned.
+
+ The results will be odd if you use a radix < 2 or > 62, you are
+ expected to know what you're up to.
+ */
+int s_mp_tovalue(char ch, int r)
+{
+ int val, xch;
+
+ if(r > 36)
+ xch = ch;
+ else
+ xch = toupper(ch);
+
+ if(isdigit(xch))
+ val = xch - '0';
+ else if(isupper(xch))
+ val = xch - 'A' + 10;
+ else if(islower(xch))
+ val = xch - 'a' + 36;
+ else if(xch == '+')
+ val = 62;
+ else if(xch == '/')
+ val = 63;
+ else
+ return -1;
+
+ if(val < 0 || val >= r)
+ return -1;
+
+ return val;
+
+} /* end s_mp_tovalue() */
+
+/* }}} */
+
+/* {{{ s_mp_todigit(val, r, low) */
+
+/*
+ Convert val to a radix-r digit, if possible. If val is out of range
+ for r, returns zero. Otherwise, returns an ASCII character denoting
+ the value in the given radix.
+
+ The results may be odd if you use a radix < 2 or > 64, you are
+ expected to know what you're doing.
+ */
+
+char s_mp_todigit(int val, int r, int low)
+{
+ char ch;
+
+ if(val < 0 || val >= r)
+ return 0;
+
+ ch = s_dmap_1[val];
+
+ if(r <= 36 && low)
+ ch = tolower(ch);
+
+ return ch;
+
+} /* end s_mp_todigit() */
+
+/* }}} */
+
+/* {{{ s_mp_outlen(bits, radix) */
+
+/*
+ Return an estimate for how long a string is needed to hold a radix
+ r representation of a number with 'bits' significant bits.
+
+ Does not include space for a sign or a NUL terminator.
+ */
+int s_mp_outlen(int bits, int r)
+{
+ return (int)((double)bits * LOG_V_2(r));
+
+} /* end s_mp_outlen() */
+
+/* }}} */
+
+/* }}} */
+
+/*------------------------------------------------------------------------*/
+/* HERE THERE BE DRAGONS */
+/* crc==4242132123, version==2, Sat Feb 02 06:43:52 2002 */
+
+/* $Source$ */
+/* $Revision$ */
+/* $Date$ */
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi.h b/third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi.h
new file mode 100644
index 0000000..9a9cc41
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/mtest/mpi.h
@@ -0,0 +1,233 @@
+/*
+ mpi.h
+
+ by Michael J. Fromberger <sting@linguist.dartmouth.edu>
+ Copyright (C) 1998 Michael J. Fromberger
+
+ Arbitrary precision integer arithmetic library
+
+ SPDX-License-Identifier: Unlicense
+
+ $Id$
+ */
+
+#ifndef _H_MPI_
+#define _H_MPI_
+
+#include "mpi-config.h"
+
+#define MP_LT -1
+#define MP_EQ 0
+#define MP_GT 1
+
+#if MP_DEBUG
+#undef MP_IOFUNC
+#define MP_IOFUNC 1
+#endif
+
+#if MP_IOFUNC
+#include <stdio.h>
+#include <ctype.h>
+#endif
+
+#include <limits.h>
+
+#define MP_NEG 1
+#define MP_ZPOS 0
+
+/* Included for compatibility... */
+#define NEG MP_NEG
+#define ZPOS MP_ZPOS
+
+#define MP_OKAY 0 /* no error, all is well */
+#define MP_YES 0 /* yes (boolean result) */
+#define MP_NO -1 /* no (boolean result) */
+#define MP_MEM -2 /* out of memory */
+#define MP_RANGE -3 /* argument out of range */
+#define MP_BADARG -4 /* invalid parameter */
+#define MP_UNDEF -5 /* answer is undefined */
+#define MP_LAST_CODE MP_UNDEF
+
+#include "mpi-types.h"
+
+/* Included for compatibility... */
+#define DIGIT_BIT MP_DIGIT_BIT
+#define DIGIT_MAX MP_DIGIT_MAX
+
+/* Macros for accessing the mp_int internals */
+#define SIGN(MP) ((MP)->sign)
+#define USED(MP) ((MP)->used)
+#define ALLOC(MP) ((MP)->alloc)
+#define DIGITS(MP) ((MP)->dp)
+#define DIGIT(MP,N) (MP)->dp[(N)]
+
+#if MP_ARGCHK == 1
+#define ARGCHK(X,Y) {if(!(X)){return (Y);}}
+#elif MP_ARGCHK == 2
+#include <assert.h>
+#define ARGCHK(X,Y) assert(X)
+#else
+#define ARGCHK(X,Y) /* */
+#endif
+
+/* This defines the maximum I/O base (minimum is 2) */
+#define MAX_RADIX 64
+
+typedef struct {
+ mp_sign sign; /* sign of this quantity */
+ mp_size alloc; /* how many digits allocated */
+ mp_size used; /* how many digits used */
+ mp_digit *dp; /* the digits themselves */
+} mp_int;
+
+/*------------------------------------------------------------------------*/
+/* Default precision */
+
+unsigned int mp_get_prec(void);
+void mp_set_prec(unsigned int prec);
+
+/*------------------------------------------------------------------------*/
+/* Memory management */
+
+mp_err mp_init(mp_int *mp);
+mp_err mp_init_array(mp_int mp[], int count);
+mp_err mp_init_size(mp_int *mp, mp_size prec);
+mp_err mp_init_copy(mp_int *mp, mp_int *from);
+mp_err mp_copy(mp_int *from, mp_int *to);
+void mp_exch(mp_int *mp1, mp_int *mp2);
+void mp_clear(mp_int *mp);
+void mp_clear_array(mp_int mp[], int count);
+void mp_zero(mp_int *mp);
+void mp_set(mp_int *mp, mp_digit d);
+mp_err mp_set_int(mp_int *mp, long z);
+mp_err mp_shrink(mp_int *a);
+
+
+/*------------------------------------------------------------------------*/
+/* Single digit arithmetic */
+
+mp_err mp_add_d(mp_int *a, mp_digit d, mp_int *b);
+mp_err mp_sub_d(mp_int *a, mp_digit d, mp_int *b);
+mp_err mp_mul_d(mp_int *a, mp_digit d, mp_int *b);
+mp_err mp_mul_2(mp_int *a, mp_int *c);
+mp_err mp_div_d(mp_int *a, mp_digit d, mp_int *q, mp_digit *r);
+mp_err mp_div_2(mp_int *a, mp_int *c);
+mp_err mp_expt_d(mp_int *a, mp_digit d, mp_int *c);
+
+/*------------------------------------------------------------------------*/
+/* Sign manipulations */
+
+mp_err mp_abs(mp_int *a, mp_int *b);
+mp_err mp_neg(mp_int *a, mp_int *b);
+
+/*------------------------------------------------------------------------*/
+/* Full arithmetic */
+
+mp_err mp_add(mp_int *a, mp_int *b, mp_int *c);
+mp_err mp_sub(mp_int *a, mp_int *b, mp_int *c);
+mp_err mp_mul(mp_int *a, mp_int *b, mp_int *c);
+mp_err mp_mul_2d(mp_int *a, mp_digit d, mp_int *c);
+#if MP_SQUARE
+mp_err mp_sqr(mp_int *a, mp_int *b);
+#else
+#define mp_sqr(a, b) mp_mul(a, a, b)
+#endif
+mp_err mp_div(mp_int *a, mp_int *b, mp_int *q, mp_int *r);
+mp_err mp_div_2d(mp_int *a, mp_digit d, mp_int *q, mp_int *r);
+mp_err mp_expt(mp_int *a, mp_int *b, mp_int *c);
+mp_err mp_2expt(mp_int *a, mp_digit k);
+mp_err mp_sqrt(mp_int *a, mp_int *b);
+
+/*------------------------------------------------------------------------*/
+/* Modular arithmetic */
+
+#if MP_MODARITH
+mp_err mp_mod(mp_int *a, mp_int *m, mp_int *c);
+mp_err mp_mod_d(mp_int *a, mp_digit d, mp_digit *c);
+mp_err mp_addmod(mp_int *a, mp_int *b, mp_int *m, mp_int *c);
+mp_err mp_submod(mp_int *a, mp_int *b, mp_int *m, mp_int *c);
+mp_err mp_mulmod(mp_int *a, mp_int *b, mp_int *m, mp_int *c);
+#if MP_SQUARE
+mp_err mp_sqrmod(mp_int *a, mp_int *m, mp_int *c);
+#else
+#define mp_sqrmod(a, m, c) mp_mulmod(a, a, m, c)
+#endif
+mp_err mp_exptmod(mp_int *a, mp_int *b, mp_int *m, mp_int *c);
+mp_err mp_exptmod_d(mp_int *a, mp_digit d, mp_int *m, mp_int *c);
+#endif /* MP_MODARITH */
+
+/*------------------------------------------------------------------------*/
+/* Comparisons */
+
+int mp_cmp_z(mp_int *a);
+int mp_cmp_d(mp_int *a, mp_digit d);
+int mp_cmp(mp_int *a, mp_int *b);
+int mp_cmp_mag(mp_int *a, mp_int *b);
+int mp_cmp_int(mp_int *a, long z);
+int mp_isodd(mp_int *a);
+int mp_iseven(mp_int *a);
+
+/*------------------------------------------------------------------------*/
+/* Number theoretic */
+
+#if MP_NUMTH
+mp_err mp_gcd(mp_int *a, mp_int *b, mp_int *c);
+mp_err mp_lcm(mp_int *a, mp_int *b, mp_int *c);
+mp_err mp_xgcd(mp_int *a, mp_int *b, mp_int *g, mp_int *x, mp_int *y);
+mp_err mp_invmod(mp_int *a, mp_int *m, mp_int *c);
+#endif /* end MP_NUMTH */
+
+/*------------------------------------------------------------------------*/
+/* Input and output */
+
+#if MP_IOFUNC
+void mp_print(mp_int *mp, FILE *ofp);
+#endif /* end MP_IOFUNC */
+
+/*------------------------------------------------------------------------*/
+/* Base conversion */
+
+#define BITS 1
+#define BYTES CHAR_BIT
+
+mp_err mp_read_signed_bin(mp_int *mp, unsigned char *str, int len);
+int mp_signed_bin_size(mp_int *mp);
+mp_err mp_to_signed_bin(mp_int *mp, unsigned char *str);
+
+mp_err mp_read_unsigned_bin(mp_int *mp, unsigned char *str, int len);
+int mp_unsigned_bin_size(mp_int *mp);
+mp_err mp_to_unsigned_bin(mp_int *mp, unsigned char *str);
+
+int mp_count_bits(mp_int *mp);
+
+#if MP_COMPAT_MACROS
+#define mp_read_raw(mp, str, len) mp_read_signed_bin((mp), (str), (len))
+#define mp_raw_size(mp) mp_signed_bin_size(mp)
+#define mp_toraw(mp, str) mp_to_signed_bin((mp), (str))
+#define mp_read_mag(mp, str, len) mp_read_unsigned_bin((mp), (str), (len))
+#define mp_mag_size(mp) mp_unsigned_bin_size(mp)
+#define mp_tomag(mp, str) mp_to_unsigned_bin((mp), (str))
+#endif
+
+mp_err mp_read_radix(mp_int *mp, unsigned char *str, int radix);
+int mp_radix_size(mp_int *mp, int radix);
+int mp_value_radix_size(int num, int qty, int radix);
+mp_err mp_toradix(mp_int *mp, char *str, int radix);
+
+int mp_char2value(char ch, int r);
+
+#define mp_tobinary(M, S) mp_toradix((M), (S), 2)
+#define mp_tooctal(M, S) mp_toradix((M), (S), 8)
+#define mp_todecimal(M, S) mp_toradix((M), (S), 10)
+#define mp_tohex(M, S) mp_toradix((M), (S), 16)
+
+/*------------------------------------------------------------------------*/
+/* Error strings */
+
+const char *mp_strerror(mp_err ec);
+
+#endif /* end _H_MPI_ */
+
+/* $Source$ */
+/* $Revision$ */
+/* $Date$ */
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/mtest/mtest.c b/third_party/heimdal/lib/hcrypto/libtommath/mtest/mtest.c
new file mode 100644
index 0000000..06c9afb
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/mtest/mtest.c
@@ -0,0 +1,374 @@
+/* makes a bignum test harness with NUM tests per operation
+ *
+ * the output is made in the following format [one parameter per line]
+
+operation
+operand1
+operand2
+[... operandN]
+result1
+result2
+[... resultN]
+
+So for example "a * b mod n" would be
+
+mulmod
+a
+b
+n
+a*b mod n
+
+e.g. if a=3, b=4 n=11 then
+
+mulmod
+3
+4
+11
+1
+
+ */
+
+#ifdef MP_8BIT
+#define THE_MASK 127
+#else
+#define THE_MASK 32767
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+#include "mpi.c"
+
+#ifdef LTM_MTEST_REAL_RAND
+#define getRandChar() fgetc(rng)
+FILE *rng;
+#else
+#define getRandChar() (rand()&0xFF)
+#endif
+
+void rand_num(mp_int *a)
+{
+ int size;
+ unsigned char buf[2048];
+ size_t sz;
+
+ size = 1 + ((getRandChar()<<8) + getRandChar()) % 101;
+ buf[0] = (getRandChar()&1)?1:0;
+#ifdef LTM_MTEST_REAL_RAND
+ sz = fread(buf+1, 1, size, rng);
+#else
+ sz = 1;
+ while (sz < (unsigned)size) {
+ buf[sz] = getRandChar();
+ ++sz;
+ }
+#endif
+ if (sz != (unsigned)size) {
+ fprintf(stderr, "\nWarning: fread failed\n\n");
+ }
+ while (buf[1] == 0) buf[1] = getRandChar();
+ mp_read_raw(a, buf, 1+size);
+}
+
+void rand_num2(mp_int *a)
+{
+ int size;
+ unsigned char buf[2048];
+ size_t sz;
+
+ size = 10 + ((getRandChar()<<8) + getRandChar()) % 101;
+ buf[0] = (getRandChar()&1)?1:0;
+#ifdef LTM_MTEST_REAL_RAND
+ sz = fread(buf+1, 1, size, rng);
+#else
+ sz = 1;
+ while (sz < (unsigned)size) {
+ buf[sz] = getRandChar();
+ ++sz;
+ }
+#endif
+ if (sz != (unsigned)size) {
+ fprintf(stderr, "\nWarning: fread failed\n\n");
+ }
+ while (buf[1] == 0) buf[1] = getRandChar();
+ mp_read_raw(a, buf, 1+size);
+}
+
+#define mp_to64(a, b) mp_toradix(a, b, 64)
+
+int main(int argc, char *argv[])
+{
+ int n, tmp;
+ long long max;
+ mp_int a, b, c, d, e;
+#ifdef MTEST_NO_FULLSPEED
+ clock_t t1;
+#endif
+ char buf[4096];
+
+ mp_init(&a);
+ mp_init(&b);
+ mp_init(&c);
+ mp_init(&d);
+ mp_init(&e);
+
+ if (argc > 1) {
+ max = strtol(argv[1], NULL, 0);
+ if (max < 0) {
+ if (max > -64) {
+ max = (1 << -(max)) + 1;
+ } else {
+ max = 1;
+ }
+ } else if (max == 0) {
+ max = 1;
+ }
+ } else {
+ max = 0;
+ }
+
+
+ /* initial (2^n - 1)^2 testing, makes sure the comba multiplier works [it has the new carry code] */
+ /*
+ mp_set(&a, 1);
+ for (n = 1; n < 8192; n++) {
+ mp_mul(&a, &a, &c);
+ printf("mul\n");
+ mp_to64(&a, buf);
+ printf("%s\n%s\n", buf, buf);
+ mp_to64(&c, buf);
+ printf("%s\n", buf);
+
+ mp_add_d(&a, 1, &a);
+ mp_mul_2(&a, &a);
+ mp_sub_d(&a, 1, &a);
+ }
+ */
+
+#ifdef LTM_MTEST_REAL_RAND
+ rng = fopen("/dev/urandom", "rb");
+ if (rng == NULL) {
+ rng = fopen("/dev/random", "rb");
+ if (rng == NULL) {
+ fprintf(stderr, "\nWarning: no /dev/[u]random available\n\n");
+ printf("exit\n");
+ return 1;
+ }
+ }
+#else
+ srand(23);
+#endif
+
+#ifdef MTEST_NO_FULLSPEED
+ t1 = clock();
+#endif
+ for (;;) {
+#ifdef MTEST_NO_FULLSPEED
+ if (clock() - t1 > CLOCKS_PER_SEC) {
+ sleep(2);
+ t1 = clock();
+ }
+#endif
+ n = getRandChar() % 15;
+
+ if (max != 0) {
+ --max;
+ if (max == 0)
+ n = 255;
+ }
+
+ if (n == 0) {
+ /* add tests */
+ rand_num(&a);
+ rand_num(&b);
+ mp_add(&a, &b, &c);
+ printf("add\n");
+ mp_to64(&a, buf);
+ printf("%s\n", buf);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ mp_to64(&c, buf);
+ printf("%s\n", buf);
+ } else if (n == 1) {
+ /* sub tests */
+ rand_num(&a);
+ rand_num(&b);
+ mp_sub(&a, &b, &c);
+ printf("sub\n");
+ mp_to64(&a, buf);
+ printf("%s\n", buf);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ mp_to64(&c, buf);
+ printf("%s\n", buf);
+ } else if (n == 2) {
+ /* mul tests */
+ rand_num(&a);
+ rand_num(&b);
+ mp_mul(&a, &b, &c);
+ printf("mul\n");
+ mp_to64(&a, buf);
+ printf("%s\n", buf);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ mp_to64(&c, buf);
+ printf("%s\n", buf);
+ } else if (n == 3) {
+ /* div tests */
+ rand_num(&a);
+ rand_num(&b);
+ mp_div(&a, &b, &c, &d);
+ printf("div\n");
+ mp_to64(&a, buf);
+ printf("%s\n", buf);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ mp_to64(&c, buf);
+ printf("%s\n", buf);
+ mp_to64(&d, buf);
+ printf("%s\n", buf);
+ } else if (n == 4) {
+ /* sqr tests */
+ rand_num(&a);
+ mp_sqr(&a, &b);
+ printf("sqr\n");
+ mp_to64(&a, buf);
+ printf("%s\n", buf);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ } else if (n == 5) {
+ /* mul_2d test */
+ rand_num(&a);
+ mp_copy(&a, &b);
+ n = getRandChar() & 63;
+ mp_mul_2d(&b, n, &b);
+ mp_to64(&a, buf);
+ printf("mul2d\n");
+ printf("%s\n", buf);
+ printf("%d\n", n);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ } else if (n == 6) {
+ /* div_2d test */
+ rand_num(&a);
+ mp_copy(&a, &b);
+ n = getRandChar() & 63;
+ mp_div_2d(&b, n, &b, NULL);
+ mp_to64(&a, buf);
+ printf("div2d\n");
+ printf("%s\n", buf);
+ printf("%d\n", n);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ } else if (n == 7) {
+ /* gcd test */
+ rand_num(&a);
+ rand_num(&b);
+ a.sign = MP_ZPOS;
+ b.sign = MP_ZPOS;
+ mp_gcd(&a, &b, &c);
+ printf("gcd\n");
+ mp_to64(&a, buf);
+ printf("%s\n", buf);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ mp_to64(&c, buf);
+ printf("%s\n", buf);
+ } else if (n == 8) {
+ /* lcm test */
+ rand_num(&a);
+ rand_num(&b);
+ a.sign = MP_ZPOS;
+ b.sign = MP_ZPOS;
+ mp_lcm(&a, &b, &c);
+ printf("lcm\n");
+ mp_to64(&a, buf);
+ printf("%s\n", buf);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ mp_to64(&c, buf);
+ printf("%s\n", buf);
+ } else if (n == 9) {
+ /* exptmod test */
+ rand_num2(&a);
+ rand_num2(&b);
+ rand_num2(&c);
+ /* if (c.dp[0]&1) mp_add_d(&c, 1, &c); */
+ a.sign = b.sign = c.sign = 0;
+ mp_exptmod(&a, &b, &c, &d);
+ printf("expt\n");
+ mp_to64(&a, buf);
+ printf("%s\n", buf);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ mp_to64(&c, buf);
+ printf("%s\n", buf);
+ mp_to64(&d, buf);
+ printf("%s\n", buf);
+ } else if (n == 10) {
+ /* invmod test */
+ do {
+ rand_num2(&a);
+ rand_num2(&b);
+ b.sign = MP_ZPOS;
+ a.sign = MP_ZPOS;
+ mp_gcd(&a, &b, &c);
+ } while (mp_cmp_d(&c, 1) != 0 || mp_cmp_d(&b, 1) == 0);
+ mp_invmod(&a, &b, &c);
+ printf("invmod\n");
+ mp_to64(&a, buf);
+ printf("%s\n", buf);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ mp_to64(&c, buf);
+ printf("%s\n", buf);
+ } else if (n == 11) {
+ rand_num(&a);
+ mp_mul_2(&a, &a);
+ mp_div_2(&a, &b);
+ printf("div2\n");
+ mp_to64(&a, buf);
+ printf("%s\n", buf);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ } else if (n == 12) {
+ rand_num2(&a);
+ mp_mul_2(&a, &b);
+ printf("mul2\n");
+ mp_to64(&a, buf);
+ printf("%s\n", buf);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ } else if (n == 13) {
+ rand_num2(&a);
+ tmp = abs(rand()) & THE_MASK;
+ mp_add_d(&a, tmp, &b);
+ printf("add_d\n");
+ mp_to64(&a, buf);
+ printf("%s\n%d\n", buf, tmp);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ } else if (n == 14) {
+ rand_num2(&a);
+ tmp = abs(rand()) & THE_MASK;
+ mp_sub_d(&a, tmp, &b);
+ printf("sub_d\n");
+ mp_to64(&a, buf);
+ printf("%s\n%d\n", buf, tmp);
+ mp_to64(&b, buf);
+ printf("%s\n", buf);
+ } else if (n == 255) {
+ printf("exit\n");
+ break;
+ }
+
+ }
+#ifdef LTM_MTEST_REAL_RAND
+ fclose(rng);
+#endif
+ return 0;
+}
+
+/* $Source$ */
+/* $Revision$ */
+/* $Date$ */
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/pre_gen/mpi.c b/third_party/heimdal/lib/hcrypto/libtommath/pre_gen/mpi.c
new file mode 100644
index 0000000..96f001d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/pre_gen/mpi.c
@@ -0,0 +1,9541 @@
+/* Start: bn_cutoffs.c */
+#include "tommath_private.h"
+#ifdef BN_CUTOFFS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#ifndef MP_FIXED_CUTOFFS
+#include "tommath_cutoffs.h"
+int KARATSUBA_MUL_CUTOFF = MP_DEFAULT_KARATSUBA_MUL_CUTOFF,
+ KARATSUBA_SQR_CUTOFF = MP_DEFAULT_KARATSUBA_SQR_CUTOFF,
+ TOOM_MUL_CUTOFF = MP_DEFAULT_TOOM_MUL_CUTOFF,
+ TOOM_SQR_CUTOFF = MP_DEFAULT_TOOM_SQR_CUTOFF;
+#endif
+
+#endif
+
+/* End: bn_cutoffs.c */
+
+/* Start: bn_deprecated.c */
+#include "tommath_private.h"
+#ifdef BN_DEPRECATED_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#ifdef BN_MP_GET_BIT_C
+int mp_get_bit(const mp_int *a, int b)
+{
+ if (b < 0) {
+ return MP_VAL;
+ }
+ return (s_mp_get_bit(a, (unsigned int)b) == MP_YES) ? MP_YES : MP_NO;
+}
+#endif
+#ifdef BN_MP_JACOBI_C
+mp_err mp_jacobi(const mp_int *a, const mp_int *n, int *c)
+{
+ if (a->sign == MP_NEG) {
+ return MP_VAL;
+ }
+ if (mp_cmp_d(n, 0uL) != MP_GT) {
+ return MP_VAL;
+ }
+ return mp_kronecker(a, n, c);
+}
+#endif
+#ifdef BN_MP_PRIME_RANDOM_EX_C
+mp_err mp_prime_random_ex(mp_int *a, int t, int size, int flags, private_mp_prime_callback cb, void *dat)
+{
+ return s_mp_prime_random_ex(a, t, size, flags, cb, dat);
+}
+#endif
+#ifdef BN_MP_RAND_DIGIT_C
+mp_err mp_rand_digit(mp_digit *r)
+{
+ mp_err err = s_mp_rand_source(r, sizeof(mp_digit));
+ *r &= MP_MASK;
+ return err;
+}
+#endif
+#ifdef BN_FAST_MP_INVMOD_C
+mp_err fast_mp_invmod(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return s_mp_invmod_fast(a, b, c);
+}
+#endif
+#ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
+mp_err fast_mp_montgomery_reduce(mp_int *x, const mp_int *n, mp_digit rho)
+{
+ return s_mp_montgomery_reduce_fast(x, n, rho);
+}
+#endif
+#ifdef BN_FAST_S_MP_MUL_DIGS_C
+mp_err fast_s_mp_mul_digs(const mp_int *a, const mp_int *b, mp_int *c, int digs)
+{
+ return s_mp_mul_digs_fast(a, b, c, digs);
+}
+#endif
+#ifdef BN_FAST_S_MP_MUL_HIGH_DIGS_C
+mp_err fast_s_mp_mul_high_digs(const mp_int *a, const mp_int *b, mp_int *c, int digs)
+{
+ return s_mp_mul_high_digs_fast(a, b, c, digs);
+}
+#endif
+#ifdef BN_FAST_S_MP_SQR_C
+mp_err fast_s_mp_sqr(const mp_int *a, mp_int *b)
+{
+ return s_mp_sqr_fast(a, b);
+}
+#endif
+#ifdef BN_MP_BALANCE_MUL_C
+mp_err mp_balance_mul(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return s_mp_balance_mul(a, b, c);
+}
+#endif
+#ifdef BN_MP_EXPTMOD_FAST_C
+mp_err mp_exptmod_fast(const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y, int redmode)
+{
+ return s_mp_exptmod_fast(G, X, P, Y, redmode);
+}
+#endif
+#ifdef BN_MP_INVMOD_SLOW_C
+mp_err mp_invmod_slow(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return s_mp_invmod_slow(a, b, c);
+}
+#endif
+#ifdef BN_MP_KARATSUBA_MUL_C
+mp_err mp_karatsuba_mul(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return s_mp_karatsuba_mul(a, b, c);
+}
+#endif
+#ifdef BN_MP_KARATSUBA_SQR_C
+mp_err mp_karatsuba_sqr(const mp_int *a, mp_int *b)
+{
+ return s_mp_karatsuba_sqr(a, b);
+}
+#endif
+#ifdef BN_MP_TOOM_MUL_C
+mp_err mp_toom_mul(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return s_mp_toom_mul(a, b, c);
+}
+#endif
+#ifdef BN_MP_TOOM_SQR_C
+mp_err mp_toom_sqr(const mp_int *a, mp_int *b)
+{
+ return s_mp_toom_sqr(a, b);
+}
+#endif
+#ifdef S_MP_REVERSE_C
+void bn_reverse(unsigned char *s, int len)
+{
+ if (len > 0) {
+ s_mp_reverse(s, (size_t)len);
+ }
+}
+#endif
+#ifdef BN_MP_TC_AND_C
+mp_err mp_tc_and(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return mp_and(a, b, c);
+}
+#endif
+#ifdef BN_MP_TC_OR_C
+mp_err mp_tc_or(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return mp_or(a, b, c);
+}
+#endif
+#ifdef BN_MP_TC_XOR_C
+mp_err mp_tc_xor(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ return mp_xor(a, b, c);
+}
+#endif
+#ifdef BN_MP_TC_DIV_2D_C
+mp_err mp_tc_div_2d(const mp_int *a, int b, mp_int *c)
+{
+ return mp_signed_rsh(a, b, c);
+}
+#endif
+#ifdef BN_MP_INIT_SET_INT_C
+mp_err mp_init_set_int(mp_int *a, unsigned long b)
+{
+ return mp_init_u32(a, (uint32_t)b);
+}
+#endif
+#ifdef BN_MP_SET_INT_C
+mp_err mp_set_int(mp_int *a, unsigned long b)
+{
+ mp_set_u32(a, (uint32_t)b);
+ return MP_OKAY;
+}
+#endif
+#ifdef BN_MP_SET_LONG_C
+mp_err mp_set_long(mp_int *a, unsigned long b)
+{
+ mp_set_u64(a, b);
+ return MP_OKAY;
+}
+#endif
+#ifdef BN_MP_SET_LONG_LONG_C
+mp_err mp_set_long_long(mp_int *a, unsigned long long b)
+{
+ mp_set_u64(a, b);
+ return MP_OKAY;
+}
+#endif
+#ifdef BN_MP_GET_INT_C
+unsigned long mp_get_int(const mp_int *a)
+{
+ return (unsigned long)mp_get_mag_u32(a);
+}
+#endif
+#ifdef BN_MP_GET_LONG_C
+unsigned long mp_get_long(const mp_int *a)
+{
+ return (unsigned long)mp_get_mag_ul(a);
+}
+#endif
+#ifdef BN_MP_GET_LONG_LONG_C
+unsigned long long mp_get_long_long(const mp_int *a)
+{
+ return mp_get_mag_ull(a);
+}
+#endif
+#ifdef BN_MP_PRIME_IS_DIVISIBLE_C
+mp_err mp_prime_is_divisible(const mp_int *a, mp_bool *result)
+{
+ return s_mp_prime_is_divisible(a, result);
+}
+#endif
+#ifdef BN_MP_EXPT_D_EX_C
+mp_err mp_expt_d_ex(const mp_int *a, mp_digit b, mp_int *c, int fast)
+{
+ (void)fast;
+ if (b > MP_MIN(MP_DIGIT_MAX, UINT32_MAX)) {
+ return MP_VAL;
+ }
+ return mp_expt_u32(a, (uint32_t)b, c);
+}
+#endif
+#ifdef BN_MP_EXPT_D_C
+mp_err mp_expt_d(const mp_int *a, mp_digit b, mp_int *c)
+{
+ if (b > MP_MIN(MP_DIGIT_MAX, UINT32_MAX)) {
+ return MP_VAL;
+ }
+ return mp_expt_u32(a, (uint32_t)b, c);
+}
+#endif
+#ifdef BN_MP_N_ROOT_EX_C
+mp_err mp_n_root_ex(const mp_int *a, mp_digit b, mp_int *c, int fast)
+{
+ (void)fast;
+ if (b > MP_MIN(MP_DIGIT_MAX, UINT32_MAX)) {
+ return MP_VAL;
+ }
+ return mp_root_u32(a, (uint32_t)b, c);
+}
+#endif
+#ifdef BN_MP_N_ROOT_C
+mp_err mp_n_root(const mp_int *a, mp_digit b, mp_int *c)
+{
+ if (b > MP_MIN(MP_DIGIT_MAX, UINT32_MAX)) {
+ return MP_VAL;
+ }
+ return mp_root_u32(a, (uint32_t)b, c);
+}
+#endif
+#ifdef BN_MP_UNSIGNED_BIN_SIZE_C
+int mp_unsigned_bin_size(const mp_int *a)
+{
+ return (int)mp_ubin_size(a);
+}
+#endif
+#ifdef BN_MP_READ_UNSIGNED_BIN_C
+mp_err mp_read_unsigned_bin(mp_int *a, const unsigned char *b, int c)
+{
+ return mp_from_ubin(a, b, (size_t) c);
+}
+#endif
+#ifdef BN_MP_TO_UNSIGNED_BIN_C
+mp_err mp_to_unsigned_bin(const mp_int *a, unsigned char *b)
+{
+ return mp_to_ubin(a, b, SIZE_MAX, NULL);
+}
+#endif
+#ifdef BN_MP_TO_UNSIGNED_BIN_N_C
+mp_err mp_to_unsigned_bin_n(const mp_int *a, unsigned char *b, unsigned long *outlen)
+{
+ size_t n = mp_ubin_size(a);
+ if (*outlen < (unsigned long)n) {
+ return MP_VAL;
+ }
+ *outlen = (unsigned long)n;
+ return mp_to_ubin(a, b, n, NULL);
+}
+#endif
+#ifdef BN_MP_SIGNED_BIN_SIZE_C
+int mp_signed_bin_size(const mp_int *a)
+{
+ return (int)mp_sbin_size(a);
+}
+#endif
+#ifdef BN_MP_READ_SIGNED_BIN_C
+mp_err mp_read_signed_bin(mp_int *a, const unsigned char *b, int c)
+{
+ return mp_from_sbin(a, b, (size_t) c);
+}
+#endif
+#ifdef BN_MP_TO_SIGNED_BIN_C
+mp_err mp_to_signed_bin(const mp_int *a, unsigned char *b)
+{
+ return mp_to_sbin(a, b, SIZE_MAX, NULL);
+}
+#endif
+#ifdef BN_MP_TO_SIGNED_BIN_N_C
+mp_err mp_to_signed_bin_n(const mp_int *a, unsigned char *b, unsigned long *outlen)
+{
+ size_t n = mp_sbin_size(a);
+ if (*outlen < (unsigned long)n) {
+ return MP_VAL;
+ }
+ *outlen = (unsigned long)n;
+ return mp_to_sbin(a, b, n, NULL);
+}
+#endif
+#ifdef BN_MP_TORADIX_N_C
+mp_err mp_toradix_n(const mp_int *a, char *str, int radix, int maxlen)
+{
+ if (maxlen < 0) {
+ return MP_VAL;
+ }
+ return mp_to_radix(a, str, (size_t)maxlen, NULL, radix);
+}
+#endif
+#ifdef BN_MP_TORADIX_C
+mp_err mp_toradix(const mp_int *a, char *str, int radix)
+{
+ return mp_to_radix(a, str, SIZE_MAX, NULL, radix);
+}
+#endif
+#ifdef BN_MP_IMPORT_C
+mp_err mp_import(mp_int *rop, size_t count, int order, size_t size, int endian, size_t nails,
+ const void *op)
+{
+ return mp_unpack(rop, count, order, size, endian, nails, op);
+}
+#endif
+#ifdef BN_MP_EXPORT_C
+mp_err mp_export(void *rop, size_t *countp, int order, size_t size,
+ int endian, size_t nails, const mp_int *op)
+{
+ return mp_pack(rop, SIZE_MAX, countp, order, size, endian, nails, op);
+}
+#endif
+#endif
+
+/* End: bn_deprecated.c */
+
+/* Start: bn_mp_2expt.c */
+#include "tommath_private.h"
+#ifdef BN_MP_2EXPT_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* computes a = 2**b
+ *
+ * Simple algorithm which zeroes the int, grows it then just sets one bit
+ * as required.
+ */
+mp_err mp_2expt(mp_int *a, int b)
+{
+ mp_err err;
+
+ /* zero a as per default */
+ mp_zero(a);
+
+ /* grow a to accomodate the single bit */
+ if ((err = mp_grow(a, (b / MP_DIGIT_BIT) + 1)) != MP_OKAY) {
+ return err;
+ }
+
+ /* set the used count of where the bit will go */
+ a->used = (b / MP_DIGIT_BIT) + 1;
+
+ /* put the single bit in its place */
+ a->dp[b / MP_DIGIT_BIT] = (mp_digit)1 << (mp_digit)(b % MP_DIGIT_BIT);
+
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_2expt.c */
+
+/* Start: bn_mp_abs.c */
+#include "tommath_private.h"
+#ifdef BN_MP_ABS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* b = |a|
+ *
+ * Simple function copies the input and fixes the sign to positive
+ */
+mp_err mp_abs(const mp_int *a, mp_int *b)
+{
+ mp_err err;
+
+ /* copy a to b */
+ if (a != b) {
+ if ((err = mp_copy(a, b)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* force the sign of b to positive */
+ b->sign = MP_ZPOS;
+
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_abs.c */
+
+/* Start: bn_mp_add.c */
+#include "tommath_private.h"
+#ifdef BN_MP_ADD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* high level addition (handles signs) */
+mp_err mp_add(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_sign sa, sb;
+ mp_err err;
+
+ /* get sign of both inputs */
+ sa = a->sign;
+ sb = b->sign;
+
+ /* handle two cases, not four */
+ if (sa == sb) {
+ /* both positive or both negative */
+ /* add their magnitudes, copy the sign */
+ c->sign = sa;
+ err = s_mp_add(a, b, c);
+ } else {
+ /* one positive, the other negative */
+ /* subtract the one with the greater magnitude from */
+ /* the one of the lesser magnitude. The result gets */
+ /* the sign of the one with the greater magnitude. */
+ if (mp_cmp_mag(a, b) == MP_LT) {
+ c->sign = sb;
+ err = s_mp_sub(b, a, c);
+ } else {
+ c->sign = sa;
+ err = s_mp_sub(a, b, c);
+ }
+ }
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_add.c */
+
+/* Start: bn_mp_add_d.c */
+#include "tommath_private.h"
+#ifdef BN_MP_ADD_D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* single digit addition */
+mp_err mp_add_d(const mp_int *a, mp_digit b, mp_int *c)
+{
+ mp_err err;
+ int ix, oldused;
+ mp_digit *tmpa, *tmpc;
+
+ /* grow c as required */
+ if (c->alloc < (a->used + 1)) {
+ if ((err = mp_grow(c, a->used + 1)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* if a is negative and |a| >= b, call c = |a| - b */
+ if ((a->sign == MP_NEG) && ((a->used > 1) || (a->dp[0] >= b))) {
+ mp_int a_ = *a;
+ /* temporarily fix sign of a */
+ a_.sign = MP_ZPOS;
+
+ /* c = |a| - b */
+ err = mp_sub_d(&a_, b, c);
+
+ /* fix sign */
+ c->sign = MP_NEG;
+
+ /* clamp */
+ mp_clamp(c);
+
+ return err;
+ }
+
+ /* old number of used digits in c */
+ oldused = c->used;
+
+ /* source alias */
+ tmpa = a->dp;
+
+ /* destination alias */
+ tmpc = c->dp;
+
+ /* if a is positive */
+ if (a->sign == MP_ZPOS) {
+ /* add digits, mu is carry */
+ mp_digit mu = b;
+ for (ix = 0; ix < a->used; ix++) {
+ *tmpc = *tmpa++ + mu;
+ mu = *tmpc >> MP_DIGIT_BIT;
+ *tmpc++ &= MP_MASK;
+ }
+ /* set final carry */
+ ix++;
+ *tmpc++ = mu;
+
+ /* setup size */
+ c->used = a->used + 1;
+ } else {
+ /* a was negative and |a| < b */
+ c->used = 1;
+
+ /* the result is a single digit */
+ if (a->used == 1) {
+ *tmpc++ = b - a->dp[0];
+ } else {
+ *tmpc++ = b;
+ }
+
+ /* setup count so the clearing of oldused
+ * can fall through correctly
+ */
+ ix = 1;
+ }
+
+ /* sign always positive */
+ c->sign = MP_ZPOS;
+
+ /* now zero to oldused */
+ MP_ZERO_DIGITS(tmpc, oldused - ix);
+ mp_clamp(c);
+
+ return MP_OKAY;
+}
+
+#endif
+
+/* End: bn_mp_add_d.c */
+
+/* Start: bn_mp_addmod.c */
+#include "tommath_private.h"
+#ifdef BN_MP_ADDMOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* d = a + b (mod c) */
+mp_err mp_addmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d)
+{
+ mp_err err;
+ mp_int t;
+
+ if ((err = mp_init(&t)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_add(a, b, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ err = mp_mod(&t, c, d);
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+#endif
+
+/* End: bn_mp_addmod.c */
+
+/* Start: bn_mp_and.c */
+#include "tommath_private.h"
+#ifdef BN_MP_AND_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* two complement and */
+mp_err mp_and(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ int used = MP_MAX(a->used, b->used) + 1, i;
+ mp_err err;
+ mp_digit ac = 1, bc = 1, cc = 1;
+ mp_sign csign = ((a->sign == MP_NEG) && (b->sign == MP_NEG)) ? MP_NEG : MP_ZPOS;
+
+ if (c->alloc < used) {
+ if ((err = mp_grow(c, used)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ for (i = 0; i < used; i++) {
+ mp_digit x, y;
+
+ /* convert to two complement if negative */
+ if (a->sign == MP_NEG) {
+ ac += (i >= a->used) ? MP_MASK : (~a->dp[i] & MP_MASK);
+ x = ac & MP_MASK;
+ ac >>= MP_DIGIT_BIT;
+ } else {
+ x = (i >= a->used) ? 0uL : a->dp[i];
+ }
+
+ /* convert to two complement if negative */
+ if (b->sign == MP_NEG) {
+ bc += (i >= b->used) ? MP_MASK : (~b->dp[i] & MP_MASK);
+ y = bc & MP_MASK;
+ bc >>= MP_DIGIT_BIT;
+ } else {
+ y = (i >= b->used) ? 0uL : b->dp[i];
+ }
+
+ c->dp[i] = x & y;
+
+ /* convert to to sign-magnitude if negative */
+ if (csign == MP_NEG) {
+ cc += ~c->dp[i] & MP_MASK;
+ c->dp[i] = cc & MP_MASK;
+ cc >>= MP_DIGIT_BIT;
+ }
+ }
+
+ c->used = used;
+ c->sign = csign;
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_and.c */
+
+/* Start: bn_mp_clamp.c */
+#include "tommath_private.h"
+#ifdef BN_MP_CLAMP_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* trim unused digits
+ *
+ * This is used to ensure that leading zero digits are
+ * trimed and the leading "used" digit will be non-zero
+ * Typically very fast. Also fixes the sign if there
+ * are no more leading digits
+ */
+void mp_clamp(mp_int *a)
+{
+ /* decrease used while the most significant digit is
+ * zero.
+ */
+ while ((a->used > 0) && (a->dp[a->used - 1] == 0u)) {
+ --(a->used);
+ }
+
+ /* reset the sign flag if used == 0 */
+ if (a->used == 0) {
+ a->sign = MP_ZPOS;
+ }
+}
+#endif
+
+/* End: bn_mp_clamp.c */
+
+/* Start: bn_mp_clear.c */
+#include "tommath_private.h"
+#ifdef BN_MP_CLEAR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* clear one (frees) */
+void mp_clear(mp_int *a)
+{
+ /* only do anything if a hasn't been freed previously */
+ if (a->dp != NULL) {
+ /* free ram */
+ MP_FREE_DIGITS(a->dp, a->alloc);
+
+ /* reset members to make debugging easier */
+ a->dp = NULL;
+ a->alloc = a->used = 0;
+ a->sign = MP_ZPOS;
+ }
+}
+#endif
+
+/* End: bn_mp_clear.c */
+
+/* Start: bn_mp_clear_multi.c */
+#include "tommath_private.h"
+#ifdef BN_MP_CLEAR_MULTI_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#include <stdarg.h>
+
+void mp_clear_multi(mp_int *mp, ...)
+{
+ mp_int *next_mp = mp;
+ va_list args;
+ va_start(args, mp);
+ while (next_mp != NULL) {
+ mp_clear(next_mp);
+ next_mp = va_arg(args, mp_int *);
+ }
+ va_end(args);
+}
+#endif
+
+/* End: bn_mp_clear_multi.c */
+
+/* Start: bn_mp_cmp.c */
+#include "tommath_private.h"
+#ifdef BN_MP_CMP_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* compare two ints (signed)*/
+mp_ord mp_cmp(const mp_int *a, const mp_int *b)
+{
+ /* compare based on sign */
+ if (a->sign != b->sign) {
+ if (a->sign == MP_NEG) {
+ return MP_LT;
+ } else {
+ return MP_GT;
+ }
+ }
+
+ /* compare digits */
+ if (a->sign == MP_NEG) {
+ /* if negative compare opposite direction */
+ return mp_cmp_mag(b, a);
+ } else {
+ return mp_cmp_mag(a, b);
+ }
+}
+#endif
+
+/* End: bn_mp_cmp.c */
+
+/* Start: bn_mp_cmp_d.c */
+#include "tommath_private.h"
+#ifdef BN_MP_CMP_D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* compare a digit */
+mp_ord mp_cmp_d(const mp_int *a, mp_digit b)
+{
+ /* compare based on sign */
+ if (a->sign == MP_NEG) {
+ return MP_LT;
+ }
+
+ /* compare based on magnitude */
+ if (a->used > 1) {
+ return MP_GT;
+ }
+
+ /* compare the only digit of a to b */
+ if (a->dp[0] > b) {
+ return MP_GT;
+ } else if (a->dp[0] < b) {
+ return MP_LT;
+ } else {
+ return MP_EQ;
+ }
+}
+#endif
+
+/* End: bn_mp_cmp_d.c */
+
+/* Start: bn_mp_cmp_mag.c */
+#include "tommath_private.h"
+#ifdef BN_MP_CMP_MAG_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* compare maginitude of two ints (unsigned) */
+mp_ord mp_cmp_mag(const mp_int *a, const mp_int *b)
+{
+ int n;
+ const mp_digit *tmpa, *tmpb;
+
+ /* compare based on # of non-zero digits */
+ if (a->used > b->used) {
+ return MP_GT;
+ }
+
+ if (a->used < b->used) {
+ return MP_LT;
+ }
+
+ /* alias for a */
+ tmpa = a->dp + (a->used - 1);
+
+ /* alias for b */
+ tmpb = b->dp + (a->used - 1);
+
+ /* compare based on digits */
+ for (n = 0; n < a->used; ++n, --tmpa, --tmpb) {
+ if (*tmpa > *tmpb) {
+ return MP_GT;
+ }
+
+ if (*tmpa < *tmpb) {
+ return MP_LT;
+ }
+ }
+ return MP_EQ;
+}
+#endif
+
+/* End: bn_mp_cmp_mag.c */
+
+/* Start: bn_mp_cnt_lsb.c */
+#include "tommath_private.h"
+#ifdef BN_MP_CNT_LSB_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+static const int lnz[16] = {
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0
+};
+
+/* Counts the number of lsbs which are zero before the first zero bit */
+int mp_cnt_lsb(const mp_int *a)
+{
+ int x;
+ mp_digit q, qq;
+
+ /* easy out */
+ if (MP_IS_ZERO(a)) {
+ return 0;
+ }
+
+ /* scan lower digits until non-zero */
+ for (x = 0; (x < a->used) && (a->dp[x] == 0u); x++) {}
+ q = a->dp[x];
+ x *= MP_DIGIT_BIT;
+
+ /* now scan this digit until a 1 is found */
+ if ((q & 1u) == 0u) {
+ do {
+ qq = q & 15u;
+ x += lnz[qq];
+ q >>= 4;
+ } while (qq == 0u);
+ }
+ return x;
+}
+
+#endif
+
+/* End: bn_mp_cnt_lsb.c */
+
+/* Start: bn_mp_complement.c */
+#include "tommath_private.h"
+#ifdef BN_MP_COMPLEMENT_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* b = ~a */
+mp_err mp_complement(const mp_int *a, mp_int *b)
+{
+ mp_err err = mp_neg(a, b);
+ return (err == MP_OKAY) ? mp_sub_d(b, 1uL, b) : err;
+}
+#endif
+
+/* End: bn_mp_complement.c */
+
+/* Start: bn_mp_copy.c */
+#include "tommath_private.h"
+#ifdef BN_MP_COPY_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* copy, b = a */
+mp_err mp_copy(const mp_int *a, mp_int *b)
+{
+ int n;
+ mp_digit *tmpa, *tmpb;
+ mp_err err;
+
+ /* if dst == src do nothing */
+ if (a == b) {
+ return MP_OKAY;
+ }
+
+ /* grow dest */
+ if (b->alloc < a->used) {
+ if ((err = mp_grow(b, a->used)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* zero b and copy the parameters over */
+ /* pointer aliases */
+
+ /* source */
+ tmpa = a->dp;
+
+ /* destination */
+ tmpb = b->dp;
+
+ /* copy all the digits */
+ for (n = 0; n < a->used; n++) {
+ *tmpb++ = *tmpa++;
+ }
+
+ /* clear high digits */
+ MP_ZERO_DIGITS(tmpb, b->used - n);
+
+ /* copy used count and sign */
+ b->used = a->used;
+ b->sign = a->sign;
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_copy.c */
+
+/* Start: bn_mp_count_bits.c */
+#include "tommath_private.h"
+#ifdef BN_MP_COUNT_BITS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* returns the number of bits in an int */
+int mp_count_bits(const mp_int *a)
+{
+ int r;
+ mp_digit q;
+
+ /* shortcut */
+ if (MP_IS_ZERO(a)) {
+ return 0;
+ }
+
+ /* get number of digits and add that */
+ r = (a->used - 1) * MP_DIGIT_BIT;
+
+ /* take the last digit and count the bits in it */
+ q = a->dp[a->used - 1];
+ while (q > 0u) {
+ ++r;
+ q >>= 1u;
+ }
+ return r;
+}
+#endif
+
+/* End: bn_mp_count_bits.c */
+
+/* Start: bn_mp_decr.c */
+#include "tommath_private.h"
+#ifdef BN_MP_DECR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Decrement "a" by one like "a--". Changes input! */
+mp_err mp_decr(mp_int *a)
+{
+ if (MP_IS_ZERO(a)) {
+ mp_set(a,1uL);
+ a->sign = MP_NEG;
+ return MP_OKAY;
+ } else if (a->sign == MP_NEG) {
+ mp_err err;
+ a->sign = MP_ZPOS;
+ if ((err = mp_incr(a)) != MP_OKAY) {
+ return err;
+ }
+ /* There is no -0 in LTM */
+ if (!MP_IS_ZERO(a)) {
+ a->sign = MP_NEG;
+ }
+ return MP_OKAY;
+ } else if (a->dp[0] > 1uL) {
+ a->dp[0]--;
+ if (a->dp[0] == 0u) {
+ mp_zero(a);
+ }
+ return MP_OKAY;
+ } else {
+ return mp_sub_d(a, 1uL,a);
+ }
+}
+#endif
+
+/* End: bn_mp_decr.c */
+
+/* Start: bn_mp_div.c */
+#include "tommath_private.h"
+#ifdef BN_MP_DIV_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#ifdef BN_MP_DIV_SMALL
+
+/* slower bit-bang division... also smaller */
+mp_err mp_div(const mp_int *a, const mp_int *b, mp_int *c, mp_int *d)
+{
+ mp_int ta, tb, tq, q;
+ int n, n2;
+ mp_err err;
+
+ /* is divisor zero ? */
+ if (MP_IS_ZERO(b)) {
+ return MP_VAL;
+ }
+
+ /* if a < b then q=0, r = a */
+ if (mp_cmp_mag(a, b) == MP_LT) {
+ if (d != NULL) {
+ err = mp_copy(a, d);
+ } else {
+ err = MP_OKAY;
+ }
+ if (c != NULL) {
+ mp_zero(c);
+ }
+ return err;
+ }
+
+ /* init our temps */
+ if ((err = mp_init_multi(&ta, &tb, &tq, &q, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+
+ mp_set(&tq, 1uL);
+ n = mp_count_bits(a) - mp_count_bits(b);
+ if ((err = mp_abs(a, &ta)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_abs(b, &tb)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_mul_2d(&tb, n, &tb)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_mul_2d(&tq, n, &tq)) != MP_OKAY) goto LBL_ERR;
+
+ while (n-- >= 0) {
+ if (mp_cmp(&tb, &ta) != MP_GT) {
+ if ((err = mp_sub(&ta, &tb, &ta)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(&q, &tq, &q)) != MP_OKAY) goto LBL_ERR;
+ }
+ if ((err = mp_div_2d(&tb, 1, &tb, NULL)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_div_2d(&tq, 1, &tq, NULL)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* now q == quotient and ta == remainder */
+ n = a->sign;
+ n2 = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
+ if (c != NULL) {
+ mp_exch(c, &q);
+ c->sign = MP_IS_ZERO(c) ? MP_ZPOS : n2;
+ }
+ if (d != NULL) {
+ mp_exch(d, &ta);
+ d->sign = MP_IS_ZERO(d) ? MP_ZPOS : n;
+ }
+LBL_ERR:
+ mp_clear_multi(&ta, &tb, &tq, &q, NULL);
+ return err;
+}
+
+#else
+
+/* integer signed division.
+ * c*b + d == a [e.g. a/b, c=quotient, d=remainder]
+ * HAC pp.598 Algorithm 14.20
+ *
+ * Note that the description in HAC is horribly
+ * incomplete. For example, it doesn't consider
+ * the case where digits are removed from 'x' in
+ * the inner loop. It also doesn't consider the
+ * case that y has fewer than three digits, etc..
+ *
+ * The overall algorithm is as described as
+ * 14.20 from HAC but fixed to treat these cases.
+*/
+mp_err mp_div(const mp_int *a, const mp_int *b, mp_int *c, mp_int *d)
+{
+ mp_int q, x, y, t1, t2;
+ int n, t, i, norm;
+ mp_sign neg;
+ mp_err err;
+
+ /* is divisor zero ? */
+ if (MP_IS_ZERO(b)) {
+ return MP_VAL;
+ }
+
+ /* if a < b then q=0, r = a */
+ if (mp_cmp_mag(a, b) == MP_LT) {
+ if (d != NULL) {
+ err = mp_copy(a, d);
+ } else {
+ err = MP_OKAY;
+ }
+ if (c != NULL) {
+ mp_zero(c);
+ }
+ return err;
+ }
+
+ if ((err = mp_init_size(&q, a->used + 2)) != MP_OKAY) {
+ return err;
+ }
+ q.used = a->used + 2;
+
+ if ((err = mp_init(&t1)) != MP_OKAY) goto LBL_Q;
+
+ if ((err = mp_init(&t2)) != MP_OKAY) goto LBL_T1;
+
+ if ((err = mp_init_copy(&x, a)) != MP_OKAY) goto LBL_T2;
+
+ if ((err = mp_init_copy(&y, b)) != MP_OKAY) goto LBL_X;
+
+ /* fix the sign */
+ neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
+ x.sign = y.sign = MP_ZPOS;
+
+ /* normalize both x and y, ensure that y >= b/2, [b == 2**MP_DIGIT_BIT] */
+ norm = mp_count_bits(&y) % MP_DIGIT_BIT;
+ if (norm < (MP_DIGIT_BIT - 1)) {
+ norm = (MP_DIGIT_BIT - 1) - norm;
+ if ((err = mp_mul_2d(&x, norm, &x)) != MP_OKAY) goto LBL_Y;
+ if ((err = mp_mul_2d(&y, norm, &y)) != MP_OKAY) goto LBL_Y;
+ } else {
+ norm = 0;
+ }
+
+ /* note hac does 0 based, so if used==5 then its 0,1,2,3,4, e.g. use 4 */
+ n = x.used - 1;
+ t = y.used - 1;
+
+ /* while (x >= y*b**n-t) do { q[n-t] += 1; x -= y*b**{n-t} } */
+ /* y = y*b**{n-t} */
+ if ((err = mp_lshd(&y, n - t)) != MP_OKAY) goto LBL_Y;
+
+ while (mp_cmp(&x, &y) != MP_LT) {
+ ++(q.dp[n - t]);
+ if ((err = mp_sub(&x, &y, &x)) != MP_OKAY) goto LBL_Y;
+ }
+
+ /* reset y by shifting it back down */
+ mp_rshd(&y, n - t);
+
+ /* step 3. for i from n down to (t + 1) */
+ for (i = n; i >= (t + 1); i--) {
+ if (i > x.used) {
+ continue;
+ }
+
+ /* step 3.1 if xi == yt then set q{i-t-1} to b-1,
+ * otherwise set q{i-t-1} to (xi*b + x{i-1})/yt */
+ if (x.dp[i] == y.dp[t]) {
+ q.dp[(i - t) - 1] = ((mp_digit)1 << (mp_digit)MP_DIGIT_BIT) - (mp_digit)1;
+ } else {
+ mp_word tmp;
+ tmp = (mp_word)x.dp[i] << (mp_word)MP_DIGIT_BIT;
+ tmp |= (mp_word)x.dp[i - 1];
+ tmp /= (mp_word)y.dp[t];
+ if (tmp > (mp_word)MP_MASK) {
+ tmp = MP_MASK;
+ }
+ q.dp[(i - t) - 1] = (mp_digit)(tmp & (mp_word)MP_MASK);
+ }
+
+ /* while (q{i-t-1} * (yt * b + y{t-1})) >
+ xi * b**2 + xi-1 * b + xi-2
+
+ do q{i-t-1} -= 1;
+ */
+ q.dp[(i - t) - 1] = (q.dp[(i - t) - 1] + 1uL) & (mp_digit)MP_MASK;
+ do {
+ q.dp[(i - t) - 1] = (q.dp[(i - t) - 1] - 1uL) & (mp_digit)MP_MASK;
+
+ /* find left hand */
+ mp_zero(&t1);
+ t1.dp[0] = ((t - 1) < 0) ? 0u : y.dp[t - 1];
+ t1.dp[1] = y.dp[t];
+ t1.used = 2;
+ if ((err = mp_mul_d(&t1, q.dp[(i - t) - 1], &t1)) != MP_OKAY) goto LBL_Y;
+
+ /* find right hand */
+ t2.dp[0] = ((i - 2) < 0) ? 0u : x.dp[i - 2];
+ t2.dp[1] = x.dp[i - 1]; /* i >= 1 always holds */
+ t2.dp[2] = x.dp[i];
+ t2.used = 3;
+ } while (mp_cmp_mag(&t1, &t2) == MP_GT);
+
+ /* step 3.3 x = x - q{i-t-1} * y * b**{i-t-1} */
+ if ((err = mp_mul_d(&y, q.dp[(i - t) - 1], &t1)) != MP_OKAY) goto LBL_Y;
+
+ if ((err = mp_lshd(&t1, (i - t) - 1)) != MP_OKAY) goto LBL_Y;
+
+ if ((err = mp_sub(&x, &t1, &x)) != MP_OKAY) goto LBL_Y;
+
+ /* if x < 0 then { x = x + y*b**{i-t-1}; q{i-t-1} -= 1; } */
+ if (x.sign == MP_NEG) {
+ if ((err = mp_copy(&y, &t1)) != MP_OKAY) goto LBL_Y;
+ if ((err = mp_lshd(&t1, (i - t) - 1)) != MP_OKAY) goto LBL_Y;
+ if ((err = mp_add(&x, &t1, &x)) != MP_OKAY) goto LBL_Y;
+
+ q.dp[(i - t) - 1] = (q.dp[(i - t) - 1] - 1uL) & MP_MASK;
+ }
+ }
+
+ /* now q is the quotient and x is the remainder
+ * [which we have to normalize]
+ */
+
+ /* get sign before writing to c */
+ x.sign = (x.used == 0) ? MP_ZPOS : a->sign;
+
+ if (c != NULL) {
+ mp_clamp(&q);
+ mp_exch(&q, c);
+ c->sign = neg;
+ }
+
+ if (d != NULL) {
+ if ((err = mp_div_2d(&x, norm, &x, NULL)) != MP_OKAY) goto LBL_Y;
+ mp_exch(&x, d);
+ }
+
+ err = MP_OKAY;
+
+LBL_Y:
+ mp_clear(&y);
+LBL_X:
+ mp_clear(&x);
+LBL_T2:
+ mp_clear(&t2);
+LBL_T1:
+ mp_clear(&t1);
+LBL_Q:
+ mp_clear(&q);
+ return err;
+}
+
+#endif
+
+#endif
+
+/* End: bn_mp_div.c */
+
+/* Start: bn_mp_div_2.c */
+#include "tommath_private.h"
+#ifdef BN_MP_DIV_2_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* b = a/2 */
+mp_err mp_div_2(const mp_int *a, mp_int *b)
+{
+ int x, oldused;
+ mp_digit r, rr, *tmpa, *tmpb;
+ mp_err err;
+
+ /* copy */
+ if (b->alloc < a->used) {
+ if ((err = mp_grow(b, a->used)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ oldused = b->used;
+ b->used = a->used;
+
+ /* source alias */
+ tmpa = a->dp + b->used - 1;
+
+ /* dest alias */
+ tmpb = b->dp + b->used - 1;
+
+ /* carry */
+ r = 0;
+ for (x = b->used - 1; x >= 0; x--) {
+ /* get the carry for the next iteration */
+ rr = *tmpa & 1u;
+
+ /* shift the current digit, add in carry and store */
+ *tmpb-- = (*tmpa-- >> 1) | (r << (MP_DIGIT_BIT - 1));
+
+ /* forward carry to next iteration */
+ r = rr;
+ }
+
+ /* zero excess digits */
+ MP_ZERO_DIGITS(b->dp + b->used, oldused - b->used);
+
+ b->sign = a->sign;
+ mp_clamp(b);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_div_2.c */
+
+/* Start: bn_mp_div_2d.c */
+#include "tommath_private.h"
+#ifdef BN_MP_DIV_2D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* shift right by a certain bit count (store quotient in c, optional remainder in d) */
+mp_err mp_div_2d(const mp_int *a, int b, mp_int *c, mp_int *d)
+{
+ mp_digit D, r, rr;
+ int x;
+ mp_err err;
+
+ /* if the shift count is <= 0 then we do no work */
+ if (b <= 0) {
+ err = mp_copy(a, c);
+ if (d != NULL) {
+ mp_zero(d);
+ }
+ return err;
+ }
+
+ /* copy */
+ if ((err = mp_copy(a, c)) != MP_OKAY) {
+ return err;
+ }
+ /* 'a' should not be used after here - it might be the same as d */
+
+ /* get the remainder */
+ if (d != NULL) {
+ if ((err = mp_mod_2d(a, b, d)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* shift by as many digits in the bit count */
+ if (b >= MP_DIGIT_BIT) {
+ mp_rshd(c, b / MP_DIGIT_BIT);
+ }
+
+ /* shift any bit count < MP_DIGIT_BIT */
+ D = (mp_digit)(b % MP_DIGIT_BIT);
+ if (D != 0u) {
+ mp_digit *tmpc, mask, shift;
+
+ /* mask */
+ mask = ((mp_digit)1 << D) - 1uL;
+
+ /* shift for lsb */
+ shift = (mp_digit)MP_DIGIT_BIT - D;
+
+ /* alias */
+ tmpc = c->dp + (c->used - 1);
+
+ /* carry */
+ r = 0;
+ for (x = c->used - 1; x >= 0; x--) {
+ /* get the lower bits of this word in a temp */
+ rr = *tmpc & mask;
+
+ /* shift the current word and mix in the carry bits from the previous word */
+ *tmpc = (*tmpc >> D) | (r << shift);
+ --tmpc;
+
+ /* set the carry to the carry bits of the current word found above */
+ r = rr;
+ }
+ }
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_div_2d.c */
+
+/* Start: bn_mp_div_3.c */
+#include "tommath_private.h"
+#ifdef BN_MP_DIV_3_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* divide by three (based on routine from MPI and the GMP manual) */
+mp_err mp_div_3(const mp_int *a, mp_int *c, mp_digit *d)
+{
+ mp_int q;
+ mp_word w, t;
+ mp_digit b;
+ mp_err err;
+ int ix;
+
+ /* b = 2**MP_DIGIT_BIT / 3 */
+ b = ((mp_word)1 << (mp_word)MP_DIGIT_BIT) / (mp_word)3;
+
+ if ((err = mp_init_size(&q, a->used)) != MP_OKAY) {
+ return err;
+ }
+
+ q.used = a->used;
+ q.sign = a->sign;
+ w = 0;
+ for (ix = a->used - 1; ix >= 0; ix--) {
+ w = (w << (mp_word)MP_DIGIT_BIT) | (mp_word)a->dp[ix];
+
+ if (w >= 3u) {
+ /* multiply w by [1/3] */
+ t = (w * (mp_word)b) >> (mp_word)MP_DIGIT_BIT;
+
+ /* now subtract 3 * [w/3] from w, to get the remainder */
+ w -= t+t+t;
+
+ /* fixup the remainder as required since
+ * the optimization is not exact.
+ */
+ while (w >= 3u) {
+ t += 1u;
+ w -= 3u;
+ }
+ } else {
+ t = 0;
+ }
+ q.dp[ix] = (mp_digit)t;
+ }
+
+ /* [optional] store the remainder */
+ if (d != NULL) {
+ *d = (mp_digit)w;
+ }
+
+ /* [optional] store the quotient */
+ if (c != NULL) {
+ mp_clamp(&q);
+ mp_exch(&q, c);
+ }
+ mp_clear(&q);
+
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_div_3.c */
+
+/* Start: bn_mp_div_d.c */
+#include "tommath_private.h"
+#ifdef BN_MP_DIV_D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* single digit division (based on routine from MPI) */
+mp_err mp_div_d(const mp_int *a, mp_digit b, mp_int *c, mp_digit *d)
+{
+ mp_int q;
+ mp_word w;
+ mp_digit t;
+ mp_err err;
+ int ix;
+
+ /* cannot divide by zero */
+ if (b == 0u) {
+ return MP_VAL;
+ }
+
+ /* quick outs */
+ if ((b == 1u) || MP_IS_ZERO(a)) {
+ if (d != NULL) {
+ *d = 0;
+ }
+ if (c != NULL) {
+ return mp_copy(a, c);
+ }
+ return MP_OKAY;
+ }
+
+ /* power of two ? */
+ if ((b & (b - 1u)) == 0u) {
+ ix = 1;
+ while ((ix < MP_DIGIT_BIT) && (b != (((mp_digit)1)<<ix))) {
+ ix++;
+ }
+ if (d != NULL) {
+ *d = a->dp[0] & (((mp_digit)1<<(mp_digit)ix) - 1uL);
+ }
+ if (c != NULL) {
+ return mp_div_2d(a, ix, c, NULL);
+ }
+ return MP_OKAY;
+ }
+
+ /* three? */
+ if (MP_HAS(MP_DIV_3) && (b == 3u)) {
+ return mp_div_3(a, c, d);
+ }
+
+ /* no easy answer [c'est la vie]. Just division */
+ if ((err = mp_init_size(&q, a->used)) != MP_OKAY) {
+ return err;
+ }
+
+ q.used = a->used;
+ q.sign = a->sign;
+ w = 0;
+ for (ix = a->used - 1; ix >= 0; ix--) {
+ w = (w << (mp_word)MP_DIGIT_BIT) | (mp_word)a->dp[ix];
+
+ if (w >= b) {
+ t = (mp_digit)(w / b);
+ w -= (mp_word)t * (mp_word)b;
+ } else {
+ t = 0;
+ }
+ q.dp[ix] = t;
+ }
+
+ if (d != NULL) {
+ *d = (mp_digit)w;
+ }
+
+ if (c != NULL) {
+ mp_clamp(&q);
+ mp_exch(&q, c);
+ }
+ mp_clear(&q);
+
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_div_d.c */
+
+/* Start: bn_mp_dr_is_modulus.c */
+#include "tommath_private.h"
+#ifdef BN_MP_DR_IS_MODULUS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* determines if a number is a valid DR modulus */
+mp_bool mp_dr_is_modulus(const mp_int *a)
+{
+ int ix;
+
+ /* must be at least two digits */
+ if (a->used < 2) {
+ return MP_NO;
+ }
+
+ /* must be of the form b**k - a [a <= b] so all
+ * but the first digit must be equal to -1 (mod b).
+ */
+ for (ix = 1; ix < a->used; ix++) {
+ if (a->dp[ix] != MP_MASK) {
+ return MP_NO;
+ }
+ }
+ return MP_YES;
+}
+
+#endif
+
+/* End: bn_mp_dr_is_modulus.c */
+
+/* Start: bn_mp_dr_reduce.c */
+#include "tommath_private.h"
+#ifdef BN_MP_DR_REDUCE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* reduce "x" in place modulo "n" using the Diminished Radix algorithm.
+ *
+ * Based on algorithm from the paper
+ *
+ * "Generating Efficient Primes for Discrete Log Cryptosystems"
+ * Chae Hoon Lim, Pil Joong Lee,
+ * POSTECH Information Research Laboratories
+ *
+ * The modulus must be of a special format [see manual]
+ *
+ * Has been modified to use algorithm 7.10 from the LTM book instead
+ *
+ * Input x must be in the range 0 <= x <= (n-1)**2
+ */
+mp_err mp_dr_reduce(mp_int *x, const mp_int *n, mp_digit k)
+{
+ mp_err err;
+ int i, m;
+ mp_word r;
+ mp_digit mu, *tmpx1, *tmpx2;
+
+ /* m = digits in modulus */
+ m = n->used;
+
+ /* ensure that "x" has at least 2m digits */
+ if (x->alloc < (m + m)) {
+ if ((err = mp_grow(x, m + m)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* top of loop, this is where the code resumes if
+ * another reduction pass is required.
+ */
+top:
+ /* aliases for digits */
+ /* alias for lower half of x */
+ tmpx1 = x->dp;
+
+ /* alias for upper half of x, or x/B**m */
+ tmpx2 = x->dp + m;
+
+ /* set carry to zero */
+ mu = 0;
+
+ /* compute (x mod B**m) + k * [x/B**m] inline and inplace */
+ for (i = 0; i < m; i++) {
+ r = ((mp_word)*tmpx2++ * (mp_word)k) + *tmpx1 + mu;
+ *tmpx1++ = (mp_digit)(r & MP_MASK);
+ mu = (mp_digit)(r >> ((mp_word)MP_DIGIT_BIT));
+ }
+
+ /* set final carry */
+ *tmpx1++ = mu;
+
+ /* zero words above m */
+ MP_ZERO_DIGITS(tmpx1, (x->used - m) - 1);
+
+ /* clamp, sub and return */
+ mp_clamp(x);
+
+ /* if x >= n then subtract and reduce again
+ * Each successive "recursion" makes the input smaller and smaller.
+ */
+ if (mp_cmp_mag(x, n) != MP_LT) {
+ if ((err = s_mp_sub(x, n, x)) != MP_OKAY) {
+ return err;
+ }
+ goto top;
+ }
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_dr_reduce.c */
+
+/* Start: bn_mp_dr_setup.c */
+#include "tommath_private.h"
+#ifdef BN_MP_DR_SETUP_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* determines the setup value */
+void mp_dr_setup(const mp_int *a, mp_digit *d)
+{
+ /* the casts are required if MP_DIGIT_BIT is one less than
+ * the number of bits in a mp_digit [e.g. MP_DIGIT_BIT==31]
+ */
+ *d = (mp_digit)(((mp_word)1 << (mp_word)MP_DIGIT_BIT) - (mp_word)a->dp[0]);
+}
+
+#endif
+
+/* End: bn_mp_dr_setup.c */
+
+/* Start: bn_mp_error_to_string.c */
+#include "tommath_private.h"
+#ifdef BN_MP_ERROR_TO_STRING_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* return a char * string for a given code */
+const char *mp_error_to_string(mp_err code)
+{
+ switch (code) {
+ case MP_OKAY:
+ return "Successful";
+ case MP_ERR:
+ return "Unknown error";
+ case MP_MEM:
+ return "Out of heap";
+ case MP_VAL:
+ return "Value out of range";
+ case MP_ITER:
+ return "Max. iterations reached";
+ case MP_BUF:
+ return "Buffer overflow";
+ default:
+ return "Invalid error code";
+ }
+}
+
+#endif
+
+/* End: bn_mp_error_to_string.c */
+
+/* Start: bn_mp_exch.c */
+#include "tommath_private.h"
+#ifdef BN_MP_EXCH_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* swap the elements of two integers, for cases where you can't simply swap the
+ * mp_int pointers around
+ */
+void mp_exch(mp_int *a, mp_int *b)
+{
+ mp_int t;
+
+ t = *a;
+ *a = *b;
+ *b = t;
+}
+#endif
+
+/* End: bn_mp_exch.c */
+
+/* Start: bn_mp_expt_u32.c */
+#include "tommath_private.h"
+#ifdef BN_MP_EXPT_U32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* calculate c = a**b using a square-multiply algorithm */
+mp_err mp_expt_u32(const mp_int *a, uint32_t b, mp_int *c)
+{
+ mp_err err;
+
+ mp_int g;
+
+ if ((err = mp_init_copy(&g, a)) != MP_OKAY) {
+ return err;
+ }
+
+ /* set initial result */
+ mp_set(c, 1uL);
+
+ while (b > 0u) {
+ /* if the bit is set multiply */
+ if ((b & 1u) != 0u) {
+ if ((err = mp_mul(c, &g, c)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ }
+
+ /* square */
+ if (b > 1u) {
+ if ((err = mp_sqr(&g, &g)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ }
+
+ /* shift to next bit */
+ b >>= 1;
+ }
+
+ err = MP_OKAY;
+
+LBL_ERR:
+ mp_clear(&g);
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_expt_u32.c */
+
+/* Start: bn_mp_exptmod.c */
+#include "tommath_private.h"
+#ifdef BN_MP_EXPTMOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* this is a shell function that calls either the normal or Montgomery
+ * exptmod functions. Originally the call to the montgomery code was
+ * embedded in the normal function but that wasted alot of stack space
+ * for nothing (since 99% of the time the Montgomery code would be called)
+ */
+mp_err mp_exptmod(const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y)
+{
+ int dr;
+
+ /* modulus P must be positive */
+ if (P->sign == MP_NEG) {
+ return MP_VAL;
+ }
+
+ /* if exponent X is negative we have to recurse */
+ if (X->sign == MP_NEG) {
+ mp_int tmpG, tmpX;
+ mp_err err;
+
+ if (!MP_HAS(MP_INVMOD)) {
+ return MP_VAL;
+ }
+
+ if ((err = mp_init_multi(&tmpG, &tmpX, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* first compute 1/G mod P */
+ if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ /* now get |X| */
+ if ((err = mp_abs(X, &tmpX)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ /* and now compute (1/G)**|X| instead of G**X [X < 0] */
+ err = mp_exptmod(&tmpG, &tmpX, P, Y);
+LBL_ERR:
+ mp_clear_multi(&tmpG, &tmpX, NULL);
+ return err;
+ }
+
+ /* modified diminished radix reduction */
+ if (MP_HAS(MP_REDUCE_IS_2K_L) && MP_HAS(MP_REDUCE_2K_L) && MP_HAS(S_MP_EXPTMOD) &&
+ (mp_reduce_is_2k_l(P) == MP_YES)) {
+ return s_mp_exptmod(G, X, P, Y, 1);
+ }
+
+ /* is it a DR modulus? default to no */
+ dr = (MP_HAS(MP_DR_IS_MODULUS) && (mp_dr_is_modulus(P) == MP_YES)) ? 1 : 0;
+
+ /* if not, is it a unrestricted DR modulus? */
+ if (MP_HAS(MP_REDUCE_IS_2K) && (dr == 0)) {
+ dr = (mp_reduce_is_2k(P) == MP_YES) ? 2 : 0;
+ }
+
+ /* if the modulus is odd or dr != 0 use the montgomery method */
+ if (MP_HAS(S_MP_EXPTMOD_FAST) && (MP_IS_ODD(P) || (dr != 0))) {
+ return s_mp_exptmod_fast(G, X, P, Y, dr);
+ } else if (MP_HAS(S_MP_EXPTMOD)) {
+ /* otherwise use the generic Barrett reduction technique */
+ return s_mp_exptmod(G, X, P, Y, 0);
+ } else {
+ /* no exptmod for evens */
+ return MP_VAL;
+ }
+}
+
+#endif
+
+/* End: bn_mp_exptmod.c */
+
+/* Start: bn_mp_exteuclid.c */
+#include "tommath_private.h"
+#ifdef BN_MP_EXTEUCLID_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Extended euclidean algorithm of (a, b) produces
+ a*u1 + b*u2 = u3
+ */
+mp_err mp_exteuclid(const mp_int *a, const mp_int *b, mp_int *U1, mp_int *U2, mp_int *U3)
+{
+ mp_int u1, u2, u3, v1, v2, v3, t1, t2, t3, q, tmp;
+ mp_err err;
+
+ if ((err = mp_init_multi(&u1, &u2, &u3, &v1, &v2, &v3, &t1, &t2, &t3, &q, &tmp, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* initialize, (u1,u2,u3) = (1,0,a) */
+ mp_set(&u1, 1uL);
+ if ((err = mp_copy(a, &u3)) != MP_OKAY) goto LBL_ERR;
+
+ /* initialize, (v1,v2,v3) = (0,1,b) */
+ mp_set(&v2, 1uL);
+ if ((err = mp_copy(b, &v3)) != MP_OKAY) goto LBL_ERR;
+
+ /* loop while v3 != 0 */
+ while (!MP_IS_ZERO(&v3)) {
+ /* q = u3/v3 */
+ if ((err = mp_div(&u3, &v3, &q, NULL)) != MP_OKAY) goto LBL_ERR;
+
+ /* (t1,t2,t3) = (u1,u2,u3) - (v1,v2,v3)q */
+ if ((err = mp_mul(&v1, &q, &tmp)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_sub(&u1, &tmp, &t1)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_mul(&v2, &q, &tmp)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_sub(&u2, &tmp, &t2)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_mul(&v3, &q, &tmp)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_sub(&u3, &tmp, &t3)) != MP_OKAY) goto LBL_ERR;
+
+ /* (u1,u2,u3) = (v1,v2,v3) */
+ if ((err = mp_copy(&v1, &u1)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_copy(&v2, &u2)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_copy(&v3, &u3)) != MP_OKAY) goto LBL_ERR;
+
+ /* (v1,v2,v3) = (t1,t2,t3) */
+ if ((err = mp_copy(&t1, &v1)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_copy(&t2, &v2)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_copy(&t3, &v3)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* make sure U3 >= 0 */
+ if (u3.sign == MP_NEG) {
+ if ((err = mp_neg(&u1, &u1)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_neg(&u2, &u2)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_neg(&u3, &u3)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* copy result out */
+ if (U1 != NULL) {
+ mp_exch(U1, &u1);
+ }
+ if (U2 != NULL) {
+ mp_exch(U2, &u2);
+ }
+ if (U3 != NULL) {
+ mp_exch(U3, &u3);
+ }
+
+ err = MP_OKAY;
+LBL_ERR:
+ mp_clear_multi(&u1, &u2, &u3, &v1, &v2, &v3, &t1, &t2, &t3, &q, &tmp, NULL);
+ return err;
+}
+#endif
+
+/* End: bn_mp_exteuclid.c */
+
+/* Start: bn_mp_fread.c */
+#include "tommath_private.h"
+#ifdef BN_MP_FREAD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#ifndef MP_NO_FILE
+/* read a bigint from a file stream in ASCII */
+mp_err mp_fread(mp_int *a, int radix, FILE *stream)
+{
+ mp_err err;
+ mp_sign neg;
+
+ /* if first digit is - then set negative */
+ int ch = fgetc(stream);
+ if (ch == (int)'-') {
+ neg = MP_NEG;
+ ch = fgetc(stream);
+ } else {
+ neg = MP_ZPOS;
+ }
+
+ /* no digits, return error */
+ if (ch == EOF) {
+ return MP_ERR;
+ }
+
+ /* clear a */
+ mp_zero(a);
+
+ do {
+ int y;
+ unsigned pos = (unsigned)(ch - (int)'(');
+ if (mp_s_rmap_reverse_sz < pos) {
+ break;
+ }
+
+ y = (int)mp_s_rmap_reverse[pos];
+
+ if ((y == 0xff) || (y >= radix)) {
+ break;
+ }
+
+ /* shift up and add */
+ if ((err = mp_mul_d(a, (mp_digit)radix, a)) != MP_OKAY) {
+ return err;
+ }
+ if ((err = mp_add_d(a, (mp_digit)y, a)) != MP_OKAY) {
+ return err;
+ }
+ } while ((ch = fgetc(stream)) != EOF);
+
+ if (a->used != 0) {
+ a->sign = neg;
+ }
+
+ return MP_OKAY;
+}
+#endif
+
+#endif
+
+/* End: bn_mp_fread.c */
+
+/* Start: bn_mp_from_sbin.c */
+#include "tommath_private.h"
+#ifdef BN_MP_FROM_SBIN_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* read signed bin, big endian, first byte is 0==positive or 1==negative */
+mp_err mp_from_sbin(mp_int *a, const unsigned char *buf, size_t size)
+{
+ mp_err err;
+
+ /* read magnitude */
+ if ((err = mp_from_ubin(a, buf + 1, size - 1u)) != MP_OKAY) {
+ return err;
+ }
+
+ /* first byte is 0 for positive, non-zero for negative */
+ if (buf[0] == (unsigned char)0) {
+ a->sign = MP_ZPOS;
+ } else {
+ a->sign = MP_NEG;
+ }
+
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_from_sbin.c */
+
+/* Start: bn_mp_from_ubin.c */
+#include "tommath_private.h"
+#ifdef BN_MP_FROM_UBIN_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* reads a unsigned char array, assumes the msb is stored first [big endian] */
+mp_err mp_from_ubin(mp_int *a, const unsigned char *buf, size_t size)
+{
+ mp_err err;
+
+ /* make sure there are at least two digits */
+ if (a->alloc < 2) {
+ if ((err = mp_grow(a, 2)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* zero the int */
+ mp_zero(a);
+
+ /* read the bytes in */
+ while (size-- > 0u) {
+ if ((err = mp_mul_2d(a, 8, a)) != MP_OKAY) {
+ return err;
+ }
+
+#ifndef MP_8BIT
+ a->dp[0] |= *buf++;
+ a->used += 1;
+#else
+ a->dp[0] = (*buf & MP_MASK);
+ a->dp[1] |= ((*buf++ >> 7) & 1u);
+ a->used += 2;
+#endif
+ }
+ mp_clamp(a);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_from_ubin.c */
+
+/* Start: bn_mp_fwrite.c */
+#include "tommath_private.h"
+#ifdef BN_MP_FWRITE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#ifndef MP_NO_FILE
+mp_err mp_fwrite(const mp_int *a, int radix, FILE *stream)
+{
+ char *buf;
+ mp_err err;
+ int len;
+ size_t written;
+
+ /* TODO: this function is not in this PR */
+ if (MP_HAS(MP_RADIX_SIZE_OVERESTIMATE)) {
+ /* if ((err = mp_radix_size_overestimate(&t, base, &len)) != MP_OKAY) goto LBL_ERR; */
+ } else {
+ if ((err = mp_radix_size(a, radix, &len)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ buf = (char *) MP_MALLOC((size_t)len);
+ if (buf == NULL) {
+ return MP_MEM;
+ }
+
+ if ((err = mp_to_radix(a, buf, (size_t)len, &written, radix)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ if (fwrite(buf, written, 1uL, stream) != 1uL) {
+ err = MP_ERR;
+ goto LBL_ERR;
+ }
+ err = MP_OKAY;
+
+
+LBL_ERR:
+ MP_FREE_BUFFER(buf, (size_t)len);
+ return err;
+}
+#endif
+
+#endif
+
+/* End: bn_mp_fwrite.c */
+
+/* Start: bn_mp_gcd.c */
+#include "tommath_private.h"
+#ifdef BN_MP_GCD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Greatest Common Divisor using the binary method */
+mp_err mp_gcd(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_int u, v;
+ int k, u_lsb, v_lsb;
+ mp_err err;
+
+ /* either zero than gcd is the largest */
+ if (MP_IS_ZERO(a)) {
+ return mp_abs(b, c);
+ }
+ if (MP_IS_ZERO(b)) {
+ return mp_abs(a, c);
+ }
+
+ /* get copies of a and b we can modify */
+ if ((err = mp_init_copy(&u, a)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_init_copy(&v, b)) != MP_OKAY) {
+ goto LBL_U;
+ }
+
+ /* must be positive for the remainder of the algorithm */
+ u.sign = v.sign = MP_ZPOS;
+
+ /* B1. Find the common power of two for u and v */
+ u_lsb = mp_cnt_lsb(&u);
+ v_lsb = mp_cnt_lsb(&v);
+ k = MP_MIN(u_lsb, v_lsb);
+
+ if (k > 0) {
+ /* divide the power of two out */
+ if ((err = mp_div_2d(&u, k, &u, NULL)) != MP_OKAY) {
+ goto LBL_V;
+ }
+
+ if ((err = mp_div_2d(&v, k, &v, NULL)) != MP_OKAY) {
+ goto LBL_V;
+ }
+ }
+
+ /* divide any remaining factors of two out */
+ if (u_lsb != k) {
+ if ((err = mp_div_2d(&u, u_lsb - k, &u, NULL)) != MP_OKAY) {
+ goto LBL_V;
+ }
+ }
+
+ if (v_lsb != k) {
+ if ((err = mp_div_2d(&v, v_lsb - k, &v, NULL)) != MP_OKAY) {
+ goto LBL_V;
+ }
+ }
+
+ while (!MP_IS_ZERO(&v)) {
+ /* make sure v is the largest */
+ if (mp_cmp_mag(&u, &v) == MP_GT) {
+ /* swap u and v to make sure v is >= u */
+ mp_exch(&u, &v);
+ }
+
+ /* subtract smallest from largest */
+ if ((err = s_mp_sub(&v, &u, &v)) != MP_OKAY) {
+ goto LBL_V;
+ }
+
+ /* Divide out all factors of two */
+ if ((err = mp_div_2d(&v, mp_cnt_lsb(&v), &v, NULL)) != MP_OKAY) {
+ goto LBL_V;
+ }
+ }
+
+ /* multiply by 2**k which we divided out at the beginning */
+ if ((err = mp_mul_2d(&u, k, c)) != MP_OKAY) {
+ goto LBL_V;
+ }
+ c->sign = MP_ZPOS;
+ err = MP_OKAY;
+LBL_V:
+ mp_clear(&u);
+LBL_U:
+ mp_clear(&v);
+ return err;
+}
+#endif
+
+/* End: bn_mp_gcd.c */
+
+/* Start: bn_mp_get_double.c */
+#include "tommath_private.h"
+#ifdef BN_MP_GET_DOUBLE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+double mp_get_double(const mp_int *a)
+{
+ int i;
+ double d = 0.0, fac = 1.0;
+ for (i = 0; i < MP_DIGIT_BIT; ++i) {
+ fac *= 2.0;
+ }
+ for (i = a->used; i --> 0;) {
+ d = (d * fac) + (double)a->dp[i];
+ }
+ return (a->sign == MP_NEG) ? -d : d;
+}
+#endif
+
+/* End: bn_mp_get_double.c */
+
+/* Start: bn_mp_get_i32.c */
+#include "tommath_private.h"
+#ifdef BN_MP_GET_I32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_SIGNED(mp_get_i32, mp_get_mag_u32, int32_t, uint32_t)
+#endif
+
+/* End: bn_mp_get_i32.c */
+
+/* Start: bn_mp_get_i64.c */
+#include "tommath_private.h"
+#ifdef BN_MP_GET_I64_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_SIGNED(mp_get_i64, mp_get_mag_u64, int64_t, uint64_t)
+#endif
+
+/* End: bn_mp_get_i64.c */
+
+/* Start: bn_mp_get_l.c */
+#include "tommath_private.h"
+#ifdef BN_MP_GET_L_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_SIGNED(mp_get_l, mp_get_mag_ul, long, unsigned long)
+#endif
+
+/* End: bn_mp_get_l.c */
+
+/* Start: bn_mp_get_ll.c */
+#include "tommath_private.h"
+#ifdef BN_MP_GET_LL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_SIGNED(mp_get_ll, mp_get_mag_ull, long long, unsigned long long)
+#endif
+
+/* End: bn_mp_get_ll.c */
+
+/* Start: bn_mp_get_mag_u32.c */
+#include "tommath_private.h"
+#ifdef BN_MP_GET_MAG_U32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_MAG(mp_get_mag_u32, uint32_t)
+#endif
+
+/* End: bn_mp_get_mag_u32.c */
+
+/* Start: bn_mp_get_mag_u64.c */
+#include "tommath_private.h"
+#ifdef BN_MP_GET_MAG_U64_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_MAG(mp_get_mag_u64, uint64_t)
+#endif
+
+/* End: bn_mp_get_mag_u64.c */
+
+/* Start: bn_mp_get_mag_ul.c */
+#include "tommath_private.h"
+#ifdef BN_MP_GET_MAG_UL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_MAG(mp_get_mag_ul, unsigned long)
+#endif
+
+/* End: bn_mp_get_mag_ul.c */
+
+/* Start: bn_mp_get_mag_ull.c */
+#include "tommath_private.h"
+#ifdef BN_MP_GET_MAG_ULL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_GET_MAG(mp_get_mag_ull, unsigned long long)
+#endif
+
+/* End: bn_mp_get_mag_ull.c */
+
+/* Start: bn_mp_grow.c */
+#include "tommath_private.h"
+#ifdef BN_MP_GROW_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* grow as required */
+mp_err mp_grow(mp_int *a, int size)
+{
+ int i;
+ mp_digit *tmp;
+
+ /* if the alloc size is smaller alloc more ram */
+ if (a->alloc < size) {
+ /* reallocate the array a->dp
+ *
+ * We store the return in a temporary variable
+ * in case the operation failed we don't want
+ * to overwrite the dp member of a.
+ */
+ tmp = (mp_digit *) MP_REALLOC(a->dp,
+ (size_t)a->alloc * sizeof(mp_digit),
+ (size_t)size * sizeof(mp_digit));
+ if (tmp == NULL) {
+ /* reallocation failed but "a" is still valid [can be freed] */
+ return MP_MEM;
+ }
+
+ /* reallocation succeeded so set a->dp */
+ a->dp = tmp;
+
+ /* zero excess digits */
+ i = a->alloc;
+ a->alloc = size;
+ MP_ZERO_DIGITS(a->dp + i, a->alloc - i);
+ }
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_grow.c */
+
+/* Start: bn_mp_incr.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INCR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Increment "a" by one like "a++". Changes input! */
+mp_err mp_incr(mp_int *a)
+{
+ if (MP_IS_ZERO(a)) {
+ mp_set(a,1uL);
+ return MP_OKAY;
+ } else if (a->sign == MP_NEG) {
+ mp_err err;
+ a->sign = MP_ZPOS;
+ if ((err = mp_decr(a)) != MP_OKAY) {
+ return err;
+ }
+ /* There is no -0 in LTM */
+ if (!MP_IS_ZERO(a)) {
+ a->sign = MP_NEG;
+ }
+ return MP_OKAY;
+ } else if (a->dp[0] < MP_DIGIT_MAX) {
+ a->dp[0]++;
+ return MP_OKAY;
+ } else {
+ return mp_add_d(a, 1uL,a);
+ }
+}
+#endif
+
+/* End: bn_mp_incr.c */
+
+/* Start: bn_mp_init.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* init a new mp_int */
+mp_err mp_init(mp_int *a)
+{
+ /* allocate memory required and clear it */
+ a->dp = (mp_digit *) MP_CALLOC((size_t)MP_PREC, sizeof(mp_digit));
+ if (a->dp == NULL) {
+ return MP_MEM;
+ }
+
+ /* set the used to zero, allocated digits to the default precision
+ * and sign to positive */
+ a->used = 0;
+ a->alloc = MP_PREC;
+ a->sign = MP_ZPOS;
+
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_init.c */
+
+/* Start: bn_mp_init_copy.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_COPY_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* creates "a" then copies b into it */
+mp_err mp_init_copy(mp_int *a, const mp_int *b)
+{
+ mp_err err;
+
+ if ((err = mp_init_size(a, b->used)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_copy(b, a)) != MP_OKAY) {
+ mp_clear(a);
+ }
+
+ return err;
+}
+#endif
+
+/* End: bn_mp_init_copy.c */
+
+/* Start: bn_mp_init_i32.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_I32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_i32, mp_set_i32, int32_t)
+#endif
+
+/* End: bn_mp_init_i32.c */
+
+/* Start: bn_mp_init_i64.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_I64_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_i64, mp_set_i64, int64_t)
+#endif
+
+/* End: bn_mp_init_i64.c */
+
+/* Start: bn_mp_init_l.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_L_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_l, mp_set_l, long)
+#endif
+
+/* End: bn_mp_init_l.c */
+
+/* Start: bn_mp_init_ll.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_LL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_ll, mp_set_ll, long long)
+#endif
+
+/* End: bn_mp_init_ll.c */
+
+/* Start: bn_mp_init_multi.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_MULTI_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#include <stdarg.h>
+
+mp_err mp_init_multi(mp_int *mp, ...)
+{
+ mp_err err = MP_OKAY; /* Assume ok until proven otherwise */
+ int n = 0; /* Number of ok inits */
+ mp_int *cur_arg = mp;
+ va_list args;
+
+ va_start(args, mp); /* init args to next argument from caller */
+ while (cur_arg != NULL) {
+ if (mp_init(cur_arg) != MP_OKAY) {
+ /* Oops - error! Back-track and mp_clear what we already
+ succeeded in init-ing, then return error.
+ */
+ va_list clean_args;
+
+ /* now start cleaning up */
+ cur_arg = mp;
+ va_start(clean_args, mp);
+ while (n-- != 0) {
+ mp_clear(cur_arg);
+ cur_arg = va_arg(clean_args, mp_int *);
+ }
+ va_end(clean_args);
+ err = MP_MEM;
+ break;
+ }
+ n++;
+ cur_arg = va_arg(args, mp_int *);
+ }
+ va_end(args);
+ return err; /* Assumed ok, if error flagged above. */
+}
+
+#endif
+
+/* End: bn_mp_init_multi.c */
+
+/* Start: bn_mp_init_set.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_SET_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* initialize and set a digit */
+mp_err mp_init_set(mp_int *a, mp_digit b)
+{
+ mp_err err;
+ if ((err = mp_init(a)) != MP_OKAY) {
+ return err;
+ }
+ mp_set(a, b);
+ return err;
+}
+#endif
+
+/* End: bn_mp_init_set.c */
+
+/* Start: bn_mp_init_size.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_SIZE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* init an mp_init for a given size */
+mp_err mp_init_size(mp_int *a, int size)
+{
+ size = MP_MAX(MP_MIN_PREC, size);
+
+ /* alloc mem */
+ a->dp = (mp_digit *) MP_CALLOC((size_t)size, sizeof(mp_digit));
+ if (a->dp == NULL) {
+ return MP_MEM;
+ }
+
+ /* set the members */
+ a->used = 0;
+ a->alloc = size;
+ a->sign = MP_ZPOS;
+
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_init_size.c */
+
+/* Start: bn_mp_init_u32.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_U32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_u32, mp_set_u32, uint32_t)
+#endif
+
+/* End: bn_mp_init_u32.c */
+
+/* Start: bn_mp_init_u64.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_U64_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_u64, mp_set_u64, uint64_t)
+#endif
+
+/* End: bn_mp_init_u64.c */
+
+/* Start: bn_mp_init_ul.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_UL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_ul, mp_set_ul, unsigned long)
+#endif
+
+/* End: bn_mp_init_ul.c */
+
+/* Start: bn_mp_init_ull.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INIT_ULL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_INIT_INT(mp_init_ull, mp_set_ull, unsigned long long)
+#endif
+
+/* End: bn_mp_init_ull.c */
+
+/* Start: bn_mp_invmod.c */
+#include "tommath_private.h"
+#ifdef BN_MP_INVMOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* hac 14.61, pp608 */
+mp_err mp_invmod(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ /* b cannot be negative and has to be >1 */
+ if ((b->sign == MP_NEG) || (mp_cmp_d(b, 1uL) != MP_GT)) {
+ return MP_VAL;
+ }
+
+ /* if the modulus is odd we can use a faster routine instead */
+ if (MP_HAS(S_MP_INVMOD_FAST) && MP_IS_ODD(b)) {
+ return s_mp_invmod_fast(a, b, c);
+ }
+
+ return MP_HAS(S_MP_INVMOD_SLOW)
+ ? s_mp_invmod_slow(a, b, c)
+ : MP_VAL;
+}
+#endif
+
+/* End: bn_mp_invmod.c */
+
+/* Start: bn_mp_is_square.c */
+#include "tommath_private.h"
+#ifdef BN_MP_IS_SQUARE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Check if remainders are possible squares - fast exclude non-squares */
+static const char rem_128[128] = {
+ 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
+ 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
+ 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
+ 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
+ 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
+ 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
+ 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
+ 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1
+};
+
+static const char rem_105[105] = {
+ 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,
+ 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1,
+ 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1,
+ 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
+ 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1,
+ 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1,
+ 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1
+};
+
+/* Store non-zero to ret if arg is square, and zero if not */
+mp_err mp_is_square(const mp_int *arg, mp_bool *ret)
+{
+ mp_err err;
+ mp_digit c;
+ mp_int t;
+ unsigned long r;
+
+ /* Default to Non-square :) */
+ *ret = MP_NO;
+
+ if (arg->sign == MP_NEG) {
+ return MP_VAL;
+ }
+
+ if (MP_IS_ZERO(arg)) {
+ return MP_OKAY;
+ }
+
+ /* First check mod 128 (suppose that MP_DIGIT_BIT is at least 7) */
+ if (rem_128[127u & arg->dp[0]] == (char)1) {
+ return MP_OKAY;
+ }
+
+ /* Next check mod 105 (3*5*7) */
+ if ((err = mp_mod_d(arg, 105uL, &c)) != MP_OKAY) {
+ return err;
+ }
+ if (rem_105[c] == (char)1) {
+ return MP_OKAY;
+ }
+
+
+ if ((err = mp_init_u32(&t, 11u*13u*17u*19u*23u*29u*31u)) != MP_OKAY) {
+ return err;
+ }
+ if ((err = mp_mod(arg, &t, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ r = mp_get_u32(&t);
+ /* Check for other prime modules, note it's not an ERROR but we must
+ * free "t" so the easiest way is to goto LBL_ERR. We know that err
+ * is already equal to MP_OKAY from the mp_mod call
+ */
+ if (((1uL<<(r%11uL)) & 0x5C4uL) != 0uL) goto LBL_ERR;
+ if (((1uL<<(r%13uL)) & 0x9E4uL) != 0uL) goto LBL_ERR;
+ if (((1uL<<(r%17uL)) & 0x5CE8uL) != 0uL) goto LBL_ERR;
+ if (((1uL<<(r%19uL)) & 0x4F50CuL) != 0uL) goto LBL_ERR;
+ if (((1uL<<(r%23uL)) & 0x7ACCA0uL) != 0uL) goto LBL_ERR;
+ if (((1uL<<(r%29uL)) & 0xC2EDD0CuL) != 0uL) goto LBL_ERR;
+ if (((1uL<<(r%31uL)) & 0x6DE2B848uL) != 0uL) goto LBL_ERR;
+
+ /* Final check - is sqr(sqrt(arg)) == arg ? */
+ if ((err = mp_sqrt(arg, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if ((err = mp_sqr(&t, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ *ret = (mp_cmp_mag(&t, arg) == MP_EQ) ? MP_YES : MP_NO;
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+#endif
+
+/* End: bn_mp_is_square.c */
+
+/* Start: bn_mp_iseven.c */
+#include "tommath_private.h"
+#ifdef BN_MP_ISEVEN_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+mp_bool mp_iseven(const mp_int *a)
+{
+ return MP_IS_EVEN(a) ? MP_YES : MP_NO;
+}
+#endif
+
+/* End: bn_mp_iseven.c */
+
+/* Start: bn_mp_isodd.c */
+#include "tommath_private.h"
+#ifdef BN_MP_ISODD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+mp_bool mp_isodd(const mp_int *a)
+{
+ return MP_IS_ODD(a) ? MP_YES : MP_NO;
+}
+#endif
+
+/* End: bn_mp_isodd.c */
+
+/* Start: bn_mp_kronecker.c */
+#include "tommath_private.h"
+#ifdef BN_MP_KRONECKER_C
+
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/*
+ Kronecker symbol (a|p)
+ Straightforward implementation of algorithm 1.4.10 in
+ Henri Cohen: "A Course in Computational Algebraic Number Theory"
+
+ @book{cohen2013course,
+ title={A course in computational algebraic number theory},
+ author={Cohen, Henri},
+ volume={138},
+ year={2013},
+ publisher={Springer Science \& Business Media}
+ }
+ */
+mp_err mp_kronecker(const mp_int *a, const mp_int *p, int *c)
+{
+ mp_int a1, p1, r;
+ mp_err err;
+ int v, k;
+
+ static const int table[8] = {0, 1, 0, -1, 0, -1, 0, 1};
+
+ if (MP_IS_ZERO(p)) {
+ if ((a->used == 1) && (a->dp[0] == 1u)) {
+ *c = 1;
+ } else {
+ *c = 0;
+ }
+ return MP_OKAY;
+ }
+
+ if (MP_IS_EVEN(a) && MP_IS_EVEN(p)) {
+ *c = 0;
+ return MP_OKAY;
+ }
+
+ if ((err = mp_init_copy(&a1, a)) != MP_OKAY) {
+ return err;
+ }
+ if ((err = mp_init_copy(&p1, p)) != MP_OKAY) {
+ goto LBL_KRON_0;
+ }
+
+ v = mp_cnt_lsb(&p1);
+ if ((err = mp_div_2d(&p1, v, &p1, NULL)) != MP_OKAY) {
+ goto LBL_KRON_1;
+ }
+
+ if ((v & 1) == 0) {
+ k = 1;
+ } else {
+ k = table[a->dp[0] & 7u];
+ }
+
+ if (p1.sign == MP_NEG) {
+ p1.sign = MP_ZPOS;
+ if (a1.sign == MP_NEG) {
+ k = -k;
+ }
+ }
+
+ if ((err = mp_init(&r)) != MP_OKAY) {
+ goto LBL_KRON_1;
+ }
+
+ for (;;) {
+ if (MP_IS_ZERO(&a1)) {
+ if (mp_cmp_d(&p1, 1uL) == MP_EQ) {
+ *c = k;
+ goto LBL_KRON;
+ } else {
+ *c = 0;
+ goto LBL_KRON;
+ }
+ }
+
+ v = mp_cnt_lsb(&a1);
+ if ((err = mp_div_2d(&a1, v, &a1, NULL)) != MP_OKAY) {
+ goto LBL_KRON;
+ }
+
+ if ((v & 1) == 1) {
+ k = k * table[p1.dp[0] & 7u];
+ }
+
+ if (a1.sign == MP_NEG) {
+ /*
+ * Compute k = (-1)^((a1)*(p1-1)/4) * k
+ * a1.dp[0] + 1 cannot overflow because the MSB
+ * of the type mp_digit is not set by definition
+ */
+ if (((a1.dp[0] + 1u) & p1.dp[0] & 2u) != 0u) {
+ k = -k;
+ }
+ } else {
+ /* compute k = (-1)^((a1-1)*(p1-1)/4) * k */
+ if ((a1.dp[0] & p1.dp[0] & 2u) != 0u) {
+ k = -k;
+ }
+ }
+
+ if ((err = mp_copy(&a1, &r)) != MP_OKAY) {
+ goto LBL_KRON;
+ }
+ r.sign = MP_ZPOS;
+ if ((err = mp_mod(&p1, &r, &a1)) != MP_OKAY) {
+ goto LBL_KRON;
+ }
+ if ((err = mp_copy(&r, &p1)) != MP_OKAY) {
+ goto LBL_KRON;
+ }
+ }
+
+LBL_KRON:
+ mp_clear(&r);
+LBL_KRON_1:
+ mp_clear(&p1);
+LBL_KRON_0:
+ mp_clear(&a1);
+
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_kronecker.c */
+
+/* Start: bn_mp_lcm.c */
+#include "tommath_private.h"
+#ifdef BN_MP_LCM_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* computes least common multiple as |a*b|/(a, b) */
+mp_err mp_lcm(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_err err;
+ mp_int t1, t2;
+
+
+ if ((err = mp_init_multi(&t1, &t2, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* t1 = get the GCD of the two inputs */
+ if ((err = mp_gcd(a, b, &t1)) != MP_OKAY) {
+ goto LBL_T;
+ }
+
+ /* divide the smallest by the GCD */
+ if (mp_cmp_mag(a, b) == MP_LT) {
+ /* store quotient in t2 such that t2 * b is the LCM */
+ if ((err = mp_div(a, &t1, &t2, NULL)) != MP_OKAY) {
+ goto LBL_T;
+ }
+ err = mp_mul(b, &t2, c);
+ } else {
+ /* store quotient in t2 such that t2 * a is the LCM */
+ if ((err = mp_div(b, &t1, &t2, NULL)) != MP_OKAY) {
+ goto LBL_T;
+ }
+ err = mp_mul(a, &t2, c);
+ }
+
+ /* fix the sign to positive */
+ c->sign = MP_ZPOS;
+
+LBL_T:
+ mp_clear_multi(&t1, &t2, NULL);
+ return err;
+}
+#endif
+
+/* End: bn_mp_lcm.c */
+
+/* Start: bn_mp_log_u32.c */
+#include "tommath_private.h"
+#ifdef BN_MP_LOG_U32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Compute log_{base}(a) */
+static mp_word s_pow(mp_word base, mp_word exponent)
+{
+ mp_word result = 1uLL;
+ while (exponent != 0u) {
+ if ((exponent & 1u) == 1u) {
+ result *= base;
+ }
+ exponent >>= 1;
+ base *= base;
+ }
+
+ return result;
+}
+
+static mp_digit s_digit_ilogb(mp_digit base, mp_digit n)
+{
+ mp_word bracket_low = 1uLL, bracket_mid, bracket_high, N;
+ mp_digit ret, high = 1uL, low = 0uL, mid;
+
+ if (n < base) {
+ return 0uL;
+ }
+ if (n == base) {
+ return 1uL;
+ }
+
+ bracket_high = (mp_word) base ;
+ N = (mp_word) n;
+
+ while (bracket_high < N) {
+ low = high;
+ bracket_low = bracket_high;
+ high <<= 1;
+ bracket_high *= bracket_high;
+ }
+
+ while (((mp_digit)(high - low)) > 1uL) {
+ mid = (low + high) >> 1;
+ bracket_mid = bracket_low * s_pow(base, (mp_word)(mid - low));
+
+ if (N < bracket_mid) {
+ high = mid ;
+ bracket_high = bracket_mid ;
+ }
+ if (N > bracket_mid) {
+ low = mid ;
+ bracket_low = bracket_mid ;
+ }
+ if (N == bracket_mid) {
+ return (mp_digit) mid;
+ }
+ }
+
+ if (bracket_high == N) {
+ ret = high;
+ } else {
+ ret = low;
+ }
+
+ return ret;
+}
+
+/* TODO: output could be "int" because the output of mp_radix_size is int, too,
+ as is the output of mp_bitcount.
+ With the same problem: max size is INT_MAX * MP_DIGIT not INT_MAX only!
+*/
+mp_err mp_log_u32(const mp_int *a, uint32_t base, uint32_t *c)
+{
+ mp_err err;
+ mp_ord cmp;
+ uint32_t high, low, mid;
+ mp_int bracket_low, bracket_high, bracket_mid, t, bi_base;
+
+ err = MP_OKAY;
+
+ if (a->sign == MP_NEG) {
+ return MP_VAL;
+ }
+
+ if (MP_IS_ZERO(a)) {
+ return MP_VAL;
+ }
+
+ if (base < 2u) {
+ return MP_VAL;
+ }
+
+ /* A small shortcut for bases that are powers of two. */
+ if ((base & (base - 1u)) == 0u) {
+ int y, bit_count;
+ for (y=0; (y < 7) && ((base & 1u) == 0u); y++) {
+ base >>= 1;
+ }
+ bit_count = mp_count_bits(a) - 1;
+ *c = (uint32_t)(bit_count/y);
+ return MP_OKAY;
+ }
+
+ if (a->used == 1) {
+ *c = (uint32_t)s_digit_ilogb(base, a->dp[0]);
+ return err;
+ }
+
+ cmp = mp_cmp_d(a, base);
+ if ((cmp == MP_LT) || (cmp == MP_EQ)) {
+ *c = cmp == MP_EQ;
+ return err;
+ }
+
+ if ((err =
+ mp_init_multi(&bracket_low, &bracket_high,
+ &bracket_mid, &t, &bi_base, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ low = 0u;
+ mp_set(&bracket_low, 1uL);
+ high = 1u;
+
+ mp_set(&bracket_high, base);
+
+ /*
+ A kind of Giant-step/baby-step algorithm.
+ Idea shamelessly stolen from https://programmingpraxis.com/2010/05/07/integer-logarithms/2/
+ The effect is asymptotic, hence needs benchmarks to test if the Giant-step should be skipped
+ for small n.
+ */
+ while (mp_cmp(&bracket_high, a) == MP_LT) {
+ low = high;
+ if ((err = mp_copy(&bracket_high, &bracket_low)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ high <<= 1;
+ if ((err = mp_sqr(&bracket_high, &bracket_high)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ }
+ mp_set(&bi_base, base);
+
+ while ((high - low) > 1u) {
+ mid = (high + low) >> 1;
+
+ if ((err = mp_expt_u32(&bi_base, (uint32_t)(mid - low), &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if ((err = mp_mul(&bracket_low, &t, &bracket_mid)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ cmp = mp_cmp(a, &bracket_mid);
+ if (cmp == MP_LT) {
+ high = mid;
+ mp_exch(&bracket_mid, &bracket_high);
+ }
+ if (cmp == MP_GT) {
+ low = mid;
+ mp_exch(&bracket_mid, &bracket_low);
+ }
+ if (cmp == MP_EQ) {
+ *c = mid;
+ goto LBL_END;
+ }
+ }
+
+ *c = (mp_cmp(&bracket_high, a) == MP_EQ) ? high : low;
+
+LBL_END:
+LBL_ERR:
+ mp_clear_multi(&bracket_low, &bracket_high, &bracket_mid,
+ &t, &bi_base, NULL);
+ return err;
+}
+
+
+#endif
+
+/* End: bn_mp_log_u32.c */
+
+/* Start: bn_mp_lshd.c */
+#include "tommath_private.h"
+#ifdef BN_MP_LSHD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* shift left a certain amount of digits */
+mp_err mp_lshd(mp_int *a, int b)
+{
+ int x;
+ mp_err err;
+ mp_digit *top, *bottom;
+
+ /* if its less than zero return */
+ if (b <= 0) {
+ return MP_OKAY;
+ }
+ /* no need to shift 0 around */
+ if (MP_IS_ZERO(a)) {
+ return MP_OKAY;
+ }
+
+ /* grow to fit the new digits */
+ if (a->alloc < (a->used + b)) {
+ if ((err = mp_grow(a, a->used + b)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* increment the used by the shift amount then copy upwards */
+ a->used += b;
+
+ /* top */
+ top = a->dp + a->used - 1;
+
+ /* base */
+ bottom = (a->dp + a->used - 1) - b;
+
+ /* much like mp_rshd this is implemented using a sliding window
+ * except the window goes the otherway around. Copying from
+ * the bottom to the top. see bn_mp_rshd.c for more info.
+ */
+ for (x = a->used - 1; x >= b; x--) {
+ *top-- = *bottom--;
+ }
+
+ /* zero the lower digits */
+ MP_ZERO_DIGITS(a->dp, b);
+
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_lshd.c */
+
+/* Start: bn_mp_mod.c */
+#include "tommath_private.h"
+#ifdef BN_MP_MOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* c = a mod b, 0 <= c < b if b > 0, b < c <= 0 if b < 0 */
+mp_err mp_mod(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_int t;
+ mp_err err;
+
+ if ((err = mp_init_size(&t, b->used)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_div(a, b, NULL, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ if (MP_IS_ZERO(&t) || (t.sign == b->sign)) {
+ err = MP_OKAY;
+ mp_exch(&t, c);
+ } else {
+ err = mp_add(b, &t, c);
+ }
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+#endif
+
+/* End: bn_mp_mod.c */
+
+/* Start: bn_mp_mod_2d.c */
+#include "tommath_private.h"
+#ifdef BN_MP_MOD_2D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* calc a value mod 2**b */
+mp_err mp_mod_2d(const mp_int *a, int b, mp_int *c)
+{
+ int x;
+ mp_err err;
+
+ /* if b is <= 0 then zero the int */
+ if (b <= 0) {
+ mp_zero(c);
+ return MP_OKAY;
+ }
+
+ /* if the modulus is larger than the value than return */
+ if (b >= (a->used * MP_DIGIT_BIT)) {
+ return mp_copy(a, c);
+ }
+
+ /* copy */
+ if ((err = mp_copy(a, c)) != MP_OKAY) {
+ return err;
+ }
+
+ /* zero digits above the last digit of the modulus */
+ x = (b / MP_DIGIT_BIT) + (((b % MP_DIGIT_BIT) == 0) ? 0 : 1);
+ MP_ZERO_DIGITS(c->dp + x, c->used - x);
+
+ /* clear the digit that is not completely outside/inside the modulus */
+ c->dp[b / MP_DIGIT_BIT] &=
+ ((mp_digit)1 << (mp_digit)(b % MP_DIGIT_BIT)) - (mp_digit)1;
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_mod_2d.c */
+
+/* Start: bn_mp_mod_d.c */
+#include "tommath_private.h"
+#ifdef BN_MP_MOD_D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+mp_err mp_mod_d(const mp_int *a, mp_digit b, mp_digit *c)
+{
+ return mp_div_d(a, b, NULL, c);
+}
+#endif
+
+/* End: bn_mp_mod_d.c */
+
+/* Start: bn_mp_montgomery_calc_normalization.c */
+#include "tommath_private.h"
+#ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/*
+ * shifts with subtractions when the result is greater than b.
+ *
+ * The method is slightly modified to shift B unconditionally upto just under
+ * the leading bit of b. This saves alot of multiple precision shifting.
+ */
+mp_err mp_montgomery_calc_normalization(mp_int *a, const mp_int *b)
+{
+ int x, bits;
+ mp_err err;
+
+ /* how many bits of last digit does b use */
+ bits = mp_count_bits(b) % MP_DIGIT_BIT;
+
+ if (b->used > 1) {
+ if ((err = mp_2expt(a, ((b->used - 1) * MP_DIGIT_BIT) + bits - 1)) != MP_OKAY) {
+ return err;
+ }
+ } else {
+ mp_set(a, 1uL);
+ bits = 1;
+ }
+
+
+ /* now compute C = A * B mod b */
+ for (x = bits - 1; x < (int)MP_DIGIT_BIT; x++) {
+ if ((err = mp_mul_2(a, a)) != MP_OKAY) {
+ return err;
+ }
+ if (mp_cmp_mag(a, b) != MP_LT) {
+ if ((err = s_mp_sub(a, b, a)) != MP_OKAY) {
+ return err;
+ }
+ }
+ }
+
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_montgomery_calc_normalization.c */
+
+/* Start: bn_mp_montgomery_reduce.c */
+#include "tommath_private.h"
+#ifdef BN_MP_MONTGOMERY_REDUCE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* computes xR**-1 == x (mod N) via Montgomery Reduction */
+mp_err mp_montgomery_reduce(mp_int *x, const mp_int *n, mp_digit rho)
+{
+ int ix, digs;
+ mp_err err;
+ mp_digit mu;
+
+ /* can the fast reduction [comba] method be used?
+ *
+ * Note that unlike in mul you're safely allowed *less*
+ * than the available columns [255 per default] since carries
+ * are fixed up in the inner loop.
+ */
+ digs = (n->used * 2) + 1;
+ if ((digs < MP_WARRAY) &&
+ (x->used <= MP_WARRAY) &&
+ (n->used < MP_MAXFAST)) {
+ return s_mp_montgomery_reduce_fast(x, n, rho);
+ }
+
+ /* grow the input as required */
+ if (x->alloc < digs) {
+ if ((err = mp_grow(x, digs)) != MP_OKAY) {
+ return err;
+ }
+ }
+ x->used = digs;
+
+ for (ix = 0; ix < n->used; ix++) {
+ /* mu = ai * rho mod b
+ *
+ * The value of rho must be precalculated via
+ * montgomery_setup() such that
+ * it equals -1/n0 mod b this allows the
+ * following inner loop to reduce the
+ * input one digit at a time
+ */
+ mu = (mp_digit)(((mp_word)x->dp[ix] * (mp_word)rho) & MP_MASK);
+
+ /* a = a + mu * m * b**i */
+ {
+ int iy;
+ mp_digit *tmpn, *tmpx, u;
+ mp_word r;
+
+ /* alias for digits of the modulus */
+ tmpn = n->dp;
+
+ /* alias for the digits of x [the input] */
+ tmpx = x->dp + ix;
+
+ /* set the carry to zero */
+ u = 0;
+
+ /* Multiply and add in place */
+ for (iy = 0; iy < n->used; iy++) {
+ /* compute product and sum */
+ r = ((mp_word)mu * (mp_word)*tmpn++) +
+ (mp_word)u + (mp_word)*tmpx;
+
+ /* get carry */
+ u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
+
+ /* fix digit */
+ *tmpx++ = (mp_digit)(r & (mp_word)MP_MASK);
+ }
+ /* At this point the ix'th digit of x should be zero */
+
+
+ /* propagate carries upwards as required*/
+ while (u != 0u) {
+ *tmpx += u;
+ u = *tmpx >> MP_DIGIT_BIT;
+ *tmpx++ &= MP_MASK;
+ }
+ }
+ }
+
+ /* at this point the n.used'th least
+ * significant digits of x are all zero
+ * which means we can shift x to the
+ * right by n.used digits and the
+ * residue is unchanged.
+ */
+
+ /* x = x/b**n.used */
+ mp_clamp(x);
+ mp_rshd(x, n->used);
+
+ /* if x >= n then x = x - n */
+ if (mp_cmp_mag(x, n) != MP_LT) {
+ return s_mp_sub(x, n, x);
+ }
+
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_montgomery_reduce.c */
+
+/* Start: bn_mp_montgomery_setup.c */
+#include "tommath_private.h"
+#ifdef BN_MP_MONTGOMERY_SETUP_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* setups the montgomery reduction stuff */
+mp_err mp_montgomery_setup(const mp_int *n, mp_digit *rho)
+{
+ mp_digit x, b;
+
+ /* fast inversion mod 2**k
+ *
+ * Based on the fact that
+ *
+ * XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n)
+ * => 2*X*A - X*X*A*A = 1
+ * => 2*(1) - (1) = 1
+ */
+ b = n->dp[0];
+
+ if ((b & 1u) == 0u) {
+ return MP_VAL;
+ }
+
+ x = (((b + 2u) & 4u) << 1) + b; /* here x*a==1 mod 2**4 */
+ x *= 2u - (b * x); /* here x*a==1 mod 2**8 */
+#if !defined(MP_8BIT)
+ x *= 2u - (b * x); /* here x*a==1 mod 2**16 */
+#endif
+#if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT))
+ x *= 2u - (b * x); /* here x*a==1 mod 2**32 */
+#endif
+#ifdef MP_64BIT
+ x *= 2u - (b * x); /* here x*a==1 mod 2**64 */
+#endif
+
+ /* rho = -1/m mod b */
+ *rho = (mp_digit)(((mp_word)1 << (mp_word)MP_DIGIT_BIT) - x) & MP_MASK;
+
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_montgomery_setup.c */
+
+/* Start: bn_mp_mul.c */
+#include "tommath_private.h"
+#ifdef BN_MP_MUL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* high level multiplication (handles sign) */
+mp_err mp_mul(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_err err;
+ int min_len = MP_MIN(a->used, b->used),
+ max_len = MP_MAX(a->used, b->used),
+ digs = a->used + b->used + 1;
+ mp_sign neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
+
+ if (MP_HAS(S_MP_BALANCE_MUL) &&
+ /* Check sizes. The smaller one needs to be larger than the Karatsuba cut-off.
+ * The bigger one needs to be at least about one MP_KARATSUBA_MUL_CUTOFF bigger
+ * to make some sense, but it depends on architecture, OS, position of the
+ * stars... so YMMV.
+ * Using it to cut the input into slices small enough for fast_s_mp_mul_digs
+ * was actually slower on the author's machine, but YMMV.
+ */
+ (min_len >= MP_KARATSUBA_MUL_CUTOFF) &&
+ ((max_len / 2) >= MP_KARATSUBA_MUL_CUTOFF) &&
+ /* Not much effect was observed below a ratio of 1:2, but again: YMMV. */
+ (max_len >= (2 * min_len))) {
+ err = s_mp_balance_mul(a,b,c);
+ } else if (MP_HAS(S_MP_TOOM_MUL) &&
+ (min_len >= MP_TOOM_MUL_CUTOFF)) {
+ err = s_mp_toom_mul(a, b, c);
+ } else if (MP_HAS(S_MP_KARATSUBA_MUL) &&
+ (min_len >= MP_KARATSUBA_MUL_CUTOFF)) {
+ err = s_mp_karatsuba_mul(a, b, c);
+ } else if (MP_HAS(S_MP_MUL_DIGS_FAST) &&
+ /* can we use the fast multiplier?
+ *
+ * The fast multiplier can be used if the output will
+ * have less than MP_WARRAY digits and the number of
+ * digits won't affect carry propagation
+ */
+ (digs < MP_WARRAY) &&
+ (min_len <= MP_MAXFAST)) {
+ err = s_mp_mul_digs_fast(a, b, c, digs);
+ } else if (MP_HAS(S_MP_MUL_DIGS)) {
+ err = s_mp_mul_digs(a, b, c, digs);
+ } else {
+ err = MP_VAL;
+ }
+ c->sign = (c->used > 0) ? neg : MP_ZPOS;
+ return err;
+}
+#endif
+
+/* End: bn_mp_mul.c */
+
+/* Start: bn_mp_mul_2.c */
+#include "tommath_private.h"
+#ifdef BN_MP_MUL_2_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* b = a*2 */
+mp_err mp_mul_2(const mp_int *a, mp_int *b)
+{
+ int x, oldused;
+ mp_err err;
+
+ /* grow to accomodate result */
+ if (b->alloc < (a->used + 1)) {
+ if ((err = mp_grow(b, a->used + 1)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ oldused = b->used;
+ b->used = a->used;
+
+ {
+ mp_digit r, rr, *tmpa, *tmpb;
+
+ /* alias for source */
+ tmpa = a->dp;
+
+ /* alias for dest */
+ tmpb = b->dp;
+
+ /* carry */
+ r = 0;
+ for (x = 0; x < a->used; x++) {
+
+ /* get what will be the *next* carry bit from the
+ * MSB of the current digit
+ */
+ rr = *tmpa >> (mp_digit)(MP_DIGIT_BIT - 1);
+
+ /* now shift up this digit, add in the carry [from the previous] */
+ *tmpb++ = ((*tmpa++ << 1uL) | r) & MP_MASK;
+
+ /* copy the carry that would be from the source
+ * digit into the next iteration
+ */
+ r = rr;
+ }
+
+ /* new leading digit? */
+ if (r != 0u) {
+ /* add a MSB which is always 1 at this point */
+ *tmpb = 1;
+ ++(b->used);
+ }
+
+ /* now zero any excess digits on the destination
+ * that we didn't write to
+ */
+ MP_ZERO_DIGITS(b->dp + b->used, oldused - b->used);
+ }
+ b->sign = a->sign;
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_mul_2.c */
+
+/* Start: bn_mp_mul_2d.c */
+#include "tommath_private.h"
+#ifdef BN_MP_MUL_2D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* shift left by a certain bit count */
+mp_err mp_mul_2d(const mp_int *a, int b, mp_int *c)
+{
+ mp_digit d;
+ mp_err err;
+
+ /* copy */
+ if (a != c) {
+ if ((err = mp_copy(a, c)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ if (c->alloc < (c->used + (b / MP_DIGIT_BIT) + 1)) {
+ if ((err = mp_grow(c, c->used + (b / MP_DIGIT_BIT) + 1)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* shift by as many digits in the bit count */
+ if (b >= MP_DIGIT_BIT) {
+ if ((err = mp_lshd(c, b / MP_DIGIT_BIT)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* shift any bit count < MP_DIGIT_BIT */
+ d = (mp_digit)(b % MP_DIGIT_BIT);
+ if (d != 0u) {
+ mp_digit *tmpc, shift, mask, r, rr;
+ int x;
+
+ /* bitmask for carries */
+ mask = ((mp_digit)1 << d) - (mp_digit)1;
+
+ /* shift for msbs */
+ shift = (mp_digit)MP_DIGIT_BIT - d;
+
+ /* alias */
+ tmpc = c->dp;
+
+ /* carry */
+ r = 0;
+ for (x = 0; x < c->used; x++) {
+ /* get the higher bits of the current word */
+ rr = (*tmpc >> shift) & mask;
+
+ /* shift the current word and OR in the carry */
+ *tmpc = ((*tmpc << d) | r) & MP_MASK;
+ ++tmpc;
+
+ /* set the carry to the carry bits of the current word */
+ r = rr;
+ }
+
+ /* set final carry */
+ if (r != 0u) {
+ c->dp[(c->used)++] = r;
+ }
+ }
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_mul_2d.c */
+
+/* Start: bn_mp_mul_d.c */
+#include "tommath_private.h"
+#ifdef BN_MP_MUL_D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* multiply by a digit */
+mp_err mp_mul_d(const mp_int *a, mp_digit b, mp_int *c)
+{
+ mp_digit u, *tmpa, *tmpc;
+ mp_word r;
+ mp_err err;
+ int ix, olduse;
+
+ /* make sure c is big enough to hold a*b */
+ if (c->alloc < (a->used + 1)) {
+ if ((err = mp_grow(c, a->used + 1)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* get the original destinations used count */
+ olduse = c->used;
+
+ /* set the sign */
+ c->sign = a->sign;
+
+ /* alias for a->dp [source] */
+ tmpa = a->dp;
+
+ /* alias for c->dp [dest] */
+ tmpc = c->dp;
+
+ /* zero carry */
+ u = 0;
+
+ /* compute columns */
+ for (ix = 0; ix < a->used; ix++) {
+ /* compute product and carry sum for this term */
+ r = (mp_word)u + ((mp_word)*tmpa++ * (mp_word)b);
+
+ /* mask off higher bits to get a single digit */
+ *tmpc++ = (mp_digit)(r & (mp_word)MP_MASK);
+
+ /* send carry into next iteration */
+ u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
+ }
+
+ /* store final carry [if any] and increment ix offset */
+ *tmpc++ = u;
+ ++ix;
+
+ /* now zero digits above the top */
+ MP_ZERO_DIGITS(tmpc, olduse - ix);
+
+ /* set used count */
+ c->used = a->used + 1;
+ mp_clamp(c);
+
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_mul_d.c */
+
+/* Start: bn_mp_mulmod.c */
+#include "tommath_private.h"
+#ifdef BN_MP_MULMOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* d = a * b (mod c) */
+mp_err mp_mulmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d)
+{
+ mp_err err;
+ mp_int t;
+
+ if ((err = mp_init_size(&t, c->used)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_mul(a, b, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ err = mp_mod(&t, c, d);
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+#endif
+
+/* End: bn_mp_mulmod.c */
+
+/* Start: bn_mp_neg.c */
+#include "tommath_private.h"
+#ifdef BN_MP_NEG_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* b = -a */
+mp_err mp_neg(const mp_int *a, mp_int *b)
+{
+ mp_err err;
+ if (a != b) {
+ if ((err = mp_copy(a, b)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ if (!MP_IS_ZERO(b)) {
+ b->sign = (a->sign == MP_ZPOS) ? MP_NEG : MP_ZPOS;
+ } else {
+ b->sign = MP_ZPOS;
+ }
+
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_neg.c */
+
+/* Start: bn_mp_or.c */
+#include "tommath_private.h"
+#ifdef BN_MP_OR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* two complement or */
+mp_err mp_or(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ int used = MP_MAX(a->used, b->used) + 1, i;
+ mp_err err;
+ mp_digit ac = 1, bc = 1, cc = 1;
+ mp_sign csign = ((a->sign == MP_NEG) || (b->sign == MP_NEG)) ? MP_NEG : MP_ZPOS;
+
+ if (c->alloc < used) {
+ if ((err = mp_grow(c, used)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ for (i = 0; i < used; i++) {
+ mp_digit x, y;
+
+ /* convert to two complement if negative */
+ if (a->sign == MP_NEG) {
+ ac += (i >= a->used) ? MP_MASK : (~a->dp[i] & MP_MASK);
+ x = ac & MP_MASK;
+ ac >>= MP_DIGIT_BIT;
+ } else {
+ x = (i >= a->used) ? 0uL : a->dp[i];
+ }
+
+ /* convert to two complement if negative */
+ if (b->sign == MP_NEG) {
+ bc += (i >= b->used) ? MP_MASK : (~b->dp[i] & MP_MASK);
+ y = bc & MP_MASK;
+ bc >>= MP_DIGIT_BIT;
+ } else {
+ y = (i >= b->used) ? 0uL : b->dp[i];
+ }
+
+ c->dp[i] = x | y;
+
+ /* convert to to sign-magnitude if negative */
+ if (csign == MP_NEG) {
+ cc += ~c->dp[i] & MP_MASK;
+ c->dp[i] = cc & MP_MASK;
+ cc >>= MP_DIGIT_BIT;
+ }
+ }
+
+ c->used = used;
+ c->sign = csign;
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_or.c */
+
+/* Start: bn_mp_pack.c */
+#include "tommath_private.h"
+#ifdef BN_MP_PACK_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* based on gmp's mpz_export.
+ * see http://gmplib.org/manual/Integer-Import-and-Export.html
+ */
+mp_err mp_pack(void *rop, size_t maxcount, size_t *written, mp_order order, size_t size,
+ mp_endian endian, size_t nails, const mp_int *op)
+{
+ mp_err err;
+ size_t odd_nails, nail_bytes, i, j, count;
+ unsigned char odd_nail_mask;
+
+ mp_int t;
+
+ count = mp_pack_count(op, nails, size);
+
+ if (count > maxcount) {
+ return MP_BUF;
+ }
+
+ if ((err = mp_init_copy(&t, op)) != MP_OKAY) {
+ return err;
+ }
+
+ if (endian == MP_NATIVE_ENDIAN) {
+ MP_GET_ENDIANNESS(endian);
+ }
+
+ odd_nails = (nails % 8u);
+ odd_nail_mask = 0xff;
+ for (i = 0u; i < odd_nails; ++i) {
+ odd_nail_mask ^= (unsigned char)(1u << (7u - i));
+ }
+ nail_bytes = nails / 8u;
+
+ for (i = 0u; i < count; ++i) {
+ for (j = 0u; j < size; ++j) {
+ unsigned char *byte = (unsigned char *)rop +
+ (((order == MP_LSB_FIRST) ? i : ((count - 1u) - i)) * size) +
+ ((endian == MP_LITTLE_ENDIAN) ? j : ((size - 1u) - j));
+
+ if (j >= (size - nail_bytes)) {
+ *byte = 0;
+ continue;
+ }
+
+ *byte = (unsigned char)((j == ((size - nail_bytes) - 1u)) ? (t.dp[0] & odd_nail_mask) : (t.dp[0] & 0xFFuL));
+
+ if ((err = mp_div_2d(&t, (j == ((size - nail_bytes) - 1u)) ? (int)(8u - odd_nails) : 8, &t, NULL)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ }
+ }
+
+ if (written != NULL) {
+ *written = count;
+ }
+ err = MP_OKAY;
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_pack.c */
+
+/* Start: bn_mp_pack_count.c */
+#include "tommath_private.h"
+#ifdef BN_MP_PACK_COUNT_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+size_t mp_pack_count(const mp_int *a, size_t nails, size_t size)
+{
+ size_t bits = (size_t)mp_count_bits(a);
+ return ((bits / ((size * 8u) - nails)) + (((bits % ((size * 8u) - nails)) != 0u) ? 1u : 0u));
+}
+
+#endif
+
+/* End: bn_mp_pack_count.c */
+
+/* Start: bn_mp_prime_fermat.c */
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_FERMAT_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* performs one Fermat test.
+ *
+ * If "a" were prime then b**a == b (mod a) since the order of
+ * the multiplicative sub-group would be phi(a) = a-1. That means
+ * it would be the same as b**(a mod (a-1)) == b**1 == b (mod a).
+ *
+ * Sets result to 1 if the congruence holds, or zero otherwise.
+ */
+mp_err mp_prime_fermat(const mp_int *a, const mp_int *b, mp_bool *result)
+{
+ mp_int t;
+ mp_err err;
+
+ /* default to composite */
+ *result = MP_NO;
+
+ /* ensure b > 1 */
+ if (mp_cmp_d(b, 1uL) != MP_GT) {
+ return MP_VAL;
+ }
+
+ /* init t */
+ if ((err = mp_init(&t)) != MP_OKAY) {
+ return err;
+ }
+
+ /* compute t = b**a mod a */
+ if ((err = mp_exptmod(b, a, a, &t)) != MP_OKAY) {
+ goto LBL_T;
+ }
+
+ /* is it equal to b? */
+ if (mp_cmp(&t, b) == MP_EQ) {
+ *result = MP_YES;
+ }
+
+ err = MP_OKAY;
+LBL_T:
+ mp_clear(&t);
+ return err;
+}
+#endif
+
+/* End: bn_mp_prime_fermat.c */
+
+/* Start: bn_mp_prime_frobenius_underwood.c */
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_FROBENIUS_UNDERWOOD_C
+
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/*
+ * See file bn_mp_prime_is_prime.c or the documentation in doc/bn.tex for the details
+ */
+#ifndef LTM_USE_ONLY_MR
+
+#ifdef MP_8BIT
+/*
+ * floor of positive solution of
+ * (2^16)-1 = (a+4)*(2*a+5)
+ * TODO: Both values are smaller than N^(1/4), would have to use a bigint
+ * for a instead but any a biger than about 120 are already so rare that
+ * it is possible to ignore them and still get enough pseudoprimes.
+ * But it is still a restriction of the set of available pseudoprimes
+ * which makes this implementation less secure if used stand-alone.
+ */
+#define LTM_FROBENIUS_UNDERWOOD_A 177
+#else
+#define LTM_FROBENIUS_UNDERWOOD_A 32764
+#endif
+mp_err mp_prime_frobenius_underwood(const mp_int *N, mp_bool *result)
+{
+ mp_int T1z, T2z, Np1z, sz, tz;
+
+ int a, ap2, length, i, j;
+ mp_err err;
+
+ *result = MP_NO;
+
+ if ((err = mp_init_multi(&T1z, &T2z, &Np1z, &sz, &tz, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ for (a = 0; a < LTM_FROBENIUS_UNDERWOOD_A; a++) {
+ /* TODO: That's ugly! No, really, it is! */
+ if ((a==2) || (a==4) || (a==7) || (a==8) || (a==10) ||
+ (a==14) || (a==18) || (a==23) || (a==26) || (a==28)) {
+ continue;
+ }
+ /* (32764^2 - 4) < 2^31, no bigint for >MP_8BIT needed) */
+ mp_set_u32(&T1z, (uint32_t)a);
+
+ if ((err = mp_sqr(&T1z, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+
+ if ((err = mp_sub_d(&T1z, 4uL, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+
+ if ((err = mp_kronecker(&T1z, N, &j)) != MP_OKAY) goto LBL_FU_ERR;
+
+ if (j == -1) {
+ break;
+ }
+
+ if (j == 0) {
+ /* composite */
+ goto LBL_FU_ERR;
+ }
+ }
+ /* Tell it a composite and set return value accordingly */
+ if (a >= LTM_FROBENIUS_UNDERWOOD_A) {
+ err = MP_ITER;
+ goto LBL_FU_ERR;
+ }
+ /* Composite if N and (a+4)*(2*a+5) are not coprime */
+ mp_set_u32(&T1z, (uint32_t)((a+4)*((2*a)+5)));
+
+ if ((err = mp_gcd(N, &T1z, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+
+ if (!((T1z.used == 1) && (T1z.dp[0] == 1u))) goto LBL_FU_ERR;
+
+ ap2 = a + 2;
+ if ((err = mp_add_d(N, 1uL, &Np1z)) != MP_OKAY) goto LBL_FU_ERR;
+
+ mp_set(&sz, 1uL);
+ mp_set(&tz, 2uL);
+ length = mp_count_bits(&Np1z);
+
+ for (i = length - 2; i >= 0; i--) {
+ /*
+ * temp = (sz*(a*sz+2*tz))%N;
+ * tz = ((tz-sz)*(tz+sz))%N;
+ * sz = temp;
+ */
+ if ((err = mp_mul_2(&tz, &T2z)) != MP_OKAY) goto LBL_FU_ERR;
+
+ /* a = 0 at about 50% of the cases (non-square and odd input) */
+ if (a != 0) {
+ if ((err = mp_mul_d(&sz, (mp_digit)a, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_add(&T1z, &T2z, &T2z)) != MP_OKAY) goto LBL_FU_ERR;
+ }
+
+ if ((err = mp_mul(&T2z, &sz, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_sub(&tz, &sz, &T2z)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_add(&sz, &tz, &sz)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_mul(&sz, &T2z, &tz)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_mod(&tz, N, &tz)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_mod(&T1z, N, &sz)) != MP_OKAY) goto LBL_FU_ERR;
+ if (s_mp_get_bit(&Np1z, (unsigned int)i) == MP_YES) {
+ /*
+ * temp = (a+2) * sz + tz
+ * tz = 2 * tz - sz
+ * sz = temp
+ */
+ if (a == 0) {
+ if ((err = mp_mul_2(&sz, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+ } else {
+ if ((err = mp_mul_d(&sz, (mp_digit)ap2, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+ }
+ if ((err = mp_add(&T1z, &tz, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_mul_2(&tz, &T2z)) != MP_OKAY) goto LBL_FU_ERR;
+ if ((err = mp_sub(&T2z, &sz, &tz)) != MP_OKAY) goto LBL_FU_ERR;
+ mp_exch(&sz, &T1z);
+ }
+ }
+
+ mp_set_u32(&T1z, (uint32_t)((2 * a) + 5));
+ if ((err = mp_mod(&T1z, N, &T1z)) != MP_OKAY) goto LBL_FU_ERR;
+ if (MP_IS_ZERO(&sz) && (mp_cmp(&tz, &T1z) == MP_EQ)) {
+ *result = MP_YES;
+ }
+
+LBL_FU_ERR:
+ mp_clear_multi(&tz, &sz, &Np1z, &T2z, &T1z, NULL);
+ return err;
+}
+
+#endif
+#endif
+
+/* End: bn_mp_prime_frobenius_underwood.c */
+
+/* Start: bn_mp_prime_is_prime.c */
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_IS_PRIME_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* portable integer log of two with small footprint */
+static unsigned int s_floor_ilog2(int value)
+{
+ unsigned int r = 0;
+ while ((value >>= 1) != 0) {
+ r++;
+ }
+ return r;
+}
+
+
+mp_err mp_prime_is_prime(const mp_int *a, int t, mp_bool *result)
+{
+ mp_int b;
+ int ix, p_max = 0, size_a, len;
+ mp_bool res;
+ mp_err err;
+ unsigned int fips_rand, mask;
+
+ /* default to no */
+ *result = MP_NO;
+
+ /* Some shortcuts */
+ /* N > 3 */
+ if (a->used == 1) {
+ if ((a->dp[0] == 0u) || (a->dp[0] == 1u)) {
+ *result = MP_NO;
+ return MP_OKAY;
+ }
+ if (a->dp[0] == 2u) {
+ *result = MP_YES;
+ return MP_OKAY;
+ }
+ }
+
+ /* N must be odd */
+ if (MP_IS_EVEN(a)) {
+ return MP_OKAY;
+ }
+ /* N is not a perfect square: floor(sqrt(N))^2 != N */
+ if ((err = mp_is_square(a, &res)) != MP_OKAY) {
+ return err;
+ }
+ if (res != MP_NO) {
+ return MP_OKAY;
+ }
+
+ /* is the input equal to one of the primes in the table? */
+ for (ix = 0; ix < PRIVATE_MP_PRIME_TAB_SIZE; ix++) {
+ if (mp_cmp_d(a, s_mp_prime_tab[ix]) == MP_EQ) {
+ *result = MP_YES;
+ return MP_OKAY;
+ }
+ }
+#ifdef MP_8BIT
+ /* The search in the loop above was exhaustive in this case */
+ if ((a->used == 1) && (PRIVATE_MP_PRIME_TAB_SIZE >= 31)) {
+ return MP_OKAY;
+ }
+#endif
+
+ /* first perform trial division */
+ if ((err = s_mp_prime_is_divisible(a, &res)) != MP_OKAY) {
+ return err;
+ }
+
+ /* return if it was trivially divisible */
+ if (res == MP_YES) {
+ return MP_OKAY;
+ }
+
+ /*
+ Run the Miller-Rabin test with base 2 for the BPSW test.
+ */
+ if ((err = mp_init_set(&b, 2uL)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_prime_miller_rabin(a, &b, &res)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ if (res == MP_NO) {
+ goto LBL_B;
+ }
+ /*
+ Rumours have it that Mathematica does a second M-R test with base 3.
+ Other rumours have it that their strong L-S test is slightly different.
+ It does not hurt, though, beside a bit of extra runtime.
+ */
+ b.dp[0]++;
+ if ((err = mp_prime_miller_rabin(a, &b, &res)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ if (res == MP_NO) {
+ goto LBL_B;
+ }
+
+ /*
+ * Both, the Frobenius-Underwood test and the the Lucas-Selfridge test are quite
+ * slow so if speed is an issue, define LTM_USE_ONLY_MR to use M-R tests with
+ * bases 2, 3 and t random bases.
+ */
+#ifndef LTM_USE_ONLY_MR
+ if (t >= 0) {
+ /*
+ * Use a Frobenius-Underwood test instead of the Lucas-Selfridge test for
+ * MP_8BIT (It is unknown if the Lucas-Selfridge test works with 16-bit
+ * integers but the necesssary analysis is on the todo-list).
+ */
+#if defined (MP_8BIT) || defined (LTM_USE_FROBENIUS_TEST)
+ err = mp_prime_frobenius_underwood(a, &res);
+ if ((err != MP_OKAY) && (err != MP_ITER)) {
+ goto LBL_B;
+ }
+ if (res == MP_NO) {
+ goto LBL_B;
+ }
+#else
+ if ((err = mp_prime_strong_lucas_selfridge(a, &res)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ if (res == MP_NO) {
+ goto LBL_B;
+ }
+#endif
+ }
+#endif
+
+ /* run at least one Miller-Rabin test with a random base */
+ if (t == 0) {
+ t = 1;
+ }
+
+ /*
+ Only recommended if the input range is known to be < 3317044064679887385961981
+
+ It uses the bases necessary for a deterministic M-R test if the input is
+ smaller than 3317044064679887385961981
+ The caller has to check the size.
+ TODO: can be made a bit finer grained but comparing is not free.
+ */
+ if (t < 0) {
+ /*
+ Sorenson, Jonathan; Webster, Jonathan (2015).
+ "Strong Pseudoprimes to Twelve Prime Bases".
+ */
+ /* 0x437ae92817f9fc85b7e5 = 318665857834031151167461 */
+ if ((err = mp_read_radix(&b, "437ae92817f9fc85b7e5", 16)) != MP_OKAY) {
+ goto LBL_B;
+ }
+
+ if (mp_cmp(a, &b) == MP_LT) {
+ p_max = 12;
+ } else {
+ /* 0x2be6951adc5b22410a5fd = 3317044064679887385961981 */
+ if ((err = mp_read_radix(&b, "2be6951adc5b22410a5fd", 16)) != MP_OKAY) {
+ goto LBL_B;
+ }
+
+ if (mp_cmp(a, &b) == MP_LT) {
+ p_max = 13;
+ } else {
+ err = MP_VAL;
+ goto LBL_B;
+ }
+ }
+
+ /* we did bases 2 and 3 already, skip them */
+ for (ix = 2; ix < p_max; ix++) {
+ mp_set(&b, s_mp_prime_tab[ix]);
+ if ((err = mp_prime_miller_rabin(a, &b, &res)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ if (res == MP_NO) {
+ goto LBL_B;
+ }
+ }
+ }
+ /*
+ Do "t" M-R tests with random bases between 3 and "a".
+ See Fips 186.4 p. 126ff
+ */
+ else if (t > 0) {
+ /*
+ * The mp_digit's have a defined bit-size but the size of the
+ * array a.dp is a simple 'int' and this library can not assume full
+ * compliance to the current C-standard (ISO/IEC 9899:2011) because
+ * it gets used for small embeded processors, too. Some of those MCUs
+ * have compilers that one cannot call standard compliant by any means.
+ * Hence the ugly type-fiddling in the following code.
+ */
+ size_a = mp_count_bits(a);
+ mask = (1u << s_floor_ilog2(size_a)) - 1u;
+ /*
+ Assuming the General Rieman hypothesis (never thought to write that in a
+ comment) the upper bound can be lowered to 2*(log a)^2.
+ E. Bach, "Explicit bounds for primality testing and related problems,"
+ Math. Comp. 55 (1990), 355-380.
+
+ size_a = (size_a/10) * 7;
+ len = 2 * (size_a * size_a);
+
+ E.g.: a number of size 2^2048 would be reduced to the upper limit
+
+ floor(2048/10)*7 = 1428
+ 2 * 1428^2 = 4078368
+
+ (would have been ~4030331.9962 with floats and natural log instead)
+ That number is smaller than 2^28, the default bit-size of mp_digit.
+ */
+
+ /*
+ How many tests, you might ask? Dana Jacobsen of Math::Prime::Util fame
+ does exactly 1. In words: one. Look at the end of _GMP_is_prime() in
+ Math-Prime-Util-GMP-0.50/primality.c if you do not believe it.
+
+ The function mp_rand() goes to some length to use a cryptographically
+ good PRNG. That also means that the chance to always get the same base
+ in the loop is non-zero, although very low.
+ If the BPSW test and/or the addtional Frobenious test have been
+ performed instead of just the Miller-Rabin test with the bases 2 and 3,
+ a single extra test should suffice, so such a very unlikely event
+ will not do much harm.
+
+ To preemptivly answer the dangling question: no, a witness does not
+ need to be prime.
+ */
+ for (ix = 0; ix < t; ix++) {
+ /* mp_rand() guarantees the first digit to be non-zero */
+ if ((err = mp_rand(&b, 1)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ /*
+ * Reduce digit before casting because mp_digit might be bigger than
+ * an unsigned int and "mask" on the other side is most probably not.
+ */
+ fips_rand = (unsigned int)(b.dp[0] & (mp_digit) mask);
+#ifdef MP_8BIT
+ /*
+ * One 8-bit digit is too small, so concatenate two if the size of
+ * unsigned int allows for it.
+ */
+ if ((MP_SIZEOF_BITS(unsigned int)/2) >= MP_SIZEOF_BITS(mp_digit)) {
+ if ((err = mp_rand(&b, 1)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ fips_rand <<= MP_SIZEOF_BITS(mp_digit);
+ fips_rand |= (unsigned int) b.dp[0];
+ fips_rand &= mask;
+ }
+#endif
+ if (fips_rand > (unsigned int)(INT_MAX - MP_DIGIT_BIT)) {
+ len = INT_MAX / MP_DIGIT_BIT;
+ } else {
+ len = (((int)fips_rand + MP_DIGIT_BIT) / MP_DIGIT_BIT);
+ }
+ /* Unlikely. */
+ if (len < 0) {
+ ix--;
+ continue;
+ }
+ /*
+ * As mentioned above, one 8-bit digit is too small and
+ * although it can only happen in the unlikely case that
+ * an "unsigned int" is smaller than 16 bit a simple test
+ * is cheap and the correction even cheaper.
+ */
+#ifdef MP_8BIT
+ /* All "a" < 2^8 have been caught before */
+ if (len == 1) {
+ len++;
+ }
+#endif
+ if ((err = mp_rand(&b, len)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ /*
+ * That number might got too big and the witness has to be
+ * smaller than "a"
+ */
+ len = mp_count_bits(&b);
+ if (len >= size_a) {
+ len = (len - size_a) + 1;
+ if ((err = mp_div_2d(&b, len, &b, NULL)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ }
+ /* Although the chance for b <= 3 is miniscule, try again. */
+ if (mp_cmp_d(&b, 3uL) != MP_GT) {
+ ix--;
+ continue;
+ }
+ if ((err = mp_prime_miller_rabin(a, &b, &res)) != MP_OKAY) {
+ goto LBL_B;
+ }
+ if (res == MP_NO) {
+ goto LBL_B;
+ }
+ }
+ }
+
+ /* passed the test */
+ *result = MP_YES;
+LBL_B:
+ mp_clear(&b);
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_prime_is_prime.c */
+
+/* Start: bn_mp_prime_miller_rabin.c */
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_MILLER_RABIN_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Miller-Rabin test of "a" to the base of "b" as described in
+ * HAC pp. 139 Algorithm 4.24
+ *
+ * Sets result to 0 if definitely composite or 1 if probably prime.
+ * Randomly the chance of error is no more than 1/4 and often
+ * very much lower.
+ */
+mp_err mp_prime_miller_rabin(const mp_int *a, const mp_int *b, mp_bool *result)
+{
+ mp_int n1, y, r;
+ mp_err err;
+ int s, j;
+
+ /* default */
+ *result = MP_NO;
+
+ /* ensure b > 1 */
+ if (mp_cmp_d(b, 1uL) != MP_GT) {
+ return MP_VAL;
+ }
+
+ /* get n1 = a - 1 */
+ if ((err = mp_init_copy(&n1, a)) != MP_OKAY) {
+ return err;
+ }
+ if ((err = mp_sub_d(&n1, 1uL, &n1)) != MP_OKAY) {
+ goto LBL_N1;
+ }
+
+ /* set 2**s * r = n1 */
+ if ((err = mp_init_copy(&r, &n1)) != MP_OKAY) {
+ goto LBL_N1;
+ }
+
+ /* count the number of least significant bits
+ * which are zero
+ */
+ s = mp_cnt_lsb(&r);
+
+ /* now divide n - 1 by 2**s */
+ if ((err = mp_div_2d(&r, s, &r, NULL)) != MP_OKAY) {
+ goto LBL_R;
+ }
+
+ /* compute y = b**r mod a */
+ if ((err = mp_init(&y)) != MP_OKAY) {
+ goto LBL_R;
+ }
+ if ((err = mp_exptmod(b, &r, a, &y)) != MP_OKAY) {
+ goto LBL_Y;
+ }
+
+ /* if y != 1 and y != n1 do */
+ if ((mp_cmp_d(&y, 1uL) != MP_EQ) && (mp_cmp(&y, &n1) != MP_EQ)) {
+ j = 1;
+ /* while j <= s-1 and y != n1 */
+ while ((j <= (s - 1)) && (mp_cmp(&y, &n1) != MP_EQ)) {
+ if ((err = mp_sqrmod(&y, a, &y)) != MP_OKAY) {
+ goto LBL_Y;
+ }
+
+ /* if y == 1 then composite */
+ if (mp_cmp_d(&y, 1uL) == MP_EQ) {
+ goto LBL_Y;
+ }
+
+ ++j;
+ }
+
+ /* if y != n1 then composite */
+ if (mp_cmp(&y, &n1) != MP_EQ) {
+ goto LBL_Y;
+ }
+ }
+
+ /* probably prime now */
+ *result = MP_YES;
+LBL_Y:
+ mp_clear(&y);
+LBL_R:
+ mp_clear(&r);
+LBL_N1:
+ mp_clear(&n1);
+ return err;
+}
+#endif
+
+/* End: bn_mp_prime_miller_rabin.c */
+
+/* Start: bn_mp_prime_next_prime.c */
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_NEXT_PRIME_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* finds the next prime after the number "a" using "t" trials
+ * of Miller-Rabin.
+ *
+ * bbs_style = 1 means the prime must be congruent to 3 mod 4
+ */
+mp_err mp_prime_next_prime(mp_int *a, int t, int bbs_style)
+{
+ int x, y;
+ mp_ord cmp;
+ mp_err err;
+ mp_bool res = MP_NO;
+ mp_digit res_tab[PRIVATE_MP_PRIME_TAB_SIZE], step, kstep;
+ mp_int b;
+
+ /* force positive */
+ a->sign = MP_ZPOS;
+
+ /* simple algo if a is less than the largest prime in the table */
+ if (mp_cmp_d(a, s_mp_prime_tab[PRIVATE_MP_PRIME_TAB_SIZE-1]) == MP_LT) {
+ /* find which prime it is bigger than "a" */
+ for (x = 0; x < PRIVATE_MP_PRIME_TAB_SIZE; x++) {
+ cmp = mp_cmp_d(a, s_mp_prime_tab[x]);
+ if (cmp == MP_EQ) {
+ continue;
+ }
+ if (cmp != MP_GT) {
+ if ((bbs_style == 1) && ((s_mp_prime_tab[x] & 3u) != 3u)) {
+ /* try again until we get a prime congruent to 3 mod 4 */
+ continue;
+ } else {
+ mp_set(a, s_mp_prime_tab[x]);
+ return MP_OKAY;
+ }
+ }
+ }
+ /* fall through to the sieve */
+ }
+
+ /* generate a prime congruent to 3 mod 4 or 1/3 mod 4? */
+ if (bbs_style == 1) {
+ kstep = 4;
+ } else {
+ kstep = 2;
+ }
+
+ /* at this point we will use a combination of a sieve and Miller-Rabin */
+
+ if (bbs_style == 1) {
+ /* if a mod 4 != 3 subtract the correct value to make it so */
+ if ((a->dp[0] & 3u) != 3u) {
+ if ((err = mp_sub_d(a, (a->dp[0] & 3u) + 1u, a)) != MP_OKAY) {
+ return err;
+ }
+ }
+ } else {
+ if (MP_IS_EVEN(a)) {
+ /* force odd */
+ if ((err = mp_sub_d(a, 1uL, a)) != MP_OKAY) {
+ return err;
+ }
+ }
+ }
+
+ /* generate the restable */
+ for (x = 1; x < PRIVATE_MP_PRIME_TAB_SIZE; x++) {
+ if ((err = mp_mod_d(a, s_mp_prime_tab[x], res_tab + x)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* init temp used for Miller-Rabin Testing */
+ if ((err = mp_init(&b)) != MP_OKAY) {
+ return err;
+ }
+
+ for (;;) {
+ /* skip to the next non-trivially divisible candidate */
+ step = 0;
+ do {
+ /* y == 1 if any residue was zero [e.g. cannot be prime] */
+ y = 0;
+
+ /* increase step to next candidate */
+ step += kstep;
+
+ /* compute the new residue without using division */
+ for (x = 1; x < PRIVATE_MP_PRIME_TAB_SIZE; x++) {
+ /* add the step to each residue */
+ res_tab[x] += kstep;
+
+ /* subtract the modulus [instead of using division] */
+ if (res_tab[x] >= s_mp_prime_tab[x]) {
+ res_tab[x] -= s_mp_prime_tab[x];
+ }
+
+ /* set flag if zero */
+ if (res_tab[x] == 0u) {
+ y = 1;
+ }
+ }
+ } while ((y == 1) && (step < (((mp_digit)1 << MP_DIGIT_BIT) - kstep)));
+
+ /* add the step */
+ if ((err = mp_add_d(a, step, a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ /* if didn't pass sieve and step == MP_MAX then skip test */
+ if ((y == 1) && (step >= (((mp_digit)1 << MP_DIGIT_BIT) - kstep))) {
+ continue;
+ }
+
+ if ((err = mp_prime_is_prime(a, t, &res)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (res == MP_YES) {
+ break;
+ }
+ }
+
+ err = MP_OKAY;
+LBL_ERR:
+ mp_clear(&b);
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_prime_next_prime.c */
+
+/* Start: bn_mp_prime_rabin_miller_trials.c */
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_RABIN_MILLER_TRIALS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+static const struct {
+ int k, t;
+} sizes[] = {
+ { 80, -1 }, /* Use deterministic algorithm for size <= 80 bits */
+ { 81, 37 }, /* max. error = 2^(-96)*/
+ { 96, 32 }, /* max. error = 2^(-96)*/
+ { 128, 40 }, /* max. error = 2^(-112)*/
+ { 160, 35 }, /* max. error = 2^(-112)*/
+ { 256, 27 }, /* max. error = 2^(-128)*/
+ { 384, 16 }, /* max. error = 2^(-128)*/
+ { 512, 18 }, /* max. error = 2^(-160)*/
+ { 768, 11 }, /* max. error = 2^(-160)*/
+ { 896, 10 }, /* max. error = 2^(-160)*/
+ { 1024, 12 }, /* max. error = 2^(-192)*/
+ { 1536, 8 }, /* max. error = 2^(-192)*/
+ { 2048, 6 }, /* max. error = 2^(-192)*/
+ { 3072, 4 }, /* max. error = 2^(-192)*/
+ { 4096, 5 }, /* max. error = 2^(-256)*/
+ { 5120, 4 }, /* max. error = 2^(-256)*/
+ { 6144, 4 }, /* max. error = 2^(-256)*/
+ { 8192, 3 }, /* max. error = 2^(-256)*/
+ { 9216, 3 }, /* max. error = 2^(-256)*/
+ { 10240, 2 } /* For bigger keysizes use always at least 2 Rounds */
+};
+
+/* returns # of RM trials required for a given bit size */
+int mp_prime_rabin_miller_trials(int size)
+{
+ int x;
+
+ for (x = 0; x < (int)(sizeof(sizes)/(sizeof(sizes[0]))); x++) {
+ if (sizes[x].k == size) {
+ return sizes[x].t;
+ } else if (sizes[x].k > size) {
+ return (x == 0) ? sizes[0].t : sizes[x - 1].t;
+ }
+ }
+ return sizes[x-1].t;
+}
+
+
+#endif
+
+/* End: bn_mp_prime_rabin_miller_trials.c */
+
+/* Start: bn_mp_prime_rand.c */
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_RAND_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* makes a truly random prime of a given size (bits),
+ *
+ * Flags are as follows:
+ *
+ * MP_PRIME_BBS - make prime congruent to 3 mod 4
+ * MP_PRIME_SAFE - make sure (p-1)/2 is prime as well (implies MP_PRIME_BBS)
+ * MP_PRIME_2MSB_ON - make the 2nd highest bit one
+ *
+ * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can
+ * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself
+ * so it can be NULL
+ *
+ */
+
+/* This is possibly the mother of all prime generation functions, muahahahahaha! */
+mp_err s_mp_prime_random_ex(mp_int *a, int t, int size, int flags, private_mp_prime_callback cb, void *dat)
+{
+ unsigned char *tmp, maskAND, maskOR_msb, maskOR_lsb;
+ int bsize, maskOR_msb_offset;
+ mp_bool res;
+ mp_err err;
+
+ /* sanity check the input */
+ if ((size <= 1) || (t <= 0)) {
+ return MP_VAL;
+ }
+
+ /* MP_PRIME_SAFE implies MP_PRIME_BBS */
+ if ((flags & MP_PRIME_SAFE) != 0) {
+ flags |= MP_PRIME_BBS;
+ }
+
+ /* calc the byte size */
+ bsize = (size>>3) + ((size&7)?1:0);
+
+ /* we need a buffer of bsize bytes */
+ tmp = (unsigned char *) MP_MALLOC((size_t)bsize);
+ if (tmp == NULL) {
+ return MP_MEM;
+ }
+
+ /* calc the maskAND value for the MSbyte*/
+ maskAND = ((size&7) == 0) ? 0xFFu : (unsigned char)(0xFFu >> (8 - (size & 7)));
+
+ /* calc the maskOR_msb */
+ maskOR_msb = 0;
+ maskOR_msb_offset = ((size & 7) == 1) ? 1 : 0;
+ if ((flags & MP_PRIME_2MSB_ON) != 0) {
+ maskOR_msb |= (unsigned char)(0x80 >> ((9 - size) & 7));
+ }
+
+ /* get the maskOR_lsb */
+ maskOR_lsb = 1u;
+ if ((flags & MP_PRIME_BBS) != 0) {
+ maskOR_lsb |= 3u;
+ }
+
+ do {
+ /* read the bytes */
+ if (cb(tmp, bsize, dat) != bsize) {
+ err = MP_VAL;
+ goto error;
+ }
+
+ /* work over the MSbyte */
+ tmp[0] &= maskAND;
+ tmp[0] |= (unsigned char)(1 << ((size - 1) & 7));
+
+ /* mix in the maskORs */
+ tmp[maskOR_msb_offset] |= maskOR_msb;
+ tmp[bsize-1] |= maskOR_lsb;
+
+ /* read it in */
+ /* TODO: casting only for now until all lengths have been changed to the type "size_t"*/
+ if ((err = mp_from_ubin(a, tmp, (size_t)bsize)) != MP_OKAY) {
+ goto error;
+ }
+
+ /* is it prime? */
+ if ((err = mp_prime_is_prime(a, t, &res)) != MP_OKAY) {
+ goto error;
+ }
+ if (res == MP_NO) {
+ continue;
+ }
+
+ if ((flags & MP_PRIME_SAFE) != 0) {
+ /* see if (a-1)/2 is prime */
+ if ((err = mp_sub_d(a, 1uL, a)) != MP_OKAY) {
+ goto error;
+ }
+ if ((err = mp_div_2(a, a)) != MP_OKAY) {
+ goto error;
+ }
+
+ /* is it prime? */
+ if ((err = mp_prime_is_prime(a, t, &res)) != MP_OKAY) {
+ goto error;
+ }
+ }
+ } while (res == MP_NO);
+
+ if ((flags & MP_PRIME_SAFE) != 0) {
+ /* restore a to the original value */
+ if ((err = mp_mul_2(a, a)) != MP_OKAY) {
+ goto error;
+ }
+ if ((err = mp_add_d(a, 1uL, a)) != MP_OKAY) {
+ goto error;
+ }
+ }
+
+ err = MP_OKAY;
+error:
+ MP_FREE_BUFFER(tmp, (size_t)bsize);
+ return err;
+}
+
+static int s_mp_rand_cb(unsigned char *dst, int len, void *dat)
+{
+ (void)dat;
+ if (len <= 0) {
+ return len;
+ }
+ if (s_mp_rand_source(dst, (size_t)len) != MP_OKAY) {
+ return 0;
+ }
+ return len;
+}
+
+mp_err mp_prime_rand(mp_int *a, int t, int size, int flags)
+{
+ return s_mp_prime_random_ex(a, t, size, flags, s_mp_rand_cb, NULL);
+}
+
+#endif
+
+/* End: bn_mp_prime_rand.c */
+
+/* Start: bn_mp_prime_strong_lucas_selfridge.c */
+#include "tommath_private.h"
+#ifdef BN_MP_PRIME_STRONG_LUCAS_SELFRIDGE_C
+
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/*
+ * See file bn_mp_prime_is_prime.c or the documentation in doc/bn.tex for the details
+ */
+#ifndef LTM_USE_ONLY_MR
+
+/*
+ * 8-bit is just too small. You can try the Frobenius test
+ * but that frobenius test can fail, too, for the same reason.
+ */
+#ifndef MP_8BIT
+
+/*
+ * multiply bigint a with int d and put the result in c
+ * Like mp_mul_d() but with a signed long as the small input
+ */
+static mp_err s_mp_mul_si(const mp_int *a, int32_t d, mp_int *c)
+{
+ mp_int t;
+ mp_err err;
+
+ if ((err = mp_init(&t)) != MP_OKAY) {
+ return err;
+ }
+
+ /*
+ * mp_digit might be smaller than a long, which excludes
+ * the use of mp_mul_d() here.
+ */
+ mp_set_i32(&t, d);
+ err = mp_mul(a, &t, c);
+ mp_clear(&t);
+ return err;
+}
+/*
+ Strong Lucas-Selfridge test.
+ returns MP_YES if it is a strong L-S prime, MP_NO if it is composite
+
+ Code ported from Thomas Ray Nicely's implementation of the BPSW test
+ at http://www.trnicely.net/misc/bpsw.html
+
+ Freeware copyright (C) 2016 Thomas R. Nicely <http://www.trnicely.net>.
+ Released into the public domain by the author, who disclaims any legal
+ liability arising from its use
+
+ The multi-line comments are made by Thomas R. Nicely and are copied verbatim.
+ Additional comments marked "CZ" (without the quotes) are by the code-portist.
+
+ (If that name sounds familiar, he is the guy who found the fdiv bug in the
+ Pentium (P5x, I think) Intel processor)
+*/
+mp_err mp_prime_strong_lucas_selfridge(const mp_int *a, mp_bool *result)
+{
+ /* CZ TODO: choose better variable names! */
+ mp_int Dz, gcd, Np1, Uz, Vz, U2mz, V2mz, Qmz, Q2mz, Qkdz, T1z, T2z, T3z, T4z, Q2kdz;
+ /* CZ TODO: Some of them need the full 32 bit, hence the (temporary) exclusion of MP_8BIT */
+ int32_t D, Ds, J, sign, P, Q, r, s, u, Nbits;
+ mp_err err;
+ mp_bool oddness;
+
+ *result = MP_NO;
+ /*
+ Find the first element D in the sequence {5, -7, 9, -11, 13, ...}
+ such that Jacobi(D,N) = -1 (Selfridge's algorithm). Theory
+ indicates that, if N is not a perfect square, D will "nearly
+ always" be "small." Just in case, an overflow trap for D is
+ included.
+ */
+
+ if ((err = mp_init_multi(&Dz, &gcd, &Np1, &Uz, &Vz, &U2mz, &V2mz, &Qmz, &Q2mz, &Qkdz, &T1z, &T2z, &T3z, &T4z, &Q2kdz,
+ NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ D = 5;
+ sign = 1;
+
+ for (;;) {
+ Ds = sign * D;
+ sign = -sign;
+ mp_set_u32(&Dz, (uint32_t)D);
+ if ((err = mp_gcd(a, &Dz, &gcd)) != MP_OKAY) goto LBL_LS_ERR;
+
+ /* if 1 < GCD < N then N is composite with factor "D", and
+ Jacobi(D,N) is technically undefined (but often returned
+ as zero). */
+ if ((mp_cmp_d(&gcd, 1uL) == MP_GT) && (mp_cmp(&gcd, a) == MP_LT)) {
+ goto LBL_LS_ERR;
+ }
+ if (Ds < 0) {
+ Dz.sign = MP_NEG;
+ }
+ if ((err = mp_kronecker(&Dz, a, &J)) != MP_OKAY) goto LBL_LS_ERR;
+
+ if (J == -1) {
+ break;
+ }
+ D += 2;
+
+ if (D > (INT_MAX - 2)) {
+ err = MP_VAL;
+ goto LBL_LS_ERR;
+ }
+ }
+
+
+
+ P = 1; /* Selfridge's choice */
+ Q = (1 - Ds) / 4; /* Required so D = P*P - 4*Q */
+
+ /* NOTE: The conditions (a) N does not divide Q, and
+ (b) D is square-free or not a perfect square, are included by
+ some authors; e.g., "Prime numbers and computer methods for
+ factorization," Hans Riesel (2nd ed., 1994, Birkhauser, Boston),
+ p. 130. For this particular application of Lucas sequences,
+ these conditions were found to be immaterial. */
+
+ /* Now calculate N - Jacobi(D,N) = N + 1 (even), and calculate the
+ odd positive integer d and positive integer s for which
+ N + 1 = 2^s*d (similar to the step for N - 1 in Miller's test).
+ The strong Lucas-Selfridge test then returns N as a strong
+ Lucas probable prime (slprp) if any of the following
+ conditions is met: U_d=0, V_d=0, V_2d=0, V_4d=0, V_8d=0,
+ V_16d=0, ..., etc., ending with V_{2^(s-1)*d}=V_{(N+1)/2}=0
+ (all equalities mod N). Thus d is the highest index of U that
+ must be computed (since V_2m is independent of U), compared
+ to U_{N+1} for the standard Lucas-Selfridge test; and no
+ index of V beyond (N+1)/2 is required, just as in the
+ standard Lucas-Selfridge test. However, the quantity Q^d must
+ be computed for use (if necessary) in the latter stages of
+ the test. The result is that the strong Lucas-Selfridge test
+ has a running time only slightly greater (order of 10 %) than
+ that of the standard Lucas-Selfridge test, while producing
+ only (roughly) 30 % as many pseudoprimes (and every strong
+ Lucas pseudoprime is also a standard Lucas pseudoprime). Thus
+ the evidence indicates that the strong Lucas-Selfridge test is
+ more effective than the standard Lucas-Selfridge test, and a
+ Baillie-PSW test based on the strong Lucas-Selfridge test
+ should be more reliable. */
+
+ if ((err = mp_add_d(a, 1uL, &Np1)) != MP_OKAY) goto LBL_LS_ERR;
+ s = mp_cnt_lsb(&Np1);
+
+ /* CZ
+ * This should round towards zero because
+ * Thomas R. Nicely used GMP's mpz_tdiv_q_2exp()
+ * and mp_div_2d() is equivalent. Additionally:
+ * dividing an even number by two does not produce
+ * any leftovers.
+ */
+ if ((err = mp_div_2d(&Np1, s, &Dz, NULL)) != MP_OKAY) goto LBL_LS_ERR;
+ /* We must now compute U_d and V_d. Since d is odd, the accumulated
+ values U and V are initialized to U_1 and V_1 (if the target
+ index were even, U and V would be initialized instead to U_0=0
+ and V_0=2). The values of U_2m and V_2m are also initialized to
+ U_1 and V_1; the FOR loop calculates in succession U_2 and V_2,
+ U_4 and V_4, U_8 and V_8, etc. If the corresponding bits
+ (1, 2, 3, ...) of t are on (the zero bit having been accounted
+ for in the initialization of U and V), these values are then
+ combined with the previous totals for U and V, using the
+ composition formulas for addition of indices. */
+
+ mp_set(&Uz, 1uL); /* U=U_1 */
+ mp_set(&Vz, (mp_digit)P); /* V=V_1 */
+ mp_set(&U2mz, 1uL); /* U_1 */
+ mp_set(&V2mz, (mp_digit)P); /* V_1 */
+
+ mp_set_i32(&Qmz, Q);
+ if ((err = mp_mul_2(&Qmz, &Q2mz)) != MP_OKAY) goto LBL_LS_ERR;
+ /* Initializes calculation of Q^d */
+ mp_set_i32(&Qkdz, Q);
+
+ Nbits = mp_count_bits(&Dz);
+
+ for (u = 1; u < Nbits; u++) { /* zero bit off, already accounted for */
+ /* Formulas for doubling of indices (carried out mod N). Note that
+ * the indices denoted as "2m" are actually powers of 2, specifically
+ * 2^(ul-1) beginning each loop and 2^ul ending each loop.
+ *
+ * U_2m = U_m*V_m
+ * V_2m = V_m*V_m - 2*Q^m
+ */
+
+ if ((err = mp_mul(&U2mz, &V2mz, &U2mz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mod(&U2mz, a, &U2mz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_sqr(&V2mz, &V2mz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_sub(&V2mz, &Q2mz, &V2mz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mod(&V2mz, a, &V2mz)) != MP_OKAY) goto LBL_LS_ERR;
+
+ /* Must calculate powers of Q for use in V_2m, also for Q^d later */
+ if ((err = mp_sqr(&Qmz, &Qmz)) != MP_OKAY) goto LBL_LS_ERR;
+
+ /* prevents overflow */ /* CZ still necessary without a fixed prealloc'd mem.? */
+ if ((err = mp_mod(&Qmz, a, &Qmz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mul_2(&Qmz, &Q2mz)) != MP_OKAY) goto LBL_LS_ERR;
+
+ if (s_mp_get_bit(&Dz, (unsigned int)u) == MP_YES) {
+ /* Formulas for addition of indices (carried out mod N);
+ *
+ * U_(m+n) = (U_m*V_n + U_n*V_m)/2
+ * V_(m+n) = (V_m*V_n + D*U_m*U_n)/2
+ *
+ * Be careful with division by 2 (mod N)!
+ */
+ if ((err = mp_mul(&U2mz, &Vz, &T1z)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mul(&Uz, &V2mz, &T2z)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mul(&V2mz, &Vz, &T3z)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mul(&U2mz, &Uz, &T4z)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = s_mp_mul_si(&T4z, Ds, &T4z)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_add(&T1z, &T2z, &Uz)) != MP_OKAY) goto LBL_LS_ERR;
+ if (MP_IS_ODD(&Uz)) {
+ if ((err = mp_add(&Uz, a, &Uz)) != MP_OKAY) goto LBL_LS_ERR;
+ }
+ /* CZ
+ * This should round towards negative infinity because
+ * Thomas R. Nicely used GMP's mpz_fdiv_q_2exp().
+ * But mp_div_2() does not do so, it is truncating instead.
+ */
+ oddness = MP_IS_ODD(&Uz) ? MP_YES : MP_NO;
+ if ((err = mp_div_2(&Uz, &Uz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((Uz.sign == MP_NEG) && (oddness != MP_NO)) {
+ if ((err = mp_sub_d(&Uz, 1uL, &Uz)) != MP_OKAY) goto LBL_LS_ERR;
+ }
+ if ((err = mp_add(&T3z, &T4z, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+ if (MP_IS_ODD(&Vz)) {
+ if ((err = mp_add(&Vz, a, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+ }
+ oddness = MP_IS_ODD(&Vz) ? MP_YES : MP_NO;
+ if ((err = mp_div_2(&Vz, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((Vz.sign == MP_NEG) && (oddness != MP_NO)) {
+ if ((err = mp_sub_d(&Vz, 1uL, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+ }
+ if ((err = mp_mod(&Uz, a, &Uz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mod(&Vz, a, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+
+ /* Calculating Q^d for later use */
+ if ((err = mp_mul(&Qkdz, &Qmz, &Qkdz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mod(&Qkdz, a, &Qkdz)) != MP_OKAY) goto LBL_LS_ERR;
+ }
+ }
+
+ /* If U_d or V_d is congruent to 0 mod N, then N is a prime or a
+ strong Lucas pseudoprime. */
+ if (MP_IS_ZERO(&Uz) || MP_IS_ZERO(&Vz)) {
+ *result = MP_YES;
+ goto LBL_LS_ERR;
+ }
+
+ /* NOTE: Ribenboim ("The new book of prime number records," 3rd ed.,
+ 1995/6) omits the condition V0 on p.142, but includes it on
+ p. 130. The condition is NECESSARY; otherwise the test will
+ return false negatives---e.g., the primes 29 and 2000029 will be
+ returned as composite. */
+
+ /* Otherwise, we must compute V_2d, V_4d, V_8d, ..., V_{2^(s-1)*d}
+ by repeated use of the formula V_2m = V_m*V_m - 2*Q^m. If any of
+ these are congruent to 0 mod N, then N is a prime or a strong
+ Lucas pseudoprime. */
+
+ /* Initialize 2*Q^(d*2^r) for V_2m */
+ if ((err = mp_mul_2(&Qkdz, &Q2kdz)) != MP_OKAY) goto LBL_LS_ERR;
+
+ for (r = 1; r < s; r++) {
+ if ((err = mp_sqr(&Vz, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_sub(&Vz, &Q2kdz, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mod(&Vz, a, &Vz)) != MP_OKAY) goto LBL_LS_ERR;
+ if (MP_IS_ZERO(&Vz)) {
+ *result = MP_YES;
+ goto LBL_LS_ERR;
+ }
+ /* Calculate Q^{d*2^r} for next r (final iteration irrelevant). */
+ if (r < (s - 1)) {
+ if ((err = mp_sqr(&Qkdz, &Qkdz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mod(&Qkdz, a, &Qkdz)) != MP_OKAY) goto LBL_LS_ERR;
+ if ((err = mp_mul_2(&Qkdz, &Q2kdz)) != MP_OKAY) goto LBL_LS_ERR;
+ }
+ }
+LBL_LS_ERR:
+ mp_clear_multi(&Q2kdz, &T4z, &T3z, &T2z, &T1z, &Qkdz, &Q2mz, &Qmz, &V2mz, &U2mz, &Vz, &Uz, &Np1, &gcd, &Dz, NULL);
+ return err;
+}
+#endif
+#endif
+#endif
+
+/* End: bn_mp_prime_strong_lucas_selfridge.c */
+
+/* Start: bn_mp_radix_size.c */
+#include "tommath_private.h"
+#ifdef BN_MP_RADIX_SIZE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* returns size of ASCII representation */
+mp_err mp_radix_size(const mp_int *a, int radix, int *size)
+{
+ mp_err err;
+ int digs;
+ mp_int t;
+ mp_digit d;
+
+ *size = 0;
+
+ /* make sure the radix is in range */
+ if ((radix < 2) || (radix > 64)) {
+ return MP_VAL;
+ }
+
+ if (MP_IS_ZERO(a)) {
+ *size = 2;
+ return MP_OKAY;
+ }
+
+ /* special case for binary */
+ if (radix == 2) {
+ *size = (mp_count_bits(a) + ((a->sign == MP_NEG) ? 1 : 0) + 1);
+ return MP_OKAY;
+ }
+
+ /* digs is the digit count */
+ digs = 0;
+
+ /* if it's negative add one for the sign */
+ if (a->sign == MP_NEG) {
+ ++digs;
+ }
+
+ /* init a copy of the input */
+ if ((err = mp_init_copy(&t, a)) != MP_OKAY) {
+ return err;
+ }
+
+ /* force temp to positive */
+ t.sign = MP_ZPOS;
+
+ /* fetch out all of the digits */
+ while (!MP_IS_ZERO(&t)) {
+ if ((err = mp_div_d(&t, (mp_digit)radix, &t, &d)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ ++digs;
+ }
+
+ /* return digs + 1, the 1 is for the NULL byte that would be required. */
+ *size = digs + 1;
+ err = MP_OKAY;
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_radix_size.c */
+
+/* Start: bn_mp_radix_smap.c */
+#include "tommath_private.h"
+#ifdef BN_MP_RADIX_SMAP_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* chars used in radix conversions */
+const char *const mp_s_rmap = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
+const uint8_t mp_s_rmap_reverse[] = {
+ 0xff, 0xff, 0xff, 0x3e, 0xff, 0xff, 0xff, 0x3f, /* ()*+,-./ */
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 01234567 */
+ 0x08, 0x09, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 89:;<=>? */
+ 0xff, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, /* @ABCDEFG */
+ 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, /* HIJKLMNO */
+ 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, /* PQRSTUVW */
+ 0x21, 0x22, 0x23, 0xff, 0xff, 0xff, 0xff, 0xff, /* XYZ[\]^_ */
+ 0xff, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, /* `abcdefg */
+ 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, /* hijklmno */
+ 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, /* pqrstuvw */
+ 0x3b, 0x3c, 0x3d, 0xff, 0xff, 0xff, 0xff, 0xff, /* xyz{|}~. */
+};
+const size_t mp_s_rmap_reverse_sz = sizeof(mp_s_rmap_reverse);
+#endif
+
+/* End: bn_mp_radix_smap.c */
+
+/* Start: bn_mp_rand.c */
+#include "tommath_private.h"
+#ifdef BN_MP_RAND_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+mp_err(*s_mp_rand_source)(void *out, size_t size) = s_mp_rand_platform;
+
+void mp_rand_source(mp_err(*source)(void *out, size_t size))
+{
+ s_mp_rand_source = (source == NULL) ? s_mp_rand_platform : source;
+}
+
+mp_err mp_rand(mp_int *a, int digits)
+{
+ int i;
+ mp_err err;
+
+ mp_zero(a);
+
+ if (digits <= 0) {
+ return MP_OKAY;
+ }
+
+ if ((err = mp_grow(a, digits)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = s_mp_rand_source(a->dp, (size_t)digits * sizeof(mp_digit))) != MP_OKAY) {
+ return err;
+ }
+
+ /* TODO: We ensure that the highest digit is nonzero. Should this be removed? */
+ while ((a->dp[digits - 1] & MP_MASK) == 0u) {
+ if ((err = s_mp_rand_source(a->dp + digits - 1, sizeof(mp_digit))) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ a->used = digits;
+ for (i = 0; i < digits; ++i) {
+ a->dp[i] &= MP_MASK;
+ }
+
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_rand.c */
+
+/* Start: bn_mp_read_radix.c */
+#include "tommath_private.h"
+#ifdef BN_MP_READ_RADIX_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#define MP_TOUPPER(c) ((((c) >= 'a') && ((c) <= 'z')) ? (((c) + 'A') - 'a') : (c))
+
+/* read a string [ASCII] in a given radix */
+mp_err mp_read_radix(mp_int *a, const char *str, int radix)
+{
+ mp_err err;
+ int y;
+ mp_sign neg;
+ unsigned pos;
+ char ch;
+
+ /* zero the digit bignum */
+ mp_zero(a);
+
+ /* make sure the radix is ok */
+ if ((radix < 2) || (radix > 64)) {
+ return MP_VAL;
+ }
+
+ /* if the leading digit is a
+ * minus set the sign to negative.
+ */
+ if (*str == '-') {
+ ++str;
+ neg = MP_NEG;
+ } else {
+ neg = MP_ZPOS;
+ }
+
+ /* set the integer to the default of zero */
+ mp_zero(a);
+
+ /* process each digit of the string */
+ while (*str != '\0') {
+ /* if the radix <= 36 the conversion is case insensitive
+ * this allows numbers like 1AB and 1ab to represent the same value
+ * [e.g. in hex]
+ */
+ ch = (radix <= 36) ? (char)MP_TOUPPER((int)*str) : *str;
+ pos = (unsigned)(ch - '(');
+ if (mp_s_rmap_reverse_sz < pos) {
+ break;
+ }
+ y = (int)mp_s_rmap_reverse[pos];
+
+ /* if the char was found in the map
+ * and is less than the given radix add it
+ * to the number, otherwise exit the loop.
+ */
+ if ((y == 0xff) || (y >= radix)) {
+ break;
+ }
+ if ((err = mp_mul_d(a, (mp_digit)radix, a)) != MP_OKAY) {
+ return err;
+ }
+ if ((err = mp_add_d(a, (mp_digit)y, a)) != MP_OKAY) {
+ return err;
+ }
+ ++str;
+ }
+
+ /* if an illegal character was found, fail. */
+ if (!((*str == '\0') || (*str == '\r') || (*str == '\n'))) {
+ mp_zero(a);
+ return MP_VAL;
+ }
+
+ /* set the sign only if a != 0 */
+ if (!MP_IS_ZERO(a)) {
+ a->sign = neg;
+ }
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_read_radix.c */
+
+/* Start: bn_mp_reduce.c */
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* reduces x mod m, assumes 0 < x < m**2, mu is
+ * precomputed via mp_reduce_setup.
+ * From HAC pp.604 Algorithm 14.42
+ */
+mp_err mp_reduce(mp_int *x, const mp_int *m, const mp_int *mu)
+{
+ mp_int q;
+ mp_err err;
+ int um = m->used;
+
+ /* q = x */
+ if ((err = mp_init_copy(&q, x)) != MP_OKAY) {
+ return err;
+ }
+
+ /* q1 = x / b**(k-1) */
+ mp_rshd(&q, um - 1);
+
+ /* according to HAC this optimization is ok */
+ if ((mp_digit)um > ((mp_digit)1 << (MP_DIGIT_BIT - 1))) {
+ if ((err = mp_mul(&q, mu, &q)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+ } else if (MP_HAS(S_MP_MUL_HIGH_DIGS)) {
+ if ((err = s_mp_mul_high_digs(&q, mu, &q, um)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+ } else if (MP_HAS(S_MP_MUL_HIGH_DIGS_FAST)) {
+ if ((err = s_mp_mul_high_digs_fast(&q, mu, &q, um)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+ } else {
+ err = MP_VAL;
+ goto CLEANUP;
+ }
+
+ /* q3 = q2 / b**(k+1) */
+ mp_rshd(&q, um + 1);
+
+ /* x = x mod b**(k+1), quick (no division) */
+ if ((err = mp_mod_2d(x, MP_DIGIT_BIT * (um + 1), x)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+
+ /* q = q * m mod b**(k+1), quick (no division) */
+ if ((err = s_mp_mul_digs(&q, m, &q, um + 1)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+
+ /* x = x - q */
+ if ((err = mp_sub(x, &q, x)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+
+ /* If x < 0, add b**(k+1) to it */
+ if (mp_cmp_d(x, 0uL) == MP_LT) {
+ mp_set(&q, 1uL);
+ if ((err = mp_lshd(&q, um + 1)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+ if ((err = mp_add(x, &q, x)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+ }
+
+ /* Back off if it's too big */
+ while (mp_cmp(x, m) != MP_LT) {
+ if ((err = s_mp_sub(x, m, x)) != MP_OKAY) {
+ goto CLEANUP;
+ }
+ }
+
+CLEANUP:
+ mp_clear(&q);
+
+ return err;
+}
+#endif
+
+/* End: bn_mp_reduce.c */
+
+/* Start: bn_mp_reduce_2k.c */
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_2K_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* reduces a modulo n where n is of the form 2**p - d */
+mp_err mp_reduce_2k(mp_int *a, const mp_int *n, mp_digit d)
+{
+ mp_int q;
+ mp_err err;
+ int p;
+
+ if ((err = mp_init(&q)) != MP_OKAY) {
+ return err;
+ }
+
+ p = mp_count_bits(n);
+top:
+ /* q = a/2**p, a = a mod 2**p */
+ if ((err = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ if (d != 1u) {
+ /* q = q * d */
+ if ((err = mp_mul_d(&q, d, &q)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ }
+
+ /* a = a + q */
+ if ((err = s_mp_add(a, &q, a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ if (mp_cmp_mag(a, n) != MP_LT) {
+ if ((err = s_mp_sub(a, n, a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ goto top;
+ }
+
+LBL_ERR:
+ mp_clear(&q);
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_reduce_2k.c */
+
+/* Start: bn_mp_reduce_2k_l.c */
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_2K_L_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* reduces a modulo n where n is of the form 2**p - d
+ This differs from reduce_2k since "d" can be larger
+ than a single digit.
+*/
+mp_err mp_reduce_2k_l(mp_int *a, const mp_int *n, const mp_int *d)
+{
+ mp_int q;
+ mp_err err;
+ int p;
+
+ if ((err = mp_init(&q)) != MP_OKAY) {
+ return err;
+ }
+
+ p = mp_count_bits(n);
+top:
+ /* q = a/2**p, a = a mod 2**p */
+ if ((err = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ /* q = q * d */
+ if ((err = mp_mul(&q, d, &q)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ /* a = a + q */
+ if ((err = s_mp_add(a, &q, a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ if (mp_cmp_mag(a, n) != MP_LT) {
+ if ((err = s_mp_sub(a, n, a)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ goto top;
+ }
+
+LBL_ERR:
+ mp_clear(&q);
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_reduce_2k_l.c */
+
+/* Start: bn_mp_reduce_2k_setup.c */
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_2K_SETUP_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* determines the setup value */
+mp_err mp_reduce_2k_setup(const mp_int *a, mp_digit *d)
+{
+ mp_err err;
+ mp_int tmp;
+ int p;
+
+ if ((err = mp_init(&tmp)) != MP_OKAY) {
+ return err;
+ }
+
+ p = mp_count_bits(a);
+ if ((err = mp_2expt(&tmp, p)) != MP_OKAY) {
+ mp_clear(&tmp);
+ return err;
+ }
+
+ if ((err = s_mp_sub(&tmp, a, &tmp)) != MP_OKAY) {
+ mp_clear(&tmp);
+ return err;
+ }
+
+ *d = tmp.dp[0];
+ mp_clear(&tmp);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_reduce_2k_setup.c */
+
+/* Start: bn_mp_reduce_2k_setup_l.c */
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_2K_SETUP_L_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* determines the setup value */
+mp_err mp_reduce_2k_setup_l(const mp_int *a, mp_int *d)
+{
+ mp_err err;
+ mp_int tmp;
+
+ if ((err = mp_init(&tmp)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_2expt(&tmp, mp_count_bits(a))) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+ if ((err = s_mp_sub(&tmp, a, d)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+
+LBL_ERR:
+ mp_clear(&tmp);
+ return err;
+}
+#endif
+
+/* End: bn_mp_reduce_2k_setup_l.c */
+
+/* Start: bn_mp_reduce_is_2k.c */
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_IS_2K_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* determines if mp_reduce_2k can be used */
+mp_bool mp_reduce_is_2k(const mp_int *a)
+{
+ int ix, iy, iw;
+ mp_digit iz;
+
+ if (a->used == 0) {
+ return MP_NO;
+ } else if (a->used == 1) {
+ return MP_YES;
+ } else if (a->used > 1) {
+ iy = mp_count_bits(a);
+ iz = 1;
+ iw = 1;
+
+ /* Test every bit from the second digit up, must be 1 */
+ for (ix = MP_DIGIT_BIT; ix < iy; ix++) {
+ if ((a->dp[iw] & iz) == 0u) {
+ return MP_NO;
+ }
+ iz <<= 1;
+ if (iz > MP_DIGIT_MAX) {
+ ++iw;
+ iz = 1;
+ }
+ }
+ return MP_YES;
+ } else {
+ return MP_YES;
+ }
+}
+
+#endif
+
+/* End: bn_mp_reduce_is_2k.c */
+
+/* Start: bn_mp_reduce_is_2k_l.c */
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_IS_2K_L_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* determines if reduce_2k_l can be used */
+mp_bool mp_reduce_is_2k_l(const mp_int *a)
+{
+ int ix, iy;
+
+ if (a->used == 0) {
+ return MP_NO;
+ } else if (a->used == 1) {
+ return MP_YES;
+ } else if (a->used > 1) {
+ /* if more than half of the digits are -1 we're sold */
+ for (iy = ix = 0; ix < a->used; ix++) {
+ if (a->dp[ix] == MP_DIGIT_MAX) {
+ ++iy;
+ }
+ }
+ return (iy >= (a->used/2)) ? MP_YES : MP_NO;
+ } else {
+ return MP_NO;
+ }
+}
+
+#endif
+
+/* End: bn_mp_reduce_is_2k_l.c */
+
+/* Start: bn_mp_reduce_setup.c */
+#include "tommath_private.h"
+#ifdef BN_MP_REDUCE_SETUP_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* pre-calculate the value required for Barrett reduction
+ * For a given modulus "b" it calulates the value required in "a"
+ */
+mp_err mp_reduce_setup(mp_int *a, const mp_int *b)
+{
+ mp_err err;
+ if ((err = mp_2expt(a, b->used * 2 * MP_DIGIT_BIT)) != MP_OKAY) {
+ return err;
+ }
+ return mp_div(a, b, a, NULL);
+}
+#endif
+
+/* End: bn_mp_reduce_setup.c */
+
+/* Start: bn_mp_root_u32.c */
+#include "tommath_private.h"
+#ifdef BN_MP_ROOT_U32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* find the n'th root of an integer
+ *
+ * Result found such that (c)**b <= a and (c+1)**b > a
+ *
+ * This algorithm uses Newton's approximation
+ * x[i+1] = x[i] - f(x[i])/f'(x[i])
+ * which will find the root in log(N) time where
+ * each step involves a fair bit.
+ */
+mp_err mp_root_u32(const mp_int *a, uint32_t b, mp_int *c)
+{
+ mp_int t1, t2, t3, a_;
+ mp_ord cmp;
+ int ilog2;
+ mp_err err;
+
+ /* input must be positive if b is even */
+ if (((b & 1u) == 0u) && (a->sign == MP_NEG)) {
+ return MP_VAL;
+ }
+
+ if ((err = mp_init_multi(&t1, &t2, &t3, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* if a is negative fudge the sign but keep track */
+ a_ = *a;
+ a_.sign = MP_ZPOS;
+
+ /* Compute seed: 2^(log_2(n)/b + 2)*/
+ ilog2 = mp_count_bits(a);
+
+ /*
+ If "b" is larger than INT_MAX it is also larger than
+ log_2(n) because the bit-length of the "n" is measured
+ with an int and hence the root is always < 2 (two).
+ */
+ if (b > (uint32_t)(INT_MAX/2)) {
+ mp_set(c, 1uL);
+ c->sign = a->sign;
+ err = MP_OKAY;
+ goto LBL_ERR;
+ }
+
+ /* "b" is smaller than INT_MAX, we can cast safely */
+ if (ilog2 < (int)b) {
+ mp_set(c, 1uL);
+ c->sign = a->sign;
+ err = MP_OKAY;
+ goto LBL_ERR;
+ }
+ ilog2 = ilog2 / ((int)b);
+ if (ilog2 == 0) {
+ mp_set(c, 1uL);
+ c->sign = a->sign;
+ err = MP_OKAY;
+ goto LBL_ERR;
+ }
+ /* Start value must be larger than root */
+ ilog2 += 2;
+ if ((err = mp_2expt(&t2,ilog2)) != MP_OKAY) goto LBL_ERR;
+ do {
+ /* t1 = t2 */
+ if ((err = mp_copy(&t2, &t1)) != MP_OKAY) goto LBL_ERR;
+
+ /* t2 = t1 - ((t1**b - a) / (b * t1**(b-1))) */
+
+ /* t3 = t1**(b-1) */
+ if ((err = mp_expt_u32(&t1, b - 1u, &t3)) != MP_OKAY) goto LBL_ERR;
+
+ /* numerator */
+ /* t2 = t1**b */
+ if ((err = mp_mul(&t3, &t1, &t2)) != MP_OKAY) goto LBL_ERR;
+
+ /* t2 = t1**b - a */
+ if ((err = mp_sub(&t2, &a_, &t2)) != MP_OKAY) goto LBL_ERR;
+
+ /* denominator */
+ /* t3 = t1**(b-1) * b */
+ if ((err = mp_mul_d(&t3, b, &t3)) != MP_OKAY) goto LBL_ERR;
+
+ /* t3 = (t1**b - a)/(b * t1**(b-1)) */
+ if ((err = mp_div(&t2, &t3, &t3, NULL)) != MP_OKAY) goto LBL_ERR;
+
+ if ((err = mp_sub(&t1, &t3, &t2)) != MP_OKAY) goto LBL_ERR;
+
+ /*
+ Number of rounds is at most log_2(root). If it is more it
+ got stuck, so break out of the loop and do the rest manually.
+ */
+ if (ilog2-- == 0) {
+ break;
+ }
+ } while (mp_cmp(&t1, &t2) != MP_EQ);
+
+ /* result can be off by a few so check */
+ /* Loop beneath can overshoot by one if found root is smaller than actual root */
+ for (;;) {
+ if ((err = mp_expt_u32(&t1, b, &t2)) != MP_OKAY) goto LBL_ERR;
+ cmp = mp_cmp(&t2, &a_);
+ if (cmp == MP_EQ) {
+ err = MP_OKAY;
+ goto LBL_ERR;
+ }
+ if (cmp == MP_LT) {
+ if ((err = mp_add_d(&t1, 1uL, &t1)) != MP_OKAY) goto LBL_ERR;
+ } else {
+ break;
+ }
+ }
+ /* correct overshoot from above or from recurrence */
+ for (;;) {
+ if ((err = mp_expt_u32(&t1, b, &t2)) != MP_OKAY) goto LBL_ERR;
+ if (mp_cmp(&t2, &a_) == MP_GT) {
+ if ((err = mp_sub_d(&t1, 1uL, &t1)) != MP_OKAY) goto LBL_ERR;
+ } else {
+ break;
+ }
+ }
+
+ /* set the result */
+ mp_exch(&t1, c);
+
+ /* set the sign of the result */
+ c->sign = a->sign;
+
+ err = MP_OKAY;
+
+LBL_ERR:
+ mp_clear_multi(&t1, &t2, &t3, NULL);
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_root_u32.c */
+
+/* Start: bn_mp_rshd.c */
+#include "tommath_private.h"
+#ifdef BN_MP_RSHD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* shift right a certain amount of digits */
+void mp_rshd(mp_int *a, int b)
+{
+ int x;
+ mp_digit *bottom, *top;
+
+ /* if b <= 0 then ignore it */
+ if (b <= 0) {
+ return;
+ }
+
+ /* if b > used then simply zero it and return */
+ if (a->used <= b) {
+ mp_zero(a);
+ return;
+ }
+
+ /* shift the digits down */
+
+ /* bottom */
+ bottom = a->dp;
+
+ /* top [offset into digits] */
+ top = a->dp + b;
+
+ /* this is implemented as a sliding window where
+ * the window is b-digits long and digits from
+ * the top of the window are copied to the bottom
+ *
+ * e.g.
+
+ b-2 | b-1 | b0 | b1 | b2 | ... | bb | ---->
+ /\ | ---->
+ \-------------------/ ---->
+ */
+ for (x = 0; x < (a->used - b); x++) {
+ *bottom++ = *top++;
+ }
+
+ /* zero the top digits */
+ MP_ZERO_DIGITS(bottom, a->used - x);
+
+ /* remove excess digits */
+ a->used -= b;
+}
+#endif
+
+/* End: bn_mp_rshd.c */
+
+/* Start: bn_mp_sbin_size.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SBIN_SIZE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* get the size for an signed equivalent */
+size_t mp_sbin_size(const mp_int *a)
+{
+ return 1u + mp_ubin_size(a);
+}
+#endif
+
+/* End: bn_mp_sbin_size.c */
+
+/* Start: bn_mp_set.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SET_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* set to a digit */
+void mp_set(mp_int *a, mp_digit b)
+{
+ a->dp[0] = b & MP_MASK;
+ a->sign = MP_ZPOS;
+ a->used = (a->dp[0] != 0u) ? 1 : 0;
+ MP_ZERO_DIGITS(a->dp + a->used, a->alloc - a->used);
+}
+#endif
+
+/* End: bn_mp_set.c */
+
+/* Start: bn_mp_set_double.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SET_DOUBLE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#if defined(__STDC_IEC_559__) || defined(__GCC_IEC_559)
+mp_err mp_set_double(mp_int *a, double b)
+{
+ uint64_t frac;
+ int exp;
+ mp_err err;
+ union {
+ double dbl;
+ uint64_t bits;
+ } cast;
+ cast.dbl = b;
+
+ exp = (int)((unsigned)(cast.bits >> 52) & 0x7FFu);
+ frac = (cast.bits & ((1uLL << 52) - 1uLL)) | (1uLL << 52);
+
+ if (exp == 0x7FF) { /* +-inf, NaN */
+ return MP_VAL;
+ }
+ exp -= 1023 + 52;
+
+ mp_set_u64(a, frac);
+
+ err = (exp < 0) ? mp_div_2d(a, -exp, a, NULL) : mp_mul_2d(a, exp, a);
+ if (err != MP_OKAY) {
+ return err;
+ }
+
+ if (((cast.bits >> 63) != 0uLL) && !MP_IS_ZERO(a)) {
+ a->sign = MP_NEG;
+ }
+
+ return MP_OKAY;
+}
+#else
+/* pragma message() not supported by several compilers (in mostly older but still used versions) */
+# ifdef _MSC_VER
+# pragma message("mp_set_double implementation is only available on platforms with IEEE754 floating point format")
+# else
+# warning "mp_set_double implementation is only available on platforms with IEEE754 floating point format"
+# endif
+#endif
+#endif
+
+/* End: bn_mp_set_double.c */
+
+/* Start: bn_mp_set_i32.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SET_I32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_SIGNED(mp_set_i32, mp_set_u32, int32_t, uint32_t)
+#endif
+
+/* End: bn_mp_set_i32.c */
+
+/* Start: bn_mp_set_i64.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SET_I64_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_SIGNED(mp_set_i64, mp_set_u64, int64_t, uint64_t)
+#endif
+
+/* End: bn_mp_set_i64.c */
+
+/* Start: bn_mp_set_l.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SET_L_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_SIGNED(mp_set_l, mp_set_ul, long, unsigned long)
+#endif
+
+/* End: bn_mp_set_l.c */
+
+/* Start: bn_mp_set_ll.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SET_LL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_SIGNED(mp_set_ll, mp_set_ull, long long, unsigned long long)
+#endif
+
+/* End: bn_mp_set_ll.c */
+
+/* Start: bn_mp_set_u32.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SET_U32_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_UNSIGNED(mp_set_u32, uint32_t)
+#endif
+
+/* End: bn_mp_set_u32.c */
+
+/* Start: bn_mp_set_u64.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SET_U64_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_UNSIGNED(mp_set_u64, uint64_t)
+#endif
+
+/* End: bn_mp_set_u64.c */
+
+/* Start: bn_mp_set_ul.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SET_UL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_UNSIGNED(mp_set_ul, unsigned long)
+#endif
+
+/* End: bn_mp_set_ul.c */
+
+/* Start: bn_mp_set_ull.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SET_ULL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+MP_SET_UNSIGNED(mp_set_ull, unsigned long long)
+#endif
+
+/* End: bn_mp_set_ull.c */
+
+/* Start: bn_mp_shrink.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SHRINK_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* shrink a bignum */
+mp_err mp_shrink(mp_int *a)
+{
+ mp_digit *tmp;
+ int alloc = MP_MAX(MP_MIN_PREC, a->used);
+ if (a->alloc != alloc) {
+ if ((tmp = (mp_digit *) MP_REALLOC(a->dp,
+ (size_t)a->alloc * sizeof(mp_digit),
+ (size_t)alloc * sizeof(mp_digit))) == NULL) {
+ return MP_MEM;
+ }
+ a->dp = tmp;
+ a->alloc = alloc;
+ }
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_shrink.c */
+
+/* Start: bn_mp_signed_rsh.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SIGNED_RSH_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* shift right by a certain bit count with sign extension */
+mp_err mp_signed_rsh(const mp_int *a, int b, mp_int *c)
+{
+ mp_err res;
+ if (a->sign == MP_ZPOS) {
+ return mp_div_2d(a, b, c, NULL);
+ }
+
+ res = mp_add_d(a, 1uL, c);
+ if (res != MP_OKAY) {
+ return res;
+ }
+
+ res = mp_div_2d(c, b, c, NULL);
+ return (res == MP_OKAY) ? mp_sub_d(c, 1uL, c) : res;
+}
+#endif
+
+/* End: bn_mp_signed_rsh.c */
+
+/* Start: bn_mp_sqr.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SQR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* computes b = a*a */
+mp_err mp_sqr(const mp_int *a, mp_int *b)
+{
+ mp_err err;
+ if (MP_HAS(S_MP_TOOM_SQR) && /* use Toom-Cook? */
+ (a->used >= MP_TOOM_SQR_CUTOFF)) {
+ err = s_mp_toom_sqr(a, b);
+ } else if (MP_HAS(S_MP_KARATSUBA_SQR) && /* Karatsuba? */
+ (a->used >= MP_KARATSUBA_SQR_CUTOFF)) {
+ err = s_mp_karatsuba_sqr(a, b);
+ } else if (MP_HAS(S_MP_SQR_FAST) && /* can we use the fast comba multiplier? */
+ (((a->used * 2) + 1) < MP_WARRAY) &&
+ (a->used < (MP_MAXFAST / 2))) {
+ err = s_mp_sqr_fast(a, b);
+ } else if (MP_HAS(S_MP_SQR)) {
+ err = s_mp_sqr(a, b);
+ } else {
+ err = MP_VAL;
+ }
+ b->sign = MP_ZPOS;
+ return err;
+}
+#endif
+
+/* End: bn_mp_sqr.c */
+
+/* Start: bn_mp_sqrmod.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SQRMOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* c = a * a (mod b) */
+mp_err mp_sqrmod(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_err err;
+ mp_int t;
+
+ if ((err = mp_init(&t)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_sqr(a, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ err = mp_mod(&t, b, c);
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+#endif
+
+/* End: bn_mp_sqrmod.c */
+
+/* Start: bn_mp_sqrt.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SQRT_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* this function is less generic than mp_n_root, simpler and faster */
+mp_err mp_sqrt(const mp_int *arg, mp_int *ret)
+{
+ mp_err err;
+ mp_int t1, t2;
+
+ /* must be positive */
+ if (arg->sign == MP_NEG) {
+ return MP_VAL;
+ }
+
+ /* easy out */
+ if (MP_IS_ZERO(arg)) {
+ mp_zero(ret);
+ return MP_OKAY;
+ }
+
+ if ((err = mp_init_copy(&t1, arg)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_init(&t2)) != MP_OKAY) {
+ goto E2;
+ }
+
+ /* First approx. (not very bad for large arg) */
+ mp_rshd(&t1, t1.used/2);
+
+ /* t1 > 0 */
+ if ((err = mp_div(arg, &t1, &t2, NULL)) != MP_OKAY) {
+ goto E1;
+ }
+ if ((err = mp_add(&t1, &t2, &t1)) != MP_OKAY) {
+ goto E1;
+ }
+ if ((err = mp_div_2(&t1, &t1)) != MP_OKAY) {
+ goto E1;
+ }
+ /* And now t1 > sqrt(arg) */
+ do {
+ if ((err = mp_div(arg, &t1, &t2, NULL)) != MP_OKAY) {
+ goto E1;
+ }
+ if ((err = mp_add(&t1, &t2, &t1)) != MP_OKAY) {
+ goto E1;
+ }
+ if ((err = mp_div_2(&t1, &t1)) != MP_OKAY) {
+ goto E1;
+ }
+ /* t1 >= sqrt(arg) >= t2 at this point */
+ } while (mp_cmp_mag(&t1, &t2) == MP_GT);
+
+ mp_exch(&t1, ret);
+
+E1:
+ mp_clear(&t2);
+E2:
+ mp_clear(&t1);
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_sqrt.c */
+
+/* Start: bn_mp_sqrtmod_prime.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SQRTMOD_PRIME_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Tonelli-Shanks algorithm
+ * https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm
+ * https://gmplib.org/list-archives/gmp-discuss/2013-April/005300.html
+ *
+ */
+
+mp_err mp_sqrtmod_prime(const mp_int *n, const mp_int *prime, mp_int *ret)
+{
+ mp_err err;
+ int legendre;
+ mp_int t1, C, Q, S, Z, M, T, R, two;
+ mp_digit i;
+
+ /* first handle the simple cases */
+ if (mp_cmp_d(n, 0uL) == MP_EQ) {
+ mp_zero(ret);
+ return MP_OKAY;
+ }
+ if (mp_cmp_d(prime, 2uL) == MP_EQ) return MP_VAL; /* prime must be odd */
+ if ((err = mp_kronecker(n, prime, &legendre)) != MP_OKAY) return err;
+ if (legendre == -1) return MP_VAL; /* quadratic non-residue mod prime */
+
+ if ((err = mp_init_multi(&t1, &C, &Q, &S, &Z, &M, &T, &R, &two, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* SPECIAL CASE: if prime mod 4 == 3
+ * compute directly: err = n^(prime+1)/4 mod prime
+ * Handbook of Applied Cryptography algorithm 3.36
+ */
+ if ((err = mp_mod_d(prime, 4uL, &i)) != MP_OKAY) goto cleanup;
+ if (i == 3u) {
+ if ((err = mp_add_d(prime, 1uL, &t1)) != MP_OKAY) goto cleanup;
+ if ((err = mp_div_2(&t1, &t1)) != MP_OKAY) goto cleanup;
+ if ((err = mp_div_2(&t1, &t1)) != MP_OKAY) goto cleanup;
+ if ((err = mp_exptmod(n, &t1, prime, ret)) != MP_OKAY) goto cleanup;
+ err = MP_OKAY;
+ goto cleanup;
+ }
+
+ /* NOW: Tonelli-Shanks algorithm */
+
+ /* factor out powers of 2 from prime-1, defining Q and S as: prime-1 = Q*2^S */
+ if ((err = mp_copy(prime, &Q)) != MP_OKAY) goto cleanup;
+ if ((err = mp_sub_d(&Q, 1uL, &Q)) != MP_OKAY) goto cleanup;
+ /* Q = prime - 1 */
+ mp_zero(&S);
+ /* S = 0 */
+ while (MP_IS_EVEN(&Q)) {
+ if ((err = mp_div_2(&Q, &Q)) != MP_OKAY) goto cleanup;
+ /* Q = Q / 2 */
+ if ((err = mp_add_d(&S, 1uL, &S)) != MP_OKAY) goto cleanup;
+ /* S = S + 1 */
+ }
+
+ /* find a Z such that the Legendre symbol (Z|prime) == -1 */
+ mp_set_u32(&Z, 2u);
+ /* Z = 2 */
+ for (;;) {
+ if ((err = mp_kronecker(&Z, prime, &legendre)) != MP_OKAY) goto cleanup;
+ if (legendre == -1) break;
+ if ((err = mp_add_d(&Z, 1uL, &Z)) != MP_OKAY) goto cleanup;
+ /* Z = Z + 1 */
+ }
+
+ if ((err = mp_exptmod(&Z, &Q, prime, &C)) != MP_OKAY) goto cleanup;
+ /* C = Z ^ Q mod prime */
+ if ((err = mp_add_d(&Q, 1uL, &t1)) != MP_OKAY) goto cleanup;
+ if ((err = mp_div_2(&t1, &t1)) != MP_OKAY) goto cleanup;
+ /* t1 = (Q + 1) / 2 */
+ if ((err = mp_exptmod(n, &t1, prime, &R)) != MP_OKAY) goto cleanup;
+ /* R = n ^ ((Q + 1) / 2) mod prime */
+ if ((err = mp_exptmod(n, &Q, prime, &T)) != MP_OKAY) goto cleanup;
+ /* T = n ^ Q mod prime */
+ if ((err = mp_copy(&S, &M)) != MP_OKAY) goto cleanup;
+ /* M = S */
+ mp_set_u32(&two, 2u);
+
+ for (;;) {
+ if ((err = mp_copy(&T, &t1)) != MP_OKAY) goto cleanup;
+ i = 0;
+ for (;;) {
+ if (mp_cmp_d(&t1, 1uL) == MP_EQ) break;
+ if ((err = mp_exptmod(&t1, &two, prime, &t1)) != MP_OKAY) goto cleanup;
+ i++;
+ }
+ if (i == 0u) {
+ if ((err = mp_copy(&R, ret)) != MP_OKAY) goto cleanup;
+ err = MP_OKAY;
+ goto cleanup;
+ }
+ if ((err = mp_sub_d(&M, i, &t1)) != MP_OKAY) goto cleanup;
+ if ((err = mp_sub_d(&t1, 1uL, &t1)) != MP_OKAY) goto cleanup;
+ if ((err = mp_exptmod(&two, &t1, prime, &t1)) != MP_OKAY) goto cleanup;
+ /* t1 = 2 ^ (M - i - 1) */
+ if ((err = mp_exptmod(&C, &t1, prime, &t1)) != MP_OKAY) goto cleanup;
+ /* t1 = C ^ (2 ^ (M - i - 1)) mod prime */
+ if ((err = mp_sqrmod(&t1, prime, &C)) != MP_OKAY) goto cleanup;
+ /* C = (t1 * t1) mod prime */
+ if ((err = mp_mulmod(&R, &t1, prime, &R)) != MP_OKAY) goto cleanup;
+ /* R = (R * t1) mod prime */
+ if ((err = mp_mulmod(&T, &C, prime, &T)) != MP_OKAY) goto cleanup;
+ /* T = (T * C) mod prime */
+ mp_set(&M, i);
+ /* M = i */
+ }
+
+cleanup:
+ mp_clear_multi(&t1, &C, &Q, &S, &Z, &M, &T, &R, &two, NULL);
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_sqrtmod_prime.c */
+
+/* Start: bn_mp_sub.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SUB_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* high level subtraction (handles signs) */
+mp_err mp_sub(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_sign sa = a->sign, sb = b->sign;
+ mp_err err;
+
+ if (sa != sb) {
+ /* subtract a negative from a positive, OR */
+ /* subtract a positive from a negative. */
+ /* In either case, ADD their magnitudes, */
+ /* and use the sign of the first number. */
+ c->sign = sa;
+ err = s_mp_add(a, b, c);
+ } else {
+ /* subtract a positive from a positive, OR */
+ /* subtract a negative from a negative. */
+ /* First, take the difference between their */
+ /* magnitudes, then... */
+ if (mp_cmp_mag(a, b) != MP_LT) {
+ /* Copy the sign from the first */
+ c->sign = sa;
+ /* The first has a larger or equal magnitude */
+ err = s_mp_sub(a, b, c);
+ } else {
+ /* The result has the *opposite* sign from */
+ /* the first number. */
+ c->sign = (sa == MP_ZPOS) ? MP_NEG : MP_ZPOS;
+ /* The second has a larger magnitude */
+ err = s_mp_sub(b, a, c);
+ }
+ }
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_sub.c */
+
+/* Start: bn_mp_sub_d.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SUB_D_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* single digit subtraction */
+mp_err mp_sub_d(const mp_int *a, mp_digit b, mp_int *c)
+{
+ mp_digit *tmpa, *tmpc;
+ mp_err err;
+ int ix, oldused;
+
+ /* grow c as required */
+ if (c->alloc < (a->used + 1)) {
+ if ((err = mp_grow(c, a->used + 1)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* if a is negative just do an unsigned
+ * addition [with fudged signs]
+ */
+ if (a->sign == MP_NEG) {
+ mp_int a_ = *a;
+ a_.sign = MP_ZPOS;
+ err = mp_add_d(&a_, b, c);
+ c->sign = MP_NEG;
+
+ /* clamp */
+ mp_clamp(c);
+
+ return err;
+ }
+
+ /* setup regs */
+ oldused = c->used;
+ tmpa = a->dp;
+ tmpc = c->dp;
+
+ /* if a <= b simply fix the single digit */
+ if (((a->used == 1) && (a->dp[0] <= b)) || (a->used == 0)) {
+ if (a->used == 1) {
+ *tmpc++ = b - *tmpa;
+ } else {
+ *tmpc++ = b;
+ }
+ ix = 1;
+
+ /* negative/1digit */
+ c->sign = MP_NEG;
+ c->used = 1;
+ } else {
+ mp_digit mu = b;
+
+ /* positive/size */
+ c->sign = MP_ZPOS;
+ c->used = a->used;
+
+ /* subtract digits, mu is carry */
+ for (ix = 0; ix < a->used; ix++) {
+ *tmpc = *tmpa++ - mu;
+ mu = *tmpc >> (MP_SIZEOF_BITS(mp_digit) - 1u);
+ *tmpc++ &= MP_MASK;
+ }
+ }
+
+ /* zero excess digits */
+ MP_ZERO_DIGITS(tmpc, oldused - ix);
+
+ mp_clamp(c);
+ return MP_OKAY;
+}
+
+#endif
+
+/* End: bn_mp_sub_d.c */
+
+/* Start: bn_mp_submod.c */
+#include "tommath_private.h"
+#ifdef BN_MP_SUBMOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* d = a - b (mod c) */
+mp_err mp_submod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d)
+{
+ mp_err err;
+ mp_int t;
+
+ if ((err = mp_init(&t)) != MP_OKAY) {
+ return err;
+ }
+
+ if ((err = mp_sub(a, b, &t)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ err = mp_mod(&t, c, d);
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+#endif
+
+/* End: bn_mp_submod.c */
+
+/* Start: bn_mp_to_radix.c */
+#include "tommath_private.h"
+#ifdef BN_MP_TO_RADIX_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* stores a bignum as a ASCII string in a given radix (2..64)
+ *
+ * Stores upto "size - 1" chars and always a NULL byte, puts the number of characters
+ * written, including the '\0', in "written".
+ */
+mp_err mp_to_radix(const mp_int *a, char *str, size_t maxlen, size_t *written, int radix)
+{
+ size_t digs;
+ mp_err err;
+ mp_int t;
+ mp_digit d;
+ char *_s = str;
+
+ /* check range of radix and size*/
+ if (maxlen < 2u) {
+ return MP_BUF;
+ }
+ if ((radix < 2) || (radix > 64)) {
+ return MP_VAL;
+ }
+
+ /* quick out if its zero */
+ if (MP_IS_ZERO(a)) {
+ *str++ = '0';
+ *str = '\0';
+ if (written != NULL) {
+ *written = 2u;
+ }
+ return MP_OKAY;
+ }
+
+ if ((err = mp_init_copy(&t, a)) != MP_OKAY) {
+ return err;
+ }
+
+ /* if it is negative output a - */
+ if (t.sign == MP_NEG) {
+ /* we have to reverse our digits later... but not the - sign!! */
+ ++_s;
+
+ /* store the flag and mark the number as positive */
+ *str++ = '-';
+ t.sign = MP_ZPOS;
+
+ /* subtract a char */
+ --maxlen;
+ }
+ digs = 0u;
+ while (!MP_IS_ZERO(&t)) {
+ if (--maxlen < 1u) {
+ /* no more room */
+ err = MP_BUF;
+ goto LBL_ERR;
+ }
+ if ((err = mp_div_d(&t, (mp_digit)radix, &t, &d)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ *str++ = mp_s_rmap[d];
+ ++digs;
+ }
+ /* reverse the digits of the string. In this case _s points
+ * to the first digit [exluding the sign] of the number
+ */
+ s_mp_reverse((unsigned char *)_s, digs);
+
+ /* append a NULL so the string is properly terminated */
+ *str = '\0';
+ digs++;
+
+ if (written != NULL) {
+ *written = (a->sign == MP_NEG) ? (digs + 1u): digs;
+ }
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+
+#endif
+
+/* End: bn_mp_to_radix.c */
+
+/* Start: bn_mp_to_sbin.c */
+#include "tommath_private.h"
+#ifdef BN_MP_TO_SBIN_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* store in signed [big endian] format */
+mp_err mp_to_sbin(const mp_int *a, unsigned char *buf, size_t maxlen, size_t *written)
+{
+ mp_err err;
+ if (maxlen == 0u) {
+ return MP_BUF;
+ }
+ if ((err = mp_to_ubin(a, buf + 1, maxlen - 1u, written)) != MP_OKAY) {
+ return err;
+ }
+ if (written != NULL) {
+ (*written)++;
+ }
+ buf[0] = (a->sign == MP_ZPOS) ? (unsigned char)0 : (unsigned char)1;
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_to_sbin.c */
+
+/* Start: bn_mp_to_ubin.c */
+#include "tommath_private.h"
+#ifdef BN_MP_TO_UBIN_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* store in unsigned [big endian] format */
+mp_err mp_to_ubin(const mp_int *a, unsigned char *buf, size_t maxlen, size_t *written)
+{
+ size_t x, count;
+ mp_err err;
+ mp_int t;
+
+ count = mp_ubin_size(a);
+ if (count > maxlen) {
+ return MP_BUF;
+ }
+
+ if ((err = mp_init_copy(&t, a)) != MP_OKAY) {
+ return err;
+ }
+
+ for (x = count; x --> 0u;) {
+#ifndef MP_8BIT
+ buf[x] = (unsigned char)(t.dp[0] & 255u);
+#else
+ buf[x] = (unsigned char)(t.dp[0] | ((t.dp[1] & 1u) << 7));
+#endif
+ if ((err = mp_div_2d(&t, 8, &t, NULL)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ }
+
+ if (written != NULL) {
+ *written = count;
+ }
+
+LBL_ERR:
+ mp_clear(&t);
+ return err;
+}
+#endif
+
+/* End: bn_mp_to_ubin.c */
+
+/* Start: bn_mp_ubin_size.c */
+#include "tommath_private.h"
+#ifdef BN_MP_UBIN_SIZE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* get the size for an unsigned equivalent */
+size_t mp_ubin_size(const mp_int *a)
+{
+ size_t size = (size_t)mp_count_bits(a);
+ return (size / 8u) + (((size & 7u) != 0u) ? 1u : 0u);
+}
+#endif
+
+/* End: bn_mp_ubin_size.c */
+
+/* Start: bn_mp_unpack.c */
+#include "tommath_private.h"
+#ifdef BN_MP_UNPACK_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* based on gmp's mpz_import.
+ * see http://gmplib.org/manual/Integer-Import-and-Export.html
+ */
+mp_err mp_unpack(mp_int *rop, size_t count, mp_order order, size_t size,
+ mp_endian endian, size_t nails, const void *op)
+{
+ mp_err err;
+ size_t odd_nails, nail_bytes, i, j;
+ unsigned char odd_nail_mask;
+
+ mp_zero(rop);
+
+ if (endian == MP_NATIVE_ENDIAN) {
+ MP_GET_ENDIANNESS(endian);
+ }
+
+ odd_nails = (nails % 8u);
+ odd_nail_mask = 0xff;
+ for (i = 0; i < odd_nails; ++i) {
+ odd_nail_mask ^= (unsigned char)(1u << (7u - i));
+ }
+ nail_bytes = nails / 8u;
+
+ for (i = 0; i < count; ++i) {
+ for (j = 0; j < (size - nail_bytes); ++j) {
+ unsigned char byte = *((const unsigned char *)op +
+ (((order == MP_MSB_FIRST) ? i : ((count - 1u) - i)) * size) +
+ ((endian == MP_BIG_ENDIAN) ? (j + nail_bytes) : (((size - 1u) - j) - nail_bytes)));
+
+ if ((err = mp_mul_2d(rop, (j == 0u) ? (int)(8u - odd_nails) : 8, rop)) != MP_OKAY) {
+ return err;
+ }
+
+ rop->dp[0] |= (j == 0u) ? (mp_digit)(byte & odd_nail_mask) : (mp_digit)byte;
+ rop->used += 1;
+ }
+ }
+
+ mp_clamp(rop);
+
+ return MP_OKAY;
+}
+
+#endif
+
+/* End: bn_mp_unpack.c */
+
+/* Start: bn_mp_xor.c */
+#include "tommath_private.h"
+#ifdef BN_MP_XOR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* two complement xor */
+mp_err mp_xor(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ int used = MP_MAX(a->used, b->used) + 1, i;
+ mp_err err;
+ mp_digit ac = 1, bc = 1, cc = 1;
+ mp_sign csign = (a->sign != b->sign) ? MP_NEG : MP_ZPOS;
+
+ if (c->alloc < used) {
+ if ((err = mp_grow(c, used)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ for (i = 0; i < used; i++) {
+ mp_digit x, y;
+
+ /* convert to two complement if negative */
+ if (a->sign == MP_NEG) {
+ ac += (i >= a->used) ? MP_MASK : (~a->dp[i] & MP_MASK);
+ x = ac & MP_MASK;
+ ac >>= MP_DIGIT_BIT;
+ } else {
+ x = (i >= a->used) ? 0uL : a->dp[i];
+ }
+
+ /* convert to two complement if negative */
+ if (b->sign == MP_NEG) {
+ bc += (i >= b->used) ? MP_MASK : (~b->dp[i] & MP_MASK);
+ y = bc & MP_MASK;
+ bc >>= MP_DIGIT_BIT;
+ } else {
+ y = (i >= b->used) ? 0uL : b->dp[i];
+ }
+
+ c->dp[i] = x ^ y;
+
+ /* convert to to sign-magnitude if negative */
+ if (csign == MP_NEG) {
+ cc += ~c->dp[i] & MP_MASK;
+ c->dp[i] = cc & MP_MASK;
+ cc >>= MP_DIGIT_BIT;
+ }
+ }
+
+ c->used = used;
+ c->sign = csign;
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_mp_xor.c */
+
+/* Start: bn_mp_zero.c */
+#include "tommath_private.h"
+#ifdef BN_MP_ZERO_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* set to zero */
+void mp_zero(mp_int *a)
+{
+ a->sign = MP_ZPOS;
+ a->used = 0;
+ MP_ZERO_DIGITS(a->dp, a->alloc);
+}
+#endif
+
+/* End: bn_mp_zero.c */
+
+/* Start: bn_prime_tab.c */
+#include "tommath_private.h"
+#ifdef BN_PRIME_TAB_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+const mp_digit ltm_prime_tab[] = {
+ 0x0002, 0x0003, 0x0005, 0x0007, 0x000B, 0x000D, 0x0011, 0x0013,
+ 0x0017, 0x001D, 0x001F, 0x0025, 0x0029, 0x002B, 0x002F, 0x0035,
+ 0x003B, 0x003D, 0x0043, 0x0047, 0x0049, 0x004F, 0x0053, 0x0059,
+ 0x0061, 0x0065, 0x0067, 0x006B, 0x006D, 0x0071, 0x007F,
+#ifndef MP_8BIT
+ 0x0083,
+ 0x0089, 0x008B, 0x0095, 0x0097, 0x009D, 0x00A3, 0x00A7, 0x00AD,
+ 0x00B3, 0x00B5, 0x00BF, 0x00C1, 0x00C5, 0x00C7, 0x00D3, 0x00DF,
+ 0x00E3, 0x00E5, 0x00E9, 0x00EF, 0x00F1, 0x00FB, 0x0101, 0x0107,
+ 0x010D, 0x010F, 0x0115, 0x0119, 0x011B, 0x0125, 0x0133, 0x0137,
+
+ 0x0139, 0x013D, 0x014B, 0x0151, 0x015B, 0x015D, 0x0161, 0x0167,
+ 0x016F, 0x0175, 0x017B, 0x017F, 0x0185, 0x018D, 0x0191, 0x0199,
+ 0x01A3, 0x01A5, 0x01AF, 0x01B1, 0x01B7, 0x01BB, 0x01C1, 0x01C9,
+ 0x01CD, 0x01CF, 0x01D3, 0x01DF, 0x01E7, 0x01EB, 0x01F3, 0x01F7,
+ 0x01FD, 0x0209, 0x020B, 0x021D, 0x0223, 0x022D, 0x0233, 0x0239,
+ 0x023B, 0x0241, 0x024B, 0x0251, 0x0257, 0x0259, 0x025F, 0x0265,
+ 0x0269, 0x026B, 0x0277, 0x0281, 0x0283, 0x0287, 0x028D, 0x0293,
+ 0x0295, 0x02A1, 0x02A5, 0x02AB, 0x02B3, 0x02BD, 0x02C5, 0x02CF,
+
+ 0x02D7, 0x02DD, 0x02E3, 0x02E7, 0x02EF, 0x02F5, 0x02F9, 0x0301,
+ 0x0305, 0x0313, 0x031D, 0x0329, 0x032B, 0x0335, 0x0337, 0x033B,
+ 0x033D, 0x0347, 0x0355, 0x0359, 0x035B, 0x035F, 0x036D, 0x0371,
+ 0x0373, 0x0377, 0x038B, 0x038F, 0x0397, 0x03A1, 0x03A9, 0x03AD,
+ 0x03B3, 0x03B9, 0x03C7, 0x03CB, 0x03D1, 0x03D7, 0x03DF, 0x03E5,
+ 0x03F1, 0x03F5, 0x03FB, 0x03FD, 0x0407, 0x0409, 0x040F, 0x0419,
+ 0x041B, 0x0425, 0x0427, 0x042D, 0x043F, 0x0443, 0x0445, 0x0449,
+ 0x044F, 0x0455, 0x045D, 0x0463, 0x0469, 0x047F, 0x0481, 0x048B,
+
+ 0x0493, 0x049D, 0x04A3, 0x04A9, 0x04B1, 0x04BD, 0x04C1, 0x04C7,
+ 0x04CD, 0x04CF, 0x04D5, 0x04E1, 0x04EB, 0x04FD, 0x04FF, 0x0503,
+ 0x0509, 0x050B, 0x0511, 0x0515, 0x0517, 0x051B, 0x0527, 0x0529,
+ 0x052F, 0x0551, 0x0557, 0x055D, 0x0565, 0x0577, 0x0581, 0x058F,
+ 0x0593, 0x0595, 0x0599, 0x059F, 0x05A7, 0x05AB, 0x05AD, 0x05B3,
+ 0x05BF, 0x05C9, 0x05CB, 0x05CF, 0x05D1, 0x05D5, 0x05DB, 0x05E7,
+ 0x05F3, 0x05FB, 0x0607, 0x060D, 0x0611, 0x0617, 0x061F, 0x0623,
+ 0x062B, 0x062F, 0x063D, 0x0641, 0x0647, 0x0649, 0x064D, 0x0653
+#endif
+};
+
+#if defined(__GNUC__) && __GNUC__ >= 4
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+const mp_digit *s_mp_prime_tab = ltm_prime_tab;
+#pragma GCC diagnostic pop
+#elif defined(_MSC_VER) && _MSC_VER >= 1500
+#pragma warning(push)
+#pragma warning(disable: 4996)
+const mp_digit *s_mp_prime_tab = ltm_prime_tab;
+#pragma warning(pop)
+#else
+const mp_digit *s_mp_prime_tab = ltm_prime_tab;
+#endif
+
+#endif
+
+/* End: bn_prime_tab.c */
+
+/* Start: bn_s_mp_add.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_ADD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* low level addition, based on HAC pp.594, Algorithm 14.7 */
+mp_err s_mp_add(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ const mp_int *x;
+ mp_err err;
+ int olduse, min, max;
+
+ /* find sizes, we let |a| <= |b| which means we have to sort
+ * them. "x" will point to the input with the most digits
+ */
+ if (a->used > b->used) {
+ min = b->used;
+ max = a->used;
+ x = a;
+ } else {
+ min = a->used;
+ max = b->used;
+ x = b;
+ }
+
+ /* init result */
+ if (c->alloc < (max + 1)) {
+ if ((err = mp_grow(c, max + 1)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* get old used digit count and set new one */
+ olduse = c->used;
+ c->used = max + 1;
+
+ {
+ mp_digit u, *tmpa, *tmpb, *tmpc;
+ int i;
+
+ /* alias for digit pointers */
+
+ /* first input */
+ tmpa = a->dp;
+
+ /* second input */
+ tmpb = b->dp;
+
+ /* destination */
+ tmpc = c->dp;
+
+ /* zero the carry */
+ u = 0;
+ for (i = 0; i < min; i++) {
+ /* Compute the sum at one digit, T[i] = A[i] + B[i] + U */
+ *tmpc = *tmpa++ + *tmpb++ + u;
+
+ /* U = carry bit of T[i] */
+ u = *tmpc >> (mp_digit)MP_DIGIT_BIT;
+
+ /* take away carry bit from T[i] */
+ *tmpc++ &= MP_MASK;
+ }
+
+ /* now copy higher words if any, that is in A+B
+ * if A or B has more digits add those in
+ */
+ if (min != max) {
+ for (; i < max; i++) {
+ /* T[i] = X[i] + U */
+ *tmpc = x->dp[i] + u;
+
+ /* U = carry bit of T[i] */
+ u = *tmpc >> (mp_digit)MP_DIGIT_BIT;
+
+ /* take away carry bit from T[i] */
+ *tmpc++ &= MP_MASK;
+ }
+ }
+
+ /* add carry */
+ *tmpc++ = u;
+
+ /* clear digits above oldused */
+ MP_ZERO_DIGITS(tmpc, olduse - c->used);
+ }
+
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_s_mp_add.c */
+
+/* Start: bn_s_mp_balance_mul.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_BALANCE_MUL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* single-digit multiplication with the smaller number as the single-digit */
+mp_err s_mp_balance_mul(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ int count, len_a, len_b, nblocks, i, j, bsize;
+ mp_int a0, tmp, A, B, r;
+ mp_err err;
+
+ len_a = a->used;
+ len_b = b->used;
+
+ nblocks = MP_MAX(a->used, b->used) / MP_MIN(a->used, b->used);
+ bsize = MP_MIN(a->used, b->used) ;
+
+ if ((err = mp_init_size(&a0, bsize + 2)) != MP_OKAY) {
+ return err;
+ }
+ if ((err = mp_init_multi(&tmp, &r, NULL)) != MP_OKAY) {
+ mp_clear(&a0);
+ return err;
+ }
+
+ /* Make sure that A is the larger one*/
+ if (len_a < len_b) {
+ B = *a;
+ A = *b;
+ } else {
+ A = *a;
+ B = *b;
+ }
+
+ for (i = 0, j=0; i < nblocks; i++) {
+ /* Cut a slice off of a */
+ a0.used = 0;
+ for (count = 0; count < bsize; count++) {
+ a0.dp[count] = A.dp[ j++ ];
+ a0.used++;
+ }
+ mp_clamp(&a0);
+ /* Multiply with b */
+ if ((err = mp_mul(&a0, &B, &tmp)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ /* Shift tmp to the correct position */
+ if ((err = mp_lshd(&tmp, bsize * i)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ /* Add to output. No carry needed */
+ if ((err = mp_add(&r, &tmp, &r)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ }
+ /* The left-overs; there are always left-overs */
+ if (j < A.used) {
+ a0.used = 0;
+ for (count = 0; j < A.used; count++) {
+ a0.dp[count] = A.dp[ j++ ];
+ a0.used++;
+ }
+ mp_clamp(&a0);
+ if ((err = mp_mul(&a0, &B, &tmp)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if ((err = mp_lshd(&tmp, bsize * i)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if ((err = mp_add(&r, &tmp, &r)) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ }
+
+ mp_exch(&r,c);
+LBL_ERR:
+ mp_clear_multi(&a0, &tmp, &r,NULL);
+ return err;
+}
+#endif
+
+/* End: bn_s_mp_balance_mul.c */
+
+/* Start: bn_s_mp_exptmod.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_EXPTMOD_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#ifdef MP_LOW_MEM
+# define TAB_SIZE 32
+# define MAX_WINSIZE 5
+#else
+# define TAB_SIZE 256
+# define MAX_WINSIZE 0
+#endif
+
+mp_err s_mp_exptmod(const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y, int redmode)
+{
+ mp_int M[TAB_SIZE], res, mu;
+ mp_digit buf;
+ mp_err err;
+ int bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
+ mp_err(*redux)(mp_int *x, const mp_int *m, const mp_int *mu);
+
+ /* find window size */
+ x = mp_count_bits(X);
+ if (x <= 7) {
+ winsize = 2;
+ } else if (x <= 36) {
+ winsize = 3;
+ } else if (x <= 140) {
+ winsize = 4;
+ } else if (x <= 450) {
+ winsize = 5;
+ } else if (x <= 1303) {
+ winsize = 6;
+ } else if (x <= 3529) {
+ winsize = 7;
+ } else {
+ winsize = 8;
+ }
+
+ winsize = MAX_WINSIZE ? MP_MIN(MAX_WINSIZE, winsize) : winsize;
+
+ /* init M array */
+ /* init first cell */
+ if ((err = mp_init(&M[1])) != MP_OKAY) {
+ return err;
+ }
+
+ /* now init the second half of the array */
+ for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
+ if ((err = mp_init(&M[x])) != MP_OKAY) {
+ for (y = 1<<(winsize-1); y < x; y++) {
+ mp_clear(&M[y]);
+ }
+ mp_clear(&M[1]);
+ return err;
+ }
+ }
+
+ /* create mu, used for Barrett reduction */
+ if ((err = mp_init(&mu)) != MP_OKAY) goto LBL_M;
+
+ if (redmode == 0) {
+ if ((err = mp_reduce_setup(&mu, P)) != MP_OKAY) goto LBL_MU;
+ redux = mp_reduce;
+ } else {
+ if ((err = mp_reduce_2k_setup_l(P, &mu)) != MP_OKAY) goto LBL_MU;
+ redux = mp_reduce_2k_l;
+ }
+
+ /* create M table
+ *
+ * The M table contains powers of the base,
+ * e.g. M[x] = G**x mod P
+ *
+ * The first half of the table is not
+ * computed though accept for M[0] and M[1]
+ */
+ if ((err = mp_mod(G, P, &M[1])) != MP_OKAY) goto LBL_MU;
+
+ /* compute the value at M[1<<(winsize-1)] by squaring
+ * M[1] (winsize-1) times
+ */
+ if ((err = mp_copy(&M[1], &M[(size_t)1 << (winsize - 1)])) != MP_OKAY) goto LBL_MU;
+
+ for (x = 0; x < (winsize - 1); x++) {
+ /* square it */
+ if ((err = mp_sqr(&M[(size_t)1 << (winsize - 1)],
+ &M[(size_t)1 << (winsize - 1)])) != MP_OKAY) goto LBL_MU;
+
+ /* reduce modulo P */
+ if ((err = redux(&M[(size_t)1 << (winsize - 1)], P, &mu)) != MP_OKAY) goto LBL_MU;
+ }
+
+ /* create upper table, that is M[x] = M[x-1] * M[1] (mod P)
+ * for x = (2**(winsize - 1) + 1) to (2**winsize - 1)
+ */
+ for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
+ if ((err = mp_mul(&M[x - 1], &M[1], &M[x])) != MP_OKAY) goto LBL_MU;
+ if ((err = redux(&M[x], P, &mu)) != MP_OKAY) goto LBL_MU;
+ }
+
+ /* setup result */
+ if ((err = mp_init(&res)) != MP_OKAY) goto LBL_MU;
+ mp_set(&res, 1uL);
+
+ /* set initial mode and bit cnt */
+ mode = 0;
+ bitcnt = 1;
+ buf = 0;
+ digidx = X->used - 1;
+ bitcpy = 0;
+ bitbuf = 0;
+
+ for (;;) {
+ /* grab next digit as required */
+ if (--bitcnt == 0) {
+ /* if digidx == -1 we are out of digits */
+ if (digidx == -1) {
+ break;
+ }
+ /* read next digit and reset the bitcnt */
+ buf = X->dp[digidx--];
+ bitcnt = (int)MP_DIGIT_BIT;
+ }
+
+ /* grab the next msb from the exponent */
+ y = (buf >> (mp_digit)(MP_DIGIT_BIT - 1)) & 1uL;
+ buf <<= (mp_digit)1;
+
+ /* if the bit is zero and mode == 0 then we ignore it
+ * These represent the leading zero bits before the first 1 bit
+ * in the exponent. Technically this opt is not required but it
+ * does lower the # of trivial squaring/reductions used
+ */
+ if ((mode == 0) && (y == 0)) {
+ continue;
+ }
+
+ /* if the bit is zero and mode == 1 then we square */
+ if ((mode == 1) && (y == 0)) {
+ if ((err = mp_sqr(&res, &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, &mu)) != MP_OKAY) goto LBL_RES;
+ continue;
+ }
+
+ /* else we add it to the window */
+ bitbuf |= (y << (winsize - ++bitcpy));
+ mode = 2;
+
+ if (bitcpy == winsize) {
+ /* ok window is filled so square as required and multiply */
+ /* square first */
+ for (x = 0; x < winsize; x++) {
+ if ((err = mp_sqr(&res, &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, &mu)) != MP_OKAY) goto LBL_RES;
+ }
+
+ /* then multiply */
+ if ((err = mp_mul(&res, &M[bitbuf], &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, &mu)) != MP_OKAY) goto LBL_RES;
+
+ /* empty window and reset */
+ bitcpy = 0;
+ bitbuf = 0;
+ mode = 1;
+ }
+ }
+
+ /* if bits remain then square/multiply */
+ if ((mode == 2) && (bitcpy > 0)) {
+ /* square then multiply if the bit is set */
+ for (x = 0; x < bitcpy; x++) {
+ if ((err = mp_sqr(&res, &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, &mu)) != MP_OKAY) goto LBL_RES;
+
+ bitbuf <<= 1;
+ if ((bitbuf & (1 << winsize)) != 0) {
+ /* then multiply */
+ if ((err = mp_mul(&res, &M[1], &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, &mu)) != MP_OKAY) goto LBL_RES;
+ }
+ }
+ }
+
+ mp_exch(&res, Y);
+ err = MP_OKAY;
+LBL_RES:
+ mp_clear(&res);
+LBL_MU:
+ mp_clear(&mu);
+LBL_M:
+ mp_clear(&M[1]);
+ for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
+ mp_clear(&M[x]);
+ }
+ return err;
+}
+#endif
+
+/* End: bn_s_mp_exptmod.c */
+
+/* Start: bn_s_mp_exptmod_fast.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_EXPTMOD_FAST_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* computes Y == G**X mod P, HAC pp.616, Algorithm 14.85
+ *
+ * Uses a left-to-right k-ary sliding window to compute the modular exponentiation.
+ * The value of k changes based on the size of the exponent.
+ *
+ * Uses Montgomery or Diminished Radix reduction [whichever appropriate]
+ */
+
+#ifdef MP_LOW_MEM
+# define TAB_SIZE 32
+# define MAX_WINSIZE 5
+#else
+# define TAB_SIZE 256
+# define MAX_WINSIZE 0
+#endif
+
+mp_err s_mp_exptmod_fast(const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y, int redmode)
+{
+ mp_int M[TAB_SIZE], res;
+ mp_digit buf, mp;
+ int bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
+ mp_err err;
+
+ /* use a pointer to the reduction algorithm. This allows us to use
+ * one of many reduction algorithms without modding the guts of
+ * the code with if statements everywhere.
+ */
+ mp_err(*redux)(mp_int *x, const mp_int *n, mp_digit rho);
+
+ /* find window size */
+ x = mp_count_bits(X);
+ if (x <= 7) {
+ winsize = 2;
+ } else if (x <= 36) {
+ winsize = 3;
+ } else if (x <= 140) {
+ winsize = 4;
+ } else if (x <= 450) {
+ winsize = 5;
+ } else if (x <= 1303) {
+ winsize = 6;
+ } else if (x <= 3529) {
+ winsize = 7;
+ } else {
+ winsize = 8;
+ }
+
+ winsize = MAX_WINSIZE ? MP_MIN(MAX_WINSIZE, winsize) : winsize;
+
+ /* init M array */
+ /* init first cell */
+ if ((err = mp_init_size(&M[1], P->alloc)) != MP_OKAY) {
+ return err;
+ }
+
+ /* now init the second half of the array */
+ for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
+ if ((err = mp_init_size(&M[x], P->alloc)) != MP_OKAY) {
+ for (y = 1<<(winsize-1); y < x; y++) {
+ mp_clear(&M[y]);
+ }
+ mp_clear(&M[1]);
+ return err;
+ }
+ }
+
+ /* determine and setup reduction code */
+ if (redmode == 0) {
+ if (MP_HAS(MP_MONTGOMERY_SETUP)) {
+ /* now setup montgomery */
+ if ((err = mp_montgomery_setup(P, &mp)) != MP_OKAY) goto LBL_M;
+ } else {
+ err = MP_VAL;
+ goto LBL_M;
+ }
+
+ /* automatically pick the comba one if available (saves quite a few calls/ifs) */
+ if (MP_HAS(S_MP_MONTGOMERY_REDUCE_FAST) &&
+ (((P->used * 2) + 1) < MP_WARRAY) &&
+ (P->used < MP_MAXFAST)) {
+ redux = s_mp_montgomery_reduce_fast;
+ } else if (MP_HAS(MP_MONTGOMERY_REDUCE)) {
+ /* use slower baseline Montgomery method */
+ redux = mp_montgomery_reduce;
+ } else {
+ err = MP_VAL;
+ goto LBL_M;
+ }
+ } else if (redmode == 1) {
+ if (MP_HAS(MP_DR_SETUP) && MP_HAS(MP_DR_REDUCE)) {
+ /* setup DR reduction for moduli of the form B**k - b */
+ mp_dr_setup(P, &mp);
+ redux = mp_dr_reduce;
+ } else {
+ err = MP_VAL;
+ goto LBL_M;
+ }
+ } else if (MP_HAS(MP_REDUCE_2K_SETUP) && MP_HAS(MP_REDUCE_2K)) {
+ /* setup DR reduction for moduli of the form 2**k - b */
+ if ((err = mp_reduce_2k_setup(P, &mp)) != MP_OKAY) goto LBL_M;
+ redux = mp_reduce_2k;
+ } else {
+ err = MP_VAL;
+ goto LBL_M;
+ }
+
+ /* setup result */
+ if ((err = mp_init_size(&res, P->alloc)) != MP_OKAY) goto LBL_M;
+
+ /* create M table
+ *
+
+ *
+ * The first half of the table is not computed though accept for M[0] and M[1]
+ */
+
+ if (redmode == 0) {
+ if (MP_HAS(MP_MONTGOMERY_CALC_NORMALIZATION)) {
+ /* now we need R mod m */
+ if ((err = mp_montgomery_calc_normalization(&res, P)) != MP_OKAY) goto LBL_RES;
+
+ /* now set M[1] to G * R mod m */
+ if ((err = mp_mulmod(G, &res, P, &M[1])) != MP_OKAY) goto LBL_RES;
+ } else {
+ err = MP_VAL;
+ goto LBL_RES;
+ }
+ } else {
+ mp_set(&res, 1uL);
+ if ((err = mp_mod(G, P, &M[1])) != MP_OKAY) goto LBL_RES;
+ }
+
+ /* compute the value at M[1<<(winsize-1)] by squaring M[1] (winsize-1) times */
+ if ((err = mp_copy(&M[1], &M[(size_t)1 << (winsize - 1)])) != MP_OKAY) goto LBL_RES;
+
+ for (x = 0; x < (winsize - 1); x++) {
+ if ((err = mp_sqr(&M[(size_t)1 << (winsize - 1)], &M[(size_t)1 << (winsize - 1)])) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&M[(size_t)1 << (winsize - 1)], P, mp)) != MP_OKAY) goto LBL_RES;
+ }
+
+ /* create upper table */
+ for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
+ if ((err = mp_mul(&M[x - 1], &M[1], &M[x])) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&M[x], P, mp)) != MP_OKAY) goto LBL_RES;
+ }
+
+ /* set initial mode and bit cnt */
+ mode = 0;
+ bitcnt = 1;
+ buf = 0;
+ digidx = X->used - 1;
+ bitcpy = 0;
+ bitbuf = 0;
+
+ for (;;) {
+ /* grab next digit as required */
+ if (--bitcnt == 0) {
+ /* if digidx == -1 we are out of digits so break */
+ if (digidx == -1) {
+ break;
+ }
+ /* read next digit and reset bitcnt */
+ buf = X->dp[digidx--];
+ bitcnt = (int)MP_DIGIT_BIT;
+ }
+
+ /* grab the next msb from the exponent */
+ y = (mp_digit)(buf >> (MP_DIGIT_BIT - 1)) & 1uL;
+ buf <<= (mp_digit)1;
+
+ /* if the bit is zero and mode == 0 then we ignore it
+ * These represent the leading zero bits before the first 1 bit
+ * in the exponent. Technically this opt is not required but it
+ * does lower the # of trivial squaring/reductions used
+ */
+ if ((mode == 0) && (y == 0)) {
+ continue;
+ }
+
+ /* if the bit is zero and mode == 1 then we square */
+ if ((mode == 1) && (y == 0)) {
+ if ((err = mp_sqr(&res, &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, mp)) != MP_OKAY) goto LBL_RES;
+ continue;
+ }
+
+ /* else we add it to the window */
+ bitbuf |= (y << (winsize - ++bitcpy));
+ mode = 2;
+
+ if (bitcpy == winsize) {
+ /* ok window is filled so square as required and multiply */
+ /* square first */
+ for (x = 0; x < winsize; x++) {
+ if ((err = mp_sqr(&res, &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, mp)) != MP_OKAY) goto LBL_RES;
+ }
+
+ /* then multiply */
+ if ((err = mp_mul(&res, &M[bitbuf], &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, mp)) != MP_OKAY) goto LBL_RES;
+
+ /* empty window and reset */
+ bitcpy = 0;
+ bitbuf = 0;
+ mode = 1;
+ }
+ }
+
+ /* if bits remain then square/multiply */
+ if ((mode == 2) && (bitcpy > 0)) {
+ /* square then multiply if the bit is set */
+ for (x = 0; x < bitcpy; x++) {
+ if ((err = mp_sqr(&res, &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, mp)) != MP_OKAY) goto LBL_RES;
+
+ /* get next bit of the window */
+ bitbuf <<= 1;
+ if ((bitbuf & (1 << winsize)) != 0) {
+ /* then multiply */
+ if ((err = mp_mul(&res, &M[1], &res)) != MP_OKAY) goto LBL_RES;
+ if ((err = redux(&res, P, mp)) != MP_OKAY) goto LBL_RES;
+ }
+ }
+ }
+
+ if (redmode == 0) {
+ /* fixup result if Montgomery reduction is used
+ * recall that any value in a Montgomery system is
+ * actually multiplied by R mod n. So we have
+ * to reduce one more time to cancel out the factor
+ * of R.
+ */
+ if ((err = redux(&res, P, mp)) != MP_OKAY) goto LBL_RES;
+ }
+
+ /* swap res with Y */
+ mp_exch(&res, Y);
+ err = MP_OKAY;
+LBL_RES:
+ mp_clear(&res);
+LBL_M:
+ mp_clear(&M[1]);
+ for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
+ mp_clear(&M[x]);
+ }
+ return err;
+}
+#endif
+
+/* End: bn_s_mp_exptmod_fast.c */
+
+/* Start: bn_s_mp_get_bit.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_GET_BIT_C
+
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Get bit at position b and return MP_YES if the bit is 1, MP_NO if it is 0 */
+mp_bool s_mp_get_bit(const mp_int *a, unsigned int b)
+{
+ mp_digit bit;
+ int limb = (int)(b / MP_DIGIT_BIT);
+
+ if (limb >= a->used) {
+ return MP_NO;
+ }
+
+ bit = (mp_digit)1 << (b % MP_DIGIT_BIT);
+ return ((a->dp[limb] & bit) != 0u) ? MP_YES : MP_NO;
+}
+
+#endif
+
+/* End: bn_s_mp_get_bit.c */
+
+/* Start: bn_s_mp_invmod_fast.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_INVMOD_FAST_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* computes the modular inverse via binary extended euclidean algorithm,
+ * that is c = 1/a mod b
+ *
+ * Based on slow invmod except this is optimized for the case where b is
+ * odd as per HAC Note 14.64 on pp. 610
+ */
+mp_err s_mp_invmod_fast(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_int x, y, u, v, B, D;
+ mp_sign neg;
+ mp_err err;
+
+ /* 2. [modified] b must be odd */
+ if (MP_IS_EVEN(b)) {
+ return MP_VAL;
+ }
+
+ /* init all our temps */
+ if ((err = mp_init_multi(&x, &y, &u, &v, &B, &D, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* x == modulus, y == value to invert */
+ if ((err = mp_copy(b, &x)) != MP_OKAY) goto LBL_ERR;
+
+ /* we need y = |a| */
+ if ((err = mp_mod(a, b, &y)) != MP_OKAY) goto LBL_ERR;
+
+ /* if one of x,y is zero return an error! */
+ if (MP_IS_ZERO(&x) || MP_IS_ZERO(&y)) {
+ err = MP_VAL;
+ goto LBL_ERR;
+ }
+
+ /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
+ if ((err = mp_copy(&x, &u)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_copy(&y, &v)) != MP_OKAY) goto LBL_ERR;
+ mp_set(&D, 1uL);
+
+top:
+ /* 4. while u is even do */
+ while (MP_IS_EVEN(&u)) {
+ /* 4.1 u = u/2 */
+ if ((err = mp_div_2(&u, &u)) != MP_OKAY) goto LBL_ERR;
+
+ /* 4.2 if B is odd then */
+ if (MP_IS_ODD(&B)) {
+ if ((err = mp_sub(&B, &x, &B)) != MP_OKAY) goto LBL_ERR;
+ }
+ /* B = B/2 */
+ if ((err = mp_div_2(&B, &B)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* 5. while v is even do */
+ while (MP_IS_EVEN(&v)) {
+ /* 5.1 v = v/2 */
+ if ((err = mp_div_2(&v, &v)) != MP_OKAY) goto LBL_ERR;
+
+ /* 5.2 if D is odd then */
+ if (MP_IS_ODD(&D)) {
+ /* D = (D-x)/2 */
+ if ((err = mp_sub(&D, &x, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+ /* D = D/2 */
+ if ((err = mp_div_2(&D, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* 6. if u >= v then */
+ if (mp_cmp(&u, &v) != MP_LT) {
+ /* u = u - v, B = B - D */
+ if ((err = mp_sub(&u, &v, &u)) != MP_OKAY) goto LBL_ERR;
+
+ if ((err = mp_sub(&B, &D, &B)) != MP_OKAY) goto LBL_ERR;
+ } else {
+ /* v - v - u, D = D - B */
+ if ((err = mp_sub(&v, &u, &v)) != MP_OKAY) goto LBL_ERR;
+
+ if ((err = mp_sub(&D, &B, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* if not zero goto step 4 */
+ if (!MP_IS_ZERO(&u)) {
+ goto top;
+ }
+
+ /* now a = C, b = D, gcd == g*v */
+
+ /* if v != 1 then there is no inverse */
+ if (mp_cmp_d(&v, 1uL) != MP_EQ) {
+ err = MP_VAL;
+ goto LBL_ERR;
+ }
+
+ /* b is now the inverse */
+ neg = a->sign;
+ while (D.sign == MP_NEG) {
+ if ((err = mp_add(&D, b, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* too big */
+ while (mp_cmp_mag(&D, b) != MP_LT) {
+ if ((err = mp_sub(&D, b, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ mp_exch(&D, c);
+ c->sign = neg;
+ err = MP_OKAY;
+
+LBL_ERR:
+ mp_clear_multi(&x, &y, &u, &v, &B, &D, NULL);
+ return err;
+}
+#endif
+
+/* End: bn_s_mp_invmod_fast.c */
+
+/* Start: bn_s_mp_invmod_slow.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_INVMOD_SLOW_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* hac 14.61, pp608 */
+mp_err s_mp_invmod_slow(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_int x, y, u, v, A, B, C, D;
+ mp_err err;
+
+ /* b cannot be negative */
+ if ((b->sign == MP_NEG) || MP_IS_ZERO(b)) {
+ return MP_VAL;
+ }
+
+ /* init temps */
+ if ((err = mp_init_multi(&x, &y, &u, &v,
+ &A, &B, &C, &D, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* x = a, y = b */
+ if ((err = mp_mod(a, b, &x)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_copy(b, &y)) != MP_OKAY) goto LBL_ERR;
+
+ /* 2. [modified] if x,y are both even then return an error! */
+ if (MP_IS_EVEN(&x) && MP_IS_EVEN(&y)) {
+ err = MP_VAL;
+ goto LBL_ERR;
+ }
+
+ /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
+ if ((err = mp_copy(&x, &u)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_copy(&y, &v)) != MP_OKAY) goto LBL_ERR;
+ mp_set(&A, 1uL);
+ mp_set(&D, 1uL);
+
+top:
+ /* 4. while u is even do */
+ while (MP_IS_EVEN(&u)) {
+ /* 4.1 u = u/2 */
+ if ((err = mp_div_2(&u, &u)) != MP_OKAY) goto LBL_ERR;
+
+ /* 4.2 if A or B is odd then */
+ if (MP_IS_ODD(&A) || MP_IS_ODD(&B)) {
+ /* A = (A+y)/2, B = (B-x)/2 */
+ if ((err = mp_add(&A, &y, &A)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_sub(&B, &x, &B)) != MP_OKAY) goto LBL_ERR;
+ }
+ /* A = A/2, B = B/2 */
+ if ((err = mp_div_2(&A, &A)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_div_2(&B, &B)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* 5. while v is even do */
+ while (MP_IS_EVEN(&v)) {
+ /* 5.1 v = v/2 */
+ if ((err = mp_div_2(&v, &v)) != MP_OKAY) goto LBL_ERR;
+
+ /* 5.2 if C or D is odd then */
+ if (MP_IS_ODD(&C) || MP_IS_ODD(&D)) {
+ /* C = (C+y)/2, D = (D-x)/2 */
+ if ((err = mp_add(&C, &y, &C)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_sub(&D, &x, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+ /* C = C/2, D = D/2 */
+ if ((err = mp_div_2(&C, &C)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_div_2(&D, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* 6. if u >= v then */
+ if (mp_cmp(&u, &v) != MP_LT) {
+ /* u = u - v, A = A - C, B = B - D */
+ if ((err = mp_sub(&u, &v, &u)) != MP_OKAY) goto LBL_ERR;
+
+ if ((err = mp_sub(&A, &C, &A)) != MP_OKAY) goto LBL_ERR;
+
+ if ((err = mp_sub(&B, &D, &B)) != MP_OKAY) goto LBL_ERR;
+ } else {
+ /* v - v - u, C = C - A, D = D - B */
+ if ((err = mp_sub(&v, &u, &v)) != MP_OKAY) goto LBL_ERR;
+
+ if ((err = mp_sub(&C, &A, &C)) != MP_OKAY) goto LBL_ERR;
+
+ if ((err = mp_sub(&D, &B, &D)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* if not zero goto step 4 */
+ if (!MP_IS_ZERO(&u)) {
+ goto top;
+ }
+
+ /* now a = C, b = D, gcd == g*v */
+
+ /* if v != 1 then there is no inverse */
+ if (mp_cmp_d(&v, 1uL) != MP_EQ) {
+ err = MP_VAL;
+ goto LBL_ERR;
+ }
+
+ /* if its too low */
+ while (mp_cmp_d(&C, 0uL) == MP_LT) {
+ if ((err = mp_add(&C, b, &C)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* too big */
+ while (mp_cmp_mag(&C, b) != MP_LT) {
+ if ((err = mp_sub(&C, b, &C)) != MP_OKAY) goto LBL_ERR;
+ }
+
+ /* C is now the inverse */
+ mp_exch(&C, c);
+ err = MP_OKAY;
+LBL_ERR:
+ mp_clear_multi(&x, &y, &u, &v, &A, &B, &C, &D, NULL);
+ return err;
+}
+#endif
+
+/* End: bn_s_mp_invmod_slow.c */
+
+/* Start: bn_s_mp_karatsuba_mul.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_KARATSUBA_MUL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* c = |a| * |b| using Karatsuba Multiplication using
+ * three half size multiplications
+ *
+ * Let B represent the radix [e.g. 2**MP_DIGIT_BIT] and
+ * let n represent half of the number of digits in
+ * the min(a,b)
+ *
+ * a = a1 * B**n + a0
+ * b = b1 * B**n + b0
+ *
+ * Then, a * b =>
+ a1b1 * B**2n + ((a1 + a0)(b1 + b0) - (a0b0 + a1b1)) * B + a0b0
+ *
+ * Note that a1b1 and a0b0 are used twice and only need to be
+ * computed once. So in total three half size (half # of
+ * digit) multiplications are performed, a0b0, a1b1 and
+ * (a1+b1)(a0+b0)
+ *
+ * Note that a multiplication of half the digits requires
+ * 1/4th the number of single precision multiplications so in
+ * total after one call 25% of the single precision multiplications
+ * are saved. Note also that the call to mp_mul can end up back
+ * in this function if the a0, a1, b0, or b1 are above the threshold.
+ * This is known as divide-and-conquer and leads to the famous
+ * O(N**lg(3)) or O(N**1.584) work which is asymptopically lower than
+ * the standard O(N**2) that the baseline/comba methods use.
+ * Generally though the overhead of this method doesn't pay off
+ * until a certain size (N ~ 80) is reached.
+ */
+mp_err s_mp_karatsuba_mul(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_int x0, x1, y0, y1, t1, x0y0, x1y1;
+ int B;
+ mp_err err = MP_MEM; /* default the return code to an error */
+
+ /* min # of digits */
+ B = MP_MIN(a->used, b->used);
+
+ /* now divide in two */
+ B = B >> 1;
+
+ /* init copy all the temps */
+ if (mp_init_size(&x0, B) != MP_OKAY) {
+ goto LBL_ERR;
+ }
+ if (mp_init_size(&x1, a->used - B) != MP_OKAY) {
+ goto X0;
+ }
+ if (mp_init_size(&y0, B) != MP_OKAY) {
+ goto X1;
+ }
+ if (mp_init_size(&y1, b->used - B) != MP_OKAY) {
+ goto Y0;
+ }
+
+ /* init temps */
+ if (mp_init_size(&t1, B * 2) != MP_OKAY) {
+ goto Y1;
+ }
+ if (mp_init_size(&x0y0, B * 2) != MP_OKAY) {
+ goto T1;
+ }
+ if (mp_init_size(&x1y1, B * 2) != MP_OKAY) {
+ goto X0Y0;
+ }
+
+ /* now shift the digits */
+ x0.used = y0.used = B;
+ x1.used = a->used - B;
+ y1.used = b->used - B;
+
+ {
+ int x;
+ mp_digit *tmpa, *tmpb, *tmpx, *tmpy;
+
+ /* we copy the digits directly instead of using higher level functions
+ * since we also need to shift the digits
+ */
+ tmpa = a->dp;
+ tmpb = b->dp;
+
+ tmpx = x0.dp;
+ tmpy = y0.dp;
+ for (x = 0; x < B; x++) {
+ *tmpx++ = *tmpa++;
+ *tmpy++ = *tmpb++;
+ }
+
+ tmpx = x1.dp;
+ for (x = B; x < a->used; x++) {
+ *tmpx++ = *tmpa++;
+ }
+
+ tmpy = y1.dp;
+ for (x = B; x < b->used; x++) {
+ *tmpy++ = *tmpb++;
+ }
+ }
+
+ /* only need to clamp the lower words since by definition the
+ * upper words x1/y1 must have a known number of digits
+ */
+ mp_clamp(&x0);
+ mp_clamp(&y0);
+
+ /* now calc the products x0y0 and x1y1 */
+ /* after this x0 is no longer required, free temp [x0==t2]! */
+ if (mp_mul(&x0, &y0, &x0y0) != MP_OKAY) {
+ goto X1Y1; /* x0y0 = x0*y0 */
+ }
+ if (mp_mul(&x1, &y1, &x1y1) != MP_OKAY) {
+ goto X1Y1; /* x1y1 = x1*y1 */
+ }
+
+ /* now calc x1+x0 and y1+y0 */
+ if (s_mp_add(&x1, &x0, &t1) != MP_OKAY) {
+ goto X1Y1; /* t1 = x1 - x0 */
+ }
+ if (s_mp_add(&y1, &y0, &x0) != MP_OKAY) {
+ goto X1Y1; /* t2 = y1 - y0 */
+ }
+ if (mp_mul(&t1, &x0, &t1) != MP_OKAY) {
+ goto X1Y1; /* t1 = (x1 + x0) * (y1 + y0) */
+ }
+
+ /* add x0y0 */
+ if (mp_add(&x0y0, &x1y1, &x0) != MP_OKAY) {
+ goto X1Y1; /* t2 = x0y0 + x1y1 */
+ }
+ if (s_mp_sub(&t1, &x0, &t1) != MP_OKAY) {
+ goto X1Y1; /* t1 = (x1+x0)*(y1+y0) - (x1y1 + x0y0) */
+ }
+
+ /* shift by B */
+ if (mp_lshd(&t1, B) != MP_OKAY) {
+ goto X1Y1; /* t1 = (x0y0 + x1y1 - (x1-x0)*(y1-y0))<<B */
+ }
+ if (mp_lshd(&x1y1, B * 2) != MP_OKAY) {
+ goto X1Y1; /* x1y1 = x1y1 << 2*B */
+ }
+
+ if (mp_add(&x0y0, &t1, &t1) != MP_OKAY) {
+ goto X1Y1; /* t1 = x0y0 + t1 */
+ }
+ if (mp_add(&t1, &x1y1, c) != MP_OKAY) {
+ goto X1Y1; /* t1 = x0y0 + t1 + x1y1 */
+ }
+
+ /* Algorithm succeeded set the return code to MP_OKAY */
+ err = MP_OKAY;
+
+X1Y1:
+ mp_clear(&x1y1);
+X0Y0:
+ mp_clear(&x0y0);
+T1:
+ mp_clear(&t1);
+Y1:
+ mp_clear(&y1);
+Y0:
+ mp_clear(&y0);
+X1:
+ mp_clear(&x1);
+X0:
+ mp_clear(&x0);
+LBL_ERR:
+ return err;
+}
+#endif
+
+/* End: bn_s_mp_karatsuba_mul.c */
+
+/* Start: bn_s_mp_karatsuba_sqr.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_KARATSUBA_SQR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Karatsuba squaring, computes b = a*a using three
+ * half size squarings
+ *
+ * See comments of karatsuba_mul for details. It
+ * is essentially the same algorithm but merely
+ * tuned to perform recursive squarings.
+ */
+mp_err s_mp_karatsuba_sqr(const mp_int *a, mp_int *b)
+{
+ mp_int x0, x1, t1, t2, x0x0, x1x1;
+ int B;
+ mp_err err = MP_MEM;
+
+ /* min # of digits */
+ B = a->used;
+
+ /* now divide in two */
+ B = B >> 1;
+
+ /* init copy all the temps */
+ if (mp_init_size(&x0, B) != MP_OKAY)
+ goto LBL_ERR;
+ if (mp_init_size(&x1, a->used - B) != MP_OKAY)
+ goto X0;
+
+ /* init temps */
+ if (mp_init_size(&t1, a->used * 2) != MP_OKAY)
+ goto X1;
+ if (mp_init_size(&t2, a->used * 2) != MP_OKAY)
+ goto T1;
+ if (mp_init_size(&x0x0, B * 2) != MP_OKAY)
+ goto T2;
+ if (mp_init_size(&x1x1, (a->used - B) * 2) != MP_OKAY)
+ goto X0X0;
+
+ {
+ int x;
+ mp_digit *dst, *src;
+
+ src = a->dp;
+
+ /* now shift the digits */
+ dst = x0.dp;
+ for (x = 0; x < B; x++) {
+ *dst++ = *src++;
+ }
+
+ dst = x1.dp;
+ for (x = B; x < a->used; x++) {
+ *dst++ = *src++;
+ }
+ }
+
+ x0.used = B;
+ x1.used = a->used - B;
+
+ mp_clamp(&x0);
+
+ /* now calc the products x0*x0 and x1*x1 */
+ if (mp_sqr(&x0, &x0x0) != MP_OKAY)
+ goto X1X1; /* x0x0 = x0*x0 */
+ if (mp_sqr(&x1, &x1x1) != MP_OKAY)
+ goto X1X1; /* x1x1 = x1*x1 */
+
+ /* now calc (x1+x0)**2 */
+ if (s_mp_add(&x1, &x0, &t1) != MP_OKAY)
+ goto X1X1; /* t1 = x1 - x0 */
+ if (mp_sqr(&t1, &t1) != MP_OKAY)
+ goto X1X1; /* t1 = (x1 - x0) * (x1 - x0) */
+
+ /* add x0y0 */
+ if (s_mp_add(&x0x0, &x1x1, &t2) != MP_OKAY)
+ goto X1X1; /* t2 = x0x0 + x1x1 */
+ if (s_mp_sub(&t1, &t2, &t1) != MP_OKAY)
+ goto X1X1; /* t1 = (x1+x0)**2 - (x0x0 + x1x1) */
+
+ /* shift by B */
+ if (mp_lshd(&t1, B) != MP_OKAY)
+ goto X1X1; /* t1 = (x0x0 + x1x1 - (x1-x0)*(x1-x0))<<B */
+ if (mp_lshd(&x1x1, B * 2) != MP_OKAY)
+ goto X1X1; /* x1x1 = x1x1 << 2*B */
+
+ if (mp_add(&x0x0, &t1, &t1) != MP_OKAY)
+ goto X1X1; /* t1 = x0x0 + t1 */
+ if (mp_add(&t1, &x1x1, b) != MP_OKAY)
+ goto X1X1; /* t1 = x0x0 + t1 + x1x1 */
+
+ err = MP_OKAY;
+
+X1X1:
+ mp_clear(&x1x1);
+X0X0:
+ mp_clear(&x0x0);
+T2:
+ mp_clear(&t2);
+T1:
+ mp_clear(&t1);
+X1:
+ mp_clear(&x1);
+X0:
+ mp_clear(&x0);
+LBL_ERR:
+ return err;
+}
+#endif
+
+/* End: bn_s_mp_karatsuba_sqr.c */
+
+/* Start: bn_s_mp_montgomery_reduce_fast.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_MONTGOMERY_REDUCE_FAST_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* computes xR**-1 == x (mod N) via Montgomery Reduction
+ *
+ * This is an optimized implementation of montgomery_reduce
+ * which uses the comba method to quickly calculate the columns of the
+ * reduction.
+ *
+ * Based on Algorithm 14.32 on pp.601 of HAC.
+*/
+mp_err s_mp_montgomery_reduce_fast(mp_int *x, const mp_int *n, mp_digit rho)
+{
+ int ix, olduse;
+ mp_err err;
+ mp_word W[MP_WARRAY];
+
+ if (x->used > MP_WARRAY) {
+ return MP_VAL;
+ }
+
+ /* get old used count */
+ olduse = x->used;
+
+ /* grow a as required */
+ if (x->alloc < (n->used + 1)) {
+ if ((err = mp_grow(x, n->used + 1)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* first we have to get the digits of the input into
+ * an array of double precision words W[...]
+ */
+ {
+ mp_word *_W;
+ mp_digit *tmpx;
+
+ /* alias for the W[] array */
+ _W = W;
+
+ /* alias for the digits of x*/
+ tmpx = x->dp;
+
+ /* copy the digits of a into W[0..a->used-1] */
+ for (ix = 0; ix < x->used; ix++) {
+ *_W++ = *tmpx++;
+ }
+
+ /* zero the high words of W[a->used..m->used*2] */
+ if (ix < ((n->used * 2) + 1)) {
+ MP_ZERO_BUFFER(_W, sizeof(mp_word) * (size_t)(((n->used * 2) + 1) - ix));
+ }
+ }
+
+ /* now we proceed to zero successive digits
+ * from the least significant upwards
+ */
+ for (ix = 0; ix < n->used; ix++) {
+ /* mu = ai * m' mod b
+ *
+ * We avoid a double precision multiplication (which isn't required)
+ * by casting the value down to a mp_digit. Note this requires
+ * that W[ix-1] have the carry cleared (see after the inner loop)
+ */
+ mp_digit mu;
+ mu = ((W[ix] & MP_MASK) * rho) & MP_MASK;
+
+ /* a = a + mu * m * b**i
+ *
+ * This is computed in place and on the fly. The multiplication
+ * by b**i is handled by offseting which columns the results
+ * are added to.
+ *
+ * Note the comba method normally doesn't handle carries in the
+ * inner loop In this case we fix the carry from the previous
+ * column since the Montgomery reduction requires digits of the
+ * result (so far) [see above] to work. This is
+ * handled by fixing up one carry after the inner loop. The
+ * carry fixups are done in order so after these loops the
+ * first m->used words of W[] have the carries fixed
+ */
+ {
+ int iy;
+ mp_digit *tmpn;
+ mp_word *_W;
+
+ /* alias for the digits of the modulus */
+ tmpn = n->dp;
+
+ /* Alias for the columns set by an offset of ix */
+ _W = W + ix;
+
+ /* inner loop */
+ for (iy = 0; iy < n->used; iy++) {
+ *_W++ += (mp_word)mu * (mp_word)*tmpn++;
+ }
+ }
+
+ /* now fix carry for next digit, W[ix+1] */
+ W[ix + 1] += W[ix] >> (mp_word)MP_DIGIT_BIT;
+ }
+
+ /* now we have to propagate the carries and
+ * shift the words downward [all those least
+ * significant digits we zeroed].
+ */
+ {
+ mp_digit *tmpx;
+ mp_word *_W, *_W1;
+
+ /* nox fix rest of carries */
+
+ /* alias for current word */
+ _W1 = W + ix;
+
+ /* alias for next word, where the carry goes */
+ _W = W + ++ix;
+
+ for (; ix < ((n->used * 2) + 1); ix++) {
+ *_W++ += *_W1++ >> (mp_word)MP_DIGIT_BIT;
+ }
+
+ /* copy out, A = A/b**n
+ *
+ * The result is A/b**n but instead of converting from an
+ * array of mp_word to mp_digit than calling mp_rshd
+ * we just copy them in the right order
+ */
+
+ /* alias for destination word */
+ tmpx = x->dp;
+
+ /* alias for shifted double precision result */
+ _W = W + n->used;
+
+ for (ix = 0; ix < (n->used + 1); ix++) {
+ *tmpx++ = *_W++ & (mp_word)MP_MASK;
+ }
+
+ /* zero oldused digits, if the input a was larger than
+ * m->used+1 we'll have to clear the digits
+ */
+ MP_ZERO_DIGITS(tmpx, olduse - ix);
+ }
+
+ /* set the max used and clamp */
+ x->used = n->used + 1;
+ mp_clamp(x);
+
+ /* if A >= m then A = A - m */
+ if (mp_cmp_mag(x, n) != MP_LT) {
+ return s_mp_sub(x, n, x);
+ }
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_s_mp_montgomery_reduce_fast.c */
+
+/* Start: bn_s_mp_mul_digs.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_MUL_DIGS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* multiplies |a| * |b| and only computes upto digs digits of result
+ * HAC pp. 595, Algorithm 14.12 Modified so you can control how
+ * many digits of output are created.
+ */
+mp_err s_mp_mul_digs(const mp_int *a, const mp_int *b, mp_int *c, int digs)
+{
+ mp_int t;
+ mp_err err;
+ int pa, pb, ix, iy;
+ mp_digit u;
+ mp_word r;
+ mp_digit tmpx, *tmpt, *tmpy;
+
+ /* can we use the fast multiplier? */
+ if ((digs < MP_WARRAY) &&
+ (MP_MIN(a->used, b->used) < MP_MAXFAST)) {
+ return s_mp_mul_digs_fast(a, b, c, digs);
+ }
+
+ if ((err = mp_init_size(&t, digs)) != MP_OKAY) {
+ return err;
+ }
+ t.used = digs;
+
+ /* compute the digits of the product directly */
+ pa = a->used;
+ for (ix = 0; ix < pa; ix++) {
+ /* set the carry to zero */
+ u = 0;
+
+ /* limit ourselves to making digs digits of output */
+ pb = MP_MIN(b->used, digs - ix);
+
+ /* setup some aliases */
+ /* copy of the digit from a used within the nested loop */
+ tmpx = a->dp[ix];
+
+ /* an alias for the destination shifted ix places */
+ tmpt = t.dp + ix;
+
+ /* an alias for the digits of b */
+ tmpy = b->dp;
+
+ /* compute the columns of the output and propagate the carry */
+ for (iy = 0; iy < pb; iy++) {
+ /* compute the column as a mp_word */
+ r = (mp_word)*tmpt +
+ ((mp_word)tmpx * (mp_word)*tmpy++) +
+ (mp_word)u;
+
+ /* the new column is the lower part of the result */
+ *tmpt++ = (mp_digit)(r & (mp_word)MP_MASK);
+
+ /* get the carry word from the result */
+ u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
+ }
+ /* set carry if it is placed below digs */
+ if ((ix + iy) < digs) {
+ *tmpt = u;
+ }
+ }
+
+ mp_clamp(&t);
+ mp_exch(&t, c);
+
+ mp_clear(&t);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_s_mp_mul_digs.c */
+
+/* Start: bn_s_mp_mul_digs_fast.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_MUL_DIGS_FAST_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Fast (comba) multiplier
+ *
+ * This is the fast column-array [comba] multiplier. It is
+ * designed to compute the columns of the product first
+ * then handle the carries afterwards. This has the effect
+ * of making the nested loops that compute the columns very
+ * simple and schedulable on super-scalar processors.
+ *
+ * This has been modified to produce a variable number of
+ * digits of output so if say only a half-product is required
+ * you don't have to compute the upper half (a feature
+ * required for fast Barrett reduction).
+ *
+ * Based on Algorithm 14.12 on pp.595 of HAC.
+ *
+ */
+mp_err s_mp_mul_digs_fast(const mp_int *a, const mp_int *b, mp_int *c, int digs)
+{
+ int olduse, pa, ix, iz;
+ mp_err err;
+ mp_digit W[MP_WARRAY];
+ mp_word _W;
+
+ /* grow the destination as required */
+ if (c->alloc < digs) {
+ if ((err = mp_grow(c, digs)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* number of output digits to produce */
+ pa = MP_MIN(digs, a->used + b->used);
+
+ /* clear the carry */
+ _W = 0;
+ for (ix = 0; ix < pa; ix++) {
+ int tx, ty;
+ int iy;
+ mp_digit *tmpx, *tmpy;
+
+ /* get offsets into the two bignums */
+ ty = MP_MIN(b->used-1, ix);
+ tx = ix - ty;
+
+ /* setup temp aliases */
+ tmpx = a->dp + tx;
+ tmpy = b->dp + ty;
+
+ /* this is the number of times the loop will iterrate, essentially
+ while (tx++ < a->used && ty-- >= 0) { ... }
+ */
+ iy = MP_MIN(a->used-tx, ty+1);
+
+ /* execute loop */
+ for (iz = 0; iz < iy; ++iz) {
+ _W += (mp_word)*tmpx++ * (mp_word)*tmpy--;
+
+ }
+
+ /* store term */
+ W[ix] = (mp_digit)_W & MP_MASK;
+
+ /* make next carry */
+ _W = _W >> (mp_word)MP_DIGIT_BIT;
+ }
+
+ /* setup dest */
+ olduse = c->used;
+ c->used = pa;
+
+ {
+ mp_digit *tmpc;
+ tmpc = c->dp;
+ for (ix = 0; ix < pa; ix++) {
+ /* now extract the previous digit [below the carry] */
+ *tmpc++ = W[ix];
+ }
+
+ /* clear unused digits [that existed in the old copy of c] */
+ MP_ZERO_DIGITS(tmpc, olduse - ix);
+ }
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_s_mp_mul_digs_fast.c */
+
+/* Start: bn_s_mp_mul_high_digs.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_MUL_HIGH_DIGS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* multiplies |a| * |b| and does not compute the lower digs digits
+ * [meant to get the higher part of the product]
+ */
+mp_err s_mp_mul_high_digs(const mp_int *a, const mp_int *b, mp_int *c, int digs)
+{
+ mp_int t;
+ int pa, pb, ix, iy;
+ mp_err err;
+ mp_digit u;
+ mp_word r;
+ mp_digit tmpx, *tmpt, *tmpy;
+
+ /* can we use the fast multiplier? */
+ if (MP_HAS(S_MP_MUL_HIGH_DIGS_FAST)
+ && ((a->used + b->used + 1) < MP_WARRAY)
+ && (MP_MIN(a->used, b->used) < MP_MAXFAST)) {
+ return s_mp_mul_high_digs_fast(a, b, c, digs);
+ }
+
+ if ((err = mp_init_size(&t, a->used + b->used + 1)) != MP_OKAY) {
+ return err;
+ }
+ t.used = a->used + b->used + 1;
+
+ pa = a->used;
+ pb = b->used;
+ for (ix = 0; ix < pa; ix++) {
+ /* clear the carry */
+ u = 0;
+
+ /* left hand side of A[ix] * B[iy] */
+ tmpx = a->dp[ix];
+
+ /* alias to the address of where the digits will be stored */
+ tmpt = &(t.dp[digs]);
+
+ /* alias for where to read the right hand side from */
+ tmpy = b->dp + (digs - ix);
+
+ for (iy = digs - ix; iy < pb; iy++) {
+ /* calculate the double precision result */
+ r = (mp_word)*tmpt +
+ ((mp_word)tmpx * (mp_word)*tmpy++) +
+ (mp_word)u;
+
+ /* get the lower part */
+ *tmpt++ = (mp_digit)(r & (mp_word)MP_MASK);
+
+ /* carry the carry */
+ u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
+ }
+ *tmpt = u;
+ }
+ mp_clamp(&t);
+ mp_exch(&t, c);
+ mp_clear(&t);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_s_mp_mul_high_digs.c */
+
+/* Start: bn_s_mp_mul_high_digs_fast.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_MUL_HIGH_DIGS_FAST_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* this is a modified version of fast_s_mul_digs that only produces
+ * output digits *above* digs. See the comments for fast_s_mul_digs
+ * to see how it works.
+ *
+ * This is used in the Barrett reduction since for one of the multiplications
+ * only the higher digits were needed. This essentially halves the work.
+ *
+ * Based on Algorithm 14.12 on pp.595 of HAC.
+ */
+mp_err s_mp_mul_high_digs_fast(const mp_int *a, const mp_int *b, mp_int *c, int digs)
+{
+ int olduse, pa, ix, iz;
+ mp_err err;
+ mp_digit W[MP_WARRAY];
+ mp_word _W;
+
+ /* grow the destination as required */
+ pa = a->used + b->used;
+ if (c->alloc < pa) {
+ if ((err = mp_grow(c, pa)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* number of output digits to produce */
+ pa = a->used + b->used;
+ _W = 0;
+ for (ix = digs; ix < pa; ix++) {
+ int tx, ty, iy;
+ mp_digit *tmpx, *tmpy;
+
+ /* get offsets into the two bignums */
+ ty = MP_MIN(b->used-1, ix);
+ tx = ix - ty;
+
+ /* setup temp aliases */
+ tmpx = a->dp + tx;
+ tmpy = b->dp + ty;
+
+ /* this is the number of times the loop will iterrate, essentially its
+ while (tx++ < a->used && ty-- >= 0) { ... }
+ */
+ iy = MP_MIN(a->used-tx, ty+1);
+
+ /* execute loop */
+ for (iz = 0; iz < iy; iz++) {
+ _W += (mp_word)*tmpx++ * (mp_word)*tmpy--;
+ }
+
+ /* store term */
+ W[ix] = (mp_digit)_W & MP_MASK;
+
+ /* make next carry */
+ _W = _W >> (mp_word)MP_DIGIT_BIT;
+ }
+
+ /* setup dest */
+ olduse = c->used;
+ c->used = pa;
+
+ {
+ mp_digit *tmpc;
+
+ tmpc = c->dp + digs;
+ for (ix = digs; ix < pa; ix++) {
+ /* now extract the previous digit [below the carry] */
+ *tmpc++ = W[ix];
+ }
+
+ /* clear unused digits [that existed in the old copy of c] */
+ MP_ZERO_DIGITS(tmpc, olduse - ix);
+ }
+ mp_clamp(c);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_s_mp_mul_high_digs_fast.c */
+
+/* Start: bn_s_mp_prime_is_divisible.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_PRIME_IS_DIVISIBLE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* determines if an integers is divisible by one
+ * of the first PRIME_SIZE primes or not
+ *
+ * sets result to 0 if not, 1 if yes
+ */
+mp_err s_mp_prime_is_divisible(const mp_int *a, mp_bool *result)
+{
+ int ix;
+ mp_err err;
+ mp_digit res;
+
+ /* default to not */
+ *result = MP_NO;
+
+ for (ix = 0; ix < PRIVATE_MP_PRIME_TAB_SIZE; ix++) {
+ /* what is a mod LBL_prime_tab[ix] */
+ if ((err = mp_mod_d(a, s_mp_prime_tab[ix], &res)) != MP_OKAY) {
+ return err;
+ }
+
+ /* is the residue zero? */
+ if (res == 0u) {
+ *result = MP_YES;
+ return MP_OKAY;
+ }
+ }
+
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_s_mp_prime_is_divisible.c */
+
+/* Start: bn_s_mp_rand_jenkins.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_RAND_JENKINS_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* Bob Jenkins' http://burtleburtle.net/bob/rand/smallprng.html */
+/* Chosen for speed and a good "mix" */
+typedef struct {
+ uint64_t a;
+ uint64_t b;
+ uint64_t c;
+ uint64_t d;
+} ranctx;
+
+static ranctx jenkins_x;
+
+#define rot(x,k) (((x)<<(k))|((x)>>(64-(k))))
+static uint64_t s_rand_jenkins_val(void)
+{
+ uint64_t e = jenkins_x.a - rot(jenkins_x.b, 7);
+ jenkins_x.a = jenkins_x.b ^ rot(jenkins_x.c, 13);
+ jenkins_x.b = jenkins_x.c + rot(jenkins_x.d, 37);
+ jenkins_x.c = jenkins_x.d + e;
+ jenkins_x.d = e + jenkins_x.a;
+ return jenkins_x.d;
+}
+
+void s_mp_rand_jenkins_init(uint64_t seed)
+{
+ uint64_t i;
+ jenkins_x.a = 0xf1ea5eedULL;
+ jenkins_x.b = jenkins_x.c = jenkins_x.d = seed;
+ for (i = 0uLL; i < 20uLL; ++i) {
+ (void)s_rand_jenkins_val();
+ }
+}
+
+mp_err s_mp_rand_jenkins(void *p, size_t n)
+{
+ char *q = (char *)p;
+ while (n > 0u) {
+ int i;
+ uint64_t x = s_rand_jenkins_val();
+ for (i = 0; (i < 8) && (n > 0u); ++i, --n) {
+ *q++ = (char)(x & 0xFFuLL);
+ x >>= 8;
+ }
+ }
+ return MP_OKAY;
+}
+
+#endif
+
+/* End: bn_s_mp_rand_jenkins.c */
+
+/* Start: bn_s_mp_rand_platform.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_RAND_PLATFORM_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* First the OS-specific special cases
+ * - *BSD
+ * - Windows
+ */
+#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
+#define BN_S_READ_ARC4RANDOM_C
+static mp_err s_read_arc4random(void *p, size_t n)
+{
+ arc4random_buf(p, n);
+ return MP_OKAY;
+}
+#endif
+
+#if defined(_WIN32) || defined(_WIN32_WCE)
+#define BN_S_READ_WINCSP_C
+
+#ifndef _WIN32_WINNT
+#define _WIN32_WINNT 0x0400
+#endif
+#ifdef _WIN32_WCE
+#define UNDER_CE
+#define ARM
+#endif
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <wincrypt.h>
+
+static mp_err s_read_wincsp(void *p, size_t n)
+{
+ static HCRYPTPROV hProv = 0;
+ if (hProv == 0) {
+ HCRYPTPROV h = 0;
+ if (!CryptAcquireContext(&h, NULL, MS_DEF_PROV, PROV_RSA_FULL,
+ (CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET)) &&
+ !CryptAcquireContext(&h, NULL, MS_DEF_PROV, PROV_RSA_FULL,
+ CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET | CRYPT_NEWKEYSET)) {
+ return MP_ERR;
+ }
+ hProv = h;
+ }
+ return CryptGenRandom(hProv, (DWORD)n, (BYTE *)p) == TRUE ? MP_OKAY : MP_ERR;
+}
+#endif /* WIN32 */
+
+#if !defined(BN_S_READ_WINCSP_C) && defined(__linux__) && defined(__GLIBC_PREREQ)
+#if __GLIBC_PREREQ(2, 25)
+#define BN_S_READ_GETRANDOM_C
+#include <sys/random.h>
+#include <errno.h>
+
+static mp_err s_read_getrandom(void *p, size_t n)
+{
+ char *q = (char *)p;
+ while (n > 0u) {
+ ssize_t ret = getrandom(q, n, 0);
+ if (ret < 0) {
+ if (errno == EINTR) {
+ continue;
+ }
+ return MP_ERR;
+ }
+ q += ret;
+ n -= (size_t)ret;
+ }
+ return MP_OKAY;
+}
+#endif
+#endif
+
+/* We assume all platforms besides windows provide "/dev/urandom".
+ * In case yours doesn't, define MP_NO_DEV_URANDOM at compile-time.
+ */
+#if !defined(BN_S_READ_WINCSP_C) && !defined(MP_NO_DEV_URANDOM)
+#define BN_S_READ_URANDOM_C
+#ifndef MP_DEV_URANDOM
+#define MP_DEV_URANDOM "/dev/urandom"
+#endif
+#include <fcntl.h>
+#include <errno.h>
+#include <unistd.h>
+
+static mp_err s_read_urandom(void *p, size_t n)
+{
+ int fd;
+ char *q = (char *)p;
+
+ do {
+ fd = open(MP_DEV_URANDOM, O_RDONLY);
+ } while ((fd == -1) && (errno == EINTR));
+ if (fd == -1) return MP_ERR;
+
+ while (n > 0u) {
+ ssize_t ret = read(fd, p, n);
+ if (ret < 0) {
+ if (errno == EINTR) {
+ continue;
+ }
+ close(fd);
+ return MP_ERR;
+ }
+ q += ret;
+ n -= (size_t)ret;
+ }
+
+ close(fd);
+ return MP_OKAY;
+}
+#endif
+
+#if defined(MP_PRNG_ENABLE_LTM_RNG)
+#define BN_S_READ_LTM_RNG
+unsigned long (*ltm_rng)(unsigned char *out, unsigned long outlen, void (*callback)(void));
+void (*ltm_rng_callback)(void);
+
+static mp_err s_read_ltm_rng(void *p, size_t n)
+{
+ unsigned long res;
+ if (ltm_rng == NULL) return MP_ERR;
+ res = ltm_rng(p, n, ltm_rng_callback);
+ if (res != n) return MP_ERR;
+ return MP_OKAY;
+}
+#endif
+
+mp_err s_read_arc4random(void *p, size_t n);
+mp_err s_read_wincsp(void *p, size_t n);
+mp_err s_read_getrandom(void *p, size_t n);
+mp_err s_read_urandom(void *p, size_t n);
+mp_err s_read_ltm_rng(void *p, size_t n);
+
+mp_err s_mp_rand_platform(void *p, size_t n)
+{
+ mp_err err = MP_ERR;
+ if ((err != MP_OKAY) && MP_HAS(S_READ_ARC4RANDOM)) err = s_read_arc4random(p, n);
+ if ((err != MP_OKAY) && MP_HAS(S_READ_WINCSP)) err = s_read_wincsp(p, n);
+ if ((err != MP_OKAY) && MP_HAS(S_READ_GETRANDOM)) err = s_read_getrandom(p, n);
+ if ((err != MP_OKAY) && MP_HAS(S_READ_URANDOM)) err = s_read_urandom(p, n);
+ if ((err != MP_OKAY) && MP_HAS(S_READ_LTM_RNG)) err = s_read_ltm_rng(p, n);
+ return err;
+}
+
+#endif
+
+/* End: bn_s_mp_rand_platform.c */
+
+/* Start: bn_s_mp_reverse.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_REVERSE_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* reverse an array, used for radix code */
+void s_mp_reverse(unsigned char *s, size_t len)
+{
+ size_t ix, iy;
+ unsigned char t;
+
+ ix = 0u;
+ iy = len - 1u;
+ while (ix < iy) {
+ t = s[ix];
+ s[ix] = s[iy];
+ s[iy] = t;
+ ++ix;
+ --iy;
+ }
+}
+#endif
+
+/* End: bn_s_mp_reverse.c */
+
+/* Start: bn_s_mp_sqr.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_SQR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */
+mp_err s_mp_sqr(const mp_int *a, mp_int *b)
+{
+ mp_int t;
+ int ix, iy, pa;
+ mp_err err;
+ mp_word r;
+ mp_digit u, tmpx, *tmpt;
+
+ pa = a->used;
+ if ((err = mp_init_size(&t, (2 * pa) + 1)) != MP_OKAY) {
+ return err;
+ }
+
+ /* default used is maximum possible size */
+ t.used = (2 * pa) + 1;
+
+ for (ix = 0; ix < pa; ix++) {
+ /* first calculate the digit at 2*ix */
+ /* calculate double precision result */
+ r = (mp_word)t.dp[2*ix] +
+ ((mp_word)a->dp[ix] * (mp_word)a->dp[ix]);
+
+ /* store lower part in result */
+ t.dp[ix+ix] = (mp_digit)(r & (mp_word)MP_MASK);
+
+ /* get the carry */
+ u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
+
+ /* left hand side of A[ix] * A[iy] */
+ tmpx = a->dp[ix];
+
+ /* alias for where to store the results */
+ tmpt = t.dp + ((2 * ix) + 1);
+
+ for (iy = ix + 1; iy < pa; iy++) {
+ /* first calculate the product */
+ r = (mp_word)tmpx * (mp_word)a->dp[iy];
+
+ /* now calculate the double precision result, note we use
+ * addition instead of *2 since it's easier to optimize
+ */
+ r = (mp_word)*tmpt + r + r + (mp_word)u;
+
+ /* store lower part */
+ *tmpt++ = (mp_digit)(r & (mp_word)MP_MASK);
+
+ /* get carry */
+ u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
+ }
+ /* propagate upwards */
+ while (u != 0uL) {
+ r = (mp_word)*tmpt + (mp_word)u;
+ *tmpt++ = (mp_digit)(r & (mp_word)MP_MASK);
+ u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
+ }
+ }
+
+ mp_clamp(&t);
+ mp_exch(&t, b);
+ mp_clear(&t);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_s_mp_sqr.c */
+
+/* Start: bn_s_mp_sqr_fast.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_SQR_FAST_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* the jist of squaring...
+ * you do like mult except the offset of the tmpx [one that
+ * starts closer to zero] can't equal the offset of tmpy.
+ * So basically you set up iy like before then you min it with
+ * (ty-tx) so that it never happens. You double all those
+ * you add in the inner loop
+
+After that loop you do the squares and add them in.
+*/
+
+mp_err s_mp_sqr_fast(const mp_int *a, mp_int *b)
+{
+ int olduse, pa, ix, iz;
+ mp_digit W[MP_WARRAY], *tmpx;
+ mp_word W1;
+ mp_err err;
+
+ /* grow the destination as required */
+ pa = a->used + a->used;
+ if (b->alloc < pa) {
+ if ((err = mp_grow(b, pa)) != MP_OKAY) {
+ return err;
+ }
+ }
+
+ /* number of output digits to produce */
+ W1 = 0;
+ for (ix = 0; ix < pa; ix++) {
+ int tx, ty, iy;
+ mp_word _W;
+ mp_digit *tmpy;
+
+ /* clear counter */
+ _W = 0;
+
+ /* get offsets into the two bignums */
+ ty = MP_MIN(a->used-1, ix);
+ tx = ix - ty;
+
+ /* setup temp aliases */
+ tmpx = a->dp + tx;
+ tmpy = a->dp + ty;
+
+ /* this is the number of times the loop will iterrate, essentially
+ while (tx++ < a->used && ty-- >= 0) { ... }
+ */
+ iy = MP_MIN(a->used-tx, ty+1);
+
+ /* now for squaring tx can never equal ty
+ * we halve the distance since they approach at a rate of 2x
+ * and we have to round because odd cases need to be executed
+ */
+ iy = MP_MIN(iy, ((ty-tx)+1)>>1);
+
+ /* execute loop */
+ for (iz = 0; iz < iy; iz++) {
+ _W += (mp_word)*tmpx++ * (mp_word)*tmpy--;
+ }
+
+ /* double the inner product and add carry */
+ _W = _W + _W + W1;
+
+ /* even columns have the square term in them */
+ if (((unsigned)ix & 1u) == 0u) {
+ _W += (mp_word)a->dp[ix>>1] * (mp_word)a->dp[ix>>1];
+ }
+
+ /* store it */
+ W[ix] = (mp_digit)_W & MP_MASK;
+
+ /* make next carry */
+ W1 = _W >> (mp_word)MP_DIGIT_BIT;
+ }
+
+ /* setup dest */
+ olduse = b->used;
+ b->used = a->used+a->used;
+
+ {
+ mp_digit *tmpb;
+ tmpb = b->dp;
+ for (ix = 0; ix < pa; ix++) {
+ *tmpb++ = W[ix] & MP_MASK;
+ }
+
+ /* clear unused digits [that existed in the old copy of c] */
+ MP_ZERO_DIGITS(tmpb, olduse - ix);
+ }
+ mp_clamp(b);
+ return MP_OKAY;
+}
+#endif
+
+/* End: bn_s_mp_sqr_fast.c */
+
+/* Start: bn_s_mp_sub.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_SUB_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* low level subtraction (assumes |a| > |b|), HAC pp.595 Algorithm 14.9 */
+mp_err s_mp_sub(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ int olduse, min, max;
+ mp_err err;
+
+ /* find sizes */
+ min = b->used;
+ max = a->used;
+
+ /* init result */
+ if (c->alloc < max) {
+ if ((err = mp_grow(c, max)) != MP_OKAY) {
+ return err;
+ }
+ }
+ olduse = c->used;
+ c->used = max;
+
+ {
+ mp_digit u, *tmpa, *tmpb, *tmpc;
+ int i;
+
+ /* alias for digit pointers */
+ tmpa = a->dp;
+ tmpb = b->dp;
+ tmpc = c->dp;
+
+ /* set carry to zero */
+ u = 0;
+ for (i = 0; i < min; i++) {
+ /* T[i] = A[i] - B[i] - U */
+ *tmpc = (*tmpa++ - *tmpb++) - u;
+
+ /* U = carry bit of T[i]
+ * Note this saves performing an AND operation since
+ * if a carry does occur it will propagate all the way to the
+ * MSB. As a result a single shift is enough to get the carry
+ */
+ u = *tmpc >> (MP_SIZEOF_BITS(mp_digit) - 1u);
+
+ /* Clear carry from T[i] */
+ *tmpc++ &= MP_MASK;
+ }
+
+ /* now copy higher words if any, e.g. if A has more digits than B */
+ for (; i < max; i++) {
+ /* T[i] = A[i] - U */
+ *tmpc = *tmpa++ - u;
+
+ /* U = carry bit of T[i] */
+ u = *tmpc >> (MP_SIZEOF_BITS(mp_digit) - 1u);
+
+ /* Clear carry from T[i] */
+ *tmpc++ &= MP_MASK;
+ }
+
+ /* clear digits above used (since we may not have grown result above) */
+ MP_ZERO_DIGITS(tmpc, olduse - c->used);
+ }
+
+ mp_clamp(c);
+ return MP_OKAY;
+}
+
+#endif
+
+/* End: bn_s_mp_sub.c */
+
+/* Start: bn_s_mp_toom_mul.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_TOOM_MUL_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* multiplication using the Toom-Cook 3-way algorithm
+ *
+ * Much more complicated than Karatsuba but has a lower
+ * asymptotic running time of O(N**1.464). This algorithm is
+ * only particularly useful on VERY large inputs
+ * (we're talking 1000s of digits here...).
+*/
+
+/*
+ This file contains code from J. Arndt's book "Matters Computational"
+ and the accompanying FXT-library with permission of the author.
+*/
+
+/*
+ Setup from
+
+ Chung, Jaewook, and M. Anwar Hasan. "Asymmetric squaring formulae."
+ 18th IEEE Symposium on Computer Arithmetic (ARITH'07). IEEE, 2007.
+
+ The interpolation from above needed one temporary variable more
+ than the interpolation here:
+
+ Bodrato, Marco, and Alberto Zanoni. "What about Toom-Cook matrices optimality."
+ Centro Vito Volterra Universita di Roma Tor Vergata (2006)
+*/
+
+mp_err s_mp_toom_mul(const mp_int *a, const mp_int *b, mp_int *c)
+{
+ mp_int S1, S2, T1, a0, a1, a2, b0, b1, b2;
+ int B, count;
+ mp_err err;
+
+ /* init temps */
+ if ((err = mp_init_multi(&S1, &S2, &T1, NULL)) != MP_OKAY) {
+ return err;
+ }
+
+ /* B */
+ B = MP_MIN(a->used, b->used) / 3;
+
+ /** a = a2 * x^2 + a1 * x + a0; */
+ if ((err = mp_init_size(&a0, B)) != MP_OKAY) goto LBL_ERRa0;
+
+ for (count = 0; count < B; count++) {
+ a0.dp[count] = a->dp[count];
+ a0.used++;
+ }
+ mp_clamp(&a0);
+ if ((err = mp_init_size(&a1, B)) != MP_OKAY) goto LBL_ERRa1;
+ for (; count < (2 * B); count++) {
+ a1.dp[count - B] = a->dp[count];
+ a1.used++;
+ }
+ mp_clamp(&a1);
+ if ((err = mp_init_size(&a2, B + (a->used - (3 * B)))) != MP_OKAY) goto LBL_ERRa2;
+ for (; count < a->used; count++) {
+ a2.dp[count - (2 * B)] = a->dp[count];
+ a2.used++;
+ }
+ mp_clamp(&a2);
+
+ /** b = b2 * x^2 + b1 * x + b0; */
+ if ((err = mp_init_size(&b0, B)) != MP_OKAY) goto LBL_ERRb0;
+ for (count = 0; count < B; count++) {
+ b0.dp[count] = b->dp[count];
+ b0.used++;
+ }
+ mp_clamp(&b0);
+ if ((err = mp_init_size(&b1, B)) != MP_OKAY) goto LBL_ERRb1;
+ for (; count < (2 * B); count++) {
+ b1.dp[count - B] = b->dp[count];
+ b1.used++;
+ }
+ mp_clamp(&b1);
+ if ((err = mp_init_size(&b2, B + (b->used - (3 * B)))) != MP_OKAY) goto LBL_ERRb2;
+ for (; count < b->used; count++) {
+ b2.dp[count - (2 * B)] = b->dp[count];
+ b2.used++;
+ }
+ mp_clamp(&b2);
+
+ /** \\ S1 = (a2+a1+a0) * (b2+b1+b0); */
+ /** T1 = a2 + a1; */
+ if ((err = mp_add(&a2, &a1, &T1)) != MP_OKAY) goto LBL_ERR;
+
+ /** S2 = T1 + a0; */
+ if ((err = mp_add(&T1, &a0, &S2)) != MP_OKAY) goto LBL_ERR;
+
+ /** c = b2 + b1; */
+ if ((err = mp_add(&b2, &b1, c)) != MP_OKAY) goto LBL_ERR;
+
+ /** S1 = c + b0; */
+ if ((err = mp_add(c, &b0, &S1)) != MP_OKAY) goto LBL_ERR;
+
+ /** S1 = S1 * S2; */
+ if ((err = mp_mul(&S1, &S2, &S1)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\S2 = (4*a2+2*a1+a0) * (4*b2+2*b1+b0); */
+ /** T1 = T1 + a2; */
+ if ((err = mp_add(&T1, &a2, &T1)) != MP_OKAY) goto LBL_ERR;
+
+ /** T1 = T1 << 1; */
+ if ((err = mp_mul_2(&T1, &T1)) != MP_OKAY) goto LBL_ERR;
+
+ /** T1 = T1 + a0; */
+ if ((err = mp_add(&T1, &a0, &T1)) != MP_OKAY) goto LBL_ERR;
+
+ /** c = c + b2; */
+ if ((err = mp_add(c, &b2, c)) != MP_OKAY) goto LBL_ERR;
+
+ /** c = c << 1; */
+ if ((err = mp_mul_2(c, c)) != MP_OKAY) goto LBL_ERR;
+
+ /** c = c + b0; */
+ if ((err = mp_add(c, &b0, c)) != MP_OKAY) goto LBL_ERR;
+
+ /** S2 = T1 * c; */
+ if ((err = mp_mul(&T1, c, &S2)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\S3 = (a2-a1+a0) * (b2-b1+b0); */
+ /** a1 = a2 - a1; */
+ if ((err = mp_sub(&a2, &a1, &a1)) != MP_OKAY) goto LBL_ERR;
+
+ /** a1 = a1 + a0; */
+ if ((err = mp_add(&a1, &a0, &a1)) != MP_OKAY) goto LBL_ERR;
+
+ /** b1 = b2 - b1; */
+ if ((err = mp_sub(&b2, &b1, &b1)) != MP_OKAY) goto LBL_ERR;
+
+ /** b1 = b1 + b0; */
+ if ((err = mp_add(&b1, &b0, &b1)) != MP_OKAY) goto LBL_ERR;
+
+ /** a1 = a1 * b1; */
+ if ((err = mp_mul(&a1, &b1, &a1)) != MP_OKAY) goto LBL_ERR;
+
+ /** b1 = a2 * b2; */
+ if ((err = mp_mul(&a2, &b2, &b1)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\S2 = (S2 - S3)/3; */
+ /** S2 = S2 - a1; */
+ if ((err = mp_sub(&S2, &a1, &S2)) != MP_OKAY) goto LBL_ERR;
+
+ /** S2 = S2 / 3; \\ this is an exact division */
+ if ((err = mp_div_3(&S2, &S2, NULL)) != MP_OKAY) goto LBL_ERR;
+
+ /** a1 = S1 - a1; */
+ if ((err = mp_sub(&S1, &a1, &a1)) != MP_OKAY) goto LBL_ERR;
+
+ /** a1 = a1 >> 1; */
+ if ((err = mp_div_2(&a1, &a1)) != MP_OKAY) goto LBL_ERR;
+
+ /** a0 = a0 * b0; */
+ if ((err = mp_mul(&a0, &b0, &a0)) != MP_OKAY) goto LBL_ERR;
+
+ /** S1 = S1 - a0; */
+ if ((err = mp_sub(&S1, &a0, &S1)) != MP_OKAY) goto LBL_ERR;
+
+ /** S2 = S2 - S1; */
+ if ((err = mp_sub(&S2, &S1, &S2)) != MP_OKAY) goto LBL_ERR;
+
+ /** S2 = S2 >> 1; */
+ if ((err = mp_div_2(&S2, &S2)) != MP_OKAY) goto LBL_ERR;
+
+ /** S1 = S1 - a1; */
+ if ((err = mp_sub(&S1, &a1, &S1)) != MP_OKAY) goto LBL_ERR;
+
+ /** S1 = S1 - b1; */
+ if ((err = mp_sub(&S1, &b1, &S1)) != MP_OKAY) goto LBL_ERR;
+
+ /** T1 = b1 << 1; */
+ if ((err = mp_mul_2(&b1, &T1)) != MP_OKAY) goto LBL_ERR;
+
+ /** S2 = S2 - T1; */
+ if ((err = mp_sub(&S2, &T1, &S2)) != MP_OKAY) goto LBL_ERR;
+
+ /** a1 = a1 - S2; */
+ if ((err = mp_sub(&a1, &S2, &a1)) != MP_OKAY) goto LBL_ERR;
+
+
+ /** P = b1*x^4+ S2*x^3+ S1*x^2+ a1*x + a0; */
+ if ((err = mp_lshd(&b1, 4 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_lshd(&S2, 3 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(&b1, &S2, &b1)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_lshd(&S1, 2 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(&b1, &S1, &b1)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_lshd(&a1, 1 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(&b1, &a1, &b1)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(&b1, &a0, c)) != MP_OKAY) goto LBL_ERR;
+
+ /** a * b - P */
+
+
+LBL_ERR:
+ mp_clear(&b2);
+LBL_ERRb2:
+ mp_clear(&b1);
+LBL_ERRb1:
+ mp_clear(&b0);
+LBL_ERRb0:
+ mp_clear(&a2);
+LBL_ERRa2:
+ mp_clear(&a1);
+LBL_ERRa1:
+ mp_clear(&a0);
+LBL_ERRa0:
+ mp_clear_multi(&S1, &S2, &T1, NULL);
+ return err;
+}
+
+#endif
+
+/* End: bn_s_mp_toom_mul.c */
+
+/* Start: bn_s_mp_toom_sqr.c */
+#include "tommath_private.h"
+#ifdef BN_S_MP_TOOM_SQR_C
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* squaring using Toom-Cook 3-way algorithm */
+
+/*
+ This file contains code from J. Arndt's book "Matters Computational"
+ and the accompanying FXT-library with permission of the author.
+*/
+
+/* squaring using Toom-Cook 3-way algorithm */
+/*
+ Setup and interpolation from algorithm SQR_3 in
+
+ Chung, Jaewook, and M. Anwar Hasan. "Asymmetric squaring formulae."
+ 18th IEEE Symposium on Computer Arithmetic (ARITH'07). IEEE, 2007.
+
+*/
+mp_err s_mp_toom_sqr(const mp_int *a, mp_int *b)
+{
+ mp_int S0, a0, a1, a2;
+ mp_digit *tmpa, *tmpc;
+ int B, count;
+ mp_err err;
+
+
+ /* init temps */
+ if ((err = mp_init(&S0)) != MP_OKAY) {
+ return err;
+ }
+
+ /* B */
+ B = a->used / 3;
+
+ /** a = a2 * x^2 + a1 * x + a0; */
+ if ((err = mp_init_size(&a0, B)) != MP_OKAY) goto LBL_ERRa0;
+
+ a0.used = B;
+ if ((err = mp_init_size(&a1, B)) != MP_OKAY) goto LBL_ERRa1;
+ a1.used = B;
+ if ((err = mp_init_size(&a2, B + (a->used - (3 * B)))) != MP_OKAY) goto LBL_ERRa2;
+
+ tmpa = a->dp;
+ tmpc = a0.dp;
+ for (count = 0; count < B; count++) {
+ *tmpc++ = *tmpa++;
+ }
+ tmpc = a1.dp;
+ for (; count < (2 * B); count++) {
+ *tmpc++ = *tmpa++;
+ }
+ tmpc = a2.dp;
+ for (; count < a->used; count++) {
+ *tmpc++ = *tmpa++;
+ a2.used++;
+ }
+ mp_clamp(&a0);
+ mp_clamp(&a1);
+ mp_clamp(&a2);
+
+ /** S0 = a0^2; */
+ if ((err = mp_sqr(&a0, &S0)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\S1 = (a2 + a1 + a0)^2 */
+ /** \\S2 = (a2 - a1 + a0)^2 */
+ /** \\S1 = a0 + a2; */
+ /** a0 = a0 + a2; */
+ if ((err = mp_add(&a0, &a2, &a0)) != MP_OKAY) goto LBL_ERR;
+ /** \\S2 = S1 - a1; */
+ /** b = a0 - a1; */
+ if ((err = mp_sub(&a0, &a1, b)) != MP_OKAY) goto LBL_ERR;
+ /** \\S1 = S1 + a1; */
+ /** a0 = a0 + a1; */
+ if ((err = mp_add(&a0, &a1, &a0)) != MP_OKAY) goto LBL_ERR;
+ /** \\S1 = S1^2; */
+ /** a0 = a0^2; */
+ if ((err = mp_sqr(&a0, &a0)) != MP_OKAY) goto LBL_ERR;
+ /** \\S2 = S2^2; */
+ /** b = b^2; */
+ if ((err = mp_sqr(b, b)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\ S3 = 2 * a1 * a2 */
+ /** \\S3 = a1 * a2; */
+ /** a1 = a1 * a2; */
+ if ((err = mp_mul(&a1, &a2, &a1)) != MP_OKAY) goto LBL_ERR;
+ /** \\S3 = S3 << 1; */
+ /** a1 = a1 << 1; */
+ if ((err = mp_mul_2(&a1, &a1)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\S4 = a2^2; */
+ /** a2 = a2^2; */
+ if ((err = mp_sqr(&a2, &a2)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\ tmp = (S1 + S2)/2 */
+ /** \\tmp = S1 + S2; */
+ /** b = a0 + b; */
+ if ((err = mp_add(&a0, b, b)) != MP_OKAY) goto LBL_ERR;
+ /** \\tmp = tmp >> 1; */
+ /** b = b >> 1; */
+ if ((err = mp_div_2(b, b)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\ S1 = S1 - tmp - S3 */
+ /** \\S1 = S1 - tmp; */
+ /** a0 = a0 - b; */
+ if ((err = mp_sub(&a0, b, &a0)) != MP_OKAY) goto LBL_ERR;
+ /** \\S1 = S1 - S3; */
+ /** a0 = a0 - a1; */
+ if ((err = mp_sub(&a0, &a1, &a0)) != MP_OKAY) goto LBL_ERR;
+
+ /** \\S2 = tmp - S4 -S0 */
+ /** \\S2 = tmp - S4; */
+ /** b = b - a2; */
+ if ((err = mp_sub(b, &a2, b)) != MP_OKAY) goto LBL_ERR;
+ /** \\S2 = S2 - S0; */
+ /** b = b - S0; */
+ if ((err = mp_sub(b, &S0, b)) != MP_OKAY) goto LBL_ERR;
+
+
+ /** \\P = S4*x^4 + S3*x^3 + S2*x^2 + S1*x + S0; */
+ /** P = a2*x^4 + a1*x^3 + b*x^2 + a0*x + S0; */
+
+ if ((err = mp_lshd(&a2, 4 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_lshd(&a1, 3 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_lshd(b, 2 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_lshd(&a0, 1 * B)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(&a2, &a1, &a2)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(&a2, b, b)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(b, &a0, b)) != MP_OKAY) goto LBL_ERR;
+ if ((err = mp_add(b, &S0, b)) != MP_OKAY) goto LBL_ERR;
+ /** a^2 - P */
+
+
+LBL_ERR:
+ mp_clear(&a2);
+LBL_ERRa2:
+ mp_clear(&a1);
+LBL_ERRa1:
+ mp_clear(&a0);
+LBL_ERRa0:
+ mp_clear(&S0);
+
+ return err;
+}
+
+#endif
+
+/* End: bn_s_mp_toom_sqr.c */
+
+
+/* EOF */
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/testme.sh b/third_party/heimdal/lib/hcrypto/libtommath/testme.sh
new file mode 100755
index 0000000..40fa32d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/testme.sh
@@ -0,0 +1,394 @@
+#!/bin/bash
+#
+# return values of this script are:
+# 0 success
+# 128 a test failed
+# >0 the number of timed-out tests
+# 255 parsing of parameters failed
+
+set -e
+
+if [ -f /proc/cpuinfo ]
+then
+ MAKE_JOBS=$(( ($(cat /proc/cpuinfo | grep -E '^processor[[:space:]]*:' | tail -n -1 | cut -d':' -f2) + 1) * 2 + 1 ))
+else
+ MAKE_JOBS=8
+fi
+
+ret=0
+TEST_CFLAGS=""
+
+_help()
+{
+ echo "Usage options for $(basename $0) [--with-cc=arg [other options]]"
+ echo
+ echo "Executing this script without any parameter will only run the default"
+ echo "configuration that has automatically been determined for the"
+ echo "architecture you're running."
+ echo
+ echo " --with-cc=* The compiler(s) to use for the tests"
+ echo " This is an option that will be iterated."
+ echo
+ echo " --test-vs-mtest=* Run test vs. mtest for '*' operations."
+ echo " Only the first of each options will be"
+ echo " taken into account."
+ echo
+ echo "To be able to specify options a compiler has to be given with"
+ echo "the option --with-cc=compilername"
+ echo "All other options will be tested with all MP_xBIT configurations."
+ echo
+ echo " --with-{m64,m32,mx32} The architecture(s) to build and test"
+ echo " for, e.g. --with-mx32."
+ echo " This is an option that will be iterated,"
+ echo " multiple selections are possible."
+ echo " The mx32 architecture is not supported"
+ echo " by clang and will not be executed."
+ echo
+ echo " --cflags=* Give an option to the compiler,"
+ echo " e.g. --cflags=-g"
+ echo " This is an option that will always be"
+ echo " passed as parameter to CC."
+ echo
+ echo " --make-option=* Give an option to make,"
+ echo " e.g. --make-option=\"-f makefile.shared\""
+ echo " This is an option that will always be"
+ echo " passed as parameter to make."
+ echo
+ echo " --with-low-mp Also build&run tests with -DMP_{8,16,32}BIT."
+ echo
+ echo " --mtest-real-rand Use real random data when running mtest."
+ echo
+ echo " --with-valgrind"
+ echo " --with-valgrind=* Run in valgrind (slow!)."
+ echo
+ echo " --with-travis-valgrind Run with valgrind on Travis on specific branches."
+ echo
+ echo " --valgrind-options Additional Valgrind options"
+ echo " Some of the options like e.g.:"
+ echo " --track-origins=yes add a lot of extra"
+ echo " runtime and may trigger the 30 minutes"
+ echo " timeout."
+ echo
+ echo "Godmode:"
+ echo
+ echo " --all Choose all architectures and gcc and clang"
+ echo " as compilers but does not run valgrind."
+ echo
+ echo " --format Runs the various source-code formatters"
+ echo " and generators and checks if the sources"
+ echo " are clean."
+ echo
+ echo " -h"
+ echo " --help This message"
+ echo
+ echo " -v"
+ echo " --version Prints the version. It is just the number"
+ echo " of git commits to this file, no deeper"
+ echo " meaning attached"
+ exit 0
+}
+
+_die()
+{
+ echo "error $2 while $1"
+ if [ "$2" != "124" ]
+ then
+ exit 128
+ else
+ echo "assuming timeout while running test - continue"
+ local _tail=""
+ which tail >/dev/null && _tail="tail -n 1 test_${suffix}.log" && \
+ echo "last line of test_"${suffix}".log was:" && $_tail && echo ""
+ ret=$(( $ret + 1 ))
+ fi
+}
+
+_make()
+{
+ echo -ne " Compile $1 $2"
+ suffix=$(echo ${1}${2} | tr ' ' '_')
+ CC="$1" CFLAGS="$2 $TEST_CFLAGS" make -j$MAKE_JOBS $3 $MAKE_OPTIONS > /dev/null 2>gcc_errors_${suffix}.log
+ errcnt=$(wc -l < gcc_errors_${suffix}.log)
+ if [[ ${errcnt} -gt 1 ]]; then
+ echo " failed"
+ cat gcc_errors_${suffix}.log
+ exit 128
+ fi
+}
+
+
+_runtest()
+{
+ make clean > /dev/null
+ local _timeout=""
+ which timeout >/dev/null && _timeout="timeout --foreground 90"
+ if [[ "$MAKE_OPTIONS" =~ "tune" ]]
+ then
+ # "make tune" will run "tune_it.sh" automatically, hence "autotune", but it cannot
+ # get switched off without some effort, so we just let it run twice for testing purposes
+ echo -e "\rRun autotune $1 $2"
+ _make "$1" "$2" ""
+ $_timeout $TUNE_CMD > test_${suffix}.log || _die "running autotune" $?
+ else
+ _make "$1" "$2" "test"
+ echo -e "\rRun test $1 $2"
+ $_timeout ./test > test_${suffix}.log || _die "running tests" $?
+ fi
+}
+
+# This is not much more of a C&P of _runtest with a different timeout
+# and the additional valgrind call.
+# TODO: merge
+_runvalgrind()
+{
+ make clean > /dev/null
+ local _timeout=""
+ # 30 minutes? Yes. Had it at 20 minutes and the Valgrind run needed over 25 minutes.
+ # A bit too close for comfort.
+ which timeout >/dev/null && _timeout="timeout --foreground 1800"
+echo "MAKE_OPTIONS = \"$MAKE_OPTIONS\""
+ if [[ "$MAKE_OPTIONS" =~ "tune" ]]
+ then
+echo "autotune branch"
+ _make "$1" "$2" ""
+ # The shell used for /bin/sh is DASH 0.5.7-4ubuntu1 on the author's machine which fails valgrind, so
+ # we just run on instance of etc/tune with the same options as in etc/tune_it.sh
+ echo -e "\rRun etc/tune $1 $2 once inside valgrind"
+ $_timeout $VALGRIND_BIN $VALGRIND_OPTS $TUNE_CMD > test_${suffix}.log || _die "running etc/tune" $?
+ else
+ _make "$1" "$2" "test"
+ echo -e "\rRun test $1 $2 inside valgrind"
+ $_timeout $VALGRIND_BIN $VALGRIND_OPTS ./test > test_${suffix}.log || _die "running tests" $?
+ fi
+}
+
+
+_banner()
+{
+ echo "uname="$(uname -a)
+ [[ "$#" != "0" ]] && (echo $1=$($1 -dumpversion)) || true
+}
+
+_exit()
+{
+ if [ "$ret" == "0" ]
+ then
+ echo "Tests successful"
+ else
+ echo "$ret tests timed out"
+ fi
+
+ exit $ret
+}
+
+ARCHFLAGS=""
+COMPILERS=""
+CFLAGS=""
+WITH_LOW_MP=""
+TEST_VS_MTEST=""
+MTEST_RAND=""
+# timed with an AMD A8-6600K
+# 25 minutes
+#VALGRIND_OPTS=" --track-origins=yes --leak-check=full --show-leak-kinds=all --error-exitcode=1 "
+# 9 minutes (14 minutes with --test-vs-mtest=333333 --mtest-real-rand)
+VALGRIND_OPTS=" --leak-check=full --show-leak-kinds=all --error-exitcode=1 "
+#VALGRIND_OPTS=""
+VALGRIND_BIN=""
+CHECK_FORMAT=""
+TUNE_CMD="./etc/tune -t -r 10 -L 3"
+
+alive_pid=0
+
+function kill_alive() {
+ disown $alive_pid || true
+ kill $alive_pid 2>/dev/null
+}
+
+function start_alive_printing() {
+ [ "$alive_pid" == "0" ] || return 0;
+ for i in `seq 1 10` ; do sleep 300 && echo "Tests still in Progress..."; done &
+ alive_pid=$!
+ trap kill_alive EXIT
+}
+
+while [ $# -gt 0 ];
+do
+ case $1 in
+ "--with-m64" | "--with-m32" | "--with-mx32")
+ ARCHFLAGS="$ARCHFLAGS ${1:6}"
+ ;;
+ --with-cc=*)
+ COMPILERS="$COMPILERS ${1#*=}"
+ ;;
+ --cflags=*)
+ CFLAGS="$CFLAGS ${1#*=}"
+ ;;
+ --valgrind-options=*)
+ VALGRIND_OPTS="$VALGRIND_OPTS ${1#*=}"
+ ;;
+ --with-valgrind*)
+ if [[ ${1#*d} != "" ]]
+ then
+ VALGRIND_BIN="${1#*=}"
+ else
+ VALGRIND_BIN="valgrind"
+ fi
+ start_alive_printing
+ ;;
+ --with-travis-valgrind*)
+ if [[ ("$TRAVIS_BRANCH" == "develop" && "$TRAVIS_PULL_REQUEST" == "false") || "$TRAVIS_BRANCH" == *"valgrind"* || "$TRAVIS_COMMIT_MESSAGE" == *"valgrind"* ]]
+ then
+ if [[ ${1#*d} != "" ]]
+ then
+ VALGRIND_BIN="${1#*=}"
+ else
+ VALGRIND_BIN="valgrind"
+ fi
+ start_alive_printing
+ fi
+ ;;
+ --make-option=*)
+ MAKE_OPTIONS="$MAKE_OPTIONS ${1#*=}"
+ ;;
+ --with-low-mp)
+ WITH_LOW_MP="1"
+ ;;
+ --test-vs-mtest=*)
+ TEST_VS_MTEST="${1#*=}"
+ if ! [ "$TEST_VS_MTEST" -eq "$TEST_VS_MTEST" ] 2> /dev/null
+ then
+ echo "--test-vs-mtest Parameter has to be int"
+ exit 255
+ fi
+ start_alive_printing
+ ;;
+ --mtest-real-rand)
+ MTEST_RAND="-DLTM_MTEST_REAL_RAND"
+ ;;
+ --format)
+ CHECK_FORMAT="1"
+ ;;
+ --all)
+ COMPILERS="gcc clang"
+ ARCHFLAGS="-m64 -m32 -mx32"
+ ;;
+ --help | -h)
+ _help
+ ;;
+ --version | -v)
+ echo $(git rev-list HEAD --count -- testme.sh) || echo "Unknown. Please run in original libtommath git repository."
+ exit 0
+ ;;
+ *)
+ echo "Ignoring option ${1}"
+ ;;
+ esac
+ shift
+done
+
+function _check_git() {
+ git update-index --refresh >/dev/null || true
+ git diff-index --quiet HEAD -- . || ( echo "FAILURE: $*" && exit 1 )
+}
+
+if [[ "$CHECK_FORMAT" == "1" ]]
+then
+ make astyle
+ _check_git "make astyle"
+ perl helper.pl --update-files
+ _check_git "helper.pl --update-files"
+ perl helper.pl --check-all
+ _check_git "helper.pl --check-all"
+ exit $?
+fi
+
+[[ "$VALGRIND_BIN" == "" ]] && VALGRIND_OPTS=""
+
+# default to CC environment variable if no compiler is defined but some other options
+if [[ "$COMPILERS" == "" ]] && [[ "$ARCHFLAGS$MAKE_OPTIONS$CFLAGS" != "" ]]
+then
+ COMPILERS="$CC"
+# default to CC environment variable and run only default config if no option is given
+elif [[ "$COMPILERS" == "" ]]
+then
+ _banner "$CC"
+ if [[ "$VALGRIND_BIN" != "" ]]
+ then
+ _runvalgrind "$CC" ""
+ else
+ _runtest "$CC" ""
+ fi
+ _exit
+fi
+
+
+archflags=( $ARCHFLAGS )
+compilers=( $COMPILERS )
+
+# choosing a compiler without specifying an architecture will use the default architecture
+if [ "${#archflags[@]}" == "0" ]
+then
+ archflags[0]=" "
+fi
+
+_banner
+
+if [[ "$TEST_VS_MTEST" != "" ]]
+then
+ make clean > /dev/null
+ _make "${compilers[0]} ${archflags[0]}" "$CFLAGS" "mtest_opponent"
+ echo
+ _make "gcc" "$MTEST_RAND" "mtest"
+ echo
+ echo "Run test vs. mtest for $TEST_VS_MTEST iterations"
+ _timeout=""
+ which timeout >/dev/null && _timeout="timeout --foreground 1800"
+ $_timeout ./mtest/mtest $TEST_VS_MTEST | $VALGRIND_BIN $VALGRIND_OPTS ./mtest_opponent > valgrind_test.log 2> test_vs_mtest_err.log
+ retval=$?
+ head -n 5 valgrind_test.log
+ tail -n 2 valgrind_test.log
+ exit $retval
+fi
+
+for i in "${compilers[@]}"
+do
+ if [ -z "$(which $i)" ]
+ then
+ echo "Skipped compiler $i, file not found"
+ continue
+ fi
+ compiler_version=$(echo "$i="$($i -dumpversion))
+ if [ "$compiler_version" == "clang=4.2.1" ]
+ then
+ # one of my versions of clang complains about some stuff in stdio.h and stdarg.h ...
+ TEST_CFLAGS="-Wno-typedef-redefinition"
+ else
+ TEST_CFLAGS=""
+ fi
+ echo $compiler_version
+
+ for a in "${archflags[@]}"
+ do
+ if [[ $(expr "$i" : "clang") -ne 0 && "$a" == "-mx32" ]]
+ then
+ echo "clang -mx32 tests skipped"
+ continue
+ fi
+ if [[ "$VALGRIND_BIN" != "" ]]
+ then
+ _runvalgrind "$i $a" "$CFLAGS"
+ [ "$WITH_LOW_MP" != "1" ] && continue
+ _runvalgrind "$i $a" "-DMP_8BIT $CFLAGS"
+ _runvalgrind "$i $a" "-DMP_16BIT $CFLAGS"
+ _runvalgrind "$i $a" "-DMP_32BIT $CFLAGS"
+ else
+ _runtest "$i $a" "$CFLAGS"
+ [ "$WITH_LOW_MP" != "1" ] && continue
+ _runtest "$i $a" "-DMP_8BIT $CFLAGS"
+ _runtest "$i $a" "-DMP_16BIT $CFLAGS"
+ _runtest "$i $a" "-DMP_32BIT $CFLAGS"
+ fi
+ done
+done
+
+_exit
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/tommath.def b/third_party/heimdal/lib/hcrypto/libtommath/tommath.def
new file mode 100644
index 0000000..229fae4
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/tommath.def
@@ -0,0 +1,145 @@
+; libtommath
+;
+; Use this command to produce a 32-bit .lib file, for use in any MSVC version
+; lib -machine:X86 -name:libtommath.dll -def:tommath.def -out:tommath.lib
+; Use this command to produce a 64-bit .lib file, for use in any MSVC version
+; lib -machine:X64 -name:libtommath.dll -def:tommath.def -out:tommath.lib
+;
+EXPORTS
+ mp_2expt
+ mp_abs
+ mp_add
+ mp_add_d
+ mp_addmod
+ mp_and
+ mp_clamp
+ mp_clear
+ mp_clear_multi
+ mp_cmp
+ mp_cmp_d
+ mp_cmp_mag
+ mp_cnt_lsb
+ mp_complement
+ mp_copy
+ mp_count_bits
+ mp_decr
+ mp_div
+ mp_div_2
+ mp_div_2d
+ mp_div_3
+ mp_div_d
+ mp_dr_is_modulus
+ mp_dr_reduce
+ mp_dr_setup
+ mp_error_to_string
+ mp_exch
+ mp_expt_u32
+ mp_exptmod
+ mp_exteuclid
+ mp_fread
+ mp_from_sbin
+ mp_from_ubin
+ mp_fwrite
+ mp_gcd
+ mp_get_double
+ mp_get_i32
+ mp_get_i64
+ mp_get_int
+ mp_get_l
+ mp_get_ll
+ mp_get_long
+ mp_get_long_long
+ mp_get_mag_u32
+ mp_get_mag_u64
+ mp_get_mag_ul
+ mp_get_mag_ull
+ mp_grow
+ mp_incr
+ mp_init
+ mp_init_copy
+ mp_init_i32
+ mp_init_i64
+ mp_init_l
+ mp_init_ll
+ mp_init_multi
+ mp_init_set
+ mp_init_set_int
+ mp_init_size
+ mp_init_u32
+ mp_init_u64
+ mp_init_ul
+ mp_init_ull
+ mp_invmod
+ mp_is_square
+ mp_iseven
+ mp_isodd
+ mp_kronecker
+ mp_lcm
+ mp_log_u32
+ mp_lshd
+ mp_mod
+ mp_mod_2d
+ mp_mod_d
+ mp_montgomery_calc_normalization
+ mp_montgomery_reduce
+ mp_montgomery_setup
+ mp_mul
+ mp_mul_2
+ mp_mul_2d
+ mp_mul_d
+ mp_mulmod
+ mp_neg
+ mp_or
+ mp_pack
+ mp_pack_count
+ mp_prime_fermat
+ mp_prime_frobenius_underwood
+ mp_prime_is_prime
+ mp_prime_miller_rabin
+ mp_prime_next_prime
+ mp_prime_rabin_miller_trials
+ mp_prime_rand
+ mp_prime_strong_lucas_selfridge
+ mp_radix_size
+ mp_rand
+ mp_read_radix
+ mp_reduce
+ mp_reduce_2k
+ mp_reduce_2k_l
+ mp_reduce_2k_setup
+ mp_reduce_2k_setup_l
+ mp_reduce_is_2k
+ mp_reduce_is_2k_l
+ mp_reduce_setup
+ mp_root_u32
+ mp_rshd
+ mp_sbin_size
+ mp_set
+ mp_set_double
+ mp_set_i32
+ mp_set_i64
+ mp_set_int
+ mp_set_l
+ mp_set_ll
+ mp_set_long
+ mp_set_long_long
+ mp_set_u32
+ mp_set_u64
+ mp_set_ul
+ mp_set_ull
+ mp_shrink
+ mp_signed_rsh
+ mp_sqr
+ mp_sqrmod
+ mp_sqrt
+ mp_sqrtmod_prime
+ mp_sub
+ mp_sub_d
+ mp_submod
+ mp_to_radix
+ mp_to_sbin
+ mp_to_ubin
+ mp_ubin_size
+ mp_unpack
+ mp_xor
+ mp_zero
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/tommath.h b/third_party/heimdal/lib/hcrypto/libtommath/tommath.h
new file mode 100644
index 0000000..e87bb08
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/tommath.h
@@ -0,0 +1,781 @@
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#ifndef BN_H_
+#define BN_H_
+
+#include <stdint.h>
+#include <stddef.h>
+#include <limits.h>
+
+#ifdef LTM_NO_FILE
+# warning LTM_NO_FILE has been deprecated, use MP_NO_FILE.
+# define MP_NO_FILE
+#endif
+
+#ifndef MP_NO_FILE
+# include <stdio.h>
+#endif
+
+#ifdef MP_8BIT
+# ifdef _MSC_VER
+# pragma message("8-bit (MP_8BIT) support is deprecated and will be dropped completely in the next version.")
+# else
+# warning "8-bit (MP_8BIT) support is deprecated and will be dropped completely in the next version."
+# endif
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* MS Visual C++ doesn't have a 128bit type for words, so fall back to 32bit MPI's (where words are 64bit) */
+#if (defined(_MSC_VER) || defined(__LLP64__) || defined(__e2k__) || defined(__LCC__)) && !defined(MP_64BIT)
+# define MP_32BIT
+#endif
+
+/* detect 64-bit mode if possible */
+#if defined(__x86_64__) || defined(_M_X64) || defined(_M_AMD64) || \
+ defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__) || \
+ defined(__s390x__) || defined(__arch64__) || defined(__aarch64__) || \
+ defined(__sparcv9) || defined(__sparc_v9__) || defined(__sparc64__) || \
+ defined(__ia64) || defined(__ia64__) || defined(__itanium__) || defined(_M_IA64) || \
+ defined(__LP64__) || defined(_LP64) || defined(__64BIT__)
+# if !(defined(MP_64BIT) || defined(MP_32BIT) || defined(MP_16BIT) || defined(MP_8BIT))
+# if defined(__GNUC__) && !defined(__hppa)
+/* we support 128bit integers only via: __attribute__((mode(TI))) */
+# define MP_64BIT
+# else
+/* otherwise we fall back to MP_32BIT even on 64bit platforms */
+# define MP_32BIT
+# endif
+# endif
+#endif
+
+#ifdef MP_DIGIT_BIT
+# error Defining MP_DIGIT_BIT is disallowed, use MP_8/16/31/32/64BIT
+#endif
+
+/* some default configurations.
+ *
+ * A "mp_digit" must be able to hold MP_DIGIT_BIT + 1 bits
+ * A "mp_word" must be able to hold 2*MP_DIGIT_BIT + 1 bits
+ *
+ * At the very least a mp_digit must be able to hold 7 bits
+ * [any size beyond that is ok provided it doesn't overflow the data type]
+ */
+
+#ifdef MP_8BIT
+typedef uint8_t mp_digit;
+typedef uint16_t private_mp_word;
+# define MP_DIGIT_BIT 7
+#elif defined(MP_16BIT)
+typedef uint16_t mp_digit;
+typedef uint32_t private_mp_word;
+# define MP_DIGIT_BIT 15
+#elif defined(MP_64BIT)
+/* for GCC only on supported platforms */
+typedef uint64_t mp_digit;
+#if defined(__GNUC__)
+typedef unsigned long private_mp_word __attribute__((mode(TI)));
+#endif
+# define MP_DIGIT_BIT 60
+#else
+typedef uint32_t mp_digit;
+typedef uint64_t private_mp_word;
+# ifdef MP_31BIT
+/*
+ * This is an extension that uses 31-bit digits.
+ * Please be aware that not all functions support this size, especially s_mp_mul_digs_fast
+ * will be reduced to work on small numbers only:
+ * Up to 8 limbs, 248 bits instead of up to 512 limbs, 15872 bits with MP_28BIT.
+ */
+# define MP_DIGIT_BIT 31
+# else
+/* default case is 28-bit digits, defines MP_28BIT as a handy macro to test */
+# define MP_DIGIT_BIT 28
+# define MP_28BIT
+# endif
+#endif
+
+/* mp_word is a private type */
+#define mp_word MP_DEPRECATED_PRAGMA("mp_word has been made private") private_mp_word
+
+#define MP_SIZEOF_MP_DIGIT (MP_DEPRECATED_PRAGMA("MP_SIZEOF_MP_DIGIT has been deprecated, use sizeof (mp_digit)") sizeof (mp_digit))
+
+#define MP_MASK ((((mp_digit)1)<<((mp_digit)MP_DIGIT_BIT))-((mp_digit)1))
+#define MP_DIGIT_MAX MP_MASK
+
+/* Primality generation flags */
+#define MP_PRIME_BBS 0x0001 /* BBS style prime */
+#define MP_PRIME_SAFE 0x0002 /* Safe prime (p-1)/2 == prime */
+#define MP_PRIME_2MSB_ON 0x0008 /* force 2nd MSB to 1 */
+
+#define LTM_PRIME_BBS (MP_DEPRECATED_PRAGMA("LTM_PRIME_BBS has been deprecated, use MP_PRIME_BBS") MP_PRIME_BBS)
+#define LTM_PRIME_SAFE (MP_DEPRECATED_PRAGMA("LTM_PRIME_SAFE has been deprecated, use MP_PRIME_SAFE") MP_PRIME_SAFE)
+#define LTM_PRIME_2MSB_ON (MP_DEPRECATED_PRAGMA("LTM_PRIME_2MSB_ON has been deprecated, use MP_PRIME_2MSB_ON") MP_PRIME_2MSB_ON)
+
+#ifdef MP_USE_ENUMS
+typedef enum {
+ MP_ZPOS = 0, /* positive */
+ MP_NEG = 1 /* negative */
+} mp_sign;
+typedef enum {
+ MP_LT = -1, /* less than */
+ MP_EQ = 0, /* equal */
+ MP_GT = 1 /* greater than */
+} mp_ord;
+typedef enum {
+ MP_NO = 0,
+ MP_YES = 1
+} mp_bool;
+typedef enum {
+ MP_OKAY = 0, /* no error */
+ MP_ERR = -1, /* unknown error */
+ MP_MEM = -2, /* out of mem */
+ MP_VAL = -3, /* invalid input */
+ MP_ITER = -4, /* maximum iterations reached */
+ MP_BUF = -5 /* buffer overflow, supplied buffer too small */
+} mp_err;
+typedef enum {
+ MP_LSB_FIRST = -1,
+ MP_MSB_FIRST = 1
+} mp_order;
+typedef enum {
+ MP_LITTLE_ENDIAN = -1,
+ MP_NATIVE_ENDIAN = 0,
+ MP_BIG_ENDIAN = 1
+} mp_endian;
+#else
+typedef int mp_sign;
+#define MP_ZPOS 0 /* positive integer */
+#define MP_NEG 1 /* negative */
+typedef int mp_ord;
+#define MP_LT -1 /* less than */
+#define MP_EQ 0 /* equal to */
+#define MP_GT 1 /* greater than */
+typedef int mp_bool;
+#define MP_YES 1
+#define MP_NO 0
+typedef int mp_err;
+#define MP_OKAY 0 /* no error */
+#define MP_ERR -1 /* unknown error */
+#define MP_MEM -2 /* out of mem */
+#define MP_VAL -3 /* invalid input */
+#define MP_RANGE (MP_DEPRECATED_PRAGMA("MP_RANGE has been deprecated in favor of MP_VAL") MP_VAL)
+#define MP_ITER -4 /* maximum iterations reached */
+#define MP_BUF -5 /* buffer overflow, supplied buffer too small */
+typedef int mp_order;
+#define MP_LSB_FIRST -1
+#define MP_MSB_FIRST 1
+typedef int mp_endian;
+#define MP_LITTLE_ENDIAN -1
+#define MP_NATIVE_ENDIAN 0
+#define MP_BIG_ENDIAN 1
+#endif
+
+/* tunable cutoffs */
+
+#ifndef MP_FIXED_CUTOFFS
+extern int
+KARATSUBA_MUL_CUTOFF,
+KARATSUBA_SQR_CUTOFF,
+TOOM_MUL_CUTOFF,
+TOOM_SQR_CUTOFF;
+#endif
+
+/* define this to use lower memory usage routines (exptmods mostly) */
+/* #define MP_LOW_MEM */
+
+/* default precision */
+#ifndef MP_PREC
+# ifndef MP_LOW_MEM
+# define PRIVATE_MP_PREC 32 /* default digits of precision */
+# elif defined(MP_8BIT)
+# define PRIVATE_MP_PREC 16 /* default digits of precision */
+# else
+# define PRIVATE_MP_PREC 8 /* default digits of precision */
+# endif
+# define MP_PREC (MP_DEPRECATED_PRAGMA("MP_PREC is an internal macro") PRIVATE_MP_PREC)
+#endif
+
+/* size of comba arrays, should be at least 2 * 2**(BITS_PER_WORD - BITS_PER_DIGIT*2) */
+#define PRIVATE_MP_WARRAY (int)(1uLL << (((CHAR_BIT * sizeof(private_mp_word)) - (2 * MP_DIGIT_BIT)) + 1))
+#define MP_WARRAY (MP_DEPRECATED_PRAGMA("MP_WARRAY is an internal macro") PRIVATE_MP_WARRAY)
+
+#if defined(__GNUC__) && __GNUC__ >= 4
+# define MP_NULL_TERMINATED __attribute__((sentinel))
+#else
+# define MP_NULL_TERMINATED
+#endif
+
+/*
+ * MP_WUR - warn unused result
+ * ---------------------------
+ *
+ * The result of functions annotated with MP_WUR must be
+ * checked and cannot be ignored.
+ *
+ * Most functions in libtommath return an error code.
+ * This error code must be checked in order to prevent crashes or invalid
+ * results.
+ *
+ * If you still want to avoid the error checks for quick and dirty programs
+ * without robustness guarantees, you can `#define MP_WUR` before including
+ * tommath.h, disabling the warnings.
+ */
+#ifndef MP_WUR
+# if defined(__GNUC__) && __GNUC__ >= 4
+# define MP_WUR __attribute__((warn_unused_result))
+# else
+# define MP_WUR
+# endif
+#endif
+
+#if defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 405)
+# define MP_DEPRECATED(x) __attribute__((deprecated("replaced by " #x)))
+# define PRIVATE_MP_DEPRECATED_PRAGMA(s) _Pragma(#s)
+# define MP_DEPRECATED_PRAGMA(s) PRIVATE_MP_DEPRECATED_PRAGMA(GCC warning s)
+#elif defined(_MSC_VER) && _MSC_VER >= 1500
+# define MP_DEPRECATED(x) __declspec(deprecated("replaced by " #x))
+# define MP_DEPRECATED_PRAGMA(s) __pragma(message(s))
+#else
+# define MP_DEPRECATED(s)
+# define MP_DEPRECATED_PRAGMA(s)
+#endif
+
+#define DIGIT_BIT (MP_DEPRECATED_PRAGMA("DIGIT_BIT macro is deprecated, MP_DIGIT_BIT instead") MP_DIGIT_BIT)
+#define USED(m) (MP_DEPRECATED_PRAGMA("USED macro is deprecated, use z->used instead") (m)->used)
+#define DIGIT(m, k) (MP_DEPRECATED_PRAGMA("DIGIT macro is deprecated, use z->dp instead") (m)->dp[(k)])
+#define SIGN(m) (MP_DEPRECATED_PRAGMA("SIGN macro is deprecated, use z->sign instead") (m)->sign)
+
+/* the infamous mp_int structure */
+typedef struct {
+ int used, alloc;
+ mp_sign sign;
+ mp_digit *dp;
+} mp_int;
+
+/* callback for mp_prime_random, should fill dst with random bytes and return how many read [upto len] */
+typedef int private_mp_prime_callback(unsigned char *dst, int len, void *dat);
+typedef private_mp_prime_callback MP_DEPRECATED(mp_rand_source) ltm_prime_callback;
+
+/* error code to char* string */
+const char *mp_error_to_string(mp_err code) MP_WUR;
+
+/* ---> init and deinit bignum functions <--- */
+/* init a bignum */
+mp_err mp_init(mp_int *a) MP_WUR;
+
+/* free a bignum */
+void mp_clear(mp_int *a);
+
+/* init a null terminated series of arguments */
+mp_err mp_init_multi(mp_int *mp, ...) MP_NULL_TERMINATED MP_WUR;
+
+/* clear a null terminated series of arguments */
+void mp_clear_multi(mp_int *mp, ...) MP_NULL_TERMINATED;
+
+/* exchange two ints */
+void mp_exch(mp_int *a, mp_int *b);
+
+/* shrink ram required for a bignum */
+mp_err mp_shrink(mp_int *a) MP_WUR;
+
+/* grow an int to a given size */
+mp_err mp_grow(mp_int *a, int size) MP_WUR;
+
+/* init to a given number of digits */
+mp_err mp_init_size(mp_int *a, int size) MP_WUR;
+
+/* ---> Basic Manipulations <--- */
+#define mp_iszero(a) (((a)->used == 0) ? MP_YES : MP_NO)
+mp_bool mp_iseven(const mp_int *a) MP_WUR;
+mp_bool mp_isodd(const mp_int *a) MP_WUR;
+#define mp_isneg(a) (((a)->sign != MP_ZPOS) ? MP_YES : MP_NO)
+
+/* set to zero */
+void mp_zero(mp_int *a);
+
+/* get and set doubles */
+double mp_get_double(const mp_int *a) MP_WUR;
+mp_err mp_set_double(mp_int *a, double b) MP_WUR;
+
+/* get integer, set integer and init with integer (int32_t) */
+int32_t mp_get_i32(const mp_int *a) MP_WUR;
+void mp_set_i32(mp_int *a, int32_t b);
+mp_err mp_init_i32(mp_int *a, int32_t b) MP_WUR;
+
+/* get integer, set integer and init with integer, behaves like two complement for negative numbers (uint32_t) */
+#define mp_get_u32(a) ((uint32_t)mp_get_i32(a))
+void mp_set_u32(mp_int *a, uint32_t b);
+mp_err mp_init_u32(mp_int *a, uint32_t b) MP_WUR;
+
+/* get integer, set integer and init with integer (int64_t) */
+int64_t mp_get_i64(const mp_int *a) MP_WUR;
+void mp_set_i64(mp_int *a, int64_t b);
+mp_err mp_init_i64(mp_int *a, int64_t b) MP_WUR;
+
+/* get integer, set integer and init with integer, behaves like two complement for negative numbers (uint64_t) */
+#define mp_get_u64(a) ((uint64_t)mp_get_i64(a))
+void mp_set_u64(mp_int *a, uint64_t b);
+mp_err mp_init_u64(mp_int *a, uint64_t b) MP_WUR;
+
+/* get magnitude */
+uint32_t mp_get_mag_u32(const mp_int *a) MP_WUR;
+uint64_t mp_get_mag_u64(const mp_int *a) MP_WUR;
+unsigned long mp_get_mag_ul(const mp_int *a) MP_WUR;
+unsigned long long mp_get_mag_ull(const mp_int *a) MP_WUR;
+
+/* get integer, set integer (long) */
+long mp_get_l(const mp_int *a) MP_WUR;
+void mp_set_l(mp_int *a, long b);
+mp_err mp_init_l(mp_int *a, long b) MP_WUR;
+
+/* get integer, set integer (unsigned long) */
+#define mp_get_ul(a) ((unsigned long)mp_get_l(a))
+void mp_set_ul(mp_int *a, unsigned long b);
+mp_err mp_init_ul(mp_int *a, unsigned long b) MP_WUR;
+
+/* get integer, set integer (long long) */
+long long mp_get_ll(const mp_int *a) MP_WUR;
+void mp_set_ll(mp_int *a, long long b);
+mp_err mp_init_ll(mp_int *a, long long b) MP_WUR;
+
+/* get integer, set integer (unsigned long long) */
+#define mp_get_ull(a) ((unsigned long long)mp_get_ll(a))
+void mp_set_ull(mp_int *a, unsigned long long b);
+mp_err mp_init_ull(mp_int *a, unsigned long long b) MP_WUR;
+
+/* set to single unsigned digit, up to MP_DIGIT_MAX */
+void mp_set(mp_int *a, mp_digit b);
+mp_err mp_init_set(mp_int *a, mp_digit b) MP_WUR;
+
+/* get integer, set integer and init with integer (deprecated) */
+MP_DEPRECATED(mp_get_mag_u32/mp_get_u32) unsigned long mp_get_int(const mp_int *a) MP_WUR;
+MP_DEPRECATED(mp_get_mag_ul/mp_get_ul) unsigned long mp_get_long(const mp_int *a) MP_WUR;
+MP_DEPRECATED(mp_get_mag_ull/mp_get_ull) unsigned long long mp_get_long_long(const mp_int *a) MP_WUR;
+MP_DEPRECATED(mp_set_ul) mp_err mp_set_int(mp_int *a, unsigned long b);
+MP_DEPRECATED(mp_set_ul) mp_err mp_set_long(mp_int *a, unsigned long b);
+MP_DEPRECATED(mp_set_ull) mp_err mp_set_long_long(mp_int *a, unsigned long long b);
+MP_DEPRECATED(mp_init_ul) mp_err mp_init_set_int(mp_int *a, unsigned long b) MP_WUR;
+
+/* copy, b = a */
+mp_err mp_copy(const mp_int *a, mp_int *b) MP_WUR;
+
+/* inits and copies, a = b */
+mp_err mp_init_copy(mp_int *a, const mp_int *b) MP_WUR;
+
+/* trim unused digits */
+void mp_clamp(mp_int *a);
+
+
+/* export binary data */
+MP_DEPRECATED(mp_pack) mp_err mp_export(void *rop, size_t *countp, int order, size_t size,
+ int endian, size_t nails, const mp_int *op) MP_WUR;
+
+/* import binary data */
+MP_DEPRECATED(mp_unpack) mp_err mp_import(mp_int *rop, size_t count, int order,
+ size_t size, int endian, size_t nails,
+ const void *op) MP_WUR;
+
+/* unpack binary data */
+mp_err mp_unpack(mp_int *rop, size_t count, mp_order order, size_t size, mp_endian endian,
+ size_t nails, const void *op) MP_WUR;
+
+/* pack binary data */
+size_t mp_pack_count(const mp_int *a, size_t nails, size_t size) MP_WUR;
+mp_err mp_pack(void *rop, size_t maxcount, size_t *written, mp_order order, size_t size,
+ mp_endian endian, size_t nails, const mp_int *op) MP_WUR;
+
+/* ---> digit manipulation <--- */
+
+/* right shift by "b" digits */
+void mp_rshd(mp_int *a, int b);
+
+/* left shift by "b" digits */
+mp_err mp_lshd(mp_int *a, int b) MP_WUR;
+
+/* c = a / 2**b, implemented as c = a >> b */
+mp_err mp_div_2d(const mp_int *a, int b, mp_int *c, mp_int *d) MP_WUR;
+
+/* b = a/2 */
+mp_err mp_div_2(const mp_int *a, mp_int *b) MP_WUR;
+
+/* a/3 => 3c + d == a */
+mp_err mp_div_3(const mp_int *a, mp_int *c, mp_digit *d) MP_WUR;
+
+/* c = a * 2**b, implemented as c = a << b */
+mp_err mp_mul_2d(const mp_int *a, int b, mp_int *c) MP_WUR;
+
+/* b = a*2 */
+mp_err mp_mul_2(const mp_int *a, mp_int *b) MP_WUR;
+
+/* c = a mod 2**b */
+mp_err mp_mod_2d(const mp_int *a, int b, mp_int *c) MP_WUR;
+
+/* computes a = 2**b */
+mp_err mp_2expt(mp_int *a, int b) MP_WUR;
+
+/* Counts the number of lsbs which are zero before the first zero bit */
+int mp_cnt_lsb(const mp_int *a) MP_WUR;
+
+/* I Love Earth! */
+
+/* makes a pseudo-random mp_int of a given size */
+mp_err mp_rand(mp_int *a, int digits) MP_WUR;
+/* makes a pseudo-random small int of a given size */
+MP_DEPRECATED(mp_rand) mp_err mp_rand_digit(mp_digit *r) MP_WUR;
+/* use custom random data source instead of source provided the platform */
+void mp_rand_source(mp_err(*source)(void *out, size_t size));
+
+#ifdef MP_PRNG_ENABLE_LTM_RNG
+# warning MP_PRNG_ENABLE_LTM_RNG has been deprecated, use mp_rand_source instead.
+/* A last resort to provide random data on systems without any of the other
+ * implemented ways to gather entropy.
+ * It is compatible with `rng_get_bytes()` from libtomcrypt so you could
+ * provide that one and then set `ltm_rng = rng_get_bytes;` */
+extern unsigned long (*ltm_rng)(unsigned char *out, unsigned long outlen, void (*callback)(void));
+extern void (*ltm_rng_callback)(void);
+#endif
+
+/* ---> binary operations <--- */
+
+/* Checks the bit at position b and returns MP_YES
+ * if the bit is 1, MP_NO if it is 0 and MP_VAL
+ * in case of error
+ */
+MP_DEPRECATED(s_mp_get_bit) int mp_get_bit(const mp_int *a, int b) MP_WUR;
+
+/* c = a XOR b (two complement) */
+MP_DEPRECATED(mp_xor) mp_err mp_tc_xor(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+mp_err mp_xor(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+
+/* c = a OR b (two complement) */
+MP_DEPRECATED(mp_or) mp_err mp_tc_or(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+mp_err mp_or(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+
+/* c = a AND b (two complement) */
+MP_DEPRECATED(mp_and) mp_err mp_tc_and(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+mp_err mp_and(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+
+/* b = ~a (bitwise not, two complement) */
+mp_err mp_complement(const mp_int *a, mp_int *b) MP_WUR;
+
+/* right shift with sign extension */
+MP_DEPRECATED(mp_signed_rsh) mp_err mp_tc_div_2d(const mp_int *a, int b, mp_int *c) MP_WUR;
+mp_err mp_signed_rsh(const mp_int *a, int b, mp_int *c) MP_WUR;
+
+/* ---> Basic arithmetic <--- */
+
+/* b = -a */
+mp_err mp_neg(const mp_int *a, mp_int *b) MP_WUR;
+
+/* b = |a| */
+mp_err mp_abs(const mp_int *a, mp_int *b) MP_WUR;
+
+/* compare a to b */
+mp_ord mp_cmp(const mp_int *a, const mp_int *b) MP_WUR;
+
+/* compare |a| to |b| */
+mp_ord mp_cmp_mag(const mp_int *a, const mp_int *b) MP_WUR;
+
+/* c = a + b */
+mp_err mp_add(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+
+/* c = a - b */
+mp_err mp_sub(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+
+/* c = a * b */
+mp_err mp_mul(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+
+/* b = a*a */
+mp_err mp_sqr(const mp_int *a, mp_int *b) MP_WUR;
+
+/* a/b => cb + d == a */
+mp_err mp_div(const mp_int *a, const mp_int *b, mp_int *c, mp_int *d) MP_WUR;
+
+/* c = a mod b, 0 <= c < b */
+mp_err mp_mod(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+
+/* Increment "a" by one like "a++". Changes input! */
+mp_err mp_incr(mp_int *a) MP_WUR;
+
+/* Decrement "a" by one like "a--". Changes input! */
+mp_err mp_decr(mp_int *a) MP_WUR;
+
+/* ---> single digit functions <--- */
+
+/* compare against a single digit */
+mp_ord mp_cmp_d(const mp_int *a, mp_digit b) MP_WUR;
+
+/* c = a + b */
+mp_err mp_add_d(const mp_int *a, mp_digit b, mp_int *c) MP_WUR;
+
+/* c = a - b */
+mp_err mp_sub_d(const mp_int *a, mp_digit b, mp_int *c) MP_WUR;
+
+/* c = a * b */
+mp_err mp_mul_d(const mp_int *a, mp_digit b, mp_int *c) MP_WUR;
+
+/* a/b => cb + d == a */
+mp_err mp_div_d(const mp_int *a, mp_digit b, mp_int *c, mp_digit *d) MP_WUR;
+
+/* c = a mod b, 0 <= c < b */
+mp_err mp_mod_d(const mp_int *a, mp_digit b, mp_digit *c) MP_WUR;
+
+/* ---> number theory <--- */
+
+/* d = a + b (mod c) */
+mp_err mp_addmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d) MP_WUR;
+
+/* d = a - b (mod c) */
+mp_err mp_submod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d) MP_WUR;
+
+/* d = a * b (mod c) */
+mp_err mp_mulmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d) MP_WUR;
+
+/* c = a * a (mod b) */
+mp_err mp_sqrmod(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+
+/* c = 1/a (mod b) */
+mp_err mp_invmod(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+
+/* c = (a, b) */
+mp_err mp_gcd(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+
+/* produces value such that U1*a + U2*b = U3 */
+mp_err mp_exteuclid(const mp_int *a, const mp_int *b, mp_int *U1, mp_int *U2, mp_int *U3) MP_WUR;
+
+/* c = [a, b] or (a*b)/(a, b) */
+mp_err mp_lcm(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+
+/* finds one of the b'th root of a, such that |c|**b <= |a|
+ *
+ * returns error if a < 0 and b is even
+ */
+mp_err mp_root_u32(const mp_int *a, uint32_t b, mp_int *c) MP_WUR;
+MP_DEPRECATED(mp_root_u32) mp_err mp_n_root(const mp_int *a, mp_digit b, mp_int *c) MP_WUR;
+MP_DEPRECATED(mp_root_u32) mp_err mp_n_root_ex(const mp_int *a, mp_digit b, mp_int *c, int fast) MP_WUR;
+
+/* special sqrt algo */
+mp_err mp_sqrt(const mp_int *arg, mp_int *ret) MP_WUR;
+
+/* special sqrt (mod prime) */
+mp_err mp_sqrtmod_prime(const mp_int *n, const mp_int *prime, mp_int *ret) MP_WUR;
+
+/* is number a square? */
+mp_err mp_is_square(const mp_int *arg, mp_bool *ret) MP_WUR;
+
+/* computes the jacobi c = (a | n) (or Legendre if b is prime) */
+MP_DEPRECATED(mp_kronecker) mp_err mp_jacobi(const mp_int *a, const mp_int *n, int *c) MP_WUR;
+
+/* computes the Kronecker symbol c = (a | p) (like jacobi() but with {a,p} in Z */
+mp_err mp_kronecker(const mp_int *a, const mp_int *p, int *c) MP_WUR;
+
+/* used to setup the Barrett reduction for a given modulus b */
+mp_err mp_reduce_setup(mp_int *a, const mp_int *b) MP_WUR;
+
+/* Barrett Reduction, computes a (mod b) with a precomputed value c
+ *
+ * Assumes that 0 < x <= m*m, note if 0 > x > -(m*m) then you can merely
+ * compute the reduction as -1 * mp_reduce(mp_abs(x)) [pseudo code].
+ */
+mp_err mp_reduce(mp_int *x, const mp_int *m, const mp_int *mu) MP_WUR;
+
+/* setups the montgomery reduction */
+mp_err mp_montgomery_setup(const mp_int *n, mp_digit *rho) MP_WUR;
+
+/* computes a = B**n mod b without division or multiplication useful for
+ * normalizing numbers in a Montgomery system.
+ */
+mp_err mp_montgomery_calc_normalization(mp_int *a, const mp_int *b) MP_WUR;
+
+/* computes x/R == x (mod N) via Montgomery Reduction */
+mp_err mp_montgomery_reduce(mp_int *x, const mp_int *n, mp_digit rho) MP_WUR;
+
+/* returns 1 if a is a valid DR modulus */
+mp_bool mp_dr_is_modulus(const mp_int *a) MP_WUR;
+
+/* sets the value of "d" required for mp_dr_reduce */
+void mp_dr_setup(const mp_int *a, mp_digit *d);
+
+/* reduces a modulo n using the Diminished Radix method */
+mp_err mp_dr_reduce(mp_int *x, const mp_int *n, mp_digit k) MP_WUR;
+
+/* returns true if a can be reduced with mp_reduce_2k */
+mp_bool mp_reduce_is_2k(const mp_int *a) MP_WUR;
+
+/* determines k value for 2k reduction */
+mp_err mp_reduce_2k_setup(const mp_int *a, mp_digit *d) MP_WUR;
+
+/* reduces a modulo b where b is of the form 2**p - k [0 <= a] */
+mp_err mp_reduce_2k(mp_int *a, const mp_int *n, mp_digit d) MP_WUR;
+
+/* returns true if a can be reduced with mp_reduce_2k_l */
+mp_bool mp_reduce_is_2k_l(const mp_int *a) MP_WUR;
+
+/* determines k value for 2k reduction */
+mp_err mp_reduce_2k_setup_l(const mp_int *a, mp_int *d) MP_WUR;
+
+/* reduces a modulo b where b is of the form 2**p - k [0 <= a] */
+mp_err mp_reduce_2k_l(mp_int *a, const mp_int *n, const mp_int *d) MP_WUR;
+
+/* Y = G**X (mod P) */
+mp_err mp_exptmod(const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y) MP_WUR;
+
+/* ---> Primes <--- */
+
+/* number of primes */
+#ifdef MP_8BIT
+# define PRIVATE_MP_PRIME_TAB_SIZE 31
+#else
+# define PRIVATE_MP_PRIME_TAB_SIZE 256
+#endif
+#define PRIME_SIZE (MP_DEPRECATED_PRAGMA("PRIME_SIZE has been made internal") PRIVATE_MP_PRIME_TAB_SIZE)
+
+/* table of first PRIME_SIZE primes */
+MP_DEPRECATED(internal) extern const mp_digit ltm_prime_tab[PRIVATE_MP_PRIME_TAB_SIZE];
+
+/* result=1 if a is divisible by one of the first PRIME_SIZE primes */
+MP_DEPRECATED(mp_prime_is_prime) mp_err mp_prime_is_divisible(const mp_int *a, mp_bool *result) MP_WUR;
+
+/* performs one Fermat test of "a" using base "b".
+ * Sets result to 0 if composite or 1 if probable prime
+ */
+mp_err mp_prime_fermat(const mp_int *a, const mp_int *b, mp_bool *result) MP_WUR;
+
+/* performs one Miller-Rabin test of "a" using base "b".
+ * Sets result to 0 if composite or 1 if probable prime
+ */
+mp_err mp_prime_miller_rabin(const mp_int *a, const mp_int *b, mp_bool *result) MP_WUR;
+
+/* This gives [for a given bit size] the number of trials required
+ * such that Miller-Rabin gives a prob of failure lower than 2^-96
+ */
+int mp_prime_rabin_miller_trials(int size) MP_WUR;
+
+/* performs one strong Lucas-Selfridge test of "a".
+ * Sets result to 0 if composite or 1 if probable prime
+ */
+mp_err mp_prime_strong_lucas_selfridge(const mp_int *a, mp_bool *result) MP_WUR;
+
+/* performs one Frobenius test of "a" as described by Paul Underwood.
+ * Sets result to 0 if composite or 1 if probable prime
+ */
+mp_err mp_prime_frobenius_underwood(const mp_int *N, mp_bool *result) MP_WUR;
+
+/* performs t random rounds of Miller-Rabin on "a" additional to
+ * bases 2 and 3. Also performs an initial sieve of trial
+ * division. Determines if "a" is prime with probability
+ * of error no more than (1/4)**t.
+ * Both a strong Lucas-Selfridge to complete the BPSW test
+ * and a separate Frobenius test are available at compile time.
+ * With t<0 a deterministic test is run for primes up to
+ * 318665857834031151167461. With t<13 (abs(t)-13) additional
+ * tests with sequential small primes are run starting at 43.
+ * Is Fips 186.4 compliant if called with t as computed by
+ * mp_prime_rabin_miller_trials();
+ *
+ * Sets result to 1 if probably prime, 0 otherwise
+ */
+mp_err mp_prime_is_prime(const mp_int *a, int t, mp_bool *result) MP_WUR;
+
+/* finds the next prime after the number "a" using "t" trials
+ * of Miller-Rabin.
+ *
+ * bbs_style = 1 means the prime must be congruent to 3 mod 4
+ */
+mp_err mp_prime_next_prime(mp_int *a, int t, int bbs_style) MP_WUR;
+
+/* makes a truly random prime of a given size (bytes),
+ * call with bbs = 1 if you want it to be congruent to 3 mod 4
+ *
+ * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can
+ * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself
+ * so it can be NULL
+ *
+ * The prime generated will be larger than 2^(8*size).
+ */
+#define mp_prime_random(a, t, size, bbs, cb, dat) (MP_DEPRECATED_PRAGMA("mp_prime_random has been deprecated, use mp_prime_rand instead") mp_prime_random_ex(a, t, ((size) * 8) + 1, (bbs==1)?MP_PRIME_BBS:0, cb, dat))
+
+/* makes a truly random prime of a given size (bits),
+ *
+ * Flags are as follows:
+ *
+ * MP_PRIME_BBS - make prime congruent to 3 mod 4
+ * MP_PRIME_SAFE - make sure (p-1)/2 is prime as well (implies MP_PRIME_BBS)
+ * MP_PRIME_2MSB_ON - make the 2nd highest bit one
+ *
+ * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can
+ * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself
+ * so it can be NULL
+ *
+ */
+MP_DEPRECATED(mp_prime_rand) mp_err mp_prime_random_ex(mp_int *a, int t, int size, int flags,
+ private_mp_prime_callback cb, void *dat) MP_WUR;
+mp_err mp_prime_rand(mp_int *a, int t, int size, int flags) MP_WUR;
+
+/* Integer logarithm to integer base */
+mp_err mp_log_u32(const mp_int *a, uint32_t base, uint32_t *c) MP_WUR;
+
+/* c = a**b */
+mp_err mp_expt_u32(const mp_int *a, uint32_t b, mp_int *c) MP_WUR;
+MP_DEPRECATED(mp_expt_u32) mp_err mp_expt_d(const mp_int *a, mp_digit b, mp_int *c) MP_WUR;
+MP_DEPRECATED(mp_expt_u32) mp_err mp_expt_d_ex(const mp_int *a, mp_digit b, mp_int *c, int fast) MP_WUR;
+
+/* ---> radix conversion <--- */
+int mp_count_bits(const mp_int *a) MP_WUR;
+
+
+MP_DEPRECATED(mp_ubin_size) int mp_unsigned_bin_size(const mp_int *a) MP_WUR;
+MP_DEPRECATED(mp_from_ubin) mp_err mp_read_unsigned_bin(mp_int *a, const unsigned char *b, int c) MP_WUR;
+MP_DEPRECATED(mp_to_ubin) mp_err mp_to_unsigned_bin(const mp_int *a, unsigned char *b) MP_WUR;
+MP_DEPRECATED(mp_to_ubin) mp_err mp_to_unsigned_bin_n(const mp_int *a, unsigned char *b, unsigned long *outlen) MP_WUR;
+
+MP_DEPRECATED(mp_sbin_size) int mp_signed_bin_size(const mp_int *a) MP_WUR;
+MP_DEPRECATED(mp_from_sbin) mp_err mp_read_signed_bin(mp_int *a, const unsigned char *b, int c) MP_WUR;
+MP_DEPRECATED(mp_to_sbin) mp_err mp_to_signed_bin(const mp_int *a, unsigned char *b) MP_WUR;
+MP_DEPRECATED(mp_to_sbin) mp_err mp_to_signed_bin_n(const mp_int *a, unsigned char *b, unsigned long *outlen) MP_WUR;
+
+size_t mp_ubin_size(const mp_int *a) MP_WUR;
+mp_err mp_from_ubin(mp_int *a, const unsigned char *buf, size_t size) MP_WUR;
+mp_err mp_to_ubin(const mp_int *a, unsigned char *buf, size_t maxlen, size_t *written) MP_WUR;
+
+size_t mp_sbin_size(const mp_int *a) MP_WUR;
+mp_err mp_from_sbin(mp_int *a, const unsigned char *buf, size_t size) MP_WUR;
+mp_err mp_to_sbin(const mp_int *a, unsigned char *buf, size_t maxlen, size_t *written) MP_WUR;
+
+mp_err mp_read_radix(mp_int *a, const char *str, int radix) MP_WUR;
+MP_DEPRECATED(mp_to_radix) mp_err mp_toradix(const mp_int *a, char *str, int radix) MP_WUR;
+MP_DEPRECATED(mp_to_radix) mp_err mp_toradix_n(const mp_int *a, char *str, int radix, int maxlen) MP_WUR;
+mp_err mp_to_radix(const mp_int *a, char *str, size_t maxlen, size_t *written, int radix) MP_WUR;
+mp_err mp_radix_size(const mp_int *a, int radix, int *size) MP_WUR;
+
+#ifndef MP_NO_FILE
+mp_err mp_fread(mp_int *a, int radix, FILE *stream) MP_WUR;
+mp_err mp_fwrite(const mp_int *a, int radix, FILE *stream) MP_WUR;
+#endif
+
+#define mp_read_raw(mp, str, len) (MP_DEPRECATED_PRAGMA("replaced by mp_read_signed_bin") mp_read_signed_bin((mp), (str), (len)))
+#define mp_raw_size(mp) (MP_DEPRECATED_PRAGMA("replaced by mp_signed_bin_size") mp_signed_bin_size(mp))
+#define mp_toraw(mp, str) (MP_DEPRECATED_PRAGMA("replaced by mp_to_signed_bin") mp_to_signed_bin((mp), (str)))
+#define mp_read_mag(mp, str, len) (MP_DEPRECATED_PRAGMA("replaced by mp_read_unsigned_bin") mp_read_unsigned_bin((mp), (str), (len))
+#define mp_mag_size(mp) (MP_DEPRECATED_PRAGMA("replaced by mp_unsigned_bin_size") mp_unsigned_bin_size(mp))
+#define mp_tomag(mp, str) (MP_DEPRECATED_PRAGMA("replaced by mp_to_unsigned_bin") mp_to_unsigned_bin((mp), (str)))
+
+#define mp_tobinary(M, S) (MP_DEPRECATED_PRAGMA("replaced by mp_to_binary") mp_toradix((M), (S), 2))
+#define mp_tooctal(M, S) (MP_DEPRECATED_PRAGMA("replaced by mp_to_octal") mp_toradix((M), (S), 8))
+#define mp_todecimal(M, S) (MP_DEPRECATED_PRAGMA("replaced by mp_to_decimal") mp_toradix((M), (S), 10))
+#define mp_tohex(M, S) (MP_DEPRECATED_PRAGMA("replaced by mp_to_hex") mp_toradix((M), (S), 16))
+
+#define mp_to_binary(M, S, N) mp_to_radix((M), (S), (N), NULL, 2)
+#define mp_to_octal(M, S, N) mp_to_radix((M), (S), (N), NULL, 8)
+#define mp_to_decimal(M, S, N) mp_to_radix((M), (S), (N), NULL, 10)
+#define mp_to_hex(M, S, N) mp_to_radix((M), (S), (N), NULL, 16)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/tommath_class.h b/third_party/heimdal/lib/hcrypto/libtommath/tommath_class.h
new file mode 100644
index 0000000..52ba585
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/tommath_class.h
@@ -0,0 +1,1319 @@
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#if !(defined(LTM1) && defined(LTM2) && defined(LTM3))
+#define LTM_INSIDE
+#if defined(LTM2)
+# define LTM3
+#endif
+#if defined(LTM1)
+# define LTM2
+#endif
+#define LTM1
+#if defined(LTM_ALL)
+# define BN_CUTOFFS_C
+# define BN_DEPRECATED_C
+# define BN_MP_2EXPT_C
+# define BN_MP_ABS_C
+# define BN_MP_ADD_C
+# define BN_MP_ADD_D_C
+# define BN_MP_ADDMOD_C
+# define BN_MP_AND_C
+# define BN_MP_CLAMP_C
+# define BN_MP_CLEAR_C
+# define BN_MP_CLEAR_MULTI_C
+# define BN_MP_CMP_C
+# define BN_MP_CMP_D_C
+# define BN_MP_CMP_MAG_C
+# define BN_MP_CNT_LSB_C
+# define BN_MP_COMPLEMENT_C
+# define BN_MP_COPY_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_DECR_C
+# define BN_MP_DIV_C
+# define BN_MP_DIV_2_C
+# define BN_MP_DIV_2D_C
+# define BN_MP_DIV_3_C
+# define BN_MP_DIV_D_C
+# define BN_MP_DR_IS_MODULUS_C
+# define BN_MP_DR_REDUCE_C
+# define BN_MP_DR_SETUP_C
+# define BN_MP_ERROR_TO_STRING_C
+# define BN_MP_EXCH_C
+# define BN_MP_EXPT_U32_C
+# define BN_MP_EXPTMOD_C
+# define BN_MP_EXTEUCLID_C
+# define BN_MP_FREAD_C
+# define BN_MP_FROM_SBIN_C
+# define BN_MP_FROM_UBIN_C
+# define BN_MP_FWRITE_C
+# define BN_MP_GCD_C
+# define BN_MP_GET_DOUBLE_C
+# define BN_MP_GET_I32_C
+# define BN_MP_GET_I64_C
+# define BN_MP_GET_L_C
+# define BN_MP_GET_LL_C
+# define BN_MP_GET_MAG_U32_C
+# define BN_MP_GET_MAG_U64_C
+# define BN_MP_GET_MAG_UL_C
+# define BN_MP_GET_MAG_ULL_C
+# define BN_MP_GROW_C
+# define BN_MP_INCR_C
+# define BN_MP_INIT_C
+# define BN_MP_INIT_COPY_C
+# define BN_MP_INIT_I32_C
+# define BN_MP_INIT_I64_C
+# define BN_MP_INIT_L_C
+# define BN_MP_INIT_LL_C
+# define BN_MP_INIT_MULTI_C
+# define BN_MP_INIT_SET_C
+# define BN_MP_INIT_SIZE_C
+# define BN_MP_INIT_U32_C
+# define BN_MP_INIT_U64_C
+# define BN_MP_INIT_UL_C
+# define BN_MP_INIT_ULL_C
+# define BN_MP_INVMOD_C
+# define BN_MP_IS_SQUARE_C
+# define BN_MP_ISEVEN_C
+# define BN_MP_ISODD_C
+# define BN_MP_KRONECKER_C
+# define BN_MP_LCM_C
+# define BN_MP_LOG_U32_C
+# define BN_MP_LSHD_C
+# define BN_MP_MOD_C
+# define BN_MP_MOD_2D_C
+# define BN_MP_MOD_D_C
+# define BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
+# define BN_MP_MONTGOMERY_REDUCE_C
+# define BN_MP_MONTGOMERY_SETUP_C
+# define BN_MP_MUL_C
+# define BN_MP_MUL_2_C
+# define BN_MP_MUL_2D_C
+# define BN_MP_MUL_D_C
+# define BN_MP_MULMOD_C
+# define BN_MP_NEG_C
+# define BN_MP_OR_C
+# define BN_MP_PACK_C
+# define BN_MP_PACK_COUNT_C
+# define BN_MP_PRIME_FERMAT_C
+# define BN_MP_PRIME_FROBENIUS_UNDERWOOD_C
+# define BN_MP_PRIME_IS_PRIME_C
+# define BN_MP_PRIME_MILLER_RABIN_C
+# define BN_MP_PRIME_NEXT_PRIME_C
+# define BN_MP_PRIME_RABIN_MILLER_TRIALS_C
+# define BN_MP_PRIME_RAND_C
+# define BN_MP_PRIME_STRONG_LUCAS_SELFRIDGE_C
+# define BN_MP_RADIX_SIZE_C
+# define BN_MP_RADIX_SMAP_C
+# define BN_MP_RAND_C
+# define BN_MP_READ_RADIX_C
+# define BN_MP_REDUCE_C
+# define BN_MP_REDUCE_2K_C
+# define BN_MP_REDUCE_2K_L_C
+# define BN_MP_REDUCE_2K_SETUP_C
+# define BN_MP_REDUCE_2K_SETUP_L_C
+# define BN_MP_REDUCE_IS_2K_C
+# define BN_MP_REDUCE_IS_2K_L_C
+# define BN_MP_REDUCE_SETUP_C
+# define BN_MP_ROOT_U32_C
+# define BN_MP_RSHD_C
+# define BN_MP_SBIN_SIZE_C
+# define BN_MP_SET_C
+# define BN_MP_SET_DOUBLE_C
+# define BN_MP_SET_I32_C
+# define BN_MP_SET_I64_C
+# define BN_MP_SET_L_C
+# define BN_MP_SET_LL_C
+# define BN_MP_SET_U32_C
+# define BN_MP_SET_U64_C
+# define BN_MP_SET_UL_C
+# define BN_MP_SET_ULL_C
+# define BN_MP_SHRINK_C
+# define BN_MP_SIGNED_RSH_C
+# define BN_MP_SQR_C
+# define BN_MP_SQRMOD_C
+# define BN_MP_SQRT_C
+# define BN_MP_SQRTMOD_PRIME_C
+# define BN_MP_SUB_C
+# define BN_MP_SUB_D_C
+# define BN_MP_SUBMOD_C
+# define BN_MP_TO_RADIX_C
+# define BN_MP_TO_SBIN_C
+# define BN_MP_TO_UBIN_C
+# define BN_MP_UBIN_SIZE_C
+# define BN_MP_UNPACK_C
+# define BN_MP_XOR_C
+# define BN_MP_ZERO_C
+# define BN_PRIME_TAB_C
+# define BN_S_MP_ADD_C
+# define BN_S_MP_BALANCE_MUL_C
+# define BN_S_MP_EXPTMOD_C
+# define BN_S_MP_EXPTMOD_FAST_C
+# define BN_S_MP_GET_BIT_C
+# define BN_S_MP_INVMOD_FAST_C
+# define BN_S_MP_INVMOD_SLOW_C
+# define BN_S_MP_KARATSUBA_MUL_C
+# define BN_S_MP_KARATSUBA_SQR_C
+# define BN_S_MP_MONTGOMERY_REDUCE_FAST_C
+# define BN_S_MP_MUL_DIGS_C
+# define BN_S_MP_MUL_DIGS_FAST_C
+# define BN_S_MP_MUL_HIGH_DIGS_C
+# define BN_S_MP_MUL_HIGH_DIGS_FAST_C
+# define BN_S_MP_PRIME_IS_DIVISIBLE_C
+# define BN_S_MP_RAND_JENKINS_C
+# define BN_S_MP_RAND_PLATFORM_C
+# define BN_S_MP_REVERSE_C
+# define BN_S_MP_SQR_C
+# define BN_S_MP_SQR_FAST_C
+# define BN_S_MP_SUB_C
+# define BN_S_MP_TOOM_MUL_C
+# define BN_S_MP_TOOM_SQR_C
+#endif
+#endif
+#if defined(BN_CUTOFFS_C)
+#endif
+
+#if defined(BN_DEPRECATED_C)
+# define BN_FAST_MP_INVMOD_C
+# define BN_FAST_MP_MONTGOMERY_REDUCE_C
+# define BN_FAST_S_MP_MUL_DIGS_C
+# define BN_FAST_S_MP_MUL_HIGH_DIGS_C
+# define BN_FAST_S_MP_SQR_C
+# define BN_MP_AND_C
+# define BN_MP_BALANCE_MUL_C
+# define BN_MP_CMP_D_C
+# define BN_MP_EXPORT_C
+# define BN_MP_EXPTMOD_FAST_C
+# define BN_MP_EXPT_D_C
+# define BN_MP_EXPT_D_EX_C
+# define BN_MP_EXPT_U32_C
+# define BN_MP_FROM_SBIN_C
+# define BN_MP_FROM_UBIN_C
+# define BN_MP_GET_BIT_C
+# define BN_MP_GET_INT_C
+# define BN_MP_GET_LONG_C
+# define BN_MP_GET_LONG_LONG_C
+# define BN_MP_GET_MAG_U32_C
+# define BN_MP_GET_MAG_ULL_C
+# define BN_MP_GET_MAG_UL_C
+# define BN_MP_IMPORT_C
+# define BN_MP_INIT_SET_INT_C
+# define BN_MP_INIT_U32_C
+# define BN_MP_INVMOD_SLOW_C
+# define BN_MP_JACOBI_C
+# define BN_MP_KARATSUBA_MUL_C
+# define BN_MP_KARATSUBA_SQR_C
+# define BN_MP_KRONECKER_C
+# define BN_MP_N_ROOT_C
+# define BN_MP_N_ROOT_EX_C
+# define BN_MP_OR_C
+# define BN_MP_PACK_C
+# define BN_MP_PRIME_IS_DIVISIBLE_C
+# define BN_MP_PRIME_RANDOM_EX_C
+# define BN_MP_RAND_DIGIT_C
+# define BN_MP_READ_SIGNED_BIN_C
+# define BN_MP_READ_UNSIGNED_BIN_C
+# define BN_MP_ROOT_U32_C
+# define BN_MP_SBIN_SIZE_C
+# define BN_MP_SET_INT_C
+# define BN_MP_SET_LONG_C
+# define BN_MP_SET_LONG_LONG_C
+# define BN_MP_SET_U32_C
+# define BN_MP_SET_U64_C
+# define BN_MP_SIGNED_BIN_SIZE_C
+# define BN_MP_SIGNED_RSH_C
+# define BN_MP_TC_AND_C
+# define BN_MP_TC_DIV_2D_C
+# define BN_MP_TC_OR_C
+# define BN_MP_TC_XOR_C
+# define BN_MP_TOOM_MUL_C
+# define BN_MP_TOOM_SQR_C
+# define BN_MP_TORADIX_C
+# define BN_MP_TORADIX_N_C
+# define BN_MP_TO_RADIX_C
+# define BN_MP_TO_SBIN_C
+# define BN_MP_TO_SIGNED_BIN_C
+# define BN_MP_TO_SIGNED_BIN_N_C
+# define BN_MP_TO_UBIN_C
+# define BN_MP_TO_UNSIGNED_BIN_C
+# define BN_MP_TO_UNSIGNED_BIN_N_C
+# define BN_MP_UBIN_SIZE_C
+# define BN_MP_UNPACK_C
+# define BN_MP_UNSIGNED_BIN_SIZE_C
+# define BN_MP_XOR_C
+# define BN_S_MP_BALANCE_MUL_C
+# define BN_S_MP_EXPTMOD_FAST_C
+# define BN_S_MP_GET_BIT_C
+# define BN_S_MP_INVMOD_FAST_C
+# define BN_S_MP_INVMOD_SLOW_C
+# define BN_S_MP_KARATSUBA_MUL_C
+# define BN_S_MP_KARATSUBA_SQR_C
+# define BN_S_MP_MONTGOMERY_REDUCE_FAST_C
+# define BN_S_MP_MUL_DIGS_FAST_C
+# define BN_S_MP_MUL_HIGH_DIGS_FAST_C
+# define BN_S_MP_PRIME_IS_DIVISIBLE_C
+# define BN_S_MP_PRIME_RANDOM_EX_C
+# define BN_S_MP_RAND_SOURCE_C
+# define BN_S_MP_REVERSE_C
+# define BN_S_MP_SQR_FAST_C
+# define BN_S_MP_TOOM_MUL_C
+# define BN_S_MP_TOOM_SQR_C
+#endif
+
+#if defined(BN_MP_2EXPT_C)
+# define BN_MP_GROW_C
+# define BN_MP_ZERO_C
+#endif
+
+#if defined(BN_MP_ABS_C)
+# define BN_MP_COPY_C
+#endif
+
+#if defined(BN_MP_ADD_C)
+# define BN_MP_CMP_MAG_C
+# define BN_S_MP_ADD_C
+# define BN_S_MP_SUB_C
+#endif
+
+#if defined(BN_MP_ADD_D_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_GROW_C
+# define BN_MP_SUB_D_C
+#endif
+
+#if defined(BN_MP_ADDMOD_C)
+# define BN_MP_ADD_C
+# define BN_MP_CLEAR_C
+# define BN_MP_INIT_C
+# define BN_MP_MOD_C
+#endif
+
+#if defined(BN_MP_AND_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_GROW_C
+#endif
+
+#if defined(BN_MP_CLAMP_C)
+#endif
+
+#if defined(BN_MP_CLEAR_C)
+#endif
+
+#if defined(BN_MP_CLEAR_MULTI_C)
+# define BN_MP_CLEAR_C
+#endif
+
+#if defined(BN_MP_CMP_C)
+# define BN_MP_CMP_MAG_C
+#endif
+
+#if defined(BN_MP_CMP_D_C)
+#endif
+
+#if defined(BN_MP_CMP_MAG_C)
+#endif
+
+#if defined(BN_MP_CNT_LSB_C)
+#endif
+
+#if defined(BN_MP_COMPLEMENT_C)
+# define BN_MP_NEG_C
+# define BN_MP_SUB_D_C
+#endif
+
+#if defined(BN_MP_COPY_C)
+# define BN_MP_GROW_C
+#endif
+
+#if defined(BN_MP_COUNT_BITS_C)
+#endif
+
+#if defined(BN_MP_DECR_C)
+# define BN_MP_INCR_C
+# define BN_MP_SET_C
+# define BN_MP_SUB_D_C
+# define BN_MP_ZERO_C
+#endif
+
+#if defined(BN_MP_DIV_C)
+# define BN_MP_ADD_C
+# define BN_MP_CLAMP_C
+# define BN_MP_CLEAR_C
+# define BN_MP_CMP_C
+# define BN_MP_CMP_MAG_C
+# define BN_MP_COPY_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_DIV_2D_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_C
+# define BN_MP_INIT_COPY_C
+# define BN_MP_INIT_SIZE_C
+# define BN_MP_LSHD_C
+# define BN_MP_MUL_2D_C
+# define BN_MP_MUL_D_C
+# define BN_MP_RSHD_C
+# define BN_MP_SUB_C
+# define BN_MP_ZERO_C
+#endif
+
+#if defined(BN_MP_DIV_2_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_GROW_C
+#endif
+
+#if defined(BN_MP_DIV_2D_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_COPY_C
+# define BN_MP_MOD_2D_C
+# define BN_MP_RSHD_C
+# define BN_MP_ZERO_C
+#endif
+
+#if defined(BN_MP_DIV_3_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_CLEAR_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_SIZE_C
+#endif
+
+#if defined(BN_MP_DIV_D_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_CLEAR_C
+# define BN_MP_COPY_C
+# define BN_MP_DIV_2D_C
+# define BN_MP_DIV_3_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_SIZE_C
+#endif
+
+#if defined(BN_MP_DR_IS_MODULUS_C)
+#endif
+
+#if defined(BN_MP_DR_REDUCE_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_CMP_MAG_C
+# define BN_MP_GROW_C
+# define BN_S_MP_SUB_C
+#endif
+
+#if defined(BN_MP_DR_SETUP_C)
+#endif
+
+#if defined(BN_MP_ERROR_TO_STRING_C)
+#endif
+
+#if defined(BN_MP_EXCH_C)
+#endif
+
+#if defined(BN_MP_EXPT_U32_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_INIT_COPY_C
+# define BN_MP_MUL_C
+# define BN_MP_SET_C
+# define BN_MP_SQR_C
+#endif
+
+#if defined(BN_MP_EXPTMOD_C)
+# define BN_MP_ABS_C
+# define BN_MP_CLEAR_MULTI_C
+# define BN_MP_DR_IS_MODULUS_C
+# define BN_MP_INIT_MULTI_C
+# define BN_MP_INVMOD_C
+# define BN_MP_REDUCE_IS_2K_C
+# define BN_MP_REDUCE_IS_2K_L_C
+# define BN_S_MP_EXPTMOD_C
+# define BN_S_MP_EXPTMOD_FAST_C
+#endif
+
+#if defined(BN_MP_EXTEUCLID_C)
+# define BN_MP_CLEAR_MULTI_C
+# define BN_MP_COPY_C
+# define BN_MP_DIV_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_MULTI_C
+# define BN_MP_MUL_C
+# define BN_MP_NEG_C
+# define BN_MP_SET_C
+# define BN_MP_SUB_C
+#endif
+
+#if defined(BN_MP_FREAD_C)
+# define BN_MP_ADD_D_C
+# define BN_MP_MUL_D_C
+# define BN_MP_ZERO_C
+#endif
+
+#if defined(BN_MP_FROM_SBIN_C)
+# define BN_MP_FROM_UBIN_C
+#endif
+
+#if defined(BN_MP_FROM_UBIN_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_GROW_C
+# define BN_MP_MUL_2D_C
+# define BN_MP_ZERO_C
+#endif
+
+#if defined(BN_MP_FWRITE_C)
+# define BN_MP_RADIX_SIZE_C
+# define BN_MP_TO_RADIX_C
+#endif
+
+#if defined(BN_MP_GCD_C)
+# define BN_MP_ABS_C
+# define BN_MP_CLEAR_C
+# define BN_MP_CMP_MAG_C
+# define BN_MP_CNT_LSB_C
+# define BN_MP_DIV_2D_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_COPY_C
+# define BN_MP_MUL_2D_C
+# define BN_S_MP_SUB_C
+#endif
+
+#if defined(BN_MP_GET_DOUBLE_C)
+#endif
+
+#if defined(BN_MP_GET_I32_C)
+# define BN_MP_GET_MAG_U32_C
+#endif
+
+#if defined(BN_MP_GET_I64_C)
+# define BN_MP_GET_MAG_U64_C
+#endif
+
+#if defined(BN_MP_GET_L_C)
+# define BN_MP_GET_MAG_UL_C
+#endif
+
+#if defined(BN_MP_GET_LL_C)
+# define BN_MP_GET_MAG_ULL_C
+#endif
+
+#if defined(BN_MP_GET_MAG_U32_C)
+#endif
+
+#if defined(BN_MP_GET_MAG_U64_C)
+#endif
+
+#if defined(BN_MP_GET_MAG_UL_C)
+#endif
+
+#if defined(BN_MP_GET_MAG_ULL_C)
+#endif
+
+#if defined(BN_MP_GROW_C)
+#endif
+
+#if defined(BN_MP_INCR_C)
+# define BN_MP_ADD_D_C
+# define BN_MP_DECR_C
+# define BN_MP_SET_C
+#endif
+
+#if defined(BN_MP_INIT_C)
+#endif
+
+#if defined(BN_MP_INIT_COPY_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_COPY_C
+# define BN_MP_INIT_SIZE_C
+#endif
+
+#if defined(BN_MP_INIT_I32_C)
+# define BN_MP_INIT_C
+# define BN_MP_SET_I32_C
+#endif
+
+#if defined(BN_MP_INIT_I64_C)
+# define BN_MP_INIT_C
+# define BN_MP_SET_I64_C
+#endif
+
+#if defined(BN_MP_INIT_L_C)
+# define BN_MP_INIT_C
+# define BN_MP_SET_L_C
+#endif
+
+#if defined(BN_MP_INIT_LL_C)
+# define BN_MP_INIT_C
+# define BN_MP_SET_LL_C
+#endif
+
+#if defined(BN_MP_INIT_MULTI_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_INIT_C
+#endif
+
+#if defined(BN_MP_INIT_SET_C)
+# define BN_MP_INIT_C
+# define BN_MP_SET_C
+#endif
+
+#if defined(BN_MP_INIT_SIZE_C)
+#endif
+
+#if defined(BN_MP_INIT_U32_C)
+# define BN_MP_INIT_C
+# define BN_MP_SET_U32_C
+#endif
+
+#if defined(BN_MP_INIT_U64_C)
+# define BN_MP_INIT_C
+# define BN_MP_SET_U64_C
+#endif
+
+#if defined(BN_MP_INIT_UL_C)
+# define BN_MP_INIT_C
+# define BN_MP_SET_UL_C
+#endif
+
+#if defined(BN_MP_INIT_ULL_C)
+# define BN_MP_INIT_C
+# define BN_MP_SET_ULL_C
+#endif
+
+#if defined(BN_MP_INVMOD_C)
+# define BN_MP_CMP_D_C
+# define BN_S_MP_INVMOD_FAST_C
+# define BN_S_MP_INVMOD_SLOW_C
+#endif
+
+#if defined(BN_MP_IS_SQUARE_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_CMP_MAG_C
+# define BN_MP_GET_I32_C
+# define BN_MP_INIT_U32_C
+# define BN_MP_MOD_C
+# define BN_MP_MOD_D_C
+# define BN_MP_SQRT_C
+# define BN_MP_SQR_C
+#endif
+
+#if defined(BN_MP_ISEVEN_C)
+#endif
+
+#if defined(BN_MP_ISODD_C)
+#endif
+
+#if defined(BN_MP_KRONECKER_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_CMP_D_C
+# define BN_MP_CNT_LSB_C
+# define BN_MP_COPY_C
+# define BN_MP_DIV_2D_C
+# define BN_MP_INIT_C
+# define BN_MP_INIT_COPY_C
+# define BN_MP_MOD_C
+#endif
+
+#if defined(BN_MP_LCM_C)
+# define BN_MP_CLEAR_MULTI_C
+# define BN_MP_CMP_MAG_C
+# define BN_MP_DIV_C
+# define BN_MP_GCD_C
+# define BN_MP_INIT_MULTI_C
+# define BN_MP_MUL_C
+#endif
+
+#if defined(BN_MP_LOG_U32_C)
+# define BN_MP_CLEAR_MULTI_C
+# define BN_MP_CMP_C
+# define BN_MP_CMP_D_C
+# define BN_MP_COPY_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_EXCH_C
+# define BN_MP_EXPT_U32_C
+# define BN_MP_INIT_MULTI_C
+# define BN_MP_MUL_C
+# define BN_MP_SET_C
+# define BN_MP_SQR_C
+#endif
+
+#if defined(BN_MP_LSHD_C)
+# define BN_MP_GROW_C
+#endif
+
+#if defined(BN_MP_MOD_C)
+# define BN_MP_ADD_C
+# define BN_MP_CLEAR_C
+# define BN_MP_DIV_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_SIZE_C
+#endif
+
+#if defined(BN_MP_MOD_2D_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_COPY_C
+# define BN_MP_ZERO_C
+#endif
+
+#if defined(BN_MP_MOD_D_C)
+# define BN_MP_DIV_D_C
+#endif
+
+#if defined(BN_MP_MONTGOMERY_CALC_NORMALIZATION_C)
+# define BN_MP_2EXPT_C
+# define BN_MP_CMP_MAG_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_MUL_2_C
+# define BN_MP_SET_C
+# define BN_S_MP_SUB_C
+#endif
+
+#if defined(BN_MP_MONTGOMERY_REDUCE_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_CMP_MAG_C
+# define BN_MP_GROW_C
+# define BN_MP_RSHD_C
+# define BN_S_MP_MONTGOMERY_REDUCE_FAST_C
+# define BN_S_MP_SUB_C
+#endif
+
+#if defined(BN_MP_MONTGOMERY_SETUP_C)
+#endif
+
+#if defined(BN_MP_MUL_C)
+# define BN_S_MP_BALANCE_MUL_C
+# define BN_S_MP_KARATSUBA_MUL_C
+# define BN_S_MP_MUL_DIGS_C
+# define BN_S_MP_MUL_DIGS_FAST_C
+# define BN_S_MP_TOOM_MUL_C
+#endif
+
+#if defined(BN_MP_MUL_2_C)
+# define BN_MP_GROW_C
+#endif
+
+#if defined(BN_MP_MUL_2D_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_COPY_C
+# define BN_MP_GROW_C
+# define BN_MP_LSHD_C
+#endif
+
+#if defined(BN_MP_MUL_D_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_GROW_C
+#endif
+
+#if defined(BN_MP_MULMOD_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_INIT_SIZE_C
+# define BN_MP_MOD_C
+# define BN_MP_MUL_C
+#endif
+
+#if defined(BN_MP_NEG_C)
+# define BN_MP_COPY_C
+#endif
+
+#if defined(BN_MP_OR_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_GROW_C
+#endif
+
+#if defined(BN_MP_PACK_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_DIV_2D_C
+# define BN_MP_INIT_COPY_C
+# define BN_MP_PACK_COUNT_C
+#endif
+
+#if defined(BN_MP_PACK_COUNT_C)
+# define BN_MP_COUNT_BITS_C
+#endif
+
+#if defined(BN_MP_PRIME_FERMAT_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_CMP_C
+# define BN_MP_CMP_D_C
+# define BN_MP_EXPTMOD_C
+# define BN_MP_INIT_C
+#endif
+
+#if defined(BN_MP_PRIME_FROBENIUS_UNDERWOOD_C)
+# define BN_MP_ADD_C
+# define BN_MP_ADD_D_C
+# define BN_MP_CLEAR_MULTI_C
+# define BN_MP_CMP_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_EXCH_C
+# define BN_MP_GCD_C
+# define BN_MP_INIT_MULTI_C
+# define BN_MP_KRONECKER_C
+# define BN_MP_MOD_C
+# define BN_MP_MUL_2_C
+# define BN_MP_MUL_C
+# define BN_MP_MUL_D_C
+# define BN_MP_SET_C
+# define BN_MP_SET_U32_C
+# define BN_MP_SQR_C
+# define BN_MP_SUB_C
+# define BN_MP_SUB_D_C
+# define BN_S_MP_GET_BIT_C
+#endif
+
+#if defined(BN_MP_PRIME_IS_PRIME_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_CMP_C
+# define BN_MP_CMP_D_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_DIV_2D_C
+# define BN_MP_INIT_SET_C
+# define BN_MP_IS_SQUARE_C
+# define BN_MP_PRIME_MILLER_RABIN_C
+# define BN_MP_PRIME_STRONG_LUCAS_SELFRIDGE_C
+# define BN_MP_RAND_C
+# define BN_MP_READ_RADIX_C
+# define BN_MP_SET_C
+# define BN_S_MP_PRIME_IS_DIVISIBLE_C
+#endif
+
+#if defined(BN_MP_PRIME_MILLER_RABIN_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_CMP_C
+# define BN_MP_CMP_D_C
+# define BN_MP_CNT_LSB_C
+# define BN_MP_DIV_2D_C
+# define BN_MP_EXPTMOD_C
+# define BN_MP_INIT_C
+# define BN_MP_INIT_COPY_C
+# define BN_MP_SQRMOD_C
+# define BN_MP_SUB_D_C
+#endif
+
+#if defined(BN_MP_PRIME_NEXT_PRIME_C)
+# define BN_MP_ADD_D_C
+# define BN_MP_CLEAR_C
+# define BN_MP_CMP_D_C
+# define BN_MP_INIT_C
+# define BN_MP_MOD_D_C
+# define BN_MP_PRIME_IS_PRIME_C
+# define BN_MP_SET_C
+# define BN_MP_SUB_D_C
+#endif
+
+#if defined(BN_MP_PRIME_RABIN_MILLER_TRIALS_C)
+#endif
+
+#if defined(BN_MP_PRIME_RAND_C)
+# define BN_MP_ADD_D_C
+# define BN_MP_DIV_2_C
+# define BN_MP_FROM_UBIN_C
+# define BN_MP_MUL_2_C
+# define BN_MP_PRIME_IS_PRIME_C
+# define BN_MP_SUB_D_C
+# define BN_S_MP_PRIME_RANDOM_EX_C
+# define BN_S_MP_RAND_CB_C
+# define BN_S_MP_RAND_SOURCE_C
+#endif
+
+#if defined(BN_MP_PRIME_STRONG_LUCAS_SELFRIDGE_C)
+# define BN_MP_ADD_C
+# define BN_MP_ADD_D_C
+# define BN_MP_CLEAR_C
+# define BN_MP_CLEAR_MULTI_C
+# define BN_MP_CMP_C
+# define BN_MP_CMP_D_C
+# define BN_MP_CNT_LSB_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_DIV_2D_C
+# define BN_MP_DIV_2_C
+# define BN_MP_GCD_C
+# define BN_MP_INIT_C
+# define BN_MP_INIT_MULTI_C
+# define BN_MP_KRONECKER_C
+# define BN_MP_MOD_C
+# define BN_MP_MUL_2_C
+# define BN_MP_MUL_C
+# define BN_MP_SET_C
+# define BN_MP_SET_I32_C
+# define BN_MP_SET_U32_C
+# define BN_MP_SQR_C
+# define BN_MP_SUB_C
+# define BN_MP_SUB_D_C
+# define BN_S_MP_GET_BIT_C
+# define BN_S_MP_MUL_SI_C
+#endif
+
+#if defined(BN_MP_RADIX_SIZE_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_DIV_D_C
+# define BN_MP_INIT_COPY_C
+#endif
+
+#if defined(BN_MP_RADIX_SMAP_C)
+#endif
+
+#if defined(BN_MP_RAND_C)
+# define BN_MP_GROW_C
+# define BN_MP_RAND_SOURCE_C
+# define BN_MP_ZERO_C
+# define BN_S_MP_RAND_PLATFORM_C
+# define BN_S_MP_RAND_SOURCE_C
+#endif
+
+#if defined(BN_MP_READ_RADIX_C)
+# define BN_MP_ADD_D_C
+# define BN_MP_MUL_D_C
+# define BN_MP_ZERO_C
+#endif
+
+#if defined(BN_MP_REDUCE_C)
+# define BN_MP_ADD_C
+# define BN_MP_CLEAR_C
+# define BN_MP_CMP_C
+# define BN_MP_CMP_D_C
+# define BN_MP_INIT_COPY_C
+# define BN_MP_LSHD_C
+# define BN_MP_MOD_2D_C
+# define BN_MP_MUL_C
+# define BN_MP_RSHD_C
+# define BN_MP_SET_C
+# define BN_MP_SUB_C
+# define BN_S_MP_MUL_DIGS_C
+# define BN_S_MP_MUL_HIGH_DIGS_C
+# define BN_S_MP_MUL_HIGH_DIGS_FAST_C
+# define BN_S_MP_SUB_C
+#endif
+
+#if defined(BN_MP_REDUCE_2K_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_CMP_MAG_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_DIV_2D_C
+# define BN_MP_INIT_C
+# define BN_MP_MUL_D_C
+# define BN_S_MP_ADD_C
+# define BN_S_MP_SUB_C
+#endif
+
+#if defined(BN_MP_REDUCE_2K_L_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_CMP_MAG_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_DIV_2D_C
+# define BN_MP_INIT_C
+# define BN_MP_MUL_C
+# define BN_S_MP_ADD_C
+# define BN_S_MP_SUB_C
+#endif
+
+#if defined(BN_MP_REDUCE_2K_SETUP_C)
+# define BN_MP_2EXPT_C
+# define BN_MP_CLEAR_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_INIT_C
+# define BN_S_MP_SUB_C
+#endif
+
+#if defined(BN_MP_REDUCE_2K_SETUP_L_C)
+# define BN_MP_2EXPT_C
+# define BN_MP_CLEAR_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_INIT_C
+# define BN_S_MP_SUB_C
+#endif
+
+#if defined(BN_MP_REDUCE_IS_2K_C)
+# define BN_MP_COUNT_BITS_C
+#endif
+
+#if defined(BN_MP_REDUCE_IS_2K_L_C)
+#endif
+
+#if defined(BN_MP_REDUCE_SETUP_C)
+# define BN_MP_2EXPT_C
+# define BN_MP_DIV_C
+#endif
+
+#if defined(BN_MP_ROOT_U32_C)
+# define BN_MP_2EXPT_C
+# define BN_MP_ADD_D_C
+# define BN_MP_CLEAR_MULTI_C
+# define BN_MP_CMP_C
+# define BN_MP_COPY_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_DIV_C
+# define BN_MP_EXCH_C
+# define BN_MP_EXPT_U32_C
+# define BN_MP_INIT_MULTI_C
+# define BN_MP_MUL_C
+# define BN_MP_MUL_D_C
+# define BN_MP_SET_C
+# define BN_MP_SUB_C
+# define BN_MP_SUB_D_C
+#endif
+
+#if defined(BN_MP_RSHD_C)
+# define BN_MP_ZERO_C
+#endif
+
+#if defined(BN_MP_SBIN_SIZE_C)
+# define BN_MP_UBIN_SIZE_C
+#endif
+
+#if defined(BN_MP_SET_C)
+#endif
+
+#if defined(BN_MP_SET_DOUBLE_C)
+# define BN_MP_DIV_2D_C
+# define BN_MP_MUL_2D_C
+# define BN_MP_SET_U64_C
+#endif
+
+#if defined(BN_MP_SET_I32_C)
+# define BN_MP_SET_U32_C
+#endif
+
+#if defined(BN_MP_SET_I64_C)
+# define BN_MP_SET_U64_C
+#endif
+
+#if defined(BN_MP_SET_L_C)
+# define BN_MP_SET_UL_C
+#endif
+
+#if defined(BN_MP_SET_LL_C)
+# define BN_MP_SET_ULL_C
+#endif
+
+#if defined(BN_MP_SET_U32_C)
+#endif
+
+#if defined(BN_MP_SET_U64_C)
+#endif
+
+#if defined(BN_MP_SET_UL_C)
+#endif
+
+#if defined(BN_MP_SET_ULL_C)
+#endif
+
+#if defined(BN_MP_SHRINK_C)
+#endif
+
+#if defined(BN_MP_SIGNED_RSH_C)
+# define BN_MP_ADD_D_C
+# define BN_MP_DIV_2D_C
+# define BN_MP_SUB_D_C
+#endif
+
+#if defined(BN_MP_SQR_C)
+# define BN_S_MP_KARATSUBA_SQR_C
+# define BN_S_MP_SQR_C
+# define BN_S_MP_SQR_FAST_C
+# define BN_S_MP_TOOM_SQR_C
+#endif
+
+#if defined(BN_MP_SQRMOD_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_INIT_C
+# define BN_MP_MOD_C
+# define BN_MP_SQR_C
+#endif
+
+#if defined(BN_MP_SQRT_C)
+# define BN_MP_ADD_C
+# define BN_MP_CLEAR_C
+# define BN_MP_CMP_MAG_C
+# define BN_MP_DIV_2_C
+# define BN_MP_DIV_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_C
+# define BN_MP_INIT_COPY_C
+# define BN_MP_RSHD_C
+# define BN_MP_ZERO_C
+#endif
+
+#if defined(BN_MP_SQRTMOD_PRIME_C)
+# define BN_MP_ADD_D_C
+# define BN_MP_CLEAR_MULTI_C
+# define BN_MP_CMP_D_C
+# define BN_MP_COPY_C
+# define BN_MP_DIV_2_C
+# define BN_MP_EXPTMOD_C
+# define BN_MP_INIT_MULTI_C
+# define BN_MP_KRONECKER_C
+# define BN_MP_MOD_D_C
+# define BN_MP_MULMOD_C
+# define BN_MP_SET_C
+# define BN_MP_SET_U32_C
+# define BN_MP_SQRMOD_C
+# define BN_MP_SUB_D_C
+# define BN_MP_ZERO_C
+#endif
+
+#if defined(BN_MP_SUB_C)
+# define BN_MP_CMP_MAG_C
+# define BN_S_MP_ADD_C
+# define BN_S_MP_SUB_C
+#endif
+
+#if defined(BN_MP_SUB_D_C)
+# define BN_MP_ADD_D_C
+# define BN_MP_CLAMP_C
+# define BN_MP_GROW_C
+#endif
+
+#if defined(BN_MP_SUBMOD_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_INIT_C
+# define BN_MP_MOD_C
+# define BN_MP_SUB_C
+#endif
+
+#if defined(BN_MP_TO_RADIX_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_DIV_D_C
+# define BN_MP_INIT_COPY_C
+# define BN_S_MP_REVERSE_C
+#endif
+
+#if defined(BN_MP_TO_SBIN_C)
+# define BN_MP_TO_UBIN_C
+#endif
+
+#if defined(BN_MP_TO_UBIN_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_DIV_2D_C
+# define BN_MP_INIT_COPY_C
+# define BN_MP_UBIN_SIZE_C
+#endif
+
+#if defined(BN_MP_UBIN_SIZE_C)
+# define BN_MP_COUNT_BITS_C
+#endif
+
+#if defined(BN_MP_UNPACK_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_MUL_2D_C
+# define BN_MP_ZERO_C
+#endif
+
+#if defined(BN_MP_XOR_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_GROW_C
+#endif
+
+#if defined(BN_MP_ZERO_C)
+#endif
+
+#if defined(BN_PRIME_TAB_C)
+#endif
+
+#if defined(BN_S_MP_ADD_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_GROW_C
+#endif
+
+#if defined(BN_S_MP_BALANCE_MUL_C)
+# define BN_MP_ADD_C
+# define BN_MP_CLAMP_C
+# define BN_MP_CLEAR_C
+# define BN_MP_CLEAR_MULTI_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_MULTI_C
+# define BN_MP_INIT_SIZE_C
+# define BN_MP_LSHD_C
+# define BN_MP_MUL_C
+#endif
+
+#if defined(BN_S_MP_EXPTMOD_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_COPY_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_C
+# define BN_MP_MOD_C
+# define BN_MP_MUL_C
+# define BN_MP_REDUCE_2K_L_C
+# define BN_MP_REDUCE_2K_SETUP_L_C
+# define BN_MP_REDUCE_C
+# define BN_MP_REDUCE_SETUP_C
+# define BN_MP_SET_C
+# define BN_MP_SQR_C
+#endif
+
+#if defined(BN_S_MP_EXPTMOD_FAST_C)
+# define BN_MP_CLEAR_C
+# define BN_MP_COPY_C
+# define BN_MP_COUNT_BITS_C
+# define BN_MP_DR_REDUCE_C
+# define BN_MP_DR_SETUP_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_SIZE_C
+# define BN_MP_MOD_C
+# define BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
+# define BN_MP_MONTGOMERY_REDUCE_C
+# define BN_MP_MONTGOMERY_SETUP_C
+# define BN_MP_MULMOD_C
+# define BN_MP_MUL_C
+# define BN_MP_REDUCE_2K_C
+# define BN_MP_REDUCE_2K_SETUP_C
+# define BN_MP_SET_C
+# define BN_MP_SQR_C
+# define BN_S_MP_MONTGOMERY_REDUCE_FAST_C
+#endif
+
+#if defined(BN_S_MP_GET_BIT_C)
+#endif
+
+#if defined(BN_S_MP_INVMOD_FAST_C)
+# define BN_MP_ADD_C
+# define BN_MP_CLEAR_MULTI_C
+# define BN_MP_CMP_C
+# define BN_MP_CMP_D_C
+# define BN_MP_CMP_MAG_C
+# define BN_MP_COPY_C
+# define BN_MP_DIV_2_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_MULTI_C
+# define BN_MP_MOD_C
+# define BN_MP_SET_C
+# define BN_MP_SUB_C
+#endif
+
+#if defined(BN_S_MP_INVMOD_SLOW_C)
+# define BN_MP_ADD_C
+# define BN_MP_CLEAR_MULTI_C
+# define BN_MP_CMP_C
+# define BN_MP_CMP_D_C
+# define BN_MP_CMP_MAG_C
+# define BN_MP_COPY_C
+# define BN_MP_DIV_2_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_MULTI_C
+# define BN_MP_MOD_C
+# define BN_MP_SET_C
+# define BN_MP_SUB_C
+#endif
+
+#if defined(BN_S_MP_KARATSUBA_MUL_C)
+# define BN_MP_ADD_C
+# define BN_MP_CLAMP_C
+# define BN_MP_CLEAR_C
+# define BN_MP_INIT_SIZE_C
+# define BN_MP_LSHD_C
+# define BN_MP_MUL_C
+# define BN_S_MP_ADD_C
+# define BN_S_MP_SUB_C
+#endif
+
+#if defined(BN_S_MP_KARATSUBA_SQR_C)
+# define BN_MP_ADD_C
+# define BN_MP_CLAMP_C
+# define BN_MP_CLEAR_C
+# define BN_MP_INIT_SIZE_C
+# define BN_MP_LSHD_C
+# define BN_MP_SQR_C
+# define BN_S_MP_ADD_C
+# define BN_S_MP_SUB_C
+#endif
+
+#if defined(BN_S_MP_MONTGOMERY_REDUCE_FAST_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_CMP_MAG_C
+# define BN_MP_GROW_C
+# define BN_S_MP_SUB_C
+#endif
+
+#if defined(BN_S_MP_MUL_DIGS_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_CLEAR_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_SIZE_C
+# define BN_S_MP_MUL_DIGS_FAST_C
+#endif
+
+#if defined(BN_S_MP_MUL_DIGS_FAST_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_GROW_C
+#endif
+
+#if defined(BN_S_MP_MUL_HIGH_DIGS_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_CLEAR_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_SIZE_C
+# define BN_S_MP_MUL_HIGH_DIGS_FAST_C
+#endif
+
+#if defined(BN_S_MP_MUL_HIGH_DIGS_FAST_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_GROW_C
+#endif
+
+#if defined(BN_S_MP_PRIME_IS_DIVISIBLE_C)
+# define BN_MP_MOD_D_C
+#endif
+
+#if defined(BN_S_MP_RAND_JENKINS_C)
+# define BN_S_MP_RAND_JENKINS_INIT_C
+#endif
+
+#if defined(BN_S_MP_RAND_PLATFORM_C)
+#endif
+
+#if defined(BN_S_MP_REVERSE_C)
+#endif
+
+#if defined(BN_S_MP_SQR_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_CLEAR_C
+# define BN_MP_EXCH_C
+# define BN_MP_INIT_SIZE_C
+#endif
+
+#if defined(BN_S_MP_SQR_FAST_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_GROW_C
+#endif
+
+#if defined(BN_S_MP_SUB_C)
+# define BN_MP_CLAMP_C
+# define BN_MP_GROW_C
+#endif
+
+#if defined(BN_S_MP_TOOM_MUL_C)
+# define BN_MP_ADD_C
+# define BN_MP_CLAMP_C
+# define BN_MP_CLEAR_C
+# define BN_MP_CLEAR_MULTI_C
+# define BN_MP_DIV_2_C
+# define BN_MP_DIV_3_C
+# define BN_MP_INIT_MULTI_C
+# define BN_MP_INIT_SIZE_C
+# define BN_MP_LSHD_C
+# define BN_MP_MUL_2_C
+# define BN_MP_MUL_C
+# define BN_MP_SUB_C
+#endif
+
+#if defined(BN_S_MP_TOOM_SQR_C)
+# define BN_MP_ADD_C
+# define BN_MP_CLAMP_C
+# define BN_MP_CLEAR_C
+# define BN_MP_DIV_2_C
+# define BN_MP_INIT_C
+# define BN_MP_INIT_SIZE_C
+# define BN_MP_LSHD_C
+# define BN_MP_MUL_2_C
+# define BN_MP_MUL_C
+# define BN_MP_SQR_C
+# define BN_MP_SUB_C
+#endif
+
+#ifdef LTM_INSIDE
+#undef LTM_INSIDE
+#ifdef LTM3
+# define LTM_LAST
+#endif
+
+#include "tommath_superclass.h"
+#include "tommath_class.h"
+#else
+# define LTM_LAST
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/tommath_cutoffs.h b/third_party/heimdal/lib/hcrypto/libtommath/tommath_cutoffs.h
new file mode 100644
index 0000000..a65a9b3
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/tommath_cutoffs.h
@@ -0,0 +1,13 @@
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+/*
+ Current values evaluated on an AMD A8-6600K (64-bit).
+ Type "make tune" to optimize them for your machine but
+ be aware that it may take a long time. It took 2:30 minutes
+ on the aforementioned machine for example.
+ */
+
+#define MP_DEFAULT_KARATSUBA_MUL_CUTOFF 80
+#define MP_DEFAULT_KARATSUBA_SQR_CUTOFF 120
+#define MP_DEFAULT_TOOM_MUL_CUTOFF 350
+#define MP_DEFAULT_TOOM_SQR_CUTOFF 400
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/tommath_private.h b/third_party/heimdal/lib/hcrypto/libtommath/tommath_private.h
new file mode 100644
index 0000000..1a0096f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/tommath_private.h
@@ -0,0 +1,303 @@
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+#ifndef TOMMATH_PRIV_H_
+#define TOMMATH_PRIV_H_
+
+#include "tommath.h"
+#include "tommath_class.h"
+
+/*
+ * Private symbols
+ * ---------------
+ *
+ * On Unix symbols can be marked as hidden if libtommath is compiled
+ * as a shared object. By default, symbols are visible.
+ * As of now, this feature is opt-in via the MP_PRIVATE_SYMBOLS define.
+ *
+ * On Win32 a .def file must be used to specify the exported symbols.
+ */
+#if defined (MP_PRIVATE_SYMBOLS) && defined(__GNUC__) && __GNUC__ >= 4
+# define MP_PRIVATE __attribute__ ((visibility ("hidden")))
+#else
+# define MP_PRIVATE
+#endif
+
+/* Hardening libtommath
+ * --------------------
+ *
+ * By default memory is zeroed before calling
+ * MP_FREE to avoid leaking data. This is good
+ * practice in cryptographical applications.
+ *
+ * Note however that memory allocators used
+ * in cryptographical applications can often
+ * be configured by itself to clear memory,
+ * rendering the clearing in tommath unnecessary.
+ * See for example https://github.com/GrapheneOS/hardened_malloc
+ * and the option CONFIG_ZERO_ON_FREE.
+ *
+ * Furthermore there are applications which
+ * value performance more and want this
+ * feature to be disabled. For such applications
+ * define MP_NO_ZERO_ON_FREE during compilation.
+ */
+#ifdef MP_NO_ZERO_ON_FREE
+# define MP_FREE_BUFFER(mem, size) MP_FREE((mem), (size))
+# define MP_FREE_DIGITS(mem, digits) MP_FREE((mem), sizeof (mp_digit) * (size_t)(digits))
+#else
+# define MP_FREE_BUFFER(mem, size) \
+do { \
+ size_t fs_ = (size); \
+ void* fm_ = (mem); \
+ if (fm_ != NULL) { \
+ MP_ZERO_BUFFER(fm_, fs_); \
+ MP_FREE(fm_, fs_); \
+ } \
+} while (0)
+# define MP_FREE_DIGITS(mem, digits) \
+do { \
+ int fd_ = (digits); \
+ void* fm_ = (mem); \
+ if (fm_ != NULL) { \
+ size_t fs_ = sizeof (mp_digit) * (size_t)fd_; \
+ MP_ZERO_BUFFER(fm_, fs_); \
+ MP_FREE(fm_, fs_); \
+ } \
+} while (0)
+#endif
+
+#ifdef MP_USE_MEMSET
+# include <string.h>
+# define MP_ZERO_BUFFER(mem, size) memset((mem), 0, (size))
+# define MP_ZERO_DIGITS(mem, digits) \
+do { \
+ int zd_ = (digits); \
+ if (zd_ > 0) { \
+ memset((mem), 0, sizeof(mp_digit) * (size_t)zd_); \
+ } \
+} while (0)
+#else
+# define MP_ZERO_BUFFER(mem, size) \
+do { \
+ size_t zs_ = (size); \
+ char* zm_ = (char*)(mem); \
+ while (zs_-- > 0u) { \
+ *zm_++ = '\0'; \
+ } \
+} while (0)
+# define MP_ZERO_DIGITS(mem, digits) \
+do { \
+ int zd_ = (digits); \
+ mp_digit* zm_ = (mem); \
+ while (zd_-- > 0) { \
+ *zm_++ = 0; \
+ } \
+} while (0)
+#endif
+
+/* Tunable cutoffs
+ * ---------------
+ *
+ * - In the default settings, a cutoff X can be modified at runtime
+ * by adjusting the corresponding X_CUTOFF variable.
+ *
+ * - Tunability of the library can be disabled at compile time
+ * by defining the MP_FIXED_CUTOFFS macro.
+ *
+ * - There is an additional file tommath_cutoffs.h, which defines
+ * the default cutoffs. These can be adjusted manually or by the
+ * autotuner.
+ *
+ */
+
+#ifdef MP_FIXED_CUTOFFS
+# include "tommath_cutoffs.h"
+# define MP_KARATSUBA_MUL_CUTOFF MP_DEFAULT_KARATSUBA_MUL_CUTOFF
+# define MP_KARATSUBA_SQR_CUTOFF MP_DEFAULT_KARATSUBA_SQR_CUTOFF
+# define MP_TOOM_MUL_CUTOFF MP_DEFAULT_TOOM_MUL_CUTOFF
+# define MP_TOOM_SQR_CUTOFF MP_DEFAULT_TOOM_SQR_CUTOFF
+#else
+# define MP_KARATSUBA_MUL_CUTOFF KARATSUBA_MUL_CUTOFF
+# define MP_KARATSUBA_SQR_CUTOFF KARATSUBA_SQR_CUTOFF
+# define MP_TOOM_MUL_CUTOFF TOOM_MUL_CUTOFF
+# define MP_TOOM_SQR_CUTOFF TOOM_SQR_CUTOFF
+#endif
+
+/* define heap macros */
+#ifndef MP_MALLOC
+/* default to libc stuff */
+# include <stdlib.h>
+# define MP_MALLOC(size) malloc(size)
+# define MP_REALLOC(mem, oldsize, newsize) realloc((mem), (newsize))
+# define MP_CALLOC(nmemb, size) calloc((nmemb), (size))
+# define MP_FREE(mem, size) free(mem)
+#else
+/* prototypes for our heap functions */
+extern void *MP_MALLOC(size_t size);
+extern void *MP_REALLOC(void *mem, size_t oldsize, size_t newsize);
+extern void *MP_CALLOC(size_t nmemb, size_t size);
+extern void MP_FREE(void *mem, size_t size);
+#endif
+
+/* feature detection macro */
+#ifdef _MSC_VER
+/* Prevent false positive: not enough arguments for function-like macro invocation */
+#pragma warning(disable: 4003)
+#endif
+#define MP_STRINGIZE(x) MP__STRINGIZE(x)
+#define MP__STRINGIZE(x) ""#x""
+#define MP_HAS(x) (sizeof(MP_STRINGIZE(BN_##x##_C)) == 1u)
+
+/* TODO: Remove private_mp_word as soon as deprecated mp_word is removed from tommath. */
+#undef mp_word
+typedef private_mp_word mp_word;
+
+#define MP_MIN(x, y) (((x) < (y)) ? (x) : (y))
+#define MP_MAX(x, y) (((x) > (y)) ? (x) : (y))
+
+/* Static assertion */
+#define MP_STATIC_ASSERT(msg, cond) typedef char mp_static_assert_##msg[(cond) ? 1 : -1];
+
+/* ---> Basic Manipulations <--- */
+#define MP_IS_ZERO(a) ((a)->used == 0)
+#define MP_IS_EVEN(a) (((a)->used == 0) || (((a)->dp[0] & 1u) == 0u))
+#define MP_IS_ODD(a) (((a)->used > 0) && (((a)->dp[0] & 1u) == 1u))
+
+#define MP_SIZEOF_BITS(type) ((size_t)CHAR_BIT * sizeof(type))
+#define MP_MAXFAST (int)(1uL << (MP_SIZEOF_BITS(mp_word) - (2u * (size_t)MP_DIGIT_BIT)))
+
+/* TODO: Remove PRIVATE_MP_WARRAY as soon as deprecated MP_WARRAY is removed from tommath.h */
+#undef MP_WARRAY
+#define MP_WARRAY PRIVATE_MP_WARRAY
+
+/* TODO: Remove PRIVATE_MP_PREC as soon as deprecated MP_PREC is removed from tommath.h */
+#ifdef PRIVATE_MP_PREC
+# undef MP_PREC
+# define MP_PREC PRIVATE_MP_PREC
+#endif
+
+/* Minimum number of available digits in mp_int, MP_PREC >= MP_MIN_PREC */
+#define MP_MIN_PREC ((((int)MP_SIZEOF_BITS(long long) + MP_DIGIT_BIT) - 1) / MP_DIGIT_BIT)
+
+MP_STATIC_ASSERT(prec_geq_min_prec, MP_PREC >= MP_MIN_PREC)
+
+/* random number source */
+extern MP_PRIVATE mp_err(*s_mp_rand_source)(void *out, size_t size);
+
+/* lowlevel functions, do not call! */
+MP_PRIVATE mp_bool s_mp_get_bit(const mp_int *a, unsigned int b);
+MP_PRIVATE mp_err s_mp_add(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+MP_PRIVATE mp_err s_mp_sub(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+MP_PRIVATE mp_err s_mp_mul_digs_fast(const mp_int *a, const mp_int *b, mp_int *c, int digs) MP_WUR;
+MP_PRIVATE mp_err s_mp_mul_digs(const mp_int *a, const mp_int *b, mp_int *c, int digs) MP_WUR;
+MP_PRIVATE mp_err s_mp_mul_high_digs_fast(const mp_int *a, const mp_int *b, mp_int *c, int digs) MP_WUR;
+MP_PRIVATE mp_err s_mp_mul_high_digs(const mp_int *a, const mp_int *b, mp_int *c, int digs) MP_WUR;
+MP_PRIVATE mp_err s_mp_sqr_fast(const mp_int *a, mp_int *b) MP_WUR;
+MP_PRIVATE mp_err s_mp_sqr(const mp_int *a, mp_int *b) MP_WUR;
+MP_PRIVATE mp_err s_mp_balance_mul(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+MP_PRIVATE mp_err s_mp_karatsuba_mul(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+MP_PRIVATE mp_err s_mp_toom_mul(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+MP_PRIVATE mp_err s_mp_karatsuba_sqr(const mp_int *a, mp_int *b) MP_WUR;
+MP_PRIVATE mp_err s_mp_toom_sqr(const mp_int *a, mp_int *b) MP_WUR;
+MP_PRIVATE mp_err s_mp_invmod_fast(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+MP_PRIVATE mp_err s_mp_invmod_slow(const mp_int *a, const mp_int *b, mp_int *c) MP_WUR;
+MP_PRIVATE mp_err s_mp_montgomery_reduce_fast(mp_int *x, const mp_int *n, mp_digit rho) MP_WUR;
+MP_PRIVATE mp_err s_mp_exptmod_fast(const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y, int redmode) MP_WUR;
+MP_PRIVATE mp_err s_mp_exptmod(const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y, int redmode) MP_WUR;
+MP_PRIVATE mp_err s_mp_rand_platform(void *p, size_t n) MP_WUR;
+MP_PRIVATE mp_err s_mp_prime_random_ex(mp_int *a, int t, int size, int flags, private_mp_prime_callback cb, void *dat);
+MP_PRIVATE void s_mp_reverse(unsigned char *s, size_t len);
+MP_PRIVATE mp_err s_mp_prime_is_divisible(const mp_int *a, mp_bool *result);
+
+/* TODO: jenkins prng is not thread safe as of now */
+MP_PRIVATE mp_err s_mp_rand_jenkins(void *p, size_t n) MP_WUR;
+MP_PRIVATE void s_mp_rand_jenkins_init(uint64_t seed);
+
+extern MP_PRIVATE const char *const mp_s_rmap;
+extern MP_PRIVATE const uint8_t mp_s_rmap_reverse[];
+extern MP_PRIVATE const size_t mp_s_rmap_reverse_sz;
+extern MP_PRIVATE const mp_digit *s_mp_prime_tab;
+
+/* deprecated functions */
+MP_DEPRECATED(s_mp_invmod_fast) mp_err fast_mp_invmod(const mp_int *a, const mp_int *b, mp_int *c);
+MP_DEPRECATED(s_mp_montgomery_reduce_fast) mp_err fast_mp_montgomery_reduce(mp_int *x, const mp_int *n,
+ mp_digit rho);
+MP_DEPRECATED(s_mp_mul_digs_fast) mp_err fast_s_mp_mul_digs(const mp_int *a, const mp_int *b, mp_int *c,
+ int digs);
+MP_DEPRECATED(s_mp_mul_high_digs_fast) mp_err fast_s_mp_mul_high_digs(const mp_int *a, const mp_int *b,
+ mp_int *c,
+ int digs);
+MP_DEPRECATED(s_mp_sqr_fast) mp_err fast_s_mp_sqr(const mp_int *a, mp_int *b);
+MP_DEPRECATED(s_mp_balance_mul) mp_err mp_balance_mul(const mp_int *a, const mp_int *b, mp_int *c);
+MP_DEPRECATED(s_mp_exptmod_fast) mp_err mp_exptmod_fast(const mp_int *G, const mp_int *X, const mp_int *P,
+ mp_int *Y,
+ int redmode);
+MP_DEPRECATED(s_mp_invmod_slow) mp_err mp_invmod_slow(const mp_int *a, const mp_int *b, mp_int *c);
+MP_DEPRECATED(s_mp_karatsuba_mul) mp_err mp_karatsuba_mul(const mp_int *a, const mp_int *b, mp_int *c);
+MP_DEPRECATED(s_mp_karatsuba_sqr) mp_err mp_karatsuba_sqr(const mp_int *a, mp_int *b);
+MP_DEPRECATED(s_mp_toom_mul) mp_err mp_toom_mul(const mp_int *a, const mp_int *b, mp_int *c);
+MP_DEPRECATED(s_mp_toom_sqr) mp_err mp_toom_sqr(const mp_int *a, mp_int *b);
+MP_DEPRECATED(s_mp_reverse) void bn_reverse(unsigned char *s, int len);
+
+#define MP_GET_ENDIANNESS(x) \
+ do{\
+ int16_t n = 0x1; \
+ char *p = (char *)&n; \
+ x = (p[0] == '\x01') ? MP_LITTLE_ENDIAN : MP_BIG_ENDIAN; \
+ } while (0)
+
+/* code-generating macros */
+#define MP_SET_UNSIGNED(name, type) \
+ void name(mp_int * a, type b) \
+ { \
+ int i = 0; \
+ while (b != 0u) { \
+ a->dp[i++] = ((mp_digit)b & MP_MASK); \
+ if (MP_SIZEOF_BITS(type) <= MP_DIGIT_BIT) { break; } \
+ b >>= ((MP_SIZEOF_BITS(type) <= MP_DIGIT_BIT) ? 0 : MP_DIGIT_BIT); \
+ } \
+ a->used = i; \
+ a->sign = MP_ZPOS; \
+ MP_ZERO_DIGITS(a->dp + a->used, a->alloc - a->used); \
+ }
+
+#define MP_SET_SIGNED(name, uname, type, utype) \
+ void name(mp_int * a, type b) \
+ { \
+ uname(a, (b < 0) ? -(utype)b : (utype)b); \
+ if (b < 0) { a->sign = MP_NEG; } \
+ }
+
+#define MP_INIT_INT(name , set, type) \
+ mp_err name(mp_int * a, type b) \
+ { \
+ mp_err err; \
+ if ((err = mp_init(a)) != MP_OKAY) { \
+ return err; \
+ } \
+ set(a, b); \
+ return MP_OKAY; \
+ }
+
+#define MP_GET_MAG(name, type) \
+ type name(const mp_int* a) \
+ { \
+ unsigned i = MP_MIN((unsigned)a->used, (unsigned)((MP_SIZEOF_BITS(type) + MP_DIGIT_BIT - 1) / MP_DIGIT_BIT)); \
+ type res = 0u; \
+ while (i --> 0u) { \
+ res <<= ((MP_SIZEOF_BITS(type) <= MP_DIGIT_BIT) ? 0 : MP_DIGIT_BIT); \
+ res |= (type)a->dp[i]; \
+ if (MP_SIZEOF_BITS(type) <= MP_DIGIT_BIT) { break; } \
+ } \
+ return res; \
+ }
+
+#define MP_GET_SIGNED(name, mag, type, utype) \
+ type name(const mp_int* a) \
+ { \
+ utype res = mag(a); \
+ return (a->sign == MP_NEG) ? (type)-res : (type)res; \
+ }
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/libtommath/tommath_superclass.h b/third_party/heimdal/lib/hcrypto/libtommath/tommath_superclass.h
new file mode 100644
index 0000000..d88bce9
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/libtommath/tommath_superclass.h
@@ -0,0 +1,110 @@
+/* LibTomMath, multiple-precision integer library -- Tom St Denis */
+/* SPDX-License-Identifier: Unlicense */
+
+/* super class file for PK algos */
+
+/* default ... include all MPI */
+#ifndef LTM_NOTHING
+#define LTM_ALL
+#endif
+
+/* RSA only (does not support DH/DSA/ECC) */
+/* #define SC_RSA_1 */
+/* #define SC_RSA_1_WITH_TESTS */
+
+/* For reference.... On an Athlon64 optimizing for speed...
+
+ LTM's mpi.o with all functions [striped] is 142KiB in size.
+
+*/
+
+#ifdef SC_RSA_1_WITH_TESTS
+# define BN_MP_ERROR_TO_STRING_C
+# define BN_MP_FREAD_C
+# define BN_MP_FWRITE_C
+# define BN_MP_INCR_C
+# define BN_MP_ISEVEN_C
+# define BN_MP_ISODD_C
+# define BN_MP_NEG_C
+# define BN_MP_PRIME_FROBENIUS_UNDERWOOD_C
+# define BN_MP_RADIX_SIZE_C
+# define BN_MP_RAND_C
+# define BN_MP_REDUCE_C
+# define BN_MP_REDUCE_2K_L_C
+# define BN_MP_FROM_SBIN_C
+# define BN_MP_ROOT_U32_C
+# define BN_MP_SET_L_C
+# define BN_MP_SET_UL_C
+# define BN_MP_SBIN_SIZE_C
+# define BN_MP_TO_RADIX_C
+# define BN_MP_TO_SBIN_C
+# define BN_S_MP_RAND_JENKINS_C
+# define BN_S_MP_RAND_PLATFORM_C
+#endif
+
+/* Works for RSA only, mpi.o is 68KiB */
+#if defined(SC_RSA_1) || defined (SC_RSA_1_WITH_TESTS)
+# define BN_CUTOFFS_C
+# define BN_MP_ADDMOD_C
+# define BN_MP_CLEAR_MULTI_C
+# define BN_MP_EXPTMOD_C
+# define BN_MP_GCD_C
+# define BN_MP_INIT_MULTI_C
+# define BN_MP_INVMOD_C
+# define BN_MP_LCM_C
+# define BN_MP_MOD_C
+# define BN_MP_MOD_D_C
+# define BN_MP_MULMOD_C
+# define BN_MP_PRIME_IS_PRIME_C
+# define BN_MP_PRIME_RABIN_MILLER_TRIALS_C
+# define BN_MP_PRIME_RAND_C
+# define BN_MP_RADIX_SMAP_C
+# define BN_MP_SET_INT_C
+# define BN_MP_SHRINK_C
+# define BN_MP_TO_UNSIGNED_BIN_C
+# define BN_MP_UNSIGNED_BIN_SIZE_C
+# define BN_PRIME_TAB_C
+# define BN_S_MP_REVERSE_C
+
+/* other modifiers */
+# define BN_MP_DIV_SMALL /* Slower division, not critical */
+
+
+/* here we are on the last pass so we turn things off. The functions classes are still there
+ * but we remove them specifically from the build. This also invokes tweaks in functions
+ * like removing support for even moduli, etc...
+ */
+# ifdef LTM_LAST
+# undef BN_MP_DR_IS_MODULUS_C
+# undef BN_MP_DR_SETUP_C
+# undef BN_MP_DR_REDUCE_C
+# undef BN_MP_DIV_3_C
+# undef BN_MP_REDUCE_2K_SETUP_C
+# undef BN_MP_REDUCE_2K_C
+# undef BN_MP_REDUCE_IS_2K_C
+# undef BN_MP_REDUCE_SETUP_C
+# undef BN_S_MP_BALANCE_MUL_C
+# undef BN_S_MP_EXPTMOD_C
+# undef BN_S_MP_INVMOD_FAST_C
+# undef BN_S_MP_KARATSUBA_MUL_C
+# undef BN_S_MP_KARATSUBA_SQR_C
+# undef BN_S_MP_MUL_HIGH_DIGS_C
+# undef BN_S_MP_MUL_HIGH_DIGS_FAST_C
+# undef BN_S_MP_TOOM_MUL_C
+# undef BN_S_MP_TOOM_SQR_C
+
+# ifndef SC_RSA_1_WITH_TESTS
+# undef BN_MP_REDUCE_C
+# endif
+
+/* To safely undefine these you have to make sure your RSA key won't exceed the Comba threshold
+ * which is roughly 255 digits [7140 bits for 32-bit machines, 15300 bits for 64-bit machines]
+ * which means roughly speaking you can handle upto 2536-bit RSA keys with these defined without
+ * trouble.
+ */
+# undef BN_MP_MONTGOMERY_REDUCE_C
+# undef BN_S_MP_MUL_DIGS_C
+# undef BN_S_MP_SQR_C
+# endif
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/md2.c b/third_party/heimdal/lib/hcrypto/md2.c
new file mode 100644
index 0000000..da41e6d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/md2.c
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include "hash.h"
+#include "md2.h"
+
+static const unsigned char subst[256] = {
+ 41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6,
+ 19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188,
+ 76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24,
+ 138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251,
+ 245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63,
+ 148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50,
+ 39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165,
+ 181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210,
+ 150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157,
+ 112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27,
+ 96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15,
+ 85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197,
+ 234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65,
+ 129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123,
+ 8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233,
+ 203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228,
+ 166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237,
+ 31, 26, 219, 153, 141, 51, 159, 17, 131, 20
+};
+
+int
+MD2_Init (struct md2 *m)
+{
+ memset(m, 0, sizeof(*m));
+ return 1;
+}
+
+static void
+calc(struct md2 *m, const void *v)
+{
+ unsigned char x[48], L;
+ const unsigned char *p = v;
+ int i, j, t;
+
+ L = m->checksum[15];
+ for (i = 0; i < 16; i++)
+ L = m->checksum[i] ^= subst[p[i] ^ L];
+
+ for (i = 0; i < 16; i++) {
+ x[i] = m->state[i];
+ x[i + 16] = p[i];
+ x[i + 32] = x[i] ^ p[i];
+ }
+
+ t = 0;
+ for (i = 0; i < 18; i++) {
+ for (j = 0; j < 48; j++)
+ t = x[j] ^= subst[t];
+ t = (t + i) & 0xff;
+ }
+
+ memcpy(m->state, x, 16);
+ memset_s(x, sizeof(x), 0, sizeof(x));
+}
+
+int
+MD2_Update (struct md2 *m, const void *v, size_t len)
+{
+ size_t idx = m->len & 0xf;
+ const unsigned char *p = v;
+
+ m->len += len;
+ if (len + idx >= 16) {
+ if (idx) {
+ memcpy(m->data + idx, p, 16 - idx);
+ calc(m, m->data);
+ p += 16;
+ len -= 16 - idx;
+ }
+ while (len >= 16) {
+ calc(m, p);
+ p += 16;
+ len -= 16;
+ }
+ idx = 0;
+ }
+
+ memcpy(m->data + idx, p, len);
+ return 1;
+}
+
+int
+MD2_Final (void *res, struct md2 *m)
+{
+ unsigned char pad[16];
+ size_t padlen;
+
+ padlen = 16 - (m->len % 16);
+ memset(pad, padlen, padlen);
+
+ MD2_Update(m, pad, padlen);
+ memcpy(pad, m->checksum, 16);
+ MD2_Update(m, pad, 16);
+
+ memcpy(res, m->state, MD2_DIGEST_LENGTH);
+ memset(m, 0, sizeof(*m));
+ return 1;
+}
diff --git a/third_party/heimdal/lib/hcrypto/md2.h b/third_party/heimdal/lib/hcrypto/md2.h
new file mode 100644
index 0000000..d82334e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/md2.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_MD2_H
+#define HEIM_MD2_H 1
+
+/* symbol renaming */
+#define MD2_Init hc_MD2_Init
+#define MD2_Update hc_MD2_Update
+#define MD2_Final hc_MD2_Final
+
+/*
+ *
+ */
+
+#define MD2_DIGEST_LENGTH 16
+
+struct md2 {
+ size_t len;
+ unsigned char data[16]; /* stored unalligned data between Update's */
+ unsigned char checksum[16];
+ unsigned char state[16]; /* lower 16 bytes of X */
+};
+
+typedef struct md2 MD2_CTX;
+
+int MD2_Init (struct md2 *m);
+int MD2_Update (struct md2 *m, const void *p, size_t len);
+int MD2_Final (void *res, struct md2 *m);
+
+#endif /* HEIM_MD2_H */
diff --git a/third_party/heimdal/lib/hcrypto/md4.c b/third_party/heimdal/lib/hcrypto/md4.c
new file mode 100644
index 0000000..2a803ce
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/md4.c
@@ -0,0 +1,250 @@
+/*
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include "hash.h"
+#include "md4.h"
+
+#define A m->counter[0]
+#define B m->counter[1]
+#define C m->counter[2]
+#define D m->counter[3]
+#define X data
+
+int
+MD4_Init (struct md4 *m)
+{
+ m->sz[0] = 0;
+ m->sz[1] = 0;
+ D = 0x10325476;
+ C = 0x98badcfe;
+ B = 0xefcdab89;
+ A = 0x67452301;
+ return 1;
+}
+
+#define F(x,y,z) CRAYFIX((x & y) | (~x & z))
+#define G(x,y,z) ((x & y) | (x & z) | (y & z))
+#define H(x,y,z) (x ^ y ^ z)
+
+#define DOIT(a,b,c,d,k,s,i,OP) \
+a = cshift(a + OP(b,c,d) + X[k] + i, s)
+
+#define DO1(a,b,c,d,k,s,i) DOIT(a,b,c,d,k,s,i,F)
+#define DO2(a,b,c,d,k,s,i) DOIT(a,b,c,d,k,s,i,G)
+#define DO3(a,b,c,d,k,s,i) DOIT(a,b,c,d,k,s,i,H)
+
+static inline void
+calc (struct md4 *m, uint32_t *data)
+{
+ uint32_t AA, BB, CC, DD;
+
+ AA = A;
+ BB = B;
+ CC = C;
+ DD = D;
+
+ /* Round 1 */
+
+ DO1(A,B,C,D,0,3,0);
+ DO1(D,A,B,C,1,7,0);
+ DO1(C,D,A,B,2,11,0);
+ DO1(B,C,D,A,3,19,0);
+
+ DO1(A,B,C,D,4,3,0);
+ DO1(D,A,B,C,5,7,0);
+ DO1(C,D,A,B,6,11,0);
+ DO1(B,C,D,A,7,19,0);
+
+ DO1(A,B,C,D,8,3,0);
+ DO1(D,A,B,C,9,7,0);
+ DO1(C,D,A,B,10,11,0);
+ DO1(B,C,D,A,11,19,0);
+
+ DO1(A,B,C,D,12,3,0);
+ DO1(D,A,B,C,13,7,0);
+ DO1(C,D,A,B,14,11,0);
+ DO1(B,C,D,A,15,19,0);
+
+ /* Round 2 */
+
+ DO2(A,B,C,D,0,3,0x5A827999);
+ DO2(D,A,B,C,4,5,0x5A827999);
+ DO2(C,D,A,B,8,9,0x5A827999);
+ DO2(B,C,D,A,12,13,0x5A827999);
+
+ DO2(A,B,C,D,1,3,0x5A827999);
+ DO2(D,A,B,C,5,5,0x5A827999);
+ DO2(C,D,A,B,9,9,0x5A827999);
+ DO2(B,C,D,A,13,13,0x5A827999);
+
+ DO2(A,B,C,D,2,3,0x5A827999);
+ DO2(D,A,B,C,6,5,0x5A827999);
+ DO2(C,D,A,B,10,9,0x5A827999);
+ DO2(B,C,D,A,14,13,0x5A827999);
+
+ DO2(A,B,C,D,3,3,0x5A827999);
+ DO2(D,A,B,C,7,5,0x5A827999);
+ DO2(C,D,A,B,11,9,0x5A827999);
+ DO2(B,C,D,A,15,13,0x5A827999);
+
+ /* Round 3 */
+
+ DO3(A,B,C,D,0,3,0x6ED9EBA1);
+ DO3(D,A,B,C,8,9,0x6ED9EBA1);
+ DO3(C,D,A,B,4,11,0x6ED9EBA1);
+ DO3(B,C,D,A,12,15,0x6ED9EBA1);
+
+ DO3(A,B,C,D,2,3,0x6ED9EBA1);
+ DO3(D,A,B,C,10,9,0x6ED9EBA1);
+ DO3(C,D,A,B,6,11,0x6ED9EBA1);
+ DO3(B,C,D,A,14,15,0x6ED9EBA1);
+
+ DO3(A,B,C,D,1,3,0x6ED9EBA1);
+ DO3(D,A,B,C,9,9,0x6ED9EBA1);
+ DO3(C,D,A,B,5,11,0x6ED9EBA1);
+ DO3(B,C,D,A,13,15,0x6ED9EBA1);
+
+ DO3(A,B,C,D,3,3,0x6ED9EBA1);
+ DO3(D,A,B,C,11,9,0x6ED9EBA1);
+ DO3(C,D,A,B,7,11,0x6ED9EBA1);
+ DO3(B,C,D,A,15,15,0x6ED9EBA1);
+
+ A += AA;
+ B += BB;
+ C += CC;
+ D += DD;
+}
+
+/*
+ * From `Performance analysis of MD5' by Joseph D. Touch <touch@isi.edu>
+ */
+
+#if defined(WORDS_BIGENDIAN)
+static inline uint32_t
+swap_uint32_t (uint32_t t)
+{
+ uint32_t temp1, temp2;
+
+ temp1 = cshift(t, 16);
+ temp2 = temp1 >> 8;
+ temp1 &= 0x00ff00ff;
+ temp2 &= 0x00ff00ff;
+ temp1 <<= 8;
+ return temp1 | temp2;
+}
+#endif
+
+struct x32{
+ unsigned int a:32;
+ unsigned int b:32;
+};
+
+int
+MD4_Update (struct md4 *m, const void *v, size_t len)
+{
+ const unsigned char *p = v;
+ size_t old_sz = m->sz[0];
+ size_t offset;
+
+ m->sz[0] += len * 8;
+ if (m->sz[0] < old_sz)
+ ++m->sz[1];
+ offset = (old_sz / 8) % 64;
+ while(len > 0) {
+ size_t l = min(len, 64 - offset);
+ memcpy(m->save + offset, p, l);
+ offset += l;
+ p += l;
+ len -= l;
+ if(offset == 64) {
+#if defined(WORDS_BIGENDIAN)
+ int i;
+ uint32_t current[16];
+ struct x32 *us = (struct x32*)m->save;
+ for(i = 0; i < 8; i++){
+ current[2*i+0] = swap_uint32_t(us[i].a);
+ current[2*i+1] = swap_uint32_t(us[i].b);
+ }
+ calc(m, current);
+#else
+ calc(m, (uint32_t*)m->save);
+#endif
+ offset = 0;
+ }
+ }
+ return 1;
+}
+
+int
+MD4_Final (void *res, struct md4 *m)
+{
+ unsigned char zeros[72];
+ unsigned offset = (m->sz[0] / 8) % 64;
+ unsigned int dstart = (120 - offset - 1) % 64 + 1;
+
+ *zeros = 0x80;
+ memset (zeros + 1, 0, sizeof(zeros) - 1);
+ zeros[dstart+0] = (m->sz[0] >> 0) & 0xff;
+ zeros[dstart+1] = (m->sz[0] >> 8) & 0xff;
+ zeros[dstart+2] = (m->sz[0] >> 16) & 0xff;
+ zeros[dstart+3] = (m->sz[0] >> 24) & 0xff;
+ zeros[dstart+4] = (m->sz[1] >> 0) & 0xff;
+ zeros[dstart+5] = (m->sz[1] >> 8) & 0xff;
+ zeros[dstart+6] = (m->sz[1] >> 16) & 0xff;
+ zeros[dstart+7] = (m->sz[1] >> 24) & 0xff;
+ MD4_Update (m, zeros, dstart + 8);
+ {
+ int i;
+ unsigned char *r = (unsigned char *)res;
+
+ for (i = 0; i < 4; ++i) {
+ r[4*i] = m->counter[i] & 0xFF;
+ r[4*i+1] = (m->counter[i] >> 8) & 0xFF;
+ r[4*i+2] = (m->counter[i] >> 16) & 0xFF;
+ r[4*i+3] = (m->counter[i] >> 24) & 0xFF;
+ }
+ }
+#if 0
+ {
+ int i;
+ uint32_t *r = (uint32_t *)res;
+
+ for (i = 0; i < 4; ++i)
+ r[i] = swap_uint32_t (m->counter[i]);
+ }
+#endif
+ return 1;
+}
diff --git a/third_party/heimdal/lib/hcrypto/md4.h b/third_party/heimdal/lib/hcrypto/md4.h
new file mode 100644
index 0000000..06575c5
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/md4.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_MD4_H
+#define HEIM_MD4_H 1
+
+/* symbol renaming */
+#define MD4_Init hc_MD4_Init
+#define MD4_Update hc_MD4_Update
+#define MD4_Final hc_MD4_Final
+
+/*
+ *
+ */
+
+#define MD4_DIGEST_LENGTH 16
+
+struct md4 {
+ unsigned int sz[2];
+ uint32_t counter[4];
+ unsigned char save[64];
+};
+
+typedef struct md4 MD4_CTX;
+
+int MD4_Init (struct md4 *m);
+int MD4_Update (struct md4 *m, const void *p, size_t len);
+int MD4_Final (void *res, struct md4 *m);
+
+#endif /* HEIM_MD4_H */
diff --git a/third_party/heimdal/lib/hcrypto/md5.c b/third_party/heimdal/lib/hcrypto/md5.c
new file mode 100644
index 0000000..ca5d160
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/md5.c
@@ -0,0 +1,274 @@
+/*
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include "hash.h"
+#include "md5.h"
+
+#define A m->counter[0]
+#define B m->counter[1]
+#define C m->counter[2]
+#define D m->counter[3]
+#define X data
+
+int
+MD5_Init (struct md5 *m)
+{
+ m->sz[0] = 0;
+ m->sz[1] = 0;
+ D = 0x10325476;
+ C = 0x98badcfe;
+ B = 0xefcdab89;
+ A = 0x67452301;
+ return 1;
+}
+
+#define F(x,y,z) CRAYFIX((x & y) | (~x & z))
+#define G(x,y,z) CRAYFIX((x & z) | (y & ~z))
+#define H(x,y,z) (x ^ y ^ z)
+#define I(x,y,z) CRAYFIX(y ^ (x | ~z))
+
+#define DOIT(a,b,c,d,k,s,i,OP) \
+a = b + cshift(a + OP(b,c,d) + X[k] + (i), s)
+
+#define DO1(a,b,c,d,k,s,i) DOIT(a,b,c,d,k,s,i,F)
+#define DO2(a,b,c,d,k,s,i) DOIT(a,b,c,d,k,s,i,G)
+#define DO3(a,b,c,d,k,s,i) DOIT(a,b,c,d,k,s,i,H)
+#define DO4(a,b,c,d,k,s,i) DOIT(a,b,c,d,k,s,i,I)
+
+static inline void
+calc (struct md5 *m, uint32_t *data)
+{
+ uint32_t AA, BB, CC, DD;
+
+ AA = A;
+ BB = B;
+ CC = C;
+ DD = D;
+
+ /* Round 1 */
+
+ DO1(A,B,C,D,0,7,0xd76aa478);
+ DO1(D,A,B,C,1,12,0xe8c7b756);
+ DO1(C,D,A,B,2,17,0x242070db);
+ DO1(B,C,D,A,3,22,0xc1bdceee);
+
+ DO1(A,B,C,D,4,7,0xf57c0faf);
+ DO1(D,A,B,C,5,12,0x4787c62a);
+ DO1(C,D,A,B,6,17,0xa8304613);
+ DO1(B,C,D,A,7,22,0xfd469501);
+
+ DO1(A,B,C,D,8,7,0x698098d8);
+ DO1(D,A,B,C,9,12,0x8b44f7af);
+ DO1(C,D,A,B,10,17,0xffff5bb1);
+ DO1(B,C,D,A,11,22,0x895cd7be);
+
+ DO1(A,B,C,D,12,7,0x6b901122);
+ DO1(D,A,B,C,13,12,0xfd987193);
+ DO1(C,D,A,B,14,17,0xa679438e);
+ DO1(B,C,D,A,15,22,0x49b40821);
+
+ /* Round 2 */
+
+ DO2(A,B,C,D,1,5,0xf61e2562);
+ DO2(D,A,B,C,6,9,0xc040b340);
+ DO2(C,D,A,B,11,14,0x265e5a51);
+ DO2(B,C,D,A,0,20,0xe9b6c7aa);
+
+ DO2(A,B,C,D,5,5,0xd62f105d);
+ DO2(D,A,B,C,10,9,0x2441453);
+ DO2(C,D,A,B,15,14,0xd8a1e681);
+ DO2(B,C,D,A,4,20,0xe7d3fbc8);
+
+ DO2(A,B,C,D,9,5,0x21e1cde6);
+ DO2(D,A,B,C,14,9,0xc33707d6);
+ DO2(C,D,A,B,3,14,0xf4d50d87);
+ DO2(B,C,D,A,8,20,0x455a14ed);
+
+ DO2(A,B,C,D,13,5,0xa9e3e905);
+ DO2(D,A,B,C,2,9,0xfcefa3f8);
+ DO2(C,D,A,B,7,14,0x676f02d9);
+ DO2(B,C,D,A,12,20,0x8d2a4c8a);
+
+ /* Round 3 */
+
+ DO3(A,B,C,D,5,4,0xfffa3942);
+ DO3(D,A,B,C,8,11,0x8771f681);
+ DO3(C,D,A,B,11,16,0x6d9d6122);
+ DO3(B,C,D,A,14,23,0xfde5380c);
+
+ DO3(A,B,C,D,1,4,0xa4beea44);
+ DO3(D,A,B,C,4,11,0x4bdecfa9);
+ DO3(C,D,A,B,7,16,0xf6bb4b60);
+ DO3(B,C,D,A,10,23,0xbebfbc70);
+
+ DO3(A,B,C,D,13,4,0x289b7ec6);
+ DO3(D,A,B,C,0,11,0xeaa127fa);
+ DO3(C,D,A,B,3,16,0xd4ef3085);
+ DO3(B,C,D,A,6,23,0x4881d05);
+
+ DO3(A,B,C,D,9,4,0xd9d4d039);
+ DO3(D,A,B,C,12,11,0xe6db99e5);
+ DO3(C,D,A,B,15,16,0x1fa27cf8);
+ DO3(B,C,D,A,2,23,0xc4ac5665);
+
+ /* Round 4 */
+
+ DO4(A,B,C,D,0,6,0xf4292244);
+ DO4(D,A,B,C,7,10,0x432aff97);
+ DO4(C,D,A,B,14,15,0xab9423a7);
+ DO4(B,C,D,A,5,21,0xfc93a039);
+
+ DO4(A,B,C,D,12,6,0x655b59c3);
+ DO4(D,A,B,C,3,10,0x8f0ccc92);
+ DO4(C,D,A,B,10,15,0xffeff47d);
+ DO4(B,C,D,A,1,21,0x85845dd1);
+
+ DO4(A,B,C,D,8,6,0x6fa87e4f);
+ DO4(D,A,B,C,15,10,0xfe2ce6e0);
+ DO4(C,D,A,B,6,15,0xa3014314);
+ DO4(B,C,D,A,13,21,0x4e0811a1);
+
+ DO4(A,B,C,D,4,6,0xf7537e82);
+ DO4(D,A,B,C,11,10,0xbd3af235);
+ DO4(C,D,A,B,2,15,0x2ad7d2bb);
+ DO4(B,C,D,A,9,21,0xeb86d391);
+
+ A += AA;
+ B += BB;
+ C += CC;
+ D += DD;
+}
+
+/*
+ * From `Performance analysis of MD5' by Joseph D. Touch <touch@isi.edu>
+ */
+
+#if defined(WORDS_BIGENDIAN)
+static inline uint32_t
+swap_uint32_t (uint32_t t)
+{
+ uint32_t temp1, temp2;
+
+ temp1 = cshift(t, 16);
+ temp2 = temp1 >> 8;
+ temp1 &= 0x00ff00ff;
+ temp2 &= 0x00ff00ff;
+ temp1 <<= 8;
+ return temp1 | temp2;
+}
+#endif
+
+struct x32{
+ unsigned int a:32;
+ unsigned int b:32;
+};
+
+int
+MD5_Update (struct md5 *m, const void *v, size_t len)
+{
+ const unsigned char *p = v;
+ size_t old_sz = m->sz[0];
+ size_t offset;
+
+ m->sz[0] += len * 8;
+ if (m->sz[0] < old_sz)
+ ++m->sz[1];
+ offset = (old_sz / 8) % 64;
+ while(len > 0){
+ size_t l = min(len, 64 - offset);
+ memcpy(m->save + offset, p, l);
+ offset += l;
+ p += l;
+ len -= l;
+ if(offset == 64){
+#if defined(WORDS_BIGENDIAN)
+ int i;
+ uint32_t swapped[16];
+ struct x32 *us = (struct x32*)m->save;
+ for(i = 0; i < 8; i++){
+ swapped[2*i+0] = swap_uint32_t(us[i].a);
+ swapped[2*i+1] = swap_uint32_t(us[i].b);
+ }
+ calc(m, swapped);
+#else
+ calc(m, (uint32_t*)m->save);
+#endif
+ offset = 0;
+ }
+ }
+ return 1;
+}
+
+int
+MD5_Final (void *res, struct md5 *m)
+{
+ unsigned char zeros[72];
+ unsigned offset = (m->sz[0] / 8) % 64;
+ unsigned int dstart = (120 - offset - 1) % 64 + 1;
+
+ *zeros = 0x80;
+ memset (zeros + 1, 0, sizeof(zeros) - 1);
+ zeros[dstart+0] = (m->sz[0] >> 0) & 0xff;
+ zeros[dstart+1] = (m->sz[0] >> 8) & 0xff;
+ zeros[dstart+2] = (m->sz[0] >> 16) & 0xff;
+ zeros[dstart+3] = (m->sz[0] >> 24) & 0xff;
+ zeros[dstart+4] = (m->sz[1] >> 0) & 0xff;
+ zeros[dstart+5] = (m->sz[1] >> 8) & 0xff;
+ zeros[dstart+6] = (m->sz[1] >> 16) & 0xff;
+ zeros[dstart+7] = (m->sz[1] >> 24) & 0xff;
+ MD5_Update (m, zeros, dstart + 8);
+ {
+ int i;
+ unsigned char *r = (unsigned char *)res;
+
+ for (i = 0; i < 4; ++i) {
+ r[4*i] = m->counter[i] & 0xFF;
+ r[4*i+1] = (m->counter[i] >> 8) & 0xFF;
+ r[4*i+2] = (m->counter[i] >> 16) & 0xFF;
+ r[4*i+3] = (m->counter[i] >> 24) & 0xFF;
+ }
+ }
+#if 0
+ {
+ int i;
+ uint32_t *r = (uint32_t *)res;
+
+ for (i = 0; i < 4; ++i)
+ r[i] = swap_uint32_t (m->counter[i]);
+ }
+#endif
+ return 1;
+}
diff --git a/third_party/heimdal/lib/hcrypto/md5.h b/third_party/heimdal/lib/hcrypto/md5.h
new file mode 100644
index 0000000..ab1ac35
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/md5.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_MD5_H
+#define HEIM_MD5_H 1
+
+/* symbol renaming */
+#define MD5_Init hc_MD5_Init
+#define MD5_Update hc_MD5_Update
+#define MD5_Final hc_MD5_Final
+
+/*
+ *
+ */
+
+#define MD5_DIGEST_LENGTH 16
+
+struct md5 {
+ unsigned int sz[2];
+ uint32_t counter[4];
+ unsigned char save[64];
+};
+
+typedef struct md5 MD5_CTX;
+
+int MD5_Init (struct md5 *m);
+int MD5_Update (struct md5 *m, const void *p, size_t len);
+int MD5_Final (void *res, struct md5 *m); /* uint32_t res[4] */
+
+#endif /* HEIM_MD5_H */
diff --git a/third_party/heimdal/lib/hcrypto/md5crypt_test.c b/third_party/heimdal/lib/hcrypto/md5crypt_test.c
new file mode 100644
index 0000000..f57c3ed
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/md5crypt_test.c
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+#include <des.h>
+
+struct test {
+ const char *str;
+ const char *salt;
+ const char *result;
+} tests[] = {
+ {"Hello world!", "$1$saltstring", "$1$saltstri$YMyguxXMBpd2TEZ.vS/3q1"},
+ {NULL, NULL, NULL}
+};
+
+static int
+do_test (void)
+{
+ struct test *t;
+ int res = 0;
+
+ for (t = tests; t->str != NULL; ++t) {
+ const char *c;
+
+ c = crypt (t->str, t->salt);
+
+ if (strcmp (c, t->result) != 0) {
+ res = 1;
+ printf ("should have been: \"%s\"\n", t->result);
+ printf ("result was: \"%s\"\n", c);
+ }
+ }
+ if (res)
+ printf ("failed\n");
+ else
+ printf ("success\n");
+ return res;
+}
+
+int
+main (void)
+{
+ return do_test ();
+}
diff --git a/third_party/heimdal/lib/hcrypto/mdtest.c b/third_party/heimdal/lib/hcrypto/mdtest.c
new file mode 100644
index 0000000..d301c5c
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/mdtest.c
@@ -0,0 +1,348 @@
+/*
+ * Copyright (c) 1995 - 2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#define HC_DEPRECATED_CRYPTO
+
+#ifdef KRB5
+#include <krb5-types.h>
+#endif
+#include <md2.h>
+#include <md4.h>
+#include <md5.h>
+#include <sha.h>
+#include <evp.h>
+
+#define ONE_MILLION_A "one million a's"
+
+struct hash_foo {
+ const char *name;
+ size_t psize;
+ size_t hsize;
+ void (*init)(void*);
+ void (*update)(void*, const void*, size_t);
+ void (*final)(void*, void*);
+ const EVP_MD * (*evp)(void);
+} md2 = {
+ "MD2",
+ sizeof(MD2_CTX),
+ 16,
+ (void (*)(void*))MD2_Init,
+ (void (*)(void*,const void*, size_t))MD2_Update,
+ (void (*)(void*, void*))MD2_Final,
+ EVP_md2
+}, md4 = {
+ "MD4",
+ sizeof(MD4_CTX),
+ 16,
+ (void (*)(void*))MD4_Init,
+ (void (*)(void*,const void*, size_t))MD4_Update,
+ (void (*)(void*, void*))MD4_Final,
+ EVP_md4
+}, md5 = {
+ "MD5",
+ sizeof(MD5_CTX),
+ 16,
+ (void (*)(void*))MD5_Init,
+ (void (*)(void*,const void*, size_t))MD5_Update,
+ (void (*)(void*, void*))MD5_Final,
+ EVP_md5
+}, sha1 = {
+ "SHA-1",
+ sizeof(struct sha),
+ 20,
+ (void (*)(void*))SHA1_Init,
+ (void (*)(void*,const void*, size_t))SHA1_Update,
+ (void (*)(void*, void*))SHA1_Final,
+ EVP_sha1
+};
+struct hash_foo sha256 = {
+ "SHA-256",
+ sizeof(SHA256_CTX),
+ 32,
+ (void (*)(void*))SHA256_Init,
+ (void (*)(void*,const void*, size_t))SHA256_Update,
+ (void (*)(void*, void*))SHA256_Final,
+ EVP_sha256
+};
+struct hash_foo sha384 = {
+ "SHA-384",
+ sizeof(SHA384_CTX),
+ 48,
+ (void (*)(void*))SHA384_Init,
+ (void (*)(void*,const void*, size_t))SHA384_Update,
+ (void (*)(void*, void*))SHA384_Final,
+ EVP_sha384
+};
+struct hash_foo sha512 = {
+ "SHA-512",
+ sizeof(SHA512_CTX),
+ 64,
+ (void (*)(void*))SHA512_Init,
+ (void (*)(void*,const void*, size_t))SHA512_Update,
+ (void (*)(void*, void*))SHA512_Final,
+ EVP_sha512
+};
+
+struct test {
+ char *str;
+ unsigned char hash[64];
+};
+
+struct test md2_tests[] = {
+ {"",
+ "\x83\x50\xe5\xa3\xe2\x4c\x15\x3d\xf2\x27\x5c\x9f\x80\x69\x27\x73" },
+ {"a",
+ "\x32\xec\x01\xec\x4a\x6d\xac\x72\xc0\xab\x96\xfb\x34\xc0\xb5\xd1" },
+ {"abc",
+ "\xda\x85\x3b\x0d\x3f\x88\xd9\x9b\x30\x28\x3a\x69\xe6\xde\xd6\xbb" },
+ {"message digest",
+ "\xab\x4f\x49\x6b\xfb\x2a\x53\x0b\x21\x9f\xf3\x30\x31\xfe\x06\xb0" },
+ {"abcdefghijklmnopqrstuvwxyz",
+ "\x4e\x8d\xdf\xf3\x65\x02\x92\xab\x5a\x41\x08\xc3\xaa\x47\x94\x0b" },
+ {"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
+ "\xda\x33\xde\xf2\xa4\x2d\xf1\x39\x75\x35\x28\x46\xc3\x03\x38\xcd" },
+ {"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "\xd5\x97\x6f\x79\xd8\x3d\x3a\x0d\xc9\x80\x6c\x3c\x66\xf3\xef\xd8" },
+ {NULL, { 0 } }
+};
+
+struct test md4_tests[] = {
+ {"",
+ {0x31, 0xd6, 0xcf, 0xe0, 0xd1, 0x6a, 0xe9, 0x31, 0xb7, 0x3c, 0x59,
+ 0xd7, 0xe0, 0xc0, 0x89, 0xc0}},
+ {"a",
+ {0xbd, 0xe5, 0x2c, 0xb3, 0x1d, 0xe3, 0x3e, 0x46, 0x24, 0x5e, 0x05,
+ 0xfb, 0xdb, 0xd6, 0xfb, 0x24}},
+ {"abc",
+ {0xa4, 0x48, 0x01, 0x7a, 0xaf, 0x21, 0xd8, 0x52, 0x5f, 0xc1, 0x0a, 0xe8, 0x7a, 0xa6, 0x72, 0x9d}},
+ {"message digest",
+ {0xd9, 0x13, 0x0a, 0x81, 0x64, 0x54, 0x9f, 0xe8, 0x18, 0x87, 0x48, 0x06, 0xe1, 0xc7, 0x01, 0x4b}},
+ {"abcdefghijklmnopqrstuvwxyz", {0xd7, 0x9e, 0x1c, 0x30, 0x8a, 0xa5, 0xbb, 0xcd, 0xee, 0xa8, 0xed, 0x63, 0xdf, 0x41, 0x2d, 0xa9, }},
+ {"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
+ {0x04, 0x3f, 0x85, 0x82, 0xf2, 0x41, 0xdb, 0x35, 0x1c, 0xe6, 0x27, 0xe1, 0x53, 0xe7, 0xf0, 0xe4}},
+ {"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ {0xe3, 0x3b, 0x4d, 0xdc, 0x9c, 0x38, 0xf2, 0x19, 0x9c, 0x3e, 0x7b, 0x16, 0x4f, 0xcc, 0x05, 0x36, }},
+ {NULL, { 0x0 }}};
+
+struct test md5_tests[] = {
+ {"", {0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, 0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, 0x7e}},
+ {"a", {0x0c, 0xc1, 0x75, 0xb9, 0xc0, 0xf1, 0xb6, 0xa8, 0x31, 0xc3, 0x99, 0xe2, 0x69, 0x77, 0x26, 0x61}},
+ {"abc", {0x90, 0x01, 0x50, 0x98, 0x3c, 0xd2, 0x4f, 0xb0, 0xd6, 0x96, 0x3f, 0x7d, 0x28, 0xe1, 0x7f, 0x72}},
+ {"message digest", {0xf9, 0x6b, 0x69, 0x7d, 0x7c, 0xb7, 0x93, 0x8d, 0x52, 0x5a, 0x2f, 0x31, 0xaa, 0xf1, 0x61, 0xd0}},
+ {"abcdefghijklmnopqrstuvwxyz", {0xc3, 0xfc, 0xd3, 0xd7, 0x61, 0x92, 0xe4, 0x00, 0x7d, 0xfb, 0x49, 0x6c, 0xca, 0x67, 0xe1, 0x3b}},
+ {"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", {0xd1, 0x74, 0xab, 0x98, 0xd2, 0x77, 0xd9, 0xf5, 0xa5, 0x61, 0x1c, 0x2c, 0x9f, 0x41, 0x9d, 0x9f}},
+ {"12345678901234567890123456789012345678901234567890123456789012345678901234567890", {0x57, 0xed, 0xf4, 0xa2, 0x2b, 0xe3, 0xc9, 0x55, 0xac, 0x49, 0xda, 0x2e, 0x21, 0x07, 0xb6, 0x7a}},
+ {NULL, { 0x0 }}};
+
+struct test sha1_tests[] = {
+ { "abc",
+ {0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A,
+ 0xBA, 0x3E, 0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C,
+ 0x9C, 0xD0, 0xD8, 0x9D}},
+ { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
+ {0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E,
+ 0xBA, 0xAE, 0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5,
+ 0xE5, 0x46, 0x70, 0xF1}},
+ { ONE_MILLION_A,
+ {0x34, 0xaa, 0x97, 0x3c, 0xd4, 0xc4, 0xda, 0xa4,
+ 0xf6, 0x1e, 0xeb, 0x2b, 0xdb, 0xad, 0x27, 0x31,
+ 0x65, 0x34, 0x01, 0x6f}},
+ { NULL, { 0 } }
+};
+
+struct test sha256_tests[] = {
+ { "abc",
+ { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,
+ 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,
+ 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,
+ 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }},
+ { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
+ { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8,
+ 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,
+ 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67,
+ 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 }},
+ { ONE_MILLION_A,
+ {0xcd,0xc7,0x6e,0x5c, 0x99,0x14,0xfb,0x92,
+ 0x81,0xa1,0xc7,0xe2, 0x84,0xd7,0x3e,0x67,
+ 0xf1,0x80,0x9a,0x48, 0xa4,0x97,0x20,0x0e,
+ 0x04,0x6d,0x39,0xcc, 0xc7,0x11,0x2c,0xd0 }},
+ { NULL, { 0 } }
+};
+
+struct test sha384_tests[] = {
+ { "abc",
+ { 0xcb,0x00,0x75,0x3f,0x45,0xa3,0x5e,0x8b,
+ 0xb5,0xa0,0x3d,0x69,0x9a,0xc6,0x50,0x07,
+ 0x27,0x2c,0x32,0xab,0x0e,0xde,0xd1,0x63,
+ 0x1a,0x8b,0x60,0x5a,0x43,0xff,0x5b,0xed,
+ 0x80,0x86,0x07,0x2b,0xa1,0xe7,0xcc,0x23,
+ 0x58,0xba,0xec,0xa1,0x34,0xc8,0x25,0xa7}},
+ { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno"
+ "ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
+ { 0x09,0x33,0x0c,0x33,0xf7,0x11,0x47,0xe8,
+ 0x3d,0x19,0x2f,0xc7,0x82,0xcd,0x1b,0x47,
+ 0x53,0x11,0x1b,0x17,0x3b,0x3b,0x05,0xd2,
+ 0x2f,0xa0,0x80,0x86,0xe3,0xb0,0xf7,0x12,
+ 0xfc,0xc7,0xc7,0x1a,0x55,0x7e,0x2d,0xb9,
+ 0x66,0xc3,0xe9,0xfa,0x91,0x74,0x60,0x39}},
+ { ONE_MILLION_A,
+ { 0x9d,0x0e,0x18,0x09,0x71,0x64,0x74,0xcb,
+ 0x08,0x6e,0x83,0x4e,0x31,0x0a,0x4a,0x1c,
+ 0xed,0x14,0x9e,0x9c,0x00,0xf2,0x48,0x52,
+ 0x79,0x72,0xce,0xc5,0x70,0x4c,0x2a,0x5b,
+ 0x07,0xb8,0xb3,0xdc,0x38,0xec,0xc4,0xeb,
+ 0xae,0x97,0xdd,0xd8,0x7f,0x3d,0x89,0x85}},
+ {NULL, { 0 }}
+};
+
+struct test sha512_tests[] = {
+ { "abc",
+ { 0xdd,0xaf,0x35,0xa1,0x93,0x61,0x7a,0xba,
+ 0xcc,0x41,0x73,0x49,0xae,0x20,0x41,0x31,
+ 0x12,0xe6,0xfa,0x4e,0x89,0xa9,0x7e,0xa2,
+ 0x0a,0x9e,0xee,0xe6,0x4b,0x55,0xd3,0x9a,
+ 0x21,0x92,0x99,0x2a,0x27,0x4f,0xc1,0xa8,
+ 0x36,0xba,0x3c,0x23,0xa3,0xfe,0xeb,0xbd,
+ 0x45,0x4d,0x44,0x23,0x64,0x3c,0xe8,0x0e,
+ 0x2a,0x9a,0xc9,0x4f,0xa5,0x4c,0xa4,0x9f }},
+ { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno"
+ "ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
+ { 0x8e,0x95,0x9b,0x75,0xda,0xe3,0x13,0xda,
+ 0x8c,0xf4,0xf7,0x28,0x14,0xfc,0x14,0x3f,
+ 0x8f,0x77,0x79,0xc6,0xeb,0x9f,0x7f,0xa1,
+ 0x72,0x99,0xae,0xad,0xb6,0x88,0x90,0x18,
+ 0x50,0x1d,0x28,0x9e,0x49,0x00,0xf7,0xe4,
+ 0x33,0x1b,0x99,0xde,0xc4,0xb5,0x43,0x3a,
+ 0xc7,0xd3,0x29,0xee,0xb6,0xdd,0x26,0x54,
+ 0x5e,0x96,0xe5,0x5b,0x87,0x4b,0xe9,0x09 }},
+ { ONE_MILLION_A,
+ { 0xe7,0x18,0x48,0x3d,0x0c,0xe7,0x69,0x64,
+ 0x4e,0x2e,0x42,0xc7,0xbc,0x15,0xb4,0x63,
+ 0x8e,0x1f,0x98,0xb1,0x3b,0x20,0x44,0x28,
+ 0x56,0x32,0xa8,0x03,0xaf,0xa9,0x73,0xeb,
+ 0xde,0x0f,0xf2,0x44,0x87,0x7e,0xa6,0x0a,
+ 0x4c,0xb0,0x43,0x2c,0xe5,0x77,0xc3,0x1b,
+ 0xeb,0x00,0x9c,0x5c,0x2c,0x49,0xaa,0x2e,
+ 0x4e,0xad,0xb2,0x17,0xad,0x8c,0xc0,0x9b }},
+ { NULL, { 0 } }
+};
+
+static int
+hash_test (struct hash_foo *hash, struct test *tests)
+{
+ struct test *t;
+ EVP_MD_CTX *ectx;
+ unsigned int esize;
+ void *ctx = malloc(hash->psize);
+ unsigned char *res = malloc(hash->hsize);
+
+ printf ("%s... ", hash->name);
+ for (t = tests; t->str; ++t) {
+ char buf[1000];
+
+ ectx = EVP_MD_CTX_create();
+ if (hash->evp() == NULL) {
+ printf("unavailable\n");
+ continue;
+ }
+ EVP_DigestInit_ex(ectx, hash->evp(), NULL);
+
+ (*hash->init)(ctx);
+ if(strcmp(t->str, ONE_MILLION_A) == 0) {
+ int i;
+ memset(buf, 'a', sizeof(buf));
+ for(i = 0; i < 1000; i++) {
+ (*hash->update)(ctx, buf, sizeof(buf));
+ EVP_DigestUpdate(ectx, buf, sizeof(buf));
+ }
+ } else {
+ (*hash->update)(ctx, (unsigned char *)t->str, strlen(t->str));
+ EVP_DigestUpdate(ectx, t->str, strlen(t->str));
+ }
+
+ (*hash->final) (res, ctx);
+ if (memcmp (res, t->hash, hash->hsize) != 0) {
+ int i;
+
+ printf ("%s(\"%s\") failed\n", hash->name, t->str);
+ printf("should be: ");
+ for(i = 0; i < hash->hsize; ++i) {
+ if(i > 0 && (i % 16) == 0)
+ printf("\n ");
+ printf("%02x ", t->hash[i]);
+ }
+ printf("\nresult was: ");
+ for(i = 0; i < hash->hsize; ++i) {
+ if(i > 0 && (i % 16) == 0)
+ printf("\n ");
+ printf("%02x ", res[i]);
+ }
+ printf("\n");
+ return 1;
+ }
+
+ EVP_DigestFinal_ex(ectx, res, &esize);
+ EVP_MD_CTX_destroy(ectx);
+
+ if (hash->hsize != esize) {
+ printf("EVP %s returned wrong hash size\n", hash->name);
+ return 1;
+ }
+
+ if (memcmp (res, t->hash, hash->hsize) != 0) {
+ printf("EVP %s failed here old function where successful!\n",
+ hash->name);
+ return 1;
+ }
+ }
+ free(ctx);
+ free(res);
+ printf ("success\n");
+ return 0;
+}
+
+int
+main (void)
+{
+ return
+ hash_test(&md2, md2_tests) +
+ hash_test(&md4, md4_tests) +
+ hash_test(&md5, md5_tests) +
+ hash_test(&sha1, sha1_tests) +
+ hash_test(&sha256, sha256_tests) +
+ hash_test(&sha384, sha384_tests) +
+ hash_test(&sha512, sha512_tests);
+}
diff --git a/third_party/heimdal/lib/hcrypto/passwd_dialog.aps b/third_party/heimdal/lib/hcrypto/passwd_dialog.aps
new file mode 100644
index 0000000..c90d030
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/passwd_dialog.aps
Binary files differ
diff --git a/third_party/heimdal/lib/hcrypto/passwd_dialog.clw b/third_party/heimdal/lib/hcrypto/passwd_dialog.clw
new file mode 100644
index 0000000..f3451af
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/passwd_dialog.clw
@@ -0,0 +1,34 @@
+; CLW file contains information for the MFC ClassWizard
+
+[General Info]
+Version=1
+LastClass=
+LastTemplate=CDialog
+NewFileInclude1=#include "stdafx.h"
+NewFileInclude2=#include "passwd_dialog.h"
+LastPage=0
+
+ClassCount=0
+
+ResourceCount=2
+Resource1=IDD_DIALOG1
+Resource2=IDD_PASSWD_DIALOG
+
+[DLG:IDD_DIALOG1]
+Type=1
+ControlCount=6
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_STATIC,static,1342308352
+Control4=IDC_STATIC,static,1342308352
+Control5=IDC_EDIT1,edit,1350631552
+Control6=IDC_EDIT2,edit,1350631584
+
+[DLG:IDD_PASSWD_DIALOG]
+Type=1
+ControlCount=4
+Control1=IDC_PASSWD_EDIT,edit,1350631456
+Control2=IDOK,button,1342242817
+Control3=IDCANCEL,button,1342242816
+Control4=IDC_STATIC,static,1342177280
+
diff --git a/third_party/heimdal/lib/hcrypto/passwd_dialog.rc b/third_party/heimdal/lib/hcrypto/passwd_dialog.rc
new file mode 100644
index 0000000..62079f2
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/passwd_dialog.rc
@@ -0,0 +1,143 @@
+//Microsoft Developer Studio generated resource script.
+//
+#include "resource.h"
+
+#define APSTUDIO_READONLY_SYMBOLS
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 2 resource.
+//
+#include "afxres.h"
+
+/////////////////////////////////////////////////////////////////////////////
+#undef APSTUDIO_READONLY_SYMBOLS
+
+/////////////////////////////////////////////////////////////////////////////
+// Swedish resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_SVE)
+#ifdef _WIN32
+LANGUAGE LANG_SWEDISH, SUBLANG_DEFAULT
+#pragma code_page(1252)
+#endif //_WIN32
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Dialog
+//
+
+IDD_PASSWD_DIALOG DIALOG DISCARDABLE 0, 0, 186, 66
+STYLE DS_ABSALIGN | DS_MODALFRAME | DS_SETFOREGROUND | DS_CENTER | WS_POPUP |
+ WS_VISIBLE | WS_CAPTION
+CAPTION "Password query"
+FONT 8, "MS Sans Serif"
+BEGIN
+ EDITTEXT IDC_PASSWD_EDIT,30,22,125,14,ES_PASSWORD
+ DEFPUSHBUTTON "OK",IDOK,30,45,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,105,45,50,14
+ LTEXT "Please insert password:",IDC_STATIC,30,13,87,8,NOT
+ WS_GROUP
+END
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// DESIGNINFO
+//
+
+#ifdef APSTUDIO_INVOKED
+GUIDELINES DESIGNINFO DISCARDABLE
+BEGIN
+ IDD_PASSWD_DIALOG, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 179
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 59
+ END
+END
+#endif // APSTUDIO_INVOKED
+
+
+#ifdef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// TEXTINCLUDE
+//
+
+1 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "resource.h\0"
+END
+
+2 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "#include ""afxres.h""\r\n"
+ "\0"
+END
+
+3 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "\r\n"
+ "\0"
+END
+
+#endif // APSTUDIO_INVOKED
+
+
+#ifndef _MAC
+/////////////////////////////////////////////////////////////////////////////
+//
+// Version
+//
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION 1,0,0,1
+ PRODUCTVERSION 1,0,0,1
+ FILEFLAGSMASK 0x3fL
+#ifdef _DEBUG
+ FILEFLAGS 0x1L
+#else
+ FILEFLAGS 0x0L
+#endif
+ FILEOS 0x40004L
+ FILETYPE 0x2L
+ FILESUBTYPE 0x0L
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "040904b0"
+ BEGIN
+ VALUE "CompanyName", "Royal Institute of Technology (KTH)\0"
+ VALUE "FileDescription", "des\0"
+ VALUE "FileVersion", "4, 0, 9, 9\0"
+ VALUE "InternalName", "des\0"
+ VALUE "LegalCopyright", "Copyright 1996 - 1998 Royal Institute of Technology (KTH)\0"
+ VALUE "OriginalFilename", "des.dll\0"
+ VALUE "ProductName", "KTH Kerberos\0"
+ VALUE "ProductVersion", "4,0,9,9\0"
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x409, 1200
+ END
+END
+
+#endif // !_MAC
+
+#endif // Swedish resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+
+#ifndef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 3 resource.
+//
+
+
+/////////////////////////////////////////////////////////////////////////////
+#endif // not APSTUDIO_INVOKED
+
diff --git a/third_party/heimdal/lib/hcrypto/passwd_dialog.res b/third_party/heimdal/lib/hcrypto/passwd_dialog.res
new file mode 100644
index 0000000..bdb2868
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/passwd_dialog.res
Binary files differ
diff --git a/third_party/heimdal/lib/hcrypto/passwd_dlg.c b/third_party/heimdal/lib/hcrypto/passwd_dlg.c
new file mode 100644
index 0000000..037fa74
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/passwd_dlg.c
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* passwd_dlg.c - Dialog boxes for Windows95/NT
+ * Author: Jörgen Karlsson - d93-jka@nada.kth.se
+ * Date: June 1996
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#ifdef WIN32 /* Visual C++ 4.0 (Windows95/NT) */
+#include "passwd_dlg.h"
+#include "Resource.h"
+#define passwdBufSZ 64
+
+char passwd[passwdBufSZ];
+
+BOOL CALLBACK
+pwd_dialog_proc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+ switch(uMsg)
+ {
+ case WM_COMMAND:
+ switch(wParam)
+ {
+ case IDOK:
+ if(!GetDlgItemText(hwndDlg,IDC_PASSWD_EDIT, passwd, passwdBufSZ))
+ EndDialog(hwndDlg, IDCANCEL);
+ case IDCANCEL:
+ EndDialog(hwndDlg, wParam);
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+
+/* return 0 if ok, 1 otherwise */
+int
+pwd_dialog(char *buf, int size)
+{
+ int i;
+ HWND wnd = GetActiveWindow();
+ HANDLE hInst = GetModuleHandle("des");
+ switch(DialogBox(hInst,MAKEINTRESOURCE(IDD_PASSWD_DIALOG),wnd,pwd_dialog_proc))
+ {
+ case IDOK:
+ strlcpy(buf, passwd, size);
+ memset (passwd, 0, sizeof(passwd));
+ return 0;
+ case IDCANCEL:
+ default:
+ memset (passwd, 0, sizeof(passwd));
+ return 1;
+ }
+}
+
+#endif /* WIN32 */
diff --git a/third_party/heimdal/lib/hcrypto/passwd_dlg.h b/third_party/heimdal/lib/hcrypto/passwd_dlg.h
new file mode 100644
index 0000000..222417d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/passwd_dlg.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* passwd_dlg.h - Dialog boxes for Windows95/NT
+ * Author: Jörgen Karlsson - d93-jka@nada.kth.se
+ * Date: June 1996
+ */
+
+/* $Id$ */
+
+#ifndef PASSWD_DLG_H
+#define PASSWD_DLG_H
+
+int pwd_dialog(char *buf, int size);
+
+
+#endif /* PASSWD_DLG_H */
diff --git a/third_party/heimdal/lib/hcrypto/pkcs12.c b/third_party/heimdal/lib/hcrypto/pkcs12.c
new file mode 100644
index 0000000..5f0791f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/pkcs12.c
@@ -0,0 +1,158 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+#include <assert.h>
+
+#include <pkcs12.h>
+#include <bn.h>
+
+int
+PKCS12_key_gen(const void *key, size_t keylen,
+ const void *salt, size_t saltlen,
+ int id, int iteration, size_t outkeysize,
+ void *out, const EVP_MD *md)
+{
+ unsigned char *v, *I, hash[EVP_MAX_MD_SIZE];
+ unsigned int size, size_I = 0;
+ unsigned char idc = id;
+ EVP_MD_CTX *ctx;
+ unsigned char *outp = out;
+ int i, vlen;
+
+ /**
+ * The argument key is pointing to an utf16 string, and thus
+ * keylen that is no a multiple of 2 is invalid.
+ */
+ if (keylen & 1)
+ return 0;
+
+ ctx = EVP_MD_CTX_create();
+ if (ctx == NULL)
+ return 0;
+
+ vlen = EVP_MD_block_size(md);
+ v = malloc(vlen + 1);
+ if (v == NULL) {
+ EVP_MD_CTX_destroy(ctx);
+ return 0;
+ }
+
+ I = calloc(1, vlen * 2);
+ if (I == NULL) {
+ EVP_MD_CTX_destroy(ctx);
+ free(v);
+ return 0;
+ }
+
+ if (salt && saltlen > 0) {
+ for (i = 0; i < vlen; i++)
+ I[i] = ((unsigned char*)salt)[i % saltlen];
+ size_I += vlen;
+ }
+ /*
+ * There is a diffrence between the no password string and the
+ * empty string, in the empty string the UTF16 NUL terminator is
+ * included into the string.
+ */
+ if (key) {
+ for (i = 0; i < vlen / 2; i++) {
+ I[(i * 2) + size_I] = 0;
+ I[(i * 2) + size_I + 1] = ((unsigned char*)key)[i % (keylen + 1)];
+ }
+ size_I += vlen;
+ }
+
+ while (1) {
+ BIGNUM *bnB, *bnOne;
+
+ if (!EVP_DigestInit_ex(ctx, md, NULL)) {
+ EVP_MD_CTX_destroy(ctx);
+ free(I);
+ free(v);
+ return 0;
+ }
+ for (i = 0; i < vlen; i++)
+ EVP_DigestUpdate(ctx, &idc, 1);
+ EVP_DigestUpdate(ctx, I, size_I);
+ EVP_DigestFinal_ex(ctx, hash, &size);
+
+ for (i = 1; i < iteration; i++)
+ EVP_Digest(hash, size, hash, &size, md, NULL);
+
+ memcpy(outp, hash, min(outkeysize, size));
+ if (outkeysize < size)
+ break;
+ outkeysize -= size;
+ outp += size;
+
+ for (i = 0; i < vlen; i++)
+ v[i] = hash[i % size];
+
+ bnB = BN_bin2bn(v, vlen, NULL);
+ bnOne = BN_new();
+ BN_set_word(bnOne, 1);
+
+ BN_uadd(bnB, bnB, bnOne);
+
+ for (i = 0; i < vlen * 2; i += vlen) {
+ BIGNUM *bnI;
+ int j;
+
+ bnI = BN_bin2bn(I + i, vlen, NULL);
+
+ BN_uadd(bnI, bnI, bnB);
+
+ j = BN_num_bytes(bnI);
+ if (j > vlen) {
+ assert(j == vlen + 1);
+ BN_bn2bin(bnI, v);
+ memcpy(I + i, v + 1, vlen);
+ } else {
+ memset(I + i, 0, vlen - j);
+ BN_bn2bin(bnI, I + i + vlen - j);
+ }
+ BN_free(bnI);
+ }
+ BN_free(bnB);
+ BN_free(bnOne);
+ size_I = vlen * 2;
+ }
+
+ EVP_MD_CTX_destroy(ctx);
+ free(I);
+ free(v);
+
+ return 1;
+}
diff --git a/third_party/heimdal/lib/hcrypto/pkcs12.h b/third_party/heimdal/lib/hcrypto/pkcs12.h
new file mode 100644
index 0000000..7e8214e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/pkcs12.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef _HEIM_PKCS12_H
+#define _HEIM_PKCS12_H 1
+
+/* symbol renaming */
+#define PKCS12_key_gen hc_PKCS12_key_gen
+
+/*
+ *
+ */
+
+#include <hcrypto/evp.h>
+
+#define PKCS12_KEY_ID 1
+#define PKCS12_IV_ID 2
+
+int PKCS12_key_gen(const void *, size_t, const void *,
+ size_t, int, int, size_t, void *, const EVP_MD *);
+
+
+#endif /* _HEIM_PKCS12_H */
diff --git a/third_party/heimdal/lib/hcrypto/pkcs5.c b/third_party/heimdal/lib/hcrypto/pkcs5.c
new file mode 100644
index 0000000..dff3cce
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/pkcs5.c
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#ifdef KRB5
+#include <krb5-types.h>
+#endif
+
+#include <evp.h>
+#include <hmac.h>
+
+/**
+ * As descriped in PKCS5, convert a password, salt, and iteration counter into a crypto key.
+ *
+ * @param password Password.
+ * @param password_len Length of password.
+ * @param salt Salt
+ * @param salt_len Length of salt.
+ * @param iter iteration counter.
+ * @param md the digest function.
+ * @param keylen the output key length.
+ * @param key the output key.
+ *
+ * @return 1 on success, non 1 on failure.
+ *
+ * @ingroup hcrypto_misc
+ */
+
+int
+PKCS5_PBKDF2_HMAC(const void * password, size_t password_len,
+ const void * salt, size_t salt_len,
+ unsigned long iter,
+ const EVP_MD *md,
+ size_t keylen, void *key)
+{
+ size_t datalen, leftofkey, checksumsize;
+ char *data, *tmpcksum;
+ uint32_t keypart;
+ unsigned long i;
+ int j;
+ char *p;
+ unsigned int hmacsize;
+
+ if (md == NULL)
+ return 0;
+
+ checksumsize = EVP_MD_size(md);
+ datalen = salt_len + 4;
+
+ tmpcksum = malloc(checksumsize + datalen);
+ if (tmpcksum == NULL)
+ return 0;
+
+ data = &tmpcksum[checksumsize];
+
+ memcpy(data, salt, salt_len);
+
+ keypart = 1;
+ leftofkey = keylen;
+ p = key;
+
+ while (leftofkey) {
+ int len;
+
+ if (leftofkey > checksumsize)
+ len = checksumsize;
+ else
+ len = leftofkey;
+
+ data[datalen - 4] = (keypart >> 24) & 0xff;
+ data[datalen - 3] = (keypart >> 16) & 0xff;
+ data[datalen - 2] = (keypart >> 8) & 0xff;
+ data[datalen - 1] = (keypart) & 0xff;
+
+ HMAC(md, password, password_len, data, datalen,
+ tmpcksum, &hmacsize);
+
+ memcpy(p, tmpcksum, len);
+ for (i = 1; i < iter; i++) {
+ HMAC(md, password, password_len, tmpcksum, checksumsize,
+ tmpcksum, &hmacsize);
+
+ for (j = 0; j < len; j++)
+ p[j] ^= tmpcksum[j];
+ }
+
+ p += len;
+ leftofkey -= len;
+ keypart++;
+ }
+
+ free(tmpcksum);
+
+ return 1;
+}
+
+/**
+ * As descriped in PKCS5, convert a password, salt, and iteration counter into a crypto key.
+ *
+ * @param password Password.
+ * @param password_len Length of password.
+ * @param salt Salt
+ * @param salt_len Length of salt.
+ * @param iter iteration counter.
+ * @param keylen the output key length.
+ * @param key the output key.
+ *
+ * @return 1 on success, non 1 on failure.
+ *
+ * @ingroup hcrypto_misc
+ */
+int
+PKCS5_PBKDF2_HMAC_SHA1(const void * password, size_t password_len,
+ const void * salt, size_t salt_len,
+ unsigned long iter,
+ size_t keylen, void *key)
+{
+ return PKCS5_PBKDF2_HMAC(password, password_len, salt, salt_len, iter,
+ EVP_sha1(), keylen, key);
+}
diff --git a/third_party/heimdal/lib/hcrypto/rand-fortuna.c b/third_party/heimdal/lib/hcrypto/rand-fortuna.c
new file mode 100644
index 0000000..313b86f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rand-fortuna.c
@@ -0,0 +1,649 @@
+/*
+ * fortuna.c
+ * Fortuna-like PRNG.
+ *
+ * Copyright (c) 2005 Marko Kreen
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $PostgreSQL: pgsql/contrib/pgcrypto/fortuna.c,v 1.8 2006/10/04 00:29:46 momjian Exp $
+ */
+
+#include <config.h>
+#include <roken.h>
+#include <rand.h>
+#include <heim_threads.h>
+
+#ifdef KRB5
+#include <krb5-types.h>
+#endif
+
+#include "randi.h"
+#include "aes.h"
+#include "sha.h"
+
+/*
+ * Why Fortuna-like: There does not seem to be any definitive reference
+ * on Fortuna in the net. Instead this implementation is based on
+ * following references:
+ *
+ * http://en.wikipedia.org/wiki/Fortuna_(PRNG)
+ * - Wikipedia article
+ * http://jlcooke.ca/random/
+ * - Jean-Luc Cooke Fortuna-based /dev/random driver for Linux.
+ */
+
+/*
+ * There is some confusion about whether and how to carry forward
+ * the state of the pools. Seems like original Fortuna does not
+ * do it, resetting hash after each request. I guess expecting
+ * feeding to happen more often that requesting. This is absolutely
+ * unsuitable for pgcrypto, as nothing asynchronous happens here.
+ *
+ * J.L. Cooke fixed this by feeding previous hash to new re-initialized
+ * hash context.
+ *
+ * Fortuna predecessor Yarrow requires ability to query intermediate
+ * 'final result' from hash, without affecting it.
+ *
+ * This implementation uses the Yarrow method - asking intermediate
+ * results, but continuing with old state.
+ */
+
+
+/*
+ * Algorithm parameters
+ */
+
+#define NUM_POOLS 32
+
+/* in microseconds */
+#define RESEED_INTERVAL 100000 /* 0.1 sec */
+
+/* for one big request, reseed after this many bytes */
+#define RESEED_BYTES (1024*1024)
+
+/*
+ * Skip reseed if pool 0 has less than this many
+ * bytes added since last reseed.
+ */
+#define POOL0_FILL (256/8)
+
+/*
+ * Algorithm constants
+ */
+
+/* Both cipher key size and hash result size */
+#define BLOCK 32
+
+/* cipher block size */
+#define CIPH_BLOCK 16
+
+/* for internal wrappers */
+#define MD_CTX SHA256_CTX
+#define CIPH_CTX AES_KEY
+
+struct fortuna_state
+{
+ unsigned char counter[CIPH_BLOCK];
+ unsigned char result[CIPH_BLOCK];
+ unsigned char key[BLOCK];
+ MD_CTX pool[NUM_POOLS];
+ CIPH_CTX ciph;
+ unsigned reseed_count;
+ struct timeval last_reseed_time;
+ unsigned pool0_bytes;
+ unsigned rnd_pos;
+ int tricks_done;
+ pid_t pid;
+};
+typedef struct fortuna_state FState;
+
+
+/*
+ * Use our own wrappers here.
+ * - Need to get intermediate result from digest, without affecting it.
+ * - Need re-set key on a cipher context.
+ * - Algorithms are guaranteed to exist.
+ * - No memory allocations.
+ */
+
+static void
+ciph_init(CIPH_CTX * ctx, const unsigned char *key, int klen)
+{
+ AES_set_encrypt_key(key, klen * 8, ctx);
+}
+
+static void
+ciph_encrypt(CIPH_CTX * ctx, const unsigned char *in, unsigned char *out)
+{
+ AES_encrypt(in, out, ctx);
+}
+
+static void
+md_init(MD_CTX * ctx)
+{
+ SHA256_Init(ctx);
+}
+
+static void
+md_update(MD_CTX * ctx, const unsigned char *data, int len)
+{
+ SHA256_Update(ctx, data, len);
+}
+
+static void
+md_result(MD_CTX * ctx, unsigned char *dst)
+{
+ SHA256_CTX tmp;
+
+ memcpy(&tmp, ctx, sizeof(*ctx));
+ SHA256_Final(dst, &tmp);
+ memset_s(&tmp, sizeof(tmp), 0, sizeof(tmp));
+}
+
+/*
+ * initialize state
+ */
+static void
+init_state(FState * st)
+{
+ int i;
+
+ memset(st, 0, sizeof(*st));
+ for (i = 0; i < NUM_POOLS; i++)
+ md_init(&st->pool[i]);
+ st->pid = getpid();
+}
+
+/*
+ * Endianess does not matter.
+ * It just needs to change without repeating.
+ */
+static void
+inc_counter(FState * st)
+{
+ uint32_t *val = (uint32_t *) st->counter;
+
+ if (++val[0])
+ return;
+ if (++val[1])
+ return;
+ if (++val[2])
+ return;
+ ++val[3];
+}
+
+/*
+ * This is called 'cipher in counter mode'.
+ */
+static void
+encrypt_counter(FState * st, unsigned char *dst)
+{
+ ciph_encrypt(&st->ciph, st->counter, dst);
+ inc_counter(st);
+}
+
+
+/*
+ * The time between reseed must be at least RESEED_INTERVAL
+ * microseconds.
+ */
+static int
+enough_time_passed(FState * st)
+{
+ int ok;
+ struct timeval tv;
+ struct timeval *last = &st->last_reseed_time;
+
+ gettimeofday(&tv, NULL);
+
+ /* check how much time has passed */
+ ok = 0;
+ if (tv.tv_sec > last->tv_sec + 1)
+ ok = 1;
+ else if (tv.tv_sec == last->tv_sec + 1)
+ {
+ if (1000000 + tv.tv_usec - last->tv_usec >= RESEED_INTERVAL)
+ ok = 1;
+ }
+ else if (tv.tv_usec - last->tv_usec >= RESEED_INTERVAL)
+ ok = 1;
+
+ /* reseed will happen, update last_reseed_time */
+ if (ok)
+ memcpy(last, &tv, sizeof(tv));
+
+ memset_s(&tv, sizeof(tv), 0, sizeof(tv));
+
+ return ok;
+}
+
+/*
+ * generate new key from all the pools
+ */
+static void
+reseed(FState * st)
+{
+ unsigned k;
+ unsigned n;
+ MD_CTX key_md;
+ unsigned char buf[BLOCK];
+
+ /* set pool as empty */
+ st->pool0_bytes = 0;
+
+ /*
+ * Both #0 and #1 reseed would use only pool 0. Just skip #0 then.
+ */
+ n = ++st->reseed_count;
+
+ /*
+ * The goal: use k-th pool only 1/(2^k) of the time.
+ */
+ md_init(&key_md);
+ for (k = 0; k < NUM_POOLS; k++)
+ {
+ md_result(&st->pool[k], buf);
+ md_update(&key_md, buf, BLOCK);
+
+ if (n & 1 || !n)
+ break;
+ n >>= 1;
+ }
+
+ /* add old key into mix too */
+ md_update(&key_md, st->key, BLOCK);
+
+ /* add pid to make output diverse after fork() */
+ md_update(&key_md, (const unsigned char *)&st->pid, sizeof(st->pid));
+
+ /* now we have new key */
+ md_result(&key_md, st->key);
+
+ /* use new key */
+ ciph_init(&st->ciph, st->key, BLOCK);
+
+ memset_s(&key_md, sizeof(key_md), 0, sizeof(key_md));
+ memset_s(buf, sizeof(buf), 0, sizeof(buf));
+}
+
+/*
+ * Pick a random pool. This uses key bytes as random source.
+ */
+static unsigned
+get_rand_pool(FState * st)
+{
+ unsigned rnd;
+
+ /*
+ * This slightly prefers lower pools - thats OK.
+ */
+ rnd = st->key[st->rnd_pos] % NUM_POOLS;
+
+ st->rnd_pos++;
+ if (st->rnd_pos >= BLOCK)
+ st->rnd_pos = 0;
+
+ return rnd;
+}
+
+/*
+ * update pools
+ */
+static void
+add_entropy(FState * st, const unsigned char *data, unsigned len)
+{
+ unsigned pos;
+ unsigned char hash[BLOCK];
+ MD_CTX md;
+
+ /* hash given data */
+ md_init(&md);
+ md_update(&md, data, len);
+ md_result(&md, hash);
+
+ /*
+ * Make sure the pool 0 is initialized, then update randomly.
+ */
+ if (st->reseed_count == 0)
+ pos = 0;
+ else
+ pos = get_rand_pool(st);
+ md_update(&st->pool[pos], hash, BLOCK);
+
+ if (pos == 0)
+ st->pool0_bytes += len;
+
+ memset_s(hash, sizeof(hash), 0, sizeof(hash));
+ memset_s(&md, sizeof(hash), 0, sizeof(md));
+}
+
+/*
+ * Just take 2 next blocks as new key
+ */
+static void
+rekey(FState * st)
+{
+ encrypt_counter(st, st->key);
+ encrypt_counter(st, st->key + CIPH_BLOCK);
+ ciph_init(&st->ciph, st->key, BLOCK);
+}
+
+/*
+ * Hide public constants. (counter, pools > 0)
+ *
+ * This can also be viewed as spreading the startup
+ * entropy over all of the components.
+ */
+static void
+startup_tricks(FState * st)
+{
+ int i;
+ unsigned char buf[BLOCK];
+
+ /* Use next block as counter. */
+ encrypt_counter(st, st->counter);
+
+ /* Now shuffle pools, excluding #0 */
+ for (i = 1; i < NUM_POOLS; i++)
+ {
+ encrypt_counter(st, buf);
+ encrypt_counter(st, buf + CIPH_BLOCK);
+ md_update(&st->pool[i], buf, BLOCK);
+ }
+ memset_s(buf, sizeof(buf), 0, sizeof(buf));
+
+ /* Hide the key. */
+ rekey(st);
+
+ /* This can be done only once. */
+ st->tricks_done = 1;
+}
+
+static void
+extract_data(FState * st, unsigned count, unsigned char *dst)
+{
+ unsigned n;
+ unsigned block_nr = 0;
+ pid_t pid = getpid();
+
+ /* Should we reseed? */
+ if (st->pool0_bytes >= POOL0_FILL || st->reseed_count == 0)
+ if (enough_time_passed(st))
+ reseed(st);
+
+ /* Do some randomization on first call */
+ if (!st->tricks_done)
+ startup_tricks(st);
+
+ /* If we forked, force a reseed again */
+ if (pid != st->pid) {
+ st->pid = pid;
+ reseed(st);
+ }
+
+ while (count > 0)
+ {
+ /* produce bytes */
+ encrypt_counter(st, st->result);
+
+ /* copy result */
+ if (count > CIPH_BLOCK)
+ n = CIPH_BLOCK;
+ else
+ n = count;
+ memcpy(dst, st->result, n);
+ dst += n;
+ count -= n;
+
+ /* must not give out too many bytes with one key */
+ block_nr++;
+ if (block_nr > (RESEED_BYTES / CIPH_BLOCK))
+ {
+ rekey(st);
+ block_nr = 0;
+ }
+ }
+ /* Set new key for next request. */
+ rekey(st);
+}
+
+/*
+ * public interface
+ */
+
+static FState main_state;
+static int init_done;
+static int have_entropy;
+#define FORTUNA_RESEED_BYTE 10000
+static unsigned resend_bytes;
+
+/*
+ * This mutex protects all of the above static elements from concurrent
+ * access by multiple threads
+ */
+static HEIMDAL_MUTEX fortuna_mutex = HEIMDAL_MUTEX_INITIALIZER;
+
+/*
+ * Try our best to do an initial seed
+ */
+#define INIT_BYTES 128
+
+/*
+ * fortuna_mutex must be held across calls to this function
+ */
+
+static int
+fortuna_reseed(void)
+{
+ int entropy_p = 0;
+
+ if (!init_done)
+ abort();
+
+#ifndef NO_RAND_UNIX_METHOD
+ {
+ unsigned char buf[INIT_BYTES];
+ if ((*hc_rand_unix_method.bytes)(buf, sizeof(buf)) == 1) {
+ add_entropy(&main_state, buf, sizeof(buf));
+ entropy_p = 1;
+ memset_s(buf, sizeof(buf), 0, sizeof(buf));
+ }
+ }
+#endif
+#ifdef HAVE_ARC4RANDOM
+ {
+ uint32_t buf[INIT_BYTES / sizeof(uint32_t)];
+ int i;
+
+ for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
+ buf[i] = arc4random();
+ add_entropy(&main_state, (void *)buf, sizeof(buf));
+ entropy_p = 1;
+ }
+#endif
+ /*
+ * Fall back to gattering data from timer and secret files, this
+ * is really the last resort.
+ */
+ if (!entropy_p) {
+ /* to save stackspace */
+ union {
+ unsigned char buf[INIT_BYTES];
+ unsigned char shad[1001];
+ } u;
+ int fd;
+
+ /* add timer info */
+ if ((*hc_rand_timer_method.bytes)(u.buf, sizeof(u.buf)) == 1)
+ add_entropy(&main_state, u.buf, sizeof(u.buf));
+ /* add /etc/shadow */
+ fd = open("/etc/shadow", O_RDONLY, 0);
+ if (fd >= 0) {
+ ssize_t n;
+ rk_cloexec(fd);
+ /* add_entropy will hash the buf */
+ while ((n = read(fd, (char *)u.shad, sizeof(u.shad))) > 0)
+ add_entropy(&main_state, u.shad, sizeof(u.shad));
+ close(fd);
+ }
+
+ memset_s(&u, sizeof(u), 0, sizeof(u));
+
+ entropy_p = 1; /* sure about this ? */
+ }
+ {
+ pid_t pid = getpid();
+ add_entropy(&main_state, (void *)&pid, sizeof(pid));
+ }
+ {
+ struct timeval tv;
+ gettimeofday(&tv, NULL);
+ add_entropy(&main_state, (void *)&tv, sizeof(tv));
+ }
+#ifdef HAVE_GETUID
+ {
+ uid_t u = getuid();
+ add_entropy(&main_state, (void *)&u, sizeof(u));
+ }
+#endif
+ return entropy_p;
+}
+
+/*
+ * fortuna_mutex must be held by callers of this function
+ */
+static int
+fortuna_init(void)
+{
+ if (!init_done)
+ {
+ init_state(&main_state);
+ init_done = 1;
+ }
+ if (!have_entropy)
+ have_entropy = fortuna_reseed();
+ return (init_done && have_entropy);
+}
+
+
+
+static void
+fortuna_seed(const void *indata, int size)
+{
+ HEIMDAL_MUTEX_lock(&fortuna_mutex);
+
+ fortuna_init();
+ add_entropy(&main_state, indata, size);
+ if (size >= INIT_BYTES)
+ have_entropy = 1;
+
+ HEIMDAL_MUTEX_unlock(&fortuna_mutex);
+}
+
+static int
+fortuna_bytes(unsigned char *outdata, int size)
+{
+ int ret = 0;
+
+ HEIMDAL_MUTEX_lock(&fortuna_mutex);
+
+ if (!fortuna_init())
+ goto out;
+
+ resend_bytes += size;
+ if (resend_bytes > FORTUNA_RESEED_BYTE || resend_bytes < size) {
+ resend_bytes = 0;
+ fortuna_reseed();
+ }
+ extract_data(&main_state, size, outdata);
+ ret = 1;
+
+out:
+ HEIMDAL_MUTEX_unlock(&fortuna_mutex);
+
+ return ret;
+}
+
+static void
+fortuna_cleanup(void)
+{
+ HEIMDAL_MUTEX_lock(&fortuna_mutex);
+
+ init_done = 0;
+ have_entropy = 0;
+ memset_s(&main_state, sizeof(main_state), 0, sizeof(main_state));
+
+ HEIMDAL_MUTEX_unlock(&fortuna_mutex);
+}
+
+static void
+fortuna_add(const void *indata, int size, double entropi)
+{
+ fortuna_seed(indata, size);
+}
+
+static int
+fortuna_pseudorand(unsigned char *outdata, int size)
+{
+ return fortuna_bytes(outdata, size);
+}
+
+static int
+fortuna_status(void)
+{
+ int result;
+
+ HEIMDAL_MUTEX_lock(&fortuna_mutex);
+ result = fortuna_init();
+ HEIMDAL_MUTEX_unlock(&fortuna_mutex);
+
+ return result ? 1 : 0;
+}
+
+#if defined(__GNUC__) || (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901)
+const RAND_METHOD hc_rand_fortuna_method = {
+ .seed = fortuna_seed,
+ .bytes = fortuna_bytes,
+ .cleanup = fortuna_cleanup,
+ .add = fortuna_add,
+ .pseudorand = fortuna_pseudorand,
+ .status = fortuna_status
+};
+#else
+const RAND_METHOD hc_rand_fortuna_method = {
+ fortuna_seed,
+ fortuna_bytes,
+ fortuna_cleanup,
+ fortuna_add,
+ fortuna_pseudorand,
+ fortuna_status
+};
+#endif
+
+const RAND_METHOD *
+RAND_fortuna_method(void)
+{
+ return &hc_rand_fortuna_method;
+}
diff --git a/third_party/heimdal/lib/hcrypto/rand-timer.c b/third_party/heimdal/lib/hcrypto/rand-timer.c
new file mode 100644
index 0000000..935a3a7
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rand-timer.c
@@ -0,0 +1,210 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1999, 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <rand.h>
+
+#include "randi.h"
+
+#ifndef WIN32 /* don't bother with this on windows */
+
+static volatile int counter;
+static volatile unsigned char *gdata; /* Global data */
+static volatile int igdata; /* Index into global data */
+static int gsize;
+
+static
+RETSIGTYPE
+sigALRM(int sig)
+{
+ if (igdata < gsize)
+ gdata[igdata++] ^= counter & 0xff;
+
+#ifndef HAVE_SIGACTION
+ signal(SIGALRM, sigALRM); /* Reinstall SysV signal handler */
+#endif
+ SIGRETURN(0);
+}
+
+#ifndef HAVE_SETITIMER
+static void
+pacemaker(struct timeval *tv)
+{
+ fd_set fds;
+ pid_t pid;
+ pid = getppid();
+ while(1){
+ FD_ZERO(&fds);
+ FD_SET(0, &fds);
+ select(1, &fds, NULL, NULL, tv);
+ kill(pid, SIGALRM);
+ }
+}
+#endif
+
+#ifdef HAVE_SIGACTION
+/* XXX ugly hack, should perhaps use function from roken */
+static RETSIGTYPE
+(*fake_signal(int sig, RETSIGTYPE (*f)(int)))(int)
+{
+ struct sigaction sa, osa;
+ sa.sa_handler = f;
+ sa.sa_flags = 0;
+ sigemptyset(&sa.sa_mask);
+ sigaction(sig, &sa, &osa);
+ return osa.sa_handler;
+}
+#define signal(S, F) fake_signal((S), (F))
+#endif
+
+#endif /* WIN32*/
+
+/*
+ *
+ */
+
+static void
+timer_seed(const void *indata, int size)
+{
+}
+
+static int
+timer_bytes(unsigned char *outdata, int size)
+{
+#ifdef WIN32
+ return 0;
+#else /* WIN32 */
+ struct itimerval tv, otv;
+ RETSIGTYPE (*osa)(int);
+ int i, j;
+#ifndef HAVE_SETITIMER
+ RETSIGTYPE (*ochld)(int);
+ pid_t pid;
+#endif
+
+ gdata = outdata;
+ gsize = size;
+ igdata = 0;
+
+ osa = signal(SIGALRM, sigALRM);
+
+ /* Start timer */
+ tv.it_value.tv_sec = 0;
+ tv.it_value.tv_usec = 10 * 1000; /* 10 ms */
+ tv.it_interval = tv.it_value;
+#ifdef HAVE_SETITIMER
+ setitimer(ITIMER_REAL, &tv, &otv);
+#else
+ ochld = signal(SIGCHLD, SIG_IGN);
+ pid = fork();
+ if(pid == -1){
+ signal(SIGCHLD, ochld != SIG_ERR ? ochld : SIG_DFL);
+ des_not_rand_data(data, size);
+ return;
+ }
+ if(pid == 0)
+ pacemaker(&tv.it_interval);
+#endif
+
+ for(i = 0; i < 4; i++) {
+ for (igdata = 0; igdata < size;) /* igdata++ in sigALRM */
+ counter++;
+ for (j = 0; j < size; j++) /* Only use 2 bits each lap */
+ gdata[j] = (gdata[j]>>2) | (gdata[j]<<6);
+ }
+#ifdef HAVE_SETITIMER
+ setitimer(ITIMER_REAL, &otv, 0);
+#else
+ kill(pid, SIGKILL);
+ while(waitpid(pid, NULL, 0) != pid);
+ signal(SIGCHLD, ochld != SIG_ERR ? ochld : SIG_DFL);
+#endif
+ signal(SIGALRM, osa != SIG_ERR ? osa : SIG_DFL);
+
+ return 1;
+#endif
+}
+
+static void
+timer_cleanup(void)
+{
+}
+
+static void
+timer_add(const void *indata, int size, double entropi)
+{
+}
+
+static int
+timer_pseudorand(unsigned char *outdata, int size)
+{
+ return timer_bytes(outdata, size);
+}
+
+static int
+timer_status(void)
+{
+#ifdef WIN32
+ return 0;
+#else
+ return 1;
+#endif
+}
+
+#if defined(__GNUC__) || (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901)
+const RAND_METHOD hc_rand_timer_method = {
+ .seed = timer_seed,
+ .bytes = timer_bytes,
+ .cleanup = timer_cleanup,
+ .add = timer_add,
+ .pseudorand = timer_pseudorand,
+ .status = timer_status
+};
+#else
+const RAND_METHOD hc_rand_timer_method = {
+ timer_seed,
+ timer_bytes,
+ timer_cleanup,
+ timer_add,
+ timer_pseudorand,
+ timer_status
+};
+#endif
+
+const RAND_METHOD *
+RAND_timer_method(void)
+{
+ return &hc_rand_timer_method;
+}
diff --git a/third_party/heimdal/lib/hcrypto/rand-unix.c b/third_party/heimdal/lib/hcrypto/rand-unix.c
new file mode 100644
index 0000000..2d6013e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rand-unix.c
@@ -0,0 +1,175 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <rand.h>
+#include <heim_threads.h>
+
+#include "randi.h"
+
+/*
+ * Unix /dev/random
+ */
+
+int
+_hc_unix_device_fd(int flags, const char **fn)
+{
+ static const char *rnd_devices[] = {
+ "/dev/urandom",
+ "/dev/random",
+ "/dev/srandom",
+ "/dev/arandom",
+ NULL
+ };
+ const char **p;
+
+ for(p = rnd_devices; *p; p++) {
+ int fd = open(*p, flags | O_NDELAY);
+ if(fd >= 0) {
+ if (fn)
+ *fn = *p;
+ rk_cloexec(fd);
+ return fd;
+ }
+ }
+ return -1;
+}
+
+static void
+unix_seed(const void *p, int size)
+{
+ const unsigned char *indata = p;
+ ssize_t count;
+ int fd;
+
+ if (size < 0)
+ return;
+ else if (size == 0)
+ return;
+
+ fd = _hc_unix_device_fd(O_RDONLY, NULL);
+ if (fd < 0)
+ return;
+
+ while (size > 0) {
+ count = write(fd, indata, size);
+ if (count < 0 && errno == EINTR)
+ continue;
+ else if (count <= 0) {
+ close(fd);
+ return;
+ }
+ indata += count;
+ size -= count;
+ }
+ close(fd);
+}
+
+
+static int
+unix_bytes(unsigned char *outdata, int size)
+{
+ ssize_t count;
+ int fd;
+
+ if (size < 0)
+ return 0;
+ else if (size == 0)
+ return 1;
+
+ fd = _hc_unix_device_fd(O_RDONLY, NULL);
+ if (fd < 0)
+ return 0;
+
+ while (size > 0) {
+ count = read(fd, outdata, size);
+ if (count < 0 && errno == EINTR)
+ continue;
+ else if (count <= 0) {
+ close(fd);
+ return 0;
+ }
+ outdata += count;
+ size -= count;
+ }
+ close(fd);
+
+ return 1;
+}
+
+static void
+unix_cleanup(void)
+{
+}
+
+static void
+unix_add(const void *indata, int size, double entropi)
+{
+ unix_seed(indata, size);
+}
+
+static int
+unix_pseudorand(unsigned char *outdata, int size)
+{
+ return unix_bytes(outdata, size);
+}
+
+static int
+unix_status(void)
+{
+ int fd;
+
+ fd = _hc_unix_device_fd(O_RDONLY, NULL);
+ if (fd < 0)
+ return 0;
+ close(fd);
+
+ return 1;
+}
+
+const RAND_METHOD hc_rand_unix_method = {
+ unix_seed,
+ unix_bytes,
+ unix_cleanup,
+ unix_add,
+ unix_pseudorand,
+ unix_status
+};
+
+const RAND_METHOD *
+RAND_unix_method(void)
+{
+ return &hc_rand_unix_method;
+}
diff --git a/third_party/heimdal/lib/hcrypto/rand-w32.c b/third_party/heimdal/lib/hcrypto/rand-w32.c
new file mode 100644
index 0000000..d7d91a3
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rand-w32.c
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <wincrypt.h>
+
+#include <rand.h>
+#include <heim_threads.h>
+
+#include "randi.h"
+
+volatile static HCRYPTPROV g_cryptprovider;
+
+static HCRYPTPROV
+_hc_CryptProvider(void)
+{
+ BOOL rv;
+ HCRYPTPROV cryptprovider = (HCRYPTPROV)0;
+
+ if (g_cryptprovider)
+ goto out;
+
+ rv = CryptAcquireContext(&cryptprovider, NULL,
+ MS_ENHANCED_PROV, PROV_RSA_FULL,
+ CRYPT_VERIFYCONTEXT);
+
+ if (GetLastError() == NTE_BAD_KEYSET) {
+ rv = CryptAcquireContext(&cryptprovider, NULL,
+ MS_ENHANCED_PROV, PROV_RSA_FULL,
+ CRYPT_NEWKEYSET);
+ }
+
+ if (rv) {
+ /* try the default provider */
+ rv = CryptAcquireContext(&cryptprovider, NULL, 0, PROV_RSA_FULL,
+ CRYPT_VERIFYCONTEXT);
+
+ if (GetLastError() == NTE_BAD_KEYSET) {
+ rv = CryptAcquireContext(&cryptprovider, NULL,
+ MS_ENHANCED_PROV, PROV_RSA_FULL,
+ CRYPT_NEWKEYSET);
+ }
+ }
+
+ if (rv) {
+ /* try just a default random number generator */
+ rv = CryptAcquireContext(&cryptprovider, NULL, 0, PROV_RNG,
+ CRYPT_VERIFYCONTEXT);
+ }
+
+ if (rv == 0 &&
+ InterlockedCompareExchangePointer((PVOID *) &g_cryptprovider,
+ (PVOID) cryptprovider, NULL) != 0) {
+
+ CryptReleaseContext(cryptprovider, 0);
+ }
+
+out:
+ return g_cryptprovider;
+}
+
+/*
+ *
+ */
+
+
+static void
+w32crypto_seed(const void *indata, int size)
+{
+}
+
+
+static int
+w32crypto_bytes(unsigned char *outdata, int size)
+{
+ if (CryptGenRandom(_hc_CryptProvider(), size, outdata))
+ return 1;
+ return 0;
+}
+
+static void
+w32crypto_cleanup(void)
+{
+ HCRYPTPROV cryptprovider;
+
+ if (InterlockedCompareExchangePointer((PVOID *) &cryptprovider,
+ 0, (PVOID) g_cryptprovider) == 0) {
+ CryptReleaseContext(cryptprovider, 0);
+ }
+}
+
+static void
+w32crypto_add(const void *indata, int size, double entropi)
+{
+}
+
+static int
+w32crypto_status(void)
+{
+ if (_hc_CryptProvider() == 0)
+ return 0;
+ return 1;
+}
+
+const RAND_METHOD hc_rand_w32crypto_method = {
+ w32crypto_seed,
+ w32crypto_bytes,
+ w32crypto_cleanup,
+ w32crypto_add,
+ w32crypto_bytes,
+ w32crypto_status
+};
+
+const RAND_METHOD *
+RAND_w32crypto_method(void)
+{
+ return &hc_rand_w32crypto_method;
+}
diff --git a/third_party/heimdal/lib/hcrypto/rand.c b/third_party/heimdal/lib/hcrypto/rand.c
new file mode 100644
index 0000000..893d5c6
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rand.c
@@ -0,0 +1,402 @@
+/*
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <rand.h>
+#include <randi.h>
+
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+
+#ifdef _WIN32
+#include<shlobj.h>
+#endif
+
+/**
+ * @page page_rand RAND - random number
+ *
+ * See the library functions here: @ref hcrypto_rand
+ */
+
+static const RAND_METHOD *selected_meth = NULL;
+static ENGINE *selected_engine = NULL;
+
+static void
+init_method(void)
+{
+ if (selected_meth != NULL)
+ return;
+#if defined(_WIN32)
+ selected_meth = &hc_rand_w32crypto_method;
+#elif defined(__APPLE__)
+ selected_meth = &hc_rand_unix_method;
+#else
+ selected_meth = &hc_rand_fortuna_method;
+#endif
+}
+
+/**
+ * Seed that random number generator. Secret material can securely be
+ * feed into the function, they will never be returned.
+ *
+ * @param indata seed data
+ * @param size length seed data
+ *
+ * @ingroup hcrypto_rand
+ */
+
+void
+RAND_seed(const void *indata, size_t size)
+{
+ init_method();
+ (*selected_meth->seed)(indata, size);
+}
+
+/**
+ * Get a random block from the random generator, can be used for key material.
+ *
+ * @param outdata random data
+ * @param size length random data
+ *
+ * @return 1 on success, 0 on failure.
+ *
+ * @ingroup hcrypto_rand
+ */
+int
+RAND_bytes(void *outdata, size_t size)
+{
+ if (size == 0)
+ return 1;
+ init_method();
+ return (*selected_meth->bytes)(outdata, size);
+}
+
+/**
+ * Reset and free memory used by the random generator.
+ *
+ * @ingroup hcrypto_rand
+ */
+
+void
+RAND_cleanup(void)
+{
+ const RAND_METHOD *meth = selected_meth;
+ ENGINE *engine = selected_engine;
+
+ selected_meth = NULL;
+ selected_engine = NULL;
+
+ if (meth)
+ (*meth->cleanup)();
+ if (engine)
+ ENGINE_finish(engine);
+}
+
+/**
+ * Seed that random number generator. Secret material can securely be
+ * feed into the function, they will never be returned.
+ *
+ * @param indata the input data.
+ * @param size size of in data.
+ * @param entropi entropi in data.
+ *
+ *
+ * @ingroup hcrypto_rand
+ */
+
+void
+RAND_add(const void *indata, size_t size, double entropi)
+{
+ init_method();
+ (*selected_meth->add)(indata, size, entropi);
+}
+
+/**
+ * Get a random block from the random generator, should NOT be used for key material.
+ *
+ * @param outdata random data
+ * @param size length random data
+ *
+ * @return 1 on success, 0 on failure.
+ *
+ * @ingroup hcrypto_rand
+ */
+
+int
+RAND_pseudo_bytes(void *outdata, size_t size)
+{
+ init_method();
+ return (*selected_meth->pseudorand)(outdata, size);
+}
+
+/**
+ * Return status of the random generator
+ *
+ * @return 1 if the random generator can deliver random data.
+ *
+ * @ingroup hcrypto_rand
+ */
+
+int
+RAND_status(void)
+{
+ init_method();
+ return (*selected_meth->status)();
+}
+
+/**
+ * Set the default random method.
+ *
+ * @param meth set the new default method.
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_rand
+ */
+
+int
+RAND_set_rand_method(const RAND_METHOD *meth)
+{
+ const RAND_METHOD *old = selected_meth;
+ selected_meth = meth;
+ if (old)
+ (*old->cleanup)();
+ if (selected_engine) {
+ ENGINE_finish(selected_engine);
+ selected_engine = NULL;
+ }
+ return 1;
+}
+
+/**
+ * Get the default random method.
+ *
+ * @return Returns a RAND_METHOD
+ *
+ * @ingroup hcrypto_rand
+ */
+
+const RAND_METHOD *
+RAND_get_rand_method(void)
+{
+ init_method();
+ return selected_meth;
+}
+
+/**
+ * Set the default random method from engine.
+ *
+ * @param engine use engine, if NULL is passed it, old method and engine is cleared.
+ *
+ * @return 1 on success, 0 on failure.
+ *
+ * @ingroup hcrypto_rand
+ */
+
+int
+RAND_set_rand_engine(ENGINE *engine)
+{
+ const RAND_METHOD *meth, *old = selected_meth;
+
+ if (engine) {
+ ENGINE_up_ref(engine);
+ meth = ENGINE_get_RAND(engine);
+ if (meth == NULL) {
+ ENGINE_finish(engine);
+ return 0;
+ }
+ } else {
+ meth = NULL;
+ }
+
+ if (old)
+ (*old->cleanup)();
+
+ if (selected_engine)
+ ENGINE_finish(selected_engine);
+
+ selected_engine = engine;
+ selected_meth = meth;
+
+ return 1;
+}
+
+#define RAND_FILE_SIZE 1024
+
+/**
+ * Load a a file and feed it into RAND_seed().
+ *
+ * @param filename name of file to read.
+ * @param size minimum size to read.
+ *
+ * @return Returns the number of seed bytes loaded (0 indicates failure)
+ *
+ * @ingroup hcrypto_rand
+ */
+
+int
+RAND_load_file(const char *filename, size_t size)
+{
+ unsigned char buf[128];
+ size_t len;
+ ssize_t slen;
+ int fd;
+
+ fd = open(filename, O_RDONLY | O_BINARY, 0600);
+ if (fd < 0)
+ return 0;
+ rk_cloexec(fd);
+ len = 0;
+ while(len < size) {
+ slen = read(fd, buf, sizeof(buf));
+ if (slen <= 0)
+ break;
+ RAND_seed(buf, slen);
+ len += slen;
+ }
+ close(fd);
+
+ return len ? 1 : 0;
+}
+
+/**
+ * Write of random numbers to a file to store for later initiation with RAND_load_file().
+ *
+ * @param filename name of file to write.
+ *
+ * @return 1 on success and non-one on failure.
+ * @ingroup hcrypto_rand
+ */
+
+int
+RAND_write_file(const char *filename)
+{
+ unsigned char buf[128];
+ size_t len;
+ int res = 0, fd;
+
+ fd = open(filename, O_WRONLY | O_CREAT | O_BINARY, 0600);
+ if (fd < 0)
+ return 0;
+ rk_cloexec(fd);
+
+ len = 0;
+ while(len < RAND_FILE_SIZE) {
+ res = RAND_bytes(buf, sizeof(buf));
+ if (res != 1)
+ break;
+ if (write(fd, buf, sizeof(buf)) != sizeof(buf)) {
+ res = 0;
+ break;
+ }
+ len += sizeof(buf);
+ }
+
+ close(fd);
+
+ return res;
+}
+
+/**
+ * Return the default random state filename for a user to use for
+ * RAND_load_file(), and RAND_write_file().
+ *
+ * @param filename buffer to hold file name.
+ * @param size size of buffer filename.
+ *
+ * @return the buffer filename or NULL on failure.
+ *
+ * @ingroup hcrypto_rand
+ */
+
+const char *
+RAND_file_name(char *filename, size_t size)
+{
+ const char *e = NULL;
+ int pathp = 0, ret;
+
+ e = secure_getenv("RANDFILE");
+ if (e == NULL)
+ e = secure_getenv("HOME");
+ if (e)
+ pathp = 1;
+
+#ifndef _WIN32
+ /*
+ * Here we really want to call getpwuid(getuid()) but this will
+ * cause recursive lookups if the nss library uses
+ * gssapi/krb5/hcrypto to authenticate to the ldap servers.
+ *
+ * So at least return the unix /dev/random if we have one
+ */
+ if (e == NULL) {
+ int fd;
+
+ fd = _hc_unix_device_fd(O_RDONLY, &e);
+ if (fd >= 0)
+ close(fd);
+ }
+#else /* Win32 */
+
+ if (e == NULL) {
+ char profile[MAX_PATH];
+
+ if (SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL,
+ SHGFP_TYPE_CURRENT, profile) == S_OK) {
+ ret = snprintf(filename, size, "%s\\.rnd", profile);
+
+ if (ret > 0 && ret < size)
+ return filename;
+ }
+ }
+
+#endif
+
+ if (e == NULL)
+ return NULL;
+
+ if (pathp)
+ ret = snprintf(filename, size, "%s/.rnd", e);
+ else
+ ret = snprintf(filename, size, "%s", e);
+
+ if (ret <= 0 || ret >= size)
+ return NULL;
+
+ return filename;
+}
diff --git a/third_party/heimdal/lib/hcrypto/rand.h b/third_party/heimdal/lib/hcrypto/rand.h
new file mode 100644
index 0000000..1955c44
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rand.h
@@ -0,0 +1,106 @@
+
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef _HEIM_RAND_H
+#define _HEIM_RAND_H 1
+
+#define RAND_METHOD hc_RAND_METHOD
+
+typedef struct RAND_METHOD RAND_METHOD;
+
+#include <hcrypto/engine.h>
+
+/* symbol renaming */
+#define RAND_bytes hc_RAND_bytes
+#define RAND_pseudo_bytes hc_RAND_pseudo_bytes
+#define RAND_seed hc_RAND_seed
+#define RAND_cleanup hc_RAND_cleanup
+#define RAND_add hc_RAND_add
+#define RAND_set_rand_method hc_RAND_set_rand_method
+#define RAND_get_rand_method hc_RAND_get_rand_method
+#define RAND_set_rand_engine hc_RAND_set_rand_engine
+#define RAND_file_name hc_RAND_file_name
+#define RAND_load_file hc_RAND_load_file
+#define RAND_write_file hc_RAND_write_file
+#define RAND_status hc_RAND_status
+#define RAND_fortuna_method hc_RAND_fortuna_method
+#define RAND_timer_method hc_RAND_timer_method
+#define RAND_unix_method hc_RAND_unix_method
+#define RAND_w32crypto_method hc_RAND_w32crypto_method
+
+/*
+ *
+ */
+
+struct RAND_METHOD
+{
+ void (*seed)(const void *, int);
+ int (*bytes)(unsigned char *, int);
+ void (*cleanup)(void);
+ void (*add)(const void *, int, double);
+ int (*pseudorand)(unsigned char *, int);
+ int (*status)(void);
+};
+
+/*
+ *
+ */
+
+int RAND_bytes(void *, size_t num);
+int RAND_pseudo_bytes(void *, size_t);
+void RAND_seed(const void *, size_t);
+void RAND_cleanup(void);
+void RAND_add(const void *, size_t, double);
+
+int RAND_set_rand_method(const RAND_METHOD *);
+const RAND_METHOD *
+ RAND_get_rand_method(void);
+int RAND_set_rand_engine(ENGINE *);
+
+const char *
+ RAND_file_name(char *, size_t);
+int RAND_load_file(const char *, size_t);
+int RAND_write_file(const char *);
+int RAND_status(void);
+
+
+const RAND_METHOD * RAND_fortuna_method(void);
+const RAND_METHOD * RAND_unix_method(void);
+const RAND_METHOD * RAND_w32crypto_method(void);
+
+#endif /* _HEIM_RAND_H */
diff --git a/third_party/heimdal/lib/hcrypto/randi.h b/third_party/heimdal/lib/hcrypto/randi.h
new file mode 100644
index 0000000..85d5d66
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/randi.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef _HEIM_RANDI_H
+#define _HEIM_RANDI_H 1
+
+extern const RAND_METHOD hc_rand_fortuna_method;
+extern const RAND_METHOD hc_rand_unix_method;
+extern const RAND_METHOD hc_rand_timer_method;
+extern const RAND_METHOD hc_rand_w32crypto_method;
+
+const RAND_METHOD * RAND_timer_method(void);
+int _hc_unix_device_fd(int, const char **);
+
+#endif /* _HEIM_RANDI_H */
diff --git a/third_party/heimdal/lib/hcrypto/rc2.c b/third_party/heimdal/lib/hcrypto/rc2.c
new file mode 100644
index 0000000..02b684c
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rc2.c
@@ -0,0 +1,240 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include "rc2.h"
+
+/*
+ * Implemented from Peter Gutmann's "Specification for Ron Rivests Cipher No.2"
+ * rfc2268 and "On the Design and Security of RC2" was also useful.
+ */
+
+static unsigned int Sbox[256] = {
+ 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed,
+ 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,
+ 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e,
+ 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,
+ 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13,
+ 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,
+ 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b,
+ 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,
+ 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c,
+ 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc,
+ 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1,
+ 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26,
+ 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57,
+ 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03,
+ 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7,
+ 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7,
+ 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7,
+ 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a,
+ 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74,
+ 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec,
+ 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc,
+ 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39,
+ 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a,
+ 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31,
+ 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae,
+ 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,
+ 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c,
+ 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,
+ 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0,
+ 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,
+ 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77,
+ 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad
+};
+
+void
+RC2_set_key(RC2_KEY *key, int len, const unsigned char *data, int bits)
+{
+ unsigned char k[128];
+ int j, T8, TM;
+
+ if (len <= 0)
+ abort();
+ if (len > 128)
+ len = 128;
+ if (bits <= 0 || bits > 1024)
+ bits = 1024;
+
+ for (j = 0; j < len; j++)
+ k[j] = data[j];
+ for (; j < 128; j++)
+ k[j] = Sbox[(k[j - len] + k[j - 1]) & 0xff];
+
+ T8 = (bits + 7) / 8;
+ j = (8*T8 - bits);
+ TM = 0xff >> j;
+
+ k[128 - T8] = Sbox[k[128 - T8] & TM];
+
+ for (j = 127 - T8; j >= 0; j--)
+ k[j] = Sbox[k[j + 1] ^ k[j + T8]];
+
+ for (j = 0; j < 64; j++)
+ key->data[j] = k[(j * 2) + 0] | (k[(j * 2) + 1] << 8);
+ memset(k, 0, sizeof(k));
+}
+
+#define ROT16L(w,n) ((w<<n)|(w>>(16-n)))
+#define ROT16R(w,n) ((w>>n)|(w<<(16-n)))
+
+void
+RC2_encryptc(unsigned char *in, unsigned char *out, const RC2_KEY *key)
+{
+ int i, j;
+ int w0, w1, w2, w3;
+ int t0, t1, t2, t3;
+
+ w0 = in[0] | (in[1] << 8);
+ w1 = in[2] | (in[3] << 8);
+ w2 = in[4] | (in[5] << 8);
+ w3 = in[6] | (in[7] << 8);
+
+ for (i = 0; i < 16; i++) {
+ j = i * 4;
+ t0 = (w0 + (w1 & ~w3) + (w2 & w3) + key->data[j + 0]) & 0xffff;
+ w0 = ROT16L(t0, 1);
+ t1 = (w1 + (w2 & ~w0) + (w3 & w0) + key->data[j + 1]) & 0xffff;
+ w1 = ROT16L(t1, 2);
+ t2 = (w2 + (w3 & ~w1) + (w0 & w1) + key->data[j + 2]) & 0xffff;
+ w2 = ROT16L(t2, 3);
+ t3 = (w3 + (w0 & ~w2) + (w1 & w2) + key->data[j + 3]) & 0xffff;
+ w3 = ROT16L(t3, 5);
+ if(i == 4 || i == 10) {
+ w0 += key->data[w3 & 63];
+ w1 += key->data[w0 & 63];
+ w2 += key->data[w1 & 63];
+ w3 += key->data[w2 & 63];
+ }
+ }
+
+ out[0] = w0 & 0xff;
+ out[1] = (w0 >> 8) & 0xff;
+ out[2] = w1 & 0xff;
+ out[3] = (w1 >> 8) & 0xff;
+ out[4] = w2 & 0xff;
+ out[5] = (w2 >> 8) & 0xff;
+ out[6] = w3 & 0xff;
+ out[7] = (w3 >> 8) & 0xff;
+}
+
+void
+RC2_decryptc(unsigned char *in, unsigned char *out, const RC2_KEY *key)
+{
+ int i, j;
+ int w0, w1, w2, w3;
+ int t0, t1, t2, t3;
+
+ w0 = in[0] | (in[1] << 8);
+ w1 = in[2] | (in[3] << 8);
+ w2 = in[4] | (in[5] << 8);
+ w3 = in[6] | (in[7] << 8);
+
+ for (i = 15; i >= 0; i--) {
+ j = i * 4;
+
+ if(i == 4 || i == 10) {
+ w3 = (w3 - key->data[w2 & 63]) & 0xffff;
+ w2 = (w2 - key->data[w1 & 63]) & 0xffff;
+ w1 = (w1 - key->data[w0 & 63]) & 0xffff;
+ w0 = (w0 - key->data[w3 & 63]) & 0xffff;
+ }
+
+ t3 = ROT16R(w3, 5);
+ w3 = (t3 - (w0 & ~w2) - (w1 & w2) - key->data[j + 3]) & 0xffff;
+ t2 = ROT16R(w2, 3);
+ w2 = (t2 - (w3 & ~w1) - (w0 & w1) - key->data[j + 2]) & 0xffff;
+ t1 = ROT16R(w1, 2);
+ w1 = (t1 - (w2 & ~w0) - (w3 & w0) - key->data[j + 1]) & 0xffff;
+ t0 = ROT16R(w0, 1);
+ w0 = (t0 - (w1 & ~w3) - (w2 & w3) - key->data[j + 0]) & 0xffff;
+
+ }
+ out[0] = w0 & 0xff;
+ out[1] = (w0 >> 8) & 0xff;
+ out[2] = w1 & 0xff;
+ out[3] = (w1 >> 8) & 0xff;
+ out[4] = w2 & 0xff;
+ out[5] = (w2 >> 8) & 0xff;
+ out[6] = w3 & 0xff;
+ out[7] = (w3 >> 8) & 0xff;
+}
+
+void
+RC2_cbc_encrypt(const unsigned char *in, unsigned char *out, long size,
+ RC2_KEY *key, unsigned char *iv, int forward_encrypt)
+{
+ unsigned char tmp[RC2_BLOCK_SIZE];
+ int i;
+
+ if (forward_encrypt) {
+ while (size >= RC2_BLOCK_SIZE) {
+ for (i = 0; i < RC2_BLOCK_SIZE; i++)
+ tmp[i] = in[i] ^ iv[i];
+ RC2_encryptc(tmp, out, key);
+ memcpy(iv, out, RC2_BLOCK_SIZE);
+ size -= RC2_BLOCK_SIZE;
+ in += RC2_BLOCK_SIZE;
+ out += RC2_BLOCK_SIZE;
+ }
+ if (size) {
+ for (i = 0; i < size; i++)
+ tmp[i] = in[i] ^ iv[i];
+ for (i = size; i < RC2_BLOCK_SIZE; i++)
+ tmp[i] = iv[i];
+ RC2_encryptc(tmp, out, key);
+ memcpy(iv, out, RC2_BLOCK_SIZE);
+ }
+ } else {
+ while (size >= RC2_BLOCK_SIZE) {
+ memcpy(tmp, in, RC2_BLOCK_SIZE);
+ RC2_decryptc(tmp, out, key);
+ for (i = 0; i < RC2_BLOCK_SIZE; i++)
+ out[i] ^= iv[i];
+ memcpy(iv, tmp, RC2_BLOCK_SIZE);
+ size -= RC2_BLOCK_SIZE;
+ in += RC2_BLOCK_SIZE;
+ out += RC2_BLOCK_SIZE;
+ }
+ if (size) {
+ memcpy(tmp, in, RC2_BLOCK_SIZE);
+ RC2_decryptc(tmp, out, key);
+ for (i = 0; i < size; i++)
+ out[i] ^= iv[i];
+ memcpy(iv, tmp, RC2_BLOCK_SIZE);
+ }
+ }
+}
diff --git a/third_party/heimdal/lib/hcrypto/rc2.h b/third_party/heimdal/lib/hcrypto/rc2.h
new file mode 100644
index 0000000..5e479fb
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rc2.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+/* symbol renaming */
+#define RC2_set_key hc_RC2_set_key
+#define RC2_encryptc hc_RC2_encryptc
+#define RC2_decryptc hc_RC2_decryptc
+#define RC2_cbc_encrypt hc_RC2_cbc_encrypt
+
+/*
+ *
+ */
+
+#define RC2_ENCRYPT 1
+#define RC2_DECRYPT 0
+
+#define RC2_BLOCK_SIZE 8
+#define RC2_BLOCK RC2_BLOCK_SIZE
+#define RC2_KEY_LENGTH 16
+
+typedef struct rc2_key {
+ unsigned int data[64];
+} RC2_KEY;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void RC2_set_key(RC2_KEY *, int, const unsigned char *,int);
+
+void RC2_encryptc(unsigned char *, unsigned char *, const RC2_KEY *);
+void RC2_decryptc(unsigned char *, unsigned char *, const RC2_KEY *);
+
+void RC2_cbc_encrypt(const unsigned char *, unsigned char *, long,
+ RC2_KEY *, unsigned char *, int);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/rc2test.c b/third_party/heimdal/lib/hcrypto/rc2test.c
new file mode 100644
index 0000000..553bed3
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rc2test.c
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <rc2.h>
+
+struct {
+ const void *key;
+ const int keylen;
+ const int bitsize;
+ const void *plain;
+ const void *cipher;
+} tests[] = {
+ {
+ "\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ 0,
+ "\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\x1C\x19\x8A\x83\x8D\xF0\x28\xB7"
+ },
+ {
+ "\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x01",
+ 16,
+ 0,
+ "\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\x21\x82\x9C\x78\xA9\xF9\xC0\x74"
+ },
+ {
+ "\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ 0,
+ "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF",
+ "\x13\xDB\x35\x17\xD3\x21\x86\x9E"
+ },
+ {
+ "\x00\x01\x02\x03\x04\x05\x06\x07"
+ "\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F",
+ 16,
+ 0,
+ "\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\x50\xDC\x01\x62\xBD\x75\x7F\x31"
+ },
+ {
+ "\x00\x00\x00\x00\x00\x00\x00\x00",
+ 8,
+ 63,
+ "\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\xeb\xb7\x73\xf9\x93\x27\x8e\xff"
+ },
+ {
+ "\xff\xff\xff\xff\xff\xff\xff\xff",
+ 8,
+ 64,
+ "\xff\xff\xff\xff\xff\xff\xff\xff",
+ "\x27\x8b\x27\xe4\x2e\x2f\x0d\x49"
+ },
+ {
+ "\x88",
+ 1,
+ 64,
+ "\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\x61\xa8\xa2\x44\xad\xac\xcc\xf0"
+ }
+};
+
+const unsigned char cbc_key[16] =
+"\x00\x00\x00\x00\x00\x00\x00\x00"
+"\x00\x00\x00\x00\x00\x00\x00\x00";
+const char cbc_iv[8] =
+"\x01\x01\x01\x01\x01\x01\x01\x01";
+const unsigned char cbc_in_data[32] =
+"\x20\x20\x20\x20\x20\x20\x20\x20"
+"\x20\x20\x20\x20\x20\x20\x20\x20"
+"\x20\x20\x20\x20\x20\x20\x20\x20"
+"\x20\x20\x20\x20\x20\x20\x20\x20";
+
+const char out_iv[8] = "\x00\x78\x1b\x6\xff\xb9\xfa\xe";
+
+const char cbc_out_data[32] =
+"\xb4\x3f\x89\x15\x69\x68\xda\x79"
+"\x29\xab\x5f\x78\xc5\xba\x15\x82"
+"\x80\x89\x57\x1b\xbe\x57\x2f\xdc"
+"\x00\x78\x1b\x06\xff\xb9\xfa\x0e";
+
+int
+main(int argc, char **argv)
+{
+ RC2_KEY key;
+ unsigned char t[8];
+ unsigned char out[40];
+ int i;
+
+ for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
+ RC2_set_key(&key, tests[i].keylen, tests[i].key, tests[i].bitsize);
+
+ memcpy(t, tests[i].plain, 8);
+ RC2_encryptc(t, t, &key);
+ if (memcmp(t, tests[i].cipher, 8) != 0) {
+ printf("encrypt %d\n", i);
+ exit(1);
+ }
+ RC2_decryptc(t, t, &key);
+ if (memcmp(t, tests[i].plain, 8) != 0) {
+ printf("decrypt: %d\n", i);
+ exit(1);
+ }
+ }
+
+ /* cbc test */
+
+ RC2_set_key(&key, 16, cbc_key, 0);
+ memcpy(t, cbc_iv, 8);
+ RC2_cbc_encrypt(cbc_in_data, out, 32, &key, t, 1);
+
+ if (memcmp(out_iv, t, 8) != 0)
+ abort();
+
+ if (memcmp(out, cbc_out_data, 32) != 0) {
+ printf("cbc test encrypt\n");
+ exit(1);
+ }
+
+ memcpy(t, cbc_iv, 8);
+ RC2_cbc_encrypt(out, out, 32, &key, t, 0);
+
+ if (memcmp(cbc_in_data, out, 32) != 0) {
+ printf("cbc test decrypt \n");
+ exit(1);
+ }
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hcrypto/rc4.c b/third_party/heimdal/lib/hcrypto/rc4.c
new file mode 100644
index 0000000..cc7882d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rc4.c
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* implemented from description in draft-kaukonen-cipher-arcfour-03.txt */
+
+#include <config.h>
+#include <roken.h>
+
+#include <rc4.h>
+
+#define SWAP(k,x,y) \
+{ unsigned int _t; \
+ _t = k->state[x]; \
+ k->state[x] = k->state[y]; \
+ k->state[y] = _t; \
+}
+
+void
+RC4_set_key(RC4_KEY *key, const int len, const unsigned char *data)
+{
+ int i, j;
+
+ for (i = 0; i < 256; i++)
+ key->state[i] = i;
+ for (i = 0, j = 0; i < 256; i++) {
+ j = (j + key->state[i] + data[i % len]) % 256;
+ SWAP(key, i, j);
+ }
+ key->x = key->y = 0;
+}
+
+void
+RC4(RC4_KEY *key, const int len, const unsigned char *in, unsigned char *out)
+{
+ int i, t;
+ unsigned x, y;
+
+ x = key->x;
+ y = key->y;
+ for (i = 0; i < len; i++) {
+ x = (x + 1) % 256;
+ y = (y + key->state[x]) % 256;
+ SWAP(key, x, y);
+ t = (key->state[x] + key->state[y]) % 256;
+ *out++ = key->state[t] ^ *in++;
+ }
+ key->x = x;
+ key->y = y;
+}
diff --git a/third_party/heimdal/lib/hcrypto/rc4.h b/third_party/heimdal/lib/hcrypto/rc4.h
new file mode 100644
index 0000000..f93482f
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rc4.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+/* symbol renaming */
+#define RC4_set_key hc_RC4_set_key
+#define RC4 hc_RC4
+
+typedef struct rc4_key {
+ unsigned int x, y;
+ unsigned int state[256];
+} RC4_KEY;
+
+void RC4_set_key(RC4_KEY *, const int, const unsigned char *);
+void RC4(RC4_KEY *, const int, const unsigned char *, unsigned char *);
diff --git a/third_party/heimdal/lib/hcrypto/rctest.c b/third_party/heimdal/lib/hcrypto/rctest.c
new file mode 100644
index 0000000..031d8cd
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rctest.c
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+#include <rc4.h>
+
+static unsigned char plain1[8] =
+ { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+static unsigned char key1[8] =
+ { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };
+static unsigned char cipher1[8] =
+ { 0x74, 0x94, 0xC2, 0xE7, 0x10, 0x4B, 0x08, 0x79 };
+
+static unsigned char plain2[5] =
+ { 0xdc, 0xee, 0x4c, 0xf9, 0x2c };
+static unsigned char key2[5] =
+ { 0x61, 0x8a, 0x63, 0xd2, 0xfb };
+static unsigned char cipher2[5] =
+ { 0xf1, 0x38, 0x29, 0xc9, 0xde };
+
+static unsigned char plain3[] =
+ {
+ 0x52, 0x75, 0x69, 0x73, 0x6c, 0x69, 0x6e, 0x6e,
+ 0x75, 0x6e, 0x20, 0x6c, 0x61, 0x75, 0x6c, 0x75,
+ 0x20, 0x6b, 0x6f, 0x72, 0x76, 0x69, 0x73, 0x73,
+ 0x73, 0x61, 0x6e, 0x69, 0x2c, 0x20, 0x74, 0xe4,
+ 0x68, 0x6b, 0xe4, 0x70, 0xe4, 0x69, 0x64, 0x65,
+ 0x6e, 0x20, 0x70, 0xe4, 0xe4, 0x6c, 0x6c, 0xe4,
+ 0x20, 0x74, 0xe4, 0x79, 0x73, 0x69, 0x6b, 0x75,
+ 0x75, 0x2e, 0x20, 0x4b, 0x65, 0x73, 0xe4, 0x79,
+ 0xf6, 0x6e, 0x20, 0x6f, 0x6e, 0x20, 0x6f, 0x6e,
+ 0x6e, 0x69, 0x20, 0x6f, 0x6d, 0x61, 0x6e, 0x61,
+ 0x6e, 0x69, 0x2c, 0x20, 0x6b, 0x61, 0x73, 0x6b,
+ 0x69, 0x73, 0x61, 0x76, 0x75, 0x75, 0x6e, 0x20,
+ 0x6c, 0x61, 0x61, 0x6b, 0x73, 0x6f, 0x74, 0x20,
+ 0x76, 0x65, 0x72, 0x68, 0x6f, 0x75, 0x75, 0x2e,
+ 0x20, 0x45, 0x6e, 0x20, 0x6d, 0x61, 0x20, 0x69,
+ 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x65, 0x2c, 0x20,
+ 0x73, 0x75, 0x72, 0x65, 0x20, 0x68, 0x75, 0x6f,
+ 0x6b, 0x61, 0x61, 0x2c, 0x20, 0x6d, 0x75, 0x74,
+ 0x74, 0x61, 0x20, 0x6d, 0x65, 0x74, 0x73, 0xe4,
+ 0x6e, 0x20, 0x74, 0x75, 0x6d, 0x6d, 0x75, 0x75,
+ 0x73, 0x20, 0x6d, 0x75, 0x6c, 0x6c, 0x65, 0x20,
+ 0x74, 0x75, 0x6f, 0x6b, 0x61, 0x61, 0x2e, 0x20,
+ 0x50, 0x75, 0x75, 0x6e, 0x74, 0x6f, 0x20, 0x70,
+ 0x69, 0x6c, 0x76, 0x65, 0x6e, 0x2c, 0x20, 0x6d,
+ 0x69, 0x20, 0x68, 0x75, 0x6b, 0x6b, 0x75, 0x75,
+ 0x2c, 0x20, 0x73, 0x69, 0x69, 0x6e, 0x74, 0x6f,
+ 0x20, 0x76, 0x61, 0x72, 0x61, 0x6e, 0x20, 0x74,
+ 0x75, 0x75, 0x6c, 0x69, 0x73, 0x65, 0x6e, 0x2c,
+ 0x20, 0x6d, 0x69, 0x20, 0x6e, 0x75, 0x6b, 0x6b,
+ 0x75, 0x75, 0x2e, 0x20, 0x54, 0x75, 0x6f, 0x6b,
+ 0x73, 0x75, 0x74, 0x20, 0x76, 0x61, 0x6e, 0x61,
+ 0x6d, 0x6f, 0x6e, 0x20, 0x6a, 0x61, 0x20, 0x76,
+ 0x61, 0x72, 0x6a, 0x6f, 0x74, 0x20, 0x76, 0x65,
+ 0x65, 0x6e, 0x2c, 0x20, 0x6e, 0x69, 0x69, 0x73,
+ 0x74, 0xe4, 0x20, 0x73, 0x79, 0x64, 0xe4, 0x6d,
+ 0x65, 0x6e, 0x69, 0x20, 0x6c, 0x61, 0x75, 0x6c,
+ 0x75, 0x6e, 0x20, 0x74, 0x65, 0x65, 0x6e, 0x2e,
+ 0x20, 0x2d, 0x20, 0x45, 0x69, 0x6e, 0x6f, 0x20,
+ 0x4c, 0x65, 0x69, 0x6e, 0x6f };
+
+static unsigned char key3[16] =
+ { 0x29, 0x04, 0x19, 0x72, 0xfb, 0x42, 0xba, 0x5f,
+ 0xc7, 0x12, 0x77, 0x12, 0xf1, 0x38, 0x29, 0xc9 };
+
+const unsigned char cipher3[] =
+ { 0x35, 0x81, 0x86, 0x99, 0x90, 0x01, 0xe6, 0xb5,
+ 0xda, 0xf0, 0x5e, 0xce, 0xeb, 0x7e, 0xee, 0x21,
+ 0xe0, 0x68, 0x9c, 0x1f, 0x00, 0xee, 0xa8, 0x1f,
+ 0x7d, 0xd2, 0xca, 0xae, 0xe1, 0xd2, 0x76, 0x3e,
+ 0x68, 0xaf, 0x0e, 0xad, 0x33, 0xd6, 0x6c, 0x26,
+ 0x8b, 0xc9, 0x46, 0xc4, 0x84, 0xfb, 0xe9, 0x4c,
+ 0x5f, 0x5e, 0x0b, 0x86, 0xa5, 0x92, 0x79, 0xe4,
+ 0xf8, 0x24, 0xe7, 0xa6, 0x40, 0xbd, 0x22, 0x32,
+ 0x10, 0xb0, 0xa6, 0x11, 0x60, 0xb7, 0xbc, 0xe9,
+ 0x86, 0xea, 0x65, 0x68, 0x80, 0x03, 0x59, 0x6b,
+ 0x63, 0x0a, 0x6b, 0x90, 0xf8, 0xe0, 0xca, 0xf6,
+ 0x91, 0x2a, 0x98, 0xeb, 0x87, 0x21, 0x76, 0xe8,
+ 0x3c, 0x20, 0x2c, 0xaa, 0x64, 0x16, 0x6d, 0x2c,
+ 0xce, 0x57, 0xff, 0x1b, 0xca, 0x57, 0xb2, 0x13,
+ 0xf0, 0xed, 0x1a, 0xa7, 0x2f, 0xb8, 0xea, 0x52,
+ 0xb0, 0xbe, 0x01, 0xcd, 0x1e, 0x41, 0x28, 0x67,
+ 0x72, 0x0b, 0x32, 0x6e, 0xb3, 0x89, 0xd0, 0x11,
+ 0xbd, 0x70, 0xd8, 0xaf, 0x03, 0x5f, 0xb0, 0xd8,
+ 0x58, 0x9d, 0xbc, 0xe3, 0xc6, 0x66, 0xf5, 0xea,
+ 0x8d, 0x4c, 0x79, 0x54, 0xc5, 0x0c, 0x3f, 0x34,
+ 0x0b, 0x04, 0x67, 0xf8, 0x1b, 0x42, 0x59, 0x61,
+ 0xc1, 0x18, 0x43, 0x07, 0x4d, 0xf6, 0x20, 0xf2,
+ 0x08, 0x40, 0x4b, 0x39, 0x4c, 0xf9, 0xd3, 0x7f,
+ 0xf5, 0x4b, 0x5f, 0x1a, 0xd8, 0xf6, 0xea, 0x7d,
+ 0xa3, 0xc5, 0x61, 0xdf, 0xa7, 0x28, 0x1f, 0x96,
+ 0x44, 0x63, 0xd2, 0xcc, 0x35, 0xa4, 0xd1, 0xb0,
+ 0x34, 0x90, 0xde, 0xc5, 0x1b, 0x07, 0x11, 0xfb,
+ 0xd6, 0xf5, 0x5f, 0x79, 0x23, 0x4d, 0x5b, 0x7c,
+ 0x76, 0x66, 0x22, 0xa6, 0x6d, 0xe9, 0x2b, 0xe9,
+ 0x96, 0x46, 0x1d, 0x5e, 0x4d, 0xc8, 0x78, 0xef,
+ 0x9b, 0xca, 0x03, 0x05, 0x21, 0xe8, 0x35, 0x1e,
+ 0x4b, 0xae, 0xd2, 0xfd, 0x04, 0xf9, 0x46, 0x73,
+ 0x68, 0xc4, 0xad, 0x6a, 0xc1, 0x86, 0xd0, 0x82,
+ 0x45, 0xb2, 0x63, 0xa2, 0x66, 0x6d, 0x1f, 0x6c,
+ 0x54, 0x20, 0xf1, 0x59, 0x9d, 0xfd, 0x9f, 0x43,
+ 0x89, 0x21, 0xc2, 0xf5, 0xa4, 0x63, 0x93, 0x8c,
+ 0xe0, 0x98, 0x22, 0x65, 0xee, 0xf7, 0x01, 0x79,
+ 0xbc, 0x55, 0x3f, 0x33, 0x9e, 0xb1, 0xa4, 0xc1,
+ 0xaf, 0x5f, 0x6a, 0x54, 0x7f };
+
+int
+main (void)
+{
+ unsigned char buf[1024];
+ RC4_KEY key;
+
+ RC4_set_key(&key, 8, key1);
+ RC4(&key, 8, plain1, buf);
+ if (memcmp(buf, cipher1, 8) != 0)
+ return 1;
+
+ RC4_set_key(&key, 5, key2);
+ RC4(&key, 5, plain2, buf);
+ if (memcmp(buf, cipher2, 5) != 0)
+ return 1;
+
+ RC4_set_key(&key, 16, key3);
+ RC4(&key, 309, plain3, buf);
+ if (memcmp(buf, cipher3, 309) != 0)
+ return 1;
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hcrypto/resource.h b/third_party/heimdal/lib/hcrypto/resource.h
new file mode 100644
index 0000000..9074dc1
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/resource.h
@@ -0,0 +1,18 @@
+//{{NO_DEPENDENCIES}}
+// Microsoft Developer Studio generated include file.
+// Used by passwd_dialog.rc
+//
+#define IDD_PASSWD_DIALOG 101
+#define IDC_EDIT1 1000
+#define IDC_PASSWD_EDIT 1001
+
+// Next default values for new objects
+//
+#ifdef APSTUDIO_INVOKED
+#ifndef APSTUDIO_READONLY_SYMBOLS
+#define _APS_NEXT_RESOURCE_VALUE 102
+#define _APS_NEXT_COMMAND_VALUE 40001
+#define _APS_NEXT_CONTROL_VALUE 1002
+#define _APS_NEXT_SYMED_VALUE 101
+#endif
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/rijndael-alg-fst.c b/third_party/heimdal/lib/hcrypto/rijndael-alg-fst.c
new file mode 100644
index 0000000..be05cdd
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rijndael-alg-fst.c
@@ -0,0 +1,1223 @@
+/* $NetBSD: rijndael-alg-fst.c,v 1.5 2001/11/13 01:40:10 lukem Exp $ */
+/* $KAME: rijndael-alg-fst.c,v 1.10 2003/07/15 10:47:16 itojun Exp $ */
+/**
+ * rijndael-alg-fst.c
+ *
+ * @version 3.0 (December 2000)
+ *
+ * Optimised ANSI C code for the Rijndael cipher (now AES)
+ *
+ * @author Vincent Rijmen <vincent.rijmen@esat.kuleuven.ac.be>
+ * @author Antoon Bosselaers <antoon.bosselaers@esat.kuleuven.ac.be>
+ * @author Paulo Barreto <paulo.barreto@terra.com.br>
+ *
+ * This code is hereby placed in the public domain.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* "$NetBSD: rijndael-alg-fst.c,v 1.5 2001/11/13 01:40:10 lukem Exp $" */
+
+#include <config.h>
+#include <roken.h>
+
+#ifdef KRB5
+#include <krb5-types.h>
+#endif
+
+#include "rijndael-alg-fst.h"
+
+/*
+Te0[x] = S [x].[02, 01, 01, 03];
+Te1[x] = S [x].[03, 02, 01, 01];
+Te2[x] = S [x].[01, 03, 02, 01];
+Te3[x] = S [x].[01, 01, 03, 02];
+Te4[x] = S [x].[01, 01, 01, 01];
+
+Td0[x] = Si[x].[0e, 09, 0d, 0b];
+Td1[x] = Si[x].[0b, 0e, 09, 0d];
+Td2[x] = Si[x].[0d, 0b, 0e, 09];
+Td3[x] = Si[x].[09, 0d, 0b, 0e];
+Td4[x] = Si[x].[01, 01, 01, 01];
+*/
+
+static const uint32_t Te0[256] = {
+ 0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU,
+ 0xfff2f20dU, 0xd66b6bbdU, 0xde6f6fb1U, 0x91c5c554U,
+ 0x60303050U, 0x02010103U, 0xce6767a9U, 0x562b2b7dU,
+ 0xe7fefe19U, 0xb5d7d762U, 0x4dababe6U, 0xec76769aU,
+ 0x8fcaca45U, 0x1f82829dU, 0x89c9c940U, 0xfa7d7d87U,
+ 0xeffafa15U, 0xb25959ebU, 0x8e4747c9U, 0xfbf0f00bU,
+ 0x41adadecU, 0xb3d4d467U, 0x5fa2a2fdU, 0x45afafeaU,
+ 0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU,
+ 0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU,
+ 0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU,
+ 0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U,
+ 0xe2717193U, 0xabd8d873U, 0x62313153U, 0x2a15153fU,
+ 0x0804040cU, 0x95c7c752U, 0x46232365U, 0x9dc3c35eU,
+ 0x30181828U, 0x379696a1U, 0x0a05050fU, 0x2f9a9ab5U,
+ 0x0e070709U, 0x24121236U, 0x1b80809bU, 0xdfe2e23dU,
+ 0xcdebeb26U, 0x4e272769U, 0x7fb2b2cdU, 0xea75759fU,
+ 0x1209091bU, 0x1d83839eU, 0x582c2c74U, 0x341a1a2eU,
+ 0x361b1b2dU, 0xdc6e6eb2U, 0xb45a5aeeU, 0x5ba0a0fbU,
+ 0xa45252f6U, 0x763b3b4dU, 0xb7d6d661U, 0x7db3b3ceU,
+ 0x5229297bU, 0xdde3e33eU, 0x5e2f2f71U, 0x13848497U,
+ 0xa65353f5U, 0xb9d1d168U, 0x00000000U, 0xc1eded2cU,
+ 0x40202060U, 0xe3fcfc1fU, 0x79b1b1c8U, 0xb65b5bedU,
+ 0xd46a6abeU, 0x8dcbcb46U, 0x67bebed9U, 0x7239394bU,
+ 0x944a4adeU, 0x984c4cd4U, 0xb05858e8U, 0x85cfcf4aU,
+ 0xbbd0d06bU, 0xc5efef2aU, 0x4faaaae5U, 0xedfbfb16U,
+ 0x864343c5U, 0x9a4d4dd7U, 0x66333355U, 0x11858594U,
+ 0x8a4545cfU, 0xe9f9f910U, 0x04020206U, 0xfe7f7f81U,
+ 0xa05050f0U, 0x783c3c44U, 0x259f9fbaU, 0x4ba8a8e3U,
+ 0xa25151f3U, 0x5da3a3feU, 0x804040c0U, 0x058f8f8aU,
+ 0x3f9292adU, 0x219d9dbcU, 0x70383848U, 0xf1f5f504U,
+ 0x63bcbcdfU, 0x77b6b6c1U, 0xafdada75U, 0x42212163U,
+ 0x20101030U, 0xe5ffff1aU, 0xfdf3f30eU, 0xbfd2d26dU,
+ 0x81cdcd4cU, 0x180c0c14U, 0x26131335U, 0xc3ecec2fU,
+ 0xbe5f5fe1U, 0x359797a2U, 0x884444ccU, 0x2e171739U,
+ 0x93c4c457U, 0x55a7a7f2U, 0xfc7e7e82U, 0x7a3d3d47U,
+ 0xc86464acU, 0xba5d5de7U, 0x3219192bU, 0xe6737395U,
+ 0xc06060a0U, 0x19818198U, 0x9e4f4fd1U, 0xa3dcdc7fU,
+ 0x44222266U, 0x542a2a7eU, 0x3b9090abU, 0x0b888883U,
+ 0x8c4646caU, 0xc7eeee29U, 0x6bb8b8d3U, 0x2814143cU,
+ 0xa7dede79U, 0xbc5e5ee2U, 0x160b0b1dU, 0xaddbdb76U,
+ 0xdbe0e03bU, 0x64323256U, 0x743a3a4eU, 0x140a0a1eU,
+ 0x924949dbU, 0x0c06060aU, 0x4824246cU, 0xb85c5ce4U,
+ 0x9fc2c25dU, 0xbdd3d36eU, 0x43acacefU, 0xc46262a6U,
+ 0x399191a8U, 0x319595a4U, 0xd3e4e437U, 0xf279798bU,
+ 0xd5e7e732U, 0x8bc8c843U, 0x6e373759U, 0xda6d6db7U,
+ 0x018d8d8cU, 0xb1d5d564U, 0x9c4e4ed2U, 0x49a9a9e0U,
+ 0xd86c6cb4U, 0xac5656faU, 0xf3f4f407U, 0xcfeaea25U,
+ 0xca6565afU, 0xf47a7a8eU, 0x47aeaee9U, 0x10080818U,
+ 0x6fbabad5U, 0xf0787888U, 0x4a25256fU, 0x5c2e2e72U,
+ 0x381c1c24U, 0x57a6a6f1U, 0x73b4b4c7U, 0x97c6c651U,
+ 0xcbe8e823U, 0xa1dddd7cU, 0xe874749cU, 0x3e1f1f21U,
+ 0x964b4bddU, 0x61bdbddcU, 0x0d8b8b86U, 0x0f8a8a85U,
+ 0xe0707090U, 0x7c3e3e42U, 0x71b5b5c4U, 0xcc6666aaU,
+ 0x904848d8U, 0x06030305U, 0xf7f6f601U, 0x1c0e0e12U,
+ 0xc26161a3U, 0x6a35355fU, 0xae5757f9U, 0x69b9b9d0U,
+ 0x17868691U, 0x99c1c158U, 0x3a1d1d27U, 0x279e9eb9U,
+ 0xd9e1e138U, 0xebf8f813U, 0x2b9898b3U, 0x22111133U,
+ 0xd26969bbU, 0xa9d9d970U, 0x078e8e89U, 0x339494a7U,
+ 0x2d9b9bb6U, 0x3c1e1e22U, 0x15878792U, 0xc9e9e920U,
+ 0x87cece49U, 0xaa5555ffU, 0x50282878U, 0xa5dfdf7aU,
+ 0x038c8c8fU, 0x59a1a1f8U, 0x09898980U, 0x1a0d0d17U,
+ 0x65bfbfdaU, 0xd7e6e631U, 0x844242c6U, 0xd06868b8U,
+ 0x824141c3U, 0x299999b0U, 0x5a2d2d77U, 0x1e0f0f11U,
+ 0x7bb0b0cbU, 0xa85454fcU, 0x6dbbbbd6U, 0x2c16163aU,
+};
+static const uint32_t Te1[256] = {
+ 0xa5c66363U, 0x84f87c7cU, 0x99ee7777U, 0x8df67b7bU,
+ 0x0dfff2f2U, 0xbdd66b6bU, 0xb1de6f6fU, 0x5491c5c5U,
+ 0x50603030U, 0x03020101U, 0xa9ce6767U, 0x7d562b2bU,
+ 0x19e7fefeU, 0x62b5d7d7U, 0xe64dababU, 0x9aec7676U,
+ 0x458fcacaU, 0x9d1f8282U, 0x4089c9c9U, 0x87fa7d7dU,
+ 0x15effafaU, 0xebb25959U, 0xc98e4747U, 0x0bfbf0f0U,
+ 0xec41adadU, 0x67b3d4d4U, 0xfd5fa2a2U, 0xea45afafU,
+ 0xbf239c9cU, 0xf753a4a4U, 0x96e47272U, 0x5b9bc0c0U,
+ 0xc275b7b7U, 0x1ce1fdfdU, 0xae3d9393U, 0x6a4c2626U,
+ 0x5a6c3636U, 0x417e3f3fU, 0x02f5f7f7U, 0x4f83ccccU,
+ 0x5c683434U, 0xf451a5a5U, 0x34d1e5e5U, 0x08f9f1f1U,
+ 0x93e27171U, 0x73abd8d8U, 0x53623131U, 0x3f2a1515U,
+ 0x0c080404U, 0x5295c7c7U, 0x65462323U, 0x5e9dc3c3U,
+ 0x28301818U, 0xa1379696U, 0x0f0a0505U, 0xb52f9a9aU,
+ 0x090e0707U, 0x36241212U, 0x9b1b8080U, 0x3ddfe2e2U,
+ 0x26cdebebU, 0x694e2727U, 0xcd7fb2b2U, 0x9fea7575U,
+ 0x1b120909U, 0x9e1d8383U, 0x74582c2cU, 0x2e341a1aU,
+ 0x2d361b1bU, 0xb2dc6e6eU, 0xeeb45a5aU, 0xfb5ba0a0U,
+ 0xf6a45252U, 0x4d763b3bU, 0x61b7d6d6U, 0xce7db3b3U,
+ 0x7b522929U, 0x3edde3e3U, 0x715e2f2fU, 0x97138484U,
+ 0xf5a65353U, 0x68b9d1d1U, 0x00000000U, 0x2cc1ededU,
+ 0x60402020U, 0x1fe3fcfcU, 0xc879b1b1U, 0xedb65b5bU,
+ 0xbed46a6aU, 0x468dcbcbU, 0xd967bebeU, 0x4b723939U,
+ 0xde944a4aU, 0xd4984c4cU, 0xe8b05858U, 0x4a85cfcfU,
+ 0x6bbbd0d0U, 0x2ac5efefU, 0xe54faaaaU, 0x16edfbfbU,
+ 0xc5864343U, 0xd79a4d4dU, 0x55663333U, 0x94118585U,
+ 0xcf8a4545U, 0x10e9f9f9U, 0x06040202U, 0x81fe7f7fU,
+ 0xf0a05050U, 0x44783c3cU, 0xba259f9fU, 0xe34ba8a8U,
+ 0xf3a25151U, 0xfe5da3a3U, 0xc0804040U, 0x8a058f8fU,
+ 0xad3f9292U, 0xbc219d9dU, 0x48703838U, 0x04f1f5f5U,
+ 0xdf63bcbcU, 0xc177b6b6U, 0x75afdadaU, 0x63422121U,
+ 0x30201010U, 0x1ae5ffffU, 0x0efdf3f3U, 0x6dbfd2d2U,
+ 0x4c81cdcdU, 0x14180c0cU, 0x35261313U, 0x2fc3ececU,
+ 0xe1be5f5fU, 0xa2359797U, 0xcc884444U, 0x392e1717U,
+ 0x5793c4c4U, 0xf255a7a7U, 0x82fc7e7eU, 0x477a3d3dU,
+ 0xacc86464U, 0xe7ba5d5dU, 0x2b321919U, 0x95e67373U,
+ 0xa0c06060U, 0x98198181U, 0xd19e4f4fU, 0x7fa3dcdcU,
+ 0x66442222U, 0x7e542a2aU, 0xab3b9090U, 0x830b8888U,
+ 0xca8c4646U, 0x29c7eeeeU, 0xd36bb8b8U, 0x3c281414U,
+ 0x79a7dedeU, 0xe2bc5e5eU, 0x1d160b0bU, 0x76addbdbU,
+ 0x3bdbe0e0U, 0x56643232U, 0x4e743a3aU, 0x1e140a0aU,
+ 0xdb924949U, 0x0a0c0606U, 0x6c482424U, 0xe4b85c5cU,
+ 0x5d9fc2c2U, 0x6ebdd3d3U, 0xef43acacU, 0xa6c46262U,
+ 0xa8399191U, 0xa4319595U, 0x37d3e4e4U, 0x8bf27979U,
+ 0x32d5e7e7U, 0x438bc8c8U, 0x596e3737U, 0xb7da6d6dU,
+ 0x8c018d8dU, 0x64b1d5d5U, 0xd29c4e4eU, 0xe049a9a9U,
+ 0xb4d86c6cU, 0xfaac5656U, 0x07f3f4f4U, 0x25cfeaeaU,
+ 0xafca6565U, 0x8ef47a7aU, 0xe947aeaeU, 0x18100808U,
+ 0xd56fbabaU, 0x88f07878U, 0x6f4a2525U, 0x725c2e2eU,
+ 0x24381c1cU, 0xf157a6a6U, 0xc773b4b4U, 0x5197c6c6U,
+ 0x23cbe8e8U, 0x7ca1ddddU, 0x9ce87474U, 0x213e1f1fU,
+ 0xdd964b4bU, 0xdc61bdbdU, 0x860d8b8bU, 0x850f8a8aU,
+ 0x90e07070U, 0x427c3e3eU, 0xc471b5b5U, 0xaacc6666U,
+ 0xd8904848U, 0x05060303U, 0x01f7f6f6U, 0x121c0e0eU,
+ 0xa3c26161U, 0x5f6a3535U, 0xf9ae5757U, 0xd069b9b9U,
+ 0x91178686U, 0x5899c1c1U, 0x273a1d1dU, 0xb9279e9eU,
+ 0x38d9e1e1U, 0x13ebf8f8U, 0xb32b9898U, 0x33221111U,
+ 0xbbd26969U, 0x70a9d9d9U, 0x89078e8eU, 0xa7339494U,
+ 0xb62d9b9bU, 0x223c1e1eU, 0x92158787U, 0x20c9e9e9U,
+ 0x4987ceceU, 0xffaa5555U, 0x78502828U, 0x7aa5dfdfU,
+ 0x8f038c8cU, 0xf859a1a1U, 0x80098989U, 0x171a0d0dU,
+ 0xda65bfbfU, 0x31d7e6e6U, 0xc6844242U, 0xb8d06868U,
+ 0xc3824141U, 0xb0299999U, 0x775a2d2dU, 0x111e0f0fU,
+ 0xcb7bb0b0U, 0xfca85454U, 0xd66dbbbbU, 0x3a2c1616U,
+};
+static const uint32_t Te2[256] = {
+ 0x63a5c663U, 0x7c84f87cU, 0x7799ee77U, 0x7b8df67bU,
+ 0xf20dfff2U, 0x6bbdd66bU, 0x6fb1de6fU, 0xc55491c5U,
+ 0x30506030U, 0x01030201U, 0x67a9ce67U, 0x2b7d562bU,
+ 0xfe19e7feU, 0xd762b5d7U, 0xabe64dabU, 0x769aec76U,
+ 0xca458fcaU, 0x829d1f82U, 0xc94089c9U, 0x7d87fa7dU,
+ 0xfa15effaU, 0x59ebb259U, 0x47c98e47U, 0xf00bfbf0U,
+ 0xadec41adU, 0xd467b3d4U, 0xa2fd5fa2U, 0xafea45afU,
+ 0x9cbf239cU, 0xa4f753a4U, 0x7296e472U, 0xc05b9bc0U,
+ 0xb7c275b7U, 0xfd1ce1fdU, 0x93ae3d93U, 0x266a4c26U,
+ 0x365a6c36U, 0x3f417e3fU, 0xf702f5f7U, 0xcc4f83ccU,
+ 0x345c6834U, 0xa5f451a5U, 0xe534d1e5U, 0xf108f9f1U,
+ 0x7193e271U, 0xd873abd8U, 0x31536231U, 0x153f2a15U,
+ 0x040c0804U, 0xc75295c7U, 0x23654623U, 0xc35e9dc3U,
+ 0x18283018U, 0x96a13796U, 0x050f0a05U, 0x9ab52f9aU,
+ 0x07090e07U, 0x12362412U, 0x809b1b80U, 0xe23ddfe2U,
+ 0xeb26cdebU, 0x27694e27U, 0xb2cd7fb2U, 0x759fea75U,
+ 0x091b1209U, 0x839e1d83U, 0x2c74582cU, 0x1a2e341aU,
+ 0x1b2d361bU, 0x6eb2dc6eU, 0x5aeeb45aU, 0xa0fb5ba0U,
+ 0x52f6a452U, 0x3b4d763bU, 0xd661b7d6U, 0xb3ce7db3U,
+ 0x297b5229U, 0xe33edde3U, 0x2f715e2fU, 0x84971384U,
+ 0x53f5a653U, 0xd168b9d1U, 0x00000000U, 0xed2cc1edU,
+ 0x20604020U, 0xfc1fe3fcU, 0xb1c879b1U, 0x5bedb65bU,
+ 0x6abed46aU, 0xcb468dcbU, 0xbed967beU, 0x394b7239U,
+ 0x4ade944aU, 0x4cd4984cU, 0x58e8b058U, 0xcf4a85cfU,
+ 0xd06bbbd0U, 0xef2ac5efU, 0xaae54faaU, 0xfb16edfbU,
+ 0x43c58643U, 0x4dd79a4dU, 0x33556633U, 0x85941185U,
+ 0x45cf8a45U, 0xf910e9f9U, 0x02060402U, 0x7f81fe7fU,
+ 0x50f0a050U, 0x3c44783cU, 0x9fba259fU, 0xa8e34ba8U,
+ 0x51f3a251U, 0xa3fe5da3U, 0x40c08040U, 0x8f8a058fU,
+ 0x92ad3f92U, 0x9dbc219dU, 0x38487038U, 0xf504f1f5U,
+ 0xbcdf63bcU, 0xb6c177b6U, 0xda75afdaU, 0x21634221U,
+ 0x10302010U, 0xff1ae5ffU, 0xf30efdf3U, 0xd26dbfd2U,
+ 0xcd4c81cdU, 0x0c14180cU, 0x13352613U, 0xec2fc3ecU,
+ 0x5fe1be5fU, 0x97a23597U, 0x44cc8844U, 0x17392e17U,
+ 0xc45793c4U, 0xa7f255a7U, 0x7e82fc7eU, 0x3d477a3dU,
+ 0x64acc864U, 0x5de7ba5dU, 0x192b3219U, 0x7395e673U,
+ 0x60a0c060U, 0x81981981U, 0x4fd19e4fU, 0xdc7fa3dcU,
+ 0x22664422U, 0x2a7e542aU, 0x90ab3b90U, 0x88830b88U,
+ 0x46ca8c46U, 0xee29c7eeU, 0xb8d36bb8U, 0x143c2814U,
+ 0xde79a7deU, 0x5ee2bc5eU, 0x0b1d160bU, 0xdb76addbU,
+ 0xe03bdbe0U, 0x32566432U, 0x3a4e743aU, 0x0a1e140aU,
+ 0x49db9249U, 0x060a0c06U, 0x246c4824U, 0x5ce4b85cU,
+ 0xc25d9fc2U, 0xd36ebdd3U, 0xacef43acU, 0x62a6c462U,
+ 0x91a83991U, 0x95a43195U, 0xe437d3e4U, 0x798bf279U,
+ 0xe732d5e7U, 0xc8438bc8U, 0x37596e37U, 0x6db7da6dU,
+ 0x8d8c018dU, 0xd564b1d5U, 0x4ed29c4eU, 0xa9e049a9U,
+ 0x6cb4d86cU, 0x56faac56U, 0xf407f3f4U, 0xea25cfeaU,
+ 0x65afca65U, 0x7a8ef47aU, 0xaee947aeU, 0x08181008U,
+ 0xbad56fbaU, 0x7888f078U, 0x256f4a25U, 0x2e725c2eU,
+ 0x1c24381cU, 0xa6f157a6U, 0xb4c773b4U, 0xc65197c6U,
+ 0xe823cbe8U, 0xdd7ca1ddU, 0x749ce874U, 0x1f213e1fU,
+ 0x4bdd964bU, 0xbddc61bdU, 0x8b860d8bU, 0x8a850f8aU,
+ 0x7090e070U, 0x3e427c3eU, 0xb5c471b5U, 0x66aacc66U,
+ 0x48d89048U, 0x03050603U, 0xf601f7f6U, 0x0e121c0eU,
+ 0x61a3c261U, 0x355f6a35U, 0x57f9ae57U, 0xb9d069b9U,
+ 0x86911786U, 0xc15899c1U, 0x1d273a1dU, 0x9eb9279eU,
+ 0xe138d9e1U, 0xf813ebf8U, 0x98b32b98U, 0x11332211U,
+ 0x69bbd269U, 0xd970a9d9U, 0x8e89078eU, 0x94a73394U,
+ 0x9bb62d9bU, 0x1e223c1eU, 0x87921587U, 0xe920c9e9U,
+ 0xce4987ceU, 0x55ffaa55U, 0x28785028U, 0xdf7aa5dfU,
+ 0x8c8f038cU, 0xa1f859a1U, 0x89800989U, 0x0d171a0dU,
+ 0xbfda65bfU, 0xe631d7e6U, 0x42c68442U, 0x68b8d068U,
+ 0x41c38241U, 0x99b02999U, 0x2d775a2dU, 0x0f111e0fU,
+ 0xb0cb7bb0U, 0x54fca854U, 0xbbd66dbbU, 0x163a2c16U,
+};
+static const uint32_t Te3[256] = {
+
+ 0x6363a5c6U, 0x7c7c84f8U, 0x777799eeU, 0x7b7b8df6U,
+ 0xf2f20dffU, 0x6b6bbdd6U, 0x6f6fb1deU, 0xc5c55491U,
+ 0x30305060U, 0x01010302U, 0x6767a9ceU, 0x2b2b7d56U,
+ 0xfefe19e7U, 0xd7d762b5U, 0xababe64dU, 0x76769aecU,
+ 0xcaca458fU, 0x82829d1fU, 0xc9c94089U, 0x7d7d87faU,
+ 0xfafa15efU, 0x5959ebb2U, 0x4747c98eU, 0xf0f00bfbU,
+ 0xadadec41U, 0xd4d467b3U, 0xa2a2fd5fU, 0xafafea45U,
+ 0x9c9cbf23U, 0xa4a4f753U, 0x727296e4U, 0xc0c05b9bU,
+ 0xb7b7c275U, 0xfdfd1ce1U, 0x9393ae3dU, 0x26266a4cU,
+ 0x36365a6cU, 0x3f3f417eU, 0xf7f702f5U, 0xcccc4f83U,
+ 0x34345c68U, 0xa5a5f451U, 0xe5e534d1U, 0xf1f108f9U,
+ 0x717193e2U, 0xd8d873abU, 0x31315362U, 0x15153f2aU,
+ 0x04040c08U, 0xc7c75295U, 0x23236546U, 0xc3c35e9dU,
+ 0x18182830U, 0x9696a137U, 0x05050f0aU, 0x9a9ab52fU,
+ 0x0707090eU, 0x12123624U, 0x80809b1bU, 0xe2e23ddfU,
+ 0xebeb26cdU, 0x2727694eU, 0xb2b2cd7fU, 0x75759feaU,
+ 0x09091b12U, 0x83839e1dU, 0x2c2c7458U, 0x1a1a2e34U,
+ 0x1b1b2d36U, 0x6e6eb2dcU, 0x5a5aeeb4U, 0xa0a0fb5bU,
+ 0x5252f6a4U, 0x3b3b4d76U, 0xd6d661b7U, 0xb3b3ce7dU,
+ 0x29297b52U, 0xe3e33eddU, 0x2f2f715eU, 0x84849713U,
+ 0x5353f5a6U, 0xd1d168b9U, 0x00000000U, 0xeded2cc1U,
+ 0x20206040U, 0xfcfc1fe3U, 0xb1b1c879U, 0x5b5bedb6U,
+ 0x6a6abed4U, 0xcbcb468dU, 0xbebed967U, 0x39394b72U,
+ 0x4a4ade94U, 0x4c4cd498U, 0x5858e8b0U, 0xcfcf4a85U,
+ 0xd0d06bbbU, 0xefef2ac5U, 0xaaaae54fU, 0xfbfb16edU,
+ 0x4343c586U, 0x4d4dd79aU, 0x33335566U, 0x85859411U,
+ 0x4545cf8aU, 0xf9f910e9U, 0x02020604U, 0x7f7f81feU,
+ 0x5050f0a0U, 0x3c3c4478U, 0x9f9fba25U, 0xa8a8e34bU,
+ 0x5151f3a2U, 0xa3a3fe5dU, 0x4040c080U, 0x8f8f8a05U,
+ 0x9292ad3fU, 0x9d9dbc21U, 0x38384870U, 0xf5f504f1U,
+ 0xbcbcdf63U, 0xb6b6c177U, 0xdada75afU, 0x21216342U,
+ 0x10103020U, 0xffff1ae5U, 0xf3f30efdU, 0xd2d26dbfU,
+ 0xcdcd4c81U, 0x0c0c1418U, 0x13133526U, 0xecec2fc3U,
+ 0x5f5fe1beU, 0x9797a235U, 0x4444cc88U, 0x1717392eU,
+ 0xc4c45793U, 0xa7a7f255U, 0x7e7e82fcU, 0x3d3d477aU,
+ 0x6464acc8U, 0x5d5de7baU, 0x19192b32U, 0x737395e6U,
+ 0x6060a0c0U, 0x81819819U, 0x4f4fd19eU, 0xdcdc7fa3U,
+ 0x22226644U, 0x2a2a7e54U, 0x9090ab3bU, 0x8888830bU,
+ 0x4646ca8cU, 0xeeee29c7U, 0xb8b8d36bU, 0x14143c28U,
+ 0xdede79a7U, 0x5e5ee2bcU, 0x0b0b1d16U, 0xdbdb76adU,
+ 0xe0e03bdbU, 0x32325664U, 0x3a3a4e74U, 0x0a0a1e14U,
+ 0x4949db92U, 0x06060a0cU, 0x24246c48U, 0x5c5ce4b8U,
+ 0xc2c25d9fU, 0xd3d36ebdU, 0xacacef43U, 0x6262a6c4U,
+ 0x9191a839U, 0x9595a431U, 0xe4e437d3U, 0x79798bf2U,
+ 0xe7e732d5U, 0xc8c8438bU, 0x3737596eU, 0x6d6db7daU,
+ 0x8d8d8c01U, 0xd5d564b1U, 0x4e4ed29cU, 0xa9a9e049U,
+ 0x6c6cb4d8U, 0x5656faacU, 0xf4f407f3U, 0xeaea25cfU,
+ 0x6565afcaU, 0x7a7a8ef4U, 0xaeaee947U, 0x08081810U,
+ 0xbabad56fU, 0x787888f0U, 0x25256f4aU, 0x2e2e725cU,
+ 0x1c1c2438U, 0xa6a6f157U, 0xb4b4c773U, 0xc6c65197U,
+ 0xe8e823cbU, 0xdddd7ca1U, 0x74749ce8U, 0x1f1f213eU,
+ 0x4b4bdd96U, 0xbdbddc61U, 0x8b8b860dU, 0x8a8a850fU,
+ 0x707090e0U, 0x3e3e427cU, 0xb5b5c471U, 0x6666aaccU,
+ 0x4848d890U, 0x03030506U, 0xf6f601f7U, 0x0e0e121cU,
+ 0x6161a3c2U, 0x35355f6aU, 0x5757f9aeU, 0xb9b9d069U,
+ 0x86869117U, 0xc1c15899U, 0x1d1d273aU, 0x9e9eb927U,
+ 0xe1e138d9U, 0xf8f813ebU, 0x9898b32bU, 0x11113322U,
+ 0x6969bbd2U, 0xd9d970a9U, 0x8e8e8907U, 0x9494a733U,
+ 0x9b9bb62dU, 0x1e1e223cU, 0x87879215U, 0xe9e920c9U,
+ 0xcece4987U, 0x5555ffaaU, 0x28287850U, 0xdfdf7aa5U,
+ 0x8c8c8f03U, 0xa1a1f859U, 0x89898009U, 0x0d0d171aU,
+ 0xbfbfda65U, 0xe6e631d7U, 0x4242c684U, 0x6868b8d0U,
+ 0x4141c382U, 0x9999b029U, 0x2d2d775aU, 0x0f0f111eU,
+ 0xb0b0cb7bU, 0x5454fca8U, 0xbbbbd66dU, 0x16163a2cU,
+};
+static const uint32_t Te4[256] = {
+ 0x63636363U, 0x7c7c7c7cU, 0x77777777U, 0x7b7b7b7bU,
+ 0xf2f2f2f2U, 0x6b6b6b6bU, 0x6f6f6f6fU, 0xc5c5c5c5U,
+ 0x30303030U, 0x01010101U, 0x67676767U, 0x2b2b2b2bU,
+ 0xfefefefeU, 0xd7d7d7d7U, 0xababababU, 0x76767676U,
+ 0xcacacacaU, 0x82828282U, 0xc9c9c9c9U, 0x7d7d7d7dU,
+ 0xfafafafaU, 0x59595959U, 0x47474747U, 0xf0f0f0f0U,
+ 0xadadadadU, 0xd4d4d4d4U, 0xa2a2a2a2U, 0xafafafafU,
+ 0x9c9c9c9cU, 0xa4a4a4a4U, 0x72727272U, 0xc0c0c0c0U,
+ 0xb7b7b7b7U, 0xfdfdfdfdU, 0x93939393U, 0x26262626U,
+ 0x36363636U, 0x3f3f3f3fU, 0xf7f7f7f7U, 0xccccccccU,
+ 0x34343434U, 0xa5a5a5a5U, 0xe5e5e5e5U, 0xf1f1f1f1U,
+ 0x71717171U, 0xd8d8d8d8U, 0x31313131U, 0x15151515U,
+ 0x04040404U, 0xc7c7c7c7U, 0x23232323U, 0xc3c3c3c3U,
+ 0x18181818U, 0x96969696U, 0x05050505U, 0x9a9a9a9aU,
+ 0x07070707U, 0x12121212U, 0x80808080U, 0xe2e2e2e2U,
+ 0xebebebebU, 0x27272727U, 0xb2b2b2b2U, 0x75757575U,
+ 0x09090909U, 0x83838383U, 0x2c2c2c2cU, 0x1a1a1a1aU,
+ 0x1b1b1b1bU, 0x6e6e6e6eU, 0x5a5a5a5aU, 0xa0a0a0a0U,
+ 0x52525252U, 0x3b3b3b3bU, 0xd6d6d6d6U, 0xb3b3b3b3U,
+ 0x29292929U, 0xe3e3e3e3U, 0x2f2f2f2fU, 0x84848484U,
+ 0x53535353U, 0xd1d1d1d1U, 0x00000000U, 0xededededU,
+ 0x20202020U, 0xfcfcfcfcU, 0xb1b1b1b1U, 0x5b5b5b5bU,
+ 0x6a6a6a6aU, 0xcbcbcbcbU, 0xbebebebeU, 0x39393939U,
+ 0x4a4a4a4aU, 0x4c4c4c4cU, 0x58585858U, 0xcfcfcfcfU,
+ 0xd0d0d0d0U, 0xefefefefU, 0xaaaaaaaaU, 0xfbfbfbfbU,
+ 0x43434343U, 0x4d4d4d4dU, 0x33333333U, 0x85858585U,
+ 0x45454545U, 0xf9f9f9f9U, 0x02020202U, 0x7f7f7f7fU,
+ 0x50505050U, 0x3c3c3c3cU, 0x9f9f9f9fU, 0xa8a8a8a8U,
+ 0x51515151U, 0xa3a3a3a3U, 0x40404040U, 0x8f8f8f8fU,
+ 0x92929292U, 0x9d9d9d9dU, 0x38383838U, 0xf5f5f5f5U,
+ 0xbcbcbcbcU, 0xb6b6b6b6U, 0xdadadadaU, 0x21212121U,
+ 0x10101010U, 0xffffffffU, 0xf3f3f3f3U, 0xd2d2d2d2U,
+ 0xcdcdcdcdU, 0x0c0c0c0cU, 0x13131313U, 0xececececU,
+ 0x5f5f5f5fU, 0x97979797U, 0x44444444U, 0x17171717U,
+ 0xc4c4c4c4U, 0xa7a7a7a7U, 0x7e7e7e7eU, 0x3d3d3d3dU,
+ 0x64646464U, 0x5d5d5d5dU, 0x19191919U, 0x73737373U,
+ 0x60606060U, 0x81818181U, 0x4f4f4f4fU, 0xdcdcdcdcU,
+ 0x22222222U, 0x2a2a2a2aU, 0x90909090U, 0x88888888U,
+ 0x46464646U, 0xeeeeeeeeU, 0xb8b8b8b8U, 0x14141414U,
+ 0xdedededeU, 0x5e5e5e5eU, 0x0b0b0b0bU, 0xdbdbdbdbU,
+ 0xe0e0e0e0U, 0x32323232U, 0x3a3a3a3aU, 0x0a0a0a0aU,
+ 0x49494949U, 0x06060606U, 0x24242424U, 0x5c5c5c5cU,
+ 0xc2c2c2c2U, 0xd3d3d3d3U, 0xacacacacU, 0x62626262U,
+ 0x91919191U, 0x95959595U, 0xe4e4e4e4U, 0x79797979U,
+ 0xe7e7e7e7U, 0xc8c8c8c8U, 0x37373737U, 0x6d6d6d6dU,
+ 0x8d8d8d8dU, 0xd5d5d5d5U, 0x4e4e4e4eU, 0xa9a9a9a9U,
+ 0x6c6c6c6cU, 0x56565656U, 0xf4f4f4f4U, 0xeaeaeaeaU,
+ 0x65656565U, 0x7a7a7a7aU, 0xaeaeaeaeU, 0x08080808U,
+ 0xbabababaU, 0x78787878U, 0x25252525U, 0x2e2e2e2eU,
+ 0x1c1c1c1cU, 0xa6a6a6a6U, 0xb4b4b4b4U, 0xc6c6c6c6U,
+ 0xe8e8e8e8U, 0xddddddddU, 0x74747474U, 0x1f1f1f1fU,
+ 0x4b4b4b4bU, 0xbdbdbdbdU, 0x8b8b8b8bU, 0x8a8a8a8aU,
+ 0x70707070U, 0x3e3e3e3eU, 0xb5b5b5b5U, 0x66666666U,
+ 0x48484848U, 0x03030303U, 0xf6f6f6f6U, 0x0e0e0e0eU,
+ 0x61616161U, 0x35353535U, 0x57575757U, 0xb9b9b9b9U,
+ 0x86868686U, 0xc1c1c1c1U, 0x1d1d1d1dU, 0x9e9e9e9eU,
+ 0xe1e1e1e1U, 0xf8f8f8f8U, 0x98989898U, 0x11111111U,
+ 0x69696969U, 0xd9d9d9d9U, 0x8e8e8e8eU, 0x94949494U,
+ 0x9b9b9b9bU, 0x1e1e1e1eU, 0x87878787U, 0xe9e9e9e9U,
+ 0xcecececeU, 0x55555555U, 0x28282828U, 0xdfdfdfdfU,
+ 0x8c8c8c8cU, 0xa1a1a1a1U, 0x89898989U, 0x0d0d0d0dU,
+ 0xbfbfbfbfU, 0xe6e6e6e6U, 0x42424242U, 0x68686868U,
+ 0x41414141U, 0x99999999U, 0x2d2d2d2dU, 0x0f0f0f0fU,
+ 0xb0b0b0b0U, 0x54545454U, 0xbbbbbbbbU, 0x16161616U,
+};
+static const uint32_t Td0[256] = {
+ 0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U,
+ 0x3bab6bcbU, 0x1f9d45f1U, 0xacfa58abU, 0x4be30393U,
+ 0x2030fa55U, 0xad766df6U, 0x88cc7691U, 0xf5024c25U,
+ 0x4fe5d7fcU, 0xc52acbd7U, 0x26354480U, 0xb562a38fU,
+ 0xdeb15a49U, 0x25ba1b67U, 0x45ea0e98U, 0x5dfec0e1U,
+ 0xc32f7502U, 0x814cf012U, 0x8d4697a3U, 0x6bd3f9c6U,
+ 0x038f5fe7U, 0x15929c95U, 0xbf6d7aebU, 0x955259daU,
+ 0xd4be832dU, 0x587421d3U, 0x49e06929U, 0x8ec9c844U,
+ 0x75c2896aU, 0xf48e7978U, 0x99583e6bU, 0x27b971ddU,
+ 0xbee14fb6U, 0xf088ad17U, 0xc920ac66U, 0x7dce3ab4U,
+ 0x63df4a18U, 0xe51a3182U, 0x97513360U, 0x62537f45U,
+ 0xb16477e0U, 0xbb6bae84U, 0xfe81a01cU, 0xf9082b94U,
+ 0x70486858U, 0x8f45fd19U, 0x94de6c87U, 0x527bf8b7U,
+ 0xab73d323U, 0x724b02e2U, 0xe31f8f57U, 0x6655ab2aU,
+ 0xb2eb2807U, 0x2fb5c203U, 0x86c57b9aU, 0xd33708a5U,
+ 0x302887f2U, 0x23bfa5b2U, 0x02036abaU, 0xed16825cU,
+ 0x8acf1c2bU, 0xa779b492U, 0xf307f2f0U, 0x4e69e2a1U,
+ 0x65daf4cdU, 0x0605bed5U, 0xd134621fU, 0xc4a6fe8aU,
+ 0x342e539dU, 0xa2f355a0U, 0x058ae132U, 0xa4f6eb75U,
+ 0x0b83ec39U, 0x4060efaaU, 0x5e719f06U, 0xbd6e1051U,
+ 0x3e218af9U, 0x96dd063dU, 0xdd3e05aeU, 0x4de6bd46U,
+ 0x91548db5U, 0x71c45d05U, 0x0406d46fU, 0x605015ffU,
+ 0x1998fb24U, 0xd6bde997U, 0x894043ccU, 0x67d99e77U,
+ 0xb0e842bdU, 0x07898b88U, 0xe7195b38U, 0x79c8eedbU,
+ 0xa17c0a47U, 0x7c420fe9U, 0xf8841ec9U, 0x00000000U,
+ 0x09808683U, 0x322bed48U, 0x1e1170acU, 0x6c5a724eU,
+ 0xfd0efffbU, 0x0f853856U, 0x3daed51eU, 0x362d3927U,
+ 0x0a0fd964U, 0x685ca621U, 0x9b5b54d1U, 0x24362e3aU,
+ 0x0c0a67b1U, 0x9357e70fU, 0xb4ee96d2U, 0x1b9b919eU,
+ 0x80c0c54fU, 0x61dc20a2U, 0x5a774b69U, 0x1c121a16U,
+ 0xe293ba0aU, 0xc0a02ae5U, 0x3c22e043U, 0x121b171dU,
+ 0x0e090d0bU, 0xf28bc7adU, 0x2db6a8b9U, 0x141ea9c8U,
+ 0x57f11985U, 0xaf75074cU, 0xee99ddbbU, 0xa37f60fdU,
+ 0xf701269fU, 0x5c72f5bcU, 0x44663bc5U, 0x5bfb7e34U,
+ 0x8b432976U, 0xcb23c6dcU, 0xb6edfc68U, 0xb8e4f163U,
+ 0xd731dccaU, 0x42638510U, 0x13972240U, 0x84c61120U,
+ 0x854a247dU, 0xd2bb3df8U, 0xaef93211U, 0xc729a16dU,
+ 0x1d9e2f4bU, 0xdcb230f3U, 0x0d8652ecU, 0x77c1e3d0U,
+ 0x2bb3166cU, 0xa970b999U, 0x119448faU, 0x47e96422U,
+ 0xa8fc8cc4U, 0xa0f03f1aU, 0x567d2cd8U, 0x223390efU,
+ 0x87494ec7U, 0xd938d1c1U, 0x8ccaa2feU, 0x98d40b36U,
+ 0xa6f581cfU, 0xa57ade28U, 0xdab78e26U, 0x3fadbfa4U,
+ 0x2c3a9de4U, 0x5078920dU, 0x6a5fcc9bU, 0x547e4662U,
+ 0xf68d13c2U, 0x90d8b8e8U, 0x2e39f75eU, 0x82c3aff5U,
+ 0x9f5d80beU, 0x69d0937cU, 0x6fd52da9U, 0xcf2512b3U,
+ 0xc8ac993bU, 0x10187da7U, 0xe89c636eU, 0xdb3bbb7bU,
+ 0xcd267809U, 0x6e5918f4U, 0xec9ab701U, 0x834f9aa8U,
+ 0xe6956e65U, 0xaaffe67eU, 0x21bccf08U, 0xef15e8e6U,
+ 0xbae79bd9U, 0x4a6f36ceU, 0xea9f09d4U, 0x29b07cd6U,
+ 0x31a4b2afU, 0x2a3f2331U, 0xc6a59430U, 0x35a266c0U,
+ 0x744ebc37U, 0xfc82caa6U, 0xe090d0b0U, 0x33a7d815U,
+ 0xf104984aU, 0x41ecdaf7U, 0x7fcd500eU, 0x1791f62fU,
+ 0x764dd68dU, 0x43efb04dU, 0xccaa4d54U, 0xe49604dfU,
+ 0x9ed1b5e3U, 0x4c6a881bU, 0xc12c1fb8U, 0x4665517fU,
+ 0x9d5eea04U, 0x018c355dU, 0xfa877473U, 0xfb0b412eU,
+ 0xb3671d5aU, 0x92dbd252U, 0xe9105633U, 0x6dd64713U,
+ 0x9ad7618cU, 0x37a10c7aU, 0x59f8148eU, 0xeb133c89U,
+ 0xcea927eeU, 0xb761c935U, 0xe11ce5edU, 0x7a47b13cU,
+ 0x9cd2df59U, 0x55f2733fU, 0x1814ce79U, 0x73c737bfU,
+ 0x53f7cdeaU, 0x5ffdaa5bU, 0xdf3d6f14U, 0x7844db86U,
+ 0xcaaff381U, 0xb968c43eU, 0x3824342cU, 0xc2a3405fU,
+ 0x161dc372U, 0xbce2250cU, 0x283c498bU, 0xff0d9541U,
+ 0x39a80171U, 0x080cb3deU, 0xd8b4e49cU, 0x6456c190U,
+ 0x7bcb8461U, 0xd532b670U, 0x486c5c74U, 0xd0b85742U,
+};
+static const uint32_t Td1[256] = {
+ 0x5051f4a7U, 0x537e4165U, 0xc31a17a4U, 0x963a275eU,
+ 0xcb3bab6bU, 0xf11f9d45U, 0xabacfa58U, 0x934be303U,
+ 0x552030faU, 0xf6ad766dU, 0x9188cc76U, 0x25f5024cU,
+ 0xfc4fe5d7U, 0xd7c52acbU, 0x80263544U, 0x8fb562a3U,
+ 0x49deb15aU, 0x6725ba1bU, 0x9845ea0eU, 0xe15dfec0U,
+ 0x02c32f75U, 0x12814cf0U, 0xa38d4697U, 0xc66bd3f9U,
+ 0xe7038f5fU, 0x9515929cU, 0xebbf6d7aU, 0xda955259U,
+ 0x2dd4be83U, 0xd3587421U, 0x2949e069U, 0x448ec9c8U,
+ 0x6a75c289U, 0x78f48e79U, 0x6b99583eU, 0xdd27b971U,
+ 0xb6bee14fU, 0x17f088adU, 0x66c920acU, 0xb47dce3aU,
+ 0x1863df4aU, 0x82e51a31U, 0x60975133U, 0x4562537fU,
+ 0xe0b16477U, 0x84bb6baeU, 0x1cfe81a0U, 0x94f9082bU,
+ 0x58704868U, 0x198f45fdU, 0x8794de6cU, 0xb7527bf8U,
+ 0x23ab73d3U, 0xe2724b02U, 0x57e31f8fU, 0x2a6655abU,
+ 0x07b2eb28U, 0x032fb5c2U, 0x9a86c57bU, 0xa5d33708U,
+ 0xf2302887U, 0xb223bfa5U, 0xba02036aU, 0x5ced1682U,
+ 0x2b8acf1cU, 0x92a779b4U, 0xf0f307f2U, 0xa14e69e2U,
+ 0xcd65daf4U, 0xd50605beU, 0x1fd13462U, 0x8ac4a6feU,
+ 0x9d342e53U, 0xa0a2f355U, 0x32058ae1U, 0x75a4f6ebU,
+ 0x390b83ecU, 0xaa4060efU, 0x065e719fU, 0x51bd6e10U,
+ 0xf93e218aU, 0x3d96dd06U, 0xaedd3e05U, 0x464de6bdU,
+ 0xb591548dU, 0x0571c45dU, 0x6f0406d4U, 0xff605015U,
+ 0x241998fbU, 0x97d6bde9U, 0xcc894043U, 0x7767d99eU,
+ 0xbdb0e842U, 0x8807898bU, 0x38e7195bU, 0xdb79c8eeU,
+ 0x47a17c0aU, 0xe97c420fU, 0xc9f8841eU, 0x00000000U,
+ 0x83098086U, 0x48322bedU, 0xac1e1170U, 0x4e6c5a72U,
+ 0xfbfd0effU, 0x560f8538U, 0x1e3daed5U, 0x27362d39U,
+ 0x640a0fd9U, 0x21685ca6U, 0xd19b5b54U, 0x3a24362eU,
+ 0xb10c0a67U, 0x0f9357e7U, 0xd2b4ee96U, 0x9e1b9b91U,
+ 0x4f80c0c5U, 0xa261dc20U, 0x695a774bU, 0x161c121aU,
+ 0x0ae293baU, 0xe5c0a02aU, 0x433c22e0U, 0x1d121b17U,
+ 0x0b0e090dU, 0xadf28bc7U, 0xb92db6a8U, 0xc8141ea9U,
+ 0x8557f119U, 0x4caf7507U, 0xbbee99ddU, 0xfda37f60U,
+ 0x9ff70126U, 0xbc5c72f5U, 0xc544663bU, 0x345bfb7eU,
+ 0x768b4329U, 0xdccb23c6U, 0x68b6edfcU, 0x63b8e4f1U,
+ 0xcad731dcU, 0x10426385U, 0x40139722U, 0x2084c611U,
+ 0x7d854a24U, 0xf8d2bb3dU, 0x11aef932U, 0x6dc729a1U,
+ 0x4b1d9e2fU, 0xf3dcb230U, 0xec0d8652U, 0xd077c1e3U,
+ 0x6c2bb316U, 0x99a970b9U, 0xfa119448U, 0x2247e964U,
+ 0xc4a8fc8cU, 0x1aa0f03fU, 0xd8567d2cU, 0xef223390U,
+ 0xc787494eU, 0xc1d938d1U, 0xfe8ccaa2U, 0x3698d40bU,
+ 0xcfa6f581U, 0x28a57adeU, 0x26dab78eU, 0xa43fadbfU,
+ 0xe42c3a9dU, 0x0d507892U, 0x9b6a5fccU, 0x62547e46U,
+ 0xc2f68d13U, 0xe890d8b8U, 0x5e2e39f7U, 0xf582c3afU,
+ 0xbe9f5d80U, 0x7c69d093U, 0xa96fd52dU, 0xb3cf2512U,
+ 0x3bc8ac99U, 0xa710187dU, 0x6ee89c63U, 0x7bdb3bbbU,
+ 0x09cd2678U, 0xf46e5918U, 0x01ec9ab7U, 0xa8834f9aU,
+ 0x65e6956eU, 0x7eaaffe6U, 0x0821bccfU, 0xe6ef15e8U,
+ 0xd9bae79bU, 0xce4a6f36U, 0xd4ea9f09U, 0xd629b07cU,
+ 0xaf31a4b2U, 0x312a3f23U, 0x30c6a594U, 0xc035a266U,
+ 0x37744ebcU, 0xa6fc82caU, 0xb0e090d0U, 0x1533a7d8U,
+ 0x4af10498U, 0xf741ecdaU, 0x0e7fcd50U, 0x2f1791f6U,
+ 0x8d764dd6U, 0x4d43efb0U, 0x54ccaa4dU, 0xdfe49604U,
+ 0xe39ed1b5U, 0x1b4c6a88U, 0xb8c12c1fU, 0x7f466551U,
+ 0x049d5eeaU, 0x5d018c35U, 0x73fa8774U, 0x2efb0b41U,
+ 0x5ab3671dU, 0x5292dbd2U, 0x33e91056U, 0x136dd647U,
+ 0x8c9ad761U, 0x7a37a10cU, 0x8e59f814U, 0x89eb133cU,
+ 0xeecea927U, 0x35b761c9U, 0xede11ce5U, 0x3c7a47b1U,
+ 0x599cd2dfU, 0x3f55f273U, 0x791814ceU, 0xbf73c737U,
+ 0xea53f7cdU, 0x5b5ffdaaU, 0x14df3d6fU, 0x867844dbU,
+ 0x81caaff3U, 0x3eb968c4U, 0x2c382434U, 0x5fc2a340U,
+ 0x72161dc3U, 0x0cbce225U, 0x8b283c49U, 0x41ff0d95U,
+ 0x7139a801U, 0xde080cb3U, 0x9cd8b4e4U, 0x906456c1U,
+ 0x617bcb84U, 0x70d532b6U, 0x74486c5cU, 0x42d0b857U,
+};
+static const uint32_t Td2[256] = {
+ 0xa75051f4U, 0x65537e41U, 0xa4c31a17U, 0x5e963a27U,
+ 0x6bcb3babU, 0x45f11f9dU, 0x58abacfaU, 0x03934be3U,
+ 0xfa552030U, 0x6df6ad76U, 0x769188ccU, 0x4c25f502U,
+ 0xd7fc4fe5U, 0xcbd7c52aU, 0x44802635U, 0xa38fb562U,
+ 0x5a49deb1U, 0x1b6725baU, 0x0e9845eaU, 0xc0e15dfeU,
+ 0x7502c32fU, 0xf012814cU, 0x97a38d46U, 0xf9c66bd3U,
+ 0x5fe7038fU, 0x9c951592U, 0x7aebbf6dU, 0x59da9552U,
+ 0x832dd4beU, 0x21d35874U, 0x692949e0U, 0xc8448ec9U,
+ 0x896a75c2U, 0x7978f48eU, 0x3e6b9958U, 0x71dd27b9U,
+ 0x4fb6bee1U, 0xad17f088U, 0xac66c920U, 0x3ab47dceU,
+ 0x4a1863dfU, 0x3182e51aU, 0x33609751U, 0x7f456253U,
+ 0x77e0b164U, 0xae84bb6bU, 0xa01cfe81U, 0x2b94f908U,
+ 0x68587048U, 0xfd198f45U, 0x6c8794deU, 0xf8b7527bU,
+ 0xd323ab73U, 0x02e2724bU, 0x8f57e31fU, 0xab2a6655U,
+ 0x2807b2ebU, 0xc2032fb5U, 0x7b9a86c5U, 0x08a5d337U,
+ 0x87f23028U, 0xa5b223bfU, 0x6aba0203U, 0x825ced16U,
+ 0x1c2b8acfU, 0xb492a779U, 0xf2f0f307U, 0xe2a14e69U,
+ 0xf4cd65daU, 0xbed50605U, 0x621fd134U, 0xfe8ac4a6U,
+ 0x539d342eU, 0x55a0a2f3U, 0xe132058aU, 0xeb75a4f6U,
+ 0xec390b83U, 0xefaa4060U, 0x9f065e71U, 0x1051bd6eU,
+
+ 0x8af93e21U, 0x063d96ddU, 0x05aedd3eU, 0xbd464de6U,
+ 0x8db59154U, 0x5d0571c4U, 0xd46f0406U, 0x15ff6050U,
+ 0xfb241998U, 0xe997d6bdU, 0x43cc8940U, 0x9e7767d9U,
+ 0x42bdb0e8U, 0x8b880789U, 0x5b38e719U, 0xeedb79c8U,
+ 0x0a47a17cU, 0x0fe97c42U, 0x1ec9f884U, 0x00000000U,
+ 0x86830980U, 0xed48322bU, 0x70ac1e11U, 0x724e6c5aU,
+ 0xfffbfd0eU, 0x38560f85U, 0xd51e3daeU, 0x3927362dU,
+ 0xd9640a0fU, 0xa621685cU, 0x54d19b5bU, 0x2e3a2436U,
+ 0x67b10c0aU, 0xe70f9357U, 0x96d2b4eeU, 0x919e1b9bU,
+ 0xc54f80c0U, 0x20a261dcU, 0x4b695a77U, 0x1a161c12U,
+ 0xba0ae293U, 0x2ae5c0a0U, 0xe0433c22U, 0x171d121bU,
+ 0x0d0b0e09U, 0xc7adf28bU, 0xa8b92db6U, 0xa9c8141eU,
+ 0x198557f1U, 0x074caf75U, 0xddbbee99U, 0x60fda37fU,
+ 0x269ff701U, 0xf5bc5c72U, 0x3bc54466U, 0x7e345bfbU,
+ 0x29768b43U, 0xc6dccb23U, 0xfc68b6edU, 0xf163b8e4U,
+ 0xdccad731U, 0x85104263U, 0x22401397U, 0x112084c6U,
+ 0x247d854aU, 0x3df8d2bbU, 0x3211aef9U, 0xa16dc729U,
+ 0x2f4b1d9eU, 0x30f3dcb2U, 0x52ec0d86U, 0xe3d077c1U,
+ 0x166c2bb3U, 0xb999a970U, 0x48fa1194U, 0x642247e9U,
+ 0x8cc4a8fcU, 0x3f1aa0f0U, 0x2cd8567dU, 0x90ef2233U,
+ 0x4ec78749U, 0xd1c1d938U, 0xa2fe8ccaU, 0x0b3698d4U,
+ 0x81cfa6f5U, 0xde28a57aU, 0x8e26dab7U, 0xbfa43fadU,
+ 0x9de42c3aU, 0x920d5078U, 0xcc9b6a5fU, 0x4662547eU,
+ 0x13c2f68dU, 0xb8e890d8U, 0xf75e2e39U, 0xaff582c3U,
+ 0x80be9f5dU, 0x937c69d0U, 0x2da96fd5U, 0x12b3cf25U,
+ 0x993bc8acU, 0x7da71018U, 0x636ee89cU, 0xbb7bdb3bU,
+ 0x7809cd26U, 0x18f46e59U, 0xb701ec9aU, 0x9aa8834fU,
+ 0x6e65e695U, 0xe67eaaffU, 0xcf0821bcU, 0xe8e6ef15U,
+ 0x9bd9bae7U, 0x36ce4a6fU, 0x09d4ea9fU, 0x7cd629b0U,
+ 0xb2af31a4U, 0x23312a3fU, 0x9430c6a5U, 0x66c035a2U,
+ 0xbc37744eU, 0xcaa6fc82U, 0xd0b0e090U, 0xd81533a7U,
+ 0x984af104U, 0xdaf741ecU, 0x500e7fcdU, 0xf62f1791U,
+ 0xd68d764dU, 0xb04d43efU, 0x4d54ccaaU, 0x04dfe496U,
+ 0xb5e39ed1U, 0x881b4c6aU, 0x1fb8c12cU, 0x517f4665U,
+ 0xea049d5eU, 0x355d018cU, 0x7473fa87U, 0x412efb0bU,
+ 0x1d5ab367U, 0xd25292dbU, 0x5633e910U, 0x47136dd6U,
+ 0x618c9ad7U, 0x0c7a37a1U, 0x148e59f8U, 0x3c89eb13U,
+ 0x27eecea9U, 0xc935b761U, 0xe5ede11cU, 0xb13c7a47U,
+ 0xdf599cd2U, 0x733f55f2U, 0xce791814U, 0x37bf73c7U,
+ 0xcdea53f7U, 0xaa5b5ffdU, 0x6f14df3dU, 0xdb867844U,
+ 0xf381caafU, 0xc43eb968U, 0x342c3824U, 0x405fc2a3U,
+ 0xc372161dU, 0x250cbce2U, 0x498b283cU, 0x9541ff0dU,
+ 0x017139a8U, 0xb3de080cU, 0xe49cd8b4U, 0xc1906456U,
+ 0x84617bcbU, 0xb670d532U, 0x5c74486cU, 0x5742d0b8U,
+};
+static const uint32_t Td3[256] = {
+ 0xf4a75051U, 0x4165537eU, 0x17a4c31aU, 0x275e963aU,
+ 0xab6bcb3bU, 0x9d45f11fU, 0xfa58abacU, 0xe303934bU,
+ 0x30fa5520U, 0x766df6adU, 0xcc769188U, 0x024c25f5U,
+ 0xe5d7fc4fU, 0x2acbd7c5U, 0x35448026U, 0x62a38fb5U,
+ 0xb15a49deU, 0xba1b6725U, 0xea0e9845U, 0xfec0e15dU,
+ 0x2f7502c3U, 0x4cf01281U, 0x4697a38dU, 0xd3f9c66bU,
+ 0x8f5fe703U, 0x929c9515U, 0x6d7aebbfU, 0x5259da95U,
+ 0xbe832dd4U, 0x7421d358U, 0xe0692949U, 0xc9c8448eU,
+ 0xc2896a75U, 0x8e7978f4U, 0x583e6b99U, 0xb971dd27U,
+ 0xe14fb6beU, 0x88ad17f0U, 0x20ac66c9U, 0xce3ab47dU,
+ 0xdf4a1863U, 0x1a3182e5U, 0x51336097U, 0x537f4562U,
+ 0x6477e0b1U, 0x6bae84bbU, 0x81a01cfeU, 0x082b94f9U,
+ 0x48685870U, 0x45fd198fU, 0xde6c8794U, 0x7bf8b752U,
+ 0x73d323abU, 0x4b02e272U, 0x1f8f57e3U, 0x55ab2a66U,
+ 0xeb2807b2U, 0xb5c2032fU, 0xc57b9a86U, 0x3708a5d3U,
+ 0x2887f230U, 0xbfa5b223U, 0x036aba02U, 0x16825cedU,
+ 0xcf1c2b8aU, 0x79b492a7U, 0x07f2f0f3U, 0x69e2a14eU,
+ 0xdaf4cd65U, 0x05bed506U, 0x34621fd1U, 0xa6fe8ac4U,
+ 0x2e539d34U, 0xf355a0a2U, 0x8ae13205U, 0xf6eb75a4U,
+ 0x83ec390bU, 0x60efaa40U, 0x719f065eU, 0x6e1051bdU,
+ 0x218af93eU, 0xdd063d96U, 0x3e05aeddU, 0xe6bd464dU,
+ 0x548db591U, 0xc45d0571U, 0x06d46f04U, 0x5015ff60U,
+ 0x98fb2419U, 0xbde997d6U, 0x4043cc89U, 0xd99e7767U,
+ 0xe842bdb0U, 0x898b8807U, 0x195b38e7U, 0xc8eedb79U,
+ 0x7c0a47a1U, 0x420fe97cU, 0x841ec9f8U, 0x00000000U,
+ 0x80868309U, 0x2bed4832U, 0x1170ac1eU, 0x5a724e6cU,
+ 0x0efffbfdU, 0x8538560fU, 0xaed51e3dU, 0x2d392736U,
+ 0x0fd9640aU, 0x5ca62168U, 0x5b54d19bU, 0x362e3a24U,
+ 0x0a67b10cU, 0x57e70f93U, 0xee96d2b4U, 0x9b919e1bU,
+ 0xc0c54f80U, 0xdc20a261U, 0x774b695aU, 0x121a161cU,
+ 0x93ba0ae2U, 0xa02ae5c0U, 0x22e0433cU, 0x1b171d12U,
+ 0x090d0b0eU, 0x8bc7adf2U, 0xb6a8b92dU, 0x1ea9c814U,
+ 0xf1198557U, 0x75074cafU, 0x99ddbbeeU, 0x7f60fda3U,
+ 0x01269ff7U, 0x72f5bc5cU, 0x663bc544U, 0xfb7e345bU,
+ 0x4329768bU, 0x23c6dccbU, 0xedfc68b6U, 0xe4f163b8U,
+ 0x31dccad7U, 0x63851042U, 0x97224013U, 0xc6112084U,
+ 0x4a247d85U, 0xbb3df8d2U, 0xf93211aeU, 0x29a16dc7U,
+ 0x9e2f4b1dU, 0xb230f3dcU, 0x8652ec0dU, 0xc1e3d077U,
+ 0xb3166c2bU, 0x70b999a9U, 0x9448fa11U, 0xe9642247U,
+ 0xfc8cc4a8U, 0xf03f1aa0U, 0x7d2cd856U, 0x3390ef22U,
+ 0x494ec787U, 0x38d1c1d9U, 0xcaa2fe8cU, 0xd40b3698U,
+ 0xf581cfa6U, 0x7ade28a5U, 0xb78e26daU, 0xadbfa43fU,
+ 0x3a9de42cU, 0x78920d50U, 0x5fcc9b6aU, 0x7e466254U,
+ 0x8d13c2f6U, 0xd8b8e890U, 0x39f75e2eU, 0xc3aff582U,
+ 0x5d80be9fU, 0xd0937c69U, 0xd52da96fU, 0x2512b3cfU,
+ 0xac993bc8U, 0x187da710U, 0x9c636ee8U, 0x3bbb7bdbU,
+ 0x267809cdU, 0x5918f46eU, 0x9ab701ecU, 0x4f9aa883U,
+ 0x956e65e6U, 0xffe67eaaU, 0xbccf0821U, 0x15e8e6efU,
+ 0xe79bd9baU, 0x6f36ce4aU, 0x9f09d4eaU, 0xb07cd629U,
+ 0xa4b2af31U, 0x3f23312aU, 0xa59430c6U, 0xa266c035U,
+ 0x4ebc3774U, 0x82caa6fcU, 0x90d0b0e0U, 0xa7d81533U,
+ 0x04984af1U, 0xecdaf741U, 0xcd500e7fU, 0x91f62f17U,
+ 0x4dd68d76U, 0xefb04d43U, 0xaa4d54ccU, 0x9604dfe4U,
+ 0xd1b5e39eU, 0x6a881b4cU, 0x2c1fb8c1U, 0x65517f46U,
+ 0x5eea049dU, 0x8c355d01U, 0x877473faU, 0x0b412efbU,
+ 0x671d5ab3U, 0xdbd25292U, 0x105633e9U, 0xd647136dU,
+ 0xd7618c9aU, 0xa10c7a37U, 0xf8148e59U, 0x133c89ebU,
+ 0xa927eeceU, 0x61c935b7U, 0x1ce5ede1U, 0x47b13c7aU,
+ 0xd2df599cU, 0xf2733f55U, 0x14ce7918U, 0xc737bf73U,
+ 0xf7cdea53U, 0xfdaa5b5fU, 0x3d6f14dfU, 0x44db8678U,
+ 0xaff381caU, 0x68c43eb9U, 0x24342c38U, 0xa3405fc2U,
+ 0x1dc37216U, 0xe2250cbcU, 0x3c498b28U, 0x0d9541ffU,
+ 0xa8017139U, 0x0cb3de08U, 0xb4e49cd8U, 0x56c19064U,
+ 0xcb84617bU, 0x32b670d5U, 0x6c5c7448U, 0xb85742d0U,
+};
+static const uint32_t Td4[256] = {
+ 0x52525252U, 0x09090909U, 0x6a6a6a6aU, 0xd5d5d5d5U,
+ 0x30303030U, 0x36363636U, 0xa5a5a5a5U, 0x38383838U,
+ 0xbfbfbfbfU, 0x40404040U, 0xa3a3a3a3U, 0x9e9e9e9eU,
+ 0x81818181U, 0xf3f3f3f3U, 0xd7d7d7d7U, 0xfbfbfbfbU,
+ 0x7c7c7c7cU, 0xe3e3e3e3U, 0x39393939U, 0x82828282U,
+ 0x9b9b9b9bU, 0x2f2f2f2fU, 0xffffffffU, 0x87878787U,
+ 0x34343434U, 0x8e8e8e8eU, 0x43434343U, 0x44444444U,
+ 0xc4c4c4c4U, 0xdedededeU, 0xe9e9e9e9U, 0xcbcbcbcbU,
+ 0x54545454U, 0x7b7b7b7bU, 0x94949494U, 0x32323232U,
+ 0xa6a6a6a6U, 0xc2c2c2c2U, 0x23232323U, 0x3d3d3d3dU,
+ 0xeeeeeeeeU, 0x4c4c4c4cU, 0x95959595U, 0x0b0b0b0bU,
+ 0x42424242U, 0xfafafafaU, 0xc3c3c3c3U, 0x4e4e4e4eU,
+ 0x08080808U, 0x2e2e2e2eU, 0xa1a1a1a1U, 0x66666666U,
+ 0x28282828U, 0xd9d9d9d9U, 0x24242424U, 0xb2b2b2b2U,
+ 0x76767676U, 0x5b5b5b5bU, 0xa2a2a2a2U, 0x49494949U,
+ 0x6d6d6d6dU, 0x8b8b8b8bU, 0xd1d1d1d1U, 0x25252525U,
+ 0x72727272U, 0xf8f8f8f8U, 0xf6f6f6f6U, 0x64646464U,
+ 0x86868686U, 0x68686868U, 0x98989898U, 0x16161616U,
+ 0xd4d4d4d4U, 0xa4a4a4a4U, 0x5c5c5c5cU, 0xccccccccU,
+ 0x5d5d5d5dU, 0x65656565U, 0xb6b6b6b6U, 0x92929292U,
+ 0x6c6c6c6cU, 0x70707070U, 0x48484848U, 0x50505050U,
+ 0xfdfdfdfdU, 0xededededU, 0xb9b9b9b9U, 0xdadadadaU,
+ 0x5e5e5e5eU, 0x15151515U, 0x46464646U, 0x57575757U,
+ 0xa7a7a7a7U, 0x8d8d8d8dU, 0x9d9d9d9dU, 0x84848484U,
+ 0x90909090U, 0xd8d8d8d8U, 0xababababU, 0x00000000U,
+ 0x8c8c8c8cU, 0xbcbcbcbcU, 0xd3d3d3d3U, 0x0a0a0a0aU,
+ 0xf7f7f7f7U, 0xe4e4e4e4U, 0x58585858U, 0x05050505U,
+ 0xb8b8b8b8U, 0xb3b3b3b3U, 0x45454545U, 0x06060606U,
+ 0xd0d0d0d0U, 0x2c2c2c2cU, 0x1e1e1e1eU, 0x8f8f8f8fU,
+ 0xcacacacaU, 0x3f3f3f3fU, 0x0f0f0f0fU, 0x02020202U,
+ 0xc1c1c1c1U, 0xafafafafU, 0xbdbdbdbdU, 0x03030303U,
+ 0x01010101U, 0x13131313U, 0x8a8a8a8aU, 0x6b6b6b6bU,
+ 0x3a3a3a3aU, 0x91919191U, 0x11111111U, 0x41414141U,
+ 0x4f4f4f4fU, 0x67676767U, 0xdcdcdcdcU, 0xeaeaeaeaU,
+ 0x97979797U, 0xf2f2f2f2U, 0xcfcfcfcfU, 0xcecececeU,
+ 0xf0f0f0f0U, 0xb4b4b4b4U, 0xe6e6e6e6U, 0x73737373U,
+ 0x96969696U, 0xacacacacU, 0x74747474U, 0x22222222U,
+ 0xe7e7e7e7U, 0xadadadadU, 0x35353535U, 0x85858585U,
+ 0xe2e2e2e2U, 0xf9f9f9f9U, 0x37373737U, 0xe8e8e8e8U,
+ 0x1c1c1c1cU, 0x75757575U, 0xdfdfdfdfU, 0x6e6e6e6eU,
+ 0x47474747U, 0xf1f1f1f1U, 0x1a1a1a1aU, 0x71717171U,
+ 0x1d1d1d1dU, 0x29292929U, 0xc5c5c5c5U, 0x89898989U,
+ 0x6f6f6f6fU, 0xb7b7b7b7U, 0x62626262U, 0x0e0e0e0eU,
+ 0xaaaaaaaaU, 0x18181818U, 0xbebebebeU, 0x1b1b1b1bU,
+ 0xfcfcfcfcU, 0x56565656U, 0x3e3e3e3eU, 0x4b4b4b4bU,
+ 0xc6c6c6c6U, 0xd2d2d2d2U, 0x79797979U, 0x20202020U,
+ 0x9a9a9a9aU, 0xdbdbdbdbU, 0xc0c0c0c0U, 0xfefefefeU,
+ 0x78787878U, 0xcdcdcdcdU, 0x5a5a5a5aU, 0xf4f4f4f4U,
+ 0x1f1f1f1fU, 0xddddddddU, 0xa8a8a8a8U, 0x33333333U,
+ 0x88888888U, 0x07070707U, 0xc7c7c7c7U, 0x31313131U,
+ 0xb1b1b1b1U, 0x12121212U, 0x10101010U, 0x59595959U,
+ 0x27272727U, 0x80808080U, 0xececececU, 0x5f5f5f5fU,
+ 0x60606060U, 0x51515151U, 0x7f7f7f7fU, 0xa9a9a9a9U,
+ 0x19191919U, 0xb5b5b5b5U, 0x4a4a4a4aU, 0x0d0d0d0dU,
+ 0x2d2d2d2dU, 0xe5e5e5e5U, 0x7a7a7a7aU, 0x9f9f9f9fU,
+ 0x93939393U, 0xc9c9c9c9U, 0x9c9c9c9cU, 0xefefefefU,
+ 0xa0a0a0a0U, 0xe0e0e0e0U, 0x3b3b3b3bU, 0x4d4d4d4dU,
+ 0xaeaeaeaeU, 0x2a2a2a2aU, 0xf5f5f5f5U, 0xb0b0b0b0U,
+ 0xc8c8c8c8U, 0xebebebebU, 0xbbbbbbbbU, 0x3c3c3c3cU,
+ 0x83838383U, 0x53535353U, 0x99999999U, 0x61616161U,
+ 0x17171717U, 0x2b2b2b2bU, 0x04040404U, 0x7e7e7e7eU,
+ 0xbabababaU, 0x77777777U, 0xd6d6d6d6U, 0x26262626U,
+ 0xe1e1e1e1U, 0x69696969U, 0x14141414U, 0x63636363U,
+ 0x55555555U, 0x21212121U, 0x0c0c0c0cU, 0x7d7d7d7dU,
+};
+static const uint32_t rcon[] = {
+ 0x01000000, 0x02000000, 0x04000000, 0x08000000,
+ 0x10000000, 0x20000000, 0x40000000, 0x80000000,
+ 0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */
+};
+
+#define SWAP(x) (_lrotl(x, 8) & 0x00ff00ff | _lrotr(x, 8) & 0xff00ff00)
+
+#ifdef _MSC_VER
+#define GETU32(p) SWAP(*((uint32_t *)(p)))
+#define PUTU32(ct, st) { *((uint32_t *)(ct)) = SWAP((st)); }
+#else
+#define GETU32(pt) (((uint32_t)(pt)[0] << 24) ^ ((uint32_t)(pt)[1] << 16) ^ ((uint32_t)(pt)[2] << 8) ^ ((uint32_t)(pt)[3]))
+#define PUTU32(ct, st) { (ct)[0] = (uint8_t)((st) >> 24); (ct)[1] = (uint8_t)((st) >> 16); (ct)[2] = (uint8_t)((st) >> 8); (ct)[3] = (uint8_t)(st); }
+#endif
+
+/**
+ * Expand the cipher key into the encryption key schedule.
+ *
+ * @return the number of rounds for the given cipher key size.
+ */
+int rijndaelKeySetupEnc(uint32_t rk[/*4*(Nr + 1)*/], const uint8_t cipherKey[], int keyBits) {
+ int i = 0;
+ uint32_t temp;
+
+ rk[0] = GETU32(cipherKey );
+ rk[1] = GETU32(cipherKey + 4);
+ rk[2] = GETU32(cipherKey + 8);
+ rk[3] = GETU32(cipherKey + 12);
+ if (keyBits == 128) {
+ for (;;) {
+ temp = rk[3];
+ rk[4] = rk[0] ^
+ (Te4[(temp >> 16) & 0xff] & 0xff000000) ^
+ (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^
+ (Te4[(temp ) & 0xff] & 0x0000ff00) ^
+ (Te4[(temp >> 24) ] & 0x000000ff) ^
+ rcon[i];
+ rk[5] = rk[1] ^ rk[4];
+ rk[6] = rk[2] ^ rk[5];
+ rk[7] = rk[3] ^ rk[6];
+ if (++i == 10) {
+ return 10;
+ }
+ rk += 4;
+ }
+ }
+ rk[4] = GETU32(cipherKey + 16);
+ rk[5] = GETU32(cipherKey + 20);
+ if (keyBits == 192) {
+ for (;;) {
+ temp = rk[ 5];
+ rk[ 6] = rk[ 0] ^
+ (Te4[(temp >> 16) & 0xff] & 0xff000000) ^
+ (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^
+ (Te4[(temp ) & 0xff] & 0x0000ff00) ^
+ (Te4[(temp >> 24) ] & 0x000000ff) ^
+ rcon[i];
+ rk[ 7] = rk[ 1] ^ rk[ 6];
+ rk[ 8] = rk[ 2] ^ rk[ 7];
+ rk[ 9] = rk[ 3] ^ rk[ 8];
+ if (++i == 8) {
+ return 12;
+ }
+ rk[10] = rk[ 4] ^ rk[ 9];
+ rk[11] = rk[ 5] ^ rk[10];
+ rk += 6;
+ }
+ }
+ rk[6] = GETU32(cipherKey + 24);
+ rk[7] = GETU32(cipherKey + 28);
+ if (keyBits == 256) {
+ for (;;) {
+ temp = rk[ 7];
+ rk[ 8] = rk[ 0] ^
+ (Te4[(temp >> 16) & 0xff] & 0xff000000) ^
+ (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^
+ (Te4[(temp ) & 0xff] & 0x0000ff00) ^
+ (Te4[(temp >> 24) ] & 0x000000ff) ^
+ rcon[i];
+ rk[ 9] = rk[ 1] ^ rk[ 8];
+ rk[10] = rk[ 2] ^ rk[ 9];
+ rk[11] = rk[ 3] ^ rk[10];
+ if (++i == 7) {
+ return 14;
+ }
+ temp = rk[11];
+ rk[12] = rk[ 4] ^
+ (Te4[(temp >> 24) ] & 0xff000000) ^
+ (Te4[(temp >> 16) & 0xff] & 0x00ff0000) ^
+ (Te4[(temp >> 8) & 0xff] & 0x0000ff00) ^
+ (Te4[(temp ) & 0xff] & 0x000000ff);
+ rk[13] = rk[ 5] ^ rk[12];
+ rk[14] = rk[ 6] ^ rk[13];
+ rk[15] = rk[ 7] ^ rk[14];
+
+ rk += 8;
+ }
+ }
+ return 0;
+}
+
+/**
+ * Expand the cipher key into the decryption key schedule.
+ *
+ * @return the number of rounds for the given cipher key size.
+ */
+int rijndaelKeySetupDec(uint32_t rk[/*4*(Nr + 1)*/], const uint8_t cipherKey[], int keyBits) {
+ int Nr, i, j;
+ uint32_t temp;
+
+ /* expand the cipher key: */
+ Nr = rijndaelKeySetupEnc(rk, cipherKey, keyBits);
+ /* invert the order of the round keys: */
+ for (i = 0, j = 4*Nr; i < j; i += 4, j -= 4) {
+ temp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp;
+ temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp;
+ temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp;
+ temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp;
+ }
+ /* apply the inverse MixColumn transform to all round keys but the first and the last: */
+ for (i = 1; i < Nr; i++) {
+ rk += 4;
+ rk[0] =
+ Td0[Te4[(rk[0] >> 24) ] & 0xff] ^
+ Td1[Te4[(rk[0] >> 16) & 0xff] & 0xff] ^
+ Td2[Te4[(rk[0] >> 8) & 0xff] & 0xff] ^
+ Td3[Te4[(rk[0] ) & 0xff] & 0xff];
+ rk[1] =
+ Td0[Te4[(rk[1] >> 24) ] & 0xff] ^
+ Td1[Te4[(rk[1] >> 16) & 0xff] & 0xff] ^
+ Td2[Te4[(rk[1] >> 8) & 0xff] & 0xff] ^
+ Td3[Te4[(rk[1] ) & 0xff] & 0xff];
+ rk[2] =
+ Td0[Te4[(rk[2] >> 24) ] & 0xff] ^
+ Td1[Te4[(rk[2] >> 16) & 0xff] & 0xff] ^
+ Td2[Te4[(rk[2] >> 8) & 0xff] & 0xff] ^
+ Td3[Te4[(rk[2] ) & 0xff] & 0xff];
+ rk[3] =
+ Td0[Te4[(rk[3] >> 24) ] & 0xff] ^
+ Td1[Te4[(rk[3] >> 16) & 0xff] & 0xff] ^
+ Td2[Te4[(rk[3] >> 8) & 0xff] & 0xff] ^
+ Td3[Te4[(rk[3] ) & 0xff] & 0xff];
+ }
+ return Nr;
+}
+
+void rijndaelEncrypt(const uint32_t rk[/*4*(Nr + 1)*/], int Nr, const uint8_t pt[16], uint8_t ct[16]) {
+ uint32_t s0, s1, s2, s3, t0, t1, t2, t3;
+#ifndef FULL_UNROLL
+ int r;
+#endif /* ?FULL_UNROLL */
+
+ /*
+ * map byte array block to cipher state
+ * and add initial round key:
+ */
+ s0 = GETU32(pt ) ^ rk[0];
+ s1 = GETU32(pt + 4) ^ rk[1];
+ s2 = GETU32(pt + 8) ^ rk[2];
+ s3 = GETU32(pt + 12) ^ rk[3];
+#ifdef FULL_UNROLL
+ /* round 1: */
+ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[ 4];
+ t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[ 5];
+ t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[ 6];
+ t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[ 7];
+ /* round 2: */
+ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[ 8];
+ s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[ 9];
+ s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[10];
+ s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[11];
+ /* round 3: */
+ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[12];
+ t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[13];
+ t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[14];
+ t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[15];
+ /* round 4: */
+ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[16];
+ s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[17];
+ s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[18];
+ s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[19];
+ /* round 5: */
+ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[20];
+ t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[21];
+ t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[22];
+ t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[23];
+ /* round 6: */
+ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[24];
+ s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[25];
+ s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[26];
+ s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[27];
+ /* round 7: */
+ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[28];
+ t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[29];
+ t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[30];
+ t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[31];
+ /* round 8: */
+ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[32];
+ s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[33];
+ s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[34];
+ s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[35];
+ /* round 9: */
+ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[36];
+ t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[37];
+ t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[38];
+ t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[39];
+ if (Nr > 10) {
+ /* round 10: */
+ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[40];
+ s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[41];
+ s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[42];
+ s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[43];
+ /* round 11: */
+ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[44];
+ t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[45];
+ t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[46];
+ t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[47];
+ if (Nr > 12) {
+ /* round 12: */
+ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[48];
+ s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[49];
+ s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[50];
+ s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[51];
+ /* round 13: */
+ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[52];
+ t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[53];
+ t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[54];
+ t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[55];
+ }
+ }
+ rk += Nr << 2;
+#else /* !FULL_UNROLL */
+ /*
+ * Nr - 1 full rounds:
+ */
+ r = Nr >> 1;
+ for (;;) {
+ t0 =
+ Te0[(s0 >> 24) ] ^
+ Te1[(s1 >> 16) & 0xff] ^
+ Te2[(s2 >> 8) & 0xff] ^
+ Te3[(s3 ) & 0xff] ^
+ rk[4];
+ t1 =
+ Te0[(s1 >> 24) ] ^
+ Te1[(s2 >> 16) & 0xff] ^
+ Te2[(s3 >> 8) & 0xff] ^
+ Te3[(s0 ) & 0xff] ^
+ rk[5];
+ t2 =
+ Te0[(s2 >> 24) ] ^
+ Te1[(s3 >> 16) & 0xff] ^
+ Te2[(s0 >> 8) & 0xff] ^
+ Te3[(s1 ) & 0xff] ^
+ rk[6];
+ t3 =
+ Te0[(s3 >> 24) ] ^
+ Te1[(s0 >> 16) & 0xff] ^
+ Te2[(s1 >> 8) & 0xff] ^
+ Te3[(s2 ) & 0xff] ^
+ rk[7];
+
+ rk += 8;
+ if (--r == 0) {
+ break;
+ }
+
+ s0 =
+ Te0[(t0 >> 24) ] ^
+ Te1[(t1 >> 16) & 0xff] ^
+ Te2[(t2 >> 8) & 0xff] ^
+ Te3[(t3 ) & 0xff] ^
+ rk[0];
+ s1 =
+ Te0[(t1 >> 24) ] ^
+ Te1[(t2 >> 16) & 0xff] ^
+ Te2[(t3 >> 8) & 0xff] ^
+ Te3[(t0 ) & 0xff] ^
+ rk[1];
+ s2 =
+ Te0[(t2 >> 24) ] ^
+ Te1[(t3 >> 16) & 0xff] ^
+ Te2[(t0 >> 8) & 0xff] ^
+ Te3[(t1 ) & 0xff] ^
+ rk[2];
+ s3 =
+ Te0[(t3 >> 24) ] ^
+ Te1[(t0 >> 16) & 0xff] ^
+ Te2[(t1 >> 8) & 0xff] ^
+ Te3[(t2 ) & 0xff] ^
+ rk[3];
+ }
+#endif /* ?FULL_UNROLL */
+ /*
+ * apply last round and
+ * map cipher state to byte array block:
+ */
+ s0 =
+ (Te4[(t0 >> 24) ] & 0xff000000) ^
+ (Te4[(t1 >> 16) & 0xff] & 0x00ff0000) ^
+ (Te4[(t2 >> 8) & 0xff] & 0x0000ff00) ^
+ (Te4[(t3 ) & 0xff] & 0x000000ff) ^
+ rk[0];
+ PUTU32(ct , s0);
+ s1 =
+ (Te4[(t1 >> 24) ] & 0xff000000) ^
+ (Te4[(t2 >> 16) & 0xff] & 0x00ff0000) ^
+ (Te4[(t3 >> 8) & 0xff] & 0x0000ff00) ^
+ (Te4[(t0 ) & 0xff] & 0x000000ff) ^
+ rk[1];
+ PUTU32(ct + 4, s1);
+ s2 =
+ (Te4[(t2 >> 24) ] & 0xff000000) ^
+ (Te4[(t3 >> 16) & 0xff] & 0x00ff0000) ^
+ (Te4[(t0 >> 8) & 0xff] & 0x0000ff00) ^
+ (Te4[(t1 ) & 0xff] & 0x000000ff) ^
+ rk[2];
+ PUTU32(ct + 8, s2);
+ s3 =
+ (Te4[(t3 >> 24) ] & 0xff000000) ^
+ (Te4[(t0 >> 16) & 0xff] & 0x00ff0000) ^
+ (Te4[(t1 >> 8) & 0xff] & 0x0000ff00) ^
+ (Te4[(t2 ) & 0xff] & 0x000000ff) ^
+ rk[3];
+ PUTU32(ct + 12, s3);
+}
+
+void rijndaelDecrypt(const uint32_t rk[/*4*(Nr + 1)*/], int Nr, const uint8_t ct[16], uint8_t pt[16]) {
+ uint32_t s0, s1, s2, s3, t0, t1, t2, t3;
+#ifndef FULL_UNROLL
+ int r;
+#endif /* ?FULL_UNROLL */
+
+ /*
+ * map byte array block to cipher state
+ * and add initial round key:
+ */
+ s0 = GETU32(ct ) ^ rk[0];
+ s1 = GETU32(ct + 4) ^ rk[1];
+ s2 = GETU32(ct + 8) ^ rk[2];
+ s3 = GETU32(ct + 12) ^ rk[3];
+#ifdef FULL_UNROLL
+ /* round 1: */
+ t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[ 4];
+ t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[ 5];
+ t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[ 6];
+ t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[ 7];
+ /* round 2: */
+ s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[ 8];
+ s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[ 9];
+ s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[10];
+ s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[11];
+ /* round 3: */
+ t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[12];
+ t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[13];
+ t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[14];
+ t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[15];
+ /* round 4: */
+ s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[16];
+ s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[17];
+ s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[18];
+ s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[19];
+ /* round 5: */
+ t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[20];
+ t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[21];
+ t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[22];
+ t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[23];
+ /* round 6: */
+ s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[24];
+ s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[25];
+ s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[26];
+ s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[27];
+ /* round 7: */
+ t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[28];
+ t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[29];
+ t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[30];
+ t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[31];
+ /* round 8: */
+ s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[32];
+ s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[33];
+ s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[34];
+ s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[35];
+ /* round 9: */
+ t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[36];
+ t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[37];
+ t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[38];
+ t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[39];
+ if (Nr > 10) {
+ /* round 10: */
+ s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[40];
+ s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[41];
+ s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[42];
+ s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[43];
+ /* round 11: */
+ t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[44];
+ t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[45];
+ t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[46];
+ t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[47];
+ if (Nr > 12) {
+ /* round 12: */
+ s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[48];
+ s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[49];
+ s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[50];
+ s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[51];
+ /* round 13: */
+ t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[52];
+ t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[53];
+ t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[54];
+ t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[55];
+ }
+ }
+ rk += Nr << 2;
+#else /* !FULL_UNROLL */
+ /*
+ * Nr - 1 full rounds:
+ */
+ r = Nr >> 1;
+ for (;;) {
+ t0 =
+ Td0[(s0 >> 24) ] ^
+ Td1[(s3 >> 16) & 0xff] ^
+ Td2[(s2 >> 8) & 0xff] ^
+ Td3[(s1 ) & 0xff] ^
+ rk[4];
+ t1 =
+ Td0[(s1 >> 24) ] ^
+ Td1[(s0 >> 16) & 0xff] ^
+ Td2[(s3 >> 8) & 0xff] ^
+ Td3[(s2 ) & 0xff] ^
+ rk[5];
+ t2 =
+ Td0[(s2 >> 24) ] ^
+ Td1[(s1 >> 16) & 0xff] ^
+ Td2[(s0 >> 8) & 0xff] ^
+ Td3[(s3 ) & 0xff] ^
+ rk[6];
+ t3 =
+ Td0[(s3 >> 24) ] ^
+ Td1[(s2 >> 16) & 0xff] ^
+ Td2[(s1 >> 8) & 0xff] ^
+ Td3[(s0 ) & 0xff] ^
+ rk[7];
+
+ rk += 8;
+ if (--r == 0) {
+ break;
+ }
+
+ s0 =
+ Td0[(t0 >> 24) ] ^
+ Td1[(t3 >> 16) & 0xff] ^
+ Td2[(t2 >> 8) & 0xff] ^
+ Td3[(t1 ) & 0xff] ^
+ rk[0];
+ s1 =
+ Td0[(t1 >> 24) ] ^
+ Td1[(t0 >> 16) & 0xff] ^
+ Td2[(t3 >> 8) & 0xff] ^
+ Td3[(t2 ) & 0xff] ^
+ rk[1];
+ s2 =
+ Td0[(t2 >> 24) ] ^
+ Td1[(t1 >> 16) & 0xff] ^
+ Td2[(t0 >> 8) & 0xff] ^
+ Td3[(t3 ) & 0xff] ^
+ rk[2];
+ s3 =
+ Td0[(t3 >> 24) ] ^
+ Td1[(t2 >> 16) & 0xff] ^
+ Td2[(t1 >> 8) & 0xff] ^
+ Td3[(t0 ) & 0xff] ^
+ rk[3];
+ }
+#endif /* ?FULL_UNROLL */
+ /*
+ * apply last round and
+ * map cipher state to byte array block:
+ */
+ s0 =
+ (Td4[(t0 >> 24) ] & 0xff000000) ^
+ (Td4[(t3 >> 16) & 0xff] & 0x00ff0000) ^
+ (Td4[(t2 >> 8) & 0xff] & 0x0000ff00) ^
+ (Td4[(t1 ) & 0xff] & 0x000000ff) ^
+ rk[0];
+ PUTU32(pt , s0);
+ s1 =
+ (Td4[(t1 >> 24) ] & 0xff000000) ^
+ (Td4[(t0 >> 16) & 0xff] & 0x00ff0000) ^
+ (Td4[(t3 >> 8) & 0xff] & 0x0000ff00) ^
+ (Td4[(t2 ) & 0xff] & 0x000000ff) ^
+ rk[1];
+ PUTU32(pt + 4, s1);
+ s2 =
+ (Td4[(t2 >> 24) ] & 0xff000000) ^
+ (Td4[(t1 >> 16) & 0xff] & 0x00ff0000) ^
+ (Td4[(t0 >> 8) & 0xff] & 0x0000ff00) ^
+ (Td4[(t3 ) & 0xff] & 0x000000ff) ^
+ rk[2];
+ PUTU32(pt + 8, s2);
+ s3 =
+ (Td4[(t3 >> 24) ] & 0xff000000) ^
+ (Td4[(t2 >> 16) & 0xff] & 0x00ff0000) ^
+ (Td4[(t1 >> 8) & 0xff] & 0x0000ff00) ^
+ (Td4[(t0 ) & 0xff] & 0x000000ff) ^
+ rk[3];
+ PUTU32(pt + 12, s3);
+}
diff --git a/third_party/heimdal/lib/hcrypto/rijndael-alg-fst.h b/third_party/heimdal/lib/hcrypto/rijndael-alg-fst.h
new file mode 100644
index 0000000..7e2e193
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rijndael-alg-fst.h
@@ -0,0 +1,46 @@
+/* $NetBSD: rijndael-alg-fst.h,v 1.2 2000/10/02 17:19:15 itojun Exp $ */
+/* $KAME: rijndael-alg-fst.h,v 1.5 2003/07/15 10:47:16 itojun Exp $ */
+/**
+ * rijndael-alg-fst.h
+ *
+ * @version 3.0 (December 2000)
+ *
+ * Optimised ANSI C code for the Rijndael cipher (now AES)
+ *
+ * @author Vincent Rijmen <vincent.rijmen@esat.kuleuven.ac.be>
+ * @author Antoon Bosselaers <antoon.bosselaers@esat.kuleuven.ac.be>
+ * @author Paulo Barreto <paulo.barreto@terra.com.br>
+ *
+ * This code is hereby placed in the public domain.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef __RIJNDAEL_ALG_FST_H
+#define __RIJNDAEL_ALG_FST_H
+
+/* symbol renaming */
+#define rijndaelKeySetupEnc _hc_rijndaelKeySetupEnc
+#define rijndaelKeySetupDec _hc_rijndaelKeySetupDec
+#define rijndaelEncrypt _hc_rijndaelEncrypt
+#define rijndaelDecrypt _hc_rijndaelDecrypt
+
+#define RIJNDAEL_MAXKC (256/32)
+#define RIJNDAEL_MAXKB (256/8)
+#define RIJNDAEL_MAXNR 14
+
+int rijndaelKeySetupEnc(uint32_t rk[/*4*(Nr + 1)*/], const uint8_t cipherKey[], int keyBits);
+int rijndaelKeySetupDec(uint32_t rk[/*4*(Nr + 1)*/], const uint8_t cipherKey[], int keyBits);
+void rijndaelEncrypt(const uint32_t rk[/*4*(Nr + 1)*/], int Nr, const uint8_t pt[16], uint8_t ct[16]);
+void rijndaelDecrypt(const uint32_t rk[/*4*(Nr + 1)*/], int Nr, const uint8_t ct[16], uint8_t pt[16]);
+
+#endif /* __RIJNDAEL_ALG_FST_H */
diff --git a/third_party/heimdal/lib/hcrypto/rnd_keys.c b/third_party/heimdal/lib/hcrypto/rnd_keys.c
new file mode 100644
index 0000000..ec35021
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rnd_keys.c
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#define HC_DEPRECATED
+
+#ifdef KRB5
+#include <krb5-types.h>
+#endif
+
+#include <des.h>
+#include <rand.h>
+
+#undef __attribute__
+#define __attribute__(X)
+
+void HC_DEPRECATED
+DES_rand_data(void *outdata, int size)
+{
+ RAND_bytes(outdata, size);
+}
+
+void HC_DEPRECATED
+DES_generate_random_block(DES_cblock *block)
+{
+ RAND_bytes(block, sizeof(*block));
+}
+
+#define DES_rand_data_key hc_DES_rand_data_key
+
+void HC_DEPRECATED
+DES_rand_data_key(DES_cblock *key);
+
+/*
+ * Generate a random DES key.
+ */
+
+void HC_DEPRECATED
+DES_rand_data_key(DES_cblock *key)
+{
+ DES_new_random_key(key);
+}
+
+void HC_DEPRECATED
+DES_set_sequence_number(void *ll)
+{
+}
+
+void HC_DEPRECATED
+DES_set_random_generator_seed(DES_cblock *seed)
+{
+ RAND_seed(seed, sizeof(*seed));
+}
+
+/**
+ * Generate a random des key using a random block, fixup parity and
+ * skip weak keys.
+ *
+ * @param key is set to a random key.
+ *
+ * @return 0 on success, non zero on random number generator failure.
+ *
+ * @ingroup hcrypto_des
+ */
+
+int HC_DEPRECATED
+DES_new_random_key(DES_cblock *key)
+{
+ do {
+ if (RAND_bytes(key, sizeof(*key)) != 1)
+ return 1;
+ DES_set_odd_parity(key);
+ } while(DES_is_weak_key(key));
+
+ return(0);
+}
+
+/**
+ * Seed the random number generator. Deprecated, use @ref page_rand
+ *
+ * @param seed a seed to seed that random number generate with.
+ *
+ * @ingroup hcrypto_des
+ */
+
+void HC_DEPRECATED
+DES_init_random_number_generator(DES_cblock *seed)
+{
+ RAND_seed(seed, sizeof(*seed));
+}
+
+/**
+ * Generate a random key, deprecated since it doesn't return an error
+ * code, use DES_new_random_key().
+ *
+ * @param key is set to a random key.
+ *
+ * @ingroup hcrypto_des
+ */
+
+void HC_DEPRECATED
+DES_random_key(DES_cblock *key)
+{
+ if (DES_new_random_key(key))
+ abort();
+}
diff --git a/third_party/heimdal/lib/hcrypto/rsa-gmp.c b/third_party/heimdal/lib/hcrypto/rsa-gmp.c
new file mode 100644
index 0000000..8fb28ed
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rsa-gmp.c
@@ -0,0 +1,584 @@
+/*
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+#include <krb5-types.h>
+#include <assert.h>
+
+#include <rsa.h>
+
+#ifdef HAVE_GMP
+
+#include <gmp.h>
+
+static void
+BN2mpz(mpz_t s, const BIGNUM *bn)
+{
+ size_t len;
+ void *p;
+
+ len = BN_num_bytes(bn);
+ p = malloc(len);
+ BN_bn2bin(bn, p);
+ mpz_init(s);
+ mpz_import(s, len, 1, 1, 1, 0, p);
+
+ free(p);
+}
+
+
+static BIGNUM *
+mpz2BN(mpz_t s)
+{
+ size_t size;
+ BIGNUM *bn;
+ void *p;
+
+ mpz_export(NULL, &size, 1, 1, 1, 0, s);
+ p = malloc(size);
+ if (p == NULL && size != 0)
+ return NULL;
+ mpz_export(p, &size, 1, 1, 1, 0, s);
+ bn = BN_bin2bn(p, size, NULL);
+ free(p);
+ return bn;
+}
+
+static int
+rsa_private_calculate(mpz_t in, mpz_t p, mpz_t q,
+ mpz_t dmp1, mpz_t dmq1, mpz_t iqmp,
+ mpz_t out)
+{
+ mpz_t vp, vq, u;
+ mpz_init(vp); mpz_init(vq); mpz_init(u);
+
+ /* vq = c ^ (d mod (q - 1)) mod q */
+ /* vp = c ^ (d mod (p - 1)) mod p */
+ mpz_fdiv_r(vp, in, p);
+ mpz_powm(vp, vp, dmp1, p);
+ mpz_fdiv_r(vq, in, q);
+ mpz_powm(vq, vq, dmq1, q);
+
+ /* C2 = 1/q mod p (iqmp) */
+ /* u = (vp - vq)C2 mod p. */
+ mpz_sub(u, vp, vq);
+#if 0
+ if (mp_int_compare_zero(&u) < 0)
+ mp_int_add(&u, p, &u);
+#endif
+ mpz_mul(u, iqmp, u);
+ mpz_fdiv_r(u, u, p);
+
+ /* c ^ d mod n = vq + u q */
+ mpz_mul(u, q, u);
+ mpz_add(out, u, vq);
+
+ mpz_clear(vp);
+ mpz_clear(vq);
+ mpz_clear(u);
+
+ return 0;
+}
+
+/*
+ *
+ */
+
+static int
+gmp_rsa_public_encrypt(int flen, const unsigned char* from,
+ unsigned char* to, RSA* rsa, int padding)
+{
+ unsigned char *p, *p0;
+ size_t size, padlen;
+ mpz_t enc, dec, n, e;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ size = RSA_size(rsa);
+
+ if (size < RSA_PKCS1_PADDING_SIZE || size - RSA_PKCS1_PADDING_SIZE < flen)
+ return -2;
+
+ BN2mpz(n, rsa->n);
+ BN2mpz(e, rsa->e);
+
+ p = p0 = malloc(size - 1);
+ if (p0 == NULL) {
+ mpz_clear(e);
+ mpz_clear(n);
+ return -3;
+ }
+
+ padlen = size - flen - 3;
+ assert(padlen >= 8);
+
+ *p++ = 2;
+ if (RAND_bytes(p, padlen) != 1) {
+ mpz_clear(e);
+ mpz_clear(n);
+ free(p0);
+ return -4;
+ }
+ while(padlen) {
+ if (*p == 0)
+ *p = 1;
+ padlen--;
+ p++;
+ }
+ *p++ = 0;
+ memcpy(p, from, flen);
+ p += flen;
+ assert((p - p0) == size - 1);
+
+ mpz_init(enc);
+ mpz_init(dec);
+ mpz_import(dec, size - 1, 1, 1, 1, 0, p0);
+ free(p0);
+
+ mpz_powm(enc, dec, e, n);
+
+ mpz_clear(dec);
+ mpz_clear(e);
+ mpz_clear(n);
+ {
+ size_t ssize;
+ mpz_export(to, &ssize, 1, 1, 1, 0, enc);
+ assert(size >= ssize);
+ size = ssize;
+ }
+ mpz_clear(enc);
+
+ return size;
+}
+
+static int
+gmp_rsa_public_decrypt(int flen, const unsigned char* from,
+ unsigned char* to, RSA* rsa, int padding)
+{
+ unsigned char *p;
+ size_t size;
+ mpz_t s, us, n, e;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ if (flen > RSA_size(rsa))
+ return -2;
+
+ BN2mpz(n, rsa->n);
+ BN2mpz(e, rsa->e);
+
+#if 0
+ /* Check that the exponent is larger then 3 */
+ if (mp_int_compare_value(&e, 3) <= 0) {
+ mp_int_clear(&n);
+ mp_int_clear(&e);
+ return -3;
+ }
+#endif
+
+ mpz_init(s);
+ mpz_init(us);
+ mpz_import(s, flen, 1, 1, 1, 0, rk_UNCONST(from));
+
+ if (mpz_cmp(s, n) >= 0) {
+ mpz_clear(n);
+ mpz_clear(e);
+ return -4;
+ }
+
+ mpz_powm(us, s, e, n);
+
+ mpz_clear(s);
+ mpz_clear(n);
+ mpz_clear(e);
+
+ p = to;
+
+ mpz_export(p, &size, 1, 1, 1, 0, us);
+ assert(size <= RSA_size(rsa));
+
+ mpz_clear(us);
+
+ /* head zero was skipped by mp_int_to_unsigned */
+ if (*p == 0)
+ return -6;
+ if (*p != 1)
+ return -7;
+ size--; p++;
+ while (size && *p == 0xff) {
+ size--; p++;
+ }
+ if (size == 0 || *p != 0)
+ return -8;
+ size--; p++;
+
+ memmove(to, p, size);
+
+ return size;
+}
+
+static int
+gmp_rsa_private_encrypt(int flen, const unsigned char* from,
+ unsigned char* to, RSA* rsa, int padding)
+{
+ unsigned char *p, *p0;
+ size_t size;
+ mpz_t in, out, n, e;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ size = RSA_size(rsa);
+
+ if (size < RSA_PKCS1_PADDING_SIZE || size - RSA_PKCS1_PADDING_SIZE < flen)
+ return -2;
+
+ p0 = p = malloc(size);
+ *p++ = 0;
+ *p++ = 1;
+ memset(p, 0xff, size - flen - 3);
+ p += size - flen - 3;
+ *p++ = 0;
+ memcpy(p, from, flen);
+ p += flen;
+ assert((p - p0) == size);
+
+ BN2mpz(n, rsa->n);
+ BN2mpz(e, rsa->e);
+
+ mpz_init(in);
+ mpz_init(out);
+ mpz_import(in, size, 1, 1, 1, 0, p0);
+ free(p0);
+
+#if 0
+ if(mp_int_compare_zero(&in) < 0 ||
+ mp_int_compare(&in, &n) >= 0) {
+ size = 0;
+ goto out;
+ }
+#endif
+
+ if (rsa->p && rsa->q && rsa->dmp1 && rsa->dmq1 && rsa->iqmp) {
+ mpz_t p, q, dmp1, dmq1, iqmp;
+
+ BN2mpz(p, rsa->p);
+ BN2mpz(q, rsa->q);
+ BN2mpz(dmp1, rsa->dmp1);
+ BN2mpz(dmq1, rsa->dmq1);
+ BN2mpz(iqmp, rsa->iqmp);
+
+ rsa_private_calculate(in, p, q, dmp1, dmq1, iqmp, out);
+
+ mpz_clear(p);
+ mpz_clear(q);
+ mpz_clear(dmp1);
+ mpz_clear(dmq1);
+ mpz_clear(iqmp);
+ } else {
+ mpz_t d;
+
+ BN2mpz(d, rsa->d);
+ mpz_powm(out, in, d, n);
+ mpz_clear(d);
+ }
+
+ {
+ size_t ssize;
+ mpz_export(to, &ssize, 1, 1, 1, 0, out);
+ assert(size >= ssize);
+ size = ssize;
+ }
+
+ mpz_clear(e);
+ mpz_clear(n);
+ mpz_clear(in);
+ mpz_clear(out);
+
+ return size;
+}
+
+static int
+gmp_rsa_private_decrypt(int flen, const unsigned char* from,
+ unsigned char* to, RSA* rsa, int padding)
+{
+ unsigned char *ptr;
+ size_t size;
+ mpz_t in, out, n, e;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ size = RSA_size(rsa);
+ if (flen > size)
+ return -2;
+
+ mpz_init(in);
+ mpz_init(out);
+
+ BN2mpz(n, rsa->n);
+ BN2mpz(e, rsa->e);
+
+ mpz_import(in, flen, 1, 1, 1, 0, from);
+
+ if(mpz_cmp_ui(in, 0) < 0 ||
+ mpz_cmp(in, n) >= 0) {
+ size = 0;
+ goto out;
+ }
+
+ if (rsa->p && rsa->q && rsa->dmp1 && rsa->dmq1 && rsa->iqmp) {
+ mpz_t p, q, dmp1, dmq1, iqmp;
+
+ BN2mpz(p, rsa->p);
+ BN2mpz(q, rsa->q);
+ BN2mpz(dmp1, rsa->dmp1);
+ BN2mpz(dmq1, rsa->dmq1);
+ BN2mpz(iqmp, rsa->iqmp);
+
+ rsa_private_calculate(in, p, q, dmp1, dmq1, iqmp, out);
+
+ mpz_clear(p);
+ mpz_clear(q);
+ mpz_clear(dmp1);
+ mpz_clear(dmq1);
+ mpz_clear(iqmp);
+ } else {
+ mpz_t d;
+
+#if 0
+ if(mp_int_compare_zero(&in) < 0 ||
+ mp_int_compare(&in, &n) >= 0)
+ return MP_RANGE;
+#endif
+
+ BN2mpz(d, rsa->d);
+ mpz_powm(out, in, d, n);
+ mpz_clear(d);
+ }
+
+ ptr = to;
+ {
+ size_t ssize;
+ mpz_export(ptr, &ssize, 1, 1, 1, 0, out);
+ assert(size >= ssize);
+ size = ssize;
+ }
+
+ /* head zero was skipped by mp_int_to_unsigned */
+ if (*ptr != 2)
+ return -3;
+ size--; ptr++;
+ while (size && *ptr != 0) {
+ size--; ptr++;
+ }
+ if (size == 0)
+ return -4;
+ size--; ptr++;
+
+ memmove(to, ptr, size);
+
+out:
+ mpz_clear(e);
+ mpz_clear(n);
+ mpz_clear(in);
+ mpz_clear(out);
+
+ return size;
+}
+
+static int
+random_num(mpz_t num, size_t len)
+{
+ unsigned char *p;
+
+ len = (len + 7) / 8;
+ p = malloc(len);
+ if (p == NULL)
+ return 1;
+ if (RAND_bytes(p, len) != 1) {
+ free(p);
+ return 1;
+ }
+ mpz_import(num, len, 1, 1, 1, 0, p);
+ free(p);
+ return 0;
+}
+
+
+static int
+gmp_rsa_generate_key(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb)
+{
+ mpz_t el, p, q, n, d, dmp1, dmq1, iqmp, t1, t2, t3;
+ int counter, ret;
+
+ if (bits < 789)
+ return -1;
+
+ ret = -1;
+
+ mpz_init(el);
+ mpz_init(p);
+ mpz_init(q);
+ mpz_init(n);
+ mpz_init(d);
+ mpz_init(dmp1);
+ mpz_init(dmq1);
+ mpz_init(iqmp);
+ mpz_init(t1);
+ mpz_init(t2);
+ mpz_init(t3);
+
+ BN2mpz(el, e);
+
+ /* generate p and q so that p != q and bits(pq) ~ bits */
+
+ counter = 0;
+ do {
+ BN_GENCB_call(cb, 2, counter++);
+ random_num(p, bits / 2 + 1);
+ mpz_nextprime(p, p);
+
+ mpz_sub_ui(t1, p, 1);
+ mpz_gcd(t2, t1, el);
+ } while(mpz_cmp_ui(t2, 1) != 0);
+
+ BN_GENCB_call(cb, 3, 0);
+
+ counter = 0;
+ do {
+ BN_GENCB_call(cb, 2, counter++);
+ random_num(q, bits / 2 + 1);
+ mpz_nextprime(q, q);
+
+ mpz_sub_ui(t1, q, 1);
+ mpz_gcd(t2, t1, el);
+ } while(mpz_cmp_ui(t2, 1) != 0);
+
+ /* make p > q */
+ if (mpz_cmp(p, q) < 0)
+ mpz_swap(p, q);
+
+ BN_GENCB_call(cb, 3, 1);
+
+ /* calculate n, n = p * q */
+ mpz_mul(n, p, q);
+
+ /* calculate d, d = 1/e mod (p - 1)(q - 1) */
+ mpz_sub_ui(t1, p, 1);
+ mpz_sub_ui(t2, q, 1);
+ mpz_mul(t3, t1, t2);
+ mpz_invert(d, el, t3);
+
+ /* calculate dmp1 dmp1 = d mod (p-1) */
+ mpz_mod(dmp1, d, t1);
+ /* calculate dmq1 dmq1 = d mod (q-1) */
+ mpz_mod(dmq1, d, t2);
+ /* calculate iqmp iqmp = 1/q mod p */
+ mpz_invert(iqmp, q, p);
+
+ /* fill in RSA key */
+
+ rsa->e = mpz2BN(el);
+ rsa->p = mpz2BN(p);
+ rsa->q = mpz2BN(q);
+ rsa->n = mpz2BN(n);
+ rsa->d = mpz2BN(d);
+ rsa->dmp1 = mpz2BN(dmp1);
+ rsa->dmq1 = mpz2BN(dmq1);
+ rsa->iqmp = mpz2BN(iqmp);
+
+ ret = 1;
+
+ mpz_clear(el);
+ mpz_clear(p);
+ mpz_clear(q);
+ mpz_clear(n);
+ mpz_clear(d);
+ mpz_clear(dmp1);
+ mpz_clear(dmq1);
+ mpz_clear(iqmp);
+ mpz_clear(t1);
+ mpz_clear(t2);
+ mpz_clear(t3);
+
+ return ret;
+}
+
+static int
+gmp_rsa_init(RSA *rsa)
+{
+ return 1;
+}
+
+static int
+gmp_rsa_finish(RSA *rsa)
+{
+ return 1;
+}
+
+const RSA_METHOD hc_rsa_gmp_method = {
+ "hcrypto GMP RSA",
+ gmp_rsa_public_encrypt,
+ gmp_rsa_public_decrypt,
+ gmp_rsa_private_encrypt,
+ gmp_rsa_private_decrypt,
+ NULL,
+ NULL,
+ gmp_rsa_init,
+ gmp_rsa_finish,
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ gmp_rsa_generate_key
+};
+
+#endif /* HAVE_GMP */
+
+/**
+ * RSA implementation using Gnu Multipresistion Library.
+ */
+
+const RSA_METHOD *
+RSA_gmp_method(void)
+{
+#ifdef HAVE_GMP
+ return &hc_rsa_gmp_method;
+#else
+ return NULL;
+#endif
+}
diff --git a/third_party/heimdal/lib/hcrypto/rsa-ltm.c b/third_party/heimdal/lib/hcrypto/rsa-ltm.c
new file mode 100644
index 0000000..1d5b73e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rsa-ltm.c
@@ -0,0 +1,637 @@
+/*
+ * Copyright (c) 2006 - 2007, 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+#include <krb5-types.h>
+#include <assert.h>
+
+#include <rsa.h>
+
+#include "tommath.h"
+
+#define CHECK(f) \
+ do { if (ret == MP_OKAY && ((ret = f)) != MP_OKAY) { goto out; } } while (0)
+#define FIRST(e) do { ret = (e); } while (0)
+#define FIRST_ALLOC(e) \
+ do { where = __LINE__; ret = ((e)) ? MP_OKAY : MP_MEM; } while (0)
+#define THEN_MP(e) \
+ do { where = __LINE__ + 1; if (ret == MP_OKAY) ret = (e); } while (0)
+#define THEN_IF_MP(cond, e) \
+ do { where = __LINE__ + 1; if (ret == MP_OKAY && (cond)) ret = (e); } while (0)
+#define THEN_IF_VOID(cond, e) \
+ do { if (ret == MP_OKAY && (cond)) e; } while (0)
+#define THEN_VOID(e) \
+ do { if (ret == MP_OKAY) e; } while (0)
+#define THEN_ALLOC(e) \
+ do { where = __LINE__ + 1; if (ret == MP_OKAY) ret = ((e)) ? MP_OKAY : MP_MEM; } while (0)
+
+static mp_err
+random_num(mp_int *num, size_t len)
+{
+ unsigned char *p;
+ mp_err ret = MP_MEM;
+
+ len = (len + 7) / 8; /* bits to bytes */
+ if ((p = malloc(len)) && RAND_bytes(p, len) != 1)
+ ret = MP_ERR;
+ if (p)
+ ret = mp_from_ubin(num, p, len);
+ free(p);
+ return ret;
+}
+
+static mp_err
+BN2mpz(mp_int *s, const BIGNUM *bn)
+{
+ size_t len;
+ mp_err ret = MP_MEM;
+ void *p;
+
+ len = BN_num_bytes(bn);
+ p = malloc(len);
+ if (p) {
+ BN_bn2bin(bn, p);
+ ret = mp_from_ubin(s, p, len);
+ }
+ free(p);
+ return ret;
+}
+
+static mp_err
+setup_blind(mp_int *n, mp_int *b, mp_int *bi)
+{
+ mp_err ret;
+
+ ret = random_num(b, mp_count_bits(n));
+ if (ret == MP_OKAY) ret = mp_mod(b, n, b);
+ if (ret == MP_OKAY) ret = mp_invmod(b, n, bi);
+ return ret;
+}
+
+static mp_err
+blind(mp_int *in, mp_int *b, mp_int *e, mp_int *n)
+{
+ mp_err ret;
+ mp_int t1;
+
+ ret = mp_init(&t1);
+ /* in' = (in * b^e) mod n */
+ if (ret == MP_OKAY) ret = mp_exptmod(b, e, n, &t1);
+ if (ret == MP_OKAY) ret = mp_mul(&t1, in, in);
+ if (ret == MP_OKAY) ret = mp_mod(in, n, in);
+ mp_clear(&t1);
+ return ret;
+}
+
+static mp_err
+unblind(mp_int *out, mp_int *bi, mp_int *n)
+{
+ mp_err ret;
+
+ /* out' = (out * 1/b) mod n */
+ ret = mp_mul(out, bi, out);
+ if (ret == MP_OKAY) ret = mp_mod(out, n, out);
+ return ret;
+}
+
+static mp_err
+ltm_rsa_private_calculate(mp_int * in, mp_int * p, mp_int * q,
+ mp_int * dmp1, mp_int * dmq1, mp_int * iqmp,
+ mp_int * out)
+{
+ mp_err ret;
+ mp_int vp, vq, u;
+ int where HEIMDAL_UNUSED_ATTRIBUTE = 0;
+
+ FIRST(mp_init_multi(&vp, &vq, &u, NULL));
+
+ /* vq = c ^ (d mod (q - 1)) mod q */
+ /* vp = c ^ (d mod (p - 1)) mod p */
+ THEN_MP(mp_mod(in, p, &u));
+ THEN_MP(mp_exptmod(&u, dmp1, p, &vp));
+ THEN_MP(mp_mod(in, q, &u));
+ THEN_MP(mp_exptmod(&u, dmq1, q, &vq));
+
+ /* C2 = 1/q mod p (iqmp) */
+ /* u = (vp - vq)C2 mod p. */
+ THEN_MP(mp_sub(&vp, &vq, &u));
+ THEN_IF_MP(mp_isneg(&u), mp_add(&u, p, &u));
+ THEN_MP(mp_mul(&u, iqmp, &u));
+ THEN_MP(mp_mod(&u, p, &u));
+
+ /* c ^ d mod n = vq + u q */
+ THEN_MP(mp_mul(&u, q, &u));
+ THEN_MP(mp_add(&u, &vq, out));
+
+ mp_clear_multi(&vp, &vq, &u, NULL);
+ return ret;
+}
+
+/*
+ *
+ */
+
+static int
+ltm_rsa_public_encrypt(int flen, const unsigned char* from,
+ unsigned char* to, RSA* rsa, int padding)
+{
+ unsigned char *p = NULL, *p0 = NULL;
+ size_t size, ssize, padlen;
+ mp_int enc, dec, n, e;
+ mp_err ret;
+ int where = __LINE__;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ FIRST(mp_init_multi(&n, &e, &enc, &dec, NULL));
+
+ size = RSA_size(rsa);
+ THEN_IF_MP((size < RSA_PKCS1_PADDING_SIZE ||
+ size - RSA_PKCS1_PADDING_SIZE < flen),
+ MP_ERR);
+ THEN_MP(BN2mpz(&n, rsa->n));
+ THEN_MP(BN2mpz(&e, rsa->e));
+ THEN_IF_MP((mp_cmp_d(&e, 3) == MP_LT), MP_ERR);
+ THEN_ALLOC((p = p0 = malloc(size - 1)));
+
+ if (ret == MP_OKAY) {
+ padlen = size - flen - 3;
+ *p++ = 2;
+ }
+ THEN_IF_MP((RAND_bytes(p, padlen) != 1), MP_ERR);
+
+ if (ret == MP_OKAY) {
+ while (padlen) {
+ if (*p == 0)
+ *p = 1;
+ padlen--;
+ p++;
+ }
+ *p++ = 0;
+ memcpy(p, from, flen);
+ p += flen;
+ assert((p - p0) == size - 1);
+ }
+
+ THEN_MP(mp_from_ubin(&dec, p0, size - 1));
+ THEN_MP(mp_exptmod(&dec, &e, &n, &enc));
+ THEN_VOID(ssize = mp_ubin_size(&enc));
+ THEN_VOID(assert(size >= ssize));
+ THEN_MP(mp_to_ubin(&enc, to, SIZE_MAX, NULL));
+ THEN_VOID(size = ssize);
+
+ mp_clear_multi(&dec, &e, &n, NULL);
+ mp_clear(&enc);
+ free(p0);
+ return ret == MP_OKAY ? size : -where;
+}
+
+static int
+ltm_rsa_public_decrypt(int flen, const unsigned char* from,
+ unsigned char* to, RSA* rsa, int padding)
+{
+ unsigned char *p;
+ mp_err ret;
+ size_t size;
+ mp_int s, us, n, e;
+ int where = 0;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ if (flen > RSA_size(rsa))
+ return -2;
+
+ FIRST(mp_init_multi(&e, &n, &s, &us, NULL));
+ THEN_MP(BN2mpz(&n, rsa->n));
+ THEN_MP(BN2mpz(&e, rsa->e));
+ THEN_MP((mp_cmp_d(&e, 3) == MP_LT) ? MP_ERR : MP_OKAY);
+ THEN_MP(mp_from_ubin(&s, rk_UNCONST(from), (size_t)flen));
+ THEN_MP((mp_cmp(&s, &n) >= 0) ? MP_ERR : MP_OKAY);
+ THEN_MP(mp_exptmod(&s, &e, &n, &us));
+
+ THEN_VOID(p = to);
+ THEN_VOID(size = mp_ubin_size(&us));
+ THEN_VOID(assert(size <= RSA_size(rsa)));
+ THEN_MP(mp_to_ubin(&us, p, SIZE_MAX, NULL));
+
+ mp_clear_multi(&e, &n, &s, NULL);
+ mp_clear(&us);
+
+ if (ret != MP_OKAY)
+ return -where;
+
+ /* head zero was skipped by mp_to_unsigned_bin */
+ if (*p == 0)
+ return -where;
+ if (*p != 1)
+ return -(where + 1);
+ size--; p++;
+ while (size && *p == 0xff) {
+ size--; p++;
+ }
+ if (size == 0 || *p != 0)
+ return -(where + 2);
+ size--; p++;
+ memmove(to, p, size);
+ return size;
+}
+
+static int
+ltm_rsa_private_encrypt(int flen, const unsigned char* from,
+ unsigned char* to, RSA* rsa, int padding)
+{
+ unsigned char *ptr, *ptr0 = NULL;
+ mp_err ret;
+ mp_int in, out, n, e;
+ mp_int bi, b;
+ size_t size;
+ int blinding = (rsa->flags & RSA_FLAG_NO_BLINDING) == 0;
+ int do_unblind = 0;
+ int where = 0;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ FIRST(mp_init_multi(&e, &n, &in, &out, &b, &bi, NULL));
+
+ size = RSA_size(rsa);
+ if (size < RSA_PKCS1_PADDING_SIZE || size - RSA_PKCS1_PADDING_SIZE < flen)
+ return -2;
+
+ THEN_ALLOC((ptr0 = ptr = malloc(size)));
+ if (ret == MP_OKAY) {
+ *ptr++ = 0;
+ *ptr++ = 1;
+ memset(ptr, 0xff, size - flen - 3);
+ ptr += size - flen - 3;
+ *ptr++ = 0;
+ memcpy(ptr, from, flen);
+ ptr += flen;
+ assert((ptr - ptr0) == size);
+ }
+
+ THEN_MP(BN2mpz(&n, rsa->n));
+ THEN_MP(BN2mpz(&e, rsa->e));
+ THEN_IF_MP((mp_cmp_d(&e, 3) == MP_LT), MP_ERR);
+ THEN_MP(mp_from_ubin(&in, ptr0, size));
+ free(ptr0);
+
+ THEN_IF_MP((mp_isneg(&in) || mp_cmp(&in, &n) >= 0), MP_ERR);
+
+ if (blinding) {
+ THEN_MP(setup_blind(&n, &b, &bi));
+ THEN_MP(blind(&in, &b, &e, &n));
+ do_unblind = 1;
+ }
+
+ if (ret == MP_OKAY && rsa->p && rsa->q && rsa->dmp1 && rsa->dmq1 &&
+ rsa->iqmp) {
+ mp_int p, q, dmp1, dmq1, iqmp;
+
+ FIRST(mp_init_multi(&p, &q, &dmp1, &dmq1, &iqmp, NULL));
+ THEN_MP(BN2mpz(&p, rsa->p));
+ THEN_MP(BN2mpz(&q, rsa->q));
+ THEN_MP(BN2mpz(&dmp1, rsa->dmp1));
+ THEN_MP(BN2mpz(&dmq1, rsa->dmq1));
+ THEN_MP(BN2mpz(&iqmp, rsa->iqmp));
+ THEN_MP(ltm_rsa_private_calculate(&in, &p, &q, &dmp1, &dmq1, &iqmp,
+ &out));
+ mp_clear_multi(&p, &q, &dmp1, &dmq1, &iqmp, NULL);
+ if (ret != MP_OKAY) goto out;
+ } else if (ret == MP_OKAY) {
+ mp_int d;
+
+ THEN_MP(BN2mpz(&d, rsa->d));
+ THEN_MP(mp_exptmod(&in, &d, &n, &out));
+ mp_clear(&d);
+ if (ret != MP_OKAY) goto out;
+ }
+
+ if (do_unblind)
+ THEN_MP(unblind(&out, &bi, &n));
+
+ if (ret == MP_OKAY && size > 0) {
+ size_t ssize;
+
+ ssize = mp_ubin_size(&out);
+ assert(size >= ssize);
+ THEN_MP(mp_to_ubin(&out, to, SIZE_MAX, NULL));
+ size = ssize;
+ }
+
+ out:
+ mp_clear_multi(&e, &n, &in, &out, &b, &bi, NULL);
+ return ret == MP_OKAY ? size : -where;
+}
+
+static int
+ltm_rsa_private_decrypt(int flen, const unsigned char* from,
+ unsigned char* to, RSA* rsa, int padding)
+{
+ unsigned char *ptr;
+ size_t size;
+ mp_err ret;
+ mp_int in, out, n, e, b, bi;
+ int blinding = (rsa->flags & RSA_FLAG_NO_BLINDING) == 0;
+ int do_unblind = 0;
+ int where = 0;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ size = RSA_size(rsa);
+ if (flen > size)
+ return -2;
+
+ FIRST(mp_init_multi(&in, &n, &e, &out, &b, &bi, NULL));
+ THEN_MP(BN2mpz(&n, rsa->n));
+ THEN_MP(BN2mpz(&e, rsa->e));
+ THEN_IF_MP((mp_cmp_d(&e, 3) == MP_LT), MP_ERR);
+ THEN_MP(mp_from_ubin(&in, rk_UNCONST(from), flen));
+ THEN_IF_MP((mp_isneg(&in) || mp_cmp(&in, &n) >= 0), MP_ERR);
+
+ if (blinding) {
+ THEN_MP(setup_blind(&n, &b, &bi));
+ THEN_MP(blind(&in, &b, &e, &n));
+ do_unblind = 1;
+ }
+
+ if (ret == MP_OKAY && rsa->p && rsa->q && rsa->dmp1 && rsa->dmq1 &&
+ rsa->iqmp) {
+ mp_int p, q, dmp1, dmq1, iqmp;
+
+ THEN_MP(mp_init_multi(&p, &q, &dmp1, &dmq1, &iqmp, NULL));
+ THEN_MP(BN2mpz(&p, rsa->p));
+ THEN_MP(BN2mpz(&q, rsa->q));
+ THEN_MP(BN2mpz(&dmp1, rsa->dmp1));
+ THEN_MP(BN2mpz(&dmq1, rsa->dmq1));
+ THEN_MP(BN2mpz(&iqmp, rsa->iqmp));
+ THEN_MP(ltm_rsa_private_calculate(&in, &p, &q, &dmp1, &dmq1, &iqmp, &out));
+ mp_clear_multi(&p, &q, &dmp1, &dmq1, &iqmp, NULL);
+ if (ret != MP_OKAY) goto out;
+ } else if (ret == MP_OKAY) {
+ mp_int d;
+
+ THEN_IF_MP((mp_isneg(&in) || mp_cmp(&in, &n) >= 0), MP_ERR);
+ THEN_MP(BN2mpz(&d, rsa->d));
+ THEN_MP(mp_exptmod(&in, &d, &n, &out));
+ mp_clear(&d);
+ if (ret != MP_OKAY) goto out;
+ }
+
+ if (do_unblind)
+ THEN_MP(unblind(&out, &bi, &n));
+
+ if (ret == MP_OKAY) {
+ size_t ssize;
+
+ ptr = to;
+ ssize = mp_ubin_size(&out);
+ assert(size >= ssize);
+ ret = mp_to_ubin(&out, ptr, SIZE_MAX, NULL);
+ if (ret != MP_OKAY) goto out;
+ size = ssize;
+
+ /* head zero was skipped by mp_int_to_unsigned */
+ if (*ptr != 2) {
+ where = __LINE__;
+ goto out;
+ }
+ size--; ptr++;
+ while (size && *ptr != 0) {
+ size--; ptr++;
+ }
+ if (size == 0) {
+ where = __LINE__;
+ goto out;
+ }
+ size--; ptr++;
+ memmove(to, ptr, size);
+ }
+
+ out:
+ mp_clear_multi(&e, &n, &in, &out, &b, &bi, NULL);
+ return (ret == MP_OKAY) ? size : -where;
+}
+
+static BIGNUM *
+mpz2BN(mp_int *s)
+{
+ size_t size;
+ BIGNUM *bn;
+ mp_err ret;
+ void *p;
+
+ size = mp_ubin_size(s);
+ if (size == 0)
+ return NULL;
+
+ p = malloc(size);
+ if (p == NULL)
+ return NULL;
+
+ ret = mp_to_ubin(s, p, SIZE_MAX, NULL);
+ if (ret == MP_OKAY)
+ bn = BN_bin2bn(p, size, NULL);
+ free(p);
+ return (ret == MP_OKAY) ? bn : NULL;
+}
+
+enum gen_pq_type { GEN_P, GEN_Q };
+
+static int
+gen_p(int bits, enum gen_pq_type pq_type, uint8_t nibble_pair, mp_int *p, mp_int *e, BN_GENCB *cb)
+{
+ unsigned char *buf = NULL;
+ mp_bool res;
+ mp_err ret = MP_MEM;
+ mp_int t1, t2;
+ size_t len = (bits + 7) / 8;
+ int trials = mp_prime_rabin_miller_trials(bits);
+ int counter = 0;
+ int where HEIMDAL_UNUSED_ATTRIBUTE = 0;
+
+
+ FIRST(mp_init_multi(&t1, &t2, NULL));
+ if (ret == MP_OKAY && (buf = malloc(len))) do {
+ BN_GENCB_call(cb, 2, counter++);
+ /* random bytes */
+ ret = (RAND_bytes(buf, len) == 1) ? MP_OKAY : MP_ERR;
+
+ /* make it odd */
+ buf[len - 1] |= 1;
+
+ /* ensure the high nibble of the product is at least 128 */
+ if (pq_type == GEN_P)
+ buf[0] = (nibble_pair & 0xf0) | (buf[0] & 0x0f);
+ else
+ buf[0] = ((nibble_pair & 0x0f) << 4) | (buf[0] & 0x0f);
+
+ /* load number */
+ THEN_MP(mp_from_ubin(p, buf, len));
+
+ /* test primality; repeat if not */
+ THEN_MP(mp_prime_is_prime(p, trials, &res));
+ if (ret == MP_OKAY && res == MP_NO) continue;
+
+ /* check gcd(p - 1, e) == 1 */
+ THEN_MP(mp_sub_d(p, 1, &t1));
+ THEN_MP(mp_gcd(&t1, e, &t2));
+ } while (ret == MP_OKAY && mp_cmp_d(&t2, 1) != MP_EQ);
+
+ mp_clear_multi(&t1, &t2, NULL);
+ free(buf);
+ return ret;
+}
+
+static uint8_t pq_high_nibble_pairs[] = {
+0x9f, 0xad, 0xae, 0xaf, 0xbc, 0xbd, 0xbe, 0xbf, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
+0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf9,
+0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
+};
+
+static int
+ltm_rsa_generate_key(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb)
+{
+ mp_int el, p, q, n, d, dmp1, dmq1, iqmp, t1, t2, t3;
+ mp_err ret;
+ uint8_t high_nibbles = 0;
+ int bitsp;
+ int where = 0;
+
+ if (bits < 789)
+ return -1;
+
+ bitsp = (bits + 1) / 2;
+
+ FIRST(mp_init_multi(&el, &p, &q, &n, &d,
+ &dmp1, &dmq1, &iqmp,
+ &t1, &t2, &t3, NULL));
+ THEN_MP(BN2mpz(&el, e));
+
+ /*
+ * randomly pick a pair of high nibbles for p and q to ensure the product's
+ * high nibble is at least 128
+ */
+ if (ret == MP_OKAY)
+ ret = (RAND_bytes(&high_nibbles, 1) == 1) ? MP_OKAY : MP_ERR;
+ high_nibbles %= sizeof(pq_high_nibble_pairs);
+ high_nibbles = pq_high_nibble_pairs[high_nibbles];
+
+ /* generate p and q so that p != q and bits(pq) ~ bits */
+ THEN_MP(gen_p(bitsp, GEN_P, high_nibbles, &p, &el, cb));
+ BN_GENCB_call(cb, 3, 0);
+ THEN_MP(gen_p(bitsp, GEN_Q, high_nibbles, &q, &el, cb));
+
+ /* make p > q */
+ if (mp_cmp(&p, &q) < 0) {
+ mp_int c;
+ c = p;
+ p = q;
+ q = c;
+ }
+
+ BN_GENCB_call(cb, 3, 1);
+
+ /* calculate n, n = p * q */
+ THEN_MP(mp_mul(&p, &q, &n));
+
+ /* calculate d, d = 1/e mod (p - 1)(q - 1) */
+ THEN_MP(mp_sub_d(&p, 1, &t1));
+ THEN_MP(mp_sub_d(&q, 1, &t2));
+ THEN_MP(mp_mul(&t1, &t2, &t3));
+ THEN_MP(mp_invmod(&el, &t3, &d));
+
+ /* calculate dmp1 dmp1 = d mod (p-1) */
+ THEN_MP(mp_mod(&d, &t1, &dmp1));
+ /* calculate dmq1 dmq1 = d mod (q-1) */
+ THEN_MP(mp_mod(&d, &t2, &dmq1));
+ /* calculate iqmp iqmp = 1/q mod p */
+ THEN_MP(mp_invmod(&q, &p, &iqmp));
+
+ /* fill in RSA key */
+
+ if (ret == MP_OKAY) {
+ rsa->e = mpz2BN(&el);
+ rsa->p = mpz2BN(&p);
+ rsa->q = mpz2BN(&q);
+ rsa->n = mpz2BN(&n);
+ rsa->d = mpz2BN(&d);
+ rsa->dmp1 = mpz2BN(&dmp1);
+ rsa->dmq1 = mpz2BN(&dmq1);
+ rsa->iqmp = mpz2BN(&iqmp);
+ }
+
+ mp_clear_multi(&el, &p, &q, &n, &d,
+ &dmp1, &dmq1, &iqmp,
+ &t1, &t2, &t3, NULL);
+ return (ret == MP_OKAY) ? 1 : -where;
+}
+
+static int
+ltm_rsa_init(RSA *rsa)
+{
+ return 1;
+}
+
+static int
+ltm_rsa_finish(RSA *rsa)
+{
+ return 1;
+}
+
+const RSA_METHOD hc_rsa_ltm_method = {
+ "hcrypto ltm RSA",
+ ltm_rsa_public_encrypt,
+ ltm_rsa_public_decrypt,
+ ltm_rsa_private_encrypt,
+ ltm_rsa_private_decrypt,
+ NULL,
+ NULL,
+ ltm_rsa_init,
+ ltm_rsa_finish,
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ ltm_rsa_generate_key
+};
+
+const RSA_METHOD *
+RSA_ltm_method(void)
+{
+ return &hc_rsa_ltm_method;
+}
diff --git a/third_party/heimdal/lib/hcrypto/rsa-tfm.c b/third_party/heimdal/lib/hcrypto/rsa-tfm.c
new file mode 100644
index 0000000..41b0fc1
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rsa-tfm.c
@@ -0,0 +1,573 @@
+/*
+ * Copyright (c) 2006 - 2007, 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+#include <krb5-types.h>
+#include <assert.h>
+
+#include <rsa.h>
+
+#ifdef USE_HCRYPTO_TFM
+
+#include "tfm.h"
+
+static void
+BN2mpz(fp_int *s, const BIGNUM *bn)
+{
+ size_t len;
+ void *p;
+
+ fp_init(s);
+
+ len = BN_num_bytes(bn);
+ p = malloc(len);
+ BN_bn2bin(bn, p);
+ fp_read_unsigned_bin(s, p, len);
+ free(p);
+}
+
+static int
+tfm_rsa_private_calculate(fp_int * in, fp_int * p, fp_int * q,
+ fp_int * dmp1, fp_int * dmq1, fp_int * iqmp,
+ fp_int * out)
+{
+ fp_int vp, vq, u;
+
+ fp_init_multi(&vp, &vq, &u, NULL);
+
+ /* vq = c ^ (d mod (q - 1)) mod q */
+ /* vp = c ^ (d mod (p - 1)) mod p */
+ fp_mod(in, p, &u);
+ fp_exptmod(&u, dmp1, p, &vp);
+ fp_mod(in, q, &u);
+ fp_exptmod(&u, dmq1, q, &vq);
+
+ /* C2 = 1/q mod p (iqmp) */
+ /* u = (vp - vq)C2 mod p. */
+ fp_sub(&vp, &vq, &u);
+ if (fp_isneg(&u))
+ fp_add(&u, p, &u);
+ fp_mul(&u, iqmp, &u);
+ fp_mod(&u, p, &u);
+
+ /* c ^ d mod n = vq + u q */
+ fp_mul(&u, q, &u);
+ fp_add(&u, &vq, out);
+
+ fp_zero_multi(&vp, &vq, &u, NULL);
+
+ return 0;
+}
+
+/*
+ *
+ */
+
+static int
+tfm_rsa_public_encrypt(int flen, const unsigned char* from,
+ unsigned char* to, RSA* rsa, int padding)
+{
+ unsigned char *p, *p0;
+ int res;
+ size_t size, padlen;
+ fp_int enc, dec, n, e;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ size = RSA_size(rsa);
+
+ if (size < RSA_PKCS1_PADDING_SIZE || size - RSA_PKCS1_PADDING_SIZE < flen)
+ return -2;
+
+ BN2mpz(&n, rsa->n);
+ BN2mpz(&e, rsa->e);
+
+ p = p0 = malloc(size - 1);
+ if (p0 == NULL) {
+ fp_zero_multi(&e, &n, NULL);
+ return -3;
+ }
+
+ padlen = size - flen - 3;
+
+ *p++ = 2;
+ if (RAND_bytes(p, padlen) != 1) {
+ fp_zero_multi(&e, &n, NULL);
+ free(p0);
+ return -4;
+ }
+ while(padlen) {
+ if (*p == 0)
+ *p = 1;
+ padlen--;
+ p++;
+ }
+ *p++ = 0;
+ memcpy(p, from, flen);
+ p += flen;
+ assert((p - p0) == size - 1);
+
+ fp_init_multi(&enc, &dec, NULL);
+ fp_read_unsigned_bin(&dec, p0, size - 1);
+ free(p0);
+
+ res = fp_exptmod(&dec, &e, &n, &enc);
+
+ fp_zero_multi(&dec, &e, &n, NULL);
+
+ if (res != 0)
+ return -4;
+
+ {
+ size_t ssize;
+ ssize = fp_unsigned_bin_size(&enc);
+ assert(size >= ssize);
+ fp_to_unsigned_bin(&enc, to);
+ size = ssize;
+ }
+ fp_zero(&enc);
+
+ return size;
+}
+
+static int
+tfm_rsa_public_decrypt(int flen, const unsigned char* from,
+ unsigned char* to, RSA* rsa, int padding)
+{
+ unsigned char *p;
+ int res;
+ size_t size;
+ fp_int s, us, n, e;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ if (flen > RSA_size(rsa))
+ return -2;
+
+ BN2mpz(&n, rsa->n);
+ BN2mpz(&e, rsa->e);
+
+#if 0
+ /* Check that the exponent is larger then 3 */
+ if (mp_int_compare_value(&e, 3) <= 0) {
+ fp_zero_multi(&e, &n, NULL);
+ return -3;
+ }
+#endif
+
+ fp_init_multi(&s, &us, NULL);
+ fp_read_unsigned_bin(&s, rk_UNCONST(from), flen);
+
+ if (fp_cmp(&s, &n) >= 0) {
+ fp_zero_multi(&e, &n, NULL);
+ return -4;
+ }
+
+ res = fp_exptmod(&s, &e, &n, &us);
+
+ fp_zero_multi(&s, &e, &n, NULL);
+
+ if (res != 0)
+ return -5;
+ p = to;
+
+
+ size = fp_unsigned_bin_size(&us);
+ assert(size <= RSA_size(rsa));
+ fp_to_unsigned_bin(&us, p);
+
+ fp_zero(&us);
+
+ /* head zero was skipped by fp_to_unsigned_bin */
+ if (*p == 0)
+ return -6;
+ if (*p != 1)
+ return -7;
+ size--; p++;
+ while (size && *p == 0xff) {
+ size--; p++;
+ }
+ if (size == 0 || *p != 0)
+ return -8;
+ size--; p++;
+
+ memmove(to, p, size);
+
+ return size;
+}
+
+static int
+tfm_rsa_private_encrypt(int flen, const unsigned char* from,
+ unsigned char* to, RSA* rsa, int padding)
+{
+ unsigned char *p, *p0;
+ int res;
+ int size;
+ fp_int in, out, n, e;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ size = RSA_size(rsa);
+
+ if (size < RSA_PKCS1_PADDING_SIZE || size - RSA_PKCS1_PADDING_SIZE < flen)
+ return -2;
+
+ p0 = p = malloc(size);
+ *p++ = 0;
+ *p++ = 1;
+ memset(p, 0xff, size - flen - 3);
+ p += size - flen - 3;
+ *p++ = 0;
+ memcpy(p, from, flen);
+ p += flen;
+ assert((p - p0) == size);
+
+ BN2mpz(&n, rsa->n);
+ BN2mpz(&e, rsa->e);
+
+ fp_init_multi(&in, &out, NULL);
+ fp_read_unsigned_bin(&in, p0, size);
+ free(p0);
+
+ if(fp_isneg(&in) || fp_cmp(&in, &n) >= 0) {
+ size = -3;
+ goto out;
+ }
+
+ if (rsa->p && rsa->q && rsa->dmp1 && rsa->dmq1 && rsa->iqmp) {
+ fp_int p, q, dmp1, dmq1, iqmp;
+
+ BN2mpz(&p, rsa->p);
+ BN2mpz(&q, rsa->q);
+ BN2mpz(&dmp1, rsa->dmp1);
+ BN2mpz(&dmq1, rsa->dmq1);
+ BN2mpz(&iqmp, rsa->iqmp);
+
+ res = tfm_rsa_private_calculate(&in, &p, &q, &dmp1, &dmq1, &iqmp, &out);
+
+ fp_zero_multi(&p, &q, &dmp1, &dmq1, &iqmp, NULL);
+
+ if (res != 0) {
+ size = -4;
+ goto out;
+ }
+ } else {
+ fp_int d;
+
+ BN2mpz(&d, rsa->d);
+ res = fp_exptmod(&in, &d, &n, &out);
+ fp_zero(&d);
+ if (res != 0) {
+ size = -5;
+ goto out;
+ }
+ }
+
+ if (size > 0) {
+ size_t ssize;
+ ssize = fp_unsigned_bin_size(&out);
+ assert(size >= ssize);
+ fp_to_unsigned_bin(&out, to);
+ size = ssize;
+ }
+
+ out:
+ fp_zero_multi(&e, &n, &in, &out, NULL);
+
+ return size;
+}
+
+static int
+tfm_rsa_private_decrypt(int flen, const unsigned char* from,
+ unsigned char* to, RSA* rsa, int padding)
+{
+ unsigned char *ptr;
+ int res;
+ int size;
+ fp_int in, out, n, e;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ size = RSA_size(rsa);
+ if (flen > size)
+ return -2;
+
+ fp_init_multi(&in, &out, NULL);
+
+ BN2mpz(&n, rsa->n);
+ BN2mpz(&e, rsa->e);
+
+ fp_read_unsigned_bin(&in, rk_UNCONST(from), flen);
+
+ if(fp_isneg(&in) || fp_cmp(&in, &n) >= 0) {
+ size = -2;
+ goto out;
+ }
+
+ if (rsa->p && rsa->q && rsa->dmp1 && rsa->dmq1 && rsa->iqmp) {
+ fp_int p, q, dmp1, dmq1, iqmp;
+
+ BN2mpz(&p, rsa->p);
+ BN2mpz(&q, rsa->q);
+ BN2mpz(&dmp1, rsa->dmp1);
+ BN2mpz(&dmq1, rsa->dmq1);
+ BN2mpz(&iqmp, rsa->iqmp);
+
+ res = tfm_rsa_private_calculate(&in, &p, &q, &dmp1, &dmq1, &iqmp, &out);
+
+ fp_zero_multi(&p, &q, &dmp1, &dmq1, &iqmp, NULL);
+
+ if (res != 0) {
+ size = -3;
+ goto out;
+ }
+
+ } else {
+ fp_int d;
+
+ if(fp_isneg(&in) || fp_cmp(&in, &n) >= 0)
+ return -4;
+
+ BN2mpz(&d, rsa->d);
+ res = fp_exptmod(&in, &d, &n, &out);
+ fp_zero(&d);
+ if (res != 0) {
+ size = -5;
+ goto out;
+ }
+ }
+
+ ptr = to;
+ {
+ size_t ssize;
+ ssize = fp_unsigned_bin_size(&out);
+ assert(size >= ssize);
+ fp_to_unsigned_bin(&out, ptr);
+ size = ssize;
+ }
+
+ /* head zero was skipped by mp_int_to_unsigned */
+ if (*ptr != 2) {
+ size = -6;
+ goto out;
+ }
+ size--; ptr++;
+ while (size && *ptr != 0) {
+ size--; ptr++;
+ }
+ if (size == 0)
+ return -7;
+ size--; ptr++;
+
+ memmove(to, ptr, size);
+
+ out:
+ fp_zero_multi(&e, &n, &in, &out, NULL);
+
+ return size;
+}
+
+static BIGNUM *
+mpz2BN(fp_int *s)
+{
+ size_t size;
+ BIGNUM *bn;
+ void *p;
+
+ size = fp_unsigned_bin_size(s);
+ p = malloc(size);
+ if (p == NULL && size != 0)
+ return NULL;
+
+ fp_to_unsigned_bin(s, p);
+
+ bn = BN_bin2bn(p, size, NULL);
+ free(p);
+ return bn;
+}
+
+static int
+random_num(fp_int *num, size_t len)
+{
+ unsigned char *p;
+
+ len = (len + 7) / 8;
+ p = malloc(len);
+ if (p == NULL)
+ return 1;
+ if (RAND_bytes(p, len) != 1) {
+ free(p);
+ return 1;
+ }
+ fp_read_unsigned_bin(num, p, len);
+ free(p);
+ return 0;
+}
+
+#define CHECK(f, v) if ((f) != (v)) { goto out; }
+
+static int
+tfm_rsa_generate_key(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb)
+{
+ fp_int el, p, q, n, d, dmp1, dmq1, iqmp, t1, t2, t3;
+ int counter, ret, bitsp;
+
+ if (bits < 789)
+ return -1;
+
+ bitsp = (bits + 1) / 2;
+
+ ret = -1;
+
+ fp_init_multi(&el, &p, &q, &n, &n, &d, &dmp1, &dmq1, &iqmp, &t1, &t2, &t3, NULL);
+
+ BN2mpz(&el, e);
+
+ /* generate p and q so that p != q and bits(pq) ~ bits */
+ counter = 0;
+ do {
+ BN_GENCB_call(cb, 2, counter++);
+ CHECK(random_num(&p, bitsp), 0);
+ CHECK(fp_find_prime(&p), FP_YES);
+
+ fp_sub_d(&p, 1, &t1);
+ fp_gcd(&t1, &el, &t2);
+ } while(fp_cmp_d(&t2, 1) != 0);
+
+ BN_GENCB_call(cb, 3, 0);
+
+ counter = 0;
+ do {
+ BN_GENCB_call(cb, 2, counter++);
+ CHECK(random_num(&q, bits - bitsp), 0);
+ CHECK(fp_find_prime(&q), FP_YES);
+
+ if (fp_cmp(&p, &q) == 0) /* don't let p and q be the same */
+ continue;
+
+ fp_sub_d(&q, 1, &t1);
+ fp_gcd(&t1, &el, &t2);
+ } while(fp_cmp_d(&t2, 1) != 0);
+
+ /* make p > q */
+ if (fp_cmp(&p, &q) < 0) {
+ fp_int c;
+ fp_copy(&p, &c);
+ fp_copy(&q, &p);
+ fp_copy(&c, &q);
+ }
+
+ BN_GENCB_call(cb, 3, 1);
+
+ /* calculate n, n = p * q */
+ fp_mul(&p, &q, &n);
+
+ /* calculate d, d = 1/e mod (p - 1)(q - 1) */
+ fp_sub_d(&p, 1, &t1);
+ fp_sub_d(&q, 1, &t2);
+ fp_mul(&t1, &t2, &t3);
+ fp_invmod(&el, &t3, &d);
+
+ /* calculate dmp1 dmp1 = d mod (p-1) */
+ fp_mod(&d, &t1, &dmp1);
+ /* calculate dmq1 dmq1 = d mod (q-1) */
+ fp_mod(&d, &t2, &dmq1);
+ /* calculate iqmp iqmp = 1/q mod p */
+ fp_invmod(&q, &p, &iqmp);
+
+ /* fill in RSA key */
+
+ rsa->e = mpz2BN(&el);
+ rsa->p = mpz2BN(&p);
+ rsa->q = mpz2BN(&q);
+ rsa->n = mpz2BN(&n);
+ rsa->d = mpz2BN(&d);
+ rsa->dmp1 = mpz2BN(&dmp1);
+ rsa->dmq1 = mpz2BN(&dmq1);
+ rsa->iqmp = mpz2BN(&iqmp);
+
+ ret = 1;
+
+out:
+ fp_zero_multi(&el, &p, &q, &n, &d, &dmp1,
+ &dmq1, &iqmp, &t1, &t2, &t3, NULL);
+
+ return ret;
+}
+
+static int
+tfm_rsa_init(RSA *rsa)
+{
+ return 1;
+}
+
+static int
+tfm_rsa_finish(RSA *rsa)
+{
+ return 1;
+}
+
+const RSA_METHOD hc_rsa_tfm_method = {
+ "hcrypto tfm RSA",
+ tfm_rsa_public_encrypt,
+ tfm_rsa_public_decrypt,
+ tfm_rsa_private_encrypt,
+ tfm_rsa_private_decrypt,
+ NULL,
+ NULL,
+ tfm_rsa_init,
+ tfm_rsa_finish,
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ tfm_rsa_generate_key
+};
+
+#endif
+
+const RSA_METHOD *
+RSA_tfm_method(void)
+{
+#ifdef USE_HCRYPTO_TFM
+ return &hc_rsa_tfm_method;
+#else
+ return NULL;
+#endif
+}
+
diff --git a/third_party/heimdal/lib/hcrypto/rsa.c b/third_party/heimdal/lib/hcrypto/rsa.c
new file mode 100644
index 0000000..6172b25
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rsa.c
@@ -0,0 +1,706 @@
+/*
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+#include <krb5-types.h>
+#include <rfc2459_asn1.h>
+
+#include <der.h>
+
+#include <rsa.h>
+
+#include "common.h"
+
+/**
+ * @page page_rsa RSA - public-key cryptography
+ *
+ * RSA is named by its inventors (Ron Rivest, Adi Shamir, and Leonard
+ * Adleman) (published in 1977), patented expired in 21 September 2000.
+ *
+ *
+ * Speed for RSA in seconds
+ * no key blinding
+ * 1000 iteration,
+ * same rsa keys (1024 and 2048)
+ * operation performed each eteration sign, verify, encrypt, decrypt on a random bit pattern
+ *
+ * name 1024 2048 4098
+ * =================================
+ * gmp: 0.73 6.60 44.80
+ * tfm: 2.45 -- --
+ * ltm: 3.79 20.74 105.41 (default in hcrypto)
+ * openssl: 4.04 11.90 82.59
+ * cdsa: 15.89 102.89 721.40
+ * imath: 40.62 -- --
+ *
+ * See the library functions here: @ref hcrypto_rsa
+ */
+
+/**
+ * Same as RSA_new_method() using NULL as engine.
+ *
+ * @return a newly allocated RSA object. Free with RSA_free().
+ *
+ * @ingroup hcrypto_rsa
+ */
+
+RSA *
+RSA_new(void)
+{
+ return RSA_new_method(NULL);
+}
+
+/**
+ * Allocate a new RSA object using the engine, if NULL is specified as
+ * the engine, use the default RSA engine as returned by
+ * ENGINE_get_default_RSA().
+ *
+ * @param engine Specific what ENGINE RSA provider should be used.
+ *
+ * @return a newly allocated RSA object. Free with RSA_free().
+ *
+ * @ingroup hcrypto_rsa
+ */
+
+RSA *
+RSA_new_method(ENGINE *engine)
+{
+ RSA *rsa;
+
+ rsa = calloc(1, sizeof(*rsa));
+ if (rsa == NULL)
+ return NULL;
+
+ rsa->references = 1;
+
+ if (engine) {
+ ENGINE_up_ref(engine);
+ rsa->engine = engine;
+ } else {
+ rsa->engine = ENGINE_get_default_RSA();
+ }
+
+ if (rsa->engine) {
+ rsa->meth = ENGINE_get_RSA(rsa->engine);
+ if (rsa->meth == NULL) {
+ ENGINE_finish(rsa->engine);
+ free(rsa);
+ return 0;
+ }
+ }
+
+ if (rsa->meth == NULL)
+ rsa->meth = rk_UNCONST(RSA_get_default_method());
+
+ (*rsa->meth->init)(rsa);
+
+ return rsa;
+}
+
+/**
+ * Free an allocation RSA object.
+ *
+ * @param rsa the RSA object to free.
+ * @ingroup hcrypto_rsa
+ */
+
+void
+RSA_free(RSA *rsa)
+{
+ if (rsa->references <= 0)
+ abort();
+
+ if (--rsa->references > 0)
+ return;
+
+ (*rsa->meth->finish)(rsa);
+
+ if (rsa->engine)
+ ENGINE_finish(rsa->engine);
+
+#define free_if(f) if (f) { BN_free(f); }
+ free_if(rsa->n);
+ free_if(rsa->e);
+ free_if(rsa->d);
+ free_if(rsa->p);
+ free_if(rsa->q);
+ free_if(rsa->dmp1);
+ free_if(rsa->dmq1);
+ free_if(rsa->iqmp);
+#undef free_if
+
+ memset(rsa, 0, sizeof(*rsa));
+ free(rsa);
+}
+
+/**
+ * Add an extra reference to the RSA object. The object should be free
+ * with RSA_free() to drop the reference.
+ *
+ * @param rsa the object to add reference counting too.
+ *
+ * @return the current reference count, can't safely be used except
+ * for debug printing.
+ *
+ * @ingroup hcrypto_rsa
+ */
+
+int
+RSA_up_ref(RSA *rsa)
+{
+ return ++rsa->references;
+}
+
+/**
+ * Return the RSA_METHOD used for this RSA object.
+ *
+ * @param rsa the object to get the method from.
+ *
+ * @return the method used for this RSA object.
+ *
+ * @ingroup hcrypto_rsa
+ */
+
+const RSA_METHOD *
+RSA_get_method(const RSA *rsa)
+{
+ return rsa->meth;
+}
+
+/**
+ * Set a new method for the RSA keypair.
+ *
+ * @param rsa rsa parameter.
+ * @param method the new method for the RSA parameter.
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_rsa
+ */
+
+int
+RSA_set_method(RSA *rsa, const RSA_METHOD *method)
+{
+ (*rsa->meth->finish)(rsa);
+
+ if (rsa->engine) {
+ ENGINE_finish(rsa->engine);
+ rsa->engine = NULL;
+ }
+
+ rsa->meth = method;
+ (*rsa->meth->init)(rsa);
+ return 1;
+}
+
+/**
+ * Set the application data for the RSA object.
+ *
+ * @param rsa the rsa object to set the parameter for
+ * @param arg the data object to store
+ *
+ * @return 1 on success.
+ *
+ * @ingroup hcrypto_rsa
+ */
+
+int
+RSA_set_app_data(RSA *rsa, void *arg)
+{
+ rsa->ex_data.sk = arg;
+ return 1;
+}
+
+/**
+ * Get the application data for the RSA object.
+ *
+ * @param rsa the rsa object to get the parameter for
+ *
+ * @return the data object
+ *
+ * @ingroup hcrypto_rsa
+ */
+
+void *
+RSA_get_app_data(const RSA *rsa)
+{
+ return rsa->ex_data.sk;
+}
+
+int
+RSA_check_key(const RSA *key)
+{
+ static const unsigned char inbuf[] = "hello, world!";
+ RSA *rsa = rk_UNCONST(key);
+ void *buffer;
+ int ret;
+
+ /*
+ * XXX I have no clue how to implement this w/o a bignum library.
+ * Well, when we have a RSA key pair, we can try to encrypt/sign
+ * and then decrypt/verify.
+ */
+
+ if (rsa->n == NULL)
+ return 0;
+
+ if (rsa->d == NULL &&
+ (rsa->p == NULL || rsa->q || rsa->dmp1 == NULL || rsa->dmq1 == NULL || rsa->iqmp == NULL))
+ return 0;
+
+ buffer = malloc(RSA_size(rsa));
+ if (buffer == NULL)
+ return 0;
+
+ ret = RSA_private_encrypt(sizeof(inbuf), inbuf, buffer,
+ rsa, RSA_PKCS1_PADDING);
+ if (ret == -1) {
+ free(buffer);
+ return 0;
+ }
+
+ ret = RSA_public_decrypt(ret, buffer, buffer,
+ rsa, RSA_PKCS1_PADDING);
+ if (ret == -1) {
+ free(buffer);
+ return 0;
+ }
+
+ if (ret == sizeof(inbuf) && ct_memcmp(buffer, inbuf, sizeof(inbuf)) == 0) {
+ free(buffer);
+ return 1;
+ }
+ free(buffer);
+ return 0;
+}
+
+int
+RSA_size(const RSA *rsa)
+{
+ return BN_num_bytes(rsa->n);
+}
+
+#define RSAFUNC(name, body) \
+int \
+name(int flen,const unsigned char* f, unsigned char* t, RSA* r, int p){\
+ return body; \
+}
+
+RSAFUNC(RSA_public_encrypt, (r)->meth->rsa_pub_enc(flen, f, t, r, p))
+RSAFUNC(RSA_public_decrypt, (r)->meth->rsa_pub_dec(flen, f, t, r, p))
+RSAFUNC(RSA_private_encrypt, (r)->meth->rsa_priv_enc(flen, f, t, r, p))
+RSAFUNC(RSA_private_decrypt, (r)->meth->rsa_priv_dec(flen, f, t, r, p))
+
+static const heim_octet_string null_entry_oid = { 2, rk_UNCONST("\x05\x00") };
+
+static const unsigned sha1_oid_tree[] = { 1, 3, 14, 3, 2, 26 };
+static const AlgorithmIdentifier _signature_sha1_data = {
+ { 6, rk_UNCONST(sha1_oid_tree) }, rk_UNCONST(&null_entry_oid)
+};
+static const unsigned sha256_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 1 };
+static const AlgorithmIdentifier _signature_sha256_data = {
+ { 9, rk_UNCONST(sha256_oid_tree) }, rk_UNCONST(&null_entry_oid)
+};
+static const unsigned md5_oid_tree[] = { 1, 2, 840, 113549, 2, 5 };
+static const AlgorithmIdentifier _signature_md5_data = {
+ { 6, rk_UNCONST(md5_oid_tree) }, rk_UNCONST(&null_entry_oid)
+};
+
+
+int
+RSA_sign(int type, const unsigned char *from, unsigned int flen,
+ unsigned char *to, unsigned int *tlen, RSA *rsa)
+{
+ if (rsa->meth->rsa_sign)
+ return rsa->meth->rsa_sign(type, from, flen, to, tlen, rsa);
+
+ if (rsa->meth->rsa_priv_enc) {
+ heim_octet_string indata;
+ DigestInfo di;
+ size_t size;
+ int ret;
+
+ memset(&di, 0, sizeof(di));
+
+ if (type == NID_sha1) {
+ di.digestAlgorithm = _signature_sha1_data;
+ } else if (type == NID_md5) {
+ di.digestAlgorithm = _signature_md5_data;
+ } else if (type == NID_sha256) {
+ di.digestAlgorithm = _signature_sha256_data;
+ } else
+ return -1;
+
+ di.digest.data = rk_UNCONST(from);
+ di.digest.length = flen;
+
+ ASN1_MALLOC_ENCODE(DigestInfo,
+ indata.data,
+ indata.length,
+ &di,
+ &size,
+ ret);
+ if (ret)
+ return ret;
+ if (indata.length != size)
+ abort();
+
+ ret = rsa->meth->rsa_priv_enc(indata.length, indata.data, to,
+ rsa, RSA_PKCS1_PADDING);
+ free(indata.data);
+ if (ret > 0) {
+ *tlen = ret;
+ ret = 1;
+ } else
+ ret = 0;
+
+ return ret;
+ }
+
+ return 0;
+}
+
+int
+RSA_verify(int type, const unsigned char *from, unsigned int flen,
+ unsigned char *sigbuf, unsigned int siglen, RSA *rsa)
+{
+ if (rsa->meth->rsa_verify)
+ return rsa->meth->rsa_verify(type, from, flen, sigbuf, siglen, rsa);
+
+ if (rsa->meth->rsa_pub_dec) {
+ const AlgorithmIdentifier *digest_alg;
+ void *data;
+ DigestInfo di;
+ size_t size;
+ int ret, ret2;
+
+ data = malloc(RSA_size(rsa));
+ if (data == NULL)
+ return -1;
+
+ memset(&di, 0, sizeof(di));
+
+ ret = rsa->meth->rsa_pub_dec(siglen, sigbuf, data, rsa, RSA_PKCS1_PADDING);
+ if (ret <= 0) {
+ free(data);
+ return -2;
+ }
+
+ ret2 = decode_DigestInfo(data, ret, &di, &size);
+ free(data);
+ if (ret2 != 0)
+ return -3;
+ if (ret != size) {
+ free_DigestInfo(&di);
+ return -4;
+ }
+
+ if (flen != di.digest.length || memcmp(di.digest.data, from, flen) != 0) {
+ free_DigestInfo(&di);
+ return -5;
+ }
+
+ if (type == NID_sha1) {
+ digest_alg = &_signature_sha1_data;
+ } else if (type == NID_md5) {
+ digest_alg = &_signature_md5_data;
+ } else if (type == NID_sha256) {
+ digest_alg = &_signature_sha256_data;
+ } else {
+ free_DigestInfo(&di);
+ return -1;
+ }
+
+ ret = der_heim_oid_cmp(&digest_alg->algorithm,
+ &di.digestAlgorithm.algorithm);
+ free_DigestInfo(&di);
+
+ if (ret != 0)
+ return 0;
+ return 1;
+ }
+
+ return 0;
+}
+
+/*
+ * A NULL RSA_METHOD that returns failure for all operations. This is
+ * used as the default RSA method if we don't have any native
+ * support.
+ */
+
+static RSAFUNC(null_rsa_public_encrypt, -1)
+static RSAFUNC(null_rsa_public_decrypt, -1)
+static RSAFUNC(null_rsa_private_encrypt, -1)
+static RSAFUNC(null_rsa_private_decrypt, -1)
+
+/*
+ *
+ */
+
+int
+RSA_generate_key_ex(RSA *r, int bits, BIGNUM *e, BN_GENCB *cb)
+{
+ if (r->meth->rsa_keygen)
+ return (*r->meth->rsa_keygen)(r, bits, e, cb);
+ return 0;
+}
+
+
+/*
+ *
+ */
+
+static int
+null_rsa_init(RSA *rsa)
+{
+ return 1;
+}
+
+static int
+null_rsa_finish(RSA *rsa)
+{
+ return 1;
+}
+
+static const RSA_METHOD rsa_null_method = {
+ "hcrypto null RSA",
+ null_rsa_public_encrypt,
+ null_rsa_public_decrypt,
+ null_rsa_private_encrypt,
+ null_rsa_private_decrypt,
+ NULL,
+ NULL,
+ null_rsa_init,
+ null_rsa_finish,
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+const RSA_METHOD *
+RSA_null_method(void)
+{
+ return &rsa_null_method;
+}
+
+extern const RSA_METHOD hc_rsa_gmp_method;
+extern const RSA_METHOD hc_rsa_tfm_method;
+extern const RSA_METHOD hc_rsa_ltm_method;
+static const RSA_METHOD *default_rsa_method = &hc_rsa_ltm_method;
+
+
+const RSA_METHOD *
+RSA_get_default_method(void)
+{
+ return default_rsa_method;
+}
+
+void
+RSA_set_default_method(const RSA_METHOD *meth)
+{
+ default_rsa_method = meth;
+}
+
+/*
+ *
+ */
+
+RSA *
+d2i_RSAPrivateKey(RSA *rsa, const unsigned char **pp, size_t len)
+{
+ RSAPrivateKey data;
+ RSA *k = rsa;
+ size_t size;
+ int ret;
+
+ ret = decode_RSAPrivateKey(*pp, len, &data, &size);
+ if (ret)
+ return NULL;
+
+ *pp += size;
+
+ if (k == NULL) {
+ k = RSA_new();
+ if (k == NULL) {
+ free_RSAPrivateKey(&data);
+ return NULL;
+ }
+ }
+
+ k->n = _hc_integer_to_BN(&data.modulus, NULL);
+ k->e = _hc_integer_to_BN(&data.publicExponent, NULL);
+ k->d = _hc_integer_to_BN(&data.privateExponent, NULL);
+ k->p = _hc_integer_to_BN(&data.prime1, NULL);
+ k->q = _hc_integer_to_BN(&data.prime2, NULL);
+ k->dmp1 = _hc_integer_to_BN(&data.exponent1, NULL);
+ k->dmq1 = _hc_integer_to_BN(&data.exponent2, NULL);
+ k->iqmp = _hc_integer_to_BN(&data.coefficient, NULL);
+ free_RSAPrivateKey(&data);
+
+ if (k->n == NULL || k->e == NULL || k->d == NULL || k->p == NULL ||
+ k->q == NULL || k->dmp1 == NULL || k->dmq1 == NULL || k->iqmp == NULL)
+ {
+ RSA_free(k);
+ return NULL;
+ }
+
+ return k;
+}
+
+int
+i2d_RSAPrivateKey(RSA *rsa, unsigned char **pp)
+{
+ RSAPrivateKey data;
+ size_t size;
+ int ret;
+
+ if (rsa->n == NULL || rsa->e == NULL || rsa->d == NULL || rsa->p == NULL ||
+ rsa->q == NULL || rsa->dmp1 == NULL || rsa->dmq1 == NULL ||
+ rsa->iqmp == NULL)
+ return -1;
+
+ memset(&data, 0, sizeof(data));
+
+ ret = _hc_BN_to_integer(rsa->n, &data.modulus);
+ ret |= _hc_BN_to_integer(rsa->e, &data.publicExponent);
+ ret |= _hc_BN_to_integer(rsa->d, &data.privateExponent);
+ ret |= _hc_BN_to_integer(rsa->p, &data.prime1);
+ ret |= _hc_BN_to_integer(rsa->q, &data.prime2);
+ ret |= _hc_BN_to_integer(rsa->dmp1, &data.exponent1);
+ ret |= _hc_BN_to_integer(rsa->dmq1, &data.exponent2);
+ ret |= _hc_BN_to_integer(rsa->iqmp, &data.coefficient);
+ if (ret) {
+ free_RSAPrivateKey(&data);
+ return -1;
+ }
+
+ if (pp == NULL) {
+ size = length_RSAPrivateKey(&data);
+ free_RSAPrivateKey(&data);
+ } else {
+ void *p;
+ size_t len;
+
+ ASN1_MALLOC_ENCODE(RSAPrivateKey, p, len, &data, &size, ret);
+ free_RSAPrivateKey(&data);
+ if (ret)
+ return -1;
+ if (len != size)
+ abort();
+
+ memcpy(*pp, p, size);
+ free(p);
+
+ *pp += size;
+
+ }
+ return size;
+}
+
+int
+i2d_RSAPublicKey(RSA *rsa, unsigned char **pp)
+{
+ RSAPublicKey data;
+ size_t size;
+ int ret;
+
+ memset(&data, 0, sizeof(data));
+
+ if (_hc_BN_to_integer(rsa->n, &data.modulus) ||
+ _hc_BN_to_integer(rsa->e, &data.publicExponent))
+ {
+ free_RSAPublicKey(&data);
+ return -1;
+ }
+
+ if (pp == NULL) {
+ size = length_RSAPublicKey(&data);
+ free_RSAPublicKey(&data);
+ } else {
+ void *p;
+ size_t len;
+
+ ASN1_MALLOC_ENCODE(RSAPublicKey, p, len, &data, &size, ret);
+ free_RSAPublicKey(&data);
+ if (ret)
+ return -1;
+ if (len != size)
+ abort();
+
+ memcpy(*pp, p, size);
+ free(p);
+
+ *pp += size;
+ }
+
+ return size;
+}
+
+RSA *
+d2i_RSAPublicKey(RSA *rsa, const unsigned char **pp, size_t len)
+{
+ RSAPublicKey data;
+ RSA *k = rsa;
+ size_t size;
+ int ret;
+
+ ret = decode_RSAPublicKey(*pp, len, &data, &size);
+ if (ret)
+ return NULL;
+
+ *pp += size;
+
+ if (k == NULL) {
+ k = RSA_new();
+ if (k == NULL) {
+ free_RSAPublicKey(&data);
+ return NULL;
+ }
+ }
+
+ k->n = _hc_integer_to_BN(&data.modulus, NULL);
+ k->e = _hc_integer_to_BN(&data.publicExponent, NULL);
+
+ free_RSAPublicKey(&data);
+
+ if (k->n == NULL || k->e == NULL) {
+ RSA_free(k);
+ return NULL;
+ }
+
+ return k;
+}
diff --git a/third_party/heimdal/lib/hcrypto/rsa.h b/third_party/heimdal/lib/hcrypto/rsa.h
new file mode 100644
index 0000000..d59213b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rsa.h
@@ -0,0 +1,184 @@
+/*
+ * Copyright (c) 2006-2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef _HEIM_RSA_H
+#define _HEIM_RSA_H 1
+
+/* symbol renaming */
+#define RSA_null_method hc_RSA_null_method
+#define RSA_ltm_method hc_RSA_ltm_method
+#define RSA_gmp_method hc_RSA_gmp_method
+#define RSA_tfm_method hc_RSA_tfm_method
+#define RSA_new hc_RSA_new
+#define RSA_new_method hc_RSA_new_method
+#define RSA_free hc_RSA_free
+#define RSA_up_ref hc_RSA_up_ref
+#define RSA_set_default_method hc_RSA_set_default_method
+#define RSA_get_default_method hc_RSA_get_default_method
+#define RSA_set_method hc_RSA_set_method
+#define RSA_get_method hc_RSA_get_method
+#define RSA_set_app_data hc_RSA_set_app_data
+#define RSA_get_app_data hc_RSA_get_app_data
+#define RSA_check_key hc_RSA_check_key
+#define RSA_size hc_RSA_size
+#define RSA_public_encrypt hc_RSA_public_encrypt
+#define RSA_public_decrypt hc_RSA_public_decrypt
+#define RSA_private_encrypt hc_RSA_private_encrypt
+#define RSA_private_decrypt hc_RSA_private_decrypt
+#define RSA_sign hc_RSA_sign
+#define RSA_verify hc_RSA_verify
+#define RSA_generate_key_ex hc_RSA_generate_key_ex
+#define d2i_RSAPrivateKey hc_d2i_RSAPrivateKey
+#define i2d_RSAPrivateKey hc_i2d_RSAPrivateKey
+#define i2d_RSAPublicKey hc_i2d_RSAPublicKey
+#define d2i_RSAPublicKey hc_d2i_RSAPublicKey
+
+#define RSA hc_RSA
+#define RSA_METHOD hc_RSA_METHOD
+
+/*
+ *
+ */
+
+typedef struct RSA RSA;
+typedef struct RSA_METHOD RSA_METHOD;
+
+#include <hcrypto/bn.h>
+#include <hcrypto/engine.h>
+
+struct RSA_METHOD {
+ const char *name;
+ int (*rsa_pub_enc)(int,const unsigned char *, unsigned char *, RSA *,int);
+ int (*rsa_pub_dec)(int,const unsigned char *, unsigned char *, RSA *,int);
+ int (*rsa_priv_enc)(int,const unsigned char *, unsigned char *, RSA *,int);
+ int (*rsa_priv_dec)(int,const unsigned char *, unsigned char *, RSA *,int);
+ void *rsa_mod_exp;
+ void *bn_mod_exp;
+ int (*init)(RSA *rsa);
+ int (*finish)(RSA *rsa);
+ int flags;
+ char *app_data;
+ int (*rsa_sign)(int, const unsigned char *, unsigned int,
+ unsigned char *, unsigned int *, const RSA *);
+ int (*rsa_verify)(int, const unsigned char *, unsigned int,
+ unsigned char *, unsigned int, const RSA *);
+ int (*rsa_keygen)(RSA *, int, BIGNUM *, BN_GENCB *);
+};
+
+struct RSA {
+ int pad;
+ long version;
+ const RSA_METHOD *meth;
+ void *engine;
+ BIGNUM *n;
+ BIGNUM *e;
+ BIGNUM *d;
+ BIGNUM *p;
+ BIGNUM *q;
+ BIGNUM *dmp1;
+ BIGNUM *dmq1;
+ BIGNUM *iqmp;
+ struct rsa_CRYPTO_EX_DATA {
+ void *sk;
+ int dummy;
+ } ex_data;
+ int references;
+ int flags;
+ void *_method_mod_n;
+ void *_method_mod_p;
+ void *_method_mod_q;
+
+ char *bignum_data;
+ void *blinding;
+ void *mt_blinding;
+};
+
+#define RSA_FLAG_NO_BLINDING 0x0080
+
+#define RSA_PKCS1_PADDING 1
+#define RSA_PKCS1_OAEP_PADDING 4
+#define RSA_PKCS1_PADDING_SIZE 11
+
+/*
+ *
+ */
+
+const RSA_METHOD *RSA_null_method(void);
+const RSA_METHOD *RSA_gmp_method(void);
+const RSA_METHOD *RSA_tfm_method(void);
+const RSA_METHOD *RSA_ltm_method(void);
+
+/*
+ *
+ */
+
+RSA * RSA_new(void);
+RSA * RSA_new_method(ENGINE *);
+void RSA_free(RSA *);
+int RSA_up_ref(RSA *);
+
+void RSA_set_default_method(const RSA_METHOD *);
+const RSA_METHOD * RSA_get_default_method(void);
+
+const RSA_METHOD * RSA_get_method(const RSA *);
+int RSA_set_method(RSA *, const RSA_METHOD *);
+
+int RSA_set_app_data(RSA *, void *arg);
+void * RSA_get_app_data(const RSA *);
+
+int RSA_check_key(const RSA *);
+int RSA_size(const RSA *);
+
+int RSA_public_encrypt(int,const unsigned char*,unsigned char*,RSA *,int);
+int RSA_private_encrypt(int,const unsigned char*,unsigned char*,RSA *,int);
+int RSA_public_decrypt(int,const unsigned char*,unsigned char*,RSA *,int);
+int RSA_private_decrypt(int,const unsigned char*,unsigned char*,RSA *,int);
+
+int RSA_sign(int, const unsigned char *, unsigned int,
+ unsigned char *, unsigned int *, RSA *);
+int RSA_verify(int, const unsigned char *, unsigned int,
+ unsigned char *, unsigned int, RSA *);
+
+int RSA_generate_key_ex(RSA *, int, BIGNUM *, BN_GENCB *);
+
+RSA * d2i_RSAPrivateKey(RSA *, const unsigned char **, size_t);
+int i2d_RSAPrivateKey(RSA *, unsigned char **);
+
+int i2d_RSAPublicKey(RSA *, unsigned char **);
+RSA * d2i_RSAPublicKey(RSA *, const unsigned char **, size_t);
+
+#endif /* _HEIM_RSA_H */
diff --git a/third_party/heimdal/lib/hcrypto/rsakey.der b/third_party/heimdal/lib/hcrypto/rsakey.der
new file mode 100644
index 0000000..e7c665e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rsakey.der
Binary files differ
diff --git a/third_party/heimdal/lib/hcrypto/rsakey2048.der b/third_party/heimdal/lib/hcrypto/rsakey2048.der
new file mode 100644
index 0000000..c802d3b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rsakey2048.der
Binary files differ
diff --git a/third_party/heimdal/lib/hcrypto/rsakey4096.der b/third_party/heimdal/lib/hcrypto/rsakey4096.der
new file mode 100644
index 0000000..1b763b8
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/rsakey4096.der
Binary files differ
diff --git a/third_party/heimdal/lib/hcrypto/sha.c b/third_party/heimdal/lib/hcrypto/sha.c
new file mode 100644
index 0000000..8eae9b4
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/sha.c
@@ -0,0 +1,300 @@
+/*
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include "hash.h"
+#include "sha.h"
+
+#define A m->counter[0]
+#define B m->counter[1]
+#define C m->counter[2]
+#define D m->counter[3]
+#define E m->counter[4]
+#define X data
+
+int
+SHA1_Init (struct sha *m)
+{
+ m->sz[0] = 0;
+ m->sz[1] = 0;
+ A = 0x67452301;
+ B = 0xefcdab89;
+ C = 0x98badcfe;
+ D = 0x10325476;
+ E = 0xc3d2e1f0;
+ return 1;
+}
+
+
+#define F0(x,y,z) CRAYFIX((x & y) | (~x & z))
+#define F1(x,y,z) (x ^ y ^ z)
+#define F2(x,y,z) ((x & y) | (x & z) | (y & z))
+#define F3(x,y,z) F1(x,y,z)
+
+#define K0 0x5a827999
+#define K1 0x6ed9eba1
+#define K2 0x8f1bbcdc
+#define K3 0xca62c1d6
+
+#define DO(t,f,k) \
+do { \
+ uint32_t temp; \
+ \
+ temp = cshift(AA, 5) + f(BB,CC,DD) + EE + data[t] + k; \
+ EE = DD; \
+ DD = CC; \
+ CC = cshift(BB, 30); \
+ BB = AA; \
+ AA = temp; \
+} while(0)
+
+static inline void
+calc (struct sha *m, uint32_t *in)
+{
+ uint32_t AA, BB, CC, DD, EE;
+ uint32_t data[80];
+ int i;
+
+ AA = A;
+ BB = B;
+ CC = C;
+ DD = D;
+ EE = E;
+
+ for (i = 0; i < 16; ++i)
+ data[i] = in[i];
+ for (i = 16; i < 80; ++i)
+ data[i] = cshift(data[i-3] ^ data[i-8] ^ data[i-14] ^ data[i-16], 1);
+
+ /* t=[0,19] */
+
+ DO(0,F0,K0);
+ DO(1,F0,K0);
+ DO(2,F0,K0);
+ DO(3,F0,K0);
+ DO(4,F0,K0);
+ DO(5,F0,K0);
+ DO(6,F0,K0);
+ DO(7,F0,K0);
+ DO(8,F0,K0);
+ DO(9,F0,K0);
+ DO(10,F0,K0);
+ DO(11,F0,K0);
+ DO(12,F0,K0);
+ DO(13,F0,K0);
+ DO(14,F0,K0);
+ DO(15,F0,K0);
+ DO(16,F0,K0);
+ DO(17,F0,K0);
+ DO(18,F0,K0);
+ DO(19,F0,K0);
+
+ /* t=[20,39] */
+
+ DO(20,F1,K1);
+ DO(21,F1,K1);
+ DO(22,F1,K1);
+ DO(23,F1,K1);
+ DO(24,F1,K1);
+ DO(25,F1,K1);
+ DO(26,F1,K1);
+ DO(27,F1,K1);
+ DO(28,F1,K1);
+ DO(29,F1,K1);
+ DO(30,F1,K1);
+ DO(31,F1,K1);
+ DO(32,F1,K1);
+ DO(33,F1,K1);
+ DO(34,F1,K1);
+ DO(35,F1,K1);
+ DO(36,F1,K1);
+ DO(37,F1,K1);
+ DO(38,F1,K1);
+ DO(39,F1,K1);
+
+ /* t=[40,59] */
+
+ DO(40,F2,K2);
+ DO(41,F2,K2);
+ DO(42,F2,K2);
+ DO(43,F2,K2);
+ DO(44,F2,K2);
+ DO(45,F2,K2);
+ DO(46,F2,K2);
+ DO(47,F2,K2);
+ DO(48,F2,K2);
+ DO(49,F2,K2);
+ DO(50,F2,K2);
+ DO(51,F2,K2);
+ DO(52,F2,K2);
+ DO(53,F2,K2);
+ DO(54,F2,K2);
+ DO(55,F2,K2);
+ DO(56,F2,K2);
+ DO(57,F2,K2);
+ DO(58,F2,K2);
+ DO(59,F2,K2);
+
+ /* t=[60,79] */
+
+ DO(60,F3,K3);
+ DO(61,F3,K3);
+ DO(62,F3,K3);
+ DO(63,F3,K3);
+ DO(64,F3,K3);
+ DO(65,F3,K3);
+ DO(66,F3,K3);
+ DO(67,F3,K3);
+ DO(68,F3,K3);
+ DO(69,F3,K3);
+ DO(70,F3,K3);
+ DO(71,F3,K3);
+ DO(72,F3,K3);
+ DO(73,F3,K3);
+ DO(74,F3,K3);
+ DO(75,F3,K3);
+ DO(76,F3,K3);
+ DO(77,F3,K3);
+ DO(78,F3,K3);
+ DO(79,F3,K3);
+
+ A += AA;
+ B += BB;
+ C += CC;
+ D += DD;
+ E += EE;
+}
+
+/*
+ * From `Performance analysis of MD5' by Joseph D. Touch <touch@isi.edu>
+ */
+
+#if !defined(WORDS_BIGENDIAN) || defined(_CRAY)
+static inline uint32_t
+swap_uint32_t (uint32_t t)
+{
+#define ROL(x,n) ((x)<<(n))|((x)>>(32-(n)))
+ uint32_t temp1, temp2;
+
+ temp1 = cshift(t, 16);
+ temp2 = temp1 >> 8;
+ temp1 &= 0x00ff00ff;
+ temp2 &= 0x00ff00ff;
+ temp1 <<= 8;
+ return temp1 | temp2;
+}
+#endif
+
+struct x32{
+ unsigned int a:32;
+ unsigned int b:32;
+};
+
+int
+SHA1_Update (struct sha *m, const void *v, size_t len)
+{
+ const unsigned char *p = v;
+ size_t old_sz = m->sz[0];
+ size_t offset;
+
+ m->sz[0] += len * 8;
+ if (m->sz[0] < old_sz)
+ ++m->sz[1];
+ offset = (old_sz / 8) % 64;
+ while(len > 0){
+ size_t l = min(len, 64 - offset);
+ memcpy(m->save + offset, p, l);
+ offset += l;
+ p += l;
+ len -= l;
+ if(offset == 64){
+#if !defined(WORDS_BIGENDIAN) || defined(_CRAY)
+ int i;
+ uint32_t SHA1current[16];
+ struct x32 *us = (struct x32*)m->save;
+ for(i = 0; i < 8; i++){
+ SHA1current[2*i+0] = swap_uint32_t(us[i].a);
+ SHA1current[2*i+1] = swap_uint32_t(us[i].b);
+ }
+ calc(m, SHA1current);
+#else
+ calc(m, (uint32_t*)m->save);
+#endif
+ offset = 0;
+ }
+ }
+ return 1;
+}
+
+int
+SHA1_Final (void *res, struct sha *m)
+{
+ unsigned char zeros[72];
+ unsigned offset = (m->sz[0] / 8) % 64;
+ unsigned int dstart = (120 - offset - 1) % 64 + 1;
+
+ *zeros = 0x80;
+ memset (zeros + 1, 0, sizeof(zeros) - 1);
+ zeros[dstart+7] = (m->sz[0] >> 0) & 0xff;
+ zeros[dstart+6] = (m->sz[0] >> 8) & 0xff;
+ zeros[dstart+5] = (m->sz[0] >> 16) & 0xff;
+ zeros[dstart+4] = (m->sz[0] >> 24) & 0xff;
+ zeros[dstart+3] = (m->sz[1] >> 0) & 0xff;
+ zeros[dstart+2] = (m->sz[1] >> 8) & 0xff;
+ zeros[dstart+1] = (m->sz[1] >> 16) & 0xff;
+ zeros[dstart+0] = (m->sz[1] >> 24) & 0xff;
+ SHA1_Update (m, zeros, dstart + 8);
+ {
+ int i;
+ unsigned char *r = (unsigned char*)res;
+
+ for (i = 0; i < 5; ++i) {
+ r[4*i+3] = m->counter[i] & 0xFF;
+ r[4*i+2] = (m->counter[i] >> 8) & 0xFF;
+ r[4*i+1] = (m->counter[i] >> 16) & 0xFF;
+ r[4*i] = (m->counter[i] >> 24) & 0xFF;
+ }
+ }
+#if 0
+ {
+ int i;
+ uint32_t *r = (uint32_t *)res;
+
+ for (i = 0; i < 5; ++i)
+ r[i] = swap_uint32_t (m->counter[i]);
+ }
+#endif
+ return 1;
+}
diff --git a/third_party/heimdal/lib/hcrypto/sha.h b/third_party/heimdal/lib/hcrypto/sha.h
new file mode 100644
index 0000000..59d7240
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/sha.h
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_SHA_H
+#define HEIM_SHA_H 1
+
+/* symbol renaming */
+#define SHA1_Init hc_SHA1_Init
+#define SHA1_Update hc_SHA1_Update
+#define SHA1_Final hc_SHA1_Final
+#define SHA256_Init hc_SHA256_Init
+#define SHA256_Update hc_SHA256_Update
+#define SHA256_Final hc_SHA256_Final
+#define SHA384_Init hc_SHA384_Init
+#define SHA384_Update hc_SHA384_Update
+#define SHA384_Final hc_SHA384_Final
+#define SHA512_Init hc_SHA512_Init
+#define SHA512_Update hc_SHA512_Update
+#define SHA512_Final hc_SHA512_Final
+
+/*
+ * SHA-1
+ */
+
+#define SHA_DIGEST_LENGTH 20
+
+struct sha {
+ unsigned int sz[2];
+ uint32_t counter[5];
+ unsigned char save[64];
+};
+
+typedef struct sha SHA_CTX;
+
+int SHA1_Init (struct sha *m);
+int SHA1_Update (struct sha *m, const void *v, size_t len);
+int SHA1_Final (void *res, struct sha *m);
+
+/*
+ * SHA-2 256
+ */
+
+#define SHA256_DIGEST_LENGTH 32
+
+struct hc_sha256state {
+ unsigned int sz[2];
+ uint32_t counter[8];
+ unsigned char save[64];
+};
+
+typedef struct hc_sha256state SHA256_CTX;
+
+int SHA256_Init (SHA256_CTX *);
+int SHA256_Update (SHA256_CTX *, const void *, size_t);
+int SHA256_Final (void *, SHA256_CTX *);
+
+/*
+ * SHA-2 512
+ */
+
+#define SHA512_DIGEST_LENGTH 64
+
+struct hc_sha512state {
+ uint64_t sz[2];
+ uint64_t counter[8];
+ unsigned char save[128];
+};
+
+typedef struct hc_sha512state SHA512_CTX;
+
+int SHA512_Init (SHA512_CTX *);
+int SHA512_Update (SHA512_CTX *, const void *, size_t);
+int SHA512_Final (void *, SHA512_CTX *);
+
+#define SHA384_DIGEST_LENGTH 48
+
+typedef struct hc_sha512state SHA384_CTX;
+
+int SHA384_Init (SHA384_CTX *);
+int SHA384_Update (SHA384_CTX *, const void *, size_t);
+int SHA384_Final (void *, SHA384_CTX *);
+
+#endif /* HEIM_SHA_H */
diff --git a/third_party/heimdal/lib/hcrypto/sha256.c b/third_party/heimdal/lib/hcrypto/sha256.c
new file mode 100644
index 0000000..1b62ba2
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/sha256.c
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include "hash.h"
+#include "sha.h"
+
+#define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z)))
+#define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
+
+#define ROTR(x,n) (((x)>>(n)) | ((x) << (32 - (n))))
+
+#define Sigma0(x) (ROTR(x,2) ^ ROTR(x,13) ^ ROTR(x,22))
+#define Sigma1(x) (ROTR(x,6) ^ ROTR(x,11) ^ ROTR(x,25))
+#define sigma0(x) (ROTR(x,7) ^ ROTR(x,18) ^ ((x)>>3))
+#define sigma1(x) (ROTR(x,17) ^ ROTR(x,19) ^ ((x)>>10))
+
+#define A m->counter[0]
+#define B m->counter[1]
+#define C m->counter[2]
+#define D m->counter[3]
+#define E m->counter[4]
+#define F m->counter[5]
+#define G m->counter[6]
+#define H m->counter[7]
+
+static const uint32_t constant_256[64] = {
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
+ 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
+ 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
+ 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
+ 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
+ 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
+ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
+};
+
+int
+SHA256_Init (SHA256_CTX *m)
+{
+ m->sz[0] = 0;
+ m->sz[1] = 0;
+ A = 0x6a09e667;
+ B = 0xbb67ae85;
+ C = 0x3c6ef372;
+ D = 0xa54ff53a;
+ E = 0x510e527f;
+ F = 0x9b05688c;
+ G = 0x1f83d9ab;
+ H = 0x5be0cd19;
+ return 1;
+}
+
+static void
+calc (SHA256_CTX *m, uint32_t *in)
+{
+ uint32_t AA, BB, CC, DD, EE, FF, GG, HH;
+ uint32_t data[64];
+ int i;
+
+ AA = A;
+ BB = B;
+ CC = C;
+ DD = D;
+ EE = E;
+ FF = F;
+ GG = G;
+ HH = H;
+
+ for (i = 0; i < 16; ++i)
+ data[i] = in[i];
+ for (i = 16; i < 64; ++i)
+ data[i] = sigma1(data[i-2]) + data[i-7] +
+ sigma0(data[i-15]) + data[i - 16];
+
+ for (i = 0; i < 64; i++) {
+ uint32_t T1, T2;
+
+ T1 = HH + Sigma1(EE) + Ch(EE, FF, GG) + constant_256[i] + data[i];
+ T2 = Sigma0(AA) + Maj(AA,BB,CC);
+
+ HH = GG;
+ GG = FF;
+ FF = EE;
+ EE = DD + T1;
+ DD = CC;
+ CC = BB;
+ BB = AA;
+ AA = T1 + T2;
+ }
+
+ A += AA;
+ B += BB;
+ C += CC;
+ D += DD;
+ E += EE;
+ F += FF;
+ G += GG;
+ H += HH;
+}
+
+/*
+ * From `Performance analysis of MD5' by Joseph D. Touch <touch@isi.edu>
+ */
+
+#if !defined(WORDS_BIGENDIAN) || defined(_CRAY)
+static inline uint32_t
+swap_uint32_t (uint32_t t)
+{
+#define ROL(x,n) ((x)<<(n))|((x)>>(32-(n)))
+ uint32_t temp1, temp2;
+
+ temp1 = cshift(t, 16);
+ temp2 = temp1 >> 8;
+ temp1 &= 0x00ff00ff;
+ temp2 &= 0x00ff00ff;
+ temp1 <<= 8;
+ return temp1 | temp2;
+}
+#endif
+
+struct x32{
+ unsigned int a:32;
+ unsigned int b:32;
+};
+
+int
+SHA256_Update (SHA256_CTX *m, const void *v, size_t len)
+{
+ const unsigned char *p = v;
+ size_t old_sz = m->sz[0];
+ size_t offset;
+
+ m->sz[0] += len * 8;
+ if (m->sz[0] < old_sz)
+ ++m->sz[1];
+ offset = (old_sz / 8) % 64;
+ while(len > 0){
+ size_t l = min(len, 64 - offset);
+ memcpy(m->save + offset, p, l);
+ offset += l;
+ p += l;
+ len -= l;
+ if(offset == 64){
+#if !defined(WORDS_BIGENDIAN) || defined(_CRAY)
+ int i;
+ uint32_t current[16];
+ struct x32 *us = (struct x32*)m->save;
+ for(i = 0; i < 8; i++){
+ current[2*i+0] = swap_uint32_t(us[i].a);
+ current[2*i+1] = swap_uint32_t(us[i].b);
+ }
+ calc(m, current);
+#else
+ calc(m, (uint32_t*)m->save);
+#endif
+ offset = 0;
+ }
+ }
+ return 1;
+}
+
+int
+SHA256_Final (void *res, SHA256_CTX *m)
+{
+ unsigned char zeros[72];
+ unsigned offset = (m->sz[0] / 8) % 64;
+ unsigned int dstart = (120 - offset - 1) % 64 + 1;
+
+ *zeros = 0x80;
+ memset (zeros + 1, 0, sizeof(zeros) - 1);
+ zeros[dstart+7] = (m->sz[0] >> 0) & 0xff;
+ zeros[dstart+6] = (m->sz[0] >> 8) & 0xff;
+ zeros[dstart+5] = (m->sz[0] >> 16) & 0xff;
+ zeros[dstart+4] = (m->sz[0] >> 24) & 0xff;
+ zeros[dstart+3] = (m->sz[1] >> 0) & 0xff;
+ zeros[dstart+2] = (m->sz[1] >> 8) & 0xff;
+ zeros[dstart+1] = (m->sz[1] >> 16) & 0xff;
+ zeros[dstart+0] = (m->sz[1] >> 24) & 0xff;
+ SHA256_Update (m, zeros, dstart + 8);
+ {
+ int i;
+ unsigned char *r = (unsigned char*)res;
+
+ for (i = 0; i < 8; ++i) {
+ r[4*i+3] = m->counter[i] & 0xFF;
+ r[4*i+2] = (m->counter[i] >> 8) & 0xFF;
+ r[4*i+1] = (m->counter[i] >> 16) & 0xFF;
+ r[4*i] = (m->counter[i] >> 24) & 0xFF;
+ }
+ }
+ return 1;
+}
diff --git a/third_party/heimdal/lib/hcrypto/sha512.c b/third_party/heimdal/lib/hcrypto/sha512.c
new file mode 100644
index 0000000..98c418e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/sha512.c
@@ -0,0 +1,301 @@
+/*
+ * Copyright (c) 2006, 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include "hash.h"
+#include "sha.h"
+
+#define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z)))
+#define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
+
+#define ROTR(x,n) (((x)>>(n)) | ((x) << (64 - (n))))
+
+#define Sigma0(x) (ROTR(x,28) ^ ROTR(x,34) ^ ROTR(x,39))
+#define Sigma1(x) (ROTR(x,14) ^ ROTR(x,18) ^ ROTR(x,41))
+#define sigma0(x) (ROTR(x,1) ^ ROTR(x,8) ^ ((x)>>7))
+#define sigma1(x) (ROTR(x,19) ^ ROTR(x,61) ^ ((x)>>6))
+
+#define A m->counter[0]
+#define B m->counter[1]
+#define C m->counter[2]
+#define D m->counter[3]
+#define E m->counter[4]
+#define F m->counter[5]
+#define G m->counter[6]
+#define H m->counter[7]
+
+static const uint64_t constant_512[80] = {
+ 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
+ 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
+ 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
+ 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
+ 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
+ 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
+ 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
+ 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
+ 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
+ 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
+ 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
+ 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
+ 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
+ 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
+ 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
+ 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
+ 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
+ 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
+ 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
+ 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
+ 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
+ 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
+ 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
+ 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
+ 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
+ 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
+ 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
+ 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
+ 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
+ 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
+ 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
+ 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
+ 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
+ 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
+ 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
+ 0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
+ 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
+ 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
+ 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
+ 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL
+};
+
+int
+SHA512_Init (SHA512_CTX *m)
+{
+ m->sz[0] = 0;
+ m->sz[1] = 0;
+ A = 0x6a09e667f3bcc908ULL;
+ B = 0xbb67ae8584caa73bULL;
+ C = 0x3c6ef372fe94f82bULL;
+ D = 0xa54ff53a5f1d36f1ULL;
+ E = 0x510e527fade682d1ULL;
+ F = 0x9b05688c2b3e6c1fULL;
+ G = 0x1f83d9abfb41bd6bULL;
+ H = 0x5be0cd19137e2179ULL;
+ return 1;
+}
+
+static void
+calc (SHA512_CTX *m, uint64_t *in)
+{
+ uint64_t AA, BB, CC, DD, EE, FF, GG, HH;
+ uint64_t data[80];
+ int i;
+
+ AA = A;
+ BB = B;
+ CC = C;
+ DD = D;
+ EE = E;
+ FF = F;
+ GG = G;
+ HH = H;
+
+ for (i = 0; i < 16; ++i)
+ data[i] = in[i];
+ for (i = 16; i < 80; ++i)
+ data[i] = sigma1(data[i-2]) + data[i-7] +
+ sigma0(data[i-15]) + data[i - 16];
+
+ for (i = 0; i < 80; i++) {
+ uint64_t T1, T2;
+
+ T1 = HH + Sigma1(EE) + Ch(EE, FF, GG) + constant_512[i] + data[i];
+ T2 = Sigma0(AA) + Maj(AA,BB,CC);
+
+ HH = GG;
+ GG = FF;
+ FF = EE;
+ EE = DD + T1;
+ DD = CC;
+ CC = BB;
+ BB = AA;
+ AA = T1 + T2;
+ }
+
+ A += AA;
+ B += BB;
+ C += CC;
+ D += DD;
+ E += EE;
+ F += FF;
+ G += GG;
+ H += HH;
+}
+
+/*
+ * From `Performance analysis of MD5' by Joseph D. Touch <touch@isi.edu>
+ */
+
+#if !defined(WORDS_BIGENDIAN) || defined(_CRAY)
+static inline uint64_t
+swap_uint64_t (uint64_t t)
+{
+ uint64_t temp;
+
+ temp = cshift64(t, 32);
+ temp = ((temp & 0xff00ff00ff00ff00ULL) >> 8) |
+ ((temp & 0x00ff00ff00ff00ffULL) << 8);
+ return ((temp & 0xffff0000ffff0000ULL) >> 16) |
+ ((temp & 0x0000ffff0000ffffULL) << 16);
+}
+
+struct x64{
+ uint64_t a;
+ uint64_t b;
+};
+#endif
+
+int
+SHA512_Update (SHA512_CTX *m, const void *v, size_t len)
+{
+ const unsigned char *p = v;
+ size_t old_sz = m->sz[0];
+ size_t offset;
+
+ m->sz[0] += len * 8;
+ if (m->sz[0] < old_sz)
+ ++m->sz[1];
+ offset = (old_sz / 8) % 128;
+ while(len > 0){
+ size_t l = min(len, 128 - offset);
+ memcpy(m->save + offset, p, l);
+ offset += l;
+ p += l;
+ len -= l;
+ if(offset == 128){
+#if !defined(WORDS_BIGENDIAN) || defined(_CRAY)
+ int i;
+ uint64_t current[16];
+ struct x64 *us = (struct x64*)m->save;
+ for(i = 0; i < 8; i++){
+ current[2*i+0] = swap_uint64_t(us[i].a);
+ current[2*i+1] = swap_uint64_t(us[i].b);
+ }
+ calc(m, current);
+#else
+ calc(m, (uint64_t*)m->save);
+#endif
+ offset = 0;
+ }
+ }
+ return 1;
+}
+
+int
+SHA512_Final (void *res, SHA512_CTX *m)
+{
+ unsigned char zeros[128 + 16];
+ unsigned offset = (m->sz[0] / 8) % 128;
+ unsigned int dstart = (240 - offset - 1) % 128 + 1;
+
+ *zeros = 0x80;
+ memset (zeros + 1, 0, sizeof(zeros) - 1);
+ zeros[dstart+15] = (m->sz[0] >> 0) & 0xff;
+ zeros[dstart+14] = (m->sz[0] >> 8) & 0xff;
+ zeros[dstart+13] = (m->sz[0] >> 16) & 0xff;
+ zeros[dstart+12] = (m->sz[0] >> 24) & 0xff;
+ zeros[dstart+11] = (m->sz[0] >> 32) & 0xff;
+ zeros[dstart+10] = (m->sz[0] >> 40) & 0xff;
+ zeros[dstart+9] = (m->sz[0] >> 48) & 0xff;
+ zeros[dstart+8] = (m->sz[0] >> 56) & 0xff;
+
+ zeros[dstart+7] = (m->sz[1] >> 0) & 0xff;
+ zeros[dstart+6] = (m->sz[1] >> 8) & 0xff;
+ zeros[dstart+5] = (m->sz[1] >> 16) & 0xff;
+ zeros[dstart+4] = (m->sz[1] >> 24) & 0xff;
+ zeros[dstart+3] = (m->sz[1] >> 32) & 0xff;
+ zeros[dstart+2] = (m->sz[1] >> 40) & 0xff;
+ zeros[dstart+1] = (m->sz[1] >> 48) & 0xff;
+ zeros[dstart+0] = (m->sz[1] >> 56) & 0xff;
+ SHA512_Update (m, zeros, dstart + 16);
+ {
+ int i;
+ unsigned char *r = (unsigned char*)res;
+
+ for (i = 0; i < 8; ++i) {
+ r[8*i+7] = m->counter[i] & 0xFF;
+ r[8*i+6] = (m->counter[i] >> 8) & 0xFF;
+ r[8*i+5] = (m->counter[i] >> 16) & 0xFF;
+ r[8*i+4] = (m->counter[i] >> 24) & 0xFF;
+ r[8*i+3] = (m->counter[i] >> 32) & 0XFF;
+ r[8*i+2] = (m->counter[i] >> 40) & 0xFF;
+ r[8*i+1] = (m->counter[i] >> 48) & 0xFF;
+ r[8*i] = (m->counter[i] >> 56) & 0xFF;
+ }
+ }
+ return 1;
+}
+
+int
+SHA384_Init(SHA384_CTX *m)
+{
+ m->sz[0] = 0;
+ m->sz[1] = 0;
+ A = 0xcbbb9d5dc1059ed8ULL;
+ B = 0x629a292a367cd507ULL;
+ C = 0x9159015a3070dd17ULL;
+ D = 0x152fecd8f70e5939ULL;
+ E = 0x67332667ffc00b31ULL;
+ F = 0x8eb44a8768581511ULL;
+ G = 0xdb0c2e0d64f98fa7ULL;
+ H = 0x47b5481dbefa4fa4ULL;
+ return 1;
+}
+
+int
+SHA384_Update (SHA384_CTX *m, const void *v, size_t len)
+{
+ SHA512_Update(m, v, len);
+ return 1;
+}
+
+int
+SHA384_Final (void *res, SHA384_CTX *m)
+{
+ unsigned char data[SHA512_DIGEST_LENGTH];
+ SHA512_Final(data, m);
+ memcpy(res, data, SHA384_DIGEST_LENGTH);
+ return 1;
+}
+
diff --git a/third_party/heimdal/lib/hcrypto/test_bn.c b/third_party/heimdal/lib/hcrypto/test_bn.c
new file mode 100644
index 0000000..74709fe
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/test_bn.c
@@ -0,0 +1,392 @@
+/*
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <bn.h>
+#include <rand.h>
+
+static int
+set_get(unsigned long num)
+{
+ BIGNUM *bn;
+
+ bn = BN_new();
+ if (!BN_set_word(bn, num))
+ return 1;
+
+ if (BN_get_word(bn) != num)
+ return 1;
+
+ BN_free(bn);
+ return 0;
+}
+
+#define CHECK(x) do { ret += x; } while(0)
+
+static int
+test_BN_set_get(void)
+{
+ int ret = 0;
+ CHECK(set_get(0));
+ CHECK(set_get(1));
+ CHECK(set_get(0xff));
+ CHECK(set_get(0x1ff));
+ CHECK(set_get(0xffff));
+ CHECK(set_get(0xf000));
+ CHECK(set_get(ULONG_MAX / 2));
+ CHECK(set_get(ULONG_MAX - 1));
+
+ return ret;
+}
+
+static int
+test_BN_bit(void)
+{
+ BIGNUM *bn;
+ int ret = 0;
+
+ bn = BN_new();
+
+ /* test setting and getting of "word" */
+ if (!BN_set_word(bn, 1))
+ return 1;
+ if (!BN_is_bit_set(bn, 0))
+ ret += 1;
+ if (!BN_is_bit_set(bn, 0))
+ ret += 1;
+
+ if (!BN_set_word(bn, 2))
+ return 1;
+ if (!BN_is_bit_set(bn, 1))
+ ret += 1;
+
+ if (!BN_set_word(bn, 3))
+ return 1;
+ if (!BN_is_bit_set(bn, 0))
+ ret += 1;
+ if (!BN_is_bit_set(bn, 1))
+ ret += 1;
+
+ if (!BN_set_word(bn, 0x100))
+ return 1;
+ if (!BN_is_bit_set(bn, 8))
+ ret += 1;
+
+ if (!BN_set_word(bn, 0x1000))
+ return 1;
+ if (!BN_is_bit_set(bn, 12))
+ ret += 1;
+
+ /* test bitsetting */
+ if (!BN_set_word(bn, 1))
+ return 1;
+ if (!BN_set_bit(bn, 1))
+ return 1;
+ if (BN_get_word(bn) != 3)
+ return 1;
+ if (!BN_clear_bit(bn, 0))
+ return 1;
+ if (BN_get_word(bn) != 2)
+ return 1;
+
+ /* test bitsetting past end of current end */
+ BN_clear(bn);
+ if (!BN_set_bit(bn, 12))
+ return 1;
+ if (BN_get_word(bn) != 0x1000)
+ return 1;
+
+ /* test bit and byte counting functions */
+ if (BN_num_bits(bn) != 13)
+ return 1;
+ if (BN_num_bytes(bn) != 2)
+ return 1;
+
+ BN_free(bn);
+ return ret;
+}
+
+struct ietest {
+ char *data;
+ size_t len;
+ unsigned long num;
+} ietests[] = {
+ { "", 0, 0 },
+ { "\x01", 1, 1 },
+ { "\x02", 1, 2 },
+ { "\xf2", 1, 0xf2 },
+ { "\x01\x00", 2, 256 }
+};
+
+static int
+test_BN_import_export(void)
+{
+ BIGNUM *bn;
+ int ret = 0;
+ int i;
+
+ bn = BN_new();
+
+ for (i = 0; i < sizeof(ietests)/sizeof(ietests[0]); i++) {
+ size_t len;
+ unsigned char *p;
+ if (!BN_bin2bn((unsigned char*)ietests[i].data, ietests[i].len, bn))
+ return 1;
+ if (BN_get_word(bn) != ietests[i].num)
+ return 1;
+ len = BN_num_bytes(bn);
+ if (len != ietests[i].len)
+ return 1;
+ p = malloc(len + 1);
+ p[len] = 0xf4;
+ BN_bn2bin(bn, p);
+ if (p[len] != 0xf4)
+ return 1;
+ if (memcmp(p, ietests[i].data, ietests[i].len) != 0)
+ return 1;
+ free(p);
+ }
+
+ BN_free(bn);
+ return ret;
+}
+
+static int
+test_BN_uadd(void)
+{
+ BIGNUM *a, *b, *c;
+ char *p;
+
+ a = BN_new();
+ b = BN_new();
+ c = BN_new();
+
+ BN_set_word(a, 1);
+ BN_set_word(b, 2);
+
+ BN_uadd(c, a, b);
+
+ if (BN_get_word(c) != 3)
+ return 1;
+
+ BN_uadd(c, b, a);
+
+ if (BN_get_word(c) != 3)
+ return 1;
+
+ BN_set_word(b, 0xff);
+
+ BN_uadd(c, a, b);
+ if (BN_get_word(c) != 0x100)
+ return 1;
+
+ BN_uadd(c, b, a);
+ if (BN_get_word(c) != 0x100)
+ return 1;
+
+ BN_set_word(a, 0xff);
+
+ BN_uadd(c, a, b);
+ if (BN_get_word(c) != 0x1fe)
+ return 1;
+
+ BN_uadd(c, b, a);
+ if (BN_get_word(c) != 0x1fe)
+ return 1;
+
+
+ BN_free(a);
+ BN_free(b);
+
+ BN_hex2bn(&a, "50212A3B611D46642C825A16A354CE0FD4D85DD2");
+ BN_hex2bn(&b, "84B6C7E8D28ACA1614954DA");
+
+ BN_uadd(c, b, a);
+ p = BN_bn2hex(c);
+ if (strcmp(p, "50212A3B611D466434CDC695307D7AB13621B2AC") != 0) {
+ free(p);
+ return 1;
+ }
+ free(p);
+
+ BN_uadd(c, a, b);
+ p = BN_bn2hex(c);
+ if (strcmp(p, "50212A3B611D466434CDC695307D7AB13621B2AC") != 0) {
+ free(p);
+ return 1;
+ }
+ free(p);
+
+ BN_free(a);
+ BN_free(b);
+ BN_free(c);
+
+ return 0;
+}
+
+static int
+test_BN_cmp(void)
+{
+ BIGNUM *a, *b;
+
+ a = BN_new();
+ b = BN_new();
+
+ if (!BN_set_word(a, 1))
+ return 1;
+ if (!BN_set_word(b, 1))
+ return 1;
+
+ if (BN_cmp(a, b) != 0)
+ return 1;
+ if (BN_cmp(b, a) != 0)
+ return 1;
+
+ if (!BN_set_word(b, 2))
+ return 1;
+
+ if (BN_cmp(a, b) >= 0)
+ return 1;
+ if (BN_cmp(b, a) <= 0)
+ return 1;
+
+ BN_set_negative(b, 1);
+
+ if (BN_cmp(a, b) <= 0)
+ return 1;
+ if (BN_cmp(b, a) >= 0)
+ return 1;
+
+ BN_free(a);
+ BN_free(b);
+
+ BN_hex2bn(&a, "50212A3B611D46642C825A16A354CE0FD4D85DD1");
+ BN_hex2bn(&b, "50212A3B611D46642C825A16A354CE0FD4D85DD2");
+
+ if (BN_cmp(a, b) >= 0)
+ return 1;
+ if (BN_cmp(b, a) <= 0)
+ return 1;
+
+ BN_set_negative(b, 1);
+
+ if (BN_cmp(a, b) <= 0)
+ return 1;
+ if (BN_cmp(b, a) >= 0)
+ return 1;
+
+ BN_free(a);
+ BN_free(b);
+ return 0;
+}
+
+static int
+test_BN_rand(void)
+{
+ BIGNUM *bn;
+
+ if (RAND_status() != 1)
+ return 0;
+
+ bn = BN_new();
+ if (bn == NULL)
+ return 1;
+
+ if (!BN_rand(bn, 1024, 0, 0))
+ return 1;
+
+ BN_free(bn);
+ return 0;
+}
+
+#define testnum 100
+#define testnum2 10
+
+static int
+test_BN_CTX(void)
+{
+ unsigned int i, j;
+ BIGNUM *bn;
+ BN_CTX *c;
+
+ if ((c = BN_CTX_new()) == NULL)
+ return 1;
+
+ for (i = 0; i < testnum; i++) {
+ BN_CTX_start(c);
+ BN_CTX_end(c);
+ }
+
+ for (i = 0; i < testnum; i++)
+ BN_CTX_start(c);
+ for (i = 0; i < testnum; i++)
+ BN_CTX_end(c);
+
+ for (i = 0; i < testnum; i++) {
+ BN_CTX_start(c);
+ if ((bn = BN_CTX_get(c)) == NULL)
+ return 1;
+ BN_CTX_end(c);
+ }
+
+ for (i = 0; i < testnum; i++) {
+ BN_CTX_start(c);
+ for (j = 0; j < testnum2; j++)
+ if ((bn = BN_CTX_get(c)) == NULL)
+ return 1;
+ }
+ for (i = 0; i < testnum; i++)
+ BN_CTX_end(c);
+
+ BN_CTX_free(c);
+ return 0;
+}
+
+
+int
+main(int argc, char **argv)
+{
+ int ret = 0;
+
+ ret += test_BN_set_get();
+ ret += test_BN_bit();
+ ret += test_BN_import_export();
+ ret += test_BN_uadd();
+ ret += test_BN_cmp();
+ ret += test_BN_rand();
+ ret += test_BN_CTX();
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/hcrypto/test_bulk.c b/third_party/heimdal/lib/hcrypto/test_bulk.c
new file mode 100644
index 0000000..e3737fd
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/test_bulk.c
@@ -0,0 +1,314 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+#include <assert.h>
+#include <getarg.h>
+
+#include <evp.h>
+#include <evp-hcrypto.h>
+#include <evp-cc.h>
+#if defined(_WIN32)
+#include <evp-w32.h>
+#endif
+#include <evp-pkcs11.h>
+#include <hex.h>
+#include <err.h>
+
+#ifdef WIN32
+#define STATS_START(M) \
+ LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds; \
+ LARGE_INTEGER Frequency; \
+ \
+ QueryPerformanceFrequency(&Frequency); \
+ QueryPerformanceCounter(&StartingTime);
+
+#define STATS_END(M) \
+ QueryPerformanceCounter(&EndingTime); \
+ ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart; \
+ ElapsedMicroseconds.QuadPart *= 1000000; \
+ ElapsedMicroseconds.QuadPart /= Frequency.QuadPart; \
+ \
+ M += (ElapsedMicroseconds.QuadPart - M) / (i + 1);
+#else
+#define STATS_START(M) \
+ struct timeval StartingTime, EndingTime; \
+ \
+ gettimeofday(&StartingTime, NULL);
+
+#define STATS_END(M) \
+ gettimeofday(&EndingTime, NULL); \
+ timevalsub(&EndingTime, &StartingTime); \
+ M += (EndingTime.tv_sec * 1000000 + EndingTime.tv_usec - M) / (i + 1);
+#endif
+
+static int version_flag;
+static int help_flag;
+static int len = 1;
+static int loops = 20;
+static char *provider = "hcrypto";
+static unsigned char *d;
+
+#ifdef __APPLE__
+#define PROVIDER_USAGE "hcrypto|cc"
+#elif defined(WIN32)
+#define PROVIDER_USAGE "hcrypto|w32crypto"
+#elif __sun || defined(PKCS11_MODULE_PATH)
+#define PROVIDER_USAGE "hcrypto|pkcs11"
+#else
+#define PROVIDER_USAGE "hcrypto"
+#endif
+
+static struct getargs args[] = {
+ { "provider", 0, arg_string, &provider,
+ "crypto provider", PROVIDER_USAGE },
+ { "loops", 0, arg_integer, &loops,
+ "number of loops", "loops" },
+ { "size", 0, arg_integer, &len,
+ "size (KB)", NULL },
+ { "version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ { "help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "");
+ exit (ret);
+}
+
+static int
+test_bulk_cipher(const char *cname, const EVP_CIPHER *c)
+{
+ static unsigned char key[16];
+ static unsigned char iv[16];
+ int i;
+ int64_t M = 0;
+
+ if (c == NULL) {
+ printf("%s not supported\n", cname);
+ return 0;
+ }
+
+ for (i = 0; i < loops; i++) {
+ EVP_CIPHER_CTX ectx;
+ EVP_CIPHER_CTX dctx;
+
+ STATS_START(M)
+
+ EVP_CIPHER_CTX_init(&ectx);
+ EVP_CIPHER_CTX_init(&dctx);
+
+ if (EVP_CipherInit_ex(&ectx, c, NULL, NULL, NULL, 1) != 1)
+ errx(1, "can't init encrypt");
+ if (EVP_CipherInit_ex(&dctx, c, NULL, NULL, NULL, 0) != 1)
+ errx(1, "can't init decrypt");
+
+ EVP_CIPHER_CTX_set_key_length(&ectx, sizeof(key));
+ EVP_CIPHER_CTX_set_key_length(&dctx, sizeof(key));
+
+ if (EVP_CipherInit_ex(&ectx, NULL, NULL, key, iv, 1) != 1)
+ errx(1, "can't init encrypt");
+ if (EVP_CipherInit_ex(&dctx, NULL, NULL, key, iv, 0) != 1)
+ errx(1, "can't init decrypt");
+
+ if (!EVP_Cipher(&ectx, d, d, len))
+ errx(1, "can't encrypt");
+ if (!EVP_Cipher(&dctx, d, d, len))
+ errx(1, "can't decrypt");
+
+ EVP_CIPHER_CTX_cleanup(&ectx);
+ EVP_CIPHER_CTX_cleanup(&dctx);
+
+ STATS_END(M);
+
+ if (d[0] != 0x00 || d[len - 1] != ((len - 1) & 0xff))
+ errx(1, "encrypt/decrypt inconsistent");
+ }
+
+ printf("%s: mean time %llu usec%s\n", cname, (unsigned long long)M,
+ (M == 1) ? "" : "s");
+
+ return 0;
+}
+
+static int
+test_bulk_digest(const char *cname, const EVP_MD *md)
+{
+ char digest[EVP_MAX_MD_SIZE];
+ int i;
+ unsigned int tmp = sizeof(digest);
+ int64_t M = 0;
+
+ if (md == NULL) {
+ printf("%s not supported\n", cname);
+ return 0;
+ }
+
+ for (i = 0; i < loops; i++) {
+ STATS_START(M);
+ EVP_Digest(d, len, digest, &tmp, md, NULL);
+ STATS_END(M);
+ }
+
+ printf("%s: mean time %llu usec%s\n", cname, (unsigned long long)M,
+ (M == 1) ? "" : "s");
+
+ return 0;
+}
+
+static void
+test_bulk_provider_hcrypto(void)
+{
+ test_bulk_cipher("hcrypto_aes_256_cbc", EVP_hcrypto_aes_256_cbc());
+#if 0
+ test_bulk_cipher("hcrypto_aes_256_cfb8", EVP_hcrypto_aes_256_cfb8());
+#endif
+ test_bulk_cipher("hcrypto_rc4", EVP_hcrypto_rc4());
+ test_bulk_digest("hcrypto_md2", EVP_hcrypto_md2());
+ test_bulk_digest("hcrypto_md4", EVP_hcrypto_md4());
+ test_bulk_digest("hcrypto_md5", EVP_hcrypto_md5());
+ test_bulk_digest("hcrypto_sha1", EVP_hcrypto_sha1());
+ test_bulk_digest("hcrypto_sha256", EVP_hcrypto_sha256());
+ test_bulk_digest("hcrypto_sha384", EVP_hcrypto_sha384());
+ test_bulk_digest("hcrypto_sha512", EVP_hcrypto_sha512());
+}
+
+#ifdef __APPLE__
+static void
+test_bulk_provider_cc(void)
+{
+ test_bulk_cipher("cc_aes_256_cbc", EVP_cc_aes_256_cbc());
+#if 0
+ test_bulk_cipher("cc_aes_256_cfb8", EVP_cc_aes_256_cfb8());
+#endif
+ test_bulk_cipher("cc_rc4", EVP_cc_rc4());
+ test_bulk_digest("cc_md2", EVP_cc_md2());
+ test_bulk_digest("cc_md4", EVP_cc_md4());
+ test_bulk_digest("cc_md5", EVP_cc_md5());
+ test_bulk_digest("cc_sha1", EVP_cc_sha1());
+ test_bulk_digest("cc_sha256", EVP_cc_sha256());
+ test_bulk_digest("cc_sha384", EVP_cc_sha384());
+ test_bulk_digest("cc_sha512", EVP_cc_sha512());
+}
+#endif /* __APPLE__ */
+
+#ifdef WIN32
+static void
+test_bulk_provider_w32crypto(void)
+{
+ test_bulk_cipher("w32crypto_aes_256_cbc", EVP_w32crypto_aes_256_cbc());
+#if 0
+ test_bulk_cipher("w32crypto_aes_256_cfb8", EVP_w32crypto_aes_256_cfb8());
+#endif
+ test_bulk_cipher("w32crypto_rc4", EVP_w32crypto_rc4());
+ test_bulk_digest("w32crypto_md2", EVP_w32crypto_md2());
+ test_bulk_digest("w32crypto_md4", EVP_w32crypto_md4());
+ test_bulk_digest("w32crypto_md5", EVP_w32crypto_md5());
+ test_bulk_digest("w32crypto_sha1", EVP_w32crypto_sha1());
+ test_bulk_digest("w32crypto_sha256", EVP_w32crypto_sha256());
+ test_bulk_digest("w32crypto_sha384", EVP_w32crypto_sha384());
+ test_bulk_digest("w32crypto_sha512", EVP_w32crypto_sha512());
+}
+#endif /* WIN32 */
+
+#if __sun || defined(PKCS11_MODULE_PATH)
+static void
+test_bulk_provider_pkcs11(void)
+{
+ test_bulk_cipher("pkcs11_aes_256_cbc", EVP_pkcs11_aes_256_cbc());
+ test_bulk_cipher("pkcs11_rc4", EVP_pkcs11_rc4());
+ test_bulk_digest("pkcs11_md5", EVP_pkcs11_md5());
+ test_bulk_digest("pkcs11_sha1", EVP_pkcs11_sha1());
+ test_bulk_digest("pkcs11_sha256", EVP_pkcs11_sha256());
+ test_bulk_digest("pkcs11_sha384", EVP_pkcs11_sha384());
+ test_bulk_digest("pkcs11_sha512", EVP_pkcs11_sha512());
+}
+#endif /* __sun || PKCS11_MODULE_PATH */
+
+int
+main(int argc, char **argv)
+{
+ int ret = 0;
+ int idx = 0;
+ int i;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &idx))
+ usage(1);
+
+ if (help_flag)
+ usage(0);
+
+ if(version_flag) {
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= idx;
+ argv += idx;
+
+ len *= 1024;
+
+ d = emalloc(len);
+ for (i = 0; i < len; i++)
+ d[i] = i & 0xff;
+
+ if (strcmp(provider, "hcrypto") == 0)
+ test_bulk_provider_hcrypto();
+#ifdef __APPLE__
+ else if (strcmp(provider, "cc") == 0)
+ test_bulk_provider_cc();
+#endif
+#ifdef WIN32
+ else if (strcmp(provider, "w32crypto") == 0)
+ test_bulk_provider_w32crypto();
+#endif
+#if __sun || defined(PKCS11_MODULE_PATH)
+ else if (strcmp(provider, "pkcs11") == 0)
+ test_bulk_provider_pkcs11();
+#endif
+ else
+ usage(1);
+
+ free(d);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/hcrypto/test_cipher.c b/third_party/heimdal/lib/hcrypto/test_cipher.c
new file mode 100644
index 0000000..c566e4b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/test_cipher.c
@@ -0,0 +1,436 @@
+/*
+ * Copyright (c) 2006-2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#define HC_DEPRECATED_CRYPTO
+
+#include <getarg.h>
+
+#include <evp.h>
+#include <evp-hcrypto.h>
+#include <evp-cc.h>
+#if defined(_WIN32)
+#include <evp-w32.h>
+#endif
+#include <evp-pkcs11.h>
+#include <evp-openssl.h>
+#include <hex.h>
+#include <err.h>
+
+struct tests {
+ const char *name;
+ void *key;
+ size_t keysize;
+ void *iv;
+ size_t datasize;
+ void *indata;
+ void *outdata;
+ void *outiv;
+};
+
+struct tests aes_tests[] = {
+ { "aes-256",
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 32,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\xdc\x95\xc0\x78\xa2\x40\x89\x89\xad\x48\xa2\x14\x92\x84\x20\x87",
+ NULL
+ }
+};
+
+struct tests aes_cfb_tests[] = {
+ { "aes-cfb8-128",
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\x66\x16\xf9\x2e\x42\xa8\xf1\x1a\x91\x16\x68\x57\x8e\xc3\xaa\x0f",
+ NULL
+ }
+};
+
+
+struct tests rc2_tests[] = {
+ { "rc2",
+ "\x88\xbc\xa9\x0e\x90\x87\x5a\x7f\x0f\x79\xc3\x84\x62\x7b\xaf\xb2",
+ 16,
+ "\x00\x00\x00\x00\x00\x00\x00\x00",
+ 8,
+ "\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\x22\x69\x55\x2a\xb0\xf8\x5c\xa6",
+ NULL
+ }
+};
+
+
+struct tests rc2_40_tests[] = {
+ { "rc2-40",
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\xc0\xb8\xff\xa5\xd6\xeb\xc9\x62\xcc\x52\x5f\xfe\x9a\x3c\x97\xe6",
+ NULL
+ }
+};
+
+struct tests des_ede3_tests[] = {
+ { "des-ede3",
+ "\x19\x17\xff\xe6\xbb\x77\x2e\xfc"
+ "\x29\x76\x43\xbc\x63\x56\x7e\x9a"
+ "\x00\x2e\x4d\x43\x1d\x5f\xfd\x58",
+ 24,
+ "\xbf\x9a\x12\xb7\x26\x69\xfd\x05",
+ 16,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\x55\x95\x97\x76\xa9\x6c\x66\x40\x64\xc7\xf4\x1c\x21\xb7\x14\x1b",
+ NULL
+ }
+};
+
+struct tests camellia128_tests[] = {
+ { "camellia128",
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ "\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\x07\x92\x3A\x39\xEB\x0A\x81\x7D\x1C\x4D\x87\xBD\xB8\x2D\x1F\x1C",
+ NULL
+ }
+};
+
+struct tests rc4_tests[] = {
+ {
+ "rc4 8",
+ "\x01\x23\x45\x67\x89\xAB\xCD\xEF",
+ 8,
+ NULL,
+ 8,
+ "\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\x74\x94\xC2\xE7\x10\x4B\x08\x79",
+ NULL
+ },
+ {
+ "rc4 5",
+ "\x61\x8a\x63\xd2\xfb",
+ 5,
+ NULL,
+ 5,
+ "\xdc\xee\x4c\xf9\x2c",
+ "\xf1\x38\x29\xc9\xde",
+ NULL
+ },
+ {
+ "rc4 309",
+ "\x29\x04\x19\x72\xfb\x42\xba\x5f\xc7\x12\x77\x12\xf1\x38\x29\xc9",
+ 16,
+ NULL,
+ 309,
+ "\x52\x75\x69\x73\x6c\x69\x6e\x6e"
+ "\x75\x6e\x20\x6c\x61\x75\x6c\x75"
+ "\x20\x6b\x6f\x72\x76\x69\x73\x73"
+ "\x73\x61\x6e\x69\x2c\x20\x74\xe4"
+ "\x68\x6b\xe4\x70\xe4\x69\x64\x65"
+ "\x6e\x20\x70\xe4\xe4\x6c\x6c\xe4"
+ "\x20\x74\xe4\x79\x73\x69\x6b\x75"
+ "\x75\x2e\x20\x4b\x65\x73\xe4\x79"
+ "\xf6\x6e\x20\x6f\x6e\x20\x6f\x6e"
+ "\x6e\x69\x20\x6f\x6d\x61\x6e\x61"
+ "\x6e\x69\x2c\x20\x6b\x61\x73\x6b"
+ "\x69\x73\x61\x76\x75\x75\x6e\x20"
+ "\x6c\x61\x61\x6b\x73\x6f\x74\x20"
+ "\x76\x65\x72\x68\x6f\x75\x75\x2e"
+ "\x20\x45\x6e\x20\x6d\x61\x20\x69"
+ "\x6c\x6f\x69\x74\x73\x65\x2c\x20"
+ "\x73\x75\x72\x65\x20\x68\x75\x6f"
+ "\x6b\x61\x61\x2c\x20\x6d\x75\x74"
+ "\x74\x61\x20\x6d\x65\x74\x73\xe4"
+ "\x6e\x20\x74\x75\x6d\x6d\x75\x75"
+ "\x73\x20\x6d\x75\x6c\x6c\x65\x20"
+ "\x74\x75\x6f\x6b\x61\x61\x2e\x20"
+ "\x50\x75\x75\x6e\x74\x6f\x20\x70"
+ "\x69\x6c\x76\x65\x6e\x2c\x20\x6d"
+ "\x69\x20\x68\x75\x6b\x6b\x75\x75"
+ "\x2c\x20\x73\x69\x69\x6e\x74\x6f"
+ "\x20\x76\x61\x72\x61\x6e\x20\x74"
+ "\x75\x75\x6c\x69\x73\x65\x6e\x2c"
+ "\x20\x6d\x69\x20\x6e\x75\x6b\x6b"
+ "\x75\x75\x2e\x20\x54\x75\x6f\x6b"
+ "\x73\x75\x74\x20\x76\x61\x6e\x61"
+ "\x6d\x6f\x6e\x20\x6a\x61\x20\x76"
+ "\x61\x72\x6a\x6f\x74\x20\x76\x65"
+ "\x65\x6e\x2c\x20\x6e\x69\x69\x73"
+ "\x74\xe4\x20\x73\x79\x64\xe4\x6d"
+ "\x65\x6e\x69\x20\x6c\x61\x75\x6c"
+ "\x75\x6e\x20\x74\x65\x65\x6e\x2e"
+ "\x20\x2d\x20\x45\x69\x6e\x6f\x20"
+ "\x4c\x65\x69\x6e\x6f",
+ "\x35\x81\x86\x99\x90\x01\xe6\xb5"
+ "\xda\xf0\x5e\xce\xeb\x7e\xee\x21"
+ "\xe0\x68\x9c\x1f\x00\xee\xa8\x1f"
+ "\x7d\xd2\xca\xae\xe1\xd2\x76\x3e"
+ "\x68\xaf\x0e\xad\x33\xd6\x6c\x26"
+ "\x8b\xc9\x46\xc4\x84\xfb\xe9\x4c"
+ "\x5f\x5e\x0b\x86\xa5\x92\x79\xe4"
+ "\xf8\x24\xe7\xa6\x40\xbd\x22\x32"
+ "\x10\xb0\xa6\x11\x60\xb7\xbc\xe9"
+ "\x86\xea\x65\x68\x80\x03\x59\x6b"
+ "\x63\x0a\x6b\x90\xf8\xe0\xca\xf6"
+ "\x91\x2a\x98\xeb\x87\x21\x76\xe8"
+ "\x3c\x20\x2c\xaa\x64\x16\x6d\x2c"
+ "\xce\x57\xff\x1b\xca\x57\xb2\x13"
+ "\xf0\xed\x1a\xa7\x2f\xb8\xea\x52"
+ "\xb0\xbe\x01\xcd\x1e\x41\x28\x67"
+ "\x72\x0b\x32\x6e\xb3\x89\xd0\x11"
+ "\xbd\x70\xd8\xaf\x03\x5f\xb0\xd8"
+ "\x58\x9d\xbc\xe3\xc6\x66\xf5\xea"
+ "\x8d\x4c\x79\x54\xc5\x0c\x3f\x34"
+ "\x0b\x04\x67\xf8\x1b\x42\x59\x61"
+ "\xc1\x18\x43\x07\x4d\xf6\x20\xf2"
+ "\x08\x40\x4b\x39\x4c\xf9\xd3\x7f"
+ "\xf5\x4b\x5f\x1a\xd8\xf6\xea\x7d"
+ "\xa3\xc5\x61\xdf\xa7\x28\x1f\x96"
+ "\x44\x63\xd2\xcc\x35\xa4\xd1\xb0"
+ "\x34\x90\xde\xc5\x1b\x07\x11\xfb"
+ "\xd6\xf5\x5f\x79\x23\x4d\x5b\x7c"
+ "\x76\x66\x22\xa6\x6d\xe9\x2b\xe9"
+ "\x96\x46\x1d\x5e\x4d\xc8\x78\xef"
+ "\x9b\xca\x03\x05\x21\xe8\x35\x1e"
+ "\x4b\xae\xd2\xfd\x04\xf9\x46\x73"
+ "\x68\xc4\xad\x6a\xc1\x86\xd0\x82"
+ "\x45\xb2\x63\xa2\x66\x6d\x1f\x6c"
+ "\x54\x20\xf1\x59\x9d\xfd\x9f\x43"
+ "\x89\x21\xc2\xf5\xa4\x63\x93\x8c"
+ "\xe0\x98\x22\x65\xee\xf7\x01\x79"
+ "\xbc\x55\x3f\x33\x9e\xb1\xa4\xc1"
+ "\xaf\x5f\x6a\x54\x7f",
+ NULL
+ }
+};
+
+
+static int
+test_cipher(int i, const EVP_CIPHER *c, struct tests *t)
+{
+ EVP_CIPHER_CTX ectx;
+ EVP_CIPHER_CTX dctx;
+ void *d;
+
+ if (c == NULL) {
+ printf("%s not supported\n", t->name);
+ return 0;
+ }
+
+ EVP_CIPHER_CTX_init(&ectx);
+ EVP_CIPHER_CTX_init(&dctx);
+
+ if (EVP_CipherInit_ex(&ectx, c, NULL, NULL, NULL, 1) != 1)
+ errx(1, "%s: %d EVP_CipherInit_ex einit", t->name, i);
+ if (EVP_CipherInit_ex(&dctx, c, NULL, NULL, NULL, 0) != 1)
+ errx(1, "%s: %d EVP_CipherInit_ex dinit", t->name, i);
+
+ EVP_CIPHER_CTX_set_key_length(&ectx, t->keysize);
+ EVP_CIPHER_CTX_set_key_length(&dctx, t->keysize);
+
+ if (EVP_CipherInit_ex(&ectx, NULL, NULL, t->key, t->iv, 1) != 1)
+ errx(1, "%s: %d EVP_CipherInit_ex encrypt", t->name, i);
+ if (EVP_CipherInit_ex(&dctx, NULL, NULL, t->key, t->iv, 0) != 1)
+ errx(1, "%s: %d EVP_CipherInit_ex decrypt", t->name, i);
+
+ d = emalloc(t->datasize);
+
+ if (!EVP_Cipher(&ectx, d, t->indata, t->datasize))
+ errx(1, "%s: %d EVP_Cipher encrypt failed", t->name, i);
+
+ if (memcmp(d, t->outdata, t->datasize) != 0) {
+ char *s, *s2;
+ hex_encode(d, t->datasize, &s);
+ hex_encode(t->outdata, t->datasize, &s2);
+ errx(1, "%s: %d encrypt not the same: %s != %s", t->name, i, s, s2);
+ }
+
+ if (!EVP_Cipher(&dctx, d, d, t->datasize))
+ errx(1, "%s: %d EVP_Cipher decrypt failed", t->name, i);
+
+ if (memcmp(d, t->indata, t->datasize) != 0) {
+ char *s;
+ hex_encode(d, t->datasize, &s);
+ errx(1, "%s: %d decrypt not the same: %s", t->name, i, s);
+ }
+
+#if 0 /* TODO */
+ if (t->outiv)
+ /* XXXX check */;
+#endif
+
+ EVP_CIPHER_CTX_cleanup(&ectx);
+ EVP_CIPHER_CTX_cleanup(&dctx);
+ free(d);
+
+ return 0;
+}
+
+static int version_flag;
+static int help_flag;
+
+static struct getargs args[] = {
+ { "version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ { "help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ int ret = 0;
+ int i, idx = 0;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &idx))
+ usage(1);
+
+ if (help_flag)
+ usage(0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= idx;
+ argv += idx;
+
+ /* hcrypto */
+ for (i = 0; i < sizeof(aes_tests)/sizeof(aes_tests[0]); i++)
+ ret += test_cipher(i, EVP_hcrypto_aes_256_cbc(), &aes_tests[i]);
+ for (i = 0; i < sizeof(aes_cfb_tests)/sizeof(aes_cfb_tests[0]); i++)
+ ret += test_cipher(i, EVP_hcrypto_aes_128_cfb8(), &aes_cfb_tests[i]);
+ for (i = 0; i < sizeof(rc2_tests)/sizeof(rc2_tests[0]); i++)
+ ret += test_cipher(i, EVP_hcrypto_rc2_cbc(), &rc2_tests[i]);
+ for (i = 0; i < sizeof(rc2_40_tests)/sizeof(rc2_40_tests[0]); i++)
+ ret += test_cipher(i, EVP_hcrypto_rc2_40_cbc(), &rc2_40_tests[i]);
+ for (i = 0; i < sizeof(des_ede3_tests)/sizeof(des_ede3_tests[0]); i++)
+ ret += test_cipher(i, EVP_hcrypto_des_ede3_cbc(), &des_ede3_tests[i]);
+ for (i = 0; i < sizeof(camellia128_tests)/sizeof(camellia128_tests[0]); i++)
+ ret += test_cipher(i, EVP_hcrypto_camellia_128_cbc(),
+ &camellia128_tests[i]);
+ for (i = 0; i < sizeof(rc4_tests)/sizeof(rc4_tests[0]); i++)
+ ret += test_cipher(i, EVP_hcrypto_rc4(), &rc4_tests[i]);
+
+ /* Common Crypto */
+#ifdef __APPLE__
+ for (i = 0; i < sizeof(aes_tests)/sizeof(aes_tests[0]); i++)
+ ret += test_cipher(i, EVP_cc_aes_256_cbc(), &aes_tests[i]);
+ for (i = 0; i < sizeof(aes_cfb_tests)/sizeof(aes_cfb_tests[0]); i++)
+ ret += test_cipher(i, EVP_cc_aes_128_cfb8(), &aes_cfb_tests[i]);
+ for (i = 0; i < sizeof(rc2_40_tests)/sizeof(rc2_40_tests[0]); i++)
+ ret += test_cipher(i, EVP_cc_rc2_40_cbc(), &rc2_40_tests[i]);
+ for (i = 0; i < sizeof(des_ede3_tests)/sizeof(des_ede3_tests[0]); i++)
+ ret += test_cipher(i, EVP_cc_des_ede3_cbc(), &des_ede3_tests[i]);
+ for (i = 0; i < sizeof(camellia128_tests)/sizeof(camellia128_tests[0]); i++)
+ ret += test_cipher(i, EVP_cc_camellia_128_cbc(),
+ &camellia128_tests[i]);
+ for (i = 0; i < sizeof(rc4_tests)/sizeof(rc4_tests[0]); i++)
+ ret += test_cipher(i, EVP_cc_rc4(), &rc4_tests[i]);
+#endif /* __APPLE__ */
+
+ /* Windows CNG (if available) */
+#ifdef WIN32
+ for (i = 0; i < sizeof(aes_tests)/sizeof(aes_tests[0]); i++)
+ ret += test_cipher(i, EVP_w32crypto_aes_256_cbc(), &aes_tests[i]);
+ for (i = 0; i < sizeof(aes_cfb_tests)/sizeof(aes_cfb_tests[0]); i++)
+ ret += test_cipher(i, EVP_w32crypto_aes_128_cfb8(), &aes_cfb_tests[i]);
+ for (i = 0; i < sizeof(rc2_tests)/sizeof(rc2_tests[0]); i++)
+ ret += test_cipher(i, EVP_w32crypto_rc2_cbc(), &rc2_tests[i]);
+ for (i = 0; i < sizeof(rc2_40_tests)/sizeof(rc2_40_tests[0]); i++)
+ ret += test_cipher(i, EVP_w32crypto_rc2_40_cbc(), &rc2_40_tests[i]);
+ for (i = 0; i < sizeof(des_ede3_tests)/sizeof(des_ede3_tests[0]); i++)
+ ret += test_cipher(i, EVP_w32crypto_des_ede3_cbc(), &des_ede3_tests[i]);
+ for (i = 0; i < sizeof(rc4_tests)/sizeof(rc4_tests[0]); i++)
+ ret += test_cipher(i, EVP_w32crypto_rc4(), &rc4_tests[i]);
+#endif /* WIN32 */
+
+ /* PKCS#11 */
+#if __sun || defined(PKCS11_MODULE_PATH)
+ for (i = 0; i < sizeof(aes_tests)/sizeof(aes_tests[0]); i++)
+ ret += test_cipher(i, EVP_pkcs11_aes_256_cbc(), &aes_tests[i]);
+ for (i = 0; i < sizeof(aes_cfb_tests)/sizeof(aes_cfb_tests[0]); i++)
+ ret += test_cipher(i, EVP_pkcs11_aes_128_cfb8(), &aes_cfb_tests[i]);
+ for (i = 0; i < sizeof(rc2_tests)/sizeof(rc2_tests[0]); i++)
+ ret += test_cipher(i, EVP_pkcs11_rc2_cbc(), &rc2_tests[i]);
+ for (i = 0; i < sizeof(rc2_40_tests)/sizeof(rc2_40_tests[0]); i++)
+ ret += test_cipher(i, EVP_pkcs11_rc2_40_cbc(), &rc2_40_tests[i]);
+ for (i = 0; i < sizeof(des_ede3_tests)/sizeof(des_ede3_tests[0]); i++)
+ ret += test_cipher(i, EVP_pkcs11_des_ede3_cbc(), &des_ede3_tests[i]);
+ for (i = 0; i < sizeof(rc4_tests)/sizeof(rc4_tests[0]); i++)
+ ret += test_cipher(i, EVP_pkcs11_rc4(), &rc4_tests[i]);
+#endif /* PKCS11_MODULE_PATH */
+
+ /* OpenSSL */
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+ for (i = 0; i < sizeof(aes_tests)/sizeof(aes_tests[0]); i++)
+ ret += test_cipher(i, EVP_ossl_aes_256_cbc(), &aes_tests[i]);
+ for (i = 0; i < sizeof(aes_cfb_tests)/sizeof(aes_cfb_tests[0]); i++)
+ ret += test_cipher(i, EVP_ossl_aes_128_cfb8(), &aes_cfb_tests[i]);
+ for (i = 0; i < sizeof(rc2_tests)/sizeof(rc2_tests[0]); i++)
+ ret += test_cipher(i, EVP_ossl_rc2_cbc(), &rc2_tests[i]);
+ for (i = 0; i < sizeof(rc2_40_tests)/sizeof(rc2_40_tests[0]); i++)
+ ret += test_cipher(i, EVP_ossl_rc2_40_cbc(), &rc2_40_tests[i]);
+ for (i = 0; i < sizeof(des_ede3_tests)/sizeof(des_ede3_tests[0]); i++)
+ ret += test_cipher(i, EVP_ossl_des_ede3_cbc(), &des_ede3_tests[i]);
+ for (i = 0; i < sizeof(rc4_tests)/sizeof(rc4_tests[0]); i++)
+ ret += test_cipher(i, EVP_ossl_rc4(), &rc4_tests[i]);
+#endif /* PKCS11_MODULE_PATH */
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/hcrypto/test_crypto.in b/third_party/heimdal/lib/hcrypto/test_crypto.in
new file mode 100644
index 0000000..d5b3893
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/test_crypto.in
@@ -0,0 +1,120 @@
+#!/bin/sh
+#
+# Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# $Id$
+#
+
+srcdir="@srcdir@"
+
+rsa="${TESTS_ENVIRONMENT} ./test_rsa@exeext@"
+engine="${TESTS_ENVIRONMENT} ./test_engine_dso@exeext@"
+rand="${TESTS_ENVIRONMENT} ./test_rand@exeext@"
+
+${engine} --test-random > /dev/null || { echo "missing random"; exit 77; }
+
+${rsa} --key=${srcdir}/rsakey.der || \
+ { echo "rsa test failed" ; exit 1; }
+
+${rsa} --time-key=${srcdir}/rsakey.der || \
+ { echo "rsa test failed" ; exit 1; }
+
+${rsa} --time-key=${srcdir}/rsakey2048.der || \
+ { echo "rsa test failed" ; exit 1; }
+
+${rsa} --time-key=generate || \
+ { echo "rsa test failed" ; exit 1; }
+
+${engine} --rsa=${srcdir}/rsakey.der || \
+ { echo "engine test failed" ; exit 1; }
+
+${rsa} --loops=4 || { echo "rsa test for 4 loops failed" ; exit 1; }
+
+for a in unix fortuna egd w32crypto ;do
+ ${rand} --method=${a} --file=crypto-test 2>error
+ res=$?
+ if test "X$res" != X0 ; then
+ grep "unknown method" error && \
+ { echo "random $a is not available" ; continue; }
+ grep "random not ready yet" error || \
+ { echo "random $a ready failing" ; cat error; exit 1; }
+ echo "random method $a out for lunch"
+ continue
+ fi
+ ${rand} --method=${a} --file=crypto-test2 2>error
+ res=$?
+ if test "X$res" != X0 ; then
+ grep "random not ready yet" error || \
+ { echo "random $a ready failing" ; cat error; exit 1; }
+ echo "random metod $a out for dinner"
+ continue
+ fi
+ cmp crypto-test crypto-test2 >/dev/null 2>/dev/null && \
+ { echo "rand output same!" ; exit 1; }
+done
+
+./example_evp_cipher 1 ${srcdir}/test_crypto.in test-out-1 || \
+ { echo "1 failed" ; exit 1; }
+
+for a in 7 15 16 17 31 32 33 ; do
+ ./example_evp_cipher $a ${srcdir}/test_crypto.in test-out-$a
+ cmp test-out-1 test-out-$a || { echo "cmp $a failed" ; exit 1; }
+done
+
+#
+# Last time we run is w/o HOME and RANDFILE to make sure we can do
+# RAND_file_name() when the environment is lacking those.
+#
+
+if [ -r /dev/random -o -r /dev/urandom -o -r /dev/srandom -o -r /dev/arandom ] ; then
+
+ # try hard to unset HOME and RANDFILE
+ HOME=
+ RANDFILE=
+
+ unset HOME
+ unset RANDFILE
+
+ ${rand} --method=unix --file=unix 2>error
+ res=$?
+ if test "X$res" != X0 ; then
+ grep "unknown method" error && \
+ { echo "random unix is not available"; exit 0; }
+ grep "random not ready yet" error || \
+ { echo "random unix ready failing" ; cat error; exit 1; }
+ echo "random method unix out for lunch"
+ continue
+ fi
+
+fi
+
+exit 0
diff --git a/third_party/heimdal/lib/hcrypto/test_dh.c b/third_party/heimdal/lib/hcrypto/test_dh.c
new file mode 100644
index 0000000..f49db67
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/test_dh.c
@@ -0,0 +1,472 @@
+/*
+* Copyright (c) 2007, Novell, Inc.
+* Author: Matthias Koenig <mkoenig@suse.de>
+*
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are met:
+*
+* * Redistributions of source code must retain the above copyright notice, this
+* list of conditions and the following disclaimer.
+*
+* * Redistributions in binary form must reproduce the above copyright notice,
+* this list of conditions and the following disclaimer in the documentation
+* and/or other materials provided with the distribution.
+*
+* * Neither the name of the Novell nor the names of its contributors may be used
+* to endorse or promote products derived from this software without specific
+* prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+* POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/* openssl diffie-hellman test code
+ * works with openssl-0.9.8e
+ * primes with 3072 and 6144 bits as specified in RFC3526
+ * fail since openssl-0.9.8f
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <ctype.h>
+#include <getarg.h>
+
+#include <dh.h>
+#include <evp.h>
+
+/*
+ *
+ */
+
+static char *id_string;
+static int verbose;
+static int version_flag;
+static int help_flag;
+
+static struct getargs args[] = {
+ { "id", 0, arg_string, &id_string,
+ "type of ENGINE", NULL },
+ { "verbose", 0, arg_flag, &verbose,
+ "verbose output from tests", NULL },
+ { "version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ { "help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+/*
+ *
+ */
+
+#define OAKLEY_PRIME_MODP768 \
+ "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" \
+ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" \
+ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" \
+ "E485B576 625E7EC6 F44C42E9 A63A3620 FFFFFFFF FFFFFFFF"
+
+#define OAKLEY_PRIME_MODP1024 \
+ "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" \
+ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" \
+ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" \
+ "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" \
+ "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381" \
+ "FFFFFFFF FFFFFFFF"
+
+#define OAKLEY_PRIME_MODP1536 \
+ "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" \
+ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" \
+ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" \
+ "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" \
+ "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" \
+ "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" \
+ "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" \
+ "670C354E 4ABC9804 F1746C08 CA237327 FFFFFFFF FFFFFFFF"
+
+/* RFC 3526 */
+#define OAKLEY_PRIME_MODP2048 \
+ "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" \
+ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" \
+ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" \
+ "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" \
+ "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" \
+ "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" \
+ "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" \
+ "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" \
+ "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" \
+ "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" \
+ "15728E5A 8AACAA68 FFFFFFFF FFFFFFFF"
+
+#define OAKLEY_PRIME_MODP3072 \
+ "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" \
+ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" \
+ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" \
+ "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" \
+ "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" \
+ "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" \
+ "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" \
+ "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" \
+ "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" \
+ "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" \
+ "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64" \
+ "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7" \
+ "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B" \
+ "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C" \
+ "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31" \
+ "43DB5BFC E0FD108E 4B82D120 A93AD2CA FFFFFFFF FFFFFFFF"
+
+#define OAKLEY_PRIME_MODP4096 \
+ "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" \
+ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" \
+ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" \
+ "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" \
+ "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" \
+ "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" \
+ "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" \
+ "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" \
+ "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" \
+ "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" \
+ "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64" \
+ "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7" \
+ "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B" \
+ "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C" \
+ "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31" \
+ "43DB5BFC E0FD108E 4B82D120 A9210801 1A723C12 A787E6D7" \
+ "88719A10 BDBA5B26 99C32718 6AF4E23C 1A946834 B6150BDA" \
+ "2583E9CA 2AD44CE8 DBBBC2DB 04DE8EF9 2E8EFC14 1FBECAA6" \
+ "287C5947 4E6BC05D 99B2964F A090C3A2 233BA186 515BE7ED" \
+ "1F612970 CEE2D7AF B81BDD76 2170481C D0069127 D5B05AA9" \
+ "93B4EA98 8D8FDDC1 86FFB7DC 90A6C08F 4DF435C9 34063199" \
+ "FFFFFFFF FFFFFFFF"
+
+#define OAKLEY_PRIME_MODP6144 \
+ "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" \
+ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" \
+ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" \
+ "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" \
+ "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" \
+ "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" \
+ "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" \
+ "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" \
+ "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" \
+ "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" \
+ "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64" \
+ "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7" \
+ "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B" \
+ "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C" \
+ "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31" \
+ "43DB5BFC E0FD108E 4B82D120 A9210801 1A723C12 A787E6D7" \
+ "88719A10 BDBA5B26 99C32718 6AF4E23C 1A946834 B6150BDA" \
+ "2583E9CA 2AD44CE8 DBBBC2DB 04DE8EF9 2E8EFC14 1FBECAA6" \
+ "287C5947 4E6BC05D 99B2964F A090C3A2 233BA186 515BE7ED" \
+ "1F612970 CEE2D7AF B81BDD76 2170481C D0069127 D5B05AA9" \
+ "93B4EA98 8D8FDDC1 86FFB7DC 90A6C08F 4DF435C9 34028492" \
+ "36C3FAB4 D27C7026 C1D4DCB2 602646DE C9751E76 3DBA37BD" \
+ "F8FF9406 AD9E530E E5DB382F 413001AE B06A53ED 9027D831" \
+ "179727B0 865A8918 DA3EDBEB CF9B14ED 44CE6CBA CED4BB1B" \
+ "DB7F1447 E6CC254B 33205151 2BD7AF42 6FB8F401 378CD2BF" \
+ "5983CA01 C64B92EC F032EA15 D1721D03 F482D7CE 6E74FEF6" \
+ "D55E702F 46980C82 B5A84031 900B1C9E 59E7C97F BEC7E8F3" \
+ "23A97A7E 36CC88BE 0F1D45B7 FF585AC5 4BD407B2 2B4154AA" \
+ "CC8F6D7E BF48E1D8 14CC5ED2 0F8037E0 A79715EE F29BE328" \
+ "06A1D58B B7C5DA76 F550AA3D 8A1FBFF0 EB19CCB1 A313D55C" \
+ "DA56C9EC 2EF29632 387FE8D7 6E3C0468 043E8F66 3F4860EE" \
+ "12BF2D5B 0B7474D6 E694F91E 6DCC4024 FFFFFFFF FFFFFFFF"
+
+#define OAKLEY_PRIME_MODP8192 \
+ "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" \
+ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" \
+ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" \
+ "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" \
+ "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" \
+ "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" \
+ "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" \
+ "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" \
+ "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" \
+ "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" \
+ "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64" \
+ "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7" \
+ "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B" \
+ "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C" \
+ "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31" \
+ "43DB5BFC E0FD108E 4B82D120 A9210801 1A723C12 A787E6D7" \
+ "88719A10 BDBA5B26 99C32718 6AF4E23C 1A946834 B6150BDA" \
+ "2583E9CA 2AD44CE8 DBBBC2DB 04DE8EF9 2E8EFC14 1FBECAA6" \
+ "287C5947 4E6BC05D 99B2964F A090C3A2 233BA186 515BE7ED" \
+ "1F612970 CEE2D7AF B81BDD76 2170481C D0069127 D5B05AA9" \
+ "93B4EA98 8D8FDDC1 86FFB7DC 90A6C08F 4DF435C9 34028492" \
+ "36C3FAB4 D27C7026 C1D4DCB2 602646DE C9751E76 3DBA37BD" \
+ "F8FF9406 AD9E530E E5DB382F 413001AE B06A53ED 9027D831" \
+ "179727B0 865A8918 DA3EDBEB CF9B14ED 44CE6CBA CED4BB1B" \
+ "DB7F1447 E6CC254B 33205151 2BD7AF42 6FB8F401 378CD2BF" \
+ "5983CA01 C64B92EC F032EA15 D1721D03 F482D7CE 6E74FEF6" \
+ "D55E702F 46980C82 B5A84031 900B1C9E 59E7C97F BEC7E8F3" \
+ "23A97A7E 36CC88BE 0F1D45B7 FF585AC5 4BD407B2 2B4154AA" \
+ "CC8F6D7E BF48E1D8 14CC5ED2 0F8037E0 A79715EE F29BE328" \
+ "06A1D58B B7C5DA76 F550AA3D 8A1FBFF0 EB19CCB1 A313D55C" \
+ "DA56C9EC 2EF29632 387FE8D7 6E3C0468 043E8F66 3F4860EE" \
+ "12BF2D5B 0B7474D6 E694F91E 6DBE1159 74A3926F 12FEE5E4" \
+ "38777CB6 A932DF8C D8BEC4D0 73B931BA 3BC832B6 8D9DD300" \
+ "741FA7BF 8AFC47ED 2576F693 6BA42466 3AAB639C 5AE4F568" \
+ "3423B474 2BF1C978 238F16CB E39D652D E3FDB8BE FC848AD9" \
+ "22222E04 A4037C07 13EB57A8 1A23F0C7 3473FC64 6CEA306B" \
+ "4BCBC886 2F8385DD FA9D4B7F A2C087E8 79683303 ED5BDD3A" \
+ "062B3CF5 B3A278A6 6D2A13F8 3F44F82D DF310EE0 74AB6A36" \
+ "4597E899 A0255DC1 64F31CC5 0846851D F9AB4819 5DED7EA1" \
+ "B1D510BD 7EE74D73 FAF36BC3 1ECFA268 359046F4 EB879F92" \
+ "4009438B 481C6CD7 889A002E D5EE382B C9190DA6 FC026E47" \
+ "9558E447 5677E9AA 9E3050E2 765694DF C81F56E8 80B96E71" \
+ "60C980DD 98EDD3DF FFFFFFFF FFFFFFFF"
+
+struct prime {
+ char *name;
+ char *value;
+} primes[] = {
+ { "modp768", OAKLEY_PRIME_MODP768 },
+ { "modp1024", OAKLEY_PRIME_MODP1024 },
+ { "modp1536", OAKLEY_PRIME_MODP1536 },
+ { "modp2048", OAKLEY_PRIME_MODP2048 },
+ { "modp3072", OAKLEY_PRIME_MODP3072 },
+ { "modp4096", OAKLEY_PRIME_MODP4096 },
+ { "modp6144", OAKLEY_PRIME_MODP6144 },
+ { "modp8192", OAKLEY_PRIME_MODP8192 },
+ { NULL, NULL }
+};
+
+/*
+ * exchange a string based "base" to a value.
+ *
+ */
+static char *
+str2val(const char *str, int base, size_t *len)
+{
+ int f;
+ size_t i;
+ char *dst;
+ char *rp;
+ const char *p;
+ char b[3];
+
+ i = 0;
+ for (p = str; *p != '\0'; p++) {
+ if (isxdigit((int)*p))
+ i++;
+ else if (isspace((int)*p))
+ ;
+ else
+ return NULL;
+ }
+ if (i == 0 || (i % 2) != 0)
+ return NULL;
+ i /= 2;
+
+ if ((dst = malloc(i)) == NULL)
+ return NULL;
+
+ i = 0;
+ f = 0;
+ for (rp = dst, p = str; *p != '\0'; p++) {
+ if (isxdigit((int)*p)) {
+ if (!f) {
+ b[0] = *p;
+ f = 1;
+ } else {
+ b[1] = *p;
+ b[2] = '\0';
+ *rp++ = (char)strtol(b, NULL, base);
+ i++;
+ f = 0;
+ }
+ }
+ }
+
+ *len = i;
+
+ return(dst);
+}
+
+static void set_prime(BIGNUM *p, char *str)
+{
+ size_t len = 0;
+ unsigned char *prime;
+
+ prime = (unsigned char *)str2val(str, 16, &len);
+ if (prime == NULL)
+ errx(1, "failed to parse %s", str);
+ BN_bin2bn(prime, len, p);
+}
+
+static void set_generator(BIGNUM *g)
+{
+ BN_set_word(g, 2);
+}
+
+static void print_secret(unsigned char *sec, size_t len)
+{
+ size_t i;
+
+ for (i = 0; i < len; ++i)
+ printf("%x", sec[i]);
+
+ printf("\n");
+}
+
+static int check_prime(ENGINE *engine, struct prime *pr)
+{
+ DH *dh1, *dh2;
+ BIGNUM *p, *g;
+ unsigned char *sec1, *sec2;
+ size_t size;
+ int ret;
+
+ if (verbose)
+ printf("Testing %s\n", pr->name);
+
+ p = BN_new();
+ g = BN_new();
+ dh1 = DH_new_method(engine);
+ dh2 = DH_new_method(engine);
+
+ /* 1. set shared parameter */
+ set_prime(p, pr->value);
+ set_generator(g);
+ dh1->p = BN_dup(p);
+ dh1->g = BN_dup(g);
+ dh2->p = BN_dup(p);
+ dh2->g = BN_dup(g);
+
+ /* 2. set keys */
+ ret = DH_generate_key(dh1);
+ if (ret == 0) {
+ fprintf(stderr, "DH_generate_key\n");
+ exit(EXIT_FAILURE);
+ }
+ ret = DH_generate_key(dh2);
+ if (ret == 0) {
+ fprintf(stderr, "DH_generate_key\n");
+ exit(EXIT_FAILURE);
+ }
+
+ /* 3. compute shared secret */
+ size = DH_size(dh1);
+ if (size != DH_size(dh2)) {
+ fprintf(stderr, "size does not match!\n");
+ exit(EXIT_FAILURE);
+ }
+ sec1 = malloc(size);
+ sec2 = malloc(size);
+ if (!sec1 || !sec2) {
+ perror("malloc");
+ exit(EXIT_FAILURE);
+ }
+ ret = DH_compute_key(sec1, dh2->pub_key, dh1);
+ if (ret == -1) {
+ fprintf(stderr, "DH_compute_key");
+ exit(EXIT_FAILURE);
+ }
+ ret = DH_compute_key(sec2, dh1->pub_key, dh2);
+ if (ret == -1) {
+ fprintf(stderr, "DH_compute_key");
+ exit(EXIT_FAILURE);
+ }
+
+ /* 4. compare shared secret */
+ if (verbose) {
+ printf("shared secret 1\n");
+ print_secret(sec1, size);
+ printf("shared secret 2\n");
+ print_secret(sec2, size);
+ }
+
+ if (memcmp(sec1, sec2, size) == 0)
+ ret = 1;
+ else
+ ret = 0;
+
+ free(sec2);
+ free(sec1);
+ DH_free(dh2);
+ DH_free(dh1);
+ BN_free(g);
+ BN_free(p);
+
+ return ret;
+}
+
+/*
+ *
+ */
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ ENGINE *engine = NULL;
+ int idx = 0;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &idx))
+ usage(1);
+
+ if (help_flag)
+ usage(0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= idx;
+ argv += idx;
+
+ OpenSSL_add_all_algorithms();
+#ifdef OPENSSL
+ ENGINE_load_openssl();
+#endif
+ ENGINE_load_builtin_engines();
+
+ if (id_string) {
+ engine = ENGINE_by_id(id_string);
+ if (engine == NULL)
+ engine = ENGINE_by_dso(id_string, id_string);
+ } else {
+ engine = ENGINE_by_id("builtin");
+ }
+ if (engine == NULL)
+ errx(1, "ENGINE_by_dso failed");
+
+ printf("dh %s\n", ENGINE_get_DH(engine)->name);
+
+ {
+ struct prime *p = primes;
+
+ for (; p->name; ++p)
+ if (check_prime(engine, p))
+ printf("%s: shared secret OK\n", p->name);
+ else
+ printf("%s: shared secret FAILURE\n", p->name);
+ }
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hcrypto/test_engine_dso.c b/third_party/heimdal/lib/hcrypto/test_engine_dso.c
new file mode 100644
index 0000000..00a672e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/test_engine_dso.c
@@ -0,0 +1,329 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+#include <getarg.h>
+
+#include <engine.h>
+#include <evp.h>
+
+struct {
+ const char *cpriv;
+ const char *cpub;
+ const char *spriv;
+ const char *spub;
+} dhtests[] = {
+ {
+ "5C0946275D07223AEAF04301D964498F3285946057B4C50D13B4FE12C88DFD8D499DD3CC00C1BC17C0D343F2FE053C9F53389110551715B1EDF261A0314485C4835D01F7B8894027D534A2D81D63619D2F58C9864AC9816086B3FF75C01B3FAFF355425AB7369A6ABDC8B633F0A0DC4D29B50F364E7594B297183D14E5CDC05D",
+ "2D66DC5998B7AEE3332DC1061C6E6F6CF0FCCD74534187E2CDC9ACBCADF0FC9D5900451F44832A762F01E9CEEF1CBD7D69D020AC524D09FAD087DFADEAC36C845157B83937B51C8DB7F500C3C54FB2A05E074E40BA982186E7FEB2534EDDB387D5480AAA355B398CCAD0886F3952C3718490B7884FA67BD8B6943CDDA20134C6",
+ "42644BA7CF74689E18BA72BF80FCA674D1A2ADF81795EB3828E67C30E42ABD07A8E90E27F046189FAC122D915276870B72427388EAAB5D06994FC38885BBACCEA1CFC45951B730D73C1A8F83208CD1351746601648C11D70BC95B817C86E4A5C40D633654615041C7934BB3CAF4E02754D542033DB024E94C7E561A29ED0C6EC",
+ "C233633AB116E2DB20B4E08DA42DE8766293E6D9042F7A2C2A2F34F18FE66010B074CCF3C9B03EF27B14F0746B738AF22776224161D767D96AEC230A1DFA6DECFFCE9FED23B96F50CCB0093E59817AD0CEAEB7993AB5764679948BFB1293C9560B07AA3DFA229E341EB17C9FAE0B1D483082461D2DDBCEEE6FE7C0A34D96F66D"
+ },
+ {
+ "76295C1280B890970F0F7EB01BBD9C5DF9BB8F590EB384A39EBF85CD141451407F955FD1D39012AA1F8BA53FD6A5A37CB2835CEDB27D1EBF1FE8AC9F2FFD628BD9BF7B8DD77CB80C8DC0A75F4567C7700442B26972833EB9738A8728A1FC274C59CED5E3ADA224B46711112AAA1CB831D2D6125E183ADA4F805A05024C9C6DDB",
+ "1E0AB5EBAAC7985FE67A574447FAE58AE4CB95416278D4C239A789D4532FA8E6F82BA10BE411D8A0A06B9E1DECE704466B3523496A8A4165B97FBCFB9CE9C4FF2DEEE786BA046E8C270FA8A9055D2F6E42EDDB32C73CF7875551A56EB69C0F14A3745745845B81C347401B27D074C60C5177BA9C14BBB1C8C219B78E15126EF8",
+ "68D84A8F92082F113542CFD990DEEFAD9C7EFA545268F8B3EBDF4CCBAF2865CF03EF60044EB4AF4154E6804CC2BDD673B801507446CEFC692DA577B6DC6E0272B7B081A1BEFDC2A4FAC83DB8845E3DA0D1B64DB33AA2164FEDB08A01E815336BD58F4E6DE6A265468E61C8C988B8AEC0D52DB714448DDC007E7C3382C07357DB",
+ "393815D507A2EF80DE2D0F2A55AAB1C25B870ACA3FC97438B4336CBF979BF9A4F8DA1B61C667129F9123045E07E24976040EC5E2368DD4EF70690102D74E900B260D3826256FD473733A7569BF514652AB78C48C334FDCA26C44ABF322643AF15BFF693A37BB2C19CA9FE5F1537FCFE2B24CF74D4E57060D35ABF115B4B6CD21"
+ },
+ {
+ "7307D6C3CB874327A95F7A6A91C336CEAA086736525DF3F8EC49497CF444C68D264EB70CD6904FE56E240EEF34E6C5177911C478A7F250A0F54183BCBE64B42BAB5D019E73E2F17C095C211E4815E6BA5FDD72786AF987ABBC9109ECEEF439AF9E2141D5222CE7DC0152D8E9A6CCCE301D21A7D1D6ACB9B91B5E28379C91890D",
+ "83FBD7BFFDF415BBB7E21D399CB2F36A61AFDBAFC542E428E444C66AA03617C0C55C639FE2428905B57035892AE1BD2C4060E807D9E003B0C204FFC8FDD69CC8ADE7A8E18DCBFFF64E3EF9DA2C117390374241466E48A020A1B2F575AE42C233F8BD357B8331CC203E0345DFC19C73E6F1F70B6C2786E681D73BF48B15FE9992",
+ "61BCF748BB05A48861578B8CB1855200B2E62A40E126BD7323E5B714645A54A2C8761EE39EE39BA6D2FE19B688168EDEA6DC5056400B5315ED299E7926176B887012E58634D78F05D7BCF0E1B81B1B41F5F8EF0B0711D3A64F9A317DD183AE039A4D3BE02A515892362F8C7BB6EB6434BB25418A438ED33D50C475122CBBE862",
+ "7DB8D69D1605D9812B7F2F3E92BCEEB3426FEEE3265A174D71B2B6E16B332B43DF0B3C2FA152E48DE2FAC110D8CECE122C3398558E7987B27CACE12722C0032AC7E7766A9BCC881BA35B9DB9E751BD4E51F7683DE092F6C1D4DD937CDCE9C16E6F7D77CC6AAD806E4082E8E22E28592C4D78256354393FE831E811E03ED0A81A"
+ },
+ {
+ "60C18B62F786DE6A4A8B13EB6DA2380B4C6731F861C715D9496DCF4A9F01CD33DDB52F1AB4D1F820FAF7AD4EFEB66586F7F08135714B13D77FE652B9EEAB2C543596A9ED307C1629CF535DD14AB22F081AE4ADF7A3E0BC7B33E0EC7A7306F9A737F55807974B5E1B7B6394BD0373917128B43A17757B34BAE1B600763E957F75",
+ "0DEDA337C38EA005D5B8567EAB681CE91892C2C62C9D42BF748FBFE681E11F25D98280E42E1539A10EEE9177EF2F40216987936AF19D9B5EBE22EEAC27242D77CE3A5061F2E5CFACF15CD0F80E736AE8642252FE91E129DE3C78CFB85A0B1BB87B059CBB24483444F8A07244F4E89370BA78D58BD409DFBB3D41921B8879B9C7",
+ "462C0707CF3366C2242A808CFDB79B77E8B3AF9D796583EB9CCD7BF4E8792AB0A818E49FFE53CA241F56988F825B366BF1E78481F8086A123259B9D83AC643E85845BF6B2C5412FFDDFAA8C9ED203CA4B3C1BFD777286099976472FA15B3CCC8418CF162F03C0C3E85D7EFC5CF5ACB9B2C039CCF3A1A9C6BB6B9C09C18D86CBD",
+ "56DB382EDB8C2D95934D20261CE1A37090B0802D451E647DB1DA3B73CDB5A878EAD598A8817302449370F9D45E34F5C45F73D02BF4EB2B3712A8665F446F5D2B774039E5444AB74807859FA58DF9EBA4B12BA4545ACED827E4ED64CC71F937D64A1033BC43403F2490C1B715A74822B8D50A72A102213F0CF7A1B98B771B34C4"
+ },
+ {
+ "61B7321207F4A73646E43E99221F902D2F38095E84CE7346A1510FE71BA7B9B34DCB6609E4DDDA8C82426E82D1C23F1E761130ECE4638D77554A7618E1608625049328FCC1F8845CA9A88E847106B01BD31EF6500E3C7EE81A048924BEAA3EDF367E5F4575341206C7A76427571898294B07BD918D4C2642854CC89D439042E5",
+ "29AA38E63E4DD7C651E25DEC7A5A53E48114F52813793D36A9DBDD4F7C06FC38406E330764E0B2AFD811C39D857EA5F904105360E06856DC0780C7D61C53165833F0AEA15CB54732DE113F44C8FCFB86F4A876DD42D7A55356D91C0173F2B012680FB54C13EF54B65DF4AEDE2E13419B1316435187CEF07D44DB3DF57C4703FD",
+ "5ED5AFB04CBFEE43EF3D9B60A57080831563648A2380D98F1EA4A96CF153903A40A2E564DED87E7254DF3270568AB952BF6F400681DD6AD919C9B06AC0F45F0646BCF37B217191AA0B7B7BED226B61F48B46DEA2E5A09E41F316583823A38A60FFD79085F43F60D98871ECA1A0F667701425094E88885A81DE9DA6C293E95060",
+ "4DE4F24EAA3E2790FBCB1B13C2ED0EFD846EC33154DBEBBEFD895E1399B3617D55EC2CE8D71CF380B55D93636FEF741328D6B1E224D46F8A8B60A41D08DD86E88DE806AA781791364E6D88BF68571BF5D8C35CB04BA302227B7E4CB6A67AB7510ACBCDBF2F8A95EB5DEE693CCA5CC425A0F1CA2D18C369A767906A2477E32704"
+ }
+};
+
+static void
+dh_test(DH *server, DH *client)
+{
+ void *skey, *ckey;
+ int ssize, csize;
+
+ skey = emalloc(DH_size(server));
+ ckey = emalloc(DH_size(client));
+
+ ssize = DH_compute_key(skey, client->pub_key, server);
+ if (ssize == -1)
+ errx(1, "DH_compute_key failed for server");
+ csize = DH_compute_key(ckey, server->pub_key, client);
+ if (csize == -1)
+ errx(1, "DH_compute_key failed for client");
+
+ if (ssize != csize)
+ errx(1, "DH_compute_key size mismatch");
+
+ if (memcmp(skey, ckey, csize) != 0)
+ errx(1, "DH_compute_key key mismatch");
+
+ free(skey);
+ free(ckey);
+}
+
+
+static int version_flag;
+static int help_flag;
+static char *id_flag;
+static char *rsa_flag;
+static int dh_flag = 1;
+static int test_random_flag;
+
+static struct getargs args[] = {
+ { "id", 0, arg_string, &id_flag,
+ "selects the engine id", "engine-id" },
+ { "rsa", 0, arg_string, &rsa_flag,
+ "tests RSA modes", "private-rsa-der-file" },
+ { "dh", 0, arg_negative_flag, &dh_flag,
+ "test dh", NULL },
+ { "test-random", 0, arg_flag, &test_random_flag,
+ "test if there is a random device", NULL },
+ { "version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ { "help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "filename.so");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ ENGINE *engine = NULL;
+ int idx = 0;
+ int have_rsa, have_dh;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &idx))
+ usage(1);
+
+ if (help_flag)
+ usage(0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= idx;
+ argv += idx;
+
+ OpenSSL_add_all_algorithms();
+
+ if (argc == 0) {
+ OpenSSL_add_all_algorithms();
+ ENGINE_load_builtin_engines();
+ engine = ENGINE_by_id("builtin");
+ } else {
+ engine = ENGINE_by_dso(argv[0], id_flag);
+ }
+ if (engine == NULL)
+ errx(1, "ENGINE_by_dso failed");
+
+ printf("name: %s\n", ENGINE_get_name(engine));
+ printf("id: %s\n", ENGINE_get_id(engine));
+ have_rsa = ENGINE_get_RSA(engine) != NULL;
+ have_dh = ENGINE_get_DH(engine) != NULL;
+ printf("RSA: %s", have_rsa ? "yes," : "no");
+ if (have_rsa)
+ printf(" %s", ENGINE_get_RSA(engine)->name);
+ printf("\n");
+ printf("DH: %s", have_dh ? "yes," : "no");
+ if (have_dh)
+ printf(" %s", ENGINE_get_DH(engine)->name);
+ printf("\n");
+
+ if (RAND_status() != 1)
+ errx(77, "no functional random device, can't execute tests");
+ if (test_random_flag)
+ exit(0);
+
+ if (rsa_flag && have_rsa) {
+ unsigned char buf[1024 * 4];
+ const unsigned char *p;
+ size_t size;
+ int keylen;
+ RSA *rsa;
+ FILE *f;
+
+ f = fopen(rsa_flag, "rb");
+ if (f == NULL)
+ err(1, "could not open file %s", rsa_flag);
+
+ size = fread(buf, 1, sizeof(buf), f);
+ if (size == 0)
+ err(1, "failed to read file %s", rsa_flag);
+ if (size == sizeof(buf))
+ err(1, "key too long in file %s!", rsa_flag);
+ fclose(f);
+
+ p = buf;
+ rsa = d2i_RSAPrivateKey(NULL, &p, size);
+ if (rsa == NULL)
+ err(1, "failed to parse key in file %s", rsa_flag);
+
+ RSA_set_method(rsa, ENGINE_get_RSA(engine));
+
+ /*
+ * try rsa signing
+ */
+
+ memcpy(buf, "hejsan", 7);
+ keylen = RSA_private_encrypt(7, buf, buf, rsa, RSA_PKCS1_PADDING);
+ if (keylen <= 0)
+ errx(1, "failed to private encrypt");
+
+ keylen = RSA_public_decrypt(keylen, buf, buf, rsa, RSA_PKCS1_PADDING);
+ if (keylen <= 0)
+ errx(1, "failed to public decrypt");
+
+ if (keylen != 7)
+ errx(1, "output buffer not same length: %d", (int)keylen);
+
+ if (memcmp(buf, "hejsan", 7) != 0)
+ errx(1, "string not the same after decryption");
+
+ /*
+ * try rsa encryption
+ */
+
+ memcpy(buf, "hejsan", 7);
+ keylen = RSA_public_encrypt(7, buf, buf, rsa, RSA_PKCS1_PADDING);
+ if (keylen <= 0)
+ errx(1, "failed to public encrypt");
+
+ keylen = RSA_private_decrypt(keylen, buf, buf, rsa, RSA_PKCS1_PADDING);
+ if (keylen <= 0)
+ errx(1, "failed to private decrypt");
+
+ if (keylen != 7)
+ errx(1, "output buffer not same length: %d", (int)keylen);
+
+ if (memcmp(buf, "hejsan", 7) != 0)
+ errx(1, "string not the same after decryption");
+
+ RSA_free(rsa);
+
+ printf("rsa test passed\n");
+
+ }
+
+ if (dh_flag) {
+ DH *server, *client;
+ int i;
+
+ /* RFC2412-MODP-group2 */
+ const char *p =
+ "FFFFFFFF" "FFFFFFFF" "C90FDAA2" "2168C234" "C4C6628B" "80DC1CD1"
+ "29024E08" "8A67CC74" "020BBEA6" "3B139B22" "514A0879" "8E3404DD"
+ "EF9519B3" "CD3A431B" "302B0A6D" "F25F1437" "4FE1356D" "6D51C245"
+ "E485B576" "625E7EC6" "F44C42E9" "A637ED6B" "0BFF5CB6" "F406B7ED"
+ "EE386BFB" "5A899FA5" "AE9F2411" "7C4B1FE6" "49286651" "ECE65381"
+ "FFFFFFFF" "FFFFFFFF";
+ const char *g = "02";
+
+ /*
+ * Try generated keys
+ */
+
+ for (i = 0; i < 10; i++) {
+ server = DH_new_method(engine);
+ client = DH_new_method(engine);
+
+ BN_hex2bn(&server->p, p);
+ BN_hex2bn(&client->p, p);
+ BN_hex2bn(&server->g, g);
+ BN_hex2bn(&client->g, g);
+
+ if (!DH_generate_key(server))
+ errx(1, "DH_generate_key failed for server");
+ if (!DH_generate_key(client))
+ errx(1, "DH_generate_key failed for client");
+
+ dh_test(server, client);
+
+ DH_free(server);
+ DH_free(client);
+ }
+ /*
+ * Try known result
+ */
+
+ for (i = 0; i < sizeof(dhtests)/sizeof(dhtests[0]); i++) {
+
+ server = DH_new_method(engine);
+ client = DH_new_method(engine);
+
+ BN_hex2bn(&server->p, p);
+ BN_hex2bn(&client->p, p);
+ BN_hex2bn(&server->g, g);
+ BN_hex2bn(&client->g, g);
+
+ BN_hex2bn(&client->priv_key, dhtests[i].cpriv);
+ BN_hex2bn(&client->pub_key, dhtests[i].cpub);
+ BN_hex2bn(&server->priv_key, dhtests[i].spriv);
+ BN_hex2bn(&server->pub_key, dhtests[i].spub);
+
+ dh_test(server, client);
+
+ DH_free(server);
+ DH_free(client);
+ }
+
+ printf("DH test passed\n");
+ }
+
+ ENGINE_finish(engine);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hcrypto/test_hmac.c b/third_party/heimdal/lib/hcrypto/test_hmac.c
new file mode 100644
index 0000000..36a5626
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/test_hmac.c
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <hmac.h>
+#include <evp.h>
+
+int
+main(int argc, char **argv)
+{
+ unsigned char buf[4] = { 0, 0, 0, 0 };
+ char hmackey[] = "hello-world";
+ size_t hmackey_size = sizeof(hmackey);
+ unsigned int hmaclen;
+ unsigned char hmac[EVP_MAX_MD_SIZE];
+ HMAC_CTX c;
+
+ char answer[20] = "\x2c\xfa\x32\xb7\x2b\x8a\xf6\xdf\xcf\xda"
+ "\x6f\xd1\x52\x4d\x54\x58\x73\x0f\xf3\x24";
+
+ HMAC_CTX_init(&c);
+ if (HMAC_Init_ex(&c, hmackey, hmackey_size, EVP_sha1(), NULL) == 0) {
+ HMAC_CTX_cleanup(&c);
+ printf("out of memory\n");
+ return 1;
+ }
+ HMAC_Update(&c, buf, sizeof(buf));
+ HMAC_Final(&c, hmac, &hmaclen);
+ HMAC_CTX_cleanup(&c);
+
+ if (hmaclen != 20) {
+ printf("hmaclen = %d\n", (int)hmaclen);
+ return 1;
+ }
+
+ if (ct_memcmp(hmac, answer, hmaclen) != 0) {
+ printf("wrong answer\n");
+ return 1;
+ }
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hcrypto/test_pkcs12.c b/third_party/heimdal/lib/hcrypto/test_pkcs12.c
new file mode 100644
index 0000000..3c7f5da
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/test_pkcs12.c
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <pkcs12.h>
+#include <evp.h>
+
+struct tests {
+ int id;
+ const char *password;
+ void *salt;
+ size_t saltsize;
+ int iterations;
+ size_t keylen;
+ const EVP_MD * (*md)(void);
+ void *key;
+};
+
+struct tests p12_pbe_tests[] = {
+ { PKCS12_KEY_ID,
+ NULL,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ 100,
+ 16,
+ EVP_sha1,
+ "\xd7\x2d\xd4\xcf\x7e\xe1\x89\xc5\xb5\xe5\x31\xa7\x63\x2c\xf0\x4b"
+ },
+ { PKCS12_KEY_ID,
+ "",
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ 100,
+ 16,
+ EVP_sha1,
+ "\x00\x54\x91\xaf\xc0\x6a\x76\xc3\xf9\xb6\xf2\x28\x1a\x15\xd9\xfe"
+ },
+ { PKCS12_KEY_ID,
+ "foobar",
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ 100,
+ 16,
+ EVP_sha1,
+ "\x79\x95\xbf\x3f\x1c\x6d\xe\xe8\xd3\x71\xc4\x94\xd\xb\x18\xb5"
+ },
+ { PKCS12_KEY_ID,
+ "foobar",
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ 2048,
+ 24,
+ EVP_sha1,
+ "\x0b\xb5\xe\xa6\x71\x0d\x0c\xf7\x44\xe\xe1\x9b\xb5\xdf\xf1\xdc\x4f\xb0\xca\xe\xee\x4f\xb9\xfd"
+ },
+ { PKCS12_IV_ID,
+ "foobar",
+ "\x3c\xdf\x84\x32\x59\xd3\xda\x69",
+ 8,
+ 2048,
+ 8,
+ EVP_sha1,
+ "\xbf\x9a\x12\xb7\x26\x69\xfd\x05"
+ }
+
+};
+
+static int
+test_pkcs12_pbe(struct tests *t)
+{
+ void *key;
+ size_t pwlen = 0;
+
+ key = malloc(t->keylen);
+ if (t->password)
+ pwlen = strlen(t->password);
+
+ if (!PKCS12_key_gen(t->password, pwlen,
+ t->salt, t->saltsize,
+ t->id, t->iterations, t->keylen,
+ key, t->md()))
+ {
+ printf("key_gen failed\n");
+ return 1;
+ }
+
+ if (memcmp(t->key, key, t->keylen) != 0) {
+ printf("incorrect key\n");
+ free(key);
+ return 1;
+ }
+ free(key);
+ return 0;
+}
+
+int
+main(int argc, char **argv)
+{
+ int ret = 0;
+ int i;
+
+ for (i = 0; i < sizeof(p12_pbe_tests)/sizeof(p12_pbe_tests[0]); i++)
+ ret += test_pkcs12_pbe(&p12_pbe_tests[i]);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/hcrypto/test_pkcs5.c b/third_party/heimdal/lib/hcrypto/test_pkcs5.c
new file mode 100644
index 0000000..3641a6e
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/test_pkcs5.c
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+#include <err.h>
+
+#include <evp.h>
+
+struct tests {
+ const char *password;
+ const char *salt;
+ int iterations;
+ const void *pbkdf2_128;
+ const void *pbkdf2_256;
+};
+
+
+const struct tests pkcs5_tests[] = {
+ { "password",
+ "ATHENA.MIT.EDUraeburn",
+ 1,
+ "\xcd\xed\xb5\x28\x1b\xb2\xf8\x01\x56\x5a\x11\x22\xb2\x56\x35\x15",
+ "\xcd\xed\xb5\x28\x1b\xb2\xf8\x01\x56\x5a\x11\x22\xb2\x56\x35\x15"
+ "\x0a\xd1\xf7\xa0\x4b\xb9\xf3\xa3\x33\xec\xc0\xe2\xe1\xf7\x08\x37"
+ },
+ { "password",
+ "ATHENA.MIT.EDUraeburn",
+ 2,
+ "\x01\xdb\xee\x7f\x4a\x9e\x24\x3e\x98\x8b\x62\xc7\x3c\xda\x93\x5d",
+ "\x01\xdb\xee\x7f\x4a\x9e\x24\x3e\x98\x8b\x62\xc7\x3c\xda\x93\x5d"
+ "\xa0\x53\x78\xb9\x32\x44\xec\x8f\x48\xa9\x9e\x61\xad\x79\x9d\x86"
+ },
+ { "password",
+ "ATHENA.MIT.EDUraeburn",
+ 1200,
+ "\x5c\x08\xeb\x61\xfd\xf7\x1e\x4e\x4e\xc3\xcf\x6b\xa1\xf5\x51\x2b",
+ "\x5c\x08\xeb\x61\xfd\xf7\x1e\x4e\x4e\xc3\xcf\x6b\xa1\xf5\x51\x2b"
+ "\xa7\xe5\x2d\xdb\xc5\xe5\x14\x2f\x70\x8a\x31\xe2\xe6\x2b\x1e\x13"
+ },
+ {
+ "password", "\x12\x34\x56\x78\x78\x56\x34\x12",
+ 5,
+ "\xd1\xda\xa7\x86\x15\xf2\x87\xe6\xa1\xc8\xb1\x20\xd7\x06\x2a\x49",
+ "\xd1\xda\xa7\x86\x15\xf2\x87\xe6\xa1\xc8\xb1\x20\xd7\x06\x2a\x49"
+ "\x3f\x98\xd2\x03\xe6\xbe\x49\xa6\xad\xf4\xfa\x57\x4b\x6e\x64\xee"
+ },
+ {
+ "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
+ "pass phrase equals block size",
+ 1200,
+ "\x13\x9c\x30\xc0\x96\x6b\xc3\x2b\xa5\x5f\xdb\xf2\x12\x53\x0a\xc9",
+ "\x13\x9c\x30\xc0\x96\x6b\xc3\x2b\xa5\x5f\xdb\xf2\x12\x53\x0a\xc9"
+ "\xc5\xec\x59\xf1\xa4\x52\xf5\xcc\x9a\xd9\x40\xfe\xa0\x59\x8e\xd1"
+ },
+ {
+ "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
+ "pass phrase exceeds block size",
+ 1200,
+ "\x9c\xca\xd6\xd4\x68\x77\x0c\xd5\x1b\x10\xe6\xa6\x87\x21\xbe\x61",
+ "\x9c\xca\xd6\xd4\x68\x77\x0c\xd5\x1b\x10\xe6\xa6\x87\x21\xbe\x61"
+ "\x1a\x8b\x4d\x28\x26\x01\xdb\x3b\x36\xbe\x92\x46\x91\x5e\xc8\x2a"
+ },
+ {
+ "\xf0\x9d\x84\x9e" /* g-clef */,
+ "EXAMPLE.COMpianist",
+ 50,
+ "\x6b\x9c\xf2\x6d\x45\x45\x5a\x43\xa5\xb8\xbb\x27\x6a\x40\x3b\x39",
+ "\x6b\x9c\xf2\x6d\x45\x45\x5a\x43\xa5\xb8\xbb\x27\x6a\x40\x3b\x39"
+ "\xe7\xfe\x37\xa0\xc4\x1e\x02\xc2\x81\xff\x30\x69\xe1\xe9\x4f\x52"
+ }
+};
+
+static int
+test_pkcs5_pbe2(const struct tests *t)
+{
+ unsigned char key[32];
+ int ret, error = 0;
+
+ ret = PKCS5_PBKDF2_HMAC(t->password, strlen(t->password),
+ t->salt, strlen(t->salt),
+ t->iterations, EVP_sha1(),
+ 16, key);
+ if (ret != 1)
+ errx(1, "PKCS5_PBKDF2_HMAC: %d", ret);
+
+ if (memcmp(t->pbkdf2_128, key, 16) != 0) {
+ printf("incorrect 128 key\n");
+ error++;
+ }
+
+ ret = PKCS5_PBKDF2_HMAC(t->password, strlen(t->password),
+ t->salt, strlen(t->salt),
+ t->iterations, EVP_sha1(),
+ 32, key);
+ if (ret != 1)
+ errx(1, "PKCS5_PBKDF2_HMAC: %d", ret);
+
+ if (memcmp(t->pbkdf2_256, key, 32) != 0) {
+ printf("incorrect 256 key\n");
+ error++;
+ }
+
+ return error;
+}
+
+int
+main(int argc, char **argv)
+{
+ int ret = 0;
+ int i;
+
+ for (i = 0; i < sizeof(pkcs5_tests)/sizeof(pkcs5_tests[0]); i++)
+ ret += test_pkcs5_pbe2(&pkcs5_tests[i]);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/hcrypto/test_rand.c b/third_party/heimdal/lib/hcrypto/test_rand.c
new file mode 100644
index 0000000..b3ee2b1
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/test_rand.c
@@ -0,0 +1,219 @@
+/*
+ * Copyright (c) 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+#include <math.h>
+
+#include <getarg.h>
+
+#include "rand.h"
+
+
+/*
+ *
+ */
+
+static int version_flag;
+static int help_flag;
+static int len = 1024 * 1024;
+static char *rand_method;
+static char *filename;
+
+static struct getargs args[] = {
+ { "length", 0, arg_integer, &len,
+ "length", NULL },
+ { "file", 0, arg_string, &filename,
+ "file name", NULL },
+ { "method", 0, arg_string, &rand_method,
+ "method", NULL },
+ { "version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ { "help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+/*
+ *
+ */
+
+/*
+ *
+ */
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(args[0]),
+ NULL,
+ "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ int idx = 0;
+ char *buffer;
+ char path[MAXPATHLEN];
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &idx))
+ usage(1);
+
+ if (help_flag)
+ usage(0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ if (argc != idx)
+ usage(1);
+
+ buffer = emalloc(len);
+
+ if (rand_method) {
+ if (0) {
+ }
+#ifndef NO_RAND_FORTUNA_METHOD
+ else if (strcasecmp(rand_method, "fortuna") == 0)
+ RAND_set_rand_method(RAND_fortuna_method());
+#endif
+#ifndef NO_RAND_UNIX_METHOD
+ else if (strcasecmp(rand_method, "unix") == 0)
+ RAND_set_rand_method(RAND_unix_method());
+#endif
+#ifdef WIN32
+ else if (strcasecmp(rand_method, "w32crypto") == 0)
+ RAND_set_rand_method(RAND_w32crypto_method());
+#endif
+ else
+ errx(1, "unknown method %s", rand_method);
+ }
+
+ if (RAND_file_name(path, sizeof(path)) == NULL)
+ errx(1, "RAND_file_name failed");
+
+ if (RAND_status() != 1)
+ errx(1, "random not ready yet");
+
+ if (RAND_bytes(buffer, len) != 1)
+ errx(1, "RAND_bytes");
+
+ if (filename)
+ rk_dumpdata(filename, buffer, len);
+
+ /* head vs tail */
+ if (len >= 100000) {
+ unsigned bytes[256];
+ unsigned bits[8];
+ size_t bit, i;
+ double res;
+ double slen = sqrt((double)len);
+
+ memset(bits, 0, sizeof(bits));
+ memset(bytes, 0, sizeof(bytes));
+
+ for (i = 0; i < len; i++) {
+ unsigned char c = ((unsigned char *)buffer)[i];
+
+ bytes[c]++;
+
+ for (bit = 0; bit < 8 && c; bit++) {
+ if (c & 1)
+ bits[bit]++;
+ c = c >> 1;
+ }
+ }
+
+ /*
+ * The count for each bit value has a mean of n*p = len/2,
+ * and a standard deviation of sqrt(n*p*q) ~ sqrt(len/4).
+ * Normalizing by dividing by "n*p", we get a mean of 1 and
+ * a standard deviation of sqrt(q/n*p) = 1/sqrt(len).
+ *
+ * A 5.33-sigma event happens 1 time in 10 million.
+ * A 5.73-sigma event happens 1 time in 100 million.
+ * A 6.11-sigma event happens 1 time in 1000 million.
+ *
+ * We tolerate 5.33-sigma events (we have 8 not entirely
+ * independent chances of skewed results) and want to fail
+ * with a good RNG less often than 1 time in million.
+ */
+ for (bit = 0; bit < 8; bit++) {
+ res = slen * fabs(1.0 - 2 * (double)bits[bit] / len);
+ if (res > 5.33)
+ errx(1, "head%d vs tail%d: %.1f-sigma (%d of %d)",
+ (int)bit, (int)bit, res, bits[bit], len);
+ printf("head vs tails bit%d: %f-sigma\n", (int)bit, res);
+ }
+
+ /*
+ * The count of each byte value has a mean of n*p = len/256,
+ * and a standard deviation of sqrt(n*p*q) ~ sqrt(len/256).
+ * Normalizing by dividing by "n*p", we get a mean of 1 and
+ * a standard deviation of sqrt(q/n*p) ~ 16/sqrt(len).
+ *
+ * We tolerate 5.73-sigma events (we have 256 not entirely
+ * independent chances of skewed results). Note, for example,
+ * a 5.2-sigma event was observed in ~5,000 runs.
+ */
+ for (i = 0; i < 256; i++) {
+ res = (slen / 16) * fabs(1.0 - 256 * (double)bytes[i] / len);
+ if (res > 5.73)
+ errx(1, "byte %d: %.1f-sigma (%d of %d)",
+ (int) i, res, bytes[i], len);
+ printf("byte %d: %f-sigma\n", (int)i, res);
+ }
+ }
+
+ free(buffer);
+
+ /* test write random file */
+ {
+ static const char *file = "test.file";
+ if (RAND_write_file(file) != 1)
+ errx(1, "RAND_write_file");
+ if (RAND_load_file(file, 1024) != 1)
+ errx(1, "RAND_load_file");
+ unlink(file);
+ }
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hcrypto/test_rsa.c b/third_party/heimdal/lib/hcrypto/test_rsa.c
new file mode 100644
index 0000000..c9766b8
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/test_rsa.c
@@ -0,0 +1,397 @@
+/*
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+#include <getarg.h>
+
+#include <engine.h>
+#include <evp.h>
+
+/*
+ *
+ */
+
+static int version_flag;
+static int help_flag;
+static int time_keygen;
+static char *time_key;
+static int key_blinding = 1;
+static char *rsa_key;
+static char *id_flag;
+static int loops = 1;
+
+static struct getargs args[] = {
+ { "loops", 0, arg_integer, &loops,
+ "number of loops", "loops" },
+ { "id", 0, arg_string, &id_flag,
+ "selects the engine id", "engine-id" },
+ { "time-keygen", 0, arg_flag, &time_keygen,
+ "time rsa generation", NULL },
+ { "time-key", 0, arg_string, &time_key,
+ "rsa key file", NULL },
+ { "key-blinding", 0, arg_negative_flag, &key_blinding,
+ "key blinding", NULL },
+ { "key", 0, arg_string, &rsa_key,
+ "rsa key file", NULL },
+ { "version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ { "help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+/*
+ *
+ */
+
+static void
+check_rsa(const unsigned char *in, size_t len, RSA *rsa, int padding)
+{
+ unsigned char *res, *res2;
+ unsigned int len2;
+ int keylen;
+
+ res = malloc(RSA_size(rsa));
+ if (res == NULL)
+ errx(1, "res: ENOMEM");
+
+ res2 = malloc(RSA_size(rsa));
+ if (res2 == NULL)
+ errx(1, "res2: ENOMEM");
+
+ /* signing */
+
+ keylen = RSA_private_encrypt(len, in, res, rsa, padding);
+ if (keylen <= 0)
+ errx(1, "failed to private encrypt: %d %d", (int)len, (int)keylen);
+
+ if (keylen > RSA_size(rsa))
+ errx(1, "keylen > RSA_size(rsa)");
+
+ keylen = RSA_public_decrypt(keylen, res, res2, rsa, padding);
+ if (keylen <= 0)
+ errx(1, "failed to public decrypt: %d", (int)keylen);
+
+ if (keylen != len)
+ errx(1, "output buffer not same length: %d", (int)keylen);
+
+ if (memcmp(res2, in, len) != 0)
+ errx(1, "string not the same after decryption");
+
+ /* encryption */
+
+ keylen = RSA_public_encrypt(len, in, res, rsa, padding);
+ if (keylen <= 0)
+ errx(1, "failed to public encrypt: %d", (int)keylen);
+
+ if (keylen > RSA_size(rsa))
+ errx(1, "keylen > RSA_size(rsa)");
+
+ keylen = RSA_private_decrypt(keylen, res, res2, rsa, padding);
+ if (keylen <= 0)
+ errx(1, "failed to private decrypt: %d", (int)keylen);
+
+ if (keylen != len)
+ errx(1, "output buffer not same length: %d", (int)keylen);
+
+ if (memcmp(res2, in, len) != 0)
+ errx(1, "string not the same after decryption");
+
+ len2 = keylen;
+
+ if (RSA_sign(NID_sha1, in, len, res, &len2, rsa) != 1)
+ errx(1, "RSA_sign failed");
+
+ if (RSA_verify(NID_sha1, in, len, res, len2, rsa) != 1)
+ errx(1, "RSA_verify failed");
+
+ free(res);
+ free(res2);
+}
+
+static int
+cb_func(int a, int b, BN_GENCB *c)
+{
+ return 1;
+}
+
+static RSA *
+read_key(ENGINE *engine, const char *keyfile)
+{
+ unsigned char buf[1024 * 4];
+ const unsigned char *p;
+ size_t size;
+ RSA *rsa;
+ FILE *f;
+
+ f = fopen(keyfile, "rb");
+ if (f == NULL)
+ err(1, "could not open file %s", keyfile);
+ rk_cloexec_file(f);
+
+ size = fread(buf, 1, sizeof(buf), f);
+ fclose(f);
+ if (size == 0)
+ err(1, "failed to read file %s", keyfile);
+ if (size == sizeof(buf))
+ err(1, "key too long in file %s!", keyfile);
+
+ p = buf;
+ rsa = d2i_RSAPrivateKey(NULL, &p, size);
+ if (rsa == NULL)
+ err(1, "failed to parse key in file %s", keyfile);
+
+ RSA_set_method(rsa, ENGINE_get_RSA(engine));
+
+ if (!key_blinding)
+ rsa->flags |= RSA_FLAG_NO_BLINDING;
+
+ return rsa;
+}
+
+/*
+ *
+ */
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "filename.so");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ ENGINE *engine = NULL;
+ int i, j, idx = 0;
+ RSA *rsa;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &idx))
+ usage(1);
+
+ if (help_flag)
+ usage(0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= idx;
+ argv += idx;
+
+ OpenSSL_add_all_algorithms();
+#ifdef OPENSSL
+ ENGINE_load_openssl();
+#endif
+ ENGINE_load_builtin_engines();
+
+ if (argc == 0) {
+ engine = ENGINE_by_id("builtin");
+ } else {
+ engine = ENGINE_by_id(argv[0]);
+ if (engine == NULL)
+ engine = ENGINE_by_dso(argv[0], id_flag);
+ }
+ if (engine == NULL)
+ errx(1, "ENGINE_by_dso failed");
+
+ if (ENGINE_get_RSA(engine) == NULL)
+ return 77;
+
+ printf("rsa %s\n", ENGINE_get_RSA(engine)->name);
+
+ if (RAND_status() != 1)
+ errx(77, "no functional random device, refusing to run tests");
+
+ if (time_keygen) {
+ struct timeval tv1, tv2;
+ BIGNUM *e;
+
+ rsa = RSA_new_method(engine);
+ if (!key_blinding)
+ rsa->flags |= RSA_FLAG_NO_BLINDING;
+
+ e = BN_new();
+ BN_set_word(e, 0x10001);
+
+ printf("running keygen with %d loops\n", loops);
+
+ gettimeofday(&tv1, NULL);
+
+ for (i = 0; i < loops; i++) {
+ rsa = RSA_new_method(engine);
+ if (RSA_generate_key_ex(rsa, 1024, e, NULL) != 1)
+ errx(1, "RSA_generate_key_ex");
+ RSA_free(rsa);
+ }
+
+ gettimeofday(&tv2, NULL);
+ timevalsub(&tv2, &tv1);
+
+ printf("time %lu.%06lu\n",
+ (unsigned long)tv2.tv_sec,
+ (unsigned long)tv2.tv_usec);
+
+ BN_free(e);
+ ENGINE_finish(engine);
+
+ return 0;
+ }
+
+ if (time_key) {
+ const int size = 20;
+ struct timeval tv1, tv2;
+ unsigned char *p;
+
+ if (strcmp(time_key, "generate") == 0) {
+ BIGNUM *e;
+
+ rsa = RSA_new_method(engine);
+ if (!key_blinding)
+ rsa->flags |= RSA_FLAG_NO_BLINDING;
+
+ e = BN_new();
+ BN_set_word(e, 0x10001);
+
+ if (RSA_generate_key_ex(rsa, 1024, e, NULL) != 1)
+ errx(1, "RSA_generate_key_ex");
+ BN_free(e);
+ } else {
+ rsa = read_key(engine, time_key);
+ }
+
+ p = emalloc(loops * size);
+
+ RAND_bytes(p, loops * size);
+
+ gettimeofday(&tv1, NULL);
+ for (i = 0; i < loops; i++)
+ check_rsa(p + (i * size), size, rsa, RSA_PKCS1_PADDING);
+ gettimeofday(&tv2, NULL);
+
+ timevalsub(&tv2, &tv1);
+
+ printf("time %lu.%06lu\n",
+ (unsigned long)tv2.tv_sec,
+ (unsigned long)tv2.tv_usec);
+
+ RSA_free(rsa);
+ ENGINE_finish(engine);
+
+ free(p);
+ return 0;
+ }
+
+ if (rsa_key) {
+ rsa = read_key(engine, rsa_key);
+
+ /*
+ * Assuming that you use the RSA key in the distribution, this
+ * test will generate a signature have a starting zero and thus
+ * will generate a checksum that is 127 byte instead of the
+ * checksum that is 128 byte (like the key).
+ */
+ {
+ const unsigned char sha1[20] = {
+ 0x6d, 0x33, 0xf9, 0x40, 0x75, 0x5b, 0x4e, 0xc5, 0x90, 0x35,
+ 0x48, 0xab, 0x75, 0x02, 0x09, 0x76, 0x9a, 0xb4, 0x7d, 0x6b
+ };
+
+ check_rsa(sha1, sizeof(sha1), rsa, RSA_PKCS1_PADDING);
+ }
+
+ for (i = 0; i < 128; i++) {
+ unsigned char sha1[20];
+
+ RAND_bytes(sha1, sizeof(sha1));
+ check_rsa(sha1, sizeof(sha1), rsa, RSA_PKCS1_PADDING);
+ }
+ for (i = 0; i < 128; i++) {
+ unsigned char des3[21];
+
+ RAND_bytes(des3, sizeof(des3));
+ check_rsa(des3, sizeof(des3), rsa, RSA_PKCS1_PADDING);
+ }
+ for (i = 0; i < 128; i++) {
+ unsigned char aes[32];
+
+ RAND_bytes(aes, sizeof(aes));
+ check_rsa(aes, sizeof(aes), rsa, RSA_PKCS1_PADDING);
+ }
+
+ RSA_free(rsa);
+ }
+
+ for (i = 0; i < loops; i++) {
+ BN_GENCB cb;
+ BIGNUM *e;
+ unsigned int n;
+
+ rsa = RSA_new_method(engine);
+ if (!key_blinding)
+ rsa->flags |= RSA_FLAG_NO_BLINDING;
+
+ e = BN_new();
+ BN_set_word(e, 0x10001);
+
+ BN_GENCB_set(&cb, cb_func, NULL);
+
+ RAND_bytes(&n, sizeof(n));
+ n &= 0x1ff;
+ n += 1024;
+
+ if (RSA_generate_key_ex(rsa, n, e, &cb) != 1)
+ errx(1, "RSA_generate_key_ex");
+
+ BN_free(e);
+
+ for (j = 0; j < 8; j++) {
+ unsigned char sha1[20];
+ RAND_bytes(sha1, sizeof(sha1));
+ check_rsa(sha1, sizeof(sha1), rsa, RSA_PKCS1_PADDING);
+ }
+
+ RSA_free(rsa);
+ }
+
+ ENGINE_finish(engine);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hcrypto/ui.c b/third_party/heimdal/lib/hcrypto/ui.c
new file mode 100644
index 0000000..0eb09e7
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/ui.c
@@ -0,0 +1,218 @@
+/*
+ * Copyright (c) 1997 - 2000, 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+#include <signal.h>
+#ifdef HAVE_TERMIOS_H
+#include <termios.h>
+#endif
+
+#include <ui.h>
+#ifdef HAVE_CONIO_H
+#include <conio.h>
+#endif
+
+static sig_atomic_t intr_flag;
+
+static void
+intr(int sig)
+{
+ intr_flag++;
+}
+
+#ifdef HAVE_CONIO_H
+
+/*
+ * Windows does console slightly different then then unix case.
+ */
+
+static int
+read_string(const char *preprompt, const char *prompt,
+ char *buf, size_t len, int echo)
+{
+ int of = 0;
+ int c;
+ char *p;
+ void (*oldsigintr)(int);
+
+ _cprintf("%s%s", preprompt, prompt);
+
+ oldsigintr = signal(SIGINT, intr);
+
+ p = buf;
+ while(intr_flag == 0){
+ c = ((echo)? _getche(): _getch());
+ if(c == '\n' || c == '\r')
+ break;
+ if(of == 0)
+ *p++ = c;
+ of = (p == buf + len);
+ }
+ if(of)
+ p--;
+ *p = 0;
+
+ if(echo == 0){
+ printf("\n");
+ }
+
+ signal(SIGINT, oldsigintr);
+
+ if(intr_flag)
+ return -2;
+ if(of)
+ return -1;
+ return 0;
+}
+
+#else /* !HAVE_CONIO_H */
+
+#ifndef NSIG
+#define NSIG 47
+#endif
+
+static int
+read_string(const char *preprompt, const char *prompt,
+ char *buf, size_t len, int echo)
+{
+ struct sigaction sigs[NSIG];
+ int oksigs[NSIG];
+ struct sigaction sa;
+ FILE *tty;
+ int ret = 0;
+ int of = 0;
+ int i;
+ int c;
+ char *p;
+
+ struct termios t_new, t_old;
+
+ memset(&oksigs, 0, sizeof(oksigs));
+
+ memset(&sa, 0, sizeof(sa));
+ sa.sa_handler = intr;
+ sigemptyset(&sa.sa_mask);
+ sa.sa_flags = 0;
+ for(i = 1; i < sizeof(sigs) / sizeof(sigs[0]); i++)
+ if (i != SIGALRM)
+ if (sigaction(i, &sa, &sigs[i]) == 0)
+ oksigs[i] = 1;
+
+ if((tty = fopen("/dev/tty", "r")) != NULL)
+ rk_cloexec_file(tty);
+ else
+ tty = stdin;
+
+ fprintf(stderr, "%s%s", preprompt, prompt);
+ fflush(stderr);
+
+ if(echo == 0){
+ tcgetattr(fileno(tty), &t_old);
+ memcpy(&t_new, &t_old, sizeof(t_new));
+ t_new.c_lflag &= ~ECHO;
+ tcsetattr(fileno(tty), TCSANOW, &t_new);
+ }
+ intr_flag = 0;
+ p = buf;
+ while(intr_flag == 0){
+ c = getc(tty);
+ if(c == EOF){
+ if(!ferror(tty))
+ ret = 1;
+ break;
+ }
+ if(c == '\n')
+ break;
+ if(of == 0)
+ *p++ = c;
+ of = (p == buf + len);
+ }
+ if(of)
+ p--;
+ *p = 0;
+
+ if(echo == 0){
+ fprintf(stderr, "\n");
+ tcsetattr(fileno(tty), TCSANOW, &t_old);
+ }
+
+ if(tty != stdin)
+ fclose(tty);
+
+ for(i = 1; i < sizeof(sigs) / sizeof(sigs[0]); i++)
+ if (oksigs[i])
+ sigaction(i, &sigs[i], NULL);
+
+ if(ret)
+ return -3;
+ if(intr_flag)
+ return -2;
+ if(of)
+ return -1;
+ return 0;
+}
+
+#endif /* HAVE_CONIO_H */
+
+int
+UI_UTIL_read_pw_string(char *buf, int length, const char *prompt, int verify)
+{
+ int ret;
+
+ ret = read_string("", prompt, buf, length, 0);
+ if (ret)
+ return ret;
+
+ if (verify & UI_UTIL_FLAG_VERIFY) {
+ char *buf2;
+ buf2 = malloc(length);
+ if (buf2 == NULL)
+ return 1;
+
+ ret = read_string("Verify password - ", prompt, buf2, length, 0);
+ if (ret) {
+ free(buf2);
+ return ret;
+ }
+ if (strcmp(buf2, buf) != 0) {
+ if (!(verify & UI_UTIL_FLAG_VERIFY_SILENT)) {
+ fprintf(stderr, "Verify failure\n");
+ fflush(stderr);
+ }
+ ret = 1;
+ }
+ free(buf2);
+ }
+ return ret;
+}
diff --git a/third_party/heimdal/lib/hcrypto/ui.h b/third_party/heimdal/lib/hcrypto/ui.h
new file mode 100644
index 0000000..4f56da7
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/ui.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef _HEIM_UI_H
+#define _HEIM_UI_H 1
+
+/* symbol renaming */
+#define UI_UTIL_read_pw_string hc_UI_UTIL_read_pw_string
+
+/* OpenSSL API extensions */
+#define UI_UTIL_FLAG_VERIFY 0x1 /* ask to verify password */
+#define UI_UTIL_FLAG_VERIFY_SILENT 0x2 /* silence on verify failure */
+
+int UI_UTIL_read_pw_string(char *, int, const char *, int); /* XXX */
+
+#endif /* _HEIM_UI_H */
+
diff --git a/third_party/heimdal/lib/hcrypto/undef.h b/third_party/heimdal/lib/hcrypto/undef.h
new file mode 100644
index 0000000..512b8c3
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/undef.h
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) 2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef HEIM_UNDEF_H
+#define HEIM_UNDEF_H 1
+
+#undef BIGNUM
+#undef BN_CTX
+#undef BN_BLINDING
+#undef BN_MONT_CTX
+#undef BN_GENCB
+#undef DH
+#undef DH_METHOD
+#undef DSA
+#undef DSA_METHOD
+#undef RSA
+#undef RSA_METHOD
+#undef RAND_METHOD
+#undef ENGINE
+#undef BN_GENCB_call
+#undef BN_GENCB_set
+#undef BN_CTX_new
+#undef BN_CTX_free
+#undef BN_CTX_start
+#undef BN_CTX_get
+#undef BN_CTX_end
+#undef BN_is_negative
+#undef BN_rand
+#undef BN_num_bits
+#undef BN_num_bytes
+#undef BN_new
+#undef BN_clear_free
+#undef BN_bin2bn
+#undef BN_bn2bin
+#undef BN_uadd
+#undef BN_set_negative
+#undef BN_set_word
+#undef BN_get_word
+#undef BN_cmp
+#undef BN_free
+#undef BN_is_bit_set
+#undef BN_clear
+#undef BN_dup
+#undef BN_set_bit
+#undef BN_clear_bit
+#undef BN_bn2hex
+#undef BN_hex2bn
+#undef EVP_CIPHER_CTX_block_size
+#undef EVP_CIPHER_CTX_cipher
+#undef EVP_CIPHER_CTX_cleanup
+#undef EVP_CIPHER_CTX_flags
+#undef EVP_CIPHER_CTX_get_app_data
+#undef EVP_CIPHER_CTX_init
+#undef EVP_CIPHER_CTX_iv_length
+#undef EVP_CIPHER_CTX_key_length
+#undef EVP_CIPHER_CTX_mode
+#undef EVP_CIPHER_CTX_set_app_data
+#undef EVP_CIPHER_CTX_set_key_length
+#undef EVP_CIPHER_CTX_set_padding
+#undef EVP_CIPHER_block_size
+#undef EVP_CIPHER_iv_length
+#undef EVP_CIPHER_key_length
+#undef EVP_Cipher
+#undef EVP_CipherInit_ex
+#undef EVP_CipherUpdate
+#undef EVP_CipherFinal_ex
+#undef EVP_Digest
+#undef EVP_DigestFinal_ex
+#undef EVP_DigestInit_ex
+#undef EVP_DigestUpdate
+#undef EVP_MD_CTX_block_size
+#undef EVP_MD_CTX_cleanup
+#undef EVP_MD_CTX_create
+#undef EVP_MD_CTX_init
+#undef EVP_MD_CTX_destroy
+#undef EVP_MD_CTX_md
+#undef EVP_MD_CTX_size
+#undef EVP_MD_block_size
+#undef EVP_MD_size
+#undef EVP_aes_128_cbc
+#undef EVP_aes_192_cbc
+#undef EVP_aes_256_cbc
+#undef EVP_aes_128_cfb8
+#undef EVP_aes_192_cfb8
+#undef EVP_aes_256_cfb8
+#undef EVP_des_cbc
+#undef EVP_des_ede3_cbc
+#undef EVP_enc_null
+#undef EVP_md2
+#undef EVP_md4
+#undef EVP_md5
+#undef EVP_md_null
+#undef EVP_rc2_40_cbc
+#undef EVP_rc2_64_cbc
+#undef EVP_rc2_cbc
+#undef EVP_rc4
+#undef EVP_rc4_40
+#undef EVP_camellia_128_cbc
+#undef EVP_camellia_192_cbc
+#undef EVP_camellia_256_cbc
+#undef EVP_sha
+#undef EVP_sha1
+#undef EVP_sha256
+#undef EVP_sha384
+#undef EVP_sha512
+#undef PKCS5_PBKDF2_HMAC
+#undef PKCS5_PBKDF2_HMAC_SHA1
+#undef EVP_BytesToKey
+#undef EVP_get_cipherbyname
+#undef OpenSSL_add_all_algorithms
+#undef OpenSSL_add_all_algorithms_conf
+#undef OpenSSL_add_all_algorithms_noconf
+#undef EVP_CIPHER_CTX_ctrl
+#undef EVP_CIPHER_CTX_rand_key
+#undef hcrypto_validate
+#undef EVP_MD_CTX
+#undef EVP_PKEY
+#undef EVP_MD
+#undef EVP_CIPHER
+#undef EVP_CIPHER_CTX
+#undef EVP_CIPH_STREAM_CIPHER
+#undef EVP_CIPH_CBC_MODE
+#undef EVP_CIPH_CFB8_MODE
+#undef EVP_CIPH_MODE
+#undef EVP_CIPH_CTRL_INIT
+#undef EVP_CTRL_INIT
+#undef EVP_CIPH_VARIABLE_LENGTH
+#undef EVP_CIPH_ALWAYS_CALL_INIT
+#undef EVP_CIPH_RAND_KEY
+#undef EVP_CTRL_RAND_KEY
+#undef NID_md2
+#undef NID_md4
+#undef NID_md5
+#undef NID_sha1
+#undef NID_sha256
+#undef NID_sha384
+#undef NID_sha512
+
+#endif /* HEIM_UNDEF_H */
diff --git a/third_party/heimdal/lib/hcrypto/validate.c b/third_party/heimdal/lib/hcrypto/validate.c
new file mode 100644
index 0000000..4b655f2
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/validate.c
@@ -0,0 +1,307 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#include <evp.h>
+#include <hmac.h>
+#include <err.h>
+
+struct tests {
+ const EVP_CIPHER *(*cipher)(void);
+ const char *name;
+ void *key;
+ size_t keysize;
+ void *iv;
+ size_t datasize;
+ void *indata;
+ void *outdata;
+ void *outiv;
+};
+
+static struct tests hc_tests[] = {
+ {
+ EVP_aes_256_cbc,
+ "aes-256",
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 32,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\xdc\x95\xc0\x78\xa2\x40\x89\x89\xad\x48\xa2\x14\x92\x84\x20\x87",
+ NULL
+ },
+#if 0
+ {
+ EVP_aes_128_cfb8,
+ "aes-cfb8-128",
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\x66\xe9\x4b\xd4\xef\x8a\x2c\x3b\x88\x4c\xfa\x59\xca\x34\x2b\x2e"
+ },
+#endif
+ {
+ EVP_des_ede3_cbc,
+ "des-ede3",
+ "\x19\x17\xff\xe6\xbb\x77\x2e\xfc"
+ "\x29\x76\x43\xbc\x63\x56\x7e\x9a"
+ "\x00\x2e\x4d\x43\x1d\x5f\xfd\x58",
+ 24,
+ "\xbf\x9a\x12\xb7\x26\x69\xfd\x05",
+ 16,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\x55\x95\x97\x76\xa9\x6c\x66\x40\x64\xc7\xf4\x1c\x21\xb7\x14\x1b",
+ NULL
+ },
+#if 0
+ {
+ EVP_camellia_128_cbc,
+ "camellia128",
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ 16,
+ "\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\x07\x92\x3A\x39\xEB\x0A\x81\x7D\x1C\x4D\x87\xBD\xB8\x2D\x1F\x1C",
+ NULL
+ },
+#endif
+ {
+ EVP_rc4,
+ "rc4 8",
+ "\x01\x23\x45\x67\x89\xAB\xCD\xEF",
+ 8,
+ NULL,
+ 8,
+ "\x00\x00\x00\x00\x00\x00\x00\x00",
+ "\x74\x94\xC2\xE7\x10\x4B\x08\x79",
+ NULL
+ },
+ {
+ EVP_rc4,
+ "rc4 5",
+ "\x61\x8a\x63\xd2\xfb",
+ 5,
+ NULL,
+ 5,
+ "\xdc\xee\x4c\xf9\x2c",
+ "\xf1\x38\x29\xc9\xde",
+ NULL
+ },
+ {
+ EVP_rc4,
+ "rc4 309",
+ "\x29\x04\x19\x72\xfb\x42\xba\x5f\xc7\x12\x77\x12\xf1\x38\x29\xc9",
+ 16,
+ NULL,
+ 309,
+ "\x52\x75\x69\x73\x6c\x69\x6e\x6e"
+ "\x75\x6e\x20\x6c\x61\x75\x6c\x75"
+ "\x20\x6b\x6f\x72\x76\x69\x73\x73"
+ "\x73\x61\x6e\x69\x2c\x20\x74\xe4"
+ "\x68\x6b\xe4\x70\xe4\x69\x64\x65"
+ "\x6e\x20\x70\xe4\xe4\x6c\x6c\xe4"
+ "\x20\x74\xe4\x79\x73\x69\x6b\x75"
+ "\x75\x2e\x20\x4b\x65\x73\xe4\x79"
+ "\xf6\x6e\x20\x6f\x6e\x20\x6f\x6e"
+ "\x6e\x69\x20\x6f\x6d\x61\x6e\x61"
+ "\x6e\x69\x2c\x20\x6b\x61\x73\x6b"
+ "\x69\x73\x61\x76\x75\x75\x6e\x20"
+ "\x6c\x61\x61\x6b\x73\x6f\x74\x20"
+ "\x76\x65\x72\x68\x6f\x75\x75\x2e"
+ "\x20\x45\x6e\x20\x6d\x61\x20\x69"
+ "\x6c\x6f\x69\x74\x73\x65\x2c\x20"
+ "\x73\x75\x72\x65\x20\x68\x75\x6f"
+ "\x6b\x61\x61\x2c\x20\x6d\x75\x74"
+ "\x74\x61\x20\x6d\x65\x74\x73\xe4"
+ "\x6e\x20\x74\x75\x6d\x6d\x75\x75"
+ "\x73\x20\x6d\x75\x6c\x6c\x65\x20"
+ "\x74\x75\x6f\x6b\x61\x61\x2e\x20"
+ "\x50\x75\x75\x6e\x74\x6f\x20\x70"
+ "\x69\x6c\x76\x65\x6e\x2c\x20\x6d"
+ "\x69\x20\x68\x75\x6b\x6b\x75\x75"
+ "\x2c\x20\x73\x69\x69\x6e\x74\x6f"
+ "\x20\x76\x61\x72\x61\x6e\x20\x74"
+ "\x75\x75\x6c\x69\x73\x65\x6e\x2c"
+ "\x20\x6d\x69\x20\x6e\x75\x6b\x6b"
+ "\x75\x75\x2e\x20\x54\x75\x6f\x6b"
+ "\x73\x75\x74\x20\x76\x61\x6e\x61"
+ "\x6d\x6f\x6e\x20\x6a\x61\x20\x76"
+ "\x61\x72\x6a\x6f\x74\x20\x76\x65"
+ "\x65\x6e\x2c\x20\x6e\x69\x69\x73"
+ "\x74\xe4\x20\x73\x79\x64\xe4\x6d"
+ "\x65\x6e\x69\x20\x6c\x61\x75\x6c"
+ "\x75\x6e\x20\x74\x65\x65\x6e\x2e"
+ "\x20\x2d\x20\x45\x69\x6e\x6f\x20"
+ "\x4c\x65\x69\x6e\x6f",
+ "\x35\x81\x86\x99\x90\x01\xe6\xb5"
+ "\xda\xf0\x5e\xce\xeb\x7e\xee\x21"
+ "\xe0\x68\x9c\x1f\x00\xee\xa8\x1f"
+ "\x7d\xd2\xca\xae\xe1\xd2\x76\x3e"
+ "\x68\xaf\x0e\xad\x33\xd6\x6c\x26"
+ "\x8b\xc9\x46\xc4\x84\xfb\xe9\x4c"
+ "\x5f\x5e\x0b\x86\xa5\x92\x79\xe4"
+ "\xf8\x24\xe7\xa6\x40\xbd\x22\x32"
+ "\x10\xb0\xa6\x11\x60\xb7\xbc\xe9"
+ "\x86\xea\x65\x68\x80\x03\x59\x6b"
+ "\x63\x0a\x6b\x90\xf8\xe0\xca\xf6"
+ "\x91\x2a\x98\xeb\x87\x21\x76\xe8"
+ "\x3c\x20\x2c\xaa\x64\x16\x6d\x2c"
+ "\xce\x57\xff\x1b\xca\x57\xb2\x13"
+ "\xf0\xed\x1a\xa7\x2f\xb8\xea\x52"
+ "\xb0\xbe\x01\xcd\x1e\x41\x28\x67"
+ "\x72\x0b\x32\x6e\xb3\x89\xd0\x11"
+ "\xbd\x70\xd8\xaf\x03\x5f\xb0\xd8"
+ "\x58\x9d\xbc\xe3\xc6\x66\xf5\xea"
+ "\x8d\x4c\x79\x54\xc5\x0c\x3f\x34"
+ "\x0b\x04\x67\xf8\x1b\x42\x59\x61"
+ "\xc1\x18\x43\x07\x4d\xf6\x20\xf2"
+ "\x08\x40\x4b\x39\x4c\xf9\xd3\x7f"
+ "\xf5\x4b\x5f\x1a\xd8\xf6\xea\x7d"
+ "\xa3\xc5\x61\xdf\xa7\x28\x1f\x96"
+ "\x44\x63\xd2\xcc\x35\xa4\xd1\xb0"
+ "\x34\x90\xde\xc5\x1b\x07\x11\xfb"
+ "\xd6\xf5\x5f\x79\x23\x4d\x5b\x7c"
+ "\x76\x66\x22\xa6\x6d\xe9\x2b\xe9"
+ "\x96\x46\x1d\x5e\x4d\xc8\x78\xef"
+ "\x9b\xca\x03\x05\x21\xe8\x35\x1e"
+ "\x4b\xae\xd2\xfd\x04\xf9\x46\x73"
+ "\x68\xc4\xad\x6a\xc1\x86\xd0\x82"
+ "\x45\xb2\x63\xa2\x66\x6d\x1f\x6c"
+ "\x54\x20\xf1\x59\x9d\xfd\x9f\x43"
+ "\x89\x21\xc2\xf5\xa4\x63\x93\x8c"
+ "\xe0\x98\x22\x65\xee\xf7\x01\x79"
+ "\xbc\x55\x3f\x33\x9e\xb1\xa4\xc1"
+ "\xaf\x5f\x6a\x54\x7f",
+ NULL
+ }
+};
+
+static int
+test_cipher(struct tests *t)
+{
+ const EVP_CIPHER *c = t->cipher();
+ EVP_CIPHER_CTX ectx;
+ EVP_CIPHER_CTX dctx;
+ void *d;
+
+ EVP_CIPHER_CTX_init(&ectx);
+ EVP_CIPHER_CTX_init(&dctx);
+
+ if (EVP_CipherInit_ex(&ectx, c, NULL, NULL, NULL, 1) != 1)
+ errx(1, "%s: EVP_CipherInit_ex einit", t->name);
+ if (EVP_CipherInit_ex(&dctx, c, NULL, NULL, NULL, 0) != 1)
+ errx(1, "%s: EVP_CipherInit_ex dinit", t->name);
+
+ EVP_CIPHER_CTX_set_key_length(&ectx, t->keysize);
+ EVP_CIPHER_CTX_set_key_length(&dctx, t->keysize);
+
+ if (EVP_CipherInit_ex(&ectx, NULL, NULL, t->key, t->iv, 1) != 1)
+ errx(1, "%s: EVP_CipherInit_ex encrypt", t->name);
+ if (EVP_CipherInit_ex(&dctx, NULL, NULL, t->key, t->iv, 0) != 1)
+ errx(1, "%s: EVP_CipherInit_ex decrypt", t->name);
+
+ d = emalloc(t->datasize);
+
+ if (!EVP_Cipher(&ectx, d, t->indata, t->datasize))
+ return 1;
+
+ if (memcmp(d, t->outdata, t->datasize) != 0)
+ errx(1, "%s: encrypt not the same", t->name);
+
+ if (!EVP_Cipher(&dctx, d, d, t->datasize))
+ return 1;
+
+ if (memcmp(d, t->indata, t->datasize) != 0)
+ errx(1, "%s: decrypt not the same", t->name);
+
+#if 0
+ if (t->outiv)
+ /* XXXX check */;
+#endif
+
+ EVP_CIPHER_CTX_cleanup(&ectx);
+ EVP_CIPHER_CTX_cleanup(&dctx);
+ free(d);
+
+ return 0;
+}
+
+static void
+check_hmac(void)
+{
+ unsigned char buf[4] = { 0, 0, 0, 0 };
+ char hmackey[] = "hello-world";
+ size_t hmackey_size = sizeof(hmackey);
+ unsigned int hmaclen;
+ unsigned char hmac[EVP_MAX_MD_SIZE];
+ HMAC_CTX c;
+
+ char answer[20] = "\x2c\xfa\x32\xb7\x2b\x8a\xf6\xdf\xcf\xda"
+ "\x6f\xd1\x52\x4d\x54\x58\x73\x0f\xf3\x24";
+
+ HMAC_CTX_init(&c);
+ if (HMAC_Init_ex(&c, hmackey, hmackey_size, EVP_sha1(), NULL) == 0)
+ errx(1, "HMAC_Init_ex() out of memory");
+ HMAC_Update(&c, buf, sizeof(buf));
+ HMAC_Final(&c, hmac, &hmaclen);
+ HMAC_CTX_cleanup(&c);
+
+ if (hmaclen != 20)
+ errx(1, "hmaclen = %d\n", (int)hmaclen);
+
+ if (ct_memcmp(hmac, answer, hmaclen) != 0)
+ errx(1, "wrong answer\n");
+}
+
+void
+hcrypto_validate(void)
+{
+ static int validated = 0;
+ unsigned int i;
+
+ /* its ok to run this twice, do don't check for races */
+ if (validated)
+ return;
+ validated++;
+
+ for (i = 0; i < sizeof(hc_tests) / sizeof(hc_tests[0]); i++)
+ test_cipher(&hc_tests[i]);
+
+ check_hmac();
+}
diff --git a/third_party/heimdal/lib/hcrypto/version-script.map b/third_party/heimdal/lib/hcrypto/version-script.map
new file mode 100644
index 0000000..fbd8141
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/version-script.map
@@ -0,0 +1,341 @@
+# $Id$
+
+HEIMDAL_CRYPTO_1.0 {
+ global:
+ hc_AES_cbc_encrypt;
+ hc_AES_cfb8_encrypt;
+ hc_AES_decrypt;
+ hc_AES_decrypt_key;
+ hc_BN_CTX_end;
+ hc_BN_CTX_free;
+ hc_BN_CTX_get;
+ hc_BN_CTX_new;
+ hc_BN_CTX_start;
+ hc_AES_encrypt;
+ hc_AES_set_encrypt_key;
+ hc_BN_GENCB_call;
+ hc_BN_GENCB_set;
+ hc_BN_bin2bn;
+ hc_BN_bn2bin;
+ hc_BN_bn2hex;
+ hc_BN_clear;
+ hc_BN_clear_bit;
+ hc_BN_clear_free;
+ hc_BN_cmp;
+ hc_BN_dup;
+ hc_BN_free;
+ hc_BN_get_word;
+ hc_BN_hex2bn;
+ hc_BN_is_bit_set;
+ hc_BN_is_negative;
+ hc_BN_new;
+ hc_BN_num_bits;
+ hc_BN_num_bytes;
+ hc_BN_rand;
+ hc_BN_set_bit;
+ hc_BN_set_negative;
+ hc_BN_set_word;
+ hc_BN_uadd;
+ hc_DES_cbc_cksum;
+ hc_DES_cbc_encrypt;
+ hc_DES_cfb64_encrypt;
+ hc_DES_check_key_parity;
+ hc_DES_ecb3_encrypt;
+ hc_DES_ecb_encrypt;
+ hc_DES_ede3_cbc_encrypt;
+ hc_DES_encrypt;
+ hc_DES_generate_random_block;
+ hc_DES_init_random_number_generator;
+ hc_DES_is_weak_key;
+ hc_DES_key_sched;
+ hc_DES_mem_rand8;
+ hc_DES_new_random_key;
+ hc_DES_pcbc_encrypt;
+ hc_DES_rand_data;
+ hc_DES_rand_data_key;
+ hc_DES_random_key;
+ hc_DES_read_password;
+ hc_DES_set_key;
+ hc_DES_set_key_checked;
+ hc_DES_set_key_unchecked;
+ hc_DES_set_odd_parity;
+ hc_DES_set_random_generator_seed;
+ hc_DES_set_sequence_number;
+ hc_DES_string_to_key;
+ hc_DH_check_pubkey;
+ hc_DH_compute_key;
+ hc_DH_free;
+ hc_DH_generate_key;
+ hc_DH_generate_parameters_ex;
+ hc_DH_get_default_method;
+ hc_DH_get_ex_data;
+ hc_DH_ltm_method;
+ hc_DH_gmp_method;
+ hc_DH_new;
+ hc_DH_new_method;
+ hc_DH_null_method;
+ hc_DH_set_default_method;
+ hc_DH_set_ex_data;
+ hc_DH_set_method;
+ hc_DH_size;
+ hc_DH_up_ref;
+ hc_DSA_free;
+ hc_DSA_get_default_method;
+ hc_DSA_new;
+ hc_DSA_null_method;
+ hc_DSA_set_default_method;
+ hc_DSA_up_ref;
+ hc_DSA_verify;
+ hc_ENGINE_new;
+ hc_ENGINE_free;
+ hc_ENGINE_add_conf_module;
+ hc_ENGINE_by_dso;
+ hc_ENGINE_by_id;
+ hc_ENGINE_finish;
+ hc_ENGINE_get_DH;
+ hc_ENGINE_get_RAND;
+ hc_ENGINE_get_RSA;
+ hc_ENGINE_get_default_DH;
+ hc_ENGINE_get_default_RSA;
+ hc_ENGINE_get_id;
+ hc_ENGINE_get_name;
+ hc_ENGINE_load_builtin_engines;
+ hc_ENGINE_set_DH;
+ hc_ENGINE_set_RSA;
+ hc_ENGINE_set_default_DH;
+ hc_ENGINE_set_default_RSA;
+ hc_ENGINE_set_destroy_function;
+ hc_ENGINE_set_id;
+ hc_ENGINE_set_name;
+ hc_ENGINE_up_ref;
+ hc_EVP_BytesToKey;
+ hc_EVP_CIPHER_CTX_block_size;
+ hc_EVP_CIPHER_CTX_cipher;
+ hc_EVP_CIPHER_CTX_cleanup;
+ hc_EVP_CIPHER_CTX_flags;
+ hc_EVP_CIPHER_CTX_get_app_data;
+ hc_EVP_CIPHER_CTX_init;
+ hc_EVP_CIPHER_CTX_iv_length;
+ hc_EVP_CIPHER_CTX_key_length;
+ hc_EVP_CIPHER_CTX_mode;
+ hc_EVP_CIPHER_CTX_set_app_data;
+ hc_EVP_CIPHER_block_size;
+ hc_EVP_CIPHER_iv_length;
+ hc_EVP_CIPHER_key_length;
+ hc_EVP_Cipher;
+ hc_EVP_CipherInit_ex;
+ hc_EVP_Digest;
+ hc_EVP_DigestFinal_ex;
+ hc_EVP_DigestInit_ex;
+ hc_EVP_DigestUpdate;
+ hc_EVP_MD_CTX_block_size;
+ hc_EVP_MD_CTX_cleanup;
+ hc_EVP_MD_CTX_cleanup;
+ hc_EVP_MD_CTX_create;
+ hc_EVP_MD_CTX_create;
+ hc_EVP_MD_CTX_destroy;
+ hc_EVP_MD_CTX_destroy;
+ hc_EVP_MD_CTX_init;
+ hc_EVP_MD_CTX_init;
+ hc_EVP_MD_CTX_md;
+ hc_EVP_MD_CTX_size;
+ hc_EVP_MD_block_size;
+ hc_EVP_MD_size;
+ hc_EVP_aes_128_cbc;
+ hc_EVP_aes_192_cbc;
+ hc_EVP_aes_256_cbc;
+ hc_EVP_aes_128_cfb8;
+ hc_EVP_aes_192_cfb8;
+ hc_EVP_aes_256_cfb8;
+ hc_EVP_des_cbc;
+ hc_EVP_des_ede3_cbc;
+ hc_EVP_camellia_128_cbc;
+ hc_EVP_camellia_192_cbc;
+ hc_EVP_camellia_256_cbc;
+ hc_EVP_enc_null;
+ hc_EVP_get_cipherbyname;
+ hc_EVP_md2;
+ hc_EVP_md4;
+ hc_EVP_md5;
+ hc_EVP_md_null;
+ hc_EVP_rc2_40_cbc;
+ hc_EVP_rc2_64_cbc;
+ hc_EVP_rc2_cbc;
+ hc_EVP_rc4;
+ hc_EVP_rc4_40;
+ hc_EVP_sha;
+ hc_EVP_sha1;
+ hc_EVP_sha256;
+ hc_EVP_sha384;
+ hc_EVP_sha512;
+
+ hc_EVP_cc_md2;
+ hc_EVP_cc_md4;
+ hc_EVP_cc_md5;
+ hc_EVP_cc_sha1;
+ hc_EVP_cc_sha256;
+ hc_EVP_cc_sha384;
+ hc_EVP_cc_sha512;
+ hc_EVP_cc_des_ede3_cbc;
+ hc_EVP_cc_aes_128_cbc;
+ hc_EVP_cc_aes_192_cbc;
+ hc_EVP_cc_aes_256_cbc;
+ hc_EVP_cc_aes_128_cfb8;
+ hc_EVP_cc_aes_192_cfb8;
+ hc_EVP_cc_aes_256_cfb8;
+
+ hc_EVP_hcrypto_md2;
+ hc_EVP_hcrypto_md4;
+ hc_EVP_hcrypto_md5;
+ hc_EVP_hcrypto_sha1;
+ hc_EVP_hcrypto_sha256;
+ hc_EVP_hcrypto_sha384;
+ hc_EVP_hcrypto_sha512;
+ hc_EVP_hcrypto_des_ede3_cbc;
+ hc_EVP_hcrypto_aes_128_cbc;
+ hc_EVP_hcrypto_aes_192_cbc;
+ hc_EVP_hcrypto_aes_256_cbc;
+ hc_EVP_hcrypto_aes_128_cfb8;
+ hc_EVP_hcrypto_aes_192_cfb8;
+ hc_EVP_hcrypto_aes_256_cfb8;
+ hc_EVP_hcrypto_rc4;
+ hc_EVP_hcrypto_rc4_40;
+
+ hc_EVP_ossl_md2;
+ hc_EVP_ossl_md4;
+ hc_EVP_ossl_md5;
+ hc_EVP_ossl_sha1;
+ hc_EVP_ossl_sha256;
+ hc_EVP_ossl_sha384;
+ hc_EVP_ossl_sha512;
+ hc_EVP_ossl_des_ede3_cbc;
+ hc_EVP_ossl_aes_128_cbc;
+ hc_EVP_ossl_aes_192_cbc;
+ hc_EVP_ossl_aes_256_cbc;
+ hc_EVP_ossl_aes_128_cfb8;
+ hc_EVP_ossl_aes_192_cfb8;
+ hc_EVP_ossl_aes_256_cfb8;
+ hc_EVP_ossl_rc2_cbc;
+ hc_EVP_ossl_rc2_40_cbc;
+ hc_EVP_ossl_rc4;
+ hc_EVP_ossl_rc4_40;
+
+ hc_EVP_pkcs11_md2;
+ hc_EVP_pkcs11_md4;
+ hc_EVP_pkcs11_md5;
+ hc_EVP_pkcs11_sha1;
+ hc_EVP_pkcs11_sha256;
+ hc_EVP_pkcs11_des_ede3_cbc;
+ hc_EVP_pkcs11_aes_128_cbc;
+ hc_EVP_pkcs11_aes_192_cbc;
+ hc_EVP_pkcs11_aes_256_cbc;
+ hc_EVP_pkcs11_aes_128_cfb8;
+ hc_EVP_pkcs11_aes_192_cfb8;
+ hc_EVP_pkcs11_aes_256_cfb8;
+ hc_EVP_pkcs11_rc2_40_cbc;
+ hc_EVP_pkcs11_rc2_64_cbc;
+ hc_EVP_pkcs11_rc2_cbc;
+ hc_EVP_pkcs11_rc4;
+ hc_EVP_pkcs11_rc4_40;
+
+ hc_EVP_hcrypto_aes_128_cts;
+ hc_EVP_hcrypto_aes_192_cts;
+ hc_EVP_hcrypto_aes_256_cts;
+ hc_HMAC;
+ hc_HMAC_CTX_cleanup;
+ hc_HMAC_CTX_free;
+ hc_HMAC_CTX_init;
+ hc_HMAC_CTX_new;
+ hc_HMAC_Final;
+ hc_HMAC_Init_ex;
+ hc_HMAC_Update;
+ hc_HMAC_size;
+ hc_MD2_Final;
+ hc_MD2_Init;
+ hc_MD2_Update;
+ hc_MD4_Final;
+ hc_MD4_Init;
+ hc_MD4_Update;
+ hc_MD5_Final;
+ hc_MD5_Init;
+ hc_MD5_Update;
+ hc_OpenSSL_add_all_algorithms;
+ hc_OpenSSL_add_all_algorithms_conf;
+ hc_OpenSSL_add_all_algorithms_noconf;
+ hc_PKCS12_key_gen;
+ hc_PKCS5_PBKDF2_HMAC;
+ hc_PKCS5_PBKDF2_HMAC_SHA1;
+ hc_RAND_add;
+ hc_RAND_bytes;
+ hc_RAND_cleanup;
+ hc_RAND_file_name;
+ hc_RAND_fortuna_method;
+ hc_RAND_get_rand_method;
+ hc_RAND_load_file;
+ hc_RAND_pseudo_bytes;
+ hc_RAND_seed;
+ hc_RAND_set_rand_engine;
+ hc_RAND_set_rand_method;
+ hc_RAND_status;
+ hc_RAND_unix_method;
+ hc_RAND_timer_method;
+ hc_RAND_write_file;
+ hc_RC2_cbc_encrypt;
+ hc_RC2_decryptc;
+ hc_RC2_encryptc;
+ hc_RC2_set_key;
+ hc_RC4;
+ hc_RC4_set_key;
+ hc_RSA_check_key;
+ hc_RSA_free;
+ hc_RSA_generate_key_ex;
+ hc_RSA_get_app_data;
+ hc_RSA_get_default_method;
+ hc_RSA_get_method;
+ hc_RSA_new;
+ hc_RSA_new_method;
+ hc_RSA_null_method;
+ hc_RSA_private_decrypt;
+ hc_RSA_private_encrypt;
+ hc_RSA_public_decrypt;
+ hc_RSA_public_encrypt;
+ hc_RSA_set_app_data;
+ hc_RSA_set_default_method;
+ hc_RSA_set_method;
+ hc_RSA_sign;
+ hc_RSA_size;
+ hc_RSA_up_ref;
+ hc_RSA_verify;
+ hc_SHA1_Final;
+ hc_SHA1_Init;
+ hc_SHA1_Update;
+ hc_SHA256_Final;
+ hc_SHA256_Init;
+ hc_SHA256_Update;
+ hc_SHA384_Final;
+ hc_SHA384_Init;
+ hc_SHA384_Update;
+ hc_SHA512_Final;
+ hc_SHA512_Init;
+ hc_SHA512_Update;
+ hc_UI_UTIL_read_pw_string;
+ hc_UI_UTIL_read_pw_string;
+ hc_i2d_DHparams;
+ hc_d2i_RSAPrivateKey;
+ hc_i2d_RSAPrivateKey;
+ hc_i2d_RSAPublicKey;
+ hc_d2i_RSAPublicKey;
+ hc_EVP_CIPHER_CTX_ctrl;
+ hc_EVP_CIPHER_CTX_rand_key;
+ hc_EVP_CIPHER_CTX_set_key_length;
+ hc_EVP_hcrypto_rc2_cbc;
+ hc_EVP_hcrypto_rc2_40_cbc;
+ hc_EVP_hcrypto_camellia_128_cbc;
+ hc_EVP_CipherUpdate;
+ hc_EVP_CipherFinal_ex;
+ hc_hcrypto_validate;
+ hc_hcrypto_scalarmult_curve25519;
+ hc_hcrypto_scalarmult_curve25519_base;
+ local:
+ *;
+};
diff --git a/third_party/heimdal/lib/hcrypto/x25519/NTMakefile b/third_party/heimdal/lib/hcrypto/x25519/NTMakefile
new file mode 100644
index 0000000..408f240
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/NTMakefile
@@ -0,0 +1,46 @@
+########################################################################
+#
+# Copyright (c) 2009, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\hcrypto\x25519
+
+!include ../../../windows/NTMakefile.w32
+
+intcflags=-I$(SRC)\lib\hcrypto
+
+LIBX25519_OBJS= \
+ $(OBJ)\ed25519_ref10.obj \
+ $(OBJ)\x25519_ref10.obj
+
+$(LIBX25519): $(LIBX25519_OBJS)
+ $(LIBCON)
+
+all:: $(LIBX25519)
+
diff --git a/third_party/heimdal/lib/hcrypto/x25519/align.h b/third_party/heimdal/lib/hcrypto/x25519/align.h
new file mode 100644
index 0000000..57c90ec
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/align.h
@@ -0,0 +1,7 @@
+#ifndef CRYPTO_ALIGN
+# if defined(__INTEL_COMPILER) || defined(_MSC_VER)
+# define CRYPTO_ALIGN(x) __declspec(align(x))
+# else
+# define CRYPTO_ALIGN(x) __attribute__ ((aligned(x)))
+# endif
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10.c b/third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10.c
new file mode 100644
index 0000000..6533404
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10.c
@@ -0,0 +1,2886 @@
+/*
+ * ISC License
+ *
+ * Copyright (c) 2013-2019
+ * Frank Denis <j at pureftpd dot org>
+ *
+ * Permission to use, copy, modify, and/or 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.
+ */
+
+#include <roken.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "ed25519_ref10.h"
+#include "align.h"
+
+static inline uint64_t
+load_3(const unsigned char *in)
+{
+ uint64_t result;
+
+ result = (uint64_t) in[0];
+ result |= ((uint64_t) in[1]) << 8;
+ result |= ((uint64_t) in[2]) << 16;
+
+ return result;
+}
+
+static inline uint64_t
+load_4(const unsigned char *in)
+{
+ uint64_t result;
+
+ result = (uint64_t) in[0];
+ result |= ((uint64_t) in[1]) << 8;
+ result |= ((uint64_t) in[2]) << 16;
+ result |= ((uint64_t) in[3]) << 24;
+
+ return result;
+}
+
+/*
+ * Field arithmetic:
+ * Use 5*51 bit limbs on 64-bit systems with support for 128 bit arithmetic,
+ * and 10*25.5 bit limbs elsewhere.
+ *
+ * Functions used elsewhere that are candidates for inlining are defined
+ * via "private/curve25519_ref10.h".
+ */
+
+#ifdef HAVE_TI_MODE
+# include "fe_51/constants.h"
+# include "fe_51/fe.h"
+#else
+# include "fe_25_5/constants.h"
+# include "fe_25_5/fe.h"
+#endif
+
+void
+fe25519_invert(fe25519 out, const fe25519 z)
+{
+ fe25519 t0;
+ fe25519 t1;
+ fe25519 t2;
+ fe25519 t3;
+ int i;
+
+ fe25519_sq(t0, z);
+ fe25519_sq(t1, t0);
+ fe25519_sq(t1, t1);
+ fe25519_mul(t1, z, t1);
+ fe25519_mul(t0, t0, t1);
+ fe25519_sq(t2, t0);
+ fe25519_mul(t1, t1, t2);
+ fe25519_sq(t2, t1);
+ for (i = 1; i < 5; ++i) {
+ fe25519_sq(t2, t2);
+ }
+ fe25519_mul(t1, t2, t1);
+ fe25519_sq(t2, t1);
+ for (i = 1; i < 10; ++i) {
+ fe25519_sq(t2, t2);
+ }
+ fe25519_mul(t2, t2, t1);
+ fe25519_sq(t3, t2);
+ for (i = 1; i < 20; ++i) {
+ fe25519_sq(t3, t3);
+ }
+ fe25519_mul(t2, t3, t2);
+ fe25519_sq(t2, t2);
+ for (i = 1; i < 10; ++i) {
+ fe25519_sq(t2, t2);
+ }
+ fe25519_mul(t1, t2, t1);
+ fe25519_sq(t2, t1);
+ for (i = 1; i < 50; ++i) {
+ fe25519_sq(t2, t2);
+ }
+ fe25519_mul(t2, t2, t1);
+ fe25519_sq(t3, t2);
+ for (i = 1; i < 100; ++i) {
+ fe25519_sq(t3, t3);
+ }
+ fe25519_mul(t2, t3, t2);
+ fe25519_sq(t2, t2);
+ for (i = 1; i < 50; ++i) {
+ fe25519_sq(t2, t2);
+ }
+ fe25519_mul(t1, t2, t1);
+ fe25519_sq(t1, t1);
+ for (i = 1; i < 5; ++i) {
+ fe25519_sq(t1, t1);
+ }
+ fe25519_mul(out, t1, t0);
+}
+
+static void
+fe25519_pow22523(fe25519 out, const fe25519 z)
+{
+ fe25519 t0;
+ fe25519 t1;
+ fe25519 t2;
+ int i;
+
+ fe25519_sq(t0, z);
+ fe25519_sq(t1, t0);
+ fe25519_sq(t1, t1);
+ fe25519_mul(t1, z, t1);
+ fe25519_mul(t0, t0, t1);
+ fe25519_sq(t0, t0);
+ fe25519_mul(t0, t1, t0);
+ fe25519_sq(t1, t0);
+ for (i = 1; i < 5; ++i) {
+ fe25519_sq(t1, t1);
+ }
+ fe25519_mul(t0, t1, t0);
+ fe25519_sq(t1, t0);
+ for (i = 1; i < 10; ++i) {
+ fe25519_sq(t1, t1);
+ }
+ fe25519_mul(t1, t1, t0);
+ fe25519_sq(t2, t1);
+ for (i = 1; i < 20; ++i) {
+ fe25519_sq(t2, t2);
+ }
+ fe25519_mul(t1, t2, t1);
+ fe25519_sq(t1, t1);
+ for (i = 1; i < 10; ++i) {
+ fe25519_sq(t1, t1);
+ }
+ fe25519_mul(t0, t1, t0);
+ fe25519_sq(t1, t0);
+ for (i = 1; i < 50; ++i) {
+ fe25519_sq(t1, t1);
+ }
+ fe25519_mul(t1, t1, t0);
+ fe25519_sq(t2, t1);
+ for (i = 1; i < 100; ++i) {
+ fe25519_sq(t2, t2);
+ }
+ fe25519_mul(t1, t2, t1);
+ fe25519_sq(t1, t1);
+ for (i = 1; i < 50; ++i) {
+ fe25519_sq(t1, t1);
+ }
+ fe25519_mul(t0, t1, t0);
+ fe25519_sq(t0, t0);
+ fe25519_sq(t0, t0);
+ fe25519_mul(out, t0, z);
+}
+
+static inline void
+fe25519_cneg(fe25519 h, const fe25519 f, unsigned int b)
+{
+ fe25519 negf;
+
+ fe25519_neg(negf, f);
+ fe25519_copy(h, f);
+ fe25519_cmov(h, negf, b);
+}
+
+static inline void
+fe25519_abs(fe25519 h, const fe25519 f)
+{
+ fe25519_cneg(h, f, fe25519_isnegative(f));
+}
+
+/*
+ r = p + q
+ */
+
+void
+ge25519_add(ge25519_p1p1 *r, const ge25519_p3 *p, const ge25519_cached *q)
+{
+ fe25519 t0;
+
+ fe25519_add(r->X, p->Y, p->X);
+ fe25519_sub(r->Y, p->Y, p->X);
+ fe25519_mul(r->Z, r->X, q->YplusX);
+ fe25519_mul(r->Y, r->Y, q->YminusX);
+ fe25519_mul(r->T, q->T2d, p->T);
+ fe25519_mul(r->X, p->Z, q->Z);
+ fe25519_add(t0, r->X, r->X);
+ fe25519_sub(r->X, r->Z, r->Y);
+ fe25519_add(r->Y, r->Z, r->Y);
+ fe25519_add(r->Z, t0, r->T);
+ fe25519_sub(r->T, t0, r->T);
+}
+
+static void
+slide_vartime(signed char *r, const unsigned char *a)
+{
+ int i;
+ int b;
+ int k;
+ int ribs;
+ int cmp;
+
+ for (i = 0; i < 256; ++i) {
+ r[i] = 1 & (a[i >> 3] >> (i & 7));
+ }
+ for (i = 0; i < 256; ++i) {
+ if (! r[i]) {
+ continue;
+ }
+ for (b = 1; b <= 6 && i + b < 256; ++b) {
+ if (! r[i + b]) {
+ continue;
+ }
+ ribs = r[i + b] << b;
+ cmp = r[i] + ribs;
+ if (cmp <= 15) {
+ r[i] = cmp;
+ r[i + b] = 0;
+ } else {
+ cmp = r[i] - ribs;
+ if (cmp < -15) {
+ break;
+ }
+ r[i] = cmp;
+ for (k = i + b; k < 256; ++k) {
+ if (! r[k]) {
+ r[k] = 1;
+ break;
+ }
+ r[k] = 0;
+ }
+ }
+ }
+ }
+}
+
+int
+ge25519_frombytes(ge25519_p3 *h, const unsigned char *s)
+{
+ fe25519 u;
+ fe25519 v;
+ fe25519 v3;
+ fe25519 vxx;
+ fe25519 m_root_check, p_root_check;
+ fe25519 negx;
+ fe25519 x_sqrtm1;
+ int has_m_root, has_p_root;
+
+ fe25519_frombytes(h->Y, s);
+ fe25519_1(h->Z);
+ fe25519_sq(u, h->Y);
+ fe25519_mul(v, u, d);
+ fe25519_sub(u, u, h->Z); /* u = y^2-1 */
+ fe25519_add(v, v, h->Z); /* v = dy^2+1 */
+
+ fe25519_sq(v3, v);
+ fe25519_mul(v3, v3, v); /* v3 = v^3 */
+ fe25519_sq(h->X, v3);
+ fe25519_mul(h->X, h->X, v);
+ fe25519_mul(h->X, h->X, u); /* x = uv^7 */
+
+ fe25519_pow22523(h->X, h->X); /* x = (uv^7)^((q-5)/8) */
+ fe25519_mul(h->X, h->X, v3);
+ fe25519_mul(h->X, h->X, u); /* x = uv^3(uv^7)^((q-5)/8) */
+
+ fe25519_sq(vxx, h->X);
+ fe25519_mul(vxx, vxx, v);
+ fe25519_sub(m_root_check, vxx, u); /* vx^2-u */
+ fe25519_add(p_root_check, vxx, u); /* vx^2+u */
+ has_m_root = fe25519_iszero(m_root_check);
+ has_p_root = fe25519_iszero(p_root_check);
+ fe25519_mul(x_sqrtm1, h->X, sqrtm1); /* x*sqrt(-1) */
+ fe25519_cmov(h->X, x_sqrtm1, 1 - has_m_root);
+
+ fe25519_neg(negx, h->X);
+ fe25519_cmov(h->X, negx, fe25519_isnegative(h->X) ^ (s[31] >> 7));
+ fe25519_mul(h->T, h->X, h->Y);
+
+ return (has_m_root | has_p_root) - 1;
+}
+
+int
+ge25519_frombytes_negate_vartime(ge25519_p3 *h, const unsigned char *s)
+{
+ fe25519 u;
+ fe25519 v;
+ fe25519 v3;
+ fe25519 vxx;
+ fe25519 m_root_check, p_root_check;
+
+ fe25519_frombytes(h->Y, s);
+ fe25519_1(h->Z);
+ fe25519_sq(u, h->Y);
+ fe25519_mul(v, u, d);
+ fe25519_sub(u, u, h->Z); /* u = y^2-1 */
+ fe25519_add(v, v, h->Z); /* v = dy^2+1 */
+
+ fe25519_sq(v3, v);
+ fe25519_mul(v3, v3, v); /* v3 = v^3 */
+ fe25519_sq(h->X, v3);
+ fe25519_mul(h->X, h->X, v);
+ fe25519_mul(h->X, h->X, u); /* x = uv^7 */
+
+ fe25519_pow22523(h->X, h->X); /* x = (uv^7)^((q-5)/8) */
+ fe25519_mul(h->X, h->X, v3);
+ fe25519_mul(h->X, h->X, u); /* x = uv^3(uv^7)^((q-5)/8) */
+
+ fe25519_sq(vxx, h->X);
+ fe25519_mul(vxx, vxx, v);
+ fe25519_sub(m_root_check, vxx, u); /* vx^2-u */
+ if (fe25519_iszero(m_root_check) == 0) {
+ fe25519_add(p_root_check, vxx, u); /* vx^2+u */
+ if (fe25519_iszero(p_root_check) == 0) {
+ return -1;
+ }
+ fe25519_mul(h->X, h->X, sqrtm1);
+ }
+
+ if (fe25519_isnegative(h->X) == (s[31] >> 7)) {
+ fe25519_neg(h->X, h->X);
+ }
+ fe25519_mul(h->T, h->X, h->Y);
+
+ return 0;
+}
+
+/*
+ r = p + q
+ */
+
+static void
+ge25519_madd(ge25519_p1p1 *r, const ge25519_p3 *p, const ge25519_precomp *q)
+{
+ fe25519 t0;
+
+ fe25519_add(r->X, p->Y, p->X);
+ fe25519_sub(r->Y, p->Y, p->X);
+ fe25519_mul(r->Z, r->X, q->yplusx);
+ fe25519_mul(r->Y, r->Y, q->yminusx);
+ fe25519_mul(r->T, q->xy2d, p->T);
+ fe25519_add(t0, p->Z, p->Z);
+ fe25519_sub(r->X, r->Z, r->Y);
+ fe25519_add(r->Y, r->Z, r->Y);
+ fe25519_add(r->Z, t0, r->T);
+ fe25519_sub(r->T, t0, r->T);
+}
+
+/*
+ r = p - q
+ */
+
+static void
+ge25519_msub(ge25519_p1p1 *r, const ge25519_p3 *p, const ge25519_precomp *q)
+{
+ fe25519 t0;
+
+ fe25519_add(r->X, p->Y, p->X);
+ fe25519_sub(r->Y, p->Y, p->X);
+ fe25519_mul(r->Z, r->X, q->yminusx);
+ fe25519_mul(r->Y, r->Y, q->yplusx);
+ fe25519_mul(r->T, q->xy2d, p->T);
+ fe25519_add(t0, p->Z, p->Z);
+ fe25519_sub(r->X, r->Z, r->Y);
+ fe25519_add(r->Y, r->Z, r->Y);
+ fe25519_sub(r->Z, t0, r->T);
+ fe25519_add(r->T, t0, r->T);
+}
+
+/*
+ r = p
+ */
+
+void
+ge25519_p1p1_to_p2(ge25519_p2 *r, const ge25519_p1p1 *p)
+{
+ fe25519_mul(r->X, p->X, p->T);
+ fe25519_mul(r->Y, p->Y, p->Z);
+ fe25519_mul(r->Z, p->Z, p->T);
+}
+
+/*
+ r = p
+ */
+
+void
+ge25519_p1p1_to_p3(ge25519_p3 *r, const ge25519_p1p1 *p)
+{
+ fe25519_mul(r->X, p->X, p->T);
+ fe25519_mul(r->Y, p->Y, p->Z);
+ fe25519_mul(r->Z, p->Z, p->T);
+ fe25519_mul(r->T, p->X, p->Y);
+}
+
+static void
+ge25519_p2_0(ge25519_p2 *h)
+{
+ fe25519_0(h->X);
+ fe25519_1(h->Y);
+ fe25519_1(h->Z);
+}
+
+/*
+ r = 2 * p
+ */
+
+static void
+ge25519_p2_dbl(ge25519_p1p1 *r, const ge25519_p2 *p)
+{
+ fe25519 t0;
+
+ fe25519_sq(r->X, p->X);
+ fe25519_sq(r->Z, p->Y);
+ fe25519_sq2(r->T, p->Z);
+ fe25519_add(r->Y, p->X, p->Y);
+ fe25519_sq(t0, r->Y);
+ fe25519_add(r->Y, r->Z, r->X);
+ fe25519_sub(r->Z, r->Z, r->X);
+ fe25519_sub(r->X, t0, r->Y);
+ fe25519_sub(r->T, r->T, r->Z);
+}
+
+static void
+ge25519_p3_0(ge25519_p3 *h)
+{
+ fe25519_0(h->X);
+ fe25519_1(h->Y);
+ fe25519_1(h->Z);
+ fe25519_0(h->T);
+}
+
+static void
+ge25519_cached_0(ge25519_cached *h)
+{
+ fe25519_1(h->YplusX);
+ fe25519_1(h->YminusX);
+ fe25519_1(h->Z);
+ fe25519_0(h->T2d);
+}
+
+/*
+ r = p
+ */
+
+void
+ge25519_p3_to_cached(ge25519_cached *r, const ge25519_p3 *p)
+{
+ fe25519_add(r->YplusX, p->Y, p->X);
+ fe25519_sub(r->YminusX, p->Y, p->X);
+ fe25519_copy(r->Z, p->Z);
+ fe25519_mul(r->T2d, p->T, d2);
+}
+
+static void
+ge25519_p3_to_precomp(ge25519_precomp *pi, const ge25519_p3 *p)
+{
+ fe25519 recip;
+ fe25519 x;
+ fe25519 y;
+ fe25519 xy;
+
+ fe25519_invert(recip, p->Z);
+ fe25519_mul(x, p->X, recip);
+ fe25519_mul(y, p->Y, recip);
+ fe25519_add(pi->yplusx, y, x);
+ fe25519_sub(pi->yminusx, y, x);
+ fe25519_mul(xy, x, y);
+ fe25519_mul(pi->xy2d, xy, d2);
+}
+
+/*
+ r = p
+ */
+
+static void
+ge25519_p3_to_p2(ge25519_p2 *r, const ge25519_p3 *p)
+{
+ fe25519_copy(r->X, p->X);
+ fe25519_copy(r->Y, p->Y);
+ fe25519_copy(r->Z, p->Z);
+}
+
+void
+ge25519_p3_tobytes(unsigned char *s, const ge25519_p3 *h)
+{
+ fe25519 recip;
+ fe25519 x;
+ fe25519 y;
+
+ fe25519_invert(recip, h->Z);
+ fe25519_mul(x, h->X, recip);
+ fe25519_mul(y, h->Y, recip);
+ fe25519_tobytes(s, y);
+ s[31] ^= fe25519_isnegative(x) << 7;
+}
+
+/*
+ r = 2 * p
+ */
+
+static void
+ge25519_p3_dbl(ge25519_p1p1 *r, const ge25519_p3 *p)
+{
+ ge25519_p2 q;
+ ge25519_p3_to_p2(&q, p);
+ ge25519_p2_dbl(r, &q);
+}
+
+static void
+ge25519_precomp_0(ge25519_precomp *h)
+{
+ fe25519_1(h->yplusx);
+ fe25519_1(h->yminusx);
+ fe25519_0(h->xy2d);
+}
+
+static unsigned char
+equal(signed char b, signed char c)
+{
+ unsigned char ub = b;
+ unsigned char uc = c;
+ unsigned char x = ub ^ uc; /* 0: yes; 1..255: no */
+ uint32_t y = (uint32_t) x; /* 0: yes; 1..255: no */
+
+ y -= 1; /* 4294967295: yes; 0..254: no */
+ y >>= 31; /* 1: yes; 0: no */
+
+ return y;
+}
+
+static unsigned char
+negative(signed char b)
+{
+ /* 18446744073709551361..18446744073709551615: yes; 0..255: no */
+ uint64_t x = b;
+
+ x >>= 63; /* 1: yes; 0: no */
+
+ return x;
+}
+
+static void
+ge25519_cmov(ge25519_precomp *t, const ge25519_precomp *u, unsigned char b)
+{
+ fe25519_cmov(t->yplusx, u->yplusx, b);
+ fe25519_cmov(t->yminusx, u->yminusx, b);
+ fe25519_cmov(t->xy2d, u->xy2d, b);
+}
+
+static void
+ge25519_cmov_cached(ge25519_cached *t, const ge25519_cached *u, unsigned char b)
+{
+ fe25519_cmov(t->YplusX, u->YplusX, b);
+ fe25519_cmov(t->YminusX, u->YminusX, b);
+ fe25519_cmov(t->Z, u->Z, b);
+ fe25519_cmov(t->T2d, u->T2d, b);
+}
+
+static void
+ge25519_cmov8(ge25519_precomp *t, const ge25519_precomp precomp[8], const signed char b)
+{
+ ge25519_precomp minust;
+ const unsigned char bnegative = negative(b);
+ const unsigned char babs = b - (((-bnegative) & b) * ((signed char) 1 << 1));
+
+ ge25519_precomp_0(t);
+ ge25519_cmov(t, &precomp[0], equal(babs, 1));
+ ge25519_cmov(t, &precomp[1], equal(babs, 2));
+ ge25519_cmov(t, &precomp[2], equal(babs, 3));
+ ge25519_cmov(t, &precomp[3], equal(babs, 4));
+ ge25519_cmov(t, &precomp[4], equal(babs, 5));
+ ge25519_cmov(t, &precomp[5], equal(babs, 6));
+ ge25519_cmov(t, &precomp[6], equal(babs, 7));
+ ge25519_cmov(t, &precomp[7], equal(babs, 8));
+ fe25519_copy(minust.yplusx, t->yminusx);
+ fe25519_copy(minust.yminusx, t->yplusx);
+ fe25519_neg(minust.xy2d, t->xy2d);
+ ge25519_cmov(t, &minust, bnegative);
+}
+
+static void
+ge25519_cmov8_base(ge25519_precomp *t, const int pos, const signed char b)
+{
+ static const ge25519_precomp base[32][8] = { /* base[i][j] = (j+1)*256^i*B */
+#ifdef HAVE_TI_MODE
+# include "fe_51/base.h"
+#else
+# include "fe_25_5/base.h"
+#endif
+ };
+ ge25519_cmov8(t, base[pos], b);
+}
+
+static void
+ge25519_cmov8_cached(ge25519_cached *t, const ge25519_cached cached[8], const signed char b)
+{
+ ge25519_cached minust;
+ const unsigned char bnegative = negative(b);
+ const unsigned char babs = b - (((-bnegative) & b) * ((signed char) 1 << 1));
+
+ ge25519_cached_0(t);
+ ge25519_cmov_cached(t, &cached[0], equal(babs, 1));
+ ge25519_cmov_cached(t, &cached[1], equal(babs, 2));
+ ge25519_cmov_cached(t, &cached[2], equal(babs, 3));
+ ge25519_cmov_cached(t, &cached[3], equal(babs, 4));
+ ge25519_cmov_cached(t, &cached[4], equal(babs, 5));
+ ge25519_cmov_cached(t, &cached[5], equal(babs, 6));
+ ge25519_cmov_cached(t, &cached[6], equal(babs, 7));
+ ge25519_cmov_cached(t, &cached[7], equal(babs, 8));
+ fe25519_copy(minust.YplusX, t->YminusX);
+ fe25519_copy(minust.YminusX, t->YplusX);
+ fe25519_copy(minust.Z, t->Z);
+ fe25519_neg(minust.T2d, t->T2d);
+ ge25519_cmov_cached(t, &minust, bnegative);
+}
+
+/*
+ r = p - q
+ */
+
+void
+ge25519_sub(ge25519_p1p1 *r, const ge25519_p3 *p, const ge25519_cached *q)
+{
+ fe25519 t0;
+
+ fe25519_add(r->X, p->Y, p->X);
+ fe25519_sub(r->Y, p->Y, p->X);
+ fe25519_mul(r->Z, r->X, q->YminusX);
+ fe25519_mul(r->Y, r->Y, q->YplusX);
+ fe25519_mul(r->T, q->T2d, p->T);
+ fe25519_mul(r->X, p->Z, q->Z);
+ fe25519_add(t0, r->X, r->X);
+ fe25519_sub(r->X, r->Z, r->Y);
+ fe25519_add(r->Y, r->Z, r->Y);
+ fe25519_sub(r->Z, t0, r->T);
+ fe25519_add(r->T, t0, r->T);
+}
+
+void
+ge25519_tobytes(unsigned char *s, const ge25519_p2 *h)
+{
+ fe25519 recip;
+ fe25519 x;
+ fe25519 y;
+
+ fe25519_invert(recip, h->Z);
+ fe25519_mul(x, h->X, recip);
+ fe25519_mul(y, h->Y, recip);
+ fe25519_tobytes(s, y);
+ s[31] ^= fe25519_isnegative(x) << 7;
+}
+
+/*
+ r = a * A + b * B
+ where a = a[0]+256*a[1]+...+256^31 a[31].
+ and b = b[0]+256*b[1]+...+256^31 b[31].
+ B is the Ed25519 base point (x,4/5) with x positive.
+
+ Only used for signatures verification.
+ */
+
+void
+ge25519_double_scalarmult_vartime(ge25519_p2 *r, const unsigned char *a,
+ const ge25519_p3 *A, const unsigned char *b)
+{
+ static const ge25519_precomp Bi[8] = {
+#ifdef HAVE_TI_MODE
+# include "fe_51/base2.h"
+#else
+# include "fe_25_5/base2.h"
+#endif
+ };
+ signed char aslide[256];
+ signed char bslide[256];
+ ge25519_cached Ai[8]; /* A,3A,5A,7A,9A,11A,13A,15A */
+ ge25519_p1p1 t;
+ ge25519_p3 u;
+ ge25519_p3 A2;
+ int i;
+
+ slide_vartime(aslide, a);
+ slide_vartime(bslide, b);
+
+ ge25519_p3_to_cached(&Ai[0], A);
+
+ ge25519_p3_dbl(&t, A);
+ ge25519_p1p1_to_p3(&A2, &t);
+
+ ge25519_add(&t, &A2, &Ai[0]);
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_p3_to_cached(&Ai[1], &u);
+
+ ge25519_add(&t, &A2, &Ai[1]);
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_p3_to_cached(&Ai[2], &u);
+
+ ge25519_add(&t, &A2, &Ai[2]);
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_p3_to_cached(&Ai[3], &u);
+
+ ge25519_add(&t, &A2, &Ai[3]);
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_p3_to_cached(&Ai[4], &u);
+
+ ge25519_add(&t, &A2, &Ai[4]);
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_p3_to_cached(&Ai[5], &u);
+
+ ge25519_add(&t, &A2, &Ai[5]);
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_p3_to_cached(&Ai[6], &u);
+
+ ge25519_add(&t, &A2, &Ai[6]);
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_p3_to_cached(&Ai[7], &u);
+
+ ge25519_p2_0(r);
+
+ for (i = 255; i >= 0; --i) {
+ if (aslide[i] || bslide[i]) {
+ break;
+ }
+ }
+
+ for (; i >= 0; --i) {
+ ge25519_p2_dbl(&t, r);
+
+ if (aslide[i] > 0) {
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_add(&t, &u, &Ai[aslide[i] / 2]);
+ } else if (aslide[i] < 0) {
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_sub(&t, &u, &Ai[(-aslide[i]) / 2]);
+ }
+
+ if (bslide[i] > 0) {
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_madd(&t, &u, &Bi[bslide[i] / 2]);
+ } else if (bslide[i] < 0) {
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_msub(&t, &u, &Bi[(-bslide[i]) / 2]);
+ }
+
+ ge25519_p1p1_to_p2(r, &t);
+ }
+}
+
+/*
+ h = a * p
+ where a = a[0]+256*a[1]+...+256^31 a[31]
+
+ Preconditions:
+ a[31] <= 127
+
+ p is public
+ */
+
+void
+ge25519_scalarmult(ge25519_p3 *h, const unsigned char *a, const ge25519_p3 *p)
+{
+ signed char e[64];
+ signed char carry;
+ ge25519_p1p1 r;
+ ge25519_p2 s;
+ ge25519_p1p1 t2, t3, t4, t5, t6, t7, t8;
+ ge25519_p3 p2, p3, p4, p5, p6, p7, p8;
+ ge25519_cached pi[8];
+ ge25519_cached t;
+ int i;
+
+ ge25519_p3_to_cached(&pi[1 - 1], p); /* p */
+
+ ge25519_p3_dbl(&t2, p);
+ ge25519_p1p1_to_p3(&p2, &t2);
+ ge25519_p3_to_cached(&pi[2 - 1], &p2); /* 2p = 2*p */
+
+ ge25519_add(&t3, p, &pi[2 - 1]);
+ ge25519_p1p1_to_p3(&p3, &t3);
+ ge25519_p3_to_cached(&pi[3 - 1], &p3); /* 3p = 2p+p */
+
+ ge25519_p3_dbl(&t4, &p2);
+ ge25519_p1p1_to_p3(&p4, &t4);
+ ge25519_p3_to_cached(&pi[4 - 1], &p4); /* 4p = 2*2p */
+
+ ge25519_add(&t5, p, &pi[4 - 1]);
+ ge25519_p1p1_to_p3(&p5, &t5);
+ ge25519_p3_to_cached(&pi[5 - 1], &p5); /* 5p = 4p+p */
+
+ ge25519_p3_dbl(&t6, &p3);
+ ge25519_p1p1_to_p3(&p6, &t6);
+ ge25519_p3_to_cached(&pi[6 - 1], &p6); /* 6p = 2*3p */
+
+ ge25519_add(&t7, p, &pi[6 - 1]);
+ ge25519_p1p1_to_p3(&p7, &t7);
+ ge25519_p3_to_cached(&pi[7 - 1], &p7); /* 7p = 6p+p */
+
+ ge25519_p3_dbl(&t8, &p4);
+ ge25519_p1p1_to_p3(&p8, &t8);
+ ge25519_p3_to_cached(&pi[8 - 1], &p8); /* 8p = 2*4p */
+
+ for (i = 0; i < 32; ++i) {
+ e[2 * i + 0] = (a[i] >> 0) & 15;
+ e[2 * i + 1] = (a[i] >> 4) & 15;
+ }
+ /* each e[i] is between 0 and 15 */
+ /* e[63] is between 0 and 7 */
+
+ carry = 0;
+ for (i = 0; i < 63; ++i) {
+ e[i] += carry;
+ carry = e[i] + 8;
+ carry >>= 4;
+ e[i] -= carry * ((signed char) 1 << 4);
+ }
+ e[63] += carry;
+ /* each e[i] is between -8 and 8 */
+
+ ge25519_p3_0(h);
+
+ for (i = 63; i != 0; i--) {
+ ge25519_cmov8_cached(&t, pi, e[i]);
+ ge25519_add(&r, h, &t);
+
+ ge25519_p1p1_to_p2(&s, &r);
+ ge25519_p2_dbl(&r, &s);
+ ge25519_p1p1_to_p2(&s, &r);
+ ge25519_p2_dbl(&r, &s);
+ ge25519_p1p1_to_p2(&s, &r);
+ ge25519_p2_dbl(&r, &s);
+ ge25519_p1p1_to_p2(&s, &r);
+ ge25519_p2_dbl(&r, &s);
+
+ ge25519_p1p1_to_p3(h, &r); /* *16 */
+ }
+ ge25519_cmov8_cached(&t, pi, e[i]);
+ ge25519_add(&r, h, &t);
+
+ ge25519_p1p1_to_p3(h, &r);
+}
+
+/*
+ h = a * B (with precomputation)
+ where a = a[0]+256*a[1]+...+256^31 a[31]
+ B is the Ed25519 base point (x,4/5) with x positive
+ (as bytes: 0x5866666666666666666666666666666666666666666666666666666666666666)
+
+ Preconditions:
+ a[31] <= 127
+ */
+
+void
+ge25519_scalarmult_base(ge25519_p3 *h, const unsigned char *a)
+{
+ signed char e[64];
+ signed char carry;
+ ge25519_p1p1 r;
+ ge25519_p2 s;
+ ge25519_precomp t;
+ int i;
+
+ for (i = 0; i < 32; ++i) {
+ e[2 * i + 0] = (a[i] >> 0) & 15;
+ e[2 * i + 1] = (a[i] >> 4) & 15;
+ }
+ /* each e[i] is between 0 and 15 */
+ /* e[63] is between 0 and 7 */
+
+ carry = 0;
+ for (i = 0; i < 63; ++i) {
+ e[i] += carry;
+ carry = e[i] + 8;
+ carry >>= 4;
+ e[i] -= carry * ((signed char) 1 << 4);
+ }
+ e[63] += carry;
+ /* each e[i] is between -8 and 8 */
+
+ ge25519_p3_0(h);
+
+ for (i = 1; i < 64; i += 2) {
+ ge25519_cmov8_base(&t, i / 2, e[i]);
+ ge25519_madd(&r, h, &t);
+ ge25519_p1p1_to_p3(h, &r);
+ }
+
+ ge25519_p3_dbl(&r, h);
+ ge25519_p1p1_to_p2(&s, &r);
+ ge25519_p2_dbl(&r, &s);
+ ge25519_p1p1_to_p2(&s, &r);
+ ge25519_p2_dbl(&r, &s);
+ ge25519_p1p1_to_p2(&s, &r);
+ ge25519_p2_dbl(&r, &s);
+ ge25519_p1p1_to_p3(h, &r);
+
+ for (i = 0; i < 64; i += 2) {
+ ge25519_cmov8_base(&t, i / 2, e[i]);
+ ge25519_madd(&r, h, &t);
+ ge25519_p1p1_to_p3(h, &r);
+ }
+}
+
+/* multiply by the order of the main subgroup l = 2^252+27742317777372353535851937790883648493 */
+static void
+ge25519_mul_l(ge25519_p3 *r, const ge25519_p3 *A)
+{
+ static const signed char aslide[253] = {
+ 13, 0, 0, 0, 0, -1, 0, 0, 0, 0, -11, 0, 0, 0, 0, 0, 0, -5, 0, 0, 0, 0, 0, 0, -3, 0, 0, 0, 0, -13, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, -13, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, -13, 0, 0, 0, 0, 0, 0, -3, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 3, 0, 0, 0, 0, -11, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 7, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
+ };
+ ge25519_cached Ai[8];
+ ge25519_p1p1 t;
+ ge25519_p3 u;
+ ge25519_p3 A2;
+ int i;
+
+ ge25519_p3_to_cached(&Ai[0], A);
+ ge25519_p3_dbl(&t, A);
+ ge25519_p1p1_to_p3(&A2, &t);
+ ge25519_add(&t, &A2, &Ai[0]);
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_p3_to_cached(&Ai[1], &u);
+ ge25519_add(&t, &A2, &Ai[1]);
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_p3_to_cached(&Ai[2], &u);
+ ge25519_add(&t, &A2, &Ai[2]);
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_p3_to_cached(&Ai[3], &u);
+ ge25519_add(&t, &A2, &Ai[3]);
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_p3_to_cached(&Ai[4], &u);
+ ge25519_add(&t, &A2, &Ai[4]);
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_p3_to_cached(&Ai[5], &u);
+ ge25519_add(&t, &A2, &Ai[5]);
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_p3_to_cached(&Ai[6], &u);
+ ge25519_add(&t, &A2, &Ai[6]);
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_p3_to_cached(&Ai[7], &u);
+
+ ge25519_p3_0(r);
+
+ for (i = 252; i >= 0; --i) {
+ ge25519_p3_dbl(&t, r);
+
+ if (aslide[i] > 0) {
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_add(&t, &u, &Ai[aslide[i] / 2]);
+ } else if (aslide[i] < 0) {
+ ge25519_p1p1_to_p3(&u, &t);
+ ge25519_sub(&t, &u, &Ai[(-aslide[i]) / 2]);
+ }
+
+ ge25519_p1p1_to_p3(r, &t);
+ }
+}
+
+int
+ge25519_is_on_curve(const ge25519_p3 *p)
+{
+ fe25519 x2;
+ fe25519 y2;
+ fe25519 z2;
+ fe25519 z4;
+ fe25519 t0;
+ fe25519 t1;
+
+ fe25519_sq(x2, p->X);
+ fe25519_sq(y2, p->Y);
+ fe25519_sq(z2, p->Z);
+ fe25519_sub(t0, y2, x2);
+ fe25519_mul(t0, t0, z2);
+
+ fe25519_mul(t1, x2, y2);
+ fe25519_mul(t1, t1, d);
+ fe25519_sq(z4, z2);
+ fe25519_add(t1, t1, z4);
+ fe25519_sub(t0, t0, t1);
+
+ return fe25519_iszero(t0);
+}
+
+int
+ge25519_is_on_main_subgroup(const ge25519_p3 *p)
+{
+ ge25519_p3 pl;
+
+ ge25519_mul_l(&pl, p);
+
+ return fe25519_iszero(pl.X);
+}
+
+int
+ge25519_is_canonical(const unsigned char *s)
+{
+ unsigned char c;
+ unsigned char d;
+ unsigned int i;
+
+ c = (s[31] & 0x7f) ^ 0x7f;
+ for (i = 30; i > 0; i--) {
+ c |= s[i] ^ 0xff;
+ }
+ c = (((unsigned int) c) - 1U) >> 8;
+ d = (0xed - 1U - (unsigned int) s[0]) >> 8;
+
+ return 1 - (c & d & 1);
+}
+
+int
+ge25519_has_small_order(const unsigned char s[32])
+{
+ CRYPTO_ALIGN(16)
+ static const unsigned char blacklist[][32] = {
+ /* 0 (order 4) */
+ { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
+ /* 1 (order 1) */
+ { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
+ /* 2707385501144840649318225287225658788936804267575313519463743609750303402022
+ (order 8) */
+ { 0x26, 0xe8, 0x95, 0x8f, 0xc2, 0xb2, 0x27, 0xb0, 0x45, 0xc3, 0xf4,
+ 0x89, 0xf2, 0xef, 0x98, 0xf0, 0xd5, 0xdf, 0xac, 0x05, 0xd3, 0xc6,
+ 0x33, 0x39, 0xb1, 0x38, 0x02, 0x88, 0x6d, 0x53, 0xfc, 0x05 },
+ /* 55188659117513257062467267217118295137698188065244968500265048394206261417927
+ (order 8) */
+ { 0xc7, 0x17, 0x6a, 0x70, 0x3d, 0x4d, 0xd8, 0x4f, 0xba, 0x3c, 0x0b,
+ 0x76, 0x0d, 0x10, 0x67, 0x0f, 0x2a, 0x20, 0x53, 0xfa, 0x2c, 0x39,
+ 0xcc, 0xc6, 0x4e, 0xc7, 0xfd, 0x77, 0x92, 0xac, 0x03, 0x7a },
+ /* p-1 (order 2) */
+ { 0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f },
+ /* p (=0, order 4) */
+ { 0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f },
+ /* p+1 (=1, order 1) */
+ { 0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f }
+ };
+ unsigned char c[7] = { 0 };
+ unsigned int k;
+ size_t i, j;
+
+#define COMPILER_ASSERT(X) (void) sizeof(char[(X) ? 1 : -1])
+
+ COMPILER_ASSERT(7 == sizeof blacklist / sizeof blacklist[0]);
+ for (j = 0; j < 31; j++) {
+ for (i = 0; i < sizeof blacklist / sizeof blacklist[0]; i++) {
+ c[i] |= s[j] ^ blacklist[i][j];
+ }
+ }
+ for (i = 0; i < sizeof blacklist / sizeof blacklist[0]; i++) {
+ c[i] |= (s[j] & 0x7f) ^ blacklist[i][j];
+ }
+ k = 0;
+ for (i = 0; i < sizeof blacklist / sizeof blacklist[0]; i++) {
+ k |= (c[i] - 1);
+ }
+ return (int) ((k >> 8) & 1);
+}
+
+/*
+ Input:
+ a[0]+256*a[1]+...+256^31*a[31] = a
+ b[0]+256*b[1]+...+256^31*b[31] = b
+ *
+ Output:
+ s[0]+256*s[1]+...+256^31*s[31] = (ab) mod l
+ where l = 2^252 + 27742317777372353535851937790883648493.
+ */
+
+void
+sc25519_mul(unsigned char s[32], const unsigned char a[32], const unsigned char b[32])
+{
+ int64_t a0 = 2097151 & load_3(a);
+ int64_t a1 = 2097151 & (load_4(a + 2) >> 5);
+ int64_t a2 = 2097151 & (load_3(a + 5) >> 2);
+ int64_t a3 = 2097151 & (load_4(a + 7) >> 7);
+ int64_t a4 = 2097151 & (load_4(a + 10) >> 4);
+ int64_t a5 = 2097151 & (load_3(a + 13) >> 1);
+ int64_t a6 = 2097151 & (load_4(a + 15) >> 6);
+ int64_t a7 = 2097151 & (load_3(a + 18) >> 3);
+ int64_t a8 = 2097151 & load_3(a + 21);
+ int64_t a9 = 2097151 & (load_4(a + 23) >> 5);
+ int64_t a10 = 2097151 & (load_3(a + 26) >> 2);
+ int64_t a11 = (load_4(a + 28) >> 7);
+
+ int64_t b0 = 2097151 & load_3(b);
+ int64_t b1 = 2097151 & (load_4(b + 2) >> 5);
+ int64_t b2 = 2097151 & (load_3(b + 5) >> 2);
+ int64_t b3 = 2097151 & (load_4(b + 7) >> 7);
+ int64_t b4 = 2097151 & (load_4(b + 10) >> 4);
+ int64_t b5 = 2097151 & (load_3(b + 13) >> 1);
+ int64_t b6 = 2097151 & (load_4(b + 15) >> 6);
+ int64_t b7 = 2097151 & (load_3(b + 18) >> 3);
+ int64_t b8 = 2097151 & load_3(b + 21);
+ int64_t b9 = 2097151 & (load_4(b + 23) >> 5);
+ int64_t b10 = 2097151 & (load_3(b + 26) >> 2);
+ int64_t b11 = (load_4(b + 28) >> 7);
+
+ int64_t s0;
+ int64_t s1;
+ int64_t s2;
+ int64_t s3;
+ int64_t s4;
+ int64_t s5;
+ int64_t s6;
+ int64_t s7;
+ int64_t s8;
+ int64_t s9;
+ int64_t s10;
+ int64_t s11;
+ int64_t s12;
+ int64_t s13;
+ int64_t s14;
+ int64_t s15;
+ int64_t s16;
+ int64_t s17;
+ int64_t s18;
+ int64_t s19;
+ int64_t s20;
+ int64_t s21;
+ int64_t s22;
+ int64_t s23;
+
+ int64_t carry0;
+ int64_t carry1;
+ int64_t carry2;
+ int64_t carry3;
+ int64_t carry4;
+ int64_t carry5;
+ int64_t carry6;
+ int64_t carry7;
+ int64_t carry8;
+ int64_t carry9;
+ int64_t carry10;
+ int64_t carry11;
+ int64_t carry12;
+ int64_t carry13;
+ int64_t carry14;
+ int64_t carry15;
+ int64_t carry16;
+ int64_t carry17;
+ int64_t carry18;
+ int64_t carry19;
+ int64_t carry20;
+ int64_t carry21;
+ int64_t carry22;
+
+ s0 = a0 * b0;
+ s1 = a0 * b1 + a1 * b0;
+ s2 = a0 * b2 + a1 * b1 + a2 * b0;
+ s3 = a0 * b3 + a1 * b2 + a2 * b1 + a3 * b0;
+ s4 = a0 * b4 + a1 * b3 + a2 * b2 + a3 * b1 + a4 * b0;
+ s5 = a0 * b5 + a1 * b4 + a2 * b3 + a3 * b2 + a4 * b1 + a5 * b0;
+ s6 = a0 * b6 + a1 * b5 + a2 * b4 + a3 * b3 + a4 * b2 + a5 * b1 + a6 * b0;
+ s7 = a0 * b7 + a1 * b6 + a2 * b5 + a3 * b4 + a4 * b3 + a5 * b2 +
+ a6 * b1 + a7 * b0;
+ s8 = a0 * b8 + a1 * b7 + a2 * b6 + a3 * b5 + a4 * b4 + a5 * b3 +
+ a6 * b2 + a7 * b1 + a8 * b0;
+ s9 = a0 * b9 + a1 * b8 + a2 * b7 + a3 * b6 + a4 * b5 + a5 * b4 +
+ a6 * b3 + a7 * b2 + a8 * b1 + a9 * b0;
+ s10 = a0 * b10 + a1 * b9 + a2 * b8 + a3 * b7 + a4 * b6 + a5 * b5 +
+ a6 * b4 + a7 * b3 + a8 * b2 + a9 * b1 + a10 * b0;
+ s11 = a0 * b11 + a1 * b10 + a2 * b9 + a3 * b8 + a4 * b7 + a5 * b6 +
+ a6 * b5 + a7 * b4 + a8 * b3 + a9 * b2 + a10 * b1 + a11 * b0;
+ s12 = a1 * b11 + a2 * b10 + a3 * b9 + a4 * b8 + a5 * b7 + a6 * b6 +
+ a7 * b5 + a8 * b4 + a9 * b3 + a10 * b2 + a11 * b1;
+ s13 = a2 * b11 + a3 * b10 + a4 * b9 + a5 * b8 + a6 * b7 + a7 * b6 +
+ a8 * b5 + a9 * b4 + a10 * b3 + a11 * b2;
+ s14 = a3 * b11 + a4 * b10 + a5 * b9 + a6 * b8 + a7 * b7 + a8 * b6 +
+ a9 * b5 + a10 * b4 + a11 * b3;
+ s15 = a4 * b11 + a5 * b10 + a6 * b9 + a7 * b8 + a8 * b7 + a9 * b6 +
+ a10 * b5 + a11 * b4;
+ s16 =
+ a5 * b11 + a6 * b10 + a7 * b9 + a8 * b8 + a9 * b7 + a10 * b6 + a11 * b5;
+ s17 = a6 * b11 + a7 * b10 + a8 * b9 + a9 * b8 + a10 * b7 + a11 * b6;
+ s18 = a7 * b11 + a8 * b10 + a9 * b9 + a10 * b8 + a11 * b7;
+ s19 = a8 * b11 + a9 * b10 + a10 * b9 + a11 * b8;
+ s20 = a9 * b11 + a10 * b10 + a11 * b9;
+ s21 = a10 * b11 + a11 * b10;
+ s22 = a11 * b11;
+ s23 = 0;
+
+ carry0 = (s0 + (int64_t) (1L << 20)) >> 21;
+ s1 += carry0;
+ s0 -= carry0 * ((uint64_t) 1L << 21);
+ carry2 = (s2 + (int64_t) (1L << 20)) >> 21;
+ s3 += carry2;
+ s2 -= carry2 * ((uint64_t) 1L << 21);
+ carry4 = (s4 + (int64_t) (1L << 20)) >> 21;
+ s5 += carry4;
+ s4 -= carry4 * ((uint64_t) 1L << 21);
+ carry6 = (s6 + (int64_t) (1L << 20)) >> 21;
+ s7 += carry6;
+ s6 -= carry6 * ((uint64_t) 1L << 21);
+ carry8 = (s8 + (int64_t) (1L << 20)) >> 21;
+ s9 += carry8;
+ s8 -= carry8 * ((uint64_t) 1L << 21);
+ carry10 = (s10 + (int64_t) (1L << 20)) >> 21;
+ s11 += carry10;
+ s10 -= carry10 * ((uint64_t) 1L << 21);
+ carry12 = (s12 + (int64_t) (1L << 20)) >> 21;
+ s13 += carry12;
+ s12 -= carry12 * ((uint64_t) 1L << 21);
+ carry14 = (s14 + (int64_t) (1L << 20)) >> 21;
+ s15 += carry14;
+ s14 -= carry14 * ((uint64_t) 1L << 21);
+ carry16 = (s16 + (int64_t) (1L << 20)) >> 21;
+ s17 += carry16;
+ s16 -= carry16 * ((uint64_t) 1L << 21);
+ carry18 = (s18 + (int64_t) (1L << 20)) >> 21;
+ s19 += carry18;
+ s18 -= carry18 * ((uint64_t) 1L << 21);
+ carry20 = (s20 + (int64_t) (1L << 20)) >> 21;
+ s21 += carry20;
+ s20 -= carry20 * ((uint64_t) 1L << 21);
+ carry22 = (s22 + (int64_t) (1L << 20)) >> 21;
+ s23 += carry22;
+ s22 -= carry22 * ((uint64_t) 1L << 21);
+
+ carry1 = (s1 + (int64_t) (1L << 20)) >> 21;
+ s2 += carry1;
+ s1 -= carry1 * ((uint64_t) 1L << 21);
+ carry3 = (s3 + (int64_t) (1L << 20)) >> 21;
+ s4 += carry3;
+ s3 -= carry3 * ((uint64_t) 1L << 21);
+ carry5 = (s5 + (int64_t) (1L << 20)) >> 21;
+ s6 += carry5;
+ s5 -= carry5 * ((uint64_t) 1L << 21);
+ carry7 = (s7 + (int64_t) (1L << 20)) >> 21;
+ s8 += carry7;
+ s7 -= carry7 * ((uint64_t) 1L << 21);
+ carry9 = (s9 + (int64_t) (1L << 20)) >> 21;
+ s10 += carry9;
+ s9 -= carry9 * ((uint64_t) 1L << 21);
+ carry11 = (s11 + (int64_t) (1L << 20)) >> 21;
+ s12 += carry11;
+ s11 -= carry11 * ((uint64_t) 1L << 21);
+ carry13 = (s13 + (int64_t) (1L << 20)) >> 21;
+ s14 += carry13;
+ s13 -= carry13 * ((uint64_t) 1L << 21);
+ carry15 = (s15 + (int64_t) (1L << 20)) >> 21;
+ s16 += carry15;
+ s15 -= carry15 * ((uint64_t) 1L << 21);
+ carry17 = (s17 + (int64_t) (1L << 20)) >> 21;
+ s18 += carry17;
+ s17 -= carry17 * ((uint64_t) 1L << 21);
+ carry19 = (s19 + (int64_t) (1L << 20)) >> 21;
+ s20 += carry19;
+ s19 -= carry19 * ((uint64_t) 1L << 21);
+ carry21 = (s21 + (int64_t) (1L << 20)) >> 21;
+ s22 += carry21;
+ s21 -= carry21 * ((uint64_t) 1L << 21);
+
+ s11 += s23 * 666643;
+ s12 += s23 * 470296;
+ s13 += s23 * 654183;
+ s14 -= s23 * 997805;
+ s15 += s23 * 136657;
+ s16 -= s23 * 683901;
+
+ s10 += s22 * 666643;
+ s11 += s22 * 470296;
+ s12 += s22 * 654183;
+ s13 -= s22 * 997805;
+ s14 += s22 * 136657;
+ s15 -= s22 * 683901;
+
+ s9 += s21 * 666643;
+ s10 += s21 * 470296;
+ s11 += s21 * 654183;
+ s12 -= s21 * 997805;
+ s13 += s21 * 136657;
+ s14 -= s21 * 683901;
+
+ s8 += s20 * 666643;
+ s9 += s20 * 470296;
+ s10 += s20 * 654183;
+ s11 -= s20 * 997805;
+ s12 += s20 * 136657;
+ s13 -= s20 * 683901;
+
+ s7 += s19 * 666643;
+ s8 += s19 * 470296;
+ s9 += s19 * 654183;
+ s10 -= s19 * 997805;
+ s11 += s19 * 136657;
+ s12 -= s19 * 683901;
+
+ s6 += s18 * 666643;
+ s7 += s18 * 470296;
+ s8 += s18 * 654183;
+ s9 -= s18 * 997805;
+ s10 += s18 * 136657;
+ s11 -= s18 * 683901;
+
+ carry6 = (s6 + (int64_t) (1L << 20)) >> 21;
+ s7 += carry6;
+ s6 -= carry6 * ((uint64_t) 1L << 21);
+ carry8 = (s8 + (int64_t) (1L << 20)) >> 21;
+ s9 += carry8;
+ s8 -= carry8 * ((uint64_t) 1L << 21);
+ carry10 = (s10 + (int64_t) (1L << 20)) >> 21;
+ s11 += carry10;
+ s10 -= carry10 * ((uint64_t) 1L << 21);
+ carry12 = (s12 + (int64_t) (1L << 20)) >> 21;
+ s13 += carry12;
+ s12 -= carry12 * ((uint64_t) 1L << 21);
+ carry14 = (s14 + (int64_t) (1L << 20)) >> 21;
+ s15 += carry14;
+ s14 -= carry14 * ((uint64_t) 1L << 21);
+ carry16 = (s16 + (int64_t) (1L << 20)) >> 21;
+ s17 += carry16;
+ s16 -= carry16 * ((uint64_t) 1L << 21);
+
+ carry7 = (s7 + (int64_t) (1L << 20)) >> 21;
+ s8 += carry7;
+ s7 -= carry7 * ((uint64_t) 1L << 21);
+ carry9 = (s9 + (int64_t) (1L << 20)) >> 21;
+ s10 += carry9;
+ s9 -= carry9 * ((uint64_t) 1L << 21);
+ carry11 = (s11 + (int64_t) (1L << 20)) >> 21;
+ s12 += carry11;
+ s11 -= carry11 * ((uint64_t) 1L << 21);
+ carry13 = (s13 + (int64_t) (1L << 20)) >> 21;
+ s14 += carry13;
+ s13 -= carry13 * ((uint64_t) 1L << 21);
+ carry15 = (s15 + (int64_t) (1L << 20)) >> 21;
+ s16 += carry15;
+ s15 -= carry15 * ((uint64_t) 1L << 21);
+
+ s5 += s17 * 666643;
+ s6 += s17 * 470296;
+ s7 += s17 * 654183;
+ s8 -= s17 * 997805;
+ s9 += s17 * 136657;
+ s10 -= s17 * 683901;
+
+ s4 += s16 * 666643;
+ s5 += s16 * 470296;
+ s6 += s16 * 654183;
+ s7 -= s16 * 997805;
+ s8 += s16 * 136657;
+ s9 -= s16 * 683901;
+
+ s3 += s15 * 666643;
+ s4 += s15 * 470296;
+ s5 += s15 * 654183;
+ s6 -= s15 * 997805;
+ s7 += s15 * 136657;
+ s8 -= s15 * 683901;
+
+ s2 += s14 * 666643;
+ s3 += s14 * 470296;
+ s4 += s14 * 654183;
+ s5 -= s14 * 997805;
+ s6 += s14 * 136657;
+ s7 -= s14 * 683901;
+
+ s1 += s13 * 666643;
+ s2 += s13 * 470296;
+ s3 += s13 * 654183;
+ s4 -= s13 * 997805;
+ s5 += s13 * 136657;
+ s6 -= s13 * 683901;
+
+ s0 += s12 * 666643;
+ s1 += s12 * 470296;
+ s2 += s12 * 654183;
+ s3 -= s12 * 997805;
+ s4 += s12 * 136657;
+ s5 -= s12 * 683901;
+ s12 = 0;
+
+ carry0 = (s0 + (int64_t) (1L << 20)) >> 21;
+ s1 += carry0;
+ s0 -= carry0 * ((uint64_t) 1L << 21);
+ carry2 = (s2 + (int64_t) (1L << 20)) >> 21;
+ s3 += carry2;
+ s2 -= carry2 * ((uint64_t) 1L << 21);
+ carry4 = (s4 + (int64_t) (1L << 20)) >> 21;
+ s5 += carry4;
+ s4 -= carry4 * ((uint64_t) 1L << 21);
+ carry6 = (s6 + (int64_t) (1L << 20)) >> 21;
+ s7 += carry6;
+ s6 -= carry6 * ((uint64_t) 1L << 21);
+ carry8 = (s8 + (int64_t) (1L << 20)) >> 21;
+ s9 += carry8;
+ s8 -= carry8 * ((uint64_t) 1L << 21);
+ carry10 = (s10 + (int64_t) (1L << 20)) >> 21;
+ s11 += carry10;
+ s10 -= carry10 * ((uint64_t) 1L << 21);
+
+ carry1 = (s1 + (int64_t) (1L << 20)) >> 21;
+ s2 += carry1;
+ s1 -= carry1 * ((uint64_t) 1L << 21);
+ carry3 = (s3 + (int64_t) (1L << 20)) >> 21;
+ s4 += carry3;
+ s3 -= carry3 * ((uint64_t) 1L << 21);
+ carry5 = (s5 + (int64_t) (1L << 20)) >> 21;
+ s6 += carry5;
+ s5 -= carry5 * ((uint64_t) 1L << 21);
+ carry7 = (s7 + (int64_t) (1L << 20)) >> 21;
+ s8 += carry7;
+ s7 -= carry7 * ((uint64_t) 1L << 21);
+ carry9 = (s9 + (int64_t) (1L << 20)) >> 21;
+ s10 += carry9;
+ s9 -= carry9 * ((uint64_t) 1L << 21);
+ carry11 = (s11 + (int64_t) (1L << 20)) >> 21;
+ s12 += carry11;
+ s11 -= carry11 * ((uint64_t) 1L << 21);
+
+ s0 += s12 * 666643;
+ s1 += s12 * 470296;
+ s2 += s12 * 654183;
+ s3 -= s12 * 997805;
+ s4 += s12 * 136657;
+ s5 -= s12 * 683901;
+ s12 = 0;
+
+ carry0 = s0 >> 21;
+ s1 += carry0;
+ s0 -= carry0 * ((uint64_t) 1L << 21);
+ carry1 = s1 >> 21;
+ s2 += carry1;
+ s1 -= carry1 * ((uint64_t) 1L << 21);
+ carry2 = s2 >> 21;
+ s3 += carry2;
+ s2 -= carry2 * ((uint64_t) 1L << 21);
+ carry3 = s3 >> 21;
+ s4 += carry3;
+ s3 -= carry3 * ((uint64_t) 1L << 21);
+ carry4 = s4 >> 21;
+ s5 += carry4;
+ s4 -= carry4 * ((uint64_t) 1L << 21);
+ carry5 = s5 >> 21;
+ s6 += carry5;
+ s5 -= carry5 * ((uint64_t) 1L << 21);
+ carry6 = s6 >> 21;
+ s7 += carry6;
+ s6 -= carry6 * ((uint64_t) 1L << 21);
+ carry7 = s7 >> 21;
+ s8 += carry7;
+ s7 -= carry7 * ((uint64_t) 1L << 21);
+ carry8 = s8 >> 21;
+ s9 += carry8;
+ s8 -= carry8 * ((uint64_t) 1L << 21);
+ carry9 = s9 >> 21;
+ s10 += carry9;
+ s9 -= carry9 * ((uint64_t) 1L << 21);
+ carry10 = s10 >> 21;
+ s11 += carry10;
+ s10 -= carry10 * ((uint64_t) 1L << 21);
+ carry11 = s11 >> 21;
+ s12 += carry11;
+ s11 -= carry11 * ((uint64_t) 1L << 21);
+
+ s0 += s12 * 666643;
+ s1 += s12 * 470296;
+ s2 += s12 * 654183;
+ s3 -= s12 * 997805;
+ s4 += s12 * 136657;
+ s5 -= s12 * 683901;
+
+ carry0 = s0 >> 21;
+ s1 += carry0;
+ s0 -= carry0 * ((uint64_t) 1L << 21);
+ carry1 = s1 >> 21;
+ s2 += carry1;
+ s1 -= carry1 * ((uint64_t) 1L << 21);
+ carry2 = s2 >> 21;
+ s3 += carry2;
+ s2 -= carry2 * ((uint64_t) 1L << 21);
+ carry3 = s3 >> 21;
+ s4 += carry3;
+ s3 -= carry3 * ((uint64_t) 1L << 21);
+ carry4 = s4 >> 21;
+ s5 += carry4;
+ s4 -= carry4 * ((uint64_t) 1L << 21);
+ carry5 = s5 >> 21;
+ s6 += carry5;
+ s5 -= carry5 * ((uint64_t) 1L << 21);
+ carry6 = s6 >> 21;
+ s7 += carry6;
+ s6 -= carry6 * ((uint64_t) 1L << 21);
+ carry7 = s7 >> 21;
+ s8 += carry7;
+ s7 -= carry7 * ((uint64_t) 1L << 21);
+ carry8 = s8 >> 21;
+ s9 += carry8;
+ s8 -= carry8 * ((uint64_t) 1L << 21);
+ carry9 = s9 >> 21;
+ s10 += carry9;
+ s9 -= carry9 * ((uint64_t) 1L << 21);
+ carry10 = s10 >> 21;
+ s11 += carry10;
+ s10 -= carry10 * ((uint64_t) 1L << 21);
+
+ s[0] = s0 >> 0;
+ s[1] = s0 >> 8;
+ s[2] = (s0 >> 16) | (s1 * ((uint64_t) 1 << 5));
+ s[3] = s1 >> 3;
+ s[4] = s1 >> 11;
+ s[5] = (s1 >> 19) | (s2 * ((uint64_t) 1 << 2));
+ s[6] = s2 >> 6;
+ s[7] = (s2 >> 14) | (s3 * ((uint64_t) 1 << 7));
+ s[8] = s3 >> 1;
+ s[9] = s3 >> 9;
+ s[10] = (s3 >> 17) | (s4 * ((uint64_t) 1 << 4));
+ s[11] = s4 >> 4;
+ s[12] = s4 >> 12;
+ s[13] = (s4 >> 20) | (s5 * ((uint64_t) 1 << 1));
+ s[14] = s5 >> 7;
+ s[15] = (s5 >> 15) | (s6 * ((uint64_t) 1 << 6));
+ s[16] = s6 >> 2;
+ s[17] = s6 >> 10;
+ s[18] = (s6 >> 18) | (s7 * ((uint64_t) 1 << 3));
+ s[19] = s7 >> 5;
+ s[20] = s7 >> 13;
+ s[21] = s8 >> 0;
+ s[22] = s8 >> 8;
+ s[23] = (s8 >> 16) | (s9 * ((uint64_t) 1 << 5));
+ s[24] = s9 >> 3;
+ s[25] = s9 >> 11;
+ s[26] = (s9 >> 19) | (s10 * ((uint64_t) 1 << 2));
+ s[27] = s10 >> 6;
+ s[28] = (s10 >> 14) | (s11 * ((uint64_t) 1 << 7));
+ s[29] = s11 >> 1;
+ s[30] = s11 >> 9;
+ s[31] = s11 >> 17;
+}
+
+/*
+ Input:
+ a[0]+256*a[1]+...+256^31*a[31] = a
+ b[0]+256*b[1]+...+256^31*b[31] = b
+ c[0]+256*c[1]+...+256^31*c[31] = c
+ *
+ Output:
+ s[0]+256*s[1]+...+256^31*s[31] = (ab+c) mod l
+ where l = 2^252 + 27742317777372353535851937790883648493.
+ */
+
+void
+sc25519_muladd(unsigned char s[32], const unsigned char a[32],
+ const unsigned char b[32], const unsigned char c[32])
+{
+ int64_t a0 = 2097151 & load_3(a);
+ int64_t a1 = 2097151 & (load_4(a + 2) >> 5);
+ int64_t a2 = 2097151 & (load_3(a + 5) >> 2);
+ int64_t a3 = 2097151 & (load_4(a + 7) >> 7);
+ int64_t a4 = 2097151 & (load_4(a + 10) >> 4);
+ int64_t a5 = 2097151 & (load_3(a + 13) >> 1);
+ int64_t a6 = 2097151 & (load_4(a + 15) >> 6);
+ int64_t a7 = 2097151 & (load_3(a + 18) >> 3);
+ int64_t a8 = 2097151 & load_3(a + 21);
+ int64_t a9 = 2097151 & (load_4(a + 23) >> 5);
+ int64_t a10 = 2097151 & (load_3(a + 26) >> 2);
+ int64_t a11 = (load_4(a + 28) >> 7);
+
+ int64_t b0 = 2097151 & load_3(b);
+ int64_t b1 = 2097151 & (load_4(b + 2) >> 5);
+ int64_t b2 = 2097151 & (load_3(b + 5) >> 2);
+ int64_t b3 = 2097151 & (load_4(b + 7) >> 7);
+ int64_t b4 = 2097151 & (load_4(b + 10) >> 4);
+ int64_t b5 = 2097151 & (load_3(b + 13) >> 1);
+ int64_t b6 = 2097151 & (load_4(b + 15) >> 6);
+ int64_t b7 = 2097151 & (load_3(b + 18) >> 3);
+ int64_t b8 = 2097151 & load_3(b + 21);
+ int64_t b9 = 2097151 & (load_4(b + 23) >> 5);
+ int64_t b10 = 2097151 & (load_3(b + 26) >> 2);
+ int64_t b11 = (load_4(b + 28) >> 7);
+
+ int64_t c0 = 2097151 & load_3(c);
+ int64_t c1 = 2097151 & (load_4(c + 2) >> 5);
+ int64_t c2 = 2097151 & (load_3(c + 5) >> 2);
+ int64_t c3 = 2097151 & (load_4(c + 7) >> 7);
+ int64_t c4 = 2097151 & (load_4(c + 10) >> 4);
+ int64_t c5 = 2097151 & (load_3(c + 13) >> 1);
+ int64_t c6 = 2097151 & (load_4(c + 15) >> 6);
+ int64_t c7 = 2097151 & (load_3(c + 18) >> 3);
+ int64_t c8 = 2097151 & load_3(c + 21);
+ int64_t c9 = 2097151 & (load_4(c + 23) >> 5);
+ int64_t c10 = 2097151 & (load_3(c + 26) >> 2);
+ int64_t c11 = (load_4(c + 28) >> 7);
+
+ int64_t s0;
+ int64_t s1;
+ int64_t s2;
+ int64_t s3;
+ int64_t s4;
+ int64_t s5;
+ int64_t s6;
+ int64_t s7;
+ int64_t s8;
+ int64_t s9;
+ int64_t s10;
+ int64_t s11;
+ int64_t s12;
+ int64_t s13;
+ int64_t s14;
+ int64_t s15;
+ int64_t s16;
+ int64_t s17;
+ int64_t s18;
+ int64_t s19;
+ int64_t s20;
+ int64_t s21;
+ int64_t s22;
+ int64_t s23;
+
+ int64_t carry0;
+ int64_t carry1;
+ int64_t carry2;
+ int64_t carry3;
+ int64_t carry4;
+ int64_t carry5;
+ int64_t carry6;
+ int64_t carry7;
+ int64_t carry8;
+ int64_t carry9;
+ int64_t carry10;
+ int64_t carry11;
+ int64_t carry12;
+ int64_t carry13;
+ int64_t carry14;
+ int64_t carry15;
+ int64_t carry16;
+ int64_t carry17;
+ int64_t carry18;
+ int64_t carry19;
+ int64_t carry20;
+ int64_t carry21;
+ int64_t carry22;
+
+ s0 = c0 + a0 * b0;
+ s1 = c1 + a0 * b1 + a1 * b0;
+ s2 = c2 + a0 * b2 + a1 * b1 + a2 * b0;
+ s3 = c3 + a0 * b3 + a1 * b2 + a2 * b1 + a3 * b0;
+ s4 = c4 + a0 * b4 + a1 * b3 + a2 * b2 + a3 * b1 + a4 * b0;
+ s5 = c5 + a0 * b5 + a1 * b4 + a2 * b3 + a3 * b2 + a4 * b1 + a5 * b0;
+ s6 = c6 + a0 * b6 + a1 * b5 + a2 * b4 + a3 * b3 + a4 * b2 + a5 * b1 +
+ a6 * b0;
+ s7 = c7 + a0 * b7 + a1 * b6 + a2 * b5 + a3 * b4 + a4 * b3 + a5 * b2 +
+ a6 * b1 + a7 * b0;
+ s8 = c8 + a0 * b8 + a1 * b7 + a2 * b6 + a3 * b5 + a4 * b4 + a5 * b3 +
+ a6 * b2 + a7 * b1 + a8 * b0;
+ s9 = c9 + a0 * b9 + a1 * b8 + a2 * b7 + a3 * b6 + a4 * b5 + a5 * b4 +
+ a6 * b3 + a7 * b2 + a8 * b1 + a9 * b0;
+ s10 = c10 + a0 * b10 + a1 * b9 + a2 * b8 + a3 * b7 + a4 * b6 + a5 * b5 +
+ a6 * b4 + a7 * b3 + a8 * b2 + a9 * b1 + a10 * b0;
+ s11 = c11 + a0 * b11 + a1 * b10 + a2 * b9 + a3 * b8 + a4 * b7 + a5 * b6 +
+ a6 * b5 + a7 * b4 + a8 * b3 + a9 * b2 + a10 * b1 + a11 * b0;
+ s12 = a1 * b11 + a2 * b10 + a3 * b9 + a4 * b8 + a5 * b7 + a6 * b6 +
+ a7 * b5 + a8 * b4 + a9 * b3 + a10 * b2 + a11 * b1;
+ s13 = a2 * b11 + a3 * b10 + a4 * b9 + a5 * b8 + a6 * b7 + a7 * b6 +
+ a8 * b5 + a9 * b4 + a10 * b3 + a11 * b2;
+ s14 = a3 * b11 + a4 * b10 + a5 * b9 + a6 * b8 + a7 * b7 + a8 * b6 +
+ a9 * b5 + a10 * b4 + a11 * b3;
+ s15 = a4 * b11 + a5 * b10 + a6 * b9 + a7 * b8 + a8 * b7 + a9 * b6 +
+ a10 * b5 + a11 * b4;
+ s16 =
+ a5 * b11 + a6 * b10 + a7 * b9 + a8 * b8 + a9 * b7 + a10 * b6 + a11 * b5;
+ s17 = a6 * b11 + a7 * b10 + a8 * b9 + a9 * b8 + a10 * b7 + a11 * b6;
+ s18 = a7 * b11 + a8 * b10 + a9 * b9 + a10 * b8 + a11 * b7;
+ s19 = a8 * b11 + a9 * b10 + a10 * b9 + a11 * b8;
+ s20 = a9 * b11 + a10 * b10 + a11 * b9;
+ s21 = a10 * b11 + a11 * b10;
+ s22 = a11 * b11;
+ s23 = 0;
+
+ carry0 = (s0 + (int64_t) (1L << 20)) >> 21;
+ s1 += carry0;
+ s0 -= carry0 * ((uint64_t) 1L << 21);
+ carry2 = (s2 + (int64_t) (1L << 20)) >> 21;
+ s3 += carry2;
+ s2 -= carry2 * ((uint64_t) 1L << 21);
+ carry4 = (s4 + (int64_t) (1L << 20)) >> 21;
+ s5 += carry4;
+ s4 -= carry4 * ((uint64_t) 1L << 21);
+ carry6 = (s6 + (int64_t) (1L << 20)) >> 21;
+ s7 += carry6;
+ s6 -= carry6 * ((uint64_t) 1L << 21);
+ carry8 = (s8 + (int64_t) (1L << 20)) >> 21;
+ s9 += carry8;
+ s8 -= carry8 * ((uint64_t) 1L << 21);
+ carry10 = (s10 + (int64_t) (1L << 20)) >> 21;
+ s11 += carry10;
+ s10 -= carry10 * ((uint64_t) 1L << 21);
+ carry12 = (s12 + (int64_t) (1L << 20)) >> 21;
+ s13 += carry12;
+ s12 -= carry12 * ((uint64_t) 1L << 21);
+ carry14 = (s14 + (int64_t) (1L << 20)) >> 21;
+ s15 += carry14;
+ s14 -= carry14 * ((uint64_t) 1L << 21);
+ carry16 = (s16 + (int64_t) (1L << 20)) >> 21;
+ s17 += carry16;
+ s16 -= carry16 * ((uint64_t) 1L << 21);
+ carry18 = (s18 + (int64_t) (1L << 20)) >> 21;
+ s19 += carry18;
+ s18 -= carry18 * ((uint64_t) 1L << 21);
+ carry20 = (s20 + (int64_t) (1L << 20)) >> 21;
+ s21 += carry20;
+ s20 -= carry20 * ((uint64_t) 1L << 21);
+ carry22 = (s22 + (int64_t) (1L << 20)) >> 21;
+ s23 += carry22;
+ s22 -= carry22 * ((uint64_t) 1L << 21);
+
+ carry1 = (s1 + (int64_t) (1L << 20)) >> 21;
+ s2 += carry1;
+ s1 -= carry1 * ((uint64_t) 1L << 21);
+ carry3 = (s3 + (int64_t) (1L << 20)) >> 21;
+ s4 += carry3;
+ s3 -= carry3 * ((uint64_t) 1L << 21);
+ carry5 = (s5 + (int64_t) (1L << 20)) >> 21;
+ s6 += carry5;
+ s5 -= carry5 * ((uint64_t) 1L << 21);
+ carry7 = (s7 + (int64_t) (1L << 20)) >> 21;
+ s8 += carry7;
+ s7 -= carry7 * ((uint64_t) 1L << 21);
+ carry9 = (s9 + (int64_t) (1L << 20)) >> 21;
+ s10 += carry9;
+ s9 -= carry9 * ((uint64_t) 1L << 21);
+ carry11 = (s11 + (int64_t) (1L << 20)) >> 21;
+ s12 += carry11;
+ s11 -= carry11 * ((uint64_t) 1L << 21);
+ carry13 = (s13 + (int64_t) (1L << 20)) >> 21;
+ s14 += carry13;
+ s13 -= carry13 * ((uint64_t) 1L << 21);
+ carry15 = (s15 + (int64_t) (1L << 20)) >> 21;
+ s16 += carry15;
+ s15 -= carry15 * ((uint64_t) 1L << 21);
+ carry17 = (s17 + (int64_t) (1L << 20)) >> 21;
+ s18 += carry17;
+ s17 -= carry17 * ((uint64_t) 1L << 21);
+ carry19 = (s19 + (int64_t) (1L << 20)) >> 21;
+ s20 += carry19;
+ s19 -= carry19 * ((uint64_t) 1L << 21);
+ carry21 = (s21 + (int64_t) (1L << 20)) >> 21;
+ s22 += carry21;
+ s21 -= carry21 * ((uint64_t) 1L << 21);
+
+ s11 += s23 * 666643;
+ s12 += s23 * 470296;
+ s13 += s23 * 654183;
+ s14 -= s23 * 997805;
+ s15 += s23 * 136657;
+ s16 -= s23 * 683901;
+
+ s10 += s22 * 666643;
+ s11 += s22 * 470296;
+ s12 += s22 * 654183;
+ s13 -= s22 * 997805;
+ s14 += s22 * 136657;
+ s15 -= s22 * 683901;
+
+ s9 += s21 * 666643;
+ s10 += s21 * 470296;
+ s11 += s21 * 654183;
+ s12 -= s21 * 997805;
+ s13 += s21 * 136657;
+ s14 -= s21 * 683901;
+
+ s8 += s20 * 666643;
+ s9 += s20 * 470296;
+ s10 += s20 * 654183;
+ s11 -= s20 * 997805;
+ s12 += s20 * 136657;
+ s13 -= s20 * 683901;
+
+ s7 += s19 * 666643;
+ s8 += s19 * 470296;
+ s9 += s19 * 654183;
+ s10 -= s19 * 997805;
+ s11 += s19 * 136657;
+ s12 -= s19 * 683901;
+
+ s6 += s18 * 666643;
+ s7 += s18 * 470296;
+ s8 += s18 * 654183;
+ s9 -= s18 * 997805;
+ s10 += s18 * 136657;
+ s11 -= s18 * 683901;
+
+ carry6 = (s6 + (int64_t) (1L << 20)) >> 21;
+ s7 += carry6;
+ s6 -= carry6 * ((uint64_t) 1L << 21);
+ carry8 = (s8 + (int64_t) (1L << 20)) >> 21;
+ s9 += carry8;
+ s8 -= carry8 * ((uint64_t) 1L << 21);
+ carry10 = (s10 + (int64_t) (1L << 20)) >> 21;
+ s11 += carry10;
+ s10 -= carry10 * ((uint64_t) 1L << 21);
+ carry12 = (s12 + (int64_t) (1L << 20)) >> 21;
+ s13 += carry12;
+ s12 -= carry12 * ((uint64_t) 1L << 21);
+ carry14 = (s14 + (int64_t) (1L << 20)) >> 21;
+ s15 += carry14;
+ s14 -= carry14 * ((uint64_t) 1L << 21);
+ carry16 = (s16 + (int64_t) (1L << 20)) >> 21;
+ s17 += carry16;
+ s16 -= carry16 * ((uint64_t) 1L << 21);
+
+ carry7 = (s7 + (int64_t) (1L << 20)) >> 21;
+ s8 += carry7;
+ s7 -= carry7 * ((uint64_t) 1L << 21);
+ carry9 = (s9 + (int64_t) (1L << 20)) >> 21;
+ s10 += carry9;
+ s9 -= carry9 * ((uint64_t) 1L << 21);
+ carry11 = (s11 + (int64_t) (1L << 20)) >> 21;
+ s12 += carry11;
+ s11 -= carry11 * ((uint64_t) 1L << 21);
+ carry13 = (s13 + (int64_t) (1L << 20)) >> 21;
+ s14 += carry13;
+ s13 -= carry13 * ((uint64_t) 1L << 21);
+ carry15 = (s15 + (int64_t) (1L << 20)) >> 21;
+ s16 += carry15;
+ s15 -= carry15 * ((uint64_t) 1L << 21);
+
+ s5 += s17 * 666643;
+ s6 += s17 * 470296;
+ s7 += s17 * 654183;
+ s8 -= s17 * 997805;
+ s9 += s17 * 136657;
+ s10 -= s17 * 683901;
+
+ s4 += s16 * 666643;
+ s5 += s16 * 470296;
+ s6 += s16 * 654183;
+ s7 -= s16 * 997805;
+ s8 += s16 * 136657;
+ s9 -= s16 * 683901;
+
+ s3 += s15 * 666643;
+ s4 += s15 * 470296;
+ s5 += s15 * 654183;
+ s6 -= s15 * 997805;
+ s7 += s15 * 136657;
+ s8 -= s15 * 683901;
+
+ s2 += s14 * 666643;
+ s3 += s14 * 470296;
+ s4 += s14 * 654183;
+ s5 -= s14 * 997805;
+ s6 += s14 * 136657;
+ s7 -= s14 * 683901;
+
+ s1 += s13 * 666643;
+ s2 += s13 * 470296;
+ s3 += s13 * 654183;
+ s4 -= s13 * 997805;
+ s5 += s13 * 136657;
+ s6 -= s13 * 683901;
+
+ s0 += s12 * 666643;
+ s1 += s12 * 470296;
+ s2 += s12 * 654183;
+ s3 -= s12 * 997805;
+ s4 += s12 * 136657;
+ s5 -= s12 * 683901;
+ s12 = 0;
+
+ carry0 = (s0 + (int64_t) (1L << 20)) >> 21;
+ s1 += carry0;
+ s0 -= carry0 * ((uint64_t) 1L << 21);
+ carry2 = (s2 + (int64_t) (1L << 20)) >> 21;
+ s3 += carry2;
+ s2 -= carry2 * ((uint64_t) 1L << 21);
+ carry4 = (s4 + (int64_t) (1L << 20)) >> 21;
+ s5 += carry4;
+ s4 -= carry4 * ((uint64_t) 1L << 21);
+ carry6 = (s6 + (int64_t) (1L << 20)) >> 21;
+ s7 += carry6;
+ s6 -= carry6 * ((uint64_t) 1L << 21);
+ carry8 = (s8 + (int64_t) (1L << 20)) >> 21;
+ s9 += carry8;
+ s8 -= carry8 * ((uint64_t) 1L << 21);
+ carry10 = (s10 + (int64_t) (1L << 20)) >> 21;
+ s11 += carry10;
+ s10 -= carry10 * ((uint64_t) 1L << 21);
+
+ carry1 = (s1 + (int64_t) (1L << 20)) >> 21;
+ s2 += carry1;
+ s1 -= carry1 * ((uint64_t) 1L << 21);
+ carry3 = (s3 + (int64_t) (1L << 20)) >> 21;
+ s4 += carry3;
+ s3 -= carry3 * ((uint64_t) 1L << 21);
+ carry5 = (s5 + (int64_t) (1L << 20)) >> 21;
+ s6 += carry5;
+ s5 -= carry5 * ((uint64_t) 1L << 21);
+ carry7 = (s7 + (int64_t) (1L << 20)) >> 21;
+ s8 += carry7;
+ s7 -= carry7 * ((uint64_t) 1L << 21);
+ carry9 = (s9 + (int64_t) (1L << 20)) >> 21;
+ s10 += carry9;
+ s9 -= carry9 * ((uint64_t) 1L << 21);
+ carry11 = (s11 + (int64_t) (1L << 20)) >> 21;
+ s12 += carry11;
+ s11 -= carry11 * ((uint64_t) 1L << 21);
+
+ s0 += s12 * 666643;
+ s1 += s12 * 470296;
+ s2 += s12 * 654183;
+ s3 -= s12 * 997805;
+ s4 += s12 * 136657;
+ s5 -= s12 * 683901;
+ s12 = 0;
+
+ carry0 = s0 >> 21;
+ s1 += carry0;
+ s0 -= carry0 * ((uint64_t) 1L << 21);
+ carry1 = s1 >> 21;
+ s2 += carry1;
+ s1 -= carry1 * ((uint64_t) 1L << 21);
+ carry2 = s2 >> 21;
+ s3 += carry2;
+ s2 -= carry2 * ((uint64_t) 1L << 21);
+ carry3 = s3 >> 21;
+ s4 += carry3;
+ s3 -= carry3 * ((uint64_t) 1L << 21);
+ carry4 = s4 >> 21;
+ s5 += carry4;
+ s4 -= carry4 * ((uint64_t) 1L << 21);
+ carry5 = s5 >> 21;
+ s6 += carry5;
+ s5 -= carry5 * ((uint64_t) 1L << 21);
+ carry6 = s6 >> 21;
+ s7 += carry6;
+ s6 -= carry6 * ((uint64_t) 1L << 21);
+ carry7 = s7 >> 21;
+ s8 += carry7;
+ s7 -= carry7 * ((uint64_t) 1L << 21);
+ carry8 = s8 >> 21;
+ s9 += carry8;
+ s8 -= carry8 * ((uint64_t) 1L << 21);
+ carry9 = s9 >> 21;
+ s10 += carry9;
+ s9 -= carry9 * ((uint64_t) 1L << 21);
+ carry10 = s10 >> 21;
+ s11 += carry10;
+ s10 -= carry10 * ((uint64_t) 1L << 21);
+ carry11 = s11 >> 21;
+ s12 += carry11;
+ s11 -= carry11 * ((uint64_t) 1L << 21);
+
+ s0 += s12 * 666643;
+ s1 += s12 * 470296;
+ s2 += s12 * 654183;
+ s3 -= s12 * 997805;
+ s4 += s12 * 136657;
+ s5 -= s12 * 683901;
+
+ carry0 = s0 >> 21;
+ s1 += carry0;
+ s0 -= carry0 * ((uint64_t) 1L << 21);
+ carry1 = s1 >> 21;
+ s2 += carry1;
+ s1 -= carry1 * ((uint64_t) 1L << 21);
+ carry2 = s2 >> 21;
+ s3 += carry2;
+ s2 -= carry2 * ((uint64_t) 1L << 21);
+ carry3 = s3 >> 21;
+ s4 += carry3;
+ s3 -= carry3 * ((uint64_t) 1L << 21);
+ carry4 = s4 >> 21;
+ s5 += carry4;
+ s4 -= carry4 * ((uint64_t) 1L << 21);
+ carry5 = s5 >> 21;
+ s6 += carry5;
+ s5 -= carry5 * ((uint64_t) 1L << 21);
+ carry6 = s6 >> 21;
+ s7 += carry6;
+ s6 -= carry6 * ((uint64_t) 1L << 21);
+ carry7 = s7 >> 21;
+ s8 += carry7;
+ s7 -= carry7 * ((uint64_t) 1L << 21);
+ carry8 = s8 >> 21;
+ s9 += carry8;
+ s8 -= carry8 * ((uint64_t) 1L << 21);
+ carry9 = s9 >> 21;
+ s10 += carry9;
+ s9 -= carry9 * ((uint64_t) 1L << 21);
+ carry10 = s10 >> 21;
+ s11 += carry10;
+ s10 -= carry10 * ((uint64_t) 1L << 21);
+
+ s[0] = s0 >> 0;
+ s[1] = s0 >> 8;
+ s[2] = (s0 >> 16) | (s1 * ((uint64_t) 1 << 5));
+ s[3] = s1 >> 3;
+ s[4] = s1 >> 11;
+ s[5] = (s1 >> 19) | (s2 * ((uint64_t) 1 << 2));
+ s[6] = s2 >> 6;
+ s[7] = (s2 >> 14) | (s3 * ((uint64_t) 1 << 7));
+ s[8] = s3 >> 1;
+ s[9] = s3 >> 9;
+ s[10] = (s3 >> 17) | (s4 * ((uint64_t) 1 << 4));
+ s[11] = s4 >> 4;
+ s[12] = s4 >> 12;
+ s[13] = (s4 >> 20) | (s5 * ((uint64_t) 1 << 1));
+ s[14] = s5 >> 7;
+ s[15] = (s5 >> 15) | (s6 * ((uint64_t) 1 << 6));
+ s[16] = s6 >> 2;
+ s[17] = s6 >> 10;
+ s[18] = (s6 >> 18) | (s7 * ((uint64_t) 1 << 3));
+ s[19] = s7 >> 5;
+ s[20] = s7 >> 13;
+ s[21] = s8 >> 0;
+ s[22] = s8 >> 8;
+ s[23] = (s8 >> 16) | (s9 * ((uint64_t) 1 << 5));
+ s[24] = s9 >> 3;
+ s[25] = s9 >> 11;
+ s[26] = (s9 >> 19) | (s10 * ((uint64_t) 1 << 2));
+ s[27] = s10 >> 6;
+ s[28] = (s10 >> 14) | (s11 * ((uint64_t) 1 << 7));
+ s[29] = s11 >> 1;
+ s[30] = s11 >> 9;
+ s[31] = s11 >> 17;
+}
+
+/*
+ Input:
+ a[0]+256*a[1]+...+256^31*a[31] = a
+ *
+ Output:
+ s[0]+256*s[1]+...+256^31*s[31] = a^2 mod l
+ where l = 2^252 + 27742317777372353535851937790883648493.
+ */
+
+static inline void
+sc25519_sq(unsigned char *s, const unsigned char *a)
+{
+ sc25519_mul(s, a, a);
+}
+
+/*
+ Input:
+ s[0]+256*a[1]+...+256^31*a[31] = a
+ n
+ *
+ Output:
+ s[0]+256*s[1]+...+256^31*s[31] = x * s^(s^n) mod l
+ where l = 2^252 + 27742317777372353535851937790883648493.
+ Overwrites s in place.
+ */
+
+static inline void
+sc25519_sqmul(unsigned char s[32], const int n, const unsigned char a[32])
+{
+ int i;
+
+ for (i = 0; i < n; i++) {
+ sc25519_sq(s, s);
+ }
+ sc25519_mul(s, s, a);
+}
+
+void
+sc25519_invert(unsigned char recip[32], const unsigned char s[32])
+{
+ unsigned char _10[32], _100[32], _11[32], _101[32], _111[32],
+ _1001[32], _1011[32], _1111[32];
+
+ sc25519_sq(_10, s);
+ sc25519_sq(_100, _10);
+ sc25519_mul(_11, _10, s);
+ sc25519_mul(_101, _10, _11);
+ sc25519_mul(_111, _10, _101);
+ sc25519_mul(_1001, _10, _111);
+ sc25519_mul(_1011, _10, _1001);
+ sc25519_mul(_1111, _100, _1011);
+ sc25519_mul(recip, _1111, s);
+
+ sc25519_sqmul(recip, 123 + 3, _101);
+ sc25519_sqmul(recip, 2 + 2, _11);
+ sc25519_sqmul(recip, 1 + 4, _1111);
+ sc25519_sqmul(recip, 1 + 4, _1111);
+ sc25519_sqmul(recip, 4, _1001);
+ sc25519_sqmul(recip, 2, _11);
+ sc25519_sqmul(recip, 1 + 4, _1111);
+ sc25519_sqmul(recip, 1 + 3, _101);
+ sc25519_sqmul(recip, 3 + 3, _101);
+ sc25519_sqmul(recip, 3, _111);
+ sc25519_sqmul(recip, 1 + 4, _1111);
+ sc25519_sqmul(recip, 2 + 3, _111);
+ sc25519_sqmul(recip, 2 + 2, _11);
+ sc25519_sqmul(recip, 1 + 4, _1011);
+ sc25519_sqmul(recip, 2 + 4, _1011);
+ sc25519_sqmul(recip, 6 + 4, _1001);
+ sc25519_sqmul(recip, 2 + 2, _11);
+ sc25519_sqmul(recip, 3 + 2, _11);
+ sc25519_sqmul(recip, 3 + 2, _11);
+ sc25519_sqmul(recip, 1 + 4, _1001);
+ sc25519_sqmul(recip, 1 + 3, _111);
+ sc25519_sqmul(recip, 2 + 4, _1111);
+ sc25519_sqmul(recip, 1 + 4, _1011);
+ sc25519_sqmul(recip, 3, _101);
+ sc25519_sqmul(recip, 2 + 4, _1111);
+ sc25519_sqmul(recip, 3, _101);
+ sc25519_sqmul(recip, 1 + 2, _11);
+}
+
+/*
+ Input:
+ s[0]+256*s[1]+...+256^63*s[63] = s
+ *
+ Output:
+ s[0]+256*s[1]+...+256^31*s[31] = s mod l
+ where l = 2^252 + 27742317777372353535851937790883648493.
+ Overwrites s in place.
+ */
+
+void
+sc25519_reduce(unsigned char s[64])
+{
+ int64_t s0 = 2097151 & load_3(s);
+ int64_t s1 = 2097151 & (load_4(s + 2) >> 5);
+ int64_t s2 = 2097151 & (load_3(s + 5) >> 2);
+ int64_t s3 = 2097151 & (load_4(s + 7) >> 7);
+ int64_t s4 = 2097151 & (load_4(s + 10) >> 4);
+ int64_t s5 = 2097151 & (load_3(s + 13) >> 1);
+ int64_t s6 = 2097151 & (load_4(s + 15) >> 6);
+ int64_t s7 = 2097151 & (load_3(s + 18) >> 3);
+ int64_t s8 = 2097151 & load_3(s + 21);
+ int64_t s9 = 2097151 & (load_4(s + 23) >> 5);
+ int64_t s10 = 2097151 & (load_3(s + 26) >> 2);
+ int64_t s11 = 2097151 & (load_4(s + 28) >> 7);
+ int64_t s12 = 2097151 & (load_4(s + 31) >> 4);
+ int64_t s13 = 2097151 & (load_3(s + 34) >> 1);
+ int64_t s14 = 2097151 & (load_4(s + 36) >> 6);
+ int64_t s15 = 2097151 & (load_3(s + 39) >> 3);
+ int64_t s16 = 2097151 & load_3(s + 42);
+ int64_t s17 = 2097151 & (load_4(s + 44) >> 5);
+ int64_t s18 = 2097151 & (load_3(s + 47) >> 2);
+ int64_t s19 = 2097151 & (load_4(s + 49) >> 7);
+ int64_t s20 = 2097151 & (load_4(s + 52) >> 4);
+ int64_t s21 = 2097151 & (load_3(s + 55) >> 1);
+ int64_t s22 = 2097151 & (load_4(s + 57) >> 6);
+ int64_t s23 = (load_4(s + 60) >> 3);
+
+ int64_t carry0;
+ int64_t carry1;
+ int64_t carry2;
+ int64_t carry3;
+ int64_t carry4;
+ int64_t carry5;
+ int64_t carry6;
+ int64_t carry7;
+ int64_t carry8;
+ int64_t carry9;
+ int64_t carry10;
+ int64_t carry11;
+ int64_t carry12;
+ int64_t carry13;
+ int64_t carry14;
+ int64_t carry15;
+ int64_t carry16;
+
+ s11 += s23 * 666643;
+ s12 += s23 * 470296;
+ s13 += s23 * 654183;
+ s14 -= s23 * 997805;
+ s15 += s23 * 136657;
+ s16 -= s23 * 683901;
+
+ s10 += s22 * 666643;
+ s11 += s22 * 470296;
+ s12 += s22 * 654183;
+ s13 -= s22 * 997805;
+ s14 += s22 * 136657;
+ s15 -= s22 * 683901;
+
+ s9 += s21 * 666643;
+ s10 += s21 * 470296;
+ s11 += s21 * 654183;
+ s12 -= s21 * 997805;
+ s13 += s21 * 136657;
+ s14 -= s21 * 683901;
+
+ s8 += s20 * 666643;
+ s9 += s20 * 470296;
+ s10 += s20 * 654183;
+ s11 -= s20 * 997805;
+ s12 += s20 * 136657;
+ s13 -= s20 * 683901;
+
+ s7 += s19 * 666643;
+ s8 += s19 * 470296;
+ s9 += s19 * 654183;
+ s10 -= s19 * 997805;
+ s11 += s19 * 136657;
+ s12 -= s19 * 683901;
+
+ s6 += s18 * 666643;
+ s7 += s18 * 470296;
+ s8 += s18 * 654183;
+ s9 -= s18 * 997805;
+ s10 += s18 * 136657;
+ s11 -= s18 * 683901;
+
+ carry6 = (s6 + (int64_t) (1L << 20)) >> 21;
+ s7 += carry6;
+ s6 -= carry6 * ((uint64_t) 1L << 21);
+ carry8 = (s8 + (int64_t) (1L << 20)) >> 21;
+ s9 += carry8;
+ s8 -= carry8 * ((uint64_t) 1L << 21);
+ carry10 = (s10 + (int64_t) (1L << 20)) >> 21;
+ s11 += carry10;
+ s10 -= carry10 * ((uint64_t) 1L << 21);
+ carry12 = (s12 + (int64_t) (1L << 20)) >> 21;
+ s13 += carry12;
+ s12 -= carry12 * ((uint64_t) 1L << 21);
+ carry14 = (s14 + (int64_t) (1L << 20)) >> 21;
+ s15 += carry14;
+ s14 -= carry14 * ((uint64_t) 1L << 21);
+ carry16 = (s16 + (int64_t) (1L << 20)) >> 21;
+ s17 += carry16;
+ s16 -= carry16 * ((uint64_t) 1L << 21);
+
+ carry7 = (s7 + (int64_t) (1L << 20)) >> 21;
+ s8 += carry7;
+ s7 -= carry7 * ((uint64_t) 1L << 21);
+ carry9 = (s9 + (int64_t) (1L << 20)) >> 21;
+ s10 += carry9;
+ s9 -= carry9 * ((uint64_t) 1L << 21);
+ carry11 = (s11 + (int64_t) (1L << 20)) >> 21;
+ s12 += carry11;
+ s11 -= carry11 * ((uint64_t) 1L << 21);
+ carry13 = (s13 + (int64_t) (1L << 20)) >> 21;
+ s14 += carry13;
+ s13 -= carry13 * ((uint64_t) 1L << 21);
+ carry15 = (s15 + (int64_t) (1L << 20)) >> 21;
+ s16 += carry15;
+ s15 -= carry15 * ((uint64_t) 1L << 21);
+
+ s5 += s17 * 666643;
+ s6 += s17 * 470296;
+ s7 += s17 * 654183;
+ s8 -= s17 * 997805;
+ s9 += s17 * 136657;
+ s10 -= s17 * 683901;
+
+ s4 += s16 * 666643;
+ s5 += s16 * 470296;
+ s6 += s16 * 654183;
+ s7 -= s16 * 997805;
+ s8 += s16 * 136657;
+ s9 -= s16 * 683901;
+
+ s3 += s15 * 666643;
+ s4 += s15 * 470296;
+ s5 += s15 * 654183;
+ s6 -= s15 * 997805;
+ s7 += s15 * 136657;
+ s8 -= s15 * 683901;
+
+ s2 += s14 * 666643;
+ s3 += s14 * 470296;
+ s4 += s14 * 654183;
+ s5 -= s14 * 997805;
+ s6 += s14 * 136657;
+ s7 -= s14 * 683901;
+
+ s1 += s13 * 666643;
+ s2 += s13 * 470296;
+ s3 += s13 * 654183;
+ s4 -= s13 * 997805;
+ s5 += s13 * 136657;
+ s6 -= s13 * 683901;
+
+ s0 += s12 * 666643;
+ s1 += s12 * 470296;
+ s2 += s12 * 654183;
+ s3 -= s12 * 997805;
+ s4 += s12 * 136657;
+ s5 -= s12 * 683901;
+ s12 = 0;
+
+ carry0 = (s0 + (int64_t) (1L << 20)) >> 21;
+ s1 += carry0;
+ s0 -= carry0 * ((uint64_t) 1L << 21);
+ carry2 = (s2 + (int64_t) (1L << 20)) >> 21;
+ s3 += carry2;
+ s2 -= carry2 * ((uint64_t) 1L << 21);
+ carry4 = (s4 + (int64_t) (1L << 20)) >> 21;
+ s5 += carry4;
+ s4 -= carry4 * ((uint64_t) 1L << 21);
+ carry6 = (s6 + (int64_t) (1L << 20)) >> 21;
+ s7 += carry6;
+ s6 -= carry6 * ((uint64_t) 1L << 21);
+ carry8 = (s8 + (int64_t) (1L << 20)) >> 21;
+ s9 += carry8;
+ s8 -= carry8 * ((uint64_t) 1L << 21);
+ carry10 = (s10 + (int64_t) (1L << 20)) >> 21;
+ s11 += carry10;
+ s10 -= carry10 * ((uint64_t) 1L << 21);
+
+ carry1 = (s1 + (int64_t) (1L << 20)) >> 21;
+ s2 += carry1;
+ s1 -= carry1 * ((uint64_t) 1L << 21);
+ carry3 = (s3 + (int64_t) (1L << 20)) >> 21;
+ s4 += carry3;
+ s3 -= carry3 * ((uint64_t) 1L << 21);
+ carry5 = (s5 + (int64_t) (1L << 20)) >> 21;
+ s6 += carry5;
+ s5 -= carry5 * ((uint64_t) 1L << 21);
+ carry7 = (s7 + (int64_t) (1L << 20)) >> 21;
+ s8 += carry7;
+ s7 -= carry7 * ((uint64_t) 1L << 21);
+ carry9 = (s9 + (int64_t) (1L << 20)) >> 21;
+ s10 += carry9;
+ s9 -= carry9 * ((uint64_t) 1L << 21);
+ carry11 = (s11 + (int64_t) (1L << 20)) >> 21;
+ s12 += carry11;
+ s11 -= carry11 * ((uint64_t) 1L << 21);
+
+ s0 += s12 * 666643;
+ s1 += s12 * 470296;
+ s2 += s12 * 654183;
+ s3 -= s12 * 997805;
+ s4 += s12 * 136657;
+ s5 -= s12 * 683901;
+ s12 = 0;
+
+ carry0 = s0 >> 21;
+ s1 += carry0;
+ s0 -= carry0 * ((uint64_t) 1L << 21);
+ carry1 = s1 >> 21;
+ s2 += carry1;
+ s1 -= carry1 * ((uint64_t) 1L << 21);
+ carry2 = s2 >> 21;
+ s3 += carry2;
+ s2 -= carry2 * ((uint64_t) 1L << 21);
+ carry3 = s3 >> 21;
+ s4 += carry3;
+ s3 -= carry3 * ((uint64_t) 1L << 21);
+ carry4 = s4 >> 21;
+ s5 += carry4;
+ s4 -= carry4 * ((uint64_t) 1L << 21);
+ carry5 = s5 >> 21;
+ s6 += carry5;
+ s5 -= carry5 * ((uint64_t) 1L << 21);
+ carry6 = s6 >> 21;
+ s7 += carry6;
+ s6 -= carry6 * ((uint64_t) 1L << 21);
+ carry7 = s7 >> 21;
+ s8 += carry7;
+ s7 -= carry7 * ((uint64_t) 1L << 21);
+ carry8 = s8 >> 21;
+ s9 += carry8;
+ s8 -= carry8 * ((uint64_t) 1L << 21);
+ carry9 = s9 >> 21;
+ s10 += carry9;
+ s9 -= carry9 * ((uint64_t) 1L << 21);
+ carry10 = s10 >> 21;
+ s11 += carry10;
+ s10 -= carry10 * ((uint64_t) 1L << 21);
+ carry11 = s11 >> 21;
+ s12 += carry11;
+ s11 -= carry11 * ((uint64_t) 1L << 21);
+
+ s0 += s12 * 666643;
+ s1 += s12 * 470296;
+ s2 += s12 * 654183;
+ s3 -= s12 * 997805;
+ s4 += s12 * 136657;
+ s5 -= s12 * 683901;
+
+ carry0 = s0 >> 21;
+ s1 += carry0;
+ s0 -= carry0 * ((uint64_t) 1L << 21);
+ carry1 = s1 >> 21;
+ s2 += carry1;
+ s1 -= carry1 * ((uint64_t) 1L << 21);
+ carry2 = s2 >> 21;
+ s3 += carry2;
+ s2 -= carry2 * ((uint64_t) 1L << 21);
+ carry3 = s3 >> 21;
+ s4 += carry3;
+ s3 -= carry3 * ((uint64_t) 1L << 21);
+ carry4 = s4 >> 21;
+ s5 += carry4;
+ s4 -= carry4 * ((uint64_t) 1L << 21);
+ carry5 = s5 >> 21;
+ s6 += carry5;
+ s5 -= carry5 * ((uint64_t) 1L << 21);
+ carry6 = s6 >> 21;
+ s7 += carry6;
+ s6 -= carry6 * ((uint64_t) 1L << 21);
+ carry7 = s7 >> 21;
+ s8 += carry7;
+ s7 -= carry7 * ((uint64_t) 1L << 21);
+ carry8 = s8 >> 21;
+ s9 += carry8;
+ s8 -= carry8 * ((uint64_t) 1L << 21);
+ carry9 = s9 >> 21;
+ s10 += carry9;
+ s9 -= carry9 * ((uint64_t) 1L << 21);
+ carry10 = s10 >> 21;
+ s11 += carry10;
+ s10 -= carry10 * ((uint64_t) 1L << 21);
+
+ s[0] = s0 >> 0;
+ s[1] = s0 >> 8;
+ s[2] = (s0 >> 16) | (s1 * ((uint64_t) 1 << 5));
+ s[3] = s1 >> 3;
+ s[4] = s1 >> 11;
+ s[5] = (s1 >> 19) | (s2 * ((uint64_t) 1 << 2));
+ s[6] = s2 >> 6;
+ s[7] = (s2 >> 14) | (s3 * ((uint64_t) 1 << 7));
+ s[8] = s3 >> 1;
+ s[9] = s3 >> 9;
+ s[10] = (s3 >> 17) | (s4 * ((uint64_t) 1 << 4));
+ s[11] = s4 >> 4;
+ s[12] = s4 >> 12;
+ s[13] = (s4 >> 20) | (s5 * ((uint64_t) 1 << 1));
+ s[14] = s5 >> 7;
+ s[15] = (s5 >> 15) | (s6 * ((uint64_t) 1 << 6));
+ s[16] = s6 >> 2;
+ s[17] = s6 >> 10;
+ s[18] = (s6 >> 18) | (s7 * ((uint64_t) 1 << 3));
+ s[19] = s7 >> 5;
+ s[20] = s7 >> 13;
+ s[21] = s8 >> 0;
+ s[22] = s8 >> 8;
+ s[23] = (s8 >> 16) | (s9 * ((uint64_t) 1 << 5));
+ s[24] = s9 >> 3;
+ s[25] = s9 >> 11;
+ s[26] = (s9 >> 19) | (s10 * ((uint64_t) 1 << 2));
+ s[27] = s10 >> 6;
+ s[28] = (s10 >> 14) | (s11 * ((uint64_t) 1 << 7));
+ s[29] = s11 >> 1;
+ s[30] = s11 >> 9;
+ s[31] = s11 >> 17;
+}
+
+int
+sc25519_is_canonical(const unsigned char s[32])
+{
+ /* 2^252+27742317777372353535851937790883648493 */
+ static const unsigned char L[32] = {
+ 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7,
+ 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10
+ };
+ unsigned char c = 0;
+ unsigned char n = 1;
+ unsigned int i = 32;
+
+ do {
+ i--;
+ c |= ((s[i] - L[i]) >> 8) & n;
+ n &= ((s[i] ^ L[i]) - 1) >> 8;
+ } while (i != 0);
+
+ return (c != 0);
+}
+
+static void
+chi25519(fe25519 out, const fe25519 z)
+{
+ fe25519 t0, t1, t2, t3;
+ int i;
+
+ fe25519_sq(t0, z);
+ fe25519_mul(t1, t0, z);
+ fe25519_sq(t0, t1);
+ fe25519_sq(t2, t0);
+ fe25519_sq(t2, t2);
+ fe25519_mul(t2, t2, t0);
+ fe25519_mul(t1, t2, z);
+ fe25519_sq(t2, t1);
+
+ for (i = 1; i < 5; i++) {
+ fe25519_sq(t2, t2);
+ }
+ fe25519_mul(t1, t2, t1);
+ fe25519_sq(t2, t1);
+ for (i = 1; i < 10; i++) {
+ fe25519_sq(t2, t2);
+ }
+ fe25519_mul(t2, t2, t1);
+ fe25519_sq(t3, t2);
+ for (i = 1; i < 20; i++) {
+ fe25519_sq(t3, t3);
+ }
+ fe25519_mul(t2, t3, t2);
+ fe25519_sq(t2, t2);
+ for (i = 1; i < 10; i++) {
+ fe25519_sq(t2, t2);
+ }
+ fe25519_mul(t1, t2, t1);
+ fe25519_sq(t2, t1);
+ for (i = 1; i < 50; i++) {
+ fe25519_sq(t2, t2);
+ }
+ fe25519_mul(t2, t2, t1);
+ fe25519_sq(t3, t2);
+ for (i = 1; i < 100; i++) {
+ fe25519_sq(t3, t3);
+ }
+ fe25519_mul(t2, t3, t2);
+ fe25519_sq(t2, t2);
+ for (i = 1; i < 50; i++) {
+ fe25519_sq(t2, t2);
+ }
+ fe25519_mul(t1, t2, t1);
+ fe25519_sq(t1, t1);
+ for (i = 1; i < 4; i++) {
+ fe25519_sq(t1, t1);
+ }
+ fe25519_mul(out, t1, t0);
+}
+
+static void
+ge25519_elligator2(unsigned char s[32], const fe25519 r, const unsigned char x_sign)
+{
+ fe25519 e;
+ fe25519 negx;
+ fe25519 rr2;
+ fe25519 x, x2, x3;
+ ge25519_p3 p3;
+ ge25519_p1p1 p1;
+ ge25519_p2 p2;
+ unsigned int e_is_minus_1;
+
+ fe25519_sq2(rr2, r);
+ rr2[0]++;
+ fe25519_invert(rr2, rr2);
+ fe25519_mul(x, curve25519_A, rr2);
+ fe25519_neg(x, x);
+
+ fe25519_sq(x2, x);
+ fe25519_mul(x3, x, x2);
+ fe25519_add(e, x3, x);
+ fe25519_mul(x2, x2, curve25519_A);
+ fe25519_add(e, x2, e);
+
+ chi25519(e, e);
+
+ fe25519_tobytes(s, e);
+ e_is_minus_1 = s[1] & 1;
+ fe25519_neg(negx, x);
+ fe25519_cmov(x, negx, e_is_minus_1);
+ fe25519_0(x2);
+ fe25519_cmov(x2, curve25519_A, e_is_minus_1);
+ fe25519_sub(x, x, x2);
+
+ /* yed = (x-1)/(x+1) */
+ {
+ fe25519 one;
+ fe25519 x_plus_one;
+ fe25519 x_plus_one_inv;
+ fe25519 x_minus_one;
+ fe25519 yed;
+
+ fe25519_1(one);
+ fe25519_add(x_plus_one, x, one);
+ fe25519_sub(x_minus_one, x, one);
+ fe25519_invert(x_plus_one_inv, x_plus_one);
+ fe25519_mul(yed, x_minus_one, x_plus_one_inv);
+ fe25519_tobytes(s, yed);
+ }
+
+ /* recover x */
+ s[31] |= x_sign;
+ if (ge25519_frombytes(&p3, s) != 0) {
+ abort(); /* LCOV_EXCL_LINE */
+ }
+
+ /* multiply by the cofactor */
+ ge25519_p3_dbl(&p1, &p3);
+ ge25519_p1p1_to_p2(&p2, &p1);
+ ge25519_p2_dbl(&p1, &p2);
+ ge25519_p1p1_to_p2(&p2, &p1);
+ ge25519_p2_dbl(&p1, &p2);
+ ge25519_p1p1_to_p3(&p3, &p1);
+
+ ge25519_p3_tobytes(s, &p3);
+}
+
+void
+ge25519_from_uniform(unsigned char s[32], const unsigned char r[32])
+{
+ fe25519 r_fe;
+ unsigned char x_sign;
+
+ memcpy(s, r, 32);
+ x_sign = s[31] & 0x80;
+ s[31] &= 0x7f;
+ fe25519_frombytes(r_fe, s);
+ ge25519_elligator2(s, r_fe, x_sign);
+}
+
+void
+ge25519_from_hash(unsigned char s[32], const unsigned char h[64])
+{
+ unsigned char fl[32];
+ unsigned char gl[32];
+ fe25519 fe_f;
+ fe25519 fe_g;
+ size_t i;
+ unsigned char x_sign;
+
+ x_sign = h[0] & 0x80;
+ for (i = 0; i < 32; i++) {
+ fl[i] = h[63 - i];
+ gl[i] = h[31 - i];
+ }
+ fl[31] &= 0x7f;
+ gl[31] &= 0x7f;
+ fe25519_frombytes(fe_f, fl);
+ fe25519_frombytes(fe_g, gl);
+ fe_f[0] += (h[32] >> 7) * 19;
+ for (i = 0; i < sizeof (fe25519) / sizeof fe_f[0]; i++) {
+ fe_f[i] += 38 * fe_g[i];
+ }
+ fe25519_reduce(fe_f, fe_f);
+ ge25519_elligator2(s, fe_f, x_sign);
+}
+
+/* Ristretto group */
+
+static int
+ristretto255_sqrt_ratio_m1(fe25519 x, const fe25519 u, const fe25519 v)
+{
+ fe25519 v3;
+ fe25519 vxx;
+ fe25519 m_root_check, p_root_check, f_root_check;
+ fe25519 x_sqrtm1;
+ int has_m_root, has_p_root, has_f_root;
+
+ fe25519_sq(v3, v);
+ fe25519_mul(v3, v3, v); /* v3 = v^3 */
+ fe25519_sq(x, v3);
+ fe25519_mul(x, x, v);
+ fe25519_mul(x, x, u); /* x = uv^7 */
+
+ fe25519_pow22523(x, x); /* x = (uv^7)^((q-5)/8) */
+ fe25519_mul(x, x, v3);
+ fe25519_mul(x, x, u); /* x = uv^3(uv^7)^((q-5)/8) */
+
+ fe25519_sq(vxx, x);
+ fe25519_mul(vxx, vxx, v); /* vx^2 */
+ fe25519_sub(m_root_check, vxx, u); /* vx^2-u */
+ fe25519_add(p_root_check, vxx, u); /* vx^2+u */
+ fe25519_mul(f_root_check, u, sqrtm1); /* u*sqrt(-1) */
+ fe25519_add(f_root_check, vxx, f_root_check); /* vx^2+u*sqrt(-1) */
+ has_m_root = fe25519_iszero(m_root_check);
+ has_p_root = fe25519_iszero(p_root_check);
+ has_f_root = fe25519_iszero(f_root_check);
+ fe25519_mul(x_sqrtm1, x, sqrtm1); /* x*sqrt(-1) */
+
+ fe25519_cmov(x, x_sqrtm1, has_p_root | has_f_root);
+ fe25519_abs(x, x);
+
+ return has_m_root | has_p_root;
+}
+
+static int
+ristretto255_is_canonical(const unsigned char *s)
+{
+ unsigned char c;
+ unsigned char d;
+ unsigned int i;
+
+ c = (s[31] & 0x7f) ^ 0x7f;
+ for (i = 30; i > 0; i--) {
+ c |= s[i] ^ 0xff;
+ }
+ c = (((unsigned int) c) - 1U) >> 8;
+ d = (0xed - 1U - (unsigned int) s[0]) >> 8;
+
+ return 1 - (((c & d) | s[0]) & 1);
+}
+
+int
+ristretto255_frombytes(ge25519_p3 *h, const unsigned char *s)
+{
+ fe25519 inv_sqrt;
+ fe25519 one;
+ fe25519 s_;
+ fe25519 ss;
+ fe25519 u1, u2;
+ fe25519 u1u1, u2u2;
+ fe25519 v;
+ fe25519 v_u2u2;
+ int was_square;
+
+ if (ristretto255_is_canonical(s) == 0) {
+ return -1;
+ }
+ fe25519_frombytes(s_, s);
+ fe25519_sq(ss, s_); /* ss = s^2 */
+
+ fe25519_1(u1);
+ fe25519_sub(u1, u1, ss); /* u1 = 1-ss */
+ fe25519_sq(u1u1, u1); /* u1u1 = u1^2 */
+
+ fe25519_1(u2);
+ fe25519_add(u2, u2, ss); /* u2 = 1+ss */
+ fe25519_sq(u2u2, u2); /* u2u2 = u2^2 */
+
+ fe25519_mul(v, d, u1u1); /* v = d*u1^2 */
+ fe25519_neg(v, v); /* v = -d*u1^2 */
+ fe25519_sub(v, v, u2u2); /* v = -(d*u1^2)-u2^2 */
+
+ fe25519_mul(v_u2u2, v, u2u2); /* v_u2u2 = v*u2^2 */
+
+ fe25519_1(one);
+ was_square = ristretto255_sqrt_ratio_m1(inv_sqrt, one, v_u2u2);
+ fe25519_mul(h->X, inv_sqrt, u2);
+ fe25519_mul(h->Y, inv_sqrt, h->X);
+ fe25519_mul(h->Y, h->Y, v);
+
+ fe25519_mul(h->X, h->X, s_);
+ fe25519_add(h->X, h->X, h->X);
+ fe25519_abs(h->X, h->X);
+ fe25519_mul(h->Y, u1, h->Y);
+ fe25519_1(h->Z);
+ fe25519_mul(h->T, h->X, h->Y);
+
+ return - ((1 - was_square) |
+ fe25519_isnegative(h->T) | fe25519_iszero(h->Y));
+}
+
+void
+ristretto255_p3_tobytes(unsigned char *s, const ge25519_p3 *h)
+{
+ fe25519 den1, den2;
+ fe25519 den_inv;
+ fe25519 eden;
+ fe25519 inv_sqrt;
+ fe25519 ix, iy;
+ fe25519 one;
+ fe25519 s_;
+ fe25519 t_z_inv;
+ fe25519 u1, u2;
+ fe25519 u1_u2u2;
+ fe25519 x_, y_;
+ fe25519 x_z_inv;
+ fe25519 z_inv;
+ fe25519 zmy;
+ int rotate;
+
+ fe25519_add(u1, h->Z, h->Y); /* u1 = Z+Y */
+ fe25519_sub(zmy, h->Z, h->Y); /* zmy = Z-Y */
+ fe25519_mul(u1, u1, zmy); /* u1 = (Z+Y)*(Z-Y) */
+ fe25519_mul(u2, h->X, h->Y); /* u2 = X*Y */
+
+ fe25519_sq(u1_u2u2, u2); /* u1_u2u2 = u2^2 */
+ fe25519_mul(u1_u2u2, u1, u1_u2u2); /* u1_u2u2 = u1*u2^2 */
+
+ fe25519_1(one);
+ (void) ristretto255_sqrt_ratio_m1(inv_sqrt, one, u1_u2u2);
+ fe25519_mul(den1, inv_sqrt, u1); /* den1 = inv_sqrt*u1 */
+ fe25519_mul(den2, inv_sqrt, u2); /* den2 = inv_sqrt*u2 */
+ fe25519_mul(z_inv, den1, den2); /* z_inv = den1*den2 */
+ fe25519_mul(z_inv, z_inv, h->T); /* z_inv = den1*den2*T */
+
+ fe25519_mul(ix, h->X, sqrtm1); /* ix = X*sqrt(-1) */
+ fe25519_mul(iy, h->Y, sqrtm1); /* iy = Y*sqrt(-1) */
+ fe25519_mul(eden, den1, invsqrtamd); /* eden = den1*sqrt(a-d) */
+
+ fe25519_mul(t_z_inv, h->T, z_inv); /* t_z_inv = T*z_inv */
+ rotate = fe25519_isnegative(t_z_inv);
+
+ fe25519_copy(x_, h->X);
+ fe25519_copy(y_, h->Y);
+ fe25519_copy(den_inv, den2);
+
+ fe25519_cmov(x_, iy, rotate);
+ fe25519_cmov(y_, ix, rotate);
+ fe25519_cmov(den_inv, eden, rotate);
+
+ fe25519_mul(x_z_inv, x_, z_inv);
+ fe25519_cneg(y_, y_, fe25519_isnegative(x_z_inv));
+
+ fe25519_sub(s_, h->Z, y_);
+ fe25519_mul(s_, den_inv, s_);
+ fe25519_abs(s_, s_);
+ fe25519_tobytes(s, s_);
+}
+
+static void
+ristretto255_elligator(ge25519_p3 *p, const fe25519 t)
+{
+ fe25519 c;
+ fe25519 n;
+ fe25519 one;
+ fe25519 r;
+ fe25519 rpd;
+ fe25519 s, s_prime;
+ fe25519 ss;
+ fe25519 u, v;
+ fe25519 w0, w1, w2, w3;
+ int wasnt_square;
+
+ fe25519_1(one);
+ fe25519_sq(r, t); /* r = t^2 */
+ fe25519_mul(r, sqrtm1, r); /* r = sqrt(-1)*t^2 */
+ fe25519_add(u, r, one); /* u = r+1 */
+ fe25519_mul(u, u, onemsqd); /* u = (r+1)*(1-d^2) */
+ fe25519_1(c);
+ fe25519_neg(c, c); /* c = -1 */
+ fe25519_add(rpd, r, d); /* rpd = r*d */
+ fe25519_mul(v, r, d); /* v = r*d */
+ fe25519_sub(v, c, v); /* v = c-r*d */
+ fe25519_mul(v, v, rpd); /* v = (c-r*d)*(r+d) */
+
+ wasnt_square = 1 - ristretto255_sqrt_ratio_m1(s, u, v);
+ fe25519_mul(s_prime, s, t);
+ fe25519_abs(s_prime, s_prime);
+ fe25519_neg(s_prime, s_prime); /* s_prime = -|s*t| */
+ fe25519_cmov(s, s_prime, wasnt_square);
+ fe25519_cmov(c, r, wasnt_square);
+
+ fe25519_sub(n, r, one); /* n = r-1 */
+ fe25519_mul(n, n, c); /* n = c*(r-1) */
+ fe25519_mul(n, n, sqdmone); /* n = c*(r-1)*(d-1)^2 */
+ fe25519_sub(n, n, v); /* n = c*(r-1)*(d-1)^2-v */
+
+ fe25519_add(w0, s, s); /* w0 = 2s */
+ fe25519_mul(w0, w0, v); /* w0 = 2s*v */
+ fe25519_mul(w1, n, sqrtadm1); /* w1 = n*sqrt(ad-1) */
+ fe25519_sq(ss, s); /* ss = s^2 */
+ fe25519_sub(w2, one, ss); /* w2 = 1-s^2 */
+ fe25519_add(w3, one, ss); /* w3 = 1+s^2 */
+
+ fe25519_mul(p->X, w0, w3);
+ fe25519_mul(p->Y, w2, w1);
+ fe25519_mul(p->Z, w1, w3);
+ fe25519_mul(p->T, w0, w2);
+}
+
+void
+ristretto255_from_hash(unsigned char s[32], const unsigned char h[64])
+{
+ fe25519 r0, r1;
+ ge25519_cached p1_cached;
+ ge25519_p1p1 p_p1p1;
+ ge25519_p3 p0, p1;
+ ge25519_p3 p;
+
+ fe25519_frombytes(r0, h);
+ fe25519_frombytes(r1, h + 32);
+ ristretto255_elligator(&p0, r0);
+ ristretto255_elligator(&p1, r1);
+ ge25519_p3_to_cached(&p1_cached, &p1);
+ ge25519_add(&p_p1p1, &p0, &p1_cached);
+ ge25519_p1p1_to_p3(&p, &p_p1p1);
+ ristretto255_p3_tobytes(s, &p);
+}
diff --git a/third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10.h b/third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10.h
new file mode 100644
index 0000000..634dd2b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10.h
@@ -0,0 +1,174 @@
+/*
+ * ISC License
+ *
+ * Copyright (c) 2013-2019
+ * Frank Denis <j at pureftpd dot org>
+ *
+ * Permission to use, copy, modify, and/or 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.
+ */
+
+#ifndef ed25519_ref10_H
+#define ed25519_ref10_H
+
+#include <roken.h>
+#include <stddef.h>
+#include <stdint.h>
+
+/*
+ fe means field element.
+ Here the field is \Z/(2^255-19).
+ */
+
+#ifdef HAVE_TI_MODE
+typedef uint64_t fe25519[5];
+#else
+typedef int32_t fe25519[10];
+#endif
+
+void fe25519_invert(fe25519 out, const fe25519 z);
+void fe25519_frombytes(fe25519 h, const unsigned char *s);
+void fe25519_tobytes(unsigned char *s, const fe25519 h);
+
+static inline int
+sodium_is_zero(const unsigned char *n, const size_t nlen)
+{
+ size_t i;
+ volatile unsigned char d = 0U;
+
+ for (i = 0U; i < nlen; i++) {
+ d |= n[i];
+ }
+ return 1 & ((d - 1) >> 8);
+}
+
+#ifdef HAVE_TI_MODE
+# include "ed25519_ref10_fe_51.h"
+#else
+# include "ed25519_ref10_fe_25_5.h"
+#endif
+
+
+/*
+ ge means group element.
+
+ Here the group is the set of pairs (x,y) of field elements
+ satisfying -x^2 + y^2 = 1 + d x^2y^2
+ where d = -121665/121666.
+
+ Representations:
+ ge25519_p2 (projective): (X:Y:Z) satisfying x=X/Z, y=Y/Z
+ ge25519_p3 (extended): (X:Y:Z:T) satisfying x=X/Z, y=Y/Z, XY=ZT
+ ge25519_p1p1 (completed): ((X:Z),(Y:T)) satisfying x=X/Z, y=Y/T
+ ge25519_precomp (Duif): (y+x,y-x,2dxy)
+ */
+
+typedef struct {
+ fe25519 X;
+ fe25519 Y;
+ fe25519 Z;
+} ge25519_p2;
+
+typedef struct {
+ fe25519 X;
+ fe25519 Y;
+ fe25519 Z;
+ fe25519 T;
+} ge25519_p3;
+
+typedef struct {
+ fe25519 X;
+ fe25519 Y;
+ fe25519 Z;
+ fe25519 T;
+} ge25519_p1p1;
+
+typedef struct {
+ fe25519 yplusx;
+ fe25519 yminusx;
+ fe25519 xy2d;
+} ge25519_precomp;
+
+typedef struct {
+ fe25519 YplusX;
+ fe25519 YminusX;
+ fe25519 Z;
+ fe25519 T2d;
+} ge25519_cached;
+
+void ge25519_tobytes(unsigned char *s, const ge25519_p2 *h);
+
+void ge25519_p3_tobytes(unsigned char *s, const ge25519_p3 *h);
+
+int ge25519_frombytes(ge25519_p3 *h, const unsigned char *s);
+
+int ge25519_frombytes_negate_vartime(ge25519_p3 *h, const unsigned char *s);
+
+void ge25519_p3_to_cached(ge25519_cached *r, const ge25519_p3 *p);
+
+void ge25519_p1p1_to_p2(ge25519_p2 *r, const ge25519_p1p1 *p);
+
+void ge25519_p1p1_to_p3(ge25519_p3 *r, const ge25519_p1p1 *p);
+
+void ge25519_add(ge25519_p1p1 *r, const ge25519_p3 *p, const ge25519_cached *q);
+
+void ge25519_sub(ge25519_p1p1 *r, const ge25519_p3 *p, const ge25519_cached *q);
+
+void ge25519_scalarmult_base(ge25519_p3 *h, const unsigned char *a);
+
+void ge25519_double_scalarmult_vartime(ge25519_p2 *r, const unsigned char *a,
+ const ge25519_p3 *A,
+ const unsigned char *b);
+
+void ge25519_scalarmult(ge25519_p3 *h, const unsigned char *a,
+ const ge25519_p3 *p);
+
+int ge25519_is_canonical(const unsigned char *s);
+
+int ge25519_is_on_curve(const ge25519_p3 *p);
+
+int ge25519_is_on_main_subgroup(const ge25519_p3 *p);
+
+int ge25519_has_small_order(const unsigned char s[32]);
+
+void ge25519_from_uniform(unsigned char s[32], const unsigned char r[32]);
+
+void ge25519_from_hash(unsigned char s[32], const unsigned char h[64]);
+
+/*
+ Ristretto group
+ */
+
+int ristretto255_frombytes(ge25519_p3 *h, const unsigned char *s);
+
+void ristretto255_p3_tobytes(unsigned char *s, const ge25519_p3 *h);
+
+void ristretto255_from_hash(unsigned char s[32], const unsigned char h[64]);
+
+/*
+ The set of scalars is \Z/l
+ where l = 2^252 + 27742317777372353535851937790883648493.
+ */
+
+void sc25519_invert(unsigned char recip[32], const unsigned char s[32]);
+
+void sc25519_reduce(unsigned char s[64]);
+
+void sc25519_mul(unsigned char s[32], const unsigned char a[32],
+ const unsigned char b[32]);
+
+void sc25519_muladd(unsigned char s[32], const unsigned char a[32],
+ const unsigned char b[32], const unsigned char c[32]);
+
+int sc25519_is_canonical(const unsigned char s[32]);
+
+#endif
diff --git a/third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10_fe_25_5.h b/third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10_fe_25_5.h
new file mode 100644
index 0000000..169b581
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10_fe_25_5.h
@@ -0,0 +1,1067 @@
+/*
+ * ISC License
+ *
+ * Copyright (c) 2013-2019
+ * Frank Denis <j at pureftpd dot org>
+ *
+ * Permission to use, copy, modify, and/or 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.
+ */
+
+#include <roken.h>
+#include <string.h>
+
+/*
+ h = 0
+ */
+
+static inline void
+fe25519_0(fe25519 h)
+{
+ memset(&h[0], 0, 10 * sizeof h[0]);
+}
+
+/*
+ h = 1
+ */
+
+static inline void
+fe25519_1(fe25519 h)
+{
+ h[0] = 1;
+ h[1] = 0;
+ memset(&h[2], 0, 8 * sizeof h[0]);
+}
+
+/*
+ h = f + g
+ Can overlap h with f or g.
+ *
+ Preconditions:
+ |f| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc.
+ |g| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc.
+ *
+ Postconditions:
+ |h| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc.
+ */
+
+static inline void
+fe25519_add(fe25519 h, const fe25519 f, const fe25519 g)
+{
+ int32_t h0 = f[0] + g[0];
+ int32_t h1 = f[1] + g[1];
+ int32_t h2 = f[2] + g[2];
+ int32_t h3 = f[3] + g[3];
+ int32_t h4 = f[4] + g[4];
+ int32_t h5 = f[5] + g[5];
+ int32_t h6 = f[6] + g[6];
+ int32_t h7 = f[7] + g[7];
+ int32_t h8 = f[8] + g[8];
+ int32_t h9 = f[9] + g[9];
+
+ h[0] = h0;
+ h[1] = h1;
+ h[2] = h2;
+ h[3] = h3;
+ h[4] = h4;
+ h[5] = h5;
+ h[6] = h6;
+ h[7] = h7;
+ h[8] = h8;
+ h[9] = h9;
+}
+
+/*
+ h = f - g
+ Can overlap h with f or g.
+ *
+ Preconditions:
+ |f| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc.
+ |g| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc.
+ *
+ Postconditions:
+ |h| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc.
+ */
+
+static void
+fe25519_sub(fe25519 h, const fe25519 f, const fe25519 g)
+{
+ int32_t h0 = f[0] - g[0];
+ int32_t h1 = f[1] - g[1];
+ int32_t h2 = f[2] - g[2];
+ int32_t h3 = f[3] - g[3];
+ int32_t h4 = f[4] - g[4];
+ int32_t h5 = f[5] - g[5];
+ int32_t h6 = f[6] - g[6];
+ int32_t h7 = f[7] - g[7];
+ int32_t h8 = f[8] - g[8];
+ int32_t h9 = f[9] - g[9];
+
+ h[0] = h0;
+ h[1] = h1;
+ h[2] = h2;
+ h[3] = h3;
+ h[4] = h4;
+ h[5] = h5;
+ h[6] = h6;
+ h[7] = h7;
+ h[8] = h8;
+ h[9] = h9;
+}
+
+/*
+ h = -f
+ *
+ Preconditions:
+ |f| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc.
+ *
+ Postconditions:
+ |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc.
+ */
+
+static inline void
+fe25519_neg(fe25519 h, const fe25519 f)
+{
+ int32_t h0 = -f[0];
+ int32_t h1 = -f[1];
+ int32_t h2 = -f[2];
+ int32_t h3 = -f[3];
+ int32_t h4 = -f[4];
+ int32_t h5 = -f[5];
+ int32_t h6 = -f[6];
+ int32_t h7 = -f[7];
+ int32_t h8 = -f[8];
+ int32_t h9 = -f[9];
+
+ h[0] = h0;
+ h[1] = h1;
+ h[2] = h2;
+ h[3] = h3;
+ h[4] = h4;
+ h[5] = h5;
+ h[6] = h6;
+ h[7] = h7;
+ h[8] = h8;
+ h[9] = h9;
+}
+
+/*
+ Replace (f,g) with (g,g) if b == 1;
+ replace (f,g) with (f,g) if b == 0.
+ *
+ Preconditions: b in {0,1}.
+ */
+
+static void
+fe25519_cmov(fe25519 f, const fe25519 g, unsigned int b)
+{
+ const uint32_t mask = (uint32_t) (-(int32_t) b);
+
+ int32_t f0 = f[0];
+ int32_t f1 = f[1];
+ int32_t f2 = f[2];
+ int32_t f3 = f[3];
+ int32_t f4 = f[4];
+ int32_t f5 = f[5];
+ int32_t f6 = f[6];
+ int32_t f7 = f[7];
+ int32_t f8 = f[8];
+ int32_t f9 = f[9];
+
+ int32_t x0 = f0 ^ g[0];
+ int32_t x1 = f1 ^ g[1];
+ int32_t x2 = f2 ^ g[2];
+ int32_t x3 = f3 ^ g[3];
+ int32_t x4 = f4 ^ g[4];
+ int32_t x5 = f5 ^ g[5];
+ int32_t x6 = f6 ^ g[6];
+ int32_t x7 = f7 ^ g[7];
+ int32_t x8 = f8 ^ g[8];
+ int32_t x9 = f9 ^ g[9];
+
+ x0 &= mask;
+ x1 &= mask;
+ x2 &= mask;
+ x3 &= mask;
+ x4 &= mask;
+ x5 &= mask;
+ x6 &= mask;
+ x7 &= mask;
+ x8 &= mask;
+ x9 &= mask;
+
+ f[0] = f0 ^ x0;
+ f[1] = f1 ^ x1;
+ f[2] = f2 ^ x2;
+ f[3] = f3 ^ x3;
+ f[4] = f4 ^ x4;
+ f[5] = f5 ^ x5;
+ f[6] = f6 ^ x6;
+ f[7] = f7 ^ x7;
+ f[8] = f8 ^ x8;
+ f[9] = f9 ^ x9;
+}
+
+static void
+fe25519_cswap(fe25519 f, fe25519 g, unsigned int b)
+{
+ const uint32_t mask = (uint32_t) (-(int64_t) b);
+
+ int32_t f0 = f[0];
+ int32_t f1 = f[1];
+ int32_t f2 = f[2];
+ int32_t f3 = f[3];
+ int32_t f4 = f[4];
+ int32_t f5 = f[5];
+ int32_t f6 = f[6];
+ int32_t f7 = f[7];
+ int32_t f8 = f[8];
+ int32_t f9 = f[9];
+
+ int32_t g0 = g[0];
+ int32_t g1 = g[1];
+ int32_t g2 = g[2];
+ int32_t g3 = g[3];
+ int32_t g4 = g[4];
+ int32_t g5 = g[5];
+ int32_t g6 = g[6];
+ int32_t g7 = g[7];
+ int32_t g8 = g[8];
+ int32_t g9 = g[9];
+
+ int32_t x0 = f0 ^ g0;
+ int32_t x1 = f1 ^ g1;
+ int32_t x2 = f2 ^ g2;
+ int32_t x3 = f3 ^ g3;
+ int32_t x4 = f4 ^ g4;
+ int32_t x5 = f5 ^ g5;
+ int32_t x6 = f6 ^ g6;
+ int32_t x7 = f7 ^ g7;
+ int32_t x8 = f8 ^ g8;
+ int32_t x9 = f9 ^ g9;
+
+ x0 &= mask;
+ x1 &= mask;
+ x2 &= mask;
+ x3 &= mask;
+ x4 &= mask;
+ x5 &= mask;
+ x6 &= mask;
+ x7 &= mask;
+ x8 &= mask;
+ x9 &= mask;
+
+ f[0] = f0 ^ x0;
+ f[1] = f1 ^ x1;
+ f[2] = f2 ^ x2;
+ f[3] = f3 ^ x3;
+ f[4] = f4 ^ x4;
+ f[5] = f5 ^ x5;
+ f[6] = f6 ^ x6;
+ f[7] = f7 ^ x7;
+ f[8] = f8 ^ x8;
+ f[9] = f9 ^ x9;
+
+ g[0] = g0 ^ x0;
+ g[1] = g1 ^ x1;
+ g[2] = g2 ^ x2;
+ g[3] = g3 ^ x3;
+ g[4] = g4 ^ x4;
+ g[5] = g5 ^ x5;
+ g[6] = g6 ^ x6;
+ g[7] = g7 ^ x7;
+ g[8] = g8 ^ x8;
+ g[9] = g9 ^ x9;
+}
+
+/*
+ h = f
+ */
+
+static inline void
+fe25519_copy(fe25519 h, const fe25519 f)
+{
+ int32_t f0 = f[0];
+ int32_t f1 = f[1];
+ int32_t f2 = f[2];
+ int32_t f3 = f[3];
+ int32_t f4 = f[4];
+ int32_t f5 = f[5];
+ int32_t f6 = f[6];
+ int32_t f7 = f[7];
+ int32_t f8 = f[8];
+ int32_t f9 = f[9];
+
+ h[0] = f0;
+ h[1] = f1;
+ h[2] = f2;
+ h[3] = f3;
+ h[4] = f4;
+ h[5] = f5;
+ h[6] = f6;
+ h[7] = f7;
+ h[8] = f8;
+ h[9] = f9;
+}
+
+/*
+ return 1 if f is in {1,3,5,...,q-2}
+ return 0 if f is in {0,2,4,...,q-1}
+
+ Preconditions:
+ |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc.
+ */
+
+static inline int
+fe25519_isnegative(const fe25519 f)
+{
+ unsigned char s[32];
+
+ fe25519_tobytes(s, f);
+
+ return s[0] & 1;
+}
+
+/*
+ return 1 if f == 0
+ return 0 if f != 0
+
+ Preconditions:
+ |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc.
+ */
+
+static inline int
+fe25519_iszero(const fe25519 f)
+{
+ unsigned char s[32];
+
+ fe25519_tobytes(s, f);
+
+ return sodium_is_zero(s, 32);
+}
+
+/*
+ h = f * g
+ Can overlap h with f or g.
+ *
+ Preconditions:
+ |f| bounded by 1.65*2^26,1.65*2^25,1.65*2^26,1.65*2^25,etc.
+ |g| bounded by 1.65*2^26,1.65*2^25,1.65*2^26,1.65*2^25,etc.
+ *
+ Postconditions:
+ |h| bounded by 1.01*2^25,1.01*2^24,1.01*2^25,1.01*2^24,etc.
+ */
+
+/*
+ Notes on implementation strategy:
+ *
+ Using schoolbook multiplication.
+ Karatsuba would save a little in some cost models.
+ *
+ Most multiplications by 2 and 19 are 32-bit precomputations;
+ cheaper than 64-bit postcomputations.
+ *
+ There is one remaining multiplication by 19 in the carry chain;
+ one *19 precomputation can be merged into this,
+ but the resulting data flow is considerably less clean.
+ *
+ There are 12 carries below.
+ 10 of them are 2-way parallelizable and vectorizable.
+ Can get away with 11 carries, but then data flow is much deeper.
+ *
+ With tighter constraints on inputs can squeeze carries into int32.
+ */
+
+static void
+fe25519_mul(fe25519 h, const fe25519 f, const fe25519 g)
+{
+ int32_t f0 = f[0];
+ int32_t f1 = f[1];
+ int32_t f2 = f[2];
+ int32_t f3 = f[3];
+ int32_t f4 = f[4];
+ int32_t f5 = f[5];
+ int32_t f6 = f[6];
+ int32_t f7 = f[7];
+ int32_t f8 = f[8];
+ int32_t f9 = f[9];
+
+ int32_t g0 = g[0];
+ int32_t g1 = g[1];
+ int32_t g2 = g[2];
+ int32_t g3 = g[3];
+ int32_t g4 = g[4];
+ int32_t g5 = g[5];
+ int32_t g6 = g[6];
+ int32_t g7 = g[7];
+ int32_t g8 = g[8];
+ int32_t g9 = g[9];
+
+ int32_t g1_19 = 19 * g1; /* 1.959375*2^29 */
+ int32_t g2_19 = 19 * g2; /* 1.959375*2^30; still ok */
+ int32_t g3_19 = 19 * g3;
+ int32_t g4_19 = 19 * g4;
+ int32_t g5_19 = 19 * g5;
+ int32_t g6_19 = 19 * g6;
+ int32_t g7_19 = 19 * g7;
+ int32_t g8_19 = 19 * g8;
+ int32_t g9_19 = 19 * g9;
+ int32_t f1_2 = 2 * f1;
+ int32_t f3_2 = 2 * f3;
+ int32_t f5_2 = 2 * f5;
+ int32_t f7_2 = 2 * f7;
+ int32_t f9_2 = 2 * f9;
+
+ int64_t f0g0 = f0 * (int64_t) g0;
+ int64_t f0g1 = f0 * (int64_t) g1;
+ int64_t f0g2 = f0 * (int64_t) g2;
+ int64_t f0g3 = f0 * (int64_t) g3;
+ int64_t f0g4 = f0 * (int64_t) g4;
+ int64_t f0g5 = f0 * (int64_t) g5;
+ int64_t f0g6 = f0 * (int64_t) g6;
+ int64_t f0g7 = f0 * (int64_t) g7;
+ int64_t f0g8 = f0 * (int64_t) g8;
+ int64_t f0g9 = f0 * (int64_t) g9;
+ int64_t f1g0 = f1 * (int64_t) g0;
+ int64_t f1g1_2 = f1_2 * (int64_t) g1;
+ int64_t f1g2 = f1 * (int64_t) g2;
+ int64_t f1g3_2 = f1_2 * (int64_t) g3;
+ int64_t f1g4 = f1 * (int64_t) g4;
+ int64_t f1g5_2 = f1_2 * (int64_t) g5;
+ int64_t f1g6 = f1 * (int64_t) g6;
+ int64_t f1g7_2 = f1_2 * (int64_t) g7;
+ int64_t f1g8 = f1 * (int64_t) g8;
+ int64_t f1g9_38 = f1_2 * (int64_t) g9_19;
+ int64_t f2g0 = f2 * (int64_t) g0;
+ int64_t f2g1 = f2 * (int64_t) g1;
+ int64_t f2g2 = f2 * (int64_t) g2;
+ int64_t f2g3 = f2 * (int64_t) g3;
+ int64_t f2g4 = f2 * (int64_t) g4;
+ int64_t f2g5 = f2 * (int64_t) g5;
+ int64_t f2g6 = f2 * (int64_t) g6;
+ int64_t f2g7 = f2 * (int64_t) g7;
+ int64_t f2g8_19 = f2 * (int64_t) g8_19;
+ int64_t f2g9_19 = f2 * (int64_t) g9_19;
+ int64_t f3g0 = f3 * (int64_t) g0;
+ int64_t f3g1_2 = f3_2 * (int64_t) g1;
+ int64_t f3g2 = f3 * (int64_t) g2;
+ int64_t f3g3_2 = f3_2 * (int64_t) g3;
+ int64_t f3g4 = f3 * (int64_t) g4;
+ int64_t f3g5_2 = f3_2 * (int64_t) g5;
+ int64_t f3g6 = f3 * (int64_t) g6;
+ int64_t f3g7_38 = f3_2 * (int64_t) g7_19;
+ int64_t f3g8_19 = f3 * (int64_t) g8_19;
+ int64_t f3g9_38 = f3_2 * (int64_t) g9_19;
+ int64_t f4g0 = f4 * (int64_t) g0;
+ int64_t f4g1 = f4 * (int64_t) g1;
+ int64_t f4g2 = f4 * (int64_t) g2;
+ int64_t f4g3 = f4 * (int64_t) g3;
+ int64_t f4g4 = f4 * (int64_t) g4;
+ int64_t f4g5 = f4 * (int64_t) g5;
+ int64_t f4g6_19 = f4 * (int64_t) g6_19;
+ int64_t f4g7_19 = f4 * (int64_t) g7_19;
+ int64_t f4g8_19 = f4 * (int64_t) g8_19;
+ int64_t f4g9_19 = f4 * (int64_t) g9_19;
+ int64_t f5g0 = f5 * (int64_t) g0;
+ int64_t f5g1_2 = f5_2 * (int64_t) g1;
+ int64_t f5g2 = f5 * (int64_t) g2;
+ int64_t f5g3_2 = f5_2 * (int64_t) g3;
+ int64_t f5g4 = f5 * (int64_t) g4;
+ int64_t f5g5_38 = f5_2 * (int64_t) g5_19;
+ int64_t f5g6_19 = f5 * (int64_t) g6_19;
+ int64_t f5g7_38 = f5_2 * (int64_t) g7_19;
+ int64_t f5g8_19 = f5 * (int64_t) g8_19;
+ int64_t f5g9_38 = f5_2 * (int64_t) g9_19;
+ int64_t f6g0 = f6 * (int64_t) g0;
+ int64_t f6g1 = f6 * (int64_t) g1;
+ int64_t f6g2 = f6 * (int64_t) g2;
+ int64_t f6g3 = f6 * (int64_t) g3;
+ int64_t f6g4_19 = f6 * (int64_t) g4_19;
+ int64_t f6g5_19 = f6 * (int64_t) g5_19;
+ int64_t f6g6_19 = f6 * (int64_t) g6_19;
+ int64_t f6g7_19 = f6 * (int64_t) g7_19;
+ int64_t f6g8_19 = f6 * (int64_t) g8_19;
+ int64_t f6g9_19 = f6 * (int64_t) g9_19;
+ int64_t f7g0 = f7 * (int64_t) g0;
+ int64_t f7g1_2 = f7_2 * (int64_t) g1;
+ int64_t f7g2 = f7 * (int64_t) g2;
+ int64_t f7g3_38 = f7_2 * (int64_t) g3_19;
+ int64_t f7g4_19 = f7 * (int64_t) g4_19;
+ int64_t f7g5_38 = f7_2 * (int64_t) g5_19;
+ int64_t f7g6_19 = f7 * (int64_t) g6_19;
+ int64_t f7g7_38 = f7_2 * (int64_t) g7_19;
+ int64_t f7g8_19 = f7 * (int64_t) g8_19;
+ int64_t f7g9_38 = f7_2 * (int64_t) g9_19;
+ int64_t f8g0 = f8 * (int64_t) g0;
+ int64_t f8g1 = f8 * (int64_t) g1;
+ int64_t f8g2_19 = f8 * (int64_t) g2_19;
+ int64_t f8g3_19 = f8 * (int64_t) g3_19;
+ int64_t f8g4_19 = f8 * (int64_t) g4_19;
+ int64_t f8g5_19 = f8 * (int64_t) g5_19;
+ int64_t f8g6_19 = f8 * (int64_t) g6_19;
+ int64_t f8g7_19 = f8 * (int64_t) g7_19;
+ int64_t f8g8_19 = f8 * (int64_t) g8_19;
+ int64_t f8g9_19 = f8 * (int64_t) g9_19;
+ int64_t f9g0 = f9 * (int64_t) g0;
+ int64_t f9g1_38 = f9_2 * (int64_t) g1_19;
+ int64_t f9g2_19 = f9 * (int64_t) g2_19;
+ int64_t f9g3_38 = f9_2 * (int64_t) g3_19;
+ int64_t f9g4_19 = f9 * (int64_t) g4_19;
+ int64_t f9g5_38 = f9_2 * (int64_t) g5_19;
+ int64_t f9g6_19 = f9 * (int64_t) g6_19;
+ int64_t f9g7_38 = f9_2 * (int64_t) g7_19;
+ int64_t f9g8_19 = f9 * (int64_t) g8_19;
+ int64_t f9g9_38 = f9_2 * (int64_t) g9_19;
+
+ int64_t h0 = f0g0 + f1g9_38 + f2g8_19 + f3g7_38 + f4g6_19 + f5g5_38 +
+ f6g4_19 + f7g3_38 + f8g2_19 + f9g1_38;
+ int64_t h1 = f0g1 + f1g0 + f2g9_19 + f3g8_19 + f4g7_19 + f5g6_19 + f6g5_19 +
+ f7g4_19 + f8g3_19 + f9g2_19;
+ int64_t h2 = f0g2 + f1g1_2 + f2g0 + f3g9_38 + f4g8_19 + f5g7_38 + f6g6_19 +
+ f7g5_38 + f8g4_19 + f9g3_38;
+ int64_t h3 = f0g3 + f1g2 + f2g1 + f3g0 + f4g9_19 + f5g8_19 + f6g7_19 +
+ f7g6_19 + f8g5_19 + f9g4_19;
+ int64_t h4 = f0g4 + f1g3_2 + f2g2 + f3g1_2 + f4g0 + f5g9_38 + f6g8_19 +
+ f7g7_38 + f8g6_19 + f9g5_38;
+ int64_t h5 = f0g5 + f1g4 + f2g3 + f3g2 + f4g1 + f5g0 + f6g9_19 + f7g8_19 +
+ f8g7_19 + f9g6_19;
+ int64_t h6 = f0g6 + f1g5_2 + f2g4 + f3g3_2 + f4g2 + f5g1_2 + f6g0 +
+ f7g9_38 + f8g8_19 + f9g7_38;
+ int64_t h7 = f0g7 + f1g6 + f2g5 + f3g4 + f4g3 + f5g2 + f6g1 + f7g0 +
+ f8g9_19 + f9g8_19;
+ int64_t h8 = f0g8 + f1g7_2 + f2g6 + f3g5_2 + f4g4 + f5g3_2 + f6g2 + f7g1_2 +
+ f8g0 + f9g9_38;
+ int64_t h9 =
+ f0g9 + f1g8 + f2g7 + f3g6 + f4g5 + f5g4 + f6g3 + f7g2 + f8g1 + f9g0;
+
+ int64_t carry0;
+ int64_t carry1;
+ int64_t carry2;
+ int64_t carry3;
+ int64_t carry4;
+ int64_t carry5;
+ int64_t carry6;
+ int64_t carry7;
+ int64_t carry8;
+ int64_t carry9;
+
+ /*
+ |h0| <= (1.65*1.65*2^52*(1+19+19+19+19)+1.65*1.65*2^50*(38+38+38+38+38))
+ i.e. |h0| <= 1.4*2^60; narrower ranges for h2, h4, h6, h8
+ |h1| <= (1.65*1.65*2^51*(1+1+19+19+19+19+19+19+19+19))
+ i.e. |h1| <= 1.7*2^59; narrower ranges for h3, h5, h7, h9
+ */
+
+ carry0 = (h0 + (int64_t)(1L << 25)) >> 26;
+ h1 += carry0;
+ h0 -= carry0 * ((uint64_t) 1L << 26);
+ carry4 = (h4 + (int64_t)(1L << 25)) >> 26;
+ h5 += carry4;
+ h4 -= carry4 * ((uint64_t) 1L << 26);
+ /* |h0| <= 2^25 */
+ /* |h4| <= 2^25 */
+ /* |h1| <= 1.71*2^59 */
+ /* |h5| <= 1.71*2^59 */
+
+ carry1 = (h1 + (int64_t)(1L << 24)) >> 25;
+ h2 += carry1;
+ h1 -= carry1 * ((uint64_t) 1L << 25);
+ carry5 = (h5 + (int64_t)(1L << 24)) >> 25;
+ h6 += carry5;
+ h5 -= carry5 * ((uint64_t) 1L << 25);
+ /* |h1| <= 2^24; from now on fits into int32 */
+ /* |h5| <= 2^24; from now on fits into int32 */
+ /* |h2| <= 1.41*2^60 */
+ /* |h6| <= 1.41*2^60 */
+
+ carry2 = (h2 + (int64_t)(1L << 25)) >> 26;
+ h3 += carry2;
+ h2 -= carry2 * ((uint64_t) 1L << 26);
+ carry6 = (h6 + (int64_t)(1L << 25)) >> 26;
+ h7 += carry6;
+ h6 -= carry6 * ((uint64_t) 1L << 26);
+ /* |h2| <= 2^25; from now on fits into int32 unchanged */
+ /* |h6| <= 2^25; from now on fits into int32 unchanged */
+ /* |h3| <= 1.71*2^59 */
+ /* |h7| <= 1.71*2^59 */
+
+ carry3 = (h3 + (int64_t)(1L << 24)) >> 25;
+ h4 += carry3;
+ h3 -= carry3 * ((uint64_t) 1L << 25);
+ carry7 = (h7 + (int64_t)(1L << 24)) >> 25;
+ h8 += carry7;
+ h7 -= carry7 * ((uint64_t) 1L << 25);
+ /* |h3| <= 2^24; from now on fits into int32 unchanged */
+ /* |h7| <= 2^24; from now on fits into int32 unchanged */
+ /* |h4| <= 1.72*2^34 */
+ /* |h8| <= 1.41*2^60 */
+
+ carry4 = (h4 + (int64_t)(1L << 25)) >> 26;
+ h5 += carry4;
+ h4 -= carry4 * ((uint64_t) 1L << 26);
+ carry8 = (h8 + (int64_t)(1L << 25)) >> 26;
+ h9 += carry8;
+ h8 -= carry8 * ((uint64_t) 1L << 26);
+ /* |h4| <= 2^25; from now on fits into int32 unchanged */
+ /* |h8| <= 2^25; from now on fits into int32 unchanged */
+ /* |h5| <= 1.01*2^24 */
+ /* |h9| <= 1.71*2^59 */
+
+ carry9 = (h9 + (int64_t)(1L << 24)) >> 25;
+ h0 += carry9 * 19;
+ h9 -= carry9 * ((uint64_t) 1L << 25);
+ /* |h9| <= 2^24; from now on fits into int32 unchanged */
+ /* |h0| <= 1.1*2^39 */
+
+ carry0 = (h0 + (int64_t)(1L << 25)) >> 26;
+ h1 += carry0;
+ h0 -= carry0 * ((uint64_t) 1L << 26);
+ /* |h0| <= 2^25; from now on fits into int32 unchanged */
+ /* |h1| <= 1.01*2^24 */
+
+ h[0] = (int32_t) h0;
+ h[1] = (int32_t) h1;
+ h[2] = (int32_t) h2;
+ h[3] = (int32_t) h3;
+ h[4] = (int32_t) h4;
+ h[5] = (int32_t) h5;
+ h[6] = (int32_t) h6;
+ h[7] = (int32_t) h7;
+ h[8] = (int32_t) h8;
+ h[9] = (int32_t) h9;
+}
+
+/*
+ h = f * f
+ Can overlap h with f.
+ *
+ Preconditions:
+ |f| bounded by 1.65*2^26,1.65*2^25,1.65*2^26,1.65*2^25,etc.
+ *
+ Postconditions:
+ |h| bounded by 1.01*2^25,1.01*2^24,1.01*2^25,1.01*2^24,etc.
+ */
+
+static void
+fe25519_sq(fe25519 h, const fe25519 f)
+{
+ int32_t f0 = f[0];
+ int32_t f1 = f[1];
+ int32_t f2 = f[2];
+ int32_t f3 = f[3];
+ int32_t f4 = f[4];
+ int32_t f5 = f[5];
+ int32_t f6 = f[6];
+ int32_t f7 = f[7];
+ int32_t f8 = f[8];
+ int32_t f9 = f[9];
+
+ int32_t f0_2 = 2 * f0;
+ int32_t f1_2 = 2 * f1;
+ int32_t f2_2 = 2 * f2;
+ int32_t f3_2 = 2 * f3;
+ int32_t f4_2 = 2 * f4;
+ int32_t f5_2 = 2 * f5;
+ int32_t f6_2 = 2 * f6;
+ int32_t f7_2 = 2 * f7;
+ int32_t f5_38 = 38 * f5; /* 1.959375*2^30 */
+ int32_t f6_19 = 19 * f6; /* 1.959375*2^30 */
+ int32_t f7_38 = 38 * f7; /* 1.959375*2^30 */
+ int32_t f8_19 = 19 * f8; /* 1.959375*2^30 */
+ int32_t f9_38 = 38 * f9; /* 1.959375*2^30 */
+
+ int64_t f0f0 = f0 * (int64_t) f0;
+ int64_t f0f1_2 = f0_2 * (int64_t) f1;
+ int64_t f0f2_2 = f0_2 * (int64_t) f2;
+ int64_t f0f3_2 = f0_2 * (int64_t) f3;
+ int64_t f0f4_2 = f0_2 * (int64_t) f4;
+ int64_t f0f5_2 = f0_2 * (int64_t) f5;
+ int64_t f0f6_2 = f0_2 * (int64_t) f6;
+ int64_t f0f7_2 = f0_2 * (int64_t) f7;
+ int64_t f0f8_2 = f0_2 * (int64_t) f8;
+ int64_t f0f9_2 = f0_2 * (int64_t) f9;
+ int64_t f1f1_2 = f1_2 * (int64_t) f1;
+ int64_t f1f2_2 = f1_2 * (int64_t) f2;
+ int64_t f1f3_4 = f1_2 * (int64_t) f3_2;
+ int64_t f1f4_2 = f1_2 * (int64_t) f4;
+ int64_t f1f5_4 = f1_2 * (int64_t) f5_2;
+ int64_t f1f6_2 = f1_2 * (int64_t) f6;
+ int64_t f1f7_4 = f1_2 * (int64_t) f7_2;
+ int64_t f1f8_2 = f1_2 * (int64_t) f8;
+ int64_t f1f9_76 = f1_2 * (int64_t) f9_38;
+ int64_t f2f2 = f2 * (int64_t) f2;
+ int64_t f2f3_2 = f2_2 * (int64_t) f3;
+ int64_t f2f4_2 = f2_2 * (int64_t) f4;
+ int64_t f2f5_2 = f2_2 * (int64_t) f5;
+ int64_t f2f6_2 = f2_2 * (int64_t) f6;
+ int64_t f2f7_2 = f2_2 * (int64_t) f7;
+ int64_t f2f8_38 = f2_2 * (int64_t) f8_19;
+ int64_t f2f9_38 = f2 * (int64_t) f9_38;
+ int64_t f3f3_2 = f3_2 * (int64_t) f3;
+ int64_t f3f4_2 = f3_2 * (int64_t) f4;
+ int64_t f3f5_4 = f3_2 * (int64_t) f5_2;
+ int64_t f3f6_2 = f3_2 * (int64_t) f6;
+ int64_t f3f7_76 = f3_2 * (int64_t) f7_38;
+ int64_t f3f8_38 = f3_2 * (int64_t) f8_19;
+ int64_t f3f9_76 = f3_2 * (int64_t) f9_38;
+ int64_t f4f4 = f4 * (int64_t) f4;
+ int64_t f4f5_2 = f4_2 * (int64_t) f5;
+ int64_t f4f6_38 = f4_2 * (int64_t) f6_19;
+ int64_t f4f7_38 = f4 * (int64_t) f7_38;
+ int64_t f4f8_38 = f4_2 * (int64_t) f8_19;
+ int64_t f4f9_38 = f4 * (int64_t) f9_38;
+ int64_t f5f5_38 = f5 * (int64_t) f5_38;
+ int64_t f5f6_38 = f5_2 * (int64_t) f6_19;
+ int64_t f5f7_76 = f5_2 * (int64_t) f7_38;
+ int64_t f5f8_38 = f5_2 * (int64_t) f8_19;
+ int64_t f5f9_76 = f5_2 * (int64_t) f9_38;
+ int64_t f6f6_19 = f6 * (int64_t) f6_19;
+ int64_t f6f7_38 = f6 * (int64_t) f7_38;
+ int64_t f6f8_38 = f6_2 * (int64_t) f8_19;
+ int64_t f6f9_38 = f6 * (int64_t) f9_38;
+ int64_t f7f7_38 = f7 * (int64_t) f7_38;
+ int64_t f7f8_38 = f7_2 * (int64_t) f8_19;
+ int64_t f7f9_76 = f7_2 * (int64_t) f9_38;
+ int64_t f8f8_19 = f8 * (int64_t) f8_19;
+ int64_t f8f9_38 = f8 * (int64_t) f9_38;
+ int64_t f9f9_38 = f9 * (int64_t) f9_38;
+
+ int64_t h0 = f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38;
+ int64_t h1 = f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38;
+ int64_t h2 = f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19;
+ int64_t h3 = f0f3_2 + f1f2_2 + f4f9_38 + f5f8_38 + f6f7_38;
+ int64_t h4 = f0f4_2 + f1f3_4 + f2f2 + f5f9_76 + f6f8_38 + f7f7_38;
+ int64_t h5 = f0f5_2 + f1f4_2 + f2f3_2 + f6f9_38 + f7f8_38;
+ int64_t h6 = f0f6_2 + f1f5_4 + f2f4_2 + f3f3_2 + f7f9_76 + f8f8_19;
+ int64_t h7 = f0f7_2 + f1f6_2 + f2f5_2 + f3f4_2 + f8f9_38;
+ int64_t h8 = f0f8_2 + f1f7_4 + f2f6_2 + f3f5_4 + f4f4 + f9f9_38;
+ int64_t h9 = f0f9_2 + f1f8_2 + f2f7_2 + f3f6_2 + f4f5_2;
+
+ int64_t carry0;
+ int64_t carry1;
+ int64_t carry2;
+ int64_t carry3;
+ int64_t carry4;
+ int64_t carry5;
+ int64_t carry6;
+ int64_t carry7;
+ int64_t carry8;
+ int64_t carry9;
+
+ carry0 = (h0 + (int64_t)(1L << 25)) >> 26;
+ h1 += carry0;
+ h0 -= carry0 * ((uint64_t) 1L << 26);
+ carry4 = (h4 + (int64_t)(1L << 25)) >> 26;
+ h5 += carry4;
+ h4 -= carry4 * ((uint64_t) 1L << 26);
+
+ carry1 = (h1 + (int64_t)(1L << 24)) >> 25;
+ h2 += carry1;
+ h1 -= carry1 * ((uint64_t) 1L << 25);
+ carry5 = (h5 + (int64_t)(1L << 24)) >> 25;
+ h6 += carry5;
+ h5 -= carry5 * ((uint64_t) 1L << 25);
+
+ carry2 = (h2 + (int64_t)(1L << 25)) >> 26;
+ h3 += carry2;
+ h2 -= carry2 * ((uint64_t) 1L << 26);
+ carry6 = (h6 + (int64_t)(1L << 25)) >> 26;
+ h7 += carry6;
+ h6 -= carry6 * ((uint64_t) 1L << 26);
+
+ carry3 = (h3 + (int64_t)(1L << 24)) >> 25;
+ h4 += carry3;
+ h3 -= carry3 * ((uint64_t) 1L << 25);
+ carry7 = (h7 + (int64_t)(1L << 24)) >> 25;
+ h8 += carry7;
+ h7 -= carry7 * ((uint64_t) 1L << 25);
+
+ carry4 = (h4 + (int64_t)(1L << 25)) >> 26;
+ h5 += carry4;
+ h4 -= carry4 * ((uint64_t) 1L << 26);
+ carry8 = (h8 + (int64_t)(1L << 25)) >> 26;
+ h9 += carry8;
+ h8 -= carry8 * ((uint64_t) 1L << 26);
+
+ carry9 = (h9 + (int64_t)(1L << 24)) >> 25;
+ h0 += carry9 * 19;
+ h9 -= carry9 * ((uint64_t) 1L << 25);
+
+ carry0 = (h0 + (int64_t)(1L << 25)) >> 26;
+ h1 += carry0;
+ h0 -= carry0 * ((uint64_t) 1L << 26);
+
+ h[0] = (int32_t) h0;
+ h[1] = (int32_t) h1;
+ h[2] = (int32_t) h2;
+ h[3] = (int32_t) h3;
+ h[4] = (int32_t) h4;
+ h[5] = (int32_t) h5;
+ h[6] = (int32_t) h6;
+ h[7] = (int32_t) h7;
+ h[8] = (int32_t) h8;
+ h[9] = (int32_t) h9;
+}
+
+/*
+ h = 2 * f * f
+ Can overlap h with f.
+ *
+ Preconditions:
+ |f| bounded by 1.65*2^26,1.65*2^25,1.65*2^26,1.65*2^25,etc.
+ *
+ Postconditions:
+ |h| bounded by 1.01*2^25,1.01*2^24,1.01*2^25,1.01*2^24,etc.
+ */
+
+static void
+fe25519_sq2(fe25519 h, const fe25519 f)
+{
+ int32_t f0 = f[0];
+ int32_t f1 = f[1];
+ int32_t f2 = f[2];
+ int32_t f3 = f[3];
+ int32_t f4 = f[4];
+ int32_t f5 = f[5];
+ int32_t f6 = f[6];
+ int32_t f7 = f[7];
+ int32_t f8 = f[8];
+ int32_t f9 = f[9];
+
+ int32_t f0_2 = 2 * f0;
+ int32_t f1_2 = 2 * f1;
+ int32_t f2_2 = 2 * f2;
+ int32_t f3_2 = 2 * f3;
+ int32_t f4_2 = 2 * f4;
+ int32_t f5_2 = 2 * f5;
+ int32_t f6_2 = 2 * f6;
+ int32_t f7_2 = 2 * f7;
+ int32_t f5_38 = 38 * f5; /* 1.959375*2^30 */
+ int32_t f6_19 = 19 * f6; /* 1.959375*2^30 */
+ int32_t f7_38 = 38 * f7; /* 1.959375*2^30 */
+ int32_t f8_19 = 19 * f8; /* 1.959375*2^30 */
+ int32_t f9_38 = 38 * f9; /* 1.959375*2^30 */
+
+ int64_t f0f0 = f0 * (int64_t) f0;
+ int64_t f0f1_2 = f0_2 * (int64_t) f1;
+ int64_t f0f2_2 = f0_2 * (int64_t) f2;
+ int64_t f0f3_2 = f0_2 * (int64_t) f3;
+ int64_t f0f4_2 = f0_2 * (int64_t) f4;
+ int64_t f0f5_2 = f0_2 * (int64_t) f5;
+ int64_t f0f6_2 = f0_2 * (int64_t) f6;
+ int64_t f0f7_2 = f0_2 * (int64_t) f7;
+ int64_t f0f8_2 = f0_2 * (int64_t) f8;
+ int64_t f0f9_2 = f0_2 * (int64_t) f9;
+ int64_t f1f1_2 = f1_2 * (int64_t) f1;
+ int64_t f1f2_2 = f1_2 * (int64_t) f2;
+ int64_t f1f3_4 = f1_2 * (int64_t) f3_2;
+ int64_t f1f4_2 = f1_2 * (int64_t) f4;
+ int64_t f1f5_4 = f1_2 * (int64_t) f5_2;
+ int64_t f1f6_2 = f1_2 * (int64_t) f6;
+ int64_t f1f7_4 = f1_2 * (int64_t) f7_2;
+ int64_t f1f8_2 = f1_2 * (int64_t) f8;
+ int64_t f1f9_76 = f1_2 * (int64_t) f9_38;
+ int64_t f2f2 = f2 * (int64_t) f2;
+ int64_t f2f3_2 = f2_2 * (int64_t) f3;
+ int64_t f2f4_2 = f2_2 * (int64_t) f4;
+ int64_t f2f5_2 = f2_2 * (int64_t) f5;
+ int64_t f2f6_2 = f2_2 * (int64_t) f6;
+ int64_t f2f7_2 = f2_2 * (int64_t) f7;
+ int64_t f2f8_38 = f2_2 * (int64_t) f8_19;
+ int64_t f2f9_38 = f2 * (int64_t) f9_38;
+ int64_t f3f3_2 = f3_2 * (int64_t) f3;
+ int64_t f3f4_2 = f3_2 * (int64_t) f4;
+ int64_t f3f5_4 = f3_2 * (int64_t) f5_2;
+ int64_t f3f6_2 = f3_2 * (int64_t) f6;
+ int64_t f3f7_76 = f3_2 * (int64_t) f7_38;
+ int64_t f3f8_38 = f3_2 * (int64_t) f8_19;
+ int64_t f3f9_76 = f3_2 * (int64_t) f9_38;
+ int64_t f4f4 = f4 * (int64_t) f4;
+ int64_t f4f5_2 = f4_2 * (int64_t) f5;
+ int64_t f4f6_38 = f4_2 * (int64_t) f6_19;
+ int64_t f4f7_38 = f4 * (int64_t) f7_38;
+ int64_t f4f8_38 = f4_2 * (int64_t) f8_19;
+ int64_t f4f9_38 = f4 * (int64_t) f9_38;
+ int64_t f5f5_38 = f5 * (int64_t) f5_38;
+ int64_t f5f6_38 = f5_2 * (int64_t) f6_19;
+ int64_t f5f7_76 = f5_2 * (int64_t) f7_38;
+ int64_t f5f8_38 = f5_2 * (int64_t) f8_19;
+ int64_t f5f9_76 = f5_2 * (int64_t) f9_38;
+ int64_t f6f6_19 = f6 * (int64_t) f6_19;
+ int64_t f6f7_38 = f6 * (int64_t) f7_38;
+ int64_t f6f8_38 = f6_2 * (int64_t) f8_19;
+ int64_t f6f9_38 = f6 * (int64_t) f9_38;
+ int64_t f7f7_38 = f7 * (int64_t) f7_38;
+ int64_t f7f8_38 = f7_2 * (int64_t) f8_19;
+ int64_t f7f9_76 = f7_2 * (int64_t) f9_38;
+ int64_t f8f8_19 = f8 * (int64_t) f8_19;
+ int64_t f8f9_38 = f8 * (int64_t) f9_38;
+ int64_t f9f9_38 = f9 * (int64_t) f9_38;
+
+ int64_t h0 = f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38;
+ int64_t h1 = f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38;
+ int64_t h2 = f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19;
+ int64_t h3 = f0f3_2 + f1f2_2 + f4f9_38 + f5f8_38 + f6f7_38;
+ int64_t h4 = f0f4_2 + f1f3_4 + f2f2 + f5f9_76 + f6f8_38 + f7f7_38;
+ int64_t h5 = f0f5_2 + f1f4_2 + f2f3_2 + f6f9_38 + f7f8_38;
+ int64_t h6 = f0f6_2 + f1f5_4 + f2f4_2 + f3f3_2 + f7f9_76 + f8f8_19;
+ int64_t h7 = f0f7_2 + f1f6_2 + f2f5_2 + f3f4_2 + f8f9_38;
+ int64_t h8 = f0f8_2 + f1f7_4 + f2f6_2 + f3f5_4 + f4f4 + f9f9_38;
+ int64_t h9 = f0f9_2 + f1f8_2 + f2f7_2 + f3f6_2 + f4f5_2;
+
+ int64_t carry0;
+ int64_t carry1;
+ int64_t carry2;
+ int64_t carry3;
+ int64_t carry4;
+ int64_t carry5;
+ int64_t carry6;
+ int64_t carry7;
+ int64_t carry8;
+ int64_t carry9;
+
+ h0 += h0;
+ h1 += h1;
+ h2 += h2;
+ h3 += h3;
+ h4 += h4;
+ h5 += h5;
+ h6 += h6;
+ h7 += h7;
+ h8 += h8;
+ h9 += h9;
+
+ carry0 = (h0 + (int64_t)(1L << 25)) >> 26;
+ h1 += carry0;
+ h0 -= carry0 * ((uint64_t) 1L << 26);
+ carry4 = (h4 + (int64_t)(1L << 25)) >> 26;
+ h5 += carry4;
+ h4 -= carry4 * ((uint64_t) 1L << 26);
+
+ carry1 = (h1 + (int64_t)(1L << 24)) >> 25;
+ h2 += carry1;
+ h1 -= carry1 * ((uint64_t) 1L << 25);
+ carry5 = (h5 + (int64_t)(1L << 24)) >> 25;
+ h6 += carry5;
+ h5 -= carry5 * ((uint64_t) 1L << 25);
+
+ carry2 = (h2 + (int64_t)(1L << 25)) >> 26;
+ h3 += carry2;
+ h2 -= carry2 * ((uint64_t) 1L << 26);
+ carry6 = (h6 + (int64_t)(1L << 25)) >> 26;
+ h7 += carry6;
+ h6 -= carry6 * ((uint64_t) 1L << 26);
+
+ carry3 = (h3 + (int64_t)(1L << 24)) >> 25;
+ h4 += carry3;
+ h3 -= carry3 * ((uint64_t) 1L << 25);
+ carry7 = (h7 + (int64_t)(1L << 24)) >> 25;
+ h8 += carry7;
+ h7 -= carry7 * ((uint64_t) 1L << 25);
+
+ carry4 = (h4 + (int64_t)(1L << 25)) >> 26;
+ h5 += carry4;
+ h4 -= carry4 * ((uint64_t) 1L << 26);
+ carry8 = (h8 + (int64_t)(1L << 25)) >> 26;
+ h9 += carry8;
+ h8 -= carry8 * ((uint64_t) 1L << 26);
+
+ carry9 = (h9 + (int64_t)(1L << 24)) >> 25;
+ h0 += carry9 * 19;
+ h9 -= carry9 * ((uint64_t) 1L << 25);
+
+ carry0 = (h0 + (int64_t)(1L << 25)) >> 26;
+ h1 += carry0;
+ h0 -= carry0 * ((uint64_t) 1L << 26);
+
+ h[0] = (int32_t) h0;
+ h[1] = (int32_t) h1;
+ h[2] = (int32_t) h2;
+ h[3] = (int32_t) h3;
+ h[4] = (int32_t) h4;
+ h[5] = (int32_t) h5;
+ h[6] = (int32_t) h6;
+ h[7] = (int32_t) h7;
+ h[8] = (int32_t) h8;
+ h[9] = (int32_t) h9;
+}
+
+static void
+fe25519_scalar_product(fe25519 h, const fe25519 f, uint32_t n)
+{
+ int64_t sn = (int64_t) n;
+ int32_t f0 = f[0];
+ int32_t f1 = f[1];
+ int32_t f2 = f[2];
+ int32_t f3 = f[3];
+ int32_t f4 = f[4];
+ int32_t f5 = f[5];
+ int32_t f6 = f[6];
+ int32_t f7 = f[7];
+ int32_t f8 = f[8];
+ int32_t f9 = f[9];
+ int64_t h0 = f0 * sn;
+ int64_t h1 = f1 * sn;
+ int64_t h2 = f2 * sn;
+ int64_t h3 = f3 * sn;
+ int64_t h4 = f4 * sn;
+ int64_t h5 = f5 * sn;
+ int64_t h6 = f6 * sn;
+ int64_t h7 = f7 * sn;
+ int64_t h8 = f8 * sn;
+ int64_t h9 = f9 * sn;
+ int64_t carry0, carry1, carry2, carry3, carry4, carry5, carry6, carry7,
+ carry8, carry9;
+
+ carry9 = (h9 + ((int64_t) 1 << 24)) >> 25;
+ h0 += carry9 * 19;
+ h9 -= carry9 * ((int64_t) 1 << 25);
+ carry1 = (h1 + ((int64_t) 1 << 24)) >> 25;
+ h2 += carry1;
+ h1 -= carry1 * ((int64_t) 1 << 25);
+ carry3 = (h3 + ((int64_t) 1 << 24)) >> 25;
+ h4 += carry3;
+ h3 -= carry3 * ((int64_t) 1 << 25);
+ carry5 = (h5 + ((int64_t) 1 << 24)) >> 25;
+ h6 += carry5;
+ h5 -= carry5 * ((int64_t) 1 << 25);
+ carry7 = (h7 + ((int64_t) 1 << 24)) >> 25;
+ h8 += carry7;
+ h7 -= carry7 * ((int64_t) 1 << 25);
+
+ carry0 = (h0 + ((int64_t) 1 << 25)) >> 26;
+ h1 += carry0;
+ h0 -= carry0 * ((int64_t) 1 << 26);
+ carry2 = (h2 + ((int64_t) 1 << 25)) >> 26;
+ h3 += carry2;
+ h2 -= carry2 * ((int64_t) 1 << 26);
+ carry4 = (h4 + ((int64_t) 1 << 25)) >> 26;
+ h5 += carry4;
+ h4 -= carry4 * ((int64_t) 1 << 26);
+ carry6 = (h6 + ((int64_t) 1 << 25)) >> 26;
+ h7 += carry6;
+ h6 -= carry6 * ((int64_t) 1 << 26);
+ carry8 = (h8 + ((int64_t) 1 << 25)) >> 26;
+ h9 += carry8;
+ h8 -= carry8 * ((int64_t) 1 << 26);
+
+ h[0] = (int32_t) h0;
+ h[1] = (int32_t) h1;
+ h[2] = (int32_t) h2;
+ h[3] = (int32_t) h3;
+ h[4] = (int32_t) h4;
+ h[5] = (int32_t) h5;
+ h[6] = (int32_t) h6;
+ h[7] = (int32_t) h7;
+ h[8] = (int32_t) h8;
+ h[9] = (int32_t) h9;
+}
diff --git a/third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10_fe_51.h b/third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10_fe_51.h
new file mode 100644
index 0000000..cd8776d
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/ed25519_ref10_fe_51.h
@@ -0,0 +1,539 @@
+/*
+ * ISC License
+ *
+ * Copyright (c) 2013-2019
+ * Frank Denis <j at pureftpd dot org>
+ *
+ * Permission to use, copy, modify, and/or 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.
+ */
+
+#include <roken.h>
+#include <string.h>
+
+#include "private/common.h"
+#include "private/quirks.h"
+#include "utils.h"
+
+/*
+ h = 0
+ */
+
+static inline void
+fe25519_0(fe25519 h)
+{
+ memset(&h[0], 0, 5 * sizeof h[0]);
+}
+
+/*
+ h = 1
+ */
+
+static inline void
+fe25519_1(fe25519 h)
+{
+ h[0] = 1;
+ memset(&h[1], 0, 4 * sizeof h[0]);
+}
+
+/*
+ h = f + g
+ Can overlap h with f or g.
+ */
+
+static inline void
+fe25519_add(fe25519 h, const fe25519 f, const fe25519 g)
+{
+ uint64_t h0 = f[0] + g[0];
+ uint64_t h1 = f[1] + g[1];
+ uint64_t h2 = f[2] + g[2];
+ uint64_t h3 = f[3] + g[3];
+ uint64_t h4 = f[4] + g[4];
+
+ h[0] = h0;
+ h[1] = h1;
+ h[2] = h2;
+ h[3] = h3;
+ h[4] = h4;
+}
+
+/*
+ h = f - g
+ */
+
+static void
+fe25519_sub(fe25519 h, const fe25519 f, const fe25519 g)
+{
+ const uint64_t mask = 0x7ffffffffffffULL;
+ uint64_t h0, h1, h2, h3, h4;
+
+ h0 = g[0];
+ h1 = g[1];
+ h2 = g[2];
+ h3 = g[3];
+ h4 = g[4];
+
+ h1 += h0 >> 51;
+ h0 &= mask;
+ h2 += h1 >> 51;
+ h1 &= mask;
+ h3 += h2 >> 51;
+ h2 &= mask;
+ h4 += h3 >> 51;
+ h3 &= mask;
+ h0 += 19ULL * (h4 >> 51);
+ h4 &= mask;
+
+ h0 = (f[0] + 0xfffffffffffdaULL) - h0;
+ h1 = (f[1] + 0xffffffffffffeULL) - h1;
+ h2 = (f[2] + 0xffffffffffffeULL) - h2;
+ h3 = (f[3] + 0xffffffffffffeULL) - h3;
+ h4 = (f[4] + 0xffffffffffffeULL) - h4;
+
+ h[0] = h0;
+ h[1] = h1;
+ h[2] = h2;
+ h[3] = h3;
+ h[4] = h4;
+}
+
+/*
+ h = -f
+ */
+
+static inline void
+fe25519_neg(fe25519 h, const fe25519 f)
+{
+ fe25519 zero;
+
+ fe25519_0(zero);
+ fe25519_sub(h, zero, f);
+}
+
+/*
+ Replace (f,g) with (g,g) if b == 1;
+ replace (f,g) with (f,g) if b == 0.
+ *
+ Preconditions: b in {0,1}.
+ */
+
+static void
+fe25519_cmov(fe25519 f, const fe25519 g, unsigned int b)
+{
+ const uint64_t mask = (uint64_t) (-(int64_t) b);
+
+ uint64_t f0 = f[0];
+ uint64_t f1 = f[1];
+ uint64_t f2 = f[2];
+ uint64_t f3 = f[3];
+ uint64_t f4 = f[4];
+
+ uint64_t x0 = f0 ^ g[0];
+ uint64_t x1 = f1 ^ g[1];
+ uint64_t x2 = f2 ^ g[2];
+ uint64_t x3 = f3 ^ g[3];
+ uint64_t x4 = f4 ^ g[4];
+
+ x0 &= mask;
+ x1 &= mask;
+ x2 &= mask;
+ x3 &= mask;
+ x4 &= mask;
+
+ f[0] = f0 ^ x0;
+ f[1] = f1 ^ x1;
+ f[2] = f2 ^ x2;
+ f[3] = f3 ^ x3;
+ f[4] = f4 ^ x4;
+}
+
+/*
+Replace (f,g) with (g,f) if b == 1;
+replace (f,g) with (f,g) if b == 0.
+
+Preconditions: b in {0,1}.
+*/
+
+static void
+fe25519_cswap(fe25519 f, fe25519 g, unsigned int b)
+{
+ const uint64_t mask = (uint64_t) (-(int64_t) b);
+
+ uint64_t f0 = f[0];
+ uint64_t f1 = f[1];
+ uint64_t f2 = f[2];
+ uint64_t f3 = f[3];
+ uint64_t f4 = f[4];
+
+ uint64_t g0 = g[0];
+ uint64_t g1 = g[1];
+ uint64_t g2 = g[2];
+ uint64_t g3 = g[3];
+ uint64_t g4 = g[4];
+
+ uint64_t x0 = f0 ^ g0;
+ uint64_t x1 = f1 ^ g1;
+ uint64_t x2 = f2 ^ g2;
+ uint64_t x3 = f3 ^ g3;
+ uint64_t x4 = f4 ^ g4;
+
+ x0 &= mask;
+ x1 &= mask;
+ x2 &= mask;
+ x3 &= mask;
+ x4 &= mask;
+
+ f[0] = f0 ^ x0;
+ f[1] = f1 ^ x1;
+ f[2] = f2 ^ x2;
+ f[3] = f3 ^ x3;
+ f[4] = f4 ^ x4;
+
+ g[0] = g0 ^ x0;
+ g[1] = g1 ^ x1;
+ g[2] = g2 ^ x2;
+ g[3] = g3 ^ x3;
+ g[4] = g4 ^ x4;
+}
+
+/*
+ h = f
+ */
+
+static inline void
+fe25519_copy(fe25519 h, const fe25519 f)
+{
+ uint64_t f0 = f[0];
+ uint64_t f1 = f[1];
+ uint64_t f2 = f[2];
+ uint64_t f3 = f[3];
+ uint64_t f4 = f[4];
+
+ h[0] = f0;
+ h[1] = f1;
+ h[2] = f2;
+ h[3] = f3;
+ h[4] = f4;
+}
+
+/*
+ return 1 if f is in {1,3,5,...,q-2}
+ return 0 if f is in {0,2,4,...,q-1}
+ */
+
+static inline int
+fe25519_isnegative(const fe25519 f)
+{
+ unsigned char s[32];
+
+ fe25519_tobytes(s, f);
+
+ return s[0] & 1;
+}
+
+/*
+ return 1 if f == 0
+ return 0 if f != 0
+ */
+
+static inline int
+fe25519_iszero(const fe25519 f)
+{
+ unsigned char s[32];
+
+ fe25519_tobytes(s, f);
+
+ return sodium_is_zero(s, 32);
+}
+
+/*
+ h = f * g
+ Can overlap h with f or g.
+ */
+
+static void
+fe25519_mul(fe25519 h, const fe25519 f, const fe25519 g)
+{
+ const uint64_t mask = 0x7ffffffffffffULL;
+ uint128_t r0, r1, r2, r3, r4, carry;
+ uint64_t f0, f1, f2, f3, f4;
+ uint64_t f1_19, f2_19, f3_19, f4_19;
+ uint64_t g0, g1, g2, g3, g4;
+ uint64_t r00, r01, r02, r03, r04;
+
+ f0 = f[0];
+ f1 = f[1];
+ f2 = f[2];
+ f3 = f[3];
+ f4 = f[4];
+
+ g0 = g[0];
+ g1 = g[1];
+ g2 = g[2];
+ g3 = g[3];
+ g4 = g[4];
+
+ f1_19 = 19ULL * f1;
+ f2_19 = 19ULL * f2;
+ f3_19 = 19ULL * f3;
+ f4_19 = 19ULL * f4;
+
+ r0 = ((uint128_t) f0 ) * ((uint128_t) g0);
+ r0 += ((uint128_t) f1_19) * ((uint128_t) g4);
+ r0 += ((uint128_t) f2_19) * ((uint128_t) g3);
+ r0 += ((uint128_t) f3_19) * ((uint128_t) g2);
+ r0 += ((uint128_t) f4_19) * ((uint128_t) g1);
+
+ r1 = ((uint128_t) f0 ) * ((uint128_t) g1);
+ r1 += ((uint128_t) f1 ) * ((uint128_t) g0);
+ r1 += ((uint128_t) f2_19) * ((uint128_t) g4);
+ r1 += ((uint128_t) f3_19) * ((uint128_t) g3);
+ r1 += ((uint128_t) f4_19) * ((uint128_t) g2);
+
+ r2 = ((uint128_t) f0 ) * ((uint128_t) g2);
+ r2 += ((uint128_t) f1 ) * ((uint128_t) g1);
+ r2 += ((uint128_t) f2 ) * ((uint128_t) g0);
+ r2 += ((uint128_t) f3_19) * ((uint128_t) g4);
+ r2 += ((uint128_t) f4_19) * ((uint128_t) g3);
+
+ r3 = ((uint128_t) f0 ) * ((uint128_t) g3);
+ r3 += ((uint128_t) f1 ) * ((uint128_t) g2);
+ r3 += ((uint128_t) f2 ) * ((uint128_t) g1);
+ r3 += ((uint128_t) f3 ) * ((uint128_t) g0);
+ r3 += ((uint128_t) f4_19) * ((uint128_t) g4);
+
+ r4 = ((uint128_t) f0 ) * ((uint128_t) g4);
+ r4 += ((uint128_t) f1 ) * ((uint128_t) g3);
+ r4 += ((uint128_t) f2 ) * ((uint128_t) g2);
+ r4 += ((uint128_t) f3 ) * ((uint128_t) g1);
+ r4 += ((uint128_t) f4 ) * ((uint128_t) g0);
+
+ r00 = ((uint64_t) r0) & mask;
+ carry = r0 >> 51;
+ r1 += carry;
+ r01 = ((uint64_t) r1) & mask;
+ carry = r1 >> 51;
+ r2 += carry;
+ r02 = ((uint64_t) r2) & mask;
+ carry = r2 >> 51;
+ r3 += carry;
+ r03 = ((uint64_t) r3) & mask;
+ carry = r3 >> 51;
+ r4 += carry;
+ r04 = ((uint64_t) r4) & mask;
+ carry = r4 >> 51;
+ r00 += 19ULL * (uint64_t) carry;
+ carry = r00 >> 51;
+ r00 &= mask;
+ r01 += (uint64_t) carry;
+ carry = r01 >> 51;
+ r01 &= mask;
+ r02 += (uint64_t) carry;
+
+ h[0] = r00;
+ h[1] = r01;
+ h[2] = r02;
+ h[3] = r03;
+ h[4] = r04;
+}
+
+/*
+ h = f * f
+ Can overlap h with f.
+ */
+
+static void
+fe25519_sq(fe25519 h, const fe25519 f)
+{
+ const uint64_t mask = 0x7ffffffffffffULL;
+ uint128_t r0, r1, r2, r3, r4, carry;
+ uint64_t f0, f1, f2, f3, f4;
+ uint64_t f0_2, f1_2, f1_38, f2_38, f3_38, f3_19, f4_19;
+ uint64_t r00, r01, r02, r03, r04;
+
+ f0 = f[0];
+ f1 = f[1];
+ f2 = f[2];
+ f3 = f[3];
+ f4 = f[4];
+
+ f0_2 = f0 << 1;
+ f1_2 = f1 << 1;
+
+ f1_38 = 38ULL * f1;
+ f2_38 = 38ULL * f2;
+ f3_38 = 38ULL * f3;
+
+ f3_19 = 19ULL * f3;
+ f4_19 = 19ULL * f4;
+
+ r0 = ((uint128_t) f0 ) * ((uint128_t) f0);
+ r0 += ((uint128_t) f1_38) * ((uint128_t) f4);
+ r0 += ((uint128_t) f2_38) * ((uint128_t) f3);
+
+ r1 = ((uint128_t) f0_2 ) * ((uint128_t) f1);
+ r1 += ((uint128_t) f2_38) * ((uint128_t) f4);
+ r1 += ((uint128_t) f3_19) * ((uint128_t) f3);
+
+ r2 = ((uint128_t) f0_2 ) * ((uint128_t) f2);
+ r2 += ((uint128_t) f1 ) * ((uint128_t) f1);
+ r2 += ((uint128_t) f3_38) * ((uint128_t) f4);
+
+ r3 = ((uint128_t) f0_2 ) * ((uint128_t) f3);
+ r3 += ((uint128_t) f1_2 ) * ((uint128_t) f2);
+ r3 += ((uint128_t) f4_19) * ((uint128_t) f4);
+
+ r4 = ((uint128_t) f0_2 ) * ((uint128_t) f4);
+ r4 += ((uint128_t) f1_2 ) * ((uint128_t) f3);
+ r4 += ((uint128_t) f2 ) * ((uint128_t) f2);
+
+ r00 = ((uint64_t) r0) & mask;
+ carry = r0 >> 51;
+ r1 += carry;
+ r01 = ((uint64_t) r1) & mask;
+ carry = r1 >> 51;
+ r2 += carry;
+ r02 = ((uint64_t) r2) & mask;
+ carry = r2 >> 51;
+ r3 += carry;
+ r03 = ((uint64_t) r3) & mask;
+ carry = r3 >> 51;
+ r4 += carry;
+ r04 = ((uint64_t) r4) & mask;
+ carry = r4 >> 51;
+ r00 += 19ULL * (uint64_t) carry;
+ carry = r00 >> 51;
+ r00 &= mask;
+ r01 += (uint64_t) carry;
+ carry = r01 >> 51;
+ r01 &= mask;
+ r02 += (uint64_t) carry;
+
+ h[0] = r00;
+ h[1] = r01;
+ h[2] = r02;
+ h[3] = r03;
+ h[4] = r04;
+}
+
+/*
+ h = 2 * f * f
+ Can overlap h with f.
+*/
+
+static void
+fe25519_sq2(fe25519 h, const fe25519 f)
+{
+ const uint64_t mask = 0x7ffffffffffffULL;
+ uint128_t r0, r1, r2, r3, r4, carry;
+ uint64_t f0, f1, f2, f3, f4;
+ uint64_t f0_2, f1_2, f1_38, f2_38, f3_38, f3_19, f4_19;
+ uint64_t r00, r01, r02, r03, r04;
+
+ f0 = f[0];
+ f1 = f[1];
+ f2 = f[2];
+ f3 = f[3];
+ f4 = f[4];
+
+ f0_2 = f0 << 1;
+ f1_2 = f1 << 1;
+
+ f1_38 = 38ULL * f1;
+ f2_38 = 38ULL * f2;
+ f3_38 = 38ULL * f3;
+
+ f3_19 = 19ULL * f3;
+ f4_19 = 19ULL * f4;
+
+ r0 = ((uint128_t) f0 ) * ((uint128_t) f0);
+ r0 += ((uint128_t) f1_38) * ((uint128_t) f4);
+ r0 += ((uint128_t) f2_38) * ((uint128_t) f3);
+
+ r1 = ((uint128_t) f0_2 ) * ((uint128_t) f1);
+ r1 += ((uint128_t) f2_38) * ((uint128_t) f4);
+ r1 += ((uint128_t) f3_19) * ((uint128_t) f3);
+
+ r2 = ((uint128_t) f0_2 ) * ((uint128_t) f2);
+ r2 += ((uint128_t) f1 ) * ((uint128_t) f1);
+ r2 += ((uint128_t) f3_38) * ((uint128_t) f4);
+
+ r3 = ((uint128_t) f0_2 ) * ((uint128_t) f3);
+ r3 += ((uint128_t) f1_2 ) * ((uint128_t) f2);
+ r3 += ((uint128_t) f4_19) * ((uint128_t) f4);
+
+ r4 = ((uint128_t) f0_2 ) * ((uint128_t) f4);
+ r4 += ((uint128_t) f1_2 ) * ((uint128_t) f3);
+ r4 += ((uint128_t) f2 ) * ((uint128_t) f2);
+
+ r0 <<= 1;
+ r1 <<= 1;
+ r2 <<= 1;
+ r3 <<= 1;
+ r4 <<= 1;
+
+ r00 = ((uint64_t) r0) & mask;
+ carry = r0 >> 51;
+ r1 += carry;
+ r01 = ((uint64_t) r1) & mask;
+ carry = r1 >> 51;
+ r2 += carry;
+ r02 = ((uint64_t) r2) & mask;
+ carry = r2 >> 51;
+ r3 += carry;
+ r03 = ((uint64_t) r3) & mask;
+ carry = r3 >> 51;
+ r4 += carry;
+ r04 = ((uint64_t) r4) & mask;
+ carry = r4 >> 51;
+ r00 += 19ULL * (uint64_t) carry;
+ carry = r00 >> 51;
+ r00 &= mask;
+ r01 += (uint64_t) carry;
+ carry = r01 >> 51;
+ r01 &= mask;
+ r02 += (uint64_t) carry;
+
+ h[0] = r00;
+ h[1] = r01;
+ h[2] = r02;
+ h[3] = r03;
+ h[4] = r04;
+}
+
+static void
+fe25519_scalar_product(fe25519 h, const fe25519 f, uint32_t n)
+{
+ const uint64_t mask = 0x7ffffffffffffULL;
+ uint128_t a;
+ uint128_t sn = (uint128_t) n;
+ uint64_t h0, h1, h2, h3, h4;
+
+ a = f[0] * sn;
+ h0 = ((uint64_t) a) & mask;
+ a = f[1] * sn + ((uint64_t) (a >> 51));
+ h1 = ((uint64_t) a) & mask;
+ a = f[2] * sn + ((uint64_t) (a >> 51));
+ h2 = ((uint64_t) a) & mask;
+ a = f[3] * sn + ((uint64_t) (a >> 51));
+ h3 = ((uint64_t) a) & mask;
+ a = f[4] * sn + ((uint64_t) (a >> 51));
+ h4 = ((uint64_t) a) & mask;
+
+ h0 += (a >> 51) * 19ULL;
+
+ h[0] = h0;
+ h[1] = h1;
+ h[2] = h2;
+ h[3] = h3;
+ h[4] = h4;
+}
diff --git a/third_party/heimdal/lib/hcrypto/x25519/fe_25_5/base.h b/third_party/heimdal/lib/hcrypto/x25519/fe_25_5/base.h
new file mode 100644
index 0000000..e18530b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/fe_25_5/base.h
@@ -0,0 +1,1344 @@
+{ /* 0/31 */
+ {
+ { 25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605 },
+ { -12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378 },
+ { -8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546 }
+ },
+ {
+ { -12815894, -12976347, -21581243, 11784320, -25355658, -2750717, -11717903, -3814571, -358445, -10211303 },
+ { -21703237, 6903825, 27185491, 6451973, -29577724, -9554005, -15616551, 11189268, -26829678, -5319081 },
+ { 26966642, 11152617, 32442495, 15396054, 14353839, -12752335, -3128826, -9541118, -15472047, -4166697 }
+ },
+ {
+ { 15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024 },
+ { 16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574 },
+ { 30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357 }
+ },
+ {
+ { -17036878, 13921892, 10945806, -6033431, 27105052, -16084379, -28926210, 15006023, 3284568, -6276540 },
+ { 23599295, -8306047, -11193664, -7687416, 13236774, 10506355, 7464579, 9656445, 13059162, 10374397 },
+ { 7798556, 16710257, 3033922, 2874086, 28997861, 2835604, 32406664, -3839045, -641708, -101325 }
+ },
+ {
+ { 10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380 },
+ { 4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306 },
+ { 19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942 }
+ },
+ {
+ { -15371964, -12862754, 32573250, 4720197, -26436522, 5875511, -19188627, -15224819, -9818940, -12085777 },
+ { -8549212, 109983, 15149363, 2178705, 22900618, 4543417, 3044240, -15689887, 1762328, 14866737 },
+ { -18199695, -15951423, -10473290, 1707278, -17185920, 3916101, -28236412, 3959421, 27914454, 4383652 }
+ },
+ {
+ { 5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766 },
+ { -30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701 },
+ { 28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300 }
+ },
+ {
+ { 14499471, -2729599, -33191113, -4254652, 28494862, 14271267, 30290735, 10876454, -33154098, 2381726 },
+ { -7195431, -2655363, -14730155, 462251, -27724326, 3941372, -6236617, 3696005, -32300832, 15351955 },
+ { 27431194, 8222322, 16448760, -3907995, -18707002, 11938355, -32961401, -2970515, 29551813, 10109425 }
+ }
+},
+{ /* 1/31 */
+ {
+ { -13657040, -13155431, -31283750, 11777098, 21447386, 6519384, -2378284, -1627556, 10092783, -4764171 },
+ { 27939166, 14210322, 4677035, 16277044, -22964462, -12398139, -32508754, 12005538, -17810127, 12803510 },
+ { 17228999, -15661624, -1233527, 300140, -1224870, -11714777, 30364213, -9038194, 18016357, 4397660 }
+ },
+ {
+ { -10958843, -7690207, 4776341, -14954238, 27850028, -15602212, -26619106, 14544525, -17477504, 982639 },
+ { 29253598, 15796703, -2863982, -9908884, 10057023, 3163536, 7332899, -4120128, -21047696, 9934963 },
+ { 5793303, 16271923, -24131614, -10116404, 29188560, 1206517, -14747930, 4559895, -30123922, -10897950 }
+ },
+ {
+ { -27643952, -11493006, 16282657, -11036493, 28414021, -15012264, 24191034, 4541697, -13338309, 5500568 },
+ { 12650548, -1497113, 9052871, 11355358, -17680037, -8400164, -17430592, 12264343, 10874051, 13524335 },
+ { 25556948, -3045990, 714651, 2510400, 23394682, -10415330, 33119038, 5080568, -22528059, 5376628 }
+ },
+ {
+ { -26088264, -4011052, -17013699, -3537628, -6726793, 1920897, -22321305, -9447443, 4535768, 1569007 },
+ { -2255422, 14606630, -21692440, -8039818, 28430649, 8775819, -30494562, 3044290, 31848280, 12543772 },
+ { -22028579, 2943893, -31857513, 6777306, 13784462, -4292203, -27377195, -2062731, 7718482, 14474653 }
+ },
+ {
+ { 2385315, 2454213, -22631320, 46603, -4437935, -15680415, 656965, -7236665, 24316168, -5253567 },
+ { 13741529, 10911568, -33233417, -8603737, -20177830, -1033297, 33040651, -13424532, -20729456, 8321686 },
+ { 21060490, -2212744, 15712757, -4336099, 1639040, 10656336, 23845965, -11874838, -9984458, 608372 }
+ },
+ {
+ { -13672732, -15087586, -10889693, -7557059, -6036909, 11305547, 1123968, -6780577, 27229399, 23887 },
+ { -23244140, -294205, -11744728, 14712571, -29465699, -2029617, 12797024, -6440308, -1633405, 16678954 },
+ { -29500620, 4770662, -16054387, 14001338, 7830047, 9564805, -1508144, -4795045, -17169265, 4904953 }
+ },
+ {
+ { 24059557, 14617003, 19037157, -15039908, 19766093, -14906429, 5169211, 16191880, 2128236, -4326833 },
+ { -16981152, 4124966, -8540610, -10653797, 30336522, -14105247, -29806336, 916033, -6882542, -2986532 },
+ { -22630907, 12419372, -7134229, -7473371, -16478904, 16739175, 285431, 2763829, 15736322, 4143876 }
+ },
+ {
+ { 2379352, 11839345, -4110402, -5988665, 11274298, 794957, 212801, -14594663, 23527084, -16458268 },
+ { 33431127, -11130478, -17838966, -15626900, 8909499, 8376530, -32625340, 4087881, -15188911, -14416214 },
+ { 1767683, 7197987, -13205226, -2022635, -13091350, 448826, 5799055, 4357868, -4774191, -16323038 }
+ }
+},
+{ /* 2/31 */
+ {
+ { 6721966, 13833823, -23523388, -1551314, 26354293, -11863321, 23365147, -3949732, 7390890, 2759800 },
+ { 4409041, 2052381, 23373853, 10530217, 7676779, -12885954, 21302353, -4264057, 1244380, -12919645 },
+ { -4421239, 7169619, 4982368, -2957590, 30256825, -2777540, 14086413, 9208236, 15886429, 16489664 }
+ },
+ {
+ { 1996075, 10375649, 14346367, 13311202, -6874135, -16438411, -13693198, 398369, -30606455, -712933 },
+ { -25307465, 9795880, -2777414, 14878809, -33531835, 14780363, 13348553, 12076947, -30836462, 5113182 },
+ { -17770784, 11797796, 31950843, 13929123, -25888302, 12288344, -30341101, -7336386, 13847711, 5387222 }
+ },
+ {
+ { -18582163, -3416217, 17824843, -2340966, 22744343, -10442611, 8763061, 3617786, -19600662, 10370991 },
+ { 20246567, -14369378, 22358229, -543712, 18507283, -10413996, 14554437, -8746092, 32232924, 16763880 },
+ { 9648505, 10094563, 26416693, 14745928, -30374318, -6472621, 11094161, 15689506, 3140038, -16510092 }
+ },
+ {
+ { -16160072, 5472695, 31895588, 4744994, 8823515, 10365685, -27224800, 9448613, -28774454, 366295 },
+ { 19153450, 11523972, -11096490, -6503142, -24647631, 5420647, 28344573, 8041113, 719605, 11671788 },
+ { 8678025, 2694440, -6808014, 2517372, 4964326, 11152271, -15432916, -15266516, 27000813, -10195553 }
+ },
+ {
+ { -15157904, 7134312, 8639287, -2814877, -7235688, 10421742, 564065, 5336097, 6750977, -14521026 },
+ { 11836410, -3979488, 26297894, 16080799, 23455045, 15735944, 1695823, -8819122, 8169720, 16220347 },
+ { -18115838, 8653647, 17578566, -6092619, -8025777, -16012763, -11144307, -2627664, -5990708, -14166033 }
+ },
+ {
+ { -23308498, -10968312, 15213228, -10081214, -30853605, -11050004, 27884329, 2847284, 2655861, 1738395 },
+ { -27537433, -14253021, -25336301, -8002780, -9370762, 8129821, 21651608, -3239336, -19087449, -11005278 },
+ { 1533110, 3437855, 23735889, 459276, 29970501, 11335377, 26030092, 5821408, 10478196, 8544890 }
+ },
+ {
+ { 32173121, -16129311, 24896207, 3921497, 22579056, -3410854, 19270449, 12217473, 17789017, -3395995 },
+ { -30552961, -2228401, -15578829, -10147201, 13243889, 517024, 15479401, -3853233, 30460520, 1052596 },
+ { -11614875, 13323618, 32618793, 8175907, -15230173, 12596687, 27491595, -4612359, 3179268, -9478891 }
+ },
+ {
+ { 31947069, -14366651, -4640583, -15339921, -15125977, -6039709, -14756777, -16411740, 19072640, -9511060 },
+ { 11685058, 11822410, 3158003, -13952594, 33402194, -4165066, 5977896, -5215017, 473099, 5040608 },
+ { -20290863, 8198642, -27410132, 11602123, 1290375, -2799760, 28326862, 1721092, -19558642, -3131606 }
+ }
+},
+{ /* 3/31 */
+ {
+ { 7881532, 10687937, 7578723, 7738378, -18951012, -2553952, 21820786, 8076149, -27868496, 11538389 },
+ { -19935666, 3899861, 18283497, -6801568, -15728660, -11249211, 8754525, 7446702, -5676054, 5797016 },
+ { -11295600, -3793569, -15782110, -7964573, 12708869, -8456199, 2014099, -9050574, -2369172, -5877341 }
+ },
+ {
+ { -22472376, -11568741, -27682020, 1146375, 18956691, 16640559, 1192730, -3714199, 15123619, 10811505 },
+ { 14352098, -3419715, -18942044, 10822655, 32750596, 4699007, -70363, 15776356, -28886779, -11974553 },
+ { -28241164, -8072475, -4978962, -5315317, 29416931, 1847569, -20654173, -16484855, 4714547, -9600655 }
+ },
+ {
+ { 15200332, 8368572, 19679101, 15970074, -31872674, 1959451, 24611599, -4543832, -11745876, 12340220 },
+ { 12876937, -10480056, 33134381, 6590940, -6307776, 14872440, 9613953, 8241152, 15370987, 9608631 },
+ { -4143277, -12014408, 8446281, -391603, 4407738, 13629032, -7724868, 15866074, -28210621, -8814099 }
+ },
+ {
+ { 26660628, -15677655, 8393734, 358047, -7401291, 992988, -23904233, 858697, 20571223, 8420556 },
+ { 14620715, 13067227, -15447274, 8264467, 14106269, 15080814, 33531827, 12516406, -21574435, -12476749 },
+ { 236881, 10476226, 57258, -14677024, 6472998, 2466984, 17258519, 7256740, 8791136, 15069930 }
+ },
+ {
+ { 1276410, -9371918, 22949635, -16322807, -23493039, -5702186, 14711875, 4874229, -30663140, -2331391 },
+ { 5855666, 4990204, -13711848, 7294284, -7804282, 1924647, -1423175, -7912378, -33069337, 9234253 },
+ { 20590503, -9018988, 31529744, -7352666, -2706834, 10650548, 31559055, -11609587, 18979186, 13396066 }
+ },
+ {
+ { 24474287, 4968103, 22267082, 4407354, 24063882, -8325180, -18816887, 13594782, 33514650, 7021958 },
+ { -11566906, -6565505, -21365085, 15928892, -26158305, 4315421, -25948728, -3916677, -21480480, 12868082 },
+ { -28635013, 13504661, 19988037, -2132761, 21078225, 6443208, -21446107, 2244500, -12455797, -8089383 }
+ },
+ {
+ { -30595528, 13793479, -5852820, 319136, -25723172, -6263899, 33086546, 8957937, -15233648, 5540521 },
+ { -11630176, -11503902, -8119500, -7643073, 2620056, 1022908, -23710744, -1568984, -16128528, -14962807 },
+ { 23152971, 775386, 27395463, 14006635, -9701118, 4649512, 1689819, 892185, -11513277, -15205948 }
+ },
+ {
+ { 9770129, 9586738, 26496094, 4324120, 1556511, -3550024, 27453819, 4763127, -19179614, 5867134 },
+ { -32765025, 1927590, 31726409, -4753295, 23962434, -16019500, 27846559, 5931263, -29749703, -16108455 },
+ { 27461885, -2977536, 22380810, 1815854, -23033753, -3031938, 7283490, -15148073, -19526700, 7734629 }
+ }
+},
+{ /* 4/31 */
+ {
+ { -8010264, -9590817, -11120403, 6196038, 29344158, -13430885, 7585295, -3176626, 18549497, 15302069 },
+ { -32658337, -6171222, -7672793, -11051681, 6258878, 13504381, 10458790, -6418461, -8872242, 8424746 },
+ { 24687205, 8613276, -30667046, -3233545, 1863892, -1830544, 19206234, 7134917, -11284482, -828919 }
+ },
+ {
+ { 11334899, -9218022, 8025293, 12707519, 17523892, -10476071, 10243738, -14685461, -5066034, 16498837 },
+ { 8911542, 6887158, -9584260, -6958590, 11145641, -9543680, 17303925, -14124238, 6536641, 10543906 },
+ { -28946384, 15479763, -17466835, 568876, -1497683, 11223454, -2669190, -16625574, -27235709, 8876771 }
+ },
+ {
+ { -25742899, -12566864, -15649966, -846607, -33026686, -796288, -33481822, 15824474, -604426, -9039817 },
+ { 10330056, 70051, 7957388, -9002667, 9764902, 15609756, 27698697, -4890037, 1657394, 3084098 },
+ { 10477963, -7470260, 12119566, -13250805, 29016247, -5365589, 31280319, 14396151, -30233575, 15272409 }
+ },
+ {
+ { -12288309, 3169463, 28813183, 16658753, 25116432, -5630466, -25173957, -12636138, -25014757, 1950504 },
+ { -26180358, 9489187, 11053416, -14746161, -31053720, 5825630, -8384306, -8767532, 15341279, 8373727 },
+ { 28685821, 7759505, -14378516, -12002860, -31971820, 4079242, 298136, -10232602, -2878207, 15190420 }
+ },
+ {
+ { -32932876, 13806336, -14337485, -15794431, -24004620, 10940928, 8669718, 2742393, -26033313, -6875003 },
+ { -1580388, -11729417, -25979658, -11445023, -17411874, -10912854, 9291594, -16247779, -12154742, 6048605 },
+ { -30305315, 14843444, 1539301, 11864366, 20201677, 1900163, 13934231, 5128323, 11213262, 9168384 }
+ },
+ {
+ { -26280513, 11007847, 19408960, -940758, -18592965, -4328580, -5088060, -11105150, 20470157, -16398701 },
+ { -23136053, 9282192, 14855179, -15390078, -7362815, -14408560, -22783952, 14461608, 14042978, 5230683 },
+ { 29969567, -2741594, -16711867, -8552442, 9175486, -2468974, 21556951, 3506042, -5933891, -12449708 }
+ },
+ {
+ { -3144746, 8744661, 19704003, 4581278, -20430686, 6830683, -21284170, 8971513, -28539189, 15326563 },
+ { -19464629, 10110288, -17262528, -3503892, -23500387, 1355669, -15523050, 15300988, -20514118, 9168260 },
+ { -5353335, 4488613, -23803248, 16314347, 7780487, -15638939, -28948358, 9601605, 33087103, -9011387 }
+ },
+ {
+ { -19443170, -15512900, -20797467, -12445323, -29824447, 10229461, -27444329, -15000531, -5996870, 15664672 },
+ { 23294591, -16632613, -22650781, -8470978, 27844204, 11461195, 13099750, -2460356, 18151676, 13417686 },
+ { -24722913, -4176517, -31150679, 5988919, -26858785, 6685065, 1661597, -12551441, 15271676, -15452665 }
+ }
+},
+{ /* 5/31 */
+ {
+ { 11433042, -13228665, 8239631, -5279517, -1985436, -725718, -18698764, 2167544, -6921301, -13440182 },
+ { -31436171, 15575146, 30436815, 12192228, -22463353, 9395379, -9917708, -8638997, 12215110, 12028277 },
+ { 14098400, 6555944, 23007258, 5757252, -15427832, -12950502, 30123440, 4617780, -16900089, -655628 }
+ },
+ {
+ { -4026201, -15240835, 11893168, 13718664, -14809462, 1847385, -15819999, 10154009, 23973261, -12684474 },
+ { -26531820, -3695990, -1908898, 2534301, -31870557, -16550355, 18341390, -11419951, 32013174, -10103539 },
+ { -25479301, 10876443, -11771086, -14625140, -12369567, 1838104, 21911214, 6354752, 4425632, -837822 }
+ },
+ {
+ { -10433389, -14612966, 22229858, -3091047, -13191166, 776729, -17415375, -12020462, 4725005, 14044970 },
+ { 19268650, -7304421, 1555349, 8692754, -21474059, -9910664, 6347390, -1411784, -19522291, -16109756 },
+ { -24864089, 12986008, -10898878, -5558584, -11312371, -148526, 19541418, 8180106, 9282262, 10282508 }
+ },
+ {
+ { -26205082, 4428547, -8661196, -13194263, 4098402, -14165257, 15522535, 8372215, 5542595, -10702683 },
+ { -10562541, 14895633, 26814552, -16673850, -17480754, -2489360, -2781891, 6993761, -18093885, 10114655 },
+ { -20107055, -929418, 31422704, 10427861, -7110749, 6150669, -29091755, -11529146, 25953725, -106158 }
+ },
+ {
+ { -4234397, -8039292, -9119125, 3046000, 2101609, -12607294, 19390020, 6094296, -3315279, 12831125 },
+ { -15998678, 7578152, 5310217, 14408357, -33548620, -224739, 31575954, 6326196, 7381791, -2421839 },
+ { -20902779, 3296811, 24736065, -16328389, 18374254, 7318640, 6295303, 8082724, -15362489, 12339664 }
+ },
+ {
+ { 27724736, 2291157, 6088201, -14184798, 1792727, 5857634, 13848414, 15768922, 25091167, 14856294 },
+ { -18866652, 8331043, 24373479, 8541013, -701998, -9269457, 12927300, -12695493, -22182473, -9012899 },
+ { -11423429, -5421590, 11632845, 3405020, 30536730, -11674039, -27260765, 13866390, 30146206, 9142070 }
+ },
+ {
+ { 3924129, -15307516, -13817122, -10054960, 12291820, -668366, -27702774, 9326384, -8237858, 4171294 },
+ { -15921940, 16037937, 6713787, 16606682, -21612135, 2790944, 26396185, 3731949, 345228, -5462949 },
+ { -21327538, 13448259, 25284571, 1143661, 20614966, -8849387, 2031539, -12391231, -16253183, -13582083 }
+ },
+ {
+ { 31016211, -16722429, 26371392, -14451233, -5027349, 14854137, 17477601, 3842657, 28012650, -16405420 },
+ { -5075835, 9368966, -8562079, -4600902, -15249953, 6970560, -9189873, 16292057, -8867157, 3507940 },
+ { 29439664, 3537914, 23333589, 6997794, -17555561, -11018068, -15209202, -15051267, -9164929, 6580396 }
+ }
+},
+{ /* 6/31 */
+ {
+ { -12185861, -7679788, 16438269, 10826160, -8696817, -6235611, 17860444, -9273846, -2095802, 9304567 },
+ { 20714564, -4336911, 29088195, 7406487, 11426967, -5095705, 14792667, -14608617, 5289421, -477127 },
+ { -16665533, -10650790, -6160345, -13305760, 9192020, -1802462, 17271490, 12349094, 26939669, -3752294 }
+ },
+ {
+ { -12889898, 9373458, 31595848, 16374215, 21471720, 13221525, -27283495, -12348559, -3698806, 117887 },
+ { 22263325, -6560050, 3984570, -11174646, -15114008, -566785, 28311253, 5358056, -23319780, 541964 },
+ { 16259219, 3261970, 2309254, -15534474, -16885711, -4581916, 24134070, -16705829, -13337066, -13552195 }
+ },
+ {
+ { 9378160, -13140186, -22845982, -12745264, 28198281, -7244098, -2399684, -717351, 690426, 14876244 },
+ { 24977353, -314384, -8223969, -13465086, 28432343, -1176353, -13068804, -12297348, -22380984, 6618999 },
+ { -1538174, 11685646, 12944378, 13682314, -24389511, -14413193, 8044829, -13817328, 32239829, -5652762 }
+ },
+ {
+ { -18603066, 4762990, -926250, 8885304, -28412480, -3187315, 9781647, -10350059, 32779359, 5095274 },
+ { -33008130, -5214506, -32264887, -3685216, 9460461, -9327423, -24601656, 14506724, 21639561, -2630236 },
+ { -16400943, -13112215, 25239338, 15531969, 3987758, -4499318, -1289502, -6863535, 17874574, 558605 }
+ },
+ {
+ { -13600129, 10240081, 9171883, 16131053, -20869254, 9599700, 33499487, 5080151, 2085892, 5119761 },
+ { -22205145, -2519528, -16381601, 414691, -25019550, 2170430, 30634760, -8363614, -31999993, -5759884 },
+ { -6845704, 15791202, 8550074, -1312654, 29928809, -12092256, 27534430, -7192145, -22351378, 12961482 }
+ },
+ {
+ { -24492060, -9570771, 10368194, 11582341, -23397293, -2245287, 16533930, 8206996, -30194652, -5159638 },
+ { -11121496, -3382234, 2307366, 6362031, -135455, 8868177, -16835630, 7031275, 7589640, 8945490 },
+ { -32152748, 8917967, 6661220, -11677616, -1192060, -15793393, 7251489, -11182180, 24099109, -14456170 }
+ },
+ {
+ { 5019558, -7907470, 4244127, -14714356, -26933272, 6453165, -19118182, -13289025, -6231896, -10280736 },
+ { 10853594, 10721687, 26480089, 5861829, -22995819, 1972175, -1866647, -10557898, -3363451, -6441124 },
+ { -17002408, 5906790, 221599, -6563147, 7828208, -13248918, 24362661, -2008168, -13866408, 7421392 }
+ },
+ {
+ { 8139927, -6546497, 32257646, -5890546, 30375719, 1886181, -21175108, 15441252, 28826358, -4123029 },
+ { 6267086, 9695052, 7709135, -16603597, -32869068, -1886135, 14795160, -7840124, 13746021, -1742048 },
+ { 28584902, 7787108, -6732942, -15050729, 22846041, -7571236, -3181936, -363524, 4771362, -8419958 }
+ }
+},
+{ /* 7/31 */
+ {
+ { 24949256, 6376279, -27466481, -8174608, -18646154, -9930606, 33543569, -12141695, 3569627, 11342593 },
+ { 26514989, 4740088, 27912651, 3697550, 19331575, -11472339, 6809886, 4608608, 7325975, -14801071 },
+ { -11618399, -14554430, -24321212, 7655128, -1369274, 5214312, -27400540, 10258390, -17646694, -8186692 }
+ },
+ {
+ { 11431204, 15823007, 26570245, 14329124, 18029990, 4796082, -31446179, 15580664, 9280358, -3973687 },
+ { -160783, -10326257, -22855316, -4304997, -20861367, -13621002, -32810901, -11181622, -15545091, 4387441 },
+ { -20799378, 12194512, 3937617, -5805892, -27154820, 9340370, -24513992, 8548137, 20617071, -7482001 }
+ },
+ {
+ { -938825, -3930586, -8714311, 16124718, 24603125, -6225393, -13775352, -11875822, 24345683, 10325460 },
+ { -19855277, -1568885, -22202708, 8714034, 14007766, 6928528, 16318175, -1010689, 4766743, 3552007 },
+ { -21751364, -16730916, 1351763, -803421, -4009670, 3950935, 3217514, 14481909, 10988822, -3994762 }
+ },
+ {
+ { 15564307, -14311570, 3101243, 5684148, 30446780, -8051356, 12677127, -6505343, -8295852, 13296005 },
+ { -9442290, 6624296, -30298964, -11913677, -4670981, -2057379, 31521204, 9614054, -30000824, 12074674 },
+ { 4771191, -135239, 14290749, -13089852, 27992298, 14998318, -1413936, -1556716, 29832613, -16391035 }
+ },
+ {
+ { 7064884, -7541174, -19161962, -5067537, -18891269, -2912736, 25825242, 5293297, -27122660, 13101590 },
+ { -2298563, 2439670, -7466610, 1719965, -27267541, -16328445, 32512469, -5317593, -30356070, -4190957 },
+ { -30006540, 10162316, -33180176, 3981723, -16482138, -13070044, 14413974, 9515896, 19568978, 9628812 }
+ },
+ {
+ { 33053803, 199357, 15894591, 1583059, 27380243, -4580435, -17838894, -6106839, -6291786, 3437740 },
+ { -18978877, 3884493, 19469877, 12726490, 15913552, 13614290, -22961733, 70104, 7463304, 4176122 },
+ { -27124001, 10659917, 11482427, -16070381, 12771467, -6635117, -32719404, -5322751, 24216882, 5944158 }
+ },
+ {
+ { 8894125, 7450974, -2664149, -9765752, -28080517, -12389115, 19345746, 14680796, 11632993, 5847885 },
+ { 26942781, -2315317, 9129564, -4906607, 26024105, 11769399, -11518837, 6367194, -9727230, 4782140 },
+ { 19916461, -4828410, -22910704, -11414391, 25606324, -5972441, 33253853, 8220911, 6358847, -1873857 }
+ },
+ {
+ { 801428, -2081702, 16569428, 11065167, 29875704, 96627, 7908388, -4480480, -13538503, 1387155 },
+ { 19646058, 5720633, -11416706, 12814209, 11607948, 12749789, 14147075, 15156355, -21866831, 11835260 },
+ { 19299512, 1155910, 28703737, 14890794, 2925026, 7269399, 26121523, 15467869, -26560550, 5052483 }
+ }
+},
+{ /* 8/31 */
+ {
+ { -3017432, 10058206, 1980837, 3964243, 22160966, 12322533, -6431123, -12618185, 12228557, -7003677 },
+ { 32944382, 14922211, -22844894, 5188528, 21913450, -8719943, 4001465, 13238564, -6114803, 8653815 },
+ { 22865569, -4652735, 27603668, -12545395, 14348958, 8234005, 24808405, 5719875, 28483275, 2841751 }
+ },
+ {
+ { -16420968, -1113305, -327719, -12107856, 21886282, -15552774, -1887966, -315658, 19932058, -12739203 },
+ { -11656086, 10087521, -8864888, -5536143, -19278573, -3055912, 3999228, 13239134, -4777469, -13910208 },
+ { 1382174, -11694719, 17266790, 9194690, -13324356, 9720081, 20403944, 11284705, -14013818, 3093230 }
+ },
+ {
+ { 16650921, -11037932, -1064178, 1570629, -8329746, 7352753, -302424, 16271225, -24049421, -6691850 },
+ { -21911077, -5927941, -4611316, -5560156, -31744103, -10785293, 24123614, 15193618, -21652117, -16739389 },
+ { -9935934, -4289447, -25279823, 4372842, 2087473, 10399484, 31870908, 14690798, 17361620, 11864968 }
+ },
+ {
+ { -11307610, 6210372, 13206574, 5806320, -29017692, -13967200, -12331205, -7486601, -25578460, -16240689 },
+ { 14668462, -12270235, 26039039, 15305210, 25515617, 4542480, 10453892, 6577524, 9145645, -6443880 },
+ { 5974874, 3053895, -9433049, -10385191, -31865124, 3225009, -7972642, 3936128, -5652273, -3050304 }
+ },
+ {
+ { 30625386, -4729400, -25555961, -12792866, -20484575, 7695099, 17097188, -16303496, -27999779, 1803632 },
+ { -3553091, 9865099, -5228566, 4272701, -5673832, -16689700, 14911344, 12196514, -21405489, 7047412 },
+ { 20093277, 9920966, -11138194, -5343857, 13161587, 12044805, -32856851, 4124601, -32343828, -10257566 }
+ },
+ {
+ { -20788824, 14084654, -13531713, 7842147, 19119038, -13822605, 4752377, -8714640, -21679658, 2288038 },
+ { -26819236, -3283715, 29965059, 3039786, -14473765, 2540457, 29457502, 14625692, -24819617, 12570232 },
+ { -1063558, -11551823, 16920318, 12494842, 1278292, -5869109, -21159943, -3498680, -11974704, 4724943 }
+ },
+ {
+ { 17960970, -11775534, -4140968, -9702530, -8876562, -1410617, -12907383, -8659932, -29576300, 1903856 },
+ { 23134274, -14279132, -10681997, -1611936, 20684485, 15770816, -12989750, 3190296, 26955097, 14109738 },
+ { 15308788, 5320727, -30113809, -14318877, 22902008, 7767164, 29425325, -11277562, 31960942, 11934971 }
+ },
+ {
+ { -27395711, 8435796, 4109644, 12222639, -24627868, 14818669, 20638173, 4875028, 10491392, 1379718 },
+ { -13159415, 9197841, 3875503, -8936108, -1383712, -5879801, 33518459, 16176658, 21432314, 12180697 },
+ { -11787308, 11500838, 13787581, -13832590, -22430679, 10140205, 1465425, 12689540, -10301319, -13872883 }
+ }
+},
+{ /* 9/31 */
+ {
+ { 5414091, -15386041, -21007664, 9643570, 12834970, 1186149, -2622916, -1342231, 26128231, 6032912 },
+ { -26337395, -13766162, 32496025, -13653919, 17847801, -12669156, 3604025, 8316894, -25875034, -10437358 },
+ { 3296484, 6223048, 24680646, -12246460, -23052020, 5903205, -8862297, -4639164, 12376617, 3188849 }
+ },
+ {
+ { 29190488, -14659046, 27549113, -1183516, 3520066, -10697301, 32049515, -7309113, -16109234, -9852307 },
+ { -14744486, -9309156, 735818, -598978, -20407687, -5057904, 25246078, -15795669, 18640741, -960977 },
+ { -6928835, -16430795, 10361374, 5642961, 4910474, 12345252, -31638386, -494430, 10530747, 1053335 }
+ },
+ {
+ { -29265967, -14186805, -13538216, -12117373, -19457059, -10655384, -31462369, -2948985, 24018831, 15026644 },
+ { -22592535, -3145277, -2289276, 5953843, -13440189, 9425631, 25310643, 13003497, -2314791, -15145616 },
+ { -27419985, -603321, -8043984, -1669117, -26092265, 13987819, -27297622, 187899, -23166419, -2531735 }
+ },
+ {
+ { -21744398, -13810475, 1844840, 5021428, -10434399, -15911473, 9716667, 16266922, -5070217, 726099 },
+ { 29370922, -6053998, 7334071, -15342259, 9385287, 2247707, -13661962, -4839461, 30007388, -15823341 },
+ { -936379, 16086691, 23751945, -543318, -1167538, -5189036, 9137109, 730663, 9835848, 4555336 }
+ },
+ {
+ { -23376435, 1410446, -22253753, -12899614, 30867635, 15826977, 17693930, 544696, -11985298, 12422646 },
+ { 31117226, -12215734, -13502838, 6561947, -9876867, -12757670, -5118685, -4096706, 29120153, 13924425 },
+ { -17400879, -14233209, 19675799, -2734756, -11006962, -5858820, -9383939, -11317700, 7240931, -237388 }
+ },
+ {
+ { -31361739, -11346780, -15007447, -5856218, -22453340, -12152771, 1222336, 4389483, 3293637, -15551743 },
+ { -16684801, -14444245, 11038544, 11054958, -13801175, -3338533, -24319580, 7733547, 12796905, -6335822 },
+ { -8759414, -10817836, -25418864, 10783769, -30615557, -9746811, -28253339, 3647836, 3222231, -11160462 }
+ },
+ {
+ { 18606113, 1693100, -25448386, -15170272, 4112353, 10045021, 23603893, -2048234, -7550776, 2484985 },
+ { 9255317, -3131197, -12156162, -1004256, 13098013, -9214866, 16377220, -2102812, -19802075, -3034702 },
+ { -22729289, 7496160, -5742199, 11329249, 19991973, -3347502, -31718148, 9936966, -30097688, -10618797 }
+ },
+ {
+ { 21878590, -5001297, 4338336, 13643897, -3036865, 13160960, 19708896, 5415497, -7360503, -4109293 },
+ { 27736861, 10103576, 12500508, 8502413, -3413016, -9633558, 10436918, -1550276, -23659143, -8132100 },
+ { 19492550, -12104365, -29681976, -852630, -3208171, 12403437, 30066266, 8367329, 13243957, 8709688 }
+ }
+},
+{ /* 10/31 */
+ {
+ { 12015105, 2801261, 28198131, 10151021, 24818120, -4743133, -11194191, -5645734, 5150968, 7274186 },
+ { 2831366, -12492146, 1478975, 6122054, 23825128, -12733586, 31097299, 6083058, 31021603, -9793610 },
+ { -2529932, -2229646, 445613, 10720828, -13849527, -11505937, -23507731, 16354465, 15067285, -14147707 }
+ },
+ {
+ { 7840942, 14037873, -33364863, 15934016, -728213, -3642706, 21403988, 1057586, -19379462, -12403220 },
+ { 915865, -16469274, 15608285, -8789130, -24357026, 6060030, -17371319, 8410997, -7220461, 16527025 },
+ { 32922597, -556987, 20336074, -16184568, 10903705, -5384487, 16957574, 52992, 23834301, 6588044 }
+ },
+ {
+ { 32752030, 11232950, 3381995, -8714866, 22652988, -10744103, 17159699, 16689107, -20314580, -1305992 },
+ { -4689649, 9166776, -25710296, -10847306, 11576752, 12733943, 7924251, -2752281, 1976123, -7249027 },
+ { 21251222, 16309901, -2983015, -6783122, 30810597, 12967303, 156041, -3371252, 12331345, -8237197 }
+ },
+ {
+ { 8651614, -4477032, -16085636, -4996994, 13002507, 2950805, 29054427, -5106970, 10008136, -4667901 },
+ { 31486080, 15114593, -14261250, 12951354, 14369431, -7387845, 16347321, -13662089, 8684155, -10532952 },
+ { 19443825, 11385320, 24468943, -9659068, -23919258, 2187569, -26263207, -6086921, 31316348, 14219878 }
+ },
+ {
+ { -28594490, 1193785, 32245219, 11392485, 31092169, 15722801, 27146014, 6992409, 29126555, 9207390 },
+ { 32382935, 1110093, 18477781, 11028262, -27411763, -7548111, -4980517, 10843782, -7957600, -14435730 },
+ { 2814918, 7836403, 27519878, -7868156, -20894015, -11553689, -21494559, 8550130, 28346258, 1994730 }
+ },
+ {
+ { -19578299, 8085545, -14000519, -3948622, 2785838, -16231307, -19516951, 7174894, 22628102, 8115180 },
+ { -30405132, 955511, -11133838, -15078069, -32447087, -13278079, -25651578, 3317160, -9943017, 930272 },
+ { -15303681, -6833769, 28856490, 1357446, 23421993, 1057177, 24091212, -1388970, -22765376, -10650715 }
+ },
+ {
+ { -22751231, -5303997, -12907607, -12768866, -15811511, -7797053, -14839018, -16554220, -1867018, 8398970 },
+ { -31969310, 2106403, -4736360, 1362501, 12813763, 16200670, 22981545, -6291273, 18009408, -15772772 },
+ { -17220923, -9545221, -27784654, 14166835, 29815394, 7444469, 29551787, -3727419, 19288549, 1325865 }
+ },
+ {
+ { 15100157, -15835752, -23923978, -1005098, -26450192, 15509408, 12376730, -3479146, 33166107, -8042750 },
+ { 20909231, 13023121, -9209752, 16251778, -5778415, -8094914, 12412151, 10018715, 2213263, -13878373 },
+ { 32529814, -11074689, 30361439, -16689753, -9135940, 1513226, 22922121, 6382134, -5766928, 8371348 }
+ }
+},
+{ /* 11/31 */
+ {
+ { 9923462, 11271500, 12616794, 3544722, -29998368, -1721626, 12891687, -8193132, -26442943, 10486144 },
+ { -22597207, -7012665, 8587003, -8257861, 4084309, -12970062, 361726, 2610596, -23921530, -11455195 },
+ { 5408411, -1136691, -4969122, 10561668, 24145918, 14240566, 31319731, -4235541, 19985175, -3436086 }
+ },
+ {
+ { -13994457, 16616821, 14549246, 3341099, 32155958, 13648976, -17577068, 8849297, 65030, 8370684 },
+ { -8320926, -12049626, 31204563, 5839400, -20627288, -1057277, -19442942, 6922164, 12743482, -9800518 },
+ { -2361371, 12678785, 28815050, 4759974, -23893047, 4884717, 23783145, 11038569, 18800704, 255233 }
+ },
+ {
+ { -5269658, -1773886, 13957886, 7990715, 23132995, 728773, 13393847, 9066957, 19258688, -14753793 },
+ { -2936654, -10827535, -10432089, 14516793, -3640786, 4372541, -31934921, 2209390, -1524053, 2055794 },
+ { 580882, 16705327, 5468415, -2683018, -30926419, -14696000, -7203346, -8994389, -30021019, 7394435 }
+ },
+ {
+ { 23838809, 1822728, -15738443, 15242727, 8318092, -3733104, -21672180, -3492205, -4821741, 14799921 },
+ { 13345610, 9759151, 3371034, -16137791, 16353039, 8577942, 31129804, 13496856, -9056018, 7402518 },
+ { 2286874, -4435931, -20042458, -2008336, -13696227, 5038122, 11006906, -15760352, 8205061, 1607563 }
+ },
+ {
+ { 14414086, -8002132, 3331830, -3208217, 22249151, -5594188, 18364661, -2906958, 30019587, -9029278 },
+ { -27688051, 1585953, -10775053, 931069, -29120221, -11002319, -14410829, 12029093, 9944378, 8024 },
+ { 4368715, -3709630, 29874200, -15022983, -20230386, -11410704, -16114594, -999085, -8142388, 5640030 }
+ },
+ {
+ { 10299610, 13746483, 11661824, 16234854, 7630238, 5998374, 9809887, -16694564, 15219798, -14327783 },
+ { 27425505, -5719081, 3055006, 10660664, 23458024, 595578, -15398605, -1173195, -18342183, 9742717 },
+ { 6744077, 2427284, 26042789, 2720740, -847906, 1118974, 32324614, 7406442, 12420155, 1994844 }
+ },
+ {
+ { 14012521, -5024720, -18384453, -9578469, -26485342, -3936439, -13033478, -10909803, 24319929, -6446333 },
+ { 16412690, -4507367, 10772641, 15929391, -17068788, -4658621, 10555945, -10484049, -30102368, -4739048 },
+ { 22397382, -7767684, -9293161, -12792868, 17166287, -9755136, -27333065, 6199366, 21880021, -12250760 }
+ },
+ {
+ { -4283307, 5368523, -31117018, 8163389, -30323063, 3209128, 16557151, 8890729, 8840445, 4957760 },
+ { -15447727, 709327, -6919446, -10870178, -29777922, 6522332, -21720181, 12130072, -14796503, 5005757 },
+ { -2114751, -14308128, 23019042, 15765735, -25269683, 6002752, 10183197, -13239326, -16395286, -2176112 }
+ }
+},
+{ /* 12/31 */
+ {
+ { -19025756, 1632005, 13466291, -7995100, -23640451, 16573537, -32013908, -3057104, 22208662, 2000468 },
+ { 3065073, -1412761, -25598674, -361432, -17683065, -5703415, -8164212, 11248527, -3691214, -7414184 },
+ { 10379208, -6045554, 8877319, 1473647, -29291284, -12507580, 16690915, 2553332, -3132688, 16400289 }
+ },
+ {
+ { 15716668, 1254266, -18472690, 7446274, -8448918, 6344164, -22097271, -7285580, 26894937, 9132066 },
+ { 24158887, 12938817, 11085297, -8177598, -28063478, -4457083, -30576463, 64452, -6817084, -2692882 },
+ { 13488534, 7794716, 22236231, 5989356, 25426474, -12578208, 2350710, -3418511, -4688006, 2364226 }
+ },
+ {
+ { 16335052, 9132434, 25640582, 6678888, 1725628, 8517937, -11807024, -11697457, 15445875, -7798101 },
+ { 29004207, -7867081, 28661402, -640412, -12794003, -7943086, 31863255, -4135540, -278050, -15759279 },
+ { -6122061, -14866665, -28614905, 14569919, -10857999, -3591829, 10343412, -6976290, -29828287, -10815811 }
+ },
+ {
+ { 27081650, 3463984, 14099042, -4517604, 1616303, -6205604, 29542636, 15372179, 17293797, 960709 },
+ { 20263915, 11434237, -5765435, 11236810, 13505955, -10857102, -16111345, 6493122, -19384511, 7639714 },
+ { -2830798, -14839232, 25403038, -8215196, -8317012, -16173699, 18006287, -16043750, 29994677, -15808121 }
+ },
+ {
+ { 9769828, 5202651, -24157398, -13631392, -28051003, -11561624, -24613141, -13860782, -31184575, 709464 },
+ { 12286395, 13076066, -21775189, -1176622, -25003198, 4057652, -32018128, -8890874, 16102007, 13205847 },
+ { 13733362, 5599946, 10557076, 3195751, -5557991, 8536970, -25540170, 8525972, 10151379, 10394400 }
+ },
+ {
+ { 4024660, -16137551, 22436262, 12276534, -9099015, -2686099, 19698229, 11743039, -33302334, 8934414 },
+ { -15879800, -4525240, -8580747, -2934061, 14634845, -698278, -9449077, 3137094, -11536886, 11721158 },
+ { 17555939, -5013938, 8268606, 2331751, -22738815, 9761013, 9319229, 8835153, -9205489, -1280045 }
+ },
+ {
+ { -461409, -7830014, 20614118, 16688288, -7514766, -4807119, 22300304, 505429, 6108462, -6183415 },
+ { -5070281, 12367917, -30663534, 3234473, 32617080, -8422642, 29880583, -13483331, -26898490, -7867459 },
+ { -31975283, 5726539, 26934134, 10237677, -3173717, -605053, 24199304, 3795095, 7592688, -14992079 }
+ },
+ {
+ { 21594432, -14964228, 17466408, -4077222, 32537084, 2739898, 6407723, 12018833, -28256052, 4298412 },
+ { -20650503, -11961496, -27236275, 570498, 3767144, -1717540, 13891942, -1569194, 13717174, 10805743 },
+ { -14676630, -15644296, 15287174, 11927123, 24177847, -8175568, -796431, 14860609, -26938930, -5863836 }
+ }
+},
+{ /* 13/31 */
+ {
+ { 12962541, 5311799, -10060768, 11658280, 18855286, -7954201, 13286263, -12808704, -4381056, 9882022 },
+ { 18512079, 11319350, -20123124, 15090309, 18818594, 5271736, -22727904, 3666879, -23967430, -3299429 },
+ { -6789020, -3146043, 16192429, 13241070, 15898607, -14206114, -10084880, -6661110, -2403099, 5276065 }
+ },
+ {
+ { 30169808, -5317648, 26306206, -11750859, 27814964, 7069267, 7152851, 3684982, 1449224, 13082861 },
+ { 10342826, 3098505, 2119311, 193222, 25702612, 12233820, 23697382, 15056736, -21016438, -8202000 },
+ { -33150110, 3261608, 22745853, 7948688, 19370557, -15177665, -26171976, 6482814, -10300080, -11060101 }
+ },
+ {
+ { 32869458, -5408545, 25609743, 15678670, -10687769, -15471071, 26112421, 2521008, -22664288, 6904815 },
+ { 29506923, 4457497, 3377935, -9796444, -30510046, 12935080, 1561737, 3841096, -29003639, -6657642 },
+ { 10340844, -6630377, -18656632, -2278430, 12621151, -13339055, 30878497, -11824370, -25584551, 5181966 }
+ },
+ {
+ { 25940115, -12658025, 17324188, -10307374, -8671468, 15029094, 24396252, -16450922, -2322852, -12388574 },
+ { -21765684, 9916823, -1300409, 4079498, -1028346, 11909559, 1782390, 12641087, 20603771, -6561742 },
+ { -18882287, -11673380, 24849422, 11501709, 13161720, -4768874, 1925523, 11914390, 4662781, 7820689 }
+ },
+ {
+ { 12241050, -425982, 8132691, 9393934, 32846760, -1599620, 29749456, 12172924, 16136752, 15264020 },
+ { -10349955, -14680563, -8211979, 2330220, -17662549, -14545780, 10658213, 6671822, 19012087, 3772772 },
+ { 3753511, -3421066, 10617074, 2028709, 14841030, -6721664, 28718732, -15762884, 20527771, 12988982 }
+ },
+ {
+ { -14822485, -5797269, -3707987, 12689773, -898983, -10914866, -24183046, -10564943, 3299665, -12424953 },
+ { -16777703, -15253301, -9642417, 4978983, 3308785, 8755439, 6943197, 6461331, -25583147, 8991218 },
+ { -17226263, 1816362, -1673288, -6086439, 31783888, -8175991, -32948145, 7417950, -30242287, 1507265 }
+ },
+ {
+ { 29692663, 6829891, -10498800, 4334896, 20945975, -11906496, -28887608, 8209391, 14606362, -10647073 },
+ { -3481570, 8707081, 32188102, 5672294, 22096700, 1711240, -33020695, 9761487, 4170404, -2085325 },
+ { -11587470, 14855945, -4127778, -1531857, -26649089, 15084046, 22186522, 16002000, -14276837, -8400798 }
+ },
+ {
+ { -4811456, 13761029, -31703877, -2483919, -3312471, 7869047, -7113572, -9620092, 13240845, 10965870 },
+ { -7742563, -8256762, -14768334, -13656260, -23232383, 12387166, 4498947, 14147411, 29514390, 4302863 },
+ { -13413405, -12407859, 20757302, -13801832, 14785143, 8976368, -5061276, -2144373, 17846988, -13971927 }
+ }
+},
+{ /* 14/31 */
+ {
+ { -2244452, -754728, -4597030, -1066309, -6247172, 1455299, -21647728, -9214789, -5222701, 12650267 },
+ { -9906797, -16070310, 21134160, 12198166, -27064575, 708126, 387813, 13770293, -19134326, 10958663 },
+ { 22470984, 12369526, 23446014, -5441109, -21520802, -9698723, -11772496, -11574455, -25083830, 4271862 }
+ },
+ {
+ { -25169565, -10053642, -19909332, 15361595, -5984358, 2159192, 75375, -4278529, -32526221, 8469673 },
+ { 15854970, 4148314, -8893890, 7259002, 11666551, 13824734, -30531198, 2697372, 24154791, -9460943 },
+ { 15446137, -15806644, 29759747, 14019369, 30811221, -9610191, -31582008, 12840104, 24913809, 9815020 }
+ },
+ {
+ { -4709286, -5614269, -31841498, -12288893, -14443537, 10799414, -9103676, 13438769, 18735128, 9466238 },
+ { 11933045, 9281483, 5081055, -5183824, -2628162, -4905629, -7727821, -10896103, -22728655, 16199064 },
+ { 14576810, 379472, -26786533, -8317236, -29426508, -10812974, -102766, 1876699, 30801119, 2164795 }
+ },
+ {
+ { 15995086, 3199873, 13672555, 13712240, -19378835, -4647646, -13081610, -15496269, -13492807, 1268052 },
+ { -10290614, -3659039, -3286592, 10948818, 23037027, 3794475, -3470338, -12600221, -17055369, 3565904 },
+ { 29210088, -9419337, -5919792, -4952785, 10834811, -13327726, -16512102, -10820713, -27162222, -14030531 }
+ },
+ {
+ { -13161890, 15508588, 16663704, -8156150, -28349942, 9019123, -29183421, -3769423, 2244111, -14001979 },
+ { -5152875, -3800936, -9306475, -6071583, 16243069, 14684434, -25673088, -16180800, 13491506, 4641841 },
+ { 10813417, 643330, -19188515, -728916, 30292062, -16600078, 27548447, -7721242, 14476989, -12767431 }
+ },
+ {
+ { 10292079, 9984945, 6481436, 8279905, -7251514, 7032743, 27282937, -1644259, -27912810, 12651324 },
+ { -31185513, -813383, 22271204, 11835308, 10201545, 15351028, 17099662, 3988035, 21721536, -3148940 },
+ { 10202177, -6545839, -31373232, -9574638, -32150642, -8119683, -12906320, 3852694, 13216206, 14842320 }
+ },
+ {
+ { -15815640, -10601066, -6538952, -7258995, -6984659, -6581778, -31500847, 13765824, -27434397, 9900184 },
+ { 14465505, -13833331, -32133984, -14738873, -27443187, 12990492, 33046193, 15796406, -7051866, -8040114 },
+ { 30924417, -8279620, 6359016, -12816335, 16508377, 9071735, -25488601, 15413635, 9524356, -7018878 }
+ },
+ {
+ { 12274201, -13175547, 32627641, -1785326, 6736625, 13267305, 5237659, -5109483, 15663516, 4035784 },
+ { -2951309, 8903985, 17349946, 601635, -16432815, -4612556, -13732739, -15889334, -22258478, 4659091 },
+ { -16916263, -4952973, -30393711, -15158821, 20774812, 15897498, 5736189, 15026997, -2178256, -13455585 }
+ }
+},
+{ /* 15/31 */
+ {
+ { -8858980, -2219056, 28571666, -10155518, -474467, -10105698, -3801496, 278095, 23440562, -290208 },
+ { 10226241, -5928702, 15139956, 120818, -14867693, 5218603, 32937275, 11551483, -16571960, -7442864 },
+ { 17932739, -12437276, -24039557, 10749060, 11316803, 7535897, 22503767, 5561594, -3646624, 3898661 }
+ },
+ {
+ { 7749907, -969567, -16339731, -16464, -25018111, 15122143, -1573531, 7152530, 21831162, 1245233 },
+ { 26958459, -14658026, 4314586, 8346991, -5677764, 11960072, -32589295, -620035, -30402091, -16716212 },
+ { -12165896, 9166947, 33491384, 13673479, 29787085, 13096535, 6280834, 14587357, -22338025, 13987525 }
+ },
+ {
+ { -24349909, 7778775, 21116000, 15572597, -4833266, -5357778, -4300898, -5124639, -7469781, -2858068 },
+ { 9681908, -6737123, -31951644, 13591838, -6883821, 386950, 31622781, 6439245, -14581012, 4091397 },
+ { -8426427, 1470727, -28109679, -1596990, 3978627, -5123623, -19622683, 12092163, 29077877, -14741988 }
+ },
+ {
+ { 5269168, -6859726, -13230211, -8020715, 25932563, 1763552, -5606110, -5505881, -20017847, 2357889 },
+ { 32264008, -15407652, -5387735, -1160093, -2091322, -3946900, 23104804, -12869908, 5727338, 189038 },
+ { 14609123, -8954470, -6000566, -16622781, -14577387, -7743898, -26745169, 10942115, -25888931, -14884697 }
+ },
+ {
+ { 20513500, 5557931, -15604613, 7829531, 26413943, -2019404, -21378968, 7471781, 13913677, -5137875 },
+ { -25574376, 11967826, 29233242, 12948236, -6754465, 4713227, -8940970, 14059180, 12878652, 8511905 },
+ { -25656801, 3393631, -2955415, -7075526, -2250709, 9366908, -30223418, 6812974, 5568676, -3127656 }
+ },
+ {
+ { 11630004, 12144454, 2116339, 13606037, 27378885, 15676917, -17408753, -13504373, -14395196, 8070818 },
+ { 27117696, -10007378, -31282771, -5570088, 1127282, 12772488, -29845906, 10483306, -11552749, -1028714 },
+ { 10637467, -5688064, 5674781, 1072708, -26343588, -6982302, -1683975, 9177853, -27493162, 15431203 }
+ },
+ {
+ { 20525145, 10892566, -12742472, 12779443, -29493034, 16150075, -28240519, 14943142, -15056790, -7935931 },
+ { -30024462, 5626926, -551567, -9981087, 753598, 11981191, 25244767, -3239766, -3356550, 9594024 },
+ { -23752644, 2636870, -5163910, -10103818, 585134, 7877383, 11345683, -6492290, 13352335, -10977084 }
+ },
+ {
+ { -1931799, -5407458, 3304649, -12884869, 17015806, -4877091, -29783850, -7752482, -13215537, -319204 },
+ { 20239939, 6607058, 6203985, 3483793, -18386976, -779229, -20723742, 15077870, -22750759, 14523817 },
+ { 27406042, -6041657, 27423596, -4497394, 4996214, 10002360, -28842031, -4545494, -30172742, -4805667 }
+ }
+},
+{ /* 16/31 */
+ {
+ { 11374242, 12660715, 17861383, -12540833, 10935568, 1099227, -13886076, -9091740, -27727044, 11358504 },
+ { -12730809, 10311867, 1510375, 10778093, -2119455, -9145702, 32676003, 11149336, -26123651, 4985768 },
+ { -19096303, 341147, -6197485, -239033, 15756973, -8796662, -983043, 13794114, -19414307, -15621255 }
+ },
+ {
+ { 6490081, 11940286, 25495923, -7726360, 8668373, -8751316, 3367603, 6970005, -1691065, -9004790 },
+ { 1656497, 13457317, 15370807, 6364910, 13605745, 8362338, -19174622, -5475723, -16796596, -5031438 },
+ { -22273315, -13524424, -64685, -4334223, -18605636, -10921968, -20571065, -7007978, -99853, -10237333 }
+ },
+ {
+ { 17747465, 10039260, 19368299, -4050591, -20630635, -16041286, 31992683, -15857976, -29260363, -5511971 },
+ { 31932027, -4986141, -19612382, 16366580, 22023614, 88450, 11371999, -3744247, 4882242, -10626905 },
+ { 29796507, 37186, 19818052, 10115756, -11829032, 3352736, 18551198, 3272828, -5190932, -4162409 }
+ },
+ {
+ { 12501286, 4044383, -8612957, -13392385, -32430052, 5136599, -19230378, -3529697, 330070, -3659409 },
+ { 6384877, 2899513, 17807477, 7663917, -2358888, 12363165, 25366522, -8573892, -271295, 12071499 },
+ { -8365515, -4042521, 25133448, -4517355, -6211027, 2265927, -32769618, 1936675, -5159697, 3829363 }
+ },
+ {
+ { 28425966, -5835433, -577090, -4697198, -14217555, 6870930, 7921550, -6567787, 26333140, 14267664 },
+ { -11067219, 11871231, 27385719, -10559544, -4585914, -11189312, 10004786, -8709488, -21761224, 8930324 },
+ { -21197785, -16396035, 25654216, -1725397, 12282012, 11008919, 1541940, 4757911, -26491501, -16408940 }
+ },
+ {
+ { 13537262, -7759490, -20604840, 10961927, -5922820, -13218065, -13156584, 6217254, -15943699, 13814990 },
+ { -17422573, 15157790, 18705543, 29619, 24409717, -260476, 27361681, 9257833, -1956526, -1776914 },
+ { -25045300, -10191966, 15366585, 15166509, -13105086, 8423556, -29171540, 12361135, -18685978, 4578290 }
+ },
+ {
+ { 24579768, 3711570, 1342322, -11180126, -27005135, 14124956, -22544529, 14074919, 21964432, 8235257 },
+ { -6528613, -2411497, 9442966, -5925588, 12025640, -1487420, -2981514, -1669206, 13006806, 2355433 },
+ { -16304899, -13605259, -6632427, -5142349, 16974359, -10911083, 27202044, 1719366, 1141648, -12796236 }
+ },
+ {
+ { -12863944, -13219986, -8318266, -11018091, -6810145, -4843894, 13475066, -3133972, 32674895, 13715045 },
+ { 11423335, -5468059, 32344216, 8962751, 24989809, 9241752, -13265253, 16086212, -28740881, -15642093 },
+ { -1409668, 12530728, -6368726, 10847387, 19531186, -14132160, -11709148, 7791794, -27245943, 4383347 }
+ }
+},
+{ /* 17/31 */
+ {
+ { -28970898, 5271447, -1266009, -9736989, -12455236, 16732599, -4862407, -4906449, 27193557, 6245191 },
+ { -15193956, 5362278, -1783893, 2695834, 4960227, 12840725, 23061898, 3260492, 22510453, 8577507 },
+ { -12632451, 11257346, -32692994, 13548177, -721004, 10879011, 31168030, 13952092, -29571492, -3635906 }
+ },
+ {
+ { 3877321, -9572739, 32416692, 5405324, -11004407, -13656635, 3759769, 11935320, 5611860, 8164018 },
+ { -16275802, 14667797, 15906460, 12155291, -22111149, -9039718, 32003002, -8832289, 5773085, -8422109 },
+ { -23788118, -8254300, 1950875, 8937633, 18686727, 16459170, -905725, 12376320, 31632953, 190926 }
+ },
+ {
+ { -24593607, -16138885, -8423991, 13378746, 14162407, 6901328, -8288749, 4508564, -25341555, -3627528 },
+ { 8884438, -5884009, 6023974, 10104341, -6881569, -4941533, 18722941, -14786005, -1672488, 827625 },
+ { -32720583, -16289296, -32503547, 7101210, 13354605, 2659080, -1800575, -14108036, -24878478, 1541286 }
+ },
+ {
+ { 2901347, -1117687, 3880376, -10059388, -17620940, -3612781, -21802117, -3567481, 20456845, -1885033 },
+ { 27019610, 12299467, -13658288, -1603234, -12861660, -4861471, -19540150, -5016058, 29439641, 15138866 },
+ { 21536104, -6626420, -32447818, -10690208, -22408077, 5175814, -5420040, -16361163, 7779328, 109896 }
+ },
+ {
+ { 30279744, 14648750, -8044871, 6425558, 13639621, -743509, 28698390, 12180118, 23177719, -554075 },
+ { 26572847, 3405927, -31701700, 12890905, -19265668, 5335866, -6493768, 2378492, 4439158, -13279347 },
+ { -22716706, 3489070, -9225266, -332753, 18875722, -1140095, 14819434, -12731527, -17717757, -5461437 }
+ },
+ {
+ { -5056483, 16566551, 15953661, 3767752, -10436499, 15627060, -820954, 2177225, 8550082, -15114165 },
+ { -18473302, 16596775, -381660, 15663611, 22860960, 15585581, -27844109, -3582739, -23260460, -8428588 },
+ { -32480551, 15707275, -8205912, -5652081, 29464558, 2713815, -22725137, 15860482, -21902570, 1494193 }
+ },
+ {
+ { -19562091, -14087393, -25583872, -9299552, 13127842, 759709, 21923482, 16529112, 8742704, 12967017 },
+ { -28464899, 1553205, 32536856, -10473729, -24691605, -406174, -8914625, -2933896, -29903758, 15553883 },
+ { 21877909, 3230008, 9881174, 10539357, -4797115, 2841332, 11543572, 14513274, 19375923, -12647961 }
+ },
+ {
+ { 8832269, -14495485, 13253511, 5137575, 5037871, 4078777, 24880818, -6222716, 2862653, 9455043 },
+ { 29306751, 5123106, 20245049, -14149889, 9592566, 8447059, -2077124, -2990080, 15511449, 4789663 },
+ { -20679756, 7004547, 8824831, -9434977, -4045704, -3750736, -5754762, 108893, 23513200, 16652362 }
+ }
+},
+{ /* 18/31 */
+ {
+ { -33256173, 4144782, -4476029, -6579123, 10770039, -7155542, -6650416, -12936300, -18319198, 10212860 },
+ { 2756081, 8598110, 7383731, -6859892, 22312759, -1105012, 21179801, 2600940, -9988298, -12506466 },
+ { -24645692, 13317462, -30449259, -15653928, 21365574, -10869657, 11344424, 864440, -2499677, -16710063 }
+ },
+ {
+ { -26432803, 6148329, -17184412, -14474154, 18782929, -275997, -22561534, 211300, 2719757, 4940997 },
+ { -1323882, 3911313, -6948744, 14759765, -30027150, 7851207, 21690126, 8518463, 26699843, 5276295 },
+ { -13149873, -6429067, 9396249, 365013, 24703301, -10488939, 1321586, 149635, -15452774, 7159369 }
+ },
+ {
+ { 9987780, -3404759, 17507962, 9505530, 9731535, -2165514, 22356009, 8312176, 22477218, -8403385 },
+ { 18155857, -16504990, 19744716, 9006923, 15154154, -10538976, 24256460, -4864995, -22548173, 9334109 },
+ { 2986088, -4911893, 10776628, -3473844, 10620590, -7083203, -21413845, 14253545, -22587149, 536906 }
+ },
+ {
+ { 4377756, 8115836, 24567078, 15495314, 11625074, 13064599, 7390551, 10589625, 10838060, -15420424 },
+ { -19342404, 867880, 9277171, -3218459, -14431572, -1986443, 19295826, -15796950, 6378260, 699185 },
+ { 7895026, 4057113, -7081772, -13077756, -17886831, -323126, -716039, 15693155, -5045064, -13373962 }
+ },
+ {
+ { -7737563, -5869402, -14566319, -7406919, 11385654, 13201616, 31730678, -10962840, -3918636, -9669325 },
+ { 10188286, -15770834, -7336361, 13427543, 22223443, 14896287, 30743455, 7116568, -21786507, 5427593 },
+ { 696102, 13206899, 27047647, -10632082, 15285305, -9853179, 10798490, -4578720, 19236243, 12477404 }
+ },
+ {
+ { -11229439, 11243796, -17054270, -8040865, -788228, -8167967, -3897669, 11180504, -23169516, 7733644 },
+ { 17800790, -14036179, -27000429, -11766671, 23887827, 3149671, 23466177, -10538171, 10322027, 15313801 },
+ { 26246234, 11968874, 32263343, -5468728, 6830755, -13323031, -15794704, -101982, -24449242, 10890804 }
+ },
+ {
+ { -31365647, 10271363, -12660625, -6267268, 16690207, -13062544, -14982212, 16484931, 25180797, -5334884 },
+ { -586574, 10376444, -32586414, -11286356, 19801893, 10997610, 2276632, 9482883, 316878, 13820577 },
+ { -9882808, -4510367, -2115506, 16457136, -11100081, 11674996, 30756178, -7515054, 30696930, -3712849 }
+ },
+ {
+ { 32988917, -9603412, 12499366, 7910787, -10617257, -11931514, -7342816, -9985397, -32349517, 7392473 },
+ { -8855661, 15927861, 9866406, -3649411, -2396914, -16655781, -30409476, -9134995, 25112947, -2926644 },
+ { -2504044, -436966, 25621774, -5678772, 15085042, -5479877, -24884878, -13526194, 5537438, -13914319 }
+ }
+},
+{ /* 19/31 */
+ {
+ { -11225584, 2320285, -9584280, 10149187, -33444663, 5808648, -14876251, -1729667, 31234590, 6090599 },
+ { -9633316, 116426, 26083934, 2897444, -6364437, -2688086, 609721, 15878753, -6970405, -9034768 },
+ { -27757857, 247744, -15194774, -9002551, 23288161, -10011936, -23869595, 6503646, 20650474, 1804084 }
+ },
+ {
+ { -27589786, 15456424, 8972517, 8469608, 15640622, 4439847, 3121995, -10329713, 27842616, -202328 },
+ { -15306973, 2839644, 22530074, 10026331, 4602058, 5048462, 28248656, 5031932, -11375082, 12714369 },
+ { 20807691, -7270825, 29286141, 11421711, -27876523, -13868230, -21227475, 1035546, -19733229, 12796920 }
+ },
+ {
+ { 12076899, -14301286, -8785001, -11848922, -25012791, 16400684, -17591495, -12899438, 3480665, -15182815 },
+ { -32361549, 5457597, 28548107, 7833186, 7303070, -11953545, -24363064, -15921875, -33374054, 2771025 },
+ { -21389266, 421932, 26597266, 6860826, 22486084, -6737172, -17137485, -4210226, -24552282, 15673397 }
+ },
+ {
+ { -20184622, 2338216, 19788685, -9620956, -4001265, -8740893, -20271184, 4733254, 3727144, -12934448 },
+ { 6120119, 814863, -11794402, -622716, 6812205, -15747771, 2019594, 7975683, 31123697, -10958981 },
+ { 30069250, -11435332, 30434654, 2958439, 18399564, -976289, 12296869, 9204260, -16432438, 9648165 }
+ },
+ {
+ { 32705432, -1550977, 30705658, 7451065, -11805606, 9631813, 3305266, 5248604, -26008332, -11377501 },
+ { 17219865, 2375039, -31570947, -5575615, -19459679, 9219903, 294711, 15298639, 2662509, -16297073 },
+ { -1172927, -7558695, -4366770, -4287744, -21346413, -8434326, 32087529, -1222777, 32247248, -14389861 }
+ },
+ {
+ { 14312628, 1221556, 17395390, -8700143, -4945741, -8684635, -28197744, -9637817, -16027623, -13378845 },
+ { -1428825, -9678990, -9235681, 6549687, -7383069, -468664, 23046502, 9803137, 17597934, 2346211 },
+ { 18510800, 15337574, 26171504, 981392, -22241552, 7827556, -23491134, -11323352, 3059833, -11782870 }
+ },
+ {
+ { 10141598, 6082907, 17829293, -1947643, 9830092, 13613136, -25556636, -5544586, -33502212, 3592096 },
+ { 33114168, -15889352, -26525686, -13343397, 33076705, 8716171, 1151462, 1521897, -982665, -6837803 },
+ { -32939165, -4255815, 23947181, -324178, -33072974, -12305637, -16637686, 3891704, 26353178, 693168 }
+ },
+ {
+ { 30374239, 1595580, -16884039, 13186931, 4600344, 406904, 9585294, -400668, 31375464, 14369965 },
+ { -14370654, -7772529, 1510301, 6434173, -18784789, -6262728, 32732230, -13108839, 17901441, 16011505 },
+ { 18171223, -11934626, -12500402, 15197122, -11038147, -15230035, -19172240, -16046376, 8764035, 12309598 }
+ }
+},
+{ /* 20/31 */
+ {
+ { 5975908, -5243188, -19459362, -9681747, -11541277, 14015782, -23665757, 1228319, 17544096, -10593782 },
+ { 5811932, -1715293, 3442887, -2269310, -18367348, -8359541, -18044043, -15410127, -5565381, 12348900 },
+ { -31399660, 11407555, 25755363, 6891399, -3256938, 14872274, -24849353, 8141295, -10632534, -585479 }
+ },
+ {
+ { -12675304, 694026, -5076145, 13300344, 14015258, -14451394, -9698672, -11329050, 30944593, 1130208 },
+ { 8247766, -6710942, -26562381, -7709309, -14401939, -14648910, 4652152, 2488540, 23550156, -271232 },
+ { 17294316, -3788438, 7026748, 15626851, 22990044, 113481, 2267737, -5908146, -408818, -137719 }
+ },
+ {
+ { 16091085, -16253926, 18599252, 7340678, 2137637, -1221657, -3364161, 14550936, 3260525, -7166271 },
+ { -4910104, -13332887, 18550887, 10864893, -16459325, -7291596, -23028869, -13204905, -12748722, 2701326 },
+ { -8574695, 16099415, 4629974, -16340524, -20786213, -6005432, -10018363, 9276971, 11329923, 1862132 }
+ },
+ {
+ { 14763076, -15903608, -30918270, 3689867, 3511892, 10313526, -21951088, 12219231, -9037963, -940300 },
+ { 8894987, -3446094, 6150753, 3013931, 301220, 15693451, -31981216, -2909717, -15438168, 11595570 },
+ { 15214962, 3537601, -26238722, -14058872, 4418657, -15230761, 13947276, 10730794, -13489462, -4363670 }
+ },
+ {
+ { -2538306, 7682793, 32759013, 263109, -29984731, -7955452, -22332124, -10188635, 977108, 699994 },
+ { -12466472, 4195084, -9211532, 550904, -15565337, 12917920, 19118110, -439841, -30534533, -14337913 },
+ { 31788461, -14507657, 4799989, 7372237, 8808585, -14747943, 9408237, -10051775, 12493932, -5409317 }
+ },
+ {
+ { -25680606, 5260744, -19235809, -6284470, -3695942, 16566087, 27218280, 2607121, 29375955, 6024730 },
+ { 842132, -2794693, -4763381, -8722815, 26332018, -12405641, 11831880, 6985184, -9940361, 2854096 },
+ { -4847262, -7969331, 2516242, -5847713, 9695691, -7221186, 16512645, 960770, 12121869, 16648078 }
+ },
+ {
+ { -15218652, 14667096, -13336229, 2013717, 30598287, -464137, -31504922, -7882064, 20237806, 2838411 },
+ { -19288047, 4453152, 15298546, -16178388, 22115043, -15972604, 12544294, -13470457, 1068881, -12499905 },
+ { -9558883, -16518835, 33238498, 13506958, 30505848, -1114596, -8486907, -2630053, 12521378, 4845654 }
+ },
+ {
+ { -28198521, 10744108, -2958380, 10199664, 7759311, -13088600, 3409348, -873400, -6482306, -12885870 },
+ { -23561822, 6230156, -20382013, 10655314, -24040585, -11621172, 10477734, -1240216, -3113227, 13974498 },
+ { 12966261, 15550616, -32038948, -1615346, 21025980, -629444, 5642325, 7188737, 18895762, 12629579 }
+ }
+},
+{ /* 21/31 */
+ {
+ { 14741879, -14946887, 22177208, -11721237, 1279741, 8058600, 11758140, 789443, 32195181, 3895677 },
+ { 10758205, 15755439, -4509950, 9243698, -4879422, 6879879, -2204575, -3566119, -8982069, 4429647 },
+ { -2453894, 15725973, -20436342, -10410672, -5803908, -11040220, -7135870, -11642895, 18047436, -15281743 }
+ },
+ {
+ { -25173001, -11307165, 29759956, 11776784, -22262383, -15820455, 10993114, -12850837, -17620701, -9408468 },
+ { 21987233, 700364, -24505048, 14972008, -7774265, -5718395, 32155026, 2581431, -29958985, 8773375 },
+ { -25568350, 454463, -13211935, 16126715, 25240068, 8594567, 20656846, 12017935, -7874389, -13920155 }
+ },
+ {
+ { 6028182, 6263078, -31011806, -11301710, -818919, 2461772, -31841174, -5468042, -1721788, -2776725 },
+ { -12278994, 16624277, 987579, -5922598, 32908203, 1248608, 7719845, -4166698, 28408820, 6816612 },
+ { -10358094, -8237829, 19549651, -12169222, 22082623, 16147817, 20613181, 13982702, -10339570, 5067943 }
+ },
+ {
+ { -30505967, -3821767, 12074681, 13582412, -19877972, 2443951, -19719286, 12746132, 5331210, -10105944 },
+ { 30528811, 3601899, -1957090, 4619785, -27361822, -15436388, 24180793, -12570394, 27679908, -1648928 },
+ { 9402404, -13957065, 32834043, 10838634, -26580150, -13237195, 26653274, -8685565, 22611444, -12715406 }
+ },
+ {
+ { 22190590, 1118029, 22736441, 15130463, -30460692, -5991321, 19189625, -4648942, 4854859, 6622139 },
+ { -8310738, -2953450, -8262579, -3388049, -10401731, -271929, 13424426, -3567227, 26404409, 13001963 },
+ { -31241838, -15415700, -2994250, 8939346, 11562230, -12840670, -26064365, -11621720, -15405155, 11020693 }
+ },
+ {
+ { 1866042, -7949489, -7898649, -10301010, 12483315, 13477547, 3175636, -12424163, 28761762, 1406734 },
+ { -448555, -1777666, 13018551, 3194501, -9580420, -11161737, 24760585, -4347088, 25577411, -13378680 },
+ { -24290378, 4759345, -690653, -1852816, 2066747, 10693769, -29595790, 9884936, -9368926, 4745410 }
+ },
+ {
+ { -9141284, 6049714, -19531061, -4341411, -31260798, 9944276, -15462008, -11311852, 10931924, -11931931 },
+ { -16561513, 14112680, -8012645, 4817318, -8040464, -11414606, -22853429, 10856641, -20470770, 13434654 },
+ { 22759489, -10073434, -16766264, -1871422, 13637442, -10168091, 1765144, -12654326, 28445307, -5364710 }
+ },
+ {
+ { 29875063, 12493613, 2795536, -3786330, 1710620, 15181182, -10195717, -8788675, 9074234, 1167180 },
+ { -26205683, 11014233, -9842651, -2635485, -26908120, 7532294, -18716888, -9535498, 3843903, 9367684 },
+ { -10969595, -6403711, 9591134, 9582310, 11349256, 108879, 16235123, 8601684, -139197, 4242895 }
+ }
+},
+{ /* 22/31 */
+ {
+ { 22092954, -13191123, -2042793, -11968512, 32186753, -11517388, -6574341, 2470660, -27417366, 16625501 },
+ { -11057722, 3042016, 13770083, -9257922, 584236, -544855, -7770857, 2602725, -27351616, 14247413 },
+ { 6314175, -10264892, -32772502, 15957557, -10157730, 168750, -8618807, 14290061, 27108877, -1180880 }
+ },
+ {
+ { -8586597, -7170966, 13241782, 10960156, -32991015, -13794596, 33547976, -11058889, -27148451, 981874 },
+ { 22833440, 9293594, -32649448, -13618667, -9136966, 14756819, -22928859, -13970780, -10479804, -16197962 },
+ { -7768587, 3326786, -28111797, 10783824, 19178761, 14905060, 22680049, 13906969, -15933690, 3797899 }
+ },
+ {
+ { 21721356, -4212746, -12206123, 9310182, -3882239, -13653110, 23740224, -2709232, 20491983, -8042152 },
+ { 9209270, -15135055, -13256557, -6167798, -731016, 15289673, 25947805, 15286587, 30997318, -6703063 },
+ { 7392032, 16618386, 23946583, -8039892, -13265164, -1533858, -14197445, -2321576, 17649998, -250080 }
+ },
+ {
+ { -9301088, -14193827, 30609526, -3049543, -25175069, -1283752, -15241566, -9525724, -2233253, 7662146 },
+ { -17558673, 1763594, -33114336, 15908610, -30040870, -12174295, 7335080, -8472199, -3174674, 3440183 },
+ { -19889700, -5977008, -24111293, -9688870, 10799743, -16571957, 40450, -4431835, 4862400, 1133 }
+ },
+ {
+ { -32856209, -7873957, -5422389, 14860950, -16319031, 7956142, 7258061, 311861, -30594991, -7379421 },
+ { -3773428, -1565936, 28985340, 7499440, 24445838, 9325937, 29727763, 16527196, 18278453, 15405622 },
+ { -4381906, 8508652, -19898366, -3674424, -5984453, 15149970, -13313598, 843523, -21875062, 13626197 }
+ },
+ {
+ { 2281448, -13487055, -10915418, -2609910, 1879358, 16164207, -10783882, 3953792, 13340839, 15928663 },
+ { 31727126, -7179855, -18437503, -8283652, 2875793, -16390330, -25269894, -7014826, -23452306, 5964753 },
+ { 4100420, -5959452, -17179337, 6017714, -18705837, 12227141, -26684835, 11344144, 2538215, -7570755 }
+ },
+ {
+ { -9433605, 6123113, 11159803, -2156608, 30016280, 14966241, -20474983, 1485421, -629256, -15958862 },
+ { -26804558, 4260919, 11851389, 9658551, -32017107, 16367492, -20205425, -13191288, 11659922, -11115118 },
+ { 26180396, 10015009, -30844224, -8581293, 5418197, 9480663, 2231568, -10170080, 33100372, -1306171 }
+ },
+ {
+ { 15121113, -5201871, -10389905, 15427821, -27509937, -15992507, 21670947, 4486675, -5931810, -14466380 },
+ { 16166486, -9483733, -11104130, 6023908, -31926798, -1364923, 2340060, -16254968, -10735770, -10039824 },
+ { 28042865, -3557089, -12126526, 12259706, -3717498, -6945899, 6766453, -8689599, 18036436, 5803270 }
+ }
+},
+{ /* 23/31 */
+ {
+ { -817581, 6763912, 11803561, 1585585, 10958447, -2671165, 23855391, 4598332, -6159431, -14117438 },
+ { -31031306, -14256194, 17332029, -2383520, 31312682, -5967183, 696309, 50292, -20095739, 11763584 },
+ { -594563, -2514283, -32234153, 12643980, 12650761, 14811489, 665117, -12613632, -19773211, -10713562 }
+ },
+ {
+ { 30464590, -11262872, -4127476, -12734478, 19835327, -7105613, -24396175, 2075773, -17020157, 992471 },
+ { 18357185, -6994433, 7766382, 16342475, -29324918, 411174, 14578841, 8080033, -11574335, -10601610 },
+ { 19598397, 10334610, 12555054, 2555664, 18821899, -10339780, 21873263, 16014234, 26224780, 16452269 }
+ },
+ {
+ { -30223925, 5145196, 5944548, 16385966, 3976735, 2009897, -11377804, -7618186, -20533829, 3698650 },
+ { 14187449, 3448569, -10636236, -10810935, -22663880, -3433596, 7268410, -10890444, 27394301, 12015369 },
+ { 19695761, 16087646, 28032085, 12999827, 6817792, 11427614, 20244189, -1312777, -13259127, -3402461 }
+ },
+ {
+ { 30860103, 12735208, -1888245, -4699734, -16974906, 2256940, -8166013, 12298312, -8550524, -10393462 },
+ { -5719826, -11245325, -1910649, 15569035, 26642876, -7587760, -5789354, -15118654, -4976164, 12651793 },
+ { -2848395, 9953421, 11531313, -5282879, 26895123, -12697089, -13118820, -16517902, 9768698, -2533218 }
+ },
+ {
+ { -24719459, 1894651, -287698, -4704085, 15348719, -8156530, 32767513, 12765450, 4940095, 10678226 },
+ { 18860224, 15980149, -18987240, -1562570, -26233012, -11071856, -7843882, 13944024, -24372348, 16582019 },
+ { -15504260, 4970268, -29893044, 4175593, -20993212, -2199756, -11704054, 15444560, -11003761, 7989037 }
+ },
+ {
+ { 31490452, 5568061, -2412803, 2182383, -32336847, 4531686, -32078269, 6200206, -19686113, -14800171 },
+ { -17308668, -15879940, -31522777, -2831, -32887382, 16375549, 8680158, -16371713, 28550068, -6857132 },
+ { -28126887, -5688091, 16837845, -1820458, -6850681, 12700016, -30039981, 4364038, 1155602, 5988841 }
+ },
+ {
+ { 21890435, -13272907, -12624011, 12154349, -7831873, 15300496, 23148983, -4470481, 24618407, 8283181 },
+ { -33136107, -10512751, 9975416, 6841041, -31559793, 16356536, 3070187, -7025928, 1466169, 10740210 },
+ { -1509399, -15488185, -13503385, -10655916, 32799044, 909394, -13938903, -5779719, -32164649, -15327040 }
+ },
+ {
+ { 3960823, -14267803, -28026090, -15918051, -19404858, 13146868, 15567327, 951507, -3260321, -573935 },
+ { 24740841, 5052253, -30094131, 8961361, 25877428, 6165135, -24368180, 14397372, -7380369, -6144105 },
+ { -28888365, 3510803, -28103278, -1158478, -11238128, -10631454, -15441463, -14453128, -1625486, -6494814 }
+ }
+},
+{ /* 24/31 */
+ {
+ { 793299, -9230478, 8836302, -6235707, -27360908, -2369593, 33152843, -4885251, -9906200, -621852 },
+ { 5666233, 525582, 20782575, -8038419, -24538499, 14657740, 16099374, 1468826, -6171428, -15186581 },
+ { -4859255, -3779343, -2917758, -6748019, 7778750, 11688288, -30404353, -9871238, -1558923, -9863646 }
+ },
+ {
+ { 10896332, -7719704, 824275, 472601, -19460308, 3009587, 25248958, 14783338, -30581476, -15757844 },
+ { 10566929, 12612572, -31944212, 11118703, -12633376, 12362879, 21752402, 8822496, 24003793, 14264025 },
+ { 27713862, -7355973, -11008240, 9227530, 27050101, 2504721, 23886875, -13117525, 13958495, -5732453 }
+ },
+ {
+ { -23481610, 4867226, -27247128, 3900521, 29838369, -8212291, -31889399, -10041781, 7340521, -15410068 },
+ { 4646514, -8011124, -22766023, -11532654, 23184553, 8566613, 31366726, -1381061, -15066784, -10375192 },
+ { -17270517, 12723032, -16993061, 14878794, 21619651, -6197576, 27584817, 3093888, -8843694, 3849921 }
+ },
+ {
+ { -9064912, 2103172, 25561640, -15125738, -5239824, 9582958, 32477045, -9017955, 5002294, -15550259 },
+ { -12057553, -11177906, 21115585, -13365155, 8808712, -12030708, 16489530, 13378448, -25845716, 12741426 },
+ { -5946367, 10645103, -30911586, 15390284, -3286982, -7118677, 24306472, 15852464, 28834118, -7646072 }
+ },
+ {
+ { -17335748, -9107057, -24531279, 9434953, -8472084, -583362, -13090771, 455841, 20461858, 5491305 },
+ { 13669248, -16095482, -12481974, -10203039, -14569770, -11893198, -24995986, 11293807, -28588204, -9421832 },
+ { 28497928, 6272777, -33022994, 14470570, 8906179, -1225630, 18504674, -14165166, 29867745, -8795943 }
+ },
+ {
+ { -16207023, 13517196, -27799630, -13697798, 24009064, -6373891, -6367600, -13175392, 22853429, -4012011 },
+ { 24191378, 16712145, -13931797, 15217831, 14542237, 1646131, 18603514, -11037887, 12876623, -2112447 },
+ { 17902668, 4518229, -411702, -2829247, 26878217, 5258055, -12860753, 608397, 16031844, 3723494 }
+ },
+ {
+ { -28632773, 12763728, -20446446, 7577504, 33001348, -13017745, 17558842, -7872890, 23896954, -4314245 },
+ { -20005381, -12011952, 31520464, 605201, 2543521, 5991821, -2945064, 7229064, -9919646, -8826859 },
+ { 28816045, 298879, -28165016, -15920938, 19000928, -1665890, -12680833, -2949325, -18051778, -2082915 }
+ },
+ {
+ { 16000882, -344896, 3493092, -11447198, -29504595, -13159789, 12577740, 16041268, -19715240, 7847707 },
+ { 10151868, 10572098, 27312476, 7922682, 14825339, 4723128, -32855931, -6519018, -10020567, 3852848 },
+ { -11430470, 15697596, -21121557, -4420647, 5386314, 15063598, 16514493, -15932110, 29330899, -15076224 }
+ }
+},
+{ /* 25/31 */
+ {
+ { -25499735, -4378794, -15222908, -6901211, 16615731, 2051784, 3303702, 15490, -27548796, 12314391 },
+ { 15683520, -6003043, 18109120, -9980648, 15337968, -5997823, -16717435, 15921866, 16103996, -3731215 },
+ { -23169824, -10781249, 13588192, -1628807, -3798557, -1074929, -19273607, 5402699, -29815713, -9841101 }
+ },
+ {
+ { 23190676, 2384583, -32714340, 3462154, -29903655, -1529132, -11266856, 8911517, -25205859, 2739713 },
+ { 21374101, -3554250, -33524649, 9874411, 15377179, 11831242, -33529904, 6134907, 4931255, 11987849 },
+ { -7732, -2978858, -16223486, 7277597, 105524, -322051, -31480539, 13861388, -30076310, 10117930 }
+ },
+ {
+ { -29501170, -10744872, -26163768, 13051539, -25625564, 5089643, -6325503, 6704079, 12890019, 15728940 },
+ { -21972360, -11771379, -951059, -4418840, 14704840, 2695116, 903376, -10428139, 12885167, 8311031 },
+ { -17516482, 5352194, 10384213, -13811658, 7506451, 13453191, 26423267, 4384730, 1888765, -5435404 }
+ },
+ {
+ { -25817338, -3107312, -13494599, -3182506, 30896459, -13921729, -32251644, -12707869, -19464434, -3340243 },
+ { -23607977, -2665774, -526091, 4651136, 5765089, 4618330, 6092245, 14845197, 17151279, -9854116 },
+ { -24830458, -12733720, -15165978, 10367250, -29530908, -265356, 22825805, -7087279, -16866484, 16176525 }
+ },
+ {
+ { -23583256, 6564961, 20063689, 3798228, -4740178, 7359225, 2006182, -10363426, -28746253, -10197509 },
+ { -10626600, -4486402, -13320562, -5125317, 3432136, -6393229, 23632037, -1940610, 32808310, 1099883 },
+ { 15030977, 5768825, -27451236, -2887299, -6427378, -15361371, -15277896, -6809350, 2051441, -15225865 }
+ },
+ {
+ { -3362323, -7239372, 7517890, 9824992, 23555850, 295369, 5148398, -14154188, -22686354, 16633660 },
+ { 4577086, -16752288, 13249841, -15304328, 19958763, -14537274, 18559670, -10759549, 8402478, -9864273 },
+ { -28406330, -1051581, -26790155, -907698, -17212414, -11030789, 9453451, -14980072, 17983010, 9967138 }
+ },
+ {
+ { -25762494, 6524722, 26585488, 9969270, 24709298, 1220360, -1677990, 7806337, 17507396, 3651560 },
+ { -10420457, -4118111, 14584639, 15971087, -15768321, 8861010, 26556809, -5574557, -18553322, -11357135 },
+ { 2839101, 14284142, 4029895, 3472686, 14402957, 12689363, -26642121, 8459447, -5605463, -7621941 }
+ },
+ {
+ { -4839289, -3535444, 9744961, 2871048, 25113978, 3187018, -25110813, -849066, 17258084, -7977739 },
+ { 18164541, -10595176, -17154882, -1542417, 19237078, -9745295, 23357533, -15217008, 26908270, 12150756 },
+ { -30264870, -7647865, 5112249, -7036672, -1499807, -6974257, 43168, -5537701, -32302074, 16215819 }
+ }
+},
+{ /* 26/31 */
+ {
+ { -6898905, 9824394, -12304779, -4401089, -31397141, -6276835, 32574489, 12532905, -7503072, -8675347 },
+ { -27343522, -16515468, -27151524, -10722951, 946346, 16291093, 254968, 7168080, 21676107, -1943028 },
+ { 21260961, -8424752, -16831886, -11920822, -23677961, 3968121, -3651949, -6215466, -3556191, -7913075 }
+ },
+ {
+ { 16544754, 13250366, -16804428, 15546242, -4583003, 12757258, -2462308, -8680336, -18907032, -9662799 },
+ { -2415239, -15577728, 18312303, 4964443, -15272530, -12653564, 26820651, 16690659, 25459437, -4564609 },
+ { -25144690, 11425020, 28423002, -11020557, -6144921, -15826224, 9142795, -2391602, -6432418, -1644817 }
+ },
+ {
+ { -23104652, 6253476, 16964147, -3768872, -25113972, -12296437, -27457225, -16344658, 6335692, 7249989 },
+ { -30333227, 13979675, 7503222, -12368314, -11956721, -4621693, -30272269, 2682242, 25993170, -12478523 },
+ { 4364628, 5930691, 32304656, -10044554, -8054781, 15091131, 22857016, -10598955, 31820368, 15075278 }
+ },
+ {
+ { 31879134, -8918693, 17258761, 90626, -8041836, -4917709, 24162788, -9650886, -17970238, 12833045 },
+ { 19073683, 14851414, -24403169, -11860168, 7625278, 11091125, -19619190, 2074449, -9413939, 14905377 },
+ { 24483667, -11935567, -2518866, -11547418, -1553130, 15355506, -25282080, 9253129, 27628530, -7555480 }
+ },
+ {
+ { 17597607, 8340603, 19355617, 552187, 26198470, -3176583, 4593324, -9157582, -14110875, 15297016 },
+ { 510886, 14337390, -31785257, 16638632, 6328095, 2713355, -20217417, -11864220, 8683221, 2921426 },
+ { 18606791, 11874196, 27155355, -5281482, -24031742, 6265446, -25178240, -1278924, 4674690, 13890525 }
+ },
+ {
+ { 13609624, 13069022, -27372361, -13055908, 24360586, 9592974, 14977157, 9835105, 4389687, 288396 },
+ { 9922506, -519394, 13613107, 5883594, -18758345, -434263, -12304062, 8317628, 23388070, 16052080 },
+ { 12720016, 11937594, -31970060, -5028689, 26900120, 8561328, -20155687, -11632979, -14754271, -10812892 }
+ },
+ {
+ { 15961858, 14150409, 26716931, -665832, -22794328, 13603569, 11829573, 7467844, -28822128, 929275 },
+ { 11038231, -11582396, -27310482, -7316562, -10498527, -16307831, -23479533, -9371869, -21393143, 2465074 },
+ { 20017163, -4323226, 27915242, 1529148, 12396362, 15675764, 13817261, -9658066, 2463391, -4622140 }
+ },
+ {
+ { -16358878, -12663911, -12065183, 4996454, -1256422, 1073572, 9583558, 12851107, 4003896, 12673717 },
+ { -1731589, -15155870, -3262930, 16143082, 19294135, 13385325, 14741514, -9103726, 7903886, 2348101 },
+ { 24536016, -16515207, 12715592, -3862155, 1511293, 10047386, -3842346, -7129159, -28377538, 10048127 }
+ }
+},
+{ /* 27/31 */
+ {
+ { -12622226, -6204820, 30718825, 2591312, -10617028, 12192840, 18873298, -7297090, -32297756, 15221632 },
+ { -26478122, -11103864, 11546244, -1852483, 9180880, 7656409, -21343950, 2095755, 29769758, 6593415 },
+ { -31994208, -2907461, 4176912, 3264766, 12538965, -868111, 26312345, -6118678, 30958054, 8292160 }
+ },
+ {
+ { 31429822, -13959116, 29173532, 15632448, 12174511, -2760094, 32808831, 3977186, 26143136, -3148876 },
+ { 22648901, 1402143, -22799984, 13746059, 7936347, 365344, -8668633, -1674433, -3758243, -2304625 },
+ { -15491917, 8012313, -2514730, -12702462, -23965846, -10254029, -1612713, -1535569, -16664475, 8194478 }
+ },
+ {
+ { 27338066, -7507420, -7414224, 10140405, -19026427, -6589889, 27277191, 8855376, 28572286, 3005164 },
+ { 26287124, 4821776, 25476601, -4145903, -3764513, -15788984, -18008582, 1182479, -26094821, -13079595 },
+ { -7171154, 3178080, 23970071, 6201893, -17195577, -4489192, -21876275, -13982627, 32208683, -1198248 }
+ },
+ {
+ { -16657702, 2817643, -10286362, 14811298, 6024667, 13349505, -27315504, -10497842, -27672585, -11539858 },
+ { 15941029, -9405932, -21367050, 8062055, 31876073, -238629, -15278393, -1444429, 15397331, -4130193 },
+ { 8934485, -13485467, -23286397, -13423241, -32446090, 14047986, 31170398, -1441021, -27505566, 15087184 }
+ },
+ {
+ { -18357243, -2156491, 24524913, -16677868, 15520427, -6360776, -15502406, 11461896, 16788528, -5868942 },
+ { -1947386, 16013773, 21750665, 3714552, -17401782, -16055433, -3770287, -10323320, 31322514, -11615635 },
+ { 21426655, -5650218, -13648287, -5347537, -28812189, -4920970, -18275391, -14621414, 13040862, -12112948 }
+ },
+ {
+ { 11293895, 12478086, -27136401, 15083750, -29307421, 14748872, 14555558, -13417103, 1613711, 4896935 },
+ { -25894883, 15323294, -8489791, -8057900, 25967126, -13425460, 2825960, -4897045, -23971776, -11267415 },
+ { -15924766, -5229880, -17443532, 6410664, 3622847, 10243618, 20615400, 12405433, -23753030, -8436416 }
+ },
+ {
+ { -7091295, 12556208, -20191352, 9025187, -17072479, 4333801, 4378436, 2432030, 23097949, -566018 },
+ { 4565804, -16025654, 20084412, -7842817, 1724999, 189254, 24767264, 10103221, -18512313, 2424778 },
+ { 366633, -11976806, 8173090, -6890119, 30788634, 5745705, -7168678, 1344109, -3642553, 12412659 }
+ },
+ {
+ { -24001791, 7690286, 14929416, -168257, -32210835, -13412986, 24162697, -15326504, -3141501, 11179385 },
+ { 18289522, -14724954, 8056945, 16430056, -21729724, 7842514, -6001441, -1486897, -18684645, -11443503 },
+ { 476239, 6601091, -6152790, -9723375, 17503545, -4863900, 27672959, 13403813, 11052904, 5219329 }
+ }
+},
+{ /* 28/31 */
+ {
+ { 20678546, -8375738, -32671898, 8849123, -5009758, 14574752, 31186971, -3973730, 9014762, -8579056 },
+ { -13644050, -10350239, -15962508, 5075808, -1514661, -11534600, -33102500, 9160280, 8473550, -3256838 },
+ { 24900749, 14435722, 17209120, -15292541, -22592275, 9878983, -7689309, -16335821, -24568481, 11788948 }
+ },
+ {
+ { -3118155, -11395194, -13802089, 14797441, 9652448, -6845904, -20037437, 10410733, -24568470, -1458691 },
+ { -15659161, 16736706, -22467150, 10215878, -9097177, 7563911, 11871841, -12505194, -18513325, 8464118 },
+ { -23400612, 8348507, -14585951, -861714, -3950205, -6373419, 14325289, 8628612, 33313881, -8370517 }
+ },
+ {
+ { -20186973, -4967935, 22367356, 5271547, -1097117, -4788838, -24805667, -10236854, -8940735, -5818269 },
+ { -6948785, -1795212, -32625683, -16021179, 32635414, -7374245, 15989197, -12838188, 28358192, -4253904 },
+ { -23561781, -2799059, -32351682, -1661963, -9147719, 10429267, -16637684, 4072016, -5351664, 5596589 }
+ },
+ {
+ { -28236598, -3390048, 12312896, 6213178, 3117142, 16078565, 29266239, 2557221, 1768301, 15373193 },
+ { -7243358, -3246960, -4593467, -7553353, -127927, -912245, -1090902, -4504991, -24660491, 3442910 },
+ { -30210571, 5124043, 14181784, 8197961, 18964734, -11939093, 22597931, 7176455, -18585478, 13365930 }
+ },
+ {
+ { -7877390, -1499958, 8324673, 4690079, 6261860, 890446, 24538107, -8570186, -9689599, -3031667 },
+ { 25008904, -10771599, -4305031, -9638010, 16265036, 15721635, 683793, -11823784, 15723479, -15163481 },
+ { -9660625, 12374379, -27006999, -7026148, -7724114, -12314514, 11879682, 5400171, 519526, -1235876 }
+ },
+ {
+ { 22258397, -16332233, -7869817, 14613016, -22520255, -2950923, -20353881, 7315967, 16648397, 7605640 },
+ { -8081308, -8464597, -8223311, 9719710, 19259459, -15348212, 23994942, -5281555, -9468848, 4763278 },
+ { -21699244, 9220969, -15730624, 1084137, -25476107, -2852390, 31088447, -7764523, -11356529, 728112 }
+ },
+ {
+ { 26047220, -11751471, -6900323, -16521798, 24092068, 9158119, -4273545, -12555558, -29365436, -5498272 },
+ { 17510331, -322857, 5854289, 8403524, 17133918, -3112612, -28111007, 12327945, 10750447, 10014012 },
+ { -10312768, 3936952, 9156313, -8897683, 16498692, -994647, -27481051, -666732, 3424691, 7540221 }
+ },
+ {
+ { 30322361, -6964110, 11361005, -4143317, 7433304, 4989748, -7071422, -16317219, -9244265, 15258046 },
+ { 13054562, -2779497, 19155474, 469045, -12482797, 4566042, 5631406, 2711395, 1062915, -5136345 },
+ { -19240248, -11254599, -29509029, -7499965, -5835763, 13005411, -6066489, 12194497, 32960380, 1459310 }
+ }
+},
+{ /* 29/31 */
+ {
+ { 19852034, 7027924, 23669353, 10020366, 8586503, -6657907, 394197, -6101885, 18638003, -11174937 },
+ { 31395534, 15098109, 26581030, 8030562, -16527914, -5007134, 9012486, -7584354, -6643087, -5442636 },
+ { -9192165, -2347377, -1997099, 4529534, 25766844, 607986, -13222, 9677543, -32294889, -6456008 }
+ },
+ {
+ { -2444496, -149937, 29348902, 8186665, 1873760, 12489863, -30934579, -7839692, -7852844, -8138429 },
+ { -15236356, -15433509, 7766470, 746860, 26346930, -10221762, -27333451, 10754588, -9431476, 5203576 },
+ { 31834314, 14135496, -770007, 5159118, 20917671, -16768096, -7467973, -7337524, 31809243, 7347066 }
+ },
+ {
+ { -9606723, -11874240, 20414459, 13033986, 13716524, -11691881, 19797970, -12211255, 15192876, -2087490 },
+ { -12663563, -2181719, 1168162, -3804809, 26747877, -14138091, 10609330, 12694420, 33473243, -13382104 },
+ { 33184999, 11180355, 15832085, -11385430, -1633671, 225884, 15089336, -11023903, -6135662, 14480053 }
+ },
+ {
+ { 31308717, -5619998, 31030840, -1897099, 15674547, -6582883, 5496208, 13685227, 27595050, 8737275 },
+ { -20318852, -15150239, 10933843, -16178022, 8335352, -7546022, -31008351, -12610604, 26498114, 66511 },
+ { 22644454, -8761729, -16671776, 4884562, -3105614, -13559366, 30540766, -4286747, -13327787, -7515095 }
+ },
+ {
+ { -28017847, 9834845, 18617207, -2681312, -3401956, -13307506, 8205540, 13585437, -17127465, 15115439 },
+ { 23711543, -672915, 31206561, -8362711, 6164647, -9709987, -33535882, -1426096, 8236921, 16492939 },
+ { -23910559, -13515526, -26299483, -4503841, 25005590, -7687270, 19574902, 10071562, 6708380, -6222424 }
+ },
+ {
+ { 2101391, -4930054, 19702731, 2367575, -15427167, 1047675, 5301017, 9328700, 29955601, -11678310 },
+ { 3096359, 9271816, -21620864, -15521844, -14847996, -7592937, -25892142, -12635595, -9917575, 6216608 },
+ { -32615849, 338663, -25195611, 2510422, -29213566, -13820213, 24822830, -6146567, -26767480, 7525079 }
+ },
+ {
+ { -23066649, -13985623, 16133487, -7896178, -3389565, 778788, -910336, -2782495, -19386633, 11994101 },
+ { 21691500, -13624626, -641331, -14367021, 3285881, -3483596, -25064666, 9718258, -7477437, 13381418 },
+ { 18445390, -4202236, 14979846, 11622458, -1727110, -3582980, 23111648, -6375247, 28535282, 15779576 }
+ },
+ {
+ { 30098053, 3089662, -9234387, 16662135, -21306940, 11308411, -14068454, 12021730, 9955285, -16303356 },
+ { 9734894, -14576830, -7473633, -9138735, 2060392, 11313496, -18426029, 9924399, 20194861, 13380996 },
+ { -26378102, -7965207, -22167821, 15789297, -18055342, -6168792, -1984914, 15707771, 26342023, 10146099 }
+ }
+},
+{ /* 30/31 */
+ {
+ { -26016874, -219943, 21339191, -41388, 19745256, -2878700, -29637280, 2227040, 21612326, -545728 },
+ { -13077387, 1184228, 23562814, -5970442, -20351244, -6348714, 25764461, 12243797, -20856566, 11649658 },
+ { -10031494, 11262626, 27384172, 2271902, 26947504, -15997771, 39944, 6114064, 33514190, 2333242 }
+ },
+ {
+ { -21433588, -12421821, 8119782, 7219913, -21830522, -9016134, -6679750, -12670638, 24350578, -13450001 },
+ { -4116307, -11271533, -23886186, 4843615, -30088339, 690623, -31536088, -10406836, 8317860, 12352766 },
+ { 18200138, -14475911, -33087759, -2696619, -23702521, -9102511, -23552096, -2287550, 20712163, 6719373 }
+ },
+ {
+ { 26656208, 6075253, -7858556, 1886072, -28344043, 4262326, 11117530, -3763210, 26224235, -3297458 },
+ { -17168938, -14854097, -3395676, -16369877, -19954045, 14050420, 21728352, 9493610, 18620611, -16428628 },
+ { -13323321, 13325349, 11432106, 5964811, 18609221, 6062965, -5269471, -9725556, -30701573, -16479657 }
+ },
+ {
+ { -23860538, -11233159, 26961357, 1640861, -32413112, -16737940, 12248509, -5240639, 13735342, 1934062 },
+ { 25089769, 6742589, 17081145, -13406266, 21909293, -16067981, -15136294, -3765346, -21277997, 5473616 },
+ { 31883677, -7961101, 1083432, -11572403, 22828471, 13290673, -7125085, 12469656, 29111212, -5451014 }
+ },
+ {
+ { 24244947, -15050407, -26262976, 2791540, -14997599, 16666678, 24367466, 6388839, -10295587, 452383 },
+ { -25640782, -3417841, 5217916, 16224624, 19987036, -4082269, -24236251, -5915248, 15766062, 8407814 },
+ { -20406999, 13990231, 15495425, 16395525, 5377168, 15166495, -8917023, -4388953, -8067909, 2276718 }
+ },
+ {
+ { 30157918, 12924066, -17712050, 9245753, 19895028, 3368142, -23827587, 5096219, 22740376, -7303417 },
+ { 2041139, -14256350, 7783687, 13876377, -25946985, -13352459, 24051124, 13742383, -15637599, 13295222 },
+ { 33338237, -8505733, 12532113, 7977527, 9106186, -1715251, -17720195, -4612972, -4451357, -14669444 }
+ },
+ {
+ { -20045281, 5454097, -14346548, 6447146, 28862071, 1883651, -2469266, -4141880, 7770569, 9620597 },
+ { 23208068, 7979712, 33071466, 8149229, 1758231, -10834995, 30945528, -1694323, -33502340, -14767970 },
+ { 1439958, -16270480, -1079989, -793782, 4625402, 10647766, -5043801, 1220118, 30494170, -11440799 }
+ },
+ {
+ { -5037580, -13028295, -2970559, -3061767, 15640974, -6701666, -26739026, 926050, -1684339, -13333647 },
+ { 13908495, -3549272, 30919928, -6273825, -21521863, 7989039, 9021034, 9078865, 3353509, 4033511 },
+ { -29663431, -15113610, 32259991, -344482, 24295849, -12912123, 23161163, 8839127, 27485041, 7356032 }
+ }
+},
+{ /* 31/31 */
+ {
+ { 9661027, 705443, 11980065, -5370154, -1628543, 14661173, -6346142, 2625015, 28431036, -16771834 },
+ { -23839233, -8311415, -25945511, 7480958, -17681669, -8354183, -22545972, 14150565, 15970762, 4099461 },
+ { 29262576, 16756590, 26350592, -8793563, 8529671, -11208050, 13617293, -9937143, 11465739, 8317062 }
+ },
+ {
+ { -25493081, -6962928, 32500200, -9419051, -23038724, -2302222, 14898637, 3848455, 20969334, -5157516 },
+ { -20384450, -14347713, -18336405, 13884722, -33039454, 2842114, -21610826, -3649888, 11177095, 14989547 },
+ { -24496721, -11716016, 16959896, 2278463, 12066309, 10137771, 13515641, 2581286, -28487508, 9930240 }
+ },
+ {
+ { -17751622, -2097826, 16544300, -13009300, -15914807, -14949081, 18345767, -13403753, 16291481, -5314038 },
+ { -33229194, 2553288, 32678213, 9875984, 8534129, 6889387, -9676774, 6957617, 4368891, 9788741 },
+ { 16660756, 7281060, -10830758, 12911820, 20108584, -8101676, -21722536, -8613148, 16250552, -11111103 }
+ },
+ {
+ { -19765507, 2390526, -16551031, 14161980, 1905286, 6414907, 4689584, 10604807, -30190403, 4782747 },
+ { -1354539, 14736941, -7367442, -13292886, 7710542, -14155590, -9981571, 4383045, 22546403, 437323 },
+ { 31665577, -12180464, -16186830, 1491339, -18368625, 3294682, 27343084, 2786261, -30633590, -14097016 }
+ },
+ {
+ { -14467279, -683715, -33374107, 7448552, 19294360, 14334329, -19690631, 2355319, -19284671, -6114373 },
+ { 15121312, -15796162, 6377020, -6031361, -10798111, -12957845, 18952177, 15496498, -29380133, 11754228 },
+ { -2637277, -13483075, 8488727, -14303896, 12728761, -1622493, 7141596, 11724556, 22761615, -10134141 }
+ },
+ {
+ { 16918416, 11729663, -18083579, 3022987, -31015732, -13339659, -28741185, -12227393, 32851222, 11717399 },
+ { 11166634, 7338049, -6722523, 4531520, -29468672, -7302055, 31474879, 3483633, -1193175, -4030831 },
+ { -185635, 9921305, 31456609, -13536438, -12013818, 13348923, 33142652, 6546660, -19985279, -3948376 }
+ },
+ {
+ { -32460596, 11266712, -11197107, -7899103, 31703694, 3855903, -8537131, -12833048, -30772034, -15486313 },
+ { -18006477, 12709068, 3991746, -6479188, -21491523, -10550425, -31135347, -16049879, 10928917, 3011958 },
+ { -6957757, -15594337, 31696059, 334240, 29576716, 14796075, -30831056, -12805180, 18008031, 10258577 }
+ },
+ {
+ { -22448644, 15655569, 7018479, -4410003, -30314266, -1201591, -1853465, 1367120, 25127874, 6671743 },
+ { 29701166, -14373934, -10878120, 9279288, -17568, 13127210, 21382910, 11042292, 25838796, 4642684 },
+ { -20430234, 14955537, -24126347, 8124619, -5369288, -5990470, 30468147, -13900640, 18423289, 4177476 }
+ }
+}
diff --git a/third_party/heimdal/lib/hcrypto/x25519/fe_25_5/base2.h b/third_party/heimdal/lib/hcrypto/x25519/fe_25_5/base2.h
new file mode 100644
index 0000000..90a1457
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/fe_25_5/base2.h
@@ -0,0 +1,40 @@
+{
+ { 25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605 },
+ { -12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378 },
+ { -8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546 }
+},
+{
+ { 15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024 },
+ { 16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574 },
+ { 30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357 }
+},
+{
+ { 10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380 },
+ { 4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306 },
+ { 19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942 }
+},
+{
+ { 5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766 },
+ { -30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701 },
+ { 28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300 }
+},
+{
+ { -22518993, -6692182, 14201702, -8745502, -23510406, 8844726, 18474211, -1361450, -13062696, 13821877 },
+ { -6455177, -7839871, 3374702, -4740862, -27098617, -10571707, 31655028, -7212327, 18853322, -14220951 },
+ { 4566830, -12963868, -28974889, -12240689, -7602672, -2830569, -8514358, -10431137, 2207753, -3209784 }
+},
+{
+ { -25154831, -4185821, 29681144, 7868801, -6854661, -9423865, -12437364, -663000, -31111463, -16132436 },
+ { 25576264, -2703214, 7349804, -11814844, 16472782, 9300885, 3844789, 15725684, 171356, 6466918 },
+ { 23103977, 13316479, 9739013, -16149481, 817875, -15038942, 8965339, -14088058, -30714912, 16193877 }
+},
+{
+ { -33521811, 3180713, -2394130, 14003687, -16903474, -16270840, 17238398, 4729455, -18074513, 9256800 },
+ { -25182317, -4174131, 32336398, 5036987, -21236817, 11360617, 22616405, 9761698, -19827198, 630305 },
+ { -13720693, 2639453, -24237460, -7406481, 9494427, -5774029, -6554551, -15960994, -2449256, -14291300 }
+},
+{
+ { -3151181, -5046075, 9282714, 6866145, -31907062, -863023, -18940575, 15033784, 25105118, -7894876 },
+ { -24326370, 15950226, -31801215, -14592823, -11662737, -5090925, 1573892, -2625887, 2198790, -15804619 },
+ { -3099351, 10324967, -2241613, 7453183, -5446979, -2735503, -13812022, -16236442, -32461234, -12290683 }
+}
diff --git a/third_party/heimdal/lib/hcrypto/x25519/fe_25_5/constants.h b/third_party/heimdal/lib/hcrypto/x25519/fe_25_5/constants.h
new file mode 100644
index 0000000..dd6da1b
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/fe_25_5/constants.h
@@ -0,0 +1,40 @@
+/* 37095705934669439343138083508754565189542113879843219016388785533085940283555 */
+static const fe25519 d = {
+ -10913610, 13857413, -15372611, 6949391, 114729, -8787816, -6275908, -3247719, -18696448, -12055116
+};
+
+/* 2 * d =
+ * 16295367250680780974490674513165176452449235426866156013048779062215315747161
+ */
+static const fe25519 d2 = {
+ -21827239, -5839606, -30745221, 13898782, 229458, 15978800, -12551817, -6495438, 29715968, 9444199 };
+
+/* sqrt(-1) */
+static const fe25519 sqrtm1 = {
+ -32595792, -7943725, 9377950, 3500415, 12389472, -272473, -25146209, -2005654, 326686, 11406482
+};
+
+/* A = 486662 */
+static const fe25519 curve25519_A = {
+ 486662, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+/* sqrt(ad - 1) with a = -1 (mod p) */
+static const fe25519 sqrtadm1 = {
+ 24849947, -153582, -23613485, 6347715, -21072328, -667138, -25271143, -15367704, -870347, 14525639
+};
+
+/* 1 / sqrt(a - d) */
+static const fe25519 invsqrtamd = {
+ 6111485, 4156064, -27798727, 12243468, -25904040, 120897, 20826367, -7060776, 6093568, -1986012
+};
+
+/* 1 - d ^ 2 */
+static const fe25519 onemsqd = {
+ 6275446, -16617371, -22938544, -3773710, 11667077, 7397348, -27922721, 1766195, -24433858, 672203
+};
+
+/* (d - 1) ^ 2 */
+static const fe25519 sqdmone = {
+ 15551795, -11097455, -13425098, -10125071, -11896535, 10178284, -26634327, 4729244, -5282110, -10116402
+};
diff --git a/third_party/heimdal/lib/hcrypto/x25519/fe_25_5/fe.h b/third_party/heimdal/lib/hcrypto/x25519/fe_25_5/fe.h
new file mode 100644
index 0000000..f216669
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/fe_25_5/fe.h
@@ -0,0 +1,220 @@
+/*
+ Ignores top bit of h.
+ */
+
+void
+fe25519_frombytes(fe25519 h, const unsigned char *s)
+{
+ int64_t h0 = load_4(s);
+ int64_t h1 = load_3(s + 4) << 6;
+ int64_t h2 = load_3(s + 7) << 5;
+ int64_t h3 = load_3(s + 10) << 3;
+ int64_t h4 = load_3(s + 13) << 2;
+ int64_t h5 = load_4(s + 16);
+ int64_t h6 = load_3(s + 20) << 7;
+ int64_t h7 = load_3(s + 23) << 5;
+ int64_t h8 = load_3(s + 26) << 4;
+ int64_t h9 = (load_3(s + 29) & 8388607) << 2;
+
+ int64_t carry0;
+ int64_t carry1;
+ int64_t carry2;
+ int64_t carry3;
+ int64_t carry4;
+ int64_t carry5;
+ int64_t carry6;
+ int64_t carry7;
+ int64_t carry8;
+ int64_t carry9;
+
+ carry9 = (h9 + (int64_t)(1L << 24)) >> 25;
+ h0 += carry9 * 19;
+ h9 -= carry9 * ((uint64_t) 1L << 25);
+ carry1 = (h1 + (int64_t)(1L << 24)) >> 25;
+ h2 += carry1;
+ h1 -= carry1 * ((uint64_t) 1L << 25);
+ carry3 = (h3 + (int64_t)(1L << 24)) >> 25;
+ h4 += carry3;
+ h3 -= carry3 * ((uint64_t) 1L << 25);
+ carry5 = (h5 + (int64_t)(1L << 24)) >> 25;
+ h6 += carry5;
+ h5 -= carry5 * ((uint64_t) 1L << 25);
+ carry7 = (h7 + (int64_t)(1L << 24)) >> 25;
+ h8 += carry7;
+ h7 -= carry7 * ((uint64_t) 1L << 25);
+
+ carry0 = (h0 + (int64_t)(1L << 25)) >> 26;
+ h1 += carry0;
+ h0 -= carry0 * ((uint64_t) 1L << 26);
+ carry2 = (h2 + (int64_t)(1L << 25)) >> 26;
+ h3 += carry2;
+ h2 -= carry2 * ((uint64_t) 1L << 26);
+ carry4 = (h4 + (int64_t)(1L << 25)) >> 26;
+ h5 += carry4;
+ h4 -= carry4 * ((uint64_t) 1L << 26);
+ carry6 = (h6 + (int64_t)(1L << 25)) >> 26;
+ h7 += carry6;
+ h6 -= carry6 * ((uint64_t) 1L << 26);
+ carry8 = (h8 + (int64_t)(1L << 25)) >> 26;
+ h9 += carry8;
+ h8 -= carry8 * ((uint64_t) 1L << 26);
+
+ h[0] = (int32_t) h0;
+ h[1] = (int32_t) h1;
+ h[2] = (int32_t) h2;
+ h[3] = (int32_t) h3;
+ h[4] = (int32_t) h4;
+ h[5] = (int32_t) h5;
+ h[6] = (int32_t) h6;
+ h[7] = (int32_t) h7;
+ h[8] = (int32_t) h8;
+ h[9] = (int32_t) h9;
+}
+
+/*
+ Preconditions:
+ |h| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc.
+
+ Write p=2^255-19; q=floor(h/p).
+ Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))).
+
+ Proof:
+ Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4.
+ Also have |h-2^230 h9|<2^231 so |19 2^(-255)(h-2^230 h9)|<1/4.
+
+ Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9).
+ Then 0<y<1.
+
+ Write r=h-pq.
+ Have 0<=r<=p-1=2^255-20.
+ Thus 0<=r+19(2^-255)r<r+19(2^-255)2^255<=2^255-1.
+
+ Write x=r+19(2^-255)r+y.
+ Then 0<x<2^255 so floor(2^(-255)x) = 0 so floor(q+2^(-255)x) = q.
+
+ Have q+2^(-255)x = 2^(-255)(h + 19 2^(-25) h9 + 2^(-1))
+ so floor(2^(-255)(h + 19 2^(-25) h9 + 2^(-1))) = q.
+*/
+
+static void
+fe25519_reduce(fe25519 h, const fe25519 f)
+{
+ int32_t h0 = f[0];
+ int32_t h1 = f[1];
+ int32_t h2 = f[2];
+ int32_t h3 = f[3];
+ int32_t h4 = f[4];
+ int32_t h5 = f[5];
+ int32_t h6 = f[6];
+ int32_t h7 = f[7];
+ int32_t h8 = f[8];
+ int32_t h9 = f[9];
+
+ int32_t q;
+ int32_t carry0, carry1, carry2, carry3, carry4, carry5, carry6, carry7, carry8, carry9;
+
+ q = (19 * h9 + ((uint32_t) 1L << 24)) >> 25;
+ q = (h0 + q) >> 26;
+ q = (h1 + q) >> 25;
+ q = (h2 + q) >> 26;
+ q = (h3 + q) >> 25;
+ q = (h4 + q) >> 26;
+ q = (h5 + q) >> 25;
+ q = (h6 + q) >> 26;
+ q = (h7 + q) >> 25;
+ q = (h8 + q) >> 26;
+ q = (h9 + q) >> 25;
+
+ /* Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. */
+ h0 += 19 * q;
+ /* Goal: Output h-2^255 q, which is between 0 and 2^255-20. */
+
+ carry0 = h0 >> 26;
+ h1 += carry0;
+ h0 -= carry0 * ((uint32_t) 1L << 26);
+ carry1 = h1 >> 25;
+ h2 += carry1;
+ h1 -= carry1 * ((uint32_t) 1L << 25);
+ carry2 = h2 >> 26;
+ h3 += carry2;
+ h2 -= carry2 * ((uint32_t) 1L << 26);
+ carry3 = h3 >> 25;
+ h4 += carry3;
+ h3 -= carry3 * ((uint32_t) 1L << 25);
+ carry4 = h4 >> 26;
+ h5 += carry4;
+ h4 -= carry4 * ((uint32_t) 1L << 26);
+ carry5 = h5 >> 25;
+ h6 += carry5;
+ h5 -= carry5 * ((uint32_t) 1L << 25);
+ carry6 = h6 >> 26;
+ h7 += carry6;
+ h6 -= carry6 * ((uint32_t) 1L << 26);
+ carry7 = h7 >> 25;
+ h8 += carry7;
+ h7 -= carry7 * ((uint32_t) 1L << 25);
+ carry8 = h8 >> 26;
+ h9 += carry8;
+ h8 -= carry8 * ((uint32_t) 1L << 26);
+ carry9 = h9 >> 25;
+ h9 -= carry9 * ((uint32_t) 1L << 25);
+
+ h[0] = h0;
+ h[1] = h1;
+ h[2] = h2;
+ h[3] = h3;
+ h[4] = h4;
+ h[5] = h5;
+ h[6] = h6;
+ h[7] = h7;
+ h[8] = h8;
+ h[9] = h9;
+}
+
+/*
+ Goal: Output h0+...+2^255 h10-2^255 q, which is between 0 and 2^255-20.
+ Have h0+...+2^230 h9 between 0 and 2^255-1;
+ evidently 2^255 h10-2^255 q = 0.
+
+ Goal: Output h0+...+2^230 h9.
+ */
+
+void
+fe25519_tobytes(unsigned char *s, const fe25519 h)
+{
+ fe25519 t;
+
+ fe25519_reduce(t, h);
+ s[0] = t[0] >> 0;
+ s[1] = t[0] >> 8;
+ s[2] = t[0] >> 16;
+ s[3] = (t[0] >> 24) | (t[1] * ((uint32_t) 1 << 2));
+ s[4] = t[1] >> 6;
+ s[5] = t[1] >> 14;
+ s[6] = (t[1] >> 22) | (t[2] * ((uint32_t) 1 << 3));
+ s[7] = t[2] >> 5;
+ s[8] = t[2] >> 13;
+ s[9] = (t[2] >> 21) | (t[3] * ((uint32_t) 1 << 5));
+ s[10] = t[3] >> 3;
+ s[11] = t[3] >> 11;
+ s[12] = (t[3] >> 19) | (t[4] * ((uint32_t) 1 << 6));
+ s[13] = t[4] >> 2;
+ s[14] = t[4] >> 10;
+ s[15] = t[4] >> 18;
+ s[16] = t[5] >> 0;
+ s[17] = t[5] >> 8;
+ s[18] = t[5] >> 16;
+ s[19] = (t[5] >> 24) | (t[6] * ((uint32_t) 1 << 1));
+ s[20] = t[6] >> 7;
+ s[21] = t[6] >> 15;
+ s[22] = (t[6] >> 23) | (t[7] * ((uint32_t) 1 << 3));
+ s[23] = t[7] >> 5;
+ s[24] = t[7] >> 13;
+ s[25] = (t[7] >> 21) | (t[8] * ((uint32_t) 1 << 4));
+ s[26] = t[8] >> 4;
+ s[27] = t[8] >> 12;
+ s[28] = (t[8] >> 20) | (t[9] * ((uint32_t) 1 << 6));
+ s[29] = t[9] >> 2;
+ s[30] = t[9] >> 10;
+ s[31] = t[9] >> 18;
+}
diff --git a/third_party/heimdal/lib/hcrypto/x25519/fe_51/base.h b/third_party/heimdal/lib/hcrypto/x25519/fe_51/base.h
new file mode 100644
index 0000000..6b3b833
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/fe_51/base.h
@@ -0,0 +1,1344 @@
+{ /* 0/31 */
+ {
+ { 1288382639258501, 245678601348599, 269427782077623, 1462984067271730, 137412439391563 },
+ { 62697248952638, 204681361388450, 631292143396476, 338455783676468, 1213667448819585 },
+ { 301289933810280, 1259582250014073, 1422107436869536, 796239922652654, 1953934009299142 }
+ },
+ {
+ { 1380971894829527, 790832306631236, 2067202295274102, 1995808275510000, 1566530869037010 },
+ { 463307831301544, 432984605774163, 1610641361907204, 750899048855000, 1894842303421586 },
+ { 748439484463711, 1033211726465151, 1396005112841647, 1611506220286469, 1972177495910992 }
+ },
+ {
+ { 1601611775252272, 1720807796594148, 1132070835939856, 1260455018889551, 2147779492816911 },
+ { 316559037616741, 2177824224946892, 1459442586438991, 1461528397712656, 751590696113597 },
+ { 1850748884277385, 1200145853858453, 1068094770532492, 672251375690438, 1586055907191707 }
+ },
+ {
+ { 934282339813791, 1846903124198670, 1172395437954843, 1007037127761661, 1830588347719256 },
+ { 1694390458783935, 1735906047636159, 705069562067493, 648033061693059, 696214010414170 },
+ { 1121406372216585, 192876649532226, 190294192191717, 1994165897297032, 2245000007398739 }
+ },
+ {
+ { 769950342298419, 132954430919746, 844085933195555, 974092374476333, 726076285546016 },
+ { 425251763115706, 608463272472562, 442562545713235, 837766094556764, 374555092627893 },
+ { 1086255230780037, 274979815921559, 1960002765731872, 929474102396301, 1190409889297339 }
+ },
+ {
+ { 1388594989461809, 316767091099457, 394298842192982, 1230079486801005, 1440737038838979 },
+ { 7380825640100, 146210432690483, 304903576448906, 1198869323871120, 997689833219095 },
+ { 1181317918772081, 114573476638901, 262805072233344, 265712217171332, 294181933805782 }
+ },
+ {
+ { 665000864555967, 2065379846933859, 370231110385876, 350988370788628, 1233371373142985 },
+ { 2019367628972465, 676711900706637, 110710997811333, 1108646842542025, 517791959672113 },
+ { 965130719900578, 247011430587952, 526356006571389, 91986625355052, 2157223321444601 }
+ },
+ {
+ { 2068619540119183, 1966274918058806, 957728544705549, 729906502578991, 159834893065166 },
+ { 2073601412052185, 31021124762708, 264500969797082, 248034690651703, 1030252227928288 },
+ { 551790716293402, 1989538725166328, 801169423371717, 2052451893578887, 678432056995012 }
+ }
+},
+{ /* 1/31 */
+ {
+ { 1368953770187805, 790347636712921, 437508475667162, 2142576377050580, 1932081720066286 },
+ { 953638594433374, 1092333936795051, 1419774766716690, 805677984380077, 859228993502513 },
+ { 1200766035879111, 20142053207432, 1465634435977050, 1645256912097844, 295121984874596 }
+ },
+ {
+ { 1735718747031557, 1248237894295956, 1204753118328107, 976066523550493, 65943769534592 },
+ { 1060098822528990, 1586825862073490, 212301317240126, 1975302711403555, 666724059764335 },
+ { 1091990273418756, 1572899409348578, 80968014455247, 306009358661350, 1520450739132526 }
+ },
+ {
+ { 1480517209436112, 1511153322193952, 1244343858991172, 304788150493241, 369136856496443 },
+ { 2151330273626164, 762045184746182, 1688074332551515, 823046109005759, 907602769079491 },
+ { 2047386910586836, 168470092900250, 1552838872594810, 340951180073789, 360819374702533 }
+ },
+ {
+ { 1982622644432056, 2014393600336956, 128909208804214, 1617792623929191, 105294281913815 },
+ { 980234343912898, 1712256739246056, 588935272190264, 204298813091998, 841798321043288 },
+ { 197561292938973, 454817274782871, 1963754960082318, 2113372252160468, 971377527342673 }
+ },
+ {
+ { 164699448829328, 3127451757672, 1199504971548753, 1766155447043652, 1899238924683527 },
+ { 732262946680281, 1674412764227063, 2182456405662809, 1350894754474250, 558458873295247 },
+ { 2103305098582922, 1960809151316468, 715134605001343, 1454892949167181, 40827143824949 }
+ },
+ {
+ { 1239289043050212, 1744654158124578, 758702410031698, 1796762995074688, 1603056663766 },
+ { 2232056027107988, 987343914584615, 2115594492994461, 1819598072792159, 1119305654014850 },
+ { 320153677847348, 939613871605645, 641883205761567, 1930009789398224, 329165806634126 }
+ },
+ {
+ { 980930490474130, 1242488692177893, 1251446316964684, 1086618677993530, 1961430968465772 },
+ { 276821765317453, 1536835591188030, 1305212741412361, 61473904210175, 2051377036983058 },
+ { 833449923882501, 1750270368490475, 1123347002068295, 185477424765687, 278090826653186 }
+ },
+ {
+ { 794524995833413, 1849907304548286, 53348672473145, 1272368559505217, 1147304168324779 },
+ { 1504846112759364, 1203096289004681, 562139421471418, 274333017451844, 1284344053775441 },
+ { 483048732424432, 2116063063343382, 30120189902313, 292451576741007, 1156379271702225 }
+ }
+},
+{ /* 2/31 */
+ {
+ { 928372153029038, 2147692869914564, 1455665844462196, 1986737809425946, 185207050258089 },
+ { 137732961814206, 706670923917341, 1387038086865771, 1965643813686352, 1384777115696347 },
+ { 481144981981577, 2053319313589856, 2065402289827512, 617954271490316, 1106602634668125 }
+ },
+ {
+ { 696298019648792, 893299659040895, 1148636718636009, 26734077349617, 2203955659340681 },
+ { 657390353372855, 998499966885562, 991893336905797, 810470207106761, 343139804608786 },
+ { 791736669492960, 934767652997115, 824656780392914, 1759463253018643, 361530362383518 }
+ },
+ {
+ { 2022541353055597, 2094700262587466, 1551008075025686, 242785517418164, 695985404963562 },
+ { 1287487199965223, 2215311941380308, 1552928390931986, 1664859529680196, 1125004975265243 },
+ { 677434665154918, 989582503122485, 1817429540898386, 1052904935475344, 1143826298169798 }
+ },
+ {
+ { 367266328308408, 318431188922404, 695629353755355, 634085657580832, 24581612564426 },
+ { 773360688841258, 1815381330538070, 363773437667376, 539629987070205, 783280434248437 },
+ { 180820816194166, 168937968377394, 748416242794470, 1227281252254508, 1567587861004268 }
+ },
+ {
+ { 478775558583645, 2062896624554807, 699391259285399, 358099408427873, 1277310261461761 },
+ { 1984740906540026, 1079164179400229, 1056021349262661, 1659958556483663, 1088529069025527 },
+ { 580736401511151, 1842931091388998, 1177201471228238, 2075460256527244, 1301133425678027 }
+ },
+ {
+ { 1515728832059182, 1575261009617579, 1510246567196186, 191078022609704, 116661716289141 },
+ { 1295295738269652, 1714742313707026, 545583042462581, 2034411676262552, 1513248090013606 },
+ { 230710545179830, 30821514358353, 760704303452229, 390668103790604, 573437871383156 }
+ },
+ {
+ { 1169380107545646, 263167233745614, 2022901299054448, 819900753251120, 2023898464874585 },
+ { 2102254323485823, 1570832666216754, 34696906544624, 1993213739807337, 70638552271463 },
+ { 894132856735058, 548675863558441, 845349339503395, 1942269668326667, 1615682209874691 }
+ },
+ {
+ { 1287670217537834, 1222355136884920, 1846481788678694, 1150426571265110, 1613523400722047 },
+ { 793388516527298, 1315457083650035, 1972286999342417, 1901825953052455, 338269477222410 },
+ { 550201530671806, 778605267108140, 2063911101902983, 115500557286349, 2041641272971022 }
+ }
+},
+{ /* 3/31 */
+ {
+ { 717255318455100, 519313764361315, 2080406977303708, 541981206705521, 774328150311600 },
+ { 261715221532238, 1795354330069993, 1496878026850283, 499739720521052, 389031152673770 },
+ { 1997217696294013, 1717306351628065, 1684313917746180, 1644426076011410, 1857378133465451 }
+ },
+ {
+ { 1475434724792648, 76931896285979, 1116729029771667, 2002544139318042, 725547833803938 },
+ { 2022306639183567, 726296063571875, 315345054448644, 1058733329149221, 1448201136060677 },
+ { 1710065158525665, 1895094923036397, 123988286168546, 1145519900776355, 1607510767693874 }
+ },
+ {
+ { 561605375422540, 1071733543815037, 131496498800990, 1946868434569999, 828138133964203 },
+ { 1548495173745801, 442310529226540, 998072547000384, 553054358385281, 644824326376171 },
+ { 1445526537029440, 2225519789662536, 914628859347385, 1064754194555068, 1660295614401091 }
+ },
+ {
+ { 1199690223111956, 24028135822341, 66638289244341, 57626156285975, 565093967979607 },
+ { 876926774220824, 554618976488214, 1012056309841565, 839961821554611, 1414499340307677 },
+ { 703047626104145, 1266841406201770, 165556500219173, 486991595001879, 1011325891650656 }
+ },
+ {
+ { 1622861044480487, 1156394801573634, 1869132565415504, 327103985777730, 2095342781472284 },
+ { 334886927423922, 489511099221528, 129160865966726, 1720809113143481, 619700195649254 },
+ { 1646545795166119, 1758370782583567, 714746174550637, 1472693650165135, 898994790308209 }
+ },
+ {
+ { 333403773039279, 295772542452938, 1693106465353610, 912330357530760, 471235657950362 },
+ { 1811196219982022, 1068969825533602, 289602974833439, 1988956043611592, 863562343398367 },
+ { 906282429780072, 2108672665779781, 432396390473936, 150625823801893, 1708930497638539 }
+ },
+ {
+ { 925664675702328, 21416848568684, 1831436641861340, 601157008940113, 371818055044496 },
+ { 1479786007267725, 1738881859066675, 68646196476567, 2146507056100328, 1247662817535471 },
+ { 52035296774456, 939969390708103, 312023458773250, 59873523517659, 1231345905848899 }
+ },
+ {
+ { 643355106415761, 290186807495774, 2013561737429023, 319648069511546, 393736678496162 },
+ { 129358342392716, 1932811617704777, 1176749390799681, 398040349861790, 1170779668090425 },
+ { 2051980782668029, 121859921510665, 2048329875753063, 1235229850149665, 519062146124755 }
+ }
+},
+{ /* 4/31 */
+ {
+ { 1608170971973096, 415809060360428, 1350468408164766, 2038620059057678, 1026904485989112 },
+ { 1837656083115103, 1510134048812070, 906263674192061, 1821064197805734, 565375124676301 },
+ { 578027192365650, 2034800251375322, 2128954087207123, 478816193810521, 2196171989962750 }
+ },
+ {
+ { 1633188840273139, 852787172373708, 1548762607215796, 1266275218902681, 1107218203325133 },
+ { 462189358480054, 1784816734159228, 1611334301651368, 1303938263943540, 707589560319424 },
+ { 1038829280972848, 38176604650029, 753193246598573, 1136076426528122, 595709990562434 }
+ },
+ {
+ { 1408451820859834, 2194984964010833, 2198361797561729, 1061962440055713, 1645147963442934 },
+ { 4701053362120, 1647641066302348, 1047553002242085, 1923635013395977, 206970314902065 },
+ { 1750479161778571, 1362553355169293, 1891721260220598, 966109370862782, 1024913988299801 }
+ },
+ {
+ { 212699049131723, 1117950018299775, 1873945661751056, 1403802921984058, 130896082652698 },
+ { 636808533673210, 1262201711667560, 390951380330599, 1663420692697294, 561951321757406 },
+ { 520731594438141, 1446301499955692, 273753264629267, 1565101517999256, 1019411827004672 }
+ },
+ {
+ { 926527492029409, 1191853477411379, 734233225181171, 184038887541270, 1790426146325343 },
+ { 1464651961852572, 1483737295721717, 1519450561335517, 1161429831763785, 405914998179977 },
+ { 996126634382301, 796204125879525, 127517800546509, 344155944689303, 615279846169038 }
+ },
+ {
+ { 738724080975276, 2188666632415296, 1961313708559162, 1506545807547587, 1151301638969740 },
+ { 622917337413835, 1218989177089035, 1284857712846592, 970502061709359, 351025208117090 },
+ { 2067814584765580, 1677855129927492, 2086109782475197, 235286517313238, 1416314046739645 }
+ },
+ {
+ { 586844262630358, 307444381952195, 458399356043426, 602068024507062, 1028548203415243 },
+ { 678489922928203, 2016657584724032, 90977383049628, 1026831907234582, 615271492942522 },
+ { 301225714012278, 1094837270268560, 1202288391010439, 644352775178361, 1647055902137983 }
+ },
+ {
+ { 1210746697896478, 1416608304244708, 686487477217856, 1245131191434135, 1051238336855737 },
+ { 1135604073198207, 1683322080485474, 769147804376683, 2086688130589414, 900445683120379 },
+ { 1971518477615628, 401909519527336, 448627091057375, 1409486868273821, 1214789035034363 }
+ }
+},
+{ /* 5/31 */
+ {
+ { 1364039144731711, 1897497433586190, 2203097701135459, 145461396811251, 1349844460790699 },
+ { 1045230323257973, 818206601145807, 630513189076103, 1672046528998132, 807204017562437 },
+ { 439961968385997, 386362664488986, 1382706320807688, 309894000125359, 2207801346498567 }
+ },
+ {
+ { 1229004686397588, 920643968530863, 123975893911178, 681423993215777, 1400559197080973 },
+ { 2003766096898049, 170074059235165, 1141124258967971, 1485419893480973, 1573762821028725 },
+ { 729905708611432, 1270323270673202, 123353058984288, 426460209632942, 2195574535456672 }
+ },
+ {
+ { 1271140255321235, 2044363183174497, 52125387634689, 1445120246694705, 942541986339084 },
+ { 1761608437466135, 583360847526804, 1586706389685493, 2157056599579261, 1170692369685772 },
+ { 871476219910823, 1878769545097794, 2241832391238412, 548957640601001, 690047440233174 }
+ },
+ {
+ { 297194732135507, 1366347803776820, 1301185512245601, 561849853336294, 1533554921345731 },
+ { 999628998628371, 1132836708493400, 2084741674517453, 469343353015612, 678782988708035 },
+ { 2189427607417022, 699801937082607, 412764402319267, 1478091893643349, 2244675696854460 }
+ },
+ {
+ { 1712292055966563, 204413590624874, 1405738637332841, 408981300829763, 861082219276721 },
+ { 508561155940631, 966928475686665, 2236717801150132, 424543858577297, 2089272956986143 },
+ { 221245220129925, 1156020201681217, 491145634799213, 542422431960839, 828100817819207 }
+ },
+ {
+ { 153756971240384, 1299874139923977, 393099165260502, 1058234455773022, 996989038681183 },
+ { 559086812798481, 573177704212711, 1629737083816402, 1399819713462595, 1646954378266038 },
+ { 1887963056288059, 228507035730124, 1468368348640282, 930557653420194, 613513962454686 }
+ },
+ {
+ { 1224529808187553, 1577022856702685, 2206946542980843, 625883007765001, 279930793512158 },
+ { 1076287717051609, 1114455570543035, 187297059715481, 250446884292121, 1885187512550540 },
+ { 902497362940219, 76749815795675, 1657927525633846, 1420238379745202, 1340321636548352 }
+ },
+ {
+ { 1129576631190784, 1281994010027327, 996844254743018, 257876363489249, 1150850742055018 },
+ { 628740660038789, 1943038498527841, 467786347793886, 1093341428303375, 235413859513003 },
+ { 237425418909360, 469614029179605, 1512389769174935, 1241726368345357, 441602891065214 }
+ }
+},
+{ /* 6/31 */
+ {
+ { 1736417953058555, 726531315520508, 1833335034432527, 1629442561574747, 624418919286085 },
+ { 1960754663920689, 497040957888962, 1909832851283095, 1271432136996826, 2219780368020940 },
+ { 1537037379417136, 1358865369268262, 2130838645654099, 828733687040705, 1999987652890901 }
+ },
+ {
+ { 629042105241814, 1098854999137608, 887281544569320, 1423102019874777, 7911258951561 },
+ { 1811562332665373, 1501882019007673, 2213763501088999, 359573079719636, 36370565049116 },
+ { 218907117361280, 1209298913016966, 1944312619096112, 1130690631451061, 1342327389191701 }
+ },
+ {
+ { 1369976867854704, 1396479602419169, 1765656654398856, 2203659200586299, 998327836117241 },
+ { 2230701885562825, 1348173180338974, 2172856128624598, 1426538746123771, 444193481326151 },
+ { 784210426627951, 918204562375674, 1284546780452985, 1324534636134684, 1872449409642708 }
+ },
+ {
+ { 319638829540294, 596282656808406, 2037902696412608, 1557219121643918, 341938082688094 },
+ { 1901860206695915, 2004489122065736, 1625847061568236, 973529743399879, 2075287685312905 },
+ { 1371853944110545, 1042332820512553, 1949855697918254, 1791195775521505, 37487364849293 }
+ },
+ {
+ { 687200189577855, 1082536651125675, 644224940871546, 340923196057951, 343581346747396 },
+ { 2082717129583892, 27829425539422, 145655066671970, 1690527209845512, 1865260509673478 },
+ { 1059729620568824, 2163709103470266, 1440302280256872, 1769143160546397, 869830310425069 }
+ },
+ {
+ { 1609516219779025, 777277757338817, 2101121130363987, 550762194946473, 1905542338659364 },
+ { 2024821921041576, 426948675450149, 595133284085473, 471860860885970, 600321679413000 },
+ { 598474602406721, 1468128276358244, 1191923149557635, 1501376424093216, 1281662691293476 }
+ },
+ {
+ { 1721138489890707, 1264336102277790, 433064545421287, 1359988423149466, 1561871293409447 },
+ { 719520245587143, 393380711632345, 132350400863381, 1543271270810729, 1819543295798660 },
+ { 396397949784152, 1811354474471839, 1362679985304303, 2117033964846756, 498041172552279 }
+ },
+ {
+ { 1812471844975748, 1856491995543149, 126579494584102, 1036244859282620, 1975108050082550 },
+ { 650623932407995, 1137551288410575, 2125223403615539, 1725658013221271, 2134892965117796 },
+ { 522584000310195, 1241762481390450, 1743702789495384, 2227404127826575, 1686746002148897 }
+ }
+},
+{ /* 7/31 */
+ {
+ { 427904865186312, 1703211129693455, 1585368107547509, 1436984488744336, 761188534613978 },
+ { 318101947455002, 248138407995851, 1481904195303927, 309278454311197, 1258516760217879 },
+ { 1275068538599310, 513726919533379, 349926553492294, 688428871968420, 1702400196000666 }
+ },
+ {
+ { 1061864036265233, 961611260325381, 321859632700838, 1045600629959517, 1985130202504038 },
+ { 1558816436882417, 1962896332636523, 1337709822062152, 1501413830776938, 294436165831932 },
+ { 818359826554971, 1862173000996177, 626821592884859, 573655738872376, 1749691246745455 }
+ },
+ {
+ { 1988022651432119, 1082111498586040, 1834020786104821, 1454826876423687, 692929915223122 },
+ { 2146513703733331, 584788900394667, 464965657279958, 2183973639356127, 238371159456790 },
+ { 1129007025494441, 2197883144413266, 265142755578169, 971864464758890, 1983715884903702 }
+ },
+ {
+ { 1291366624493075, 381456718189114, 1711482489312444, 1815233647702022, 892279782992467 },
+ { 444548969917454, 1452286453853356, 2113731441506810, 645188273895859, 810317625309512 },
+ { 2242724082797924, 1373354730327868, 1006520110883049, 2147330369940688, 1151816104883620 }
+ },
+ {
+ { 1745720200383796, 1911723143175317, 2056329390702074, 355227174309849, 879232794371100 },
+ { 163723479936298, 115424889803150, 1156016391581227, 1894942220753364, 1970549419986329 },
+ { 681981452362484, 267208874112496, 1374683991933094, 638600984916117, 646178654558546 }
+ },
+ {
+ { 13378654854251, 106237307029567, 1944412051589651, 1841976767925457, 230702819835573 },
+ { 260683893467075, 854060306077237, 913639551980112, 4704576840123, 280254810808712 },
+ { 715374893080287, 1173334812210491, 1806524662079626, 1894596008000979, 398905715033393 }
+ },
+ {
+ { 500026409727661, 1596431288195371, 1420380351989370, 985211561521489, 392444930785633 },
+ { 2096421546958141, 1922523000950363, 789831022876840, 427295144688779, 320923973161730 },
+ { 1927770723575450, 1485792977512719, 1850996108474547, 551696031508956, 2126047405475647 }
+ },
+ {
+ { 2112099158080148, 742570803909715, 6484558077432, 1951119898618916, 93090382703416 },
+ { 383905201636970, 859946997631870, 855623867637644, 1017125780577795, 794250831877809 },
+ { 77571826285752, 999304298101753, 487841111777762, 1038031143212339, 339066367948762 }
+ }
+},
+{ /* 8/31 */
+ {
+ { 674994775520533, 266035846330789, 826951213393478, 1405007746162285, 1781791018620876 },
+ { 1001412661522686, 348196197067298, 1666614366723946, 888424995032760, 580747687801357 },
+ { 1939560076207777, 1409892634407635, 552574736069277, 383854338280405, 190706709864139 }
+ },
+ {
+ { 2177087163428741, 1439255351721944, 1208070840382793, 2230616362004769, 1396886392021913 },
+ { 676962063230039, 1880275537148808, 2046721011602706, 888463247083003, 1318301552024067 },
+ { 1466980508178206, 617045217998949, 652303580573628, 757303753529064, 207583137376902 }
+ },
+ {
+ { 1511056752906902, 105403126891277, 493434892772846, 1091943425335976, 1802717338077427 },
+ { 1853982405405128, 1878664056251147, 1528011020803992, 1019626468153565, 1128438412189035 },
+ { 1963939888391106, 293456433791664, 697897559513649, 985882796904380, 796244541237972 }
+ },
+ {
+ { 416770998629779, 389655552427054, 1314476859406756, 1749382513022778, 1161905598739491 },
+ { 1428358296490651, 1027115282420478, 304840698058337, 441410174026628, 1819358356278573 },
+ { 204943430200135, 1554861433819175, 216426658514651, 264149070665950, 2047097371738319 }
+ },
+ {
+ { 1934415182909034, 1393285083565062, 516409331772960, 1157690734993892, 121039666594268 },
+ { 662035583584445, 286736105093098, 1131773000510616, 818494214211439, 472943792054479 },
+ { 665784778135882, 1893179629898606, 808313193813106, 276797254706413, 1563426179676396 }
+ },
+ {
+ { 945205108984232, 526277562959295, 1324180513733566, 1666970227868664, 153547609289173 },
+ { 2031433403516252, 203996615228162, 170487168837083, 981513604791390, 843573964916831 },
+ { 1476570093962618, 838514669399805, 1857930577281364, 2017007352225784, 317085545220047 }
+ },
+ {
+ { 1461557121912842, 1600674043318359, 2157134900399597, 1670641601940616, 127765583803283 },
+ { 1293543509393474, 2143624609202546, 1058361566797508, 214097127393994, 946888515472729 },
+ { 357067959932916, 1290876214345711, 521245575443703, 1494975468601005, 800942377643885 }
+ },
+ {
+ { 566116659100033, 820247422481740, 994464017954148, 327157611686365, 92591318111744 },
+ { 617256647603209, 1652107761099439, 1857213046645471, 1085597175214970, 817432759830522 },
+ { 771808161440705, 1323510426395069, 680497615846440, 851580615547985, 1320806384849017 }
+ }
+},
+{ /* 9/31 */
+ {
+ { 1219260086131915, 647169006596815, 79601124759706, 2161724213426748, 404861897060198 },
+ { 1327968293887866, 1335500852943256, 1401587164534264, 558137311952440, 1551360549268902 },
+ { 417621685193956, 1429953819744454, 396157358457099, 1940470778873255, 214000046234152 }
+ },
+ {
+ { 1268047918491973, 2172375426948536, 1533916099229249, 1761293575457130, 1590622667026765 },
+ { 1627072914981959, 2211603081280073, 1912369601616504, 1191770436221309, 2187309757525860 },
+ { 1149147819689533, 378692712667677, 828475842424202, 2218619146419342, 70688125792186 }
+ },
+ {
+ { 1299739417079761, 1438616663452759, 1536729078504412, 2053896748919838, 1008421032591246 },
+ { 2040723824657366, 399555637875075, 632543375452995, 872649937008051, 1235394727030233 },
+ { 2211311599327900, 2139787259888175, 938706616835350, 12609661139114, 2081897930719789 }
+ },
+ {
+ { 1324994503390450, 336982330582631, 1183998925654177, 1091654665913274, 48727673971319 },
+ { 1845522914617879, 1222198248335542, 150841072760134, 1927029069940982, 1189913404498011 },
+ { 1079559557592645, 2215338383666441, 1903569501302605, 49033973033940, 305703433934152 }
+ },
+ {
+ { 94653405416909, 1386121349852999, 1062130477891762, 36553947479274, 833669648948846 },
+ { 1432015813136298, 440364795295369, 1395647062821501, 1976874522764578, 934452372723352 },
+ { 1296625309219774, 2068273464883862, 1858621048097805, 1492281814208508, 2235868981918946 }
+ },
+ {
+ { 1490330266465570, 1858795661361448, 1436241134969763, 294573218899647, 1208140011028933 },
+ { 1282462923712748, 741885683986255, 2027754642827561, 518989529541027, 1826610009555945 },
+ { 1525827120027511, 723686461809551, 1597702369236987, 244802101764964, 1502833890372311 }
+ },
+ {
+ { 113622036244513, 1233740067745854, 674109952278496, 2114345180342965, 166764512856263 },
+ { 2041668749310338, 2184405322203901, 1633400637611036, 2110682505536899, 2048144390084644 },
+ { 503058759232932, 760293024620937, 2027152777219493, 666858468148475, 1539184379870952 }
+ },
+ {
+ { 1916168475367211, 915626432541343, 883217071712575, 363427871374304, 1976029821251593 },
+ { 678039535434506, 570587290189340, 1605302676614120, 2147762562875701, 1706063797091704 },
+ { 1439489648586438, 2194580753290951, 832380563557396, 561521973970522, 584497280718389 }
+ }
+},
+{ /* 10/31 */
+ {
+ { 187989455492609, 681223515948275, 1933493571072456, 1872921007304880, 488162364135671 },
+ { 1413466089534451, 410844090765630, 1397263346404072, 408227143123410, 1594561803147811 },
+ { 2102170800973153, 719462588665004, 1479649438510153, 1097529543970028, 1302363283777685 }
+ },
+ {
+ { 942065717847195, 1069313679352961, 2007341951411051, 70973416446291, 1419433790163706 },
+ { 1146565545556377, 1661971299445212, 406681704748893, 564452436406089, 1109109865829139 },
+ { 2214421081775077, 1165671861210569, 1890453018796184, 3556249878661, 442116172656317 }
+ },
+ {
+ { 753830546620811, 1666955059895019, 1530775289309243, 1119987029104146, 2164156153857580 },
+ { 615171919212796, 1523849404854568, 854560460547503, 2067097370290715, 1765325848586042 },
+ { 1094538949313667, 1796592198908825, 870221004284388, 2025558921863561, 1699010892802384 }
+ },
+ {
+ { 1951351290725195, 1916457206844795, 198025184438026, 1909076887557595, 1938542290318919 },
+ { 1014323197538413, 869150639940606, 1756009942696599, 1334952557375672, 1544945379082874 },
+ { 764055910920305, 1603590757375439, 146805246592357, 1843313433854297, 954279890114939 }
+ },
+ {
+ { 80113526615750, 764536758732259, 1055139345100233, 469252651759390, 617897512431515 },
+ { 74497112547268, 740094153192149, 1745254631717581, 727713886503130, 1283034364416928 },
+ { 525892105991110, 1723776830270342, 1476444848991936, 573789489857760, 133864092632978 }
+ },
+ {
+ { 542611720192581, 1986812262899321, 1162535242465837, 481498966143464, 544600533583622 },
+ { 64123227344372, 1239927720647794, 1360722983445904, 222610813654661, 62429487187991 },
+ { 1793193323953132, 91096687857833, 70945970938921, 2158587638946380, 1537042406482111 }
+ },
+ {
+ { 1895854577604609, 1394895708949416, 1728548428495944, 1140864900240149, 563645333603061 },
+ { 141358280486863, 91435889572504, 1087208572552643, 1829599652522921, 1193307020643647 },
+ { 1611230858525381, 950720175540785, 499589887488610, 2001656988495019, 88977313255908 }
+ },
+ {
+ { 1189080501479658, 2184348804772597, 1040818725742319, 2018318290311834, 1712060030915354 },
+ { 873966876953756, 1090638350350440, 1708559325189137, 672344594801910, 1320437969700239 },
+ { 1508590048271766, 1131769479776094, 101550868699323, 428297785557897, 561791648661744 }
+ }
+},
+{ /* 11/31 */
+ {
+ { 756417570499462, 237882279232602, 2136263418594016, 1701968045454886, 703713185137472 },
+ { 1781187809325462, 1697624151492346, 1381393690939988, 175194132284669, 1483054666415238 },
+ { 2175517777364616, 708781536456029, 955668231122942, 1967557500069555, 2021208005604118 }
+ },
+ {
+ { 1115135966606887, 224217372950782, 915967306279222, 593866251291540, 561747094208006 },
+ { 1443163092879439, 391875531646162, 2180847134654632, 464538543018753, 1594098196837178 },
+ { 850858855888869, 319436476624586, 327807784938441, 740785849558761, 17128415486016 }
+ },
+ {
+ { 2132756334090067, 536247820155645, 48907151276867, 608473197600695, 1261689545022784 },
+ { 1525176236978354, 974205476721062, 293436255662638, 148269621098039, 137961998433963 },
+ { 1121075518299410, 2071745529082111, 1265567917414828, 1648196578317805, 496232102750820 }
+ },
+ {
+ { 122321229299801, 1022922077493685, 2001275453369484, 2017441881607947, 993205880778002 },
+ { 654925550560074, 1168810995576858, 575655959430926, 905758704861388, 496774564663534 },
+ { 1954109525779738, 2117022646152485, 338102630417180, 1194140505732026, 107881734943492 }
+ },
+ {
+ { 1714785840001267, 2036500018681589, 1876380234251966, 2056717182974196, 1645855254384642 },
+ { 106431476499341, 62482972120563, 1513446655109411, 807258751769522, 538491469114 },
+ { 2002850762893643, 1243624520538135, 1486040410574605, 2184752338181213, 378495998083531 }
+ },
+ {
+ { 922510868424903, 1089502620807680, 402544072617374, 1131446598479839, 1290278588136533 },
+ { 1867998812076769, 715425053580701, 39968586461416, 2173068014586163, 653822651801304 },
+ { 162892278589453, 182585796682149, 75093073137630, 497037941226502, 133871727117371 }
+ },
+ {
+ { 1914596576579670, 1608999621851578, 1987629837704609, 1519655314857977, 1819193753409464 },
+ { 1949315551096831, 1069003344994464, 1939165033499916, 1548227205730856, 1933767655861407 },
+ { 1730519386931635, 1393284965610134, 1597143735726030, 416032382447158, 1429665248828629 }
+ },
+ {
+ { 360275475604565, 547835731063078, 215360904187529, 596646739879007, 332709650425085 },
+ { 47602113726801, 1522314509708010, 437706261372925, 814035330438027, 335930650933545 },
+ { 1291597595523886, 1058020588994081, 402837842324045, 1363323695882781, 2105763393033193 }
+ }
+},
+{ /* 12/31 */
+ {
+ { 109521982566564, 1715257748585139, 1112231216891516, 2046641005101484, 134249157157013 },
+ { 2156991030936798, 2227544497153325, 1869050094431622, 754875860479115, 1754242344267058 },
+ { 1846089562873800, 98894784984326, 1412430299204844, 171351226625762, 1100604760929008 }
+ },
+ {
+ { 84172382130492, 499710970700046, 425749630620778, 1762872794206857, 612842602127960 },
+ { 868309334532756, 1703010512741873, 1952690008738057, 4325269926064, 2071083554962116 },
+ { 523094549451158, 401938899487815, 1407690589076010, 2022387426254453, 158660516411257 }
+ },
+ {
+ { 612867287630009, 448212612103814, 571629077419196, 1466796750919376, 1728478129663858 },
+ { 1723848973783452, 2208822520534681, 1718748322776940, 1974268454121942, 1194212502258141 },
+ { 1254114807944608, 977770684047110, 2010756238954993, 1783628927194099, 1525962994408256 }
+ },
+ {
+ { 232464058235826, 1948628555342434, 1835348780427694, 1031609499437291, 64472106918373 },
+ { 767338676040683, 754089548318405, 1523192045639075, 435746025122062, 512692508440385 },
+ { 1255955808701983, 1700487367990941, 1166401238800299, 1175121994891534, 1190934801395380 }
+ },
+ {
+ { 349144008168292, 1337012557669162, 1475912332999108, 1321618454900458, 47611291904320 },
+ { 877519947135419, 2172838026132651, 272304391224129, 1655143327559984, 886229406429814 },
+ { 375806028254706, 214463229793940, 572906353144089, 572168269875638, 697556386112979 }
+ },
+ {
+ { 1168827102357844, 823864273033637, 2071538752104697, 788062026895924, 599578340743362 },
+ { 1948116082078088, 2054898304487796, 2204939184983900, 210526805152138, 786593586607626 },
+ { 1915320147894736, 156481169009469, 655050471180417, 592917090415421, 2165897438660879 }
+ },
+ {
+ { 1726336468579724, 1119932070398949, 1929199510967666, 33918788322959, 1836837863503150 },
+ { 829996854845988, 217061778005138, 1686565909803640, 1346948817219846, 1723823550730181 },
+ { 384301494966394, 687038900403062, 2211195391021739, 254684538421383, 1245698430589680 }
+ },
+ {
+ { 1247567493562688, 1978182094455847, 183871474792955, 806570235643435, 288461518067916 },
+ { 1449077384734201, 38285445457996, 2136537659177832, 2146493000841573, 725161151123125 },
+ { 1201928866368855, 800415690605445, 1703146756828343, 997278587541744, 1858284414104014 }
+ }
+},
+{ /* 13/31 */
+ {
+ { 356468809648877, 782373916933152, 1718002439402870, 1392222252219254, 663171266061951 },
+ { 759628738230460, 1012693474275852, 353780233086498, 246080061387552, 2030378857679162 },
+ { 2040672435071076, 888593182036908, 1298443657189359, 1804780278521327, 354070726137060 }
+ },
+ {
+ { 1894938527423184, 1463213041477277, 474410505497651, 247294963033299, 877975941029128 },
+ { 207937160991127, 12966911039119, 820997788283092, 1010440472205286, 1701372890140810 },
+ { 218882774543183, 533427444716285, 1233243976733245, 435054256891319, 1509568989549904 }
+ },
+ {
+ { 1888838535711826, 1052177758340622, 1213553803324135, 169182009127332, 463374268115872 },
+ { 299137589460312, 1594371588983567, 868058494039073, 257771590636681, 1805012993142921 },
+ { 1806842755664364, 2098896946025095, 1356630998422878, 1458279806348064, 347755825962072 }
+ },
+ {
+ { 1402334161391744, 1560083671046299, 1008585416617747, 1147797150908892, 1420416683642459 },
+ { 665506704253369, 273770475169863, 799236974202630, 848328990077558, 1811448782807931 },
+ { 1468412523962641, 771866649897997, 1931766110147832, 799561180078482, 524837559150077 }
+ },
+ {
+ { 2223212657821850, 630416247363666, 2144451165500328, 816911130947791, 1024351058410032 },
+ { 1266603897524861, 156378408858100, 1275649024228779, 447738405888420, 253186462063095 },
+ { 2022215964509735, 136144366993649, 1800716593296582, 1193970603800203, 871675847064218 }
+ },
+ {
+ { 1862751661970328, 851596246739884, 1519315554814041, 1542798466547449, 1417975335901520 },
+ { 1228168094547481, 334133883362894, 587567568420081, 433612590281181, 603390400373205 },
+ { 121893973206505, 1843345804916664, 1703118377384911, 497810164760654, 101150811654673 }
+ },
+ {
+ { 458346255946468, 290909935619344, 1452768413850679, 550922875254215, 1537286854336538 },
+ { 584322311184395, 380661238802118, 114839394528060, 655082270500073, 2111856026034852 },
+ { 996965581008991, 2148998626477022, 1012273164934654, 1073876063914522, 1688031788934939 }
+ },
+ {
+ { 923487018849600, 2085106799623355, 528082801620136, 1606206360876188, 735907091712524 },
+ { 1697697887804317, 1335343703828273, 831288615207040, 949416685250051, 288760277392022 },
+ { 1419122478109648, 1325574567803701, 602393874111094, 2107893372601700, 1314159682671307 }
+ }
+},
+{ /* 14/31 */
+ {
+ { 2201150872731804, 2180241023425241, 97663456423163, 1633405770247824, 848945042443986 },
+ { 1173339555550611, 818605084277583, 47521504364289, 924108720564965, 735423405754506 },
+ { 830104860549448, 1886653193241086, 1600929509383773, 1475051275443631, 286679780900937 }
+ },
+ {
+ { 1577111294832995, 1030899169768747, 144900916293530, 1964672592979567, 568390100955250 },
+ { 278388655910247, 487143369099838, 927762205508727, 181017540174210, 1616886700741287 },
+ { 1191033906638969, 940823957346562, 1606870843663445, 861684761499847, 658674867251089 }
+ },
+ {
+ { 1875032594195546, 1427106132796197, 724736390962158, 901860512044740, 635268497268760 },
+ { 622869792298357, 1903919278950367, 1922588621661629, 1520574711600434, 1087100760174640 },
+ { 25465949416618, 1693639527318811, 1526153382657203, 125943137857169, 145276964043999 }
+ },
+ {
+ { 214739857969358, 920212862967915, 1939901550972269, 1211862791775221, 85097515720120 },
+ { 2006245852772938, 734762734836159, 254642929763427, 1406213292755966, 239303749517686 },
+ { 1619678837192149, 1919424032779215, 1357391272956794, 1525634040073113, 1310226789796241 }
+ },
+ {
+ { 1040763709762123, 1704449869235352, 605263070456329, 1998838089036355, 1312142911487502 },
+ { 1996723311435669, 1844342766567060, 985455700466044, 1165924681400960, 311508689870129 },
+ { 43173156290518, 2202883069785309, 1137787467085917, 1733636061944606, 1394992037553852 }
+ },
+ {
+ { 670078326344559, 555655025059356, 471959386282438, 2141455487356409, 849015953823125 },
+ { 2197214573372804, 794254097241315, 1030190060513737, 267632515541902, 2040478049202624 },
+ { 1812516004670529, 1609256702920783, 1706897079364493, 258549904773295, 996051247540686 }
+ },
+ {
+ { 1540374301420584, 1764656898914615, 1810104162020396, 923808779163088, 664390074196579 },
+ { 1323460699404750, 1262690757880991, 871777133477900, 1060078894988977, 1712236889662886 },
+ { 1696163952057966, 1391710137550823, 608793846867416, 1034391509472039, 1780770894075012 }
+ },
+ {
+ { 1367603834210841, 2131988646583224, 890353773628144, 1908908219165595, 270836895252891 },
+ { 597536315471731, 40375058742586, 1942256403956049, 1185484645495932, 312666282024145 },
+ { 1919411405316294, 1234508526402192, 1066863051997083, 1008444703737597, 1348810787701552 }
+ }
+},
+{ /* 15/31 */
+ {
+ { 2102881477513865, 1570274565945361, 1573617900503708, 18662635732583, 2232324307922098 },
+ { 1853931367696942, 8107973870707, 350214504129299, 775206934582587, 1752317649166792 },
+ { 1417148368003523, 721357181628282, 505725498207811, 373232277872983, 261634707184480 }
+ },
+ {
+ { 2186733281493267, 2250694917008620, 1014829812957440, 479998161452389, 83566193876474 },
+ { 1268116367301224, 560157088142809, 802626839600444, 2210189936605713, 1129993785579988 },
+ { 615183387352312, 917611676109240, 878893615973325, 978940963313282, 938686890583575 }
+ },
+ {
+ { 522024729211672, 1045059315315808, 1892245413707790, 1907891107684253, 2059998109500714 },
+ { 1799679152208884, 912132775900387, 25967768040979, 432130448590461, 274568990261996 },
+ { 98698809797682, 2144627600856209, 1907959298569602, 811491302610148, 1262481774981493 }
+ },
+ {
+ { 1791451399743152, 1713538728337276, 118349997257490, 1882306388849954, 158235232210248 },
+ { 1217809823321928, 2173947284933160, 1986927836272325, 1388114931125539, 12686131160169 },
+ { 1650875518872272, 1136263858253897, 1732115601395988, 734312880662190, 1252904681142109 }
+ },
+ {
+ { 372986456113865, 525430915458171, 2116279931702135, 501422713587815, 1907002872974925 },
+ { 803147181835288, 868941437997146, 316299302989663, 943495589630550, 571224287904572 },
+ { 227742695588364, 1776969298667369, 628602552821802, 457210915378118, 2041906378111140 }
+ },
+ {
+ { 815000523470260, 913085688728307, 1052060118271173, 1345536665214223, 541623413135555 },
+ { 1580216071604333, 1877997504342444, 857147161260913, 703522726778478, 2182763974211603 },
+ { 1870080310923419, 71988220958492, 1783225432016732, 615915287105016, 1035570475990230 }
+ },
+ {
+ { 730987750830150, 857613889540280, 1083813157271766, 1002817255970169, 1719228484436074 },
+ { 377616581647602, 1581980403078513, 804044118130621, 2034382823044191, 643844048472185 },
+ { 176957326463017, 1573744060478586, 528642225008045, 1816109618372371, 1515140189765006 }
+ },
+ {
+ { 1888911448245718, 1387110895611080, 1924503794066429, 1731539523700949, 2230378382645454 },
+ { 443392177002051, 233793396845137, 2199506622312416, 1011858706515937, 974676837063129 },
+ { 1846351103143623, 1949984838808427, 671247021915253, 1946756846184401, 1929296930380217 }
+ }
+},
+{ /* 16/31 */
+ {
+ { 849646212452002, 1410198775302919, 73767886183695, 1641663456615812, 762256272452411 },
+ { 692017667358279, 723305578826727, 1638042139863265, 748219305990306, 334589200523901 },
+ { 22893968530686, 2235758574399251, 1661465835630252, 925707319443452, 1203475116966621 }
+ },
+ {
+ { 801299035785166, 1733292596726131, 1664508947088596, 467749120991922, 1647498584535623 },
+ { 903105258014366, 427141894933047, 561187017169777, 1884330244401954, 1914145708422219 },
+ { 1344191060517578, 1960935031767890, 1518838929955259, 1781502350597190, 1564784025565682 }
+ },
+ {
+ { 673723351748086, 1979969272514923, 1175287312495508, 1187589090978666, 1881897672213940 },
+ { 1917185587363432, 1098342571752737, 5935801044414, 2000527662351839, 1538640296181569 },
+ { 2495540013192, 678856913479236, 224998292422872, 219635787698590, 1972465269000940 }
+ },
+ {
+ { 271413961212179, 1353052061471651, 344711291283483, 2014925838520662, 2006221033113941 },
+ { 194583029968109, 514316781467765, 829677956235672, 1676415686873082, 810104584395840 },
+ { 1980510813313589, 1948645276483975, 152063780665900, 129968026417582, 256984195613935 }
+ },
+ {
+ { 1860190562533102, 1936576191345085, 461100292705964, 1811043097042830, 957486749306835 },
+ { 796664815624365, 1543160838872951, 1500897791837765, 1667315977988401, 599303877030711 },
+ { 1151480509533204, 2136010406720455, 738796060240027, 319298003765044, 1150614464349587 }
+ },
+ {
+ { 1731069268103150, 735642447616087, 1364750481334268, 417232839982871, 927108269127661 },
+ { 1017222050227968, 1987716148359, 2234319589635701, 621282683093392, 2132553131763026 },
+ { 1567828528453324, 1017807205202360, 565295260895298, 829541698429100, 307243822276582 }
+ },
+ {
+ { 249079270936248, 1501514259790706, 947909724204848, 944551802437487, 552658763982480 },
+ { 2089966982947227, 1854140343916181, 2151980759220007, 2139781292261749, 158070445864917 },
+ { 1338766321464554, 1906702607371284, 1519569445519894, 115384726262267, 1393058953390992 }
+ },
+ {
+ { 1364621558265400, 1512388234908357, 1926731583198686, 2041482526432505, 920401122333774 },
+ { 1884844597333588, 601480070269079, 620203503079537, 1079527400117915, 1202076693132015 },
+ { 840922919763324, 727955812569642, 1303406629750194, 522898432152867, 294161410441865 }
+ }
+},
+{ /* 17/31 */
+ {
+ { 353760790835310, 1598361541848743, 1122905698202299, 1922533590158905, 419107700666580 },
+ { 359856369838236, 180914355488683, 861726472646627, 218807937262986, 575626773232501 },
+ { 755467689082474, 909202735047934, 730078068932500, 936309075711518, 2007798262842972 }
+ },
+ {
+ { 1609384177904073, 362745185608627, 1335318541768201, 800965770436248, 547877979267412 },
+ { 984339177776787, 815727786505884, 1645154585713747, 1659074964378553, 1686601651984156 },
+ { 1697863093781930, 599794399429786, 1104556219769607, 830560774794755, 12812858601017 }
+ },
+ {
+ { 1168737550514982, 897832437380552, 463140296333799, 302564600022547, 2008360505135501 },
+ { 1856930662813910, 678090852002597, 1920179140755167, 1259527833759868, 55540971895511 },
+ { 1158643631044921, 476554103621892, 178447851439725, 1305025542653569, 103433927680625 }
+ },
+ {
+ { 2176793111709008, 1576725716350391, 2009350167273523, 2012390194631546, 2125297410909580 },
+ { 825403285195098, 2144208587560784, 1925552004644643, 1915177840006985, 1015952128947864 },
+ { 1807108316634472, 1534392066433717, 347342975407218, 1153820745616376, 7375003497471 }
+ },
+ {
+ { 983061001799725, 431211889901241, 2201903782961093, 817393911064341, 2214616493042167 },
+ { 228567918409756, 865093958780220, 358083886450556, 159617889659320, 1360637926292598 },
+ { 234147501399755, 2229469128637390, 2175289352258889, 1397401514549353, 1885288963089922 }
+ },
+ {
+ { 1111762412951562, 252849572507389, 1048714233823341, 146111095601446, 1237505378776770 },
+ { 1113790697840279, 1051167139966244, 1045930658550944, 2011366241542643, 1686166824620755 },
+ { 1054097349305049, 1872495070333352, 182121071220717, 1064378906787311, 100273572924182 }
+ },
+ {
+ { 1306410853171605, 1627717417672447, 50983221088417, 1109249951172250, 870201789081392 },
+ { 104233794644221, 1548919791188248, 2224541913267306, 2054909377116478, 1043803389015153 },
+ { 216762189468802, 707284285441622, 190678557969733, 973969342604308, 1403009538434867 }
+ },
+ {
+ { 1279024291038477, 344776835218310, 273722096017199, 1834200436811442, 634517197663804 },
+ { 343805853118335, 1302216857414201, 566872543223541, 2051138939539004, 321428858384280 },
+ { 470067171324852, 1618629234173951, 2000092177515639, 7307679772789, 1117521120249968 }
+ }
+},
+{ /* 18/31 */
+ {
+ { 278151578291475, 1810282338562947, 1771599529530998, 1383659409671631, 685373414471841 },
+ { 577009397403102, 1791440261786291, 2177643735971638, 174546149911960, 1412505077782326 },
+ { 893719721537457, 1201282458018197, 1522349501711173, 58011597740583, 1130406465887139 }
+ },
+ {
+ { 412607348255453, 1280455764199780, 2233277987330768, 14180080401665, 331584698417165 },
+ { 262483770854550, 990511055108216, 526885552771698, 571664396646158, 354086190278723 },
+ { 1820352417585487, 24495617171480, 1547899057533253, 10041836186225, 480457105094042 }
+ },
+ {
+ { 2023310314989233, 637905337525881, 2106474638900687, 557820711084072, 1687858215057826 },
+ { 1144168702609745, 604444390410187, 1544541121756138, 1925315550126027, 626401428894002 },
+ { 1922168257351784, 2018674099908659, 1776454117494445, 956539191509034, 36031129147635 }
+ },
+ {
+ { 544644538748041, 1039872944430374, 876750409130610, 710657711326551, 1216952687484972 },
+ { 58242421545916, 2035812695641843, 2118491866122923, 1191684463816273, 46921517454099 },
+ { 272268252444639, 1374166457774292, 2230115177009552, 1053149803909880, 1354288411641016 }
+ },
+ {
+ { 1857910905368338, 1754729879288912, 885945464109877, 1516096106802166, 1602902393369811 },
+ { 1193437069800958, 901107149704790, 999672920611411, 477584824802207, 364239578697845 },
+ { 886299989548838, 1538292895758047, 1590564179491896, 1944527126709657, 837344427345298 }
+ },
+ {
+ { 754558365378305, 1712186480903618, 1703656826337531, 750310918489786, 518996040250900 },
+ { 1309847803895382, 1462151862813074, 211370866671570, 1544595152703681, 1027691798954090 },
+ { 803217563745370, 1884799722343599, 1357706345069218, 2244955901722095, 730869460037413 }
+ },
+ {
+ { 689299471295966, 1831210565161071, 1375187341585438, 1106284977546171, 1893781834054269 },
+ { 696351368613042, 1494385251239250, 738037133616932, 636385507851544, 927483222611406 },
+ { 1949114198209333, 1104419699537997, 783495707664463, 1747473107602770, 2002634765788641 }
+ },
+ {
+ { 1607325776830197, 530883941415333, 1451089452727895, 1581691157083423, 496100432831154 },
+ { 1068900648804224, 2006891997072550, 1134049269345549, 1638760646180091, 2055396084625778 },
+ { 2222475519314561, 1870703901472013, 1884051508440561, 1344072275216753, 1318025677799069 }
+ }
+},
+{ /* 19/31 */
+ {
+ { 155711679280656, 681100400509288, 389811735211209, 2135723811340709, 408733211204125 },
+ { 7813206966729, 194444201427550, 2071405409526507, 1065605076176312, 1645486789731291 },
+ { 16625790644959, 1647648827778410, 1579910185572704, 436452271048548, 121070048451050 }
+ },
+ {
+ { 1037263028552531, 568385780377829, 297953104144430, 1558584511931211, 2238221839292471 },
+ { 190565267697443, 672855706028058, 338796554369226, 337687268493904, 853246848691734 },
+ { 1763863028400139, 766498079432444, 1321118624818005, 69494294452268, 858786744165651 }
+ },
+ {
+ { 1292056768563024, 1456632109855638, 1100631247050184, 1386133165675321, 1232898350193752 },
+ { 366253102478259, 525676242508811, 1449610995265438, 1183300845322183, 185960306491545 },
+ { 28315355815982, 460422265558930, 1799675876678724, 1969256312504498, 1051823843138725 }
+ },
+ {
+ { 156914999361983, 1606148405719949, 1665208410108430, 317643278692271, 1383783705665320 },
+ { 54684536365732, 2210010038536222, 1194984798155308, 535239027773705, 1516355079301361 },
+ { 1484387703771650, 198537510937949, 2186282186359116, 617687444857508, 647477376402122 }
+ },
+ {
+ { 2147715541830533, 500032538445817, 646380016884826, 352227855331122, 1488268620408052 },
+ { 159386186465542, 1877626593362941, 618737197060512, 1026674284330807, 1158121760792685 },
+ { 1744544377739822, 1964054180355661, 1685781755873170, 2169740670377448, 1286112621104591 }
+ },
+ {
+ { 81977249784993, 1667943117713086, 1668983819634866, 1605016835177615, 1353960708075544 },
+ { 1602253788689063, 439542044889886, 2220348297664483, 657877410752869, 157451572512238 },
+ { 1029287186166717, 65860128430192, 525298368814832, 1491902500801986, 1461064796385400 }
+ },
+ {
+ { 408216988729246, 2121095722306989, 913562102267595, 1879708920318308, 241061448436731 },
+ { 1185483484383269, 1356339572588553, 584932367316448, 102132779946470, 1792922621116791 },
+ { 1966196870701923, 2230044620318636, 1425982460745905, 261167817826569, 46517743394330 }
+ },
+ {
+ { 107077591595359, 884959942172345, 27306869797400, 2224911448949390, 964352058245223 },
+ { 1730194207717538, 431790042319772, 1831515233279467, 1372080552768581, 1074513929381760 },
+ { 1450880638731607, 1019861580989005, 1229729455116861, 1174945729836143, 826083146840706 }
+ }
+},
+{ /* 20/31 */
+ {
+ { 1899935429242705, 1602068751520477, 940583196550370, 82431069053859, 1540863155745696 },
+ { 2136688454840028, 2099509000964294, 1690800495246475, 1217643678575476, 828720645084218 },
+ { 765548025667841, 462473984016099, 998061409979798, 546353034089527, 2212508972466858 }
+ },
+ {
+ { 46575283771160, 892570971573071, 1281983193144090, 1491520128287375, 75847005908304 },
+ { 1801436127943107, 1734436817907890, 1268728090345068, 167003097070711, 2233597765834956 },
+ { 1997562060465113, 1048700225534011, 7615603985628, 1855310849546841, 2242557647635213 }
+ },
+ {
+ { 1161017320376250, 492624580169043, 2169815802355237, 976496781732542, 1770879511019629 },
+ { 1357044908364776, 729130645262438, 1762469072918979, 1365633616878458, 181282906404941 },
+ { 1080413443139865, 1155205815510486, 1848782073549786, 622566975152580, 124965574467971 }
+ },
+ {
+ { 1184526762066993, 247622751762817, 692129017206356, 820018689412496, 2188697339828085 },
+ { 2020536369003019, 202261491735136, 1053169669150884, 2056531979272544, 778165514694311 },
+ { 237404399610207, 1308324858405118, 1229680749538400, 720131409105291, 1958958863624906 }
+ },
+ {
+ { 515583508038846, 17656978857189, 1717918437373989, 1568052070792483, 46975803123923 },
+ { 281527309158085, 36970532401524, 866906920877543, 2222282602952734, 1289598729589882 },
+ { 1278207464902042, 494742455008756, 1262082121427081, 1577236621659884, 1888786707293291 }
+ },
+ {
+ { 353042527954210, 1830056151907359, 1111731275799225, 174960955838824, 404312815582675 },
+ { 2064251142068628, 1666421603389706, 1419271365315441, 468767774902855, 191535130366583 },
+ { 1716987058588002, 1859366439773457, 1767194234188234, 64476199777924, 1117233614485261 }
+ },
+ {
+ { 984292135520292, 135138246951259, 2220652137473167, 1722843421165029, 190482558012909 },
+ { 298845952651262, 1166086588952562, 1179896526238434, 1347812759398693, 1412945390096208 },
+ { 1143239552672925, 906436640714209, 2177000572812152, 2075299936108548, 325186347798433 }
+ },
+ {
+ { 721024854374772, 684487861263316, 1373438744094159, 2193186935276995, 1387043709851261 },
+ { 418098668140962, 715065997721283, 1471916138376055, 2168570337288357, 937812682637044 },
+ { 1043584187226485, 2143395746619356, 2209558562919611, 482427979307092, 847556718384018 }
+ }
+},
+{ /* 21/31 */
+ {
+ { 1248731221520759, 1465200936117687, 540803492710140, 52978634680892, 261434490176109 },
+ { 1057329623869501, 620334067429122, 461700859268034, 2012481616501857, 297268569108938 },
+ { 1055352180870759, 1553151421852298, 1510903185371259, 1470458349428097, 1226259419062731 }
+ },
+ {
+ { 1492988790301668, 790326625573331, 1190107028409745, 1389394752159193, 1620408196604194 },
+ { 47000654413729, 1004754424173864, 1868044813557703, 173236934059409, 588771199737015 },
+ { 30498470091663, 1082245510489825, 576771653181956, 806509986132686, 1317634017056939 }
+ },
+ {
+ { 420308055751555, 1493354863316002, 165206721528088, 1884845694919786, 2065456951573059 },
+ { 1115636332012334, 1854340990964155, 83792697369514, 1972177451994021, 457455116057587 },
+ { 1698968457310898, 1435137169051090, 1083661677032510, 938363267483709, 340103887207182 }
+ },
+ {
+ { 1995325341336574, 911500251774648, 164010755403692, 855378419194762, 1573601397528842 },
+ { 241719380661528, 310028521317150, 1215881323380194, 1408214976493624, 2141142156467363 },
+ { 1315157046163473, 727368447885818, 1363466668108618, 1668921439990361, 1398483384337907 }
+ },
+ {
+ { 75029678299646, 1015388206460473, 1849729037055212, 1939814616452984, 444404230394954 },
+ { 2053597130993710, 2024431685856332, 2233550957004860, 2012407275509545, 872546993104440 },
+ { 1217269667678610, 599909351968693, 1390077048548598, 1471879360694802, 739586172317596 }
+ },
+ {
+ { 1718318639380794, 1560510726633958, 904462881159922, 1418028351780052, 94404349451937 },
+ { 2132502667405250, 214379346175414, 1502748313768060, 1960071701057800, 1353971822643138 },
+ { 319394212043702, 2127459436033571, 717646691535162, 663366796076914, 318459064945314 }
+ },
+ {
+ { 405989424923593, 1960452633787083, 667349034401665, 1492674260767112, 1451061489880787 },
+ { 947085906234007, 323284730494107, 1485778563977200, 728576821512394, 901584347702286 },
+ { 1575783124125742, 2126210792434375, 1569430791264065, 1402582372904727, 1891780248341114 }
+ },
+ {
+ { 838432205560695, 1997703511451664, 1018791879907867, 1662001808174331, 78328132957753 },
+ { 739152638255629, 2074935399403557, 505483666745895, 1611883356514088, 628654635394878 },
+ { 1822054032121349, 643057948186973, 7306757352712, 577249257962099, 284735863382083 }
+ }
+},
+{ /* 22/31 */
+ {
+ { 1366558556363930, 1448606567552086, 1478881020944768, 165803179355898, 1115718458123498 },
+ { 204146226972102, 1630511199034723, 2215235214174763, 174665910283542, 956127674017216 },
+ { 1562934578796716, 1070893489712745, 11324610642270, 958989751581897, 2172552325473805 }
+ },
+ {
+ { 1770564423056027, 735523631664565, 1326060113795289, 1509650369341127, 65892421582684 },
+ { 623682558650637, 1337866509471512, 990313350206649, 1314236615762469, 1164772974270275 },
+ { 223256821462517, 723690150104139, 1000261663630601, 933280913953265, 254872671543046 }
+ },
+ {
+ { 1969087237026041, 624795725447124, 1335555107635969, 2069986355593023, 1712100149341902 },
+ { 1236103475266979, 1837885883267218, 1026072585230455, 1025865513954973, 1801964901432134 },
+ { 1115241013365517, 1712251818829143, 2148864332502771, 2096001471438138, 2235017246626125 }
+ },
+ {
+ { 1299268198601632, 2047148477845621, 2165648650132450, 1612539282026145, 514197911628890 },
+ { 118352772338543, 1067608711804704, 1434796676193498, 1683240170548391, 230866769907437 },
+ { 1850689576796636, 1601590730430274, 1139674615958142, 1954384401440257, 76039205311 }
+ },
+ {
+ { 1723387471374172, 997301467038410, 533927635123657, 20928644693965, 1756575222802513 },
+ { 2146711623855116, 503278928021499, 625853062251406, 1109121378393107, 1033853809911861 },
+ { 571005965509422, 2005213373292546, 1016697270349626, 56607856974274, 914438579435146 }
+ },
+ {
+ { 1346698876211176, 2076651707527589, 1084761571110205, 265334478828406, 1068954492309671 },
+ { 1769967932677654, 1695893319756416, 1151863389675920, 1781042784397689, 400287774418285 },
+ { 1851867764003121, 403841933237558, 820549523771987, 761292590207581, 1743735048551143 }
+ },
+ {
+ { 410915148140008, 2107072311871739, 1004367461876503, 99684895396761, 1180818713503224 },
+ { 285945406881439, 648174397347453, 1098403762631981, 1366547441102991, 1505876883139217 },
+ { 672095903120153, 1675918957959872, 636236529315028, 1569297300327696, 2164144194785875 }
+ },
+ {
+ { 1902708175321798, 1035343530915438, 1178560808893263, 301095684058146, 1280977479761118 },
+ { 1615357281742403, 404257611616381, 2160201349780978, 1160947379188955, 1578038619549541 },
+ { 2013087639791217, 822734930507457, 1785668418619014, 1668650702946164, 389450875221715 }
+ }
+},
+{ /* 23/31 */
+ {
+ { 453918449698368, 106406819929001, 2072540975937135, 308588860670238, 1304394580755385 },
+ { 1295082798350326, 2091844511495996, 1851348972587817, 3375039684596, 789440738712837 },
+ { 2083069137186154, 848523102004566, 993982213589257, 1405313299916317, 1532824818698468 }
+ },
+ {
+ { 1495961298852430, 1397203457344779, 1774950217066942, 139302743555696, 66603584342787 },
+ { 1782411379088302, 1096724939964781, 27593390721418, 542241850291353, 1540337798439873 },
+ { 693543956581437, 171507720360750, 1557908942697227, 1074697073443438, 1104093109037196 }
+ },
+ {
+ { 345288228393419, 1099643569747172, 134881908403743, 1740551994106740, 248212179299770 },
+ { 231429562203065, 1526290236421172, 2021375064026423, 1520954495658041, 806337791525116 },
+ { 1079623667189886, 872403650198613, 766894200588288, 2163700860774109, 2023464507911816 }
+ },
+ {
+ { 854645372543796, 1936406001954827, 151460662541253, 825325739271555, 1554306377287556 },
+ { 1497138821904622, 1044820250515590, 1742593886423484, 1237204112746837, 849047450816987 },
+ { 667962773375330, 1897271816877105, 1399712621683474, 1143302161683099, 2081798441209593 }
+ },
+ {
+ { 127147851567005, 1936114012888110, 1704424366552046, 856674880716312, 716603621335359 },
+ { 1072409664800960, 2146937497077528, 1508780108920651, 935767602384853, 1112800433544068 },
+ { 333549023751292, 280219272863308, 2104176666454852, 1036466864875785, 536135186520207 }
+ },
+ {
+ { 373666279883137, 146457241530109, 304116267127857, 416088749147715, 1258577131183391 },
+ { 1186115062588401, 2251609796968486, 1098944457878953, 1153112761201374, 1791625503417267 },
+ { 1870078460219737, 2129630962183380, 852283639691142, 292865602592851, 401904317342226 }
+ },
+ {
+ { 1361070124828035, 815664541425524, 1026798897364671, 1951790935390647, 555874891834790 },
+ { 1546301003424277, 459094500062839, 1097668518375311, 1780297770129643, 720763293687608 },
+ { 1212405311403990, 1536693382542438, 61028431067459, 1863929423417129, 1223219538638038 }
+ },
+ {
+ { 1294303766540260, 1183557465955093, 882271357233093, 63854569425375, 2213283684565087 },
+ { 339050984211414, 601386726509773, 413735232134068, 966191255137228, 1839475899458159 },
+ { 235605972169408, 2174055643032978, 1538335001838863, 1281866796917192, 1815940222628465 }
+ }
+},
+{ /* 24/31 */
+ {
+ { 1632352921721536, 1833328609514701, 2092779091951987, 1923956201873226, 2210068022482919 },
+ { 35271216625062, 1712350667021807, 983664255668860, 98571260373038, 1232645608559836 },
+ { 1998172393429622, 1798947921427073, 784387737563581, 1589352214827263, 1589861734168180 }
+ },
+ {
+ { 1733739258725305, 31715717059538, 201969945218860, 992093044556990, 1194308773174556 },
+ { 846415389605137, 746163495539180, 829658752826080, 592067705956946, 957242537821393 },
+ { 1758148849754419, 619249044817679, 168089007997045, 1371497636330523, 1867101418880350 }
+ },
+ {
+ { 326633984209635, 261759506071016, 1700682323676193, 1577907266349064, 1217647663383016 },
+ { 1714182387328607, 1477856482074168, 574895689942184, 2159118410227270, 1555532449716575 },
+ { 853828206885131, 998498946036955, 1835887550391235, 207627336608048, 258363815956050 }
+ },
+ {
+ { 141141474651677, 1236728744905256, 643101419899887, 1646615130509173, 1208239602291765 },
+ { 1501663228068911, 1354879465566912, 1444432675498247, 897812463852601, 855062598754348 },
+ { 714380763546606, 1032824444965790, 1774073483745338, 1063840874947367, 1738680636537158 }
+ },
+ {
+ { 1640635546696252, 633168953192112, 2212651044092396, 30590958583852, 368515260889378 },
+ { 1171650314802029, 1567085444565577, 1453660792008405, 757914533009261, 1619511342778196 },
+ { 420958967093237, 971103481109486, 2169549185607107, 1301191633558497, 1661514101014240 }
+ },
+ {
+ { 907123651818302, 1332556122804146, 1824055253424487, 1367614217442959, 1982558335973172 },
+ { 1121533090144639, 1021251337022187, 110469995947421, 1511059774758394, 2110035908131662 },
+ { 303213233384524, 2061932261128138, 352862124777736, 40828818670255, 249879468482660 }
+ },
+ {
+ { 856559257852200, 508517664949010, 1378193767894916, 1723459126947129, 1962275756614521 },
+ { 1445691340537320, 40614383122127, 402104303144865, 485134269878232, 1659439323587426 },
+ { 20057458979482, 1183363722525800, 2140003847237215, 2053873950687614, 2112017736174909 }
+ },
+ {
+ { 2228654250927986, 1483591363415267, 1368661293910956, 1076511285177291, 526650682059608 },
+ { 709481497028540, 531682216165724, 316963769431931, 1814315888453765, 258560242424104 },
+ { 1053447823660455, 1955135194248683, 1010900954918985, 1182614026976701, 1240051576966610 }
+ }
+},
+{ /* 25/31 */
+ {
+ { 1957943897155497, 1788667368028035, 137692910029106, 1039519607062, 826404763313028 },
+ { 1848942433095597, 1582009882530495, 1849292741020143, 1068498323302788, 2001402229799484 },
+ { 1528282417624269, 2142492439828191, 2179662545816034, 362568973150328, 1591374675250271 }
+ },
+ {
+ { 160026679434388, 232341189218716, 2149181472355545, 598041771119831, 183859001910173 },
+ { 2013278155187349, 662660471354454, 793981225706267, 411706605985744, 804490933124791 },
+ { 2051892037280204, 488391251096321, 2230187337030708, 930221970662692, 679002758255210 }
+ },
+ {
+ { 1530723630438670, 875873929577927, 341560134269988, 449903119530753, 1055551308214179 },
+ { 1461835919309432, 1955256480136428, 180866187813063, 1551979252664528, 557743861963950 },
+ { 359179641731115, 1324915145732949, 902828372691474, 294254275669987, 1887036027752957 }
+ },
+ {
+ { 2043271609454323, 2038225437857464, 1317528426475850, 1398989128982787, 2027639881006861 },
+ { 2072902725256516, 312132452743412, 309930885642209, 996244312618453, 1590501300352303 },
+ { 1397254305160710, 695734355138021, 2233992044438756, 1776180593969996, 1085588199351115 }
+ },
+ {
+ { 440567051331029, 254894786356681, 493869224930222, 1556322069683366, 1567456540319218 },
+ { 1950722461391320, 1907845598854797, 1822757481635527, 2121567704750244, 73811931471221 },
+ { 387139307395758, 2058036430315676, 1220915649965325, 1794832055328951, 1230009312169328 }
+ },
+ {
+ { 1765973779329517, 659344059446977, 19821901606666, 1301928341311214, 1116266004075885 },
+ { 1127572801181483, 1224743760571696, 1276219889847274, 1529738721702581, 1589819666871853 },
+ { 2181229378964934, 2190885205260020, 1511536077659137, 1246504208580490, 668883326494241 }
+ },
+ {
+ { 437866655573314, 669026411194768, 81896997980338, 523874406393178, 245052060935236 },
+ { 1975438052228868, 1071801519999806, 594652299224319, 1877697652668809, 1489635366987285 },
+ { 958592545673770, 233048016518599, 851568750216589, 567703851596087, 1740300006094761 }
+ },
+ {
+ { 2014540178270324, 192672779514432, 213877182641530, 2194819933853411, 1716422829364835 },
+ { 1540769606609725, 2148289943846077, 1597804156127445, 1230603716683868, 815423458809453 },
+ { 1738560251245018, 1779576754536888, 1783765347671392, 1880170990446751, 1088225159617541 }
+ }
+},
+{ /* 26/31 */
+ {
+ { 659303913929492, 1956447718227573, 1830568515922666, 841069049744408, 1669607124206368 },
+ { 1143465490433355, 1532194726196059, 1093276745494697, 481041706116088, 2121405433561163 },
+ { 1686424298744462, 1451806974487153, 266296068846582, 1834686947542675, 1720762336132256 }
+ },
+ {
+ { 889217026388959, 1043290623284660, 856125087551909, 1669272323124636, 1603340330827879 },
+ { 1206396181488998, 333158148435054, 1402633492821422, 1120091191722026, 1945474114550509 },
+ { 766720088232571, 1512222781191002, 1189719893490790, 2091302129467914, 2141418006894941 }
+ },
+ {
+ { 419663647306612, 1998875112167987, 1426599870253707, 1154928355379510, 486538532138187 },
+ { 938160078005954, 1421776319053174, 1941643234741774, 180002183320818, 1414380336750546 },
+ { 398001940109652, 1577721237663248, 1012748649830402, 1540516006905144, 1011684812884559 }
+ },
+ {
+ { 1653276489969630, 6081825167624, 1921777941170836, 1604139841794531, 861211053640641 },
+ { 996661541407379, 1455877387952927, 744312806857277, 139213896196746, 1000282908547789 },
+ { 1450817495603008, 1476865707053229, 1030490562252053, 620966950353376, 1744760161539058 }
+ },
+ {
+ { 559728410002599, 37056661641185, 2038622963352006, 1637244893271723, 1026565352238948 },
+ { 962165956135846, 1116599660248791, 182090178006815, 1455605467021751, 196053588803284 },
+ { 796863823080135, 1897365583584155, 420466939481601, 2165972651724672, 932177357788289 }
+ },
+ {
+ { 877047233620632, 1375632631944375, 643773611882121, 660022738847877, 19353932331831 },
+ { 2216943882299338, 394841323190322, 2222656898319671, 558186553950529, 1077236877025190 },
+ { 801118384953213, 1914330175515892, 574541023311511, 1471123787903705, 1526158900256288 }
+ },
+ {
+ { 949617889087234, 2207116611267331, 912920039141287, 501158539198789, 62362560771472 },
+ { 1474518386765335, 1760793622169197, 1157399790472736, 1622864308058898, 165428294422792 },
+ { 1961673048027128, 102619413083113, 1051982726768458, 1603657989805485, 1941613251499678 }
+ },
+ {
+ { 1401939116319266, 335306339903072, 72046196085786, 862423201496006, 850518754531384 },
+ { 1234706593321979, 1083343891215917, 898273974314935, 1640859118399498, 157578398571149 },
+ { 1143483057726416, 1992614991758919, 674268662140796, 1773370048077526, 674318359920189 }
+ }
+},
+{ /* 27/31 */
+ {
+ { 1835401379538542, 173900035308392, 818247630716732, 1762100412152786, 1021506399448291 },
+ { 1506632088156630, 2127481795522179, 513812919490255, 140643715928370, 442476620300318 },
+ { 2056683376856736, 219094741662735, 2193541883188309, 1841182310235800, 556477468664293 }
+ },
+ {
+ { 1315019427910827, 1049075855992603, 2066573052986543, 266904467185534, 2040482348591520 },
+ { 94096246544434, 922482381166992, 24517828745563, 2139430508542503, 2097139044231004 },
+ { 537697207950515, 1399352016347350, 1563663552106345, 2148749520888918, 549922092988516 }
+ },
+ {
+ { 1747985413252434, 680511052635695, 1809559829982725, 594274250930054, 201673170745982 },
+ { 323583936109569, 1973572998577657, 1192219029966558, 79354804385273, 1374043025560347 },
+ { 213277331329947, 416202017849623, 1950535221091783, 1313441578103244, 2171386783823658 }
+ },
+ {
+ { 189088804229831, 993969372859110, 895870121536987, 1547301535298256, 1477373024911350 },
+ { 1620578418245010, 541035331188469, 2235785724453865, 2154865809088198, 1974627268751826 },
+ { 1346805451740245, 1350981335690626, 942744349501813, 2155094562545502, 1012483751693409 }
+ },
+ {
+ { 2107080134091762, 1132567062788208, 1824935377687210, 769194804343737, 1857941799971888 },
+ { 1074666112436467, 249279386739593, 1174337926625354, 1559013532006480, 1472287775519121 },
+ { 1872620123779532, 1892932666768992, 1921559078394978, 1270573311796160, 1438913646755037 }
+ },
+ {
+ { 837390187648199, 1012253300223599, 989780015893987, 1351393287739814, 328627746545550 },
+ { 1028328827183114, 1711043289969857, 1350832470374933, 1923164689604327, 1495656368846911 },
+ { 1900828492104143, 430212361082163, 687437570852799, 832514536673512, 1685641495940794 }
+ },
+ {
+ { 842632847936398, 605670026766216, 290836444839585, 163210774892356, 2213815011799645 },
+ { 1176336383453996, 1725477294339771, 12700622672454, 678015708818208, 162724078519879 },
+ { 1448049969043497, 1789411762943521, 385587766217753, 90201620913498, 832999441066823 }
+ },
+ {
+ { 516086333293313, 2240508292484616, 1351669528166508, 1223255565316488, 750235824427138 },
+ { 1263624896582495, 1102602401673328, 526302183714372, 2152015839128799, 1483839308490010 },
+ { 442991718646863, 1599275157036458, 1925389027579192, 899514691371390, 350263251085160 }
+ }
+},
+{ /* 28/31 */
+ {
+ { 1689713572022143, 593854559254373, 978095044791970, 1985127338729499, 1676069120347625 },
+ { 1557207018622683, 340631692799603, 1477725909476187, 614735951619419, 2033237123746766 },
+ { 968764929340557, 1225534776710944, 662967304013036, 1155521416178595, 791142883466590 }
+ },
+ {
+ { 1487081286167458, 993039441814934, 1792378982844640, 698652444999874, 2153908693179754 },
+ { 1123181311102823, 685575944875442, 507605465509927, 1412590462117473, 568017325228626 },
+ { 560258797465417, 2193971151466401, 1824086900849026, 579056363542056, 1690063960036441 }
+ },
+ {
+ { 1918407319222416, 353767553059963, 1930426334528099, 1564816146005724, 1861342381708096 },
+ { 2131325168777276, 1176636658428908, 1756922641512981, 1390243617176012, 1966325177038383 },
+ { 2063958120364491, 2140267332393533, 699896251574968, 273268351312140, 375580724713232 }
+ },
+ {
+ { 2024297515263178, 416959329722687, 1079014235017302, 171612225573183, 1031677520051053 },
+ { 2033900009388450, 1744902869870788, 2190580087917640, 1949474984254121, 231049754293748 },
+ { 343868674606581, 550155864008088, 1450580864229630, 481603765195050, 896972360018042 }
+ },
+ {
+ { 2151139328380127, 314745882084928, 59756825775204, 1676664391494651, 2048348075599360 },
+ { 1528930066340597, 1605003907059576, 1055061081337675, 1458319101947665, 1234195845213142 },
+ { 830430507734812, 1780282976102377, 1425386760709037, 362399353095425, 2168861579799910 }
+ },
+ {
+ { 1155762232730333, 980662895504006, 2053766700883521, 490966214077606, 510405877041357 },
+ { 1683750316716132, 652278688286128, 1221798761193539, 1897360681476669, 319658166027343 },
+ { 618808732869972, 72755186759744, 2060379135624181, 1730731526741822, 48862757828238 }
+ },
+ {
+ { 1463171970593505, 1143040711767452, 614590986558883, 1409210575145591, 1882816996436803 },
+ { 2230133264691131, 563950955091024, 2042915975426398, 827314356293472, 672028980152815 },
+ { 264204366029760, 1654686424479449, 2185050199932931, 2207056159091748, 506015669043634 }
+ },
+ {
+ { 1784446333136569, 1973746527984364, 334856327359575, 1156769775884610, 1023950124675478 },
+ { 2065270940578383, 31477096270353, 306421879113491, 181958643936686, 1907105536686083 },
+ { 1496516440779464, 1748485652986458, 872778352227340, 818358834654919, 97932669284220 }
+ }
+},
+{ /* 29/31 */
+ {
+ { 471636015770351, 672455402793577, 1804995246884103, 1842309243470804, 1501862504981682 },
+ { 1013216974933691, 538921919682598, 1915776722521558, 1742822441583877, 1886550687916656 },
+ { 2094270000643336, 303971879192276, 40801275554748, 649448917027930, 1818544418535447 }
+ },
+ {
+ { 2241737709499165, 549397817447461, 838180519319392, 1725686958520781, 1705639080897747 },
+ { 1216074541925116, 50120933933509, 1565829004133810, 721728156134580, 349206064666188 },
+ { 948617110470858, 346222547451945, 1126511960599975, 1759386906004538, 493053284802266 }
+ },
+ {
+ { 1454933046815146, 874696014266362, 1467170975468588, 1432316382418897, 2111710746366763 },
+ { 2105387117364450, 1996463405126433, 1303008614294500, 851908115948209, 1353742049788635 },
+ { 750300956351719, 1487736556065813, 15158817002104, 1511998221598392, 971739901354129 }
+ },
+ {
+ { 1874648163531693, 2124487685930551, 1810030029384882, 918400043048335, 586348627300650 },
+ { 1235084464747900, 1166111146432082, 1745394857881591, 1405516473883040, 4463504151617 },
+ { 1663810156463827, 327797390285791, 1341846161759410, 1964121122800605, 1747470312055380 }
+ },
+ {
+ { 660005247548233, 2071860029952887, 1358748199950107, 911703252219107, 1014379923023831 },
+ { 2206641276178231, 1690587809721504, 1600173622825126, 2156096097634421, 1106822408548216 },
+ { 1344788193552206, 1949552134239140, 1735915881729557, 675891104100469, 1834220014427292 }
+ },
+ {
+ { 1920949492387964, 158885288387530, 70308263664033, 626038464897817, 1468081726101009 },
+ { 622221042073383, 1210146474039168, 1742246422343683, 1403839361379025, 417189490895736 },
+ { 22727256592983, 168471543384997, 1324340989803650, 1839310709638189, 504999476432775 }
+ },
+ {
+ { 1313240518756327, 1721896294296942, 52263574587266, 2065069734239232, 804910473424630 },
+ { 1337466662091884, 1287645354669772, 2018019646776184, 652181229374245, 898011753211715 },
+ { 1969792547910734, 779969968247557, 2011350094423418, 1823964252907487, 1058949448296945 }
+ },
+ {
+ { 207343737062002, 1118176942430253, 758894594548164, 806764629546266, 1157700123092949 },
+ { 1273565321399022, 1638509681964574, 759235866488935, 666015124346707, 897983460943405 },
+ { 1717263794012298, 1059601762860786, 1837819172257618, 1054130665797229, 680893204263559 }
+ }
+},
+{ /* 30/31 */
+ {
+ { 2237039662793603, 2249022333361206, 2058613546633703, 149454094845279, 2215176649164582 },
+ { 79472182719605, 1851130257050174, 1825744808933107, 821667333481068, 781795293511946 },
+ { 755822026485370, 152464789723500, 1178207602290608, 410307889503239, 156581253571278 }
+ },
+ {
+ { 1418185496130297, 484520167728613, 1646737281442950, 1401487684670265, 1349185550126961 },
+ { 1495380034400429, 325049476417173, 46346894893933, 1553408840354856, 828980101835683 },
+ { 1280337889310282, 2070832742866672, 1640940617225222, 2098284908289951, 450929509534434 }
+ },
+ {
+ { 407703353998781, 126572141483652, 286039827513621, 1999255076709338, 2030511179441770 },
+ { 1254958221100483, 1153235960999843, 942907704968834, 637105404087392, 1149293270147267 },
+ { 894249020470196, 400291701616810, 406878712230981, 1599128793487393, 1145868722604026 }
+ },
+ {
+ { 1497955250203334, 110116344653260, 1128535642171976, 1900106496009660, 129792717460909 },
+ { 452487513298665, 1352120549024569, 1173495883910956, 1999111705922009, 367328130454226 },
+ { 1717539401269642, 1475188995688487, 891921989653942, 836824441505699, 1885988485608364 }
+ },
+ {
+ { 1241784121422547, 187337051947583, 1118481812236193, 428747751936362, 30358898927325 },
+ { 2022432361201842, 1088816090685051, 1977843398539868, 1854834215890724, 564238862029357 },
+ { 938868489100585, 1100285072929025, 1017806255688848, 1957262154788833, 152787950560442 }
+ },
+ {
+ { 867319417678923, 620471962942542, 226032203305716, 342001443957629, 1761675818237336 },
+ { 1295072362439987, 931227904689414, 1355731432641687, 922235735834035, 892227229410209 },
+ { 1680989767906154, 535362787031440, 2136691276706570, 1942228485381244, 1267350086882274 }
+ },
+ {
+ { 366018233770527, 432660629755596, 126409707644535, 1973842949591662, 645627343442376 },
+ { 535509430575217, 546885533737322, 1524675609547799, 2138095752851703, 1260738089896827 },
+ { 1159906385590467, 2198530004321610, 714559485023225, 81880727882151, 1484020820037082 }
+ },
+ {
+ { 1377485731340769, 2046328105512000, 1802058637158797, 62146136768173, 1356993908853901 },
+ { 2013612215646735, 1830770575920375, 536135310219832, 609272325580394, 270684344495013 },
+ { 1237542585982777, 2228682050256790, 1385281931622824, 593183794882890, 493654978552689 }
+ }
+},
+{ /* 31/31 */
+ {
+ { 47341488007760, 1891414891220257, 983894663308928, 176161768286818, 1126261115179708 },
+ { 1694030170963455, 502038567066200, 1691160065225467, 949628319562187, 275110186693066 },
+ { 1124515748676336, 1661673816593408, 1499640319059718, 1584929449166988, 558148594103306 }
+ },
+ {
+ { 1784525599998356, 1619698033617383, 2097300287550715, 258265458103756, 1905684794832758 },
+ { 1288941072872766, 931787902039402, 190731008859042, 2006859954667190, 1005931482221702 },
+ { 1465551264822703, 152905080555927, 680334307368453, 173227184634745, 666407097159852 }
+ },
+ {
+ { 2111017076203943, 1378760485794347, 1248583954016456, 1352289194864422, 1895180776543896 },
+ { 171348223915638, 662766099800389, 462338943760497, 466917763340314, 656911292869115 },
+ { 488623681976577, 866497561541722, 1708105560937768, 1673781214218839, 1506146329818807 }
+ },
+ {
+ { 160425464456957, 950394373239689, 430497123340934, 711676555398832, 320964687779005 },
+ { 988979367990485, 1359729327576302, 1301834257246029, 294141160829308, 29348272277475 },
+ { 1434382743317910, 100082049942065, 221102347892623, 186982837860588, 1305765053501834 }
+ },
+ {
+ { 2205916462268190, 499863829790820, 961960554686616, 158062762756985, 1841471168298305 },
+ { 1191737341426592, 1847042034978363, 1382213545049056, 1039952395710448, 788812858896859 },
+ { 1346965964571152, 1291881610839830, 2142916164336056, 786821641205979, 1571709146321039 }
+ },
+ {
+ { 787164375951248, 202869205373189, 1356590421032140, 1431233331032510, 786341368775957 },
+ { 492448143532951, 304105152670757, 1761767168301056, 233782684697790, 1981295323106089 },
+ { 665807507761866, 1343384868355425, 895831046139653, 439338948736892, 1986828765695105 }
+ },
+ {
+ { 756096210874553, 1721699973539149, 258765301727885, 1390588532210645, 1212530909934781 },
+ { 852891097972275, 1816988871354562, 1543772755726524, 1174710635522444, 202129090724628 },
+ { 1205281565824323, 22430498399418, 992947814485516, 1392458699738672, 688441466734558 }
+ },
+ {
+ { 1050627428414972, 1955849529137135, 2171162376368357, 91745868298214, 447733118757826 },
+ { 1287181461435438, 622722465530711, 880952150571872, 741035693459198, 311565274989772 },
+ { 1003649078149734, 545233927396469, 1849786171789880, 1318943684880434, 280345687170552 }
+ }
+}
diff --git a/third_party/heimdal/lib/hcrypto/x25519/fe_51/base2.h b/third_party/heimdal/lib/hcrypto/x25519/fe_51/base2.h
new file mode 100644
index 0000000..d088241
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/fe_51/base2.h
@@ -0,0 +1,40 @@
+{
+ { 1288382639258501, 245678601348599, 269427782077623, 1462984067271730, 137412439391563 },
+ { 62697248952638, 204681361388450, 631292143396476, 338455783676468, 1213667448819585 },
+ { 301289933810280, 1259582250014073, 1422107436869536, 796239922652654, 1953934009299142 }
+},
+{
+ { 1601611775252272, 1720807796594148, 1132070835939856, 1260455018889551, 2147779492816911 },
+ { 316559037616741, 2177824224946892, 1459442586438991, 1461528397712656, 751590696113597 },
+ { 1850748884277385, 1200145853858453, 1068094770532492, 672251375690438, 1586055907191707 }
+},
+{
+ { 769950342298419, 132954430919746, 844085933195555, 974092374476333, 726076285546016 },
+ { 425251763115706, 608463272472562, 442562545713235, 837766094556764, 374555092627893 },
+ { 1086255230780037, 274979815921559, 1960002765731872, 929474102396301, 1190409889297339 }
+},
+{
+ { 665000864555967, 2065379846933859, 370231110385876, 350988370788628, 1233371373142985 },
+ { 2019367628972465, 676711900706637, 110710997811333, 1108646842542025, 517791959672113 },
+ { 965130719900578, 247011430587952, 526356006571389, 91986625355052, 2157223321444601 }
+},
+{
+ { 1802695059465007, 1664899123557221, 593559490740857, 2160434469266659, 927570450755031 },
+ { 1725674970513508, 1933645953859181, 1542344539275782, 1767788773573747, 1297447965928905 },
+ { 1381809363726107, 1430341051343062, 2061843536018959, 1551778050872521, 2036394857967624 }
+},
+{
+ { 1970894096313054, 528066325833207, 1619374932191227, 2207306624415883, 1169170329061080 },
+ { 2070390218572616, 1458919061857835, 624171843017421, 1055332792707765, 433987520732508 },
+ { 893653801273833, 1168026499324677, 1242553501121234, 1306366254304474, 1086752658510815 }
+},
+{
+ { 213454002618221, 939771523987438, 1159882208056014, 317388369627517, 621213314200687 },
+ { 1971678598905747, 338026507889165, 762398079972271, 655096486107477, 42299032696322 },
+ { 177130678690680, 1754759263300204, 1864311296286618, 1180675631479880, 1292726903152791 }
+},
+{
+ { 1913163449625248, 460779200291993, 2193883288642314, 1008900146920800, 1721983679009502 },
+ { 1070401523076875, 1272492007800961, 1910153608563310, 2075579521696771, 1191169788841221 },
+ { 692896803108118, 500174642072499, 2068223309439677, 1162190621851337, 1426986007309901 }
+}
diff --git a/third_party/heimdal/lib/hcrypto/x25519/fe_51/constants.h b/third_party/heimdal/lib/hcrypto/x25519/fe_51/constants.h
new file mode 100644
index 0000000..24e5cb5
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/fe_51/constants.h
@@ -0,0 +1,41 @@
+/* 37095705934669439343138083508754565189542113879843219016388785533085940283555 */
+static const fe25519 d = {
+ 929955233495203, 466365720129213, 1662059464998953, 2033849074728123, 1442794654840575
+};
+
+/* 2 * d =
+ * 16295367250680780974490674513165176452449235426866156013048779062215315747161
+ */
+static const fe25519 d2 = {
+ 1859910466990425, 932731440258426, 1072319116312658, 1815898335770999, 633789495995903
+};
+
+/* sqrt(-1) */
+static const fe25519 sqrtm1 = {
+ 1718705420411056, 234908883556509, 2233514472574048, 2117202627021982, 765476049583133
+};
+
+/* A = 486662 */
+static const fe25519 curve25519_A = {
+ 486662, 0, 0, 0, 0
+};
+
+/* sqrt(ad - 1) with a = -1 (mod p) */
+static const fe25519 sqrtadm1 = {
+ 2241493124984347, 425987919032274, 2207028919301688, 1220490630685848, 974799131293748
+};
+
+/* 1 / sqrt(a - d) */
+static const fe25519 invsqrtamd = {
+ 278908739862762, 821645201101625, 8113234426968, 1777959178193151, 2118520810568447
+};
+
+/* 1 - d ^ 2 */
+static const fe25519 onemsqd = {
+ 1136626929484150, 1998550399581263, 496427632559748, 118527312129759, 45110755273534
+};
+
+/* (d - 1) ^ 2 */
+static const fe25519 sqdmone = {
+ 1507062230895904, 1572317787530805, 683053064812840, 317374165784489, 1572899562415810
+};
diff --git a/third_party/heimdal/lib/hcrypto/x25519/fe_51/fe.h b/third_party/heimdal/lib/hcrypto/x25519/fe_51/fe.h
new file mode 100644
index 0000000..de87626
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/fe_51/fe.h
@@ -0,0 +1,116 @@
+/*
+ Ignores top bit of h.
+ */
+
+void
+fe25519_frombytes(fe25519 h, const unsigned char *s)
+{
+ const uint64_t mask = 0x7ffffffffffffULL;
+ uint64_t h0, h1, h2, h3, h4;
+
+ h0 = (LOAD64_LE(s ) ) & mask;
+ h1 = (LOAD64_LE(s + 6) >> 3) & mask;
+ h2 = (LOAD64_LE(s + 12) >> 6) & mask;
+ h3 = (LOAD64_LE(s + 19) >> 1) & mask;
+ h4 = (LOAD64_LE(s + 24) >> 12) & mask;
+
+ h[0] = h0;
+ h[1] = h1;
+ h[2] = h2;
+ h[3] = h3;
+ h[4] = h4;
+}
+
+static void
+fe25519_reduce(fe25519 h, const fe25519 f)
+{
+ const uint64_t mask = 0x7ffffffffffffULL;
+ uint128_t t[5];
+
+ t[0] = f[0];
+ t[1] = f[1];
+ t[2] = f[2];
+ t[3] = f[3];
+ t[4] = f[4];
+
+ t[1] += t[0] >> 51;
+ t[0] &= mask;
+ t[2] += t[1] >> 51;
+ t[1] &= mask;
+ t[3] += t[2] >> 51;
+ t[2] &= mask;
+ t[4] += t[3] >> 51;
+ t[3] &= mask;
+ t[0] += 19 * (t[4] >> 51);
+ t[4] &= mask;
+
+ t[1] += t[0] >> 51;
+ t[0] &= mask;
+ t[2] += t[1] >> 51;
+ t[1] &= mask;
+ t[3] += t[2] >> 51;
+ t[2] &= mask;
+ t[4] += t[3] >> 51;
+ t[3] &= mask;
+ t[0] += 19 * (t[4] >> 51);
+ t[4] &= mask;
+
+ /* now t is between 0 and 2^255-1, properly carried. */
+ /* case 1: between 0 and 2^255-20. case 2: between 2^255-19 and 2^255-1. */
+
+ t[0] += 19ULL;
+
+ t[1] += t[0] >> 51;
+ t[0] &= mask;
+ t[2] += t[1] >> 51;
+ t[1] &= mask;
+ t[3] += t[2] >> 51;
+ t[2] &= mask;
+ t[4] += t[3] >> 51;
+ t[3] &= mask;
+ t[0] += 19ULL * (t[4] >> 51);
+ t[4] &= mask;
+
+ /* now between 19 and 2^255-1 in both cases, and offset by 19. */
+
+ t[0] += 0x8000000000000 - 19ULL;
+ t[1] += 0x8000000000000 - 1ULL;
+ t[2] += 0x8000000000000 - 1ULL;
+ t[3] += 0x8000000000000 - 1ULL;
+ t[4] += 0x8000000000000 - 1ULL;
+
+ /* now between 2^255 and 2^256-20, and offset by 2^255. */
+
+ t[1] += t[0] >> 51;
+ t[0] &= mask;
+ t[2] += t[1] >> 51;
+ t[1] &= mask;
+ t[3] += t[2] >> 51;
+ t[2] &= mask;
+ t[4] += t[3] >> 51;
+ t[3] &= mask;
+ t[4] &= mask;
+
+ h[0] = t[0];
+ h[1] = t[1];
+ h[2] = t[2];
+ h[3] = t[3];
+ h[4] = t[4];
+}
+
+void
+fe25519_tobytes(unsigned char *s, const fe25519 h)
+{
+ fe25519 t;
+ uint64_t t0, t1, t2, t3;
+
+ fe25519_reduce(t, h);
+ t0 = t[0] | (t[1] << 51);
+ t1 = (t[1] >> 13) | (t[2] << 38);
+ t2 = (t[2] >> 26) | (t[3] << 25);
+ t3 = (t[3] >> 39) | (t[4] << 12);
+ STORE64_LE(s + 0, t0);
+ STORE64_LE(s + 8, t1);
+ STORE64_LE(s + 16, t2);
+ STORE64_LE(s + 24, t3);
+}
diff --git a/third_party/heimdal/lib/hcrypto/x25519/x25519_ref10.c b/third_party/heimdal/lib/hcrypto/x25519/x25519_ref10.c
new file mode 100644
index 0000000..d6fced7
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519/x25519_ref10.c
@@ -0,0 +1,209 @@
+/*
+ * ISC License
+ *
+ * Copyright (c) 2013-2019
+ * Frank Denis <j at pureftpd dot org>
+ *
+ * Permission to use, copy, modify, and/or 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.
+ */
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include "ed25519_ref10.h"
+#include "x25519_ref10.h"
+#include "align.h"
+
+/*
+ * Reject small order points early to mitigate the implications of
+ * unexpected optimizations that would affect the ref10 code.
+ * See https://eprint.iacr.org/2017/806.pdf for reference.
+ */
+static int
+has_small_order(const unsigned char s[32])
+{
+ CRYPTO_ALIGN(16)
+ static const unsigned char blacklist[][32] = {
+ /* 0 (order 4) */
+ { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
+ /* 1 (order 1) */
+ { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
+ /* 325606250916557431795983626356110631294008115727848805560023387167927233504
+ (order 8) */
+ { 0xe0, 0xeb, 0x7a, 0x7c, 0x3b, 0x41, 0xb8, 0xae, 0x16, 0x56, 0xe3,
+ 0xfa, 0xf1, 0x9f, 0xc4, 0x6a, 0xda, 0x09, 0x8d, 0xeb, 0x9c, 0x32,
+ 0xb1, 0xfd, 0x86, 0x62, 0x05, 0x16, 0x5f, 0x49, 0xb8, 0x00 },
+ /* 39382357235489614581723060781553021112529911719440698176882885853963445705823
+ (order 8) */
+ { 0x5f, 0x9c, 0x95, 0xbc, 0xa3, 0x50, 0x8c, 0x24, 0xb1, 0xd0, 0xb1,
+ 0x55, 0x9c, 0x83, 0xef, 0x5b, 0x04, 0x44, 0x5c, 0xc4, 0x58, 0x1c,
+ 0x8e, 0x86, 0xd8, 0x22, 0x4e, 0xdd, 0xd0, 0x9f, 0x11, 0x57 },
+ /* p-1 (order 2) */
+ { 0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f },
+ /* p (=0, order 4) */
+ { 0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f },
+ /* p+1 (=1, order 1) */
+ { 0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f }
+ };
+ unsigned char c[7] = { 0 };
+ unsigned int k;
+ size_t i, j;
+
+#define COMPILER_ASSERT(X) (void) sizeof(char[(X) ? 1 : -1])
+
+ COMPILER_ASSERT(7 == sizeof blacklist / sizeof blacklist[0]);
+ for (j = 0; j < 31; j++) {
+ for (i = 0; i < sizeof blacklist / sizeof blacklist[0]; i++) {
+ c[i] |= s[j] ^ blacklist[i][j];
+ }
+ }
+ for (i = 0; i < sizeof blacklist / sizeof blacklist[0]; i++) {
+ c[i] |= (s[j] & 0x7f) ^ blacklist[i][j];
+ }
+ k = 0;
+ for (i = 0; i < sizeof blacklist / sizeof blacklist[0]; i++) {
+ k |= (c[i] - 1);
+ }
+ return (int) ((k >> 8) & 1);
+}
+
+static int
+crypto_scalarmult_curve25519_ref10(unsigned char *q,
+ const unsigned char *n,
+ const unsigned char *p)
+{
+ unsigned char *t = q;
+ unsigned int i;
+ fe25519 x1;
+ fe25519 x2;
+ fe25519 z2;
+ fe25519 x3;
+ fe25519 z3;
+ fe25519 tmp0;
+ fe25519 tmp1;
+ int pos;
+ unsigned int swap;
+ unsigned int b;
+
+ if (has_small_order(p)) {
+ return -1;
+ }
+ for (i = 0; i < 32; i++) {
+ t[i] = n[i];
+ }
+ t[0] &= 248;
+ t[31] &= 127;
+ t[31] |= 64;
+ fe25519_frombytes(x1, p);
+ fe25519_1(x2);
+ fe25519_0(z2);
+ fe25519_copy(x3, x1);
+ fe25519_1(z3);
+
+ swap = 0;
+ for (pos = 254; pos >= 0; --pos) {
+ b = t[pos / 8] >> (pos & 7);
+ b &= 1;
+ swap ^= b;
+ fe25519_cswap(x2, x3, swap);
+ fe25519_cswap(z2, z3, swap);
+ swap = b;
+ fe25519_sub(tmp0, x3, z3);
+ fe25519_sub(tmp1, x2, z2);
+ fe25519_add(x2, x2, z2);
+ fe25519_add(z2, x3, z3);
+ fe25519_mul(z3, tmp0, x2);
+ fe25519_mul(z2, z2, tmp1);
+ fe25519_sq(tmp0, tmp1);
+ fe25519_sq(tmp1, x2);
+ fe25519_add(x3, z3, z2);
+ fe25519_sub(z2, z3, z2);
+ fe25519_mul(x2, tmp1, tmp0);
+ fe25519_sub(tmp1, tmp1, tmp0);
+ fe25519_sq(z2, z2);
+ fe25519_scalar_product(z3, tmp1, 121666);
+ fe25519_sq(x3, x3);
+ fe25519_add(tmp0, tmp0, z3);
+ fe25519_mul(z3, x1, z2);
+ fe25519_mul(z2, tmp1, tmp0);
+ }
+ fe25519_cswap(x2, x3, swap);
+ fe25519_cswap(z2, z3, swap);
+
+ fe25519_invert(z2, z2);
+ fe25519_mul(x2, x2, z2);
+ fe25519_tobytes(q, x2);
+
+ return 0;
+}
+
+static void
+edwards_to_montgomery(fe25519 montgomeryX, const fe25519 edwardsY, const fe25519 edwardsZ)
+{
+ fe25519 tempX;
+ fe25519 tempZ;
+
+ fe25519_add(tempX, edwardsZ, edwardsY);
+ fe25519_sub(tempZ, edwardsZ, edwardsY);
+ fe25519_invert(tempZ, tempZ);
+ fe25519_mul(montgomeryX, tempX, tempZ);
+}
+
+int
+crypto_scalarmult_curve25519_base(unsigned char *q,
+ const unsigned char *n)
+{
+ unsigned char *t = q;
+ ge25519_p3 A;
+ fe25519 pk;
+ unsigned int i;
+
+ for (i = 0; i < 32; i++) {
+ t[i] = n[i];
+ }
+ t[0] &= 248;
+ t[31] &= 127;
+ t[31] |= 64;
+ ge25519_scalarmult_base(&A, t);
+ edwards_to_montgomery(pk, A.Y, A.Z);
+ fe25519_tobytes(q, pk);
+
+ return 0;
+}
+
+int
+crypto_scalarmult_curve25519(unsigned char *q, const unsigned char *n,
+ const unsigned char *p)
+{
+ size_t i;
+ volatile unsigned char d = 0;
+
+ if (crypto_scalarmult_curve25519_ref10(q, n, p) != 0) {
+ return -1; /* LCOV_EXCL_LINE */
+ }
+ for (i = 0; i < crypto_scalarmult_curve25519_BYTES; i++) {
+ d |= q[i];
+ }
+ return -(1 & ((d - 1) >> 8));
+}
+
diff --git a/third_party/heimdal/lib/hcrypto/x25519_ref10.h b/third_party/heimdal/lib/hcrypto/x25519_ref10.h
new file mode 100644
index 0000000..f43cc02
--- /dev/null
+++ b/third_party/heimdal/lib/hcrypto/x25519_ref10.h
@@ -0,0 +1,55 @@
+/*
+ * ISC License
+ *
+ * Copyright (c) 2013-2019
+ * Frank Denis <j at pureftpd dot org>
+ *
+ * Permission to use, copy, modify, and/or 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.
+ */
+
+#ifndef x25519_ref10_H
+#define x25519_ref10_H
+
+#include <stddef.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define crypto_scalarmult_curve25519_BYTES 32U
+size_t crypto_scalarmult_curve25519_bytes(void);
+
+#define crypto_scalarmult_curve25519_SCALARBYTES 32U
+size_t crypto_scalarmult_curve25519_scalarbytes(void);
+
+/*
+ * NOTE: Do not use the result of this function directly for key exchange.
+ *
+ * Hash the result with the public keys in order to compute a shared
+ * secret key: H(q || client_pk || server_pk)
+ *
+ * Or unless this is not an option, use the crypto_kx() API instead.
+ */
+#define crypto_scalarmult_curve25519 hc_hcrypto_scalarmult_curve25519
+int crypto_scalarmult_curve25519(unsigned char *q, const unsigned char *n,
+ const unsigned char *p);
+
+#define crypto_scalarmult_curve25519_base hc_hcrypto_scalarmult_curve25519_base
+int crypto_scalarmult_curve25519_base(unsigned char *q,
+ const unsigned char *n);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/third_party/heimdal/lib/hdb/Makefile.am b/third_party/heimdal/lib/hdb/Makefile.am
new file mode 100644
index 0000000..89ab15d
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/Makefile.am
@@ -0,0 +1,168 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+WFLAGS += $(WFLAGS_ENUM_CONV)
+
+AM_CPPFLAGS += -I../asn1 -I$(srcdir)/../asn1
+AM_CPPFLAGS += $(INCLUDE_openldap) -DHDB_DB_DIR=\"$(DIR_hdbdir)\"
+AM_CPPFLAGS += -I$(srcdir)/../krb5
+AM_CPPFLAGS += $(INCLUDE_sqlite3)
+AM_CPPFLAGS += $(INCLUDE_libintl)
+AM_CPPFLAGS += -DHDB_DEFAULT_DB_TYPE=\"$(db_type):\"
+if HAVE_DBHEADER
+AM_CPPFLAGS += -I$(DBHEADER)
+endif
+
+BUILT_SOURCES = \
+ $(gen_files_hdb) \
+ hdb_err.c \
+ hdb_err.h
+
+gen_files_hdb = \
+ asn1_Event.c \
+ asn1_GENERATION.c \
+ asn1_HDB_EncTypeList.c \
+ asn1_HDB_Ext_Aliases.c \
+ asn1_HDB_Ext_Constrained_delegation_acl.c \
+ asn1_HDB_Ext_KeyRotation.c \
+ asn1_HDB_Ext_KeySet.c \
+ asn1_HDB_Ext_Lan_Manager_OWF.c \
+ asn1_HDB_Ext_Password.c \
+ asn1_HDB_Ext_PKINIT_acl.c \
+ asn1_HDB_Ext_PKINIT_cert.c \
+ asn1_HDB_Ext_PKINIT_hash.c \
+ asn1_HDB_EntryOrAlias.c \
+ asn1_HDB_entry_alias.c \
+ asn1_HDB_entry.c \
+ asn1_HDB_extension.c \
+ asn1_HDB_extensions.c \
+ asn1_HDB_keyset.c \
+ asn1_HDBFlags.c \
+ asn1_Key.c \
+ asn1_KeyRotation.c \
+ asn1_KeyRotationFlags.c \
+ asn1_Keys.c \
+ asn1_Salt.c
+
+CLEANFILES = $(BUILT_SOURCES) $(gen_files_hdb) \
+ hdb_asn1{,-priv}.h hdb_asn1_files hdb_asn1-template.c \
+ hdb_asn1_syms.c hdb_asn1_oids.c hdb_asn1.json \
+ testhdb-*
+
+LDADD = libhdb.la \
+ ../krb5/libkrb5.la \
+ ../asn1/libasn1.la \
+ $(LIB_hcrypto) \
+ $(LIB_roken) \
+ $(LIB_openldap) \
+ $(LIB_libintl) \
+ $(LIB_ldopen)
+
+
+if OPENLDAP_MODULE
+
+ldap_so = hdb_ldap.la
+hdb_ldap_la_SOURCES = hdb-ldap.c
+hdb_ldap_la_LDFLAGS = -module -avoid-version
+hdb_ldap_la_LIBADD = $(LIB_openldap) libhdb.la
+
+else
+
+ldap = hdb-ldap.c
+ldap_lib = $(LIB_openldap)
+
+endif
+
+
+lib_LTLIBRARIES = libhdb.la $(ldap_so)
+libhdb_la_LDFLAGS = -version-info 11:0:2
+
+if versionscript
+libhdb_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+endif
+
+# test_hdbkeys and test_mkey are not tests -- they are manual test utils
+noinst_PROGRAMS = test_dbinfo test_hdbkeys test_mkey test_namespace test_concurrency
+TESTS = test_dbinfo test_namespace test_concurrency
+
+dist_libhdb_la_SOURCES = \
+ common.c \
+ db.c \
+ db3.c \
+ ext.c \
+ $(ldap) \
+ hdb.c \
+ hdb-sqlite.c \
+ hdb-keytab.c \
+ hdb-mdb.c \
+ hdb-mitdb.c \
+ hdb_locl.h \
+ keys.c \
+ keytab.c \
+ dbinfo.c \
+ mkey.c \
+ ndbm.c \
+ print.c
+
+nodist_libhdb_la_SOURCES = $(BUILT_SOURCES)
+
+libhdb_la_DEPENDENCIES = version-script.map
+
+include_HEADERS = hdb.h $(srcdir)/hdb-protos.h
+nodist_include_HEADERS = hdb_err.h hdb_asn1.h
+
+noinst_HEADERS = $(srcdir)/hdb-private.h
+
+libhdb_la_LIBADD = \
+ $(LIB_com_err) \
+ ../krb5/libkrb5.la \
+ ../asn1/libasn1.la \
+ $(LIB_sqlite3) \
+ $(LIBADD_roken) \
+ $(ldap_lib) \
+ $(LIB_dlopen) \
+ $(DB3LIB) $(DB1LIB) $(LMDBLIB) $(NDBMLIB)
+
+HDB_PROTOS = $(srcdir)/hdb-protos.h $(srcdir)/hdb-private.h
+
+ALL_OBJECTS = $(libhdb_la_OBJECTS)
+ALL_OBJECTS += $(test_dbinfo_OBJECTS)
+ALL_OBJECTS += $(test_hdbkeys_OBJECTS)
+ALL_OBJECTS += $(test_mkey_OBJECTS)
+ALL_OBJECTS += $(test_namespace_OBJECTS)
+ALL_OBJECTS += $(test_concurrency_OBJECTS)
+
+$(ALL_OBJECTS): $(HDB_PROTOS) hdb_asn1.h hdb_asn1-priv.h hdb_err.h
+
+test_namespace_LDADD = $(LDADD) $(test_hdbkeys_LIBS) $(LIB_heimbase)
+
+$(srcdir)/hdb-protos.h: $(dist_libhdb_la_SOURCES)
+ cd $(srcdir); perl ../../cf/make-proto.pl -q -P comment -o hdb-protos.h $(dist_libhdb_la_SOURCES) || rm -f hdb-protos.h
+
+$(srcdir)/hdb-private.h: $(dist_libhdb_la_SOURCES)
+ cd $(srcdir); perl ../../cf/make-proto.pl -q -P comment -p hdb-private.h $(dist_libhdb_la_SOURCES) || rm -f hdb-private.h
+
+$(gen_files_hdb) hdb_asn1.h hdb_asn1-priv.h: hdb_asn1_files
+ for genfile in '$(gen_files_hdb)'; do \
+ $(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i $${genfile}; \
+ done
+
+hdb_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/hdb.asn1
+ $(ASN1_COMPILE) --option-file=$(srcdir)/hdb.opt $(srcdir)/hdb.asn1 hdb_asn1
+ @$(CLANG_FORMAT) -style=$(CLANG_FORMAT_STYLE) -i $$(cat hdb_asn1_files)
+
+# to help stupid solaris make
+
+hdb_err.h: hdb_err.et
+
+EXTRA_DIST = \
+ NTMakefile \
+ libhdb-version.rc \
+ libhdb-exports.def \
+ hdb.asn1 \
+ hdb_err.et \
+ hdb.schema \
+ version-script.map \
+ data-mkey.mit.des3.le \
+ data-mkey.mit.des3.be
diff --git a/third_party/heimdal/lib/hdb/NTMakefile b/third_party/heimdal/lib/hdb/NTMakefile
new file mode 100644
index 0000000..f4801f7
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/NTMakefile
@@ -0,0 +1,189 @@
+########################################################################
+#
+# Copyright (c) 2009, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\hdb
+
+intcflags=-DASN1_LIB
+
+!include ../../windows/NTMakefile.w32
+
+$(OBJ)\asn1_hdb_asn1.c $(OBJ)\hdb_asn1.h $(OBJ)\hdb_asn1-priv.h: $(BINDIR)\asn1_compile.exe hdb.asn1
+ cd $(OBJ)
+ $(BINDIR)\asn1_compile.exe --one-code-file --option-file=$(SRCDIR)\hdb.opt $(SRCDIR)\hdb.asn1 hdb_asn1
+ cd $(SRCDIR)
+
+!ifdef OPENLDAP_MODULE
+
+ldap_dll = $(BINDIR)\hdb_ldap.dll
+ldap_lib = $(LIBDIR)\hdb_ldap.lib
+ldap_objs = $(OBJ)\hdb-ldap.obj
+
+$(ldap_dll): $(ldap_objs)
+ $(DLLGUILINK) -implib:$(ldap_lib)
+ $(DLLPREP)
+
+clean::
+ -$(RM) $(ldap_dll)
+ -$(RM) $(ldap_lib)
+
+!else
+
+ldap = $(OBJ)\hdb-ldap.obj
+ldap_c = hdb-ldap.c
+
+!endif
+
+dist_libhdb_la_SOURCES = \
+ common.c \
+ db.c \
+ db3.c \
+ ext.c \
+ $(ldap_c) \
+ hdb.c \
+ hdb-sqlite.c \
+ hdb-keytab.c \
+ hdb-mitdb.c \
+ hdb-mdb.c \
+ hdb_locl.h \
+ keys.c \
+ keytab.c \
+ dbinfo.c \
+ mkey.c \
+ ndbm.c \
+ print.c
+
+libhdb_OBJs = \
+ $(OBJ)\common.obj \
+ $(OBJ)\db.obj \
+ $(OBJ)\db3.obj \
+ $(OBJ)\ext.obj \
+ $(ldap) \
+ $(OBJ)\hdb.obj \
+ $(OBJ)\hdb-sqlite.obj \
+ $(OBJ)\hdb-keytab.obj \
+ $(OBJ)\hdb-mitdb.obj \
+ $(OBJ)\keys.obj \
+ $(OBJ)\keytab.obj \
+ $(OBJ)\dbinfo.obj \
+ $(OBJ)\mkey.obj \
+ $(OBJ)\ndbm.obj \
+ $(OBJ)\print.obj \
+ $(OBJ)\asn1_hdb_asn1.obj \
+ $(OBJ)\hdb_err.obj
+
+$(OBJ)\hdb_err.c $(OBJ)\hdb_err.h: hdb_err.et
+ cd $(OBJ)
+ $(BINDIR)\compile_et.exe $(SRCDIR)\hdb_err.et
+ cd $(SRCDIR)
+
+$(OBJ)\hdb-protos.h: $(dist_libhdb_la_SOURCES)
+ $(PERL) ../../cf/make-proto.pl -q -P remove -o $@ $(dist_libhdb_la_SOURCES) \
+ || $(RM) $@
+
+$(OBJ)\hdb-private.h: $(dist_libhdb_la_SOURCES)
+ $(PERL) ../../cf/make-proto.pl -q -P remote -p $@ $(dist_libhdb_la_SOURCES) \
+ || $(RM) $@
+
+INCFILES= \
+ $(INCDIR)\hdb.h \
+ $(INCDIR)\hdb-protos.h \
+ $(OBJ)\hdb-private.h \
+ $(INCDIR)\hdb_err.h \
+ $(INCDIR)\hdb_asn1.h \
+ $(INCDIR)\hdb_asn1-priv.h
+
+!ifndef STATICLIBS
+
+RES=$(OBJ)\libhdb-version.res
+
+$(LIBHDB): $(BINDIR)\libhdb.dll
+
+$(BINDIR)\libhdb.dll: $(libhdb_OBJs) $(ldap_lib) $(LIBHEIMBASE) $(LIBHEIMDAL) $(LIBSQLITE) $(LIBCOMERR) $(LIBROKEN) $(RES)
+ $(DLLGUILINK) -def:libhdb-exports.def -implib:$(LIBHDB)
+ $(DLLPREP_NODIST)
+
+clean::
+ -$(RM) $(BINDIR)\libhdb.*
+
+!else
+
+$(LIBHDB): $(libhdb_OBJs) $(ldap_lib)
+ $(LIBCON)
+
+!endif
+
+all:: $(INCFILES) $(LIBHDB)
+
+clean::
+ -$(RM) $(INCFILES)
+ -$(RM) $(LIBHDB)
+
+test:: test-binaries test-run
+
+test-binaries: $(OBJ)\test_dbinfo.exe $(OBJ)\test_hdbkeys.exe $(OBJ)\test_namespace.exe
+
+$(OBJ)\test_dbinfo.exe: $(OBJ)\test_dbinfo.obj $(LIBHDB) $(LIBHEIMDAL) $(LIBROKEN) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_hdbkeys.exe: $(OBJ)\test_hdbkeys.obj $(LIBHDB) $(LIBHEIMDAL) $(LIBROKEN) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_namespace.exe: $(OBJ)\test_namespace.obj $(LIBHDB) $(LIBHEIMDAL) $(LIBHEIMBASE) $(LIBROKEN) $(LIBVERS)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+test-run:
+ cd $(OBJ)
+ -test_dbinfo.exe
+ -test_hdbkeys.exe
+ -test_namespace.exe
+ cd $(SRCDIR)
+
+!ifdef OPENLDAP_INC
+openldap_inc_flag=-I$(OPENLDAP_INC)
+!else
+openldap_inc_flag=
+!endif
+
+hdb_cflags=$(openldap_inc_flag) -I$(OBJ)
+
+{}.c{$(OBJ)}.obj::
+ $(C2OBJ_P) $(hdb_cflags) -DASN1_LIB
+
+{$(OBJ)}.c{$(OBJ)}.obj::
+ $(C2OBJ_P) $(hdb_cflags)
+
+test-exports:
+ $(PERL) ..\..\cf\w32-check-exported-symbols.pl --vs version-script.map --def libhdb-exports.def
+
+test:: test-exports
diff --git a/third_party/heimdal/lib/hdb/common.c b/third_party/heimdal/lib/hdb/common.c
new file mode 100644
index 0000000..a92cc13
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/common.c
@@ -0,0 +1,1745 @@
+/*
+ * Copyright (c) 1997-2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include "hdb_locl.h"
+
+int
+hdb_principal2key(krb5_context context, krb5_const_principal p, krb5_data *key)
+{
+ Principal new;
+ size_t len = 0;
+ int ret;
+
+ ret = copy_Principal(p, &new);
+ if(ret)
+ return ret;
+ new.name.name_type = 0;
+
+ ASN1_MALLOC_ENCODE(Principal, key->data, key->length, &new, &len, ret);
+ if (ret == 0 && key->length != len)
+ krb5_abortx(context, "internal asn.1 encoder error");
+ free_Principal(&new);
+ return ret;
+}
+
+int
+hdb_key2principal(krb5_context context, krb5_data *key, krb5_principal p)
+{
+ return decode_Principal(key->data, key->length, p, NULL);
+}
+
+int
+hdb_entry2value(krb5_context context, const hdb_entry *ent, krb5_data *value)
+{
+ size_t len = 0;
+ int ret;
+
+ ASN1_MALLOC_ENCODE(HDB_entry, value->data, value->length, ent, &len, ret);
+ if (ret == 0 && value->length != len)
+ krb5_abortx(context, "internal asn.1 encoder error");
+ return ret;
+}
+
+int
+hdb_value2entry(krb5_context context, krb5_data *value, hdb_entry *ent)
+{
+ return decode_HDB_entry(value->data, value->length, ent, NULL);
+}
+
+int
+hdb_entry_alias2value(krb5_context context,
+ const hdb_entry_alias *alias,
+ krb5_data *value)
+{
+ size_t len = 0;
+ int ret;
+
+ ASN1_MALLOC_ENCODE(HDB_entry_alias, value->data, value->length,
+ alias, &len, ret);
+ if (ret == 0 && value->length != len)
+ krb5_abortx(context, "internal asn.1 encoder error");
+ return ret;
+}
+
+int
+hdb_value2entry_alias(krb5_context context, krb5_data *value,
+ hdb_entry_alias *ent)
+{
+ return decode_HDB_entry_alias(value->data, value->length, ent, NULL);
+}
+
+/*
+ * Some old databases may not have stored the salt with each key, which will
+ * break clients when aliases or canonicalization are used. Generate a
+ * default salt based on the real principal name in the entry to handle
+ * this case.
+ */
+static krb5_error_code
+add_default_salts(krb5_context context, HDB *db, hdb_entry *entry)
+{
+ krb5_error_code ret;
+ size_t i;
+ krb5_salt pwsalt;
+
+ ret = krb5_get_pw_salt(context, entry->principal, &pwsalt);
+ if (ret)
+ return ret;
+
+ for (i = 0; i < entry->keys.len; i++) {
+ Key *key = &entry->keys.val[i];
+
+ if (key->salt != NULL ||
+ _krb5_enctype_requires_random_salt(context, key->key.keytype))
+ continue;
+
+ key->salt = calloc(1, sizeof(*key->salt));
+ if (key->salt == NULL) {
+ ret = krb5_enomem(context);
+ break;
+ }
+
+ key->salt->type = KRB5_PADATA_PW_SALT;
+
+ ret = krb5_data_copy(&key->salt->salt,
+ pwsalt.saltvalue.data,
+ pwsalt.saltvalue.length);
+ if (ret)
+ break;
+ }
+
+ krb5_free_salt(context, pwsalt);
+
+ return ret;
+}
+
+static krb5_error_code
+fetch_entry_or_alias(krb5_context context,
+ HDB *db,
+ krb5_const_principal principal,
+ unsigned flags,
+ hdb_entry *entry)
+{
+ HDB_EntryOrAlias eoa;
+ krb5_principal enterprise_principal = NULL;
+ krb5_data key, value;
+ krb5_error_code ret;
+
+ value.length = 0;
+ value.data = 0;
+ key = value;
+
+ if (principal->name.name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
+ if (principal->name.name_string.len != 1) {
+ ret = KRB5_PARSE_MALFORMED;
+ krb5_set_error_message(context, ret, "malformed principal: "
+ "enterprise name with %d name components",
+ principal->name.name_string.len);
+ return ret;
+ }
+ ret = krb5_parse_name(context, principal->name.name_string.val[0],
+ &enterprise_principal);
+ if (ret)
+ return ret;
+ principal = enterprise_principal;
+ }
+
+ ret = hdb_principal2key(context, principal, &key);
+ if (ret == 0)
+ ret = db->hdb__get(context, db, key, &value);
+ if (ret == 0)
+ ret = decode_HDB_EntryOrAlias(value.data, value.length, &eoa, NULL);
+ if (ret == 0 && eoa.element == choice_HDB_EntryOrAlias_entry) {
+ *entry = eoa.u.entry;
+ } else if (ret == 0 && eoa.element == choice_HDB_EntryOrAlias_alias) {
+ krb5_data_free(&key);
+ ret = hdb_principal2key(context, eoa.u.alias.principal, &key);
+ if (ret == 0) {
+ krb5_data_free(&value);
+ ret = db->hdb__get(context, db, key, &value);
+ }
+ if (ret == 0)
+ /* No alias chaining */
+ ret = hdb_value2entry(context, &value, entry);
+ krb5_free_principal(context, eoa.u.alias.principal);
+ } else if (ret == 0)
+ ret = ENOTSUP;
+ if (ret == 0 && enterprise_principal) {
+ /*
+ * Whilst Windows does not canonicalize enterprise principal names if
+ * the canonicalize flag is unset, the original specification in
+ * draft-ietf-krb-wg-kerberos-referrals-03.txt says we should.
+ */
+ entry->flags.force_canonicalize = 1;
+ }
+
+ /* HDB_F_GET_ANY indicates request originated from KDC (not kadmin) */
+ if (ret == 0 && eoa.element == choice_HDB_EntryOrAlias_alias &&
+ (flags & (HDB_F_CANON|HDB_F_GET_ANY)) == 0) {
+
+ /* `principal' was alias but canon not req'd */
+ free_HDB_entry(entry);
+ ret = HDB_ERR_NOENTRY;
+ }
+
+ krb5_free_principal(context, enterprise_principal);
+ krb5_data_free(&value);
+ krb5_data_free(&key);
+ principal = enterprise_principal = NULL;
+ return ret;
+}
+
+krb5_error_code
+_hdb_fetch_kvno(krb5_context context, HDB *db, krb5_const_principal principal,
+ unsigned flags, krb5_kvno kvno, hdb_entry *entry)
+{
+ krb5_error_code ret;
+
+ ret = fetch_entry_or_alias(context, db, principal, flags, entry);
+ if (ret)
+ return ret;
+
+ if ((flags & HDB_F_DECRYPT) && (flags & HDB_F_ALL_KVNOS)) {
+ /* Decrypt the current keys */
+ ret = hdb_unseal_keys(context, db, entry);
+ if (ret) {
+ hdb_free_entry(context, db, entry);
+ return ret;
+ }
+ /* Decrypt the key history too */
+ ret = hdb_unseal_keys_kvno(context, db, 0, flags, entry);
+ if (ret) {
+ hdb_free_entry(context, db, entry);
+ return ret;
+ }
+ } else if ((flags & HDB_F_DECRYPT)) {
+ if ((flags & HDB_F_KVNO_SPECIFIED) == 0 || kvno == entry->kvno) {
+ /* Decrypt the current keys */
+ ret = hdb_unseal_keys(context, db, entry);
+ if (ret) {
+ hdb_free_entry(context, db, entry);
+ return ret;
+ }
+ } else {
+ if ((flags & HDB_F_ALL_KVNOS))
+ kvno = 0;
+ /*
+ * Find and decrypt the keys from the history that we want,
+ * and swap them with the current keys
+ */
+ ret = hdb_unseal_keys_kvno(context, db, kvno, flags, entry);
+ if (ret) {
+ hdb_free_entry(context, db, entry);
+ return ret;
+ }
+ }
+ }
+ if ((flags & HDB_F_FOR_AS_REQ) && (flags & HDB_F_GET_CLIENT)) {
+ /*
+ * Generate default salt for any principals missing one; note such
+ * principals could include those for which a random (non-password)
+ * key was generated, but given the salt will be ignored by a keytab
+ * client it doesn't hurt to include the default salt.
+ */
+ ret = add_default_salts(context, db, entry);
+ if (ret) {
+ hdb_free_entry(context, db, entry);
+ return ret;
+ }
+ }
+
+ return 0;
+}
+
+static krb5_error_code
+hdb_remove_aliases(krb5_context context, HDB *db, krb5_data *key)
+{
+ const HDB_Ext_Aliases *aliases;
+ krb5_error_code code;
+ hdb_entry oldentry;
+ krb5_data value;
+ size_t i;
+
+ code = db->hdb__get(context, db, *key, &value);
+ if (code == HDB_ERR_NOENTRY)
+ return 0;
+ else if (code)
+ return code;
+
+ code = hdb_value2entry(context, &value, &oldentry);
+ krb5_data_free(&value);
+ if (code)
+ return code;
+
+ code = hdb_entry_get_aliases(&oldentry, &aliases);
+ if (code || aliases == NULL) {
+ free_HDB_entry(&oldentry);
+ return code;
+ }
+ for (i = 0; i < aliases->aliases.len; i++) {
+ krb5_data akey;
+
+ code = hdb_principal2key(context, &aliases->aliases.val[i], &akey);
+ if (code == 0) {
+ code = db->hdb__del(context, db, akey);
+ krb5_data_free(&akey);
+ }
+ if (code) {
+ free_HDB_entry(&oldentry);
+ return code;
+ }
+ }
+ free_HDB_entry(&oldentry);
+ return 0;
+}
+
+static krb5_error_code
+hdb_add_aliases(krb5_context context, HDB *db,
+ unsigned flags, hdb_entry *entry)
+{
+ const HDB_Ext_Aliases *aliases;
+ krb5_error_code code;
+ krb5_data key, value;
+ size_t i;
+
+ code = hdb_entry_get_aliases(entry, &aliases);
+ if (code || aliases == NULL)
+ return code;
+
+ for (i = 0; i < aliases->aliases.len; i++) {
+ hdb_entry_alias entryalias;
+ entryalias.principal = entry->principal;
+
+ code = hdb_entry_alias2value(context, &entryalias, &value);
+ if (code)
+ return code;
+
+ code = hdb_principal2key(context, &aliases->aliases.val[i], &key);
+ if (code == 0) {
+ code = db->hdb__put(context, db, flags, key, value);
+ krb5_data_free(&key);
+ }
+ krb5_data_free(&value);
+ if (code)
+ return code;
+ }
+ return 0;
+}
+
+/* Check if new aliases are already used for other entries */
+static krb5_error_code
+hdb_check_aliases(krb5_context context, HDB *db, hdb_entry *entry)
+{
+ const HDB_Ext_Aliases *aliases = NULL;
+ HDB_EntryOrAlias eoa;
+ krb5_data akey, value;
+ size_t i;
+ int ret;
+
+ memset(&eoa, 0, sizeof(eoa));
+ krb5_data_zero(&value);
+ akey = value;
+
+ ret = hdb_entry_get_aliases(entry, &aliases);
+ for (i = 0; ret == 0 && aliases && i < aliases->aliases.len; i++) {
+ ret = hdb_principal2key(context, &aliases->aliases.val[i], &akey);
+ if (ret == 0)
+ ret = db->hdb__get(context, db, akey, &value);
+ if (ret == 0)
+ ret = decode_HDB_EntryOrAlias(value.data, value.length, &eoa, NULL);
+ if (ret == 0 && eoa.element != choice_HDB_EntryOrAlias_entry &&
+ eoa.element != choice_HDB_EntryOrAlias_alias)
+ ret = ENOTSUP;
+ if (ret == 0 && eoa.element == choice_HDB_EntryOrAlias_entry)
+ /* New alias names an existing non-alias entry in the HDB */
+ ret = HDB_ERR_EXISTS;
+ if (ret == 0 && eoa.element == choice_HDB_EntryOrAlias_alias &&
+ !krb5_principal_compare(context, eoa.u.alias.principal,
+ entry->principal))
+ /* New alias names an existing alias of a different entry */
+ ret = HDB_ERR_EXISTS;
+ if (ret == HDB_ERR_NOENTRY) /* from db->hdb__get */
+ /* New alias is a name that doesn't exist in the HDB */
+ ret = 0;
+
+ free_HDB_EntryOrAlias(&eoa);
+ krb5_data_free(&value);
+ krb5_data_free(&akey);
+ }
+ return ret;
+}
+
+/*
+ * Many HDB entries don't have `etypes' setup. Historically we use the
+ * enctypes of the selected keyset as the entry's supported enctypes, but that
+ * is problematic. By doing this at store time and, if need be, at fetch time,
+ * we can make sure to stop deriving supported etypes from keys in the long
+ * run. We also need kadm5/kadmin support for etypes. We'll use this function
+ * there to derive etypes when using a kadm5_principal_ent_t that lacks the new
+ * TL data for etypes.
+ */
+krb5_error_code
+hdb_derive_etypes(krb5_context context, hdb_entry *e, HDB_Ext_KeySet *base_keys)
+{
+ krb5_error_code ret = 0;
+ size_t i, k, netypes;
+ HDB_extension *ext;
+
+ if (!base_keys &&
+ (ext = hdb_find_extension(e, choice_HDB_extension_data_hist_keys)))
+ base_keys = &ext->data.u.hist_keys;
+
+ netypes = e->keys.len;
+ if (netypes == 0 && base_keys) {
+ /* There's no way that base_keys->val[i].keys.len == 0, but hey */
+ for (i = 0; netypes == 0 && i < base_keys->len; i++)
+ netypes = base_keys->val[i].keys.len;
+ }
+
+ if (netypes == 0)
+ return 0;
+
+ if (e->etypes != NULL) {
+ free(e->etypes->val);
+ e->etypes->len = 0;
+ e->etypes->val = 0;
+ } else if ((e->etypes = calloc(1, sizeof(e->etypes[0]))) == NULL) {
+ ret = krb5_enomem(context);
+ }
+ if (ret == 0 &&
+ (e->etypes->val = calloc(netypes, sizeof(e->etypes->val[0]))) == NULL)
+ ret = krb5_enomem(context);
+ if (ret) {
+ free(e->etypes);
+ e->etypes = 0;
+ return ret;
+ }
+ e->etypes->len = netypes;
+ for (i = 0; i < e->keys.len && i < netypes; i++)
+ e->etypes->val[i] = e->keys.val[i].key.keytype;
+ if (!base_keys || i)
+ return 0;
+ for (k = 0; i == 0 && k < base_keys->len; k++) {
+ if (!base_keys->val[k].keys.len)
+ continue;
+ for (; i < base_keys->val[k].keys.len; i++)
+ e->etypes->val[i] = base_keys->val[k].keys.val[i].key.keytype;
+ }
+ return 0;
+}
+
+krb5_error_code
+_hdb_store(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
+{
+ krb5_data key, value;
+ int code;
+
+ if (entry->flags.do_not_store ||
+ entry->flags.force_canonicalize)
+ return HDB_ERR_MISUSE;
+ /* check if new aliases already is used */
+ code = hdb_check_aliases(context, db, entry);
+ if (code)
+ return code;
+
+ if ((flags & HDB_F_PRECHECK) && (flags & HDB_F_REPLACE))
+ return 0;
+
+ if ((flags & HDB_F_PRECHECK)) {
+ code = hdb_principal2key(context, entry->principal, &key);
+ if (code)
+ return code;
+ code = db->hdb__get(context, db, key, &value);
+ krb5_data_free(&key);
+ if (code == 0)
+ krb5_data_free(&value);
+ if (code == HDB_ERR_NOENTRY)
+ return 0;
+ return code ? code : HDB_ERR_EXISTS;
+ }
+
+ if ((entry->etypes == NULL || entry->etypes->len == 0) &&
+ (code = hdb_derive_etypes(context, entry, NULL)))
+ return code;
+
+ if (entry->generation == NULL) {
+ struct timeval t;
+ entry->generation = malloc(sizeof(*entry->generation));
+ if(entry->generation == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ gettimeofday(&t, NULL);
+ entry->generation->time = t.tv_sec;
+ entry->generation->usec = t.tv_usec;
+ entry->generation->gen = 0;
+ } else
+ entry->generation->gen++;
+
+ code = hdb_seal_keys(context, db, entry);
+ if (code)
+ return code;
+
+ code = hdb_principal2key(context, entry->principal, &key);
+ if (code)
+ return code;
+
+ /* remove aliases */
+ code = hdb_remove_aliases(context, db, &key);
+ if (code) {
+ krb5_data_free(&key);
+ return code;
+ }
+ code = hdb_entry2value(context, entry, &value);
+ if (code == 0)
+ code = db->hdb__put(context, db, flags & HDB_F_REPLACE, key, value);
+ krb5_data_free(&value);
+ krb5_data_free(&key);
+ if (code)
+ return code;
+
+ code = hdb_add_aliases(context, db, flags, entry);
+
+ return code;
+}
+
+krb5_error_code
+_hdb_remove(krb5_context context, HDB *db,
+ unsigned flags, krb5_const_principal principal)
+{
+ krb5_data key, value;
+ HDB_EntryOrAlias eoa;
+ int is_alias = -1;
+ int code;
+
+ /*
+ * We only allow deletion of entries by canonical name. To remove an
+ * alias use kadm5_modify_principal().
+ *
+ * We need to determine if this is an alias. We decode as a
+ * HDB_EntryOrAlias, which is expensive -- we could decode as a
+ * HDB_entry_alias instead and assume it's an entry if decoding fails...
+ */
+
+ code = hdb_principal2key(context, principal, &key);
+ if (code == 0)
+ code = db->hdb__get(context, db, key, &value);
+ if (code == 0) {
+ code = decode_HDB_EntryOrAlias(value.data, value.length, &eoa, NULL);
+ krb5_data_free(&value);
+ }
+ if (code == 0) {
+ is_alias = eoa.element == choice_HDB_EntryOrAlias_entry ? 0 : 1;
+ free_HDB_EntryOrAlias(&eoa);
+ }
+
+ if ((flags & HDB_F_PRECHECK)) {
+ if (code == 0 && is_alias)
+ krb5_set_error_message(context, code = HDB_ERR_NOENTRY,
+ "Cannot delete alias of principal");
+ krb5_data_free(&key);
+ return code;
+ }
+
+ if (code == 0)
+ code = hdb_remove_aliases(context, db, &key);
+ if (code == 0)
+ code = db->hdb__del(context, db, key);
+ krb5_data_free(&key);
+ return code;
+}
+
+/* PRF+(K_base, pad, keylen(etype)) */
+static krb5_error_code
+derive_Key1(krb5_context context,
+ krb5_data *pad,
+ EncryptionKey *base,
+ krb5int32 etype,
+ EncryptionKey *nk)
+{
+ krb5_error_code ret;
+ krb5_crypto crypto = NULL;
+ krb5_data out;
+ size_t len;
+
+ out.data = 0;
+ out.length = 0;
+
+ ret = krb5_enctype_keysize(context, base->keytype, &len);
+ if (ret == 0)
+ ret = krb5_crypto_init(context, base, 0, &crypto);
+ if (ret == 0)
+ ret = krb5_crypto_prfplus(context, crypto, pad, len, &out);
+ if (crypto)
+ krb5_crypto_destroy(context, crypto);
+ if (ret == 0)
+ ret = krb5_random_to_key(context, etype, out.data, out.length, nk);
+ krb5_data_free(&out);
+ return ret;
+}
+
+/* PRF+(PRF+(K_base, princ, keylen(etype)), kvno, keylen(etype)) */
+/* XXX Make it PRF+(PRF+(K_base, princ, keylen(K_base.etype)), and lift it, kvno, keylen(etype)) */
+static krb5_error_code
+derive_Key(krb5_context context,
+ const char *princ,
+ krb5uint32 kvno,
+ EncryptionKey *base,
+ krb5int32 etype,
+ Key *nk)
+{
+ krb5_error_code ret = 0;
+ EncryptionKey intermediate;
+ krb5_data pad;
+
+ nk->salt = NULL;
+ nk->mkvno = NULL;
+ nk->key.keytype = 0;
+ nk->key.keyvalue.data = 0;
+ nk->key.keyvalue.length = 0;
+
+ intermediate.keytype = 0;
+ intermediate.keyvalue.data = 0;
+ intermediate.keyvalue.length = 0;
+ if (princ) {
+ /* Derive intermediate key for the given principal */
+ /* XXX Lift to optimize? */
+ pad.data = (void *)(uintptr_t)princ;
+ pad.length = strlen(princ);
+ ret = derive_Key1(context, &pad, base, etype, &intermediate);
+ if (ret == 0)
+ base = &intermediate;
+ } /* else `base' is already an intermediate key for the desired princ */
+
+ /* Derive final key for `kvno' from intermediate key */
+ kvno = htonl(kvno);
+ pad.data = &kvno;
+ pad.length = sizeof(kvno);
+ if (ret == 0)
+ ret = derive_Key1(context, &pad, base, etype, &nk->key);
+ free_EncryptionKey(&intermediate);
+ return ret;
+}
+
+/*
+ * PRF+(PRF+(K_base, princ, keylen(etype)), kvno, keylen(etype)) for one
+ * enctype.
+ */
+static krb5_error_code
+derive_Keys(krb5_context context,
+ const char *princ,
+ krb5uint32 kvno,
+ krb5int32 etype,
+ const Keys *base,
+ Keys *dk)
+
+{
+ krb5_error_code ret = 0;
+ size_t i;
+ Key nk;
+
+ dk->len = 0;
+ dk->val = 0;
+
+ /*
+ * The enctypes of the base keys is the list of enctypes to derive keys
+ * for. Still, we derive all keys from the first base key.
+ */
+ for (i = 0; ret == 0 && i < base->len; i++) {
+ if (etype != KRB5_ENCTYPE_NULL && etype != base->val[i].key.keytype)
+ continue;
+ ret = derive_Key(context, princ, kvno, &base->val[0].key,
+ base->val[i].key.keytype, &nk);
+ if (ret)
+ break;
+ ret = add_Keys(dk, &nk);
+ free_Key(&nk);
+ /*
+ * FIXME We need to finish kdc/kadm5/kadmin support for the `etypes' so
+ * we can reduce the number of keys in keytabs to just those in current
+ * use and only of *one* enctype.
+ *
+ * What we could do is derive *one* key and for the others output a
+ * one-byte key of the intended enctype (which will never work).
+ *
+ * We'll never need any keys but the first one...
+ */
+ }
+
+ if (ret)
+ free_Keys(dk);
+ return ret;
+}
+
+/* Helper for derive_keys_for_kr() */
+static krb5_error_code
+derive_keyset(krb5_context context,
+ const Keys *base_keys,
+ const char *princ,
+ krb5int32 etype,
+ krb5uint32 kvno,
+ KerberosTime set_time, /* "now" */
+ hdb_keyset *dks)
+{
+ dks->kvno = kvno;
+ dks->keys.val = 0;
+ dks->set_time = malloc(sizeof(*(dks->set_time)));
+ if (dks->set_time == NULL)
+ return krb5_enomem(context);
+ *dks->set_time = set_time;
+ return derive_Keys(context, princ, kvno, etype, base_keys, &dks->keys);
+}
+
+/* Possibly derive and install in `h' a keyset identified by `t' */
+static krb5_error_code
+derive_keys_for_kr(krb5_context context,
+ hdb_entry *h,
+ HDB_Ext_KeySet *base_keys,
+ int is_current_keyset,
+ int rotation_period_offset,
+ const char *princ,
+ krb5int32 etype,
+ krb5uint32 kvno_wanted,
+ KerberosTime t,
+ struct KeyRotation *krp)
+{
+ krb5_error_code ret;
+ hdb_keyset dks;
+ KerberosTime set_time, n;
+ krb5uint32 kvno;
+ size_t i;
+
+ if (rotation_period_offset < -1 || rotation_period_offset > 1)
+ return EINVAL; /* wat */
+
+ /*
+ * Compute `kvno' and `set_time' given `t' and `krp'.
+ *
+ * There be signed 32-bit time_t dragons here.
+ *
+ * (t - krp->epoch < 0) is better than (krp->epoch < t), making us more
+ * tolerant of signed 32-bit time_t here near 2038. Of course, we have
+ * signed 32-bit time_t dragons elsewhere.
+ */
+ if (t - krp->epoch < 0)
+ return 0; /* This KR is not relevant yet */
+ n = (t - krp->epoch) / krp->period;
+ n += rotation_period_offset;
+ set_time = krp->epoch + krp->period * n;
+ kvno = krp->base_kvno + n;
+
+
+ /*
+ * Do not waste cycles computing keys not wanted or needed.
+ * A past kvno is too old if its set_time + rotation period is in the past
+ * by more than half a rotation period, since then no service ticket
+ * encrypted with keys of that kvno can still be extant.
+ *
+ * A future kvno is not coming up soon enough if we're more than a quarter
+ * of the rotation period away from it.
+ *
+ * Recall: the assumption for virtually-keyed principals is that services
+ * fetch their future keys frequently enough that they'll never miss having
+ * the keys they need.
+ */
+ if (!is_current_keyset || rotation_period_offset != 0) {
+ if ((kvno_wanted && kvno != kvno_wanted) ||
+ t - (set_time + krp->period + (krp->period >> 1)) > 0 ||
+ (set_time - t > 0 && (set_time - t) > (krp->period >> 2)))
+ return 0;
+ }
+
+ for (i = 0; i < base_keys->len; i++) {
+ if (base_keys->val[i].kvno == krp->base_key_kvno)
+ break;
+ }
+ if (i == base_keys->len) {
+ /* Base key not found! */
+ if (kvno_wanted || is_current_keyset) {
+ krb5_set_error_message(context, ret = HDB_ERR_KVNO_NOT_FOUND,
+ "Base key version %u not found for %s",
+ krp->base_key_kvno, princ);
+ return ret;
+ }
+ return 0;
+ }
+
+ ret = derive_keyset(context, &base_keys->val[i].keys, princ, etype, kvno,
+ set_time, &dks);
+ if (ret == 0)
+ ret = hdb_install_keyset(context, h, is_current_keyset, &dks);
+
+ free_HDB_keyset(&dks);
+ return ret;
+}
+
+/* Derive and install current keys, and possibly preceding or next keys */
+static krb5_error_code
+derive_keys_for_current_kr(krb5_context context,
+ hdb_entry *h,
+ HDB_Ext_KeySet *base_keys,
+ const char *princ,
+ unsigned int flags,
+ krb5int32 etype,
+ krb5uint32 kvno_wanted,
+ KerberosTime t,
+ struct KeyRotation *krp,
+ KerberosTime future_epoch)
+{
+ krb5_error_code ret;
+
+ /* derive_keys_for_kr() for current kvno and install as the current keys */
+ ret = derive_keys_for_kr(context, h, base_keys, 1, 0, princ, etype,
+ kvno_wanted, t, krp);
+ if (!(flags & HDB_F_ALL_KVNOS))
+ return ret;
+
+ /* */
+
+
+ /*
+ * derive_keys_for_kr() for prev kvno if still needed -- it can only be
+ * needed if the prev kvno's start time is within this KR's epoch.
+ *
+ * Note that derive_keys_for_kr() can return without doing anything if this
+ * is isn't the current keyset. So these conditions need not be
+ * sufficiently narrow.
+ */
+ if (ret == 0 && t - krp->epoch >= krp->period)
+ ret = derive_keys_for_kr(context, h, base_keys, 0, -1, princ, etype,
+ kvno_wanted, t, krp);
+ /*
+ * derive_keys_for_kr() for next kvno if near enough, but only if it
+ * doesn't start after the next KR's epoch.
+ */
+ if (future_epoch &&
+ t - krp->epoch >= 0 /* We know! Hint to the compiler */) {
+ KerberosTime next_kvno_start, n;
+
+ n = (t - krp->epoch) / krp->period;
+ next_kvno_start = krp->epoch + krp->period * (n + 1);
+ if (future_epoch - next_kvno_start <= 0)
+ return ret;
+ }
+ if (ret == 0)
+ ret = derive_keys_for_kr(context, h, base_keys, 0, 1, princ, etype,
+ kvno_wanted, t, krp);
+ return ret;
+}
+
+/*
+ * Derive and install all keysets in `h' that `princ' needs at time `now'.
+ *
+ * This mutates the entry `h' to
+ *
+ * a) not have base keys,
+ * b) have keys derived from the base keys according to
+ * c) the key rotation periods for the base principal (possibly the same
+ * principal if it's a concrete principal with virtual keys), and the
+ * requested time, enctype, and kvno (all of which are optional, with zero
+ * implying some default).
+ *
+ * Arguments:
+ *
+ * - `flags' is the flags passed to `hdb_fetch_kvno()'
+ * - `princ' is the name of the principal we'll end up with in `entry'
+ * - `h_is_namespace' indicates whether `h' is for a namespace or a concrete
+ * principal (that might nonetheless have virtual/derived keys)
+ * - `t' is the time such that the derived keys are for kvnos needed at `t'
+ * - `etype' indicates what enctype to derive keys for (0 for all enctypes in
+ * `entry->etypes')
+ * - `kvno' requests a particular kvno, or all if zero
+ *
+ * The caller doesn't know if the principal needs key derivation -- we make
+ * that determination in this function.
+ *
+ * Note that this function is fully deterministic for any given set of
+ * arguments and HDB contents.
+ *
+ * Definitions:
+ *
+ * - A keyset is a set of keys for a single kvno.
+ * - A keyset is relevant IFF:
+ * - it is the keyset for a time period identified by `t' in a
+ * corresponding KR
+ * - it is a keyset for a past time period for which there may be extant,
+ * not-yet-expired tickets that a service may need to decrypt
+ * - it is a keyset for an upcoming time period that a service will need to
+ * fetch before that time period becomes current, that way the service
+ * can have keytab entries for those keys in time for when the KDC starts
+ * encrypting service tickets to those keys
+ *
+ * This function derives the keyset(s) for the current KR first. The idea is
+ * to optimize the order of resulting keytabs so that the most likely keys to
+ * be used come first.
+ *
+ * Invariants:
+ *
+ * - KR metadata is sane because sanity is checked for when storing HDB
+ * entries
+ * - KRs are sorted by epoch in descending order; KR #0's epoch is the most
+ * recent
+ * - KR periods are non-zero (we divide by period)
+ * - kvnos are numerically ordered and correspond to time periods
+ * - within each KR, the kvnos for larger times are larger than (or equal
+ * to) the kvnos of earlier times
+ * - at KR boundaries, the first kvno of the newer boundary is larger than
+ * the kvno of the last time period of the previous KR
+ * - the time `t' must fall into exactly one KR period
+ * - the time `t' must fall into exactly one period within a KR period
+ * - at most two kvnos will be relevant from the KR that `t' falls into
+ * (the current kvno for `t', and possibly either the preceding, or the
+ * next)
+ * - at most one kvno from non-current KRs will be derived: possibly one for a
+ * preceding KR, and possibly one from an upcoming KR
+ *
+ * There can be:
+ *
+ * - no KR extension (not a namespace principal, and no virtual keys)
+ * - 1, 2, or 3 KRs (see above)
+ * - the newest KR may have the `deleted' flag, meaning "does not exist after
+ * this epoch"
+ *
+ * Note that the last time period in any older KR can be partial.
+ *
+ * Timeline diagram:
+ *
+ * .......|--+--+...+--|---+---+---+...+--|----+...
+ * T20 T10 T11 RT12 T1n T01
+ * ^ ^ ^ ^ ^ ^ ^ T00
+ * | | | T22 T2n | | ^
+ * ^ | T21 | | |
+ * princ | | epoch of | epoch of
+ * did | | middle KR | newest epoch
+ * not | | |
+ * exist! | start of Note that T1n
+ * | second kvno is shown as shorter
+ * | in 1st epoch than preceding periods
+ * |
+ * ^
+ * first KR's
+ * epoch, and start
+ * of its first kvno
+ *
+ * Tmn == the start of the Mth KR's Nth time period.
+ * (higher M -> older KR; lower M -> newer KR)
+ * (N is the reverse: lower N -> older time period in KR)
+ * T20 == start of oldest KR -- no keys before this time will be derived.
+ * T2n == last time period in oldest KR
+ * T10 == start of middle KR
+ * T1n == last time period in middle KR
+ * T00 == start of newest KR
+ * T0n == current time period in newest KR for wall clock time
+ */
+static krb5_error_code
+derive_keys(krb5_context context,
+ unsigned flags,
+ krb5_const_principal princ,
+ int h_is_namespace,
+ krb5_timestamp t,
+ krb5int32 etype,
+ krb5uint32 kvno,
+ hdb_entry *h)
+{
+ HDB_Ext_KeyRotation kr;
+ HDB_Ext_KeySet base_keys;
+ krb5_error_code ret = 0;
+ size_t current_kr, future_kr, past_kr, i;
+ char *p = NULL;
+ int valid = 1;
+
+ if (!h_is_namespace && !h->flags.virtual_keys)
+ return 0;
+ h->flags.virtual = 1;
+
+ kr.len = 0;
+ kr.val = 0;
+ if (ret == 0) {
+ const HDB_Ext_KeyRotation *ckr;
+
+ /* Installing keys invalidates `ckr', so we copy it */
+ ret = hdb_entry_get_key_rotation(context, h, &ckr);
+ if (!ckr)
+ return ret;
+ if (ret == 0)
+ ret = copy_HDB_Ext_KeyRotation(ckr, &kr);
+ }
+
+ /* Get the base keys from the entry, and remove them */
+ base_keys.val = 0;
+ base_keys.len = 0;
+ if (ret == 0)
+ ret = _hdb_remove_base_keys(context, h, &base_keys, &kr);
+
+ /* Make sure we have h->etypes */
+ if (ret == 0 && !h->etypes)
+ ret = hdb_derive_etypes(context, h, &base_keys);
+
+ /* Keys not desired? Don't derive them! */
+ if (ret || !(flags & HDB_F_DECRYPT)) {
+ free_HDB_Ext_KeyRotation(&kr);
+ free_HDB_Ext_KeySet(&base_keys);
+ return ret;
+ }
+
+ /* The principal name will be used in key derivation and error messages */
+ if (ret == 0)
+ ret = krb5_unparse_name(context, princ, &p);
+
+ /* Sanity check key rotations, determine current & last kr */
+ if (ret == 0 && kr.len < 1)
+ krb5_set_error_message(context, ret = HDB_ERR_NOENTRY,
+ "no key rotation periods for %s", p);
+ if (ret == 0)
+ current_kr = future_kr = past_kr = kr.len;
+ else
+ current_kr = future_kr = past_kr = 1;
+
+ /*
+ * Identify a current, next, and previous KRs if there are any.
+ *
+ * There can be up to three KRs, ordered by epoch, descending, making up a
+ * timeline like:
+ *
+ * ...|---------|--------|------>
+ * ^ | | |
+ * | | | |
+ * | | | Newest KR (kr.val[0])
+ * | | Middle KR (kr.val[1])
+ * | Oldest (last) KR (kr.val[2])
+ * |
+ * Before the begging of time for this namespace
+ *
+ * We step through these from future towards past looking for the best
+ * future, current, and past KRs. The best current KR is one that has its
+ * epoch nearest to `t' but in the past of `t'.
+ *
+ * We validate KRs before storing HDB entries with the KR extension, so we
+ * can assume they are valid here. However, we do some validity checking,
+ * and if they're not valid, we pick the best current KR and ignore the
+ * others.
+ *
+ * In principle there cannot be two future KRs, but this function is
+ * deterministic and takes a time value, so it should not enforce this just
+ * so we can test. Enforcement of such rules should be done at store time.
+ */
+ for (i = 0; ret == 0 && i < kr.len; i++) {
+ /* Minimal validation: order and period */
+ if (i && kr.val[i - 1].epoch - kr.val[i].epoch <= 0) {
+ future_kr = past_kr = kr.len;
+ valid = 0;
+ }
+ if (!kr.val[i].period) {
+ future_kr = past_kr = kr.len;
+ valid = 0;
+ continue;
+ }
+ if (t - kr.val[i].epoch >= 0) {
+ /*
+ * `t' is in the future of this KR's epoch, so it's a candidate for
+ * either current or past KR.
+ */
+ if (current_kr == kr.len)
+ current_kr = i; /* First curr KR candidate; should be best */
+ else if (kr.val[current_kr].epoch - kr.val[i].epoch < 0)
+ current_kr = i; /* Invalid KRs, but better curr KR cand. */
+ else if (valid && past_kr == kr.len)
+ past_kr = i;
+ } else if (valid) {
+ /* This KR is in the future of `t', a candidate for next KR */
+ future_kr = i;
+ }
+ }
+ if (ret == 0 && current_kr == kr.len)
+ /* No current KR -> too soon */
+ krb5_set_error_message(context, ret = HDB_ERR_NOENTRY,
+ "Too soon for virtual principal to exist");
+
+ /* Check that the principal has not been marked deleted */
+ if (ret == 0 && current_kr < kr.len && kr.val[current_kr].flags.deleted)
+ krb5_set_error_message(context, ret = HDB_ERR_NOENTRY,
+ "virtual principal %s does not exist "
+ "because last key rotation period "
+ "marks deletion", p);
+
+ /*
+ * Derive and set in `h' its current kvno and current keys.
+ *
+ * This will set h->kvno as well.
+ *
+ * This may set up to TWO keysets for the current key rotation period:
+ * - current keys (h->keys and h->kvno)
+ * - possibly one future
+ * OR
+ * possibly one past keyset in hist_keys for the current_kr
+ */
+ if (ret == 0 && current_kr < kr.len)
+ ret = derive_keys_for_current_kr(context, h, &base_keys, p, flags,
+ etype, kvno, t, &kr.val[current_kr],
+ current_kr ? kr.val[0].epoch : 0);
+
+ /*
+ * Derive and set in `h' its future keys for next KR if it is soon to be
+ * current.
+ *
+ * We want to derive keys for the first kvno of the next (future) KR if
+ * it's sufficiently close to `t', meaning within 1 period of the current
+ * KR, but we want these keys to be available sooner, so 1.5 of the current
+ * period.
+ */
+ if (ret == 0 && future_kr < kr.len && (flags & HDB_F_ALL_KVNOS))
+ ret = derive_keys_for_kr(context, h, &base_keys, 0, 0, p, etype, kvno,
+ kr.val[future_kr].epoch, &kr.val[future_kr]);
+
+ /*
+ * Derive and set in `h' its past keys for the previous KR if its last time
+ * period could still have extant, unexpired service tickets encrypted in
+ * its keys.
+ */
+ if (ret == 0 && past_kr < kr.len && (flags & HDB_F_ALL_KVNOS))
+ ret = derive_keys_for_kr(context, h, &base_keys, 0, 0, p, etype, kvno,
+ kr.val[current_kr].epoch - 1, &kr.val[past_kr]);
+
+ /*
+ * Impose a bound on h->max_life so that [when the KDC is the caller]
+ * the KDC won't issue tickets longer lived than this.
+ */
+ if (ret == 0 && !h->max_life &&
+ (h->max_life = calloc(1, sizeof(h->max_life[0]))) == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0 && *h->max_life > kr.val[current_kr].period >> 1)
+ *h->max_life = kr.val[current_kr].period >> 1;
+
+ free_HDB_Ext_KeyRotation(&kr);
+ free_HDB_Ext_KeySet(&base_keys);
+ free(p);
+ return ret;
+}
+
+/*
+ * Pick a best kvno for the given principal at the given time.
+ *
+ * Implements the [hdb] new_service_key_delay configuration parameter.
+ *
+ * In order for disparate keytab provisioning systems such as OSKT and our own
+ * kadmin ext_keytab and httpkadmind's get-keys to coexist, we need to be able
+ * to force keys set by the former to not become current keys until users of
+ * the latter have had a chance to fetch those keys into their keytabs. To do
+ * this we have to search the list of keys in the entry looking for the newest
+ * keys older than `now - db->new_service_key_delay'.
+ *
+ * The context is that OSKT's krb5_keytab is very happy to change keys in a way
+ * that requires all members of a cluster to rekey together. If one also
+ * wishes to have cluster members that opt out of this and just fetch current,
+ * past, and future keys periodically, then the keys set by OSKT must not come
+ * into effect until all the opt-out members have had a chance to fetch the new
+ * keys.
+ *
+ * The assumption is that services will fetch new keys periodically, say, every
+ * four hours. Then one can set `[hdb] new_service_key_delay = 8h' in the
+ * configuration and new keys set by OSKT will not be used until 8h after they
+ * are set.
+ *
+ * Naturally, this applies only to concrete principals with concrete keys.
+ */
+static krb5_error_code
+pick_kvno(krb5_context context,
+ HDB *db,
+ unsigned flags,
+ krb5_timestamp now,
+ krb5uint32 kvno,
+ hdb_entry *h)
+{
+ HDB_extension *ext;
+ HDB_Ext_KeySet keys;
+ time_t current = 0;
+ time_t best;
+ size_t i;
+
+ /*
+ * If we want a specific kvno, or if the caller doesn't want new keys
+ * delayed, or if there's no new-key delay configured, or we're not
+ * fetching for use as a service principal, then we're out.
+ */
+ if (!(flags & HDB_F_DELAY_NEW_KEYS) || kvno || h->flags.virtual ||
+ h->flags.virtual_keys || db->new_service_key_delay <= 0)
+ return 0;
+
+ /* No history -> current keyset is the only one and therefore the best */
+ ext = hdb_find_extension(h, choice_HDB_extension_data_hist_keys);
+ if (!ext)
+ return 0;
+
+ /* Assume the current keyset is the best to start with */
+ (void) hdb_entry_get_pw_change_time(h, &current);
+ if (current == 0 && h->modified_by)
+ current = h->modified_by->time;
+ if (current == 0)
+ current = h->created_by.time;
+
+ /* Current keyset starts out as best */
+ best = current;
+ kvno = h->kvno;
+
+ /* Look for a better keyset in the history */
+ keys = ext->data.u.hist_keys;
+ for (i = 0; i < keys.len; i++) {
+ /* No set_time? Ignore. Too new? Ignore */
+ if (!keys.val[i].set_time ||
+ keys.val[i].set_time[0] + db->new_service_key_delay > now)
+ continue;
+
+ /*
+ * Ignore the keyset with kvno 1 when the entry has better kvnos
+ * because kadmin's `ank -r' command immediately changes the keys.
+ */
+ if (kvno > 1 && keys.val[i].kvno == 1)
+ continue;
+
+ /*
+ * This keyset's set_time older than the previous best? Ignore.
+ * However, if the current best is the entry's current and that one
+ * is too new, then don't ignore this one.
+ */
+ if (keys.val[i].set_time[0] < best &&
+ (best != current || current + db->new_service_key_delay < now))
+ continue;
+
+ /*
+ * If two good enough keysets have the same set_time, take the keyset
+ * with the highest kvno.
+ */
+ if (keys.val[i].set_time[0] == best && keys.val[i].kvno <= kvno)
+ continue;
+
+ /*
+ * This keyset is clearly more current than the previous best keyset
+ * but still old enough to use for encrypting tickets with.
+ */
+ best = keys.val[i].set_time[0];
+ kvno = keys.val[i].kvno;
+ }
+ return hdb_change_kvno(context, kvno, h);
+}
+
+/*
+ * Make a WELLKNOWN/HOSTBASED-NAMESPACE/${svc}/${hostname} or
+ * WELLKNOWN/HOSTBASED-NAMESPACE/${svc}/${hostname}/${domainname} principal
+ * object, with the service and hostname components take from `wanted', but if
+ * the service name is not in the list `db->virtual_hostbased_princ_svcs[]'
+ * then use "_" (wildcard) instead. This way we can have different attributes
+ * for different services in the same namespaces.
+ *
+ * For example, virtual hostbased service names for the "host" service might
+ * have ok-as-delegate set, but ones for the "HTTP" service might not.
+ */
+static krb5_error_code
+make_namespace_princ(krb5_context context,
+ HDB *db,
+ krb5_const_principal wanted,
+ krb5_principal *namespace)
+{
+ krb5_error_code ret = 0;
+ const char *realm = krb5_principal_get_realm(context, wanted);
+ const char *comp0 = krb5_principal_get_comp_string(context, wanted, 0);
+ const char *comp1 = krb5_principal_get_comp_string(context, wanted, 1);
+ const char *comp2 = krb5_principal_get_comp_string(context, wanted, 2);
+ char * const *svcs = db->virtual_hostbased_princ_svcs;
+ size_t i;
+
+ *namespace = NULL;
+ if (comp0 == NULL || comp1 == NULL)
+ return EINVAL;
+ if (strcmp(comp0, "krbtgt") == 0)
+ return 0;
+
+ for (i = 0; svcs && svcs[i]; i++) {
+ if (strcmp(comp0, svcs[i]) == 0) {
+ comp0 = svcs[i];
+ break;
+ }
+ }
+ if (!svcs || !svcs[i])
+ comp0 = "_";
+
+ /* First go around, need a namespace princ. Make it! */
+ ret = krb5_build_principal(context, namespace, strlen(realm),
+ realm, KRB5_WELLKNOWN_NAME,
+ HDB_WK_NAMESPACE, comp0, NULL);
+ if (ret == 0)
+ ret = krb5_principal_set_comp_string(context, *namespace, 3, comp1);
+ if (ret == 0 && comp2)
+ /* Support domain-based names */
+ ret = krb5_principal_set_comp_string(context, *namespace, 4, comp2);
+ /* Caller frees `*namespace' on error */
+ return ret;
+}
+
+static int
+is_namespace_princ_p(krb5_context context,
+ krb5_const_principal princ)
+{
+ return
+ krb5_principal_get_num_comp(context, princ) >= 4
+ && strcmp(krb5_principal_get_comp_string(context, princ, 0),
+ KRB5_WELLKNOWN_NAME) == 0
+ && strcmp(krb5_principal_get_comp_string(context, princ, 1),
+ HDB_WK_NAMESPACE) == 0;
+}
+
+/* See call site */
+static krb5_error_code
+rewrite_hostname(krb5_context context,
+ krb5_const_principal wanted_princ,
+ krb5_const_principal ns_princ,
+ krb5_const_principal found_ns_princ,
+ char **s)
+{
+ const char *ns_host_part, *wanted_host_part, *found_host_part;
+ const char *p, *r;
+ size_t ns_host_part_len, wanted_host_part_len;
+
+ wanted_host_part = krb5_principal_get_comp_string(context, wanted_princ, 1);
+ wanted_host_part_len = strlen(wanted_host_part);
+ if (wanted_host_part_len > 256) {
+ krb5_set_error_message(context, HDB_ERR_NOENTRY,
+ "Aliases of host-based principals longer than "
+ "256 bytes not supported");
+ return HDB_ERR_NOENTRY;
+ }
+
+ ns_host_part = krb5_principal_get_comp_string(context, ns_princ, 3);
+ ns_host_part_len = strlen(ns_host_part);
+
+ /* Find `ns_host_part' as the tail of `wanted_host_part' */
+ for (r = p = strstr(wanted_host_part, ns_host_part);
+ r && strnlen(r, ns_host_part_len + 1) > ns_host_part_len;
+ p = (r = strstr(r, ns_host_part)) ? r : p)
+ ;
+ if (!p || strnlen(p, ns_host_part_len + 1) != ns_host_part_len)
+ return HDB_ERR_NOENTRY; /* Can't happen */
+ if (p == wanted_host_part || p[-1] != '.')
+ return HDB_ERR_NOENTRY;
+
+ found_host_part =
+ krb5_principal_get_comp_string(context, found_ns_princ, 3);
+ return
+ asprintf(s, "%.*s%s", (int)(p - wanted_host_part), wanted_host_part,
+ found_host_part) < 0 ||
+ *s == NULL ? krb5_enomem(context) : 0;
+}
+
+/*
+ * Fix `h->principal' to match the desired `princ' in the namespace
+ * `nsprinc' (which is either the same as `h->principal' or an alias
+ * of it).
+ */
+static krb5_error_code
+fix_princ_name(krb5_context context,
+ krb5_const_principal princ,
+ krb5_const_principal nsprinc,
+ hdb_entry *h)
+{
+ krb5_error_code ret = 0;
+ char *s = NULL;
+
+ if (!nsprinc)
+ return 0;
+ if (krb5_principal_get_num_comp(context, princ) < 2)
+ return HDB_ERR_NOENTRY;
+
+ /* `nsprinc' must be a namespace principal */
+
+ if (krb5_principal_compare(context, nsprinc, h->principal)) {
+ /*
+ * `h' is the HDB entry for `nsprinc', and `nsprinc' is its canonical
+ * name.
+ *
+ * Set the entry's principal name to the desired name. The keys will
+ * be fixed next (upstairs, but don't forget to!).
+ */
+ free_Principal(h->principal);
+ return copy_Principal(princ, h->principal);
+ }
+
+ if (!is_namespace_princ_p(context, h->principal)) {
+ /*
+ * The alias is a namespace, but the canonical name is not. WAT.
+ *
+ * Well, the KDC will just issue a referral anyways, so we can leave
+ * `h->principal' as is...
+ *
+ * Remove all of `h's keys just in case, and leave
+ * `h->principal' as-is.
+ */
+ free_Keys(&h->keys);
+ (void) hdb_entry_clear_password(context, h);
+ return hdb_clear_extension(context, h,
+ choice_HDB_extension_data_hist_keys);
+ }
+
+ /*
+ * A namespace alias of a namespace entry.
+ *
+ * We'll want to rewrite the original principal accordingly.
+ *
+ * E.g., if the caller wanted host/foo.ns.test.h5l.se and we
+ * found WELLKNOWN/HOSTBASED-NAMESPACE/ns.test.h5l.se is an
+ * alias of WELLKNOWN/HOSTBASED-NAMESPACE/ns.example.org, then
+ * we'll want to treat host/foo.ns.test.h5l.se as an alias of
+ * host/foo.ns.example.org.
+ */
+ if (krb5_principal_get_num_comp(context, h->principal) !=
+ 2 + krb5_principal_get_num_comp(context, princ))
+ ret = HDB_ERR_NOENTRY; /* Only host-based services for now */
+ if (ret == 0)
+ ret = rewrite_hostname(context, princ, nsprinc, h->principal, &s);
+ if (ret == 0) {
+ krb5_free_principal(context, h->principal);
+ h->principal = NULL;
+ ret = krb5_make_principal(context, &h->principal,
+ krb5_principal_get_realm(context, princ),
+ krb5_principal_get_comp_string(context,
+ princ, 0),
+ s,
+ NULL);
+ }
+ return ret;
+}
+
+/* Wrapper around db->hdb_fetch_kvno() that implements virtual princs/keys */
+static krb5_error_code
+fetch_it(krb5_context context,
+ HDB *db,
+ krb5_const_principal princ,
+ unsigned flags,
+ krb5_timestamp t,
+ krb5int32 etype,
+ krb5uint32 kvno,
+ hdb_entry *ent)
+{
+ krb5_const_principal tmpprinc = princ;
+ krb5_principal nsprinc = NULL;
+ krb5_error_code ret = 0;
+ const char *comp0 = krb5_principal_get_comp_string(context, princ, 0);
+ const char *comp1 = krb5_principal_get_comp_string(context, princ, 1);
+ const char *tmp;
+ size_t mindots = db->virtual_hostbased_princ_ndots;
+ size_t maxdots = db->virtual_hostbased_princ_maxdots;
+ size_t hdots = 0;
+ char *host = NULL;
+ int do_search = 0;
+
+ if (!db->enable_virtual_hostbased_princs)
+ maxdots = mindots = 0;
+ if (db->enable_virtual_hostbased_princs && comp1 &&
+ strcmp("krbtgt", comp0) != 0 && strcmp(KRB5_WELLKNOWN_NAME, comp0) != 0) {
+ char *htmp;
+
+ if ((host = strdup(comp1)) == NULL)
+ return krb5_enomem(context);
+
+ /* Strip out any :port */
+ htmp = strchr(host, ':');
+ if (htmp) {
+ if (strchr(htmp + 1, ':')) {
+ /* Extra ':'s? No virtualization for you! */
+ free(host);
+ host = NULL;
+ htmp = NULL;
+ } else {
+ *htmp = '\0';
+ }
+ }
+ /* Count dots in `host' */
+ for (hdots = 0, htmp = host; htmp && *htmp; htmp++)
+ if (*htmp == '.')
+ hdots++;
+
+ do_search = 1;
+ }
+
+ tmp = host ? host : comp1;
+ for (ret = HDB_ERR_NOENTRY; ret == HDB_ERR_NOENTRY; tmpprinc = nsprinc) {
+ krb5_error_code ret2 = 0;
+
+ /*
+ * We break out of this loop with ret == 0 only if we found the HDB
+ * entry we were looking for or the HDB entry for a matching namespace.
+ *
+ * Otherwise we break out with ret != 0, typically HDB_ERR_NOENTRY.
+ *
+ * First time through we lookup the principal as given.
+ *
+ * Next we lookup a namespace principal, stripping off hostname labels
+ * from the left until we find one or get tired of looking or run out
+ * of labels.
+ */
+ ret = db->hdb_fetch_kvno(context, db, tmpprinc, flags, kvno, ent);
+ if (ret != HDB_ERR_NOENTRY || hdots == 0 || hdots < mindots || !tmp ||
+ !do_search)
+ break;
+
+ /*
+ * Breadcrumb:
+ *
+ * - if we found a concrete principal, but it's been marked
+ * as now-virtual, then we must keep going
+ *
+ * But this will be coded in the future.
+ *
+ * Maybe we can take attributes from the concrete principal...
+ */
+
+ /*
+ * The namespace's hostname will not have more labels than maxdots + 1.
+ * Thus we truncate immediately down to maxdots + 1 if we haven't yet.
+ *
+ * Example: with maxdots == 3,
+ * foo.bar.baz.app.blah.example -> baz.app.blah.example
+ */
+ while (maxdots && hdots > maxdots && tmp) {
+ tmp = strchr(tmp, '.');
+ /* tmp != NULL because maxdots > 0; we check to quiet linters */
+ if (tmp == NULL) {
+ ret = HDB_ERR_NOENTRY;
+ goto out;
+ }
+ tmp++;
+ hdots--;
+ }
+
+ if (nsprinc == NULL)
+ /* First go around, need a namespace princ. Make it! */
+ ret2 = make_namespace_princ(context, db, tmpprinc, &nsprinc);
+
+ /* Update the hostname component of the namespace principal */
+ if (ret2 == 0)
+ ret2 = krb5_principal_set_comp_string(context, nsprinc, 3, tmp);
+ if (ret2)
+ ret = ret2;
+
+ if (tmp) {
+ /* Strip off left-most label for the next go-around */
+ if ((tmp = strchr(tmp, '.')))
+ tmp++;
+ hdots--;
+ } /* else we'll break out after the next db->hdb_fetch_kvno() call */
+ }
+
+ /*
+ * If unencrypted keys were requested, derive them. There may not be any
+ * key derivation to do, but that's decided in derive_keys().
+ */
+ if (ret == 0) {
+ /* Fix the principal name if namespaced */
+ ret = fix_princ_name(context, princ, nsprinc, ent);
+
+ /* Derive keys if namespaced or virtual */
+ if (ret == 0)
+ ret = derive_keys(context, flags, princ, !!nsprinc, t, etype, kvno,
+ ent);
+ /* Pick the best kvno for this principal at the given time */
+ if (ret == 0)
+ ret = pick_kvno(context, db, flags, t, kvno, ent);
+ }
+
+out:
+ if (ret != 0 && ret != HDB_ERR_WRONG_REALM)
+ hdb_free_entry(context, db, ent);
+ krb5_free_principal(context, nsprinc);
+ free(host);
+ return ret;
+}
+
+/**
+ * Fetch a principal's HDB entry, possibly generating virtual keys from base
+ * keys according to strict key rotation schedules. If a time is given, other
+ * than HDB I/O, this function is pure, thus usable for testing.
+ *
+ * HDB writers should use `db->hdb_fetch_kvno()' to avoid materializing virtual
+ * principals.
+ *
+ * HDB readers should use this function rather than `db->hdb_fetch_kvno()'
+ * unless they only want to see concrete principals and not bother generating
+ * any virtual keys.
+ *
+ * @param context Context
+ * @param db HDB
+ * @param principal Principal name
+ * @param flags Fetch flags
+ * @param t For virtual keys, use this as the point in time (use zero to mean "now")
+ * @param etype Key enctype (use KRB5_ENCTYPE_NULL to mean "preferred")
+ * @param kvno Key version number (use zero to mean "current")
+ * @param h Output HDB entry
+ *
+ * @return Zero on success, an error code otherwise.
+ */
+krb5_error_code
+hdb_fetch_kvno(krb5_context context,
+ HDB *db,
+ krb5_const_principal principal,
+ unsigned int flags,
+ krb5_timestamp t,
+ krb5int32 etype,
+ krb5uint32 kvno,
+ hdb_entry *h)
+{
+ krb5_error_code ret = HDB_ERR_NOENTRY;
+
+ flags |= kvno ? HDB_F_KVNO_SPECIFIED : 0; /* XXX is this needed */
+ if (t == 0)
+ krb5_timeofday(context, &t);
+ ret = fetch_it(context, db, principal, flags, t, etype, kvno, h);
+ if (ret == HDB_ERR_NOENTRY)
+ krb5_set_error_message(context, ret, "no such entry found in hdb");
+
+ /*
+ * This check is to support aliases in HDB; the force_canonicalize
+ * check is to allow HDB backends to support realm name canon
+ * independently of principal aliases (used by Samba).
+ */
+ if (ret == 0 && !(flags & HDB_F_ADMIN_DATA) &&
+ !h->flags.force_canonicalize &&
+ !krb5_realm_compare(context, principal, h->principal))
+ ret = HDB_ERR_WRONG_REALM;
+ return ret;
+}
+
+size_t ASN1CALL
+length_hdb_keyset(HDB_keyset *data)
+{
+ return length_HDB_keyset(data);
+}
+
+size_t ASN1CALL
+length_hdb_entry(HDB_entry *data)
+{
+ return length_HDB_entry(data);
+}
+
+size_t ASN1CALL
+length_hdb_entry_alias(HDB_entry_alias *data)
+{
+ return length_HDB_entry_alias(data);
+}
+
+void ASN1CALL
+free_hdb_keyset(HDB_keyset *data)
+{
+ free_HDB_keyset(data);
+}
+
+void ASN1CALL
+free_hdb_entry(HDB_entry *data)
+{
+ free_HDB_entry(data);
+}
+
+void ASN1CALL
+free_hdb_entry_alias(HDB_entry_alias *data)
+{
+ free_HDB_entry_alias(data);
+}
+
+size_t ASN1CALL
+copy_hdb_keyset(const HDB_keyset *from, HDB_keyset *to)
+{
+ return copy_HDB_keyset(from, to);
+}
+
+size_t ASN1CALL
+copy_hdb_entry(const HDB_entry *from, HDB_entry *to)
+{
+ return copy_HDB_entry(from, to);
+}
+
+size_t ASN1CALL
+copy_hdb_entry_alias(const HDB_entry_alias *from, HDB_entry_alias *to)
+{
+ return copy_HDB_entry_alias(from, to);
+}
+
+int ASN1CALL
+decode_hdb_keyset(const unsigned char *p,
+ size_t len,
+ HDB_keyset *data,
+ size_t *size)
+{
+ return decode_HDB_keyset(p, len, data, size);
+}
+
+int ASN1CALL
+decode_hdb_entry(const unsigned char *p,
+ size_t len,
+ HDB_entry *data,
+ size_t *size)
+{
+ return decode_HDB_entry(p, len, data, size);
+}
+
+int ASN1CALL
+decode_hdb_entry_alias(const unsigned char *p,
+ size_t len,
+ HDB_entry_alias *data,
+ size_t *size)
+{
+ return decode_HDB_entry_alias(p, len, data, size);
+}
+
+int ASN1CALL
+encode_hdb_keyset(unsigned char *p,
+ size_t len,
+ const HDB_keyset *data,
+ size_t *size)
+{
+ return encode_HDB_keyset(p, len, data, size);
+}
+
+int ASN1CALL
+encode_hdb_entry(unsigned char *p,
+ size_t len,
+ const HDB_entry *data,
+ size_t *size)
+{
+ return encode_HDB_entry(p, len, data, size);
+}
+
+int ASN1CALL
+encode_hdb_entry_alias(unsigned char *p,
+ size_t len,
+ const HDB_entry_alias *data,
+ size_t *size)
+{
+ return encode_HDB_entry_alias(p, len, data, size);
+}
diff --git a/third_party/heimdal/lib/hdb/data-mkey.mit.des3.be b/third_party/heimdal/lib/hdb/data-mkey.mit.des3.be
new file mode 100644
index 0000000..4278ed3
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/data-mkey.mit.des3.be
Binary files differ
diff --git a/third_party/heimdal/lib/hdb/data-mkey.mit.des3.le b/third_party/heimdal/lib/hdb/data-mkey.mit.des3.le
new file mode 100644
index 0000000..19fdc93
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/data-mkey.mit.des3.le
Binary files differ
diff --git a/third_party/heimdal/lib/hdb/db.c b/third_party/heimdal/lib/hdb/db.c
new file mode 100644
index 0000000..5fcce7b
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/db.c
@@ -0,0 +1,391 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hdb_locl.h"
+
+#if defined(HAVE_DB1)
+
+#if defined(HAVE_DB_185_H)
+#include <db_185.h>
+#elif defined(HAVE_DB_H)
+#include <db.h>
+#endif
+
+typedef struct {
+ HDB hdb; /* generic members */
+ int lock_fd; /* DB-specific */
+ int do_sync; /* DB-specific */
+} DB1_HDB;
+
+static krb5_error_code
+DB_close(krb5_context context, HDB *db)
+{
+ DB1_HDB *db1 = (DB1_HDB *)db;
+ DB *d = (DB*)db->hdb_db;
+
+ heim_assert(d != 0, "Closing already closed HDB");
+
+ (*d->close)(d);
+ db->hdb_db = 0;
+
+ if (db1->lock_fd >= 0) {
+ close(db1->lock_fd);
+ db1->lock_fd = -1;
+ }
+
+ return 0;
+}
+
+static krb5_error_code
+DB_destroy(krb5_context context, HDB *db)
+{
+ krb5_error_code ret;
+
+ ret = hdb_clear_master_key(context, db);
+ krb5_config_free_strings(db->virtual_hostbased_princ_svcs);
+ free(db->hdb_name);
+ free(db);
+ return ret;
+}
+
+static krb5_error_code
+DB_set_sync(krb5_context context, HDB *db, int on)
+{
+ DB1_HDB *db1 = (DB1_HDB *)db;
+ DB *d = (DB*)db->hdb_db;
+ krb5_error_code ret = 0;
+
+ db1->do_sync = on;
+ if (on) {
+ ret = (*d->sync)(d, 0);
+ if (ret == -1) {
+ ret = errno;
+ krb5_set_error_message(context, ret, "Database %s put sync error: %s",
+ db->hdb_name, strerror(ret));
+ }
+ }
+ return ret;
+}
+
+static krb5_error_code
+DB_lock(krb5_context context, HDB *db, int operation)
+{
+
+ return 0;
+}
+
+static krb5_error_code
+DB_unlock(krb5_context context, HDB *db)
+{
+
+ return 0;
+}
+
+
+static krb5_error_code
+DB_seq(krb5_context context, HDB *db,
+ unsigned flags, hdb_entry *entry, int flag)
+{
+ DB *d = (DB*)db->hdb_db;
+ DBT key, value;
+ krb5_data key_data, data;
+ int code;
+
+ code = (*d->seq)(d, &key, &value, flag);
+ if(code == -1) {
+ code = errno;
+ krb5_set_error_message(context, code, "Database %s seq error: %s",
+ db->hdb_name, strerror(code));
+ return code;
+ }
+ if(code == 1) {
+ krb5_clear_error_message(context);
+ return HDB_ERR_NOENTRY;
+ }
+
+ key_data.data = key.data;
+ key_data.length = key.size;
+ data.data = value.data;
+ data.length = value.size;
+ memset(entry, 0, sizeof(*entry));
+ if (hdb_value2entry(context, &data, entry))
+ return DB_seq(context, db, flags, entry, R_NEXT);
+ if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) {
+ code = hdb_unseal_keys (context, db, entry);
+ if (code)
+ hdb_free_entry (context, db, entry);
+ }
+ if (code == 0 && entry->principal == NULL) {
+ entry->principal = malloc(sizeof(*entry->principal));
+ if (entry->principal == NULL) {
+ code = ENOMEM;
+ krb5_set_error_message(context, code, "malloc: out of memory");
+ hdb_free_entry (context, db, entry);
+ } else {
+ hdb_key2principal(context, &key_data, entry->principal);
+ }
+ }
+ return code;
+}
+
+
+static krb5_error_code
+DB_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
+{
+ return DB_seq(context, db, flags, entry, R_FIRST);
+}
+
+
+static krb5_error_code
+DB_nextkey(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
+{
+ return DB_seq(context, db, flags, entry, R_NEXT);
+}
+
+static krb5_error_code
+DB_rename(krb5_context context, HDB *db, const char *new_name)
+{
+ int ret;
+ char *old, *new;
+
+ if (strncmp(new_name, "db:", sizeof("db:") - 1) == 0)
+ new_name += sizeof("db:") - 1;
+ else if (strncmp(new_name, "db1:", sizeof("db1:") - 1) == 0)
+ new_name += sizeof("db1:") - 1;
+ asprintf(&old, "%s.db", db->hdb_name);
+ asprintf(&new, "%s.db", new_name);
+ ret = rename(old, new);
+ free(old);
+ free(new);
+ if(ret)
+ return errno;
+
+ free(db->hdb_name);
+ db->hdb_name = strdup(new_name);
+ return 0;
+}
+
+static krb5_error_code
+DB__get(krb5_context context, HDB *db, krb5_data key, krb5_data *reply)
+{
+ DB *d = (DB*)db->hdb_db;
+ DBT k, v;
+ int code;
+
+ k.data = key.data;
+ k.size = key.length;
+ code = (*d->get)(d, &k, &v, 0);
+ if(code < 0) {
+ code = errno;
+ krb5_set_error_message(context, code, "Database %s get error: %s",
+ db->hdb_name, strerror(code));
+ return code;
+ }
+ if(code == 1) {
+ krb5_clear_error_message(context);
+ return HDB_ERR_NOENTRY;
+ }
+
+ krb5_data_copy(reply, v.data, v.size);
+ return 0;
+}
+
+static krb5_error_code
+DB__put(krb5_context context, HDB *db, int replace,
+ krb5_data key, krb5_data value)
+{
+ DB1_HDB *db1 = (DB1_HDB *)db;
+ DB *d = (DB*)db->hdb_db;
+ DBT k, v;
+ int code;
+
+ k.data = key.data;
+ k.size = key.length;
+ v.data = value.data;
+ v.size = value.length;
+ krb5_clear_error_message(context);
+ code = (*d->put)(d, &k, &v, replace ? 0 : R_NOOVERWRITE);
+ if(code < 0) {
+ code = errno;
+ krb5_set_error_message(context, code, "Database %s put error: %s",
+ db->hdb_name, strerror(code));
+ return code;
+ }
+ if(code == 1) {
+ return HDB_ERR_EXISTS;
+ }
+
+ return db->hdb_set_sync(context, db, db1->do_sync);
+}
+
+static krb5_error_code
+DB__del(krb5_context context, HDB *db, krb5_data key)
+{
+ DB1_HDB *db1 = (DB1_HDB *)db;
+ DB *d = (DB*)db->hdb_db;
+ DBT k;
+ krb5_error_code code;
+ k.data = key.data;
+ k.size = key.length;
+ krb5_clear_error_message(context);
+ code = (*d->del)(d, &k, 0);
+ if (code == 1)
+ return HDB_ERR_NOENTRY;
+ if (code < 0) {
+ code = errno;
+ krb5_set_error_message(context, code, "Database %s del error: %s",
+ db->hdb_name, strerror(code));
+ return code;
+ }
+ return db->hdb_set_sync(context, db, db1->do_sync);
+}
+
+static DB *
+_open_db(char *fn, int flags, int mode, int *fd)
+{
+#ifndef O_EXLOCK
+ int op;
+ int ret;
+
+ *fd = open(fn, flags, mode);
+ if (*fd == -1)
+ return NULL;
+
+ if ((flags & O_ACCMODE) == O_RDONLY)
+ op = LOCK_SH;
+ else
+ op = LOCK_EX;
+
+ ret = flock(*fd, op);
+ if (ret == -1) {
+ int saved_errno;
+
+ saved_errno = errno;
+ close(*fd);
+ errno = saved_errno;
+ return NULL;
+ }
+#else
+ if ((flags & O_ACCMODE) == O_RDONLY)
+ flags |= O_SHLOCK;
+ else
+ flags |= O_EXLOCK;
+#endif
+
+ return dbopen(fn, flags, mode, DB_BTREE, NULL);
+}
+
+static krb5_error_code
+DB_open(krb5_context context, HDB *db, int flags, mode_t mode)
+{
+ DB1_HDB *db1 = (DB1_HDB *)db;
+ char *fn;
+ krb5_error_code ret;
+
+ asprintf(&fn, "%s.db", db->hdb_name);
+ if (fn == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ db->hdb_db = _open_db(fn, flags, mode, &db1->lock_fd);
+ free(fn);
+ /* try to open without .db extension */
+ if(db->hdb_db == NULL && errno == ENOENT)
+ db->hdb_db = _open_db(db->hdb_name, flags, mode, &db1->lock_fd);
+ if(db->hdb_db == NULL) {
+ krb5_set_error_message(context, errno, "dbopen (%s): %s",
+ db->hdb_name, strerror(errno));
+ return errno;
+ }
+ if((flags & O_ACCMODE) == O_RDONLY)
+ ret = hdb_check_db_format(context, db);
+ else
+ ret = hdb_init_db(context, db);
+ if(ret == HDB_ERR_NOENTRY) {
+ krb5_clear_error_message(context);
+ return 0;
+ }
+ if (ret) {
+ DB_close(context, db);
+ krb5_set_error_message(context, ret, "hdb_open: failed %s database %s",
+ (flags & O_ACCMODE) == O_RDONLY ?
+ "checking format of" : "initialize",
+ db->hdb_name);
+ }
+ return ret;
+}
+
+krb5_error_code
+hdb_db1_create(krb5_context context, HDB **db,
+ const char *filename)
+{
+ DB1_HDB **db1 = (DB1_HDB **)db;
+ *db = calloc(1, sizeof(**db1)); /* Allocate space for the larger db1 */
+ if (*db == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ (*db)->hdb_db = NULL;
+ (*db)->hdb_name = strdup(filename);
+ if ((*db)->hdb_name == NULL) {
+ free(*db);
+ *db = NULL;
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ (*db)->hdb_master_key_set = 0;
+ (*db)->hdb_openp = 0;
+ (*db)->hdb_capability_flags = HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL;
+ (*db)->hdb_open = DB_open;
+ (*db)->hdb_close = DB_close;
+ (*db)->hdb_fetch_kvno = _hdb_fetch_kvno;
+ (*db)->hdb_store = _hdb_store;
+ (*db)->hdb_remove = _hdb_remove;
+ (*db)->hdb_firstkey = DB_firstkey;
+ (*db)->hdb_nextkey= DB_nextkey;
+ (*db)->hdb_lock = DB_lock;
+ (*db)->hdb_unlock = DB_unlock;
+ (*db)->hdb_rename = DB_rename;
+ (*db)->hdb__get = DB__get;
+ (*db)->hdb__put = DB__put;
+ (*db)->hdb__del = DB__del;
+ (*db)->hdb_destroy = DB_destroy;
+ (*db)->hdb_set_sync = DB_set_sync;
+
+ (*db1)->lock_fd = -1;
+ (*db1)->do_sync = 1;
+ return 0;
+}
+
+#endif /* defined(HAVE_DB1) */
diff --git a/third_party/heimdal/lib/hdb/db3.c b/third_party/heimdal/lib/hdb/db3.c
new file mode 100644
index 0000000..9d0c0a9
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/db3.c
@@ -0,0 +1,495 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hdb_locl.h"
+
+#include <fcntl.h>
+
+#if HAVE_DB3
+
+#ifdef HAVE_DBHEADER
+#include <db.h>
+#elif HAVE_DB6_DB_H
+#include <db6/db.h>
+#elif HAVE_DB5_DB_H
+#include <db5/db.h>
+#elif HAVE_DB4_DB_H
+#include <db4/db.h>
+#elif HAVE_DB3_DB_H
+#include <db3/db.h>
+#else
+#include <db.h>
+#endif
+
+typedef struct {
+ HDB hdb; /* generic members */
+ int lock_fd; /* DB3-specific */
+ int do_sync; /* DB3-specific */
+} DB3_HDB;
+
+
+static krb5_error_code
+DB_close(krb5_context context, HDB *db)
+{
+ DB3_HDB *db3 = (DB3_HDB *)db;
+ DB *d = (DB*)db->hdb_db;
+ DBC *dbcp = (DBC*)db->hdb_dbc;
+
+ heim_assert(d != 0, "Closing already closed HDB");
+
+ if (dbcp != NULL)
+ dbcp->c_close(dbcp);
+ if (d != NULL)
+ d->close(d, 0);
+ if (db3->lock_fd >= 0)
+ close(db3->lock_fd);
+
+ db3->lock_fd = -1;
+ db->hdb_dbc = 0;
+ db->hdb_db = 0;
+
+ return 0;
+}
+
+static krb5_error_code
+DB_destroy(krb5_context context, HDB *db)
+{
+ krb5_error_code ret;
+
+ ret = hdb_clear_master_key(context, db);
+ krb5_config_free_strings(db->virtual_hostbased_princ_svcs);
+ free(db->hdb_name);
+ free(db);
+ return ret;
+}
+
+static krb5_error_code
+DB_set_sync(krb5_context context, HDB *db, int on)
+{
+ DB3_HDB *db3 = (DB3_HDB *)db;
+ DB *d = (DB*)db->hdb_db;
+ krb5_error_code ret = 0;
+
+ db3->do_sync = on;
+ if (on) {
+ ret = (*d->sync)(d, 0);
+ if (ret) {
+ if (ret == EACCES || ret == ENOSPC || ret == EINVAL) {
+ krb5_set_error_message(context, ret,
+ "Database %s put sync error: %s",
+ db->hdb_name, strerror(ret));
+ } else {
+ ret = HDB_ERR_UK_SERROR;
+ krb5_set_error_message(context, ret,
+ "Database %s put sync error: unknown (%d)",
+ db->hdb_name, ret);
+ }
+ }
+ }
+ return ret;
+}
+
+static krb5_error_code
+DB_lock(krb5_context context, HDB *db, int operation)
+{
+
+ return 0;
+}
+
+static krb5_error_code
+DB_unlock(krb5_context context, HDB *db)
+{
+
+ return 0;
+}
+
+
+static krb5_error_code
+DB_seq(krb5_context context, HDB *db,
+ unsigned flags, hdb_entry *entry, int flag)
+{
+ DBT key, value;
+ DBC *dbcp = db->hdb_dbc;
+ krb5_data key_data, data;
+ int code;
+
+ memset(&key, 0, sizeof(DBT));
+ memset(&value, 0, sizeof(DBT));
+ code = (*dbcp->c_get)(dbcp, &key, &value, flag);
+ if (code == DB_NOTFOUND)
+ return HDB_ERR_NOENTRY;
+ if (code)
+ return code;
+
+ key_data.data = key.data;
+ key_data.length = key.size;
+ data.data = value.data;
+ data.length = value.size;
+ memset(entry, 0, sizeof(*entry));
+ if (hdb_value2entry(context, &data, entry))
+ return DB_seq(context, db, flags, entry, DB_NEXT);
+ if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) {
+ code = hdb_unseal_keys (context, db, entry);
+ if (code)
+ hdb_free_entry (context, db, entry);
+ }
+ if (entry->principal == NULL) {
+ entry->principal = malloc(sizeof(*entry->principal));
+ if (entry->principal == NULL) {
+ hdb_free_entry (context, db, entry);
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ } else {
+ hdb_key2principal(context, &key_data, entry->principal);
+ }
+ }
+ return 0;
+}
+
+
+static krb5_error_code
+DB_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
+{
+ return DB_seq(context, db, flags, entry, DB_FIRST);
+}
+
+
+static krb5_error_code
+DB_nextkey(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
+{
+ return DB_seq(context, db, flags, entry, DB_NEXT);
+}
+
+static krb5_error_code
+DB_rename(krb5_context context, HDB *db, const char *new_name)
+{
+ int ret;
+ char *old, *new;
+
+ if (strncmp(new_name, "db:", sizeof("db:") - 1) == 0)
+ new_name += sizeof("db:") - 1;
+ else if (strncmp(new_name, "db3:", sizeof("db3:") - 1) == 0)
+ new_name += sizeof("db3:") - 1;
+
+ ret = asprintf(&old, "%s.db", db->hdb_name);
+ if (ret == -1)
+ return ENOMEM;
+ ret = asprintf(&new, "%s.db", new_name);
+ if (ret == -1) {
+ free(old);
+ return ENOMEM;
+ }
+ ret = rename(old, new);
+ free(old);
+ if(ret) {
+ free(new);
+ return errno;
+ }
+
+ free(db->hdb_name);
+ new[strlen(new) - 3] = '\0';
+ db->hdb_name = new;
+ return 0;
+}
+
+static krb5_error_code
+DB__get(krb5_context context, HDB *db, krb5_data key, krb5_data *reply)
+{
+ DB *d = (DB*)db->hdb_db;
+ DBT k, v;
+ int code;
+
+ memset(&k, 0, sizeof(DBT));
+ memset(&v, 0, sizeof(DBT));
+ k.data = key.data;
+ k.size = key.length;
+ k.flags = 0;
+ code = (*d->get)(d, NULL, &k, &v, 0);
+ if(code == DB_NOTFOUND)
+ return HDB_ERR_NOENTRY;
+ if(code)
+ return code;
+
+ krb5_data_copy(reply, v.data, v.size);
+ return 0;
+}
+
+static krb5_error_code
+DB__put(krb5_context context, HDB *db, int replace,
+ krb5_data key, krb5_data value)
+{
+ DB3_HDB *db3 = (DB3_HDB *)db;
+ DB *d = (DB*)db->hdb_db;
+ DBT k, v;
+ int code;
+
+ memset(&k, 0, sizeof(DBT));
+ memset(&v, 0, sizeof(DBT));
+ k.data = key.data;
+ k.size = key.length;
+ k.flags = 0;
+ v.data = value.data;
+ v.size = value.length;
+ v.flags = 0;
+ code = (*d->put)(d, NULL, &k, &v, replace ? 0 : DB_NOOVERWRITE);
+ if(code == DB_KEYEXIST)
+ return HDB_ERR_EXISTS;
+ if (code) {
+ /*
+ * Berkeley DB 3 and up have a terrible error reporting
+ * interface...
+ *
+ * DB->err() doesn't output a string.
+ * DB->set_errcall()'s callback function doesn't have a void *
+ * argument that can be used to place the error somewhere.
+ *
+ * The only thing we could do is fopen()/fdopen() a file, set it
+ * with DB->set_errfile(), then call DB->err(), then read the
+ * message from the file, unset it with DB->set_errfile(), close
+ * it and delete it. That's a lot of work... so we don't do it.
+ */
+ if (code == EACCES || code == ENOSPC || code == EINVAL) {
+ krb5_set_error_message(context, code,
+ "Database %s put error: %s",
+ db->hdb_name, strerror(code));
+ } else {
+ code = HDB_ERR_UK_SERROR;
+ krb5_set_error_message(context, code,
+ "Database %s put error: unknown (%d)",
+ db->hdb_name, code);
+ }
+ return code;
+ }
+ return db->hdb_set_sync(context, db, db3->do_sync);
+}
+
+static krb5_error_code
+DB__del(krb5_context context, HDB *db, krb5_data key)
+{
+ DB3_HDB *db3 = (DB3_HDB *)db;
+ DB *d = (DB*)db->hdb_db;
+ DBT k;
+ krb5_error_code code;
+ memset(&k, 0, sizeof(DBT));
+ k.data = key.data;
+ k.size = key.length;
+ k.flags = 0;
+ code = (*d->del)(d, NULL, &k, 0);
+ if(code == DB_NOTFOUND)
+ return HDB_ERR_NOENTRY;
+ if (code) {
+ if (code == EACCES || code == ENOSPC || code == EINVAL) {
+ krb5_set_error_message(context, code,
+ "Database %s del error: %s",
+ db->hdb_name, strerror(code));
+ } else {
+ code = HDB_ERR_UK_SERROR;
+ krb5_set_error_message(context, code,
+ "Database %s del error: unknown (%d)",
+ db->hdb_name, code);
+ }
+ return code;
+ }
+ return db->hdb_set_sync(context, db, db3->do_sync);
+}
+
+#define RD_CACHE_SZ 0x8000 /* Minimal read cache size */
+#define WR_CACHE_SZ 0x8000 /* Minimal write cache size */
+
+static int
+_open_db(DB *d, char *fn, int myflags, int flags, mode_t mode, int *fd)
+{
+ int ret;
+ int cache_size = (myflags & DB_RDONLY) ? RD_CACHE_SZ : WR_CACHE_SZ;
+
+ *fd = open(fn, flags, mode);
+
+ if (*fd == -1)
+ return errno;
+
+ /*
+ * Without DB_FCNTL_LOCKING, the DB library complains when initializing
+ * a database in an empty file. Since the database is our lock file,
+ * we create it before Berkeley DB does, so a new DB always starts empty.
+ */
+ myflags |= DB_FCNTL_LOCKING;
+
+ ret = flock(*fd, (myflags&DB_RDONLY) ? LOCK_SH : LOCK_EX);
+ if (ret == -1) {
+ ret = errno;
+ close(*fd);
+ *fd = -1;
+ return ret;
+ }
+
+ d->set_cachesize(d, 0, cache_size, 0);
+
+#if (DB_VERSION_MAJOR > 4) || ((DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR >= 1))
+ ret = (*d->open)(d, NULL, fn, NULL, DB_BTREE, myflags, mode);
+#else
+ ret = (*d->open)(d, fn, NULL, DB_BTREE, myflags, mode);
+#endif
+
+ if (ret != 0) {
+ close(*fd);
+ *fd = -1;
+ }
+
+ return ret;
+}
+
+static krb5_error_code
+DB_open(krb5_context context, HDB *db, int flags, mode_t mode)
+{
+ DB3_HDB *db3 = (DB3_HDB *)db;
+ DBC *dbc = NULL;
+ char *fn;
+ krb5_error_code ret;
+ DB *d;
+ int myflags = 0;
+ int aret;
+
+ heim_assert(db->hdb_db == 0, "Opening already open HDB");
+
+ if (flags & O_CREAT)
+ myflags |= DB_CREATE;
+
+ if (flags & O_EXCL)
+ myflags |= DB_EXCL;
+
+ if((flags & O_ACCMODE) == O_RDONLY)
+ myflags |= DB_RDONLY;
+
+ if (flags & O_TRUNC)
+ myflags |= DB_TRUNCATE;
+
+ aret = asprintf(&fn, "%s.db", db->hdb_name);
+ if (aret == -1) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ if (db_create(&d, NULL, 0) != 0) {
+ free(fn);
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ db->hdb_db = d;
+
+ /* From here on out always DB_close() before returning on error */
+
+ ret = _open_db(d, fn, myflags, flags, mode, &db3->lock_fd);
+ free(fn);
+ if (ret == ENOENT) {
+ /* try to open without .db extension */
+ ret = _open_db(d, db->hdb_name, myflags, flags, mode, &db3->lock_fd);
+ }
+
+ if (ret) {
+ DB_close(context, db);
+ krb5_set_error_message(context, ret, "opening %s: %s",
+ db->hdb_name, strerror(ret));
+ return ret;
+ }
+
+#ifndef DB_CURSOR_BULK
+# define DB_CURSOR_BULK 0 /* Missing with DB < 4.8 */
+#endif
+ ret = (*d->cursor)(d, NULL, &dbc, DB_CURSOR_BULK);
+
+ if (ret) {
+ DB_close(context, db);
+ krb5_set_error_message(context, ret, "d->cursor: %s", strerror(ret));
+ return ret;
+ }
+ db->hdb_dbc = dbc;
+
+ if((flags & O_ACCMODE) == O_RDONLY)
+ ret = hdb_check_db_format(context, db);
+ else
+ ret = hdb_init_db(context, db);
+ if(ret == HDB_ERR_NOENTRY)
+ return 0;
+ if (ret) {
+ DB_close(context, db);
+ krb5_set_error_message(context, ret, "hdb_open: failed %s database %s",
+ (flags & O_ACCMODE) == O_RDONLY ?
+ "checking format of" : "initialize",
+ db->hdb_name);
+ }
+
+ return ret;
+}
+
+krb5_error_code
+hdb_db3_create(krb5_context context, HDB **db,
+ const char *filename)
+{
+ DB3_HDB **db3 = (DB3_HDB **)db;
+ *db3 = calloc(1, sizeof(**db3)); /* Allocate space for the larger db3 */
+ if (*db == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ (*db)->hdb_db = NULL;
+ (*db)->hdb_name = strdup(filename);
+ if ((*db)->hdb_name == NULL) {
+ free(*db);
+ *db = NULL;
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ (*db)->hdb_master_key_set = 0;
+ (*db)->hdb_openp = 0;
+ (*db)->hdb_capability_flags = HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL;
+ (*db)->hdb_open = DB_open;
+ (*db)->hdb_close = DB_close;
+ (*db)->hdb_fetch_kvno = _hdb_fetch_kvno;
+ (*db)->hdb_store = _hdb_store;
+ (*db)->hdb_remove = _hdb_remove;
+ (*db)->hdb_firstkey = DB_firstkey;
+ (*db)->hdb_nextkey= DB_nextkey;
+ (*db)->hdb_lock = DB_lock;
+ (*db)->hdb_unlock = DB_unlock;
+ (*db)->hdb_rename = DB_rename;
+ (*db)->hdb__get = DB__get;
+ (*db)->hdb__put = DB__put;
+ (*db)->hdb__del = DB__del;
+ (*db)->hdb_destroy = DB_destroy;
+ (*db)->hdb_set_sync = DB_set_sync;
+
+ (*db3)->lock_fd = -1;
+ return 0;
+}
+#endif /* HAVE_DB3 */
diff --git a/third_party/heimdal/lib/hdb/dbinfo.c b/third_party/heimdal/lib/hdb/dbinfo.c
new file mode 100644
index 0000000..60b11f8
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/dbinfo.c
@@ -0,0 +1,291 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hdb_locl.h"
+
+struct hdb_dbinfo {
+ char *label;
+ char *realm;
+ char *dbname;
+ char *mkey_file;
+ char *acl_file;
+ char *log_file;
+ const krb5_config_binding *binding;
+ struct hdb_dbinfo *next;
+};
+
+static int
+get_dbinfo(krb5_context context,
+ const krb5_config_binding *db_binding,
+ const char *label,
+ struct hdb_dbinfo **db)
+{
+ struct hdb_dbinfo *di;
+ const char *p;
+
+ *db = NULL;
+
+ p = krb5_config_get_string(context, db_binding, "dbname", NULL);
+ if(p == NULL)
+ return 0;
+
+ di = calloc(1, sizeof(*di));
+ if (di == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ di->label = strdup(label);
+ di->dbname = strdup(p);
+
+ p = krb5_config_get_string(context, db_binding, "realm", NULL);
+ if(p)
+ di->realm = strdup(p);
+ p = krb5_config_get_string(context, db_binding, "mkey_file", NULL);
+ if(p)
+ di->mkey_file = strdup(p);
+ p = krb5_config_get_string(context, db_binding, "acl_file", NULL);
+ if(p)
+ di->acl_file = strdup(p);
+ p = krb5_config_get_string(context, db_binding, "log_file", NULL);
+ if(p)
+ di->log_file = strdup(p);
+
+ di->binding = db_binding;
+
+ *db = di;
+ return 0;
+}
+
+
+int
+hdb_get_dbinfo(krb5_context context, struct hdb_dbinfo **dbp)
+{
+ const krb5_config_binding *db_binding;
+ struct hdb_dbinfo *di, **dt, *databases;
+ const char *default_dbname = HDB_DEFAULT_DB;
+ const char *default_mkey = HDB_DB_DIR "/m-key";
+ const char *default_acl = HDB_DB_DIR "/kadmind.acl";
+ const char *p;
+ int ret;
+
+ *dbp = NULL;
+ dt = NULL;
+ databases = NULL;
+
+ db_binding = krb5_config_get_list(context, NULL,
+ "kdc",
+ "database",
+ NULL);
+ if (db_binding) {
+
+ ret = get_dbinfo(context, db_binding, "default", &databases);
+ if (ret == 0 && databases != NULL)
+ dt = &databases->next;
+
+ for ( ; db_binding != NULL; db_binding = db_binding->next) {
+
+ if (db_binding->type != krb5_config_list)
+ continue;
+
+ ret = get_dbinfo(context, db_binding->u.list,
+ db_binding->name, &di);
+ if (ret)
+ krb5_err(context, 1, ret, "failed getting realm");
+
+ if (di == NULL)
+ continue;
+
+ if (dt)
+ *dt = di;
+ else {
+ hdb_free_dbinfo(context, &databases);
+ databases = di;
+ }
+ dt = &di->next;
+
+ }
+ }
+
+ if (databases == NULL) {
+ /* if there are none specified, create one and use defaults */
+ databases = calloc(1, sizeof(*databases));
+ databases->label = strdup("default");
+ }
+
+ for (di = databases; di; di = di->next) {
+ if (di->dbname == NULL) {
+ di->dbname = strdup(default_dbname);
+ if (di->mkey_file == NULL)
+ di->mkey_file = strdup(default_mkey);
+ }
+ if (di->mkey_file == NULL) {
+ p = strrchr(di->dbname, '.');
+ if(p == NULL || strchr(p, '/') != NULL)
+ /* final pathname component does not contain a . */
+ ret = asprintf(&di->mkey_file, "%s.mkey", di->dbname);
+ else
+ /* the filename is something.else, replace .else with
+ .mkey */
+ ret = asprintf(&di->mkey_file, "%.*s.mkey",
+ (int)(p - di->dbname), di->dbname);
+ if (ret == -1) {
+ hdb_free_dbinfo(context, &databases);
+ return ENOMEM;
+ }
+ }
+ if(di->acl_file == NULL)
+ di->acl_file = strdup(default_acl);
+ }
+ *dbp = databases;
+ return 0;
+}
+
+
+struct hdb_dbinfo *
+hdb_dbinfo_get_next(struct hdb_dbinfo *dbp, struct hdb_dbinfo *dbprevp)
+{
+ if (dbprevp == NULL)
+ return dbp;
+ else
+ return dbprevp->next;
+}
+
+const char *
+hdb_dbinfo_get_label(krb5_context context, struct hdb_dbinfo *dbp)
+{
+ return dbp->label;
+}
+
+const char *
+hdb_dbinfo_get_realm(krb5_context context, struct hdb_dbinfo *dbp)
+{
+ return dbp->realm;
+}
+
+const char *
+hdb_dbinfo_get_dbname(krb5_context context, struct hdb_dbinfo *dbp)
+{
+ return dbp->dbname;
+}
+
+const char *
+hdb_dbinfo_get_mkey_file(krb5_context context, struct hdb_dbinfo *dbp)
+{
+ return dbp->mkey_file;
+}
+
+const char *
+hdb_dbinfo_get_acl_file(krb5_context context, struct hdb_dbinfo *dbp)
+{
+ return dbp->acl_file;
+}
+
+const char *
+hdb_dbinfo_get_log_file(krb5_context context, struct hdb_dbinfo *dbp)
+{
+ return dbp->log_file;
+}
+
+const krb5_config_binding *
+hdb_dbinfo_get_binding(krb5_context context, struct hdb_dbinfo *dbp)
+{
+ return dbp->binding;
+}
+
+void
+hdb_free_dbinfo(krb5_context context, struct hdb_dbinfo **dbp)
+{
+ struct hdb_dbinfo *di, *ndi;
+
+ for(di = *dbp; di != NULL; di = ndi) {
+ ndi = di->next;
+ free (di->label);
+ free (di->realm);
+ free (di->dbname);
+ free (di->mkey_file);
+ free (di->acl_file);
+ free (di->log_file);
+ free(di);
+ }
+ *dbp = NULL;
+}
+
+/**
+ * Return the directory where the hdb database resides.
+ *
+ * @param context Kerberos 5 context.
+ *
+ * @return string pointing to directory.
+ */
+
+const char *
+hdb_db_dir(krb5_context context)
+{
+ const char *p;
+
+ p = krb5_config_get_string(context, NULL, "hdb", "db-dir", NULL);
+ if (p)
+ return p;
+
+ return HDB_DB_DIR;
+}
+
+/**
+ * Return the default hdb database resides.
+ *
+ * @param context Kerberos 5 context.
+ *
+ * @return string pointing to directory.
+ */
+
+const char *
+hdb_default_db(krb5_context context)
+{
+ static char *default_hdb = NULL;
+ struct hdb_dbinfo *dbinfo = NULL;
+ struct hdb_dbinfo *d = NULL;
+ const char *s;
+
+ if (default_hdb)
+ return default_hdb;
+
+ (void) hdb_get_dbinfo(context, &dbinfo);
+ while ((d = hdb_dbinfo_get_next(dbinfo, d)) != NULL) {
+ if ((s = hdb_dbinfo_get_dbname(context, d)) &&
+ (default_hdb = strdup(s)))
+ break;
+ }
+
+ hdb_free_dbinfo(context, &dbinfo);
+ return default_hdb ? default_hdb : HDB_DEFAULT_DB;
+}
diff --git a/third_party/heimdal/lib/hdb/ext.c b/third_party/heimdal/lib/hdb/ext.c
new file mode 100644
index 0000000..48683ef
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/ext.c
@@ -0,0 +1,786 @@
+/*
+ * Copyright (c) 2004 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hdb_locl.h"
+#include <der.h>
+
+krb5_error_code
+hdb_entry_check_mandatory(krb5_context context, const hdb_entry *ent)
+{
+ size_t i;
+
+ if (ent->extensions == NULL)
+ return 0;
+
+ /*
+ * check for unknown extensions and if they where tagged mandatory
+ */
+
+ for (i = 0; i < ent->extensions->len; i++) {
+ if (ent->extensions->val[i].data.element !=
+ choice_HDB_extension_data_asn1_ellipsis)
+ continue;
+ if (ent->extensions->val[i].mandatory) {
+ krb5_set_error_message(context, HDB_ERR_MANDATORY_OPTION,
+ "Principal have unknown "
+ "mandatory extension");
+ return HDB_ERR_MANDATORY_OPTION;
+ }
+ }
+ return 0;
+}
+
+HDB_extension *
+hdb_find_extension(const hdb_entry *entry, int type)
+{
+ size_t i;
+
+ if (entry->extensions == NULL)
+ return NULL;
+
+ for (i = 0; i < entry->extensions->len; i++)
+ if (entry->extensions->val[i].data.element == (unsigned)type)
+ return &entry->extensions->val[i];
+ return NULL;
+}
+
+/*
+ * Replace the extension `ext' in `entry'. Make a copy of the
+ * extension, so the caller must still free `ext' on both success and
+ * failure. Returns 0 or error code.
+ */
+
+krb5_error_code
+hdb_replace_extension(krb5_context context,
+ hdb_entry *entry,
+ const HDB_extension *ext)
+{
+ HDB_extension *ext2;
+ int ret;
+
+ ext2 = NULL;
+
+ if (entry->extensions == NULL) {
+ entry->extensions = calloc(1, sizeof(*entry->extensions));
+ if (entry->extensions == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ } else if (ext->data.element != choice_HDB_extension_data_asn1_ellipsis) {
+ ext2 = hdb_find_extension(entry, ext->data.element);
+ } else {
+ /*
+ * This is an unknown extension, and we are asked to replace a
+ * possible entry in `entry' that is of the same type. This
+ * might seem impossible, but ASN.1 CHOICE comes to our
+ * rescue. The first tag in each branch in the CHOICE is
+ * unique, so just find the element in the list that have the
+ * same tag was we are putting into the list.
+ */
+ Der_class replace_class, list_class;
+ Der_type replace_type, list_type;
+ unsigned int replace_tag, list_tag;
+ size_t size;
+ size_t i;
+
+ ret = der_get_tag(ext->data.u.asn1_ellipsis.data,
+ ext->data.u.asn1_ellipsis.length,
+ &replace_class, &replace_type, &replace_tag,
+ &size);
+ if (ret) {
+ krb5_set_error_message(context, ret, "hdb: failed to decode "
+ "replacement hdb extension");
+ return ret;
+ }
+
+ for (i = 0; i < entry->extensions->len; i++) {
+ HDB_extension *ext3 = &entry->extensions->val[i];
+
+ if (ext3->data.element != choice_HDB_extension_data_asn1_ellipsis)
+ continue;
+
+ ret = der_get_tag(ext3->data.u.asn1_ellipsis.data,
+ ext3->data.u.asn1_ellipsis.length,
+ &list_class, &list_type, &list_tag,
+ &size);
+ if (ret) {
+ krb5_set_error_message(context, ret, "hdb: failed to decode "
+ "present hdb extension");
+ return ret;
+ }
+
+ if (MAKE_TAG(replace_class,replace_type,replace_type) ==
+ MAKE_TAG(list_class,list_type,list_type)) {
+ ext2 = ext3;
+ break;
+ }
+ }
+ }
+
+ if (ext2) {
+ free_HDB_extension(ext2);
+ ret = copy_HDB_extension(ext, ext2);
+ if (ret)
+ krb5_set_error_message(context, ret, "hdb: failed to copy replacement "
+ "hdb extension");
+ return ret;
+ }
+
+ return add_HDB_extensions(entry->extensions, ext);
+}
+
+krb5_error_code
+hdb_clear_extension(krb5_context context,
+ hdb_entry *entry,
+ int type)
+{
+ size_t i;
+
+ if (entry->extensions == NULL)
+ return 0;
+
+ for (i = 0; i < entry->extensions->len; ) {
+ if (entry->extensions->val[i].data.element == (unsigned)type)
+ (void) remove_HDB_extensions(entry->extensions, i);
+ else
+ i++;
+ }
+ if (entry->extensions->len == 0) {
+ free(entry->extensions->val);
+ free(entry->extensions);
+ entry->extensions = NULL;
+ }
+
+ return 0;
+}
+
+
+krb5_error_code
+hdb_entry_get_pkinit_acl(const hdb_entry *entry, const HDB_Ext_PKINIT_acl **a)
+{
+ const HDB_extension *ext;
+
+ ext = hdb_find_extension(entry, choice_HDB_extension_data_pkinit_acl);
+ if (ext)
+ *a = &ext->data.u.pkinit_acl;
+ else
+ *a = NULL;
+
+ return 0;
+}
+
+krb5_error_code
+hdb_entry_get_pkinit_hash(const hdb_entry *entry, const HDB_Ext_PKINIT_hash **a)
+{
+ const HDB_extension *ext;
+
+ ext = hdb_find_extension(entry, choice_HDB_extension_data_pkinit_cert_hash);
+ if (ext)
+ *a = &ext->data.u.pkinit_cert_hash;
+ else
+ *a = NULL;
+
+ return 0;
+}
+
+krb5_error_code
+hdb_entry_get_pkinit_cert(const hdb_entry *entry, const HDB_Ext_PKINIT_cert **a)
+{
+ const HDB_extension *ext;
+
+ ext = hdb_find_extension(entry, choice_HDB_extension_data_pkinit_cert);
+ if (ext)
+ *a = &ext->data.u.pkinit_cert;
+ else
+ *a = NULL;
+
+ return 0;
+}
+
+krb5_error_code
+hdb_entry_get_krb5_config(const hdb_entry *entry, heim_octet_string *c)
+{
+ const HDB_extension *ext;
+
+ c->data = NULL;
+ c->length = 0;
+ ext = hdb_find_extension(entry, choice_HDB_extension_data_krb5_config);
+ if (ext)
+ *c = ext->data.u.krb5_config;
+ return 0;
+}
+
+krb5_error_code
+hdb_entry_set_krb5_config(krb5_context context,
+ hdb_entry *entry,
+ heim_octet_string *s)
+{
+ HDB_extension ext;
+
+ ext.mandatory = FALSE;
+ ext.data.element = choice_HDB_extension_data_last_pw_change;
+ /* hdb_replace_extension() copies this, so no need to copy it here */
+ ext.data.u.krb5_config = *s;
+ return hdb_replace_extension(context, entry, &ext);
+}
+
+krb5_error_code
+hdb_entry_get_pw_change_time(const hdb_entry *entry, time_t *t)
+{
+ const HDB_extension *ext;
+
+ ext = hdb_find_extension(entry, choice_HDB_extension_data_last_pw_change);
+ if (ext)
+ *t = ext->data.u.last_pw_change;
+ else
+ *t = 0;
+
+ return 0;
+}
+
+krb5_error_code
+hdb_entry_set_pw_change_time(krb5_context context,
+ hdb_entry *entry,
+ time_t t)
+{
+ HDB_extension ext;
+
+ ext.mandatory = FALSE;
+ ext.data.element = choice_HDB_extension_data_last_pw_change;
+ if (t == 0)
+ t = time(NULL);
+ ext.data.u.last_pw_change = t;
+
+ return hdb_replace_extension(context, entry, &ext);
+}
+
+int
+hdb_entry_get_password(krb5_context context, HDB *db,
+ const hdb_entry *entry, char **p)
+{
+ HDB_extension *ext;
+ char *str;
+ int ret;
+
+ ext = hdb_find_extension(entry, choice_HDB_extension_data_password);
+ if (ext) {
+ heim_utf8_string xstr;
+ heim_octet_string pw;
+
+ if (db->hdb_master_key_set && ext->data.u.password.mkvno) {
+ hdb_master_key key;
+
+ key = _hdb_find_master_key(ext->data.u.password.mkvno,
+ db->hdb_master_key);
+
+ if (key == NULL) {
+ krb5_set_error_message(context, HDB_ERR_NO_MKEY,
+ "master key %d missing",
+ *ext->data.u.password.mkvno);
+ return HDB_ERR_NO_MKEY;
+ }
+
+ ret = _hdb_mkey_decrypt(context, key, HDB_KU_MKEY,
+ ext->data.u.password.password.data,
+ ext->data.u.password.password.length,
+ &pw);
+ } else {
+ ret = der_copy_octet_string(&ext->data.u.password.password, &pw);
+ }
+ if (ret) {
+ krb5_clear_error_message(context);
+ return ret;
+ }
+
+ xstr = pw.data;
+ if (xstr[pw.length - 1] != '\0') {
+ krb5_set_error_message(context, EINVAL, "malformed password");
+ return EINVAL;
+ }
+
+ *p = strdup(xstr);
+
+ der_free_octet_string(&pw);
+ if (*p == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ return 0;
+ }
+
+ ret = krb5_unparse_name(context, entry->principal, &str);
+ if (ret == 0) {
+ krb5_set_error_message(context, ENOENT,
+ "no password attribute for %s", str);
+ free(str);
+ } else
+ krb5_clear_error_message(context);
+
+ return ENOENT;
+}
+
+int
+hdb_entry_set_password(krb5_context context, HDB *db,
+ hdb_entry *entry, const char *p)
+{
+ HDB_extension ext;
+ hdb_master_key key;
+ int ret;
+
+ ext.mandatory = FALSE;
+ ext.data.element = choice_HDB_extension_data_password;
+
+ if (db->hdb_master_key_set) {
+
+ key = _hdb_find_master_key(NULL, db->hdb_master_key);
+ if (key == NULL) {
+ krb5_set_error_message(context, HDB_ERR_NO_MKEY,
+ "hdb_entry_set_password: "
+ "failed to find masterkey");
+ return HDB_ERR_NO_MKEY;
+ }
+
+ ret = _hdb_mkey_encrypt(context, key, HDB_KU_MKEY,
+ p, strlen(p) + 1,
+ &ext.data.u.password.password);
+ if (ret)
+ return ret;
+
+ ext.data.u.password.mkvno =
+ malloc(sizeof(*ext.data.u.password.mkvno));
+ if (ext.data.u.password.mkvno == NULL) {
+ free_HDB_extension(&ext);
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ *ext.data.u.password.mkvno = _hdb_mkey_version(key);
+
+ } else {
+ ext.data.u.password.mkvno = NULL;
+
+ ret = krb5_data_copy(&ext.data.u.password.password,
+ p, strlen(p) + 1);
+ if (ret) {
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ free_HDB_extension(&ext);
+ return ret;
+ }
+ }
+
+ ret = hdb_replace_extension(context, entry, &ext);
+
+ free_HDB_extension(&ext);
+
+ return ret;
+}
+
+int
+hdb_entry_clear_password(krb5_context context, hdb_entry *entry)
+{
+ return hdb_clear_extension(context, entry,
+ choice_HDB_extension_data_password);
+}
+
+krb5_error_code
+hdb_entry_get_ConstrainedDelegACL(const hdb_entry *entry,
+ const HDB_Ext_Constrained_delegation_acl **a)
+{
+ const HDB_extension *ext;
+
+ ext = hdb_find_extension(entry,
+ choice_HDB_extension_data_allowed_to_delegate_to);
+ if (ext)
+ *a = &ext->data.u.allowed_to_delegate_to;
+ else
+ *a = NULL;
+
+ return 0;
+}
+
+krb5_error_code
+hdb_entry_get_aliases(const hdb_entry *entry, const HDB_Ext_Aliases **a)
+{
+ const HDB_extension *ext;
+
+ ext = hdb_find_extension(entry, choice_HDB_extension_data_aliases);
+ if (ext)
+ *a = &ext->data.u.aliases;
+ else
+ *a = NULL;
+
+ return 0;
+}
+
+unsigned int
+hdb_entry_get_kvno_diff_clnt(const hdb_entry *entry)
+{
+ const HDB_extension *ext;
+
+ ext = hdb_find_extension(entry,
+ choice_HDB_extension_data_hist_kvno_diff_clnt);
+ if (ext)
+ return ext->data.u.hist_kvno_diff_clnt;
+ return 1;
+}
+
+krb5_error_code
+hdb_entry_set_kvno_diff_clnt(krb5_context context, hdb_entry *entry,
+ unsigned int diff)
+{
+ HDB_extension ext;
+
+ if (diff > 16384)
+ return EINVAL;
+ ext.mandatory = FALSE;
+ ext.data.element = choice_HDB_extension_data_hist_kvno_diff_clnt;
+ ext.data.u.hist_kvno_diff_clnt = diff;
+ return hdb_replace_extension(context, entry, &ext);
+}
+
+krb5_error_code
+hdb_entry_clear_kvno_diff_clnt(krb5_context context, hdb_entry *entry)
+{
+ return hdb_clear_extension(context, entry,
+ choice_HDB_extension_data_hist_kvno_diff_clnt);
+}
+
+unsigned int
+hdb_entry_get_kvno_diff_svc(const hdb_entry *entry)
+{
+ const HDB_extension *ext;
+
+ ext = hdb_find_extension(entry,
+ choice_HDB_extension_data_hist_kvno_diff_svc);
+ if (ext)
+ return ext->data.u.hist_kvno_diff_svc;
+ return 1024; /* max_life effectively provides a better default */
+}
+
+krb5_error_code
+hdb_entry_set_kvno_diff_svc(krb5_context context, hdb_entry *entry,
+ unsigned int diff)
+{
+ HDB_extension ext;
+
+ if (diff > 16384)
+ return EINVAL;
+ ext.mandatory = FALSE;
+ ext.data.element = choice_HDB_extension_data_hist_kvno_diff_svc;
+ ext.data.u.hist_kvno_diff_svc = diff;
+ return hdb_replace_extension(context, entry, &ext);
+}
+
+krb5_error_code
+hdb_entry_clear_kvno_diff_svc(krb5_context context, hdb_entry *entry)
+{
+ return hdb_clear_extension(context, entry,
+ choice_HDB_extension_data_hist_kvno_diff_svc);
+}
+
+krb5_error_code
+hdb_set_last_modified_by(krb5_context context, hdb_entry *entry,
+ krb5_principal modby, time_t modtime)
+{
+ krb5_error_code ret;
+ Event *old_ev;
+ Event *ev;
+
+ old_ev = entry->modified_by;
+
+ ev = calloc(1, sizeof (*ev));
+ if (!ev)
+ return ENOMEM;
+ if (modby)
+ ret = krb5_copy_principal(context, modby, &ev->principal);
+ else
+ ret = krb5_parse_name(context, "root/admin", &ev->principal);
+ if (ret) {
+ free(ev);
+ return ret;
+ }
+ ev->time = modtime;
+ if (!ev->time)
+ time(&ev->time);
+
+ entry->modified_by = ev;
+ if (old_ev)
+ free_Event(old_ev);
+ return 0;
+}
+
+krb5_error_code
+hdb_entry_get_key_rotation(krb5_context context,
+ const hdb_entry *entry,
+ const HDB_Ext_KeyRotation **kr)
+{
+ HDB_extension *ext =
+ hdb_find_extension(entry, choice_HDB_extension_data_key_rotation);
+
+ *kr = ext ? &ext->data.u.key_rotation : NULL;
+ return 0;
+}
+
+krb5_error_code
+hdb_validate_key_rotation(krb5_context context,
+ const KeyRotation *past_kr,
+ const KeyRotation *new_kr)
+{
+ unsigned int last_kvno;
+
+ if (new_kr->period < 1) {
+ krb5_set_error_message(context, EINVAL,
+ "Key rotation periods must be non-zero "
+ "and positive");
+ return EINVAL;
+ }
+ if (new_kr->base_key_kvno < 1 || new_kr->base_kvno < 1) {
+ krb5_set_error_message(context, EINVAL,
+ "Key version number zero not allowed "
+ "for key rotation");
+ return EINVAL;
+ }
+ if (!past_kr)
+ return 0;
+
+ if (past_kr->base_key_kvno == new_kr->base_key_kvno) {
+ /*
+ * The new base keys can be the same as the old, but must have
+ * different kvnos. (Well, not must must. It's a convention for now.)
+ */
+ krb5_set_error_message(context, EINVAL,
+ "Base key version numbers for KRs must differ");
+ return EINVAL;
+ }
+ if (new_kr->epoch - past_kr->epoch <= 0) {
+ krb5_set_error_message(context, EINVAL,
+ "New key rotation periods must start later "
+ "than existing ones");
+ return EINVAL;
+ }
+
+ last_kvno = 1 + ((new_kr->epoch - past_kr->epoch) / past_kr->period);
+ if (new_kr->base_kvno <= last_kvno) {
+ krb5_set_error_message(context, EINVAL,
+ "New key rotation base kvno must be larger "
+ "the last kvno for the current key "
+ "rotation (%u)", last_kvno);
+ return EINVAL;
+ }
+ return 0;
+}
+
+static int
+kr_eq(const KeyRotation *a, const KeyRotation *b)
+{
+ return !!(
+ a->epoch == b->epoch &&
+ a->period == b->period &&
+ a->base_kvno == b->base_kvno &&
+ a->base_key_kvno == b->base_key_kvno &&
+ KeyRotationFlags2int(a->flags) == KeyRotationFlags2int(b->flags)
+ );
+}
+
+krb5_error_code
+hdb_validate_key_rotations(krb5_context context,
+ const HDB_Ext_KeyRotation *existing,
+ const HDB_Ext_KeyRotation *krs)
+{
+ krb5_error_code ret = 0;
+ size_t added = 0;
+ size_t i;
+
+ if ((!existing || !existing->len) && (!krs || !krs->len))
+ return 0; /* Nothing to do; weird */
+
+ /*
+ * HDB_Ext_KeyRotation has to have 1..3 elements, and this is enforced by
+ * the ASN.1 compiler and the code it generates. Nonetheless we'll check
+ * that there's not zero elements.
+ */
+ if ((!krs || !krs->len)) {
+ /*
+ * NOTE: We can clear this on concrete principals with virtual keys
+ * though. The caller can check for that case.
+ */
+ krb5_set_error_message(context, EINVAL,
+ "Cannot clear key rotation metadata on "
+ "virtual principal namespaces");
+ ret = EINVAL;
+ }
+
+ /* Validate the new KRs by themselves */
+ for (i = 0; ret == 0 && i < krs->len; i++) {
+ ret = hdb_validate_key_rotation(context,
+ i+1 < krs->len ? &krs->val[i+1] : 0,
+ &krs->val[i]);
+ }
+ if (ret || !existing || !existing->len)
+ return ret;
+
+ if (existing->len == krs->len) {
+ /* Check for no change */
+ for (i = 0; i < krs->len; i++)
+ if (!kr_eq(&existing->val[i], &krs->val[i]))
+ break;
+ if (i == krs->len)
+ return 0; /* No change */
+ }
+
+ /*
+ * Check that new KRs make sense in the context of the previous KRs.
+ *
+ * Permitted changes:
+ *
+ * - add one new KR in front
+ * - drop old KRs
+ *
+ * Start by checking if we're adding a KR, then go on to check for dropped
+ * KRs and/or last KR alteration.
+ */
+ if (existing->val[0].epoch == krs->val[0].epoch ||
+ existing->val[0].base_kvno == krs->val[0].base_kvno) {
+ if (!kr_eq(&existing->val[0], &krs->val[0])) {
+ krb5_set_error_message(context, EINVAL,
+ "Key rotation change not sensible");
+ ret = EINVAL;
+ }
+ /* Key rotation *not* added */
+ } else {
+ /* Key rotation added; check it first */
+ ret = hdb_validate_key_rotation(context,
+ &existing->val[0],
+ &krs->val[0]);
+ added = 1;
+ }
+ for (i = 0; ret == 0 && i < existing->len && i + added < krs->len; i++)
+ if (!kr_eq(&existing->val[i], &krs->val[i + added]))
+ krb5_set_error_message(context, ret = EINVAL,
+ "Only last key rotation may be truncated");
+ return ret;
+}
+
+/* XXX We need a function to "revoke" the past */
+
+/**
+ * This function adds a KeyRotation value to an entry, validating the
+ * change. One of `entry' and `krs' must be NULL, and the other non-NULL, and
+ * whichever is given will be altered.
+ *
+ * @param context Context
+ * @param entry An HDB entry
+ * @param krs A key rotation extension for hdb_entry
+ * @param kr A new KeyRotation value
+ *
+ * @return Zero on success, an error otherwise.
+ */
+krb5_error_code
+hdb_entry_add_key_rotation(krb5_context context,
+ hdb_entry *entry,
+ HDB_Ext_KeyRotation *krs,
+ const KeyRotation *kr)
+{
+ krb5_error_code ret;
+ HDB_extension new_ext;
+ HDB_extension *ext = &new_ext;
+ KeyRotation tmp;
+ size_t i, sz;
+
+ if (kr->period < 1) {
+ krb5_set_error_message(context, EINVAL,
+ "Key rotation period cannot be zero");
+ return EINVAL;
+ }
+
+ new_ext.mandatory = TRUE;
+ new_ext.data.element = choice_HDB_extension_data_key_rotation;
+ new_ext.data.u.key_rotation.len = 0;
+ new_ext.data.u.key_rotation.val = 0;
+
+ if (entry && krs)
+ return EINVAL;
+
+ if (entry) {
+ ext = hdb_find_extension(entry, choice_HDB_extension_data_key_rotation);
+ if (!ext)
+ ext = &new_ext;
+ } else {
+ const KeyRotation *prev_kr = &krs->val[0];
+ unsigned int last_kvno = 0;
+
+ if (kr->epoch - prev_kr->epoch <= 0) {
+ krb5_set_error_message(context, EINVAL,
+ "New key rotation periods must start later "
+ "than existing ones");
+ return EINVAL;
+ }
+
+ if (kr->base_kvno <= prev_kr->base_kvno ||
+ kr->base_kvno - prev_kr->base_kvno <=
+ (last_kvno = 1 +
+ ((kr->epoch - prev_kr->epoch) / prev_kr->period))) {
+ krb5_set_error_message(context, EINVAL,
+ "New key rotation base kvno must be larger "
+ "the last kvno for the current key "
+ "rotation (%u)", last_kvno);
+ return EINVAL;
+ }
+ }
+
+ /* First, append */
+ ret = add_HDB_Ext_KeyRotation(&ext->data.u.key_rotation, kr);
+ if (ret)
+ return ret;
+
+ /* Rotate new to front */
+ tmp = ext->data.u.key_rotation.val[ext->data.u.key_rotation.len - 1];
+ sz = sizeof(ext->data.u.key_rotation.val[0]);
+ memmove(&ext->data.u.key_rotation.val[1], &ext->data.u.key_rotation.val[0],
+ (ext->data.u.key_rotation.len - 1) * sz);
+ ext->data.u.key_rotation.val[0] = tmp;
+
+ /* Drop too old entries */
+ for (i = 3; i < ext->data.u.key_rotation.len; i++)
+ free_KeyRotation(&ext->data.u.key_rotation.val[i]);
+ ext->data.u.key_rotation.len =
+ ext->data.u.key_rotation.len > 3 ? 3 : ext->data.u.key_rotation.len;
+
+ if (ext != &new_ext)
+ return 0;
+
+ /* Install new extension */
+ if (ret == 0 && entry)
+ ret = hdb_replace_extension(context, entry, ext);
+ free_HDB_extension(&new_ext);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/hdb/hdb-keytab.c b/third_party/heimdal/lib/hdb/hdb-keytab.c
new file mode 100644
index 0000000..c9b469c
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/hdb-keytab.c
@@ -0,0 +1,232 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hdb_locl.h"
+#include <assert.h>
+
+typedef struct {
+ char *path;
+ krb5_keytab keytab;
+} *hdb_keytab;
+
+/*
+ *
+ */
+
+static krb5_error_code
+hkt_close(krb5_context context, HDB *db)
+{
+ hdb_keytab k = (hdb_keytab)db->hdb_db;
+ krb5_error_code ret;
+
+ assert(k->keytab);
+
+ ret = krb5_kt_close(context, k->keytab);
+ k->keytab = NULL;
+
+ return ret;
+}
+
+static krb5_error_code
+hkt_destroy(krb5_context context, HDB *db)
+{
+ hdb_keytab k = (hdb_keytab)db->hdb_db;
+ krb5_error_code ret;
+
+ ret = hdb_clear_master_key(context, db);
+ krb5_config_free_strings(db->virtual_hostbased_princ_svcs);
+
+ free(k->path);
+ free(k);
+
+ free(db->hdb_name);
+ free(db);
+ return ret;
+}
+
+static krb5_error_code
+hkt_lock(krb5_context context, HDB *db, int operation)
+{
+ return 0;
+}
+
+static krb5_error_code
+hkt_unlock(krb5_context context, HDB *db)
+{
+ return 0;
+}
+
+static krb5_error_code
+hkt_firstkey(krb5_context context, HDB *db,
+ unsigned flags, hdb_entry *entry)
+{
+ return HDB_ERR_DB_INUSE;
+}
+
+static krb5_error_code
+hkt_nextkey(krb5_context context, HDB * db, unsigned flags,
+ hdb_entry * entry)
+{
+ return HDB_ERR_DB_INUSE;
+}
+
+static krb5_error_code
+hkt_open(krb5_context context, HDB * db, int flags, mode_t mode)
+{
+ hdb_keytab k = (hdb_keytab)db->hdb_db;
+ krb5_error_code ret;
+
+ assert(k->keytab == NULL);
+
+ ret = krb5_kt_resolve(context, k->path, &k->keytab);
+ if (ret)
+ return ret;
+
+ return 0;
+}
+
+static krb5_error_code
+hkt_fetch_kvno(krb5_context context, HDB * db, krb5_const_principal principal,
+ unsigned flags, krb5_kvno kvno, hdb_entry * entry)
+{
+ hdb_keytab k = (hdb_keytab)db->hdb_db;
+ krb5_error_code ret;
+ krb5_keytab_entry ktentry;
+
+ if (!(flags & HDB_F_KVNO_SPECIFIED)) {
+ /* Preserve previous behaviour if no kvno specified */
+ kvno = 0;
+ }
+
+ memset(&ktentry, 0, sizeof(ktentry));
+
+ entry->flags.server = 1;
+ entry->flags.forwardable = 1;
+ entry->flags.renewable = 1;
+
+ /* Not recorded in the OD backend, make something up */
+ ret = krb5_parse_name(context, "hdb/keytab@WELL-KNOWN:KEYTAB-BACKEND",
+ &entry->created_by.principal);
+ if (ret)
+ goto out;
+
+ /*
+ * XXX really needs to try all enctypes and just not pick the
+ * first one, even if that happens to be des3-cbc-sha1 (ie best
+ * enctype) in the Apple case. A while loop over all known
+ * enctypes should work.
+ */
+
+ ret = krb5_kt_get_entry(context, k->keytab, principal, kvno, 0, &ktentry);
+ if (ret) {
+ ret = HDB_ERR_NOENTRY;
+ goto out;
+ }
+
+ ret = krb5_copy_principal(context, principal, &entry->principal);
+ if (ret)
+ goto out;
+
+ ret = _hdb_keytab2hdb_entry(context, &ktentry, entry);
+
+ out:
+ if (ret) {
+ free_HDB_entry(entry);
+ memset(entry, 0, sizeof(*entry));
+ }
+ krb5_kt_free_entry(context, &ktentry);
+
+ return ret;
+}
+
+static krb5_error_code
+hkt_store(krb5_context context, HDB * db, unsigned flags,
+ hdb_entry * entry)
+{
+ return HDB_ERR_DB_INUSE;
+}
+
+
+krb5_error_code
+hdb_keytab_create(krb5_context context, HDB ** db, const char *arg)
+{
+ hdb_keytab k;
+
+ *db = calloc(1, sizeof(**db));
+ if (*db == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ memset(*db, 0, sizeof(**db));
+
+ k = calloc(1, sizeof(*k));
+ if (k == NULL) {
+ free(*db);
+ *db = NULL;
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ k->path = strdup(arg);
+ if (k->path == NULL) {
+ free(k);
+ free(*db);
+ *db = NULL;
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+
+ (*db)->hdb_db = k;
+
+ (*db)->hdb_master_key_set = 0;
+ (*db)->hdb_openp = 0;
+ (*db)->hdb_open = hkt_open;
+ (*db)->hdb_close = hkt_close;
+ (*db)->hdb_fetch_kvno = hkt_fetch_kvno;
+ (*db)->hdb_store = hkt_store;
+ (*db)->hdb_remove = NULL;
+ (*db)->hdb_firstkey = hkt_firstkey;
+ (*db)->hdb_nextkey = hkt_nextkey;
+ (*db)->hdb_lock = hkt_lock;
+ (*db)->hdb_unlock = hkt_unlock;
+ (*db)->hdb_rename = NULL;
+ (*db)->hdb__get = NULL;
+ (*db)->hdb__put = NULL;
+ (*db)->hdb__del = NULL;
+ (*db)->hdb_destroy = hkt_destroy;
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hdb/hdb-ldap.c b/third_party/heimdal/lib/hdb/hdb-ldap.c
new file mode 100644
index 0000000..5cd097f
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/hdb-ldap.c
@@ -0,0 +1,2117 @@
+/*
+ * Copyright (c) 1999-2001, 2003, PADL Software Pty Ltd.
+ * Copyright (c) 2004, Andrew Bartlett.
+ * Copyright (c) 2003 - 2008, Kungliga Tekniska Högskolan.
+ * Copyright (c) 2015, Timothy Pearson.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hdb_locl.h"
+
+#ifdef OPENLDAP
+
+#include <lber.h>
+#include <ldap.h>
+#include <sys/un.h>
+#include <hex.h>
+
+static krb5_error_code LDAP__connect(krb5_context context, HDB *);
+static krb5_error_code LDAP_close(krb5_context context, HDB *);
+
+static krb5_error_code
+LDAP_message2entry(krb5_context context, HDB * db, LDAPMessage * msg,
+ int flags, hdb_entry * ent);
+
+static const char *default_structural_object = "account";
+static char *structural_object;
+static const char *default_ldap_url = "ldapi:///";
+static krb5_boolean samba_forwardable;
+
+struct hdbldapdb {
+ LDAP *h_lp;
+ int h_msgid;
+ char *h_base;
+ char *h_url;
+ char *h_bind_dn;
+ char *h_bind_password;
+ krb5_boolean h_start_tls;
+ char *h_createbase;
+};
+
+#define HDB2LDAP(db) (((struct hdbldapdb *)(db)->hdb_db)->h_lp)
+#define HDB2MSGID(db) (((struct hdbldapdb *)(db)->hdb_db)->h_msgid)
+#define HDBSETMSGID(db,msgid) \
+ do { ((struct hdbldapdb *)(db)->hdb_db)->h_msgid = msgid; } while(0)
+#define HDB2BASE(dn) (((struct hdbldapdb *)(db)->hdb_db)->h_base)
+#define HDB2URL(dn) (((struct hdbldapdb *)(db)->hdb_db)->h_url)
+#define HDB2BINDDN(db) (((struct hdbldapdb *)(db)->hdb_db)->h_bind_dn)
+#define HDB2BINDPW(db) (((struct hdbldapdb *)(db)->hdb_db)->h_bind_password)
+#define HDB2CREATE(db) (((struct hdbldapdb *)(db)->hdb_db)->h_createbase)
+
+/*
+ *
+ */
+
+static char * krb5kdcentry_attrs[] = {
+ "cn",
+ "createTimestamp",
+ "creatorsName",
+ "krb5EncryptionType",
+ "krb5KDCFlags",
+ "krb5Key",
+ "krb5KeyVersionNumber",
+ "krb5MaxLife",
+ "krb5MaxRenew",
+ "krb5PasswordEnd",
+ "krb5PrincipalName",
+ "krb5PrincipalRealm",
+ "krb5ExtendedAttributes",
+ "krb5ValidEnd",
+ "krb5ValidStart",
+ "modifiersName",
+ "modifyTimestamp",
+ "objectClass",
+ "sambaAcctFlags",
+ "sambaKickoffTime",
+ "sambaNTPassword",
+ "sambaPwdLastSet",
+ "sambaPwdMustChange",
+ "uid",
+ NULL
+};
+
+static char *krb5principal_attrs[] = {
+ "cn",
+ "createTimestamp",
+ "creatorsName",
+ "krb5PrincipalName",
+ "krb5PrincipalRealm",
+ "modifiersName",
+ "modifyTimestamp",
+ "objectClass",
+ "uid",
+ NULL
+};
+
+static int
+LDAP_no_size_limit(krb5_context context, LDAP *lp)
+{
+ int ret, limit = LDAP_NO_LIMIT;
+
+ ret = ldap_set_option(lp, LDAP_OPT_SIZELIMIT, (const void *)&limit);
+ if (ret != LDAP_SUCCESS) {
+ krb5_set_error_message(context, HDB_ERR_BADVERSION,
+ "ldap_set_option: %s",
+ ldap_err2string(ret));
+ return HDB_ERR_BADVERSION;
+ }
+ return 0;
+}
+
+static int
+check_ldap(krb5_context context, HDB *db, int ret)
+{
+ switch (ret) {
+ case LDAP_SUCCESS:
+ return 0;
+ case LDAP_SERVER_DOWN:
+ LDAP_close(context, db);
+ return 1;
+ default:
+ return 1;
+ }
+}
+
+static krb5_error_code
+LDAP__setmod(LDAPMod *** modlist, int modop, const char *attribute,
+ int *pIndex)
+{
+ int cMods;
+
+ if (*modlist == NULL) {
+ *modlist = (LDAPMod **)ber_memcalloc(1, sizeof(LDAPMod *));
+ if (*modlist == NULL)
+ return ENOMEM;
+ }
+
+ for (cMods = 0; (*modlist)[cMods] != NULL; cMods++) {
+ if ((*modlist)[cMods]->mod_op == modop &&
+ strcasecmp((*modlist)[cMods]->mod_type, attribute) == 0) {
+ break;
+ }
+ }
+
+ *pIndex = cMods;
+
+ if ((*modlist)[cMods] == NULL) {
+ LDAPMod *mod;
+
+ *modlist = (LDAPMod **)ber_memrealloc(*modlist,
+ (cMods + 2) * sizeof(LDAPMod *));
+ if (*modlist == NULL)
+ return ENOMEM;
+
+ (*modlist)[cMods] = (LDAPMod *)ber_memalloc(sizeof(LDAPMod));
+ if ((*modlist)[cMods] == NULL)
+ return ENOMEM;
+
+ mod = (*modlist)[cMods];
+ mod->mod_op = modop;
+ mod->mod_type = ber_strdup(attribute);
+ if (mod->mod_type == NULL) {
+ ber_memfree(mod);
+ (*modlist)[cMods] = NULL;
+ return ENOMEM;
+ }
+
+ if (modop & LDAP_MOD_BVALUES) {
+ mod->mod_bvalues = NULL;
+ } else {
+ mod->mod_values = NULL;
+ }
+
+ (*modlist)[cMods + 1] = NULL;
+ }
+
+ return 0;
+}
+
+static krb5_error_code
+LDAP_addmod_len(LDAPMod *** modlist, int modop, const char *attribute,
+ unsigned char *value, size_t len)
+{
+ krb5_error_code ret;
+ int cMods, i = 0;
+
+ ret = LDAP__setmod(modlist, modop | LDAP_MOD_BVALUES, attribute, &cMods);
+ if (ret)
+ return ret;
+
+ if (value != NULL) {
+ struct berval **bv;
+
+ bv = (*modlist)[cMods]->mod_bvalues;
+ if (bv != NULL) {
+ for (i = 0; bv[i] != NULL; i++)
+ ;
+ bv = ber_memrealloc(bv, (i + 2) * sizeof(*bv));
+ } else
+ bv = ber_memalloc(2 * sizeof(*bv));
+ if (bv == NULL)
+ return ENOMEM;
+
+ (*modlist)[cMods]->mod_bvalues = bv;
+
+ bv[i] = ber_memalloc(sizeof(**bv));;
+ if (bv[i] == NULL)
+ return ENOMEM;
+
+ bv[i]->bv_val = (void *)value;
+ bv[i]->bv_len = len;
+
+ bv[i + 1] = NULL;
+ }
+
+ return 0;
+}
+
+static krb5_error_code
+LDAP_addmod(LDAPMod *** modlist, int modop, const char *attribute,
+ const char *value)
+{
+ int cMods, i = 0;
+ krb5_error_code ret;
+
+ ret = LDAP__setmod(modlist, modop, attribute, &cMods);
+ if (ret)
+ return ret;
+
+ if (value != NULL) {
+ char **bv;
+
+ bv = (*modlist)[cMods]->mod_values;
+ if (bv != NULL) {
+ for (i = 0; bv[i] != NULL; i++)
+ ;
+ bv = ber_memrealloc(bv, (i + 2) * sizeof(*bv));
+ } else
+ bv = ber_memalloc(2 * sizeof(*bv));
+ if (bv == NULL)
+ return ENOMEM;
+
+ (*modlist)[cMods]->mod_values = bv;
+
+ bv[i] = ber_strdup(value);
+ if (bv[i] == NULL)
+ return ENOMEM;
+
+ bv[i + 1] = NULL;
+ }
+
+ return 0;
+}
+
+static krb5_error_code
+LDAP_addmod_generalized_time(LDAPMod *** mods, int modop,
+ const char *attribute, KerberosTime * time)
+{
+ char buf[22];
+ struct tm *tm;
+
+ /* XXX not threadsafe */
+ tm = gmtime(time);
+ strftime(buf, sizeof(buf), "%Y%m%d%H%M%SZ", tm);
+
+ return LDAP_addmod(mods, modop, attribute, buf);
+}
+
+static krb5_error_code
+LDAP_addmod_integer(krb5_context context,
+ LDAPMod *** mods, int modop,
+ const char *attribute, unsigned long l)
+{
+ krb5_error_code ret;
+ char *buf;
+
+ ret = asprintf(&buf, "%ld", l);
+ if (ret < 0) {
+ krb5_set_error_message(context, ENOMEM,
+ "asprintf: out of memory:");
+ return ENOMEM;
+ }
+ ret = LDAP_addmod(mods, modop, attribute, buf);
+ free (buf);
+ return ret;
+}
+
+static krb5_error_code
+LDAP_get_string_value(HDB * db, LDAPMessage * entry,
+ const char *attribute, char **ptr)
+{
+ struct berval **vals;
+
+ vals = ldap_get_values_len(HDB2LDAP(db), entry, attribute);
+ if (vals == NULL || vals[0] == NULL) {
+ *ptr = NULL;
+ return HDB_ERR_NOENTRY;
+ }
+
+ *ptr = malloc(vals[0]->bv_len + 1);
+ if (*ptr == NULL) {
+ ldap_value_free_len(vals);
+ return ENOMEM;
+ }
+
+ memcpy(*ptr, vals[0]->bv_val, vals[0]->bv_len);
+ (*ptr)[vals[0]->bv_len] = 0;
+
+ ldap_value_free_len(vals);
+
+ return 0;
+}
+
+static krb5_error_code
+LDAP_get_integer_value(HDB * db, LDAPMessage * entry,
+ const char *attribute, int *ptr)
+{
+ krb5_error_code ret;
+ char *val;
+
+ ret = LDAP_get_string_value(db, entry, attribute, &val);
+ if (ret)
+ return ret;
+ *ptr = atoi(val);
+ free(val);
+ return 0;
+}
+
+static krb5_error_code
+LDAP_get_generalized_time_value(HDB * db, LDAPMessage * entry,
+ const char *attribute, KerberosTime * kt)
+{
+ char *tmp, *gentime;
+ struct tm tm;
+ int ret;
+
+ *kt = 0;
+
+ ret = LDAP_get_string_value(db, entry, attribute, &gentime);
+ if (ret)
+ return ret;
+
+ tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
+ if (tmp == NULL) {
+ free(gentime);
+ return HDB_ERR_NOENTRY;
+ }
+
+ free(gentime);
+
+ *kt = timegm(&tm);
+
+ return 0;
+}
+
+static int
+bervalstrcmp(struct berval *v, const char *str)
+{
+ size_t len = strlen(str);
+ return (v->bv_len == len) && strncasecmp(str, (char *)v->bv_val, len) == 0;
+}
+
+
+static krb5_error_code
+LDAP_entry2mods(krb5_context context, HDB * db, hdb_entry * ent,
+ LDAPMessage * msg, LDAPMod *** pmods, krb5_boolean *pis_new_entry)
+{
+ krb5_error_code ret;
+ krb5_boolean is_new_entry = FALSE;
+ char *tmp = NULL;
+ LDAPMod **mods = NULL;
+ hdb_entry orig;
+ unsigned long oflags, nflags;
+ int i;
+
+ krb5_boolean is_samba_account = FALSE;
+ krb5_boolean is_account = FALSE;
+ krb5_boolean is_heimdal_entry = FALSE;
+ krb5_boolean is_heimdal_principal = FALSE;
+
+ struct berval **vals;
+
+ *pmods = NULL;
+
+ if (msg != NULL) {
+
+ ret = LDAP_message2entry(context, db, msg, 0, &orig);
+ if (ret)
+ goto out;
+
+ vals = ldap_get_values_len(HDB2LDAP(db), msg, "objectClass");
+ if (vals) {
+ int num_objectclasses = ldap_count_values_len(vals);
+ for (i=0; i < num_objectclasses; i++) {
+ if (bervalstrcmp(vals[i], "sambaSamAccount"))
+ is_samba_account = TRUE;
+ else if (bervalstrcmp(vals[i], structural_object))
+ is_account = TRUE;
+ else if (bervalstrcmp(vals[i], "krb5Principal"))
+ is_heimdal_principal = TRUE;
+ else if (bervalstrcmp(vals[i], "krb5KDCEntry"))
+ is_heimdal_entry = TRUE;
+ }
+ ldap_value_free_len(vals);
+ }
+
+ /*
+ * If this is just a "account" entry and no other objectclass
+ * is hanging on this entry, it's really a new entry.
+ */
+ if (is_samba_account == FALSE && is_heimdal_principal == FALSE &&
+ is_heimdal_entry == FALSE) {
+ if (is_account == TRUE) {
+ is_new_entry = TRUE;
+ } else {
+ ret = HDB_ERR_NOENTRY;
+ goto out;
+ }
+ }
+ } else
+ is_new_entry = TRUE;
+
+ if (is_new_entry) {
+
+ /* to make it perfectly obvious we're depending on
+ * orig being intiialized to zero */
+ memset(&orig, 0, sizeof(orig));
+
+ /* account is the structural object class */
+ if (is_account == FALSE) {
+ ret = LDAP_addmod(&mods, LDAP_MOD_ADD, "objectClass", "top");
+ if (ret)
+ goto out;
+
+ ret = LDAP_addmod(&mods, LDAP_MOD_ADD, "objectClass",
+ structural_object);
+ is_account = TRUE;
+ if (ret)
+ goto out;
+ }
+
+ ret = LDAP_addmod(&mods, LDAP_MOD_ADD, "objectClass", "krb5Principal");
+ is_heimdal_principal = TRUE;
+ if (ret)
+ goto out;
+
+ ret = LDAP_addmod(&mods, LDAP_MOD_ADD, "objectClass", "krb5KDCEntry");
+ is_heimdal_entry = TRUE;
+ if (ret)
+ goto out;
+ }
+
+ if (is_new_entry ||
+ krb5_principal_compare(context, ent->principal, orig.principal)
+ == FALSE)
+ {
+ if (is_heimdal_principal || is_heimdal_entry) {
+
+ ret = krb5_unparse_name(context, ent->principal, &tmp);
+ if (ret)
+ goto out;
+
+ ret = LDAP_addmod(&mods, LDAP_MOD_REPLACE,
+ "krb5PrincipalName", tmp);
+ if (ret) {
+ free(tmp);
+ goto out;
+ }
+ free(tmp);
+ }
+
+ if (is_account || is_samba_account) {
+ ret = krb5_unparse_name_short(context, ent->principal, &tmp);
+ if (ret)
+ goto out;
+ ret = LDAP_addmod(&mods, LDAP_MOD_REPLACE, "uid", tmp);
+ if (ret) {
+ free(tmp);
+ goto out;
+ }
+ free(tmp);
+ }
+ }
+
+ if (is_heimdal_entry && (ent->kvno != orig.kvno || is_new_entry)) {
+ ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE,
+ "krb5KeyVersionNumber",
+ ent->kvno);
+ if (ret)
+ goto out;
+ }
+
+ if (is_heimdal_entry && ent->extensions) {
+ if (!is_new_entry) {
+ vals = ldap_get_values_len(HDB2LDAP(db), msg, "krb5ExtendedAttributes");
+ if (vals) {
+ ldap_value_free_len(vals);
+ ret = LDAP_addmod(&mods, LDAP_MOD_DELETE, "krb5ExtendedAttributes", NULL);
+ if (ret)
+ goto out;
+ }
+ }
+
+ for (i = 0; i < ent->extensions->len; i++) {
+ unsigned char *buf;
+ size_t size, sz = 0;
+
+ ASN1_MALLOC_ENCODE(HDB_extension, buf, size, &ent->extensions->val[i], &sz, ret);
+ if (ret)
+ goto out;
+ if (size != sz)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ ret = LDAP_addmod_len(&mods, LDAP_MOD_ADD, "krb5ExtendedAttributes", buf, sz);
+ if (ret)
+ goto out;
+ }
+ }
+
+ if (is_heimdal_entry && ent->valid_start) {
+ if (orig.valid_end == NULL
+ || (*(ent->valid_start) != *(orig.valid_start))) {
+ ret = LDAP_addmod_generalized_time(&mods, LDAP_MOD_REPLACE,
+ "krb5ValidStart",
+ ent->valid_start);
+ if (ret)
+ goto out;
+ }
+ }
+
+ if (ent->valid_end) {
+ if (orig.valid_end == NULL || (*(ent->valid_end) != *(orig.valid_end))) {
+ if (is_heimdal_entry) {
+ ret = LDAP_addmod_generalized_time(&mods, LDAP_MOD_REPLACE,
+ "krb5ValidEnd",
+ ent->valid_end);
+ if (ret)
+ goto out;
+ }
+ if (is_samba_account) {
+ ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE,
+ "sambaKickoffTime",
+ *(ent->valid_end));
+ if (ret)
+ goto out;
+ }
+ }
+ }
+
+ if (ent->pw_end) {
+ if (orig.pw_end == NULL || (*(ent->pw_end) != *(orig.pw_end))) {
+ if (is_heimdal_entry) {
+ ret = LDAP_addmod_generalized_time(&mods, LDAP_MOD_REPLACE,
+ "krb5PasswordEnd",
+ ent->pw_end);
+ if (ret)
+ goto out;
+ }
+
+ if (is_samba_account) {
+ ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE,
+ "sambaPwdMustChange",
+ *(ent->pw_end));
+ if (ret)
+ goto out;
+ }
+ }
+ }
+
+
+#if 0 /* we we have last_pw_change */
+ if (is_samba_account && ent->last_pw_change) {
+ if (orig.last_pw_change == NULL || (*(ent->last_pw_change) != *(orig.last_pw_change))) {
+ ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE,
+ "sambaPwdLastSet",
+ *(ent->last_pw_change));
+ if (ret)
+ goto out;
+ }
+ }
+#endif
+
+ if (is_heimdal_entry && ent->max_life) {
+ if (orig.max_life == NULL
+ || (*(ent->max_life) != *(orig.max_life))) {
+
+ ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE,
+ "krb5MaxLife",
+ *(ent->max_life));
+ if (ret)
+ goto out;
+ }
+ }
+
+ if (is_heimdal_entry && ent->max_renew) {
+ if (orig.max_renew == NULL
+ || (*(ent->max_renew) != *(orig.max_renew))) {
+
+ ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE,
+ "krb5MaxRenew",
+ *(ent->max_renew));
+ if (ret)
+ goto out;
+ }
+ }
+
+ oflags = HDBFlags2int(orig.flags);
+ nflags = HDBFlags2int(ent->flags);
+
+ if (is_heimdal_entry && oflags != nflags) {
+
+ ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE,
+ "krb5KDCFlags",
+ nflags);
+ if (ret)
+ goto out;
+ }
+
+ /* Remove keys if they exists, and then replace keys. */
+ if (!is_new_entry && orig.keys.len > 0) {
+ vals = ldap_get_values_len(HDB2LDAP(db), msg, "krb5Key");
+ if (vals) {
+ ldap_value_free_len(vals);
+
+ ret = LDAP_addmod(&mods, LDAP_MOD_DELETE, "krb5Key", NULL);
+ if (ret)
+ goto out;
+ }
+ }
+
+ for (i = 0; i < ent->keys.len; i++) {
+
+ if (is_samba_account
+ && ent->keys.val[i].key.keytype == ETYPE_ARCFOUR_HMAC_MD5) {
+ char *ntHexPassword;
+ char *nt;
+ time_t now = time(NULL);
+
+ /* the key might have been 'sealed', but samba passwords
+ are clear in the directory */
+ ret = hdb_unseal_key(context, db, &ent->keys.val[i]);
+ if (ret)
+ goto out;
+
+ nt = ent->keys.val[i].key.keyvalue.data;
+ /* store in ntPassword, not krb5key */
+ ret = hex_encode(nt, 16, &ntHexPassword);
+ if (ret < 0) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "hdb-ldap: failed to "
+ "hex encode key");
+ goto out;
+ }
+ ret = LDAP_addmod(&mods, LDAP_MOD_REPLACE, "sambaNTPassword",
+ ntHexPassword);
+ free(ntHexPassword);
+ if (ret)
+ goto out;
+ ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE,
+ "sambaPwdLastSet", now);
+ if (ret)
+ goto out;
+
+ /* have to kill the LM passwod if it exists */
+ vals = ldap_get_values_len(HDB2LDAP(db), msg, "sambaLMPassword");
+ if (vals) {
+ ldap_value_free_len(vals);
+ ret = LDAP_addmod(&mods, LDAP_MOD_DELETE,
+ "sambaLMPassword", NULL);
+ if (ret)
+ goto out;
+ }
+
+ } else if (is_heimdal_entry) {
+ unsigned char *buf;
+ size_t len, buf_size;
+
+ ASN1_MALLOC_ENCODE(Key, buf, buf_size, &ent->keys.val[i], &len, ret);
+ if (ret)
+ goto out;
+ if(buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ /* addmod_len _owns_ the key, doesn't need to copy it */
+ ret = LDAP_addmod_len(&mods, LDAP_MOD_ADD, "krb5Key", buf, len);
+ if (ret)
+ goto out;
+ }
+ }
+
+ if (ent->etypes) {
+ int add_krb5EncryptionType = 0;
+
+ /*
+ * Only add/modify krb5EncryptionType if it's a new heimdal
+ * entry or krb5EncryptionType already exists on the entry.
+ */
+
+ if (!is_new_entry) {
+ vals = ldap_get_values_len(HDB2LDAP(db), msg, "krb5EncryptionType");
+ if (vals) {
+ ldap_value_free_len(vals);
+ ret = LDAP_addmod(&mods, LDAP_MOD_DELETE, "krb5EncryptionType",
+ NULL);
+ if (ret)
+ goto out;
+ add_krb5EncryptionType = 1;
+ }
+ } else if (is_heimdal_entry)
+ add_krb5EncryptionType = 1;
+
+ if (add_krb5EncryptionType) {
+ for (i = 0; i < ent->etypes->len; i++) {
+ if (is_samba_account &&
+ ent->keys.val[i].key.keytype == ETYPE_ARCFOUR_HMAC_MD5)
+ {
+ ;
+ } else if (is_heimdal_entry) {
+ ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_ADD,
+ "krb5EncryptionType",
+ ent->etypes->val[i]);
+ if (ret)
+ goto out;
+ }
+ }
+ }
+ }
+
+ /* for clarity */
+ ret = 0;
+
+ out:
+
+ *pis_new_entry = is_new_entry;
+
+ if (ret == 0)
+ *pmods = mods;
+ else if (mods != NULL) {
+ ldap_mods_free(mods, 1);
+ *pmods = NULL;
+ }
+
+ if (msg)
+ hdb_free_entry(context, db, &orig);
+
+ return ret;
+}
+
+static krb5_error_code
+LDAP_dn2principal(krb5_context context, HDB * db, const char *dn,
+ krb5_principal * principal)
+{
+ krb5_error_code ret;
+ int rc;
+ const char *filter = "(objectClass=krb5Principal)";
+ LDAPMessage *res = NULL, *e;
+ char *p;
+
+ ret = LDAP_no_size_limit(context, HDB2LDAP(db));
+ if (ret)
+ goto out;
+
+ rc = ldap_search_ext_s(HDB2LDAP(db), dn, LDAP_SCOPE_SUBTREE,
+ filter, krb5principal_attrs, 0,
+ NULL, NULL, NULL,
+ 0, &res);
+ if (check_ldap(context, db, rc)) {
+ ret = HDB_ERR_NOENTRY;
+ krb5_set_error_message(context, ret, "ldap_search_ext_s: "
+ "filter: %s error: %s",
+ filter, ldap_err2string(rc));
+ goto out;
+ }
+
+ e = ldap_first_entry(HDB2LDAP(db), res);
+ if (e == NULL) {
+ ret = HDB_ERR_NOENTRY;
+ goto out;
+ }
+
+ ret = LDAP_get_string_value(db, e, "krb5PrincipalName", &p);
+ if (ret) {
+ ret = HDB_ERR_NOENTRY;
+ goto out;
+ }
+
+ ret = krb5_parse_name(context, p, principal);
+ free(p);
+
+ out:
+ if (res)
+ ldap_msgfree(res);
+
+ return ret;
+}
+
+static int
+need_quote(unsigned char c)
+{
+ return (c & 0x80) ||
+ (c < 32) ||
+ (c == '(') ||
+ (c == ')') ||
+ (c == '*') ||
+ (c == '\\') ||
+ (c == 0x7f);
+}
+
+static const char hexchar[] = "0123456789ABCDEF";
+
+static krb5_error_code
+escape_value(krb5_context context, const char *unquoted, char **quoted)
+{
+ size_t i, len;
+
+ for (i = 0, len = 0; unquoted[i] != '\0'; i++, len++) {
+ if (need_quote((unsigned char)unquoted[i]))
+ len += 2;
+ }
+
+ *quoted = malloc(len + 1);
+ if (*quoted == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ for (i = 0; unquoted[0] ; unquoted++) {
+ if (need_quote((unsigned char)unquoted[0])) {
+ (*quoted)[i++] = '\\';
+ (*quoted)[i++] = hexchar[(unquoted[0] >> 4) & 0xf];
+ (*quoted)[i++] = hexchar[(unquoted[0] ) & 0xf];
+ } else
+ (*quoted)[i++] = (char)unquoted[0];
+ }
+ (*quoted)[i] = '\0';
+ return 0;
+}
+
+
+static krb5_error_code
+LDAP__lookup_princ(krb5_context context,
+ HDB *db,
+ const char *princname,
+ const char *userid,
+ LDAPMessage **msg)
+{
+ krb5_error_code ret;
+ int rc;
+ char *quote, *filter = NULL;
+
+ ret = LDAP__connect(context, db);
+ if (ret)
+ return ret;
+
+ /*
+ * Quote searches that contain filter language, this quote
+ * searches for *@REALM, which takes very long time.
+ */
+
+ ret = escape_value(context, princname, &quote);
+ if (ret)
+ goto out;
+
+ rc = asprintf(&filter,
+ "(&(objectClass=krb5Principal)(krb5PrincipalName=%s))",
+ quote);
+ free(quote);
+
+ if (rc < 0) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ goto out;
+ }
+
+ ret = LDAP_no_size_limit(context, HDB2LDAP(db));
+ if (ret)
+ goto out;
+
+ rc = ldap_search_ext_s(HDB2LDAP(db), HDB2BASE(db),
+ LDAP_SCOPE_SUBTREE, filter,
+ krb5kdcentry_attrs, 0,
+ NULL, NULL, NULL,
+ 0, msg);
+ if (check_ldap(context, db, rc)) {
+ ret = HDB_ERR_NOENTRY;
+ krb5_set_error_message(context, ret, "ldap_search_ext_s: "
+ "filter: %s - error: %s",
+ filter, ldap_err2string(rc));
+ goto out;
+ }
+
+ if (userid && ldap_count_entries(HDB2LDAP(db), *msg) == 0) {
+ free(filter);
+ filter = NULL;
+ ldap_msgfree(*msg);
+ *msg = NULL;
+
+ ret = escape_value(context, userid, &quote);
+ if (ret)
+ goto out;
+
+ rc = asprintf(&filter,
+ "(&(|(objectClass=sambaSamAccount)(objectClass=%s))(uid=%s))",
+ structural_object, quote);
+ free(quote);
+ if (rc < 0) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "asprintf: out of memory");
+ goto out;
+ }
+
+ ret = LDAP_no_size_limit(context, HDB2LDAP(db));
+ if (ret)
+ goto out;
+
+ rc = ldap_search_ext_s(HDB2LDAP(db), HDB2BASE(db), LDAP_SCOPE_SUBTREE,
+ filter, krb5kdcentry_attrs, 0,
+ NULL, NULL, NULL,
+ 0, msg);
+ if (check_ldap(context, db, rc)) {
+ ret = HDB_ERR_NOENTRY;
+ krb5_set_error_message(context, ret,
+ "ldap_search_ext_s: filter: %s error: %s",
+ filter, ldap_err2string(rc));
+ goto out;
+ }
+ }
+
+ ret = 0;
+
+ out:
+ if (filter)
+ free(filter);
+
+ return ret;
+}
+
+static krb5_error_code
+LDAP_principal2message(krb5_context context, HDB * db,
+ krb5_const_principal princ, LDAPMessage ** msg)
+{
+ char *name, *name_short = NULL;
+ krb5_error_code ret;
+ krb5_realm *r, *r0;
+
+ *msg = NULL;
+
+ ret = krb5_unparse_name(context, princ, &name);
+ if (ret)
+ return ret;
+
+ ret = krb5_get_default_realms(context, &r0);
+ if(ret) {
+ free(name);
+ return ret;
+ }
+ for (r = r0; *r != NULL; r++) {
+ if(strcmp(krb5_principal_get_realm(context, princ), *r) == 0) {
+ ret = krb5_unparse_name_short(context, princ, &name_short);
+ if (ret) {
+ krb5_free_host_realm(context, r0);
+ free(name);
+ return ret;
+ }
+ break;
+ }
+ }
+ krb5_free_host_realm(context, r0);
+
+ ret = LDAP__lookup_princ(context, db, name, name_short, msg);
+ free(name);
+ free(name_short);
+
+ return ret;
+}
+
+/*
+ * Construct an hdb_entry from a directory entry.
+ */
+static krb5_error_code
+LDAP_message2entry(krb5_context context, HDB * db, LDAPMessage * msg,
+ int flags, hdb_entry * ent)
+{
+ char *unparsed_name = NULL, *dn = NULL, *ntPasswordIN = NULL;
+ char *samba_acct_flags = NULL;
+ struct berval **keys;
+ struct berval **extensions;
+ struct berval **vals;
+ int tmp, tmp_time, i, ret, have_arcfour = 0;
+
+ memset(ent, 0, sizeof(*ent));
+ ent->flags = int2HDBFlags(0);
+
+ ret = LDAP_get_string_value(db, msg, "krb5PrincipalName", &unparsed_name);
+ if (ret == 0) {
+ ret = krb5_parse_name(context, unparsed_name, &ent->principal);
+ if (ret)
+ goto out;
+ } else {
+ ret = LDAP_get_string_value(db, msg, "uid",
+ &unparsed_name);
+ if (ret == 0) {
+ ret = krb5_parse_name(context, unparsed_name, &ent->principal);
+ if (ret)
+ goto out;
+ } else {
+ krb5_set_error_message(context, HDB_ERR_NOENTRY,
+ "hdb-ldap: ldap entry missing"
+ "principal name");
+ return HDB_ERR_NOENTRY;
+ }
+ }
+
+ {
+ int integer;
+ ret = LDAP_get_integer_value(db, msg, "krb5KeyVersionNumber",
+ &integer);
+ if (ret)
+ ent->kvno = 0;
+ else
+ ent->kvno = integer;
+ }
+
+ keys = ldap_get_values_len(HDB2LDAP(db), msg, "krb5Key");
+ if (keys != NULL) {
+ size_t l;
+
+ ent->keys.len = ldap_count_values_len(keys);
+ ent->keys.val = (Key *) calloc(ent->keys.len, sizeof(Key));
+ if (ent->keys.val == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "calloc: out of memory");
+ goto out;
+ }
+ for (i = 0; i < ent->keys.len; i++) {
+ decode_Key((unsigned char *) keys[i]->bv_val,
+ (size_t) keys[i]->bv_len, &ent->keys.val[i], &l);
+ }
+ ber_bvecfree(keys);
+ } else {
+#if 1
+ /*
+ * This violates the ASN1 but it allows a principal to
+ * be related to a general directory entry without creating
+ * the keys. Hopefully it's OK.
+ */
+ ent->keys.len = 0;
+ ent->keys.val = NULL;
+#else
+ ret = HDB_ERR_NOENTRY;
+ goto out;
+#endif
+ }
+
+ extensions = ldap_get_values_len(HDB2LDAP(db), msg, "krb5ExtendedAttributes");
+ if (extensions != NULL) {
+ size_t l;
+
+ ent->extensions = calloc(1, sizeof(*(ent->extensions)));
+ if (ent->extensions == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ ent->extensions->len = ldap_count_values_len(extensions);
+ ent->extensions->val = (HDB_extension *) calloc(ent->extensions->len, sizeof(HDB_extension));
+ if (ent->extensions->val == NULL) {
+ ent->extensions->len = 0;
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ for (i = 0; i < ent->extensions->len; i++) {
+ ret = decode_HDB_extension((unsigned char *) extensions[i]->bv_val,
+ (size_t) extensions[i]->bv_len, &ent->extensions->val[i], &l);
+ if (ret)
+ krb5_set_error_message(context, ret, "decode_HDB_extension failed");
+ }
+ ber_bvecfree(extensions);
+ } else {
+ ent->extensions = NULL;
+ }
+
+ vals = ldap_get_values_len(HDB2LDAP(db), msg, "krb5EncryptionType");
+ if (vals != NULL) {
+ ent->etypes = malloc(sizeof(*(ent->etypes)));
+ if (ent->etypes == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret,"malloc: out of memory");
+ goto out;
+ }
+ ent->etypes->len = ldap_count_values_len(vals);
+ ent->etypes->val = calloc(ent->etypes->len,
+ sizeof(ent->etypes->val[0]));
+ if (ent->etypes->val == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ ent->etypes->len = 0;
+ goto out;
+ }
+ for (i = 0; i < ent->etypes->len; i++) {
+ char *buf;
+
+ buf = malloc(vals[i]->bv_len + 1);
+ if (buf == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ goto out;
+ }
+ memcpy(buf, vals[i]->bv_val, vals[i]->bv_len);
+ buf[vals[i]->bv_len] = '\0';
+ ent->etypes->val[i] = atoi(buf);
+ free(buf);
+ }
+ ldap_value_free_len(vals);
+ }
+
+ for (i = 0; i < ent->keys.len; i++) {
+ if (ent->keys.val[i].key.keytype == ETYPE_ARCFOUR_HMAC_MD5) {
+ have_arcfour = 1;
+ break;
+ }
+ }
+
+ /* manually construct the NT (type 23) key */
+ ret = LDAP_get_string_value(db, msg, "sambaNTPassword", &ntPasswordIN);
+ if (ret == 0 && have_arcfour == 0) {
+ unsigned *etypes;
+ Key *ks;
+
+ ks = realloc(ent->keys.val,
+ (ent->keys.len + 1) *
+ sizeof(ent->keys.val[0]));
+ if (ks == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ goto out;
+ }
+ ent->keys.val = ks;
+ memset(&ent->keys.val[ent->keys.len], 0, sizeof(Key));
+ ent->keys.val[ent->keys.len].key.keytype = ETYPE_ARCFOUR_HMAC_MD5;
+ ret = krb5_data_alloc (&ent->keys.val[ent->keys.len].key.keyvalue, 16);
+ if (ret) {
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ ret = ENOMEM;
+ goto out;
+ }
+ ret = hex_decode(ntPasswordIN,
+ ent->keys.val[ent->keys.len].key.keyvalue.data, 16);
+ ent->keys.len++;
+ if (ret == -1) {
+ krb5_set_error_message(context, ret = EINVAL,
+ "invalid hex encoding of password");
+ goto out;
+ }
+
+ if (ent->etypes == NULL) {
+ ent->etypes = malloc(sizeof(*(ent->etypes)));
+ if (ent->etypes == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ goto out;
+ }
+ ent->etypes->val = NULL;
+ ent->etypes->len = 0;
+ }
+
+ for (i = 0; i < ent->etypes->len; i++)
+ if (ent->etypes->val[i] == ETYPE_ARCFOUR_HMAC_MD5)
+ break;
+ /* If there is no ARCFOUR enctype, add one */
+ if (i == ent->etypes->len) {
+ etypes = realloc(ent->etypes->val,
+ (ent->etypes->len + 1) *
+ sizeof(ent->etypes->val[0]));
+ if (etypes == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ goto out;
+ }
+ ent->etypes->val = etypes;
+ ent->etypes->val[ent->etypes->len] =
+ ETYPE_ARCFOUR_HMAC_MD5;
+ ent->etypes->len++;
+ }
+ }
+
+ ret = LDAP_get_generalized_time_value(db, msg, "createTimestamp",
+ &ent->created_by.time);
+ if (ret)
+ ent->created_by.time = time(NULL);
+
+ ent->created_by.principal = NULL;
+
+ if (flags & HDB_F_ADMIN_DATA) {
+ ret = LDAP_get_string_value(db, msg, "creatorsName", &dn);
+ if (ret == 0) {
+ LDAP_dn2principal(context, db, dn, &ent->created_by.principal);
+ free(dn);
+ }
+
+ ent->modified_by = calloc(1, sizeof(*ent->modified_by));
+ if (ent->modified_by == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ goto out;
+ }
+
+ ret = LDAP_get_generalized_time_value(db, msg, "modifyTimestamp",
+ &ent->modified_by->time);
+ if (ret == 0) {
+ ret = LDAP_get_string_value(db, msg, "modifiersName", &dn);
+ if (ret == 0) {
+ LDAP_dn2principal(context, db, dn, &ent->modified_by->principal);
+ free(dn);
+ } else {
+ free(ent->modified_by);
+ ent->modified_by = NULL;
+ }
+ }
+ }
+
+ ent->valid_start = malloc(sizeof(*ent->valid_start));
+ if (ent->valid_start == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ goto out;
+ }
+ ret = LDAP_get_generalized_time_value(db, msg, "krb5ValidStart",
+ ent->valid_start);
+ if (ret) {
+ /* OPTIONAL */
+ free(ent->valid_start);
+ ent->valid_start = NULL;
+ }
+
+ ent->valid_end = malloc(sizeof(*ent->valid_end));
+ if (ent->valid_end == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ goto out;
+ }
+ ret = LDAP_get_generalized_time_value(db, msg, "krb5ValidEnd",
+ ent->valid_end);
+ if (ret) {
+ /* OPTIONAL */
+ free(ent->valid_end);
+ ent->valid_end = NULL;
+ }
+
+ ret = LDAP_get_integer_value(db, msg, "sambaKickoffTime", &tmp_time);
+ if (ret == 0) {
+ if (ent->valid_end == NULL) {
+ ent->valid_end = malloc(sizeof(*ent->valid_end));
+ if (ent->valid_end == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ goto out;
+ }
+ }
+ *ent->valid_end = tmp_time;
+ }
+
+ ent->pw_end = malloc(sizeof(*ent->pw_end));
+ if (ent->pw_end == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ goto out;
+ }
+ ret = LDAP_get_generalized_time_value(db, msg, "krb5PasswordEnd",
+ ent->pw_end);
+ if (ret) {
+ /* OPTIONAL */
+ free(ent->pw_end);
+ ent->pw_end = NULL;
+ }
+
+ ret = LDAP_get_integer_value(db, msg, "sambaPwdLastSet", &tmp_time);
+ if (ret == 0) {
+ time_t delta;
+
+ delta = krb5_config_get_time_default(context, NULL,
+ 0,
+ "kadmin",
+ "password_lifetime",
+ NULL);
+
+ if (delta) {
+ if (ent->pw_end == NULL) {
+ ent->pw_end = malloc(sizeof(*ent->pw_end));
+ if (ent->pw_end == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ goto out;
+ }
+ }
+
+ *ent->pw_end = tmp_time + delta;
+ }
+ }
+
+ ret = LDAP_get_integer_value(db, msg, "sambaPwdMustChange", &tmp_time);
+ if (ret == 0) {
+ if (ent->pw_end == NULL) {
+ ent->pw_end = malloc(sizeof(*ent->pw_end));
+ if (ent->pw_end == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ goto out;
+ }
+ }
+ *ent->pw_end = tmp_time;
+ }
+
+ /* OPTIONAL */
+ ret = LDAP_get_integer_value(db, msg, "sambaPwdLastSet", &tmp_time);
+ if (ret == 0)
+ hdb_entry_set_pw_change_time(context, ent, tmp_time);
+
+ {
+ int max_life;
+
+ ent->max_life = malloc(sizeof(*ent->max_life));
+ if (ent->max_life == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ goto out;
+ }
+ ret = LDAP_get_integer_value(db, msg, "krb5MaxLife", &max_life);
+ if (ret) {
+ free(ent->max_life);
+ ent->max_life = NULL;
+ } else
+ *ent->max_life = max_life;
+ }
+
+ {
+ int max_renew;
+
+ ent->max_renew = malloc(sizeof(*ent->max_renew));
+ if (ent->max_renew == NULL) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ goto out;
+ }
+ ret = LDAP_get_integer_value(db, msg, "krb5MaxRenew", &max_renew);
+ if (ret) {
+ free(ent->max_renew);
+ ent->max_renew = NULL;
+ } else
+ *ent->max_renew = max_renew;
+ }
+
+ ret = LDAP_get_integer_value(db, msg, "krb5KDCFlags", &tmp);
+ if (ret)
+ tmp = 0;
+
+ ent->flags = int2HDBFlags(tmp);
+
+ /* Try and find Samba flags to put into the mix */
+ ret = LDAP_get_string_value(db, msg, "sambaAcctFlags", &samba_acct_flags);
+ if (ret == 0) {
+ /* parse the [UXW...] string:
+
+ 'N' No password
+ 'D' Disabled
+ 'H' Homedir required
+ 'T' Temp account.
+ 'U' User account (normal)
+ 'M' MNS logon user account - what is this ?
+ 'W' Workstation account
+ 'S' Server account
+ 'L' Locked account
+ 'X' No Xpiry on password
+ 'I' Interdomain trust account
+
+ */
+
+ int flags_len = strlen(samba_acct_flags);
+
+ if (flags_len < 2)
+ goto out2;
+
+ if (samba_acct_flags[0] != '['
+ || samba_acct_flags[flags_len - 1] != ']')
+ goto out2;
+
+ /* Allow forwarding */
+ if (samba_forwardable)
+ ent->flags.forwardable = TRUE;
+
+ for (i=0; i < flags_len; i++) {
+ switch (samba_acct_flags[i]) {
+ case ' ':
+ case '[':
+ case ']':
+ break;
+ case 'N':
+ /* how to handle no password in kerberos? */
+ break;
+ case 'D':
+ ent->flags.invalid = TRUE;
+ break;
+ case 'H':
+ break;
+ case 'T':
+ /* temp duplicate */
+ ent->flags.invalid = TRUE;
+ break;
+ case 'U':
+ ent->flags.client = TRUE;
+ break;
+ case 'M':
+ break;
+ case 'W':
+ case 'S':
+ ent->flags.server = TRUE;
+ ent->flags.client = TRUE;
+ break;
+ case 'L':
+ ent->flags.invalid = TRUE;
+ break;
+ case 'X':
+ if (ent->pw_end) {
+ free(ent->pw_end);
+ ent->pw_end = NULL;
+ }
+ break;
+ case 'I':
+ ent->flags.server = TRUE;
+ ent->flags.client = TRUE;
+ break;
+ }
+ }
+ out2:
+ free(samba_acct_flags);
+ }
+
+ ret = 0;
+
+out:
+ free(unparsed_name);
+ free(ntPasswordIN);
+
+ if (ret)
+ hdb_free_entry(context, db, ent);
+
+ return ret;
+}
+
+static krb5_error_code
+LDAP_close(krb5_context context, HDB * db)
+{
+ if (HDB2LDAP(db)) {
+ ldap_unbind_ext(HDB2LDAP(db), NULL, NULL);
+ ((struct hdbldapdb *)db->hdb_db)->h_lp = NULL;
+ }
+
+ return 0;
+}
+
+static krb5_error_code
+LDAP_lock(krb5_context context, HDB * db, int operation)
+{
+ return 0;
+}
+
+static krb5_error_code
+LDAP_unlock(krb5_context context, HDB * db)
+{
+ return 0;
+}
+
+static krb5_error_code
+LDAP_seq(krb5_context context, HDB * db, unsigned flags, hdb_entry * entry)
+{
+ int msgid, rc, parserc;
+ krb5_error_code ret;
+ LDAPMessage *e;
+
+ msgid = HDB2MSGID(db);
+ if (msgid < 0)
+ return HDB_ERR_NOENTRY;
+
+ do {
+ rc = ldap_result(HDB2LDAP(db), msgid, LDAP_MSG_ONE, NULL, &e);
+ switch (rc) {
+ case LDAP_RES_SEARCH_REFERENCE:
+ ldap_msgfree(e);
+ ret = 0;
+ break;
+ case LDAP_RES_SEARCH_ENTRY:
+ /* We have an entry. Parse it. */
+ ret = LDAP_message2entry(context, db, e, flags, entry);
+ ldap_msgfree(e);
+ break;
+ case LDAP_RES_SEARCH_RESULT:
+ /* We're probably at the end of the results. If not, abandon. */
+ parserc =
+ ldap_parse_result(HDB2LDAP(db), e, NULL, NULL, NULL,
+ NULL, NULL, 1);
+ ret = HDB_ERR_NOENTRY;
+ if (parserc != LDAP_SUCCESS
+ && parserc != LDAP_MORE_RESULTS_TO_RETURN) {
+ krb5_set_error_message(context, ret, "ldap_parse_result: %s",
+ ldap_err2string(parserc));
+ ldap_abandon_ext(HDB2LDAP(db), msgid, NULL, NULL);
+ }
+ HDBSETMSGID(db, -1);
+ break;
+ case LDAP_SERVER_DOWN:
+ ldap_msgfree(e);
+ LDAP_close(context, db);
+ HDBSETMSGID(db, -1);
+ ret = ENETDOWN;
+ break;
+ default:
+ /* Some unspecified error (timeout?). Abandon. */
+ ldap_msgfree(e);
+ ldap_abandon_ext(HDB2LDAP(db), msgid, NULL, NULL);
+ ret = HDB_ERR_NOENTRY;
+ HDBSETMSGID(db, -1);
+ break;
+ }
+ } while (rc == LDAP_RES_SEARCH_REFERENCE);
+
+ if (ret == 0) {
+ if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) {
+ ret = hdb_unseal_keys(context, db, entry);
+ if (ret)
+ hdb_free_entry(context, db, entry);
+ }
+ }
+
+ return ret;
+}
+
+static krb5_error_code
+LDAP_firstkey(krb5_context context, HDB *db, unsigned flags,
+ hdb_entry *entry)
+{
+ krb5_error_code ret;
+ int msgid;
+
+ ret = LDAP__connect(context, db);
+ if (ret)
+ return ret;
+
+ ret = LDAP_no_size_limit(context, HDB2LDAP(db));
+ if (ret)
+ return ret;
+
+ ret = ldap_search_ext(HDB2LDAP(db), HDB2BASE(db),
+ LDAP_SCOPE_SUBTREE,
+ "(|(objectClass=krb5Principal)(objectClass=sambaSamAccount))",
+ krb5kdcentry_attrs, 0,
+ NULL, NULL, NULL, 0, &msgid);
+ if (ret != LDAP_SUCCESS || msgid < 0)
+ return HDB_ERR_NOENTRY;
+
+ HDBSETMSGID(db, msgid);
+
+ return LDAP_seq(context, db, flags, entry);
+}
+
+static krb5_error_code
+LDAP_nextkey(krb5_context context, HDB * db, unsigned flags,
+ hdb_entry * entry)
+{
+ return LDAP_seq(context, db, flags, entry);
+}
+
+static krb5_error_code
+LDAP__connect(krb5_context context, HDB * db)
+{
+ int rc, version = LDAP_VERSION3;
+ /*
+ * Empty credentials to do a SASL bind with LDAP. Note that empty
+ * different from NULL credentials. If you provide NULL
+ * credentials instead of empty credentials you will get a SASL
+ * bind in progress message.
+ */
+ struct berval bv = { 0, "" };
+ const char *sasl_method = "EXTERNAL";
+ const char *bind_dn = NULL;
+
+ if (HDB2BINDDN(db) != NULL && HDB2BINDPW(db) != NULL) {
+ /* A bind DN was specified; use SASL SIMPLE */
+ bind_dn = HDB2BINDDN(db);
+ sasl_method = LDAP_SASL_SIMPLE;
+ bv.bv_val = HDB2BINDPW(db);
+ bv.bv_len = strlen(bv.bv_val);
+ }
+
+ if (HDB2LDAP(db)) {
+ /* connection has been opened. ping server. */
+ struct sockaddr_un addr;
+ socklen_t len = sizeof(addr);
+ int sd;
+
+ if (ldap_get_option(HDB2LDAP(db), LDAP_OPT_DESC, &sd) == 0 &&
+ getpeername(sd, (struct sockaddr *) &addr, &len) < 0) {
+ /* the other end has died. reopen. */
+ LDAP_close(context, db);
+ }
+ }
+
+ if (HDB2LDAP(db) != NULL) /* server is UP */
+ return 0;
+
+ rc = ldap_initialize(&((struct hdbldapdb *)db->hdb_db)->h_lp, HDB2URL(db));
+ if (rc != LDAP_SUCCESS) {
+ krb5_set_error_message(context, HDB_ERR_NOENTRY, "ldap_initialize: %s",
+ ldap_err2string(rc));
+ return HDB_ERR_NOENTRY;
+ }
+
+ rc = ldap_set_option(HDB2LDAP(db), LDAP_OPT_PROTOCOL_VERSION,
+ (const void *)&version);
+ if (rc != LDAP_SUCCESS) {
+ krb5_set_error_message(context, HDB_ERR_BADVERSION,
+ "ldap_set_option: %s", ldap_err2string(rc));
+ LDAP_close(context, db);
+ return HDB_ERR_BADVERSION;
+ }
+
+ if (((struct hdbldapdb *)db->hdb_db)->h_start_tls) {
+ rc = ldap_start_tls_s(HDB2LDAP(db), NULL, NULL);
+
+ if (rc != LDAP_SUCCESS) {
+ krb5_set_error_message(context, HDB_ERR_BADVERSION,
+ "ldap_start_tls_s: %s", ldap_err2string(rc));
+ LDAP_close(context, db);
+ return HDB_ERR_BADVERSION;
+ }
+ }
+
+ rc = ldap_sasl_bind_s(HDB2LDAP(db), bind_dn, sasl_method, &bv,
+ NULL, NULL, NULL);
+ if (rc != LDAP_SUCCESS) {
+ krb5_set_error_message(context, HDB_ERR_BADVERSION,
+ "ldap_sasl_bind_s: %s", ldap_err2string(rc));
+ LDAP_close(context, db);
+ return HDB_ERR_BADVERSION;
+ }
+
+ return 0;
+}
+
+static krb5_error_code
+LDAP_open(krb5_context context, HDB * db, int flags, mode_t mode)
+{
+ /* Not the right place for this. */
+#ifdef HAVE_SIGACTION
+ struct sigaction sa;
+
+ sa.sa_flags = 0;
+ sa.sa_handler = SIG_IGN;
+ sigemptyset(&sa.sa_mask);
+
+ sigaction(SIGPIPE, &sa, NULL);
+#else
+ signal(SIGPIPE, SIG_IGN);
+#endif /* HAVE_SIGACTION */
+
+ return LDAP__connect(context, db);
+}
+
+static krb5_error_code
+LDAP_fetch_kvno(krb5_context context, HDB * db, krb5_const_principal principal,
+ unsigned flags, krb5_kvno kvno, hdb_entry * entry)
+{
+ LDAPMessage *msg, *e;
+ krb5_error_code ret;
+
+ ret = LDAP_principal2message(context, db, principal, &msg);
+ if (ret)
+ return ret;
+
+ e = ldap_first_entry(HDB2LDAP(db), msg);
+ if (e == NULL) {
+ ret = HDB_ERR_NOENTRY;
+ goto out;
+ }
+
+ ret = LDAP_message2entry(context, db, e, flags, entry);
+ if (ret == 0) {
+ if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) {
+ ret = hdb_unseal_keys(context, db, entry);
+ if (ret)
+ hdb_free_entry(context, db, entry);
+ }
+ }
+
+ out:
+ ldap_msgfree(msg);
+
+ return ret;
+}
+
+#if 0
+static krb5_error_code
+LDAP_fetch(krb5_context context, HDB * db, krb5_const_principal principal,
+ unsigned flags, hdb_entry * entry)
+{
+ return LDAP_fetch_kvno(context, db, principal,
+ flags & (~HDB_F_KVNO_SPECIFIED), 0, entry);
+}
+#endif
+
+static krb5_error_code
+LDAP_store(krb5_context context, HDB * db, unsigned flags,
+ hdb_entry * entry)
+{
+ LDAPMod **mods = NULL;
+ krb5_error_code ret;
+ const char *errfn;
+ int rc;
+ LDAPMessage *msg = NULL, *e = NULL;
+ char *dn = NULL, *name = NULL;
+ krb5_boolean is_new_entry;
+
+ if ((flags & HDB_F_PRECHECK))
+ return 0; /* we can't guarantee whether we'll be able to perform it */
+
+ ret = LDAP_principal2message(context, db, entry->principal, &msg);
+ if (ret == 0)
+ e = ldap_first_entry(HDB2LDAP(db), msg);
+
+ ret = krb5_unparse_name(context, entry->principal, &name);
+ if (ret) {
+ free(name);
+ return ret;
+ }
+
+ ret = hdb_seal_keys(context, db, entry);
+ if (ret)
+ goto out;
+
+ /* turn new entry into LDAPMod array */
+ ret = LDAP_entry2mods(context, db, entry, e, &mods, &is_new_entry);
+ if (ret)
+ goto out;
+
+ if (e == NULL) {
+ ret = asprintf(&dn, "krb5PrincipalName=%s,%s", name, HDB2CREATE(db));
+ if (ret < 0) {
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "asprintf: out of memory");
+ goto out;
+ }
+ } else if ((flags & HDB_F_REPLACE) || (is_new_entry)) {
+ /* Entry exists, and we're allowed to replace it. */
+ /* Entry may also exist but need to be modified to create a new principal. */
+ dn = ldap_get_dn(HDB2LDAP(db), e);
+ } else {
+ /* Entry exists, but we're not allowed to replace it. Bail. */
+ ret = HDB_ERR_EXISTS;
+ goto out;
+ }
+
+ /* write entry into directory */
+ if (e == NULL) {
+ /* didn't exist before */
+ rc = ldap_add_ext_s(HDB2LDAP(db), dn, mods, NULL, NULL );
+ errfn = "ldap_add_ext_s";
+ } else {
+ /* already existed, send deltas only */
+ rc = ldap_modify_ext_s(HDB2LDAP(db), dn, mods, NULL, NULL );
+ errfn = "ldap_modify_ext_s";
+ }
+
+ if (check_ldap(context, db, rc)) {
+ char *ld_error = NULL;
+ ldap_get_option(HDB2LDAP(db), LDAP_OPT_ERROR_STRING,
+ &ld_error);
+ ret = HDB_ERR_CANT_LOCK_DB;
+ krb5_set_error_message(context, ret, "%s: %s (DN=%s) %s: %s",
+ errfn, name, dn, ldap_err2string(rc), ld_error);
+ } else
+ ret = 0;
+
+ out:
+ /* free stuff */
+ if (dn)
+ free(dn);
+ if (msg)
+ ldap_msgfree(msg);
+ if (mods)
+ ldap_mods_free(mods, 1);
+ if (name)
+ free(name);
+
+ return ret;
+}
+
+static krb5_error_code
+LDAP_remove(krb5_context context, HDB *db,
+ unsigned flags, krb5_const_principal principal)
+{
+ krb5_error_code ret;
+ LDAPMessage *msg, *e;
+ char *dn = NULL;
+ int rc, limit = LDAP_NO_LIMIT;
+
+ if ((flags & HDB_F_PRECHECK))
+ return 0; /* we can't guarantee whether we'll be able to perform it */
+
+ ret = LDAP_principal2message(context, db, principal, &msg);
+ if (ret)
+ goto out;
+
+ e = ldap_first_entry(HDB2LDAP(db), msg);
+ if (e == NULL) {
+ ret = HDB_ERR_NOENTRY;
+ goto out;
+ }
+
+ dn = ldap_get_dn(HDB2LDAP(db), e);
+ if (dn == NULL) {
+ ret = HDB_ERR_NOENTRY;
+ goto out;
+ }
+
+ rc = ldap_set_option(HDB2LDAP(db), LDAP_OPT_SIZELIMIT, (const void *)&limit);
+ if (rc != LDAP_SUCCESS) {
+ ret = HDB_ERR_BADVERSION;
+ krb5_set_error_message(context, ret, "ldap_set_option: %s",
+ ldap_err2string(rc));
+ goto out;
+ }
+
+ /* HACK: This should check if we need to delete the object or just some attributes */
+
+ rc = ldap_delete_ext_s(HDB2LDAP(db), dn, NULL, NULL );
+ if (check_ldap(context, db, rc)) {
+ ret = HDB_ERR_CANT_LOCK_DB;
+ krb5_set_error_message(context, ret, "ldap_delete_ext_s: %s",
+ ldap_err2string(rc));
+ } else
+ ret = 0;
+
+ out:
+ if (dn != NULL)
+ free(dn);
+ if (msg != NULL)
+ ldap_msgfree(msg);
+
+ return ret;
+}
+
+static krb5_error_code
+LDAP_destroy(krb5_context context, HDB * db)
+{
+ krb5_error_code ret;
+
+ LDAP_close(context, db);
+
+ ret = hdb_clear_master_key(context, db);
+ if (HDB2BASE(db))
+ free(HDB2BASE(db));
+ if (HDB2CREATE(db))
+ free(HDB2CREATE(db));
+ if (HDB2URL(db))
+ free(HDB2URL(db));
+ krb5_config_free_strings(db->virtual_hostbased_princ_svcs);
+ if (db->hdb_name)
+ free(db->hdb_name);
+ free(db->hdb_db);
+ free(db);
+
+ return ret;
+}
+
+static krb5_error_code
+LDAP_set_sync(krb5_context context, HDB * db, int on)
+{
+ (void)on;
+ return 0;
+}
+
+static krb5_error_code
+hdb_ldap_common(krb5_context context,
+ HDB ** db,
+ const char *search_base,
+ const char *url)
+{
+ struct hdbldapdb *h;
+ const char *create_base = NULL;
+ const char *ldap_secret_file = NULL;
+
+ if (url == NULL || url[0] == '\0') {
+ const char *p;
+ p = krb5_config_get_string(context, NULL, "kdc",
+ "hdb-ldap-url", NULL);
+ if (p == NULL)
+ p = default_ldap_url;
+
+ url = p;
+ }
+
+ if (search_base == NULL || search_base[0] == '\0') {
+ krb5_set_error_message(context, ENOMEM, "ldap search base not configured");
+ return ENOMEM; /* XXX */
+ }
+
+ if (structural_object == NULL) {
+ const char *p;
+
+ p = krb5_config_get_string(context, NULL, "kdc",
+ "hdb-ldap-structural-object", NULL);
+ if (p == NULL)
+ p = default_structural_object;
+ structural_object = strdup(p);
+ if (structural_object == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ }
+
+ samba_forwardable =
+ krb5_config_get_bool_default(context, NULL, TRUE,
+ "kdc", "hdb-samba-forwardable", NULL);
+
+ *db = calloc(1, sizeof(**db));
+ if (*db == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ memset(*db, 0, sizeof(**db));
+
+ h = calloc(1, sizeof(*h));
+ if (h == NULL) {
+ free(*db);
+ *db = NULL;
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ (*db)->hdb_db = h;
+
+ /* XXX */
+ if (asprintf(&(*db)->hdb_name, "ldap:%s", search_base) == -1) {
+ LDAP_destroy(context, *db);
+ *db = NULL;
+ krb5_set_error_message(context, ENOMEM, "strdup: out of memory");
+ return ENOMEM;
+ }
+
+ h->h_url = strdup(url);
+ h->h_base = strdup(search_base);
+ if (h->h_url == NULL || h->h_base == NULL) {
+ LDAP_destroy(context, *db);
+ *db = NULL;
+ krb5_set_error_message(context, ENOMEM, "strdup: out of memory");
+ return ENOMEM;
+ }
+
+ ldap_secret_file = krb5_config_get_string(context, NULL, "kdc",
+ "hdb-ldap-secret-file", NULL);
+ if (ldap_secret_file != NULL) {
+ krb5_config_binding *tmp;
+ krb5_error_code ret;
+ const char *p;
+
+ ret = krb5_config_parse_file(context, ldap_secret_file, &tmp);
+ if (ret)
+ return ret;
+
+ p = krb5_config_get_string(context, tmp, "kdc",
+ "hdb-ldap-bind-dn", NULL);
+ if (p != NULL)
+ h->h_bind_dn = strdup(p);
+
+ p = krb5_config_get_string(context, tmp, "kdc",
+ "hdb-ldap-bind-password", NULL);
+ if (p != NULL)
+ h->h_bind_password = strdup(p);
+
+ krb5_config_file_free(context, tmp);
+ }
+
+ h->h_start_tls =
+ krb5_config_get_bool_default(context, NULL, FALSE,
+ "kdc", "hdb-ldap-start-tls", NULL);
+
+ create_base = krb5_config_get_string(context, NULL, "kdc",
+ "hdb-ldap-create-base", NULL);
+ if (create_base == NULL)
+ create_base = h->h_base;
+
+ h->h_createbase = strdup(create_base);
+ if (h->h_createbase == NULL) {
+ LDAP_destroy(context, *db);
+ *db = NULL;
+ krb5_set_error_message(context, ENOMEM, "strdup: out of memory");
+ return ENOMEM;
+ }
+
+ (*db)->hdb_master_key_set = 0;
+ (*db)->hdb_openp = 0;
+ (*db)->hdb_capability_flags = HDB_CAP_F_SHARED_DIRECTORY;
+ (*db)->hdb_open = LDAP_open;
+ (*db)->hdb_close = LDAP_close;
+ (*db)->hdb_fetch_kvno = LDAP_fetch_kvno;
+ (*db)->hdb_store = LDAP_store;
+ (*db)->hdb_remove = LDAP_remove;
+ (*db)->hdb_firstkey = LDAP_firstkey;
+ (*db)->hdb_nextkey = LDAP_nextkey;
+ (*db)->hdb_lock = LDAP_lock;
+ (*db)->hdb_unlock = LDAP_unlock;
+ (*db)->hdb_rename = NULL;
+ (*db)->hdb__get = NULL;
+ (*db)->hdb__put = NULL;
+ (*db)->hdb__del = NULL;
+ (*db)->hdb_destroy = LDAP_destroy;
+ (*db)->hdb_set_sync = LDAP_set_sync;
+
+ return 0;
+}
+
+#ifdef OPENLDAP_MODULE
+static
+#endif
+
+krb5_error_code
+hdb_ldap_create(krb5_context context, HDB ** db, const char *arg)
+{
+ return hdb_ldap_common(context, db, arg, NULL);
+}
+
+#ifdef OPENLDAP_MODULE
+static
+#endif
+
+krb5_error_code
+hdb_ldapi_create(krb5_context context, HDB ** db, const char *arg)
+{
+ krb5_error_code ret;
+ char *search_base, *p;
+
+ if (asprintf(&p, "ldapi:%s", arg) == -1 || p == NULL) {
+ *db = NULL;
+ krb5_set_error_message(context, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+ search_base = strchr(p + strlen("ldapi://"), ':');
+ if (search_base == NULL) {
+ *db = NULL;
+ krb5_set_error_message(context, HDB_ERR_BADVERSION,
+ "search base missing");
+ return HDB_ERR_BADVERSION;
+ }
+ *search_base = '\0';
+ search_base++;
+
+ ret = hdb_ldap_common(context, db, search_base, p);
+ free(p);
+ return ret;
+}
+
+#ifdef OPENLDAP_MODULE
+static krb5_error_code
+init(krb5_context context, void **ctx)
+{
+ *ctx = NULL;
+ return 0;
+}
+
+static void
+fini(void *ctx)
+{
+}
+
+struct hdb_method hdb_ldap_interface = {
+ HDB_INTERFACE_VERSION,
+ init,
+ fini,
+ 0 /*is_file_based*/, 0 /*can_taste*/,
+ "ldap",
+ hdb_ldap_create
+};
+
+struct hdb_method hdb_ldapi_interface = {
+ HDB_INTERFACE_VERSION,
+ init,
+ fini,
+ 0 /*is_file_based*/, 0 /*can_taste*/,
+ "ldapi",
+ hdb_ldapi_create
+};
+#endif
+
+#endif /* OPENLDAP */
diff --git a/third_party/heimdal/lib/hdb/hdb-mdb.c b/third_party/heimdal/lib/hdb/hdb-mdb.c
new file mode 100644
index 0000000..6aa5201
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/hdb-mdb.c
@@ -0,0 +1,692 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * Copyright (c) 2011 - Howard Chu, Symas Corp.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hdb_locl.h"
+
+#if HAVE_LMDB
+
+/* LMDB */
+
+#include <lmdb.h>
+
+#define KILO 1024
+
+#define E(sym, kret) case sym: ret = kret; ename = #sym; break
+
+/* Note: calls krb5_set_error_message() */
+static krb5_error_code
+mdb2krb5_code(krb5_context context, int code)
+{
+ krb5_error_code ret = 0;
+ const char *ename = "UNKNOWN";
+ const char *estr = mdb_strerror(code);
+
+ switch (code) {
+ case MDB_SUCCESS: return 0;
+ E(MDB_KEYEXIST, HDB_ERR_EXISTS);
+ E(MDB_NOTFOUND, HDB_ERR_NOENTRY);
+ E(MDB_PAGE_NOTFOUND, HDB_ERR_UK_SERROR);
+ E(MDB_CORRUPTED, HDB_ERR_UK_SERROR);
+ E(MDB_PANIC, HDB_ERR_UK_SERROR);
+ E(MDB_VERSION_MISMATCH, HDB_ERR_UK_SERROR);
+ E(MDB_INVALID, HDB_ERR_UK_SERROR);
+ E(MDB_MAP_FULL, HDB_ERR_UK_SERROR);
+ E(MDB_DBS_FULL, HDB_ERR_UK_SERROR);
+ E(MDB_READERS_FULL, HDB_ERR_UK_SERROR);
+ E(MDB_TLS_FULL, HDB_ERR_UK_SERROR);
+ E(MDB_TXN_FULL, HDB_ERR_UK_SERROR);
+ E(MDB_CURSOR_FULL, HDB_ERR_UK_SERROR);
+ E(MDB_PAGE_FULL, HDB_ERR_UK_SERROR);
+ E(MDB_MAP_RESIZED, HDB_ERR_UK_SERROR);
+ E(MDB_INCOMPATIBLE, HDB_ERR_UK_SERROR);
+ E(MDB_BAD_RSLOT, HDB_ERR_UK_SERROR);
+ E(MDB_BAD_TXN, HDB_ERR_UK_SERROR);
+ E(MDB_BAD_VALSIZE, HDB_ERR_UK_SERROR);
+ E(MDB_BAD_DBI, HDB_ERR_UK_SERROR);
+ default:
+ if (code > 0 && code < 100)
+ ret = code;
+ else
+ ret = HDB_ERR_UK_SERROR;
+ break;
+ }
+ if (ret)
+ krb5_set_error_message(context, ret, "MDB error %s (%d): %s",
+ ename, code, estr);
+ return ret;
+}
+
+typedef struct mdb_info {
+ MDB_env *e;
+ MDB_txn *t;
+ MDB_dbi d;
+ MDB_cursor *c;
+ int oflags;
+ mode_t mode;
+ size_t mapsize;
+ unsigned int in_tx:1;
+} mdb_info;
+
+/* See below */
+struct keep_it_open {
+ char *path;
+ MDB_env *env;
+ MDB_dbi d;
+ unsigned int oflags;
+ size_t refs;
+ size_t mapsize;
+ unsigned int valid:1;
+ struct keep_it_open *next;
+} *keep_them_open;
+HEIMDAL_MUTEX keep_them_open_lock = HEIMDAL_MUTEX_INITIALIZER;
+
+/*
+ * On Unix LMDB uses fcntl() byte-range locks, and unlike SQLite3 (which also
+ * uses fcntl() byte-range locks) LMDB takes no precautions to avoid early
+ * first-close()s that cause other threads' locks to get dropped. No, LMDB
+ * requires the caller to take such precautions. For us that means opening one
+ * mdb env per-{HDB, mode} (where mode is read-write or read-only), never
+ * closing it, and sharing it with all threads.
+ *
+ * Sharing an MDB_env * across multiple threads is documented to be safe, and
+ * internally LMDB uses pread(2), pwrite(2), and mmap(2) for I/O, using
+ * read(2)/write(2) only in the DB copy routines that we don't use.
+ *
+ * On WIN32 we don't have to do any of this, however, to avoid ifdef spaghetti,
+ * we share this code on all platforms, even if it isn't strictly needed.
+ *
+ * Also, one must call mdb_open() (aka mdb_dbi_open()) only once per call to
+ * mdb_env_open() and per B-tree. We only use one B-tree in each LMDB: the
+ * main one.
+ *
+ * On success this outputs an `MDB_env *' (the handle for the LMDB) and an
+ * `MDB_dbi' (the handle for the main B-tree in the LMDB).
+ *
+ * ALSO, LMDB requires that we re-open the `MDB_env' when the database grows
+ * larger than the mmap size. We handle this by finding in `keep_them_open'
+ * the env we already have, marking it unusable, and the finding some other
+ * better one or opening a new one and adding it to the list.
+ */
+static krb5_error_code
+my_mdb_env_create_and_open(krb5_context context,
+ mdb_info *mi,
+ const char *path,
+ int mapfull)
+{
+ struct keep_it_open *p, *n;
+ MDB_txn *txn = NULL;
+ unsigned int flags = MDB_NOSUBDIR;
+ struct stat st;
+ size_t mapsize = 0;
+ int max_readers;
+ int locked = 0;
+ int code = 0;
+
+ mi->oflags &= O_ACCMODE;
+ flags |= (mi->oflags == O_RDONLY) ? MDB_RDONLY : 0;
+
+ mi->e = NULL;
+
+ /*
+ * Allocate a new object, in case we don't already have one in
+ * `keep_them_open'; if we don't need it, we'll free it. This way we do
+ * some of the work of creating one while not holding a lock.
+ */
+ if ((n = calloc(1, sizeof(*n))) == NULL ||
+ (n->path = strdup(path)) == NULL) {
+ free(n);
+ return krb5_enomem(context);
+ }
+ n->oflags = mi->oflags;
+
+ max_readers = krb5_config_get_int_default(context, NULL, 0, "kdc",
+ "hdb-mdb-maxreaders", NULL);
+ mapsize = krb5_config_get_int_default(context, NULL, 0, "kdc", "hdb-mdb-mapsize",
+ NULL);
+ if (mapsize > INT_MAX)
+ mapsize = 0;
+
+ memset(&st, 0, sizeof(st));
+ if (stat(path, &st) == 0 && st.st_size > mapsize * KILO)
+ mapsize += (st.st_size + (st.st_size >> 2)) / KILO;
+ if (mapsize < 100 * 1024)
+ mapsize = 100 * 1024; /* 100MB */
+ if (mapsize < mi->mapsize)
+ mapsize = mi->mapsize;
+ if (mapfull)
+ mapsize += 10 * 1024;
+ if ((code = mdb_env_create(&n->env)) ||
+ (max_readers && (code = mdb_env_set_maxreaders(n->env, max_readers))))
+ goto out;
+
+ /* Look for an existing env */
+ HEIMDAL_MUTEX_lock(&keep_them_open_lock);
+ locked = 1;
+ for (p = keep_them_open; p; p = p->next) {
+ if (strcmp(p->path, path) != 0)
+ continue;
+ if (p->mapsize > mapsize)
+ /* Always increase mapsize */
+ mapsize = p->mapsize + (p->mapsize >> 1);
+ if (!p->valid || p->oflags != mi->oflags)
+ continue;
+ /* Found one; output it and get out */
+ mi->e = p->env;
+ mi->d = p->d;
+ p->refs++;
+ goto out;
+ }
+
+ /* Did not find one, so open and add this one to the list */
+
+ /* Open the LMDB itself */
+ n->refs = 1;
+ n->valid = 1;
+ krb5_debug(context, 5, "Opening HDB LMDB %s with mapsize %llu",
+ path, (unsigned long long)mapsize * KILO);
+ code = mdb_env_set_mapsize(n->env, mapsize * KILO);
+ if (code == 0)
+ code = mdb_env_open(n->env, path, flags, mi->mode);
+ if (code == 0)
+ /* Open a transaction so we can resolve the main B-tree */
+ code = mdb_txn_begin(n->env, NULL, MDB_RDONLY, &txn);
+ if (code == 0)
+ /* Resolve the main B-tree */
+ code = mdb_open(txn, NULL, 0, &n->d);
+ if (code)
+ goto out;
+
+ /* Successfully opened the LMDB; output the two handles */
+ mi->mapsize = n->mapsize = mapsize;
+ mi->e = n->env;
+ mi->d = n->d;
+
+ /* Add this keep_it_open to the front of the list */
+ n->next = keep_them_open;
+ keep_them_open = n;
+ n = NULL;
+
+out:
+ if (locked)
+ HEIMDAL_MUTEX_unlock(&keep_them_open_lock);
+ if (n) {
+ if (n->env)
+ mdb_env_close(n->env);
+ free(n->path);
+ free(n);
+ }
+ (void) mdb_txn_commit(txn); /* Safe when `txn == NULL' */
+ return mdb2krb5_code(context, code);
+}
+
+static void
+my_mdb_env_close(krb5_context context,
+ const char *db_name,
+ MDB_env **envp)
+{
+ struct keep_it_open **prev;
+ struct keep_it_open *p, *old;
+ size_t refs_seen = 0;
+ size_t slen = strlen(db_name);
+ MDB_env *env = *envp;
+
+ if (env == NULL)
+ return;
+
+ HEIMDAL_MUTEX_lock(&keep_them_open_lock);
+ for (p = keep_them_open; p; p = p->next) {
+ /*
+ * We can have multiple open ones and we need to know if this is the
+ * last one, so we can't break out early.
+ */
+ if (p->env == env)
+ refs_seen += (--(p->refs));
+ else if (strncmp(db_name, p->path, slen) == 0 &&
+ strcmp(p->path + slen, ".mdb") == 0)
+ refs_seen += p->refs;
+ }
+ krb5_debug(context, 6, "Closing HDB LMDB %s / %p; refs %llu", db_name, env,
+ (unsigned long long)refs_seen);
+ prev = &keep_them_open;
+ for (p = keep_them_open; !refs_seen && p; ) {
+ /* We're the last close */
+ if (p->refs ||
+ strncmp(db_name, p->path, slen) != 0 ||
+ strcmp(p->path + slen, ".mdb") != 0) {
+
+ /* Not us; this keep_it_open stays */
+ prev = &p->next;
+ p = p->next;
+ continue;
+ }
+
+ /* Close and remove this one */
+ krb5_debug(context, 6, "Closing HDB LMDB %s (mapsize was %llu)",
+ db_name, (unsigned long long)p->mapsize * KILO);
+ old = p;
+ *prev = (p = p->next); /* prev stays */
+ mdb_env_close(old->env);
+ free(old->path);
+ free(old);
+ }
+ HEIMDAL_MUTEX_unlock(&keep_them_open_lock);
+}
+
+/*
+ * This is a wrapper around my_mdb_env_create_and_open(). It may close an
+ * existing MDB_env in mi->e if it's there. If we need to reopen because the
+ * MDB grew too much, then we call this.
+ */
+static krb5_error_code
+my_reopen_mdb(krb5_context context, HDB *db, int mapfull)
+{
+ mdb_info *mi = (mdb_info *)db->hdb_db;
+ char *fn;
+ krb5_error_code ret = 0;
+
+ /* No-op if we don't have an open one */
+ my_mdb_env_close(context, db->hdb_name, &mi->e);
+ if (asprintf(&fn, "%s.mdb", db->hdb_name) == -1)
+ ret = krb5_enomem(context);
+ if (ret == 0)
+ ret = my_mdb_env_create_and_open(context, mi, fn, mapfull);
+ free(fn);
+ return ret;
+}
+
+static krb5_error_code
+DB_close(krb5_context context, HDB *db)
+{
+ mdb_info *mi = (mdb_info *)db->hdb_db;
+
+ mdb_cursor_close(mi->c);
+ mdb_txn_abort(mi->t);
+ my_mdb_env_close(context, db->hdb_name, &mi->e);
+ mi->c = 0;
+ mi->t = 0;
+ mi->e = 0;
+ return 0;
+}
+
+static krb5_error_code
+DB_destroy(krb5_context context, HDB *db)
+{
+ krb5_error_code ret;
+
+ ret = hdb_clear_master_key(context, db);
+ krb5_config_free_strings(db->virtual_hostbased_princ_svcs);
+ free(db->hdb_name);
+ free(db->hdb_db);
+ free(db);
+ return ret;
+}
+
+static krb5_error_code
+DB_set_sync(krb5_context context, HDB *db, int on)
+{
+ mdb_info *mi = (mdb_info *)db->hdb_db;
+
+ mdb_env_set_flags(mi->e, MDB_NOSYNC, !on);
+ return mdb_env_sync(mi->e, 0);
+}
+
+static krb5_error_code
+DB_lock(krb5_context context, HDB *db, int operation)
+{
+ db->lock_count++;
+ return 0;
+}
+
+static krb5_error_code
+DB_unlock(krb5_context context, HDB *db)
+{
+ if (db->lock_count > 1) {
+ db->lock_count--;
+ return 0;
+ }
+ heim_assert(db->lock_count == 1, "HDB lock/unlock sequence does not match");
+ db->lock_count--;
+ return 0;
+}
+
+
+static krb5_error_code
+DB_seq(krb5_context context, HDB *db,
+ unsigned flags, hdb_entry *entry, int flag)
+{
+ mdb_info *mi = db->hdb_db;
+ MDB_val key, value;
+ krb5_data key_data, data;
+ int code;
+
+ /*
+ * No need to worry about MDB_MAP_FULL when we're scanning the DB since we
+ * have snapshot semantics, and any DB growth from other transactions
+ * should not affect us.
+ */
+ key.mv_size = 0;
+ value.mv_size = 0;
+ code = mdb_cursor_get(mi->c, &key, &value, flag);
+ if (code)
+ return mdb2krb5_code(context, code);
+
+ key_data.data = key.mv_data;
+ key_data.length = key.mv_size;
+ data.data = value.mv_data;
+ data.length = value.mv_size;
+ memset(entry, 0, sizeof(*entry));
+ if (hdb_value2entry(context, &data, entry))
+ return DB_seq(context, db, flags, entry, MDB_NEXT);
+ if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) {
+ code = hdb_unseal_keys (context, db, entry);
+ if (code)
+ hdb_free_entry (context, db, entry);
+ }
+ if (entry->principal == NULL) {
+ entry->principal = malloc(sizeof(*entry->principal));
+ if (entry->principal == NULL) {
+ hdb_free_entry (context, db, entry);
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ } else {
+ hdb_key2principal(context, &key_data, entry->principal);
+ }
+ }
+ return 0;
+}
+
+
+static krb5_error_code
+DB_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
+{
+ krb5_error_code ret = 0;
+ mdb_info *mi = db->hdb_db;
+ int tries = 3;
+ int code = 0;
+
+ /* Always start with a fresh cursor to pick up latest DB state */
+
+ do {
+ if (mi->t)
+ mdb_txn_abort(mi->t);
+ mi->t = NULL;
+ if (code)
+ code = my_reopen_mdb(context, db, 1);
+ if (code == 0)
+ code = mdb_txn_begin(mi->e, NULL, MDB_RDONLY, &mi->t);
+ if (code == 0)
+ code = mdb_cursor_open(mi->t, mi->d, &mi->c);
+ if (code == 0) {
+ ret = DB_seq(context, db, flags, entry, MDB_FIRST);
+ break;
+ }
+ } while (code == MDB_MAP_FULL && --tries > 0);
+
+ if (code || ret) {
+ mdb_txn_abort(mi->t);
+ mi->t = NULL;
+ }
+ return ret ? ret : mdb2krb5_code(context, code);
+}
+
+
+static krb5_error_code
+DB_nextkey(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
+{
+ return DB_seq(context, db, flags, entry, MDB_NEXT);
+}
+
+static krb5_error_code
+DB_rename(krb5_context context, HDB *db, const char *new_name)
+{
+ int ret;
+ char *old, *new;
+
+ if (strncmp(new_name, "mdb:", sizeof("mdb:") - 1) == 0)
+ new_name += sizeof("mdb:") - 1;
+ else if (strncmp(new_name, "lmdb:", sizeof("lmdb:") - 1) == 0)
+ new_name += sizeof("lmdb:") - 1;
+ if (asprintf(&old, "%s.mdb", db->hdb_name) == -1)
+ return ENOMEM;
+ if (asprintf(&new, "%s.mdb", new_name) == -1) {
+ free(old);
+ return ENOMEM;
+ }
+ ret = rename(old, new);
+ free(old);
+ free(new);
+ if(ret)
+ return errno;
+
+ free(db->hdb_name);
+ db->hdb_name = strdup(new_name);
+ return 0;
+}
+
+static krb5_error_code
+DB__get(krb5_context context, HDB *db, krb5_data key, krb5_data *reply)
+{
+ mdb_info *mi = (mdb_info*)db->hdb_db;
+ MDB_txn *txn = NULL;
+ MDB_val k, v;
+ int tries = 3;
+ int code = 0;
+
+ k.mv_data = key.data;
+ k.mv_size = key.length;
+
+ do {
+ if (txn) {
+ mdb_txn_abort(txn);
+ txn = NULL;
+ }
+ if (code)
+ code = my_reopen_mdb(context, db, 1);
+ if (code == 0)
+ code = mdb_txn_begin(mi->e, NULL, MDB_RDONLY, &txn);
+ if (code == 0)
+ code = mdb_get(txn, mi->d, &k, &v);
+ if (code == 0)
+ krb5_data_copy(reply, v.mv_data, v.mv_size);
+ } while (code == MDB_MAP_FULL && --tries > 0);
+
+ if (code)
+ mdb_txn_abort(txn);
+ else
+ (void) mdb_txn_commit(txn); /* Empty transaction? -> commit */
+ return mdb2krb5_code(context, code);
+}
+
+static krb5_error_code
+DB__put(krb5_context context, HDB *db, int replace,
+ krb5_data key, krb5_data value)
+{
+ mdb_info *mi = (mdb_info*)db->hdb_db;
+ MDB_txn *txn = NULL;
+ MDB_val k, v;
+ int tries = 3;
+ int code = 0;
+
+ k.mv_data = key.data;
+ k.mv_size = key.length;
+ v.mv_data = value.data;
+ v.mv_size = value.length;
+
+ do {
+ if (txn) {
+ mdb_txn_abort(txn);
+ txn = NULL;
+ }
+ if (code)
+ code = my_reopen_mdb(context, db, 1);
+ if (code == 0)
+ code = mdb_txn_begin(mi->e, NULL, 0, &txn);
+ if (code == 0)
+ code = mdb_put(txn, mi->d, &k, &v, replace ? 0 : MDB_NOOVERWRITE);
+ if (code == 0) {
+ /*
+ * No need to call mdb_env_sync(); it's done automatically if
+ * MDB_NOSYNC is not set.
+ */
+ code = mdb_txn_commit(txn);
+ txn = NULL;
+ }
+ } while (code == MDB_MAP_FULL && --tries > 0);
+ if (txn)
+ mdb_txn_abort(txn);
+ return mdb2krb5_code(context, code);
+}
+
+static krb5_error_code
+DB__del(krb5_context context, HDB *db, krb5_data key)
+{
+ mdb_info *mi = (mdb_info*)db->hdb_db;
+ MDB_txn *txn = NULL;
+ MDB_val k;
+ int tries = 3;
+ int code = 0;
+
+ k.mv_data = key.data;
+ k.mv_size = key.length;
+
+ do {
+ if (txn) {
+ mdb_txn_abort(txn);
+ txn = NULL;
+ }
+ if (code)
+ code = my_reopen_mdb(context, db, 1);
+ if (code == 0)
+ code = mdb_txn_begin(mi->e, NULL, 0, &txn);
+ if (code == 0)
+ code = mdb_del(txn, mi->d, &k, NULL);
+ if (code == 0) {
+ /*
+ * No need to call mdb_env_sync(); it's done automatically if
+ * MDB_NOSYNC is not set.
+ */
+ code = mdb_txn_commit(txn);
+ txn = NULL;
+ }
+ } while (code == MDB_MAP_FULL && --tries > 0);
+
+ if (txn)
+ mdb_txn_abort(txn);
+ return mdb2krb5_code(context, code);
+}
+
+static krb5_error_code
+DB_open(krb5_context context, HDB *db, int oflags, mode_t mode)
+{
+ mdb_info *mi = (mdb_info *)db->hdb_db;
+ krb5_error_code ret;
+
+ mi->e = NULL;
+ mi->mode = mode;
+ mi->oflags = oflags & O_ACCMODE;
+ ret = my_reopen_mdb(context, db, 0);
+ if (ret) {
+ krb5_prepend_error_message(context, ret, "opening %s:", db->hdb_name);
+ return ret;
+ }
+
+ if ((oflags & O_ACCMODE) == O_RDONLY) {
+ ret = hdb_check_db_format(context, db);
+ /*
+ * Dubious: if the DB is not initialized, shouldn't we tell the
+ * caller??
+ */
+ if (ret == HDB_ERR_NOENTRY)
+ return 0;
+ } else {
+ /* hdb_init_db() calls hdb_check_db_format() */
+ ret = hdb_init_db(context, db);
+ }
+ if (ret) {
+ DB_close(context, db);
+ krb5_set_error_message(context, ret, "hdb_open: failed %s database %s",
+ (oflags & O_ACCMODE) == O_RDONLY ?
+ "checking format of" : "initialize",
+ db->hdb_name);
+ }
+
+ return ret;
+}
+
+krb5_error_code
+hdb_mdb_create(krb5_context context, HDB **db,
+ const char *filename)
+{
+ *db = calloc(1, sizeof(**db));
+ if (*db == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ (*db)->hdb_db = calloc(1, sizeof(mdb_info));
+ if ((*db)->hdb_db == NULL) {
+ free(*db);
+ *db = NULL;
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ (*db)->hdb_name = strdup(filename);
+ if ((*db)->hdb_name == NULL) {
+ free((*db)->hdb_db);
+ free(*db);
+ *db = NULL;
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ (*db)->hdb_master_key_set = 0;
+ (*db)->hdb_openp = 0;
+ (*db)->hdb_capability_flags = HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL;
+ (*db)->hdb_open = DB_open;
+ (*db)->hdb_close = DB_close;
+ (*db)->hdb_fetch_kvno = _hdb_fetch_kvno;
+ (*db)->hdb_store = _hdb_store;
+ (*db)->hdb_remove = _hdb_remove;
+ (*db)->hdb_firstkey = DB_firstkey;
+ (*db)->hdb_nextkey= DB_nextkey;
+ (*db)->hdb_lock = DB_lock;
+ (*db)->hdb_unlock = DB_unlock;
+ (*db)->hdb_rename = DB_rename;
+ (*db)->hdb__get = DB__get;
+ (*db)->hdb__put = DB__put;
+ (*db)->hdb__del = DB__del;
+ (*db)->hdb_destroy = DB_destroy;
+ (*db)->hdb_set_sync = DB_set_sync;
+ return 0;
+}
+#endif /* HAVE_LMDB */
diff --git a/third_party/heimdal/lib/hdb/hdb-mitdb.c b/third_party/heimdal/lib/hdb/hdb-mitdb.c
new file mode 100644
index 0000000..7436f39
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/hdb-mitdb.c
@@ -0,0 +1,1500 @@
+/*
+ * Copyright (c) 1997 - 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#define KRB5_KDB_DISALLOW_POSTDATED 0x00000001
+#define KRB5_KDB_DISALLOW_FORWARDABLE 0x00000002
+#define KRB5_KDB_DISALLOW_TGT_BASED 0x00000004
+#define KRB5_KDB_DISALLOW_RENEWABLE 0x00000008
+#define KRB5_KDB_DISALLOW_PROXIABLE 0x00000010
+#define KRB5_KDB_DISALLOW_DUP_SKEY 0x00000020
+#define KRB5_KDB_DISALLOW_ALL_TIX 0x00000040
+#define KRB5_KDB_REQUIRES_PRE_AUTH 0x00000080
+#define KRB5_KDB_REQUIRES_HW_AUTH 0x00000100
+#define KRB5_KDB_REQUIRES_PWCHANGE 0x00000200
+#define KRB5_KDB_DISALLOW_SVR 0x00001000
+#define KRB5_KDB_PWCHANGE_SERVICE 0x00002000
+#define KRB5_KDB_SUPPORT_DESMD5 0x00004000
+#define KRB5_KDB_NEW_PRINC 0x00008000
+
+/*
+
+key: krb5_unparse_name + NUL
+
+ 16: baselength
+ 32: attributes
+ 32: max time
+ 32: max renewable time
+ 32: client expire
+ 32: passwd expire
+ 32: last successful passwd
+ 32: last failed attempt
+ 32: num of failed attempts
+ 16: num tl data
+ 16: num data data
+ 16: principal length
+ length: principal
+ for num tl data times
+ 16: tl data type
+ 16: tl data length
+ length: length
+ for num key data times
+ 16: version (num keyblocks)
+ 16: kvno
+ for version times:
+ 16: type
+ 16: length
+ length: keydata
+
+
+key_data_contents[0]
+
+ int16: length
+ read-of-data: key-encrypted, key-usage 0, master-key
+
+salt:
+ version2 = salt in key_data->key_data_contents[1]
+ else default salt.
+
+*/
+
+#include "hdb_locl.h"
+
+typedef struct MITDB {
+ HDB db; /* Generic */
+ int do_sync; /* MITDB-specific */
+} MITDB;
+
+static void
+attr_to_flags(unsigned attr, HDBFlags *flags)
+{
+ flags->postdate = !(attr & KRB5_KDB_DISALLOW_POSTDATED);
+ flags->forwardable = !(attr & KRB5_KDB_DISALLOW_FORWARDABLE);
+ flags->initial = !!(attr & KRB5_KDB_DISALLOW_TGT_BASED);
+ flags->renewable = !(attr & KRB5_KDB_DISALLOW_RENEWABLE);
+ flags->proxiable = !(attr & KRB5_KDB_DISALLOW_PROXIABLE);
+ /* DUP_SKEY */
+ flags->invalid = !!(attr & KRB5_KDB_DISALLOW_ALL_TIX);
+ flags->require_preauth = !!(attr & KRB5_KDB_REQUIRES_PRE_AUTH);
+ flags->require_hwauth = !!(attr & KRB5_KDB_REQUIRES_HW_AUTH);
+ flags->require_pwchange = !!(attr & KRB5_KDB_REQUIRES_PWCHANGE);
+ flags->server = !(attr & KRB5_KDB_DISALLOW_SVR);
+ flags->change_pw = !!(attr & KRB5_KDB_PWCHANGE_SERVICE);
+ flags->client = 1; /* XXX */
+}
+
+#define KDB_V1_BASE_LENGTH 38
+
+#define CHECK(x) do { if ((x)) goto out; } while(0)
+
+#ifdef HAVE_DB1
+static krb5_error_code
+mdb_principal2key(krb5_context context,
+ krb5_const_principal principal,
+ krb5_data *key)
+{
+ krb5_error_code ret;
+ char *str;
+
+ ret = krb5_unparse_name(context, principal, &str);
+ if (ret)
+ return ret;
+ key->data = str;
+ key->length = strlen(str) + 1;
+ return 0;
+}
+#endif /* HAVE_DB1 */
+
+#define KRB5_KDB_SALTTYPE_NORMAL 0
+#define KRB5_KDB_SALTTYPE_V4 1
+#define KRB5_KDB_SALTTYPE_NOREALM 2
+#define KRB5_KDB_SALTTYPE_ONLYREALM 3
+#define KRB5_KDB_SALTTYPE_SPECIAL 4
+#define KRB5_KDB_SALTTYPE_AFS3 5
+#define KRB5_KDB_SALTTYPE_CERTHASH 6
+
+static krb5_error_code
+fix_salt(krb5_context context, hdb_entry *ent, Key *k)
+{
+ krb5_error_code ret;
+ Salt *salt = k->salt;
+ /* fix salt type */
+ switch((int)salt->type) {
+ case KRB5_KDB_SALTTYPE_NORMAL:
+ salt->type = KRB5_PADATA_PW_SALT;
+ break;
+ case KRB5_KDB_SALTTYPE_V4:
+ krb5_data_free(&salt->salt);
+ salt->type = KRB5_PADATA_PW_SALT;
+ break;
+ case KRB5_KDB_SALTTYPE_NOREALM:
+ {
+ size_t len;
+ size_t i;
+ char *p;
+
+ len = 0;
+ for (i = 0; i < ent->principal->name.name_string.len; ++i)
+ len += strlen(ent->principal->name.name_string.val[i]);
+ ret = krb5_data_alloc (&salt->salt, len);
+ if (ret)
+ return ret;
+ p = salt->salt.data;
+ for (i = 0; i < ent->principal->name.name_string.len; ++i) {
+ memcpy (p,
+ ent->principal->name.name_string.val[i],
+ strlen(ent->principal->name.name_string.val[i]));
+ p += strlen(ent->principal->name.name_string.val[i]);
+ }
+
+ salt->type = KRB5_PADATA_PW_SALT;
+ break;
+ }
+ case KRB5_KDB_SALTTYPE_ONLYREALM:
+ krb5_data_free(&salt->salt);
+ ret = krb5_data_copy(&salt->salt,
+ ent->principal->realm,
+ strlen(ent->principal->realm));
+ if(ret)
+ return ret;
+ salt->type = KRB5_PADATA_PW_SALT;
+ break;
+ case KRB5_KDB_SALTTYPE_SPECIAL:
+ salt->type = KRB5_PADATA_PW_SALT;
+ break;
+ case KRB5_KDB_SALTTYPE_AFS3:
+ krb5_data_free(&salt->salt);
+ ret = krb5_data_copy(&salt->salt,
+ ent->principal->realm,
+ strlen(ent->principal->realm));
+ if(ret)
+ return ret;
+ salt->type = KRB5_PADATA_AFS3_SALT;
+ break;
+ case KRB5_KDB_SALTTYPE_CERTHASH:
+ krb5_data_free(&salt->salt);
+ free(k->salt);
+ k->salt = NULL;
+ break;
+ default:
+ abort();
+ }
+ return 0;
+}
+
+
+/**
+ * This function takes a key from a krb5_storage from an MIT KDB encoded
+ * entry and places it in the given Key object.
+ *
+ * @param context Context
+ * @param entry HDB entry
+ * @param sp krb5_storage with current offset set to the beginning of a
+ * key
+ * @param version See comments in caller body for the backstory on this
+ * @param k Key * to load the key into
+ */
+static krb5_error_code
+mdb_keyvalue2key(krb5_context context, hdb_entry *entry, krb5_storage *sp, uint16_t version, Key *k)
+{
+ size_t i;
+ uint16_t u16, type;
+ krb5_error_code ret;
+
+ k->mkvno = malloc(sizeof(*k->mkvno));
+ if (k->mkvno == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ *k->mkvno = 1;
+
+ for (i = 0; i < version; i++) {
+ CHECK(ret = krb5_ret_uint16(sp, &type));
+ CHECK(ret = krb5_ret_uint16(sp, &u16));
+ if (i == 0) {
+ /* This "version" means we have a key */
+ k->key.keytype = type;
+ /*
+ * MIT stores keys encrypted keys as {16-bit length
+ * of plaintext key, {encrypted key}}. The reason
+ * for this is that the Kerberos cryptosystem is not
+ * length-preserving. Heimdal's approach is to
+ * truncate the plaintext to the expected length of
+ * the key given its enctype, so we ignore this
+ * 16-bit length-of-plaintext-key field.
+ */
+ if (u16 > 2) {
+ krb5_storage_seek(sp, 2, SEEK_CUR); /* skip real length */
+ k->key.keyvalue.length = u16 - 2; /* adjust cipher len */
+ k->key.keyvalue.data = malloc(k->key.keyvalue.length);
+ krb5_storage_read(sp, k->key.keyvalue.data,
+ k->key.keyvalue.length);
+ } else {
+ /* We'll ignore this key; see our caller */
+ k->key.keyvalue.length = 0;
+ k->key.keyvalue.data = NULL;
+ krb5_storage_seek(sp, u16, SEEK_CUR); /* skip real length */
+ }
+ } else if (i == 1) {
+ /* This "version" means we have a salt */
+ k->salt = calloc(1, sizeof(*k->salt));
+ if (k->salt == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ k->salt->type = type;
+ if (u16 != 0) {
+ k->salt->salt.data = malloc(u16);
+ if (k->salt->salt.data == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ k->salt->salt.length = u16;
+ krb5_storage_read(sp, k->salt->salt.data, k->salt->salt.length);
+ }
+ fix_salt(context, entry, k);
+ } else {
+ /*
+ * Whatever this "version" might be, we skip it
+ *
+ * XXX A krb5.conf parameter requesting that we log
+ * about strangeness like this, or return an error
+ * from here, might be nice.
+ */
+ krb5_storage_seek(sp, u16, SEEK_CUR);
+ }
+ }
+
+ return 0;
+
+out:
+ free_Key(k);
+ return ret;
+}
+
+
+static krb5_error_code
+add_1des_dup(krb5_context context, Keys *keys, Key *key, krb5_keytype keytype)
+{
+ key->key.keytype = keytype;
+ return add_Keys(keys, key);
+}
+
+/*
+ * This monstrosity is here so we can avoid having to do enctype
+ * similarity checking in the KDC. This helper function dups 1DES keys
+ * in a keyset for all the similar 1DES enctypes for which keys are
+ * missing. And, of course, we do this only if there's any 1DES keys in
+ * the keyset to begin with.
+ */
+static krb5_error_code
+dup_similar_keys_in_keyset(krb5_context context, Keys *keys)
+{
+ krb5_error_code ret;
+ size_t i, k;
+ Key key;
+ int keyset_has_1des_crc = 0;
+ int keyset_has_1des_md4 = 0;
+ int keyset_has_1des_md5 = 0;
+
+ memset(&key, 0, sizeof (key));
+ k = keys->len;
+ for (i = 0; i < keys->len; i++) {
+ if (keys->val[i].key.keytype == ETYPE_DES_CBC_CRC) {
+ keyset_has_1des_crc = 1;
+ if (k == keys->len)
+ k = i;
+ } else if (keys->val[i].key.keytype == ETYPE_DES_CBC_MD4) {
+ keyset_has_1des_crc = 1;
+ if (k == keys->len)
+ k = i;
+ } else if (keys->val[i].key.keytype == ETYPE_DES_CBC_MD5) {
+ keyset_has_1des_crc = 1;
+ if (k == keys->len)
+ k = i;
+ }
+ }
+ if (k == keys->len)
+ return 0;
+
+ ret = copy_Key(&keys->val[k], &key);
+ if (ret)
+ return ret;
+ if (!keyset_has_1des_crc) {
+ ret = add_1des_dup(context, keys, &key, ETYPE_DES_CBC_CRC);
+ if (ret)
+ goto out;
+ }
+ if (!keyset_has_1des_md4) {
+ ret = add_1des_dup(context, keys, &key, ETYPE_DES_CBC_MD4);
+ if (ret)
+ goto out;
+ }
+ if (!keyset_has_1des_md5) {
+ ret = add_1des_dup(context, keys, &key, ETYPE_DES_CBC_MD5);
+ if (ret)
+ goto out;
+ }
+
+out:
+ free_Key(&key);
+ return ret;
+}
+
+
+static krb5_error_code
+dup_similar_keys(krb5_context context, hdb_entry *entry)
+{
+ krb5_error_code ret;
+ HDB_Ext_KeySet *hist_keys;
+ HDB_extension *extp;
+ size_t i;
+
+ ret = dup_similar_keys_in_keyset(context, &entry->keys);
+ if (ret)
+ return ret;
+ extp = hdb_find_extension(entry, choice_HDB_extension_data_hist_keys);
+ if (extp == NULL)
+ return 0;
+
+ hist_keys = &extp->data.u.hist_keys;
+ for (i = 0; i < hist_keys->len; i++) {
+ ret = dup_similar_keys_in_keyset(context, &hist_keys->val[i].keys);
+ if (ret)
+ return ret;
+ }
+ return 0;
+}
+
+
+/**
+ * This function parses an MIT krb5 encoded KDB entry and fills in the
+ * given HDB entry with it.
+ *
+ * @param context krb5_context
+ * @param data Encoded MIT KDB entry
+ * @param target_kvno Desired kvno, or 0 for the entry's current kvno
+ * @param entry Desired kvno, or 0 for the entry's current kvno
+ */
+krb5_error_code
+_hdb_mdb_value2entry(krb5_context context, krb5_data *data,
+ krb5_kvno target_kvno, hdb_entry *entry)
+{
+ krb5_error_code ret;
+ krb5_storage *sp;
+ Key k;
+ krb5_kvno key_kvno;
+ uint32_t u32;
+ uint16_t u16, num_keys, num_tl;
+ ssize_t sz;
+ size_t i;
+ char *p;
+
+ memset(&k, 0, sizeof (k));
+ memset(entry, 0, sizeof(*entry));
+
+ sp = krb5_storage_from_data(data);
+ if (sp == NULL) {
+ krb5_set_error_message(context, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_LE);
+
+ /*
+ * 16: baselength
+ *
+ * The story here is that these 16 bits have to be a constant:
+ * KDB_V1_BASE_LENGTH. Once upon a time a different value here
+ * would have been used to indicate the presence of "extra data"
+ * between the "base" contents and the {principal name, TL data,
+ * keys} that follow it. Nothing supports such "extra data"
+ * nowadays, so neither do we here.
+ *
+ * XXX But... surely we ought to log about this extra data, or skip
+ * it, or something, in case anyone has MIT KDBs with ancient
+ * entries in them... Logging would allow the admin to know which
+ * entries to dump with MIT krb5's kdb5_util. But logging would be
+ * noisy. For now we do nothing.
+ */
+ CHECK(ret = krb5_ret_uint16(sp, &u16));
+ if (u16 != KDB_V1_BASE_LENGTH) { ret = EINVAL; goto out; }
+ /* 32: attributes */
+ CHECK(ret = krb5_ret_uint32(sp, &u32));
+ attr_to_flags(u32, &entry->flags);
+
+ /* 32: max time */
+ CHECK(ret = krb5_ret_uint32(sp, &u32));
+ if (u32) {
+ entry->max_life = malloc(sizeof(*entry->max_life));
+ *entry->max_life = u32;
+ }
+ /* 32: max renewable time */
+ CHECK(ret = krb5_ret_uint32(sp, &u32));
+ if (u32) {
+ entry->max_renew = malloc(sizeof(*entry->max_renew));
+ *entry->max_renew = u32;
+ }
+ /* 32: client expire */
+ CHECK(ret = krb5_ret_uint32(sp, &u32));
+ if (u32) {
+ entry->valid_end = malloc(sizeof(*entry->valid_end));
+ *entry->valid_end = u32;
+ }
+ /* 32: passwd expire */
+ CHECK(ret = krb5_ret_uint32(sp, &u32));
+ if (u32) {
+ entry->pw_end = malloc(sizeof(*entry->pw_end));
+ *entry->pw_end = u32;
+ }
+ /* 32: last successful passwd */
+ CHECK(ret = krb5_ret_uint32(sp, &u32));
+ /* 32: last failed attempt */
+ CHECK(ret = krb5_ret_uint32(sp, &u32));
+ /* 32: num of failed attempts */
+ CHECK(ret = krb5_ret_uint32(sp, &u32));
+ /* 16: num tl data */
+ CHECK(ret = krb5_ret_uint16(sp, &u16));
+ num_tl = u16;
+ /* 16: num key data */
+ CHECK(ret = krb5_ret_uint16(sp, &u16));
+ num_keys = u16;
+ /* 16: principal length */
+ CHECK(ret = krb5_ret_uint16(sp, &u16));
+ /* length: principal */
+ {
+ /*
+ * Note that the principal name includes the NUL in the entry,
+ * but we don't want to take chances, so we add an extra NUL.
+ */
+ p = malloc(u16 + 1);
+ if (p == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ sz = krb5_storage_read(sp, p, u16);
+ if (sz != u16) {
+ ret = EINVAL; /* XXX */
+ goto out;
+ }
+ p[u16] = '\0';
+ CHECK(ret = krb5_parse_name(context, p, &entry->principal));
+ free(p);
+ }
+ /* for num tl data times
+ 16: tl data type
+ 16: tl data length
+ length: length */
+#define mit_KRB5_TL_LAST_PWD_CHANGE 1
+#define mit_KRB5_TL_MOD_PRINC 2
+ for (i = 0; i < num_tl; i++) {
+ int tl_type;
+ krb5_principal modby;
+ /* 16: TL data type */
+ CHECK(ret = krb5_ret_uint16(sp, &u16));
+ tl_type = u16;
+ /* 16: TL data length */
+ CHECK(ret = krb5_ret_uint16(sp, &u16));
+ /*
+ * For rollback to MIT purposes we really must understand some
+ * TL data!
+ *
+ * XXX Move all this to separate functions, one per-TL type.
+ */
+ switch (tl_type) {
+ case mit_KRB5_TL_LAST_PWD_CHANGE:
+ CHECK(ret = krb5_ret_uint32(sp, &u32));
+ CHECK(ret = hdb_entry_set_pw_change_time(context, entry, u32));
+ break;
+ case mit_KRB5_TL_MOD_PRINC:
+ if (u16 < 5) {
+ ret = EINVAL; /* XXX */
+ goto out;
+ }
+ CHECK(ret = krb5_ret_uint32(sp, &u32)); /* mod time */
+ p = malloc(u16 - 4 + 1);
+ if (!p) {
+ ret = ENOMEM;
+ goto out;
+ }
+ p[u16 - 4] = '\0';
+ sz = krb5_storage_read(sp, p, u16 - 4);
+ if (sz != u16 - 4) {
+ ret = EINVAL; /* XXX */
+ goto out;
+ }
+ CHECK(ret = krb5_parse_name(context, p, &modby));
+ CHECK(ret = hdb_set_last_modified_by(context, entry, modby, u32));
+ krb5_free_principal(context, modby);
+ free(p);
+ break;
+ default:
+ krb5_storage_seek(sp, u16, SEEK_CUR);
+ break;
+ }
+ }
+ /*
+ * for num key data times
+ * 16: "version"
+ * 16: kvno
+ * for version times:
+ * 16: type
+ * 16: length
+ * length: keydata
+ *
+ * "version" here is really 1 or 2, the first meaning there's only
+ * keys for this kvno, the second meaning there's keys and salt[s?].
+ * That's right... hold that gag reflex, you can do it.
+ */
+ for (i = 0; i < num_keys; i++) {
+ uint16_t version;
+
+ CHECK(ret = krb5_ret_uint16(sp, &u16));
+ version = u16;
+ CHECK(ret = krb5_ret_uint16(sp, &u16));
+ key_kvno = u16;
+
+ ret = mdb_keyvalue2key(context, entry, sp, version, &k);
+ if (ret)
+ goto out;
+ if (k.key.keytype == 0 || k.key.keyvalue.length == 0) {
+ /*
+ * Older MIT KDBs may have enctype 0 / length 0 keys. We
+ * ignore these.
+ */
+ free_Key(&k);
+ continue;
+ }
+
+ if ((target_kvno == 0 && entry->kvno < key_kvno) ||
+ (target_kvno == key_kvno && entry->kvno != target_kvno)) {
+ /*
+ * MIT's KDB doesn't keep track of kvno. The highest kvno
+ * is the current kvno, and we just found a new highest
+ * kvno or the desired kvno.
+ *
+ * Note that there's no guarantee of any key ordering, but
+ * generally MIT KDB entries have keys in strictly
+ * descending kvno order.
+ *
+ * XXX We do assume that keys are clustered by kvno. If
+ * not, then bad. It might be possible to construct
+ * non-clustered keys via the kadm5 API. It wouldn't be
+ * hard to cope with this, since if it happens the worst
+ * that will happen is that some of the current keys can be
+ * found in the history extension, and we could just pull
+ * them back out in that case.
+ */
+ ret = hdb_add_current_keys_to_history(context, entry);
+ if (ret)
+ goto out;
+ free_Keys(&entry->keys);
+ ret = add_Keys(&entry->keys, &k);
+ free_Key(&k);
+ if (ret)
+ goto out;
+ entry->kvno = key_kvno;
+ continue;
+ }
+
+ if (entry->kvno == key_kvno) {
+ /*
+ * Note that if key_kvno == 0 and target_kvno == 0 then we
+ * end up adding those keys here. Yeah, kvno 0 is very
+ * special for us, but just in case, we keep such keys.
+ */
+ ret = add_Keys(&entry->keys, &k);
+ free_Key(&k);
+ if (ret)
+ goto out;
+ entry->kvno = key_kvno;
+ } else {
+ ret = hdb_add_history_key(context, entry, key_kvno, &k);
+ if (ret)
+ goto out;
+ free_Key(&k);
+ }
+ }
+
+ if (target_kvno != 0 && entry->kvno != target_kvno) {
+ ret = HDB_ERR_KVNO_NOT_FOUND;
+ goto out;
+ }
+
+ krb5_storage_free(sp);
+
+ return dup_similar_keys(context, entry);
+
+out:
+ krb5_storage_free(sp);
+
+ if (ret == HEIM_ERR_EOF)
+ /* Better error code than "end of file" */
+ ret = HEIM_ERR_BAD_HDBENT_ENCODING;
+ free_HDB_entry(entry);
+ free_Key(&k);
+ return ret;
+}
+
+#if 0
+static krb5_error_code
+mdb_entry2value(krb5_context context, hdb_entry *entry, krb5_data *data)
+{
+ return EINVAL;
+}
+#endif
+
+#if HAVE_DB1
+
+#if defined(HAVE_DB_185_H)
+#include <db_185.h>
+#elif defined(HAVE_DB_H)
+#include <db.h>
+#endif
+
+
+static krb5_error_code
+mdb_close(krb5_context context, HDB *db)
+{
+ DB *d = (DB*)db->hdb_db;
+ (*d->close)(d);
+ return 0;
+}
+
+static krb5_error_code
+mdb_destroy(krb5_context context, HDB *db)
+{
+ krb5_error_code ret;
+
+ ret = hdb_clear_master_key(context, db);
+ krb5_config_free_strings(db->virtual_hostbased_princ_svcs);
+ free(db->hdb_name);
+ free(db);
+ return ret;
+}
+
+static krb5_error_code
+mdb_set_sync(krb5_context context, HDB *db, int on)
+{
+ MITDB *mdb = (MITDB *)db;
+ DB *d = (DB*)db->hdb_db;
+
+ mdb->do_sync = on;
+ if (on)
+ return fsync((*d->fd)(d));
+ return 0;
+}
+
+static krb5_error_code
+mdb_lock(krb5_context context, HDB *db, int operation)
+{
+ DB *d = (DB*)db->hdb_db;
+ int fd = (*d->fd)(d);
+ krb5_error_code ret;
+
+ if (db->lock_count > 1) {
+ db->lock_count++;
+ if (db->lock_type == HDB_WLOCK || db->lock_count == operation)
+ return 0;
+ }
+
+ if(fd < 0) {
+ krb5_set_error_message(context, HDB_ERR_CANT_LOCK_DB,
+ "Can't lock database: %s", db->hdb_name);
+ return HDB_ERR_CANT_LOCK_DB;
+ }
+ ret = hdb_lock(fd, operation);
+ if (ret)
+ return ret;
+ db->lock_count++;
+ return 0;
+}
+
+static krb5_error_code
+mdb_unlock(krb5_context context, HDB *db)
+{
+ DB *d = (DB*)db->hdb_db;
+ int fd = (*d->fd)(d);
+
+ if (db->lock_count > 1) {
+ db->lock_count--;
+ return 0;
+ }
+ heim_assert(db->lock_count == 1, "HDB lock/unlock sequence does not match");
+ db->lock_count--;
+
+ if(fd < 0) {
+ krb5_set_error_message(context, HDB_ERR_CANT_LOCK_DB,
+ "Can't unlock database: %s", db->hdb_name);
+ return HDB_ERR_CANT_LOCK_DB;
+ }
+ return hdb_unlock(fd);
+}
+
+
+static krb5_error_code
+mdb_seq(krb5_context context, HDB *db,
+ unsigned flags, hdb_entry *entry, int flag)
+{
+ DB *d = (DB*)db->hdb_db;
+ DBT key, value;
+ krb5_data key_data, data;
+ int code;
+
+ code = db->hdb_lock(context, db, HDB_RLOCK);
+ if(code == -1) {
+ krb5_set_error_message(context, HDB_ERR_DB_INUSE, "Database %s in use", db->hdb_name);
+ return HDB_ERR_DB_INUSE;
+ }
+ code = (*d->seq)(d, &key, &value, flag);
+ db->hdb_unlock(context, db); /* XXX check value */
+ if(code == -1) {
+ code = errno;
+ krb5_set_error_message(context, code, "Database %s seq error: %s",
+ db->hdb_name, strerror(code));
+ return code;
+ }
+ if(code == 1) {
+ krb5_clear_error_message(context);
+ return HDB_ERR_NOENTRY;
+ }
+
+ key_data.data = key.data;
+ key_data.length = key.size;
+ data.data = value.data;
+ data.length = value.size;
+ memset(entry, 0, sizeof(*entry));
+
+ if (_hdb_mdb_value2entry(context, &data, 0, entry))
+ return mdb_seq(context, db, flags, entry, R_NEXT);
+
+ if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) {
+ code = hdb_unseal_keys (context, db, entry);
+ if (code)
+ hdb_free_entry (context, db, entry);
+ }
+
+ return code;
+}
+
+
+static krb5_error_code
+mdb_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
+{
+ return mdb_seq(context, db, flags, entry, R_FIRST);
+}
+
+
+static krb5_error_code
+mdb_nextkey(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
+{
+ return mdb_seq(context, db, flags, entry, R_NEXT);
+}
+
+static krb5_error_code
+mdb_rename(krb5_context context, HDB *db, const char *new_name)
+{
+ int ret;
+ char *old = NULL;
+ char *new = NULL;
+
+ if (asprintf(&old, "%s.db", db->hdb_name) < 0)
+ goto out;
+ if (asprintf(&new, "%s.db", new_name) < 0)
+ goto out;
+ ret = rename(old, new);
+ if(ret)
+ goto out;
+
+ free(db->hdb_name);
+ db->hdb_name = strdup(new_name);
+ errno = 0;
+
+out:
+ free(old);
+ free(new);
+ return errno;
+}
+
+static krb5_error_code
+mdb__get(krb5_context context, HDB *db, krb5_data key, krb5_data *reply)
+{
+ DB *d = (DB*)db->hdb_db;
+ DBT k, v;
+ int code;
+
+ k.data = key.data;
+ k.size = key.length;
+ code = db->hdb_lock(context, db, HDB_RLOCK);
+ if(code)
+ return code;
+ code = (*d->get)(d, &k, &v, 0);
+ db->hdb_unlock(context, db);
+ if(code < 0) {
+ code = errno;
+ krb5_set_error_message(context, code, "Database %s get error: %s",
+ db->hdb_name, strerror(code));
+ return code;
+ }
+ if(code == 1) {
+ krb5_clear_error_message(context);
+ return HDB_ERR_NOENTRY;
+ }
+
+ krb5_data_copy(reply, v.data, v.size);
+ return 0;
+}
+
+static krb5_error_code
+mdb__put(krb5_context context, HDB *db, int replace,
+ krb5_data key, krb5_data value)
+{
+ MITDB *mdb = (MITDB *)db;
+ DB *d = (DB*)db->hdb_db;
+ DBT k, v;
+ int code;
+
+ k.data = key.data;
+ k.size = key.length;
+ v.data = value.data;
+ v.size = value.length;
+ code = db->hdb_lock(context, db, HDB_WLOCK);
+ if(code)
+ return code;
+ code = (*d->put)(d, &k, &v, replace ? 0 : R_NOOVERWRITE);
+ if (code == 0) {
+ code = mdb_set_sync(context, db, mdb->do_sync);
+ db->hdb_unlock(context, db);
+ return code;
+ }
+ db->hdb_unlock(context, db);
+ if(code < 0) {
+ code = errno;
+ krb5_set_error_message(context, code, "Database %s put error: %s",
+ db->hdb_name, strerror(code));
+ return code;
+ }
+ krb5_clear_error_message(context);
+ return HDB_ERR_EXISTS;
+}
+
+static krb5_error_code
+mdb__del(krb5_context context, HDB *db, krb5_data key)
+{
+ MITDB *mdb = (MITDB *)db;
+ DB *d = (DB*)db->hdb_db;
+ DBT k;
+ krb5_error_code code;
+ k.data = key.data;
+ k.size = key.length;
+ code = db->hdb_lock(context, db, HDB_WLOCK);
+ if(code)
+ return code;
+ code = (*d->del)(d, &k, 0);
+ if (code == 0) {
+ code = mdb_set_sync(context, db, mdb->do_sync);
+ db->hdb_unlock(context, db);
+ return code;
+ }
+ db->hdb_unlock(context, db);
+ if(code == 1) {
+ code = errno;
+ krb5_set_error_message(context, code, "Database %s put error: %s",
+ db->hdb_name, strerror(code));
+ return code;
+ }
+ if(code < 0)
+ return errno;
+ return 0;
+}
+
+static krb5_error_code
+mdb_fetch_kvno(krb5_context context, HDB *db, krb5_const_principal principal,
+ unsigned flags, krb5_kvno kvno, hdb_entry *entry)
+{
+ krb5_data key, value;
+ krb5_error_code ret;
+
+ ret = mdb_principal2key(context, principal, &key);
+ if (ret)
+ return ret;
+ ret = db->hdb__get(context, db, key, &value);
+ krb5_data_free(&key);
+ if(ret)
+ return ret;
+ ret = _hdb_mdb_value2entry(context, &value, kvno, entry);
+ krb5_data_free(&value);
+ if (ret)
+ return ret;
+
+ if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) {
+ ret = hdb_unseal_keys (context, db, entry);
+ if (ret) {
+ hdb_free_entry(context, db, entry);
+ return ret;
+ }
+ }
+
+ return 0;
+}
+
+static krb5_error_code
+mdb_store(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
+{
+ krb5_error_code ret;
+ krb5_storage *sp = NULL;
+ krb5_storage *spent = NULL;
+ krb5_data line = { 0, 0 };
+ krb5_data kdb_ent = { 0, 0 };
+ krb5_data key = { 0, 0 };
+ krb5_data value = { 0, 0 };
+ krb5_ssize_t sz;
+
+ if ((flags & HDB_F_PRECHECK) && (flags & HDB_F_REPLACE))
+ return 0;
+
+ if ((flags & HDB_F_PRECHECK)) {
+ ret = mdb_principal2key(context, entry->principal, &key);
+ if (ret) return ret;
+ ret = db->hdb__get(context, db, key, &value);
+ krb5_data_free(&key);
+ if (ret == 0)
+ krb5_data_free(&value);
+ if (ret == HDB_ERR_NOENTRY)
+ return 0;
+ return ret ? ret : HDB_ERR_EXISTS;
+ }
+
+ sp = krb5_storage_emem();
+ if (!sp) return ENOMEM;
+ ret = _hdb_set_master_key_usage(context, db, 0); /* MIT KDB uses KU 0 */
+ ret = hdb_seal_keys(context, db, entry);
+ if (ret) return ret;
+ ret = entry2mit_string_int(context, sp, entry);
+ if (ret) goto out;
+ sz = krb5_storage_write(sp, "\n", 2); /* NUL-terminate */
+ ret = ENOMEM;
+ if (sz != 2) goto out;
+ ret = krb5_storage_to_data(sp, &line);
+ if (ret) goto out;
+
+ ret = ENOMEM;
+ spent = krb5_storage_emem();
+ if (!spent) goto out;
+ ret = _hdb_mit_dump2mitdb_entry(context, line.data, spent);
+ if (ret) goto out;
+ ret = krb5_storage_to_data(spent, &kdb_ent);
+ if (ret) goto out;
+ ret = mdb_principal2key(context, entry->principal, &key);
+ if (ret) goto out;
+ ret = mdb__put(context, db, 1, key, kdb_ent);
+
+out:
+ if (sp)
+ krb5_storage_free(sp);
+ if (spent)
+ krb5_storage_free(spent);
+ krb5_data_free(&line);
+ krb5_data_free(&kdb_ent);
+ krb5_data_free(&key);
+
+ return ret;
+}
+
+static krb5_error_code
+mdb_remove(krb5_context context, HDB *db,
+ unsigned flags, krb5_const_principal principal)
+{
+ krb5_error_code code;
+ krb5_data key;
+ krb5_data value = { 0, 0 };
+
+ mdb_principal2key(context, principal, &key);
+
+ if ((flags & HDB_F_PRECHECK)) {
+ code = db->hdb__get(context, db, key, &value);
+ krb5_data_free(&key);
+ if (code == 0) {
+ krb5_data_free(&value);
+ return 0;
+ }
+ return code;
+ }
+
+ code = db->hdb__del(context, db, key);
+ krb5_data_free(&key);
+ return code;
+}
+
+static krb5_error_code
+mdb_open(krb5_context context, HDB *db, int flags, mode_t mode)
+{
+ char *fn;
+ char *actual_fn;
+ krb5_error_code ret;
+ struct stat st;
+
+ if (asprintf(&fn, "%s.db", db->hdb_name) < 0) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ if (stat(fn, &st) == 0)
+ actual_fn = fn;
+ else
+ actual_fn = db->hdb_name;
+ db->hdb_db = dbopen(actual_fn, flags, mode, DB_BTREE, NULL);
+ if (db->hdb_db == NULL) {
+ switch (errno) {
+#ifdef EFTYPE
+ case EFTYPE:
+#endif
+ case EINVAL:
+ db->hdb_db = dbopen(actual_fn, flags, mode, DB_HASH, NULL);
+ }
+ }
+ free(fn);
+
+ if (db->hdb_db == NULL) {
+ ret = errno;
+ krb5_set_error_message(context, ret, "dbopen (%s): %s",
+ db->hdb_name, strerror(ret));
+ return ret;
+ }
+#if 0
+ /*
+ * Don't do this -- MIT won't be able to handle the
+ * HDB_DB_FORMAT_ENTRY key.
+ */
+ if ((flags & O_ACCMODE) != O_RDONLY)
+ ret = hdb_init_db(context, db);
+#endif
+ ret = hdb_check_db_format(context, db);
+ if (ret == HDB_ERR_NOENTRY) {
+ krb5_clear_error_message(context);
+ return 0;
+ }
+ if (ret) {
+ mdb_close(context, db);
+ krb5_set_error_message(context, ret, "hdb_open: failed %s database %s",
+ (flags & O_ACCMODE) == O_RDONLY ?
+ "checking format of" : "initialize",
+ db->hdb_name);
+ }
+ return ret;
+}
+
+krb5_error_code
+hdb_mitdb_create(krb5_context context, HDB **db,
+ const char *filename)
+{
+ MITDB **mdb = (MITDB **)db;
+ *mdb = calloc(1, sizeof(**mdb));
+ if (*mdb == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ (*db)->hdb_db = NULL;
+ (*db)->hdb_name = strdup(filename);
+ if ((*db)->hdb_name == NULL) {
+ free(*db);
+ *db = NULL;
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ (*mdb)->do_sync = 1;
+ (*db)->hdb_master_key_set = 0;
+ (*db)->hdb_openp = 0;
+ (*db)->hdb_capability_flags = 0;
+ (*db)->hdb_open = mdb_open;
+ (*db)->hdb_close = mdb_close;
+ (*db)->hdb_fetch_kvno = mdb_fetch_kvno;
+ (*db)->hdb_store = mdb_store;
+ (*db)->hdb_remove = mdb_remove;
+ (*db)->hdb_firstkey = mdb_firstkey;
+ (*db)->hdb_nextkey= mdb_nextkey;
+ (*db)->hdb_lock = mdb_lock;
+ (*db)->hdb_unlock = mdb_unlock;
+ (*db)->hdb_rename = mdb_rename;
+ (*db)->hdb__get = mdb__get;
+ (*db)->hdb__put = mdb__put;
+ (*db)->hdb__del = mdb__del;
+ (*db)->hdb_destroy = mdb_destroy;
+ (*db)->hdb_set_sync = mdb_set_sync;
+ return 0;
+}
+
+#endif /* HAVE_DB1 */
+
+/*
+can have any number of princ stanzas.
+format is as follows (only \n indicates newlines)
+princ\t%d\t (%d is KRB5_KDB_V1_BASE_LENGTH, always 38)
+%d\t (strlen of principal e.g. shadow/foo@ANDREW.CMU.EDU)
+%d\t (number of tl_data)
+%d\t (number of key data, e.g. how many keys for this user)
+%d\t (extra data length)
+%s\t (principal name)
+%d\t (attributes)
+%d\t (max lifetime, seconds)
+%d\t (max renewable life, seconds)
+%d\t (expiration, seconds since epoch or 2145830400 for never)
+%d\t (password expiration, seconds, 0 for never)
+%d\t (last successful auth, seconds since epoch)
+%d\t (last failed auth, per above)
+%d\t (failed auth count)
+foreach tl_data 0 to number of tl_data - 1 as above
+ %d\t%d\t (data type, data length)
+ foreach tl_data 0 to length-1
+ %02x (tl data contents[element n])
+ except if tl_data length is 0
+ %d (always -1)
+ \t
+foreach key 0 to number of keys - 1 as above
+ %d\t%d\t (key data version, kvno)
+ foreach version 0 to key data version - 1 (a key or a salt)
+ %d\t%d\t(data type for this key, data length for this key)
+ foreach key data length 0 to length-1
+ %02x (key data contents[element n])
+ except if key_data length is 0
+ %d (always -1)
+ \t
+foreach extra data length 0 to length - 1
+ %02x (extra data part)
+unless no extra data
+ %d (always -1)
+;\n
+
+*/
+
+#if 0
+/* Why ever did we loop? */
+static char *
+nexttoken(char **p)
+{
+ char *q;
+ do {
+ q = strsep(p, " \t");
+ } while(q && *q == '\0');
+ return q;
+}
+#endif
+
+static char *
+nexttoken(char **p, size_t len, const char *what)
+{
+ char *q;
+
+ if (*p == NULL)
+ return NULL;
+
+ q = *p;
+ *p += len;
+ /* Must be followed by a delimiter (right?) */
+ if (strsep(p, " \t") != q + len) {
+ warnx("No tokens left in dump entry while looking for %s", what);
+ return NULL;
+ }
+ if (*q == '\0')
+ warnx("Empty last token in dump entry while looking for %s", what);
+ return q;
+}
+
+static size_t
+getdata(char **p, unsigned char *buf, size_t len, const char *what)
+{
+ size_t i;
+ int v;
+ char *q = nexttoken(p, 0, what);
+ if (q == NULL) {
+ warnx("Failed to find hex-encoded binary data (%s) in dump", what);
+ return 0;
+ }
+ i = 0;
+ while (*q && i < len) {
+ if (sscanf(q, "%02x", &v) != 1)
+ break;
+ buf[i++] = v;
+ q += 2;
+ }
+ return i;
+}
+
+static int
+getint(char **p, const char *what, int *val)
+{
+ char *q = nexttoken(p, 0, what);
+ if (!q) {
+ warnx("Failed to find a signed integer (%s) in dump", what);
+ return 1;
+ }
+ if (sscanf(q, "%d", val) != 1)
+ return 1;
+ return 0;
+}
+
+static unsigned int
+getuint(char **p, const char *what)
+{
+ int val;
+ char *q = nexttoken(p, 0, what);
+ if (!q) {
+ warnx("Failed to find an unsigned integer (%s) in dump", what);
+ return 0;
+ }
+ if (sscanf(q, "%u", &val) != 1)
+ return 0;
+ return val;
+}
+
+#define KRB5_KDB_SALTTYPE_NORMAL 0
+#define KRB5_KDB_SALTTYPE_V4 1
+#define KRB5_KDB_SALTTYPE_NOREALM 2
+#define KRB5_KDB_SALTTYPE_ONLYREALM 3
+#define KRB5_KDB_SALTTYPE_SPECIAL 4
+#define KRB5_KDB_SALTTYPE_AFS3 5
+
+#define CHECK_UINT(num) \
+ if ((num) < 0 || (num) > INT_MAX) return EINVAL
+#define CHECK_UINT16(num) \
+ if ((num) < 0 || (num) > 1<<15) return EINVAL
+#define CHECK_NUM(num, maxv) \
+ if ((num) > (maxv)) return EINVAL
+
+/*
+ * This utility function converts an MIT dump entry to an MIT on-disk
+ * encoded entry, which can then be decoded with _hdb_mdb_value2entry().
+ * This allows us to have a single decoding function (_hdb_mdb_value2entry),
+ * which makes the code cleaner (less code duplication), if a bit less
+ * efficient. It also will allow us to have a function to dump an HDB
+ * entry in MIT format so we can dump HDB into MIT format for rollback
+ * purposes. And that will allow us to write to MIT KDBs, again
+ * somewhat inefficiently, also for migration/rollback purposes.
+ */
+int
+_hdb_mit_dump2mitdb_entry(krb5_context context, char *line, krb5_storage *sp)
+{
+ krb5_error_code ret = EINVAL;
+ char *p = line, *q;
+ char *princ;
+ krb5_ssize_t sz;
+ size_t i;
+ size_t princ_len;
+ unsigned int num_tl_data;
+ size_t num_key_data;
+ unsigned int attributes;
+ int tmp;
+
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_LE);
+
+ q = nexttoken(&p, 0, "record type (princ or policy)");
+ if (strcmp(q, "kdb5_util") == 0 || strcmp(q, "policy") == 0 ||
+ strcmp(q, "princ") != 0) {
+ warnx("Supposed MIT dump entry does not start with 'kdb5_util', "
+ "'policy', nor 'princ'");
+ return -1;
+ }
+ if (getint(&p, "constant '38'", &tmp) || tmp != 38) {
+ warnx("Dump entry does not start with '38<TAB>'");
+ return EINVAL;
+ }
+#define KDB_V1_BASE_LENGTH 38
+ ret = krb5_store_int16(sp, KDB_V1_BASE_LENGTH);
+ if (ret) return ret;
+
+ princ_len = getuint(&p, "principal name length");
+ if (princ_len > (1<<15) - 1) {
+ warnx("Principal name in dump entry too long (%llu)",
+ (unsigned long long)princ_len);
+ return EINVAL;
+ }
+ num_tl_data = getuint(&p, "number of TL data");
+ num_key_data = getuint(&p, "number of key data");
+ (void) getint(&p, "5th field, length of 'extra data'", &tmp);
+ princ = nexttoken(&p, (int)princ_len, "principal name");
+ if (princ == NULL) {
+ warnx("Failed to read principal name (expected length %llu)",
+ (unsigned long long)princ_len);
+ return -1;
+ }
+
+ attributes = getuint(&p, "attributes");
+ ret = krb5_store_uint32(sp, attributes);
+ if (ret) return ret;
+
+ if (getint(&p, "max life", &tmp)) return EINVAL;
+ ret = krb5_store_uint32(sp, tmp);
+ if (ret) return ret;
+
+ if (getint(&p, "max renewable life", &tmp)) return EINVAL;
+ ret = krb5_store_uint32(sp, tmp);
+ if (ret) return ret;
+
+ if (getint(&p, "expiration", &tmp)) return EINVAL;
+ ret = krb5_store_uint32(sp, tmp);
+ if (ret) return ret;
+
+ if (getint(&p, "pw expiration", &tmp)) return EINVAL;
+ ret = krb5_store_uint32(sp, tmp);
+ if (ret) return ret;
+
+ if (getint(&p, "last auth", &tmp)) return EINVAL;
+ ret = krb5_store_uint32(sp, tmp);
+ if (ret) return ret;
+
+ if (getint(&p, "last failed auth", &tmp)) return EINVAL;
+ ret = krb5_store_uint32(sp, tmp);
+ if (ret) return ret;
+
+ if (getint(&p,"fail auth count", &tmp)) return EINVAL;
+ ret = krb5_store_uint32(sp, tmp);
+ if (ret) return ret;
+
+ /* add TL data count */
+ CHECK_NUM(num_tl_data, 1023);
+ ret = krb5_store_uint16(sp, num_tl_data);
+ if (ret) return ret;
+
+ /* add key count */
+ CHECK_NUM(num_key_data, 1023);
+ ret = krb5_store_uint16(sp, num_key_data);
+ if (ret) return ret;
+
+ /* add principal unparsed name length and unparsed name */
+ princ_len = strlen(princ);
+ princ_len++; /* must count and write the NUL in the on-disk encoding */
+ ret = krb5_store_uint16(sp, princ_len);
+ if (ret) return ret;
+ sz = krb5_storage_write(sp, princ, princ_len);
+ if (sz != princ_len) return ENOMEM;
+
+ /* scan and write TL data */
+ for (i = 0; i < num_tl_data; i++) {
+ char *reading_what;
+ int tl_type, tl_length;
+ unsigned char *buf;
+
+ if (getint(&p, "TL data type", &tl_type) ||
+ getint(&p, "data length", &tl_length))
+ return EINVAL;
+
+ if (asprintf(&reading_what, "TL data type %d (length %d)",
+ tl_type, tl_length) < 0)
+ return ENOMEM;
+
+ /*
+ * XXX Leaking reading_what, but only on ENOMEM cases anyways,
+ * so we don't care.
+ */
+ CHECK_UINT16(tl_type);
+ ret = krb5_store_uint16(sp, tl_type);
+ if (ret) return ret;
+ CHECK_UINT16(tl_length);
+ ret = krb5_store_uint16(sp, tl_length);
+ if (ret) return ret;
+
+ if (tl_length) {
+ buf = malloc(tl_length);
+ if (!buf) return ENOMEM;
+ if (getdata(&p, buf, tl_length, reading_what) != tl_length) {
+ free(buf);
+ return EINVAL;
+ }
+ sz = krb5_storage_write(sp, buf, tl_length);
+ free(buf);
+ if (sz != tl_length) return ENOMEM;
+ } else {
+ if (strcmp(nexttoken(&p, 0, "'-1' field"), "-1") != 0) return EINVAL;
+ }
+ free(reading_what);
+ }
+
+ for (i = 0; i < num_key_data; i++) {
+ unsigned char *buf;
+ int key_versions;
+ int kvno;
+ int keytype;
+ int keylen;
+ size_t k;
+
+ if (getint(&p, "key data 'version'", &key_versions)) return EINVAL;
+ CHECK_UINT16(key_versions);
+ ret = krb5_store_int16(sp, key_versions);
+ if (ret) return ret;
+
+ if (getint(&p, "kvno", &kvno)) return EINVAL;
+ CHECK_UINT16(kvno);
+ ret = krb5_store_int16(sp, kvno);
+ if (ret) return ret;
+
+ for (k = 0; k < key_versions; k++) {
+ if (getint(&p, "enctype", &keytype)) return EINVAL;
+ CHECK_UINT16(keytype);
+ ret = krb5_store_int16(sp, keytype);
+ if (ret) return ret;
+
+ if (getint(&p, "encrypted key length", &keylen)) return EINVAL;
+ CHECK_UINT16(keylen);
+ ret = krb5_store_int16(sp, keylen);
+ if (ret) return ret;
+
+ if (keylen) {
+ buf = malloc(keylen);
+ if (!buf) return ENOMEM;
+ if (getdata(&p, buf, keylen, "key (or salt) data") != keylen) {
+ free(buf);
+ return EINVAL;
+ }
+ sz = krb5_storage_write(sp, buf, keylen);
+ free(buf);
+ if (sz != keylen) return ENOMEM;
+ } else {
+ if (strcmp(nexttoken(&p, 0,
+ "'-1' zero-length key/salt field"),
+ "-1") != 0) {
+ warnx("Expected '-1' field because key/salt length is 0");
+ return -1;
+ }
+ }
+ }
+ }
+ /*
+ * The rest is "extra data", but there's never any and we wouldn't
+ * know what to do with it.
+ */
+ /* nexttoken(&p, 0, "extra data"); */
+ return 0;
+}
+
diff --git a/third_party/heimdal/lib/hdb/hdb-sqlite.c b/third_party/heimdal/lib/hdb/hdb-sqlite.c
new file mode 100644
index 0000000..4bb2f8e
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/hdb-sqlite.c
@@ -0,0 +1,1075 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hdb_locl.h"
+#include "sqlite3.h"
+
+#define MAX_RETRIES 10
+
+typedef struct hdb_sqlite_db {
+ double version;
+ sqlite3 *db;
+ char *db_file;
+
+ sqlite3_stmt *connect;
+ sqlite3_stmt *get_version;
+ sqlite3_stmt *fetch;
+ sqlite3_stmt *get_ids;
+ sqlite3_stmt *add_entry;
+ sqlite3_stmt *add_principal;
+ sqlite3_stmt *add_alias;
+ sqlite3_stmt *delete_aliases;
+ sqlite3_stmt *update_entry;
+ sqlite3_stmt *remove;
+ sqlite3_stmt *get_all_entries;
+
+} hdb_sqlite_db;
+
+/* This should be used to mark updates which make the code incompatible
+ * with databases created with previous versions. Don't update it if
+ * compatibility is not broken. */
+#define HDBSQLITE_VERSION 0.1
+
+#define _HDBSQLITE_STRINGIFY(x) #x
+#define HDBSQLITE_STRINGIFY(x) _HDBSQLITE_STRINGIFY(x)
+
+#define HDBSQLITE_CREATE_TABLES \
+ " BEGIN TRANSACTION;" \
+ " CREATE TABLE Version (number REAL);" \
+ " INSERT INTO Version (number)" \
+ " VALUES (" HDBSQLITE_STRINGIFY(HDBSQLITE_VERSION) ");" \
+ " CREATE TABLE Principal" \
+ " (id INTEGER PRIMARY KEY," \
+ " principal TEXT UNIQUE NOT NULL," \
+ " canonical INTEGER," \
+ " entry INTEGER);" \
+ " CREATE TABLE Entry" \
+ " (id INTEGER PRIMARY KEY," \
+ " data BLOB);" \
+ " COMMIT"
+#define HDBSQLITE_CREATE_TRIGGERS \
+ " CREATE TRIGGER remove_principals AFTER DELETE ON Entry" \
+ " BEGIN" \
+ " DELETE FROM Principal" \
+ " WHERE entry = OLD.id;" \
+ " END"
+#define HDBSQLITE_CONNECT \
+ " PRAGMA journal_mode = WAL"
+#define HDBSQLITE_GET_VERSION \
+ " SELECT number FROM Version"
+#define HDBSQLITE_FETCH \
+ " SELECT Entry.data FROM Principal, Entry" \
+ " WHERE Principal.principal = ? AND" \
+ " Entry.id = Principal.entry"
+#define HDBSQLITE_GET_IDS \
+ " SELECT id, entry FROM Principal" \
+ " WHERE principal = ?"
+#define HDBSQLITE_ADD_ENTRY \
+ " INSERT INTO Entry (data) VALUES (?)"
+#define HDBSQLITE_ADD_PRINCIPAL \
+ " INSERT INTO Principal (principal, entry, canonical)" \
+ " VALUES (?, last_insert_rowid(), 1)"
+#define HDBSQLITE_ADD_ALIAS \
+ " INSERT INTO Principal (principal, entry, canonical)" \
+ " VALUES(?, ?, 0)"
+#define HDBSQLITE_DELETE_ALIASES \
+ " DELETE FROM Principal" \
+ " WHERE entry = ? AND canonical = 0"
+#define HDBSQLITE_UPDATE_ENTRY \
+ " UPDATE Entry SET data = ?" \
+ " WHERE id = ?"
+#define HDBSQLITE_REMOVE \
+ " DELETE FROM ENTRY WHERE id = " \
+ " (SELECT entry FROM Principal" \
+ " WHERE principal = ?)"
+#define HDBSQLITE_GET_ALL_ENTRIES \
+ " SELECT data FROM Entry"
+
+/**
+ * Wrapper around sqlite3_prepare_v2.
+ *
+ * @param context The current krb5 context
+ * @param statement Where to store the pointer to the statement
+ * after preparing it
+ * @param str SQL code for the statement
+ *
+ * @return 0 if OK, an error code if not
+ */
+static krb5_error_code
+hdb_sqlite_prepare_stmt(krb5_context context,
+ sqlite3 *db,
+ sqlite3_stmt **statement,
+ const char *str)
+{
+ int ret, tries = 0;
+
+ ret = sqlite3_prepare_v2(db, str, -1, statement, NULL);
+ while((tries++ < MAX_RETRIES) &&
+ ((ret == SQLITE_BUSY) ||
+ (ret == SQLITE_IOERR_BLOCKED) ||
+ (ret == SQLITE_LOCKED))) {
+ krb5_warnx(context, "hdb-sqlite: prepare busy");
+ sleep(1);
+ ret = sqlite3_prepare_v2(db, str, -1, statement, NULL);
+ }
+
+ if (ret != SQLITE_OK) {
+ krb5_set_error_message(context, HDB_ERR_UK_RERROR,
+ "Failed to prepare stmt %s: %s",
+ str, sqlite3_errmsg(db));
+ return HDB_ERR_UK_RERROR;
+ }
+
+ return 0;
+}
+
+static krb5_error_code
+prep_stmts(krb5_context context, hdb_sqlite_db *hsdb)
+{
+ int ret;
+
+ ret = hdb_sqlite_prepare_stmt(context, hsdb->db,
+ &hsdb->connect,
+ HDBSQLITE_CONNECT);
+ if (ret)
+ return ret;
+ ret = hdb_sqlite_prepare_stmt(context, hsdb->db,
+ &hsdb->get_version,
+ HDBSQLITE_GET_VERSION);
+ if (ret)
+ return ret;
+ ret = hdb_sqlite_prepare_stmt(context, hsdb->db,
+ &hsdb->fetch,
+ HDBSQLITE_FETCH);
+ if (ret)
+ return ret;
+ ret = hdb_sqlite_prepare_stmt(context, hsdb->db,
+ &hsdb->get_ids,
+ HDBSQLITE_GET_IDS);
+ if (ret)
+ return ret;
+ ret = hdb_sqlite_prepare_stmt(context, hsdb->db,
+ &hsdb->add_entry,
+ HDBSQLITE_ADD_ENTRY);
+ if (ret)
+ return ret;
+ ret = hdb_sqlite_prepare_stmt(context, hsdb->db,
+ &hsdb->add_principal,
+ HDBSQLITE_ADD_PRINCIPAL);
+ if (ret)
+ return ret;
+ ret = hdb_sqlite_prepare_stmt(context, hsdb->db,
+ &hsdb->add_alias,
+ HDBSQLITE_ADD_ALIAS);
+ if (ret)
+ return ret;
+ ret = hdb_sqlite_prepare_stmt(context, hsdb->db,
+ &hsdb->delete_aliases,
+ HDBSQLITE_DELETE_ALIASES);
+ if (ret)
+ return ret;
+ ret = hdb_sqlite_prepare_stmt(context, hsdb->db,
+ &hsdb->update_entry,
+ HDBSQLITE_UPDATE_ENTRY);
+ if (ret)
+ return ret;
+ ret = hdb_sqlite_prepare_stmt(context, hsdb->db,
+ &hsdb->remove,
+ HDBSQLITE_REMOVE);
+ if (ret)
+ return ret;
+ ret = hdb_sqlite_prepare_stmt(context, hsdb->db,
+ &hsdb->get_all_entries,
+ HDBSQLITE_GET_ALL_ENTRIES);
+ return ret;
+}
+
+static void
+finalize_stmts(krb5_context context, hdb_sqlite_db *hsdb)
+{
+ if (hsdb->connect != NULL)
+ sqlite3_finalize(hsdb->connect);
+ hsdb->connect = NULL;
+
+ if (hsdb->get_version != NULL)
+ sqlite3_finalize(hsdb->get_version);
+ hsdb->get_version = NULL;
+
+ if (hsdb->fetch != NULL)
+ sqlite3_finalize(hsdb->fetch);
+ hsdb->fetch = NULL;
+
+ if (hsdb->get_ids != NULL)
+ sqlite3_finalize(hsdb->get_ids);
+ hsdb->get_ids = NULL;
+
+ if (hsdb->add_entry != NULL)
+ sqlite3_finalize(hsdb->add_entry);
+ hsdb->add_entry = NULL;
+
+ if (hsdb->add_principal != NULL)
+ sqlite3_finalize(hsdb->add_principal);
+ hsdb->add_principal = NULL;
+
+ if (hsdb->add_alias != NULL)
+ sqlite3_finalize(hsdb->add_alias);
+ hsdb->add_alias = NULL;
+
+ if (hsdb->delete_aliases != NULL)
+ sqlite3_finalize(hsdb->delete_aliases);
+ hsdb->delete_aliases = NULL;
+
+ if (hsdb->update_entry != NULL)
+ sqlite3_finalize(hsdb->update_entry);
+ hsdb->update_entry = NULL;
+
+ if (hsdb->remove != NULL)
+ sqlite3_finalize(hsdb->remove);
+ hsdb->remove = NULL;
+
+ if (hsdb->get_all_entries != NULL)
+ sqlite3_finalize(hsdb->get_all_entries);
+ hsdb->get_all_entries = NULL;
+}
+
+/**
+ * A wrapper around sqlite3_exec.
+ *
+ * @param context The current krb5 context
+ * @param database An open sqlite3 database handle
+ * @param statement SQL code to execute
+ * @param error_code What to return if the statement fails
+ *
+ * @return 0 if OK, else error_code
+ */
+static krb5_error_code
+hdb_sqlite_exec_stmt(krb5_context context,
+ hdb_sqlite_db *hsdb,
+ const char *statement,
+ krb5_error_code error_code)
+{
+ int ret;
+ int reinit_stmts = 0;
+ sqlite3 *database = hsdb->db;
+
+ ret = sqlite3_exec(database, statement, NULL, NULL, NULL);
+
+ while(((ret == SQLITE_BUSY) ||
+ (ret == SQLITE_IOERR_BLOCKED) ||
+ (ret == SQLITE_LOCKED))) {
+ if (reinit_stmts == 0 && ret == SQLITE_BUSY) {
+ finalize_stmts(context, hsdb);
+ reinit_stmts = 1;
+ }
+ krb5_warnx(context, "hdb-sqlite: exec busy: %d", (int)getpid());
+ sleep(1);
+ ret = sqlite3_exec(database, statement, NULL, NULL, NULL);
+ }
+
+ if (ret != SQLITE_OK && error_code) {
+ krb5_set_error_message(context, error_code,
+ "Execute %s: %s", statement,
+ sqlite3_errmsg(database));
+ return error_code;
+ }
+
+ if (reinit_stmts)
+ return prep_stmts(context, hsdb);
+
+ return 0;
+}
+
+/**
+ *
+ */
+
+static krb5_error_code
+bind_principal(krb5_context context, krb5_const_principal principal, sqlite3_stmt *stmt, int key)
+{
+ krb5_error_code ret;
+ char *str = NULL;
+
+ ret = krb5_unparse_name(context, principal, &str);
+ if (ret)
+ return ret;
+
+ sqlite3_bind_text(stmt, key, str, -1, SQLITE_TRANSIENT);
+ free(str);
+ return 0;
+}
+
+static int hdb_sqlite_step(krb5_context, sqlite3 *, sqlite3_stmt *);
+
+/**
+ * Opens an sqlite3 database handle to a file, may create the
+ * database file depending on flags.
+ *
+ * @param context The current krb5 context
+ * @param db Heimdal database handle
+ * @param flags Controls whether or not the file may be created,
+ * may be 0 or SQLITE_OPEN_CREATE
+ */
+static krb5_error_code
+hdb_sqlite_open_database(krb5_context context, HDB *db, int flags)
+{
+ int ret;
+ hdb_sqlite_db *hsdb = (hdb_sqlite_db*) db->hdb_db;
+
+ ret = sqlite3_open_v2(hsdb->db_file, &hsdb->db,
+ SQLITE_OPEN_READWRITE | flags, NULL);
+
+ if (ret) {
+ if (hsdb->db) {
+ ret = ENOENT;
+ krb5_set_error_message(context, ret,
+ "Error opening sqlite database %s: %s",
+ hsdb->db_file, sqlite3_errmsg(hsdb->db));
+ sqlite3_close(hsdb->db);
+ hsdb->db = NULL;
+ } else
+ ret = krb5_enomem(context);
+ return ret;
+ }
+ return 0;
+}
+
+static int
+hdb_sqlite_step(krb5_context context, sqlite3 *db, sqlite3_stmt *stmt)
+{
+ int ret;
+
+ ret = sqlite3_step(stmt);
+ while(((ret == SQLITE_BUSY) ||
+ (ret == SQLITE_IOERR_BLOCKED) ||
+ (ret == SQLITE_LOCKED))) {
+ krb5_warnx(context, "hdb-sqlite: step busy: %d", (int)getpid());
+ sleep(1);
+ ret = sqlite3_step(stmt);
+ }
+ return ret;
+}
+
+/**
+ * Closes the database and frees memory allocated for statements.
+ *
+ * @param context The current krb5 context
+ * @param db Heimdal database handle
+ */
+static krb5_error_code
+hdb_sqlite_close_database(krb5_context context, HDB *db)
+{
+ hdb_sqlite_db *hsdb = (hdb_sqlite_db *) db->hdb_db;
+
+ finalize_stmts(context, hsdb);
+
+ /* XXX Use sqlite3_close_v2() when we upgrade SQLite3 */
+ if (sqlite3_close(hsdb->db) != SQLITE_OK) {
+ krb5_set_error_message(context, HDB_ERR_UK_SERROR,
+ "SQLite BEGIN TRANSACTION failed: %s",
+ sqlite3_errmsg(hsdb->db));
+ return HDB_ERR_UK_SERROR;
+ }
+
+ return 0;
+}
+
+/**
+ * Opens an sqlite database file and prepares it for use.
+ * If the file does not exist it will be created.
+ *
+ * @param context The current krb5_context
+ * @param db The heimdal database handle
+ * @param filename Where to store the database file
+ *
+ * @return 0 if everything worked, an error code if not
+ */
+static krb5_error_code
+hdb_sqlite_make_database(krb5_context context, HDB *db, const char *filename)
+{
+ int ret;
+ int created_file = 0;
+ hdb_sqlite_db *hsdb = (hdb_sqlite_db *) db->hdb_db;
+
+ hsdb->db_file = strdup(filename);
+ if(hsdb->db_file == NULL)
+ return ENOMEM;
+
+ ret = hdb_sqlite_open_database(context, db, 0);
+ if (ret) {
+ ret = hdb_sqlite_open_database(context, db, SQLITE_OPEN_CREATE);
+ if (ret) goto out;
+
+ created_file = 1;
+
+ hdb_sqlite_exec_stmt(context, hsdb,
+ "PRAGMA main.page_size = 8192",
+ HDB_ERR_UK_SERROR);
+
+ ret = hdb_sqlite_exec_stmt(context, hsdb,
+ HDBSQLITE_CREATE_TABLES,
+ HDB_ERR_UK_SERROR);
+ if (ret) goto out;
+
+ ret = hdb_sqlite_exec_stmt(context, hsdb,
+ HDBSQLITE_CREATE_TRIGGERS,
+ HDB_ERR_UK_SERROR);
+ if (ret) goto out;
+ }
+
+ ret = prep_stmts(context, hsdb);
+ if (ret) goto out;
+
+ sqlite3_reset(hsdb->connect);
+ (void) hdb_sqlite_step(context, hsdb->db, hsdb->connect);
+ sqlite3_reset(hsdb->connect);
+
+ ret = hdb_sqlite_step(context, hsdb->db, hsdb->get_version);
+ if(ret == SQLITE_ROW) {
+ hsdb->version = sqlite3_column_double(hsdb->get_version, 0);
+ }
+ sqlite3_reset(hsdb->get_version);
+ ret = 0;
+
+ if(hsdb->version != HDBSQLITE_VERSION) {
+ ret = HDB_ERR_UK_SERROR;
+ krb5_set_error_message(context, ret, "HDBSQLITE_VERSION mismatch");
+ }
+
+ if(ret) goto out;
+
+ return 0;
+
+ out:
+ if (hsdb->db)
+ sqlite3_close(hsdb->db);
+ if (created_file)
+ unlink(hsdb->db_file);
+ free(hsdb->db_file);
+ hsdb->db_file = NULL;
+
+ return ret;
+}
+
+/**
+ * Retrieves an entry by searching for the given
+ * principal in the Principal database table, both
+ * for canonical principals and aliases.
+ *
+ * @param context The current krb5_context
+ * @param db Heimdal database handle
+ * @param principal The principal whose entry to search for
+ * @param flags Currently only for HDB_F_DECRYPT
+ * @param kvno kvno to fetch is HDB_F_KVNO_SPECIFIED use used
+ *
+ * @return 0 if everything worked, an error code if not
+ */
+static krb5_error_code
+hdb_sqlite_fetch_kvno(krb5_context context, HDB *db, krb5_const_principal principal,
+ unsigned flags, krb5_kvno kvno, hdb_entry *entry)
+{
+ int sqlite_error;
+ krb5_error_code ret;
+ hdb_sqlite_db *hsdb = (hdb_sqlite_db*)(db->hdb_db);
+ sqlite3_stmt *fetch = hsdb->fetch;
+ krb5_data value;
+ krb5_principal enterprise_principal = NULL;
+
+ if (principal->name.name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
+ if (principal->name.name_string.len != 1) {
+ ret = KRB5_PARSE_MALFORMED;
+ krb5_set_error_message(context, ret, "malformed principal: "
+ "enterprise name with %d name components",
+ principal->name.name_string.len);
+ return ret;
+ }
+ ret = krb5_parse_name(context, principal->name.name_string.val[0],
+ &enterprise_principal);
+ if (ret)
+ return ret;
+ principal = enterprise_principal;
+ }
+
+ ret = bind_principal(context, principal, fetch, 1);
+ krb5_free_principal(context, enterprise_principal);
+ if (ret)
+ return ret;
+
+ sqlite_error = hdb_sqlite_step(context, hsdb->db, fetch);
+ if (sqlite_error != SQLITE_ROW) {
+ if(sqlite_error == SQLITE_DONE) {
+ ret = HDB_ERR_NOENTRY;
+ goto out;
+ } else {
+ ret = HDB_ERR_UK_RERROR;
+ krb5_set_error_message(context, ret,
+ "sqlite fetch failed: %d",
+ sqlite_error);
+ goto out;
+ }
+ }
+
+ value.length = sqlite3_column_bytes(fetch, 0);
+ value.data = (void *) sqlite3_column_blob(fetch, 0);
+
+ ret = hdb_value2entry(context, &value, entry);
+ if(ret)
+ goto out;
+
+ if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) {
+ ret = hdb_unseal_keys(context, db, entry);
+ if(ret) {
+ hdb_free_entry(context, db, entry);
+ goto out;
+ }
+ }
+
+ ret = 0;
+
+out:
+
+ sqlite3_clear_bindings(fetch);
+ sqlite3_reset(fetch);
+
+
+ return ret;
+}
+
+/**
+ * Convenience function to step a prepared statement with no
+ * value once.
+ *
+ * @param context The current krb5_context
+ * @param statement A prepared sqlite3 statement
+ *
+ * @return 0 if everything worked, an error code if not
+ */
+static krb5_error_code
+hdb_sqlite_step_once(krb5_context context, HDB *db, sqlite3_stmt *statement)
+{
+ int ret;
+ hdb_sqlite_db *hsdb = (hdb_sqlite_db *) db->hdb_db;
+
+ ret = hdb_sqlite_step(context, hsdb->db, statement);
+ sqlite3_clear_bindings(statement);
+ sqlite3_reset(statement);
+
+ return ret;
+}
+
+
+/**
+ * Stores an hdb_entry in the database. If flags contains HDB_F_REPLACE
+ * a previous entry may be replaced.
+ *
+ * @param context The current krb5_context
+ * @param db Heimdal database handle
+ * @param flags May currently only contain HDB_F_REPLACE
+ * @param entry The data to store
+ *
+ * @return 0 if everything worked, an error code if not
+ */
+static krb5_error_code
+hdb_sqlite_store(krb5_context context, HDB *db, unsigned flags,
+ hdb_entry *entry)
+{
+ int ret;
+ int i;
+ sqlite_int64 entry_id;
+ const HDB_Ext_Aliases *aliases;
+
+ hdb_sqlite_db *hsdb = (hdb_sqlite_db *)(db->hdb_db);
+ krb5_data value;
+ sqlite3_stmt *get_ids = hsdb->get_ids;
+
+ krb5_data_zero(&value);
+
+ ret = hdb_sqlite_exec_stmt(context, hsdb,
+ "BEGIN IMMEDIATE TRANSACTION",
+ HDB_ERR_UK_SERROR);
+ if(ret != SQLITE_OK) {
+ ret = HDB_ERR_UK_SERROR;
+ krb5_set_error_message(context, ret,
+ "SQLite BEGIN TRANSACTION failed: %s",
+ sqlite3_errmsg(hsdb->db));
+ goto rollback;
+ }
+
+ ret = hdb_seal_keys(context, db, entry);
+ if(ret) {
+ goto rollback;
+ }
+
+ ret = hdb_entry2value(context, entry, &value);
+ if(ret) {
+ goto rollback;
+ }
+
+ ret = bind_principal(context, entry->principal, get_ids, 1);
+ if (ret)
+ goto rollback;
+
+ ret = hdb_sqlite_step(context, hsdb->db, get_ids);
+
+ if(ret == SQLITE_DONE) { /* No such principal */
+
+ sqlite3_bind_blob(hsdb->add_entry, 1,
+ value.data, value.length, SQLITE_STATIC);
+ ret = hdb_sqlite_step(context, hsdb->db, hsdb->add_entry);
+ sqlite3_clear_bindings(hsdb->add_entry);
+ sqlite3_reset(hsdb->add_entry);
+ if (ret != SQLITE_DONE && ret != SQLITE_CONSTRAINT) {
+ ret = HDB_ERR_UK_SERROR;
+ goto rollback;
+ }
+ if (ret == SQLITE_CONSTRAINT) {
+ ret = HDB_ERR_EXISTS;
+ goto rollback;
+ }
+
+ ret = bind_principal(context, entry->principal, hsdb->add_principal, 1);
+ if (ret)
+ goto rollback;
+
+ ret = hdb_sqlite_step(context, hsdb->db, hsdb->add_principal);
+ sqlite3_clear_bindings(hsdb->add_principal);
+ sqlite3_reset(hsdb->add_principal);
+ if (ret != SQLITE_DONE && ret != SQLITE_CONSTRAINT) {
+ ret = HDB_ERR_UK_SERROR;
+ goto rollback;
+ }
+ if (ret == SQLITE_CONSTRAINT) {
+ ret = HDB_ERR_EXISTS;
+ goto rollback;
+ }
+
+ /* Now let's learn what Entry ID we got for the new principal */
+ sqlite3_reset(get_ids);
+ ret = hdb_sqlite_step(context, hsdb->db, get_ids);
+ if (ret != SQLITE_ROW) {
+ ret = HDB_ERR_UK_SERROR;
+ goto rollback;
+ }
+
+ entry_id = sqlite3_column_int64(get_ids, 1);
+
+ } else if(ret == SQLITE_ROW) { /* Found a principal */
+
+ if(!(flags & HDB_F_REPLACE)) {
+ ret = HDB_ERR_EXISTS;
+ goto rollback;
+ }
+
+ entry_id = sqlite3_column_int64(get_ids, 1);
+
+ sqlite3_bind_int64(hsdb->delete_aliases, 1, entry_id);
+ ret = hdb_sqlite_step_once(context, db, hsdb->delete_aliases);
+ if (ret != SQLITE_DONE) {
+ ret = HDB_ERR_UK_SERROR;
+ goto rollback;
+ }
+
+ sqlite3_bind_blob(hsdb->update_entry, 1,
+ value.data, value.length, SQLITE_STATIC);
+ sqlite3_bind_int64(hsdb->update_entry, 2, entry_id);
+ ret = hdb_sqlite_step_once(context, db, hsdb->update_entry);
+ if (ret != SQLITE_DONE) {
+ ret = HDB_ERR_UK_SERROR;
+ goto rollback;
+ }
+
+ } else {
+ /* Error! */
+ ret = HDB_ERR_UK_SERROR;
+ goto rollback;
+ }
+
+ ret = hdb_entry_get_aliases(entry, &aliases);
+ if(ret || aliases == NULL)
+ goto commit;
+
+ for(i = 0; i < aliases->aliases.len; i++) {
+
+ ret = bind_principal(context, &aliases->aliases.val[i], hsdb->add_alias, 1);
+ if (ret)
+ goto rollback;
+
+ sqlite3_bind_int64(hsdb->add_alias, 2, entry_id);
+ ret = hdb_sqlite_step_once(context, db, hsdb->add_alias);
+ if (ret == SQLITE_CONSTRAINT) {
+ ret = HDB_ERR_EXISTS;
+ goto rollback;
+ }
+ if (ret != SQLITE_DONE) {
+ ret = HDB_ERR_UK_SERROR;
+ goto rollback;
+ }
+ }
+
+commit:
+ krb5_data_free(&value);
+ sqlite3_clear_bindings(get_ids);
+ sqlite3_reset(get_ids);
+
+ if ((flags & HDB_F_PRECHECK)) {
+ (void) hdb_sqlite_exec_stmt(context, hsdb, "ROLLBACK", 0);
+ return 0;
+ }
+
+ ret = hdb_sqlite_exec_stmt(context, hsdb, "COMMIT", HDB_ERR_UK_SERROR);
+ if(ret != SQLITE_OK)
+ krb5_warnx(context, "hdb-sqlite: COMMIT problem: %ld: %s",
+ (long)HDB_ERR_UK_SERROR, sqlite3_errmsg(hsdb->db));
+
+ return ret == SQLITE_OK ? 0 : HDB_ERR_UK_SERROR;
+
+rollback:
+ krb5_data_free(&value);
+ sqlite3_clear_bindings(get_ids);
+ sqlite3_reset(get_ids);
+ krb5_warnx(context, "hdb-sqlite: store rollback problem: %d: %s",
+ ret, sqlite3_errmsg(hsdb->db));
+
+ (void) hdb_sqlite_exec_stmt(context, hsdb, "ROLLBACK", 0);
+ return ret;
+}
+
+/**
+ * This may be called often by other code, since the BDB backends
+ * can not have several open connections. SQLite can handle
+ * many processes with open handles to the database file
+ * and closing/opening the handle is an expensive operation.
+ * Hence, this function does nothing.
+ *
+ * @param context The current krb5 context
+ * @param db Heimdal database handle
+ *
+ * @return Always returns 0
+ */
+static krb5_error_code
+hdb_sqlite_close(krb5_context context, HDB *db)
+{
+ return 0;
+}
+
+/**
+ * The opposite of hdb_sqlite_close. Since SQLite accepts
+ * many open handles to the database file the handle does not
+ * need to be closed, or reopened.
+ *
+ * @param context The current krb5 context
+ * @param db Heimdal database handle
+ * @param flags
+ * @param mode_t
+ *
+ * @return Always returns 0
+ */
+static krb5_error_code
+hdb_sqlite_open(krb5_context context, HDB *db, int flags, mode_t mode)
+{
+ return 0;
+}
+
+/**
+ * Closes the databse and frees all resources.
+ *
+ * @param context The current krb5 context
+ * @param db Heimdal database handle
+ *
+ * @return 0 on success, an error code if not
+ */
+static krb5_error_code
+hdb_sqlite_destroy(krb5_context context, HDB *db)
+{
+ int ret, ret2;
+ hdb_sqlite_db *hsdb;
+
+ ret = hdb_clear_master_key(context, db);
+
+ ret2 = hdb_sqlite_close_database(context, db);
+
+ hsdb = (hdb_sqlite_db*)(db->hdb_db);
+
+ krb5_config_free_strings(db->virtual_hostbased_princ_svcs);
+ free(hsdb->db_file);
+ free(db->hdb_name);
+ free(db->hdb_db);
+ free(db);
+
+ return ret ? ret : ret2;
+}
+
+static krb5_error_code
+hdb_sqlite_set_sync(krb5_context context, HDB *db, int on)
+{
+ return hdb_sqlite_exec_stmt(context, (hdb_sqlite_db*)(db->hdb_db),
+ on ? "PRAGMA main.synchronous = NORMAL" :
+ "PRAGMA main.synchronous = OFF",
+ HDB_ERR_UK_SERROR);
+}
+
+/*
+ * Not sure if this is needed.
+ */
+static krb5_error_code
+hdb_sqlite_lock(krb5_context context, HDB *db, int operation)
+{
+ krb5_set_error_message(context, HDB_ERR_CANT_LOCK_DB,
+ "lock not implemented");
+ return HDB_ERR_CANT_LOCK_DB;
+}
+
+/*
+ * Not sure if this is needed.
+ */
+static krb5_error_code
+hdb_sqlite_unlock(krb5_context context, HDB *db)
+{
+ krb5_set_error_message(context, HDB_ERR_CANT_LOCK_DB,
+ "unlock not implemented");
+ return HDB_ERR_CANT_LOCK_DB;
+}
+
+/*
+ * Should get the next entry, to allow iteration over all entries.
+ */
+static krb5_error_code
+hdb_sqlite_nextkey(krb5_context context, HDB *db, unsigned flags,
+ hdb_entry *entry)
+{
+ krb5_error_code ret = 0;
+ int sqlite_error;
+ krb5_data value;
+
+ hdb_sqlite_db *hsdb = (hdb_sqlite_db *) db->hdb_db;
+
+ sqlite_error = hdb_sqlite_step(context, hsdb->db, hsdb->get_all_entries);
+ if(sqlite_error == SQLITE_ROW) {
+ /* Found an entry */
+ value.length = sqlite3_column_bytes(hsdb->get_all_entries, 0);
+ value.data = (void *) sqlite3_column_blob(hsdb->get_all_entries, 0);
+ memset(entry, 0, sizeof(*entry));
+ ret = hdb_value2entry(context, &value, entry);
+ }
+ else if(sqlite_error == SQLITE_DONE) {
+ /* No more entries */
+ ret = HDB_ERR_NOENTRY;
+ sqlite3_reset(hsdb->get_all_entries);
+ }
+ else {
+ ret = HDB_ERR_UK_RERROR;
+ krb5_set_error_message(context, HDB_ERR_UK_RERROR,
+ "SELECT failed after returning one or "
+ "more rows: %s", sqlite3_errmsg(hsdb->db));
+
+ }
+
+ return ret;
+}
+
+/*
+ * Should get the first entry in the database.
+ * What is flags used for?
+ */
+static krb5_error_code
+hdb_sqlite_firstkey(krb5_context context, HDB *db, unsigned flags,
+ hdb_entry *entry)
+{
+ hdb_sqlite_db *hsdb = (hdb_sqlite_db *) db->hdb_db;
+ krb5_error_code ret;
+
+ sqlite3_reset(hsdb->get_all_entries);
+
+ ret = hdb_sqlite_nextkey(context, db, flags, entry);
+ if(ret)
+ return ret;
+
+ return 0;
+}
+
+/*
+ * Renames the database file.
+ */
+static krb5_error_code
+hdb_sqlite_rename(krb5_context context, HDB *db, const char *new_name)
+{
+ krb5_error_code ret, ret2;
+ hdb_sqlite_db *hsdb = (hdb_sqlite_db *) db->hdb_db;
+
+ krb5_warnx(context, "hdb_sqlite_rename");
+
+ if (strncasecmp(new_name, "sqlite:", 7) == 0)
+ new_name += 7;
+
+ ret = hdb_sqlite_close_database(context, db);
+
+ if (rename(hsdb->db_file, new_name) == -1)
+ return errno;
+
+ free(hsdb->db_file);
+ ret2 = hdb_sqlite_make_database(context, db, new_name);
+ return ret ? ret : ret2;
+}
+
+/*
+ * Removes a principal, including aliases and associated entry.
+ */
+static krb5_error_code
+hdb_sqlite_remove(krb5_context context, HDB *db,
+ unsigned flags, krb5_const_principal principal)
+{
+ krb5_error_code ret;
+ hdb_sqlite_db *hsdb = (hdb_sqlite_db*)(db->hdb_db);
+ sqlite3_stmt *get_ids = hsdb->get_ids;
+ sqlite3_stmt *rm = hsdb->remove;
+
+ ret = bind_principal(context, principal, rm, 1);
+
+ if (ret == 0)
+ ret = hdb_sqlite_exec_stmt(context, hsdb,
+ "BEGIN IMMEDIATE TRANSACTION",
+ HDB_ERR_UK_SERROR);
+ if (ret != SQLITE_OK) {
+ ret = HDB_ERR_UK_SERROR;
+ (void) hdb_sqlite_exec_stmt(context, hsdb, "ROLLBACK", 0);
+ krb5_set_error_message(context, ret,
+ "SQLite BEGIN TRANSACTION failed: %s",
+ sqlite3_errmsg(hsdb->db));
+ return ret;
+ }
+
+ if ((flags & HDB_F_PRECHECK)) {
+ ret = bind_principal(context, principal, get_ids, 1);
+ if (ret)
+ return ret;
+
+ ret = hdb_sqlite_step(context, hsdb->db, get_ids);
+ sqlite3_clear_bindings(get_ids);
+ sqlite3_reset(get_ids);
+ if (ret == SQLITE_DONE) {
+ (void) hdb_sqlite_exec_stmt(context, hsdb, "ROLLBACK", 0);
+ return HDB_ERR_NOENTRY;
+ }
+ }
+
+ ret = hdb_sqlite_step(context, hsdb->db, rm);
+ sqlite3_clear_bindings(rm);
+ sqlite3_reset(rm);
+ if (ret != SQLITE_DONE) {
+ (void) hdb_sqlite_exec_stmt(context, hsdb, "ROLLBACK", 0);
+ ret = HDB_ERR_UK_SERROR;
+ krb5_set_error_message(context, ret, "sqlite remove failed: %d", ret);
+ return ret;
+ }
+
+ if ((flags & HDB_F_PRECHECK)) {
+ (void) hdb_sqlite_exec_stmt(context, hsdb, "ROLLBACK", 0);
+ return 0;
+ }
+
+ ret = hdb_sqlite_exec_stmt(context, hsdb, "COMMIT", HDB_ERR_UK_SERROR);
+ if (ret != SQLITE_OK)
+ krb5_warnx(context, "hdb-sqlite: COMMIT problem: %ld: %s",
+ (long)HDB_ERR_UK_SERROR, sqlite3_errmsg(hsdb->db));
+
+ return 0;
+}
+
+/**
+ * Create SQLITE object, and creates the on disk database if its doesn't exists.
+ *
+ * @param context A Kerberos 5 context.
+ * @param db a returned database handle.
+ * @param filename filename
+ *
+ * @return 0 on success, an error code if not
+ */
+
+krb5_error_code
+hdb_sqlite_create(krb5_context context, HDB **db, const char *filename)
+{
+ krb5_error_code ret;
+ hdb_sqlite_db *hsdb;
+
+ *db = calloc(1, sizeof (**db));
+ if (*db == NULL)
+ return krb5_enomem(context);
+
+ (*db)->hdb_name = strdup(filename);
+ if ((*db)->hdb_name == NULL) {
+ free(*db);
+ *db = NULL;
+ return krb5_enomem(context);
+ }
+
+ hsdb = (hdb_sqlite_db*) calloc(1, sizeof (*hsdb));
+ if (hsdb == NULL) {
+ free((*db)->hdb_name);
+ free(*db);
+ *db = NULL;
+ return krb5_enomem(context);
+ }
+
+ (*db)->hdb_db = hsdb;
+
+ /* XXX make_database should make sure everything else is freed on error */
+ ret = hdb_sqlite_make_database(context, *db, filename);
+ if (ret) {
+ free((*db)->hdb_db);
+ free(*db);
+ *db = NULL;
+ return ret;
+ }
+
+ (*db)->hdb_master_key_set = 0;
+ (*db)->hdb_openp = 0;
+ (*db)->hdb_capability_flags = HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL;
+
+ (*db)->hdb_open = hdb_sqlite_open;
+ (*db)->hdb_close = hdb_sqlite_close;
+
+ (*db)->hdb_lock = hdb_sqlite_lock;
+ (*db)->hdb_unlock = hdb_sqlite_unlock;
+ (*db)->hdb_firstkey = hdb_sqlite_firstkey;
+ (*db)->hdb_nextkey = hdb_sqlite_nextkey;
+ (*db)->hdb_fetch_kvno = hdb_sqlite_fetch_kvno;
+ (*db)->hdb_store = hdb_sqlite_store;
+ (*db)->hdb_remove = hdb_sqlite_remove;
+ (*db)->hdb_destroy = hdb_sqlite_destroy;
+ (*db)->hdb_rename = hdb_sqlite_rename;
+ (*db)->hdb_set_sync = hdb_sqlite_set_sync;
+ (*db)->hdb__get = NULL;
+ (*db)->hdb__put = NULL;
+ (*db)->hdb__del = NULL;
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hdb/hdb.asn1 b/third_party/heimdal/lib/hdb/hdb.asn1
new file mode 100644
index 0000000..b0bfbf9
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/hdb.asn1
@@ -0,0 +1,251 @@
+-- $Id$
+HDB DEFINITIONS ::=
+BEGIN
+
+IMPORTS EncryptionKey, KerberosTime, Principal FROM krb5;
+
+hdb_db_format INTEGER ::= 2 -- format of database,
+ -- update when making changes
+
+-- these must have the same value as the pa-* counterparts
+hdb-pw-salt INTEGER ::= 3
+hdb-afs3-salt INTEGER ::= 10
+
+Salt ::= SEQUENCE {
+ type[0] INTEGER (0..4294967295),
+ salt[1] OCTET STRING,
+ opaque[2] OCTET STRING OPTIONAL
+}
+
+Key ::= SEQUENCE {
+ mkvno[0] INTEGER (0..4294967295) OPTIONAL, -- master key version number
+ key[1] EncryptionKey,
+ salt[2] Salt OPTIONAL
+}
+
+Event ::= SEQUENCE {
+ time[0] KerberosTime,
+ principal[1] Principal OPTIONAL
+}
+
+HDBFlags ::= BIT STRING {
+ initial(0), -- require as-req
+ forwardable(1), -- may issue forwardable
+ proxiable(2), -- may issue proxiable
+ renewable(3), -- may issue renewable
+ postdate(4), -- may issue postdatable
+ server(5), -- may be server
+ client(6), -- may be client
+ invalid(7), -- entry is invalid
+ require-preauth(8), -- must use preauth
+ change-pw(9), -- change password service
+ require-hwauth(10), -- must use hwauth
+ ok-as-delegate(11), -- as in TicketFlags
+ user-to-user(12), -- may use user-to-user auth
+ immutable(13), -- may not be deleted
+ trusted-for-delegation(14), -- Trusted to print forwardabled tickets
+ allow-kerberos4(15), -- Allow Kerberos 4 requests
+ allow-digest(16), -- Allow digest requests
+ locked-out(17), -- Account is locked out,
+ -- authentication will be denied
+ require-pwchange(18), -- require a passwd change
+
+ materialize(19), -- store even if within virtual namespace
+ virtual-keys(20), -- entry stored; keys mostly derived
+ virtual(21), -- entry not stored; keys always derived
+ synthetic(22), -- entry not stored; for PKINIT
+ no-auth-data-reqd(23), -- omit PAC from service tickets
+
+ force-canonicalize(30), -- force the KDC to return the canonical
+ -- principal irrespective of the setting
+ -- of the canonicalize KDC option
+ do-not-store(31) -- Not to be modified and stored in HDB
+}
+
+GENERATION ::= SEQUENCE {
+ time[0] KerberosTime, -- timestamp
+ usec[1] INTEGER (0..4294967295), -- microseconds
+ gen[2] INTEGER (0..4294967295) -- generation number
+}
+
+HDB-Ext-PKINIT-acl ::= SEQUENCE OF SEQUENCE {
+ subject[0] UTF8String,
+ issuer[1] UTF8String OPTIONAL,
+ anchor[2] UTF8String OPTIONAL
+}
+
+HDB-Ext-PKINIT-hash ::= SEQUENCE OF SEQUENCE {
+ digest-type[0] OBJECT IDENTIFIER,
+ digest[1] OCTET STRING
+}
+
+HDB-Ext-PKINIT-cert ::= SEQUENCE OF SEQUENCE {
+ cert[0] OCTET STRING
+}
+
+HDB-Ext-Constrained-delegation-acl ::= SEQUENCE OF Principal
+
+-- hdb-ext-referrals ::= PA-SERVER-REFERRAL-DATA
+
+HDB-Ext-Lan-Manager-OWF ::= OCTET STRING
+
+HDB-Ext-Password ::= SEQUENCE {
+ mkvno[0] INTEGER (0..4294967295) OPTIONAL, -- master key version number
+ password OCTET STRING
+}
+
+HDB-Ext-Aliases ::= SEQUENCE {
+ case-insensitive[0] BOOLEAN, -- case insensitive name allowed
+ aliases[1] SEQUENCE OF Principal -- all names, inc primary
+}
+
+Keys ::= SEQUENCE OF Key
+
+HDB_keyset ::= SEQUENCE {
+ kvno[0] INTEGER (0..4294967295),
+ keys[1] Keys,
+ set-time[2] KerberosTime OPTIONAL, -- time this keyset was created/set
+ ...
+}
+
+HDB-Ext-KeySet ::= SEQUENCE OF HDB_keyset
+
+--
+-- We need a function of current (or given, but it will always be current) time
+-- and a base hdb_entry or its HDB-Ext-KeyRotation and service ticket lifetime,
+-- that outputs a sequence of {kvno, set_time, max_life} representing past keys
+-- (up to one per past and current KeyRotation), current keys (for the current
+-- KeyRotation), up to one future key for the current KeyRotation, and up to
+-- one future key for the _next_ (future) KeyRotation if there is one.
+--
+-- We have to impose constraints on new KeyRotation elements of
+-- HDB-Ext-KeyRotation.
+--
+-- So virtual keysets (keytabs) will contain:
+--
+-- - up to one past keyset for all KeyRotation periods that are "applicable"
+-- - the current keyset for all KeyRotation periods that are "applicable"
+-- - up to one future keyset for all KeyRotation periods that are "applicable"
+--
+-- An applicable KeyRotation period is:
+--
+-- - the KeyRotation whose `epoch` is a) in the past and b) nearest to the
+-- current time - we call this the current KeyRotation
+-- - a KeyRotation whose `epoch` is nearest but in the past of the current
+-- one
+-- - a KeyRotation whose `epoch` is nearest but in the future of the current
+-- one
+--
+-- A service principal's max ticket life will be bounded by half the current
+-- key rotation period.
+--
+-- Note: There can be more than one applicable past KeyRotation, and more than
+-- one applicable KeyRotation. We might not want to permit this.
+-- However, it's probably easier to permit it, though we might not test
+-- end-to-end.
+--
+-- Testing:
+--
+-- - We should have standalone unit tests for all these pure functions.
+--
+-- - We should have a test that uses kadm5 and GSS to test against a KDC using
+-- small key rotation periods on the order of seconds, with back-off in case
+-- of losing a race condition.
+--
+KeyRotationFlags ::= BIT STRING {
+ deleted(0), -- if set on a materialized principal, this will mean
+ -- the principal does not exist
+ -- if set on a namespace, this will mean that
+ -- only materialized principal below it exist
+ parent(1) -- if set on a materialized principal, this will mean
+ -- that the keys for kvnos in this KeyRotation spec
+ -- will be derived from the parent's base keys and
+ -- corresponding KeyRotation spec
+ -- if set on a namespace, this flag will be ignored
+ -- (or we could support nested namespaces?)
+}
+KeyRotation ::= SEQUENCE {
+ -- base-kvno is always computed at set time and set for the principal,
+ -- and is never subject to admin choice. The base-kvno is that of the
+ -- current kvno at that period's `from` given the previous period.
+ --
+ -- Also, insertion of KeyRotation elements before existing ones (in
+ -- time) is never permitted, and all new KeyRotation elements must be
+ -- in the future relative to existing ones.
+ --
+ -- HDB-Ext-KeyRotation will always be sorted (as stored) by `from`, in
+ -- descending order.
+ --
+ -- Max service ticket lifetime will be constrained to no more than half
+ -- the period of the the applicable KeyRotation elements.
+ --
+ flags[0] KeyRotationFlags,
+ epoch[1] KerberosTime, -- start of this period
+ period[2] INTEGER(0..4294967295), -- key rotation seconds
+ base-kvno[3] INTEGER(0..4294967295), -- starting from this kvno
+ base-key-kvno[4]INTEGER(0..4294967295), -- kvno of base-key
+ ...
+}
+
+HDB-Ext-KeyRotation ::= SEQUENCE SIZE (1..3) OF KeyRotation
+
+HDB-extension ::= SEQUENCE {
+ mandatory[0] BOOLEAN, -- kdc MUST understand this extension,
+ -- if not the whole entry must
+ -- be rejected
+ data[1] CHOICE {
+ pkinit-acl[0] HDB-Ext-PKINIT-acl,
+ pkinit-cert-hash[1] HDB-Ext-PKINIT-hash,
+ allowed-to-delegate-to[2] HDB-Ext-Constrained-delegation-acl,
+-- referral-info[3] HDB-Ext-Referrals,
+ lm-owf[4] HDB-Ext-Lan-Manager-OWF,
+ password[5] HDB-Ext-Password,
+ aliases[6] HDB-Ext-Aliases,
+ last-pw-change[7] KerberosTime,
+ pkinit-cert[8] HDB-Ext-PKINIT-cert,
+ hist-keys[9] HDB-Ext-KeySet,
+ hist-kvno-diff-clnt[10] INTEGER (0..4294967295),
+ hist-kvno-diff-svc[11] INTEGER (0..4294967295),
+ policy[12] UTF8String,
+ principal-id[13] INTEGER(-9223372036854775808..9223372036854775807),
+ key-rotation[14] HDB-Ext-KeyRotation,
+ krb5-config[15] OCTET STRING,
+ ...
+ },
+ ...
+}
+
+HDB-extensions ::= SEQUENCE OF HDB-extension
+
+-- Just for convenience, for encoding this as TL data in lib/kadm5
+HDB-EncTypeList ::= SEQUENCE OF INTEGER (0..4294967295)
+
+HDB_entry ::= SEQUENCE {
+ principal[0] Principal OPTIONAL, -- this is optional only
+ -- for compatibility with libkrb5
+ kvno[1] INTEGER (0..4294967295),
+ keys[2] Keys,
+ created-by[3] Event,
+ modified-by[4] Event OPTIONAL,
+ valid-start[5] KerberosTime OPTIONAL,
+ valid-end[6] KerberosTime OPTIONAL,
+ pw-end[7] KerberosTime OPTIONAL,
+ max-life[8] INTEGER (0..4294967295) OPTIONAL,
+ max-renew[9] INTEGER (0..4294967295) OPTIONAL,
+ flags[10] HDBFlags,
+ etypes[11] HDB-EncTypeList OPTIONAL,
+ generation[12] GENERATION OPTIONAL,
+ extensions[13] HDB-extensions OPTIONAL,
+ session-etypes[14] HDB-EncTypeList OPTIONAL
+}
+
+HDB_entry_alias ::= [APPLICATION 0] SEQUENCE {
+ principal[0] Principal OPTIONAL
+}
+
+HDB-EntryOrAlias ::= CHOICE {
+ entry HDB_entry,
+ alias HDB_entry_alias
+}
+
+END
diff --git a/third_party/heimdal/lib/hdb/hdb.c b/third_party/heimdal/lib/hdb/hdb.c
new file mode 100644
index 0000000..171ba9e
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/hdb.c
@@ -0,0 +1,848 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include "hdb_locl.h"
+
+#ifdef HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+/*! @mainpage Heimdal database backend library
+ *
+ * @section intro Introduction
+ *
+ * Heimdal libhdb library provides the backend support for Heimdal kdc
+ * and kadmind. Its here where plugins for diffrent database engines
+ * can be pluged in and extend support for here Heimdal get the
+ * principal and policy data from.
+ *
+ * Example of Heimdal backend are:
+ * - Berkeley DB 1.85
+ * - Berkeley DB 3.0
+ * - Berkeley DB 4.0
+ * - New Berkeley DB
+ * - LDAP
+ *
+ *
+ * The project web page: http://www.h5l.org/
+ *
+ */
+
+const int hdb_interface_version = HDB_INTERFACE_VERSION;
+
+static struct hdb_method methods[] = {
+ /* "db:" should be db3 if we have db3, or db1 if we have db1 */
+#if HAVE_DB3
+ { HDB_INTERFACE_VERSION, NULL, NULL, 1 /*is_file_based*/, 1 /*can_taste*/,
+ "db:", hdb_db3_create},
+#elif HAVE_DB1
+ { HDB_INTERFACE_VERSION, NULL, NULL, 1, 1, "db:", hdb_db1_create},
+#endif
+#if HAVE_DB1
+ { HDB_INTERFACE_VERSION, NULL, NULL, 1, 1, "db1:", hdb_db1_create},
+#endif
+#if HAVE_DB3
+ { HDB_INTERFACE_VERSION, NULL, NULL, 1, 1, "db3:", hdb_db3_create},
+#endif
+#if HAVE_DB1
+ { HDB_INTERFACE_VERSION, NULL, NULL, 1, 1, "mit-db:", hdb_mitdb_create},
+#endif
+#if HAVE_LMDB
+ { HDB_INTERFACE_VERSION, NULL, NULL, 1, 1, "mdb:", hdb_mdb_create},
+ { HDB_INTERFACE_VERSION, NULL, NULL, 1, 1, "lmdb:", hdb_mdb_create},
+#endif
+#if HAVE_NDBM
+ { HDB_INTERFACE_VERSION, NULL, NULL, 1, 0, "ndbm:", hdb_ndbm_create},
+#endif
+#ifdef HAVE_SQLITE3
+ { HDB_INTERFACE_VERSION, NULL, NULL, 1, 1, "sqlite:", hdb_sqlite_create},
+#endif
+ /* The keytab interface can't use its hdb_open() method to "taste" a DB */
+ { HDB_INTERFACE_VERSION, NULL, NULL, 1, 0, "keytab:", hdb_keytab_create},
+ /* The rest are not file-based */
+#if defined(OPENLDAP) && !defined(OPENLDAP_MODULE)
+ { HDB_INTERFACE_VERSION, NULL, NULL, 0, 0, "ldap:", hdb_ldap_create},
+ { HDB_INTERFACE_VERSION, NULL, NULL, 0, 0, "ldapi:", hdb_ldapi_create},
+#elif defined(OPENLDAP)
+ { HDB_INTERFACE_VERSION, NULL, NULL, 0, 0, "ldap:", NULL},
+ { HDB_INTERFACE_VERSION, NULL, NULL, 0, 0, "ldapi:", NULL},
+#endif
+ { 0, NULL, NULL, 0, 0, NULL, NULL}
+};
+
+/**
+ * Returns the Keys of `e' for `kvno', or NULL if not found. The Keys will
+ * remain valid provided that the entry is not mutated.
+ *
+ * @param context Context
+ * @param e The HDB entry
+ * @param kvno The kvno
+ *
+ * @return A pointer to the Keys for the requested kvno.
+ */
+const Keys *
+hdb_kvno2keys(krb5_context context,
+ const hdb_entry *e,
+ krb5_kvno kvno)
+{
+ HDB_Ext_KeySet *hist_keys;
+ HDB_extension *extp;
+ size_t i;
+
+ if (kvno == 0 || e->kvno == kvno)
+ return &e->keys;
+
+ extp = hdb_find_extension(e, choice_HDB_extension_data_hist_keys);
+ if (extp == NULL)
+ return 0;
+
+ hist_keys = &extp->data.u.hist_keys;
+ for (i = 0; i < hist_keys->len; i++) {
+ if (hist_keys->val[i].kvno == kvno)
+ return &hist_keys->val[i].keys;
+ }
+
+ return NULL;
+}
+
+/* Based on remove_HDB_Ext_KeySet(), generated by the ASN.1 compiler */
+static int
+dequeue_HDB_Ext_KeySet(HDB_Ext_KeySet *data, unsigned int element, hdb_keyset *ks)
+{
+ if (element >= data->len) {
+ ks->kvno = 0;
+ ks->keys.len = 0;
+ ks->keys.val = 0;
+ ks->set_time = 0;
+ return ASN1_OVERRUN;
+ }
+ *ks = data->val[element];
+ data->len--;
+ /* Swap instead of memmove()... changes the order of elements */
+ if (element < data->len)
+ data->val[element] = data->val[data->len];
+ if (data->len == 0) {
+ free(data->val);
+ data->val = 0;
+ }
+ return 0;
+}
+
+
+/**
+ * Removes from `e' and optionally outputs the keyset for the requested `kvno'.
+ *
+ * @param context Context
+ * @param e The HDB entry
+ * @param kvno The key version number
+ * @param ks A pointer to a variable of type hdb_keyset (may be NULL)
+ *
+ * @return Zero on success, an error code otherwise.
+ */
+krb5_error_code
+hdb_remove_keys(krb5_context context,
+ hdb_entry *e,
+ krb5_kvno kvno,
+ hdb_keyset *ks)
+{
+ HDB_Ext_KeySet *hist_keys;
+ HDB_extension *extp;
+ size_t i;
+
+ if (kvno == 0 || e->kvno == kvno) {
+ if (ks) {
+ KerberosTime t;
+
+ (void) hdb_entry_get_pw_change_time(e, &t);
+ if (t) {
+ if ((ks->set_time = malloc(sizeof(*ks->set_time))) == NULL)
+ return krb5_enomem(context);
+ *ks->set_time = t;
+ }
+ ks->kvno = e->kvno;
+ ks->keys = e->keys;
+ e->keys.len = 0;
+ e->keys.val = NULL;
+ e->kvno = 0;
+ } else {
+ free_Keys(&e->keys);
+ }
+ return 0;
+ }
+
+ if (ks) {
+ ks->kvno = 0;
+ ks->keys.len = 0;
+ ks->keys.val = 0;
+ ks->set_time = 0;
+ }
+
+ extp = hdb_find_extension(e, choice_HDB_extension_data_hist_keys);
+ if (extp == NULL)
+ return 0;
+
+ hist_keys = &extp->data.u.hist_keys;
+ for (i = 0; i < hist_keys->len; i++) {
+ if (hist_keys->val[i].kvno != kvno)
+ continue;
+ if (ks)
+ return dequeue_HDB_Ext_KeySet(hist_keys, i, ks);
+ return remove_HDB_Ext_KeySet(hist_keys, i);
+ }
+ return HDB_ERR_NOENTRY;
+}
+
+/**
+ * Removes from `e' and outputs all the base keys for virtual principal and/or
+ * key derivation.
+ *
+ * @param context Context
+ * @param e The HDB entry
+ * @param ks A pointer to a variable of type HDB_Ext_KeySet
+ * @param ckr A pointer to stable (copied) HDB_Ext_KeyRotation
+ *
+ * @return Zero on success, an error code otherwise.
+ */
+krb5_error_code
+_hdb_remove_base_keys(krb5_context context,
+ hdb_entry *e,
+ HDB_Ext_KeySet *base_keys,
+ const HDB_Ext_KeyRotation *ckr)
+{
+ krb5_error_code ret = 0;
+ size_t i, k;
+
+ base_keys->len = 0;
+ if ((base_keys->val = calloc(ckr->len, sizeof(base_keys->val[0]))) == NULL)
+ ret = krb5_enomem(context);
+
+ for (k = i = 0; ret == 0 && i < ckr->len; i++) {
+ const KeyRotation *krp = &ckr->val[i];
+
+ /*
+ * WARNING: O(N * M) where M is number of keysets and N is the number
+ * of base keysets.
+ *
+ * In practice N will never be > 3 because the ASN.1 module imposes
+ * that as a constraint, and M will generally be the same as N, so this
+ * will be O(1) after all.
+ */
+ ret = hdb_remove_keys(context, e, krp->base_key_kvno,
+ &base_keys->val[k]);
+ if (ret == 0)
+ k++;
+ else if (ret == HDB_ERR_NOENTRY)
+ ret = 0;
+ }
+ if (ret == 0)
+ base_keys->len = k;
+ else
+ free_HDB_Ext_KeySet(base_keys);
+ return 0;
+}
+
+/**
+ * Removes from `e' and outputs all the base keys for virtual principal and/or
+ * key derivation.
+ *
+ * @param context Context
+ * @param e The HDB entry
+ * @param is_current_keyset Whether to make the keys the current keys for `e'
+ * @param ks A pointer to an hdb_keyset containing the keys to set
+ *
+ * @return Zero on success, an error code otherwise.
+ */
+krb5_error_code
+hdb_install_keyset(krb5_context context,
+ hdb_entry *e,
+ int is_current_keyset,
+ const hdb_keyset *ks)
+{
+ krb5_error_code ret = 0;
+
+ if (is_current_keyset) {
+ if (e->keys.len &&
+ (ret = hdb_add_current_keys_to_history(context, e)))
+ return ret;
+ free_Keys(&e->keys);
+ e->kvno = ks->kvno;
+ if (ret == 0)
+ ret = copy_Keys(&ks->keys, &e->keys);
+ if (ret == 0 && ks->set_time)
+ ret = hdb_entry_set_pw_change_time(context, e, *ks->set_time);
+ return ret;
+ }
+ return hdb_add_history_keyset(context, e, ks);
+}
+
+
+krb5_error_code
+hdb_next_enctype2key(krb5_context context,
+ const hdb_entry *e,
+ const Keys *keyset,
+ krb5_enctype enctype,
+ Key **key)
+{
+ const Keys *keys = keyset ? keyset : &e->keys;
+ Key *k;
+
+ for (k = *key ? (*key) + 1 : keys->val; k < keys->val + keys->len; k++) {
+ if(k->key.keytype == enctype){
+ *key = k;
+ return 0;
+ }
+ }
+ krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+ "No next enctype %d for hdb-entry",
+ (int)enctype);
+ return KRB5_PROG_ETYPE_NOSUPP; /* XXX */
+}
+
+krb5_error_code
+hdb_enctype2key(krb5_context context,
+ hdb_entry *e,
+ const Keys *keyset,
+ krb5_enctype enctype,
+ Key **key)
+{
+ *key = NULL;
+ return hdb_next_enctype2key(context, e, keyset, enctype, key);
+}
+
+void
+hdb_free_key(Key *key)
+{
+ memset_s(key->key.keyvalue.data,
+ key->key.keyvalue.length,
+ 0,
+ key->key.keyvalue.length);
+ free_Key(key);
+ free(key);
+}
+
+
+krb5_error_code
+hdb_lock(int fd, int operation)
+{
+ int i, code = 0;
+
+ for(i = 0; i < 3; i++){
+ code = flock(fd, (operation == HDB_RLOCK ? LOCK_SH : LOCK_EX) | LOCK_NB);
+ if(code == 0 || errno != EWOULDBLOCK)
+ break;
+ sleep(1);
+ }
+ if(code == 0)
+ return 0;
+ if(errno == EWOULDBLOCK)
+ return HDB_ERR_DB_INUSE;
+ return HDB_ERR_CANT_LOCK_DB;
+}
+
+krb5_error_code
+hdb_unlock(int fd)
+{
+ int code;
+ code = flock(fd, LOCK_UN);
+ if(code)
+ return 4711 /* XXX */;
+ return 0;
+}
+
+void
+hdb_free_entry(krb5_context context, HDB *db, hdb_entry *ent)
+{
+ Key *k;
+ size_t i;
+
+ if (db && db->hdb_free_entry_context)
+ db->hdb_free_entry_context(context, db, ent);
+
+ for(i = 0; i < ent->keys.len; i++) {
+ k = &ent->keys.val[i];
+
+ memset_s(k->key.keyvalue.data,
+ k->key.keyvalue.length,
+ 0,
+ k->key.keyvalue.length);
+ }
+ free_HDB_entry(ent);
+}
+
+krb5_error_code
+hdb_foreach(krb5_context context,
+ HDB *db,
+ unsigned flags,
+ hdb_foreach_func_t func,
+ void *data)
+{
+ krb5_error_code ret;
+ hdb_entry entry;
+ ret = db->hdb_firstkey(context, db, flags, &entry);
+ if (ret == 0)
+ krb5_clear_error_message(context);
+ while(ret == 0){
+ ret = (*func)(context, db, &entry, data);
+ hdb_free_entry(context, db, &entry);
+ if(ret == 0)
+ ret = db->hdb_nextkey(context, db, flags, &entry);
+ }
+ if(ret == HDB_ERR_NOENTRY)
+ ret = 0;
+ return ret;
+}
+
+krb5_error_code
+hdb_check_db_format(krb5_context context, HDB *db)
+{
+ krb5_data tag;
+ krb5_data version;
+ krb5_error_code ret, ret2;
+ unsigned ver;
+ int foo;
+
+ ret = db->hdb_lock(context, db, HDB_RLOCK);
+ if (ret)
+ return ret;
+
+ tag.data = (void *)(intptr_t)HDB_DB_FORMAT_ENTRY;
+ tag.length = strlen(tag.data);
+ ret = (*db->hdb__get)(context, db, tag, &version);
+ ret2 = db->hdb_unlock(context, db);
+ if(ret)
+ return ret;
+ if (ret2)
+ return ret2;
+ foo = sscanf(version.data, "%u", &ver);
+ krb5_data_free (&version);
+ if (foo != 1)
+ return HDB_ERR_BADVERSION;
+ if(ver != HDB_DB_FORMAT)
+ return HDB_ERR_BADVERSION;
+ return 0;
+}
+
+krb5_error_code
+hdb_init_db(krb5_context context, HDB *db)
+{
+ krb5_error_code ret, ret2;
+ krb5_data tag;
+ krb5_data version;
+ char ver[32];
+
+ ret = hdb_check_db_format(context, db);
+ if(ret != HDB_ERR_NOENTRY)
+ return ret;
+
+ ret = db->hdb_lock(context, db, HDB_WLOCK);
+ if (ret)
+ return ret;
+
+ tag.data = (void *)(intptr_t)HDB_DB_FORMAT_ENTRY;
+ tag.length = strlen(tag.data);
+ snprintf(ver, sizeof(ver), "%u", HDB_DB_FORMAT);
+ version.data = ver;
+ version.length = strlen(version.data) + 1; /* zero terminated */
+ ret = (*db->hdb__put)(context, db, 0, tag, version);
+ ret2 = db->hdb_unlock(context, db);
+ if (ret) {
+ if (ret2)
+ krb5_clear_error_message(context);
+ return ret;
+ }
+ return ret2;
+}
+
+/*
+ * `default_dbmethod' is the last resort default.
+ *
+ * In hdb_create() we may try all the `methods[]' until one succeeds or all
+ * fail.
+ */
+#if defined(HAVE_LMDB)
+static struct hdb_method default_dbmethod =
+ { HDB_INTERFACE_VERSION, NULL, NULL, 1, 1, "", hdb_mdb_create };
+#elif defined(HAVE_DB3)
+static struct hdb_method default_dbmethod =
+ { HDB_INTERFACE_VERSION, NULL, NULL, 1, 1, "", hdb_db3_create };
+#elif defined(HAVE_DB1)
+static struct hdb_method default_dbmethod =
+ { HDB_INTERFACE_VERSION, NULL, NULL, 1, 1, "", hdb_db1_create };
+#elif defined(HAVE_NDBM)
+static struct hdb_method default_dbmethod =
+ { HDB_INTERFACE_VERSION, NULL, NULL, 0, 1, "", hdb_ndbm_create };
+#else
+static struct hdb_method default_dbmethod =
+ { 0, NULL, NULL, 0, 0, NULL, NULL};
+#endif
+
+static int
+is_pathish(const char *s)
+{
+ if (s[0] == '/' ||
+ strncmp(s, "./", sizeof("./") - 1) == 0 ||
+ strncmp(s, "../", sizeof("../") - 1) == 0)
+ return 1;
+#ifdef WIN32
+ if (s[0] == '\\' || (isalpha(s[0]) && s[0] == ':') ||
+ strncmp(s, ".\\", sizeof(".\\") - 1) == 0 ||
+ strncmp(s, "\\\\", sizeof("\\\\") - 1) == 0)
+ return 1;
+#endif
+ return 0;
+}
+
+static const struct hdb_method *
+has_method_prefix(const char *filename)
+{
+ const struct hdb_method *h;
+
+ for (h = methods; h->prefix != NULL; ++h)
+ if (strncmp(filename, h->prefix, strlen(h->prefix)) == 0)
+ return h;
+ return NULL;
+}
+
+/*
+ * find the relevant method for `filename', returning a pointer to the
+ * rest in `rest'.
+ * return NULL if there's no such method.
+ */
+
+static const struct hdb_method *
+find_method(const char *filename, const char **rest)
+{
+ const struct hdb_method *h = has_method_prefix(filename);
+
+ *rest = h ? filename + strlen(h->prefix) : filename;
+ return h;
+}
+
+struct cb_s {
+ const char *residual;
+ const char *filename;
+ const struct hdb_method *h;
+};
+
+static krb5_error_code KRB5_LIB_CALL
+callback(krb5_context context, const void *plug, void *plugctx, void *userctx)
+{
+ const struct hdb_method *h = (const struct hdb_method *)plug;
+ struct cb_s *cb_ctx = (struct cb_s *)userctx;
+
+ if (strncmp(cb_ctx->filename, h->prefix, strlen(h->prefix)) == 0) {
+ cb_ctx->residual = cb_ctx->filename + strlen(h->prefix) + 1;
+ cb_ctx->h = h;
+ return 0;
+ }
+ return KRB5_PLUGIN_NO_HANDLE;
+}
+
+static char *
+make_sym(const char *prefix)
+{
+ char *s, *sym;
+
+ errno = 0;
+ if (prefix == NULL || prefix[0] == '\0')
+ return NULL;
+ if ((s = strdup(prefix)) == NULL)
+ return NULL;
+ if (strchr(s, ':') != NULL)
+ *strchr(s, ':') = '\0';
+ if (asprintf(&sym, "hdb_%s_interface", s) == -1)
+ sym = NULL;
+ free(s);
+ return sym;
+}
+
+static const char *hdb_plugin_deps[] = { "hdb", "krb5", NULL };
+
+krb5_error_code
+hdb_list_builtin(krb5_context context, char **list)
+{
+ const struct hdb_method *h;
+ size_t len = 0;
+ char *buf = NULL;
+
+ for (h = methods; h->prefix != NULL; ++h) {
+ if (h->prefix[0] == '\0')
+ continue;
+ len += strlen(h->prefix) + 2;
+ }
+
+ len += 1;
+ buf = malloc(len);
+ if (buf == NULL) {
+ return krb5_enomem(context);
+ }
+ buf[0] = '\0';
+
+ for (h = methods; h->prefix != NULL; ++h) {
+ if (h->create == NULL) {
+ struct cb_s cb_ctx;
+ char *f;
+ struct heim_plugin_data hdb_plugin_data;
+
+ hdb_plugin_data.module = "krb5";
+ hdb_plugin_data.min_version = HDB_INTERFACE_VERSION;
+ hdb_plugin_data.deps = hdb_plugin_deps;
+ hdb_plugin_data.get_instance = hdb_get_instance;
+
+ /* Try loading the plugin */
+ if (asprintf(&f, "%sfoo", h->prefix) == -1)
+ f = NULL;
+ if ((hdb_plugin_data.name = make_sym(h->prefix)) == NULL) {
+ free(buf);
+ free(f);
+ return krb5_enomem(context);
+ }
+ cb_ctx.filename = f;
+ cb_ctx.residual = NULL;
+ cb_ctx.h = NULL;
+ (void)_krb5_plugin_run_f(context, &hdb_plugin_data, 0,
+ &cb_ctx, callback);
+ free(f);
+ free(rk_UNCONST(hdb_plugin_data.name));
+ if (cb_ctx.h == NULL || cb_ctx.h->create == NULL)
+ continue;
+ }
+ if (h != methods)
+ strlcat(buf, ", ", len);
+ strlcat(buf, h->prefix, len);
+ }
+ *list = buf;
+ return 0;
+}
+
+krb5_error_code
+_hdb_keytab2hdb_entry(krb5_context context,
+ const krb5_keytab_entry *ktentry,
+ hdb_entry *entry)
+{
+ entry->kvno = ktentry->vno;
+ entry->created_by.time = ktentry->timestamp;
+
+ entry->keys.val = calloc(1, sizeof(entry->keys.val[0]));
+ if (entry->keys.val == NULL)
+ return ENOMEM;
+ entry->keys.len = 1;
+
+ entry->keys.val[0].mkvno = NULL;
+ entry->keys.val[0].salt = NULL;
+
+ return krb5_copy_keyblock_contents(context,
+ &ktentry->keyblock,
+ &entry->keys.val[0].key);
+}
+
+static krb5_error_code
+load_config(krb5_context context, HDB *db)
+{
+ db->enable_virtual_hostbased_princs =
+ krb5_config_get_bool_default(context, NULL, FALSE, "hdb",
+ "enable_virtual_hostbased_princs",
+ NULL);
+ db->virtual_hostbased_princ_ndots =
+ krb5_config_get_int_default(context, NULL, 1, "hdb",
+ "virtual_hostbased_princ_mindots",
+ NULL);
+ db->virtual_hostbased_princ_maxdots =
+ krb5_config_get_int_default(context, NULL, 0, "hdb",
+ "virtual_hostbased_princ_maxdots",
+ NULL);
+ db->new_service_key_delay =
+ krb5_config_get_time_default(context, NULL, 0, "hdb",
+ "new_service_key_delay", NULL);
+ /*
+ * XXX Needs freeing in the HDB backends because we don't have a
+ * first-class hdb_close() :(
+ */
+ db->virtual_hostbased_princ_svcs =
+ krb5_config_get_strings(context, NULL, "hdb",
+ "virtual_hostbased_princ_svcs", NULL);
+ /* Check for ENOMEM */
+ if (db->virtual_hostbased_princ_svcs == NULL
+ && krb5_config_get_string(context, NULL, "hdb",
+ "virtual_hostbased_princ_svcs", NULL)) {
+ return krb5_enomem(context);
+ }
+ return 0;
+}
+
+/**
+ * Create a handle for a Kerberos database
+ *
+ * Create a handle for a Kerberos database backend specified by a
+ * filename. Doesn't actually create or even open an HDB file(s);
+ * you have to call the hdb_open() open method of the resulting HDB
+ * to open the database, and you have to use O_CREAT to create it.
+ *
+ * If `filename' does not have a backend type prefix, all file-based
+ * backends will be tried until one succeeds or all fail, and if the
+ * HDB exists for some backend, that will be used. A build-time
+ * default backend type will be used if the `filename' does not exist.
+ *
+ * Note that the actual filename may have a suffix added, such as
+ * ".db". Also, for backends such as "ldap:" and "ldapi:" the
+ * `filename' is more like a URI.
+ *
+ * @param [in] context Context
+ * @param [out] db HDB handle output
+ * @param [in] filename The name of the HDB
+ *
+ * @return Zero on success else a krb5 error code.
+ */
+
+krb5_error_code
+hdb_create(krb5_context context, HDB **db, const char *filename)
+{
+ krb5_error_code ret = ENOTSUP;
+ struct cb_s cb_ctx;
+
+ *db = NULL;
+ if (filename == NULL)
+ filename = hdb_default_db(context);
+
+ cb_ctx.h = find_method(filename, &cb_ctx.residual);
+ cb_ctx.filename = filename;
+
+ if (cb_ctx.h == NULL || cb_ctx.h->create == NULL) {
+ struct heim_plugin_data hdb_plugin_data;
+
+ /*
+ * `filename' does not start with a known HDB backend prefix.
+ *
+ * Try plugins.
+ */
+ hdb_plugin_data.module = "krb5";
+ hdb_plugin_data.min_version = HDB_INTERFACE_VERSION;
+ hdb_plugin_data.deps = hdb_plugin_deps;
+ hdb_plugin_data.get_instance = hdb_get_instance;
+
+ if ((hdb_plugin_data.name = make_sym(filename)) == NULL)
+ return krb5_enomem(context);
+
+ (void)_krb5_plugin_run_f(context, &hdb_plugin_data, 0 /* flags */,
+ &cb_ctx, callback);
+
+ free(rk_UNCONST(hdb_plugin_data.name));
+ }
+
+ if (cb_ctx.h == NULL || cb_ctx.h->create == NULL) {
+ int pathish = is_pathish(filename);
+ /*
+ * `filename' does not start with a known HDB backend prefix and it
+ * wasn't handled by any plugin.
+ *
+ * If it's "filename-ish", try all builtin HDB backends that are
+ * local-file-ish, but use hdb_open() to see if the HDB exists and stop
+ * when a backend is found for which the HDB exists.
+ */
+ if (!pathish) {
+ krb5_set_error_message(context, ret = ENOTSUP,
+ "No database support for %s",
+ cb_ctx.filename);
+ return ret;
+ }
+ for (cb_ctx.h = methods; cb_ctx.h->prefix != NULL; cb_ctx.h++) {
+ if (cb_ctx.h->is_file_based)
+ continue;
+ if (!cb_ctx.h->can_taste)
+ continue;
+ /* Taste the file */
+ ret = (*cb_ctx.h->create)(context, db, filename);
+ if (ret == 0)
+ ret = (*db)->hdb_open(context, *db, O_RDONLY, 0);
+ if (ret == 0) {
+ (void) (*db)->hdb_close(context, *db);
+ break;
+ }
+ if (*db)
+ (*db)->hdb_destroy(context, *db);
+ *db = NULL;
+ }
+ if (cb_ctx.h->prefix == NULL)
+ cb_ctx.h = NULL;
+ }
+#ifdef HDB_DEFAULT_DB_TYPE
+ if (cb_ctx.h == NULL) {
+ /*
+ * If still we've not picked a backend, use a build configuration time
+ * default.
+ */
+ for (cb_ctx.h = methods; cb_ctx.h->prefix != NULL; cb_ctx.h++)
+ if (strcmp(cb_ctx.h->prefix, HDB_DEFAULT_DB_TYPE) == 0)
+ break;
+ if (cb_ctx.h->prefix == NULL)
+ cb_ctx.h = NULL;
+ }
+#endif
+ if (cb_ctx.h == NULL)
+ /* Last resort default */
+ cb_ctx.h = &default_dbmethod;
+ if (cb_ctx.h->prefix == NULL) {
+ krb5_set_error_message(context, ENOTSUP,
+ "Could not determine default DB backend for %s",
+ filename);
+ return ENOTSUP;
+ }
+ if (!*db) {
+ ret = (*cb_ctx.h->create)(context, db, cb_ctx.residual);
+ if (ret == 0)
+ (*db)->hdb_method_name = cb_ctx.h->prefix;
+ }
+ if (ret == 0 && *db)
+ ret = load_config(context, *db);
+ if (ret && *db) {
+ (*db)->hdb_destroy(context, *db);
+ *db = NULL;
+ }
+ return ret;
+}
+
+uintptr_t KRB5_CALLCONV
+hdb_get_instance(const char *libname)
+{
+ static const char *instance = "libhdb";
+
+ if (strcmp(libname, "hdb") == 0)
+ return (uintptr_t)instance;
+ else if (strcmp(libname, "krb5") == 0)
+ return krb5_get_instance(libname);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hdb/hdb.h b/third_party/heimdal/lib/hdb/hdb.h
new file mode 100644
index 0000000..2a3d1c4
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/hdb.h
@@ -0,0 +1,337 @@
+/*
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __HDB_H__
+#define __HDB_H__
+
+#include <stdio.h>
+
+#include <krb5.h>
+
+#include <hdb_err.h>
+
+#include <heimbase-svc.h>
+#include <heim_asn1.h>
+#include <hdb_asn1.h>
+
+#define HDB_DB_FORMAT hdb_db_format
+
+typedef HDB_keyset hdb_keyset;
+typedef HDB_entry hdb_entry;
+typedef HDB_entry_alias hdb_entry_alias;
+
+struct hdb_dbinfo;
+
+enum hdb_lockop{ HDB_RLOCK, HDB_WLOCK };
+
+/* flags for various functions */
+#define HDB_F_DECRYPT 0x00001 /* decrypt keys */
+#define HDB_F_REPLACE 0x00002 /* replace entry */
+#define HDB_F_GET_CLIENT 0x00004 /* fetch client */
+#define HDB_F_GET_SERVER 0x00008 /* fetch server */
+#define HDB_F_GET_KRBTGT 0x00010 /* fetch krbtgt */
+#define HDB_F_GET_ANY ( HDB_F_GET_CLIENT | \
+ HDB_F_GET_SERVER | \
+ HDB_F_GET_KRBTGT ) /* fetch any of client,server,krbtgt */
+#define HDB_F_CANON 0x00020 /* want canonicalition */
+#define HDB_F_ADMIN_DATA 0x00040 /* want data that kdc don't use */
+#define HDB_F_KVNO_SPECIFIED 0x00080 /* we want a particular KVNO */
+#define HDB_F_LIVE_CLNT_KVNOS 0x00200 /* we want all live keys for pre-auth */
+#define HDB_F_LIVE_SVC_KVNOS 0x00400 /* we want all live keys for tix */
+#define HDB_F_ALL_KVNOS 0x00800 /* we want all the keys, live or not */
+#define HDB_F_FOR_AS_REQ 0x01000 /* fetch is for a AS REQ */
+#define HDB_F_FOR_TGS_REQ 0x02000 /* fetch is for a TGS REQ */
+#define HDB_F_PRECHECK 0x04000 /* check that the operation would succeed */
+#define HDB_F_DELAY_NEW_KEYS 0x08000 /* apply [hdb] new_service_key_delay */
+#define HDB_F_SYNTHETIC_OK 0x10000 /* synthetic principal for PKINIT or GSS preauth OK */
+#define HDB_F_GET_FAST_COOKIE 0x20000 /* fetch the FX-COOKIE key (not a normal principal) */
+
+/* hdb_capability_flags */
+#define HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL 1
+#define HDB_CAP_F_HANDLE_PASSWORDS 2
+#define HDB_CAP_F_PASSWORD_UPDATE_KEYS 4
+#define HDB_CAP_F_SHARED_DIRECTORY 8
+
+#define heim_pcontext krb5_context
+#define heim_pconfig void *
+
+typedef struct hdb_request_desc {
+ HEIM_SVC_REQUEST_DESC_COMMON_ELEMENTS;
+} *hdb_request_t;
+
+#undef heim_pcontext
+#undef heim_pconfig
+
+/* key usage for master key */
+#define HDB_KU_MKEY 0x484442
+
+/*
+ * Second component of WELLKNOWN namespace principals, the third component is
+ * the common DNS suffix of the implied virtual hosts.
+ */
+#define HDB_WK_NAMESPACE "HOSTBASED-NAMESPACE"
+
+typedef struct hdb_master_key_data *hdb_master_key;
+
+/**
+ * HDB backend function pointer structure
+ *
+ * The HDB structure is what the KDC and kadmind framework uses to
+ * query the backend database when talking about principals.
+ */
+
+typedef struct HDB {
+ void *hdb_db;
+ void *hdb_dbc; /** don't use, only for DB3 */
+ const char *hdb_method_name;
+ char *hdb_name;
+ int hdb_master_key_set;
+ hdb_master_key hdb_master_key;
+ int hdb_openp;
+ int hdb_capability_flags;
+ int lock_count;
+ int lock_type;
+ /*
+ * These fields cache config values.
+ *
+ * XXX Move these into a structure that we point to so that we
+ * don't need to break the ABI every time we add a field.
+ */
+ int enable_virtual_hostbased_princs;
+ size_t virtual_hostbased_princ_ndots; /* Min. # of .s in hostname */
+ size_t virtual_hostbased_princ_maxdots; /* Max. # of .s in namespace */
+ char **virtual_hostbased_princ_svcs; /* Which svcs are not wildcarded */
+ time_t new_service_key_delay; /* Delay for new keys */
+ /**
+ * Open (or create) the a Kerberos database.
+ *
+ * Open (or create) the a Kerberos database that was resolved with
+ * hdb_create(). The third and fourth flag to the function are the
+ * same as open(), thus passing O_CREAT will create the data base
+ * if it doesn't exists.
+ *
+ * Then done the caller should call hdb_close(), and to release
+ * all resources hdb_destroy().
+ */
+ krb5_error_code (*hdb_open)(krb5_context, struct HDB*, int, mode_t);
+ /**
+ * Close the database for transaction
+ *
+ * Closes the database for further transactions, wont release any
+ * permanant resources. the database can be ->hdb_open-ed again.
+ */
+ krb5_error_code (*hdb_close)(krb5_context, struct HDB*);
+ /**
+ * Free backend-specific entry context.
+ */
+ void (*hdb_free_entry_context)(krb5_context, struct HDB*, hdb_entry*);
+ /**
+ * Fetch an entry from the backend
+ *
+ * Fetch an entry from the backend, flags are what type of entry
+ * should be fetch: client, server, krbtgt.
+ * knvo (if specified and flags HDB_F_KVNO_SPECIFIED set) is the kvno to get
+ */
+ krb5_error_code (*hdb_fetch_kvno)(krb5_context, struct HDB*,
+ krb5_const_principal, unsigned, krb5_kvno,
+ hdb_entry*);
+ /**
+ * Store an entry to database
+ */
+ krb5_error_code (*hdb_store)(krb5_context, struct HDB*,
+ unsigned, hdb_entry*);
+ /**
+ * Remove an entry from the database.
+ */
+ krb5_error_code (*hdb_remove)(krb5_context, struct HDB*,
+ unsigned, krb5_const_principal);
+ /**
+ * As part of iteration, fetch one entry
+ */
+ krb5_error_code (*hdb_firstkey)(krb5_context, struct HDB*,
+ unsigned, hdb_entry*);
+ /**
+ * As part of iteration, fetch next entry
+ */
+ krb5_error_code (*hdb_nextkey)(krb5_context, struct HDB*,
+ unsigned, hdb_entry*);
+ /**
+ * Lock database
+ *
+ * A lock can only be held by one consumers. Transaction can still
+ * happen on the database while the lock is held, so the entry is
+ * only useful for syncroning creation of the database and renaming of the database.
+ */
+ krb5_error_code (*hdb_lock)(krb5_context, struct HDB*, int);
+ /**
+ * Unlock database
+ */
+ krb5_error_code (*hdb_unlock)(krb5_context, struct HDB*);
+ /**
+ * Rename the data base.
+ *
+ * Assume that the database is not hdb_open'ed and not locked.
+ */
+ krb5_error_code (*hdb_rename)(krb5_context, struct HDB*, const char*);
+ /**
+ * Get an hdb_entry from a classical DB backend
+ *
+ * This function takes a principal key (krb5_data) and returns all
+ * data related to principal in the return krb5_data. The returned
+ * encoded entry is of type hdb_entry or hdb_entry_alias.
+ */
+ krb5_error_code (*hdb__get)(krb5_context, struct HDB*,
+ krb5_data, krb5_data*);
+ /**
+ * Store an hdb_entry from a classical DB backend
+ *
+ * This function takes a principal key (krb5_data) and encoded
+ * hdb_entry or hdb_entry_alias as the data to store.
+ *
+ * For a file-based DB, this must synchronize to disk when done.
+ * This is sub-optimal for kadm5_s_rename_principal(), and for
+ * kadm5_s_modify_principal() when using principal aliases; to
+ * improve this so that only one fsync() need be done
+ * per-transaction will require HDB API extensions.
+ */
+ krb5_error_code (*hdb__put)(krb5_context, struct HDB*, int,
+ krb5_data, krb5_data);
+ /**
+ * Delete and hdb_entry from a classical DB backend
+ *
+ * This function takes a principal key (krb5_data) naming the record
+ * to delete.
+ *
+ * Same discussion as in @ref HDB::hdb__put
+ */
+ krb5_error_code (*hdb__del)(krb5_context, struct HDB*, krb5_data);
+ /**
+ * Destroy the handle to the database.
+ *
+ * Destroy the handle to the database, deallocate all memory and
+ * related resources. Does not remove any permanent data. Its the
+ * logical reverse of hdb_create() function that is the entry
+ * point for the module.
+ */
+ krb5_error_code (*hdb_destroy)(krb5_context, struct HDB*);
+ /**
+ * Get the list of realms this backend handles.
+ * This call is optional to support. The returned realms are used
+ * for announcing the realms over bonjour. Free returned array
+ * with krb5_free_host_realm().
+ */
+ krb5_error_code (*hdb_get_realms)(krb5_context, struct HDB *, krb5_realm **);
+ /**
+ * Change password.
+ *
+ * Will update keys for the entry when given password. The new
+ * keys must be written into the entry and will then later be
+ * ->hdb_store() into the database. The backend will still perform
+ * all other operations, increasing the kvno, and update
+ * modification timestamp.
+ *
+ * The backend needs to call _kadm5_set_keys() and perform password
+ * quality checks.
+ */
+ krb5_error_code (*hdb_password)(krb5_context, struct HDB*, hdb_entry*, const char *, int);
+
+ /**
+ * Authentication auditing. Note that this function is called by
+ * both the AS and TGS, but currently only the AS sets the auth
+ * event type. This may change in a future version.
+ *
+ * Event details are available by querying the request using
+ * heim_audit_getkv(HDB_REQUEST_KV_...).
+ *
+ * In case the entry is locked out, the backend should set the
+ * hdb_entry.flags.locked-out flag.
+ */
+ krb5_error_code (*hdb_audit)(krb5_context, struct HDB *, hdb_entry *, hdb_request_t);
+
+ /**
+ * Check if delegation is allowed.
+ */
+ krb5_error_code (*hdb_check_constrained_delegation)(krb5_context, struct HDB *, hdb_entry *, krb5_const_principal);
+
+ /**
+ * Check if this name is an alias for the supplied client for PKINIT userPrinicpalName logins
+ */
+ krb5_error_code (*hdb_check_pkinit_ms_upn_match)(krb5_context, struct HDB *, hdb_entry *, krb5_const_principal);
+
+ /**
+ * Check if s4u2self is allowed from this client to this server or the SPN is a valid SPN of this client (for user2user)
+ */
+ krb5_error_code (*hdb_check_client_matches_target_service)(krb5_context, struct HDB *, hdb_entry *, hdb_entry *);
+
+ /**
+ * Enable/disable synchronous updates
+ *
+ * Calling this with 0 disables sync. Calling it with non-zero enables
+ * sync and does an fsync().
+ */
+ krb5_error_code (*hdb_set_sync)(krb5_context, struct HDB *, int);
+}HDB;
+
+#define HDB_INTERFACE_VERSION 11
+
+struct hdb_method {
+ HEIM_PLUGIN_FTABLE_COMMON_ELEMENTS(krb5_context);
+ unsigned int is_file_based:1;
+ unsigned int can_taste:1;
+ const char *prefix;
+ krb5_error_code (*create)(krb5_context, HDB **, const char *filename);
+};
+
+/* dump entry format, for hdb_print_entry() */
+typedef enum hdb_dump_format {
+ HDB_DUMP_HEIMDAL = 0,
+ HDB_DUMP_MIT = 1,
+} hdb_dump_format_t;
+
+struct hdb_print_entry_arg {
+ FILE *out;
+ hdb_dump_format_t fmt;
+};
+
+typedef krb5_error_code (*hdb_foreach_func_t)(krb5_context, HDB*,
+ hdb_entry*, void*);
+extern krb5_kt_ops hdb_kt_ops;
+extern krb5_kt_ops hdb_get_kt_ops;
+
+extern const int hdb_interface_version;
+
+#include <hdb-protos.h>
+
+#endif /* __HDB_H__ */
diff --git a/third_party/heimdal/lib/hdb/hdb.opt b/third_party/heimdal/lib/hdb/hdb.opt
new file mode 100644
index 0000000..626f8c7
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/hdb.opt
@@ -0,0 +1,5 @@
+--sequence=HDB-extensions
+--sequence=HDB-Ext-KeyRotation
+--sequence=HDB-Ext-KeySet
+--sequence=Keys
+--decorate=HDB_entry:void:context?:::
diff --git a/third_party/heimdal/lib/hdb/hdb.schema b/third_party/heimdal/lib/hdb/hdb.schema
new file mode 100644
index 0000000..f9fb080
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/hdb.schema
@@ -0,0 +1,144 @@
+# Definitions for a Kerberos V KDC schema
+#
+# $Id$
+#
+# This version is compatible with OpenLDAP 1.8
+#
+# OID Base is iso(1) org(3) dod(6) internet(1) private(4) enterprise(1) padl(5322) kdcSchema(10)
+#
+# Syntaxes are under 1.3.6.1.4.1.5322.10.0
+# Attributes types are under 1.3.6.1.4.1.5322.10.1
+# Object classes are under 1.3.6.1.4.1.5322.10.2
+
+# Syntax definitions
+
+#krb5KDCFlagsSyntax SYNTAX ::= {
+# WITH SYNTAX INTEGER
+#-- initial(0), -- require as-req
+#-- forwardable(1), -- may issue forwardable
+#-- proxiable(2), -- may issue proxiable
+#-- renewable(3), -- may issue renewable
+#-- postdate(4), -- may issue postdatable
+#-- server(5), -- may be server
+#-- client(6), -- may be client
+#-- invalid(7), -- entry is invalid
+#-- require-preauth(8), -- must use preauth
+#-- change-pw(9), -- change password service
+#-- require-hwauth(10), -- must use hwauth
+#-- ok-as-delegate(11), -- as in TicketFlags
+#-- user-to-user(12), -- may use user-to-user auth
+#-- immutable(13) -- may not be deleted
+# ID { 1.3.6.1.4.1.5322.10.0.1 }
+#}
+
+#krb5PrincipalNameSyntax SYNTAX ::= {
+# WITH SYNTAX OCTET STRING
+#-- String representations of distinguished names as per RFC1510
+# ID { 1.3.6.1.4.1.5322.10.0.2 }
+#}
+
+# Attribute type definitions
+
+attributetype ( 1.3.6.1.4.1.5322.10.1.1
+ NAME 'krb5PrincipalName'
+ DESC 'The unparsed Kerberos principal name'
+ EQUALITY caseExactIA5Match
+ SINGLE-VALUE
+ SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
+
+attributetype ( 1.3.6.1.4.1.5322.10.1.2
+ NAME 'krb5KeyVersionNumber'
+ EQUALITY integerMatch
+ SINGLE-VALUE
+ SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 )
+
+attributetype ( 1.3.6.1.4.1.5322.10.1.3
+ NAME 'krb5MaxLife'
+ EQUALITY integerMatch
+ SINGLE-VALUE
+ SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 )
+
+attributetype ( 1.3.6.1.4.1.5322.10.1.4
+ NAME 'krb5MaxRenew'
+ EQUALITY integerMatch
+ SINGLE-VALUE
+ SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 )
+
+attributetype ( 1.3.6.1.4.1.5322.10.1.5
+ NAME 'krb5KDCFlags'
+ EQUALITY integerMatch
+ SINGLE-VALUE
+ SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 )
+
+attributetype ( 1.3.6.1.4.1.5322.10.1.6
+ NAME 'krb5EncryptionType'
+ EQUALITY integerMatch
+ SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 )
+
+attributetype ( 1.3.6.1.4.1.5322.10.1.7
+ NAME 'krb5ValidStart'
+ EQUALITY generalizedTimeMatch
+ ORDERING generalizedTimeOrderingMatch
+ SYNTAX 1.3.6.1.4.1.1466.115.121.1.24
+ SINGLE-VALUE )
+
+attributetype ( 1.3.6.1.4.1.5322.10.1.8
+ NAME 'krb5ValidEnd'
+ EQUALITY generalizedTimeMatch
+ ORDERING generalizedTimeOrderingMatch
+ SYNTAX 1.3.6.1.4.1.1466.115.121.1.24
+ SINGLE-VALUE )
+
+attributetype ( 1.3.6.1.4.1.5322.10.1.9
+ NAME 'krb5PasswordEnd'
+ EQUALITY generalizedTimeMatch
+ ORDERING generalizedTimeOrderingMatch
+ SYNTAX 1.3.6.1.4.1.1466.115.121.1.24
+ SINGLE-VALUE )
+
+# this is temporary; keys will eventually
+# be child entries or compound attributes.
+attributetype ( 1.3.6.1.4.1.5322.10.1.10
+ NAME 'krb5Key'
+ DESC 'Encoded ASN1 Key as an octet string'
+ SYNTAX 1.3.6.1.4.1.1466.115.121.1.5 )
+
+attributetype ( 1.3.6.1.4.1.5322.10.1.11
+ NAME 'krb5PrincipalRealm'
+ DESC 'Distinguished name of krb5Realm entry'
+ SUP distinguishedName )
+
+attributetype ( 1.3.6.1.4.1.5322.10.1.12
+ NAME 'krb5RealmName'
+ EQUALITY octetStringMatch
+ SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{128} )
+
+attributetype ( 1.3.6.1.4.1.5322.10.1.13
+ NAME 'krb5ExtendedAttributes'
+ DESC 'Encoded ASN1 HDB Extension Attributes as an octet string'
+ SYNTAX 1.3.6.1.4.1.1466.115.121.1.5 )
+
+# Object class definitions
+
+objectclass ( 1.3.6.1.4.1.5322.10.2.1
+ NAME 'krb5Principal'
+ SUP top
+ AUXILIARY
+ MUST ( krb5PrincipalName )
+ MAY ( cn $ krb5PrincipalRealm ) )
+
+objectclass ( 1.3.6.1.4.1.5322.10.2.2
+ NAME 'krb5KDCEntry'
+ SUP krb5Principal
+ AUXILIARY
+ MUST ( krb5KeyVersionNumber )
+ MAY ( krb5ValidStart $ krb5ValidEnd $ krb5PasswordEnd $
+ krb5MaxLife $ krb5MaxRenew $ krb5KDCFlags $
+ krb5EncryptionType $ krb5Key $ krb5ExtendedAttributes ) )
+
+objectclass ( 1.3.6.1.4.1.5322.10.2.3
+ NAME 'krb5Realm'
+ SUP top
+ AUXILIARY
+ MUST ( krb5RealmName ) )
+
diff --git a/third_party/heimdal/lib/hdb/hdb_err.et b/third_party/heimdal/lib/hdb/hdb_err.et
new file mode 100644
index 0000000..6a79ffa
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/hdb_err.et
@@ -0,0 +1,33 @@
+#
+# Error messages for the hdb library
+#
+# This might look like a com_err file, but is not
+#
+id "$Id$"
+
+error_table hdb
+
+prefix HDB_ERR
+
+index 1
+#error_code INUSE, "Entry already exists in database"
+error_code UK_SERROR, "Database store error"
+error_code UK_RERROR, "Database read error"
+error_code NOENTRY, "No such entry in the database"
+error_code DB_INUSE, "Database is locked or in use--try again later"
+error_code DB_CHANGED, "Database was modified during read"
+error_code RECURSIVELOCK, "Attempt to lock database twice"
+error_code NOTLOCKED, "Attempt to unlock database when not locked"
+error_code BADLOCKMODE, "Invalid kdb lock mode"
+error_code CANT_LOCK_DB, "Insufficient access to lock database"
+error_code EXISTS, "Entry already exists in database"
+error_code BADVERSION, "Wrong database version"
+error_code NO_MKEY, "No correct master key"
+error_code MANDATORY_OPTION, "Entry contains unknown mandatory extension"
+error_code NO_WRITE_SUPPORT, "HDB backend doesn't contain write support"
+error_code NOT_FOUND_HERE, "The secret for this entry is not replicated to this database"
+error_code MISUSE, "Incorrect use of the API"
+error_code KVNO_NOT_FOUND, "Entry key version number not found"
+error_code WRONG_REALM, "The principal exists in another realm."
+
+end
diff --git a/third_party/heimdal/lib/hdb/hdb_locl.h b/third_party/heimdal/lib/hdb/hdb_locl.h
new file mode 100644
index 0000000..fd7b184
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/hdb_locl.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 1997-2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __HDB_LOCL_H__
+#define __HDB_LOCL_H__
+
+#include <config.h>
+
+#include <assert.h>
+#include <heimbase.h>
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <errno.h>
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef HAVE_SYS_FILE_H
+#include <sys/file.h>
+#endif
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif
+#include <roken.h>
+
+#include "crypto-headers.h"
+#include <krb5.h>
+#include <hdb.h>
+#include <hdb-private.h>
+
+#define HDB_DEFAULT_DB HDB_DB_DIR "/heimdal"
+#define HDB_DB_FORMAT_ENTRY "hdb/db-format"
+
+#endif /* __HDB_LOCL_H__ */
diff --git a/third_party/heimdal/lib/hdb/keys.c b/third_party/heimdal/lib/hdb/keys.c
new file mode 100644
index 0000000..457e5da
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/keys.c
@@ -0,0 +1,855 @@
+/*
+ * Copyright (c) 1997 - 2011 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include "hdb_locl.h"
+
+#include <pkinit_asn1.h>
+#include <base64.h>
+
+/*
+ * free all the memory used by (len, keys)
+ */
+
+void
+hdb_free_keys(krb5_context context, int len, Key *keys)
+{
+ size_t i;
+
+ for (i = 0; i < len; i++) {
+ free(keys[i].mkvno);
+ keys[i].mkvno = NULL;
+ if (keys[i].salt != NULL) {
+ free_Salt(keys[i].salt);
+ free(keys[i].salt);
+ keys[i].salt = NULL;
+ }
+ krb5_free_keyblock_contents(context, &keys[i].key);
+ }
+ free (keys);
+}
+
+/*
+ * for each entry in `default_keys' try to parse it as a sequence
+ * of etype:salttype:salt, syntax of this if something like:
+ * [(des|des3|etype):](pw-salt|afs3)[:string], if etype is omitted it
+ * means all etypes, and if string is omitted is means the default
+ * string (for that principal). Additional special values:
+ * v5 == pw-salt, and
+ * v4 == des:pw-salt:
+ * afs or afs3 == des:afs3-salt
+ */
+
+static const krb5_enctype des_etypes[] = {
+ KRB5_ENCTYPE_DES_CBC_MD5,
+ KRB5_ENCTYPE_DES_CBC_MD4,
+ KRB5_ENCTYPE_DES_CBC_CRC
+};
+
+static const krb5_enctype all_etypes[] = {
+ KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96,
+ KRB5_ENCTYPE_DES3_CBC_SHA1,
+ KRB5_ENCTYPE_ARCFOUR_HMAC_MD5
+};
+
+static krb5_error_code
+parse_key_set(krb5_context context, const char *key,
+ krb5_enctype **ret_enctypes, size_t *ret_num_enctypes,
+ krb5_salt *salt, krb5_principal principal)
+{
+ const char *p;
+ char buf[3][256];
+ int num_buf = 0;
+ int i, num_enctypes = 0;
+ krb5_enctype e;
+ const krb5_enctype *enctypes = NULL;
+ krb5_error_code ret;
+
+ p = key;
+
+ *ret_enctypes = NULL;
+ *ret_num_enctypes = 0;
+
+ /* split p in a list of :-separated strings */
+ for(num_buf = 0; num_buf < 3; num_buf++)
+ if(strsep_copy(&p, ":", buf[num_buf], sizeof(buf[num_buf])) == -1)
+ break;
+
+ salt->saltvalue.data = NULL;
+ salt->saltvalue.length = 0;
+
+ for(i = 0; i < num_buf; i++) {
+ if(enctypes == NULL && num_buf > 1) {
+ /* this might be a etype specifier */
+ /* XXX there should be a string_to_etypes handling
+ special cases like `des' and `all' */
+ if(strcmp(buf[i], "des") == 0) {
+ enctypes = des_etypes;
+ num_enctypes = sizeof(des_etypes)/sizeof(des_etypes[0]);
+ } else if(strcmp(buf[i], "des3") == 0) {
+ e = KRB5_ENCTYPE_DES3_CBC_SHA1;
+ enctypes = &e;
+ num_enctypes = 1;
+ } else {
+ ret = krb5_string_to_enctype(context, buf[i], &e);
+ if (ret == 0) {
+ enctypes = &e;
+ num_enctypes = 1;
+ } else
+ return ret;
+ }
+ continue;
+ }
+ if(salt->salttype == 0) {
+ /* interpret string as a salt specifier, if no etype
+ is set, this sets default values */
+ /* XXX should perhaps use string_to_salttype, but that
+ interface sucks */
+ if(strcmp(buf[i], "pw-salt") == 0) {
+ if(enctypes == NULL) {
+ enctypes = all_etypes;
+ num_enctypes = sizeof(all_etypes)/sizeof(all_etypes[0]);
+ }
+ salt->salttype = KRB5_PW_SALT;
+ } else if(strcmp(buf[i], "afs3-salt") == 0) {
+ if(enctypes == NULL) {
+ enctypes = des_etypes;
+ num_enctypes = sizeof(des_etypes)/sizeof(des_etypes[0]);
+ }
+ salt->salttype = KRB5_AFS3_SALT;
+ }
+ continue;
+ }
+
+ if (salt->saltvalue.data != NULL)
+ free(salt->saltvalue.data);
+ /* if there is a final string, use it as the string to
+ salt with, this is mostly useful with null salt for
+ v4 compat, and a cell name for afs compat */
+ salt->saltvalue.data = strdup(buf[i]);
+ if (salt->saltvalue.data == NULL)
+ return krb5_enomem(context);
+ salt->saltvalue.length = strlen(buf[i]);
+ }
+
+ if(enctypes == NULL || salt->salttype == 0) {
+ krb5_free_salt(context, *salt);
+ krb5_set_error_message(context, EINVAL, "bad value for default_keys `%s'", key);
+ return EINVAL;
+ }
+
+ /* if no salt was specified make up default salt */
+ if(salt->saltvalue.data == NULL) {
+ if(salt->salttype == KRB5_PW_SALT) {
+ ret = krb5_get_pw_salt(context, principal, salt);
+ if (ret)
+ return ret;
+ } else if(salt->salttype == KRB5_AFS3_SALT) {
+ krb5_const_realm realm = krb5_principal_get_realm(context, principal);
+ salt->saltvalue.data = strdup(realm);
+ if(salt->saltvalue.data == NULL) {
+ krb5_set_error_message(context, ENOMEM,
+ "out of memory while "
+ "parsing salt specifiers");
+ return ENOMEM;
+ }
+ strlwr(salt->saltvalue.data);
+ salt->saltvalue.length = strlen(realm);
+ }
+ }
+
+ *ret_enctypes = malloc(sizeof(enctypes[0]) * num_enctypes);
+ if (*ret_enctypes == NULL) {
+ krb5_free_salt(context, *salt);
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ memcpy(*ret_enctypes, enctypes, sizeof(enctypes[0]) * num_enctypes);
+ *ret_num_enctypes = num_enctypes;
+
+ return 0;
+}
+
+/**
+ * This function prunes an HDB entry's historic keys by kvno.
+ *
+ * @param context Context
+ * @param entry HDB entry
+ * @param kvno Keyset kvno to prune, or zero to prune all too-old keys
+ */
+krb5_error_code
+hdb_prune_keys_kvno(krb5_context context, hdb_entry *entry, int kvno)
+{
+ HDB_extension *ext;
+ HDB_Ext_KeySet *keys;
+ hdb_keyset *elem;
+ time_t keep_time = 0;
+ size_t nelem;
+ size_t i;
+
+ /*
+ * XXX Pruning old keys for namespace principals may not be desirable, but!
+ * as long as the `set_time's of the base keys for a namespace principal
+ * match the `epoch's of the corresponding KeyRotation periods, it will be
+ * perfectly acceptable to prune old [base] keys for namespace principals
+ * just as for any other principal. Therefore, we may not need to make any
+ * changes here w.r.t. namespace principals.
+ */
+
+ ext = hdb_find_extension(entry, choice_HDB_extension_data_hist_keys);
+ if (ext == NULL)
+ return 0;
+ keys = &ext->data.u.hist_keys;
+ nelem = keys->len;
+
+ /*
+ * Optionally drop key history for keys older than now - max_life, which is
+ * all the keys no longer needed to decrypt extant tickets.
+ */
+ if (kvno == 0 && entry->max_life != NULL && nelem > 0) {
+ time_t ceiling = time(NULL) - *entry->max_life;
+
+ /*
+ * Compute most recent key timestamp that predates the current time
+ * by at least the entry's maximum ticket lifetime.
+ */
+ for (i = 0; i < nelem; ++i) {
+ elem = &keys->val[i];
+ if (elem->set_time && *elem->set_time < ceiling
+ && (keep_time == 0 || *elem->set_time > keep_time))
+ keep_time = *elem->set_time;
+ }
+ }
+
+ if (kvno == 0 && keep_time == 0)
+ return 0;
+
+ for (i = 0; i < nelem; /* see below */) {
+ elem = &keys->val[i];
+ if ((kvno && kvno == elem->kvno) ||
+ (keep_time && elem->set_time && *elem->set_time < keep_time)) {
+ remove_HDB_Ext_KeySet(keys, i);
+ /*
+ * Removing the i'th element shifts the tail down, continue
+ * at same index with reduced upper bound.
+ */
+ --nelem;
+ continue;
+ }
+ ++i;
+ }
+
+ return 0;
+}
+
+/**
+ * This function prunes an HDB entry's keys that are too old to have been used
+ * to mint still valid tickets (based on the entry's maximum ticket lifetime).
+ *
+ * @param context Context
+ * @param entry HDB entry
+ */
+krb5_error_code
+hdb_prune_keys(krb5_context context, hdb_entry *entry)
+{
+ if (!krb5_config_get_bool_default(context, NULL, FALSE,
+ "kadmin", "prune-key-history", NULL))
+ return 0;
+ return hdb_prune_keys_kvno(context, entry, 0);
+}
+
+/**
+ * This function adds a keyset to an HDB entry's key history.
+ *
+ * @param context Context
+ * @param entry HDB entry
+ * @param kvno Key version number of the key to add to the history
+ * @param key The Key to add
+ */
+krb5_error_code
+hdb_add_history_keyset(krb5_context context,
+ hdb_entry *entry,
+ const hdb_keyset *ks)
+{
+ size_t i;
+ HDB_Ext_KeySet *hist_keys;
+ HDB_extension ext;
+ HDB_extension *extp;
+ krb5_error_code ret = 0;
+
+ memset(&ext, 0, sizeof (ext));
+
+ extp = hdb_find_extension(entry, choice_HDB_extension_data_hist_keys);
+ if (extp == NULL) {
+ ext.mandatory = FALSE;
+ ext.data.element = choice_HDB_extension_data_hist_keys;
+ ext.data.u.hist_keys.len = 0;
+ ext.data.u.hist_keys.val = 0;
+ extp = &ext;
+ }
+ hist_keys = &extp->data.u.hist_keys;
+
+ for (i = 0; i < hist_keys->len; i++) {
+ if (hist_keys->val[i].kvno == ks->kvno) {
+ /* Replace existing */
+ free_HDB_keyset(&hist_keys->val[i]);
+ ret = copy_HDB_keyset(ks, &hist_keys->val[i]);
+ break;
+ }
+ }
+ if (i >= hist_keys->len)
+ ret = add_HDB_Ext_KeySet(hist_keys, ks); /* Append new */
+ if (ret == 0 && extp == &ext)
+ ret = hdb_replace_extension(context, entry, &ext);
+ free_HDB_extension(&ext);
+ return ret;
+}
+
+/**
+ * This function adds an HDB entry's current keyset to the entry's key
+ * history. The current keyset is left alone; the caller is responsible
+ * for freeing it.
+ *
+ * @param context Context
+ * @param entry HDB entry
+ *
+ * @return Zero on success, or an error code otherwise.
+ */
+krb5_error_code
+hdb_add_current_keys_to_history(krb5_context context, hdb_entry *entry)
+{
+ krb5_error_code ret;
+ hdb_keyset ks;
+ time_t newtime;
+
+ if (entry->keys.len == 0)
+ return 0; /* nothing to do */
+
+ ret = hdb_entry_get_pw_change_time(entry, &newtime);
+ if (ret)
+ return ret;
+
+ ks.keys = entry->keys;
+ ks.kvno = entry->kvno;
+ ks.set_time = &newtime;
+
+ ret = hdb_add_history_keyset(context, entry, &ks);
+ if (ret == 0)
+ ret = hdb_prune_keys(context, entry);
+ return ret;
+}
+
+/**
+ * This function adds a key to an HDB entry's key history.
+ *
+ * @param context Context
+ * @param entry HDB entry
+ * @param kvno Key version number of the key to add to the history
+ * @param key The Key to add
+ *
+ * @return Zero on success, or an error code otherwise.
+ */
+krb5_error_code
+hdb_add_history_key(krb5_context context, hdb_entry *entry, krb5_kvno kvno, Key *key)
+{
+ size_t i;
+ hdb_keyset keyset;
+ HDB_Ext_KeySet *hist_keys;
+ HDB_extension ext;
+ HDB_extension *extp;
+ krb5_error_code ret;
+
+ memset(&keyset, 0, sizeof (keyset));
+ memset(&ext, 0, sizeof (ext));
+
+ extp = hdb_find_extension(entry, choice_HDB_extension_data_hist_keys);
+ if (extp == NULL) {
+ ext.data.element = choice_HDB_extension_data_hist_keys;
+ extp = &ext;
+ }
+
+ extp->mandatory = FALSE;
+ hist_keys = &extp->data.u.hist_keys;
+
+ for (i = 0; i < hist_keys->len; i++) {
+ if (hist_keys->val[i].kvno == kvno) {
+ ret = add_Keys(&hist_keys->val[i].keys, key);
+ goto out;
+ }
+ }
+
+ keyset.kvno = kvno;
+ ret = add_Keys(&keyset.keys, key);
+ if (ret)
+ goto out;
+ ret = add_HDB_Ext_KeySet(hist_keys, &keyset);
+ if (ret)
+ goto out;
+ if (extp == &ext) {
+ ret = hdb_replace_extension(context, entry, &ext);
+ if (ret)
+ goto out;
+ }
+
+out:
+ free_HDB_keyset(&keyset);
+ free_HDB_extension(&ext);
+ return ret;
+}
+
+/**
+ * This function changes an hdb_entry's kvno, swapping the current key
+ * set with a historical keyset. If no historical keys are found then
+ * an error is returned (the caller can still set entry->kvno directly).
+ *
+ * @param context krb5_context
+ * @param new_kvno New kvno for the entry
+ * @param entry hdb_entry to modify
+ */
+krb5_error_code
+hdb_change_kvno(krb5_context context, krb5_kvno new_kvno, hdb_entry *entry)
+{
+ HDB_extension ext;
+ HDB_extension *extp;
+ hdb_keyset keyset;
+ HDB_Ext_KeySet *hist_keys;
+ size_t i;
+ int found = 0;
+ krb5_error_code ret;
+
+ if (entry->kvno == new_kvno)
+ return 0;
+
+ extp = hdb_find_extension(entry, choice_HDB_extension_data_hist_keys);
+ if (extp == NULL) {
+ memset(&ext, 0, sizeof (ext));
+ ext.data.element = choice_HDB_extension_data_hist_keys;
+ extp = &ext;
+ }
+
+ memset(&keyset, 0, sizeof (keyset));
+ hist_keys = &extp->data.u.hist_keys;
+ for (i = 0; i < hist_keys->len; i++) {
+ if (hist_keys->val[i].kvno == new_kvno) {
+ found = 1;
+ ret = copy_HDB_keyset(&hist_keys->val[i], &keyset);
+ if (ret)
+ goto out;
+ ret = remove_HDB_Ext_KeySet(hist_keys, i);
+ if (ret)
+ goto out;
+ break;
+ }
+ }
+
+ if (!found)
+ return HDB_ERR_KVNO_NOT_FOUND;
+
+ ret = hdb_add_current_keys_to_history(context, entry);
+ if (ret)
+ goto out;
+
+ /* Note: we do nothing with keyset.set_time */
+ entry->kvno = new_kvno;
+ entry->keys = keyset.keys; /* shortcut */
+ memset(&keyset.keys, 0, sizeof (keyset.keys));
+
+out:
+ free_HDB_keyset(&keyset);
+ return ret;
+}
+
+
+static krb5_error_code
+add_enctype_to_key_set(Key **key_set, size_t *nkeyset,
+ krb5_enctype enctype, krb5_salt *salt)
+{
+ krb5_error_code ret;
+ Key key, *tmp;
+
+ memset(&key, 0, sizeof(key));
+
+ tmp = realloc(*key_set, (*nkeyset + 1) * sizeof((*key_set)[0]));
+ if (tmp == NULL)
+ return ENOMEM;
+
+ *key_set = tmp;
+
+ key.key.keytype = enctype;
+ key.key.keyvalue.length = 0;
+ key.key.keyvalue.data = NULL;
+
+ if (salt) {
+ key.salt = calloc(1, sizeof(*key.salt));
+ if (key.salt == NULL) {
+ free_Key(&key);
+ return ENOMEM;
+ }
+
+ key.salt->type = salt->salttype;
+ krb5_data_zero (&key.salt->salt);
+
+ ret = krb5_data_copy(&key.salt->salt,
+ salt->saltvalue.data,
+ salt->saltvalue.length);
+ if (ret) {
+ free_Key(&key);
+ return ret;
+ }
+ } else
+ key.salt = NULL;
+
+ (*key_set)[*nkeyset] = key;
+
+ *nkeyset += 1;
+
+ return 0;
+}
+
+
+static
+krb5_error_code
+ks_tuple2str(krb5_context context, int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple, char ***ks_tuple_strs)
+{
+ size_t i;
+ char **ksnames;
+ krb5_error_code rc = KRB5_PROG_ETYPE_NOSUPP;
+
+ *ks_tuple_strs = NULL;
+ if (n_ks_tuple < 1)
+ return 0;
+
+ if ((ksnames = calloc(n_ks_tuple + 1, sizeof (*ksnames))) == NULL)
+ return (errno);
+
+ for (i = 0; i < n_ks_tuple; i++) {
+ char *ename, *sname;
+
+ if (krb5_enctype_to_string(context, ks_tuple[i].ks_enctype, &ename))
+ goto out;
+ if (krb5_salttype_to_string(context, ks_tuple[i].ks_enctype,
+ ks_tuple[i].ks_salttype, &sname)) {
+ free(ename);
+ goto out;
+ }
+
+ if (asprintf(&ksnames[i], "%s:%s", ename, sname) == -1) {
+ rc = errno;
+ free(ename);
+ free(sname);
+ goto out;
+ }
+ free(ename);
+ free(sname);
+ }
+
+ ksnames[i] = NULL;
+ *ks_tuple_strs = ksnames;
+ return 0;
+
+out:
+ for (i = 0; i < n_ks_tuple; i++)
+ free(ksnames[i]);
+ free(ksnames);
+ return (rc);
+}
+
+/*
+ *
+ */
+
+static char **
+glob_rules_keys(krb5_context context, krb5_const_principal principal)
+{
+ const krb5_config_binding *list;
+ krb5_principal pattern;
+ krb5_error_code ret;
+
+ list = krb5_config_get_list(context, NULL, "kadmin",
+ "default_key_rules", NULL);
+ if (list == NULL)
+ return NULL;
+
+ while (list) {
+ if (list->type == krb5_config_string) {
+ ret = krb5_parse_name(context, list->name, &pattern);
+ if (ret == 0) {
+ ret = krb5_principal_match(context, principal, pattern);
+ krb5_free_principal(context, pattern);
+ if (ret) {
+ return krb5_config_get_strings(context, list,
+ list->name, NULL);
+ }
+ }
+ }
+ list = list->next;
+ }
+ return NULL;
+}
+
+/*
+ * NIST guidance in Section 5.1 of [SP800-132] requires that a portion
+ * of the salt of at least 128 bits shall be randomly generated.
+ */
+static krb5_error_code
+add_random_to_salt(krb5_context context, krb5_salt *in, krb5_salt *out)
+{
+ krb5_error_code ret;
+ char *p;
+ unsigned char random[16];
+ char *s;
+ int slen;
+
+ krb5_generate_random_block(random, sizeof(random));
+
+ slen = rk_base64_encode(random, sizeof(random), &s);
+ if (slen < 0)
+ return ENOMEM;
+
+ ret = krb5_data_alloc(&out->saltvalue, slen + in->saltvalue.length);
+ if (ret) {
+ free(s);
+ return ret;
+ }
+
+ p = out->saltvalue.data;
+ memcpy(p, s, slen);
+ memcpy(&p[slen], in->saltvalue.data, in->saltvalue.length);
+
+ out->salttype = in->salttype;
+ free(s);
+
+ return 0;
+}
+
+/*
+ * Generate the `key_set' from the [kadmin]default_keys statement. If
+ * `no_salt' is set, salt is not important (and will not be set) since
+ * it's random keys that is going to be created.
+ */
+
+krb5_error_code
+hdb_generate_key_set(krb5_context context, krb5_principal principal,
+ krb5_key_salt_tuple *ks_tuple, int n_ks_tuple,
+ Key **ret_key_set, size_t *nkeyset, int no_salt)
+{
+ char **ktypes = NULL;
+ char **kp;
+ krb5_error_code ret;
+ Key *k, *key_set;
+ size_t i, j;
+ char **ks_tuple_strs;
+ char **config_ktypes = NULL;
+ static const char *default_keytypes[] = {
+ "aes256-cts-hmac-sha1-96:pw-salt",
+ "des3-cbc-sha1:pw-salt",
+ "arcfour-hmac-md5:pw-salt",
+ NULL
+ };
+
+ if ((ret = ks_tuple2str(context, n_ks_tuple, ks_tuple, &ks_tuple_strs)))
+ return ret;
+
+ ktypes = ks_tuple_strs;
+ if (ktypes == NULL) {
+ config_ktypes = glob_rules_keys(context, principal);
+ ktypes = config_ktypes;
+ }
+ if (ktypes == NULL) {
+ config_ktypes = krb5_config_get_strings(context, NULL, "kadmin",
+ "default_keys", NULL);
+ ktypes = config_ktypes;
+ }
+ if (ktypes == NULL)
+ ktypes = (char **)(intptr_t)default_keytypes;
+
+ *ret_key_set = key_set = NULL;
+ *nkeyset = 0;
+
+ for(kp = ktypes; kp && *kp; kp++) {
+ const char *p;
+ krb5_salt salt;
+ krb5_enctype *enctypes;
+ size_t num_enctypes;
+
+ p = *kp;
+ /* check alias */
+ if(strcmp(p, "v5") == 0)
+ p = "pw-salt";
+ else if(strcmp(p, "v4") == 0)
+ p = "des:pw-salt:";
+ else if(strcmp(p, "afs") == 0 || strcmp(p, "afs3") == 0)
+ p = "des:afs3-salt";
+ else if (strcmp(p, "arcfour-hmac-md5") == 0)
+ p = "arcfour-hmac-md5:pw-salt";
+
+ memset(&salt, 0, sizeof(salt));
+
+ ret = parse_key_set(context, p,
+ &enctypes, &num_enctypes, &salt, principal);
+ if (ret) {
+ krb5_warn(context, ret, "bad value for default_keys `%s'", *kp);
+ ret = 0;
+ krb5_free_salt(context, salt);
+ continue;
+ }
+
+ for (i = 0; i < num_enctypes; i++) {
+ krb5_salt *saltp = no_salt ? NULL : &salt;
+ krb5_salt rsalt;
+
+ /* find duplicates */
+ for (j = 0; j < *nkeyset; j++) {
+
+ k = &key_set[j];
+
+ if (k->key.keytype == enctypes[i]) {
+ if (no_salt)
+ break;
+ if (k->salt == NULL && salt.salttype == KRB5_PW_SALT)
+ break;
+ if (k->salt->type == salt.salttype &&
+ k->salt->salt.length == salt.saltvalue.length &&
+ memcmp(k->salt->salt.data, salt.saltvalue.data,
+ salt.saltvalue.length) == 0)
+ break;
+ }
+ }
+ /* not a duplicate, lets add it */
+ if (j < *nkeyset)
+ continue;
+
+ memset(&rsalt, 0, sizeof(rsalt));
+
+ /* prepend salt with randomness if required */
+ if (!no_salt &&
+ _krb5_enctype_requires_random_salt(context, enctypes[i])) {
+ saltp = &rsalt;
+ ret = add_random_to_salt(context, &salt, &rsalt);
+ }
+
+ if (ret == 0)
+ ret = add_enctype_to_key_set(&key_set, nkeyset, enctypes[i],
+ saltp);
+ krb5_free_salt(context, rsalt);
+
+ if (ret) {
+ free(enctypes);
+ krb5_free_salt(context, salt);
+ goto out;
+ }
+ }
+ free(enctypes);
+ krb5_free_salt(context, salt);
+ }
+
+ *ret_key_set = key_set;
+
+ out:
+ if (config_ktypes != NULL)
+ krb5_config_free_strings(config_ktypes);
+
+ for(kp = ks_tuple_strs; kp && *kp; kp++)
+ free(*kp);
+ free(ks_tuple_strs);
+
+ if (ret) {
+ krb5_warn(context, ret,
+ "failed to parse the [kadmin]default_keys values");
+
+ for (i = 0; i < *nkeyset; i++)
+ free_Key(&key_set[i]);
+ free(key_set);
+ } else if (*nkeyset == 0) {
+ krb5_warnx(context,
+ "failed to parse any of the [kadmin]default_keys values");
+ ret = EINVAL; /* XXX */
+ }
+
+ return ret;
+}
+
+
+krb5_error_code
+hdb_generate_key_set_password_with_ks_tuple(krb5_context context,
+ krb5_principal principal,
+ const char *password,
+ krb5_key_salt_tuple *ks_tuple,
+ int n_ks_tuple,
+ Key **keys, size_t *num_keys)
+{
+ krb5_error_code ret;
+ size_t i;
+
+ ret = hdb_generate_key_set(context, principal, ks_tuple, n_ks_tuple,
+ keys, num_keys, 0);
+ if (ret)
+ return ret;
+
+ for (i = 0; i < (*num_keys); i++) {
+ krb5_salt salt;
+ Key *key = &(*keys)[i];
+
+ salt.salttype = key->salt->type;
+ salt.saltvalue.length = key->salt->salt.length;
+ salt.saltvalue.data = key->salt->salt.data;
+
+ ret = krb5_string_to_key_salt (context,
+ key->key.keytype,
+ password,
+ salt,
+ &key->key);
+ if(ret)
+ break;
+ }
+
+ if(ret) {
+ hdb_free_keys (context, *num_keys, *keys);
+ return ret;
+ }
+ return ret;
+}
+
+
+krb5_error_code
+hdb_generate_key_set_password(krb5_context context,
+ krb5_principal principal,
+ const char *password,
+ Key **keys, size_t *num_keys)
+{
+
+ return hdb_generate_key_set_password_with_ks_tuple(context, principal,
+ password, NULL, 0,
+ keys, num_keys);
+}
diff --git a/third_party/heimdal/lib/hdb/keytab.c b/third_party/heimdal/lib/hdb/keytab.c
new file mode 100644
index 0000000..b1aa020
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/keytab.c
@@ -0,0 +1,449 @@
+/*
+ * Copyright (c) 1999 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hdb_locl.h"
+
+/* keytab backend for HDB databases */
+
+struct hdb_data {
+ char *dbname;
+ char *mkey;
+};
+
+struct hdb_cursor {
+ HDB *db;
+ hdb_entry hdb_entry;
+ int first, next;
+ int key_idx;
+};
+
+/*
+ * the format for HDB keytabs is:
+ * HDB:[HDBFORMAT:database-specific-data[:mkey=mkey-file]]
+ */
+
+static krb5_error_code KRB5_CALLCONV
+hdb_resolve(krb5_context context, const char *name, krb5_keytab id)
+{
+ struct hdb_data *d;
+ const char *db, *mkey;
+
+ d = malloc(sizeof(*d));
+ if(d == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ db = name;
+ mkey = strstr(name, ":mkey=");
+ if(mkey == NULL || mkey[6] == '\0') {
+ if(*name == '\0')
+ d->dbname = NULL;
+ else {
+ d->dbname = strdup(name);
+ if(d->dbname == NULL) {
+ free(d);
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ }
+ d->mkey = NULL;
+ } else {
+ d->dbname = malloc(mkey - db + 1);
+ if(d->dbname == NULL) {
+ free(d);
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ memmove(d->dbname, db, mkey - db);
+ d->dbname[mkey - db] = '\0';
+
+ d->mkey = strdup(mkey + 6);
+ if(d->mkey == NULL) {
+ free(d->dbname);
+ free(d);
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ }
+ id->data = d;
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+hdb_close(krb5_context context, krb5_keytab id)
+{
+ struct hdb_data *d = id->data;
+
+ free(d->dbname);
+ free(d->mkey);
+ free(d);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+hdb_get_name(krb5_context context,
+ krb5_keytab id,
+ char *name,
+ size_t namesize)
+{
+ struct hdb_data *d = id->data;
+
+ snprintf(name, namesize, "%s%s%s",
+ d->dbname ? d->dbname : "",
+ (d->dbname || d->mkey) ? ":" : "",
+ d->mkey ? d->mkey : "");
+ return 0;
+}
+
+/*
+ * try to figure out the database (`dbname') and master-key (`mkey')
+ * that should be used for `principal'.
+ */
+
+static krb5_error_code
+find_db (krb5_context context,
+ char **dbname,
+ char **mkey,
+ krb5_const_principal principal)
+{
+ krb5_const_realm realm = krb5_principal_get_realm(context, principal);
+ krb5_error_code ret;
+ struct hdb_dbinfo *head, *dbinfo = NULL;
+
+ *dbname = *mkey = NULL;
+
+ ret = hdb_get_dbinfo(context, &head);
+ if (ret)
+ return ret;
+
+ while ((dbinfo = hdb_dbinfo_get_next(head, dbinfo)) != NULL) {
+ const char *p = hdb_dbinfo_get_realm(context, dbinfo);
+ if (p && strcmp (realm, p) == 0) {
+ p = hdb_dbinfo_get_dbname(context, dbinfo);
+ if (p)
+ *dbname = strdup(p);
+ p = hdb_dbinfo_get_mkey_file(context, dbinfo);
+ if (p)
+ *mkey = strdup(p);
+ break;
+ }
+ }
+ hdb_free_dbinfo(context, &head);
+ if (*dbname == NULL &&
+ (*dbname = strdup(hdb_default_db(context))) == NULL) {
+ free(*mkey);
+ *mkey = NULL;
+ return krb5_enomem(context);
+ }
+ return 0;
+}
+
+/*
+ * find the keytab entry in `id' for `principal, kvno, enctype' and return
+ * it in `entry'. return 0 or an error code
+ */
+
+static krb5_error_code KRB5_CALLCONV
+hdb_get_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_const_principal principal,
+ krb5_kvno kvno,
+ krb5_enctype enctype,
+ krb5_keytab_entry *entry)
+{
+ hdb_entry ent;
+ krb5_error_code ret;
+ struct hdb_data *d = id->data;
+ const char *dbname = d->dbname;
+ const char *mkey = d->mkey;
+ char *fdbname = NULL, *fmkey = NULL;
+ HDB *db;
+ size_t i;
+
+ if (!principal)
+ return KRB5_KT_NOTFOUND;
+
+ memset(&ent, 0, sizeof(ent));
+
+ if (dbname == NULL) {
+ ret = find_db(context, &fdbname, &fmkey, principal);
+ if (ret)
+ return ret;
+ dbname = fdbname;
+ mkey = fmkey;
+ }
+
+ ret = hdb_create (context, &db, dbname);
+ if (ret)
+ goto out2;
+ ret = hdb_set_master_keyfile (context, db, mkey);
+ if (ret) {
+ (*db->hdb_destroy)(context, db);
+ goto out2;
+ }
+
+ ret = (*db->hdb_open)(context, db, O_RDONLY, 0);
+ if (ret) {
+ (*db->hdb_destroy)(context, db);
+ goto out2;
+ }
+
+ ret = hdb_fetch_kvno(context, db, principal,
+ HDB_F_DECRYPT|HDB_F_KVNO_SPECIFIED|
+ HDB_F_GET_CLIENT|HDB_F_GET_SERVER|HDB_F_GET_KRBTGT,
+ 0, 0, kvno, &ent);
+
+ if(ret == HDB_ERR_NOENTRY) {
+ ret = KRB5_KT_NOTFOUND;
+ goto out;
+ }else if(ret)
+ goto out;
+
+ if(kvno && (krb5_kvno)ent.kvno != kvno) {
+ hdb_free_entry(context, db, &ent);
+ ret = KRB5_KT_NOTFOUND;
+ goto out;
+ }
+ if(enctype == 0)
+ if(ent.keys.len > 0)
+ enctype = ent.keys.val[0].key.keytype;
+ ret = KRB5_KT_NOTFOUND;
+ for(i = 0; i < ent.keys.len; i++) {
+ if(ent.keys.val[i].key.keytype == enctype) {
+ krb5_copy_principal(context, principal, &entry->principal);
+ entry->vno = ent.kvno;
+ krb5_copy_keyblock_contents(context,
+ &ent.keys.val[i].key,
+ &entry->keyblock);
+ ret = 0;
+ break;
+ }
+ }
+ hdb_free_entry(context, db, &ent);
+ out:
+ (*db->hdb_close)(context, db);
+ (*db->hdb_destroy)(context, db);
+ out2:
+ free(fdbname);
+ free(fmkey);
+ return ret;
+}
+
+/*
+ * find the keytab entry in `id' for `principal, kvno, enctype' and return
+ * it in `entry'. return 0 or an error code
+ */
+
+static krb5_error_code KRB5_CALLCONV
+hdb_start_seq_get(krb5_context context,
+ krb5_keytab id,
+ krb5_kt_cursor *cursor)
+{
+ krb5_error_code ret;
+ struct hdb_cursor *c;
+ struct hdb_data *d = id->data;
+ const char *dbname = d->dbname;
+ const char *mkey = d->mkey;
+ HDB *db;
+
+ if (dbname == NULL) {
+ /*
+ * We don't support enumerating without being told what
+ * backend to enumerate on
+ */
+ ret = KRB5_KT_NOTFOUND;
+ return ret;
+ }
+
+ ret = hdb_create (context, &db, dbname);
+ if (ret)
+ return ret;
+ ret = hdb_set_master_keyfile (context, db, mkey);
+ if (ret) {
+ (*db->hdb_destroy)(context, db);
+ return ret;
+ }
+
+ ret = (*db->hdb_open)(context, db, O_RDONLY, 0);
+ if (ret) {
+ (*db->hdb_destroy)(context, db);
+ return ret;
+ }
+
+ cursor->data = c = malloc (sizeof(*c));
+ if(c == NULL){
+ (*db->hdb_close)(context, db);
+ (*db->hdb_destroy)(context, db);
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ c->db = db;
+ c->first = TRUE;
+ c->next = TRUE;
+ c->key_idx = 0;
+
+ cursor->data = c;
+ return ret;
+}
+
+static int KRB5_CALLCONV
+hdb_next_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry,
+ krb5_kt_cursor *cursor)
+{
+ struct hdb_cursor *c = cursor->data;
+ krb5_error_code ret;
+
+ memset(entry, 0, sizeof(*entry));
+
+ if (c->first) {
+ c->first = FALSE;
+ ret = (c->db->hdb_firstkey)(context, c->db,
+ HDB_F_DECRYPT|
+ HDB_F_GET_CLIENT|HDB_F_GET_SERVER|HDB_F_GET_KRBTGT,
+ &c->hdb_entry);
+ if (ret == HDB_ERR_NOENTRY)
+ return KRB5_KT_END;
+ else if (ret)
+ return ret;
+
+ if (c->hdb_entry.keys.len == 0)
+ hdb_free_entry(context, c->db, &c->hdb_entry);
+ else
+ c->next = FALSE;
+ }
+
+ while (c->next) {
+ ret = (c->db->hdb_nextkey)(context, c->db,
+ HDB_F_DECRYPT|
+ HDB_F_GET_CLIENT|HDB_F_GET_SERVER|HDB_F_GET_KRBTGT,
+ &c->hdb_entry);
+ if (ret == HDB_ERR_NOENTRY)
+ return KRB5_KT_END;
+ else if (ret)
+ return ret;
+
+ /* If no keys on this entry, try again */
+ if (c->hdb_entry.keys.len == 0)
+ hdb_free_entry(context, c->db, &c->hdb_entry);
+ else
+ c->next = FALSE;
+ }
+
+ /*
+ * Return next enc type (keytabs are one slot per key, while
+ * hdb is one record per principal.
+ */
+
+ ret = krb5_copy_principal(context,
+ c->hdb_entry.principal,
+ &entry->principal);
+ if (ret)
+ return ret;
+
+ entry->vno = c->hdb_entry.kvno;
+ ret = krb5_copy_keyblock_contents(context,
+ &c->hdb_entry.keys.val[c->key_idx].key,
+ &entry->keyblock);
+ if (ret) {
+ krb5_free_principal(context, entry->principal);
+ memset(entry, 0, sizeof(*entry));
+ return ret;
+ }
+ c->key_idx++;
+
+ /*
+ * Once we get to the end of the list, signal that we want the
+ * next entry
+ */
+
+ if ((size_t)c->key_idx == c->hdb_entry.keys.len) {
+ hdb_free_entry(context, c->db, &c->hdb_entry);
+ c->next = TRUE;
+ c->key_idx = 0;
+ }
+
+ return 0;
+}
+
+
+static int KRB5_CALLCONV
+hdb_end_seq_get(krb5_context context,
+ krb5_keytab id,
+ krb5_kt_cursor *cursor)
+{
+ struct hdb_cursor *c = cursor->data;
+
+ if (!c->next)
+ hdb_free_entry(context, c->db, &c->hdb_entry);
+
+ (c->db->hdb_close)(context, c->db);
+ (c->db->hdb_destroy)(context, c->db);
+
+ free(c);
+ return 0;
+}
+
+krb5_kt_ops hdb_kt_ops = {
+ "HDB",
+ hdb_resolve,
+ hdb_get_name,
+ hdb_close,
+ NULL, /* destroy */
+ hdb_get_entry,
+ hdb_start_seq_get,
+ hdb_next_entry,
+ hdb_end_seq_get,
+ NULL, /* add */
+ NULL, /* remove */
+ NULL,
+ 0
+};
+
+krb5_kt_ops hdb_get_kt_ops = {
+ "HDBGET",
+ hdb_resolve,
+ hdb_get_name,
+ hdb_close,
+ NULL,
+ hdb_get_entry,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ 0
+};
diff --git a/third_party/heimdal/lib/hdb/libhdb-exports.def b/third_party/heimdal/lib/hdb/libhdb-exports.def
new file mode 100644
index 0000000..72a7fb7
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/libhdb-exports.def
@@ -0,0 +1,180 @@
+EXPORTS
+ encode_HDB_keyset
+ _hdb_fetch_kvno
+ _hdb_remove
+ _hdb_store
+ hdb_add_current_keys_to_history
+ hdb_add_history_key
+ hdb_add_history_keyset
+ hdb_add_master_key
+ hdb_change_kvno
+ hdb_check_db_format
+ hdb_clear_extension
+ hdb_clear_master_key
+ hdb_create
+ hdb_db_dir
+ hdb_dbinfo_get_acl_file
+ hdb_dbinfo_get_binding
+ hdb_dbinfo_get_dbname
+ hdb_dbinfo_get_label
+ hdb_dbinfo_get_log_file
+ hdb_dbinfo_get_mkey_file
+ hdb_dbinfo_get_next
+ hdb_dbinfo_get_realm
+ hdb_derive_etypes
+ hdb_default_db
+ hdb_enctype2key
+ hdb_entry2string
+ hdb_entry2value
+ hdb_entry_add_key_rotation
+ hdb_entry_alias2value
+ hdb_entry_check_mandatory
+ hdb_entry_clear_password
+ hdb_entry_get_ConstrainedDelegACL
+ hdb_entry_get_aliases
+ hdb_entry_get_key_rotation
+ hdb_entry_get_krb5_config
+ hdb_entry_get_password
+ hdb_entry_get_pkinit_acl
+ hdb_entry_get_pkinit_cert
+ hdb_entry_get_pkinit_hash
+ hdb_entry_get_pw_change_time
+ hdb_entry_set_krb5_config
+ hdb_entry_set_password
+ hdb_entry_set_pw_change_time
+ hdb_fetch_kvno
+ hdb_find_extension
+ hdb_foreach
+ hdb_free_dbinfo
+ hdb_free_entry
+ hdb_free_key
+ hdb_free_keys
+ hdb_free_master_key
+ hdb_generate_key_set
+ hdb_generate_key_set_password
+ hdb_generate_key_set_password_with_ks_tuple
+ hdb_get_dbinfo
+ hdb_get_instance
+ hdb_init_db
+ hdb_install_keyset
+ hdb_interface_version DATA
+ hdb_key2principal
+ hdb_kvno2keys
+ hdb_list_builtin
+ hdb_lock
+ hdb_next_enctype2key
+ hdb_principal2key
+ hdb_print_entry
+ hdb_process_master_key
+ hdb_prune_keys
+ hdb_prune_keys_kvno
+ hdb_read_master_key
+ hdb_remove_keys
+ hdb_replace_extension
+ hdb_seal_key
+ hdb_seal_key_mkey
+ hdb_seal_keys
+ hdb_seal_keys_mkey
+ hdb_set_last_modified_by
+ hdb_set_master_key
+ hdb_set_master_keyfile
+ hdb_unlock
+ hdb_unseal_key
+ hdb_unseal_key_mkey
+ hdb_unseal_keys
+ hdb_unseal_keys_kvno
+ hdb_unseal_keys_mkey
+ hdb_validate_key_rotation
+ hdb_validate_key_rotations
+ hdb_value2entry
+ hdb_value2entry_alias
+ hdb_write_master_key
+ length_HDB_keyset
+ initialize_hdb_error_table_r
+
+ hdb_kt_ops
+ hdb_get_kt_ops
+
+; MIT KDB related entries
+ _hdb_mdb_value2entry
+ _hdb_mit_dump2mitdb_entry
+
+; some random bits needed for libkadm
+ add_HDB_Ext_KeyRotation
+ add_HDB_Ext_KeySet
+ add_Keys
+ asn1_HDBFlags_units
+ copy_Event
+ copy_HDB_EncTypeList
+ copy_hdb_entry
+ copy_HDB_entry
+ copy_hdb_entry_alias
+ copy_HDB_entry_alias
+ copy_HDB_EntryOrAlias
+ copy_HDB_extensions
+ copy_HDB_Ext_KeyRotation
+ copy_Key
+ copy_Keys
+ copy_Salt
+ decode_HDB_EncTypeList
+ decode_hdb_entry
+ decode_HDB_entry
+ decode_hdb_entry_alias
+ decode_HDB_entry_alias
+ decode_HDB_EntryOrAlias
+ decode_HDB_Ext_Aliases
+ decode_HDB_extension
+ decode_HDB_Ext_KeyRotation
+ decode_HDB_Ext_PKINIT_acl
+ decode_Key
+ decode_Keys
+ encode_HDB_EncTypeList
+ encode_hdb_entry
+ encode_HDB_entry
+ encode_hdb_entry_alias
+ encode_HDB_entry_alias
+ encode_HDB_EntryOrAlias
+ encode_HDB_Ext_Aliases
+ encode_HDB_extension
+ encode_HDB_Ext_KeyRotation
+ encode_HDB_Ext_PKINIT_acl
+ encode_hdb_keyset
+ encode_Key
+ encode_Keys
+ free_Event
+ free_HDB_EncTypeList
+ free_hdb_entry
+ free_HDB_entry
+ free_hdb_entry_alias
+ free_HDB_entry_alias
+ free_HDB_EntryOrAlias
+ free_HDB_Ext_Aliases
+ free_HDB_extension
+ free_HDB_extensions
+ free_HDB_Ext_KeyRotation
+ free_HDB_Ext_KeySet
+ free_HDB_Ext_PKINIT_acl
+ free_hdb_keyset
+ free_HDB_keyset
+ free_Key
+ free_Keys
+ free_Salt
+ HDBFlags2int
+ int2HDBFlags
+ int2KeyRotationFlags
+ KeyRotationFlags2int
+ length_HDB_EncTypeList
+ length_hdb_entry
+ length_HDB_entry
+ length_hdb_entry_alias
+ length_HDB_entry_alias
+ length_HDB_EntryOrAlias
+ length_HDB_Ext_Aliases
+ length_HDB_extension
+ length_HDB_Ext_KeyRotation
+ length_HDB_Ext_PKINIT_acl
+ length_hdb_keyset
+ length_Key
+ length_Keys
+ remove_HDB_Ext_KeyRotation
+ remove_Keys
diff --git a/third_party/heimdal/lib/hdb/libhdb-version.rc b/third_party/heimdal/lib/hdb/libhdb-version.rc
new file mode 100644
index 0000000..b0d417b
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/libhdb-version.rc
@@ -0,0 +1,36 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#define RC_FILE_TYPE VFT_DLL
+#define RC_FILE_DESC_0409 "Heimdal DB Library"
+#define RC_FILE_ORIG_0409 "libhdb.dll"
+
+#include "../../windows/version.rc"
diff --git a/third_party/heimdal/lib/hdb/mkey.c b/third_party/heimdal/lib/hdb/mkey.c
new file mode 100644
index 0000000..cfc27d4
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/mkey.c
@@ -0,0 +1,769 @@
+/*
+ * Copyright (c) 2000 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hdb_locl.h"
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+
+struct hdb_master_key_data {
+ krb5_keytab_entry keytab;
+ krb5_crypto crypto;
+ struct hdb_master_key_data *next;
+ unsigned int key_usage;
+};
+
+void
+hdb_free_master_key(krb5_context context, hdb_master_key mkey)
+{
+ struct hdb_master_key_data *ptr;
+ while(mkey) {
+ krb5_kt_free_entry(context, &mkey->keytab);
+ if (mkey->crypto)
+ krb5_crypto_destroy(context, mkey->crypto);
+ ptr = mkey;
+ mkey = mkey->next;
+ free(ptr);
+ }
+}
+
+krb5_error_code
+hdb_process_master_key(krb5_context context,
+ int kvno, krb5_keyblock *key, krb5_enctype etype,
+ hdb_master_key *mkey)
+{
+ krb5_error_code ret;
+
+ *mkey = calloc(1, sizeof(**mkey));
+ if(*mkey == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ (*mkey)->key_usage = HDB_KU_MKEY;
+ (*mkey)->keytab.vno = kvno;
+ ret = krb5_parse_name(context, "K/M", &(*mkey)->keytab.principal);
+ if(ret)
+ goto fail;
+ ret = krb5_copy_keyblock_contents(context, key, &(*mkey)->keytab.keyblock);
+ if(ret)
+ goto fail;
+ if(etype != 0)
+ (*mkey)->keytab.keyblock.keytype = etype;
+ (*mkey)->keytab.timestamp = time(NULL);
+ ret = krb5_crypto_init(context, key, etype, &(*mkey)->crypto);
+ if(ret)
+ goto fail;
+ return 0;
+ fail:
+ hdb_free_master_key(context, *mkey);
+ *mkey = NULL;
+ return ret;
+}
+
+krb5_error_code
+hdb_add_master_key(krb5_context context, krb5_keyblock *key,
+ hdb_master_key *inout)
+{
+ int vno = 0;
+ hdb_master_key p;
+ krb5_error_code ret;
+
+ for(p = *inout; p; p = p->next)
+ vno = max(vno, p->keytab.vno);
+ vno++;
+ ret = hdb_process_master_key(context, vno, key, 0, &p);
+ if(ret)
+ return ret;
+ p->next = *inout;
+ *inout = p;
+ return 0;
+}
+
+static krb5_error_code
+read_master_keytab(krb5_context context, const char *filename,
+ hdb_master_key *mkey)
+{
+ krb5_error_code ret;
+ krb5_keytab id;
+ krb5_kt_cursor cursor;
+ krb5_keytab_entry entry;
+ hdb_master_key p;
+
+ *mkey = NULL;
+ ret = krb5_kt_resolve(context, filename, &id);
+ if(ret)
+ return ret;
+
+ ret = krb5_kt_start_seq_get(context, id, &cursor);
+ if(ret)
+ goto out;
+ while(krb5_kt_next_entry(context, id, &entry, &cursor) == 0) {
+ p = calloc(1, sizeof(*p));
+ if (p == NULL) {
+ ret = ENOMEM;
+ break;
+ }
+ p->keytab = entry;
+ p->next = *mkey;
+ *mkey = p;
+ ret = krb5_crypto_init(context, &p->keytab.keyblock, 0, &p->crypto);
+ if (ret)
+ break;
+ }
+ krb5_kt_end_seq_get(context, id, &cursor);
+ out:
+ krb5_kt_close(context, id);
+ if (ret) {
+ hdb_free_master_key(context, *mkey);
+ *mkey = NULL;
+ }
+ return ret;
+}
+
+/* read a MIT master keyfile */
+static krb5_error_code
+read_master_mit(krb5_context context, const char *filename,
+ int byteorder, hdb_master_key *mkey)
+{
+ int fd;
+ krb5_error_code ret;
+ krb5_storage *sp;
+ int16_t enctype;
+ krb5_keyblock key;
+
+ fd = open(filename, O_RDONLY | O_BINARY);
+ if(fd < 0) {
+ int save_errno = errno;
+ krb5_set_error_message(context, save_errno, "failed to open %s: %s",
+ filename, strerror(save_errno));
+ return save_errno;
+ }
+ sp = krb5_storage_from_fd(fd);
+ if(sp == NULL) {
+ close(fd);
+ return errno;
+ }
+ krb5_storage_set_flags(sp, byteorder);
+ /* could possibly use ret_keyblock here, but do it with more
+ checks for now */
+ {
+ ret = krb5_ret_int16(sp, &enctype);
+ if (ret)
+ goto out;
+ ret = krb5_enctype_valid(context, enctype);
+ if (ret)
+ goto out;
+ key.keytype = enctype;
+ ret = krb5_ret_data(sp, &key.keyvalue);
+ if(ret)
+ goto out;
+ }
+ ret = hdb_process_master_key(context, 1, &key, 0, mkey);
+ krb5_free_keyblock_contents(context, &key);
+ out:
+ krb5_storage_free(sp);
+ close(fd);
+ return ret;
+}
+
+/* read an old master key file */
+static krb5_error_code
+read_master_encryptionkey(krb5_context context, const char *filename,
+ hdb_master_key *mkey)
+{
+ int fd;
+ krb5_keyblock key;
+ krb5_error_code ret;
+ unsigned char buf[256];
+ ssize_t len;
+ size_t ret_len;
+
+ fd = open(filename, O_RDONLY | O_BINARY);
+ if(fd < 0) {
+ int save_errno = errno;
+ krb5_set_error_message(context, save_errno, "failed to open %s: %s",
+ filename, strerror(save_errno));
+ return save_errno;
+ }
+
+ len = read(fd, buf, sizeof(buf));
+ close(fd);
+ if(len < 0) {
+ int save_errno = errno;
+ krb5_set_error_message(context, save_errno, "error reading %s: %s",
+ filename, strerror(save_errno));
+ return save_errno;
+ }
+
+ ret = decode_EncryptionKey(buf, len, &key, &ret_len);
+ memset_s(buf, sizeof(buf), 0, sizeof(buf));
+ if(ret)
+ return ret;
+
+ /* Originally, the keytype was just that, and later it got changed
+ to des-cbc-md5, but we always used des in cfb64 mode. This
+ should cover all cases, but will break if someone has hacked
+ this code to really use des-cbc-md5 -- but then that's not my
+ problem. */
+ if(key.keytype == ETYPE_DES_CBC_CRC || key.keytype == ETYPE_DES_CBC_MD5)
+ key.keytype = ETYPE_DES_CFB64_NONE;
+
+ ret = hdb_process_master_key(context, 0, &key, 0, mkey);
+ krb5_free_keyblock_contents(context, &key);
+ return ret;
+}
+
+/* read a krb4 /.k style file */
+static krb5_error_code
+read_master_krb4(krb5_context context, const char *filename,
+ hdb_master_key *mkey)
+{
+ int fd;
+ krb5_keyblock key;
+ krb5_error_code ret;
+ unsigned char buf[256];
+ ssize_t len;
+
+ fd = open(filename, O_RDONLY | O_BINARY);
+ if(fd < 0) {
+ int save_errno = errno;
+ krb5_set_error_message(context, save_errno, "failed to open %s: %s",
+ filename, strerror(save_errno));
+ return save_errno;
+ }
+
+ len = read(fd, buf, sizeof(buf));
+ close(fd);
+ if(len < 0) {
+ int save_errno = errno;
+ krb5_set_error_message(context, save_errno, "error reading %s: %s",
+ filename, strerror(save_errno));
+ return save_errno;
+ }
+ if(len != 8) {
+ krb5_set_error_message(context, HEIM_ERR_EOF,
+ "bad contents of %s", filename);
+ return HEIM_ERR_EOF; /* XXX file might be too large */
+ }
+
+ memset(&key, 0, sizeof(key));
+ key.keytype = ETYPE_DES_PCBC_NONE;
+ ret = krb5_data_copy(&key.keyvalue, buf, len);
+ memset_s(buf, sizeof(buf), 0, sizeof(buf));
+ if(ret)
+ return ret;
+
+ ret = hdb_process_master_key(context, 0, &key, 0, mkey);
+ krb5_free_keyblock_contents(context, &key);
+ return ret;
+}
+
+krb5_error_code
+hdb_read_master_key(krb5_context context, const char *filename,
+ hdb_master_key *mkey)
+{
+ FILE *f;
+ unsigned char buf[16];
+ krb5_error_code ret;
+
+ off_t len;
+
+ *mkey = NULL;
+
+ if(filename == NULL)
+ filename = HDB_DB_DIR "/m-key";
+
+ f = fopen(filename, "r");
+ if(f == NULL) {
+ int save_errno = errno;
+ krb5_set_error_message(context, save_errno, "failed to open %s: %s",
+ filename, strerror(save_errno));
+ return save_errno;
+ }
+
+ if(fread(buf, 1, 2, f) != 2) {
+ fclose(f);
+ krb5_set_error_message(context, HEIM_ERR_EOF, "end of file reading %s", filename);
+ return HEIM_ERR_EOF;
+ }
+
+ fseek(f, 0, SEEK_END);
+ len = ftell(f);
+
+ if(fclose(f) != 0)
+ return errno;
+
+ if(len < 0)
+ return errno;
+
+ if(len == 8) {
+ ret = read_master_krb4(context, filename, mkey);
+ } else if(buf[0] == 0x30 && len <= 127 && buf[1] == len - 2) {
+ ret = read_master_encryptionkey(context, filename, mkey);
+ } else if(buf[0] == 5 && buf[1] >= 1 && buf[1] <= 2) {
+ ret = read_master_keytab(context, filename, mkey);
+ } else {
+ /*
+ * Check both LittleEndian and BigEndian since they key file
+ * might be moved from a machine with diffrent byte order, or
+ * its running on MacOS X that always uses BE master keys.
+ */
+ ret = read_master_mit(context, filename, KRB5_STORAGE_BYTEORDER_LE, mkey);
+ if (ret)
+ ret = read_master_mit(context, filename, KRB5_STORAGE_BYTEORDER_BE, mkey);
+ }
+ return ret;
+}
+
+krb5_error_code
+hdb_write_master_key(krb5_context context, const char *filename,
+ hdb_master_key mkey)
+{
+ krb5_error_code ret;
+ hdb_master_key p;
+ krb5_keytab kt;
+
+ if(filename == NULL)
+ filename = HDB_DB_DIR "/m-key";
+
+ ret = krb5_kt_resolve(context, filename, &kt);
+ if(ret)
+ return ret;
+
+ for(p = mkey; p; p = p->next) {
+ ret = krb5_kt_add_entry(context, kt, &p->keytab);
+ }
+
+ krb5_kt_close(context, kt);
+
+ return ret;
+}
+
+krb5_error_code
+_hdb_set_master_key_usage(krb5_context context, HDB *db, unsigned int key_usage)
+{
+ if (db->hdb_master_key_set == 0)
+ return HDB_ERR_NO_MKEY;
+ db->hdb_master_key->key_usage = key_usage;
+ return 0;
+}
+
+hdb_master_key
+_hdb_find_master_key(unsigned int *mkvno, hdb_master_key mkey)
+{
+ hdb_master_key ret = NULL;
+ while(mkey) {
+ if(ret == NULL && mkey->keytab.vno == 0)
+ ret = mkey;
+ if(mkvno == NULL) {
+ if(ret == NULL || mkey->keytab.vno > ret->keytab.vno)
+ ret = mkey;
+ } else if((uint32_t)mkey->keytab.vno == *mkvno)
+ return mkey;
+ mkey = mkey->next;
+ }
+ return ret;
+}
+
+int
+_hdb_mkey_version(hdb_master_key mkey)
+{
+ return mkey->keytab.vno;
+}
+
+int
+_hdb_mkey_decrypt(krb5_context context, hdb_master_key key,
+ krb5_key_usage usage,
+ void *ptr, size_t size, krb5_data *res)
+{
+ return krb5_decrypt(context, key->crypto, usage,
+ ptr, size, res);
+}
+
+int
+_hdb_mkey_encrypt(krb5_context context, hdb_master_key key,
+ krb5_key_usage usage,
+ const void *ptr, size_t size, krb5_data *res)
+{
+ return krb5_encrypt(context, key->crypto, usage,
+ ptr, size, res);
+}
+
+krb5_error_code
+hdb_unseal_key_mkey(krb5_context context, Key *k, hdb_master_key mkey)
+{
+
+ krb5_error_code ret;
+ krb5_data res;
+ size_t keysize;
+
+ hdb_master_key key;
+
+ if(k->mkvno == NULL)
+ return 0;
+
+ key = _hdb_find_master_key(k->mkvno, mkey);
+
+ if (key == NULL)
+ return HDB_ERR_NO_MKEY;
+
+ ret = _hdb_mkey_decrypt(context, key, HDB_KU_MKEY,
+ k->key.keyvalue.data,
+ k->key.keyvalue.length,
+ &res);
+ if(ret == KRB5KRB_AP_ERR_BAD_INTEGRITY) {
+ /* try to decrypt with MIT key usage */
+ ret = _hdb_mkey_decrypt(context, key, 0,
+ k->key.keyvalue.data,
+ k->key.keyvalue.length,
+ &res);
+ }
+ if (ret)
+ return ret;
+
+ /* fixup keylength if the key got padded when encrypting it */
+ ret = krb5_enctype_keysize(context, k->key.keytype, &keysize);
+ if (ret) {
+ krb5_data_free(&res);
+ return ret;
+ }
+ if (keysize > res.length) {
+ krb5_data_free(&res);
+ return KRB5_BAD_KEYSIZE;
+ }
+
+ memset(k->key.keyvalue.data, 0, k->key.keyvalue.length);
+ free(k->key.keyvalue.data);
+ k->key.keyvalue = res;
+ k->key.keyvalue.length = keysize;
+ free(k->mkvno);
+ k->mkvno = NULL;
+
+ return 0;
+}
+
+krb5_error_code
+hdb_unseal_keys_mkey(krb5_context context, hdb_entry *ent, hdb_master_key mkey)
+{
+ size_t i;
+
+ for(i = 0; i < ent->keys.len; i++){
+ krb5_error_code ret;
+
+ ret = hdb_unseal_key_mkey(context, &ent->keys.val[i], mkey);
+ if (ret)
+ return ret;
+ }
+ return 0;
+}
+
+krb5_error_code
+hdb_unseal_keys(krb5_context context, HDB *db, hdb_entry *ent)
+{
+ if (db->hdb_master_key_set == 0)
+ return 0;
+ return hdb_unseal_keys_mkey(context, ent, db->hdb_master_key);
+}
+
+/*
+ * Unseal the keys for the given kvno (or all of them) of entry.
+ *
+ * If kvno == 0 -> unseal all.
+ * if kvno != 0 -> unseal the requested kvno and make sure it's the one listed
+ * as the current keyset for the entry (swapping it with a
+ * historical keyset if need be).
+ */
+krb5_error_code
+hdb_unseal_keys_kvno(krb5_context context, HDB *db, krb5_kvno kvno,
+ unsigned flags, hdb_entry *ent)
+{
+ krb5_error_code ret = HDB_ERR_NOENTRY;
+ HDB_extension *ext;
+ HDB_Ext_KeySet *hist_keys;
+ Key *tmp_val;
+ time_t tmp_set_time;
+ unsigned int tmp_len;
+ unsigned int kvno_diff = 0;
+ krb5_kvno tmp_kvno;
+ size_t i, k;
+ int exclude_dead = 0;
+ KerberosTime now = 0;
+
+ if (kvno == 0)
+ ret = 0;
+
+ if ((flags & HDB_F_LIVE_CLNT_KVNOS) || (flags & HDB_F_LIVE_SVC_KVNOS)) {
+ exclude_dead = 1;
+ now = time(NULL);
+ if (HDB_F_LIVE_CLNT_KVNOS)
+ kvno_diff = hdb_entry_get_kvno_diff_clnt(ent);
+ else
+ kvno_diff = hdb_entry_get_kvno_diff_svc(ent);
+ }
+
+ ext = hdb_find_extension(ent, choice_HDB_extension_data_hist_keys);
+ if (ext == NULL || (&ext->data.u.hist_keys)->len == 0)
+ return hdb_unseal_keys_mkey(context, ent, db->hdb_master_key);
+
+ /* For swapping; see below */
+ tmp_len = ent->keys.len;
+ tmp_val = ent->keys.val;
+ tmp_kvno = ent->kvno;
+ (void) hdb_entry_get_pw_change_time(ent, &tmp_set_time);
+
+ hist_keys = &ext->data.u.hist_keys;
+
+ for (i = 0; i < hist_keys->len; i++) {
+ if (kvno != 0 && hist_keys->val[i].kvno != kvno)
+ continue;
+
+ if (exclude_dead &&
+ ((ent->max_life != NULL &&
+ hist_keys->val[i].set_time != NULL &&
+ (*hist_keys->val[i].set_time) < (now - (*ent->max_life))) ||
+ (hist_keys->val[i].kvno < kvno &&
+ (kvno - hist_keys->val[i].kvno) > kvno_diff)))
+ /*
+ * The KDC may want to to check for this keyset's set_time
+ * is within the TGS principal's max_life, say. But we stop
+ * here.
+ */
+ continue;
+
+ /* Either the keys we want, or all the keys */
+ for (k = 0; k < hist_keys->val[i].keys.len; k++) {
+ ret = hdb_unseal_key_mkey(context,
+ &hist_keys->val[i].keys.val[k],
+ db->hdb_master_key);
+ /*
+ * If kvno == 0 we might not want to bail here! E.g., if we
+ * no longer have the right master key, so just ignore this.
+ *
+ * We could filter out keys that we can't decrypt here
+ * because of HDB_ERR_NO_MKEY. However, it seems safest to
+ * filter them out only where necessary, say, in kadm5.
+ */
+ if (ret && kvno != 0)
+ return ret;
+ if (ret && ret != HDB_ERR_NO_MKEY)
+ return (ret);
+ }
+
+ if (kvno == 0)
+ continue;
+
+ /*
+ * What follows is a bit of a hack.
+ *
+ * This is the keyset we're being asked for, but it's not the
+ * current keyset. So we add the current keyset to the history,
+ * leave the one we were asked for in the history, and pretend
+ * the one we were asked for is also the current keyset.
+ *
+ * This is a bit of a defensive hack in case an entry fetched
+ * this way ever gets modified then stored: if the keyset is not
+ * changed we can detect this and put things back, else we won't
+ * drop any keysets from history by accident.
+ *
+ * Note too that we only ever get called with a non-zero kvno
+ * either in the KDC or in cases where we aren't changing the
+ * HDB entry anyways, which is why this is just a defensive
+ * hack. We also don't fetch specific kvnos in the dump case,
+ * so there's no danger that we'll dump this entry and load it
+ * again, repeatedly causing the history to grow boundelessly.
+ */
+
+ /* Swap key sets */
+ ent->kvno = hist_keys->val[i].kvno;
+ ent->keys.val = hist_keys->val[i].keys.val;
+ ent->keys.len = hist_keys->val[i].keys.len;
+ if (hist_keys->val[i].set_time != NULL)
+ /* Sloppy, but the callers we expect won't care */
+ (void) hdb_entry_set_pw_change_time(context, ent,
+ *hist_keys->val[i].set_time);
+ hist_keys->val[i].kvno = tmp_kvno;
+ hist_keys->val[i].keys.val = tmp_val;
+ hist_keys->val[i].keys.len = tmp_len;
+ if (hist_keys->val[i].set_time != NULL)
+ /* Sloppy, but the callers we expect won't care */
+ *hist_keys->val[i].set_time = tmp_set_time;
+
+ return 0;
+ }
+
+ return (ret);
+}
+
+krb5_error_code
+hdb_unseal_key(krb5_context context, HDB *db, Key *k)
+{
+ if (db->hdb_master_key_set == 0)
+ return 0;
+ return hdb_unseal_key_mkey(context, k, db->hdb_master_key);
+}
+
+krb5_error_code
+hdb_seal_key_mkey(krb5_context context, Key *k, hdb_master_key mkey)
+{
+ krb5_error_code ret;
+ krb5_data res;
+ hdb_master_key key;
+
+ if(k->mkvno != NULL)
+ return 0;
+
+ key = _hdb_find_master_key(k->mkvno, mkey);
+
+ if (key == NULL)
+ return HDB_ERR_NO_MKEY;
+
+ ret = _hdb_mkey_encrypt(context, key, HDB_KU_MKEY,
+ k->key.keyvalue.data,
+ k->key.keyvalue.length,
+ &res);
+ if (ret)
+ return ret;
+
+ memset(k->key.keyvalue.data, 0, k->key.keyvalue.length);
+ free(k->key.keyvalue.data);
+ k->key.keyvalue = res;
+
+ if (k->mkvno == NULL) {
+ k->mkvno = malloc(sizeof(*k->mkvno));
+ if (k->mkvno == NULL)
+ return ENOMEM;
+ }
+ *k->mkvno = key->keytab.vno;
+
+ return 0;
+}
+
+krb5_error_code
+hdb_seal_keys_mkey(krb5_context context, hdb_entry *ent, hdb_master_key mkey)
+{
+ HDB_extension *ext;
+ HDB_Ext_KeySet *hist_keys;
+ size_t i, k;
+ krb5_error_code ret;
+
+ for(i = 0; i < ent->keys.len; i++){
+ ret = hdb_seal_key_mkey(context, &ent->keys.val[i], mkey);
+ if (ret)
+ return ret;
+ }
+
+ ext = hdb_find_extension(ent, choice_HDB_extension_data_hist_keys);
+ if (ext == NULL)
+ return 0;
+ hist_keys = &ext->data.u.hist_keys;
+
+ for (i = 0; i < hist_keys->len; i++) {
+ for (k = 0; k < hist_keys->val[i].keys.len; k++) {
+ ret = hdb_seal_key_mkey(context, &hist_keys->val[i].keys.val[k],
+ mkey);
+ if (ret)
+ return ret;
+ }
+ }
+
+ return 0;
+}
+
+krb5_error_code
+hdb_seal_keys(krb5_context context, HDB *db, hdb_entry *ent)
+{
+ if (db->hdb_master_key_set == 0)
+ return 0;
+
+ return hdb_seal_keys_mkey(context, ent, db->hdb_master_key);
+}
+
+krb5_error_code
+hdb_seal_key(krb5_context context, HDB *db, Key *k)
+{
+ if (db->hdb_master_key_set == 0)
+ return 0;
+
+ return hdb_seal_key_mkey(context, k, db->hdb_master_key);
+}
+
+krb5_error_code
+hdb_set_master_key(krb5_context context,
+ HDB *db,
+ krb5_keyblock *key)
+{
+ krb5_error_code ret;
+ hdb_master_key mkey;
+
+ ret = hdb_process_master_key(context, 0, key, 0, &mkey);
+ if (ret)
+ return ret;
+ db->hdb_master_key = mkey;
+#if 0 /* XXX - why? */
+ des_set_random_generator_seed(key.keyvalue.data);
+#endif
+ db->hdb_master_key_set = 1;
+ db->hdb_master_key->key_usage = HDB_KU_MKEY;
+ return 0;
+}
+
+krb5_error_code
+hdb_set_master_keyfile (krb5_context context,
+ HDB *db,
+ const char *keyfile)
+{
+ hdb_master_key key;
+ krb5_error_code ret;
+
+ ret = hdb_read_master_key(context, keyfile, &key);
+ if (ret) {
+ if (ret != ENOENT)
+ return ret;
+ krb5_clear_error_message(context);
+ return 0;
+ }
+ db->hdb_master_key = key;
+ db->hdb_master_key_set = 1;
+ return ret;
+}
+
+krb5_error_code
+hdb_clear_master_key (krb5_context context,
+ HDB *db)
+{
+ if (db->hdb_master_key_set) {
+ hdb_free_master_key(context, db->hdb_master_key);
+ db->hdb_master_key_set = 0;
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hdb/ndbm.c b/third_party/heimdal/lib/hdb/ndbm.c
new file mode 100644
index 0000000..52c52c8
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/ndbm.c
@@ -0,0 +1,406 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hdb_locl.h"
+
+#if HAVE_NDBM
+
+#if defined(HAVE_GDBM_NDBM_H)
+#include <gdbm/ndbm.h>
+#define WRITE_SUPPORT 1
+#elif defined(HAVE_NDBM_H)
+#include <ndbm.h>
+#elif defined(HAVE_DBM_H)
+#define WRITE_SUPPORT 1
+#include <dbm.h>
+#endif
+
+struct ndbm_db {
+ DBM *db;
+ int lock_fd;
+};
+
+static krb5_error_code
+NDBM_destroy(krb5_context context, HDB *db)
+{
+ hdb_clear_master_key(context, db);
+ krb5_config_free_strings(db->virtual_hostbased_princ_svcs);
+ free(db->hdb_name);
+ free(db);
+ return 0;
+}
+
+static krb5_error_code
+NDBM_lock(krb5_context context, HDB *db, int operation)
+{
+ struct ndbm_db *d = db->hdb_db;
+ return hdb_lock(d->lock_fd, operation);
+}
+
+static krb5_error_code
+NDBM_unlock(krb5_context context, HDB *db)
+{
+ struct ndbm_db *d = db->hdb_db;
+ return hdb_unlock(d->lock_fd);
+}
+
+static krb5_error_code
+NDBM_seq(krb5_context context, HDB *db,
+ unsigned flags, hdb_entry *entry, int first)
+
+{
+ struct ndbm_db *d = (struct ndbm_db *)db->hdb_db;
+ datum key, value;
+ krb5_data key_data, data;
+ krb5_error_code ret = 0;
+
+ if(first)
+ key = dbm_firstkey(d->db);
+ else
+ key = dbm_nextkey(d->db);
+ if(key.dptr == NULL)
+ return HDB_ERR_NOENTRY;
+ key_data.data = key.dptr;
+ key_data.length = key.dsize;
+ ret = db->hdb_lock(context, db, HDB_RLOCK);
+ if(ret) return ret;
+ value = dbm_fetch(d->db, key);
+ db->hdb_unlock(context, db);
+ data.data = value.dptr;
+ data.length = value.dsize;
+ memset(entry, 0, sizeof(*entry));
+ if(hdb_value2entry(context, &data, entry))
+ return NDBM_seq(context, db, flags, entry, 0);
+ if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) {
+ ret = hdb_unseal_keys (context, db, entry);
+ if (ret)
+ hdb_free_entry (context, db, entry);
+ }
+ if (ret == 0 && entry->principal == NULL) {
+ entry->principal = malloc (sizeof(*entry->principal));
+ if (entry->principal == NULL) {
+ hdb_free_entry (context, db, entry);
+ ret = ENOMEM;
+ krb5_set_error_message(context, ret, "malloc: out of memory");
+ } else {
+ hdb_key2principal (context, &key_data, entry->principal);
+ }
+ }
+ return ret;
+}
+
+
+static krb5_error_code
+NDBM_firstkey(krb5_context context, HDB *db,unsigned flags,hdb_entry *entry)
+{
+ return NDBM_seq(context, db, flags, entry, 1);
+}
+
+
+static krb5_error_code
+NDBM_nextkey(krb5_context context, HDB *db, unsigned flags,hdb_entry *entry)
+{
+ return NDBM_seq(context, db, flags, entry, 0);
+}
+
+static krb5_error_code
+open_lock_file(krb5_context context, const char *db_name, int *fd)
+{
+ char *lock_file;
+ int ret = 0;
+
+ /* lock old and new databases */
+ if (asprintf(&lock_file, "%s.lock", db_name) == -1) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ *fd = open(lock_file, O_RDWR | O_CREAT, 0600);
+ if(*fd < 0) {
+ ret = errno;
+ krb5_set_error_message(context, ret, "open(%s): %s", lock_file,
+ strerror(ret));
+ }
+ free(lock_file);
+ return ret;
+}
+
+
+static krb5_error_code
+NDBM_rename(krb5_context context, HDB *db, const char *new_name)
+{
+ int ret;
+ char *old_dir = NULL, *old_pag = NULL;
+ char *new_dir = NULL, *new_pag = NULL;
+ int old_lock_fd, new_lock_fd;
+
+ /* lock old and new databases */
+ ret = open_lock_file(context, db->hdb_name, &old_lock_fd);
+ if (ret)
+ return ret;
+
+ ret = hdb_lock(old_lock_fd, HDB_WLOCK);
+ if(ret) {
+ close(old_lock_fd);
+ return ret;
+ }
+
+ ret = open_lock_file(context, new_name, &new_lock_fd);
+ if (ret) {
+ hdb_unlock(old_lock_fd);
+ close(old_lock_fd);
+ return ret;
+ }
+
+ ret = hdb_lock(new_lock_fd, HDB_WLOCK);
+ if(ret) {
+ hdb_unlock(old_lock_fd);
+ close(old_lock_fd);
+ close(new_lock_fd);
+ return ret;
+ }
+
+ if (asprintf(&old_dir, "%s.dir", db->hdb_name) == -1) {
+ old_dir = NULL;
+ ret = ENOMEM;
+ goto out;
+ }
+ if (asprintf(&old_pag, "%s.pag", db->hdb_name) == -1) {
+ old_pag = NULL;
+ ret = ENOMEM;
+ goto out;
+ }
+ if (asprintf(&new_dir, "%s.dir", new_name) == -1) {
+ new_dir = NULL;
+ ret = ENOMEM;
+ goto out;
+ }
+ if (asprintf(&new_pag, "%s.pag", new_name) == -1) {
+ new_pag = NULL;
+ ret = ENOMEM;
+ goto out;
+ }
+
+ ret = rename(old_dir, new_dir) || rename(old_pag, new_pag);
+ if (ret) {
+ ret = errno;
+ if (ret == 0)
+ ret = EPERM;
+ krb5_set_error_message(context, ret, "rename: %s", strerror(ret));
+ }
+
+ out:
+ free(old_dir);
+ free(old_pag);
+ free(new_dir);
+ free(new_pag);
+
+ hdb_unlock(new_lock_fd);
+ hdb_unlock(old_lock_fd);
+ close(new_lock_fd);
+ close(old_lock_fd);
+
+ if(ret)
+ return ret;
+
+ free(db->hdb_name);
+ db->hdb_name = strdup(new_name);
+ return 0;
+}
+
+static krb5_error_code
+NDBM__get(krb5_context context, HDB *db, krb5_data key, krb5_data *reply)
+{
+ struct ndbm_db *d = (struct ndbm_db *)db->hdb_db;
+ datum k, v;
+ int code;
+
+ k.dptr = key.data;
+ k.dsize = key.length;
+ code = db->hdb_lock(context, db, HDB_RLOCK);
+ if(code)
+ return code;
+ v = dbm_fetch(d->db, k);
+ db->hdb_unlock(context, db);
+ if(v.dptr == NULL)
+ return HDB_ERR_NOENTRY;
+
+ krb5_data_copy(reply, v.dptr, v.dsize);
+ return 0;
+}
+
+static krb5_error_code
+NDBM__put(krb5_context context, HDB *db, int replace,
+ krb5_data key, krb5_data value)
+{
+#ifdef WRITE_SUPPORT
+ struct ndbm_db *d = (struct ndbm_db *)db->hdb_db;
+ datum k, v;
+ int code;
+
+ k.dptr = key.data;
+ k.dsize = key.length;
+ v.dptr = value.data;
+ v.dsize = value.length;
+
+ code = db->hdb_lock(context, db, HDB_WLOCK);
+ if(code)
+ return code;
+ code = dbm_store(d->db, k, v, replace ? DBM_REPLACE : DBM_INSERT);
+ db->hdb_unlock(context, db);
+ if(code == 1)
+ return HDB_ERR_EXISTS;
+ if (code < 0)
+ return code;
+ return 0;
+#else
+ return HDB_ERR_NO_WRITE_SUPPORT;
+#endif
+}
+
+static krb5_error_code
+NDBM__del(krb5_context context, HDB *db, krb5_data key)
+{
+ struct ndbm_db *d = (struct ndbm_db *)db->hdb_db;
+ datum k;
+ int code;
+ krb5_error_code ret;
+
+ k.dptr = key.data;
+ k.dsize = key.length;
+ ret = db->hdb_lock(context, db, HDB_WLOCK);
+ if(ret) return ret;
+ code = dbm_delete(d->db, k);
+ db->hdb_unlock(context, db);
+ if(code < 0)
+ return errno;
+ return 0;
+}
+
+
+static krb5_error_code
+NDBM_close(krb5_context context, HDB *db)
+{
+ struct ndbm_db *d = db->hdb_db;
+ dbm_close(d->db);
+ close(d->lock_fd);
+ free(d);
+ return 0;
+}
+
+static krb5_error_code
+NDBM_open(krb5_context context, HDB *db, int flags, mode_t mode)
+{
+ krb5_error_code ret;
+ struct ndbm_db *d = malloc(sizeof(*d));
+
+ if(d == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ d->db = dbm_open((char*)db->hdb_name, flags, mode);
+ if(d->db == NULL){
+ ret = errno;
+ free(d);
+ krb5_set_error_message(context, ret, "dbm_open(%s): %s", db->hdb_name,
+ strerror(ret));
+ return ret;
+ }
+
+ ret = open_lock_file(context, db->hdb_name, &d->lock_fd);
+ if (ret) {
+ ret = errno;
+ dbm_close(d->db);
+ free(d);
+ krb5_set_error_message(context, ret, "open(lock file): %s",
+ strerror(ret));
+ return ret;
+ }
+
+ db->hdb_db = d;
+ if((flags & O_ACCMODE) == O_RDONLY)
+ ret = hdb_check_db_format(context, db);
+ else
+ ret = hdb_init_db(context, db);
+ if(ret == HDB_ERR_NOENTRY)
+ return 0;
+ if (ret) {
+ NDBM_close(context, db);
+ krb5_set_error_message(context, ret, "hdb_open: failed %s database %s",
+ (flags & O_ACCMODE) == O_RDONLY ?
+ "checking format of" : "initialize",
+ db->hdb_name);
+ }
+ return ret;
+}
+
+krb5_error_code
+hdb_ndbm_create(krb5_context context, HDB **db,
+ const char *filename)
+{
+ *db = calloc(1, sizeof(**db));
+ if (*db == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ (*db)->hdb_db = NULL;
+ (*db)->hdb_name = strdup(filename);
+ if ((*db)->hdb_name == NULL) {
+ free(*db);
+ *db = NULL;
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+ (*db)->hdb_master_key_set = 0;
+ (*db)->hdb_openp = 0;
+ (*db)->hdb_capability_flags = HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL;
+ (*db)->hdb_open = NDBM_open;
+ (*db)->hdb_close = NDBM_close;
+ (*db)->hdb_fetch_kvno = _hdb_fetch_kvno;
+ (*db)->hdb_store = _hdb_store;
+ (*db)->hdb_remove = _hdb_remove;
+ (*db)->hdb_firstkey = NDBM_firstkey;
+ (*db)->hdb_nextkey= NDBM_nextkey;
+ (*db)->hdb_lock = NDBM_lock;
+ (*db)->hdb_unlock = NDBM_unlock;
+ (*db)->hdb_rename = NDBM_rename;
+ (*db)->hdb__get = NDBM__get;
+ (*db)->hdb__put = NDBM__put;
+ (*db)->hdb__del = NDBM__del;
+ (*db)->hdb_destroy = NDBM_destroy;
+ return 0;
+}
+
+#endif /* HAVE_NDBM */
diff --git a/third_party/heimdal/lib/hdb/print.c b/third_party/heimdal/lib/hdb/print.c
new file mode 100644
index 0000000..7f25358
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/print.c
@@ -0,0 +1,597 @@
+/*
+ * Copyright (c) 1999-2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "hdb_locl.h"
+#include <hex.h>
+#include <ctype.h>
+
+/*
+ This is the present contents of a dump line. This might change at
+ any time. Fields are separated by white space.
+
+ principal
+ keyblock
+ kvno
+ keys...
+ mkvno
+ enctype
+ keyvalue
+ salt (- means use normal salt)
+ creation date and principal
+ modification date and principal
+ principal valid from date (not used)
+ principal valid end date (not used)
+ principal key expires (not used)
+ max ticket life
+ max renewable life
+ flags
+ generation number
+ */
+
+/*
+ * These utility functions return the number of bytes written or -1, and
+ * they set an error in the context.
+ */
+static ssize_t
+append_string(krb5_context context, krb5_storage *sp, const char *fmt, ...)
+{
+ ssize_t sz;
+ char *s;
+ int rc;
+ va_list ap;
+ va_start(ap, fmt);
+ rc = vasprintf(&s, fmt, ap);
+ va_end(ap);
+ if(rc < 0) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return -1;
+ }
+ sz = krb5_storage_write(sp, s, strlen(s));
+ free(s);
+ return sz;
+}
+
+static krb5_error_code
+append_hex(krb5_context context, krb5_storage *sp,
+ int always_encode, int lower, krb5_data *data)
+{
+ ssize_t sz;
+ int printable = 1;
+ size_t i;
+ char *p;
+
+ p = data->data;
+ if (!always_encode) {
+ for (i = 0; i < data->length; i++) {
+ if (!isalnum((unsigned char)p[i]) && p[i] != '.'){
+ printable = 0;
+ break;
+ }
+ }
+ }
+ if (printable && !always_encode)
+ return append_string(context, sp, "\"%.*s\"",
+ data->length, data->data);
+ sz = hex_encode(data->data, data->length, &p);
+ if (sz == -1) return sz;
+ if (lower)
+ strlwr(p);
+ sz = append_string(context, sp, "%s", p);
+ free(p);
+ return sz;
+}
+
+static char *
+time2str(time_t t)
+{
+ static char buf[128];
+ strftime(buf, sizeof(buf), "%Y%m%d%H%M%S", gmtime(&t));
+ return buf;
+}
+
+static ssize_t
+append_event(krb5_context context, krb5_storage *sp, Event *ev)
+{
+ krb5_error_code ret;
+ ssize_t sz;
+ char *pr = NULL;
+ if(ev == NULL)
+ return append_string(context, sp, "- ");
+ if (ev->principal != NULL) {
+ ret = krb5_unparse_name(context, ev->principal, &pr);
+ if (ret) return -1; /* krb5_unparse_name() sets error info */
+ }
+ sz = append_string(context, sp, "%s:%s ", time2str(ev->time),
+ pr ? pr : "UNKNOWN");
+ free(pr);
+ return sz;
+}
+
+#define KRB5_KDB_SALTTYPE_NORMAL 0
+#define KRB5_KDB_SALTTYPE_V4 1
+#define KRB5_KDB_SALTTYPE_NOREALM 2
+#define KRB5_KDB_SALTTYPE_ONLYREALM 3
+#define KRB5_KDB_SALTTYPE_SPECIAL 4
+#define KRB5_KDB_SALTTYPE_AFS3 5
+
+static ssize_t
+append_mit_key(krb5_context context, krb5_storage *sp,
+ krb5_const_principal princ,
+ unsigned int kvno, Key *key)
+{
+ krb5_error_code ret;
+ krb5_salt k5salt;
+ ssize_t sz;
+ size_t key_versions = key->salt ? 2 : 1;
+ size_t decrypted_key_length;
+ char buf[2];
+ krb5_data keylenbytes;
+ unsigned int salttype;
+
+ sz = append_string(context, sp, "\t%u\t%u\t%d\t%d\t", key_versions, kvno,
+ key->key.keytype, key->key.keyvalue.length + 2);
+ if (sz == -1) return sz;
+ ret = krb5_enctype_keysize(context, key->key.keytype, &decrypted_key_length);
+ if (ret) return -1; /* XXX we lose the error code */
+ buf[0] = decrypted_key_length & 0xff;
+ buf[1] = (decrypted_key_length & 0xff00) >> 8;
+ keylenbytes.data = buf;
+ keylenbytes.length = sizeof (buf);
+ sz = append_hex(context, sp, 1, 1, &keylenbytes);
+ if (sz == -1) return sz;
+ sz = append_hex(context, sp, 1, 1, &key->key.keyvalue);
+ if (!key->salt)
+ return sz;
+
+ /* Map salt to MIT KDB style */
+ switch (key->salt->type) {
+ case KRB5_PADATA_PW_SALT:
+
+ /*
+ * Compute normal salt and then see whether it matches the stored one
+ */
+ ret = krb5_get_pw_salt(context, princ, &k5salt);
+ if (ret) return -1;
+ if (k5salt.saltvalue.length == key->salt->salt.length &&
+ memcmp(k5salt.saltvalue.data, key->salt->salt.data,
+ k5salt.saltvalue.length) == 0)
+ salttype = KRB5_KDB_SALTTYPE_NORMAL; /* matches */
+ else if (key->salt->salt.length == strlen(princ->realm) &&
+ memcmp(key->salt->salt.data, princ->realm,
+ key->salt->salt.length) == 0)
+ salttype = KRB5_KDB_SALTTYPE_ONLYREALM; /* matches realm */
+ else if (key->salt->salt.length ==
+ k5salt.saltvalue.length - strlen(princ->realm) &&
+ memcmp((char *)k5salt.saltvalue.data + strlen(princ->realm),
+ key->salt->salt.data, key->salt->salt.length) == 0)
+ salttype = KRB5_KDB_SALTTYPE_NOREALM; /* matches w/o realm */
+ else
+ salttype = KRB5_KDB_SALTTYPE_NORMAL; /* hope for best */
+
+ break;
+
+ case KRB5_PADATA_AFS3_SALT:
+ salttype = KRB5_KDB_SALTTYPE_AFS3;
+ break;
+
+ default:
+ return -1;
+ }
+
+ sz = append_string(context, sp, "\t%u\t%u\t", salttype,
+ key->salt->salt.length);
+ if (sz == -1) return sz;
+ return append_hex(context, sp, 1, 1, &key->salt->salt);
+}
+
+static krb5_error_code
+entry2string_int (krb5_context context, krb5_storage *sp, hdb_entry *ent)
+{
+ char *p;
+ size_t i;
+ krb5_error_code ret;
+
+ /* --- principal */
+ ret = krb5_unparse_name(context, ent->principal, &p);
+ if(ret)
+ return ret;
+ append_string(context, sp, "%s ", p);
+ free(p);
+ /* --- kvno */
+ append_string(context, sp, "%d", ent->kvno);
+ /* --- keys */
+ for(i = 0; i < ent->keys.len; i++){
+ /* --- mkvno, keytype */
+ if(ent->keys.val[i].mkvno)
+ append_string(context, sp, ":%d:%d:",
+ *ent->keys.val[i].mkvno,
+ ent->keys.val[i].key.keytype);
+ else
+ append_string(context, sp, "::%d:",
+ ent->keys.val[i].key.keytype);
+ /* --- keydata */
+ append_hex(context, sp, 0, 0, &ent->keys.val[i].key.keyvalue);
+ append_string(context, sp, ":");
+ /* --- salt */
+ if(ent->keys.val[i].salt){
+ append_string(context, sp, "%u/", ent->keys.val[i].salt->type);
+ append_hex(context, sp, 0, 0, &ent->keys.val[i].salt->salt);
+ }else
+ append_string(context, sp, "-");
+ }
+ append_string(context, sp, " ");
+ /* --- created by */
+ append_event(context, sp, &ent->created_by);
+ /* --- modified by */
+ append_event(context, sp, ent->modified_by);
+
+ /* --- valid start */
+ if(ent->valid_start)
+ append_string(context, sp, "%s ", time2str(*ent->valid_start));
+ else
+ append_string(context, sp, "- ");
+
+ /* --- valid end */
+ if(ent->valid_end)
+ append_string(context, sp, "%s ", time2str(*ent->valid_end));
+ else
+ append_string(context, sp, "- ");
+
+ /* --- password ends */
+ if(ent->pw_end)
+ append_string(context, sp, "%s ", time2str(*ent->pw_end));
+ else
+ append_string(context, sp, "- ");
+
+ /* --- max life */
+ if(ent->max_life)
+ append_string(context, sp, "%d ", *ent->max_life);
+ else
+ append_string(context, sp, "- ");
+
+ /* --- max renewable life */
+ if(ent->max_renew)
+ append_string(context, sp, "%d ", *ent->max_renew);
+ else
+ append_string(context, sp, "- ");
+
+ /* --- flags */
+ append_string(context, sp, "%d ", HDBFlags2int(ent->flags));
+
+ /* --- generation number */
+ if(ent->generation) {
+ append_string(context, sp, "%s:%d:%d ", time2str(ent->generation->time),
+ ent->generation->usec,
+ ent->generation->gen);
+ } else
+ append_string(context, sp, "- ");
+
+ /* --- extensions */
+ if(ent->extensions && ent->extensions->len > 0) {
+ for(i = 0; i < ent->extensions->len; i++) {
+ void *d;
+ size_t size, sz = 0;
+
+ ASN1_MALLOC_ENCODE(HDB_extension, d, size,
+ &ent->extensions->val[i], &sz, ret);
+ if (ret) {
+ krb5_clear_error_message(context);
+ return ret;
+ }
+ if(size != sz)
+ krb5_abortx(context, "internal asn.1 encoder error");
+
+ if (hex_encode(d, size, &p) < 0) {
+ free(d);
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ free(d);
+ append_string(context, sp, "%s%s", p,
+ ent->extensions->len - 1 != i ? ":" : "");
+ free(p);
+ }
+ } else
+ append_string(context, sp, "-");
+
+ return 0;
+}
+
+#define KRB5_KDB_DISALLOW_POSTDATED 0x00000001
+#define KRB5_KDB_DISALLOW_FORWARDABLE 0x00000002
+#define KRB5_KDB_DISALLOW_TGT_BASED 0x00000004
+#define KRB5_KDB_DISALLOW_RENEWABLE 0x00000008
+#define KRB5_KDB_DISALLOW_PROXIABLE 0x00000010
+#define KRB5_KDB_DISALLOW_DUP_SKEY 0x00000020
+#define KRB5_KDB_DISALLOW_ALL_TIX 0x00000040
+#define KRB5_KDB_REQUIRES_PRE_AUTH 0x00000080
+#define KRB5_KDB_REQUIRES_HW_AUTH 0x00000100
+#define KRB5_KDB_REQUIRES_PWCHANGE 0x00000200
+#define KRB5_KDB_DISALLOW_SVR 0x00001000
+#define KRB5_KDB_PWCHANGE_SERVICE 0x00002000
+#define KRB5_KDB_SUPPORT_DESMD5 0x00004000
+#define KRB5_KDB_NEW_PRINC 0x00008000
+
+static int
+flags_to_attr(HDBFlags flags)
+{
+ int a = 0;
+
+ if (!flags.postdate)
+ a |= KRB5_KDB_DISALLOW_POSTDATED;
+ if (!flags.forwardable)
+ a |= KRB5_KDB_DISALLOW_FORWARDABLE;
+ if (flags.initial)
+ a |= KRB5_KDB_DISALLOW_TGT_BASED;
+ if (!flags.renewable)
+ a |= KRB5_KDB_DISALLOW_RENEWABLE;
+ if (!flags.proxiable)
+ a |= KRB5_KDB_DISALLOW_PROXIABLE;
+ if (flags.invalid)
+ a |= KRB5_KDB_DISALLOW_ALL_TIX;
+ if (flags.require_preauth)
+ a |= KRB5_KDB_REQUIRES_PRE_AUTH;
+ if (flags.require_hwauth)
+ a |= KRB5_KDB_REQUIRES_HW_AUTH;
+ if (!flags.server)
+ a |= KRB5_KDB_DISALLOW_SVR;
+ if (flags.change_pw)
+ a |= KRB5_KDB_PWCHANGE_SERVICE;
+ return a;
+}
+
+krb5_error_code
+entry2mit_string_int(krb5_context context, krb5_storage *sp, hdb_entry *ent)
+{
+ krb5_error_code ret;
+ ssize_t sz;
+ size_t i, k;
+ size_t num_tl_data = 0;
+ size_t num_key_data = 0;
+ char *p;
+ HDB_Ext_KeySet *hist_keys = NULL;
+ HDB_extension *extp;
+ time_t last_pw_chg = 0;
+ time_t exp = 0;
+ time_t pwexp = 0;
+ unsigned int max_life = 0;
+ unsigned int max_renew = 0;
+
+ if (ent->modified_by)
+ num_tl_data++;
+
+ ret = hdb_entry_get_pw_change_time(ent, &last_pw_chg);
+ if (ret) return ret;
+ if (last_pw_chg)
+ num_tl_data++;
+
+ extp = hdb_find_extension(ent, choice_HDB_extension_data_hist_keys);
+ if (extp)
+ hist_keys = &extp->data.u.hist_keys;
+
+ for (i = 0; i < ent->keys.len;i++) {
+ if (ent->keys.val[i].key.keytype == ETYPE_DES_CBC_MD4 ||
+ ent->keys.val[i].key.keytype == ETYPE_DES_CBC_MD5)
+ continue;
+ num_key_data++;
+ }
+ if (hist_keys) {
+ for (i = 0; i < hist_keys->len; i++) {
+ /*
+ * MIT uses the highest kvno as the current kvno instead of
+ * tracking kvno separately, so we can't dump keysets with kvno
+ * higher than the entry's kvno.
+ */
+ if (hist_keys->val[i].kvno >= ent->kvno)
+ continue;
+ for (k = 0; k < hist_keys->val[i].keys.len; k++) {
+ if (ent->keys.val[k].key.keytype == ETYPE_DES_CBC_MD4 ||
+ ent->keys.val[k].key.keytype == ETYPE_DES_CBC_MD5)
+ continue;
+ num_key_data++;
+ }
+ }
+ }
+
+ ret = krb5_unparse_name(context, ent->principal, &p);
+ if (ret) return ret;
+ sz = append_string(context, sp, "princ\t38\t%u\t%u\t%u\t0\t%s\t%d",
+ strlen(p), num_tl_data, num_key_data, p,
+ flags_to_attr(ent->flags));
+ free(p);
+ if (sz == -1) return ENOMEM;
+
+ if (ent->max_life)
+ max_life = *ent->max_life;
+ if (ent->max_renew)
+ max_renew = *ent->max_renew;
+ if (ent->valid_end)
+ exp = *ent->valid_end;
+ if (ent->pw_end)
+ pwexp = *ent->pw_end;
+
+ sz = append_string(context, sp, "\t%u\t%u\t%u\t%u\t0\t0\t0",
+ max_life, max_renew, exp, pwexp);
+ if (sz == -1) return ENOMEM;
+
+ /* Dump TL data we know: last pw chg and modified_by */
+#define mit_KRB5_TL_LAST_PWD_CHANGE 1
+#define mit_KRB5_TL_MOD_PRINC 2
+ if (last_pw_chg) {
+ krb5_data d;
+ time_t val;
+ unsigned char *ptr;
+
+ ptr = (unsigned char *)&last_pw_chg;
+ val = ((unsigned long)ptr[3] << 24) | (ptr[2] << 16)
+ | (ptr[1] << 8) | ptr[0];
+ d.data = &val;
+ d.length = sizeof (last_pw_chg);
+ sz = append_string(context, sp, "\t%u\t%u\t",
+ mit_KRB5_TL_LAST_PWD_CHANGE, d.length);
+ if (sz == -1) return ENOMEM;
+ sz = append_hex(context, sp, 1, 1, &d);
+ if (sz == -1) return ENOMEM;
+ }
+ if (ent->modified_by) {
+ krb5_data d;
+ unsigned int val;
+ size_t plen;
+ unsigned char *ptr;
+ char *modby_p;
+
+ ptr = (unsigned char *)&ent->modified_by->time;
+ val = ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (ptr[3] << 24);
+ d.data = &val;
+ d.length = sizeof (ent->modified_by->time);
+ ret = krb5_unparse_name(context, ent->modified_by->principal, &modby_p);
+ if (ret)
+ return ret;
+ plen = strlen(modby_p);
+ sz = append_string(context, sp, "\t%u\t%u\t",
+ mit_KRB5_TL_MOD_PRINC,
+ d.length + plen + 1 /* NULL counted */);
+ if (sz == -1) {
+ free(modby_p);
+ return ENOMEM;
+ }
+ sz = append_hex(context, sp, 1, 1, &d);
+ if (sz == -1) {
+ free(modby_p);
+ return ENOMEM;
+ }
+ d.data = modby_p;
+ d.length = plen + 1;
+ sz = append_hex(context, sp, 1, 1, &d);
+ free(modby_p);
+ if (sz == -1)
+ return ENOMEM;
+ }
+ /*
+ * Dump keys (remembering to not include any with kvno higher than
+ * the entry's because MIT doesn't track entry kvno separately from
+ * the entry's keys -- max kvno is it)
+ */
+ for (i = 0; i < ent->keys.len; i++) {
+ if (ent->keys.val[i].key.keytype == ETYPE_DES_CBC_MD4 ||
+ ent->keys.val[i].key.keytype == ETYPE_DES_CBC_MD5)
+ continue;
+ sz = append_mit_key(context, sp, ent->principal, ent->kvno,
+ &ent->keys.val[i]);
+ if (sz == -1) return ENOMEM;
+ }
+ for (i = 0; hist_keys && i < ent->kvno; i++) {
+ size_t m;
+
+ /* dump historical keys */
+ for (k = 0; k < hist_keys->len; k++) {
+ if (hist_keys->val[k].kvno != ent->kvno - i)
+ continue;
+ for (m = 0; m < hist_keys->val[k].keys.len; m++) {
+ if (ent->keys.val[k].key.keytype == ETYPE_DES_CBC_MD4 ||
+ ent->keys.val[k].key.keytype == ETYPE_DES_CBC_MD5)
+ continue;
+ sz = append_mit_key(context, sp, ent->principal,
+ hist_keys->val[k].kvno,
+ &hist_keys->val[k].keys.val[m]);
+ if (sz == -1) return ENOMEM;
+ }
+ }
+ }
+ sz = append_string(context, sp, "\t-1;"); /* "extra data" */
+ if (sz == -1) return ENOMEM;
+ return 0;
+}
+
+krb5_error_code
+hdb_entry2string(krb5_context context, hdb_entry *ent, char **str)
+{
+ krb5_error_code ret;
+ krb5_data data;
+ krb5_storage *sp;
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ ret = entry2string_int(context, sp, ent);
+ if (ret) {
+ krb5_storage_free(sp);
+ return ret;
+ }
+
+ krb5_storage_write(sp, "\0", 1);
+ krb5_storage_to_data(sp, &data);
+ krb5_storage_free(sp);
+ *str = data.data;
+ return 0;
+}
+
+/* print a hdb_entry to (FILE*)data; suitable for hdb_foreach */
+
+krb5_error_code
+hdb_print_entry(krb5_context context, HDB *db, hdb_entry *entry,
+ void *data)
+{
+ struct hdb_print_entry_arg *parg = data;
+ krb5_error_code ret;
+ krb5_storage *sp;
+
+ fflush(parg->out);
+ sp = krb5_storage_from_fd(fileno(parg->out));
+ if (sp == NULL) {
+ krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ switch (parg->fmt) {
+ case HDB_DUMP_HEIMDAL:
+ ret = entry2string_int(context, sp, entry);
+ break;
+ case HDB_DUMP_MIT:
+ ret = entry2mit_string_int(context, sp, entry);
+ break;
+ default:
+ heim_abort("Only two dump formats supported: Heimdal and MIT");
+ }
+ if (ret) {
+ krb5_storage_free(sp);
+ return ret;
+ }
+
+ krb5_storage_write(sp, "\n", 1);
+ krb5_storage_free(sp);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hdb/test_concurrency.c b/third_party/heimdal/lib/hdb/test_concurrency.c
new file mode 100644
index 0000000..35c01f5
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/test_concurrency.c
@@ -0,0 +1,506 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * This test tries to test reader/writer concurrency for the SQLite3 and LMDB
+ * HDB backends. We're hoping to find that one thread or process can dump the
+ * HDB while another writes -- this way backups and ipropd-master need not
+ * block write transactions when dumping a huge HDB.
+ *
+ * It has two modes: threaded, and forked.
+ *
+ * Apparently, neither LMDB nor SQLite3 give us the desired level of
+ * concurrency in threaded mode, with this test not making progress. This is
+ * surprising, at least for SQLite3, which is supposed to support N readers, 1
+ * writer and be thread-safe. LMDB also is supposed to support N readers, 1
+ * writers, but perhaps not all in one process?
+ */
+
+#include "hdb_locl.h"
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <pthread.h>
+#include <getarg.h>
+
+struct tsync {
+ pthread_mutex_t lock;
+ pthread_cond_t rcv;
+ pthread_cond_t wcv;
+ const char *hdb_name;
+ const char *fname;
+ volatile int writer_go;
+ volatile int reader_go;
+ int writer_go_pipe[2];
+ int reader_go_pipe[2];
+};
+
+static void *
+threaded_reader(void *d)
+{
+ krb5_error_code ret;
+ krb5_context context;
+ struct tsync *s = d;
+ hdb_entry entr;
+ HDB *dbr = NULL;
+
+ printf("Reader thread opening HDB\n");
+
+ if ((krb5_init_context(&context)))
+ errx(1, "krb5_init_context failed");
+
+ printf("Reader thread waiting for writer to create the HDB\n");
+ (void) pthread_mutex_lock(&s->lock);
+ s->writer_go = 1;
+ (void) pthread_cond_signal(&s->wcv);
+ while (!s->reader_go)
+ (void) pthread_cond_wait(&s->rcv, &s->lock);
+ s->reader_go = 0;
+ (void) pthread_mutex_unlock(&s->lock);
+
+ /* Open a new HDB handle to read */
+ if ((ret = hdb_create(context, &dbr, s->hdb_name))) {
+ //(void) unlink(s->fname);
+ krb5_err(context, 1, ret, "Could not get a handle for HDB %s (read)",
+ s->hdb_name);
+ }
+ if ((ret = dbr->hdb_open(context, dbr, O_RDONLY, 0))) {
+ //(void) unlink(s->fname);
+ krb5_err(context, 1, ret, "Could not open HDB %s", s->hdb_name);
+ }
+ if ((ret = dbr->hdb_firstkey(context, dbr, 0, &entr))) {
+ //(void) unlink(s->fname);
+ krb5_err(context, 1, ret, "Could not iterate HDB %s", s->hdb_name);
+ }
+ free_HDB_entry(&entr);
+
+ /* Tell the writer to go ahead and write */
+ printf("Reader thread iterated one entry; telling writer to write more\n");
+ s->writer_go = 1;
+ (void) pthread_mutex_lock(&s->lock);
+ (void) pthread_cond_signal(&s->wcv);
+
+ /* Wait for the writer to have written one more entry to the HDB */
+ printf("Reader thread waiting for writer\n");
+ while (!s->reader_go)
+ (void) pthread_cond_wait(&s->rcv, &s->lock);
+ s->reader_go = 0;
+ (void) pthread_mutex_unlock(&s->lock);
+
+ /* Iterate the rest */
+ printf("Reader thread iterating another entry\n");
+ if ((ret = dbr->hdb_nextkey(context, dbr, 0, &entr))) {
+ //(void) unlink(s->fname);
+ krb5_err(context, 1, ret,
+ "Could not iterate while writing to HDB %s", s->hdb_name);
+ }
+ printf("Reader thread iterated another entry\n");
+ free_HDB_entry(&entr);
+ if ((ret = dbr->hdb_nextkey(context, dbr, 0, &entr)) == 0) {
+ //(void) unlink(s->fname);
+ krb5_warn(context, ret,
+ "HDB %s sees writes committed since starting iteration",
+ s->hdb_name);
+ } else if (ret != HDB_ERR_NOENTRY) {
+ //(void) unlink(s->fname);
+ krb5_err(context, 1, ret,
+ "Could not iterate while writing to HDB %s (2)", s->hdb_name);
+ }
+
+ /* Tell the writer we're done */
+ printf("Reader thread telling writer to go\n");
+ s->writer_go = 1;
+ (void) pthread_cond_signal(&s->wcv);
+ (void) pthread_mutex_unlock(&s->lock);
+
+ dbr->hdb_close(context, dbr);
+ dbr->hdb_destroy(context, dbr);
+ krb5_free_context(context);
+ printf("Reader thread exiting\n");
+ return 0;
+}
+
+static void
+forked_reader(struct tsync *s)
+{
+ krb5_error_code ret;
+ krb5_context context;
+ hdb_entry entr;
+ ssize_t bytes;
+ char b[1];
+ HDB *dbr = NULL;
+
+ printf("Reader process opening HDB\n");
+
+ (void) close(s->writer_go_pipe[0]);
+ (void) close(s->reader_go_pipe[1]);
+ s->writer_go_pipe[0] = -1;
+ s->reader_go_pipe[1] = -1;
+ if ((krb5_init_context(&context)))
+ errx(1, "krb5_init_context failed");
+
+ printf("Reader process waiting for writer\n");
+ while ((bytes = read(s->reader_go_pipe[0], b, sizeof(b))) == -1 &&
+ errno == EINTR)
+ ;
+ if (bytes == -1)
+ err(1, "Could not read from reader-go pipe (error)");
+
+ /* Open a new HDB handle to read */
+ if ((ret = hdb_create(context, &dbr, s->hdb_name))) {
+ //(void) unlink(s->fname);
+ krb5_err(context, 1, ret, "Could not get a handle for HDB %s (read)",
+ s->hdb_name);
+ }
+ if ((ret = dbr->hdb_open(context, dbr, O_RDONLY, 0))) {
+ //(void) unlink(s->fname);
+ krb5_err(context, 1, ret, "Could not open HDB %s", s->hdb_name);
+ }
+ if ((ret = dbr->hdb_firstkey(context, dbr, 0, &entr))) {
+ //(void) unlink(s->fname);
+ krb5_err(context, 1, ret, "Could not iterate HDB %s", s->hdb_name);
+ }
+ printf("Reader process iterated one entry\n");
+ free_HDB_entry(&entr);
+
+ /* Tell the writer to go ahead and write */
+ printf("Reader process iterated one entry; telling writer to write more\n");
+ while ((bytes = write(s->writer_go_pipe[1], "", sizeof(""))) == -1 &&
+ errno == EINTR)
+ ;
+ if (bytes == -1)
+ err(1, "Could not write to writer-go pipe (error)");
+
+
+ /* Wait for the writer to have written one more entry to the HDB */
+ printf("Reader process waiting for writer\n");
+ while ((bytes = read(s->reader_go_pipe[0], b, sizeof(b))) == -1 &&
+ errno == EINTR)
+ ;
+ if (bytes == -1)
+ err(1, "Could not read from reader-go pipe (error)");
+ if (bytes == 0)
+ errx(1, "Could not read from reader-go pipe (EOF)");
+
+ /* Iterate the rest */
+ if ((ret = dbr->hdb_nextkey(context, dbr, 0, &entr))) {
+ //(void) unlink(s->fname);
+ krb5_err(context, 1, ret,
+ "Could not iterate while writing to HDB %s", s->hdb_name);
+ }
+ free_HDB_entry(&entr);
+ printf("Reader process iterated another entry\n");
+ if ((ret = dbr->hdb_nextkey(context, dbr, 0, &entr)) == 0) {
+ //(void) unlink(s->fname);
+ krb5_warn(context, ret,
+ "HDB %s sees writes committed since starting iteration (%s)",
+ s->hdb_name, entr.principal->name.name_string.val[0]);
+ } else if (ret != HDB_ERR_NOENTRY) {
+ //(void) unlink(s->fname);
+ krb5_err(context, 1, ret,
+ "Could not iterate while writing to HDB %s (2)", s->hdb_name);
+ }
+
+ /* Tell the writer we're done */
+ printf("Reader process done; telling writer to go\n");
+ while ((bytes = write(s->writer_go_pipe[1], "", sizeof(""))) == -1 &&
+ errno == EINTR)
+ ;
+ if (bytes == -1)
+ err(1, "Could not write to writer-go pipe (error)");
+
+ dbr->hdb_close(context, dbr);
+ dbr->hdb_destroy(context, dbr);
+ krb5_free_context(context);
+ (void) close(s->writer_go_pipe[1]);
+ (void) close(s->reader_go_pipe[0]);
+ printf("Reader process exiting\n");
+ _exit(0);
+}
+
+static krb5_error_code
+make_entry(krb5_context context, hdb_entry *entry, const char *name)
+{
+ krb5_error_code ret;
+
+ memset(entry, 0, sizeof(*entry));
+ entry->kvno = 2;
+ entry->keys.len = 0;
+ entry->keys.val = NULL;
+ entry->created_by.time = time(NULL);
+ entry->modified_by = NULL;
+ entry->valid_start = NULL;
+ entry->valid_end = NULL;
+ entry->max_life = NULL;
+ entry->max_renew = NULL;
+ entry->etypes = NULL;
+ entry->generation = NULL;
+ entry->extensions = NULL;
+ if ((ret = krb5_make_principal(context, &entry->principal,
+ "TEST.H5L.SE", name, NULL)))
+ return ret;
+ if ((ret = krb5_make_principal(context, &entry->created_by.principal,
+ "TEST.H5L.SE", "tester", NULL)))
+ return ret;
+ return 0;
+}
+
+static void
+readers_turn(struct tsync *s, pid_t child, int threaded)
+{
+ if (threaded) {
+ (void) pthread_mutex_lock(&s->lock);
+ s->reader_go = 1;
+ (void) pthread_cond_signal(&s->rcv);
+
+ while (!s->writer_go)
+ (void) pthread_cond_wait(&s->wcv, &s->lock);
+ s->writer_go = 0;
+ (void) pthread_mutex_unlock(&s->lock);
+ } else {
+ ssize_t bytes;
+ char b[1];
+
+ while ((bytes = write(s->reader_go_pipe[1], "", sizeof(""))) == -1 &&
+ errno == EINTR)
+ ;
+ if (bytes == -1) {
+ kill(child, SIGKILL);
+ err(1, "Could not write to reader-go pipe (error)");
+ }
+ if (bytes == 0) {
+ kill(child, SIGKILL);
+ err(1, "Could not write to reader-go pipe (EOF?)");
+ }
+
+ while ((bytes = read(s->writer_go_pipe[0], b, sizeof(b))) == -1 &&
+ errno == EINTR)
+ ;
+ if (bytes == -1) {
+ kill(child, SIGKILL);
+ err(1, "Could not read from writer-go pipe");
+ }
+ if (bytes == 0) {
+ kill(child, SIGKILL);
+ errx(1, "Child errored");
+ }
+ s->writer_go = 0;
+ }
+}
+
+static void
+test_hdb_concurrency(char *name, const char *ext, int threaded)
+{
+ krb5_error_code ret;
+ krb5_context context;
+ char *fname = strchr(name, ':') + 1;
+ char *fname_ext = NULL;
+ pthread_t reader_thread;
+ struct tsync ts;
+ hdb_entry entw;
+ pid_t child = getpid();
+ HDB *dbw = NULL;
+ int status;
+ int fd;
+
+ memset(&ts, 0, sizeof(ts));
+ (void) pthread_cond_init(&ts.rcv, NULL);
+ (void) pthread_cond_init(&ts.wcv, NULL);
+ (void) pthread_mutex_init(&ts.lock, NULL);
+
+ if ((krb5_init_context(&context)))
+ errx(1, "krb5_init_context failed");
+
+ /* Use mkstemp() then unlink() to avoid warnings about mktemp(); ugh */
+ if ((fd = mkstemp(fname)) == -1)
+ err(1, "mkstemp(%s)", fname);
+ (void) close(fd);
+ (void) unlink(fname);
+ if (asprintf(&fname_ext, "%s%s", fname, ext ? ext : "") == -1 ||
+ fname_ext == NULL)
+ err(1, "Out of memory");
+ ts.hdb_name = name;
+ ts.fname = fname_ext;
+
+ if (threaded) {
+ printf("Starting reader thread\n");
+ (void) pthread_mutex_lock(&ts.lock);
+ if ((errno = pthread_create(&reader_thread, NULL, threaded_reader, &ts))) {
+ (void) unlink(fname_ext);
+ krb5_err(context, 1, errno, "Could not create a thread to read HDB");
+ }
+
+ /* Wait for reader */
+ while (!ts.writer_go)
+ (void) pthread_cond_wait(&ts.wcv, &ts.lock);
+ (void) pthread_mutex_unlock(&ts.lock);
+ } else {
+ printf("Starting reader process\n");
+ if (pipe(ts.writer_go_pipe) == -1)
+ err(1, "Could not create a pipe");
+ if (pipe(ts.reader_go_pipe) == -1)
+ err(1, "Could not create a pipe");
+ switch ((child = fork())) {
+ case -1: err(1, "Could not fork a child");
+ case 0: forked_reader(&ts); _exit(0);
+ default: break;
+ }
+ (void) close(ts.writer_go_pipe[1]);
+ ts.writer_go_pipe[1] = -1;
+ }
+
+ printf("Writing two entries into HDB\n");
+ if ((ret = hdb_create(context, &dbw, name)))
+ krb5_err(context, 1, ret, "Could not get a handle for HDB %s (write)",
+ name);
+ if ((ret = dbw->hdb_open(context, dbw, O_RDWR | O_CREAT, 0600)))
+ krb5_err(context, 1, ret, "Could not create HDB %s", name);
+
+ /* Add two entries */
+ memset(&entw, 0, sizeof(entw));
+ if ((ret = make_entry(context, &entw, "foo")) ||
+ (ret = dbw->hdb_store(context, dbw, 0, &entw))) {
+ (void) unlink(fname_ext);
+ krb5_err(context, 1, ret,
+ "Could not store entry for \"foo\" in HDB %s", name);
+ }
+ free_HDB_entry(&entw);
+ if ((ret = make_entry(context, &entw, "bar")) ||
+ (ret = dbw->hdb_store(context, dbw, 0, &entw))) {
+ (void) unlink(fname_ext);
+ krb5_err(context, 1, ret,
+ "Could not store entry for \"foo\" in HDB %s", name);
+ }
+ free_HDB_entry(&entw);
+
+ /* Tell the reader to start reading */
+ readers_turn(&ts, child, threaded);
+
+ /* Store one more entry */
+ if ((ret = make_entry(context, &entw, "foobar")) ||
+ (ret = dbw->hdb_store(context, dbw, 0, &entw))) {
+ (void) unlink(fname_ext);
+ krb5_err(context, 1, ret,
+ "Could not store entry for \"foobar\" in HDB %s "
+ "while iterating it", name);
+ }
+ free_HDB_entry(&entw);
+
+ /* Tell the reader to go again */
+ readers_turn(&ts, child, threaded);
+
+ dbw->hdb_close(context, dbw);
+ dbw->hdb_destroy(context, dbw);
+ if (threaded) {
+ (void) pthread_join(reader_thread, NULL);
+ } else {
+ (void) close(ts.writer_go_pipe[1]);
+ (void) close(ts.reader_go_pipe[0]);
+ (void) close(ts.reader_go_pipe[1]);
+ while (wait(&status) == -1 && errno == EINTR)
+ ;
+ (void) close(ts.writer_go_pipe[0]);
+ if (!WIFEXITED(status))
+ errx(1, "Child reader died");
+ if (WEXITSTATUS(status) != 0)
+ errx(1, "Child reader errored");
+ }
+ (void) unlink(fname_ext);
+ krb5_free_context(context);
+}
+
+static int use_fork;
+static int use_threads;
+static int help_flag;
+static int version_flag;
+
+struct getargs args[] = {
+ { "use-fork", 'f', arg_flag, &use_fork, NULL, NULL },
+ { "use-threads", 't', arg_flag, &use_threads, NULL, NULL },
+ { "help", 'h', arg_flag, &help_flag, NULL, NULL },
+ { "version", 0, arg_flag, &version_flag, NULL, NULL }
+};
+
+static int num_args = sizeof(args) / sizeof(args[0]);
+
+int
+main(int argc, char **argv)
+{
+ char stemplate[sizeof("sqlite:testhdb-XXXXXX")];
+#ifdef HAVE_LMDB
+ char ltemplate[sizeof("lmdb:testhdb-XXXXXX")];
+#endif
+ int o = 0;
+
+ setprogname(argv[0]);
+
+ if (getarg(args, num_args, argc, argv, &o))
+ krb5_std_usage(1, args, num_args);
+
+ if (help_flag)
+ krb5_std_usage(0, args, num_args);
+
+ if (version_flag){
+ print_version(NULL);
+ return 0;
+ }
+
+ if (!use_fork && !use_threads)
+ use_threads = use_fork = 1;
+
+#ifdef HAVE_FORK
+ if (use_fork) {
+ printf("Testing SQLite3 HDB backend (multi-process)\n");
+ memcpy(stemplate, "sqlite:testhdb-XXXXXX", sizeof("sqlite:testhdb-XXXXXX"));
+ test_hdb_concurrency(stemplate, "", 0);
+
+#ifdef HAVE_LMDB
+ printf("Testing LMDB HDB backend (multi-process)\n");
+ memcpy(ltemplate, "lmdb:testhdb-XXXXXX", sizeof("lmdb:testhdb-XXXXXX"));
+ test_hdb_concurrency(ltemplate, ".lmdb", 0);
+#endif
+ }
+#endif
+
+ if (use_threads) {
+ printf("Testing SQLite3 HDB backend (multi-process)\n");
+ memcpy(stemplate, "sqlite:testhdb-XXXXXX", sizeof("sqlite:testhdb-XXXXXX"));
+ test_hdb_concurrency(stemplate, "", 1);
+
+#ifdef HAVE_LMDB
+ printf("Testing LMDB HDB backend (multi-process)\n");
+ memcpy(ltemplate, "lmdb:testhdb-XXXXXX", sizeof("lmdb:testhdb-XXXXXX"));
+ test_hdb_concurrency(ltemplate, ".lmdb", 1);
+#endif
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hdb/test_dbinfo.c b/third_party/heimdal/lib/hdb/test_dbinfo.c
new file mode 100644
index 0000000..195fd41
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/test_dbinfo.c
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hdb_locl.h"
+#include <getarg.h>
+
+static int help_flag;
+static int version_flag;
+
+struct getargs args[] = {
+ { "help", 'h', arg_flag, &help_flag, NULL, NULL },
+ { "version", 0, arg_flag, &version_flag, NULL, NULL }
+};
+
+static int num_args = sizeof(args) / sizeof(args[0]);
+
+/*
+ * Prove that HDB_EntryOrAlias being a CHOICE of hdb_entry or hdb_entry_alias
+ * adds nothing to the encoding of those types.
+ */
+static
+void
+check_HDB_EntryOrAlias(krb5_context context)
+{
+ HDB_EntryOrAlias eoa;
+ hdb_entry entry;
+ hdb_entry_alias alias;
+ krb5_data v;
+ size_t len;
+ int ret;
+
+ memset(&entry, 0, sizeof(entry));
+ memset(&alias, 0, sizeof(alias));
+ memset(&eoa, 0, sizeof(eoa));
+ krb5_data_zero(&v);
+
+ ret = krb5_make_principal(context, &alias.principal, "KTH.SE", "foo",
+ NULL);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_make_principal");
+ ASN1_MALLOC_ENCODE(HDB_entry_alias, v.data, v.length, &alias, &len, ret);
+ if (ret)
+ krb5_err(context, 1, ret, "encode_HDB_EntryOrAlias");
+ if (v.length != len)
+ abort();
+ ret = decode_HDB_EntryOrAlias(v.data, v.length, &eoa, &len);
+ if (ret)
+ krb5_err(context, 1, ret, "decode_HDB_EntryOrAlias");
+ if (v.length != len)
+ abort();
+ free_HDB_EntryOrAlias(&eoa);
+ free_HDB_entry_alias(&alias);
+ krb5_data_free(&v);
+
+ ret = krb5_make_principal(context, &entry.principal, "KTH.SE", "foo",
+ NULL);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_make_principal");
+ entry.kvno = 5;
+ entry.flags.initial = 1;
+ ASN1_MALLOC_ENCODE(HDB_entry, v.data, v.length, &entry, &len, ret);
+ if (ret)
+ krb5_err(context, 1, ret, "encode_HDB_EntryOrAlias");
+ if (v.length != len)
+ abort();
+ ret = decode_HDB_EntryOrAlias(v.data, v.length, &eoa, &len);
+ if (ret)
+ krb5_err(context, 1, ret, "decode_HDB_EntryOrAlias");
+ if (v.length != len)
+ abort();
+ free_HDB_EntryOrAlias(&eoa);
+ free_HDB_entry(&entry);
+ krb5_data_free(&v);
+}
+
+int
+main(int argc, char **argv)
+{
+ struct hdb_dbinfo *info, *d;
+ krb5_context context;
+ int ret, o = 0;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, num_args, argc, argv, &o))
+ krb5_std_usage(1, args, num_args);
+
+ if(help_flag)
+ krb5_std_usage(0, args, num_args);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ check_HDB_EntryOrAlias(context);
+
+ ret = hdb_get_dbinfo(context, &info);
+ if (ret)
+ krb5_err(context, 1, ret, "hdb_get_dbinfo");
+
+ d = NULL;
+ while ((d = hdb_dbinfo_get_next(info, d)) != NULL) {
+ const char *s;
+ s = hdb_dbinfo_get_label(context, d);
+ printf("label: %s\n", s ? s : "no label");
+ s = hdb_dbinfo_get_realm(context, d);
+ printf("\trealm: %s\n", s ? s : "no realm");
+ s = hdb_dbinfo_get_dbname(context, d);
+ printf("\tdbname: %s\n", s ? s : "no dbname");
+ s = hdb_dbinfo_get_mkey_file(context, d);
+ printf("\tmkey_file: %s\n", s ? s : "no mkey file");
+ s = hdb_dbinfo_get_acl_file(context, d);
+ printf("\tacl_file: %s\n", s ? s : "no acl file");
+ }
+
+ hdb_free_dbinfo(context, &info);
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hdb/test_hdbkeys.c b/third_party/heimdal/lib/hdb/test_hdbkeys.c
new file mode 100644
index 0000000..d6bc31d
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/test_hdbkeys.c
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hdb_locl.h"
+#include <getarg.h>
+#include <base64.h>
+
+static int help_flag;
+static int version_flag;
+static int kvno_integer = 1;
+
+struct getargs args[] = {
+ { "kvno", 'd', arg_integer, &kvno_integer, NULL, NULL },
+ { "help", 'h', arg_flag, &help_flag, NULL, NULL },
+ { "version", 0, arg_flag, &version_flag, NULL, NULL }
+};
+
+static int num_args = sizeof(args) / sizeof(args[0]);
+
+int
+main(int argc, char **argv)
+{
+ krb5_principal principal;
+ krb5_context context;
+ char *principal_str, *password_str, *str;
+ int ret, o = 0;
+ hdb_keyset keyset;
+ size_t length, len;
+ void *data;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, num_args, argc, argv, &o))
+ krb5_std_usage(1, args, num_args);
+
+ if(help_flag)
+ krb5_std_usage(0, args, num_args);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ if (argc != 3)
+ errx(1, "username and password missing");
+
+ principal_str = argv[1];
+ password_str = argv[2];
+
+ ret = krb5_parse_name (context, principal_str, &principal);
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_parse_name %s", principal_str);
+
+ memset(&keyset, 0, sizeof(keyset));
+
+ keyset.kvno = kvno_integer;
+ keyset.set_time = malloc(sizeof (*keyset.set_time));
+ if (keyset.set_time == NULL)
+ errx(1, "couldn't allocate set_time field of keyset");
+ *keyset.set_time = time(NULL);
+
+ ret = hdb_generate_key_set_password(context, principal, password_str,
+ &keyset.keys.val, &len);
+ if (ret)
+ krb5_err(context, 1, ret, "hdb_generate_key_set_password");
+ keyset.keys.len = len;
+
+ if (keyset.keys.len == 0)
+ krb5_errx (context, 1, "hdb_generate_key_set_password length 0");
+
+ krb5_free_principal (context, principal);
+
+ ASN1_MALLOC_ENCODE(HDB_keyset, data, length, &keyset, &len, ret);
+ if (ret)
+ krb5_errx(context, 1, "encode keyset");
+ if (len != length)
+ krb5_abortx(context, "foo");
+
+ krb5_free_context(context);
+
+ ret = rk_base64_encode(data, length, &str);
+ if (ret < 0)
+ errx(1, "base64_encode");
+
+ printf("keyset: %s\n", str);
+
+ free(data);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hdb/test_mkey.c b/third_party/heimdal/lib/hdb/test_mkey.c
new file mode 100644
index 0000000..97399c6
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/test_mkey.c
@@ -0,0 +1,55 @@
+
+#include "hdb_locl.h"
+#include <getarg.h>
+#include <base64.h>
+
+static char *mkey_file;
+static int help_flag;
+static int version_flag;
+
+struct getargs args[] = {
+ { "mkey-file", 0, arg_string, &mkey_file, NULL, NULL },
+ { "help", 'h', arg_flag, &help_flag, NULL, NULL },
+ { "version", 0, arg_flag, &version_flag, NULL, NULL }
+};
+
+static int num_args = sizeof(args) / sizeof(args[0]);
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ int ret, o = 0;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, num_args, argc, argv, &o))
+ krb5_std_usage(1, args, num_args);
+
+ if(help_flag)
+ krb5_std_usage(0, args, num_args);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_init_context failed: %d", ret);
+
+ if (mkey_file) {
+ hdb_master_key mkey;
+
+ ret = hdb_read_master_key(context, mkey_file, &mkey);
+ if (ret)
+ krb5_err(context, 1, ret, "failed to read master key %s", mkey_file);
+
+ hdb_free_master_key(context, mkey);
+ } else
+ krb5_errx(context, 1, "no command option given");
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hdb/test_namespace.c b/third_party/heimdal/lib/hdb/test_namespace.c
new file mode 100644
index 0000000..f9b4cdb
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/test_namespace.c
@@ -0,0 +1,941 @@
+/*
+ * Copyright (c) 2020 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * This program implements an ephemeral, memory-based HDB backend, stores into
+ * it just one HDB entry -one for a namespace- then checks that virtual
+ * principals are returned below that namespace by hdb_fetch_kvno(), and that
+ * the logic for automatic key rotation of virtual principals is correct.
+ */
+
+#include "hdb_locl.h"
+#include <hex.h>
+
+static KeyRotation krs[2];
+static const char *base_pw[2] = { "Testing123...", "Tested123..." };
+
+typedef struct {
+ HDB hdb; /* generic members */
+ /*
+ * Make this dict a global, add a mutex lock around it, and a .finit and/or
+ * atexit() handler to free it, and we'd have a first-class MEMORY HDB.
+ *
+ * What would a first-class MEMORY HDB be good for though, besides testing?
+ *
+ * However, we could move this dict into `HDB' and then have _hdb_store()
+ * and friends support it as a cache for frequently-used & seldom-changing
+ * entries, such as: K/M, namespaces, and krbtgt principals. That would
+ * speed up lookups, especially for backends with poor reader-writer
+ * concurrency (DB, LMDB) and LDAP. Such entries could be cached for a
+ * minute or three at a time.
+ */
+ heim_dict_t dict;
+} TEST_HDB;
+
+struct hdb_called {
+ int create;
+ int init;
+ int fini;
+};
+
+static krb5_error_code
+TDB_close(krb5_context context, HDB *db)
+{
+ return 0;
+}
+
+static krb5_error_code
+TDB_destroy(krb5_context context, HDB *db)
+{
+ TEST_HDB *tdb = (void *)db;
+
+ heim_release(tdb->dict);
+ free(tdb->hdb.hdb_name);
+ free(tdb);
+ return 0;
+}
+
+static krb5_error_code
+TDB_set_sync(krb5_context context, HDB *db, int on)
+{
+ return 0;
+}
+
+static krb5_error_code
+TDB_lock(krb5_context context, HDB *db, int operation)
+{
+
+ return 0;
+}
+
+static krb5_error_code
+TDB_unlock(krb5_context context, HDB *db)
+{
+
+ return 0;
+}
+
+static krb5_error_code
+TDB_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
+{
+ /* XXX Implement */
+ /* Tricky thing: heim_dict_iterate_f() is inconvenient here */
+ /* We need this to check that virtual principals aren't created */
+ return 0;
+}
+
+static krb5_error_code
+TDB_nextkey(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
+{
+ /* XXX Implement */
+ /* Tricky thing: heim_dict_iterate_f() is inconvenient here */
+ /* We need this to check that virtual principals aren't created */
+ return 0;
+}
+
+static krb5_error_code
+TDB_rename(krb5_context context, HDB *db, const char *new_name)
+{
+ return EEXIST;
+}
+
+static krb5_error_code
+TDB__get(krb5_context context, HDB *db, krb5_data key, krb5_data *reply)
+{
+ krb5_error_code ret = 0;
+ TEST_HDB *tdb = (void *)db;
+ heim_object_t k, v = NULL;
+
+ if ((k = heim_data_create(key.data, key.length)) == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0 && (v = heim_dict_get_value(tdb->dict, k)) == NULL)
+ ret = HDB_ERR_NOENTRY;
+ if (ret == 0)
+ ret = krb5_data_copy(reply, heim_data_get_ptr(v), heim_data_get_length(v));
+ heim_release(k);
+ return ret;
+}
+
+static krb5_error_code
+TDB__put(krb5_context context, HDB *db, int rplc, krb5_data kd, krb5_data vd)
+{
+ krb5_error_code ret = 0;
+ TEST_HDB *tdb = (void *)db;
+ heim_object_t k = NULL;
+ heim_object_t v = NULL;
+
+ if ((k = heim_data_create(kd.data, kd.length)) == NULL ||
+ (v = heim_data_create(vd.data, vd.length)) == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0 && !rplc && heim_dict_get_value(tdb->dict, k) != NULL)
+ ret = HDB_ERR_EXISTS;
+ if (ret == 0 && heim_dict_set_value(tdb->dict, k, v))
+ ret = krb5_enomem(context);
+ heim_release(k);
+ heim_release(v);
+ return ret;
+}
+
+static krb5_error_code
+TDB__del(krb5_context context, HDB *db, krb5_data key)
+{
+ krb5_error_code ret = 0;
+ TEST_HDB *tdb = (void *)db;
+ heim_object_t k;
+
+ if ((k = heim_data_create(key.data, key.length)) == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0 && heim_dict_get_value(tdb->dict, k) == NULL)
+ ret = HDB_ERR_NOENTRY;
+ if (ret == 0)
+ heim_dict_delete_key(tdb->dict, k);
+ heim_release(k);
+ return ret;
+}
+
+static krb5_error_code
+TDB_open(krb5_context context, HDB *db, int flags, mode_t mode)
+{
+ return 0;
+}
+
+static krb5_error_code
+hdb_test_create(krb5_context context, struct HDB **db, const char *arg)
+{
+ TEST_HDB *tdb;
+
+ if ((tdb = calloc(1, sizeof(tdb[0]))) == NULL ||
+ (tdb->hdb.hdb_name = strdup(arg)) == NULL ||
+ (tdb->dict = heim_dict_create(10)) == NULL) {
+ if (tdb)
+ free(tdb->hdb.hdb_name);
+ free(tdb);
+ return krb5_enomem(context);
+ }
+
+ tdb->hdb.hdb_db = NULL;
+ tdb->hdb.hdb_master_key_set = 0;
+ tdb->hdb.hdb_openp = 0;
+ tdb->hdb.hdb_capability_flags = HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL;
+ tdb->hdb.hdb_open = TDB_open;
+ tdb->hdb.hdb_close = TDB_close;
+ tdb->hdb.hdb_fetch_kvno = _hdb_fetch_kvno;
+ tdb->hdb.hdb_store = _hdb_store;
+ tdb->hdb.hdb_remove = _hdb_remove;
+ tdb->hdb.hdb_firstkey = TDB_firstkey;
+ tdb->hdb.hdb_nextkey= TDB_nextkey;
+ tdb->hdb.hdb_lock = TDB_lock;
+ tdb->hdb.hdb_unlock = TDB_unlock;
+ tdb->hdb.hdb_rename = TDB_rename;
+ tdb->hdb.hdb__get = TDB__get;
+ tdb->hdb.hdb__put = TDB__put;
+ tdb->hdb.hdb__del = TDB__del;
+ tdb->hdb.hdb_destroy = TDB_destroy;
+ tdb->hdb.hdb_set_sync = TDB_set_sync;
+ *db = &tdb->hdb;
+
+ return 0;
+}
+
+static krb5_error_code
+hdb_test_init(krb5_context context, void **ctx)
+{
+ *ctx = NULL;
+ return 0;
+}
+
+static void hdb_test_fini(void *ctx)
+{
+}
+
+struct hdb_method hdb_test =
+{
+#ifdef WIN32
+ /* Not c99 */
+ HDB_INTERFACE_VERSION,
+ hdb_test_init,
+ hdb_test_fini,
+ 1 /*is_file_based*/, 1 /*can_taste*/,
+ "test",
+ hdb_test_create
+#else
+ .minor_version = HDB_INTERFACE_VERSION,
+ .init = hdb_test_init,
+ .fini = hdb_test_fini,
+ .is_file_based = 1,
+ .can_taste = 1,
+ .prefix = "test",
+ .create = hdb_test_create
+#endif
+};
+
+static krb5_error_code
+make_base_key(krb5_context context,
+ krb5_const_principal p,
+ const char *pw,
+ krb5_keyblock *k)
+{
+ return krb5_string_to_key(context, KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128,
+ pw, p, k);
+}
+
+static krb5_error_code
+tderive_key(krb5_context context,
+ const char *p,
+ KeyRotation *kr,
+ int toffset,
+ krb5_keyblock *base,
+ krb5int32 etype,
+ krb5_keyblock *k,
+ uint32_t *kvno,
+ time_t *set_time)
+{
+ krb5_error_code ret = 0;
+ krb5_crypto crypto = NULL;
+ EncryptionKey intermediate;
+ krb5_data pad, out;
+ size_t len;
+ int n;
+
+ n = toffset / kr->period;
+ *set_time = kr->epoch + kr->period * n;
+ *kvno = kr->base_kvno + n;
+
+ out.data = 0;
+ out.length = 0;
+
+ /* Derive intermediate key */
+ pad.data = (void *)(uintptr_t)p;
+ pad.length = strlen(p);
+ ret = krb5_enctype_keysize(context, base->keytype, &len);
+ if (ret == 0)
+ ret = krb5_crypto_init(context, base, 0, &crypto);
+ if (ret == 0)
+ ret = krb5_crypto_prfplus(context, crypto, &pad, len, &out);
+ if (crypto)
+ krb5_crypto_destroy(context, crypto);
+ crypto = NULL;
+ if (ret == 0)
+ ret = krb5_random_to_key(context, etype, out.data, out.length,
+ &intermediate);
+ krb5_data_free(&out);
+
+ /* Derive final key */
+ pad.data = kvno;
+ pad.length = sizeof(*kvno);
+ if (ret == 0)
+ ret = krb5_enctype_keysize(context, etype, &len);
+ if (ret == 0)
+ ret = krb5_crypto_init(context, &intermediate, 0, &crypto);
+ if (ret == 0) {
+ *kvno = htonl(*kvno);
+ ret = krb5_crypto_prfplus(context, crypto, &pad, len, &out);
+ *kvno = ntohl(*kvno);
+ }
+ if (crypto)
+ krb5_crypto_destroy(context, crypto);
+ if (ret == 0)
+ ret = krb5_random_to_key(context, etype, out.data, out.length, k);
+ krb5_data_free(&out);
+
+ free_EncryptionKey(&intermediate);
+ return ret;
+}
+
+/* Create a namespace principal */
+static void
+make_namespace(krb5_context context, HDB *db, const char *name)
+{
+ krb5_error_code ret = 0;
+ hdb_entry e;
+ Key k;
+
+ memset(&k, 0, sizeof(k));
+ k.mkvno = 0;
+ k.salt = 0;
+
+ /* Setup the HDB entry */
+ memset(&e, 0, sizeof(e));
+ e.created_by.time = krs[0].epoch;
+ e.valid_start = e.valid_end = e.pw_end = 0;
+ e.generation = 0;
+ e.flags = int2HDBFlags(0);
+ e.flags.server = e.flags.client = 1;
+ e.flags.virtual = 1;
+
+ /* Setup etypes */
+ if (ret == 0 &&
+ (e.etypes = malloc(sizeof(*e.etypes))) == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0)
+ e.etypes->len = 3;
+ if (ret == 0 &&
+ (e.etypes->val = calloc(e.etypes->len,
+ sizeof(e.etypes->val[0]))) == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0) {
+ e.etypes->val[0] = KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128;
+ e.etypes->val[1] = KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192;
+ e.etypes->val[2] = KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96;
+ }
+
+ /* Setup max_life and max_renew */
+ if (ret == 0 &&
+ (e.max_life = malloc(sizeof(*e.max_life))) == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0 &&
+ (e.max_renew = malloc(sizeof(*e.max_renew))) == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0)
+ /* Make it long, so we see the clamped max */
+ *e.max_renew = 2 * ((*e.max_life = 15 * 24 * 3600));
+
+ /* Setup principal name and created_by */
+ if (ret == 0)
+ ret = krb5_parse_name(context, name, &e.principal);
+ if (ret == 0)
+ ret = krb5_parse_name(context, "admin@BAR.EXAMPLE",
+ &e.created_by.principal);
+
+ /* Make base keys for first epoch */
+ if (ret == 0)
+ ret = make_base_key(context, e.principal, base_pw[0], &k.key);
+ if (ret == 0)
+ add_Keys(&e.keys, &k);
+ if (ret == 0)
+ ret = hdb_entry_set_pw_change_time(context, &e, krs[0].epoch);
+ free_Key(&k);
+ e.kvno = krs[0].base_key_kvno;
+
+ /* Move them to history */
+ if (ret == 0)
+ ret = hdb_add_current_keys_to_history(context, &e);
+ free_Keys(&e.keys);
+
+ /* Make base keys for second epoch */
+ if (ret == 0)
+ ret = make_base_key(context, e.principal, base_pw[1], &k.key);
+ if (ret == 0)
+ add_Keys(&e.keys, &k);
+ e.kvno = krs[1].base_key_kvno;
+ if (ret == 0)
+ ret = hdb_entry_set_pw_change_time(context, &e, krs[1].epoch);
+
+ /* Add the key rotation metadata */
+ if (ret == 0)
+ ret = hdb_entry_add_key_rotation(context, &e, 0, &krs[0]);
+ if (ret == 0)
+ ret = hdb_entry_add_key_rotation(context, &e, 0, &krs[1]);
+
+ if (ret == 0)
+ ret = db->hdb_store(context, db, 0, &e);
+ if (ret)
+ krb5_err(context, 1, ret, "failed to setup a namespace principal");
+ free_Key(&k);
+ hdb_free_entry(context, db, &e);
+}
+
+#define WK_PREFIX "WELLKNOWN/" HDB_WK_NAMESPACE "/"
+
+static const char *expected[] = {
+ WK_PREFIX "_/bar.example@BAR.EXAMPLE",
+ "HTTP/bar.example@BAR.EXAMPLE",
+ "HTTP/foo.bar.example@BAR.EXAMPLE",
+ "host/foo.bar.example@BAR.EXAMPLE",
+ "HTTP/blah.foo.bar.example@BAR.EXAMPLE",
+};
+static const char *unexpected[] = {
+ WK_PREFIX "_/no.example@BAZ.EXAMPLE",
+ "HTTP/no.example@BAR.EXAMPLE",
+ "HTTP/foo.no.example@BAR.EXAMPLE",
+ "HTTP/blah.foo.no.example@BAR.EXAMPLE",
+};
+
+/*
+ * We'll fetch as many entries as we have principal names in `expected[]', for
+ * as many KeyRotation periods as we have (between 1 and 3), and for up to 5
+ * different time offsets in each period.
+ */
+#define NUM_OFFSETS 5
+static hdb_entry e[
+ (sizeof(expected) / sizeof(expected[0])) *
+ (sizeof(krs) / sizeof(krs[0])) *
+ NUM_OFFSETS
+];
+
+static int
+hist_key_compar(const void *va, const void *vb)
+{
+ const hdb_keyset *a = va;
+ const hdb_keyset *b = vb;
+
+ return a->kvno - b->kvno;
+}
+
+/*
+ * Fetch keys for some decent time in the given kr.
+ *
+ * `kr' is an index into the global `krs[]'.
+ * `t' is a number 0..4 inclusive that identifies a time period relative to the
+ * epoch of `krs[kr]' (see code below).
+ */
+static void
+fetch_entries(krb5_context context,
+ HDB *db,
+ size_t kr,
+ size_t t,
+ int must_fail)
+{
+ krb5_error_code ret = 0;
+ krb5_principal p = NULL;
+ krb5_keyblock base_key, dk;
+ hdb_entry *ep;
+ hdb_entry no;
+ size_t i, b;
+ int toffset = 0;
+
+ memset(&base_key, 0, sizeof(base_key));
+
+ /* Work out offset of first entry in `e[]' */
+ assert(kr < sizeof(krs) / sizeof(krs[0]));
+ assert(t < NUM_OFFSETS);
+ b = (kr * NUM_OFFSETS + t) * (sizeof(expected) / sizeof(expected[0]));
+ assert(b < sizeof(e) / sizeof(e[0]));
+ assert(sizeof(e) / sizeof(e[0]) - b >=
+ (sizeof(expected) / sizeof(expected[0])));
+
+ switch (t) {
+ case 0: toffset = 1; break; /* epoch + 1s */
+ case 1: toffset = 1 + (krs[kr].period >> 1); break; /* epoch + period/2 */
+ case 2: toffset = 1 + (krs[kr].period >> 2); break; /* epoch + period/4 */
+ case 3: toffset = 1 + (krs[kr].period >> 3); break; /* epoch + period/8 */
+ case 4: toffset = 1 - (krs[kr].period >> 3); break; /* epoch - period/8 */
+ }
+
+ for (i = 0; ret == 0 && i < sizeof(expected) / sizeof(expected[0]); i++) {
+ ep = &e[b + i];
+ memset(ep, 0, sizeof(*ep));
+ if (ret == 0)
+ ret = krb5_parse_name(context, expected[i], &p);
+ if (ret == 0 && i == 0) {
+ if (toffset < 0 && kr)
+ ret = make_base_key(context, p, base_pw[kr - 1], &base_key);
+ else
+ ret = make_base_key(context, p, base_pw[kr], &base_key);
+ }
+ if (ret == 0)
+ ret = hdb_fetch_kvno(context, db, p,
+ HDB_F_DECRYPT | HDB_F_ALL_KVNOS,
+ krs[kr].epoch + toffset, 0, 0, ep);
+ if (i && must_fail && ret == 0)
+ krb5_errx(context, 1,
+ "virtual principal that shouldn't exist does");
+ if (kr == 0 && toffset < 0 && ret == HDB_ERR_NOENTRY)
+ continue;
+ if (kr == 0 && toffset < 0) {
+ /*
+ * Virtual principals don't exist before their earliest key
+ * rotation epoch's start time.
+ */
+ if (i == 0) {
+ if (ret)
+ krb5_errx(context, 1,
+ "namespace principal does not exist before its time");
+ } else if (i != 0) {
+ if (ret == 0)
+ krb5_errx(context, 1,
+ "virtual principal exists before its time");
+ if (ret != HDB_ERR_NOENTRY)
+ krb5_errx(context, 1, "wrong error code");
+ ret = 0;
+ }
+ } else {
+ if (ret == 0 &&
+ !krb5_principal_compare(context, p, ep->principal))
+ krb5_errx(context, 1, "wrong principal in fetched entry");
+ }
+
+ {
+ HDB_Ext_KeySet *hist_keys;
+ HDB_extension *ext;
+ ext = hdb_find_extension(ep,
+ choice_HDB_extension_data_hist_keys);
+ if (ext) {
+ /* Sort key history by kvno, why not */
+ hist_keys = &ext->data.u.hist_keys;
+ qsort(hist_keys->val, hist_keys->len,
+ sizeof(hist_keys->val[0]), hist_key_compar);
+ }
+ }
+
+ krb5_free_principal(context, p);
+ }
+ if (ret && must_fail) {
+ free_EncryptionKey(&base_key);
+ return;
+ }
+ if (ret)
+ krb5_err(context, 1, ret, "virtual principal test failed");
+
+ for (i = 0; i < sizeof(unexpected) / sizeof(unexpected[0]); i++) {
+ memset(&no, 0, sizeof(no));
+ if (ret == 0)
+ ret = krb5_parse_name(context, unexpected[i], &p);
+ if (ret == 0)
+ ret = hdb_fetch_kvno(context, db, p, HDB_F_DECRYPT,
+ krs[kr].epoch + toffset, 0, 0, &no);
+ if (ret == 0)
+ krb5_errx(context, 1, "bogus principal exists, wat");
+ krb5_free_principal(context, p);
+ ret = 0;
+ }
+
+ if (kr == 0 && toffset < 0)
+ return;
+
+ /*
+ * XXX
+ *
+ * Add check that derived keys are a) different, b) as expected, using a
+ * set of test vectors or else by computing the expected keys here with
+ * code that's not shared with lib/hdb/common.c.
+ *
+ * Add check that we get expected past and/or future keys, not just current
+ * keys.
+ */
+ for (i = 1; ret == 0 && i < sizeof(expected) / sizeof(expected[0]); i++) {
+ uint32_t kvno;
+ time_t set_time, chg_time;
+
+ ep = &e[b + i];
+ if (toffset > 0) {
+ ret = tderive_key(context, expected[i], &krs[kr], toffset,
+ &base_key, base_key.keytype, &dk, &kvno, &set_time);
+ } else /* XXX */{
+ /* XXX */
+ assert(kr);
+ ret = tderive_key(context, expected[i], &krs[kr - 1],
+ krs[kr].epoch - krs[kr - 1].epoch + toffset,
+ &base_key, base_key.keytype, &dk, &kvno, &set_time);
+ }
+ if (ret)
+ krb5_err(context, 1, ret, "deriving keys for comparison");
+
+ if (kvno != ep->kvno)
+ krb5_errx(context, 1, "kvno mismatch (%u != %u)", kvno, ep->kvno);
+ (void) hdb_entry_get_pw_change_time(ep, &chg_time);
+ if (set_time != chg_time)
+ krb5_errx(context, 1, "key change time mismatch");
+ if (ep->keys.len == 0)
+ krb5_errx(context, 1, "no keys!");
+ if (ep->keys.val[0].key.keytype != dk.keytype)
+ krb5_errx(context, 1, "enctype mismatch!");
+ if (ep->keys.val[0].key.keyvalue.length !=
+ dk.keyvalue.length)
+ krb5_errx(context, 1, "key length mismatch!");
+ if (memcmp(ep->keys.val[0].key.keyvalue.data,
+ dk.keyvalue.data, dk.keyvalue.length) != 0)
+ krb5_errx(context, 1, "key mismatch!");
+ if (memcmp(ep->keys.val[0].key.keyvalue.data,
+ e[b + i - 1].keys.val[0].key.keyvalue.data,
+ dk.keyvalue.length) == 0)
+ krb5_errx(context, 1, "different virtual principals have the same keys!");
+ /* XXX Add check that we have the expected number of history keys */
+ free_EncryptionKey(&dk);
+ }
+ free_EncryptionKey(&base_key);
+}
+
+static void
+check_kvnos(krb5_context context)
+{
+ HDB_Ext_KeySet keysets;
+ size_t i, k, m, p; /* iterator indices */
+
+ keysets.len = 0;
+ keysets.val = 0;
+
+ /* For every principal name */
+ for (i = 0; i < sizeof(expected)/sizeof(expected[0]); i++) {
+ free_HDB_Ext_KeySet(&keysets);
+
+ /* For every entry we've fetched for it */
+ for (k = 0; k < sizeof(e)/sizeof(e[0]); k++) {
+ HDB_Ext_KeySet *hist_keys;
+ HDB_extension *ext;
+ hdb_entry *ep;
+ int match = 0;
+
+ if ((k % NUM_OFFSETS) != i)
+ continue;
+
+ ep = &e[k];
+ if (ep->principal == NULL)
+ continue; /* Didn't fetch this one */
+
+ /*
+ * Check that the current keys for it match what we've seen already
+ * or else add them to `keysets'.
+ */
+ for (m = 0; m < keysets.len; m++) {
+ if (ep->kvno == keysets.val[m].kvno) {
+ /* Check the key is the same */
+ if (ep->keys.val[0].key.keytype !=
+ keysets.val[m].keys.val[0].key.keytype ||
+ ep->keys.val[0].key.keyvalue.length !=
+ keysets.val[m].keys.val[0].key.keyvalue.length ||
+ memcmp(ep->keys.val[0].key.keyvalue.data,
+ keysets.val[m].keys.val[0].key.keyvalue.data,
+ ep->keys.val[0].key.keyvalue.length) != 0)
+ krb5_errx(context, 1,
+ "key mismatch for same princ & kvno");
+ match = 1;
+ }
+ }
+ if (m == keysets.len) {
+ hdb_keyset ks;
+
+ ks.kvno = ep->kvno;
+ ks.keys = ep->keys;
+ ks.set_time = 0;
+ if (add_HDB_Ext_KeySet(&keysets, &ks))
+ krb5_err(context, 1, ENOMEM, "out of memory");
+ match = 1;
+ }
+ if (match)
+ continue;
+
+ /* For all non-current keysets, repeat the above */
+ ext = hdb_find_extension(ep,
+ choice_HDB_extension_data_hist_keys);
+ if (!ext)
+ continue;
+ hist_keys = &ext->data.u.hist_keys;
+ for (p = 0; p < hist_keys->len; p++) {
+ for (m = 0; m < keysets.len; m++) {
+ if (keysets.val[m].kvno == hist_keys->val[p].kvno)
+ if (ep->keys.val[0].key.keytype !=
+ keysets.val[m].keys.val[0].key.keytype ||
+ ep->keys.val[0].key.keyvalue.length !=
+ keysets.val[m].keys.val[0].key.keyvalue.length ||
+ memcmp(ep->keys.val[0].key.keyvalue.data,
+ keysets.val[m].keys.val[0].key.keyvalue.data,
+ ep->keys.val[0].key.keyvalue.length) != 0)
+ krb5_errx(context, 1,
+ "key mismatch for same princ & kvno");
+ }
+ if (m == keysets.len) {
+ hdb_keyset ks;
+ ks.kvno = ep->kvno;
+ ks.keys = ep->keys;
+ ks.set_time = 0;
+ if (add_HDB_Ext_KeySet(&keysets, &ks))
+ krb5_err(context, 1, ENOMEM, "out of memory");
+ }
+ }
+ }
+ }
+ free_HDB_Ext_KeySet(&keysets);
+}
+
+static void
+print_em(krb5_context context)
+{
+ HDB_Ext_KeySet *hist_keys;
+ HDB_extension *ext;
+ size_t i, p;
+
+ for (i = 0; i < sizeof(e)/sizeof(e[0]); i++) {
+ const char *name = expected[i % (sizeof(expected)/sizeof(expected[0]))];
+ char *x;
+
+ if (0 == i % (sizeof(expected)/sizeof(expected[0])))
+ continue;
+ if (e[i].principal == NULL)
+ continue;
+ hex_encode(e[i].keys.val[0].key.keyvalue.data,
+ e[i].keys.val[0].key.keyvalue.length, &x);
+ printf("%s %u %s\n", x, e[i].kvno, name);
+ free(x);
+
+ ext = hdb_find_extension(&e[i], choice_HDB_extension_data_hist_keys);
+ if (!ext)
+ continue;
+ hist_keys = &ext->data.u.hist_keys;
+ for (p = 0; p < hist_keys->len; p++) {
+ hex_encode(hist_keys->val[p].keys.val[0].key.keyvalue.data,
+ hist_keys->val[p].keys.val[0].key.keyvalue.length, &x);
+ printf("%s %u %s\n", x, hist_keys->val[p].kvno, name);
+ free(x);
+ }
+ }
+}
+
+#if 0
+static void
+check_expected_kvnos(krb5_context context)
+{
+ HDB_Ext_KeySet *hist_keys;
+ HDB_extension *ext;
+ size_t i, k, m, p;
+
+ for (i = 0; i < sizeof(expected)/sizeof(expected[0]); i++) {
+ for (k = 0; k < sizeof(krs)/sizeof(krs[0]); k++) {
+ hdb_entry *ep = &e[k * sizeof(expected)/sizeof(expected[0]) + i];
+
+ if (ep->principal == NULL)
+ continue;
+ for (m = 0; m < NUM_OFFSETS; m++) {
+ ext = hdb_find_extension(ep,
+ choice_HDB_extension_data_hist_keys);
+ if (!ext)
+ continue;
+ hist_keys = &ext->data.u.hist_keys;
+ for (p = 0; p < hist_keys->len; p++) {
+ fprintf(stderr, "%s at %lu, %lu: history kvno %u\n",
+ expected[i], k, m, hist_keys->val[p].kvno);
+ }
+ }
+ fprintf(stderr, "%s at %lu: kvno %u\n", expected[i], k,
+ ep->kvno);
+ }
+ }
+}
+#endif
+
+#define SOME_TIME 1596318329
+#define SOME_BASE_KVNO 150
+#define SOME_EPOCH (SOME_TIME - (7 * 24 * 3600) - (SOME_TIME % (7 * 24 * 3600)))
+#define SOME_PERIOD 3600
+
+#define CONF \
+ "[hdb]\n" \
+ "\tenable_virtual_hostbased_princs = true\n" \
+ "\tvirtual_hostbased_princ_mindots = 1\n" \
+ "\tvirtual_hostbased_princ_maxdots = 3\n" \
+
+int
+main(int argc, char **argv)
+{
+ krb5_error_code ret;
+ krb5_context context;
+ size_t i;
+ HDB *db = NULL;
+
+ setprogname(argv[0]);
+ memset(e, 0, sizeof(e));
+ ret = krb5_init_context(&context);
+ if (ret == 0)
+ ret = krb5_set_config(context, CONF);
+ if (ret == 0)
+ ret = krb5_plugin_register(context, PLUGIN_TYPE_DATA, "hdb_test_interface",
+ &hdb_test);
+ if (ret == 0)
+ ret = hdb_create(context, &db, "test:mem");
+ if (ret)
+ krb5_err(context, 1, ret, "failed to setup HDB driver and test");
+
+ assert(db->enable_virtual_hostbased_princs);
+ assert(db->virtual_hostbased_princ_ndots == 1);
+ assert(db->virtual_hostbased_princ_maxdots == 3);
+
+ /* Setup key rotation metadata in a convenient way */
+ /*
+ * FIXME Reorder these two KRs to match how we store them to avoid
+ * confusion. #0 should be future-most, #1 should past-post.
+ */
+ krs[0].flags = krs[1].flags = int2KeyRotationFlags(0);
+ krs[0].epoch = SOME_EPOCH - 20 * 24 * 3600;
+ krs[0].period = SOME_PERIOD >> 1;
+ krs[0].base_kvno = 150;
+ krs[0].base_key_kvno = 1;
+ krs[1].epoch = SOME_TIME;
+ krs[1].period = SOME_PERIOD;
+ krs[1].base_kvno = krs[0].base_kvno + 1 + (krs[1].epoch + (krs[0].period - 1) - krs[0].epoch) / krs[0].period;
+ krs[1].base_key_kvno = 2;
+
+ {
+ HDB_Ext_KeyRotation existing_krs, new_krs;
+ KeyRotation ordered_krs[2];
+
+ ordered_krs[0] = krs[1];
+ ordered_krs[1] = krs[0];
+ existing_krs.len = 0;
+ existing_krs.val = 0;
+ new_krs.len = 1;
+ new_krs.val = &ordered_krs[1];
+ if ((ret = hdb_validate_key_rotations(context, NULL, &new_krs)) ||
+ (ret = hdb_validate_key_rotations(context, &existing_krs,
+ &new_krs)))
+ krb5_err(context, 1, ret, "Valid KeyRotation thought invalid");
+ new_krs.len = 1;
+ new_krs.val = &ordered_krs[0];
+ if ((ret = hdb_validate_key_rotations(context, NULL, &new_krs)) ||
+ (ret = hdb_validate_key_rotations(context, &existing_krs,
+ &new_krs)))
+ krb5_err(context, 1, ret, "Valid KeyRotation thought invalid");
+ new_krs.len = 2;
+ new_krs.val = &ordered_krs[0];
+ if ((ret = hdb_validate_key_rotations(context, NULL, &new_krs)) ||
+ (ret = hdb_validate_key_rotations(context, &existing_krs,
+ &new_krs)))
+ krb5_err(context, 1, ret, "Valid KeyRotation thought invalid");
+ existing_krs.len = 1;
+ existing_krs.val = &ordered_krs[1];
+ if ((ret = hdb_validate_key_rotations(context, &existing_krs,
+ &new_krs)))
+ krb5_err(context, 1, ret, "Valid KeyRotation thought invalid");
+ existing_krs.len = 2;
+ existing_krs.val = &ordered_krs[0];
+ if ((ret = hdb_validate_key_rotations(context, &existing_krs,
+ &new_krs)))
+ krb5_err(context, 1, ret, "Valid KeyRotation thought invalid");
+
+ new_krs.len = 2;
+ new_krs.val = &krs[0];
+ if ((ret = hdb_validate_key_rotations(context, &existing_krs,
+ &new_krs)) == 0)
+ krb5_errx(context, 1, "Invalid KeyRotation thought valid");
+ }
+
+ make_namespace(context, db, WK_PREFIX "_/bar.example@BAR.EXAMPLE");
+
+ fetch_entries(context, db, 1, 0, 0);
+ fetch_entries(context, db, 1, 1, 0);
+ fetch_entries(context, db, 1, 2, 0);
+ fetch_entries(context, db, 1, 3, 0);
+ fetch_entries(context, db, 1, 4, 0); /* Just before newest KR */
+
+ fetch_entries(context, db, 0, 0, 0);
+ fetch_entries(context, db, 0, 1, 0);
+ fetch_entries(context, db, 0, 2, 0);
+ fetch_entries(context, db, 0, 3, 0);
+ fetch_entries(context, db, 0, 4, 1); /* Must fail: just before 1st KR */
+
+ /*
+ * Check that for every virtual principal in `expected[]', all the keysets
+ * with the same kvno, in all the entries fetched for different times,
+ * match.
+ */
+ check_kvnos(context);
+
+#if 0
+ /*
+ * Check that for every virtual principal in `expected[]' we have the
+ * expected key history.
+ */
+ check_expected_kvnos(context);
+#endif
+
+ /*
+ * XXX Add various tests here, checking `e[]':
+ *
+ * - Extract all {principal, kvno, key} for all keys, current and
+ * otherwise, then sort by {key, kvno, principal}, then check that the
+ * only time we have matching keys is when the kvno and principal also
+ * match.
+ */
+
+ print_em(context);
+
+ /*
+ * XXX Test adding a third KR, a 4th KR, dropping KRs...
+ */
+
+ /* Cleanup */
+ for (i = 0; ret == 0 && i < sizeof(e) / sizeof(e[0]); i++)
+ hdb_free_entry(context, db, &e[i]);
+ db->hdb_destroy(context, db);
+ krb5_free_context(context);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hdb/version-script.map b/third_party/heimdal/lib/hdb/version-script.map
new file mode 100644
index 0000000..058060d
--- /dev/null
+++ b/third_party/heimdal/lib/hdb/version-script.map
@@ -0,0 +1,189 @@
+# $Id$
+
+HEIMDAL_HDB_1.0 {
+ global:
+ _hdb_fetch_kvno;
+ _hdb_remove;
+ _hdb_store;
+ hdb_add_current_keys_to_history;
+ hdb_add_history_key;
+ hdb_add_history_keyset;
+ hdb_add_master_key;
+ hdb_change_kvno;
+ hdb_check_db_format;
+ hdb_clear_extension;
+ hdb_clear_master_key;
+ hdb_create;
+ hdb_db_dir;
+ hdb_dbinfo_get_acl_file;
+ hdb_dbinfo_get_binding;
+ hdb_dbinfo_get_dbname;
+ hdb_dbinfo_get_label;
+ hdb_dbinfo_get_log_file;
+ hdb_dbinfo_get_mkey_file;
+ hdb_dbinfo_get_next;
+ hdb_dbinfo_get_realm;
+ hdb_default_db;
+ hdb_derive_etypes;
+ hdb_enctype2key;
+ hdb_entry2string;
+ hdb_entry2value;
+ hdb_entry_add_key_rotation;
+ hdb_entry_alias2value;
+ hdb_entry_check_mandatory;
+ hdb_entry_clear_password;
+ hdb_entry_get_ConstrainedDelegACL;
+ hdb_entry_get_aliases;
+ hdb_entry_get_key_rotation;
+ hdb_entry_get_krb5_config;
+ hdb_entry_get_password;
+ hdb_entry_get_pkinit_acl;
+ hdb_entry_get_pkinit_cert;
+ hdb_entry_get_pkinit_hash;
+ hdb_entry_get_pw_change_time;
+ hdb_entry_set_krb5_config;
+ hdb_entry_set_password;
+ hdb_entry_set_pw_change_time;
+ hdb_fetch_kvno;
+ hdb_find_extension;
+ hdb_foreach;
+ hdb_free_dbinfo;
+ hdb_free_entry;
+ hdb_free_key;
+ hdb_free_keys;
+ hdb_free_master_key;
+ hdb_generate_key_set;
+ hdb_generate_key_set_password;
+ hdb_generate_key_set_password_with_ks_tuple;
+ hdb_get_dbinfo;
+ hdb_get_instance;
+ hdb_init_db;
+ hdb_install_keyset;
+ hdb_key2principal;
+ hdb_kvno2keys;
+ hdb_list_builtin;
+ hdb_lock;
+ hdb_next_enctype2key;
+ hdb_principal2key;
+ hdb_print_entry;
+ hdb_process_master_key;
+ hdb_prune_keys;
+ hdb_prune_keys_kvno;
+ hdb_read_master_key;
+ hdb_remove_keys;
+ hdb_replace_extension;
+ hdb_seal_key;
+ hdb_seal_key_mkey;
+ hdb_seal_keys;
+ hdb_seal_keys_mkey;
+ hdb_set_last_modified_by;
+ hdb_set_master_key;
+ hdb_set_master_keyfile;
+ hdb_unlock;
+ hdb_unseal_key;
+ hdb_unseal_key_mkey;
+ hdb_unseal_keys;
+ hdb_unseal_keys_kvno;
+ hdb_unseal_keys_mkey;
+ hdb_validate_key_rotation;
+ hdb_validate_key_rotations;
+ hdb_value2entry;
+ hdb_value2entry_alias;
+ hdb_write_master_key;
+ length_hdb_keyset;
+ length_HDB_keyset;
+ hdb_interface_version;
+ initialize_hdb_error_table_r;
+
+ # MIT KDB related entries
+ _hdb_mdb_value2entry;
+ _hdb_mit_dump2mitdb_entry;
+
+ hdb_kt_ops;
+ hdb_get_kt_ops;
+
+ # some random bits needed for libkadm
+ add_HDB_Ext_KeyRotation;
+ add_HDB_Ext_KeySet;
+ add_HDB_Ext_KeySet;
+ add_Keys;
+ add_Keys;
+ asn1_HDBFlags_units;
+ copy_Event;
+ copy_HDB_EncTypeList;
+ copy_hdb_entry;
+ copy_hdb_entry_alias;
+ copy_HDB_entry;
+ copy_HDB_entry_alias;
+ copy_HDB_EntryOrAlias;
+ copy_HDB_extensions;
+ copy_HDB_Ext_KeyRotation;
+ copy_Key;
+ copy_Keys;
+ copy_Salt;
+ decode_HDB_EncTypeList;
+ decode_hdb_entry;
+ decode_hdb_entry_alias;
+ decode_HDB_entry;
+ decode_HDB_entry_alias;
+ decode_HDB_EntryOrAlias;
+ decode_HDB_Ext_Aliases;
+ decode_HDB_extension;
+ decode_HDB_Ext_KeyRotation;
+ decode_HDB_Ext_PKINIT_acl;
+ decode_Key;
+ decode_Keys;
+ encode_HDB_EncTypeList;
+ encode_hdb_entry;
+ encode_hdb_entry_alias;
+ encode_HDB_entry;
+ encode_HDB_entry_alias;
+ encode_HDB_EntryOrAlias;
+ encode_HDB_Ext_Aliases;
+ encode_HDB_extension;
+ encode_HDB_Ext_KeyRotation;
+ encode_HDB_Ext_PKINIT_acl;
+ encode_hdb_keyset;
+ encode_HDB_keyset;
+ encode_Key;
+ encode_Keys;
+ free_Event;
+ free_HDB_EncTypeList;
+ free_hdb_entry;
+ free_hdb_entry_alias;
+ free_HDB_entry;
+ free_HDB_entry_alias;
+ free_HDB_EntryOrAlias;
+ free_HDB_Ext_Aliases;
+ free_HDB_extension;
+ free_HDB_extensions;
+ free_HDB_Ext_KeyRotation;
+ free_HDB_Ext_KeySet;
+ free_HDB_Ext_PKINIT_acl;
+ free_hdb_keyset;
+ free_HDB_keyset;
+ free_Key;
+ free_Keys;
+ free_Salt;
+ HDBFlags2int;
+ int2HDBFlags;
+ int2KeyRotationFlags;
+ KeyRotationFlags2int;
+ length_HDB_EncTypeList;
+ length_hdb_entry;
+ length_hdb_entry_alias;
+ length_HDB_entry;
+ length_HDB_entry_alias;
+ length_HDB_EntryOrAlias;
+ length_HDB_Ext_Aliases;
+ length_HDB_extension;
+ length_HDB_Ext_KeyRotation;
+ length_HDB_Ext_PKINIT_acl;
+ length_Key;
+ length_Keys;
+ remove_HDB_Ext_KeyRotation;
+ remove_Keys;
+
+ local:
+ *;
+};
diff --git a/third_party/heimdal/lib/heimdal/NTMakefile b/third_party/heimdal/lib/heimdal/NTMakefile
new file mode 100644
index 0000000..dc7d459
--- /dev/null
+++ b/third_party/heimdal/lib/heimdal/NTMakefile
@@ -0,0 +1,98 @@
+########################################################################
+#
+# Copyright (c) 2009, 2010 Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR = lib\heimdal
+
+!include ../../windows/NTMakefile.w32
+
+!ifndef STATICLIBS
+
+DLLDEPS= \
+ $(LIBASN1) \
+ $(LIBCOMERR) \
+ $(LIBHCRYPTO) \
+ $(LIBHX509) \
+ $(LIBKRB5) \
+ $(LIBROKEN) \
+ $(LIBSQLITE) \
+ $(LIBWIND) \
+ $(LIBLTM) \
+ $(LIBX25519) \
+ $(LIBHEIMBASE)
+
+DLLSDKDEPS= \
+ $(PTHREAD_LIB) \
+ secur32.lib \
+ shell32.lib \
+ dnsapi.lib \
+ shlwapi.lib \
+ version.lib
+
+
+dlllflags=$(dlllflags) /DELAYLOAD:bcrypt.dll
+DLLSDKDEPS=$(DLLSDKDEPS)\
+ bcrypt.lib \
+ delayimp.lib
+
+DEF=$(OBJ)\heimdal.def
+
+RES=$(OBJ)\heimdal-version.res
+
+DEFSRC= ..\asn1\libasn1-exports.def \
+ ..\wind\libwind-exports.def \
+ ..\hcrypto\libhcrypto-exports.def \
+ ..\hx509\libhx509-exports.def \
+ $(OBJDIR)\lib\krb5\libkrb5-exports.def
+
+$(DEF): $(DEFSRC)
+ copy $(DEFSRC: = + ) $(DEF)
+
+DLL=$(BINDIR)\heimdal.dll
+
+$(LIBHEIMDAL): $(BINDIR)\heimdal.dll
+
+$(DLL): $(DLLDEPS) $(DEF) $(RES)
+ $(DLLGUILINK_C) $(DLLDEPS) $(DLLSDKDEPS) $(RES) \
+ -def:$(DEF) -out:$(DLL) \
+ -implib:$(LIBHEIMDAL)
+ $(DLLPREP_NODIST)
+
+clean::
+ -$(RM) $(BINDIR)\heimdal.*
+
+!else
+
+$(LIBHEIMDAL): $(LIBASN1) $(LIBWIND) $(LIBHCRYPTO) $(LIBHX509) $(LIBKRB5) $(LIBHEIMBASE)
+ $(LIBCON)
+
+!endif
+
+all:: $(LIBHEIMDAL)
diff --git a/third_party/heimdal/lib/heimdal/heimdal-version.rc b/third_party/heimdal/lib/heimdal/heimdal-version.rc
new file mode 100644
index 0000000..1da512c
--- /dev/null
+++ b/third_party/heimdal/lib/heimdal/heimdal-version.rc
@@ -0,0 +1,36 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#define RC_FILE_TYPE VFT_DLL
+#define RC_FILE_DESC_0409 "Heimdal Kerberos Library"
+#define RC_FILE_ORIG_0409 "heimdal.dll"
+
+#include "../../windows/version.rc"
diff --git a/third_party/heimdal/lib/hx509/ChangeLog b/third_party/heimdal/lib/hx509/ChangeLog
new file mode 100644
index 0000000..d00f1f3
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/ChangeLog
@@ -0,0 +1,2749 @@
+2008-07-14 Love Hörnquist Åstrand <lha@kth.se>
+
+ * hxtool.c: Break out print_eval_types().
+
+2008-06-21 Love Hörnquist Åstrand <lha@kth.se>
+
+ * ks_p12.c: pass in time_now to unevelope
+
+ * cms.c: Pass in time_now to unevelope, us verify context time in
+ verify_signed.
+
+2008-05-23 Love Hörnquist Åstrand <lha@kth.se>
+
+ * hx_locl.h: Include <limits.h> for TYPE_MAX defines.
+
+2008-04-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * sel-lex.l: Use _hx509_sel_yyerror() instead of error_message().
+
+2008-04-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * sel-lex.l: Include <config.h>
+
+2008-04-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Update make-proto usage.
+
+2008-04-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ca.c: BasicConstraints.pathLenConstraint unsigned int.
+
+ * sel-lex.l: Prefix sel_error with _hx509_ since its global on
+ platforms w/o symbol versioning.
+
+ * sel.h: rename yyerror to sel_yyerror in the whole library, not
+ just the lexer
+
+ * sel-lex.l: rename yyerror to sel_yyerror in the whole library,
+ not just the lexer
+
+2008-04-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * sel-lex.l: Rename yyerror to sel_yyerror and make it static.
+
+2008-04-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hx509.h: Make self-standing by including missing files.
+
+2008-04-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_p11.c: Use unsigned where appropriate.
+
+ * softp11.c: call va_start before using vsnprintf.
+
+ * crypto.c: make refcount slightly more sane.
+
+ * keyset.c: make refcount slightly more sane.
+
+ * cert.c: make refcount slightly more sane.
+
+2008-03-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_nist2.in: Try to find unzip.
+
+2008-03-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * version-script.map: add missing symbols
+
+ * spnego: Make delegated credentials delegated directly, Oleg
+ Sharoiko pointed out that it always didnt work with the old
+ code. Also add som missing cred and context pass-thou functions in
+ the SPNEGO layer.
+
+2008-03-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rename to be more consistent, export for teting
+
+ * Add language to support querying certificates to find a
+ match. Support constructs like "1.3.6.1.5.2.3.5" IN
+ %{certificate.eku} AND %{certificate.subject} TAILMATCH "C=SE".
+
+2008-02-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * version-script.map: add hx509_pem_read
+
+ * hxtool-commands.in: Add --pem to cms-verify-sd.
+
+ * test_cms.in: Test verifying PEM signature files.
+
+ * hxtool.c: Support verifying PEM signature files.
+
+2008-02-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: libhx509_la_OBJECTS depends on hx_locl.h
+
+2008-02-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Use ldap-prep (with libwind) to compare names
+
+2008-01-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cert.c (hx509_query_match_eku): update to support the NULL
+ eku (reset), clearify the old behaivor with regards repetitive
+ calls.
+
+ * Add matching on EKU, validate EKUs, add hxtool matching glue,
+ add check. Adapted from pach from Tim Miller of Mitre
+
+2008-01-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_soft_pkcs11.c: use func for more C_ functions.
+
+2008-01-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * version-script.map: Export hx509_free_error_string().
+
+2008-01-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * version-script.map: only export C_GetFunctionList
+
+ * test_soft_pkcs11.c: use C_GetFunctionList
+
+ * softp11.c: fix comment, remove label.
+
+ * softp11.c: Add option app-fatal to control if softtoken should
+ abort() on erroneous input from applications.
+
+2008-01-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_pkcs11.in: Test password less certificates too
+
+ * keyset.c: document HX509_CERTS_UNPROTECT_ALL
+
+ * ks_file.c: Support HX509_CERTS_UNPROTECT_ALL.
+
+ * hx509.h: Add HX509_CERTS_UNPROTECT_ALL.
+
+ * test_soft_pkcs11.c: Only log in if needed.
+
+2008-01-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * softp11.c: Support PINs to login to the store.
+
+ * Makefile.am: add java pkcs11 test
+
+ * test_java_pkcs11.in: first version of disable java test
+
+ * softp11.c: Drop unused stuff.
+
+ * cert.c: Spelling, Add hx509_cert_get_SPKI_AlgorithmIdentifier,
+ remove unused stuff, add hx509_context to some functions.
+
+ * softp11.c: Add more glue to figure out what keytype this
+ certificate is using.
+
+2008-01-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_pkcs11.in: test debug
+
+ * Add a PKCS11 provider supporting signing and verifing sigatures.
+
+2008-01-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * version-script.map: Replace hx509_name_to_der_name with
+ hx509_name_binary.
+
+ * print.c: make print_func static
+
+2007-12-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * print.c: doxygen
+
+ * env.c: doxygen
+
+ * doxygen.c: add more groups
+
+ * ca.c: doxygen.
+
+2007-12-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ca.c: doxygen
+
+2007-12-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * error.c: doxygen
+
+2007-12-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * More documentation
+
+ * lock.c: Add page referance
+
+ * keyset.c: some more documentation.
+
+ * cms.c: Doxygen documentation.
+
+2007-12-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * *.[ch]: More documentation
+
+2007-12-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * handle refcount on NULL.
+
+ * test_nist_pkcs12.in: drop echo -n, doesn't work with posix sh
+
+2007-12-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_nist2.in: Print that this is version 2 of the tests
+
+ * test_nist.in: Drop printing of $id.
+
+ * hx509.h: Add HX509_VHN_F_ALLOW_NO_MATCH.
+
+ * name.c: spelling.
+
+ * cert.c: make work the doxygen.
+
+ * name.c: fix doxygen compiling.
+
+ * Makefile.am: add doxygen.c
+
+ * doxygen.c: Add doxygen main page.
+
+ * cert.c: Add doxygen.
+
+ * revoke.c (_hx509_revoke_ref): new function.
+
+2007-11-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_keychain.c: Check if SecKeyGetCSPHandle needs prototype.
+
+2007-08-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * data/nist-data: Make work on case senstive filesystems too.
+
+2007-08-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cert.c: match rfc822 contrains better, provide better error
+ strings.
+
+2007-08-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cert.c: "self-signed doesn't count" doesn't apply to trust
+ anchor certificate. make trust anchor check consistant.
+
+ * revoke.c: make compile.
+
+ * revoke.c (verify_crl): set error strings.
+
+ * revoke.c (verify_crl): handle with the signer is the
+ CRLsigner (shortcut).
+
+ * cert.c: Fix NC, comment on how to use _hx509_check_key_usage.
+
+2007-08-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_nist2.in, Makefile, test/nist*: Add nist pkits tests.
+
+ * revoke.c: Update to use CERT_REVOKED error, shortcut out of OCSP
+ checking when OCSP reply is a revocation reply.
+
+ * hx509_err.et: Make CERT_REVOKED error OCSP/CRL agnostic.
+
+ * name.c (_hx509_Name_to_string): make printableString handle
+ space (0x20) diffrences as required by rfc3280.
+
+ * revoke.c: Search for the right issuer when looking for the
+ issuer of the CRL signer.
+
+2007-08-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * revoke.c: Handle CRL signing certificate better, try to not
+ revalidate invalid CRLs over and over.
+
+2007-08-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cms.c: remove stale comment.
+
+ * test_nist.in: Unpack PKITS_data.zip and run tests.
+
+ * test_nist_cert.in: Adapt to new nist pkits framework.
+
+ * test_nist_pkcs12.in: Adapt to new nist pkits framework.
+
+ * Makefile.am: clean PKITS_data
+
+2007-07-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add version-script.map to EXTRA_DIST
+
+2007-07-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add depenency on asn1_compile for asn1 built files.
+
+2007-07-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * peer.c: update (c), indent.
+
+ * Makefile.am: New library version.
+
+2007-06-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_p11.c: Add sha2 types.
+
+ * ref/pkcs11.h: Sync with scute.
+
+ * ref/pkcs11.h: Add sha2 CKM's.
+
+ * print.c: Print authorityInfoAccess.
+
+ * cert.c: Rename proxyCertInfo oid.
+
+ * ca.c: Rename proxyCertInfo oid.
+
+ * print.c: Rename proxyCertInfo oid.
+
+2007-06-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_ca.in: Adapt to new request handling.
+
+ * req.c: Allow export some of the request parameters.
+
+ * hxtool-commands.in: Adapt to new request handling.
+
+ * hxtool.c: Adapt to new request handling.
+
+ * test_req.in: Adapt to new request handling.
+
+ * version-script.map: Add initialize_hx_error_table_r.
+
+ * req.c: Move _hx509_request_print here.
+
+ * hxtool.c: use _hx509_request_print
+
+ * version-script.map: Export more crap^W semiprivate functions.
+
+ * hxtool.c: don't _hx509_abort
+
+ * version-script.map: add missing ;
+
+2007-06-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cms.c: Use hx509_crypto_random_iv.
+
+ * crypto.c: Split out the iv creation from hx509_crypto_encrypt
+ since _hx509_pbe_encrypt needs to use the iv from the s2k
+ function.
+
+ * test_cert.in: Test PEM and DER FILE writing functionallity.
+
+ * ks_file.c: Add writing DER certificates.
+
+ * hxtool.c: Update to new hx509_pem_write().
+
+ * test_cms.in: test creation of PEM signeddata.
+
+ * hx509.h: PEM struct/function declarations.
+
+ * ks_file.c: Use PEM encoding/decoding functions.
+
+ * file.c: PEM encode/decoding functions.
+
+ * ks_file.c: Use hx509_pem_write.
+
+ * version-script.map: Export some semi-private functions.
+
+ * hxtool.c: Enable writing out signed data as a pem attachment.
+
+ * hxtool-commands.in (cms-create-signed): add --pem
+
+ * file.c (hx509_pem_write): Add.
+
+ * test_ca.in: Issue and test null subject cert.
+
+ * cert.c: Match is first component is in a CN=.
+
+ * test_ca.in: Test hostname if first CN.
+
+ * Makefile.am: Add version script.
+
+ * version-script.map: Limited exported symbols.
+
+ * test_ca.in: test --hostname.
+
+ * test_chain.in: test max-depth
+
+ * hx509.h: fixate HX509_HN_HOSTNAME at 0.
+
+ * hxtool-commands.in: add --hostname add --max-depth
+
+ * cert.c: Verify hostname and max-depth.
+
+ * hxtool.c: Verify hostname and test max-depth.
+
+2007-06-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_cms.in: Test --id-by-name.
+
+ * hxtool-commands.in: add cms-create-sd --id-by-name
+
+ * hxtool.c: Use HX509_CMS_SIGATURE_ID_NAME.
+
+ * cms.c: Implement and use HX509_CMS_SIGATURE_ID_NAME.
+
+ * hx509.h: Add HX509_CMS_SIGATURE_ID_NAME, use subject name for
+ CMS.Identifier. hx509_hostname_type: add hostname type for
+ matching.
+
+ * cert.c (match_general_name): more strict rfc822Name matching.
+ (hx509_verify_hostname): add hostname type for matching.
+
+2007-06-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool.c: Make compile again.
+
+ * hxtool.c: Added peap-server for to make windows peap clients
+ happy.
+
+ * hxtool.c: Unify parse_oid code.
+
+ * hxtool.c: Implement --content-type.
+
+ * hxtool-commands.in: Add content-type.
+
+ * test_cert.in: more cert and keyset tests.
+
+2007-06-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * revoke.c: Avoid stomping on NULL.
+
+ * revoke.c: Avoid reusing i.
+
+ * cert.c: Provide __attribute__ for _hx509_abort.
+
+ * ks_file.c: Fail if not finding iv.
+
+ * keyset.c: Avoid useing freed memory.
+
+ * crypto.c: Free memory in failure case.
+
+ * crypto.c: Free memory in failure case.
+
+2007-06-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * *.c: Add hx509_cert_init_data and use everywhere
+
+ * hx_locl.h: Now that KEYCHAIN:system-anchors is fast again, use
+ that.
+
+ * ks_keychain.c: Implement trust anchor support with
+ SecTrustCopyAnchorCertificates.
+
+ * keyset.c: Set ref to 1 for the new object.
+
+ * cert.c: Fix logic for allow_default_trust_anchors
+
+ * keyset.c: Add refcounting to keystores.
+
+ * cert.c: Change logic for default trust anchors, make it be
+ either default trust anchor, the user supplied, or non at all.
+
+2007-06-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add data/j.pem.
+
+ * Makefile.am: Add test_windows.in.
+
+2007-06-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_keychain.c: rename functions, leaks less memory and more
+ paranoia.
+
+ * test_cms.in: Test cms peer-alg.
+
+ * crypto.c (rsa_create_signature): make oid_id_pkcs1_rsaEncryption
+ mean rsa-with-sha1 but oid oid_id_pkcs1_rsaEncryption in algorithm
+ field. XXX should probably use another algorithmIdentifier for
+ this.
+
+ * peer.c: Make free function return void.
+
+ * cms.c (hx509_cms_create_signed_1): Use hx509_peer_info to select
+ the signature algorithm too.
+
+ * hxtool-commands.in: Add cms-create-sd --peer-alg.
+
+ * req.c: Use _hx509_crypto_default_sig_alg.
+
+ * test_windows.in: Create crl, because everyone needs one.
+
+ * Makefile.am: add wcrl.crl
+
+2007-06-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hx_locl.h: Disable KEYCHAIN for now, its slow.
+
+ * cms.c: When we are not using pkcs7-data, avoid seing
+ signedAttributes since some clients get upset by that (pkcs7 based
+ or just plain broken).
+
+ * ks_keychain.c: Provide rsa signatures.
+
+ * ks_keychain.c: Limit the searches to the selected keychain.
+
+ * ks_keychain.c: include -framework Security specific header files
+ after #ifdef
+
+ * ks_keychain.c: Find and attach private key (does not provide
+ operations yet though).
+
+ * ks_p11.c: Prefix rsa method with p11_
+
+ * ks_keychain.c: Allow opening a specific chain, making "system"
+ special and be the system X509Anchors file. By not specifing any
+ keychain ("KEYCHAIN:"), all keychains are probed.
+
+2007-06-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool.c (verify): Friendlier error message.
+
+ * cert.c: Read in and use default trust anchors if they exists.
+
+ * hx_locl.h: Add concept of default_trust_anchors.
+
+ * ks_keychain.c: Remove err(), remove extra empty comment, fix
+ _iter function.
+
+ * error.c (hx509_get_error_string): if the error code is not the
+ one we expect, punt and use the default com_err/strerror string
+ instead.
+
+ * keyset.c (hx509_certs_merge): its ok to merge in the NULL set of
+ certs.
+
+ * test_windows.in: Fix status string.
+
+ * ks_p12.c (store_func): free whole CertBag, not just the data
+ part.
+
+ * print.c: Check that the self-signed cert is really self-signed.
+
+ * print.c: Use selfsigned for CRL DP whine, tell if its a
+ self-signed.
+
+ * print.c: Whine if its a non CA/proxy and doesn't have CRL DP.
+
+ * ca.c: Add cRLSign to CA certs.
+
+ * cert.c: Register NULL and KEYCHAIN.
+
+ * ks_null.c: register the NULL keystore.
+
+ * Makefile.am: Add ks_keychain.c and related libs.
+
+ * test_crypto.in: Print certificate with utf8.
+
+ * print.c: Leak less memory.
+
+ * hxtool.c: Leak less memory.
+
+ * print.c: Leak less memory, use functions that does same but
+ more.
+
+ * name.c (quote_string): don't sign extend the (signed) char to
+ avoid printing too much, add an assert to check that we didn't
+ overrun the buffer.
+
+ * name.c: Use right element out of the CHOICE for printableString
+ and utf8String
+
+ * ks_keychain.c: Certificate only KeyChain backend.
+
+ * name.c: Reset name before parsing it.
+
+2007-06-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * revoke.c (hx509_crl_*): fix sizeof() mistakes to fix memory
+ corruption.
+
+ * hxtool.c: Add lifetime to crls.
+
+ * hxtool-commands.in: Add lifetime to crls.
+
+ * revoke.c: Add lifetime to crls.
+
+ * test_ca.in: More crl checks.
+
+ * revoke.c: Add revoking certs.
+
+ * hxtool-commands.in: argument is certificates.. for crl-sign
+
+ * hxtool.c (certificate_copy): free lock
+
+ * revoke.c: Fix hx509_set_error_string calls, add
+ hx509_crl_add_revoked_certs(), implement hx509_crl_{alloc,free}.
+
+ * hxtool.c (crl_sign): free lock
+
+ * cert.c (hx509_context_free): free querystat
+
+2007-06-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_chain.in: test ocsp-verify
+
+ * revoke.c (hx509_ocsp_verify): explain what its useful for and
+ provide sane error message.
+
+ * hx509_err.et: New error code, CERT_NOT_IN_OCSP
+
+ * hxtool.c: New command ocsp-verify, check if ocsp contains all
+ certs and are valid (exist and non expired).
+
+ * hxtool-commands.in: New command ocsp-verify.
+
+2007-06-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_ca.in: Create crl and verify that is works.
+
+ * hxtool.c: Sign CRL command.
+
+ * hx509.h: Add hx509_crl.
+
+ * hxtool-commands.in: Add crl-sign commands.
+
+ * revoke.c: Support to generate an empty CRL.
+
+ * tst-crypto-select2: Switched default types.
+
+ * tst-crypto-select1: Switched default types.
+
+ * ca.c: Use default AlgorithmIdentifier.
+
+ * cms.c: Use default AlgorithmIdentifier.
+
+ * crypto.c: Provide default AlgorithmIdentifier and use them.
+
+ * hx_locl.h: Provide default AlgorithmIdentifier.
+
+ * keyset.c (hx509_certs_find): collects stats for queries.
+
+ * cert.c: Sort and print more info.
+
+ * hx_locl.h: Add querystat to hx509_context.
+
+ * test_*.in: sprinle stat saveing
+
+ * Makefile.am: Add stat and objdir.
+
+ * collector.c (_hx509_collector_alloc): return error code instead
+ of pointer.
+
+ * hxtool.c: Add statistic hook.
+
+ * ks_file.c: Update _hx509_collector_alloc prototype.
+
+ * ks_p12.c: Update _hx509_collector_alloc prototype.
+
+ * ks_p11.c: Update _hx509_collector_alloc prototype.
+
+ * hxtool-commands.in: Add statistics hook.
+
+ * cert.c: Statistics printing.
+
+ * ks_p12.c: plug memory leak
+
+ * ca.c (hx509_ca_tbs_add_crl_dp_uri): plug memory leak
+
+2007-05-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * print.c: print utf8 type SAN's
+
+ * Makefile.am: Fix windows client cert name.
+
+ * test_windows.in: Add crl-uri for the ee certs.
+
+ * print.c: Printf formating.
+
+ * ca.c: Add glue for adding CRL dps.
+
+ * test_ca.in: Readd the crl adding code, it works (somewhat) now.
+
+ * print.c: Fix printing of CRL DPnames (I hate IMPLICIT encoded
+ structures).
+
+ * hxtool-commands.in: make ca and alias of certificate-sign
+
+2007-05-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * crypto.c (hx509_crypto_select): copy AI to the right place.
+
+ * hxtool-commands.in: Add ca --ms-upn.
+
+ * hxtool.c: add --ms-upn and add more EKU's for pk-init client.
+
+ * ca.c: Add hx509_ca_tbs_add_san_ms_upn and refactor code.
+
+ * test_crypto.in: Resurect killed e.
+
+ * test_crypto.in: check for aes256-cbc
+
+ * tst-crypto-select7: check for aes256-cbc
+
+ * test_windows.in: test windows stuff
+
+ * hxtool.c: add ca --domain-controller option, add secret key
+ option to avaible.
+
+ * ca.c: Add hx509_ca_tbs_set_domaincontroller.
+
+ * hxtool-commands.in: add ca --domain-controller
+
+ * hxtool.c: hook for testing secrety key algs
+
+ * crypto.c: Add selection code for secret key crypto.
+
+ * hx509.h: Add HX509_SELECT_SECRET_ENC.
+
+2007-05-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_p11.c: add more mechtypes
+
+2007-05-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * print.c: Indent.
+
+ * hxtool-commands.in: add test-crypto command
+
+ * hxtool.c: test crypto command
+
+ * cms.c (hx509_cms_create_signed_1): if no eContentType is given,
+ use pkcs7-data.
+
+ * print.c: add Netscape cert comment
+
+ * crypto.c: Try both the empty password and the NULL
+ password (nothing vs the octet string \x00\x00).
+
+ * print.c: Add some US Fed PKI oids.
+
+ * ks_p11.c: Add some more hashes.
+
+2007-04-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool.c (crypto_select): stop memory leak
+
+2007-04-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * peer.c (hx509_peer_info_free): free memory used too
+
+ * hxtool.c (crypto_select): only free peer if it was used.
+
+2007-04-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool.c: free template
+
+ * ks_mem.c (mem_free): free key array too
+
+ * hxtool.c: free private key and tbs
+
+ * hxtool.c (hxtool_ca): free signer
+
+ * hxtool.c (crypto_available): free peer too.
+
+ * ca.c (get_AuthorityKeyIdentifier): leak less memory
+
+ * hxtool.c (hxtool_ca): free SPKI
+
+ * hxtool.c (hxtool_ca): free cert
+
+ * ks_mem.c (mem_getkeys): allocate one more the we have elements
+ so its possible to store the NULL pointer at the end.
+
+2007-04-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: CLEANFILES += cert-null.pem cert-sub-ca2.pem
+
+2007-02-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ca.c: Disable CRLDistributionPoints for now, its IMPLICIT code
+ in the asn1 parser.
+
+ * print.c: Add some more \n's.
+
+2007-02-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * file.c: Allow mapping using heim_octet_string.
+
+ * hxtool.c: Add options to generate detached signatures.
+
+ * cms.c: Add flags to generate detached signatures.
+
+ * hx509.h: Flag to generate detached signatures.
+
+ * test_cms.in: Support detached sigatures.
+
+ * name.c (hx509_general_name_unparse): unparse the other
+ GeneralName nametypes.
+
+ * print.c: Use less printf. Use hx509_general_name_unparse.
+
+ * cert.c: Fix printing and plug leak-on-error.
+
+2007-01-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_ca.in: Add test for ca --crl-uri.
+
+ * hxtool.c: Add ca --crl-uri.
+
+ * hxtool-commands.in: add ca --crl-uri
+
+ * ca.c: Code to set CRLDistributionPoints in certificates.
+
+ * print.c: Check CRLDistributionPointNames.
+
+ * name.c (hx509_general_name_unparse): function for unparsing
+ GeneralName, only supports GeneralName.URI
+
+ * cert.c (is_proxy_cert): free info if we wont return it.
+
+2007-01-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool.c: Try to help how to use this command.
+
+2007-01-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * switch to sha256 as default digest for signing
+
+2007-01-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_ca.in: Really test sub-ca code, add basic constraints tests
+
+2007-01-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Fix makefile problem.
+
+2007-01-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool.c: Set num of bits before we generate the key.
+
+2007-01-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cms.c (hx509_cms_create_signed_1): use hx509_cert_binary
+
+ * ks_p12.c (store_func): use hx509_cert_binary
+
+ * ks_file.c (store_func): use hx509_cert_binary
+
+ * cert.c (hx509_cert_binary): return binary encoded
+ certificate (DER format)
+
+2007-01-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ca.c (hx509_ca_tbs_subject_expand): new function.
+
+ * name.c (hx509_name_expand): if env is NULL, return directly
+
+ * test_ca.in: test template handling
+
+ * hx509.h: Add template flags.
+
+ * Makefile.am: clean out new files
+
+ * hxtool.c: Add certificate template processing, fix hx509_err
+ usage.
+
+ * hxtool-commands.in: Add certificate template processing.
+
+ * ca.c: Add certificate template processing. Fix return messages
+ from hx509_ca_tbs_add_eku.
+
+ * cert.c: Export more stuff from certificate.
+
+2007-01-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ca.c: update (c)
+
+ * ca.c: (hx509_ca_tbs_add_eku): filter out dups.
+
+ * hxtool.c: Add type email and add email eku when using option
+ --email.
+
+ * Makefile.am: add env.c
+
+ * name.c: Remove abort, add error handling.
+
+ * test_name.c: test name expansion
+
+ * name.c: add hx509_name_expand
+
+ * env.c: key-value pair help functions
+
+2007-01-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ca.c: Don't issue certs with subject DN that is NULL and have no
+ SANs
+
+ * print.c: Fix previous test.
+
+ * print.c: Check there is a SAN if subject DN is NULL.
+
+ * test_ca.in: test email, null subject dn
+
+ * hxtool.c: Allow setting parameters to private key generation.
+
+ * hx_locl.h: Allow setting parameters to private key generation.
+
+ * crypto.c: Allow setting parameters to private key generation.
+
+ * hxtool.c (eval_types): add jid if user gave one
+
+ * hxtool-commands.in (certificate-sign): add --jid
+
+ * ca.c (hx509_ca_tbs_add_san_jid): Allow adding
+ id-pkix-on-xmppAddr OtherName.
+
+ * print.c: Print id-pkix-on-xmppAddr OtherName.
+
+2007-01-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * no random, no RSA/DH tests
+
+ * hxtool.c (info): print status of random generator
+
+ * Makefile.am: remove files created by tests
+
+ * error.c: constify
+
+ * name.c: constify
+
+ * revoke.c: constify
+
+ * hx_locl.h: constify
+
+ * keyset.c: constify
+
+ * ks_p11.c: constify
+
+ * hx_locl.h: make printinfo char * argument const.
+
+ * cms.c: move _hx509_set_digest_alg from cms.c to crypto.c since
+ its only used there.
+
+ * crypto.c: remove no longer used stuff, move set_digest_alg here
+ from cms.c since its only used here.
+
+ * Makefile.am: add data/test-nopw.p12 to EXTRA_DIST
+
+2007-01-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * print.c: BasicConstraints vs criticality bit is complicated and
+ not really possible to evaluate on its own, silly RFC3280.
+
+ * ca.c: Make basicConstraints critical if this is a CA.
+
+ * print.c: fix the version vs extension test
+
+ * print.c: More validation checks.
+
+ * name.c (hx509_name_cmp): add
+
+2007-01-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_p11.c (collect_private_key): Missing CKA_MODULUS is ok
+ too (XXX why should these be fetched given they are not used).
+
+ * test_ca.in: rename all files to PEM files, since that is what
+ they are.
+
+ * hxtool.c: copy out the key with the self signed CA cert
+
+ * Factor out private key operation out of the signing, operations,
+ support import, export, and generation of private keys. Add
+ support for writing PEM and PKCS12 files with private keys in them.
+
+ * data/gen-req.sh: Generate a no password pkcs12 file.
+
+2007-01-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cms.c: Check for internal ASN1 encoder error.
+
+2007-01-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Drop most of the pkcs11 files.
+
+ * test_ca.in: test reissueing ca certificate (xxx time
+ validAfter).
+
+ * hxtool.c: Allow setting serialNumber (needed for reissuing
+ certificates) Change --key argument to --out-key.
+
+ * hxtool-commands.in (issue-certificate): Allow setting
+ serialNumber (needed for reissuing certificates), Change --key
+ argument to --out-key.
+
+ * ref: Replace with Marcus Brinkmann of g10 Code GmbH pkcs11
+ headerfile that is compatible with GPL (file taken from scute)
+
+2007-01-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_ca.in: Test to generate key and use them.
+
+ * hxtool.c: handle other keys the pkcs10 requested keys
+
+ * hxtool-commands.in: add generate key commands
+
+ * req.c (_hx509_request_to_pkcs10): PKCS10 needs to have a subject
+
+ * hxtool-commands.in: Spelling.
+
+ * ca.c (hx509_ca_tbs_set_proxy): allow negative pathLenConstraint
+ to signal no limit
+
+ * ks_file.c: Try all formats on the binary file before giving up,
+ this way we can handle binary rsa keys too.
+
+ * data/key2.der: new test key
+
+2007-01-04 David Love <fx@gnu.org>
+
+ * Makefile.am (hxtool_LDADD): Add libasn1.la
+
+ * hxtool.c (pcert_verify): Fix format string.
+
+2006-12-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool.c: Allow setting path length
+
+ * cert.c: Fix test for proxy certs chain length, it was too
+ restrictive.
+
+ * data: regen
+
+ * data/openssl.cnf: (proxy_cert) make length 0
+
+ * test_ca.in: Issue a long living cert.
+
+ * hxtool.c: add --lifetime to ca command.
+
+ * hxtool-commands.in: add --lifetime to ca command.
+
+ * ca.c: allow setting notBefore and notAfter.
+
+ * test_ca.in: Test generation of proxy certificates.
+
+ * ca.c: Allow generation of proxy certificates, always include
+ BasicConstraints, fix error codes.
+
+ * hxtool.c: Allow generation of proxy certificates.
+
+ * test_name.c: make hx509_parse_name take a hx509_context.
+
+ * name.c: Split building RDN to a separate function.
+
+2006-12-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: clean test_ca files.
+
+ * test_ca.in: test issuing self-signed and CA certificates.
+
+ * hxtool.c: Add bits to allow issuing self-signed and CA
+ certificates.
+
+ * hxtool-commands.in: Add bits to allow issuing self-signed and CA
+ certificates.
+
+ * ca.c: Add bits to allow issuing CA certificates.
+
+ * revoke.c: use new OCSPSigning.
+
+ * ca.c: Add Subject Key Identifier.
+
+ * ca.c: Add Authority Key Identifier.
+
+ * cert.c: Locally export _hx509_find_extension_subject_key_id.
+ Handle AuthorityKeyIdentifier where only authorityCertSerialNumber
+ and authorityCertSerialNumber is set.
+
+ * hxtool-commands.in: Add dnsname and rfc822 SANs.
+
+ * test_ca.in: Test dnsname and rfc822 SANs.
+
+ * ca.c: Add dnsname and rfc822 SANs.
+
+ * hxtool.c: Add dnsname and rfc822 SANs.
+
+ * test_ca.in: test adding eku, ku and san to the
+ certificate (https and pk-init)
+
+ * hxtool.c: Add eku, ku and san to the certificate.
+
+ * ca.c: Add eku, ku and san to the certificate.
+
+ * hxtool-commands.in: Add --type and --pk-init-principal
+
+ * ocsp.asn1: remove id-kp-OCSPSigning, its in rfc2459.asn1 now
+
+2006-12-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ca.c: Add KeyUsage extension.
+
+ * Makefile.am: add ca.c, add sign-certificate tests.
+
+ * crypto.c: Add _hx509_create_signature_bitstring.
+
+ * hxtool-commands.in: Add the sign-certificate tool.
+
+ * hxtool.c: Add the sign-certificate tool.
+
+ * cert.c: Add HX509_QUERY_OPTION_KU_KEYCERTSIGN.
+
+ * hx509.h: Add hx509_ca_tbs and HX509_QUERY_OPTION_KU_KEYCERTSIGN.
+
+ * test_ca.in: Basic test of generating a pkcs10 request, signing
+ it and verifying the chain.
+
+ * ca.c: Naive certificate signer.
+
+2006-12-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool.c: add hxtool_hex
+
+2006-12-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: use top_builddir for libasn1.la
+
+2006-12-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool.c (print_certificate): print serial number.
+
+ * name.c (no): add S=stateOrProvinceName
+
+2006-12-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * crypto.c (_hx509_private_key_assign_rsa): set a default sig alg
+
+ * ks_file.c (try_decrypt): pass down AlgorithmIdentifier that key
+ uses to do sigatures so there is no need to hardcode RSA into this
+ function.
+
+2006-12-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_file.c: Pass filename to the parse functions and use it in
+ the error messages
+
+ * test_chain.in: test proxy cert (third level)
+
+ * hx509_err.et: fix errorstring for PROXY_CERT_NAME_WRONG
+
+ * data: regen
+
+ * Makefile.am: EXTRA_DIST: add
+ data/proxy10-child-child-test.{key,crt}
+
+ * data/gen-req.sh: Fix names and restrictions on the proxy
+ certificates
+
+ * cert.c: Clairfy and make proxy cert handling work for multiple
+ levels, before it was too restrictive. More helpful error message.
+
+2006-12-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cert.c (check_key_usage): tell what keyusages are missing
+
+ * print.c: Split OtherName printing code to a oid lookup and print
+ function.
+
+ * print.c (Time2string): print hour as hour not min
+
+ * Makefile.am: CLEANFILES += test
+
+2006-12-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am (EXTRA_DIST): add data/pkinit-proxy* files
+
+ * Makefile.am (EXTRA_DIST): add tst-crypto* files
+
+ * cert.c (hx509_query_match_issuer_serial): make a copy of the
+ data
+
+ * cert.c (hx509_query_match_issuer_serial): allow matching on
+ issuer and serial num
+
+ * cert.c (_hx509_calculate_path): add flag to allow leaving out
+ trust anchor
+
+ * cms.c (hx509_cms_create_signed_1): when building the path, omit
+ the trust anchors.
+
+ * crypto.c (rsa_create_signature): Abort when signature is longer,
+ not shorter.
+
+ * cms.c: Provide time to _hx509_calculate_path so we don't send no
+ longer valid certs to our peer.
+
+ * cert.c (find_parent): when checking for certs and its not a
+ trust anchor, require time be in range.
+ (_hx509_query_match_cert): Add time validity-testing to query mask
+
+ * hx_locl.h: add time validity-testing to query mask
+
+ * test_cms.in: Tests for CMS SignedData with incomplete chain from
+ the signer.
+
+2006-11-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cms.c (hx509_cms_verify_signed): specify what signature we
+ failed to verify
+
+ * Makefile.am: Depend on LIB_com_err for AIX.
+
+ * keyset.c: Remove anther strndup that causes AIX to fall over.
+
+ * cert.c: Don't check the trust anchors expiration time since they
+ are transported out of band, from RFC3820.
+
+ * cms.c: sprinkle more error strings
+
+ * crypto.c: sprinkle more error strings
+
+ * hxtool.c: use unsigned int as counter to fit better with the
+ asn1 compiler
+
+ * crypto.c: use unsigned int as counter to fit better with the
+ asn1 compiler
+
+2006-11-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cms.c: Remove trailing white space.
+
+ * crypto.c: rewrite comment to make more sense
+
+ * crypto.c (hx509_crypto_select): check sig_algs[j]->key_oid
+
+ * hxtool-commands.in (crypto-available): add --type
+
+ * crypto.c (hx509_crypto_available): let alg pass if its keyless
+
+ * hxtool-commands.in: Expand crypto-select
+
+ * cms.c: Rename hx509_select to hx509_crypto_select.
+
+ * hxtool-commands.in: Add crypto-select and crypto-available.
+
+ * hxtool.c: Add crypto-select and crypto-available.
+
+ * crypto.c (hx509_crypto_available): use right index.
+ (hx509_crypto_free_algs): new function
+
+ * crypto.c (hx509_crypto_select): improve
+ (hx509_crypto_available): new function
+
+2006-11-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cert.c: Sprinkle more error string and hx509_contexts.
+
+ * cms.c: Sprinkle more error strings.
+
+ * crypto.c: Sprinkle error string and hx509_contexts.
+
+ * crypto.c: Add some more comments about how this works.
+
+ * crypto.c (hx509_select): new function.
+
+ * Makefile.am: add peer.c
+
+ * hxtool.c: Update hx509_cms_create_signed_1.
+
+ * hx_locl.h: add struct hx509_peer_info
+
+ * peer.c: Allow selection of digest/sig-alg
+
+ * cms.c: Allow selection of a better digest using hx509_peer_info.
+
+ * revoke.c: Handle that _hx509_verify_signature takes a context.
+
+ * cert.c: Handle that _hx509_verify_signature takes a context.
+
+2006-11-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cms.c: Sprinkle error strings.
+
+ * crypto.c: Sprinkle context and error strings.
+
+2006-11-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * name.c: Handle printing and parsing raw oids in name.
+
+2006-11-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cert.c (_hx509_calculate_path): allow to calculate optimistic
+ path when we don't know the trust anchors, just follow the chain
+ upward until we no longer find a parent or we hit the max limit.
+
+ * cms.c (hx509_cms_create_signed_1): provide a best effort path to
+ the trust anchors to be stored in the SignedData packet, if find
+ parents until trust anchor or max length.
+
+ * data: regen
+
+ * data/gen-req.sh: Build pk-init proxy cert.
+
+2006-11-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * error.c (hx509_get_error_string): Put ", " between strings in
+ error message.
+
+2006-11-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * data/openssl.cnf: Change realm to TEST.H5L.SE
+
+2006-11-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * revoke.c: Sprinkle error strings.
+
+2006-11-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hx_locl.h: add context variable to cmp function.
+
+ * cert.c (hx509_query_match_cmp_func): allow setting the match
+ function.
+
+2006-10-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_p11.c: Return less EINVAL.
+
+ * hx509_err.et: add more pkcs11 errors
+
+ * hx509_err.et: more error-codes
+
+ * revoke.c: Return less EINVAL.
+
+ * ks_dir.c: sprinkel more hx509_set_error_string
+
+ * ks_file.c: Return less EINVAL.
+
+ * hxtool.c: Pass in context to _hx509_parse_private_key.
+
+ * ks_file.c: Sprinkle more hx509_context so we can return propper
+ errors.
+
+ * hx509_err.et: add HX509_PARSING_KEY_FAILED
+
+ * crypto.c: Sprinkle more hx509_context so we can return propper
+ errors.
+
+ * collector.c: No more EINVAL.
+
+ * hx509_err.et: add HX509_LOCAL_ATTRIBUTE_MISSING
+
+ * cert.c (hx509_cert_get_base_subject): one less EINVAL
+ (_hx509_cert_private_decrypt): one less EINVAL
+
+2006-10-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * collector.c: indent
+
+ * hxtool.c: Try to not leak memory.
+
+ * req.c: clean memory before free
+
+ * crypto.c (_hx509_private_key2SPKI): indent
+
+ * req.c: Try to not leak memory.
+
+2006-10-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_crypto.in: Read 50 kilobyte random data
+
+ * revoke.c: Try to not leak memory.
+
+ * hxtool.c: Try to not leak memory.
+
+ * crypto.c (hx509_crypto_destroy): free oid.
+
+ * error.c: Clean error string on failure just to make sure.
+
+ * cms.c: Try to not leak memory (again).
+
+ * hxtool.c: use a sensable content type
+
+ * cms.c: Try harder to free certificate.
+
+2006-10-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add make check data.
+
+2006-10-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_p11.c (p11_list_keys): make element of search_data[0]
+ constants and set them later
+
+ * Makefile.am: Add more files.
+
+2006-10-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_file.c: set ret, remember to free ivdata
+
+2006-10-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hx_locl.h: Include <parse_bytes.h>.
+
+ * test_crypto.in: Test random-data.
+
+ * hxtool.c: RAND_bytes() return 1 for cryptographic strong data,
+ check for that.
+
+ * Makefile.am: clean random-data
+
+ * hxtool.c: Add random-data command, use sl_slc_help.
+
+ * hxtool-commands.in: Add random-data.
+
+ * ks_p12.c: Remember to release certs.
+
+ * ks_p11.c: Remember to release certs.
+
+2006-10-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * prefix der primitives with der_
+
+ * lock.c: Match the prompt type PROMPT exact.
+
+ * hx_locl.h: Drop heim_any.h
+
+2006-10-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_p11.c (p11_release_module): j needs to be used as inter loop
+ index. From Douglas Engert.
+
+ * ks_file.c (parse_rsa_private_key): try all passwords and
+ prompter.
+
+2006-10-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_*.in: Parameterise the invocation of hxtool, so we can make
+ it run under TESTS_ENVIRONMENT. From Andrew Bartlett
+
+2006-10-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_crypto.in: Put all test stuck at 2006-09-25 since all their
+ chains where valied then.
+
+ * hxtool.c: Implement --time= option.
+
+ * hxtool-commands.in: Add option time.
+
+ * Makefile.am: test_name is a PROGRAM_TESTS
+
+ * ks_p11.c: Return HX509_PKCS11_NO_SLOT when there are no slots
+ and HX509_PKCS11_NO_TOKEN when there are no token. For use in PAM
+ modules that want to detect when to use smartcard login and when
+ not to. Patched based on code from Douglas Engert.
+
+ * hx509_err.et: Add new pkcs11 related errors in a new section:
+ keystore related error. Patched based on code from Douglas
+ Engert.
+
+2006-10-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Make depenency for slc built files just like
+ everywhere else.
+
+ * cert.c: Add all openssl algs and init asn1 et
+
+2006-10-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_file.c (parse_rsa_private_key): free type earlier.
+
+ * ks_file.c (parse_rsa_private_key): free type after use
+
+ * name.c (_hx509_Name_to_string): remove dup const
+
+2006-10-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add more libs to libhx509
+
+2006-10-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_p11.c: Fix double free's, NULL ptr de-reference, and conform
+ better to pkcs11. From Douglas Engert.
+
+ * ref: remove ^M, it breaks solaris 10s cc. From Harald Barth
+
+2006-09-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_crypto.in: Bleichenbacher bad cert from Ralf-Philipp
+ Weinmann and Andrew Pyshkin, pad right.
+
+ * data: starfield test root cert and Ralf-Philipp and Andreis
+ correctly padded bad cert
+
+2006-09-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_crypto.in: Add test for yutaka certs.
+
+ * cert.c: Add a strict rfc3280 verification flag. rfc3280 requires
+ certificates to have KeyUsage.keyCertSign if they are to be used
+ for signing of certificates, but the step in the verifiation is
+ optional.
+
+ * hxtool.c: Improve printing and error reporting.
+
+2006-09-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_crypto.in,Makefile.am,data/bleichenbacher-{bad,good}.pem:
+ test bleichenbacher from eay
+
+2006-09-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool.c: Make common function for all getarg_strings and
+ hx509_certs_append commonly used.
+
+ * cms.c: HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT is a negative
+ flag, treat it was such.
+
+2006-09-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * req.c: Use the new add_GeneralNames function.
+
+ * hx509.h: Add HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT.
+
+ * ks_p12.c: Adapt to new signature of hx509_cms_unenvelope.
+
+ * hxtool.c: Adapt to new signature of hx509_cms_unenvelope.
+
+ * cms.c: Allow passing in encryptedContent and flag. Add new flag
+ HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT.
+
+2006-09-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_p11.c: cast void * to char * when using it for %s formating
+ in printf.
+
+ * name.c: New function _hx509_Name_to_string.
+
+2006-09-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_file.c: Sprinkle error messages.
+
+ * cms.c: Sprinkle even more error messages.
+
+ * cms.c: Sprinkle some error messages.
+
+ * cms.c (find_CMSIdentifier): only free string when we allocated
+ one.
+
+ * ks_p11.c: Don't build most of the pkcs11 module if there are no
+ dlopen().
+
+2006-09-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cms.c (hx509_cms_unenvelope): try to save the error string from
+ find_CMSIdentifier so we have one more bit of information what
+ went wrong.
+
+ * hxtool.c: More pretty printing, make verify_signed return the
+ error string from the library.
+
+ * cms.c: Try returning what certificates failed to parse or be
+ found.
+
+ * ks_p11.c (p11_list_keys): fetch CKA_LABEL and use it to set the
+ friendlyname for the certificate.
+
+2006-09-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * crypto.c: check that there are no extra bytes in the checksum
+ and that the parameters are NULL or the NULL-type. All to avoid
+ having excess data that can be used to fake the signature.
+
+ * hxtool.c: print keyusage
+
+ * print.c: add hx509_cert_keyusage_print, simplify oid printing
+
+ * cert.c: add _hx509_cert_get_keyusage
+
+ * ks_p11.c: keep one session around for the whole life of the keyset
+
+ * test_query.in: tests more selection
+
+ * hxtool.c: improve pretty printing in print and query
+
+ * hxtool{.c,-commands.in}: add selection on KU and printing to query
+
+ * test_cms.in: Add cms test for digitalSignature and
+ keyEncipherment certs.
+
+ * name.c (no): Add serialNumber
+
+ * ks_p11.c (p11_get_session): return better error messages
+
+2006-09-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ref: update to pkcs11 reference files 2.20
+
+ * ks_p11.c: add more mechflags
+
+ * name.c (no): add OU and sort
+
+ * revoke.c: pass context to _hx509_create_signature
+
+ * ks_p11.c (p11_printinfo): print proper plural s
+
+ * ks_p11.c: save the mechs supported when initing the token, print
+ them in printinfo.
+
+ * hx_locl.h: Include <parse_units.h>.
+
+ * cms.c: pass context to _hx509_create_signature
+
+ * req.c: pass context to _hx509_create_signature
+
+ * keyset.c (hx509_certs_info): print information about the keyset.
+
+ * hxtool.c (pcert_print) print keystore info when --info flag is
+ given.
+
+ * hxtool-commands.in: Add hxtool print --info.
+
+ * test_query.in: Test hxtool print --info.
+
+ * hx_locl.h (hx509_keyset_ops): add printinfo
+
+ * crypto.c: Start to hang the private key operations of the
+ private key, pass hx509_context to create_checksum.
+
+2006-05-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_p11.c: Iterate over all slots, not just the first/selected
+ one.
+
+2006-05-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cert.c: Add release function for certifiates so backend knowns
+ when its no longer used.
+
+ * ks_p11.c: Add reference counting on certifiates, push out
+ CK_SESSION_HANDLE from slot.
+
+ * cms.c: sprinkle more hx509_clear_error_string
+
+2006-05-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_p11.c: Sprinkle some hx509_set_error_strings
+
+2006-05-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool.c: Avoid shadowing.
+
+ * revoke.c: Avoid shadowing.
+
+ * ks_file.c: Avoid shadowing.
+
+ * cert.c: Avoid shadowing.
+
+2006-05-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * lock.c (hx509_prompt_hidden): reshuffle to avoid gcc warning
+
+ * hx509.h: Reshuffle the prompter types, remove the hidden field.
+
+ * lock.c (hx509_prompt_hidden): return if the prompt should be
+ hidden or not
+
+ * revoke.c (hx509_revoke_free): allow free of NULL.
+
+2006-05-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_file.c (file_init): Avoid shadowing ret (and thus avoiding
+ crashing).
+
+ * ks_dir.c: Implement DIR: caches useing FILE: caches.
+
+ * ks_p11.c: Catch more errors.
+
+2006-05-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * crypto.c (hx509_crypto_encrypt): free correctly in error
+ path. From Andrew Bartlett.
+
+ * crypto.c: If RAND_bytes fails, then we will attempt to
+ double-free crypt->key.data. From Andrew Bartlett.
+
+2006-05-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * name.c: Rename u_intXX_t to uintXX_t
+
+2006-05-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * TODO: More to do about the about the PKCS11 code.
+
+ * ks_p11.c: Use the prompter from the lock function.
+
+ * lock.c: Deal with that hx509_prompt.reply is no longer a
+ pointer.
+
+ * hx509.h: Make hx509_prompt.reply not a pointer.
+
+2006-05-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * keyset.c: Sprinkle setting error strings.
+
+ * crypto.c: Sprinkle setting error strings.
+
+ * collector.c: Sprinkle setting error strings.
+
+ * cms.c: Sprinkle setting error strings.
+
+2006-05-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_name.c: renamed one error code
+
+ * name.c: renamed one error code
+
+ * ks_p11.c: _hx509_set_cert_attribute changed signature
+
+ * hxtool.c (pcert_print): use hx509_err so I can test it
+
+ * error.c (hx509_set_error_stringv): clear errors on malloc
+ failure
+
+ * hx509_err.et: Add some more errors
+
+ * cert.c: Sprinkle setting error strings.
+
+ * cms.c: _hx509_path_append changed signature.
+
+ * revoke.c: changed signature of _hx509_check_key_usage
+
+ * keyset.c: changed signature of _hx509_query_match_cert
+
+ * hx509.h: Add support for error strings.
+
+ * cms.c: changed signature of _hx509_check_key_usage
+
+ * Makefile.am: ibhx509_la_files += error.c
+
+ * ks_file.c: Sprinkel setting error strings.
+
+ * cert.c: Sprinkel setting error strings.
+
+ * hx_locl.h: Add support for error strings.
+
+ * error.c: Add string error handling functions.
+
+ * keyset.c (hx509_certs_init): pass the right error code back
+
+2006-04-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * revoke.c: Revert previous patch.
+ (hx509_ocsp_verify): new function that returns the expiration of
+ certificate in ocsp data-blob
+
+ * cert.c: Reverse previous patch, lets do it another way.
+
+ * cert.c (hx509_revoke_verify): update usage
+
+ * revoke.c: Make compile.
+
+ * revoke.c: Add the expiration time the crl/ocsp info expire
+
+ * name.c: Add hx509_name_is_null_p
+
+ * cert.c: remove _hx509_cert_private_sigature
+
+2006-04-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * name.c: Expose more of Name.
+
+ * hxtool.c (main): add missing argument to printf
+
+ * data/openssl.cnf: Add EKU for the KDC certificate
+
+ * cert.c (hx509_cert_get_base_subject): reject un-canon proxy
+ certs, not the reverse
+ (add_to_list): constify and fix argument order to
+ copy_octet_string
+ (hx509_cert_find_subjectAltName_otherName): make work
+
+2006-04-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * data/{pkinit,kdc}.{crt,key}: pkinit certificates
+
+ * data/gen-req.sh: Generate pkinit certificates.
+
+ * data/openssl.cnf: Add pkinit glue.
+
+ * cert.c (hx509_verify_hostname): implement stub function
+
+2006-04-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * TODO: CRL delta support
+
+2006-04-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * data/.cvsignore: ignore leftover from OpenSSL cert generation
+
+ * hx509_err.et: Add name malformated error
+
+ * name.c (hx509_parse_name): don't abort on error, rather return
+ error
+
+ * test_name.c: Test failure parsing name.
+
+ * cert.c: When verifying certificates, store subject basename for
+ later consumption.
+
+ * test_name.c: test to parse and print name and check that they
+ are the same.
+
+ * name.c (hx509_parse_name): fix length argument to printf string
+
+ * name.c (hx509_parse_name): fix length argument to stringtooid, 1
+ too short.
+
+ * cert.c: remove debug printf's
+
+ * name.c (hx509_parse_name): make compile pre c99
+
+ * data/gen-req.sh: OpenSSL have a serious issue of user confusion
+ -subj in -ca takes the arguments in LDAP order. -subj for x509
+ takes it in x509 order.
+
+ * cert.c (hx509_verify_path): handle the case where the where two
+ proxy certs in a chain.
+
+ * test_chain.in: enable two proxy certificates in a chain test
+
+ * test_chain.in: tests proxy certificates
+
+ * data: re-gen
+
+ * data/gen-req.sh: build proxy certificates
+
+ * data/openssl.cnf: add def for proxy10_cert
+
+ * hx509_err.et: Add another proxy certificate error.
+
+ * cert.c (hx509_verify_path): Need to mangle name to remove the CN
+ of the subject, copying issuer only works for one level but is
+ better then doing no checking at all.
+
+ * hxtool.c: Add verify --allow-proxy-certificate.
+
+ * hxtool-commands.in: add verify --allow-proxy-certificate
+
+ * hx509_err.et: Add proxy certificate errors.
+
+ * cert.c: Fix comment about subject name of proxy certificate.
+
+ * test_chain.in: tests for proxy certs
+
+ * data/gen-req.sh: gen proxy and non-proxy tests certificates
+
+ * data/openssl.cnf: Add definition for proxy certs
+
+ * data/*proxy-test.*: Add proxy certificates
+
+ * cert.c (hx509_verify_path): verify proxy certificate have no san
+ or ian
+
+ * cert.c (hx509_verify_set_proxy_certificate): Add
+ (*): rename policy cert to proxy cert
+
+ * cert.c: Initial support for proxy certificates.
+
+2006-04-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool.c: some error checking
+
+ * name.c: Switch over to asn1 generaed oids.
+
+ * TODO: merge with old todo file
+
+2006-04-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_query.in: make quiet
+
+ * test_req.in: SKIP test if there is no RSA support.
+
+ * hxtool.c: print dh method too
+
+ * test_chain.in: SKIP test if there is no RSA support.
+
+ * test_cms.in: SKIP test if there is no RSA support.
+
+ * test_nist.in: SKIP test if there is no RSA support.
+
+2006-04-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool-commands.in: Allow passing in pool and anchor to
+ signedData
+
+ * hxtool.c: Allow passing in pool and anchor to signedData
+
+ * test_cms.in: Test that certs in signed data is picked up.
+
+ * hx_locl.h: Expose the path building function to internal
+ functions.
+
+ * cert.c: Expose the path building function to internal functions.
+
+ * hxtool-commands.in: cms-envelope: Add support for choosing the
+ encryption type
+
+ * hxtool.c (cms_create_enveloped): Add support for choosing the
+ encryption type
+
+ * test_cms.in: Test generating des-ede3 aes-128 aes-256 enveloped
+ data
+
+ * crypto.c: Add names to cipher types.
+
+ * cert.c (hx509_query_match_friendly_name): fix return value
+
+ * data/gen-req.sh: generate tests for enveloped data using
+ des-ede3 and aes256
+
+ * test_cms.in: add tests for enveloped data using des-ede3 and
+ aes256
+
+ * cert.c (hx509_query_match_friendly_name): New function.
+
+2006-04-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_p11.c: Add support for parsing slot-number.
+
+ * crypto.c (oid_private_rc2_40): simply
+
+ * crypto.c: Use oids from asn1 generator.
+
+ * ks_file.c (file_init): reset length when done with a part
+
+ * test_cms.in: check with test.combined.crt.
+
+ * data/gen-req.sh: Create test.combined.crt.
+
+ * test_cms.in: Test signed data using keyfile that is encrypted.
+
+ * ks_file.c: Remove (commented out) debug printf
+
+ * ks_file.c (parse_rsa_private_key): use EVP_get_cipherbyname
+
+ * ks_file.c (parse_rsa_private_key): make working for one
+ password.
+
+ * ks_file.c (parse_rsa_private_key): Implement enought for
+ testing.
+
+ * hx_locl.h: Add <ctype.h>
+
+ * ks_file.c: Add glue code for PEM encrypted password files.
+
+ * test_cms.in: Add commeted out password protected PEM file,
+ remove password for those tests that doesn't need it.
+
+ * test_cms.in: adapt test now that we can use any certificate and
+ trust anchor
+
+ * collector.c: handle PEM RSA PRIVATE KEY files
+
+ * cert.c: Remove unused function.
+
+ * ks_dir.c: move code here from ks_file.c now that its no longer
+ used.
+
+ * ks_file.c: Add support for parsing unencrypted RSA PRIVATE KEY
+
+ * crypto.c: Handle rsa private keys better.
+
+2006-04-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool.c: Use hx509_cms_{,un}wrap_ContentInfo
+
+ * cms.c: Make hx509_cms_{,un}wrap_ContentInfo usable in asn1
+ un-aware code.
+
+ * cert.c (hx509_verify_path): if trust anchor is not self signed,
+ don't check sig From Douglas Engert.
+
+ * test_chain.in: test "sub-cert -> sub-ca"
+
+ * crypto.c: Use the right length for the sha256 checksums.
+
+2006-04-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * crypto.c: Fix breakage from sha256 code.
+
+ * crypto.c: Add SHA256 support, and symbols for the other new
+ SHA-2 types.
+
+2006-04-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_cms.in: test rc2-40 rc2-64 rc2-128 enveloped data
+
+ * data/test-enveloped-rc2-{40,64,128}: add tests cases for rc2
+
+ * cms.c: Update prototypes changes for hx509_crypto_[gs]et_params.
+
+ * crypto.c: Break out the parameter handling code for encrypting
+ data to handle RC2. Needed for Windows 2k pk-init support.
+
+2006-04-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Split libhx509_la_SOURCES into build file and
+ distributed files so we can avoid building prototypes for
+ build-files.
+
+2006-04-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * TODO: split certificate request into pkcs10 and CRMF
+
+ * hxtool-commands.in: Add nonce flag to ocsp-fetch
+
+ * hxtool.c: control sending nonce
+
+ * hxtool.c (request_create): store the request in a file, no in
+ bitbucket.
+
+ * cert.c: expose print_cert_subject internally
+
+ * hxtool.c: Add ocsp_print.
+
+ * hxtool-commands.in: New command "ocsp-print".
+
+ * hx_locl.h: Include <hex.h>.
+
+ * revoke.c (verify_ocsp): require issuer to match too.
+ (free_ocsp): new function
+ (hx509_revoke_ocsp_print): new function, print ocsp reply
+
+ * Makefile.am: build CRMF files
+
+ * data/key.der: needed for cert request test
+
+ * test_req.in: adapt to rename of pkcs10-create to request-create
+
+ * hxtool.c: adapt to rename of pkcs10-create to request-create
+
+ * hxtool-commands.in: Rename pkcs10-create to request-create
+
+ * crypto.c: (_hx509_parse_private_key): Avoid crashing on bad input.
+
+ * hxtool.c (pkcs10_create): use opt->subject_string
+
+ * hxtool-commands.in: Add pkcs10-create --subject
+
+ * Makefile.am: Add test_req to tests.
+
+ * test_req.in: Test for pkcs10 commands.
+
+ * name.c (hx509_parse_name): new function.
+
+ * hxtool.c (pkcs10_create): implement
+
+ * hxtool-commands.in (pkcs10-create): Add arguments
+
+ * crypto.c: Add _hx509_private_key2SPKI and support
+ functions (only support RSA for now).
+
+2006-04-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool-commands.in: Add pkcs10-create command.
+
+ * hx509.h: Add hx509_request.
+
+ * TODO: more stuff
+
+ * Makefile.am: Add req.c
+
+ * req.c: Create certificate requests, prototype converts the
+ request in a pkcs10 packet.
+
+ * hxtool.c: Add pkcs10_create
+
+ * name.c (hx509_name_copy): new function.
+
+2006-04-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * TODO: fill out what do
+
+ * hxtool-commands.in: add pkcs10-print
+
+ * hx_locl.h: Include <pkcs10_asn1.h>.
+
+ * pkcs10.asn1: PKCS#10
+
+ * hxtool.c (pkcs10_print): new function.
+
+ * test_chain.in: test ocsp keyhash
+
+ * data: generate ocsp keyhash version too
+
+ * revoke.c (load_ocsp): test that we got back a BasicReponse
+
+ * ocsp.asn1: Add asn1_id_pkix_ocsp*.
+
+ * Makefile.am: Add asn1_id_pkix_ocsp*.
+
+ * cert.c: Add HX509_QUERY_MATCH_KEY_HASH_SHA1
+
+ * hx_locl.h: Add HX509_QUERY_MATCH_KEY_HASH_SHA1
+
+ * revoke.c: Support OCSPResponderID.byKey, indent.
+
+ * revoke.c (hx509_ocsp_request): Add nonce to ocsp request.
+
+ * hxtool.c: Add nonce to ocsp request.
+
+ * test_chain.in: Added crl tests
+
+ * data/nist-data: rename missing-crl to missing-revoke
+
+ * data: make ca use openssl ca command so we can add ocsp tests,
+ and regen certs
+
+ * test_chain.in: Add revoked ocsp cert test
+
+ * cert.c: rename missing-crl to missing-revoke
+
+ * revoke.c: refactor code, fix a un-init-ed variable
+
+ * test_chain.in: rename missing-crl to missing-revoke add ocsp
+ tests
+
+ * test_cms.in: rename missing-crl to missing-revoke
+
+ * hxtool.c: rename missing-crl to missing-revoke
+
+ * hxtool-commands.in: rename missing-crl to missing-revoke
+
+ * revoke.c: Plug one memory leak.
+
+ * revoke.c: Renamed generic CRL related errors.
+
+ * hx509_err.et: Comments and renamed generic CRL related errors
+
+ * revoke.c: Add ocsp checker.
+
+ * ocsp.asn1: Add id-kp-OCSPSigning
+
+ * hxtool-commands.in: add url-path argument to ocsp-fetch
+
+ * hxtool.c: implement ocsp-fetch
+
+ * cert.c: Use HX509_DEFAULT_OCSP_TIME_DIFF.
+
+ * hx_locl.h: Add ocsp_time_diff to hx509_context
+
+ * crypto.c (_hx509_verify_signature_bitstring): new function,
+ commonly use when checking certificates
+
+ * cms.c (hx509_cms_envelope_1): check for internal ASN.1 encoder
+ error
+
+ * cert.c: Add ocsp glue, use new
+ _hx509_verify_signature_bitstring, add eku checking function.
+
+2006-03-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add id_kp_OCSPSigning.x
+
+ * revoke.c: Pick out certs in ocsp response
+
+ * TODO: list of stuff to verify
+
+ * revoke.c: Add code to load OCSPBasicOCSPResponse files, reload
+ crl when its changed on disk.
+
+ * cert.c: Update for ocsp merge. handle building path w/o
+ subject (using subject key id)
+
+ * ks_p12.c: _hx509_map_file changed prototype.
+
+ * file.c: _hx509_map_file changed prototype, returns struct stat
+ if requested.
+
+ * ks_file.c: _hx509_map_file changed prototype.
+
+ * hxtool.c: Add stub for ocsp-fetch, _hx509_map_file changed
+ prototype, add ocsp parsing to verify command.
+
+ * hx_locl.h: rename HX509_CTX_CRL_MISSING_OK to
+ HX509_CTX_VERIFY_MISSING_OK now that we have OCSP glue
+
+2006-03-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hx_locl.h: Add <krb5-types.h> to make it compile on Solaris,
+ from Alex V. Labuta.
+
+2006-03-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * crypto.c (_hx509_pbe_decrypt): try all passwords, not just the
+ first one.
+
+2006-03-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * print.c (check_altName): Print the othername oid.
+
+ * crypto.c: Manual page claims RSA_public_decrypt will return -1
+ on error, lets check for that
+
+ * crypto.c (_hx509_pbe_decrypt): also try the empty password
+
+ * collector.c (match_localkeyid): no need to add back the cert to
+ the cert pool, its already there.
+
+ * crypto.c: Add REQUIRE_SIGNER
+
+ * cert.c (hx509_cert_free): ok to free NULL
+
+ * hx509_err.et: Add new error code SIGNATURE_WITHOUT_SIGNER.
+
+ * name.c (_hx509_name_ds_cmp): make DirectoryString case
+ insenstive
+ (hx509_name_to_string): less spacing
+
+ * cms.c: Check for signature error, check consitency of error
+
+2006-03-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * collector.c (_hx509_collector_alloc): handle errors
+
+ * cert.c (hx509_query_alloc): allocate slight more more then a
+ sizeof(pointer)
+
+ * crypto.c (_hx509_private_key_assign_key_file): ask for password
+ if nothing matches.
+
+ * cert.c: Expose more of the hx509_query interface.
+
+ * collector.c: hx509_certs_find is now exposed.
+
+ * cms.c: hx509_certs_find is now exposed.
+
+ * revoke.c: hx509_certs_find is now exposed.
+
+ * keyset.c (hx509_certs_free): allow free-ing NULL
+ (hx509_certs_find): expose
+ (hx509_get_one_cert): new function
+
+ * hxtool.c: hx509_certs_find is now exposed.
+
+ * hx_locl.h: Remove hx509_query, its exposed now.
+
+ * hx509.h: Add hx509_query.
+
+2006-02-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cert.c: Add exceptions for null (empty) subjectNames
+
+ * data/nist-data: Add some more name constraints tests.
+
+ * data/nist-data: Add some of the test from 4.13 Name Constraints.
+
+ * cert.c: Name constraits needs to be evaluated in block as they
+ appear in the certificates, they can not be joined to one
+ list. One example of this is:
+
+ - cert is cn=foo,dc=bar,dc=baz
+ - subca is dc=foo,dc=baz with name restriction dc=kaka,dc=baz
+ - ca is dc=baz with name restriction dc=baz
+
+ If the name restrictions are merged to a list, the certificate
+ will pass this test.
+
+2006-02-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cert.c: Handle more name constraints cases.
+
+ * crypto.c (dsa_verify_signature): if test if malloc failed
+
+2006-01-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cms.c: Drop partial pkcs12 string2key implementation.
+
+2006-01-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * data/nist-data: Add commited out DSA tests (they fail).
+
+ * data/nist-data: Add 4.2 Validity Periods.
+
+ * test_nist.in: Make less verbose to use.
+
+ * Makefile.am: Add test_nist_cert.
+
+ * data/nist-data: Add some more CRL-tests.
+
+ * test_nist.in: Print $id instead of . when running the tests.
+
+ * test_nist.in: Drop verifying certifiates, its done in another
+ test now.
+
+ * data/nist-data: fixup kill-rectangle leftovers
+
+ * data/nist-data: Drop verifying certifiates, its done in another
+ test now. Add more crl tests. comment out all unused tests.
+
+ * test_nist_cert.in: test parse all nist certs
+
+2006-01-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hx509_err.et: Add HX509_CRL_UNKNOWN_EXTENSION.
+
+ * revoke.c: Check for unknown extentions in CRLs and CRLEntries.
+
+ * test_nist.in: Parse new format to handle CRL info.
+
+ * test_chain.in: Add --missing-crl.
+
+ * name.c (hx509_unparse_der_name): Rename from hx509_parse_name.
+ (_hx509_unparse_Name): Add.
+
+ * hxtool-commands.in: Add --missing-crl to verify commands.
+
+ * hx509_err.et: Add CRL errors.
+
+ * cert.c (hx509_context_set_missing_crl): new function Add CRL
+ handling.
+
+ * hx_locl.h: Add HX509_CTX_CRL_MISSING_OK.
+
+ * revoke.c: Parse and verify CRLs (simplistic).
+
+ * hxtool.c: Parse CRL info.
+
+ * data/nist-data: Change format so we can deal with CRLs, also
+ note the test-id from PKITS.
+
+ * data: regenerate test
+
+ * data/gen-req.sh: use static-file to generate tests
+
+ * data/static-file: new file to use for commited tests
+
+ * test_cms.in: Use static file, add --missing-crl.
+
+2006-01-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * print.c: Its cRLReason, not cRLReasons.
+
+ * hxtool.c: Attach revoke context to verify context.
+
+ * data/nist-data: change syntax to make match better with crl
+ checks
+
+ * cert.c: Verify no certificates has been revoked with the new
+ revoke interface.
+
+ * Makefile.am: libhx509_la_SOURCES += revoke.c
+
+ * revoke.c: Add framework for handling CRLs.
+
+ * hx509.h: Add hx509_revoke_ctx.
+
+2006-01-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * delete crypto_headers.h, use global file instead.
+
+ * crypto.c (PBE_string2key): libdes now supports PKCS12_key_gen
+
+2006-01-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * crypto_headers.h: Need BN_is_negative too.
+
+2006-01-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ks_p11.c (p11_rsa_public_decrypt): since is wrong, don't provide
+ it. PKCS11 can't do public_decrypt, it support verify though. All
+ this doesn't matter, since the code never go though this path.
+
+ * crypto_headers.h: Provide glue to compile with less warnings
+ with OpenSSL
+
+2006-01-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Depend on LIB_des
+
+ * lock.c: Use "crypto_headers.h".
+
+ * crypto_headers.h: Include the two diffrent implementation of
+ crypto headers.
+
+ * cert.c: Use "crypto-headers.h". Load ENGINE configuration.
+
+ * crypto.c: Make compile with both OpenSSL and heimdal libdes.
+
+ * ks_p11.c: Add code for public key decryption (not supported yet)
+ and use "crypto-headers.h".
+
+
+2006-01-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * add a hx509_context where we can store configuration
+
+ * p11.c,Makefile.am: pkcs11 is now supported by library, remove
+ old files.
+
+ * ks_p11.c: more paranoid on refcount, set refcounter ealier,
+ reset pointers after free
+
+ * collector.c (struct private_key): remove temporary key data
+ storage, convert directly to a key
+ (match_localkeyid): match certificate and key using localkeyid
+ (match_keys): match certificate and key using _hx509_match_keys
+ (_hx509_collector_collect): rewrite to use match_keys and
+ match_localkeyid
+
+ * crypto.c (_hx509_match_keys): function that determins if a
+ private key matches a certificate, used when there is no
+ localkeyid.
+ (*) reset free pointer
+
+ * ks_file.c: Rewrite to use collector and mapping support
+ function.
+
+ * ks_p11.c (rsa_pkcs1_method): constify
+
+ * ks_p11.c: drop extra wrapping of p11_init
+
+ * crypto.c (_hx509_private_key_assign_key_file): use function to
+ extact rsa key
+
+ * cert.c: Revert previous, refcounter is unsigned, so it can never
+ be negative.
+
+ * cert.c (hx509_cert_ref): more refcount paranoia
+
+ * ks_p11.c: Implement rsa_private_decrypt and add stubs for public
+ ditto.
+
+ * ks_p11.c: Less printf, less memory leaks.
+
+ * ks_p11.c: Implement signing using pkcs11.
+
+ * ks_p11.c: Partly assign private key, enough to complete
+ collection, but not any crypto functionallity.
+
+ * collector.c: Use hx509_private_key to assign private keys.
+
+ * crypto.c: Remove most of the EVP_PKEY code, and use RSA
+ directly, this temporary removes DSA support.
+
+ * hxtool.c (print_f): print if there is a friendly name and if
+ there is a private key
+
+2006-01-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * name.c: Avoid warning from missing __attribute__((noreturn))
+
+ * lock.c (_hx509_lock_unlock_certs): return unlock certificates
+
+ * crypto.c (_hx509_private_key_assign_ptr): new function, exposes
+ EVP_PKEY
+ (_hx509_private_key_assign_key_file): remember to free private key
+ if there is one.
+
+ * cert.c (_hx509_abort): add newline to output and flush stdout
+
+ * Makefile.am: libhx509_la_SOURCES += collector.c
+
+ * hx_locl.h: forward type declaration of struct hx509_collector.
+
+ * collector.c: Support functions to collect certificates and
+ private keys and then match them.
+
+ * ks_p12.c: Use the new hx509_collector support functions.
+
+ * ks_p11.c: Add enough glue to support certificate iteration.
+
+ * test_nist_pkcs12.in: Less verbose.
+
+ * cert.c (hx509_cert_free): if there is a private key assosited
+ with this cert, free it
+
+ * print.c: Use _hx509_abort.
+
+ * ks_p12.c: Use _hx509_abort.
+
+ * hxtool.c: Use _hx509_abort.
+
+ * crypto.c: Use _hx509_abort.
+
+ * cms.c: Use _hx509_abort.
+
+ * cert.c: Use _hx509_abort.
+
+ * name.c: use _hx509_abort
+
+2006-01-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * name.c (hx509_name_to_string): don't cut bmpString in half.
+
+ * name.c (hx509_name_to_string): don't overwrite with 1 byte with
+ bmpString.
+
+ * ks_file.c (parse_certificate): avoid stomping before array
+
+ * name.c (oidtostring): avoid leaking memory
+
+ * keyset.c: Add _hx509_ks_dir_register.
+
+ * Makefile.am (libhx509_la_SOURCES): += ks_dir.c
+
+ * hxtool-commands.in: Remove pkcs11.
+
+ * hxtool.c: Remove pcert_pkcs11.
+
+ * ks_file.c: Factor out certificate parsing code.
+
+ * ks_dir.c: Add new keystore that treats all files in a directory
+ a keystore, useful for regression tests.
+
+2005-12-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_nist_pkcs12.in: Test parse PKCS12 files from NIST.
+
+ * data/nist-data: Can handle DSA certificate.
+
+ * hxtool.c: Print error code on failure.
+
+2005-10-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * crypto.c: Support DSA signature operations.
+
+2005-10-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * print.c: Validate that issuerAltName and subjectAltName isn't
+ empty.
+
+2005-09-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * p11.c: Cast to unsigned char to avoid warning.
+
+ * keyset.c: Register pkcs11 module.
+
+ * Makefile.am: Add ks_p11.c, install hxtool.
+
+ * ks_p11.c: Starting point of a pkcs11 module.
+
+2005-09-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * lock.c: Implement prompter.
+
+ * hxtool-commands.in: add --content to print
+
+ * hxtool.c: Split verify and print.
+
+ * cms.c: _hx509_pbe_decrypt now takes a hx509_lock.
+
+ * crypto.c: Make _hx509_pbe_decrypt take a hx509_lock, workaround
+ for empty password.
+
+ * name.c: Add DC, handle all Directory strings, fix signless
+ problems.
+
+2005-09-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_query.in: Pass in --pass to all commands.
+
+ * hxtool.c: Use option --pass.
+
+ * hxtool-commands.in: Add --pass to all commands.
+
+ * hx509_err.et: add UNKNOWN_LOCK_COMMAND and CRYPTO_NO_PROMPTER
+
+ * test_cms.in: pass in password to cms-create-sd
+
+ * crypto.c: Abstract out PBE_string2key so I can add PBE2 s2k
+ later. Avoid signess warnings with OpenSSL.
+
+ * cms.c: Use void * instead of char * for to avoid signedness
+ issues
+
+ * cert.c (hx509_cert_get_attribute): remove const, its not
+
+ * ks_p12.c: Cast size_t to unsigned long when print.
+
+ * name.c: Fix signedness warning.
+
+ * test_query.in: Use echo, the function check isn't defined here.
+
+2005-08-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool-commands.in: Add more options that was missing.
+
+2005-07-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_cms.in: Use --certificate= for enveloped/unenvelope.
+
+ * hxtool.c: Use --certificate= for enveloped/unenvelope. Clean
+ up.
+
+ * test_cms.in: add EnvelopeData tests
+
+ * hxtool.c: use id-envelopedData for ContentInfo
+
+ * hxtool-commands.in: add contentinfo wrapping for create/unwrap
+ enveloped data
+
+ * hxtool.c: add contentinfo wrapping for create/unwrap enveloped
+ data
+
+ * data/gen-req.sh: add enveloped data (aes128)
+
+ * crypto.c: add "new" RC2 oid
+
+2005-07-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hx_locl.h, cert.c: Add HX509_QUERY_MATCH_FUNCTION that allows
+ caller to match by function, note that this doesn't not work
+ directly for backends that implements ->query, they must do their
+ own processing. (I'm running out of flags, only 12 left now)
+
+ * test_cms.in: verify ContentInfo wrapping code in hxtool
+
+ * hxtool-commands.in (cms_create_sd): support wrapping in content
+ info spelling
+
+ * hxtool.c (cms_create_sd): support wrapping in content info
+
+ * test_cms.in: test more cms signeddata messages
+
+ * data/gen-req.sh: generate SignedData
+
+ * hxtool.c (cms_create_sd): support certificate store, add support
+ to unwrap a ContentInfo the SignedData inside.
+
+ * crypto.c: sprinkel rk_UNCONST
+
+ * crypto.c: add DER NULL to the digest oid's
+
+ * hxtool-commands.in: add --content-info to cms-verify-sd
+
+ * cms.c (hx509_cms_create_signed_1): pass in a full
+ AlgorithmIdentifier instead of heim_oid for digest_alg
+
+ * crypto.c: make digest_alg a digest_oid, it's not needed right
+ now
+
+ * hx509_err.et: add CERT_NOT_FOUND
+
+ * keyset.c (_hx509_certs_find): add error code for cert not
+ found
+
+ * cms.c (hx509_cms_verify_signed): add external store of
+ certificates, use the right digest algorithm identifier.
+
+ * cert.c: fix const warning
+
+ * ks_p12.c: slightly less verbose
+
+ * cert.c: add hx509_cert_find_subjectAltName_otherName, add
+ HX509_QUERY_MATCH_FRIENDLY_NAME
+
+ * hx509.h: add hx509_octet_string_list, remove bad comment
+
+ * hx_locl.h: add HX509_QUERY_MATCH_FRIENDLY_NAME
+
+ * keyset.c (hx509_certs_append): needs a hx509_lock, add one
+
+ * Makefile.am: add test cases tempfiles to CLEANFILES
+
+ * Makefile.am: add test_query to TESTS, fix dependency on hxtool
+ sources on hxtool-commands.h
+
+ * hxtool-commands.in: explain what signer is for create-sd
+
+ * hxtool.c: add query, add more options to verify-sd and create-sd
+
+ * test_cms.in: add more cms tests
+
+ * hxtool-commands.in: add query, add more options to verify-sd
+
+ * test_query.in: test query interface
+
+ * data: fix filenames for ds/ke files, add pkcs12 files, regen
+
+ * hxtool.c,Makefile.am,hxtool-commands.in: switch to slc
+
+2005-07-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cert.c (hx509_verify_destroy_ctx): add
+
+ * hxtool.c: free hx509_verify_ctx
+
+ * name.c (_hx509_name_ds_cmp): make sure all strings are not equal
+
+2005-07-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hxtool.c: return error
+
+ * keyset.c: return errors from iterations
+
+ * test_chain.in: clean up checks
+
+ * ks_file.c (parse_certificate): return errno's not 1 in case of
+ error
+
+ * ks_file.c (file_iter): make sure endpointer is NULL
+
+ * ks_mem.c (mem_iter): follow conversion and return NULL when we
+ get to the end, not ENOENT.
+
+ * Makefile.am: test_chain depends on hxtool
+
+ * data: test certs that lasts 10 years
+
+ * data/gen-req.sh: script to generate test certs
+
+ * Makefile.am: Add regression tests.
+
+ * data: test certificate and keys
+
+ * test_chain.in: test chain
+
+ * hxtool.c (cms_create_sd): add KU digitalSigature as a
+ requirement to the query
+
+ * hx_locl.h: add KeyUsage query bits
+
+ * hx509_err.et: add KeyUsage error
+
+ * cms.c: add checks for KeyUsage
+
+ * cert.c: more checks on KeyUsage, allow to query on them too
+
+2005-07-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * cms.c: Add missing break.
+
+ * hx_locl.h,cms.c,cert.c: allow matching on SubjectKeyId
+
+ * hxtool.c: Use _hx509_map_file, _hx509_unmap_file and
+ _hx509_write_file.
+
+ * file.c (_hx509_write_file): in case of write error, return errno
+
+ * file.c (_hx509_write_file): add a function that write a data
+ blob to disk too
+
+ * Fix id-tags
+
+ * Import mostly complete X.509 and CMS library. Handles, PEM, DER,
+ PKCS12 encoded certicates. Verificate RSA chains and handled
+ CMS's SignedData, and EnvelopedData.
+
+
diff --git a/third_party/heimdal/lib/hx509/Makefile.am b/third_party/heimdal/lib/hx509/Makefile.am
new file mode 100644
index 0000000..214dabf
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/Makefile.am
@@ -0,0 +1,398 @@
+include $(top_srcdir)/Makefile.am.common
+
+AM_CPPFLAGS += $(INCLUDE_openssl_crypto)
+
+lib_LTLIBRARIES = libhx509.la libhx509template.la
+libhx509_la_LDFLAGS = -version-info 5:0:0
+libhx509template_la_LDFLAGS = -version-info 5:0:0
+
+BUILT_SOURCES = \
+ sel-gram.h \
+ hx509_err.c \
+ hx509_err.h
+
+AM_YFLAGS = -o sel-gram.c
+
+dist_libhx509_la_SOURCES = \
+ ca.c \
+ cert.c \
+ char_map.h \
+ cms.c \
+ collector.c \
+ crypto.c \
+ crypto-ec.c \
+ doxygen.c \
+ error.c \
+ env.c \
+ file.c \
+ hx509.h \
+ hx_locl.h \
+ sel.c \
+ sel.h \
+ sel-gram.y \
+ sel-lex.l \
+ keyset.c \
+ ks_dir.c \
+ ks_file.c \
+ ks_mem.c \
+ ks_null.c \
+ ks_p11.c \
+ ks_p12.c \
+ ks_keychain.c \
+ lock.c \
+ name.c \
+ peer.c \
+ print.c \
+ softp11.c \
+ ref/pkcs11.h \
+ req.c \
+ revoke.c
+
+dist_libhx509template_la_SOURCES = $(dist_libhx509_la_SOURCES)
+
+sel-gram.h: sel-gram.c
+sel-lex.c: sel-gram.h
+
+libhx509_la_DEPENDENCIES = version-script.map
+libhx509template_la_DEPENDENCIES = version-script.map
+
+libhx509_la_LIBADD = \
+ $(LIB_com_err) \
+ $(LIB_hcrypto) \
+ $(LIB_openssl_crypto) \
+ $(top_builddir)/lib/asn1/libasn1.la \
+ $(top_builddir)/lib/wind/libwind.la \
+ $(top_builddir)/lib/base/libheimbase.la \
+ $(LIBADD_roken) \
+ $(LIB_dlopen)
+
+libhx509template_la_LIBADD = \
+ $(LIB_com_err) \
+ $(LIB_hcrypto) \
+ $(LIB_openssl_crypto) \
+ $(top_builddir)/lib/asn1/libasn1template.la \
+ $(top_builddir)/lib/wind/libwind.la \
+ $(top_builddir)/lib/base/libheimbase.la \
+ $(LIBADD_roken) \
+ $(LIB_dlopen)
+
+if FRAMEWORK_SECURITY
+libhx509_la_LDFLAGS += -framework Security -framework CoreFoundation
+libhx509template_la_LDFLAGS += -framework Security -framework CoreFoundation
+endif
+
+if versionscript
+libhx509_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+libhx509template_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+endif
+$(libhx509_la_OBJECTS): $(srcdir)/version-script.map $(nodist_include_HEADERS) $(priv_headers)
+$(libhx509template_la_OBJECTS): $(srcdir)/version-script.map $(nodist_include_HEADERS) $(priv_headers)
+
+nodist_libhx509_la_SOURCES = $(BUILT_SOURCES)
+nodist_libhx509template_la_SOURCES = $(BUILT_SOURCES)
+
+dist_include_HEADERS = hx509.h $(srcdir)/hx509-protos.h
+
+noinst_HEADERS = $(srcdir)/hx509-private.h
+
+nodist_include_HEADERS = hx509_err.h
+
+ALL_OBJECTS = $(libhx509_la_OBJECTS)
+ALL_OBJECTS += $(hxtool_OBJECTS)
+
+HX509_PROTOS = $(srcdir)/hx509-protos.h $(srcdir)/hx509-private.h
+
+$(ALL_OBJECTS): $(HX509_PROTOS)
+
+$(libhx509_la_OBJECTS): $(srcdir)/hx_locl.h
+$(libhx509template_la_OBJECTS): $(srcdir)/hx_locl.h
+
+$(srcdir)/hx509-protos.h: $(dist_libhx509_la_SOURCES)
+ $(heim_verbose)cd $(srcdir) && perl ../../cf/make-proto.pl -R '^(_|^C)' -E HX509_LIB -q -P comment -o hx509-protos.h $(dist_libhx509_la_SOURCES) || rm -f hx509-protos.h
+
+$(srcdir)/hx509-private.h: $(dist_libhx509_la_SOURCES)
+ $(heim_verbose)cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p hx509-private.h $(dist_libhx509_la_SOURCES) || rm -f hx509-private.h
+
+bin_PROGRAMS = hxtool
+
+hxtool-commands.c hxtool-commands.h: hxtool-commands.in $(SLC)
+ $(heim_verbose)$(SLC) $(srcdir)/hxtool-commands.in
+
+dist_hxtool_SOURCES = hxtool.c
+nodist_hxtool_SOURCES = hxtool-commands.c hxtool-commands.h
+
+$(hxtool_OBJECTS): hxtool-commands.h $(nodist_include_HEADERS)
+
+hxtool_LDADD = \
+ libhx509template.la \
+ $(top_builddir)/lib/asn1/libasn1.la \
+ $(LIB_hcrypto) \
+ $(LIB_roken) \
+ $(top_builddir)/lib/sl/libsl.la
+
+CLEANFILES = $(BUILT_SOURCES) sel-gram.c sel-lex.c \
+ $(TESTS) \
+ hxtool-commands.c hxtool-commands.h *.tmp \
+ request.out \
+ out.pem out2.pem \
+ sd sd.pem \
+ sd.data sd.data.out \
+ ev.data ev.data.out \
+ cert-null.pem cert-sub-ca2.pem \
+ cert-ee.pem cert-ca.pem \
+ cert-sub-ee.pem cert-sub-ca.pem \
+ cert-proxy.der cert-ca.der cert-ee.der pkcs10-request.der \
+ wca.pem wuser.pem wdc.pem wcrl.crl \
+ random-data statfile crl.crl \
+ test p11dbg.log pkcs11.cfg \
+ test-rc-file.rc
+
+clean-local:
+ @echo "cleaning PKITS" ; rm -rf PKITS_data
+
+#
+# regression tests
+#
+
+check_SCRIPTS = $(SCRIPT_TESTS)
+check_PROGRAMS = $(PROGRAM_TESTS) test_soft_pkcs11
+
+LDADD = libhx509.la
+
+test_soft_pkcs11_LDADD = libhx509.la $(top_builddir)/lib/asn1/libasn1.la
+
+test_name_LDADD = libhx509.la $(LIB_roken) $(top_builddir)/lib/asn1/libasn1.la
+test_expr_LDADD = libhx509.la $(LIB_roken) $(top_builddir)/lib/asn1/libasn1.la
+
+TESTS = $(SCRIPT_TESTS) $(PROGRAM_TESTS)
+
+PROGRAM_TESTS = \
+ test_name \
+ test_expr
+
+SCRIPT_TESTS = \
+ test_ca \
+ test_cert \
+ test_chain \
+ test_cms \
+ test_crypto \
+ test_nist \
+ test_nist2 \
+ test_pkcs11 \
+ test_java_pkcs11 \
+ test_nist_cert \
+ test_nist_pkcs12 \
+ test_req \
+ test_windows \
+ test_query
+
+do_subst = $(heim_verbose)sed -e 's,[@]srcdir[@],$(srcdir),g' \
+ -e 's,[@]objdir[@],$(top_builddir)/lib/hx509,g' \
+ -e 's,[@]egrep[@],$(EGREP),g'
+
+test_ca: test_ca.in Makefile
+ $(do_subst) < $(srcdir)/test_ca.in > test_ca.tmp
+ $(heim_verbose)chmod +x test_ca.tmp
+ mv test_ca.tmp test_ca
+
+test_cert: test_cert.in Makefile
+ $(do_subst) < $(srcdir)/test_cert.in > test_cert.tmp
+ $(heim_verbose)chmod +x test_cert.tmp
+ mv test_cert.tmp test_cert
+
+test_chain: test_chain.in Makefile
+ $(do_subst) < $(srcdir)/test_chain.in > test_chain.tmp
+ $(heim_verbose)chmod +x test_chain.tmp
+ mv test_chain.tmp test_chain
+
+test_cms: test_cms.in Makefile
+ $(do_subst) < $(srcdir)/test_cms.in > test_cms.tmp
+ $(heim_verbose)chmod +x test_cms.tmp
+ mv test_cms.tmp test_cms
+
+test_crypto: test_crypto.in Makefile
+ $(do_subst) < $(srcdir)/test_crypto.in > test_crypto.tmp
+ $(heim_verbose)chmod +x test_crypto.tmp
+ mv test_crypto.tmp test_crypto
+
+test_nist: test_nist.in Makefile
+ $(do_subst) < $(srcdir)/test_nist.in > test_nist.tmp
+ $(heim_verbose)chmod +x test_nist.tmp
+ mv test_nist.tmp test_nist
+
+test_nist2: test_nist2.in Makefile
+ $(do_subst) < $(srcdir)/test_nist2.in > test_nist2.tmp
+ $(heim_verbose)chmod +x test_nist2.tmp
+ mv test_nist2.tmp test_nist2
+
+test_pkcs11: test_pkcs11.in Makefile
+ $(do_subst) < $(srcdir)/test_pkcs11.in > test_pkcs11.tmp
+ $(heim_verbose)chmod +x test_pkcs11.tmp
+ mv test_pkcs11.tmp test_pkcs11
+
+test_java_pkcs11: test_java_pkcs11.in Makefile
+ $(do_subst) < $(srcdir)/test_java_pkcs11.in > test_java_pkcs11.tmp
+ $(heim_verbose)chmod +x test_java_pkcs11.tmp
+ mv test_java_pkcs11.tmp test_java_pkcs11
+
+test_nist_cert: test_nist_cert.in Makefile
+ $(do_subst) < $(srcdir)/test_nist_cert.in > test_nist_cert.tmp
+ $(heim_verbose)chmod +x test_nist_cert.tmp
+ mv test_nist_cert.tmp test_nist_cert
+
+test_nist_pkcs12: test_nist_pkcs12.in Makefile
+ $(do_subst) < $(srcdir)/test_nist_pkcs12.in > test_nist_pkcs12.tmp
+ $(heim_verbose)chmod +x test_nist_pkcs12.tmp
+ mv test_nist_pkcs12.tmp test_nist_pkcs12
+
+test_req: test_req.in Makefile
+ $(do_subst) < $(srcdir)/test_req.in > test_req.tmp
+ $(heim_verbose)chmod +x test_req.tmp
+ mv test_req.tmp test_req
+
+test_windows: test_windows.in Makefile
+ $(do_subst) < $(srcdir)/test_windows.in > test_windows.tmp
+ $(heim_verbose)chmod +x test_windows.tmp
+ mv test_windows.tmp test_windows
+
+test_query: test_query.in Makefile
+ $(do_subst) < $(srcdir)/test_query.in > test_query.tmp
+ $(heim_verbose)chmod +x test_query.tmp
+ mv test_query.tmp test_query
+
+EXTRA_DIST = \
+ NTMakefile \
+ hxtool-version.rc \
+ libhx509-exports.def \
+ version-script.map \
+ hx509_err.et \
+ hxtool-commands.in \
+ quote.py \
+ test_ca.in \
+ test_chain.in \
+ test_cert.in \
+ test_cms.in \
+ test_crypto.in \
+ test_nist.in \
+ test_nist2.in \
+ test_nist_cert.in \
+ test_nist_pkcs12.in \
+ test_pkcs11.in \
+ test_java_pkcs11.in \
+ test_query.in \
+ test_req.in \
+ test_windows.in \
+ tst-crypto-available1 \
+ tst-crypto-available2 \
+ tst-crypto-available3 \
+ tst-crypto-select \
+ tst-crypto-select1 \
+ tst-crypto-select2 \
+ tst-crypto-select3 \
+ tst-crypto-select4 \
+ tst-crypto-select5 \
+ tst-crypto-select6 \
+ tst-crypto-select7 \
+ data/PKITS_data.zip \
+ data/eccurve.pem \
+ data/https.crt \
+ data/https.key \
+ data/mkcert.sh \
+ data/nist-result2 \
+ data/n0ll.pem \
+ data/secp256r1TestCA.cert.pem \
+ data/secp256r1TestCA.key.pem \
+ data/secp256r1TestCA.pem \
+ data/secp256r2TestClient.cert.pem \
+ data/secp256r2TestClient.key.pem \
+ data/secp256r2TestClient.pem \
+ data/secp256r2TestServer.cert.pem \
+ data/secp256r2TestServer.key.pem \
+ data/secp256r2TestServer.pem \
+ data/bleichenbacher-bad.pem \
+ data/bleichenbacher-good.pem \
+ data/bleichenbacher-sf-pad-correct.pem \
+ data/ca.crt \
+ data/ca.key \
+ data/crl1.crl \
+ data/crl1.der \
+ data/gen-req.sh \
+ data/j.pem \
+ data/kdc.crt \
+ data/kdc.key \
+ data/key.der \
+ data/key2.der \
+ data/nist-data \
+ data/nist-data2 \
+ data/no-proxy-test.crt \
+ data/no-proxy-test.key \
+ data/ocsp-req1.der \
+ data/ocsp-req2.der \
+ data/ocsp-resp1-2.der \
+ data/ocsp-resp1-3.der \
+ data/ocsp-resp1-ca.der \
+ data/ocsp-resp1-keyhash.der \
+ data/ocsp-resp1-ocsp-no-cert.der \
+ data/ocsp-resp1-ocsp.der \
+ data/ocsp-resp1.der \
+ data/ocsp-resp2.der \
+ data/ocsp-responder.crt \
+ data/ocsp-responder.key \
+ data/openssl.1.0.cnf \
+ data/openssl.1.1.cnf \
+ data/pkinit-proxy-chain.crt \
+ data/pkinit-proxy.crt \
+ data/pkinit-proxy.key \
+ data/pkinit-pw.key \
+ data/pkinit.crt \
+ data/pkinit.key \
+ data/pkinit-ec.crt \
+ data/pkinit-ec.key \
+ data/proxy-level-test.crt \
+ data/proxy-level-test.key \
+ data/proxy-test.crt \
+ data/proxy-test.key \
+ data/proxy10-child-test.crt \
+ data/proxy10-child-test.key \
+ data/proxy10-child-child-test.crt \
+ data/proxy10-child-child-test.key \
+ data/proxy10-test.crt \
+ data/proxy10-test.key \
+ data/revoke.crt \
+ data/revoke.key \
+ data/sf-class2-root.pem \
+ data/static-file \
+ data/sub-ca.crt \
+ data/sub-ca.key \
+ data/sub-cert.crt \
+ data/sub-cert.key \
+ data/sub-cert.p12 \
+ data/test-ds-only.crt \
+ data/test-ds-only.key \
+ data/test-enveloped-aes-128 \
+ data/test-enveloped-aes-256 \
+ data/test-enveloped-des \
+ data/test-enveloped-des-ede3 \
+ data/test-enveloped-rc2-128 \
+ data/test-enveloped-rc2-40 \
+ data/test-enveloped-rc2-64 \
+ data/test-ke-only.crt \
+ data/test-ke-only.key \
+ data/test-nopw.p12 \
+ data/test-pw.key \
+ data/test-signed-data \
+ data/test-signed-data-noattr \
+ data/test-signed-data-noattr-nocerts \
+ data/test-signed-sha-1 \
+ data/test-signed-sha-256 \
+ data/test-signed-sha-512 \
+ data/test.combined.crt \
+ data/test.crt \
+ data/test.key \
+ data/test.p12 \
+ data/win-u16-in-printablestring.der \
+ data/yutaka-pad-broken-ca.pem \
+ data/yutaka-pad-broken-cert.pem \
+ data/yutaka-pad-ok-ca.pem \
+ data/yutaka-pad-ok-cert.pem \
+ data/yutaka-pad.key
diff --git a/third_party/heimdal/lib/hx509/NTMakefile b/third_party/heimdal/lib/hx509/NTMakefile
new file mode 100644
index 0000000..4d5ff09
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/NTMakefile
@@ -0,0 +1,180 @@
+########################################################################
+#
+# Copyright (c) 2009-2017, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\hx509
+intcflags=-I$(OBJ)
+localcflags=-DASN1_LIB
+
+!include ../../windows/NTMakefile.w32
+
+libhx509_la_OBJS = \
+ $(OBJ)\ca.obj \
+ $(OBJ)\cert.obj \
+ $(OBJ)\cms.obj \
+ $(OBJ)\collector.obj \
+ $(OBJ)\crypto.obj \
+ $(OBJ)\crypto-ec.obj \
+ $(OBJ)\error.obj \
+ $(OBJ)\env.obj \
+ $(OBJ)\file.obj \
+ $(OBJ)\hx509_err.obj \
+ $(OBJ)\sel.obj \
+ $(OBJ)\sel-gram.obj \
+ $(OBJ)\sel-lex.obj \
+ $(OBJ)\keyset.obj \
+ $(OBJ)\ks_dir.obj \
+ $(OBJ)\ks_file.obj \
+ $(OBJ)\ks_mem.obj \
+ $(OBJ)\ks_null.obj \
+ $(OBJ)\ks_p11.obj \
+ $(OBJ)\ks_p12.obj \
+ $(OBJ)\ks_keychain.obj \
+ $(OBJ)\lock.obj \
+ $(OBJ)\name.obj \
+ $(OBJ)\peer.obj \
+ $(OBJ)\print.obj \
+ $(OBJ)\softp11.obj \
+ $(OBJ)\req.obj \
+ $(OBJ)\revoke.obj
+
+$(LIBHX509): $(libhx509_la_OBJS)
+ $(LIBCON)
+
+dist_libhx509_la_SOURCES = \
+ $(SRCDIR)\ca.c \
+ $(SRCDIR)\cert.c \
+ $(SRCDIR)\cms.c \
+ $(SRCDIR)\collector.c \
+ $(SRCDIR)\crypto.c \
+ $(SRCDIR)\crypto-ec.c \
+ $(SRCDIR)\doxygen.c \
+ $(SRCDIR)\error.c \
+ $(SRCDIR)\env.c \
+ $(SRCDIR)\file.c \
+ $(SRCDIR)\hx509.h \
+ $(SRCDIR)\hx_locl.h \
+ $(SRCDIR)\sel.c \
+ $(SRCDIR)\sel.h \
+ $(SRCDIR)\sel-gram.y \
+ $(SRCDIR)\sel-lex.l \
+ $(SRCDIR)\keyset.c \
+ $(SRCDIR)\ks_dir.c \
+ $(SRCDIR)\ks_file.c \
+ $(SRCDIR)\ks_mem.c \
+ $(SRCDIR)\ks_null.c \
+ $(SRCDIR)\ks_p11.c \
+ $(SRCDIR)\ks_p12.c \
+ $(SRCDIR)\ks_keychain.c \
+ $(SRCDIR)\lock.c \
+ $(SRCDIR)\name.c \
+ $(SRCDIR)\peer.c \
+ $(SRCDIR)\print.c \
+ $(SRCDIR)\softp11.c \
+ $(SRCDIR)\ref\pkcs11.h \
+ $(SRCDIR)\req.c \
+ $(SRCDIR)\revoke.c
+
+{}.c{$(OBJ)}.obj::
+ $(C2OBJ_P) -DBUILD_HX509_LIB -DASN1_LIB
+
+{$(OBJ)}.c{$(OBJ)}.obj::
+ $(C2OBJ_P) -DBUILD_HX509_LIB -DASN1_LIB
+
+asn1_compile=$(BINDIR)\asn1_compile.exe
+
+INCFILES= \
+ $(INCDIR)\hx509.h \
+ $(INCDIR)\hx509-protos.h \
+ $(INCDIR)\hx509-private.h \
+ $(INCDIR)\hx509_err.h
+
+hxtool.c: $(OBJ)\hxtool-commands.h
+
+SLC=$(BINDIR)\slc.exe
+
+$(OBJ)\hxtool-commands.c $(OBJ)\hxtool-commands.h: hxtool-commands.in $(SLC)
+ cd $(OBJ)
+ $(CP) $(SRCDIR)\hxtool-commands.in $(OBJ)\hxtool-commands.in
+ $(SLC) hxtool-commands.in
+ cd $(SRCDIR)
+
+$(BINDIR)\hxtool.exe: $(OBJ)\tool\hxtool.obj $(OBJ)\tool\hxtool-commands.obj $(LIBHEIMDAL) $(OBJ)\hxtool-version.res
+ $(EXECONLINK) $(LIBHEIMDAL) $(LIBROKEN) $(LIBSL) $(LIBVERS) $(LIBCOMERR) $(LIB_openssl_crypto)
+ $(EXEPREP)
+
+$(OBJ)\hx509-protos.h:
+ cd $(OBJ)
+ $(PERL) $(SRCDIR)\..\..\cf\make-proto.pl -R "^(_|^C)" -E HX509_LIB -q -P remove -o hx509-protos.h $(dist_libhx509_la_SOURCES) || $(RM) -f hx509-protos.h
+ cd $(SRCDIR)
+
+$(OBJ)\hx509-private.h:
+ cd $(OBJ)
+ $(PERL) $(SRCDIR)\..\..\cf\make-proto.pl -q -P remove -p hx509-private.h $(dist_libhx509_la_SOURCES) || $(RM) -f hx509-private.h
+ cd $(SRCDIR)
+
+$(OBJ)\hx509_err.c $(OBJ)\hx509_err.h: hx509_err.et
+ cd $(OBJ)
+ $(BINDIR)\compile_et.exe $(SRCDIR)\hx509_err.et
+ cd $(SRCDIR)
+
+$(OBJ)\sel-gram.obj: $(OBJ)\sel-gram.c
+ $(C2OBJ) -I$(SRCDIR)
+
+$(OBJ)\sel-lex.obj: $(OBJ)\sel-lex.c
+ $(C2OBJ) -I$(SRCDIR) -I$(OBJ) -DYY_NO_UNISTD_H
+
+$(OBJ)\sel-gram.c: sel-gram.y
+ $(YACC) -o $@ --defines=$(OBJ)\sel-gram.h sel-gram.y
+
+$(OBJ)\sel-lex.c: sel-lex.l
+ $(LEX) -P_hx509_sel_yy -o$@ sel-lex.l
+
+all:: $(INCFILES) $(LIBHX509)
+
+prep:: mktooldir
+
+mktooldir:
+! if !exist($(OBJ)\tool)
+ $(MKDIR) $(OBJ)\tool
+! endif
+
+all-tools:: $(BINDIR)\hxtool.exe
+
+clean::
+ -$(RM) $(BINDIR)\hxtool.*
+ -$(RM) $(OBJ)\tool\*.*
+
+{}.c{$(OBJ)\tool}.obj::
+ $(C2OBJ_C) /Fd$(OBJ)\tool\ /Fo$(OBJ)\tool\ $(MPOPT) /UASN1_LIB $<
+
+{$(OBJ)}.c{$(OBJ)\tool}.obj::
+ $(C2OBJ_C) /Fd$(OBJ)\tool\ /Fo$(OBJ)\tool\ $(MPOPT) /UASN1_LIB $<
+
diff --git a/third_party/heimdal/lib/hx509/TODO b/third_party/heimdal/lib/hx509/TODO
new file mode 100644
index 0000000..ecdfa8d
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/TODO
@@ -0,0 +1,61 @@
+Handle private_key_ops better, esp wrt ->key_oid
+
+Better support for keyex negotiation, DH and ECDH.
+
+x501 name
+ parsing
+ comparing (ldap canonlisation rules)
+
+DSA support
+DSA2 support
+
+Rewrite the pkcs11 code to support the following:
+
+ * Reset the pin on card change.
+ * Ref count the lock structure to make sure we have a
+ prompter when we need it.
+ * Add support for CK_TOKEN_INFO.CKF_PROTECTED_AUTHENTICATION_PATH
+
+x509 policy mappings support
+
+CRL delta support
+
+Qualified statement
+ https://bugzilla.mozilla.org/show_bug.cgi?id=277797#c2
+
+
+Signed Receipts
+ http://www.faqs.org/rfcs/rfc2634.html
+ chapter 2
+
+tests
+ nist tests
+ name constrains
+ policy mappings
+ http://csrc.nist.gov/pki/testing/x509paths.html
+
+ building path using Subject/Issuer vs SubjKeyID vs AuthKeyID
+ negative tests
+ all checksums
+ conditions/branches
+
+pkcs7
+ handle pkcs7 support in CMS ?
+
+certificate request
+ generate pkcs10 request
+ from existing cert
+ generate CRMF request
+ pk-init KDC/client
+ web server/client
+ jabber server/client
+ email
+
+
+x509 issues:
+
+ OtherName is left unspecified, but it's used by other
+ specs. creating this hole where a application/CA can't specify
+ policy for SubjectAltName what covers whole space. For example, a
+ CA is trusted to provide authentication but not authorization.
+
diff --git a/third_party/heimdal/lib/hx509/ca.c b/third_party/heimdal/lib/hx509/ca.c
new file mode 100644
index 0000000..3d62b93
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/ca.c
@@ -0,0 +1,3093 @@
+/*
+ * Copyright (c) 2006 - 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+/**
+ * @page page_ca Hx509 CA functions
+ *
+ * See the library functions here: @ref hx509_ca
+ */
+
+struct hx509_ca_tbs {
+ hx509_name subject;
+ SubjectPublicKeyInfo spki;
+ KeyUsage ku;
+ ExtKeyUsage eku;
+ GeneralNames san;
+ CertificatePolicies cps;
+ PolicyMappings pms;
+ heim_integer serial;
+ struct {
+ unsigned int proxy:1;
+ unsigned int ca:1;
+ unsigned int key:1;
+ unsigned int serial:1;
+ unsigned int domaincontroller:1;
+ unsigned int xUniqueID:1;
+ } flags;
+ time_t notBefore;
+ time_t notAfter;
+ HeimPkinitPrincMaxLifeSecs pkinitTicketMaxLife;
+ int pathLenConstraint; /* both for CA and Proxy */
+ CRLDistributionPoints crldp;
+ heim_bit_string subjectUniqueID;
+ heim_bit_string issuerUniqueID;
+ AlgorithmIdentifier *sigalg;
+};
+
+/**
+ * Allocate an to-be-signed certificate object that will be converted
+ * into an certificate.
+ *
+ * @param context A hx509 context.
+ * @param tbs returned to-be-signed certicate object, free with
+ * hx509_ca_tbs_free().
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_init(hx509_context context, hx509_ca_tbs *tbs)
+{
+ *tbs = calloc(1, sizeof(**tbs));
+ if (*tbs == NULL)
+ return ENOMEM;
+
+ return 0;
+}
+
+/**
+ * Free an To Be Signed object.
+ *
+ * @param tbs object to free.
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_ca_tbs_free(hx509_ca_tbs *tbs)
+{
+ if (tbs == NULL || *tbs == NULL)
+ return;
+
+ free_SubjectPublicKeyInfo(&(*tbs)->spki);
+ free_CertificatePolicies(&(*tbs)->cps);
+ free_PolicyMappings(&(*tbs)->pms);
+ free_GeneralNames(&(*tbs)->san);
+ free_ExtKeyUsage(&(*tbs)->eku);
+ der_free_heim_integer(&(*tbs)->serial);
+ free_CRLDistributionPoints(&(*tbs)->crldp);
+ der_free_bit_string(&(*tbs)->subjectUniqueID);
+ der_free_bit_string(&(*tbs)->issuerUniqueID);
+ if ((*tbs)->subject)
+ hx509_name_free(&(*tbs)->subject);
+ if ((*tbs)->sigalg) {
+ free_AlgorithmIdentifier((*tbs)->sigalg);
+ free((*tbs)->sigalg);
+ }
+
+ memset(*tbs, 0, sizeof(**tbs));
+ free(*tbs);
+ *tbs = NULL;
+}
+
+/**
+ * Set the absolute time when the certificate is valid from. If not
+ * set the current time will be used.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param t time the certificated will start to be valid
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_set_notBefore(hx509_context context,
+ hx509_ca_tbs tbs,
+ time_t t)
+{
+ tbs->notBefore = t;
+ return 0;
+}
+
+/**
+ * Set the absolute time when the certificate is valid to.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param t time when the certificate will expire
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_set_notAfter(hx509_context context,
+ hx509_ca_tbs tbs,
+ time_t t)
+{
+ tbs->notAfter = t;
+ return 0;
+}
+
+/**
+ * Set the relative time when the certificiate is going to expire.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param delta seconds to the certificate is going to expire.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_set_notAfter_lifetime(hx509_context context,
+ hx509_ca_tbs tbs,
+ time_t delta)
+{
+ return hx509_ca_tbs_set_notAfter(context, tbs, time(NULL) + delta);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_set_pkinit_max_life(hx509_context context,
+ hx509_ca_tbs tbs,
+ time_t max_life)
+{
+ tbs->pkinitTicketMaxLife = max_life;
+ return 0;
+}
+
+static const struct units templatebits[] = {
+ { "ExtendedKeyUsage", HX509_CA_TEMPLATE_EKU },
+ { "KeyUsage", HX509_CA_TEMPLATE_KU },
+ { "SPKI", HX509_CA_TEMPLATE_SPKI },
+ { "notAfter", HX509_CA_TEMPLATE_NOTAFTER },
+ { "notBefore", HX509_CA_TEMPLATE_NOTBEFORE },
+ { "serial", HX509_CA_TEMPLATE_SERIAL },
+ { "subject", HX509_CA_TEMPLATE_SUBJECT },
+ { "pkinitMaxLife", HX509_CA_TEMPLATE_PKINIT_MAX_LIFE },
+ { NULL, 0 }
+};
+
+/**
+ * Make of template units, use to build flags argument to
+ * hx509_ca_tbs_set_template() with parse_units().
+ *
+ * @return an units structure.
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION const struct units * HX509_LIB_CALL
+hx509_ca_tbs_template_units(void)
+{
+ return templatebits;
+}
+
+/**
+ * Initialize the to-be-signed certificate object from a template certificate.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param flags bit field selecting what to copy from the template
+ * certificate.
+ * @param cert template certificate.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_set_template(hx509_context context,
+ hx509_ca_tbs tbs,
+ int flags,
+ hx509_cert cert)
+{
+ int ret;
+
+ if (flags & HX509_CA_TEMPLATE_SUBJECT) {
+ if (tbs->subject)
+ hx509_name_free(&tbs->subject);
+ ret = hx509_cert_get_subject(cert, &tbs->subject);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to get subject from template");
+ return ret;
+ }
+ }
+ if (flags & HX509_CA_TEMPLATE_SERIAL) {
+ der_free_heim_integer(&tbs->serial);
+ ret = hx509_cert_get_serialnumber(cert, &tbs->serial);
+ tbs->flags.serial = !ret;
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to copy serial number");
+ return ret;
+ }
+ }
+ if (flags & HX509_CA_TEMPLATE_NOTBEFORE)
+ tbs->notBefore = hx509_cert_get_notBefore(cert);
+ if (flags & HX509_CA_TEMPLATE_NOTAFTER)
+ tbs->notAfter = hx509_cert_get_notAfter(cert);
+ if (flags & HX509_CA_TEMPLATE_SPKI) {
+ free_SubjectPublicKeyInfo(&tbs->spki);
+ ret = hx509_cert_get_SPKI(context, cert, &tbs->spki);
+ tbs->flags.key = !ret;
+ if (ret)
+ return ret;
+ }
+ if (flags & HX509_CA_TEMPLATE_KU) {
+ ret = _hx509_cert_get_keyusage(context, cert, &tbs->ku);
+ if (ret)
+ return ret;
+ }
+ if (flags & HX509_CA_TEMPLATE_EKU) {
+ ExtKeyUsage eku;
+ size_t i;
+ ret = _hx509_cert_get_eku(context, cert, &eku);
+ if (ret)
+ return ret;
+ for (i = 0; i < eku.len; i++) {
+ ret = hx509_ca_tbs_add_eku(context, tbs, &eku.val[i]);
+ if (ret) {
+ free_ExtKeyUsage(&eku);
+ return ret;
+ }
+ }
+ free_ExtKeyUsage(&eku);
+ }
+ if (flags & HX509_CA_TEMPLATE_PKINIT_MAX_LIFE) {
+ time_t max_life;
+
+ if ((max_life = hx509_cert_get_pkinit_max_life(context, cert, 0)) > 0)
+ hx509_ca_tbs_set_pkinit_max_life(context, tbs, max_life);
+ }
+ return 0;
+}
+
+/**
+ * Make the to-be-signed certificate object a CA certificate. If the
+ * pathLenConstraint is negative path length constraint is used.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param pathLenConstraint path length constraint, negative, no
+ * constraint.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_set_ca(hx509_context context,
+ hx509_ca_tbs tbs,
+ int pathLenConstraint)
+{
+ tbs->flags.ca = 1;
+ tbs->pathLenConstraint = pathLenConstraint;
+ return 0;
+}
+
+/**
+ * Make the to-be-signed certificate object a proxy certificate. If the
+ * pathLenConstraint is negative path length constraint is used.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param pathLenConstraint path length constraint, negative, no
+ * constraint.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_set_proxy(hx509_context context,
+ hx509_ca_tbs tbs,
+ int pathLenConstraint)
+{
+ tbs->flags.proxy = 1;
+ tbs->pathLenConstraint = pathLenConstraint;
+ return 0;
+}
+
+
+/**
+ * Make the to-be-signed certificate object a windows domain controller certificate.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_set_domaincontroller(hx509_context context,
+ hx509_ca_tbs tbs)
+{
+ tbs->flags.domaincontroller = 1;
+ return 0;
+}
+
+/**
+ * Set the subject public key info (SPKI) in the to-be-signed certificate
+ * object. SPKI is the public key and key related parameters in the
+ * certificate.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param spki subject public key info to use for the to-be-signed certificate object.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_set_spki(hx509_context context,
+ hx509_ca_tbs tbs,
+ const SubjectPublicKeyInfo *spki)
+{
+ int ret;
+ free_SubjectPublicKeyInfo(&tbs->spki);
+ ret = copy_SubjectPublicKeyInfo(spki, &tbs->spki);
+ tbs->flags.key = !ret;
+ return ret;
+}
+
+/**
+ * Set the serial number to use for to-be-signed certificate object.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param serialNumber serial number to use for the to-be-signed
+ * certificate object.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_set_serialnumber(hx509_context context,
+ hx509_ca_tbs tbs,
+ const heim_integer *serialNumber)
+{
+ int ret;
+ der_free_heim_integer(&tbs->serial);
+ ret = der_copy_heim_integer(serialNumber, &tbs->serial);
+ tbs->flags.serial = !ret;
+ return ret;
+}
+
+/**
+ * Copy elements of a CSR into a TBS, but only if all of them are authorized.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param req CSR
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_set_from_csr(hx509_context context,
+ hx509_ca_tbs tbs,
+ hx509_request req)
+{
+ hx509_san_type san_type;
+ heim_oid oid = { 0, 0 };
+ KeyUsage ku;
+ size_t i;
+ char *s = NULL;
+ int ret;
+
+ if (hx509_request_count_unauthorized(req)) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return EACCES;
+ }
+
+ ret = hx509_request_get_ku(context, req, &ku);
+ if (ret == 0 && KeyUsage2int(ku))
+ ret = hx509_ca_tbs_add_ku(context, tbs, ku);
+
+ for (i = 0; ret == 0; i++) {
+ free(s); s = NULL;
+ der_free_oid(&oid);
+ ret = hx509_request_get_eku(req, i, &s);
+ if (ret == 0)
+ ret = der_parse_heim_oid(s, ".", &oid);
+ if (ret == 0)
+ ret = hx509_ca_tbs_add_eku(context, tbs, &oid);
+ }
+ if (ret == HX509_NO_ITEM)
+ ret = 0;
+
+ for (i = 0; ret == 0; i++) {
+ free(s); s = NULL;
+ ret = hx509_request_get_san(req, i, &san_type, &s);
+ if (ret == 0)
+ ret = hx509_ca_tbs_add_san(context, tbs, san_type, s);
+ }
+ if (ret == HX509_NO_ITEM)
+ ret = 0;
+
+ der_free_oid(&oid);
+ free(s);
+ return ret;
+}
+
+/**
+ * An an extended key usage to the to-be-signed certificate object.
+ * Duplicates will detected and not added.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param oid extended key usage to add.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_ku(hx509_context context,
+ hx509_ca_tbs tbs,
+ KeyUsage ku)
+{
+ tbs->ku = ku;
+ return 0;
+}
+
+/**
+ * An an extended key usage to the to-be-signed certificate object.
+ * Duplicates will detected and not added.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param oid extended key usage to add.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_eku(hx509_context context,
+ hx509_ca_tbs tbs,
+ const heim_oid *oid)
+{
+ void *ptr;
+ int ret;
+ unsigned i;
+
+ /* search for duplicates */
+ for (i = 0; i < tbs->eku.len; i++) {
+ if (der_heim_oid_cmp(oid, &tbs->eku.val[i]) == 0)
+ return 0;
+ }
+
+ ptr = realloc(tbs->eku.val, sizeof(tbs->eku.val[0]) * (tbs->eku.len + 1));
+ if (ptr == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+ tbs->eku.val = ptr;
+ ret = der_copy_oid(oid, &tbs->eku.val[tbs->eku.len]);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ return ret;
+ }
+ tbs->eku.len += 1;
+ return 0;
+}
+
+/**
+ * Add a certificate policy to the to-be-signed certificate object. Duplicates
+ * will detected and not added.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param oid policy OID.
+ * @param cps_uri CPS URI to qualify policy with.
+ * @param user_notice user notice display text to qualify policy with.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_pol(hx509_context context,
+ hx509_ca_tbs tbs,
+ const heim_oid *oid,
+ const char *cps_uri,
+ const char *user_notice)
+{
+ PolicyQualifierInfos pqis;
+ PolicyQualifierInfo pqi;
+ PolicyInformation pi;
+ size_t i, size;
+ int ret = 0;
+
+ /* search for duplicates */
+ for (i = 0; i < tbs->cps.len; i++) {
+ if (der_heim_oid_cmp(oid, &tbs->cps.val[i].policyIdentifier) == 0)
+ return 0;
+ }
+
+ memset(&pi, 0, sizeof(pi));
+ memset(&pqi, 0, sizeof(pqi));
+ memset(&pqis, 0, sizeof(pqis));
+
+ pi.policyIdentifier = *oid;
+ if (cps_uri) {
+ CPSuri uri;
+
+ uri.length = strlen(cps_uri);
+ uri.data = (void *)(uintptr_t)cps_uri;
+ pqi.policyQualifierId = asn1_oid_id_pkix_qt_cps;
+
+ ASN1_MALLOC_ENCODE(CPSuri,
+ pqi.qualifier.data,
+ pqi.qualifier.length,
+ &uri, &size, ret);
+ if (ret == 0) {
+ ret = add_PolicyQualifierInfos(&pqis, &pqi);
+ free_heim_any(&pqi.qualifier);
+ }
+ }
+ if (ret == 0 && user_notice) {
+ DisplayText dt;
+ UserNotice un;
+
+ dt.element = choice_DisplayText_utf8String;
+ dt.u.utf8String = (void *)(uintptr_t)user_notice;
+ un.explicitText = &dt;
+ un.noticeRef = 0;
+
+ pqi.policyQualifierId = asn1_oid_id_pkix_qt_unotice;
+ ASN1_MALLOC_ENCODE(UserNotice,
+ pqi.qualifier.data,
+ pqi.qualifier.length,
+ &un, &size, ret);
+ if (ret == 0) {
+ ret = add_PolicyQualifierInfos(&pqis, &pqi);
+ free_heim_any(&pqi.qualifier);
+ }
+ }
+
+ pi.policyQualifiers = pqis.len ? &pqis : 0;
+
+ if (ret == 0)
+ ret = add_CertificatePolicies(&tbs->cps, &pi);
+
+ free_PolicyQualifierInfos(&pqis);
+ return ret;
+}
+
+/**
+ * Add a certificate policy mapping to the to-be-signed certificate object.
+ * Duplicates will detected and not added.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param issuer issuerDomainPolicy policy OID.
+ * @param subject subjectDomainPolicy policy OID.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_pol_mapping(hx509_context context,
+ hx509_ca_tbs tbs,
+ const heim_oid *issuer,
+ const heim_oid *subject)
+{
+ PolicyMapping pm;
+ size_t i;
+
+ /* search for duplicates */
+ for (i = 0; i < tbs->pms.len; i++) {
+ PolicyMapping *pmp = &tbs->pms.val[i];
+ if (der_heim_oid_cmp(issuer, &pmp->issuerDomainPolicy) == 0 &&
+ der_heim_oid_cmp(subject, &pmp->subjectDomainPolicy) == 0)
+ return 0;
+ }
+
+ memset(&pm, 0, sizeof(pm));
+ pm.issuerDomainPolicy = *issuer;
+ pm.subjectDomainPolicy = *subject;
+ return add_PolicyMappings(&tbs->pms, &pm);
+}
+
+/**
+ * Add CRL distribution point URI to the to-be-signed certificate
+ * object.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param uri uri to the CRL.
+ * @param issuername name of the issuer.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_crl_dp_uri(hx509_context context,
+ hx509_ca_tbs tbs,
+ const char *uri,
+ hx509_name issuername)
+{
+ DistributionPointName dpn;
+ DistributionPoint dp;
+ GeneralNames crlissuer;
+ GeneralName gn, ign;
+ Name in;
+ int ret;
+
+ memset(&dp, 0, sizeof(dp));
+ memset(&gn, 0, sizeof(gn));
+ memset(&ign, 0, sizeof(ign));
+ memset(&in, 0, sizeof(in));
+ gn.element = choice_GeneralName_uniformResourceIdentifier;
+ gn.u.uniformResourceIdentifier.data = rk_UNCONST(uri);
+ gn.u.uniformResourceIdentifier.length = strlen(uri);
+ dpn.element = choice_DistributionPointName_fullName;
+ dpn.u.fullName.len = 1;
+ dpn.u.fullName.val = &gn;
+ dp.distributionPoint = &dpn;
+
+ if (issuername) {
+ ign.element = choice_GeneralName_directoryName;
+ ret = hx509_name_to_Name(issuername, &ign.u.directoryName);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ return ret;
+ }
+ crlissuer.len = 1;
+ crlissuer.val = &ign;
+ dp.cRLIssuer = &crlissuer;
+ }
+
+ ret = add_CRLDistributionPoints(&tbs->crldp, &dp);
+ if (issuername)
+ free_Name(&ign.u.directoryName);
+
+ if (ret)
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ return ret;
+}
+
+/**
+ * Add Subject Alternative Name otherName to the to-be-signed
+ * certificate object.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param oid the oid of the OtherName.
+ * @param os data in the other name.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_san_otherName(hx509_context context,
+ hx509_ca_tbs tbs,
+ const heim_oid *oid,
+ const heim_octet_string *os)
+{
+ GeneralName gn;
+
+ memset(&gn, 0, sizeof(gn));
+ gn.element = choice_GeneralName_otherName;
+ gn.u.otherName.type_id = *oid;
+ gn.u.otherName.value = *os;
+
+ return add_GeneralNames(&tbs->san, &gn);
+}
+
+static
+int
+dequote_strndup(hx509_context context, const char *in, size_t len, char **out)
+{
+ size_t i, k;
+ char *s;
+
+ *out = NULL;
+ if ((s = malloc(len + 1)) == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "malloc: out of memory");
+ return ENOMEM;
+ }
+
+ for (k = i = 0; i < len; i++) {
+ if (in[i] == '\\') {
+ switch (in[++i]) {
+ case 't': s[k++] = '\t'; break;
+ case 'b': s[k++] = '\b'; break;
+ case 'n': s[k++] = '\n'; break;
+ case '0':
+ for (i++; i < len; i++) {
+ if (in[i] == '\0')
+ break;
+ if (in[i++] == '\\' && in[i] == '0')
+ continue;
+ hx509_set_error_string(context, 0,
+ HX509_PARSING_NAME_FAILED,
+ "embedded NULs not supported in "
+ "PKINIT SANs");
+ free(s);
+ return HX509_PARSING_NAME_FAILED;
+ }
+ break;
+ case '\0':
+ hx509_set_error_string(context, 0,
+ HX509_PARSING_NAME_FAILED,
+ "trailing unquoted backslashes not "
+ "allowed in PKINIT SANs");
+ free(s);
+ return HX509_PARSING_NAME_FAILED;
+ default: s[k++] = in[i]; break;
+ }
+ } else {
+ s[k++] = in[i];
+ }
+ }
+ s[k] = '\0';
+
+ *out = s;
+ return 0;
+}
+
+int
+_hx509_make_pkinit_san(hx509_context context,
+ const char *principal,
+ heim_octet_string *os)
+{
+ KRB5PrincipalName p;
+ size_t size;
+ int ret;
+
+ os->data = NULL;
+ os->length = 0;
+ memset(&p, 0, sizeof(p));
+
+ /* Parse principal */
+ {
+ const char *str, *str_start;
+ size_t n, i;
+
+ /* Count number of components */
+ n = 1;
+ for (str = principal; *str != '\0' && *str != '@'; str++) {
+ if (*str == '\\') {
+ if (str[1] == '\0') {
+ ret = HX509_PARSING_NAME_FAILED;
+ hx509_set_error_string(context, 0, ret,
+ "trailing \\ in principal name");
+ goto out;
+ }
+ str++;
+ } else if(*str == '/') {
+ n++;
+ } else if(*str == '@') {
+ break;
+ }
+ }
+ if (*str != '@') {
+ /* Note that we allow the realm to be empty */
+ ret = HX509_PARSING_NAME_FAILED;
+ hx509_set_error_string(context, 0, ret, "Missing @ in principal");
+ goto out;
+ };
+
+ p.principalName.name_string.val =
+ calloc(n, sizeof(*p.principalName.name_string.val));
+ if (p.principalName.name_string.val == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "malloc: out of memory");
+ goto out;
+ }
+ p.principalName.name_string.len = n;
+ p.principalName.name_type = KRB5_NT_PRINCIPAL;
+
+ for (i = 0, str_start = str = principal; *str != '\0'; str++) {
+ if (*str=='\\') {
+ str++;
+ } else if(*str == '/') {
+ /* Note that we allow components to be empty */
+ ret = dequote_strndup(context, str_start, str - str_start,
+ &p.principalName.name_string.val[i++]);
+ if (ret)
+ goto out;
+ str_start = str + 1;
+ } else if(*str == '@') {
+ ret = dequote_strndup(context, str_start, str - str_start,
+ &p.principalName.name_string.val[i++]);
+ if (ret == 0)
+ ret = dequote_strndup(context, str + 1, strlen(str + 1), &p.realm);
+ if (ret)
+ goto out;
+ break;
+ }
+ }
+ }
+
+ ASN1_MALLOC_ENCODE(KRB5PrincipalName, os->data, os->length, &p, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ if (size != os->length)
+ _hx509_abort("internal ASN.1 encoder error");
+
+out:
+ free_KRB5PrincipalName(&p);
+ return ret;
+}
+
+static int
+add_ia5string_san(hx509_context context,
+ hx509_ca_tbs tbs,
+ const heim_oid *oid,
+ const char *string)
+{
+ SRVName ustring;
+ heim_octet_string os;
+ size_t size;
+ int ret;
+
+ ustring.data = (void *)(uintptr_t)string;
+ ustring.length = strlen(string);
+
+ os.length = 0;
+ os.data = NULL;
+
+ ASN1_MALLOC_ENCODE(SRVName, os.data, os.length, &ustring, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ return ret;
+ }
+ if (size != os.length)
+ _hx509_abort("internal ASN.1 encoder error");
+
+ ret = hx509_ca_tbs_add_san_otherName(context, tbs, oid, &os);
+ free(os.data);
+ return ret;
+}
+
+/**
+ * Add DNSSRV Subject Alternative Name to the to-be-signed certificate object.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param dnssrv An ASCII string of the for _Service.Name.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_san_dnssrv(hx509_context context,
+ hx509_ca_tbs tbs,
+ const char *dnssrv)
+{
+ size_t i, len;
+
+ /* Minimal DNSSRV input validation */
+ if (dnssrv == 0 || dnssrv[0] != '_') {
+ hx509_set_error_string(context, 0, EINVAL, "Invalid DNSSRV name");
+ return EINVAL;
+ }
+ for (i = 1, len = strlen(dnssrv); i < len; i++) {
+ if (dnssrv[i] == '.' && dnssrv[i + 1] != '\0')
+ break;
+ }
+ if (i == len) {
+ hx509_set_error_string(context, 0, EINVAL, "Invalid DNSSRV name");
+ return EINVAL;
+ }
+
+ return add_ia5string_san(context, tbs,
+ &asn1_oid_id_pkix_on_dnsSRV, dnssrv);
+}
+
+/**
+ * Add Kerberos Subject Alternative Name to the to-be-signed
+ * certificate object. The principal string is a UTF8 string.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param principal Kerberos principal to add to the certificate.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_san_pkinit(hx509_context context,
+ hx509_ca_tbs tbs,
+ const char *principal)
+{
+ heim_octet_string os;
+ int ret;
+
+ ret = _hx509_make_pkinit_san(context, principal, &os);
+ if (ret == 0)
+ ret = hx509_ca_tbs_add_san_otherName(context, tbs,
+ &asn1_oid_id_pkinit_san, &os);
+ free(os.data);
+ return ret;
+}
+
+/*
+ *
+ */
+
+static int
+add_utf8_san(hx509_context context,
+ hx509_ca_tbs tbs,
+ const heim_oid *oid,
+ const char *string)
+{
+ const PKIXXmppAddr ustring = (const PKIXXmppAddr)(uintptr_t)string;
+ heim_octet_string os;
+ size_t size;
+ int ret;
+
+ os.length = 0;
+ os.data = NULL;
+
+ ASN1_MALLOC_ENCODE(PKIXXmppAddr, os.data, os.length, &ustring, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ return ret;
+ }
+ if (size != os.length)
+ _hx509_abort("internal ASN.1 encoder error");
+
+ ret = hx509_ca_tbs_add_san_otherName(context, tbs, oid, &os);
+ free(os.data);
+ return ret;
+}
+
+/**
+ * Add Microsoft UPN Subject Alternative Name to the to-be-signed
+ * certificate object. The principal string is a UTF8 string.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param principal Microsoft UPN string.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_san_ms_upn(hx509_context context,
+ hx509_ca_tbs tbs,
+ const char *principal)
+{
+ return add_utf8_san(context, tbs, &asn1_oid_id_pkinit_ms_san, principal);
+}
+
+/**
+ * Add a Jabber/XMPP jid Subject Alternative Name to the to-be-signed
+ * certificate object. The jid is an UTF8 string.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param jid string of an a jabber id in UTF8.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_san_jid(hx509_context context,
+ hx509_ca_tbs tbs,
+ const char *jid)
+{
+ return add_utf8_san(context, tbs, &asn1_oid_id_pkix_on_xmppAddr, jid);
+}
+
+
+/**
+ * Add a Subject Alternative Name hostname to to-be-signed certificate
+ * object. A domain match starts with ., an exact match does not.
+ *
+ * Example of a an domain match: .domain.se matches the hostname
+ * host.domain.se.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param dnsname a hostame.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_san_hostname(hx509_context context,
+ hx509_ca_tbs tbs,
+ const char *dnsname)
+{
+ GeneralName gn;
+
+ memset(&gn, 0, sizeof(gn));
+ gn.element = choice_GeneralName_dNSName;
+ gn.u.dNSName.data = rk_UNCONST(dnsname);
+ gn.u.dNSName.length = strlen(dnsname);
+
+ return add_GeneralNames(&tbs->san, &gn);
+}
+
+/**
+ * Add a Subject Alternative Name rfc822 (email address) to
+ * to-be-signed certificate object.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param rfc822Name a string to a email address.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_san_rfc822name(hx509_context context,
+ hx509_ca_tbs tbs,
+ const char *rfc822Name)
+{
+ GeneralName gn;
+
+ memset(&gn, 0, sizeof(gn));
+ gn.element = choice_GeneralName_rfc822Name;
+ gn.u.rfc822Name.data = rk_UNCONST(rfc822Name);
+ gn.u.rfc822Name.length = strlen(rfc822Name);
+
+ return add_GeneralNames(&tbs->san, &gn);
+}
+
+/*
+ * PermanentIdentifier is one SAN for naming devices with TPMs after their
+ * endorsement keys or EK certificates. See TPM 2.0 Keys for Device Identity
+ * and Attestation, Version 1.00, Revision 2, 9/17/2020 (DRAFT).
+ *
+ * The text on the form of permanent identifiers for TPM endorsement keys sans
+ * certificates is clearly problematic, saying: "When the TPM does not have an
+ * EK certificate, the identifierValue is a digest of a concatenation of the
+ * UTF8 string “EkPubkey” (terminating NULL not included) with the binary EK
+ * public key", but since arbitrary binary is not necessarily valid UTF-8...
+ * and since NULs embedded in UTF-8 might be OK in some contexts but really
+ * isn't in C (and Heimdal's ASN.1 compiler does not allow NULs in the
+ * middle of strings)... That just cannot be correct. Since elsewhere the TCG
+ * specs use the hex encoding of the SHA-256 digest of the DER encoding of
+ * public keys, that's what we should support in Heimdal, and maybe send in a
+ * comment.
+ *
+ * Also, even where one should use hex encoding of the SHA-256 digest of the
+ * DER encoding of public keys, how should the public keys be represented?
+ * Presumably as SPKIs, with all the required parameters and no more.
+ */
+
+/**
+ * Add a Subject Alternative Name of PermanentIdentifier type to a to-be-signed
+ * certificate object. The permanent identifier form for TPM endorsement key
+ * certificates is the hex encoding of the SHA-256 digest of the DER encoding
+ * of the certificate. The permanent identifier form for TPM endorsement keys
+ * are of the form "EkPubkey<public-key>", where the form of <public-key> is
+ * not well specified at this point. It is the caller's responsibility to
+ * format the identifierValue.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param str permanent identifier name in the form "[<assigner-oid>]:[<id>]".
+ * @param assigner The OID of an assigner.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_san_permanentIdentifier_string(hx509_context context,
+ hx509_ca_tbs tbs,
+ const char *str)
+{
+ const heim_oid *found = NULL;
+ heim_oid oid;
+ const char *oidstr, *id;
+ char *freeme, *p;
+ int ret;
+
+ if ((freeme = strdup(str)) == NULL)
+ return hx509_enomem(context);
+
+ oidstr = freeme;
+ p = strchr(freeme, ':');
+ if (!p) {
+ hx509_set_error_string(context, 0, EINVAL,
+ "Invalid PermanentIdentifier string (should be \"[<oid>]:[<id>]\")",
+ oidstr);
+ free(freeme);
+ return EINVAL;
+ }
+ if (p) {
+ *(p++) = '\0';
+ id = p;
+ }
+ if (oidstr[0] != '\0') {
+ ret = der_find_heim_oid_by_name(oidstr, &found);
+ if (ret) {
+ ret = der_parse_heim_oid(oidstr, " .", &oid);
+ if (ret == 0)
+ found = &oid;
+ }
+ }
+ ret = hx509_ca_tbs_add_san_permanentIdentifier(context, tbs, id, found);
+ if (found == &oid)
+ der_free_oid(&oid);
+ free(freeme);
+ return ret;
+}
+
+/**
+ * Add a Subject Alternative Name of PermanentIdentifier type to a to-be-signed
+ * certificate object. The permanent identifier form for TPM endorsement key
+ * certificates is the hex encoding of the SHA-256 digest of the DER encoding
+ * of the certificate. The permanent identifier form for TPM endorsement keys
+ * are of the form "EkPubkey<public-key>", where the form of <public-key> is
+ * not well specified at this point. It is the caller's responsibility to
+ * format the identifierValue.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param identifierValue The permanent identifier name.
+ * @param assigner The OID of an assigner.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_san_permanentIdentifier(hx509_context context,
+ hx509_ca_tbs tbs,
+ const char *identifierValue,
+ const heim_oid *assigner)
+{
+ PermanentIdentifier pi;
+ heim_utf8_string s = (void *)(uintptr_t)identifierValue;
+ heim_octet_string os;
+ size_t size;
+ int ret;
+
+ pi.identifierValue = &s;
+ pi.assigner = (heim_oid*)(uintptr_t)assigner;
+ os.length = 0;
+ os.data = NULL;
+
+ ASN1_MALLOC_ENCODE(PermanentIdentifier, os.data, os.length, &pi, &size,
+ ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ return ret;
+ }
+ if (size != os.length)
+ _hx509_abort("internal ASN.1 encoder error");
+
+ ret = hx509_ca_tbs_add_san_otherName(context, tbs,
+ &asn1_oid_id_pkix_on_permanentIdentifier,
+ &os);
+ free(os.data);
+ return ret;
+}
+
+/**
+ * Add a Subject Alternative Name of HardwareModuleName type to a to-be-signed
+ * certificate object.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param str a string of the form "<oid>:<serial>".
+ * @param hwserial The serial number.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_san_hardwareModuleName_string(hx509_context context,
+ hx509_ca_tbs tbs,
+ const char *str)
+{
+ const heim_oid *found = NULL;
+ heim_oid oid;
+ const char *oidstr, *sno;
+ char *freeme, *p;
+ int ret;
+
+ if ((freeme = strdup(str)) == NULL)
+ return hx509_enomem(context);
+
+ oidstr = freeme;
+ p = strchr(freeme, ':');
+ if (!p) {
+ hx509_set_error_string(context, 0, EINVAL,
+ "Invalid HardwareModuleName string (should be "
+ "\"<oid>:<serial>\")",
+ oidstr);
+ free(freeme);
+ return EINVAL;
+ }
+ if (p) {
+ *(p++) = '\0';
+ sno = p;
+ }
+ if (oidstr[0] == '\0') {
+ found = &asn1_oid_tcg_tpm20;
+ } else {
+ ret = der_find_heim_oid_by_name(oidstr, &found);
+ if (ret) {
+ ret = der_parse_heim_oid(oidstr, " .", &oid);
+ if (ret == 0)
+ found = &oid;
+ }
+ }
+ if (!found) {
+ hx509_set_error_string(context, 0, EINVAL,
+ "Could not resolve or parse OID \"%s\"",
+ oidstr);
+ free(freeme);
+ return EINVAL;
+ }
+ ret = hx509_ca_tbs_add_san_hardwareModuleName(context, tbs, found, sno);
+ if (found == &oid)
+ der_free_oid(&oid);
+ free(freeme);
+ return ret;
+}
+
+/**
+ * Add a Subject Alternative Name of HardwareModuleName type to a to-be-signed
+ * certificate object.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param hwtype The hardwar module type (e.g., `&asn1_oid_tcg_tpm20').
+ * @param hwserial The serial number.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_san_hardwareModuleName(hx509_context context,
+ hx509_ca_tbs tbs,
+ const heim_oid *hwtype,
+ const char *hwserial)
+{
+ HardwareModuleName hm;
+ heim_octet_string os;
+ size_t size;
+ int ret;
+
+ hm.hwType = *hwtype;
+ hm.hwSerialNum.data = (void *)(uintptr_t)hwserial;
+ hm.hwSerialNum.length = strlen(hwserial);
+ os.length = 0;
+ os.data = NULL;
+
+ ASN1_MALLOC_ENCODE(HardwareModuleName, os.data, os.length, &hm, &size,
+ ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ return ret;
+ }
+ if (size != os.length)
+ _hx509_abort("internal ASN.1 encoder error");
+
+ ret = hx509_ca_tbs_add_san_otherName(context, tbs,
+ &asn1_oid_id_on_hardwareModuleName,
+ &os);
+ free(os.data);
+ return ret;
+}
+
+/**
+ * Add a Subject Alternative Name of the given type to the
+ * to-be-signed certificate object.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param rfc822Name a string to a email address.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_add_san(hx509_context context,
+ hx509_ca_tbs tbs,
+ hx509_san_type type,
+ const char *s)
+{
+ switch (type) {
+ case HX509_SAN_TYPE_EMAIL:
+ return hx509_ca_tbs_add_san_rfc822name(context, tbs, s);
+ case HX509_SAN_TYPE_DNSNAME:
+ return hx509_ca_tbs_add_san_hostname(context, tbs, s);
+ case HX509_SAN_TYPE_DN:
+ return ENOTSUP;
+ case HX509_SAN_TYPE_REGISTERED_ID:
+ return ENOTSUP;
+ case HX509_SAN_TYPE_XMPP:
+ return hx509_ca_tbs_add_san_jid(context, tbs, s);
+ case HX509_SAN_TYPE_PKINIT:
+ return hx509_ca_tbs_add_san_pkinit(context, tbs, s);
+ case HX509_SAN_TYPE_MS_UPN:
+ return hx509_ca_tbs_add_san_ms_upn(context, tbs, s);
+ default:
+ return ENOTSUP;
+ }
+}
+
+/**
+ * Set the subject name of a to-be-signed certificate object.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param subject the name to set a subject.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_set_subject(hx509_context context,
+ hx509_ca_tbs tbs,
+ hx509_name subject)
+{
+ if (tbs->subject)
+ hx509_name_free(&tbs->subject);
+ return hx509_name_copy(context, subject, &tbs->subject);
+}
+
+/**
+ * Set the issuerUniqueID and subjectUniqueID
+ *
+ * These are only supposed to be used considered with version 2
+ * certificates, replaced by the two extensions SubjectKeyIdentifier
+ * and IssuerKeyIdentifier. This function is to allow application
+ * using legacy protocol to issue them.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param issuerUniqueID to be set
+ * @param subjectUniqueID to be set
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_set_unique(hx509_context context,
+ hx509_ca_tbs tbs,
+ const heim_bit_string *subjectUniqueID,
+ const heim_bit_string *issuerUniqueID)
+{
+ int ret;
+
+ der_free_bit_string(&tbs->subjectUniqueID);
+ der_free_bit_string(&tbs->issuerUniqueID);
+
+ if (subjectUniqueID) {
+ ret = der_copy_bit_string(subjectUniqueID, &tbs->subjectUniqueID);
+ if (ret)
+ return ret;
+ }
+
+ if (issuerUniqueID) {
+ ret = der_copy_bit_string(issuerUniqueID, &tbs->issuerUniqueID);
+ if (ret)
+ return ret;
+ }
+
+ return 0;
+}
+
+/**
+ * Expand the the subject name in the to-be-signed certificate object
+ * using hx509_name_expand().
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param env environment variable to expand variables in the subject
+ * name, see hx509_env_init().
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_subject_expand(hx509_context context,
+ hx509_ca_tbs tbs,
+ hx509_env env)
+{
+ return hx509_name_expand(context, tbs->subject, env);
+}
+
+/**
+ * Get the name of a to-be-signed certificate object.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ *
+ * @return An hx509 name.
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION hx509_name HX509_LIB_CALL
+hx509_ca_tbs_get_name(hx509_ca_tbs tbs)
+{
+ return tbs->subject;
+}
+
+/**
+ * Set signature algorithm on the to be signed certificate
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param sigalg signature algorithm to use
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_tbs_set_signature_algorithm(hx509_context context,
+ hx509_ca_tbs tbs,
+ const AlgorithmIdentifier *sigalg)
+{
+ int ret;
+
+ tbs->sigalg = calloc(1, sizeof(*tbs->sigalg));
+ if (tbs->sigalg == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "Out of memory");
+ return ENOMEM;
+ }
+ ret = copy_AlgorithmIdentifier(sigalg, tbs->sigalg);
+ if (ret) {
+ free(tbs->sigalg);
+ tbs->sigalg = NULL;
+ return ret;
+ }
+ return 0;
+}
+
+/*
+ *
+ */
+
+static int
+add_extension(hx509_context context,
+ TBSCertificate *tbsc,
+ int critical_flag,
+ const heim_oid *oid,
+ const heim_octet_string *data)
+{
+ Extension ext;
+ int ret;
+
+ memset(&ext, 0, sizeof(ext));
+
+ ext.critical = critical_flag;
+ ret = der_copy_oid(oid, &ext.extnID);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ ret = der_copy_octet_string(data, &ext.extnValue);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ ret = add_Extensions(tbsc->extensions, &ext);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+out:
+ free_Extension(&ext);
+ return ret;
+}
+
+static int
+build_proxy_prefix(hx509_context context, const Name *issuer, Name *subject)
+{
+ char *tstr;
+ time_t t;
+ int ret;
+
+ ret = copy_Name(issuer, subject);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to copy subject name");
+ return ret;
+ }
+
+ t = time(NULL);
+ ret = asprintf(&tstr, "ts-%lu", (unsigned long)t);
+ if (ret == -1 || tstr == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM,
+ "Failed to copy subject name");
+ return ENOMEM;
+ }
+ /* prefix with CN=<ts>,...*/
+ ret = _hx509_name_modify(context, subject, 1, &asn1_oid_id_at_commonName, tstr);
+ free(tstr);
+ if (ret)
+ free_Name(subject);
+ return ret;
+}
+
+static int
+ca_sign(hx509_context context,
+ hx509_ca_tbs tbs,
+ hx509_private_key signer,
+ const AuthorityKeyIdentifier *ai,
+ const Name *issuername,
+ hx509_cert *certificate)
+{
+ heim_error_t error = NULL;
+ heim_octet_string data;
+ Certificate c;
+ TBSCertificate *tbsc;
+ size_t size;
+ int ret;
+ const AlgorithmIdentifier *sigalg;
+ time_t notBefore;
+ time_t notAfter;
+
+ sigalg = tbs->sigalg;
+ if (sigalg == NULL)
+ sigalg = _hx509_crypto_default_sig_alg;
+
+ memset(&c, 0, sizeof(c));
+
+ /*
+ * Default values are: Valid since 24h ago, valid one year into
+ * the future, KeyUsage digitalSignature and keyEncipherment set,
+ * and keyCertSign for CA certificates.
+ */
+ notBefore = tbs->notBefore;
+ if (notBefore == 0)
+ notBefore = time(NULL) - 3600 * 24;
+ notAfter = tbs->notAfter;
+ if (notAfter == 0)
+ notAfter = time(NULL) + 3600 * 24 * 365;
+
+ if (tbs->flags.ca) {
+ tbs->ku.keyCertSign = 1;
+ tbs->ku.cRLSign = 1;
+ } else if (KeyUsage2int(tbs->ku) == 0) {
+ tbs->ku.digitalSignature = 1;
+ tbs->ku.keyEncipherment = 1;
+ }
+
+ /*
+ *
+ */
+
+ tbsc = &c.tbsCertificate;
+
+ /* Default subject Name to empty */
+ if (tbs->subject == NULL &&
+ (ret = hx509_empty_name(context, &tbs->subject)))
+ return ret;
+
+ /* Sanity checks */
+ if (tbs->flags.key == 0) {
+ ret = EINVAL;
+ hx509_set_error_string(context, 0, ret, "No public key set");
+ return ret;
+ }
+ /*
+ * Don't put restrictions on proxy certificate's subject name, it
+ * will be generated below.
+ */
+ if (!tbs->flags.proxy) {
+ if (hx509_name_is_null_p(tbs->subject) && tbs->san.len == 0) {
+ hx509_set_error_string(context, 0, EINVAL,
+ "Empty subject and no SubjectAltNames");
+ return EINVAL;
+ }
+ }
+ if (tbs->flags.ca && tbs->flags.proxy) {
+ hx509_set_error_string(context, 0, EINVAL, "Can't be proxy and CA "
+ "at the same time");
+ return EINVAL;
+ }
+ if (tbs->flags.proxy) {
+ if (tbs->san.len > 0) {
+ hx509_set_error_string(context, 0, EINVAL,
+ "Proxy certificate is not allowed "
+ "to have SubjectAltNames");
+ return EINVAL;
+ }
+ }
+
+ /* version [0] Version OPTIONAL, -- EXPLICIT nnn DEFAULT 1, */
+ tbsc->version = calloc(1, sizeof(*tbsc->version));
+ if (tbsc->version == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ *tbsc->version = rfc3280_version_3;
+ /* serialNumber CertificateSerialNumber, */
+ if (tbs->flags.serial) {
+ ret = der_copy_heim_integer(&tbs->serial, &tbsc->serialNumber);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ } else {
+ /*
+ * If no explicit serial number is specified, 20 random bytes should be
+ * sufficiently collision resistant. Since the serial number must be a
+ * positive integer, ensure minimal ASN.1 DER form by forcing the high
+ * bit off and the next bit on (thus avoiding an all zero first octet).
+ */
+ tbsc->serialNumber.length = 20;
+ tbsc->serialNumber.data = malloc(tbsc->serialNumber.length);
+ if (tbsc->serialNumber.data == NULL){
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ RAND_bytes(tbsc->serialNumber.data, tbsc->serialNumber.length);
+ ((unsigned char *)tbsc->serialNumber.data)[0] &= 0x7f;
+ ((unsigned char *)tbsc->serialNumber.data)[0] |= 0x40;
+ }
+ /* signature AlgorithmIdentifier, */
+ ret = copy_AlgorithmIdentifier(sigalg, &tbsc->signature);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Failed to copy signature alg");
+ goto out;
+ }
+ /* issuer Name, */
+ if (issuername)
+ ret = copy_Name(issuername, &tbsc->issuer);
+ else
+ ret = hx509_name_to_Name(tbs->subject, &tbsc->issuer);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Failed to copy issuer name");
+ goto out;
+ }
+ /* validity Validity, */
+ {
+ /*
+ * From RFC 5280, section 4.1.2.5:
+ *
+ * CAs conforming to this profile MUST always encode certificate
+ * validity dates through the year 2049 as UTCTime; certificate validity
+ * dates in 2050 or later MUST be encoded as GeneralizedTime.
+ * Conforming applications MUST be able to process validity dates that
+ * are encoded in either UTCTime or GeneralizedTime.
+ *
+ * 2524608000 is seconds since the epoch for 2050-01-01T00:00:00Z.
+ *
+ * Both, ...u.generalTime and ...u..utcTime are time_t.
+ */
+ if (notBefore < 1 || (int64_t)notBefore < 2524608000)
+ tbsc->validity.notBefore.element = choice_Time_utcTime;
+ else
+ tbsc->validity.notBefore.element = choice_Time_generalTime;
+ tbsc->validity.notBefore.u.generalTime = notBefore;
+
+ if (notAfter < 1 || (int64_t)notAfter < 2524608000)
+ tbsc->validity.notAfter.element = choice_Time_utcTime;
+ else
+ tbsc->validity.notAfter.element = choice_Time_generalTime;
+ tbsc->validity.notAfter.u.generalTime = notAfter;
+ }
+ /* subject Name, */
+ if (tbs->flags.proxy) {
+ ret = build_proxy_prefix(context, &tbsc->issuer, &tbsc->subject);
+ if (ret)
+ goto out;
+ } else {
+ ret = hx509_name_to_Name(tbs->subject, &tbsc->subject);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to copy subject name");
+ goto out;
+ }
+ }
+ /* subjectPublicKeyInfo SubjectPublicKeyInfo, */
+ ret = copy_SubjectPublicKeyInfo(&tbs->spki, &tbsc->subjectPublicKeyInfo);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Failed to copy spki");
+ goto out;
+ }
+ /* issuerUniqueID [1] IMPLICIT BIT STRING OPTIONAL */
+ if (tbs->issuerUniqueID.length) {
+ tbsc->issuerUniqueID = calloc(1, sizeof(*tbsc->issuerUniqueID));
+ if (tbsc->issuerUniqueID == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ ret = der_copy_bit_string(&tbs->issuerUniqueID, tbsc->issuerUniqueID);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ }
+ /* subjectUniqueID [2] IMPLICIT BIT STRING OPTIONAL */
+ if (tbs->subjectUniqueID.length) {
+ tbsc->subjectUniqueID = calloc(1, sizeof(*tbsc->subjectUniqueID));
+ if (tbsc->subjectUniqueID == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+
+ ret = der_copy_bit_string(&tbs->subjectUniqueID, tbsc->subjectUniqueID);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ }
+
+ /* extensions [3] EXPLICIT Extensions OPTIONAL */
+ tbsc->extensions = calloc(1, sizeof(*tbsc->extensions));
+ if (tbsc->extensions == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+
+ /* Add the text BMP string Domaincontroller to the cert */
+ if (tbs->flags.domaincontroller) {
+ data.data = rk_UNCONST("\x1e\x20\x00\x44\x00\x6f\x00\x6d"
+ "\x00\x61\x00\x69\x00\x6e\x00\x43"
+ "\x00\x6f\x00\x6e\x00\x74\x00\x72"
+ "\x00\x6f\x00\x6c\x00\x6c\x00\x65"
+ "\x00\x72");
+ data.length = 34;
+
+ ret = add_extension(context, tbsc, 0,
+ &asn1_oid_id_ms_cert_enroll_domaincontroller,
+ &data);
+ if (ret)
+ goto out;
+ }
+
+ /* Add KeyUsage */
+ if (KeyUsage2int(tbs->ku) > 0) {
+ ASN1_MALLOC_ENCODE(KeyUsage, data.data, data.length,
+ &tbs->ku, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ if (size != data.length)
+ _hx509_abort("internal ASN.1 encoder error");
+ ret = add_extension(context, tbsc, 1,
+ &asn1_oid_id_x509_ce_keyUsage, &data);
+ free(data.data);
+ if (ret)
+ goto out;
+ }
+
+ /* Add ExtendedKeyUsage */
+ if (tbs->eku.len > 0) {
+ ASN1_MALLOC_ENCODE(ExtKeyUsage, data.data, data.length,
+ &tbs->eku, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ if (size != data.length)
+ _hx509_abort("internal ASN.1 encoder error");
+ ret = add_extension(context, tbsc, 1,
+ &asn1_oid_id_x509_ce_extKeyUsage, &data);
+ free(data.data);
+ if (ret)
+ goto out;
+ }
+
+ /* Add Subject Alternative Name */
+ if (tbs->san.len > 0) {
+ ASN1_MALLOC_ENCODE(GeneralNames, data.data, data.length,
+ &tbs->san, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ if (size != data.length)
+ _hx509_abort("internal ASN.1 encoder error");
+
+ /* The SAN extension is critical if the subject Name is empty */
+ ret = add_extension(context, tbsc, hx509_name_is_null_p(tbs->subject),
+ &asn1_oid_id_x509_ce_subjectAltName, &data);
+ free(data.data);
+ if (ret)
+ goto out;
+ }
+
+ /* Add Authority Key Identifier */
+ if (ai) {
+ ASN1_MALLOC_ENCODE(AuthorityKeyIdentifier, data.data, data.length,
+ ai, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ if (size != data.length)
+ _hx509_abort("internal ASN.1 encoder error");
+ ret = add_extension(context, tbsc, 0,
+ &asn1_oid_id_x509_ce_authorityKeyIdentifier,
+ &data);
+ free(data.data);
+ if (ret)
+ goto out;
+ }
+
+ /* Add Subject Key Identifier */
+ {
+ SubjectKeyIdentifier si;
+ unsigned char hash[SHA_DIGEST_LENGTH];
+
+ {
+ EVP_MD_CTX *ctx;
+
+ ctx = EVP_MD_CTX_create();
+ EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
+ EVP_DigestUpdate(ctx, tbs->spki.subjectPublicKey.data,
+ tbs->spki.subjectPublicKey.length / 8);
+ EVP_DigestFinal_ex(ctx, hash, NULL);
+ EVP_MD_CTX_destroy(ctx);
+ }
+
+ si.data = hash;
+ si.length = sizeof(hash);
+
+ ASN1_MALLOC_ENCODE(SubjectKeyIdentifier, data.data, data.length,
+ &si, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ if (size != data.length)
+ _hx509_abort("internal ASN.1 encoder error");
+ ret = add_extension(context, tbsc, 0,
+ &asn1_oid_id_x509_ce_subjectKeyIdentifier,
+ &data);
+ free(data.data);
+ if (ret)
+ goto out;
+ }
+
+ /* Add BasicConstraints */
+ {
+ BasicConstraints bc;
+ unsigned int path;
+
+ memset(&bc, 0, sizeof(bc));
+
+ if (tbs->flags.ca) {
+ bc.cA = 1;
+ if (tbs->pathLenConstraint >= 0) {
+ path = tbs->pathLenConstraint;
+ bc.pathLenConstraint = &path;
+ }
+ }
+
+ ASN1_MALLOC_ENCODE(BasicConstraints, data.data, data.length,
+ &bc, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ if (size != data.length)
+ _hx509_abort("internal ASN.1 encoder error");
+ /* Critical if this is a CA */
+ ret = add_extension(context, tbsc, tbs->flags.ca,
+ &asn1_oid_id_x509_ce_basicConstraints,
+ &data);
+ free(data.data);
+ if (ret)
+ goto out;
+ }
+
+ /* Add Proxy */
+ if (tbs->flags.proxy) {
+ ProxyCertInfo info;
+
+ memset(&info, 0, sizeof(info));
+
+ if (tbs->pathLenConstraint >= 0) {
+ info.pCPathLenConstraint =
+ malloc(sizeof(*info.pCPathLenConstraint));
+ if (info.pCPathLenConstraint == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ *info.pCPathLenConstraint = tbs->pathLenConstraint;
+ }
+
+ ret = der_copy_oid(&asn1_oid_id_pkix_ppl_inheritAll,
+ &info.proxyPolicy.policyLanguage);
+ if (ret) {
+ free_ProxyCertInfo(&info);
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+
+ ASN1_MALLOC_ENCODE(ProxyCertInfo, data.data, data.length,
+ &info, &size, ret);
+ free_ProxyCertInfo(&info);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ if (size != data.length)
+ _hx509_abort("internal ASN.1 encoder error");
+ ret = add_extension(context, tbsc, 0,
+ &asn1_oid_id_pkix_pe_proxyCertInfo,
+ &data);
+ free(data.data);
+ if (ret)
+ goto out;
+ }
+
+ /* Add CRL distribution point */
+ if (tbs->crldp.len) {
+ ASN1_MALLOC_ENCODE(CRLDistributionPoints, data.data, data.length,
+ &tbs->crldp, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ if (size != data.length)
+ _hx509_abort("internal ASN.1 encoder error");
+ ret = add_extension(context, tbsc, FALSE,
+ &asn1_oid_id_x509_ce_cRLDistributionPoints,
+ &data);
+ free(data.data);
+ if (ret)
+ goto out;
+ }
+
+ /* Add CertificatePolicies */
+ if (tbs->cps.len) {
+ ASN1_MALLOC_ENCODE(CertificatePolicies, data.data, data.length,
+ &tbs->cps, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ if (size != data.length)
+ _hx509_abort("internal ASN.1 encoder error");
+ ret = add_extension(context, tbsc, FALSE,
+ &asn1_oid_id_x509_ce_certificatePolicies, &data);
+ free(data.data);
+ if (ret)
+ goto out;
+ }
+
+ /* Add PolicyMappings */
+ if (tbs->cps.len) {
+ ASN1_MALLOC_ENCODE(PolicyMappings, data.data, data.length,
+ &tbs->pms, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ if (size != data.length)
+ _hx509_abort("internal ASN.1 encoder error");
+ ret = add_extension(context, tbsc, FALSE,
+ &asn1_oid_id_x509_ce_policyMappings, &data);
+ free(data.data);
+ if (ret)
+ goto out;
+ }
+
+ /* Add Heimdal PKINIT ticket max life extension */
+ if (tbs->pkinitTicketMaxLife > 0) {
+ ASN1_MALLOC_ENCODE(HeimPkinitPrincMaxLifeSecs, data.data, data.length,
+ &tbs->pkinitTicketMaxLife, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ if (size != data.length)
+ _hx509_abort("internal ASN.1 encoder error");
+ ret = add_extension(context, tbsc, FALSE,
+ &asn1_oid_id_heim_ce_pkinit_princ_max_life, &data);
+ free(data.data);
+ if (ret)
+ goto out;
+ }
+
+ ASN1_MALLOC_ENCODE(TBSCertificate, data.data, data.length,tbsc, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "malloc out of memory");
+ goto out;
+ }
+ if (data.length != size)
+ _hx509_abort("internal ASN.1 encoder error");
+
+ ret = _hx509_create_signature_bitstring(context,
+ signer,
+ sigalg,
+ &data,
+ &c.signatureAlgorithm,
+ &c.signatureValue);
+ free(data.data);
+ if (ret)
+ goto out;
+
+ *certificate = hx509_cert_init(context, &c, &error);
+ if (*certificate == NULL) {
+ ret = heim_error_get_code(error);
+ heim_release(error);
+ goto out;
+ }
+
+ free_Certificate(&c);
+
+ return 0;
+
+out:
+ free_Certificate(&c);
+ return ret;
+}
+
+static int
+get_AuthorityKeyIdentifier(hx509_context context,
+ const Certificate *certificate,
+ AuthorityKeyIdentifier *ai)
+{
+ SubjectKeyIdentifier si;
+ int ret;
+
+ ret = _hx509_find_extension_subject_key_id(certificate, &si);
+ if (ret == 0) {
+ ai->keyIdentifier = calloc(1, sizeof(*ai->keyIdentifier));
+ if (ai->keyIdentifier == NULL) {
+ free_SubjectKeyIdentifier(&si);
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ ret = der_copy_octet_string(&si, ai->keyIdentifier);
+ free_SubjectKeyIdentifier(&si);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ } else {
+ GeneralNames gns;
+ GeneralName gn;
+ Name name;
+
+ memset(&gn, 0, sizeof(gn));
+ memset(&gns, 0, sizeof(gns));
+ memset(&name, 0, sizeof(name));
+
+ ai->authorityCertIssuer =
+ calloc(1, sizeof(*ai->authorityCertIssuer));
+ if (ai->authorityCertIssuer == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ ai->authorityCertSerialNumber =
+ calloc(1, sizeof(*ai->authorityCertSerialNumber));
+ if (ai->authorityCertSerialNumber == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+
+ /*
+ * XXX unbreak when asn1 compiler handle IMPLICIT
+ *
+ * This is so horrible.
+ */
+
+ ret = copy_Name(&certificate->tbsCertificate.subject, &name);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+
+ memset(&gn, 0, sizeof(gn));
+ gn.element = choice_GeneralName_directoryName;
+ gn.u.directoryName.element = choice_Name_rdnSequence;
+ gn.u.directoryName.u.rdnSequence = name.u.rdnSequence;
+
+ ret = add_GeneralNames(&gns, &gn);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+
+ ai->authorityCertIssuer->val = gns.val;
+ ai->authorityCertIssuer->len = gns.len;
+
+ ret = der_copy_heim_integer(&certificate->tbsCertificate.serialNumber,
+ ai->authorityCertSerialNumber);
+ if (ai->authorityCertSerialNumber == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ }
+out:
+ if (ret)
+ free_AuthorityKeyIdentifier(ai);
+ return ret;
+}
+
+
+/**
+ * Sign a to-be-signed certificate object with a issuer certificate.
+ *
+ * The caller needs to at least have called the following functions on the
+ * to-be-signed certificate object:
+ * - hx509_ca_tbs_init()
+ * - hx509_ca_tbs_set_subject()
+ * - hx509_ca_tbs_set_spki()
+ *
+ * When done the to-be-signed certificate object should be freed with
+ * hx509_ca_tbs_free().
+ *
+ * When creating self-signed certificate use hx509_ca_sign_self() instead.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param signer the CA certificate object to sign with (need private key).
+ * @param certificate return cerificate, free with hx509_cert_free().
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_sign(hx509_context context,
+ hx509_ca_tbs tbs,
+ hx509_cert signer,
+ hx509_cert *certificate)
+{
+ const Certificate *signer_cert;
+ AuthorityKeyIdentifier ai;
+ int ret;
+
+ memset(&ai, 0, sizeof(ai));
+
+ signer_cert = _hx509_get_cert(signer);
+
+ ret = get_AuthorityKeyIdentifier(context, signer_cert, &ai);
+ if (ret)
+ goto out;
+
+ ret = ca_sign(context,
+ tbs,
+ _hx509_cert_private_key(signer),
+ &ai,
+ &signer_cert->tbsCertificate.subject,
+ certificate);
+
+out:
+ free_AuthorityKeyIdentifier(&ai);
+
+ return ret;
+}
+
+/**
+ * Work just like hx509_ca_sign() but signs it-self.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param signer private key to sign with.
+ * @param certificate return cerificate, free with hx509_cert_free().
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ca_sign_self(hx509_context context,
+ hx509_ca_tbs tbs,
+ hx509_private_key signer,
+ hx509_cert *certificate)
+{
+ return ca_sign(context,
+ tbs,
+ signer,
+ NULL,
+ NULL,
+ certificate);
+}
+
+/*
+ * The following used to be `kdc_issue_certificate()', which was added for
+ * kx509 support in the kdc, then adapted for bx509d. It now has no
+ * kdc-specific code and very little krb5-specific code, and is named
+ * `hx509_ca_issue_certificate()'.
+ */
+
+/* From lib/krb5/principal.c */
+#define princ_num_comp(P) ((P)->principalName.name_string.len)
+#define princ_type(P) ((P)->principalName.name_type)
+#define princ_comp(P) ((P)->principalName.name_string.val)
+#define princ_ncomp(P, N) ((P)->principalName.name_string.val[(N)])
+#define princ_realm(P) ((P)->realm)
+
+static const char *
+princ_get_comp_string(KRB5PrincipalName *principal, unsigned int component)
+{
+ if (component >= princ_num_comp(principal))
+ return NULL;
+ return princ_ncomp(principal, component);
+}
+/* XXX Add unparse_name() */
+
+typedef enum {
+ CERT_NOTSUP = 0,
+ CERT_CLIENT = 1,
+ CERT_SERVER = 2,
+ CERT_MIXED = 3
+} cert_type;
+
+static void
+frees(char **s)
+{
+ free(*s);
+ *s = NULL;
+}
+
+static heim_error_code
+count_sans(hx509_request req, size_t *n)
+{
+ size_t i;
+ char *s = NULL;
+ int ret = 0;
+
+ *n = 0;
+ for (i = 0; ret == 0; i++) {
+ hx509_san_type san_type;
+
+ ret = hx509_request_get_san(req, i, &san_type, &s);
+ if (ret)
+ break;
+ switch (san_type) {
+ case HX509_SAN_TYPE_DNSNAME:
+ case HX509_SAN_TYPE_EMAIL:
+ case HX509_SAN_TYPE_XMPP:
+ case HX509_SAN_TYPE_PKINIT:
+ case HX509_SAN_TYPE_MS_UPN:
+ (*n)++;
+ break;
+ default:
+ ret = ENOTSUP;
+ }
+ frees(&s);
+ }
+ free(s);
+ return ret == HX509_NO_ITEM ? 0 : ret;
+}
+
+static int
+has_sans(hx509_request req)
+{
+ hx509_san_type san_type;
+ char *s = NULL;
+ int ret = hx509_request_get_san(req, 0, &san_type, &s);
+
+ frees(&s);
+ return ret == HX509_NO_ITEM ? 0 : 1;
+}
+
+static cert_type
+characterize_cprinc(hx509_context context,
+ KRB5PrincipalName *cprinc)
+{
+ unsigned int ncomp = princ_num_comp(cprinc);
+ const char *comp1 = princ_get_comp_string(cprinc, 1);
+
+ switch (ncomp) {
+ case 1:
+ return CERT_CLIENT;
+ case 2:
+ if (strchr(comp1, '.') == NULL)
+ return CERT_CLIENT;
+ return CERT_SERVER;
+ case 3:
+ if (strchr(comp1, '.'))
+ return CERT_SERVER;
+ return CERT_NOTSUP;
+ default:
+ return CERT_NOTSUP;
+ }
+}
+
+/* Characterize request as client or server cert req */
+static cert_type
+characterize(hx509_context context,
+ KRB5PrincipalName *cprinc,
+ hx509_request req)
+{
+ heim_error_code ret = 0;
+ cert_type res = CERT_NOTSUP;
+ size_t i;
+ char *s = NULL;
+ int want_ekus = 0;
+
+ if (!has_sans(req))
+ return characterize_cprinc(context, cprinc);
+
+ for (i = 0; ret == 0; i++) {
+ heim_oid oid;
+
+ frees(&s);
+ ret = hx509_request_get_eku(req, i, &s);
+ if (ret)
+ break;
+
+ want_ekus = 1;
+ ret = der_parse_heim_oid(s, ".", &oid);
+ if (ret)
+ break;
+ /*
+ * If the client wants only a server certificate, then we'll be
+ * willing to issue one that may be longer-lived than the client's
+ * ticket/token.
+ *
+ * There may be other server EKUs, but these are the ones we know
+ * of.
+ */
+ if (der_heim_oid_cmp(&asn1_oid_id_pkix_kp_serverAuth, &oid) &&
+ der_heim_oid_cmp(&asn1_oid_id_pkix_kp_OCSPSigning, &oid) &&
+ der_heim_oid_cmp(&asn1_oid_id_pkix_kp_secureShellServer, &oid))
+ res |= CERT_CLIENT;
+ else
+ res |= CERT_SERVER;
+ der_free_oid(&oid);
+ }
+ frees(&s);
+ if (ret == HX509_NO_ITEM)
+ ret = 0;
+
+ for (i = 0; ret == 0; i++) {
+ hx509_san_type san_type;
+
+ frees(&s);
+ ret = hx509_request_get_san(req, i, &san_type, &s);
+ if (ret)
+ break;
+ switch (san_type) {
+ case HX509_SAN_TYPE_DNSNAME:
+ if (!want_ekus)
+ res |= CERT_SERVER;
+ break;
+ case HX509_SAN_TYPE_EMAIL:
+ case HX509_SAN_TYPE_XMPP:
+ case HX509_SAN_TYPE_PKINIT:
+ case HX509_SAN_TYPE_MS_UPN:
+ if (!want_ekus)
+ res |= CERT_CLIENT;
+ break;
+ default:
+ ret = ENOTSUP;
+ }
+ if (ret)
+ break;
+ }
+ frees(&s);
+ if (ret == HX509_NO_ITEM)
+ ret = 0;
+ return ret ? CERT_NOTSUP : res;
+}
+
+/*
+ * Get a configuration sub-tree for kx509 based on what's being requested and
+ * by whom.
+ *
+ * We have a number of cases:
+ *
+ * - default certificate (no CSR used, or no certificate extensions requested)
+ * - for client principals
+ * - for service principals
+ * - client certificate requested (CSR used and client-y SANs/EKUs requested)
+ * - server certificate requested (CSR used and server-y SANs/EKUs requested)
+ * - mixed client/server certificate requested (...)
+ */
+static heim_error_code
+get_cf(hx509_context context,
+ const heim_config_binding *cf,
+ heim_log_facility *logf,
+ hx509_request req,
+ KRB5PrincipalName *cprinc,
+ const heim_config_binding **out)
+{
+ heim_error_code ret;
+ unsigned int ncomp = princ_num_comp(cprinc);
+ const char *realm = princ_realm(cprinc);
+ const char *comp0 = princ_get_comp_string(cprinc, 0);
+ const char *comp1 = princ_get_comp_string(cprinc, 1);
+ const char *label = NULL;
+ const char *svc = NULL;
+ const char *def = NULL;
+ cert_type certtype = CERT_NOTSUP;
+ size_t nsans = 0;
+
+ *out = NULL;
+ if (ncomp == 0) {
+ heim_log_msg(context->hcontext, logf, 5, NULL,
+ "Client principal has no components!");
+ hx509_set_error_string(context, 0, ret = ENOTSUP,
+ "Client principal has no components!");
+ return ret;
+ }
+
+ if ((ret = count_sans(req, &nsans)) ||
+ (certtype = characterize(context, cprinc, req)) == CERT_NOTSUP) {
+ heim_log_msg(context->hcontext, logf, 5, NULL,
+ "Could not characterize CSR");
+ hx509_set_error_string(context, 0, ret, "Could not characterize CSR");
+ return ret;
+ }
+
+ if (nsans) {
+ def = "custom";
+ /* Client requested some certificate extension, a SAN or EKU */
+ switch (certtype) {
+ case CERT_MIXED: label = "mixed"; break;
+ case CERT_CLIENT: label = "client"; break;
+ case CERT_SERVER: label = "server"; break;
+ default:
+ hx509_set_error_string(context, 0, ret = ENOTSUP,
+ "Requested SAN/EKU combination not "
+ "supported");
+ return ret;
+ }
+ } else {
+ def = "default";
+ /* Default certificate desired */
+ if (ncomp == 1) {
+ label = "user";
+ } else if (ncomp == 2 && strcmp(comp1, "root") == 0) {
+ label = "root_user";
+ } else if (ncomp == 2 && strcmp(comp1, "admin") == 0) {
+ label = "admin_user";
+ } else if (strchr(comp1, '.')) {
+ label = "hostbased_service";
+ svc = comp0;
+ } else {
+ label = "other";
+ }
+ }
+
+ *out = heim_config_get_list(context->hcontext, cf, label, svc, NULL);
+ if (*out) {
+ ret = 0;
+ } else {
+ heim_log_msg(context->hcontext, logf, 3, NULL,
+ "No configuration for %s %s certificate's realm "
+ "-> %s -> kx509 -> %s%s%s", def, label, realm, label,
+ svc ? " -> " : "", svc ? svc : "");
+ hx509_set_error_string(context, 0, EACCES,
+ "No configuration for %s %s certificate's realm "
+ "-> %s -> kx509 -> %s%s%s", def, label, realm, label,
+ svc ? " -> " : "", svc ? svc : "");
+ }
+ return ret;
+}
+
+
+/*
+ * Find and set a certificate template using a configuration sub-tree
+ * appropriate to the requesting principal.
+ *
+ * This allows for the specification of the following in configuration:
+ *
+ * - certificates as templates, with ${var} tokens in subjectName attribute
+ * values that will be expanded later
+ * - a plain string with ${var} tokens to use as the subjectName
+ * - EKUs
+ * - whether to include a PKINIT SAN
+ */
+static heim_error_code
+set_template(hx509_context context,
+ heim_log_facility *logf,
+ const heim_config_binding *cf,
+ hx509_ca_tbs tbs)
+{
+ heim_error_code ret = 0;
+ const char *cert_template = NULL;
+ const char *subj_name = NULL;
+ char **ekus = NULL;
+
+ if (cf == NULL)
+ return EACCES; /* Can't happen */
+
+ cert_template = heim_config_get_string(context->hcontext, cf,
+ "template_cert", NULL);
+ subj_name = heim_config_get_string(context->hcontext, cf, "subject_name",
+ NULL);
+ ekus = heim_config_get_strings(context->hcontext, cf, "ekus", NULL);
+
+ if (cert_template) {
+ hx509_certs certs;
+ hx509_cert template;
+
+ ret = hx509_certs_init(context, cert_template, 0, NULL, &certs);
+ if (ret == 0)
+ ret = hx509_get_one_cert(context, certs, &template);
+ hx509_certs_free(&certs);
+ if (ret) {
+ heim_log_msg(context->hcontext, logf, 1, NULL,
+ "Failed to load certificate template from %s",
+ cert_template);
+ hx509_set_error_string(context, 0, EACCES,
+ "Failed to load certificate template from "
+ "%s", cert_template);
+ return ret;
+ }
+
+ /*
+ * Only take the subjectName, the keyUsage, and EKUs from the template
+ * certificate.
+ */
+ ret = hx509_ca_tbs_set_template(context, tbs,
+ HX509_CA_TEMPLATE_SUBJECT |
+ HX509_CA_TEMPLATE_KU |
+ HX509_CA_TEMPLATE_EKU,
+ template);
+ hx509_cert_free(template);
+ if (ret)
+ return ret;
+ }
+
+ if (subj_name) {
+ hx509_name dn = NULL;
+
+ ret = hx509_parse_name(context, subj_name, &dn);
+ if (ret == 0)
+ ret = hx509_ca_tbs_set_subject(context, tbs, dn);
+ hx509_name_free(&dn);
+ if (ret)
+ return ret;
+ }
+
+ if (cert_template == NULL && subj_name == NULL) {
+ hx509_name dn = NULL;
+
+ ret = hx509_empty_name(context, &dn);
+ if (ret == 0)
+ ret = hx509_ca_tbs_set_subject(context, tbs, dn);
+ hx509_name_free(&dn);
+ if (ret)
+ return ret;
+ }
+
+ if (ekus) {
+ size_t i;
+
+ for (i = 0; ret == 0 && ekus[i]; i++) {
+ heim_oid oid = { 0, 0 };
+
+ if ((ret = der_find_or_parse_heim_oid(ekus[i], ".", &oid)) == 0)
+ ret = hx509_ca_tbs_add_eku(context, tbs, &oid);
+ der_free_oid(&oid);
+ }
+ heim_config_free_strings(ekus);
+ }
+
+ /*
+ * XXX A KeyUsage template would be nice, but it needs some smarts to
+ * remove, e.g., encipherOnly, decipherOnly, keyEncipherment, if the SPKI
+ * algorithm does not support encryption. The same logic should be added
+ * to hx509_ca_tbs_set_template()'s HX509_CA_TEMPLATE_KU functionality.
+ */
+ return ret;
+}
+
+/*
+ * Find and set a certificate template, set "variables" in `env', and add add
+ * default SANs/EKUs as appropriate.
+ *
+ * TODO:
+ * - lookup a template for the client principal in its HDB entry
+ * - lookup subjectName, SANs for a principal in its HDB entry
+ * - lookup a host-based client principal's HDB entry and add its canonical
+ * name / aliases as dNSName SANs
+ * (this would have to be if requested by the client, perhaps)
+ */
+static heim_error_code
+set_tbs(hx509_context context,
+ heim_log_facility *logf,
+ const heim_config_binding *cf,
+ hx509_request req,
+ KRB5PrincipalName *cprinc,
+ hx509_env *env,
+ hx509_ca_tbs tbs)
+{
+ KRB5PrincipalName cprinc_no_realm = *cprinc;
+ heim_error_code ret;
+ unsigned int ncomp = princ_num_comp(cprinc);
+ const char *realm = princ_realm(cprinc);
+ const char *comp0 = princ_get_comp_string(cprinc, 0);
+ const char *comp1 = princ_get_comp_string(cprinc, 1);
+ const char *comp2 = princ_get_comp_string(cprinc, 2);
+ struct rk_strpool *strpool;
+ char *princ_no_realm = NULL;
+ char *princ = NULL;
+
+ strpool = _hx509_unparse_kerberos_name(NULL, cprinc);
+ if (strpool)
+ princ = rk_strpoolcollect(strpool);
+ cprinc_no_realm.realm = NULL;
+ strpool = _hx509_unparse_kerberos_name(NULL, &cprinc_no_realm);
+ if (strpool)
+ princ_no_realm = rk_strpoolcollect(strpool);
+ if (princ == NULL || princ_no_realm == NULL) {
+ free(princ);
+ return hx509_enomem(context);
+ }
+ strpool = NULL;
+ ret = hx509_env_add(context, env, "principal-name-without-realm",
+ princ_no_realm);
+ if (ret == 0)
+ ret = hx509_env_add(context, env, "principal-name", princ);
+ if (ret == 0)
+ ret = hx509_env_add(context, env, "principal-name-realm",
+ realm);
+
+ /* Populate requested certificate extensions from CSR/CSRPlus if allowed */
+ if (ret == 0)
+ ret = hx509_ca_tbs_set_from_csr(context, tbs, req);
+ if (ret == 0)
+ ret = set_template(context, logf, cf, tbs);
+
+ /*
+ * Optionally add PKINIT SAN.
+ *
+ * Adding an id-pkinit-san means the client can use the certificate to
+ * initiate PKINIT. That might seem odd, but it enables a sort of PKIX
+ * credential delegation by allowing forwarded Kerberos tickets to be
+ * used to acquire PKIX credentials. Thus this can work:
+ *
+ * PKIX (w/ HW token) -> Kerberos ->
+ * PKIX (w/ softtoken) -> Kerberos ->
+ * PKIX (w/ softtoken) -> Kerberos ->
+ * ...
+ *
+ * Note that we may not have added the PKINIT EKU -- that depends on the
+ * template, and host-based service templates might well not include it.
+ */
+ if (ret == 0 && !has_sans(req) &&
+ heim_config_get_bool_default(context->hcontext, cf, FALSE,
+ "include_pkinit_san", NULL)) {
+ ret = hx509_ca_tbs_add_san_pkinit(context, tbs, princ);
+ }
+
+ if (ret)
+ goto out;
+
+ if (ncomp == 1) {
+ const char *email_domain;
+
+ ret = hx509_env_add(context, env, "principal-component0",
+ princ_no_realm);
+
+ /*
+ * If configured, include an rfc822Name that's just the client's
+ * principal name sans realm @ configured email domain.
+ */
+ if (ret == 0 && !has_sans(req) &&
+ (email_domain = heim_config_get_string(context->hcontext, cf,
+ "email_domain", NULL))) {
+ char *email;
+
+ if (asprintf(&email, "%s@%s", princ_no_realm, email_domain) == -1 ||
+ email == NULL)
+ goto enomem;
+ ret = hx509_ca_tbs_add_san_rfc822name(context, tbs, email);
+ free(email);
+ }
+ } else if (ncomp == 2 || ncomp == 3) {
+ /*
+ * 2- and 3-component principal name.
+ *
+ * We do not have a reliable name-type indicator. If the second
+ * component has a '.' in it then we'll assume that the name is a
+ * host-based (2-component) or domain-based (3-component) service
+ * principal name. Else we'll assume it's a two-component admin-style
+ * username.
+ */
+
+ ret = hx509_env_add(context, env, "principal-component0", comp0);
+ if (ret == 0)
+ ret = hx509_env_add(context, env, "principal-component1", comp1);
+ if (ret == 0 && ncomp == 3)
+ ret = hx509_env_add(context, env, "principal-component2", comp2);
+ if (ret == 0 && strchr(comp1, '.')) {
+ /* Looks like host-based or domain-based service */
+ ret = hx509_env_add(context, env, "principal-service-name", comp0);
+ if (ret == 0)
+ ret = hx509_env_add(context, env, "principal-host-name",
+ comp1);
+ if (ret == 0 && ncomp == 3)
+ ret = hx509_env_add(context, env, "principal-domain-name",
+ comp2);
+ if (ret == 0 && !has_sans(req) &&
+ heim_config_get_bool_default(context->hcontext, cf, FALSE,
+ "include_dnsname_san", NULL)) {
+ ret = hx509_ca_tbs_add_san_hostname(context, tbs, comp1);
+ }
+ }
+ } else {
+ heim_log_msg(context->hcontext, logf, 5, NULL,
+ "kx509/bx509 client %s has too many components!", princ);
+ hx509_set_error_string(context, 0, ret = EACCES,
+ "kx509/bx509 client %s has too many "
+ "components!", princ);
+ }
+
+out:
+ if (ret == ENOMEM)
+ goto enomem;
+ free(princ_no_realm);
+ free(princ);
+ return ret;
+
+enomem:
+ heim_log_msg(context->hcontext, logf, 0, NULL,
+ "Could not set up TBSCertificate: Out of memory");
+ ret = hx509_enomem(context);
+ goto out;
+}
+
+/*
+ * Set the notBefore/notAfter for the certificate to be issued.
+ *
+ * Here `starttime' is the supplicant's credentials' notBefore equivalent,
+ * while `endtime' is the supplicant's credentials' notAfter equivalent.
+ *
+ * `req_life' is the lifetime requested by the supplicant.
+ *
+ * `endtime' must be larger than the current time.
+ *
+ * `starttime' can be zero or negative, in which case the notBefore will be the
+ * current time minus five minutes.
+ *
+ * `endtime', `req_life' and configuration parameters will be used to compute
+ * the actual notAfter.
+ */
+static heim_error_code
+tbs_set_times(hx509_context context,
+ const heim_config_binding *cf,
+ heim_log_facility *logf,
+ time_t starttime,
+ time_t endtime,
+ time_t req_life,
+ hx509_ca_tbs tbs)
+{
+ time_t now = time(NULL);
+ time_t force = heim_config_get_time_default(context->hcontext,
+ cf, 5 * 24 * 3600,
+ "force_cert_lifetime", NULL);
+ time_t clamp = heim_config_get_time_default(context->hcontext, cf, 0,
+ "max_cert_lifetime", NULL);
+ int allow_more = heim_config_get_bool_default(context->hcontext, cf, FALSE,
+ "allow_extra_lifetime",
+ NULL);
+ starttime = starttime > 0 ? starttime : now - 5 * 60;
+
+ if (endtime < now) {
+ heim_log_msg(context->hcontext, logf, 3, NULL,
+ "Endtime is in the past");
+ hx509_set_error_string(context, 0, ERANGE, "Endtime is in the past");
+ return ERANGE;
+ }
+
+ /* Apply requested lifetime if shorter or if allowed more */
+ if (req_life > 0 && req_life <= endtime - now)
+ endtime = now + req_life;
+ else if (req_life > 0 && allow_more)
+ endtime = now + req_life;
+
+ /* Apply floor */
+ if (force > 0 && force > endtime - now)
+ endtime = now + force;
+
+ /* Apply ceiling */
+ if (clamp > 0 && clamp < endtime - now)
+ endtime = now + clamp;
+
+ hx509_ca_tbs_set_notAfter(context, tbs, endtime);
+ hx509_ca_tbs_set_notBefore(context, tbs, starttime);
+ return 0;
+}
+
+/*
+ * Build a certifate for `principal' and its CSR.
+ *
+ * XXX Make `cprinc' a GeneralName! That's why this is private for now.
+ */
+heim_error_code
+_hx509_ca_issue_certificate(hx509_context context,
+ const heim_config_binding *cf,
+ heim_log_facility *logf,
+ hx509_request req,
+ KRB5PrincipalName *cprinc,
+ time_t starttime,
+ time_t endtime,
+ time_t req_life,
+ int send_chain,
+ hx509_certs *out)
+{
+ heim_error_code ret;
+ const char *ca;
+ hx509_ca_tbs tbs = NULL;
+ hx509_certs chain = NULL;
+ hx509_cert signer = NULL;
+ hx509_cert cert = NULL;
+ hx509_env env = NULL;
+ KeyUsage ku;
+
+ *out = NULL;
+ /* Force KU */
+ ku = int2KeyUsage(0);
+ ku.digitalSignature = 1;
+ hx509_request_authorize_ku(req, ku);
+
+ ret = get_cf(context, cf, logf, req, cprinc, &cf);
+ if (ret)
+ return ret;
+
+ if ((ca = heim_config_get_string(context->hcontext, cf,
+ "ca", NULL)) == NULL) {
+ heim_log_msg(context->hcontext, logf, 3, NULL,
+ "No kx509 CA issuer credential specified");
+ hx509_set_error_string(context, 0, ret = EACCES,
+ "No kx509 CA issuer credential specified");
+ return ret;
+ }
+
+ ret = hx509_ca_tbs_init(context, &tbs);
+ if (ret) {
+ heim_log_msg(context->hcontext, logf, 0, NULL,
+ "Failed to create certificate: Out of memory");
+ return ret;
+ }
+
+ /* Lookup a template and set things in `env' and `tbs' as appropriate */
+ if (ret == 0)
+ ret = set_tbs(context, logf, cf, req, cprinc, &env, tbs);
+
+ /* Populate generic template "env" variables */
+
+ /*
+ * The `tbs' and `env' are now complete as to naming and EKUs.
+ *
+ * We check that the `tbs' is not name-less, after which all remaining
+ * failures here will not be policy failures. So we also log the intent to
+ * issue a certificate now.
+ */
+ if (ret == 0 && hx509_name_is_null_p(hx509_ca_tbs_get_name(tbs)) &&
+ !has_sans(req)) {
+ heim_log_msg(context->hcontext, logf, 3, NULL,
+ "Not issuing certificate because it would have no names");
+ hx509_set_error_string(context, 0, ret = EACCES,
+ "Not issuing certificate because it "
+ "would have no names");
+ }
+ if (ret)
+ goto out;
+
+ /*
+ * Still to be done below:
+ *
+ * - set certificate spki
+ * - set certificate validity
+ * - expand variables in certificate subject name template
+ * - sign certificate
+ * - encode certificate and chain
+ */
+
+ /* Load the issuer certificate and private key */
+ {
+ hx509_certs certs;
+ hx509_query *q;
+
+ ret = hx509_certs_init(context, ca, 0, NULL, &certs);
+ if (ret) {
+ heim_log_msg(context->hcontext, logf, 1, NULL,
+ "Failed to load CA certificate and private key %s",
+ ca);
+ hx509_set_error_string(context, 0, ret, "Failed to load "
+ "CA certificate and private key %s", ca);
+ goto out;
+ }
+ ret = hx509_query_alloc(context, &q);
+ if (ret) {
+ hx509_certs_free(&certs);
+ goto out;
+ }
+
+ hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
+ hx509_query_match_option(q, HX509_QUERY_OPTION_KU_KEYCERTSIGN);
+
+ ret = hx509_certs_find(context, certs, q, &signer);
+ hx509_query_free(context, q);
+ hx509_certs_free(&certs);
+ if (ret) {
+ heim_log_msg(context->hcontext, logf, 1, NULL,
+ "Failed to find a CA certificate in %s", ca);
+ hx509_set_error_string(context, 0, ret,
+ "Failed to find a CA certificate in %s",
+ ca);
+ goto out;
+ }
+ }
+
+ /* Populate the subject public key in the TBS context */
+ {
+ SubjectPublicKeyInfo spki;
+
+ ret = hx509_request_get_SubjectPublicKeyInfo(context,
+ req, &spki);
+ if (ret == 0)
+ ret = hx509_ca_tbs_set_spki(context, tbs, &spki);
+ free_SubjectPublicKeyInfo(&spki);
+ if (ret)
+ goto out;
+ }
+
+ /* Work out cert expiration */
+ if (ret == 0)
+ ret = tbs_set_times(context, cf, logf, starttime, endtime, req_life,
+ tbs);
+
+ /* Expand the subjectName template in the TBS using the env */
+ if (ret == 0)
+ ret = hx509_ca_tbs_subject_expand(context, tbs, env);
+ hx509_env_free(&env);
+
+ /* All done with the TBS, sign/issue the certificate */
+ if (ret == 0)
+ ret = hx509_ca_sign(context, tbs, signer, &cert);
+
+ /*
+ * Gather the certificate and chain into a MEMORY store, being careful not
+ * to include private keys in the chain.
+ *
+ * We could have specified a separate configuration parameter for an hx509
+ * store meant to have only the chain and no private keys, but expecting
+ * the full chain in the issuer credential store and copying only the certs
+ * (but not the private keys) is safer and easier to configure.
+ */
+ if (ret == 0)
+ ret = hx509_certs_init(context, "MEMORY:certs",
+ HX509_CERTS_NO_PRIVATE_KEYS, NULL, out);
+ if (ret == 0)
+ ret = hx509_certs_add(context, *out, cert);
+ if (ret == 0 && send_chain) {
+ ret = hx509_certs_init(context, ca,
+ HX509_CERTS_NO_PRIVATE_KEYS, NULL, &chain);
+ if (ret == 0)
+ ret = hx509_certs_merge(context, *out, chain);
+ }
+
+out:
+ hx509_certs_free(&chain);
+ if (env)
+ hx509_env_free(&env);
+ if (tbs)
+ hx509_ca_tbs_free(&tbs);
+ if (cert)
+ hx509_cert_free(cert);
+ if (signer)
+ hx509_cert_free(signer);
+ if (ret)
+ hx509_certs_free(out);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/hx509/cert.c b/third_party/heimdal/lib/hx509/cert.c
new file mode 100644
index 0000000..33805b8
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/cert.c
@@ -0,0 +1,3892 @@
+/*
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+#include "crypto-headers.h"
+#include <rtbl.h>
+
+/**
+ * @page page_cert The basic certificate
+ *
+ * The basic hx509 cerificate object in hx509 is hx509_cert. The
+ * hx509_cert object is representing one X509/PKIX certificate and
+ * associated attributes; like private key, friendly name, etc.
+ *
+ * A hx509_cert object is usully found via the keyset interfaces (@ref
+ * page_keyset), but its also possible to create a certificate
+ * directly from a parsed object with hx509_cert_init() and
+ * hx509_cert_init_data().
+ *
+ * See the library functions here: @ref hx509_cert
+ */
+
+struct hx509_verify_ctx_data {
+ hx509_certs trust_anchors;
+ int flags;
+#define HX509_VERIFY_CTX_F_TIME_SET 1
+#define HX509_VERIFY_CTX_F_ALLOW_PROXY_CERTIFICATE 2
+#define HX509_VERIFY_CTX_F_REQUIRE_RFC3280 4
+#define HX509_VERIFY_CTX_F_CHECK_TRUST_ANCHORS 8
+#define HX509_VERIFY_CTX_F_NO_DEFAULT_ANCHORS 16
+#define HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK 32
+ time_t time_now;
+ unsigned int max_depth;
+#define HX509_VERIFY_MAX_DEPTH 30
+ hx509_revoke_ctx revoke_ctx;
+};
+
+#define REQUIRE_RFC3280(ctx) ((ctx)->flags & HX509_VERIFY_CTX_F_REQUIRE_RFC3280)
+#define CHECK_TA(ctx) ((ctx)->flags & HX509_VERIFY_CTX_F_CHECK_TRUST_ANCHORS)
+#define ALLOW_DEF_TA(ctx) (((ctx)->flags & HX509_VERIFY_CTX_F_NO_DEFAULT_ANCHORS) == 0)
+
+struct _hx509_cert_attrs {
+ size_t len;
+ hx509_cert_attribute *val;
+};
+
+struct hx509_cert_data {
+ unsigned int ref;
+ char *friendlyname;
+ Certificate *data;
+ hx509_private_key private_key;
+ struct _hx509_cert_attrs attrs;
+ hx509_name basename;
+ _hx509_cert_release_func release;
+ void *ctx;
+};
+
+typedef struct hx509_name_constraints {
+ NameConstraints *val;
+ size_t len;
+} hx509_name_constraints;
+
+#define GeneralSubtrees_SET(g,var) \
+ (g)->len = (var)->len, (g)->val = (var)->val;
+
+static void
+init_context_once(void *ignored)
+{
+
+ ENGINE_add_conf_module();
+ OpenSSL_add_all_algorithms();
+}
+
+/**
+ * Return a cookie identifying this instance of a library.
+ *
+ * Inputs:
+ *
+ * @context A krb5_context
+ * @module Our library name or a library we depend on
+ *
+ * Outputs: The instance cookie
+ *
+ * @ingroup krb5_support
+ */
+
+HX509_LIB_FUNCTION uintptr_t HX509_LIB_CALL
+hx509_get_instance(const char *libname)
+{
+ static const char *instance = "libhx509";
+
+ if (strcmp(libname, "hx509") == 0)
+ return (uintptr_t)instance;
+
+ return 0;
+}
+
+#ifndef PATH_SEP
+# define PATH_SEP ":"
+#endif
+static const char *hx509_config_file =
+"~/.hx509/config" PATH_SEP
+SYSCONFDIR "/hx509.conf" PATH_SEP
+#ifdef _WIN32
+"%{COMMON_APPDATA}/Heimdal/hx509.conf" PATH_SEP
+"%{WINDOWS}/hx509.ini"
+#else /* _WIN32 */
+"/etc/hx509.conf"
+#endif /* _WIN32 */
+;
+
+/**
+ * Creates a hx509 context that most functions in the library
+ * uses. The context is only allowed to be used by one thread at each
+ * moment. Free the context with hx509_context_free().
+ *
+ * @param context Returns a pointer to new hx509 context.
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_context_init(hx509_context *contextp)
+{
+ static heim_base_once_t init_context = HEIM_BASE_ONCE_INIT;
+ heim_error_code ret;
+ hx509_context context;
+ const char *anchors;
+ char **files = NULL;
+
+ *contextp = NULL;
+ context = calloc(1, sizeof(*context));
+ if (context == NULL)
+ return ENOMEM;
+
+ heim_base_once_f(&init_context, NULL, init_context_once);
+
+ if ((context->hcontext = heim_context_init()) == NULL) {
+ free(context);
+ return ENOMEM;
+ }
+
+ if ((ret = heim_get_default_config_files(hx509_config_file,
+ "HX509_CONFIG",
+ &files))) {
+ heim_context_free(&context->hcontext);
+ free(context);
+ return ret;
+ }
+
+ /* If there's no hx509 config, we continue, as we never needed it before */
+ if (files)
+ (void) heim_set_config_files(context->hcontext, files, &context->cf);
+ heim_free_config_files(files);
+
+ _hx509_ks_null_register(context);
+ _hx509_ks_mem_register(context);
+ _hx509_ks_file_register(context);
+ _hx509_ks_pkcs12_register(context);
+ _hx509_ks_pkcs11_register(context);
+ _hx509_ks_dir_register(context);
+ _hx509_ks_keychain_register(context);
+
+ context->ocsp_time_diff =
+ heim_config_get_time_default(context->hcontext, context->cf,
+ HX509_DEFAULT_OCSP_TIME_DIFF,
+ "libdefaults", "ocsp_time_dif", NULL);
+
+ initialize_hx_error_table_r(&context->et_list);
+ initialize_asn1_error_table_r(&context->et_list);
+
+#ifdef HX509_DEFAULT_ANCHORS
+ anchors = heim_config_get_string_default(context->hcontext, context->cf,
+ HX509_DEFAULT_ANCHORS,
+ "libdefaults", "anchors", NULL);
+#else
+ anchors = heim_config_get_string(context->hcontext, context->cf,
+ "libdefaults", "anchors", NULL);
+#endif
+ if (anchors)
+ (void)hx509_certs_init(context, anchors, 0, NULL,
+ &context->default_trust_anchors);
+
+ *contextp = context;
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_set_log_dest(hx509_context context, heim_log_facility *fac)
+{
+ return heim_set_log_dest(context->hcontext, fac);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_set_debug_dest(hx509_context context, heim_log_facility *fac)
+{
+ return heim_set_debug_dest(context->hcontext, fac);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_set_warn_dest(hx509_context context, heim_log_facility *fac)
+{
+ return heim_set_warn_dest(context->hcontext, fac);
+}
+
+/**
+ * Selects if the hx509_revoke_verify() function is going to require
+ * the existans of a revokation method (OCSP, CRL) or not. Note that
+ * hx509_verify_path(), hx509_cms_verify_signed(), and other function
+ * call hx509_revoke_verify().
+ *
+ * @param context hx509 context to change the flag for.
+ * @param flag zero, revokation method required, non zero missing
+ * revokation method ok
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_context_set_missing_revoke(hx509_context context, int flag)
+{
+ if (flag)
+ context->flags |= HX509_CTX_VERIFY_MISSING_OK;
+ else
+ context->flags &= ~HX509_CTX_VERIFY_MISSING_OK;
+}
+
+/**
+ * Free the context allocated by hx509_context_init().
+ *
+ * @param context context to be freed.
+ *
+ * @ingroup hx509
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_context_free(hx509_context *context)
+{
+ if (!*context)
+ return;
+
+ hx509_clear_error_string(*context);
+ if ((*context)->ks_ops) {
+ free((*context)->ks_ops);
+ (*context)->ks_ops = NULL;
+ }
+ (*context)->ks_num_ops = 0;
+ free_error_table ((*context)->et_list);
+ if ((*context)->querystat)
+ free((*context)->querystat);
+ hx509_certs_free(&(*context)->default_trust_anchors);
+ heim_config_file_free((*context)->hcontext, (*context)->cf);
+ heim_context_free(&(*context)->hcontext);
+ memset(*context, 0, sizeof(**context));
+ free(*context);
+ *context = NULL;
+}
+
+/*
+ *
+ */
+
+HX509_LIB_FUNCTION Certificate * HX509_LIB_CALL
+_hx509_get_cert(hx509_cert cert)
+{
+ return cert->data;
+}
+
+/*
+ *
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_cert_get_version(const Certificate *t)
+{
+ return t->tbsCertificate.version ? *t->tbsCertificate.version + 1 : 1;
+}
+
+static hx509_cert
+cert_init(hx509_context context, heim_error_t *error)
+{
+ hx509_cert cert;
+
+ cert = malloc(sizeof(*cert));
+ if (cert == NULL) {
+ if (error)
+ *error = heim_error_create_enomem();
+ return NULL;
+ }
+ cert->ref = 1;
+ cert->friendlyname = NULL;
+ cert->attrs.len = 0;
+ cert->attrs.val = NULL;
+ cert->private_key = NULL;
+ cert->basename = NULL;
+ cert->release = NULL;
+ cert->ctx = NULL;
+ cert->data= NULL;
+ return cert;
+}
+
+/**
+ * Allocate and init an hx509 certificate object from the decoded
+ * certificate `c´.
+ *
+ * @param context A hx509 context.
+ * @param c
+ * @param error
+ *
+ * @return Returns an hx509 certificate
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION hx509_cert HX509_LIB_CALL
+hx509_cert_init(hx509_context context, const Certificate *c, heim_error_t *error)
+{
+ hx509_cert cert;
+ int ret;
+
+ if ((cert = cert_init(context, error)) == NULL)
+ return NULL;
+
+ cert->data = calloc(1, sizeof(*(cert->data)));
+ if (cert->data == NULL) {
+ free(cert);
+ if (error)
+ *error = heim_error_create_enomem();
+ return NULL;
+ }
+ ret = copy_Certificate(c, cert->data);
+ if (ret) {
+ free(cert->data);
+ free(cert);
+ cert = NULL;
+ }
+ return cert;
+}
+
+/**
+ * Copy a certificate object, but drop any private key assignment.
+ *
+ * @param context A hx509 context.
+ * @param src Certificate object
+ * @param error
+ *
+ * @return Returns an hx509 certificate
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION hx509_cert HX509_LIB_CALL
+hx509_cert_copy_no_private_key(hx509_context context,
+ hx509_cert src,
+ heim_error_t *error)
+{
+ return hx509_cert_init(context, src->data, error);
+}
+
+/**
+ * Allocate and init an hx509 certificate object containing only a private key
+ * (but no Certificate).
+ *
+ * @param context A hx509 context.
+ * @param key
+ * @param error
+ *
+ * @return Returns an hx509 certificate
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION hx509_cert HX509_LIB_CALL
+hx509_cert_init_private_key(hx509_context context,
+ hx509_private_key key,
+ heim_error_t *error)
+{
+ hx509_cert cert;
+
+ if ((cert = cert_init(context, error)))
+ (void) _hx509_cert_assign_key(cert, key);
+ return cert;
+}
+
+/**
+ * Just like hx509_cert_init(), but instead of a decode certificate
+ * takes an pointer and length to a memory region that contains a
+ * DER/BER encoded certificate.
+ *
+ * If the memory region doesn't contain just the certificate and
+ * nothing more the function will fail with
+ * HX509_EXTRA_DATA_AFTER_STRUCTURE.
+ *
+ * @param context A hx509 context.
+ * @param ptr pointer to memory region containing encoded certificate.
+ * @param len length of memory region.
+ * @param error possibly returns an error
+ *
+ * @return An hx509 certificate
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION hx509_cert HX509_LIB_CALL
+hx509_cert_init_data(hx509_context context,
+ const void *ptr,
+ size_t len,
+ heim_error_t *error)
+{
+ hx509_cert cert;
+ Certificate t;
+ size_t size;
+ int ret;
+
+ ret = decode_Certificate(ptr, len, &t, &size);
+ if (ret) {
+ if (error)
+ *error = heim_error_create(ret, "Failed to decode certificate");
+ errno = ret;
+ return NULL;
+ }
+ if (size != len) {
+ free_Certificate(&t);
+ if (error)
+ *error = heim_error_create(HX509_EXTRA_DATA_AFTER_STRUCTURE,
+ "Extra data after certificate");
+ errno = HX509_EXTRA_DATA_AFTER_STRUCTURE;
+ return NULL;
+ }
+
+ cert = hx509_cert_init(context, &t, error);
+ free_Certificate(&t);
+ return cert;
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_cert_set_release(hx509_cert cert,
+ _hx509_cert_release_func release,
+ void *ctx)
+{
+ cert->release = release;
+ cert->ctx = ctx;
+}
+
+
+/* Doesn't make a copy of `private_key'. */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_cert_assign_key(hx509_cert cert, hx509_private_key private_key)
+{
+ if (cert->private_key)
+ hx509_private_key_free(&cert->private_key);
+ cert->private_key = _hx509_private_key_ref(private_key);
+ return 0;
+}
+
+/**
+ * Free reference to the hx509 certificate object, if the refcounter
+ * reaches 0, the object if freed. Its allowed to pass in NULL.
+ *
+ * @param cert the cert to free.
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_cert_free(hx509_cert cert)
+{
+ size_t i;
+
+ if (cert == NULL)
+ return;
+
+ if (cert->ref <= 0)
+ _hx509_abort("cert refcount <= 0 on free");
+ if (--cert->ref > 0)
+ return;
+
+ if (cert->release)
+ (cert->release)(cert, cert->ctx);
+
+ if (cert->private_key)
+ hx509_private_key_free(&cert->private_key);
+
+ if (cert->data)
+ free_Certificate(cert->data);
+ free(cert->data);
+
+ for (i = 0; i < cert->attrs.len; i++) {
+ der_free_octet_string(&cert->attrs.val[i]->data);
+ der_free_oid(&cert->attrs.val[i]->oid);
+ free(cert->attrs.val[i]);
+ }
+ free(cert->attrs.val);
+ free(cert->friendlyname);
+ if (cert->basename)
+ hx509_name_free(&cert->basename);
+ memset(cert, 0, sizeof(*cert));
+ free(cert);
+}
+
+/**
+ * Add a reference to a hx509 certificate object.
+ *
+ * @param cert a pointer to an hx509 certificate object.
+ *
+ * @return the same object as is passed in.
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION hx509_cert HX509_LIB_CALL
+hx509_cert_ref(hx509_cert cert)
+{
+ if (cert == NULL)
+ return NULL;
+ if (cert->ref <= 0)
+ _hx509_abort("cert refcount <= 0");
+ cert->ref++;
+ if (cert->ref == 0)
+ _hx509_abort("cert refcount == 0");
+ return cert;
+}
+
+/**
+ * Allocate an verification context that is used fo control the
+ * verification process.
+ *
+ * @param context A hx509 context.
+ * @param ctx returns a pointer to a hx509_verify_ctx object.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_verify_init_ctx(hx509_context context, hx509_verify_ctx *ctx)
+{
+ hx509_verify_ctx c;
+
+ c = calloc(1, sizeof(*c));
+ if (c == NULL)
+ return ENOMEM;
+
+ c->max_depth = HX509_VERIFY_MAX_DEPTH;
+
+ *ctx = c;
+
+ return 0;
+}
+
+/**
+ * Free an hx509 verification context.
+ *
+ * @param ctx the context to be freed.
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_verify_destroy_ctx(hx509_verify_ctx ctx)
+{
+ if (ctx) {
+ hx509_certs_free(&ctx->trust_anchors);
+ hx509_revoke_free(&ctx->revoke_ctx);
+ memset(ctx, 0, sizeof(*ctx));
+ }
+ free(ctx);
+}
+
+/**
+ * Set the trust anchors in the verification context, makes an
+ * reference to the keyset, so the consumer can free the keyset
+ * independent of the destruction of the verification context (ctx).
+ * If there already is a keyset attached, it's released.
+ *
+ * @param ctx a verification context
+ * @param set a keyset containing the trust anchors.
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_verify_attach_anchors(hx509_verify_ctx ctx, hx509_certs set)
+{
+ if (ctx->trust_anchors)
+ hx509_certs_free(&ctx->trust_anchors);
+ ctx->trust_anchors = hx509_certs_ref(set);
+}
+
+/**
+ * Attach an revocation context to the verfication context, , makes an
+ * reference to the revoke context, so the consumer can free the
+ * revoke context independent of the destruction of the verification
+ * context. If there is no revoke context, the verification process is
+ * NOT going to check any verification status.
+ *
+ * @param ctx a verification context.
+ * @param revoke_ctx a revoke context.
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_verify_attach_revoke(hx509_verify_ctx ctx, hx509_revoke_ctx revoke_ctx)
+{
+ if (ctx->revoke_ctx)
+ hx509_revoke_free(&ctx->revoke_ctx);
+ ctx->revoke_ctx = _hx509_revoke_ref(revoke_ctx);
+}
+
+/**
+ * Set the clock time the the verification process is going to
+ * use. Used to check certificate in the past and future time. If not
+ * set the current time will be used.
+ *
+ * @param ctx a verification context.
+ * @param t the time the verifiation is using.
+ *
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_verify_set_time(hx509_verify_ctx ctx, time_t t)
+{
+ ctx->flags |= HX509_VERIFY_CTX_F_TIME_SET;
+ ctx->time_now = t;
+}
+
+HX509_LIB_FUNCTION time_t HX509_LIB_CALL
+_hx509_verify_get_time(hx509_verify_ctx ctx)
+{
+ return ctx->time_now;
+}
+
+/**
+ * Set the maximum depth of the certificate chain that the path
+ * builder is going to try.
+ *
+ * @param ctx a verification context
+ * @param max_depth maxium depth of the certificate chain, include
+ * trust anchor.
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_verify_set_max_depth(hx509_verify_ctx ctx, unsigned int max_depth)
+{
+ ctx->max_depth = max_depth;
+}
+
+/**
+ * Allow or deny the use of proxy certificates
+ *
+ * @param ctx a verification context
+ * @param boolean if non zero, allow proxy certificates.
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_verify_set_proxy_certificate(hx509_verify_ctx ctx, int boolean)
+{
+ if (boolean)
+ ctx->flags |= HX509_VERIFY_CTX_F_ALLOW_PROXY_CERTIFICATE;
+ else
+ ctx->flags &= ~HX509_VERIFY_CTX_F_ALLOW_PROXY_CERTIFICATE;
+}
+
+/**
+ * Select strict RFC3280 verification of certificiates. This means
+ * checking key usage on CA certificates, this will make version 1
+ * certificiates unuseable.
+ *
+ * @param ctx a verification context
+ * @param boolean if non zero, use strict verification.
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_verify_set_strict_rfc3280_verification(hx509_verify_ctx ctx, int boolean)
+{
+ if (boolean)
+ ctx->flags |= HX509_VERIFY_CTX_F_REQUIRE_RFC3280;
+ else
+ ctx->flags &= ~HX509_VERIFY_CTX_F_REQUIRE_RFC3280;
+}
+
+/**
+ * Allow using the operating system builtin trust anchors if no other
+ * trust anchors are configured.
+ *
+ * @param ctx a verification context
+ * @param boolean if non zero, useing the operating systems builtin
+ * trust anchors.
+ *
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_verify_ctx_f_allow_default_trustanchors(hx509_verify_ctx ctx, int boolean)
+{
+ if (boolean)
+ ctx->flags &= ~HX509_VERIFY_CTX_F_NO_DEFAULT_ANCHORS;
+ else
+ ctx->flags |= HX509_VERIFY_CTX_F_NO_DEFAULT_ANCHORS;
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_verify_ctx_f_allow_best_before_signature_algs(hx509_context ctx,
+ int boolean)
+{
+ if (boolean)
+ ctx->flags &= ~HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK;
+ else
+ ctx->flags |= HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK;
+}
+
+static const Extension *
+find_extension(const Certificate *cert, const heim_oid *oid, size_t *idx)
+{
+ const TBSCertificate *c = &cert->tbsCertificate;
+
+ if (c->version == NULL || *c->version < 2 || c->extensions == NULL)
+ return NULL;
+
+ for (;*idx < c->extensions->len; (*idx)++) {
+ if (der_heim_oid_cmp(&c->extensions->val[*idx].extnID, oid) == 0)
+ return &c->extensions->val[(*idx)++];
+ }
+ return NULL;
+}
+
+static int
+find_extension_auth_key_id(const Certificate *subject,
+ AuthorityKeyIdentifier *ai)
+{
+ const Extension *e;
+ size_t size;
+ size_t i = 0;
+
+ memset(ai, 0, sizeof(*ai));
+
+ e = find_extension(subject, &asn1_oid_id_x509_ce_authorityKeyIdentifier, &i);
+ if (e == NULL)
+ return HX509_EXTENSION_NOT_FOUND;
+
+ return decode_AuthorityKeyIdentifier(e->extnValue.data,
+ e->extnValue.length,
+ ai, &size);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_find_extension_subject_key_id(const Certificate *issuer,
+ SubjectKeyIdentifier *si)
+{
+ const Extension *e;
+ size_t size;
+ size_t i = 0;
+
+ memset(si, 0, sizeof(*si));
+
+ e = find_extension(issuer, &asn1_oid_id_x509_ce_subjectKeyIdentifier, &i);
+ if (e == NULL)
+ return HX509_EXTENSION_NOT_FOUND;
+
+ return decode_SubjectKeyIdentifier(e->extnValue.data,
+ e->extnValue.length,
+ si, &size);
+}
+
+static int
+find_extension_name_constraints(const Certificate *subject,
+ NameConstraints *nc)
+{
+ const Extension *e;
+ size_t size;
+ size_t i = 0;
+
+ memset(nc, 0, sizeof(*nc));
+
+ e = find_extension(subject, &asn1_oid_id_x509_ce_nameConstraints, &i);
+ if (e == NULL)
+ return HX509_EXTENSION_NOT_FOUND;
+
+ return decode_NameConstraints(e->extnValue.data,
+ e->extnValue.length,
+ nc, &size);
+}
+
+static int
+find_extension_subject_alt_name(const Certificate *cert, size_t *i,
+ GeneralNames *sa)
+{
+ const Extension *e;
+ size_t size;
+
+ memset(sa, 0, sizeof(*sa));
+
+ e = find_extension(cert, &asn1_oid_id_x509_ce_subjectAltName, i);
+ if (e == NULL)
+ return HX509_EXTENSION_NOT_FOUND;
+
+ return decode_GeneralNames(e->extnValue.data,
+ e->extnValue.length,
+ sa, &size);
+}
+
+static int
+find_extension_eku(const Certificate *cert, ExtKeyUsage *eku)
+{
+ const Extension *e;
+ size_t size;
+ size_t i = 0;
+
+ memset(eku, 0, sizeof(*eku));
+
+ e = find_extension(cert, &asn1_oid_id_x509_ce_extKeyUsage, &i);
+ if (e == NULL)
+ return HX509_EXTENSION_NOT_FOUND;
+
+ return decode_ExtKeyUsage(e->extnValue.data,
+ e->extnValue.length,
+ eku, &size);
+}
+
+static int
+add_to_list(hx509_octet_string_list *list, const heim_octet_string *entry)
+{
+ void *p;
+ int ret;
+
+ p = realloc(list->val, (list->len + 1) * sizeof(list->val[0]));
+ if (p == NULL)
+ return ENOMEM;
+ list->val = p;
+ ret = der_copy_octet_string(entry, &list->val[list->len]);
+ if (ret)
+ return ret;
+ list->len++;
+ return 0;
+}
+
+/**
+ * Free a list of octet strings returned by another hx509 library
+ * function.
+ *
+ * @param list list to be freed.
+ *
+ * @ingroup hx509_misc
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_free_octet_string_list(hx509_octet_string_list *list)
+{
+ size_t i;
+
+ if (list->val) {
+ for (i = 0; i < list->len; i++)
+ der_free_octet_string(&list->val[i]);
+ free(list->val);
+ }
+ list->val = NULL;
+ list->len = 0;
+}
+
+/**
+ * Return a list of subjectAltNames specified by oid in the
+ * certificate. On error the
+ *
+ * The returned list of octet string should be freed with
+ * hx509_free_octet_string_list().
+ *
+ * @param context A hx509 context.
+ * @param cert a hx509 certificate object.
+ * @param oid an oid to for SubjectAltName.
+ * @param list list of matching SubjectAltName.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_find_subjectAltName_otherName(hx509_context context,
+ hx509_cert cert,
+ const heim_oid *oid,
+ hx509_octet_string_list *list)
+{
+ GeneralNames sa;
+ int ret;
+ size_t i, j;
+
+ list->val = NULL;
+ list->len = 0;
+
+ i = 0;
+ while (1) {
+ ret = find_extension_subject_alt_name(_hx509_get_cert(cert), &i, &sa);
+ i++;
+ if (ret == HX509_EXTENSION_NOT_FOUND) {
+ return 0;
+ } else if (ret != 0) {
+ hx509_set_error_string(context, 0, ret, "Error searching for SAN");
+ hx509_free_octet_string_list(list);
+ return ret;
+ }
+
+ for (j = 0; j < sa.len; j++) {
+ if (sa.val[j].element == choice_GeneralName_otherName &&
+ der_heim_oid_cmp(&sa.val[j].u.otherName.type_id, oid) == 0)
+ {
+ ret = add_to_list(list, &sa.val[j].u.otherName.value);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Error adding an exra SAN to "
+ "return list");
+ hx509_free_octet_string_list(list);
+ free_GeneralNames(&sa);
+ return ret;
+ }
+ }
+ }
+ free_GeneralNames(&sa);
+ }
+}
+
+
+static int
+check_key_usage(hx509_context context, const Certificate *cert,
+ unsigned flags, int req_present)
+{
+ const Extension *e;
+ KeyUsage ku;
+ size_t size;
+ int ret;
+ size_t i = 0;
+ uint64_t ku_flags;
+
+ if (_hx509_cert_get_version(cert) < 3)
+ return 0;
+
+ e = find_extension(cert, &asn1_oid_id_x509_ce_keyUsage, &i);
+ if (e == NULL) {
+ if (req_present) {
+ hx509_set_error_string(context, 0, HX509_KU_CERT_MISSING,
+ "Required extension key "
+ "usage missing from certificate");
+ return HX509_KU_CERT_MISSING;
+ }
+ return 0;
+ }
+
+ ret = decode_KeyUsage(e->extnValue.data, e->extnValue.length, &ku, &size);
+ if (ret)
+ return ret;
+ ku_flags = KeyUsage2int(ku);
+ if ((ku_flags & flags) != flags) {
+ uint64_t missing = (~ku_flags) & flags;
+ char buf[256], *name;
+
+ int result = unparse_flags(missing, asn1_KeyUsage_units(),
+ buf, sizeof(buf));
+ _hx509_unparse_Name(&cert->tbsCertificate.subject, &name);
+ hx509_set_error_string(context, 0, HX509_KU_CERT_MISSING,
+ "Key usage %s required but missing "
+ "from certificate %s",
+ (result > 0) ? buf : "<unknown>",
+ name ? name : "<unknown>");
+ free(name);
+ return HX509_KU_CERT_MISSING;
+ }
+ return 0;
+}
+
+/*
+ * Return 0 on matching key usage 'flags' for 'cert', otherwise return
+ * an error code. If 'req_present' the existence is required of the
+ * KeyUsage extension.
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_check_key_usage(hx509_context context, hx509_cert cert,
+ unsigned flags, int req_present)
+{
+ return check_key_usage(context, _hx509_get_cert(cert), flags, req_present);
+}
+
+enum certtype { PROXY_CERT, EE_CERT, CA_CERT };
+
+static int
+check_basic_constraints(hx509_context context, const Certificate *cert,
+ enum certtype type, size_t depth)
+{
+ BasicConstraints bc;
+ const Extension *e;
+ size_t size;
+ int ret;
+ size_t i = 0;
+
+ if (_hx509_cert_get_version(cert) < 3)
+ return 0;
+
+ e = find_extension(cert, &asn1_oid_id_x509_ce_basicConstraints, &i);
+ if (e == NULL) {
+ switch(type) {
+ case PROXY_CERT:
+ case EE_CERT:
+ return 0;
+ case CA_CERT: {
+ char *name;
+ ret = _hx509_unparse_Name(&cert->tbsCertificate.subject, &name);
+ assert(ret == 0);
+ hx509_set_error_string(context, 0, HX509_EXTENSION_NOT_FOUND,
+ "basicConstraints missing from "
+ "CA certifiacte %s", name);
+ free(name);
+ return HX509_EXTENSION_NOT_FOUND;
+ }
+ }
+ }
+
+ ret = decode_BasicConstraints(e->extnValue.data,
+ e->extnValue.length, &bc,
+ &size);
+ if (ret)
+ return ret;
+ switch(type) {
+ case PROXY_CERT:
+ if (bc.cA)
+ ret = HX509_PARENT_IS_CA;
+ break;
+ case EE_CERT:
+ ret = 0;
+ break;
+ case CA_CERT:
+ if (!bc.cA)
+ ret = HX509_PARENT_NOT_CA;
+ else if (bc.pathLenConstraint)
+ if (depth - 1 > *bc.pathLenConstraint)
+ ret = HX509_CA_PATH_TOO_DEEP;
+ break;
+ }
+ free_BasicConstraints(&bc);
+ return ret;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_cert_is_parent_cmp(const Certificate *subject,
+ const Certificate *issuer,
+ int allow_self_signed)
+{
+ int diff;
+ AuthorityKeyIdentifier ai;
+ SubjectKeyIdentifier si;
+ int ret_ai, ret_si, ret;
+
+ ret = _hx509_name_cmp(&issuer->tbsCertificate.subject,
+ &subject->tbsCertificate.issuer,
+ &diff);
+ if (ret)
+ return ret;
+ if (diff)
+ return diff;
+
+ memset(&ai, 0, sizeof(ai));
+ memset(&si, 0, sizeof(si));
+
+ /*
+ * Try to find AuthorityKeyIdentifier, if it's not present in the
+ * subject certificate nor the parent.
+ */
+
+ ret_ai = find_extension_auth_key_id(subject, &ai);
+ if (ret_ai && ret_ai != HX509_EXTENSION_NOT_FOUND)
+ return 1;
+ ret_si = _hx509_find_extension_subject_key_id(issuer, &si);
+ if (ret_si && ret_si != HX509_EXTENSION_NOT_FOUND)
+ return -1;
+
+ if (ret_si && ret_ai)
+ goto out;
+ if (ret_ai)
+ goto out;
+ if (ret_si) {
+ if (allow_self_signed) {
+ diff = 0;
+ goto out;
+ } else if (ai.keyIdentifier) {
+ diff = -1;
+ goto out;
+ }
+ }
+
+ if (ai.keyIdentifier == NULL) {
+ Name name;
+
+ if (ai.authorityCertIssuer == NULL)
+ return -1;
+ if (ai.authorityCertSerialNumber == NULL)
+ return -1;
+
+ diff = der_heim_integer_cmp(ai.authorityCertSerialNumber,
+ &issuer->tbsCertificate.serialNumber);
+ if (diff)
+ return diff;
+ if (ai.authorityCertIssuer->len != 1)
+ return -1;
+ if (ai.authorityCertIssuer->val[0].element != choice_GeneralName_directoryName)
+ return -1;
+
+ name.element = (enum Name_enum)
+ ai.authorityCertIssuer->val[0].u.directoryName.element;
+ name.u.rdnSequence =
+ ai.authorityCertIssuer->val[0].u.directoryName.u.rdnSequence;
+
+ ret = _hx509_name_cmp(&issuer->tbsCertificate.subject,
+ &name,
+ &diff);
+ if (ret)
+ return ret;
+ if (diff)
+ return diff;
+ diff = 0;
+ } else
+ diff = der_heim_octet_string_cmp(ai.keyIdentifier, &si);
+ if (diff)
+ goto out;
+
+ out:
+ free_AuthorityKeyIdentifier(&ai);
+ free_SubjectKeyIdentifier(&si);
+ return diff;
+}
+
+static int
+certificate_is_anchor(hx509_context context,
+ hx509_certs trust_anchors,
+ const hx509_cert cert)
+{
+ hx509_query q;
+ hx509_cert c;
+ int ret;
+
+ if (trust_anchors == NULL)
+ return 0;
+
+ _hx509_query_clear(&q);
+
+ q.match = HX509_QUERY_MATCH_CERTIFICATE;
+ q.certificate = _hx509_get_cert(cert);
+
+ ret = hx509_certs_find(context, trust_anchors, &q, &c);
+ if (ret == 0)
+ hx509_cert_free(c);
+ return ret == 0;
+}
+
+static int
+certificate_is_self_signed(hx509_context context,
+ const Certificate *cert,
+ int *self_signed)
+{
+ int ret, diff;
+ ret = _hx509_name_cmp(&cert->tbsCertificate.subject,
+ &cert->tbsCertificate.issuer, &diff);
+ *self_signed = (diff == 0);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to check if self signed");
+ } else
+ ret = _hx509_self_signed_valid(context, &cert->signatureAlgorithm);
+
+ return ret;
+}
+
+/*
+ * The subjectName is "null" when it's empty set of relative DBs.
+ */
+
+static int
+subject_null_p(const Certificate *c)
+{
+ return c->tbsCertificate.subject.u.rdnSequence.len == 0;
+}
+
+
+static int
+find_parent(hx509_context context,
+ time_t time_now,
+ hx509_certs trust_anchors,
+ hx509_path *path,
+ hx509_certs pool,
+ hx509_cert current,
+ hx509_cert *parent)
+{
+ AuthorityKeyIdentifier ai;
+ hx509_query q;
+ int ret;
+
+ *parent = NULL;
+ memset(&ai, 0, sizeof(ai));
+
+ _hx509_query_clear(&q);
+
+ if (!subject_null_p(current->data)) {
+ q.match |= HX509_QUERY_FIND_ISSUER_CERT;
+ q.subject = _hx509_get_cert(current);
+ } else {
+ ret = find_extension_auth_key_id(current->data, &ai);
+ if (ret) {
+ hx509_set_error_string(context, 0, HX509_CERTIFICATE_MALFORMED,
+ "Subjectless certificate missing AuthKeyID");
+ return HX509_CERTIFICATE_MALFORMED;
+ }
+
+ if (ai.keyIdentifier == NULL) {
+ free_AuthorityKeyIdentifier(&ai);
+ hx509_set_error_string(context, 0, HX509_CERTIFICATE_MALFORMED,
+ "Subjectless certificate missing keyIdentifier "
+ "inside AuthKeyID");
+ return HX509_CERTIFICATE_MALFORMED;
+ }
+
+ q.subject_id = ai.keyIdentifier;
+ q.match = HX509_QUERY_MATCH_SUBJECT_KEY_ID;
+ }
+
+ q.path = path;
+ q.match |= HX509_QUERY_NO_MATCH_PATH;
+
+ if (pool) {
+ q.timenow = time_now;
+ q.match |= HX509_QUERY_MATCH_TIME;
+
+ ret = hx509_certs_find(context, pool, &q, parent);
+ if (ret == 0) {
+ free_AuthorityKeyIdentifier(&ai);
+ return 0;
+ }
+ q.match &= ~HX509_QUERY_MATCH_TIME;
+ }
+
+ if (trust_anchors) {
+ ret = hx509_certs_find(context, trust_anchors, &q, parent);
+ if (ret == 0) {
+ free_AuthorityKeyIdentifier(&ai);
+ return ret;
+ }
+ }
+ free_AuthorityKeyIdentifier(&ai);
+
+ {
+ hx509_name name;
+ char *str;
+
+ ret = hx509_cert_get_subject(current, &name);
+ if (ret) {
+ hx509_clear_error_string(context);
+ return HX509_ISSUER_NOT_FOUND;
+ }
+ ret = hx509_name_to_string(name, &str);
+ hx509_name_free(&name);
+ if (ret) {
+ hx509_clear_error_string(context);
+ return HX509_ISSUER_NOT_FOUND;
+ }
+
+ hx509_set_error_string(context, 0, HX509_ISSUER_NOT_FOUND,
+ "Failed to find issuer for "
+ "certificate with subject: '%s'", str);
+ free(str);
+ }
+ return HX509_ISSUER_NOT_FOUND;
+}
+
+/*
+ *
+ */
+
+static int
+is_proxy_cert(hx509_context context,
+ const Certificate *cert,
+ ProxyCertInfo *rinfo)
+{
+ ProxyCertInfo info;
+ const Extension *e;
+ size_t size;
+ int ret;
+ size_t i = 0;
+
+ if (rinfo)
+ memset(rinfo, 0, sizeof(*rinfo));
+
+ e = find_extension(cert, &asn1_oid_id_pkix_pe_proxyCertInfo, &i);
+ if (e == NULL) {
+ hx509_clear_error_string(context);
+ return HX509_EXTENSION_NOT_FOUND;
+ }
+
+ ret = decode_ProxyCertInfo(e->extnValue.data,
+ e->extnValue.length,
+ &info,
+ &size);
+ if (ret) {
+ hx509_clear_error_string(context);
+ return ret;
+ }
+ if (size != e->extnValue.length) {
+ free_ProxyCertInfo(&info);
+ hx509_clear_error_string(context);
+ return HX509_EXTRA_DATA_AFTER_STRUCTURE;
+ }
+ if (rinfo == NULL)
+ free_ProxyCertInfo(&info);
+ else
+ *rinfo = info;
+
+ return 0;
+}
+
+/*
+ * Path operations are like MEMORY based keyset, but with exposed
+ * internal so we can do easy searches.
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_path_append(hx509_context context, hx509_path *path, hx509_cert cert)
+{
+ hx509_cert *val;
+ val = realloc(path->val, (path->len + 1) * sizeof(path->val[0]));
+ if (val == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ path->val = val;
+ path->val[path->len] = hx509_cert_ref(cert);
+ path->len++;
+
+ return 0;
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_path_free(hx509_path *path)
+{
+ unsigned i;
+
+ for (i = 0; i < path->len; i++)
+ hx509_cert_free(path->val[i]);
+ free(path->val);
+ path->val = NULL;
+ path->len = 0;
+}
+
+/*
+ * Find path by looking up issuer for the top certificate and continue
+ * until an anchor certificate is found or max limit is found. A
+ * certificate never included twice in the path.
+ *
+ * If the trust anchors are not given, calculate optimistic path, just
+ * follow the chain upward until we no longer find a parent or we hit
+ * the max path limit. In this case, a failure will always be returned
+ * depending on what error condition is hit first.
+ *
+ * The path includes a path from the top certificate to the anchor
+ * certificate.
+ *
+ * The caller needs to free `path´ both on successful built path and
+ * failure.
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_calculate_path(hx509_context context,
+ int flags,
+ time_t time_now,
+ hx509_certs anchors,
+ unsigned int max_depth,
+ hx509_cert cert,
+ hx509_certs pool,
+ hx509_path *path)
+{
+ hx509_cert parent, current;
+ int ret;
+
+ if (max_depth == 0)
+ max_depth = HX509_VERIFY_MAX_DEPTH;
+
+ ret = _hx509_path_append(context, path, cert);
+ if (ret)
+ return ret;
+
+ current = hx509_cert_ref(cert);
+
+ while (!certificate_is_anchor(context, anchors, current)) {
+
+ ret = find_parent(context, time_now, anchors, path,
+ pool, current, &parent);
+ hx509_cert_free(current);
+ if (ret)
+ return ret;
+
+ ret = _hx509_path_append(context, path, parent);
+ if (ret)
+ return ret;
+ current = parent;
+
+ if (path->len > max_depth) {
+ hx509_cert_free(current);
+ hx509_set_error_string(context, 0, HX509_PATH_TOO_LONG,
+ "Path too long while bulding "
+ "certificate chain");
+ return HX509_PATH_TOO_LONG;
+ }
+ }
+
+ if ((flags & HX509_CALCULATE_PATH_NO_ANCHOR) &&
+ path->len > 0 &&
+ certificate_is_anchor(context, anchors, path->val[path->len - 1]))
+ {
+ hx509_cert_free(path->val[path->len - 1]);
+ path->len--;
+ }
+
+ hx509_cert_free(current);
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_AlgorithmIdentifier_cmp(const AlgorithmIdentifier *p,
+ const AlgorithmIdentifier *q)
+{
+ int diff;
+ diff = der_heim_oid_cmp(&p->algorithm, &q->algorithm);
+ if (diff)
+ return diff;
+ if (p->parameters) {
+ if (q->parameters)
+ return heim_any_cmp(p->parameters,
+ q->parameters);
+ else
+ return 1;
+ } else {
+ if (q->parameters)
+ return -1;
+ else
+ return 0;
+ }
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_Certificate_cmp(const Certificate *p, const Certificate *q)
+{
+ int diff;
+ diff = der_heim_bit_string_cmp(&p->signatureValue, &q->signatureValue);
+ if (diff)
+ return diff;
+ diff = _hx509_AlgorithmIdentifier_cmp(&p->signatureAlgorithm,
+ &q->signatureAlgorithm);
+ if (diff)
+ return diff;
+ diff = der_heim_octet_string_cmp(&p->tbsCertificate._save,
+ &q->tbsCertificate._save);
+ return diff;
+}
+
+/**
+ * Compare to hx509 certificate object, useful for sorting.
+ *
+ * @param p a hx509 certificate object.
+ * @param q a hx509 certificate object.
+ *
+ * @return 0 the objects are the same, returns > 0 is p is "larger"
+ * then q, < 0 if p is "smaller" then q.
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_cmp(hx509_cert p, hx509_cert q)
+{
+ return _hx509_Certificate_cmp(p->data, q->data);
+}
+
+/**
+ * Return the name of the issuer of the hx509 certificate.
+ *
+ * @param p a hx509 certificate object.
+ * @param name a pointer to a hx509 name, should be freed by
+ * hx509_name_free().
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_get_issuer(hx509_cert p, hx509_name *name)
+{
+ return _hx509_name_from_Name(&p->data->tbsCertificate.issuer, name);
+}
+
+/**
+ * Return the name of the subject of the hx509 certificate.
+ *
+ * @param p a hx509 certificate object.
+ * @param name a pointer to a hx509 name, should be freed by
+ * hx509_name_free(). See also hx509_cert_get_base_subject().
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_get_subject(hx509_cert p, hx509_name *name)
+{
+ return _hx509_name_from_Name(&p->data->tbsCertificate.subject, name);
+}
+
+/**
+ * Return the name of the base subject of the hx509 certificate. If
+ * the certiicate is a verified proxy certificate, the this function
+ * return the base certificate (root of the proxy chain). If the proxy
+ * certificate is not verified with the base certificate
+ * HX509_PROXY_CERTIFICATE_NOT_CANONICALIZED is returned.
+ *
+ * @param context a hx509 context.
+ * @param c a hx509 certificate object.
+ * @param name a pointer to a hx509 name, should be freed by
+ * hx509_name_free(). See also hx509_cert_get_subject().
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_get_base_subject(hx509_context context, hx509_cert c,
+ hx509_name *name)
+{
+ if (c->basename)
+ return hx509_name_copy(context, c->basename, name);
+ if (is_proxy_cert(context, c->data, NULL) == 0) {
+ int ret = HX509_PROXY_CERTIFICATE_NOT_CANONICALIZED;
+ hx509_set_error_string(context, 0, ret,
+ "Proxy certificate has not been "
+ "canonicalized yet: no base name");
+ return ret;
+ }
+ return _hx509_name_from_Name(&c->data->tbsCertificate.subject, name);
+}
+
+/**
+ * Get serial number of the certificate.
+ *
+ * @param p a hx509 certificate object.
+ * @param i serial number, should be freed ith der_free_heim_integer().
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_get_serialnumber(hx509_cert p, heim_integer *i)
+{
+ return der_copy_heim_integer(&p->data->tbsCertificate.serialNumber, i);
+}
+
+/**
+ * Get notBefore time of the certificate.
+ *
+ * @param p a hx509 certificate object.
+ *
+ * @return return not before time
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION time_t HX509_LIB_CALL
+hx509_cert_get_notBefore(hx509_cert p)
+{
+ return _hx509_Time2time_t(&p->data->tbsCertificate.validity.notBefore);
+}
+
+/**
+ * Get notAfter time of the certificate.
+ *
+ * @param p a hx509 certificate object.
+ *
+ * @return return not after time.
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION time_t HX509_LIB_CALL
+hx509_cert_get_notAfter(hx509_cert p)
+{
+ return _hx509_Time2time_t(&p->data->tbsCertificate.validity.notAfter);
+}
+
+/**
+ * Get a maximum Kerberos credential lifetime from a Heimdal certificate
+ * extension.
+ *
+ * @param context hx509 context.
+ * @param cert Certificate.
+ * @param bound If larger than zero, return no more than this.
+ *
+ * @return maximum ticket lifetime.
+ */
+HX509_LIB_FUNCTION time_t HX509_LIB_CALL
+hx509_cert_get_pkinit_max_life(hx509_context context,
+ hx509_cert cert,
+ time_t bound)
+{
+ HeimPkinitPrincMaxLifeSecs r = 0;
+ size_t sz, i;
+ time_t b, e;
+ int ret;
+
+ for (i = 0; i < cert->data->tbsCertificate.extensions->len; i++) {
+ Extension *ext = &cert->data->tbsCertificate.extensions->val[i];
+
+ if (ext->_ioschoice_extnValue.element !=
+ choice_Extension_iosnumunknown &&
+ ext->_ioschoice_extnValue.element !=
+ choice_Extension_iosnum_id_heim_ce_pkinit_princ_max_life)
+ continue;
+ if (ext->_ioschoice_extnValue.element == choice_Extension_iosnumunknown &&
+ der_heim_oid_cmp(&asn1_oid_id_heim_ce_pkinit_princ_max_life, &ext->extnID))
+ continue;
+ if (ext->_ioschoice_extnValue.u.ext_HeimPkinitPrincMaxLife) {
+ r = *ext->_ioschoice_extnValue.u.ext_HeimPkinitPrincMaxLife;
+ } else {
+ ret = decode_HeimPkinitPrincMaxLifeSecs(ext->extnValue.data,
+ ext->extnValue.length,
+ &r, &sz);
+ /* No need to free_HeimPkinitPrincMaxLifeSecs(); it's an int */
+ if (ret || r < 1)
+ return 0;
+ }
+ if (bound > 0 && r > bound)
+ return bound;
+ return r;
+ }
+ if (hx509_cert_check_eku(context, cert,
+ &asn1_oid_id_heim_eku_pkinit_certlife_is_max_life, 0))
+ return 0;
+ b = hx509_cert_get_notBefore(cert);
+ e = hx509_cert_get_notAfter(cert);
+ if (e > b)
+ r = e - b;
+ if (bound > 0 && r > bound)
+ return bound;
+ return r;
+}
+
+/**
+ * Get the SubjectPublicKeyInfo structure from the hx509 certificate.
+ *
+ * @param context a hx509 context.
+ * @param p a hx509 certificate object.
+ * @param spki SubjectPublicKeyInfo, should be freed with
+ * free_SubjectPublicKeyInfo().
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_get_SPKI(hx509_context context, hx509_cert p, SubjectPublicKeyInfo *spki)
+{
+ int ret;
+
+ ret = copy_SubjectPublicKeyInfo(&p->data->tbsCertificate.subjectPublicKeyInfo, spki);
+ if (ret)
+ hx509_set_error_string(context, 0, ret, "Failed to copy SPKI");
+ return ret;
+}
+
+/**
+ * Get the AlgorithmIdentifier from the hx509 certificate.
+ *
+ * @param context a hx509 context.
+ * @param p a hx509 certificate object.
+ * @param alg AlgorithmIdentifier, should be freed with
+ * free_AlgorithmIdentifier(). The algorithmidentifier is
+ * typicly rsaEncryption, or id-ecPublicKey, or some other
+ * public key mechanism.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_get_SPKI_AlgorithmIdentifier(hx509_context context,
+ hx509_cert p,
+ AlgorithmIdentifier *alg)
+{
+ int ret;
+
+ ret = copy_AlgorithmIdentifier(&p->data->tbsCertificate.subjectPublicKeyInfo.algorithm, alg);
+ if (ret)
+ hx509_set_error_string(context, 0, ret,
+ "Failed to copy SPKI AlgorithmIdentifier");
+ return ret;
+}
+
+static int
+get_x_unique_id(hx509_context context, const char *name,
+ const heim_bit_string *cert, heim_bit_string *subject)
+{
+ int ret;
+
+ if (cert == NULL) {
+ ret = HX509_EXTENSION_NOT_FOUND;
+ hx509_set_error_string(context, 0, ret, "%s unique id doesn't exist", name);
+ return ret;
+ }
+ ret = der_copy_bit_string(cert, subject);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "malloc out of memory", name);
+ return ret;
+ }
+ return 0;
+}
+
+/**
+ * Get a copy of the Issuer Unique ID
+ *
+ * @param context a hx509_context
+ * @param p a hx509 certificate
+ * @param issuer the issuer id returned, free with der_free_bit_string()
+ *
+ * @return An hx509 error code, see hx509_get_error_string(). The
+ * error code HX509_EXTENSION_NOT_FOUND is returned if the certificate
+ * doesn't have a issuerUniqueID
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_get_issuer_unique_id(hx509_context context, hx509_cert p, heim_bit_string *issuer)
+{
+ return get_x_unique_id(context, "issuer", p->data->tbsCertificate.issuerUniqueID, issuer);
+}
+
+/**
+ * Get a copy of the Subect Unique ID
+ *
+ * @param context a hx509_context
+ * @param p a hx509 certificate
+ * @param subject the subject id returned, free with der_free_bit_string()
+ *
+ * @return An hx509 error code, see hx509_get_error_string(). The
+ * error code HX509_EXTENSION_NOT_FOUND is returned if the certificate
+ * doesn't have a subjectUniqueID
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_get_subject_unique_id(hx509_context context, hx509_cert p, heim_bit_string *subject)
+{
+ return get_x_unique_id(context, "subject", p->data->tbsCertificate.subjectUniqueID, subject);
+}
+
+
+HX509_LIB_FUNCTION hx509_private_key HX509_LIB_CALL
+_hx509_cert_private_key(hx509_cert p)
+{
+ return p->private_key;
+}
+
+/**
+ * Indicate whether a hx509_cert has a private key.
+ *
+ * @param p a hx509 certificate
+ *
+ * @return 1 if p has a private key, 0 otherwise.
+ *
+ * @ingroup hx509_cert
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_have_private_key(hx509_cert p)
+{
+ return p->private_key ? 1 : 0;
+}
+
+/**
+ * Indicate whether a hx509_cert has a private key only (no certificate).
+ *
+ * @param p a hx509 certificate
+ *
+ * @return 1 if p has a private key only (no certificate), 0 otherwise.
+ *
+ * @ingroup hx509_cert
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_have_private_key_only(hx509_cert p)
+{
+ return p->private_key && !p->data ? 1 : 0;
+}
+
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_cert_private_key_exportable(hx509_cert p)
+{
+ if (p->private_key == NULL)
+ return 0;
+ return _hx509_private_key_exportable(p->private_key);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_cert_private_decrypt(hx509_context context,
+ const heim_octet_string *ciphertext,
+ const heim_oid *encryption_oid,
+ hx509_cert p,
+ heim_octet_string *cleartext)
+{
+ cleartext->data = NULL;
+ cleartext->length = 0;
+
+ if (p->private_key == NULL) {
+ hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING,
+ "Private key missing");
+ return HX509_PRIVATE_KEY_MISSING;
+ }
+
+ return hx509_private_key_private_decrypt(context,
+ ciphertext,
+ encryption_oid,
+ p->private_key,
+ cleartext);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_public_encrypt(hx509_context context,
+ const heim_octet_string *cleartext,
+ const hx509_cert p,
+ heim_oid *encryption_oid,
+ heim_octet_string *ciphertext)
+{
+ return _hx509_public_encrypt(context,
+ cleartext, p->data,
+ encryption_oid, ciphertext);
+}
+
+/*
+ *
+ */
+
+HX509_LIB_FUNCTION time_t HX509_LIB_CALL
+_hx509_Time2time_t(const Time *t)
+{
+ switch(t->element) {
+ case choice_Time_utcTime:
+ return t->u.utcTime;
+ case choice_Time_generalTime:
+ return t->u.generalTime;
+ }
+ return 0;
+}
+
+/*
+ *
+ */
+
+static int
+init_name_constraints(hx509_name_constraints *nc)
+{
+ memset(nc, 0, sizeof(*nc));
+ return 0;
+}
+
+static int
+add_name_constraints(hx509_context context, const Certificate *c, int not_ca,
+ hx509_name_constraints *nc)
+{
+ NameConstraints tnc;
+ int ret;
+
+ ret = find_extension_name_constraints(c, &tnc);
+ if (ret == HX509_EXTENSION_NOT_FOUND)
+ return 0;
+ else if (ret) {
+ hx509_set_error_string(context, 0, ret, "Failed getting NameConstraints");
+ return ret;
+ } else if (not_ca) {
+ ret = HX509_VERIFY_CONSTRAINTS;
+ hx509_set_error_string(context, 0, ret, "Not a CA and "
+ "have NameConstraints");
+ } else {
+ NameConstraints *val;
+ val = realloc(nc->val, sizeof(nc->val[0]) * (nc->len + 1));
+ if (val == NULL) {
+ hx509_clear_error_string(context);
+ ret = ENOMEM;
+ goto out;
+ }
+ nc->val = val;
+ ret = copy_NameConstraints(&tnc, &nc->val[nc->len]);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ nc->len += 1;
+ }
+out:
+ free_NameConstraints(&tnc);
+ return ret;
+}
+
+static int
+match_RDN(const RelativeDistinguishedName *c,
+ const RelativeDistinguishedName *n)
+{
+ size_t i;
+
+ if (c->len != n->len)
+ return HX509_NAME_CONSTRAINT_ERROR;
+
+ for (i = 0; i < n->len; i++) {
+ int diff, ret;
+
+ if (der_heim_oid_cmp(&c->val[i].type, &n->val[i].type) != 0)
+ return HX509_NAME_CONSTRAINT_ERROR;
+ ret = _hx509_name_ds_cmp(&c->val[i].value, &n->val[i].value, &diff);
+ if (ret)
+ return ret;
+ if (diff != 0)
+ return HX509_NAME_CONSTRAINT_ERROR;
+ }
+ return 0;
+}
+
+static int
+match_X501Name(const Name *c, const Name *n)
+{
+ size_t i;
+ int ret;
+
+ if (c->element != choice_Name_rdnSequence
+ || n->element != choice_Name_rdnSequence)
+ return 0;
+ if (c->u.rdnSequence.len > n->u.rdnSequence.len)
+ return HX509_NAME_CONSTRAINT_ERROR;
+ for (i = 0; i < c->u.rdnSequence.len; i++) {
+ ret = match_RDN(&c->u.rdnSequence.val[i], &n->u.rdnSequence.val[i]);
+ if (ret)
+ return ret;
+ }
+ return 0;
+}
+
+
+static int
+match_general_name(const GeneralName *c, const GeneralName *n, int *match)
+{
+ /*
+ * Name constraints only apply to the same name type, see RFC3280,
+ * 4.2.1.11.
+ */
+ assert(c->element == n->element);
+
+ switch(c->element) {
+ case choice_GeneralName_otherName:
+ if (der_heim_oid_cmp(&c->u.otherName.type_id,
+ &n->u.otherName.type_id) != 0)
+ return HX509_NAME_CONSTRAINT_ERROR;
+ if (heim_any_cmp(&c->u.otherName.value,
+ &n->u.otherName.value) != 0)
+ return HX509_NAME_CONSTRAINT_ERROR;
+ *match = 1;
+ return 0;
+ case choice_GeneralName_rfc822Name: {
+ const char *s;
+ size_t len1, len2;
+ s = memchr(c->u.rfc822Name.data, '@', c->u.rfc822Name.length);
+ if (s) {
+ if (der_printable_string_cmp(&c->u.rfc822Name, &n->u.rfc822Name) != 0)
+ return HX509_NAME_CONSTRAINT_ERROR;
+ } else {
+ s = memchr(n->u.rfc822Name.data, '@', n->u.rfc822Name.length);
+ if (s == NULL)
+ return HX509_NAME_CONSTRAINT_ERROR;
+ len1 = c->u.rfc822Name.length;
+ len2 = n->u.rfc822Name.length -
+ (s - ((char *)n->u.rfc822Name.data));
+ if (len1 > len2)
+ return HX509_NAME_CONSTRAINT_ERROR;
+ if (memcmp(s + 1 + len2 - len1, c->u.rfc822Name.data, len1) != 0)
+ return HX509_NAME_CONSTRAINT_ERROR;
+ if (len1 < len2 && s[len2 - len1 + 1] != '.')
+ return HX509_NAME_CONSTRAINT_ERROR;
+ }
+ *match = 1;
+ return 0;
+ }
+ case choice_GeneralName_dNSName: {
+ size_t lenc, lenn;
+ char *ptr;
+
+ lenc = c->u.dNSName.length;
+ lenn = n->u.dNSName.length;
+ if (lenc > lenn)
+ return HX509_NAME_CONSTRAINT_ERROR;
+ ptr = n->u.dNSName.data;
+ if (memcmp(&ptr[lenn - lenc], c->u.dNSName.data, lenc) != 0)
+ return HX509_NAME_CONSTRAINT_ERROR;
+ if (lenn != lenc && ptr[lenn - lenc - 1] != '.')
+ return HX509_NAME_CONSTRAINT_ERROR;
+ *match = 1;
+ return 0;
+ }
+ case choice_GeneralName_directoryName: {
+ Name c_name, n_name;
+ int ret;
+
+ c_name._save.data = NULL;
+ c_name._save.length = 0;
+ c_name.element = (enum Name_enum)c->u.directoryName.element;
+ c_name.u.rdnSequence = c->u.directoryName.u.rdnSequence;
+
+ n_name._save.data = NULL;
+ n_name._save.length = 0;
+ n_name.element = (enum Name_enum)n->u.directoryName.element;
+ n_name.u.rdnSequence = n->u.directoryName.u.rdnSequence;
+
+ ret = match_X501Name(&c_name, &n_name);
+ if (ret == 0)
+ *match = 1;
+ return ret;
+ }
+ case choice_GeneralName_uniformResourceIdentifier:
+ case choice_GeneralName_iPAddress:
+ case choice_GeneralName_registeredID:
+ default:
+ return HX509_NAME_CONSTRAINT_ERROR;
+ }
+}
+
+static int
+match_alt_name(const GeneralName *n, const Certificate *c,
+ int *same, int *match)
+{
+ GeneralNames sa;
+ int ret = 0;
+ size_t i, j;
+
+ i = 0;
+ do {
+ ret = find_extension_subject_alt_name(c, &i, &sa);
+ if (ret == HX509_EXTENSION_NOT_FOUND) {
+ ret = 0;
+ break;
+ } else if (ret != 0)
+ break;
+
+ for (j = 0; j < sa.len; j++) {
+ if (n->element == sa.val[j].element) {
+ *same = 1;
+ match_general_name(n, &sa.val[j], match);
+ }
+ }
+ free_GeneralNames(&sa);
+ } while (1);
+ return ret;
+}
+
+
+static int
+match_tree(const GeneralSubtrees *t, const Certificate *c, int *match)
+{
+ int name, alt_name, same;
+ unsigned int i;
+ int ret = 0;
+
+ name = alt_name = same = *match = 0;
+ for (i = 0; i < t->len; i++) {
+ if (t->val[i].minimum && t->val[i].maximum)
+ return HX509_RANGE;
+
+ /*
+ * If the constraint apply to directoryNames, test is with
+ * subjectName of the certificate if the certificate have a
+ * non-null (empty) subjectName.
+ */
+
+ if (t->val[i].base.element == choice_GeneralName_directoryName
+ && !subject_null_p(c))
+ {
+ GeneralName certname;
+
+ memset(&certname, 0, sizeof(certname));
+ certname.element = choice_GeneralName_directoryName;
+ certname.u.directoryName.element = (enum Name_enum)
+ c->tbsCertificate.subject.element;
+ certname.u.directoryName.u.rdnSequence =
+ c->tbsCertificate.subject.u.rdnSequence;
+
+ match_general_name(&t->val[i].base, &certname, &name);
+ }
+
+ /* Handle subjectAltNames, this is icky since they
+ * restrictions only apply if the subjectAltName is of the
+ * same type. So if there have been a match of type, require
+ * altname to be set.
+ */
+ match_alt_name(&t->val[i].base, c, &same, &alt_name);
+ }
+ if (name && (!same || alt_name))
+ *match = 1;
+ return ret;
+}
+
+static int
+check_name_constraints(hx509_context context,
+ const hx509_name_constraints *nc,
+ const Certificate *c)
+{
+ int match, ret;
+ size_t i;
+
+ for (i = 0 ; i < nc->len; i++) {
+ GeneralSubtrees gs;
+
+ if (nc->val[i].permittedSubtrees) {
+ GeneralSubtrees_SET(&gs, nc->val[i].permittedSubtrees);
+ ret = match_tree(&gs, c, &match);
+ if (ret) {
+ hx509_clear_error_string(context);
+ return ret;
+ }
+ /* allow null subjectNames, they wont matches anything */
+ if (match == 0 && !subject_null_p(c)) {
+ hx509_set_error_string(context, 0, HX509_VERIFY_CONSTRAINTS,
+ "Error verifying constraints: "
+ "certificate didn't match any "
+ "permitted subtree");
+ return HX509_VERIFY_CONSTRAINTS;
+ }
+ }
+ if (nc->val[i].excludedSubtrees) {
+ GeneralSubtrees_SET(&gs, nc->val[i].excludedSubtrees);
+ ret = match_tree(&gs, c, &match);
+ if (ret) {
+ hx509_clear_error_string(context);
+ return ret;
+ }
+ if (match) {
+ hx509_set_error_string(context, 0, HX509_VERIFY_CONSTRAINTS,
+ "Error verifying constraints: "
+ "certificate included in excluded "
+ "subtree");
+ return HX509_VERIFY_CONSTRAINTS;
+ }
+ }
+ }
+ return 0;
+}
+
+static void
+free_name_constraints(hx509_name_constraints *nc)
+{
+ size_t i;
+
+ for (i = 0 ; i < nc->len; i++)
+ free_NameConstraints(&nc->val[i]);
+ free(nc->val);
+}
+
+/**
+ * Build and verify the path for the certificate to the trust anchor
+ * specified in the verify context. The path is constructed from the
+ * certificate, the pool and the trust anchors.
+ *
+ * @param context A hx509 context.
+ * @param ctx A hx509 verification context.
+ * @param cert the certificate to build the path from.
+ * @param pool A keyset of certificates to build the chain from.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_verify_path(hx509_context context,
+ hx509_verify_ctx ctx,
+ hx509_cert cert,
+ hx509_certs pool)
+{
+ hx509_name_constraints nc;
+ hx509_path path;
+ int ret, proxy_cert_depth, selfsigned_depth, diff;
+ size_t i, k;
+ enum certtype type;
+ Name proxy_issuer;
+ hx509_certs anchors = NULL;
+
+ memset(&proxy_issuer, 0, sizeof(proxy_issuer));
+
+ if ((ctx->flags & HX509_VERIFY_CTX_F_ALLOW_PROXY_CERTIFICATE) == 0 &&
+ is_proxy_cert(context, cert->data, NULL) == 0)
+ {
+ ret = HX509_PROXY_CERT_INVALID;
+ hx509_set_error_string(context, 0, ret,
+ "Proxy certificate is not allowed as an EE "
+ "certificate if proxy certificate is disabled");
+ return ret;
+ }
+
+ ret = init_name_constraints(&nc);
+ if (ret)
+ return ret;
+
+ path.val = NULL;
+ path.len = 0;
+
+ if ((ctx->flags & HX509_VERIFY_CTX_F_TIME_SET) == 0)
+ ctx->time_now = time(NULL);
+
+ /*
+ *
+ */
+ if (ctx->trust_anchors)
+ anchors = hx509_certs_ref(ctx->trust_anchors);
+ else if (context->default_trust_anchors && ALLOW_DEF_TA(ctx))
+ anchors = hx509_certs_ref(context->default_trust_anchors);
+ else {
+ ret = hx509_certs_init(context, "MEMORY:no-TA", 0, NULL, &anchors);
+ if (ret)
+ goto out;
+ }
+
+ /*
+ * Calculate the path from the certificate user presented to the
+ * to an anchor.
+ */
+ ret = _hx509_calculate_path(context, 0, ctx->time_now,
+ anchors, ctx->max_depth,
+ cert, pool, &path);
+ if (ret)
+ goto out;
+
+ /*
+ * Check CA and proxy certificate chain from the top of the
+ * certificate chain. Also check certificate is valid with respect
+ * to the current time.
+ *
+ */
+
+ proxy_cert_depth = 0;
+ selfsigned_depth = 0;
+
+ if (ctx->flags & HX509_VERIFY_CTX_F_ALLOW_PROXY_CERTIFICATE)
+ type = PROXY_CERT;
+ else
+ type = EE_CERT;
+
+ for (i = 0; i < path.len; i++) {
+ Certificate *c;
+ time_t t;
+
+ c = _hx509_get_cert(path.val[i]);
+
+ /*
+ * Lets do some basic check on issuer like
+ * keyUsage.keyCertSign and basicConstraints.cA bit depending
+ * on what type of certificate this is.
+ */
+
+ switch (type) {
+ case CA_CERT:
+
+ /* XXX make constants for keyusage */
+ ret = check_key_usage(context, c, 1 << 5,
+ REQUIRE_RFC3280(ctx) ? TRUE : FALSE);
+ if (ret) {
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "Key usage missing from CA certificate");
+ goto out;
+ }
+
+ /* self signed cert doesn't add to path length */
+ if (i + 1 != path.len) {
+ int selfsigned;
+
+ ret = certificate_is_self_signed(context, c, &selfsigned);
+ if (ret)
+ goto out;
+ if (selfsigned)
+ selfsigned_depth++;
+ }
+
+ break;
+ case PROXY_CERT: {
+ ProxyCertInfo info;
+
+ if (is_proxy_cert(context, c, &info) == 0) {
+ size_t j;
+
+ if (info.pCPathLenConstraint != NULL &&
+ *info.pCPathLenConstraint < i)
+ {
+ free_ProxyCertInfo(&info);
+ ret = HX509_PATH_TOO_LONG;
+ hx509_set_error_string(context, 0, ret,
+ "Proxy certificate chain "
+ "longer than allowed");
+ goto out;
+ }
+ /* XXX MUST check info.proxyPolicy */
+ free_ProxyCertInfo(&info);
+
+ j = 0;
+ if (find_extension(c, &asn1_oid_id_x509_ce_subjectAltName, &j)) {
+ ret = HX509_PROXY_CERT_INVALID;
+ hx509_set_error_string(context, 0, ret,
+ "Proxy certificate has explicitly "
+ "forbidden subjectAltName");
+ goto out;
+ }
+
+ j = 0;
+ if (find_extension(c, &asn1_oid_id_x509_ce_issuerAltName, &j)) {
+ ret = HX509_PROXY_CERT_INVALID;
+ hx509_set_error_string(context, 0, ret,
+ "Proxy certificate has explicitly "
+ "forbidden issuerAltName");
+ goto out;
+ }
+
+ /*
+ * The subject name of the proxy certificate should be
+ * CN=XXX,<proxy issuer>, prune of CN and check if its
+ * the same over the whole chain of proxy certs and
+ * then check with the EE cert when we get to it.
+ */
+
+ if (proxy_cert_depth) {
+ ret = _hx509_name_cmp(&proxy_issuer, &c->tbsCertificate.subject, &diff);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ if (diff) {
+ ret = HX509_PROXY_CERT_NAME_WRONG;
+ hx509_set_error_string(context, 0, ret,
+ "Base proxy name not right");
+ goto out;
+ }
+ }
+
+ free_Name(&proxy_issuer);
+
+ ret = copy_Name(&c->tbsCertificate.subject, &proxy_issuer);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+
+ j = proxy_issuer.u.rdnSequence.len;
+ if (proxy_issuer.u.rdnSequence.len < 2
+ || proxy_issuer.u.rdnSequence.val[j - 1].len > 1
+ || der_heim_oid_cmp(&proxy_issuer.u.rdnSequence.val[j - 1].val[0].type,
+ &asn1_oid_id_at_commonName))
+ {
+ ret = HX509_PROXY_CERT_NAME_WRONG;
+ hx509_set_error_string(context, 0, ret,
+ "Proxy name too short or "
+ "does not have Common name "
+ "at the top");
+ goto out;
+ }
+
+ free_RelativeDistinguishedName(&proxy_issuer.u.rdnSequence.val[j - 1]);
+ proxy_issuer.u.rdnSequence.len -= 1;
+
+ ret = _hx509_name_cmp(&proxy_issuer, &c->tbsCertificate.issuer, &diff);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ goto out;
+ }
+ if (diff != 0) {
+ ret = HX509_PROXY_CERT_NAME_WRONG;
+ hx509_set_error_string(context, 0, ret,
+ "Proxy issuer name not as expected");
+ goto out;
+ }
+
+ break;
+ } else {
+ /*
+ * Now we are done with the proxy certificates, this
+ * cert was an EE cert and we we will fall though to
+ * EE checking below.
+ */
+ type = EE_CERT;
+ }
+ }
+ fallthrough;
+ case EE_CERT:
+ /*
+ * If there where any proxy certificates in the chain
+ * (proxy_cert_depth > 0), check that the proxy issuer
+ * matched proxy certificates "base" subject.
+ */
+ if (proxy_cert_depth) {
+
+ ret = _hx509_name_cmp(&proxy_issuer,
+ &c->tbsCertificate.subject, &diff);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ goto out;
+ }
+ if (diff) {
+ ret = HX509_PROXY_CERT_NAME_WRONG;
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ if (cert->basename)
+ hx509_name_free(&cert->basename);
+
+ ret = _hx509_name_from_Name(&proxy_issuer, &cert->basename);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ }
+
+ break;
+ }
+
+ ret = check_basic_constraints(context, c, type,
+ i - proxy_cert_depth - selfsigned_depth);
+ if (ret)
+ goto out;
+
+ /*
+ * Don't check the trust anchors expiration time since they
+ * are transported out of band, from RFC3820.
+ */
+ if (i + 1 != path.len || CHECK_TA(ctx)) {
+
+ t = _hx509_Time2time_t(&c->tbsCertificate.validity.notBefore);
+ if (t > ctx->time_now) {
+ ret = HX509_CERT_USED_BEFORE_TIME;
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ t = _hx509_Time2time_t(&c->tbsCertificate.validity.notAfter);
+ if (t < ctx->time_now) {
+ ret = HX509_CERT_USED_AFTER_TIME;
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ }
+
+ if (type == EE_CERT)
+ type = CA_CERT;
+ else if (type == PROXY_CERT)
+ proxy_cert_depth++;
+ }
+
+ /*
+ * Verify constraints, do this backward so path constraints are
+ * checked in the right order.
+ */
+
+ for (ret = 0, k = path.len; k > 0; k--) {
+ Certificate *c;
+ int selfsigned;
+ i = k - 1;
+
+ c = _hx509_get_cert(path.val[i]);
+
+ ret = certificate_is_self_signed(context, c, &selfsigned);
+ if (ret)
+ goto out;
+
+ /* verify name constraints, not for selfsigned and anchor */
+ if (!selfsigned || i + 1 != path.len) {
+ ret = check_name_constraints(context, &nc, c);
+ if (ret) {
+ goto out;
+ }
+ }
+ ret = add_name_constraints(context, c, i == 0, &nc);
+ if (ret)
+ goto out;
+
+ /* XXX verify all other silly constraints */
+
+ }
+
+ /*
+ * Verify that no certificates has been revoked.
+ */
+
+ if (ctx->revoke_ctx) {
+ hx509_certs certs;
+
+ ret = hx509_certs_init(context, "MEMORY:revoke-certs", 0,
+ NULL, &certs);
+ if (ret)
+ goto out;
+
+ for (i = 0; i < path.len; i++) {
+ ret = hx509_certs_add(context, certs, path.val[i]);
+ if (ret) {
+ hx509_certs_free(&certs);
+ goto out;
+ }
+ }
+ ret = hx509_certs_merge(context, certs, pool);
+ if (ret) {
+ hx509_certs_free(&certs);
+ goto out;
+ }
+
+ for (i = 0; i < path.len - 1; i++) {
+ size_t parent = (i < path.len - 1) ? i + 1 : i;
+
+ ret = hx509_revoke_verify(context,
+ ctx->revoke_ctx,
+ certs,
+ ctx->time_now,
+ path.val[i],
+ path.val[parent]);
+ if (ret) {
+ hx509_certs_free(&certs);
+ goto out;
+ }
+ }
+ hx509_certs_free(&certs);
+ }
+
+ /*
+ * Verify signatures, do this backward so public key working
+ * parameter is passed up from the anchor up though the chain.
+ */
+
+ for (k = path.len; k > 0; k--) {
+ hx509_cert signer;
+ Certificate *c;
+ i = k - 1;
+
+ c = _hx509_get_cert(path.val[i]);
+
+ /* is last in chain (trust anchor) */
+ if (i + 1 == path.len) {
+ int selfsigned;
+
+ signer = path.val[i];
+
+ ret = certificate_is_self_signed(context, signer->data, &selfsigned);
+ if (ret)
+ goto out;
+
+ /* if trust anchor is not self signed, don't check sig */
+ if (!selfsigned)
+ continue;
+ } else {
+ /* take next certificate in chain */
+ signer = path.val[i + 1];
+ }
+
+ /* verify signatureValue */
+ ret = _hx509_verify_signature_bitstring(context,
+ signer,
+ &c->signatureAlgorithm,
+ &c->tbsCertificate._save,
+ &c->signatureValue);
+ if (ret) {
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "Failed to verify signature of certificate");
+ goto out;
+ }
+ /*
+ * Verify that the sigature algorithm is not weak. Ignore
+ * trust anchors since they are provisioned by the user.
+ */
+
+ if (i + 1 != path.len && (ctx->flags & HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK) == 0) {
+ ret = _hx509_signature_is_weak(context, &c->signatureAlgorithm);
+ if (ret)
+ goto out;
+ }
+ }
+
+out:
+ hx509_certs_free(&anchors);
+ free_Name(&proxy_issuer);
+ free_name_constraints(&nc);
+ _hx509_path_free(&path);
+
+ return ret;
+}
+
+/**
+ * Verify a signature made using the private key of an certificate.
+ *
+ * @param context A hx509 context.
+ * @param signer the certificate that made the signature.
+ * @param alg algorthm that was used to sign the data.
+ * @param data the data that was signed.
+ * @param sig the sigature to verify.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_crypto
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_verify_signature(hx509_context context,
+ const hx509_cert signer,
+ const AlgorithmIdentifier *alg,
+ const heim_octet_string *data,
+ const heim_octet_string *sig)
+{
+ return _hx509_verify_signature(context, signer, alg, data, sig);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_verify_signature_bitstring(hx509_context context,
+ const hx509_cert signer,
+ const AlgorithmIdentifier *alg,
+ const heim_octet_string *data,
+ const heim_bit_string *sig)
+{
+ heim_octet_string os;
+
+ if (sig->length & 7) {
+ hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT,
+ "signature not multiple of 8 bits");
+ return HX509_CRYPTO_SIG_INVALID_FORMAT;
+ }
+
+ os.data = sig->data;
+ os.length = sig->length / 8;
+
+ return _hx509_verify_signature(context, signer, alg, data, &os);
+}
+
+
+
+/**
+ * Verify that the certificate is allowed to be used for the hostname
+ * and address.
+ *
+ * @param context A hx509 context.
+ * @param cert the certificate to match with
+ * @param flags Flags to modify the behavior:
+ * - HX509_VHN_F_ALLOW_NO_MATCH no match is ok
+ * @param type type of hostname:
+ * - HX509_HN_HOSTNAME for plain hostname.
+ * - HX509_HN_DNSSRV for DNS SRV names.
+ * @param hostname the hostname to check
+ * @param sa address of the host
+ * @param sa_size length of address
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_verify_hostname(hx509_context context,
+ const hx509_cert cert,
+ int flags,
+ hx509_hostname_type type,
+ const char *hostname,
+ const struct sockaddr *sa,
+ /* XXX krb5_socklen_t */ int sa_size)
+{
+ GeneralNames san;
+ const Name *name;
+ int ret;
+ size_t i, j, k;
+
+ if (sa && sa_size <= 0)
+ return EINVAL;
+
+ memset(&san, 0, sizeof(san));
+
+ i = 0;
+ do {
+ ret = find_extension_subject_alt_name(cert->data, &i, &san);
+ if (ret == HX509_EXTENSION_NOT_FOUND)
+ break;
+ else if (ret != 0)
+ return HX509_PARSING_NAME_FAILED;
+
+ for (j = 0; j < san.len; j++) {
+ switch (san.val[j].element) {
+ case choice_GeneralName_dNSName: {
+ heim_printable_string hn;
+ hn.data = rk_UNCONST(hostname);
+ hn.length = strlen(hostname);
+
+ if (der_printable_string_cmp(&san.val[j].u.dNSName, &hn) == 0) {
+ free_GeneralNames(&san);
+ return 0;
+ }
+ break;
+ }
+ default:
+ break;
+ }
+ }
+ free_GeneralNames(&san);
+ } while (1);
+
+ name = &cert->data->tbsCertificate.subject;
+
+ /* Find first CN= in the name, and try to match the hostname on that */
+ for (ret = 0, k = name->u.rdnSequence.len; ret == 0 && k > 0; k--) {
+ i = k - 1;
+ for (j = 0; ret == 0 && j < name->u.rdnSequence.val[i].len; j++) {
+ AttributeTypeAndValue *n = &name->u.rdnSequence.val[i].val[j];
+
+ if (der_heim_oid_cmp(&n->type, &asn1_oid_id_at_commonName) == 0) {
+ DirectoryString *ds = &n->value;
+ switch (ds->element) {
+ case choice_DirectoryString_printableString: {
+ heim_printable_string hn;
+ hn.data = rk_UNCONST(hostname);
+ hn.length = strlen(hostname);
+
+ if (der_printable_string_cmp(&ds->u.printableString, &hn) == 0)
+ return 0;
+ break;
+ }
+ case choice_DirectoryString_ia5String: {
+ heim_ia5_string hn;
+ hn.data = rk_UNCONST(hostname);
+ hn.length = strlen(hostname);
+
+ if (der_ia5_string_cmp(&ds->u.ia5String, &hn) == 0)
+ return 0;
+ break;
+ }
+ case choice_DirectoryString_utf8String:
+ if (strcasecmp(ds->u.utf8String, hostname) == 0)
+ return 0;
+ default:
+ break;
+ }
+ ret = HX509_NAME_CONSTRAINT_ERROR;
+ }
+ }
+ }
+
+ if ((flags & HX509_VHN_F_ALLOW_NO_MATCH) == 0)
+ ret = HX509_NAME_CONSTRAINT_ERROR;
+
+ return ret;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_set_cert_attribute(hx509_context context,
+ hx509_cert cert,
+ const heim_oid *oid,
+ const heim_octet_string *attr)
+{
+ hx509_cert_attribute a;
+ void *d;
+ int ret;
+
+ /*
+ * TODO: Rewrite this (and hx509_cert_attribute, and _hx509_cert_attrs) to
+ * use the add_AttributeValues() util generated by asn1_compile.
+ */
+
+ if (hx509_cert_get_attribute(cert, oid) != NULL)
+ return 0;
+
+ d = realloc(cert->attrs.val,
+ sizeof(cert->attrs.val[0]) * (cert->attrs.len + 1));
+ if (d == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+ cert->attrs.val = d;
+
+ a = malloc(sizeof(*a));
+ if (a == NULL)
+ return ENOMEM;
+
+ ret = der_copy_octet_string(attr, &a->data);
+ if (ret == 0)
+ ret = der_copy_oid(oid, &a->oid);
+ if (ret == 0) {
+ cert->attrs.val[cert->attrs.len] = a;
+ cert->attrs.len++;
+ } else {
+ der_free_octet_string(&a->data);
+ free(a);
+ }
+
+ return ret;
+}
+
+/**
+ * Get an external attribute for the certificate, examples are
+ * friendly name and id.
+ *
+ * @param cert hx509 certificate object to search
+ * @param oid an oid to search for.
+ *
+ * @return an hx509_cert_attribute, only valid as long as the
+ * certificate is referenced.
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION hx509_cert_attribute HX509_LIB_CALL
+hx509_cert_get_attribute(hx509_cert cert, const heim_oid *oid)
+{
+ size_t i;
+ for (i = 0; i < cert->attrs.len; i++)
+ if (der_heim_oid_cmp(oid, &cert->attrs.val[i]->oid) == 0)
+ return cert->attrs.val[i];
+ return NULL;
+}
+
+/**
+ * Set the friendly name on the certificate.
+ *
+ * @param cert The certificate to set the friendly name on
+ * @param name Friendly name.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_set_friendly_name(hx509_cert cert, const char *name)
+{
+ if (cert->friendlyname)
+ free(cert->friendlyname);
+ cert->friendlyname = strdup(name);
+ if (cert->friendlyname == NULL)
+ return ENOMEM;
+ return 0;
+}
+
+/**
+ * Get friendly name of the certificate.
+ *
+ * @param cert cert to get the friendly name from.
+ *
+ * @return an friendly name or NULL if there is. The friendly name is
+ * only valid as long as the certificate is referenced.
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION const char * HX509_LIB_CALL
+hx509_cert_get_friendly_name(hx509_cert cert)
+{
+ hx509_cert_attribute a;
+ PKCS9_friendlyName n;
+ size_t sz;
+ int ret;
+ size_t i;
+
+ if (cert->friendlyname)
+ return cert->friendlyname;
+
+ a = hx509_cert_get_attribute(cert, &asn1_oid_id_pkcs_9_at_friendlyName);
+ if (a == NULL) {
+ hx509_name name;
+
+ ret = hx509_cert_get_subject(cert, &name);
+ if (ret)
+ return NULL;
+ ret = hx509_name_to_string(name, &cert->friendlyname);
+ hx509_name_free(&name);
+ if (ret)
+ return NULL;
+ return cert->friendlyname;
+ }
+
+ ret = decode_PKCS9_friendlyName(a->data.data, a->data.length, &n, &sz);
+ if (ret)
+ return NULL;
+
+ if (n.len != 1) {
+ free_PKCS9_friendlyName(&n);
+ return NULL;
+ }
+
+ cert->friendlyname = malloc(n.val[0].length + 1);
+ if (cert->friendlyname == NULL) {
+ free_PKCS9_friendlyName(&n);
+ return NULL;
+ }
+
+ for (i = 0; i < n.val[0].length; i++) {
+ if (n.val[0].data[i] <= 0xff)
+ cert->friendlyname[i] = n.val[0].data[i] & 0xff;
+ else
+ cert->friendlyname[i] = 'X';
+ }
+ cert->friendlyname[i] = '\0';
+ free_PKCS9_friendlyName(&n);
+
+ return cert->friendlyname;
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_query_clear(hx509_query *q)
+{
+ memset(q, 0, sizeof(*q));
+}
+
+/**
+ * Allocate an query controller. Free using hx509_query_free().
+ *
+ * @param context A hx509 context.
+ * @param q return pointer to a hx509_query.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_query_alloc(hx509_context context, hx509_query **q)
+{
+ *q = calloc(1, sizeof(**q));
+ if (*q == NULL)
+ return ENOMEM;
+ return 0;
+}
+
+
+/**
+ * Set match options for the hx509 query controller.
+ *
+ * @param q query controller.
+ * @param option options to control the query controller.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_query_match_option(hx509_query *q, hx509_query_option option)
+{
+ switch(option) {
+ case HX509_QUERY_OPTION_PRIVATE_KEY:
+ q->match |= HX509_QUERY_PRIVATE_KEY;
+ break;
+ case HX509_QUERY_OPTION_KU_ENCIPHERMENT:
+ q->match |= HX509_QUERY_KU_ENCIPHERMENT;
+ break;
+ case HX509_QUERY_OPTION_KU_DIGITALSIGNATURE:
+ q->match |= HX509_QUERY_KU_DIGITALSIGNATURE;
+ break;
+ case HX509_QUERY_OPTION_KU_KEYCERTSIGN:
+ q->match |= HX509_QUERY_KU_KEYCERTSIGN;
+ break;
+ case HX509_QUERY_OPTION_END:
+ default:
+ break;
+ }
+}
+
+/**
+ * Set the issuer and serial number of match in the query
+ * controller. The function make copies of the isser and serial number.
+ *
+ * @param q a hx509 query controller
+ * @param issuer issuer to search for
+ * @param serialNumber the serialNumber of the issuer.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_query_match_issuer_serial(hx509_query *q,
+ const Name *issuer,
+ const heim_integer *serialNumber)
+{
+ int ret;
+ if (q->serial) {
+ der_free_heim_integer(q->serial);
+ free(q->serial);
+ }
+ q->serial = malloc(sizeof(*q->serial));
+ if (q->serial == NULL)
+ return ENOMEM;
+ ret = der_copy_heim_integer(serialNumber, q->serial);
+ if (ret) {
+ free(q->serial);
+ q->serial = NULL;
+ return ret;
+ }
+ if (q->issuer_name) {
+ free_Name(q->issuer_name);
+ free(q->issuer_name);
+ }
+ q->issuer_name = malloc(sizeof(*q->issuer_name));
+ if (q->issuer_name == NULL)
+ return ENOMEM;
+ ret = copy_Name(issuer, q->issuer_name);
+ if (ret) {
+ free(q->issuer_name);
+ q->issuer_name = NULL;
+ return ret;
+ }
+ q->match |= HX509_QUERY_MATCH_SERIALNUMBER|HX509_QUERY_MATCH_ISSUER_NAME;
+ return 0;
+}
+
+/**
+ * Set the query controller to match on a friendly name
+ *
+ * @param q a hx509 query controller.
+ * @param name a friendly name to match on
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_query_match_friendly_name(hx509_query *q, const char *name)
+{
+ if (q->friendlyname)
+ free(q->friendlyname);
+ q->friendlyname = strdup(name);
+ if (q->friendlyname == NULL)
+ return ENOMEM;
+ q->match |= HX509_QUERY_MATCH_FRIENDLY_NAME;
+ return 0;
+}
+
+/**
+ * Set the query controller to require an one specific EKU (extended
+ * key usage). Any previous EKU matching is overwitten. If NULL is
+ * passed in as the eku, the EKU requirement is reset.
+ *
+ * @param q a hx509 query controller.
+ * @param eku an EKU to match on.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_query_match_eku(hx509_query *q, const heim_oid *eku)
+{
+ int ret;
+
+ if (eku == NULL) {
+ if (q->eku) {
+ der_free_oid(q->eku);
+ free(q->eku);
+ q->eku = NULL;
+ }
+ q->match &= ~HX509_QUERY_MATCH_EKU;
+ } else {
+ if (q->eku) {
+ der_free_oid(q->eku);
+ } else {
+ q->eku = calloc(1, sizeof(*q->eku));
+ if (q->eku == NULL)
+ return ENOMEM;
+ }
+ ret = der_copy_oid(eku, q->eku);
+ if (ret) {
+ free(q->eku);
+ q->eku = NULL;
+ return ret;
+ }
+ q->match |= HX509_QUERY_MATCH_EKU;
+ }
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_query_match_expr(hx509_context context, hx509_query *q, const char *expr)
+{
+ if (q->expr) {
+ _hx509_expr_free(q->expr);
+ q->expr = NULL;
+ }
+
+ if (expr == NULL) {
+ q->match &= ~HX509_QUERY_MATCH_EXPR;
+ return 0;
+ }
+
+ q->expr = _hx509_expr_parse(expr);
+ if (q->expr == NULL) {
+ const char *reason = _hx509_expr_parse_error();
+
+ hx509_set_error_string(context, 0, EINVAL,
+ "Invalid certificate query match expression: "
+ "%s (%s)", expr,
+ reason ? reason : "syntax error");
+ return EINVAL;
+ }
+
+ q->match |= HX509_QUERY_MATCH_EXPR;
+ return 0;
+}
+
+/**
+ * Set the query controller to match using a specific match function.
+ *
+ * @param q a hx509 query controller.
+ * @param func function to use for matching, if the argument is NULL,
+ * the match function is removed.
+ * @param ctx context passed to the function.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_query_match_cmp_func(hx509_query *q,
+ int (*func)(hx509_context, hx509_cert, void *),
+ void *ctx)
+{
+ if (func)
+ q->match |= HX509_QUERY_MATCH_FUNCTION;
+ else
+ q->match &= ~HX509_QUERY_MATCH_FUNCTION;
+ q->cmp_func = func;
+ q->cmp_func_ctx = ctx;
+ return 0;
+}
+
+/**
+ * Free the query controller.
+ *
+ * @param context A hx509 context.
+ * @param q a pointer to the query controller.
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_query_free(hx509_context context, hx509_query *q)
+{
+ if (q == NULL)
+ return;
+
+ if (q->serial) {
+ der_free_heim_integer(q->serial);
+ free(q->serial);
+ }
+ if (q->issuer_name) {
+ free_Name(q->issuer_name);
+ free(q->issuer_name);
+ }
+ if (q->eku) {
+ der_free_oid(q->eku);
+ free(q->eku);
+ }
+ if (q->friendlyname)
+ free(q->friendlyname);
+ if (q->expr)
+ _hx509_expr_free(q->expr);
+
+ memset(q, 0, sizeof(*q));
+ free(q);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_query_match_cert(hx509_context context, const hx509_query *q, hx509_cert cert)
+{
+ Certificate *c = _hx509_get_cert(cert);
+ int ret, diff;
+
+ _hx509_query_statistic(context, 1, q);
+
+ if ((q->match & HX509_QUERY_FIND_ISSUER_CERT) &&
+ _hx509_cert_is_parent_cmp(q->subject, c, 0) != 0)
+ return 0;
+
+ if ((q->match & HX509_QUERY_MATCH_CERTIFICATE) &&
+ _hx509_Certificate_cmp(q->certificate, c) != 0)
+ return 0;
+
+ if ((q->match & HX509_QUERY_MATCH_SERIALNUMBER)
+ && der_heim_integer_cmp(&c->tbsCertificate.serialNumber, q->serial) != 0)
+ return 0;
+
+ if (q->match & HX509_QUERY_MATCH_ISSUER_NAME) {
+ ret = _hx509_name_cmp(&c->tbsCertificate.issuer, q->issuer_name, &diff);
+ if (ret || diff)
+ return 0;
+ }
+
+ if (q->match & HX509_QUERY_MATCH_SUBJECT_NAME) {
+ ret = _hx509_name_cmp(&c->tbsCertificate.subject, q->subject_name, &diff);
+ if (ret || diff)
+ return 0;
+ }
+
+ if (q->match & HX509_QUERY_MATCH_SUBJECT_KEY_ID) {
+ SubjectKeyIdentifier si;
+
+ ret = _hx509_find_extension_subject_key_id(c, &si);
+ if (ret == 0) {
+ if (der_heim_octet_string_cmp(&si, q->subject_id) != 0)
+ ret = 1;
+ free_SubjectKeyIdentifier(&si);
+ }
+ if (ret)
+ return 0;
+ }
+ if ((q->match & HX509_QUERY_MATCH_ISSUER_ID))
+ return 0;
+ if ((q->match & HX509_QUERY_PRIVATE_KEY) &&
+ _hx509_cert_private_key(cert) == NULL)
+ return 0;
+
+ {
+ unsigned ku = 0;
+ if (q->match & HX509_QUERY_KU_DIGITALSIGNATURE)
+ ku |= (1 << 0);
+ if (q->match & HX509_QUERY_KU_NONREPUDIATION)
+ ku |= (1 << 1);
+ if (q->match & HX509_QUERY_KU_ENCIPHERMENT)
+ ku |= (1 << 2);
+ if (q->match & HX509_QUERY_KU_DATAENCIPHERMENT)
+ ku |= (1 << 3);
+ if (q->match & HX509_QUERY_KU_KEYAGREEMENT)
+ ku |= (1 << 4);
+ if (q->match & HX509_QUERY_KU_KEYCERTSIGN)
+ ku |= (1 << 5);
+ if (q->match & HX509_QUERY_KU_CRLSIGN)
+ ku |= (1 << 6);
+ if (ku && check_key_usage(context, c, ku, TRUE))
+ return 0;
+ }
+ if ((q->match & HX509_QUERY_ANCHOR))
+ return 0;
+
+ if (q->match & HX509_QUERY_MATCH_LOCAL_KEY_ID) {
+ hx509_cert_attribute a;
+
+ a = hx509_cert_get_attribute(cert, &asn1_oid_id_pkcs_9_at_localKeyId);
+ if (a == NULL)
+ return 0;
+ if (der_heim_octet_string_cmp(&a->data, q->local_key_id) != 0)
+ return 0;
+ }
+
+ if (q->match & HX509_QUERY_NO_MATCH_PATH) {
+ size_t i;
+
+ for (i = 0; i < q->path->len; i++)
+ if (hx509_cert_cmp(q->path->val[i], cert) == 0)
+ return 0;
+ }
+ if (q->match & HX509_QUERY_MATCH_FRIENDLY_NAME) {
+ const char *name = hx509_cert_get_friendly_name(cert);
+ if (name == NULL)
+ return 0;
+ if (strcasecmp(q->friendlyname, name) != 0)
+ return 0;
+ }
+ if (q->match & HX509_QUERY_MATCH_FUNCTION) {
+ ret = (*q->cmp_func)(context, cert, q->cmp_func_ctx);
+ if (ret != 0)
+ return 0;
+ }
+
+ if (q->match & HX509_QUERY_MATCH_KEY_HASH_SHA1) {
+ heim_octet_string os;
+
+ os.data = c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.data;
+ os.length =
+ c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.length / 8;
+
+ ret = _hx509_verify_signature(context,
+ NULL,
+ hx509_signature_sha1(),
+ &os,
+ q->keyhash_sha1);
+ if (ret != 0)
+ return 0;
+ }
+
+ if (q->match & HX509_QUERY_MATCH_TIME) {
+ time_t t;
+ t = _hx509_Time2time_t(&c->tbsCertificate.validity.notBefore);
+ if (t > q->timenow)
+ return 0;
+ t = _hx509_Time2time_t(&c->tbsCertificate.validity.notAfter);
+ if (t < q->timenow)
+ return 0;
+ }
+
+ /* If an EKU is required, check the cert for it. */
+ if ((q->match & HX509_QUERY_MATCH_EKU) &&
+ hx509_cert_check_eku(context, cert, q->eku, 0))
+ return 0;
+
+ if ((q->match & HX509_QUERY_MATCH_EXPR)) {
+ hx509_env env = NULL;
+
+ ret = _hx509_cert_to_env(context, cert, &env);
+ if (ret)
+ return 0;
+
+ ret = _hx509_expr_eval(context, env, q->expr);
+ hx509_env_free(&env);
+ if (ret == 0)
+ return 0;
+ }
+
+ if (q->match & ~HX509_QUERY_MASK)
+ return 0;
+
+ return 1;
+}
+
+/**
+ * Set a statistic file for the query statistics.
+ *
+ * @param context A hx509 context.
+ * @param fn statistics file name
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_query_statistic_file(hx509_context context, const char *fn)
+{
+ if (context->querystat)
+ free(context->querystat);
+ context->querystat = strdup(fn);
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_query_statistic(hx509_context context, int type, const hx509_query *q)
+{
+ FILE *f;
+ if (context->querystat == NULL)
+ return;
+ f = fopen(context->querystat, "a");
+ if (f == NULL)
+ return;
+ rk_cloexec_file(f);
+ fprintf(f, "%d %d\n", type, q->match);
+ fclose(f);
+}
+
+static const char *statname[] = {
+ "find issuer cert",
+ "match serialnumber",
+ "match issuer name",
+ "match subject name",
+ "match subject key id",
+ "match issuer id",
+ "private key",
+ "ku encipherment",
+ "ku digitalsignature",
+ "ku keycertsign",
+ "ku crlsign",
+ "ku nonrepudiation",
+ "ku keyagreement",
+ "ku dataencipherment",
+ "anchor",
+ "match certificate",
+ "match local key id",
+ "no match path",
+ "match friendly name",
+ "match function",
+ "match key hash sha1",
+ "match time"
+};
+
+struct stat_el {
+ unsigned long stats;
+ unsigned int index;
+};
+
+
+static int
+stat_sort(const void *a, const void *b)
+{
+ const struct stat_el *ae = a;
+ const struct stat_el *be = b;
+ return be->stats - ae->stats;
+}
+
+/**
+ * Unparse the statistics file and print the result on a FILE descriptor.
+ *
+ * @param context A hx509 context.
+ * @param printtype tyep to print
+ * @param out the FILE to write the data on.
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_query_unparse_stats(hx509_context context, int printtype, FILE *out)
+{
+ rtbl_t t;
+ FILE *f;
+ int type, mask, num;
+ size_t i;
+ unsigned long multiqueries = 0, totalqueries = 0;
+ struct stat_el stats[32];
+
+ if (context->querystat == NULL)
+ return;
+ f = fopen(context->querystat, "r");
+ if (f == NULL) {
+ fprintf(out, "No statistics file %s: %s.\n",
+ context->querystat, strerror(errno));
+ return;
+ }
+ rk_cloexec_file(f);
+
+ for (i = 0; i < sizeof(stats)/sizeof(stats[0]); i++) {
+ stats[i].index = i;
+ stats[i].stats = 0;
+ }
+
+ while (fscanf(f, "%d %d\n", &type, &mask) == 2) {
+ if (type != printtype)
+ continue;
+ num = i = 0;
+ while (mask && i < sizeof(stats)/sizeof(stats[0])) {
+ if (mask & 1) {
+ stats[i].stats++;
+ num++;
+ }
+ mask = mask >>1 ;
+ i++;
+ }
+ if (num > 1)
+ multiqueries++;
+ totalqueries++;
+ }
+ fclose(f);
+
+ qsort(stats, sizeof(stats)/sizeof(stats[0]), sizeof(stats[0]), stat_sort);
+
+ t = rtbl_create();
+ if (t == NULL)
+ errx(1, "out of memory");
+
+ rtbl_set_separator (t, " ");
+
+ rtbl_add_column_by_id (t, 0, "Name", 0);
+ rtbl_add_column_by_id (t, 1, "Counter", 0);
+
+
+ for (i = 0; i < sizeof(stats)/sizeof(stats[0]); i++) {
+ char str[10];
+
+ if (stats[i].index < sizeof(statname)/sizeof(statname[0]))
+ rtbl_add_column_entry_by_id (t, 0, statname[stats[i].index]);
+ else {
+ snprintf(str, sizeof(str), "%d", stats[i].index);
+ rtbl_add_column_entry_by_id (t, 0, str);
+ }
+ snprintf(str, sizeof(str), "%lu", stats[i].stats);
+ rtbl_add_column_entry_by_id (t, 1, str);
+ }
+
+ rtbl_format(t, out);
+ rtbl_destroy(t);
+
+ fprintf(out, "\nQueries: multi %lu total %lu\n",
+ multiqueries, totalqueries);
+}
+
+/**
+ * Check the extended key usage on the hx509 certificate.
+ *
+ * @param context A hx509 context.
+ * @param cert A hx509 context.
+ * @param eku the EKU to check for
+ * @param allow_any_eku if the any EKU is set, allow that to be a
+ * substitute.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_check_eku(hx509_context context, hx509_cert cert,
+ const heim_oid *eku, int allow_any_eku)
+{
+ ExtKeyUsage e;
+ int ret;
+ size_t i;
+
+ ret = find_extension_eku(_hx509_get_cert(cert), &e);
+ if (ret) {
+ hx509_clear_error_string(context);
+ return ret;
+ }
+
+ for (i = 0; i < e.len; i++) {
+ if (der_heim_oid_cmp(eku, &e.val[i]) == 0) {
+ free_ExtKeyUsage(&e);
+ return 0;
+ }
+ if (allow_any_eku) {
+ if (der_heim_oid_cmp(&asn1_oid_id_x509_ce_anyExtendedKeyUsage,
+ &e.val[i]) == 0) {
+ free_ExtKeyUsage(&e);
+ return 0;
+ }
+ }
+ }
+ free_ExtKeyUsage(&e);
+ hx509_clear_error_string(context);
+ return HX509_CERTIFICATE_MISSING_EKU;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_cert_get_keyusage(hx509_context context,
+ hx509_cert c,
+ KeyUsage *ku)
+{
+ Certificate *cert;
+ const Extension *e;
+ size_t size;
+ int ret;
+ size_t i = 0;
+
+ memset(ku, 0, sizeof(*ku));
+
+ cert = _hx509_get_cert(c);
+
+ if (_hx509_cert_get_version(cert) < 3)
+ return 0;
+
+ e = find_extension(cert, &asn1_oid_id_x509_ce_keyUsage, &i);
+ if (e == NULL)
+ return HX509_KU_CERT_MISSING;
+
+ ret = decode_KeyUsage(e->extnValue.data, e->extnValue.length, ku, &size);
+ if (ret)
+ return ret;
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_cert_get_eku(hx509_context context,
+ hx509_cert cert,
+ ExtKeyUsage *e)
+{
+ int ret;
+
+ memset(e, 0, sizeof(*e));
+
+ ret = find_extension_eku(_hx509_get_cert(cert), e);
+ if (ret && ret != HX509_EXTENSION_NOT_FOUND) {
+ hx509_clear_error_string(context);
+ return ret;
+ }
+ return 0;
+}
+
+/**
+ * Encodes the hx509 certificate as a DER encode binary.
+ *
+ * @param context A hx509 context.
+ * @param c the certificate to encode.
+ * @param os the encode certificate, set to NULL, 0 on case of
+ * error. Free the os->data with hx509_xfree().
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_binary(hx509_context context, hx509_cert c, heim_octet_string *os)
+{
+ size_t size;
+ int ret;
+
+ os->data = NULL;
+ os->length = 0;
+
+ ASN1_MALLOC_ENCODE(Certificate, os->data, os->length,
+ _hx509_get_cert(c), &size, ret);
+ if (ret) {
+ os->data = NULL;
+ os->length = 0;
+ return ret;
+ }
+ if (os->length != size)
+ _hx509_abort("internal ASN.1 encoder error");
+ return ret;
+}
+
+/*
+ * Last to avoid lost __attribute__s due to #undef.
+ */
+
+#undef __attribute__
+#define __attribute__(X)
+
+HX509_LIB_NORETURN_FUNCTION void HX509_LIB_CALL
+_hx509_abort(const char *fmt, ...)
+ __attribute__ ((__noreturn__, __format__ (__printf__, 1, 2)))
+{
+ va_list ap;
+ va_start(ap, fmt);
+ vprintf(fmt, ap);
+ va_end(ap);
+ printf("\n");
+ fflush(stdout);
+ abort();
+}
+
+/**
+ * Free a data element allocated in the library.
+ *
+ * @param ptr data to be freed.
+ *
+ * @ingroup hx509_misc
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_xfree(void *ptr)
+{
+ free(ptr);
+}
+
+/**
+ *
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_cert_to_env(hx509_context context, hx509_cert cert, hx509_env *env)
+{
+ ExtKeyUsage eku;
+ hx509_name name;
+ char *buf;
+ int ret;
+ hx509_env envcert = NULL;
+
+ *env = NULL;
+
+ /* version */
+ ret = asprintf(&buf, "%d", _hx509_cert_get_version(_hx509_get_cert(cert)));
+ if (ret == -1)
+ goto out;
+ ret = hx509_env_add(context, &envcert, "version", buf);
+ free(buf);
+ if (ret)
+ goto out;
+
+ /* subject */
+ ret = hx509_cert_get_subject(cert, &name);
+ if (ret)
+ goto out;
+
+ ret = hx509_name_to_string(name, &buf);
+ hx509_name_free(&name);
+ if (ret)
+ goto out;
+
+ ret = hx509_env_add(context, &envcert, "subject", buf);
+ hx509_xfree(buf);
+ if (ret)
+ goto out;
+
+ /* issuer */
+ ret = hx509_cert_get_issuer(cert, &name);
+ if (ret)
+ goto out;
+
+ ret = hx509_name_to_string(name, &buf);
+ hx509_name_free(&name);
+ if (ret)
+ goto out;
+
+ ret = hx509_env_add(context, &envcert, "issuer", buf);
+ hx509_xfree(buf);
+ if (ret)
+ goto out;
+
+ /* eku */
+
+ ret = _hx509_cert_get_eku(context, cert, &eku);
+ if (ret == HX509_EXTENSION_NOT_FOUND)
+ ;
+ else if (ret != 0)
+ goto out;
+ else {
+ size_t i;
+ hx509_env enveku = NULL;
+
+ for (i = 0; i < eku.len; i++) {
+
+ ret = der_print_heim_oid(&eku.val[i], '.', &buf);
+ if (ret) {
+ free_ExtKeyUsage(&eku);
+ hx509_env_free(&enveku);
+ goto out;
+ }
+ ret = hx509_env_add(context, &enveku, buf, "oid-name-here");
+ free(buf);
+ if (ret) {
+ free_ExtKeyUsage(&eku);
+ hx509_env_free(&enveku);
+ goto out;
+ }
+ }
+ free_ExtKeyUsage(&eku);
+
+ ret = hx509_env_add_binding(context, &envcert, "eku", enveku);
+ if (ret) {
+ hx509_env_free(&enveku);
+ goto out;
+ }
+ }
+
+ {
+ Certificate *c = _hx509_get_cert(cert);
+ heim_octet_string os, sig;
+ hx509_env envhash = NULL;
+
+ os.data = c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.data;
+ os.length =
+ c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.length / 8;
+
+ ret = _hx509_create_signature(context,
+ NULL,
+ hx509_signature_sha1(),
+ &os,
+ NULL,
+ &sig);
+ if (ret != 0)
+ goto out;
+
+ ret = hex_encode(sig.data, sig.length, &buf);
+ der_free_octet_string(&sig);
+ if (ret < 0) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret,
+ "Out of memory");
+ goto out;
+ }
+
+ ret = hx509_env_add(context, &envhash, "sha1", buf);
+ free(buf);
+ if (ret)
+ goto out;
+
+ ret = hx509_env_add_binding(context, &envcert, "hash", envhash);
+ if (ret) {
+ hx509_env_free(&envhash);
+ goto out;
+ }
+ }
+
+ ret = hx509_env_add_binding(context, env, "certificate", envcert);
+ if (ret)
+ goto out;
+
+ return 0;
+
+out:
+ hx509_env_free(&envcert);
+ return ret;
+}
+
+/**
+ * Print a simple representation of a certificate
+ *
+ * @param context A hx509 context, can be NULL
+ * @param cert certificate to print
+ * @param out the stdio output stream, if NULL, stdout is used
+ *
+ * @return An hx509 error code
+ *
+ * @ingroup hx509_cert
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_print_cert(hx509_context context, hx509_cert cert, FILE *out)
+{
+ hx509_name name;
+ char *str;
+ int ret;
+
+ if (out == NULL)
+ out = stderr;
+
+ ret = hx509_cert_get_issuer(cert, &name);
+ if (ret)
+ return ret;
+ hx509_name_to_string(name, &str);
+ hx509_name_free(&name);
+ fprintf(out, " issuer: \"%s\"\n", str);
+ free(str);
+
+ ret = hx509_cert_get_subject(cert, &name);
+ if (ret)
+ return ret;
+ hx509_name_to_string(name, &str);
+ hx509_name_free(&name);
+ fprintf(out, " subject: \"%s\"\n", str);
+ free(str);
+
+ {
+ heim_integer serialNumber;
+
+ ret = hx509_cert_get_serialnumber(cert, &serialNumber);
+ if (ret)
+ return ret;
+ ret = der_print_hex_heim_integer(&serialNumber, &str);
+ if (ret)
+ return ret;
+ der_free_heim_integer(&serialNumber);
+ fprintf(out, " serial: %s\n", str);
+ free(str);
+ }
+
+ fprintf(out, " keyusage: ");
+ ret = hx509_cert_keyusage_print(context, cert, &str);
+ if (ret == 0) {
+ fprintf(out, "%s\n", str);
+ free(str);
+ } else
+ fprintf(out, "no");
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hx509/char_map.h b/third_party/heimdal/lib/hx509/char_map.h
new file mode 100644
index 0000000..8a3026c
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/char_map.h
@@ -0,0 +1,45 @@
+#define Q_CONTROL_CHAR 1
+#define Q_PRINTABLE 2
+#define Q_RFC2253_QUOTE_FIRST 4
+#define Q_RFC2253_QUOTE_LAST 8
+#define Q_RFC2253_QUOTE 16
+#define Q_RFC2253_HEX 32
+
+#define Q_RFC2253 (Q_RFC2253_QUOTE_FIRST|Q_RFC2253_QUOTE_LAST|Q_RFC2253_QUOTE|Q_RFC2253_HEX)
+
+
+
+unsigned char char_map[] = {
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x06 , 0x00 , 0x00 , 0x10 , 0x00 , 0x00 , 0x00 , 0x00 ,
+ 0x00 , 0x00 , 0x00 , 0x12 , 0x12 , 0x02 , 0x02 , 0x02 ,
+ 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 ,
+ 0x02 , 0x02 , 0x02 , 0x10 , 0x10 , 0x12 , 0x10 , 0x02 ,
+ 0x00 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 ,
+ 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 ,
+ 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 ,
+ 0x02 , 0x02 , 0x02 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 ,
+ 0x00 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 ,
+ 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 ,
+ 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 ,
+ 0x02 , 0x02 , 0x02 , 0x00 , 0x00 , 0x00 , 0x00 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 ,
+ 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21
+};
diff --git a/third_party/heimdal/lib/hx509/cms.c b/third_party/heimdal/lib/hx509/cms.c
new file mode 100644
index 0000000..d2728a3
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/cms.c
@@ -0,0 +1,1718 @@
+/*
+ * Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+/**
+ * @page page_cms CMS/PKCS7 message functions.
+ *
+ * CMS is defined in RFC 3369 and is an continuation of the RSA Labs
+ * standard PKCS7. The basic messages in CMS is
+ *
+ * - SignedData
+ * Data signed with private key (RSA, DSA, ECDSA) or secret
+ * (symmetric) key
+ * - EnvelopedData
+ * Data encrypted with private key (RSA)
+ * - EncryptedData
+ * Data encrypted with secret (symmetric) key.
+ * - ContentInfo
+ * Wrapper structure including type and data.
+ *
+ *
+ * See the library functions here: @ref hx509_cms
+ */
+
+#define ALLOC(X, N) (X) = calloc((N), sizeof(*(X)))
+#define ALLOC_SEQ(X, N) do { (X)->len = (N); ALLOC((X)->val, (N)); } while(0)
+
+/**
+ * Wrap data and oid in a ContentInfo and encode it.
+ *
+ * @param oid type of the content.
+ * @param buf data to be wrapped. If a NULL pointer is passed in, the
+ * optional content field in the ContentInfo is not going be filled
+ * in.
+ * @param res the encoded buffer, the result should be freed with
+ * der_free_octet_string().
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_cms
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cms_wrap_ContentInfo(const heim_oid *oid,
+ const heim_octet_string *buf,
+ heim_octet_string *res)
+{
+ ContentInfo ci;
+ size_t size;
+ int ret;
+
+ memset(res, 0, sizeof(*res));
+ memset(&ci, 0, sizeof(ci));
+
+ ret = der_copy_oid(oid, &ci.contentType);
+ if (ret)
+ return ret;
+ if (buf) {
+ ALLOC(ci.content, 1);
+ if (ci.content == NULL) {
+ free_ContentInfo(&ci);
+ return ENOMEM;
+ }
+ ci.content->data = malloc(buf->length);
+ if (ci.content->data == NULL) {
+ free_ContentInfo(&ci);
+ return ENOMEM;
+ }
+ memcpy(ci.content->data, buf->data, buf->length);
+ ci.content->length = buf->length;
+ }
+
+ ASN1_MALLOC_ENCODE(ContentInfo, res->data, res->length, &ci, &size, ret);
+ free_ContentInfo(&ci);
+ if (ret)
+ return ret;
+ if (res->length != size)
+ _hx509_abort("internal ASN.1 encoder error");
+
+ return 0;
+}
+
+/**
+ * Decode an ContentInfo and unwrap data and oid it.
+ *
+ * @param in the encoded buffer.
+ * @param oid type of the content.
+ * @param out data to be wrapped.
+ * @param have_data since the data is optional, this flags show dthe
+ * diffrence between no data and the zero length data.
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_cms
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cms_unwrap_ContentInfo(const heim_octet_string *in,
+ heim_oid *oid,
+ heim_octet_string *out,
+ int *have_data)
+{
+ ContentInfo ci;
+ size_t size;
+ int ret;
+
+ memset(oid, 0, sizeof(*oid));
+ memset(out, 0, sizeof(*out));
+
+ ret = decode_ContentInfo(in->data, in->length, &ci, &size);
+ if (ret)
+ return ret;
+
+ ret = der_copy_oid(&ci.contentType, oid);
+ if (ret) {
+ free_ContentInfo(&ci);
+ return ret;
+ }
+ if (ci.content) {
+ ret = der_copy_octet_string(ci.content, out);
+ if (ret) {
+ der_free_oid(oid);
+ free_ContentInfo(&ci);
+ return ret;
+ }
+ } else
+ memset(out, 0, sizeof(*out));
+
+ if (have_data)
+ *have_data = (ci.content != NULL) ? 1 : 0;
+
+ free_ContentInfo(&ci);
+
+ return 0;
+}
+
+#define CMS_ID_SKI 0
+#define CMS_ID_NAME 1
+
+static int
+fill_CMSIdentifier(const hx509_cert cert,
+ int type,
+ CMSIdentifier *id)
+{
+ int ret;
+
+ switch (type) {
+ case CMS_ID_SKI:
+ id->element = choice_CMSIdentifier_subjectKeyIdentifier;
+ ret = _hx509_find_extension_subject_key_id(_hx509_get_cert(cert),
+ &id->u.subjectKeyIdentifier);
+ if (ret == 0)
+ break;
+ fallthrough;
+ case CMS_ID_NAME: {
+ hx509_name name;
+
+ id->element = choice_CMSIdentifier_issuerAndSerialNumber;
+ ret = hx509_cert_get_issuer(cert, &name);
+ if (ret)
+ return ret;
+ ret = hx509_name_to_Name(name, &id->u.issuerAndSerialNumber.issuer);
+ hx509_name_free(&name);
+ if (ret)
+ return ret;
+
+ ret = hx509_cert_get_serialnumber(cert, &id->u.issuerAndSerialNumber.serialNumber);
+ break;
+ }
+ default:
+ _hx509_abort("CMS fill identifier with unknown type");
+ }
+ return ret;
+}
+
+static int
+unparse_CMSIdentifier(hx509_context context,
+ CMSIdentifier *id,
+ char **str)
+{
+ int ret = -1;
+
+ *str = NULL;
+ switch (id->element) {
+ case choice_CMSIdentifier_issuerAndSerialNumber: {
+ IssuerAndSerialNumber *iasn;
+ char *serial, *name;
+
+ iasn = &id->u.issuerAndSerialNumber;
+
+ ret = _hx509_Name_to_string(&iasn->issuer, &name);
+ if(ret)
+ return ret;
+ ret = der_print_hex_heim_integer(&iasn->serialNumber, &serial);
+ if (ret) {
+ free(name);
+ return ret;
+ }
+ ret = asprintf(str, "certificate issued by %s with serial number %s",
+ name, serial);
+ free(name);
+ free(serial);
+ break;
+ }
+ case choice_CMSIdentifier_subjectKeyIdentifier: {
+ KeyIdentifier *ki = &id->u.subjectKeyIdentifier;
+ char *keyid;
+ ssize_t len;
+
+ len = hex_encode(ki->data, ki->length, &keyid);
+ if (len < 0)
+ return ENOMEM;
+
+ ret = asprintf(str, "certificate with id %s", keyid);
+ free(keyid);
+ break;
+ }
+ default:
+ ret = asprintf(str, "certificate have unknown CMSidentifier type");
+ break;
+ }
+ /*
+ * In the following if, we check ret and *str which should be returned/set
+ * by asprintf(3) in every branch of the switch statement.
+ */
+ if (ret == -1 || *str == NULL)
+ return ENOMEM;
+ return 0;
+}
+
+static int
+find_CMSIdentifier(hx509_context context,
+ CMSIdentifier *client,
+ hx509_certs certs,
+ time_t time_now,
+ hx509_cert *signer_cert,
+ int match)
+{
+ hx509_query q;
+ hx509_cert cert;
+ Certificate c;
+ int ret;
+
+ memset(&c, 0, sizeof(c));
+ _hx509_query_clear(&q);
+
+ *signer_cert = NULL;
+
+ switch (client->element) {
+ case choice_CMSIdentifier_issuerAndSerialNumber:
+ q.serial = &client->u.issuerAndSerialNumber.serialNumber;
+ q.issuer_name = &client->u.issuerAndSerialNumber.issuer;
+ q.match = HX509_QUERY_MATCH_SERIALNUMBER|HX509_QUERY_MATCH_ISSUER_NAME;
+ break;
+ case choice_CMSIdentifier_subjectKeyIdentifier:
+ q.subject_id = &client->u.subjectKeyIdentifier;
+ q.match = HX509_QUERY_MATCH_SUBJECT_KEY_ID;
+ break;
+ default:
+ hx509_set_error_string(context, 0, HX509_CMS_NO_RECIPIENT_CERTIFICATE,
+ "unknown CMS identifier element");
+ return HX509_CMS_NO_RECIPIENT_CERTIFICATE;
+ }
+
+ q.match |= match;
+
+ q.match |= HX509_QUERY_MATCH_TIME;
+ if (time_now)
+ q.timenow = time_now;
+ else
+ q.timenow = time(NULL);
+
+ ret = hx509_certs_find(context, certs, &q, &cert);
+ if (ret == HX509_CERT_NOT_FOUND) {
+ char *str;
+
+ ret = unparse_CMSIdentifier(context, client, &str);
+ if (ret == 0) {
+ hx509_set_error_string(context, 0,
+ HX509_CMS_NO_RECIPIENT_CERTIFICATE,
+ "Failed to find %s", str);
+ } else
+ hx509_clear_error_string(context);
+ return HX509_CMS_NO_RECIPIENT_CERTIFICATE;
+ } else if (ret) {
+ hx509_set_error_string(context, HX509_ERROR_APPEND,
+ HX509_CMS_NO_RECIPIENT_CERTIFICATE,
+ "Failed to find CMS id in cert store");
+ return HX509_CMS_NO_RECIPIENT_CERTIFICATE;
+ }
+
+ *signer_cert = cert;
+
+ return 0;
+}
+
+/**
+ * Decode and unencrypt EnvelopedData.
+ *
+ * Extract data and parameteres from from the EnvelopedData. Also
+ * supports using detached EnvelopedData.
+ *
+ * @param context A hx509 context.
+ * @param certs Certificate that can decrypt the EnvelopedData
+ * encryption key.
+ * @param flags HX509_CMS_UE flags to control the behavior.
+ * @param data pointer the structure the contains the DER/BER encoded
+ * EnvelopedData stucture.
+ * @param length length of the data that data point to.
+ * @param encryptedContent in case of detached signature, this
+ * contains the actual encrypted data, othersize its should be NULL.
+ * @param time_now set the current time, if zero the library uses now as the date.
+ * @param contentType output type oid, should be freed with der_free_oid().
+ * @param content the data, free with der_free_octet_string().
+ *
+ * @return an hx509 error code.
+ *
+ * @ingroup hx509_cms
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cms_unenvelope(hx509_context context,
+ hx509_certs certs,
+ int flags,
+ const void *data,
+ size_t length,
+ const heim_octet_string *encryptedContent,
+ time_t time_now,
+ heim_oid *contentType,
+ heim_octet_string *content)
+{
+ heim_octet_string key;
+ EnvelopedData ed;
+ hx509_cert cert;
+ AlgorithmIdentifier *ai;
+ const heim_octet_string *enccontent;
+ heim_octet_string *params, params_data;
+ heim_octet_string ivec;
+ size_t size;
+ int ret, matched = 0, findflags = 0;
+ size_t i;
+
+
+ memset(&key, 0, sizeof(key));
+ memset(&ed, 0, sizeof(ed));
+ memset(&ivec, 0, sizeof(ivec));
+ memset(content, 0, sizeof(*content));
+ memset(contentType, 0, sizeof(*contentType));
+
+ if ((flags & HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT) == 0)
+ findflags |= HX509_QUERY_KU_ENCIPHERMENT;
+
+ ret = decode_EnvelopedData(data, length, &ed, &size);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to decode EnvelopedData");
+ return ret;
+ }
+
+ if (ed.recipientInfos.len == 0) {
+ ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE;
+ hx509_set_error_string(context, 0, ret,
+ "No recipient info in enveloped data");
+ goto out;
+ }
+
+ enccontent = ed.encryptedContentInfo.encryptedContent;
+ if (enccontent == NULL) {
+ if (encryptedContent == NULL) {
+ ret = HX509_CMS_NO_DATA_AVAILABLE;
+ hx509_set_error_string(context, 0, ret,
+ "Content missing from encrypted data");
+ goto out;
+ }
+ enccontent = encryptedContent;
+ } else if (encryptedContent != NULL) {
+ ret = HX509_CMS_NO_DATA_AVAILABLE;
+ hx509_set_error_string(context, 0, ret,
+ "Both internal and external encrypted data");
+ goto out;
+ }
+
+ cert = NULL;
+ for (i = 0; i < ed.recipientInfos.len; i++) {
+ KeyTransRecipientInfo *ri;
+ char *str;
+ int ret2;
+
+ ri = &ed.recipientInfos.val[i];
+
+ ret = find_CMSIdentifier(context, &ri->rid, certs,
+ time_now, &cert,
+ HX509_QUERY_PRIVATE_KEY|findflags);
+ if (ret)
+ continue;
+
+ matched = 1; /* found a matching certificate, let decrypt */
+
+ ret = _hx509_cert_private_decrypt(context,
+ &ri->encryptedKey,
+ &ri->keyEncryptionAlgorithm.algorithm,
+ cert, &key);
+
+ hx509_cert_free(cert);
+ if (ret == 0)
+ break; /* succuessfully decrypted cert */
+ cert = NULL;
+ ret2 = unparse_CMSIdentifier(context, &ri->rid, &str);
+ if (ret2 == 0) {
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "Failed to decrypt with %s", str);
+ free(str);
+ }
+ }
+
+ if (!matched) {
+ ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE;
+ hx509_set_error_string(context, 0, ret,
+ "No private key matched any certificate");
+ goto out;
+ }
+
+ if (cert == NULL) {
+ ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE;
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "No private key decrypted the transfer key");
+ goto out;
+ }
+
+ ret = der_copy_oid(&ed.encryptedContentInfo.contentType, contentType);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to copy EnvelopedData content oid");
+ goto out;
+ }
+
+ ai = &ed.encryptedContentInfo.contentEncryptionAlgorithm;
+ if (ai->parameters) {
+ params_data.data = ai->parameters->data;
+ params_data.length = ai->parameters->length;
+ params = &params_data;
+ } else
+ params = NULL;
+
+ {
+ hx509_crypto crypto;
+
+ ret = hx509_crypto_init(context, NULL, &ai->algorithm, &crypto);
+ if (ret)
+ goto out;
+
+ if (flags & HX509_CMS_UE_ALLOW_WEAK)
+ hx509_crypto_allow_weak(crypto);
+
+ if (params) {
+ ret = hx509_crypto_set_params(context, crypto, params, &ivec);
+ if (ret) {
+ hx509_crypto_destroy(crypto);
+ goto out;
+ }
+ }
+
+ ret = hx509_crypto_set_key_data(crypto, key.data, key.length);
+ if (ret) {
+ hx509_crypto_destroy(crypto);
+ hx509_set_error_string(context, 0, ret,
+ "Failed to set key for decryption "
+ "of EnvelopedData");
+ goto out;
+ }
+
+ ret = hx509_crypto_decrypt(crypto,
+ enccontent->data,
+ enccontent->length,
+ ivec.length ? &ivec : NULL,
+ content);
+ hx509_crypto_destroy(crypto);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to decrypt EnvelopedData");
+ goto out;
+ }
+ }
+
+out:
+
+ free_EnvelopedData(&ed);
+ der_free_octet_string(&key);
+ if (ivec.length)
+ der_free_octet_string(&ivec);
+ if (ret) {
+ der_free_oid(contentType);
+ der_free_octet_string(content);
+ }
+
+ return ret;
+}
+
+/**
+ * Encrypt end encode EnvelopedData.
+ *
+ * Encrypt and encode EnvelopedData. The data is encrypted with a
+ * random key and the the random key is encrypted with the
+ * certificates private key. This limits what private key type can be
+ * used to RSA.
+ *
+ * @param context A hx509 context.
+ * @param flags flags to control the behavior.
+ * - HX509_CMS_EV_NO_KU_CHECK - Don't check KU on certificate
+ * - HX509_CMS_EV_ALLOW_WEAK - Allow weak crytpo
+ * - HX509_CMS_EV_ID_NAME - prefer issuer name and serial number
+ * @param cert Certificate to encrypt the EnvelopedData encryption key
+ * with.
+ * @param data pointer the data to encrypt.
+ * @param length length of the data that data point to.
+ * @param encryption_type Encryption cipher to use for the bulk data,
+ * use NULL to get default.
+ * @param contentType type of the data that is encrypted
+ * @param content the output of the function,
+ * free with der_free_octet_string().
+ *
+ * @return an hx509 error code.
+ *
+ * @ingroup hx509_cms
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cms_envelope_1(hx509_context context,
+ int flags,
+ hx509_cert cert,
+ const void *data,
+ size_t length,
+ const heim_oid *encryption_type,
+ const heim_oid *contentType,
+ heim_octet_string *content)
+{
+ KeyTransRecipientInfo *ri;
+ heim_octet_string ivec;
+ heim_octet_string key;
+ hx509_crypto crypto = NULL;
+ int ret, cmsidflag;
+ EnvelopedData ed;
+ size_t size;
+
+ memset(&ivec, 0, sizeof(ivec));
+ memset(&key, 0, sizeof(key));
+ memset(&ed, 0, sizeof(ed));
+ memset(content, 0, sizeof(*content));
+
+ if (encryption_type == NULL)
+ encryption_type = &asn1_oid_id_aes_256_cbc;
+
+ if ((flags & HX509_CMS_EV_NO_KU_CHECK) == 0) {
+ ret = _hx509_check_key_usage(context, cert, 1 << 2, TRUE);
+ if (ret)
+ goto out;
+ }
+
+ ret = hx509_crypto_init(context, NULL, encryption_type, &crypto);
+ if (ret)
+ goto out;
+
+ if (flags & HX509_CMS_EV_ALLOW_WEAK)
+ hx509_crypto_allow_weak(crypto);
+
+ ret = hx509_crypto_set_random_key(crypto, &key);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Create random key for EnvelopedData content");
+ goto out;
+ }
+
+ ret = hx509_crypto_random_iv(crypto, &ivec);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to create a random iv");
+ goto out;
+ }
+
+ ret = hx509_crypto_encrypt(crypto,
+ data,
+ length,
+ &ivec,
+ &ed.encryptedContentInfo.encryptedContent);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to encrypt EnvelopedData content");
+ goto out;
+ }
+
+ {
+ AlgorithmIdentifier *enc_alg;
+ enc_alg = &ed.encryptedContentInfo.contentEncryptionAlgorithm;
+ ret = der_copy_oid(encryption_type, &enc_alg->algorithm);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to set crypto oid "
+ "for EnvelopedData");
+ goto out;
+ }
+ ALLOC(enc_alg->parameters, 1);
+ if (enc_alg->parameters == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret,
+ "Failed to allocate crypto parameters "
+ "for EnvelopedData");
+ goto out;
+ }
+
+ ret = hx509_crypto_get_params(context,
+ crypto,
+ &ivec,
+ enc_alg->parameters);
+ if (ret) {
+ goto out;
+ }
+ }
+
+ ALLOC_SEQ(&ed.recipientInfos, 1);
+ if (ed.recipientInfos.val == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret,
+ "Failed to allocate recipients info "
+ "for EnvelopedData");
+ goto out;
+ }
+
+ ri = &ed.recipientInfos.val[0];
+
+ if (flags & HX509_CMS_EV_ID_NAME) {
+ ri->version = 0;
+ cmsidflag = CMS_ID_NAME;
+ } else {
+ ri->version = 2;
+ cmsidflag = CMS_ID_SKI;
+ }
+
+ ret = fill_CMSIdentifier(cert, cmsidflag, &ri->rid);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to set CMS identifier info "
+ "for EnvelopedData");
+ goto out;
+ }
+
+ ret = hx509_cert_public_encrypt(context,
+ &key, cert,
+ &ri->keyEncryptionAlgorithm.algorithm,
+ &ri->encryptedKey);
+ if (ret) {
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "Failed to encrypt transport key for "
+ "EnvelopedData");
+ goto out;
+ }
+
+ /*
+ *
+ */
+
+ ed.version = 0;
+ ed.originatorInfo = NULL;
+
+ ret = der_copy_oid(contentType, &ed.encryptedContentInfo.contentType);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to copy content oid for "
+ "EnvelopedData");
+ goto out;
+ }
+
+ ed.unprotectedAttrs = NULL;
+
+ ASN1_MALLOC_ENCODE(EnvelopedData, content->data, content->length,
+ &ed, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to encode EnvelopedData");
+ goto out;
+ }
+ if (size != content->length)
+ _hx509_abort("internal ASN.1 encoder error");
+
+out:
+ if (crypto)
+ hx509_crypto_destroy(crypto);
+ if (ret)
+ der_free_octet_string(content);
+ der_free_octet_string(&key);
+ der_free_octet_string(&ivec);
+ free_EnvelopedData(&ed);
+
+ return ret;
+}
+
+static int
+any_to_certs(hx509_context context, const SignedData *sd, hx509_certs certs)
+{
+ int ret;
+ size_t i;
+
+ if (sd->certificates == NULL)
+ return 0;
+
+ for (i = 0; i < sd->certificates->len; i++) {
+ heim_error_t error;
+ hx509_cert c;
+
+ c = hx509_cert_init_data(context,
+ sd->certificates->val[i].data,
+ sd->certificates->val[i].length,
+ &error);
+ if (c == NULL) {
+ ret = heim_error_get_code(error);
+ heim_release(error);
+ return ret;
+ }
+ ret = hx509_certs_add(context, certs, c);
+ hx509_cert_free(c);
+ if (ret)
+ return ret;
+ }
+
+ return 0;
+}
+
+static const Attribute *
+find_attribute(const CMSAttributes *attr, const heim_oid *oid)
+{
+ size_t i;
+ for (i = 0; i < attr->len; i++)
+ if (der_heim_oid_cmp(&attr->val[i].type, oid) == 0)
+ return &attr->val[i];
+ return NULL;
+}
+
+/**
+ * Decode SignedData and verify that the signature is correct.
+ *
+ * @param context A hx509 context.
+ * @param ctx a hx509 verify context.
+ * @param flags to control the behaivor of the function.
+ * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
+ * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
+ * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
+ * @param data pointer to CMS SignedData encoded data.
+ * @param length length of the data that data point to.
+ * @param signedContent external data used for signature.
+ * @param pool certificate pool to build certificates paths.
+ * @param contentType free with der_free_oid().
+ * @param content the output of the function, free with
+ * der_free_octet_string().
+ * @param signer_certs list of the cerficates used to sign this
+ * request, free with hx509_certs_free().
+ *
+ * @return an hx509 error code.
+ *
+ * @ingroup hx509_cms
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cms_verify_signed(hx509_context context,
+ hx509_verify_ctx ctx,
+ unsigned int flags,
+ const void *data,
+ size_t length,
+ const heim_octet_string *signedContent,
+ hx509_certs pool,
+ heim_oid *contentType,
+ heim_octet_string *content,
+ hx509_certs *signer_certs)
+{
+ unsigned int verify_flags;
+
+ return hx509_cms_verify_signed_ext(context,
+ ctx,
+ flags,
+ data,
+ length,
+ signedContent,
+ pool,
+ contentType,
+ content,
+ signer_certs,
+ &verify_flags);
+}
+
+/**
+ * Decode SignedData and verify that the signature is correct.
+ *
+ * @param context A hx509 context.
+ * @param ctx a hx509 verify context.
+ * @param flags to control the behaivor of the function.
+ * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
+ * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
+ * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
+ * @param data pointer to CMS SignedData encoded data.
+ * @param length length of the data that data point to.
+ * @param signedContent external data used for signature.
+ * @param pool certificate pool to build certificates paths.
+ * @param contentType free with der_free_oid().
+ * @param content the output of the function, free with
+ * der_free_octet_string().
+ * @param signer_certs list of the cerficates used to sign this
+ * request, free with hx509_certs_free().
+ * @param verify_flags flags indicating whether the certificate
+ * was verified or not
+ *
+ * @return an hx509 error code.
+ *
+ * @ingroup hx509_cms
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cms_verify_signed_ext(hx509_context context,
+ hx509_verify_ctx ctx,
+ unsigned int flags,
+ const void *data,
+ size_t length,
+ const heim_octet_string *signedContent,
+ hx509_certs pool,
+ heim_oid *contentType,
+ heim_octet_string *content,
+ hx509_certs *signer_certs,
+ unsigned int *verify_flags)
+{
+ SignerInfo *signer_info;
+ hx509_cert cert = NULL;
+ hx509_certs certs = NULL;
+ SignedData sd;
+ size_t size;
+ int ret, found_valid_sig;
+ size_t i;
+
+ *signer_certs = NULL;
+ *verify_flags = 0;
+
+ content->data = NULL;
+ content->length = 0;
+ contentType->length = 0;
+ contentType->components = NULL;
+
+ memset(&sd, 0, sizeof(sd));
+
+ ret = decode_SignedData(data, length, &sd, &size);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to decode SignedData");
+ goto out;
+ }
+
+ if (sd.encapContentInfo.eContent == NULL && signedContent == NULL) {
+ ret = HX509_CMS_NO_DATA_AVAILABLE;
+ hx509_set_error_string(context, 0, ret,
+ "No content data in SignedData");
+ goto out;
+ }
+ if (sd.encapContentInfo.eContent && signedContent) {
+ ret = HX509_CMS_NO_DATA_AVAILABLE;
+ hx509_set_error_string(context, 0, ret,
+ "Both external and internal SignedData");
+ goto out;
+ }
+
+ if (sd.encapContentInfo.eContent)
+ ret = der_copy_octet_string(sd.encapContentInfo.eContent, content);
+ else
+ ret = der_copy_octet_string(signedContent, content);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "malloc: out of memory");
+ goto out;
+ }
+
+ ret = hx509_certs_init(context, "MEMORY:cms-cert-buffer",
+ 0, NULL, &certs);
+ if (ret)
+ goto out;
+
+ ret = hx509_certs_init(context, "MEMORY:cms-signer-certs",
+ 0, NULL, signer_certs);
+ if (ret)
+ goto out;
+
+ /* XXX Check CMS version */
+
+ ret = any_to_certs(context, &sd, certs);
+ if (ret)
+ goto out;
+
+ if (pool) {
+ ret = hx509_certs_merge(context, certs, pool);
+ if (ret)
+ goto out;
+ }
+
+ for (found_valid_sig = 0, i = 0; i < sd.signerInfos.len; i++) {
+ heim_octet_string signed_data = { 0, 0 };
+ const heim_oid *match_oid;
+ heim_oid decode_oid;
+
+ signer_info = &sd.signerInfos.val[i];
+ match_oid = NULL;
+
+ if (signer_info->signature.length == 0) {
+ ret = HX509_CMS_MISSING_SIGNER_DATA;
+ hx509_set_error_string(context, 0, ret,
+ "SignerInfo %d in SignedData "
+ "missing sigature", i);
+ continue;
+ }
+
+ ret = find_CMSIdentifier(context, &signer_info->sid, certs,
+ _hx509_verify_get_time(ctx), &cert,
+ HX509_QUERY_KU_DIGITALSIGNATURE);
+ if (ret) {
+ /**
+ * If HX509_CMS_VS_NO_KU_CHECK is set, allow more liberal
+ * search for matching certificates by not considering
+ * KeyUsage bits on the certificates.
+ */
+ if ((flags & HX509_CMS_VS_NO_KU_CHECK) == 0)
+ continue;
+
+ ret = find_CMSIdentifier(context, &signer_info->sid, certs,
+ _hx509_verify_get_time(ctx), &cert,
+ 0);
+ if (ret)
+ continue;
+
+ }
+
+ if (signer_info->signedAttrs) {
+ const Attribute *attr;
+
+ CMSAttributes sa;
+ heim_octet_string os;
+
+ sa.val = signer_info->signedAttrs->val;
+ sa.len = signer_info->signedAttrs->len;
+
+ /* verify that sigature exists */
+ attr = find_attribute(&sa, &asn1_oid_id_pkcs9_messageDigest);
+ if (attr == NULL) {
+ ret = HX509_CRYPTO_SIGNATURE_MISSING;
+ hx509_set_error_string(context, 0, ret,
+ "SignerInfo have signed attributes "
+ "but messageDigest (signature) "
+ "is missing");
+ goto next_sigature;
+ }
+ if (attr->value.len != 1) {
+ ret = HX509_CRYPTO_SIGNATURE_MISSING;
+ hx509_set_error_string(context, 0, ret,
+ "SignerInfo have more then one "
+ "messageDigest (signature)");
+ goto next_sigature;
+ }
+
+ ret = decode_MessageDigest(attr->value.val[0].data,
+ attr->value.val[0].length,
+ &os,
+ &size);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to decode "
+ "messageDigest (signature)");
+ goto next_sigature;
+ }
+
+ ret = _hx509_verify_signature(context,
+ NULL,
+ &signer_info->digestAlgorithm,
+ content,
+ &os);
+ der_free_octet_string(&os);
+ if (ret) {
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "Failed to verify messageDigest");
+ goto next_sigature;
+ }
+
+ /*
+ * Fetch content oid inside signedAttrs or set it to
+ * id-pkcs7-data.
+ */
+ attr = find_attribute(&sa, &asn1_oid_id_pkcs9_contentType);
+ if (attr == NULL) {
+ match_oid = &asn1_oid_id_pkcs7_data;
+ } else {
+ if (attr->value.len != 1) {
+ ret = HX509_CMS_DATA_OID_MISMATCH;
+ hx509_set_error_string(context, 0, ret,
+ "More then one oid in signedAttrs");
+ goto next_sigature;
+
+ }
+ ret = decode_ContentType(attr->value.val[0].data,
+ attr->value.val[0].length,
+ &decode_oid,
+ &size);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to decode "
+ "oid in signedAttrs");
+ goto next_sigature;
+ }
+ match_oid = &decode_oid;
+ }
+
+ ASN1_MALLOC_ENCODE(CMSAttributes,
+ signed_data.data,
+ signed_data.length,
+ &sa,
+ &size, ret);
+ if (ret) {
+ if (match_oid == &decode_oid)
+ der_free_oid(&decode_oid);
+ hx509_clear_error_string(context);
+ goto next_sigature;
+ }
+ if (size != signed_data.length)
+ _hx509_abort("internal ASN.1 encoder error");
+
+ } else {
+ signed_data.data = content->data;
+ signed_data.length = content->length;
+ match_oid = &asn1_oid_id_pkcs7_data;
+ }
+
+ /**
+ * If HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH, allow
+ * encapContentInfo mismatch with the oid in signedAttributes
+ * (or if no signedAttributes where use, pkcs7-data oid).
+ * This is only needed to work with broken CMS implementations
+ * that doesn't follow CMS signedAttributes rules.
+ */
+
+ if (der_heim_oid_cmp(match_oid, &sd.encapContentInfo.eContentType) &&
+ (flags & HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH) == 0) {
+ ret = HX509_CMS_DATA_OID_MISMATCH;
+ hx509_set_error_string(context, 0, ret,
+ "Oid in message mismatch from the expected");
+ }
+ if (match_oid == &decode_oid)
+ der_free_oid(&decode_oid);
+
+ if (ret == 0) {
+ ret = hx509_verify_signature(context,
+ cert,
+ &signer_info->signatureAlgorithm,
+ &signed_data,
+ &signer_info->signature);
+ if (ret)
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "Failed to verify signature in "
+ "CMS SignedData");
+ }
+ if (signed_data.data != NULL && content->data != signed_data.data) {
+ free(signed_data.data);
+ signed_data.data = NULL;
+ }
+ if (ret)
+ goto next_sigature;
+
+ /**
+ * If HX509_CMS_VS_NO_VALIDATE flags is set, return the signer
+ * certificate unconditionally but do not set HX509_CMS_VSE_VALIDATED.
+ */
+ ret = hx509_verify_path(context, ctx, cert, certs);
+ if (ret == 0 || (flags & HX509_CMS_VS_NO_VALIDATE)) {
+ if (ret == 0)
+ *verify_flags |= HX509_CMS_VSE_VALIDATED;
+
+ ret = hx509_certs_add(context, *signer_certs, cert);
+ if (ret == 0)
+ found_valid_sig++;
+ }
+
+ next_sigature:
+ if (cert)
+ hx509_cert_free(cert);
+ cert = NULL;
+ }
+ /**
+ * If HX509_CMS_VS_ALLOW_ZERO_SIGNER is set, allow empty
+ * SignerInfo (no signatures). If SignedData have no signatures,
+ * the function will return 0 with signer_certs set to NULL. Zero
+ * signers is allowed by the standard, but since its only useful
+ * in corner cases, it make into a flag that the caller have to
+ * turn on.
+ */
+ if (sd.signerInfos.len == 0 && (flags & HX509_CMS_VS_ALLOW_ZERO_SIGNER)) {
+ if (*signer_certs)
+ hx509_certs_free(signer_certs);
+ } else if (found_valid_sig == 0) {
+ if (ret == 0) {
+ ret = HX509_CMS_SIGNER_NOT_FOUND;
+ hx509_set_error_string(context, 0, ret,
+ "No signers where found");
+ }
+ goto out;
+ }
+
+ ret = der_copy_oid(&sd.encapContentInfo.eContentType, contentType);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+
+out:
+ free_SignedData(&sd);
+ if (certs)
+ hx509_certs_free(&certs);
+ if (ret) {
+ if (content->data)
+ der_free_octet_string(content);
+ if (*signer_certs)
+ hx509_certs_free(signer_certs);
+ der_free_oid(contentType);
+ der_free_octet_string(content);
+ }
+
+ return ret;
+}
+
+static int
+add_one_attribute(Attribute **attr,
+ unsigned int *len,
+ const heim_oid *oid,
+ heim_octet_string *data)
+{
+ void *d;
+ int ret;
+
+ d = realloc(*attr, sizeof((*attr)[0]) * (*len + 1));
+ if (d == NULL)
+ return ENOMEM;
+ (*attr) = d;
+
+ ret = der_copy_oid(oid, &(*attr)[*len].type);
+ if (ret)
+ return ret;
+
+ ALLOC_SEQ(&(*attr)[*len].value, 1);
+ if ((*attr)[*len].value.val == NULL) {
+ der_free_oid(&(*attr)[*len].type);
+ return ENOMEM;
+ }
+
+ (*attr)[*len].value.val[0].data = data->data;
+ (*attr)[*len].value.val[0].length = data->length;
+
+ *len += 1;
+
+ return 0;
+}
+
+/**
+ * Decode SignedData and verify that the signature is correct.
+ *
+ * @param context A hx509 context.
+ * @param flags
+ * @param eContentType the type of the data.
+ * @param data data to sign
+ * @param length length of the data that data point to.
+ * @param digest_alg digest algorithm to use, use NULL to get the
+ * default or the peer determined algorithm.
+ * @param cert certificate to use for sign the data.
+ * @param peer info about the peer the message to send the message to,
+ * like what digest algorithm to use.
+ * @param anchors trust anchors that the client will use, used to
+ * polulate the certificates included in the message
+ * @param pool certificates to use in try to build the path to the
+ * trust anchors.
+ * @param signed_data the output of the function, free with
+ * der_free_octet_string().
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_cms
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cms_create_signed_1(hx509_context context,
+ int flags,
+ const heim_oid *eContentType,
+ const void *data, size_t length,
+ const AlgorithmIdentifier *digest_alg,
+ hx509_cert cert,
+ hx509_peer_info peer,
+ hx509_certs anchors,
+ hx509_certs pool,
+ heim_octet_string *signed_data)
+{
+ hx509_certs certs;
+ int ret = 0;
+
+ signed_data->data = NULL;
+ signed_data->length = 0;
+
+ ret = hx509_certs_init(context, "MEMORY:certs", 0, NULL, &certs);
+ if (ret)
+ return ret;
+ ret = hx509_certs_add(context, certs, cert);
+ if (ret)
+ goto out;
+
+ ret = hx509_cms_create_signed(context, flags, eContentType, data, length,
+ digest_alg, certs, peer, anchors, pool,
+ signed_data);
+
+ out:
+ hx509_certs_free(&certs);
+ return ret;
+}
+
+struct sigctx {
+ SignedData sd;
+ const AlgorithmIdentifier *digest_alg;
+ const heim_oid *eContentType;
+ heim_octet_string content;
+ hx509_peer_info peer;
+ int cmsidflag;
+ int leafonly;
+ hx509_certs certs;
+ hx509_certs anchors;
+ hx509_certs pool;
+};
+
+static int HX509_LIB_CALL
+sig_process(hx509_context context, void *ctx, hx509_cert cert)
+{
+ struct sigctx *sigctx = ctx;
+ heim_octet_string buf, sigdata = { 0, NULL };
+ SignerInfo *signer_info = NULL;
+ AlgorithmIdentifier digest;
+ size_t size;
+ void *ptr;
+ int ret;
+ SignedData *sd = &sigctx->sd;
+ hx509_path path;
+
+ memset(&digest, 0, sizeof(digest));
+ memset(&path, 0, sizeof(path));
+
+ if (_hx509_cert_private_key(cert) == NULL) {
+ hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING,
+ "Private key missing for signing");
+ return HX509_PRIVATE_KEY_MISSING;
+ }
+
+ if (sigctx->digest_alg) {
+ ret = copy_AlgorithmIdentifier(sigctx->digest_alg, &digest);
+ if (ret)
+ hx509_clear_error_string(context);
+ } else {
+ ret = hx509_crypto_select(context, HX509_SELECT_DIGEST,
+ _hx509_cert_private_key(cert),
+ sigctx->peer, &digest);
+ }
+ if (ret)
+ goto out;
+
+ /*
+ * Allocate on more signerInfo and do the signature processing
+ */
+
+ ptr = realloc(sd->signerInfos.val,
+ (sd->signerInfos.len + 1) * sizeof(sd->signerInfos.val[0]));
+ if (ptr == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ sd->signerInfos.val = ptr;
+
+ signer_info = &sd->signerInfos.val[sd->signerInfos.len];
+
+ memset(signer_info, 0, sizeof(*signer_info));
+
+ signer_info->version = 1;
+
+ ret = fill_CMSIdentifier(cert, sigctx->cmsidflag, &signer_info->sid);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+
+ signer_info->signedAttrs = NULL;
+ signer_info->unsignedAttrs = NULL;
+
+ ret = copy_AlgorithmIdentifier(&digest, &signer_info->digestAlgorithm);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+
+ /*
+ * If it isn't pkcs7-data send signedAttributes
+ */
+
+ if (der_heim_oid_cmp(sigctx->eContentType, &asn1_oid_id_pkcs7_data) != 0) {
+ CMSAttributes sa;
+ heim_octet_string sig;
+
+ ALLOC(signer_info->signedAttrs, 1);
+ if (signer_info->signedAttrs == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ ret = _hx509_create_signature(context,
+ NULL,
+ &digest,
+ &sigctx->content,
+ NULL,
+ &sig);
+ if (ret)
+ goto out;
+
+ ASN1_MALLOC_ENCODE(MessageDigest,
+ buf.data,
+ buf.length,
+ &sig,
+ &size,
+ ret);
+ der_free_octet_string(&sig);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ if (size != buf.length)
+ _hx509_abort("internal ASN.1 encoder error");
+
+ ret = add_one_attribute(&signer_info->signedAttrs->val,
+ &signer_info->signedAttrs->len,
+ &asn1_oid_id_pkcs9_messageDigest,
+ &buf);
+ if (ret) {
+ free(buf.data);
+ hx509_clear_error_string(context);
+ goto out;
+ }
+
+
+ ASN1_MALLOC_ENCODE(ContentType,
+ buf.data,
+ buf.length,
+ sigctx->eContentType,
+ &size,
+ ret);
+ if (ret)
+ goto out;
+ if (size != buf.length)
+ _hx509_abort("internal ASN.1 encoder error");
+
+ ret = add_one_attribute(&signer_info->signedAttrs->val,
+ &signer_info->signedAttrs->len,
+ &asn1_oid_id_pkcs9_contentType,
+ &buf);
+ if (ret) {
+ free(buf.data);
+ hx509_clear_error_string(context);
+ goto out;
+ }
+
+ sa.val = signer_info->signedAttrs->val;
+ sa.len = signer_info->signedAttrs->len;
+
+ ASN1_MALLOC_ENCODE(CMSAttributes,
+ sigdata.data,
+ sigdata.length,
+ &sa,
+ &size,
+ ret);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ if (size != sigdata.length)
+ _hx509_abort("internal ASN.1 encoder error");
+ } else {
+ sigdata.data = sigctx->content.data;
+ sigdata.length = sigctx->content.length;
+ }
+
+ {
+ AlgorithmIdentifier sigalg;
+
+ ret = hx509_crypto_select(context, HX509_SELECT_PUBLIC_SIG,
+ _hx509_cert_private_key(cert), sigctx->peer,
+ &sigalg);
+ if (ret)
+ goto out;
+
+ ret = _hx509_create_signature(context,
+ _hx509_cert_private_key(cert),
+ &sigalg,
+ &sigdata,
+ &signer_info->signatureAlgorithm,
+ &signer_info->signature);
+ free_AlgorithmIdentifier(&sigalg);
+ if (ret)
+ goto out;
+ }
+
+ sigctx->sd.signerInfos.len++;
+ signer_info = NULL;
+
+ /*
+ * Provide best effort path
+ */
+ if (sigctx->certs) {
+ unsigned int i;
+
+ if (sigctx->pool && sigctx->leafonly == 0) {
+ _hx509_calculate_path(context,
+ HX509_CALCULATE_PATH_NO_ANCHOR,
+ time(NULL),
+ sigctx->anchors,
+ 0,
+ cert,
+ sigctx->pool,
+ &path);
+ } else
+ _hx509_path_append(context, &path, cert);
+
+ for (i = 0; i < path.len; i++) {
+ /* XXX remove dups */
+ ret = hx509_certs_add(context, sigctx->certs, path.val[i]);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ }
+ }
+
+ out:
+ if (signer_info)
+ free_SignerInfo(signer_info);
+ if (sigdata.data != sigctx->content.data)
+ der_free_octet_string(&sigdata);
+ _hx509_path_free(&path);
+ free_AlgorithmIdentifier(&digest);
+
+ return ret;
+}
+
+static int HX509_LIB_CALL
+cert_process(hx509_context context, void *ctx, hx509_cert cert)
+{
+ struct sigctx *sigctx = ctx;
+ const unsigned int i = sigctx->sd.certificates->len;
+ void *ptr;
+ int ret;
+
+ ptr = realloc(sigctx->sd.certificates->val,
+ (i + 1) * sizeof(sigctx->sd.certificates->val[0]));
+ if (ptr == NULL)
+ return ENOMEM;
+ sigctx->sd.certificates->val = ptr;
+
+ ret = hx509_cert_binary(context, cert,
+ &sigctx->sd.certificates->val[i]);
+ if (ret == 0)
+ sigctx->sd.certificates->len++;
+
+ return ret;
+}
+
+static int
+cmp_AlgorithmIdentifier(const AlgorithmIdentifier *p, const AlgorithmIdentifier *q)
+{
+ return der_heim_oid_cmp(&p->algorithm, &q->algorithm);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cms_create_signed(hx509_context context,
+ int flags,
+ const heim_oid *eContentType,
+ const void *data, size_t length,
+ const AlgorithmIdentifier *digest_alg,
+ hx509_certs certs,
+ hx509_peer_info peer,
+ hx509_certs anchors,
+ hx509_certs pool,
+ heim_octet_string *signed_data)
+{
+ unsigned int i, j;
+ hx509_name name;
+ int ret;
+ size_t size;
+ struct sigctx sigctx;
+
+ memset(&sigctx, 0, sizeof(sigctx));
+ memset(&name, 0, sizeof(name));
+
+ if (eContentType == NULL)
+ eContentType = &asn1_oid_id_pkcs7_data;
+
+ sigctx.digest_alg = digest_alg;
+ sigctx.content.data = rk_UNCONST(data);
+ sigctx.content.length = length;
+ sigctx.eContentType = eContentType;
+ sigctx.peer = peer;
+ /**
+ * Use HX509_CMS_SIGNATURE_ID_NAME to preferred use of issuer name
+ * and serial number if possible. Otherwise subject key identifier
+ * will preferred.
+ */
+ if (flags & HX509_CMS_SIGNATURE_ID_NAME)
+ sigctx.cmsidflag = CMS_ID_NAME;
+ else
+ sigctx.cmsidflag = CMS_ID_SKI;
+
+ /**
+ * Use HX509_CMS_SIGNATURE_LEAF_ONLY to only request leaf
+ * certificates to be added to the SignedData.
+ */
+ sigctx.leafonly = (flags & HX509_CMS_SIGNATURE_LEAF_ONLY) ? 1 : 0;
+
+ /**
+ * Use HX509_CMS_NO_CERTS to make the SignedData contain no
+ * certificates, overrides HX509_CMS_SIGNATURE_LEAF_ONLY.
+ */
+
+ if ((flags & HX509_CMS_SIGNATURE_NO_CERTS) == 0) {
+ ret = hx509_certs_init(context, "MEMORY:certs", 0, NULL, &sigctx.certs);
+ if (ret)
+ return ret;
+ }
+
+ sigctx.anchors = anchors;
+ sigctx.pool = pool;
+
+ sigctx.sd.version = cMSVersion_v3;
+
+ ret = der_copy_oid(eContentType, &sigctx.sd.encapContentInfo.eContentType);
+ if (ret)
+ goto out;
+
+ /**
+ * Use HX509_CMS_SIGNATURE_DETACHED to create detached signatures.
+ */
+ if ((flags & HX509_CMS_SIGNATURE_DETACHED) == 0) {
+ ALLOC(sigctx.sd.encapContentInfo.eContent, 1);
+ if (sigctx.sd.encapContentInfo.eContent == NULL) {
+ hx509_clear_error_string(context);
+ ret = ENOMEM;
+ goto out;
+ }
+
+ sigctx.sd.encapContentInfo.eContent->data = malloc(length);
+ if (sigctx.sd.encapContentInfo.eContent->data == NULL) {
+ hx509_clear_error_string(context);
+ ret = ENOMEM;
+ goto out;
+ }
+ memcpy(sigctx.sd.encapContentInfo.eContent->data, data, length);
+ sigctx.sd.encapContentInfo.eContent->length = length;
+ }
+
+ /**
+ * Use HX509_CMS_SIGNATURE_NO_SIGNER to create no sigInfo (no
+ * signatures).
+ */
+ if ((flags & HX509_CMS_SIGNATURE_NO_SIGNER) == 0) {
+ ret = hx509_certs_iter_f(context, certs, sig_process, &sigctx);
+ if (ret)
+ goto out;
+ }
+
+ if (sigctx.sd.signerInfos.len) {
+
+ /*
+ * For each signerInfo, collect all different digest types.
+ */
+ for (i = 0; i < sigctx.sd.signerInfos.len; i++) {
+ AlgorithmIdentifier *di =
+ &sigctx.sd.signerInfos.val[i].digestAlgorithm;
+
+ for (j = 0; j < sigctx.sd.digestAlgorithms.len; j++)
+ if (cmp_AlgorithmIdentifier(di, &sigctx.sd.digestAlgorithms.val[j]) == 0)
+ break;
+ if (j == sigctx.sd.digestAlgorithms.len) {
+ ret = add_DigestAlgorithmIdentifiers(&sigctx.sd.digestAlgorithms, di);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ }
+ }
+ }
+
+ /*
+ * Add certs we think are needed, build as part of sig_process
+ */
+ if (sigctx.certs) {
+ ALLOC(sigctx.sd.certificates, 1);
+ if (sigctx.sd.certificates == NULL) {
+ hx509_clear_error_string(context);
+ ret = ENOMEM;
+ goto out;
+ }
+
+ ret = hx509_certs_iter_f(context, sigctx.certs, cert_process, &sigctx);
+ if (ret)
+ goto out;
+ }
+
+ ASN1_MALLOC_ENCODE(SignedData,
+ signed_data->data, signed_data->length,
+ &sigctx.sd, &size, ret);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ if (signed_data->length != size)
+ _hx509_abort("internal ASN.1 encoder error");
+
+out:
+ hx509_certs_free(&sigctx.certs);
+ free_SignedData(&sigctx.sd);
+
+ return ret;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cms_decrypt_encrypted(hx509_context context,
+ hx509_lock lock,
+ const void *data,
+ size_t length,
+ heim_oid *contentType,
+ heim_octet_string *content)
+{
+ heim_octet_string cont;
+ CMSEncryptedData ed;
+ AlgorithmIdentifier *ai;
+ int ret;
+
+ memset(content, 0, sizeof(*content));
+ memset(&cont, 0, sizeof(cont));
+
+ ret = decode_CMSEncryptedData(data, length, &ed, NULL);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to decode CMSEncryptedData");
+ return ret;
+ }
+
+ if (ed.encryptedContentInfo.encryptedContent == NULL) {
+ ret = HX509_CMS_NO_DATA_AVAILABLE;
+ hx509_set_error_string(context, 0, ret,
+ "No content in EncryptedData");
+ goto out;
+ }
+
+ ret = der_copy_oid(&ed.encryptedContentInfo.contentType, contentType);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+
+ ai = &ed.encryptedContentInfo.contentEncryptionAlgorithm;
+ if (ai->parameters == NULL) {
+ ret = HX509_ALG_NOT_SUPP;
+ hx509_clear_error_string(context);
+ goto out;
+ }
+
+ ret = _hx509_pbe_decrypt(context,
+ lock,
+ ai,
+ ed.encryptedContentInfo.encryptedContent,
+ &cont);
+ if (ret)
+ goto out;
+
+ *content = cont;
+
+out:
+ if (ret) {
+ if (cont.data)
+ free(cont.data);
+ }
+ free_CMSEncryptedData(&ed);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/hx509/collector.c b/third_party/heimdal/lib/hx509/collector.c
new file mode 100644
index 0000000..7b46809
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/collector.c
@@ -0,0 +1,331 @@
+/*
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+struct private_key {
+ AlgorithmIdentifier alg;
+ hx509_private_key private_key;
+ heim_octet_string localKeyId;
+};
+
+struct hx509_collector {
+ hx509_lock lock;
+ hx509_certs unenvelop_certs;
+ hx509_certs certs;
+ struct {
+ struct private_key **data;
+ size_t len;
+ } val;
+};
+
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_collector_alloc(hx509_context context, hx509_lock lock, struct hx509_collector **collector)
+{
+ struct hx509_collector *c;
+ int ret;
+
+ *collector = NULL;
+
+ c = calloc(1, sizeof(*c));
+ if (c == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+ c->lock = lock;
+
+ ret = hx509_certs_init(context, "MEMORY:collector-unenvelop-cert",
+ 0,NULL, &c->unenvelop_certs);
+ if (ret) {
+ free(c);
+ return ret;
+ }
+ c->val.data = NULL;
+ c->val.len = 0;
+ ret = hx509_certs_init(context, "MEMORY:collector-tmp-store",
+ 0, NULL, &c->certs);
+ if (ret) {
+ hx509_certs_free(&c->unenvelop_certs);
+ free(c);
+ return ret;
+ }
+
+ *collector = c;
+ return 0;
+}
+
+HX509_LIB_FUNCTION hx509_lock HX509_LIB_CALL
+_hx509_collector_get_lock(struct hx509_collector *c)
+{
+ return c->lock;
+}
+
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_collector_certs_add(hx509_context context,
+ struct hx509_collector *c,
+ hx509_cert cert)
+{
+ return hx509_certs_add(context, c->certs, cert);
+}
+
+static void
+free_private_key(struct private_key *key)
+{
+ free_AlgorithmIdentifier(&key->alg);
+ if (key->private_key)
+ hx509_private_key_free(&key->private_key);
+ der_free_octet_string(&key->localKeyId);
+ free(key);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_collector_private_key_add(hx509_context context,
+ struct hx509_collector *c,
+ const AlgorithmIdentifier *alg,
+ hx509_private_key private_key,
+ const heim_octet_string *key_data,
+ const heim_octet_string *localKeyId)
+{
+ struct private_key *key;
+ void *d;
+ int ret;
+
+ key = calloc(1, sizeof(*key));
+ if (key == NULL)
+ return ENOMEM;
+
+ d = realloc(c->val.data, (c->val.len + 1) * sizeof(c->val.data[0]));
+ if (d == NULL) {
+ free(key);
+ hx509_set_error_string(context, 0, ENOMEM, "Out of memory");
+ return ENOMEM;
+ }
+ c->val.data = d;
+
+ ret = copy_AlgorithmIdentifier(alg, &key->alg);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Failed to copy "
+ "AlgorithmIdentifier");
+ goto out;
+ }
+ if (private_key) {
+ key->private_key = private_key;
+ } else {
+ ret = hx509_parse_private_key(context, alg,
+ key_data->data, key_data->length,
+ HX509_KEY_FORMAT_DER,
+ &key->private_key);
+ if (ret)
+ goto out;
+ }
+ if (localKeyId) {
+ ret = der_copy_octet_string(localKeyId, &key->localKeyId);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to copy localKeyId");
+ goto out;
+ }
+ } else
+ memset(&key->localKeyId, 0, sizeof(key->localKeyId));
+
+ c->val.data[c->val.len] = key;
+ c->val.len++;
+
+out:
+ if (ret)
+ free_private_key(key);
+
+ return ret;
+}
+
+static int
+match_localkeyid(hx509_context context,
+ struct private_key *value,
+ hx509_certs certs)
+{
+ hx509_cert cert;
+ hx509_query q;
+ int ret;
+
+ if (value->localKeyId.length == 0) {
+ hx509_set_error_string(context, 0, HX509_LOCAL_ATTRIBUTE_MISSING,
+ "No local key attribute on private key");
+ return HX509_LOCAL_ATTRIBUTE_MISSING;
+ }
+
+ _hx509_query_clear(&q);
+ q.match |= HX509_QUERY_MATCH_LOCAL_KEY_ID;
+
+ q.local_key_id = &value->localKeyId;
+
+ ret = hx509_certs_find(context, certs, &q, &cert);
+ if (ret == 0 && cert == NULL)
+ ret = HX509_CERT_NOT_FOUND;
+ if (ret == 0) {
+ if (value->private_key)
+ _hx509_cert_assign_key(cert, value->private_key);
+ hx509_cert_free(cert);
+ }
+ return ret;
+}
+
+static int
+match_keys(hx509_context context, struct private_key *value, hx509_certs certs)
+{
+ hx509_cursor cursor;
+ hx509_cert c;
+ int ret, found = HX509_CERT_NOT_FOUND;
+
+ if (value->private_key == NULL) {
+ hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING,
+ "No private key to compare with");
+ return HX509_PRIVATE_KEY_MISSING;
+ }
+
+ ret = hx509_certs_start_seq(context, certs, &cursor);
+ if (ret)
+ return ret;
+
+ c = NULL;
+ while (1) {
+ ret = hx509_certs_next_cert(context, certs, cursor, &c);
+ if (ret)
+ break;
+ if (c == NULL)
+ break;
+ if (_hx509_cert_private_key(c)) {
+ hx509_cert_free(c);
+ continue;
+ }
+
+ ret = _hx509_match_keys(c, value->private_key);
+ if (ret) {
+ _hx509_cert_assign_key(c, value->private_key);
+ hx509_cert_free(c);
+ found = 0;
+ break;
+ }
+ hx509_cert_free(c);
+ }
+
+ hx509_certs_end_seq(context, certs, cursor);
+
+ if (found)
+ hx509_clear_error_string(context);
+
+ return found;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_collector_collect_certs(hx509_context context,
+ struct hx509_collector *c,
+ hx509_certs *ret_certs)
+{
+ hx509_certs certs;
+ int ret;
+ size_t i;
+
+ *ret_certs = NULL;
+
+ ret = hx509_certs_init(context, "MEMORY:collector-store", 0, NULL, &certs);
+ if (ret)
+ return ret;
+
+ ret = hx509_certs_merge(context, certs, c->certs);
+ if (ret) {
+ hx509_certs_free(&certs);
+ return ret;
+ }
+
+ for (i = 0; i < c->val.len; i++) {
+ ret = match_localkeyid(context, c->val.data[i], certs);
+ if (ret == 0)
+ continue;
+ ret = match_keys(context, c->val.data[i], certs);
+ if (ret == 0)
+ continue;
+ }
+
+ *ret_certs = certs;
+
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_collector_collect_private_keys(hx509_context context,
+ struct hx509_collector *c,
+ hx509_private_key **keys)
+{
+ size_t i, nkeys;
+
+ *keys = NULL;
+
+ for (i = 0, nkeys = 0; i < c->val.len; i++)
+ if (c->val.data[i]->private_key)
+ nkeys++;
+
+ *keys = calloc(nkeys + 1, sizeof(**keys));
+ if (*keys == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "malloc - out of memory");
+ return ENOMEM;
+ }
+
+ for (i = 0, nkeys = 0; i < c->val.len; i++) {
+ if (c->val.data[i]->private_key) {
+ (*keys)[nkeys++] = c->val.data[i]->private_key;
+ c->val.data[i]->private_key = NULL;
+ }
+ }
+ (*keys)[nkeys] = NULL;
+
+ return 0;
+}
+
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_collector_free(struct hx509_collector *c)
+{
+ size_t i;
+
+ if (c->unenvelop_certs)
+ hx509_certs_free(&c->unenvelop_certs);
+ if (c->certs)
+ hx509_certs_free(&c->certs);
+ for (i = 0; i < c->val.len; i++)
+ free_private_key(c->val.data[i]);
+ if (c->val.data)
+ free(c->val.data);
+ free(c);
+}
diff --git a/third_party/heimdal/lib/hx509/crypto-ec.c b/third_party/heimdal/lib/hx509/crypto-ec.c
new file mode 100644
index 0000000..46e6cd8
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/crypto-ec.c
@@ -0,0 +1,533 @@
+/*
+ * Copyright (c) 2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+#include <openssl/ec.h>
+#include <openssl/ecdsa.h>
+#include <openssl/rsa.h>
+#include <openssl/bn.h>
+#include <openssl/objects.h>
+#define HEIM_NO_CRYPTO_HDRS
+#endif /* HAVE_HCRYPTO_W_OPENSSL */
+
+#include "hx_locl.h"
+
+extern const AlgorithmIdentifier _hx509_signature_sha512_data;
+extern const AlgorithmIdentifier _hx509_signature_sha384_data;
+extern const AlgorithmIdentifier _hx509_signature_sha256_data;
+extern const AlgorithmIdentifier _hx509_signature_sha1_data;
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_private_eckey_free(void *eckey)
+{
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+ EC_KEY_free(eckey);
+#endif
+}
+
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+static int
+heim_oid2ecnid(heim_oid *oid)
+{
+ /*
+ * Now map to openssl OID fun
+ */
+
+ if (der_heim_oid_cmp(oid, ASN1_OID_ID_EC_GROUP_SECP256R1) == 0)
+ return NID_X9_62_prime256v1;
+#ifdef NID_secp521r1
+ else if (der_heim_oid_cmp(oid, ASN1_OID_ID_EC_GROUP_SECP521R1) == 0)
+ return NID_secp521r1;
+#endif
+#ifdef NID_secp384r1
+ else if (der_heim_oid_cmp(oid, ASN1_OID_ID_EC_GROUP_SECP384R1) == 0)
+ return NID_secp384r1;
+#endif
+#ifdef NID_secp160r1
+ else if (der_heim_oid_cmp(oid, ASN1_OID_ID_EC_GROUP_SECP160R1) == 0)
+ return NID_secp160r1;
+#endif
+#ifdef NID_secp160r2
+ else if (der_heim_oid_cmp(oid, ASN1_OID_ID_EC_GROUP_SECP160R2) == 0)
+ return NID_secp160r2;
+#endif
+
+ return NID_undef;
+}
+
+static int
+parse_ECParameters(hx509_context context,
+ heim_octet_string *parameters, int *nid)
+{
+ ECParameters ecparam;
+ size_t size;
+ int ret;
+
+ if (parameters == NULL) {
+ ret = HX509_PARSING_KEY_FAILED;
+ hx509_set_error_string(context, 0, ret,
+ "EC parameters missing");
+ return ret;
+ }
+
+ ret = decode_ECParameters(parameters->data, parameters->length,
+ &ecparam, &size);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to decode EC parameters");
+ return ret;
+ }
+
+ if (ecparam.element != choice_ECParameters_namedCurve) {
+ free_ECParameters(&ecparam);
+ hx509_set_error_string(context, 0, ret,
+ "EC parameters is not a named curve");
+ return HX509_CRYPTO_SIG_INVALID_FORMAT;
+ }
+
+ *nid = heim_oid2ecnid(&ecparam.u.namedCurve);
+ free_ECParameters(&ecparam);
+ if (*nid == NID_undef) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to find matcing NID for EC curve");
+ return HX509_CRYPTO_SIG_INVALID_FORMAT;
+ }
+ return 0;
+}
+
+
+/*
+ *
+ */
+
+static int
+ecdsa_verify_signature(hx509_context context,
+ const struct signature_alg *sig_alg,
+ const Certificate *signer,
+ const AlgorithmIdentifier *alg,
+ const heim_octet_string *data,
+ const heim_octet_string *sig)
+{
+ const AlgorithmIdentifier *digest_alg;
+ const SubjectPublicKeyInfo *spi;
+ heim_octet_string digest;
+ int ret;
+ EC_KEY *key = NULL;
+ int groupnid;
+ EC_GROUP *group;
+ const unsigned char *p;
+ long len;
+
+ digest_alg = sig_alg->digest_alg;
+
+ ret = _hx509_create_signature(context,
+ NULL,
+ digest_alg,
+ data,
+ NULL,
+ &digest);
+ if (ret)
+ return ret;
+
+ /* set up EC KEY */
+ spi = &signer->tbsCertificate.subjectPublicKeyInfo;
+
+ if (der_heim_oid_cmp(&spi->algorithm.algorithm, ASN1_OID_ID_ECPUBLICKEY) != 0)
+ return HX509_CRYPTO_SIG_INVALID_FORMAT;
+
+ /*
+ * Find the group id
+ */
+
+ ret = parse_ECParameters(context, spi->algorithm.parameters, &groupnid);
+ if (ret) {
+ der_free_octet_string(&digest);
+ return ret;
+ }
+
+ /*
+ * Create group, key, parse key
+ */
+
+ key = EC_KEY_new();
+ group = EC_GROUP_new_by_curve_name(groupnid);
+ EC_KEY_set_group(key, group);
+ EC_GROUP_free(group);
+
+ p = spi->subjectPublicKey.data;
+ len = spi->subjectPublicKey.length / 8;
+
+ if (o2i_ECPublicKey(&key, &p, len) == NULL) {
+ EC_KEY_free(key);
+ return HX509_CRYPTO_SIG_INVALID_FORMAT;
+ }
+
+ ret = ECDSA_verify(-1, digest.data, digest.length,
+ sig->data, sig->length, key);
+ der_free_octet_string(&digest);
+ EC_KEY_free(key);
+ if (ret != 1) {
+ ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
+ return ret;
+ }
+
+ return 0;
+}
+
+static int
+ecdsa_create_signature(hx509_context context,
+ const struct signature_alg *sig_alg,
+ const hx509_private_key signer,
+ const AlgorithmIdentifier *alg,
+ const heim_octet_string *data,
+ AlgorithmIdentifier *signatureAlgorithm,
+ heim_octet_string *sig)
+{
+ const AlgorithmIdentifier *digest_alg;
+ heim_octet_string indata;
+ const heim_oid *sig_oid;
+ unsigned int siglen;
+ int ret;
+
+ if (signer->ops && der_heim_oid_cmp(signer->ops->key_oid, ASN1_OID_ID_ECPUBLICKEY) != 0)
+ _hx509_abort("internal error passing private key to wrong ops");
+
+ sig_oid = sig_alg->sig_oid;
+ digest_alg = sig_alg->digest_alg;
+
+ if (signatureAlgorithm) {
+ ret = _hx509_set_digest_alg(signatureAlgorithm, sig_oid,
+ "\x05\x00", 2);
+ if (ret) {
+ hx509_clear_error_string(context);
+ return ret;
+ }
+ }
+
+ ret = _hx509_create_signature(context,
+ NULL,
+ digest_alg,
+ data,
+ NULL,
+ &indata);
+ if (ret)
+ goto error;
+
+ sig->length = ECDSA_size(signer->private_key.ecdsa);
+ sig->data = malloc(sig->length);
+ if (sig->data == NULL) {
+ der_free_octet_string(&indata);
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ goto error;
+ }
+
+ siglen = sig->length;
+
+ ret = ECDSA_sign(-1, indata.data, indata.length,
+ sig->data, &siglen, signer->private_key.ecdsa);
+ der_free_octet_string(&indata);
+ if (ret != 1) {
+ ret = HX509_CMS_FAILED_CREATE_SIGATURE;
+ hx509_set_error_string(context, 0, ret,
+ "ECDSA sign failed: %d", ret);
+ goto error;
+ }
+ if (siglen > sig->length)
+ _hx509_abort("ECDSA signature prelen longer the output len");
+
+ sig->length = siglen;
+
+ return 0;
+ error:
+ if (signatureAlgorithm)
+ free_AlgorithmIdentifier(signatureAlgorithm);
+ return ret;
+}
+
+static int
+ecdsa_available(const hx509_private_key signer,
+ const AlgorithmIdentifier *sig_alg)
+{
+ const struct signature_alg *sig;
+ const EC_GROUP *group;
+ BN_CTX *bnctx = NULL;
+ BIGNUM *order = NULL;
+ int ret = 0;
+
+ if (der_heim_oid_cmp(signer->ops->key_oid, &asn1_oid_id_ecPublicKey) != 0)
+ _hx509_abort("internal error passing private key to wrong ops");
+
+ sig = _hx509_find_sig_alg(&sig_alg->algorithm);
+
+ if (sig == NULL || sig->digest_size == 0)
+ return 0;
+
+ group = EC_KEY_get0_group(signer->private_key.ecdsa);
+ if (group == NULL)
+ return 0;
+
+ bnctx = BN_CTX_new();
+ order = BN_new();
+ if (order == NULL)
+ goto err;
+
+ if (EC_GROUP_get_order(group, order, bnctx) != 1)
+ goto err;
+
+#if 0
+ /* If anything, require a digest at least as wide as the EC key size */
+ if (BN_num_bytes(order) > sig->digest_size)
+#endif
+ ret = 1;
+ err:
+ if (bnctx)
+ BN_CTX_free(bnctx);
+ if (order)
+ BN_clear_free(order);
+
+ return ret;
+}
+
+static int
+ecdsa_private_key2SPKI(hx509_context context,
+ hx509_private_key private_key,
+ SubjectPublicKeyInfo *spki)
+{
+ memset(spki, 0, sizeof(*spki));
+ return ENOMEM;
+}
+
+static int
+ecdsa_private_key_export(hx509_context context,
+ const hx509_private_key key,
+ hx509_key_format_t format,
+ heim_octet_string *data)
+{
+ return HX509_CRYPTO_KEY_FORMAT_UNSUPPORTED;
+}
+
+static int
+ecdsa_private_key_import(hx509_context context,
+ const AlgorithmIdentifier *keyai,
+ const void *data,
+ size_t len,
+ hx509_key_format_t format,
+ hx509_private_key private_key)
+{
+ const unsigned char *p = data;
+ EC_KEY **pkey = NULL;
+ EC_KEY *key;
+
+ if (keyai->parameters) {
+ EC_GROUP *group;
+ int groupnid;
+ int ret;
+
+ ret = parse_ECParameters(context, keyai->parameters, &groupnid);
+ if (ret)
+ return ret;
+
+ key = EC_KEY_new();
+ if (key == NULL)
+ return ENOMEM;
+
+ group = EC_GROUP_new_by_curve_name(groupnid);
+ if (group == NULL) {
+ EC_KEY_free(key);
+ return ENOMEM;
+ }
+ EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE);
+ if (EC_KEY_set_group(key, group) == 0) {
+ EC_KEY_free(key);
+ EC_GROUP_free(group);
+ return ENOMEM;
+ }
+ EC_GROUP_free(group);
+ pkey = &key;
+ }
+
+ switch (format) {
+ case HX509_KEY_FORMAT_DER:
+
+ private_key->private_key.ecdsa = d2i_ECPrivateKey(pkey, &p, len);
+ if (private_key->private_key.ecdsa == NULL) {
+ hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
+ "Failed to parse EC private key");
+ return HX509_PARSING_KEY_FAILED;
+ }
+ private_key->signature_alg = ASN1_OID_ID_ECDSA_WITH_SHA256;
+ break;
+
+ default:
+ return HX509_CRYPTO_KEY_FORMAT_UNSUPPORTED;
+ }
+
+ return 0;
+}
+
+static int
+ecdsa_generate_private_key(hx509_context context,
+ struct hx509_generate_private_context *ctx,
+ hx509_private_key private_key)
+{
+ return ENOMEM;
+}
+
+static BIGNUM *
+ecdsa_get_internal(hx509_context context,
+ hx509_private_key key,
+ const char *type)
+{
+ return NULL;
+}
+
+static const unsigned ecPublicKey[] ={ 1, 2, 840, 10045, 2, 1 };
+const AlgorithmIdentifier _hx509_signature_ecPublicKey = {
+ { 6, rk_UNCONST(ecPublicKey) }, NULL
+};
+
+static const unsigned ecdsa_with_sha256_oid[] ={ 1, 2, 840, 10045, 4, 3, 2 };
+const AlgorithmIdentifier _hx509_signature_ecdsa_with_sha256_data = {
+ { 7, rk_UNCONST(ecdsa_with_sha256_oid) }, NULL
+};
+
+static const unsigned ecdsa_with_sha384_oid[] ={ 1, 2, 840, 10045, 4, 3, 3 };
+const AlgorithmIdentifier _hx509_signature_ecdsa_with_sha384_data = {
+ { 7, rk_UNCONST(ecdsa_with_sha384_oid) }, NULL
+};
+
+static const unsigned ecdsa_with_sha512_oid[] ={ 1, 2, 840, 10045, 4, 3, 4 };
+const AlgorithmIdentifier _hx509_signature_ecdsa_with_sha512_data = {
+ { 7, rk_UNCONST(ecdsa_with_sha512_oid) }, NULL
+};
+
+static const unsigned ecdsa_with_sha1_oid[] ={ 1, 2, 840, 10045, 4, 1 };
+const AlgorithmIdentifier _hx509_signature_ecdsa_with_sha1_data = {
+ { 6, rk_UNCONST(ecdsa_with_sha1_oid) }, NULL
+};
+
+hx509_private_key_ops ecdsa_private_key_ops = {
+ "EC PRIVATE KEY",
+ ASN1_OID_ID_ECPUBLICKEY,
+ ecdsa_available,
+ ecdsa_private_key2SPKI,
+ ecdsa_private_key_export,
+ ecdsa_private_key_import,
+ ecdsa_generate_private_key,
+ ecdsa_get_internal
+};
+
+const struct signature_alg ecdsa_with_sha512_alg = {
+ "ecdsa-with-sha512",
+ ASN1_OID_ID_ECDSA_WITH_SHA512,
+ &_hx509_signature_ecdsa_with_sha512_data,
+ ASN1_OID_ID_ECPUBLICKEY,
+ &_hx509_signature_sha512_data,
+ PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|
+ SIG_PUBLIC_SIG|SELF_SIGNED_OK,
+ 0,
+ NULL,
+ ecdsa_verify_signature,
+ ecdsa_create_signature,
+ 64
+};
+
+const struct signature_alg ecdsa_with_sha384_alg = {
+ "ecdsa-with-sha384",
+ ASN1_OID_ID_ECDSA_WITH_SHA384,
+ &_hx509_signature_ecdsa_with_sha384_data,
+ ASN1_OID_ID_ECPUBLICKEY,
+ &_hx509_signature_sha384_data,
+ PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|
+ SIG_PUBLIC_SIG|SELF_SIGNED_OK,
+ 0,
+ NULL,
+ ecdsa_verify_signature,
+ ecdsa_create_signature,
+ 48
+};
+
+const struct signature_alg ecdsa_with_sha256_alg = {
+ "ecdsa-with-sha256",
+ ASN1_OID_ID_ECDSA_WITH_SHA256,
+ &_hx509_signature_ecdsa_with_sha256_data,
+ ASN1_OID_ID_ECPUBLICKEY,
+ &_hx509_signature_sha256_data,
+ PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|
+ SIG_PUBLIC_SIG|SELF_SIGNED_OK,
+ 0,
+ NULL,
+ ecdsa_verify_signature,
+ ecdsa_create_signature,
+ 32
+};
+
+const struct signature_alg ecdsa_with_sha1_alg = {
+ "ecdsa-with-sha1",
+ ASN1_OID_ID_ECDSA_WITH_SHA1,
+ &_hx509_signature_ecdsa_with_sha1_data,
+ ASN1_OID_ID_ECPUBLICKEY,
+ &_hx509_signature_sha1_data,
+ PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|
+ SIG_PUBLIC_SIG|SELF_SIGNED_OK,
+ 0,
+ NULL,
+ ecdsa_verify_signature,
+ ecdsa_create_signature,
+ 20
+};
+
+#endif /* HAVE_HCRYPTO_W_OPENSSL */
+
+HX509_LIB_FUNCTION const AlgorithmIdentifier * HX509_LIB_CALL
+hx509_signature_ecPublicKey(void)
+{
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+ return &_hx509_signature_ecPublicKey;
+#else
+ return NULL;
+#endif /* HAVE_HCRYPTO_W_OPENSSL */
+}
+
+HX509_LIB_FUNCTION const AlgorithmIdentifier * HX509_LIB_CALL
+hx509_signature_ecdsa_with_sha256(void)
+{
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+ return &_hx509_signature_ecdsa_with_sha256_data;
+#else
+ return NULL;
+#endif /* HAVE_HCRYPTO_W_OPENSSL */
+}
diff --git a/third_party/heimdal/lib/hx509/crypto.c b/third_party/heimdal/lib/hx509/crypto.c
new file mode 100644
index 0000000..8d368ed
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/crypto.c
@@ -0,0 +1,2804 @@
+/*
+ * Copyright (c) 2004 - 2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+/*-
+ * RFC5758 specifies no parameters for ecdsa-with-SHA<N> signatures
+ * RFC5754 specifies NULL parameters for sha<N>WithRSAEncryption signatures
+ *
+ * XXX: Make sure that the parameters are either NULL in both the tbs and the
+ * signature, or absent from both the tbs and the signature.
+ */
+
+static const heim_octet_string null_entry_oid = { 2, rk_UNCONST("\x05\x00") };
+
+static const unsigned sha512_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 3 };
+const AlgorithmIdentifier _hx509_signature_sha512_data = {
+ { 9, rk_UNCONST(sha512_oid_tree) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned sha384_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 2 };
+const AlgorithmIdentifier _hx509_signature_sha384_data = {
+ { 9, rk_UNCONST(sha384_oid_tree) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned sha256_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 1 };
+const AlgorithmIdentifier _hx509_signature_sha256_data = {
+ { 9, rk_UNCONST(sha256_oid_tree) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned sha1_oid_tree[] = { 1, 3, 14, 3, 2, 26 };
+const AlgorithmIdentifier _hx509_signature_sha1_data = {
+ { 6, rk_UNCONST(sha1_oid_tree) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned md5_oid_tree[] = { 1, 2, 840, 113549, 2, 5 };
+const AlgorithmIdentifier _hx509_signature_md5_data = {
+ { 6, rk_UNCONST(md5_oid_tree) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned rsa_with_sha512_oid[] ={ 1, 2, 840, 113549, 1, 1, 13 };
+const AlgorithmIdentifier _hx509_signature_rsa_with_sha512_data = {
+ { 7, rk_UNCONST(rsa_with_sha512_oid) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned rsa_with_sha384_oid[] ={ 1, 2, 840, 113549, 1, 1, 12 };
+const AlgorithmIdentifier _hx509_signature_rsa_with_sha384_data = {
+ { 7, rk_UNCONST(rsa_with_sha384_oid) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned rsa_with_sha256_oid[] ={ 1, 2, 840, 113549, 1, 1, 11 };
+const AlgorithmIdentifier _hx509_signature_rsa_with_sha256_data = {
+ { 7, rk_UNCONST(rsa_with_sha256_oid) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned rsa_with_sha1_oid[] ={ 1, 2, 840, 113549, 1, 1, 5 };
+const AlgorithmIdentifier _hx509_signature_rsa_with_sha1_data = {
+ { 7, rk_UNCONST(rsa_with_sha1_oid) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned rsa_with_md5_oid[] ={ 1, 2, 840, 113549, 1, 1, 4 };
+const AlgorithmIdentifier _hx509_signature_rsa_with_md5_data = {
+ { 7, rk_UNCONST(rsa_with_md5_oid) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned rsa_oid[] ={ 1, 2, 840, 113549, 1, 1, 1 };
+const AlgorithmIdentifier _hx509_signature_rsa_data = {
+ { 7, rk_UNCONST(rsa_oid) }, NULL
+};
+
+static const unsigned rsa_pkcs1_x509_oid[] ={ 1, 2, 752, 43, 16, 1 };
+const AlgorithmIdentifier _hx509_signature_rsa_pkcs1_x509_data = {
+ { 6, rk_UNCONST(rsa_pkcs1_x509_oid) }, NULL
+};
+
+static const unsigned des_rsdi_ede3_cbc_oid[] ={ 1, 2, 840, 113549, 3, 7 };
+const AlgorithmIdentifier _hx509_des_rsdi_ede3_cbc_oid = {
+ { 6, rk_UNCONST(des_rsdi_ede3_cbc_oid) }, NULL
+};
+
+static const unsigned aes128_cbc_oid[] ={ 2, 16, 840, 1, 101, 3, 4, 1, 2 };
+const AlgorithmIdentifier _hx509_crypto_aes128_cbc_data = {
+ { 9, rk_UNCONST(aes128_cbc_oid) }, NULL
+};
+
+static const unsigned aes256_cbc_oid[] ={ 2, 16, 840, 1, 101, 3, 4, 1, 42 };
+const AlgorithmIdentifier _hx509_crypto_aes256_cbc_data = {
+ { 9, rk_UNCONST(aes256_cbc_oid) }, NULL
+};
+
+/*
+ *
+ */
+
+static BIGNUM *
+heim_int2BN(const heim_integer *i)
+{
+ BIGNUM *bn;
+
+ bn = BN_bin2bn(i->data, i->length, NULL);
+ BN_set_negative(bn, i->negative);
+ return bn;
+}
+
+/*
+ *
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_set_digest_alg(DigestAlgorithmIdentifier *id,
+ const heim_oid *oid,
+ const void *param, size_t length)
+{
+ int ret;
+ if (param) {
+ id->parameters = malloc(sizeof(*id->parameters));
+ if (id->parameters == NULL)
+ return ENOMEM;
+ id->parameters->data = malloc(length);
+ if (id->parameters->data == NULL) {
+ free(id->parameters);
+ id->parameters = NULL;
+ return ENOMEM;
+ }
+ memcpy(id->parameters->data, param, length);
+ id->parameters->length = length;
+ } else
+ id->parameters = NULL;
+ ret = der_copy_oid(oid, &id->algorithm);
+ if (ret) {
+ if (id->parameters) {
+ free(id->parameters->data);
+ free(id->parameters);
+ id->parameters = NULL;
+ }
+ return ret;
+ }
+ return 0;
+}
+
+/*
+ *
+ */
+
+static int
+rsa_verify_signature(hx509_context context,
+ const struct signature_alg *sig_alg,
+ const Certificate *signer,
+ const AlgorithmIdentifier *alg,
+ const heim_octet_string *data,
+ const heim_octet_string *sig)
+{
+ const SubjectPublicKeyInfo *spi;
+ DigestInfo di;
+ unsigned char *to;
+ int tosize, retsize;
+ int ret;
+ RSA *rsa;
+ size_t size;
+ const unsigned char *p;
+
+ memset(&di, 0, sizeof(di));
+
+ spi = &signer->tbsCertificate.subjectPublicKeyInfo;
+
+ p = spi->subjectPublicKey.data;
+ size = spi->subjectPublicKey.length / 8;
+
+ rsa = d2i_RSAPublicKey(NULL, &p, size);
+ if (rsa == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ goto out;
+ }
+
+ tosize = RSA_size(rsa);
+ to = malloc(tosize);
+ if (to == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ goto out;
+ }
+
+ retsize = RSA_public_decrypt(sig->length, (unsigned char *)sig->data,
+ to, rsa, RSA_PKCS1_PADDING);
+ if (retsize <= 0) {
+ ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
+ hx509_set_error_string(context, 0, ret,
+ "RSA public decrypt failed: %d", retsize);
+ free(to);
+ goto out;
+ }
+ if (retsize > tosize)
+ _hx509_abort("internal rsa decryption failure: ret > tosize");
+
+ if (sig_alg->flags & RA_RSA_USES_DIGEST_INFO) {
+
+ ret = decode_DigestInfo(to, retsize, &di, &size);
+ free(to);
+ if (ret) {
+ goto out;
+ }
+
+ /* Check for extra data inside the sigature */
+ if (size != (size_t)retsize) {
+ ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
+ hx509_set_error_string(context, 0, ret, "size from decryption mismatch");
+ goto out;
+ }
+
+ if (sig_alg->digest_alg &&
+ der_heim_oid_cmp(&di.digestAlgorithm.algorithm,
+ &sig_alg->digest_alg->algorithm) != 0)
+ {
+ ret = HX509_CRYPTO_OID_MISMATCH;
+ hx509_set_error_string(context, 0, ret, "object identifier in RSA sig mismatch");
+ goto out;
+ }
+
+ /* verify that the parameters are NULL or the NULL-type */
+ if (di.digestAlgorithm.parameters != NULL &&
+ (di.digestAlgorithm.parameters->length != 2 ||
+ memcmp(di.digestAlgorithm.parameters->data, "\x05\x00", 2) != 0))
+ {
+ ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
+ hx509_set_error_string(context, 0, ret, "Extra parameters inside RSA signature");
+ goto out;
+ }
+
+ ret = _hx509_verify_signature(context,
+ NULL,
+ &di.digestAlgorithm,
+ data,
+ &di.digest);
+ if (ret)
+ goto out;
+
+ } else {
+ if ((size_t)retsize != data->length ||
+ ct_memcmp(to, data->data, retsize) != 0)
+ {
+ ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
+ hx509_set_error_string(context, 0, ret, "RSA Signature incorrect");
+ goto out;
+ }
+ free(to);
+ ret = 0;
+ }
+
+ out:
+ free_DigestInfo(&di);
+ if (rsa)
+ RSA_free(rsa);
+ return ret;
+}
+
+static int
+rsa_create_signature(hx509_context context,
+ const struct signature_alg *sig_alg,
+ const hx509_private_key signer,
+ const AlgorithmIdentifier *alg,
+ const heim_octet_string *data,
+ AlgorithmIdentifier *signatureAlgorithm,
+ heim_octet_string *sig)
+{
+ const AlgorithmIdentifier *digest_alg;
+ heim_octet_string indata;
+ const heim_oid *sig_oid;
+ size_t size;
+ int ret;
+
+ if (signer->ops && der_heim_oid_cmp(signer->ops->key_oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) != 0)
+ return HX509_ALG_NOT_SUPP;
+
+ if (alg)
+ sig_oid = &alg->algorithm;
+ else
+ sig_oid = signer->signature_alg;
+
+ if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA512WITHRSAENCRYPTION) == 0) {
+ digest_alg = hx509_signature_sha512();
+ } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA384WITHRSAENCRYPTION) == 0) {
+ digest_alg = hx509_signature_sha384();
+ } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA256WITHRSAENCRYPTION) == 0) {
+ digest_alg = hx509_signature_sha256();
+ } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION) == 0) {
+ digest_alg = hx509_signature_sha1();
+ } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_MD5WITHRSAENCRYPTION) == 0) {
+ digest_alg = hx509_signature_md5();
+ } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_MD5WITHRSAENCRYPTION) == 0) {
+ digest_alg = hx509_signature_md5();
+ } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_DSA_WITH_SHA1) == 0) {
+ digest_alg = hx509_signature_sha1();
+ } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) == 0) {
+ digest_alg = hx509_signature_sha1();
+ } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_HEIM_RSA_PKCS1_X509) == 0) {
+ digest_alg = NULL;
+ } else
+ return HX509_ALG_NOT_SUPP;
+
+ if (signatureAlgorithm) {
+ ret = _hx509_set_digest_alg(signatureAlgorithm, sig_oid,
+ "\x05\x00", 2);
+ if (ret) {
+ hx509_clear_error_string(context);
+ return ret;
+ }
+ }
+
+ if (digest_alg) {
+ DigestInfo di;
+ memset(&di, 0, sizeof(di));
+
+ ret = _hx509_create_signature(context,
+ NULL,
+ digest_alg,
+ data,
+ &di.digestAlgorithm,
+ &di.digest);
+ if (ret)
+ return ret;
+ ASN1_MALLOC_ENCODE(DigestInfo,
+ indata.data,
+ indata.length,
+ &di,
+ &size,
+ ret);
+ free_DigestInfo(&di);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ return ret;
+ }
+ if (indata.length != size)
+ _hx509_abort("internal ASN.1 encoder error");
+ } else {
+ indata = *data;
+ }
+
+ sig->length = RSA_size(signer->private_key.rsa);
+ sig->data = malloc(sig->length);
+ if (sig->data == NULL) {
+ der_free_octet_string(&indata);
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ ret = RSA_private_encrypt(indata.length, indata.data,
+ sig->data,
+ signer->private_key.rsa,
+ RSA_PKCS1_PADDING);
+ if (indata.data != data->data)
+ der_free_octet_string(&indata);
+ if (ret <= 0) {
+ ret = HX509_CMS_FAILED_CREATE_SIGATURE;
+ hx509_set_error_string(context, 0, ret,
+ "RSA private encrypt failed: %d", ret);
+ return ret;
+ }
+ if (sig->length > (size_t)ret) {
+ size = sig->length - ret;
+ memmove((uint8_t *)sig->data + size, sig->data, ret);
+ memset(sig->data, 0, size);
+ } else if (sig->length < (size_t)ret)
+ _hx509_abort("RSA signature prelen longer the output len");
+
+ return 0;
+}
+
+static int
+rsa_private_key_import(hx509_context context,
+ const AlgorithmIdentifier *keyai,
+ const void *data,
+ size_t len,
+ hx509_key_format_t format,
+ hx509_private_key private_key)
+{
+ switch (format) {
+ case HX509_KEY_FORMAT_DER: {
+ const unsigned char *p = data;
+
+ private_key->private_key.rsa =
+ d2i_RSAPrivateKey(NULL, &p, len);
+ if (private_key->private_key.rsa == NULL) {
+ hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
+ "Failed to parse RSA key");
+ return HX509_PARSING_KEY_FAILED;
+ }
+ private_key->signature_alg = ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION;
+ break;
+
+ }
+ default:
+ return HX509_CRYPTO_KEY_FORMAT_UNSUPPORTED;
+ }
+
+ return 0;
+}
+
+static int
+rsa_private_key2SPKI(hx509_context context,
+ hx509_private_key private_key,
+ SubjectPublicKeyInfo *spki)
+{
+ int len, ret;
+
+ memset(spki, 0, sizeof(*spki));
+
+ len = i2d_RSAPublicKey(private_key->private_key.rsa, NULL);
+ if (len < 0)
+ return -1;
+
+ spki->subjectPublicKey.data = malloc(len);
+ if (spki->subjectPublicKey.data == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "malloc - out of memory");
+ return ENOMEM;
+ }
+ spki->subjectPublicKey.length = len * 8;
+
+ ret = _hx509_set_digest_alg(&spki->algorithm,
+ ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+ "\x05\x00", 2);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "malloc - out of memory");
+ free(spki->subjectPublicKey.data);
+ spki->subjectPublicKey.data = NULL;
+ spki->subjectPublicKey.length = 0;
+ return ret;
+ }
+
+ {
+ unsigned char *pp = spki->subjectPublicKey.data;
+ i2d_RSAPublicKey(private_key->private_key.rsa, &pp);
+ }
+
+ return 0;
+}
+
+static int
+rsa_generate_private_key(hx509_context context,
+ struct hx509_generate_private_context *ctx,
+ hx509_private_key private_key)
+{
+ BIGNUM *e;
+ int ret;
+ unsigned long bits;
+
+ static const int default_rsa_e = 65537;
+ static const int default_rsa_bits = 2048;
+
+ private_key->private_key.rsa = RSA_new();
+ if (private_key->private_key.rsa == NULL) {
+ hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
+ "Failed to generate RSA key");
+ return HX509_PARSING_KEY_FAILED;
+ }
+
+ e = BN_new();
+ BN_set_word(e, default_rsa_e);
+
+ bits = default_rsa_bits;
+
+ if (ctx->num_bits)
+ bits = ctx->num_bits;
+
+ ret = RSA_generate_key_ex(private_key->private_key.rsa, bits, e, NULL);
+ BN_free(e);
+ if (ret != 1) {
+ hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
+ "Failed to generate RSA key");
+ return HX509_PARSING_KEY_FAILED;
+ }
+ private_key->signature_alg = ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION;
+
+ return 0;
+}
+
+static int
+rsa_private_key_export(hx509_context context,
+ const hx509_private_key key,
+ hx509_key_format_t format,
+ heim_octet_string *data)
+{
+ int ret;
+
+ data->data = NULL;
+ data->length = 0;
+
+ switch (format) {
+ case HX509_KEY_FORMAT_DER:
+
+ ret = i2d_RSAPrivateKey(key->private_key.rsa, NULL);
+ if (ret <= 0) {
+ ret = EINVAL;
+ hx509_set_error_string(context, 0, ret,
+ "Private key is not exportable");
+ return ret;
+ }
+
+ data->data = malloc(ret);
+ if (data->data == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "malloc out of memory");
+ return ret;
+ }
+ data->length = ret;
+
+ {
+ unsigned char *p = data->data;
+ i2d_RSAPrivateKey(key->private_key.rsa, &p);
+ }
+ break;
+ default:
+ return HX509_CRYPTO_KEY_FORMAT_UNSUPPORTED;
+ }
+
+ return 0;
+}
+
+static BIGNUM *
+rsa_get_internal(hx509_context context,
+ hx509_private_key key,
+ const char *type)
+{
+ if (strcasecmp(type, "rsa-modulus") == 0) {
+ return BN_dup(key->private_key.rsa->n);
+ } else if (strcasecmp(type, "rsa-exponent") == 0) {
+ return BN_dup(key->private_key.rsa->e);
+ } else
+ return NULL;
+}
+
+
+
+static hx509_private_key_ops rsa_private_key_ops = {
+ "RSA PRIVATE KEY",
+ ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+ NULL,
+ rsa_private_key2SPKI,
+ rsa_private_key_export,
+ rsa_private_key_import,
+ rsa_generate_private_key,
+ rsa_get_internal
+};
+
+/*
+ *
+ */
+
+static int
+dsa_verify_signature(hx509_context context,
+ const struct signature_alg *sig_alg,
+ const Certificate *signer,
+ const AlgorithmIdentifier *alg,
+ const heim_octet_string *data,
+ const heim_octet_string *sig)
+{
+ const SubjectPublicKeyInfo *spi;
+ DSAPublicKey pk;
+ DSAParams param;
+ size_t size;
+ DSA *dsa;
+ int ret;
+
+ spi = &signer->tbsCertificate.subjectPublicKeyInfo;
+
+ dsa = DSA_new();
+ if (dsa == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ ret = decode_DSAPublicKey(spi->subjectPublicKey.data,
+ spi->subjectPublicKey.length / 8,
+ &pk, &size);
+ if (ret)
+ goto out;
+
+ dsa->pub_key = heim_int2BN(&pk);
+
+ free_DSAPublicKey(&pk);
+
+ if (dsa->pub_key == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ goto out;
+ }
+
+ if (spi->algorithm.parameters == NULL) {
+ ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
+ hx509_set_error_string(context, 0, ret, "DSA parameters missing");
+ goto out;
+ }
+
+ ret = decode_DSAParams(spi->algorithm.parameters->data,
+ spi->algorithm.parameters->length,
+ &param,
+ &size);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "DSA parameters failed to decode");
+ goto out;
+ }
+
+ dsa->p = heim_int2BN(&param.p);
+ dsa->q = heim_int2BN(&param.q);
+ dsa->g = heim_int2BN(&param.g);
+
+ free_DSAParams(&param);
+
+ if (dsa->p == NULL || dsa->q == NULL || dsa->g == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ goto out;
+ }
+
+ ret = DSA_verify(-1, data->data, data->length,
+ (unsigned char*)sig->data, sig->length,
+ dsa);
+ if (ret == 1)
+ ret = 0;
+ else if (ret == 0 || ret == -1) {
+ ret = HX509_CRYPTO_BAD_SIGNATURE;
+ hx509_set_error_string(context, 0, ret, "BAD DSA sigature");
+ } else {
+ ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
+ hx509_set_error_string(context, 0, ret, "Invalid format of DSA sigature");
+ }
+
+ out:
+ DSA_free(dsa);
+
+ return ret;
+}
+
+#if 0
+static int
+dsa_parse_private_key(hx509_context context,
+ const void *data,
+ size_t len,
+ hx509_private_key private_key)
+{
+ const unsigned char *p = data;
+
+ private_key->private_key.dsa =
+ d2i_DSAPrivateKey(NULL, &p, len);
+ if (private_key->private_key.dsa == NULL)
+ return EINVAL;
+ private_key->signature_alg = ASN1_OID_ID_DSA_WITH_SHA1;
+
+ return 0;
+/* else */
+ hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
+ "No support to parse DSA keys");
+ return HX509_PARSING_KEY_FAILED;
+}
+#endif
+
+static int
+evp_md_create_signature(hx509_context context,
+ const struct signature_alg *sig_alg,
+ const hx509_private_key signer,
+ const AlgorithmIdentifier *alg,
+ const heim_octet_string *data,
+ AlgorithmIdentifier *signatureAlgorithm,
+ heim_octet_string *sig)
+{
+ size_t sigsize = EVP_MD_size(sig_alg->evp_md());
+ EVP_MD_CTX *ctx;
+
+ memset(sig, 0, sizeof(*sig));
+
+ if (signatureAlgorithm) {
+ int ret;
+ ret = _hx509_set_digest_alg(signatureAlgorithm,
+ sig_alg->sig_oid, "\x05\x00", 2);
+ if (ret)
+ return ret;
+ }
+
+
+ sig->data = malloc(sigsize);
+ if (sig->data == NULL) {
+ sig->length = 0;
+ return ENOMEM;
+ }
+ sig->length = sigsize;
+
+ ctx = EVP_MD_CTX_create();
+ EVP_DigestInit_ex(ctx, sig_alg->evp_md(), NULL);
+ EVP_DigestUpdate(ctx, data->data, data->length);
+ EVP_DigestFinal_ex(ctx, sig->data, NULL);
+ EVP_MD_CTX_destroy(ctx);
+
+
+ return 0;
+}
+
+static int
+evp_md_verify_signature(hx509_context context,
+ const struct signature_alg *sig_alg,
+ const Certificate *signer,
+ const AlgorithmIdentifier *alg,
+ const heim_octet_string *data,
+ const heim_octet_string *sig)
+{
+ unsigned char digest[EVP_MAX_MD_SIZE];
+ EVP_MD_CTX *ctx;
+ size_t sigsize = EVP_MD_size(sig_alg->evp_md());
+
+ if (sig->length != sigsize || sigsize > sizeof(digest)) {
+ hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT,
+ "SHA256 sigature have wrong length");
+ return HX509_CRYPTO_SIG_INVALID_FORMAT;
+ }
+
+ ctx = EVP_MD_CTX_create();
+ EVP_DigestInit_ex(ctx, sig_alg->evp_md(), NULL);
+ EVP_DigestUpdate(ctx, data->data, data->length);
+ EVP_DigestFinal_ex(ctx, digest, NULL);
+ EVP_MD_CTX_destroy(ctx);
+
+ if (ct_memcmp(digest, sig->data, sigsize) != 0) {
+ hx509_set_error_string(context, 0, HX509_CRYPTO_BAD_SIGNATURE,
+ "Bad %s sigature", sig_alg->name);
+ return HX509_CRYPTO_BAD_SIGNATURE;
+ }
+
+ return 0;
+}
+
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+extern const struct signature_alg ecdsa_with_sha512_alg;
+extern const struct signature_alg ecdsa_with_sha384_alg;
+extern const struct signature_alg ecdsa_with_sha256_alg;
+extern const struct signature_alg ecdsa_with_sha1_alg;
+#endif
+
+static const struct signature_alg heim_rsa_pkcs1_x509 = {
+ "rsa-pkcs1-x509",
+ ASN1_OID_ID_HEIM_RSA_PKCS1_X509,
+ &_hx509_signature_rsa_pkcs1_x509_data,
+ ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+ NULL,
+ PROVIDE_CONF|REQUIRE_SIGNER|SIG_PUBLIC_SIG,
+ 0,
+ NULL,
+ rsa_verify_signature,
+ rsa_create_signature,
+ 0
+};
+
+static const struct signature_alg pkcs1_rsa_sha1_alg = {
+ "rsa",
+ ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+ &_hx509_signature_rsa_with_sha1_data,
+ ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+ NULL,
+ PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK,
+ 0,
+ NULL,
+ rsa_verify_signature,
+ rsa_create_signature,
+ 0
+};
+
+static const struct signature_alg rsa_with_sha512_alg = {
+ "rsa-with-sha512",
+ ASN1_OID_ID_PKCS1_SHA512WITHRSAENCRYPTION,
+ &_hx509_signature_rsa_with_sha512_data,
+ ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+ &_hx509_signature_sha512_data,
+ PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK,
+ 0,
+ NULL,
+ rsa_verify_signature,
+ rsa_create_signature,
+ 0
+};
+
+static const struct signature_alg rsa_with_sha384_alg = {
+ "rsa-with-sha384",
+ ASN1_OID_ID_PKCS1_SHA384WITHRSAENCRYPTION,
+ &_hx509_signature_rsa_with_sha384_data,
+ ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+ &_hx509_signature_sha384_data,
+ PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK,
+ 0,
+ NULL,
+ rsa_verify_signature,
+ rsa_create_signature,
+ 0
+};
+
+static const struct signature_alg rsa_with_sha256_alg = {
+ "rsa-with-sha256",
+ ASN1_OID_ID_PKCS1_SHA256WITHRSAENCRYPTION,
+ &_hx509_signature_rsa_with_sha256_data,
+ ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+ &_hx509_signature_sha256_data,
+ PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK,
+ 0,
+ NULL,
+ rsa_verify_signature,
+ rsa_create_signature,
+ 0
+};
+
+static const struct signature_alg rsa_with_sha1_alg = {
+ "rsa-with-sha1",
+ ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION,
+ &_hx509_signature_rsa_with_sha1_data,
+ ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+ &_hx509_signature_sha1_data,
+ PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK,
+ 0,
+ NULL,
+ rsa_verify_signature,
+ rsa_create_signature,
+ 0
+};
+
+static const struct signature_alg rsa_with_sha1_alg_secsig = {
+ "rsa-with-sha1",
+ ASN1_OID_ID_SECSIG_SHA_1WITHRSAENCRYPTION,
+ &_hx509_signature_rsa_with_sha1_data,
+ ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+ &_hx509_signature_sha1_data,
+ PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK,
+ 0,
+ NULL,
+ rsa_verify_signature,
+ rsa_create_signature,
+ 0
+};
+
+static const struct signature_alg rsa_with_md5_alg = {
+ "rsa-with-md5",
+ ASN1_OID_ID_PKCS1_MD5WITHRSAENCRYPTION,
+ &_hx509_signature_rsa_with_md5_data,
+ ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+ &_hx509_signature_md5_data,
+ PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|WEAK_SIG_ALG,
+ 1230739889,
+ NULL,
+ rsa_verify_signature,
+ rsa_create_signature,
+ 0
+};
+
+static const struct signature_alg dsa_sha1_alg = {
+ "dsa-with-sha1",
+ ASN1_OID_ID_DSA_WITH_SHA1,
+ NULL,
+ ASN1_OID_ID_DSA,
+ &_hx509_signature_sha1_data,
+ PROVIDE_CONF|REQUIRE_SIGNER|SIG_PUBLIC_SIG,
+ 0,
+ NULL,
+ dsa_verify_signature,
+ /* create_signature */ NULL,
+ 0
+};
+
+static const struct signature_alg sha512_alg = {
+ "sha-512",
+ ASN1_OID_ID_SHA512,
+ &_hx509_signature_sha512_data,
+ NULL,
+ NULL,
+ SIG_DIGEST,
+ 0,
+ EVP_sha512,
+ evp_md_verify_signature,
+ evp_md_create_signature,
+ 0
+};
+
+static const struct signature_alg sha384_alg = {
+ "sha-384",
+ ASN1_OID_ID_SHA384,
+ &_hx509_signature_sha384_data,
+ NULL,
+ NULL,
+ SIG_DIGEST,
+ 0,
+ EVP_sha384,
+ evp_md_verify_signature,
+ evp_md_create_signature,
+ 0
+};
+
+static const struct signature_alg sha256_alg = {
+ "sha-256",
+ ASN1_OID_ID_SHA256,
+ &_hx509_signature_sha256_data,
+ NULL,
+ NULL,
+ SIG_DIGEST,
+ 0,
+ EVP_sha256,
+ evp_md_verify_signature,
+ evp_md_create_signature,
+ 0
+};
+
+static const struct signature_alg sha1_alg = {
+ "sha1",
+ ASN1_OID_ID_SECSIG_SHA_1,
+ &_hx509_signature_sha1_data,
+ NULL,
+ NULL,
+ SIG_DIGEST,
+ 0,
+ EVP_sha1,
+ evp_md_verify_signature,
+ evp_md_create_signature,
+ 0
+};
+
+static const struct signature_alg md5_alg = {
+ "rsa-md5",
+ ASN1_OID_ID_RSA_DIGEST_MD5,
+ &_hx509_signature_md5_data,
+ NULL,
+ NULL,
+ SIG_DIGEST|WEAK_SIG_ALG,
+ 0,
+ EVP_md5,
+ evp_md_verify_signature,
+ NULL,
+ 0
+};
+
+/*
+ * Order matter in this structure, "best" first for each "key
+ * compatible" type (type is ECDSA, RSA, DSA, none, etc)
+ */
+
+static const struct signature_alg *sig_algs[] = {
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+ &ecdsa_with_sha512_alg,
+ &ecdsa_with_sha384_alg,
+ &ecdsa_with_sha256_alg,
+ &ecdsa_with_sha1_alg,
+#endif
+ &rsa_with_sha512_alg,
+ &rsa_with_sha384_alg,
+ &rsa_with_sha256_alg,
+ &rsa_with_sha1_alg,
+ &rsa_with_sha1_alg_secsig,
+ &pkcs1_rsa_sha1_alg,
+ &rsa_with_md5_alg,
+ &heim_rsa_pkcs1_x509,
+ &dsa_sha1_alg,
+ &sha512_alg,
+ &sha384_alg,
+ &sha256_alg,
+ &sha1_alg,
+ &md5_alg,
+ NULL
+};
+
+const struct signature_alg *
+_hx509_find_sig_alg(const heim_oid *oid)
+{
+ unsigned int i;
+ for (i = 0; sig_algs[i]; i++)
+ if (der_heim_oid_cmp(sig_algs[i]->sig_oid, oid) == 0)
+ return sig_algs[i];
+ return NULL;
+}
+
+static const AlgorithmIdentifier *
+alg_for_privatekey(const hx509_private_key pk, int type)
+{
+ const heim_oid *keytype;
+ unsigned int i;
+
+ if (pk->ops == NULL)
+ return NULL;
+
+ keytype = pk->ops->key_oid;
+
+ for (i = 0; sig_algs[i]; i++) {
+ if (sig_algs[i]->key_oid == NULL)
+ continue;
+ if (der_heim_oid_cmp(sig_algs[i]->key_oid, keytype) != 0)
+ continue;
+ if (pk->ops->available &&
+ pk->ops->available(pk, sig_algs[i]->sig_alg) == 0)
+ continue;
+ if (type == HX509_SELECT_PUBLIC_SIG)
+ return sig_algs[i]->sig_alg;
+ if (type == HX509_SELECT_DIGEST)
+ return sig_algs[i]->digest_alg;
+
+ return NULL;
+ }
+ return NULL;
+}
+
+/*
+ *
+ */
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+extern hx509_private_key_ops ecdsa_private_key_ops;
+#endif
+
+static struct hx509_private_key_ops *private_algs[] = {
+ &rsa_private_key_ops,
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+ &ecdsa_private_key_ops,
+#endif
+ NULL
+};
+
+HX509_LIB_FUNCTION hx509_private_key_ops * HX509_LIB_CALL
+hx509_find_private_alg(const heim_oid *oid)
+{
+ int i;
+ for (i = 0; private_algs[i]; i++) {
+ if (private_algs[i]->key_oid == NULL)
+ continue;
+ if (der_heim_oid_cmp(private_algs[i]->key_oid, oid) == 0)
+ return private_algs[i];
+ }
+ return NULL;
+}
+
+/*
+ * Check if the algorithm `alg' have a best before date, and if it
+ * des, make sure the its before the time `t'.
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_signature_is_weak(hx509_context context, const AlgorithmIdentifier *alg)
+{
+ const struct signature_alg *md;
+
+ md = _hx509_find_sig_alg(&alg->algorithm);
+ if (md == NULL) {
+ hx509_clear_error_string(context);
+ return HX509_SIG_ALG_NO_SUPPORTED;
+ }
+ if (md->flags & WEAK_SIG_ALG) {
+ hx509_set_error_string(context, 0, HX509_CRYPTO_ALGORITHM_BEST_BEFORE,
+ "Algorithm %s is weak", md->name);
+ return HX509_CRYPTO_ALGORITHM_BEST_BEFORE;
+ }
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_self_signed_valid(hx509_context context,
+ const AlgorithmIdentifier *alg)
+{
+ const struct signature_alg *md;
+
+ md = _hx509_find_sig_alg(&alg->algorithm);
+ if (md == NULL) {
+ hx509_clear_error_string(context);
+ return HX509_SIG_ALG_NO_SUPPORTED;
+ }
+ if ((md->flags & SELF_SIGNED_OK) == 0) {
+ hx509_set_error_string(context, 0, HX509_CRYPTO_ALGORITHM_BEST_BEFORE,
+ "Algorithm %s not trusted for self signatures",
+ md->name);
+ return HX509_CRYPTO_ALGORITHM_BEST_BEFORE;
+ }
+ return 0;
+}
+
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_verify_signature(hx509_context context,
+ const hx509_cert cert,
+ const AlgorithmIdentifier *alg,
+ const heim_octet_string *data,
+ const heim_octet_string *sig)
+{
+ const struct signature_alg *md;
+ const Certificate *signer = NULL;
+
+ if (cert)
+ signer = _hx509_get_cert(cert);
+
+ md = _hx509_find_sig_alg(&alg->algorithm);
+ if (md == NULL) {
+ hx509_clear_error_string(context);
+ return HX509_SIG_ALG_NO_SUPPORTED;
+ }
+ if (signer && (md->flags & PROVIDE_CONF) == 0) {
+ hx509_clear_error_string(context);
+ return HX509_CRYPTO_SIG_NO_CONF;
+ }
+ if (signer == NULL && (md->flags & REQUIRE_SIGNER)) {
+ hx509_clear_error_string(context);
+ return HX509_CRYPTO_SIGNATURE_WITHOUT_SIGNER;
+ }
+ if (md->key_oid && signer) {
+ const SubjectPublicKeyInfo *spi;
+ spi = &signer->tbsCertificate.subjectPublicKeyInfo;
+
+ if (der_heim_oid_cmp(&spi->algorithm.algorithm, md->key_oid) != 0) {
+ hx509_clear_error_string(context);
+ return HX509_SIG_ALG_DONT_MATCH_KEY_ALG;
+ }
+ }
+ return (*md->verify_signature)(context, md, signer, alg, data, sig);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_create_signature(hx509_context context,
+ const hx509_private_key signer,
+ const AlgorithmIdentifier *alg,
+ const heim_octet_string *data,
+ AlgorithmIdentifier *signatureAlgorithm,
+ heim_octet_string *sig)
+{
+ const struct signature_alg *md;
+
+ md = _hx509_find_sig_alg(&alg->algorithm);
+ if (md == NULL) {
+ hx509_set_error_string(context, 0, HX509_SIG_ALG_NO_SUPPORTED,
+ "algorithm no supported");
+ return HX509_SIG_ALG_NO_SUPPORTED;
+ }
+
+ if (signer && (md->flags & PROVIDE_CONF) == 0) {
+ hx509_set_error_string(context, 0, HX509_SIG_ALG_NO_SUPPORTED,
+ "algorithm provides no conf");
+ return HX509_CRYPTO_SIG_NO_CONF;
+ }
+
+ return (*md->create_signature)(context, md, signer, alg, data,
+ signatureAlgorithm, sig);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_create_signature_bitstring(hx509_context context,
+ const hx509_private_key signer,
+ const AlgorithmIdentifier *alg,
+ const heim_octet_string *data,
+ AlgorithmIdentifier *signatureAlgorithm,
+ heim_bit_string *sig)
+{
+ heim_octet_string os;
+ int ret;
+
+ ret = _hx509_create_signature(context, signer, alg,
+ data, signatureAlgorithm, &os);
+ if (ret)
+ return ret;
+ sig->data = os.data;
+ sig->length = os.length * 8;
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_public_encrypt(hx509_context context,
+ const heim_octet_string *cleartext,
+ const Certificate *cert,
+ heim_oid *encryption_oid,
+ heim_octet_string *ciphertext)
+{
+ const SubjectPublicKeyInfo *spi;
+ unsigned char *to;
+ int tosize;
+ int ret;
+ RSA *rsa;
+ size_t size;
+ const unsigned char *p;
+
+ ciphertext->data = NULL;
+ ciphertext->length = 0;
+
+ spi = &cert->tbsCertificate.subjectPublicKeyInfo;
+
+ p = spi->subjectPublicKey.data;
+ size = spi->subjectPublicKey.length / 8;
+
+ rsa = d2i_RSAPublicKey(NULL, &p, size);
+ if (rsa == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ tosize = RSA_size(rsa);
+ to = malloc(tosize);
+ if (to == NULL) {
+ RSA_free(rsa);
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ ret = RSA_public_encrypt(cleartext->length,
+ (unsigned char *)cleartext->data,
+ to, rsa, RSA_PKCS1_PADDING);
+ RSA_free(rsa);
+ if (ret <= 0) {
+ free(to);
+ hx509_set_error_string(context, 0, HX509_CRYPTO_RSA_PUBLIC_ENCRYPT,
+ "RSA public encrypt failed with %d", ret);
+ return HX509_CRYPTO_RSA_PUBLIC_ENCRYPT;
+ }
+ if (ret > tosize)
+ _hx509_abort("internal rsa decryption failure: ret > tosize");
+
+ ciphertext->length = ret;
+ ciphertext->data = to;
+
+ ret = der_copy_oid(ASN1_OID_ID_PKCS1_RSAENCRYPTION, encryption_oid);
+ if (ret) {
+ der_free_octet_string(ciphertext);
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_private_key_private_decrypt(hx509_context context,
+ const heim_octet_string *ciphertext,
+ const heim_oid *encryption_oid,
+ hx509_private_key p,
+ heim_octet_string *cleartext)
+{
+ int ret;
+
+ cleartext->data = NULL;
+ cleartext->length = 0;
+
+ if (p->private_key.rsa == NULL) {
+ hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING,
+ "Private RSA key missing");
+ return HX509_PRIVATE_KEY_MISSING;
+ }
+
+ cleartext->length = RSA_size(p->private_key.rsa);
+ cleartext->data = malloc(cleartext->length);
+ if (cleartext->data == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+ ret = RSA_private_decrypt(ciphertext->length, ciphertext->data,
+ cleartext->data,
+ p->private_key.rsa,
+ RSA_PKCS1_PADDING);
+ if (ret <= 0) {
+ der_free_octet_string(cleartext);
+ hx509_set_error_string(context, 0, HX509_CRYPTO_RSA_PRIVATE_DECRYPT,
+ "Failed to decrypt using private key: %d", ret);
+ return HX509_CRYPTO_RSA_PRIVATE_DECRYPT;
+ }
+ if (cleartext->length < (size_t)ret)
+ _hx509_abort("internal rsa decryption failure: ret > tosize");
+
+ cleartext->length = ret;
+
+ return 0;
+}
+
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_parse_private_key(hx509_context context,
+ const AlgorithmIdentifier *keyai,
+ const void *data,
+ size_t len,
+ hx509_key_format_t format,
+ hx509_private_key *private_key)
+{
+ struct hx509_private_key_ops *ops;
+ int ret;
+
+ *private_key = NULL;
+
+ if (format == HX509_KEY_FORMAT_PKCS8) {
+ PKCS8PrivateKeyInfo ki;
+ hx509_private_key key;
+
+ ret = decode_PKCS8PrivateKeyInfo(data, len, &ki, NULL);
+ if (ret) {
+ hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
+ "Failed to parse PKCS#8-encoded private "
+ "key");
+ return HX509_PARSING_KEY_FAILED;
+ }
+
+ /* Re-enter to parse DER-encoded key from PKCS#8 envelope */
+ ret = hx509_parse_private_key(context, &ki.privateKeyAlgorithm,
+ ki.privateKey.data, ki.privateKey.length,
+ HX509_KEY_FORMAT_DER, &key);
+ free_PKCS8PrivateKeyInfo(&ki);
+ if (ret) {
+ hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
+ "Failed to parse RSA key from PKCS#8 "
+ "envelope");
+ return HX509_PARSING_KEY_FAILED;
+ }
+
+ *private_key = key;
+ return ret;
+ }
+
+ ops = hx509_find_private_alg(&keyai->algorithm);
+ if (ops == NULL) {
+ hx509_clear_error_string(context);
+ return HX509_SIG_ALG_NO_SUPPORTED;
+ }
+
+ ret = hx509_private_key_init(private_key, ops, NULL);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ return ret;
+ }
+
+ ret = (*ops->import)(context, keyai, data, len, format, *private_key);
+ if (ret)
+ hx509_private_key_free(private_key);
+
+ return ret;
+}
+
+/*
+ *
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_private_key2SPKI(hx509_context context,
+ hx509_private_key private_key,
+ SubjectPublicKeyInfo *spki)
+{
+ const struct hx509_private_key_ops *ops = private_key->ops;
+ if (ops == NULL || ops->get_spki == NULL) {
+ hx509_set_error_string(context, 0, HX509_UNIMPLEMENTED_OPERATION,
+ "Private key have no key2SPKI function");
+ return HX509_UNIMPLEMENTED_OPERATION;
+ }
+ return (*ops->get_spki)(context, private_key, spki);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_generate_private_key_init(hx509_context context,
+ const heim_oid *oid,
+ struct hx509_generate_private_context **ctx)
+{
+ *ctx = NULL;
+
+ if (der_heim_oid_cmp(oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) != 0) {
+ hx509_set_error_string(context, 0, EINVAL,
+ "private key not an RSA key");
+ return EINVAL;
+ }
+
+ *ctx = calloc(1, sizeof(**ctx));
+ if (*ctx == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+ (*ctx)->key_oid = oid;
+
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_generate_private_key_is_ca(hx509_context context,
+ struct hx509_generate_private_context *ctx)
+{
+ ctx->isCA = 1;
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_generate_private_key_bits(hx509_context context,
+ struct hx509_generate_private_context *ctx,
+ unsigned long bits)
+{
+ ctx->num_bits = bits;
+ return 0;
+}
+
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_generate_private_key_free(struct hx509_generate_private_context **ctx)
+{
+ free(*ctx);
+ *ctx = NULL;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_generate_private_key(hx509_context context,
+ struct hx509_generate_private_context *ctx,
+ hx509_private_key *private_key)
+{
+ struct hx509_private_key_ops *ops;
+ int ret;
+
+ *private_key = NULL;
+
+ ops = hx509_find_private_alg(ctx->key_oid);
+ if (ops == NULL) {
+ hx509_clear_error_string(context);
+ return HX509_SIG_ALG_NO_SUPPORTED;
+ }
+
+ ret = hx509_private_key_init(private_key, ops, NULL);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ return ret;
+ }
+
+ ret = (*ops->generate_private_key)(context, ctx, *private_key);
+ if (ret)
+ hx509_private_key_free(private_key);
+
+ return ret;
+}
+
+/*
+ *
+ */
+
+const AlgorithmIdentifier *
+hx509_signature_sha512(void)
+{ return &_hx509_signature_sha512_data; }
+
+const AlgorithmIdentifier *
+hx509_signature_sha384(void)
+{ return &_hx509_signature_sha384_data; }
+
+const AlgorithmIdentifier *
+hx509_signature_sha256(void)
+{ return &_hx509_signature_sha256_data; }
+
+const AlgorithmIdentifier *
+hx509_signature_sha1(void)
+{ return &_hx509_signature_sha1_data; }
+
+const AlgorithmIdentifier *
+hx509_signature_md5(void)
+{ return &_hx509_signature_md5_data; }
+
+const AlgorithmIdentifier *
+hx509_signature_rsa_with_sha512(void)
+{ return &_hx509_signature_rsa_with_sha512_data; }
+
+const AlgorithmIdentifier *
+hx509_signature_rsa_with_sha384(void)
+{ return &_hx509_signature_rsa_with_sha384_data; }
+
+const AlgorithmIdentifier *
+hx509_signature_rsa_with_sha256(void)
+{ return &_hx509_signature_rsa_with_sha256_data; }
+
+const AlgorithmIdentifier *
+hx509_signature_rsa_with_sha1(void)
+{ return &_hx509_signature_rsa_with_sha1_data; }
+
+const AlgorithmIdentifier *
+hx509_signature_rsa_with_md5(void)
+{ return &_hx509_signature_rsa_with_md5_data; }
+
+const AlgorithmIdentifier *
+hx509_signature_rsa(void)
+{ return &_hx509_signature_rsa_data; }
+
+const AlgorithmIdentifier *
+hx509_signature_rsa_pkcs1_x509(void)
+{ return &_hx509_signature_rsa_pkcs1_x509_data; }
+
+const AlgorithmIdentifier *
+hx509_crypto_des_rsdi_ede3_cbc(void)
+{ return &_hx509_des_rsdi_ede3_cbc_oid; }
+
+const AlgorithmIdentifier *
+hx509_crypto_aes128_cbc(void)
+{ return &_hx509_crypto_aes128_cbc_data; }
+
+const AlgorithmIdentifier *
+hx509_crypto_aes256_cbc(void)
+{ return &_hx509_crypto_aes256_cbc_data; }
+
+/*
+ *
+ */
+
+const AlgorithmIdentifier * _hx509_crypto_default_sig_alg =
+ &_hx509_signature_rsa_with_sha256_data;
+const AlgorithmIdentifier * _hx509_crypto_default_digest_alg =
+ &_hx509_signature_sha256_data;
+const AlgorithmIdentifier * _hx509_crypto_default_secret_alg =
+ &_hx509_crypto_aes128_cbc_data;
+
+/*
+ *
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_private_key_init(hx509_private_key *key,
+ hx509_private_key_ops *ops,
+ void *keydata)
+{
+ *key = calloc(1, sizeof(**key));
+ if (*key == NULL)
+ return ENOMEM;
+ (*key)->ref = 1;
+ (*key)->ops = ops;
+ (*key)->private_key.keydata = keydata;
+ return 0;
+}
+
+HX509_LIB_FUNCTION hx509_private_key HX509_LIB_CALL
+_hx509_private_key_ref(hx509_private_key key)
+{
+ if (key->ref == 0)
+ _hx509_abort("key refcount <= 0 on ref");
+ key->ref++;
+ if (key->ref == UINT_MAX)
+ _hx509_abort("key refcount == UINT_MAX on ref");
+ return key;
+}
+
+HX509_LIB_FUNCTION const char * HX509_LIB_CALL
+_hx509_private_pem_name(hx509_private_key key)
+{
+ return key->ops->pemtype;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_private_key_free(hx509_private_key *key)
+{
+ if (key == NULL || *key == NULL)
+ return 0;
+
+ if ((*key)->ref == 0)
+ _hx509_abort("key refcount == 0 on free");
+ if (--(*key)->ref > 0)
+ return 0;
+
+ if ((*key)->ops && der_heim_oid_cmp((*key)->ops->key_oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) == 0) {
+ if ((*key)->private_key.rsa)
+ RSA_free((*key)->private_key.rsa);
+ } else if ((*key)->ops && der_heim_oid_cmp((*key)->ops->key_oid,
+ ASN1_OID_ID_ECPUBLICKEY) == 0 &&
+ (*key)->private_key.ecdsa != NULL) {
+ _hx509_private_eckey_free((*key)->private_key.ecdsa);
+ }
+ (*key)->private_key.rsa = NULL;
+ free(*key);
+ *key = NULL;
+ return 0;
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_private_key_assign_rsa(hx509_private_key key, void *ptr)
+{
+ if (key->private_key.rsa)
+ RSA_free(key->private_key.rsa);
+ key->private_key.rsa = ptr;
+ key->signature_alg = ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION;
+ key->md = &pkcs1_rsa_sha1_alg;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_private_key_oid(hx509_context context,
+ const hx509_private_key key,
+ heim_oid *data)
+{
+ int ret;
+ ret = der_copy_oid(key->ops->key_oid, data);
+ if (ret)
+ hx509_set_error_string(context, 0, ret, "malloc out of memory");
+ return ret;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_private_key_exportable(hx509_private_key key)
+{
+ if (key->ops->export == NULL)
+ return 0;
+ return 1;
+}
+
+HX509_LIB_FUNCTION BIGNUM * HX509_LIB_CALL
+_hx509_private_key_get_internal(hx509_context context,
+ hx509_private_key key,
+ const char *type)
+{
+ if (key->ops->get_internal == NULL)
+ return NULL;
+ return (*key->ops->get_internal)(context, key, type);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_private_key_export(hx509_context context,
+ const hx509_private_key key,
+ hx509_key_format_t format,
+ heim_octet_string *data)
+{
+ data->length = 0;
+ data->data = NULL;
+ if (key->ops->export == NULL) {
+ hx509_clear_error_string(context);
+ return HX509_UNIMPLEMENTED_OPERATION;
+ }
+ if (format == HX509_KEY_FORMAT_PKCS8) {
+ PKCS8PrivateKeyInfo ki;
+ size_t size;
+ int ret;
+
+ memset(&ki, 0, sizeof(ki));
+ ki.attributes = NULL; /* No localKeyId needed */
+ ki.privateKey.data = NULL;
+ ki.privateKeyAlgorithm.algorithm.components = NULL;
+ ret = der_parse_hex_heim_integer("00", &ki.version);
+ if (ret == 0)
+ ret = _hx509_private_key_oid(context, key,
+ &ki.privateKeyAlgorithm.algorithm);
+ if (ret == 0)
+ /* Re-enter */
+ ret = _hx509_private_key_export(context, key, HX509_KEY_FORMAT_DER,
+ &ki.privateKey);
+
+ /*
+ * XXX To set ki.privateKeyAlgorithm.parameters we'll need to either
+ * move this code into the *key->ops->export() functions, or expand
+ * their signature to allow them to set it for us, or add a method to
+ * hx509_private_key_ops that allows us to get the parameters from the
+ * backend.
+ */
+ ki.privateKeyAlgorithm.parameters = NULL;
+
+ if (ret == 0)
+ ASN1_MALLOC_ENCODE(PKCS8PrivateKeyInfo, data->data, data->length,
+ &ki, &size, ret);
+ free_PKCS8PrivateKeyInfo(&ki);
+ if (ret == 0 && size != data->length)
+ ret = EINVAL;
+ if (ret)
+ hx509_set_error_string(context, 0, ret,
+ "Private key PKCS#8 encoding failed");
+ return ret;
+ }
+ return (*key->ops->export)(context, key, format, data);
+}
+
+/*
+ *
+ */
+
+struct hx509cipher {
+ const char *name;
+ int flags;
+#define CIPHER_WEAK 1
+ const heim_oid *oid;
+ const AlgorithmIdentifier *(*ai_func)(void);
+ const EVP_CIPHER *(*evp_func)(void);
+ int (*get_params)(hx509_context, const hx509_crypto,
+ const heim_octet_string *, heim_octet_string *);
+ int (*set_params)(hx509_context, const heim_octet_string *,
+ hx509_crypto, heim_octet_string *);
+};
+
+struct hx509_crypto_data {
+ char *name;
+ int flags;
+#define ALLOW_WEAK 1
+
+#define PADDING_NONE 2
+#define PADDING_PKCS7 4
+#define PADDING_FLAGS (2|4)
+ const struct hx509cipher *cipher;
+ const EVP_CIPHER *c;
+ heim_octet_string key;
+ heim_oid oid;
+ void *param;
+};
+
+/*
+ *
+ */
+
+static unsigned private_rc2_40_oid_data[] = { 127, 1 };
+
+static heim_oid asn1_oid_private_rc2_40 =
+ { 2, private_rc2_40_oid_data };
+
+/*
+ *
+ */
+
+static int
+CMSCBCParam_get(hx509_context context, const hx509_crypto crypto,
+ const heim_octet_string *ivec, heim_octet_string *param)
+{
+ size_t size;
+ int ret;
+
+ assert(crypto->param == NULL);
+ if (ivec == NULL)
+ return 0;
+
+ ASN1_MALLOC_ENCODE(CMSCBCParameter, param->data, param->length,
+ ivec, &size, ret);
+ if (ret == 0 && size != param->length)
+ _hx509_abort("Internal asn1 encoder failure");
+ if (ret)
+ hx509_clear_error_string(context);
+ return ret;
+}
+
+static int
+CMSCBCParam_set(hx509_context context, const heim_octet_string *param,
+ hx509_crypto crypto, heim_octet_string *ivec)
+{
+ int ret;
+ if (ivec == NULL)
+ return 0;
+
+ ret = decode_CMSCBCParameter(param->data, param->length, ivec, NULL);
+ if (ret)
+ hx509_clear_error_string(context);
+
+ return ret;
+}
+
+struct _RC2_params {
+ int maximum_effective_key;
+};
+
+static int
+CMSRC2CBCParam_get(hx509_context context, const hx509_crypto crypto,
+ const heim_octet_string *ivec, heim_octet_string *param)
+{
+ CMSRC2CBCParameter rc2params;
+ const struct _RC2_params *p = crypto->param;
+ int maximum_effective_key = 128;
+ size_t size;
+ int ret;
+
+ memset(&rc2params, 0, sizeof(rc2params));
+
+ if (p)
+ maximum_effective_key = p->maximum_effective_key;
+
+ switch(maximum_effective_key) {
+ case 40:
+ rc2params.rc2ParameterVersion = 160;
+ break;
+ case 64:
+ rc2params.rc2ParameterVersion = 120;
+ break;
+ case 128:
+ rc2params.rc2ParameterVersion = 58;
+ break;
+ }
+ rc2params.iv = *ivec;
+
+ ASN1_MALLOC_ENCODE(CMSRC2CBCParameter, param->data, param->length,
+ &rc2params, &size, ret);
+ if (ret == 0 && size != param->length)
+ _hx509_abort("Internal asn1 encoder failure");
+
+ return ret;
+}
+
+static int
+CMSRC2CBCParam_set(hx509_context context, const heim_octet_string *param,
+ hx509_crypto crypto, heim_octet_string *ivec)
+{
+ CMSRC2CBCParameter rc2param;
+ struct _RC2_params *p;
+ size_t size;
+ int ret;
+
+ ret = decode_CMSRC2CBCParameter(param->data, param->length,
+ &rc2param, &size);
+ if (ret) {
+ hx509_clear_error_string(context);
+ return ret;
+ }
+
+ p = calloc(1, sizeof(*p));
+ if (p == NULL) {
+ free_CMSRC2CBCParameter(&rc2param);
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+ switch(rc2param.rc2ParameterVersion) {
+ case 160:
+ crypto->c = EVP_rc2_40_cbc();
+ p->maximum_effective_key = 40;
+ break;
+ case 120:
+ crypto->c = EVP_rc2_64_cbc();
+ p->maximum_effective_key = 64;
+ break;
+ case 58:
+ crypto->c = EVP_rc2_cbc();
+ p->maximum_effective_key = 128;
+ break;
+ default:
+ free(p);
+ free_CMSRC2CBCParameter(&rc2param);
+ return HX509_CRYPTO_SIG_INVALID_FORMAT;
+ }
+ if (ivec)
+ ret = der_copy_octet_string(&rc2param.iv, ivec);
+ free_CMSRC2CBCParameter(&rc2param);
+ if (ret) {
+ free(p);
+ hx509_clear_error_string(context);
+ } else
+ crypto->param = p;
+
+ return ret;
+}
+
+/*
+ *
+ */
+
+static const struct hx509cipher ciphers[] = {
+ {
+ "rc2-cbc",
+ CIPHER_WEAK,
+ ASN1_OID_ID_PKCS3_RC2_CBC,
+ NULL,
+ EVP_rc2_cbc,
+ CMSRC2CBCParam_get,
+ CMSRC2CBCParam_set
+ },
+ {
+ "rc2-cbc",
+ CIPHER_WEAK,
+ ASN1_OID_ID_RSADSI_RC2_CBC,
+ NULL,
+ EVP_rc2_cbc,
+ CMSRC2CBCParam_get,
+ CMSRC2CBCParam_set
+ },
+ {
+ "rc2-40-cbc",
+ CIPHER_WEAK,
+ &asn1_oid_private_rc2_40,
+ NULL,
+ EVP_rc2_40_cbc,
+ CMSRC2CBCParam_get,
+ CMSRC2CBCParam_set
+ },
+ {
+ "des-ede3-cbc",
+ 0,
+ ASN1_OID_ID_PKCS3_DES_EDE3_CBC,
+ NULL,
+ EVP_des_ede3_cbc,
+ CMSCBCParam_get,
+ CMSCBCParam_set
+ },
+ {
+ "des-ede3-cbc",
+ 0,
+ ASN1_OID_ID_RSADSI_DES_EDE3_CBC,
+ hx509_crypto_des_rsdi_ede3_cbc,
+ EVP_des_ede3_cbc,
+ CMSCBCParam_get,
+ CMSCBCParam_set
+ },
+ {
+ "aes-128-cbc",
+ 0,
+ ASN1_OID_ID_AES_128_CBC,
+ hx509_crypto_aes128_cbc,
+ EVP_aes_128_cbc,
+ CMSCBCParam_get,
+ CMSCBCParam_set
+ },
+ {
+ "aes-192-cbc",
+ 0,
+ ASN1_OID_ID_AES_192_CBC,
+ NULL,
+ EVP_aes_192_cbc,
+ CMSCBCParam_get,
+ CMSCBCParam_set
+ },
+ {
+ "aes-256-cbc",
+ 0,
+ ASN1_OID_ID_AES_256_CBC,
+ hx509_crypto_aes256_cbc,
+ EVP_aes_256_cbc,
+ CMSCBCParam_get,
+ CMSCBCParam_set
+ }
+};
+
+static const struct hx509cipher *
+find_cipher_by_oid(const heim_oid *oid)
+{
+ size_t i;
+
+ for (i = 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++)
+ if (der_heim_oid_cmp(oid, ciphers[i].oid) == 0)
+ return &ciphers[i];
+
+ return NULL;
+}
+
+static const struct hx509cipher *
+find_cipher_by_name(const char *name)
+{
+ size_t i;
+
+ for (i = 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++)
+ if (strcasecmp(name, ciphers[i].name) == 0)
+ return &ciphers[i];
+
+ return NULL;
+}
+
+
+HX509_LIB_FUNCTION const heim_oid * HX509_LIB_CALL
+hx509_crypto_enctype_by_name(const char *name)
+{
+ const struct hx509cipher *cipher;
+
+ cipher = find_cipher_by_name(name);
+ if (cipher == NULL)
+ return NULL;
+ return cipher->oid;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crypto_init(hx509_context context,
+ const char *provider,
+ const heim_oid *enctype,
+ hx509_crypto *crypto)
+{
+ const struct hx509cipher *cipher;
+
+ *crypto = NULL;
+
+ cipher = find_cipher_by_oid(enctype);
+ if (cipher == NULL) {
+ hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
+ "Algorithm not supported");
+ return HX509_ALG_NOT_SUPP;
+ }
+
+ *crypto = calloc(1, sizeof(**crypto));
+ if (*crypto == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+
+ (*crypto)->flags = PADDING_PKCS7;
+ (*crypto)->cipher = cipher;
+ (*crypto)->c = (*cipher->evp_func)();
+
+ if (der_copy_oid(enctype, &(*crypto)->oid)) {
+ hx509_crypto_destroy(*crypto);
+ *crypto = NULL;
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+
+ return 0;
+}
+
+HX509_LIB_FUNCTION const char * HX509_LIB_CALL
+hx509_crypto_provider(hx509_crypto crypto)
+{
+ return "unknown";
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_crypto_destroy(hx509_crypto crypto)
+{
+ if (crypto->name)
+ free(crypto->name);
+ if (crypto->key.data)
+ free(crypto->key.data);
+ if (crypto->param)
+ free(crypto->param);
+ der_free_oid(&crypto->oid);
+ memset(crypto, 0, sizeof(*crypto));
+ free(crypto);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crypto_set_key_name(hx509_crypto crypto, const char *name)
+{
+ return 0;
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_crypto_allow_weak(hx509_crypto crypto)
+{
+ crypto->flags |= ALLOW_WEAK;
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_crypto_set_padding(hx509_crypto crypto, int padding_type)
+{
+ switch (padding_type) {
+ case HX509_CRYPTO_PADDING_PKCS7:
+ crypto->flags &= ~PADDING_FLAGS;
+ crypto->flags |= PADDING_PKCS7;
+ break;
+ case HX509_CRYPTO_PADDING_NONE:
+ crypto->flags &= ~PADDING_FLAGS;
+ crypto->flags |= PADDING_NONE;
+ break;
+ default:
+ _hx509_abort("Invalid padding");
+ }
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crypto_set_key_data(hx509_crypto crypto, const void *data, size_t length)
+{
+ if (EVP_CIPHER_key_length(crypto->c) > (int)length)
+ return HX509_CRYPTO_INTERNAL_ERROR;
+
+ if (crypto->key.data) {
+ free(crypto->key.data);
+ crypto->key.data = NULL;
+ crypto->key.length = 0;
+ }
+ crypto->key.data = malloc(length);
+ if (crypto->key.data == NULL)
+ return ENOMEM;
+ memcpy(crypto->key.data, data, length);
+ crypto->key.length = length;
+
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crypto_set_random_key(hx509_crypto crypto, heim_octet_string *key)
+{
+ if (crypto->key.data) {
+ free(crypto->key.data);
+ crypto->key.length = 0;
+ }
+
+ crypto->key.length = EVP_CIPHER_key_length(crypto->c);
+ crypto->key.data = malloc(crypto->key.length);
+ if (crypto->key.data == NULL) {
+ crypto->key.length = 0;
+ return ENOMEM;
+ }
+ if (RAND_bytes(crypto->key.data, crypto->key.length) <= 0) {
+ free(crypto->key.data);
+ crypto->key.data = NULL;
+ crypto->key.length = 0;
+ return HX509_CRYPTO_INTERNAL_ERROR;
+ }
+ if (key)
+ return der_copy_octet_string(&crypto->key, key);
+ else
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crypto_set_params(hx509_context context,
+ hx509_crypto crypto,
+ const heim_octet_string *param,
+ heim_octet_string *ivec)
+{
+ return (*crypto->cipher->set_params)(context, param, crypto, ivec);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crypto_get_params(hx509_context context,
+ hx509_crypto crypto,
+ const heim_octet_string *ivec,
+ heim_octet_string *param)
+{
+ return (*crypto->cipher->get_params)(context, crypto, ivec, param);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crypto_random_iv(hx509_crypto crypto, heim_octet_string *ivec)
+{
+ ivec->length = EVP_CIPHER_iv_length(crypto->c);
+ ivec->data = malloc(ivec->length);
+ if (ivec->data == NULL) {
+ ivec->length = 0;
+ return ENOMEM;
+ }
+
+ if (RAND_bytes(ivec->data, ivec->length) <= 0) {
+ free(ivec->data);
+ ivec->data = NULL;
+ ivec->length = 0;
+ return HX509_CRYPTO_INTERNAL_ERROR;
+ }
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crypto_encrypt(hx509_crypto crypto,
+ const void *data,
+ const size_t length,
+ const heim_octet_string *ivec,
+ heim_octet_string **ciphertext)
+{
+ EVP_CIPHER_CTX evp;
+ size_t padsize, bsize;
+ int ret;
+
+ *ciphertext = NULL;
+
+ if ((crypto->cipher->flags & CIPHER_WEAK) &&
+ (crypto->flags & ALLOW_WEAK) == 0)
+ return HX509_CRYPTO_ALGORITHM_BEST_BEFORE;
+
+ assert(EVP_CIPHER_iv_length(crypto->c) == (int)ivec->length);
+
+ EVP_CIPHER_CTX_init(&evp);
+
+ ret = EVP_CipherInit_ex(&evp, crypto->c, NULL,
+ crypto->key.data, ivec->data, 1);
+ if (ret != 1) {
+ EVP_CIPHER_CTX_cleanup(&evp);
+ ret = HX509_CRYPTO_INTERNAL_ERROR;
+ goto out;
+ }
+
+ *ciphertext = calloc(1, sizeof(**ciphertext));
+ if (*ciphertext == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ assert(crypto->flags & PADDING_FLAGS);
+
+ bsize = EVP_CIPHER_block_size(crypto->c);
+ padsize = 0;
+
+ if (crypto->flags & PADDING_NONE) {
+ if (bsize != 1 && (length % bsize) != 0)
+ return HX509_CMS_PADDING_ERROR;
+ } else if (crypto->flags & PADDING_PKCS7) {
+ if (bsize != 1)
+ padsize = bsize - (length % bsize);
+ }
+
+ (*ciphertext)->length = length + padsize;
+ (*ciphertext)->data = malloc(length + padsize);
+ if ((*ciphertext)->data == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ memcpy((*ciphertext)->data, data, length);
+ if (padsize) {
+ size_t i;
+ unsigned char *p = (*ciphertext)->data;
+ p += length;
+ for (i = 0; i < padsize; i++)
+ *p++ = padsize;
+ }
+
+ ret = EVP_Cipher(&evp, (*ciphertext)->data,
+ (*ciphertext)->data,
+ length + padsize);
+ if (ret != 1) {
+ ret = HX509_CRYPTO_INTERNAL_ERROR;
+ goto out;
+ }
+ ret = 0;
+
+ out:
+ if (ret) {
+ if (*ciphertext) {
+ if ((*ciphertext)->data) {
+ free((*ciphertext)->data);
+ }
+ free(*ciphertext);
+ *ciphertext = NULL;
+ }
+ }
+ EVP_CIPHER_CTX_cleanup(&evp);
+
+ return ret;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crypto_decrypt(hx509_crypto crypto,
+ const void *data,
+ const size_t length,
+ heim_octet_string *ivec,
+ heim_octet_string *clear)
+{
+ EVP_CIPHER_CTX evp;
+ void *idata = NULL;
+ int ret;
+
+ clear->data = NULL;
+ clear->length = 0;
+
+ if ((crypto->cipher->flags & CIPHER_WEAK) &&
+ (crypto->flags & ALLOW_WEAK) == 0)
+ return HX509_CRYPTO_ALGORITHM_BEST_BEFORE;
+
+ if (ivec && EVP_CIPHER_iv_length(crypto->c) < (int)ivec->length)
+ return HX509_CRYPTO_INTERNAL_ERROR;
+
+ if (crypto->key.data == NULL)
+ return HX509_CRYPTO_INTERNAL_ERROR;
+
+ if (ivec)
+ idata = ivec->data;
+
+ EVP_CIPHER_CTX_init(&evp);
+
+ ret = EVP_CipherInit_ex(&evp, crypto->c, NULL,
+ crypto->key.data, idata, 0);
+ if (ret != 1) {
+ EVP_CIPHER_CTX_cleanup(&evp);
+ return HX509_CRYPTO_INTERNAL_ERROR;
+ }
+
+ clear->length = length;
+ clear->data = malloc(length);
+ if (clear->data == NULL) {
+ EVP_CIPHER_CTX_cleanup(&evp);
+ clear->length = 0;
+ return ENOMEM;
+ }
+
+ if (EVP_Cipher(&evp, clear->data, data, length) != 1) {
+ return HX509_CRYPTO_INTERNAL_ERROR;
+ }
+ EVP_CIPHER_CTX_cleanup(&evp);
+
+ if ((crypto->flags & PADDING_PKCS7) && EVP_CIPHER_block_size(crypto->c) > 1) {
+ int padsize;
+ unsigned char *p;
+ int j, bsize = EVP_CIPHER_block_size(crypto->c);
+
+ if ((int)clear->length < bsize) {
+ ret = HX509_CMS_PADDING_ERROR;
+ goto out;
+ }
+
+ p = clear->data;
+ p += clear->length - 1;
+ padsize = *p;
+ if (padsize > bsize) {
+ ret = HX509_CMS_PADDING_ERROR;
+ goto out;
+ }
+ clear->length -= padsize;
+ for (j = 0; j < padsize; j++) {
+ if (*p-- != padsize) {
+ ret = HX509_CMS_PADDING_ERROR;
+ goto out;
+ }
+ }
+ }
+
+ return 0;
+
+ out:
+ if (clear->data)
+ free(clear->data);
+ clear->data = NULL;
+ clear->length = 0;
+ return ret;
+}
+
+typedef int (*PBE_string2key_func)(hx509_context,
+ const char *,
+ const heim_octet_string *,
+ hx509_crypto *, heim_octet_string *,
+ heim_octet_string *,
+ const heim_oid *, const EVP_MD *);
+
+static int
+PBE_string2key(hx509_context context,
+ const char *password,
+ const heim_octet_string *parameters,
+ hx509_crypto *crypto,
+ heim_octet_string *key, heim_octet_string *iv,
+ const heim_oid *enc_oid,
+ const EVP_MD *md)
+{
+ PKCS12_PBEParams p12params;
+ int passwordlen;
+ hx509_crypto c;
+ int iter, saltlen, ret;
+ unsigned char *salt;
+
+ passwordlen = password ? strlen(password) : 0;
+
+ if (parameters == NULL)
+ return HX509_ALG_NOT_SUPP;
+
+ ret = decode_PKCS12_PBEParams(parameters->data,
+ parameters->length,
+ &p12params, NULL);
+ if (ret)
+ goto out;
+
+ if (p12params.iterations)
+ iter = *p12params.iterations;
+ else
+ iter = 1;
+ salt = p12params.salt.data;
+ saltlen = p12params.salt.length;
+
+ if (!PKCS12_key_gen (password, passwordlen, salt, saltlen,
+ PKCS12_KEY_ID, iter, key->length, key->data, md)) {
+ ret = HX509_CRYPTO_INTERNAL_ERROR;
+ goto out;
+ }
+
+ if (!PKCS12_key_gen (password, passwordlen, salt, saltlen,
+ PKCS12_IV_ID, iter, iv->length, iv->data, md)) {
+ ret = HX509_CRYPTO_INTERNAL_ERROR;
+ goto out;
+ }
+
+ ret = hx509_crypto_init(context, NULL, enc_oid, &c);
+ if (ret)
+ goto out;
+
+ hx509_crypto_allow_weak(c);
+
+ ret = hx509_crypto_set_key_data(c, key->data, key->length);
+ if (ret) {
+ hx509_crypto_destroy(c);
+ goto out;
+ }
+
+ *crypto = c;
+out:
+ free_PKCS12_PBEParams(&p12params);
+ return ret;
+}
+
+static const heim_oid *
+find_string2key(const heim_oid *oid,
+ const EVP_CIPHER **c,
+ const EVP_MD **md,
+ PBE_string2key_func *s2k)
+{
+ if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND40BITRC2_CBC) == 0) {
+ *c = EVP_rc2_40_cbc();
+ if (*c == NULL)
+ return NULL;
+ *md = EVP_sha1();
+ if (*md == NULL)
+ return NULL;
+ *s2k = PBE_string2key;
+ return &asn1_oid_private_rc2_40;
+ } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND128BITRC2_CBC) == 0) {
+ *c = EVP_rc2_cbc();
+ if (*c == NULL)
+ return NULL;
+ *md = EVP_sha1();
+ if (*md == NULL)
+ return NULL;
+ *s2k = PBE_string2key;
+ return ASN1_OID_ID_PKCS3_RC2_CBC;
+#if 0
+ } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND40BITRC4) == 0) {
+ *c = EVP_rc4_40();
+ if (*c == NULL)
+ return NULL;
+ *md = EVP_sha1();
+ if (*md == NULL)
+ return NULL;
+ *s2k = PBE_string2key;
+ return NULL;
+ } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND128BITRC4) == 0) {
+ *c = EVP_rc4();
+ if (*c == NULL)
+ return NULL;
+ *md = EVP_sha1();
+ if (*md == NULL)
+ return NULL;
+ *s2k = PBE_string2key;
+ return ASN1_OID_ID_PKCS3_RC4;
+#endif
+ } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND3_KEYTRIPLEDES_CBC) == 0) {
+ *c = EVP_des_ede3_cbc();
+ if (*c == NULL)
+ return NULL;
+ *md = EVP_sha1();
+ if (*md == NULL)
+ return NULL;
+ *s2k = PBE_string2key;
+ return ASN1_OID_ID_PKCS3_DES_EDE3_CBC;
+ }
+
+ return NULL;
+}
+
+/*
+ *
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_pbe_encrypt(hx509_context context,
+ hx509_lock lock,
+ const AlgorithmIdentifier *ai,
+ const heim_octet_string *content,
+ heim_octet_string *econtent)
+{
+ hx509_clear_error_string(context);
+ return EINVAL;
+}
+
+/*
+ *
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_pbe_decrypt(hx509_context context,
+ hx509_lock lock,
+ const AlgorithmIdentifier *ai,
+ const heim_octet_string *econtent,
+ heim_octet_string *content)
+{
+ const struct _hx509_password *pw;
+ heim_octet_string key, iv;
+ const heim_oid *enc_oid;
+ const EVP_CIPHER *c;
+ const EVP_MD *md;
+ PBE_string2key_func s2k;
+ int ret = 0;
+ size_t i;
+
+ memset(&key, 0, sizeof(key));
+ memset(&iv, 0, sizeof(iv));
+
+ memset(content, 0, sizeof(*content));
+
+ enc_oid = find_string2key(&ai->algorithm, &c, &md, &s2k);
+ if (enc_oid == NULL) {
+ hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
+ "String to key algorithm not supported");
+ ret = HX509_ALG_NOT_SUPP;
+ goto out;
+ }
+
+ key.length = EVP_CIPHER_key_length(c);
+ key.data = malloc(key.length);
+ if (key.data == NULL) {
+ ret = ENOMEM;
+ hx509_clear_error_string(context);
+ goto out;
+ }
+
+ iv.length = EVP_CIPHER_iv_length(c);
+ iv.data = malloc(iv.length);
+ if (iv.data == NULL) {
+ ret = ENOMEM;
+ hx509_clear_error_string(context);
+ goto out;
+ }
+
+ pw = _hx509_lock_get_passwords(lock);
+
+ ret = HX509_CRYPTO_INTERNAL_ERROR;
+ for (i = 0; i < pw->len + 1; i++) {
+ hx509_crypto crypto;
+ const char *password;
+
+ if (i < pw->len)
+ password = pw->val[i];
+ else if (i < pw->len + 1)
+ password = "";
+ else
+ password = NULL;
+
+ ret = (*s2k)(context, password, ai->parameters, &crypto,
+ &key, &iv, enc_oid, md);
+ if (ret)
+ goto out;
+
+ ret = hx509_crypto_decrypt(crypto,
+ econtent->data,
+ econtent->length,
+ &iv,
+ content);
+ hx509_crypto_destroy(crypto);
+ if (ret == 0)
+ goto out;
+
+ }
+out:
+ if (key.data)
+ der_free_octet_string(&key);
+ if (iv.data)
+ der_free_octet_string(&iv);
+ return ret;
+}
+
+/*
+ *
+ */
+
+
+static int
+match_keys_rsa(hx509_cert c, hx509_private_key private_key)
+{
+ const Certificate *cert;
+ const SubjectPublicKeyInfo *spi;
+ RSAPublicKey pk;
+ RSA *rsa;
+ size_t size;
+ int ret;
+
+ if (private_key->private_key.rsa == NULL)
+ return 0;
+
+ rsa = private_key->private_key.rsa;
+ if (rsa->d == NULL || rsa->p == NULL || rsa->q == NULL)
+ return 0;
+
+ cert = _hx509_get_cert(c);
+ spi = &cert->tbsCertificate.subjectPublicKeyInfo;
+
+ rsa = RSA_new();
+ if (rsa == NULL)
+ return 0;
+
+ ret = decode_RSAPublicKey(spi->subjectPublicKey.data,
+ spi->subjectPublicKey.length / 8,
+ &pk, &size);
+ if (ret) {
+ RSA_free(rsa);
+ return 0;
+ }
+ rsa->n = heim_int2BN(&pk.modulus);
+ rsa->e = heim_int2BN(&pk.publicExponent);
+
+ free_RSAPublicKey(&pk);
+
+ rsa->d = BN_dup(private_key->private_key.rsa->d);
+ rsa->p = BN_dup(private_key->private_key.rsa->p);
+ rsa->q = BN_dup(private_key->private_key.rsa->q);
+ rsa->dmp1 = BN_dup(private_key->private_key.rsa->dmp1);
+ rsa->dmq1 = BN_dup(private_key->private_key.rsa->dmq1);
+ rsa->iqmp = BN_dup(private_key->private_key.rsa->iqmp);
+
+ if (rsa->n == NULL || rsa->e == NULL ||
+ rsa->d == NULL || rsa->p == NULL|| rsa->q == NULL ||
+ rsa->dmp1 == NULL || rsa->dmq1 == NULL) {
+ RSA_free(rsa);
+ return 0;
+ }
+
+ ret = RSA_check_key(rsa);
+ RSA_free(rsa);
+
+ return ret == 1;
+}
+
+static int
+match_keys_ec(hx509_cert c, hx509_private_key private_key)
+{
+ return 1; /* XXX use EC_KEY_check_key */
+}
+
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_match_keys(hx509_cert c, hx509_private_key key)
+{
+ if (!key->ops)
+ return 0;
+ if (der_heim_oid_cmp(key->ops->key_oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) == 0)
+ return match_keys_rsa(c, key);
+ if (der_heim_oid_cmp(key->ops->key_oid, ASN1_OID_ID_ECPUBLICKEY) == 0)
+ return match_keys_ec(c, key);
+ return 0;
+
+}
+
+
+static const heim_oid *
+find_keytype(const hx509_private_key key)
+{
+ const struct signature_alg *md;
+
+ if (key == NULL)
+ return NULL;
+
+ md = _hx509_find_sig_alg(key->signature_alg);
+ if (md == NULL)
+ return NULL;
+ return md->key_oid;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crypto_select(const hx509_context context,
+ int type,
+ const hx509_private_key source,
+ hx509_peer_info peer,
+ AlgorithmIdentifier *selected)
+{
+ const AlgorithmIdentifier *def = NULL;
+ size_t i, j;
+ int ret, bits;
+
+ memset(selected, 0, sizeof(*selected));
+
+ if (type == HX509_SELECT_DIGEST) {
+ bits = SIG_DIGEST;
+ if (source)
+ def = alg_for_privatekey(source, type);
+ if (def == NULL)
+ def = _hx509_crypto_default_digest_alg;
+ } else if (type == HX509_SELECT_PUBLIC_SIG) {
+ bits = SIG_PUBLIC_SIG;
+ /* XXX depend on `source´ and `peer´ */
+ if (source)
+ def = alg_for_privatekey(source, type);
+ if (def == NULL)
+ def = _hx509_crypto_default_sig_alg;
+ } else if (type == HX509_SELECT_SECRET_ENC) {
+ bits = SIG_SECRET;
+ def = _hx509_crypto_default_secret_alg;
+ } else {
+ hx509_set_error_string(context, 0, EINVAL,
+ "Unknown type %d of selection", type);
+ return EINVAL;
+ }
+
+ if (peer) {
+ const heim_oid *keytype = NULL;
+
+ keytype = find_keytype(source);
+
+ for (i = 0; i < peer->len; i++) {
+ for (j = 0; sig_algs[j]; j++) {
+ if ((sig_algs[j]->flags & bits) != bits)
+ continue;
+ if (der_heim_oid_cmp(sig_algs[j]->sig_oid,
+ &peer->val[i].algorithm) != 0)
+ continue;
+ if (keytype && sig_algs[j]->key_oid &&
+ der_heim_oid_cmp(keytype, sig_algs[j]->key_oid))
+ continue;
+
+ /* found one, use that */
+ ret = copy_AlgorithmIdentifier(&peer->val[i], selected);
+ if (ret)
+ hx509_clear_error_string(context);
+ return ret;
+ }
+ if (bits & SIG_SECRET) {
+ const struct hx509cipher *cipher;
+
+ cipher = find_cipher_by_oid(&peer->val[i].algorithm);
+ if (cipher == NULL)
+ continue;
+ if (cipher->ai_func == NULL)
+ continue;
+ ret = copy_AlgorithmIdentifier(cipher->ai_func(), selected);
+ if (ret)
+ hx509_clear_error_string(context);
+ return ret;
+ }
+ }
+ }
+
+ /* use default */
+ ret = copy_AlgorithmIdentifier(def, selected);
+ if (ret)
+ hx509_clear_error_string(context);
+ return ret;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crypto_available(hx509_context context,
+ int type,
+ hx509_cert source,
+ AlgorithmIdentifier **val,
+ unsigned int *plen)
+{
+ const heim_oid *keytype = NULL;
+ unsigned int len, i;
+ void *ptr;
+ int bits, ret;
+
+ *val = NULL;
+
+ if (type == HX509_SELECT_ALL) {
+ bits = SIG_DIGEST | SIG_PUBLIC_SIG | SIG_SECRET;
+ } else if (type == HX509_SELECT_DIGEST) {
+ bits = SIG_DIGEST;
+ } else if (type == HX509_SELECT_PUBLIC_SIG) {
+ bits = SIG_PUBLIC_SIG;
+ } else {
+ hx509_set_error_string(context, 0, EINVAL,
+ "Unknown type %d of available", type);
+ return EINVAL;
+ }
+
+ if (source)
+ keytype = find_keytype(_hx509_cert_private_key(source));
+
+ len = 0;
+ for (i = 0; sig_algs[i]; i++) {
+ if ((sig_algs[i]->flags & bits) == 0)
+ continue;
+ if (sig_algs[i]->sig_alg == NULL)
+ continue;
+ if (keytype && sig_algs[i]->key_oid &&
+ der_heim_oid_cmp(sig_algs[i]->key_oid, keytype))
+ continue;
+
+ /* found one, add that to the list */
+ ptr = realloc(*val, sizeof(**val) * (len + 1));
+ if (ptr == NULL)
+ goto out;
+ *val = ptr;
+
+ ret = copy_AlgorithmIdentifier(sig_algs[i]->sig_alg, &(*val)[len]);
+ if (ret)
+ goto out;
+ len++;
+ }
+
+ /* Add AES */
+ if (bits & SIG_SECRET) {
+
+ for (i = 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++) {
+
+ if (ciphers[i].flags & CIPHER_WEAK)
+ continue;
+ if (ciphers[i].ai_func == NULL)
+ continue;
+
+ ptr = realloc(*val, sizeof(**val) * (len + 1));
+ if (ptr == NULL)
+ goto out;
+ *val = ptr;
+
+ ret = copy_AlgorithmIdentifier((ciphers[i].ai_func)(), &(*val)[len]);
+ if (ret)
+ goto out;
+ len++;
+ }
+ }
+
+ *plen = len;
+ return 0;
+
+out:
+ for (i = 0; i < len; i++)
+ free_AlgorithmIdentifier(&(*val)[i]);
+ free(*val);
+ *val = NULL;
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_crypto_free_algs(AlgorithmIdentifier *val,
+ unsigned int len)
+{
+ unsigned int i;
+ for (i = 0; i < len; i++)
+ free_AlgorithmIdentifier(&val[i]);
+ free(val);
+}
diff --git a/third_party/heimdal/lib/hx509/data/PKITS.pdf b/third_party/heimdal/lib/hx509/data/PKITS.pdf
new file mode 100644
index 0000000..3a56862
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/PKITS.pdf
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/PKITS_data.zip b/third_party/heimdal/lib/hx509/data/PKITS_data.zip
new file mode 100644
index 0000000..50d6fbb
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/PKITS_data.zip
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/bleichenbacher-bad.pem b/third_party/heimdal/lib/hx509/data/bleichenbacher-bad.pem
new file mode 100644
index 0000000..2c71932
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/bleichenbacher-bad.pem
@@ -0,0 +1,12 @@
+-----BEGIN CERTIFICATE-----
+MIIBsDCCAVoCAQYwDQYJKoZIhvcNAQEFBQAwYzELMAkGA1UEBhMCQVUxEzARBgNV
+BAgTClF1ZWVuc2xhbmQxGjAYBgNVBAoTEUNyeXB0U29mdCBQdHkgTHRkMSMwIQYD
+VQQDExpTZXJ2ZXIgdGVzdCBjZXJ0ICg1MTIgYml0KTAeFw0wNjA5MTEyMzU4NTVa
+Fw0wNjEwMTEyMzU4NTVaMGMxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpRdWVlbnNs
+YW5kMRowGAYDVQQKExFDcnlwdFNvZnQgUHR5IEx0ZDEjMCEGA1UEAxMaU2VydmVy
+IHRlc3QgY2VydCAoNTEyIGJpdCkwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAn7PD
+hCeV/xIxUg8V70YRxK2A5jZbD92A12GN4PxyRQk0/lVmRUNMaJdq/qigpd9feP/u
+12S4PwTLb/8q/v657QIDAQABMA0GCSqGSIb3DQEBBQUAA0EAbynCRIlUQgaqyNgU
+DF6P14yRKUtX8akOP2TwStaSiVf/akYqfLFm3UGka5XbPj4rifrZ0/sOoZEEBvHQ
+e20sRA==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/bleichenbacher-good.pem b/third_party/heimdal/lib/hx509/data/bleichenbacher-good.pem
new file mode 100644
index 0000000..409147b
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/bleichenbacher-good.pem
@@ -0,0 +1,12 @@
+-----BEGIN CERTIFICATE-----
+MIIBsDCCAVoCAQYwDQYJKoZIhvcNAQEFBQAwYzELMAkGA1UEBhMCQVUxEzARBgNV
+BAgTClF1ZWVuc2xhbmQxGjAYBgNVBAoTEUNyeXB0U29mdCBQdHkgTHRkMSMwIQYD
+VQQDExpTZXJ2ZXIgdGVzdCBjZXJ0ICg1MTIgYml0KTAeFw0wNjA5MTEyMzU5MDJa
+Fw0wNjEwMTEyMzU5MDJaMGMxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpRdWVlbnNs
+YW5kMRowGAYDVQQKExFDcnlwdFNvZnQgUHR5IEx0ZDEjMCEGA1UEAxMaU2VydmVy
+IHRlc3QgY2VydCAoNTEyIGJpdCkwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAn7PD
+hCeV/xIxUg8V70YRxK2A5jZbD92A12GN4PxyRQk0/lVmRUNMaJdq/qigpd9feP/u
+12S4PwTLb/8q/v657QIDAQABMA0GCSqGSIb3DQEBBQUAA0EAc+fnj0rB2CYautG2
+4itiMOU4SN6JFTFDCTU/Gb5aR/Fiu7HJkuE5yGEnTdnwcId/T9sTW251yzCc1e2z
+rHX/kw==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/bleichenbacher-sf-pad-correct.pem b/third_party/heimdal/lib/hx509/data/bleichenbacher-sf-pad-correct.pem
new file mode 100644
index 0000000..3e73f5d
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/bleichenbacher-sf-pad-correct.pem
@@ -0,0 +1,16 @@
+-----BEGIN CERTIFICATE-----
+MIICgzCCAWugAwIBAgIBFzANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzEl
+MCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMp
+U3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDYw
+ODE5MTY1MTMwWhcNMDYxMDE4MTY1MTMwWjARMQ8wDQYDVQQDEwZIYWNrZXIwgZ8w
+DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAKSu6ChWttBsOpaBrYf4PzyCGNe6DuE7
+rmq4CMskdz8uiAJ3wVd8jGsjdeY4YzoXSVp+9mEF6XqNgyDf8Ub3kNgPYxvJ28lg
+QVpd5RdGWXHo14LWBTD1mtFkCiAhVlATsVNI/tjv2tv7Jp8EsylbDHe7hslA0rns
+Rr2cS9bvpM03AgMBAAGjEzARMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEF
+BQADggEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADLL/Up63HkFWD15INcW
+Xd1nZGI+gO/whm58ICyJ1Js7ON6N4NyBTwe8513CvdOlOdG/Ctmy2gxEE47HhEed
+ST8AUooI0ey599t84P20gGRuOYIjr7c=
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/ca.crt b/third_party/heimdal/lib/hx509/data/ca.crt
new file mode 100644
index 0000000..7aa8bcf
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/ca.crt
@@ -0,0 +1,32 @@
+-----BEGIN CERTIFICATE-----
+MIIFczCCA1ugAwIBAgIJAI34CtjBcJHEMA0GCSqGSIb3DQEBCwUAMCoxGzAZBgNV
+BAMMEmh4NTA5IFRlc3QgUm9vdCBDQTELMAkGA1UEBhMCU0UwIBcNMTkwMzIyMjIy
+NTAxWhgPMjUxODExMjEyMjI1MDFaMCoxGzAZBgNVBAMMEmh4NTA5IFRlc3QgUm9v
+dCBDQTELMAkGA1UEBhMCU0UwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC
+AQDE4gbVQ/vlPFU2W62rukqiUkJ/EIDo1HE4r+xpxO12Ke45NtqSep0d2FfSvEu8
+dhot1jWIkijF7B/bFuB0LyFryCAV/zlU9rLoadCmur5ONIgXRm7eW19wxo5YRD4C
+A1IRwvT+Axz0TC3eyquUN1C0r7ZWbiOY8uQy3Sjfar16Z3TtqlKgo4R/yF7dIPJO
+OVHaznC+xsfLsYE2r9PqbTjBF3O1pIhwV9oA3tfs23EtvcZBP3y3LSsjnKaF0b/N
+XmjLNW9hbmAfN+16TEMOlVZvBjUPO3CC/GU0PJzm1/FqyzXWeRx5FZNi7fCPKg8J
+9QDAgK5mMn+ZPazuUt70uxUFrnRLCjCia/TgC+t2d+3AqsnRlYnLYDv/MeP/QwqH
+GK3+WuAS6uqXZMtilDhY+oiMTZ4vDHvwzJ5q3UhIpWXj5cSGWAxQurKgUsjT9sta
+gGmXlBauMYSzFM5T+TXica1qE7dNXjXr2sTy9BHIp+aWJuGkX9rSx8tHwbkIkVTp
+4UCZ+QoxBRaSmiuyFPM77yg6wZBuSuRRN/BNKvAhuJaE1MdA+vobbyyNbv56MU0+
+WI4ucD+b08JmJp3k+fgM0fKXBQlEL4mp7zeUoLmC1yCy48Zk1foPZTRH9pIGB/zU
+z4B8o20NmereB9bX0IjJ6eqMDqvAZWZ99Nf16Q3X88T88wIDAQABo4GZMIGWMB0G
+A1UdDgQWBBRTuMwJxp9C6tXkdCC0Ze1o+J21BTBaBgNVHSMEUzBRgBRTuMwJxp9C
+6tXkdCC0Ze1o+J21BaEupCwwKjEbMBkGA1UEAwwSaHg1MDkgVGVzdCBSb290IENB
+MQswCQYDVQQGEwJTRYIJAI34CtjBcJHEMAwGA1UdEwQFMAMBAf8wCwYDVR0PBAQD
+AgHmMA0GCSqGSIb3DQEBCwUAA4ICAQCdea8Tx/1vuQCqn2AOmIzEO9xgmaY3opl9
+0Px82DafNuFFJu9WlPrsKeADtSqpA/MwBjL8K+T3dhL4Bxhq8jed0gGsS3C3xFTl
+/RJbnFiLuveMErPTEtxaRYpa3oibQ15eJbDq533Is1x8oeK6NnHB6St3nboST0f3
+6SeAsoeHrI16eUEJQ3UKJYJlxATEqOpeaWwdlT6jF9u0WyENz0ijD0b9FPY/zq6D
+zx47Zd5F6aisrtKNXFjB9/oHV6jOh9OGxz6WfT1z2AZ+69jEm+xE8coq4nyWcJrS
+cf7ENBIw1Rknpxk3/H1p0q+Zze5/JBYlKOtEML1dwRIRquVgfhcI/tOq7m5jUxTl
+/6dW8FCnuEFBnUvUrZ0Hv3g2jvHElpPjYkLwZyKFYyvY/G+xCZAiqaYZ2kQqRmti
+KvSfh8fJlV2Jj2aDI1I4JjACG7LYBe7WXCs7TccRrhnx/RUY7cpJwEQrIOKBq8wx
+DD58oPgvkmNPP5lZcFARjnWcY8xS9KzT+KaZWM3ZPefg3Vk//3HfwZfDE3Y7IMgu
+quuLcpeGtMDyurnm6piUdPITt8yW+MMJR8V+PeF0zLdN4dA0nuJpZWZ3fvnevmAL
+jh/ia0LuzkhVSj1R1dXXopZevazh/tmAuKU9BbeYGvwI1RFXVvyzpGRfMbgaze3Q
+tIrreKeFxg==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/ca.key b/third_party/heimdal/lib/hx509/data/ca.key
new file mode 100644
index 0000000..83cff75
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/ca.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJRAIBADANBgkqhkiG9w0BAQEFAASCCS4wggkqAgEAAoICAQDE4gbVQ/vlPFU2
+W62rukqiUkJ/EIDo1HE4r+xpxO12Ke45NtqSep0d2FfSvEu8dhot1jWIkijF7B/b
+FuB0LyFryCAV/zlU9rLoadCmur5ONIgXRm7eW19wxo5YRD4CA1IRwvT+Axz0TC3e
+yquUN1C0r7ZWbiOY8uQy3Sjfar16Z3TtqlKgo4R/yF7dIPJOOVHaznC+xsfLsYE2
+r9PqbTjBF3O1pIhwV9oA3tfs23EtvcZBP3y3LSsjnKaF0b/NXmjLNW9hbmAfN+16
+TEMOlVZvBjUPO3CC/GU0PJzm1/FqyzXWeRx5FZNi7fCPKg8J9QDAgK5mMn+ZPazu
+Ut70uxUFrnRLCjCia/TgC+t2d+3AqsnRlYnLYDv/MeP/QwqHGK3+WuAS6uqXZMti
+lDhY+oiMTZ4vDHvwzJ5q3UhIpWXj5cSGWAxQurKgUsjT9stagGmXlBauMYSzFM5T
++TXica1qE7dNXjXr2sTy9BHIp+aWJuGkX9rSx8tHwbkIkVTp4UCZ+QoxBRaSmiuy
+FPM77yg6wZBuSuRRN/BNKvAhuJaE1MdA+vobbyyNbv56MU0+WI4ucD+b08JmJp3k
++fgM0fKXBQlEL4mp7zeUoLmC1yCy48Zk1foPZTRH9pIGB/zUz4B8o20NmereB9bX
+0IjJ6eqMDqvAZWZ99Nf16Q3X88T88wIDAQABAoICAQCD8TXDFpxpM9WnaCkrPN1n
+itklbln1rulxo/Q7rc21ssQDc89m+uTwa1vvzmCzHDLPJQ8bR1gry+JNYTdqpWsw
+YB2goDo7xlh/iOpb0ipXHr1VW85RFcsQOQCMBq/HiZImdRDaahutXKAg/pGd8rQT
+Yu4/XfBdP+nObIhHsbDppwules+E+BCD0jRA3SOFaMSCbncAYxbiW0LM82iBYlD2
+llDlGi6Vm0pt6umpwiZHETcb4wAhghO2+fRfGgIAD5ULGfRaxy2DvmdX3mPSEiKq
+pO5KFvt/zMXGDBjaWz1e5HBgGyoJu3vagLsGNpl9gsPOPm6h7pW0jLCnxsHEINwk
+lGbhCR9ubaZMCNuwEppPNeusURG35XiSEHC4fBPhlG6pB737a6ih/w9dwOkLuijJ
+X3vOaVj2K5waExi72uij+GnZBylemOTAy9lE3xlUzhO74h9F8DuoJHMxXKU5a24L
+/hmnnIYHOJpHQIfcfkMIx9VuG/qsug+DdOxlgByT6hbkRbX2gGSP3iqy7XUnb2g0
+3QQdyQpz8wJ2x568EAAC0HKhQj2fcL1L5lpM5xpbg6s87o50reMhcAogb2mGjx3Q
+r8u9PJeYgJ5FOqu0zLbenWkb4OLtLz6kHhOdimkCrybL+bLQFdl9lNAOqgVuJxyT
+NaClP+v9lAACBkONihU8AQKCAQEA9hxExY0NXFDZHiLq4M4DG79BthLWLi4QFZI5
+2vpzrS5kT90rptAzBenTBWdUifAI8JPkq2R8VKB8j7F5YELQ9UTmoT+qMGEslQ1p
+RTE8fZln6UhLUIv5tTwhL6Afbs2Faz7Vd7rUq9eUkyxsjxtZe5cPH1dGplx0iPQI
+QQ1OasSWc8TmZWXRvcRWe5vWiJLFZKt6fJZWYyBBvu8L7PZ6QR5Oa2EO1UTPPX+W
+7+BwsoH9Bguv+hYliKEReN8SIfOF9E/OElrNooy7eANFTQ3pNEou68rqpzX4jgdW
+G4Nnsu9rkO8K+bb+/MLBvdxrEiKrNb+xwcVOFaJNqz6aNMC14QKCAQEAzMtbIpig
+dLUha3QXrXIsEjH/hlGx0c6Q9VH/toQbBNE4LOrS4QlurX3iRz79tNYLYdwLrZ2Q
++tK31/ilX/hGIiA1w6fHcrQokddMJhhGoR6nSUiybs+75Ac01xHDSYXCo/YOkr8m
+HOtRWi+0qJqzU4sticPwi2YStM6L2gNpEDU9FQTG/wgLLHPxDEjRpkhmgQbt8nEQ
+M+amXK1othrZVSTJl1hREF11DkzhkZYyGgY4ifAyAOPW7z5K0nS2drV8PExFSkr+
+2eriVvavu/40WbvadhTy1cyVL7N3svzY34TgwqsXX1Stz8dQBa+uImt9gxmZIK9I
+reONiErKBhClUwKCAQEAjY1IyM8OBjDCECFJMq+K/iSM6OoAomMAAUgvWpF+gvcR
+3xV4i+Nn1VjddFgwOX4Dxktp1GJhWFNOEV+kTgdgJBHTDJ+PhW/+smQaTh+5iQv4
+xiY8m0FHCERjWf8g1RwERuDG6qxcsdG2tMdyUQUL/JevrPkHu5ulszeYn8HFfoc/
+eaqgUWW0sw8AJuxFAhxYyEQQmSPm3/Cnn+fh1hMV0epadExIucVv5RFDgQh4CVPW
+cem6935RbDon0HuM9FYaj6BvCAOODpYfJTHMZDtCDD82qYv2VuIl6ZqynfSAalxm
+Y9/5UhM8qahiwo7KTo3+J1XwKWEQPkUxovLIwtqsQQKCAQEAgMgwWyUXYcy1Y1jx
+usRdKmP+h3zAEWuQhHQ4FZIlW3YlmTlhutmvm7HZpWvbJuii57r0LQ00qkXwDgPy
+GtOJZtRSeuL67QqVqIB3Bk2lvJQGJnNsoXpIcTCG7efhok5XA7wrleRWF0FzOv9c
+39nIgvS2gjeRAFgD02c/Uq1qWCLicmE6sg1g2WdfYZY5IBPPQbwVzauDwN9+JjF1
+824W1Q/5JQ8Iiv36Ki/2eRK2Ft9qlnNRPnYIJxJJAucaBrRBl7luqTVX5blq87zU
+7acBTJxw2Gh7/C5WclStJQUTbBunK0NjwzMAyfRQQgMjwclOeC6UuJUBYzgBPH+r
+Yvz8uQKCAQA8WchJ0UQmOP98voo0cnIX0lcZcddwzdsZm78p1PrXqmsrxnlmRILA
+wZ5okzIzEqu1Xltu5DS/CAAWdRkY/2LFGty1dW5UR47xsWE7fMf4dbPeOcBxgfh4
+sQgG7KcWY9mw3PZ4PmPP63nRC/1Ws/+dlvpNA77BjyHH7laTVZbUadS/0bCzhJG0
+RW27r5UcPV8IhKTNU8iOxvaN2U0N2RaaxZ8AaYj8UEeMlFp91DXYa5SCWY1yM0c7
+QYpO3EtSLj+ECk09lDzQBPUo4jzb5CoTFYDEdXr8Rt4I/r03fkOwHslWUzXVyqRe
+xC/DrYbFBHh4yQWuQPsmCbi6OkGKDvwA
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/crl1.crl b/third_party/heimdal/lib/hx509/data/crl1.crl
new file mode 100644
index 0000000..575f80e
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/crl1.crl
@@ -0,0 +1,16 @@
+-----BEGIN X509 CRL-----
+MIIChTBvMA0GCSqGSIb3DQEBBQUAMCoxGzAZBgNVBAMMEmh4NTA5IFRlc3QgUm9v
+dCBDQTELMAkGA1UEBhMCU0UXDTE5MDMyMjIyMjUxNloXDTI5MDEyODIyMjUxNlow
+FDASAgEDFw0xOTAzMjIyMjI1MTZaMA0GCSqGSIb3DQEBBQUAA4ICAQBCM4u2dByD
+hPsQUpPAPsZ/a7tPdvkgmcLtk2CFhtJqtDBT96SAr0tVpcpIbZoB0tH/MvJfhAaR
+AOLrgdmrwlKaIbq3uyEDIghRlRiG2WXX+gsP9yK1xS6AuQnXS8Pnyng0xo2V8fMy
+UCN+gKvO70O6dqcDApU1Tt5jxkPFACBYSSMsuunrjWGuttKGebJJGeBzU+PYt7bZ
+7CT2BgsLgl5J2DL6KO9tGjDmlGKKC2joF1PDkjzbIfs389eyOZqJu/3Q4EtBFzad
+Yz0DAEDzDrn7dj53NJp6dxbqOM86woak37dtDG5Mwu8KTQEGpfsqdofQf39nluJu
+70NHJrXP+9IQ7Tvb3bakZbyigw7J9PBXaHyImXN/gejYD/FQjghnmS2QU72JsSKT
+3nAN3I6MRAEIhoaxForCl3f+uHgtvQBBITSIUdnGaTZnI0mXrkHS9H4eWWJREZbc
+wBqKGZxbfy8ZbPaKv75Zzj0ZMns7vNybUqLEE/OcwrEjd/pCLwWZ6KzgtS1t22TU
+o3H26GNLzMQvg/1dVsRZWrkWxAjVNHtUIXXbmBOvSii3BX7jPIfH1bCZrfsl0xrS
+BsqhtIZj74hyTV1FX79CdFu0Ag/ugtzY4K8rdIu9kaPe2Ju6ulQBtpmCK++H7szP
+48fJOwV1aKzJGVCH61kSGc8ljyGjDEDn4Q==
+-----END X509 CRL-----
diff --git a/third_party/heimdal/lib/hx509/data/crl1.der b/third_party/heimdal/lib/hx509/data/crl1.der
new file mode 100644
index 0000000..a667423
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/crl1.der
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/eccurve.pem b/third_party/heimdal/lib/hx509/data/eccurve.pem
new file mode 100644
index 0000000..a76e47d
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/eccurve.pem
@@ -0,0 +1,3 @@
+-----BEGIN EC PARAMETERS-----
+BggqhkjOPQMBBw==
+-----END EC PARAMETERS-----
diff --git a/third_party/heimdal/lib/hx509/data/gen-req.sh b/third_party/heimdal/lib/hx509/data/gen-req.sh
new file mode 100755
index 0000000..09f0dfb
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/gen-req.sh
@@ -0,0 +1,360 @@
+#!/bin/sh
+# $Id$
+#
+# This script need openssl 0.9.8a or newer, so it can parse the
+# otherName section for pkinit certificates.
+#
+
+openssl=openssl
+
+# workaround until openssl -objects lands
+if ${openssl} version | grep '^OpenSSL 1\.[1-9]' >/dev/null ; then
+ config=openssl.1.1.cnf
+else
+ config=openssl.1.0.cnf
+fi
+
+gen_cert()
+{
+ keytype=${6:-rsa:4096}
+ ${openssl} req \
+ -new \
+ -subj "$1" \
+ -config ${config} \
+ -newkey $keytype \
+ -sha1 \
+ -nodes \
+ -keyout out.key \
+ -out cert.req > /dev/null 2>/dev/null
+
+ if [ "$3" = "ca" ] ; then
+ ${openssl} x509 \
+ -req \
+ -days 182500 \
+ -in cert.req \
+ -extfile ${config} \
+ -extensions $4 \
+ -signkey out.key \
+ -out cert.crt
+
+ ln -s ca.crt `${openssl} x509 -hash -noout -in cert.crt`.0
+
+ name=$3
+
+ elif [ "$3" = "proxy" ] ; then
+
+ ${openssl} x509 \
+ -req \
+ -in cert.req \
+ -days 182500 \
+ -out cert.crt \
+ -CA $2.crt \
+ -CAkey $2.key \
+ -CAcreateserial \
+ -extfile ${config} \
+ -extensions $4
+
+ name=$5
+ else
+
+ ${openssl} ca \
+ -name $4 \
+ -days 182500 \
+ -cert $2.crt \
+ -keyfile $2.key \
+ -in cert.req \
+ -out cert.crt \
+ -outdir . \
+ -batch \
+ -config ${config}
+
+ name=$3
+ fi
+
+ mv cert.crt $name.crt
+ mv out.key $name.key
+}
+
+echo "01" > serial
+> index.txt
+rm -f *.0
+
+gen_cert "/CN=hx509 Test Root CA/C=SE" "root" "ca" "v3_ca"
+gen_cert "/CN=OCSP responder/C=SE" "ca" "ocsp-responder" "ocsp"
+gen_cert "/CN=Test cert/C=SE" "ca" "test" "usr"
+gen_cert "/CN=Revoke cert/C=SE" "ca" "revoke" "usr"
+gen_cert "/CN=Test cert KeyEncipherment/C=SE" "ca" "test-ke-only" "usr_ke"
+gen_cert "/CN=Test cert DigitalSignature/C=SE" "ca" "test-ds-only" "usr_ds"
+gen_cert "/CN=pkinit/C=SE" "ca" "pkinit" "pkinit_client"
+$openssl ecparam -name secp256r1 -out eccurve.pem
+gen_cert "/CN=pkinit-ec/C=SE" "ca" "pkinit-ec" "pkinit_client" "XXX" ec:eccurve.pem
+gen_cert "/C=SE/CN=pkinit/CN=pkinit-proxy" "pkinit" "proxy" "proxy_cert" pkinit-proxy
+gen_cert "/CN=kdc/C=SE" "ca" "kdc" "pkinit_kdc"
+gen_cert "/CN=www.test.h5l.se/C=SE" "ca" "https" "https"
+gen_cert "/CN=Sub CA/C=SE" "ca" "sub-ca" "subca"
+gen_cert "/CN=Test sub cert/C=SE" "sub-ca" "sub-cert" "usr"
+gen_cert "/C=SE/CN=Test cert/CN=proxy" "test" "proxy" "proxy_cert" proxy-test
+gen_cert "/C=SE/CN=Test cert/CN=proxy/CN=child" "proxy-test" "proxy" "proxy_cert" proxy-level-test
+gen_cert "/C=SE/CN=Test cert/CN=no-proxy" "test" "proxy" "usr_cert" no-proxy-test
+gen_cert "/C=SE/CN=Test cert/CN=proxy10" "test" "proxy" "proxy10_cert" proxy10-test
+gen_cert "/C=SE/CN=Test cert/CN=proxy10/CN=child" "proxy10-test" "proxy" "proxy10_cert" proxy10-child-test
+gen_cert "/C=SE/CN=Test cert/CN=proxy10/CN=child/CN=child" "proxy10-child-test" "proxy" "proxy10_cert" proxy10-child-child-test
+
+
+# combine
+cat sub-ca.crt ca.crt > sub-ca-combined.crt
+cat test.crt test.key > test.combined.crt
+cat pkinit-proxy.crt pkinit.crt > pkinit-proxy-chain.crt
+
+# password protected key
+${openssl} rsa -in test.key -aes256 -passout pass:foobar -out test-pw.key
+${openssl} rsa -in pkinit.key -aes256 -passout pass:foo -out pkinit-pw.key
+
+
+${openssl} ca \
+ -name usr \
+ -cert ca.crt \
+ -keyfile ca.key \
+ -revoke revoke.crt \
+ -config ${config}
+
+${openssl} pkcs12 \
+ -export \
+ -in test.crt \
+ -inkey test.key \
+ -passout pass:foobar \
+ -out test.p12 \
+ -name "friendlyname-test" \
+ -certfile ca.crt \
+ -caname ca
+
+${openssl} pkcs12 \
+ -export \
+ -in sub-cert.crt \
+ -inkey sub-cert.key \
+ -passout pass:foobar \
+ -out sub-cert.p12 \
+ -name "friendlyname-sub-cert" \
+ -certfile sub-ca-combined.crt \
+ -caname sub-ca \
+ -caname ca
+
+${openssl} pkcs12 \
+ -keypbe NONE \
+ -certpbe NONE \
+ -export \
+ -in test.crt \
+ -inkey test.key \
+ -passout pass:foobar \
+ -out test-nopw.p12 \
+ -name "friendlyname-cert" \
+ -certfile ca.crt \
+ -caname ca
+
+${openssl} smime \
+ -sign \
+ -nodetach \
+ -binary \
+ -in static-file \
+ -signer test.crt \
+ -inkey test.key \
+ -outform DER \
+ -out test-signed-data
+
+${openssl} smime \
+ -sign \
+ -nodetach \
+ -binary \
+ -in static-file \
+ -signer test.crt \
+ -inkey test.key \
+ -noattr \
+ -outform DER \
+ -out test-signed-data-noattr
+
+${openssl} smime \
+ -sign \
+ -nodetach \
+ -binary \
+ -in static-file \
+ -signer test.crt \
+ -inkey test.key \
+ -noattr \
+ -nocerts \
+ -outform DER \
+ -out test-signed-data-noattr-nocerts
+
+${openssl} smime \
+ -sign \
+ -md sha1 \
+ -nodetach \
+ -binary \
+ -in static-file \
+ -signer test.crt \
+ -inkey test.key \
+ -outform DER \
+ -out test-signed-sha-1
+
+${openssl} smime \
+ -sign \
+ -md sha256 \
+ -nodetach \
+ -binary \
+ -in static-file \
+ -signer test.crt \
+ -inkey test.key \
+ -outform DER \
+ -out test-signed-sha-256
+
+${openssl} smime \
+ -sign \
+ -md sha512 \
+ -nodetach \
+ -binary \
+ -in static-file \
+ -signer test.crt \
+ -inkey test.key \
+ -outform DER \
+ -out test-signed-sha-512
+
+
+${openssl} smime \
+ -encrypt \
+ -nodetach \
+ -binary \
+ -in static-file \
+ -outform DER \
+ -out test-enveloped-rc2-40 \
+ -rc2-40 \
+ test.crt
+
+${openssl} smime \
+ -encrypt \
+ -nodetach \
+ -binary \
+ -in static-file \
+ -outform DER \
+ -out test-enveloped-rc2-64 \
+ -rc2-64 \
+ test.crt
+
+${openssl} smime \
+ -encrypt \
+ -nodetach \
+ -binary \
+ -in static-file \
+ -outform DER \
+ -out test-enveloped-rc2-128 \
+ -rc2-128 \
+ test.crt
+
+${openssl} smime \
+ -encrypt \
+ -nodetach \
+ -binary \
+ -in static-file \
+ -outform DER \
+ -out test-enveloped-des \
+ -des \
+ test.crt
+
+${openssl} smime \
+ -encrypt \
+ -nodetach \
+ -binary \
+ -in static-file \
+ -outform DER \
+ -out test-enveloped-des-ede3 \
+ -des3 \
+ test.crt
+
+${openssl} smime \
+ -encrypt \
+ -nodetach \
+ -binary \
+ -in static-file \
+ -outform DER \
+ -out test-enveloped-aes-128 \
+ -aes128 \
+ test.crt
+
+${openssl} smime \
+ -encrypt \
+ -nodetach \
+ -binary \
+ -in static-file \
+ -outform DER \
+ -out test-enveloped-aes-256 \
+ -aes256 \
+ test.crt
+
+echo ocsp requests
+
+${openssl} ocsp \
+ -issuer ca.crt \
+ -cert test.crt \
+ -reqout ocsp-req1.der
+
+${openssl} ocsp \
+ -index index.txt \
+ -rsigner ocsp-responder.crt \
+ -rkey ocsp-responder.key \
+ -CA ca.crt \
+ -reqin ocsp-req1.der \
+ -noverify \
+ -respout ocsp-resp1-ocsp.der
+
+${openssl} ocsp \
+ -index index.txt \
+ -rsigner ca.crt \
+ -rkey ca.key \
+ -CA ca.crt \
+ -reqin ocsp-req1.der \
+ -noverify \
+ -respout ocsp-resp1-ca.der
+
+${openssl} ocsp \
+ -index index.txt \
+ -rsigner ocsp-responder.crt \
+ -rkey ocsp-responder.key \
+ -CA ca.crt \
+ -resp_no_certs \
+ -reqin ocsp-req1.der \
+ -noverify \
+ -respout ocsp-resp1-ocsp-no-cert.der
+
+${openssl} ocsp \
+ -index index.txt \
+ -rsigner ocsp-responder.crt \
+ -rkey ocsp-responder.key \
+ -CA ca.crt \
+ -reqin ocsp-req1.der \
+ -resp_key_id \
+ -noverify \
+ -respout ocsp-resp1-keyhash.der
+
+${openssl} ocsp \
+ -issuer ca.crt \
+ -cert revoke.crt \
+ -reqout ocsp-req2.der
+
+${openssl} ocsp \
+ -index index.txt \
+ -rsigner ocsp-responder.crt \
+ -rkey ocsp-responder.key \
+ -CA ca.crt \
+ -reqin ocsp-req2.der \
+ -noverify \
+ -respout ocsp-resp2.der
+
+${openssl} ca \
+ -gencrl \
+ -name usr \
+ -crldays 3600 \
+ -keyfile ca.key \
+ -cert ca.crt \
+ -crl_reason superseded \
+ -out crl1.crl \
+ -config ${config}
+
+${openssl} crl -in crl1.crl -outform der -out crl1.der
diff --git a/third_party/heimdal/lib/hx509/data/https.crt b/third_party/heimdal/lib/hx509/data/https.crt
new file mode 100644
index 0000000..54d5df1
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/https.crt
@@ -0,0 +1,116 @@
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 9 (0x9)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: CN=hx509 Test Root CA, C=SE
+ Validity
+ Not Before: Mar 22 22:25:10 2019 GMT
+ Not After : Nov 21 22:25:10 2518 GMT
+ Subject: C=SE, CN=www.test.h5l.se
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:bb:ca:85:9c:3d:6b:5a:21:1b:2c:84:35:48:37:
+ bc:13:62:93:ff:7b:be:49:40:e2:36:b5:7a:54:a4:
+ e3:0f:b1:87:29:de:6b:7d:86:ec:b6:25:c5:9c:dc:
+ 13:06:57:4c:80:1b:86:f0:ac:e6:64:8f:aa:63:cc:
+ 28:49:5c:84:09:b8:0f:31:99:dd:36:d2:42:b5:aa:
+ df:31:f6:27:ca:c2:4c:50:11:5b:01:94:17:da:2a:
+ 5c:21:e5:b5:81:23:69:3e:4f:1d:08:48:95:57:30:
+ 77:96:ae:9b:78:87:10:e4:6d:90:e8:78:ad:19:41:
+ 3d:b8:91:1c:b6:04:78:52:e5:e4:3f:28:df:01:13:
+ da:aa:cb:24:cf:f5:93:f9:02:b8:c5:dc:47:fb:79:
+ e5:de:9e:19:b3:28:ab:2d:bd:73:48:0f:71:0a:b6:
+ 81:5a:6d:02:6d:9c:c8:c3:14:d5:82:bf:19:b8:d0:
+ 6f:58:32:6c:76:91:f3:07:6b:25:4a:59:f4:2d:c9:
+ 8d:da:ee:cc:30:5b:5b:d8:f3:0d:63:28:8d:9c:df:
+ 21:b5:3a:41:e0:55:d0:5f:f1:32:45:0b:6b:40:b6:
+ d8:43:0c:7b:28:3d:2d:7c:40:19:a2:e0:d6:a2:0b:
+ 32:65:a3:81:e9:1c:e5:6a:f6:61:7c:66:fa:c6:10:
+ bf:5d:1d:d9:c1:1a:67:fb:a0:43:15:ff:f5:40:5a:
+ 0c:8a:4b:48:38:d5:c7:77:48:19:f7:21:de:73:17:
+ 97:cf:03:d7:c3:84:22:38:ae:f2:be:d2:61:af:37:
+ 38:31:41:01:97:58:93:ba:80:da:bb:00:33:a8:2b:
+ 98:34:80:8b:00:1e:83:02:c4:26:3f:5c:51:a9:29:
+ e3:ac:b1:36:31:57:87:43:94:57:3a:17:f4:6d:34:
+ bf:23:b6:a2:56:d2:b7:72:7e:35:34:d9:58:46:c1:
+ 64:2d:3f:e7:ff:e4:fd:42:11:d9:04:98:ba:9d:88:
+ ec:e7:ae:bb:11:42:fd:00:cb:24:17:27:94:2c:a0:
+ 34:df:18:8b:7a:bc:39:55:6c:02:3b:44:cf:a4:42:
+ f3:e3:81:5b:d6:90:8e:78:d7:3f:4c:ef:6c:de:4d:
+ 7e:41:ce:87:8f:c0:38:a4:57:05:63:32:85:c3:de:
+ 88:aa:8c:0b:04:df:c3:86:64:4c:19:91:e1:e4:b2:
+ f8:f6:f3:fe:93:c3:3e:c1:b1:74:b4:72:ff:88:94:
+ 8d:34:a3:b0:9d:55:aa:fe:bc:bc:41:55:49:8a:f1:
+ ee:dd:fa:0e:a1:fa:b9:71:a7:d5:fc:b7:fc:ab:c2:
+ af:8f:bd:6e:48:ec:54:f0:f8:a8:b4:d7:6c:11:0e:
+ f9:16:ab
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints:
+ CA:FALSE
+ X509v3 Key Usage:
+ Digital Signature, Non Repudiation, Key Encipherment
+ X509v3 Subject Key Identifier:
+ AA:3C:0D:95:CD:14:0A:9C:A5:2D:09:6E:EE:5B:43:A9:AF:3F:6E:54
+ Signature Algorithm: sha1WithRSAEncryption
+ a3:ec:06:1b:66:b3:cb:a3:12:38:ef:30:dc:a6:a1:fc:d3:52:
+ d0:73:c8:a9:4d:0b:8e:02:2a:08:a6:4f:55:41:2f:46:2b:cf:
+ e9:04:07:9d:42:47:0d:88:64:1f:39:ae:d7:9b:30:43:47:f9:
+ ba:96:a8:2f:7a:6e:4b:22:9c:65:c7:9c:8c:c6:d2:f2:5f:a9:
+ fd:de:eb:9e:7a:13:b8:22:0c:59:15:90:ba:65:b7:08:3d:dd:
+ 2e:e2:09:be:47:53:25:0a:8c:d3:e0:78:e9:1a:15:8e:32:b2:
+ 5f:76:e1:68:3c:2f:33:3f:38:17:ff:3b:ad:43:b7:0e:87:08:
+ 97:6b:8d:a7:6c:3b:de:1a:18:3d:5b:74:0b:87:03:8a:49:b0:
+ 22:84:2a:72:f1:01:c3:b5:55:9e:4a:56:c1:96:6c:ba:9c:eb:
+ 58:ce:4e:53:fd:b8:99:02:c1:d5:62:ef:b5:44:73:1c:c6:4f:
+ 26:f9:8d:6b:e9:58:be:3c:4a:56:ef:65:6a:f5:71:1c:3b:8e:
+ f4:ae:43:44:ab:26:80:41:da:a9:6b:9b:63:49:bc:39:76:3b:
+ 1e:fe:a5:24:0e:4c:59:51:9d:47:c4:ce:2b:90:65:e8:f8:ae:
+ ab:aa:14:cc:d2:4a:cf:85:20:40:dd:80:49:ea:7c:98:04:ee:
+ 57:41:e6:bc:13:fc:28:5e:08:5c:ee:fa:1b:72:ea:80:e8:ba:
+ 7e:d6:34:eb:fc:88:f1:16:42:b2:bb:22:9c:e0:36:84:23:f5:
+ 20:86:dc:38:55:89:dc:0e:67:7c:c7:bb:2f:36:25:bc:ca:be:
+ 2b:1c:79:26:79:2b:49:17:3c:76:02:cf:f9:e3:8a:3f:15:69:
+ 2c:12:5c:99:93:85:11:c8:90:68:d6:f1:8d:87:30:bf:0d:ec:
+ 89:9a:f4:48:cc:26:95:c7:65:cd:30:cc:d0:93:c3:80:3f:ad:
+ a6:fa:7c:88:82:53:0e:9b:16:c3:dd:27:9a:d0:99:05:fb:2d:
+ d0:e6:fa:08:92:46:ee:dd:44:9d:56:b2:95:52:99:db:5a:20:
+ 16:c9:a7:a3:0b:a3:c5:d8:0a:b7:c2:cf:f7:95:a4:df:4c:f9:
+ 2f:69:a0:27:6e:0f:85:3e:76:b4:3d:6b:f7:4a:de:1a:de:a4:
+ d3:01:91:f1:44:59:44:2c:93:15:52:99:da:6e:93:b8:da:54:
+ b5:06:ff:82:9b:cf:57:0c:7d:06:6b:ff:ce:b9:c9:47:62:c9:
+ 15:f4:67:4e:57:12:74:d7:b5:31:53:cc:eb:d7:05:4d:34:58:
+ a9:5d:33:85:2d:72:6f:12:99:7e:60:63:27:05:74:8b:85:0c:
+ 0b:f9:b3:b4:e7:f6:4e:4b
+-----BEGIN CERTIFICATE-----
+MIIFBzCCAu+gAwIBAgIBCTANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw
+OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMCAXDTE5MDMyMjIyMjUxMFoYDzI1
+MTgxMTIxMjIyNTEwWjAnMQswCQYDVQQGEwJTRTEYMBYGA1UEAwwPd3d3LnRlc3Qu
+aDVsLnNlMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAu8qFnD1rWiEb
+LIQ1SDe8E2KT/3u+SUDiNrV6VKTjD7GHKd5rfYbstiXFnNwTBldMgBuG8KzmZI+q
+Y8woSVyECbgPMZndNtJCtarfMfYnysJMUBFbAZQX2ipcIeW1gSNpPk8dCEiVVzB3
+lq6beIcQ5G2Q6HitGUE9uJEctgR4UuXkPyjfARPaqsskz/WT+QK4xdxH+3nl3p4Z
+syirLb1zSA9xCraBWm0CbZzIwxTVgr8ZuNBvWDJsdpHzB2slSln0LcmN2u7MMFtb
+2PMNYyiNnN8htTpB4FXQX/EyRQtrQLbYQwx7KD0tfEAZouDWogsyZaOB6RzlavZh
+fGb6xhC/XR3ZwRpn+6BDFf/1QFoMiktIONXHd0gZ9yHecxeXzwPXw4QiOK7yvtJh
+rzc4MUEBl1iTuoDauwAzqCuYNICLAB6DAsQmP1xRqSnjrLE2MVeHQ5RXOhf0bTS/
+I7aiVtK3cn41NNlYRsFkLT/n/+T9QhHZBJi6nYjs5667EUL9AMskFyeULKA03xiL
+erw5VWwCO0TPpELz44Fb1pCOeNc/TO9s3k1+Qc6Hj8A4pFcFYzKFw96IqowLBN/D
+hmRMGZHh5LL49vP+k8M+wbF0tHL/iJSNNKOwnVWq/ry8QVVJivHu3foOofq5cafV
+/Lf8q8Kvj71uSOxU8PiotNdsEQ75FqsCAwEAAaM5MDcwCQYDVR0TBAIwADALBgNV
+HQ8EBAMCBeAwHQYDVR0OBBYEFKo8DZXNFAqcpS0Jbu5bQ6mvP25UMA0GCSqGSIb3
+DQEBBQUAA4ICAQCj7AYbZrPLoxI47zDcpqH801LQc8ipTQuOAioIpk9VQS9GK8/p
+BAedQkcNiGQfOa7XmzBDR/m6lqgvem5LIpxlx5yMxtLyX6n93uueehO4IgxZFZC6
+ZbcIPd0u4gm+R1MlCozT4HjpGhWOMrJfduFoPC8zPzgX/zutQ7cOhwiXa42nbDve
+Ghg9W3QLhwOKSbAihCpy8QHDtVWeSlbBlmy6nOtYzk5T/biZAsHVYu+1RHMcxk8m
++Y1r6Vi+PEpW72Vq9XEcO470rkNEqyaAQdqpa5tjSbw5djse/qUkDkxZUZ1HxM4r
+kGXo+K6rqhTM0krPhSBA3YBJ6nyYBO5XQea8E/woXghc7vobcuqA6Lp+1jTr/Ijx
+FkKyuyKc4DaEI/Ughtw4VYncDmd8x7svNiW8yr4rHHkmeStJFzx2As/544o/FWks
+ElyZk4URyJBo1vGNhzC/DeyJmvRIzCaVx2XNMMzQk8OAP62m+nyIglMOmxbD3Sea
+0JkF+y3Q5voIkkbu3USdVrKVUpnbWiAWyaejC6PF2Aq3ws/3laTfTPkvaaAnbg+F
+Pna0PWv3St4a3qTTAZHxRFlELJMVUpnabpO42lS1Bv+Cm89XDH0Ga//OuclHYskV
+9GdOVxJ017UxU8zr1wVNNFipXTOFLXJvEpl+YGMnBXSLhQwL+bO05/ZOSw==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/https.key b/third_party/heimdal/lib/hx509/data/https.key
new file mode 100644
index 0000000..59d7bfd
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/https.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJRAIBADANBgkqhkiG9w0BAQEFAASCCS4wggkqAgEAAoICAQC7yoWcPWtaIRss
+hDVIN7wTYpP/e75JQOI2tXpUpOMPsYcp3mt9huy2JcWc3BMGV0yAG4bwrOZkj6pj
+zChJXIQJuA8xmd020kK1qt8x9ifKwkxQEVsBlBfaKlwh5bWBI2k+Tx0ISJVXMHeW
+rpt4hxDkbZDoeK0ZQT24kRy2BHhS5eQ/KN8BE9qqyyTP9ZP5ArjF3Ef7eeXenhmz
+KKstvXNID3EKtoFabQJtnMjDFNWCvxm40G9YMmx2kfMHayVKWfQtyY3a7swwW1vY
+8w1jKI2c3yG1OkHgVdBf8TJFC2tAtthDDHsoPS18QBmi4NaiCzJlo4HpHOVq9mF8
+ZvrGEL9dHdnBGmf7oEMV//VAWgyKS0g41cd3SBn3Id5zF5fPA9fDhCI4rvK+0mGv
+NzgxQQGXWJO6gNq7ADOoK5g0gIsAHoMCxCY/XFGpKeOssTYxV4dDlFc6F/RtNL8j
+tqJW0rdyfjU02VhGwWQtP+f/5P1CEdkEmLqdiOznrrsRQv0AyyQXJ5QsoDTfGIt6
+vDlVbAI7RM+kQvPjgVvWkI541z9M72zeTX5BzoePwDikVwVjMoXD3oiqjAsE38OG
+ZEwZkeHksvj28/6Twz7BsXS0cv+IlI00o7CdVar+vLxBVUmK8e7d+g6h+rlxp9X8
+t/yrwq+PvW5I7FTw+Ki012wRDvkWqwIDAQABAoICAQCUxRFqQGIeieGsN6S6bKUL
+umnC2XZbNBLCAq1CB0p2sU6CBdmkHVLDzlKqPNK5kEljp+sUGfV/ryzuWNuFmsxj
+orQuuFU+y/3bS938B6VohNrOB6HQM1FeHXbVx9Qt1S7YFPbMDCx7YUMsVXGHX4Er
+Zf2JnaiMPFo4MIXNUOc9zTAwNSHOCbuO2NZ2BXhPqi9VWHiSKfTIkvmLLGnIF7EP
+YmRMd18skvV8ftuxaHzpUpl/B2leNrwkhuVAeEqXh4HhEC7YRZvvp0CxM4PkjUj7
+AO4EU33CylkE2ODZP/2cy/2xyF5891Jkf6ePmI2Q3Ev1pz4QvjqlrUB3vGForfXa
+4fLUY+UjmIUPrfF81qryfVbie96wcXIKLEa9osnd/vSJLvs5jrKtpuN1z2lsonz+
+kwwV3lBVeL+DtBJnpGV0qHGaa0GFxjtQKtVPm2HMjPpk0oUh1lAnv4rfdxR0QQIP
+JWhYTt6TfqvClmvKKNuu1O8WGw7ngpUniqenWvHXmgnZtfuVMUvjn55nPWSyV2gf
+r1qRSYZQKlgzCOrCvX1+tXpRfsYqdQccxgBnxrnXTBknwvIEbFbK/QrLnfUnskuQ
+GHbTJUsM3wXChFsx3l4HsxuJG8hbvk5ayX64R8WKzw4tcE78b+vII489GjjuSqdp
+L5uniS8kOO99OqZydUiYeQKCAQEA+ALfEEa70OzH5rJxGEbQu34LB3rQTMGONKrc
+dbdO2MWfsnIJsmybSYOH1YHT2DdUe9aQUNvlu8CVQKEElyG3YPHDR2a0/9roMmy+
+89vw0OScpqjdhl6ULiyzJGM0f23HfbpugBNRhAdrSK02aPDQrenw8Yuk9abhFi+k
+V3VOd+q3Vx9QZ+5BIugqBnWr+2P7tCUxr5sjp5Srj3iyEzH24Yt5OEGPq5GuM2T1
+xYWmjJ5DkJEh5lG1/aeYjZAj4vHFkUZMnIH/A9EYcZG7cHXifwT1/o/SCRazLK1u
+yTV5fJ2Cj5Fc4AtbNzR6nt8nQ3yYOpU/jiNRZZ3rz/PIMksTFwKCAQEAwdcRlA9u
+mDkKQF2xcyFbdjE+FBz4ZdenpjBtoCOLlDJpOhC+rc7meCbnWfwV52dmMOEJVjj8
+y/8Aa2+ZAIGm1GfFaYxR0kdqoiAmbNdUtqqIS0gqOngAZ3kgDBxWCW7vEtggE9wS
+84Nb+2OrhuqxhEo4vJAtlqDLo8ajjgg1iwIrtjfuFGJsBfLiM/AR0E1ZUi6X+FDW
+StGZfzwM9/3VNrJ2yzVXy1VKzS6nzX5OjzDlbdDXHl0XbEKXwkSMXrkfPCvqJmy1
+R9Hiz4ajYnEBJ47SPuV6vfivV591HKEdVWGgS9ezh2wAG1yHUATlUHjFuaTjYJO1
+efc5YXe3kFTljQKCAQEAz//4fHoWQp6S+NRnLWkW3mhTb658zCL41QsHYmKeagc0
+bEBgCZg0lG8PmO0NcqTU4heNaYNDJTfa9R0V8HqChXe9w0BMRNifLMsvSu4HBer1
+xoCRaYQg2qj6hWX+PXEggj29NwT8tLJUM9uxakmtem5dePcZHj0bQbQrLH5hlQjx
+Qswsbz3OuyvjMw+1cVzlWKxpA1IlkQKK8ATVtGuPFpIW1CuIBuhjJQ9jYIk6qWyC
+Vdiiibu12kqZEwD0V/1VKQXAcvJDojvXOEh031i+4LCUby7HhH/ZPXsnEvEaNn0T
+Zr0PG4fqtF37CQs2rs7sDRXm+5p7RbIwd3OJT0TPeQKCAQBObUn7cdL5W/q92Cq3
+vkNXKs1HLgGCkyKNpwJzzG3o5AyXJbdAc3nkGzl3uvrRyZAbLrGsZRpDH0V4Morh
+HZP2VJYXAmMIhUSrm/5wAx+PWKgUbXpIdc0UEHna7IwS/QNVyIQSBPTV+cv5hnYb
+/FEeiTkzcdJAI4bBGNmL2d5wA8zTyQVW0guKzJ6hDPzoHqOJELkECxDo7K0CQbWt
+kNH3c3WE+mwvJK9DHSFfjz8RyGLLb7fZ3Shg8QCd5UY1/QiaO9pc+ZbPHCh8dqkc
+Z0RkUPDX6dkji77F4QptLvLDXOCSTw+gNx5D88f7pD9zs6msVv54UMsYMeLRgLKQ
+fwjxAoIBAQD3C6bhnfTvlphLX+Fq9ObNJNNIYm5+k5cWjgAYJG9ZbC/hbVE3ZUuL
+kYynfu56rA73yb1TBJswpem1tEwDRCUfuEcgIWmjlKdQOMqVaW3EtZDDZpJyZJpQ
+Vf4P46WCsM8pzDK2eYsy3IHRhJgrDMu+cLNOtq/7e1zeOtmPzutuZm5eo9KP7jJ2
+bse1S5e5j2VwOeyHW5wUGer99JizbbcoSn4GkejRTj8I+SHsOu1kQzAV3pQCcvJe
+4Kk7itN65RsZOxh5BShk+X3TIna8QholzxuqSi9aZdBUouUWXYHpM8ch8UDEXCy+
+PJKGZjLpgXkldTcRw00N0NRePp73WR86
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/j.pem b/third_party/heimdal/lib/hx509/data/j.pem
new file mode 100644
index 0000000..45ae8e8
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/j.pem
@@ -0,0 +1,26 @@
+-----BEGIN CERTIFICATE-----
+MIIEajCCA1KgAwIBAgIBATANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJKUDEN
+MAsGA1UECgwESlBLSTEpMCcGA1UECwwgUHJlZmVjdHVyYWwgQXNzb2NpYXRpb24g
+Rm9yIEpQS0kxETAPBgNVBAsMCEJyaWRnZUNBMB4XDTAzMTIyNzA1MDgxNVoXDTEz
+MTIyNjE0NTk1OVowWjELMAkGA1UEBhMCSlAxDTALBgNVBAoMBEpQS0kxKTAnBgNV
+BAsMIFByZWZlY3R1cmFsIEFzc29jaWF0aW9uIEZvciBKUEtJMREwDwYDVQQLDAhC
+cmlkZ2VDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANTnUmg7K3m8
+52vd77kwkq156euwoWm5no8E8kmaTSc7x2RABPpqNTlMKdZ6ttsyYrqREeDkcvPL
+yF7yf/I8+innasNtsytcTAy8xY8Avsbd4JkCGW9dyPjk9pzzc3yLQ64Rx2fujRn2
+agcEVdPCr/XpJygX8FD5bbhkZ0CVoiASBmlHOcC3YpFlfbT1QcpOSOb7o+VdKVEi
+MMfbBuU2IlYIaSr/R1nO7RPNtkqkFWJ1/nKjKHyzZje7j70qSxb+BTGcNgTHa1YA
+UrogKB+UpBftmb4ds+XlkEJ1dvwokiSbCDaWFKD+YD4B2s0bvjCbw8xuZFYGhNyR
+/2D5XfN1s2MCAwEAAaOCATkwggE1MA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E
+BTADAQH/MG0GA1UdHwRmMGQwYqBgoF6kXDBaMQswCQYDVQQGEwJKUDENMAsGA1UE
+CgwESlBLSTEpMCcGA1UECwwgUHJlZmVjdHVyYWwgQXNzb2NpYXRpb24gRm9yIEpQ
+S0kxETAPBgNVBAsMCEJyaWRnZUNBMIGDBgNVHREEfDB6pHgwdjELMAkGA1UEBhMC
+SlAxJzAlBgNVBAoMHuWFrOeahOWAi+S6uuiqjeiovOOCteODvOODk+OCuTEeMBwG
+A1UECwwV6YO96YGT5bqc55yM5Y2U6K2w5LyaMR4wHAYDVQQLDBXjg5bjg6rjg4Pj
+grjoqo3oqLzlsYAwHQYDVR0OBBYEFNQXMiCqQNkR2OaZmQgLtf8mR8p8MA0GCSqG
+SIb3DQEBBQUAA4IBAQATjJo4reTNPC5CsvAKu1RYT8PyXFVYHbKsEpGt4GR8pDCg
+HEGAiAhHSNrGh9CagZMXADvlG0gmMOnXowriQQixrtpkmx0TB8tNAlZptZWkZC+R
+8TnjOkHrk2nFAEC3ezbdK0R7MR4tJLDQCnhEWbg50rf0wZ/aF8uAaVeEtHXa6W0M
+Xq3dSe0XAcrLbX4zZHQTaWvdpLAIjl6DZ3SCieRMyoWUL+LXaLFdTP5WBCd+No58
+IounD9X4xxze2aeRVaiV/WnQ0OSPNS7n7YXy6xQdnaOU4KRW/Lne1EDf5IfWC/ih
+bVAmhZMbcrkWWcsR6aCPG+2mV3zTD6AUzuKPal8Y
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/kdc.crt b/third_party/heimdal/lib/hx509/data/kdc.crt
new file mode 100644
index 0000000..a92fcc0
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/kdc.crt
@@ -0,0 +1,122 @@
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 8 (0x8)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: CN=hx509 Test Root CA, C=SE
+ Validity
+ Not Before: Mar 22 22:25:09 2019 GMT
+ Not After : Nov 21 22:25:09 2518 GMT
+ Subject: C=SE, CN=kdc
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:d1:73:ec:58:67:7a:65:30:ab:19:15:a1:bf:1e:
+ de:db:e5:4a:92:f0:99:8a:eb:02:6d:e4:31:1a:c7:
+ 4d:07:57:b1:82:9e:d2:d2:c7:f3:0b:b2:82:61:5c:
+ ba:38:c3:54:e9:e1:be:6b:5f:0d:22:62:2b:cb:d5:
+ 34:0e:63:0b:50:8a:8b:b3:be:6a:e1:85:dc:b1:28:
+ 13:ee:dd:6e:40:d5:48:1d:eb:aa:04:0b:e7:c8:1c:
+ 6d:60:54:b6:cc:be:52:5a:88:22:ce:07:2d:3f:cb:
+ fc:00:ab:8b:a5:e7:32:8e:b1:8b:03:d8:81:a2:69:
+ d4:9f:3a:ff:da:b5:e3:0d:e3:21:54:29:cb:61:ba:
+ 16:13:94:97:1b:72:24:6d:da:d7:d9:35:b1:57:f1:
+ 3b:9d:ee:90:76:4e:58:1f:4e:76:12:c6:89:2a:54:
+ bf:e8:53:5a:de:05:79:93:0b:41:2c:03:c5:30:58:
+ a8:e6:57:08:f9:47:7c:c0:3a:5c:eb:1b:33:68:52:
+ 02:19:08:e6:35:48:05:a7:51:22:89:1c:1e:c8:0b:
+ 55:73:b2:c9:75:f9:74:aa:de:5e:3a:54:f8:96:47:
+ cf:25:2d:75:e7:71:74:31:91:17:85:44:89:8a:16:
+ 88:ca:12:dd:0e:36:4d:e5:af:b3:db:d3:7c:53:8d:
+ 7a:08:69:92:72:81:c8:13:c7:71:96:8f:2d:54:98:
+ c9:63:10:26:be:59:8f:db:82:47:c1:29:c6:28:7f:
+ a0:16:bf:85:a2:eb:2f:2f:46:86:6b:77:1f:31:30:
+ d4:52:35:32:09:16:cd:48:ec:3c:4c:2c:03:e5:b9:
+ 90:e9:f7:b4:7d:97:91:31:27:4e:df:b6:bd:b6:ec:
+ ca:47:16:00:58:e9:87:4f:20:af:ef:4c:34:42:5b:
+ 3e:28:aa:cd:39:75:3b:6f:7c:b9:7b:50:76:67:25:
+ 31:46:f5:34:aa:c6:5a:22:77:b5:9d:6d:88:4d:f1:
+ e6:e7:ca:d2:d8:70:10:58:39:58:0f:ce:8d:b3:4d:
+ e4:f4:80:ca:31:75:3c:38:61:6c:d9:17:d2:aa:72:
+ f9:e0:ac:86:ab:33:16:84:e8:c8:de:58:9d:78:ac:
+ f1:2a:64:b8:e3:f2:cb:20:42:dd:f9:bd:2e:c2:84:
+ 6e:11:34:76:a5:c5:54:c5:51:9b:cb:85:d1:05:82:
+ 1c:33:d5:95:18:ad:4c:94:d2:7b:4f:72:23:ff:c1:
+ 4b:a2:ea:1a:3a:18:c2:f5:c8:08:76:00:12:25:e5:
+ ee:30:b9:8d:2f:0f:95:3d:70:ac:6a:eb:d8:c5:71:
+ 9a:cf:a9:a6:6a:ce:45:07:a4:41:de:85:fb:ad:e0:
+ 39:0b:6f
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints:
+ CA:FALSE
+ X509v3 Key Usage:
+ Digital Signature, Non Repudiation, Key Encipherment
+ X509v3 Extended Key Usage:
+ Signing KDC Response
+ X509v3 Subject Key Identifier:
+ 62:AF:D5:17:E4:9F:2A:8D:8A:CA:2B:05:E1:25:66:BB:61:03:77:EA
+ X509v3 Subject Alternative Name:
+ othername:<unsupported>
+ Signature Algorithm: sha1WithRSAEncryption
+ 41:29:9f:70:6b:36:28:cc:86:e1:4d:ae:25:34:b1:24:ab:f8:
+ 03:de:28:da:d1:13:8e:03:d3:5a:57:72:69:f9:04:1c:e0:1d:
+ 14:91:c7:a0:8b:ab:c7:61:6e:4e:86:2a:2a:40:22:10:10:58:
+ 0c:18:95:eb:d2:15:18:35:3c:fc:42:25:1a:dc:03:cb:ba:f3:
+ 81:80:d2:45:4e:c6:90:11:2f:e9:db:76:9a:e3:1d:0c:04:dc:
+ fb:d9:ec:bd:48:38:66:78:d6:52:c2:bc:ae:20:9b:1d:87:28:
+ 9f:38:fa:db:8f:17:1f:3e:29:85:17:a0:95:bd:72:88:0c:93:
+ 88:ba:8e:31:67:2b:03:b0:bf:3a:7e:e4:e2:82:f7:6c:36:1a:
+ d1:8e:7c:87:63:17:e4:68:7f:4b:e7:dc:40:b5:02:5a:62:be:
+ 54:ee:11:30:39:80:2a:c0:3e:8f:3b:67:cb:9d:9f:ee:c1:ea:
+ f1:4c:e8:55:24:6a:73:84:ef:82:ca:99:ec:84:05:5e:82:a1:
+ 52:40:5e:71:10:c9:c3:9b:18:ce:7f:50:db:8a:49:d4:b6:b9:
+ 5e:ef:13:4c:e8:be:76:2b:cc:f9:eb:9e:9b:4b:29:8e:ee:1c:
+ e5:bd:08:f0:50:63:e2:c3:94:20:2f:fe:cb:6a:ed:2b:2a:e2:
+ 51:44:3d:06:d1:b4:43:26:43:07:4d:c9:e1:4f:9d:3d:0f:a6:
+ 74:93:ff:51:74:c8:aa:2d:76:ab:93:6f:84:47:2d:70:37:d2:
+ 21:f0:cb:4d:a5:8b:df:91:4b:95:f0:ba:fe:d9:fc:f2:ed:b5:
+ e7:91:03:5a:ad:12:43:f3:ba:c8:a7:51:34:9b:40:bd:71:39:
+ af:b1:9f:e4:9f:3f:1b:27:a5:84:43:a2:c3:3f:52:63:a8:bf:
+ 8b:59:82:53:b5:26:64:16:73:90:f8:7b:7d:ce:f6:41:b6:8b:
+ 81:56:90:c2:ff:46:46:8f:63:3d:95:d9:f0:49:73:37:d9:14:
+ 2b:26:95:ac:19:29:1d:cb:c2:03:d7:36:4e:4a:39:3e:51:02:
+ de:aa:dc:6b:77:a8:57:ba:50:21:0e:8e:b7:48:bc:44:fa:45:
+ db:c9:bb:72:ea:e4:2a:7a:35:75:3c:68:29:5d:b9:57:0b:d3:
+ 2e:2c:4f:01:1b:f0:21:0c:fc:95:17:b7:40:be:aa:0c:f9:04:
+ 60:6a:d1:54:0d:b9:68:d7:e9:7a:f4:96:ad:f1:a0:15:15:c2:
+ 51:61:44:5f:0e:bb:98:d1:81:9f:c1:81:d6:e2:26:d5:11:56:
+ d2:cd:0f:9c:6b:69:f0:78:24:ff:bf:df:02:2b:0d:d1:83:5b:
+ 14:4d:c0:e2:80:47:65:2b
+-----BEGIN CERTIFICATE-----
+MIIFWzCCA0OgAwIBAgIBCDANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw
+OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMCAXDTE5MDMyMjIyMjUwOVoYDzI1
+MTgxMTIxMjIyNTA5WjAbMQswCQYDVQQGEwJTRTEMMAoGA1UEAwwDa2RjMIICIjAN
+BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0XPsWGd6ZTCrGRWhvx7e2+VKkvCZ
+iusCbeQxGsdNB1exgp7S0sfzC7KCYVy6OMNU6eG+a18NImIry9U0DmMLUIqLs75q
+4YXcsSgT7t1uQNVIHeuqBAvnyBxtYFS2zL5SWogizgctP8v8AKuLpecyjrGLA9iB
+omnUnzr/2rXjDeMhVCnLYboWE5SXG3IkbdrX2TWxV/E7ne6Qdk5YH052EsaJKlS/
+6FNa3gV5kwtBLAPFMFio5lcI+Ud8wDpc6xszaFICGQjmNUgFp1EiiRweyAtVc7LJ
+dfl0qt5eOlT4lkfPJS1153F0MZEXhUSJihaIyhLdDjZN5a+z29N8U416CGmScoHI
+E8dxlo8tVJjJYxAmvlmP24JHwSnGKH+gFr+FousvL0aGa3cfMTDUUjUyCRbNSOw8
+TCwD5bmQ6fe0fZeRMSdO37a9tuzKRxYAWOmHTyCv70w0Qls+KKrNOXU7b3y5e1B2
+ZyUxRvU0qsZaIne1nW2ITfHm58rS2HAQWDlYD86Ns03k9IDKMXU8OGFs2RfSqnL5
+4KyGqzMWhOjI3lideKzxKmS44/LLIELd+b0uwoRuETR2pcVUxVGby4XRBYIcM9WV
+GK1MlNJ7T3Ij/8FLouoaOhjC9cgIdgASJeXuMLmNLw+VPXCsauvYxXGaz6mmas5F
+B6RB3oX7reA5C28CAwEAAaOBmDCBlTAJBgNVHRMEAjAAMAsGA1UdDwQEAwIF4DAS
+BgNVHSUECzAJBgcrBgEFAgMFMB0GA1UdDgQWBBRir9UX5J8qjYrKKwXhJWa7YQN3
+6jBIBgNVHREEQTA/oD0GBisGAQUCAqAzMDGgDRsLVEVTVC5INUwuU0WhIDAeoAMC
+AQGhFzAVGwZrcmJ0Z3QbC1RFU1QuSDVMLlNFMA0GCSqGSIb3DQEBBQUAA4ICAQBB
+KZ9wazYozIbhTa4lNLEkq/gD3ija0ROOA9NaV3Jp+QQc4B0Ukcegi6vHYW5Ohioq
+QCIQEFgMGJXr0hUYNTz8QiUa3APLuvOBgNJFTsaQES/p23aa4x0MBNz72ey9SDhm
+eNZSwryuIJsdhyifOPrbjxcfPimFF6CVvXKIDJOIuo4xZysDsL86fuTigvdsNhrR
+jnyHYxfkaH9L59xAtQJaYr5U7hEwOYAqwD6PO2fLnZ/uwerxTOhVJGpzhO+Cypns
+hAVegqFSQF5xEMnDmxjOf1DbiknUtrle7xNM6L52K8z5656bSymO7hzlvQjwUGPi
+w5QgL/7Lau0rKuJRRD0G0bRDJkMHTcnhT509D6Z0k/9RdMiqLXark2+ERy1wN9Ih
+8MtNpYvfkUuV8Lr+2fzy7bXnkQNarRJD87rIp1E0m0C9cTmvsZ/knz8bJ6WEQ6LD
+P1JjqL+LWYJTtSZkFnOQ+Ht9zvZBtouBVpDC/0ZGj2M9ldnwSXM32RQrJpWsGSkd
+y8ID1zZOSjk+UQLeqtxrd6hXulAhDo63SLxE+kXbybty6uQqejV1PGgpXblXC9Mu
+LE8BG/AhDPyVF7dAvqoM+QRgatFUDblo1+l69Jat8aAVFcJRYURfDruY0YGfwYHW
+4ibVEVbSzQ+ca2nweCT/v98CKw3Rg1sUTcDigEdlKw==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/kdc.key b/third_party/heimdal/lib/hx509/data/kdc.key
new file mode 100644
index 0000000..1984f20
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/kdc.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQDRc+xYZ3plMKsZ
+FaG/Ht7b5UqS8JmK6wJt5DEax00HV7GCntLSx/MLsoJhXLo4w1Tp4b5rXw0iYivL
+1TQOYwtQiouzvmrhhdyxKBPu3W5A1Ugd66oEC+fIHG1gVLbMvlJaiCLOBy0/y/wA
+q4ul5zKOsYsD2IGiadSfOv/ateMN4yFUKcthuhYTlJcbciRt2tfZNbFX8Tud7pB2
+TlgfTnYSxokqVL/oU1reBXmTC0EsA8UwWKjmVwj5R3zAOlzrGzNoUgIZCOY1SAWn
+USKJHB7IC1Vzssl1+XSq3l46VPiWR88lLXXncXQxkReFRImKFojKEt0ONk3lr7Pb
+03xTjXoIaZJygcgTx3GWjy1UmMljECa+WY/bgkfBKcYof6AWv4Wi6y8vRoZrdx8x
+MNRSNTIJFs1I7DxMLAPluZDp97R9l5ExJ07ftr227MpHFgBY6YdPIK/vTDRCWz4o
+qs05dTtvfLl7UHZnJTFG9TSqxloid7WdbYhN8ebnytLYcBBYOVgPzo2zTeT0gMox
+dTw4YWzZF9KqcvngrIarMxaE6MjeWJ14rPEqZLjj8ssgQt35vS7ChG4RNHalxVTF
+UZvLhdEFghwz1ZUYrUyU0ntPciP/wUui6ho6GML1yAh2ABIl5e4wuY0vD5U9cKxq
+69jFcZrPqaZqzkUHpEHehfut4DkLbwIDAQABAoICAH37+GGEfH55M7E27b+D1hD2
+blDMH88LZL6sz0yILLEJ8l/bIHxggLS8fugJWoniFCVJ/7udxMy1uBo298TflmKv
+szA+jRNx7TkyHitDTZn5sBMvOWiNsLERSEj1K68jm22RDT5X2sPQ8peEl88GrcZe
+zHtXs0H53kaYumTXmuczg0yYhxkVUUodynZbxcW+KK8iOLXpCC8K3CINJbxO+X55
+pO+tYnFgEfwR1vq3fk/3RJi7+3vxRhiLA2KsuE9CYT2SdmiQjcfmtl/Z0agfHfS9
+vHyHQd6QWbidYJg9m/jo4JRAL/cyqu1VlIw4mXJR8514kzaFO324nbrQDqxDIO7v
+jvFL9SjnReVxUjfnQ7W5BackMn7rxaa4gGm3P1ZAYY0DrSBThlleKkuGhuOHaRFG
+P3uPjfar4ybGnozqCrVpuFJLOtQocdJpPBdQtS0WuE3sMOUkOV9HfqxusnS074on
+2qn3Yy7PhKBfqBYKVqd0l99QHjwr3/0VLjDpnVvvFZFDcH9uL9daD+JfZj3aaGdv
+bmPGwO4svlVEDzfScoI3NnReGEH/bgmdbaPBcSiX42NX12XHWZ55d9grQlJWdSw5
+W8+Dqy86/gCA0VJ4fKaJM5ZGbngOwjgCYZkNHyFo42/zTFSI1S9PiWTNAHPGqZyD
+nOjpXLR1N+dk0yBwpOQhAoIBAQDy5BeFO+mqp3NWHZXVoy+THqumajCR5AjEsbFl
+aWosL99Zk/avfA7G8orHXrAj1XEsGxkFtCnRUlg35LqMYK1tYYIk5NqdFCAeQUOe
+7NgNlicjiKG+a69bQ5TOtgmtdhIh+Uu1yNgbNelWJFizyxoFFFX7jp52utNWix3r
+x6LfTZmNUQqbFetuMKln0WzVwa0uqezzvxZ7oPLVeEc4LT7wtKTPDf6/VTfoeLoO
+JvvMb5cnKZGQmpC8Jub5mRkEFcUIGmbKM2G9sRFPNt2Lh08xVCDXEJSFZPiBpLGP
+6TvJ9DkKEd0Shj0VdnV9304XkcFdfjWIDHlfLJnzwn++Wx9rAoIBAQDcwdUVfsFE
+kVJtdWjtAAj1uSEAPDiggfDhTlOsJMQ3U7PlmdgiafNMKpzmLwqH8Pe5IK4Z9KZ1
+pT+d89udXGOUXhqU6kvxfVu3S7skE9r5DYS/kg7xXJerir+fGsZ5lGDqz90xYxhp
+ect5jOtsRxDlI7Vg5guUp30h8FsAdrP42jiUZxy4AkBdVuyqKAbl5ZtnV4eCk3fV
+iLyVmD27I6h8jnvGvPVODjpesuu7XzQe9ZhyAU/7JSsshLKoKIjwZSx77dhfqI9i
+pm1cwhKbT7opZa2zuXd1h/nDo4SLOfBRTQ+424NPhfk754HKup+lskXuedlumqhj
+z6V8QbfjVRkNAoIBAG+WxQuMC/1AMyfkLbtZ3niLxbaN4MSV7EVZkbOSq5mjYMyJ
+wvK6XxudwI55/RhpbjYiOOu66t9lImyDZAUsQWEYRC9pCNrTrTHZMBTqoRQU4ORd
+WFngpU6bjNkvHuEXdpsvKk5Y+Jf/u7S8vBfV/p1Iy3vn+Pt5N7Dx9wwkyromr54S
+FnpLpr8YEixFNeg6s7LVlKwjJVQlDItwV+ACQYFarMEHn/sNTsM5+9iWpmY0+k+e
+tGan7EjU4pbXdHvA+KWRY5oP4x7AI8Ct5zi8MHDsQq4ryuBCFD2TiZQhRjuxPSdY
+L6XcEGI06yOqHPmNGDY4zqUzfetw1UX9HK06tgMCggEAF5UZRz+QM9v2Wz0UpWTA
+kEdjkBvezL601czBQX13/JUTfa6OmTaKSBOxSSGzVUxXmk40aw9ojN7HSf9X8ZqC
+BMJ8wnW5ASYsGwubBUKdvMdF7BUVRZFnnmqnB78bfrdsFwl3jqQQYowhQW3dZGa/
+FktXP++zQwEVa/+6KPWFSks9ihTty3ZqG86CX7cA7aQ2kraWAkvwnD4ML0rhJVGs
+2Ql7jYJ4DguVDrK8XfrQnZIM4/jh62lQEGRolXAnGM8mDmMdHzLphldTDXqp9C9z
+KqLzCGUCruqEsvKP4TOiSX0a9dt1TpR4SH71rYt8LH473DrmEFuzK15uRjTbCQz5
+LQKCAQEA0hy4cQ07D32jcaN0xQ40Av8fO3dDwgcrSrTfBIk2naa7w9ssshhIFCWT
+pXC68HjbXJAm+FUmzp1wyj1ss+1CWSHD9sWPUwJj/T0fGSfpPKC5UpuvSMXRsych
+DX2WwGIExAHDF1vHlhc9mn26IZo+oZPA1X2SqurKz7RYuDXpiAdMQx1azjMuzQF0
+xBPoILyT4ZgDW1YCs87QF+Rk7x6S1HePF0dCDo6vke34ydZe+by/UnLhiGtbTtI7
+uBLJkF39dTie3vP+2I6eQbV+RUhhf1MGHSf8tVw7sIdtTbB3b7pEemMQhpyGJ02P
+RCBsiAswkZ1vTsDII1BKYPknuvgH9g==
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/key.der b/third_party/heimdal/lib/hx509/data/key.der
new file mode 100644
index 0000000..e7c665e
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/key.der
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/key2.der b/third_party/heimdal/lib/hx509/data/key2.der
new file mode 100644
index 0000000..fe3f413
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/key2.der
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/mkcert.sh b/third_party/heimdal/lib/hx509/data/mkcert.sh
new file mode 100755
index 0000000..c06528d
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/mkcert.sh
@@ -0,0 +1,83 @@
+#! /bin/bash
+
+set -e
+
+DAYS=182500
+
+key() {
+ local key=$1; shift
+
+ if [ ! -f "${key}.pem" ]; then
+ openssl genpkey \
+ -paramfile <(openssl ecparam -name prime256v1) \
+ -out "${key}.pem"
+ fi
+}
+
+req() {
+ local key=$1; shift
+ local dn=$1; shift
+
+ openssl req -new -sha256 -key "${key}.pem" \
+ -config <(printf "[req]\n%s\n%s\n[dn]\nCN_default=foo\n" \
+ "prompt = yes" "distinguished_name = dn") \
+ -subj "${dn}"
+}
+
+cert() {
+ local cert=$1; shift
+ local exts=$1; shift
+
+ openssl x509 -req -sha256 -out "${cert}.pem" \
+ -extfile <(printf "%s\n" "$exts") "$@"
+}
+
+genroot() {
+ local dn=$1; shift
+ local key=$1; shift
+ local cert=$1; shift
+
+ exts=$(printf "%s\n%s\n%s\n%s\n" \
+ "subjectKeyIdentifier = hash" \
+ "authorityKeyIdentifier = keyid" \
+ "basicConstraints = CA:true" \
+ "keyUsage = keyCertSign, cRLSign" )
+ key "$key"; req "$key" "$dn" |
+ cert "$cert" "$exts" -signkey "${key}.pem" \
+ -set_serial 1 -days "${DAYS}"
+}
+
+genee() {
+ local dn=$1; shift
+ local key=$1; shift
+ local cert=$1; shift
+ local cakey=$1; shift
+ local cacert=$1; shift
+
+ exts=$(printf "%s\n%s\n%s\n%s\n" \
+ "subjectKeyIdentifier = hash" \
+ "authorityKeyIdentifier = keyid, issuer" \
+ "basicConstraints = CA:false" \
+ "keyUsage = digitalSignature, keyEncipherment, dataEncipherment" \
+ )
+ key "$key"; req "$key" "$dn" |
+ cert "$cert" "$exts" -CA "${cacert}.pem" -CAkey "${cakey}.pem" \
+ -set_serial 2 -days "${DAYS}" "$@"
+}
+
+
+genroot "/C=SE/O=Heimdal/CN=CA secp256r1" \
+ secp256r1TestCA.key secp256r1TestCA.cert
+genee "/C=SE/O=Heimdal/CN=Server" \
+ secp256r2TestServer.key secp256r2TestServer.cert \
+ secp256r1TestCA.key secp256r1TestCA.cert
+genee "/C=SE/O=Heimdal/CN=Client" \
+ secp256r2TestClient.key secp256r2TestClient.cert \
+ secp256r1TestCA.key secp256r1TestCA.cert
+
+cat secp256r1TestCA.key.pem secp256r1TestCA.cert.pem > \
+ secp256r1TestCA.pem
+cat secp256r2TestClient.cert.pem secp256r2TestClient.key.pem > \
+ secp256r2TestClient.pem
+cat secp256r2TestServer.cert.pem secp256r2TestServer.key.pem > \
+ secp256r2TestServer.pem
diff --git a/third_party/heimdal/lib/hx509/data/n0ll.pem b/third_party/heimdal/lib/hx509/data/n0ll.pem
new file mode 100644
index 0000000..4b17377
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/n0ll.pem
@@ -0,0 +1,47 @@
+https://www.noisebridge.net/pipermail/noisebridge-discuss/2009-September/008400.html
+
+Jacob Appelbaum jacob at appelbaum.net
+Tue Sep 29 22:51:33 PDT 2009
+
+
+I hope this release will help with confirmation of the bug and with
+regression testing. Feel free to use this certificate for anything
+relating to free software too. Consider it released into the public
+domain of interesting integers.
+
+-----BEGIN CERTIFICATE-----
+MIIGTjCCBbegAwIBAgIDExefMA0GCSqGSIb3DQEBBQUAMIIBEjELMAkGA1UEBhMC
+RVMxEjAQBgNVBAgTCUJhcmNlbG9uYTESMBAGA1UEBxMJQmFyY2Vsb25hMSkwJwYD
+VQQKEyBJUFMgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgcy5sLjEuMCwGA1UEChQl
+Z2VuZXJhbEBpcHNjYS5jb20gQy5JLkYuICBCLUI2MjIxMDY5NTEuMCwGA1UECxMl
+aXBzQ0EgQ0xBU0VBMSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEuMCwGA1UEAxMl
+aXBzQ0EgQ0xBU0VBMSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEgMB4GCSqGSIb3
+DQEJARYRZ2VuZXJhbEBpcHNjYS5jb20wHhcNMDkwNzMwMDcxNDQyWhcNMTEwNzMw
+MDcxNDQyWjCBnjELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAU
+BgNVBAcTDVNhbiBGcmFuY2lzY28xFDASBgNVBAoTC05vaXNlYnJpZGdlMSMwIQYD
+VQQLExpNb3hpZSBNYXJsaW5zcGlrZSBGYW4gQ2x1YjEnMCUGA1UEAxQeKgB0aG91
+Z2h0Y3JpbWUubm9pc2VicmlkZ2UubmV0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB
+iQKBgQDPTRdCAI0MQZUxjEAwvF5CtigJdS8ZYdmrTezzRMQcAZVvJ+twB5hPHgXQ
+82xJRebeSHpZ8MKTajecAnJPvRQ2JqFwl9T+SyTozSkeYRqFsG+WBoMQE9aJn70H
+Z/FC3ptjZ4uW+QbvfJNLavk5MTJ/mFnvzpG+Bc7wgjPYdgZMnwIDAQABo4IDITCC
+Ax0wCQYDVR0TBAIwADARBglghkgBhvhCAQEEBAMCBkAwCwYDVR0PBAQDAgP4MBMG
+A1UdJQQMMAoGCCsGAQUFBwMBMB0GA1UdDgQWBBStfpIwBXE+eXWUWtE3s5JqXon2
+TzAfBgNVHSMEGDAWgBQOB2DUOckbW12QeyPI0jSdSppGOTAJBgNVHREEAjAAMBwG
+A1UdEgQVMBOBEWdlbmVyYWxAaXBzY2EuY29tMHIGCWCGSAGG+EIBDQRlFmNPcmdh
+bml6YXRpb24gSW5mb3JtYXRpb24gTk9UIFZBTElEQVRFRC4gQ0xBU0VBMSBTZXJ2
+ZXIgQ2VydGlmaWNhdGUgaXNzdWVkIGJ5IGh0dHBzOi8vd3d3Lmlwc2NhLmNvbS8w
+LwYJYIZIAYb4QgECBCIWIGh0dHBzOi8vd3d3Lmlwc2NhLmNvbS9pcHNjYTIwMDIv
+MEMGCWCGSAGG+EIBBAQ2FjRodHRwczovL3d3dy5pcHNjYS5jb20vaXBzY2EyMDAy
+L2lwc2NhMjAwMkNMQVNFQTEuY3JsMEYGCWCGSAGG+EIBAwQ5FjdodHRwczovL3d3
+dy5pcHNjYS5jb20vaXBzY2EyMDAyL3Jldm9jYXRpb25DTEFTRUExLmh0bWw/MEMG
+CWCGSAGG+EIBBwQ2FjRodHRwczovL3d3dy5pcHNjYS5jb20vaXBzY2EyMDAyL3Jl
+bmV3YWxDTEFTRUExLmh0bWw/MEEGCWCGSAGG+EIBCAQ0FjJodHRwczovL3d3dy5p
+cHNjYS5jb20vaXBzY2EyMDAyL3BvbGljeUNMQVNFQTEuaHRtbDCBgwYDVR0fBHww
+ejA5oDegNYYzaHR0cDovL3d3dy5pcHNjYS5jb20vaXBzY2EyMDAyL2lwc2NhMjAw
+MkNMQVNFQTEuY3JsMD2gO6A5hjdodHRwOi8vd3d3YmFjay5pcHNjYS5jb20vaXBz
+Y2EyMDAyL2lwc2NhMjAwMkNMQVNFQTEuY3JsMDIGCCsGAQUFBwEBBCYwJDAiBggr
+BgEFBQcwAYYWaHR0cDovL29jc3AuaXBzY2EuY29tLzANBgkqhkiG9w0BAQUFAAOB
+gQAjzXaLBu+/+RP0vQ6WjW/Pxgm4WQYhecqZ2+7ZFbsUCMJPQ8XE2uv+rIteGnRF
+Zr3hYb+dVlfUnethjPhazZW+/hU4FePqmlbTtmMe+zMLThiScyC8y3EW4L4BZYcp
+p1drPlZIj2RmSgPQ99oToUk5O6t+LMg1N14ajr9TpM8yNQ==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/nist-data b/third_party/heimdal/lib/hx509/data/nist-data
new file mode 100644
index 0000000..7407b80
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/nist-data
@@ -0,0 +1,91 @@
+# $Id$
+# id verify cert hxtool-verify-arguments...
+# p(ass) f(ail)
+# Those id's that end with i are invariants of the orignal test
+#
+# 4.1 Signature Verification
+#
+4.1.1 p ValidCertificatePathTest1EE.crt GoodCACert.crt GoodCACRL.crl
+4.1.2 f InvalidCASignatureTest2EE.crt BadSignedCACert.crt BadSignedCACRL.crl
+4.1.3 f InvalidEESignatureTest3EE.crt GoodCACert.crt GoodCACRL.crl
+#4.1.4 p ValidDSASignaturesTest4EE.crt DSACACert.crt DSACACRL.crl
+#4.1.5 p ValidDSAParameterInheritanceTest5EE.crl DSAParametersInheritedCACert.crt DSAParametersInheritedCACRL.crl DSACACert.crt DSACACRL.crl
+#4.1.6 f InvalidDSASignaturesTest6EE.crt DSACACert.crt DSACACRL.crl
+#
+# 4.2 Validity Periods
+#
+4.2.1 f InvalidCAnotBeforeDateTest1EE.crt BadnotBeforeDateCACert.crt BadnotBeforeDateCACRL.crl
+4.2.2 f InvalidEEnotBeforeDateTest2EE.crt GoodCACert.crt GoodCACRL.crl
+4.2.3 p Validpre2000UTCnotBeforeDateTest3EE.crt GoodCACert.crt GoodCACRL.crl
+4.2.4 p ValidGeneralizedTimenotBeforeDateTest4EE.crt GoodCACert.crt GoodCACRL.crl
+4.2.5 f InvalidCAnotAfterDateTest5EE.crt BadnotAfterDateCACert.crt BadnotAfterDateCACRL.crl
+4.2.6 f InvalidEEnotAfterDateTest6EE.crt GoodCACert.crt GoodCACRL.crl
+4.2.7 f Invalidpre2000UTCEEnotAfterDateTest7EE.crt GoodCACert.crt GoodCACRL.crl
+#4.2.8 p ValidGeneralizedTimenotAfterDateTest8EE.crt GoodCACert.crt GoodCACRL.crl
+#
+# 4.4 CRtests
+#
+4.4.1 f InvalidMissingCRLTest1EE.crt NoCRLCACert.crt
+4.4.1i p InvalidMissingCRLTest1EE.crt --missing-revoke NoCRLCACert.crt
+4.4.2 f InvalidRevokedEETest3EE.crt GoodCACert.crt InvalidRevokedCATest2EE.crt GoodCACRL.crl RevokedsubCACRL.crl
+4.4.2i p InvalidRevokedEETest3EE.crt --missing-revoke GoodCACert.crt InvalidRevokedCATest2EE.crt
+4.4.3 f InvalidRevokedEETest3EE.crt GoodCACert.crt GoodCACRL.crl
+4.4.3i p InvalidRevokedEETest3EE.crt --missing-revoke GoodCACert.crt
+4.4.4 f InvalidBadCRLSignatureTest4EE.crt BadCRLSignatureCACert.crt BadCRLSignatureCACRL.crl
+4.4.4i p InvalidBadCRLSignatureTest4EE.crt --missing-revoke BadCRLSignatureCACert.crt
+4.4.5 f InvalidBadCRLIssuerNameTest5EE.crt BadCRLIssuerNameCACert.crt BadCRLIssuerNameCACRL.crl
+4.4.5i p InvalidBadCRLIssuerNameTest5EE.crt --missing-revoke BadCRLIssuerNameCACert.crt
+4.4.6 f InvalidWrongCRLTest6EE.crt WrongCRLCACert.crt WrongCRLCACRL.crl
+4.4.7 p ValidTwoCRLsTest7EE.crt TwoCRLsCACert.crt TwoCRLsCAGoodCRL.crl TwoCRLsCABadCRL.crl
+4.4.8 f InvalidUnknownCRLEntryExtensionTest8EE.crt UnknownCRLEntryExtensionCACert.crt UnknownCRLEntryExtensionCACRL.crl
+4.4.9 f InvalidUnknownCRLExtensionTest9EE.crt UnknownCRLExtensionCACert.crt UnknownCRLExtensionCACRL.crl
+4.4.10 f InvalidUnknownCRLExtensionTest10EE.crt UnknownCRLExtensionCACert.crt UnknownCRLExtensionCACRL.crl
+4.4.11 f InvalidOldCRLnextUpdateTest11EE.crt OldCRLnextUpdateCACert.crt OldCRLnextUpdateCACRL.crl
+4.4.12 f Invalidpre2000CRLnextUpdateTest12EE.crt pre2000CRLnextUpdateCACert.crt pre2000CRLnextUpdateCACRL.crl
+#4.4.13-xxx s ValidGeneralizedTimeCRLnextUpdateTest13EE.crt GeneralizedTimeCRLnextUpdateCACert.crt GeneralizedTimeCRLnextUpdateCACRL.crl
+4.4.14 p ValidNegativeSerialNumberTest14EE.crt NegativeSerialNumberCACert.crt NegativeSerialNumberCACRL.crl
+4.4.15 f InvalidNegativeSerialNumberTest15EE.crt NegativeSerialNumberCACert.crt NegativeSerialNumberCACRL.crl
+4.4.16 p ValidLongSerialNumberTest16EE.crt LongSerialNumberCACert.crt LongSerialNumberCACRL.crl
+4.4.17 p ValidLongSerialNumberTest17EE.crt LongSerialNumberCACert.crt LongSerialNumberCACRL.crl
+4.4.18 f InvalidLongSerialNumberTest18EE.crt LongSerialNumberCACert.crt LongSerialNumberCACRL.crl
+#
+#
+# 4.8 Ceificate Policies
+incomplete4.8.2 p AllCertificatesNoPoliciesTest2EE.crt NoPoliciesCACert.crt NoPoliciesCACRL.crl
+incomplete4.8.10 p AllCertificatesSamePoliciesTest10EE.crt PoliciesP12CACert.crt PoliciesP12CACRL.crl
+incomplete4.8.13 p AllCertificatesSamePoliciesTest13EE.crt PoliciesP123CACert.crt PoliciesP123CACRL.crl
+incomplete4.8.11 p AllCertificatesanyPolicyTest11EE.crt anyPolicyCACert.crt anyPolicyCACRL.crl
+unknown p AnyPolicyTest14EE.crt anyPolicyCACert.crt anyPolicyCACRL.crl
+unknown f BadSignedCACert.crt
+unknown f BadnotAfterDateCACert.crt
+unknown f BadnotBeforeDateCACert.crt
+#
+# 4.13 Name Constraints
+#
+4.13.1 p ValidDNnameConstraintsTest1EE.crt nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl
+4.13.2 f InvalidDNnameConstraintsTest2EE.crt nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl
+4.13.3 f InvalidDNnameConstraintsTest3EE.crt nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl
+4.13.4 p ValidDNnameConstraintsTest4EE.crt nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl
+4.13.5 p ValidDNnameConstraintsTest5EE.crt nameConstraintsDN2CACert.crt nameConstraintsDN2CACRL.crl
+4.13.6 p ValidDNnameConstraintsTest6EE.crt nameConstraintsDN3CACert.crt nameConstraintsDN3CACRL.crl
+4.13.7 f InvalidDNnameConstraintsTest7EE.crt nameConstraintsDN3CACert.crt nameConstraintsDN3CACRL.crl
+4.13.8 f InvalidDNnameConstraintsTest8EE.crt nameConstraintsDN4CACert.crt nameConstraintsDN4CACRL.crl
+4.13.9 f InvalidDNnameConstraintsTest9EE.crt nameConstraintsDN4CACert.crt nameConstraintsDN4CACRL.crl
+4.13.10 f InvalidDNnameConstraintsTest10EE.crt nameConstraintsDN5CACert.crt nameConstraintsDN5CACRL.crl
+4.13.11 p ValidDNnameConstraintsTest11EE.crt nameConstraintsDN5CACert.crt nameConstraintsDN5CACRL.crl
+4.13.12 f InvalidDNnameConstraintsTest12EE.crt nameConstraintsDN1subCA1Cert.crt nameConstraintsDN1subCA1CRL.crl nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl
+4.13.13 f InvalidDNnameConstraintsTest13EE.crt nameConstraintsDN1subCA1Cert.crt nameConstraintsDN1subCA1CRL.crl nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl
+4.13.14 p ValidDNnameConstraintsTest14EE.crt nameConstraintsDN1subCA2Cert.crt nameConstraintsDN1subCA2CRL.crl nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl
+4.13.15 f InvalidDNnameConstraintsTest15EE.crt nameConstraintsDN3subCA1Cert.crt nameConstraintsDN3subCA1CRL.crl nameConstraintsDN3CACert.crt nameConstraintsDN3CACRL.crl
+4.13.16 f InvalidDNnameConstraintsTest16EE.crt nameConstraintsDN3subCA1Cert.crt nameConstraintsDN3subCA1CRL.crl nameConstraintsDN3CACert.crt nameConstraintsDN3CACRL.crl
+4.13.17 f InvalidDNnameConstraintsTest17EE.crt nameConstraintsDN3subCA2Cert.crt nameConstraintsDN3subCA2CRL.crl nameConstraintsDN3CACert.crt nameConstraintsDN3CACRL.crl
+4.13.18 p ValidDNnameConstraintsTest18EE.crt nameConstraintsDN3subCA2Cert.crt nameConstraintsDN3subCA2CRL.crl nameConstraintsDN3CACert.crt nameConstraintsDN3CACRL.crl
+#
+# no crl for self issued cert
+#
+#4.13.19 p ValidDNnameConstraintsTest19EE.crt nameConstraintsDN1SelfIssuedCACert.crt nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl
+# ??
+4.13.20 f InvalidDNnameConstraintsTest20EE.crt nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl
+#4.13.21 p ValidRFC822nameConstraintsTest21EE.crt nameConstraintsRFC822CA1Cert.crt nameConstraintsRFC822CA1CRL.crl
+#page 74
+end
diff --git a/third_party/heimdal/lib/hx509/data/nist-data2 b/third_party/heimdal/lib/hx509/data/nist-data2
new file mode 100644
index 0000000..491beac
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/nist-data2
@@ -0,0 +1,291 @@
+# 4.1.1 Valid Signatures Test1 - Validate Successfully
+0 ValidCertificatePathTest1EE.crt
+# 4.1.2 Invalid CA Signature Test2 - Reject - Invalid signature on intermediate certificate
+1 InvalidCASignatureTest2EE.crt
+# 4.1.3 Invalid EE Signature Test3 - Reject - Invalid signature on end entity certificate
+1 InvalidEESignatureTest3EE.crt
+# 4.1.4 Valid DSA Signatures Test4 - Reject - Application can not process DSA signatures
+1 ValidDSASignaturesTest4EE.crt
+# 4.2.1 Invalid CA notBefore Date Test1 - Reject - notBefore date in intermediate certificate is after the current date
+1 InvalidCAnotBeforeDateTest1EE.crt
+# 4.2.2 Invalid EE notBefore Date Test2 - Reject - notBefore date in end entity certificate is after the current date
+1 InvalidEEnotBeforeDateTest2EE.crt
+# 4.2.3 Valid pre2000 UTC notBefore Date Test3 - Validate Successfully
+0 Validpre2000UTCnotBeforeDateTest3EE.crt
+# 4.2.4 Valid GeneralizedTime notBefore Date Test4 - Validate Successfully
+0 ValidGeneralizedTimenotBeforeDateTest4EE.crt
+# 4.2.5 Invalid CA notAfter Date Test5 - Reject - notAfter date in intermediate certificate is before the current date
+1 InvalidCAnotAfterDateTest5EE.crt
+# 4.2.6 Invalid EE notAfter Date Test6 - Reject - notAfter date in end entity certificate is before the current date
+1 InvalidEEnotAfterDateTest6EE.crt
+# 4.2.7 Invalid pre2000 UTC EE notAfter Date Test7 - Reject - notAfter date in end entity certificate is before the current date
+1 Invalidpre2000UTCEEnotAfterDateTest7EE.crt
+# 4.2.8 Valid GeneralizedTime notAfter Date Test8 - Validate Successfully
+0 ValidGeneralizedTimenotAfterDateTest8EE.crt
+# 4.3.1 Invalid Name Chaining EE Test1 - Reject - names do not chain
+1 InvalidNameChainingTest1EE.crt
+# 4.3.2 Invalid Name Chaining Order Test2 - Reject - names do not chain
+1 InvalidNameChainingOrderTest2EE.crt
+# 4.3.3 Valid Name Chaining Whitespace Test3 - Validate Successfully
+0 ValidNameChainingWhitespaceTest3EE.crt
+# 4.3.4 Valid Name Chaining Whitespace Test4 - Validate Successfully
+0 ValidNameChainingWhitespaceTest4EE.crt
+# 4.3.5 Valid Name Chaining Capitalization Test5 - Validate Successfully
+0 ValidNameChainingCapitalizationTest5EE.crt
+# 4.3.6 Valid Name Chaining UIDs Test6 - Validate Successfully
+0 ValidNameUIDsTest6EE.crt
+# 4.3.9 Valid UTF8String Encoded Names Test9 - Validate Successfully
+0 ValidUTF8StringEncodedNamesTest9EE.crt
+# 4.4.1 Missing CRL Test1 - Reject or Warn - status of end entity certificate can not be determined
+3 InvalidMissingCRLTest1EE.crt
+# 4.4.2 Invalid Revoked CA Test2 - Reject - an intermediate certificate has been revoked.
+2 InvalidRevokedCATest2EE.crt
+# 4.4.3 Invalid Revoked EE Test3 - Reject - the end entity certificate has been revoked
+2 InvalidRevokedEETest3EE.crt
+# 4.4.4. Invalid Bad CRL Signature Test4 - Reject or Warn - status of end entity certificate can not be determined
+3 InvalidBadCRLSignatureTest4EE.crt
+# 4.4.5 Invalid Bad CRL Issuer Name Test5 - Reject or Warn - status of end entity certificate can not be determined
+3 InvalidBadCRLIssuerNameTest5EE.crt
+# 4.4.6 Invalid Wrong CRL Test6 - Reject or Warn - status of end entity certificate can not be determined
+3 InvalidWrongCRLTest6EE.crt
+# 4.4.7 Valid Two CRLs Test7 - Validate Successfully
+0 ValidTwoCRLsTest7EE.crt
+# 4.4.8 Invalid Unknown CRL Entry Extension Test8 - Reject - the end entity certificate has been revoked
+2 InvalidUnknownCRLEntryExtensionTest8EE.crt
+# 4.4.9 Invalid Unknown CRL Extension Test9 - Reject - the end entity certificate has been revoked
+2 InvalidUnknownCRLExtensionTest9EE.crt
+# 4.4.10 Invalid Unknown CRL Extension Test10 - Reject or Warn - status of end entity certificate can not be determined
+3 InvalidUnknownCRLExtensionTest10EE.crt
+# 4.4.11 Invalid Old CRL nextUpdate Test11 - Reject or Warn - status of end entity certificate can not be determined
+3 InvalidOldCRLnextUpdateTest11EE.crt
+# 4.4.12 Invalid pre2000 CRL nextUpdate Tesst12 - Reject or Warn - status of end entity certificate can not be determined
+3 Invalidpre2000CRLnextUpdateTest12EE.crt
+# 4.4.13 Valid GeneralizedTime CRL nextUpdate Test13 - Validate Successfully
+0 ValidGeneralizedTimeCRLnextUpdateTest13EE.crt
+# 4.4.14 Valid Negative Serial Number Test14 - Validate Successfully
+0 ValidNegativeSerialNumberTest14EE.crt
+# 4.4.15 Invalid Negative Serial Number Test15 - Reject - the end entity certificate has been revoked
+2 InvalidNegativeSerialNumberTest15EE.crt
+# 4.4.16 Valid Long Serial Number Test16 - Validate Successfully
+0 ValidLongSerialNumberTest16EE.crt
+# 4.4.17 Valid Long Serial Number Test17 - Validate Successfully
+0 ValidLongSerialNumberTest17EE.crt
+# 4.4.18 Invalid Long Serial Number Test18 - Reject - the end entity certificate has been revoked
+2 InvalidLongSerialNumberTest18EE.crt
+# 4.4.19 Valid Separate Certificate and CRL Keys Test19 - Validate Successfully
+0 ValidSeparateCertificateandCRLKeysTest19EE.crt
+# 4.4.20 Invalid Separate Certificate and CRL Keys Test20 - Reject - the end entity certificate has been revoked
+2 InvalidSeparateCertificateandCRLKeysTest20EE.crt
+# 4.4.21 Invalid Separate Certificate and CRL Keys Test21 - Reject or Warn - status of end entity certificate can not be determined
+3 InvalidSeparateCertificateandCRLKeysTest21EE.crt
+# 4.5.1 Valid Basic Self-Issued Old With New Test1 - Validate Successfully
+0 ValidBasicSelfIssuedOldWithNewTest1EE.crt
+# 4.5.2 Invalid Basic Self-Issued Old With New Test2 - Reject - the end entity certificate has been revoked
+2 InvalidBasicSelfIssuedOldWithNewTest2EE.crt
+# 4.5.3 Valid Basic Self-Issued New With Old Test3 - Validate Successfully
+0 ValidBasicSelfIssuedNewWithOldTest3EE.crt
+# 4.5.4 Valid Basic Self-Issued New With Old Test4 - Validate Successfully
+0 ValidBasicSelfIssuedNewWithOldTest4EE.crt
+# 4.5.5 Invalid Basic Self-Issued New With Old Test5 - Reject - the end entity certificate has been revoked
+2 InvalidBasicSelfIssuedNewWithOldTest5EE.crt
+# 4.5.6 Valid Basic Self-Issued CRL Signing Key Test6 - Validate Successfully
+0 ValidBasicSelfIssuedCRLSigningKeyTest6EE.crt
+# 4.5.7 Invalid Basic Self-Issued CRL Signing Key Test7 - Reject - the end entity certificate has been revoked
+2 InvalidBasicSelfIssuedCRLSigningKeyTest7EE.crt
+# 4.5.8 Invalid Basic Self-Issued CRL Signing Key Test8 - Reject - invalid certification path
+1 InvalidBasicSelfIssuedCRLSigningKeyTest8EE.crt
+# 4.6.1 Invalid Missing basicConstraints Test1 - Reject - invalid certification path
+1 InvalidMissingbasicConstraintsTest1EE.crt
+# 4.6.2 Invalid cA False Test2 - Reject - invalid certification path
+1 InvalidcAFalseTest2EE.crt
+# 4.6.3 Invalid cA False Test3 - Reject - invalid certification path
+1 InvalidcAFalseTest3EE.crt
+# 4.6.4 Valid basicConstraints Not Critical Test4 - Validate Successfully
+0 ValidbasicConstraintsNotCriticalTest4EE.crt
+# 4.6.5 Invalid pathLenConstraint Test5 - Reject - invalid certification path
+1 InvalidpathLenConstraintTest5EE.crt
+# 4.6.6 Invalid pathLenConstraint Test6 - Reject - invalid certification path
+1 InvalidpathLenConstraintTest6EE.crt
+# 4.6.7 Valid pathLenConstraint Test7 - Validate Successfully
+0 ValidpathLenConstraintTest7EE.crt
+# 4.6.8 Valid pathLenConstraint Test8 - Validate Successfully
+0 ValidpathLenConstraintTest8EE.crt
+# 4.6.9 Invalid pathLenConstraint Test9 - Reject - invalid certification path
+1 InvalidpathLenConstraintTest9EE.crt
+# 4.6.10 Invalid pathLenConstraint Test10 - Reject - invalid certification path
+1 InvalidpathLenConstraintTest10EE.crt
+# 4.6.11 Invalid pathLenConstraint Test11 - Reject - invalid certification path
+1 InvalidpathLenConstraintTest11EE.crt
+# 4.6.12 Invalid pathLenConstraint Test12 - Reject - invalid certification path
+1 InvalidpathLenConstraintTest12EE.crt
+# 4.6.13 Valid pathLenConstraint Test13 - Validate Successfully
+0 ValidpathLenConstraintTest13EE.crt
+# 4.6.14 Valid pathLenConstraint Test14 - Validate Successfully
+0 ValidpathLenConstraintTest14EE.crt
+# 4.6.15 Valid Self-Issued pathLenConstraint Test15 - Validate Successfully
+0 ValidSelfIssuedpathLenConstraintTest15EE.crt
+# 4.6.16 Invalid Self-Issued pathLenConstraint Test16 - Reject - invalid certification path
+1 InvalidSelfIssuedpathLenConstraintTest16EE.crt
+# 4.6.17 Valid Self-Issued pathLenConstraint Test17 - Validate Successfully
+0 ValidSelfIssuedpathLenConstraintTest17EE.crt
+# 4.7.1 Invalid keyUsage Critical keyCertSign False Test1 - Reject - invalid certification path
+1 InvalidkeyUsageCriticalkeyCertSignFalseTest1EE.crt
+# 4.7.2 Invalid keyUsage Not Critical keyCertSign False Test2 - Reject - invalid certification path
+1 InvalidkeyUsageNotCriticalkeyCertSignFalseTest2EE.crt
+# 4.7.3 Valid keyUsage Not Critical Test3 - Validate Successfully
+0 ValidkeyUsageNotCriticalTest3EE.crt
+# 4.7.4 Invalid keyUsage Critical cRLSign False Test4 - Reject - invalid certification path
+1 InvalidkeyUsageCriticalcRLSignFalseTest4EE.crt
+# 4.7.5 Invalid keyUsage Not Critical cRLSign False Test5 - Reject - invalid certification path
+1 InvalidkeyUsageNotCriticalcRLSignFalseTest5EE.crt
+0 UserNoticeQualifierTest19EE.crt
+# 4.10.1 Valid Policy Mapping Test1, subtest 1 - Reject - unrecognized critical extension [Test using the default settings (i.e., <i>initial-policy-set</i> = <i>any-policy</i>)
+1 InvalidSelfIssuedrequireExplicitPolicyTest8EE.crt
+# 4.11.2 Valid inhibitPolicyMapping Test2 - Reject - unrecognized critical extension
+1 ValidinhibitPolicyMappingTest2EE.crt
+# 4.12.2 Valid inhibitAnyPolicy Test2 - Reject - unrecognized critical extension
+1 ValidinhibitAnyPolicyTest2EE.crt
+# 4.13.1 Valid DN nameConstraints Test1 - Validate Successfully
+0 ValidDNnameConstraintsTest1EE.crt
+# 4.13.2 Invalid DN nameConstraints Test2 - Reject - name constraints violation
+1 InvalidDNnameConstraintsTest2EE.crt
+# 4.13.3 Invalid DN nameConstraints Test3 - Reject - name constraints violation
+1 InvalidDNnameConstraintsTest3EE.crt
+# 4.13.4 Valid DN nameConstraints Test4 - Validate Successfully
+0 ValidDNnameConstraintsTest4EE.crt
+# 4.13.5 Valid DN nameConstraints Test5 - Validate Successfully
+0 ValidDNnameConstraintsTest5EE.crt
+# 4.13.6 Valid DN nameConstraints Test6 - Validate Successfully
+0 ValidDNnameConstraintsTest6EE.crt
+# 4.13.7 Invalid DN nameConstraints Test7 - Reject - name constraints violation
+1 InvalidDNnameConstraintsTest7EE.crt
+# 4.13.8 Invalid DN nameConstraints Test8 - Reject - name constraints violation
+1 InvalidDNnameConstraintsTest8EE.crt
+# 4.13.9 Invalid DN nameConstraints Test9 - Reject - name constraints violation
+1 InvalidDNnameConstraintsTest9EE.crt
+# 4.13.10 Invalid DN nameConstraints Test10 - Reject - name constraints violation
+1 InvalidDNnameConstraintsTest10EE.crt
+# 4.13.11 Valid DN nameConstraints Test11 - Validate Successfully
+0 ValidDNnameConstraintsTest11EE.crt
+# 4.13.12 Invalid DN nameConstraints Test12 - Reject - name constraints violation
+1 InvalidDNnameConstraintsTest12EE.crt
+# 4.13.13 Invalid DN nameConstraints Test13 - Reject - name constraints violation
+1 InvalidDNnameConstraintsTest13EE.crt
+# 4.13.14 Valid DN nameConstraints Test14 - Validate Successfully
+0 ValidDNnameConstraintsTest14EE.crt
+# 4.13.15 Invalid DN nameConstraints Test15 - Reject - name constraints violation
+1 InvalidDNnameConstraintsTest15EE.crt
+# 4.13.16 Invalid DN nameConstraints Test16 - Reject - name constraints violation
+1 InvalidDNnameConstraintsTest16EE.crt
+# 4.13.17 Invalid DN nameConstraints Test17 - Reject - name constraints violation
+1 InvalidDNnameConstraintsTest17EE.crt
+# 4.13.18 Valid DN nameConstraints Test18 - Validate Successfully
+0 ValidDNnameConstraintsTest18EE.crt
+# 4.13.19 Valid Self-Issued DN nameConstraints Test19 - Validate Successfully
+0 ValidDNnameConstraintsTest19EE.crt
+# 4.13.20 Invalid Self-Issued DN nameConstraints Test20 - Reject - name constraints violation
+1 InvalidDNnameConstraintsTest20EE.crt
+# 4.13.21 Valid RFC822 nameConstraints Test21 - Validate Successfully
+0 ValidRFC822nameConstraintsTest21EE.crt
+# 4.13.22 Invalid RFC822 nameConstraints Test22 - Reject - name constraints violation
+1 InvalidRFC822nameConstraintsTest22EE.crt
+# 4.13.23 Valid RFC822 nameConstraints Test23 - Validate Successfully
+0 ValidRFC822nameConstraintsTest23EE.crt
+# 4.13.24 Invalid RFC822 nameConstraints Test24 - Reject - name constraints violation
+1 InvalidRFC822nameConstraintsTest24EE.crt
+# 4.13.25 Valid RFC822 nameConstraints Test25 - Validate Successfully
+0 ValidRFC822nameConstraintsTest25EE.crt
+# 4.13.26 Invalid RFC822 nameConstraints Test26 - Reject - name constraints violation
+1 InvalidRFC822nameConstraintsTest26EE.crt
+# 4.13.27 Valid DN and RFC822 nameConstraints Test27 - Validate Successfully
+0 ValidDNandRFC822nameConstraintsTest27EE.crt
+# 4.13.28 Invalid DN and RFC822 nameConstraints Test28 - Reject - name constraints violation
+1 InvalidDNandRFC822nameConstraintsTest28EE.crt
+# 4.13.29 Invalid DN and RFC822 nameConstraints Test29 - Reject - name constraints violation
+1 InvalidDNandRFC822nameConstraintsTest29EE.crt
+# 4.13.30 Valid DNS nameConstraints Test30 - Validate Successfully
+0 ValidDNSnameConstraintsTest30EE.crt
+# 4.13.31 Invalid DNS nameConstraints Test31 - Reject - name constraints violation
+1 InvalidDNSnameConstraintsTest31EE.crt
+# 4.13.32 Valid DNS nameConstraints Test32 - Validate Successfully
+0 ValidDNSnameConstraintsTest32EE.crt
+# 4.13.33 Invalid DNS nameConstraints Test33 - Reject - name constraints violation
+1 InvalidDNSnameConstraintsTest33EE.crt
+# 4.13.34 Valid URI nameConstraints Test34 - Validate Successfully
+0 ValidURInameConstraintsTest34EE.crt
+# 4.13.35 Invalid URI nameConstraints Test35 - Reject - name constraints violation
+1 InvalidURInameConstraintsTest35EE.crt
+# 4.13.36 Valid URI nameConstraints Test36 - Validate Successfully
+0 ValidURInameConstraintsTest36EE.crt
+# 4.13.37 Invalid URI nameConstraints Test37 - Reject - name constraints violation
+1 InvalidURInameConstraintsTest37EE.crt
+# 4.13.38 Invalid DNS nameConstraints Test38 - Reject - name constraints violation
+1 InvalidDNSnameConstraintsTest38EE.crt
+# 4.14.1 Valid distributionPoint Test1 - Validate Successfully
+0 ValiddistributionPointTest1EE.crt
+# 4.14.2 Invalid distributionPoint Test2 - Reject - end entity certificate has been revoked
+2 InvaliddistributionPointTest2EE.crt
+# 4.14.3 Invalid distributionPoint Test3 - Reject or Warn - status of end entity certificate can not be determined
+3 InvaliddistributionPointTest3EE.crt
+# 4.14.4 Valid distributionPoint Test4 - Validate Successfully
+0 ValiddistributionPointTest4EE.crt
+# 4.14.5 Valid distributionPoint Test5 - Validate Successfully
+0 ValiddistributionPointTest5EE.crt
+# 4.14.6 Invalid distributionPoint Test6 - Reject - end entity certificate has been revoked
+2 InvaliddistributionPointTest6EE.crt
+# 4.14.7 Valid distributionPoint Test7 - Validate Successfully
+0 ValiddistributionPointTest7EE.crt
+# 4.14.8 Invalid distributionPoint Test8 - Reject or Warn - status of end entity certificate can not be determined
+3 InvaliddistributionPointTest8EE.crt
+# 4.14.9 Invalid distributionPoint Test9 - Reject or Warn - status of end entity certificate can not be determined
+3 InvaliddistributionPointTest9EE.crt
+# 4.14.10 Valid No issuingDistributionPoint Test10 - Validate Successfully
+0 ValidNoissuingDistributionPointTest10EE.crt
+# 4.14.11 Invalid onlyContainsUserCerts CRL Test11 - Reject or Warn - status of end entity certificate can not be determined
+3 InvalidonlyContainsUserCertsTest11EE.crt
+# 4.14.12 Invalid onlyContainsCACerts CRL Test12 - Reject or Warn - status of end entity certificate can not be determined
+3 InvalidonlyContainsCACertsTest12EE.crt
+# 4.14.13 Valid onlyContainsCACerts CRL Test13 - Validate Successfully
+0 ValidonlyContainsCACertsTest13EE.crt
+# 4.14.14 Invalid onlyContainsAttributeCerts Test14 - Reject or Warn - status of end entity certificate can not be determined
+3 InvalidonlyContainsAttributeCertsTest14EE.crt
+# 4.14.15 Invalid onlySomeReasons Test15 - Reject - end entity certificate has been revoked
+2 InvalidonlySomeReasonsTest15EE.crt
+# 4.14.16 Invalid onlySomeReasons Test16 - Reject - end entity certificate is on hold
+2 InvalidonlySomeReasonsTest16EE.crt
+# 4.14.17 Invalid onlySomeReasons Test17 - Reject or Warn - status of end entity certificate can not be determined
+3 InvalidonlySomeReasonsTest17EE.crt
+# 4.14.18 Valid onlySomeReasons Test18 - Validate Successfully
+0 ValidonlySomeReasonsTest18EE.crt
+# 4.14.19 Valid onlySomeReasons Test19 - Validate Successfully
+0 ValidonlySomeReasonsTest19EE.crt
+# 4.14.20 Invalid onlySomeReasons Test20 - Reject - end entity certificate has been revoked
+2 InvalidonlySomeReasonsTest20EE.crt
+# 4.14.21 Invalid onlySomeReasons Test21 - Reject - end entity certificate has been revoked
+2 InvalidonlySomeReasonsTest21EE.crt
+# 4.14.24 Valid IDP with indirectCRL Test24 - Reject or Warn - status of end entity certificate can not be determined
+3 ValidIDPwithindirectCRLTest24EE.crt
+# 4.15.1 Invalid deltaCRLIndicator No Base Test1 - Reject or Warn - status of end entity certificate can not be determined
+3 InvaliddeltaCRLIndicatorNoBaseTest1EE.crt
+# 4.15.2 Valid delta-CRL Test2 - Validate Successfully
+0 ValiddeltaCRLTest2EE.crt
+# 4.15.3 Invalid delta-CRL Test3 - Reject - end entity certificate has been revoked
+2 InvaliddeltaCRLTest3EE.crt
+# 4.15.4 Invalid delta-CRL Test4 - Reject - end entity certificate has been revoked
+2 InvaliddeltaCRLTest4EE.crt
+# 4.15.5 Valid delta-CRL Test5 - Validate Successfully
+0 ValiddeltaCRLTest5EE.crt
+# 4.15.6 Invalid delta-CRL Test6 - Reject - end entity certificate has been revoked
+2 InvaliddeltaCRLTest6EE.crt
+# 4.15.7 Valid delta-CRL Test7 - Validate Successfully
+0 ValiddeltaCRLTest7EE.crt
+# 4.15.8 Valid delta-CRL Test8 - Validate Successfully
+0 ValiddeltaCRLTest8EE.crt
+# 4.15.9 Invalid delta-CRL Test9 - Reject - end entity certificate has been revoked
+2 InvaliddeltaCRLTest9EE.crt
+# 4.15.10 Invalid delta-CRL Test10 - Reject or Warn - status of end entity certificate can not be determined
+3 InvaliddeltaCRLTest10EE.crt
+# 4.16.1 Valid Unknown Not Critical Certificate Extension Test1 - Validate Successfully
+0 ValidUnknownNotCriticalCertificateExtensionTest1EE.crt
+# 4.16.2 Invalid Unknown Critical Certificate Extension Test2 - Reject - unrecognized critical extension
+1 InvalidUnknownCriticalCertificateExtensionTest2EE.crt
diff --git a/third_party/heimdal/lib/hx509/data/nist-result2 b/third_party/heimdal/lib/hx509/data/nist-result2
new file mode 100644
index 0000000..93a22e7
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/nist-result2
@@ -0,0 +1,31 @@
+# $Id$
+# id FAIL
+4.2.8 EITHER depeneds on if time_t is 64 bit or not
+4.3.5 FAIL
+4.4.13 EITHER depeneds on if time_t is 64 bit or not
+4.5.1 FAIL
+4.5.4 FAIL
+4.5.6 FAIL
+4.6.15 FAIL
+4.6.17 FAIL
+4.11.2 FAIL
+4.12.2 FAIL
+4.13.19 FAIL
+4.13.21 FAIL
+4.13.23 FAIL
+4.13.26 FAIL
+4.13.27 FAIL
+4.13.30 FAIL
+4.13.33 FAIL
+4.13.34 FAIL
+4.13.37 FAIL
+4.14.1 FAIL
+4.14.4 FAIL
+4.14.5 FAIL
+4.14.7 FAIL
+4.14.13 FAIL
+4.14.18 FAIL
+4.14.19 FAIL
+4.15.4 FAIL
+4.15.5 FAIL
+4.16.2 FAIL
diff --git a/third_party/heimdal/lib/hx509/data/no-proxy-test.crt b/third_party/heimdal/lib/hx509/data/no-proxy-test.crt
new file mode 100644
index 0000000..5f27bcd
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/no-proxy-test.crt
@@ -0,0 +1,30 @@
+-----BEGIN CERTIFICATE-----
+MIIFEzCCAvugAwIBAgIJAKQmPUkmhyKiMA0GCSqGSIb3DQEBCwUAMCExCzAJBgNV
+BAYTAlNFMRIwEAYDVQQDDAlUZXN0IGNlcnQwIBcNMTkwMzIyMjIyNTEzWhgPMjUx
+ODExMjEyMjI1MTNaMDQxCzAJBgNVBAYTAlNFMRIwEAYDVQQDDAlUZXN0IGNlcnQx
+ETAPBgNVBAMMCG5vLXByb3h5MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKC
+AgEA1wY5NrUAYbdIiJyOwEG5zo6892LuPxYrJ39qy0868pQMPuViT3IjP8fOockf
+IHFqM1M/rYEKBCaHm3W5d0+QET1T3pJq7eOTuG8Ep4BiMDm2mD0VeWOCeLJjfnuR
+8WPG3Fz//55NBCByMc4as5+Gw9b6z6Mh8pFMyz4zyMQI420Gss9hHoTiD9o4fhM4
+U5M+l+gvVYmvLhZ0Z8hIJAqnlRJoIKeEbcHS1qIqkN0vkdRZc5usJmxhpJi8SjTS
+pGiP53QDmGDJMHd5Fsfyv98n6T6fIkf+O2sAVnxdgOBIyYibdMH021/UzbXZHoDK
+Nx5HH9lr1R9vE5fy969yCQ10lgaNmlp68j8/5B8QPeRbe29DQ1rRBzheji1kkxbg
+8FU7GKu92GHrDhK5dasl7tH3qx4WKOAD4ENJI4vSDWo/IxkKYLLuNIMcVhmGORGl
+IvxaDVxr5wHdGgpBJwc2BxcHU6/8cuYGDewR2h/TWb6jTVmfq7lx+fefEkTDmOxI
+WbXwGtbZqqX5EzWp3VTBakONdRjJwxg3MShWJ1ZhYawzeTwZg3FOIn9W2tLkPNU7
+Ly/fZMBD6qJ5X/0gJGkx9QRlANMJnj0POaBvIyzkGz95QlyIoiAJyuzCKbX5WQdd
+jy1drnB2VdAjWyAjUP+9JsMJJKyLYOWxvemE1yAIIL9yjVMCAwEAAaM5MDcwCQYD
+VR0TBAIwADALBgNVHQ8EBAMCBeAwHQYDVR0OBBYEFN8mmgQlHmnWopRs35laOYZ9
+/02LMA0GCSqGSIb3DQEBCwUAA4ICAQB6dmCcY2XRzeZz2CQ2DdGJRyBDdHFf7W3O
+4Tk/w2ZQLFx6BwttOB94LcaVFRUHp9arkNDH6ne9ntQ1LZ3fPoRR4RXwQO8c+pIf
+ZDWPEr7Exv1F1zrjAEHx2UcP1pu4PU9PDqmGs2BarnHgKotfY8AXdJkl1g128LIQ
+WOmQFyI6Ny//4MT/5YB6OSr2zzrKz5FyGxKSG49xfPSSAf3mHAUxHzBJ1orpHIpo
+zQcrt6oRbi9G9cKVYTEVRVM2CgqMJwBUH7d9BRIab4hp7lqynFJKg3uOH90cmms1
+dY5NRmy+jmAqveEGvCw2+vmHtbj5NikwUBnRqZGW/XHLSj8niCtO2PT30xzpDiEa
+iYBGyuETV5vwFIbucdbenaBrrbvumr4lWqhjadQVwjhNcqdmhIxuGGXF/XGG5+do
+hFaYD5fguyfQDGaeFQIipPEyZcx0QcGA77g7eKYgPyBFZxGHS7P1x1GrchZIOH1q
+W59AuSwxKWGEAM2tlp2+Esp3Zj8UBy2nL9fXRyDEMerCuJUcbCLODGYDc0/s/7Cs
+G8ZNK+GXs68CgxJCbxY5uUcYQyVpRFi62jvghuPGQkxytQ/GWM+q94ncr8I2+lsO
+kTcdzYbAapst+XoPL9enQwAkw4yksJ8Rx2P2TDRAZl58+utRrdQyL0oD9cJy57LE
+cpMYhZWsyQ==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/no-proxy-test.key b/third_party/heimdal/lib/hx509/data/no-proxy-test.key
new file mode 100644
index 0000000..9f30400
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/no-proxy-test.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDXBjk2tQBht0iI
+nI7AQbnOjrz3Yu4/Fisnf2rLTzrylAw+5WJPciM/x86hyR8gcWozUz+tgQoEJoeb
+dbl3T5ARPVPekmrt45O4bwSngGIwObaYPRV5Y4J4smN+e5HxY8bcXP//nk0EIHIx
+zhqzn4bD1vrPoyHykUzLPjPIxAjjbQayz2EehOIP2jh+EzhTkz6X6C9Via8uFnRn
+yEgkCqeVEmggp4RtwdLWoiqQ3S+R1Flzm6wmbGGkmLxKNNKkaI/ndAOYYMkwd3kW
+x/K/3yfpPp8iR/47awBWfF2A4EjJiJt0wfTbX9TNtdkegMo3Hkcf2WvVH28Tl/L3
+r3IJDXSWBo2aWnryPz/kHxA95Ft7b0NDWtEHOF6OLWSTFuDwVTsYq73YYesOErl1
+qyXu0ferHhYo4APgQ0kji9INaj8jGQpgsu40gxxWGYY5EaUi/FoNXGvnAd0aCkEn
+BzYHFwdTr/xy5gYN7BHaH9NZvqNNWZ+ruXH5958SRMOY7EhZtfAa1tmqpfkTNand
+VMFqQ411GMnDGDcxKFYnVmFhrDN5PBmDcU4if1ba0uQ81TsvL99kwEPqonlf/SAk
+aTH1BGUA0wmePQ85oG8jLOQbP3lCXIiiIAnK7MIptflZB12PLV2ucHZV0CNbICNQ
+/70mwwkkrItg5bG96YTXIAggv3KNUwIDAQABAoICAQDKOoMyzZbXUC66tSuY6/fZ
+qetVa8kQskPR+QcywYh6Pv0pZklI2NsIEF5pUKOiuqgcL26TOup1rtsZPeY5rS2c
+2SX5DZHdvIzhCCDDfH5cRttRYRnCOfGqnHPwsD05XxLXi+wEuBhNCkr8RpBcYWu4
+4oavJAk4fqlP+WdwqdaGNrL3Fw2LS4TlTeKVyHPQPoq/CdMCyuRkHyBJv1cB9rdX
+/6DJHWPyajlmPcx0xGIJ8EJU9ZM56/MFf9SOohF+KQ02rKj49gYiPCs5XsIS7Mk3
+l/rInhcgQOlnbb3vCIHMcVtru0MT05RsCFx0UMJehm50KOM+5TptnhoYEvzYQLxk
+578RDQUNiQxdonmcF8QXvCBHArP20SLyfwavNsFtvfNe26i+9ti/+GaLsKHRC/ZI
+NsaIsO3wGT2E2/qoyFt+aOxrlNeT4zq+tHX01U8UzK3qhp6/RuSrQeCdmE7e/Mjb
+GVDpBYBbscfcApSCVyrpJ51Fs2VKt9QBliocrxG0Voa4xpdwC9XCI3AfTyzzG5le
+fSqhl4kB0iDboWJQgiH7hJKhFtBnrBVhPQ+bcl/G4+OZYV9HNZ98gNurCW9qO7Bf
+8jP3/A1YWYY4GI7LVqsjOZdFk3EXz1g0PR8UH4+4RRrmVAe6QD4zzQmk7ecGu5k7
+nZXuAluURI6ExdBoGGxU8QKCAQEA8GYwOHkZjNNWVDBkhjVliUHtwHof+8MoJp/L
+pHR2dwIH3UXU9RrFfzfz2sQ07Vi7aiyyebVXAA1q8ENHfeHvlWbT0SPBZOKbujVJ
+S+cNYZJvlWrvS/1ZgNld5SDSaV6R5tMIdAOyWvYm3ijgVGOmEccZVdby0MagTvJx
+fwxcNe5H86KGbZrEFieaCjz69Mg9jQh9QhfRxom1H38EcXd5O9wRSpLoXBH4c8Ha
+WBiFGaNZJrvOtCZz5YYsWVoaW9GHa4fTs9aQEirDoIR1GD+b6srD/bWX+CfM/SwG
+7bDNh2NZuH/24R+55/SUxBdhttImtiE1TmJ8XkhnocuZc03SuQKCAQEA5Pp55xqe
+cAELtdHv6iyM25e8Iv9KVMJ9y9HGH9cLdk9OwOwWroIhdIYe/yvYmHSSSiCQI+JB
+DC+2n9qxda1DHMpJWPIS4bEkKEPRsVmUyQp68OSxKcPh60m1lWk+UMhcPFWJEggz
+XKDacyjC596r4FBMk6n84lhu3HII3Zfho25IeMOgOcGlFHn5TETaqUQG1D0dParO
+rtP151TKFjyihOn8WibkcZ8uT0PXjREVCXgiha4Z/eNFeIknC007uus8bCWKUz0n
+krNTz9hiGDJHRoyGdUS9PlusW1rA8kXMvQ+8SWzHCqgwfx6zB/Nzii+glFOzzIhG
+Vydp/zFrLhJKawKCAQBAddY2PlqYhU6fsn4x8n1waYo700NiObk5ah2r0kK1tIix
+T3lD49LTQwiTP4tFnUZbuPJ+ah6S+AYVuKSh34Rjljfz21ePGqhRLNqjjKfs4twi
+v5K82Ik4YJCp0Lw63s3Wi/23Rgp8E4bmiSVl23Z7S9zCRKnFS41Ovfmq7ICJQYRv
+ksPi/d3YZvQKDMHqAwtmFsGniEWKrAAyGtfxKO0MHP1R9sRxc6wgNfm7J5ABCOjt
+1uwdKDZpdCnOJ7frqOpb7gbZMQ5eoLLmBr5zKxM+yPH2xMukEeAIfta4w3DI/d3f
++AgV43Dw/ocpcW+VGxKgQZVOmF/q1BVdr/9MiLCZAoIBAEEFZ2xawLbpdRvSW6BR
+ukX5FnGRsNfUysf/75THCfg0mRZrdB1l0n42P8MR/lV8dLYb/RJTg0kkm2VVQqM5
+6h7Yym85fmccWDoe2ALWf0t/cF3Lcwt7FkIsEiY1Vn62BosTdvLp5TveaWneH0qc
+jo4J/1THJopXtlNfBml2YZp5DJdOZcdA19GyuToRK055hL7sA8upHzvB8MgZ6bDa
+0wOPNhubg69IFmxnxWPHgAPKW3M+dx8DVIzf1Xh+HAH+HpBPMLJmYUBlL92Lgn+A
+d4DvEpdmR57XhWADq1qgu3zMZRksjHDYRb0zSH9vgFWzJJQ6GIpyABdrl8vhip/w
+jbUCggEBAMelGQB2zBBbo1F+InIPkCZH/r0Z/VrB6bQG2UY5c5Em5dTliKjE9r7U
+EGJBgLxPiHQomxG6Z/AWVzbUiv650sjfTu/W9qZ4iCEAQvGtR5FxhgtBTspMURxR
+W+QiMmkKrkkQgVBXslXgOGerj1RUe+gjaaO6qEdH5famYBXOYAG1gnq3hYa8DWMg
+OOQPoWBv2bCrtFNmuMFuHI4dTACvzbEipBTsTs0AbAQbvcSuo+KQqCcXhFfENJ/d
+7F9XN3fxSG7g4YAiIVOUjNZYz36bcpV0zpHUde+mbOvE9uXny5CFRkMHkio0Kj8h
+vMvFV9XqcWhoGHKX/S/Hmjljr7ln1Dc=
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/ocsp-req1.der b/third_party/heimdal/lib/hx509/data/ocsp-req1.der
new file mode 100644
index 0000000..e536ebb
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/ocsp-req1.der
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/ocsp-req2.der b/third_party/heimdal/lib/hx509/data/ocsp-req2.der
new file mode 100644
index 0000000..e224fa6
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/ocsp-req2.der
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/ocsp-resp1-2.der b/third_party/heimdal/lib/hx509/data/ocsp-resp1-2.der
new file mode 100644
index 0000000..98d88e4
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/ocsp-resp1-2.der
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/ocsp-resp1-3.der b/third_party/heimdal/lib/hx509/data/ocsp-resp1-3.der
new file mode 100644
index 0000000..4c65016
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/ocsp-resp1-3.der
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/ocsp-resp1-ca.der b/third_party/heimdal/lib/hx509/data/ocsp-resp1-ca.der
new file mode 100644
index 0000000..228918c
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/ocsp-resp1-ca.der
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/ocsp-resp1-keyhash.der b/third_party/heimdal/lib/hx509/data/ocsp-resp1-keyhash.der
new file mode 100644
index 0000000..250a1f1
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/ocsp-resp1-keyhash.der
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/ocsp-resp1-ocsp-no-cert.der b/third_party/heimdal/lib/hx509/data/ocsp-resp1-ocsp-no-cert.der
new file mode 100644
index 0000000..6ebbd84
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/ocsp-resp1-ocsp-no-cert.der
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/ocsp-resp1-ocsp.der b/third_party/heimdal/lib/hx509/data/ocsp-resp1-ocsp.der
new file mode 100644
index 0000000..c97654a
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/ocsp-resp1-ocsp.der
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/ocsp-resp1.der b/third_party/heimdal/lib/hx509/data/ocsp-resp1.der
new file mode 100644
index 0000000..8546eba
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/ocsp-resp1.der
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/ocsp-resp2.der b/third_party/heimdal/lib/hx509/data/ocsp-resp2.der
new file mode 100644
index 0000000..d731f38
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/ocsp-resp2.der
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/ocsp-responder.crt b/third_party/heimdal/lib/hx509/data/ocsp-responder.crt
new file mode 100644
index 0000000..753ca56
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/ocsp-responder.crt
@@ -0,0 +1,119 @@
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 1 (0x1)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: CN=hx509 Test Root CA, C=SE
+ Validity
+ Not Before: Mar 22 22:25:01 2019 GMT
+ Not After : Nov 21 22:25:01 2518 GMT
+ Subject: C=SE, CN=OCSP responder
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:b1:21:1d:c9:2b:44:9e:62:fe:13:94:ea:a1:e1:
+ cd:17:0e:bb:4d:1c:62:27:ee:d3:f7:61:c8:26:c1:
+ 0f:45:fc:10:d8:39:c3:da:86:a0:00:30:d7:ad:86:
+ ff:c6:36:6c:f5:e2:26:8c:f6:76:1b:d0:09:b6:a5:
+ f8:cb:d5:88:fc:ca:ca:28:49:ed:64:2b:f3:88:4e:
+ 8e:ec:7c:63:b8:75:6a:cc:73:b6:66:6c:c3:7c:e4:
+ d7:50:95:88:12:84:e7:5c:50:87:db:4c:bf:91:98:
+ b1:3a:44:57:0b:1a:7a:f1:93:e3:4c:69:8b:9f:d7:
+ b9:20:8d:0e:cb:ff:de:38:6f:6a:91:55:1a:6f:a6:
+ 82:1d:05:f6:fc:46:8c:83:8b:ab:6e:3f:6a:6f:c5:
+ 0c:cc:ff:3c:78:74:d4:f8:56:be:59:60:d5:3f:4d:
+ 3e:e4:e1:4b:2d:c5:2a:d1:6a:7a:21:b9:6e:61:10:
+ 03:79:88:5b:74:f4:29:0d:56:d3:6b:d5:7d:8c:59:
+ 5d:4e:89:0d:a3:a6:8b:43:28:e8:e2:f1:bb:d5:eb:
+ 65:9b:c2:d6:62:aa:df:66:d5:92:dd:84:6c:29:28:
+ 1a:e8:29:b3:09:d1:45:14:44:cb:30:03:73:3a:94:
+ a3:a3:24:89:15:fb:ca:e0:a6:62:35:48:f8:92:50:
+ 3a:ff:17:d8:4a:1e:a0:9c:d9:68:cc:21:e1:c9:36:
+ d1:47:bc:f1:56:3e:87:18:10:0d:f5:56:9a:c9:79:
+ 16:c0:08:a0:59:65:b2:00:dd:9a:e9:97:e7:8f:85:
+ ee:cd:0d:20:5e:2d:58:ff:8e:e3:ce:4f:36:65:c3:
+ f1:88:39:dd:34:29:db:8c:ed:6e:c8:7b:30:ad:49:
+ 58:e6:f9:5b:85:46:0a:04:0f:9e:ea:ca:a8:2a:35:
+ 0d:66:f3:48:b6:e3:c7:e0:e8:a3:ed:6c:f3:e4:cd:
+ 1d:45:f3:e2:2c:6c:5b:91:b8:26:dd:49:d4:78:d3:
+ 4e:57:3a:b5:af:cd:3a:05:d5:89:63:f5:bc:73:1f:
+ 26:cc:2c:4b:2d:81:b3:5d:49:28:04:46:f8:24:5a:
+ 68:1d:06:1b:2d:be:56:f9:b3:f4:d1:50:2f:95:9b:
+ 9f:45:c7:62:35:bc:46:a9:df:c6:45:21:e9:1c:7d:
+ a8:2e:b1:87:91:0b:7c:fb:97:52:31:f9:41:73:ba:
+ 83:22:4a:80:f9:ff:f1:95:74:79:f7:20:95:f0:17:
+ 20:7d:ac:55:e8:b0:c6:b2:a6:56:c6:c0:cf:3d:78:
+ d5:9e:37:41:b4:78:aa:30:f0:2d:59:7c:6a:c8:68:
+ cc:91:09:13:f8:9f:04:e3:a9:86:c2:74:ba:f6:32:
+ 44:0d:bd
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints:
+ CA:FALSE
+ X509v3 Key Usage:
+ Digital Signature, Non Repudiation, Key Encipherment
+ X509v3 Extended Key Usage:
+ OCSP No Check, OCSP Signing
+ X509v3 Subject Key Identifier:
+ D0:3C:E8:05:07:BB:9A:96:36:88:44:AA:9A:4F:62:9E:9F:33:5B:03
+ Signature Algorithm: sha1WithRSAEncryption
+ c0:72:d2:af:26:74:de:f8:7c:96:bf:ab:d2:ed:95:d9:bb:0b:
+ 07:31:8a:4b:21:f0:b5:7e:ab:b4:50:b0:af:bf:96:64:ce:38:
+ 99:3d:f3:26:02:4d:5a:da:71:ad:6d:a6:f7:fc:5e:46:16:3d:
+ 9e:cf:95:a3:5d:0c:4a:64:a1:84:88:b0:31:0e:eb:54:cb:99:
+ 42:45:09:92:ea:b7:74:f5:fb:ff:c6:91:31:27:bd:54:55:9f:
+ 6c:bb:e2:45:4a:33:ed:00:a5:4e:e2:7b:2c:98:f1:3b:bc:f2:
+ 87:33:e5:22:d8:fc:a8:4c:90:e2:df:ce:48:c8:3c:56:43:6c:
+ ac:f1:f6:e0:75:c2:a7:f9:33:87:4e:75:a6:22:17:78:32:88:
+ aa:f9:2a:40:4c:e0:25:6c:4c:0c:cb:6f:1a:7b:13:0d:35:a6:
+ 23:86:42:75:3c:c1:69:c1:c5:79:77:51:4b:19:14:e7:4b:f9:
+ df:0b:30:aa:c4:97:84:6e:57:7b:00:b3:a5:31:c6:9f:17:f1:
+ b0:4c:81:f7:e6:df:e8:c0:d2:91:03:c2:e3:dd:94:c4:f0:ee:
+ 1c:73:1c:33:ae:91:60:fe:cf:48:08:0a:95:c1:95:28:af:31:
+ 23:a6:2a:1c:d1:6c:7f:68:e8:a9:a4:27:8f:6f:29:33:a9:48:
+ 0c:03:8f:fa:b5:ef:2a:9a:ce:ed:ba:74:39:88:ef:3b:d9:93:
+ 77:34:30:d1:a3:5c:9d:f1:3c:30:19:c2:ca:2e:41:5b:23:bb:
+ 6a:67:35:e3:e2:c6:6e:a0:3e:76:50:db:6b:ee:02:98:81:bf:
+ 75:ac:3a:78:4f:f4:fb:d1:7a:1f:85:1a:24:cd:b8:06:7e:95:
+ 28:85:2a:c6:41:23:35:08:31:59:ce:ad:a3:23:1a:7a:11:26:
+ d9:45:57:bf:ea:e0:72:3a:f8:48:e0:c1:5c:b3:20:93:b5:1a:
+ 93:75:ef:f3:19:9d:ed:5d:9f:81:73:21:02:96:fa:ee:c9:4c:
+ c7:95:1b:aa:65:b9:69:15:3c:ef:b3:f6:e1:f5:89:78:05:50:
+ d3:54:c4:c9:40:e5:5f:3e:bd:36:d2:0e:27:99:5e:83:e5:4b:
+ bf:72:84:13:64:8d:d9:db:69:8b:04:37:e8:db:22:46:29:84:
+ 08:83:40:34:d8:e0:bf:cc:5c:7c:b2:bd:c5:38:7d:59:e6:9d:
+ 8a:78:87:08:13:6f:a5:7d:2f:88:80:ce:e5:86:38:6f:53:b8:
+ 99:ba:f5:21:9e:8f:5f:aa:3a:07:73:9b:02:f1:97:1f:8b:52:
+ 53:5e:24:af:d7:b9:a4:3f:4e:64:c8:62:26:b3:c0:44:dd:bb:
+ 29:8c:b5:66:05:5d:fd:f7
+-----BEGIN CERTIFICATE-----
+MIIFJjCCAw6gAwIBAgIBATANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw
+OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMCAXDTE5MDMyMjIyMjUwMVoYDzI1
+MTgxMTIxMjIyNTAxWjAmMQswCQYDVQQGEwJTRTEXMBUGA1UEAwwOT0NTUCByZXNw
+b25kZXIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCxIR3JK0SeYv4T
+lOqh4c0XDrtNHGIn7tP3YcgmwQ9F/BDYOcPahqAAMNethv/GNmz14iaM9nYb0Am2
+pfjL1Yj8ysooSe1kK/OITo7sfGO4dWrMc7ZmbMN85NdQlYgShOdcUIfbTL+RmLE6
+RFcLGnrxk+NMaYuf17kgjQ7L/944b2qRVRpvpoIdBfb8RoyDi6tuP2pvxQzM/zx4
+dNT4Vr5ZYNU/TT7k4UstxSrRanohuW5hEAN5iFt09CkNVtNr1X2MWV1OiQ2jpotD
+KOji8bvV62WbwtZiqt9m1ZLdhGwpKBroKbMJ0UUURMswA3M6lKOjJIkV+8rgpmI1
+SPiSUDr/F9hKHqCc2WjMIeHJNtFHvPFWPocYEA31VprJeRbACKBZZbIA3Zrpl+eP
+he7NDSBeLVj/juPOTzZlw/GIOd00KduM7W7IezCtSVjm+VuFRgoED57qyqgqNQ1m
+80i248fg6KPtbPPkzR1F8+IsbFuRuCbdSdR4005XOrWvzToF1Ylj9bxzHybMLEst
+gbNdSSgERvgkWmgdBhstvlb5s/TRUC+Vm59Fx2I1vEap38ZFIekcfagusYeRC3z7
+l1Ix+UFzuoMiSoD5//GVdHn3IJXwFyB9rFXosMayplbGwM89eNWeN0G0eKow8C1Z
+fGrIaMyRCRP4nwTjqYbCdLr2MkQNvQIDAQABo1kwVzAJBgNVHRMEAjAAMAsGA1Ud
+DwQEAwIF4DAeBgNVHSUEFzAVBgkrBgEFBQcwAQUGCCsGAQUFBwMJMB0GA1UdDgQW
+BBTQPOgFB7ualjaIRKqaT2KenzNbAzANBgkqhkiG9w0BAQUFAAOCAgEAwHLSryZ0
+3vh8lr+r0u2V2bsLBzGKSyHwtX6rtFCwr7+WZM44mT3zJgJNWtpxrW2m9/xeRhY9
+ns+Vo10MSmShhIiwMQ7rVMuZQkUJkuq3dPX7/8aRMSe9VFWfbLviRUoz7QClTuJ7
+LJjxO7zyhzPlItj8qEyQ4t/OSMg8VkNsrPH24HXCp/kzh051piIXeDKIqvkqQEzg
+JWxMDMtvGnsTDTWmI4ZCdTzBacHFeXdRSxkU50v53wswqsSXhG5XewCzpTHGnxfx
+sEyB9+bf6MDSkQPC492UxPDuHHMcM66RYP7PSAgKlcGVKK8xI6YqHNFsf2joqaQn
+j28pM6lIDAOP+rXvKprO7bp0OYjvO9mTdzQw0aNcnfE8MBnCyi5BWyO7amc14+LG
+bqA+dlDba+4CmIG/daw6eE/0+9F6H4UaJM24Bn6VKIUqxkEjNQgxWc6toyMaehEm
+2UVXv+rgcjr4SODBXLMgk7Uak3Xv8xmd7V2fgXMhApb67slMx5UbqmW5aRU877P2
+4fWJeAVQ01TEyUDlXz69NtIOJ5leg+VLv3KEE2SN2dtpiwQ36NsiRimECINANNjg
+v8xcfLK9xTh9WeadiniHCBNvpX0viIDO5YY4b1O4mbr1IZ6PX6o6B3ObAvGXH4tS
+U14kr9e5pD9OZMhiJrPARN27KYy1ZgVd/fc=
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/ocsp-responder.key b/third_party/heimdal/lib/hx509/data/ocsp-responder.key
new file mode 100644
index 0000000..140aaf8
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/ocsp-responder.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCxIR3JK0SeYv4T
+lOqh4c0XDrtNHGIn7tP3YcgmwQ9F/BDYOcPahqAAMNethv/GNmz14iaM9nYb0Am2
+pfjL1Yj8ysooSe1kK/OITo7sfGO4dWrMc7ZmbMN85NdQlYgShOdcUIfbTL+RmLE6
+RFcLGnrxk+NMaYuf17kgjQ7L/944b2qRVRpvpoIdBfb8RoyDi6tuP2pvxQzM/zx4
+dNT4Vr5ZYNU/TT7k4UstxSrRanohuW5hEAN5iFt09CkNVtNr1X2MWV1OiQ2jpotD
+KOji8bvV62WbwtZiqt9m1ZLdhGwpKBroKbMJ0UUURMswA3M6lKOjJIkV+8rgpmI1
+SPiSUDr/F9hKHqCc2WjMIeHJNtFHvPFWPocYEA31VprJeRbACKBZZbIA3Zrpl+eP
+he7NDSBeLVj/juPOTzZlw/GIOd00KduM7W7IezCtSVjm+VuFRgoED57qyqgqNQ1m
+80i248fg6KPtbPPkzR1F8+IsbFuRuCbdSdR4005XOrWvzToF1Ylj9bxzHybMLEst
+gbNdSSgERvgkWmgdBhstvlb5s/TRUC+Vm59Fx2I1vEap38ZFIekcfagusYeRC3z7
+l1Ix+UFzuoMiSoD5//GVdHn3IJXwFyB9rFXosMayplbGwM89eNWeN0G0eKow8C1Z
+fGrIaMyRCRP4nwTjqYbCdLr2MkQNvQIDAQABAoICAF7zLJ9Y5ViuIhrnGfubKjBx
+AjBsxaU4XkHfFcbIeOKAI5t1I6rxvbU8eXEYy+U56aDJEPdBasCv/XT+dWb22Y8B
+Oers7idjdBGeYvkcGOyZbJ2aba1sIkLB/TXCYoXi3o7a0GjbNFnc6ywb1Dksgbkc
+GJ0uet09a4yqcMMkLsA74Xl0kE5HiLn8J5DGVK5zYXsg3XJ6w8jkDUtY/Yz+Gt2Y
+jdd4Ff3lU0J+zdwiYsPPPf8j8WjlknkYJSV0ZLMKZ1mj0eO2jiwqq75doLF++bzL
+idU8VWXgyQ678BV01fIeAIZxS/s4Rfp+ghkD0HIXmbxralzxc6iHKF/99Nmhzm1o
+/1PxIqTkso1G1MvizXgr54Uxdv7N01nuL+nDp4q1kBieCqAfkDbbbk9NQb/BUntx
+ZZH2VJxFk8iit8O9BLPM5xiwsdx0QNeYEYQ+fXl75QCLN2zEMaPeOXpV6zWy2NR4
+P+eUEmOC+8Uj44/k21R/Zf46SAEB9YZPmAmq7rW9ACj17sj6e2F1hsVStMy3aG3h
+59GG+sxMSIHwMJ/xB9r+xfaoX4iUapogy1N8pKyYL2CT6c2VB+wBW0gJsuxEGIt3
+x5LugOkCiArTOxTO54tTNeO/5+G+PkYrZwQazCuj9PQPTymHd4ieh61t/8CpasxT
+faIJQt+GxtrBWI8Pc2h1AoIBAQDn22N6+XkouiQcg+sunLFwT5jxQsUZIOVAjx8r
+WFoCW6onzltldxrpP+dx0nOaeBbwHTCRDYrHJhA3bmpaXjBYI8MunfYzHTxmCS1p
+0/cGCMhcZc4dokOh60c1C9/UTG5hAEUAB9kP5C3H1OoL63OM24XQl7hwwX7WFOdL
+VzzADDssLlfhsWRuXa9H5uD2ziqmWE6EZE9Jx5UlolgGpAGcS4YoJi5PaMnYdIJF
+Cpf4gqhtuuUWD7brF9QCKF+e2lLqt4FHSrInqUIYD8HL4xToDPdKfxzUrI3S9dDh
+g7yWWIRKR1W2IFSxBCwedLHl7VGpmgJ+RVovsTbnU+DLplGnAoIBAQDDktp+6FJP
+WorkWUOUWLz4Ao3R3Cd/s7zZlhyNd2fjonH4uBry+X0Vunz2525YtOEVXcVM8Mqa
+KDRyluAwp9pHYc3mhqGafWjoyH1+aDbkALSRcrGw1MkodqgSqxSt1RjgjXwbJb9Y
+wUQSTxd7eJym2WtWAp0WQjH20ygMLu4Lt79HK6M+L0hi9lcxbNNxlQEC5FKgplLn
+urpACHtzrUiIBfpu0LJL0E3dUytQUSVXE02R8j8STRO4lu3n90lZktEl0XuHEHqr
+JXn+p1EhgxpMaYbKr+/v1dFc1RFnaDJO1b2IIaX4psKPPjF408EGqzwXeUen4RLJ
+oaaDSTftN+n7AoIBACBe8w6yUgYrpusMSAOkAOoLUvEsP1R40UkoMlPc7AQ0RBd2
+qjAKZwl10JyFo3pHlfxENwmpeFzBpbX3hoXDbMCBjbiueTc9t7cPRPXnkC+Zfk/Y
+LuTYSNUMgk6Xr9J2MVr9rKSKc/XSB8pEocC0SNe7tn0fEbM8cLb3CCvurB6sFn7e
+oYpzN/BoyBYj1/jdY/sBjUTStHc6lEpC1kNnFop5yOtGGWUg3j2IVr/I8NrTcyyO
+0Xk5DHLaStFaTa9iD/2RTU1k0mbTLNUrLgWHWN3lIYmXIbFXvh1cEKPLvsLG7QFp
+4D+jV++3A2nlJQlTDvm89OgoSqUp+t5lSZdlSzUCggEBAJ+BA+aA/7Bsfd6i1rUE
+coorOxMvZJ+ILbuf7AWMnxROhnl9Xa1QwS2ZfRW5xoteajyMz79imzqDE9NpLctA
++otBPzaGEwL2yTshWQhhYnMuCBaf3kAEK1NvAsDG+wSTScjKW6+gZ6Cxbx0nmFVB
+FzIVHK93Tjq7HhjaOk1FcSvpXn1jH641zem4U4Ch6wk1py9+m80eGXuZFRHoWRcM
++pzFk2wRlXizmO2rSSYmKDgOLDOdyMbaSf1ASyPm0NHXJfCcGw0a6ZDv7cE9ILQe
+QrKTVjW0rBGE5025EIqvtmgJdpyyJLTY/NDqvlp3CXSw7z+N0F0g+bustStZ6dz0
+v0UCggEAXsErHCyXn4LGb77CKdqLPC+VzXUtpY7ydBBOZ/4jemRdGn1YjgDPBrOl
+tESL90Ir1F36zAQOenEOn2VIfCX0DWFLKA5FE2dRM/7X79yTOFwZ2n9Ubz0ulNVH
+zHB2eSHsUhhVszRgqXFwWWwDnkqB7V8HkEXGodl77qf79KL6BQdBj9HbX/4Es1KS
+C4OedUoFIgkvDppiG3mS9JftlHpKM60ckDpkTREdbsRxy2UEjXSdaW/ycJne+xYs
+KKwq1IWDGJYoAfcH6f/9ipG/tC7e5ckUXIQO2bQdtVwqpL0b2VneiWdK4F8EmdiZ
+SSGDNVUC8knNaz9M5HYwvqUl1if8yg==
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/openssl.1.0.cnf b/third_party/heimdal/lib/hx509/data/openssl.1.0.cnf
new file mode 100644
index 0000000..b014656
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/openssl.1.0.cnf
@@ -0,0 +1,190 @@
+oid_section = new_oids
+
+[new_oids]
+pkkdcekuoid = 1.3.6.1.5.2.3.5
+
+[ca]
+
+default_ca = user
+
+[usr]
+database = index.txt
+serial = serial
+x509_extensions = usr_cert
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+[ocsp]
+database = index.txt
+serial = serial
+x509_extensions = ocsp_cert
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+[usr_ke]
+database = index.txt
+serial = serial
+x509_extensions = usr_cert_ke
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+[usr_ds]
+database = index.txt
+serial = serial
+x509_extensions = usr_cert_ds
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+[pkinit_client]
+database = index.txt
+serial = serial
+x509_extensions = pkinit_client_cert
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+[pkinit_kdc]
+database = index.txt
+serial = serial
+x509_extensions = pkinit_kdc_cert
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+[https]
+database = index.txt
+serial = serial
+x509_extensions = https_cert
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+[subca]
+database = index.txt
+serial = serial
+x509_extensions = v3_ca
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+
+[req]
+distinguished_name = req_distinguished_name
+x509_extensions = v3_ca # The extensions to add to the self signed cert
+
+string_mask = utf8only
+
+[v3_ca]
+
+subjectKeyIdentifier=hash
+authorityKeyIdentifier=keyid:always,issuer:always
+basicConstraints = CA:true
+keyUsage = cRLSign, keyCertSign, keyEncipherment, nonRepudiation, digitalSignature
+
+[usr_cert]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+subjectKeyIdentifier = hash
+
+[usr_cert_ke]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, keyEncipherment
+subjectKeyIdentifier = hash
+
+[proxy_cert]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+subjectKeyIdentifier = hash
+proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:0,policy:text:foo
+
+[pkinitc_principals]
+princ1 = GeneralString:bar
+
+[pkinitc_principal_seq]
+name_type = EXP:0,INTEGER:1
+name_string = EXP:1,SEQUENCE:pkinitc_principals
+
+[pkinitc_princ_name]
+realm = EXP:0,GeneralString:TEST.H5L.SE
+principal_name = EXP:1,SEQUENCE:pkinitc_principal_seq
+
+[pkinit_client_cert]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+subjectKeyIdentifier = hash
+subjectAltName=otherName:1.3.6.1.5.2.2;SEQUENCE:pkinitc_princ_name
+
+[https_cert]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+#extendedKeyUsage = https-server XXX
+subjectKeyIdentifier = hash
+
+[pkinit_kdc_cert]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+extendedKeyUsage = pkkdcekuoid
+subjectKeyIdentifier = hash
+subjectAltName=otherName:1.3.6.1.5.2.2;SEQUENCE:pkinitkdc_princ_name
+
+[pkinitkdc_princ_name]
+realm = EXP:0,GeneralString:TEST.H5L.SE
+principal_name = EXP:1,SEQUENCE:pkinitkdc_principal_seq
+
+[pkinitkdc_principal_seq]
+name_type = EXP:0,INTEGER:1
+name_string = EXP:1,SEQUENCE:pkinitkdc_principals
+
+[pkinitkdc_principals]
+princ1 = GeneralString:krbtgt
+princ2 = GeneralString:TEST.H5L.SE
+
+[proxy10_cert]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+subjectKeyIdentifier = hash
+proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:10,policy:text:foo
+
+[usr_cert_ds]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature
+subjectKeyIdentifier = hash
+
+[ocsp_cert]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+# ocsp-nocheck and kp-OCSPSigning
+extendedKeyUsage = 1.3.6.1.5.5.7.48.1.5, 1.3.6.1.5.5.7.3.9
+subjectKeyIdentifier = hash
+
+[req_distinguished_name]
+countryName = Country Name (2 letter code)
+countryName_default = SE
+countryName_min = 2
+countryName_max = 2
+
+organizationalName = Organizational Unit Name (eg, section)
+
+commonName = Common Name (eg, YOUR name)
+commonName_max = 64
+
+#[req_attributes]
+#challengePassword = A challenge password
+#challengePassword_min = 4
+#challengePassword_max = 20
+
+[policy_match]
+countryName = match
+commonName = supplied
diff --git a/third_party/heimdal/lib/hx509/data/openssl.1.1.cnf b/third_party/heimdal/lib/hx509/data/openssl.1.1.cnf
new file mode 100644
index 0000000..110073f
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/openssl.1.1.cnf
@@ -0,0 +1,185 @@
+[ca]
+
+default_ca = user
+
+[usr]
+database = index.txt
+serial = serial
+x509_extensions = usr_cert
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+[ocsp]
+database = index.txt
+serial = serial
+x509_extensions = ocsp_cert
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+[usr_ke]
+database = index.txt
+serial = serial
+x509_extensions = usr_cert_ke
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+[usr_ds]
+database = index.txt
+serial = serial
+x509_extensions = usr_cert_ds
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+[pkinit_client]
+database = index.txt
+serial = serial
+x509_extensions = pkinit_client_cert
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+[pkinit_kdc]
+database = index.txt
+serial = serial
+x509_extensions = pkinit_kdc_cert
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+[https]
+database = index.txt
+serial = serial
+x509_extensions = https_cert
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+[subca]
+database = index.txt
+serial = serial
+x509_extensions = v3_ca
+default_md=sha1
+policy = policy_match
+email_in_dn = no
+certs = .
+
+
+[req]
+distinguished_name = req_distinguished_name
+x509_extensions = v3_ca # The extensions to add to the self signed cert
+
+string_mask = utf8only
+
+[v3_ca]
+
+subjectKeyIdentifier=hash
+authorityKeyIdentifier=keyid:always,issuer:always
+basicConstraints = CA:true
+keyUsage = cRLSign, keyCertSign, keyEncipherment, nonRepudiation, digitalSignature
+
+[usr_cert]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+subjectKeyIdentifier = hash
+
+[usr_cert_ke]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, keyEncipherment
+subjectKeyIdentifier = hash
+
+[proxy_cert]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+subjectKeyIdentifier = hash
+proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:0,policy:text:foo
+
+[pkinitc_principals]
+princ1 = GeneralString:bar
+
+[pkinitc_principal_seq]
+name_type = EXP:0,INTEGER:1
+name_string = EXP:1,SEQUENCE:pkinitc_principals
+
+[pkinitc_princ_name]
+realm = EXP:0,GeneralString:TEST.H5L.SE
+principal_name = EXP:1,SEQUENCE:pkinitc_principal_seq
+
+[pkinit_client_cert]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+subjectKeyIdentifier = hash
+subjectAltName=otherName:1.3.6.1.5.2.2;SEQUENCE:pkinitc_princ_name
+
+[https_cert]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+#extendedKeyUsage = https-server XXX
+subjectKeyIdentifier = hash
+
+[pkinit_kdc_cert]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+extendedKeyUsage = 1.3.6.1.5.2.3.5
+subjectKeyIdentifier = hash
+subjectAltName=otherName:1.3.6.1.5.2.2;SEQUENCE:pkinitkdc_princ_name
+
+[pkinitkdc_princ_name]
+realm = EXP:0,GeneralString:TEST.H5L.SE
+principal_name = EXP:1,SEQUENCE:pkinitkdc_principal_seq
+
+[pkinitkdc_principal_seq]
+name_type = EXP:0,INTEGER:1
+name_string = EXP:1,SEQUENCE:pkinitkdc_principals
+
+[pkinitkdc_principals]
+princ1 = GeneralString:krbtgt
+princ2 = GeneralString:TEST.H5L.SE
+
+[proxy10_cert]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+subjectKeyIdentifier = hash
+proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:10,policy:text:foo
+
+[usr_cert_ds]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature
+subjectKeyIdentifier = hash
+
+[ocsp_cert]
+basicConstraints=CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+# ocsp-nocheck and kp-OCSPSigning
+extendedKeyUsage = 1.3.6.1.5.5.7.48.1.5, 1.3.6.1.5.5.7.3.9
+subjectKeyIdentifier = hash
+
+[req_distinguished_name]
+countryName = Country Name (2 letter code)
+countryName_default = SE
+countryName_min = 2
+countryName_max = 2
+
+organizationalName = Organizational Unit Name (eg, section)
+
+commonName = Common Name (eg, YOUR name)
+commonName_max = 64
+
+#[req_attributes]
+#challengePassword = A challenge password
+#challengePassword_min = 4
+#challengePassword_max = 20
+
+[policy_match]
+countryName = match
+commonName = supplied
diff --git a/third_party/heimdal/lib/hx509/data/pkinit-ec.crt b/third_party/heimdal/lib/hx509/data/pkinit-ec.crt
new file mode 100644
index 0000000..54435d3
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/pkinit-ec.crt
@@ -0,0 +1,81 @@
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 7 (0x7)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: CN=hx509 Test Root CA, C=SE
+ Validity
+ Not Before: Mar 22 22:25:06 2019 GMT
+ Not After : Nov 21 22:25:06 2518 GMT
+ Subject: C=SE, CN=pkinit-ec
+ Subject Public Key Info:
+ Public Key Algorithm: id-ecPublicKey
+ Public-Key: (256 bit)
+ pub:
+ 04:c0:2b:8e:f3:0c:c3:1b:88:94:eb:4e:6a:12:f2:
+ fb:63:99:77:a2:13:7a:16:ce:48:dc:48:9a:83:91:
+ 5e:a9:b8:ab:17:77:94:ae:55:09:8d:69:4a:a4:a8:
+ 6b:77:12:01:fb:3c:6f:cd:b1:e3:02:be:63:b1:43:
+ 8d:8f:df:8c:75
+ ASN1 OID: prime256v1
+ NIST CURVE: P-256
+ X509v3 extensions:
+ X509v3 Basic Constraints:
+ CA:FALSE
+ X509v3 Key Usage:
+ Digital Signature, Non Repudiation, Key Encipherment
+ X509v3 Subject Key Identifier:
+ 77:9B:74:4B:75:90:50:CE:20:C3:00:9B:A5:23:F7:69:A8:C7:CC:34
+ X509v3 Subject Alternative Name:
+ othername:<unsupported>
+ Signature Algorithm: sha1WithRSAEncryption
+ 70:02:b8:13:0f:d9:2b:7a:e9:42:5c:82:6a:9d:ea:f8:51:dc:
+ a9:2e:67:ec:c3:cb:67:48:fe:6a:bd:58:86:67:c2:1f:d4:a0:
+ dc:7d:17:41:93:8d:e0:67:60:01:60:cc:34:1f:0e:b0:fc:9b:
+ 5f:f6:cf:91:2b:a3:ec:28:5b:80:ff:31:21:14:5b:3c:a2:5c:
+ 6b:3b:32:94:de:ab:03:d9:41:70:c1:4f:4e:49:4d:63:8f:9a:
+ 8b:be:14:87:b0:df:bc:64:83:e1:99:ce:e6:77:12:5a:43:e3:
+ 3b:d7:e9:10:5e:68:36:38:de:88:c2:78:af:97:a3:a2:4e:bf:
+ a9:2d:e1:98:f4:9a:35:ec:b4:2a:70:18:09:99:ff:80:fb:73:
+ 49:75:47:54:31:7a:e1:43:28:4b:53:71:81:92:4c:42:db:9b:
+ 52:38:ad:90:47:db:4e:da:75:6f:37:14:ce:56:6e:06:d0:40:
+ 8e:df:f1:71:23:98:ee:b4:43:b7:77:3a:1c:a5:a3:6f:3e:d3:
+ 5f:86:0b:6d:d4:b8:4a:2e:8a:e0:d7:d2:75:5f:ca:bc:9c:e2:
+ d8:b9:04:bf:ec:8a:1e:78:28:f5:13:73:9c:dd:2c:10:73:55:
+ cf:40:96:8d:8a:b4:1c:79:bd:aa:01:de:b2:de:c4:30:04:11:
+ af:d5:fb:cb:28:44:25:02:ab:b3:68:22:02:1b:99:b1:96:eb:
+ f7:f3:ad:6e:32:76:67:be:bb:78:bc:46:9a:1c:b3:8e:66:39:
+ eb:cb:d8:76:c8:06:e5:79:1e:f0:fa:54:3f:a1:ea:ff:60:e8:
+ fb:55:d9:1c:47:3a:e7:67:df:c8:69:1d:d1:9a:56:96:2b:01:
+ 79:ad:22:f2:7a:3b:e6:be:32:84:9a:e3:50:db:89:69:c1:3e:
+ 19:09:d5:b3:3c:2c:08:90:8b:93:aa:39:ae:48:90:ec:cf:79:
+ 3d:15:91:86:3e:38:0e:0a:99:b1:d9:78:14:59:17:44:c0:76:
+ 70:a0:7a:92:64:2a:60:04:aa:ce:6b:b1:d5:c1:3b:e8:1b:58:
+ 6f:7d:dd:dc:90:49:55:e1:37:5a:7b:75:89:da:08:c1:a5:33:
+ c9:f9:0d:4a:1d:08:e0:a8:be:3f:0e:a2:e0:10:71:92:50:f8:
+ 75:33:98:7c:be:c9:2f:c8:7c:b2:19:94:14:59:0b:1c:ca:bc:
+ 34:ff:03:a4:3c:f0:bd:ac:c8:f6:63:8f:59:d3:eb:65:e9:96:
+ 9b:21:a9:94:a7:7d:fe:dd:62:cd:77:62:6a:58:38:de:63:4c:
+ 0c:c3:ea:09:4f:6a:80:76:07:59:ba:15:d2:b4:c1:46:1e:11:
+ 50:5b:be:8d:8e:21:4e:78
+-----BEGIN CERTIFICATE-----
+MIIDcDCCAVigAwIBAgIBBzANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw
+OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMCAXDTE5MDMyMjIyMjUwNloYDzI1
+MTgxMTIxMjIyNTA2WjAhMQswCQYDVQQGEwJTRTESMBAGA1UEAwwJcGtpbml0LWVj
+MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEwCuO8wzDG4iU605qEvL7Y5l3ohN6
+Fs5I3Eiag5FeqbirF3eUrlUJjWlKpKhrdxIB+zxvzbHjAr5jsUONj9+MdaNzMHEw
+CQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwHQYDVR0OBBYEFHebdEt1kFDOIMMAm6Uj
+92mox8w0MDgGA1UdEQQxMC+gLQYGKwYBBQICoCMwIaANGwtURVNULkg1TC5TRaEQ
+MA6gAwIBAaEHMAUbA2JhcjANBgkqhkiG9w0BAQUFAAOCAgEAcAK4Ew/ZK3rpQlyC
+ap3q+FHcqS5n7MPLZ0j+ar1YhmfCH9Sg3H0XQZON4GdgAWDMNB8OsPybX/bPkSuj
+7ChbgP8xIRRbPKJcazsylN6rA9lBcMFPTklNY4+ai74Uh7DfvGSD4ZnO5ncSWkPj
+O9fpEF5oNjjeiMJ4r5ejok6/qS3hmPSaNey0KnAYCZn/gPtzSXVHVDF64UMoS1Nx
+gZJMQtubUjitkEfbTtp1bzcUzlZuBtBAjt/xcSOY7rRDt3c6HKWjbz7TX4YLbdS4
+Si6K4NfSdV/KvJzi2LkEv+yKHngo9RNznN0sEHNVz0CWjYq0HHm9qgHest7EMAQR
+r9X7yyhEJQKrs2giAhuZsZbr9/OtbjJ2Z767eLxGmhyzjmY568vYdsgG5Xke8PpU
+P6Hq/2Do+1XZHEc652ffyGkd0ZpWlisBea0i8no75r4yhJrjUNuJacE+GQnVszws
+CJCLk6o5rkiQ7M95PRWRhj44DgqZsdl4FFkXRMB2cKB6kmQqYASqzmux1cE76BtY
+b33d3JBJVeE3Wnt1idoIwaUzyfkNSh0I4Ki+Pw6i4BBxklD4dTOYfL7JL8h8shmU
+FFkLHMq8NP8DpDzwvazI9mOPWdPrZemWmyGplKd9/t1izXdialg43mNMDMPqCU9q
+gHYHWboV0rTBRh4RUFu+jY4hTng=
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/pkinit-ec.key b/third_party/heimdal/lib/hx509/data/pkinit-ec.key
new file mode 100644
index 0000000..0ac3fe4
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/pkinit-ec.key
@@ -0,0 +1,5 @@
+-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg38AlgS7f0d6rvR6u
+mLJVGl/UF04RYiIeWsVJYUNS7RKhRANCAATAK47zDMMbiJTrTmoS8vtjmXeiE3oW
+zkjcSJqDkV6puKsXd5SuVQmNaUqkqGt3EgH7PG/NseMCvmOxQ42P34x1
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/pkinit-proxy-chain.crt b/third_party/heimdal/lib/hx509/data/pkinit-proxy-chain.crt
new file mode 100644
index 0000000..2b425bc
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/pkinit-proxy-chain.crt
@@ -0,0 +1,149 @@
+-----BEGIN CERTIFICATE-----
+MIIFODCCAyCgAwIBAgIJAJd7zCsMMPvAMA0GCSqGSIb3DQEBCwUAMB4xCzAJBgNV
+BAYTAlNFMQ8wDQYDVQQDDAZwa2luaXQwIBcNMTkwMzIyMjIyNTA3WhgPMjUxODEx
+MjEyMjI1MDdaMDUxCzAJBgNVBAYTAlNFMQ8wDQYDVQQDDAZwa2luaXQxFTATBgNV
+BAMMDHBraW5pdC1wcm94eTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB
+AM1Z218qhKJXqYoQ/5DZgDYNtgJ9QLkPF0vsu6cScVhykomP1H2Qjj3+u6ZFB9oj
+YS/ynPgkCjwexA7nDGVxfrR0OksDNFGHwCu/O1wagzyeImgvYYzPlKyFqT+0IN0U
+TgEoMdtXUduxmJGr0wEr2aMeiETUGZmRc02icTPZIznhf9elXmAp7EQspjtN9P04
+OCkVygr/FKkeI7XsZR8Ekzqdaf400g1Cy+X2kMvnRs/Tyf3qp/xv1RG7cDz+vfiB
+8S/Vd2zSyBFboOZZi0xVo2vEs9nzBbmTQFAFINSEtIjJWb9Tupz4YwU/xK9bq2G7
+/eOrt4e9pXry1gUKNN/qZIEkbaebhWxW6twMVO/nyXlnklpF1PvPKHsWP2JqhJK7
+9SZcqZkeRit1wlwXsWhb+Zzl27K74P1WgNQF9lbPwhQ6bPmadirCs0kkMBDjmh4U
+SJe/5wIOLVPY0KrhQeC7Vn+hkCxqRTwZQuLKDWUKgd4jmvsjfLYAZVQfGUBX1x7D
+Wng44pW7ytOSbn/4pAu38FGGLbPcKNw+cRRtHtBpWiCthDIJ6gOmJo8JngaU2Iss
+ozmxfGZsdQscUEFVwL5X9YaBpWcGKKxZH7UXq3S3wOEm2yQ6/UrdJnuP+xIYFEiA
+c7tQIFBYoX11+/cZGyVZmn8ESM4ytw9QqmxxaDAEdaJjAgMBAAGjYDBeMAkGA1Ud
+EwQCMAAwCwYDVR0PBAQDAgXgMB0GA1UdDgQWBBSU/W8lX964Gjrb5YqSo3zg3XLl
+vzAlBggrBgEFBQcBDgEB/wQWMBQCAQAwDwYIKwYBBQUHFQAEA2ZvbzANBgkqhkiG
+9w0BAQsFAAOCAgEA2bcpIO8UZ7eDFPtIZd6BWVrQZ5Dj+LZA0KV2v+FjoZQN0/w6
+gzloDy0x3yym6lOtCNPnjxcYP2yfGl5WZet1VXCR+KXXHGID2MkOXhXTCH7eSCGC
+GZpOsSEWs+CXyP/X5B85nkweK8MzLRdJc4Ilxf1UMMOdobgQnRq41NgWyQxA8xLR
+jEeGV+CD5dvteyqBeXvq4IBBUTqAiyoH57XXZRPwWH7z3h9f7B4GdoQuRBQK+idM
+hLgtQ9nkT+DDyoMC6iAtIVwntxsAIg5rUSkQ6RgS3ap6SC94+v3q5V2BJaJl/R+0
+X5ybK2hRKWsUAvU280UX/xT5EGeokHwegI+F7yQflTGI1p090uhBYZvWYj2G8wf5
+nlE7a2h8IG3SmS7qUlKe+RyPwHce+jgHU0aS3ROxreLGf/VX1k3yR2Vk0wpVWFis
+WeC7U5g+iqv/UomqxpFwP3iH8RJhL3eGYVmatHIXjm838wepofexqUL4UKoY/t+h
+FmMusCz2SFZFbgOHF1Vd9C3c/mr6J4HbYju1hO09iOFuQmoo4CjNjdKyLvP1HSap
+g7IPdLP0f++1gGcRq8AkFC9U/vZx5OPwjIku645WeOBoLhFcSoLxyhMeekSNXpwS
+WHArnvVC7cmuvuzmzf5+XqmBzSD0RWGK09drTZdryXuzv8djbeqldeRr1Zg=
+-----END CERTIFICATE-----
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 6 (0x6)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: CN=hx509 Test Root CA, C=SE
+ Validity
+ Not Before: Mar 22 22:25:06 2019 GMT
+ Not After : Nov 21 22:25:06 2518 GMT
+ Subject: C=SE, CN=pkinit
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:e4:e6:1a:b1:de:91:30:34:8a:c7:f2:d9:0a:09:
+ 82:13:46:e9:db:c8:54:1e:0e:b0:b0:0a:e3:a3:b5:
+ 55:3c:6f:f8:45:8f:24:ed:56:c5:16:23:aa:ad:86:
+ 5a:5a:e0:8f:a2:f5:82:59:cc:70:b7:45:cc:1b:44:
+ a7:49:4b:ff:63:28:9d:01:22:79:ca:1a:6a:2b:75:
+ f8:40:c0:f0:93:b1:ab:85:cd:af:88:ac:30:f3:cb:
+ 42:87:fc:be:76:bb:fd:1c:a4:45:7a:66:37:47:ea:
+ aa:bf:c4:4b:47:fb:5b:ab:3f:c1:22:a9:06:f2:61:
+ 3d:5b:20:51:fc:ce:a7:82:74:6f:3d:ac:68:d6:78:
+ a2:77:83:26:af:23:63:20:3f:21:6e:29:1f:55:4c:
+ a6:d0:5a:51:e5:96:c1:cd:22:03:22:ee:de:42:3c:
+ 82:4d:29:20:c6:be:85:5b:04:3a:5f:8b:c7:e8:4e:
+ aa:3c:8e:dd:0d:d8:e5:d0:ff:0b:52:37:40:51:0d:
+ 33:f7:a8:05:07:76:dc:48:20:cd:52:38:a4:1f:44:
+ 11:cf:6d:58:a9:5a:9a:34:cb:93:07:30:e3:66:7b:
+ dc:d3:0b:6b:a2:1c:3f:19:ec:0b:0c:ea:29:6c:75:
+ 4d:7a:86:cf:35:87:9e:50:15:f3:34:73:0e:ac:4b:
+ a5:aa:1f:a2:f9:d5:8f:34:bd:5f:19:ae:22:8c:7f:
+ f7:ca:64:e6:ed:42:75:e5:92:9c:53:53:b7:66:68:
+ e5:07:eb:08:40:ec:bd:7c:ae:b0:c4:a5:4b:d7:4b:
+ 58:86:05:a8:91:db:ee:7a:3f:c4:fd:83:e5:7b:cb:
+ d0:8c:87:68:3b:83:67:e5:6a:5e:fa:28:b5:ee:07:
+ b1:0d:6a:93:1e:b0:c7:5c:57:fd:ce:e2:9c:0f:5e:
+ fe:41:cf:20:f2:1d:88:52:00:d4:83:fe:5b:d7:87:
+ 49:b0:78:2b:a7:60:c2:55:c6:c3:a2:6d:16:04:7f:
+ 8b:12:f7:65:c6:91:41:53:d8:ac:70:c0:3d:83:d8:
+ e0:6c:bb:3e:48:b8:c2:72:be:c0:35:61:40:ff:9f:
+ 97:18:9e:c7:39:0f:93:36:8f:0e:a6:3c:6d:5b:fd:
+ 89:6a:bb:ee:5e:43:f8:0d:29:7a:cf:23:bf:0b:c1:
+ 29:76:ae:a2:9a:73:b2:d0:b9:bd:48:51:25:8a:6b:
+ a9:c5:07:94:26:03:10:74:7b:fc:b7:5d:8f:2d:97:
+ 55:11:3e:7c:04:89:0e:b9:b9:73:2a:6c:5b:12:19:
+ 65:92:48:64:d5:4f:2c:79:3f:16:ad:65:97:21:db:
+ 3c:30:68:67:aa:42:14:86:59:57:b0:79:15:9e:a3:
+ 05:4f:33
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints:
+ CA:FALSE
+ X509v3 Key Usage:
+ Digital Signature, Non Repudiation, Key Encipherment
+ X509v3 Subject Key Identifier:
+ 7A:C6:DB:B8:D2:75:D1:8D:BB:72:AE:B5:25:6E:6F:8C:AF:63:3A:4D
+ X509v3 Subject Alternative Name:
+ othername:<unsupported>
+ Signature Algorithm: sha1WithRSAEncryption
+ 7f:5c:76:fd:3d:ef:0c:7f:70:c7:09:d3:5c:c1:b6:40:25:47:
+ a3:6a:bf:4e:ad:d1:e6:cc:92:86:b6:6a:42:3d:4f:bc:f1:6f:
+ fd:7e:22:52:9c:dc:a6:0b:71:98:80:44:cf:f1:91:bb:50:c8:
+ 15:cd:8c:d8:9c:7d:8d:69:61:1b:4c:66:40:77:44:45:33:9c:
+ 9a:04:01:a1:4b:82:3a:d7:39:97:27:90:a6:71:9a:b1:9c:ce:
+ 60:01:8b:a5:6f:39:a3:e1:75:de:3c:5c:61:66:a5:50:db:0f:
+ 4a:03:32:8d:dd:e5:b6:ab:6a:b2:53:6a:4c:c9:99:74:f7:f5:
+ 1e:a5:06:1a:d3:64:26:c5:77:f4:a6:40:1a:c4:7e:22:05:a6:
+ a5:25:f7:5d:74:a5:c9:86:c0:3a:88:2e:6e:0e:58:4f:e5:6e:
+ e9:2a:34:2a:1d:1d:a4:e4:74:f3:a5:e5:56:5d:5f:02:c4:eb:
+ c7:12:f2:55:6a:f1:6c:ec:6e:b8:c1:2d:aa:4a:7d:ed:91:c8:
+ 78:1b:b7:b9:37:17:32:ee:1b:b5:d9:5c:98:d2:cf:d8:c6:90:
+ a5:c9:f1:eb:8d:2c:d4:90:b2:8c:e5:53:9a:66:20:92:8b:a2:
+ 0c:8b:76:9b:5f:5b:39:77:69:67:a7:8c:de:10:57:85:45:a4:
+ 8f:85:3a:59:5f:fc:0c:70:de:1c:67:33:5e:9b:a5:21:3d:bd:
+ 2e:de:3e:c2:0d:cf:8f:52:43:92:01:cc:47:da:af:47:85:69:
+ 94:d3:9f:c9:d5:5d:50:ca:27:a5:bb:c0:53:12:e0:e8:3c:ed:
+ 0d:bd:47:97:af:be:b8:f9:0c:10:2a:79:21:3c:15:ef:c0:a5:
+ eb:33:38:93:5b:a3:de:1a:97:eb:c3:db:04:1f:e8:f4:23:10:
+ ff:2d:1e:9b:4e:1f:8e:27:7d:71:34:e2:be:74:a2:62:69:9a:
+ 83:7b:6e:9e:e4:a2:7c:84:82:ff:83:b3:cd:d2:0f:74:05:72:
+ b8:b0:45:23:b6:cd:04:25:2d:58:7f:92:ce:68:f9:ba:d0:9e:
+ a8:e1:f8:c0:86:0e:aa:ee:f9:af:ff:5c:bf:46:76:08:b1:83:
+ e7:66:8b:ca:1b:8f:f4:9f:6a:ac:71:4e:3a:d1:77:fd:97:81:
+ ff:0e:d0:d1:4a:7e:6d:94:e6:8c:e1:28:92:b1:68:83:5a:62:
+ 48:0d:26:ee:28:60:57:ff:52:b8:1e:8c:03:d8:fb:c1:6e:4f:
+ fd:7a:46:0b:0f:c8:05:ad:3a:a4:68:be:fd:30:62:ce:f2:0a:
+ b1:34:2c:95:e7:e2:91:ec:a3:c6:4e:2d:a5:fe:09:45:84:38:
+ 9c:d7:f4:0b:18:22:9d:df
+-----BEGIN CERTIFICATE-----
+MIIFODCCAyCgAwIBAgIBBjANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw
+OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMCAXDTE5MDMyMjIyMjUwNloYDzI1
+MTgxMTIxMjIyNTA2WjAeMQswCQYDVQQGEwJTRTEPMA0GA1UEAwwGcGtpbml0MIIC
+IjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA5OYasd6RMDSKx/LZCgmCE0bp
+28hUHg6wsArjo7VVPG/4RY8k7VbFFiOqrYZaWuCPovWCWcxwt0XMG0SnSUv/Yyid
+ASJ5yhpqK3X4QMDwk7Grhc2viKww88tCh/y+drv9HKRFemY3R+qqv8RLR/tbqz/B
+IqkG8mE9WyBR/M6ngnRvPaxo1niid4MmryNjID8hbikfVUym0FpR5ZbBzSIDIu7e
+QjyCTSkgxr6FWwQ6X4vH6E6qPI7dDdjl0P8LUjdAUQ0z96gFB3bcSCDNUjikH0QR
+z21YqVqaNMuTBzDjZnvc0wtrohw/GewLDOopbHVNeobPNYeeUBXzNHMOrEulqh+i
++dWPNL1fGa4ijH/3ymTm7UJ15ZKcU1O3ZmjlB+sIQOy9fK6wxKVL10tYhgWokdvu
+ej/E/YPle8vQjIdoO4Nn5Wpe+ii17gexDWqTHrDHXFf9zuKcD17+Qc8g8h2IUgDU
+g/5b14dJsHgrp2DCVcbDom0WBH+LEvdlxpFBU9iscMA9g9jgbLs+SLjCcr7ANWFA
+/5+XGJ7HOQ+TNo8OpjxtW/2JarvuXkP4DSl6zyO/C8Epdq6imnOy0Lm9SFElimup
+xQeUJgMQdHv8t12PLZdVET58BIkOublzKmxbEhllkkhk1U8seT8WrWWXIds8MGhn
+qkIUhllXsHkVnqMFTzMCAwEAAaNzMHEwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAw
+HQYDVR0OBBYEFHrG27jSddGNu3KutSVub4yvYzpNMDgGA1UdEQQxMC+gLQYGKwYB
+BQICoCMwIaANGwtURVNULkg1TC5TRaEQMA6gAwIBAaEHMAUbA2JhcjANBgkqhkiG
+9w0BAQUFAAOCAgEAf1x2/T3vDH9wxwnTXMG2QCVHo2q/Tq3R5syShrZqQj1PvPFv
+/X4iUpzcpgtxmIBEz/GRu1DIFc2M2Jx9jWlhG0xmQHdERTOcmgQBoUuCOtc5lyeQ
+pnGasZzOYAGLpW85o+F13jxcYWalUNsPSgMyjd3ltqtqslNqTMmZdPf1HqUGGtNk
+JsV39KZAGsR+IgWmpSX3XXSlyYbAOogubg5YT+Vu6So0Kh0dpOR086XlVl1fAsTr
+xxLyVWrxbOxuuMEtqkp97ZHIeBu3uTcXMu4btdlcmNLP2MaQpcnx640s1JCyjOVT
+mmYgkouiDIt2m19bOXdpZ6eM3hBXhUWkj4U6WV/8DHDeHGczXpulIT29Lt4+wg3P
+j1JDkgHMR9qvR4VplNOfydVdUMonpbvAUxLg6DztDb1Hl6++uPkMECp5ITwV78Cl
+6zM4k1uj3hqX68PbBB/o9CMQ/y0em04fjid9cTTivnSiYmmag3tunuSifISC/4Oz
+zdIPdAVyuLBFI7bNBCUtWH+Szmj5utCeqOH4wIYOqu75r/9cv0Z2CLGD52aLyhuP
+9J9qrHFOOtF3/ZeB/w7Q0Up+bZTmjOEokrFog1piSA0m7ihgV/9SuB6MA9j7wW5P
+/XpGCw/IBa06pGi+/TBizvIKsTQslefikeyjxk4tpf4JRYQ4nNf0Cxgind8=
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/pkinit-proxy.crt b/third_party/heimdal/lib/hx509/data/pkinit-proxy.crt
new file mode 100644
index 0000000..d92acdf
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/pkinit-proxy.crt
@@ -0,0 +1,30 @@
+-----BEGIN CERTIFICATE-----
+MIIFODCCAyCgAwIBAgIJAJd7zCsMMPvAMA0GCSqGSIb3DQEBCwUAMB4xCzAJBgNV
+BAYTAlNFMQ8wDQYDVQQDDAZwa2luaXQwIBcNMTkwMzIyMjIyNTA3WhgPMjUxODEx
+MjEyMjI1MDdaMDUxCzAJBgNVBAYTAlNFMQ8wDQYDVQQDDAZwa2luaXQxFTATBgNV
+BAMMDHBraW5pdC1wcm94eTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB
+AM1Z218qhKJXqYoQ/5DZgDYNtgJ9QLkPF0vsu6cScVhykomP1H2Qjj3+u6ZFB9oj
+YS/ynPgkCjwexA7nDGVxfrR0OksDNFGHwCu/O1wagzyeImgvYYzPlKyFqT+0IN0U
+TgEoMdtXUduxmJGr0wEr2aMeiETUGZmRc02icTPZIznhf9elXmAp7EQspjtN9P04
+OCkVygr/FKkeI7XsZR8Ekzqdaf400g1Cy+X2kMvnRs/Tyf3qp/xv1RG7cDz+vfiB
+8S/Vd2zSyBFboOZZi0xVo2vEs9nzBbmTQFAFINSEtIjJWb9Tupz4YwU/xK9bq2G7
+/eOrt4e9pXry1gUKNN/qZIEkbaebhWxW6twMVO/nyXlnklpF1PvPKHsWP2JqhJK7
+9SZcqZkeRit1wlwXsWhb+Zzl27K74P1WgNQF9lbPwhQ6bPmadirCs0kkMBDjmh4U
+SJe/5wIOLVPY0KrhQeC7Vn+hkCxqRTwZQuLKDWUKgd4jmvsjfLYAZVQfGUBX1x7D
+Wng44pW7ytOSbn/4pAu38FGGLbPcKNw+cRRtHtBpWiCthDIJ6gOmJo8JngaU2Iss
+ozmxfGZsdQscUEFVwL5X9YaBpWcGKKxZH7UXq3S3wOEm2yQ6/UrdJnuP+xIYFEiA
+c7tQIFBYoX11+/cZGyVZmn8ESM4ytw9QqmxxaDAEdaJjAgMBAAGjYDBeMAkGA1Ud
+EwQCMAAwCwYDVR0PBAQDAgXgMB0GA1UdDgQWBBSU/W8lX964Gjrb5YqSo3zg3XLl
+vzAlBggrBgEFBQcBDgEB/wQWMBQCAQAwDwYIKwYBBQUHFQAEA2ZvbzANBgkqhkiG
+9w0BAQsFAAOCAgEA2bcpIO8UZ7eDFPtIZd6BWVrQZ5Dj+LZA0KV2v+FjoZQN0/w6
+gzloDy0x3yym6lOtCNPnjxcYP2yfGl5WZet1VXCR+KXXHGID2MkOXhXTCH7eSCGC
+GZpOsSEWs+CXyP/X5B85nkweK8MzLRdJc4Ilxf1UMMOdobgQnRq41NgWyQxA8xLR
+jEeGV+CD5dvteyqBeXvq4IBBUTqAiyoH57XXZRPwWH7z3h9f7B4GdoQuRBQK+idM
+hLgtQ9nkT+DDyoMC6iAtIVwntxsAIg5rUSkQ6RgS3ap6SC94+v3q5V2BJaJl/R+0
+X5ybK2hRKWsUAvU280UX/xT5EGeokHwegI+F7yQflTGI1p090uhBYZvWYj2G8wf5
+nlE7a2h8IG3SmS7qUlKe+RyPwHce+jgHU0aS3ROxreLGf/VX1k3yR2Vk0wpVWFis
+WeC7U5g+iqv/UomqxpFwP3iH8RJhL3eGYVmatHIXjm838wepofexqUL4UKoY/t+h
+FmMusCz2SFZFbgOHF1Vd9C3c/mr6J4HbYju1hO09iOFuQmoo4CjNjdKyLvP1HSap
+g7IPdLP0f++1gGcRq8AkFC9U/vZx5OPwjIku645WeOBoLhFcSoLxyhMeekSNXpwS
+WHArnvVC7cmuvuzmzf5+XqmBzSD0RWGK09drTZdryXuzv8djbeqldeRr1Zg=
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/pkinit-proxy.key b/third_party/heimdal/lib/hx509/data/pkinit-proxy.key
new file mode 100644
index 0000000..6ef1f81
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/pkinit-proxy.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDNWdtfKoSiV6mK
+EP+Q2YA2DbYCfUC5DxdL7LunEnFYcpKJj9R9kI49/rumRQfaI2Ev8pz4JAo8HsQO
+5wxlcX60dDpLAzRRh8ArvztcGoM8niJoL2GMz5Sshak/tCDdFE4BKDHbV1HbsZiR
+q9MBK9mjHohE1BmZkXNNonEz2SM54X/XpV5gKexELKY7TfT9ODgpFcoK/xSpHiO1
+7GUfBJM6nWn+NNINQsvl9pDL50bP08n96qf8b9URu3A8/r34gfEv1Xds0sgRW6Dm
+WYtMVaNrxLPZ8wW5k0BQBSDUhLSIyVm/U7qc+GMFP8SvW6thu/3jq7eHvaV68tYF
+CjTf6mSBJG2nm4VsVurcDFTv58l5Z5JaRdT7zyh7Fj9iaoSSu/UmXKmZHkYrdcJc
+F7FoW/mc5duyu+D9VoDUBfZWz8IUOmz5mnYqwrNJJDAQ45oeFEiXv+cCDi1T2NCq
+4UHgu1Z/oZAsakU8GULiyg1lCoHeI5r7I3y2AGVUHxlAV9cew1p4OOKVu8rTkm5/
++KQLt/BRhi2z3CjcPnEUbR7QaVogrYQyCeoDpiaPCZ4GlNiLLKM5sXxmbHULHFBB
+VcC+V/WGgaVnBiisWR+1F6t0t8DhJtskOv1K3SZ7j/sSGBRIgHO7UCBQWKF9dfv3
+GRslWZp/BEjOMrcPUKpscWgwBHWiYwIDAQABAoICAQCIK2e+qXEePccc2Ly/jpro
+PRtOd0Qt8wXdwPOGjEJBBmiJc6jSQsMv9PT2Apx8WC2gH99a5Hss9rHHuAqOUj5U
+5yWojE1rKvuRhtOT9bjEv4/NSm4Dc7sA0/kxVv7b2xUGy2KUMkkDx7aGEkxvYGaH
+Nj3idksrfDnbZzZtzTUAsrmVhAEa/3G+m2T3unAUYe1LwTkjJZbLtkKz5jf/44bF
+vZCFkv0e8gZHTcMikxBvy98L00jlqjq98W8x4zKR0Yjf0UvKC9PDPuFpHkOysK8X
+TW59vhszvaNN7LiidAVLF0m+B4WdhVAUMP750W3J92EaUcn35xgOeWzWFriNKt7N
+W9P288jWeNazQoNS6ygi9zJERX869UWxw+SAiWlymhmFC9tQgMEH1RJy3TtrFQpa
+krDv8mnkYBLU7BUI//jEbWLSfrXndHKgsLEO+bXViVV80PqX3d6xxTRItuANcZKy
+Yz4kA4aKDg1lrDcDMUTG4BZJthHD1xlCg7d+xnxVmamsoQ89AyErsYmVMxd5C2IA
+TbCKseKyPd7nztHc1ktEdpM6DhXqrZw0o1pCVSQeXkPpFqG3b0vwtZFYiyNwJGpW
+Wzn3w7f6ZRwZYAbj3t1Esxjw+ej++6DTbUBZWRllhgpMoryCbtCfWRsL7S4u6I7E
+1dzmF8pdJ+vvOaeC5BZxoQKCAQEA7dPAX7ZCOp6Mgp88VIBw4Rb6duSBPWqiL3mn
+4BtV2UFbU+So4Ro5SRUF1O6KJ8tZsyRfGZn+B+wSjPUsgp4dFfpP1GSQvIk3HkEU
+Zg6VNvxPRd/oloRjvG119BBXr7mpkCDEmGxLqXAvxvafFc4gGajFBRISPWLsDAYu
+0yDMkCmPWMWMLx/sYLv2lE/0GLa7oOO/5flHFM/Mom4HOactq6nghHT8Rn77b9zg
+WOyNsX0nZTtjLlWGjH/R2mRLYwI1mq3cUTCnwRNPYhgbgIQS7666jtfUP17H1W2H
++hZrggrmVVHzYSW1Z2fLUTAMXuPUE98bnF5LytoZ1huMQU6ESwKCAQEA3QrTAZwj
+KU9Kc/Ur9K047Xfs56XpOtlo67sWY8GQRxFv+pIKT5zJIJBm6O/9Ps+ZuhykzOdZ
+uuee8pDzszFw6jprRpEutFRh//xBE+VKW1SQipKKS8hHYIH+BJlLBJ0VdvQCtoLX
+sTOmmL7E3szuKUEmCPQqYj3VrAWQXqzNF7uQdns62lSBLI2b8ZuwBbS6Pk4J9Ic8
+d902+y9kTO2j4jipMQHxVVEoaksZxdVTUZgAlku+xkMM/oxQclMoXnx4uemiQoxq
+u6k0waZpW5yvlNys23YCFPl8A3tMWZ0HC5UOQVXL2KgsVLAoYvNJAhQxWbSj0i6m
+sRSsEN/SmJobSQKCAQBJkZRTxzyLh5otmfZ+qVDBwGrwNlVoW0EacIamw631y8rl
+k7lOEN+hpNgt+zBPiQ8RZHHqqIE1kChY5ErFiQW0U784E3fWapfbSwR1YZN08+3N
+zqrTTNbRZgbz3c5SNJuoUwqdn/pzypls8cNaam3xogx4OhPcW2precooU2AURFbs
+fgeUWEq1zc9EJ8t5jaVS6sDk8gyz+mfx4xlnEzkEfkNOliWn5QYAn5Hi0CIwwmda
+YFmY7qn1cmDHLvlHAlr0o02g6+0ow8FttclkIvb8n89j+o3UoIwukHhcu2y8SITh
+5bzk01ZfS3NQhQ1+mPl0wDJ5V44YjQkq+1CSrygrAoIBAQDN9K/26Ay7CO5ObTqv
+mFdarEtI7AYMl1Zzjral7E0Kauzzg++njma4uNOqZzKHu9d42geUBFxPElG/od/w
+LzkOhbA+6DekPpuxcNESQKqvvnOPKktBoTMgcP7GOi7z9YlydJmyhOeEbKPl3pqB
+HmEqf1F5NkfnkcXtqqGCFXBjlJheTSPhGqvhX3DWBkJUjriaJQyRkxB8ftoj4VyL
+cUEqH7FFwJGk9SG7KI6zDrm7ZO3nHFx9TyxkYUjzvRf4MfIrB83wQ/WPNXG6ndu9
+SJkxEwzcz2/RK0Sp2dCiDvXpjNDjf5WYIdpsblazHAwCq93vv6iExoL6rFBGyMXo
++m5BAoIBAEEH9DWpYZRLw2SQbsdSgMRRFo2Kvu7jpmCbQVWlBA2WjAUIPhie4hkt
+DUUKVROwzPXinMCkZuZ1YL/A1R9gJ30Qo+c4Cj6tKlZ8Ux5cmEOjLfQuREMsJ9Tv
+wYyFodqKW4wRvtNn2Ij+C/VV4dDncIMM0mw8EoQ4/DP2aseqzG49rOrYGl43gs1l
+RTMyyPiWyweJZ2e0IRSnqrcSEcvPfw9ViZWNVAHMycA6ttt3gSi0+57OjPmxeEPC
+9z9x5N+7zKOfpUo6/jguC1TRFzmKJYpMlRhM/0Ruz2imghKMn86PUKI/GBrOXhx4
+k2odOmvIh8CJ2ZSNtza8KPoCHxzIOQU=
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/pkinit-pw.key b/third_party/heimdal/lib/hx509/data/pkinit-pw.key
new file mode 100644
index 0000000..3fef51f
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/pkinit-pw.key
@@ -0,0 +1,54 @@
+-----BEGIN RSA PRIVATE KEY-----
+Proc-Type: 4,ENCRYPTED
+DEK-Info: AES-256-CBC,0D7945ED368F10EDD0E5FB517DA6CEDD
+
+U4MlgA6Abbuv+8v7XUYDCxGw8Sd4xWCuxFWu3+twUWfpN3MG95RPuCf21m1rXb0q
+BmmyRECQg6Kk+wuFKVeKEVsBT5pJ/CmutPeE3Y1Oxkn0G09RygO3+mrZInnMdACM
+9TYYUA6AGp67hF4G5pJUk7T+Zdfu5+pxhzsRC24UussXFlUtnPCS1QlRWUraVpzs
+Ei7whYsfz3Fcw5ZEo5b9z+NHqU3OIMfLH2Q0dPJ7Y2gHtteaftmOcRALcz7l4Jug
++9YCAOChw110BII76z6fwPDKbJuMAlZuzhB4XFfYbwVqvMbddQslANb2PiaReIRk
+g52kJY/cMb/nSbGwf0ZG9rGhcuw6xdvMoTFPtqqy7NXEPxfwlxoAxsJVg3Rp/4d9
+M8h4mOyvDjuluIK1GpPfoHGCOYFyduaQQM+KZ00D08j/d8y8RkaD07eXOLQE3CHY
+qXO8fE91lpcnxVRVCv1s4v63/FgqYrrU7rqSgGaQwKrcZK4hZEbL8yMcJFe4KOoJ
+m2k7pqi6hL9JILz7G9+oMnrObOZ9aK+ZiXz09+CxWYhwCcQrFXaK9XKDUWLqoSZn
+ZBj1xYqwW1kvhybdUENHXUVh3G4lA2+sWbEKvSLwcAsiIVkYxuiWwb9Ix5MPCKDK
+ZuzIQaQ5Ji5PWPqCR4iYdt8BOq/r2iMEUwJ2KZtxRcPknbH94rt31dz0cXr/fFO7
+OPxGTuJILIvf+wRZ88x8hmYA6JjRvEHZDrlwmk+uoUBsOYEcVOg7hd/AQYd1BZWQ
+HvlELIHaGgLxmq/C1InRbU/mtnIElBHAI3NLKpSgGyFH4/Mis/M/VnHJaC3sWKFR
+bJ5SobVa8HYgRy6y3mA/DsssGVj/dz2riTzjCXpNmju83D8wGJ8iDjJP0183R6Zh
+Rb83W3EAjkHHLIkli40E7H6cq1RjXTrzUpvE21Yq5vbk6rBnLRO/lDX4lpFq0S09
+Rd8UQUhXqTxtOGXIFv/4sS2P4oIAx+mk4pf+iJMltjvCLCNkPQRL+NewVHMm4zhK
+25Yo9SNObY/zk3MBKH0FnI9xAmS7xUdzjRTQvP8yqBu0lQfJo2np3FsjtGyvjYWO
+b11L4mc+n19LCA2PpU4VaWxzPfZraBBHJy75Cqk0xXx/9obtrgZ89qXgv6H6PZod
+8W64PUK+895+07plpOAmrS0WZL0muh5m9qarabmY0dcoiG16Ln2iAEJTvepKn/7f
+H7rC8OoFr6AWYRx3hj0dLCSs6VPVFLAyQvEPIQlPFndT8rhuP9z8W1W6OkLpe8wE
+fVFL3jNMwRTYTB9aAwFFeyrf1CbaTs8iRmp0eZgTteNbhshx1UdAasj7sLLUhPFe
+cU9evtCKFqoRfSiuR0uzetWMJ7vODxGDzGkbDhIqVRpcUaBz6cQs4NlslT/ebXe9
+5xL6KWI3vUIJeWcTEJbl0sUTBbmRUxPB636XdQ4l3OIYI32NK29fX2+2pHXqaWql
+L8iVwsLJM422pxHdixGmO0eLEJ1Y62tvmTWQ3Nr+/ZJP8h9yk61gj2QTHOVAyz7o
+UxZie77035ni7vZG0AjJDz80hj9rnMpznTUZCiEzArJ65RTrUmiiedSyatHYEREK
+pC3+2aqvrOaGCikIfFTAEOKlE2ZjDVZ1jYCFCVFmJE6sqtpIigMeiChsFlxg4FCo
+zIvfFEY6QdnqHPvUMsXNr/p5xcVQjZhitk8Av/Lr1gSsHapiRthbty2Yry1r2QYb
+T79qdouzk0sGdIORM5SmEvPAp/459cy91nIEav4eC5JB/owPyPB5KNuz6wL1Guo1
+TUDoOyR/vkB4Ybm9A4se6ldYftK3nxiFCL96SgqFP5WC6JAwZROBKFn5HWLdVPOD
+/lXB3SxGe48PjcAX2ugo8KySpDC41uUIHOdxPeRBUPWB9bRpAmLfV7lsBC0X7fPn
+ghdnQav0TcQTOwChNaCLpUSzRzk71y7IR/4LASgm7WZUoV3YF8SarsA+wOvKCuKf
+GJJThmSRzhSU8xbyU8hdVAd0XT8d2tSNJLuJ8PT//dqbh4Ft6U+DjpNX2XUtAINe
+9L61Wpj5HduTqcXSTeHnhdDqjuAEGrFkR3P/SmA/r+uaaVvi/sbbh8cBqvjC3O40
+Z+e4JDd2XvjCgChdJIOUJfHfvLGjkaGJIecizT8YYGO0FyebnPPah/Jj1R4XPaWZ
++Wu2ro1/GKKnHCsIMbEz4BbGrapi63RWGRufNhVE518CX7vMsqgbMFgspfbUinrq
+N6+5MD/VLrMkbCrYxVFRP8Lcug4IJhRjV9olI9GEN7/ulMV8A4UQXh0K9zPox21H
+qPf9kgPpd8GNWXZ+/kQkuLL74BjWCiiUxqDLFY6xKN+5yPwe9l0TNymuSNAxJCMZ
+2Jyfhaq3R7AlqNisoNFO99g3HVXXowi1dK9hc2AqXdqyN5w6LrO8eAy3FQsBv8iD
+pFruJeMve+Fohzrnb8L9B+Wm5nNUH9Z1/jsR+/rnaoqOYl1qza88URqlcy8ovPXh
+1y3d0YGZi877nzLPTe0WPSy0ueJkolqx27hrwvLA6SLBFwzg174pS/vmH1cmEKep
+ZekUuAUxp3pJ70Dzu+lsSnye66mUxx56JHGcCD1uiUkB8qWXTGrnTGkxUJYfZoip
+0nX6YWChnuXkQ46B/tYIaP0+d94LkqjB2VzEDv71oXU4uTD2hqK2i2oTRlXQUBV6
+iNutj1sawU7WUXBRUf0ls8GRIHb6xvNVwnus0/P0VnUkTMCVE3ohQCw2SLkCiPtX
+o24G7A6jNCsM3XTfK68P0TqkMKg5wYJM7Pbt4FLBRxy0uzeR6GarMneLP173rH+Z
+LX5zVvEveL6yHnmKHZm9OoXj+NNn9HkUdCWqxmOvYNl8TTRh58ZCIUDJn4ZQcMkw
+jjOSPfaPWkNrLXm/PxW55JmLuewgHGWo/1gfJCrewrvkuXWJffL09An1/rJoqb0B
+TSFAKj6c/WhJvG7qFYLd7+tMfoet2exw34uP6tvi8Lq/u6cG63wXKbzhpXtvyqOs
+wOOVZDnTskF5syX20FojeKCLCUQWIMv/vYKlrCeA0zpxL4qQFxpHlHAI2cw8MtVa
+Cd8XFmQihZRm+7A8dDsL0AU5ai0kh7yIAhZZ/bR4sUscnbO2y/w+AItcBbfcCK8T
+-----END RSA PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/pkinit.crt b/third_party/heimdal/lib/hx509/data/pkinit.crt
new file mode 100644
index 0000000..3f20629
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/pkinit.crt
@@ -0,0 +1,119 @@
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 6 (0x6)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: CN=hx509 Test Root CA, C=SE
+ Validity
+ Not Before: Mar 22 22:25:06 2019 GMT
+ Not After : Nov 21 22:25:06 2518 GMT
+ Subject: C=SE, CN=pkinit
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:e4:e6:1a:b1:de:91:30:34:8a:c7:f2:d9:0a:09:
+ 82:13:46:e9:db:c8:54:1e:0e:b0:b0:0a:e3:a3:b5:
+ 55:3c:6f:f8:45:8f:24:ed:56:c5:16:23:aa:ad:86:
+ 5a:5a:e0:8f:a2:f5:82:59:cc:70:b7:45:cc:1b:44:
+ a7:49:4b:ff:63:28:9d:01:22:79:ca:1a:6a:2b:75:
+ f8:40:c0:f0:93:b1:ab:85:cd:af:88:ac:30:f3:cb:
+ 42:87:fc:be:76:bb:fd:1c:a4:45:7a:66:37:47:ea:
+ aa:bf:c4:4b:47:fb:5b:ab:3f:c1:22:a9:06:f2:61:
+ 3d:5b:20:51:fc:ce:a7:82:74:6f:3d:ac:68:d6:78:
+ a2:77:83:26:af:23:63:20:3f:21:6e:29:1f:55:4c:
+ a6:d0:5a:51:e5:96:c1:cd:22:03:22:ee:de:42:3c:
+ 82:4d:29:20:c6:be:85:5b:04:3a:5f:8b:c7:e8:4e:
+ aa:3c:8e:dd:0d:d8:e5:d0:ff:0b:52:37:40:51:0d:
+ 33:f7:a8:05:07:76:dc:48:20:cd:52:38:a4:1f:44:
+ 11:cf:6d:58:a9:5a:9a:34:cb:93:07:30:e3:66:7b:
+ dc:d3:0b:6b:a2:1c:3f:19:ec:0b:0c:ea:29:6c:75:
+ 4d:7a:86:cf:35:87:9e:50:15:f3:34:73:0e:ac:4b:
+ a5:aa:1f:a2:f9:d5:8f:34:bd:5f:19:ae:22:8c:7f:
+ f7:ca:64:e6:ed:42:75:e5:92:9c:53:53:b7:66:68:
+ e5:07:eb:08:40:ec:bd:7c:ae:b0:c4:a5:4b:d7:4b:
+ 58:86:05:a8:91:db:ee:7a:3f:c4:fd:83:e5:7b:cb:
+ d0:8c:87:68:3b:83:67:e5:6a:5e:fa:28:b5:ee:07:
+ b1:0d:6a:93:1e:b0:c7:5c:57:fd:ce:e2:9c:0f:5e:
+ fe:41:cf:20:f2:1d:88:52:00:d4:83:fe:5b:d7:87:
+ 49:b0:78:2b:a7:60:c2:55:c6:c3:a2:6d:16:04:7f:
+ 8b:12:f7:65:c6:91:41:53:d8:ac:70:c0:3d:83:d8:
+ e0:6c:bb:3e:48:b8:c2:72:be:c0:35:61:40:ff:9f:
+ 97:18:9e:c7:39:0f:93:36:8f:0e:a6:3c:6d:5b:fd:
+ 89:6a:bb:ee:5e:43:f8:0d:29:7a:cf:23:bf:0b:c1:
+ 29:76:ae:a2:9a:73:b2:d0:b9:bd:48:51:25:8a:6b:
+ a9:c5:07:94:26:03:10:74:7b:fc:b7:5d:8f:2d:97:
+ 55:11:3e:7c:04:89:0e:b9:b9:73:2a:6c:5b:12:19:
+ 65:92:48:64:d5:4f:2c:79:3f:16:ad:65:97:21:db:
+ 3c:30:68:67:aa:42:14:86:59:57:b0:79:15:9e:a3:
+ 05:4f:33
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints:
+ CA:FALSE
+ X509v3 Key Usage:
+ Digital Signature, Non Repudiation, Key Encipherment
+ X509v3 Subject Key Identifier:
+ 7A:C6:DB:B8:D2:75:D1:8D:BB:72:AE:B5:25:6E:6F:8C:AF:63:3A:4D
+ X509v3 Subject Alternative Name:
+ othername:<unsupported>
+ Signature Algorithm: sha1WithRSAEncryption
+ 7f:5c:76:fd:3d:ef:0c:7f:70:c7:09:d3:5c:c1:b6:40:25:47:
+ a3:6a:bf:4e:ad:d1:e6:cc:92:86:b6:6a:42:3d:4f:bc:f1:6f:
+ fd:7e:22:52:9c:dc:a6:0b:71:98:80:44:cf:f1:91:bb:50:c8:
+ 15:cd:8c:d8:9c:7d:8d:69:61:1b:4c:66:40:77:44:45:33:9c:
+ 9a:04:01:a1:4b:82:3a:d7:39:97:27:90:a6:71:9a:b1:9c:ce:
+ 60:01:8b:a5:6f:39:a3:e1:75:de:3c:5c:61:66:a5:50:db:0f:
+ 4a:03:32:8d:dd:e5:b6:ab:6a:b2:53:6a:4c:c9:99:74:f7:f5:
+ 1e:a5:06:1a:d3:64:26:c5:77:f4:a6:40:1a:c4:7e:22:05:a6:
+ a5:25:f7:5d:74:a5:c9:86:c0:3a:88:2e:6e:0e:58:4f:e5:6e:
+ e9:2a:34:2a:1d:1d:a4:e4:74:f3:a5:e5:56:5d:5f:02:c4:eb:
+ c7:12:f2:55:6a:f1:6c:ec:6e:b8:c1:2d:aa:4a:7d:ed:91:c8:
+ 78:1b:b7:b9:37:17:32:ee:1b:b5:d9:5c:98:d2:cf:d8:c6:90:
+ a5:c9:f1:eb:8d:2c:d4:90:b2:8c:e5:53:9a:66:20:92:8b:a2:
+ 0c:8b:76:9b:5f:5b:39:77:69:67:a7:8c:de:10:57:85:45:a4:
+ 8f:85:3a:59:5f:fc:0c:70:de:1c:67:33:5e:9b:a5:21:3d:bd:
+ 2e:de:3e:c2:0d:cf:8f:52:43:92:01:cc:47:da:af:47:85:69:
+ 94:d3:9f:c9:d5:5d:50:ca:27:a5:bb:c0:53:12:e0:e8:3c:ed:
+ 0d:bd:47:97:af:be:b8:f9:0c:10:2a:79:21:3c:15:ef:c0:a5:
+ eb:33:38:93:5b:a3:de:1a:97:eb:c3:db:04:1f:e8:f4:23:10:
+ ff:2d:1e:9b:4e:1f:8e:27:7d:71:34:e2:be:74:a2:62:69:9a:
+ 83:7b:6e:9e:e4:a2:7c:84:82:ff:83:b3:cd:d2:0f:74:05:72:
+ b8:b0:45:23:b6:cd:04:25:2d:58:7f:92:ce:68:f9:ba:d0:9e:
+ a8:e1:f8:c0:86:0e:aa:ee:f9:af:ff:5c:bf:46:76:08:b1:83:
+ e7:66:8b:ca:1b:8f:f4:9f:6a:ac:71:4e:3a:d1:77:fd:97:81:
+ ff:0e:d0:d1:4a:7e:6d:94:e6:8c:e1:28:92:b1:68:83:5a:62:
+ 48:0d:26:ee:28:60:57:ff:52:b8:1e:8c:03:d8:fb:c1:6e:4f:
+ fd:7a:46:0b:0f:c8:05:ad:3a:a4:68:be:fd:30:62:ce:f2:0a:
+ b1:34:2c:95:e7:e2:91:ec:a3:c6:4e:2d:a5:fe:09:45:84:38:
+ 9c:d7:f4:0b:18:22:9d:df
+-----BEGIN CERTIFICATE-----
+MIIFODCCAyCgAwIBAgIBBjANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw
+OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMCAXDTE5MDMyMjIyMjUwNloYDzI1
+MTgxMTIxMjIyNTA2WjAeMQswCQYDVQQGEwJTRTEPMA0GA1UEAwwGcGtpbml0MIIC
+IjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA5OYasd6RMDSKx/LZCgmCE0bp
+28hUHg6wsArjo7VVPG/4RY8k7VbFFiOqrYZaWuCPovWCWcxwt0XMG0SnSUv/Yyid
+ASJ5yhpqK3X4QMDwk7Grhc2viKww88tCh/y+drv9HKRFemY3R+qqv8RLR/tbqz/B
+IqkG8mE9WyBR/M6ngnRvPaxo1niid4MmryNjID8hbikfVUym0FpR5ZbBzSIDIu7e
+QjyCTSkgxr6FWwQ6X4vH6E6qPI7dDdjl0P8LUjdAUQ0z96gFB3bcSCDNUjikH0QR
+z21YqVqaNMuTBzDjZnvc0wtrohw/GewLDOopbHVNeobPNYeeUBXzNHMOrEulqh+i
++dWPNL1fGa4ijH/3ymTm7UJ15ZKcU1O3ZmjlB+sIQOy9fK6wxKVL10tYhgWokdvu
+ej/E/YPle8vQjIdoO4Nn5Wpe+ii17gexDWqTHrDHXFf9zuKcD17+Qc8g8h2IUgDU
+g/5b14dJsHgrp2DCVcbDom0WBH+LEvdlxpFBU9iscMA9g9jgbLs+SLjCcr7ANWFA
+/5+XGJ7HOQ+TNo8OpjxtW/2JarvuXkP4DSl6zyO/C8Epdq6imnOy0Lm9SFElimup
+xQeUJgMQdHv8t12PLZdVET58BIkOublzKmxbEhllkkhk1U8seT8WrWWXIds8MGhn
+qkIUhllXsHkVnqMFTzMCAwEAAaNzMHEwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAw
+HQYDVR0OBBYEFHrG27jSddGNu3KutSVub4yvYzpNMDgGA1UdEQQxMC+gLQYGKwYB
+BQICoCMwIaANGwtURVNULkg1TC5TRaEQMA6gAwIBAaEHMAUbA2JhcjANBgkqhkiG
+9w0BAQUFAAOCAgEAf1x2/T3vDH9wxwnTXMG2QCVHo2q/Tq3R5syShrZqQj1PvPFv
+/X4iUpzcpgtxmIBEz/GRu1DIFc2M2Jx9jWlhG0xmQHdERTOcmgQBoUuCOtc5lyeQ
+pnGasZzOYAGLpW85o+F13jxcYWalUNsPSgMyjd3ltqtqslNqTMmZdPf1HqUGGtNk
+JsV39KZAGsR+IgWmpSX3XXSlyYbAOogubg5YT+Vu6So0Kh0dpOR086XlVl1fAsTr
+xxLyVWrxbOxuuMEtqkp97ZHIeBu3uTcXMu4btdlcmNLP2MaQpcnx640s1JCyjOVT
+mmYgkouiDIt2m19bOXdpZ6eM3hBXhUWkj4U6WV/8DHDeHGczXpulIT29Lt4+wg3P
+j1JDkgHMR9qvR4VplNOfydVdUMonpbvAUxLg6DztDb1Hl6++uPkMECp5ITwV78Cl
+6zM4k1uj3hqX68PbBB/o9CMQ/y0em04fjid9cTTivnSiYmmag3tunuSifISC/4Oz
+zdIPdAVyuLBFI7bNBCUtWH+Szmj5utCeqOH4wIYOqu75r/9cv0Z2CLGD52aLyhuP
+9J9qrHFOOtF3/ZeB/w7Q0Up+bZTmjOEokrFog1piSA0m7ihgV/9SuB6MA9j7wW5P
+/XpGCw/IBa06pGi+/TBizvIKsTQslefikeyjxk4tpf4JRYQ4nNf0Cxgind8=
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/pkinit.key b/third_party/heimdal/lib/hx509/data/pkinit.key
new file mode 100644
index 0000000..ee1c842
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/pkinit.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJRAIBADANBgkqhkiG9w0BAQEFAASCCS4wggkqAgEAAoICAQDk5hqx3pEwNIrH
+8tkKCYITRunbyFQeDrCwCuOjtVU8b/hFjyTtVsUWI6qthlpa4I+i9YJZzHC3Rcwb
+RKdJS/9jKJ0BInnKGmordfhAwPCTsauFza+IrDDzy0KH/L52u/0cpEV6ZjdH6qq/
+xEtH+1urP8EiqQbyYT1bIFH8zqeCdG89rGjWeKJ3gyavI2MgPyFuKR9VTKbQWlHl
+lsHNIgMi7t5CPIJNKSDGvoVbBDpfi8foTqo8jt0N2OXQ/wtSN0BRDTP3qAUHdtxI
+IM1SOKQfRBHPbVipWpo0y5MHMONme9zTC2uiHD8Z7AsM6ilsdU16hs81h55QFfM0
+cw6sS6WqH6L51Y80vV8ZriKMf/fKZObtQnXlkpxTU7dmaOUH6whA7L18rrDEpUvX
+S1iGBaiR2+56P8T9g+V7y9CMh2g7g2flal76KLXuB7ENapMesMdcV/3O4pwPXv5B
+zyDyHYhSANSD/lvXh0mweCunYMJVxsOibRYEf4sS92XGkUFT2KxwwD2D2OBsuz5I
+uMJyvsA1YUD/n5cYnsc5D5M2jw6mPG1b/Ylqu+5eQ/gNKXrPI78LwSl2rqKac7LQ
+ub1IUSWKa6nFB5QmAxB0e/y3XY8tl1URPnwEiQ65uXMqbFsSGWWSSGTVTyx5Pxat
+ZZch2zwwaGeqQhSGWVeweRWeowVPMwIDAQABAoICABdRKV79ISUb9RcxMdLH7Swx
+iRkOayM0s+L6+P1wN2KUtWHAly5mLGV49KYAjau8PGWJROII5WKGBaixcakRyM49
+EOFQtb9UuYP73HIcNWWWL7bNoRf3EnWDOx/HK0/FDp+gTEOPrgnxabtnL5QBkvD6
+6Z2yQjbmmO1zeWabVoz/d2V87qEKYOJzxbkJjct3Ityp67swt715teYBWXSgBlnE
+o3dz2oIpsmEMf2EqKRgakR6lBMpucy457g9AK9MQNckL40NTJlAAV6gxTzkU9AML
+WBUdOm7l/9do9W1CGagS7gfBnhFBd1wYo3eJUvbtbBsTKIB3dDUMR14Mam46toFQ
+pxRjTOpywwePQSJAxR3M1QbnOup3w8Mw9+Vw++mVS0woXhCz2zwmPTuC6/YN1WCM
+Zs4jRFQrc1fw3o6BBNmoMb9TL2aDOLbAtMSvFlH4FQQTy4RLzOoZnNAvy5f4qmzp
+VvEqiZzgXhg+VjPlQpGEoBptt3Jru9vOBCdPTd1L7jMUjC3lf+MR1QrJxFNdK0cH
+0YeSehTFOtZ4fTPwXlKJsPXSGyu3ZvN3ukt15X/qQypeqqlnln7BjKuUyltkAl8z
+727G1tgiObFDUL/oPbeqkmGoN+z8mn6PlyN3pe/mYwZES6F5RoEy/AAOrhp0HINz
+lzt7bZVoFY+tVkZU6AyBAoIBAQD6Wc6rzhwa2klX1BjOJXbgsh8tA5zvYM44fcZz
+JSanqwMfiu60nvVW0nF0jVfHKGckJ2KQYbNKucTBJRgAY4a2eXrcEIkOPY50b9Dv
+BtCNhiwfQ31VQct+qoS2693d9N3Q17d0sqUwvSAN33YcePTb/uC8L3Ys6pFrsrn/
+RRTdlcF3077jaYjKFAGRRWhHDaJNsm3XZm1jgHWRktRgiJe+EN6NjW2ScC1UqN1l
+5To2AFbxg/87T89rLcKi47CNF1akFV5o0csQX3KUZtLse5VM5R4j7NGtd8deHgJv
+c+/xC6RblmX6AgXTXUICNBjgIF/QV5XyKTvA3QEvG3eErfBDAoIBAQDqEGBL6MGG
+PT9M7GGFq7pc/BAHkm31+Zq0pTV6EbBwu4SGZtFkhXZJXAi6cAhKBr9u8colZmEW
+EG+OVPhNN4cNOPrbDESFaM5D0dNED5AAUlyE0ozI+Rlx7m91UhPufyWCg66SJNj9
+7o3Kh57N7p8RqpBicuXv6bBBna1+AA6/v3JImE4FWRyg8LwUWWmCVU8CDKzuUdQ2
+Os+irE/eXq20/FYNoFkYNiS28wh9c06v90f9n1QV6ma3tSy11g7a/uTZ4oX6HVoj
+26sMx+z+SDWnKCgTSiELdzpeLooMMAI9toyNLLLw2knzHhOz1M2wcxuYa4hSo6Dj
+N6odujQwCu5RAoIBAQD2ymNG0Aa6nebhMs9FIH+A33aGLGKfQ6Hm5G4mAkCJ1rZc
+eNv5qB2Yehmn2NHoHTcX1899HyLcjiacdBGmCHa7GSP5Hj/NjvcIZ1Xi26fpa5PB
+OgmqaxLMihIMNJXhgMrNXmmWG6lmU3nu0xOe28oduLMYL/1iJ9Y1AdoC/7mi+kbe
+9hjeG6Hh+zjUWUSDjrgpubQ4O9un0/GSENlVVDGqBv0tM3cJfZXiOBkQopjwtQMA
+UKvhbzq8oD6XzrazT4d0dzA7SlzQhhbwnjBdOTKju9Urev/z7fjWGeUys2qcB2r9
+clSS0T2m7+7rNyoyfxeUzVKehvFFnVfWdVArtj/7AoIBAQDE66wokRUn/CVicUkG
+7din3EUcKbyrgij/LDNWlMVNwuWXMa+fE43V4EFToWfH5+9sxq2cU4sAxikkpSYV
+yM6teC/M1IBdgTRv6HsGutUbAC/oaz+Y4cHfkYtiOACe2YfUSzc2qxuIYAgYyYr4
+lHZtpYM94I7FDmWEfsT0ydWeytG6c7DIXRVx7bc+o47Z4S3Mep+PDXctfMMtiCzV
+1+/q4ZUAd9QdQ4gWB1gwOy+Lac6+eSqEGaX7jsij3wi2hFZDXYn8SG+K1YgOA7HG
+qTfCf01gFTDB9bg8fokUAdwQ0aFkMKQHcI9gpABNfo7ikaU40ddqN1Hnd/B+fCbl
++HxRAoIBAQCA98OxfQECOxve0RMTAslR1mq7MqHMcmk/ukENJsErxWYp2r4Ghgmu
+wWeweGBFwTPJ1lqm0+mpyUphE20m8A6QxN4dR7ckAQfGjuc6ZRBJDhSY/rPv+3j0
+fBhKyJl+DL4RiNCXncQFD4sa8YH6UcsGDo8OkWr1ZzOQp0jTSa8yOmswDlt7boch
+5DGHb5xtngPe5lpVg+t2VZeXF7sTy7BZwwTLLZWtI5wHuUAnOeLvwCMHmZTrpwe+
+cN0oo2nQTI/EgYf5ZyVj+zfiaxvST5AN6BKj8QApwC0q/TipqoLghxD3YNzUokFI
+RGobyk3036+cucUBlLFJBboNBbUzUX7l
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/proxy-level-test.crt b/third_party/heimdal/lib/hx509/data/proxy-level-test.crt
new file mode 100644
index 0000000..51422e9
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/proxy-level-test.crt
@@ -0,0 +1,31 @@
+-----BEGIN CERTIFICATE-----
+MIIFVzCCAz+gAwIBAgIJAOXO+qv/iXxCMA0GCSqGSIb3DQEBCwUAMDExCzAJBgNV
+BAYTAlNFMRIwEAYDVQQDDAlUZXN0IGNlcnQxDjAMBgNVBAMMBXByb3h5MCAXDTE5
+MDMyMjIyMjUxM1oYDzI1MTgxMTIxMjIyNTEzWjBBMQswCQYDVQQGEwJTRTESMBAG
+A1UEAwwJVGVzdCBjZXJ0MQ4wDAYDVQQDDAVwcm94eTEOMAwGA1UEAwwFY2hpbGQw
+ggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDPMfDYnc56LmPFqSovq3KU
+JcBypPhCtrOiJ3vwLIumg+NDlsWdhG0EP8xwGnbikR5RNAi/PtCV8cGsbQ3+Fio8
+AFVQs956itoNEvzoL+mbyNpyRVr1ph9qJ/lO5mzdNfCQb++b73bkygUaNKJPpdL5
+VNEwdG6bEEw59+WWqATO1geUv//AeNPqLrKFDMg5HQzCjGXhwE99J156AQ4fw6lB
+0Yubssk6AfHLKd+UKh8qRPdO1EYzgHRuSGW7olXUbiS3wmPe1/JYMEiILjGmvAaA
+Y55qsxFxZlTEehO99WF6rOrP1lC3ddcBd0fXBvJTiQeQsHT29tiVlPMFolmnQMbO
++bzLUPSx9ukW2deirFViXnC7pb5Cv8ZIJ2jsZEG3D4JM5WqZ1ycrKAq49r284LbX
+LZH0ZnKZyGJmOjsXqIwWJJthMSlb7l/TA4IdRePYlaYQNQqIYwsPv9o+wv3owUaV
+1PePDbn3PY/LENshooIV1yqhbA/Kr4ayiYuTFLtugPcWwi8sAXFNC3t6x4+xTK3n
+S0n30hvIWZGKes8Zz46E6ANAf+stiKWxhTROrfLNKvenKXc4iVETOzZkBhQPyhk5
+dM1aC9rylQnm30o8oVnNpn/z9rePdCDbBluHKcJE4xcX5QpU3qybO5W5A7dhxsjw
+0iVfuheSt5AkE4ixHAy/6wIDAQABo2AwXjAJBgNVHRMEAjAAMAsGA1UdDwQEAwIF
+4DAdBgNVHQ4EFgQUcMWBbIV1HXTcW9hfIFew2urXq5QwJQYIKwYBBQUHAQ4BAf8E
+FjAUAgEAMA8GCCsGAQUFBxUABANmb28wDQYJKoZIhvcNAQELBQADggIBAGygvoGy
+/aUbaxSh8v1ug6qHHDMuKAddD4qnTx/JKFyUbVDKOUsiu4kuwH5uoIMhhPd5XYBw
+2gNjptKIK/o5CMGXQpAFV9cfd7h57bhBTBU5xPvdsTsXSRObkmESE07XF81Vmqbz
+3+YvbhYy98mHszMnsBzG24pJYn+Xhv0KfUINV+BzZZPZmwTkZki8gnAYpSfA85d2
+o1SO2iP0kZPUOoTRDrvN6v7EHFxar8Prka2jpHBPRXUMANbGl/Iu8SvzukVDc6g2
+pEBa9vDPl2Tf44kct+hB7Q735xSfHF5PJaUt/kzVclFNNWyNRr99S1mM5IEnAzF3
+PpkWHOke/L1dvWJT7wBSPfwMtyQz7gIGdA6Oq5CkFxE259bb7XJxRwfQV12pB4p5
+ZYUDTpd1P3D+VHQzmGi+EcgKEgoydVp4ikQj7aDUQWzZ49st+xLf0suE6wmNNSd+
+4dSuAeHbV0rglwlo/LZ3UPCd8nzhGTC5t6L8vFcDkrC7RyaBR8X2OeTU8FLP02me
+q1eMF8k89L6ar1etLfC2+PKRGhcohJjm1Yz7sTSIeT6SnSxZeoSGAkFFwy70in0m
+9mJNpNGfBCr2DS+XncpvVcIIYjHmrKWYfbnxYcouh/PJqpKKp4JXceV0u1e2DlvQ
+Cew9o2dZuv5HXMmm4xpp8gyrzCzfZuExPIZd
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/proxy-level-test.key b/third_party/heimdal/lib/hx509/data/proxy-level-test.key
new file mode 100644
index 0000000..352bfa8
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/proxy-level-test.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJRAIBADANBgkqhkiG9w0BAQEFAASCCS4wggkqAgEAAoICAQDPMfDYnc56LmPF
+qSovq3KUJcBypPhCtrOiJ3vwLIumg+NDlsWdhG0EP8xwGnbikR5RNAi/PtCV8cGs
+bQ3+Fio8AFVQs956itoNEvzoL+mbyNpyRVr1ph9qJ/lO5mzdNfCQb++b73bkygUa
+NKJPpdL5VNEwdG6bEEw59+WWqATO1geUv//AeNPqLrKFDMg5HQzCjGXhwE99J156
+AQ4fw6lB0Yubssk6AfHLKd+UKh8qRPdO1EYzgHRuSGW7olXUbiS3wmPe1/JYMEiI
+LjGmvAaAY55qsxFxZlTEehO99WF6rOrP1lC3ddcBd0fXBvJTiQeQsHT29tiVlPMF
+olmnQMbO+bzLUPSx9ukW2deirFViXnC7pb5Cv8ZIJ2jsZEG3D4JM5WqZ1ycrKAq4
+9r284LbXLZH0ZnKZyGJmOjsXqIwWJJthMSlb7l/TA4IdRePYlaYQNQqIYwsPv9o+
+wv3owUaV1PePDbn3PY/LENshooIV1yqhbA/Kr4ayiYuTFLtugPcWwi8sAXFNC3t6
+x4+xTK3nS0n30hvIWZGKes8Zz46E6ANAf+stiKWxhTROrfLNKvenKXc4iVETOzZk
+BhQPyhk5dM1aC9rylQnm30o8oVnNpn/z9rePdCDbBluHKcJE4xcX5QpU3qybO5W5
+A7dhxsjw0iVfuheSt5AkE4ixHAy/6wIDAQABAoICAQCfHKLwNn+RpH5KFJao9OiQ
+jE01vSpJUTSxmdC7p/m2biHgjbBEPqXZVYURscEKTJcTlPoCo6JbA8TPPRA5x5u3
+aCocR4TaZjb9Q0+knuavE5dtmYU4j9IgG4KA7MM9PWb4BH3lKggLunggn7rln1pc
+zp22sDMgMWvYOF6/S1gl3ocD3E3y6NcUR7ggJKi982kRHfA/ZQel/M24s4a9LeyU
+9u5XKv0M5uFgO0/O4Gn+c+fXSXx/oG3JIx+87/UppUvdMhKv1vXsc2e/7HmEqW/0
+uIu3NLx4cTU3jOgMQJwTMSdBZDuoJ35tScSJhHQjYl/E5T1tSjMY68GU2hAvOLdy
+Z+rsZTcu9orvnMij0kmxjbXdQGK3PlcLiiwYZKrwuyn3b3aMq0nq0OwTsGtSRPDf
+30dOSuTEf8GKnxB9wtogYD6aEDOhFJNXYh819W9weNyIeGu6sarsReKAJJihyO3I
+1VtlexqEWB5OFn5KbHZoRp4Fvc8XtaXolajHsCcic1uKUOG/Iuegum9EemcPnmPW
+XVe6JknXhrjxd48KiaXLQ7dYoIGCQMjvdsOvIwzppf6ZZ7WMyqxGnb3TtmDDJxIf
+ovSu43s9uWhTOA5Nrp5sY3VFSyzq0g5U8NgEC+HjGVgA3UB0GDsB+vUaEseZg0Kf
+faXIuvJg3WoGJ/VVWnaTwQKCAQEA+FSa4kjKmD+fm4LA9bmVldB+cfsqSl3TUcfr
+oxb0i2ouYhrG0eV6EjvXizswF3CuVGKQCtWg7GDeG3vKbVFtkSTg1KU9jir4ha3k
+5spAxqNBB5S+IK6xeGipHiu6AuHZZN/8Z2T2FWkGNTdRRKnw8cdfSlBq9wG/LXJW
+g/Cnxsvyu8temursSIX2nKYSUsHZIBnJZAXUwBOWUMLpzaS6UtdKIJDCaPprx4Kz
+elYqJhddT8eO3HIXXWthVzjm+dgyKnxSjIUVyVekKareNzGxZxjMu1lg6tybnR2O
+rBejni9//y2HQyFRuWUzRV9FwjiWS6AJNm1V4OvaxOIjKHFG5wKCAQEA1Zgaierq
+g8OudyNGFpNQ9TAS7lcERP3z/nyR0kgnSBlTpppaWzUgkdifmK8tMmiu+M7Mj8Qf
+Nb5/h+HdwY62xA476/iI8yrSppHj3nuC2aWn9wg6gP/iKUF0ZvaxR3MsU+k1gs6Z
+IcozjzIxuyY1whMm+FaPrHx+1l/P1Dn6JotZ1uFhikzmoZc8atLIK6wPylkz2i/X
+7OkOkkz10BpvbC44F66Owlf49Gjwa1c7Mj9kJYsY+Dqoo4nk6j7EqzJN3e3Pa+n6
+pAfQhddVUKl1ULBlnLHGh6x3vAb4L6sfmsq7EhbTGQFd/M1oxUtPW6BAJ63gYPAh
+AWU8Emg59lBSXQKCAQAxTApbNXwScT7sDi7kGO1bCkKvud6RWMLkjz116M6vBmsi
+ypIBhP6QtBR77UoEvTe+RLq3i+UgR7KP3ik3Plzz3VBMpmjr2hfv4a95KVlmlW4J
+ZTvBHSzZ7Fz2QlPw0ojnf5eJpv87DNhQpCSb7uiH9r4x8HjrhAtBqFsIYjPMQRx0
+r1CejFhPpVhpjIZCq3zA5J2YH5g2cSz751WmnzblzxtGD7aoRF41AvtCI+zGFwlN
+Fx6DIJsGzpRKTl975bE/weJZRuomSCGsq+DlMBY5kzDBWGLm/NhffkieXSr78g4E
+yDL73pdsqGxfLySYA8fCR4jMpzPPLMMHJqU4GBStAoIBAQCBwLi+d5qnGMRvU1pM
+dImFqQKXDv1k+/Cw8/ORjotuXRRX7QRey9NRRgsNsbz/FmDUfKv/2eArweGvJiKU
+ZqHYT91O59gqACWfUpjemqFOnjd+9dy0aL122nBf7BSdlvWis9Tx9ZdI05CmuJNF
+YVze3MubqNn2qlpS2DlkbyPrLlQRGTEr1rN0Dm+BZTJ8dTXScoXxUYcWQC296kqZ
+dLWjPiCNIllO7ioqL2V9j6xCRggMVoeApAG19xq8wgyvAwwSeVi78ZN0+dpOtBT7
+vzWpIr9XhRdZbAgAjStPqeC1I9qojn0Gf7Ic1JuE3s8ClkLi19mqibVDJ8BqXi53
+1ytxAoIBAQDCgJk3PsF9v2W2SVHrs1zpcEOP3JR9Oj6q6ThAHLF6uUqXsWEbXjKk
+z3ReI7tMO8A5J0rpPuCEJUdiPtly8FsyiXIheSOQ7UN0w6ip3abDwuJFGFYBqrib
+MEI+r7b6xT5o3U+csGbimhwCtGeCDL9W9YwK4nYGi/+NO+6qfX4dovOyydCZff5m
+Gl5MRo7L76EnLheVHDGq4PQLZtLJCT6O2OAA/p+5IUFWzf1uOnoceDyw2KueijN4
+67gtUS9T6ex5/MWRoWeIcNhmXM+aFcAbW79hAycliP8jIF7q5feUER5QepYGfZ3c
+JKt/SLgrlhrJ0BbcNKAnbzOeBZGPpEJk
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/proxy-test.crt b/third_party/heimdal/lib/hx509/data/proxy-test.crt
new file mode 100644
index 0000000..9f9cd57
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/proxy-test.crt
@@ -0,0 +1,30 @@
+-----BEGIN CERTIFICATE-----
+MIIFNzCCAx+gAwIBAgIJAKQmPUkmhyKhMA0GCSqGSIb3DQEBCwUAMCExCzAJBgNV
+BAYTAlNFMRIwEAYDVQQDDAlUZXN0IGNlcnQwIBcNMTkwMzIyMjIyNTEyWhgPMjUx
+ODExMjEyMjI1MTJaMDExCzAJBgNVBAYTAlNFMRIwEAYDVQQDDAlUZXN0IGNlcnQx
+DjAMBgNVBAMMBXByb3h5MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA
+mPssWfri3hoR0eHC6FCqD3arIBwD+XeYJXS2y1zA9UgijF3rLDtyubOpp/5Or6Q9
+cO7m4S+4xPquasRUS8A9rJZbxi3rvptVFD2DBmpEUNbIjlW2TdymVpAtD4uHKpOA
+xeEtn6eXlhDiiJcrrqLds9cLGRG0XaPSeTwzOWqhtyEeMp3rvVQ/NeMfYsMF87m/
+txopxdJnpEoArfxxudLSQ0HrILLVV/VbQZEcoJXEMjhZg0Qnw5rHRV5dacLT1gmp
+w2yRQID0rbcKk6b3ukRHXD9OWNt074afzQJmMx1MDlHv8IeFtksxEhhA9i612LTi
+KaU5Ac11ZJ+ew2YnV3HU3roH6BHeGeWHDhxqfpV7DPXZsUVo18kgrY+w1E+lcntT
+FfWzWXF6p7gIPQKBy/IG3FsdP9ugx4y54Jl2HsrBEOjA+x45TL80T0zA0FXuu6fo
+oljNGUrQfPQiWJCnQmWkjIhbVo+aovSlBRnOSsAxr7H8Ry4jhF2eQG8TIDgPRGs3
+DSwIUJyQwoRvRpo01ZJ1akfUkJFzv519EuN/zfNVTO2KBGVXprkONCZVN6eVpDVb
+rClN5iUqCimn4xhv2T7VhDKO6mjOMMR38kdLvsrtAWBpob7hDHr0zAXCwSwheVVM
+fMkYHZEyVfsxS7/ooA+oLwbHewhV3zJQDK6zAgyi+jUCAwEAAaNgMF4wCQYDVR0T
+BAIwADALBgNVHQ8EBAMCBeAwHQYDVR0OBBYEFFyuJ+5Hf8HzZNaew6ZLRnQubKRB
+MCUGCCsGAQUFBwEOAQH/BBYwFAIBADAPBggrBgEFBQcVAAQDZm9vMA0GCSqGSIb3
+DQEBCwUAA4ICAQAqn4xPkjg5lR+wOQwxKyxfzjS2ycEW+8WLp+l5p7qHmv4JOSwO
+/XFf+6sRSGiBwHAoOq3yJlU0NzEq+uLjEg20/MXQ1+R4N2AsWeD4wUxRkjoukmc+
+at4wza4SoJLzfv8rYtZRx7quXDq+tFgAHxZv/AB3tghCyjS9JiaAc2aA015XmAec
+qZcLjWoDmIH4mgT+LuenPbS9Dus8mGbOiTsns+iVCMZKJOBU1KF1UUy+f+J3SGqX
+nsHzfMiFqU8qA6sQ3mZy4yqPG0Yu7r6YfpV2HQPCLXy1VZ3BINf/9YINaUCe/NpQ
+Md1Pd6Q3U8+QObyAxXVfmTRFGCDu+S0NlpEfZzPnRYxr0ZfwC3SKWMwVHugv9v3k
+qkZAgB4T9u0TqBjuB9mWoyzYEqwRgFg0AjrtgWXPJ8MSnth3eSrJjcXhEqgq1NvJ
+SZVPzYW9RKB7lAM/4cDmrGXB1Lq2g4b5R8H1wzBtjL+CGjCuly9uR5HvxCOPLzPm
+btZTRQtdA96L490wcv4D3JHN9ro0cq4QB2m6XKr2wDDh3CEgQQmaTKufWR8zAL8R
+5HYtKxt1dcz6w4FiLgq9g+ADZMwJpErmGgldX/NKMz4Rfy0qMCprIn6XgPWWlSC4
+BT/0EyLjDJhwap661H5sMkchCx4uywG6EvQBRf4bxpWQgxReSO1znefULQ==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/proxy-test.key b/third_party/heimdal/lib/hx509/data/proxy-test.key
new file mode 100644
index 0000000..fc303ea
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/proxy-test.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQCY+yxZ+uLeGhHR
+4cLoUKoPdqsgHAP5d5gldLbLXMD1SCKMXessO3K5s6mn/k6vpD1w7ubhL7jE+q5q
+xFRLwD2sllvGLeu+m1UUPYMGakRQ1siOVbZN3KZWkC0Pi4cqk4DF4S2fp5eWEOKI
+lyuuot2z1wsZEbRdo9J5PDM5aqG3IR4yneu9VD814x9iwwXzub+3GinF0mekSgCt
+/HG50tJDQesgstVX9VtBkRyglcQyOFmDRCfDmsdFXl1pwtPWCanDbJFAgPSttwqT
+pve6REdcP05Y23Tvhp/NAmYzHUwOUe/wh4W2SzESGED2LrXYtOIppTkBzXVkn57D
+ZidXcdTeugfoEd4Z5YcOHGp+lXsM9dmxRWjXySCtj7DUT6Vye1MV9bNZcXqnuAg9
+AoHL8gbcWx0/26DHjLngmXYeysEQ6MD7HjlMvzRPTMDQVe67p+iiWM0ZStB89CJY
+kKdCZaSMiFtWj5qi9KUFGc5KwDGvsfxHLiOEXZ5AbxMgOA9EazcNLAhQnJDChG9G
+mjTVknVqR9SQkXO/nX0S43/N81VM7YoEZVemuQ40JlU3p5WkNVusKU3mJSoKKafj
+GG/ZPtWEMo7qaM4wxHfyR0u+yu0BYGmhvuEMevTMBcLBLCF5VUx8yRgdkTJV+zFL
+v+igD6gvBsd7CFXfMlAMrrMCDKL6NQIDAQABAoICAHwnJAhmXyYHHD0sLmUhydJA
+6YJmmickkvqa7Rq/zO2DPF6Ufh5opKPnFiH7dlp/PUng6MkKVLawB0soyIytmJ/v
+as28SN1o7LQ/c42KQqUkmqFBGHG6R9hqq9c40lqQWOq+46r1dUVZsK9PmCjjjm+8
+bwpKXwm7wT2YyK2pR1L68qn7le0SaTZPfBJH2hXBwsBT4GDmcCxZzpFlFdrMKM5i
+ufLQj+oRep0MqqH8ybxEFQk+D9NkUqKOgdsqPYcwUnECNCOYRHqS2WeZEuU9Mni/
++9KLUCxwIlJbxxtmhGn+v26CXdbi0RExU883e2dC7WUE7O30k3g1PsCvr+/8ttdG
+AwzeeLb1o+dYIJrFBb/YmpehrE2JP5aTi47AtSAkKnYo5lSkxPEdqxSNuU6VQp4l
++MtPvV6JKY0HfDYKPxdXFdrGDQurNeRjrgyXZ0MSxxVCscR0TXij2bkiGd6Euknf
+Oxgg6KqFRFwXA+aWupNA1lknTEU9AIPb4QBYH8Je3st+Q4FxBCFHE6N0+uKdbX9j
+GlZ01d4WJxo3rJf2q11Wq24G3v+UBtHV/RRrWy7ZBedlr0XFQ+i4lhFFPOvLFSS1
+Hv+7Hzuh4h22RhsAOxNveX89MlhPb6ZrR+3C8U2K7EjHxVlGzAvcoutD7qjUF9N7
+rXOHJG2qwkmoGO5L6z6lAoIBAQDHlvHduYwxfAanrITkQRRodkl8V0xcQhQTNFNj
+1vhQWqzBo1C1p1A4ICuTEmAPR7r8LuCYAP07RbfxPbMS6qfCT4nnJmGPONgkn1my
+s/9s7o5k07TST/Z9VVPCewc0+XcyWHwpgZMPeLSDqB5yRK+t3NoqGOnX3LI4fNE/
+YB5zQWh7cG60SKl18kXvCunMnh0pE8mGE+Mx70RMOrmBxnLv0xDbwbqfY5K8nY7b
+ccaFVMLHkE3YipF+0/zp2H0SVlV48h/fkwYdIzcDNje7ejMRJk0/zviPuTJz4S+0
+sJC3IJ6Cyzk12zmyV7zc0VShFutUbLccmKxfWde4N9I2FiUTAoIBAQDEN+49eQho
+0q0aNLe4LxCXsjJLhDB7XcZiGsFtKrfd79jAo7v/C0HiqbZCecrbcG62Hip4aEc8
+0bFj980LM57XM89QUylzKFJXtQe7/nxvmozQTuX6tFb2AxwSwFcYHfeFPkjsqWTF
+iBsREZ4l7CS1wsgC2vb36rk6GfkAjGd6ZYn7Jl1JXHr6868gBtle1Ad3H/S7BW+J
+Io6upgPHbI11/29ScMu8c7oYk6jQiBrVZd6PEq47AhWatFqlSyq2mjlgGkleRzrN
+J4SogzRs9Emd0xF23bjdGzK1B8GJY6GqUN+lZ2SvkKT2PyQvDuWSOurlOv9GQuBq
+kELci3kNb/SXAoIBAQC0JcEfYQdx7sFO/H9iSn9yHjoL2fvZVecqwlL2TaUJWh6O
+FKuXmnHkhtztvWsov5S9ZE5hxJrMsgvp2cfVLinHT+Vn1pO+Iw+sVowuqRrGJrgt
+t4yBO51+2NJmOodxwC1fKtC+4e5ry4YbQ1ZfyzFKW4oq7xu6M8BFDhwL+OTjIMl+
+iSfS37bc95U5wn7uqlQlrG977l1lx9G8gFDKGuXJI5gW0lBw5v4d8pRr69DErZG1
+cMFizweuEwc3xqh1MamqJdixAtJE4HEaHAjH1e9b7ldRXa2qg/1O7JUToT6tm+qW
+oXl86+ey2lBkeyjI0ZgNNqc8T21eDwiPhQreuLQzAoIBACHdgVnMvN3SlpuyQ48f
+WF7GG5Ya/38bRTUDZyTfPZKpZaCB4d135Owo3FMG0DMlaYY3GJ9lZ/4gNtyJFTN8
+ukpsH7i+UaYVbHjEvsv8dR+R7gG5zEmDvIqDKOI3nhCEg4bUpCNsbP8GqZ09jC0B
+X6ibMIgFoKBTO5rChs5IbUebpL/a9DjIJFWRn0UIyZVrRMqTklqA6qohc7zC3F4b
+5yJZbq4s14zz8EdznKw5AWCZT1skHzwB9RaZUBe9LGcNoR9sCgOiiYyE6Ilo87Bm
+TRpXJml8hP5sRkkmSInczzck9CSI/sCqVz5E0YrpqEefsZDUqOBIhJD/yvpjfAYM
+r4sCggEBALY2BvWagNcnTdINCI25Tt0S6J4vAScyG/LESS+qRxTUklpqAsXNPMQ+
+O9n3B8knb/1UuXeHC7yAScNUSGqq+Z68D9my5cXanSVzOlLwRu6tUa7J58fbkkif
+I3PoVDPjEkYy/yWJEIjqKu5z0x7uMKXid/rf9BHCIH802v0s+EsQZn36kmU3MMpB
+Rriubez85f37vXES6A6DD5EmWUvAAuKvfvXWXtml0f9d/JZd+8jMrHQCwFprdTyM
+fN1crepFBAl6oheb3ColMByiMvU/WzcT5vwCnUEd+46QLuTU0BdXcKWKXviHI1Us
+2f09X6R0XLrRpaAyQD+H/2DVhYM4CV0=
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/proxy10-child-child-test.crt b/third_party/heimdal/lib/hx509/data/proxy10-child-child-test.crt
new file mode 100644
index 0000000..a606da6
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/proxy10-child-child-test.crt
@@ -0,0 +1,32 @@
+-----BEGIN CERTIFICATE-----
+MIIFezCCA2OgAwIBAgIJAIZ6hp81I2P5MA0GCSqGSIb3DQEBCwUAMEMxCzAJBgNV
+BAYTAlNFMRIwEAYDVQQDDAlUZXN0IGNlcnQxEDAOBgNVBAMMB3Byb3h5MTAxDjAM
+BgNVBAMMBWNoaWxkMCAXDTE5MDMyMjIyMjUxNloYDzI1MTgxMTIxMjIyNTE2WjBT
+MQswCQYDVQQGEwJTRTESMBAGA1UEAwwJVGVzdCBjZXJ0MRAwDgYDVQQDDAdwcm94
+eTEwMQ4wDAYDVQQDDAVjaGlsZDEOMAwGA1UEAwwFY2hpbGQwggIiMA0GCSqGSIb3
+DQEBAQUAA4ICDwAwggIKAoICAQDOIxKHoKGi1/5V21RKfDqag54mjcz/ye0NvVHq
+QKXJ4I8EVZyP7fwtl4ElcZ0GyHhqetXsulqgzuoGns5eCAq9mMkX4+3/EXvy0lyz
+rVa+K5ysq6rsUMg7LPpiWA6RM3YYahNedzk3gsRghJ8q0vbvpTzNZQ1A+IOY1kdX
+AeqyBqUT6kLycPYzU/eL2WzVe6pTRt1p2LKckDjxCKJI1ocYhWrdFhbB9YduvEVp
+IRTINGXGvTpk8ZwzvgUQk1BmeGc1qqnmY+/wEEfpu1OZD2+5rJWQ7pSyB1jnMBxq
+mTc5jkrMkzJX9F5JleVY9+bKZcBGu34mmAa4vXfwQOnM2HXAvjw3DJGlZCuNKExs
+Ji9RyZcbe1NZqlBkp9l79cnlqURV6HftFFTyBNloEaNdzi81rYiMlxEoHEHqjLvo
+9HCNV90WDDHPxDG+iOKyY6OAZ/QtjGEAjizp1NYHYkvTG3PzVvqQCsNF4iWzksQY
+3M0OgyDybskOxvUN0NzDrF7Zw0+SqBSnYGWokVoghzQHMQHEOv/gYvrdw4kGs5Db
+RXPfiYKJSPlsFgi0zXpZgm8Br2GxEW6ZfADaK/eONC6FW2W4aL9oqC8XyV2kYi/v
+69G+UeULhVELL4bsUf0moPELFpuwyShHqfQ4l5Us5m66zxc/I0ekz2N66mWv/WQ9
+LNJBBwIDAQABo2AwXjAJBgNVHRMEAjAAMAsGA1UdDwQEAwIF4DAdBgNVHQ4EFgQU
+W8uH0Ungtk49Eykz3IE+8z536hswJQYIKwYBBQUHAQ4BAf8EFjAUAgEKMA8GCCsG
+AQUFBxUABANmb28wDQYJKoZIhvcNAQELBQADggIBAAJxESHv3qYUiqzpmWI13Bbe
+v9UqS/Le+WmWosv7JfbBV/aL9T2FF0uw/sMojKxxs88wfipYAaf7Or92JBlaSyt0
+YMhmhW7+miLEoWqeKkRfBx0q5IHvtmQMpNjDxA9uTXJW0U6FIyhVxXRte/3x4owk
+KUfq5P43ErPMEVipaM0ns2y4+d9WimFtUY/52l/NqH84pwgP/2JuNYtRaOZ5pjyO
+//zSUpiDbyE1OCeBG2b+YqKwDnCdxdqj0pZps/1fLieBr89GbS4SEMlqRgqN6LxO
+XHkfS3frkD87l32zTuQnhD8vxKU01Kr85t6CPL+FIUhjUCxG3Tll8Z+coxgZp8IX
+bjpyJfEx9834UqA3EDKpcuh3vndvov0nXe5XnxpmYevuCpd5fIjnbAdimFMshni7
+WhW+9HzKGTAKqaGXqRyEsPybm6Psw6F60p5Kbr9X8/+WM8j3mReQI4n1yKfW25kR
+HlqLPmwrJUOGDsf2NV0kYg/8Zd+D5uT02LUKQPh5gd/9X/vm/YNJfmLvkK9V0yI9
+5U6nxRe+kQDreWSpP0mS2Bl3o/mOKDwinn4zZLU3IStrvhoVEo9LeIuehsul8zpk
+57x1zHsKwviywBdAeJOXglQRhGhy76+jcN6Ii5rx6Na7uSlTSQqyz23bXfK8BcJr
+TpIzMZLfa2s8faTjnjAD
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/proxy10-child-child-test.key b/third_party/heimdal/lib/hx509/data/proxy10-child-child-test.key
new file mode 100644
index 0000000..7a55601
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/proxy10-child-child-test.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDOIxKHoKGi1/5V
+21RKfDqag54mjcz/ye0NvVHqQKXJ4I8EVZyP7fwtl4ElcZ0GyHhqetXsulqgzuoG
+ns5eCAq9mMkX4+3/EXvy0lyzrVa+K5ysq6rsUMg7LPpiWA6RM3YYahNedzk3gsRg
+hJ8q0vbvpTzNZQ1A+IOY1kdXAeqyBqUT6kLycPYzU/eL2WzVe6pTRt1p2LKckDjx
+CKJI1ocYhWrdFhbB9YduvEVpIRTINGXGvTpk8ZwzvgUQk1BmeGc1qqnmY+/wEEfp
+u1OZD2+5rJWQ7pSyB1jnMBxqmTc5jkrMkzJX9F5JleVY9+bKZcBGu34mmAa4vXfw
+QOnM2HXAvjw3DJGlZCuNKExsJi9RyZcbe1NZqlBkp9l79cnlqURV6HftFFTyBNlo
+EaNdzi81rYiMlxEoHEHqjLvo9HCNV90WDDHPxDG+iOKyY6OAZ/QtjGEAjizp1NYH
+YkvTG3PzVvqQCsNF4iWzksQY3M0OgyDybskOxvUN0NzDrF7Zw0+SqBSnYGWokVog
+hzQHMQHEOv/gYvrdw4kGs5DbRXPfiYKJSPlsFgi0zXpZgm8Br2GxEW6ZfADaK/eO
+NC6FW2W4aL9oqC8XyV2kYi/v69G+UeULhVELL4bsUf0moPELFpuwyShHqfQ4l5Us
+5m66zxc/I0ekz2N66mWv/WQ9LNJBBwIDAQABAoICAHrZ6CcwkmRMueVNS9UAaKTB
+oDV1+SDQpRi1JeaoFKZV0KZSp3YX7Vz2mB9KsLzkKO+8uVXWUkDYUB0V9AOSY2RP
+dDlqu+Jx9x7mRB1JRxMbRsqZnMot8sdhrO+Db1sWAmHWhiicgVsV8hdbssiA5m44
+Wh5HBTkdYsBppCa0m7zxvNw7lx6KOBCrEDMmp3grtXzgFQEKBpjMU0NDVAR45ha1
+HNUaXwHFZKuYRP28m3gd0jI5gF28qM0liDsysI4BX/FZ/tux38OA0Hr6C36C9qD/
+vDueFLxtKIzP3X+iRIlmxilZ6H0GxFKypPb6927UaV0+TJaPsCHVuW9UIILW1oWw
+asv7C6hix0Pkyv2mX4E/wIXEbURuNLXidWJdc86PrFHJh4vtogGpLaLJt8ez6hUh
+3fpqUG/abQrPS+Sa+B+8XdgbruU9u+egfv+kZ2tXzbB/HMlLthgFpjQdHVgU1ZQj
+gCr00fe97BU4oLJO5k+cz0idxNnoBgrgxWL/ffxdETo+Y494D9Gx6oj7JtagqPat
++tG2MVyXzcrV82GWejBPt5IhGcl2xPRSxuJ2xI9VndyAemBNGWL5150PNWAuZmCF
+38x5snuuKibeUryek4qndPHeQ6bYT5jNIkgwBjlv8o2KjFnrzA56/v125psL6sSZ
+XmkloJNZfpnAehzXWeyBAoIBAQDspyysQoCYp7dFvkJUK3LLX/wCkrPHlP4N0QiO
+sa5CUEf6jSrt32a3IR9oo1JycvxMb9zaF+6u03P/y11gVZi6V7plmhlKNDUTg9it
+skR6aBt85wrahK6CWRyKnN9hOI8G4gv7jAyW+yVCDaRHTKPMB1KoQkZ+XUFUVt1v
+tZxGG1gso7nJTjAPTnR3V9SV6I/T00x7LcrWpr39YWO9dkPzXK4kQzmAnVAIw8Jr
+RiEkTjGYWJlTYgGDmhas5u8IsUqJnjbmYMOsXy+hgL5FDp/BssP/Wk8dmHQwEVXw
+ksZfeUh67L6+D12J09LXX2f2NObO1lTqGbzTTGqfgo3QEkVhAoIBAQDe/T0zIDSF
+x2gPUNaBbaXRVSUg4MjxGtTkBfsf89bzoVeMgrR7tJ1ixu0tv5RcBmmeonGt/BS3
+qQZTHM0GUROnTYME8UqqlwfxGXptawCnyffJDEolE+UzHgm+hKsrajJZN6i+hop6
+ATrSPYwyB1dpcC9IYoaaavlkOxpCeZPvIm5r4eMDkiggip/EngmhnbzzRSv1uoUb
+j79VhTbJyOR4uDc9pSBYhtzBEv+bxhbWoH6UUfEPlbw63TtJ3Mtm1gwGy2VDtP5W
+tnTNT4U5VGHN7Y4KTKRROwerB/omWAuZfuSK8JAktQ87jCdULn8ZSdkYh3m9CHRr
+N7beNCFR4LdnAoIBAQCwF91X+Mwzy2jGjsJQW1w6FRwy1fLMqgM5SLfzZidi1NYa
+i/zLsBaAYjc653ysCP/P6NUPvAsxL8r7Jdo/mrHgxvK+M6Jp4tszwEH1TddCtkDt
++gXLgDtSZvij9AMMFsfmuUFtVlLv7cVVl00MeOzRHwnUhixqTv4TwedX/m1ghWxh
+Gxtdvb5pRVnIjCR1v+12E56vce2jN8PbzSIokt4RMn+qIBOjrmslenUq2a5Dk6O3
+1wWQVDcINBp3YgewEiyCpqX3Wz1+//0zUddDD5S0z06krhB81zptohiuwKi31kmm
+no94YXqa2nHjLOzw+YBdnILnB2vIVu5n7v+TOmVBAoIBAAUZr7uqoejpbbTj+XQO
+aPuHwgile5MgNPxeMqdBcYozB4icOLqXn/3xZN1mA2Ozddj+CDGdkW+9+voNr5bU
+ZemuuS90wWtzdugJ2CYGi4ZK9VLw6AU/Fj/8EOb9q9ibXjlyL3bkJuixfIHwjHNc
+faBYw4wZTNDdX4TuYSRiGYMfu3zWNtYPEsHjydG6d6ftrrO1wlKliIPf3tV67Yzh
+/m/QbtsHGt1LgGMeJyCOAFm6ZArKcQQVPa/u/XssBK7+eFnzbwaEbkjXdYZ4qihs
+iKwoIdaUeDGvcvZzgUI9Q06oe1u+Mt3UElwfUYr4YUnXyZJpDtzHA7qsFI+yi4yO
+4kMCggEBALjlyMbOBKzr95yhoTiO8zONQR4PzYt/mOqVrT5JUQqN7FBlGC5rWaG5
+d8Ur1lXiUtuGEVSzhAERyosr7+10nUWaAKnuFhhtLpggauXHKor7vABeu93dC2KA
+6O/K+dMfkx1sMaGXI79B6fCClbEEMJf1J0Zbm5/+UdO4/CyntbVM3tDAPNf0GgIE
+5fI84disd4D8HmLW6Snv93bS7BygXYlBq7Cq8xAw5OvxIl6eroYa6vXcymL1P1XY
+ksRGLm50drZPooekZlQyPIIUvmP/C+Byz347Hz2sDv4KuTjHV5PZSLbDIUYXinQS
+9MZTi7RGridSLpg1QpqCUOcbhOQ1MKQ=
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/proxy10-child-test.crt b/third_party/heimdal/lib/hx509/data/proxy10-child-test.crt
new file mode 100644
index 0000000..41cb814
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/proxy10-child-test.crt
@@ -0,0 +1,31 @@
+-----BEGIN CERTIFICATE-----
+MIIFWzCCA0OgAwIBAgIJAM764JrT/2XxMA0GCSqGSIb3DQEBCwUAMDMxCzAJBgNV
+BAYTAlNFMRIwEAYDVQQDDAlUZXN0IGNlcnQxEDAOBgNVBAMMB3Byb3h5MTAwIBcN
+MTkwMzIyMjIyNTE1WhgPMjUxODExMjEyMjI1MTVaMEMxCzAJBgNVBAYTAlNFMRIw
+EAYDVQQDDAlUZXN0IGNlcnQxEDAOBgNVBAMMB3Byb3h5MTAxDjAMBgNVBAMMBWNo
+aWxkMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAunD1wwgtFwDOISki
+iVAOjL6Q5UHHTFfGMkeXoa6/awWWjRBZT3IdmQlxxXlIEafS9vBMHW4xvAVf2qmg
+Y6IZUy4EGqdrzzzmf64E/QcRW6vGbqRQY+HBqYDum+se4s/XfCo7sSpTLbZexhoM
+Uz22k3reKzT3xurXtbxF+GQcpb2HnESnTL2omtU2PgEZ8BwhjisEB3rHTtQFqBdF
+1uKSvRDJtDlRSUbqgY+cYCFUMdIEtn4djesLdH7yt34i5kukN6RajXJjQTSQFGce
+egHaMOcQ7phIv7j305RFJ6waCXBwTCsBoIPtE2wt9pfgFu8zbcWenXpaxR+en/n/
+2gU7LnK3Odiyh3d0/8a+79gWxXWbmXYV2oYVl9ZxSTqa+wvzYQNaw1BPyhGxd95S
+ACJOw8XuZ16ZEqQArEH59A36NKdca3OYjAf82fOEfRdIHm/CD9SEv9NRQpgzfzBF
+cmiaIdBJg+QJJ0eNr4wZq8sVp1BKlnDosEq0nJ2ywRB3SeTbUrz3VxR3pzjtNYO1
+fIXUnBsoymZtUYqKiNLVP96RyWplxF204zEMP3zx0vIx6pKMmsWivEURxNdo/Hih
+eiDaHB93aw+5+2pgKQOfIg0jj4ChE1JN2FOKBDAFq5+9rJIDuhS0Nk4PtYy/7n4R
+iIDKiqWDNc2syEZYlEO+1QQuuRkCAwEAAaNgMF4wCQYDVR0TBAIwADALBgNVHQ8E
+BAMCBeAwHQYDVR0OBBYEFD4E+/XklnqAWUXZrJa01AuHb6IbMCUGCCsGAQUFBwEO
+AQH/BBYwFAIBCjAPBggrBgEFBQcVAAQDZm9vMA0GCSqGSIb3DQEBCwUAA4ICAQCW
+nwXJetxx3Y82aBcyG9sQ5CTObsP1TyHRLVOKeA5jTwVxzSjQOChuUijLFbJ3QYds
+vP8h56rjn/hLSi7kdyh1s1+mDBRFWAdJCfRfQhQWvgK7eaphln7qUXUXa3JR66Um
+R56cXa6A4KG/Qk2vKw+NLjwA01vF+YzynSijwlaRptYLeOZMUMRzD8IwgqkdOAHr
+6+RgiRrRIfdZHYmMX3/7sTvzub/d4QfANjKYPVkciW3E71yeAOLOfjjK68u4OMhn
+F3I1vHdhCwxh87gZdiutmUjd+xTHhyIVObpSYIfSDCWqjp70s6sTJBdTCDnzIzcp
+ta/iI1EkyOH0aOSzz4bclcWAA2R95JeQDP8PLUA8gddvkbW4f9RJbWMjAk3r6WMM
+aSlx7djzbKdXIPd7ecFRWPf5uianNHlTHH2pZkHQoENCfuNTs688OzjBEDzUIvOZ
+S3WbVlqSzdf8Xp8xDp01QbC/bwFJwOeZjdj4IVyF2vXB2AaE5Xy/umQz1NVnIqK1
+CUyv/EP4HMbWIW5hpaMZJ4VyhrkoX4sLDj25UN1VAzD9lTyAGpMv5KpWd98MhYIX
+7KHP69Xo4CHf1RibdRVX6jW+GvzRZGHPb8/V8qgDwOM7UPjsPuwq5Cacatu0L7tQ
+hqtYGxcBDAIRIrmm5sZCW4F3l4efUtzozWZS0vzTyQ==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/proxy10-child-test.key b/third_party/heimdal/lib/hx509/data/proxy10-child-test.key
new file mode 100644
index 0000000..7bc4a02
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/proxy10-child-test.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQC6cPXDCC0XAM4h
+KSKJUA6MvpDlQcdMV8YyR5ehrr9rBZaNEFlPch2ZCXHFeUgRp9L28EwdbjG8BV/a
+qaBjohlTLgQap2vPPOZ/rgT9BxFbq8ZupFBj4cGpgO6b6x7iz9d8KjuxKlMttl7G
+GgxTPbaTet4rNPfG6te1vEX4ZBylvYecRKdMvaia1TY+ARnwHCGOKwQHesdO1AWo
+F0XW4pK9EMm0OVFJRuqBj5xgIVQx0gS2fh2N6wt0fvK3fiLmS6Q3pFqNcmNBNJAU
+Zx56Adow5xDumEi/uPfTlEUnrBoJcHBMKwGgg+0TbC32l+AW7zNtxZ6delrFH56f
++f/aBTsucrc52LKHd3T/xr7v2BbFdZuZdhXahhWX1nFJOpr7C/NhA1rDUE/KEbF3
+3lIAIk7Dxe5nXpkSpACsQfn0Dfo0p1xrc5iMB/zZ84R9F0geb8IP1IS/01FCmDN/
+MEVyaJoh0EmD5AknR42vjBmryxWnUEqWcOiwSrScnbLBEHdJ5NtSvPdXFHenOO01
+g7V8hdScGyjKZm1RioqI0tU/3pHJamXEXbTjMQw/fPHS8jHqkoyaxaK8RRHE12j8
+eKF6INocH3drD7n7amApA58iDSOPgKETUk3YU4oEMAWrn72skgO6FLQ2Tg+1jL/u
+fhGIgMqKpYM1zazIRliUQ77VBC65GQIDAQABAoICAA5i4wPeoKQSwtUaOHkB/W1s
+0v9tuPQyHbAJiDDIrCqU7s4Jwep4csI5UVcciawbGBNH7Yej1iCdBY1441Bs1Klv
+do+b9ZyzJVIa2nWv0u4Q7inhcfaTF/99XGwZk3OK+CSzmZGNI4f2d4+vuN2/eFQe
++f+5gZkOzABQ+9Ez4GYFnu42+fXY+Kah5yKXsSmu8gPnW9M77R8vCxSyXwg6yXnf
+TsEiXxxZZYUD0Nw2FioV+5kdWCh4R5UAqrfv+r9sfMpyWy5o8jG43ZlFb7uYYv69
+BbhzdcGdgzoHSeLKy+OIkpG+C80YAPYrtcw+YeNDJ+PDiP67zz9Atlu/zbdEChHk
+tazsDmDqv6ML07X4fPrkPi5PRMN0AXqDz94nXKEAh9fvgrW7c/jhakNgHWX039Ph
+5fGD09GjKUkzHr7zIZ5S6LrBrb9BLe8BiTfaZGqpSmRFEKxGwCr15k5w0Mzj/UpJ
+Ftcr78u9qthfooaGYGMXiMWZy1138TD/V6Kro/ajMUDhkmmXNuJghDBAQOhHUmcG
+Jldth0gwgyVzbQDpbEhI0ZOL4urGyNqylMmfGkN2uAfBfp0TnQT+7msru5BpNqnW
+RRAplCh47TpUJ871P7Tm5bSS4SjysfaFXiG0qQXFUSzaRFCYFkzMRoxHV1PBXr0X
+/ZmU8r9MtwRh8O+tXy6BAoIBAQDk04GAIlhDBpHmgCPWKTQ9GiYGhXsY9Wb2rbD5
+VaPdF46RW6mHDUJ+SMvNpwGZGfe59Yox1PJG1f8i7B+UCMZZFShttdBGuKRCH+aJ
+SIlkBmXK37ikAQREU+hmp0/mbMgq8Lspsjrxmlmi8rsLRKyHlAK3AUAoC2KqoohT
+dLEg3uY+5UzpkZQOfeK5/+DaKXjjkHE6dVkjQm0pNtXHJsMQMvcjfH1T6XCuwUKw
+zN8aOfvy/mFv5eOJazhAOZ3+QlUbOWh3EpBeEt7Sqqo7kQ5BZZKR+jDjWZETONya
+aYQetRHKnFlYWjewpyp+z7SDPNHcXqtK57+QRLXyrOuuQg1RAoIBAQDQlOs8TOht
+dJChYks2eiC5sQ8hC0ybMi+x7lJ8KALwPvf9VCKJIri2BxTvxkbC03YnUTsKlCm6
+7Jgkkx3Vy33FCXfaRhwLHaAuA+DwfzMn7WXtP4MJoKWyOJEck5HJzKWCqetdf7Dh
+ie/HsgtH2DHqljjhSleEYWVBcjoXVwWL2ctEcl3qr1JSpsRp+TadnIpoyDVWWszt
+xQwXpmVPs24svwI0x7p4Q2JzTAqd1oM+o2P48eFThXOobvRA+XGvucse0wWm3N+T
+4p1LbH07fguriOGqHea5ZPw7spURcP3CFEfUlsgiKUWjonuCvqjGGLV1U6RZ83FT
+S9o35O1Rut1JAoIBAEXL1dZVo4JeQKaEM2ohi1OP5EVc9Z05TTy04iRLYP4RL2Vb
+BiyxeLS4U6HY7P3cE9ne8VYd1ACTSY1HZKJswsNtVrWQHYVU0JVy0YjSXUXrRaVJ
+9DHiNYD57wtQwWhRigS/BPfE64HCSNERJMhdHBsGpIVZlk4gmundRaPfFiAmnShW
+HM2pn/WDpGKDj/w7ZipTZpYkMRo2KsHFfhOO2TTZttRWJowvyjUjscnn061WPmlx
++hp9jpfd4nyElpJ1fSweqKSZPvvS2bB8agxdRHHiH4DzRXIzYbLxRyi6QphzNogM
+hJwUeKQjeSzRAgh9xq1nGuxwH9hLfQwWfpTahOECggEAcBL0aswwP0/Yvr5gB3+L
+wfr/VBQML3/B3OtfatLc8VYEThw9Ck6bzUL03vk84EZbQDkHbmG6InQqM8zQxSW4
+CH1T5vaw7tAWV2NCJDdUt2l50QbFVBD7t01pu18XgMTzUcgXbX/E/QruyfBC23Gx
+MIlTOsqFR95FV+sWh5/8nO6Dp92D1SwrIbn147NCw2FvhWm+Lw5O+ptcKgEAgti4
+pFZlyxJegWxDpAwB0FmI38lPWF4vYn9ca+5iU980VOWR3Jgqe0RG5eFn/zTl/Wd2
+wc6k4pF6fbdjSHhmXJ7H2tam2fXCx4hBoPEXSGNFsFtqdQZiUurZw5YIROw/ECFF
+8QKCAQA8PV4eu8rzdw37cJnZOZRYg60PZ80c6LteqBnXwDp7HP7cAR11GUp1fous
+o4L1Od8aNUSVpfmmSOR28MuVhZ4wNbV/t+g9VzO4r2zuI/kkEeMstf85hXPLrkjL
+eo2HCu2xgM54vNVhG4MN2G5OWgMMkDDX3sPWeYN4Em428iYPHTgod2GaGQ9AnGI0
+wUGHhfGlP690xAvjQJLk0OvTrzKcjdPKrpUmCzIfT7ljfl2PE7l944C9aNvS9cEY
+iGkrbALi+EgfcfahEdEbQyIZU6GFDRltgnGtLeOE8NmqabQQgm0THXPjn/CzR3Os
+Qshwvh4gXup0rcomkC+d8vVJ2p35
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/proxy10-test.crt b/third_party/heimdal/lib/hx509/data/proxy10-test.crt
new file mode 100644
index 0000000..9c89f71
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/proxy10-test.crt
@@ -0,0 +1,30 @@
+-----BEGIN CERTIFICATE-----
+MIIFOTCCAyGgAwIBAgIJAKQmPUkmhyKjMA0GCSqGSIb3DQEBCwUAMCExCzAJBgNV
+BAYTAlNFMRIwEAYDVQQDDAlUZXN0IGNlcnQwIBcNMTkwMzIyMjIyNTE0WhgPMjUx
+ODExMjEyMjI1MTRaMDMxCzAJBgNVBAYTAlNFMRIwEAYDVQQDDAlUZXN0IGNlcnQx
+EDAOBgNVBAMMB3Byb3h5MTAwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC
+AQDNg69jn3h/uqasiOdUD/MC0vJoty8ncj9NNGfU7YHSLpRnuoyPL8YCRRbxreUP
+lIQ5oAP4ERJSrrRoGWuwiboLthVj6OgM1IrU3h9M2sM7fGdLuQ1QCDP0Bsu23MPJ
+KWMCUpd3p7jXrPaf1WzUtaIql0pjFFlqZRf1RLKvH4CfDgrx/k3z49RsiZtgxlw2
+VxpGL3cPUO1MfXEq4roMWdT0sGTdJ56l+PkF3Ud2DxhNytmDv1ld2gZhC5H+k5ZI
+i3Xr8zvV2dCbSlnnXk8qTG+aWwYGpHFQPwP7UxQDUAk1XAX5/EBXwCTtTDNIhsNI
+qB6k9MF3/mreD5frofvx6xEW8CShdAf2vUXC4OB8hkO/NfdaoQj99PL7d8LiICoQ
+u4fOZ20g6zpkS+jir5p3KcVbotN0cMkx+k2YwyK3PoLV74RTsigOjp828eoT24Wz
+3/ztjn4C0uMHcJz4yHmbrn7xOf7VcaNvfm9qz9H/MpA2Eg0Nj4nBOnTf25WLvgAB
+KN0Ctb6rNbF3UfVR9h+QK4kQqhlwjMfPqeT2AL0fOFptotcdPj86z2ux1cvC/w/x
+nZrgUdcj2GLLwvCxsmVx5RWOWU7wFoo3WrWpyx228CvaPTQXN5LKBIgpf1wmk4b1
+wR3afu0I5RQp8kSD/2kQBW24D4+AAH1jFbP9IfxxSXCazwIDAQABo2AwXjAJBgNV
+HRMEAjAAMAsGA1UdDwQEAwIF4DAdBgNVHQ4EFgQUiFCNi8YSDjclAz4L6ZPKi9Ea
+afQwJQYIKwYBBQUHAQ4BAf8EFjAUAgEKMA8GCCsGAQUFBxUABANmb28wDQYJKoZI
+hvcNAQELBQADggIBAKEy0OrFQkrc3ngQXWBhOEoLElCYIpM5sVDn3aV8i8UAQ9KB
+uLfxmcJm5CPZcIAFive2TWVFm1eq6Fr1WEwZ2QtAOXwoQwCzKISsdFRHEV2SNtpg
+uUaKlhGUwiYWt9aPkmJD4f/VZB7LeKE4CWij88ey+76Lujkr+ILZnrXnc2Mwf3J/
+x+/RfINh4oM+7rHccAJtznwZ2TCBvF3p5cLlLH413IGnZjO/myz/EMQ8MJoFNc1G
+dWXOZiGnbq2+W9rHKOV9rYhIZ5YLLiK6L7vKsLph83KTzWCZW7tZDAmwtFFXw406
+bdWL2+gWBC9SxN3RI2jB9VQtaLspOW+v8qH7cpDaO0xTXufsVjiGbh1hPdAMonQd
+k0rrrkLY6ADguTYkHs1E3Eebki6LvyyXBEKJYTtEHfJnU2T1YWwFpqvvFOghFljH
+QyZC29QR0rLB2B6uepQXl6d4fFYfYkhjx7SANDx4QA8QqrLgeGjufj9H3yk9e/XX
+lto6sjNsOOncP9svCxJgQkp4w7tQxqZ/51RBQAJkUDkwPImstxTIFRdqeXHxLynX
+3zTv6rt/767S7SlDfLZs8OrGKPeILGDBF/Q0UQrnrk9Oa+yP2QV3Msg79odKqBzK
+MfcQ4DFIfnN9ZRq7d0ffaZ6AqJVbwYM/LlGFAC57z2xsuEAR+Ea0/bjzbaib
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/proxy10-test.key b/third_party/heimdal/lib/hx509/data/proxy10-test.key
new file mode 100644
index 0000000..733c2ff
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/proxy10-test.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQDNg69jn3h/uqas
+iOdUD/MC0vJoty8ncj9NNGfU7YHSLpRnuoyPL8YCRRbxreUPlIQ5oAP4ERJSrrRo
+GWuwiboLthVj6OgM1IrU3h9M2sM7fGdLuQ1QCDP0Bsu23MPJKWMCUpd3p7jXrPaf
+1WzUtaIql0pjFFlqZRf1RLKvH4CfDgrx/k3z49RsiZtgxlw2VxpGL3cPUO1MfXEq
+4roMWdT0sGTdJ56l+PkF3Ud2DxhNytmDv1ld2gZhC5H+k5ZIi3Xr8zvV2dCbSlnn
+Xk8qTG+aWwYGpHFQPwP7UxQDUAk1XAX5/EBXwCTtTDNIhsNIqB6k9MF3/mreD5fr
+ofvx6xEW8CShdAf2vUXC4OB8hkO/NfdaoQj99PL7d8LiICoQu4fOZ20g6zpkS+ji
+r5p3KcVbotN0cMkx+k2YwyK3PoLV74RTsigOjp828eoT24Wz3/ztjn4C0uMHcJz4
+yHmbrn7xOf7VcaNvfm9qz9H/MpA2Eg0Nj4nBOnTf25WLvgABKN0Ctb6rNbF3UfVR
+9h+QK4kQqhlwjMfPqeT2AL0fOFptotcdPj86z2ux1cvC/w/xnZrgUdcj2GLLwvCx
+smVx5RWOWU7wFoo3WrWpyx228CvaPTQXN5LKBIgpf1wmk4b1wR3afu0I5RQp8kSD
+/2kQBW24D4+AAH1jFbP9IfxxSXCazwIDAQABAoICAAXV+HQGwkA2R6dcl90OOuNY
+pCOPGBqxptSFaXFlcStLwVEUvgsO2zuTRKyGOJvxprOQNKylp3SLm3ndRu6TaqIM
+gJz+ryA2JN8Yk6D2EVcuGCzRS2x7XyZNzxkZOcILl9EoET8HlzsgoTw2rkl4Auvc
+sfMQT92ykzSWx9ArP9bEalEm3IXRcWXHno7n8xRj8s4NaP8ZWDO02DLUj13saxyr
+qaGSD3I9GK0u9GmI0jLbUMPp+hqtJ0M4NeQZwsm6lBWoKYnQDplqShVE21CjLQQg
+E5K6trEFqRJI8KeLbUeDnnPT0uvq++F1KXukwATfKUeb36aNpfE6ViENz362Ix0L
+lDqWU6gSOPBOO0hD/LLSzGJY/61MrIy4P8S3gS2u40jm8YaW45Bed72pTGwkyz7Z
+9c3YbSJYWNg+o18yI7z4JVlJkptMsq3KJwj7BXIAgFT+uIteCbf7UXCNdsUzSiE8
+k2JxiNKlaaw7xnQvGuwFdDB+uCQC3PGngmDU222mq1Twm8rMHAgjt6RMO3tv42H3
+Fsap/MIDiVUQfYrTHoN2FVG852CzVbnGxPaxDJYS/vfVmSFcMeW91lbQM9J88721
+gG7hs55IrBvEse7U21EtlLISf3HYpLnMlHqH4S61VuKKS9Tmx67llfi6HMKupG27
+NfDFfoLiQCFltTCBcrHxAoIBAQD1YhrgDXmOiVCFuSdiu3k063+2pC/r4uUSo9QZ
+zPAMq9XIgXdGJoWCcQ1kg+/qEvhBxBbzywoU5zJQluu3V33JrT1Y2tNzyPaLNIpb
+aFYUP27/yC1xOyD5bcYvaVV612pVuORzN8PRShbpTyfSDhGxx8/KxXBg6iN0Adk/
+Rk1rzgl9UH0WLy7hS5hecroX/bfqlKWLjfWEtsDo+dyA/HoL6ku0YDuQvJvzZrDB
+gQfDo+FewaL+idZC2Bx61f36h93dlggeJgC4sOHh/j/AXkMaKEHFRvM0SLOE1lrm
+RyT3kdhCUoX799+Ke/BxcjfPwY1GKxsVWaiwbFUAwFcWYyPJAoIBAQDWZ/zw75El
+PjsrwIGr3BLmmyxMeJKPniIdhdEvgj4/2jY3ao7DdRcLe2RZy6J0vdrA2XfeQDdf
+zX03T23Ha0uCGXgqRUUa1wKFrzDnXTD1YAXFqQc8XXozTyEkF7+oz3wQnqpMhK6I
+X5CAwmZc6s7mObF4MiBKWQFlyL+rHybc+ZFe2LvS6UgP2btCsWvUJ1xCgwnnCA4a
+Q/8ximehCSJqYrt/icOVSdNf4rzzgzQxCObvplw3E/stRgahQcYSI61JN9Ja0ONe
+bCpuUpDNShPrE5W6uDB9ogfjX9BN9Zbwq4bR8WwhBGZLDS0Peqfe20yJ4mbsEEez
+9mgvvEeBtaXXAoIBAHPTnin6UlGUwXyNnGi/Y4Q2UW+N6szmqgh1ao3PLdRdXCkr
+63gigMzEvnSezqVn1OV+QPNM+PJK+3YM9zDwzIBhFN8XU86Ios+suk5RXqhqFOQJ
+wmF7bqIuTeldSCsW+auC/drhDL6CwXPZmEtPtsx7K7tkHRqyCpAcu0Zh0fO8KsCL
+OLA7D17rRv32G59tdN320nmgRa8icMbIAmykQJvVOWzoK9WzIc3vwClm1ZpkheIr
+dtu9hnTA/BiDYEJc1b5drnFEsPx9CfKaB8+u7u+u5vTO+8fHNW3TnM6r8Ggn4LPV
+rkb0hwEgZau3JV8c1qmzeTJHwxeb2zfiknkPzPkCggEAMsEnFXoAqApVQ4QsrhxI
+tSJimC+qsijC9q4o2NBCICdt0ix9YzOiousw1DjqWixfTmusfoZBFYK1c5Rv7lct
+5rxUv9zqAPKI/FB+iSZ8Ynm6pBHhTp7qQJ8ovzyH+FQ1kFGfCsIV9t54fKKITNKg
+68sYgdWL402ykP+2r7GOJ51ElmlD/SeQEYB/XchWOEChDHWssG4tuHYEQRv8cBiT
+dw+sRwK7s+loCjjIdfTHNBxhXrXI+pjWSt9azm2dj8m2SbDXMPxl9oIwgTE2agJx
+OKLIPQ1BHVxv9ZlG3E2Yz5wrLCO0bxR1iqqx0go9Fvpe4f0gVB1+e9GG1FYDr2bq
+vQKCAQEA5HDb2Va1e9QkK8mvTKcWad9czLwNXKdvWanv2j2+VJTmjWG0KuzNsoQQ
+5ZUpUQ1XFpC8aYaJRuWVsXShZ69E3RHGrH9jtYQ36mf+Aao0oMW4FoJ+szAHoN2K
+8f4PES5TcK7wlQafq61Tkgsrr8KT6UbNWr7F97UgcPKI0HVs6yEJ/hY3HExaBxug
+VHLUSTOPIx3Sey47wR9I6XvbESSVLh27cy/GIDBOI4OEQTN6bg3t/7Pf7o4agan+
+r41oGtzuhX2CXbiqEaynU1wOrSjBshO29Cm++5MBnqiGUA7UCv5BHX/vU0ECKEW8
+M4C7UTY7JIl5vsDk5aoxq4Rt6pBkQQ==
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/revoke.crt b/third_party/heimdal/lib/hx509/data/revoke.crt
new file mode 100644
index 0000000..ded2325
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/revoke.crt
@@ -0,0 +1,116 @@
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 3 (0x3)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: CN=hx509 Test Root CA, C=SE
+ Validity
+ Not Before: Mar 22 22:25:03 2019 GMT
+ Not After : Nov 21 22:25:03 2518 GMT
+ Subject: C=SE, CN=Revoke cert
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:ce:ac:a3:c6:69:47:c4:dd:f4:d9:0e:ac:42:90:
+ ae:57:f2:68:c4:77:89:9a:65:cd:8f:97:fc:68:6b:
+ 6b:65:0f:52:2d:d1:db:83:2c:1e:39:35:dd:fb:f6:
+ e8:c1:40:e9:ab:a6:48:23:e9:f0:e1:8f:72:27:6c:
+ e2:8d:04:e9:ca:e3:fe:ac:d9:28:16:be:db:19:fc:
+ 9a:20:d6:93:1f:15:b8:b6:97:cf:07:5a:da:ab:aa:
+ 97:c0:e9:39:7d:f9:df:96:c9:99:8f:6f:51:3f:64:
+ 13:0e:ad:0e:4e:2e:66:6f:72:6f:63:a6:a5:fd:85:
+ 0f:ac:ea:03:4d:81:14:bc:f3:5b:e5:fc:f6:6a:f7:
+ 57:b3:c3:b0:ed:4b:43:b1:cf:e2:1f:f6:44:07:83:
+ 27:b8:ef:19:9f:35:2b:95:59:b9:e1:69:c5:19:07:
+ 06:d7:17:da:35:4b:ba:74:68:c3:d3:28:ab:1e:b4:
+ 8a:ba:2b:f3:5e:06:75:0c:c8:a2:a9:ea:ec:29:1a:
+ 98:fb:b6:00:e0:98:78:cf:ea:36:2c:e1:51:8e:15:
+ 74:ba:4e:2d:8c:df:9b:72:72:52:b7:c7:82:45:35:
+ ba:c3:62:bf:29:d0:c0:17:6b:be:3b:e4:87:6a:26:
+ 34:4f:84:b5:ad:34:72:5f:4c:96:d8:d4:cd:5d:6f:
+ a3:ac:b1:55:a8:c8:c6:5d:99:0b:f0:bd:5e:f2:85:
+ 3e:74:05:d7:0f:9f:95:5a:14:1f:19:31:af:55:75:
+ 2a:80:22:7b:f7:ff:89:4b:70:5a:74:52:77:7a:ac:
+ 6b:86:2d:cc:5e:ca:57:3d:a1:20:d0:95:80:0b:48:
+ 26:52:69:9d:19:7f:0e:a9:63:97:70:b6:25:64:79:
+ ae:19:45:f8:7f:fd:23:75:9b:0f:d5:57:ae:56:50:
+ 9a:0c:fd:eb:f2:1b:a9:0a:3d:a2:1d:f3:07:cd:b9:
+ 63:5b:3d:95:21:9a:f6:27:2e:46:6a:3f:8f:48:b9:
+ e5:d7:ef:27:08:fc:45:37:70:23:88:a2:89:50:7e:
+ a3:ba:06:b3:b9:50:60:7d:aa:d6:eb:1c:b9:79:1c:
+ 16:06:d2:07:d3:c6:09:73:2a:8a:92:10:93:cc:52:
+ b4:bf:4b:09:d6:71:c1:60:57:3e:2f:12:13:90:18:
+ 06:44:cf:79:6f:50:78:11:8c:e9:ab:2b:97:19:5f:
+ b2:67:a9:fa:9b:b0:99:44:35:0e:00:18:6f:9a:00:
+ 39:e2:ac:e2:79:25:e1:46:d2:18:e4:80:d5:ca:ed:
+ 15:dc:7f:a7:90:7f:26:71:26:38:6b:ef:be:92:0c:
+ 07:64:24:64:a7:85:9d:2b:d9:14:bc:64:40:46:eb:
+ 78:b9:dd
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints:
+ CA:FALSE
+ X509v3 Key Usage:
+ Digital Signature, Non Repudiation, Key Encipherment
+ X509v3 Subject Key Identifier:
+ 3B:AC:F2:D9:72:19:FF:77:61:0C:6B:2C:C0:69:D0:28:46:8A:C1:D7
+ Signature Algorithm: sha1WithRSAEncryption
+ 23:5d:75:da:82:54:6a:eb:29:cf:e0:55:da:4e:69:c3:d1:7b:
+ 27:20:37:ca:3e:ac:ba:55:30:0d:a6:57:44:de:1b:71:aa:57:
+ 80:8d:55:e1:48:fb:43:dc:23:d3:fd:85:ab:36:35:11:1d:41:
+ 30:59:ff:e4:61:e1:4d:14:8b:64:9e:cc:a0:71:19:a3:a9:10:
+ 84:47:72:dd:2b:56:5e:78:a9:ed:f1:32:8b:b4:5b:87:aa:bd:
+ 74:4f:ee:50:ba:36:d5:70:56:40:7d:64:d6:04:42:ae:50:2b:
+ 95:48:f5:74:8b:a6:b5:5c:49:9d:9c:f1:0c:0f:0a:f1:53:43:
+ ec:1f:59:6f:1e:54:ca:9d:b2:39:73:58:28:b7:0b:74:e3:ed:
+ d4:36:ef:7d:1d:c6:1f:2c:ff:a7:df:a2:a7:9e:94:b9:3f:3d:
+ 18:fa:07:d6:e9:03:f6:3a:d1:79:55:df:af:12:13:ef:45:af:
+ 63:57:fc:ef:db:5c:bd:e7:93:b5:81:35:e9:a9:e4:39:99:b9:
+ 32:7b:6f:1a:14:41:3a:fa:68:3c:0a:ae:9e:95:51:72:32:dc:
+ d6:e9:98:7d:65:db:ce:57:1f:1a:e5:2a:5a:c0:07:26:64:f0:
+ 49:ff:af:97:74:fe:98:20:94:7f:f7:3c:a7:46:ed:ad:e5:1b:
+ 7a:08:c4:d4:ce:3f:8a:ef:07:79:ec:d5:f1:1b:2b:f6:e0:95:
+ 31:ef:8e:bd:b8:ec:a7:84:f8:ff:c6:39:7a:15:8d:4b:4e:05:
+ c8:e6:2e:bb:bb:74:5a:51:92:f7:b1:04:55:2b:dc:42:18:d5:
+ 83:95:c4:d0:73:10:62:d5:55:8d:ea:a0:fd:ff:ef:10:9b:8f:
+ b3:ba:8a:91:75:5e:b9:9d:36:7d:53:5d:8d:1b:0d:c5:bb:1c:
+ 23:fc:08:5b:1f:3a:d5:1c:35:61:48:58:8e:c0:42:7c:3c:c8:
+ a0:17:8a:04:13:a6:03:49:cf:86:18:39:32:e4:fe:32:38:bd:
+ 53:bd:49:fa:65:63:3d:41:6a:c7:65:f5:df:7d:7b:8d:d0:74:
+ b2:c3:8b:bd:1e:4f:96:15:a0:7b:23:fe:81:e0:de:7f:06:b3:
+ f8:a2:52:cf:43:91:49:6f:ae:d8:6f:4f:51:85:7b:c2:f7:f8:
+ c8:4d:e0:a8:48:9a:5b:05:e2:60:fd:b7:bb:b7:7a:2b:35:e6:
+ 15:f3:e8:5f:b6:cb:d5:b0:7b:45:70:db:fe:82:97:c5:6b:be:
+ a9:60:21:87:19:b6:91:32:2f:01:b3:04:84:a3:1d:8b:06:00:
+ 3e:37:f4:c3:ff:b4:55:cb:cc:d1:d1:96:9b:d8:1a:0b:9f:47:
+ 66:b7:90:9c:d1:09:c2:aa
+-----BEGIN CERTIFICATE-----
+MIIFAzCCAuugAwIBAgIBAzANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw
+OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMCAXDTE5MDMyMjIyMjUwM1oYDzI1
+MTgxMTIxMjIyNTAzWjAjMQswCQYDVQQGEwJTRTEUMBIGA1UEAwwLUmV2b2tlIGNl
+cnQwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDOrKPGaUfE3fTZDqxC
+kK5X8mjEd4maZc2Pl/xoa2tlD1It0duDLB45Nd379ujBQOmrpkgj6fDhj3InbOKN
+BOnK4/6s2SgWvtsZ/Jog1pMfFbi2l88HWtqrqpfA6Tl9+d+WyZmPb1E/ZBMOrQ5O
+LmZvcm9jpqX9hQ+s6gNNgRS881vl/PZq91ezw7DtS0Oxz+If9kQHgye47xmfNSuV
+WbnhacUZBwbXF9o1S7p0aMPTKKsetIq6K/NeBnUMyKKp6uwpGpj7tgDgmHjP6jYs
+4VGOFXS6Ti2M35tyclK3x4JFNbrDYr8p0MAXa7475IdqJjRPhLWtNHJfTJbY1M1d
+b6OssVWoyMZdmQvwvV7yhT50BdcPn5VaFB8ZMa9VdSqAInv3/4lLcFp0Und6rGuG
+Lcxeylc9oSDQlYALSCZSaZ0Zfw6pY5dwtiVkea4ZRfh//SN1mw/VV65WUJoM/evy
+G6kKPaId8wfNuWNbPZUhmvYnLkZqP49IueXX7ycI/EU3cCOIoolQfqO6BrO5UGB9
+qtbrHLl5HBYG0gfTxglzKoqSEJPMUrS/SwnWccFgVz4vEhOQGAZEz3lvUHgRjOmr
+K5cZX7JnqfqbsJlENQ4AGG+aADnirOJ5JeFG0hjkgNXK7RXcf6eQfyZxJjhr776S
+DAdkJGSnhZ0r2RS8ZEBG63i53QIDAQABozkwNzAJBgNVHRMEAjAAMAsGA1UdDwQE
+AwIF4DAdBgNVHQ4EFgQUO6zy2XIZ/3dhDGsswGnQKEaKwdcwDQYJKoZIhvcNAQEF
+BQADggIBACNdddqCVGrrKc/gVdpOacPReycgN8o+rLpVMA2mV0TeG3GqV4CNVeFI
++0PcI9P9has2NREdQTBZ/+Rh4U0Ui2SezKBxGaOpEIRHct0rVl54qe3xMou0W4eq
+vXRP7lC6NtVwVkB9ZNYEQq5QK5VI9XSLprVcSZ2c8QwPCvFTQ+wfWW8eVMqdsjlz
+WCi3C3Tj7dQ2730dxh8s/6ffoqeelLk/PRj6B9bpA/Y60XlV368SE+9Fr2NX/O/b
+XL3nk7WBNemp5DmZuTJ7bxoUQTr6aDwKrp6VUXIy3NbpmH1l285XHxrlKlrAByZk
+8En/r5d0/pgglH/3PKdG7a3lG3oIxNTOP4rvB3ns1fEbK/bglTHvjr247KeE+P/G
+OXoVjUtOBcjmLru7dFpRkvexBFUr3EIY1YOVxNBzEGLVVY3qoP3/7xCbj7O6ipF1
+XrmdNn1TXY0bDcW7HCP8CFsfOtUcNWFIWI7AQnw8yKAXigQTpgNJz4YYOTLk/jI4
+vVO9SfplYz1Basdl9d99e43QdLLDi70eT5YVoHsj/oHg3n8Gs/iiUs9DkUlvrthv
+T1GFe8L3+MhN4KhImlsF4mD9t7u3eis15hXz6F+2y9Wwe0Vw2/6Cl8VrvqlgIYcZ
+tpEyLwGzBISjHYsGAD439MP/tFXLzNHRlpvYGgufR2a3kJzRCcKq
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/revoke.key b/third_party/heimdal/lib/hx509/data/revoke.key
new file mode 100644
index 0000000..d70b74f
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/revoke.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDOrKPGaUfE3fTZ
+DqxCkK5X8mjEd4maZc2Pl/xoa2tlD1It0duDLB45Nd379ujBQOmrpkgj6fDhj3In
+bOKNBOnK4/6s2SgWvtsZ/Jog1pMfFbi2l88HWtqrqpfA6Tl9+d+WyZmPb1E/ZBMO
+rQ5OLmZvcm9jpqX9hQ+s6gNNgRS881vl/PZq91ezw7DtS0Oxz+If9kQHgye47xmf
+NSuVWbnhacUZBwbXF9o1S7p0aMPTKKsetIq6K/NeBnUMyKKp6uwpGpj7tgDgmHjP
+6jYs4VGOFXS6Ti2M35tyclK3x4JFNbrDYr8p0MAXa7475IdqJjRPhLWtNHJfTJbY
+1M1db6OssVWoyMZdmQvwvV7yhT50BdcPn5VaFB8ZMa9VdSqAInv3/4lLcFp0Und6
+rGuGLcxeylc9oSDQlYALSCZSaZ0Zfw6pY5dwtiVkea4ZRfh//SN1mw/VV65WUJoM
+/evyG6kKPaId8wfNuWNbPZUhmvYnLkZqP49IueXX7ycI/EU3cCOIoolQfqO6BrO5
+UGB9qtbrHLl5HBYG0gfTxglzKoqSEJPMUrS/SwnWccFgVz4vEhOQGAZEz3lvUHgR
+jOmrK5cZX7JnqfqbsJlENQ4AGG+aADnirOJ5JeFG0hjkgNXK7RXcf6eQfyZxJjhr
+776SDAdkJGSnhZ0r2RS8ZEBG63i53QIDAQABAoICAQCH6WxCXJW/1x7fZxDNLYwZ
+deaD3QB2sp/94DszCAE2El8+lpU+q9KsWMpEmljyTZfdM5qZU4z/KHAvkSFjD2oX
+7NtcG+qLGrPHYSCSm8lgVc6E9UxGT+8hmSv2xujx+VKaPLVpaBEMGOmXayLPMyBW
+BfFOnRbno4ttcO7/FvXmVDuJAVOjgEkChJxjUG2SD11rG24dapjCuyokUrj4nGrq
+272r+bz70knDZquVRhgRUttFdAEO8Tw4BxMOdxrRlxX66ezVCxmEmYBJaoJ5/Sq+
+v0lmA2ddDueQ2bGf/emjTfQl7Vg9TXQlcstFY8HRgpJAAMvgvW7BUQKaUUdEPNhq
+177x6a450fc3oN7sC/gOFXrx0bPmwJMa1gDGIAkdzB6p1R2aeM0WwFPny0iflgf9
+3oNFdA/zvK8eCSiY3TbD/F3qyzdw0j7lRW3BSYn9XWS0FJHQTXYb4H8rjFkcHMHp
+Zg7rv8C7H/vS2eCdS6j/7UhJnXLapodmxwLkcpsuilMUT9IjcdMHCqRyuEQT8vtZ
+u4Dl9nf9Rw4SMVeCwkEWFmMQUdNDSo4CO2Yyo2Qv4kEh307lFuX5icDFdbY0ODbD
+qrBaWKVkSDNKRrzwBu6dwrW5X/zTHNCi+i8nJNCUysm/Pue98x1pHzkKcE0tbSQf
+uaT+qSeTR5/iVsmgmNlbAQKCAQEA8g2YTH9SgCXoaanghvbgk4Q5uimEFdEaza6H
+XWEgC7PQDehBoJCwBhuMtSj237uU6XB8Q9o1fV1Lv0Y9Xl6Ht9QlAI5p05jXM7a8
+/e9qIg1ZJy0eUmC+ICCdW8UbWnEyb8JAGucRJ4xHSc4QIbE0uYvKlt6n/AidEYiU
+zasNUANEdT7BL0EY5XheQ8IIloI8/olz02WxJtyCnvVkfHszXaB9+l/zEQhYXBIy
+oo+PLkd0rApB/JDnive1rlwG40eLp5CvlA0uATX6ZKWOGY0UhDbQfuBwzqOoCiXf
+0qmmUk3dCAJeRSQcY8zcVn8u8qq9z56IFcaWBHKfPPnDG4kBPQKCAQEA2pUw1KnE
+rxcKHs2Giqz4edx35gddaNgvKbX1/iFrFRqjctmf74KVx7E9CAs30UUMgohVhccl
+xsbvn3SLkiGKKxp+cK8Sciq2O7g9AXwsKHWzMG6hl/tXjBYAQx7XSkbDYgDJdE9i
+PhfUkBi2PAPJzSBGT9BJiPNm5uxCLrkj+YG5qe64fG5ZiBdQ2iLz3ggrWcwUBM6t
+a1SaqDbysTiUStoUr8URbZeveRS0NmTUt5YNhQvkYHyWRD8JNMSKBoCMCRrhykEI
+oA2tzptesQs92kUrl7C7XHUczFULGH/KrXD9RAVxLFC8rlqiU0PwUEYDbGYVd/+R
+f8q+TOAjNsTlIQKCAQEA6CEFh4crFV5FTt/tRUGJCa9qtQ+PbmTEcbAIfRLh6pcc
+1dmA5n0bciAFhs6sQs/f9Sc85M1lMr7AH8U6oT/CpBa9DZWGA7i12RBMmrJ5dAKd
+Fyb7x0Cj1KeygQm8O7YHCoqdc69ZEjZDP5Jwgf8xcyeOt7T8IIYaK3ByU/LQp4Ua
+p93w4mJpf9c5f32bQsvPtsMW4wrJI12hntPy9DYqgoWhivVtY04/frys9pz6UQWR
+7FNCCPbmNq1r/LSgnmJEmgP1feRN1Ddx1Ae5COP1Yv42YRbY2DK2ulSsG5k6uf+W
+E1JCGciRuVwDiqgZ2/rGYU/FbiyuPcG22IEmDUgMeQKCAQB4sWY8Ft2WfFdHON7w
+VaAB0b2Wkzx9ttkb4/BHeXZiOcpEkWvhWS6RDAmSFnekosbMkLEAZD00rAYF+tlS
+QBjFwiRM3i6GQZVMFmgBGOpdENh3hq7Nd6gYntFYPoBL8BTUWXDjOy4Y8Rma0zpU
+mxbjn82TJoRkDVolahEFMY9uprW44iqV8myXW6B2QlR7pfEh7TCkkuZo3FdlSKnr
+Nz2SsyY3A86iv93RMqBrZHOcR0uBylY4/LIQTuora9Z2zqYEJQbFofE8RzFQYrP/
+eCCYFBeE874QyE21ecPdrDpiWIBP/d1GxfHZKAx3g4z/Fhmv0hJKpyBU+sLnOd/X
+zxJhAoIBAA1EoDaxl2E8VYtFEb/PSdXI2n1OJJ5Vo5M6ChEtkU1tc3j0GkibRzKH
+y4MpFTUYKUaAr0TYil9aZSasCLC3IpHZtTW//QcqalO76Xv/ZTDXIEDq5KIQ0/H6
+3K0cwUl6VzKgwtK+wkqR/vdQnB3uhJgHrYQQ2/9vkpcAJmeYx7Pfjor9hpivloCD
+iRhpPjE4H4yiG+85/dRZaZ21X59FKoBleVown6ZYI4Z5BKHEULesTl/kqWXvsHpu
+RD4yQ+gR2yKNYmpZ10pqZ+0EYZWf6iqrFZCWJ7pvMO0hMye17yC5QD4qMqJCtJZL
+oSgi/Llzrh+HYp+WubHP32IPhXGX+w0=
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/secp256r1TestCA.cert.pem b/third_party/heimdal/lib/hx509/data/secp256r1TestCA.cert.pem
new file mode 100644
index 0000000..3522b09
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/secp256r1TestCA.cert.pem
@@ -0,0 +1,12 @@
+-----BEGIN CERTIFICATE-----
+MIIBuTCCAWCgAwIBAgIBATAKBggqhkjOPQQDAjA2MQswCQYDVQQGEwJTRTEQMA4G
+A1UECgwHSGVpbWRhbDEVMBMGA1UEAwwMQ0Egc2VjcDI1NnIxMCAXDTE5MDMyMjIy
+MjUyNVoYDzI1MTgxMTIxMjIyNTI1WjA2MQswCQYDVQQGEwJTRTEQMA4GA1UECgwH
+SGVpbWRhbDEVMBMGA1UEAwwMQ0Egc2VjcDI1NnIxMFkwEwYHKoZIzj0CAQYIKoZI
+zj0DAQcDQgAE5SuFK+KhglopQr1aMjl4ZEBaw4HYM2yVORyBOQWx3e8Pj90bFocE
+4gyS4P2V0YraxACsQgMp+s4e8/6gXPeMtqNdMFswHQYDVR0OBBYEFOtR3wCoaF9m
+8dWylzOdd5vfbwmDMB8GA1UdIwQYMBaAFOtR3wCoaF9m8dWylzOdd5vfbwmDMAwG
+A1UdEwQFMAMBAf8wCwYDVR0PBAQDAgEGMAoGCCqGSM49BAMCA0cAMEQCIF/JTbEv
+iuYcuREFzWgZ/AgfLe2sRwEgSy6UcAWOYllkAiApMzA3xKjaX1/hhkDGKZnHfcTM
+tRuM0FuTdO+e15ku8w==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/secp256r1TestCA.key.pem b/third_party/heimdal/lib/hx509/data/secp256r1TestCA.key.pem
new file mode 100644
index 0000000..3888266
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/secp256r1TestCA.key.pem
@@ -0,0 +1,5 @@
+-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgL2N0gdHhAjBGcJ40
+gHePPMwGKygIVDXTfjysn9zPiSOhRANCAATlK4Ur4qGCWilCvVoyOXhkQFrDgdgz
+bJU5HIE5BbHd7w+P3RsWhwTiDJLg/ZXRitrEAKxCAyn6zh7z/qBc94y2
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/secp256r1TestCA.pem b/third_party/heimdal/lib/hx509/data/secp256r1TestCA.pem
new file mode 100644
index 0000000..9b1df2c
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/secp256r1TestCA.pem
@@ -0,0 +1,17 @@
+-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgL2N0gdHhAjBGcJ40
+gHePPMwGKygIVDXTfjysn9zPiSOhRANCAATlK4Ur4qGCWilCvVoyOXhkQFrDgdgz
+bJU5HIE5BbHd7w+P3RsWhwTiDJLg/ZXRitrEAKxCAyn6zh7z/qBc94y2
+-----END PRIVATE KEY-----
+-----BEGIN CERTIFICATE-----
+MIIBuTCCAWCgAwIBAgIBATAKBggqhkjOPQQDAjA2MQswCQYDVQQGEwJTRTEQMA4G
+A1UECgwHSGVpbWRhbDEVMBMGA1UEAwwMQ0Egc2VjcDI1NnIxMCAXDTE5MDMyMjIy
+MjUyNVoYDzI1MTgxMTIxMjIyNTI1WjA2MQswCQYDVQQGEwJTRTEQMA4GA1UECgwH
+SGVpbWRhbDEVMBMGA1UEAwwMQ0Egc2VjcDI1NnIxMFkwEwYHKoZIzj0CAQYIKoZI
+zj0DAQcDQgAE5SuFK+KhglopQr1aMjl4ZEBaw4HYM2yVORyBOQWx3e8Pj90bFocE
+4gyS4P2V0YraxACsQgMp+s4e8/6gXPeMtqNdMFswHQYDVR0OBBYEFOtR3wCoaF9m
+8dWylzOdd5vfbwmDMB8GA1UdIwQYMBaAFOtR3wCoaF9m8dWylzOdd5vfbwmDMAwG
+A1UdEwQFMAMBAf8wCwYDVR0PBAQDAgEGMAoGCCqGSM49BAMCA0cAMEQCIF/JTbEv
+iuYcuREFzWgZ/AgfLe2sRwEgSy6UcAWOYllkAiApMzA3xKjaX1/hhkDGKZnHfcTM
+tRuM0FuTdO+e15ku8w==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/secp256r2TestClient.cert.pem b/third_party/heimdal/lib/hx509/data/secp256r2TestClient.cert.pem
new file mode 100644
index 0000000..5763c5a
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/secp256r2TestClient.cert.pem
@@ -0,0 +1,12 @@
+-----BEGIN CERTIFICATE-----
+MIIBsDCCAVegAwIBAgIBAjAKBggqhkjOPQQDAjA2MQswCQYDVQQGEwJTRTEQMA4G
+A1UECgwHSGVpbWRhbDEVMBMGA1UEAwwMQ0Egc2VjcDI1NnIxMCAXDTE5MDMyMjIy
+MjUyNVoYDzI1MTgxMTIxMjIyNTI1WjAwMQswCQYDVQQGEwJTRTEQMA4GA1UECgwH
+SGVpbWRhbDEPMA0GA1UEAwwGQ2xpZW50MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcD
+QgAE7v8wIgEd/yBAtDmW2nW7II4IDDy7KVlnv6/+sHegoe4AjIvqr9CNldkfcVHl
+VwjMA1q83lIB/H0IUmk+T6lQhKNaMFgwHQYDVR0OBBYEFKNeDhfd+znE5CBO6aNl
+DAUjXdF6MB8GA1UdIwQYMBaAFOtR3wCoaF9m8dWylzOdd5vfbwmDMAkGA1UdEwQC
+MAAwCwYDVR0PBAQDAgSwMAoGCCqGSM49BAMCA0cAMEQCIBVFIAeFxXeB4LURDxv/
+YnGzJJK0b+pjK5hVEPYww8dzAiAmHrccM21Ga7S+/yFWIvMe3BKtAl0O62TTI2Fg
+CHiIWQ==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/secp256r2TestClient.key.pem b/third_party/heimdal/lib/hx509/data/secp256r2TestClient.key.pem
new file mode 100644
index 0000000..36c67f9
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/secp256r2TestClient.key.pem
@@ -0,0 +1,5 @@
+-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg6oD5CbNzN7oAWqcq
+dKJKw2WU5EwnUV05+7S9gXgeW/qhRANCAATu/zAiAR3/IEC0OZbadbsgjggMPLsp
+WWe/r/6wd6Ch7gCMi+qv0I2V2R9xUeVXCMwDWrzeUgH8fQhSaT5PqVCE
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/secp256r2TestClient.pem b/third_party/heimdal/lib/hx509/data/secp256r2TestClient.pem
new file mode 100644
index 0000000..9f49adc
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/secp256r2TestClient.pem
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIIBsDCCAVegAwIBAgIBAjAKBggqhkjOPQQDAjA2MQswCQYDVQQGEwJTRTEQMA4G
+A1UECgwHSGVpbWRhbDEVMBMGA1UEAwwMQ0Egc2VjcDI1NnIxMCAXDTE5MDMyMjIy
+MjUyNVoYDzI1MTgxMTIxMjIyNTI1WjAwMQswCQYDVQQGEwJTRTEQMA4GA1UECgwH
+SGVpbWRhbDEPMA0GA1UEAwwGQ2xpZW50MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcD
+QgAE7v8wIgEd/yBAtDmW2nW7II4IDDy7KVlnv6/+sHegoe4AjIvqr9CNldkfcVHl
+VwjMA1q83lIB/H0IUmk+T6lQhKNaMFgwHQYDVR0OBBYEFKNeDhfd+znE5CBO6aNl
+DAUjXdF6MB8GA1UdIwQYMBaAFOtR3wCoaF9m8dWylzOdd5vfbwmDMAkGA1UdEwQC
+MAAwCwYDVR0PBAQDAgSwMAoGCCqGSM49BAMCA0cAMEQCIBVFIAeFxXeB4LURDxv/
+YnGzJJK0b+pjK5hVEPYww8dzAiAmHrccM21Ga7S+/yFWIvMe3BKtAl0O62TTI2Fg
+CHiIWQ==
+-----END CERTIFICATE-----
+-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg6oD5CbNzN7oAWqcq
+dKJKw2WU5EwnUV05+7S9gXgeW/qhRANCAATu/zAiAR3/IEC0OZbadbsgjggMPLsp
+WWe/r/6wd6Ch7gCMi+qv0I2V2R9xUeVXCMwDWrzeUgH8fQhSaT5PqVCE
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/secp256r2TestServer.cert.pem b/third_party/heimdal/lib/hx509/data/secp256r2TestServer.cert.pem
new file mode 100644
index 0000000..71935b8
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/secp256r2TestServer.cert.pem
@@ -0,0 +1,12 @@
+-----BEGIN CERTIFICATE-----
+MIIBsDCCAVegAwIBAgIBAjAKBggqhkjOPQQDAjA2MQswCQYDVQQGEwJTRTEQMA4G
+A1UECgwHSGVpbWRhbDEVMBMGA1UEAwwMQ0Egc2VjcDI1NnIxMCAXDTE5MDMyMjIy
+MjUyNVoYDzI1MTgxMTIxMjIyNTI1WjAwMQswCQYDVQQGEwJTRTEQMA4GA1UECgwH
+SGVpbWRhbDEPMA0GA1UEAwwGU2VydmVyMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcD
+QgAEi1mCfULxkG8qSQ2gSh9YvQksJNodPaUmPt32NG1IqJHY+U613keG14Oo/vwr
+h6CVEyTmeqyYSihqV9s2wUHLxKNaMFgwHQYDVR0OBBYEFOowNM57NxGxrHqV/oT9
+eT5DM+iuMB8GA1UdIwQYMBaAFOtR3wCoaF9m8dWylzOdd5vfbwmDMAkGA1UdEwQC
+MAAwCwYDVR0PBAQDAgSwMAoGCCqGSM49BAMCA0cAMEQCIB2nDbiSg6jTeoSWfCvG
+23Pn4xxbes8Nb+/8+1lDjLWPAiA+KB8wJhUA4hO/Axfu85wKjddpbGtJR0JlxtEe
+whF52Q==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/secp256r2TestServer.key.pem b/third_party/heimdal/lib/hx509/data/secp256r2TestServer.key.pem
new file mode 100644
index 0000000..fb57e79
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/secp256r2TestServer.key.pem
@@ -0,0 +1,5 @@
+-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgKo/47DaveCl90GxH
+LCE7IGBua2XsE+jI4RUWZrqjhBGhRANCAASLWYJ9QvGQbypJDaBKH1i9CSwk2h09
+pSY+3fY0bUiokdj5TrXeR4bXg6j+/CuHoJUTJOZ6rJhKKGpX2zbBQcvE
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/secp256r2TestServer.pem b/third_party/heimdal/lib/hx509/data/secp256r2TestServer.pem
new file mode 100644
index 0000000..31a354d
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/secp256r2TestServer.pem
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIIBsDCCAVegAwIBAgIBAjAKBggqhkjOPQQDAjA2MQswCQYDVQQGEwJTRTEQMA4G
+A1UECgwHSGVpbWRhbDEVMBMGA1UEAwwMQ0Egc2VjcDI1NnIxMCAXDTE5MDMyMjIy
+MjUyNVoYDzI1MTgxMTIxMjIyNTI1WjAwMQswCQYDVQQGEwJTRTEQMA4GA1UECgwH
+SGVpbWRhbDEPMA0GA1UEAwwGU2VydmVyMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcD
+QgAEi1mCfULxkG8qSQ2gSh9YvQksJNodPaUmPt32NG1IqJHY+U613keG14Oo/vwr
+h6CVEyTmeqyYSihqV9s2wUHLxKNaMFgwHQYDVR0OBBYEFOowNM57NxGxrHqV/oT9
+eT5DM+iuMB8GA1UdIwQYMBaAFOtR3wCoaF9m8dWylzOdd5vfbwmDMAkGA1UdEwQC
+MAAwCwYDVR0PBAQDAgSwMAoGCCqGSM49BAMCA0cAMEQCIB2nDbiSg6jTeoSWfCvG
+23Pn4xxbes8Nb+/8+1lDjLWPAiA+KB8wJhUA4hO/Axfu85wKjddpbGtJR0JlxtEe
+whF52Q==
+-----END CERTIFICATE-----
+-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgKo/47DaveCl90GxH
+LCE7IGBua2XsE+jI4RUWZrqjhBGhRANCAASLWYJ9QvGQbypJDaBKH1i9CSwk2h09
+pSY+3fY0bUiokdj5TrXeR4bXg6j+/CuHoJUTJOZ6rJhKKGpX2zbBQcvE
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/sf-class2-root.pem b/third_party/heimdal/lib/hx509/data/sf-class2-root.pem
new file mode 100644
index 0000000..d552e65
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/sf-class2-root.pem
@@ -0,0 +1,24 @@
+-----BEGIN CERTIFICATE-----
+MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzEl
+MCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMp
+U3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQw
+NjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBoMQswCQYDVQQGEwJVUzElMCMGA1UE
+ChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZp
+ZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqGSIb3
+DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf
+8MOh2tTYbitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN
++lq2cwQlZut3f+dZxkqZJRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0
+X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVmepsZGD3/cVE8MC5fvj13c7JdBmzDI1aa
+K4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSNF4Azbl5KXZnJHoe0nRrA
+1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HFMIHCMB0G
+A1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fR
+zt0fhvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0
+YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBD
+bGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8w
+DQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGsafPzWdqbAYcaT1epoXkJKtv3
+L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLMPUxA2IGvd56D
+eruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl
+xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynp
+VSJYACPq4xJDKVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEY
+WQPJIrSPnNVeKtelttQKbfi3QBFGmh95DmK/D5fs4C8fF5Q=
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/static-file b/third_party/heimdal/lib/hx509/data/static-file
new file mode 100644
index 0000000..2216857
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/static-file
@@ -0,0 +1,84 @@
+This is a static file don't change the content, it is used in the test
+
+#!/bin/sh
+#
+# Copyright (c) 2005 Kungliga Tekniska Hgskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+#
+
+srcdir="@srcdir@"
+
+echo "try printing"
+./hxtool print \
+ --pass=PASS:foobar \
+ PKCS12:$srcdir/data/test.p12 || exit 1
+
+echo "make sure entry is found (friendlyname)"
+./hxtool query \
+ --pass=PASS:foobar \
+ --friendlyname=friendlyname-test \
+ PKCS12:$srcdir/data/test.p12 || exit 1
+
+echo "make sure entry is not found (friendlyname)"
+./hxtool query \
+ --pass=PASS:foobar \
+ --friendlyname=friendlyname-test-not \
+ PKCS12:$srcdir/data/test.p12 && exit 1
+
+echo "check for ca cert (friendlyname)"
+./hxtool query \
+ --pass=PASS:foobar \
+ --friendlyname=ca \
+ PKCS12:$srcdir/data/test.p12 || exit 1
+
+echo "make sure entry is not found (friendlyname)"
+./hxtool query \
+ --pass=PASS:foobar \
+ --friendlyname=friendlyname-test \
+ PKCS12:$srcdir/data/sub-cert.p12 && exit 1
+
+echo "make sure entry is found (friendlyname|private key)"
+./hxtool query \
+ --pass=PASS:foobar \
+ --friendlyname=friendlyname-test \
+ --private-key \
+ PKCS12:$srcdir/data/test.p12 || exit 1
+
+echo "make sure entry is not found (friendlyname|private key)"
+./hxtool query \
+ --pass=PASS:foobar \
+ --friendlyname=ca \
+ --private-key \
+ PKCS12:$srcdir/data/test.p12 && exit 1
+
+exit 0
+
diff --git a/third_party/heimdal/lib/hx509/data/sub-ca.crt b/third_party/heimdal/lib/hx509/data/sub-ca.crt
new file mode 100644
index 0000000..25f3ae8
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/sub-ca.crt
@@ -0,0 +1,123 @@
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 10 (0xa)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: CN=hx509 Test Root CA, C=SE
+ Validity
+ Not Before: Mar 22 22:25:10 2019 GMT
+ Not After : Nov 21 22:25:10 2518 GMT
+ Subject: C=SE, CN=Sub CA
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:c7:18:39:67:2a:c4:6b:c6:1a:64:23:bb:ba:4c:
+ 47:22:35:91:b7:c9:eb:57:b9:8b:8f:83:62:be:0a:
+ 56:49:cc:ed:de:7e:f9:44:db:8f:f9:f9:ec:db:a2:
+ 4a:d3:fa:b1:36:c0:93:e9:2b:d0:9a:64:65:43:52:
+ 64:0e:af:3c:0a:23:57:d9:66:44:0c:ef:a6:73:7e:
+ 4d:71:94:76:5d:d2:2e:9c:02:1e:44:4b:67:0d:61:
+ 05:ff:f1:cc:29:94:93:ab:f7:b6:d7:33:d0:9e:b4:
+ 02:1a:7b:03:bb:9c:52:00:21:43:97:ff:59:f3:b1:
+ eb:16:67:b1:5a:66:26:99:04:12:28:bb:68:97:38:
+ 66:cf:d3:cc:da:41:d8:4f:e2:f9:59:48:da:ca:55:
+ b9:2a:63:43:6b:0d:c5:58:75:8e:6e:55:d2:77:cd:
+ df:8a:14:82:a2:72:f3:e8:93:a1:e4:72:f3:c0:93:
+ b3:0b:72:98:ad:53:93:53:86:fc:b0:3b:77:1c:aa:
+ f5:64:77:ce:92:0c:07:82:60:39:e9:d6:bc:df:dc:
+ ad:f9:4f:42:d2:db:42:76:6e:0b:f5:fa:58:05:7f:
+ 3c:d9:cf:eb:d2:c0:9a:26:2c:e8:90:73:0a:3c:42:
+ e5:f9:0b:cd:53:2d:16:14:75:f8:47:2e:04:1a:47:
+ d8:a6:20:0f:ec:96:fe:14:30:87:30:84:04:74:42:
+ 45:b3:3b:c1:48:84:54:4e:69:9b:f5:cb:7a:da:75:
+ 1e:26:93:87:5e:a2:c6:8f:fd:0f:96:84:76:2d:18:
+ 86:f7:87:1e:95:47:10:45:b5:45:ea:38:b7:e0:22:
+ 28:c6:98:42:5f:ed:69:d6:73:a3:d4:72:de:74:f7:
+ 2a:d2:90:5d:66:86:a1:b5:a4:fb:c7:37:94:65:82:
+ 80:d7:88:84:be:d6:5f:fd:25:88:0b:ee:6b:bb:4b:
+ 94:c6:e1:39:95:74:93:44:44:8e:3f:7e:13:33:49:
+ 8e:e3:f4:a0:43:e7:2d:15:f7:02:e9:bf:a8:94:65:
+ 71:df:45:35:f7:cc:03:b6:e4:d6:32:d2:98:66:ba:
+ d6:da:76:35:e0:81:76:25:0a:94:3f:6c:a6:53:49:
+ 52:c5:38:44:4d:ea:b4:fd:50:ee:63:e1:1b:51:ef:
+ 62:64:0e:39:cb:10:73:9d:fd:b0:2e:15:5a:cb:90:
+ 1c:9f:e9:88:37:14:92:32:7b:7a:00:fd:35:b4:d3:
+ 8c:99:90:74:95:7d:bf:25:41:04:68:56:38:3e:f1:
+ f5:97:b5:f3:cc:b8:16:99:40:1f:9d:eb:51:88:46:
+ 2a:62:b9:a5:bd:ad:97:db:58:5a:d4:6c:ed:32:db:
+ b4:5a:f5
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Subject Key Identifier:
+ 63:34:08:C8:42:04:47:74:99:65:DD:4F:EA:C5:0F:05:D9:F8:CE:47
+ X509v3 Authority Key Identifier:
+ keyid:53:B8:CC:09:C6:9F:42:EA:D5:E4:74:20:B4:65:ED:68:F8:9D:B5:05
+ DirName:/CN=hx509 Test Root CA/C=SE
+ serial:8D:F8:0A:D8:C1:70:91:C4
+
+ X509v3 Basic Constraints:
+ CA:TRUE
+ X509v3 Key Usage:
+ Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign, CRL Sign
+ Signature Algorithm: sha1WithRSAEncryption
+ 77:0b:fc:11:37:04:49:92:2b:97:e1:ee:b6:94:33:11:be:bb:
+ db:8b:6e:ce:42:11:39:b2:be:61:03:a2:ef:d4:06:1f:63:d2:
+ af:1f:c5:43:80:67:1d:10:a0:3d:93:d1:7f:bd:be:9e:21:48:
+ d0:a8:ea:8c:32:0a:f7:eb:b0:c7:0f:ac:a7:8b:c6:1a:18:10:
+ 51:88:fd:1a:53:4b:1b:7b:94:5e:59:02:92:72:6c:df:32:3a:
+ 9c:f5:87:c9:fd:a2:f8:d3:df:34:be:75:7e:51:15:eb:b0:df:
+ 87:1b:15:df:fc:97:1e:06:f9:6e:8b:79:45:3d:c4:76:d2:1d:
+ 8e:04:8f:72:d6:b0:7c:09:79:23:47:7a:9a:41:76:7e:c3:3d:
+ 2d:46:26:db:72:64:a8:1d:ca:94:fe:d8:69:e7:24:1f:dc:c8:
+ 7b:4f:2f:89:7b:a3:8c:33:7f:0f:54:16:f4:45:60:e1:df:68:
+ f5:5b:3a:ce:1c:63:e6:81:ca:a6:aa:e4:a2:c1:07:e3:ec:ef:
+ ef:ad:cc:ac:5a:e1:57:40:15:09:b3:0f:f1:58:b2:2a:45:eb:
+ 5e:16:03:9c:2c:c1:ce:22:48:67:06:5e:0a:fd:fd:d5:76:8e:
+ a8:db:2c:38:15:b4:c1:e4:0f:12:98:0a:43:19:e6:74:b9:8b:
+ e3:7a:92:2e:2a:30:1d:b7:85:39:d5:29:2f:54:16:7d:b0:f6:
+ f9:17:e2:95:07:ff:0f:e6:16:55:6d:97:c8:41:c6:5f:8f:a9:
+ 3c:3a:19:8d:66:29:13:f3:00:6d:31:f3:f1:14:a5:e8:c7:2c:
+ c0:18:4b:5e:15:88:eb:59:44:97:91:1c:78:d7:a0:4d:a1:bf:
+ bf:b0:67:4f:68:df:d3:d0:c4:6e:b8:1d:36:bd:a8:c8:b4:67:
+ 34:c0:b2:28:8a:e9:1a:30:14:b3:be:d5:a3:a0:57:4f:b7:ff:
+ a0:9e:c0:28:58:90:43:57:e7:7c:d0:81:90:41:54:85:56:4b:
+ cd:f4:a3:63:3b:1a:8f:82:0d:2c:9d:79:58:40:f4:f6:37:a0:
+ fc:77:db:82:ab:de:fa:0c:7f:c2:ce:35:80:4e:f7:d8:0d:8b:
+ cd:5b:8c:a9:82:ec:a3:a1:ca:b8:4e:29:fd:35:79:dc:4d:f3:
+ bf:ee:41:a0:88:63:b9:65:22:bb:0d:27:e8:91:d4:20:51:06:
+ f9:e7:9a:e9:7c:4c:4a:64:b5:4f:22:79:36:ad:79:e8:b8:6a:
+ 6f:f8:e8:39:48:7b:3f:87:14:9a:22:ec:7d:33:94:35:42:29:
+ 56:11:de:15:bd:4c:c2:5d:ff:9f:82:72:a2:00:b3:e9:68:38:
+ 5b:ab:dd:0d:90:73:cd:80
+-----BEGIN CERTIFICATE-----
+MIIFXzCCA0egAwIBAgIBCjANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw
+OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMCAXDTE5MDMyMjIyMjUxMFoYDzI1
+MTgxMTIxMjIyNTEwWjAeMQswCQYDVQQGEwJTRTEPMA0GA1UEAwwGU3ViIENBMIIC
+IjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxxg5ZyrEa8YaZCO7ukxHIjWR
+t8nrV7mLj4NivgpWSczt3n75RNuP+fns26JK0/qxNsCT6SvQmmRlQ1JkDq88CiNX
+2WZEDO+mc35NcZR2XdIunAIeREtnDWEF//HMKZSTq/e21zPQnrQCGnsDu5xSACFD
+l/9Z87HrFmexWmYmmQQSKLtolzhmz9PM2kHYT+L5WUjaylW5KmNDaw3FWHWOblXS
+d83fihSConLz6JOh5HLzwJOzC3KYrVOTU4b8sDt3HKr1ZHfOkgwHgmA56da839yt
++U9C0ttCdm4L9fpYBX882c/r0sCaJizokHMKPELl+QvNUy0WFHX4Ry4EGkfYpiAP
+7Jb+FDCHMIQEdEJFszvBSIRUTmmb9ct62nUeJpOHXqLGj/0PloR2LRiG94celUcQ
+RbVF6ji34CIoxphCX+1p1nOj1HLedPcq0pBdZoahtaT7xzeUZYKA14iEvtZf/SWI
+C+5ru0uUxuE5lXSTRESOP34TM0mO4/SgQ+ctFfcC6b+olGVx30U198wDtuTWMtKY
+ZrrW2nY14IF2JQqUP2ymU0lSxThETeq0/VDuY+EbUe9iZA45yxBznf2wLhVay5Ac
+n+mINxSSMnt6AP01tNOMmZB0lX2/JUEEaFY4PvH1l7XzzLgWmUAfnetRiEYqYrml
+va2X21ha1GztMtu0WvUCAwEAAaOBmTCBljAdBgNVHQ4EFgQUYzQIyEIER3SZZd1P
+6sUPBdn4zkcwWgYDVR0jBFMwUYAUU7jMCcafQurV5HQgtGXtaPidtQWhLqQsMCox
+GzAZBgNVBAMMEmh4NTA5IFRlc3QgUm9vdCBDQTELMAkGA1UEBhMCU0WCCQCN+ArY
+wXCRxDAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIB5jANBgkqhkiG9w0BAQUFAAOC
+AgEAdwv8ETcESZIrl+HutpQzEb6724tuzkIRObK+YQOi79QGH2PSrx/FQ4BnHRCg
+PZPRf72+niFI0KjqjDIK9+uwxw+sp4vGGhgQUYj9GlNLG3uUXlkCknJs3zI6nPWH
+yf2i+NPfNL51flEV67DfhxsV3/yXHgb5bot5RT3EdtIdjgSPctawfAl5I0d6mkF2
+fsM9LUYm23JkqB3KlP7YaeckH9zIe08viXujjDN/D1QW9EVg4d9o9Vs6zhxj5oHK
+pqrkosEH4+zv763MrFrhV0AVCbMP8ViyKkXrXhYDnCzBziJIZwZeCv391XaOqNss
+OBW0weQPEpgKQxnmdLmL43qSLiowHbeFOdUpL1QWfbD2+RfilQf/D+YWVW2XyEHG
+X4+pPDoZjWYpE/MAbTHz8RSl6McswBhLXhWI61lEl5EceNegTaG/v7BnT2jf09DE
+brgdNr2oyLRnNMCyKIrpGjAUs77Vo6BXT7f/oJ7AKFiQQ1fnfNCBkEFUhVZLzfSj
+Yzsaj4INLJ15WED09jeg/Hfbgqve+gx/ws41gE732A2LzVuMqYLso6HKuE4p/TV5
+3E3zv+5BoIhjuWUiuw0n6JHUIFEG+eea6XxMSmS1TyJ5Nq156Lhqb/joOUh7P4cU
+miLsfTOUNUIpVhHeFb1Mwl3/n4JyogCz6Wg4W6vdDZBzzYA=
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/sub-ca.key b/third_party/heimdal/lib/hx509/data/sub-ca.key
new file mode 100644
index 0000000..1475e42
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/sub-ca.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDHGDlnKsRrxhpk
+I7u6TEciNZG3yetXuYuPg2K+ClZJzO3efvlE24/5+ezbokrT+rE2wJPpK9CaZGVD
+UmQOrzwKI1fZZkQM76Zzfk1xlHZd0i6cAh5ES2cNYQX/8cwplJOr97bXM9CetAIa
+ewO7nFIAIUOX/1nzsesWZ7FaZiaZBBIou2iXOGbP08zaQdhP4vlZSNrKVbkqY0Nr
+DcVYdY5uVdJ3zd+KFIKicvPok6HkcvPAk7MLcpitU5NThvywO3ccqvVkd86SDAeC
+YDnp1rzf3K35T0LS20J2bgv1+lgFfzzZz+vSwJomLOiQcwo8QuX5C81TLRYUdfhH
+LgQaR9imIA/slv4UMIcwhAR0QkWzO8FIhFROaZv1y3radR4mk4deosaP/Q+WhHYt
+GIb3hx6VRxBFtUXqOLfgIijGmEJf7WnWc6PUct509yrSkF1mhqG1pPvHN5RlgoDX
+iIS+1l/9JYgL7mu7S5TG4TmVdJNERI4/fhMzSY7j9KBD5y0V9wLpv6iUZXHfRTX3
+zAO25NYy0phmutbadjXggXYlCpQ/bKZTSVLFOERN6rT9UO5j4RtR72JkDjnLEHOd
+/bAuFVrLkByf6Yg3FJIye3oA/TW004yZkHSVfb8lQQRoVjg+8fWXtfPMuBaZQB+d
+61GIRipiuaW9rZfbWFrUbO0y27Ra9QIDAQABAoICAHBMg6RjhSNdPGmbljoA6Gat
+XKIULMDwkX3DmCClaAJ8qvdDG4rxZYaUqDtCkX57+xVtDoEJC8LqOgv9Hx8BTJZT
+VSv0+RFq47JlXX1hRlqpQU0SDMxs05XCUkYJtyUE/z6SnPlJ6rR5yG3zUSmzhLU6
+DgxgJfbFNlsO5gSddcv9ddivzNDvKV60kunRFhgJaKgp5e8W5zi3gMGTpOq+dDZc
+Bjk5UItsAjtrJ5TaIQjgpgjLxsQAQYoSiBknHMSy5f6vl3ax9Tx/uISbjk8Npr+G
+lEL5qDGTJyvx6qE2Mgv3tvUMyHG53bkGv68qlG1lNp6BP7FYzwl/eSl9FSdVuycK
+UsUMi+dpuQlXOVprKAKTxYw+E7n8TV7ewmudbOEFR/ao6qCJqNtSQJa5dFFhU9An
+ld/rKIcY9gfobYtS0qRiGAt18Be7qt6qGpwAZogfe+VM/G3S00yVP21gGN2qju3M
+6vF99CTVLeD+g8JUJT+olzShLpZAgw09hXMx1JJJksl+kv6FNG0EotxlXCdIQTsG
+TtWvOFXck7E5FZHjj+5eXCyRNVKzWRJAU6POr3Qr0gLpcg0DBbzfLAvDEA8k3V2Y
+DqQeyi7xrd7ALKZmrLWnLQQdXQ8rUN0f/8lsus3TOiXjly3/GIediaYb+uxdACmC
+4d+twAWpdnWrAiWDaICBAoIBAQDm7vUgSu2rsbd+YvBhYrNhTmmyVr/5HWOGaDjX
+YJWj2Vqh4sVeoVjRpVgC4Yyx/iE9f4MPsiBzWmudMuG/yytxIfWWXEBGXmAHYL8Z
+d6acVWer0yZik/xYV8nUUVUzzB7EvB7XdFtGMYPTZNiqhyZ9CGMeIHcaXndqejeJ
+ycbOr+IDgBKQ9fGdpAZjTprrB0WqOhnxy6EJoObg6bicgIPCBxzdVCDo6mmkkRrQ
+lIYRMAtjIzbGdwT6OADUf9Lr2aPBuKBQeEKFbADyNNyenqvcSFKcGcug2DZ8sIYN
+US28VHke87mOg6qrNh166e00Hlp0q42Q2hV/8XxRQDDwxoqFAoIBAQDctIx8lGcJ
+kxftf5j7ss0iUYSkT77HF7V9q81X7iMSjHTEyIYD2UHt2PS0gUL1jnjOXjIDFFHU
+HzfymvsEjV8Vr8nUvKVkSUXWFnYPQ4rFP2d+Zyv64AhDKRrIOiG9ozLhqDdu7wui
+XXigEuuwG6+LObO09FwKOhDRNgpuQnDlgHPidyu4PHoz56SlzGpTXM1/nTIGkWMi
+v2aZF2hAzQM3bEqeyRUTnX/DvOQbFLDYLDc/KWaPDvBTJCwa2tPSZRA5ArmEmloc
+yxTdf+DaSBy7P2EExfXkKNgvO978GYHUBk3SdA/2BLy0kNU1BSrajtjrxSLqUD8j
+aVYafGb5eNGxAoIBAQCBZOkCVBmBt406CtPnrTcXUalVnNfqDHaEjAc1Xs/Zw+LN
+jFPMpxkuNrfuvVRpMxyK6dSUydj26XYc2bK2FW/c7ws9WalGBIFIAQRyj6FSPWRe
+WWxLleGx2lajWYMlB71BvKqHTJIL7ZiQrRPd0OZW7okjC0vRAZdlmN9fnCiCDPjV
+v0An6zabfpl5sUSKZkO5kt6QpekwjPBwm2SuhC/PWs7okMfz2cyhwhBFSMMqBEKN
+JOD/KRcn4JNOfeS/8+2WkQ16qTeUrKSHEemAEyX2wqtO/gEjuaImEX67HX5D5Q0M
+s8GHweyyDBtOkJ4xMsS6VJl4zUl4q+VdXVtOveBFAoIBAEbpl+37PLP92AVOJxhQ
+Fcr+CDFHEhQkEQNE7SBgelJeYLJNf4nDB4TlXZKVqa7+TOB5sXX91GDkevRvSVHo
+HnH4XlAFINr9E/w6kUpMOE0yFw2tFptv2hfCIEHPM8IbqqCIjO8OzV0ozTYZfjLC
+Yn/IVW5ByUTb7UVbKLTOkjmbMSDFi32RqO3+co93A36vZbOoDUfA9OpYNx3fQHb5
+qBvppnwoPaZkx4Vbrqro1f1PD50yryot8Ze1GpqyTrbeE/1NW9A4S9XOhnC4wsU/
+wEOFlKWU+XGKkhNzGC1GAMngEKca9XnlgcA+fNKhS2iX1yjB2XsRt4eoM6sk520m
+nbECggEBAM2u917mgRcyRrOF3orTy0p5aRkHmAi7rdlr/E2CC/I+Uk00cSEJKgfL
+IzLOs5ZARc6kkBAilNhz8lWWADaonmE5qDZjAzYwIuNWlZgWGYO74RwpavNaK7UM
+MhRWCzomZUyNHKJiubkM8CTaioVsqoZS/OiWGHtGtSTAAknCb1wc5fppNU0xUQ/5
+AZGlrpUdb86VGN/lNNsF16tZ0mWUazXMXDCZgT9869p41OQYgIGDPvf9y9mWyYR6
+VbQSyfvDh4Wiu4Sf7L6OP8VG+xvhD+sRZPB9i3TzvhFWrzkcP3sXRqPxpdSSWgyP
+Ca7fU8eAAjotw7SSdeefJ+CduL/cNQE=
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/sub-cert.crt b/third_party/heimdal/lib/hx509/data/sub-cert.crt
new file mode 100644
index 0000000..b98c463
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/sub-cert.crt
@@ -0,0 +1,116 @@
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 11 (0xb)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: C=SE, CN=Sub CA
+ Validity
+ Not Before: Mar 22 22:25:12 2019 GMT
+ Not After : Nov 21 22:25:12 2518 GMT
+ Subject: C=SE, CN=Test sub cert
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:ef:45:00:67:2b:7e:d2:ea:7d:80:b1:ae:81:5e:
+ fb:dd:82:ca:de:db:98:37:70:e8:3c:a2:01:87:8b:
+ 88:2e:40:30:22:d4:65:1d:7e:cb:cb:d5:40:e0:51:
+ 06:f0:f3:d9:00:db:5d:6a:0f:d3:11:bc:a1:3c:69:
+ 25:65:a9:87:b5:8a:3e:6c:79:2a:e8:5b:1a:9e:b4:
+ a4:81:5b:c3:83:f6:fd:9a:a8:48:6a:c4:ce:7f:81:
+ 26:83:c9:e5:b5:c9:a2:18:ed:0c:ea:1a:26:59:49:
+ df:56:ea:c2:33:2f:65:c2:14:30:5d:78:4e:91:09:
+ 6d:f5:77:ee:e8:0e:fe:ca:14:92:af:73:c4:8e:91:
+ b1:62:1a:c1:46:3e:36:d2:33:6a:7f:05:4e:d5:7b:
+ fe:69:4f:6c:b1:be:89:e6:7e:8d:5b:de:10:6c:a6:
+ bc:4a:05:66:17:19:71:e3:2c:62:bf:8b:4b:3c:6d:
+ fb:2a:7b:95:d5:d4:02:f0:43:e0:ce:cc:7a:30:fb:
+ a9:93:d2:50:a0:17:67:c6:08:8d:3c:9c:83:69:1f:
+ b7:ab:cf:d0:77:b6:8e:cc:89:0d:82:cd:e1:fb:53:
+ 2c:1d:f6:6b:81:0d:8f:da:dc:6a:34:93:06:23:32:
+ fb:83:90:40:8a:7f:ad:cf:2c:81:6a:10:cb:59:29:
+ d4:f2:af:b2:ee:f0:7b:b2:d5:0f:9d:5c:e6:d3:eb:
+ 18:9b:89:01:11:5f:e7:f4:50:34:e6:2c:31:b1:f3:
+ 60:af:03:a5:40:00:47:88:76:cd:52:da:1b:11:03:
+ 57:f5:3d:a1:01:f6:2f:9e:f5:01:37:22:a0:7d:5f:
+ 40:87:2d:69:72:70:80:05:16:24:2d:a6:b1:5e:ca:
+ 40:ad:f2:da:7f:c9:8f:7a:32:b2:8c:be:9b:de:66:
+ 17:92:81:83:8d:1a:f5:c9:8b:9a:3b:4a:84:b2:24:
+ 63:97:60:f6:3a:c0:84:88:2a:dd:6b:f8:e7:44:29:
+ 79:cf:98:d9:ab:36:93:10:a8:7a:7b:90:bc:bb:e0:
+ 43:c1:93:13:80:9d:cb:a6:68:67:94:67:6b:3a:58:
+ bd:02:39:20:88:e1:64:8e:a1:7a:6b:99:3b:9b:00:
+ 65:11:b5:fd:b7:18:55:fe:67:f4:94:ab:c2:08:a7:
+ 3a:d8:a7:b4:6e:d9:e9:89:1e:b0:81:1e:23:31:a9:
+ 17:b7:c7:f9:df:5b:90:2c:46:96:c5:d5:a6:cc:8b:
+ e4:db:fd:4b:47:8d:8f:bb:e4:41:d0:99:fe:81:83:
+ 88:a7:f0:a5:81:ae:c9:62:f6:4f:d8:12:60:33:20:
+ 6f:d1:39:37:f5:1f:05:40:62:43:9b:97:a5:7b:16:
+ cc:93:e5
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints:
+ CA:FALSE
+ X509v3 Key Usage:
+ Digital Signature, Non Repudiation, Key Encipherment
+ X509v3 Subject Key Identifier:
+ 48:26:75:6B:4D:E0:98:93:39:02:40:D3:F1:1C:6D:D0:D8:45:A6:04
+ Signature Algorithm: sha1WithRSAEncryption
+ aa:a0:db:44:96:6c:b5:c7:96:93:a3:11:e5:dc:1f:69:08:87:
+ f5:5f:50:25:99:03:6c:d2:89:55:4c:04:d4:8a:49:73:e8:e1:
+ 82:4f:f6:45:24:1c:ef:46:09:b2:19:09:16:5f:11:05:13:e7:
+ 3f:ca:5b:af:4f:6f:39:df:a8:71:1c:cb:62:2b:8d:42:b9:a7:
+ 58:76:72:db:88:8d:3a:e0:33:5c:ef:41:c7:30:d6:d0:9a:9c:
+ 70:f1:72:74:e6:0d:6c:1c:11:ff:f3:4a:ee:3d:d2:f7:3a:56:
+ 9f:41:63:83:60:4c:6b:63:d5:9a:a1:c8:22:b2:a5:8c:03:99:
+ 2f:04:65:a8:52:1b:1c:cb:4b:e4:b1:a0:86:7c:d7:85:e9:9a:
+ 8b:8f:f1:2d:e9:45:d0:f4:ee:51:cf:13:da:ff:ea:e8:cc:30:
+ cc:ed:f3:7e:f9:4d:59:a3:d2:ca:f2:4f:5b:73:65:63:de:39:
+ 0e:87:e1:16:30:65:d0:fa:da:0d:57:df:82:de:09:2c:24:7a:
+ ef:9c:d8:fa:7c:5a:25:f1:1e:e3:e1:56:c5:79:c3:13:37:38:
+ 03:dd:b4:6f:c0:61:b7:cb:41:bb:77:0c:c3:4f:14:e0:8c:e9:
+ 89:4b:55:6b:dc:ce:11:9b:f0:68:32:e2:64:c8:75:6a:80:26:
+ 88:fc:c1:ad:56:07:57:07:2d:fc:10:c8:42:94:f6:f4:7a:e2:
+ 94:ee:05:aa:28:7a:f3:d6:62:4a:fb:99:c0:df:dd:ca:77:14:
+ 70:6e:63:d1:68:25:6b:de:51:8b:8c:0c:5e:68:79:25:a5:68:
+ 74:c1:43:23:75:4f:eb:30:c6:84:79:a9:df:25:a6:66:56:cd:
+ 9c:95:40:b0:12:c0:60:9d:b3:99:02:4d:d1:de:25:2d:00:49:
+ e4:8f:81:8f:14:5d:3e:1c:c4:ac:11:ac:ef:0d:a7:ca:0c:01:
+ 88:54:26:bb:38:c7:24:b8:4b:45:97:40:9b:21:ea:7b:e0:5b:
+ 5f:d4:3d:dc:01:0a:8e:3d:db:31:8b:e8:23:8b:5c:48:34:95:
+ de:71:cc:61:43:aa:59:0e:be:0a:7f:75:8d:fb:b9:f0:fd:28:
+ e9:76:8d:5f:ea:9c:59:07:28:a5:b4:df:8f:0b:3c:c7:ad:00:
+ fe:9e:28:86:cd:52:fe:e3:78:81:ed:5e:73:40:1c:06:02:a8:
+ b1:84:b3:ec:56:ce:a3:70:22:ce:ab:0f:4b:8d:36:09:2d:6d:
+ 5e:93:2d:c4:20:c4:bd:8e:78:68:0a:84:81:b9:85:b7:cb:03:
+ c0:26:b9:c3:d8:e7:ab:c6:a6:7c:55:a4:e6:96:b3:65:84:5b:
+ 7e:bd:1e:c9:94:f6:25:c7
+-----BEGIN CERTIFICATE-----
+MIIE+TCCAuGgAwIBAgIBCzANBgkqhkiG9w0BAQUFADAeMQswCQYDVQQGEwJTRTEP
+MA0GA1UEAwwGU3ViIENBMCAXDTE5MDMyMjIyMjUxMloYDzI1MTgxMTIxMjIyNTEy
+WjAlMQswCQYDVQQGEwJTRTEWMBQGA1UEAwwNVGVzdCBzdWIgY2VydDCCAiIwDQYJ
+KoZIhvcNAQEBBQADggIPADCCAgoCggIBAO9FAGcrftLqfYCxroFe+92Cyt7bmDdw
+6DyiAYeLiC5AMCLUZR1+y8vVQOBRBvDz2QDbXWoP0xG8oTxpJWWph7WKPmx5Kuhb
+Gp60pIFbw4P2/ZqoSGrEzn+BJoPJ5bXJohjtDOoaJllJ31bqwjMvZcIUMF14TpEJ
+bfV37ugO/soUkq9zxI6RsWIawUY+NtIzan8FTtV7/mlPbLG+ieZ+jVveEGymvEoF
+ZhcZceMsYr+LSzxt+yp7ldXUAvBD4M7MejD7qZPSUKAXZ8YIjTycg2kft6vP0He2
+jsyJDYLN4ftTLB32a4ENj9rcajSTBiMy+4OQQIp/rc8sgWoQy1kp1PKvsu7we7LV
+D51c5tPrGJuJARFf5/RQNOYsMbHzYK8DpUAAR4h2zVLaGxEDV/U9oQH2L571ATci
+oH1fQIctaXJwgAUWJC2msV7KQK3y2n/Jj3oysoy+m95mF5KBg40a9cmLmjtKhLIk
+Y5dg9jrAhIgq3Wv450Qpec+Y2as2kxCoenuQvLvgQ8GTE4Cdy6ZoZ5RnazpYvQI5
+IIjhZI6hemuZO5sAZRG1/bcYVf5n9JSrwginOtintG7Z6YkesIEeIzGpF7fH+d9b
+kCxGlsXVpsyL5Nv9S0eNj7vkQdCZ/oGDiKfwpYGuyWL2T9gSYDMgb9E5N/UfBUBi
+Q5uXpXsWzJPlAgMBAAGjOTA3MAkGA1UdEwQCMAAwCwYDVR0PBAQDAgXgMB0GA1Ud
+DgQWBBRIJnVrTeCYkzkCQNPxHG3Q2EWmBDANBgkqhkiG9w0BAQUFAAOCAgEAqqDb
+RJZstceWk6MR5dwfaQiH9V9QJZkDbNKJVUwE1IpJc+jhgk/2RSQc70YJshkJFl8R
+BRPnP8pbr09vOd+ocRzLYiuNQrmnWHZy24iNOuAzXO9BxzDW0JqccPFydOYNbBwR
+//NK7j3S9zpWn0Fjg2BMa2PVmqHIIrKljAOZLwRlqFIbHMtL5LGghnzXhemai4/x
+LelF0PTuUc8T2v/q6MwwzO3zfvlNWaPSyvJPW3NlY945DofhFjBl0PraDVffgt4J
+LCR675zY+nxaJfEe4+FWxXnDEzc4A920b8Bht8tBu3cMw08U4IzpiUtVa9zOEZvw
+aDLiZMh1aoAmiPzBrVYHVwct/BDIQpT29HrilO4Fqih689ZiSvuZwN/dyncUcG5j
+0Wgla95Ri4wMXmh5JaVodMFDI3VP6zDGhHmp3yWmZlbNnJVAsBLAYJ2zmQJN0d4l
+LQBJ5I+BjxRdPhzErBGs7w2nygwBiFQmuzjHJLhLRZdAmyHqe+BbX9Q93AEKjj3b
+MYvoI4tcSDSV3nHMYUOqWQ6+Cn91jfu58P0o6XaNX+qcWQcopbTfjws8x60A/p4o
+hs1S/uN4ge1ec0AcBgKosYSz7FbOo3AizqsPS402CS1tXpMtxCDEvY54aAqEgbmF
+t8sDwCa5w9jnq8amfFWk5pazZYRbfr0eyZT2Jcc=
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/sub-cert.key b/third_party/heimdal/lib/hx509/data/sub-cert.key
new file mode 100644
index 0000000..481dabb
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/sub-cert.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDvRQBnK37S6n2A
+sa6BXvvdgsre25g3cOg8ogGHi4guQDAi1GUdfsvL1UDgUQbw89kA211qD9MRvKE8
+aSVlqYe1ij5seSroWxqetKSBW8OD9v2aqEhqxM5/gSaDyeW1yaIY7QzqGiZZSd9W
+6sIzL2XCFDBdeE6RCW31d+7oDv7KFJKvc8SOkbFiGsFGPjbSM2p/BU7Ve/5pT2yx
+vonmfo1b3hBsprxKBWYXGXHjLGK/i0s8bfsqe5XV1ALwQ+DOzHow+6mT0lCgF2fG
+CI08nINpH7erz9B3to7MiQ2CzeH7Uywd9muBDY/a3Go0kwYjMvuDkECKf63PLIFq
+EMtZKdTyr7Lu8Huy1Q+dXObT6xibiQERX+f0UDTmLDGx82CvA6VAAEeIds1S2hsR
+A1f1PaEB9i+e9QE3IqB9X0CHLWlycIAFFiQtprFeykCt8tp/yY96MrKMvpveZheS
+gYONGvXJi5o7SoSyJGOXYPY6wISIKt1r+OdEKXnPmNmrNpMQqHp7kLy74EPBkxOA
+ncumaGeUZ2s6WL0COSCI4WSOoXprmTubAGURtf23GFX+Z/SUq8IIpzrYp7Ru2emJ
+HrCBHiMxqRe3x/nfW5AsRpbF1abMi+Tb/UtHjY+75EHQmf6Bg4in8KWBrsli9k/Y
+EmAzIG/ROTf1HwVAYkObl6V7FsyT5QIDAQABAoICAQC9cwIdrlfNwrM6mfVVJBMC
+0hO1n2QHydNoZtIVM8rQ7Cvw+AFT+Fh+/UxQEHgRgtI4lniBiSQTcCquPYbJ1xDI
+EjzZAJuTvMb4EIoMjs7hB0jIEyS7vTbPyD/pq4vBg3Rgjhlipu/kVNSM6nZ3tri4
+kem1qJN0zWWOLbcxcOYWtXFrkJt6UyuDRTHxX0Ni7ikNh/Nin7nSQnwKxJZFtcBR
+lCOnE+IULfAmrBP7zuIlTbJ1l5N+kLoTw7nL6cLvmwHJFQqxK56BE+cr6wuBiV+X
+dfClDne+wgKROpdDEaczqyhMVRfL6CQWI93H4P3EExMImcgwoWXKmy+g/skzwSaE
+tbFeN2cxFd3Ow3f8BWqrWEzXdwp4+26SzVXMNpjbyQoaYtxp0OhyTKI65FmaQjVS
+9We5D0asPl7Fbc+xobXQ+1InkrQevZDPcU3ejqsrm9qtGzctpv8wWaU3ByvodkQg
+ZxAzXuE8bwwJ/m/jbirXxnKfNo+22nH0ksCYH6UmQEgHdkFO22QpaiDZFvudC3mZ
+JMbP/bjXHvzukltMPXXiGcNEeP/PPVtD2EewOZV2vNVYXP/wXu9Gt2djclV1jj9j
+X3ABa7WE65ZhREqBT5RpSPizTvlyEYIUwvawnPCrwfEeVbMq/t3em1hquk2d9RTs
+UyVjuEaqKDyZdGMumiPEhQKCAQEA/09qzOJWJv5XsPUlbvmzL9Zbsv0vMlchFiNB
+zESdSmYbeNBdj9CsJjEIZldqxERAErcsHdtHUuyWNKe4phi1s5bSR3cgcjhdv4LI
+bRghUsqf7p86sINxqz5yA4jx+JmLMUbghBCSlbCKruEli0FSxUtpeYzxftEb+jZA
+PamBTNDsbaXmNhm6f95I39zxn9Gx++p+7H4/hHpXBAk7PCa1ePAzKWKiDobJbelo
+CuFxQSzPFOmhze0wVq98QIvnNnxB/x3wX8ybk4vrJSbX6NQlSWhYsrUt3HnsTDZs
+zF++euPTL04kMoaitYvZW9Mg3ZPBxazn2Cu0cswkXn4gHZ6gIwKCAQEA7+p9cMuR
+KAv4dllBm3WWxPsX7hP1f8l2d7hmyYW4r5AaWMWNI84HhArpi3EPLxd/DUwvBU57
+YejR4DXQxrZoGr5uYkzXwgPAYQujV80GGK/wpj09jQh1Xn3lE7kpPEweK9SBIJB+
+anD+8FzGo17Bz23/Wp5zjVDi/yovRZdTSqQCowiZ5df4ls42Oms5u9lipwUTv4Rk
+QFQsh7zn5JQ30U3Ef36FMpRcM4GlR+gw/JjM9zB5aboxLJmws/e3rfS/eGNXCPKE
++xiDAhdmsx44HOONBEgJ5myxJ44uifY83xIQwaE+nyuXWBIqJLKiEmEm8GJ9bgdz
+L1iD1UiNaTm4VwKCAQB49tzIRDjDcuCDdDMPOHmgobSCwpi5BjUj8wJ60Muhc21y
+uW6K9DiMQ9ESBDsO0LN26piZcMqDTJsCSbEf6Tc15rCssZGK7I/mbAWgQr2PJ3fN
+LF43QZ/6nbSRXjIfMkiTyVwY1m1NRP8ASqZqK0IXPlqz/4ZwKo1R6KBZVtVvWtGa
+Re8kFN6bNOtcPaexrD3i+MC4NjzL/Nb7j5AkOMbkjRIAer4DmfMYA22LMjNhyOQ4
+qVVDZyzu9WgugNrEouz1/e5kxWG076cyzAuiQdmExU65JUScYJwHpAW6c2ahfQ4T
+LLfTxJyU3bTXX9oDgb1edkTG1DZD6dsVdjarMfv3AoIBAC3J9z772yxlfHo59seQ
+3cGimqKZtJU7Ah0/WH7FwsXfHugqbBGVVOHio0g1v8whE+KZ06+TlwDMyqGcI8iJ
+L71K8w5X1CX3SVQ8QGSVgMBdc/SGY6TzJFNwe7QT9sbHUErVN//bFAWEo2OEkXTE
+tQC94aqN60fhVDGW/4aspvzr6ITtM1Imsg82NCtaI56ykp2F3osC3Y9ZgVY2u5to
+nm6YBRTANPO+VQqPh9f9fLv4/cV/vuxq2M/GVW9DrA7LU2/KpeXTQ4YY24gepz8w
+WU1KMLPMe/c6b2U5QbCbCmsYq5IJEEaYrz3j2Z8/aKdRW3ktkvrY+SbkIeUm/7ZB
+iekCggEBANkmkU/Mxj0C6Exv9YbrFehPxfgPcuyfAt7qdEzazjVmPWbhgpriPW55
+z/FEx/clfhaR8EWTNESKkLhX/qfGXHytlxUn8VWzcM6GIhvBTF6gUTX5hp1+peh+
+hztIBCQVPLpAXhf4Sf9+WwtBGrgo7RkIbzq/S1DynaymuVjBemSUvjKOKrVJm7gr
+DTIbmVjw5RXe5/HhPp7w8XlR4nDOYRuSd7ycG2l2xmK4VMK5QqaPEIrKDtsX0dsK
++VsrO5897j4ZZOdBif0YSRL5/zbZEA/HIA3kJ45jZDKMNPNfQBIK8yzW9KhLlBgL
+G2q8/Es7kVEQkUPyRNnHTWdnKW+vIQ0=
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/sub-cert.p12 b/third_party/heimdal/lib/hx509/data/sub-cert.p12
new file mode 100644
index 0000000..18898c8
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/sub-cert.p12
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/tcg-devid.pem b/third_party/heimdal/lib/hx509/data/tcg-devid.pem
new file mode 100644
index 0000000..66b769c
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/tcg-devid.pem
@@ -0,0 +1,24 @@
+-----BEGIN CERTIFICATE-----
+MIIEGDCCAwCgAwIBAgIBATANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAlFeGFt
+cGxlQ0EwHhcNMTQwMTE1MTU0MDUwWhcNMTUwMTE1MTU0MDUwWjAAMIIBIjANBgkq
+hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAncvm0aOBK05rdNInYXzJGV5SFteVUFpt
+XFxg4evROvlulB3BzUmFGQYFDcItVnJX2fAvf0UJLtLBVBQggb5ylL6bRpj72cS3
+oyNbs0CGmix9Z1QDjkZZFvIsD1GcKO0tvsCvsEItH8Cm0fq8WcGFijWLdRD5eulP
+55pq1bAHAvIo4+VLMJVBG71xrKGZeHPjKoq6seYjh7AGy+hk2vmFzpZ8Ghdgqv+K
+02IZ7FEdzuylHW8U3qsxBHysMut4inj6AiVf467OOs5meHiifIK9MGkovMrfY9iX
+uUVUs/KXpE1sgeoX9BLvx1BPcODosr5K+z5i71OtIXy4CXrPvcGzRwIDAQABo4IB
+hzCCAYMwQAYIKwYBBQUHAQEENDAyMDAGCCsGAQUFBzAChiRodHRwOi8vd3d3LmV4
+YW1wbGUuY29tL0V4YW1wbGVDQS5jcnQwDgYDVR0PAQH/BAQDAgAgMIGBBgNVHREB
+Af8EdzB1pEswSTEWMBQGBWeBBQIBDAtpZDo1NDQzNDcwMDEXMBUGBWeBBQICDAxB
+QkNERUYxMjM0NTYxFjAUBgVngQUCAwwLaWQ6MDAwMTAwMjOgJgYIKwYBBQUHCASg
+GjAYBgVngQUBAgQPdHBtc2VyaWFsbnVtYmVyMAwGA1UdEwEB/wQCMAAwNQYDVR0f
+BC4wLDAqoCigJoYkaHR0cDovL3d3dy5leGFtcGxlLmNvbS9FeGFtcGxlQ0EuY3Js
+MBAGA1UdIAQJMAcwBQYDKgMEMB8GA1UdIwQYMBaAFDR3ZyRMRK/nnirgskxpV5Uk
+sz3aMBAGA1UdJQQJMAcGBWeBBQgBMCEGA1UdCQQaMBgwFgYFZ4EFAhAxDTALDAMy
+LjACAQACAWMwDQYJKoZIhvcNAQELBQADggEBABtrZu0n/7jPTYxak2n30AUakS7f
+Ihomojo14e8Lp/HF7/2VaUcohJH4KekCHTf8wpPxM/b9xRKLSOORA2Ey255Q2h8T
+v19he0dcdTvDPNQVY3AKaFO4cNiXeOYPR8n3IDYK5QdPqrdRX4/Bc34QcTWFDALx
+C00L/kDvBjV7l0Et2DBJIiBNziVKxs1xn136buZYRam6ZJhTRzNMMQ0eZ279Um4M
+39EI4DIFv6FzX0sC5waacVg6HFYd933NtdkDWV0VTGuk+5V8rH4Sjx+sywHahkoz
+BJhQBai2qiWEt7bB0ExGN2ZXPjiQiG4UHvLgGlCOUHX7EDNf0dvfUIZ6hLY=
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/tcg-ek-cp.pem b/third_party/heimdal/lib/hx509/data/tcg-ek-cp.pem
new file mode 100644
index 0000000..f6631b2
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/tcg-ek-cp.pem
@@ -0,0 +1,24 @@
+-----BEGIN CERTIFICATE-----
+MIID7zCCAtegAwIBAgIBATANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAlFeGFt
+cGxlQ0EwHhcNMTQwMTE1MTU0MDUwWhcNMTUwMTE1MTU0MDUwWjAAMIIBIjANBgkq
+hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAncvm0aOBK05rdNInYXzJGV5SFteVUFpt
+XFxg4evROvlulB3BzUmFGQYFDcItVnJX2fAvf0UJLtLBVBQggb5ylL6bRpj72cS3
+oyNbs0CGmix9Z1QDjkZZFvIsD1GcKO0tvsCvsEItH8Cm0fq8WcGFijWLdRD5eulP
+55pq1bAHAvIo4+VLMJVBG71xrKGZeHPjKoq6seYjh7AGy+hk2vmFzpZ8Ghdgqv+K
+02IZ7FEdzuylHW8U3qsxBHysMut4inj6AiVf467OOs5meHiifIK9MGkovMrfY9iX
+uUVUs/KXpE1sgeoX9BLvx1BPcODosr5K+z5i71OtIXy4CXrPvcGzRwIDAQABo4IB
+XjCCAVowQAYIKwYBBQUHAQEENDAyMDAGCCsGAQUFBzAChiRodHRwOi8vd3d3LmV4
+YW1wbGUuY29tL0V4YW1wbGVDQS5jcnQwDgYDVR0PAQH/BAQDAgAgMFkGA1UdEQEB
+/wRPME2kSzBJMRYwFAYFZ4EFAgEMC2lkOjU0NDM0NzAwMRcwFQYFZ4EFAgIMDEFC
+Q0RFRjEyMzQ1NjEWMBQGBWeBBQIDDAtpZDowMDAxMDAyMzAMBgNVHRMBAf8EAjAA
+MDUGA1UdHwQuMCwwKqAooCaGJGh0dHA6Ly93d3cuZXhhbXBsZS5jb20vRXhhbXBs
+ZUNBLmNybDAQBgNVHSAECTAHMAUGAyoDBDAfBgNVHSMEGDAWgBQ0d2ckTESv554q
+4LJMaVeVJLM92jAQBgNVHSUECTAHBgVngQUIATAhBgNVHQkEGjAYMBYGBWeBBQIQ
+MQ0wCwwDMi4wAgEAAgFjMA0GCSqGSIb3DQEBCwUAA4IBAQAba2btJ/+4z02MWpNp
+99AFGpEu3yIaJqI6NeHvC6fxxe/9lWlHKISR+CnpAh03/MKT8TP2/cUSi0jjkQNh
+MtueUNofE79fYXtHXHU7wzzUFWNwCmhTuHDYl3jmD0fJ9yA2CuUHT6q3UV+PwXN+
+EHE1hQwC8QtNC/5A7wY1e5dBLdgwSSIgTc4lSsbNcZ9d+m7mWEWpumSYU0czTDEN
+Hmdu/VJuDN/RCOAyBb+hc19LAucGmnFYOhxWHfd9zbXZA1ldFUxrpPuVfKx+Eo8f
+rMsB2oZKMwSYUAWotqolhLe2wdBMRjdmVz44kIhuFB7y4BpQjlB1+xAzX9Hb31CG
+eoS2
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/test-ds-only.crt b/third_party/heimdal/lib/hx509/data/test-ds-only.crt
new file mode 100644
index 0000000..ce0de74
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-ds-only.crt
@@ -0,0 +1,117 @@
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 5 (0x5)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: CN=hx509 Test Root CA, C=SE
+ Validity
+ Not Before: Mar 22 22:25:05 2019 GMT
+ Not After : Nov 21 22:25:05 2518 GMT
+ Subject: C=SE, CN=Test cert DigitalSignature
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:d2:e5:b6:27:f7:6c:c1:d0:ba:8a:4a:6a:4e:b5:
+ a6:92:2e:5b:98:d7:0c:6a:7e:f4:bf:19:30:2d:ee:
+ 1c:5a:ee:28:f6:5c:a8:12:03:20:c7:e8:2b:b1:44:
+ 9f:b7:54:27:6e:17:fc:c0:f6:f7:ea:38:d2:c8:77:
+ ab:6a:ae:d1:ab:9f:1e:79:df:8a:51:55:aa:6c:6a:
+ 13:74:74:2f:c0:20:57:ef:f3:e1:71:da:b0:ec:62:
+ e9:8a:01:da:f6:e6:c6:5a:fe:11:61:58:5c:a0:01:
+ ec:0e:af:70:0d:72:94:a1:d4:1c:76:53:ae:39:a0:
+ cf:70:d8:d9:7c:95:18:2b:5f:36:00:2f:5c:be:a2:
+ d5:8e:0e:e3:aa:76:0c:1f:86:b3:69:fe:e4:29:0a:
+ 30:b1:ca:83:1a:f2:88:fc:91:2f:58:be:a4:a0:25:
+ 82:bf:16:b3:ca:70:09:7e:cf:29:f9:2e:58:0b:4a:
+ 3a:3c:6d:e7:05:63:d5:53:90:ed:ee:96:9e:8e:d7:
+ a8:ef:50:8b:37:bd:dc:88:f5:12:bc:04:4e:e4:f3:
+ ec:5d:9d:e6:46:14:e1:e1:6b:15:ab:f4:52:f6:12:
+ 76:ae:2d:a7:65:ec:8f:bd:90:51:52:4d:e7:cf:ba:
+ 23:01:7a:85:8b:22:41:a6:98:08:e4:33:00:c1:e2:
+ 82:b0:b2:c6:f4:6a:34:c6:a9:d7:b1:cc:c6:1a:0b:
+ ad:69:1f:89:af:e0:63:cd:51:c9:36:7f:08:f0:31:
+ 97:ea:78:bb:ae:21:4c:aa:2d:32:de:36:03:cf:64:
+ f8:8a:c0:c5:b3:c4:f9:79:74:7a:8b:d5:ec:bf:19:
+ 87:c9:25:0c:99:7d:56:a3:93:68:97:c3:cc:08:fb:
+ 37:c0:2c:cb:87:f2:b4:4e:fe:ce:86:69:2b:8e:c3:
+ 9e:40:a9:b6:43:6e:d6:b6:3d:08:43:24:09:58:8d:
+ af:d2:5d:1c:0e:cd:bc:e3:0b:b3:4b:a5:69:a8:3c:
+ d7:07:d0:7f:d7:78:c7:5c:a4:9f:e1:a2:bc:76:77:
+ 80:25:0e:82:2b:43:1e:e4:67:49:47:d9:65:45:57:
+ ed:59:d7:6e:a1:8d:76:a0:c2:65:52:c8:c8:57:5d:
+ dd:b4:d2:4f:27:a5:08:f1:88:7e:d2:3e:5d:60:c6:
+ 67:fb:c9:19:e7:78:cc:41:6d:24:11:cd:a4:e6:cf:
+ 56:8c:41:4d:af:d6:e2:22:c0:a3:64:2c:4b:27:f6:
+ b3:87:9d:08:e6:2a:2f:db:c8:50:57:95:a3:cf:67:
+ 77:f8:80:15:f3:45:00:47:f8:80:6e:21:b5:80:f1:
+ 81:29:45:3f:a9:8a:e2:12:12:4d:c4:90:e3:da:ab:
+ 08:80:bd
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints:
+ CA:FALSE
+ X509v3 Key Usage:
+ Digital Signature, Non Repudiation
+ X509v3 Subject Key Identifier:
+ C4:44:DE:34:6C:55:F0:21:00:F4:CF:F0:55:67:92:FB:8F:B3:40:46
+ Signature Algorithm: sha1WithRSAEncryption
+ a3:9c:c7:b7:3d:fc:8e:3d:5b:58:98:b0:05:63:fd:a7:50:c2:
+ d4:e8:c2:48:b8:b0:a8:e3:f9:c2:8b:11:47:a1:11:5e:e8:4d:
+ 75:c5:b8:d9:ec:af:81:95:1e:ec:d8:f6:8a:b6:17:12:ab:d4:
+ 30:84:cb:35:6a:c8:50:5e:1c:55:26:77:ee:84:f0:80:92:95:
+ c3:37:50:b3:23:21:7a:3b:63:5a:18:e4:48:fc:de:9b:26:50:
+ 38:9e:2f:a3:ad:03:5f:0c:b0:a1:0e:41:0b:01:71:b9:a2:df:
+ 84:f6:c4:d6:9d:8b:f7:a8:ed:cc:7e:b6:8c:5c:bc:26:0c:97:
+ 77:15:dc:fb:66:4b:0d:01:d9:8e:58:8e:1c:bf:35:47:b8:10:
+ d4:12:e5:80:09:b3:d8:4a:f4:0a:3f:6a:2f:9f:47:16:80:a7:
+ 92:6a:d4:3b:79:7b:25:b9:3e:14:a9:90:4e:92:6e:92:7b:6f:
+ 04:3a:0d:c6:63:77:82:e2:2d:e9:24:63:ce:a0:b1:8c:23:1d:
+ db:79:b8:4f:77:b8:7f:d2:49:5d:b4:60:a0:78:bb:d6:d7:56:
+ ff:23:c1:fa:46:cd:9a:2b:0d:87:df:b5:98:eb:7e:fd:af:6e:
+ 9d:03:de:d3:97:e7:19:09:20:13:ce:2e:b5:89:f0:47:ad:b2:
+ 3d:f1:5e:77:8b:dd:d3:6e:e2:a8:3c:cd:6a:22:a1:63:92:8c:
+ 2e:ca:0a:0d:aa:2c:15:98:de:27:08:e5:ee:a5:e0:e5:54:30:
+ 26:2f:32:ab:c3:de:e0:82:32:2a:dd:39:cb:3c:75:95:8f:9e:
+ 37:34:34:80:14:27:aa:c6:89:d3:8f:7a:35:19:3b:8b:c1:56:
+ 06:76:b3:0c:12:05:10:f4:5a:62:ff:d5:ef:e0:f8:da:aa:dc:
+ 2b:14:73:ad:31:c8:da:19:fe:54:51:32:0f:3b:7f:13:21:0d:
+ 5c:4f:33:e7:07:92:36:fd:01:04:d4:e6:4c:ba:dc:b4:75:c0:
+ f6:1f:3c:5a:4a:34:40:87:3b:8c:44:60:de:11:8d:18:41:0a:
+ e4:e9:d6:19:f5:7b:8f:53:3c:d8:3d:7c:4f:f4:b0:86:93:69:
+ c1:f1:e0:cd:8f:df:cd:ef:33:31:a8:e1:93:cf:bd:13:13:66:
+ 55:ef:44:63:06:0a:11:7a:78:e7:5c:6f:d0:f9:9d:bf:90:e5:
+ f4:d1:54:31:b8:0d:ed:ed:c0:e2:63:5c:13:01:ff:a8:11:c5:
+ 7d:42:e1:94:63:6a:63:99:0f:82:ef:49:f7:93:92:e6:72:d7:
+ ed:88:d6:ab:b2:25:8c:37:8d:08:22:a0:80:9b:14:fb:a4:a2:
+ 4f:43:be:ff:d4:e9:7e:79
+-----BEGIN CERTIFICATE-----
+MIIFEjCCAvqgAwIBAgIBBTANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw
+OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMCAXDTE5MDMyMjIyMjUwNVoYDzI1
+MTgxMTIxMjIyNTA1WjAyMQswCQYDVQQGEwJTRTEjMCEGA1UEAwwaVGVzdCBjZXJ0
+IERpZ2l0YWxTaWduYXR1cmUwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC
+AQDS5bYn92zB0LqKSmpOtaaSLluY1wxqfvS/GTAt7hxa7ij2XKgSAyDH6CuxRJ+3
+VCduF/zA9vfqONLId6tqrtGrnx5534pRVapsahN0dC/AIFfv8+Fx2rDsYumKAdr2
+5sZa/hFhWFygAewOr3ANcpSh1Bx2U645oM9w2Nl8lRgrXzYAL1y+otWODuOqdgwf
+hrNp/uQpCjCxyoMa8oj8kS9YvqSgJYK/FrPKcAl+zyn5LlgLSjo8becFY9VTkO3u
+lp6O16jvUIs3vdyI9RK8BE7k8+xdneZGFOHhaxWr9FL2EnauLadl7I+9kFFSTefP
+uiMBeoWLIkGmmAjkMwDB4oKwssb0ajTGqdexzMYaC61pH4mv4GPNUck2fwjwMZfq
+eLuuIUyqLTLeNgPPZPiKwMWzxPl5dHqL1ey/GYfJJQyZfVajk2iXw8wI+zfALMuH
+8rRO/s6GaSuOw55AqbZDbta2PQhDJAlYja/SXRwOzbzjC7NLpWmoPNcH0H/XeMdc
+pJ/horx2d4AlDoIrQx7kZ0lH2WVFV+1Z126hjXagwmVSyMhXXd200k8npQjxiH7S
+Pl1gxmf7yRnneMxBbSQRzaTmz1aMQU2v1uIiwKNkLEsn9rOHnQjmKi/byFBXlaPP
+Z3f4gBXzRQBH+IBuIbWA8YEpRT+piuISEk3EkOPaqwiAvQIDAQABozkwNzAJBgNV
+HRMEAjAAMAsGA1UdDwQEAwIGwDAdBgNVHQ4EFgQUxETeNGxV8CEA9M/wVWeS+4+z
+QEYwDQYJKoZIhvcNAQEFBQADggIBAKOcx7c9/I49W1iYsAVj/adQwtTowki4sKjj
++cKLEUehEV7oTXXFuNnsr4GVHuzY9oq2FxKr1DCEyzVqyFBeHFUmd+6E8ICSlcM3
+ULMjIXo7Y1oY5Ej83psmUDieL6OtA18MsKEOQQsBcbmi34T2xNadi/eo7cx+toxc
+vCYMl3cV3PtmSw0B2Y5Yjhy/NUe4ENQS5YAJs9hK9Ao/ai+fRxaAp5Jq1Dt5eyW5
+PhSpkE6SbpJ7bwQ6DcZjd4LiLekkY86gsYwjHdt5uE93uH/SSV20YKB4u9bXVv8j
+wfpGzZorDYfftZjrfv2vbp0D3tOX5xkJIBPOLrWJ8Eetsj3xXneL3dNu4qg8zWoi
+oWOSjC7KCg2qLBWY3icI5e6l4OVUMCYvMqvD3uCCMirdOcs8dZWPnjc0NIAUJ6rG
+idOPejUZO4vBVgZ2swwSBRD0WmL/1e/g+Nqq3CsUc60xyNoZ/lRRMg87fxMhDVxP
+M+cHkjb9AQTU5ky63LR1wPYfPFpKNECHO4xEYN4RjRhBCuTp1hn1e49TPNg9fE/0
+sIaTacHx4M2P383vMzGo4ZPPvRMTZlXvRGMGChF6eOdcb9D5nb+Q5fTRVDG4De3t
+wOJjXBMB/6gRxX1C4ZRjamOZD4LvSfeTkuZy1+2I1quyJYw3jQgioICbFPukok9D
+vv/U6X55
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/test-ds-only.key b/third_party/heimdal/lib/hx509/data/test-ds-only.key
new file mode 100644
index 0000000..9129038
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-ds-only.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDS5bYn92zB0LqK
+SmpOtaaSLluY1wxqfvS/GTAt7hxa7ij2XKgSAyDH6CuxRJ+3VCduF/zA9vfqONLI
+d6tqrtGrnx5534pRVapsahN0dC/AIFfv8+Fx2rDsYumKAdr25sZa/hFhWFygAewO
+r3ANcpSh1Bx2U645oM9w2Nl8lRgrXzYAL1y+otWODuOqdgwfhrNp/uQpCjCxyoMa
+8oj8kS9YvqSgJYK/FrPKcAl+zyn5LlgLSjo8becFY9VTkO3ulp6O16jvUIs3vdyI
+9RK8BE7k8+xdneZGFOHhaxWr9FL2EnauLadl7I+9kFFSTefPuiMBeoWLIkGmmAjk
+MwDB4oKwssb0ajTGqdexzMYaC61pH4mv4GPNUck2fwjwMZfqeLuuIUyqLTLeNgPP
+ZPiKwMWzxPl5dHqL1ey/GYfJJQyZfVajk2iXw8wI+zfALMuH8rRO/s6GaSuOw55A
+qbZDbta2PQhDJAlYja/SXRwOzbzjC7NLpWmoPNcH0H/XeMdcpJ/horx2d4AlDoIr
+Qx7kZ0lH2WVFV+1Z126hjXagwmVSyMhXXd200k8npQjxiH7SPl1gxmf7yRnneMxB
+bSQRzaTmz1aMQU2v1uIiwKNkLEsn9rOHnQjmKi/byFBXlaPPZ3f4gBXzRQBH+IBu
+IbWA8YEpRT+piuISEk3EkOPaqwiAvQIDAQABAoICAQDFT5tL6yY6ctGDvrmVKEhO
+bcbOySvZmyvaenNkFWk7/aQfUnMAXyLVRTdTo3OWbspxK0oTMzyhS0aRvbyHlEWg
+Pr+hoG3lSLOouNm401c1dk0vt0mOXt+2WZhLwQ6efyzHRvr1y1jlbsbuul6ohjHe
+8fcrEYFoczaBSrC36TnyoiKAq88moGwSe4WvHsCa4kiLe6j1aI5EWMaueImHW0Ij
+0kFtf4rCwze0x3tqw+FuO1iuP2Ua0mwY091rUKX62bpAxC5OsFl/7kcdb8R2WcWC
+WWAj+i3OFY17e9eLyIuxo3ab4STDrD6TSSl8Slz+MRS9Nmco1AT+GzH+ZmVoAEbp
+3LeAwXK0oGdbQqi+eSiM3mPH9KTgLs2rfqh/6oKLE/eNsU7CmLWXuMME9ORfSB+i
+dLqp3s1HWXJOS8hkJAhoJgHLEQn8XWsOtRFUw4kSgaWu23fultTv5trM3ZyaGR0o
+xDpeptKDnV85oul0nT8+Qpbj/w4MQU/INC/sxN29Qkiy3lvHE/y/C7a4GxB8DY6K
+kFUdcwT5dWw6SHqqPFxeDf3sz8Uo7RQSiXZkpHHg1U/Md456G7lgQTB5YtpZPVeY
+vJt2nlyeeP/61D0K7Im/DmS0Owenz4LyvBIiTA2gZXEbvxBd1Aq9iL/LT+GIDJJN
+dC7nbMKaHRXhcG0rysOWIQKCAQEA9+b2neaBBCEoZkH4iQteocBxgXZw60BugMIL
+v5KKh58VKC6P720d2TcL3gRfwo+9tuYcXIjn2r/mjM7N1ppDNM9/VNaelQlttK1b
+sd3C7RKjhWozWhPSfh8gHl2BKeBT+2wS26pSZX43oIyyj+sa6f7JnVbn7sGqcSFD
+js5hw3jIX3z8SR06zqUHOGes9OFn1GABvxAU70PpsCfAnMLvM9TvBopG/4RtGjBA
+HyhQYN2wdPnym32P+Ectf0z+SpVqtmTA2uy0VdbacHzhvObI+zN0/PWJhPsj4QMa
+8ycDpccwBvpD2XbkC6mEEbTJBfgbmjn+0J60hNh4+kg73Sh6hQKCAQEA2clNNbfh
+6AxN5V/MT/aPA/CONexzlAPTfpV1SS6MOcPlzhUScKzcigfMLJ5eHrXpJNRrq9cL
+TQOSQq+N8dXI0ZtmLvWFIeLq51jFe3WwCN3RuwWqOpzGHPpXaq/Ib/HUR0AMJ3uV
+ofm8kCpF9szx3xb8KeAK5Z3ZPciubETVdAj6ep7T6RrAXMHF+wXhW+yZSNju38tc
+IsZgt7LPKqElsSIbilE3qYdfVoHGKabqYZkmWTESURbWQe9wC1WnePyLv8/1ROfU
+C9U4Eh/w+WlocEa/1k6pkVu0etTh0v2bKnF4XRE6FoYbMz1dOSD4yxSTG7zKhdka
+m/3wEDYJqd3u2QKCAQEAl2ZWLZ8uIjCB9NnLiR8Jf24BpFiKpBJoqnhYJnq/4g41
+JKIzQ713YkatF73CIhgZfE9S+Oyf9UgH7O0MZ0k1TFaBZHXiyhDFEHhjrOBMAO/G
+MF/o1tWOU3p86i6fCM05XS7m4YNG6TdJj+L91sl2WXxC87W01msuxgLTuK6wpGnq
+re6uQZT5amT9YORoi/HxsJGl32NZ9bqbSPsuNk8TOauNA4iFzd25qCnZr222kUIz
+V22jTnVD7RTDY6DJGRHh51znL40qodYi+Fo8n1qvWkNV6numrjGW+wAjgGbOYnuh
+CFHmCDUFF15DC3FG6D9b1DghOJYEl7GBSRG+hdYH5QKCAQAuoGFuYcr00kWPGR51
+9DSURFk+BDyOcO9Dx53PqC6PY3h80ZgcFXY1+wtkdhdyfcHHh87xgF3EBEK5EjrS
+jtGqxplu7lOteJaQJzpIf17L1ynC36idWdk0dQhoJ/BCv0SSaIzxmwzjG8OaHeLS
+vvf9qj8cfAH5PP04tBFbzrTgXde6juyRmI+cjEPlxVGFS7dZmFA0C6bTLyOf0KF3
+3/5g2QuKZm8DVZ88txYE7t55PL+wEsh4IeqHPUsAsjrjtTX6P/yj3vpP+jtB7iK6
+Uy3v88W4jSjSnQ6byZ37fR5OTPLXAgwsrFOAed/OjleVqvb/1kCJvXxr70cJQXh6
+LLCpAoIBAFckgxXk4i3X3grFXa1nhORfvdGtxSzP1Rvq1cLdOTVxtB7Xf+18dAgZ
+3OHMW0Q6WKh4hP0pEeLpiptxhhHl0I9nFJBYAd9UrLwmLzUYYySqVQvFO2JifcY2
+Zer0KdNlej0PGjzXMcOkNXyF5IctAD7svPjZ/B3KzL88xHUumKLYhTMflaMhsqhW
+RKiMQbo2NT/38Vu3j9EWG6zbizVV9owXrb7atmR/JLZsaIS1Uory7ccIq8svFAW1
+SrQP7eZ1GDg7Kbh+0rfJf6N+Hh9Qumao97yqAYJHS/Udpw5uVhVtXeAEdR2lRoDB
+dDGZmYTPMav2jSUmg7BMOO1iyjFI0hg=
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/test-enveloped-aes-128 b/third_party/heimdal/lib/hx509/data/test-enveloped-aes-128
new file mode 100644
index 0000000..a75409b
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-enveloped-aes-128
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/test-enveloped-aes-256 b/third_party/heimdal/lib/hx509/data/test-enveloped-aes-256
new file mode 100644
index 0000000..4fda391
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-enveloped-aes-256
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/test-enveloped-des b/third_party/heimdal/lib/hx509/data/test-enveloped-des
new file mode 100644
index 0000000..944da00
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-enveloped-des
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/test-enveloped-des-ede3 b/third_party/heimdal/lib/hx509/data/test-enveloped-des-ede3
new file mode 100644
index 0000000..c27dfbc
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-enveloped-des-ede3
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/test-enveloped-rc2-128 b/third_party/heimdal/lib/hx509/data/test-enveloped-rc2-128
new file mode 100644
index 0000000..72f8158
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-enveloped-rc2-128
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/test-enveloped-rc2-40 b/third_party/heimdal/lib/hx509/data/test-enveloped-rc2-40
new file mode 100644
index 0000000..0e5eb02
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-enveloped-rc2-40
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/test-enveloped-rc2-64 b/third_party/heimdal/lib/hx509/data/test-enveloped-rc2-64
new file mode 100644
index 0000000..9ce6694
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-enveloped-rc2-64
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/test-ke-only.crt b/third_party/heimdal/lib/hx509/data/test-ke-only.crt
new file mode 100644
index 0000000..a6cc06a
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-ke-only.crt
@@ -0,0 +1,117 @@
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 4 (0x4)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: CN=hx509 Test Root CA, C=SE
+ Validity
+ Not Before: Mar 22 22:25:04 2019 GMT
+ Not After : Nov 21 22:25:04 2518 GMT
+ Subject: C=SE, CN=Test cert KeyEncipherment
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:bf:5f:55:ca:c5:c6:c5:00:a6:40:17:fc:1f:a2:
+ c7:e7:41:1b:29:37:6e:ba:7c:01:19:f3:4a:d7:c4:
+ 9a:83:17:4d:40:cd:30:d1:9f:fd:94:49:41:5c:7a:
+ 2d:32:83:81:29:15:e3:b2:1f:06:1b:f5:f3:7f:91:
+ cf:dc:82:b1:4e:d5:a9:48:da:63:49:b8:b8:41:0d:
+ cf:eb:76:df:1a:33:5a:7b:2f:ed:13:5d:ce:77:85:
+ bc:1f:52:b4:ff:96:20:48:09:19:d7:0d:55:ed:a8:
+ 9f:de:bd:26:2a:cf:2c:f4:48:d3:eb:94:f1:b4:ca:
+ 5b:6d:1b:21:82:46:98:23:84:d7:be:08:90:54:f4:
+ 46:ef:59:6e:8b:8c:7f:65:90:5a:c3:fb:c4:1d:97:
+ 9e:1a:be:82:96:d7:86:5b:d7:1a:0e:04:1f:30:71:
+ 99:70:40:28:6c:b2:16:3c:19:f1:f3:9f:54:22:9c:
+ e0:e5:2b:c9:30:a1:01:cf:7e:1f:a2:40:d7:d3:ad:
+ 23:6d:fe:55:dc:ad:87:88:ee:e8:9b:81:e8:72:8d:
+ 2a:25:58:ff:81:18:f0:24:9a:13:31:f9:30:7c:ed:
+ f1:d5:4b:13:ce:bf:83:48:47:9c:44:99:0d:52:e7:
+ 52:4f:02:91:10:fe:77:39:f3:fc:ce:04:bf:57:4e:
+ 3b:17:a3:c2:94:85:10:d6:76:a2:c0:04:45:d1:ff:
+ 96:a7:c0:a8:39:bb:7a:4c:f4:96:4c:5f:2d:63:85:
+ 52:6e:74:5d:70:7a:de:35:7c:92:9f:ed:e6:85:c8:
+ f0:1d:b7:be:29:54:78:5e:7c:4a:a2:b8:85:ee:b7:
+ 20:2d:0c:78:a6:32:be:c0:a2:89:4f:f4:c8:e0:3c:
+ 3a:4c:b3:68:a1:a7:eb:b5:c7:21:74:b9:3d:0e:07:
+ 3f:ce:35:29:b5:33:1f:ac:d8:36:dd:d1:54:3d:47:
+ c9:29:c6:26:23:e8:51:8d:25:9a:8c:96:84:74:e9:
+ f0:10:d8:96:f5:ad:22:31:8f:e9:6a:a5:9b:3b:00:
+ 93:5e:80:22:f1:3a:e5:2d:10:7b:c6:a8:b9:6b:8f:
+ ab:33:64:99:fe:aa:77:7a:0f:96:f9:3f:fe:15:6d:
+ 8e:4a:95:a7:35:9b:f4:20:cb:a2:a1:d9:f6:62:6b:
+ a7:4e:b4:22:3d:22:73:f4:7e:0d:af:62:41:7a:d2:
+ 15:ab:b9:a2:25:a8:87:e0:b5:1b:be:c0:16:d1:e4:
+ 40:5b:56:a7:ab:39:d1:85:02:f5:4f:95:3f:37:dc:
+ 97:e4:89:c8:20:ab:11:9f:d8:f1:77:d6:b0:60:4f:
+ ab:f9:88:37:ef:9f:bc:2a:f3:22:3d:2e:21:82:63:
+ c6:21:73
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints:
+ CA:FALSE
+ X509v3 Key Usage:
+ Non Repudiation, Key Encipherment
+ X509v3 Subject Key Identifier:
+ FF:78:58:BD:A5:C2:4D:D1:07:04:05:DD:15:6A:A2:2C:92:EB:54:04
+ Signature Algorithm: sha1WithRSAEncryption
+ 0d:b6:af:48:3b:0f:01:49:0b:12:d7:bc:9f:35:09:2a:42:e4:
+ d2:86:d2:c5:53:65:1b:a4:d5:52:87:28:dc:01:70:97:f3:0b:
+ 87:35:67:bb:b7:dd:f9:80:09:d3:84:33:11:2a:fe:0b:85:75:
+ 4b:d1:84:0c:46:35:d3:69:b8:fe:fc:a3:5a:c7:10:8c:2b:36:
+ c8:f0:ab:e7:f8:98:6c:b5:ec:1e:26:69:31:9b:07:29:03:ee:
+ 21:34:5c:52:1a:58:4a:c5:10:43:6b:8e:fc:9d:94:12:67:d0:
+ 12:40:55:14:f0:8f:d5:a7:a9:c7:d4:65:99:53:0d:3f:9a:23:
+ ab:13:ed:25:eb:33:56:b8:b3:ed:f5:6d:6b:a4:26:6c:80:6d:
+ 4c:27:8e:e5:5f:4d:e8:83:0b:c8:ca:17:6c:de:b9:af:ff:2f:
+ cb:9c:25:24:5f:09:e4:d9:62:a8:6e:de:da:c9:9e:1f:be:bf:
+ 19:1a:df:01:e2:dc:8c:ef:64:40:8e:b3:2a:0d:29:a9:7f:e7:
+ fa:bb:4b:76:41:c4:82:e7:07:d0:21:d5:1a:88:64:27:58:1a:
+ 8f:9e:48:e8:cb:40:d2:f0:ff:68:06:10:1b:5a:c3:1b:9f:48:
+ 52:b6:a0:8a:4c:0e:be:f3:e4:ed:a1:7a:9c:52:91:38:15:fc:
+ 92:ff:82:55:10:bd:d7:a2:1c:bb:e4:8c:56:d5:f6:c7:77:12:
+ 2f:cb:61:c6:75:a2:71:9c:4e:96:b3:0f:b6:d7:85:cb:52:0f:
+ 96:87:4a:05:15:ba:f7:31:b0:76:54:07:b8:59:38:5e:7a:03:
+ a4:87:60:e9:12:4d:aa:3a:98:d6:b9:46:a1:73:40:87:27:cf:
+ aa:87:66:e8:32:37:74:0c:93:ff:a9:ef:52:3b:a2:36:1e:16:
+ 1c:07:45:e9:65:9f:9e:de:ff:7b:b1:c4:a8:7e:59:25:79:1f:
+ da:7f:35:85:36:ea:cf:79:ff:71:96:77:28:3a:e6:af:68:f5:
+ 4c:c3:1a:20:7b:09:8d:66:15:b0:92:0a:4b:39:e4:f1:06:9e:
+ 9e:4e:f1:ca:bf:81:77:e7:00:82:79:26:0f:d1:f9:a2:4d:9a:
+ c8:7a:da:f6:d0:1e:65:04:02:2b:14:0b:84:45:eb:5d:6c:68:
+ 04:d7:a6:98:85:8c:fb:7e:de:42:63:68:5d:cd:a1:3d:4b:85:
+ 5e:e5:c3:38:a6:79:f4:02:5c:d0:ea:53:c6:91:84:08:b2:eb:
+ 2f:02:bb:5d:3b:bc:f2:e7:8d:67:44:70:0f:96:63:25:25:1a:
+ 38:1a:cc:a6:72:2d:41:23:8c:cc:95:12:4b:4f:64:91:21:79:
+ 96:46:70:8d:68:dc:dc:d5
+-----BEGIN CERTIFICATE-----
+MIIFETCCAvmgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw
+OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMCAXDTE5MDMyMjIyMjUwNFoYDzI1
+MTgxMTIxMjIyNTA0WjAxMQswCQYDVQQGEwJTRTEiMCAGA1UEAwwZVGVzdCBjZXJ0
+IEtleUVuY2lwaGVybWVudDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB
+AL9fVcrFxsUApkAX/B+ix+dBGyk3brp8ARnzStfEmoMXTUDNMNGf/ZRJQVx6LTKD
+gSkV47IfBhv183+Rz9yCsU7VqUjaY0m4uEENz+t23xozWnsv7RNdzneFvB9StP+W
+IEgJGdcNVe2on969JirPLPRI0+uU8bTKW20bIYJGmCOE174IkFT0Ru9ZbouMf2WQ
+WsP7xB2Xnhq+gpbXhlvXGg4EHzBxmXBAKGyyFjwZ8fOfVCKc4OUryTChAc9+H6JA
+19OtI23+Vdyth4ju6JuB6HKNKiVY/4EY8CSaEzH5MHzt8dVLE86/g0hHnESZDVLn
+Uk8CkRD+dznz/M4Ev1dOOxejwpSFENZ2osAERdH/lqfAqDm7ekz0lkxfLWOFUm50
+XXB63jV8kp/t5oXI8B23vilUeF58SqK4he63IC0MeKYyvsCiiU/0yOA8OkyzaKGn
+67XHIXS5PQ4HP841KbUzH6zYNt3RVD1HySnGJiPoUY0lmoyWhHTp8BDYlvWtIjGP
+6WqlmzsAk16AIvE65S0Qe8aouWuPqzNkmf6qd3oPlvk//hVtjkqVpzWb9CDLoqHZ
+9mJrp060Ij0ic/R+Da9iQXrSFau5oiWoh+C1G77AFtHkQFtWp6s50YUC9U+VPzfc
+l+SJyCCrEZ/Y8XfWsGBPq/mIN++fvCrzIj0uIYJjxiFzAgMBAAGjOTA3MAkGA1Ud
+EwQCMAAwCwYDVR0PBAQDAgVgMB0GA1UdDgQWBBT/eFi9pcJN0QcEBd0VaqIskutU
+BDANBgkqhkiG9w0BAQUFAAOCAgEADbavSDsPAUkLEte8nzUJKkLk0obSxVNlG6TV
+Uoco3AFwl/MLhzVnu7fd+YAJ04QzESr+C4V1S9GEDEY102m4/vyjWscQjCs2yPCr
+5/iYbLXsHiZpMZsHKQPuITRcUhpYSsUQQ2uO/J2UEmfQEkBVFPCP1aepx9RlmVMN
+P5ojqxPtJeszVriz7fVta6QmbIBtTCeO5V9N6IMLyMoXbN65r/8vy5wlJF8J5Nli
+qG7e2smeH76/GRrfAeLcjO9kQI6zKg0pqX/n+rtLdkHEgucH0CHVGohkJ1gaj55I
+6MtA0vD/aAYQG1rDG59IUragikwOvvPk7aF6nFKROBX8kv+CVRC916Icu+SMVtX2
+x3cSL8thxnWicZxOlrMPtteFy1IPlodKBRW69zGwdlQHuFk4XnoDpIdg6RJNqjqY
+1rlGoXNAhyfPqodm6DI3dAyT/6nvUjuiNh4WHAdF6WWfnt7/e7HEqH5ZJXkf2n81
+hTbqz3n/cZZ3KDrmr2j1TMMaIHsJjWYVsJIKSznk8Qaenk7xyr+Bd+cAgnkmD9H5
+ok2ayHra9tAeZQQCKxQLhEXrXWxoBNemmIWM+37eQmNoXc2hPUuFXuXDOKZ59AJc
+0OpTxpGECLLrLwK7XTu88ueNZ0RwD5ZjJSUaOBrMpnItQSOMzJUSS09kkSF5lkZw
+jWjc3NU=
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/test-ke-only.key b/third_party/heimdal/lib/hx509/data/test-ke-only.key
new file mode 100644
index 0000000..1b463b9
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-ke-only.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQC/X1XKxcbFAKZA
+F/wfosfnQRspN266fAEZ80rXxJqDF01AzTDRn/2USUFcei0yg4EpFeOyHwYb9fN/
+kc/cgrFO1alI2mNJuLhBDc/rdt8aM1p7L+0TXc53hbwfUrT/liBICRnXDVXtqJ/e
+vSYqzyz0SNPrlPG0ylttGyGCRpgjhNe+CJBU9EbvWW6LjH9lkFrD+8Qdl54avoKW
+14Zb1xoOBB8wcZlwQChsshY8GfHzn1QinODlK8kwoQHPfh+iQNfTrSNt/lXcrYeI
+7uibgehyjSolWP+BGPAkmhMx+TB87fHVSxPOv4NIR5xEmQ1S51JPApEQ/nc58/zO
+BL9XTjsXo8KUhRDWdqLABEXR/5anwKg5u3pM9JZMXy1jhVJudF1wet41fJKf7eaF
+yPAdt74pVHhefEqiuIXutyAtDHimMr7AoolP9MjgPDpMs2ihp+u1xyF0uT0OBz/O
+NSm1Mx+s2Dbd0VQ9R8kpxiYj6FGNJZqMloR06fAQ2Jb1rSIxj+lqpZs7AJNegCLx
+OuUtEHvGqLlrj6szZJn+qnd6D5b5P/4VbY5Klac1m/Qgy6Kh2fZia6dOtCI9InP0
+fg2vYkF60hWruaIlqIfgtRu+wBbR5EBbVqerOdGFAvVPlT833JfkicggqxGf2PF3
+1rBgT6v5iDfvn7wq8yI9LiGCY8YhcwIDAQABAoICADokNcV4Vw5tRxU79D6MTx2k
+OyNHkx2XJSKENx3cvnDLeI4SiR129SzDINd+yxKIv4oC+32XTVzbWZJNc5B0KHhi
+E59tsjKoq1ogXyYTpG6qYXgBtI5otpy7hc8iapkoPECGe1JJ2+xrib67SshAz1Cc
+e74cL18VB7fbQU/6MKjB6GX05hzZZl+7lQlSszXhKKJYcFnpQYCwlq5LZqeqb2EI
+wY0PRmXDKET1yimSXF7+7inh7bXSmrpqgElQ8T1zY98MwDHfzqhQFFh29TahvkRn
+PQHBy0amk/ca1HAfXCrog8uglrD+oF0qXIC+2zxvySL2DarTFNgHl6vj51oYC315
+pThrEPf8SZX6d7rg7t0TGAnAfYFwn9ba+cVW8YmSI78CZ/tD2kzD0QA2nnFbuQTW
+a/fwWJvPW7Fnw9S5TaCff8vYk3r4eO+R3qdR5zsxJ5io/uB6TVrFmG4JwBSOa2fR
+YvBf6SEZ/9VkQffqg6UIVhcj5BhaEIlST/lsLhgSA2nsW6ms7bfMfGjLxWrchNFy
+VKgrRC63E58vgkOw1AS8KUzzhqKvJUG2cgvZVoFylNwWY5oVI5shp08XgvoChLOS
+S8OY9MQUZby0BbXECRsa0c9/LIjk9wGILXfzORfblNE29IbLXxNsjrRnD0pzdu6k
+uGJ1khRueU9JxorWsPKRAoIBAQDeuvOyilg0wVI0Z7qSeKd/Eo9Gc7oSgiEb7uir
+XkRjWaO7H1w07b0s0pTww2GfyisgkeJgqi+k4vmYt2+gy4xHFpYJ9Pxa3cTHVRh6
+Ptb3CxXfOoE8pY3k4NH88LLz6j/3c3b8gGOUHKDBdXovPQ/uNgq5IROnMBWyopbE
+odPIErOI2Qt8bTywczCnCGaXNDtTijVvZShz3GxOlAHcL+1HIE8Sq12NehFk6MF/
+CDEd4PcIlNmTpz9/7S6fdth+tOrVo9glgC9p8TQpzE6UZEZsfD+N2nYYrmRQ/jQM
+WINC7M5rOkOu0QHMrpV7C2BWcnlcSK3xhX2RWVjCIo1ossuZAoIBAQDb9Ue32sI6
+6uAmh2dZ3EMQFTlo4pmk87YSUHaMQlr0KL/ggXxJJ2rINCxnaJXapSHqFu0X06uv
+/JaS5Hiyc1xGZdGX9UNPz4PfYDt0akGxPXtYXsLsNRpye1PGYiXeKbWWlI2Vvlpc
+wpFFf6lyXvoPZ7Pd4vjH7SgFmh3SsF84IJ6O2I6F/s4sJydROIDdmHfQRy8HpcPS
+5QOnsFwK1DKAvas9y73clAohrcfjQnLHIw1pEUtYIWXxLmVNHy73n3YeD9sajNfs
+0aypuaQ4T+BxLyqfLrCntwfdk7GljzK/ICQfsFzC/PCLZEmrMjD2cUlng7q4Ctwf
+qdURukQMtJzrAoIBAQClFm0LKP+4GpKTxU7EwilkRp1r2ttQXKOt0KckXfrSqN5z
+FAuEL7LIRk2fJzJ0/aR5v6fLfllSHepjB5P12ulex57uQmfJ8haoqKo78dfjxJOx
+oeuoyA0kWH9MvBvoLvi6sRrAjWlBnvaIbkriOKBWMDhCgAHRKhLrFRgrJseSxEnO
+ZRHeaBlTsA2fwNpJuK1AfnCc4J3bQsYEeC/oxJ1a2tfBPsNY2eGKqfrB7ZB6VQTF
+l46toomuiF7GU5CkWfS15XuQUDLUk7PWR1j3JFwOjQmOWx6trJUuczyg6fpg4KUf
+VVBVgxWSYNTrHsOJT9AkVrqXChrIYTEos/OcZuoBAoIBAQCglFfwZHdqFfDgj/em
+xcP76NLJvKyYnQeuJSn2ybanC1zRZRa8PVeao2RLdjH4tpek02nx/CkaSNgQk1V+
+SfPyvQCf5IFoscG/gPzGx4//+jejU0MQuM//BgQqD5s/rsmQDhGzYY2MrMrrpwCo
+q6f5OSc59SrUolGWjWX6W6KYUlAPTw/1yQjxeQAeLpb9sALAfkdaWO02eNULRhhc
+G4BnNpDeg3CvqTAgWENWqTssIG3455RO2csXoVx5Siu6waK03bSClJJKpORd4FaA
+eegMGXgPUEHNnzTR0bJegMV2fNuCevmtrIVb7jJOFk1ijWAefzAAjoUXZKBV2ds2
+P2FTAoIBAF7XhtL2lcAo5dPYzpOR/9p6ue1XLpZf+nbvm0mhrC/Z1jrea1e89Gzg
+TurHhSIZFUT7y9yXd2A0qDwJICKkm63XZzZ5rm4B+tfMdT9DPIxIeJMNrnatL4an
+IwgSTyvgIoKC6G93nOL9nC3Wa2AJ8dp4MeWKXa7VHGQBRc8JlPoVi9UrwMBXgGVB
+uUHvwxhUnUlsJ5kJRyF9ln2wGPba0d+HvddZZY4gPM88vn2JNleke70V0W1DkEPs
+BQBJIix7XfvXQqPHiMMaIof9IEgTHHRkhd7gYZohEZ02jlT6CwJMgkjb8+Qosfs3
+hFXFVI1+i1ntO6Nf9NvTPVfjJNWzW7Y=
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/test-nopw.p12 b/third_party/heimdal/lib/hx509/data/test-nopw.p12
new file mode 100644
index 0000000..e94aa9a
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-nopw.p12
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/test-pw.key b/third_party/heimdal/lib/hx509/data/test-pw.key
new file mode 100644
index 0000000..495eef6
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-pw.key
@@ -0,0 +1,54 @@
+-----BEGIN RSA PRIVATE KEY-----
+Proc-Type: 4,ENCRYPTED
+DEK-Info: AES-256-CBC,AE05E89E216F377B4B073A88DA8A284B
+
+4DWOJFa1qSC1Mcf/mGI09WyyEbxgbSKmRzZaPaFH7obN2o/D9zMQ6BqjnUVR6Rm7
+UXcXPpzObks/EJVyIPc/vfiGLkq/wWEiqVKWZebV4r0OhCetKdyXipiiSGLUzta8
+olQXfEthbeE9+NPB0hspGzt4owyoPuhvrgO5m+7h++iQj2ljbbUG3WLJf9Frd7eN
+GMXKJwtBUVgGPxjs89etY9JMXig9bgUDPwVhE/3VPiG+LlHeZDD5C2+gUi09d2sv
+gCN53XD1x7bFWKBzEPmGjFXMraZAd85Ew20re1RJP/R2+KJV+z72Af2DNUl3HL4f
+KgeyXkjy8xgKILnkN17hraHCwR4d/onFwjEhHyNeCHgqYSGqD5Tp80eUwHOIC8od
+Iwnw1Pe5ZrO9i1w3bdIMhOcP5jyMEAt/l3+Yc4bG34zNgRDam5V2PMYiY//OQ/Ge
+pn+Ug4WBNkab7eSOt7Dz+TskKtVy4/twBp1o6WndRwbvu3fTPkVxrOuPH1YYMmUn
+xQL/C3aMZXcjytiSHzQ09dQrOXYeT+RYcTrpXvY1RiVFawkPlBn5pSvzNG2mvXhG
+ed3iDDfBdLvqjdEeoANYOafuuuvaUBRq1ouq4sPA5zLCWmDCsH/J72RZ1ECyc2rT
+BR4Kld47cbw3+oLZmyrIfChOG/ah6IyDbF1qFiV6plmLca8JrmnCxBPbBxP4PG1f
+uT6a4ABkXbhGW3iBEzSEAjLIQssMeyHHJ6/87/+ZmvQBy02N5kwRmXRhePy1JnTF
+4LPOA/yWDqvNniOfozKvS9g3RZX5ZLKY2NQ9Xz4mPfwv3BdRbNr+8Jyf2jYJGpgQ
+pVkLdKJErW9XogbpWDbCeI5q/aA/tbwfjbM4rvH7nXhC44jzg4sHEYPmuFBpvDF0
+gNgU0mglkAFitoCh5yY688ZhbquRZF8lI2/ZwXWjmpUafkTRfrrUJSLLm3izUvtS
+R/2OBscqTiWWp7pkaivUX9/nEB7cEoXVYyE/PdbRAf3lSylgHFLfshzKkii2N1pO
+jnJ9ZUlduolaHxMMPcu5CJSEQHOavI5gLULld37iNjJwIHfh8hgaP39bcXZeVsMT
+EdePCUX2i6moBcmwuOtz2o0jGjGOmoxLv7yFAiRSCxDI04tOa0ulikf5tt/EBKKF
+p7h5/DVWN1KkbGu9Ys5xi2GBIAnyK4T7UTdWkvE4xZw6pVL0WUX/qdj42MDu4ocR
+ZP8mQqfmoiprzdO+y7J6lo4ZnRV7EK82Q2SFsoyG+Ev3vLGA6Xdr4e7cd9WFuim6
+V7eErJFpt1cHx04nJxuy43nruohDH+wOX6KZnxNQAQHoM7O5JoLGkdN/s+MNirmH
+IWUjKlm71lWTllD3UXt+sg0E9+aPbjNA8blc8zZ2VUj+3GoLt0kUTjED81TVT+Qz
+uXlGTVWUXnBYBSNN2Gbfv3/cZSHr2eraM4TiKQJ07LvgP1+VioDPG9ZyVjMVbWVT
+2Yl7xzF97O5MLIVS0HDIxIEV7MgpCF98SRXGsr4MLgG14u/FByyH6vXHNPIlDd0z
++AXnXWXEJpn73Oh6f1ht/3mXiYSNmXrr7W8kRabZmrrCajQ5Hi8eC4qV/2Z49bWu
+ryFbhI8/1+CYrkYzgFkrjptgrUHSZL0VLFINeP9uF1WNkGp3kMzW/ZZK7aksqmEM
+v5JE2HoD7+Dn7mNsHL9NfvhbH2kfwHKwrMPa9C3u5OrSX2KyyMS4UJGQ1QX+/6c4
+oYuLhslEwh+Iw1jwVentWTApNw7ONgrsxac59dOiaF/UQUBfWSDmwwlnvoAqJEVp
+l4CfetCTgZApsxKUQZWC2ls4cZDcMa3BGdyORV/5vXrxAxYQyIIkACkT3Zsxnu9V
+cjkOj/G07To8wgncc+u++yOErQ0m5OrdR0T+cJTgiyeWVgXMahiWZ5qt+GMbCzaJ
+xeKb/V6Es9ZPj2Qzqi7Sj1LRtKahh8E3XH5WVMdNKZVWZwXkd3sButezHEzB80p2
+2lhuajOolcwTfgQEtF/F/HuaokjB9r6lN0RmjUq5eIIMQ1KMRrzFsdQNDgCxGdAv
+GxjrvxOm5xM/QQ7QlXzNTxkwP4QbBDdn/nMWjAlVtQxurqtz6kxp4p03nkpToydM
+P2EeP243RpxRquadw9TqiL5IEqXdjpBon1RlKk+ZNVm4rYJWZ0UXk/CRvMeWKUeb
+Ib/0xCe2ZugyZbYQziZzrMl9WX6LKHhJP8bWA7t4Bb05bvDju0casma6gslQ/JdB
+1Ok59w59TpJYtSSEU3llMbCS4ll130/OlbKZa2Hy7LKgXkRsjVeYTBzvXC34/PKl
+v1E0PY8P6Vz60j1bxHlrEaCb+j4yxZF54cqgmvoWiKdwXSvEDw3Wb64wATFzPQKj
+T87vtU4FEVokRxgumF8BKHldKc7RPwmMuISSwG5+G7zOeOpuz7ETF4EyzX/D+a2W
+mOqX6WxS08BjzShzkdLEQtJU0TbtTPaYMQ8tVxiosypVQ+UlWh5qRtzQBodmCNYD
+3dwmrn/1IJ4LhUq0RFIczjzEP8QfkkwaNUUNp7T7DCFCn6ktkU/IBqzQf9CygfRp
+8vCdp0jMNn1JDpAW8SRvvqMlly6QeN9ndQO1Ql22k5Ihlw4yCw2/44XhEmlGsB3x
+jKEkSej5ipuQ2xX3DjFfsSKgceF0zOCGeTbw4Kt0CuwGLh6ZQLUHQktD2/BysJZu
+XH+y4NtD4Sr06DIgF43ECuTxWdptGiaDgk7neW2/1f7eLDOj8IooCHkt0a1DDzFF
+Xt5trABWgb2Qa9sjWJ89eUMc6gC48vyiLeXeaZQ5YuWcCdDcjZHY7KAvLY+r2OKN
+49O/X2WY6WmVoByoyi4S2MOER4VUbbyZEcvAqTOBcj6e4JJprtHsl4ppiDYVXVot
+U8GSYqxgNN7jyNthIti5sr/kczM3Q9peCLZN92j2CKU2wQb1qilEMkCSWpGUfyzD
+9M40fssEtIMAnwVfi8XjAezHFzdlKID0AR/b+aKndeR+4xEMdzEWkNsH452e0tRz
+vgebV+wM5Zva0+/+tG57iPQLwEpjv2septoQuuh3ACdgFkmPgcHspcu495+Wdi3g
+2Ipxrx/e1o4ragEEQXaaSSGBSCTz8qeWcvKtRm0d8fMtnERc5yzLYHRzhEm/8oc3
+-----END RSA PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/test-signed-data b/third_party/heimdal/lib/hx509/data/test-signed-data
new file mode 100644
index 0000000..1228c85
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-signed-data
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/test-signed-data-noattr b/third_party/heimdal/lib/hx509/data/test-signed-data-noattr
new file mode 100644
index 0000000..f230779
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-signed-data-noattr
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/test-signed-data-noattr-nocerts b/third_party/heimdal/lib/hx509/data/test-signed-data-noattr-nocerts
new file mode 100644
index 0000000..49fba9b
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-signed-data-noattr-nocerts
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/test-signed-sha-1 b/third_party/heimdal/lib/hx509/data/test-signed-sha-1
new file mode 100644
index 0000000..8ad1121
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-signed-sha-1
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/test-signed-sha-256 b/third_party/heimdal/lib/hx509/data/test-signed-sha-256
new file mode 100644
index 0000000..1228c85
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-signed-sha-256
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/test-signed-sha-512 b/third_party/heimdal/lib/hx509/data/test-signed-sha-512
new file mode 100644
index 0000000..1e40abe
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test-signed-sha-512
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/test.combined.crt b/third_party/heimdal/lib/hx509/data/test.combined.crt
new file mode 100644
index 0000000..a07dbf1
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test.combined.crt
@@ -0,0 +1,168 @@
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 2 (0x2)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: CN=hx509 Test Root CA, C=SE
+ Validity
+ Not Before: Mar 22 22:25:02 2019 GMT
+ Not After : Nov 21 22:25:02 2518 GMT
+ Subject: C=SE, CN=Test cert
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:da:1d:4d:ca:51:9d:f1:9f:d7:a4:7a:45:f8:75:
+ 98:66:b2:c5:7d:53:de:42:35:74:81:cd:1e:9f:f3:
+ 43:d7:a7:83:7f:fb:a2:ce:3c:44:37:80:4f:21:36:
+ a6:f6:c9:51:74:9e:e2:9b:bf:ad:e4:eb:72:11:64:
+ 36:88:b3:a9:91:63:c7:ee:38:c4:f5:8c:06:71:e5:
+ 09:b7:eb:57:5d:bf:db:5b:72:07:c5:29:e8:6f:33:
+ b3:a2:27:ef:1f:50:f0:55:33:63:41:23:e0:b2:f7:
+ 21:77:4b:ab:9d:73:2a:bb:b6:4e:88:7f:7c:e5:c6:
+ 37:3e:b6:20:c1:57:3e:6d:57:78:ef:0d:47:e9:41:
+ e7:fa:b6:2d:32:3f:42:05:8d:56:af:f5:c4:b8:6e:
+ 99:1a:e7:07:d5:a1:3f:29:7d:ce:b2:39:a6:ab:06:
+ 7a:e2:26:39:d8:96:9e:3b:c8:af:79:3e:9a:24:4e:
+ 4b:b2:af:e4:07:0e:71:dc:2f:70:27:97:3c:a2:fa:
+ 69:9b:57:4b:c5:53:5e:28:0c:b0:c7:57:1f:a2:b2:
+ 26:0f:5f:bf:d3:45:78:90:5a:2c:fc:6a:67:33:b6:
+ c1:7e:cd:17:c0:58:9e:ba:85:c5:15:5a:5a:67:db:
+ bf:2f:05:cd:38:d9:94:c9:95:7f:9b:68:b0:62:ff:
+ 37:92:cf:d8:77:be:cb:72:3d:0f:b9:80:44:57:c0:
+ c9:10:01:fd:07:25:30:eb:d8:48:05:af:98:fa:c4:
+ 64:6d:59:a6:6a:8d:1b:d4:4b:f3:07:98:68:e3:bb:
+ 59:c9:21:f8:11:b4:a2:82:1b:0d:e8:8c:e0:a5:e1:
+ 1c:71:ca:c3:2d:90:43:c3:ee:99:2c:7d:41:48:39:
+ c8:00:72:0d:80:39:23:a1:3a:27:ed:07:ca:32:8f:
+ 34:ca:bb:9d:67:13:7d:31:ed:4a:db:35:7a:ce:b3:
+ 89:e3:64:9d:3e:47:4e:d3:b7:bd:ab:12:16:10:bb:
+ 66:e8:1a:77:4c:2a:e0:b9:16:69:66:14:83:4e:4a:
+ f3:6f:ab:85:6a:70:c6:9b:ce:93:ab:75:36:a3:a5:
+ aa:9f:45:d6:a2:7f:17:c7:6f:f9:f5:e7:35:51:a5:
+ 75:c5:07:be:26:ce:7b:3f:29:3a:74:6b:17:79:4e:
+ cf:4c:0a:69:75:58:db:eb:a8:dd:f1:e6:cc:a3:18:
+ 53:a5:c5:a5:5a:a1:cf:37:6a:b1:9f:d3:d4:eb:0f:
+ 02:40:d2:ae:68:ce:bc:c5:46:e3:ee:f8:97:88:ee:
+ c8:a7:01:7a:a1:23:af:f3:31:2c:2a:6f:12:77:dc:
+ 3c:51:9d:40:f4:9a:2a:7b:85:29:1f:3e:c3:d5:37:
+ 8e:6e:09
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints:
+ CA:FALSE
+ X509v3 Key Usage:
+ Digital Signature, Non Repudiation, Key Encipherment
+ X509v3 Subject Key Identifier:
+ 1B:F4:EC:34:42:BA:8B:67:AC:55:F2:37:5D:B4:68:A9:D8:5E:58:7B
+ Signature Algorithm: sha1WithRSAEncryption
+ 95:f7:1c:99:72:42:4f:d3:bd:ba:3f:7a:75:bb:01:3a:ad:ce:
+ 6b:7b:b7:3d:5d:3b:46:51:ea:9a:36:94:70:36:1c:3b:fc:ba:
+ 9d:8b:0d:44:36:08:ad:a6:73:82:bc:23:ed:f9:5a:09:8f:9d:
+ 62:11:c1:94:7c:61:66:1f:8b:b9:0a:dc:3a:b5:eb:22:54:de:
+ a3:e5:8a:94:10:1f:84:52:6d:fe:27:c8:e5:cb:a5:8e:a9:83:
+ 16:95:0d:6c:3e:57:85:e1:ec:82:05:47:6d:28:ad:0d:84:fa:
+ 40:a0:96:f4:84:aa:d1:e1:0b:b7:91:e2:47:4f:05:97:f8:10:
+ a0:e8:57:bd:ed:48:65:55:75:da:e5:34:e8:f1:20:95:d6:40:
+ 8c:42:bf:b4:d9:55:c8:30:e8:d5:ce:d8:1d:30:65:90:39:eb:
+ e2:83:ed:11:03:cd:07:c0:e1:c4:91:84:a0:97:8e:6d:22:e6:
+ 75:77:21:7c:32:8b:48:ed:d6:b2:19:2e:af:26:ad:7d:6c:ce:
+ 09:e1:78:b6:72:61:60:22:92:b8:df:42:6b:34:6b:5f:35:ef:
+ f1:d3:c6:7f:92:05:3c:d0:08:77:01:66:f7:57:b8:65:de:d3:
+ d2:b1:bf:93:b1:8c:a3:27:e6:d4:e2:2b:9b:cd:9d:be:31:82:
+ 5b:53:dd:5a:bd:39:05:5f:8c:56:f2:7f:9b:b7:ef:e6:07:96:
+ bf:8a:d9:8d:bb:62:98:86:de:aa:91:c3:fe:e7:bb:a7:1f:f0:
+ fd:1f:6c:a6:04:04:f0:c2:51:a1:91:8c:9a:ee:f9:87:42:37:
+ 7e:9c:27:72:59:dc:60:a8:8e:d1:81:97:f1:15:c3:d8:a9:4e:
+ 9a:09:e9:81:76:39:36:b3:08:a1:e5:5e:97:37:ba:43:8f:06:
+ 1a:70:69:3b:fe:79:a6:5e:2d:26:04:e9:bc:5f:57:c9:d0:80:
+ c2:0d:4b:c7:0e:dd:04:e5:15:49:9d:d7:ff:ee:a3:1c:04:56:
+ 7d:e2:a0:d3:39:1a:59:bd:85:b0:eb:54:ea:81:8b:e1:17:94:
+ a5:fe:e3:0c:d0:74:42:ee:4a:f4:66:90:49:4b:64:bc:47:35:
+ f5:b2:60:8e:74:05:d0:a6:d2:94:b4:e0:0f:4b:3f:35:ea:2a:
+ e0:24:58:c1:6e:d0:65:6e:58:f7:e1:90:02:ae:40:23:25:e9:
+ 80:9a:d2:a7:ea:5d:fc:6d:f8:45:0f:db:53:91:55:32:46:e3:
+ 6a:c0:54:0a:5a:4c:e8:1a:1e:a6:33:3e:fe:ed:b6:ad:cf:6a:
+ 3c:2f:b2:6c:47:75:f1:29:43:31:69:c3:0c:42:56:5b:d9:b8:
+ 99:7b:ff:2b:50:87:34:2e
+-----BEGIN CERTIFICATE-----
+MIIFATCCAumgAwIBAgIBAjANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw
+OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMCAXDTE5MDMyMjIyMjUwMloYDzI1
+MTgxMTIxMjIyNTAyWjAhMQswCQYDVQQGEwJTRTESMBAGA1UEAwwJVGVzdCBjZXJ0
+MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA2h1NylGd8Z/XpHpF+HWY
+ZrLFfVPeQjV0gc0en/ND16eDf/uizjxEN4BPITam9slRdJ7im7+t5OtyEWQ2iLOp
+kWPH7jjE9YwGceUJt+tXXb/bW3IHxSnobzOzoifvH1DwVTNjQSPgsvchd0urnXMq
+u7ZOiH985cY3PrYgwVc+bVd47w1H6UHn+rYtMj9CBY1Wr/XEuG6ZGucH1aE/KX3O
+sjmmqwZ64iY52JaeO8iveT6aJE5Lsq/kBw5x3C9wJ5c8ovppm1dLxVNeKAywx1cf
+orImD1+/00V4kFos/GpnM7bBfs0XwFieuoXFFVpaZ9u/LwXNONmUyZV/m2iwYv83
+ks/Yd77Lcj0PuYBEV8DJEAH9ByUw69hIBa+Y+sRkbVmmao0b1EvzB5ho47tZySH4
+EbSighsN6IzgpeEcccrDLZBDw+6ZLH1BSDnIAHINgDkjoTon7QfKMo80yrudZxN9
+Me1K2zV6zrOJ42SdPkdO07e9qxIWELtm6Bp3TCrguRZpZhSDTkrzb6uFanDGm86T
+q3U2o6Wqn0XWon8Xx2/59ec1UaV1xQe+Js57Pyk6dGsXeU7PTAppdVjb66jd8ebM
+oxhTpcWlWqHPN2qxn9PU6w8CQNKuaM68xUbj7viXiO7IpwF6oSOv8zEsKm8Sd9w8
+UZ1A9Joqe4UpHz7D1TeObgkCAwEAAaM5MDcwCQYDVR0TBAIwADALBgNVHQ8EBAMC
+BeAwHQYDVR0OBBYEFBv07DRCuotnrFXyN120aKnYXlh7MA0GCSqGSIb3DQEBBQUA
+A4ICAQCV9xyZckJP0726P3p1uwE6rc5re7c9XTtGUeqaNpRwNhw7/Lqdiw1ENgit
+pnOCvCPt+VoJj51iEcGUfGFmH4u5Ctw6tesiVN6j5YqUEB+EUm3+J8jly6WOqYMW
+lQ1sPleF4eyCBUdtKK0NhPpAoJb0hKrR4Qu3keJHTwWX+BCg6Fe97UhlVXXa5TTo
+8SCV1kCMQr+02VXIMOjVztgdMGWQOevig+0RA80HwOHEkYSgl45tIuZ1dyF8MotI
+7dayGS6vJq19bM4J4Xi2cmFgIpK430JrNGtfNe/x08Z/kgU80Ah3AWb3V7hl3tPS
+sb+TsYyjJ+bU4iubzZ2+MYJbU91avTkFX4xW8n+bt+/mB5a/itmNu2KYht6qkcP+
+57unH/D9H2ymBATwwlGhkYya7vmHQjd+nCdyWdxgqI7RgZfxFcPYqU6aCemBdjk2
+swih5V6XN7pDjwYacGk7/nmmXi0mBOm8X1fJ0IDCDUvHDt0E5RVJndf/7qMcBFZ9
+4qDTORpZvYWw61TqgYvhF5Sl/uMM0HRC7kr0ZpBJS2S8RzX1smCOdAXQptKUtOAP
+Sz816irgJFjBbtBlblj34ZACrkAjJemAmtKn6l38bfhFD9tTkVUyRuNqwFQKWkzo
+Gh6mMz7+7batz2o8L7JsR3XxKUMxacMMQlZb2biZe/8rUIc0Lg==
+-----END CERTIFICATE-----
+-----BEGIN PRIVATE KEY-----
+MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQDaHU3KUZ3xn9ek
+ekX4dZhmssV9U95CNXSBzR6f80PXp4N/+6LOPEQ3gE8hNqb2yVF0nuKbv63k63IR
+ZDaIs6mRY8fuOMT1jAZx5Qm361ddv9tbcgfFKehvM7OiJ+8fUPBVM2NBI+Cy9yF3
+S6udcyq7tk6If3zlxjc+tiDBVz5tV3jvDUfpQef6ti0yP0IFjVav9cS4bpka5wfV
+oT8pfc6yOaarBnriJjnYlp47yK95PpokTkuyr+QHDnHcL3Anlzyi+mmbV0vFU14o
+DLDHVx+isiYPX7/TRXiQWiz8amcztsF+zRfAWJ66hcUVWlpn278vBc042ZTJlX+b
+aLBi/zeSz9h3vstyPQ+5gERXwMkQAf0HJTDr2EgFr5j6xGRtWaZqjRvUS/MHmGjj
+u1nJIfgRtKKCGw3ojOCl4RxxysMtkEPD7pksfUFIOcgAcg2AOSOhOiftB8oyjzTK
+u51nE30x7UrbNXrOs4njZJ0+R07Tt72rEhYQu2boGndMKuC5FmlmFINOSvNvq4Vq
+cMabzpOrdTajpaqfRdaifxfHb/n15zVRpXXFB74mzns/KTp0axd5Ts9MCml1WNvr
+qN3x5syjGFOlxaVaoc83arGf09TrDwJA0q5ozrzFRuPu+JeI7sinAXqhI6/zMSwq
+bxJ33DxRnUD0mip7hSkfPsPVN45uCQIDAQABAoICAQDC4zgktLSJtyb5Yf+vN3PL
+H6VyjEOlqRnG+T6J8NUHljfbXT5lRFg3tz/9D1Y0YEGWEHmubKC2UOIFRCOuFcpH
+jH6SDst+E3WWwu3iFjhkHg+kL8ldlEqJQgsZstDojGuR1W60P5iAkGyoqUZYUxU1
+0HlvYWp57JhkQlwWJRw0mtoFzzoX47mhvLG5megmCdoRM2po2PmYniHT8lX7ftv3
+R6fyXMHj3AAH1Nzh0jln/lXAZu0gZiU7YN6/vOtblLirb1B5apDbadhRtLUoCGLN
+/pwfVJCT+Bj38nsLtw8rl/pgkGTOiuCZDPnCUI9DCYhUPbzXNSLK0/fHJs2kRyKh
+Nv+skWwmHdkCnzIliutxMlzehRHvRINoQ+/U/mNTE1FaNYnNEnSxpUSMKnPYUyTD
+YBhjFjtwkRpRDzbbcMBQk7Tbj2aISvFiAz/KOtRBDmBx70IxzxvqZ/5s94lyHZ5H
+fozf6LgBfJ5dmboNqHA18oBTAQDO2UBrIxyPSYExWdJ4o0vpTqwpmk8RTwgBsYfU
+EfDj3UqO5KJHTJAqdqdhXhz2c5J6EAyxDDItNg10rEVQVQbGbTPLtI8spjWfwJ6g
+P5L0j/cJx+nxNQvhrIMQgJfCrZS92PL6Yt0OqTS44m8mJgmt4z9OqZUtoT21fmcS
+uIOMYOY/NZBc+wMJ27UoeQKCAQEA8w6aZ+NAqmdDfEi/37XsbadsxDppPZ+/Ss2b
+aWOYwNU8P65rt3+EWjLrwMugiKOH1063QmZYcj74C4iaAhLblBiQH24YtiJi9tYs
+JCcFLWp01ZEqcxqBqI2kaHd9tuIaANGM+nKZH2MwTkzZ5IX1eAqZ0qgkC7Dx0JvO
+x1fXuhRTuFwTSkKZM3w4ba5G4DgczmKQr2SXm19PsMF61YX0n7HFuss85Z6xkONH
+gF6yokmPT7k/Ly4PLXZ9kycNx2EI5s1B79iAjaJAK8ifaEfUNNIi/xBf97oX6+hy
+AhO8aiC7snt6Tf2DNaJCZR1IKeO0M+5pkN6DZfV0hbQ9ulhD6wKCAQEA5bqt2VJJ
+9Vuuu8jcRlHfc4Cbubu+bMt9gbVp33ckAtRtQGQM4tHoHdd2hv4q8lV/f/K3m6Ps
+EMGeQ6QBuCWtkqD659eI5hvkchKjF+YGx/jt7k6EUlVUU1bfKXCgQv6W2VmrckzG
+ULsedOBLeT0Keppgw4kHqx+o/5DB9G3pZnVBITqGUP471q5X+c3BbAwN+9q8yRyY
+BimYJZKx0qgmpHSZ+4l3L6eLlcQiHev7TxGw1sGkpt3OF8NmR5PEzXUYC8qoi8na
+neLwTs9NKyb6hmOwTNJiWR5PNxWJeURxfl6GIfoxyUjptIrc5dve6k+ESxGgsSI1
+vyXgRUeiMlP82wKCAQEAuqx2jl+NZNLWk/fT1d+FbFpwQO2Tso6kfrEXMYQa589d
+7JLrjA1V+2ishHBgJVFjnUuJmGe+elA+da0+i2UsW7vZxSnrtMcINwga8tE9OrpO
+bVCGx8yN1ISkxs8vMGzLB+HpYtjtHZwyl5CSsN7pvn510cLtnEUUE+H2mEexGetO
+uYOOFTS9MTuwoxx8tuyhwykUcoDRp7U2IU0YKDIvxQ7mDCbX6ItPWTYVzlPs4pOY
+i+R80KGRaptcqs4N2Rl/mrP+dlVTtnPs0TPOqmqwYrkZw8gxzLOSd88Y8NtzlBb7
+0YLgVlHkmia606n/qJyH5HKxhWBAjuhLy/y4hAwSbQKB/1xtv4SwlxEg0iy7o+Sn
+DEBsfjs8TmF3fgex9ebzCIoa7dn6ZzTbP4jCJ+4oVR8rRyEzhqwYR+J2BDcyxX5R
+qoRUQJ8HGQ18K226EeSLqC7M+O3oqVR3AHaHfUIvDkvmIstQSKq0ORZCMv7TP4qI
+BK9PbZ8+gtdW5aftlhvCHSYcBxhXc7MilvDJNJxNLIVMVFQArfQ8jO3tzklPvDwF
+a4a/YzTRGiMSRhb70r43M+WcOIovXw/ELidhdsVVrtj7Q7F62FVl4Y+kvwr2XRX/
+mMx5T3WZL/irOTPwdl9UKlWtskn5YA6cR2tcc4QH8qhTVebeMMkT+ovtsU4uhBO7
+twKCAQAnvazlAlCSy/OeRqucmyqKjWTMEey6c/5dYlCkirF9J5o3n1YHhOSp8DY8
+iEjyl6ptsASapBhD6BpI4AwI6u92WBEwG15bleMlctVmtj7v39AFwNwSvvZtBZcZ
+jJ+TWaTT0nMvP90cZe5ql2DTrp/Mp4K9+3oR5qk9+EszobSoHxpgDzLogG+Zp/k/
+2NMj125uhuC0GTV5lKcrY6JquXPtqFBKOiBLr3j5sRe+iZ4UqZEjTo91nrV2E3HD
+kFJSP1weCD2HQ48T74nS775yrQnR+mWAJjuLpyDW5UXIDpvYlSbnmJ08+4C5Mu/e
+UK2bY3PmI10F5vBYLQpLlCYUyBDf
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/test.crt b/third_party/heimdal/lib/hx509/data/test.crt
new file mode 100644
index 0000000..40663c4
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test.crt
@@ -0,0 +1,116 @@
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 2 (0x2)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: CN=hx509 Test Root CA, C=SE
+ Validity
+ Not Before: Mar 22 22:25:02 2019 GMT
+ Not After : Nov 21 22:25:02 2518 GMT
+ Subject: C=SE, CN=Test cert
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:da:1d:4d:ca:51:9d:f1:9f:d7:a4:7a:45:f8:75:
+ 98:66:b2:c5:7d:53:de:42:35:74:81:cd:1e:9f:f3:
+ 43:d7:a7:83:7f:fb:a2:ce:3c:44:37:80:4f:21:36:
+ a6:f6:c9:51:74:9e:e2:9b:bf:ad:e4:eb:72:11:64:
+ 36:88:b3:a9:91:63:c7:ee:38:c4:f5:8c:06:71:e5:
+ 09:b7:eb:57:5d:bf:db:5b:72:07:c5:29:e8:6f:33:
+ b3:a2:27:ef:1f:50:f0:55:33:63:41:23:e0:b2:f7:
+ 21:77:4b:ab:9d:73:2a:bb:b6:4e:88:7f:7c:e5:c6:
+ 37:3e:b6:20:c1:57:3e:6d:57:78:ef:0d:47:e9:41:
+ e7:fa:b6:2d:32:3f:42:05:8d:56:af:f5:c4:b8:6e:
+ 99:1a:e7:07:d5:a1:3f:29:7d:ce:b2:39:a6:ab:06:
+ 7a:e2:26:39:d8:96:9e:3b:c8:af:79:3e:9a:24:4e:
+ 4b:b2:af:e4:07:0e:71:dc:2f:70:27:97:3c:a2:fa:
+ 69:9b:57:4b:c5:53:5e:28:0c:b0:c7:57:1f:a2:b2:
+ 26:0f:5f:bf:d3:45:78:90:5a:2c:fc:6a:67:33:b6:
+ c1:7e:cd:17:c0:58:9e:ba:85:c5:15:5a:5a:67:db:
+ bf:2f:05:cd:38:d9:94:c9:95:7f:9b:68:b0:62:ff:
+ 37:92:cf:d8:77:be:cb:72:3d:0f:b9:80:44:57:c0:
+ c9:10:01:fd:07:25:30:eb:d8:48:05:af:98:fa:c4:
+ 64:6d:59:a6:6a:8d:1b:d4:4b:f3:07:98:68:e3:bb:
+ 59:c9:21:f8:11:b4:a2:82:1b:0d:e8:8c:e0:a5:e1:
+ 1c:71:ca:c3:2d:90:43:c3:ee:99:2c:7d:41:48:39:
+ c8:00:72:0d:80:39:23:a1:3a:27:ed:07:ca:32:8f:
+ 34:ca:bb:9d:67:13:7d:31:ed:4a:db:35:7a:ce:b3:
+ 89:e3:64:9d:3e:47:4e:d3:b7:bd:ab:12:16:10:bb:
+ 66:e8:1a:77:4c:2a:e0:b9:16:69:66:14:83:4e:4a:
+ f3:6f:ab:85:6a:70:c6:9b:ce:93:ab:75:36:a3:a5:
+ aa:9f:45:d6:a2:7f:17:c7:6f:f9:f5:e7:35:51:a5:
+ 75:c5:07:be:26:ce:7b:3f:29:3a:74:6b:17:79:4e:
+ cf:4c:0a:69:75:58:db:eb:a8:dd:f1:e6:cc:a3:18:
+ 53:a5:c5:a5:5a:a1:cf:37:6a:b1:9f:d3:d4:eb:0f:
+ 02:40:d2:ae:68:ce:bc:c5:46:e3:ee:f8:97:88:ee:
+ c8:a7:01:7a:a1:23:af:f3:31:2c:2a:6f:12:77:dc:
+ 3c:51:9d:40:f4:9a:2a:7b:85:29:1f:3e:c3:d5:37:
+ 8e:6e:09
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints:
+ CA:FALSE
+ X509v3 Key Usage:
+ Digital Signature, Non Repudiation, Key Encipherment
+ X509v3 Subject Key Identifier:
+ 1B:F4:EC:34:42:BA:8B:67:AC:55:F2:37:5D:B4:68:A9:D8:5E:58:7B
+ Signature Algorithm: sha1WithRSAEncryption
+ 95:f7:1c:99:72:42:4f:d3:bd:ba:3f:7a:75:bb:01:3a:ad:ce:
+ 6b:7b:b7:3d:5d:3b:46:51:ea:9a:36:94:70:36:1c:3b:fc:ba:
+ 9d:8b:0d:44:36:08:ad:a6:73:82:bc:23:ed:f9:5a:09:8f:9d:
+ 62:11:c1:94:7c:61:66:1f:8b:b9:0a:dc:3a:b5:eb:22:54:de:
+ a3:e5:8a:94:10:1f:84:52:6d:fe:27:c8:e5:cb:a5:8e:a9:83:
+ 16:95:0d:6c:3e:57:85:e1:ec:82:05:47:6d:28:ad:0d:84:fa:
+ 40:a0:96:f4:84:aa:d1:e1:0b:b7:91:e2:47:4f:05:97:f8:10:
+ a0:e8:57:bd:ed:48:65:55:75:da:e5:34:e8:f1:20:95:d6:40:
+ 8c:42:bf:b4:d9:55:c8:30:e8:d5:ce:d8:1d:30:65:90:39:eb:
+ e2:83:ed:11:03:cd:07:c0:e1:c4:91:84:a0:97:8e:6d:22:e6:
+ 75:77:21:7c:32:8b:48:ed:d6:b2:19:2e:af:26:ad:7d:6c:ce:
+ 09:e1:78:b6:72:61:60:22:92:b8:df:42:6b:34:6b:5f:35:ef:
+ f1:d3:c6:7f:92:05:3c:d0:08:77:01:66:f7:57:b8:65:de:d3:
+ d2:b1:bf:93:b1:8c:a3:27:e6:d4:e2:2b:9b:cd:9d:be:31:82:
+ 5b:53:dd:5a:bd:39:05:5f:8c:56:f2:7f:9b:b7:ef:e6:07:96:
+ bf:8a:d9:8d:bb:62:98:86:de:aa:91:c3:fe:e7:bb:a7:1f:f0:
+ fd:1f:6c:a6:04:04:f0:c2:51:a1:91:8c:9a:ee:f9:87:42:37:
+ 7e:9c:27:72:59:dc:60:a8:8e:d1:81:97:f1:15:c3:d8:a9:4e:
+ 9a:09:e9:81:76:39:36:b3:08:a1:e5:5e:97:37:ba:43:8f:06:
+ 1a:70:69:3b:fe:79:a6:5e:2d:26:04:e9:bc:5f:57:c9:d0:80:
+ c2:0d:4b:c7:0e:dd:04:e5:15:49:9d:d7:ff:ee:a3:1c:04:56:
+ 7d:e2:a0:d3:39:1a:59:bd:85:b0:eb:54:ea:81:8b:e1:17:94:
+ a5:fe:e3:0c:d0:74:42:ee:4a:f4:66:90:49:4b:64:bc:47:35:
+ f5:b2:60:8e:74:05:d0:a6:d2:94:b4:e0:0f:4b:3f:35:ea:2a:
+ e0:24:58:c1:6e:d0:65:6e:58:f7:e1:90:02:ae:40:23:25:e9:
+ 80:9a:d2:a7:ea:5d:fc:6d:f8:45:0f:db:53:91:55:32:46:e3:
+ 6a:c0:54:0a:5a:4c:e8:1a:1e:a6:33:3e:fe:ed:b6:ad:cf:6a:
+ 3c:2f:b2:6c:47:75:f1:29:43:31:69:c3:0c:42:56:5b:d9:b8:
+ 99:7b:ff:2b:50:87:34:2e
+-----BEGIN CERTIFICATE-----
+MIIFATCCAumgAwIBAgIBAjANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw
+OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMCAXDTE5MDMyMjIyMjUwMloYDzI1
+MTgxMTIxMjIyNTAyWjAhMQswCQYDVQQGEwJTRTESMBAGA1UEAwwJVGVzdCBjZXJ0
+MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA2h1NylGd8Z/XpHpF+HWY
+ZrLFfVPeQjV0gc0en/ND16eDf/uizjxEN4BPITam9slRdJ7im7+t5OtyEWQ2iLOp
+kWPH7jjE9YwGceUJt+tXXb/bW3IHxSnobzOzoifvH1DwVTNjQSPgsvchd0urnXMq
+u7ZOiH985cY3PrYgwVc+bVd47w1H6UHn+rYtMj9CBY1Wr/XEuG6ZGucH1aE/KX3O
+sjmmqwZ64iY52JaeO8iveT6aJE5Lsq/kBw5x3C9wJ5c8ovppm1dLxVNeKAywx1cf
+orImD1+/00V4kFos/GpnM7bBfs0XwFieuoXFFVpaZ9u/LwXNONmUyZV/m2iwYv83
+ks/Yd77Lcj0PuYBEV8DJEAH9ByUw69hIBa+Y+sRkbVmmao0b1EvzB5ho47tZySH4
+EbSighsN6IzgpeEcccrDLZBDw+6ZLH1BSDnIAHINgDkjoTon7QfKMo80yrudZxN9
+Me1K2zV6zrOJ42SdPkdO07e9qxIWELtm6Bp3TCrguRZpZhSDTkrzb6uFanDGm86T
+q3U2o6Wqn0XWon8Xx2/59ec1UaV1xQe+Js57Pyk6dGsXeU7PTAppdVjb66jd8ebM
+oxhTpcWlWqHPN2qxn9PU6w8CQNKuaM68xUbj7viXiO7IpwF6oSOv8zEsKm8Sd9w8
+UZ1A9Joqe4UpHz7D1TeObgkCAwEAAaM5MDcwCQYDVR0TBAIwADALBgNVHQ8EBAMC
+BeAwHQYDVR0OBBYEFBv07DRCuotnrFXyN120aKnYXlh7MA0GCSqGSIb3DQEBBQUA
+A4ICAQCV9xyZckJP0726P3p1uwE6rc5re7c9XTtGUeqaNpRwNhw7/Lqdiw1ENgit
+pnOCvCPt+VoJj51iEcGUfGFmH4u5Ctw6tesiVN6j5YqUEB+EUm3+J8jly6WOqYMW
+lQ1sPleF4eyCBUdtKK0NhPpAoJb0hKrR4Qu3keJHTwWX+BCg6Fe97UhlVXXa5TTo
+8SCV1kCMQr+02VXIMOjVztgdMGWQOevig+0RA80HwOHEkYSgl45tIuZ1dyF8MotI
+7dayGS6vJq19bM4J4Xi2cmFgIpK430JrNGtfNe/x08Z/kgU80Ah3AWb3V7hl3tPS
+sb+TsYyjJ+bU4iubzZ2+MYJbU91avTkFX4xW8n+bt+/mB5a/itmNu2KYht6qkcP+
+57unH/D9H2ymBATwwlGhkYya7vmHQjd+nCdyWdxgqI7RgZfxFcPYqU6aCemBdjk2
+swih5V6XN7pDjwYacGk7/nmmXi0mBOm8X1fJ0IDCDUvHDt0E5RVJndf/7qMcBFZ9
+4qDTORpZvYWw61TqgYvhF5Sl/uMM0HRC7kr0ZpBJS2S8RzX1smCOdAXQptKUtOAP
+Sz816irgJFjBbtBlblj34ZACrkAjJemAmtKn6l38bfhFD9tTkVUyRuNqwFQKWkzo
+Gh6mMz7+7batz2o8L7JsR3XxKUMxacMMQlZb2biZe/8rUIc0Lg==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/test.key b/third_party/heimdal/lib/hx509/data/test.key
new file mode 100644
index 0000000..03de157
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQDaHU3KUZ3xn9ek
+ekX4dZhmssV9U95CNXSBzR6f80PXp4N/+6LOPEQ3gE8hNqb2yVF0nuKbv63k63IR
+ZDaIs6mRY8fuOMT1jAZx5Qm361ddv9tbcgfFKehvM7OiJ+8fUPBVM2NBI+Cy9yF3
+S6udcyq7tk6If3zlxjc+tiDBVz5tV3jvDUfpQef6ti0yP0IFjVav9cS4bpka5wfV
+oT8pfc6yOaarBnriJjnYlp47yK95PpokTkuyr+QHDnHcL3Anlzyi+mmbV0vFU14o
+DLDHVx+isiYPX7/TRXiQWiz8amcztsF+zRfAWJ66hcUVWlpn278vBc042ZTJlX+b
+aLBi/zeSz9h3vstyPQ+5gERXwMkQAf0HJTDr2EgFr5j6xGRtWaZqjRvUS/MHmGjj
+u1nJIfgRtKKCGw3ojOCl4RxxysMtkEPD7pksfUFIOcgAcg2AOSOhOiftB8oyjzTK
+u51nE30x7UrbNXrOs4njZJ0+R07Tt72rEhYQu2boGndMKuC5FmlmFINOSvNvq4Vq
+cMabzpOrdTajpaqfRdaifxfHb/n15zVRpXXFB74mzns/KTp0axd5Ts9MCml1WNvr
+qN3x5syjGFOlxaVaoc83arGf09TrDwJA0q5ozrzFRuPu+JeI7sinAXqhI6/zMSwq
+bxJ33DxRnUD0mip7hSkfPsPVN45uCQIDAQABAoICAQDC4zgktLSJtyb5Yf+vN3PL
+H6VyjEOlqRnG+T6J8NUHljfbXT5lRFg3tz/9D1Y0YEGWEHmubKC2UOIFRCOuFcpH
+jH6SDst+E3WWwu3iFjhkHg+kL8ldlEqJQgsZstDojGuR1W60P5iAkGyoqUZYUxU1
+0HlvYWp57JhkQlwWJRw0mtoFzzoX47mhvLG5megmCdoRM2po2PmYniHT8lX7ftv3
+R6fyXMHj3AAH1Nzh0jln/lXAZu0gZiU7YN6/vOtblLirb1B5apDbadhRtLUoCGLN
+/pwfVJCT+Bj38nsLtw8rl/pgkGTOiuCZDPnCUI9DCYhUPbzXNSLK0/fHJs2kRyKh
+Nv+skWwmHdkCnzIliutxMlzehRHvRINoQ+/U/mNTE1FaNYnNEnSxpUSMKnPYUyTD
+YBhjFjtwkRpRDzbbcMBQk7Tbj2aISvFiAz/KOtRBDmBx70IxzxvqZ/5s94lyHZ5H
+fozf6LgBfJ5dmboNqHA18oBTAQDO2UBrIxyPSYExWdJ4o0vpTqwpmk8RTwgBsYfU
+EfDj3UqO5KJHTJAqdqdhXhz2c5J6EAyxDDItNg10rEVQVQbGbTPLtI8spjWfwJ6g
+P5L0j/cJx+nxNQvhrIMQgJfCrZS92PL6Yt0OqTS44m8mJgmt4z9OqZUtoT21fmcS
+uIOMYOY/NZBc+wMJ27UoeQKCAQEA8w6aZ+NAqmdDfEi/37XsbadsxDppPZ+/Ss2b
+aWOYwNU8P65rt3+EWjLrwMugiKOH1063QmZYcj74C4iaAhLblBiQH24YtiJi9tYs
+JCcFLWp01ZEqcxqBqI2kaHd9tuIaANGM+nKZH2MwTkzZ5IX1eAqZ0qgkC7Dx0JvO
+x1fXuhRTuFwTSkKZM3w4ba5G4DgczmKQr2SXm19PsMF61YX0n7HFuss85Z6xkONH
+gF6yokmPT7k/Ly4PLXZ9kycNx2EI5s1B79iAjaJAK8ifaEfUNNIi/xBf97oX6+hy
+AhO8aiC7snt6Tf2DNaJCZR1IKeO0M+5pkN6DZfV0hbQ9ulhD6wKCAQEA5bqt2VJJ
+9Vuuu8jcRlHfc4Cbubu+bMt9gbVp33ckAtRtQGQM4tHoHdd2hv4q8lV/f/K3m6Ps
+EMGeQ6QBuCWtkqD659eI5hvkchKjF+YGx/jt7k6EUlVUU1bfKXCgQv6W2VmrckzG
+ULsedOBLeT0Keppgw4kHqx+o/5DB9G3pZnVBITqGUP471q5X+c3BbAwN+9q8yRyY
+BimYJZKx0qgmpHSZ+4l3L6eLlcQiHev7TxGw1sGkpt3OF8NmR5PEzXUYC8qoi8na
+neLwTs9NKyb6hmOwTNJiWR5PNxWJeURxfl6GIfoxyUjptIrc5dve6k+ESxGgsSI1
+vyXgRUeiMlP82wKCAQEAuqx2jl+NZNLWk/fT1d+FbFpwQO2Tso6kfrEXMYQa589d
+7JLrjA1V+2ishHBgJVFjnUuJmGe+elA+da0+i2UsW7vZxSnrtMcINwga8tE9OrpO
+bVCGx8yN1ISkxs8vMGzLB+HpYtjtHZwyl5CSsN7pvn510cLtnEUUE+H2mEexGetO
+uYOOFTS9MTuwoxx8tuyhwykUcoDRp7U2IU0YKDIvxQ7mDCbX6ItPWTYVzlPs4pOY
+i+R80KGRaptcqs4N2Rl/mrP+dlVTtnPs0TPOqmqwYrkZw8gxzLOSd88Y8NtzlBb7
+0YLgVlHkmia606n/qJyH5HKxhWBAjuhLy/y4hAwSbQKB/1xtv4SwlxEg0iy7o+Sn
+DEBsfjs8TmF3fgex9ebzCIoa7dn6ZzTbP4jCJ+4oVR8rRyEzhqwYR+J2BDcyxX5R
+qoRUQJ8HGQ18K226EeSLqC7M+O3oqVR3AHaHfUIvDkvmIstQSKq0ORZCMv7TP4qI
+BK9PbZ8+gtdW5aftlhvCHSYcBxhXc7MilvDJNJxNLIVMVFQArfQ8jO3tzklPvDwF
+a4a/YzTRGiMSRhb70r43M+WcOIovXw/ELidhdsVVrtj7Q7F62FVl4Y+kvwr2XRX/
+mMx5T3WZL/irOTPwdl9UKlWtskn5YA6cR2tcc4QH8qhTVebeMMkT+ovtsU4uhBO7
+twKCAQAnvazlAlCSy/OeRqucmyqKjWTMEey6c/5dYlCkirF9J5o3n1YHhOSp8DY8
+iEjyl6ptsASapBhD6BpI4AwI6u92WBEwG15bleMlctVmtj7v39AFwNwSvvZtBZcZ
+jJ+TWaTT0nMvP90cZe5ql2DTrp/Mp4K9+3oR5qk9+EszobSoHxpgDzLogG+Zp/k/
+2NMj125uhuC0GTV5lKcrY6JquXPtqFBKOiBLr3j5sRe+iZ4UqZEjTo91nrV2E3HD
+kFJSP1weCD2HQ48T74nS775yrQnR+mWAJjuLpyDW5UXIDpvYlSbnmJ08+4C5Mu/e
+UK2bY3PmI10F5vBYLQpLlCYUyBDf
+-----END PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/data/test.p12 b/third_party/heimdal/lib/hx509/data/test.p12
new file mode 100644
index 0000000..32d9c81
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/test.p12
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/win-u16-in-printablestring.der b/third_party/heimdal/lib/hx509/data/win-u16-in-printablestring.der
new file mode 100644
index 0000000..5f6178f
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/win-u16-in-printablestring.der
Binary files differ
diff --git a/third_party/heimdal/lib/hx509/data/yutaka-pad-broken-ca.pem b/third_party/heimdal/lib/hx509/data/yutaka-pad-broken-ca.pem
new file mode 100644
index 0000000..32685d1
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/yutaka-pad-broken-ca.pem
@@ -0,0 +1,16 @@
+-----BEGIN CERTIFICATE-----
+MIICijCCAfOgAwIBAgIJAOSnzE4Qx2H+MA0GCSqGSIb3DQEBBQUAMDkxCzAJBgNV
+BAYTAkpQMRQwEgYDVQQKEwtDQSBURVNUIDEtNDEUMBIGA1UEAxMLQ0EgVEVTVCAx
+LTQwHhcNMDYwOTA3MTYzMzE4WhcNMDYxMDA3MTYzMzE4WjA5MQswCQYDVQQGEwJK
+UDEUMBIGA1UEChMLQ0EgVEVTVCAxLTQxFDASBgNVBAMTC0NBIFRFU1QgMS00MIGd
+MA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDZfFjkPDZeorxWqk7/DKM2d/9Nao28
+dM6T5sb5L41hD5C1kXV6MJev5ALASSxtI6OVOmZO4gfubnsvcj0NTZO4SeF1yL1r
+VDPdx7juQI1cbDiG/EwIMW29UIdj9h052JTmEbpT0RuP/4JWmAWrdO5UE40xua7S
+z2/6+DB2ZklFoQIBA6OBmzCBmDAdBgNVHQ4EFgQU340JbeYcg6V9zi8aozy48aIh
+tfgwaQYDVR0jBGIwYIAU340JbeYcg6V9zi8aozy48aIhtfihPaQ7MDkxCzAJBgNV
+BAYTAkpQMRQwEgYDVQQKEwtDQSBURVNUIDEtNDEUMBIGA1UEAxMLQ0EgVEVTVCAx
+LTSCCQDkp8xOEMdh/jAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GBABsH
+aJ/c/3cGHssi8IvVRci/aavqj607y7l22nKDtG1p4KAjnfNhBMOhRhFv00nJnokK
+y0uc4DIegAW1bxQjqcMNNEmGbzAeixH/cRCot8C1LobEQmxNWCY2DJLWoI3wwqr8
+uUSnI1CDZ5402etkCiNXsDy/eYDrF+2KonkIWRrr
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/yutaka-pad-broken-cert.pem b/third_party/heimdal/lib/hx509/data/yutaka-pad-broken-cert.pem
new file mode 100644
index 0000000..b0726ea
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/yutaka-pad-broken-cert.pem
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE-----
+MIICzTCCAjagAwIBAgIJAOSnzE4Qx2H/MA0GCSqGSIb3DQEBBQUAMDkxCzAJBgNV
+BAYTAkpQMRQwEgYDVQQKEwtDQSBURVNUIDEtNDEUMBIGA1UEAxMLQ0EgVEVTVCAx
+LTQwHhcNMDYwOTA3MTY0MDM3WhcNMDcwOTA3MTY0MDM3WjBPMQswCQYDVQQGEwJK
+UDEOMAwGA1UECBMFVG9reW8xFjAUBgNVBAoTDVRFU1QgMiBDTElFTlQxGDAWBgNV
+BAMTD3d3dzIuZXhhbXBsZS5qcDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA
+vSpZ6ig9DpeKB60h7ii1RitNuvkn4INOfEXjCjPSFwmIbGJqnyWvKTiMKzguEYkG
+6CZAbsx44t3kvsVDeUd5WZBRgMoeQd1tNJBU4BXxOA8bVzdwstzaPeeufQtZDvKf
+M4ej+fo/j9lYH9udCug1huaNybcCtijzGonkddX4JEUCAwEAAaOBxjCBwzAJBgNV
+HRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZp
+Y2F0ZTAdBgNVHQ4EFgQUK0DZtd8K1P2ij9gVKUNcHlx7uCIwaQYDVR0jBGIwYIAU
+340JbeYcg6V9zi8aozy48aIhtfihPaQ7MDkxCzAJBgNVBAYTAkpQMRQwEgYDVQQK
+EwtDQSBURVNUIDEtNDEUMBIGA1UEAxMLQ0EgVEVTVCAxLTSCCQDkp8xOEMdh/jAN
+BgkqhkiG9w0BAQUFAAOBgQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAUKJ+eFJYSvXwGF2wxzDXj+x5YCItrHFmrEy4AXXAW+H0NgJVNvqRY/O
+Kw==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/yutaka-pad-ok-ca.pem b/third_party/heimdal/lib/hx509/data/yutaka-pad-ok-ca.pem
new file mode 100644
index 0000000..32685d1
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/yutaka-pad-ok-ca.pem
@@ -0,0 +1,16 @@
+-----BEGIN CERTIFICATE-----
+MIICijCCAfOgAwIBAgIJAOSnzE4Qx2H+MA0GCSqGSIb3DQEBBQUAMDkxCzAJBgNV
+BAYTAkpQMRQwEgYDVQQKEwtDQSBURVNUIDEtNDEUMBIGA1UEAxMLQ0EgVEVTVCAx
+LTQwHhcNMDYwOTA3MTYzMzE4WhcNMDYxMDA3MTYzMzE4WjA5MQswCQYDVQQGEwJK
+UDEUMBIGA1UEChMLQ0EgVEVTVCAxLTQxFDASBgNVBAMTC0NBIFRFU1QgMS00MIGd
+MA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDZfFjkPDZeorxWqk7/DKM2d/9Nao28
+dM6T5sb5L41hD5C1kXV6MJev5ALASSxtI6OVOmZO4gfubnsvcj0NTZO4SeF1yL1r
+VDPdx7juQI1cbDiG/EwIMW29UIdj9h052JTmEbpT0RuP/4JWmAWrdO5UE40xua7S
+z2/6+DB2ZklFoQIBA6OBmzCBmDAdBgNVHQ4EFgQU340JbeYcg6V9zi8aozy48aIh
+tfgwaQYDVR0jBGIwYIAU340JbeYcg6V9zi8aozy48aIhtfihPaQ7MDkxCzAJBgNV
+BAYTAkpQMRQwEgYDVQQKEwtDQSBURVNUIDEtNDEUMBIGA1UEAxMLQ0EgVEVTVCAx
+LTSCCQDkp8xOEMdh/jAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GBABsH
+aJ/c/3cGHssi8IvVRci/aavqj607y7l22nKDtG1p4KAjnfNhBMOhRhFv00nJnokK
+y0uc4DIegAW1bxQjqcMNNEmGbzAeixH/cRCot8C1LobEQmxNWCY2DJLWoI3wwqr8
+uUSnI1CDZ5402etkCiNXsDy/eYDrF+2KonkIWRrr
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/yutaka-pad-ok-cert.pem b/third_party/heimdal/lib/hx509/data/yutaka-pad-ok-cert.pem
new file mode 100644
index 0000000..9a89e59
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/yutaka-pad-ok-cert.pem
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE-----
+MIICzTCCAjagAwIBAgIJAOSnzE4Qx2H/MA0GCSqGSIb3DQEBBQUAMDkxCzAJBgNV
+BAYTAkpQMRQwEgYDVQQKEwtDQSBURVNUIDEtNDEUMBIGA1UEAxMLQ0EgVEVTVCAx
+LTQwHhcNMDYwOTA3MTY0MDM3WhcNMDcwOTA3MTY0MDM3WjBPMQswCQYDVQQGEwJK
+UDEOMAwGA1UECBMFVG9reW8xFjAUBgNVBAoTDVRFU1QgMiBDTElFTlQxGDAWBgNV
+BAMTD3d3dzIuZXhhbXBsZS5qcDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA
+vSpZ6ig9DpeKB60h7ii1RitNuvkn4INOfEXjCjPSFwmIbGJqnyWvKTiMKzguEYkG
+6CZAbsx44t3kvsVDeUd5WZBRgMoeQd1tNJBU4BXxOA8bVzdwstzaPeeufQtZDvKf
+M4ej+fo/j9lYH9udCug1huaNybcCtijzGonkddX4JEUCAwEAAaOBxjCBwzAJBgNV
+HRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZp
+Y2F0ZTAdBgNVHQ4EFgQUK0DZtd8K1P2ij9gVKUNcHlx7uCIwaQYDVR0jBGIwYIAU
+340JbeYcg6V9zi8aozy48aIhtfihPaQ7MDkxCzAJBgNVBAYTAkpQMRQwEgYDVQQK
+EwtDQSBURVNUIDEtNDEUMBIGA1UEAxMLQ0EgVEVTVCAxLTSCCQDkp8xOEMdh/jAN
+BgkqhkiG9w0BAQUFAAOBgQCkGhwCDLRwWbDnDFReXkIZ1/9OhfiR8yL1idP9iYVU
+cSoWxSHPBWkv6LORFS03APcXCSzDPJ9pxTjFjGGFSI91fNrzkKdHU/+0WCF2uTh7
+Dz2blqtcmnJqMSn1xHxxfM/9e6M3XwFUMf7SGiKRAbDfsauPafEPTn83vSeKj1lg
+Dw==
+-----END CERTIFICATE-----
diff --git a/third_party/heimdal/lib/hx509/data/yutaka-pad.key b/third_party/heimdal/lib/hx509/data/yutaka-pad.key
new file mode 100644
index 0000000..1763623
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/data/yutaka-pad.key
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICXQIBAAKBgQC9KlnqKD0Ol4oHrSHuKLVGK026+Sfgg058ReMKM9IXCYhsYmqf
+Ja8pOIwrOC4RiQboJkBuzHji3eS+xUN5R3lZkFGAyh5B3W00kFTgFfE4DxtXN3Cy
+3No95659C1kO8p8zh6P5+j+P2Vgf250K6DWG5o3JtwK2KPMaieR11fgkRQIDAQAB
+AoGBAJCYvwJun713uNsFTNpv46EvmMtDiWfk9ymnglVaJ03Uy6ON11Kvy6UGxJ6E
+4zIkPFNYaghH5GAGncP1pg4exHKRGJTNcQbMf9iOsCTOuvKSWbBZpnJcFllKyESK
+PTt72D6x/cuzDXVTeWvQMoOILa09szW7aqFNIdxae4Vq7a4BAkEA6MoehuRtZ4N9
+Jtc9cIpSKOOatZ1UajWEFV2yVHaDED2kkWxKjppPzRn06LzX8LWm1RT0qe3Zyasi
+iXCXlno/+QJBANAGvY+k/+OvzWnv1yTKO8OmrMqkSzh3KAhFbiVWdQaqMSCWtKYk
+GoOKnq0PB73ExhdbTFmxC4KBPHTC2guOca0CQCD78pNebnoKUYNdYCFAGCAfD97H
+6hwadRqp6gi5uhxk/5pzY6UNDF2dXexURayfsIHktD4Xq5I9o2kiAPibXdECQQDC
+KihwlL9K02JVSMl0y1XxDfclxSd4cq9o2PUv4HymVeA43LGMiRI+SPpF6Ut+ctW6
+IzsmVDu7+chl6yD9vFyZAkA3Auv9UxKL3kPtvu5G/lrCVmwzVfAzuwtnmSfp1+M5
+yTYBz+VFSsYrdlDZ3jdLnFzVOMiIm9pZca/L93QjmXJ+
+-----END RSA PRIVATE KEY-----
diff --git a/third_party/heimdal/lib/hx509/doxygen.c b/third_party/heimdal/lib/hx509/doxygen.c
new file mode 100644
index 0000000..a6d3d9c
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/doxygen.c
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/** @mainpage Heimdal PKIX/X.509 library
+ *
+ * @section intro Introduction
+ *
+ * Heimdal libhx509 library is a implementation of the PKIX/X.509 and
+ * related protocols.
+ *
+ * PKIX/X.509 is ...
+ *
+ *
+ * Sections in this manual are:
+ * - @ref page_name
+ * - @ref page_cert
+ * - @ref page_keyset
+ * - @ref page_error
+ * - @ref page_lock
+ * - @ref page_cms
+ * - @ref page_ca
+ * - @ref page_revoke
+ * - @ref page_print
+ * - @ref page_env
+ *
+ * The project web page:
+ * http://www.h5l.org/
+ *
+ */
+
+/** @defgroup hx509 hx509 library */
+
+/** @defgroup hx509_error hx509 error functions
+ * See the @ref page_error for description and examples. */
+/** @defgroup hx509_cert hx509 certificate functions
+ * See the @ref page_cert for description and examples. */
+/** @defgroup hx509_keyset hx509 certificate store functions
+ * See the @ref page_keyset for description and examples. */
+/** @defgroup hx509_cms hx509 CMS/pkcs7 functions
+ * See the @ref page_cms for description and examples. */
+/** @defgroup hx509_crypto hx509 crypto functions */
+/** @defgroup hx509_misc hx509 misc functions */
+/** @defgroup hx509_name hx509 name functions
+ * See the @ref page_name for description and examples. */
+/** @defgroup hx509_revoke hx509 revokation checking functions
+ * See the @ref page_revoke for description and examples. */
+/** @defgroup hx509_verify hx509 verification functions */
+/** @defgroup hx509_lock hx509 lock functions
+ * See the @ref page_lock for description and examples. */
+/** @defgroup hx509_query hx509 query functions */
+/** @defgroup hx509_ca hx509 CA functions
+ * See the @ref page_ca for description and examples. */
+/** @defgroup hx509_peer hx509 certificate selecting functions */
+/** @defgroup hx509_print hx509 printing functions */
+/** @defgroup hx509_env hx509 environment functions */
diff --git a/third_party/heimdal/lib/hx509/env.c b/third_party/heimdal/lib/hx509/env.c
new file mode 100644
index 0000000..7970438
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/env.c
@@ -0,0 +1,245 @@
+/*
+ * Copyright (c) 2007 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+/**
+ * @page page_env Hx509 environment functions
+ *
+ * See the library functions here: @ref hx509_env
+ */
+
+/**
+ * Add a new key/value pair to the hx509_env.
+ *
+ * @param context A hx509 context.
+ * @param env environment to add the environment variable too.
+ * @param key key to add
+ * @param value value to add
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_env
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_env_add(hx509_context context, hx509_env *env,
+ const char *key, const char *value)
+{
+ hx509_env n;
+
+ n = malloc(sizeof(*n));
+ if (n == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ n->type = env_string;
+ n->next = NULL;
+ n->name = strdup(key);
+ if (n->name == NULL) {
+ free(n);
+ return ENOMEM;
+ }
+ n->u.string = strdup(value);
+ if (n->u.string == NULL) {
+ free(n->name);
+ free(n);
+ return ENOMEM;
+ }
+
+ /* add to tail */
+ if (*env) {
+ hx509_env e = *env;
+ while (e->next)
+ e = e->next;
+ e->next = n;
+ } else
+ *env = n;
+
+ return 0;
+}
+
+/**
+ * Add a new key/binding pair to the hx509_env.
+ *
+ * @param context A hx509 context.
+ * @param env environment to add the environment variable too.
+ * @param key key to add
+ * @param list binding list to add
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_env
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_env_add_binding(hx509_context context, hx509_env *env,
+ const char *key, hx509_env list)
+{
+ hx509_env n;
+
+ n = malloc(sizeof(*n));
+ if (n == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ n->type = env_list;
+ n->next = NULL;
+ n->name = strdup(key);
+ if (n->name == NULL) {
+ free(n);
+ return ENOMEM;
+ }
+ n->u.list = list;
+
+ /* add to tail */
+ if (*env) {
+ hx509_env e = *env;
+ while (e->next)
+ e = e->next;
+ e->next = n;
+ } else
+ *env = n;
+
+ return 0;
+}
+
+
+/**
+ * Search the hx509_env for a length based key.
+ *
+ * @param context A hx509 context.
+ * @param env environment to add the environment variable too.
+ * @param key key to search for.
+ * @param len length of key.
+ *
+ * @return the value if the key is found, NULL otherwise.
+ *
+ * @ingroup hx509_env
+ */
+
+HX509_LIB_FUNCTION const char * HX509_LIB_CALL
+hx509_env_lfind(hx509_context context, hx509_env env,
+ const char *key, size_t len)
+{
+ while(env) {
+ if (strncmp(key, env->name ,len) == 0
+ && env->name[len] == '\0' && env->type == env_string)
+ return env->u.string;
+ env = env->next;
+ }
+ return NULL;
+}
+
+/**
+ * Search the hx509_env for a key.
+ *
+ * @param context A hx509 context.
+ * @param env environment to add the environment variable too.
+ * @param key key to search for.
+ *
+ * @return the value if the key is found, NULL otherwise.
+ *
+ * @ingroup hx509_env
+ */
+
+HX509_LIB_FUNCTION const char * HX509_LIB_CALL
+hx509_env_find(hx509_context context, hx509_env env, const char *key)
+{
+ while(env) {
+ if (strcmp(key, env->name) == 0 && env->type == env_string)
+ return env->u.string;
+ env = env->next;
+ }
+ return NULL;
+}
+
+/**
+ * Search the hx509_env for a binding.
+ *
+ * @param context A hx509 context.
+ * @param env environment to add the environment variable too.
+ * @param key key to search for.
+ *
+ * @return the binding if the key is found, NULL if not found.
+ *
+ * @ingroup hx509_env
+ */
+
+hx509_env
+hx509_env_find_binding(hx509_context context,
+ hx509_env env,
+ const char *key)
+{
+ while(env) {
+ if (strcmp(key, env->name) == 0 && env->type == env_list)
+ return env->u.list;
+ env = env->next;
+ }
+ return NULL;
+}
+
+static void
+env_free(hx509_env b)
+{
+ while(b) {
+ hx509_env next = b->next;
+
+ if (b->type == env_string)
+ free(b->u.string);
+ else if (b->type == env_list)
+ env_free(b->u.list);
+
+ free(b->name);
+ free(b);
+ b = next;
+ }
+}
+
+/**
+ * Free an hx509_env environment context.
+ *
+ * @param env the environment to free.
+ *
+ * @ingroup hx509_env
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_env_free(hx509_env *env)
+{
+ if (*env)
+ env_free(*env);
+ *env = NULL;
+}
diff --git a/third_party/heimdal/lib/hx509/error.c b/third_party/heimdal/lib/hx509/error.c
new file mode 100644
index 0000000..aee4f79
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/error.c
@@ -0,0 +1,220 @@
+/*
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+/**
+ * @page page_error Hx509 error reporting functions
+ *
+ * See the library functions here: @ref hx509_error
+ */
+
+struct hx509_error_data {
+ hx509_error next;
+ int code;
+ char *msg;
+};
+
+/**
+ * Resets the error strings the hx509 context.
+ *
+ * @param context A hx509 context.
+ *
+ * @ingroup hx509_error
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_clear_error_string(hx509_context context)
+{
+ if (context) {
+ heim_release(context->error);
+ context->error = NULL;
+ }
+}
+
+/**
+ * Add an error message to the hx509 context.
+ *
+ * @param context A hx509 context.
+ * @param flags
+ * - HX509_ERROR_APPEND appends the error string to the old messages
+ (code is updated).
+ * @param code error code related to error message
+ * @param fmt error message format
+ * @param ap arguments to error message format
+ *
+ * @ingroup hx509_error
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_set_error_stringv(hx509_context context, int flags, int code,
+ const char *fmt, va_list ap)
+{
+ heim_error_t msg;
+
+ if (context == NULL)
+ return;
+
+ msg = heim_error_createv(code, fmt, ap);
+ if (msg) {
+ if (flags & HX509_ERROR_APPEND)
+ heim_error_append(msg, context->error);
+ heim_release(context->error);
+ }
+ context->error = msg;
+}
+
+/**
+ * See hx509_set_error_stringv().
+ *
+ * @param context A hx509 context.
+ * @param flags
+ * - HX509_ERROR_APPEND appends the error string to the old messages
+ (code is updated).
+ * @param code error code related to error message
+ * @param fmt error message format
+ * @param ... arguments to error message format
+ *
+ * @ingroup hx509_error
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_set_error_string(hx509_context context, int flags, int code,
+ const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ hx509_set_error_stringv(context, flags, code, fmt, ap);
+ va_end(ap);
+}
+
+/**
+ * Sets ENOMEM as the error on a hx509 context.
+ *
+ * @param context A hx509 context.
+ *
+ * @ingroup hx509_error
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_enomem(hx509_context context)
+{
+ return heim_enomem(context->hcontext);
+}
+
+/**
+ * Get an error string from context associated with error_code.
+ *
+ * @param context A hx509 context.
+ * @param error_code Get error message for this error code.
+ *
+ * @return error string, free with hx509_free_error_string().
+ *
+ * @ingroup hx509_error
+ */
+
+HX509_LIB_FUNCTION char * HX509_LIB_CALL
+hx509_get_error_string(hx509_context context, int error_code)
+{
+ heim_string_t s = NULL;
+ const char *cstr = NULL;
+ char *str;
+
+ if (context) {
+ if (context->error &&
+ heim_error_get_code(context->error) == error_code &&
+ (s = heim_error_copy_string(context->error)))
+ cstr = heim_string_get_utf8(s);
+
+ if (cstr == NULL)
+ cstr = com_right(context->et_list, error_code);
+
+ if (cstr == NULL && error_code > -1)
+ cstr = strerror(error_code);
+ } /* else this could be an error in hx509_context_init() */
+
+ if (cstr == NULL)
+ cstr = error_message(error_code); /* never returns NULL */
+
+ str = strdup(cstr);
+ heim_release(s);
+ return str;
+}
+
+/**
+ * Free error string returned by hx509_get_error_string().
+ *
+ * @param str error string to free.
+ *
+ * @ingroup hx509_error
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_free_error_string(char *str)
+{
+ free(str);
+}
+
+/**
+ * Print error message and fatally exit from error code
+ *
+ * @param context A hx509 context.
+ * @param exit_code exit() code from process.
+ * @param error_code Error code for the reason to exit.
+ * @param fmt format string with the exit message.
+ * @param ... argument to format string.
+ *
+ * @ingroup hx509_error
+ */
+
+HX509_LIB_NORETURN_FUNCTION
+ __attribute__ ((__noreturn__, __format__ (__printf__, 4, 5)))
+void HX509_LIB_CALL
+hx509_err(hx509_context context, int exit_code,
+ int error_code, const char *fmt, ...)
+{
+ va_list ap;
+ const char *msg;
+ char *str;
+ int ret;
+
+ va_start(ap, fmt);
+ ret = vasprintf(&str, fmt, ap);
+ va_end(ap);
+ msg = hx509_get_error_string(context, error_code);
+ if (msg == NULL)
+ msg = "no error";
+
+ errx(exit_code, "%s: %s", ret != -1 ? str : "ENOMEM", msg);
+}
diff --git a/third_party/heimdal/lib/hx509/file.c b/third_party/heimdal/lib/hx509/file.c
new file mode 100644
index 0000000..a22f625
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/file.c
@@ -0,0 +1,387 @@
+/*
+ * Copyright (c) 2005 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_map_file_os(const char *fn, heim_octet_string *os)
+{
+ size_t length;
+ void *data;
+ int ret;
+
+ ret = rk_undumpdata(fn, &data, &length);
+
+ os->data = data;
+ os->length = length;
+
+ return ret;
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_unmap_file_os(heim_octet_string *os)
+{
+ rk_xfree(os->data);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_write_file(const char *fn, const void *data, size_t length)
+{
+ rk_dumpdata(fn, data, length);
+ return 0;
+}
+
+/*
+ *
+ */
+
+static void
+print_pem_stamp(FILE *f, const char *type, const char *str)
+{
+ fprintf(f, "-----%s %s-----\n", type, str);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_pem_write(hx509_context context, const char *type,
+ hx509_pem_header *headers, FILE *f,
+ const void *data, size_t size)
+{
+ const char *p = data;
+ size_t length;
+ char *line;
+
+#define ENCODE_LINE_LENGTH 54
+
+ print_pem_stamp(f, "BEGIN", type);
+
+ while (headers) {
+ fprintf(f, "%s: %s\n%s",
+ headers->header, headers->value,
+ headers->next ? "" : "\n");
+ headers = headers->next;
+ }
+
+ while (size > 0) {
+ ssize_t l;
+
+ length = size;
+ if (length > ENCODE_LINE_LENGTH)
+ length = ENCODE_LINE_LENGTH;
+
+ l = rk_base64_encode(p, length, &line);
+ if (l < 0) {
+ hx509_set_error_string(context, 0, ENOMEM,
+ "malloc - out of memory");
+ return ENOMEM;
+ }
+ size -= length;
+ fprintf(f, "%s\n", line);
+ p += length;
+ free(line);
+ }
+
+ print_pem_stamp(f, "END", type);
+
+ return 0;
+}
+
+/*
+ *
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_pem_add_header(hx509_pem_header **headers,
+ const char *header, const char *value)
+{
+ hx509_pem_header *h;
+
+ h = calloc(1, sizeof(*h));
+ if (h == NULL)
+ return ENOMEM;
+ h->header = strdup(header);
+ if (h->header == NULL) {
+ free(h);
+ return ENOMEM;
+ }
+ h->value = strdup(value);
+ if (h->value == NULL) {
+ free(h->header);
+ free(h);
+ return ENOMEM;
+ }
+
+ h->next = *headers;
+ *headers = h;
+
+ return 0;
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_pem_free_header(hx509_pem_header *headers)
+{
+ hx509_pem_header *h;
+ while (headers) {
+ h = headers;
+ headers = headers->next;
+ free(h->header);
+ free(h->value);
+ free(h);
+ }
+}
+
+/*
+ *
+ */
+
+HX509_LIB_FUNCTION const char * HX509_LIB_CALL
+hx509_pem_find_header(const hx509_pem_header *h, const char *header)
+{
+ while(h) {
+ if (strcmp(header, h->header) == 0)
+ return h->value;
+ h = h->next;
+ }
+ return NULL;
+}
+
+
+/*
+ *
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_pem_read(hx509_context context,
+ FILE *f,
+ hx509_pem_read_func func,
+ void *ctx)
+{
+ hx509_pem_header *headers = NULL;
+ char *type = NULL;
+ void *data = NULL;
+ size_t len = 0;
+ char buf[1024];
+ int ret = HX509_PARSING_KEY_FAILED;
+
+ enum { BEFORE, SEARCHHEADER, INHEADER, INDATA, DONE } where;
+
+ where = BEFORE;
+
+ while (fgets(buf, sizeof(buf), f) != NULL) {
+ char *p;
+ int i;
+
+ i = strcspn(buf, "\n");
+ if (buf[i] == '\n') {
+ buf[i] = '\0';
+ if (i > 0)
+ i--;
+ }
+ if (buf[i] == '\r') {
+ buf[i] = '\0';
+ if (i > 0)
+ i--;
+ }
+
+ switch (where) {
+ case BEFORE:
+ if (strncmp("-----BEGIN ", buf, 11) == 0) {
+ type = strdup(buf + 11);
+ if (type == NULL)
+ break;
+ p = strchr(type, '-');
+ if (p)
+ *p = '\0';
+ where = SEARCHHEADER;
+ }
+ break;
+ case SEARCHHEADER:
+ p = strchr(buf, ':');
+ if (p == NULL) {
+ where = INDATA;
+ goto indata;
+ }
+ fallthrough;
+ case INHEADER:
+ if (buf[0] == '\0') {
+ where = INDATA;
+ break;
+ }
+ p = strchr(buf, ':');
+ if (p) {
+ *p++ = '\0';
+ while (isspace((int)*p))
+ p++;
+ ret = hx509_pem_add_header(&headers, buf, p);
+ if (ret)
+ abort();
+ }
+ break;
+ case INDATA:
+ indata:
+
+ if (strncmp("-----END ", buf, 9) == 0) {
+ where = DONE;
+ break;
+ }
+
+ p = emalloc(i);
+ i = rk_base64_decode(buf, p);
+ if (i < 0) {
+ free(p);
+ goto out;
+ }
+
+ data = erealloc(data, len + i);
+ memcpy(((char *)data) + len, p, i);
+ free(p);
+ len += i;
+ break;
+ case DONE:
+ abort();
+ }
+
+ if (where == DONE) {
+ ret = (*func)(context, type, headers, data, len, ctx);
+ out:
+ free(data);
+ data = NULL;
+ len = 0;
+ free(type);
+ type = NULL;
+ where = BEFORE;
+ hx509_pem_free_header(headers);
+ headers = NULL;
+ if (ret)
+ break;
+ }
+ }
+
+ if (where != BEFORE) {
+ hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
+ "File ends before end of PEM end tag");
+ ret = HX509_PARSING_KEY_FAILED;
+ }
+ if (data)
+ free(data);
+ if (type)
+ free(type);
+ if (headers)
+ hx509_pem_free_header(headers);
+
+ return ret;
+}
+
+/*
+ * On modern systems there's no such thing as scrubbing a file. Not this way
+ * anyways. However, for now we'll cargo-cult this along just as in lib/krb5.
+ */
+static int
+scrub_file(int fd, ssize_t sz)
+{
+ char buf[128];
+
+ memset(buf, 0, sizeof(buf));
+ while (sz > 0) {
+ ssize_t tmp;
+ size_t wr = sizeof(buf) > sz ? (size_t)sz : sizeof(buf);
+
+ tmp = write(fd, buf, wr);
+ if (tmp == -1)
+ return errno;
+ sz -= tmp;
+ }
+#ifdef _MSC_VER
+ return _commit(fd);
+#else
+ return fsync(fd);
+#endif
+}
+
+int
+_hx509_erase_file(hx509_context context, const char *fn)
+{
+ struct stat sb1, sb2;
+ int ret;
+ int fd;
+
+ if (fn == NULL)
+ return 0;
+
+ /* This is based on _krb5_erase_file(), minus file locking */
+ ret = lstat(fn, &sb1);
+ if (ret == -1 && errno == ENOENT)
+ return 0;
+ if (ret == -1) {
+ hx509_set_error_string(context, 0, errno, "hx509_certs_destroy: "
+ "stat of \"%s\": %s", fn, strerror(errno));
+ return errno;
+ }
+
+ fd = open(fn, O_RDWR | O_BINARY | O_CLOEXEC | O_NOFOLLOW);
+ if (fd < 0)
+ return errno == ENOENT ? 0 : errno;
+ rk_cloexec(fd);
+
+ if (unlink(fn) < 0) {
+ ret = errno;
+ (void) close(fd);
+ hx509_set_error_string(context, 0, ret, "hx509_certs_destroy: "
+ "unlinking \"%s\": %s", fn, strerror(ret));
+ return ret;
+ }
+
+ /* check TOCTOU, symlinks */
+ ret = fstat(fd, &sb2);
+ if (ret < 0) {
+ ret = errno;
+ hx509_set_error_string(context, 0, ret, "hx509_certs_destroy: "
+ "fstat of %d, \"%s\": %s", fd, fn,
+ strerror(ret));
+ (void) close(fd);
+ return ret;
+ }
+ if (sb1.st_dev != sb2.st_dev || sb1.st_ino != sb2.st_ino) {
+ (void) close(fd);
+ return EPERM;
+ }
+
+ /* there are still hard links to this file */
+ if (sb2.st_nlink != 0) {
+ close(fd);
+ return 0;
+ }
+
+ ret = scrub_file(fd, sb2.st_size);
+ (void) close(fd);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/hx509/hx509.h b/third_party/heimdal/lib/hx509/hx509.h
new file mode 100644
index 0000000..75d6473
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/hx509.h
@@ -0,0 +1,221 @@
+/*
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIMDAL_HX509_H
+#define HEIMDAL_HX509_H 1
+
+#include <rfc2459_asn1.h>
+#include <rfc4108_asn1.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <heimbase.h>
+
+typedef struct hx509_cert_attribute_data *hx509_cert_attribute;
+typedef struct hx509_cert_data *hx509_cert;
+typedef struct hx509_certs_data *hx509_certs;
+typedef struct hx509_context_data *hx509_context;
+typedef struct hx509_crypto_data *hx509_crypto;
+typedef struct hx509_lock_data *hx509_lock;
+typedef struct hx509_name_data *hx509_name;
+typedef struct hx509_private_key *hx509_private_key;
+typedef struct hx509_private_key_ops hx509_private_key_ops;
+typedef struct hx509_validate_ctx_data *hx509_validate_ctx;
+typedef struct hx509_verify_ctx_data *hx509_verify_ctx;
+typedef struct hx509_revoke_ctx_data *hx509_revoke_ctx;
+typedef struct hx509_query_data hx509_query;
+typedef void * hx509_cursor;
+typedef struct hx509_request_data *hx509_request;
+typedef struct hx509_error_data *hx509_error;
+typedef struct hx509_peer_info *hx509_peer_info;
+typedef struct hx509_ca_tbs *hx509_ca_tbs;
+typedef struct hx509_env_data *hx509_env;
+typedef struct hx509_crl *hx509_crl;
+
+typedef void (*hx509_vprint_func)(void *, const char *, va_list);
+
+typedef enum {
+ HX509_SAN_TYPE_UNSUPPORTED = 0,
+ /* The following correspond to the enum GeneralName_enum values: */
+ HX509_SAN_TYPE_EMAIL = 2,
+ HX509_SAN_TYPE_DNSNAME = 3,
+ HX509_SAN_TYPE_DN = 4,
+ HX509_SAN_TYPE_REGISTERED_ID = 7,
+ /*
+ * Missing support for:
+ * - URI SANs
+ * - IP address SANs
+ * - various otherName SANs we know about (e.g., DNSSRV)
+ *
+ * The following are otherName SAN types, and assigned manually here:
+ */
+ HX509_SAN_TYPE_XMPP = 32,
+ HX509_SAN_TYPE_PKINIT = 33,
+ HX509_SAN_TYPE_MS_UPN = 34,
+ HX509_SAN_TYPE_DNSSRV = 35, /* SRVName [RFC4985] */
+ HX509_SAN_TYPE_PERMANENT_ID = 36, /* PermanentIdentifier [RFC4043] */
+ HX509_SAN_TYPE_HW_MODULE = 37, /* HardwareModuleName [RFC4108] */
+} hx509_san_type;
+
+enum {
+ HX509_VHN_F_ALLOW_NO_MATCH = 1
+};
+
+enum {
+ HX509_VALIDATE_F_VALIDATE = 1,
+ HX509_VALIDATE_F_VERBOSE = 2
+};
+
+enum {
+ HX509_CRYPTO_PADDING_PKCS7 = 0,
+ HX509_CRYPTO_PADDING_NONE = 1
+};
+
+enum {
+ HX509_KEY_FORMAT_GUESS = 0,
+ HX509_KEY_FORMAT_DER = 1,
+ HX509_KEY_FORMAT_WIN_BACKUPKEY = 2,
+ HX509_KEY_FORMAT_PKCS8 = 3,
+};
+typedef uint32_t hx509_key_format_t;
+
+struct hx509_cert_attribute_data {
+ heim_oid oid;
+ heim_octet_string data;
+};
+
+typedef enum {
+ HX509_PROMPT_TYPE_PASSWORD = 0x1, /* password, hidden */
+ HX509_PROMPT_TYPE_QUESTION = 0x2, /* question, not hidden */
+ HX509_PROMPT_TYPE_INFO = 0x4 /* infomation, reply doesn't matter */
+} hx509_prompt_type;
+
+typedef struct hx509_prompt {
+ const char *prompt;
+ hx509_prompt_type type;
+ heim_octet_string reply;
+} hx509_prompt;
+
+typedef int (*hx509_prompter_fct)(void *, const hx509_prompt *);
+
+typedef struct hx509_octet_string_list {
+ size_t len;
+ heim_octet_string *val;
+} hx509_octet_string_list;
+
+typedef struct hx509_pem_header {
+ struct hx509_pem_header *next;
+ char *header;
+ char *value;
+} hx509_pem_header;
+
+typedef int
+(*hx509_pem_read_func)(hx509_context, const char *, const hx509_pem_header *,
+ const void *, size_t, void *ctx);
+
+/*
+ * Options passed to hx509_query_match_option.
+ */
+typedef enum {
+ HX509_QUERY_OPTION_PRIVATE_KEY = 1,
+ HX509_QUERY_OPTION_KU_ENCIPHERMENT = 2,
+ HX509_QUERY_OPTION_KU_DIGITALSIGNATURE = 3,
+ HX509_QUERY_OPTION_KU_KEYCERTSIGN = 4,
+ HX509_QUERY_OPTION_END = 0xffff
+} hx509_query_option;
+
+/* flags to hx509_certs_init */
+#define HX509_CERTS_CREATE 0x01
+#define HX509_CERTS_UNPROTECT_ALL 0x02
+#define HX509_CERTS_NO_PRIVATE_KEYS 0x04
+
+/* flags to hx509_certs_store */
+#define HX509_CERTS_STORE_NO_PRIVATE_KEYS 0x04
+
+
+/* flags to hx509_set_error_string */
+#define HX509_ERROR_APPEND 0x01
+
+/* flags to hx509_cms_unenvelope */
+#define HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT 0x01
+#define HX509_CMS_UE_ALLOW_WEAK 0x02
+
+/* flags to hx509_cms_envelope_1 */
+#define HX509_CMS_EV_NO_KU_CHECK 0x01
+#define HX509_CMS_EV_ALLOW_WEAK 0x02
+#define HX509_CMS_EV_ID_NAME 0x04
+
+/* flags to hx509_cms_verify_signed */
+#define HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH 0x01
+#define HX509_CMS_VS_NO_KU_CHECK 0x02
+#define HX509_CMS_VS_ALLOW_ZERO_SIGNER 0x04
+#define HX509_CMS_VS_NO_VALIDATE 0x08
+
+/* flags from hx509_cms_verify_signed_ext (out verify_flags) */
+#define HX509_CMS_VSE_VALIDATED 0x01
+
+/* selectors passed to hx509_crypto_select and hx509_crypto_available */
+#define HX509_SELECT_ALL 0
+#define HX509_SELECT_DIGEST 1
+#define HX509_SELECT_PUBLIC_SIG 2
+#define HX509_SELECT_PUBLIC_ENC 3
+#define HX509_SELECT_SECRET_ENC 4
+
+/* flags to hx509_ca_tbs_set_template */
+#define HX509_CA_TEMPLATE_SUBJECT 1
+#define HX509_CA_TEMPLATE_SERIAL 2
+#define HX509_CA_TEMPLATE_NOTBEFORE 4
+#define HX509_CA_TEMPLATE_NOTAFTER 8
+#define HX509_CA_TEMPLATE_SPKI 16
+#define HX509_CA_TEMPLATE_KU 32
+#define HX509_CA_TEMPLATE_EKU 64
+#define HX509_CA_TEMPLATE_PKINIT_MAX_LIFE 128
+
+/* flags hx509_cms_create_signed* */
+#define HX509_CMS_SIGNATURE_DETACHED 0x01
+#define HX509_CMS_SIGNATURE_ID_NAME 0x02
+#define HX509_CMS_SIGNATURE_NO_SIGNER 0x04
+#define HX509_CMS_SIGNATURE_LEAF_ONLY 0x08
+#define HX509_CMS_SIGNATURE_NO_CERTS 0x10
+
+/* hx509_verify_hostname nametype */
+typedef enum {
+ HX509_HN_HOSTNAME = 0,
+ HX509_HN_DNSSRV
+} hx509_hostname_type;
+
+#include <hx509-protos.h>
+#include <hx509_err.h>
+
+#endif /* HEIMDAL_HX509_H */
diff --git a/third_party/heimdal/lib/hx509/hx509_err.et b/third_party/heimdal/lib/hx509/hx509_err.et
new file mode 100644
index 0000000..db81f5d
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/hx509_err.et
@@ -0,0 +1,110 @@
+#
+# Error messages for the hx509 library
+#
+# This might look like a com_err file, but is not
+#
+id "$Id$"
+
+error_table hx
+prefix HX509
+
+# path validation and construction related errors
+error_code BAD_TIMEFORMAT, "ASN.1 failed call to system time library"
+error_code EXTENSION_NOT_FOUND, "Extension not found"
+error_code NO_PATH, "Certification path not found"
+error_code PARENT_NOT_CA, "Parent certificate is not a CA"
+error_code CA_PATH_TOO_DEEP, "CA path too deep"
+error_code SIG_ALG_NO_SUPPORTED, "Signature algorithm not supported"
+error_code SIG_ALG_DONT_MATCH_KEY_ALG, "Signature algorithm doesn't match certificate key"
+error_code CERT_USED_BEFORE_TIME, "Certificate used before it became valid"
+error_code CERT_USED_AFTER_TIME, "Certificate used after it became invalid"
+error_code PRIVATE_KEY_MISSING, "Private key required for the operation is missing"
+error_code ALG_NOT_SUPP, "Algorithm not supported"
+error_code ISSUER_NOT_FOUND, "Issuer couldn't be found"
+error_code VERIFY_CONSTRAINTS, "Error verifying constraints"
+error_code RANGE, "Number too large"
+error_code NAME_CONSTRAINT_ERROR, "Error while verifying name constraints"
+error_code PATH_TOO_LONG, "Path is too long, failed to find valid anchor"
+error_code KU_CERT_MISSING, "Required keyusage for this certificate is missing"
+error_code CERT_NOT_FOUND, "Certificate not found"
+error_code UNKNOWN_LOCK_COMMAND, "Unknown lock command"
+error_code PARENT_IS_CA, "Parent certificate is a CA"
+error_code EXTRA_DATA_AFTER_STRUCTURE, "Extra data was found after the structure"
+error_code PROXY_CERT_INVALID, "Proxy certificate is invalid"
+error_code PROXY_CERT_NAME_WRONG, "Proxy certificate name is wrong"
+error_code NAME_MALFORMED, "Name is malformed"
+error_code CERTIFICATE_MALFORMED, "Certificate is malformed"
+error_code CERTIFICATE_MISSING_EKU, "Certificate is missing a required EKU"
+error_code PROXY_CERTIFICATE_NOT_CANONICALIZED, "Proxy certificate not canonicalized"
+error_code NO_ITEM, "No such item / iteration end"
+
+# cms related errors
+index 32
+prefix HX509_CMS
+error_code FAILED_CREATE_SIGATURE, "Failed to create signature"
+error_code MISSING_SIGNER_DATA, "Missing signer data"
+error_code SIGNER_NOT_FOUND, "Couldn't find signers certificate"
+error_code NO_DATA_AVAILABLE, "No data to perform the operation on"
+error_code INVALID_DATA, "Data in the message is invalid"
+error_code PADDING_ERROR, "Padding in the message invalid"
+error_code NO_RECIPIENT_CERTIFICATE, "Couldn't find recipient certificate"
+error_code DATA_OID_MISMATCH, "Mismatch bewteen signed type and unsigned type"
+
+# crypto related errors
+index 64
+prefix HX509_CRYPTO
+error_code INTERNAL_ERROR, "Internal error in the crypto engine"
+error_code EXTERNAL_ERROR, "External error in the crypto engine"
+error_code SIGNATURE_MISSING, "Signature missing for data"
+error_code BAD_SIGNATURE, "Signature is not valid"
+error_code SIG_NO_CONF, "Sigature doesn't provide confidentiality"
+error_code SIG_INVALID_FORMAT, "Invalid format on signature"
+error_code OID_MISMATCH, "Mismatch between oids"
+error_code NO_PROMPTER, "No prompter function defined"
+error_code SIGNATURE_WITHOUT_SIGNER, "Signature requires signer, but none available"
+error_code RSA_PUBLIC_ENCRYPT, "RSA public encyption failed"
+error_code RSA_PRIVATE_ENCRYPT, "RSA private encyption failed"
+error_code RSA_PUBLIC_DECRYPT, "RSA public decryption failed"
+error_code RSA_PRIVATE_DECRYPT, "RSA private decryption failed"
+error_code ALGORITHM_BEST_BEFORE, "Algorithm has passed its best before date"
+error_code KEY_FORMAT_UNSUPPORTED, "Key format is unsupported"
+
+# revoke related errors
+index 96
+prefix HX509
+error_code CRL_USED_BEFORE_TIME, "CRL used before it became valid"
+error_code CRL_USED_AFTER_TIME, "CRL used after it became invalid"
+error_code CRL_INVALID_FORMAT, "CRL have invalid format"
+error_code CERT_REVOKED, "Certificate is revoked"
+error_code REVOKE_STATUS_MISSING, "No revoke status found for certificates"
+error_code CRL_UNKNOWN_EXTENSION, "Unknown extension"
+error_code REVOKE_WRONG_DATA, "Got wrong CRL/OCSP data from server"
+error_code REVOKE_NOT_SAME_PARENT, "Doesn't have same parent as other certificates"
+error_code CERT_NOT_IN_OCSP, "Certificates not in OCSP reply"
+
+# misc error
+index 108
+error_code LOCAL_ATTRIBUTE_MISSING, "No local key attribute"
+error_code PARSING_KEY_FAILED, "Failed to parse key"
+error_code UNSUPPORTED_OPERATION, "Unsupported operation"
+error_code UNIMPLEMENTED_OPERATION, "Unimplemented operation"
+error_code PARSING_NAME_FAILED, "Failed to parse name"
+
+# keystore related error
+index 128
+prefix HX509_PKCS11
+error_code NO_SLOT, "No smartcard reader/device found"
+error_code NO_TOKEN, "No smartcard in reader"
+error_code NO_MECH, "No supported mech(s)"
+error_code TOKEN_CONFUSED, "Token or slot failed in inconsistent way"
+error_code OPEN_SESSION, "Failed to open session to slot"
+error_code LOGIN, "Failed to login to slot"
+error_code LOAD, "Failed to load PKCS module"
+
+# pkinit related errors
+error_code PIN_INCORRECT, "Incorrect User PIN"
+error_code PIN_LOCKED, "User PIN locked"
+error_code PIN_NOT_INITIALIZED, "User PIN not initialized"
+error_code PIN_EXPIRED, "User PIN expired"
+
+end
diff --git a/third_party/heimdal/lib/hx509/hx_locl.h b/third_party/heimdal/lib/hx509/hx_locl.h
new file mode 100644
index 0000000..d653f7d
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/hx_locl.h
@@ -0,0 +1,330 @@
+/*
+ * Copyright (c) 2004 - 2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#include <config.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include <errno.h>
+#ifdef HAVE_STRINGS_H
+#include <strings.h>
+#endif
+#include <assert.h>
+#include <stdarg.h>
+#include <err.h>
+#include <limits.h>
+
+#include <roken.h>
+
+#include <getarg.h>
+#include <base64.h>
+#include <hex.h>
+#include <com_err.h>
+#include <parse_units.h>
+#include <parse_bytes.h>
+
+#include <krb5-types.h>
+
+#include <rfc2459_asn1.h>
+#include <rfc4108_asn1.h>
+#include <cms_asn1.h>
+#include <pkcs8_asn1.h>
+#include <pkcs9_asn1.h>
+#include <pkcs12_asn1.h>
+#include <ocsp_asn1.h>
+#include <pkcs10_asn1.h>
+#include <asn1_err.h>
+#include <pkinit_asn1.h>
+
+#include <der.h>
+
+#ifndef O_CLOEXEC
+#define O_CLOEXEC 0
+#endif
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+
+/*
+ * We use OpenSSL for EC, but to do this we need to disable cross-references
+ * between OpenSSL and hcrypto bn.h and such. Source files that use OpenSSL EC
+ * must define HEIM_NO_CRYPTO_HDRS before including this file.
+ */
+
+#define HC_DEPRECATED_CRYPTO
+#ifndef HEIM_NO_CRYPTO_HDRS
+#include "crypto-headers.h"
+#endif
+
+struct hx509_keyset_ops;
+struct hx509_collector;
+struct hx509_generate_private_context;
+typedef struct hx509_path hx509_path;
+
+#include <heimbase.h>
+
+#include <hx509.h>
+
+typedef void (*_hx509_cert_release_func)(struct hx509_cert_data *, void *);
+
+
+#include "sel.h"
+
+#include <hx509-private.h>
+#include <hx509_err.h>
+
+struct hx509_peer_info {
+ hx509_cert cert;
+ AlgorithmIdentifier *val;
+ size_t len;
+};
+
+#define HX509_CERTS_FIND_SERIALNUMBER 1
+#define HX509_CERTS_FIND_ISSUER 2
+#define HX509_CERTS_FIND_SUBJECT 4
+#define HX509_CERTS_FIND_ISSUER_KEY_ID 8
+#define HX509_CERTS_FIND_SUBJECT_KEY_ID 16
+
+struct hx509_name_data {
+ Name der_name;
+};
+
+struct hx509_path {
+ size_t len;
+ hx509_cert *val;
+};
+
+struct hx509_query_data {
+ int match;
+#define HX509_QUERY_FIND_ISSUER_CERT 0x000001
+#define HX509_QUERY_MATCH_SERIALNUMBER 0x000002
+#define HX509_QUERY_MATCH_ISSUER_NAME 0x000004
+#define HX509_QUERY_MATCH_SUBJECT_NAME 0x000008
+#define HX509_QUERY_MATCH_SUBJECT_KEY_ID 0x000010
+#define HX509_QUERY_MATCH_ISSUER_ID 0x000020
+#define HX509_QUERY_PRIVATE_KEY 0x000040
+#define HX509_QUERY_KU_ENCIPHERMENT 0x000080
+#define HX509_QUERY_KU_DIGITALSIGNATURE 0x000100
+#define HX509_QUERY_KU_KEYCERTSIGN 0x000200
+#define HX509_QUERY_KU_CRLSIGN 0x000400
+#define HX509_QUERY_KU_NONREPUDIATION 0x000800
+#define HX509_QUERY_KU_KEYAGREEMENT 0x001000
+#define HX509_QUERY_KU_DATAENCIPHERMENT 0x002000
+#define HX509_QUERY_ANCHOR 0x004000
+#define HX509_QUERY_MATCH_CERTIFICATE 0x008000
+#define HX509_QUERY_MATCH_LOCAL_KEY_ID 0x010000
+#define HX509_QUERY_NO_MATCH_PATH 0x020000
+#define HX509_QUERY_MATCH_FRIENDLY_NAME 0x040000
+#define HX509_QUERY_MATCH_FUNCTION 0x080000
+#define HX509_QUERY_MATCH_KEY_HASH_SHA1 0x100000
+#define HX509_QUERY_MATCH_TIME 0x200000
+#define HX509_QUERY_MATCH_EKU 0x400000
+#define HX509_QUERY_MATCH_EXPR 0x800000
+#define HX509_QUERY_MASK 0xffffff
+ Certificate *subject;
+ Certificate *certificate;
+ heim_integer *serial;
+ heim_octet_string *subject_id;
+ heim_octet_string *local_key_id;
+ Name *issuer_name;
+ Name *subject_name;
+ hx509_path *path;
+ char *friendlyname;
+ int (*cmp_func)(hx509_context, hx509_cert, void *);
+ void *cmp_func_ctx;
+ heim_octet_string *keyhash_sha1;
+ time_t timenow;
+ heim_oid *eku;
+ struct hx_expr *expr;
+};
+
+struct hx509_keyset_ops {
+ const char *name;
+ int flags;
+ int (*init)(hx509_context, hx509_certs, void **,
+ int, const char *, hx509_lock);
+ int (*store)(hx509_context, hx509_certs, void *, int, hx509_lock);
+ int (*free)(hx509_certs, void *);
+ int (*add)(hx509_context, hx509_certs, void *, hx509_cert);
+ int (*query)(hx509_context, hx509_certs, void *,
+ const hx509_query *, hx509_cert *);
+ int (*iter_start)(hx509_context, hx509_certs, void *, void **);
+ int (*iter)(hx509_context, hx509_certs, void *, void *, hx509_cert *);
+ int (*iter_end)(hx509_context, hx509_certs, void *, void *);
+ int (*printinfo)(hx509_context, hx509_certs,
+ void *, int (*)(void *, const char *), void *);
+ int (*getkeys)(hx509_context, hx509_certs, void *, hx509_private_key **);
+ int (*addkey)(hx509_context, hx509_certs, void *, hx509_private_key);
+ int (*destroy)(hx509_context, hx509_certs, void *);
+};
+
+struct _hx509_password {
+ size_t len;
+ char **val;
+};
+
+extern hx509_lock _hx509_empty_lock;
+
+struct hx509_context_data {
+ struct hx509_keyset_ops **ks_ops;
+ int ks_num_ops;
+ int flags;
+#define HX509_CTX_VERIFY_MISSING_OK 1
+ int ocsp_time_diff;
+#define HX509_DEFAULT_OCSP_TIME_DIFF (5*60)
+ heim_error_t error;
+ struct et_list *et_list;
+ char *querystat;
+ hx509_certs default_trust_anchors;
+ heim_context hcontext;
+ heim_config_section *cf;
+};
+
+/* _hx509_calculate_path flag field */
+#define HX509_CALCULATE_PATH_NO_ANCHOR 1
+
+/* environment */
+struct hx509_env_data {
+ enum { env_string, env_list } type;
+ char *name;
+ struct hx509_env_data *next;
+ union {
+ char *string;
+ struct hx509_env_data *list;
+ } u;
+};
+
+
+extern const AlgorithmIdentifier * _hx509_crypto_default_sig_alg;
+extern const AlgorithmIdentifier * _hx509_crypto_default_digest_alg;
+extern const AlgorithmIdentifier * _hx509_crypto_default_secret_alg;
+
+/*
+ * Private bits from crypto.c, so crypto-ec.c can also see them.
+ *
+ * This is part of the use-OpenSSL-for-EC hack.
+ */
+
+struct hx509_crypto;
+
+struct signature_alg;
+
+struct hx509_generate_private_context {
+ const heim_oid *key_oid;
+ int isCA;
+ unsigned long num_bits;
+};
+
+struct hx509_private_key_ops {
+ const char *pemtype;
+ const heim_oid *key_oid;
+ int (*available)(const hx509_private_key,
+ const AlgorithmIdentifier *);
+ int (*get_spki)(hx509_context,
+ const hx509_private_key,
+ SubjectPublicKeyInfo *);
+ int (*export)(hx509_context context,
+ const hx509_private_key,
+ hx509_key_format_t,
+ heim_octet_string *);
+ int (*import)(hx509_context, const AlgorithmIdentifier *,
+ const void *, size_t, hx509_key_format_t,
+ hx509_private_key);
+ int (*generate_private_key)(hx509_context,
+ struct hx509_generate_private_context *,
+ hx509_private_key);
+ BIGNUM *(*get_internal)(hx509_context, hx509_private_key, const char *);
+};
+
+struct hx509_private_key {
+ unsigned int ref;
+ const struct signature_alg *md;
+ const heim_oid *signature_alg;
+ union {
+ RSA *rsa;
+ void *keydata;
+ void *ecdsa; /* EC_KEY */
+ } private_key;
+ hx509_private_key_ops *ops;
+};
+
+/*
+ *
+ */
+
+struct signature_alg {
+ const char *name;
+ const heim_oid *sig_oid;
+ const AlgorithmIdentifier *sig_alg;
+ const heim_oid *key_oid;
+ const AlgorithmIdentifier *digest_alg;
+ int flags;
+#define PROVIDE_CONF 0x1
+#define REQUIRE_SIGNER 0x2
+#define SELF_SIGNED_OK 0x4
+#define WEAK_SIG_ALG 0x8
+
+#define SIG_DIGEST 0x100
+#define SIG_PUBLIC_SIG 0x200
+#define SIG_SECRET 0x400
+
+#define RA_RSA_USES_DIGEST_INFO 0x1000000
+
+ time_t best_before; /* refuse signature made after best before date */
+ const EVP_MD *(*evp_md)(void);
+ int (*verify_signature)(hx509_context context,
+ const struct signature_alg *,
+ const Certificate *,
+ const AlgorithmIdentifier *,
+ const heim_octet_string *,
+ const heim_octet_string *);
+ int (*create_signature)(hx509_context,
+ const struct signature_alg *,
+ const hx509_private_key,
+ const AlgorithmIdentifier *,
+ const heim_octet_string *,
+ AlgorithmIdentifier *,
+ heim_octet_string *);
+ int digest_size;
+};
+
+/*
+ * Configurable options
+ */
+
+#ifdef __APPLE__
+#define HX509_DEFAULT_ANCHORS "KEYCHAIN:system-anchors"
+#endif
diff --git a/third_party/heimdal/lib/hx509/hxtool-commands.in b/third_party/heimdal/lib/hx509/hxtool-commands.in
new file mode 100644
index 0000000..279095d
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/hxtool-commands.in
@@ -0,0 +1,1057 @@
+/*
+ * Copyright (c) 2005 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+/* $Id$ */
+
+command = {
+ name = "list-oids"
+ help = "List known OIDs"
+ function = "hxtool_list_oids"
+ min_args="0"
+ max_args="0"
+}
+command = {
+ name = "cms-create-sd"
+ name = "cms-sign"
+ option = {
+ long = "certificate"
+ short = "c"
+ type = "strings"
+ argument = "certificate-store"
+ help = "certificate stores to pull certificates from"
+ }
+ option = {
+ long = "signer"
+ short = "s"
+ type = "string"
+ argument = "signer-friendly-name"
+ help = "certificate to sign with"
+ }
+ option = {
+ long = "anchors"
+ type = "strings"
+ argument = "certificate-store"
+ help = "trust anchors"
+ }
+ option = {
+ long = "pool"
+ type = "strings"
+ argument = "certificate-pool"
+ help = "certificate store to pull certificates from"
+ }
+ option = {
+ long = "pass"
+ type = "strings"
+ argument = "password"
+ help = "password, prompter, or environment"
+ }
+ option = {
+ long = "peer-alg"
+ type = "strings"
+ argument = "oid"
+ help = "oid that the peer support"
+ }
+ option = {
+ long = "content-type"
+ type = "string"
+ argument = "oid"
+ help = "content type oid"
+ }
+ option = {
+ long = "content-info"
+ type = "flag"
+ help = "wrapped out-data in a ContentInfo"
+ }
+ option = {
+ long = "pem"
+ type = "flag"
+ help = "wrap out-data in PEM armor"
+ }
+ option = {
+ long = "detached-signature"
+ type = "flag"
+ help = "create a detached signature"
+ }
+ option = {
+ long = "signer"
+ type = "-flag"
+ help = "do not sign"
+ }
+ option = {
+ long = "id-by-name"
+ type = "flag"
+ help = "use subject name for CMS Identifier"
+ }
+ option = {
+ long = "embedded-certs"
+ type = "-flag"
+ help = "don't embed certificates"
+ }
+ option = {
+ long = "embed-leaf-only"
+ type = "flag"
+ help = "only embed leaf certificate"
+ }
+ min_args="1"
+ max_args="2"
+ argument="in-file out-file"
+ help = "Wrap a file within a SignedData object"
+}
+command = {
+ name = "cms-verify-sd"
+ option = {
+ long = "anchors"
+ short = "D"
+ type = "strings"
+ argument = "certificate-store"
+ help = "trust anchors"
+ }
+ option = {
+ long = "certificate"
+ short = "c"
+ type = "strings"
+ argument = "certificate-store"
+ help = "certificate store to pull certificates from"
+ }
+ option = {
+ long = "pass"
+ type = "strings"
+ argument = "password"
+ help = "password, prompter, or environment"
+ }
+ option = {
+ long = "missing-revoke"
+ type = "flag"
+ help = "missing CRL/OCSP is ok"
+ }
+ option = {
+ long = "content-info"
+ type = "flag"
+ help = "unwrap in-data that's in a ContentInfo"
+ }
+ option = {
+ long = "pem"
+ type = "flag"
+ help = "unwrap in-data from PEM armor"
+ }
+ option = {
+ long = "signer-allowed"
+ type = "-flag"
+ help = "allow no signer"
+ }
+ option = {
+ long = "allow-wrong-oid"
+ type = "flag"
+ help = "allow wrong oid flag"
+ }
+ option = {
+ long = "signed-content"
+ type = "string"
+ help = "file containing content"
+ }
+ option = {
+ long = "oid-sym"
+ type = "flag"
+ help = "show symbolic name for OID"
+ }
+ min_args="1"
+ max_args="2"
+ argument="in-file [out-file]"
+ help = "Verify a file within a SignedData object"
+}
+command = {
+ name = "cms-unenvelope"
+ option = {
+ long = "certificate"
+ short = "c"
+ type = "strings"
+ argument = "certificate-store"
+ help = "certificate used to decrypt the data"
+ }
+ option = {
+ long = "pass"
+ type = "strings"
+ argument = "password"
+ help = "password, prompter, or environment"
+ }
+ option = {
+ long = "content-info"
+ type = "flag"
+ help = "wrapped out-data in a ContentInfo"
+ }
+ option = {
+ long = "allow-weak-crypto"
+ type = "flag"
+ help = "allow weak crypto"
+ }
+ min_args="2"
+ argument="in-file out-file"
+ help = "Unenvelope a file containing a EnvelopedData object"
+}
+command = {
+ name = "cms-envelope"
+ function = "cms_create_enveloped"
+ option = {
+ long = "certificate"
+ short = "c"
+ type = "strings"
+ argument = "certificate-store"
+ help = "certificates used to receive the data"
+ }
+ option = {
+ long = "pass"
+ type = "strings"
+ argument = "password"
+ help = "password, prompter, or environment"
+ }
+ option = {
+ long = "encryption-type"
+ type = "string"
+ argument = "enctype"
+ help = "enctype"
+ }
+ option = {
+ long = "content-type"
+ type = "string"
+ argument = "oid"
+ help = "content type oid"
+ }
+ option = {
+ long = "content-info"
+ type = "flag"
+ help = "wrapped out-data in a ContentInfo"
+ }
+ option = {
+ long = "allow-weak-crypto"
+ type = "flag"
+ help = "allow weak crypto"
+ }
+ min_args="2"
+ argument="in-file out-file"
+ help = "Envelope a file containing a EnvelopedData object"
+}
+command = {
+ name = "verify"
+ function = "pcert_verify"
+ option = {
+ long = "pass"
+ type = "strings"
+ argument = "password"
+ help = "password, prompter, or environment"
+ }
+ option = {
+ long = "allow-proxy-certificate"
+ type = "flag"
+ help = "allow proxy certificates"
+ }
+ option = {
+ long = "missing-revoke"
+ type = "flag"
+ help = "missing CRL/OCSP is ok"
+ }
+ option = {
+ long = "time"
+ type = "string"
+ help = "time when to validate the chain"
+ }
+ option = {
+ long = "verbose"
+ short = "v"
+ type = "flag"
+ help = "verbose logging"
+ }
+ option = {
+ long = "max-depth"
+ type = "integer"
+ help = "maximum search length of certificate trust anchor"
+ }
+ option = {
+ long = "hostname"
+ type = "string"
+ help = "match hostname to certificate"
+ }
+ argument = "cert:foo chain:cert1 chain:cert2 anchor:anchor1 anchor:anchor2"
+ help = "Verify certificate chain"
+}
+command = {
+ name = "print"
+ function = "pcert_print"
+ option = {
+ long = "pass"
+ type = "strings"
+ argument = "password"
+ help = "password, prompter, or environment"
+ }
+ option = {
+ long = "content"
+ type = "flag"
+ help = "print the content of the certificates"
+ }
+ option = {
+ long = "raw-json"
+ type = "flag"
+ help = "print the DER content of the certificates as JSON"
+ }
+ option = {
+ long = "never-fail"
+ type = "flag"
+ help = "never fail with an error code"
+ }
+ option = {
+ long = "info"
+ type = "flag"
+ help = "print the information about the certificate store"
+ }
+ min_args="1"
+ argument="certificate ..."
+ help = "Print certificates"
+}
+command = {
+ name = "validate"
+ function = "pcert_validate"
+ option = {
+ long = "pass"
+ type = "strings"
+ argument = "password"
+ help = "password, prompter, or environment"
+ }
+ min_args="1"
+ argument="certificate ..."
+ help = "Validate content of certificates"
+}
+command = {
+ name = "certificate-copy"
+ name = "cc"
+ option = {
+ long = "in-pass"
+ type = "strings"
+ argument = "password"
+ help = "password, prompter, or environment"
+ }
+ option = {
+ long = "out-pass"
+ type = "string"
+ argument = "password"
+ help = "password, prompter, or environment"
+ }
+ min_args="2"
+ argument="in-certificates-1 ... out-certificate"
+ help = "Copy in certificates stores into out certificate store"
+}
+command = {
+ name = "ocsp-fetch"
+ option = {
+ long = "pass"
+ type = "strings"
+ argument = "password"
+ help = "password, prompter, or environment"
+ }
+ option = {
+ long = "sign"
+ type = "string"
+ argument = "certificate"
+ help = "certificate use to sign the request"
+ }
+ option = {
+ long = "url-path"
+ type = "string"
+ argument = "url"
+ help = "part after host in url to put in the request"
+ }
+ option = {
+ long = "nonce"
+ type = "-flag"
+ default = "1"
+ help = "don't include nonce in request"
+ }
+ option = {
+ long = "pool"
+ type = "strings"
+ argument = "certificate-store"
+ help = "pool to find parent certificate in"
+ }
+ min_args="2"
+ argument="outfile certs ..."
+ help = "Fetch OCSP responses for the following certs"
+}
+command = {
+ option = {
+ long = "ocsp-file"
+ type = "string"
+ help = "OCSP file"
+ }
+ name = "ocsp-verify"
+ min_args="1"
+ argument="certificates ..."
+ help = "Check that certificates are in OCSP file and valid"
+}
+command = {
+ name = "ocsp-print"
+ option = {
+ long = "verbose"
+ type = "flag"
+ help = "verbose"
+ }
+ min_args="1"
+ argument="ocsp-response-file ..."
+ help = "Print the OCSP responses"
+}
+command = {
+ name = "revoke-print"
+ option = {
+ long = "verbose"
+ type = "flag"
+ help = "verbose"
+ }
+ min_args="1"
+ argument="ocsp/crl files"
+ help = "Print the OCSP/CRL files"
+}
+command = {
+ name = "generate-key"
+ option = {
+ long = "type"
+ type = "string"
+ help = "keytype"
+ }
+ option = {
+ long = "key-bits"
+ type = "integer"
+ help = "number of bits in the generated key";
+ }
+ option = {
+ long = "verbose"
+ type = "flag"
+ help = "verbose status"
+ }
+ min_args="1"
+ max_args="1"
+ argument="output-file"
+ help = "Generate a private key"
+}
+command = {
+ name = "request-create"
+ option = {
+ long = "subject"
+ type = "string"
+ help = "Subject DN"
+ }
+ option = {
+ long = "eku"
+ type = "strings"
+ argument = "oid-string"
+ help = "Add Extended Key Usage OID"
+ }
+ option = {
+ long = "email"
+ type = "strings"
+ help = "Email address in SubjectAltName"
+ }
+ option = {
+ long = "jid"
+ type = "strings"
+ help = "XMPP (Jabber) address in SubjectAltName"
+ }
+ option = {
+ long = "dnsname"
+ type = "strings"
+ help = "Hostname or domainname in SubjectAltName"
+ }
+ option = {
+ long = "kerberos"
+ type = "strings"
+ help = "Kerberos principal name as SubjectAltName"
+ }
+ option = {
+ long = "ms-kerberos"
+ type = "strings"
+ help = "Kerberos principal name as SubjectAltName (Microsoft variant)"
+ }
+ option = {
+ long = "registered"
+ type = "strings"
+ help = "Registered object ID as SubjectAltName"
+ }
+ option = {
+ long = "dn"
+ type = "strings"
+ help = "Directory name as SubjectAltName"
+ }
+ option = {
+ long = "type"
+ type = "string"
+ help = "Type of request CRMF or PKCS10, defaults to PKCS10"
+ }
+ option = {
+ long = "key"
+ type = "string"
+ help = "Key-pair"
+ }
+ option = {
+ long = "generate-key"
+ type = "string"
+ help = "keytype"
+ }
+ option = {
+ long = "key-bits"
+ type = "integer"
+ help = "number of bits in the generated key";
+ }
+ option = {
+ long = "verbose"
+ type = "flag"
+ help = "verbose status"
+ }
+ min_args="1"
+ max_args="1"
+ argument="output-file"
+ help = "Create a CRMF or PKCS10 request"
+}
+command = {
+ name = "request-print"
+ option = {
+ long = "verbose"
+ type = "flag"
+ help = "verbose printing"
+ }
+ min_args="1"
+ argument="requests ..."
+ help = "Print requests"
+}
+command = {
+ name = "query"
+ option = {
+ long = "exact"
+ type = "flag"
+ help = "exact match"
+ }
+ option = {
+ long = "private-key"
+ type = "flag"
+ help = "search for private key"
+ }
+ option = {
+ long = "friendlyname"
+ type = "string"
+ argument = "name"
+ help = "match on friendly name"
+ }
+ option = {
+ long = "eku"
+ type = "string"
+ argument = "oid-string"
+ help = "match on EKU"
+ }
+ option = {
+ long = "expr"
+ type = "string"
+ argument = "expression"
+ help = "match on expression"
+ }
+ option = {
+ long = "keyEncipherment"
+ type = "flag"
+ help = "match keyEncipherment certificates"
+ }
+ option = {
+ long = "digitalSignature"
+ type = "flag"
+ help = "match digitalSignature certificates"
+ }
+ option = {
+ long = "print"
+ type = "flag"
+ help = "print matches"
+ }
+ option = {
+ long = "pass"
+ type = "strings"
+ argument = "password"
+ help = "password, prompter, or environment"
+ }
+ min_args="1"
+ argument="certificates ..."
+ help = "Query the certificates for a match"
+}
+command = {
+ name = "info"
+}
+command = {
+ name = "random-data"
+ min_args="1"
+ argument="bytes"
+ help = "Generates random bytes and prints them to standard output"
+}
+command = {
+ option = {
+ long = "type"
+ type = "string"
+ help = "type of CMS algorithm"
+ }
+ option = {
+ long = "oid-syms"
+ type = "flag"
+ help = "show symbolic names for OIDs"
+ }
+ name = "crypto-available"
+ min_args="0"
+ help = "Print available CMS crypto types"
+}
+command = {
+ option = {
+ long = "type"
+ type = "string"
+ help = "type of CMS algorithm"
+ }
+ option = {
+ long = "certificate"
+ type = "string"
+ help = "source certificate limiting the choices"
+ }
+ option = {
+ long = "peer-cmstype"
+ type = "strings"
+ help = "peer limiting cmstypes"
+ }
+ option = {
+ long = "oid-sym"
+ type = "flag"
+ help = "show symbolic name for OID"
+ }
+ name = "crypto-select"
+ min_args="0"
+ help = "Print selected CMS type"
+}
+command = {
+ option = {
+ long = "decode"
+ short = "d"
+ type = "flag"
+ help = "decode instead of encode"
+ }
+ name = "hex"
+ function = "hxtool_hex"
+ min_args="0"
+ help = "Encode input to hex"
+}
+command = {
+ option = {
+ long = "issue-ca"
+ type = "flag"
+ help = "Issue a CA certificate"
+ }
+ option = {
+ long = "issue-proxy"
+ type = "flag"
+ help = "Issue a proxy certificate"
+ }
+ option = {
+ long = "domain-controller"
+ type = "flag"
+ help = "Issue a MS domaincontroller certificate"
+ }
+ option = {
+ long = "subject"
+ type = "string"
+ help = "Subject of issued certificate"
+ }
+ option = {
+ long = "ca-certificate"
+ type = "string"
+ help = "Issuing CA certificate"
+ }
+ option = {
+ long = "self-signed"
+ type = "flag"
+ help = "Issuing a self-signed certificate"
+ }
+ option = {
+ long = "ca-private-key"
+ type = "string"
+ help = "Private key for self-signed certificate"
+ }
+ option = {
+ long = "certificate"
+ type = "string"
+ help = "Issued certificate"
+ }
+ option = {
+ long = "type"
+ type = "strings"
+ help = "Types of certificate to issue (can be used more then once)"
+ }
+ option = {
+ long = "lifetime"
+ type = "string"
+ help = "Lifetime of certificate"
+ }
+ option = {
+ long = "signature-algorithm"
+ type = "string"
+ help = "Signature algorithm to use"
+ }
+ option = {
+ long = "serial-number"
+ type = "string"
+ help = "serial-number of certificate"
+ }
+ option = {
+ long = "path-length"
+ default = "-1"
+ type = "integer"
+ help = "Maximum path length (CA and proxy certificates), -1 no limit"
+ }
+ option = {
+ long = "eku"
+ type = "strings"
+ argument = "oid-string"
+ help = "Add Extended Key Usage OID"
+ }
+ option = {
+ long = "ku"
+ type = "strings"
+ help = "Key Usage (digitalSignature, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign, cRLSign, encipherOnly, decipherOnly)"
+ }
+ option = {
+ long = "hostname"
+ type = "strings"
+ help = "DNS names this certificate is allowed to serve"
+ }
+ option = {
+ long = "dnssrv"
+ type = "strings"
+ help = "DNS SRV names this certificate is allowed to serve"
+ }
+ option = {
+ long = "email"
+ type = "strings"
+ help = "email addresses assigned to this certificate"
+ }
+ option = {
+ long = "pk-init-principal"
+ type = "strings"
+ help = "PK-INIT principal (for SAN)"
+ }
+ option = {
+ long = "ms-upn"
+ type = "string"
+ help = "Microsoft UPN (for SAN)"
+ }
+ option = {
+ long = "jid"
+ type = "string"
+ help = "XMPP jabber id (for SAN)"
+ }
+ option = {
+ long = "permanent-id"
+ type = "string"
+ help = "PermanentIdentifier ([oid]:[serial])"
+ }
+ option = {
+ long = "hardware-module-name"
+ type = "string"
+ help = "HardwareModuleName (oid:serial)"
+ }
+ option = {
+ long = "policy"
+ type = "strings"
+ help = "Certificate Policy OID and optional URI and/or notice (OID:URI<space>notice_text)"
+ }
+ option = {
+ long = "policy-mapping"
+ type = "strings"
+ help = "Certificate Policy mapping (OID:OID)"
+ }
+ option = {
+ long = "pkinit-max-life"
+ type = "string"
+ help = "maximum Kerberos ticket lifetime extension for PKINIT"
+ }
+ option = {
+ long = "req"
+ type = "string"
+ help = "certificate request"
+ }
+ option = {
+ long = "certificate-private-key"
+ type = "string"
+ help = "private-key"
+ }
+ option = {
+ long = "generate-key"
+ type = "string"
+ help = "keytype"
+ }
+ option = {
+ long = "key-bits"
+ type = "integer"
+ help = "number of bits in the generated key"
+ }
+ option = {
+ long = "crl-uri"
+ type = "string"
+ help = "URI to CRL"
+ }
+ option = {
+ long = "template-certificate"
+ type = "string"
+ help = "certificate"
+ }
+ option = {
+ long = "template-fields"
+ type = "string"
+ help = "flag"
+ }
+ name = "certificate-sign"
+ name = "cert-sign"
+ name = "issue-certificate"
+ name = "ca"
+ function = "hxtool_ca"
+ min_args="0"
+ help = "Issue a certificate"
+}
+command = {
+ name = "test-crypto"
+ option = {
+ long = "pass"
+ type = "strings"
+ argument = "password"
+ help = "password, prompter, or environment"
+ }
+ option = {
+ long = "verbose"
+ type = "flag"
+ help = "verbose printing"
+ }
+ min_args="1"
+ argument="certificates..."
+ help = "Test crypto system related to the certificates"
+}
+command = {
+ option = {
+ long = "type"
+ type = "integer"
+ help = "type of statistics"
+ }
+ name = "statistic-print"
+ min_args="0"
+ help = "Print statistics"
+}
+command = {
+ option = {
+ long = "signer"
+ type = "string"
+ help = "signer certificate"
+ }
+ option = {
+ long = "pass"
+ type = "strings"
+ argument = "password"
+ help = "password, prompter, or environment"
+ }
+ option = {
+ long = "crl-file"
+ type = "string"
+ help = "CRL output file"
+ }
+ option = {
+ long = "lifetime"
+ type = "string"
+ help = "time the crl will be valid"
+ }
+ name = "crl-sign"
+ min_args="0"
+ argument="certificates..."
+ help = "Create a CRL"
+}
+command = {
+ option = {
+ long = "verbose"
+ short = "v"
+ type = "flag"
+ help = "verbose"
+ }
+ option = {
+ long = "end-entity"
+ type = "flag"
+ help = "check the first EE certificate in the store"
+ }
+ option = {
+ long = "ca"
+ type = "flag"
+ help = "check the first CA certificate in the store"
+ }
+ option = {
+ long = "cert-num"
+ type = "integer"
+ default = "-1"
+ help = "check the nth certificate in the store"
+ }
+ option = {
+ long = "expr"
+ type = "string"
+ argument = "expression"
+ help = "test the first certificate matching expression"
+ }
+ option = {
+ long = "has-email-san"
+ short = "M"
+ type = "strings"
+ argument = "email-address"
+ help = "check that cert has email SAN"
+ }
+ option = {
+ long = "has-xmpp-san"
+ type = "strings"
+ short = "X"
+ argument = "jabber address"
+ help = "check that cert has XMPP SAN"
+ }
+ option = {
+ long = "has-ms-upn-san"
+ short = "U"
+ type = "strings"
+ argument = "UPN"
+ help = "check that cert has UPN SAN"
+ }
+ option = {
+ long = "has-dnsname-san"
+ short = "D"
+ type = "strings"
+ argument = "domainname"
+ help = "check that cert has domainname SAN"
+ }
+ option = {
+ long = "has-pkinit-san"
+ short = "P"
+ type = "strings"
+ argument = "Kerberos principal name"
+ help = "check that cert has PKINIT SAN"
+ }
+ option = {
+ long = "has-registeredID-san"
+ short = "R"
+ type = "strings"
+ argument = "OID"
+ help = "check that cert has registeredID SAN"
+ }
+ option = {
+ long = "has-eku"
+ short = "E"
+ type = "strings"
+ argument = "OID"
+ help = "check that cert has EKU"
+ }
+ option = {
+ long = "has-ku"
+ short = "K"
+ type = "strings"
+ argument = "key usage element"
+ help = "check that cert has key usage"
+ }
+ option = {
+ long = "exact"
+ type = "flag"
+ help = "check that cert has only given SANs/EKUs/KUs"
+ }
+ option = {
+ long = "valid-now"
+ short = "n"
+ type = "flag"
+ help = "check that current time is in certicate's validity period"
+ }
+ option = {
+ long = "valid-at"
+ type = "string"
+ argument = "datetime"
+ help = "check that the certificate is valid at given time"
+ }
+ option = {
+ long = "not-after-eq"
+ type = "string"
+ argument = "datetime"
+ help = "check that the certificate's notAfter is as given"
+ }
+ option = {
+ long = "not-after-lt"
+ type = "string"
+ argument = "datetime"
+ help = "check that the certificate's notAfter is before the given time"
+ }
+ option = {
+ long = "not-after-gt"
+ type = "string"
+ argument = "datetime"
+ help = "check that the certificate's notAfter is after the given time"
+ }
+ option = {
+ long = "not-before-eq"
+ type = "string"
+ argument = "datetime"
+ help = "check that the certificate's notBefore is as given"
+ }
+ option = {
+ long = "not-before-lt"
+ type = "string"
+ argument = "datetime"
+ help = "check that the certificate's notBefore is before the given time"
+ }
+ option = {
+ long = "not-before-gt"
+ type = "string"
+ argument = "datetime"
+ help = "check that the certificate's notBefore is after the given time"
+ }
+ option = {
+ long = "has-private-key"
+ type = "flag"
+ help = "check that the certificate has a private key"
+ }
+ option = {
+ long = "lacks-private-key"
+ type = "flag"
+ help = "check that the certificate does not have a private key"
+ }
+ name = "acert"
+ min_args = "1"
+ max_args = "1"
+ argument = "certificate-store"
+ help = "Assert certificate content"
+}
+command = {
+ name = "help"
+ name = "?"
+ argument = "[command]"
+ min_args = "0"
+ max_args = "1"
+ help = "Help! I need somebody"
+}
diff --git a/third_party/heimdal/lib/hx509/hxtool-version.rc b/third_party/heimdal/lib/hx509/hxtool-version.rc
new file mode 100644
index 0000000..7e5197c
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/hxtool-version.rc
@@ -0,0 +1,36 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#define RC_FILE_TYPE VFT_APP
+#define RC_FILE_DESC_0409 "Heimdal X.509 Certificate Tool"
+#define RC_FILE_ORIG_0409 "hxtool.exe"
+
+#include "../../windows/version.rc"
diff --git a/third_party/heimdal/lib/hx509/hxtool.c b/third_party/heimdal/lib/hx509/hxtool.c
new file mode 100644
index 0000000..1bcfdfa
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/hxtool.c
@@ -0,0 +1,3162 @@
+/*
+ * Copyright (c) 2004 - 2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+#include <hxtool-commands.h>
+#include <sl.h>
+#include <rtbl.h>
+#include <parse_time.h>
+
+static hx509_context context;
+
+static char *stat_file_string;
+static int version_flag;
+static int help_flag;
+
+struct getargs args[] = {
+ { "statistic-file", 0, arg_string, &stat_file_string, NULL, NULL },
+ { "version", 0, arg_flag, &version_flag, NULL, NULL },
+ { "help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+int num_args = sizeof(args) / sizeof(args[0]);
+
+static void
+usage(int code)
+{
+ arg_printusage(args, num_args, NULL, "command");
+ printf("Use \"%s help\" to get more help\n", getprogname());
+ exit(code);
+}
+
+/*
+ *
+ */
+
+static void
+lock_strings(hx509_lock lock, getarg_strings *pass)
+{
+ int i;
+ for (i = 0; i < pass->num_strings; i++) {
+ int ret = hx509_lock_command_string(lock, pass->strings[i]);
+ if (ret)
+ errx(1, "hx509_lock_command_string: %s: %d",
+ pass->strings[i], ret);
+ }
+}
+
+static char *
+fix_store_name(hx509_context contextp, const char *sn, const char *def_type)
+{
+ const char *residue = strchr(sn, ':');
+ char *s = NULL;
+
+ if (residue) {
+ s = estrdup(sn);
+ s[residue - sn] = '\0';
+ if (_hx509_ks_type(contextp, s)) {
+ free(s);
+ return estrdup(sn);
+ }
+ free(s);
+ s = NULL;
+ }
+ if (asprintf(&s, "%s:%s", def_type, sn) == -1 || s == NULL)
+ err(1, "Out of memory");
+ return s;
+}
+
+static char *
+fix_csr_name(const char *cn, const char *def_type)
+{
+ char *s = NULL;
+
+ if (strncmp(cn, "PKCS10:", sizeof("PKCS10:") - 1) == 0 || strchr(cn, ':'))
+ return estrdup(cn);
+ if (asprintf(&s, "%s:%s", def_type, cn) == -1 || s == NULL)
+ err(1, "Out of memory");
+ return s;
+}
+
+/*
+ *
+ */
+
+static void
+certs_strings(hx509_context contextp, const char *type, hx509_certs certs,
+ hx509_lock lock, const getarg_strings *s)
+{
+ int i, ret;
+
+ for (i = 0; i < s->num_strings; i++) {
+ char *sn = fix_store_name(contextp, s->strings[i], "FILE");
+
+ ret = hx509_certs_append(contextp, certs, lock, sn);
+ if (ret)
+ hx509_err(contextp, 1, ret,
+ "hx509_certs_append: %s %s", type, sn);
+ free(sn);
+ }
+}
+
+/*
+ *
+ */
+
+static void
+parse_oid(const char *str, const heim_oid *def, heim_oid *oid)
+{
+ int ret;
+
+ if (str) {
+ const heim_oid *found = NULL;
+
+ ret = der_find_heim_oid_by_name(str, &found);
+ if (ret == 0)
+ ret = der_copy_oid(found, oid);
+ else
+ ret = der_parse_heim_oid(str, " .", oid);
+ } else {
+ ret = der_copy_oid(def, oid);
+ }
+ if (ret)
+ errx(1, "parse_oid failed for: %s", str ? str : "default oid");
+}
+
+/*
+ *
+ */
+
+static void
+peer_strings(hx509_context contextp,
+ hx509_peer_info *peer,
+ const getarg_strings *s)
+{
+ AlgorithmIdentifier *val;
+ int ret, i;
+
+ ret = hx509_peer_info_alloc(contextp, peer);
+ if (ret)
+ hx509_err(contextp, 1, ret, "hx509_peer_info_alloc");
+
+ val = calloc(s->num_strings, sizeof(*val));
+ if (val == NULL)
+ err(1, "malloc");
+
+ for (i = 0; i < s->num_strings; i++)
+ parse_oid(s->strings[i], NULL, &val[i].algorithm);
+
+ ret = hx509_peer_info_set_cms_algs(contextp, *peer, val, s->num_strings);
+ if (ret)
+ hx509_err(contextp, 1, ret, "hx509_peer_info_set_cms_algs");
+
+ for (i = 0; i < s->num_strings; i++)
+ free_AlgorithmIdentifier(&val[i]);
+ free(val);
+}
+
+/*
+ *
+ */
+
+struct pem_data {
+ heim_octet_string *os;
+ int detached_data;
+};
+
+static int
+pem_reader(hx509_context contextp, const char *type,
+ const hx509_pem_header *headers,
+ const void *data , size_t length, void *ctx)
+{
+ struct pem_data *p = (struct pem_data *)ctx;
+ const char *h;
+
+ p->os->data = malloc(length);
+ if (p->os->data == NULL)
+ return ENOMEM;
+ memcpy(p->os->data, data, length);
+ p->os->length = length;
+
+ h = hx509_pem_find_header(headers, "Content-disposition");
+ if (h && strcasecmp(h, "detached") == 0)
+ p->detached_data = 1;
+
+ return 0;
+}
+
+/*
+ *
+ */
+
+int
+cms_verify_sd(struct cms_verify_sd_options *opt, int argc, char **argv)
+{
+ hx509_verify_ctx ctx = NULL;
+ heim_oid type;
+ heim_octet_string c, co, signeddata, *sd = NULL;
+ hx509_certs store = NULL;
+ hx509_certs signers = NULL;
+ hx509_certs anchors = NULL;
+ hx509_lock lock;
+ int ret, flags = 0;
+
+ size_t sz;
+ void *p = NULL;
+
+ if (opt->missing_revoke_flag)
+ hx509_context_set_missing_revoke(context, 1);
+
+ hx509_lock_init(context, &lock);
+ lock_strings(lock, &opt->pass_strings);
+
+ ret = hx509_verify_init_ctx(context, &ctx);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_verify_init_ctx");
+
+ ret = hx509_certs_init(context, "MEMORY:cms-anchors", 0, NULL, &anchors);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+ ret = hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &store);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+
+ certs_strings(context, "anchors", anchors, lock, &opt->anchors_strings);
+ certs_strings(context, "store", store, lock, &opt->certificate_strings);
+
+ if (opt->pem_flag) {
+ struct pem_data pd;
+ FILE *f;
+
+ pd.os = &co;
+ pd.detached_data = 0;
+
+ f = fopen(argv[0], "r");
+ if (f == NULL)
+ err(1, "Failed to open file %s", argv[0]);
+
+ ret = hx509_pem_read(context, f, pem_reader, &pd);
+ fclose(f);
+ if (ret)
+ errx(1, "PEM reader failed: %d", ret);
+
+ if (pd.detached_data && opt->signed_content_string == NULL) {
+ char *r = strrchr(argv[0], '.');
+ if (r && strcasecmp(r, ".pem") == 0) {
+ char *s = strdup(argv[0]);
+ if (s == NULL)
+ errx(1, "malloc: out of memory");
+ s[r - argv[0]] = '\0';
+ ret = _hx509_map_file_os(s, &signeddata);
+ if (ret)
+ errx(1, "map_file: %s: %d", s, ret);
+ free(s);
+ sd = &signeddata;
+ }
+ }
+
+ } else {
+ ret = rk_undumpdata(argv[0], &p, &sz);
+ if (ret)
+ err(1, "map_file: %s: %d", argv[0], ret);
+
+ co.data = p;
+ co.length = sz;
+ }
+
+ if (opt->signed_content_string) {
+ ret = _hx509_map_file_os(opt->signed_content_string, &signeddata);
+ if (ret)
+ errx(1, "map_file: %s: %d", opt->signed_content_string, ret);
+ sd = &signeddata;
+ }
+
+ if (opt->content_info_flag) {
+ heim_octet_string uwco;
+ heim_oid oid;
+
+ ret = hx509_cms_unwrap_ContentInfo(&co, &oid, &uwco, NULL);
+ if (ret)
+ errx(1, "hx509_cms_unwrap_ContentInfo: %d", ret);
+
+ if (der_heim_oid_cmp(&oid, &asn1_oid_id_pkcs7_signedData) != 0)
+ errx(1, "Content is not SignedData");
+ der_free_oid(&oid);
+
+ if (p == NULL)
+ der_free_octet_string(&co);
+ else {
+ rk_xfree(p);
+ p = NULL;
+ }
+ co = uwco;
+ }
+
+ hx509_verify_attach_anchors(ctx, anchors);
+
+ if (!opt->signer_allowed_flag)
+ flags |= HX509_CMS_VS_ALLOW_ZERO_SIGNER;
+ if (opt->allow_wrong_oid_flag)
+ flags |= HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH;
+
+ ret = hx509_cms_verify_signed(context, ctx, flags, co.data, co.length, sd,
+ store, &type, &c, &signers);
+ if (p != co.data)
+ der_free_octet_string(&co);
+ else
+ rk_xfree(p);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_cms_verify_signed");
+
+ {
+ char *str;
+ if (opt->oid_sym_flag)
+ der_print_heim_oid_sym(&type, '.', &str);
+ else
+ der_print_heim_oid(&type, '.', &str);
+ printf("type: %s\n", str);
+ free(str);
+ der_free_oid(&type);
+ }
+ if (signers == NULL) {
+ printf("unsigned\n");
+ } else {
+ printf("signers:\n");
+ hx509_certs_iter_f(context, signers, hx509_ci_print_names, stdout);
+ }
+
+ hx509_verify_destroy_ctx(ctx);
+
+ hx509_certs_free(&store);
+ hx509_certs_free(&signers);
+ hx509_certs_free(&anchors);
+
+ hx509_lock_free(lock);
+
+ if (argc > 1) {
+ ret = _hx509_write_file(argv[1], c.data, c.length);
+ if (ret)
+ errx(1, "hx509_write_file: %d", ret);
+ }
+
+ der_free_octet_string(&c);
+
+ if (sd)
+ _hx509_unmap_file_os(sd);
+
+ return 0;
+}
+
+static int HX509_LIB_CALL
+print_signer(hx509_context contextp, void *ctx, hx509_cert cert)
+{
+ hx509_pem_header **header = ctx;
+ char *signer_name = NULL;
+ hx509_name name;
+ int ret;
+
+ ret = hx509_cert_get_subject(cert, &name);
+ if (ret)
+ errx(1, "hx509_cert_get_subject");
+
+ ret = hx509_name_to_string(name, &signer_name);
+ hx509_name_free(&name);
+ if (ret)
+ errx(1, "hx509_name_to_string");
+
+ hx509_pem_add_header(header, "Signer", signer_name);
+
+ free(signer_name);
+ return 0;
+}
+
+int
+cms_create_sd(struct cms_create_sd_options *opt, int argc, char **argv)
+{
+ heim_oid contentType;
+ hx509_peer_info peer = NULL;
+ heim_octet_string o;
+ hx509_query *q;
+ hx509_lock lock;
+ hx509_certs store, pool, anchors, signer = NULL;
+ size_t sz;
+ void *p;
+ int ret, flags = 0;
+ const char *outfile = NULL;
+ char *infile, *freeme = NULL;
+
+ memset(&contentType, 0, sizeof(contentType));
+
+ infile = argv[0];
+
+ if (argc < 2) {
+ ret = asprintf(&freeme, "%s.%s", infile,
+ opt->pem_flag ? "pem" : "cms-signeddata");
+ if (ret == -1 || freeme == NULL)
+ errx(1, "out of memory");
+ outfile = freeme;
+ } else
+ outfile = argv[1];
+
+ hx509_lock_init(context, &lock);
+ lock_strings(lock, &opt->pass_strings);
+
+ ret = hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &store);
+ if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+ ret = hx509_certs_init(context, "MEMORY:cert-pool", 0, NULL, &pool);
+ if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+
+ certs_strings(context, "store", store, lock, &opt->certificate_strings);
+ certs_strings(context, "pool", pool, lock, &opt->pool_strings);
+
+ if (opt->anchors_strings.num_strings) {
+ ret = hx509_certs_init(context, "MEMORY:cert-anchors",
+ 0, NULL, &anchors);
+ if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+ certs_strings(context, "anchors", anchors, lock, &opt->anchors_strings);
+ } else
+ anchors = NULL;
+
+ if (opt->detached_signature_flag)
+ flags |= HX509_CMS_SIGNATURE_DETACHED;
+ if (opt->id_by_name_flag)
+ flags |= HX509_CMS_SIGNATURE_ID_NAME;
+ if (!opt->signer_flag) {
+ flags |= HX509_CMS_SIGNATURE_NO_SIGNER;
+
+ }
+
+ if (opt->signer_flag) {
+ ret = hx509_query_alloc(context, &q);
+ if (ret)
+ errx(1, "hx509_query_alloc: %d", ret);
+
+ hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
+ hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
+
+ if (opt->signer_string)
+ hx509_query_match_friendly_name(q, opt->signer_string);
+
+ ret = hx509_certs_filter(context, store, q, &signer);
+ hx509_query_free(context, q);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_find");
+ }
+ if (!opt->embedded_certs_flag)
+ flags |= HX509_CMS_SIGNATURE_NO_CERTS;
+ if (opt->embed_leaf_only_flag)
+ flags |= HX509_CMS_SIGNATURE_LEAF_ONLY;
+
+ ret = rk_undumpdata(infile, &p, &sz);
+ if (ret)
+ err(1, "map_file: %s: %d", infile, ret);
+
+ if (opt->peer_alg_strings.num_strings)
+ peer_strings(context, &peer, &opt->peer_alg_strings);
+
+ parse_oid(opt->content_type_string, &asn1_oid_id_pkcs7_data, &contentType);
+
+ ret = hx509_cms_create_signed(context,
+ flags,
+ &contentType,
+ p,
+ sz,
+ NULL,
+ signer,
+ peer,
+ anchors,
+ pool,
+ &o);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_cms_create_signed: %d", ret);
+
+ hx509_certs_free(&anchors);
+ hx509_certs_free(&pool);
+ hx509_certs_free(&store);
+ rk_xfree(p);
+ hx509_lock_free(lock);
+ hx509_peer_info_free(peer);
+ der_free_oid(&contentType);
+
+ if (opt->content_info_flag) {
+ heim_octet_string wo;
+
+ ret = hx509_cms_wrap_ContentInfo(&asn1_oid_id_pkcs7_signedData, &o, &wo);
+ if (ret)
+ errx(1, "hx509_cms_wrap_ContentInfo: %d", ret);
+
+ der_free_octet_string(&o);
+ o = wo;
+ }
+
+ if (opt->pem_flag) {
+ hx509_pem_header *header = NULL;
+ FILE *f;
+
+ hx509_pem_add_header(&header, "Content-disposition",
+ opt->detached_signature_flag ?
+ "detached" : "inline");
+ if (signer) {
+ ret = hx509_certs_iter_f(context, signer, print_signer, header);
+ if (ret)
+ hx509_err(context, 1, ret, "print signer");
+ }
+
+ f = fopen(outfile, "w");
+ if (f == NULL)
+ err(1, "open %s", outfile);
+
+ ret = hx509_pem_write(context, "CMS SIGNEDDATA", header, f,
+ o.data, o.length);
+ fclose(f);
+ hx509_pem_free_header(header);
+ if (ret)
+ errx(1, "hx509_pem_write: %d", ret);
+
+ } else {
+ ret = _hx509_write_file(outfile, o.data, o.length);
+ if (ret)
+ errx(1, "hx509_write_file: %d", ret);
+ }
+
+ hx509_certs_free(&signer);
+ free(o.data);
+ free(freeme);
+
+ return 0;
+}
+
+int
+cms_unenvelope(struct cms_unenvelope_options *opt, int argc, char **argv)
+{
+ heim_oid contentType = { 0, NULL };
+ heim_octet_string o, co;
+ hx509_certs certs;
+ size_t sz;
+ void *p;
+ int ret;
+ hx509_lock lock;
+ int flags = 0;
+
+ hx509_lock_init(context, &lock);
+ lock_strings(lock, &opt->pass_strings);
+
+ ret = rk_undumpdata(argv[0], &p, &sz);
+ if (ret)
+ err(1, "map_file: %s: %d", argv[0], ret);
+
+ co.data = p;
+ co.length = sz;
+
+ if (opt->content_info_flag) {
+ heim_octet_string uwco;
+ heim_oid oid;
+
+ ret = hx509_cms_unwrap_ContentInfo(&co, &oid, &uwco, NULL);
+ if (ret)
+ errx(1, "hx509_cms_unwrap_ContentInfo: %d", ret);
+
+ if (der_heim_oid_cmp(&oid, &asn1_oid_id_pkcs7_envelopedData) != 0)
+ errx(1, "Content is not SignedData");
+ der_free_oid(&oid);
+
+ co = uwco;
+ }
+
+ ret = hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &certs);
+ if (ret)
+ errx(1, "hx509_certs_init: MEMORY: %d", ret);
+
+ certs_strings(context, "store", certs, lock, &opt->certificate_strings);
+
+ if (opt->allow_weak_crypto_flag)
+ flags |= HX509_CMS_UE_ALLOW_WEAK;
+
+ ret = hx509_cms_unenvelope(context, certs, flags, co.data, co.length,
+ NULL, 0, &contentType, &o);
+ if (co.data != p)
+ der_free_octet_string(&co);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_cms_unenvelope");
+
+ rk_xfree(p);
+ hx509_lock_free(lock);
+ hx509_certs_free(&certs);
+ der_free_oid(&contentType);
+
+ ret = _hx509_write_file(argv[1], o.data, o.length);
+ if (ret)
+ errx(1, "hx509_write_file: %d", ret);
+
+ der_free_octet_string(&o);
+
+ return 0;
+}
+
+int
+cms_create_enveloped(struct cms_envelope_options *opt, int argc, char **argv)
+{
+ heim_oid contentType;
+ heim_octet_string o;
+ const heim_oid *enctype = NULL;
+ hx509_query *q;
+ hx509_certs certs;
+ hx509_cert cert;
+ int ret;
+ size_t sz;
+ void *p;
+ hx509_lock lock;
+ int flags = 0;
+
+ memset(&contentType, 0, sizeof(contentType));
+
+ hx509_lock_init(context, &lock);
+ lock_strings(lock, &opt->pass_strings);
+
+ ret = rk_undumpdata(argv[0], &p, &sz);
+ if (ret)
+ err(1, "map_file: %s: %d", argv[0], ret);
+
+ ret = hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &certs);
+ if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+
+ certs_strings(context, "store", certs, lock, &opt->certificate_strings);
+
+ if (opt->allow_weak_crypto_flag)
+ flags |= HX509_CMS_EV_ALLOW_WEAK;
+
+ if (opt->encryption_type_string) {
+ enctype = hx509_crypto_enctype_by_name(opt->encryption_type_string);
+ if (enctype == NULL)
+ errx(1, "encryption type: %s no found",
+ opt->encryption_type_string);
+ }
+
+ ret = hx509_query_alloc(context, &q);
+ if (ret)
+ errx(1, "hx509_query_alloc: %d", ret);
+
+ hx509_query_match_option(q, HX509_QUERY_OPTION_KU_ENCIPHERMENT);
+
+ ret = hx509_certs_find(context, certs, q, &cert);
+ hx509_query_free(context, q);
+ if (ret)
+ errx(1, "hx509_certs_find: %d", ret);
+
+ parse_oid(opt->content_type_string, &asn1_oid_id_pkcs7_data, &contentType);
+
+ ret = hx509_cms_envelope_1(context, flags, cert, p, sz, enctype,
+ &contentType, &o);
+ if (ret)
+ errx(1, "hx509_cms_envelope_1: %d", ret);
+
+ hx509_cert_free(cert);
+ hx509_certs_free(&certs);
+ rk_xfree(p);
+ der_free_oid(&contentType);
+
+ if (opt->content_info_flag) {
+ heim_octet_string wo;
+
+ ret = hx509_cms_wrap_ContentInfo(&asn1_oid_id_pkcs7_envelopedData, &o, &wo);
+ if (ret)
+ errx(1, "hx509_cms_wrap_ContentInfo: %d", ret);
+
+ der_free_octet_string(&o);
+ o = wo;
+ }
+
+ hx509_lock_free(lock);
+
+ ret = _hx509_write_file(argv[1], o.data, o.length);
+ if (ret)
+ errx(1, "hx509_write_file: %d", ret);
+
+ der_free_octet_string(&o);
+
+ return 0;
+}
+
+static void
+print_certificate(hx509_context hxcontext, hx509_cert cert, int verbose)
+{
+ const char *fn;
+ int ret;
+
+ fn = hx509_cert_get_friendly_name(cert);
+ if (fn)
+ printf(" friendly name: %s\n", fn);
+ printf(" private key: %s\n",
+ _hx509_cert_private_key(cert) ? "yes" : "no");
+
+ ret = hx509_print_cert(hxcontext, cert, stdout);
+ if (ret)
+ errx(1, "failed to print cert");
+
+ if (verbose) {
+ hx509_validate_ctx vctx;
+
+ hx509_validate_ctx_init(hxcontext, &vctx);
+ hx509_validate_ctx_set_print(vctx, hx509_print_stdout, stdout);
+ hx509_validate_ctx_add_flags(vctx, HX509_VALIDATE_F_VALIDATE);
+ hx509_validate_ctx_add_flags(vctx, HX509_VALIDATE_F_VERBOSE);
+
+ hx509_validate_cert(hxcontext, vctx, cert);
+
+ hx509_validate_ctx_free(vctx);
+ }
+}
+
+
+struct print_s {
+ int counter;
+ int verbose;
+};
+
+static int HX509_LIB_CALL
+print_f(hx509_context hxcontext, void *ctx, hx509_cert cert)
+{
+ struct print_s *s = ctx;
+
+ printf("cert: %d\n", s->counter++);
+ print_certificate(context, cert, s->verbose);
+
+ return 0;
+}
+
+static int HX509_LIB_CALL
+print_fjson(hx509_context hxcontext, void *ctx, hx509_cert cert)
+{
+ const Certificate *c = NULL;
+ char *json = NULL;
+
+ c = _hx509_get_cert(cert);
+ if (c)
+ json = print_Certificate(c, ASN1_PRINT_INDENT);
+ if (json)
+ printf("%s\n", json);
+ else
+ hx509_err(context, 1, errno, "Could not format certificate as JSON");
+ free(json);
+ return 0;
+}
+
+
+int
+pcert_print(struct print_options *opt, int argc, char **argv)
+{
+ hx509_certs certs;
+ hx509_lock lock;
+ struct print_s s;
+
+ s.counter = 0;
+ s.verbose = opt->content_flag;
+
+ hx509_lock_init(context, &lock);
+ lock_strings(lock, &opt->pass_strings);
+
+ while(argc--) {
+ char *sn = fix_store_name(context, argv[0], "FILE");
+ int ret;
+
+ ret = hx509_certs_init(context, sn, 0, lock, &certs);
+ free(sn);
+ if (ret) {
+ if (opt->never_fail_flag) {
+ printf("ignoreing failure: %d\n", ret);
+ continue;
+ }
+ hx509_err(context, 1, ret, "hx509_certs_init");
+ }
+ if (opt->raw_json_flag) {
+ hx509_certs_iter_f(context, certs, print_fjson, &s);
+ } else {
+ if (opt->info_flag)
+ hx509_certs_info(context, certs, NULL, NULL);
+ hx509_certs_iter_f(context, certs, print_f, &s);
+ }
+ hx509_certs_free(&certs);
+ argv++;
+ }
+
+ hx509_lock_free(lock);
+
+ return 0;
+}
+
+
+static int HX509_LIB_CALL
+validate_f(hx509_context hxcontext, void *ctx, hx509_cert c)
+{
+ hx509_validate_cert(hxcontext, ctx, c);
+ return 0;
+}
+
+int
+pcert_validate(struct validate_options *opt, int argc, char **argv)
+{
+ hx509_validate_ctx ctx;
+ hx509_certs certs;
+ hx509_lock lock;
+
+ hx509_lock_init(context, &lock);
+ lock_strings(lock, &opt->pass_strings);
+
+ hx509_validate_ctx_init(context, &ctx);
+ hx509_validate_ctx_set_print(ctx, hx509_print_stdout, stdout);
+ hx509_validate_ctx_add_flags(ctx, HX509_VALIDATE_F_VALIDATE);
+
+ while(argc--) {
+ char *sn = fix_store_name(context, argv[0], "FILE");
+ int ret;
+
+ ret = hx509_certs_init(context, sn, 0, lock, &certs);
+ if (ret)
+ errx(1, "hx509_certs_init: %d", ret);
+ hx509_certs_iter_f(context, certs, validate_f, ctx);
+ hx509_certs_free(&certs);
+ argv++;
+ free(sn);
+ }
+ hx509_validate_ctx_free(ctx);
+
+ hx509_lock_free(lock);
+
+ return 0;
+}
+
+int
+certificate_copy(struct certificate_copy_options *opt, int argc, char **argv)
+{
+ hx509_certs certs;
+ hx509_lock inlock, outlock = NULL;
+ char *sn;
+ int ret;
+
+ hx509_lock_init(context, &inlock);
+ lock_strings(inlock, &opt->in_pass_strings);
+
+ if (opt->out_pass_string) {
+ hx509_lock_init(context, &outlock);
+ ret = hx509_lock_command_string(outlock, opt->out_pass_string);
+ if (ret)
+ errx(1, "hx509_lock_command_string: %s: %d",
+ opt->out_pass_string, ret);
+ }
+
+ sn = fix_store_name(context, argv[argc - 1], "FILE");
+ ret = hx509_certs_init(context, sn,
+ HX509_CERTS_CREATE, inlock, &certs);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_init %s", sn);
+ free(sn);
+
+ while(argc-- > 1) {
+ int retx;
+
+ sn = fix_store_name(context, argv[0], "FILE");
+ retx = hx509_certs_append(context, certs, inlock, sn);
+ if (retx)
+ hx509_err(context, 1, retx, "hx509_certs_append %s", sn);
+ free(sn);
+ argv++;
+ }
+
+ ret = hx509_certs_store(context, certs, 0, outlock);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_store");
+
+ hx509_certs_free(&certs);
+ hx509_lock_free(inlock);
+ hx509_lock_free(outlock);
+
+ return 0;
+}
+
+struct verify {
+ hx509_verify_ctx ctx;
+ hx509_certs chain;
+ const char *hostname;
+ int errors;
+ int count;
+};
+
+static int HX509_LIB_CALL
+verify_f(hx509_context hxcontext, void *ctx, hx509_cert c)
+{
+ struct verify *v = ctx;
+ int ret;
+
+ ret = hx509_verify_path(hxcontext, v->ctx, c, v->chain);
+ if (ret) {
+ char *s = hx509_get_error_string(hxcontext, ret);
+ printf("verify_path: %s: %d\n", s, ret);
+ hx509_free_error_string(s);
+ v->errors++;
+ } else {
+ v->count++;
+ printf("path ok\n");
+ }
+
+ if (v->hostname) {
+ ret = hx509_verify_hostname(hxcontext, c, 0, HX509_HN_HOSTNAME,
+ v->hostname, NULL, 0);
+ if (ret) {
+ printf("verify_hostname: %d\n", ret);
+ v->errors++;
+ }
+ }
+
+ return 0;
+}
+
+int
+pcert_verify(struct verify_options *opt, int argc, char **argv)
+{
+ hx509_certs anchors, chain, certs;
+ hx509_revoke_ctx revoke_ctx;
+ hx509_verify_ctx ctx;
+ struct verify v;
+ int ret;
+
+ memset(&v, 0, sizeof(v));
+
+ if (opt->missing_revoke_flag)
+ hx509_context_set_missing_revoke(context, 1);
+
+ ret = hx509_verify_init_ctx(context, &ctx);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_verify_init_ctx");
+ ret = hx509_certs_init(context, "MEMORY:anchors", 0, NULL, &anchors);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+ ret = hx509_certs_init(context, "MEMORY:chain", 0, NULL, &chain);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+ ret = hx509_certs_init(context, "MEMORY:certs", 0, NULL, &certs);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+
+ if (opt->allow_proxy_certificate_flag)
+ hx509_verify_set_proxy_certificate(ctx, 1);
+
+ if (opt->time_string) {
+ const char *p;
+ struct tm tm;
+ time_t t;
+
+ memset(&tm, 0, sizeof(tm));
+
+ p = strptime (opt->time_string, "%Y-%m-%d", &tm);
+ if (p == NULL)
+ errx(1, "Failed to parse time %s, need to be on format %%Y-%%m-%%d",
+ opt->time_string);
+
+ t = tm2time (tm, 0);
+
+ hx509_verify_set_time(ctx, t);
+ }
+
+ if (opt->hostname_string)
+ v.hostname = opt->hostname_string;
+ if (opt->max_depth_integer)
+ hx509_verify_set_max_depth(ctx, opt->max_depth_integer);
+
+ ret = hx509_revoke_init(context, &revoke_ctx);
+ if (ret)
+ errx(1, "hx509_revoke_init: %d", ret);
+
+ while(argc--) {
+ const char *s = *argv++;
+ char *sn = NULL;
+
+ if (strncmp(s, "chain:", 6) == 0) {
+ s += 6;
+
+ sn = fix_store_name(context, s, "FILE");
+ ret = hx509_certs_append(context, chain, NULL, sn);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_append: chain: %s: %d",
+ sn, ret);
+
+ } else if (strncmp(s, "anchor:", 7) == 0) {
+ s += 7;
+
+ sn = fix_store_name(context, s, "FILE");
+ ret = hx509_certs_append(context, anchors, NULL, sn);
+ if (ret)
+ hx509_err(context, 1, ret,
+ "hx509_certs_append: anchor: %s: %d", sn, ret);
+
+ } else if (strncmp(s, "cert:", 5) == 0) {
+ s += 5;
+
+ sn = fix_store_name(context, s, "FILE");
+ ret = hx509_certs_append(context, certs, NULL, sn);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_append: certs: %s: %d",
+ sn, ret);
+
+ } else if (strncmp(s, "crl:", 4) == 0) {
+ s += 4;
+
+ ret = hx509_revoke_add_crl(context, revoke_ctx, s);
+ if (ret)
+ errx(1, "hx509_revoke_add_crl: %s: %d", s, ret);
+
+ } else if (strncmp(s, "ocsp:", 5) == 0) {
+ s += 5;
+
+ ret = hx509_revoke_add_ocsp(context, revoke_ctx, s);
+ if (ret)
+ errx(1, "hx509_revoke_add_ocsp: %s: %d", s, ret);
+
+ } else {
+ errx(1, "unknown option to verify: `%s'\n", s);
+ }
+ free(sn);
+ }
+
+ hx509_verify_attach_anchors(ctx, anchors);
+ hx509_verify_attach_revoke(ctx, revoke_ctx);
+
+ v.ctx = ctx;
+ v.chain = chain;
+
+ hx509_certs_iter_f(context, certs, verify_f, &v);
+
+ hx509_verify_destroy_ctx(ctx);
+
+ hx509_certs_free(&certs);
+ hx509_certs_free(&chain);
+ hx509_certs_free(&anchors);
+
+ hx509_revoke_free(&revoke_ctx);
+
+
+ if (v.count == 0) {
+ printf("no certs verify at all\n");
+ return 1;
+ }
+
+ if (v.errors) {
+ printf("failed verifing %d checks\n", v.errors);
+ return 1;
+ }
+
+ return 0;
+}
+
+int
+query(struct query_options *opt, int argc, char **argv)
+{
+ hx509_lock lock;
+ hx509_query *q;
+ hx509_certs certs;
+ hx509_cert c;
+ int ret;
+
+ ret = hx509_query_alloc(context, &q);
+ if (ret)
+ errx(1, "hx509_query_alloc: %d", ret);
+
+ hx509_lock_init(context, &lock);
+ lock_strings(lock, &opt->pass_strings);
+
+ ret = hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &certs);
+ if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+
+ while (argc > 0) {
+ char *sn = fix_store_name(context, argv[0], "FILE");
+
+ ret = hx509_certs_append(context, certs, lock, sn);
+ if (ret)
+ errx(1, "hx509_certs_append: %s: %d", sn, ret);
+ free(sn);
+
+ argc--;
+ argv++;
+ }
+
+ if (opt->friendlyname_string)
+ hx509_query_match_friendly_name(q, opt->friendlyname_string);
+
+ if (opt->eku_string) {
+ heim_oid oid;
+
+ parse_oid(opt->eku_string, NULL, &oid);
+
+ ret = hx509_query_match_eku(q, &oid);
+ if (ret)
+ errx(1, "hx509_query_match_eku: %d", ret);
+ der_free_oid(&oid);
+ }
+
+ if (opt->private_key_flag)
+ hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
+
+ if (opt->keyEncipherment_flag)
+ hx509_query_match_option(q, HX509_QUERY_OPTION_KU_ENCIPHERMENT);
+
+ if (opt->digitalSignature_flag)
+ hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
+
+ if (opt->expr_string)
+ hx509_query_match_expr(context, q, opt->expr_string);
+
+ ret = hx509_certs_find(context, certs, q, &c);
+ hx509_query_free(context, q);
+ if (ret)
+ printf("no match found (%d)\n", ret);
+ else {
+ printf("match found\n");
+ if (opt->print_flag)
+ print_certificate(context, c, 0);
+ }
+
+ hx509_cert_free(c);
+ hx509_certs_free(&certs);
+
+ hx509_lock_free(lock);
+
+ return ret;
+}
+
+int
+ocsp_fetch(struct ocsp_fetch_options *opt, int argc, char **argv)
+{
+ hx509_certs reqcerts, pool;
+ heim_octet_string req, nonce_data, *nonce = &nonce_data;
+ hx509_lock lock;
+ int i, ret;
+ char *file;
+ const char *url = "/";
+
+ memset(&nonce, 0, sizeof(nonce));
+
+ hx509_lock_init(context, &lock);
+ lock_strings(lock, &opt->pass_strings);
+
+ /* no nonce */
+ if (!opt->nonce_flag)
+ nonce = NULL;
+
+ if (opt->url_path_string)
+ url = opt->url_path_string;
+
+ ret = hx509_certs_init(context, "MEMORY:ocsp-pool", 0, NULL, &pool);
+ if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+
+ certs_strings(context, "ocsp-pool", pool, lock, &opt->pool_strings);
+
+ file = argv[0];
+
+ ret = hx509_certs_init(context, "MEMORY:ocsp-req", 0, NULL, &reqcerts);
+ if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+
+ for (i = 1; i < argc; i++) {
+ char *sn = fix_store_name(context, argv[i], "FILE");
+
+ ret = hx509_certs_append(context, reqcerts, lock, sn);
+ if (ret)
+ errx(1, "hx509_certs_append: req: %s: %d", sn, ret);
+ free(sn);
+ }
+
+ ret = hx509_ocsp_request(context, reqcerts, pool, NULL, NULL, &req, nonce);
+ if (ret)
+ errx(1, "hx509_ocsp_request: req: %d", ret);
+
+ {
+ FILE *f;
+
+ f = fopen(file, "w");
+ if (f == NULL)
+ abort();
+
+ fprintf(f,
+ "POST %s HTTP/1.0\r\n"
+ "Content-Type: application/ocsp-request\r\n"
+ "Content-Length: %ld\r\n"
+ "\r\n",
+ url,
+ (unsigned long)req.length);
+ fwrite(req.data, req.length, 1, f);
+ fclose(f);
+ }
+
+ if (nonce)
+ der_free_octet_string(nonce);
+
+ hx509_certs_free(&reqcerts);
+ hx509_certs_free(&pool);
+
+ return 0;
+}
+
+int
+ocsp_print(struct ocsp_print_options *opt, int argc, char **argv)
+{
+ hx509_revoke_ocsp_print(context, argv[0], stdout);
+ return 0;
+}
+
+int
+revoke_print(struct revoke_print_options *opt, int argc, char **argv)
+{
+ hx509_revoke_ctx revoke_ctx;
+ int ret;
+
+ ret = hx509_revoke_init(context, &revoke_ctx);
+ if (ret)
+ errx(1, "hx509_revoke_init: %d", ret);
+
+ while(argc--) {
+ char *s = *argv++;
+
+ if (strncmp(s, "crl:", 4) == 0) {
+ s += 4;
+
+ ret = hx509_revoke_add_crl(context, revoke_ctx, s);
+ if (ret)
+ errx(1, "hx509_revoke_add_crl: %s: %d", s, ret);
+
+ } else if (strncmp(s, "ocsp:", 5) == 0) {
+ s += 5;
+
+ ret = hx509_revoke_add_ocsp(context, revoke_ctx, s);
+ if (ret)
+ errx(1, "hx509_revoke_add_ocsp: %s: %d", s, ret);
+
+ } else {
+ errx(1, "unknown option to verify: `%s'\n", s);
+ }
+ }
+
+ ret = hx509_revoke_print(context, revoke_ctx, stdout);
+ if (ret)
+ warnx("hx509_revoke_print: %d", ret);
+
+ hx509_revoke_free(&revoke_ctx);
+ return ret;
+}
+
+/*
+ *
+ */
+
+static int HX509_LIB_CALL
+verify_o(hx509_context hxcontext, void *ctx, hx509_cert c)
+{
+ heim_octet_string *os = ctx;
+ time_t expiration;
+ int ret;
+
+ ret = hx509_ocsp_verify(context, 0, c, 0,
+ os->data, os->length, &expiration);
+ if (ret) {
+ char *s = hx509_get_error_string(hxcontext, ret);
+ printf("ocsp_verify: %s: %d\n", s, ret);
+ hx509_free_error_string(s);
+ } else
+ printf("expire: %d\n", (int)expiration);
+
+ return ret;
+}
+
+
+int
+ocsp_verify(struct ocsp_verify_options *opt, int argc, char **argv)
+{
+ hx509_lock lock;
+ hx509_certs certs;
+ int ret, i;
+ heim_octet_string os;
+
+ hx509_lock_init(context, &lock);
+
+ if (opt->ocsp_file_string == NULL)
+ errx(1, "no ocsp file given");
+
+ ret = _hx509_map_file_os(opt->ocsp_file_string, &os);
+ if (ret)
+ err(1, "map_file: %s: %d", argv[0], ret);
+
+ ret = hx509_certs_init(context, "MEMORY:test-certs", 0, NULL, &certs);
+ if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+
+ for (i = 0; i < argc; i++) {
+ char *sn = fix_store_name(context, argv[i], "FILE");
+
+ ret = hx509_certs_append(context, certs, lock, sn);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_append: %s", sn);
+ free(sn);
+ }
+
+ ret = hx509_certs_iter_f(context, certs, verify_o, &os);
+
+ hx509_certs_free(&certs);
+ _hx509_unmap_file_os(&os);
+ hx509_lock_free(lock);
+
+ return ret;
+}
+
+static int
+read_private_key(const char *fn, hx509_private_key *key)
+{
+ hx509_private_key *keys;
+ hx509_certs certs;
+ char *sn = fix_store_name(context, fn, "FILE");
+ int ret;
+
+ *key = NULL;
+
+ ret = hx509_certs_init(context, sn, 0, NULL, &certs);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_init: %s", sn);
+
+ ret = _hx509_certs_keys_get(context, certs, &keys);
+ hx509_certs_free(&certs);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_keys_get");
+ if (keys[0] == NULL)
+ errx(1, "no keys in key store: %s", sn);
+ free(sn);
+
+ *key = _hx509_private_key_ref(keys[0]);
+ _hx509_certs_keys_free(context, keys);
+
+ return 0;
+}
+
+static void
+get_key(const char *fn, const char *type, int optbits,
+ hx509_private_key *signer)
+{
+ int ret = 0;
+
+ if (type) {
+ struct hx509_generate_private_context *gen_ctx = NULL;
+
+ if (strcasecmp(type, "rsa") != 0)
+ errx(1, "can only handle rsa keys for now");
+
+ ret = _hx509_generate_private_key_init(context,
+ ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+ &gen_ctx);
+ if (ret == 0)
+ ret = _hx509_generate_private_key_bits(context, gen_ctx, optbits);
+ if (ret == 0)
+ ret = _hx509_generate_private_key(context, gen_ctx, signer);
+ _hx509_generate_private_key_free(&gen_ctx);
+ if (ret)
+ hx509_err(context, 1, ret, "failed to generate private key of type %s", type);
+
+ if (fn) {
+ char *sn = fix_store_name(context, fn, "FILE");
+ hx509_certs certs = NULL;
+ hx509_cert cert = NULL;
+
+ cert = hx509_cert_init_private_key(context, *signer, NULL);
+ if (cert)
+ ret = hx509_certs_init(context, sn,
+ HX509_CERTS_CREATE |
+ HX509_CERTS_UNPROTECT_ALL,
+ NULL, &certs);
+ if (ret == 0)
+ ret = hx509_certs_add(context, certs, cert);
+ if (ret == 0)
+ ret = hx509_certs_store(context, certs, 0, NULL);
+ if (ret)
+ hx509_err(context, 1, ret, "failed to store generated private "
+ "key in %s", sn);
+
+ if (certs)
+ hx509_certs_free(&certs);
+ if (cert)
+ hx509_cert_free(cert);
+ free(sn);
+ }
+ } else {
+ if (fn == NULL)
+ err(1, "no private key");
+ ret = read_private_key(fn, signer);
+ if (ret)
+ hx509_err(context, 1, ret, "failed to read private key from %s",
+ fn);
+ }
+}
+
+int
+generate_key(struct generate_key_options *opt, int argc, char **argv)
+{
+ hx509_private_key signer;
+ const char *type = opt->type_string ? opt->type_string : "rsa";
+ int bits = opt->key_bits_integer ? opt->key_bits_integer : 2048;
+
+ memset(&signer, 0, sizeof(signer));
+ get_key(argv[0], type, bits, &signer);
+ hx509_private_key_free(&signer);
+ return 0;
+}
+
+int
+request_create(struct request_create_options *opt, int argc, char **argv)
+{
+ heim_octet_string request;
+ hx509_request req;
+ int ret, i;
+ hx509_private_key signer;
+ SubjectPublicKeyInfo key;
+ const char *outfile = argv[0];
+
+ memset(&key, 0, sizeof(key));
+ memset(&signer, 0, sizeof(signer));
+
+ get_key(opt->key_string,
+ opt->generate_key_string,
+ opt->key_bits_integer,
+ &signer);
+
+ hx509_request_init(context, &req);
+
+ if (opt->subject_string) {
+ hx509_name name = NULL;
+
+ ret = hx509_parse_name(context, opt->subject_string, &name);
+ if (ret)
+ errx(1, "hx509_parse_name: %d\n", ret);
+ hx509_request_set_name(context, req, name);
+
+ if (opt->verbose_flag) {
+ char *s;
+ hx509_name_to_string(name, &s);
+ printf("%s\n", s);
+ free(s);
+ }
+ hx509_name_free(&name);
+ }
+
+ for (i = 0; i < opt->email_strings.num_strings; i++) {
+ ret = hx509_request_add_email(context, req,
+ opt->email_strings.strings[i]);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_request_add_email");
+ }
+
+ for (i = 0; i < opt->jid_strings.num_strings; i++) {
+ ret = hx509_request_add_xmpp_name(context, req,
+ opt->jid_strings.strings[i]);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_request_add_xmpp_name");
+ }
+
+ for (i = 0; i < opt->dnsname_strings.num_strings; i++) {
+ ret = hx509_request_add_dns_name(context, req,
+ opt->dnsname_strings.strings[i]);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_request_add_dns_name");
+ }
+
+ for (i = 0; i < opt->kerberos_strings.num_strings; i++) {
+ ret = hx509_request_add_pkinit(context, req,
+ opt->kerberos_strings.strings[i]);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_request_add_pkinit");
+ }
+
+ for (i = 0; i < opt->ms_kerberos_strings.num_strings; i++) {
+ ret = hx509_request_add_ms_upn_name(context, req,
+ opt->ms_kerberos_strings.strings[i]);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_request_add_ms_upn_name");
+ }
+
+ for (i = 0; i < opt->registered_strings.num_strings; i++) {
+ heim_oid oid;
+
+ parse_oid(opt->registered_strings.strings[i], NULL, &oid);
+ ret = hx509_request_add_registered(context, req, &oid);
+ der_free_oid(&oid);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_request_add_registered");
+ }
+
+ for (i = 0; i < opt->eku_strings.num_strings; i++) {
+ heim_oid oid;
+
+ parse_oid(opt->eku_strings.strings[i], NULL, &oid);
+ ret = hx509_request_add_eku(context, req, &oid);
+ der_free_oid(&oid);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_request_add_eku");
+ }
+
+
+ ret = hx509_private_key2SPKI(context, signer, &key);
+ if (ret)
+ errx(1, "hx509_private_key2SPKI: %d\n", ret);
+
+ ret = hx509_request_set_SubjectPublicKeyInfo(context,
+ req,
+ &key);
+ free_SubjectPublicKeyInfo(&key);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_request_set_SubjectPublicKeyInfo");
+
+ ret = hx509_request_to_pkcs10(context,
+ req,
+ signer,
+ &request);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_request_to_pkcs10");
+
+ hx509_private_key_free(&signer);
+ hx509_request_free(&req);
+
+ if (ret == 0)
+ rk_dumpdata(outfile, request.data, request.length);
+ der_free_octet_string(&request);
+
+ return 0;
+}
+
+int
+request_print(struct request_print_options *opt, int argc, char **argv)
+{
+ int ret, i;
+
+ printf("request print\n");
+
+ for (i = 0; i < argc; i++) {
+ hx509_request req;
+ char *cn = fix_csr_name(argv[i], "PKCS10");
+
+ ret = hx509_request_parse(context, cn, &req);
+ if (ret)
+ hx509_err(context, 1, ret, "parse_request: %s", cn);
+
+ ret = hx509_request_print(context, req, stdout);
+ hx509_request_free(&req);
+ if (ret)
+ hx509_err(context, 1, ret, "Failed to print file %s", cn);
+ free(cn);
+ }
+
+ return 0;
+}
+
+int
+info(void *opt, int argc, char **argv)
+{
+
+ ENGINE_add_conf_module();
+
+ {
+ const RSA_METHOD *m = RSA_get_default_method();
+ if (m != NULL)
+ printf("rsa: %s\n", m->name);
+ }
+ {
+ const DH_METHOD *m = DH_get_default_method();
+ if (m != NULL)
+ printf("dh: %s\n", m->name);
+ }
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+ {
+ printf("ecdsa: ECDSA_METHOD-not-export\n");
+ }
+#else
+ {
+ printf("ecdsa: hcrypto null\n");
+ }
+#endif
+ {
+ int ret = RAND_status();
+ printf("rand: %s\n", ret == 1 ? "ok" : "not available");
+ }
+
+ return 0;
+}
+
+int
+random_data(void *opt, int argc, char **argv)
+{
+ void *ptr;
+ ssize_t len;
+ int ret;
+
+ len = parse_bytes(argv[0], "byte");
+ if (len <= 0) {
+ fprintf(stderr, "bad argument to random-data\n");
+ return 1;
+ }
+
+ ptr = malloc(len);
+ if (ptr == NULL) {
+ fprintf(stderr, "out of memory\n");
+ return 1;
+ }
+
+ ret = RAND_bytes(ptr, len);
+ if (ret != 1) {
+ free(ptr);
+ fprintf(stderr, "did not get cryptographic strong random\n");
+ return 1;
+ }
+
+ fwrite(ptr, len, 1, stdout);
+ fflush(stdout);
+
+ free(ptr);
+
+ return 0;
+}
+
+int
+crypto_available(struct crypto_available_options *opt, int argc, char **argv)
+{
+ AlgorithmIdentifier *val;
+ unsigned int len, i;
+ int ret, type = HX509_SELECT_ALL;
+
+ if (opt->type_string) {
+ if (strcmp(opt->type_string, "all") == 0)
+ type = HX509_SELECT_ALL;
+ else if (strcmp(opt->type_string, "digest") == 0)
+ type = HX509_SELECT_DIGEST;
+ else if (strcmp(opt->type_string, "public-sig") == 0)
+ type = HX509_SELECT_PUBLIC_SIG;
+ else if (strcmp(opt->type_string, "secret") == 0)
+ type = HX509_SELECT_SECRET_ENC;
+ else
+ errx(1, "unknown type: %s", opt->type_string);
+ }
+
+ ret = hx509_crypto_available(context, type, NULL, &val, &len);
+ if (ret)
+ errx(1, "hx509_crypto_available");
+
+ for (i = 0; i < len; i++) {
+ char *s;
+ if (opt->oid_syms_flag)
+ der_print_heim_oid_sym(&val[i].algorithm, '.', &s);
+ else
+ der_print_heim_oid(&val[i].algorithm, '.', &s);
+ printf("%s\n", s);
+ free(s);
+ }
+
+ hx509_crypto_free_algs(val, len);
+
+ return 0;
+}
+
+int
+crypto_select(struct crypto_select_options *opt, int argc, char **argv)
+{
+ hx509_peer_info peer = NULL;
+ AlgorithmIdentifier selected;
+ int ret, type = HX509_SELECT_DIGEST;
+ char *s;
+
+ if (opt->type_string) {
+ if (strcmp(opt->type_string, "digest") == 0)
+ type = HX509_SELECT_DIGEST;
+ else if (strcmp(opt->type_string, "public-sig") == 0)
+ type = HX509_SELECT_PUBLIC_SIG;
+ else if (strcmp(opt->type_string, "secret") == 0)
+ type = HX509_SELECT_SECRET_ENC;
+ else
+ errx(1, "unknown type: %s", opt->type_string);
+ }
+
+ if (opt->peer_cmstype_strings.num_strings)
+ peer_strings(context, &peer, &opt->peer_cmstype_strings);
+
+ ret = hx509_crypto_select(context, type, NULL, peer, &selected);
+ if (ret)
+ errx(1, "hx509_crypto_available");
+
+ if (opt->oid_sym_flag)
+ der_print_heim_oid_sym(&selected.algorithm, '.', &s);
+ else
+ der_print_heim_oid(&selected.algorithm, '.', &s);
+ printf("%s\n", s);
+ free(s);
+ free_AlgorithmIdentifier(&selected);
+
+ hx509_peer_info_free(peer);
+
+ return 0;
+}
+
+int
+hxtool_hex(struct hex_options *opt, int argc, char **argv)
+{
+
+ if (opt->decode_flag) {
+ char buf[1024], buf2[1024], *p;
+ ssize_t len;
+
+ while(fgets(buf, sizeof(buf), stdin) != NULL) {
+ buf[strcspn(buf, "\r\n")] = '\0';
+ p = buf;
+ while(isspace(*(unsigned char *)p))
+ p++;
+ len = hex_decode(p, buf2, strlen(p));
+ if (len < 0)
+ errx(1, "hex_decode failed");
+ if (fwrite(buf2, 1, len, stdout) != (size_t)len)
+ errx(1, "fwrite failed");
+ }
+ } else {
+ char buf[28], *p;
+ ssize_t len;
+
+ while((len = fread(buf, 1, sizeof(buf), stdin)) != 0) {
+ len = hex_encode(buf, len, &p);
+ if (len < 0)
+ continue;
+ fprintf(stdout, "%s\n", p);
+ free(p);
+ }
+ }
+ return 0;
+}
+
+struct cert_type_opt {
+ int pkinit;
+};
+
+
+static int
+https_server(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt *opt)
+{
+ return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkix_kp_serverAuth);
+}
+
+static int
+https_negotiate_server(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt *opt)
+{
+ int ret = hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkekuoid);
+ if (ret == 0)
+ ret = hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkix_kp_serverAuth);
+ opt->pkinit++;
+ return ret;
+}
+
+static int
+https_client(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt *opt)
+{
+ return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkix_kp_clientAuth);
+}
+
+static int
+peap_server(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt *opt)
+{
+ return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkix_kp_serverAuth);
+}
+
+static int
+pkinit_kdc(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt *opt)
+{
+ opt->pkinit++;
+ return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkkdcekuoid);
+}
+
+static int
+pkinit_client(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt *opt)
+{
+ int ret;
+
+ opt->pkinit++;
+
+ ret = hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkekuoid);
+ if (ret)
+ return ret;
+
+ ret = hx509_ca_tbs_add_eku(context, tbs, &asn1_oid_id_pkix_kp_clientAuth);
+ if (ret)
+ return ret;
+
+ return hx509_ca_tbs_add_eku(context, tbs, &asn1_oid_id_pkinit_ms_eku);
+}
+
+static int
+email_client(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt *opt)
+{
+ return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkix_kp_emailProtection);
+}
+
+struct {
+ const char *type;
+ const char *desc;
+ int (*eval)(hx509_context, hx509_ca_tbs, struct cert_type_opt *);
+} certtypes[] = {
+ {
+ "https-server",
+ "Used for HTTPS server and many other TLS server certificate types",
+ https_server
+ },
+ {
+ "https-client",
+ "Used for HTTPS client certificates",
+ https_client
+ },
+ {
+ "email-client",
+ "Certificate will be use for email",
+ email_client
+ },
+ {
+ "pkinit-client",
+ "Certificate used for Kerberos PK-INIT client certificates",
+ pkinit_client
+ },
+ {
+ "pkinit-kdc",
+ "Certificates used for Kerberos PK-INIT KDC certificates",
+ pkinit_kdc
+ },
+ {
+ "https-negotiate-server",
+ "Used for HTTPS server and many other TLS server certificate types",
+ https_negotiate_server
+ },
+ {
+ "peap-server",
+ "Certificate used for Radius PEAP (Protected EAP)",
+ peap_server
+ }
+};
+
+static void
+print_eval_types(FILE *out)
+{
+ rtbl_t table;
+ unsigned i;
+
+ table = rtbl_create();
+ rtbl_add_column_by_id (table, 0, "Name", 0);
+ rtbl_add_column_by_id (table, 1, "Description", 0);
+
+ for (i = 0; i < sizeof(certtypes)/sizeof(certtypes[0]); i++) {
+ rtbl_add_column_entry_by_id(table, 0, certtypes[i].type);
+ rtbl_add_column_entry_by_id(table, 1, certtypes[i].desc);
+ }
+
+ rtbl_format (table, out);
+ rtbl_destroy (table);
+}
+
+static int
+eval_types(hx509_context contextp,
+ hx509_ca_tbs tbs,
+ const struct certificate_sign_options *opt)
+{
+ struct cert_type_opt ctopt;
+ int i;
+ size_t j;
+ int ret;
+
+ memset(&ctopt, 0, sizeof(ctopt));
+
+ for (i = 0; i < opt->type_strings.num_strings; i++) {
+ const char *type = opt->type_strings.strings[i];
+
+ for (j = 0; j < sizeof(certtypes)/sizeof(certtypes[0]); j++) {
+ if (strcasecmp(type, certtypes[j].type) == 0) {
+ ret = (*certtypes[j].eval)(contextp, tbs, &ctopt);
+ if (ret)
+ hx509_err(contextp, 1, ret,
+ "Failed to evaluate cert type %s", type);
+ break;
+ }
+ }
+ if (j >= sizeof(certtypes)/sizeof(certtypes[0])) {
+ fprintf(stderr, "Unknown certificate type %s\n\n", type);
+ fprintf(stderr, "Available types:\n");
+ print_eval_types(stderr);
+ exit(1);
+ }
+ }
+
+ for (i = 0; i < opt->pk_init_principal_strings.num_strings; i++) {
+ const char *pk_init_princ = opt->pk_init_principal_strings.strings[i];
+
+ if (!ctopt.pkinit)
+ errx(1, "pk-init principal given but no pk-init oid");
+
+ ret = hx509_ca_tbs_add_san_pkinit(contextp, tbs, pk_init_princ);
+ if (ret)
+ hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_pkinit");
+ }
+
+ if (opt->ms_upn_string) {
+ if (!ctopt.pkinit)
+ errx(1, "MS upn given but no pk-init oid");
+
+ ret = hx509_ca_tbs_add_san_ms_upn(contextp, tbs, opt->ms_upn_string);
+ if (ret)
+ hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_ms_upn");
+ }
+
+
+ for (i = 0; i < opt->hostname_strings.num_strings; i++) {
+ const char *hostname = opt->hostname_strings.strings[i];
+
+ ret = hx509_ca_tbs_add_san_hostname(contextp, tbs, hostname);
+ if (ret)
+ hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_hostname");
+ }
+
+ for (i = 0; i < opt->dnssrv_strings.num_strings; i++) {
+ const char *dnssrv = opt->dnssrv_strings.strings[i];
+
+ ret = hx509_ca_tbs_add_san_dnssrv(contextp, tbs, dnssrv);
+ if (ret)
+ hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_dnssrv");
+ }
+
+ for (i = 0; i < opt->email_strings.num_strings; i++) {
+ const char *email = opt->email_strings.strings[i];
+
+ ret = hx509_ca_tbs_add_san_rfc822name(contextp, tbs, email);
+ if (ret)
+ hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_hostname");
+
+ ret = hx509_ca_tbs_add_eku(contextp, tbs,
+ &asn1_oid_id_pkix_kp_emailProtection);
+ if (ret)
+ hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_eku");
+ }
+
+ if (opt->jid_string) {
+ ret = hx509_ca_tbs_add_san_jid(contextp, tbs, opt->jid_string);
+ if (ret)
+ hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_jid");
+ }
+
+ return 0;
+}
+
+int
+hxtool_ca(struct certificate_sign_options *opt, int argc, char **argv)
+{
+ int ret;
+ hx509_ca_tbs tbs;
+ hx509_cert signer = NULL, cert = NULL;
+ hx509_private_key private_key = NULL;
+ hx509_private_key cert_key = NULL;
+ hx509_name subject = NULL;
+ SubjectPublicKeyInfo spki;
+ heim_oid oid;
+ size_t i;
+ int delta = 0;
+
+ memset(&oid, 0, sizeof(oid));
+ memset(&spki, 0, sizeof(spki));
+
+ if (opt->ca_certificate_string == NULL && !opt->self_signed_flag)
+ errx(1, "--ca-certificate argument missing (not using --self-signed)");
+ if (opt->ca_private_key_string == NULL && opt->generate_key_string == NULL && opt->self_signed_flag)
+ errx(1, "--ca-private-key argument missing (using --self-signed)");
+ if (opt->certificate_string == NULL)
+ errx(1, "--certificate argument missing");
+
+ if (opt->template_certificate_string && opt->template_fields_string == NULL)
+ errx(1, "--template-certificate used but no --template-fields given");
+
+ if (opt->lifetime_string) {
+ delta = parse_time(opt->lifetime_string, "day");
+ if (delta < 0)
+ errx(1, "Invalid lifetime: %s", opt->lifetime_string);
+ }
+
+ if (opt->ca_certificate_string) {
+ hx509_certs cacerts = NULL;
+ hx509_query *q;
+ char *sn = fix_store_name(context, opt->ca_certificate_string, "FILE");
+
+ ret = hx509_certs_init(context, sn, 0, NULL, &cacerts);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_init: %s", sn);
+
+ ret = hx509_query_alloc(context, &q);
+ if (ret)
+ errx(1, "hx509_query_alloc: %d", ret);
+
+ hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
+ if (!opt->issue_proxy_flag)
+ hx509_query_match_option(q, HX509_QUERY_OPTION_KU_KEYCERTSIGN);
+
+ ret = hx509_certs_find(context, cacerts, q, &signer);
+ hx509_query_free(context, q);
+ hx509_certs_free(&cacerts);
+ if (ret)
+ hx509_err(context, 1, ret, "no CA certificate found");
+ free(sn);
+ } else if (opt->self_signed_flag) {
+ if (opt->generate_key_string == NULL
+ && opt->ca_private_key_string == NULL)
+ errx(1, "no signing private key");
+
+ if (opt->req_string)
+ errx(1, "can't be self-signing and have a request at the same time");
+ } else
+ errx(1, "missing ca key");
+
+ if (opt->ca_private_key_string) {
+
+ ret = read_private_key(opt->ca_private_key_string, &private_key);
+ if (ret)
+ err(1, "read_private_key");
+
+ ret = hx509_private_key2SPKI(context, private_key, &spki);
+ if (ret)
+ errx(1, "hx509_private_key2SPKI: %d\n", ret);
+
+ if (opt->self_signed_flag)
+ cert_key = private_key;
+ }
+
+ if (opt->req_string) {
+ hx509_request req;
+ char *cn = fix_csr_name(opt->req_string, "PKCS10");
+
+ /*
+ * Extract the CN and other attributes we want to preserve from the
+ * requested subjectName and then set them in the hx509_env for the
+ * template.
+ */
+ ret = hx509_request_parse(context, cn, &req);
+ if (ret)
+ hx509_err(context, 1, ret, "parse_request: %s", cn);
+ ret = hx509_request_get_name(context, req, &subject);
+ if (ret)
+ hx509_err(context, 1, ret, "get name");
+ ret = hx509_request_get_SubjectPublicKeyInfo(context, req, &spki);
+ if (ret)
+ hx509_err(context, 1, ret, "get spki");
+ hx509_request_free(&req);
+ free(cn);
+ }
+
+ if (opt->generate_key_string) {
+ struct hx509_generate_private_context *keyctx;
+
+ ret = _hx509_generate_private_key_init(context,
+ &asn1_oid_id_pkcs1_rsaEncryption,
+ &keyctx);
+ if (ret)
+ hx509_err(context, 1, ret, "generate private key");
+
+ if (opt->issue_ca_flag)
+ _hx509_generate_private_key_is_ca(context, keyctx);
+
+ if (opt->key_bits_integer)
+ _hx509_generate_private_key_bits(context, keyctx,
+ opt->key_bits_integer);
+
+ ret = _hx509_generate_private_key(context, keyctx,
+ &cert_key);
+ _hx509_generate_private_key_free(&keyctx);
+ if (ret)
+ hx509_err(context, 1, ret, "generate private key");
+
+ ret = hx509_private_key2SPKI(context, cert_key, &spki);
+ if (ret)
+ errx(1, "hx509_private_key2SPKI: %d\n", ret);
+
+ if (opt->self_signed_flag)
+ private_key = cert_key;
+ }
+
+ if (opt->certificate_private_key_string) {
+ ret = read_private_key(opt->certificate_private_key_string, &cert_key);
+ if (ret)
+ err(1, "read_private_key for certificate");
+ }
+
+ if (opt->subject_string) {
+ if (subject)
+ hx509_name_free(&subject);
+ ret = hx509_parse_name(context, opt->subject_string, &subject);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_parse_name");
+ }
+
+ /*
+ *
+ */
+
+ ret = hx509_ca_tbs_init(context, &tbs);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_tbs_init");
+
+ for (i = 0; i < opt->eku_strings.num_strings; i++) {
+ parse_oid(opt->eku_strings.strings[i], NULL, &oid);
+ ret = hx509_ca_tbs_add_eku(context, tbs, &oid);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_request_add_eku");
+ der_free_oid(&oid);
+ }
+ if (opt->ku_strings.num_strings) {
+ const struct units *kus = asn1_KeyUsage_units();
+ const struct units *kup;
+ uint64_t n = 0;
+
+ for (i = 0; i < opt->ku_strings.num_strings; i++) {
+ for (kup = kus; kup->name; kup++) {
+ if (strcmp(kup->name, opt->ku_strings.strings[i]))
+ continue;
+ n |= kup->mult;
+ break;
+ }
+ }
+ ret = hx509_ca_tbs_add_ku(context, tbs, int2KeyUsage(n));
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_request_add_ku");
+ }
+ if (opt->signature_algorithm_string) {
+ const AlgorithmIdentifier *sigalg;
+ if (strcasecmp(opt->signature_algorithm_string, "rsa-with-sha1") == 0)
+ sigalg = hx509_signature_rsa_with_sha1();
+ else if (strcasecmp(opt->signature_algorithm_string, "rsa-with-sha256") == 0)
+ sigalg = hx509_signature_rsa_with_sha256();
+ else
+ errx(1, "unsupported sigature algorithm");
+ hx509_ca_tbs_set_signature_algorithm(context, tbs, sigalg);
+ }
+
+ if (opt->template_certificate_string) {
+ hx509_cert template;
+ hx509_certs tcerts;
+ char *sn = fix_store_name(context, opt->template_certificate_string,
+ "FILE");
+ int flags;
+
+ ret = hx509_certs_init(context, sn, 0, NULL, &tcerts);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_init: %s", sn);
+
+ ret = hx509_get_one_cert(context, tcerts, &template);
+
+ hx509_certs_free(&tcerts);
+ if (ret)
+ hx509_err(context, 1, ret, "no template certificate found");
+
+ flags = parse_units(opt->template_fields_string,
+ hx509_ca_tbs_template_units(), "");
+
+ ret = hx509_ca_tbs_set_template(context, tbs, flags, template);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_tbs_set_template");
+
+ hx509_cert_free(template);
+ free(sn);
+ }
+
+ if (opt->serial_number_string) {
+ heim_integer serialNumber;
+
+ ret = der_parse_hex_heim_integer(opt->serial_number_string,
+ &serialNumber);
+ if (ret)
+ err(1, "der_parse_hex_heim_integer");
+ ret = hx509_ca_tbs_set_serialnumber(context, tbs, &serialNumber);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_tbs_init");
+ der_free_heim_integer(&serialNumber);
+ }
+
+ if (spki.subjectPublicKey.length) {
+ ret = hx509_ca_tbs_set_spki(context, tbs, &spki);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_tbs_set_spki");
+ }
+
+ if (subject) {
+ ret = hx509_ca_tbs_set_subject(context, tbs, subject);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_tbs_set_subject");
+ }
+
+ if (opt->crl_uri_string) {
+ ret = hx509_ca_tbs_add_crl_dp_uri(context, tbs,
+ opt->crl_uri_string, NULL);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_tbs_add_crl_dp_uri");
+ }
+
+ eval_types(context, tbs, opt);
+
+ if (opt->permanent_id_string) {
+ ret = hx509_ca_tbs_add_san_permanentIdentifier_string(context, tbs,
+ opt->permanent_id_string);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_tbs_add_san_permanentIdentifier");
+ }
+
+ if (opt->hardware_module_name_string) {
+ ret = hx509_ca_tbs_add_san_hardwareModuleName_string(context, tbs,
+ opt->hardware_module_name_string);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_tbs_add_san_hardwareModuleName_string");
+ }
+
+ for (i = 0; ret == 0 && i < opt->policy_strings.num_strings; i++) {
+ char *oidstr, *uri, *dt;
+
+ if ((oidstr = strdup(opt->policy_strings.strings[i])) == NULL)
+ hx509_err(context, 1, ENOMEM, "out of memory");
+ uri = strchr(oidstr, ':');
+ if (uri)
+ *(uri++) = '\0';
+ dt = strchr(uri ? uri : "", ' ');
+ if (dt)
+ *(dt++) = '\0';
+
+ parse_oid(oidstr, NULL, &oid);
+ ret = hx509_ca_tbs_add_pol(context, tbs, &oid, uri, dt);
+ der_free_oid(&oid);
+ free(oidstr);
+ }
+
+ for (i = 0; ret == 0 && i < opt->policy_mapping_strings.num_strings; i++) {
+ char *issuer_oidstr, *subject_oidstr;
+ heim_oid issuer_oid, subject_oid;
+
+ if ((issuer_oidstr =
+ strdup(opt->policy_mapping_strings.strings[i])) == NULL)
+ hx509_err(context, 1, ENOMEM, "out of memory");
+ subject_oidstr = strchr(issuer_oidstr, ':');
+ if (subject_oidstr == NULL)
+ subject_oidstr = issuer_oidstr;
+ else
+ *(subject_oidstr++) = '\0';
+
+ parse_oid(issuer_oidstr, NULL, &issuer_oid);
+ parse_oid(subject_oidstr, NULL, &subject_oid);
+ ret = hx509_ca_tbs_add_pol_mapping(context, tbs, &issuer_oid,
+ &subject_oid);
+ if (ret)
+ hx509_err(context, 1, ret, "failed to add policy mapping");
+ der_free_oid(&issuer_oid);
+ der_free_oid(&subject_oid);
+ free(issuer_oidstr);
+ }
+
+ if (opt->issue_ca_flag) {
+ ret = hx509_ca_tbs_set_ca(context, tbs, opt->path_length_integer);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_tbs_set_ca");
+ }
+ if (opt->issue_proxy_flag) {
+ ret = hx509_ca_tbs_set_proxy(context, tbs, opt->path_length_integer);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_tbs_set_proxy");
+ }
+ if (opt->domain_controller_flag) {
+ hx509_ca_tbs_set_domaincontroller(context, tbs);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_tbs_set_domaincontroller");
+ }
+
+ if (delta) {
+ ret = hx509_ca_tbs_set_notAfter_lifetime(context, tbs, delta);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_tbs_set_notAfter_lifetime");
+ }
+ if (opt->pkinit_max_life_string) {
+ time_t t = parse_time(opt->pkinit_max_life_string, "s");
+
+ ret = hx509_ca_tbs_set_pkinit_max_life(context, tbs, t);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_tbs_set_pkinit_max_life");
+ }
+
+ if (opt->self_signed_flag) {
+ ret = hx509_ca_sign_self(context, tbs, private_key, &cert);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_sign_self");
+ } else {
+ ret = hx509_ca_sign(context, tbs, signer, &cert);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_ca_sign");
+ }
+
+ if (cert_key) {
+ ret = _hx509_cert_assign_key(cert, cert_key);
+ if (ret)
+ hx509_err(context, 1, ret, "_hx509_cert_assign_key");
+ }
+
+ {
+ hx509_certs certs;
+ char *sn = fix_store_name(context, opt->certificate_string, "FILE");
+
+ ret = hx509_certs_init(context, sn, HX509_CERTS_CREATE, NULL, &certs);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_init");
+
+ ret = hx509_certs_add(context, certs, cert);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_add");
+
+ ret = hx509_certs_store(context, certs, 0, NULL);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_store");
+
+ hx509_certs_free(&certs);
+ free(sn);
+ }
+
+ if (subject)
+ hx509_name_free(&subject);
+ if (signer)
+ hx509_cert_free(signer);
+ hx509_cert_free(cert);
+ free_SubjectPublicKeyInfo(&spki);
+
+ if (private_key != cert_key)
+ hx509_private_key_free(&private_key);
+ hx509_private_key_free(&cert_key);
+
+ hx509_ca_tbs_free(&tbs);
+
+ return 0;
+}
+
+static int HX509_LIB_CALL
+test_one_cert(hx509_context hxcontext, void *ctx, hx509_cert cert)
+{
+ heim_octet_string sd, c;
+ hx509_verify_ctx vctx = ctx;
+ hx509_certs signer = NULL;
+ heim_oid type;
+ int ret;
+
+ if (_hx509_cert_private_key(cert) == NULL)
+ return 0;
+
+ ret = hx509_cms_create_signed_1(context, 0, NULL, NULL, 0,
+ NULL, cert, NULL, NULL, NULL, &sd);
+ if (ret)
+ errx(1, "hx509_cms_create_signed_1");
+
+ ret = hx509_cms_verify_signed(context, vctx, 0, sd.data, sd.length,
+ NULL, NULL, &type, &c, &signer);
+ free(sd.data);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_cms_verify_signed");
+
+ printf("create-signature verify-sigature done\n");
+
+ free(c.data);
+
+ return 0;
+}
+
+int
+test_crypto(struct test_crypto_options *opt, int argc, char ** argv)
+{
+ hx509_verify_ctx vctx;
+ hx509_certs certs;
+ hx509_lock lock;
+ int i, ret;
+
+ hx509_lock_init(context, &lock);
+ lock_strings(lock, &opt->pass_strings);
+
+ ret = hx509_certs_init(context, "MEMORY:test-crypto", 0, NULL, &certs);
+ if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+
+ for (i = 0; i < argc; i++) {
+ char *sn = fix_store_name(context, argv[i], "FILE");
+ ret = hx509_certs_append(context, certs, lock, sn);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_append %s", sn);
+ free(sn);
+ }
+
+ ret = hx509_verify_init_ctx(context, &vctx);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_verify_init_ctx");
+
+ hx509_verify_attach_anchors(vctx, certs);
+
+ ret = hx509_certs_iter_f(context, certs, test_one_cert, vctx);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_cert_iter");
+
+ hx509_certs_free(&certs);
+ hx509_verify_destroy_ctx(vctx);
+
+ return 0;
+}
+
+int
+statistic_print(struct statistic_print_options*opt, int argc, char **argv)
+{
+ int type = 0;
+
+ if (stat_file_string == NULL)
+ errx(1, "no stat file");
+
+ if (opt->type_integer)
+ type = opt->type_integer;
+
+ hx509_query_unparse_stats(context, type, stdout);
+ return 0;
+}
+
+/*
+ *
+ */
+
+int
+crl_sign(struct crl_sign_options *opt, int argc, char **argv)
+{
+ hx509_crl crl;
+ heim_octet_string os;
+ hx509_cert signer = NULL;
+ hx509_lock lock;
+ int ret;
+
+ hx509_lock_init(context, &lock);
+ lock_strings(lock, &opt->pass_strings);
+
+ ret = hx509_crl_alloc(context, &crl);
+ if (ret)
+ errx(1, "crl alloc");
+
+ if (opt->signer_string == NULL)
+ errx(1, "signer missing");
+
+ {
+ hx509_certs certs = NULL;
+ hx509_query *q;
+ char *sn = fix_store_name(context, opt->signer_string, "FILE");
+
+ ret = hx509_certs_init(context, sn, 0, NULL, &certs);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_init: %s", sn);
+
+ ret = hx509_query_alloc(context, &q);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_query_alloc: %d", ret);
+
+ hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
+
+ ret = hx509_certs_find(context, certs, q, &signer);
+ hx509_query_free(context, q);
+ hx509_certs_free(&certs);
+ if (ret)
+ hx509_err(context, 1, ret, "no signer certificate found");
+ free(sn);
+ }
+
+ if (opt->lifetime_string) {
+ int delta;
+
+ delta = parse_time(opt->lifetime_string, "day");
+ if (delta < 0)
+ errx(1, "Invalid lifetime: %s", opt->lifetime_string);
+
+ hx509_crl_lifetime(context, crl, delta);
+ }
+
+ {
+ hx509_certs revoked = NULL;
+ int i;
+
+ ret = hx509_certs_init(context, "MEMORY:revoked-certs", 0,
+ NULL, &revoked);
+ if (ret)
+ hx509_err(context, 1, ret,
+ "hx509_certs_init: MEMORY cert");
+
+ for (i = 0; i < argc; i++) {
+ char *sn = fix_store_name(context, argv[i], "FILE");
+
+ ret = hx509_certs_append(context, revoked, lock, sn);
+ if (ret)
+ hx509_err(context, 1, ret, "hx509_certs_append: %s", sn);
+ free(sn);
+ }
+
+ hx509_crl_add_revoked_certs(context, crl, revoked);
+ hx509_certs_free(&revoked);
+ }
+
+ hx509_crl_sign(context, signer, crl, &os);
+
+ if (opt->crl_file_string)
+ rk_dumpdata(opt->crl_file_string, os.data, os.length);
+
+ free(os.data);
+
+ hx509_crl_free(context, &crl);
+ hx509_cert_free(signer);
+ hx509_lock_free(lock);
+
+ return 0;
+}
+
+int
+hxtool_list_oids(void *opt, int argc, char **argv)
+{
+ const heim_oid *oid;
+ int cursor = -1;
+
+ while (der_match_heim_oid_by_name("", &cursor, &oid) == 0) {
+ char *s = NULL;
+
+ if ((errno = der_print_heim_oid_sym(oid, '.', &s)) > 0)
+ err(1, "der_print_heim_oid_sym");
+ printf("%s\n", s);
+ free(s);
+ }
+ return 0;
+}
+
+static int
+acert1_sans_utf8_other(struct acert_options *opt,
+ struct getarg_strings *wanted,
+ const char *type,
+ heim_any *san,
+ size_t *count)
+{
+ size_t k, len;
+
+ if (!wanted->num_strings)
+ return 0;
+ for (k = 0; k < wanted->num_strings; k++) {
+ len = strlen(wanted->strings[k]);
+ if (len == san->length &&
+ strncmp(san->data, wanted->strings[k], len) == 0) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Matched OtherName SAN %s (%s)\n",
+ wanted->strings[k], type);
+ (*count)++;
+ return 0;
+ }
+ }
+ if (opt->verbose_flag)
+ fprintf(stderr, "Did not match OtherName SAN %s (%s)\n",
+ wanted->strings[k], type);
+ return -1;
+}
+
+static int
+acert1_sans_other(struct acert_options *opt,
+ heim_oid *type_id,
+ heim_any *value,
+ size_t *count)
+{
+ heim_any pkinit;
+ size_t k, match;
+ const char *type_str = NULL;
+ char *s = NULL;
+ int ret;
+
+ (void) der_print_heim_oid_sym(type_id, '.', &s);
+ type_str = s ? s : "<unknown>";
+ if (der_heim_oid_cmp(type_id, &asn1_oid_id_pkix_on_xmppAddr) == 0) {
+ ret = acert1_sans_utf8_other(opt, &opt->has_xmpp_san_strings,
+ s ? s : "xmpp", value, count);
+ free(s);
+ return ret;
+ }
+ if (der_heim_oid_cmp(type_id, &asn1_oid_id_pkinit_san) != 0) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Ignoring OtherName SAN of type %s\n", type_str);
+ free(s);
+ return -1;
+ }
+
+ free(s);
+ type_str = s = NULL;
+
+ if (opt->has_pkinit_san_strings.num_strings == 0)
+ return 0;
+
+ for (k = 0; k < opt->has_pkinit_san_strings.num_strings; k++) {
+ const char *s2 = opt->has_pkinit_san_strings.strings[k];
+
+ if ((ret = _hx509_make_pkinit_san(context, s2, &pkinit)))
+ return ret;
+ match = (pkinit.length == value->length &&
+ memcmp(pkinit.data, value->data, pkinit.length) == 0);
+ free(pkinit.data);
+ if (match) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Matched PKINIT SAN %s\n", s2);
+ (*count)++;
+ return 0;
+ }
+ }
+ if (opt->verbose_flag)
+ fprintf(stderr, "Unexpected PKINIT SAN\n");
+ return -1;
+}
+
+static int
+acert1_sans(struct acert_options *opt,
+ Extension *e,
+ size_t *count,
+ size_t *found)
+{
+ heim_printable_string hps;
+ GeneralNames gns;
+ size_t i, k, sz;
+ size_t unwanted = 0;
+ int ret = 0;
+
+ memset(&gns, 0, sizeof(gns));
+ decode_GeneralNames(e->extnValue.data, e->extnValue.length, &gns, &sz);
+ for (i = 0; (ret == -1 || ret == 0) && i < gns.len; i++) {
+ GeneralName *gn = &gns.val[i];
+ const char *s;
+
+ (*found)++;
+ if (gn->element == choice_GeneralName_rfc822Name) {
+ for (k = 0; k < opt->has_email_san_strings.num_strings; k++) {
+ s = opt->has_email_san_strings.strings[k];
+ hps.data = rk_UNCONST(s);
+ hps.length = strlen(s);
+ if (der_printable_string_cmp(&gn->u.rfc822Name, &hps) == 0) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Matched e-mail address SAN %s\n", s);
+ (*count)++;
+ break;
+ }
+ }
+ if (k && k == opt->has_email_san_strings.num_strings) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Unexpected e-mail address SAN %.*s\n",
+ (int)gn->u.rfc822Name.length,
+ (const char *)gn->u.rfc822Name.data);
+ unwanted++;
+ }
+ } else if (gn->element == choice_GeneralName_dNSName) {
+ for (k = 0; k < opt->has_dnsname_san_strings.num_strings; k++) {
+ s = opt->has_dnsname_san_strings.strings[k];
+ hps.data = rk_UNCONST(s);
+ hps.length = strlen(s);
+ if (der_printable_string_cmp(&gn->u.dNSName, &hps) == 0) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Matched dNSName SAN %s\n", s);
+ (*count)++;
+ break;
+ }
+ }
+ if (k && k == opt->has_dnsname_san_strings.num_strings) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Unexpected e-mail address SAN %.*s\n",
+ (int)gn->u.dNSName.length,
+ (const char *)gn->u.dNSName.data);
+ unwanted++;
+ }
+ } else if (gn->element == choice_GeneralName_registeredID) {
+ for (k = 0; k < opt->has_registeredID_san_strings.num_strings; k++) {
+ heim_oid oid;
+
+ s = opt->has_registeredID_san_strings.strings[k];
+ memset(&oid, 0, sizeof(oid));
+ parse_oid(s, NULL, &oid);
+ if (der_heim_oid_cmp(&gn->u.registeredID, &oid) == 0) {
+ der_free_oid(&oid);
+ if (opt->verbose_flag)
+ fprintf(stderr, "Matched registeredID SAN %s\n", s);
+ (*count)++;
+ break;
+ }
+ der_free_oid(&oid);
+ }
+ if (k && k == opt->has_dnsname_san_strings.num_strings) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Unexpected registeredID SAN\n");
+ unwanted++;
+ }
+ } else if (gn->element == choice_GeneralName_otherName) {
+ ret = acert1_sans_other(opt, &gn->u.otherName.type_id,
+ &gn->u.otherName.value, count);
+ } else if (opt->verbose_flag) {
+ fprintf(stderr, "Unexpected unsupported SAN\n");
+ unwanted++;
+ }
+ }
+ free_GeneralNames(&gns);
+ if (ret == 0 && unwanted && opt->exact_flag)
+ return -1;
+ return ret;
+}
+
+static int
+acert1_ekus(struct acert_options *opt,
+ Extension *e,
+ size_t *count,
+ size_t *found)
+{
+ ExtKeyUsage eku;
+ size_t i, k, sz;
+ size_t unwanted = 0;
+ int ret = 0;
+
+ memset(&eku, 0, sizeof(eku));
+ decode_ExtKeyUsage(e->extnValue.data, e->extnValue.length, &eku, &sz);
+ for (i = 0; (ret == -1 || ret == 0) && i < eku.len; i++) {
+ (*found)++;
+ for (k = 0; k < opt->has_eku_strings.num_strings; k++) {
+ const char *s = opt->has_eku_strings.strings[k];
+ heim_oid oid;
+
+ memset(&oid, 0, sizeof(oid));
+ parse_oid(s, NULL, &oid);
+ if (der_heim_oid_cmp(&eku.val[i], &oid) == 0) {
+ der_free_oid(&oid);
+ if (opt->verbose_flag)
+ fprintf(stderr, "Matched EKU OID %s\n", s);
+ (*count)++;
+ break;
+ }
+ der_free_oid(&oid);
+ }
+ if (k && k == opt->has_eku_strings.num_strings) {
+ char *oids = NULL;
+
+ (void) der_print_heim_oid_sym(&eku.val[i], '.', &oids);
+ if (opt->verbose_flag)
+ fprintf(stderr, "Unexpected EKU OID %s\n",
+ oids ? oids : "<could-not-format-OID>");
+ unwanted++;
+ }
+ }
+ free_ExtKeyUsage(&eku);
+ if (ret == 0 && unwanted && opt->exact_flag)
+ return -1;
+ return ret;
+}
+
+static int
+acert1_kus(struct acert_options *opt,
+ Extension *e,
+ size_t *count,
+ size_t *found)
+{
+ const struct units *u = asn1_KeyUsage_units();
+ uint64_t ku_num;
+ KeyUsage ku;
+ size_t unwanted = 0;
+ size_t wanted = opt->has_ku_strings.num_strings;
+ size_t i, k, sz;
+ int ret;
+
+ memset(&ku, 0, sizeof(ku));
+ ret = decode_KeyUsage(e->extnValue.data, e->extnValue.length, &ku, &sz);
+ if (ret)
+ return ret;
+ ku_num = KeyUsage2int(ku);
+
+ /* Validate requested key usage values */
+ for (k = 0; k < wanted; k++) {
+ const char *s = opt->has_ku_strings.strings[k];
+
+ for (i = 0; u[i].name; i++)
+ if (strcmp(s, u[i].name) == 0)
+ break;
+
+ if (u[i].name == NULL)
+ warnx("Warning: requested key usage %s unknown", s);
+ }
+
+ for (i = 0; u[i].name; i++) {
+ if ((u[i].mult & ku_num))
+ (*found)++;
+ for (k = 0; k < wanted; k++) {
+ const char *s = opt->has_ku_strings.strings[k];
+
+ if (!(u[i].mult & ku_num) || strcmp(s, u[i].name) != 0)
+ continue;
+
+ if (opt->verbose_flag)
+ fprintf(stderr, "Matched key usage %s\n", s);
+ (*count)++;
+ break;
+ }
+ if ((u[i].mult & ku_num) && k == wanted) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Unexpected key usage %s\n", u[i].name);
+ unwanted++;
+ }
+ }
+
+ return (unwanted && opt->exact_flag) ? -1 : 0;
+}
+
+static time_t
+ptime(const char *s)
+{
+ struct tm at_tm;
+ char *rest;
+ int at_s;
+
+ if ((rest = strptime(s, "%Y-%m-%dT%H:%M:%S", &at_tm)) != NULL &&
+ rest[0] == '\0')
+ return mktime(&at_tm);
+ if ((rest = strptime(s, "%Y%m%d%H%M%S", &at_tm)) != NULL && rest[0] == '\0')
+ return mktime(&at_tm);
+ if ((at_s = parse_time(s, "s")) != -1)
+ return time(NULL) + at_s;
+ errx(1, "Could not parse time spec %s", s);
+}
+
+static int
+acert1_validity(struct acert_options *opt, hx509_cert cert)
+{
+ time_t not_before_eq = 0;
+ time_t not_before_lt = 0;
+ time_t not_before_gt = 0;
+ time_t not_after_eq = 0;
+ time_t not_after_lt = 0;
+ time_t not_after_gt = 0;
+ int ret = 0;
+
+ if (opt->valid_now_flag) {
+ time_t now = time(NULL);
+
+ if (hx509_cert_get_notBefore(cert) > now) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Certificate not valid yet\n");
+ ret = -1;
+ }
+ if (hx509_cert_get_notAfter(cert) < now) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Certificate currently expired\n");
+ ret = -1;
+ }
+ }
+ if (opt->valid_at_string) {
+ time_t at = ptime(opt->valid_at_string);
+
+ if (hx509_cert_get_notBefore(cert) > at) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Certificate not valid yet at %s\n",
+ opt->valid_at_string);
+ ret = -1;
+ }
+ if (hx509_cert_get_notAfter(cert) < at) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Certificate expired before %s\n",
+ opt->valid_at_string);
+ ret = -1;
+ }
+ }
+
+ if (opt->not_before_eq_string)
+ not_before_eq = ptime(opt->not_before_eq_string);
+ if (opt->not_before_lt_string)
+ not_before_lt = ptime(opt->not_before_lt_string);
+ if (opt->not_before_gt_string)
+ not_before_gt = ptime(opt->not_before_gt_string);
+ if (opt->not_after_eq_string)
+ not_after_eq = ptime(opt->not_after_eq_string);
+ if (opt->not_after_lt_string)
+ not_after_lt = ptime(opt->not_after_lt_string);
+ if (opt->not_after_gt_string)
+ not_after_gt = ptime(opt->not_after_gt_string);
+
+ if ((not_before_eq && hx509_cert_get_notBefore(cert) != not_before_eq) ||
+ (not_before_lt && hx509_cert_get_notBefore(cert) >= not_before_lt) ||
+ (not_before_gt && hx509_cert_get_notBefore(cert) <= not_before_gt)) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Certificate notBefore not as requested\n");
+ ret = -1;
+ }
+ if ((not_after_eq && hx509_cert_get_notAfter(cert) != not_after_eq) ||
+ (not_after_lt && hx509_cert_get_notAfter(cert) >= not_after_lt) ||
+ (not_after_gt && hx509_cert_get_notAfter(cert) <= not_after_gt)) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Certificate notAfter not as requested\n");
+ ret = -1;
+ }
+
+ if (opt->has_private_key_flag && !hx509_cert_have_private_key(cert)) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Certificate does not have a private key\n");
+ ret = -1;
+ }
+
+ if (opt->lacks_private_key_flag && hx509_cert_have_private_key(cert)) {
+ if (opt->verbose_flag)
+ fprintf(stderr, "Certificate does not have a private key\n");
+ ret = -1;
+ }
+
+ return ret;
+}
+
+static int
+acert1(struct acert_options *opt, size_t cert_num, hx509_cert cert, int *matched)
+{
+ const heim_oid *misc_exts [] = {
+ &asn1_oid_id_x509_ce_authorityKeyIdentifier,
+ &asn1_oid_id_x509_ce_subjectKeyIdentifier,
+ &asn1_oid_id_x509_ce_basicConstraints,
+ &asn1_oid_id_x509_ce_nameConstraints,
+ &asn1_oid_id_x509_ce_certificatePolicies,
+ &asn1_oid_id_x509_ce_policyMappings,
+ &asn1_oid_id_x509_ce_issuerAltName,
+ &asn1_oid_id_x509_ce_subjectDirectoryAttributes,
+ &asn1_oid_id_x509_ce_policyConstraints,
+ &asn1_oid_id_x509_ce_cRLDistributionPoints,
+ &asn1_oid_id_x509_ce_deltaCRLIndicator,
+ &asn1_oid_id_x509_ce_issuingDistributionPoint,
+ &asn1_oid_id_x509_ce_inhibitAnyPolicy,
+ &asn1_oid_id_x509_ce_cRLNumber,
+ &asn1_oid_id_x509_ce_freshestCRL,
+ NULL
+ };
+ const Certificate *c;
+ const Extensions *e;
+ KeyUsage ku;
+ size_t matched_elements = 0;
+ size_t wanted, sans_wanted, ekus_wanted, kus_wanted;
+ size_t found, sans_found, ekus_found, kus_found;
+ size_t i, k;
+ int ret;
+
+ if ((c = _hx509_get_cert(cert)) == NULL)
+ errx(1, "Could not get Certificate");
+ e = c->tbsCertificate.extensions;
+
+ ret = _hx509_cert_get_keyusage(context, cert, &ku);
+ if (ret && ret != HX509_KU_CERT_MISSING)
+ hx509_err(context, 1, ret, "Could not get key usage of certificate");
+ if (ret == HX509_KU_CERT_MISSING && opt->ca_flag)
+ return 0; /* want CA cert; this isn't it */
+ if (ret == 0 && opt->ca_flag && !ku.keyCertSign)
+ return 0; /* want CA cert; this isn't it */
+ if (ret == 0 && opt->end_entity_flag && ku.keyCertSign)
+ return 0; /* want EE cert; this isn't it */
+
+ if (opt->cert_num_integer != -1 && cert_num <= INT_MAX &&
+ opt->cert_num_integer != (int)cert_num)
+ return 0;
+ if (opt->cert_num_integer == -1 || opt->cert_num_integer == (int)cert_num)
+ *matched = 1;
+
+ if (_hx509_cert_get_version(c) < 3) {
+ warnx("Certificate with version %d < 3 ignored",
+ _hx509_cert_get_version(c));
+ return 0;
+ }
+
+ sans_wanted = opt->has_email_san_strings.num_strings
+ + opt->has_xmpp_san_strings.num_strings
+ + opt->has_ms_upn_san_strings.num_strings
+ + opt->has_dnsname_san_strings.num_strings
+ + opt->has_pkinit_san_strings.num_strings
+ + opt->has_registeredID_san_strings.num_strings;
+ ekus_wanted = opt->has_eku_strings.num_strings;
+ kus_wanted = opt->has_ku_strings.num_strings;
+ wanted = sans_wanted + ekus_wanted + kus_wanted;
+ sans_found = ekus_found = kus_found = 0;
+
+ if (e == NULL) {
+ if (wanted)
+ return -1;
+ return acert1_validity(opt, cert);
+ }
+
+ for (i = 0; i < e->len; i++) {
+ if (der_heim_oid_cmp(&e->val[i].extnID,
+ &asn1_oid_id_x509_ce_subjectAltName) == 0) {
+ ret = acert1_sans(opt, &e->val[i], &matched_elements, &sans_found);
+ if (ret == -1 && sans_wanted == 0 &&
+ (!opt->exact_flag || sans_found == 0))
+ ret = 0;
+ } else if (der_heim_oid_cmp(&e->val[i].extnID,
+ &asn1_oid_id_x509_ce_extKeyUsage) == 0) {
+ ret = acert1_ekus(opt, &e->val[i], &matched_elements, &ekus_found);
+ if (ret == -1 && ekus_wanted == 0 &&
+ (!opt->exact_flag || ekus_found == 0))
+ ret = 0;
+ } else if (der_heim_oid_cmp(&e->val[i].extnID,
+ &asn1_oid_id_x509_ce_keyUsage) == 0) {
+ ret = acert1_kus(opt, &e->val[i], &matched_elements, &kus_found);
+ if (ret == -1 && kus_wanted == 0 &&
+ (!opt->exact_flag || kus_found == 0))
+ ret = 0;
+ } else {
+ char *oids = NULL;
+
+ for (k = 0; misc_exts[k]; k++) {
+ if (der_heim_oid_cmp(&e->val[i].extnID, misc_exts[k]) == 0)
+ break;
+ }
+ if (misc_exts[k])
+ continue;
+
+ (void) der_print_heim_oid(&e->val[i].extnID, '.', &oids);
+ warnx("Matching certificate has unexpected certificate "
+ "extension %s", oids ? oids : "<could not display OID>");
+ free(oids);
+ ret = -1;
+ }
+ if (ret && ret != -1)
+ hx509_err(context, 1, ret, "Error checking matching certificate");
+ if (ret == -1)
+ break;
+ }
+ if (matched_elements != wanted)
+ return -1;
+ found = sans_found + ekus_found + kus_found;
+ if (matched_elements != found && opt->exact_flag)
+ return -1;
+ if (ret)
+ return ret;
+ return acert1_validity(opt, cert);
+}
+
+int
+acert(struct acert_options *opt, int argc, char **argv)
+{
+ hx509_cursor cursor = NULL;
+ hx509_query *q = NULL;
+ hx509_certs certs = NULL;
+ hx509_cert cert = NULL;
+ char *sn = fix_store_name(context, argv[0], "FILE");
+ size_t n = 0;
+ int matched = 0;
+ int ret;
+
+ if (opt->not_after_eq_string &&
+ (opt->not_after_lt_string || opt->not_after_gt_string))
+ errx(1, "--not-after-eq should not be given with --not-after-lt/gt");
+ if (opt->not_before_eq_string &&
+ (opt->not_before_lt_string || opt->not_before_gt_string))
+ errx(1, "--not-before-eq should not be given with --not-before-lt/gt");
+
+ if ((ret = hx509_certs_init(context, sn, 0, NULL, &certs)))
+ hx509_err(context, 1, ret, "Could not load certificates from %s", sn);
+
+ if (opt->expr_string) {
+ if ((ret = hx509_query_alloc(context, &q)) ||
+ (ret = hx509_query_match_expr(context, q, opt->expr_string)))
+ hx509_err(context, 1, ret, "Could not initialize query");
+ if ((ret = hx509_certs_find(context, certs, q, &cert)) || !cert)
+ hx509_err(context, 1, ret, "No matching certificate");
+ ret = acert1(opt, -1, cert, &matched);
+ matched = 1;
+ } else {
+ ret = hx509_certs_start_seq(context, certs, &cursor);
+ while (ret == 0 &&
+ (ret = hx509_certs_next_cert(context, certs,
+ cursor, &cert)) == 0 &&
+ cert) {
+ ret = acert1(opt, n++, cert, &matched);
+ if (matched)
+ break;
+ hx509_cert_free(cert);
+ cert = NULL;
+ }
+ if (cursor)
+ (void) hx509_certs_end_seq(context, certs, cursor);
+ }
+ if (!matched && ret)
+ hx509_err(context, 1, ret, "Could not find certificate");
+ if (!matched)
+ errx(1, "Could not find certificate");
+ if (ret == -1)
+ errx(1, "Matching certificate did not meet requirements");
+ if (ret)
+ hx509_err(context, 1, ret, "Matching certificate did not meet "
+ "requirements");
+ hx509_cert_free(cert);
+ free(sn);
+ return 0;
+}
+
+/*
+ *
+ */
+
+int
+help(void *opt, int argc, char **argv)
+{
+ sl_slc_help(commands, argc, argv);
+ return 0;
+}
+
+int
+main(int argc, char **argv)
+{
+ int ret, optidx = 0;
+
+ setprogname (argv[0]);
+
+ if(getarg(args, num_args, argc, argv, &optidx))
+ usage(1);
+ if(help_flag)
+ usage(0);
+ if(version_flag) {
+ print_version(NULL);
+ exit(0);
+ }
+ argv += optidx;
+ argc -= optidx;
+
+ if (argc == 0)
+ usage(1);
+
+ ret = hx509_context_init(&context);
+ if (ret)
+ errx(1, "hx509_context_init failed with %d", ret);
+
+ if (stat_file_string)
+ hx509_query_statistic_file(context, stat_file_string);
+
+ ret = sl_command(commands, argc, argv);
+ if(ret == -1)
+ warnx ("unrecognized command: %s", argv[0]);
+
+ hx509_context_free(&context);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/hx509/keyset.c b/third_party/heimdal/lib/hx509/keyset.c
new file mode 100644
index 0000000..f25cdf4
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/keyset.c
@@ -0,0 +1,846 @@
+/*
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+/**
+ * @page page_keyset Certificate store operations
+ *
+ * Type of certificates store:
+ * - MEMORY
+ * In memory based format. Doesn't support storing.
+ * - FILE
+ * FILE supports raw DER certicates and PEM certicates. When PEM is
+ * used the file can contain may certificates and match private
+ * keys. Support storing the certificates. DER format only supports
+ * on certificate and no private key.
+ * - PEM-FILE
+ * Same as FILE, defaulting to PEM encoded certificates.
+ * - PEM-FILE
+ * Same as FILE, defaulting to DER encoded certificates.
+ * - PKCS11
+ * - PKCS12
+ * - DIR
+ * - KEYCHAIN
+ * Apple Mac OS X KeyChain backed keychain object.
+ *
+ * See the library functions here: @ref hx509_keyset
+ */
+
+struct hx509_certs_data {
+ unsigned int ref;
+ struct hx509_keyset_ops *ops;
+ void *ops_data;
+ int flags;
+};
+
+struct hx509_keyset_ops *
+_hx509_ks_type(hx509_context context, const char *type)
+{
+ int i;
+
+ for (i = 0; i < context->ks_num_ops; i++)
+ if (strcasecmp(type, context->ks_ops[i]->name) == 0)
+ return context->ks_ops[i];
+
+ return NULL;
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_ks_register(hx509_context context, struct hx509_keyset_ops *ops)
+{
+ struct hx509_keyset_ops **val;
+
+ if (_hx509_ks_type(context, ops->name))
+ return;
+
+ val = realloc(context->ks_ops,
+ (context->ks_num_ops + 1) * sizeof(context->ks_ops[0]));
+ if (val == NULL)
+ return;
+ val[context->ks_num_ops] = ops;
+ context->ks_ops = val;
+ context->ks_num_ops++;
+}
+
+/**
+ * Open or creates a new hx509 certificate store.
+ *
+ * @param context A hx509 context
+ * @param name name of the store, format is TYPE:type-specific-string,
+ * if NULL is used the MEMORY store is used.
+ * @param flags list of flags:
+ * - HX509_CERTS_CREATE create a new keystore of the specific TYPE.
+ * - HX509_CERTS_UNPROTECT_ALL fails if any private key failed to be extracted.
+ * - HX509_CERTS_NO_PRIVATE_KEYS does not load or permit adding private keys
+ * @param lock a lock that unlocks the certificates store, use NULL to
+ * select no password/certifictes/prompt lock (see @ref page_lock).
+ * @param certs return pointer, free with hx509_certs_free().
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_certs_init(hx509_context context,
+ const char *name, int flags,
+ hx509_lock lock, hx509_certs *certs)
+{
+ struct hx509_keyset_ops *ops;
+ const char *residue;
+ hx509_certs c;
+ char *type;
+ int ret;
+
+ *certs = NULL;
+
+ if (name == NULL)
+ name = "";
+
+ residue = strchr(name, ':');
+ if (residue) {
+ type = malloc(residue - name + 1);
+ if (type)
+ strlcpy(type, name, residue - name + 1);
+ residue++;
+ if (residue[0] == '\0')
+ residue = NULL;
+ } else {
+ type = strdup("MEMORY");
+ residue = name;
+ }
+ if (type == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+
+ ops = _hx509_ks_type(context, type);
+ if (ops == NULL) {
+ hx509_set_error_string(context, 0, ENOENT,
+ "Keyset type %s is not supported", type);
+ free(type);
+ return ENOENT;
+ }
+ free(type);
+ c = calloc(1, sizeof(*c));
+ if (c == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+ c->flags = flags;
+ c->ops = ops;
+ c->ref = 1;
+
+ ret = (*ops->init)(context, c, &c->ops_data, flags, residue, lock);
+ if (ret) {
+ free(c);
+ return ret;
+ }
+
+ *certs = c;
+ return 0;
+}
+
+/**
+ * Destroys and frees a hx509 certificate store.
+ *
+ * @param context A hx509 context
+ * @param certs A store to destroy
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_certs_destroy(hx509_context context,
+ hx509_certs *certs)
+{
+ int ret = 0;
+
+ if (*certs) {
+ if ((*certs)->ops->destroy)
+ ret = ((*certs)->ops->destroy)(context, *certs, (*certs)->ops_data);
+ else
+ ret = ENOTSUP;
+ }
+ hx509_certs_free(certs);
+ return ret;
+}
+
+/**
+ * Write the certificate store to stable storage.
+ *
+ * Use the HX509_CERTS_STORE_NO_PRIVATE_KEYS flag to ensure that no private
+ * keys are stored, even if added.
+ *
+ * @param context A hx509 context.
+ * @param certs a certificate store to store.
+ * @param flags currently one flag is defined: HX509_CERTS_STORE_NO_PRIVATE_KEYS
+ * @param lock a lock that unlocks the certificates store, use NULL to
+ * select no password/certifictes/prompt lock (see @ref page_lock).
+ *
+ * @return Returns an hx509 error code. HX509_UNSUPPORTED_OPERATION if
+ * the certificate store doesn't support the store operation.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_certs_store(hx509_context context,
+ hx509_certs certs,
+ int flags,
+ hx509_lock lock)
+{
+ if (certs->ops->store == NULL) {
+ hx509_set_error_string(context, 0, HX509_UNSUPPORTED_OPERATION,
+ "keystore if type %s doesn't support "
+ "store operation",
+ certs->ops->name);
+ return HX509_UNSUPPORTED_OPERATION;
+ }
+
+ return (*certs->ops->store)(context, certs, certs->ops_data, flags, lock);
+}
+
+
+HX509_LIB_FUNCTION hx509_certs HX509_LIB_CALL
+hx509_certs_ref(hx509_certs certs)
+{
+ if (certs == NULL)
+ return NULL;
+ if (certs->ref == 0)
+ _hx509_abort("certs refcount == 0 on ref");
+ if (certs->ref == UINT_MAX)
+ _hx509_abort("certs refcount == UINT_MAX on ref");
+ certs->ref++;
+ return certs;
+}
+
+/**
+ * Free a certificate store.
+ *
+ * @param certs certificate store to free.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_certs_free(hx509_certs *certs)
+{
+ if (*certs) {
+ if ((*certs)->ref == 0)
+ _hx509_abort("cert refcount == 0 on free");
+ if (--(*certs)->ref > 0)
+ return;
+
+ (*(*certs)->ops->free)(*certs, (*certs)->ops_data);
+ free(*certs);
+ *certs = NULL;
+ }
+}
+
+/**
+ * Start the integration
+ *
+ * @param context a hx509 context.
+ * @param certs certificate store to iterate over
+ * @param cursor cursor that will keep track of progress, free with
+ * hx509_certs_end_seq().
+ *
+ * @return Returns an hx509 error code. HX509_UNSUPPORTED_OPERATION is
+ * returned if the certificate store doesn't support the iteration
+ * operation.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_certs_start_seq(hx509_context context,
+ hx509_certs certs,
+ hx509_cursor *cursor)
+{
+ int ret;
+
+ if (certs->ops->iter_start == NULL) {
+ hx509_set_error_string(context, 0, HX509_UNSUPPORTED_OPERATION,
+ "Keyset type %s doesn't support iteration",
+ certs->ops->name);
+ return HX509_UNSUPPORTED_OPERATION;
+ }
+
+ ret = (*certs->ops->iter_start)(context, certs, certs->ops_data, cursor);
+ if (ret)
+ return ret;
+
+ return 0;
+}
+
+/**
+ * Get next ceritificate from the certificate keystore pointed out by
+ * cursor.
+ *
+ * @param context a hx509 context.
+ * @param certs certificate store to iterate over.
+ * @param cursor cursor that keeps track of progress.
+ * @param cert return certificate next in store, NULL if the store
+ * contains no more certificates. Free with hx509_cert_free().
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_certs_next_cert(hx509_context context,
+ hx509_certs certs,
+ hx509_cursor cursor,
+ hx509_cert *cert)
+{
+ *cert = NULL;
+ return (*certs->ops->iter)(context, certs, certs->ops_data, cursor, cert);
+}
+
+/**
+ * End the iteration over certificates.
+ *
+ * @param context a hx509 context.
+ * @param certs certificate store to iterate over.
+ * @param cursor cursor that will keep track of progress, freed.
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_certs_end_seq(hx509_context context,
+ hx509_certs certs,
+ hx509_cursor cursor)
+{
+ (*certs->ops->iter_end)(context, certs, certs->ops_data, cursor);
+ return 0;
+}
+
+/**
+ * Iterate over all certificates in a keystore and call a function
+ * for each of them.
+ *
+ * @param context a hx509 context.
+ * @param certs certificate store to iterate over.
+ * @param func function to call for each certificate. The function
+ * should return non-zero to abort the iteration, that value is passed
+ * back to the caller of hx509_certs_iter_f().
+ * @param ctx context variable that will passed to the function.
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_certs_iter_f(hx509_context context,
+ hx509_certs certs,
+ int (HX509_LIB_CALL *func)(hx509_context, void *, hx509_cert),
+ void *ctx)
+{
+ hx509_cursor cursor;
+ hx509_cert c;
+ int ret;
+
+ ret = hx509_certs_start_seq(context, certs, &cursor);
+ if (ret)
+ return ret;
+
+ while (1) {
+ ret = hx509_certs_next_cert(context, certs, cursor, &c);
+ if (ret)
+ break;
+ if (c == NULL) {
+ ret = 0;
+ break;
+ }
+ ret = (*func)(context, ctx, c);
+ hx509_cert_free(c);
+ if (ret)
+ break;
+ }
+
+ hx509_certs_end_seq(context, certs, cursor);
+
+ return ret;
+}
+
+#ifdef __BLOCKS__
+
+static int
+certs_iter(hx509_context context, void *ctx, hx509_cert cert)
+{
+ int (^func)(hx509_cert) = ctx;
+ return func(cert);
+}
+
+/**
+ * Iterate over all certificates in a keystore and call a block
+ * for each of them.
+ *
+ * @param context a hx509 context.
+ * @param certs certificate store to iterate over.
+ * @param func block to call for each certificate. The function
+ * should return non-zero to abort the iteration, that value is passed
+ * back to the caller of hx509_certs_iter().
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_certs_iter(hx509_context context,
+ hx509_certs certs,
+ int (^func)(hx509_cert))
+{
+ return hx509_certs_iter_f(context, certs, certs_iter, func);
+}
+#endif
+
+
+/**
+ * Function to use to hx509_certs_iter_f() as a function argument, the
+ * ctx variable to hx509_certs_iter_f() should be a FILE file descriptor.
+ *
+ * @param context a hx509 context.
+ * @param ctx used by hx509_certs_iter_f().
+ * @param c a certificate
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ci_print_names(hx509_context context, void *ctx, hx509_cert c)
+{
+ Certificate *cert;
+ hx509_name n;
+ char *s, *i;
+
+ cert = _hx509_get_cert(c);
+
+ _hx509_name_from_Name(&cert->tbsCertificate.subject, &n);
+ hx509_name_to_string(n, &s);
+ hx509_name_free(&n);
+ _hx509_name_from_Name(&cert->tbsCertificate.issuer, &n);
+ hx509_name_to_string(n, &i);
+ hx509_name_free(&n);
+ fprintf(ctx, "subject: %s\nissuer: %s\n", s, i);
+ free(s);
+ free(i);
+ return 0;
+}
+
+/**
+ * Add a certificate to the certificiate store.
+ *
+ * The receiving keyset certs will either increase reference counter
+ * of the cert or make a deep copy, either way, the caller needs to
+ * free the cert itself.
+ *
+ * @param context a hx509 context.
+ * @param certs certificate store to add the certificate to.
+ * @param cert certificate to add.
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_certs_add(hx509_context context, hx509_certs certs, hx509_cert cert)
+{
+ hx509_cert copy = NULL;
+ int ret;
+
+ if (certs->ops->add == NULL) {
+ hx509_set_error_string(context, 0, ENOENT,
+ "Keyset type %s doesn't support add operation",
+ certs->ops->name);
+ return ENOENT;
+ }
+
+ if ((certs->flags & HX509_CERTS_NO_PRIVATE_KEYS) &&
+ hx509_cert_have_private_key(cert)) {
+ if ((copy = hx509_cert_copy_no_private_key(context, cert,
+ NULL)) == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM,
+ "Could not add certificate to store");
+ return ENOMEM;
+ }
+ cert = copy;
+ }
+
+ ret = (*certs->ops->add)(context, certs, certs->ops_data, cert);
+ hx509_cert_free(copy);
+ return ret;
+}
+
+/**
+ * Find a certificate matching the query.
+ *
+ * @param context a hx509 context.
+ * @param certs certificate store to search.
+ * @param q query allocated with @ref hx509_query functions.
+ * @param r return certificate (or NULL on error), should be freed
+ * with hx509_cert_free().
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_certs_find(hx509_context context,
+ hx509_certs certs,
+ const hx509_query *q,
+ hx509_cert *r)
+{
+ hx509_cursor cursor;
+ hx509_cert c;
+ int ret;
+
+ *r = NULL;
+
+ _hx509_query_statistic(context, 0, q);
+
+ if (certs->ops->query)
+ return (*certs->ops->query)(context, certs, certs->ops_data, q, r);
+
+ ret = hx509_certs_start_seq(context, certs, &cursor);
+ if (ret)
+ return ret;
+
+ c = NULL;
+ while (1) {
+ ret = hx509_certs_next_cert(context, certs, cursor, &c);
+ if (ret)
+ break;
+ if (c == NULL)
+ break;
+ if (_hx509_query_match_cert(context, q, c)) {
+ *r = c;
+ c = NULL;
+ break;
+ }
+ hx509_cert_free(c);
+ c = NULL;
+ }
+
+ hx509_cert_free(c);
+ hx509_certs_end_seq(context, certs, cursor);
+ if (ret)
+ return ret;
+ /**
+ * Return HX509_CERT_NOT_FOUND if no certificate in certs matched
+ * the query.
+ */
+ if (*r == NULL) {
+ hx509_clear_error_string(context);
+ return HX509_CERT_NOT_FOUND;
+ }
+
+ return 0;
+}
+
+/**
+ * Filter certificate matching the query.
+ *
+ * @param context a hx509 context.
+ * @param certs certificate store to search.
+ * @param q query allocated with @ref hx509_query functions.
+ * @param result the filtered certificate store, caller must free with
+ * hx509_certs_free().
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_certs_filter(hx509_context context,
+ hx509_certs certs,
+ const hx509_query *q,
+ hx509_certs *result)
+{
+ hx509_cursor cursor;
+ hx509_cert c;
+ int ret, found = 0;
+
+ _hx509_query_statistic(context, 0, q);
+
+ ret = hx509_certs_init(context, "MEMORY:filter-certs", 0,
+ NULL, result);
+ if (ret)
+ return ret;
+
+ ret = hx509_certs_start_seq(context, certs, &cursor);
+ if (ret) {
+ hx509_certs_free(result);
+ return ret;
+ }
+
+ c = NULL;
+ while (1) {
+ ret = hx509_certs_next_cert(context, certs, cursor, &c);
+ if (ret)
+ break;
+ if (c == NULL)
+ break;
+ if (_hx509_query_match_cert(context, q, c)) {
+ hx509_certs_add(context, *result, c);
+ found = 1;
+ }
+ hx509_cert_free(c);
+ }
+
+ hx509_certs_end_seq(context, certs, cursor);
+ if (ret) {
+ hx509_certs_free(result);
+ return ret;
+ }
+
+ /**
+ * Return HX509_CERT_NOT_FOUND if no certificate in certs matched
+ * the query.
+ */
+ if (!found) {
+ hx509_certs_free(result);
+ hx509_clear_error_string(context);
+ return HX509_CERT_NOT_FOUND;
+ }
+
+ return 0;
+}
+
+
+static int HX509_LIB_CALL
+certs_merge_func(hx509_context context, void *ctx, hx509_cert c)
+{
+ return hx509_certs_add(context, (hx509_certs)ctx, c);
+}
+
+/**
+ * Merge one certificate store into another. The from store is kept intact.
+ *
+ * @param context a hx509 context.
+ * @param to the store to merge into.
+ * @param from the store to copy the object from.
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_certs_merge(hx509_context context, hx509_certs to, hx509_certs from)
+{
+ if (from == NULL)
+ return 0;
+ return hx509_certs_iter_f(context, from, certs_merge_func, to);
+}
+
+/**
+ * Same a hx509_certs_merge() but use a lock and name to describe the
+ * from source.
+ *
+ * @param context a hx509 context.
+ * @param to the store to merge into.
+ * @param lock a lock that unlocks the certificates store, use NULL to
+ * select no password/certifictes/prompt lock (see @ref page_lock).
+ * @param name name of the source store
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_certs_append(hx509_context context,
+ hx509_certs to,
+ hx509_lock lock,
+ const char *name)
+{
+ hx509_certs s;
+ int ret;
+
+ ret = hx509_certs_init(context, name, 0, lock, &s);
+ if (ret)
+ return ret;
+ ret = hx509_certs_merge(context, to, s);
+ hx509_certs_free(&s);
+ return ret;
+}
+
+/**
+ * Get one random certificate from the certificate store.
+ *
+ * @param context a hx509 context.
+ * @param certs a certificate store to get the certificate from.
+ * @param c return certificate, should be freed with hx509_cert_free().
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_get_one_cert(hx509_context context, hx509_certs certs, hx509_cert *c)
+{
+ hx509_cursor cursor;
+ int ret;
+
+ *c = NULL;
+
+ ret = hx509_certs_start_seq(context, certs, &cursor);
+ if (ret)
+ return ret;
+
+ ret = hx509_certs_next_cert(context, certs, cursor, c);
+ if (ret)
+ return ret;
+
+ hx509_certs_end_seq(context, certs, cursor);
+ return 0;
+}
+
+static int
+certs_info_stdio(void *ctx, const char *str)
+{
+ FILE *f = ctx;
+ fprintf(f, "%s\n", str);
+ return 0;
+}
+
+/**
+ * Print some info about the certificate store.
+ *
+ * @param context a hx509 context.
+ * @param certs certificate store to print information about.
+ * @param func function that will get each line of the information, if
+ * NULL is used the data is printed on a FILE descriptor that should
+ * be passed in ctx, if ctx also is NULL, stdout is used.
+ * @param ctx parameter to func.
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_certs_info(hx509_context context,
+ hx509_certs certs,
+ int (*func)(void *, const char *),
+ void *ctx)
+{
+ if (func == NULL) {
+ func = certs_info_stdio;
+ if (ctx == NULL)
+ ctx = stdout;
+ }
+ if (certs->ops->printinfo == NULL) {
+ (*func)(ctx, "No info function for certs");
+ return 0;
+ }
+ return (*certs->ops->printinfo)(context, certs, certs->ops_data,
+ func, ctx);
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_pi_printf(int (*func)(void *, const char *), void *ctx,
+ const char *fmt, ...)
+{
+ va_list ap;
+ char *str;
+ int ret;
+
+ va_start(ap, fmt);
+ ret = vasprintf(&str, fmt, ap);
+ va_end(ap);
+ if (ret == -1 || str == NULL)
+ return;
+ (*func)(ctx, str);
+ free(str);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_certs_keys_get(hx509_context context,
+ hx509_certs certs,
+ hx509_private_key **keys)
+{
+ if (certs->ops->getkeys == NULL) {
+ *keys = NULL;
+ return 0;
+ }
+ return (*certs->ops->getkeys)(context, certs, certs->ops_data, keys);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_certs_keys_add(hx509_context context,
+ hx509_certs certs,
+ hx509_private_key key)
+{
+ if (certs->ops->addkey == NULL) {
+ hx509_set_error_string(context, 0, EINVAL,
+ "keystore if type %s doesn't support "
+ "key add operation",
+ certs->ops->name);
+ return EINVAL;
+ }
+ return (*certs->ops->addkey)(context, certs, certs->ops_data, key);
+}
+
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_certs_keys_free(hx509_context context,
+ hx509_private_key *keys)
+{
+ size_t i;
+
+ if (keys == NULL)
+ return;
+ for (i = 0; keys[i]; i++)
+ hx509_private_key_free(&keys[i]);
+ free(keys);
+}
diff --git a/third_party/heimdal/lib/hx509/ks_dir.c b/third_party/heimdal/lib/hx509/ks_dir.c
new file mode 100644
index 0000000..3bc99f2
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/ks_dir.c
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+#include <dirent.h>
+
+/*
+ * The DIR keyset module is strange compared to the other modules
+ * since it does lazy evaluation and really doesn't keep any local
+ * state except for the directory iteration and cert iteration of
+ * files. DIR ignores most errors so that the consumer doesn't get
+ * failes for stray files in directories.
+ */
+
+struct dircursor {
+ DIR *dir;
+ hx509_certs certs;
+ void *iter;
+};
+
+/*
+ *
+ */
+
+static int
+dir_init(hx509_context context,
+ hx509_certs certs, void **data, int flags,
+ const char *residue, hx509_lock lock)
+{
+ *data = NULL;
+
+ if (residue == NULL || residue[0] == '\0') {
+ hx509_set_error_string(context, 0, EINVAL,
+ "DIR file name not specified");
+ return EINVAL;
+ }
+
+ {
+ struct stat sb;
+ int ret;
+
+ ret = stat(residue, &sb);
+ if (ret == -1) {
+ hx509_set_error_string(context, 0, ENOENT,
+ "No such file %s", residue);
+ return ENOENT;
+ }
+
+ if (!S_ISDIR(sb.st_mode)) {
+ hx509_set_error_string(context, 0, ENOTDIR,
+ "%s is not a directory", residue);
+ return ENOTDIR;
+ }
+ }
+
+ *data = strdup(residue);
+ if (*data == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+
+ return 0;
+}
+
+static int
+dir_free(hx509_certs certs, void *data)
+{
+ free(data);
+ return 0;
+}
+
+static int
+dir_iter_start(hx509_context context,
+ hx509_certs certs, void *data, void **cursor)
+{
+ struct dircursor *d;
+
+ *cursor = NULL;
+
+ d = calloc(1, sizeof(*d));
+ if (d == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+
+ d->dir = opendir(data);
+ if (d->dir == NULL) {
+ hx509_clear_error_string(context);
+ free(d);
+ return errno;
+ }
+ rk_cloexec_dir(d->dir);
+ d->certs = NULL;
+ d->iter = NULL;
+
+ *cursor = d;
+ return 0;
+}
+
+static int
+dir_iter(hx509_context context,
+ hx509_certs certs, void *data, void *iter, hx509_cert *cert)
+{
+ struct dircursor *d = iter;
+ int ret = 0;
+
+ *cert = NULL;
+
+ do {
+ struct dirent *dir;
+ char *fn;
+
+ if (d->certs) {
+ ret = hx509_certs_next_cert(context, d->certs, d->iter, cert);
+ if (ret) {
+ hx509_certs_end_seq(context, d->certs, d->iter);
+ d->iter = NULL;
+ hx509_certs_free(&d->certs);
+ return ret;
+ }
+ if (*cert) {
+ ret = 0;
+ break;
+ }
+ hx509_certs_end_seq(context, d->certs, d->iter);
+ d->iter = NULL;
+ hx509_certs_free(&d->certs);
+ }
+
+ dir = readdir(d->dir);
+ if (dir == NULL) {
+ ret = 0;
+ break;
+ }
+ if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0)
+ continue;
+
+ if (asprintf(&fn, "FILE:%s/%s", (char *)data, dir->d_name) == -1)
+ return ENOMEM;
+
+ ret = hx509_certs_init(context, fn, 0, NULL, &d->certs);
+ if (ret == 0) {
+
+ ret = hx509_certs_start_seq(context, d->certs, &d->iter);
+ if (ret)
+ hx509_certs_free(&d->certs);
+ }
+ /* ignore errors */
+ if (ret) {
+ d->certs = NULL;
+ ret = 0;
+ }
+
+ free(fn);
+ } while(ret == 0);
+
+ return ret;
+}
+
+
+static int
+dir_iter_end(hx509_context context,
+ hx509_certs certs,
+ void *data,
+ void *cursor)
+{
+ struct dircursor *d = cursor;
+
+ if (d->certs) {
+ hx509_certs_end_seq(context, d->certs, d->iter);
+ d->iter = NULL;
+ hx509_certs_free(&d->certs);
+ }
+ closedir(d->dir);
+ free(d);
+ return 0;
+}
+
+
+static struct hx509_keyset_ops keyset_dir = {
+ "DIR",
+ 0,
+ dir_init,
+ NULL,
+ dir_free,
+ NULL,
+ NULL,
+ dir_iter_start,
+ dir_iter,
+ dir_iter_end,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_ks_dir_register(hx509_context context)
+{
+ _hx509_ks_register(context, &keyset_dir);
+}
diff --git a/third_party/heimdal/lib/hx509/ks_file.c b/third_party/heimdal/lib/hx509/ks_file.c
new file mode 100644
index 0000000..880668b
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/ks_file.c
@@ -0,0 +1,800 @@
+/*
+ * Copyright (c) 2005 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+#ifndef WIN32
+#include <libgen.h>
+#endif
+
+typedef enum { USE_PEM, USE_DER } outformat;
+
+struct ks_file {
+ hx509_certs certs;
+ char *fn;
+ outformat format;
+};
+
+/*
+ *
+ */
+
+static int
+parse_certificate(hx509_context context, const char *fn, int flags,
+ struct hx509_collector *c,
+ const hx509_pem_header *headers,
+ const void *data, size_t len,
+ const AlgorithmIdentifier *ai)
+{
+ heim_error_t error = NULL;
+ hx509_cert cert;
+ int ret;
+
+ cert = hx509_cert_init_data(context, data, len, &error);
+ if (cert == NULL) {
+ ret = heim_error_get_code(error);
+ heim_release(error);
+ return ret;
+ }
+
+ ret = _hx509_collector_certs_add(context, c, cert);
+ hx509_cert_free(cert);
+ return ret;
+}
+
+static int
+try_decrypt(hx509_context context,
+ struct hx509_collector *collector,
+ int flags,
+ const AlgorithmIdentifier *alg,
+ const EVP_CIPHER *c,
+ const void *ivdata,
+ const void *password,
+ size_t passwordlen,
+ const void *cipher,
+ size_t len)
+{
+ heim_octet_string clear;
+ size_t keylen;
+ void *key;
+ int ret;
+
+ keylen = EVP_CIPHER_key_length(c);
+
+ key = malloc(keylen);
+ if (key == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+
+ ret = EVP_BytesToKey(c, EVP_md5(), ivdata,
+ password, passwordlen,
+ 1, key, NULL);
+ if (ret <= 0) {
+ ret = HX509_CRYPTO_INTERNAL_ERROR;
+ hx509_set_error_string(context, 0, ret,
+ "Failed to do string2key for private key");
+ goto out;
+ }
+
+ clear.data = malloc(len);
+ if (clear.data == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM,
+ "Out of memory to decrypt for private key");
+ ret = ENOMEM;
+ goto out;
+ }
+ clear.length = len;
+
+ {
+ EVP_CIPHER_CTX ctx;
+ EVP_CIPHER_CTX_init(&ctx);
+ EVP_CipherInit_ex(&ctx, c, NULL, key, ivdata, 0);
+ EVP_Cipher(&ctx, clear.data, cipher, len);
+ EVP_CIPHER_CTX_cleanup(&ctx);
+ }
+
+ if (!(flags & HX509_CERTS_NO_PRIVATE_KEYS))
+ ret = _hx509_collector_private_key_add(context, collector, alg, NULL,
+ &clear, NULL);
+
+ memset_s(clear.data, clear.length, 0, clear.length);
+ free(clear.data);
+out:
+ memset_s(key, keylen, 0, keylen);
+ free(key);
+ return ret;
+}
+
+static int
+parse_pkcs8_private_key(hx509_context context, const char *fn, int flags,
+ struct hx509_collector *c,
+ const hx509_pem_header *headers,
+ const void *data, size_t length,
+ const AlgorithmIdentifier *ai)
+{
+ PKCS8PrivateKeyInfo ki;
+ heim_octet_string keydata;
+ int ret;
+
+ ret = decode_PKCS8PrivateKeyInfo(data, length, &ki, NULL);
+ if (ret)
+ return ret;
+
+ if (!(flags & HX509_CERTS_NO_PRIVATE_KEYS)) {
+ keydata.data = rk_UNCONST(data);
+ keydata.length = length;
+ ret = _hx509_collector_private_key_add(context,
+ c,
+ &ki.privateKeyAlgorithm,
+ NULL,
+ &ki.privateKey,
+ &keydata);
+ }
+ free_PKCS8PrivateKeyInfo(&ki);
+ return ret;
+}
+
+static int
+parse_pem_private_key(hx509_context context, const char *fn, int flags,
+ struct hx509_collector *c,
+ const hx509_pem_header *headers,
+ const void *data, size_t len,
+ const AlgorithmIdentifier *ai)
+{
+ int ret = 0;
+ const char *enc;
+
+ enc = hx509_pem_find_header(headers, "Proc-Type");
+ if (enc) {
+ const char *dek;
+ char *type, *iv;
+ ssize_t ssize, size;
+ void *ivdata;
+ const EVP_CIPHER *cipher;
+ const struct _hx509_password *pw;
+ hx509_lock lock;
+ int decrypted = 0;
+ size_t i;
+
+ lock = _hx509_collector_get_lock(c);
+ if (lock == NULL) {
+ hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
+ "Failed to get password for "
+ "password protected file %s", fn);
+ return HX509_ALG_NOT_SUPP;
+ }
+
+ if (strcmp(enc, "4,ENCRYPTED") != 0) {
+ hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
+ "Private key encrypted in unknown method %s "
+ "in file",
+ enc, fn);
+ hx509_clear_error_string(context);
+ return HX509_PARSING_KEY_FAILED;
+ }
+
+ dek = hx509_pem_find_header(headers, "DEK-Info");
+ if (dek == NULL) {
+ hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
+ "Encrypted private key missing DEK-Info");
+ return HX509_PARSING_KEY_FAILED;
+ }
+
+ type = strdup(dek);
+ if (type == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+
+ iv = strchr(type, ',');
+ if (iv == NULL) {
+ free(type);
+ hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
+ "IV missing");
+ return HX509_PARSING_KEY_FAILED;
+ }
+
+ *iv++ = '\0';
+
+ size = strlen(iv);
+ ivdata = malloc(size);
+ if (ivdata == NULL) {
+ hx509_clear_error_string(context);
+ free(type);
+ return ENOMEM;
+ }
+
+ cipher = EVP_get_cipherbyname(type);
+ if (cipher == NULL) {
+ free(ivdata);
+ hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
+ "Private key encrypted with "
+ "unsupported cipher: %s",
+ type);
+ free(type);
+ return HX509_ALG_NOT_SUPP;
+ }
+
+#define PKCS5_SALT_LEN 8
+
+ ssize = hex_decode(iv, ivdata, size);
+ free(type);
+ type = NULL;
+ iv = NULL;
+
+ if (ssize < 0 || ssize < PKCS5_SALT_LEN || ssize < EVP_CIPHER_iv_length(cipher)) {
+ free(ivdata);
+ hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
+ "Salt have wrong length in "
+ "private key file");
+ return HX509_PARSING_KEY_FAILED;
+ }
+
+ pw = _hx509_lock_get_passwords(lock);
+ if (pw != NULL) {
+ const void *password;
+ size_t passwordlen;
+
+ for (i = 0; i < pw->len; i++) {
+ password = pw->val[i];
+ passwordlen = strlen(password);
+
+ ret = try_decrypt(context, c, flags, ai, cipher, ivdata,
+ password, passwordlen, data, len);
+ if (ret == 0) {
+ decrypted = 1;
+ break;
+ }
+ }
+ }
+ if (!decrypted) {
+ hx509_prompt prompt;
+ char password[128];
+
+ memset(&prompt, 0, sizeof(prompt));
+
+ prompt.prompt = "Password for keyfile: ";
+ prompt.type = HX509_PROMPT_TYPE_PASSWORD;
+ prompt.reply.data = password;
+ prompt.reply.length = sizeof(password);
+
+ ret = hx509_lock_prompt(lock, &prompt);
+ if (ret == 0)
+ ret = try_decrypt(context, c, flags, ai, cipher, ivdata,
+ password, strlen(password), data, len);
+ /* XXX add password to lock password collection ? */
+ memset_s(password, sizeof(password), 0, sizeof(password));
+ }
+ free(ivdata);
+
+ } else if (!(flags & HX509_CERTS_NO_PRIVATE_KEYS)) {
+ heim_octet_string keydata;
+
+ keydata.data = rk_UNCONST(data);
+ keydata.length = len;
+
+ ret = _hx509_collector_private_key_add(context, c, ai, NULL,
+ &keydata, NULL);
+ }
+
+ return ret;
+}
+
+
+struct pem_formats {
+ const char *name;
+ int (*func)(hx509_context, const char *, int, struct hx509_collector *,
+ const hx509_pem_header *, const void *, size_t,
+ const AlgorithmIdentifier *);
+ const AlgorithmIdentifier *(*ai)(void);
+} formats[] = {
+ { "CERTIFICATE", parse_certificate, NULL },
+ { "PRIVATE KEY", parse_pkcs8_private_key, NULL },
+ { "RSA PRIVATE KEY", parse_pem_private_key, hx509_signature_rsa },
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+ { "EC PRIVATE KEY", parse_pem_private_key, hx509_signature_ecPublicKey }
+#endif
+};
+
+
+struct pem_ctx {
+ int flags;
+ struct hx509_collector *c;
+};
+
+static int
+pem_func(hx509_context context, const char *type,
+ const hx509_pem_header *header,
+ const void *data, size_t len, void *ctx)
+{
+ struct pem_ctx *pem_ctx = (struct pem_ctx*)ctx;
+ int ret = 0;
+ size_t j;
+
+ for (j = 0; j < sizeof(formats)/sizeof(formats[0]); j++) {
+ const char *q = formats[j].name;
+ if (strcasecmp(type, q) == 0) {
+ const AlgorithmIdentifier *ai = NULL;
+
+ if (formats[j].ai != NULL)
+ ai = (*formats[j].ai)();
+
+ ret = (*formats[j].func)(context, NULL, pem_ctx->flags, pem_ctx->c,
+ header, data, len, ai);
+ if (ret && (pem_ctx->flags & HX509_CERTS_UNPROTECT_ALL)) {
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "Failed parseing PEM format %s", type);
+ return ret;
+ }
+ break;
+ }
+ }
+ if (j == sizeof(formats)/sizeof(formats[0])) {
+ ret = HX509_UNSUPPORTED_OPERATION;
+ hx509_set_error_string(context, 0, ret,
+ "Found no matching PEM format for %s", type);
+ return ret;
+ }
+ return 0;
+}
+
+/*
+ *
+ */
+
+static int
+file_init_common(hx509_context context,
+ hx509_certs certs, void **data, int flags,
+ const char *residue, hx509_lock lock, outformat format)
+{
+ char *p, *pnext;
+ struct ks_file *ksf = NULL;
+ hx509_private_key *keys = NULL;
+ int ret;
+ struct pem_ctx pem_ctx;
+
+ pem_ctx.flags = flags;
+ pem_ctx.c = NULL;
+
+ if (residue == NULL || residue[0] == '\0') {
+ hx509_set_error_string(context, 0, EINVAL,
+ "PEM file name not specified");
+ return EINVAL;
+ }
+
+ *data = NULL;
+
+ if (lock == NULL)
+ lock = _hx509_empty_lock;
+
+ ksf = calloc(1, sizeof(*ksf));
+ if (ksf == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+ ksf->format = format;
+
+ ksf->fn = strdup(residue);
+ if (ksf->fn == NULL) {
+ hx509_clear_error_string(context);
+ ret = ENOMEM;
+ goto out;
+ }
+
+ /*
+ * XXX this is broken, the function should parse the file before
+ * overwriting it
+ */
+
+ if (flags & HX509_CERTS_CREATE) {
+ /*
+ * Note that the file creation is deferred until file_store() is
+ * called.
+ */
+ ret = hx509_certs_init(context, "MEMORY:ks-file-create",
+ 0, lock, &ksf->certs);
+ if (ret)
+ goto out;
+ *data = ksf;
+ return 0;
+ }
+
+ ret = _hx509_collector_alloc(context, lock, &pem_ctx.c);
+ if (ret)
+ goto out;
+
+ for (p = ksf->fn; p != NULL; p = pnext) {
+ FILE *f;
+
+ pnext = strchr(p, ',');
+ if (pnext)
+ *pnext++ = '\0';
+
+
+ if ((f = fopen(p, "r")) == NULL) {
+ ret = ENOENT;
+ hx509_set_error_string(context, 0, ret,
+ "Failed to open PEM file \"%s\": %s",
+ p, strerror(errno));
+ goto out;
+ }
+ rk_cloexec_file(f);
+
+ ret = hx509_pem_read(context, f, pem_func, &pem_ctx);
+ fclose(f);
+ if (ret != 0 && ret != HX509_PARSING_KEY_FAILED)
+ goto out;
+ else if (ret == HX509_PARSING_KEY_FAILED) {
+ size_t length;
+ void *ptr;
+ size_t i;
+
+ ret = rk_undumpdata(p, &ptr, &length);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+
+ for (i = 0; i < sizeof(formats)/sizeof(formats[0]); i++) {
+ const AlgorithmIdentifier *ai = NULL;
+
+ if (formats[i].ai != NULL)
+ ai = (*formats[i].ai)();
+
+ ret = (*formats[i].func)(context, p, pem_ctx.flags, pem_ctx.c,
+ NULL, ptr, length, ai);
+ if (ret == 0)
+ break;
+ }
+ rk_xfree(ptr);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ }
+ }
+
+ ret = _hx509_collector_collect_certs(context, pem_ctx.c, &ksf->certs);
+ if (ret)
+ goto out;
+
+ ret = _hx509_collector_collect_private_keys(context, pem_ctx.c, &keys);
+ if (ret == 0) {
+ int i;
+
+ for (i = 0; keys[i]; i++)
+ _hx509_certs_keys_add(context, ksf->certs, keys[i]);
+ _hx509_certs_keys_free(context, keys);
+ }
+
+out:
+ if (ret == 0)
+ *data = ksf;
+ else {
+ if (ksf->fn)
+ free(ksf->fn);
+ free(ksf);
+ }
+ if (pem_ctx.c)
+ _hx509_collector_free(pem_ctx.c);
+
+ return ret;
+}
+
+static int
+file_init_pem(hx509_context context,
+ hx509_certs certs, void **data, int flags,
+ const char *residue, hx509_lock lock)
+{
+ return file_init_common(context, certs, data, flags, residue, lock, USE_PEM);
+}
+
+static int
+file_init_der(hx509_context context,
+ hx509_certs certs, void **data, int flags,
+ const char *residue, hx509_lock lock)
+{
+ return file_init_common(context, certs, data, flags, residue, lock, USE_DER);
+}
+
+static int
+file_free(hx509_certs certs, void *data)
+{
+ struct ks_file *ksf = data;
+ hx509_certs_free(&ksf->certs);
+ free(ksf->fn);
+ free(ksf);
+ return 0;
+}
+
+struct store_ctx {
+ FILE *f;
+ outformat format;
+ int store_flags;
+};
+
+static int HX509_LIB_CALL
+store_func(hx509_context context, void *ctx, hx509_cert c)
+{
+ struct store_ctx *sc = ctx;
+ heim_octet_string data;
+ int ret = 0;
+
+ if (hx509_cert_have_private_key_only(c)) {
+ data.length = 0;
+ data.data = NULL;
+ } else {
+ ret = hx509_cert_binary(context, c, &data);
+ if (ret)
+ return ret;
+ }
+
+ switch (sc->format) {
+ case USE_DER:
+ /* Can't store both. Well, we could, but nothing will support it */
+ if (data.data) {
+ fwrite(data.data, data.length, 1, sc->f);
+ } else if (_hx509_cert_private_key_exportable(c) &&
+ !(sc->store_flags & HX509_CERTS_STORE_NO_PRIVATE_KEYS)) {
+ hx509_private_key key = _hx509_cert_private_key(c);
+
+ free(data.data);
+ data.length = 0;
+ data.data = NULL;
+ ret = _hx509_private_key_export(context, key,
+ HX509_KEY_FORMAT_DER, &data);
+ if (ret == 0 && data.length)
+ fwrite(data.data, data.length, 1, sc->f);
+ }
+ break;
+ case USE_PEM:
+ if (_hx509_cert_private_key_exportable(c) &&
+ !(sc->store_flags & HX509_CERTS_STORE_NO_PRIVATE_KEYS)) {
+ heim_octet_string priv_key;
+ hx509_private_key key = _hx509_cert_private_key(c);
+
+ ret = _hx509_private_key_export(context, key,
+ HX509_KEY_FORMAT_DER, &priv_key);
+ if (ret == 0)
+ ret = hx509_pem_write(context, _hx509_private_pem_name(key), NULL,
+ sc->f, priv_key.data, priv_key.length);
+ free(priv_key.data);
+ }
+ if (ret == 0 && data.data) {
+ ret = hx509_pem_write(context, "CERTIFICATE", NULL, sc->f,
+ data.data, data.length);
+ }
+ break;
+ }
+
+ free(data.data);
+ return ret;
+}
+
+static int
+mk_temp(const char *fn, char **tfn)
+{
+ char *ds;
+ int ret = -1;
+
+#ifdef WIN32
+ char buf[PATH_MAX];
+ char *p;
+
+ *tfn = NULL;
+
+ if ((ds = _fullpath(buf, fn, sizeof(buf))) == NULL) {
+ errno = errno ? errno : ENAMETOOLONG;
+ return -1;
+ }
+
+ if ((p = strrchr(ds, '\\')) == NULL) {
+ ret = asprintf(tfn, ".%s-XXXXXX", ds); /* XXX can't happen */
+ } else {
+ *(p++) = '\0';
+ ret = asprintf(tfn, "%s/.%s-XXXXXX", ds, p);
+ }
+#else
+ *tfn = NULL;
+ if ((ds = strdup(fn)))
+ ret = asprintf(tfn, "%s/.%s-XXXXXX", dirname(ds), basename(ds));
+ free(ds);
+#endif
+
+ /*
+ * Using mkostemp() risks leaving garbage files lying around. To do better
+ * without resorting to file locks (which have their own problems) we need
+ * O_TMPFILE and linkat(2), which only Linux has.
+ */
+ return (ret == -1 || *tfn == NULL) ? -1 : mkostemp(*tfn, O_CLOEXEC);
+}
+
+static int
+file_store(hx509_context context,
+ hx509_certs certs, void *data, int flags, hx509_lock lock)
+{
+ struct ks_file *ksf = data;
+ struct store_ctx sc;
+ char *tfn;
+ int ret;
+ int fd;
+
+ sc.f = NULL;
+ fd = mk_temp(ksf->fn, &tfn);
+ if (fd > -1)
+ sc.f = fdopen(fd, "w");
+ if (sc.f == NULL) {
+ hx509_set_error_string(context, 0, ret = errno,
+ "Failed to open file %s for writing", ksf->fn);
+ if (fd > -1)
+ (void) close(fd);
+ return ret;
+ }
+ rk_cloexec_file(sc.f);
+ sc.store_flags = flags;
+ sc.format = ksf->format;
+
+ ret = hx509_certs_iter_f(context, ksf->certs, store_func, &sc);
+ if (ret == 0)
+ ret = fclose(sc.f);
+ else
+ (void) fclose(sc.f);
+ if (ret)
+ (void) unlink(tfn);
+ else
+ (void) rename(tfn, ksf->fn);
+ free(tfn);
+ return ret;
+}
+
+static int
+file_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c)
+{
+ struct ks_file *ksf = data;
+ return hx509_certs_add(context, ksf->certs, c);
+}
+
+static int
+file_iter_start(hx509_context context,
+ hx509_certs certs, void *data, void **cursor)
+{
+ struct ks_file *ksf = data;
+ return hx509_certs_start_seq(context, ksf->certs, cursor);
+}
+
+static int
+file_iter(hx509_context context,
+ hx509_certs certs, void *data, void *iter, hx509_cert *cert)
+{
+ struct ks_file *ksf = data;
+ return hx509_certs_next_cert(context, ksf->certs, iter, cert);
+}
+
+static int
+file_iter_end(hx509_context context,
+ hx509_certs certs,
+ void *data,
+ void *cursor)
+{
+ struct ks_file *ksf = data;
+ return hx509_certs_end_seq(context, ksf->certs, cursor);
+}
+
+static int
+file_getkeys(hx509_context context,
+ hx509_certs certs,
+ void *data,
+ hx509_private_key **keys)
+{
+ struct ks_file *ksf = data;
+ return _hx509_certs_keys_get(context, ksf->certs, keys);
+}
+
+static int
+file_addkey(hx509_context context,
+ hx509_certs certs,
+ void *data,
+ hx509_private_key key)
+{
+ struct ks_file *ksf = data;
+ return _hx509_certs_keys_add(context, ksf->certs, key);
+}
+
+static int
+file_destroy(hx509_context context,
+ hx509_certs certs,
+ void *data)
+{
+ struct ks_file *ksf = data;
+ return _hx509_erase_file(context, ksf->fn);
+}
+
+static struct hx509_keyset_ops keyset_file = {
+ "FILE",
+ 0,
+ file_init_pem,
+ file_store,
+ file_free,
+ file_add,
+ NULL,
+ file_iter_start,
+ file_iter,
+ file_iter_end,
+ NULL,
+ file_getkeys,
+ file_addkey,
+ file_destroy
+};
+
+static struct hx509_keyset_ops keyset_pemfile = {
+ "PEM-FILE",
+ 0,
+ file_init_pem,
+ file_store,
+ file_free,
+ file_add,
+ NULL,
+ file_iter_start,
+ file_iter,
+ file_iter_end,
+ NULL,
+ file_getkeys,
+ file_addkey,
+ file_destroy
+};
+
+static struct hx509_keyset_ops keyset_derfile = {
+ "DER-FILE",
+ 0,
+ file_init_der,
+ file_store,
+ file_free,
+ file_add,
+ NULL,
+ file_iter_start,
+ file_iter,
+ file_iter_end,
+ NULL,
+ file_getkeys,
+ file_addkey,
+ file_destroy
+};
+
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_ks_file_register(hx509_context context)
+{
+ _hx509_ks_register(context, &keyset_file);
+ _hx509_ks_register(context, &keyset_pemfile);
+ _hx509_ks_register(context, &keyset_derfile);
+}
diff --git a/third_party/heimdal/lib/hx509/ks_keychain.c b/third_party/heimdal/lib/hx509/ks_keychain.c
new file mode 100644
index 0000000..3243ee8
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/ks_keychain.c
@@ -0,0 +1,627 @@
+/*
+ * Copyright (c) 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+#ifdef HAVE_FRAMEWORK_SECURITY
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+
+#include <Security/Security.h>
+
+/* Missing function decls in pre Leopard */
+#ifdef NEED_SECKEYGETCSPHANDLE_PROTO
+OSStatus SecKeyGetCSPHandle(SecKeyRef, CSSM_CSP_HANDLE *);
+OSStatus SecKeyGetCredentials(SecKeyRef, CSSM_ACL_AUTHORIZATION_TAG,
+ int, const CSSM_ACCESS_CREDENTIALS **);
+#define kSecCredentialTypeDefault 0
+#define CSSM_SIZE uint32_t
+#endif
+
+
+static int
+getAttribute(SecKeychainItemRef itemRef, SecItemAttr item,
+ SecKeychainAttributeList **attrs)
+{
+ SecKeychainAttributeInfo attrInfo;
+ UInt32 attrFormat = 0;
+ OSStatus ret;
+
+ *attrs = NULL;
+
+ attrInfo.count = 1;
+ attrInfo.tag = &item;
+ attrInfo.format = &attrFormat;
+
+ ret = SecKeychainItemCopyAttributesAndData(itemRef, &attrInfo, NULL,
+ attrs, NULL, NULL);
+ if (ret)
+ return EINVAL;
+ return 0;
+}
+
+
+/*
+ *
+ */
+
+struct kc_rsa {
+ SecKeychainItemRef item;
+ size_t keysize;
+};
+
+
+static int
+kc_rsa_public_encrypt(int flen,
+ const unsigned char *from,
+ unsigned char *to,
+ RSA *rsa,
+ int padding)
+{
+ return -1;
+}
+
+static int
+kc_rsa_public_decrypt(int flen,
+ const unsigned char *from,
+ unsigned char *to,
+ RSA *rsa,
+ int padding)
+{
+ return -1;
+}
+
+
+static int
+kc_rsa_private_encrypt(int flen,
+ const unsigned char *from,
+ unsigned char *to,
+ RSA *rsa,
+ int padding)
+{
+ struct kc_rsa *kc = RSA_get_app_data(rsa);
+
+ CSSM_RETURN cret;
+ OSStatus ret;
+ const CSSM_ACCESS_CREDENTIALS *creds;
+ SecKeyRef privKeyRef = (SecKeyRef)kc->item;
+ CSSM_CSP_HANDLE cspHandle;
+ const CSSM_KEY *cssmKey;
+ CSSM_CC_HANDLE sigHandle = 0;
+ CSSM_DATA sig, in;
+ int fret = 0;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ cret = SecKeyGetCSSMKey(privKeyRef, &cssmKey);
+ if(cret) abort();
+
+ cret = SecKeyGetCSPHandle(privKeyRef, &cspHandle);
+ if(cret) abort();
+
+ ret = SecKeyGetCredentials(privKeyRef, CSSM_ACL_AUTHORIZATION_SIGN,
+ kSecCredentialTypeDefault, &creds);
+ if(ret) abort();
+
+ ret = CSSM_CSP_CreateSignatureContext(cspHandle, CSSM_ALGID_RSA,
+ creds, cssmKey, &sigHandle);
+ if(ret) abort();
+
+ in.Data = (uint8 *)from;
+ in.Length = flen;
+
+ sig.Data = (uint8 *)to;
+ sig.Length = kc->keysize;
+
+ cret = CSSM_SignData(sigHandle, &in, 1, CSSM_ALGID_NONE, &sig);
+ if(cret) {
+ /* cssmErrorString(cret); */
+ fret = -1;
+ } else
+ fret = sig.Length;
+
+ if(sigHandle)
+ CSSM_DeleteContext(sigHandle);
+
+ return fret;
+}
+
+static int
+kc_rsa_private_decrypt(int flen, const unsigned char *from, unsigned char *to,
+ RSA * rsa, int padding)
+{
+ struct kc_rsa *kc = RSA_get_app_data(rsa);
+
+ CSSM_RETURN cret;
+ OSStatus ret;
+ const CSSM_ACCESS_CREDENTIALS *creds;
+ SecKeyRef privKeyRef = (SecKeyRef)kc->item;
+ CSSM_CSP_HANDLE cspHandle;
+ const CSSM_KEY *cssmKey;
+ CSSM_CC_HANDLE handle = 0;
+ CSSM_DATA out, in, rem;
+ int fret = 0;
+ CSSM_SIZE outlen = 0;
+ char remdata[1024];
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ cret = SecKeyGetCSSMKey(privKeyRef, &cssmKey);
+ if(cret) abort();
+
+ cret = SecKeyGetCSPHandle(privKeyRef, &cspHandle);
+ if(cret) abort();
+
+ ret = SecKeyGetCredentials(privKeyRef, CSSM_ACL_AUTHORIZATION_DECRYPT,
+ kSecCredentialTypeDefault, &creds);
+ if(ret) abort();
+
+
+ ret = CSSM_CSP_CreateAsymmetricContext (cspHandle,
+ CSSM_ALGID_RSA,
+ creds,
+ cssmKey,
+ CSSM_PADDING_PKCS1,
+ &handle);
+ if(ret) abort();
+
+ in.Data = (uint8 *)from;
+ in.Length = flen;
+
+ out.Data = (uint8 *)to;
+ out.Length = kc->keysize;
+
+ rem.Data = (uint8 *)remdata;
+ rem.Length = sizeof(remdata);
+
+ cret = CSSM_DecryptData(handle, &in, 1, &out, 1, &outlen, &rem);
+ if(cret) {
+ /* cssmErrorString(cret); */
+ fret = -1;
+ } else
+ fret = out.Length;
+
+ if(handle)
+ CSSM_DeleteContext(handle);
+
+ return fret;
+}
+
+static int
+kc_rsa_init(RSA *rsa)
+{
+ return 1;
+}
+
+static int
+kc_rsa_finish(RSA *rsa)
+{
+ struct kc_rsa *kc_rsa = RSA_get_app_data(rsa);
+ CFRelease(kc_rsa->item);
+ memset(kc_rsa, 0, sizeof(*kc_rsa));
+ free(kc_rsa);
+ return 1;
+}
+
+static const RSA_METHOD kc_rsa_pkcs1_method = {
+ "hx509 Keychain PKCS#1 RSA",
+ kc_rsa_public_encrypt,
+ kc_rsa_public_decrypt,
+ kc_rsa_private_encrypt,
+ kc_rsa_private_decrypt,
+ NULL,
+ NULL,
+ kc_rsa_init,
+ kc_rsa_finish,
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+static int
+set_private_key(hx509_context context,
+ SecKeychainItemRef itemRef,
+ hx509_cert cert)
+{
+ struct kc_rsa *kc;
+ hx509_private_key key;
+ RSA *rsa;
+ int ret;
+
+ ret = hx509_private_key_init(&key, NULL, NULL);
+ if (ret)
+ return ret;
+
+ kc = calloc(1, sizeof(*kc));
+ if (kc == NULL)
+ _hx509_abort("out of memory");
+
+ kc->item = itemRef;
+
+ rsa = RSA_new();
+ if (rsa == NULL)
+ _hx509_abort("out of memory");
+
+ /* Argh, fake modulus since OpenSSL API is on crack */
+ {
+ SecKeychainAttributeList *attrs = NULL;
+ uint32_t size;
+ void *data;
+
+ rsa->n = BN_new();
+ if (rsa->n == NULL) abort();
+
+ ret = getAttribute(itemRef, kSecKeyKeySizeInBits, &attrs);
+ if (ret) abort();
+
+ size = *(uint32_t *)attrs->attr[0].data;
+ SecKeychainItemFreeAttributesAndData(attrs, NULL);
+
+ kc->keysize = (size + 7) / 8;
+
+ data = malloc(kc->keysize);
+ memset(data, 0xe0, kc->keysize);
+ BN_bin2bn(data, kc->keysize, rsa->n);
+ free(data);
+ }
+ rsa->e = NULL;
+
+ RSA_set_method(rsa, &kc_rsa_pkcs1_method);
+ ret = RSA_set_app_data(rsa, kc);
+ if (ret != 1)
+ _hx509_abort("RSA_set_app_data");
+
+ hx509_private_key_assign_rsa(key, rsa);
+ _hx509_cert_assign_key(cert, key);
+
+ return 0;
+}
+
+/*
+ *
+ */
+
+struct ks_keychain {
+ int anchors;
+ SecKeychainRef keychain;
+};
+
+static int
+keychain_init(hx509_context context,
+ hx509_certs certs, void **data, int flags,
+ const char *residue, hx509_lock lock)
+{
+ struct ks_keychain *ctx;
+
+ if (flags & HX509_CERTS_NO_PRIVATE_KEYS) {
+ hx509_set_error_string(context, 0, ENOTSUP,
+ "KEYCHAIN store does not support not reading "
+ "private keys");
+ return ENOTSUP;
+ }
+
+ ctx = calloc(1, sizeof(*ctx));
+ if (ctx == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+
+ if (residue) {
+ if (strcasecmp(residue, "system-anchors") == 0) {
+ ctx->anchors = 1;
+ } else if (strncasecmp(residue, "FILE:", 5) == 0) {
+ OSStatus ret;
+
+ ret = SecKeychainOpen(residue + 5, &ctx->keychain);
+ if (ret != noErr) {
+ hx509_set_error_string(context, 0, ENOENT,
+ "Failed to open %s", residue);
+ free(ctx);
+ return ENOENT;
+ }
+ } else {
+ hx509_set_error_string(context, 0, ENOENT,
+ "Unknown subtype %s", residue);
+ free(ctx);
+ return ENOENT;
+ }
+ }
+
+ *data = ctx;
+ return 0;
+}
+
+/*
+ *
+ */
+
+static int
+keychain_free(hx509_certs certs, void *data)
+{
+ struct ks_keychain *ctx = data;
+ if (ctx->keychain)
+ CFRelease(ctx->keychain);
+ memset(ctx, 0, sizeof(*ctx));
+ free(ctx);
+ return 0;
+}
+
+/*
+ *
+ */
+
+struct iter {
+ hx509_certs certs;
+ void *cursor;
+ SecKeychainSearchRef searchRef;
+};
+
+static int
+keychain_iter_start(hx509_context context,
+ hx509_certs certs, void *data, void **cursor)
+{
+ struct ks_keychain *ctx = data;
+ struct iter *iter;
+
+ iter = calloc(1, sizeof(*iter));
+ if (iter == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ if (ctx->anchors) {
+ CFArrayRef anchors;
+ int ret;
+ int i;
+
+ ret = hx509_certs_init(context, "MEMORY:ks-file-create",
+ 0, NULL, &iter->certs);
+ if (ret) {
+ free(iter);
+ return ret;
+ }
+
+ ret = SecTrustCopyAnchorCertificates(&anchors);
+ if (ret != 0) {
+ hx509_certs_free(&iter->certs);
+ free(iter);
+ hx509_set_error_string(context, 0, ENOMEM,
+ "Can't get trust anchors from Keychain");
+ return ENOMEM;
+ }
+ for (i = 0; i < CFArrayGetCount(anchors); i++) {
+ SecCertificateRef cr;
+ hx509_cert cert;
+ CSSM_DATA cssm;
+
+ cr = (SecCertificateRef)CFArrayGetValueAtIndex(anchors, i);
+
+ SecCertificateGetData(cr, &cssm);
+
+ cert = hx509_cert_init_data(context, cssm.Data, cssm.Length, NULL);
+ if (cert == NULL)
+ continue;
+
+ ret = hx509_certs_add(context, iter->certs, cert);
+ hx509_cert_free(cert);
+ }
+ CFRelease(anchors);
+ }
+
+ if (iter->certs) {
+ int ret;
+ ret = hx509_certs_start_seq(context, iter->certs, &iter->cursor);
+ if (ret) {
+ hx509_certs_free(&iter->certs);
+ free(iter);
+ return ret;
+ }
+ } else {
+ OSStatus ret;
+
+ ret = SecKeychainSearchCreateFromAttributes(ctx->keychain,
+ kSecCertificateItemClass,
+ NULL,
+ &iter->searchRef);
+ if (ret) {
+ free(iter);
+ hx509_set_error_string(context, 0, ret,
+ "Failed to start search for attributes");
+ return ENOMEM;
+ }
+ }
+
+ *cursor = iter;
+ return 0;
+}
+
+/*
+ *
+ */
+
+static int
+keychain_iter(hx509_context context,
+ hx509_certs certs, void *data, void *cursor, hx509_cert *cert)
+{
+ SecKeychainAttributeList *attrs = NULL;
+ SecKeychainAttributeInfo attrInfo;
+ UInt32 attrFormat[1] = { 0 };
+ SecKeychainItemRef itemRef;
+ SecItemAttr item[1];
+ heim_error_t error = NULL;
+ struct iter *iter = cursor;
+ OSStatus ret;
+ UInt32 len;
+ void *ptr = NULL;
+
+ if (iter->certs)
+ return hx509_certs_next_cert(context, iter->certs, iter->cursor, cert);
+
+ *cert = NULL;
+
+ ret = SecKeychainSearchCopyNext(iter->searchRef, &itemRef);
+ if (ret == errSecItemNotFound)
+ return 0;
+ else if (ret != 0)
+ return EINVAL;
+
+ /*
+ * Pick out certificate and matching "keyid"
+ */
+
+ item[0] = kSecPublicKeyHashItemAttr;
+
+ attrInfo.count = 1;
+ attrInfo.tag = item;
+ attrInfo.format = attrFormat;
+
+ ret = SecKeychainItemCopyAttributesAndData(itemRef, &attrInfo, NULL,
+ &attrs, &len, &ptr);
+ if (ret)
+ return EINVAL;
+
+ *cert = hx509_cert_init_data(context, ptr, len, &error);
+ if (*cert == NULL) {
+ ret = heim_error_get_code(error);
+ heim_release(error);
+ goto out;
+ }
+
+ /*
+ * Find related private key if there is one by looking at
+ * kSecPublicKeyHashItemAttr == kSecKeyLabel
+ */
+ {
+ SecKeychainSearchRef search;
+ SecKeychainAttribute attrKeyid;
+ SecKeychainAttributeList attrList;
+
+ attrKeyid.tag = kSecKeyLabel;
+ attrKeyid.length = attrs->attr[0].length;
+ attrKeyid.data = attrs->attr[0].data;
+
+ attrList.count = 1;
+ attrList.attr = &attrKeyid;
+
+ ret = SecKeychainSearchCreateFromAttributes(NULL,
+ CSSM_DL_DB_RECORD_PRIVATE_KEY,
+ &attrList,
+ &search);
+ if (ret) {
+ ret = 0;
+ goto out;
+ }
+
+ ret = SecKeychainSearchCopyNext(search, &itemRef);
+ CFRelease(search);
+ if (ret == errSecItemNotFound) {
+ ret = 0;
+ goto out;
+ } else if (ret) {
+ ret = EINVAL;
+ goto out;
+ }
+ set_private_key(context, itemRef, *cert);
+ }
+
+out:
+ SecKeychainItemFreeAttributesAndData(attrs, ptr);
+
+ return ret;
+}
+
+/*
+ *
+ */
+
+static int
+keychain_iter_end(hx509_context context,
+ hx509_certs certs,
+ void *data,
+ void *cursor)
+{
+ struct iter *iter = cursor;
+
+ if (iter->certs) {
+ hx509_certs_end_seq(context, iter->certs, iter->cursor);
+ hx509_certs_free(&iter->certs);
+ } else {
+ CFRelease(iter->searchRef);
+ }
+
+ memset(iter, 0, sizeof(*iter));
+ free(iter);
+ return 0;
+}
+
+/*
+ *
+ */
+
+struct hx509_keyset_ops keyset_keychain = {
+ "KEYCHAIN",
+ 0,
+ keychain_init,
+ NULL,
+ keychain_free,
+ NULL,
+ NULL,
+ keychain_iter_start,
+ keychain_iter,
+ keychain_iter_end,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+#pragma clang diagnostic pop
+
+#endif /* HAVE_FRAMEWORK_SECURITY */
+
+/*
+ *
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_ks_keychain_register(hx509_context context)
+{
+#ifdef HAVE_FRAMEWORK_SECURITY
+ _hx509_ks_register(context, &keyset_keychain);
+#endif
+}
diff --git a/third_party/heimdal/lib/hx509/ks_mem.c b/third_party/heimdal/lib/hx509/ks_mem.c
new file mode 100644
index 0000000..f325d12
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/ks_mem.c
@@ -0,0 +1,224 @@
+/*
+ * Copyright (c) 2005 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+/*
+ * Should use two hash/tree certificates intead of a array. Criteria
+ * should be subject and subjectKeyIdentifier since those two are
+ * commonly seached on in CMS and path building.
+ */
+
+struct mem_data {
+ char *name;
+ struct {
+ unsigned long len;
+ hx509_cert *val;
+ } certs;
+ hx509_private_key *keys;
+};
+
+static int
+mem_init(hx509_context context,
+ hx509_certs certs, void **data, int flags,
+ const char *residue, hx509_lock lock)
+{
+ struct mem_data *mem;
+ mem = calloc(1, sizeof(*mem));
+ if (mem == NULL)
+ return ENOMEM;
+ if (residue == NULL || residue[0] == '\0')
+ residue = "anonymous";
+ mem->name = strdup(residue);
+ if (mem->name == NULL) {
+ free(mem);
+ return ENOMEM;
+ }
+ *data = mem;
+ return 0;
+}
+
+static int
+mem_free(hx509_certs certs, void *data)
+{
+ struct mem_data *mem = data;
+ unsigned long i;
+
+ for (i = 0; i < mem->certs.len; i++)
+ hx509_cert_free(mem->certs.val[i]);
+ free(mem->certs.val);
+ for (i = 0; mem->keys && mem->keys[i]; i++)
+ hx509_private_key_free(&mem->keys[i]);
+ free(mem->keys);
+ free(mem->name);
+ free(mem);
+
+ return 0;
+}
+
+static int
+mem_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c)
+{
+ struct mem_data *mem = data;
+ hx509_cert *val;
+
+ val = realloc(mem->certs.val,
+ (mem->certs.len + 1) * sizeof(mem->certs.val[0]));
+ if (val == NULL)
+ return ENOMEM;
+
+ mem->certs.val = val;
+ mem->certs.val[mem->certs.len] = hx509_cert_ref(c);
+ mem->certs.len++;
+
+ return 0;
+}
+
+static int
+mem_iter_start(hx509_context context,
+ hx509_certs certs,
+ void *data,
+ void **cursor)
+{
+ unsigned long *iter = malloc(sizeof(*iter));
+
+ if (iter == NULL)
+ return ENOMEM;
+
+ *iter = 0;
+ *cursor = iter;
+
+ return 0;
+}
+
+static int
+mem_iter(hx509_context contexst,
+ hx509_certs certs,
+ void *data,
+ void *cursor,
+ hx509_cert *cert)
+{
+ unsigned long *iter = cursor;
+ struct mem_data *mem = data;
+
+ if (*iter >= mem->certs.len) {
+ *cert = NULL;
+ return 0;
+ }
+
+ *cert = hx509_cert_ref(mem->certs.val[*iter]);
+ (*iter)++;
+ return 0;
+}
+
+static int
+mem_iter_end(hx509_context context,
+ hx509_certs certs,
+ void *data,
+ void *cursor)
+{
+ free(cursor);
+ return 0;
+}
+
+static int
+mem_getkeys(hx509_context context,
+ hx509_certs certs,
+ void *data,
+ hx509_private_key **keys)
+{
+ struct mem_data *mem = data;
+ int i;
+
+ for (i = 0; mem->keys && mem->keys[i]; i++)
+ ;
+ *keys = calloc(i + 1, sizeof(**keys));
+ for (i = 0; mem->keys && mem->keys[i]; i++) {
+ (*keys)[i] = _hx509_private_key_ref(mem->keys[i]);
+ if ((*keys)[i] == NULL) {
+ while (--i >= 0)
+ hx509_private_key_free(&(*keys)[i]);
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+ }
+ (*keys)[i] = NULL;
+ return 0;
+}
+
+static int
+mem_addkey(hx509_context context,
+ hx509_certs certs,
+ void *data,
+ hx509_private_key key)
+{
+ struct mem_data *mem = data;
+ void *ptr;
+ int i;
+
+ for (i = 0; mem->keys && mem->keys[i]; i++)
+ ;
+ ptr = realloc(mem->keys, (i + 2) * sizeof(*mem->keys));
+ if (ptr == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+ mem->keys = ptr;
+ mem->keys[i] = _hx509_private_key_ref(key);
+ mem->keys[i + 1] = NULL;
+ return 0;
+}
+
+
+static struct hx509_keyset_ops keyset_mem = {
+ "MEMORY",
+ 0,
+ mem_init,
+ NULL,
+ mem_free,
+ mem_add,
+ NULL,
+ mem_iter_start,
+ mem_iter,
+ mem_iter_end,
+ NULL,
+ mem_getkeys,
+ mem_addkey,
+ NULL
+};
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_ks_mem_register(hx509_context context)
+{
+ _hx509_ks_register(context, &keyset_mem);
+}
diff --git a/third_party/heimdal/lib/hx509/ks_null.c b/third_party/heimdal/lib/hx509/ks_null.c
new file mode 100644
index 0000000..c241d30
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/ks_null.c
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2005 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+
+static int
+null_init(hx509_context context,
+ hx509_certs certs, void **data, int flags,
+ const char *residue, hx509_lock lock)
+{
+ *data = NULL;
+ return 0;
+}
+
+static int
+null_free(hx509_certs certs, void *data)
+{
+ assert(data == NULL);
+ return 0;
+}
+
+static int
+null_iter_start(hx509_context context,
+ hx509_certs certs, void *data, void **cursor)
+{
+ *cursor = NULL;
+ return 0;
+}
+
+static int
+null_iter(hx509_context context,
+ hx509_certs certs, void *data, void *iter, hx509_cert *cert)
+{
+ *cert = NULL;
+ return ENOENT;
+}
+
+static int
+null_iter_end(hx509_context context,
+ hx509_certs certs,
+ void *data,
+ void *cursor)
+{
+ assert(cursor == NULL);
+ return 0;
+}
+
+
+struct hx509_keyset_ops keyset_null = {
+ "NULL",
+ 0,
+ null_init,
+ NULL,
+ null_free,
+ NULL,
+ NULL,
+ null_iter_start,
+ null_iter,
+ null_iter_end,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_ks_null_register(hx509_context context)
+{
+ _hx509_ks_register(context, &keyset_null);
+}
diff --git a/third_party/heimdal/lib/hx509/ks_p11.c b/third_party/heimdal/lib/hx509/ks_p11.c
new file mode 100644
index 0000000..265523b
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/ks_p11.c
@@ -0,0 +1,1230 @@
+/*
+ * Copyright (c) 2004 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+#ifdef HAVE_DLOPEN
+
+#include "ref/pkcs11.h"
+
+struct p11_slot {
+ uint64_t flags;
+#define P11_SESSION 1
+#define P11_SESSION_IN_USE 2
+#define P11_LOGIN_REQ 4
+#define P11_LOGIN_DONE 8
+#define P11_TOKEN_PRESENT 16
+ CK_SESSION_HANDLE session;
+ CK_SLOT_ID id;
+ CK_BBOOL token;
+ char *name;
+ hx509_certs certs;
+ char *pin;
+ struct {
+ CK_MECHANISM_TYPE_PTR list;
+ CK_ULONG num;
+ CK_MECHANISM_INFO_PTR *infos;
+ } mechs;
+};
+
+struct p11_module {
+ void *dl_handle;
+ CK_FUNCTION_LIST_PTR funcs;
+ CK_ULONG num_slots;
+ unsigned int ref;
+ unsigned int selected_slot;
+ struct p11_slot *slot;
+};
+
+#define P11FUNC(module,f,args) (*(module)->funcs->C_##f)args
+
+static int p11_get_session(hx509_context,
+ struct p11_module *,
+ struct p11_slot *,
+ hx509_lock,
+ CK_SESSION_HANDLE *);
+static int p11_put_session(struct p11_module *,
+ struct p11_slot *,
+ CK_SESSION_HANDLE);
+static void p11_release_module(struct p11_module *);
+
+static int p11_list_keys(hx509_context,
+ struct p11_module *,
+ struct p11_slot *,
+ CK_SESSION_HANDLE,
+ hx509_lock,
+ hx509_certs *);
+
+/*
+ *
+ */
+
+struct p11_rsa {
+ struct p11_module *p;
+ struct p11_slot *slot;
+ CK_OBJECT_HANDLE private_key;
+ CK_OBJECT_HANDLE public_key;
+};
+
+static int
+p11_rsa_public_encrypt(int flen,
+ const unsigned char *from,
+ unsigned char *to,
+ RSA *rsa,
+ int padding)
+{
+ return -1;
+}
+
+static int
+p11_rsa_public_decrypt(int flen,
+ const unsigned char *from,
+ unsigned char *to,
+ RSA *rsa,
+ int padding)
+{
+ return -1;
+}
+
+
+static int
+p11_rsa_private_encrypt(int flen,
+ const unsigned char *from,
+ unsigned char *to,
+ RSA *rsa,
+ int padding)
+{
+ struct p11_rsa *p11rsa = RSA_get_app_data(rsa);
+ CK_OBJECT_HANDLE key = p11rsa->private_key;
+ CK_SESSION_HANDLE session;
+ CK_MECHANISM mechanism;
+ CK_ULONG ck_sigsize;
+ int ret;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ memset(&mechanism, 0, sizeof(mechanism));
+ mechanism.mechanism = CKM_RSA_PKCS;
+
+ ck_sigsize = RSA_size(rsa);
+
+ ret = p11_get_session(NULL, p11rsa->p, p11rsa->slot, NULL, &session);
+ if (ret)
+ return -1;
+
+ ret = P11FUNC(p11rsa->p, SignInit, (session, &mechanism, key));
+ if (ret != CKR_OK) {
+ p11_put_session(p11rsa->p, p11rsa->slot, session);
+ return -1;
+ }
+
+ ret = P11FUNC(p11rsa->p, Sign,
+ (session, (CK_BYTE *)(intptr_t)from, flen, to, &ck_sigsize));
+ p11_put_session(p11rsa->p, p11rsa->slot, session);
+ if (ret != CKR_OK)
+ return -1;
+
+ return ck_sigsize;
+}
+
+static int
+p11_rsa_private_decrypt(int flen, const unsigned char *from, unsigned char *to,
+ RSA * rsa, int padding)
+{
+ struct p11_rsa *p11rsa = RSA_get_app_data(rsa);
+ CK_OBJECT_HANDLE key = p11rsa->private_key;
+ CK_SESSION_HANDLE session;
+ CK_MECHANISM mechanism;
+ CK_ULONG ck_sigsize;
+ int ret;
+
+ if (padding != RSA_PKCS1_PADDING)
+ return -1;
+
+ memset(&mechanism, 0, sizeof(mechanism));
+ mechanism.mechanism = CKM_RSA_PKCS;
+
+ ck_sigsize = RSA_size(rsa);
+
+ ret = p11_get_session(NULL, p11rsa->p, p11rsa->slot, NULL, &session);
+ if (ret)
+ return -1;
+
+ ret = P11FUNC(p11rsa->p, DecryptInit, (session, &mechanism, key));
+ if (ret != CKR_OK) {
+ p11_put_session(p11rsa->p, p11rsa->slot, session);
+ return -1;
+ }
+
+ ret = P11FUNC(p11rsa->p, Decrypt,
+ (session, (CK_BYTE *)(intptr_t)from, flen, to, &ck_sigsize));
+ p11_put_session(p11rsa->p, p11rsa->slot, session);
+ if (ret != CKR_OK)
+ return -1;
+
+ return ck_sigsize;
+}
+
+static int
+p11_rsa_init(RSA *rsa)
+{
+ return 1;
+}
+
+static int
+p11_rsa_finish(RSA *rsa)
+{
+ struct p11_rsa *p11rsa = RSA_get_app_data(rsa);
+ p11_release_module(p11rsa->p);
+ free(p11rsa);
+ return 1;
+}
+
+static const RSA_METHOD p11_rsa_pkcs1_method = {
+ "hx509 PKCS11 PKCS#1 RSA",
+ p11_rsa_public_encrypt,
+ p11_rsa_public_decrypt,
+ p11_rsa_private_encrypt,
+ p11_rsa_private_decrypt,
+ NULL,
+ NULL,
+ p11_rsa_init,
+ p11_rsa_finish,
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+/*
+ *
+ */
+
+static int
+p11_mech_info(hx509_context context,
+ struct p11_module *p,
+ struct p11_slot *slot,
+ int num)
+{
+ CK_ULONG i;
+ int ret;
+
+ ret = P11FUNC(p, GetMechanismList, (slot->id, NULL_PTR, &i));
+ if (ret) {
+ hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH,
+ "Failed to get mech list count for slot %d",
+ num);
+ return HX509_PKCS11_NO_MECH;
+ }
+ if (i == 0) {
+ hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH,
+ "no mech supported for slot %d", num);
+ return HX509_PKCS11_NO_MECH;
+ }
+ slot->mechs.list = calloc(i, sizeof(slot->mechs.list[0]));
+ if (slot->mechs.list == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM,
+ "out of memory");
+ return ENOMEM;
+ }
+ slot->mechs.num = i;
+ ret = P11FUNC(p, GetMechanismList, (slot->id, slot->mechs.list, &i));
+ if (ret) {
+ hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH,
+ "Failed to get mech list for slot %d",
+ num);
+ return HX509_PKCS11_NO_MECH;
+ }
+ assert(i == slot->mechs.num);
+
+ slot->mechs.infos = calloc(i, sizeof(*slot->mechs.infos));
+ if (slot->mechs.list == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM,
+ "out of memory");
+ return ENOMEM;
+ }
+
+ for (i = 0; i < slot->mechs.num; i++) {
+ slot->mechs.infos[i] = calloc(1, sizeof(*(slot->mechs.infos[0])));
+ if (slot->mechs.infos[i] == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM,
+ "out of memory");
+ return ENOMEM;
+ }
+ ret = P11FUNC(p, GetMechanismInfo, (slot->id, slot->mechs.list[i],
+ slot->mechs.infos[i]));
+ if (ret) {
+ hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH,
+ "Failed to get mech info for slot %d",
+ num);
+ return HX509_PKCS11_NO_MECH;
+ }
+ }
+
+ return 0;
+}
+
+static int
+p11_init_slot(hx509_context context,
+ struct p11_module *p,
+ hx509_lock lock,
+ CK_SLOT_ID id,
+ int num,
+ struct p11_slot *slot)
+{
+ CK_SESSION_HANDLE session;
+ CK_SLOT_INFO slot_info;
+ CK_TOKEN_INFO token_info;
+ size_t i;
+ int ret;
+
+ slot->certs = NULL;
+ slot->id = id;
+
+ ret = P11FUNC(p, GetSlotInfo, (slot->id, &slot_info));
+ if (ret) {
+ hx509_set_error_string(context, 0, HX509_PKCS11_TOKEN_CONFUSED,
+ "Failed to init PKCS11 slot %d",
+ num);
+ return HX509_PKCS11_TOKEN_CONFUSED;
+ }
+
+ for (i = sizeof(slot_info.slotDescription) - 1; i > 0; i--) {
+ char c = slot_info.slotDescription[i];
+ if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\0')
+ continue;
+ i++;
+ break;
+ }
+
+ ret = asprintf(&slot->name, "%.*s", (int)i,
+ slot_info.slotDescription);
+ if (ret == -1)
+ return ENOMEM;
+
+ if ((slot_info.flags & CKF_TOKEN_PRESENT) == 0)
+ return 0;
+
+ ret = P11FUNC(p, GetTokenInfo, (slot->id, &token_info));
+ if (ret) {
+ hx509_set_error_string(context, 0, HX509_PKCS11_NO_TOKEN,
+ "Failed to init PKCS11 slot %d "
+ "with error 0x%08x",
+ num, ret);
+ return HX509_PKCS11_NO_TOKEN;
+ }
+ slot->flags |= P11_TOKEN_PRESENT;
+
+ if (token_info.flags & CKF_LOGIN_REQUIRED)
+ slot->flags |= P11_LOGIN_REQ;
+
+ ret = p11_get_session(context, p, slot, lock, &session);
+ if (ret)
+ return ret;
+
+ ret = p11_mech_info(context, p, slot, num);
+ if (ret)
+ goto out;
+
+ ret = p11_list_keys(context, p, slot, session, lock, &slot->certs);
+ out:
+ p11_put_session(p, slot, session);
+
+ return ret;
+}
+
+static int
+p11_get_session(hx509_context context,
+ struct p11_module *p,
+ struct p11_slot *slot,
+ hx509_lock lock,
+ CK_SESSION_HANDLE *psession)
+{
+ CK_RV ret;
+
+ if (slot->flags & P11_SESSION_IN_USE)
+ _hx509_abort("slot already in session");
+
+ if (slot->flags & P11_SESSION) {
+ slot->flags |= P11_SESSION_IN_USE;
+ *psession = slot->session;
+ return 0;
+ }
+
+ ret = P11FUNC(p, OpenSession, (slot->id,
+ CKF_SERIAL_SESSION,
+ NULL,
+ NULL,
+ &slot->session));
+ if (ret != CKR_OK) {
+ if (context)
+ hx509_set_error_string(context, 0, HX509_PKCS11_OPEN_SESSION,
+ "Failed to OpenSession for slot id %d "
+ "with error: 0x%08x",
+ (int)slot->id, ret);
+ return HX509_PKCS11_OPEN_SESSION;
+ }
+
+ slot->flags |= P11_SESSION;
+
+ /*
+ * If we have have to login, and haven't tried before and have a
+ * prompter or known to work pin code.
+ *
+ * This code is very conversative and only uses the prompter in
+ * the hx509_lock, the reason is that it's bad to try many
+ * passwords on a pkcs11 token, it might lock up and have to be
+ * unlocked by a administrator.
+ *
+ * XXX try harder to not use pin several times on the same card.
+ */
+
+ if ( (slot->flags & P11_LOGIN_REQ)
+ && (slot->flags & P11_LOGIN_DONE) == 0
+ && (lock || slot->pin))
+ {
+ hx509_prompt prompt;
+ char pin[20];
+ char *str;
+
+ if (slot->pin == NULL) {
+
+ memset(&prompt, 0, sizeof(prompt));
+
+ ret = asprintf(&str, "PIN code for %s: ", slot->name);
+ if (ret == -1 || str == NULL) {
+ if (context)
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+ prompt.prompt = str;
+ prompt.type = HX509_PROMPT_TYPE_PASSWORD;
+ prompt.reply.data = pin;
+ prompt.reply.length = sizeof(pin);
+
+ ret = hx509_lock_prompt(lock, &prompt);
+ if (ret) {
+ free(str);
+ if (context)
+ hx509_set_error_string(context, 0, ret,
+ "Failed to get pin code for slot "
+ "id %d with error: %d",
+ (int)slot->id, ret);
+ return ret;
+ }
+ free(str);
+ } else {
+ strlcpy(pin, slot->pin, sizeof(pin));
+ }
+
+ ret = P11FUNC(p, Login, (slot->session, CKU_USER,
+ (unsigned char*)pin, strlen(pin)));
+ if (ret != CKR_OK) {
+ if (context)
+ hx509_set_error_string(context, 0, HX509_PKCS11_LOGIN,
+ "Failed to login on slot id %d "
+ "with error: 0x%08x",
+ (int)slot->id, ret);
+ switch(ret) {
+ case CKR_PIN_LOCKED:
+ return HX509_PKCS11_PIN_LOCKED;
+ case CKR_PIN_EXPIRED:
+ return HX509_PKCS11_PIN_EXPIRED;
+ case CKR_PIN_INCORRECT:
+ return HX509_PKCS11_PIN_INCORRECT;
+ case CKR_USER_PIN_NOT_INITIALIZED:
+ return HX509_PKCS11_PIN_NOT_INITIALIZED;
+ default:
+ return HX509_PKCS11_LOGIN;
+ }
+ } else
+ slot->flags |= P11_LOGIN_DONE;
+
+ if (slot->pin == NULL) {
+ slot->pin = strdup(pin);
+ if (slot->pin == NULL) {
+ if (context)
+ hx509_set_error_string(context, 0, ENOMEM,
+ "out of memory");
+ return ENOMEM;
+ }
+ }
+ } else
+ slot->flags |= P11_LOGIN_DONE;
+
+ slot->flags |= P11_SESSION_IN_USE;
+
+ *psession = slot->session;
+
+ return 0;
+}
+
+static int
+p11_put_session(struct p11_module *p,
+ struct p11_slot *slot,
+ CK_SESSION_HANDLE session)
+{
+ if ((slot->flags & P11_SESSION_IN_USE) == 0)
+ _hx509_abort("slot not in session");
+ slot->flags &= ~P11_SESSION_IN_USE;
+
+ return 0;
+}
+
+static int
+iterate_entries(hx509_context context,
+ struct p11_module *p, struct p11_slot *slot,
+ CK_SESSION_HANDLE session,
+ CK_ATTRIBUTE *search_data, int num_search_data,
+ CK_ATTRIBUTE *query, int num_query,
+ int (*func)(hx509_context,
+ struct p11_module *, struct p11_slot *,
+ CK_SESSION_HANDLE session,
+ CK_OBJECT_HANDLE object,
+ void *, CK_ATTRIBUTE *, int), void *ptr)
+{
+ CK_OBJECT_HANDLE object;
+ CK_ULONG object_count;
+ int ret, ret2, i;
+
+ ret = P11FUNC(p, FindObjectsInit, (session, search_data, num_search_data));
+ if (ret != CKR_OK) {
+ return -1;
+ }
+ while (1) {
+ ret = P11FUNC(p, FindObjects, (session, &object, 1, &object_count));
+ if (ret != CKR_OK) {
+ return -1;
+ }
+ if (object_count == 0)
+ break;
+
+ for (i = 0; i < num_query; i++)
+ query[i].pValue = NULL;
+
+ ret = P11FUNC(p, GetAttributeValue,
+ (session, object, query, num_query));
+ if (ret != CKR_OK) {
+ return -1;
+ }
+ for (i = 0; i < num_query; i++) {
+ query[i].pValue = malloc(query[i].ulValueLen);
+ if (query[i].pValue == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ }
+ ret = P11FUNC(p, GetAttributeValue,
+ (session, object, query, num_query));
+ if (ret != CKR_OK) {
+ ret = -1;
+ goto out;
+ }
+
+ ret = (*func)(context, p, slot, session, object, ptr, query, num_query);
+ if (ret)
+ goto out;
+
+ for (i = 0; i < num_query; i++) {
+ if (query[i].pValue)
+ free(query[i].pValue);
+ query[i].pValue = NULL;
+ }
+ }
+ out:
+
+ for (i = 0; i < num_query; i++) {
+ if (query[i].pValue)
+ free(query[i].pValue);
+ query[i].pValue = NULL;
+ }
+
+ ret2 = P11FUNC(p, FindObjectsFinal, (session));
+ if (ret2 != CKR_OK) {
+ return ret2;
+ }
+
+ return ret;
+}
+
+static BIGNUM *
+getattr_bn(struct p11_module *p,
+ struct p11_slot *slot,
+ CK_SESSION_HANDLE session,
+ CK_OBJECT_HANDLE object,
+ unsigned int type)
+{
+ CK_ATTRIBUTE query;
+ BIGNUM *bn;
+ int ret;
+
+ query.type = type;
+ query.pValue = NULL;
+ query.ulValueLen = 0;
+
+ ret = P11FUNC(p, GetAttributeValue,
+ (session, object, &query, 1));
+ if (ret != CKR_OK)
+ return NULL;
+
+ query.pValue = malloc(query.ulValueLen);
+
+ ret = P11FUNC(p, GetAttributeValue,
+ (session, object, &query, 1));
+ if (ret != CKR_OK) {
+ free(query.pValue);
+ return NULL;
+ }
+ bn = BN_bin2bn(query.pValue, query.ulValueLen, NULL);
+ free(query.pValue);
+
+ return bn;
+}
+
+static int
+collect_private_key(hx509_context context,
+ struct p11_module *p, struct p11_slot *slot,
+ CK_SESSION_HANDLE session,
+ CK_OBJECT_HANDLE object,
+ void *ptr, CK_ATTRIBUTE *query, int num_query)
+{
+ struct hx509_collector *collector = ptr;
+ hx509_private_key key;
+ heim_octet_string localKeyId;
+ int ret;
+ RSA *rsa;
+ struct p11_rsa *p11rsa;
+
+ localKeyId.data = query[0].pValue;
+ localKeyId.length = query[0].ulValueLen;
+
+ ret = hx509_private_key_init(&key, NULL, NULL);
+ if (ret)
+ return ret;
+
+ rsa = RSA_new();
+ if (rsa == NULL)
+ _hx509_abort("out of memory");
+
+ /*
+ * The exponent and modulus should always be present according to
+ * the pkcs11 specification, but some smartcards leaves it out,
+ * let ignore any failure to fetch it.
+ */
+ rsa->n = getattr_bn(p, slot, session, object, CKA_MODULUS);
+ rsa->e = getattr_bn(p, slot, session, object, CKA_PUBLIC_EXPONENT);
+
+ p11rsa = calloc(1, sizeof(*p11rsa));
+ if (p11rsa == NULL)
+ _hx509_abort("out of memory");
+
+ p11rsa->p = p;
+ p11rsa->slot = slot;
+ p11rsa->private_key = object;
+
+ if (p->ref == 0)
+ _hx509_abort("pkcs11 ref == 0 on alloc");
+ p->ref++;
+ if (p->ref == UINT_MAX)
+ _hx509_abort("pkcs11 ref == UINT_MAX on alloc");
+
+ RSA_set_method(rsa, &p11_rsa_pkcs1_method);
+ ret = RSA_set_app_data(rsa, p11rsa);
+ if (ret != 1)
+ _hx509_abort("RSA_set_app_data");
+
+ hx509_private_key_assign_rsa(key, rsa);
+
+ ret = _hx509_collector_private_key_add(context,
+ collector,
+ hx509_signature_rsa(),
+ key,
+ NULL,
+ &localKeyId);
+
+ if (ret) {
+ hx509_private_key_free(&key);
+ return ret;
+ }
+ return 0;
+}
+
+static void
+p11_cert_release(hx509_cert cert, void *ctx)
+{
+ struct p11_module *p = ctx;
+ p11_release_module(p);
+}
+
+
+static int
+collect_cert(hx509_context context,
+ struct p11_module *p, struct p11_slot *slot,
+ CK_SESSION_HANDLE session,
+ CK_OBJECT_HANDLE object,
+ void *ptr, CK_ATTRIBUTE *query, int num_query)
+{
+ struct hx509_collector *collector = ptr;
+ heim_error_t error = NULL;
+ hx509_cert cert;
+ int ret;
+
+ if ((CK_LONG)query[0].ulValueLen == -1 ||
+ (CK_LONG)query[1].ulValueLen == -1)
+ {
+ return 0;
+ }
+
+ cert = hx509_cert_init_data(context, query[1].pValue,
+ query[1].ulValueLen, &error);
+ if (cert == NULL) {
+ ret = heim_error_get_code(error);
+ heim_release(error);
+ return ret;
+ }
+
+ if (p->ref == 0)
+ _hx509_abort("pkcs11 ref == 0 on alloc");
+ p->ref++;
+ if (p->ref == UINT_MAX)
+ _hx509_abort("pkcs11 ref to high");
+
+ _hx509_cert_set_release(cert, p11_cert_release, p);
+
+ {
+ heim_octet_string data;
+
+ data.data = query[0].pValue;
+ data.length = query[0].ulValueLen;
+
+ _hx509_set_cert_attribute(context,
+ cert,
+ &asn1_oid_id_pkcs_9_at_localKeyId,
+ &data);
+ }
+
+ if ((CK_LONG)query[2].ulValueLen != -1) {
+ char *str;
+
+ ret = asprintf(&str, "%.*s",
+ (int)query[2].ulValueLen, (char *)query[2].pValue);
+ if (ret != -1 && str) {
+ hx509_cert_set_friendly_name(cert, str);
+ free(str);
+ }
+ }
+
+ ret = _hx509_collector_certs_add(context, collector, cert);
+ hx509_cert_free(cert);
+
+ return ret;
+}
+
+
+static int
+p11_list_keys(hx509_context context,
+ struct p11_module *p,
+ struct p11_slot *slot,
+ CK_SESSION_HANDLE session,
+ hx509_lock lock,
+ hx509_certs *certs)
+{
+ struct hx509_collector *collector;
+ CK_OBJECT_CLASS key_class;
+ CK_ATTRIBUTE search_data[] = {
+ {CKA_CLASS, NULL, 0},
+ };
+ CK_ATTRIBUTE query_data[3] = {
+ {CKA_ID, NULL, 0},
+ {CKA_VALUE, NULL, 0},
+ {CKA_LABEL, NULL, 0}
+ };
+ int ret;
+
+ search_data[0].pValue = &key_class;
+ search_data[0].ulValueLen = sizeof(key_class);
+
+ if (lock == NULL)
+ lock = _hx509_empty_lock;
+
+ ret = _hx509_collector_alloc(context, lock, &collector);
+ if (ret)
+ return ret;
+
+ key_class = CKO_PRIVATE_KEY;
+ ret = iterate_entries(context, p, slot, session,
+ search_data, 1,
+ query_data, 1,
+ collect_private_key, collector);
+ if (ret)
+ goto out;
+
+ key_class = CKO_CERTIFICATE;
+ ret = iterate_entries(context, p, slot, session,
+ search_data, 1,
+ query_data, 3,
+ collect_cert, collector);
+ if (ret)
+ goto out;
+
+ ret = _hx509_collector_collect_certs(context, collector, &slot->certs);
+
+out:
+ _hx509_collector_free(collector);
+
+ return ret;
+}
+
+
+static int
+p11_init(hx509_context context,
+ hx509_certs certs, void **data, int flags,
+ const char *residue, hx509_lock lock)
+{
+ CK_C_GetFunctionList getFuncs;
+ struct p11_module *p;
+ char *list, *str;
+ int ret;
+
+ *data = NULL;
+
+ if (flags & HX509_CERTS_NO_PRIVATE_KEYS) {
+ hx509_set_error_string(context, 0, ENOTSUP,
+ "PKCS#11 store does not support "
+ "HX509_CERTS_NO_PRIVATE_KEYS flag");
+ return ENOTSUP;
+ }
+
+ if (residue == NULL || residue[0] == '\0') {
+ hx509_set_error_string(context, 0, EINVAL,
+ "PKCS#11 store not specified");
+ return EINVAL;
+ }
+ list = strdup(residue);
+ if (list == NULL)
+ return ENOMEM;
+
+ p = calloc(1, sizeof(*p));
+ if (p == NULL) {
+ free(list);
+ return ENOMEM;
+ }
+
+ p->ref = 1;
+ p->selected_slot = 0;
+
+ str = strchr(list, ',');
+ if (str)
+ *str++ = '\0';
+ while (str) {
+ char *strnext;
+ strnext = strchr(str, ',');
+ if (strnext)
+ *strnext++ = '\0';
+ if (strncasecmp(str, "slot=", 5) == 0)
+ p->selected_slot = atoi(str + 5);
+ str = strnext;
+ }
+
+ p->dl_handle = dlopen(list, RTLD_NOW | RTLD_LOCAL | RTLD_GROUP);
+ if (p->dl_handle == NULL) {
+ ret = HX509_PKCS11_LOAD;
+ hx509_set_error_string(context, 0, ret,
+ "Failed to open %s: %s", list, dlerror());
+ goto out;
+ }
+
+ getFuncs = (CK_C_GetFunctionList) dlsym(p->dl_handle, "C_GetFunctionList");
+ if (getFuncs == NULL) {
+ ret = HX509_PKCS11_LOAD;
+ hx509_set_error_string(context, 0, ret,
+ "C_GetFunctionList missing in %s: %s",
+ list, dlerror());
+ goto out;
+ }
+
+ ret = (*getFuncs)(&p->funcs);
+ if (ret) {
+ ret = HX509_PKCS11_LOAD;
+ hx509_set_error_string(context, 0, ret,
+ "C_GetFunctionList failed in %s", list);
+ goto out;
+ }
+
+ ret = P11FUNC(p, Initialize, (NULL_PTR));
+ if (ret != CKR_OK) {
+ ret = HX509_PKCS11_TOKEN_CONFUSED;
+ hx509_set_error_string(context, 0, ret,
+ "Failed initialize the PKCS11 module");
+ goto out;
+ }
+
+ ret = P11FUNC(p, GetSlotList, (FALSE, NULL, &p->num_slots));
+ if (ret) {
+ ret = HX509_PKCS11_TOKEN_CONFUSED;
+ hx509_set_error_string(context, 0, ret,
+ "Failed to get number of PKCS11 slots");
+ goto out;
+ }
+
+ if (p->num_slots == 0) {
+ ret = HX509_PKCS11_NO_SLOT;
+ hx509_set_error_string(context, 0, ret,
+ "Selected PKCS11 module have no slots");
+ goto out;
+ }
+
+
+ {
+ CK_SLOT_ID_PTR slot_ids;
+ int num_tokens = 0;
+ size_t i;
+
+ slot_ids = malloc(p->num_slots * sizeof(*slot_ids));
+ if (slot_ids == NULL) {
+ hx509_clear_error_string(context);
+ ret = ENOMEM;
+ goto out;
+ }
+
+ ret = P11FUNC(p, GetSlotList, (FALSE, slot_ids, &p->num_slots));
+ if (ret) {
+ free(slot_ids);
+ hx509_set_error_string(context, 0, HX509_PKCS11_TOKEN_CONFUSED,
+ "Failed getting slot-list from "
+ "PKCS11 module");
+ ret = HX509_PKCS11_TOKEN_CONFUSED;
+ goto out;
+ }
+
+ p->slot = calloc(p->num_slots, sizeof(p->slot[0]));
+ if (p->slot == NULL) {
+ free(slot_ids);
+ hx509_set_error_string(context, 0, ENOMEM,
+ "Failed to get memory for slot-list");
+ ret = ENOMEM;
+ goto out;
+ }
+
+ for (i = 0; i < p->num_slots; i++) {
+ if ((p->selected_slot != 0) && (slot_ids[i] != (p->selected_slot - 1)))
+ continue;
+ ret = p11_init_slot(context, p, lock, slot_ids[i], i, &p->slot[i]);
+ if (!ret) {
+ if (p->slot[i].flags & P11_TOKEN_PRESENT)
+ num_tokens++;
+ }
+ }
+ free(slot_ids);
+ if (ret)
+ goto out;
+ if (num_tokens == 0) {
+ ret = HX509_PKCS11_NO_TOKEN;
+ goto out;
+ }
+ }
+
+ free(list);
+
+ *data = p;
+
+ return 0;
+ out:
+ if (list)
+ free(list);
+ p11_release_module(p);
+ return ret;
+}
+
+static void
+p11_release_module(struct p11_module *p)
+{
+ size_t i;
+
+ if (p->ref == 0)
+ _hx509_abort("pkcs11 ref to low");
+ if (--p->ref > 0)
+ return;
+
+ for (i = 0; i < p->num_slots; i++) {
+ if (p->slot[i].flags & P11_SESSION_IN_USE)
+ _hx509_abort("pkcs11 module release while session in use");
+ if (p->slot[i].flags & P11_SESSION) {
+ P11FUNC(p, CloseSession, (p->slot[i].session));
+ }
+
+ if (p->slot[i].name)
+ free(p->slot[i].name);
+ if (p->slot[i].pin) {
+ memset(p->slot[i].pin, 0, strlen(p->slot[i].pin));
+ free(p->slot[i].pin);
+ }
+ if (p->slot[i].mechs.num) {
+ free(p->slot[i].mechs.list);
+
+ if (p->slot[i].mechs.infos) {
+ size_t j;
+
+ for (j = 0 ; j < p->slot[i].mechs.num ; j++)
+ free(p->slot[i].mechs.infos[j]);
+ free(p->slot[i].mechs.infos);
+ }
+ }
+ }
+ free(p->slot);
+
+ if (p->funcs)
+ P11FUNC(p, Finalize, (NULL));
+
+ if (p->dl_handle)
+ dlclose(p->dl_handle);
+
+ memset(p, 0, sizeof(*p));
+ free(p);
+}
+
+static int
+p11_free(hx509_certs certs, void *data)
+{
+ struct p11_module *p = data;
+ size_t i;
+
+ for (i = 0; i < p->num_slots; i++) {
+ if (p->slot[i].certs)
+ hx509_certs_free(&p->slot[i].certs);
+ }
+ p11_release_module(p);
+ return 0;
+}
+
+struct p11_cursor {
+ hx509_certs certs;
+ void *cursor;
+};
+
+static int
+p11_iter_start(hx509_context context,
+ hx509_certs certs, void *data, void **cursor)
+{
+ struct p11_module *p = data;
+ struct p11_cursor *c;
+ int ret;
+ size_t i;
+
+ c = malloc(sizeof(*c));
+ if (c == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+ ret = hx509_certs_init(context, "MEMORY:pkcs11-iter", 0, NULL, &c->certs);
+ if (ret) {
+ free(c);
+ return ret;
+ }
+
+ for (i = 0 ; i < p->num_slots; i++) {
+ if (p->slot[i].certs == NULL)
+ continue;
+ ret = hx509_certs_merge(context, c->certs, p->slot[i].certs);
+ if (ret) {
+ hx509_certs_free(&c->certs);
+ free(c);
+ return ret;
+ }
+ }
+
+ ret = hx509_certs_start_seq(context, c->certs, &c->cursor);
+ if (ret) {
+ hx509_certs_free(&c->certs);
+ free(c);
+ return 0;
+ }
+ *cursor = c;
+
+ return 0;
+}
+
+static int
+p11_iter(hx509_context context,
+ hx509_certs certs, void *data, void *cursor, hx509_cert *cert)
+{
+ struct p11_cursor *c = cursor;
+ return hx509_certs_next_cert(context, c->certs, c->cursor, cert);
+}
+
+static int
+p11_iter_end(hx509_context context,
+ hx509_certs certs, void *data, void *cursor)
+{
+ struct p11_cursor *c = cursor;
+ int ret;
+ ret = hx509_certs_end_seq(context, c->certs, c->cursor);
+ hx509_certs_free(&c->certs);
+ free(c);
+ return ret;
+}
+
+#define MECHFLAG(x) { "unknown-flag-" #x, x }
+static struct units mechflags[] = {
+ MECHFLAG(0x80000000),
+ MECHFLAG(0x40000000),
+ MECHFLAG(0x20000000),
+ MECHFLAG(0x10000000),
+ MECHFLAG(0x08000000),
+ MECHFLAG(0x04000000),
+ {"ec-compress", 0x2000000 },
+ {"ec-uncompress", 0x1000000 },
+ {"ec-namedcurve", 0x0800000 },
+ {"ec-ecparameters", 0x0400000 },
+ {"ec-f-2m", 0x0200000 },
+ {"ec-f-p", 0x0100000 },
+ {"derive", 0x0080000 },
+ {"unwrap", 0x0040000 },
+ {"wrap", 0x0020000 },
+ {"genereate-key-pair", 0x0010000 },
+ {"generate", 0x0008000 },
+ {"verify-recover", 0x0004000 },
+ {"verify", 0x0002000 },
+ {"sign-recover", 0x0001000 },
+ {"sign", 0x0000800 },
+ {"digest", 0x0000400 },
+ {"decrypt", 0x0000200 },
+ {"encrypt", 0x0000100 },
+ MECHFLAG(0x00080),
+ MECHFLAG(0x00040),
+ MECHFLAG(0x00020),
+ MECHFLAG(0x00010),
+ MECHFLAG(0x00008),
+ MECHFLAG(0x00004),
+ MECHFLAG(0x00002),
+ {"hw", 0x0000001 },
+ { NULL, 0x0000000 }
+};
+#undef MECHFLAG
+
+static int
+p11_printinfo(hx509_context context,
+ hx509_certs certs,
+ void *data,
+ int (*func)(void *, const char *),
+ void *ctx)
+{
+ struct p11_module *p = data;
+ size_t i, j;
+
+ _hx509_pi_printf(func, ctx, "pkcs11 driver with %d slot%s",
+ p->num_slots, p->num_slots > 1 ? "s" : "");
+
+ for (i = 0; i < p->num_slots; i++) {
+ struct p11_slot *s = &p->slot[i];
+
+ _hx509_pi_printf(func, ctx, "slot %d: id: %d name: %s flags: %08x",
+ i, (int)s->id, s->name, s->flags);
+
+ _hx509_pi_printf(func, ctx, "number of supported mechanisms: %lu",
+ (unsigned long)s->mechs.num);
+ for (j = 0; j < s->mechs.num; j++) {
+ const char *mechname = "unknown";
+ char flags[256], unknownname[40];
+#define MECHNAME(s,n) case s: mechname = n; break
+ switch(s->mechs.list[j]) {
+ MECHNAME(CKM_RSA_PKCS_KEY_PAIR_GEN, "rsa-pkcs-key-pair-gen");
+ MECHNAME(CKM_RSA_PKCS, "rsa-pkcs");
+ MECHNAME(CKM_RSA_X_509, "rsa-x-509");
+ MECHNAME(CKM_MD5_RSA_PKCS, "md5-rsa-pkcs");
+ MECHNAME(CKM_SHA1_RSA_PKCS, "sha1-rsa-pkcs");
+ MECHNAME(CKM_SHA256_RSA_PKCS, "sha256-rsa-pkcs");
+ MECHNAME(CKM_SHA384_RSA_PKCS, "sha384-rsa-pkcs");
+ MECHNAME(CKM_SHA512_RSA_PKCS, "sha512-rsa-pkcs");
+ MECHNAME(CKM_RIPEMD160_RSA_PKCS, "ripemd160-rsa-pkcs");
+ MECHNAME(CKM_RSA_PKCS_OAEP, "rsa-pkcs-oaep");
+ MECHNAME(CKM_SHA512_HMAC, "sha512-hmac");
+ MECHNAME(CKM_SHA512, "sha512");
+ MECHNAME(CKM_SHA384_HMAC, "sha384-hmac");
+ MECHNAME(CKM_SHA384, "sha384");
+ MECHNAME(CKM_SHA256_HMAC, "sha256-hmac");
+ MECHNAME(CKM_SHA256, "sha256");
+ MECHNAME(CKM_SHA_1, "sha1");
+ MECHNAME(CKM_MD5, "md5");
+ MECHNAME(CKM_RIPEMD160, "ripemd-160");
+ MECHNAME(CKM_DES_ECB, "des-ecb");
+ MECHNAME(CKM_DES_CBC, "des-cbc");
+ MECHNAME(CKM_AES_ECB, "aes-ecb");
+ MECHNAME(CKM_AES_CBC, "aes-cbc");
+ MECHNAME(CKM_DH_PKCS_PARAMETER_GEN, "dh-pkcs-parameter-gen");
+ default:
+ snprintf(unknownname, sizeof(unknownname),
+ "unknown-mech-%lu",
+ (unsigned long)s->mechs.list[j]);
+ mechname = unknownname;
+ break;
+ }
+#undef MECHNAME
+ unparse_flags(s->mechs.infos[j]->flags, mechflags,
+ flags, sizeof(flags));
+
+ _hx509_pi_printf(func, ctx, " %s: %s", mechname, flags);
+ }
+ }
+
+ return 0;
+}
+
+static struct hx509_keyset_ops keyset_pkcs11 = {
+ "PKCS11",
+ 0,
+ p11_init,
+ NULL,
+ p11_free,
+ NULL,
+ NULL,
+ p11_iter_start,
+ p11_iter,
+ p11_iter_end,
+ p11_printinfo,
+ NULL,
+ NULL,
+ NULL
+};
+
+#endif /* HAVE_DLOPEN */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_ks_pkcs11_register(hx509_context context)
+{
+#ifdef HAVE_DLOPEN
+ _hx509_ks_register(context, &keyset_pkcs11);
+#endif
+}
diff --git a/third_party/heimdal/lib/hx509/ks_p12.c b/third_party/heimdal/lib/hx509/ks_p12.c
new file mode 100644
index 0000000..6fd7cd1
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/ks_p12.c
@@ -0,0 +1,756 @@
+/*
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+struct ks_pkcs12 {
+ hx509_certs certs;
+ char *fn;
+ unsigned int store_no_priv_keys;
+};
+
+typedef int (*collector_func)(hx509_context,
+ struct hx509_collector *,
+ int,
+ const void *, size_t,
+ const PKCS12_Attributes *);
+
+struct type {
+ const heim_oid *oid;
+ collector_func func;
+};
+
+static void
+parse_pkcs12_type(hx509_context, struct hx509_collector *, int,
+ const heim_oid *, const void *, size_t,
+ const PKCS12_Attributes *);
+
+
+static const PKCS12_Attribute *
+find_attribute(const PKCS12_Attributes *attrs, const heim_oid *oid)
+{
+ size_t i;
+ if (attrs == NULL)
+ return NULL;
+ for (i = 0; i < attrs->len; i++)
+ if (der_heim_oid_cmp(oid, &attrs->val[i].attrId) == 0)
+ return &attrs->val[i];
+ return NULL;
+}
+
+static int
+keyBag_parser(hx509_context context,
+ struct hx509_collector *c,
+ int flags,
+ const void *data, size_t length,
+ const PKCS12_Attributes *attrs)
+{
+ const PKCS12_Attribute *attr;
+ PKCS8PrivateKeyInfo ki;
+ const heim_octet_string *os = NULL;
+ int ret;
+
+ if (flags & HX509_CERTS_NO_PRIVATE_KEYS)
+ return 0;
+
+ attr = find_attribute(attrs, &asn1_oid_id_pkcs_9_at_localKeyId);
+ if (attr)
+ os = &attr->attrValues;
+
+ ret = decode_PKCS8PrivateKeyInfo(data, length, &ki, NULL);
+ if (ret)
+ return ret;
+
+ _hx509_collector_private_key_add(context,
+ c,
+ &ki.privateKeyAlgorithm,
+ NULL,
+ &ki.privateKey,
+ os);
+ free_PKCS8PrivateKeyInfo(&ki);
+ return 0;
+}
+
+static int
+ShroudedKeyBag_parser(hx509_context context,
+ struct hx509_collector *c,
+ int flags,
+ const void *data, size_t length,
+ const PKCS12_Attributes *attrs)
+{
+ PKCS8EncryptedPrivateKeyInfo pk;
+ heim_octet_string content;
+ int ret;
+
+ memset(&pk, 0, sizeof(pk));
+
+ ret = decode_PKCS8EncryptedPrivateKeyInfo(data, length, &pk, NULL);
+ if (ret)
+ return ret;
+
+ ret = _hx509_pbe_decrypt(context,
+ _hx509_collector_get_lock(c),
+ &pk.encryptionAlgorithm,
+ &pk.encryptedData,
+ &content);
+ free_PKCS8EncryptedPrivateKeyInfo(&pk);
+ if (ret)
+ return ret;
+
+ ret = keyBag_parser(context, c, flags, content.data, content.length,
+ attrs);
+ der_free_octet_string(&content);
+ return ret;
+}
+
+static int
+certBag_parser(hx509_context context,
+ struct hx509_collector *c,
+ int flags,
+ const void *data, size_t length,
+ const PKCS12_Attributes *attrs)
+{
+ heim_error_t error = NULL;
+ heim_octet_string os;
+ hx509_cert cert;
+ PKCS12_CertBag cb;
+ int ret;
+
+ ret = decode_PKCS12_CertBag(data, length, &cb, NULL);
+ if (ret)
+ return ret;
+
+ if (der_heim_oid_cmp(&asn1_oid_id_pkcs_9_at_certTypes_x509, &cb.certType)) {
+ free_PKCS12_CertBag(&cb);
+ return 0;
+ }
+
+ ret = decode_PKCS12_OctetString(cb.certValue.data,
+ cb.certValue.length,
+ &os,
+ NULL);
+ free_PKCS12_CertBag(&cb);
+ if (ret)
+ return ret;
+
+ cert = hx509_cert_init_data(context, os.data, os.length, &error);
+ der_free_octet_string(&os);
+ if (cert == NULL) {
+ ret = heim_error_get_code(error);
+ heim_release(error);
+ return ret;
+ }
+
+ ret = _hx509_collector_certs_add(context, c, cert);
+ if (ret) {
+ hx509_cert_free(cert);
+ return ret;
+ }
+
+ {
+ const PKCS12_Attribute *attr;
+ const heim_oid *oids[] = {
+ &asn1_oid_id_pkcs_9_at_localKeyId, &asn1_oid_id_pkcs_9_at_friendlyName
+ };
+ size_t i;
+
+ for (i = 0; i < sizeof(oids)/sizeof(oids[0]); i++) {
+ const heim_oid *oid = oids[i];
+ attr = find_attribute(attrs, oid);
+ if (attr)
+ _hx509_set_cert_attribute(context, cert, oid,
+ &attr->attrValues);
+ }
+ }
+
+ hx509_cert_free(cert);
+
+ return 0;
+}
+
+static int
+parse_safe_content(hx509_context context,
+ struct hx509_collector *c,
+ int flags,
+ const unsigned char *p, size_t len)
+{
+ PKCS12_SafeContents sc;
+ int ret;
+ size_t i;
+
+ memset(&sc, 0, sizeof(sc));
+
+ ret = decode_PKCS12_SafeContents(p, len, &sc, NULL);
+ if (ret)
+ return ret;
+
+ for (i = 0; i < sc.len ; i++)
+ parse_pkcs12_type(context,
+ c,
+ flags,
+ &sc.val[i].bagId,
+ sc.val[i].bagValue.data,
+ sc.val[i].bagValue.length,
+ sc.val[i].bagAttributes);
+
+ free_PKCS12_SafeContents(&sc);
+ return 0;
+}
+
+static int
+safeContent_parser(hx509_context context,
+ struct hx509_collector *c,
+ int flags,
+ const void *data, size_t length,
+ const PKCS12_Attributes *attrs)
+{
+ heim_octet_string os;
+ int ret;
+
+ ret = decode_PKCS12_OctetString(data, length, &os, NULL);
+ if (ret)
+ return ret;
+ ret = parse_safe_content(context, c, flags, os.data, os.length);
+ der_free_octet_string(&os);
+ return ret;
+}
+
+static int
+encryptedData_parser(hx509_context context,
+ struct hx509_collector *c,
+ int flags,
+ const void *data, size_t length,
+ const PKCS12_Attributes *attrs)
+{
+ heim_octet_string content;
+ heim_oid contentType;
+ int ret;
+
+ memset(&contentType, 0, sizeof(contentType));
+
+ ret = hx509_cms_decrypt_encrypted(context,
+ _hx509_collector_get_lock(c),
+ data, length,
+ &contentType,
+ &content);
+ if (ret)
+ return ret;
+
+ if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkcs7_data) == 0)
+ ret = parse_safe_content(context, c, flags,
+ content.data, content.length);
+
+ der_free_octet_string(&content);
+ der_free_oid(&contentType);
+ return ret;
+}
+
+static int
+envelopedData_parser(hx509_context context,
+ struct hx509_collector *c,
+ int flags,
+ const void *data, size_t length,
+ const PKCS12_Attributes *attrs)
+{
+ heim_octet_string content;
+ heim_oid contentType;
+ hx509_lock lock;
+ int ret;
+
+ memset(&contentType, 0, sizeof(contentType));
+
+ lock = _hx509_collector_get_lock(c);
+
+ ret = hx509_cms_unenvelope(context,
+ _hx509_lock_unlock_certs(lock),
+ 0,
+ data, length,
+ NULL,
+ 0,
+ &contentType,
+ &content);
+ if (ret) {
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "PKCS12 failed to unenvelope");
+ return ret;
+ }
+
+ if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkcs7_data) == 0)
+ ret = parse_safe_content(context, c, flags,
+ content.data, content.length);
+
+ der_free_octet_string(&content);
+ der_free_oid(&contentType);
+
+ return ret;
+}
+
+
+struct type bagtypes[] = {
+ { &asn1_oid_id_pkcs12_keyBag, keyBag_parser },
+ { &asn1_oid_id_pkcs12_pkcs8ShroudedKeyBag, ShroudedKeyBag_parser },
+ { &asn1_oid_id_pkcs12_certBag, certBag_parser },
+ { &asn1_oid_id_pkcs7_data, safeContent_parser },
+ { &asn1_oid_id_pkcs7_encryptedData, encryptedData_parser },
+ { &asn1_oid_id_pkcs7_envelopedData, envelopedData_parser }
+};
+
+static void
+parse_pkcs12_type(hx509_context context,
+ struct hx509_collector *c,
+ int flags,
+ const heim_oid *oid,
+ const void *data, size_t length,
+ const PKCS12_Attributes *attrs)
+{
+ size_t i;
+
+ for (i = 0; i < sizeof(bagtypes)/sizeof(bagtypes[0]); i++)
+ if (der_heim_oid_cmp(bagtypes[i].oid, oid) == 0)
+ (*bagtypes[i].func)(context, c, flags, data, length, attrs);
+}
+
+static int
+p12_init(hx509_context context,
+ hx509_certs certs, void **data, int flags,
+ const char *residue, hx509_lock lock)
+{
+ struct ks_pkcs12 *p12;
+ size_t len;
+ void *buf;
+ PKCS12_PFX pfx;
+ PKCS12_AuthenticatedSafe as;
+ int ret;
+ size_t i;
+ struct hx509_collector *c;
+
+ *data = NULL;
+
+ if (residue == NULL || residue[0] == '\0') {
+ hx509_set_error_string(context, 0, EINVAL,
+ "PKCS#12 file not specified");
+ return EINVAL;
+ }
+
+ if (lock == NULL)
+ lock = _hx509_empty_lock;
+
+ ret = _hx509_collector_alloc(context, lock, &c);
+ if (ret)
+ return ret;
+
+ p12 = calloc(1, sizeof(*p12));
+ if (p12 == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ goto out;
+ }
+
+ p12->fn = strdup(residue);
+ if (p12->fn == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ goto out;
+ }
+
+ if (flags & HX509_CERTS_CREATE) {
+ ret = hx509_certs_init(context, "MEMORY:ks-file-create",
+ 0, lock, &p12->certs);
+ if (ret == 0)
+ *data = p12;
+ goto out;
+ }
+
+ ret = rk_undumpdata(residue, &buf, &len);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+
+ ret = decode_PKCS12_PFX(buf, len, &pfx, NULL);
+ rk_xfree(buf);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to decode the PFX in %s", residue);
+ goto out;
+ }
+
+ if (der_heim_oid_cmp(&pfx.authSafe.contentType, &asn1_oid_id_pkcs7_data) != 0) {
+ free_PKCS12_PFX(&pfx);
+ ret = EINVAL;
+ hx509_set_error_string(context, 0, ret,
+ "PKCS PFX isn't a pkcs7-data container");
+ goto out;
+ }
+
+ if (pfx.authSafe.content == NULL) {
+ free_PKCS12_PFX(&pfx);
+ ret = EINVAL;
+ hx509_set_error_string(context, 0, ret,
+ "PKCS PFX missing data");
+ goto out;
+ }
+
+ {
+ heim_octet_string asdata;
+
+ ret = decode_PKCS12_OctetString(pfx.authSafe.content->data,
+ pfx.authSafe.content->length,
+ &asdata,
+ NULL);
+ free_PKCS12_PFX(&pfx);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ ret = decode_PKCS12_AuthenticatedSafe(asdata.data,
+ asdata.length,
+ &as,
+ NULL);
+ der_free_octet_string(&asdata);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ }
+
+ for (i = 0; i < as.len; i++)
+ parse_pkcs12_type(context,
+ c,
+ flags,
+ &as.val[i].contentType,
+ as.val[i].content->data,
+ as.val[i].content->length,
+ NULL);
+
+ free_PKCS12_AuthenticatedSafe(&as);
+
+ ret = _hx509_collector_collect_certs(context, c, &p12->certs);
+ if (ret == 0)
+ *data = p12;
+
+out:
+ _hx509_collector_free(c);
+
+ if (ret && p12) {
+ if (p12->fn)
+ free(p12->fn);
+ if (p12->certs)
+ hx509_certs_free(&p12->certs);
+ free(p12);
+ }
+
+ return ret;
+}
+
+static int
+addBag(hx509_context context,
+ PKCS12_AuthenticatedSafe *as,
+ const heim_oid *oid,
+ void *data,
+ size_t length)
+{
+ void *ptr;
+ int ret;
+
+ ptr = realloc(as->val, sizeof(as->val[0]) * (as->len + 1));
+ if (ptr == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+ as->val = ptr;
+
+ ret = der_copy_oid(oid, &as->val[as->len].contentType);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ return ret;
+ }
+
+ as->val[as->len].content = calloc(1, sizeof(*as->val[0].content));
+ if (as->val[as->len].content == NULL) {
+ der_free_oid(&as->val[as->len].contentType);
+ hx509_set_error_string(context, 0, ENOMEM, "malloc out of memory");
+ return ENOMEM;
+ }
+
+ as->val[as->len].content->data = data;
+ as->val[as->len].content->length = length;
+
+ as->len++;
+
+ return 0;
+}
+
+struct store_func_ctx {
+ PKCS12_AuthenticatedSafe as;
+ int store_flags;
+};
+
+static int HX509_LIB_CALL
+store_func(hx509_context context, void *d, hx509_cert c)
+{
+ struct store_func_ctx *ctx = d;
+ PKCS12_OctetString os;
+ PKCS12_CertBag cb;
+ size_t size;
+ int ret;
+
+ memset(&os, 0, sizeof(os));
+ memset(&cb, 0, sizeof(cb));
+
+ os.data = NULL;
+ os.length = 0;
+
+ ret = hx509_cert_binary(context, c, &os);
+ if (ret)
+ return ret;
+
+ ASN1_MALLOC_ENCODE(PKCS12_OctetString,
+ cb.certValue.data,cb.certValue.length,
+ &os, &size, ret);
+ free(os.data);
+ if (ret)
+ goto out;
+ ret = der_copy_oid(&asn1_oid_id_pkcs_9_at_certTypes_x509, &cb.certType);
+ if (ret) {
+ free_PKCS12_CertBag(&cb);
+ goto out;
+ }
+ ASN1_MALLOC_ENCODE(PKCS12_CertBag, os.data, os.length,
+ &cb, &size, ret);
+ free_PKCS12_CertBag(&cb);
+ if (ret)
+ goto out;
+
+ ret = addBag(context, &ctx->as, &asn1_oid_id_pkcs12_certBag, os.data,
+ os.length);
+
+ if (_hx509_cert_private_key_exportable(c) &&
+ !(ctx->store_flags & HX509_CERTS_STORE_NO_PRIVATE_KEYS)) {
+ hx509_private_key key = _hx509_cert_private_key(c);
+ PKCS8PrivateKeyInfo pki;
+
+ memset(&pki, 0, sizeof(pki));
+
+ ret = der_parse_hex_heim_integer("00", &pki.version);
+ if (ret)
+ return ret;
+ ret = _hx509_private_key_oid(context, key,
+ &pki.privateKeyAlgorithm.algorithm);
+ if (ret) {
+ free_PKCS8PrivateKeyInfo(&pki);
+ return ret;
+ }
+ ret = _hx509_private_key_export(context,
+ _hx509_cert_private_key(c),
+ HX509_KEY_FORMAT_DER,
+ &pki.privateKey);
+ if (ret) {
+ free_PKCS8PrivateKeyInfo(&pki);
+ return ret;
+ }
+ /* set attribute, asn1_oid_id_pkcs_9_at_localKeyId */
+
+ ASN1_MALLOC_ENCODE(PKCS8PrivateKeyInfo, os.data, os.length,
+ &pki, &size, ret);
+ free_PKCS8PrivateKeyInfo(&pki);
+ if (ret)
+ return ret;
+
+ ret = addBag(context, &ctx->as, &asn1_oid_id_pkcs12_keyBag, os.data,
+ os.length);
+ if (ret)
+ return ret;
+ }
+
+out:
+ return ret;
+}
+
+static int
+p12_store(hx509_context context,
+ hx509_certs certs, void *data, int flags, hx509_lock lock)
+{
+ struct ks_pkcs12 *p12 = data;
+ PKCS12_PFX pfx;
+ struct store_func_ctx ctx;
+ PKCS12_OctetString asdata;
+ size_t size;
+ int ret;
+
+ memset(&ctx, 0, sizeof(ctx));
+ memset(&pfx, 0, sizeof(pfx));
+ ctx.store_flags = flags;
+
+ ret = hx509_certs_iter_f(context, p12->certs, store_func, &ctx);
+ if (ret)
+ goto out;
+
+ ASN1_MALLOC_ENCODE(PKCS12_AuthenticatedSafe, asdata.data, asdata.length,
+ &ctx.as, &size, ret);
+ free_PKCS12_AuthenticatedSafe(&ctx.as);
+ if (ret)
+ return ret;
+
+ ret = der_parse_hex_heim_integer("03", &pfx.version);
+ if (ret) {
+ free(asdata.data);
+ goto out;
+ }
+
+ pfx.authSafe.content = calloc(1, sizeof(*pfx.authSafe.content));
+
+ ASN1_MALLOC_ENCODE(PKCS12_OctetString,
+ pfx.authSafe.content->data,
+ pfx.authSafe.content->length,
+ &asdata, &size, ret);
+ free(asdata.data);
+ if (ret)
+ goto out;
+
+ ret = der_copy_oid(&asn1_oid_id_pkcs7_data, &pfx.authSafe.contentType);
+ if (ret)
+ goto out;
+
+ ASN1_MALLOC_ENCODE(PKCS12_PFX, asdata.data, asdata.length,
+ &pfx, &size, ret);
+ if (ret)
+ goto out;
+
+#if 0
+ const struct _hx509_password *pw;
+
+ pw = _hx509_lock_get_passwords(lock);
+ if (pw != NULL) {
+ pfx.macData = calloc(1, sizeof(*pfx.macData));
+ if (pfx.macData == NULL) {
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "malloc out of memory");
+ return ret;
+ }
+ if (pfx.macData == NULL) {
+ free(asdata.data);
+ goto out;
+ }
+ }
+ ret = calculate_hash(&aspath, pw, pfx.macData);
+#endif
+
+ rk_dumpdata(p12->fn, asdata.data, asdata.length);
+ free(asdata.data);
+
+out:
+ free_PKCS12_AuthenticatedSafe(&ctx.as);
+ free_PKCS12_PFX(&pfx);
+
+ return ret;
+}
+
+
+static int
+p12_free(hx509_certs certs, void *data)
+{
+ struct ks_pkcs12 *p12 = data;
+ hx509_certs_free(&p12->certs);
+ free(p12->fn);
+ free(p12);
+ return 0;
+}
+
+static int
+p12_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c)
+{
+ struct ks_pkcs12 *p12 = data;
+ return hx509_certs_add(context, p12->certs, c);
+}
+
+static int
+p12_iter_start(hx509_context context,
+ hx509_certs certs,
+ void *data,
+ void **cursor)
+{
+ struct ks_pkcs12 *p12 = data;
+ return hx509_certs_start_seq(context, p12->certs, cursor);
+}
+
+static int
+p12_iter(hx509_context context,
+ hx509_certs certs,
+ void *data,
+ void *cursor,
+ hx509_cert *cert)
+{
+ struct ks_pkcs12 *p12 = data;
+ return hx509_certs_next_cert(context, p12->certs, cursor, cert);
+}
+
+static int
+p12_iter_end(hx509_context context,
+ hx509_certs certs,
+ void *data,
+ void *cursor)
+{
+ struct ks_pkcs12 *p12 = data;
+ return hx509_certs_end_seq(context, p12->certs, cursor);
+}
+
+static int
+p12_destroy(hx509_context context, hx509_certs certs, void *data)
+{
+ struct ks_pkcs12 *p12 = data;
+ return _hx509_erase_file(context, p12->fn);
+}
+
+static struct hx509_keyset_ops keyset_pkcs12 = {
+ "PKCS12",
+ 0,
+ p12_init,
+ p12_store,
+ p12_free,
+ p12_add,
+ NULL,
+ p12_iter_start,
+ p12_iter,
+ p12_iter_end,
+ NULL,
+ NULL,
+ NULL,
+ p12_destroy
+};
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_ks_pkcs12_register(hx509_context context)
+{
+ _hx509_ks_register(context, &keyset_pkcs12);
+}
diff --git a/third_party/heimdal/lib/hx509/libhx509-exports.def b/third_party/heimdal/lib/hx509/libhx509-exports.def
new file mode 100644
index 0000000..745ad5a
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/libhx509-exports.def
@@ -0,0 +1,288 @@
+
+EXPORTS
+ _hx509_cert_assign_key
+ _hx509_cert_get_keyusage
+ _hx509_cert_get_version
+ _hx509_cert_private_key
+ _hx509_certs_keys_free
+ _hx509_certs_keys_get
+ _hx509_expr_eval
+ _hx509_expr_free
+ _hx509_expr_parse
+ _hx509_generate_private_key
+ _hx509_generate_private_key_bits
+ _hx509_generate_private_key_free
+ _hx509_generate_private_key_init
+ _hx509_generate_private_key_is_ca
+ _hx509_get_cert
+ _hx509_ks_type
+ _hx509_make_pkinit_san
+ _hx509_map_file_os
+ _hx509_name_from_Name
+ hx509_private_key2SPKI
+ hx509_private_key_free
+ _hx509_private_key_ref
+ hx509_request_add_GeneralName
+ hx509_request_add_dns_name
+ hx509_request_add_dns_srv
+ hx509_request_add_eku
+ hx509_request_add_email
+ hx509_request_add_ms_upn_name
+ hx509_request_add_pkinit
+ hx509_request_add_registered
+ hx509_request_add_xmpp_name
+ hx509_request_authorize_ku
+ hx509_request_authorize_eku
+ hx509_request_authorize_san
+ hx509_request_count_unsupported
+ hx509_request_count_unauthorized
+ _hx509_private_key_export
+ _hx509_private_key_exportable
+ _hx509_private_key_get_internal
+ _hx509_private_key_oid
+ _hx509_private_key_ref
+ hx509_request_free
+ hx509_request_get_eku
+ hx509_request_get_exts
+ hx509_request_get_ku
+ hx509_request_get_name
+ hx509_request_get_san
+ hx509_request_get_SubjectPublicKeyInfo
+ hx509_request_get_name
+ hx509_request_init
+ hx509_request_parse
+ hx509_request_parse_der
+ hx509_request_print
+ hx509_request_set_SubjectPublicKeyInfo
+ hx509_request_add_email
+ hx509_request_set_name
+ hx509_request_set_ku
+ hx509_request_to_pkcs10
+ _hx509_unmap_file_os
+ _hx509_write_file
+ hx509_bitstring_print
+ _hx509_ca_issue_certificate
+ hx509_ca_sign
+ hx509_ca_sign_self
+ hx509_ca_tbs_add_crl_dp_uri
+ hx509_ca_tbs_add_eku
+ hx509_ca_tbs_add_ku
+ hx509_ca_tbs_add_pol
+ hx509_ca_tbs_add_pol_mapping
+ hx509_ca_tbs_add_san
+ hx509_ca_tbs_add_san_dnssrv
+ hx509_ca_tbs_add_san_hardwareModuleName
+ hx509_ca_tbs_add_san_hardwareModuleName_string
+ hx509_ca_tbs_add_san_hostname
+ hx509_ca_tbs_add_san_jid
+ hx509_ca_tbs_add_san_ms_upn
+ hx509_ca_tbs_add_san_otherName
+ hx509_ca_tbs_add_san_permanentIdentifier
+ hx509_ca_tbs_add_san_permanentIdentifier_string
+ hx509_ca_tbs_add_san_pkinit
+ hx509_ca_tbs_add_san_rfc822name
+ hx509_ca_tbs_free
+ hx509_ca_tbs_get_name
+ hx509_ca_tbs_init
+ hx509_ca_tbs_set_ca
+ hx509_ca_tbs_set_domaincontroller
+ hx509_ca_tbs_set_from_csr
+ hx509_ca_tbs_set_notAfter
+ hx509_ca_tbs_set_notAfter_lifetime
+ hx509_ca_tbs_set_notBefore
+ hx509_ca_tbs_set_pkinit_max_life
+ hx509_ca_tbs_set_proxy
+ hx509_ca_tbs_set_serialnumber
+ hx509_ca_tbs_set_signature_algorithm
+ hx509_ca_tbs_set_spki
+ hx509_ca_tbs_set_subject
+ hx509_ca_tbs_set_template
+ hx509_ca_tbs_subject_expand
+ hx509_ca_tbs_template_units
+; hx509_cert
+; hx509_cert_attribute
+ hx509_cert_binary
+ hx509_cert_check_eku
+ hx509_cert_cmp
+ hx509_cert_find_subjectAltName_otherName
+ hx509_cert_free
+ hx509_cert_get_SPKI
+ hx509_cert_get_SPKI_AlgorithmIdentifier
+ hx509_cert_get_attribute
+ hx509_cert_get_base_subject
+ hx509_cert_get_friendly_name
+ hx509_cert_get_issuer
+ hx509_cert_get_notAfter
+ hx509_cert_get_notBefore
+ hx509_cert_get_pkinit_max_life
+ hx509_cert_get_serialnumber
+ hx509_cert_get_subject
+ hx509_cert_have_private_key
+ hx509_cert_have_private_key_only
+ hx509_cert_init
+ hx509_cert_init_data
+ hx509_cert_init_private_key
+ hx509_cert_keyusage_print
+ hx509_cert_ref
+ hx509_cert_set_friendly_name
+ hx509_certs_add
+ hx509_certs_append
+ hx509_certs_destroy
+ hx509_certs_end_seq
+ hx509_certs_ref
+ hx509_certs_filter
+ hx509_certs_find
+ hx509_certs_free
+ hx509_certs_info
+ hx509_certs_init
+; hx509_certs_iter
+ hx509_certs_iter_f
+ hx509_certs_merge
+ hx509_certs_next_cert
+ hx509_certs_start_seq
+ hx509_certs_store
+ hx509_ci_print_names
+ hx509_clear_error_string
+ hx509_cms_create_signed
+ hx509_cms_create_signed_1
+ hx509_cms_decrypt_encrypted
+ hx509_cms_envelope_1
+ hx509_cms_unenvelope
+ hx509_cms_unwrap_ContentInfo
+ hx509_cms_verify_signed
+ hx509_cms_verify_signed_ext
+ hx509_cms_wrap_ContentInfo
+ hx509_context_free
+ hx509_context_init
+ hx509_context_set_missing_revoke
+ hx509_crl_add_revoked_certs
+ hx509_crl_alloc
+ hx509_crl_free
+ hx509_crl_lifetime
+ hx509_crl_sign
+ hx509_crypto_aes128_cbc
+ hx509_crypto_aes256_cbc
+ hx509_crypto_allow_weak
+ hx509_crypto_available
+ hx509_crypto_decrypt
+ hx509_crypto_des_rsdi_ede3_cbc
+ hx509_crypto_destroy
+ hx509_crypto_encrypt
+ hx509_crypto_enctype_by_name
+ hx509_crypto_free_algs
+ hx509_crypto_get_params
+ hx509_crypto_init
+ hx509_crypto_provider
+ hx509_crypto_select
+ hx509_crypto_set_key_data
+ hx509_crypto_set_key_name
+ hx509_crypto_set_padding
+ hx509_crypto_set_params
+ hx509_crypto_set_random_key
+ hx509_empty_name
+ hx509_env_add
+ hx509_env_add_binding
+ hx509_env_find
+ hx509_env_find_binding
+ hx509_env_free
+; hx509_env_init
+ hx509_env_lfind
+ hx509_err
+ hx509_free_error_string
+ hx509_free_octet_string_list
+ hx509_general_name_unparse
+ hx509_get_error_string
+ hx509_get_instance
+ hx509_get_one_cert
+ hx509_lock_add_cert
+ hx509_lock_add_certs
+ hx509_lock_add_password
+ hx509_lock_command_string
+ hx509_lock_free
+ hx509_lock_init
+ hx509_lock_prompt
+ hx509_lock_reset_certs
+ hx509_lock_reset_passwords
+ hx509_lock_reset_promper
+ hx509_lock_set_prompter
+ hx509_name_binary
+ hx509_name_cmp
+ hx509_name_copy
+ hx509_name_expand
+ hx509_name_free
+ hx509_name_is_null_p
+ hx509_name_normalize
+ hx509_name_to_Name
+ hx509_name_to_string
+ hx509_ocsp_request
+ hx509_ocsp_verify
+ hx509_oid_print
+ hx509_oid_sprint
+ hx509_parse_name
+ hx509_parse_private_key
+ hx509_peer_info_add_cms_alg
+ hx509_peer_info_alloc
+ hx509_peer_info_free
+ hx509_peer_info_set_cert
+ hx509_peer_info_set_cms_algs
+ hx509_pem_add_header
+ hx509_pem_find_header
+ hx509_pem_free_header
+ hx509_pem_read
+ hx509_pem_write
+ hx509_print_stdout
+ hx509_print_cert
+ hx509_prompt_hidden
+ hx509_query_alloc
+ hx509_query_free
+ hx509_query_match_cmp_func
+ hx509_query_match_eku
+ hx509_query_match_expr
+ hx509_query_match_friendly_name
+ hx509_query_match_issuer_serial
+ hx509_query_match_option
+ hx509_query_statistic_file
+ hx509_query_unparse_stats
+ hx509_revoke_add_crl
+ hx509_revoke_add_ocsp
+ hx509_revoke_free
+ hx509_revoke_init
+ hx509_revoke_ocsp_print
+ hx509_revoke_print
+ hx509_revoke_verify
+ hx509_set_error_string
+ hx509_set_error_stringv
+ hx509_signature_md5
+ hx509_signature_rsa
+ hx509_signature_rsa_with_md5
+ hx509_signature_rsa_with_sha1
+ hx509_signature_rsa_with_sha256
+ hx509_signature_rsa_with_sha384
+ hx509_signature_rsa_with_sha512
+ hx509_signature_sha1
+ hx509_signature_sha256
+ hx509_signature_sha384
+ hx509_signature_sha512
+ hx509_unparse_der_name
+ hx509_validate_cert
+ hx509_validate_ctx_add_flags
+ hx509_validate_ctx_free
+ hx509_validate_ctx_init
+ hx509_validate_ctx_set_print
+ hx509_verify_attach_anchors
+ hx509_verify_attach_revoke
+ hx509_verify_ctx_f_allow_default_trustanchors
+ hx509_verify_destroy_ctx
+ hx509_verify_hostname
+ hx509_verify_init_ctx
+ hx509_verify_path
+ hx509_verify_set_max_depth
+ hx509_verify_set_proxy_certificate
+ hx509_verify_set_strict_rfc3280_verification
+ hx509_verify_set_time
+ hx509_verify_signature
+ hx509_xfree
+ initialize_hx_error_table_r
+
+; pkcs11 symbols
+ C_GetFunctionList
diff --git a/third_party/heimdal/lib/hx509/lock.c b/third_party/heimdal/lib/hx509/lock.c
new file mode 100644
index 0000000..7f767d2
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/lock.c
@@ -0,0 +1,252 @@
+/*
+ * Copyright (c) 2005 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+/**
+ * @page page_lock Locking and unlocking certificates and encrypted data.
+ *
+ * See the library functions here: @ref hx509_lock
+ */
+
+struct hx509_lock_data {
+ struct _hx509_password password;
+ hx509_certs certs;
+ hx509_prompter_fct prompt;
+ void *prompt_data;
+};
+
+static struct hx509_lock_data empty_lock_data = {
+ { 0, NULL },
+ NULL,
+ NULL,
+ NULL
+};
+
+hx509_lock _hx509_empty_lock = &empty_lock_data;
+
+/*
+ *
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_lock_init(hx509_context context, hx509_lock *lock)
+{
+ hx509_lock l;
+ int ret;
+
+ *lock = NULL;
+
+ l = calloc(1, sizeof(*l));
+ if (l == NULL)
+ return ENOMEM;
+
+ ret = hx509_certs_init(context,
+ "MEMORY:locks-internal",
+ 0,
+ NULL,
+ &l->certs);
+ if (ret) {
+ free(l);
+ return ret;
+ }
+
+ *lock = l;
+
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_lock_add_password(hx509_lock lock, const char *password)
+{
+ void *d;
+ char *s;
+
+ s = strdup(password);
+ if (s == NULL)
+ return ENOMEM;
+
+ d = realloc(lock->password.val,
+ (lock->password.len + 1) * sizeof(lock->password.val[0]));
+ if (d == NULL) {
+ free(s);
+ return ENOMEM;
+ }
+ lock->password.val = d;
+ lock->password.val[lock->password.len] = s;
+ lock->password.len++;
+
+ return 0;
+}
+
+HX509_LIB_FUNCTION const struct _hx509_password * HX509_LIB_CALL
+_hx509_lock_get_passwords(hx509_lock lock)
+{
+ return &lock->password;
+}
+
+HX509_LIB_FUNCTION hx509_certs HX509_LIB_CALL
+_hx509_lock_unlock_certs(hx509_lock lock)
+{
+ return lock->certs;
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_lock_reset_passwords(hx509_lock lock)
+{
+ size_t i;
+ for (i = 0; i < lock->password.len; i++)
+ free(lock->password.val[i]);
+ free(lock->password.val);
+ lock->password.val = NULL;
+ lock->password.len = 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_lock_add_cert(hx509_context context, hx509_lock lock, hx509_cert cert)
+{
+ return hx509_certs_add(context, lock->certs, cert);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_lock_add_certs(hx509_context context, hx509_lock lock, hx509_certs certs)
+{
+ return hx509_certs_merge(context, lock->certs, certs);
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_lock_reset_certs(hx509_context context, hx509_lock lock)
+{
+ hx509_certs certs = lock->certs;
+ int ret;
+
+ ret = hx509_certs_init(context,
+ "MEMORY:locks-internal",
+ 0,
+ NULL,
+ &lock->certs);
+ if (ret == 0)
+ hx509_certs_free(&certs);
+ else
+ lock->certs = certs;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_lock_find_cert(hx509_lock lock, const hx509_query *q, hx509_cert *c)
+{
+ *c = NULL;
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_lock_set_prompter(hx509_lock lock, hx509_prompter_fct prompt, void *data)
+{
+ lock->prompt = prompt;
+ lock->prompt_data = data;
+ return 0;
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_lock_reset_promper(hx509_lock lock)
+{
+ lock->prompt = NULL;
+ lock->prompt_data = NULL;
+}
+
+static int
+default_prompter(void *data, const hx509_prompt *prompter)
+{
+ if (hx509_prompt_hidden(prompter->type)) {
+ if(UI_UTIL_read_pw_string(prompter->reply.data,
+ prompter->reply.length,
+ prompter->prompt,
+ 0))
+ return 1;
+ } else {
+ char *s = prompter->reply.data;
+
+ fputs (prompter->prompt, stdout);
+ fflush (stdout);
+ if(fgets(prompter->reply.data,
+ prompter->reply.length,
+ stdin) == NULL)
+ return 1;
+ s[strcspn(s, "\n")] = '\0';
+ }
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_lock_prompt(hx509_lock lock, hx509_prompt *prompt)
+{
+ if (lock->prompt == NULL)
+ return HX509_CRYPTO_NO_PROMPTER;
+ return (*lock->prompt)(lock->prompt_data, prompt);
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_lock_free(hx509_lock lock)
+{
+ if (lock) {
+ hx509_certs_free(&lock->certs);
+ hx509_lock_reset_passwords(lock);
+ memset(lock, 0, sizeof(*lock));
+ free(lock);
+ }
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_prompt_hidden(hx509_prompt_type type)
+{
+ /* default to hidden if unknown */
+
+ switch (type) {
+ case HX509_PROMPT_TYPE_QUESTION:
+ case HX509_PROMPT_TYPE_INFO:
+ return 0;
+ default:
+ return 1;
+ }
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_lock_command_string(hx509_lock lock, const char *string)
+{
+ if (strncasecmp(string, "PASS:", 5) == 0) {
+ hx509_lock_add_password(lock, string + 5);
+ } else if (strcasecmp(string, "PROMPT") == 0) {
+ hx509_lock_set_prompter(lock, default_prompter, NULL);
+ } else
+ return HX509_UNKNOWN_LOCK_COMMAND;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hx509/name.c b/third_party/heimdal/lib/hx509/name.c
new file mode 100644
index 0000000..7d67716
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/name.c
@@ -0,0 +1,1529 @@
+/*
+ * Copyright (c) 2004 - 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+#include <wind.h>
+#include "char_map.h"
+
+/**
+ * @page page_name PKIX/X.509 Names
+ *
+ * There are several names in PKIX/X.509, GeneralName and Name.
+ *
+ * A Name consists of an ordered list of Relative Distinguished Names
+ * (RDN). Each RDN consists of an unordered list of typed strings. The
+ * types are defined by OID and have long and short description. For
+ * example id-at-commonName (2.5.4.3) have the long name CommonName
+ * and short name CN. The string itself can be of several encoding,
+ * UTF8, UTF16, Teltex string, etc. The type limit what encoding
+ * should be used.
+ *
+ * GeneralName is a broader nametype that can contains al kind of
+ * stuff like Name, IP addresses, partial Name, etc.
+ *
+ * Name is mapped into a hx509_name object.
+ *
+ * Parse and string name into a hx509_name object with hx509_parse_name(),
+ * make it back into string representation with hx509_name_to_string().
+ *
+ * Name string are defined rfc2253, rfc1779 and X.501.
+ *
+ * See the library functions here: @ref hx509_name
+ */
+
+static const struct {
+ const char *n;
+ const heim_oid *o;
+ int type_choice; /* Preference for DirectoryString choice; 0 -> no pref */
+ wind_profile_flags flags;
+ /*
+ * RFC52380 imposes maximum lengths for some strings in Names. These are
+ * ASN.1 size limits. We should implement these in our copy of the PKIX
+ * ASN.1 module. For now we treat them as maximum byte counts rather than
+ * maximum character counts, and we encode and enforce them here.
+ *
+ * 0 -> no max
+ *
+ * Some of these attributes aren't of type DirectoryString, so our
+ * type_choice isn't really correct. We're not really set up for
+ * attributes whose types aren't DirectoryString or one of its choice arms'
+ * type, much less are we set up for non-string attribute value types.
+ */
+ size_t max_bytes;
+} no[] = {
+ { "C", &asn1_oid_id_at_countryName,
+ choice_DirectoryString_printableString, 0, 2 },
+ { "CN", &asn1_oid_id_at_commonName, 0, 0, ub_common_name },
+ { "DC", &asn1_oid_id_domainComponent, choice_DirectoryString_ia5String,
+ 0, 63 }, /* DNS label */
+ { "L", &asn1_oid_id_at_localityName, 0, 0, ub_locality_name },
+ { "O", &asn1_oid_id_at_organizationName, 0, 0, ub_organization_name },
+ { "OU", &asn1_oid_id_at_organizationalUnitName, 0, 0,
+ ub_organizational_unit_name },
+ { "S", &asn1_oid_id_at_stateOrProvinceName, 0, 0, ub_state_name },
+ { "STREET", &asn1_oid_id_at_streetAddress, 0, 0, 0 }, /* ENOTSUP */
+ { "UID", &asn1_oid_id_Userid, 0, 0, ub_numeric_user_id_length },
+ { "emailAddress", &asn1_oid_id_pkcs9_emailAddress,
+ choice_DirectoryString_ia5String, 0, ub_emailaddress_length },
+ /* This is for DevID certificates and maybe others */
+ { "serialNumber", &asn1_oid_id_at_serialNumber, 0, 0, ub_serial_number },
+ /* These are for TPM 2.0 Endorsement Key Certificates (EKCerts) */
+ { "TPMManufacturer", &asn1_oid_tcg_at_tpmManufacturer, 0, 0,
+ ub_emailaddress_length },
+ { "TPMModel", &asn1_oid_tcg_at_tpmModel, 0, 0, ub_emailaddress_length },
+ { "TPMVersion", &asn1_oid_tcg_at_tpmVersion, 0, 0, ub_emailaddress_length },
+};
+
+static char *
+quote_string(const char *f, size_t len, int flags, size_t *rlen)
+{
+ size_t i, j, tolen;
+ const unsigned char *from = (const unsigned char *)f;
+ unsigned char *to;
+
+ tolen = len * 3 + 1;
+ to = malloc(tolen);
+ if (to == NULL)
+ return NULL;
+
+ for (i = 0, j = 0; i < len; i++) {
+ unsigned char map = char_map[from[i]] & flags;
+ if (i == 0 && (map & Q_RFC2253_QUOTE_FIRST)) {
+ to[j++] = '\\';
+ to[j++] = from[i];
+ } else if ((i + 1) == len && (map & Q_RFC2253_QUOTE_LAST)) {
+
+ to[j++] = '\\';
+ to[j++] = from[i];
+ } else if (map & Q_RFC2253_QUOTE) {
+ to[j++] = '\\';
+ to[j++] = from[i];
+ } else if (map & Q_RFC2253_HEX) {
+ int l = snprintf((char *)&to[j], tolen - j - 1,
+ "#%02x", (unsigned char)from[i]);
+ j += l;
+ } else {
+ to[j++] = from[i];
+ }
+ }
+ to[j] = '\0';
+ assert(j < tolen);
+ *rlen = j;
+ return (char *)to;
+}
+
+
+static int
+append_string(char **str, size_t *total_len, const char *ss,
+ size_t len, int quote)
+{
+ char *s, *qs;
+
+ if (quote)
+ qs = quote_string(ss, len, Q_RFC2253, &len);
+ else
+ qs = rk_UNCONST(ss);
+
+ s = realloc(*str, len + *total_len + 1);
+ if (s == NULL)
+ _hx509_abort("allocation failure"); /* XXX */
+ memcpy(s + *total_len, qs, len);
+ if (qs != ss)
+ free(qs);
+ s[*total_len + len] = '\0';
+ *str = s;
+ *total_len += len;
+ return 0;
+}
+
+static char *
+oidtostring(const heim_oid *type, int *type_choice)
+{
+ char *s;
+ size_t i;
+
+ if (type_choice)
+ *type_choice = choice_DirectoryString_utf8String;
+
+ for (i = 0; i < sizeof(no)/sizeof(no[0]); i++) {
+ if (der_heim_oid_cmp(no[i].o, type) == 0) {
+ if (type_choice && no[i].type_choice)
+ *type_choice = no[i].type_choice;
+ return strdup(no[i].n);
+ }
+ }
+ if (der_print_heim_oid(type, '.', &s) != 0)
+ return NULL;
+ return s;
+}
+
+static size_t
+oidtomaxlen(const heim_oid *type)
+{
+ size_t i;
+
+ for (i = 0; i < sizeof(no)/sizeof(no[0]); i++) {
+ if (der_heim_oid_cmp(no[i].o, type) == 0)
+ return no[i].max_bytes;
+ }
+ return 0;
+}
+
+static int
+stringtooid(const char *name, size_t len, heim_oid *oid)
+{
+ int ret;
+ size_t i;
+ char *s;
+
+ memset(oid, 0, sizeof(*oid));
+
+ for (i = 0; i < sizeof(no)/sizeof(no[0]); i++) {
+ if (strncasecmp(no[i].n, name, len) == 0)
+ return der_copy_oid(no[i].o, oid);
+ }
+ s = malloc(len + 1);
+ if (s == NULL)
+ return ENOMEM;
+ memcpy(s, name, len);
+ s[len] = '\0';
+ ret = der_parse_heim_oid(s, ".", oid);
+ free(s);
+ return ret;
+}
+
+/**
+ * Convert the hx509 name object into a printable string.
+ * The resulting string should be freed with free().
+ *
+ * @param name name to print
+ * @param str the string to return
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_name
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_name_to_string(const hx509_name name, char **str)
+{
+ return _hx509_Name_to_string(&name->der_name, str);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_Name_to_string(const Name *n, char **str)
+{
+ size_t total_len = 0;
+ size_t i, j, m;
+ int ret;
+
+ *str = strdup("");
+ if (*str == NULL)
+ return ENOMEM;
+
+ for (m = n->u.rdnSequence.len; m > 0; m--) {
+ size_t len;
+ i = m - 1;
+
+ for (j = 0; j < n->u.rdnSequence.val[i].len; j++) {
+ DirectoryString *ds = &n->u.rdnSequence.val[i].val[j].value;
+ char *oidname;
+ char *ss;
+
+ oidname = oidtostring(&n->u.rdnSequence.val[i].val[j].type, NULL);
+
+ switch(ds->element) {
+ case choice_DirectoryString_ia5String:
+ ss = ds->u.ia5String.data;
+ len = ds->u.ia5String.length;
+ break;
+ case choice_DirectoryString_printableString:
+ ss = ds->u.printableString.data;
+ len = ds->u.printableString.length;
+ break;
+ case choice_DirectoryString_utf8String:
+ ss = ds->u.utf8String;
+ len = strlen(ss);
+ break;
+ case choice_DirectoryString_bmpString: {
+ const uint16_t *bmp = ds->u.bmpString.data;
+ size_t bmplen = ds->u.bmpString.length;
+ size_t k;
+
+ ret = wind_ucs2utf8_length(bmp, bmplen, &k);
+ if (ret) {
+ free(oidname);
+ free(*str);
+ *str = NULL;
+ return ret;
+ }
+
+ ss = malloc(k + 1);
+ if (ss == NULL)
+ _hx509_abort("allocation failure"); /* XXX */
+ ret = wind_ucs2utf8(bmp, bmplen, ss, NULL);
+ if (ret) {
+ free(oidname);
+ free(ss);
+ free(*str);
+ *str = NULL;
+ return ret;
+ }
+ ss[k] = '\0';
+ len = k;
+ break;
+ }
+ case choice_DirectoryString_teletexString:
+ ss = ds->u.teletexString;
+ len = strlen(ss);
+ break;
+ case choice_DirectoryString_universalString: {
+ const uint32_t *uni = ds->u.universalString.data;
+ size_t unilen = ds->u.universalString.length;
+ size_t k;
+
+ ret = wind_ucs4utf8_length(uni, unilen, &k);
+ if (ret) {
+ free(oidname);
+ free(*str);
+ *str = NULL;
+ return ret;
+ }
+
+ ss = malloc(k + 1);
+ if (ss == NULL)
+ _hx509_abort("allocation failure"); /* XXX */
+ ret = wind_ucs4utf8(uni, unilen, ss, NULL);
+ if (ret) {
+ free(ss);
+ free(oidname);
+ free(*str);
+ *str = NULL;
+ return ret;
+ }
+ ss[k] = '\0';
+ len = k;
+ break;
+ }
+ default:
+ _hx509_abort("unknown directory type: %d", ds->element);
+ exit(1);
+ }
+ append_string(str, &total_len, oidname, strlen(oidname), 0);
+ free(oidname);
+ append_string(str, &total_len, "=", 1, 0);
+ append_string(str, &total_len, ss, len, 1);
+ if (ds->element == choice_DirectoryString_bmpString ||
+ ds->element == choice_DirectoryString_universalString)
+ {
+ free(ss);
+ }
+ if (j + 1 < n->u.rdnSequence.val[i].len)
+ append_string(str, &total_len, "+", 1, 0);
+ }
+
+ if (i > 0)
+ append_string(str, &total_len, ",", 1, 0);
+ }
+ return 0;
+}
+
+#define COPYCHARARRAY(_ds,_el,_l,_n) \
+ (_l) = strlen(_ds->u._el); \
+ (_n) = malloc((_l + 1) * sizeof((_n)[0])); \
+ if ((_n) == NULL) \
+ return ENOMEM; \
+ for (i = 0; i < (_l); i++) \
+ (_n)[i] = _ds->u._el[i]
+
+
+#define COPYVALARRAY(_ds,_el,_l,_n) \
+ (_l) = _ds->u._el.length; \
+ (_n) = malloc((_l + 1) * sizeof((_n)[0])); \
+ if ((_n) == NULL) \
+ return ENOMEM; \
+ for (i = 0; i < (_l); i++) \
+ (_n)[i] = _ds->u._el.data[i]
+
+#define COPYVOIDARRAY(_ds,_el,_l,_n) \
+ (_l) = _ds->u._el.length; \
+ (_n) = malloc((_l + 1) * sizeof((_n)[0])); \
+ if ((_n) == NULL) \
+ return ENOMEM; \
+ for (i = 0; i < (_l); i++) \
+ (_n)[i] = ((unsigned char *)_ds->u._el.data)[i]
+
+
+
+static int
+dsstringprep(const DirectoryString *ds, uint32_t **rname, size_t *rlen)
+{
+ wind_profile_flags flags;
+ size_t i, len;
+ int ret = 0;
+ uint32_t *name;
+
+ *rname = NULL;
+ *rlen = 0;
+
+ switch(ds->element) {
+ case choice_DirectoryString_ia5String:
+ flags = WIND_PROFILE_LDAP;
+ COPYVOIDARRAY(ds, ia5String, len, name);
+ break;
+ case choice_DirectoryString_printableString:
+ flags = WIND_PROFILE_LDAP;
+ flags |= WIND_PROFILE_LDAP_CASE_EXACT_ATTRIBUTE;
+ COPYVOIDARRAY(ds, printableString, len, name);
+ break;
+ case choice_DirectoryString_teletexString:
+ flags = WIND_PROFILE_LDAP_CASE;
+ COPYCHARARRAY(ds, teletexString, len, name);
+ break;
+ case choice_DirectoryString_bmpString:
+ flags = WIND_PROFILE_LDAP;
+ COPYVALARRAY(ds, bmpString, len, name);
+ break;
+ case choice_DirectoryString_universalString:
+ flags = WIND_PROFILE_LDAP;
+ COPYVALARRAY(ds, universalString, len, name);
+ break;
+ case choice_DirectoryString_utf8String:
+ flags = WIND_PROFILE_LDAP;
+ ret = wind_utf8ucs4_length(ds->u.utf8String, &len);
+ if (ret)
+ return ret;
+ name = malloc((len + 1) * sizeof(name[0]));
+ if (name == NULL)
+ return ENOMEM;
+ ret = wind_utf8ucs4(ds->u.utf8String, name, &len);
+ if (ret) {
+ free(name);
+ return ret;
+ }
+ break;
+ default:
+ _hx509_abort("unknown directory type: %d", ds->element);
+ }
+
+ *rlen = len;
+ /* try a couple of times to get the length right, XXX gross */
+ for (i = 0; i < 4; i++) {
+ *rlen = *rlen * 2;
+ if ((*rname = malloc((rlen[0] + 1) * sizeof((*rname)[0]))) == NULL) {
+ ret = ENOMEM;
+ break;
+ }
+
+ ret = wind_stringprep(name, len, *rname, rlen, flags);
+ if (ret == WIND_ERR_OVERRUN) {
+ free(*rname);
+ *rname = NULL;
+ continue;
+ } else
+ break;
+ }
+ free(name);
+ if (ret) {
+ if (*rname)
+ free(*rname);
+ *rname = NULL;
+ *rlen = 0;
+ return ret;
+ }
+
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_name_ds_cmp(const DirectoryString *ds1,
+ const DirectoryString *ds2,
+ int *diff)
+{
+ uint32_t *ds1lp, *ds2lp;
+ size_t ds1len, ds2len, i;
+ int ret;
+
+ ret = dsstringprep(ds1, &ds1lp, &ds1len);
+ if (ret)
+ return ret;
+ ret = dsstringprep(ds2, &ds2lp, &ds2len);
+ if (ret) {
+ free(ds1lp);
+ return ret;
+ }
+
+ if (ds1len != ds2len)
+ *diff = ds1len - ds2len;
+ else {
+ for (i = 0; i < ds1len; i++) {
+ *diff = ds1lp[i] - ds2lp[i];
+ if (*diff)
+ break;
+ }
+ }
+ free(ds1lp);
+ free(ds2lp);
+
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_name_cmp(const Name *n1, const Name *n2, int *c)
+{
+ int ret;
+ size_t i, j;
+
+ *c = n1->u.rdnSequence.len - n2->u.rdnSequence.len;
+ if (*c)
+ return 0;
+
+ for (i = 0 ; i < n1->u.rdnSequence.len; i++) {
+ *c = n1->u.rdnSequence.val[i].len - n2->u.rdnSequence.val[i].len;
+ if (*c)
+ return 0;
+
+ for (j = 0; j < n1->u.rdnSequence.val[i].len; j++) {
+ *c = der_heim_oid_cmp(&n1->u.rdnSequence.val[i].val[j].type,
+ &n1->u.rdnSequence.val[i].val[j].type);
+ if (*c)
+ return 0;
+
+ ret = _hx509_name_ds_cmp(&n1->u.rdnSequence.val[i].val[j].value,
+ &n2->u.rdnSequence.val[i].val[j].value,
+ c);
+ if (ret)
+ return ret;
+ if (*c)
+ return 0;
+ }
+ }
+ *c = 0;
+ return 0;
+}
+
+/**
+ * Compare to hx509 name object, useful for sorting.
+ *
+ * @param n1 a hx509 name object.
+ * @param n2 a hx509 name object.
+ *
+ * @return 0 the objects are the same, returns > 0 is n2 is "larger"
+ * then n2, < 0 if n1 is "smaller" then n2.
+ *
+ * @ingroup hx509_name
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_name_cmp(hx509_name n1, hx509_name n2)
+{
+ int ret, diff;
+ ret = _hx509_name_cmp(&n1->der_name, &n2->der_name, &diff);
+ if (ret)
+ return ret;
+ return diff;
+}
+
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_name_from_Name(const Name *n, hx509_name *name)
+{
+ int ret;
+ *name = calloc(1, sizeof(**name));
+ if (*name == NULL)
+ return ENOMEM;
+ ret = copy_Name(n, &(*name)->der_name);
+ if (ret) {
+ free(*name);
+ *name = NULL;
+ }
+ return ret;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_name_modify(hx509_context context,
+ Name *name,
+ int append,
+ const heim_oid *oid,
+ const char *str)
+{
+ RelativeDistinguishedName rdn;
+ size_t max_len = oidtomaxlen(oid);
+ char *s = NULL;
+ int type_choice = choice_DirectoryString_printableString;
+ int ret;
+
+ /*
+ * Check string length upper bounds.
+ *
+ * Because we don't have these bounds in our copy of the PKIX ASN.1 module,
+ * and because we might like to catch these early anyways, we enforce them
+ * here.
+ */
+ if (max_len && strlen(str) > max_len) {
+ char *a = oidtostring(oid, &type_choice);
+
+ ret = HX509_PARSING_NAME_FAILED;
+ hx509_set_error_string(context, 0, ret, "RDN attribute %s value too "
+ "long (max %llu): %s", a ? a : "<unknown>",
+ max_len, str);
+ free(a);
+ return ret;
+ }
+
+ memset(&rdn, 0, sizeof(rdn));
+ if ((rdn.val = malloc(sizeof(rdn.val[0]))) == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "Out of memory");
+ return ENOMEM;
+ }
+ rdn.len = 1;
+
+ /*
+ * How best to pick a type for this attribute value?
+ *
+ * Options:
+ *
+ * 1) the API deals only in UTF-8, let the callers convert to/from UTF-8
+ * and whatever the current locale wants
+ *
+ * 2) use the best type for the codeset of the current locale.
+ *
+ * We choose (1).
+ *
+ * However, for some cases we really should prefer other types when the
+ * input string is all printable ASCII.
+ */
+ rdn.val[0].value.element = type_choice;
+ if ((s = strdup(str)) == NULL ||
+ der_copy_oid(oid, &rdn.val[0].type)) {
+ free(rdn.val);
+ free(s);
+ return hx509_enomem(context);
+ }
+ switch (rdn.val[0].value.element) {
+ /* C strings: */
+ case choice_DirectoryString_utf8String:
+ rdn.val[0].value.u.utf8String = s;
+ break;
+ case choice_DirectoryString_teletexString:
+ rdn.val[0].value.u.teletexString = s;
+ break;
+
+ /* Length and pointer */
+ case choice_DirectoryString_ia5String:
+ rdn.val[0].value.u.ia5String.data = s;
+ rdn.val[0].value.u.ia5String.length = strlen(s);
+ break;
+ case choice_DirectoryString_printableString:
+ rdn.val[0].value.u.printableString.data = s;
+ rdn.val[0].value.u.printableString.length = strlen(s);
+ break;
+ case choice_DirectoryString_universalString:
+ free(s);
+ free(rdn.val);
+ hx509_set_error_string(context, 0, ENOTSUP, "UniversalString not supported");
+ return ENOTSUP;
+ case choice_DirectoryString_bmpString:
+ free(s);
+ free(rdn.val);
+ hx509_set_error_string(context, 0, ENOTSUP, "BMPString not supported");
+ return ENOTSUP;
+ default:
+ free(s);
+ free(rdn.val);
+ hx509_set_error_string(context, 0, ENOTSUP,
+ "Internal error; unknown DirectoryString choice");
+ return ENOTSUP;
+ }
+
+ /* Append RDN. If the caller wanted to prepend instead, we'll rotate. */
+ ret = add_RDNSequence(&name->u.rdnSequence, &rdn);
+ free_RelativeDistinguishedName(&rdn);
+
+ if (ret || append || name->u.rdnSequence.len < 2)
+ return ret;
+
+ /* Rotate */
+ rdn = name->u.rdnSequence.val[name->u.rdnSequence.len - 1];
+ memmove(&name->u.rdnSequence.val[1],
+ &name->u.rdnSequence.val[0],
+ (name->u.rdnSequence.len - 1) *
+ sizeof(name->u.rdnSequence.val[0]));
+ name->u.rdnSequence.val[0] = rdn;
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_empty_name(hx509_context context, hx509_name *name)
+{
+ if ((*name = calloc(1, sizeof(**name))) == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+ (*name)->der_name.element = choice_Name_rdnSequence;
+ (*name)->der_name.u.rdnSequence.val = 0;
+ (*name)->der_name.u.rdnSequence.len = 0;
+ return 0;
+}
+
+/**
+ * Parse a string into a hx509 name object.
+ *
+ * @param context A hx509 context.
+ * @param str a string to parse.
+ * @param name the resulting object, NULL in case of error.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_name
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_parse_name(hx509_context context, const char *str, hx509_name *name)
+{
+ const char *p, *q;
+ size_t len;
+ hx509_name n;
+ int ret;
+
+ *name = NULL;
+
+ n = calloc(1, sizeof(*n));
+ if (n == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ n->der_name.element = choice_Name_rdnSequence;
+
+ p = str;
+
+ while (p != NULL && *p != '\0') {
+ heim_oid oid;
+ int last;
+
+ q = strchr(p, ',');
+ if (q) {
+ len = (q - p);
+ last = 1;
+ } else {
+ len = strlen(p);
+ last = 0;
+ }
+
+ q = strchr(p, '=');
+ if (q == NULL) {
+ ret = HX509_PARSING_NAME_FAILED;
+ hx509_set_error_string(context, 0, ret, "missing = in %s", p);
+ goto out;
+ }
+ if (q == p) {
+ ret = HX509_PARSING_NAME_FAILED;
+ hx509_set_error_string(context, 0, ret,
+ "missing name before = in %s", p);
+ goto out;
+ }
+
+ if ((size_t)(q - p) > len) {
+ ret = HX509_PARSING_NAME_FAILED;
+ hx509_set_error_string(context, 0, ret, " = after , in %s", p);
+ goto out;
+ }
+
+ ret = stringtooid(p, q - p, &oid);
+ if (ret) {
+ ret = HX509_PARSING_NAME_FAILED;
+ hx509_set_error_string(context, 0, ret,
+ "unknown type: %.*s", (int)(q - p), p);
+ goto out;
+ }
+
+ {
+ size_t pstr_len = len - (q - p) - 1;
+ const char *pstr = p + (q - p) + 1;
+ char *r;
+
+ r = malloc(pstr_len + 1);
+ if (r == NULL) {
+ der_free_oid(&oid);
+ ret = ENOMEM;
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ goto out;
+ }
+ memcpy(r, pstr, pstr_len);
+ r[pstr_len] = '\0';
+
+ ret = _hx509_name_modify(context, &n->der_name, 0, &oid, r);
+ free(r);
+ der_free_oid(&oid);
+ if(ret)
+ goto out;
+ }
+ p += len + last;
+ }
+
+ *name = n;
+
+ return 0;
+out:
+ hx509_name_free(&n);
+ return HX509_NAME_MALFORMED;
+}
+
+/**
+ * Copy a hx509 name object.
+ *
+ * @param context A hx509 cotext.
+ * @param from the name to copy from
+ * @param to the name to copy to
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_name
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_name_copy(hx509_context context, const hx509_name from, hx509_name *to)
+{
+ int ret;
+
+ *to = calloc(1, sizeof(**to));
+ if (*to == NULL)
+ return ENOMEM;
+ ret = copy_Name(&from->der_name, &(*to)->der_name);
+ if (ret) {
+ free(*to);
+ *to = NULL;
+ return ENOMEM;
+ }
+ return 0;
+}
+
+/**
+ * Convert a hx509_name into a Name.
+ *
+ * @param from the name to copy from
+ * @param to the name to copy to
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_name
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_name_to_Name(const hx509_name from, Name *to)
+{
+ return copy_Name(&from->der_name, to);
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_name_normalize(hx509_context context, hx509_name name)
+{
+ return 0;
+}
+
+/**
+ * Expands variables in the name using env. Variables are on the form
+ * ${name}. Useful when dealing with certificate templates.
+ *
+ * @param context A hx509 cotext.
+ * @param name the name to expand.
+ * @param env environment variable to expand.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_name
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_name_expand(hx509_context context,
+ hx509_name name,
+ hx509_env env)
+{
+ Name *n = &name->der_name;
+ size_t i, j;
+ int bounds_check = 1;
+
+ if (env == NULL)
+ return 0;
+
+ if (n->element != choice_Name_rdnSequence) {
+ hx509_set_error_string(context, 0, EINVAL, "RDN not of supported type");
+ return EINVAL;
+ }
+
+ for (i = 0 ; i < n->u.rdnSequence.len; i++) {
+ for (j = 0; j < n->u.rdnSequence.val[i].len; j++) {
+ /** Only UTF8String rdnSequence names are allowed */
+ /*
+ THIS SHOULD REALLY BE:
+ COMP = n->u.rdnSequence.val[i].val[j];
+ normalize COMP to utf8
+ check if there are variables
+ expand variables
+ convert back to orignal format, store in COMP
+ free normalized utf8 string
+ */
+ DirectoryString *ds = &n->u.rdnSequence.val[i].val[j].value;
+ heim_oid *type = &n->u.rdnSequence.val[i].val[j].type;
+ const char *sval = NULL;
+ char *p, *p2;
+ char *s = NULL;
+ struct rk_strpool *strpool = NULL;
+
+ switch (ds->element) {
+ case choice_DirectoryString_utf8String:
+ sval = ds->u.utf8String;
+ break;
+ case choice_DirectoryString_teletexString:
+ sval = ds->u.utf8String;
+ break;
+ case choice_DirectoryString_ia5String:
+ s = strndup(ds->u.ia5String.data,
+ ds->u.ia5String.length);
+ break;
+ case choice_DirectoryString_printableString:
+ s = strndup(ds->u.printableString.data,
+ ds->u.printableString.length);
+ break;
+ case choice_DirectoryString_universalString:
+ hx509_set_error_string(context, 0, ENOTSUP, "UniversalString not supported");
+ return ENOTSUP;
+ case choice_DirectoryString_bmpString:
+ hx509_set_error_string(context, 0, ENOTSUP, "BMPString not supported");
+ return ENOTSUP;
+ }
+ if (sval == NULL && s == NULL)
+ return hx509_enomem(context);
+ if (s)
+ sval = s;
+
+ p = strstr(sval, "${");
+ if (p) {
+ strpool = rk_strpoolprintf(strpool, "%.*s", (int)(p - sval), sval);
+ if (strpool == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ free(s);
+ return ENOMEM;
+ }
+ }
+
+ while (p != NULL) {
+ /* expand variables */
+ const char *value;
+ p2 = strchr(p, '}');
+ if (p2 == NULL) {
+ hx509_set_error_string(context, 0, EINVAL, "missing }");
+ rk_strpoolfree(strpool);
+ free(s);
+ return EINVAL;
+ }
+ p += 2;
+ value = hx509_env_lfind(context, env, p, p2 - p);
+ if (value == NULL) {
+ hx509_set_error_string(context, 0, EINVAL,
+ "variable %.*s missing",
+ (int)(p2 - p), p);
+ rk_strpoolfree(strpool);
+ free(s);
+ return EINVAL;
+ }
+ strpool = rk_strpoolprintf(strpool, "%s", value);
+ if (strpool == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ free(s);
+ return ENOMEM;
+ }
+ p2++;
+
+ p = strstr(p2, "${");
+ if (p)
+ strpool = rk_strpoolprintf(strpool, "%.*s",
+ (int)(p - p2), p2);
+ else
+ strpool = rk_strpoolprintf(strpool, "%s", p2);
+ if (strpool == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ free(s);
+ return ENOMEM;
+ }
+ }
+
+ free(s);
+ s = NULL;
+
+ if (strpool) {
+ size_t max_bytes;
+
+ if ((s = rk_strpoolcollect(strpool)) == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ /* Check upper bounds! */
+ if ((max_bytes = oidtomaxlen(type)) && strlen(s) > max_bytes)
+ bounds_check = 0;
+
+ switch (ds->element) {
+ /* C strings: */
+ case choice_DirectoryString_utf8String:
+ free(ds->u.utf8String);
+ ds->u.utf8String = s;
+ break;
+ case choice_DirectoryString_teletexString:
+ free(ds->u.teletexString);
+ ds->u.teletexString = s;
+ break;
+
+ /* Length and pointer */
+ case choice_DirectoryString_ia5String:
+ free(ds->u.ia5String.data);
+ ds->u.ia5String.data = s;
+ ds->u.ia5String.length = strlen(s);
+ break;
+ case choice_DirectoryString_printableString:
+ free(ds->u.printableString.data);
+ ds->u.printableString.data = s;
+ ds->u.printableString.length = strlen(s);
+ break;
+ default:
+ break; /* Handled above */
+ }
+ }
+ }
+ }
+
+ if (!bounds_check) {
+ hx509_set_error_string(context, 0, HX509_PARSING_NAME_FAILED,
+ "some expanded RDNs are too long");
+ return HX509_PARSING_NAME_FAILED;
+ }
+ return 0;
+}
+
+/**
+ * Free a hx509 name object, upond return *name will be NULL.
+ *
+ * @param name a hx509 name object to be freed.
+ *
+ * @ingroup hx509_name
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_name_free(hx509_name *name)
+{
+ free_Name(&(*name)->der_name);
+ memset(*name, 0, sizeof(**name));
+ free(*name);
+ *name = NULL;
+}
+
+/**
+ * Convert a DER encoded name info a string.
+ *
+ * @param data data to a DER/BER encoded name
+ * @param length length of data
+ * @param str the resulting string, is NULL on failure.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_name
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_unparse_der_name(const void *data, size_t length, char **str)
+{
+ Name name;
+ int ret;
+
+ *str = NULL;
+
+ ret = decode_Name(data, length, &name, NULL);
+ if (ret)
+ return ret;
+ ret = _hx509_Name_to_string(&name, str);
+ free_Name(&name);
+ return ret;
+}
+
+/**
+ * Convert a hx509_name object to DER encoded name.
+ *
+ * @param name name to concert
+ * @param os data to a DER encoded name, free the resulting octet
+ * string with hx509_xfree(os->data).
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_name
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_name_binary(const hx509_name name, heim_octet_string *os)
+{
+ size_t size;
+ int ret;
+
+ ASN1_MALLOC_ENCODE(Name, os->data, os->length, &name->der_name, &size, ret);
+ if (ret)
+ return ret;
+ if (os->length != size)
+ _hx509_abort("internal ASN.1 encoder error");
+
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_unparse_Name(const Name *aname, char **str)
+{
+ hx509_name name;
+ int ret;
+
+ ret = _hx509_name_from_Name(aname, &name);
+ if (ret)
+ return ret;
+
+ ret = hx509_name_to_string(name, str);
+ hx509_name_free(&name);
+ return ret;
+}
+
+/**
+ * Check if a name is empty.
+ *
+ * @param name the name to check if its empty/null.
+ *
+ * @return non zero if the name is empty/null.
+ *
+ * @ingroup hx509_name
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_name_is_null_p(const hx509_name name)
+{
+ return name->der_name.element == choice_Name_rdnSequence &&
+ name->der_name.u.rdnSequence.len == 0;
+}
+
+int
+_hx509_unparse_PermanentIdentifier(hx509_context context,
+ struct rk_strpool **strpool,
+ heim_any *value)
+{
+ PermanentIdentifier pi;
+ size_t len;
+ const char *pid = "";
+ char *s = NULL;
+ int ret;
+
+ ret = decode_PermanentIdentifier(value->data, value->length, &pi, &len);
+ if (ret == 0 && pi.assigner &&
+ der_print_heim_oid(pi.assigner, '.', &s) != 0)
+ ret = hx509_enomem(context);
+ if (pi.identifierValue && *pi.identifierValue)
+ pid = *pi.identifierValue;
+ if (ret == 0 &&
+ (*strpool = rk_strpoolprintf(*strpool, "%s:%s", s ? s : "", pid)) == NULL)
+ ret = hx509_enomem(context);
+ free_PermanentIdentifier(&pi);
+ free(s);
+ if (ret) {
+ rk_strpoolfree(*strpool);
+ *strpool = rk_strpoolprintf(NULL,
+ "<error-decoding-PermanentIdentifier");
+ hx509_set_error_string(context, 0, ret,
+ "Failed to decode PermanentIdentifier");
+ }
+ return ret;
+}
+
+int
+_hx509_unparse_HardwareModuleName(hx509_context context,
+ struct rk_strpool **strpool,
+ heim_any *value)
+{
+ HardwareModuleName hm;
+ size_t len;
+ char *s = NULL;
+ int ret;
+
+ ret = decode_HardwareModuleName(value->data, value->length, &hm, &len);
+ if (ret == 0 && hm.hwSerialNum.length > 256)
+ hm.hwSerialNum.length = 256;
+ if (ret == 0)
+ ret = der_print_heim_oid(&hm.hwType, '.', &s);
+ if (ret == 0) {
+ *strpool = rk_strpoolprintf(*strpool, "%s:%.*s%s", s,
+ (int)hm.hwSerialNum.length,
+ (char *)hm.hwSerialNum.data,
+ value->length == len ? "" : ", <garbage>");
+ if (*strpool == NULL)
+ ret = hx509_enomem(context);
+ }
+ free_HardwareModuleName(&hm);
+ free(s);
+ if (ret) {
+ rk_strpoolfree(*strpool);
+ *strpool = rk_strpoolprintf(NULL,
+ "<error-decoding-HardwareModuleName");
+ hx509_set_error_string(context, 0, ret,
+ "Failed to decode HardwareModuleName");
+ }
+ return ret;
+}
+
+/*
+ * This necessarily duplicates code from libkrb5, and has to unless we move
+ * common code here or to lib/roken for it. We do have slightly different
+ * needs (e.g., we want space quoted, and we want to indicate whether we saw
+ * trailing garbage, we have no need for flags, no special realm treatment,
+ * etc) than the corresponding code in libkrb5, so for now we duplicate this
+ * code.
+ *
+ * The relevant RFCs here are RFC1964 for the string representation of Kerberos
+ * principal names, and RFC4556 for the KRB5PrincipalName ASN.1 type (Kerberos
+ * lacks such a type because on the wire the name and realm are sent
+ * separately as a form of cheap compression).
+ *
+ * Note that we cannot handle embedded NULs because of Heimdal's representation
+ * of ASN.1 strings as C strings.
+ */
+int
+_hx509_unparse_KRB5PrincipalName(hx509_context context,
+ struct rk_strpool **strpool,
+ heim_any *value)
+{
+ KRB5PrincipalName kn;
+ size_t len;
+ int ret;
+
+ ret = decode_KRB5PrincipalName(value->data, value->length, &kn, &len);
+ if (ret == 0 &&
+ (*strpool = _hx509_unparse_kerberos_name(*strpool, &kn)) == NULL)
+ ret = hx509_enomem(context);
+ free_KRB5PrincipalName(&kn);
+ if (ret == 0 && (value->length != len) &&
+ (*strpool = rk_strpoolprintf(*strpool, " <garbage>")) == NULL)
+ ret = hx509_enomem(context);
+ if (ret) {
+ rk_strpoolfree(*strpool);
+ *strpool = rk_strpoolprintf(NULL,
+ "<error-decoding-PrincipalName");
+ hx509_set_error_string(context, 0, ret,
+ "Failed to decode PermanentIdentifier");
+ }
+ return ret;
+}
+
+struct rk_strpool *
+_hx509_unparse_kerberos_name(struct rk_strpool *strpool, KRB5PrincipalName *kn)
+{
+ static const char comp_quotable_chars[] = " \n\t\b\\/@";
+ static const char realm_quotable_chars[] = " \n\t\b\\@";
+ const char *s;
+ size_t i, k, len, plen;
+ int need_slash = 0;
+
+ for (i = 0; i < kn->principalName.name_string.len; i++) {
+ s = kn->principalName.name_string.val[i];
+ len = strlen(s);
+
+ if (need_slash)
+ strpool = rk_strpoolprintf(strpool, "/");
+ need_slash = 1;
+
+ for (k = 0; k < len; s += plen, k += plen) {
+ char c;
+
+ plen = strcspn(s, comp_quotable_chars);
+ if (plen)
+ strpool = rk_strpoolprintf(strpool, "%.*s", (int)plen, s);
+ if (k + plen >= len)
+ continue;
+ switch ((c = s[plen++])) {
+ case '\n': strpool = rk_strpoolprintf(strpool, "\\n"); break;
+ case '\t': strpool = rk_strpoolprintf(strpool, "\\t"); break;
+ case '\b': strpool = rk_strpoolprintf(strpool, "\\b"); break;
+ /* default -> '@', ' ', '\\', or '/' */
+ default: strpool = rk_strpoolprintf(strpool, "\\%c", c); break;
+ }
+ }
+ }
+ if (!kn->realm)
+ return strpool;
+ strpool = rk_strpoolprintf(strpool, "@");
+
+ s = kn->realm;
+ len = strlen(kn->realm);
+ for (k = 0; k < len; s += plen, k += plen) {
+ char c;
+
+ plen = strcspn(s, realm_quotable_chars);
+ if (plen)
+ strpool = rk_strpoolprintf(strpool, "%.*s", (int)plen, s);
+ if (k + plen >= len)
+ continue;
+ switch ((c = s[plen++])) {
+ case '\n': strpool = rk_strpoolprintf(strpool, "\\n"); break;
+ case '\t': strpool = rk_strpoolprintf(strpool, "\\t"); break;
+ case '\b': strpool = rk_strpoolprintf(strpool, "\\b"); break;
+ /* default -> '@', ' ', or '\\' */
+ default: strpool = rk_strpoolprintf(strpool, "\\%c", c); break;
+ }
+ }
+ return strpool;
+}
+
+int
+_hx509_unparse_utf8_string_name(hx509_context context,
+ struct rk_strpool **strpool,
+ heim_any *value)
+{
+ PKIXXmppAddr us;
+ size_t size;
+ int ret;
+
+ ret = decode_PKIXXmppAddr(value->data, value->length, &us, &size);
+ if (ret == 0 &&
+ (*strpool = rk_strpoolprintf(*strpool, "%s", us)) == NULL)
+ ret = hx509_enomem(context);
+ if (ret) {
+ rk_strpoolfree(*strpool);
+ *strpool = rk_strpoolprintf(NULL,
+ "<error-decoding-UTF8String-SAN>");
+ hx509_set_error_string(context, 0, ret,
+ "Failed to decode UTF8String SAN");
+ }
+ free_PKIXXmppAddr(&us);
+ return ret;
+}
+
+int
+_hx509_unparse_ia5_string_name(hx509_context context,
+ struct rk_strpool **strpool,
+ heim_any *value)
+{
+ SRVName us;
+ size_t size;
+ int ret;
+
+ ret = decode_SRVName(value->data, value->length, &us, &size);
+ if (ret == 0) {
+ rk_strpoolfree(*strpool);
+ *strpool = rk_strpoolprintf(NULL,
+ "<error-decoding-IA5String-SAN>");
+ hx509_set_error_string(context, 0, ret,
+ "Failed to decode UTF8String SAN");
+ return ret;
+ }
+ *strpool = rk_strpoolprintf(*strpool, "%.*s",
+ (int)us.length, (char *)us.data);
+ free_SRVName(&us);
+ return ret;
+}
+
+typedef int (*other_unparser_f)(hx509_context,
+ struct rk_strpool **,
+ heim_any *);
+
+struct {
+ const heim_oid *oid;
+ const char *friendly_name;
+ other_unparser_f f;
+} o_unparsers[] = {
+ { &asn1_oid_id_pkinit_san,
+ "KerberosPrincipalName",
+ _hx509_unparse_KRB5PrincipalName },
+ { &asn1_oid_id_pkix_on_permanentIdentifier,
+ "PermanentIdentifier",
+ _hx509_unparse_PermanentIdentifier },
+ { &asn1_oid_id_on_hardwareModuleName,
+ "HardwareModuleName",
+ _hx509_unparse_HardwareModuleName },
+ { &asn1_oid_id_pkix_on_xmppAddr,
+ "XMPPName",
+ _hx509_unparse_utf8_string_name },
+ { &asn1_oid_id_pkinit_ms_san,
+ "MSFTKerberosPrincipalName",
+ _hx509_unparse_utf8_string_name },
+ { &asn1_oid_id_pkix_on_dnsSRV,
+ "SRVName",
+ _hx509_unparse_ia5_string_name },
+};
+
+/**
+ * Unparse the hx509 name in name into a string.
+ *
+ * @param name the name to print
+ * @param str an allocated string returns the name in string form
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_name
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_general_name_unparse(GeneralName *name, char **str)
+{
+ hx509_context context;
+ int ret;
+
+ if ((ret = hx509_context_init(&context)))
+ return ret;
+ ret = hx509_general_name_unparse2(context, name, str);
+ hx509_context_free(&context);
+ return ret;
+}
+
+/**
+ * Unparse the hx509 name in name into a string.
+ *
+ * @param context hx509 library context
+ * @param name the name to print
+ * @param str an allocated string returns the name in string form
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_name
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_general_name_unparse2(hx509_context context,
+ GeneralName *name,
+ char **str)
+{
+ struct rk_strpool *strpool = NULL;
+ int ret = 0;
+
+ *str = NULL;
+
+ switch (name->element) {
+ case choice_GeneralName_otherName: {
+ size_t i;
+ char *oid;
+
+ ret = hx509_oid_sprint(&name->u.otherName.type_id, &oid);
+ if (ret == 0)
+ strpool = rk_strpoolprintf(strpool, "otherName: %s ", oid);
+ if (strpool == NULL)
+ ret = ENOMEM;
+
+ for (i = 0; ret == 0 && i < sizeof(o_unparsers)/sizeof(o_unparsers[0]); i++) {
+ if (der_heim_oid_cmp(&name->u.otherName.type_id,
+ o_unparsers[i].oid))
+ continue;
+ strpool = rk_strpoolprintf(strpool, "%s ",o_unparsers[i].friendly_name);
+ if (strpool == NULL)
+ ret = ENOMEM;
+ if (ret == 0)
+ ret = o_unparsers[i].f(context, &strpool, &name->u.otherName.value);
+ break;
+ }
+ if (ret == 0 && i == sizeof(o_unparsers)/sizeof(o_unparsers[0])) {
+ strpool = rk_strpoolprintf(strpool, "<unknown-other-name-type>");
+ ret = ENOTSUP;
+ }
+ free(oid);
+ break;
+ }
+ case choice_GeneralName_rfc822Name:
+ strpool = rk_strpoolprintf(strpool, "rfc822Name: %.*s",
+ (int)name->u.rfc822Name.length,
+ (char *)name->u.rfc822Name.data);
+ break;
+ case choice_GeneralName_dNSName:
+ strpool = rk_strpoolprintf(strpool, "dNSName: %.*s",
+ (int)name->u.dNSName.length,
+ (char *)name->u.dNSName.data);
+ break;
+ case choice_GeneralName_directoryName: {
+ Name dir;
+ char *s;
+ memset(&dir, 0, sizeof(dir));
+ dir.element = (enum Name_enum)name->u.directoryName.element;
+ dir.u.rdnSequence = name->u.directoryName.u.rdnSequence;
+ ret = _hx509_unparse_Name(&dir, &s);
+ if (ret)
+ return ret;
+ strpool = rk_strpoolprintf(strpool, "directoryName: %s", s);
+ free(s);
+ break;
+ }
+ case choice_GeneralName_uniformResourceIdentifier:
+ strpool = rk_strpoolprintf(strpool, "URI: %.*s",
+ (int)name->u.uniformResourceIdentifier.length,
+ (char *)name->u.uniformResourceIdentifier.data);
+ break;
+ case choice_GeneralName_iPAddress: {
+ unsigned char *a = name->u.iPAddress.data;
+
+ strpool = rk_strpoolprintf(strpool, "IPAddress: ");
+ if (strpool == NULL)
+ break;
+ if (name->u.iPAddress.length == 4)
+ strpool = rk_strpoolprintf(strpool, "%d.%d.%d.%d",
+ a[0], a[1], a[2], a[3]);
+ else if (name->u.iPAddress.length == 16)
+ strpool = rk_strpoolprintf(strpool,
+ "%02X:%02X:%02X:%02X:"
+ "%02X:%02X:%02X:%02X:"
+ "%02X:%02X:%02X:%02X:"
+ "%02X:%02X:%02X:%02X",
+ a[0], a[1], a[2], a[3],
+ a[4], a[5], a[6], a[7],
+ a[8], a[9], a[10], a[11],
+ a[12], a[13], a[14], a[15]);
+ else
+ strpool = rk_strpoolprintf(strpool,
+ "unknown IP address of length %lu",
+ (unsigned long)name->u.iPAddress.length);
+ break;
+ }
+ case choice_GeneralName_registeredID: {
+ char *oid;
+ hx509_oid_sprint(&name->u.registeredID, &oid);
+ if (oid == NULL)
+ return ENOMEM;
+ strpool = rk_strpoolprintf(strpool, "registeredID: %s", oid);
+ free(oid);
+ break;
+ }
+ default:
+ return EINVAL;
+ }
+ if (ret)
+ rk_strpoolfree(strpool);
+ else if (strpool == NULL || (*str = rk_strpoolcollect(strpool)) == NULL)
+ return ENOMEM;
+ return ret;
+}
diff --git a/third_party/heimdal/lib/hx509/peer.c b/third_party/heimdal/lib/hx509/peer.c
new file mode 100644
index 0000000..2501f01
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/peer.c
@@ -0,0 +1,237 @@
+/*
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+/**
+ * @page page_peer Hx509 crypto selecting functions
+ *
+ * Peer info structures are used togeter with hx509_crypto_select() to
+ * select the best avaible crypto algorithm to use.
+ *
+ * See the library functions here: @ref hx509_peer
+ */
+
+/**
+ * Allocate a new peer info structure an init it to default values.
+ *
+ * @param context A hx509 context.
+ * @param peer return an allocated peer, free with hx509_peer_info_free().
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_peer
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_peer_info_alloc(hx509_context context, hx509_peer_info *peer)
+{
+ *peer = calloc(1, sizeof(**peer));
+ if (*peer == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+ return 0;
+}
+
+
+static void
+free_cms_alg(hx509_peer_info peer)
+{
+ if (peer->val) {
+ size_t i;
+ for (i = 0; i < peer->len; i++)
+ free_AlgorithmIdentifier(&peer->val[i]);
+ free(peer->val);
+ peer->val = NULL;
+ peer->len = 0;
+ }
+}
+
+/**
+ * Free a peer info structure.
+ *
+ * @param peer peer info to be freed.
+ *
+ * @ingroup hx509_peer
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_peer_info_free(hx509_peer_info peer)
+{
+ if (peer == NULL)
+ return;
+ if (peer->cert)
+ hx509_cert_free(peer->cert);
+ free_cms_alg(peer);
+ memset(peer, 0, sizeof(*peer));
+ free(peer);
+}
+
+/**
+ * Set the certificate that remote peer is using.
+ *
+ * @param peer peer info to update
+ * @param cert cerificate of the remote peer.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_peer
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_peer_info_set_cert(hx509_peer_info peer,
+ hx509_cert cert)
+{
+ if (peer->cert)
+ hx509_cert_free(peer->cert);
+ peer->cert = hx509_cert_ref(cert);
+ return 0;
+}
+
+/**
+ * Add an additional algorithm that the peer supports.
+ *
+ * @param context A hx509 context.
+ * @param peer the peer to set the new algorithms for
+ * @param val an AlgorithmsIdentier to add
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_peer
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_peer_info_add_cms_alg(hx509_context context,
+ hx509_peer_info peer,
+ const AlgorithmIdentifier *val)
+{
+ void *ptr;
+ int ret;
+
+ ptr = realloc(peer->val, sizeof(peer->val[0]) * (peer->len + 1));
+ if (ptr == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+ peer->val = ptr;
+ ret = copy_AlgorithmIdentifier(val, &peer->val[peer->len]);
+ if (ret == 0)
+ peer->len += 1;
+ else
+ hx509_set_error_string(context, 0, ret, "out of memory");
+ return ret;
+}
+
+/**
+ * Set the algorithms that the peer supports.
+ *
+ * @param context A hx509 context.
+ * @param peer the peer to set the new algorithms for
+ * @param val array of supported AlgorithmsIdentiers
+ * @param len length of array val.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_peer
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_peer_info_set_cms_algs(hx509_context context,
+ hx509_peer_info peer,
+ const AlgorithmIdentifier *val,
+ size_t len)
+{
+ size_t i;
+
+ free_cms_alg(peer);
+
+ peer->val = calloc(len, sizeof(*peer->val));
+ if (peer->val == NULL) {
+ peer->len = 0;
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+ peer->len = len;
+ for (i = 0; i < len; i++) {
+ int ret;
+ ret = copy_AlgorithmIdentifier(&val[i], &peer->val[i]);
+ if (ret) {
+ hx509_clear_error_string(context);
+ free_cms_alg(peer);
+ return ret;
+ }
+ }
+ return 0;
+}
+
+#if 0
+
+/*
+ * S/MIME
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_peer_info_parse_smime(hx509_peer_info peer,
+ const heim_octet_string *data)
+{
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_peer_info_unparse_smime(hx509_peer_info peer,
+ heim_octet_string *data)
+{
+ return 0;
+}
+
+/*
+ * For storing hx509_peer_info to be able to cache them.
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_peer_info_parse(hx509_peer_info peer,
+ const heim_octet_string *data)
+{
+ return 0;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_peer_info_unparse(hx509_peer_info peer,
+ heim_octet_string *data)
+{
+ return 0;
+}
+#endif
diff --git a/third_party/heimdal/lib/hx509/print.c b/third_party/heimdal/lib/hx509/print.c
new file mode 100644
index 0000000..3309913
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/print.c
@@ -0,0 +1,1144 @@
+/*
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+#include <vis.h>
+#include <vis-extras.h>
+
+/**
+ * @page page_print Hx509 printing functions
+ *
+ * See the library functions here: @ref hx509_print
+ */
+
+struct hx509_validate_ctx_data {
+ hx509_context context;
+ int flags;
+ hx509_vprint_func vprint_func;
+ void *ctx;
+};
+
+struct cert_status {
+ unsigned int selfsigned:1;
+ unsigned int isca:1;
+ unsigned int isproxy:1;
+ unsigned int haveSAN:1;
+ unsigned int haveIAN:1;
+ unsigned int haveSKI:1;
+ unsigned int haveAKI:1;
+ unsigned int haveCRLDP:1;
+};
+
+
+/*
+ *
+ */
+
+static int
+Time2string(const Time *T, char **str)
+{
+ time_t t;
+ char *s;
+ struct tm *tm;
+
+ *str = NULL;
+ t = _hx509_Time2time_t(T);
+ tm = gmtime (&t);
+ s = malloc(30);
+ if (s == NULL)
+ return ENOMEM;
+ strftime(s, 30, "%Y-%m-%d %H:%M:%S", tm);
+ *str = s;
+ return 0;
+}
+
+/**
+ * Helper function to print on stdout for:
+ * - hx509_oid_print(),
+ * - hx509_bitstring_print(),
+ * - hx509_validate_ctx_set_print().
+ *
+ * @param ctx the context to the print function. If the ctx is NULL,
+ * stdout is used.
+ * @param fmt the printing format.
+ * @param va the argumet list.
+ *
+ * @ingroup hx509_print
+ */
+
+HX509_LIB_FUNCTION void
+hx509_print_stdout(void *ctx, const char *fmt, va_list va)
+{
+ FILE *f = ctx;
+ if (f == NULL)
+ f = stdout;
+ vfprintf(f, fmt, va);
+}
+
+static void
+print_func(hx509_vprint_func func, void *ctx, const char *fmt, ...)
+{
+ va_list va;
+ va_start(va, fmt);
+ (*func)(ctx, fmt, va);
+ va_end(va);
+}
+
+/**
+ * Print a oid to a string.
+ *
+ * @param oid oid to print
+ * @param str allocated string, free with hx509_xfree().
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_print
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_oid_sprint(const heim_oid *oid, char **str)
+{
+ return der_print_heim_oid(oid, '.', str);
+}
+
+/**
+ * Print a oid using a hx509_vprint_func function. To print to stdout
+ * use hx509_print_stdout().
+ *
+ * @param oid oid to print
+ * @param func hx509_vprint_func to print with.
+ * @param ctx context variable to hx509_vprint_func function.
+ *
+ * @ingroup hx509_print
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_oid_print(const heim_oid *oid, hx509_vprint_func func, void *ctx)
+{
+ char *str;
+ hx509_oid_sprint(oid, &str);
+ print_func(func, ctx, "%s", str);
+ free(str);
+}
+
+/**
+ * Print a bitstring using a hx509_vprint_func function. To print to
+ * stdout use hx509_print_stdout().
+ *
+ * @param b bit string to print.
+ * @param func hx509_vprint_func to print with.
+ * @param ctx context variable to hx509_vprint_func function.
+ *
+ * @ingroup hx509_print
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_bitstring_print(const heim_bit_string *b,
+ hx509_vprint_func func, void *ctx)
+{
+ size_t i;
+ print_func(func, ctx, "\tlength: %d\n\t", b->length);
+ for (i = 0; i < (b->length + 7) / 8; i++)
+ print_func(func, ctx, "%02x%s%s",
+ ((unsigned char *)b->data)[i],
+ i < (b->length - 7) / 8
+ && (i == 0 || (i % 16) != 15) ? ":" : "",
+ i != 0 && (i % 16) == 15 ?
+ (i <= ((b->length + 7) / 8 - 2) ? "\n\t" : "\n"):"");
+}
+
+/**
+ * Print certificate usage for a certificate to a string.
+ *
+ * @param context A hx509 context.
+ * @param c a certificate print the keyusage for.
+ * @param s the return string with the keysage printed in to, free
+ * with hx509_xfree().
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_print
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_cert_keyusage_print(hx509_context context, hx509_cert c, char **s)
+{
+ KeyUsage ku;
+ char buf[256];
+ int ret;
+
+ *s = NULL;
+
+ ret = _hx509_cert_get_keyusage(context, c, &ku);
+ if (ret)
+ return ret;
+ unparse_flags(KeyUsage2int(ku), asn1_KeyUsage_units(), buf, sizeof(buf));
+ *s = strdup(buf);
+ if (*s == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ return 0;
+}
+
+/*
+ *
+ */
+
+static void
+validate_vprint(void *c, const char *fmt, va_list va)
+{
+ hx509_validate_ctx ctx = c;
+ if (ctx->vprint_func == NULL)
+ return;
+ (ctx->vprint_func)(ctx->ctx, fmt, va);
+}
+
+static void
+validate_print(hx509_validate_ctx ctx, int flags, const char *fmt, ...)
+{
+ va_list va;
+ if ((ctx->flags & flags) == 0)
+ return;
+ va_start(va, fmt);
+ validate_vprint(ctx, fmt, va);
+ va_end(va);
+}
+
+/*
+ * Don't Care, SHOULD critical, SHOULD NOT critical, MUST critical,
+ * MUST NOT critical
+ */
+enum critical_flag { D_C = 0, S_C, S_N_C, M_C, M_N_C };
+
+static int
+check_Null(hx509_validate_ctx ctx,
+ struct cert_status *status,
+ enum critical_flag cf, const Extension *e)
+{
+ switch(cf) {
+ case D_C:
+ break;
+ case S_C:
+ if (!e->critical)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "\tCritical not set on SHOULD\n");
+ break;
+ case S_N_C:
+ if (e->critical)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "\tCritical set on SHOULD NOT\n");
+ break;
+ case M_C:
+ if (!e->critical)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "\tCritical not set on MUST\n");
+ break;
+ case M_N_C:
+ if (e->critical)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "\tCritical set on MUST NOT\n");
+ break;
+ default:
+ _hx509_abort("internal check_Null state error");
+ }
+ return 0;
+}
+
+static int
+check_subjectKeyIdentifier(hx509_validate_ctx ctx,
+ struct cert_status *status,
+ enum critical_flag cf,
+ const Extension *e)
+{
+ SubjectKeyIdentifier si;
+ size_t size;
+ int ret;
+
+ status->haveSKI = 1;
+ check_Null(ctx, status, cf, e);
+
+ ret = decode_SubjectKeyIdentifier(e->extnValue.data,
+ e->extnValue.length,
+ &si, &size);
+ if (ret) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Decoding SubjectKeyIdentifier failed: %d", ret);
+ return 1;
+ }
+ if (size != e->extnValue.length) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Decoding SKI ahve extra bits on the end");
+ return 1;
+ }
+ if (si.length == 0)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "SKI is too short (0 bytes)");
+ if (si.length > 20)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "SKI is too long");
+
+ {
+ char *id;
+ hex_encode(si.data, si.length, &id);
+ if (id) {
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "\tsubject key id: %s\n", id);
+ free(id);
+ }
+ }
+
+ free_SubjectKeyIdentifier(&si);
+
+ return 0;
+}
+
+static int
+check_authorityKeyIdentifier(hx509_validate_ctx ctx,
+ struct cert_status *status,
+ enum critical_flag cf,
+ const Extension *e)
+{
+ AuthorityKeyIdentifier ai;
+ size_t size;
+ int ret;
+
+ status->haveAKI = 1;
+ check_Null(ctx, status, cf, e);
+
+ ret = decode_AuthorityKeyIdentifier(e->extnValue.data,
+ e->extnValue.length,
+ &ai, &size);
+ if (ret) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Decoding AuthorityKeyIdentifier failed: %d", ret);
+ return 1;
+ }
+ if (size != e->extnValue.length) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Decoding SKI ahve extra bits on the end");
+ return 1;
+ }
+
+ if (ai.keyIdentifier) {
+ char *id;
+ hex_encode(ai.keyIdentifier->data, ai.keyIdentifier->length, &id);
+ if (id) {
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "\tauthority key id: %s\n", id);
+ free(id);
+ }
+ }
+
+ free_AuthorityKeyIdentifier(&ai);
+ return 0;
+}
+
+static int
+check_extKeyUsage(hx509_validate_ctx ctx,
+ struct cert_status *status,
+ enum critical_flag cf,
+ const Extension *e)
+{
+ ExtKeyUsage eku;
+ size_t size, i;
+ int ret;
+
+ check_Null(ctx, status, cf, e);
+
+ ret = decode_ExtKeyUsage(e->extnValue.data,
+ e->extnValue.length,
+ &eku, &size);
+ if (ret) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Decoding ExtKeyUsage failed: %d", ret);
+ return 1;
+ }
+ if (size != e->extnValue.length) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Padding data in EKU");
+ free_ExtKeyUsage(&eku);
+ return 1;
+ }
+ if (eku.len == 0) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "ExtKeyUsage length is 0");
+ return 1;
+ }
+
+ for (i = 0; i < eku.len; i++) {
+ char *str;
+ ret = der_print_heim_oid (&eku.val[i], '.', &str);
+ if (ret) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "\tEKU: failed to print oid %d", i);
+ free_ExtKeyUsage(&eku);
+ return 1;
+ }
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "\teku-%d: %s\n", i, str);;
+ free(str);
+ }
+
+ free_ExtKeyUsage(&eku);
+
+ return 0;
+}
+
+static int
+check_CRLDistributionPoints(hx509_validate_ctx ctx,
+ struct cert_status *status,
+ enum critical_flag cf,
+ const Extension *e)
+{
+ CRLDistributionPoints dp;
+ size_t size;
+ int ret;
+ size_t i;
+
+ check_Null(ctx, status, cf, e);
+
+ ret = decode_CRLDistributionPoints(e->extnValue.data,
+ e->extnValue.length,
+ &dp, &size);
+ if (ret) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Decoding CRL Distribution Points failed: %d\n", ret);
+ return 1;
+ }
+
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "CRL Distribution Points:\n");
+ for (i = 0 ; i < dp.len; i++) {
+ if (dp.val[i].distributionPoint) {
+ DistributionPointName dpname = dp.val[i].distributionPoint[0];
+ size_t j;
+
+ switch (dpname.element) {
+ case choice_DistributionPointName_fullName:
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "Fullname:\n");
+
+ for (j = 0 ; j < dpname.u.fullName.len; j++) {
+ char *s;
+ GeneralName *name = &dpname.u.fullName.val[j];
+
+ ret = hx509_general_name_unparse2(ctx->context, name, &s);
+ if (ret) {
+ s = hx509_get_error_string(ctx->context, ret);
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Unknown DistributionPointName: %s", s);
+ hx509_free_error_string(s);
+ } else {
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE, " %s\n", s);
+ free(s);
+ }
+ }
+ break;
+ case choice_DistributionPointName_nameRelativeToCRLIssuer:
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "Unknown nameRelativeToCRLIssuer");
+ break;
+ default:
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Unknown DistributionPointName");
+ break;
+ }
+ }
+ }
+ free_CRLDistributionPoints(&dp);
+
+ status->haveCRLDP = 1;
+
+ return 0;
+}
+
+static int
+check_altName(hx509_validate_ctx ctx,
+ struct cert_status *status,
+ const char *name,
+ enum critical_flag cf,
+ const Extension *e)
+{
+ GeneralNames gn;
+ size_t size;
+ int ret;
+ size_t i;
+
+ check_Null(ctx, status, cf, e);
+
+ if (e->extnValue.length == 0) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "%sAltName empty, not allowed", name);
+ return 1;
+ }
+ ret = decode_GeneralNames(e->extnValue.data, e->extnValue.length,
+ &gn, &size);
+ if (ret) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "\tret = %d while decoding %s GeneralNames\n",
+ ret, name);
+ return 1;
+ }
+ if (gn.len == 0) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "%sAltName generalName empty, not allowed\n", name);
+ return 1;
+ }
+
+ for (i = 0; i < gn.len; i++) {
+ char *s;
+
+ ret = hx509_general_name_unparse2(ctx->context, &gn.val[i], &s);
+ if (ret) {
+ s = hx509_get_error_string(ctx->context, ret);
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Error unparsing GeneralName: %s\n", s);
+ hx509_free_error_string(s);
+ return 1;
+ }
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\t%s\n", s);
+ free(s);
+ }
+
+ free_GeneralNames(&gn);
+ return 0;
+}
+
+static int
+check_subjectAltName(hx509_validate_ctx ctx,
+ struct cert_status *status,
+ enum critical_flag cf,
+ const Extension *e)
+{
+ status->haveSAN = 1;
+ return check_altName(ctx, status, "subject", cf, e);
+}
+
+static int
+check_issuerAltName(hx509_validate_ctx ctx,
+ struct cert_status *status,
+ enum critical_flag cf,
+ const Extension *e)
+{
+ status->haveIAN = 1;
+ return check_altName(ctx, status, "issuer", cf, e);
+}
+
+
+static int
+check_basicConstraints(hx509_validate_ctx ctx,
+ struct cert_status *status,
+ enum critical_flag cf,
+ const Extension *e)
+{
+ BasicConstraints b;
+ size_t size;
+ int ret;
+
+ check_Null(ctx, status, cf, e);
+
+ ret = decode_BasicConstraints(e->extnValue.data, e->extnValue.length,
+ &b, &size);
+ if (ret) {
+ printf("\tret = %d while decoding BasicConstraints\n", ret);
+ return 0;
+ }
+ if (size != e->extnValue.length)
+ printf("\tlength of der data isn't same as extension\n");
+
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "\tis %sa CA\n", b.cA ? "" : "NOT ");
+ if (b.pathLenConstraint)
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "\tpathLenConstraint: %d\n", *b.pathLenConstraint);
+
+ if (b.cA) {
+ if (!e->critical)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Is a CA and not BasicConstraints CRITICAL\n");
+ status->isca = 1;
+ }
+ free_BasicConstraints(&b);
+
+ return 0;
+}
+
+static int
+check_proxyCertInfo(hx509_validate_ctx ctx,
+ struct cert_status *status,
+ enum critical_flag cf,
+ const Extension *e)
+{
+ check_Null(ctx, status, cf, e);
+ status->isproxy = 1;
+ return 0;
+}
+
+static int
+check_authorityInfoAccess(hx509_validate_ctx ctx,
+ struct cert_status *status,
+ enum critical_flag cf,
+ const Extension *e)
+{
+ AuthorityInfoAccessSyntax aia;
+ size_t size;
+ int ret;
+ size_t i;
+
+ check_Null(ctx, status, cf, e);
+
+ ret = decode_AuthorityInfoAccessSyntax(e->extnValue.data,
+ e->extnValue.length,
+ &aia, &size);
+ if (ret) {
+ printf("\tret = %d while decoding AuthorityInfoAccessSyntax\n", ret);
+ return 0;
+ }
+
+ for (i = 0; i < aia.len; i++) {
+ char *str;
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "\ttype: ");
+ hx509_oid_print(&aia.val[i].accessMethod, validate_vprint, ctx);
+ ret = hx509_general_name_unparse2(ctx->context,
+ &aia.val[i].accessLocation, &str);
+ if (ret) {
+ str = hx509_get_error_string(ctx->context, ret);
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Error unparsing AuthorityInfoAccessSyntax "
+ "accessLocation: %s", str);
+ hx509_free_error_string(str);
+ } else {
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "\n\tdirname: %s\n", str);
+ free(str);
+ }
+ }
+ free_AuthorityInfoAccessSyntax(&aia);
+
+ return ret;
+}
+
+static int
+get_display_text(DisplayText *dt, char **out)
+{
+ int r = -1;
+
+ *out = NULL;
+
+ /*
+ * XXX We're cheating with various string types here.
+ *
+ * Proper support for IA5String is a real pain, and we don't have it.
+ *
+ * We also don't have support for BMPString.
+ */
+ switch (dt->element) {
+ case choice_DisplayText_ia5String:
+ r = rk_strasvisx(out, dt->u.ia5String.data, dt->u.ia5String.length,
+ VIS_CSTYLE | VIS_TAB | VIS_NL, "");
+ break;
+ case choice_DisplayText_visibleString:
+ r = rk_strasvis(out, dt->u.visibleString,
+ VIS_CSTYLE | VIS_TAB | VIS_NL, "");
+ break;
+ case choice_DisplayText_bmpString:
+ errno = ENOTSUP; /* XXX Need a UTF-16 -> UTF-8 conversion */
+ break;
+ case choice_DisplayText_utf8String:
+ r = rk_strasvis(out, dt->u.visibleString,
+ VIS_CSTYLE | VIS_TAB | VIS_NL, "");
+ break;
+ default:
+ errno = EINVAL;
+ }
+ return r < 0 ? errno : 0;
+}
+
+static int
+check_certificatePolicies(hx509_validate_ctx ctx,
+ struct cert_status *status,
+ enum critical_flag cf,
+ const Extension *e)
+{
+ CertificatePolicies cp;
+ size_t i, size;
+ int ret = 0;
+
+ check_Null(ctx, status, cf, e);
+
+ if (e->extnValue.length == 0) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "CertificatePolicies empty, not allowed");
+ return 1;
+ }
+ ret = decode_CertificatePolicies(e->extnValue.data, e->extnValue.length,
+ &cp, &size);
+ if (ret) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "\tret = %d while decoding CertificatePolicies\n", ret);
+ return 1;
+ }
+ if (cp.len == 0) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "CertificatePolicies empty, not allowed\n");
+ return 1;
+ }
+
+ for (i = 0; ret == 0 && i < cp.len; i++) {
+ size_t k;
+ char *poid = NULL;
+ char *qoid = NULL;
+ char *dt = NULL;
+
+ ret = der_print_heim_oid(&cp.val[i].policyIdentifier, '.', &poid);
+ if (ret == 0)
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\tPolicy: %s", poid);
+
+ for (k = 0;
+ ret == 0 && cp.val[i].policyQualifiers &&
+ k < cp.val[i].policyQualifiers->len;
+ k++) {
+ PolicyQualifierInfo *pi = &cp.val[i].policyQualifiers->val[k];
+
+ if (der_heim_oid_cmp(&pi->policyQualifierId,
+ &asn1_oid_id_pkix_qt_cps) == 0) {
+ CPSuri cps;
+
+ ret = decode_CPSuri(pi->qualifier.data, pi->qualifier.length,
+ &cps, &size);
+ if (ret == 0) {
+ if (cps.length > 4096)
+ cps.length = 4096;
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ ":CPSuri:%.*s",
+ (int)cps.length, (char *)cps.data);
+ free_CPSuri(&cps);
+ }
+ } else if (der_heim_oid_cmp(&pi->policyQualifierId,
+ &asn1_oid_id_pkix_qt_unotice) == 0) {
+ UserNotice un;
+
+ ret = decode_UserNotice(pi->qualifier.data,
+ pi->qualifier.length, &un, &size);
+ if (ret == 0) {
+ if (un.explicitText) {
+ /*
+ * get_display_text() will strvis to make it safer to
+ * print.
+ */
+ ret = get_display_text(un.explicitText, &dt);
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ " UserNotice:DistplayText:%s", dt);
+ } else if (un.noticeRef) {
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ " UserNotice:NoticeRef:<noticeRef-not-supported>",
+ qoid);
+ } else {
+ ret = der_print_heim_oid(&pi->policyQualifierId, '.',
+ &qoid);
+ if (ret)
+ break;
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ " Unknown:%s", qoid);
+ }
+ free_UserNotice(&un);
+ }
+ } else {
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ ", qualifier %s:<unknown>", qoid);
+ }
+ free(qoid);
+ free(dt);
+ qoid = dt = 0;
+ }
+ if (ret == 0) {
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\n");
+ } else {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "\nOut of memory formatting certificate policy");
+ ret = ENOMEM;
+ }
+ free(poid);
+ free(qoid);
+ free(dt);
+ poid = qoid = dt = 0;
+ }
+
+ free_CertificatePolicies(&cp);
+
+ return ret ? 1 : 0;
+}
+
+static int
+check_policyMappings(hx509_validate_ctx ctx,
+ struct cert_status *status,
+ enum critical_flag cf,
+ const Extension *e)
+{
+ PolicyMappings pm;
+ size_t i, size;
+ int ret = 0;
+
+ check_Null(ctx, status, cf, e);
+
+ if (e->extnValue.length == 0) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "PolicyMappings empty, not allowed");
+ return 1;
+ }
+ ret = decode_PolicyMappings(e->extnValue.data, e->extnValue.length,
+ &pm, &size);
+ if (ret) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "\tret = %d while decoding PolicyMappings\n", ret);
+ return 1;
+ }
+ if (pm.len == 0) {
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "PolicyMappings empty, not allowed\n");
+ return 1;
+ }
+
+ for (i = 0; ret == 0 && i < pm.len; i++) {
+ char *idpoid = NULL;
+ char *sdpoid = NULL;
+
+ ret = der_print_heim_oid(&pm.val[i].issuerDomainPolicy, '.', &idpoid);
+ if (ret == 0)
+ ret = der_print_heim_oid(&pm.val[i].subjectDomainPolicy, '.',
+ &sdpoid);
+ if (ret == 0)
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "\tPolicy mapping %s -> %s\n", idpoid, sdpoid);
+ else
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "ret=%d while decoding PolicyMappings\n", ret);
+ free(sdpoid);
+ free(idpoid);
+ }
+
+ free_PolicyMappings(&pm);
+ return 0;
+}
+
+/*
+ *
+ */
+
+struct {
+ const char *name;
+ const heim_oid *oid;
+ int (*func)(hx509_validate_ctx ctx,
+ struct cert_status *status,
+ enum critical_flag cf,
+ const Extension *);
+ enum critical_flag cf;
+} check_extension[] = {
+#define ext(name, checkname) #name, &asn1_oid_id_x509_ce_##name, check_##checkname
+ { ext(subjectDirectoryAttributes, Null), M_N_C },
+ { ext(subjectKeyIdentifier, subjectKeyIdentifier), M_N_C },
+ { ext(keyUsage, Null), S_C },
+ { ext(subjectAltName, subjectAltName), M_N_C },
+ { ext(issuerAltName, issuerAltName), S_N_C },
+ { ext(basicConstraints, basicConstraints), D_C },
+ { ext(cRLNumber, Null), M_N_C },
+ { ext(cRLReason, Null), M_N_C },
+ { ext(holdInstructionCode, Null), M_N_C },
+ { ext(invalidityDate, Null), M_N_C },
+ { ext(deltaCRLIndicator, Null), M_C },
+ { ext(issuingDistributionPoint, Null), M_C },
+ { ext(certificateIssuer, Null), M_C },
+ { ext(nameConstraints, Null), M_C },
+ { ext(cRLDistributionPoints, CRLDistributionPoints), S_N_C },
+ { ext(certificatePolicies, certificatePolicies), 0 },
+ { ext(policyMappings, policyMappings), M_N_C },
+ { ext(authorityKeyIdentifier, authorityKeyIdentifier), M_N_C },
+ { ext(policyConstraints, Null), D_C },
+ { ext(extKeyUsage, extKeyUsage), D_C },
+ { ext(freshestCRL, Null), M_N_C },
+ { ext(inhibitAnyPolicy, Null), M_C },
+#undef ext
+#define ext(name, checkname) #name, &asn1_oid_id_pkix_pe_##name, check_##checkname
+ { ext(proxyCertInfo, proxyCertInfo), M_C },
+ { ext(authorityInfoAccess, authorityInfoAccess), M_C },
+#undef ext
+ { "US Fed PKI - PIV Interim", &asn1_oid_id_uspkicommon_piv_interim,
+ check_Null, D_C },
+ { "Netscape cert comment", &asn1_oid_id_netscape_cert_comment,
+ check_Null, D_C },
+ { NULL, NULL, NULL, 0 }
+};
+
+/**
+ * Allocate a hx509 validation/printing context.
+ *
+ * @param context A hx509 context.
+ * @param ctx a new allocated hx509 validation context, free with
+ * hx509_validate_ctx_free().
+
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_print
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_validate_ctx_init(hx509_context context, hx509_validate_ctx *ctx)
+{
+ *ctx = calloc(1, sizeof(**ctx));
+ if (*ctx == NULL)
+ return hx509_enomem(context);
+ (*ctx)->context = context;
+ return 0;
+}
+
+/**
+ * Set the printing functions for the validation context.
+ *
+ * @param ctx a hx509 valication context.
+ * @param func the printing function to usea.
+ * @param c the context variable to the printing function.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_print
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_validate_ctx_set_print(hx509_validate_ctx ctx,
+ hx509_vprint_func func,
+ void *c)
+{
+ ctx->vprint_func = func;
+ ctx->ctx = c;
+}
+
+/**
+ * Add flags to control the behaivor of the hx509_validate_cert()
+ * function.
+ *
+ * @param ctx A hx509 validation context.
+ * @param flags flags to add to the validation context.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_print
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_validate_ctx_add_flags(hx509_validate_ctx ctx, int flags)
+{
+ ctx->flags |= flags;
+}
+
+/**
+ * Free an hx509 validate context.
+ *
+ * @param ctx the hx509 validate context to free.
+ *
+ * @ingroup hx509_print
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_validate_ctx_free(hx509_validate_ctx ctx)
+{
+ free(ctx);
+}
+
+/**
+ * Validate/Print the status of the certificate.
+ *
+ * @param context A hx509 context.
+ * @param ctx A hx509 validation context.
+ * @param cert the cerificate to validate/print.
+
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_print
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_validate_cert(hx509_context context,
+ hx509_validate_ctx ctx,
+ hx509_cert cert)
+{
+ Certificate *c = _hx509_get_cert(cert);
+ TBSCertificate *t = &c->tbsCertificate;
+ hx509_name issuer, subject;
+ char *str;
+ struct cert_status status;
+ int ret;
+
+ memset(&status, 0, sizeof(status));
+
+ if (_hx509_cert_get_version(c) != 3)
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "Not version 3 certificate\n");
+
+ if ((t->version == NULL || *t->version < 2) && t->extensions)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Not version 3 certificate with extensions\n");
+
+ if (_hx509_cert_get_version(c) >= 3 && t->extensions == NULL)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Version 3 certificate without extensions\n");
+
+ ret = hx509_cert_get_subject(cert, &subject);
+ if (ret) abort();
+ hx509_name_to_string(subject, &str);
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "subject name: %s\n", str);
+ free(str);
+
+ ret = hx509_cert_get_issuer(cert, &issuer);
+ if (ret) abort();
+ hx509_name_to_string(issuer, &str);
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "issuer name: %s\n", str);
+ free(str);
+
+ if (hx509_name_cmp(subject, issuer) == 0) {
+ status.selfsigned = 1;
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "\tis a self-signed certificate\n");
+ }
+
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "Validity:\n");
+
+ Time2string(&t->validity.notBefore, &str);
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\tnotBefore %s\n", str);
+ free(str);
+ Time2string(&t->validity.notAfter, &str);
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\tnotAfter %s\n", str);
+ free(str);
+
+ if (t->extensions) {
+ size_t i, j;
+
+ if (t->extensions->len == 0) {
+ validate_print(ctx,
+ HX509_VALIDATE_F_VALIDATE|HX509_VALIDATE_F_VERBOSE,
+ "The empty extensions list is not "
+ "allowed by PKIX\n");
+ }
+
+ for (i = 0; i < t->extensions->len; i++) {
+
+ for (j = 0; check_extension[j].name; j++)
+ if (der_heim_oid_cmp(check_extension[j].oid,
+ &t->extensions->val[i].extnID) == 0)
+ break;
+ if (check_extension[j].name == NULL) {
+ int flags = HX509_VALIDATE_F_VERBOSE;
+ if (t->extensions->val[i].critical)
+ flags |= HX509_VALIDATE_F_VALIDATE;
+ validate_print(ctx, flags, "don't know what ");
+ if (t->extensions->val[i].critical)
+ validate_print(ctx, flags, "and is CRITICAL ");
+ if (ctx->flags & flags)
+ hx509_oid_print(&t->extensions->val[i].extnID,
+ validate_vprint, ctx);
+ validate_print(ctx, flags, " is\n");
+ continue;
+ }
+ validate_print(ctx,
+ HX509_VALIDATE_F_VALIDATE|HX509_VALIDATE_F_VERBOSE,
+ "checking extension: %s\n",
+ check_extension[j].name);
+ (*check_extension[j].func)(ctx,
+ &status,
+ check_extension[j].cf,
+ &t->extensions->val[i]);
+ }
+ } else
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "no extensions\n");
+
+ if (status.isca) {
+ if (!status.haveSKI)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "CA certificate have no SubjectKeyIdentifier\n");
+
+ } else {
+ if (!status.haveAKI)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Is not CA and doesn't have "
+ "AuthorityKeyIdentifier\n");
+ }
+
+
+ if (!status.haveSKI)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Doesn't have SubjectKeyIdentifier\n");
+
+ if (status.isproxy && status.isca)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Proxy and CA at the same time!\n");
+
+ if (status.isproxy) {
+ if (status.haveSAN)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Proxy and have SAN\n");
+ if (status.haveIAN)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Proxy and have IAN\n");
+ }
+
+ if (hx509_name_is_null_p(subject) && !status.haveSAN)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "NULL subject DN and doesn't have a SAN\n");
+
+ if (!status.selfsigned && !status.haveCRLDP)
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Not a CA nor PROXY and doesn't have"
+ "CRL Dist Point\n");
+
+ if (status.selfsigned) {
+ ret = _hx509_verify_signature_bitstring(context,
+ cert,
+ &c->signatureAlgorithm,
+ &c->tbsCertificate._save,
+ &c->signatureValue);
+ if (ret == 0)
+ validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+ "Self-signed certificate was self-signed\n");
+ else
+ validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+ "Self-signed certificate NOT really self-signed!\n");
+ }
+
+ hx509_name_free(&subject);
+ hx509_name_free(&issuer);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hx509/quote.py b/third_party/heimdal/lib/hx509/quote.py
new file mode 100644
index 0000000..41887e5
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/quote.py
@@ -0,0 +1,101 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2010 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+
+CONTROL_CHAR = 1
+PRINTABLE = 2
+RFC2253_QUOTE_FIRST = 4
+RFC2253_QUOTE_LAST = 8
+RFC2253_QUOTE = 16
+RFC2253_HEX = 32
+
+chars = []
+
+for i in range(0, 256):
+ chars.append(0);
+
+for i in range(0, 256):
+ if (i < 32 or i > 126):
+ chars[i] |= CONTROL_CHAR | RFC2253_HEX;
+
+for i in range(ord("A"), ord("Z") + 1):
+ chars[i] |= PRINTABLE
+for i in range(ord("a"), ord("z") + 1):
+ chars[i] |= PRINTABLE
+for i in range(ord("0"), ord("9") + 1):
+ chars[i] |= PRINTABLE
+
+chars[ord(' ')] |= PRINTABLE
+chars[ord('+')] |= PRINTABLE
+chars[ord(',')] |= PRINTABLE
+chars[ord('-')] |= PRINTABLE
+chars[ord('.')] |= PRINTABLE
+chars[ord('/')] |= PRINTABLE
+chars[ord(':')] |= PRINTABLE
+chars[ord('=')] |= PRINTABLE
+chars[ord('?')] |= PRINTABLE
+
+chars[ord(' ')] |= RFC2253_QUOTE_FIRST | RFC2253_QUOTE_FIRST
+
+chars[ord(',')] |= RFC2253_QUOTE
+chars[ord('=')] |= RFC2253_QUOTE
+chars[ord('+')] |= RFC2253_QUOTE
+chars[ord('<')] |= RFC2253_QUOTE
+chars[ord('>')] |= RFC2253_QUOTE
+chars[ord('#')] |= RFC2253_QUOTE
+chars[ord(';')] |= RFC2253_QUOTE
+
+print "#define Q_CONTROL_CHAR 1"
+print "#define Q_PRINTABLE 2"
+print "#define Q_RFC2253_QUOTE_FIRST 4"
+print "#define Q_RFC2253_QUOTE_LAST 8"
+print "#define Q_RFC2253_QUOTE 16"
+print "#define Q_RFC2253_HEX 32"
+print ""
+print "#define Q_RFC2253 (Q_RFC2253_QUOTE_FIRST|Q_RFC2253_QUOTE_LAST|Q_RFC2253_QUOTE|Q_RFC2253_HEX)"
+print "\n" * 2
+
+
+
+
+print "unsigned char char_map[] = {\n\t",
+for x in range(0, 256):
+ if (x % 8) == 0 and x != 0:
+ print "\n\t",
+ print "0x%(char)02x" % { 'char' : chars[x] },
+ if x < 255:
+ print ", ",
+ else:
+ print ""
+print "};"
diff --git a/third_party/heimdal/lib/hx509/ref/pkcs11.h b/third_party/heimdal/lib/hx509/ref/pkcs11.h
new file mode 100644
index 0000000..a294c5e
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/ref/pkcs11.h
@@ -0,0 +1,1722 @@
+/* pkcs11.h
+ Copyright 2006, 2007 g10 Code GmbH
+ Copyright 2006 Andreas Jellinghaus
+
+ This file is free software; as a special exception the author gives
+ unlimited permission to copy and/or distribute it, with or without
+ modifications, as long as this notice is preserved.
+
+ This file is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY, to the extent permitted by law; without even
+ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ PURPOSE. */
+
+/* Please submit changes back to the Scute project at
+ http://www.scute.org/ (or send them to marcus@g10code.com), so that
+ they can be picked up by other projects from there as well. */
+
+/* This file is a modified implementation of the PKCS #11 standard by
+ RSA Security Inc. It is mostly a drop-in replacement, with the
+ following change:
+
+ This header file does not require any macro definitions by the user
+ (like CK_DEFINE_FUNCTION etc). In fact, it defines those macros
+ for you (if useful, some are missing, let me know if you need
+ more).
+
+ There is an additional API available that does comply better to the
+ GNU coding standard. It can be switched on by defining
+ CRYPTOKI_GNU before including this header file. For this, the
+ following changes are made to the specification:
+
+ All structure types are changed to a "struct ck_foo" where CK_FOO
+ is the type name in PKCS #11.
+
+ All non-structure types are changed to ck_foo_t where CK_FOO is the
+ lowercase version of the type name in PKCS #11. The basic types
+ (CK_ULONG et al.) are removed without substitute.
+
+ All members of structures are modified in the following way: Type
+ indication prefixes are removed, and underscore characters are
+ inserted before words. Then the result is lowercased.
+
+ Note that function names are still in the original case, as they
+ need for ABI compatibility.
+
+ CK_FALSE, CK_TRUE and NULL_PTR are removed without substitute. Use
+ <stdbool.h>.
+
+ If CRYPTOKI_COMPAT is defined before including this header file,
+ then none of the API changes above take place, and the API is the
+ one defined by the PKCS #11 standard. */
+
+#ifndef PKCS11_H
+#define PKCS11_H 1
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+
+/* The version of cryptoki we implement. The revision is changed with
+ each modification of this file. If you do not use the "official"
+ version of this file, please consider deleting the revision macro
+ (you may use a macro with a different name to keep track of your
+ versions). */
+#define CRYPTOKI_VERSION_MAJOR 2
+#define CRYPTOKI_VERSION_MINOR 30
+#define CRYPTOKI_VERSION_REVISION 0
+#define CRYPTOKI_VERSION_AMENDMENT 0
+
+
+/* Compatibility interface is default, unless CRYPTOKI_GNU is
+ given. */
+#ifndef CRYPTOKI_GNU
+#ifndef CRYPTOKI_COMPAT
+#define CRYPTOKI_COMPAT 1
+#endif
+#endif
+
+/* System dependencies. */
+
+#if defined(_WIN32) || defined(CRYPTOKI_FORCE_WIN32)
+
+/* There is a matching pop below. */
+#pragma pack(push, cryptoki, 1)
+
+#ifdef CRYPTOKI_EXPORTS
+#define CK_SPEC __declspec(dllexport)
+#else
+#define CK_SPEC __declspec(dllimport)
+#endif
+
+#else
+
+#if defined(CRYPTOKI_VISIBILITY) && defined(CRYPTOKI_EXPORTS)
+#define CK_SPEC __attribute__((visibility("default")))
+#else
+#define CK_SPEC
+#endif
+
+#endif
+
+
+#ifdef CRYPTOKI_COMPAT
+ /* If we are in compatibility mode, switch all exposed names to the
+ PKCS #11 variant. There are corresponding #undefs below. */
+
+#define ck_flags_t CK_FLAGS
+#define ck_version _CK_VERSION
+
+#define ck_info _CK_INFO
+#define cryptoki_version cryptokiVersion
+#define manufacturer_id manufacturerID
+#define library_description libraryDescription
+#define library_version libraryVersion
+
+#define ck_notification_t CK_NOTIFICATION
+#define ck_slot_id_t CK_SLOT_ID
+
+#define ck_slot_info _CK_SLOT_INFO
+#define slot_description slotDescription
+#define hardware_version hardwareVersion
+#define firmware_version firmwareVersion
+
+#define ck_token_info _CK_TOKEN_INFO
+#define serial_number serialNumber
+#define max_session_count ulMaxSessionCount
+#define session_count ulSessionCount
+#define max_rw_session_count ulMaxRwSessionCount
+#define rw_session_count ulRwSessionCount
+#define max_pin_len ulMaxPinLen
+#define min_pin_len ulMinPinLen
+#define total_public_memory ulTotalPublicMemory
+#define free_public_memory ulFreePublicMemory
+#define total_private_memory ulTotalPrivateMemory
+#define free_private_memory ulFreePrivateMemory
+#define utc_time utcTime
+
+#define ck_session_handle_t CK_SESSION_HANDLE
+#define ck_user_type_t CK_USER_TYPE
+#define ck_state_t CK_STATE
+
+#define ck_session_info _CK_SESSION_INFO
+#define slot_id slotID
+#define device_error ulDeviceError
+
+#define ck_object_handle_t CK_OBJECT_HANDLE
+#define ck_object_class_t CK_OBJECT_CLASS
+#define ck_hw_feature_type_t CK_HW_FEATURE_TYPE
+#define ck_key_type_t CK_KEY_TYPE
+#define ck_certificate_type_t CK_CERTIFICATE_TYPE
+#define ck_attribute_type_t CK_ATTRIBUTE_TYPE
+
+#define ck_attribute _CK_ATTRIBUTE
+#define value pValue
+#define value_len ulValueLen
+
+#define ck_date _CK_DATE
+
+#define ck_mechanism_type_t CK_MECHANISM_TYPE
+
+#define ck_mechanism _CK_MECHANISM
+#define parameter pParameter
+#define parameter_len ulParameterLen
+
+#define ck_mechanism_info _CK_MECHANISM_INFO
+#define min_key_size ulMinKeySize
+#define max_key_size ulMaxKeySize
+
+#define hash_alg hashAlg
+#define source_data pSourceData
+#define source_data_len ulSourceDataLen
+
+#define slen sLen
+
+#define ck_ec_kdf_type_t CK_EC_KDF_TYPE
+
+#define shared_data_len ulSharedDataLen
+#define shared_data pSharedData
+#define public_data_len ulPublicDataLen
+#define public_data pPublicData
+
+#define private_data_len ulPrivateDataLen
+#define private_data hPrivateData
+#define public_data_len2 ulPublicDataLen2
+#define public_data2 pPublicData2
+
+#define public_key publicKey
+
+#define ck_x9_42_dh_kdf_type_t CK_X9_42_DH_KDF_TYPE
+
+#define other_info_len ulOtherInfoLen
+#define other_info pOtherInfo
+
+#define data pData
+#define len ulLen
+
+#define ck_rv_t CK_RV
+#define ck_notify_t CK_NOTIFY
+
+#define ck_function_list _CK_FUNCTION_LIST
+
+#define ck_createmutex_t CK_CREATEMUTEX
+#define ck_destroymutex_t CK_DESTROYMUTEX
+#define ck_lockmutex_t CK_LOCKMUTEX
+#define ck_unlockmutex_t CK_UNLOCKMUTEX
+
+#define ck_c_initialize_args _CK_C_INITIALIZE_ARGS
+#define create_mutex CreateMutex
+#define destroy_mutex DestroyMutex
+#define lock_mutex LockMutex
+#define unlock_mutex UnlockMutex
+#define reserved pReserved
+
+#endif /* CRYPTOKI_COMPAT */
+
+
+
+typedef unsigned long ck_flags_t;
+
+struct ck_version
+{
+ unsigned char major;
+ unsigned char minor;
+};
+
+
+struct ck_info
+{
+ struct ck_version cryptoki_version;
+ unsigned char manufacturer_id[32];
+ ck_flags_t flags;
+ unsigned char library_description[32];
+ struct ck_version library_version;
+};
+
+
+typedef unsigned long ck_notification_t;
+
+#define CKN_SURRENDER (0)
+#define CKN_OTP_CHANGED (1)
+
+typedef unsigned long ck_slot_id_t;
+
+
+struct ck_slot_info
+{
+ unsigned char slot_description[64];
+ unsigned char manufacturer_id[32];
+ ck_flags_t flags;
+ struct ck_version hardware_version;
+ struct ck_version firmware_version;
+};
+
+
+#define CKF_TOKEN_PRESENT (1 << 0)
+#define CKF_REMOVABLE_DEVICE (1 << 1)
+#define CKF_HW_SLOT (1 << 2)
+#define CKF_ARRAY_ATTRIBUTE (1 << 30)
+
+
+struct ck_token_info
+{
+ unsigned char label[32];
+ unsigned char manufacturer_id[32];
+ unsigned char model[16];
+ unsigned char serial_number[16];
+ ck_flags_t flags;
+ unsigned long max_session_count;
+ unsigned long session_count;
+ unsigned long max_rw_session_count;
+ unsigned long rw_session_count;
+ unsigned long max_pin_len;
+ unsigned long min_pin_len;
+ unsigned long total_public_memory;
+ unsigned long free_public_memory;
+ unsigned long total_private_memory;
+ unsigned long free_private_memory;
+ struct ck_version hardware_version;
+ struct ck_version firmware_version;
+ unsigned char utc_time[16];
+};
+
+
+#define CKF_RNG (1 << 0)
+#define CKF_WRITE_PROTECTED (1 << 1)
+#define CKF_LOGIN_REQUIRED (1 << 2)
+#define CKF_USER_PIN_INITIALIZED (1 << 3)
+#define CKF_RESTORE_KEY_NOT_NEEDED (1 << 5)
+#define CKF_CLOCK_ON_TOKEN (1 << 6)
+#define CKF_PROTECTED_AUTHENTICATION_PATH (1 << 8)
+#define CKF_DUAL_CRYPTO_OPERATIONS (1 << 9)
+#define CKF_TOKEN_INITIALIZED (1 << 10)
+#define CKF_SECONDARY_AUTHENTICATION (1 << 11)
+#define CKF_USER_PIN_COUNT_LOW (1 << 16)
+#define CKF_USER_PIN_FINAL_TRY (1 << 17)
+#define CKF_USER_PIN_LOCKED (1 << 18)
+#define CKF_USER_PIN_TO_BE_CHANGED (1 << 19)
+#define CKF_SO_PIN_COUNT_LOW (1 << 20)
+#define CKF_SO_PIN_FINAL_TRY (1 << 21)
+#define CKF_SO_PIN_LOCKED (1 << 22)
+#define CKF_SO_PIN_TO_BE_CHANGED (1 << 23)
+#define CKF_ERROR_STATE (1 << 24)
+
+#define CK_UNAVAILABLE_INFORMATION ((unsigned long) -1)
+#define CK_EFFECTIVELY_INFINITE (0)
+
+
+typedef unsigned long ck_session_handle_t;
+
+#define CK_INVALID_HANDLE (0)
+
+
+typedef unsigned long ck_user_type_t;
+
+#define CKU_SO (0)
+#define CKU_USER (1)
+#define CKU_CONTEXT_SPECIFIC (2)
+
+
+typedef unsigned long ck_state_t;
+
+#define CKS_RO_PUBLIC_SESSION (0)
+#define CKS_RO_USER_FUNCTIONS (1)
+#define CKS_RW_PUBLIC_SESSION (2)
+#define CKS_RW_USER_FUNCTIONS (3)
+#define CKS_RW_SO_FUNCTIONS (4)
+
+
+struct ck_session_info
+{
+ ck_slot_id_t slot_id;
+ ck_state_t state;
+ ck_flags_t flags;
+ unsigned long device_error;
+};
+
+#define CKF_RW_SESSION (1 << 1)
+#define CKF_SERIAL_SESSION (1 << 2)
+
+
+typedef unsigned long ck_object_handle_t;
+
+
+typedef unsigned long ck_object_class_t;
+
+#define CKO_DATA (0)
+#define CKO_CERTIFICATE (1)
+#define CKO_PUBLIC_KEY (2)
+#define CKO_PRIVATE_KEY (3)
+#define CKO_SECRET_KEY (4)
+#define CKO_HW_FEATURE (5)
+#define CKO_DOMAIN_PARAMETERS (6)
+#define CKO_MECHANISM (7)
+#define CKO_OTP_KEY (8)
+#define CKO_VENDOR_DEFINED ((unsigned long) (1ul << 31))
+
+
+typedef unsigned long ck_hw_feature_type_t;
+
+#define CKH_MONOTONIC_COUNTER (1)
+#define CKH_CLOCK (2)
+#define CKH_USER_INTERFACE (3)
+#define CKH_VENDOR_DEFINED ((unsigned long) (1ul << 31))
+
+
+typedef unsigned long ck_key_type_t;
+
+#define CKK_RSA (0)
+#define CKK_DSA (1)
+#define CKK_DH (2)
+#define CKK_ECDSA (3)
+#define CKK_EC (3)
+#define CKK_X9_42_DH (4)
+#define CKK_KEA (5)
+#define CKK_GENERIC_SECRET (0x10)
+#define CKK_RC2 (0x11)
+#define CKK_RC4 (0x12)
+#define CKK_DES (0x13)
+#define CKK_DES2 (0x14)
+#define CKK_DES3 (0x15)
+#define CKK_CAST (0x16)
+#define CKK_CAST3 (0x17)
+#define CKK_CAST5 (0x18)
+#define CKK_CAST128 (0x18)
+#define CKK_RC5 (0x19)
+#define CKK_IDEA (0x1a)
+#define CKK_SKIPJACK (0x1b)
+#define CKK_BATON (0x1c)
+#define CKK_JUNIPER (0x1d)
+#define CKK_CDMF (0x1e)
+#define CKK_AES (0x1f)
+#define CKK_BLOWFISH (0x20)
+#define CKK_TWOFISH (0x21)
+#define CKK_SECURID (0x22)
+#define CKK_HOTP (0x23)
+#define CKK_ACTI (0x24)
+#define CKK_CAMELLIA (0x25)
+#define CKK_ARIA (0x26)
+#define CKK_MD5_HMAC (0x27)
+#define CKK_SHA_1_HMAC (0x28)
+#define CKK_RIPEMD128_HMAC (0x29)
+#define CKK_RIPEMD160_HMAC (0x2A)
+#define CKK_SHA256_HMAC (0x2B)
+#define CKK_SHA384_HMAC (0x2C)
+#define CKK_SHA512_HMAC (0x2D)
+#define CKK_SHA224_HMAC (0x2E)
+#define CKK_SEED (0x2F)
+#define CKK_GOSTR3410 (0x30)
+#define CKK_GOSTR3411 (0x31)
+#define CKK_GOST28147 (0x32)
+#define CKK_VENDOR_DEFINED ((unsigned long) (1ul << 31))
+
+
+typedef unsigned long ck_certificate_type_t;
+
+#define CKC_X_509 (0)
+#define CKC_X_509_ATTR_CERT (1)
+#define CKC_WTLS (2)
+#define CKC_VENDOR_DEFINED ((unsigned long) (1ul << 31))
+#define CKC_OPENPGP (CKC_VENDOR_DEFINED|0x00504750)
+
+#define CK_OTP_FORMAT_DECIMAL (0)
+#define CK_OTP_FORMAT_HEXADECIMAL (1)
+#define CK_OTP_FORMAT_ALPHANUMERIC (2)
+#define CK_OTP_FORMAT_BINARY (3)
+
+#define CK_OTP_PARAM_IGNORED (0)
+#define CK_OTP_PARAM_OPTIONAL (1)
+#define CK_OTP_PARAM_MANDATORY (2)
+
+typedef unsigned long ck_attribute_type_t;
+
+#define CKA_CLASS (0)
+#define CKA_TOKEN (1)
+#define CKA_PRIVATE (2)
+#define CKA_LABEL (3)
+#define CKA_APPLICATION (0x10)
+#define CKA_VALUE (0x11)
+#define CKA_OBJECT_ID (0x12)
+#define CKA_CERTIFICATE_TYPE (0x80)
+#define CKA_ISSUER (0x81)
+#define CKA_SERIAL_NUMBER (0x82)
+#define CKA_AC_ISSUER (0x83)
+#define CKA_OWNER (0x84)
+#define CKA_ATTR_TYPES (0x85)
+#define CKA_TRUSTED (0x86)
+#define CKA_CERTIFICATE_CATEGORY (0x87)
+#define CKA_JAVA_MIDP_SECURITY_DOMAIN (0x88)
+#define CKA_URL (0x89)
+#define CKA_HASH_OF_SUBJECT_PUBLIC_KEY (0x8a)
+#define CKA_HASH_OF_ISSUER_PUBLIC_KEY (0x8b)
+#define CKA_NAME_HASH_ALGORITHM (0x8c)
+#define CKA_CHECK_VALUE (0x90)
+#define CKA_KEY_TYPE (0x100)
+#define CKA_SUBJECT (0x101)
+#define CKA_ID (0x102)
+#define CKA_SENSITIVE (0x103)
+#define CKA_ENCRYPT (0x104)
+#define CKA_DECRYPT (0x105)
+#define CKA_WRAP (0x106)
+#define CKA_UNWRAP (0x107)
+#define CKA_SIGN (0x108)
+#define CKA_SIGN_RECOVER (0x109)
+#define CKA_VERIFY (0x10a)
+#define CKA_VERIFY_RECOVER (0x10b)
+#define CKA_DERIVE (0x10c)
+#define CKA_START_DATE (0x110)
+#define CKA_END_DATE (0x111)
+#define CKA_MODULUS (0x120)
+#define CKA_MODULUS_BITS (0x121)
+#define CKA_PUBLIC_EXPONENT (0x122)
+#define CKA_PRIVATE_EXPONENT (0x123)
+#define CKA_PRIME_1 (0x124)
+#define CKA_PRIME_2 (0x125)
+#define CKA_EXPONENT_1 (0x126)
+#define CKA_EXPONENT_2 (0x127)
+#define CKA_COEFFICIENT (0x128)
+#define CKA_PRIME (0x130)
+#define CKA_SUBPRIME (0x131)
+#define CKA_BASE (0x132)
+#define CKA_PRIME_BITS (0x133)
+#define CKA_SUB_PRIME_BITS (0x134)
+#define CKA_SUBPRIME_BITS (0x134)
+#define CKA_VALUE_BITS (0x160)
+#define CKA_VALUE_LEN (0x161)
+#define CKA_EXTRACTABLE (0x162)
+#define CKA_LOCAL (0x163)
+#define CKA_NEVER_EXTRACTABLE (0x164)
+#define CKA_ALWAYS_SENSITIVE (0x165)
+#define CKA_KEY_GEN_MECHANISM (0x166)
+#define CKA_MODIFIABLE (0x170)
+#define CKA_COPYABLE (0x171)
+#define CKA_ECDSA_PARAMS (0x180)
+#define CKA_EC_PARAMS (0x180)
+#define CKA_EC_POINT (0x181)
+#define CKA_SECONDARY_AUTH (0x200)
+#define CKA_AUTH_PIN_FLAGS (0x201)
+#define CKA_ALWAYS_AUTHENTICATE (0x202)
+#define CKA_WRAP_WITH_TRUSTED (0x210)
+#define CKA_OTP_FORMAT (0x220)
+#define CKA_OTP_LENGTH (0x221)
+#define CKA_OTP_TIME_INTERVAL (0x222)
+#define CKA_OTP_USER_FRIENDLY_MODE (0x223)
+#define CKA_OTP_CHALLENGE_REQUIREMENT (0x224)
+#define CKA_OTP_TIME_REQUIREMENT (0x225)
+#define CKA_OTP_COUNTER_REQUIREMENT (0x226)
+#define CKA_OTP_PIN_REQUIREMENT (0x227)
+#define CKA_OTP_COUNTER (0x22E)
+#define CKA_OTP_TIME (0x22F)
+#define CKA_OTP_USER_IDENTIFIER (0x22A)
+#define CKA_OTP_SERVICE_IDENTIFIER (0x22B)
+#define CKA_OTP_SERVICE_LOGO (0x22C)
+#define CKA_OTP_SERVICE_LOGO_TYPE (0x22D)
+#define CKA_GOSTR3410_PARAMS (0x250)
+#define CKA_GOSTR3411_PARAMS (0x251)
+#define CKA_GOST28147_PARAMS (0x252)
+#define CKA_HW_FEATURE_TYPE (0x300)
+#define CKA_RESET_ON_INIT (0x301)
+#define CKA_HAS_RESET (0x302)
+#define CKA_PIXEL_X (0x400)
+#define CKA_PIXEL_Y (0x401)
+#define CKA_RESOLUTION (0x402)
+#define CKA_CHAR_ROWS (0x403)
+#define CKA_CHAR_COLUMNS (0x404)
+#define CKA_COLOR (0x405)
+#define CKA_BITS_PER_PIXEL (0x406)
+#define CKA_CHAR_SETS (0x480)
+#define CKA_ENCODING_METHODS (0x481)
+#define CKA_MIME_TYPES (0x482)
+#define CKA_MECHANISM_TYPE (0x500)
+#define CKA_REQUIRED_CMS_ATTRIBUTES (0x501)
+#define CKA_DEFAULT_CMS_ATTRIBUTES (0x502)
+#define CKA_SUPPORTED_CMS_ATTRIBUTES (0x503)
+#define CKA_WRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE | 0x211)
+#define CKA_UNWRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE | 0x212)
+#define CKA_DERIVE_TEMPLATE (CKF_ARRAY_ATTRIBUTE | 0x213)
+#define CKA_ALLOWED_MECHANISMS (CKF_ARRAY_ATTRIBUTE | 0x600)
+#define CKA_VENDOR_DEFINED ((unsigned long) (1ul << 31))
+
+
+struct ck_attribute
+{
+ ck_attribute_type_t type;
+ void *value;
+ unsigned long value_len;
+};
+
+
+struct ck_date
+{
+ unsigned char year[4];
+ unsigned char month[2];
+ unsigned char day[2];
+};
+
+
+typedef unsigned long ck_mechanism_type_t;
+
+#define CKM_RSA_PKCS_KEY_PAIR_GEN (0)
+#define CKM_RSA_PKCS (1)
+#define CKM_RSA_9796 (2)
+#define CKM_RSA_X_509 (3)
+#define CKM_MD2_RSA_PKCS (4)
+#define CKM_MD5_RSA_PKCS (5)
+#define CKM_SHA1_RSA_PKCS (6)
+#define CKM_RIPEMD128_RSA_PKCS (7)
+#define CKM_RIPEMD160_RSA_PKCS (8)
+#define CKM_RSA_PKCS_OAEP (9)
+#define CKM_RSA_X9_31_KEY_PAIR_GEN (0xa)
+#define CKM_RSA_X9_31 (0xb)
+#define CKM_SHA1_RSA_X9_31 (0xc)
+#define CKM_RSA_PKCS_PSS (0xd)
+#define CKM_SHA1_RSA_PKCS_PSS (0xe)
+#define CKM_DSA_KEY_PAIR_GEN (0x10)
+#define CKM_DSA (0x11)
+#define CKM_DSA_SHA1 (0x12)
+#define CKM_DSA_SHA224 (0x13)
+#define CKM_DSA_SHA256 (0x14)
+#define CKM_DSA_SHA384 (0x15)
+#define CKM_DSA_SHA512 (0x16)
+#define CKM_DH_PKCS_KEY_PAIR_GEN (0x20)
+#define CKM_DH_PKCS_DERIVE (0x21)
+#define CKM_X9_42_DH_KEY_PAIR_GEN (0x30)
+#define CKM_X9_42_DH_DERIVE (0x31)
+#define CKM_X9_42_DH_HYBRID_DERIVE (0x32)
+#define CKM_X9_42_MQV_DERIVE (0x33)
+#define CKM_SHA256_RSA_PKCS (0x40)
+#define CKM_SHA384_RSA_PKCS (0x41)
+#define CKM_SHA512_RSA_PKCS (0x42)
+#define CKM_SHA256_RSA_PKCS_PSS (0x43)
+#define CKM_SHA384_RSA_PKCS_PSS (0x44)
+#define CKM_SHA512_RSA_PKCS_PSS (0x45)
+#define CKM_SHA224_RSA_PKCS (0x46)
+#define CKM_SHA224_RSA_PKCS_PSS (0x47)
+#define CKM_RC2_KEY_GEN (0x100)
+#define CKM_RC2_ECB (0x101)
+#define CKM_RC2_CBC (0x102)
+#define CKM_RC2_MAC (0x103)
+#define CKM_RC2_MAC_GENERAL (0x104)
+#define CKM_RC2_CBC_PAD (0x105)
+#define CKM_RC4_KEY_GEN (0x110)
+#define CKM_RC4 (0x111)
+#define CKM_DES_KEY_GEN (0x120)
+#define CKM_DES_ECB (0x121)
+#define CKM_DES_CBC (0x122)
+#define CKM_DES_MAC (0x123)
+#define CKM_DES_MAC_GENERAL (0x124)
+#define CKM_DES_CBC_PAD (0x125)
+#define CKM_DES2_KEY_GEN (0x130)
+#define CKM_DES3_KEY_GEN (0x131)
+#define CKM_DES3_ECB (0x132)
+#define CKM_DES3_CBC (0x133)
+#define CKM_DES3_MAC (0x134)
+#define CKM_DES3_MAC_GENERAL (0x135)
+#define CKM_DES3_CBC_PAD (0x136)
+#define CKM_DES3_CMAC_GENERAL (0x137)
+#define CKM_DES3_CMAC (0x138)
+#define CKM_CDMF_KEY_GEN (0x140)
+#define CKM_CDMF_ECB (0x141)
+#define CKM_CDMF_CBC (0x142)
+#define CKM_CDMF_MAC (0x143)
+#define CKM_CDMF_MAC_GENERAL (0x144)
+#define CKM_CDMF_CBC_PAD (0x145)
+#define CKM_DES_OFB64 (0x150)
+#define CKM_DES_OFB8 (0x151)
+#define CKM_DES_CFB64 (0x152)
+#define CKM_DES_CFB8 (0x153)
+#define CKM_MD2 (0x200)
+#define CKM_MD2_HMAC (0x201)
+#define CKM_MD2_HMAC_GENERAL (0x202)
+#define CKM_MD5 (0x210)
+#define CKM_MD5_HMAC (0x211)
+#define CKM_MD5_HMAC_GENERAL (0x212)
+#define CKM_SHA_1 (0x220)
+#define CKM_SHA_1_HMAC (0x221)
+#define CKM_SHA_1_HMAC_GENERAL (0x222)
+#define CKM_RIPEMD128 (0x230)
+#define CKM_RIPEMD128_HMAC (0x231)
+#define CKM_RIPEMD128_HMAC_GENERAL (0x232)
+#define CKM_RIPEMD160 (0x240)
+#define CKM_RIPEMD160_HMAC (0x241)
+#define CKM_RIPEMD160_HMAC_GENERAL (0x242)
+#define CKM_SHA256 (0x250)
+#define CKM_SHA256_HMAC (0x251)
+#define CKM_SHA256_HMAC_GENERAL (0x252)
+#define CKM_SHA224 (0x255)
+#define CKM_SHA224_HMAC (0x256)
+#define CKM_SHA224_HMAC_GENERAL (0x257)
+#define CKM_SHA384 (0x260)
+#define CKM_SHA384_HMAC (0x261)
+#define CKM_SHA384_HMAC_GENERAL (0x262)
+#define CKM_SHA512 (0x270)
+#define CKM_SHA512_HMAC (0x271)
+#define CKM_SHA512_HMAC_GENERAL (0x272)
+#define CKM_SECURID_KEY_GEN (0x280)
+#define CKM_SECURID (0x282)
+#define CKM_HOTP_KEY_GEN (0x290)
+#define CKM_HOTP (0x291)
+#define CKM_ACTI (0x2A0)
+#define CKM_ACTI_KEY_GEN (0x2A1)
+#define CKM_CAST_KEY_GEN (0x300)
+#define CKM_CAST_ECB (0x301)
+#define CKM_CAST_CBC (0x302)
+#define CKM_CAST_MAC (0x303)
+#define CKM_CAST_MAC_GENERAL (0x304)
+#define CKM_CAST_CBC_PAD (0x305)
+#define CKM_CAST3_KEY_GEN (0x310)
+#define CKM_CAST3_ECB (0x311)
+#define CKM_CAST3_CBC (0x312)
+#define CKM_CAST3_MAC (0x313)
+#define CKM_CAST3_MAC_GENERAL (0x314)
+#define CKM_CAST3_CBC_PAD (0x315)
+#define CKM_CAST5_KEY_GEN (0x320)
+#define CKM_CAST128_KEY_GEN (0x320)
+#define CKM_CAST5_ECB (0x321)
+#define CKM_CAST128_ECB (0x321)
+#define CKM_CAST5_CBC (0x322)
+#define CKM_CAST128_CBC (0x322)
+#define CKM_CAST5_MAC (0x323)
+#define CKM_CAST128_MAC (0x323)
+#define CKM_CAST5_MAC_GENERAL (0x324)
+#define CKM_CAST128_MAC_GENERAL (0x324)
+#define CKM_CAST5_CBC_PAD (0x325)
+#define CKM_CAST128_CBC_PAD (0x325)
+#define CKM_RC5_KEY_GEN (0x330)
+#define CKM_RC5_ECB (0x331)
+#define CKM_RC5_CBC (0x332)
+#define CKM_RC5_MAC (0x333)
+#define CKM_RC5_MAC_GENERAL (0x334)
+#define CKM_RC5_CBC_PAD (0x335)
+#define CKM_IDEA_KEY_GEN (0x340)
+#define CKM_IDEA_ECB (0x341)
+#define CKM_IDEA_CBC (0x342)
+#define CKM_IDEA_MAC (0x343)
+#define CKM_IDEA_MAC_GENERAL (0x344)
+#define CKM_IDEA_CBC_PAD (0x345)
+#define CKM_GENERIC_SECRET_KEY_GEN (0x350)
+#define CKM_CONCATENATE_BASE_AND_KEY (0x360)
+#define CKM_CONCATENATE_BASE_AND_DATA (0x362)
+#define CKM_CONCATENATE_DATA_AND_BASE (0x363)
+#define CKM_XOR_BASE_AND_DATA (0x364)
+#define CKM_EXTRACT_KEY_FROM_KEY (0x365)
+#define CKM_SSL3_PRE_MASTER_KEY_GEN (0x370)
+#define CKM_SSL3_MASTER_KEY_DERIVE (0x371)
+#define CKM_SSL3_KEY_AND_MAC_DERIVE (0x372)
+#define CKM_SSL3_MASTER_KEY_DERIVE_DH (0x373)
+#define CKM_TLS_PRE_MASTER_KEY_GEN (0x374)
+#define CKM_TLS_MASTER_KEY_DERIVE (0x375)
+#define CKM_TLS_KEY_AND_MAC_DERIVE (0x376)
+#define CKM_TLS_MASTER_KEY_DERIVE_DH (0x377)
+#define CKM_TLS_PRF (0x378)
+#define CKM_SSL3_MD5_MAC (0x380)
+#define CKM_SSL3_SHA1_MAC (0x381)
+#define CKM_MD5_KEY_DERIVATION (0x390)
+#define CKM_MD2_KEY_DERIVATION (0x391)
+#define CKM_SHA1_KEY_DERIVATION (0x392)
+#define CKM_SHA256_KEY_DERIVATION (0x393)
+#define CKM_SHA384_KEY_DERIVATION (0x394)
+#define CKM_SHA512_KEY_DERIVATION (0x395)
+#define CKM_SHA224_KEY_DERIVATION (0x396)
+#define CKM_PBE_MD2_DES_CBC (0x3a0)
+#define CKM_PBE_MD5_DES_CBC (0x3a1)
+#define CKM_PBE_MD5_CAST_CBC (0x3a2)
+#define CKM_PBE_MD5_CAST3_CBC (0x3a3)
+#define CKM_PBE_MD5_CAST5_CBC (0x3a4)
+#define CKM_PBE_MD5_CAST128_CBC (0x3a4)
+#define CKM_PBE_SHA1_CAST5_CBC (0x3a5)
+#define CKM_PBE_SHA1_CAST128_CBC (0x3a5)
+#define CKM_PBE_SHA1_RC4_128 (0x3a6)
+#define CKM_PBE_SHA1_RC4_40 (0x3a7)
+#define CKM_PBE_SHA1_DES3_EDE_CBC (0x3a8)
+#define CKM_PBE_SHA1_DES2_EDE_CBC (0x3a9)
+#define CKM_PBE_SHA1_RC2_128_CBC (0x3aa)
+#define CKM_PBE_SHA1_RC2_40_CBC (0x3ab)
+#define CKM_PKCS5_PBKD2 (0x3b0)
+#define CKM_PBA_SHA1_WITH_SHA1_HMAC (0x3c0)
+#define CKM_WTLS_PRE_MASTER_KEY_GEN (0x3d0)
+#define CKM_WTLS_MASTER_KEY_DERIVE (0x3d1)
+#define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC (0x3d2)
+#define CKM_WTLS_PRF (0x3d3)
+#define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE (0x3d4)
+#define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE (0x3d5)
+#define CKM_KEY_WRAP_LYNKS (0x400)
+#define CKM_KEY_WRAP_SET_OAEP (0x401)
+#define CKM_CMS_SIG (0x500)
+#define CKM_KIP_DERIVE (0x510)
+#define CKM_KIP_WRAP (0x511)
+#define CKM_KIP_MAC (0x512)
+#define CKM_CAMELLIA_KEY_GEN (0x550)
+#define CKM_CAMELLIA_ECB (0x551)
+#define CKM_CAMELLIA_CBC (0x552)
+#define CKM_CAMELLIA_MAC (0x553)
+#define CKM_CAMELLIA_MAC_GENERAL (0x554)
+#define CKM_CAMELLIA_CBC_PAD (0x555)
+#define CKM_CAMELLIA_ECB_ENCRYPT_DATA (0x556)
+#define CKM_CAMELLIA_CBC_ENCRYPT_DATA (0x557)
+#define CKM_CAMELLIA_CTR (0x558)
+#define CKM_ARIA_KEY_GEN (0x560)
+#define CKM_ARIA_ECB (0x561)
+#define CKM_ARIA_CBC (0x562)
+#define CKM_ARIA_MAC (0x563)
+#define CKM_ARIA_MAC_GENERAL (0x564)
+#define CKM_ARIA_CBC_PAD (0x565)
+#define CKM_ARIA_ECB_ENCRYPT_DATA (0x566)
+#define CKM_ARIA_CBC_ENCRYPT_DATA (0x567)
+#define CKM_SEED_KEY_GEN (0x650)
+#define CKM_SEED_ECB (0x651)
+#define CKM_SEED_CBC (0x652)
+#define CKM_SEED_MAC (0x653)
+#define CKM_SEED_MAC_GENERAL (0x654)
+#define CKM_SEED_CBC_PAD (0x655)
+#define CKM_SEED_ECB_ENCRYPT_DATA (0x656)
+#define CKM_SEED_CBC_ENCRYPT_DATA (0x657)
+#define CKM_SKIPJACK_KEY_GEN (0x1000)
+#define CKM_SKIPJACK_ECB64 (0x1001)
+#define CKM_SKIPJACK_CBC64 (0x1002)
+#define CKM_SKIPJACK_OFB64 (0x1003)
+#define CKM_SKIPJACK_CFB64 (0x1004)
+#define CKM_SKIPJACK_CFB32 (0x1005)
+#define CKM_SKIPJACK_CFB16 (0x1006)
+#define CKM_SKIPJACK_CFB8 (0x1007)
+#define CKM_SKIPJACK_WRAP (0x1008)
+#define CKM_SKIPJACK_PRIVATE_WRAP (0x1009)
+#define CKM_SKIPJACK_RELAYX (0x100a)
+#define CKM_KEA_KEY_PAIR_GEN (0x1010)
+#define CKM_KEA_KEY_DERIVE (0x1011)
+#define CKM_FORTEZZA_TIMESTAMP (0x1020)
+#define CKM_BATON_KEY_GEN (0x1030)
+#define CKM_BATON_ECB128 (0x1031)
+#define CKM_BATON_ECB96 (0x1032)
+#define CKM_BATON_CBC128 (0x1033)
+#define CKM_BATON_COUNTER (0x1034)
+#define CKM_BATON_SHUFFLE (0x1035)
+#define CKM_BATON_WRAP (0x1036)
+#define CKM_ECDSA_KEY_PAIR_GEN (0x1040)
+#define CKM_EC_KEY_PAIR_GEN (0x1040)
+#define CKM_ECDSA (0x1041)
+#define CKM_ECDSA_SHA1 (0x1042)
+#define CKM_ECDSA_SHA224 (0x1043)
+#define CKM_ECDSA_SHA256 (0x1044)
+#define CKM_ECDSA_SHA384 (0x1045)
+#define CKM_ECDSA_SHA512 (0x1046)
+#define CKM_ECDH1_DERIVE (0x1050)
+#define CKM_ECDH1_COFACTOR_DERIVE (0x1051)
+#define CKM_ECMQV_DERIVE (0x1052)
+#define CKM_JUNIPER_KEY_GEN (0x1060)
+#define CKM_JUNIPER_ECB128 (0x1061)
+#define CKM_JUNIPER_CBC128 (0x1062)
+#define CKM_JUNIPER_COUNTER (0x1063)
+#define CKM_JUNIPER_SHUFFLE (0x1064)
+#define CKM_JUNIPER_WRAP (0x1065)
+#define CKM_FASTHASH (0x1070)
+#define CKM_AES_KEY_GEN (0x1080)
+#define CKM_AES_ECB (0x1081)
+#define CKM_AES_CBC (0x1082)
+#define CKM_AES_MAC (0x1083)
+#define CKM_AES_MAC_GENERAL (0x1084)
+#define CKM_AES_CBC_PAD (0x1085)
+#define CKM_AES_CTR (0x1086)
+#define CKM_AES_GCM (0x1087)
+#define CKM_AES_CCM (0x1088)
+#define CKM_AES_CTS (0x1089)
+#define CKM_AES_CMAC (0x108a)
+#define CKM_AES_CMAC_GENERAL (0x108b)
+#define CKM_BLOWFISH_KEY_GEN (0x1090)
+#define CKM_BLOWFISH_CBC (0x1091)
+#define CKM_TWOFISH_KEY_GEN (0x1092)
+#define CKM_TWOFISH_CBC (0x1093)
+#define CKM_BLOWFISH_CBC_PAD (0x1094)
+#define CKM_TWOFISH_CBC_PAD (0x1095)
+#define CKM_DES_ECB_ENCRYPT_DATA (0x1100)
+#define CKM_DES_CBC_ENCRYPT_DATA (0x1101)
+#define CKM_DES3_ECB_ENCRYPT_DATA (0x1102)
+#define CKM_DES3_CBC_ENCRYPT_DATA (0x1103)
+#define CKM_AES_ECB_ENCRYPT_DATA (0x1104)
+#define CKM_AES_CBC_ENCRYPT_DATA (0x1105)
+#define CKM_GOSTR3410_KEY_PAIR_GEN (0x1200)
+#define CKM_GOSTR3410 (0x1201)
+#define CKM_GOSTR3410_WITH_GOSTR3411 (0x1202)
+#define CKM_GOSTR3410_KEY_WRAP (0x1203)
+#define CKM_GOSTR3410_DERIVE (0x1204)
+#define CKM_GOSTR3411 (0x1210)
+#define CKM_GOSTR3411_HMAC (0x1211)
+#define CKM_GOST28147_KEY_GEN (0x1220)
+#define CKM_GOST28147_ECB (0x1221)
+#define CKM_GOST28147 (0x1222)
+#define CKM_GOST28147_MAC (0x1223)
+#define CKM_GOST28147_KEY_WRAP (0x1224)
+#define CKM_DSA_PARAMETER_GEN (0x2000)
+#define CKM_DH_PKCS_PARAMETER_GEN (0x2001)
+#define CKM_X9_42_DH_PARAMETER_GEN (0x2002)
+#define CKM_AES_OFB (0x2104)
+#define CKM_AES_CFB64 (0x2105)
+#define CKM_AES_CFB8 (0x2106)
+#define CKM_AES_CFB128 (0x2107)
+#define CKM_AES_KEY_WRAP (0x2109)
+#define CKM_AES_KEY_WRAP_PAD (0x210a)
+#define CKM_RSA_PKCS_TPM_1_1 (0x4001)
+#define CKM_RSA_PKCS_OAEPTPM_1_1 (0x4002)
+#define CKM_VENDOR_DEFINED ((unsigned long) (1ul << 31))
+
+
+struct ck_mechanism
+{
+ ck_mechanism_type_t mechanism;
+ void *parameter;
+ unsigned long parameter_len;
+};
+
+
+struct ck_mechanism_info
+{
+ unsigned long min_key_size;
+ unsigned long max_key_size;
+ ck_flags_t flags;
+};
+
+#define CKF_HW (1 << 0)
+#define CKF_ENCRYPT (1 << 8)
+#define CKF_DECRYPT (1 << 9)
+#define CKF_DIGEST (1 << 10)
+#define CKF_SIGN (1 << 11)
+#define CKF_SIGN_RECOVER (1 << 12)
+#define CKF_VERIFY (1 << 13)
+#define CKF_VERIFY_RECOVER (1 << 14)
+#define CKF_GENERATE (1 << 15)
+#define CKF_GENERATE_KEY_PAIR (1 << 16)
+#define CKF_WRAP (1 << 17)
+#define CKF_UNWRAP (1 << 18)
+#define CKF_DERIVE (1 << 19)
+#define CKF_EC_F_P (1 << 20)
+#define CKF_EC_F_2M (1 << 21)
+#define CKF_EC_ECPARAMETERS (1 << 22)
+#define CKF_EC_NAMEDCURVE (1 << 23)
+#define CKF_EC_UNCOMPRESS (1 << 24)
+#define CKF_EC_COMPRESS (1 << 25)
+#define CKF_EXTENSION ((unsigned long) (1ul << 31))
+
+
+/* The following MGFs are defined */
+#define CKG_MGF1_SHA1 (0x00000001)
+#define CKG_MGF1_SHA256 (0x00000002)
+#define CKG_MGF1_SHA384 (0x00000003)
+#define CKG_MGF1_SHA512 (0x00000004)
+#define CKG_MGF1_SHA224 (0x00000005)
+
+#define CKZ_DATA_SPECIFIED (0x00000001)
+
+struct ck_rsa_pkcs_oaep_params {
+ ck_mechanism_type_t hash_alg;
+ unsigned long mgf;
+ unsigned long source;
+ void *source_data;
+ unsigned long source_data_len;
+};
+
+struct ck_rsa_pkcs_pss_params {
+ ck_mechanism_type_t hash_alg;
+ unsigned long mgf;
+ unsigned long slen;
+};
+
+typedef unsigned long ck_ec_kdf_type_t;
+
+/* The following EC Key Derivation Functions are defined */
+#define CKD_NULL (0x00000001)
+#define CKD_SHA1_KDF (0x00000002)
+
+struct ck_ecdh1_derive_params {
+ ck_ec_kdf_type_t kdf;
+ unsigned long shared_data_len;
+ unsigned char *shared_data;
+ unsigned long public_data_len;
+ unsigned char *public_data;
+};
+
+struct ck_ecdh2_derive_params {
+ ck_ec_kdf_type_t kdf;
+ unsigned long shared_data_len;
+ unsigned char *shared_data;
+ unsigned long public_data_len;
+ unsigned char *public_data;
+ unsigned long private_data_len;
+ ck_object_handle_t private_data;
+ unsigned long public_data_len2;
+ unsigned char *public_data2;
+};
+
+struct ck_ecmqv_derive_params {
+ ck_ec_kdf_type_t kdf;
+ unsigned long shared_data_len;
+ unsigned char *shared_data;
+ unsigned long public_data_len;
+ unsigned char *public_data;
+ unsigned long private_data_len;
+ ck_object_handle_t private_data;
+ unsigned long public_data_len2;
+ unsigned char *public_data2;
+ ck_object_handle_t public_key;
+};
+
+typedef unsigned long ck_x9_42_dh_kdf_type_t;
+
+/* The following X9.42 DH key derivation functions are defined */
+#define CKD_SHA1_KDF_ASN1 (0x00000003)
+#define CKD_SHA1_KDF_CONCATENATE (0x00000004)
+#define CKD_SHA224_KDF (0x00000005)
+#define CKD_SHA256_KDF (0x00000006)
+#define CKD_SHA384_KDF (0x00000007)
+#define CKD_SHA512_KDF (0x00000008)
+#define CKD_CPDIVERSIFY_KDF (0x00000009)
+
+struct ck_x9_42_dh1_derive_params {
+ ck_x9_42_dh_kdf_type_t kdf;
+ unsigned long other_info_len;
+ unsigned char *other_info;
+ unsigned long public_data_len;
+ unsigned char *public_data;
+};
+
+struct ck_x9_42_dh2_derive_params {
+ ck_x9_42_dh_kdf_type_t kdf;
+ unsigned long other_info_len;
+ unsigned char *other_info;
+ unsigned long public_data_len;
+ unsigned char *public_data;
+ unsigned long private_data_len;
+ ck_object_handle_t private_data;
+ unsigned long public_data_len2;
+ unsigned char *public_data2;
+};
+
+struct ck_x9_42_mqv_derive_params {
+ ck_x9_42_dh_kdf_type_t kdf;
+ unsigned long other_info_len;
+ unsigned char *other_info;
+ unsigned long public_data_len;
+ unsigned char *public_data;
+ unsigned long private_data_len;
+ ck_object_handle_t private_data;
+ unsigned long public_data_len2;
+ unsigned char *public_data2;
+ ck_object_handle_t public_key;
+};
+
+struct ck_des_cbc_encrypt_data_params {
+ unsigned char iv[8];
+ unsigned char *data;
+ unsigned long length;
+};
+
+struct ck_aes_cbc_encrypt_data_params {
+ unsigned char iv[16];
+ unsigned char *data;
+ unsigned long length;
+};
+
+struct ck_key_derivation_string_data {
+ unsigned char *data;
+ unsigned long len;
+};
+
+/* Flags for C_WaitForSlotEvent. */
+#define CKF_DONT_BLOCK (1)
+
+
+typedef unsigned long ck_rv_t;
+
+
+typedef ck_rv_t (*ck_notify_t) (ck_session_handle_t session,
+ ck_notification_t event, void *application);
+
+/* Forward reference. */
+struct ck_function_list;
+
+#define _CK_DECLARE_FUNCTION(name, args) \
+typedef ck_rv_t (*CK_ ## name) args; \
+ck_rv_t CK_SPEC name args
+
+_CK_DECLARE_FUNCTION (C_Initialize, (void *init_args));
+_CK_DECLARE_FUNCTION (C_Finalize, (void *reserved));
+_CK_DECLARE_FUNCTION (C_GetInfo, (struct ck_info *info));
+_CK_DECLARE_FUNCTION (C_GetFunctionList,
+ (struct ck_function_list **function_list));
+
+_CK_DECLARE_FUNCTION (C_GetSlotList,
+ (unsigned char token_present, ck_slot_id_t *slot_list,
+ unsigned long *count));
+_CK_DECLARE_FUNCTION (C_GetSlotInfo,
+ (ck_slot_id_t slot_id, struct ck_slot_info *info));
+_CK_DECLARE_FUNCTION (C_GetTokenInfo,
+ (ck_slot_id_t slot_id, struct ck_token_info *info));
+_CK_DECLARE_FUNCTION (C_WaitForSlotEvent,
+ (ck_flags_t flags, ck_slot_id_t *slot, void *reserved));
+_CK_DECLARE_FUNCTION (C_GetMechanismList,
+ (ck_slot_id_t slot_id,
+ ck_mechanism_type_t *mechanism_list,
+ unsigned long *count));
+_CK_DECLARE_FUNCTION (C_GetMechanismInfo,
+ (ck_slot_id_t slot_id, ck_mechanism_type_t type,
+ struct ck_mechanism_info *info));
+_CK_DECLARE_FUNCTION (C_InitToken,
+ (ck_slot_id_t slot_id, unsigned char *pin,
+ unsigned long pin_len, unsigned char *label));
+_CK_DECLARE_FUNCTION (C_InitPIN,
+ (ck_session_handle_t session, unsigned char *pin,
+ unsigned long pin_len));
+_CK_DECLARE_FUNCTION (C_SetPIN,
+ (ck_session_handle_t session, unsigned char *old_pin,
+ unsigned long old_len, unsigned char *new_pin,
+ unsigned long new_len));
+
+_CK_DECLARE_FUNCTION (C_OpenSession,
+ (ck_slot_id_t slot_id, ck_flags_t flags,
+ void *application, ck_notify_t notify,
+ ck_session_handle_t *session));
+_CK_DECLARE_FUNCTION (C_CloseSession, (ck_session_handle_t session));
+_CK_DECLARE_FUNCTION (C_CloseAllSessions, (ck_slot_id_t slot_id));
+_CK_DECLARE_FUNCTION (C_GetSessionInfo,
+ (ck_session_handle_t session,
+ struct ck_session_info *info));
+_CK_DECLARE_FUNCTION (C_GetOperationState,
+ (ck_session_handle_t session,
+ unsigned char *operation_state,
+ unsigned long *operation_state_len));
+_CK_DECLARE_FUNCTION (C_SetOperationState,
+ (ck_session_handle_t session,
+ unsigned char *operation_state,
+ unsigned long operation_state_len,
+ ck_object_handle_t encryption_key,
+ ck_object_handle_t authentiation_key));
+_CK_DECLARE_FUNCTION (C_Login,
+ (ck_session_handle_t session, ck_user_type_t user_type,
+ unsigned char *pin, unsigned long pin_len));
+_CK_DECLARE_FUNCTION (C_Logout, (ck_session_handle_t session));
+
+_CK_DECLARE_FUNCTION (C_CreateObject,
+ (ck_session_handle_t session,
+ struct ck_attribute *templ,
+ unsigned long count, ck_object_handle_t *object));
+_CK_DECLARE_FUNCTION (C_CopyObject,
+ (ck_session_handle_t session, ck_object_handle_t object,
+ struct ck_attribute *templ, unsigned long count,
+ ck_object_handle_t *new_object));
+_CK_DECLARE_FUNCTION (C_DestroyObject,
+ (ck_session_handle_t session,
+ ck_object_handle_t object));
+_CK_DECLARE_FUNCTION (C_GetObjectSize,
+ (ck_session_handle_t session,
+ ck_object_handle_t object,
+ unsigned long *size));
+_CK_DECLARE_FUNCTION (C_GetAttributeValue,
+ (ck_session_handle_t session,
+ ck_object_handle_t object,
+ struct ck_attribute *templ,
+ unsigned long count));
+_CK_DECLARE_FUNCTION (C_SetAttributeValue,
+ (ck_session_handle_t session,
+ ck_object_handle_t object,
+ struct ck_attribute *templ,
+ unsigned long count));
+_CK_DECLARE_FUNCTION (C_FindObjectsInit,
+ (ck_session_handle_t session,
+ struct ck_attribute *templ,
+ unsigned long count));
+_CK_DECLARE_FUNCTION (C_FindObjects,
+ (ck_session_handle_t session,
+ ck_object_handle_t *object,
+ unsigned long max_object_count,
+ unsigned long *object_count));
+_CK_DECLARE_FUNCTION (C_FindObjectsFinal,
+ (ck_session_handle_t session));
+
+_CK_DECLARE_FUNCTION (C_EncryptInit,
+ (ck_session_handle_t session,
+ struct ck_mechanism *mechanism,
+ ck_object_handle_t key));
+_CK_DECLARE_FUNCTION (C_Encrypt,
+ (ck_session_handle_t session,
+ unsigned char *data, unsigned long data_len,
+ unsigned char *encrypted_data,
+ unsigned long *encrypted_data_len));
+_CK_DECLARE_FUNCTION (C_EncryptUpdate,
+ (ck_session_handle_t session,
+ unsigned char *part, unsigned long part_len,
+ unsigned char *encrypted_part,
+ unsigned long *encrypted_part_len));
+_CK_DECLARE_FUNCTION (C_EncryptFinal,
+ (ck_session_handle_t session,
+ unsigned char *last_encrypted_part,
+ unsigned long *last_encrypted_part_len));
+
+_CK_DECLARE_FUNCTION (C_DecryptInit,
+ (ck_session_handle_t session,
+ struct ck_mechanism *mechanism,
+ ck_object_handle_t key));
+_CK_DECLARE_FUNCTION (C_Decrypt,
+ (ck_session_handle_t session,
+ unsigned char *encrypted_data,
+ unsigned long encrypted_data_len,
+ unsigned char *data, unsigned long *data_len));
+_CK_DECLARE_FUNCTION (C_DecryptUpdate,
+ (ck_session_handle_t session,
+ unsigned char *encrypted_part,
+ unsigned long encrypted_part_len,
+ unsigned char *part, unsigned long *part_len));
+_CK_DECLARE_FUNCTION (C_DecryptFinal,
+ (ck_session_handle_t session,
+ unsigned char *last_part,
+ unsigned long *last_part_len));
+
+_CK_DECLARE_FUNCTION (C_DigestInit,
+ (ck_session_handle_t session,
+ struct ck_mechanism *mechanism));
+_CK_DECLARE_FUNCTION (C_Digest,
+ (ck_session_handle_t session,
+ unsigned char *data, unsigned long data_len,
+ unsigned char *digest,
+ unsigned long *digest_len));
+_CK_DECLARE_FUNCTION (C_DigestUpdate,
+ (ck_session_handle_t session,
+ unsigned char *part, unsigned long part_len));
+_CK_DECLARE_FUNCTION (C_DigestKey,
+ (ck_session_handle_t session, ck_object_handle_t key));
+_CK_DECLARE_FUNCTION (C_DigestFinal,
+ (ck_session_handle_t session,
+ unsigned char *digest,
+ unsigned long *digest_len));
+
+_CK_DECLARE_FUNCTION (C_SignInit,
+ (ck_session_handle_t session,
+ struct ck_mechanism *mechanism,
+ ck_object_handle_t key));
+_CK_DECLARE_FUNCTION (C_Sign,
+ (ck_session_handle_t session,
+ unsigned char *data, unsigned long data_len,
+ unsigned char *signature,
+ unsigned long *signature_len));
+_CK_DECLARE_FUNCTION (C_SignUpdate,
+ (ck_session_handle_t session,
+ unsigned char *part, unsigned long part_len));
+_CK_DECLARE_FUNCTION (C_SignFinal,
+ (ck_session_handle_t session,
+ unsigned char *signature,
+ unsigned long *signature_len));
+_CK_DECLARE_FUNCTION (C_SignRecoverInit,
+ (ck_session_handle_t session,
+ struct ck_mechanism *mechanism,
+ ck_object_handle_t key));
+_CK_DECLARE_FUNCTION (C_SignRecover,
+ (ck_session_handle_t session,
+ unsigned char *data, unsigned long data_len,
+ unsigned char *signature,
+ unsigned long *signature_len));
+
+_CK_DECLARE_FUNCTION (C_VerifyInit,
+ (ck_session_handle_t session,
+ struct ck_mechanism *mechanism,
+ ck_object_handle_t key));
+_CK_DECLARE_FUNCTION (C_Verify,
+ (ck_session_handle_t session,
+ unsigned char *data, unsigned long data_len,
+ unsigned char *signature,
+ unsigned long signature_len));
+_CK_DECLARE_FUNCTION (C_VerifyUpdate,
+ (ck_session_handle_t session,
+ unsigned char *part, unsigned long part_len));
+_CK_DECLARE_FUNCTION (C_VerifyFinal,
+ (ck_session_handle_t session,
+ unsigned char *signature,
+ unsigned long signature_len));
+_CK_DECLARE_FUNCTION (C_VerifyRecoverInit,
+ (ck_session_handle_t session,
+ struct ck_mechanism *mechanism,
+ ck_object_handle_t key));
+_CK_DECLARE_FUNCTION (C_VerifyRecover,
+ (ck_session_handle_t session,
+ unsigned char *signature,
+ unsigned long signature_len,
+ unsigned char *data,
+ unsigned long *data_len));
+
+_CK_DECLARE_FUNCTION (C_DigestEncryptUpdate,
+ (ck_session_handle_t session,
+ unsigned char *part, unsigned long part_len,
+ unsigned char *encrypted_part,
+ unsigned long *encrypted_part_len));
+_CK_DECLARE_FUNCTION (C_DecryptDigestUpdate,
+ (ck_session_handle_t session,
+ unsigned char *encrypted_part,
+ unsigned long encrypted_part_len,
+ unsigned char *part,
+ unsigned long *part_len));
+_CK_DECLARE_FUNCTION (C_SignEncryptUpdate,
+ (ck_session_handle_t session,
+ unsigned char *part, unsigned long part_len,
+ unsigned char *encrypted_part,
+ unsigned long *encrypted_part_len));
+_CK_DECLARE_FUNCTION (C_DecryptVerifyUpdate,
+ (ck_session_handle_t session,
+ unsigned char *encrypted_part,
+ unsigned long encrypted_part_len,
+ unsigned char *part,
+ unsigned long *part_len));
+
+_CK_DECLARE_FUNCTION (C_GenerateKey,
+ (ck_session_handle_t session,
+ struct ck_mechanism *mechanism,
+ struct ck_attribute *templ,
+ unsigned long count,
+ ck_object_handle_t *key));
+_CK_DECLARE_FUNCTION (C_GenerateKeyPair,
+ (ck_session_handle_t session,
+ struct ck_mechanism *mechanism,
+ struct ck_attribute *public_key_template,
+ unsigned long public_key_attribute_count,
+ struct ck_attribute *private_key_template,
+ unsigned long private_key_attribute_count,
+ ck_object_handle_t *public_key,
+ ck_object_handle_t *private_key));
+_CK_DECLARE_FUNCTION (C_WrapKey,
+ (ck_session_handle_t session,
+ struct ck_mechanism *mechanism,
+ ck_object_handle_t wrapping_key,
+ ck_object_handle_t key,
+ unsigned char *wrapped_key,
+ unsigned long *wrapped_key_len));
+_CK_DECLARE_FUNCTION (C_UnwrapKey,
+ (ck_session_handle_t session,
+ struct ck_mechanism *mechanism,
+ ck_object_handle_t unwrapping_key,
+ unsigned char *wrapped_key,
+ unsigned long wrapped_key_len,
+ struct ck_attribute *templ,
+ unsigned long attribute_count,
+ ck_object_handle_t *key));
+_CK_DECLARE_FUNCTION (C_DeriveKey,
+ (ck_session_handle_t session,
+ struct ck_mechanism *mechanism,
+ ck_object_handle_t base_key,
+ struct ck_attribute *templ,
+ unsigned long attribute_count,
+ ck_object_handle_t *key));
+
+_CK_DECLARE_FUNCTION (C_SeedRandom,
+ (ck_session_handle_t session, unsigned char *seed,
+ unsigned long seed_len));
+_CK_DECLARE_FUNCTION (C_GenerateRandom,
+ (ck_session_handle_t session,
+ unsigned char *random_data,
+ unsigned long random_len));
+
+_CK_DECLARE_FUNCTION (C_GetFunctionStatus, (ck_session_handle_t session));
+_CK_DECLARE_FUNCTION (C_CancelFunction, (ck_session_handle_t session));
+
+
+struct ck_function_list
+{
+ struct ck_version version;
+ CK_C_Initialize C_Initialize;
+ CK_C_Finalize C_Finalize;
+ CK_C_GetInfo C_GetInfo;
+ CK_C_GetFunctionList C_GetFunctionList;
+ CK_C_GetSlotList C_GetSlotList;
+ CK_C_GetSlotInfo C_GetSlotInfo;
+ CK_C_GetTokenInfo C_GetTokenInfo;
+ CK_C_GetMechanismList C_GetMechanismList;
+ CK_C_GetMechanismInfo C_GetMechanismInfo;
+ CK_C_InitToken C_InitToken;
+ CK_C_InitPIN C_InitPIN;
+ CK_C_SetPIN C_SetPIN;
+ CK_C_OpenSession C_OpenSession;
+ CK_C_CloseSession C_CloseSession;
+ CK_C_CloseAllSessions C_CloseAllSessions;
+ CK_C_GetSessionInfo C_GetSessionInfo;
+ CK_C_GetOperationState C_GetOperationState;
+ CK_C_SetOperationState C_SetOperationState;
+ CK_C_Login C_Login;
+ CK_C_Logout C_Logout;
+ CK_C_CreateObject C_CreateObject;
+ CK_C_CopyObject C_CopyObject;
+ CK_C_DestroyObject C_DestroyObject;
+ CK_C_GetObjectSize C_GetObjectSize;
+ CK_C_GetAttributeValue C_GetAttributeValue;
+ CK_C_SetAttributeValue C_SetAttributeValue;
+ CK_C_FindObjectsInit C_FindObjectsInit;
+ CK_C_FindObjects C_FindObjects;
+ CK_C_FindObjectsFinal C_FindObjectsFinal;
+ CK_C_EncryptInit C_EncryptInit;
+ CK_C_Encrypt C_Encrypt;
+ CK_C_EncryptUpdate C_EncryptUpdate;
+ CK_C_EncryptFinal C_EncryptFinal;
+ CK_C_DecryptInit C_DecryptInit;
+ CK_C_Decrypt C_Decrypt;
+ CK_C_DecryptUpdate C_DecryptUpdate;
+ CK_C_DecryptFinal C_DecryptFinal;
+ CK_C_DigestInit C_DigestInit;
+ CK_C_Digest C_Digest;
+ CK_C_DigestUpdate C_DigestUpdate;
+ CK_C_DigestKey C_DigestKey;
+ CK_C_DigestFinal C_DigestFinal;
+ CK_C_SignInit C_SignInit;
+ CK_C_Sign C_Sign;
+ CK_C_SignUpdate C_SignUpdate;
+ CK_C_SignFinal C_SignFinal;
+ CK_C_SignRecoverInit C_SignRecoverInit;
+ CK_C_SignRecover C_SignRecover;
+ CK_C_VerifyInit C_VerifyInit;
+ CK_C_Verify C_Verify;
+ CK_C_VerifyUpdate C_VerifyUpdate;
+ CK_C_VerifyFinal C_VerifyFinal;
+ CK_C_VerifyRecoverInit C_VerifyRecoverInit;
+ CK_C_VerifyRecover C_VerifyRecover;
+ CK_C_DigestEncryptUpdate C_DigestEncryptUpdate;
+ CK_C_DecryptDigestUpdate C_DecryptDigestUpdate;
+ CK_C_SignEncryptUpdate C_SignEncryptUpdate;
+ CK_C_DecryptVerifyUpdate C_DecryptVerifyUpdate;
+ CK_C_GenerateKey C_GenerateKey;
+ CK_C_GenerateKeyPair C_GenerateKeyPair;
+ CK_C_WrapKey C_WrapKey;
+ CK_C_UnwrapKey C_UnwrapKey;
+ CK_C_DeriveKey C_DeriveKey;
+ CK_C_SeedRandom C_SeedRandom;
+ CK_C_GenerateRandom C_GenerateRandom;
+ CK_C_GetFunctionStatus C_GetFunctionStatus;
+ CK_C_CancelFunction C_CancelFunction;
+ CK_C_WaitForSlotEvent C_WaitForSlotEvent;
+};
+
+
+typedef ck_rv_t (*ck_createmutex_t) (void **mutex);
+typedef ck_rv_t (*ck_destroymutex_t) (void *mutex);
+typedef ck_rv_t (*ck_lockmutex_t) (void *mutex);
+typedef ck_rv_t (*ck_unlockmutex_t) (void *mutex);
+
+
+struct ck_c_initialize_args
+{
+ ck_createmutex_t create_mutex;
+ ck_destroymutex_t destroy_mutex;
+ ck_lockmutex_t lock_mutex;
+ ck_unlockmutex_t unlock_mutex;
+ ck_flags_t flags;
+ void *reserved;
+};
+
+
+#define CKF_LIBRARY_CANT_CREATE_OS_THREADS (1 << 0)
+#define CKF_OS_LOCKING_OK (1 << 1)
+
+#define CKR_OK (0)
+#define CKR_CANCEL (1)
+#define CKR_HOST_MEMORY (2)
+#define CKR_SLOT_ID_INVALID (3)
+#define CKR_GENERAL_ERROR (5)
+#define CKR_FUNCTION_FAILED (6)
+#define CKR_ARGUMENTS_BAD (7)
+#define CKR_NO_EVENT (8)
+#define CKR_NEED_TO_CREATE_THREADS (9)
+#define CKR_CANT_LOCK (0xa)
+#define CKR_ATTRIBUTE_READ_ONLY (0x10)
+#define CKR_ATTRIBUTE_SENSITIVE (0x11)
+#define CKR_ATTRIBUTE_TYPE_INVALID (0x12)
+#define CKR_ATTRIBUTE_VALUE_INVALID (0x13)
+#define CKR_COPY_PROHIBITED (0x1A)
+#define CKR_DATA_INVALID (0x20)
+#define CKR_DATA_LEN_RANGE (0x21)
+#define CKR_DEVICE_ERROR (0x30)
+#define CKR_DEVICE_MEMORY (0x31)
+#define CKR_DEVICE_REMOVED (0x32)
+#define CKR_ENCRYPTED_DATA_INVALID (0x40)
+#define CKR_ENCRYPTED_DATA_LEN_RANGE (0x41)
+#define CKR_FUNCTION_CANCELED (0x50)
+#define CKR_FUNCTION_NOT_PARALLEL (0x51)
+#define CKR_FUNCTION_NOT_SUPPORTED (0x54)
+#define CKR_KEY_HANDLE_INVALID (0x60)
+#define CKR_KEY_SIZE_RANGE (0x62)
+#define CKR_KEY_TYPE_INCONSISTENT (0x63)
+#define CKR_KEY_NOT_NEEDED (0x64)
+#define CKR_KEY_CHANGED (0x65)
+#define CKR_KEY_NEEDED (0x66)
+#define CKR_KEY_INDIGESTIBLE (0x67)
+#define CKR_KEY_FUNCTION_NOT_PERMITTED (0x68)
+#define CKR_KEY_NOT_WRAPPABLE (0x69)
+#define CKR_KEY_UNEXTRACTABLE (0x6a)
+#define CKR_MECHANISM_INVALID (0x70)
+#define CKR_MECHANISM_PARAM_INVALID (0x71)
+#define CKR_OBJECT_HANDLE_INVALID (0x82)
+#define CKR_OPERATION_ACTIVE (0x90)
+#define CKR_OPERATION_NOT_INITIALIZED (0x91)
+#define CKR_PIN_INCORRECT (0xa0)
+#define CKR_PIN_INVALID (0xa1)
+#define CKR_PIN_LEN_RANGE (0xa2)
+#define CKR_PIN_EXPIRED (0xa3)
+#define CKR_PIN_LOCKED (0xa4)
+#define CKR_SESSION_CLOSED (0xb0)
+#define CKR_SESSION_COUNT (0xb1)
+#define CKR_SESSION_HANDLE_INVALID (0xb3)
+#define CKR_SESSION_PARALLEL_NOT_SUPPORTED (0xb4)
+#define CKR_SESSION_READ_ONLY (0xb5)
+#define CKR_SESSION_EXISTS (0xb6)
+#define CKR_SESSION_READ_ONLY_EXISTS (0xb7)
+#define CKR_SESSION_READ_WRITE_SO_EXISTS (0xb8)
+#define CKR_SIGNATURE_INVALID (0xc0)
+#define CKR_SIGNATURE_LEN_RANGE (0xc1)
+#define CKR_TEMPLATE_INCOMPLETE (0xd0)
+#define CKR_TEMPLATE_INCONSISTENT (0xd1)
+#define CKR_TOKEN_NOT_PRESENT (0xe0)
+#define CKR_TOKEN_NOT_RECOGNIZED (0xe1)
+#define CKR_TOKEN_WRITE_PROTECTED (0xe2)
+#define CKR_UNWRAPPING_KEY_HANDLE_INVALID (0xf0)
+#define CKR_UNWRAPPING_KEY_SIZE_RANGE (0xf1)
+#define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT (0xf2)
+#define CKR_USER_ALREADY_LOGGED_IN (0x100)
+#define CKR_USER_NOT_LOGGED_IN (0x101)
+#define CKR_USER_PIN_NOT_INITIALIZED (0x102)
+#define CKR_USER_TYPE_INVALID (0x103)
+#define CKR_USER_ANOTHER_ALREADY_LOGGED_IN (0x104)
+#define CKR_USER_TOO_MANY_TYPES (0x105)
+#define CKR_WRAPPED_KEY_INVALID (0x110)
+#define CKR_WRAPPED_KEY_LEN_RANGE (0x112)
+#define CKR_WRAPPING_KEY_HANDLE_INVALID (0x113)
+#define CKR_WRAPPING_KEY_SIZE_RANGE (0x114)
+#define CKR_WRAPPING_KEY_TYPE_INCONSISTENT (0x115)
+#define CKR_RANDOM_SEED_NOT_SUPPORTED (0x120)
+#define CKR_RANDOM_NO_RNG (0x121)
+#define CKR_DOMAIN_PARAMS_INVALID (0x130)
+#define CKR_BUFFER_TOO_SMALL (0x150)
+#define CKR_SAVED_STATE_INVALID (0x160)
+#define CKR_INFORMATION_SENSITIVE (0x170)
+#define CKR_STATE_UNSAVEABLE (0x180)
+#define CKR_CRYPTOKI_NOT_INITIALIZED (0x190)
+#define CKR_CRYPTOKI_ALREADY_INITIALIZED (0x191)
+#define CKR_MUTEX_BAD (0x1a0)
+#define CKR_MUTEX_NOT_LOCKED (0x1a1)
+#define CKR_NEW_PIN_MODE (0x1b0)
+#define CKR_NEXT_OTP (0x1b1)
+#define CKR_EXCEEDED_MAX_ITERATIONS (0x1b5)
+#define CKR_FIPS_SELF_TEST_FAILED (0x1b6)
+#define CKR_LIBRARY_LOAD_FAILED (0x1b7)
+#define CKR_PIN_TOO_WEAK (0x1b8)
+#define CKR_PUBLIC_KEY_INVALID (0x1b9)
+#define CKR_FUNCTION_REJECTED (0x200)
+#define CKR_VENDOR_DEFINED ((unsigned long) (1ul << 31))
+
+
+
+/* Compatibility layer. */
+
+#ifdef CRYPTOKI_COMPAT
+
+#undef CK_DEFINE_FUNCTION
+#define CK_DEFINE_FUNCTION(retval, name) retval CK_SPEC name
+
+/* For NULL. */
+#include <stddef.h>
+
+typedef unsigned char CK_BYTE;
+typedef unsigned char CK_CHAR;
+typedef unsigned char CK_UTF8CHAR;
+typedef unsigned char CK_BBOOL;
+typedef unsigned long int CK_ULONG;
+typedef long int CK_LONG;
+typedef CK_BYTE *CK_BYTE_PTR;
+typedef CK_CHAR *CK_CHAR_PTR;
+typedef CK_UTF8CHAR *CK_UTF8CHAR_PTR;
+typedef CK_ULONG *CK_ULONG_PTR;
+typedef void *CK_VOID_PTR;
+typedef void **CK_VOID_PTR_PTR;
+#define CK_FALSE 0
+#define CK_TRUE 1
+#ifndef CK_DISABLE_TRUE_FALSE
+#ifndef FALSE
+#define FALSE 0
+#endif
+#ifndef TRUE
+#define TRUE 1
+#endif
+#endif
+
+typedef struct ck_version CK_VERSION;
+typedef struct ck_version *CK_VERSION_PTR;
+
+typedef struct ck_info CK_INFO;
+typedef struct ck_info *CK_INFO_PTR;
+
+typedef ck_slot_id_t *CK_SLOT_ID_PTR;
+
+typedef struct ck_slot_info CK_SLOT_INFO;
+typedef struct ck_slot_info *CK_SLOT_INFO_PTR;
+
+typedef struct ck_token_info CK_TOKEN_INFO;
+typedef struct ck_token_info *CK_TOKEN_INFO_PTR;
+
+typedef ck_session_handle_t *CK_SESSION_HANDLE_PTR;
+
+typedef struct ck_session_info CK_SESSION_INFO;
+typedef struct ck_session_info *CK_SESSION_INFO_PTR;
+
+typedef ck_object_handle_t *CK_OBJECT_HANDLE_PTR;
+
+typedef ck_object_class_t *CK_OBJECT_CLASS_PTR;
+
+typedef struct ck_attribute CK_ATTRIBUTE;
+typedef struct ck_attribute *CK_ATTRIBUTE_PTR;
+
+typedef struct ck_date CK_DATE;
+typedef struct ck_date *CK_DATE_PTR;
+
+typedef ck_mechanism_type_t *CK_MECHANISM_TYPE_PTR;
+
+typedef struct ck_mechanism CK_MECHANISM;
+typedef struct ck_mechanism *CK_MECHANISM_PTR;
+
+typedef struct ck_mechanism_info CK_MECHANISM_INFO;
+typedef struct ck_mechanism_info *CK_MECHANISM_INFO_PTR;
+
+typedef struct ck_rsa_pkcs_oaep_params CK_RSA_PKCS_OAEP_PARAMS;
+typedef struct ck_rsa_pkcs_oaep_params *CK_RSA_PKCS_OAEP_PARAMS_PTR;
+
+typedef struct ck_rsa_pkcs_pss_params CK_RSA_PKCS_PSS_PARAMS;
+typedef struct ck_rsa_pkcs_pss_params *CK_RSA_PKCS_PSS_PARAMS_PTR;
+
+typedef struct ck_ecdh1_derive_params CK_ECDH1_DERIVE_PARAMS;
+typedef struct ck_ecdh1_derive_params *CK_ECDH1_DERIVE_PARAMS_PTR;
+
+typedef struct ck_des_cbc_encrypt_data_params CK_DES_CBC_ENCRYPT_DATA_PARAMS;
+typedef struct ck_des_cbc_encrypt_data_params *CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR;
+
+typedef struct ck_aes_cbc_encrypt_data_params CK_AES_CBC_ENCRYPT_DATA_PARAMS;
+typedef struct ck_aes_cbc_encrypt_data_params *CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR;
+
+typedef struct ck_key_derivation_string_data CK_KEY_DERIVATION_STRING_DATA;
+typedef struct ck_key_derivation_string_data *CK_KEY_DERIVATION_STRING_DATA_PTR;
+
+typedef struct ck_function_list CK_FUNCTION_LIST;
+typedef struct ck_function_list *CK_FUNCTION_LIST_PTR;
+typedef struct ck_function_list **CK_FUNCTION_LIST_PTR_PTR;
+
+typedef struct ck_c_initialize_args CK_C_INITIALIZE_ARGS;
+typedef struct ck_c_initialize_args *CK_C_INITIALIZE_ARGS_PTR;
+
+#define NULL_PTR NULL
+
+/* Delete the helper macros defined at the top of the file. */
+#undef ck_flags_t
+#undef ck_version
+
+#undef ck_info
+#undef cryptoki_version
+#undef manufacturer_id
+#undef library_description
+#undef library_version
+
+#undef ck_notification_t
+#undef ck_slot_id_t
+
+#undef ck_slot_info
+#undef slot_description
+#undef hardware_version
+#undef firmware_version
+
+#undef ck_token_info
+#undef serial_number
+#undef max_session_count
+#undef session_count
+#undef max_rw_session_count
+#undef rw_session_count
+#undef max_pin_len
+#undef min_pin_len
+#undef total_public_memory
+#undef free_public_memory
+#undef total_private_memory
+#undef free_private_memory
+#undef utc_time
+
+#undef ck_session_handle_t
+#undef ck_user_type_t
+#undef ck_state_t
+
+#undef ck_session_info
+#undef slot_id
+#undef device_error
+
+#undef ck_object_handle_t
+#undef ck_object_class_t
+#undef ck_hw_feature_type_t
+#undef ck_key_type_t
+#undef ck_certificate_type_t
+#undef ck_attribute_type_t
+
+#undef ck_attribute
+#undef value
+#undef value_len
+
+#undef ck_date
+
+#undef ck_mechanism_type_t
+
+#undef ck_mechanism
+#undef parameter
+#undef parameter_len
+
+#undef ck_mechanism_info
+#undef min_key_size
+#undef max_key_size
+
+#undef ck_rsa_pkcs_oaep_params
+#undef hash_alg
+#undef source_data
+#undef source_data_len
+#undef slen
+
+#undef ck_ec_kdf_type_t
+#undef shared_data_len
+#undef shared_data
+#undef public_data_len
+#undef public_data
+#undef private_data_len
+#undef private_data
+#undef public_data_len2
+#undef public_data2
+#undef public_key
+
+#undef ck_x9_42_dh_kdf_type_t
+#undef other_info_len
+#undef other_info
+
+#undef data
+#undef len
+
+#undef ck_rv_t
+#undef ck_notify_t
+
+#undef ck_function_list
+
+#undef ck_createmutex_t
+#undef ck_destroymutex_t
+#undef ck_lockmutex_t
+#undef ck_unlockmutex_t
+
+#undef ck_c_initialize_args
+#undef create_mutex
+#undef destroy_mutex
+#undef lock_mutex
+#undef unlock_mutex
+#undef reserved
+
+#endif /* CRYPTOKI_COMPAT */
+
+
+/* System dependencies. */
+#if defined(_WIN32) || defined(CRYPTOKI_FORCE_WIN32)
+#pragma pack(pop, cryptoki)
+#endif
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif /* PKCS11_H */
diff --git a/third_party/heimdal/lib/hx509/req.c b/third_party/heimdal/lib/hx509/req.c
new file mode 100644
index 0000000..2b3f46d
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/req.c
@@ -0,0 +1,1520 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+#include <pkcs10_asn1.h>
+
+typedef struct abitstring_s {
+ unsigned char *feats;
+ size_t feat_bytes;
+} *abitstring;
+
+struct hx509_request_data {
+ hx509_context context;
+ hx509_name name;
+ SubjectPublicKeyInfo key;
+ KeyUsage ku;
+ ExtKeyUsage eku;
+ GeneralNames san;
+ struct abitstring_s authorized_EKUs;
+ struct abitstring_s authorized_SANs;
+ uint32_t nunsupported; /* Count of unsupported features requested */
+ uint32_t nauthorized; /* Count of supported features authorized */
+ uint32_t ku_are_authorized:1;
+};
+
+/**
+ * Allocate and initialize an hx509_request structure representing a PKCS#10
+ * certificate signing request.
+ *
+ * @param context An hx509 context.
+ * @param req Where to put the new hx509_request object.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_init(hx509_context context, hx509_request *req)
+{
+ *req = calloc(1, sizeof(**req));
+ if (*req == NULL)
+ return ENOMEM;
+
+ (*req)->context = context;
+ return 0;
+}
+
+/**
+ * Free a certificate signing request object.
+ *
+ * @param req A pointer to the hx509_request to free.
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_request_free(hx509_request *reqp)
+{
+ hx509_request req = *reqp;
+
+ *reqp = NULL;
+ if (req == NULL)
+ return;
+ if (req->name)
+ hx509_name_free(&req->name);
+ free(req->authorized_EKUs.feats);
+ free(req->authorized_SANs.feats);
+ free_SubjectPublicKeyInfo(&req->key);
+ free_ExtKeyUsage(&req->eku);
+ free_GeneralNames(&req->san);
+ memset(req, 0, sizeof(*req));
+ free(req);
+}
+
+/**
+ * Set the subjectName of the CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request to alter.
+ * @param name The subjectName.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_set_name(hx509_context context,
+ hx509_request req,
+ hx509_name name)
+{
+ if (req->name)
+ hx509_name_free(&req->name);
+ if (name) {
+ int ret = hx509_name_copy(context, name, &req->name);
+ if (ret)
+ return ret;
+ }
+ return 0;
+}
+
+/**
+ * Get the subject name requested by a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param name Where to put the name.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_get_name(hx509_context context,
+ hx509_request req,
+ hx509_name *name)
+{
+ if (req->name == NULL) {
+ hx509_set_error_string(context, 0, EINVAL, "Request have no name");
+ return EINVAL;
+ }
+ return hx509_name_copy(context, req->name, name);
+}
+
+/**
+ * Set the subject public key requested by a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param key The public key.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_set_SubjectPublicKeyInfo(hx509_context context,
+ hx509_request req,
+ const SubjectPublicKeyInfo *key)
+{
+ free_SubjectPublicKeyInfo(&req->key);
+ return copy_SubjectPublicKeyInfo(key, &req->key);
+}
+
+/**
+ * Get the subject public key requested by a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param key Where to put the key.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_get_SubjectPublicKeyInfo(hx509_context context,
+ hx509_request req,
+ SubjectPublicKeyInfo *key)
+{
+ return copy_SubjectPublicKeyInfo(&req->key, key);
+}
+
+/**
+ * Set the key usage requested by a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param ku The key usage.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_set_ku(hx509_context context, hx509_request req, KeyUsage ku)
+{
+ uint64_t n = KeyUsage2int(ku);
+
+ if ((KeyUsage2int(req->ku) & n) != n)
+ req->ku_are_authorized = 0;
+ req->ku = ku;
+ return 0;
+}
+
+/**
+ * Get the key usage requested by a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param ku Where to put the key usage.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_get_ku(hx509_context context, hx509_request req, KeyUsage *ku)
+{
+ *ku = req->ku;
+ return 0;
+}
+
+/**
+ * Add an extended key usage OID to a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param oid The EKU OID.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_add_eku(hx509_context context,
+ hx509_request req,
+ const heim_oid *oid)
+{
+ void *val;
+ int ret;
+
+ val = realloc(req->eku.val, sizeof(req->eku.val[0]) * (req->eku.len + 1));
+ if (val == NULL)
+ return ENOMEM;
+ req->eku.val = val;
+
+ ret = der_copy_oid(oid, &req->eku.val[req->eku.len]);
+ if (ret)
+ return ret;
+
+ req->eku.len += 1;
+
+ return 0;
+}
+
+/**
+ * Add a GeneralName (Jabber ID) subject alternative name to a CSR.
+ *
+ * XXX Make this take a heim_octet_string, not a GeneralName*.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param gn The GeneralName object.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_add_GeneralName(hx509_context context,
+ hx509_request req,
+ const GeneralName *gn)
+{
+ return add_GeneralNames(&req->san, gn);
+}
+
+static int
+add_utf8_other_san(hx509_context context,
+ GeneralNames *gns,
+ const heim_oid *oid,
+ const char *s)
+{
+ const PKIXXmppAddr us = (const PKIXXmppAddr)(uintptr_t)s;
+ GeneralName gn;
+ size_t size;
+ int ret;
+
+ gn.element = choice_GeneralName_otherName;
+ gn.u.otherName.type_id.length = 0;
+ gn.u.otherName.type_id.components = 0;
+ gn.u.otherName.value.data = NULL;
+ gn.u.otherName.value.length = 0;
+ ret = der_copy_oid(oid, &gn.u.otherName.type_id);
+ if (ret == 0)
+ ASN1_MALLOC_ENCODE(PKIXXmppAddr, gn.u.otherName.value.data,
+ gn.u.otherName.value.length, &us, &size, ret);
+ if (ret == 0 && size != gn.u.otherName.value.length)
+ _hx509_abort("internal ASN.1 encoder error");
+ if (ret == 0)
+ ret = add_GeneralNames(gns, &gn);
+ free_GeneralName(&gn);
+ if (ret)
+ hx509_set_error_string(context, 0, ret, "Out of memory");
+ return ret;
+}
+
+/**
+ * Add an xmppAddr (Jabber ID) subject alternative name to a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param jid The XMPP address.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_add_xmpp_name(hx509_context context,
+ hx509_request req,
+ const char *jid)
+{
+ return add_utf8_other_san(context, &req->san,
+ &asn1_oid_id_pkix_on_xmppAddr, jid);
+}
+
+/**
+ * Add a Microsoft UPN subject alternative name to a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param hostname The XMPP address.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_add_ms_upn_name(hx509_context context,
+ hx509_request req,
+ const char *upn)
+{
+ return add_utf8_other_san(context, &req->san, &asn1_oid_id_pkinit_ms_san,
+ upn);
+}
+
+/**
+ * Add a dNSName (hostname) subject alternative name to a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param hostname The fully-qualified hostname.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_add_dns_name(hx509_context context,
+ hx509_request req,
+ const char *hostname)
+{
+ GeneralName name;
+
+ memset(&name, 0, sizeof(name));
+ name.element = choice_GeneralName_dNSName;
+ name.u.dNSName.data = rk_UNCONST(hostname);
+ name.u.dNSName.length = strlen(hostname);
+
+ return add_GeneralNames(&req->san, &name);
+}
+
+/**
+ * Add a dnsSRV (_service.hostname) subject alternative name to a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param dnssrv The DNS SRV name.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_add_dns_srv(hx509_context context,
+ hx509_request req,
+ const char *dnssrv)
+{
+ GeneralName gn;
+ SRVName n;
+ size_t size;
+ int ret;
+
+ memset(&n, 0, sizeof(n));
+ memset(&gn, 0, sizeof(gn));
+ gn.element = choice_GeneralName_otherName;
+ gn.u.otherName.type_id.length = 0;
+ gn.u.otherName.type_id.components = 0;
+ gn.u.otherName.value.data = NULL;
+ gn.u.otherName.value.length = 0;
+ n.length = strlen(dnssrv);
+ n.data = (void *)(uintptr_t)dnssrv;
+ ASN1_MALLOC_ENCODE(SRVName,
+ gn.u.otherName.value.data,
+ gn.u.otherName.value.length, &n, &size, ret);
+ if (ret == 0)
+ ret = der_copy_oid(&asn1_oid_id_pkix_on_dnsSRV, &gn.u.otherName.type_id);
+ if (ret == 0)
+ ret = add_GeneralNames(&req->san, &gn);
+ free_GeneralName(&gn);
+ return ret;
+}
+
+/**
+ * Add an rfc822Name (e-mail address) subject alternative name to a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param email The e-mail address.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_add_email(hx509_context context,
+ hx509_request req,
+ const char *email)
+{
+ GeneralName name;
+
+ memset(&name, 0, sizeof(name));
+ name.element = choice_GeneralName_rfc822Name;
+ name.u.rfc822Name.data = rk_UNCONST(email);
+ name.u.rfc822Name.length = strlen(email);
+
+ return add_GeneralNames(&req->san, &name);
+}
+
+/**
+ * Add a registeredID (OID) subject alternative name to a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param oid The OID.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_add_registered(hx509_context context,
+ hx509_request req,
+ heim_oid *oid)
+{
+ GeneralName name;
+ int ret;
+
+ memset(&name, 0, sizeof(name));
+ name.element = choice_GeneralName_registeredID;
+ ret = der_copy_oid(oid, &name.u.registeredID);
+ if (ret)
+ return ret;
+ ret = add_GeneralNames(&req->san, &name);
+ free_GeneralName(&name);
+ return ret;
+}
+
+/**
+ * Add a Kerberos V5 principal subject alternative name to a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param princ The Kerberos principal name.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_add_pkinit(hx509_context context,
+ hx509_request req,
+ const char *princ)
+{
+ KRB5PrincipalName kn;
+ GeneralName gn;
+ int ret;
+
+ memset(&kn, 0, sizeof(kn));
+ memset(&gn, 0, sizeof(gn));
+ gn.element = choice_GeneralName_otherName;
+ gn.u.otherName.type_id.length = 0;
+ gn.u.otherName.type_id.components = 0;
+ gn.u.otherName.value.data = NULL;
+ gn.u.otherName.value.length = 0;
+ ret = der_copy_oid(&asn1_oid_id_pkinit_san, &gn.u.otherName.type_id);
+ if (ret == 0)
+ ret = _hx509_make_pkinit_san(context, princ, &gn.u.otherName.value);
+ if (ret == 0)
+ ret = add_GeneralNames(&req->san, &gn);
+ free_GeneralName(&gn);
+ return ret;
+}
+
+/* XXX Add DNSSRV and other SANs */
+
+static int
+get_exts(hx509_context context,
+ const hx509_request req,
+ Extensions *exts)
+{
+ size_t size;
+ int ret = 0;
+
+ exts->val = NULL;
+ exts->len = 0;
+
+ if (KeyUsage2int(req->ku)) {
+ Extension e;
+
+ memset(&e, 0, sizeof(e));
+ /* The critical field needs to be made DEFAULT FALSE... */
+ e.critical = 1;
+ if (ret == 0)
+ ASN1_MALLOC_ENCODE(KeyUsage, e.extnValue.data, e.extnValue.length,
+ &req->ku, &size, ret);
+ if (ret == 0)
+ ret = der_copy_oid(&asn1_oid_id_x509_ce_keyUsage, &e.extnID);
+ if (ret == 0)
+ ret = add_Extensions(exts, &e);
+ free_Extension(&e);
+ }
+ if (ret == 0 && req->eku.len) {
+ Extension e;
+
+ memset(&e, 0, sizeof(e));
+ e.critical = 1;
+ if (ret == 0)
+ ASN1_MALLOC_ENCODE(ExtKeyUsage,
+ e.extnValue.data, e.extnValue.length,
+ &req->eku, &size, ret);
+ if (ret == 0)
+ ret = der_copy_oid(&asn1_oid_id_x509_ce_extKeyUsage, &e.extnID);
+ if (ret == 0)
+ ret = add_Extensions(exts, &e);
+ free_Extension(&e);
+ }
+ if (ret == 0 && req->san.len) {
+ Extension e;
+
+ memset(&e, 0, sizeof(e));
+ /*
+ * SANs are critical when the subject Name is empty.
+ *
+ * The empty DN check could probably stand to be a function we export.
+ */
+ e.critical = FALSE;
+ if (req->name &&
+ req->name->der_name.element == choice_Name_rdnSequence &&
+ req->name->der_name.u.rdnSequence.len == 0)
+ e.critical = 1;
+ if (ret == 0)
+ ASN1_MALLOC_ENCODE(GeneralNames,
+ e.extnValue.data, e.extnValue.length,
+ &req->san,
+ &size, ret);
+ if (ret == 0)
+ ret = der_copy_oid(&asn1_oid_id_x509_ce_subjectAltName, &e.extnID);
+ if (ret == 0)
+ ret = add_Extensions(exts, &e);
+ free_Extension(&e);
+ }
+
+ return ret;
+}
+
+/**
+ * Get the KU/EKUs/SANs set on a request as a DER-encoding of Extensions.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param exts_der Where to put the DER-encoded Extensions.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_get_exts(hx509_context context,
+ const hx509_request req,
+ heim_octet_string *exts_der)
+{
+ Extensions exts;
+ size_t size;
+ int ret;
+
+ exts_der->data = NULL;
+ exts_der->length = 0;
+ ret = get_exts(context, req, &exts);
+ if (ret == 0 && exts.len /* Extensions has a min size constraint of 1 */)
+ ASN1_MALLOC_ENCODE(Extensions, exts_der->data, exts_der->length,
+ &exts, &size, ret);
+ free_Extensions(&exts);
+ return ret;
+}
+
+/* XXX Add PEM */
+
+/**
+ * Encode a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param signer The private key corresponding to the CSR's subject public key.
+ * @param request Where to put the DER-encoded CSR.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_to_pkcs10(hx509_context context,
+ const hx509_request req,
+ const hx509_private_key signer,
+ heim_octet_string *request)
+{
+ CertificationRequest r;
+ Extensions exts;
+ heim_octet_string data;
+ size_t size;
+ int ret;
+
+ request->data = NULL;
+ request->length = 0;
+
+ data.length = 0;
+ data.data = NULL;
+
+ if (req->name == NULL) {
+ hx509_set_error_string(context, 0, EINVAL,
+ "PKCS10 needs to have a subject");
+ return EINVAL;
+ }
+
+ memset(&r, 0, sizeof(r));
+
+ /* Setup CSR */
+ r.certificationRequestInfo.version = pkcs10_v1;
+ ret = copy_Name(&req->name->der_name,
+ &r.certificationRequestInfo.subject);
+ if (ret == 0)
+ ret = copy_SubjectPublicKeyInfo(&req->key,
+ &r.certificationRequestInfo.subjectPKInfo);
+
+ /* Encode extReq attribute with requested Certificate Extensions */
+
+ if (ret == 0)
+ ret = get_exts(context, req, &exts);
+ if (ret == 0 && exts.len) {
+ Attribute *a = NULL; /* Quiet VC */
+ heim_any extns;
+
+ r.certificationRequestInfo.attributes =
+ calloc(1, sizeof(r.certificationRequestInfo.attributes[0]));
+ if (r.certificationRequestInfo.attributes == NULL)
+ ret = ENOMEM;
+ if (ret == 0) {
+ r.certificationRequestInfo.attributes[0].len = 1;
+ r.certificationRequestInfo.attributes[0].val =
+ calloc(1, sizeof(r.certificationRequestInfo.attributes[0].val[0]));
+ if (r.certificationRequestInfo.attributes[0].val == NULL)
+ ret = ENOMEM;
+ if (ret == 0)
+ a = r.certificationRequestInfo.attributes[0].val;
+ }
+ if (ret == 0)
+ ASN1_MALLOC_ENCODE(Extensions, extns.data, extns.length,
+ &exts, &size, ret);
+ if (ret == 0 && a)
+ ret = der_copy_oid(&asn1_oid_id_pkcs9_extReq, &a->type);
+ if (ret == 0)
+ ret = add_AttributeValues(&a->value, &extns);
+ free_heim_any(&extns);
+ }
+
+ /* Encode CSR body for signing */
+ if (ret == 0)
+ ASN1_MALLOC_ENCODE(CertificationRequestInfo, data.data, data.length,
+ &r.certificationRequestInfo, &size, ret);
+ if (ret == 0 && data.length != size)
+ abort();
+
+ /* Self-sign CSR body */
+ if (ret == 0) {
+ ret = _hx509_create_signature_bitstring(context, signer,
+ _hx509_crypto_default_sig_alg,
+ &data,
+ &r.signatureAlgorithm,
+ &r.signature);
+ }
+ free(data.data);
+
+ /* Encode CSR */
+ if (ret == 0)
+ ASN1_MALLOC_ENCODE(CertificationRequest, request->data, request->length,
+ &r, &size, ret);
+ if (ret == 0 && request->length != size)
+ abort();
+
+ free_CertificationRequest(&r);
+ free_Extensions(&exts);
+ return ret;
+}
+
+/**
+ * Parse an encoded CSR and verify its self-signature.
+ *
+ * @param context An hx509 context.
+ * @param der The DER-encoded CSR.
+ * @param req Where to put request object.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_parse_der(hx509_context context,
+ heim_octet_string *der,
+ hx509_request *req)
+{
+ CertificationRequestInfo *rinfo = NULL;
+ CertificationRequest r;
+ hx509_cert signer = NULL;
+ Extensions exts;
+ size_t i, size;
+ int ret;
+
+ memset(&exts, 0, sizeof(exts));
+
+ /* Initial setup and decoding of CSR */
+ ret = hx509_request_init(context, req);
+ if (ret)
+ return ret;
+ ret = decode_CertificationRequest(der->data, der->length, &r, &size);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Failed to decode CSR");
+ free(*req);
+ *req = NULL;
+ return ret;
+ }
+ rinfo = &r.certificationRequestInfo;
+
+ /*
+ * Setup a 'signer' for verifying the self-signature for proof of
+ * possession.
+ *
+ * Sadly we need a "certificate" here because _hx509_verify_signature_*()
+ * functions want one as a signer even though all the verification
+ * functions that use the signer argument only ever use the spki of the
+ * signer certificate.
+ *
+ * FIXME Change struct signature_alg's verify_signature's prototype to use
+ * an spki instead of an hx509_cert as the signer! The we won't have
+ * to do this.
+ */
+ if (ret == 0) {
+ Certificate c;
+ memset(&c, 0, sizeof(c));
+ c.tbsCertificate.subjectPublicKeyInfo = rinfo->subjectPKInfo;
+ if ((signer = hx509_cert_init(context, &c, NULL)) == NULL)
+ ret = ENOMEM;
+ }
+
+ /* Verify the signature */
+ if (ret == 0)
+ ret = _hx509_verify_signature_bitstring(context, signer,
+ &r.signatureAlgorithm,
+ &rinfo->_save,
+ &r.signature);
+ if (ret)
+ hx509_set_error_string(context, 0, ret,
+ "CSR signature verification failed");
+ hx509_cert_free(signer);
+
+ /* Populate the hx509_request */
+ if (ret == 0)
+ ret = hx509_request_set_SubjectPublicKeyInfo(context, *req,
+ &rinfo->subjectPKInfo);
+ if (ret == 0)
+ ret = _hx509_name_from_Name(&rinfo->subject, &(*req)->name);
+
+ /* Extract KUs, EKUs, and SANs from the CSR's attributes */
+ if (ret || !rinfo->attributes || !rinfo->attributes[0].len)
+ goto out;
+
+ for (i = 0; ret == 0 && i < rinfo->attributes[0].len; i++) {
+ Attribute *a = &rinfo->attributes[0].val[i];
+ heim_any *av = NULL;
+
+ /* We only support Extensions request attributes */
+ if (der_heim_oid_cmp(&a->type, &asn1_oid_id_pkcs9_extReq) != 0) {
+ char *oidstr = NULL;
+
+ /*
+ * We need an HX509_TRACE facility for this sort of warning.
+ *
+ * We'd put the warning in the context and then allow the caller to
+ * extract and reset the warning.
+ *
+ * FIXME
+ */
+ der_print_heim_oid(&a->type, '.', &oidstr);
+ warnx("Unknown or unsupported CSR attribute %s",
+ oidstr ? oidstr : "<error decoding OID>");
+ free(oidstr);
+ continue;
+ }
+ if (!a->value.val)
+ continue;
+
+ av = a->value.val;
+ ret = decode_Extensions(av->data, av->length, &exts, NULL);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "CSR signature verification failed "
+ "due to invalid extReq attribute");
+ goto out;
+ }
+ }
+ for (i = 0; ret == 0 && i < exts.len; i++) {
+ const char *what = "";
+ Extension *e = &exts.val[i];
+
+ if (der_heim_oid_cmp(&e->extnID,
+ &asn1_oid_id_x509_ce_keyUsage) == 0) {
+ ret = decode_KeyUsage(e->extnValue.data, e->extnValue.length,
+ &(*req)->ku, NULL);
+ what = "keyUsage";
+ /*
+ * Count all KUs as one requested extension to be authorized,
+ * though the caller will have to check the KU values individually.
+ */
+ if (KeyUsage2int((*req)->ku) & ~KeyUsage2int(int2KeyUsage(~0)))
+ (*req)->nunsupported++;
+ } else if (der_heim_oid_cmp(&e->extnID,
+ &asn1_oid_id_x509_ce_extKeyUsage) == 0) {
+ ret = decode_ExtKeyUsage(e->extnValue.data, e->extnValue.length,
+ &(*req)->eku, NULL);
+ what = "extKeyUsage";
+
+ /*
+ * Count each EKU as a separate requested extension to be
+ * authorized.
+ */
+ } else if (der_heim_oid_cmp(&e->extnID,
+ &asn1_oid_id_x509_ce_subjectAltName) == 0) {
+ ret = decode_GeneralNames(e->extnValue.data, e->extnValue.length,
+ &(*req)->san, NULL);
+ what = "subjectAlternativeName";
+
+ /*
+ * Count each SAN as a separate requested extension to be
+ * authorized.
+ */
+ } else {
+ char *oidstr = NULL;
+
+ (*req)->nunsupported++;
+
+ /*
+ * We need an HX509_TRACE facility for this sort of warning.
+ *
+ * We'd put the warning in the context and then allow the caller to
+ * extract and reset the warning.
+ *
+ * FIXME
+ */
+ der_print_heim_oid(&e->extnID, '.', &oidstr);
+ warnx("Unknown or unsupported CSR extension request %s",
+ oidstr ? oidstr : "<error decoding OID>");
+ free(oidstr);
+ }
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "CSR signature verification failed "
+ "due to invalid %s extension", what);
+ break;
+ }
+ }
+
+out:
+ free_CertificationRequest(&r);
+ free_Extensions(&exts);
+ if (ret)
+ hx509_request_free(req);
+ return ret;
+}
+
+/**
+ * Parse an encoded CSR and verify its self-signature.
+ *
+ * @param context An hx509 context.
+ * @param csr The name of a store containing the CSR ("PKCS10:/path/to/file")
+ * @param req Where to put request object.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_parse(hx509_context context,
+ const char *csr,
+ hx509_request *req)
+{
+ heim_octet_string d;
+ int ret;
+
+ /* XXX Add support for PEM */
+ if (strncmp(csr, "PKCS10:", 7) != 0) {
+ hx509_set_error_string(context, 0, HX509_UNSUPPORTED_OPERATION,
+ "CSR location does not start with \"PKCS10:\": %s",
+ csr);
+ return HX509_UNSUPPORTED_OPERATION;
+ }
+
+ ret = rk_undumpdata(csr + 7, &d.data, &d.length);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Could not read %s", csr);
+ return ret;
+ }
+
+ ret = hx509_request_parse_der(context, &d, req);
+ free(d.data);
+ if (ret)
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ " (while parsing CSR from %s)", csr);
+ return ret;
+}
+
+/**
+ * Get some EKU from a CSR. Usable as an iterator.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param idx The index of the EKU (0 for the first) to return
+ * @param out A pointer to a char * variable where the OID will be placed
+ * (caller must free with free())
+ *
+ * @return Zero on success, HX509_NO_ITEM if no such item exists (denoting
+ * iteration end), or an error.
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_get_eku(hx509_request req,
+ size_t idx,
+ char **out)
+{
+ *out = NULL;
+ if (idx >= req->eku.len)
+ return HX509_NO_ITEM;
+ return der_print_heim_oid(&req->eku.val[idx], '.', out);
+}
+
+static int
+abitstring_check(abitstring a, size_t n, int idx)
+{
+ size_t bytes;
+
+ if (idx >= n)
+ return EINVAL;
+
+ bytes = (idx + 1) / CHAR_BIT + (((idx + 1) % CHAR_BIT) ? 1 : 0);
+ if (a->feat_bytes < bytes)
+ return 0;
+
+ return !!(a->feats[idx / CHAR_BIT] & (1UL<<(idx % CHAR_BIT)));
+}
+
+/*
+ * Sets and returns 0 if not already set, -1 if already set. Positive return
+ * values are system errors.
+ */
+static int
+abitstring_set(abitstring a, size_t n, int idx)
+{
+ size_t bytes;
+
+ if (idx >= n)
+ return EINVAL;
+
+ bytes = n / CHAR_BIT + ((n % CHAR_BIT) ? 1 : 0);
+ if (a->feat_bytes < bytes) {
+ unsigned char *tmp;
+
+ if ((tmp = realloc(a->feats, bytes)) == NULL)
+ return ENOMEM;
+ memset(tmp + a->feat_bytes, 0, bytes - a->feat_bytes);
+ a->feats = tmp;
+ a->feat_bytes = bytes;
+ }
+
+ if (!(a->feats[idx / CHAR_BIT] & (1UL<<(idx % CHAR_BIT)))) {
+ a->feats[idx / CHAR_BIT] |= 1UL<<(idx % CHAR_BIT);
+ return 0;
+ }
+ return -1;
+}
+
+/*
+ * Resets and returns 0 if not already reset, -1 if already reset. Positive
+ * return values are system errors.
+ */
+static int
+abitstring_reset(abitstring a, size_t n, int idx)
+{
+ size_t bytes;
+
+ if (idx >= n)
+ return EINVAL;
+
+ bytes = (idx + 1) / CHAR_BIT + (((idx + 1) % CHAR_BIT) ? 1 : 0);
+ if (a->feat_bytes >= bytes &&
+ (a->feats[idx / CHAR_BIT] & (1UL<<(idx % CHAR_BIT)))) {
+ a->feats[idx / CHAR_BIT] &= ~(1UL<<(idx % CHAR_BIT));
+ return 0;
+ }
+ return -1;
+}
+
+static int
+authorize_feat(hx509_request req, abitstring a, size_t n, int idx)
+{
+ int ret;
+
+ ret = abitstring_set(a, n, idx);
+ switch (ret) {
+ case 0:
+ req->nauthorized++;
+ fallthrough;
+ case -1:
+ return 0;
+ default:
+ return ret;
+ }
+}
+
+static int
+reject_feat(hx509_request req, abitstring a, size_t n, int idx)
+{
+ int ret;
+
+ ret = abitstring_reset(a, n, idx);
+ switch (ret) {
+ case 0:
+ req->nauthorized--;
+ fallthrough;
+ case -1:
+ return 0;
+ default:
+ return ret;
+ }
+}
+
+/**
+ * Filter the requested KeyUsage and mark it authorized.
+ *
+ * @param req The hx509_request object.
+ * @param ku Permitted KeyUsage
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_request_authorize_ku(hx509_request req, KeyUsage ku)
+{
+ (void) hx509_request_set_ku(NULL, req, ku);
+ req->ku = int2KeyUsage(KeyUsage2int(req->ku) & KeyUsage2int(ku));
+ if (KeyUsage2int(ku))
+ req->ku_are_authorized = 1;
+}
+
+/**
+ * Mark a requested EKU as authorized.
+ *
+ * @param req The hx509_request object.
+ * @param idx The index of an EKU that can be fetched with
+ * hx509_request_get_eku()
+ *
+ * @return Zero on success, an error otherwise.
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_authorize_eku(hx509_request req, size_t idx)
+{
+ return authorize_feat(req, &req->authorized_EKUs, req->eku.len, idx);
+}
+
+/**
+ * Mark a requested EKU as not authorized.
+ *
+ * @param req The hx509_request object.
+ * @param idx The index of an EKU that can be fetched with
+ * hx509_request_get_eku()
+ *
+ * @return Zero on success, an error otherwise.
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_reject_eku(hx509_request req, size_t idx)
+{
+ return reject_feat(req, &req->authorized_EKUs, req->eku.len, idx);
+}
+
+/**
+ * Check if an EKU has been marked authorized.
+ *
+ * @param req The hx509_request object.
+ * @param idx The index of an EKU that can be fetched with
+ * hx509_request_get_eku()
+ *
+ * @return Non-zero if authorized, zero if not.
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_eku_authorized_p(hx509_request req, size_t idx)
+{
+ return abitstring_check(&req->authorized_EKUs, req->eku.len, idx);
+}
+
+/**
+ * Mark a requested SAN as authorized.
+ *
+ * @param req The hx509_request object.
+ * @param idx The cursor as modified by a SAN iterator.
+ *
+ * @return Zero on success, an error otherwise.
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_authorize_san(hx509_request req, size_t idx)
+{
+ return authorize_feat(req, &req->authorized_SANs, req->san.len, idx);
+}
+
+/**
+ * Mark a requested SAN as not authorized.
+ *
+ * @param req The hx509_request object.
+ * @param idx The cursor as modified by a SAN iterator.
+ *
+ * @return Zero on success, an error otherwise.
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_reject_san(hx509_request req, size_t idx)
+{
+ return reject_feat(req, &req->authorized_SANs, req->san.len, idx);
+}
+
+/**
+ * Check if a SAN has been marked authorized.
+ *
+ * @param req The hx509_request object.
+ * @param idx The index of a SAN that can be fetched with
+ * hx509_request_get_san()
+ *
+ * @return Non-zero if authorized, zero if not.
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_san_authorized_p(hx509_request req, size_t idx)
+{
+ return abitstring_check(&req->authorized_SANs, req->san.len, idx);
+}
+
+/**
+ * Return the count of unsupported requested certificate extensions.
+ *
+ * @param req The hx509_request object.
+ * @return The number of unsupported certificate extensions requested.
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION size_t HX509_LIB_CALL
+hx509_request_count_unsupported(hx509_request req)
+{
+ return req->nunsupported;
+}
+
+/**
+ * Return the count of as-yet unauthorized certificate extensions requested.
+ *
+ * @param req The hx509_request object.
+ * @return The number of as-yet unauthorized certificate extensions requested.
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION size_t HX509_LIB_CALL
+hx509_request_count_unauthorized(hx509_request req)
+{
+ size_t nrequested = req->eku.len + req->san.len +
+ (KeyUsage2int(req->ku) ? 1 : 0) + req->nunsupported;
+
+ return nrequested - (req->nauthorized + req->ku_are_authorized);
+}
+
+static hx509_san_type
+san_map_type(GeneralName *san)
+{
+ static const struct {
+ const heim_oid *oid;
+ hx509_san_type type;
+ } map[] = {
+ { &asn1_oid_id_pkix_on_dnsSRV, HX509_SAN_TYPE_DNSSRV },
+ { &asn1_oid_id_pkinit_san, HX509_SAN_TYPE_PKINIT },
+ { &asn1_oid_id_pkix_on_xmppAddr, HX509_SAN_TYPE_XMPP },
+ { &asn1_oid_id_pkinit_ms_san, HX509_SAN_TYPE_MS_UPN },
+ { &asn1_oid_id_pkix_on_permanentIdentifier, HX509_SAN_TYPE_PERMANENT_ID },
+ { &asn1_oid_id_on_hardwareModuleName, HX509_SAN_TYPE_HW_MODULE },
+ };
+ size_t i;
+
+ switch (san->element) {
+ case choice_GeneralName_rfc822Name: return HX509_SAN_TYPE_EMAIL;
+ case choice_GeneralName_dNSName: return HX509_SAN_TYPE_DNSNAME;
+ case choice_GeneralName_directoryName: return HX509_SAN_TYPE_DN;
+ case choice_GeneralName_registeredID: return HX509_SAN_TYPE_REGISTERED_ID;
+ case choice_GeneralName_otherName: {
+ for (i = 0; i < sizeof(map)/sizeof(map[0]); i++)
+ if (der_heim_oid_cmp(&san->u.otherName.type_id, map[i].oid) == 0)
+ return map[i].type;
+ }
+ fallthrough;
+ default: return HX509_SAN_TYPE_UNSUPPORTED;
+ }
+}
+
+/**
+ * Return the count of as-yet unauthorized certificate extensions requested.
+ *
+ * @param req The hx509_request object.
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION size_t HX509_LIB_CALL
+hx509_request_get_san(hx509_request req,
+ size_t idx,
+ hx509_san_type *type,
+ char **out)
+{
+ struct rk_strpool *pool = NULL;
+ GeneralName *san;
+
+ *out = NULL;
+ if (idx >= req->san.len)
+ return HX509_NO_ITEM;
+
+ san = &req->san.val[idx];
+ switch ((*type = san_map_type(san))) {
+ case HX509_SAN_TYPE_UNSUPPORTED: return 0;
+ case HX509_SAN_TYPE_EMAIL:
+ *out = strndup(san->u.rfc822Name.data,
+ san->u.rfc822Name.length);
+ break;
+ case HX509_SAN_TYPE_DNSNAME:
+ *out = strndup(san->u.dNSName.data,
+ san->u.dNSName.length);
+ break;
+ case HX509_SAN_TYPE_DNSSRV: {
+ SRVName name;
+ size_t size;
+ int ret;
+
+ ret = decode_SRVName(san->u.otherName.value.data,
+ san->u.otherName.value.length, &name, &size);
+ if (ret)
+ return ret;
+ *out = strndup(name.data, name.length);
+ break;
+ }
+ case HX509_SAN_TYPE_PERMANENT_ID: {
+ PermanentIdentifier pi;
+ size_t size;
+ char *s = NULL;
+ int ret;
+
+ ret = decode_PermanentIdentifier(san->u.otherName.value.data,
+ san->u.otherName.value.length,
+ &pi, &size);
+ if (ret == 0 && pi.assigner) {
+ ret = der_print_heim_oid(pi.assigner, '.', &s);
+ if (ret == 0 &&
+ (pool = rk_strpoolprintf(NULL, "%s", s)) == NULL)
+ ret = ENOMEM;
+ } else if (ret == 0) {
+ pool = rk_strpoolprintf(NULL, "-");
+ }
+ if (ret == 0 &&
+ (pool = rk_strpoolprintf(pool, "%s%s",
+ *pi.identifierValue ? " " : "",
+ *pi.identifierValue ? *pi.identifierValue : "")) == NULL)
+ ret = ENOMEM;
+ if (ret == 0 && (*out = rk_strpoolcollect(pool)) == NULL)
+ ret = ENOMEM;
+ free_PermanentIdentifier(&pi);
+ free(s);
+ return ret;
+ }
+ case HX509_SAN_TYPE_HW_MODULE: {
+ HardwareModuleName hn;
+ size_t size;
+ char *s = NULL;
+ int ret;
+
+ ret = decode_HardwareModuleName(san->u.otherName.value.data,
+ san->u.otherName.value.length,
+ &hn, &size);
+ if (ret == 0 && hn.hwSerialNum.length > 256)
+ hn.hwSerialNum.length = 256;
+ if (ret == 0)
+ ret = der_print_heim_oid(&hn.hwType, '.', &s);
+ if (ret == 0)
+ pool = rk_strpoolprintf(NULL, "%s", s);
+ if (ret == 0 && pool)
+ pool = rk_strpoolprintf(pool, " %.*s",
+ (int)hn.hwSerialNum.length,
+ (char *)hn.hwSerialNum.data);
+ if (ret == 0 &&
+ (pool == NULL || (*out = rk_strpoolcollect(pool)) == NULL))
+ ret = ENOMEM;
+ free_HardwareModuleName(&hn);
+ return ret;
+ }
+ case HX509_SAN_TYPE_DN: {
+ Name name;
+
+ if (san->u.directoryName.element == choice_Name_rdnSequence) {
+ name.element = choice_Name_rdnSequence;
+ name.u.rdnSequence = san->u.directoryName.u.rdnSequence;
+ return _hx509_Name_to_string(&name, out);
+ }
+ *type = HX509_SAN_TYPE_UNSUPPORTED;
+ return 0;
+ }
+ case HX509_SAN_TYPE_REGISTERED_ID:
+ return der_print_heim_oid(&san->u.registeredID, '.', out);
+ case HX509_SAN_TYPE_XMPP:
+ fallthrough;
+ case HX509_SAN_TYPE_MS_UPN: {
+ int ret;
+
+ ret = _hx509_unparse_utf8_string_name(req->context, &pool,
+ &san->u.otherName.value);
+ if ((*out = rk_strpoolcollect(pool)) == NULL)
+ return hx509_enomem(req->context);
+ return ret;
+ }
+ case HX509_SAN_TYPE_PKINIT: {
+ int ret;
+
+ ret = _hx509_unparse_KRB5PrincipalName(req->context, &pool,
+ &san->u.otherName.value);
+ if ((*out = rk_strpoolcollect(pool)) == NULL)
+ return hx509_enomem(req->context);
+ return ret;
+ }
+ default:
+ *type = HX509_SAN_TYPE_UNSUPPORTED;
+ return 0;
+ }
+ if (*out == NULL)
+ return ENOMEM;
+ return 0;
+}
+
+/**
+ * Display a CSR.
+ *
+ * @param context An hx509 context.
+ * @param req The hx509_request object.
+ * @param f A FILE * to print the CSR to.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_request
+ */
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_request_print(hx509_context context, hx509_request req, FILE *f)
+{
+ uint64_t ku_num;
+ size_t i;
+ char *s = NULL;
+ int ret = 0;
+
+ /*
+ * It's really unformatunate that we can't reuse more of the
+ * lib/hx509/print.c infrastructure here, as it's too focused on
+ * Certificates.
+ *
+ * For that matter, it's really annoying that CSRs don't more resemble
+ * Certificates. Indeed, an ideal CSR would look like this:
+ *
+ * CSRInfo ::= {
+ * desiredTbsCertificate TBSCertificate,
+ * attributes [1] SEQUENCE OF Attribute OPTIONAL,
+ * }
+ * CSR :: = {
+ * csrInfo CSRInfo,
+ * sigAlg AlgorithmIdentifier,
+ * signature BIT STRING
+ * }
+ *
+ * with everything related to the desired certificate in
+ * desiredTbsCertificate and anything not related to the CSR's contents in
+ * the 'attributes' field.
+ *
+ * That wouldn't allow one to have optional desired TBSCertificate
+ * features, but hey. One could express "gimme all or gimme nothing" as an
+ * attribute, or "gimme what you can", then check what one got.
+ */
+ fprintf(f, "PKCS#10 CertificationRequest:\n");
+
+ if (req->name) {
+ char *subject;
+ ret = hx509_name_to_string(req->name, &subject);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Failed to print name");
+ return ret;
+ }
+ fprintf(f, " name: %s\n", subject);
+ free(subject);
+ }
+ /* XXX Use hx509_request_get_ku() accessor */
+ if ((ku_num = KeyUsage2int(req->ku))) {
+ const struct units *u;
+ const char *first = " ";
+
+ fprintf(f, " key usage:");
+ for (u = asn1_KeyUsage_units(); u->name; ++u) {
+ if ((ku_num & u->mult)) {
+ fprintf(f, "%s%s", first, u->name);
+ first = ", ";
+ ku_num &= ~u->mult;
+ }
+ }
+ if (ku_num)
+ fprintf(f, "%s<unknown-KeyUsage-value(s)>", first);
+ fprintf(f, "\n");
+ }
+ if (req->eku.len) {
+ const char *first = " ";
+
+ fprintf(f, " eku:");
+ for (i = 0; ret == 0; i++) {
+ free(s); s = NULL;
+ ret = hx509_request_get_eku(req, i, &s);
+ if (ret)
+ break;
+ fprintf(f, "%s{%s}", first, s);
+ first = ", ";
+ }
+ fprintf(f, "\n");
+ }
+ free(s); s = NULL;
+ if (ret == HX509_NO_ITEM)
+ ret = 0;
+ for (i = 0; ret == 0; i++) {
+ hx509_san_type san_type;
+
+ free(s); s = NULL;
+ ret = hx509_request_get_san(req, i, &san_type, &s);
+ if (ret)
+ break;
+ switch (san_type) {
+ case HX509_SAN_TYPE_EMAIL:
+ fprintf(f, " san: rfc822Name: %s\n", s);
+ break;
+ case HX509_SAN_TYPE_DNSNAME:
+ fprintf(f, " san: dNSName: %s\n", s);
+ break;
+ case HX509_SAN_TYPE_DN:
+ fprintf(f, " san: dn: %s\n", s);
+ break;
+ case HX509_SAN_TYPE_REGISTERED_ID:
+ fprintf(f, " san: registeredID: %s\n", s);
+ break;
+ case HX509_SAN_TYPE_XMPP:
+ fprintf(f, " san: xmpp: %s\n", s);
+ break;
+ case HX509_SAN_TYPE_PKINIT:
+ fprintf(f, " san: pkinit: %s\n", s);
+ break;
+ case HX509_SAN_TYPE_MS_UPN:
+ fprintf(f, " san: ms-upn: %s\n", s);
+ break;
+ default:
+ fprintf(f, " san: <SAN type not supported>\n");
+ break;
+ }
+ }
+ free(s); s = NULL;
+ if (ret == HX509_NO_ITEM)
+ ret = 0;
+ return ret;
+}
diff --git a/third_party/heimdal/lib/hx509/revoke.c b/third_party/heimdal/lib/hx509/revoke.c
new file mode 100644
index 0000000..18b2f8f
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/revoke.c
@@ -0,0 +1,1650 @@
+/*
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/**
+ * @page page_revoke Revocation methods
+ *
+ * There are two revocation method for PKIX/X.509: CRL and OCSP.
+ * Revocation is needed if the private key is lost and
+ * stolen. Depending on how picky you are, you might want to make
+ * revocation for destroyed private keys too (smartcard broken), but
+ * that should not be a problem.
+ *
+ * CRL is a list of certificates that have expired.
+ *
+ * OCSP is an online checking method where the requestor sends a list
+ * of certificates to the OCSP server to return a signed reply if they
+ * are valid or not. Some services sends a OCSP reply as part of the
+ * hand-shake to make the revoktion decision simpler/faster for the
+ * client.
+ */
+
+#include "hx_locl.h"
+
+struct revoke_crl {
+ char *path;
+ time_t last_modfied;
+ CRLCertificateList crl;
+ int verified;
+ int failed_verify;
+};
+
+struct revoke_ocsp {
+ char *path;
+ time_t last_modfied;
+ OCSPBasicOCSPResponse ocsp;
+ hx509_certs certs;
+ hx509_cert signer;
+};
+
+
+struct hx509_revoke_ctx_data {
+ unsigned int ref;
+ struct {
+ struct revoke_crl *val;
+ size_t len;
+ } crls;
+ struct {
+ struct revoke_ocsp *val;
+ size_t len;
+ } ocsps;
+};
+
+/**
+ * Allocate a revokation context. Free with hx509_revoke_free().
+ *
+ * @param context A hx509 context.
+ * @param ctx returns a newly allocated revokation context.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_revoke
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_revoke_init(hx509_context context, hx509_revoke_ctx *ctx)
+{
+ *ctx = calloc(1, sizeof(**ctx));
+ if (*ctx == NULL)
+ return ENOMEM;
+
+ (*ctx)->ref = 1;
+ (*ctx)->crls.len = 0;
+ (*ctx)->crls.val = NULL;
+ (*ctx)->ocsps.len = 0;
+ (*ctx)->ocsps.val = NULL;
+
+ return 0;
+}
+
+HX509_LIB_FUNCTION hx509_revoke_ctx HX509_LIB_CALL
+_hx509_revoke_ref(hx509_revoke_ctx ctx)
+{
+ if (ctx == NULL)
+ return NULL;
+ if (ctx->ref == 0)
+ _hx509_abort("revoke ctx refcount == 0 on ref");
+ ctx->ref++;
+ if (ctx->ref == UINT_MAX)
+ _hx509_abort("revoke ctx refcount == UINT_MAX on ref");
+ return ctx;
+}
+
+static void
+free_ocsp(struct revoke_ocsp *ocsp)
+{
+ free(ocsp->path);
+ free_OCSPBasicOCSPResponse(&ocsp->ocsp);
+ hx509_certs_free(&ocsp->certs);
+ hx509_cert_free(ocsp->signer);
+}
+
+/**
+ * Free a hx509 revokation context.
+ *
+ * @param ctx context to be freed
+ *
+ * @ingroup hx509_revoke
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_revoke_free(hx509_revoke_ctx *ctx)
+{
+ size_t i ;
+
+ if (ctx == NULL || *ctx == NULL)
+ return;
+
+ if ((*ctx)->ref == 0)
+ _hx509_abort("revoke ctx refcount == 0 on free");
+ if (--(*ctx)->ref > 0)
+ return;
+
+ for (i = 0; i < (*ctx)->crls.len; i++) {
+ free((*ctx)->crls.val[i].path);
+ free_CRLCertificateList(&(*ctx)->crls.val[i].crl);
+ }
+
+ for (i = 0; i < (*ctx)->ocsps.len; i++)
+ free_ocsp(&(*ctx)->ocsps.val[i]);
+ free((*ctx)->ocsps.val);
+
+ free((*ctx)->crls.val);
+
+ memset(*ctx, 0, sizeof(**ctx));
+ free(*ctx);
+ *ctx = NULL;
+}
+
+static int
+verify_ocsp(hx509_context context,
+ struct revoke_ocsp *ocsp,
+ time_t time_now,
+ hx509_certs certs,
+ hx509_cert parent)
+{
+ hx509_cert signer = NULL;
+ hx509_query q;
+ int ret;
+
+ _hx509_query_clear(&q);
+
+ /*
+ * Need to match on issuer too in case there are two CA that have
+ * issued the same name to a certificate. One example of this is
+ * the www.openvalidation.org test's ocsp validator.
+ */
+
+ q.match = HX509_QUERY_MATCH_ISSUER_NAME;
+ q.issuer_name = &_hx509_get_cert(parent)->tbsCertificate.issuer;
+
+ switch(ocsp->ocsp.tbsResponseData.responderID.element) {
+ case choice_OCSPResponderID_byName:
+ q.match |= HX509_QUERY_MATCH_SUBJECT_NAME;
+ q.subject_name = &ocsp->ocsp.tbsResponseData.responderID.u.byName;
+ break;
+ case choice_OCSPResponderID_byKey:
+ q.match |= HX509_QUERY_MATCH_KEY_HASH_SHA1;
+ q.keyhash_sha1 = &ocsp->ocsp.tbsResponseData.responderID.u.byKey;
+ break;
+ }
+
+ ret = hx509_certs_find(context, certs, &q, &signer);
+ if (ret && ocsp->certs)
+ ret = hx509_certs_find(context, ocsp->certs, &q, &signer);
+ if (ret == 0 && signer == NULL)
+ ret = HX509_CERT_NOT_FOUND;
+ if (ret)
+ goto out;
+
+ /*
+ * If signer certificate isn't the CA certificate, lets check the
+ * it is the CA that signed the signer certificate and the OCSP EKU
+ * is set.
+ */
+ if (hx509_cert_cmp(signer, parent) != 0) {
+ Certificate *p = _hx509_get_cert(parent);
+ Certificate *s = _hx509_get_cert(signer);
+
+ ret = _hx509_cert_is_parent_cmp(s, p, 0);
+ if (ret != 0) {
+ ret = HX509_PARENT_NOT_CA;
+ hx509_set_error_string(context, 0, ret, "Revoke OCSP signer "
+ "doesn't have CA as signer certificate");
+ goto out;
+ }
+
+ ret = _hx509_verify_signature_bitstring(context,
+ parent,
+ &s->signatureAlgorithm,
+ &s->tbsCertificate._save,
+ &s->signatureValue);
+ if (ret) {
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "OCSP signer signature invalid");
+ goto out;
+ }
+
+ ret = hx509_cert_check_eku(context, signer,
+ &asn1_oid_id_pkix_kp_OCSPSigning, 0);
+ if (ret)
+ goto out;
+ }
+
+ ret = _hx509_verify_signature_bitstring(context,
+ signer,
+ &ocsp->ocsp.signatureAlgorithm,
+ &ocsp->ocsp.tbsResponseData._save,
+ &ocsp->ocsp.signature);
+ if (ret) {
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "OCSP signature invalid");
+ goto out;
+ }
+
+ ocsp->signer = signer;
+ signer = NULL;
+out:
+ if (signer)
+ hx509_cert_free(signer);
+
+ return ret;
+}
+
+/*
+ *
+ */
+
+static int
+parse_ocsp_basic(const void *data, size_t length, OCSPBasicOCSPResponse *basic)
+{
+ OCSPResponse resp;
+ size_t size;
+ int ret;
+
+ memset(basic, 0, sizeof(*basic));
+
+ ret = decode_OCSPResponse(data, length, &resp, &size);
+ if (ret)
+ return ret;
+ if (length != size) {
+ free_OCSPResponse(&resp);
+ return ASN1_EXTRA_DATA;
+ }
+
+ switch (resp.responseStatus) {
+ case successful:
+ break;
+ default:
+ free_OCSPResponse(&resp);
+ return HX509_REVOKE_WRONG_DATA;
+ }
+
+ if (resp.responseBytes == NULL) {
+ free_OCSPResponse(&resp);
+ return EINVAL;
+ }
+
+ ret = der_heim_oid_cmp(&resp.responseBytes->responseType,
+ &asn1_oid_id_pkix_ocsp_basic);
+ if (ret != 0) {
+ free_OCSPResponse(&resp);
+ return HX509_REVOKE_WRONG_DATA;
+ }
+
+ ret = decode_OCSPBasicOCSPResponse(resp.responseBytes->response.data,
+ resp.responseBytes->response.length,
+ basic,
+ &size);
+ if (ret) {
+ free_OCSPResponse(&resp);
+ return ret;
+ }
+ if (size != resp.responseBytes->response.length) {
+ free_OCSPResponse(&resp);
+ free_OCSPBasicOCSPResponse(basic);
+ return ASN1_EXTRA_DATA;
+ }
+ free_OCSPResponse(&resp);
+
+ return 0;
+}
+
+/*
+ *
+ */
+
+static int
+load_ocsp(hx509_context context, struct revoke_ocsp *ocsp)
+{
+ OCSPBasicOCSPResponse basic;
+ hx509_certs certs = NULL;
+ size_t length;
+ struct stat sb;
+ void *data;
+ int ret;
+
+ ret = rk_undumpdata(ocsp->path, &data, &length);
+ if (ret)
+ return ret;
+
+ ret = stat(ocsp->path, &sb);
+ if (ret) {
+ rk_xfree(data);
+ return errno;
+ }
+
+ ret = parse_ocsp_basic(data, length, &basic);
+ rk_xfree(data);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to parse OCSP response");
+ return ret;
+ }
+
+ if (basic.certs) {
+ size_t i;
+
+ ret = hx509_certs_init(context, "MEMORY:ocsp-certs", 0,
+ NULL, &certs);
+ if (ret) {
+ free_OCSPBasicOCSPResponse(&basic);
+ return ret;
+ }
+
+ for (i = 0; i < basic.certs->len; i++) {
+ hx509_cert c;
+
+ c = hx509_cert_init(context, &basic.certs->val[i], NULL);
+ if (c == NULL)
+ continue;
+
+ ret = hx509_certs_add(context, certs, c);
+ hx509_cert_free(c);
+ if (ret)
+ continue;
+ }
+ }
+
+ ocsp->last_modfied = sb.st_mtime;
+
+ free_OCSPBasicOCSPResponse(&ocsp->ocsp);
+ hx509_certs_free(&ocsp->certs);
+ hx509_cert_free(ocsp->signer);
+
+ ocsp->ocsp = basic;
+ ocsp->certs = certs;
+ ocsp->signer = NULL;
+
+ return 0;
+}
+
+/**
+ * Add a OCSP file to the revokation context.
+ *
+ * @param context hx509 context
+ * @param ctx hx509 revokation context
+ * @param path path to file that is going to be added to the context.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_revoke
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_revoke_add_ocsp(hx509_context context,
+ hx509_revoke_ctx ctx,
+ const char *path)
+{
+ void *data;
+ int ret;
+ size_t i;
+
+ if (strncmp(path, "FILE:", 5) != 0) {
+ hx509_set_error_string(context, 0, HX509_UNSUPPORTED_OPERATION,
+ "unsupport type in %s", path);
+ return HX509_UNSUPPORTED_OPERATION;
+ }
+
+ path += 5;
+
+ for (i = 0; i < ctx->ocsps.len; i++) {
+ if (strcmp(ctx->ocsps.val[0].path, path) == 0)
+ return 0;
+ }
+
+ data = realloc(ctx->ocsps.val,
+ (ctx->ocsps.len + 1) * sizeof(ctx->ocsps.val[0]));
+ if (data == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+
+ ctx->ocsps.val = data;
+
+ memset(&ctx->ocsps.val[ctx->ocsps.len], 0,
+ sizeof(ctx->ocsps.val[0]));
+
+ ctx->ocsps.val[ctx->ocsps.len].path = strdup(path);
+ if (ctx->ocsps.val[ctx->ocsps.len].path == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+
+ ret = load_ocsp(context, &ctx->ocsps.val[ctx->ocsps.len]);
+ if (ret) {
+ free(ctx->ocsps.val[ctx->ocsps.len].path);
+ return ret;
+ }
+ ctx->ocsps.len++;
+
+ return ret;
+}
+
+/*
+ *
+ */
+
+static int
+verify_crl(hx509_context context,
+ hx509_revoke_ctx ctx,
+ CRLCertificateList *crl,
+ time_t time_now,
+ hx509_certs certs,
+ hx509_cert parent)
+{
+ hx509_cert signer;
+ hx509_query q;
+ time_t t;
+ int ret;
+
+ t = _hx509_Time2time_t(&crl->tbsCertList.thisUpdate);
+ if (t > time_now) {
+ hx509_set_error_string(context, 0, HX509_CRL_USED_BEFORE_TIME,
+ "CRL used before time");
+ return HX509_CRL_USED_BEFORE_TIME;
+ }
+
+ if (crl->tbsCertList.nextUpdate == NULL) {
+ hx509_set_error_string(context, 0, HX509_CRL_INVALID_FORMAT,
+ "CRL missing nextUpdate");
+ return HX509_CRL_INVALID_FORMAT;
+ }
+
+ t = _hx509_Time2time_t(crl->tbsCertList.nextUpdate);
+ if (t < time_now) {
+ hx509_set_error_string(context, 0, HX509_CRL_USED_AFTER_TIME,
+ "CRL used after time");
+ return HX509_CRL_USED_AFTER_TIME;
+ }
+
+ _hx509_query_clear(&q);
+
+ /*
+ * If it's the signer have CRLSIGN bit set, use that as the signer
+ * cert for the certificate, otherwise, search for a certificate.
+ */
+ if (_hx509_check_key_usage(context, parent, 1 << 6, FALSE) == 0) {
+ signer = hx509_cert_ref(parent);
+ } else {
+ q.match = HX509_QUERY_MATCH_SUBJECT_NAME;
+ q.match |= HX509_QUERY_KU_CRLSIGN;
+ q.subject_name = &crl->tbsCertList.issuer;
+
+ ret = hx509_certs_find(context, certs, &q, &signer);
+ if (ret == 0 && signer == NULL)
+ ret = HX509_CERT_NOT_FOUND;
+ if (ret) {
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "Failed to find certificate for CRL");
+ return ret;
+ }
+ }
+
+ ret = _hx509_verify_signature_bitstring(context,
+ signer,
+ &crl->signatureAlgorithm,
+ &crl->tbsCertList._save,
+ &crl->signatureValue);
+ if (ret) {
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "CRL signature invalid");
+ goto out;
+ }
+
+ /*
+ * If signer is not CA cert, need to check revoke status of this
+ * CRL signing cert too, this include all parent CRL signer cert
+ * up to the root *sigh*, assume root at least hve CERTSIGN flag
+ * set.
+ */
+ while (_hx509_check_key_usage(context, signer, 1 << 5, TRUE)) {
+ hx509_cert crl_parent;
+
+ _hx509_query_clear(&q);
+
+ q.match = HX509_QUERY_MATCH_SUBJECT_NAME;
+ q.match |= HX509_QUERY_KU_CRLSIGN;
+ q.subject_name = &_hx509_get_cert(signer)->tbsCertificate.issuer;
+
+ ret = hx509_certs_find(context, certs, &q, &crl_parent);
+ if (ret) {
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "Failed to find parent of CRL signer");
+ goto out;
+ }
+
+ ret = hx509_revoke_verify(context,
+ ctx,
+ certs,
+ time_now,
+ signer,
+ crl_parent);
+ hx509_cert_free(signer);
+ signer = crl_parent;
+ if (ret) {
+ hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+ "Failed to verify revocation "
+ "status of CRL signer");
+ goto out;
+ }
+ }
+
+out:
+ hx509_cert_free(signer);
+
+ return ret;
+}
+
+static int
+crl_parser(hx509_context context, const char *type,
+ const hx509_pem_header *header,
+ const void *data, size_t len, void *ctx)
+{
+ CRLCertificateList *crl = (CRLCertificateList *)ctx;
+ size_t size;
+ int ret;
+
+ if (strcasecmp("X509 CRL", type) != 0)
+ return HX509_CRYPTO_SIG_INVALID_FORMAT;
+
+ ret = decode_CRLCertificateList(data, len, crl, &size);
+ if (ret)
+ return ret;
+
+ /* check signature is aligned */
+ if (crl->signatureValue.length & 7) {
+ free_CRLCertificateList(crl);
+ return HX509_CRYPTO_SIG_INVALID_FORMAT;
+ }
+
+ return 0;
+}
+
+static int
+load_crl(hx509_context context, const char *path, time_t *t, CRLCertificateList *crl)
+{
+ struct stat sb;
+ size_t length;
+ void *data;
+ FILE *f;
+ int ret;
+
+ memset(crl, 0, sizeof(*crl));
+
+ ret = stat(path, &sb);
+ if (ret)
+ return errno;
+
+ *t = sb.st_mtime;
+
+ if ((f = fopen(path, "r")) == NULL)
+ return errno;
+
+ rk_cloexec_file(f);
+
+ ret = hx509_pem_read(context, f, crl_parser, crl);
+ fclose(f);
+
+ if (ret == HX509_PARSING_KEY_FAILED) {
+
+ ret = rk_undumpdata(path, &data, &length);
+ if (ret)
+ return ret;
+
+ ret = crl_parser(context, "X509 CRL", NULL, data, length, crl);
+ rk_xfree(data);
+ }
+ return ret;
+}
+
+/**
+ * Add a CRL file to the revokation context.
+ *
+ * @param context hx509 context
+ * @param ctx hx509 revokation context
+ * @param path path to file that is going to be added to the context.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_revoke
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_revoke_add_crl(hx509_context context,
+ hx509_revoke_ctx ctx,
+ const char *path)
+{
+ void *data;
+ size_t i;
+ int ret;
+
+ if (strncmp(path, "FILE:", 5) != 0) {
+ hx509_set_error_string(context, 0, HX509_UNSUPPORTED_OPERATION,
+ "unsupported type in %s", path);
+ return HX509_UNSUPPORTED_OPERATION;
+ }
+
+
+ path += 5;
+
+ for (i = 0; i < ctx->crls.len; i++) {
+ if (strcmp(ctx->crls.val[i].path, path) == 0)
+ return 0;
+ }
+
+ data = realloc(ctx->crls.val,
+ (ctx->crls.len + 1) * sizeof(ctx->crls.val[0]));
+ if (data == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+ ctx->crls.val = data;
+
+ memset(&ctx->crls.val[ctx->crls.len], 0, sizeof(ctx->crls.val[0]));
+
+ ctx->crls.val[ctx->crls.len].path = strdup(path);
+ if (ctx->crls.val[ctx->crls.len].path == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+
+ ret = load_crl(context,
+ path,
+ &ctx->crls.val[ctx->crls.len].last_modfied,
+ &ctx->crls.val[ctx->crls.len].crl);
+ if (ret) {
+ free(ctx->crls.val[ctx->crls.len].path);
+ return ret;
+ }
+
+ ctx->crls.len++;
+
+ return ret;
+}
+
+/**
+ * Check that a certificate is not expired according to a revokation
+ * context. Also need the parent certificte to the check OCSP
+ * parent identifier.
+ *
+ * @param context hx509 context
+ * @param ctx hx509 revokation context
+ * @param certs
+ * @param now
+ * @param cert
+ * @param parent_cert
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_revoke
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_revoke_verify(hx509_context context,
+ hx509_revoke_ctx ctx,
+ hx509_certs certs,
+ time_t now,
+ hx509_cert cert,
+ hx509_cert parent_cert)
+{
+ const Certificate *c = _hx509_get_cert(cert);
+ const Certificate *p = _hx509_get_cert(parent_cert);
+ unsigned long i, j, k;
+ int ret;
+
+ hx509_clear_error_string(context);
+
+ for (i = 0; i < ctx->ocsps.len; i++) {
+ struct revoke_ocsp *ocsp = &ctx->ocsps.val[i];
+ struct stat sb;
+
+ /* check this ocsp apply to this cert */
+
+ /* check if there is a newer version of the file */
+ ret = stat(ocsp->path, &sb);
+ if (ret == 0 && ocsp->last_modfied != sb.st_mtime) {
+ ret = load_ocsp(context, ocsp);
+ if (ret)
+ continue;
+ }
+
+ /* verify signature in ocsp if not already done */
+ if (ocsp->signer == NULL) {
+ ret = verify_ocsp(context, ocsp, now, certs, parent_cert);
+ if (ret)
+ continue;
+ }
+
+ for (j = 0; j < ocsp->ocsp.tbsResponseData.responses.len; j++) {
+ heim_octet_string os;
+
+ ret = der_heim_integer_cmp(&ocsp->ocsp.tbsResponseData.responses.val[j].certID.serialNumber,
+ &c->tbsCertificate.serialNumber);
+ if (ret != 0)
+ continue;
+
+ /* verify issuer hashes hash */
+ ret = _hx509_verify_signature(context,
+ NULL,
+ &ocsp->ocsp.tbsResponseData.responses.val[i].certID.hashAlgorithm,
+ &c->tbsCertificate.issuer._save,
+ &ocsp->ocsp.tbsResponseData.responses.val[i].certID.issuerNameHash);
+ if (ret != 0)
+ continue;
+
+ os.data = p->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.data;
+ os.length = p->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.length / 8;
+
+ ret = _hx509_verify_signature(context,
+ NULL,
+ &ocsp->ocsp.tbsResponseData.responses.val[j].certID.hashAlgorithm,
+ &os,
+ &ocsp->ocsp.tbsResponseData.responses.val[j].certID.issuerKeyHash);
+ if (ret != 0)
+ continue;
+
+ switch (ocsp->ocsp.tbsResponseData.responses.val[j].certStatus.element) {
+ case choice_OCSPCertStatus_good:
+ break;
+ case choice_OCSPCertStatus_revoked:
+ hx509_set_error_string(context, 0,
+ HX509_CERT_REVOKED,
+ "Certificate revoked by issuer in OCSP");
+ return HX509_CERT_REVOKED;
+ case choice_OCSPCertStatus_unknown:
+ continue;
+ }
+
+ /* don't allow the update to be in the future */
+ if (ocsp->ocsp.tbsResponseData.responses.val[j].thisUpdate >
+ now + context->ocsp_time_diff)
+ continue;
+
+ /* don't allow the next update to be in the past */
+ if (ocsp->ocsp.tbsResponseData.responses.val[j].nextUpdate) {
+ if (*ocsp->ocsp.tbsResponseData.responses.val[j].nextUpdate < now)
+ continue;
+ } /* else should force a refetch, but can we ? */
+
+ return 0;
+ }
+ }
+
+ for (i = 0; i < ctx->crls.len; i++) {
+ struct revoke_crl *crl = &ctx->crls.val[i];
+ struct stat sb;
+ int diff;
+
+ /* check if cert.issuer == crls.val[i].crl.issuer */
+ ret = _hx509_name_cmp(&c->tbsCertificate.issuer,
+ &crl->crl.tbsCertList.issuer, &diff);
+ if (ret || diff)
+ continue;
+
+ ret = stat(crl->path, &sb);
+ if (ret == 0 && crl->last_modfied != sb.st_mtime) {
+ CRLCertificateList cl;
+
+ ret = load_crl(context, crl->path, &crl->last_modfied, &cl);
+ if (ret == 0) {
+ free_CRLCertificateList(&crl->crl);
+ crl->crl = cl;
+ crl->verified = 0;
+ crl->failed_verify = 0;
+ }
+ }
+ if (crl->failed_verify)
+ continue;
+
+ /* verify signature in crl if not already done */
+ if (crl->verified == 0) {
+ ret = verify_crl(context, ctx, &crl->crl, now, certs, parent_cert);
+ if (ret) {
+ crl->failed_verify = 1;
+ continue;
+ }
+ crl->verified = 1;
+ }
+
+ if (crl->crl.tbsCertList.crlExtensions) {
+ for (j = 0; j < crl->crl.tbsCertList.crlExtensions->len; j++) {
+ if (crl->crl.tbsCertList.crlExtensions->val[j].critical) {
+ hx509_set_error_string(context, 0,
+ HX509_CRL_UNKNOWN_EXTENSION,
+ "Unknown CRL extension");
+ return HX509_CRL_UNKNOWN_EXTENSION;
+ }
+ }
+ }
+
+ if (crl->crl.tbsCertList.revokedCertificates == NULL)
+ return 0;
+
+ /* check if cert is in crl */
+ for (j = 0; j < crl->crl.tbsCertList.revokedCertificates->len; j++) {
+ time_t t;
+
+ ret = der_heim_integer_cmp(&crl->crl.tbsCertList.revokedCertificates->val[j].userCertificate,
+ &c->tbsCertificate.serialNumber);
+ if (ret != 0)
+ continue;
+
+ t = _hx509_Time2time_t(&crl->crl.tbsCertList.revokedCertificates->val[j].revocationDate);
+ if (t > now)
+ continue;
+
+ if (crl->crl.tbsCertList.revokedCertificates->val[j].crlEntryExtensions)
+ for (k = 0; k < crl->crl.tbsCertList.revokedCertificates->val[j].crlEntryExtensions->len; k++)
+ if (crl->crl.tbsCertList.revokedCertificates->val[j].crlEntryExtensions->val[k].critical)
+ return HX509_CRL_UNKNOWN_EXTENSION;
+
+ hx509_set_error_string(context, 0,
+ HX509_CERT_REVOKED,
+ "Certificate revoked by issuer in CRL");
+ return HX509_CERT_REVOKED;
+ }
+
+ return 0;
+ }
+
+
+ if (context->flags & HX509_CTX_VERIFY_MISSING_OK)
+ return 0;
+ hx509_set_error_string(context, HX509_ERROR_APPEND,
+ HX509_REVOKE_STATUS_MISSING,
+ "No revocation status found for certificates");
+ return HX509_REVOKE_STATUS_MISSING;
+}
+
+struct ocsp_add_ctx {
+ OCSPTBSRequest *req;
+ hx509_certs certs;
+ const AlgorithmIdentifier *digest;
+ hx509_cert parent;
+};
+
+static int HX509_LIB_CALL
+add_to_req(hx509_context context, void *ptr, hx509_cert cert)
+{
+ struct ocsp_add_ctx *ctx = ptr;
+ OCSPInnerRequest *one;
+ hx509_cert parent = NULL;
+ Certificate *p, *c = _hx509_get_cert(cert);
+ heim_octet_string os;
+ int ret;
+ hx509_query q;
+ void *d;
+
+ d = realloc(ctx->req->requestList.val,
+ sizeof(ctx->req->requestList.val[0]) *
+ (ctx->req->requestList.len + 1));
+ if (d == NULL)
+ return ENOMEM;
+ ctx->req->requestList.val = d;
+
+ one = &ctx->req->requestList.val[ctx->req->requestList.len];
+ memset(one, 0, sizeof(*one));
+
+ _hx509_query_clear(&q);
+
+ q.match |= HX509_QUERY_FIND_ISSUER_CERT;
+ q.subject = c;
+
+ ret = hx509_certs_find(context, ctx->certs, &q, &parent);
+ if (ret)
+ goto out;
+
+ if (ctx->parent) {
+ if (hx509_cert_cmp(ctx->parent, parent) != 0) {
+ ret = HX509_REVOKE_NOT_SAME_PARENT;
+ hx509_set_error_string(context, 0, ret,
+ "Not same parent certifate as "
+ "last certificate in request");
+ goto out;
+ }
+ } else
+ ctx->parent = hx509_cert_ref(parent);
+
+ p = _hx509_get_cert(parent);
+
+ ret = copy_AlgorithmIdentifier(ctx->digest, &one->reqCert.hashAlgorithm);
+ if (ret)
+ goto out;
+
+ ret = _hx509_create_signature(context,
+ NULL,
+ &one->reqCert.hashAlgorithm,
+ &c->tbsCertificate.issuer._save,
+ NULL,
+ &one->reqCert.issuerNameHash);
+ if (ret)
+ goto out;
+
+ os.data = p->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.data;
+ os.length =
+ p->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.length / 8;
+
+ ret = _hx509_create_signature(context,
+ NULL,
+ &one->reqCert.hashAlgorithm,
+ &os,
+ NULL,
+ &one->reqCert.issuerKeyHash);
+ if (ret)
+ goto out;
+
+ ret = copy_CertificateSerialNumber(&c->tbsCertificate.serialNumber,
+ &one->reqCert.serialNumber);
+ if (ret)
+ goto out;
+
+ ctx->req->requestList.len++;
+out:
+ hx509_cert_free(parent);
+ if (ret) {
+ free_OCSPInnerRequest(one);
+ memset(one, 0, sizeof(*one));
+ }
+
+ return ret;
+}
+
+/**
+ * Create an OCSP request for a set of certificates.
+ *
+ * @param context a hx509 context
+ * @param reqcerts list of certificates to request ocsp data for
+ * @param pool certificate pool to use when signing
+ * @param signer certificate to use to sign the request
+ * @param digest the signing algorithm in the request, if NULL use the
+ * default signature algorithm,
+ * @param request the encoded request, free with free_heim_octet_string().
+ * @param nonce nonce in the request, free with free_heim_octet_string().
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_revoke
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ocsp_request(hx509_context context,
+ hx509_certs reqcerts,
+ hx509_certs pool,
+ hx509_cert signer,
+ const AlgorithmIdentifier *digest,
+ heim_octet_string *request,
+ heim_octet_string *nonce)
+{
+ OCSPRequest req;
+ size_t size;
+ int ret;
+ struct ocsp_add_ctx ctx;
+ Extensions *es;
+
+ memset(&req, 0, sizeof(req));
+
+ if (digest == NULL)
+ digest = _hx509_crypto_default_digest_alg;
+
+ ctx.req = &req.tbsRequest;
+ ctx.certs = pool;
+ ctx.digest = digest;
+ ctx.parent = NULL;
+
+ ret = hx509_certs_iter_f(context, reqcerts, add_to_req, &ctx);
+ hx509_cert_free(ctx.parent);
+ if (ret)
+ goto out;
+
+ if (nonce) {
+ req.tbsRequest.requestExtensions =
+ calloc(1, sizeof(*req.tbsRequest.requestExtensions));
+ if (req.tbsRequest.requestExtensions == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ es = req.tbsRequest.requestExtensions;
+
+ es->val = calloc(es->len, sizeof(es->val[0]));
+ if (es->val == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ es->len = 1;
+ ret = der_copy_oid(&asn1_oid_id_pkix_ocsp_nonce, &es->val[0].extnID);
+ if (ret) {
+ free_OCSPRequest(&req);
+ return ret;
+ }
+
+ es->val[0].extnValue.data = malloc(10);
+ if (es->val[0].extnValue.data == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ es->val[0].extnValue.length = 10;
+
+ ret = RAND_bytes(es->val[0].extnValue.data,
+ es->val[0].extnValue.length);
+ if (ret != 1) {
+ ret = HX509_CRYPTO_INTERNAL_ERROR;
+ goto out;
+ }
+ ret = der_copy_octet_string(nonce, &es->val[0].extnValue);
+ if (ret) {
+ ret = ENOMEM;
+ goto out;
+ }
+ }
+
+ ASN1_MALLOC_ENCODE(OCSPRequest, request->data, request->length,
+ &req, &size, ret);
+ free_OCSPRequest(&req);
+ if (ret)
+ goto out;
+ if (size != request->length)
+ _hx509_abort("internal ASN.1 encoder error");
+
+ return 0;
+
+out:
+ free_OCSPRequest(&req);
+ return ret;
+}
+
+static char *
+printable_time(time_t t)
+{
+ static char s[128];
+ char *p;
+ if ((p = ctime(&t)) == NULL)
+ strlcpy(s, "?", sizeof(s));
+ else {
+ strlcpy(s, p + 4, sizeof(s));
+ s[20] = 0;
+ }
+ return s;
+}
+
+/*
+ *
+ */
+
+static int
+print_ocsp(hx509_context context, struct revoke_ocsp *ocsp, FILE *out)
+{
+ int ret = 0;
+ size_t i;
+
+ fprintf(out, "signer: ");
+
+ switch(ocsp->ocsp.tbsResponseData.responderID.element) {
+ case choice_OCSPResponderID_byName: {
+ hx509_name n;
+ char *s;
+ _hx509_name_from_Name(&ocsp->ocsp.tbsResponseData.responderID.u.byName, &n);
+ hx509_name_to_string(n, &s);
+ hx509_name_free(&n);
+ fprintf(out, " byName: %s\n", s);
+ free(s);
+ break;
+ }
+ case choice_OCSPResponderID_byKey: {
+ char *s;
+ hex_encode(ocsp->ocsp.tbsResponseData.responderID.u.byKey.data,
+ ocsp->ocsp.tbsResponseData.responderID.u.byKey.length,
+ &s);
+ fprintf(out, " byKey: %s\n", s);
+ free(s);
+ break;
+ }
+ default:
+ _hx509_abort("choice_OCSPResponderID unknown");
+ break;
+ }
+
+ fprintf(out, "producedAt: %s\n",
+ printable_time(ocsp->ocsp.tbsResponseData.producedAt));
+
+ fprintf(out, "replies: %d\n", ocsp->ocsp.tbsResponseData.responses.len);
+
+ for (i = 0; i < ocsp->ocsp.tbsResponseData.responses.len; i++) {
+ const char *status;
+ switch (ocsp->ocsp.tbsResponseData.responses.val[i].certStatus.element) {
+ case choice_OCSPCertStatus_good:
+ status = "good";
+ break;
+ case choice_OCSPCertStatus_revoked:
+ status = "revoked";
+ break;
+ case choice_OCSPCertStatus_unknown:
+ status = "unknown";
+ break;
+ default:
+ status = "element unknown";
+ }
+
+ fprintf(out, "\t%llu. status: %s\n", (unsigned long long)i, status);
+
+ fprintf(out, "\tthisUpdate: %s\n",
+ printable_time(ocsp->ocsp.tbsResponseData.responses.val[i].thisUpdate));
+ if (ocsp->ocsp.tbsResponseData.responses.val[i].nextUpdate)
+ fprintf(out, "\tproducedAt: %s\n",
+ printable_time(ocsp->ocsp.tbsResponseData.responses.val[i].thisUpdate));
+
+ }
+
+ fprintf(out, "appended certs:\n");
+ if (ocsp->certs)
+ ret = hx509_certs_iter_f(context, ocsp->certs, hx509_ci_print_names, out);
+
+ return ret;
+}
+
+static int
+print_crl(hx509_context context, struct revoke_crl *crl, FILE *out)
+{
+ {
+ hx509_name n;
+ char *s;
+ _hx509_name_from_Name(&crl->crl.tbsCertList.issuer, &n);
+ hx509_name_to_string(n, &s);
+ hx509_name_free(&n);
+ fprintf(out, " issuer: %s\n", s);
+ free(s);
+ }
+
+ fprintf(out, " thisUpdate: %s\n",
+ printable_time(_hx509_Time2time_t(&crl->crl.tbsCertList.thisUpdate)));
+
+ return 0;
+}
+
+
+/*
+ *
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_revoke_print(hx509_context context,
+ hx509_revoke_ctx ctx,
+ FILE *out)
+{
+ int saved_ret = 0, ret;
+ size_t n;
+
+ for (n = 0; n < ctx->ocsps.len; n++) {
+ struct revoke_ocsp *ocsp = &ctx->ocsps.val[n];
+
+ fprintf(out, "OCSP %s\n", ocsp->path);
+
+ ret = print_ocsp(context, ocsp, out);
+ if (ret) {
+ fprintf(out, "failure printing OCSP: %d\n", ret);
+ saved_ret = ret;
+ }
+ }
+
+ for (n = 0; n < ctx->crls.len; n++) {
+ struct revoke_crl *crl = &ctx->crls.val[n];
+
+ fprintf(out, "CRL %s\n", crl->path);
+
+ ret = print_crl(context, crl, out);
+ if (ret) {
+ fprintf(out, "failure printing CRL: %d\n", ret);
+ saved_ret = ret;
+ }
+ }
+ return saved_ret;
+
+}
+
+/**
+ * Print the OCSP reply stored in a file.
+ *
+ * @param context a hx509 context
+ * @param path path to a file with a OCSP reply
+ * @param out the out FILE descriptor to print the reply on
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_revoke
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_revoke_ocsp_print(hx509_context context, const char *path, FILE *out)
+{
+ struct revoke_ocsp ocsp;
+ int ret;
+
+ if (out == NULL)
+ out = stdout;
+
+ memset(&ocsp, 0, sizeof(ocsp));
+
+ ocsp.path = strdup(path);
+ if (ocsp.path == NULL)
+ return ENOMEM;
+
+ ret = load_ocsp(context, &ocsp);
+ if (ret) {
+ free_ocsp(&ocsp);
+ return ret;
+ }
+
+ ret = print_ocsp(context, &ocsp, out);
+
+ free_ocsp(&ocsp);
+ return ret;
+}
+
+/**
+ * Verify that the certificate is part of the OCSP reply and it's not
+ * expired. Doesn't verify signature the OCSP reply or it's done by a
+ * authorized sender, that is assumed to be already done.
+ *
+ * @param context a hx509 context
+ * @param now the time right now, if 0, use the current time.
+ * @param cert the certificate to verify
+ * @param flags flags control the behavior
+ * @param data pointer to the encode ocsp reply
+ * @param length the length of the encode ocsp reply
+ * @param expiration return the time the OCSP will expire and need to
+ * be rechecked.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_ocsp_verify(hx509_context context,
+ time_t now,
+ hx509_cert cert,
+ int flags,
+ const void *data, size_t length,
+ time_t *expiration)
+{
+ const Certificate *c = _hx509_get_cert(cert);
+ OCSPBasicOCSPResponse basic;
+ int ret;
+ size_t i;
+
+ if (now == 0)
+ now = time(NULL);
+
+ *expiration = 0;
+
+ ret = parse_ocsp_basic(data, length, &basic);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret,
+ "Failed to parse OCSP response");
+ return ret;
+ }
+
+ for (i = 0; i < basic.tbsResponseData.responses.len; i++) {
+
+ ret = der_heim_integer_cmp(&basic.tbsResponseData.responses.val[i].certID.serialNumber,
+ &c->tbsCertificate.serialNumber);
+ if (ret != 0)
+ continue;
+
+ /* verify issuer hashes hash */
+ ret = _hx509_verify_signature(context,
+ NULL,
+ &basic.tbsResponseData.responses.val[i].certID.hashAlgorithm,
+ &c->tbsCertificate.issuer._save,
+ &basic.tbsResponseData.responses.val[i].certID.issuerNameHash);
+ if (ret != 0)
+ continue;
+
+ switch (basic.tbsResponseData.responses.val[i].certStatus.element) {
+ case choice_OCSPCertStatus_good:
+ break;
+ case choice_OCSPCertStatus_revoked:
+ case choice_OCSPCertStatus_unknown:
+ continue;
+ }
+
+ /* don't allow the update to be in the future */
+ if (basic.tbsResponseData.responses.val[i].thisUpdate >
+ now + context->ocsp_time_diff)
+ continue;
+
+ /* don't allow the next update to be in the past */
+ if (basic.tbsResponseData.responses.val[i].nextUpdate) {
+ if (*basic.tbsResponseData.responses.val[i].nextUpdate < now)
+ continue;
+ *expiration = *basic.tbsResponseData.responses.val[i].nextUpdate;
+ } else
+ *expiration = now;
+
+ free_OCSPBasicOCSPResponse(&basic);
+ return 0;
+ }
+
+ free_OCSPBasicOCSPResponse(&basic);
+
+ {
+ hx509_name name;
+ char *subject;
+
+ ret = hx509_cert_get_subject(cert, &name);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ ret = hx509_name_to_string(name, &subject);
+ hx509_name_free(&name);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+ hx509_set_error_string(context, 0, HX509_CERT_NOT_IN_OCSP,
+ "Certificate %s not in OCSP response "
+ "or not good",
+ subject);
+ free(subject);
+ }
+out:
+ return HX509_CERT_NOT_IN_OCSP;
+}
+
+struct hx509_crl {
+ hx509_certs revoked;
+ time_t expire;
+};
+
+/**
+ * Create a CRL context. Use hx509_crl_free() to free the CRL context.
+ *
+ * @param context a hx509 context.
+ * @param crl return pointer to a newly allocated CRL context.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crl_alloc(hx509_context context, hx509_crl *crl)
+{
+ int ret;
+
+ *crl = calloc(1, sizeof(**crl));
+ if (*crl == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ ret = hx509_certs_init(context, "MEMORY:crl", 0, NULL, &(*crl)->revoked);
+ if (ret) {
+ free(*crl);
+ *crl = NULL;
+ return ret;
+ }
+ (*crl)->expire = 0;
+ return ret;
+}
+
+/**
+ * Add revoked certificate to an CRL context.
+ *
+ * @param context a hx509 context.
+ * @param crl the CRL to add the revoked certificate to.
+ * @param certs keyset of certificate to revoke.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crl_add_revoked_certs(hx509_context context,
+ hx509_crl crl,
+ hx509_certs certs)
+{
+ return hx509_certs_merge(context, crl->revoked, certs);
+}
+
+/**
+ * Set the lifetime of a CRL context.
+ *
+ * @param context a hx509 context.
+ * @param crl a CRL context
+ * @param delta delta time the certificate is valid, library adds the
+ * current time to this.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crl_lifetime(hx509_context context, hx509_crl crl, int delta)
+{
+ crl->expire = time(NULL) + delta;
+ return 0;
+}
+
+/**
+ * Free a CRL context.
+ *
+ * @param context a hx509 context.
+ * @param crl a CRL context to free.
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+hx509_crl_free(hx509_context context, hx509_crl *crl)
+{
+ if (*crl == NULL)
+ return;
+ hx509_certs_free(&(*crl)->revoked);
+ memset(*crl, 0, sizeof(**crl));
+ free(*crl);
+ *crl = NULL;
+}
+
+static int HX509_LIB_CALL
+add_revoked(hx509_context context, void *ctx, hx509_cert cert)
+{
+ TBSCRLCertList *c = ctx;
+ unsigned int num;
+ void *ptr;
+ int ret;
+
+ num = c->revokedCertificates->len;
+ ptr = realloc(c->revokedCertificates->val,
+ (num + 1) * sizeof(c->revokedCertificates->val[0]));
+ if (ptr == NULL) {
+ hx509_clear_error_string(context);
+ return ENOMEM;
+ }
+ c->revokedCertificates->val = ptr;
+
+ ret = hx509_cert_get_serialnumber(cert,
+ &c->revokedCertificates->val[num].userCertificate);
+ if (ret) {
+ hx509_clear_error_string(context);
+ return ret;
+ }
+ c->revokedCertificates->val[num].revocationDate.element =
+ choice_Time_generalTime;
+ c->revokedCertificates->val[num].revocationDate.u.generalTime =
+ time(NULL) - 3600 * 24;
+ c->revokedCertificates->val[num].crlEntryExtensions = NULL;
+
+ c->revokedCertificates->len++;
+
+ return 0;
+}
+
+/**
+ * Sign a CRL and return an encode certificate.
+ *
+ * @param context a hx509 context.
+ * @param signer certificate to sign the CRL with
+ * @param crl the CRL to sign
+ * @param os return the signed and encoded CRL, free with
+ * free_heim_octet_string()
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_verify
+ */
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+hx509_crl_sign(hx509_context context,
+ hx509_cert signer,
+ hx509_crl crl,
+ heim_octet_string *os)
+{
+ const AlgorithmIdentifier *sigalg = _hx509_crypto_default_sig_alg;
+ CRLCertificateList c;
+ size_t size;
+ int ret;
+ hx509_private_key signerkey;
+
+ memset(&c, 0, sizeof(c));
+
+ signerkey = _hx509_cert_private_key(signer);
+ if (signerkey == NULL) {
+ ret = HX509_PRIVATE_KEY_MISSING;
+ hx509_set_error_string(context, 0, ret,
+ "Private key missing for CRL signing");
+ return ret;
+ }
+
+ c.tbsCertList.version = malloc(sizeof(*c.tbsCertList.version));
+ if (c.tbsCertList.version == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ return ENOMEM;
+ }
+
+ *c.tbsCertList.version = 1;
+
+ ret = copy_AlgorithmIdentifier(sigalg, &c.tbsCertList.signature);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+
+ ret = copy_Name(&_hx509_get_cert(signer)->tbsCertificate.issuer,
+ &c.tbsCertList.issuer);
+ if (ret) {
+ hx509_clear_error_string(context);
+ goto out;
+ }
+
+ c.tbsCertList.thisUpdate.element = choice_Time_generalTime;
+ c.tbsCertList.thisUpdate.u.generalTime = time(NULL) - 24 * 3600;
+
+ c.tbsCertList.nextUpdate = malloc(sizeof(*c.tbsCertList.nextUpdate));
+ if (c.tbsCertList.nextUpdate == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ ret = ENOMEM;
+ goto out;
+ }
+
+ {
+ time_t next = crl->expire;
+ if (next == 0)
+ next = time(NULL) + 24 * 3600 * 365;
+
+ c.tbsCertList.nextUpdate->element = choice_Time_generalTime;
+ c.tbsCertList.nextUpdate->u.generalTime = next;
+ }
+
+ c.tbsCertList.revokedCertificates =
+ calloc(1, sizeof(*c.tbsCertList.revokedCertificates));
+ if (c.tbsCertList.revokedCertificates == NULL) {
+ hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+ ret = ENOMEM;
+ goto out;
+ }
+ c.tbsCertList.crlExtensions = NULL;
+
+ ret = hx509_certs_iter_f(context, crl->revoked, add_revoked, &c.tbsCertList);
+ if (ret)
+ goto out;
+
+ /* if not revoked certs, remove OPTIONAL entry */
+ if (c.tbsCertList.revokedCertificates->len == 0) {
+ free(c.tbsCertList.revokedCertificates);
+ c.tbsCertList.revokedCertificates = NULL;
+ }
+
+ ASN1_MALLOC_ENCODE(TBSCRLCertList, os->data, os->length,
+ &c.tbsCertList, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "failed to encode tbsCRL");
+ goto out;
+ }
+ if (size != os->length)
+ _hx509_abort("internal ASN.1 encoder error");
+
+
+ ret = _hx509_create_signature_bitstring(context,
+ signerkey,
+ sigalg,
+ os,
+ &c.signatureAlgorithm,
+ &c.signatureValue);
+ free(os->data);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "Failed to sign CRL");
+ goto out;
+ }
+
+ ASN1_MALLOC_ENCODE(CRLCertificateList, os->data, os->length,
+ &c, &size, ret);
+ if (ret) {
+ hx509_set_error_string(context, 0, ret, "failed to encode CRL");
+ goto out;
+ }
+ if (size != os->length)
+ _hx509_abort("internal ASN.1 encoder error");
+
+ free_CRLCertificateList(&c);
+
+ return 0;
+
+out:
+ free_CRLCertificateList(&c);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/hx509/sel-gram.y b/third_party/heimdal/lib/hx509/sel-gram.y
new file mode 100644
index 0000000..09f641d
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/sel-gram.y
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+%{
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#include <hx_locl.h>
+
+#if !defined(yylex)
+#define yylex _hx509_sel_yylex
+#define yywrap _hx509_sel_yywrap
+#endif
+#if !defined(yyparse)
+#define yyparse _hx509_sel_yyparse
+#define yyerror _hx509_sel_yyerror
+#define yylval _hx509_sel_yylval
+#define yychar _hx509_sel_yychar
+#define yydebug _hx509_sel_yydebug
+#define yynerrs _hx509_sel_yynerrs
+#endif
+
+%}
+
+%union {
+ char *string;
+ struct hx_expr *expr;
+}
+
+%token kw_TRUE
+%token kw_FALSE
+%token kw_AND
+%token kw_OR
+%token kw_IN
+%token kw_TAILMATCH
+
+%type <expr> expr
+%type <expr> comp
+%type <expr> word words
+%type <expr> number
+%type <expr> string
+%type <expr> function
+%type <expr> variable variables
+
+%token <string> NUMBER
+%token <string> STRING
+%token <string> IDENTIFIER
+
+%left '!'
+%left kw_AND
+%left kw_OR
+
+%start start
+
+%%
+
+start: expr { _hx509_expr_input.expr = $1; }
+
+expr : kw_TRUE { $$ = _hx509_make_expr(op_TRUE, NULL, NULL); }
+ | kw_FALSE { $$ = _hx509_make_expr(op_FALSE, NULL, NULL); }
+ | '!' expr { $$ = _hx509_make_expr(op_NOT, $2, NULL); }
+ | expr kw_AND expr { $$ = _hx509_make_expr(op_AND, $1, $3); }
+ | expr kw_OR expr { $$ = _hx509_make_expr(op_OR, $1, $3); }
+ | '(' expr ')' { $$ = $2; }
+ | comp { $$ = _hx509_make_expr(op_COMP, $1, NULL); }
+ ;
+
+words : word { $$ = _hx509_make_expr(expr_WORDS, $1, NULL); }
+ | word ',' words { $$ = _hx509_make_expr(expr_WORDS, $1, $3); }
+ ;
+
+comp : word '=' '=' word { $$ = _hx509_make_expr(comp_EQ, $1, $4); }
+ | word '!' '=' word { $$ = _hx509_make_expr(comp_NE, $1, $4); }
+ | word kw_TAILMATCH word { $$ = _hx509_make_expr(comp_TAILEQ, $1, $3); }
+ | word kw_IN '(' words ')' { $$ = _hx509_make_expr(comp_IN, $1, $4); }
+ | word kw_IN variable { $$ = _hx509_make_expr(comp_IN, $1, $3); }
+ ;
+
+word : number { $$ = $1; }
+ | string { $$ = $1; }
+ | function { $$ = $1; }
+ | variable { $$ = $1; }
+ ;
+
+number : NUMBER { $$ = _hx509_make_expr(expr_NUMBER, $1, NULL); };
+string : STRING { $$ = _hx509_make_expr(expr_STRING, $1, NULL); };
+
+function: IDENTIFIER '(' words ')' {
+ $$ = _hx509_make_expr(expr_FUNCTION, $1, $3); }
+ ;
+variable: '%' '{' variables '}' { $$ = $3; }
+ ;
+
+variables: IDENTIFIER '.' variables {
+ $$ = _hx509_make_expr(expr_VAR, $1, $3); }
+ | IDENTIFIER {
+ $$ = _hx509_make_expr(expr_VAR, $1, NULL); }
+ ;
diff --git a/third_party/heimdal/lib/hx509/sel-lex.l b/third_party/heimdal/lib/hx509/sel-lex.l
new file mode 100644
index 0000000..f401e40
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/sel-lex.l
@@ -0,0 +1,148 @@
+%{
+/*
+ * Copyright (c) 2004 - 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifdef __GNUC__
+#pragma GCC diagnostic ignored "-Wunused-function"
+#endif
+
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#undef ECHO
+
+#include <stdio.h>
+#include <string.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include "sel.h"
+#include "sel-gram.h"
+unsigned lineno = 1;
+
+static char * handle_string(void);
+static int lex_input(char *, int);
+
+struct hx_expr_input _hx509_expr_input;
+
+#ifndef YY_NULL
+#define YY_NULL 0
+#endif
+
+#define YY_NO_UNPUT 1
+
+#undef YY_INPUT
+#define YY_INPUT(buf,res,maxsize) (res = lex_input(buf, maxsize))
+
+#undef ECHO
+
+%}
+%%
+
+TRUE { return kw_TRUE; }
+FALSE { return kw_FALSE; }
+AND { return kw_AND; }
+OR { return kw_OR; }
+IN { return kw_IN; }
+TAILMATCH { return kw_TAILMATCH; }
+
+[A-Za-z][-A-Za-z0-9_]* {
+ yylval.string = strdup ((const char *)yytext);
+ return IDENTIFIER;
+ }
+"\"" { yylval.string = handle_string(); return STRING; }
+\n { ++lineno; }
+[,.!={}()%] { return *yytext; }
+[ \t] ;
+%%
+
+static char *
+handle_string(void)
+{
+ char x[1024];
+ int i = 0;
+ int c;
+ int quote = 0;
+ while((c = input()) != EOF){
+ if(quote) {
+ x[i++] = '\\';
+ x[i++] = c;
+ quote = 0;
+ continue;
+ }
+ if(c == '\n'){
+ _hx509_sel_yyerror("unterminated string");
+ lineno++;
+ break;
+ }
+ if(c == '\\'){
+ quote++;
+ continue;
+ }
+ if(c == '\"')
+ break;
+ x[i++] = c;
+ }
+ x[i] = '\0';
+ return strdup(x);
+}
+
+#if !defined(yywrap)
+#define yywrap _hx509_sel_yywrap
+#endif
+
+int
+yywrap ()
+{
+ return 1;
+}
+
+static int
+lex_input(char *buf, int max_size)
+{
+ int n;
+
+ n = _hx509_expr_input.length - _hx509_expr_input.offset;
+ if (max_size < n)
+ n = max_size;
+ if (n <= 0)
+ return YY_NULL;
+
+ memcpy(buf, _hx509_expr_input.buf + _hx509_expr_input.offset, n);
+ _hx509_expr_input.offset += n;
+
+ return n;
+}
diff --git a/third_party/heimdal/lib/hx509/sel.c b/third_party/heimdal/lib/hx509/sel.c
new file mode 100644
index 0000000..bfd55e9
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/sel.c
@@ -0,0 +1,240 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+HX509_LIB_FUNCTION struct hx_expr * HX509_LIB_CALL
+_hx509_make_expr(enum hx_expr_op op, void *arg1, void *arg2)
+{
+ struct hx_expr *expr;
+
+ expr = malloc(sizeof(*expr));
+ if (expr == NULL)
+ return NULL;
+ expr->op = op;
+ expr->arg1 = arg1;
+ expr->arg2 = arg2;
+
+ return expr;
+}
+
+static const char *
+eval_word(hx509_context context, hx509_env env, struct hx_expr *word)
+{
+ switch (word->op) {
+ case expr_STRING:
+ return word->arg1;
+ case expr_VAR:
+ if (word->arg2 == NULL)
+ return hx509_env_find(context, env, word->arg1);
+
+ env = hx509_env_find_binding(context, env, word->arg1);
+ if (env == NULL)
+ return NULL;
+
+ return eval_word(context, env, word->arg2);
+ default:
+ return NULL;
+ }
+}
+
+static hx509_env
+find_variable(hx509_context context, hx509_env env, struct hx_expr *word)
+{
+ assert(word->op == expr_VAR);
+
+ if (word->arg2 == NULL)
+ return hx509_env_find_binding(context, env, word->arg1);
+
+ env = hx509_env_find_binding(context, env, word->arg1);
+ if (env == NULL)
+ return NULL;
+ return find_variable(context, env, word->arg2);
+}
+
+static int
+eval_comp(hx509_context context, hx509_env env, struct hx_expr *expr)
+{
+ switch (expr->op) {
+ case comp_NE:
+ case comp_EQ:
+ case comp_TAILEQ: {
+ const char *s1, *s2;
+ int ret;
+
+ s1 = eval_word(context, env, expr->arg1);
+ s2 = eval_word(context, env, expr->arg2);
+
+ if (s1 == NULL || s2 == NULL)
+ return FALSE;
+
+ if (expr->op == comp_TAILEQ) {
+ size_t len1 = strlen(s1);
+ size_t len2 = strlen(s2);
+
+ if (len1 < len2)
+ return 0;
+ ret = strcmp(s1 + (len1 - len2), s2) == 0;
+ } else {
+ ret = strcmp(s1, s2) == 0;
+ if (expr->op == comp_NE)
+ ret = !ret;
+ }
+ return ret;
+ }
+ case comp_IN: {
+ struct hx_expr *subexpr;
+ const char *w, *s1;
+
+ w = eval_word(context, env, expr->arg1);
+
+ subexpr = expr->arg2;
+
+ if (subexpr->op == expr_WORDS) {
+ while (subexpr) {
+ s1 = eval_word(context, env, subexpr->arg1);
+ if (strcmp(w, s1) == 0)
+ return TRUE;
+ subexpr = subexpr->arg2;
+ }
+ } else if (subexpr->op == expr_VAR) {
+ hx509_env subenv;
+
+ subenv = find_variable(context, env, subexpr);
+ if (subenv == NULL)
+ return FALSE;
+
+ while (subenv) {
+ if (subenv->type != env_string)
+ continue;
+ if (strcmp(w, subenv->name) == 0)
+ return TRUE;
+ if (strcmp(w, subenv->u.string) == 0)
+ return TRUE;
+ subenv = subenv->next;
+ }
+
+ } else
+ _hx509_abort("hx509 eval IN unknown op: %d", (int)subexpr->op);
+
+ return FALSE;
+ }
+ default:
+ _hx509_abort("hx509 eval expr with unknown op: %d", (int)expr->op);
+ }
+ return FALSE;
+}
+
+HX509_LIB_FUNCTION int HX509_LIB_CALL
+_hx509_expr_eval(hx509_context context, hx509_env env, struct hx_expr *expr)
+{
+ switch (expr->op) {
+ case op_TRUE:
+ return 1;
+ case op_FALSE:
+ return 0;
+ case op_NOT:
+ return ! _hx509_expr_eval(context, env, expr->arg1);
+ case op_AND:
+ return _hx509_expr_eval(context, env, expr->arg1) &&
+ _hx509_expr_eval(context, env, expr->arg2);
+ case op_OR:
+ return _hx509_expr_eval(context, env, expr->arg1) ||
+ _hx509_expr_eval(context, env, expr->arg2);
+ case op_COMP:
+ return eval_comp(context, env, expr->arg1);
+ default:
+ _hx509_abort("hx509 eval expr with unknown op: %d", (int)expr->op);
+ UNREACHABLE(return 0);
+ }
+}
+
+HX509_LIB_FUNCTION void HX509_LIB_CALL
+_hx509_expr_free(struct hx_expr *expr)
+{
+ switch (expr->op) {
+ case expr_STRING:
+ case expr_NUMBER:
+ free(expr->arg1);
+ break;
+ case expr_WORDS:
+ case expr_FUNCTION:
+ case expr_VAR:
+ free(expr->arg1);
+ if (expr->arg2)
+ _hx509_expr_free(expr->arg2);
+ break;
+ default:
+ if (expr->arg1)
+ _hx509_expr_free(expr->arg1);
+ if (expr->arg2)
+ _hx509_expr_free(expr->arg2);
+ break;
+ }
+ free(expr);
+}
+
+/* XXX Horrible, no good cause not thread-safe */
+HX509_LIB_FUNCTION struct hx_expr * HX509_LIB_CALL
+_hx509_expr_parse(const char *buf)
+{
+ _hx509_expr_input.buf = buf;
+ _hx509_expr_input.length = strlen(buf);
+ _hx509_expr_input.offset = 0;
+ _hx509_expr_input.expr = NULL;
+
+ if (_hx509_expr_input.error) {
+ free(_hx509_expr_input.error);
+ _hx509_expr_input.error = NULL;
+ }
+
+ yyparse();
+
+ return _hx509_expr_input.expr;
+}
+
+const char *
+_hx509_expr_parse_error(void)
+{
+ return _hx509_expr_input.error;
+}
+
+void
+_hx509_sel_yyerror (const char *s)
+{
+ if (_hx509_expr_input.error)
+ free(_hx509_expr_input.error);
+
+ _hx509_expr_input.error = strdup(s);
+}
+
diff --git a/third_party/heimdal/lib/hx509/sel.h b/third_party/heimdal/lib/hx509/sel.h
new file mode 100644
index 0000000..daa471e
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/sel.h
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+enum hx_expr_op {
+ op_TRUE,
+ op_FALSE,
+ op_NOT,
+ op_AND,
+ op_OR,
+ op_COMP,
+
+ comp_EQ,
+ comp_NE,
+ comp_IN,
+ comp_TAILEQ,
+
+ expr_NUMBER,
+ expr_STRING,
+ expr_FUNCTION,
+ expr_VAR,
+ expr_WORDS
+};
+
+struct hx_expr {
+ enum hx_expr_op op;
+ void *arg1;
+ void *arg2;
+};
+
+struct hx_expr_input {
+ const char *buf;
+ size_t length;
+ size_t offset;
+ struct hx_expr *expr;
+ char *error;
+};
+
+extern struct hx_expr_input _hx509_expr_input;
+
+/*
+ * With bison/flex, the more modern way to allow multiple yacc/lex grammars to
+ * be linked into a single executable is to use the
+ *
+ * bison: -p, --name-prefix=,PREFIX/, -Dapi.prefix=PREFIX
+ * flex: -Pprefix, --prefix=STRING
+ *
+ * options, these take care of renaming all the machine-generated global entry
+ * points, some of which are new. When these options are used "yylex",
+ * "yyparse", ... are already defined and our (potentially incomplete) attempt
+ * to do the same conflicts with the "right" new way to handle this. The below
+ * logic gets us out of the way when the job has already been taken care of by
+ * the parser-generator.
+ */
+#if !defined(yylex)
+#define yylex _hx509_sel_yylex
+#define yywrap _hx509_sel_yywrap
+#endif
+#if !defined(yyparse)
+#define yyparse _hx509_sel_yyparse
+#define yyerror _hx509_sel_yyerror
+#define yylval _hx509_sel_yylval
+#define yychar _hx509_sel_yychar
+#define yydebug _hx509_sel_yydebug
+#define yynerrs _hx509_sel_yynerrs
+#endif
+
+int _hx509_sel_yyparse(void);
+int _hx509_sel_yylex(void);
+void _hx509_sel_yyerror(const char *);
+
diff --git a/third_party/heimdal/lib/hx509/softp11.c b/third_party/heimdal/lib/hx509/softp11.c
new file mode 100644
index 0000000..75f6755
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/softp11.c
@@ -0,0 +1,1777 @@
+/*
+ * Copyright (c) 2004 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#define CRYPTOKI_EXPORTS 1
+
+#include "hx_locl.h"
+#include "ref/pkcs11.h"
+
+#define OBJECT_ID_MASK 0xfff
+#define HANDLE_OBJECT_ID(h) ((h) & OBJECT_ID_MASK)
+#define OBJECT_ID(obj) HANDLE_OBJECT_ID((obj)->object_handle)
+
+#ifndef HAVE_RANDOM
+#define random() rand()
+#define srandom(s) srand(s)
+#endif
+
+#ifdef _WIN32
+#include <shlobj.h>
+#endif
+
+struct st_attr {
+ CK_ATTRIBUTE attribute;
+ int secret;
+};
+
+struct st_object {
+ CK_OBJECT_HANDLE object_handle;
+ struct st_attr *attrs;
+ int num_attributes;
+ hx509_cert cert;
+};
+
+static struct soft_token {
+ CK_VOID_PTR application;
+ CK_NOTIFY notify;
+ char *config_file;
+ hx509_certs certs;
+ struct {
+ struct st_object **objs;
+ int num_objs;
+ } object;
+ struct {
+ int hardware_slot;
+ int app_error_fatal;
+ int login_done;
+ } flags;
+ int open_sessions;
+ struct session_state {
+ CK_SESSION_HANDLE session_handle;
+
+ struct {
+ CK_ATTRIBUTE *attributes;
+ CK_ULONG num_attributes;
+ int next_object;
+ } find;
+
+ int sign_object;
+ CK_MECHANISM_PTR sign_mechanism;
+ int verify_object;
+ CK_MECHANISM_PTR verify_mechanism;
+ } state[10];
+#define MAX_NUM_SESSION (sizeof(soft_token.state)/sizeof(soft_token.state[0]))
+ FILE *logfile;
+} soft_token;
+
+static hx509_context context;
+
+static void
+application_error(const char *fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ vprintf(fmt, ap);
+ va_end(ap);
+ if (soft_token.flags.app_error_fatal)
+ abort();
+}
+
+static void
+st_logf(const char *fmt, ...)
+{
+ va_list ap;
+ if (soft_token.logfile == NULL)
+ return;
+ va_start(ap, fmt);
+ vfprintf(soft_token.logfile, fmt, ap);
+ va_end(ap);
+ fflush(soft_token.logfile);
+}
+
+static CK_RV
+init_context(void)
+{
+ if (context == NULL) {
+ int ret = hx509_context_init(&context);
+ if (ret)
+ return CKR_GENERAL_ERROR;
+ }
+ return CKR_OK;
+}
+
+#define INIT_CONTEXT() { CK_RV icret = init_context(); if (icret) return icret; }
+
+static void
+snprintf_fill(char *str, size_t size, char fillchar, const char *fmt, ...)
+{
+ int len;
+ va_list ap;
+ va_start(ap, fmt);
+ len = vsnprintf(str, size, fmt, ap);
+ va_end(ap);
+ if (len < 0 || (size_t)len > size)
+ return;
+ while ((size_t)len < size)
+ str[len++] = fillchar;
+}
+
+#ifndef TEST_APP
+#define printf error_use_st_logf
+#endif
+
+#define VERIFY_SESSION_HANDLE(s, state) \
+{ \
+ CK_RV xret; \
+ xret = verify_session_handle(s, state); \
+ if (xret != CKR_OK) { \
+ /* return CKR_OK */; \
+ } \
+}
+
+static CK_RV
+verify_session_handle(CK_SESSION_HANDLE hSession,
+ struct session_state **state)
+{
+ size_t i;
+
+ for (i = 0; i < MAX_NUM_SESSION; i++){
+ if (soft_token.state[i].session_handle == hSession)
+ break;
+ }
+ if (i == MAX_NUM_SESSION) {
+ application_error("use of invalid handle: 0x%08lx\n",
+ (unsigned long)hSession);
+ return CKR_SESSION_HANDLE_INVALID;
+ }
+ if (state)
+ *state = &soft_token.state[i];
+ return CKR_OK;
+}
+
+static CK_RV
+object_handle_to_object(CK_OBJECT_HANDLE handle,
+ struct st_object **object)
+{
+ int i = HANDLE_OBJECT_ID(handle);
+
+ *object = NULL;
+ if (i >= soft_token.object.num_objs)
+ return CKR_ARGUMENTS_BAD;
+ if (soft_token.object.objs[i] == NULL)
+ return CKR_ARGUMENTS_BAD;
+ if (soft_token.object.objs[i]->object_handle != handle)
+ return CKR_ARGUMENTS_BAD;
+ *object = soft_token.object.objs[i];
+ return CKR_OK;
+}
+
+static int
+attributes_match(const struct st_object *obj,
+ const CK_ATTRIBUTE *attributes,
+ CK_ULONG num_attributes)
+{
+ CK_ULONG i;
+ int j;
+
+ st_logf("attributes_match: %ld\n", (unsigned long)OBJECT_ID(obj));
+
+ for (i = 0; i < num_attributes; i++) {
+ int match = 0;
+ for (j = 0; j < obj->num_attributes; j++) {
+ if (attributes[i].type == obj->attrs[j].attribute.type &&
+ attributes[i].ulValueLen == obj->attrs[j].attribute.ulValueLen &&
+ memcmp(attributes[i].pValue, obj->attrs[j].attribute.pValue,
+ attributes[i].ulValueLen) == 0) {
+ match = 1;
+ break;
+ }
+ }
+ if (match == 0) {
+ st_logf("type %d attribute have no match\n", attributes[i].type);
+ return 0;
+ }
+ }
+ st_logf("attribute matches\n");
+ return 1;
+}
+
+static void
+print_attributes(const CK_ATTRIBUTE *attributes,
+ CK_ULONG num_attributes)
+{
+ CK_ULONG i;
+
+ st_logf("find objects: attrs: %lu\n", (unsigned long)num_attributes);
+
+ for (i = 0; i < num_attributes; i++) {
+ st_logf(" type: ");
+ switch (attributes[i].type) {
+ case CKA_TOKEN: {
+ CK_BBOOL *ck_true;
+ if (attributes[i].ulValueLen != sizeof(CK_BBOOL)) {
+ application_error("token attribute wrong length\n");
+ break;
+ }
+ ck_true = attributes[i].pValue;
+ st_logf("token: %s", *ck_true ? "TRUE" : "FALSE");
+ break;
+ }
+ case CKA_CLASS: {
+ CK_OBJECT_CLASS *class;
+ if (attributes[i].ulValueLen != sizeof(CK_ULONG)) {
+ application_error("class attribute wrong length\n");
+ break;
+ }
+ class = attributes[i].pValue;
+ st_logf("class ");
+ switch (*class) {
+ case CKO_CERTIFICATE:
+ st_logf("certificate");
+ break;
+ case CKO_PUBLIC_KEY:
+ st_logf("public key");
+ break;
+ case CKO_PRIVATE_KEY:
+ st_logf("private key");
+ break;
+ case CKO_SECRET_KEY:
+ st_logf("secret key");
+ break;
+ case CKO_DOMAIN_PARAMETERS:
+ st_logf("domain parameters");
+ break;
+ default:
+ st_logf("[class %lx]", (long unsigned)*class);
+ break;
+ }
+ break;
+ }
+ case CKA_PRIVATE:
+ st_logf("private");
+ break;
+ case CKA_LABEL:
+ st_logf("label");
+ break;
+ case CKA_APPLICATION:
+ st_logf("application");
+ break;
+ case CKA_VALUE:
+ st_logf("value");
+ break;
+ case CKA_ID:
+ st_logf("id");
+ break;
+ default:
+ st_logf("[unknown 0x%08lx]", (unsigned long)attributes[i].type);
+ break;
+ }
+ st_logf("\n");
+ }
+}
+
+static struct st_object *
+add_st_object(void)
+{
+ struct st_object *o, **objs;
+ int i;
+
+ o = calloc(1, sizeof(*o));
+ if (o == NULL)
+ return NULL;
+
+ for (i = 0; i < soft_token.object.num_objs; i++) {
+ if (soft_token.object.objs[i] == NULL) {
+ soft_token.object.objs[i] = o;
+ break;
+ }
+ }
+ if (i == soft_token.object.num_objs) {
+ objs = realloc(soft_token.object.objs,
+ (soft_token.object.num_objs + 1) * sizeof(soft_token.object.objs[0]));
+ if (objs == NULL) {
+ free(o);
+ return NULL;
+ }
+ soft_token.object.objs = objs;
+ soft_token.object.objs[soft_token.object.num_objs++] = o;
+ }
+ soft_token.object.objs[i]->object_handle =
+ (random() & (~OBJECT_ID_MASK)) | i;
+
+ return o;
+}
+
+static CK_RV
+add_object_attribute(struct st_object *o,
+ int secret,
+ CK_ATTRIBUTE_TYPE type,
+ CK_VOID_PTR pValue,
+ CK_ULONG ulValueLen)
+{
+ struct st_attr *a;
+ int i;
+
+ if (pValue == NULL && ulValueLen)
+ return CKR_ARGUMENTS_BAD;
+
+ i = o->num_attributes;
+ a = realloc(o->attrs, (i + 1) * sizeof(o->attrs[0]));
+ if (a == NULL)
+ return CKR_DEVICE_MEMORY;
+ o->attrs = a;
+ o->attrs[i].secret = secret;
+ o->attrs[i].attribute.type = type;
+ o->attrs[i].attribute.pValue = malloc(ulValueLen);
+ if (o->attrs[i].attribute.pValue == NULL && ulValueLen != 0)
+ return CKR_DEVICE_MEMORY;
+ if (ulValueLen)
+ memcpy(o->attrs[i].attribute.pValue, pValue, ulValueLen);
+ o->attrs[i].attribute.ulValueLen = ulValueLen;
+ o->num_attributes++;
+
+ return CKR_OK;
+}
+
+static CK_RV
+add_pubkey_info(hx509_context hxctx, struct st_object *o,
+ CK_KEY_TYPE key_type, hx509_cert cert)
+{
+ BIGNUM *num;
+ CK_BYTE *modulus = NULL;
+ size_t modulus_len = 0;
+ CK_ULONG modulus_bits = 0;
+ CK_BYTE *exponent = NULL;
+ size_t exponent_len = 0;
+
+ if (key_type != CKK_RSA)
+ return CKR_OK;
+ if (_hx509_cert_private_key(cert) == NULL)
+ return CKR_OK;
+
+ num = _hx509_private_key_get_internal(context,
+ _hx509_cert_private_key(cert),
+ "rsa-modulus");
+ if (num == NULL)
+ return CKR_GENERAL_ERROR;
+ modulus_bits = BN_num_bits(num);
+
+ modulus_len = BN_num_bytes(num);
+ modulus = malloc(modulus_len);
+ BN_bn2bin(num, modulus);
+ BN_free(num);
+
+ add_object_attribute(o, 0, CKA_MODULUS, modulus, modulus_len);
+ add_object_attribute(o, 0, CKA_MODULUS_BITS,
+ &modulus_bits, sizeof(modulus_bits));
+
+ free(modulus);
+
+ num = _hx509_private_key_get_internal(context,
+ _hx509_cert_private_key(cert),
+ "rsa-exponent");
+ if (num == NULL)
+ return CKR_GENERAL_ERROR;
+
+ exponent_len = BN_num_bytes(num);
+ exponent = malloc(exponent_len);
+ BN_bn2bin(num, exponent);
+ BN_free(num);
+
+ add_object_attribute(o, 0, CKA_PUBLIC_EXPONENT,
+ exponent, exponent_len);
+
+ free(exponent);
+
+ return CKR_OK;
+}
+
+
+struct foo {
+ char *label;
+ char *id;
+};
+
+static int HX509_LIB_CALL
+add_cert(hx509_context hxctx, void *ctx, hx509_cert cert)
+{
+ static char empty[] = "";
+ struct foo *foo = (struct foo *)ctx;
+ struct st_object *o = NULL;
+ CK_OBJECT_CLASS type;
+ CK_BBOOL bool_true = CK_TRUE;
+ CK_BBOOL bool_false = CK_FALSE;
+ CK_CERTIFICATE_TYPE cert_type = CKC_X_509;
+ CK_KEY_TYPE key_type;
+ CK_MECHANISM_TYPE mech_type;
+ CK_RV ret = CKR_GENERAL_ERROR;
+ int hret;
+ heim_octet_string cert_data, subject_data, issuer_data, serial_data;
+
+ st_logf("adding certificate\n");
+
+ serial_data.data = NULL;
+ serial_data.length = 0;
+ cert_data = subject_data = issuer_data = serial_data;
+
+ hret = hx509_cert_binary(hxctx, cert, &cert_data);
+ if (hret)
+ goto out;
+
+ {
+ hx509_name name;
+
+ hret = hx509_cert_get_issuer(cert, &name);
+ if (hret)
+ goto out;
+ hret = hx509_name_binary(name, &issuer_data);
+ hx509_name_free(&name);
+ if (hret)
+ goto out;
+
+ hret = hx509_cert_get_subject(cert, &name);
+ if (hret)
+ goto out;
+ hret = hx509_name_binary(name, &subject_data);
+ hx509_name_free(&name);
+ if (hret)
+ goto out;
+ }
+
+ {
+ AlgorithmIdentifier alg;
+
+ hret = hx509_cert_get_SPKI_AlgorithmIdentifier(context, cert, &alg);
+ if (hret) {
+ ret = CKR_DEVICE_MEMORY;
+ goto out;
+ }
+
+ key_type = CKK_RSA; /* XXX */
+
+ free_AlgorithmIdentifier(&alg);
+ }
+
+
+ type = CKO_CERTIFICATE;
+ o = add_st_object();
+ if (o == NULL) {
+ ret = CKR_DEVICE_MEMORY;
+ goto out;
+ }
+
+ o->cert = hx509_cert_ref(cert);
+
+ add_object_attribute(o, 0, CKA_CLASS, &type, sizeof(type));
+ add_object_attribute(o, 0, CKA_TOKEN, &bool_true, sizeof(bool_true));
+ add_object_attribute(o, 0, CKA_PRIVATE, &bool_false, sizeof(bool_false));
+ add_object_attribute(o, 0, CKA_MODIFIABLE, &bool_false, sizeof(bool_false));
+ add_object_attribute(o, 0, CKA_LABEL, foo->label, strlen(foo->label));
+
+ add_object_attribute(o, 0, CKA_CERTIFICATE_TYPE, &cert_type, sizeof(cert_type));
+ add_object_attribute(o, 0, CKA_ID, foo->id, strlen(foo->id));
+
+ add_object_attribute(o, 0, CKA_SUBJECT, subject_data.data, subject_data.length);
+ add_object_attribute(o, 0, CKA_ISSUER, issuer_data.data, issuer_data.length);
+ add_object_attribute(o, 0, CKA_SERIAL_NUMBER, serial_data.data, serial_data.length);
+ add_object_attribute(o, 0, CKA_VALUE, cert_data.data, cert_data.length);
+ add_object_attribute(o, 0, CKA_TRUSTED, &bool_false, sizeof(bool_false));
+
+ st_logf("add cert ok: %lx\n", (unsigned long)OBJECT_ID(o));
+
+ type = CKO_PUBLIC_KEY;
+ o = add_st_object();
+ if (o == NULL) {
+ ret = CKR_DEVICE_MEMORY;
+ goto out;
+ }
+ o->cert = hx509_cert_ref(cert);
+
+ add_object_attribute(o, 0, CKA_CLASS, &type, sizeof(type));
+ add_object_attribute(o, 0, CKA_TOKEN, &bool_true, sizeof(bool_true));
+ add_object_attribute(o, 0, CKA_PRIVATE, &bool_false, sizeof(bool_false));
+ add_object_attribute(o, 0, CKA_MODIFIABLE, &bool_false, sizeof(bool_false));
+ add_object_attribute(o, 0, CKA_LABEL, foo->label, strlen(foo->label));
+
+ add_object_attribute(o, 0, CKA_KEY_TYPE, &key_type, sizeof(key_type));
+ add_object_attribute(o, 0, CKA_ID, foo->id, strlen(foo->id));
+ add_object_attribute(o, 0, CKA_START_DATE, empty, 1); /* XXX */
+ add_object_attribute(o, 0, CKA_END_DATE, empty, 1); /* XXX */
+ add_object_attribute(o, 0, CKA_DERIVE, &bool_false, sizeof(bool_false));
+ add_object_attribute(o, 0, CKA_LOCAL, &bool_false, sizeof(bool_false));
+ mech_type = CKM_RSA_X_509;
+ add_object_attribute(o, 0, CKA_KEY_GEN_MECHANISM, &mech_type, sizeof(mech_type));
+
+ add_object_attribute(o, 0, CKA_SUBJECT, subject_data.data, subject_data.length);
+ add_object_attribute(o, 0, CKA_ENCRYPT, &bool_true, sizeof(bool_true));
+ add_object_attribute(o, 0, CKA_VERIFY, &bool_true, sizeof(bool_true));
+ add_object_attribute(o, 0, CKA_VERIFY_RECOVER, &bool_false, sizeof(bool_false));
+ add_object_attribute(o, 0, CKA_WRAP, &bool_true, sizeof(bool_true));
+ add_object_attribute(o, 0, CKA_TRUSTED, &bool_true, sizeof(bool_true));
+
+ add_pubkey_info(hxctx, o, key_type, cert);
+
+ st_logf("add key ok: %lx\n", (unsigned long)OBJECT_ID(o));
+
+ if (hx509_cert_have_private_key(cert)) {
+ CK_FLAGS flags;
+
+ type = CKO_PRIVATE_KEY;
+
+ /* Note to static analyzers: `o' is still referred to via globals */
+ o = add_st_object();
+ if (o == NULL) {
+ ret = CKR_DEVICE_MEMORY;
+ goto out;
+ }
+ o->cert = hx509_cert_ref(cert);
+
+ add_object_attribute(o, 0, CKA_CLASS, &type, sizeof(type));
+ add_object_attribute(o, 0, CKA_TOKEN, &bool_true, sizeof(bool_true));
+ add_object_attribute(o, 0, CKA_PRIVATE, &bool_true, sizeof(bool_false));
+ add_object_attribute(o, 0, CKA_MODIFIABLE, &bool_false, sizeof(bool_false));
+ add_object_attribute(o, 0, CKA_LABEL, foo->label, strlen(foo->label));
+
+ add_object_attribute(o, 0, CKA_KEY_TYPE, &key_type, sizeof(key_type));
+ add_object_attribute(o, 0, CKA_ID, foo->id, strlen(foo->id));
+ add_object_attribute(o, 0, CKA_START_DATE, empty, 1); /* XXX */
+ add_object_attribute(o, 0, CKA_END_DATE, empty, 1); /* XXX */
+ add_object_attribute(o, 0, CKA_DERIVE, &bool_false, sizeof(bool_false));
+ add_object_attribute(o, 0, CKA_LOCAL, &bool_false, sizeof(bool_false));
+ mech_type = CKM_RSA_X_509;
+ add_object_attribute(o, 0, CKA_KEY_GEN_MECHANISM, &mech_type, sizeof(mech_type));
+
+ add_object_attribute(o, 0, CKA_SUBJECT, subject_data.data, subject_data.length);
+ add_object_attribute(o, 0, CKA_SENSITIVE, &bool_true, sizeof(bool_true));
+ add_object_attribute(o, 0, CKA_SECONDARY_AUTH, &bool_false, sizeof(bool_true));
+ flags = 0;
+ add_object_attribute(o, 0, CKA_AUTH_PIN_FLAGS, &flags, sizeof(flags));
+
+ add_object_attribute(o, 0, CKA_DECRYPT, &bool_true, sizeof(bool_true));
+ add_object_attribute(o, 0, CKA_SIGN, &bool_true, sizeof(bool_true));
+ add_object_attribute(o, 0, CKA_SIGN_RECOVER, &bool_false, sizeof(bool_false));
+ add_object_attribute(o, 0, CKA_UNWRAP, &bool_true, sizeof(bool_true));
+ add_object_attribute(o, 0, CKA_EXTRACTABLE, &bool_true, sizeof(bool_true));
+ add_object_attribute(o, 0, CKA_NEVER_EXTRACTABLE, &bool_false, sizeof(bool_false));
+
+ add_pubkey_info(hxctx, o, key_type, cert);
+ }
+
+ ret = CKR_OK;
+ out:
+ if (ret != CKR_OK) {
+ st_logf("something went wrong when adding cert!\n");
+
+ /* XXX wack o */;
+ }
+ hx509_xfree(cert_data.data);
+ hx509_xfree(serial_data.data);
+ hx509_xfree(issuer_data.data);
+ hx509_xfree(subject_data.data);
+
+ /* Note to static analyzers: `o' is still referred to via globals */
+ return 0;
+}
+
+static CK_RV
+add_certificate(const char *cert_file,
+ const char *pin,
+ char *id,
+ char *label)
+{
+ hx509_certs certs;
+ hx509_lock lock = NULL;
+ int ret, flags = 0;
+
+ struct foo foo;
+ foo.id = id;
+ foo.label = label;
+
+ if (pin == NULL)
+ flags |= HX509_CERTS_UNPROTECT_ALL;
+
+ if (pin) {
+ char *str;
+ ret = asprintf(&str, "PASS:%s", pin);
+ if (ret == -1 || !str) {
+ st_logf("failed to allocate memory\n");
+ return CKR_GENERAL_ERROR;
+ }
+
+ hx509_lock_init(context, &lock);
+ hx509_lock_command_string(lock, str);
+
+ memset(str, 0, strlen(str));
+ free(str);
+ }
+
+ ret = hx509_certs_init(context, cert_file, flags, lock, &certs);
+ if (ret) {
+ st_logf("failed to open file %s\n", cert_file);
+ return CKR_GENERAL_ERROR;
+ }
+
+ ret = hx509_certs_iter_f(context, certs, add_cert, &foo);
+ hx509_certs_free(&certs);
+ if (ret) {
+ st_logf("failed adding certs from file %s\n", cert_file);
+ return CKR_GENERAL_ERROR;
+ }
+
+ return CKR_OK;
+}
+
+static void
+find_object_final(struct session_state *state)
+{
+ if (state->find.attributes) {
+ CK_ULONG i;
+
+ for (i = 0; i < state->find.num_attributes; i++) {
+ if (state->find.attributes[i].pValue)
+ free(state->find.attributes[i].pValue);
+ }
+ free(state->find.attributes);
+ state->find.attributes = NULL;
+ state->find.num_attributes = 0;
+ state->find.next_object = -1;
+ }
+}
+
+static void
+reset_crypto_state(struct session_state *state)
+{
+ state->sign_object = -1;
+ if (state->sign_mechanism)
+ free(state->sign_mechanism);
+ state->sign_mechanism = NULL_PTR;
+ state->verify_object = -1;
+ if (state->verify_mechanism)
+ free(state->verify_mechanism);
+ state->verify_mechanism = NULL_PTR;
+}
+
+static void
+close_session(struct session_state *state)
+{
+ if (state->find.attributes) {
+ application_error("application didn't do C_FindObjectsFinal\n");
+ find_object_final(state);
+ }
+
+ state->session_handle = CK_INVALID_HANDLE;
+ soft_token.application = NULL_PTR;
+ soft_token.notify = NULL_PTR;
+ reset_crypto_state(state);
+}
+
+static const char *
+has_session(void)
+{
+ return soft_token.open_sessions > 0 ? "yes" : "no";
+}
+
+static CK_RV
+read_conf_file(const char *fn, CK_USER_TYPE userType, const char *pin)
+{
+ char buf[1024], *type, *s, *p;
+ FILE *f;
+ CK_RV ret = CKR_OK;
+ CK_RV failed = CKR_OK;
+
+ if (fn == NULL) {
+ st_logf("Can't open configuration file. No file specified\n");
+ return CKR_GENERAL_ERROR;
+ }
+
+ f = fopen(fn, "r");
+ if (f == NULL) {
+ st_logf("can't open configuration file %s\n", fn);
+ return CKR_GENERAL_ERROR;
+ }
+ rk_cloexec_file(f);
+
+ while(fgets(buf, sizeof(buf), f) != NULL) {
+ buf[strcspn(buf, "\n")] = '\0';
+
+ st_logf("line: %s\n", buf);
+
+ p = buf;
+ while (isspace((unsigned char)*p))
+ p++;
+ if (*p == '#')
+ continue;
+ while (isspace((unsigned char)*p))
+ p++;
+
+ s = NULL;
+ type = strtok_r(p, "\t", &s);
+ if (type == NULL)
+ continue;
+
+ if (strcasecmp("certificate", type) == 0) {
+ char *cert, *id, *label;
+
+ id = strtok_r(NULL, "\t", &s);
+ if (id == NULL) {
+ st_logf("no id\n");
+ continue;
+ }
+ st_logf("id: %s\n", id);
+ label = strtok_r(NULL, "\t", &s);
+ if (label == NULL) {
+ st_logf("no label\n");
+ continue;
+ }
+ cert = strtok_r(NULL, "\t", &s);
+ if (cert == NULL) {
+ st_logf("no certfiicate store\n");
+ continue;
+ }
+
+ st_logf("adding: %s: %s in file %s\n", id, label, cert);
+
+ ret = add_certificate(cert, pin, id, label);
+ if (ret)
+ failed = ret;
+ } else if (strcasecmp("debug", type) == 0) {
+ char *name;
+
+ name = strtok_r(NULL, "\t", &s);
+ if (name == NULL) {
+ st_logf("no filename\n");
+ continue;
+ }
+
+ if (soft_token.logfile)
+ fclose(soft_token.logfile);
+
+ if (strcasecmp(name, "stdout") == 0)
+ soft_token.logfile = stdout;
+ else {
+ soft_token.logfile = fopen(name, "a");
+ if (soft_token.logfile)
+ rk_cloexec_file(soft_token.logfile);
+ }
+ if (soft_token.logfile == NULL)
+ st_logf("failed to open file: %s\n", name);
+
+ } else if (strcasecmp("app-fatal", type) == 0) {
+ char *name;
+
+ name = strtok_r(NULL, "\t", &s);
+ if (name == NULL) {
+ st_logf("argument to app-fatal\n");
+ continue;
+ }
+
+ if (strcmp(name, "true") == 0 || strcmp(name, "on") == 0)
+ soft_token.flags.app_error_fatal = 1;
+ else if (strcmp(name, "false") == 0 || strcmp(name, "off") == 0)
+ soft_token.flags.app_error_fatal = 0;
+ else
+ st_logf("unknown app-fatal: %s\n", name);
+
+ } else {
+ st_logf("unknown type: %s\n", type);
+ }
+ }
+
+ fclose(f);
+
+ return failed;
+}
+
+static CK_RV
+func_not_supported(void)
+{
+ st_logf("function not supported\n");
+ return CKR_FUNCTION_NOT_SUPPORTED;
+}
+
+static char *
+get_config_file_for_user(void)
+{
+ char *fn;
+ int ret;
+
+ fn = secure_getenv("SOFTPKCS11RC");
+ if (fn)
+ fn = strdup(fn);
+ if (fn == NULL) {
+ char homebuf[MAX_PATH];
+ const char *home = roken_get_appdatadir(homebuf, sizeof(homebuf));
+
+ if (home) {
+ ret = asprintf(&fn, "%s/.soft-token.rc", home);
+ if (ret == -1)
+ fn = NULL;
+ } else {
+#ifndef WIN32
+ fn = strdup("/etc/soft-token.rc");
+#endif
+ }
+ }
+
+ return fn;
+}
+
+
+CK_RV CK_SPEC
+C_Initialize(CK_VOID_PTR a)
+{
+ CK_C_INITIALIZE_ARGS_PTR args = a;
+ CK_RV ret;
+ size_t i;
+
+ st_logf("Initialize\n");
+
+ INIT_CONTEXT();
+
+ OpenSSL_add_all_algorithms();
+
+ srandom(getpid() ^ (int) time(NULL));
+
+ for (i = 0; i < MAX_NUM_SESSION; i++) {
+ soft_token.state[i].session_handle = CK_INVALID_HANDLE;
+ soft_token.state[i].find.attributes = NULL;
+ soft_token.state[i].find.num_attributes = 0;
+ soft_token.state[i].find.next_object = -1;
+ reset_crypto_state(&soft_token.state[i]);
+ }
+
+ soft_token.flags.hardware_slot = 1;
+ soft_token.flags.app_error_fatal = 0;
+ soft_token.flags.login_done = 0;
+
+ soft_token.object.objs = NULL;
+ soft_token.object.num_objs = 0;
+
+ soft_token.logfile = NULL;
+#if 0
+ soft_token.logfile = stdout;
+#endif
+#if 0
+ soft_token.logfile = fopen("/tmp/log-pkcs11.txt", "a");
+#endif
+
+ if (a != NULL_PTR) {
+ st_logf("\tCreateMutex:\t%p\n", args->CreateMutex);
+ st_logf("\tDestroyMutext\t%p\n", args->DestroyMutex);
+ st_logf("\tLockMutext\t%p\n", args->LockMutex);
+ st_logf("\tUnlockMutext\t%p\n", args->UnlockMutex);
+ st_logf("\tFlags\t%04x\n", (unsigned int)args->flags);
+ }
+
+ soft_token.config_file = get_config_file_for_user();
+
+ /*
+ * This operations doesn't return CKR_OK if any of the
+ * certificates failes to be unparsed (ie password protected).
+ */
+ ret = read_conf_file(soft_token.config_file, CKU_USER, NULL);
+ if (ret == CKR_OK)
+ soft_token.flags.login_done = 1;
+
+ return CKR_OK;
+}
+
+CK_RV
+C_Finalize(CK_VOID_PTR args)
+{
+ size_t i;
+
+ INIT_CONTEXT();
+
+ st_logf("Finalize\n");
+
+ for (i = 0; i < MAX_NUM_SESSION; i++) {
+ if (soft_token.state[i].session_handle != CK_INVALID_HANDLE) {
+ application_error("application finalized without "
+ "closing session\n");
+ close_session(&soft_token.state[i]);
+ }
+ }
+
+ return CKR_OK;
+}
+
+CK_RV
+C_GetInfo(CK_INFO_PTR args)
+{
+ INIT_CONTEXT();
+
+ st_logf("GetInfo\n");
+
+ memset(args, 17, sizeof(*args));
+ args->cryptokiVersion.major = 2;
+ args->cryptokiVersion.minor = 10;
+ snprintf_fill((char *)args->manufacturerID,
+ sizeof(args->manufacturerID),
+ ' ',
+ "Heimdal hx509 SoftToken");
+ snprintf_fill((char *)args->libraryDescription,
+ sizeof(args->libraryDescription), ' ',
+ "Heimdal hx509 SoftToken");
+ args->libraryVersion.major = 2;
+ args->libraryVersion.minor = 0;
+
+ return CKR_OK;
+}
+
+extern CK_FUNCTION_LIST funcs;
+
+CK_RV
+C_GetFunctionList(CK_FUNCTION_LIST_PTR_PTR ppFunctionList)
+{
+ INIT_CONTEXT();
+
+ *ppFunctionList = &funcs;
+ return CKR_OK;
+}
+
+CK_RV
+C_GetSlotList(CK_BBOOL tokenPresent,
+ CK_SLOT_ID_PTR pSlotList,
+ CK_ULONG_PTR pulCount)
+{
+ INIT_CONTEXT();
+ st_logf("GetSlotList: %s\n",
+ tokenPresent ? "tokenPresent" : "token not Present");
+ if (pSlotList)
+ pSlotList[0] = 1;
+ *pulCount = 1;
+ return CKR_OK;
+}
+
+CK_RV
+C_GetSlotInfo(CK_SLOT_ID slotID,
+ CK_SLOT_INFO_PTR pInfo)
+{
+ INIT_CONTEXT();
+ st_logf("GetSlotInfo: slot: %d : %s\n", (int)slotID, has_session());
+
+ memset(pInfo, 18, sizeof(*pInfo));
+
+ if (slotID != 1)
+ return CKR_ARGUMENTS_BAD;
+
+ snprintf_fill((char *)pInfo->slotDescription,
+ sizeof(pInfo->slotDescription),
+ ' ',
+ "Heimdal hx509 SoftToken (slot)");
+ snprintf_fill((char *)pInfo->manufacturerID,
+ sizeof(pInfo->manufacturerID),
+ ' ',
+ "Heimdal hx509 SoftToken (slot)");
+ pInfo->flags = CKF_TOKEN_PRESENT;
+ if (soft_token.flags.hardware_slot)
+ pInfo->flags |= CKF_HW_SLOT;
+ pInfo->hardwareVersion.major = 1;
+ pInfo->hardwareVersion.minor = 0;
+ pInfo->firmwareVersion.major = 1;
+ pInfo->firmwareVersion.minor = 0;
+
+ return CKR_OK;
+}
+
+CK_RV
+C_GetTokenInfo(CK_SLOT_ID slotID,
+ CK_TOKEN_INFO_PTR pInfo)
+{
+ INIT_CONTEXT();
+ st_logf("GetTokenInfo: %s\n", has_session());
+
+ memset(pInfo, 19, sizeof(*pInfo));
+
+ snprintf_fill((char *)pInfo->label,
+ sizeof(pInfo->label),
+ ' ',
+ "Heimdal hx509 SoftToken (token)");
+ snprintf_fill((char *)pInfo->manufacturerID,
+ sizeof(pInfo->manufacturerID),
+ ' ',
+ "Heimdal hx509 SoftToken (token)");
+ snprintf_fill((char *)pInfo->model,
+ sizeof(pInfo->model),
+ ' ',
+ "Heimdal hx509 SoftToken (token)");
+ snprintf_fill((char *)pInfo->serialNumber,
+ sizeof(pInfo->serialNumber),
+ ' ',
+ "4711");
+ pInfo->flags =
+ CKF_TOKEN_INITIALIZED |
+ CKF_USER_PIN_INITIALIZED;
+
+ if (soft_token.flags.login_done == 0)
+ pInfo->flags |= CKF_LOGIN_REQUIRED;
+
+ /* CFK_RNG |
+ CKF_RESTORE_KEY_NOT_NEEDED |
+ */
+ pInfo->ulMaxSessionCount = MAX_NUM_SESSION;
+ pInfo->ulSessionCount = soft_token.open_sessions;
+ pInfo->ulMaxRwSessionCount = MAX_NUM_SESSION;
+ pInfo->ulRwSessionCount = soft_token.open_sessions;
+ pInfo->ulMaxPinLen = 1024;
+ pInfo->ulMinPinLen = 0;
+ pInfo->ulTotalPublicMemory = 4711;
+ pInfo->ulFreePublicMemory = 4712;
+ pInfo->ulTotalPrivateMemory = 4713;
+ pInfo->ulFreePrivateMemory = 4714;
+ pInfo->hardwareVersion.major = 2;
+ pInfo->hardwareVersion.minor = 0;
+ pInfo->firmwareVersion.major = 2;
+ pInfo->firmwareVersion.minor = 0;
+
+ return CKR_OK;
+}
+
+CK_RV
+C_GetMechanismList(CK_SLOT_ID slotID,
+ CK_MECHANISM_TYPE_PTR pMechanismList,
+ CK_ULONG_PTR pulCount)
+{
+ INIT_CONTEXT();
+ st_logf("GetMechanismList\n");
+
+ *pulCount = 1;
+ if (pMechanismList == NULL_PTR)
+ return CKR_OK;
+ pMechanismList[0] = CKM_RSA_PKCS;
+
+ return CKR_OK;
+}
+
+CK_RV
+C_GetMechanismInfo(CK_SLOT_ID slotID,
+ CK_MECHANISM_TYPE type,
+ CK_MECHANISM_INFO_PTR pInfo)
+{
+ INIT_CONTEXT();
+ st_logf("GetMechanismInfo: slot %d type: %d\n",
+ (int)slotID, (int)type);
+ memset(pInfo, 0, sizeof(*pInfo));
+
+ return CKR_OK;
+}
+
+CK_RV
+C_InitToken(CK_SLOT_ID slotID,
+ CK_UTF8CHAR_PTR pPin,
+ CK_ULONG ulPinLen,
+ CK_UTF8CHAR_PTR pLabel)
+{
+ INIT_CONTEXT();
+ st_logf("InitToken: slot %d\n", (int)slotID);
+ return CKR_FUNCTION_NOT_SUPPORTED;
+}
+
+CK_RV
+C_OpenSession(CK_SLOT_ID slotID,
+ CK_FLAGS flags,
+ CK_VOID_PTR pApplication,
+ CK_NOTIFY Notify,
+ CK_SESSION_HANDLE_PTR phSession)
+{
+ size_t i;
+ INIT_CONTEXT();
+ st_logf("OpenSession: slot: %d\n", (int)slotID);
+
+ if (soft_token.open_sessions == MAX_NUM_SESSION)
+ return CKR_SESSION_COUNT;
+
+ soft_token.application = pApplication;
+ soft_token.notify = Notify;
+
+ for (i = 0; i < MAX_NUM_SESSION; i++)
+ if (soft_token.state[i].session_handle == CK_INVALID_HANDLE)
+ break;
+ if (i == MAX_NUM_SESSION)
+ abort();
+
+ soft_token.open_sessions++;
+
+ soft_token.state[i].session_handle =
+ (CK_SESSION_HANDLE)(random() & 0xfffff);
+ *phSession = soft_token.state[i].session_handle;
+
+ return CKR_OK;
+}
+
+CK_RV
+C_CloseSession(CK_SESSION_HANDLE hSession)
+{
+ struct session_state *state;
+ INIT_CONTEXT();
+ st_logf("CloseSession\n");
+
+ if (verify_session_handle(hSession, &state) != CKR_OK)
+ application_error("closed session not open");
+ else
+ close_session(state);
+
+ return CKR_OK;
+}
+
+CK_RV
+C_CloseAllSessions(CK_SLOT_ID slotID)
+{
+ size_t i;
+ INIT_CONTEXT();
+
+ st_logf("CloseAllSessions\n");
+
+ for (i = 0; i < MAX_NUM_SESSION; i++)
+ if (soft_token.state[i].session_handle != CK_INVALID_HANDLE)
+ close_session(&soft_token.state[i]);
+
+ return CKR_OK;
+}
+
+CK_RV
+C_GetSessionInfo(CK_SESSION_HANDLE hSession,
+ CK_SESSION_INFO_PTR pInfo)
+{
+ st_logf("GetSessionInfo\n");
+ INIT_CONTEXT();
+
+ VERIFY_SESSION_HANDLE(hSession, NULL);
+
+ memset(pInfo, 20, sizeof(*pInfo));
+
+ pInfo->slotID = 1;
+ if (soft_token.flags.login_done)
+ pInfo->state = CKS_RO_USER_FUNCTIONS;
+ else
+ pInfo->state = CKS_RO_PUBLIC_SESSION;
+ pInfo->flags = CKF_SERIAL_SESSION;
+ pInfo->ulDeviceError = 0;
+
+ return CKR_OK;
+}
+
+CK_RV
+C_Login(CK_SESSION_HANDLE hSession,
+ CK_USER_TYPE userType,
+ CK_UTF8CHAR_PTR pPin,
+ CK_ULONG ulPinLen)
+{
+ char *pin = NULL;
+ CK_RV ret;
+ INIT_CONTEXT();
+
+ st_logf("Login\n");
+
+ VERIFY_SESSION_HANDLE(hSession, NULL);
+
+ if (pPin != NULL_PTR) {
+ int aret;
+
+ aret = asprintf(&pin, "%.*s", (int)ulPinLen, pPin);
+ if (aret != -1 && pin)
+ st_logf("type: %d password: %s\n", (int)userType, pin);
+ else
+ st_logf("memory error: asprintf failed\n");
+ }
+
+ /*
+ * Login
+ */
+
+ ret = read_conf_file(soft_token.config_file, userType, pin);
+ if (ret == CKR_OK)
+ soft_token.flags.login_done = 1;
+
+ free(pin);
+
+ return soft_token.flags.login_done ? CKR_OK : CKR_PIN_INCORRECT;
+}
+
+CK_RV
+C_Logout(CK_SESSION_HANDLE hSession)
+{
+ st_logf("Logout\n");
+ INIT_CONTEXT();
+
+ VERIFY_SESSION_HANDLE(hSession, NULL);
+ return CKR_FUNCTION_NOT_SUPPORTED;
+}
+
+CK_RV
+C_GetObjectSize(CK_SESSION_HANDLE hSession,
+ CK_OBJECT_HANDLE hObject,
+ CK_ULONG_PTR pulSize)
+{
+ st_logf("GetObjectSize\n");
+ INIT_CONTEXT();
+
+ VERIFY_SESSION_HANDLE(hSession, NULL);
+ return CKR_FUNCTION_NOT_SUPPORTED;
+}
+
+CK_RV
+C_GetAttributeValue(CK_SESSION_HANDLE hSession,
+ CK_OBJECT_HANDLE hObject,
+ CK_ATTRIBUTE_PTR pTemplate,
+ CK_ULONG ulCount)
+{
+ struct session_state *state;
+ struct st_object *obj;
+ CK_ULONG i;
+ CK_RV ret;
+ int j;
+
+ INIT_CONTEXT();
+
+ st_logf("GetAttributeValue: %lx\n",
+ (unsigned long)HANDLE_OBJECT_ID(hObject));
+ VERIFY_SESSION_HANDLE(hSession, &state);
+
+ if ((ret = object_handle_to_object(hObject, &obj)) != CKR_OK) {
+ st_logf("object not found: %lx\n",
+ (unsigned long)HANDLE_OBJECT_ID(hObject));
+ return ret;
+ }
+
+ for (i = 0; i < ulCount; i++) {
+ st_logf(" getting 0x%08lx\n", (unsigned long)pTemplate[i].type);
+ for (j = 0; j < obj->num_attributes; j++) {
+ if (obj->attrs[j].secret) {
+ pTemplate[i].ulValueLen = (CK_ULONG)-1;
+ break;
+ }
+ if (pTemplate[i].type == obj->attrs[j].attribute.type) {
+ if (pTemplate[i].pValue != NULL_PTR && obj->attrs[j].secret == 0) {
+ if (pTemplate[i].ulValueLen >= obj->attrs[j].attribute.ulValueLen)
+ memcpy(pTemplate[i].pValue, obj->attrs[j].attribute.pValue,
+ obj->attrs[j].attribute.ulValueLen);
+ }
+ pTemplate[i].ulValueLen = obj->attrs[j].attribute.ulValueLen;
+ break;
+ }
+ }
+ if (j == obj->num_attributes) {
+ st_logf("key type: 0x%08lx not found\n", (unsigned long)pTemplate[i].type);
+ pTemplate[i].ulValueLen = (CK_ULONG)-1;
+ }
+
+ }
+ return CKR_OK;
+}
+
+CK_RV
+C_FindObjectsInit(CK_SESSION_HANDLE hSession,
+ CK_ATTRIBUTE_PTR pTemplate,
+ CK_ULONG ulCount)
+{
+ struct session_state *state;
+
+ st_logf("FindObjectsInit\n");
+
+ INIT_CONTEXT();
+
+ VERIFY_SESSION_HANDLE(hSession, &state);
+
+ if (state->find.next_object != -1) {
+ application_error("application didn't do C_FindObjectsFinal\n");
+ find_object_final(state);
+ }
+ if (ulCount) {
+ CK_ULONG i;
+
+ print_attributes(pTemplate, ulCount);
+
+ state->find.attributes =
+ calloc(1, ulCount * sizeof(state->find.attributes[0]));
+ if (state->find.attributes == NULL)
+ return CKR_DEVICE_MEMORY;
+ for (i = 0; i < ulCount; i++) {
+ state->find.attributes[i].pValue =
+ malloc(pTemplate[i].ulValueLen);
+ if (state->find.attributes[i].pValue == NULL) {
+ find_object_final(state);
+ return CKR_DEVICE_MEMORY;
+ }
+ memcpy(state->find.attributes[i].pValue,
+ pTemplate[i].pValue, pTemplate[i].ulValueLen);
+ state->find.attributes[i].type = pTemplate[i].type;
+ state->find.attributes[i].ulValueLen = pTemplate[i].ulValueLen;
+ }
+ state->find.num_attributes = ulCount;
+ state->find.next_object = 0;
+ } else {
+ st_logf("find all objects\n");
+ state->find.attributes = NULL;
+ state->find.num_attributes = 0;
+ state->find.next_object = 0;
+ }
+
+ return CKR_OK;
+}
+
+CK_RV
+C_FindObjects(CK_SESSION_HANDLE hSession,
+ CK_OBJECT_HANDLE_PTR phObject,
+ CK_ULONG ulMaxObjectCount,
+ CK_ULONG_PTR pulObjectCount)
+{
+ struct session_state *state;
+ int i;
+
+ INIT_CONTEXT();
+
+ st_logf("FindObjects\n");
+
+ VERIFY_SESSION_HANDLE(hSession, &state);
+
+ if (state->find.next_object == -1) {
+ application_error("application didn't do C_FindObjectsInit\n");
+ return CKR_ARGUMENTS_BAD;
+ }
+ if (ulMaxObjectCount == 0) {
+ application_error("application asked for 0 objects\n");
+ return CKR_ARGUMENTS_BAD;
+ }
+ *pulObjectCount = 0;
+ for (i = state->find.next_object; i < soft_token.object.num_objs; i++) {
+ st_logf("FindObjects: %d\n", i);
+ state->find.next_object = i + 1;
+ if (attributes_match(soft_token.object.objs[i],
+ state->find.attributes,
+ state->find.num_attributes)) {
+ *phObject++ = soft_token.object.objs[i]->object_handle;
+ ulMaxObjectCount--;
+ (*pulObjectCount)++;
+ if (ulMaxObjectCount == 0)
+ break;
+ }
+ }
+ return CKR_OK;
+}
+
+CK_RV
+C_FindObjectsFinal(CK_SESSION_HANDLE hSession)
+{
+ struct session_state *state;
+
+ INIT_CONTEXT();
+
+ st_logf("FindObjectsFinal\n");
+ VERIFY_SESSION_HANDLE(hSession, &state);
+ find_object_final(state);
+ return CKR_OK;
+}
+
+static CK_RV
+commonInit(CK_ATTRIBUTE *attr_match, int attr_match_len,
+ const CK_MECHANISM_TYPE *mechs, int mechs_len,
+ const CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey,
+ struct st_object **o)
+{
+ CK_RV ret;
+ int i;
+
+ *o = NULL;
+ if ((ret = object_handle_to_object(hKey, o)) != CKR_OK)
+ return ret;
+
+ ret = attributes_match(*o, attr_match, attr_match_len);
+ if (!ret) {
+ application_error("called commonInit on key that doesn't "
+ "support required attr");
+ return CKR_ARGUMENTS_BAD;
+ }
+
+ for (i = 0; i < mechs_len; i++)
+ if (mechs[i] == pMechanism->mechanism)
+ break;
+ if (i == mechs_len) {
+ application_error("called mech (%08lx) not supported\n",
+ pMechanism->mechanism);
+ return CKR_ARGUMENTS_BAD;
+ }
+ return CKR_OK;
+}
+
+
+static CK_RV
+dup_mechanism(CK_MECHANISM_PTR *dp, const CK_MECHANISM_PTR pMechanism)
+{
+ CK_MECHANISM_PTR p;
+
+ p = malloc(sizeof(*p));
+ if (p == NULL)
+ return CKR_DEVICE_MEMORY;
+
+ if (*dp)
+ free(*dp);
+ *dp = p;
+ memcpy(p, pMechanism, sizeof(*p));
+
+ return CKR_OK;
+}
+
+CK_RV
+C_DigestInit(CK_SESSION_HANDLE hSession,
+ CK_MECHANISM_PTR pMechanism)
+{
+ st_logf("DigestInit\n");
+ INIT_CONTEXT();
+ VERIFY_SESSION_HANDLE(hSession, NULL);
+ return CKR_FUNCTION_NOT_SUPPORTED;
+}
+
+CK_RV
+C_SignInit(CK_SESSION_HANDLE hSession,
+ CK_MECHANISM_PTR pMechanism,
+ CK_OBJECT_HANDLE hKey)
+{
+ struct session_state *state;
+ CK_MECHANISM_TYPE mechs[] = { CKM_RSA_PKCS };
+ CK_BBOOL bool_true = CK_TRUE;
+ CK_ATTRIBUTE attr[] = {
+ { CKA_SIGN, &bool_true, sizeof(bool_true) }
+ };
+ struct st_object *o;
+ CK_RV ret;
+
+ INIT_CONTEXT();
+ st_logf("SignInit\n");
+ VERIFY_SESSION_HANDLE(hSession, &state);
+
+ ret = commonInit(attr, sizeof(attr)/sizeof(attr[0]),
+ mechs, sizeof(mechs)/sizeof(mechs[0]),
+ pMechanism, hKey, &o);
+ if (ret)
+ return ret;
+
+ ret = dup_mechanism(&state->sign_mechanism, pMechanism);
+ if (ret == CKR_OK)
+ state->sign_object = OBJECT_ID(o);
+
+ return CKR_OK;
+}
+
+CK_RV
+C_Sign(CK_SESSION_HANDLE hSession,
+ CK_BYTE_PTR pData,
+ CK_ULONG ulDataLen,
+ CK_BYTE_PTR pSignature,
+ CK_ULONG_PTR pulSignatureLen)
+{
+ struct session_state *state;
+ struct st_object *o;
+ CK_RV ret;
+ int hret;
+ const AlgorithmIdentifier *alg;
+ heim_octet_string sig, data;
+
+ INIT_CONTEXT();
+ st_logf("Sign\n");
+ VERIFY_SESSION_HANDLE(hSession, &state);
+
+ sig.data = NULL;
+ sig.length = 0;
+
+ if (state->sign_object == -1)
+ return CKR_ARGUMENTS_BAD;
+
+ if (pulSignatureLen == NULL) {
+ st_logf("signature len NULL\n");
+ ret = CKR_ARGUMENTS_BAD;
+ goto out;
+ }
+
+ if (pData == NULL_PTR) {
+ st_logf("data NULL\n");
+ ret = CKR_ARGUMENTS_BAD;
+ goto out;
+ }
+
+ o = soft_token.object.objs[state->sign_object];
+
+ if (hx509_cert_have_private_key(o->cert) == 0) {
+ st_logf("private key NULL\n");
+ return CKR_ARGUMENTS_BAD;
+ }
+
+ switch(state->sign_mechanism->mechanism) {
+ case CKM_RSA_PKCS:
+ alg = hx509_signature_rsa_pkcs1_x509();
+ break;
+ default:
+ ret = CKR_FUNCTION_NOT_SUPPORTED;
+ goto out;
+ }
+
+ data.data = pData;
+ data.length = ulDataLen;
+
+ hret = _hx509_create_signature(context,
+ _hx509_cert_private_key(o->cert),
+ alg,
+ &data,
+ NULL,
+ &sig);
+ if (hret) {
+ ret = CKR_DEVICE_ERROR;
+ goto out;
+ }
+ *pulSignatureLen = sig.length;
+
+ if (pSignature != NULL_PTR)
+ memcpy(pSignature, sig.data, sig.length);
+
+ ret = CKR_OK;
+ out:
+ if (sig.data) {
+ memset(sig.data, 0, sig.length);
+ der_free_octet_string(&sig);
+ }
+ return ret;
+}
+
+CK_RV
+C_SignUpdate(CK_SESSION_HANDLE hSession,
+ CK_BYTE_PTR pPart,
+ CK_ULONG ulPartLen)
+{
+ INIT_CONTEXT();
+ st_logf("SignUpdate\n");
+ VERIFY_SESSION_HANDLE(hSession, NULL);
+ return CKR_FUNCTION_NOT_SUPPORTED;
+}
+
+
+CK_RV
+C_SignFinal(CK_SESSION_HANDLE hSession,
+ CK_BYTE_PTR pSignature,
+ CK_ULONG_PTR pulSignatureLen)
+{
+ INIT_CONTEXT();
+ st_logf("SignUpdate\n");
+ VERIFY_SESSION_HANDLE(hSession, NULL);
+ return CKR_FUNCTION_NOT_SUPPORTED;
+}
+
+CK_RV
+C_VerifyInit(CK_SESSION_HANDLE hSession,
+ CK_MECHANISM_PTR pMechanism,
+ CK_OBJECT_HANDLE hKey)
+{
+ struct session_state *state;
+ CK_MECHANISM_TYPE mechs[] = { CKM_RSA_PKCS };
+ CK_BBOOL bool_true = CK_TRUE;
+ CK_ATTRIBUTE attr[] = {
+ { CKA_VERIFY, &bool_true, sizeof(bool_true) }
+ };
+ struct st_object *o;
+ CK_RV ret;
+
+ INIT_CONTEXT();
+ st_logf("VerifyInit\n");
+ VERIFY_SESSION_HANDLE(hSession, &state);
+
+ ret = commonInit(attr, sizeof(attr)/sizeof(attr[0]),
+ mechs, sizeof(mechs)/sizeof(mechs[0]),
+ pMechanism, hKey, &o);
+ if (ret)
+ return ret;
+
+ ret = dup_mechanism(&state->verify_mechanism, pMechanism);
+ if (ret == CKR_OK)
+ state->verify_object = OBJECT_ID(o);
+
+ return ret;
+}
+
+CK_RV
+C_Verify(CK_SESSION_HANDLE hSession,
+ CK_BYTE_PTR pData,
+ CK_ULONG ulDataLen,
+ CK_BYTE_PTR pSignature,
+ CK_ULONG ulSignatureLen)
+{
+ struct session_state *state;
+ struct st_object *o;
+ const AlgorithmIdentifier *alg;
+ CK_RV ret;
+ int hret;
+ heim_octet_string data, sig;
+
+ INIT_CONTEXT();
+ st_logf("Verify\n");
+ VERIFY_SESSION_HANDLE(hSession, &state);
+
+ if (state->verify_object == -1)
+ return CKR_ARGUMENTS_BAD;
+
+ o = soft_token.object.objs[state->verify_object];
+
+ switch(state->verify_mechanism->mechanism) {
+ case CKM_RSA_PKCS:
+ alg = hx509_signature_rsa_pkcs1_x509();
+ break;
+ default:
+ ret = CKR_FUNCTION_NOT_SUPPORTED;
+ goto out;
+ }
+
+ sig.data = pData;
+ sig.length = ulDataLen;
+ data.data = pSignature;
+ data.length = ulSignatureLen;
+
+ hret = _hx509_verify_signature(context,
+ o->cert,
+ alg,
+ &data,
+ &sig);
+ if (hret) {
+ ret = CKR_GENERAL_ERROR;
+ goto out;
+ }
+ ret = CKR_OK;
+
+ out:
+ return ret;
+}
+
+
+CK_RV
+C_VerifyUpdate(CK_SESSION_HANDLE hSession,
+ CK_BYTE_PTR pPart,
+ CK_ULONG ulPartLen)
+{
+ INIT_CONTEXT();
+ st_logf("VerifyUpdate\n");
+ VERIFY_SESSION_HANDLE(hSession, NULL);
+ return CKR_FUNCTION_NOT_SUPPORTED;
+}
+
+CK_RV
+C_VerifyFinal(CK_SESSION_HANDLE hSession,
+ CK_BYTE_PTR pSignature,
+ CK_ULONG ulSignatureLen)
+{
+ INIT_CONTEXT();
+ st_logf("VerifyFinal\n");
+ VERIFY_SESSION_HANDLE(hSession, NULL);
+ return CKR_FUNCTION_NOT_SUPPORTED;
+}
+
+CK_RV
+C_GenerateRandom(CK_SESSION_HANDLE hSession,
+ CK_BYTE_PTR RandomData,
+ CK_ULONG ulRandomLen)
+{
+ INIT_CONTEXT();
+ st_logf("GenerateRandom\n");
+ VERIFY_SESSION_HANDLE(hSession, NULL);
+ return CKR_FUNCTION_NOT_SUPPORTED;
+}
+
+
+CK_FUNCTION_LIST funcs = {
+ { 2, 11 },
+ C_Initialize,
+ C_Finalize,
+ C_GetInfo,
+ C_GetFunctionList,
+ C_GetSlotList,
+ C_GetSlotInfo,
+ C_GetTokenInfo,
+ C_GetMechanismList,
+ C_GetMechanismInfo,
+ C_InitToken,
+ (void *)func_not_supported, /* C_InitPIN */
+ (void *)func_not_supported, /* C_SetPIN */
+ C_OpenSession,
+ C_CloseSession,
+ C_CloseAllSessions,
+ C_GetSessionInfo,
+ (void *)func_not_supported, /* C_GetOperationState */
+ (void *)func_not_supported, /* C_SetOperationState */
+ C_Login,
+ C_Logout,
+ (void *)func_not_supported, /* C_CreateObject */
+ (void *)func_not_supported, /* C_CopyObject */
+ (void *)func_not_supported, /* C_DestroyObject */
+ (void *)func_not_supported, /* C_GetObjectSize */
+ C_GetAttributeValue,
+ (void *)func_not_supported, /* C_SetAttributeValue */
+ C_FindObjectsInit,
+ C_FindObjects,
+ C_FindObjectsFinal,
+ (void *)func_not_supported, /* C_EncryptInit, */
+ (void *)func_not_supported, /* C_Encrypt, */
+ (void *)func_not_supported, /* C_EncryptUpdate, */
+ (void *)func_not_supported, /* C_EncryptFinal, */
+ (void *)func_not_supported, /* C_DecryptInit, */
+ (void *)func_not_supported, /* C_Decrypt, */
+ (void *)func_not_supported, /* C_DecryptUpdate, */
+ (void *)func_not_supported, /* C_DecryptFinal, */
+ C_DigestInit,
+ (void *)func_not_supported, /* C_Digest */
+ (void *)func_not_supported, /* C_DigestUpdate */
+ (void *)func_not_supported, /* C_DigestKey */
+ (void *)func_not_supported, /* C_DigestFinal */
+ C_SignInit,
+ C_Sign,
+ C_SignUpdate,
+ C_SignFinal,
+ (void *)func_not_supported, /* C_SignRecoverInit */
+ (void *)func_not_supported, /* C_SignRecover */
+ C_VerifyInit,
+ C_Verify,
+ C_VerifyUpdate,
+ C_VerifyFinal,
+ (void *)func_not_supported, /* C_VerifyRecoverInit */
+ (void *)func_not_supported, /* C_VerifyRecover */
+ (void *)func_not_supported, /* C_DigestEncryptUpdate */
+ (void *)func_not_supported, /* C_DecryptDigestUpdate */
+ (void *)func_not_supported, /* C_SignEncryptUpdate */
+ (void *)func_not_supported, /* C_DecryptVerifyUpdate */
+ (void *)func_not_supported, /* C_GenerateKey */
+ (void *)func_not_supported, /* C_GenerateKeyPair */
+ (void *)func_not_supported, /* C_WrapKey */
+ (void *)func_not_supported, /* C_UnwrapKey */
+ (void *)func_not_supported, /* C_DeriveKey */
+ (void *)func_not_supported, /* C_SeedRandom */
+ C_GenerateRandom,
+ (void *)func_not_supported, /* C_GetFunctionStatus */
+ (void *)func_not_supported, /* C_CancelFunction */
+ (void *)func_not_supported /* C_WaitForSlotEvent */
+};
diff --git a/third_party/heimdal/lib/hx509/test_ca.in b/third_party/heimdal/lib/hx509/test_ca.in
new file mode 100644
index 0000000..cf739a1
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_ca.in
@@ -0,0 +1,480 @@
+#!/bin/sh
+#
+# Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# $Id$
+#
+
+srcdir="@srcdir@"
+objdir="@objdir@"
+
+stat="--statistic-file=${objdir}/statfile"
+
+hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}"
+
+if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then
+ exit 77
+fi
+if ${hxtool} info | grep 'rand: not available' > /dev/null ; then
+ exit 77
+fi
+
+echo "create certificate request"
+${hxtool} request-create \
+ --subject="CN=Love,DC=it,DC=su,DC=se" \
+ --key=FILE:$srcdir/data/key.der \
+ pkcs10-request.der || exit 1
+
+echo "issue certificate"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \
+ --subject="cn=foo" \
+ --req="PKCS10:pkcs10-request.der" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+
+echo "verify certificate"
+${hxtool} verify --missing-revoke \
+ cert:FILE:cert-ee.pem \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "issue crl (no cert)"
+${hxtool} crl-sign \
+ --crl-file=crl.crl \
+ --signer=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key || exit 1
+
+echo "verify certificate (with CRL)"
+${hxtool} verify \
+ cert:FILE:cert-ee.pem \
+ crl:FILE:crl.crl \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "issue crl (with cert)"
+${hxtool} crl-sign \
+ --crl-file=crl.crl \
+ --signer=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \
+ FILE:cert-ee.pem || exit 1
+
+echo "verify certificate (included in CRL)"
+${hxtool} verify \
+ cert:FILE:cert-ee.pem \
+ crl:FILE:crl.crl \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1
+
+# XXX Check that the certs issued below have the requested content
+
+echo "issue crl (with cert)"
+${hxtool} crl-sign \
+ --crl-file=crl.crl \
+ --lifetime='1 month' \
+ --signer=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \
+ FILE:cert-ee.pem || exit 1
+
+echo "verify certificate (included in CRL, and lifetime 1 month)"
+${hxtool} verify \
+ cert:FILE:cert-ee.pem \
+ crl:FILE:crl.crl \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1
+
+echo "issue certificate (10years 1 month)"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \
+ --subject="cn=foo" \
+ --lifetime="10years 1 month" \
+ --req="PKCS10:pkcs10-request.der" \
+ --permanent-id=1.2.3.4.5.6.6:SomeVendor:A0B1C2D3 \
+ --hardware-module-name=tcg-tpm20:SomeVendor:Z0Y1X2W3 \
+ --policy="1.2.3.4.5.6:data:foo this is a warning" \
+ --policy="id-x509-ce-certificatePolicies-anyPolicy" \
+ --policy-mapping="1.2.3.4.5.6:1.2.3.4.5.6" \
+ --policy-mapping="1.2.3.4.5.6:1.2.3.4.5.7" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+${hxtool} print --content FILE:cert-ee.pem || exit 1
+
+echo "issue certificate (with https ekus)"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \
+ --subject="cn=foo" \
+ --type="https-server" \
+ --type="https-client" \
+ --req="PKCS10:pkcs10-request.der" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+${hxtool} print --content FILE:cert-ee.pem || exit 1
+
+echo "issue certificate (pkinit KDC)"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \
+ --subject="cn=foo" \
+ --type="pkinit-kdc" \
+ --pk-init-principal="krbtgt/TEST.H5L.SE@TEST.H5L.SE" \
+ --req="PKCS10:pkcs10-request.der" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+${hxtool} print --content FILE:cert-ee.pem || exit 1
+
+echo "issue certificate (pkinit client)"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \
+ --subject="cn=foo" \
+ --type="pkinit-client" \
+ --pk-init-principal="lha@TEST.H5L.SE" \
+ --req="PKCS10:pkcs10-request.der" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+${hxtool} print --content FILE:cert-ee.pem || exit 1
+
+echo "issue certificate (hostnames)"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \
+ --subject="cn=foo" \
+ --type="https-server" \
+ --hostname="www.test.h5l.se" \
+ --hostname="ftp.test.h5l.se" \
+ --req="PKCS10:pkcs10-request.der" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+${hxtool} print --content FILE:cert-ee.pem || exit 1
+
+echo "verify certificate hostname (ok)"
+${hxtool} verify --missing-revoke \
+ --hostname=www.test.h5l.se \
+ cert:FILE:cert-ee.pem \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "verify certificate hostname (fail)"
+${hxtool} verify --missing-revoke \
+ --hostname=www2.test.h5l.se \
+ cert:FILE:cert-ee.pem \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1
+
+echo "verify certificate hostname (fail)"
+${hxtool} verify --missing-revoke \
+ --hostname=2www.test.h5l.se \
+ cert:FILE:cert-ee.pem \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1
+
+echo "issue certificate (hostname in CN)"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \
+ --subject="cn=www.test.h5l.se" \
+ --type="https-server" \
+ --req="PKCS10:pkcs10-request.der" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+${hxtool} print --content FILE:cert-ee.pem || exit 1
+
+echo "verify certificate hostname (ok)"
+${hxtool} verify --missing-revoke \
+ --hostname=www.test.h5l.se \
+ cert:FILE:cert-ee.pem \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "verify certificate hostname (fail)"
+${hxtool} verify --missing-revoke \
+ --hostname=www2.test.h5l.se \
+ cert:FILE:cert-ee.pem \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1
+
+echo "issue certificate (email)"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \
+ --subject="cn=foo" \
+ --email="lha@test.h5l.se" \
+ --email="test@test.h5l.se" \
+ --req="PKCS10:pkcs10-request.der" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+${hxtool} print --content FILE:cert-ee.pem || exit 1
+
+echo "issue certificate (email, null subject DN)"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \
+ --subject="" \
+ --email="lha@test.h5l.se" \
+ --req="PKCS10:pkcs10-request.der" \
+ --certificate="FILE:cert-null.pem" || exit 1
+${hxtool} print --content FILE:cert-null.pem || exit 1
+
+echo "issue certificate (jabber)"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \
+ --subject="cn=foo" \
+ --jid="lha@test.h5l.se" \
+ --req="PKCS10:pkcs10-request.der" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+${hxtool} print --content FILE:cert-ee.pem || exit 1
+
+echo "issue self-signed cert"
+${hxtool} issue-certificate \
+ --self-signed \
+ --ca-private-key=FILE:$srcdir/data/key.der \
+ --subject="cn=test" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+${hxtool} print --content FILE:cert-ee.pem || exit 1
+
+echo "issue ca cert"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \
+ --issue-ca \
+ --subject="cn=ca-cert" \
+ --req="PKCS10:pkcs10-request.der" \
+ --certificate="FILE:cert-ca.der" || exit 1
+${hxtool} print --content FILE:cert-ca.der || exit 1
+
+echo "issue self-signed ca cert"
+${hxtool} issue-certificate \
+ --self-signed \
+ --issue-ca \
+ --ca-private-key=FILE:$srcdir/data/key.der \
+ --subject="cn=ca-root" \
+ --certificate="FILE:cert-ca.der" || exit 1
+${hxtool} print --content FILE:cert-ca.der || exit 1
+
+echo "issue proxy certificate"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ --issue-proxy \
+ --req="PKCS10:pkcs10-request.der" \
+ --certificate="FILE:cert-proxy.der" || exit 1
+${hxtool} print --content FILE:cert-proxy.der || exit 1
+
+echo "verify proxy cert"
+${hxtool} verify --missing-revoke \
+ --allow-proxy-certificate \
+ cert:FILE:cert-proxy.der \
+ chain:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "issue ca cert (generate rsa key)"
+${hxtool} issue-certificate \
+ --self-signed \
+ --issue-ca \
+ --serial-number="deadbeaf" \
+ --generate-key=rsa \
+ --path-length=-1 \
+ --subject="cn=ca2-cert" \
+ --certificate="FILE:cert-ca.pem" || exit 1
+${hxtool} print --content FILE:cert-ca.pem || exit 1
+
+echo "issue sub-ca cert (generate rsa key)"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:cert-ca.pem \
+ --issue-ca \
+ --serial-number="deadbeaf22" \
+ --generate-key=rsa \
+ --subject="cn=sub-ca2-cert" \
+ --certificate="FILE:cert-sub-ca.pem" || exit 1
+${hxtool} print --content FILE:cert-sub-ca.pem || exit 1
+
+echo "issue ee cert (generate rsa key)"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:cert-ca.pem \
+ --generate-key=rsa \
+ --subject="cn=cert-ee2" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+${hxtool} print --content FILE:cert-ee.pem || exit 1
+
+echo "issue sub-ca ee cert (generate rsa key)"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:cert-sub-ca.pem \
+ --generate-key=rsa \
+ --subject="cn=cert-sub-ee2" \
+ --certificate="FILE:cert-sub-ee.pem" || exit 1
+${hxtool} print --content FILE:cert-sub-ee.pem || exit 1
+
+echo "verify certificate (ee)"
+${hxtool} verify --missing-revoke \
+ cert:FILE:cert-ee.pem \
+ anchor:FILE:cert-ca.pem > /dev/null || exit 1
+
+echo "verify certificate (sub-ee)"
+${hxtool} verify --missing-revoke \
+ cert:FILE:cert-sub-ee.pem \
+ chain:FILE:cert-sub-ca.pem \
+ anchor:FILE:cert-ca.pem || exit 1
+
+echo "sign CMS signature (generate key)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:cert-ee.pem \
+ "$srcdir/test_name.c" \
+ sd.data > /dev/null || exit 1
+
+echo "verify CMS signature (generate key)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:cert-ca.pem \
+ sd.data sd.data.out > /dev/null || exit 1
+cmp "$srcdir/test_name.c" sd.data.out || exit 1
+
+echo "extend ca cert"
+${hxtool} issue-certificate \
+ --self-signed \
+ --issue-ca \
+ --lifetime="2years" \
+ --serial-number="deadbeaf" \
+ --ca-private-key=FILE:cert-ca.pem \
+ --subject="cn=ca2-cert" \
+ --certificate="FILE:cert-ca.pem" || exit 1
+${hxtool} print --content FILE:cert-ca.pem || exit 1
+
+echo "verify certificate generated by previous ca"
+${hxtool} verify --missing-revoke \
+ cert:FILE:cert-ee.pem \
+ anchor:FILE:cert-ca.pem > /dev/null || exit 1
+
+echo "extend ca cert (template)"
+${hxtool} issue-certificate \
+ --self-signed \
+ --issue-ca \
+ --lifetime="3years" \
+ --template-certificate="FILE:cert-ca.pem" \
+ --template-fields="serialNumber,notBefore,subject" \
+ --path-length=-1 \
+ --ca-private-key=FILE:cert-ca.pem \
+ --certificate="FILE:cert-ca.pem" || exit 1
+${hxtool} print --content FILE:cert-ca.pem || exit 1
+
+echo "verify certificate generated by previous ca"
+${hxtool} verify --missing-revoke \
+ cert:FILE:cert-ee.pem \
+ anchor:FILE:cert-ca.pem > /dev/null || exit 1
+
+echo "extend sub-ca cert (template)"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:cert-ca.pem \
+ --issue-ca \
+ --lifetime="2years" \
+ --template-certificate="FILE:cert-sub-ca.pem" \
+ --template-fields="serialNumber,notBefore,subject,SPKI" \
+ --certificate="FILE:cert-sub-ca2.pem" || exit 1
+${hxtool} print --content FILE:cert-sub-ca2.pem || exit 1
+
+echo "verify certificate (sub-ee) with extended chain"
+${hxtool} verify --missing-revoke \
+ cert:FILE:cert-sub-ee.pem \
+ chain:FILE:cert-sub-ca.pem \
+ anchor:FILE:cert-ca.pem > /dev/null || exit 1
+
+echo "+++++++++++ test basic constraints"
+
+echo "extend ca cert (too low path-length constraint)"
+${hxtool} issue-certificate \
+ --self-signed \
+ --issue-ca \
+ --lifetime="3years" \
+ --template-certificate="FILE:cert-ca.pem" \
+ --template-fields="serialNumber,notBefore,subject" \
+ --path-length=0 \
+ --ca-private-key=FILE:cert-ca.pem \
+ --certificate="FILE:cert-ca.pem" || exit 1
+
+echo "verify failure of certificate (sub-ee) with path-length constraint"
+${hxtool} verify --missing-revoke \
+ cert:FILE:cert-sub-ee.pem \
+ chain:FILE:cert-sub-ca.pem \
+ anchor:FILE:cert-ca.pem > /dev/null && exit 1
+
+echo "extend ca cert (exact path-length constraint)"
+${hxtool} issue-certificate \
+ --self-signed \
+ --issue-ca \
+ --lifetime="3years" \
+ --template-certificate="FILE:cert-ca.pem" \
+ --template-fields="serialNumber,notBefore,subject" \
+ --path-length=1 \
+ --ca-private-key=FILE:cert-ca.pem \
+ --certificate="FILE:cert-ca.pem" || exit 1
+
+echo "verify certificate (sub-ee) with exact path-length constraint"
+${hxtool} verify --missing-revoke \
+ cert:FILE:cert-sub-ee.pem \
+ chain:FILE:cert-sub-ca.pem \
+ anchor:FILE:cert-ca.pem > /dev/null || exit 1
+
+echo "Check missing basicConstrants.isCa"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:cert-ca.pem \
+ --lifetime="2years" \
+ --template-certificate="FILE:cert-sub-ca.pem" \
+ --template-fields="serialNumber,notBefore,subject,SPKI" \
+ --certificate="FILE:cert-sub-ca2.pem" || exit 1
+
+echo "verify failure certificate (sub-ee) with missing isCA"
+${hxtool} verify --missing-revoke \
+ cert:FILE:cert-sub-ee.pem \
+ chain:FILE:cert-sub-ca2.pem \
+ anchor:FILE:cert-ca.pem > /dev/null && exit 1
+
+echo "issue ee cert (crl uri)"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:cert-ca.pem \
+ --req="PKCS10:pkcs10-request.der" \
+ --crl-uri="http://www.test.h5l.se/crl1.crl" \
+ --subject="cn=cert-ee-crl-uri" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+
+echo "issue null subject cert"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:cert-ca.pem \
+ --req="PKCS10:pkcs10-request.der" \
+ --subject="" \
+ --email="lha@test.h5l.se" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+
+echo "verify certificate null subject"
+${hxtool} verify --missing-revoke \
+ cert:FILE:cert-ee.pem \
+ anchor:FILE:cert-ca.pem > /dev/null || exit 1
+
+echo "+++++++++++ test sigalg"
+
+echo "issue cert with sha256"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:cert-ca.pem \
+ --signature-algorithm=rsa-with-sha256 \
+ --subject="cn=foo" \
+ --req="PKCS10:pkcs10-request.der" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+
+echo "verify certificate"
+${hxtool} verify --missing-revoke \
+ cert:FILE:cert-ee.pem \
+ anchor:FILE:cert-ca.pem > /dev/null || exit 1
+
+echo "issue cert with sha1"
+${hxtool} issue-certificate \
+ --ca-certificate=FILE:cert-ca.pem \
+ --signature-algorithm=rsa-with-sha1 \
+ --subject="cn=foo" \
+ --req="PKCS10:pkcs10-request.der" \
+ --certificate="FILE:cert-ee.pem" || exit 1
+
+echo "verify certificate"
+${hxtool} verify --missing-revoke \
+ cert:FILE:cert-ee.pem \
+ anchor:FILE:cert-ca.pem > /dev/null || exit 1
+
+exit 0
diff --git a/third_party/heimdal/lib/hx509/test_cert.in b/third_party/heimdal/lib/hx509/test_cert.in
new file mode 100644
index 0000000..5fa14d0
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_cert.in
@@ -0,0 +1,84 @@
+#!/bin/sh
+#
+# Copyright (c) 2007 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# $Id: test_chain.in 20809 2007-06-03 03:19:06Z lha $
+#
+
+srcdir="@srcdir@"
+objdir="@objdir@"
+
+hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}"
+if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then
+ exit 77
+fi
+if ${hxtool} info | grep 'rand: not available' > /dev/null ; then
+ exit 77
+fi
+
+echo "print DIR"
+${hxtool} print --content DIR:$srcdir/data > /dev/null 2>/dev/null || exit 1
+
+echo "print FILE"
+for a in $srcdir/data/*.crt; do
+ ${hxtool} print --content FILE:"$a" > /dev/null 2>/dev/null
+done
+
+echo "print NULL"
+${hxtool} print --content NULL: > /dev/null || exit 1
+
+echo "copy dance"
+${hxtool} certificate-copy \
+ FILE:${srcdir}/data/test.crt PEM-FILE:cert-pem.tmp || exit 1
+
+${hxtool} certificate-copy PEM-FILE:cert-pem.tmp DER-FILE:cert-der.tmp || exit 1
+${hxtool} certificate-copy DER-FILE:cert-der.tmp PEM-FILE:cert-pem2.tmp || exit 1
+
+cmp cert-pem.tmp cert-pem2.tmp || exit 1
+
+echo "verify n0ll cert (fail)"
+${hxtool} verify --missing-revoke \
+ --hostname=foo.com \
+ cert:FILE:$srcdir/data/n0ll.pem \
+ anchor:FILE:$srcdir/data/n0ll.pem && exit 1
+
+echo "verify n0ll cert (fail)"
+${hxtool} verify --missing-revoke \
+ cert:FILE:$srcdir/data/n0ll.pem \
+ anchor:FILE:$srcdir/data/n0ll.pem && exit 1
+
+echo "check that windows cert with utf16 in printable string works"
+${hxtool} verify --missing-revoke \
+ cert:FILE:$srcdir/data/win-u16-in-printablestring.der \
+ anchor:FILE:$srcdir/data/win-u16-in-printablestring.der || exit 1
+
+exit 0
diff --git a/third_party/heimdal/lib/hx509/test_chain.in b/third_party/heimdal/lib/hx509/test_chain.in
new file mode 100644
index 0000000..b8c8cf5
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_chain.in
@@ -0,0 +1,256 @@
+#!/bin/sh
+#
+# Copyright (c) 2004 - 2006 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# $Id$
+#
+
+srcdir="@srcdir@"
+objdir="@objdir@"
+
+stat="--statistic-file=${objdir}/statfile"
+
+hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}"
+if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then
+ exit 77
+fi
+if ${hxtool} info | grep 'rand: not available' > /dev/null ; then
+ exit 77
+fi
+
+echo "cert -> root"
+${hxtool} verify --missing-revoke \
+ cert:FILE:$srcdir/data/test.crt \
+ chain:FILE:$srcdir/data/test.crt \
+ chain:FILE:$srcdir/data/ca.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "cert -> root"
+${hxtool} verify --missing-revoke \
+ cert:FILE:$srcdir/data/test.crt \
+ chain:FILE:$srcdir/data/ca.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "cert -> root"
+${hxtool} verify --missing-revoke \
+ cert:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "sub-cert -> root"
+${hxtool} verify --missing-revoke \
+ cert:FILE:$srcdir/data/sub-cert.crt \
+ chain:FILE:$srcdir/data/ca.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1
+
+echo "sub-cert -> sub-ca -> root"
+${hxtool} verify --missing-revoke \
+ cert:FILE:$srcdir/data/sub-cert.crt \
+ chain:FILE:$srcdir/data/sub-ca.crt \
+ chain:FILE:$srcdir/data/ca.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "sub-cert -> sub-ca"
+${hxtool} verify --missing-revoke \
+ cert:FILE:$srcdir/data/sub-cert.crt \
+ anchor:FILE:$srcdir/data/sub-ca.crt > /dev/null || exit 1
+
+echo "sub-cert -> sub-ca -> root"
+${hxtool} verify --missing-revoke \
+ cert:FILE:$srcdir/data/sub-cert.crt \
+ chain:FILE:$srcdir/data/sub-ca.crt \
+ chain:FILE:$srcdir/data/ca.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "sub-cert -> sub-ca -> root"
+${hxtool} verify --missing-revoke \
+ cert:FILE:$srcdir/data/sub-cert.crt \
+ chain:FILE:$srcdir/data/ca.crt \
+ chain:FILE:$srcdir/data/sub-ca.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "sub-cert -> sub-ca -> root"
+${hxtool} verify --missing-revoke \
+ cert:FILE:$srcdir/data/sub-cert.crt \
+ chain:FILE:$srcdir/data/sub-ca.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "max depth 2 (ok)"
+${hxtool} verify --missing-revoke \
+ --max-depth=2 \
+ cert:FILE:$srcdir/data/sub-cert.crt \
+ chain:FILE:$srcdir/data/sub-ca.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1
+
+echo "max depth 1 (fail)"
+${hxtool} verify --missing-revoke \
+ --max-depth=1 \
+ cert:FILE:$srcdir/data/sub-cert.crt \
+ chain:FILE:$srcdir/data/sub-ca.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1
+
+echo "ocsp non-ca responder"
+${hxtool} verify \
+ cert:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt \
+ ocsp:FILE:$srcdir/data/ocsp-resp1-ocsp.der > /dev/null || exit 1
+
+echo "ocsp ca responder"
+${hxtool} verify \
+ cert:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt \
+ ocsp:FILE:$srcdir/data/ocsp-resp1-ca.der > /dev/null || exit 1
+
+echo "ocsp no-ca responder, missing cert"
+${hxtool} verify \
+ cert:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt \
+ ocsp:FILE:$srcdir/data/ocsp-resp1-ocsp-no-cert.der > /dev/null && exit 1
+
+echo "ocsp no-ca responder, missing cert, in pool"
+${hxtool} verify \
+ cert:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt \
+ ocsp:FILE:$srcdir/data/ocsp-resp1-ocsp-no-cert.der \
+ chain:FILE:$srcdir/data/ocsp-responder.crt > /dev/null || exit 1
+
+echo "ocsp no-ca responder, keyHash"
+${hxtool} verify \
+ cert:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt \
+ ocsp:FILE:$srcdir/data/ocsp-resp1-keyhash.der > /dev/null || exit 1
+
+echo "ocsp revoked cert"
+${hxtool} verify \
+ cert:FILE:$srcdir/data/revoke.crt \
+ anchor:FILE:$srcdir/data/ca.crt \
+ ocsp:FILE:$srcdir/data/ocsp-resp2.der > /dev/null && exit 1
+
+for a in resp1-ocsp-no-cert resp1-ca resp1-keyhash resp2 ; do
+ echo "ocsp print reply $a"
+ ${hxtool} ocsp-print \
+ $srcdir/data/ocsp-${a}.der > /dev/null || exit 1
+done
+
+echo "ocsp verify exists"
+${hxtool} ocsp-verify \
+ --ocsp-file=$srcdir/data/ocsp-resp1-ca.der \
+ FILE:$srcdir/data/test.crt > /dev/null || exit 1
+
+echo "ocsp verify not exists"
+${hxtool} ocsp-verify \
+ --ocsp-file=$srcdir/data/ocsp-resp1.der \
+ FILE:$srcdir/data/ca.crt > /dev/null && exit 1
+
+echo "ocsp verify revoked"
+${hxtool} ocsp-verify \
+ --ocsp-file=$srcdir/data/ocsp-resp2.der \
+ FILE:$srcdir/data/revoke.crt > /dev/null && exit 1
+
+echo "crl non-revoked cert"
+${hxtool} verify \
+ cert:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt \
+ crl:FILE:$srcdir/data/crl1.der > /dev/null || exit 1
+
+echo "crl revoked cert"
+${hxtool} verify \
+ cert:FILE:$srcdir/data/revoke.crt \
+ anchor:FILE:$srcdir/data/ca.crt \
+ crl:FILE:$srcdir/data/crl1.der > /dev/null && exit 1
+
+if ${hxtool} info | grep 'ecdsa: hcrypto null' > /dev/null ; then
+ echo "not testing ECDSA since hcrypto doesnt support ECDSA"
+else
+ echo "eccert -> root"
+ ${hxtool} verify --missing-revoke \
+ cert:FILE:$srcdir/data/secp256r2TestServer.cert.pem \
+ anchor:FILE:$srcdir/data/secp256r1TestCA.cert.pem > /dev/null || exit 1
+
+ echo "eccert -> root"
+ ${hxtool} verify --missing-revoke \
+ cert:FILE:$srcdir/data/secp256r2TestClient.cert.pem \
+ anchor:FILE:$srcdir/data/secp256r1TestCA.cert.pem > /dev/null || exit 1
+fi
+
+echo "proxy cert"
+${hxtool} verify --missing-revoke \
+ --allow-proxy-certificate \
+ cert:FILE:$srcdir/data/proxy-test.crt \
+ chain:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "proxy cert (negative)"
+${hxtool} verify --missing-revoke \
+ cert:FILE:$srcdir/data/proxy-test.crt \
+ chain:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1
+
+echo "proxy cert (level fail)"
+${hxtool} verify --missing-revoke \
+ --allow-proxy-certificate \
+ cert:FILE:$srcdir/data/proxy-level-test.crt \
+ chain:FILE:$srcdir/data/proxy-test.crt \
+ chain:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1
+
+echo "not a proxy cert"
+${hxtool} verify --missing-revoke \
+ --allow-proxy-certificate \
+ cert:FILE:$srcdir/data/no-proxy-test.crt \
+ chain:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1
+
+echo "proxy cert (max level 10)"
+${hxtool} verify --missing-revoke \
+ --allow-proxy-certificate \
+ cert:FILE:$srcdir/data/proxy10-test.crt \
+ chain:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "proxy cert (second level)"
+${hxtool} verify --missing-revoke \
+ --allow-proxy-certificate \
+ cert:FILE:$srcdir/data/proxy10-child-test.crt \
+ chain:FILE:$srcdir/data/proxy10-test.crt \
+ chain:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+echo "proxy cert (third level)"
+${hxtool} verify --missing-revoke \
+ --allow-proxy-certificate \
+ cert:FILE:$srcdir/data/proxy10-child-child-test.crt \
+ chain:FILE:$srcdir/data/proxy10-child-test.crt \
+ chain:FILE:$srcdir/data/proxy10-test.crt \
+ chain:FILE:$srcdir/data/test.crt \
+ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1
+
+exit 0
diff --git a/third_party/heimdal/lib/hx509/test_cms.in b/third_party/heimdal/lib/hx509/test_cms.in
new file mode 100644
index 0000000..8b3de76
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_cms.in
@@ -0,0 +1,514 @@
+#!/bin/sh
+#
+# Copyright (c) 2005 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# $Id$
+#
+
+srcdir="@srcdir@"
+objdir="@objdir@"
+
+stat="--statistic-file=${objdir}/statfile"
+
+hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}"
+
+if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then
+ exit 77
+fi
+if ${hxtool} info | grep 'rand: not available' > /dev/null ; then
+ exit 77
+fi
+
+if ${hxtool} info | grep 'ecdsa: hcrypto null' > /dev/null ; then
+ echo "not testing ECDSA since hcrypto doesnt support ECDSA"
+else
+ echo "create signed data (ec)"
+ ${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/secp256r2TestClient.pem \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+ echo "verify signed data (ec)"
+ ${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/secp256r1TestCA.cert.pem \
+ sd.data sd.data.out > /dev/null || exit 1
+ cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+fi
+
+echo "create signed data"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify signed data"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out > /dev/null || exit 1
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
+echo "create signed data (no signer)"
+${hxtool} cms-create-sd \
+ --no-signer \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify signed data (no signer)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --no-signer-allowed \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out > signer.tmp || exit 1
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+grep "unsigned" signer.tmp > /dev/null || exit 1
+
+echo "verify signed data (no signer) (test failure)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out 2> signer.tmp && exit 1
+grep "No signers where found" signer.tmp > /dev/null || exit 1
+
+echo "create signed data (id-by-name)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ --id-by-name \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify signed data"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out > /dev/null || exit 1
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
+echo "verify signed data (EE cert as anchor)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/test.crt \
+ sd.data sd.data.out > /dev/null || exit 1
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
+echo "create signed data (password)"
+${hxtool} cms-create-sd \
+ --pass=PASS:foobar \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test-pw.key \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify signed data"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out > /dev/null || exit 1
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
+echo "create signed data (combined)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/test.combined.crt \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify signed data"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out > /dev/null || exit 1
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
+echo "create signed data (content info)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ --content-info \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify signed data (content info)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ --content-info \
+ sd.data sd.data.out > /dev/null || exit 1
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
+echo "create signed data (content type)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ --content-type=1.1.1.1 \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify signed data (content type)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out > /dev/null || exit 1
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
+echo "create signed data (pem)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ --pem \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify signed data (pem)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ --pem \
+ sd.data sd.data.out > /dev/null
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
+echo "create signed data (pem, detached)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ --detached-signature \
+ --pem \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify signed data (pem, detached)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ --pem \
+ --signed-content="$srcdir/test_chain.in" \
+ sd.data sd.data.out > /dev/null
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
+echo "create signed data (p12)"
+${hxtool} cms-create-sd \
+ --pass=PASS:foobar \
+ --certificate=PKCS12:$srcdir/data/test.p12 \
+ --signer=friendlyname-test \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify signed data"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ --content-info \
+ "$srcdir/data/test-signed-data" sd.data.out > /dev/null || exit 1
+cmp "$srcdir/data/static-file" sd.data.out || exit 1
+
+echo "verify signed data (no attr)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ --content-info \
+ "$srcdir/data/test-signed-data-noattr" sd.data.out > /dev/null || exit 1
+cmp "$srcdir/data/static-file" sd.data.out || exit 1
+
+echo "verify failure signed data (no attr, no certs)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ --content-info \
+ "$srcdir/data/test-signed-data-noattr-nocerts" \
+ sd.data.out > /dev/null 2>/dev/null && exit 1
+
+echo "verify signed data (no attr, no certs)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ --certificate=FILE:$srcdir/data/test.crt \
+ --content-info \
+ "$srcdir/data/test-signed-data-noattr-nocerts" \
+ sd.data.out > /dev/null || exit 1
+cmp "$srcdir/data/static-file" sd.data.out || exit 1
+
+echo "verify signed data - sha1"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ --content-info \
+ "$srcdir/data/test-signed-sha-1" sd.data.out > /dev/null || exit 1
+cmp "$srcdir/data/static-file" sd.data.out || exit 1
+
+echo "verify signed data - sha256"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ --content-info \
+ "$srcdir/data/test-signed-sha-256" sd.data.out > /dev/null || exit 1
+cmp "$srcdir/data/static-file" sd.data.out || exit 1
+
+#echo "verify signed data - sha512"
+#${hxtool} cms-verify-sd \
+# --missing-revoke \
+# --anchors=FILE:$srcdir/data/ca.crt \
+# --content-info \
+# "$srcdir/data/test-signed-sha-512" sd.data.out > /dev/null || exit 1
+#cmp "$srcdir/data/static-file" sd.data.out || exit 1
+
+
+echo "create signed data (subcert, no certs)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify failure signed data"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out > /dev/null 2> /dev/null && exit 1
+
+echo "verify success signed data"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --certificate=FILE:$srcdir/data/sub-ca.crt \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out > /dev/null || exit 1
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
+echo "create signed data (subcert, certs)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \
+ --pool=FILE:$srcdir/data/sub-ca.crt \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify success signed data"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out > /dev/null || exit 1
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
+echo "create signed data (subcert, certs, no-root)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \
+ --pool=FILE:$srcdir/data/sub-ca.crt \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify success signed data"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out > /dev/null || exit 1
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
+echo "create signed data (subcert, no-subca, no-root)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify failure signed data"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out > /dev/null 2>/dev/null && exit 1
+
+echo "create signed data (sd cert)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/test-ds-only.crt,$srcdir/data/test-ds-only.key \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "create signed data (ke cert)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/test-ke-only.crt,$srcdir/data/test-ke-only.key \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null 2>/dev/null && exit 1
+
+echo "create signed data (sd + ke certs)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/test-ke-only.crt,$srcdir/data/test-ke-only.key \
+ --certificate=FILE:$srcdir/data/test-ds-only.crt,$srcdir/data/test-ds-only.key \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "create signed data (ke + sd certs)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/test-ds-only.crt,$srcdir/data/test-ds-only.key \
+ --certificate=FILE:$srcdir/data/test-ke-only.crt,$srcdir/data/test-ke-only.key \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "create signed data (detached)"
+${hxtool} cms-create-sd \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ --detached-signature \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify signed data (detached)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --signed-content="$srcdir/test_chain.in" \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out > /dev/null || exit 1
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
+echo "verify failure signed data (detached)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out > /dev/null 2>/dev/null && exit 1
+
+echo "create signed data (rsa)"
+${hxtool} cms-create-sd \
+ --peer-alg=1.2.840.113549.1.1.1 \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ "$srcdir/test_chain.in" \
+ sd.data > /dev/null || exit 1
+
+echo "verify signed data (rsa)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ sd.data sd.data.out > /dev/null 2>/dev/null || exit 1
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
+echo "create signed data (pem, detached)"
+cp "$srcdir/test_chain.in" sd
+${hxtool} cms-sign \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ --detached-signature \
+ --pem \
+ sd > /dev/null || exit 1
+
+echo "verify signed data (pem, detached)"
+${hxtool} cms-verify-sd \
+ --missing-revoke \
+ --anchors=FILE:$srcdir/data/ca.crt \
+ --pem \
+ sd.pem > /dev/null
+
+echo "create signed data (no certs, detached sig)"
+cp "$srcdir/test_chain.in" sd
+${hxtool} cms-sign \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ --detached-signature \
+ --no-embedded-certs \
+ "$srcdir/data/static-file" \
+ sd > /dev/null || exit 1
+
+echo "create signed data (leif only, detached sig)"
+cp "$srcdir/test_chain.in" sd
+${hxtool} cms-sign \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ --detached-signature \
+ --embed-leaf-only \
+ "$srcdir/data/static-file" \
+ sd > /dev/null || exit 1
+
+echo "create signed data (no certs, detached sig, 2 signers)"
+cp "$srcdir/test_chain.in" sd
+${hxtool} cms-sign \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ --certificate=FILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \
+ --detached-signature \
+ --no-embedded-certs \
+ "$srcdir/data/static-file" \
+ sd > /dev/null || exit 1
+
+echo "create signed data (no certs, detached sig, 3 signers)"
+cp "$srcdir/test_chain.in" sd
+${hxtool} cms-sign \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ --certificate=FILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \
+ --certificate=FILE:$srcdir/data/test-ds-only.crt,$srcdir/data/test-ds-only.key \
+ --detached-signature \
+ --no-embedded-certs \
+ "$srcdir/data/static-file" \
+ sd > /dev/null || exit 1
+
+echo "envelope data (content-type)"
+${hxtool} cms-envelope \
+ --certificate=FILE:$srcdir/data/test.crt \
+ --content-type=1.1.1.1 \
+ "$srcdir/data/static-file" \
+ ev.data > /dev/null || exit 1
+
+echo "unenvelope data (content-type)"
+${hxtool} cms-unenvelope \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ ev.data ev.data.out \
+ FILE:$srcdir/data/test.crt,$srcdir/data/test.key > /dev/null || exit 1
+cmp "$srcdir/data/static-file" ev.data.out || exit 1
+
+echo "envelope data (content-info)"
+${hxtool} cms-envelope \
+ --certificate=FILE:$srcdir/data/test.crt \
+ --content-info \
+ "$srcdir/data/static-file" \
+ ev.data > /dev/null || exit 1
+
+echo "unenvelope data (content-info)"
+${hxtool} cms-unenvelope \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ --content-info \
+ ev.data ev.data.out \
+ FILE:$srcdir/data/test.crt,$srcdir/data/test.key > /dev/null || exit 1
+cmp "$srcdir/data/static-file" ev.data.out || exit 1
+
+for a in des-ede3 aes-128 aes-256; do
+
+ rm -f ev.data ev.data.out
+ echo "envelope data ($a)"
+ ${hxtool} cms-envelope \
+ --encryption-type="$a-cbc" \
+ --certificate=FILE:$srcdir/data/test.crt \
+ "$srcdir/data/static-file" \
+ ev.data || exit 1
+
+ echo "unenvelope data ($a)"
+ ${hxtool} cms-unenvelope \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ ev.data ev.data.out > /dev/null || exit 1
+ cmp "$srcdir/data/static-file" ev.data.out || exit 1
+done
+
+for a in rc2-40 rc2-64 rc2-128 des-ede3 aes-128 aes-256; do
+ echo "static unenvelope data ($a)"
+
+ rm -f ev.data.out
+ ${hxtool} cms-unenvelope \
+ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+ --content-info \
+ --allow-weak \
+ "$srcdir/data/test-enveloped-$a" ev.data.out > /dev/null || exit 1
+ cmp "$srcdir/data/static-file" ev.data.out || exit 1
+done
+
+exit 0
diff --git a/third_party/heimdal/lib/hx509/test_crypto.in b/third_party/heimdal/lib/hx509/test_crypto.in
new file mode 100644
index 0000000..9206031
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_crypto.in
@@ -0,0 +1,192 @@
+#!/bin/sh
+#
+# Copyright (c) 2006 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# $Id$
+#
+
+srcdir="@srcdir@"
+objdir="@objdir@"
+
+stat="--statistic-file=${objdir}/statfile"
+
+hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}"
+
+if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then
+ exit 77
+fi
+if ${hxtool} info | grep 'rand: not available' > /dev/null ; then
+ exit 77
+fi
+
+
+echo "Bleichenbacher good cert (from eay)"
+${hxtool} verify --missing-revoke \
+ --time=2006-09-25 \
+ cert:FILE:$srcdir/data/bleichenbacher-good.pem \
+ anchor:FILE:$srcdir/data/bleichenbacher-good.pem > /dev/null || exit 1
+
+echo "Bleichenbacher bad cert (from eay)"
+${hxtool} verify --missing-revoke \
+ --time=2006-09-25 \
+ cert:FILE:$srcdir/data/bleichenbacher-bad.pem \
+ anchor:FILE:$srcdir/data/bleichenbacher-bad.pem > /dev/null && exit 1
+
+echo "Bleichenbacher good cert (from yutaka)"
+${hxtool} verify --missing-revoke \
+ --time=2006-09-25 \
+ cert:FILE:$srcdir/data/yutaka-pad-ok-cert.pem \
+ anchor:FILE:$srcdir/data/yutaka-pad-ok-ca.pem > /dev/null || exit 1
+
+echo "Bleichenbacher bad cert (from yutaka)"
+${hxtool} verify --missing-revoke \
+ --time=2006-09-25 \
+ cert:FILE:$srcdir/data/yutaka-pad-broken-cert.pem \
+ anchor:FILE:$srcdir/data/yutaka-pad-broken-ca.pem > /dev/null && exit 1
+
+# Ralf-Philipp Weinmann <weinmann@cdc.informatik.tu-darmstadt.de>
+# Andrew Pyshkin <pychkine@cdc.informatik.tu-darmstadt.de>
+echo "Bleichenbacher bad cert (sf pad correct)"
+${hxtool} verify --missing-revoke \
+ --time=2006-09-25 \
+ cert:FILE:$srcdir/data/bleichenbacher-sf-pad-correct.pem \
+ anchor:FILE:$srcdir/data/sf-class2-root.pem > /dev/null && exit 1
+
+echo Read 50 kilobyte random data
+${hxtool} random-data 50kilobyte > random-data || exit 1
+
+echo "crypto select1"
+${hxtool} crypto-select > test || { echo "select1"; exit 1; }
+cmp test ${srcdir}/tst-crypto-select1 > /dev/null || \
+ { echo "select1 failure"; exit 1; }
+
+echo "crypto select1"
+${hxtool} crypto-select --type=digest > test || { echo "select1"; exit 1; }
+cmp test ${srcdir}/tst-crypto-select1 > /dev/null || \
+ { echo "select1 failure"; exit 1; }
+
+echo "crypto select2"
+${hxtool} crypto-select --type=public-sig > test || { echo "select2"; exit 1; }
+cmp test ${srcdir}/tst-crypto-select2 > /dev/null || \
+ { echo "select2 failure"; exit 1; }
+
+echo "crypto select3"
+${hxtool} crypto-select \
+ --type=public-sig \
+ --peer-cmstype=1.2.840.113549.1.1.4 \
+ > test || { echo "select3"; exit 1; }
+cmp test ${srcdir}/tst-crypto-select3 > /dev/null || \
+ { echo "select3 failure"; exit 1; }
+
+echo "crypto select4"
+${hxtool} crypto-select \
+ --type=public-sig \
+ --peer-cmstype=1.2.840.113549.1.1.5 \
+ --peer-cmstype=1.2.840.113549.1.1.4 \
+ > test || { echo "select4"; exit 1; }
+cmp test ${srcdir}/tst-crypto-select4 > /dev/null || \
+ { echo "select4 failure"; exit 1; }
+
+echo "crypto select5"
+${hxtool} crypto-select \
+ --type=public-sig \
+ --peer-cmstype=1.2.840.113549.1.1.11 \
+ --peer-cmstype=1.2.840.113549.1.1.5 \
+ > test || { echo "select5"; exit 1; }
+cmp test ${srcdir}/tst-crypto-select5 > /dev/null || \
+ { echo "select5 failure"; exit 1; }
+
+echo "crypto select6"
+${hxtool} crypto-select \
+ --type=public-sig \
+ --peer-cmstype=1.2.840.113549.2.5 \
+ --peer-cmstype=1.2.840.113549.1.1.5 \
+ > test || { echo "select6"; exit 1; }
+cmp test ${srcdir}/tst-crypto-select6 > /dev/null || \
+ { echo "select6 failure"; exit 1; }
+
+echo "crypto select7"
+${hxtool} crypto-select \
+ --type=secret \
+ --peer-cmstype=2.16.840.1.101.3.4.1.42 \
+ --peer-cmstype=1.2.840.113549.3.7 \
+ --peer-cmstype=1.2.840.113549.1.1.5 \
+ > test || { echo "select7"; exit 1; }
+cmp test ${srcdir}/tst-crypto-select7 > /dev/null || \
+ { echo "select7 failure"; exit 1; }
+
+#echo "crypto available1"
+#${hxtool} crypto-available \
+# --type=all \
+# > test || { echo "available1"; exit 1; }
+#cmp test ${srcdir}/tst-crypto-available1 > /dev/null || \
+# { echo "available1 failure"; exit 1; }
+
+echo "crypto available2"
+${hxtool} crypto-available \
+ --type=digest \
+ > test || { echo "available2"; exit 1; }
+cmp test ${srcdir}/tst-crypto-available2 > /dev/null || \
+ { echo "available2 failure"; exit 1; }
+
+#echo "crypto available3"
+#${hxtool} crypto-available \
+# --type=public-sig \
+# > test || { echo "available3"; exit 1; }
+#cmp test ${srcdir}/tst-crypto-available3 > /dev/null || \
+# { echo "available3 failure"; exit 1; }
+
+echo "copy keystore FILE existing -> FILE"
+${hxtool} certificate-copy \
+ FILE:${srcdir}/data/test.crt,${srcdir}/data/test.key \
+ FILE:out.pem || exit 1
+
+echo "copy keystore FILE -> FILE"
+${hxtool} certificate-copy \
+ FILE:out.pem \
+ FILE:out2.pem || exit 1
+
+echo "copy keystore FILE -> PKCS12"
+${hxtool} certificate-copy \
+ FILE:out.pem \
+ PKCS12:out2.pem || exit 1
+
+echo "print certificate with utf8"
+${hxtool} print \
+ FILE:$srcdir/data/j.pem >/dev/null 2>/dev/null || exit 1
+
+echo "Make sure that we can parse EC private keys"
+${hxtool} print --content \
+ FILE:$srcdir/data/pkinit-ec.crt,$srcdir/data/pkinit-ec.key \
+ > /dev/null || exit 1
+
+exit 0
diff --git a/third_party/heimdal/lib/hx509/test_expr.c b/third_party/heimdal/lib/hx509/test_expr.c
new file mode 100644
index 0000000..8c2c0a5
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_expr.c
@@ -0,0 +1,87 @@
+
+#include "hx_locl.h"
+#include <err.h>
+
+struct foo {
+ int val;
+ char *str;
+} foo[] = {
+ { 0, "FALSE" },
+ { 1, "TRUE" },
+ { 0, "!TRUE" },
+ { 0, "! TRUE" },
+ { 0, "!\tTRUE" },
+ { 0, "( FALSE AND FALSE )" },
+ { 0, "( TRUE AND FALSE )" },
+ { 1, "( TRUE AND TRUE )" },
+ { 1, "( TRUE OR TRUE )" },
+ { 1, "( TRUE OR FALSE )" },
+ { 0, "( FALSE OR FALSE )" },
+ { 1, "! ( FALSE OR FALSE )" },
+
+ { 1, "\"foo\" TAILMATCH \"foo\"" },
+ { 1, "\"foobar\" TAILMATCH \"bar\"" },
+ { 0, "\"foobar\" TAILMATCH \"foo\"" },
+
+ { 1, "\"foo\" == \"foo\"" },
+ { 0, "\"foo\" == \"bar\"" },
+ { 0, "\"foo\" != \"foo\"" },
+ { 1, "\"foo\" != \"bar\"" },
+ { 1, "%{variable} == \"foo\"" },
+ { 0, "%{variable} == \"bar\"" },
+ { 1, "%{context.variable} == \"foo\"" },
+ { 0, "%{context.variable} == \"bar\"" },
+ { 1, "\"foo\" IN ( \"bar\", \"foo\")" },
+ { 0, "\"foo\" IN ( \"bar\", \"baz\")" },
+ { 0, "\"bar\" IN %{context}" },
+ { 1, "\"foo\" IN %{context}" },
+ { 1, "\"variable\" IN %{context}" },
+
+ { 1, "\"foo\" IN %{context} AND %{context.variable} == \"foo\"" }
+};
+
+int
+main(int argc, char **argv)
+{
+ struct hx_expr *expr;
+ hx509_context context;
+ hx509_env env = NULL, env2 = NULL;
+ int val, i, ret;
+
+#if 0
+ extern int yydebug;
+ yydebug = 1;
+#endif
+
+ ret = hx509_context_init(&context);
+ if (ret)
+ errx(1, "hx509_context_init failed with %d", ret);
+
+ hx509_env_add(context, &env, "variable", "foo");
+ hx509_env_add(context, &env2, "variable", "foo");
+ hx509_env_add_binding(context, &env, "context", env2);
+
+ for (i = 0; i < sizeof(foo)/sizeof(foo[0]); i++) {
+
+ expr = _hx509_expr_parse(foo[i].str);
+ if (expr == NULL)
+ errx(1, "_hx509_expr_parse failed for %d: %s", i, foo[i].str);
+
+ val = _hx509_expr_eval(context, env, expr);
+ if (foo[i].val) {
+ if (val == 0)
+ errx(1, "_hx509_expr_eval not true when it should: %d: %s",
+ i, foo[i].str);
+ } else {
+ if (val)
+ errx(1, "_hx509_expr_eval true when it should not: %d: %s",
+ i, foo[i].str);
+ }
+
+ _hx509_expr_free(expr);
+ }
+
+ hx509_env_free(&env);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hx509/test_java_pkcs11.in b/third_party/heimdal/lib/hx509/test_java_pkcs11.in
new file mode 100644
index 0000000..9a843a4
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_java_pkcs11.in
@@ -0,0 +1,73 @@
+#!/bin/sh
+#
+# Copyright (c) 2008 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+
+exit 0
+
+srcdir="@srcdir@"
+objdir="@objdir@"
+
+dir=$objdir
+file=
+
+for a in libhx509.so .libs/libhx509.so libhx509.dylib .libs/libhx509.dylib ; do
+ if [ -f $dir/$a ] ; then
+ file=$dir/$a
+ break
+ fi
+done
+
+if [ "X$file" = X ] ; then
+ exit 0
+fi
+
+cat > pkcs11.cfg <<EOF
+name = Heimdal
+library = $file
+EOF
+
+cat > test-rc-file.rc <<EOF
+certificate cert User certificate FILE:$srcdir/data/test.crt,$srcdir/data/test.key
+debug stdout
+EOF
+
+
+env SOFTPKCS11RC="test-rc-file.rc" \
+ keytool \
+ -keystore NONE \
+ -storetype PKCS11 \
+ -providerClass sun.security.pkcs11.SunPKCS11 \
+ -providerArg pkcs11.cfg \
+ -list || exit 1
+
+exit 0
diff --git a/third_party/heimdal/lib/hx509/test_name.c b/third_party/heimdal/lib/hx509/test_name.c
new file mode 100644
index 0000000..ba4cbaa
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_name.c
@@ -0,0 +1,468 @@
+/*
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+
+static int
+test_name(hx509_context context, const char *name)
+{
+ hx509_name n;
+ char *s;
+ int ret;
+
+ ret = hx509_parse_name(context, name, &n);
+ if (ret)
+ return 1;
+
+ ret = hx509_name_to_string(n, &s);
+ if (ret)
+ return 1;
+
+ if (strcmp(s, name) != 0)
+ return 1;
+
+ hx509_name_free(&n);
+ free(s);
+
+ return 0;
+}
+
+static int
+test_name_fail(hx509_context context, const char *name)
+{
+ hx509_name n;
+
+ if (hx509_parse_name(context, name, &n) == HX509_NAME_MALFORMED)
+ return 0;
+ hx509_name_free(&n);
+ return 1;
+}
+
+static int
+test_expand(hx509_context context, const char *name, const char *expected)
+{
+ hx509_env env = NULL;
+ hx509_name n;
+ char *s;
+ int ret;
+
+ hx509_env_add(context, &env, "uid", "lha");
+
+ ret = hx509_parse_name(context, name, &n);
+ if (ret)
+ return 1;
+
+ ret = hx509_name_expand(context, n, env);
+ hx509_env_free(&env);
+ if (ret)
+ return 1;
+
+ ret = hx509_name_to_string(n, &s);
+ hx509_name_free(&n);
+ if (ret)
+ return 1;
+
+ ret = strcmp(s, expected) != 0;
+ free(s);
+ if (ret)
+ return 1;
+
+ return 0;
+}
+
+char certdata1[] =
+ "\x30\x82\x04\x1d\x30\x82\x03\x05\xa0\x03\x02\x01\x02\x02\x10\x4e"
+ "\x81\x2d\x8a\x82\x65\xe0\x0b\x02\xee\x3e\x35\x02\x46\xe5\x3d\x30"
+ "\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x30\x81"
+ "\x81\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x47\x42\x31\x1b"
+ "\x30\x19\x06\x03\x55\x04\x08\x13\x12\x47\x72\x65\x61\x74\x65\x72"
+ "\x20\x4d\x61\x6e\x63\x68\x65\x73\x74\x65\x72\x31\x10\x30\x0e\x06"
+ "\x03\x55\x04\x07\x13\x07\x53\x61\x6c\x66\x6f\x72\x64\x31\x1a\x30"
+ "\x18\x06\x03\x55\x04\x0a\x13\x11\x43\x4f\x4d\x4f\x44\x4f\x20\x43"
+ "\x41\x20\x4c\x69\x6d\x69\x74\x65\x64\x31\x27\x30\x25\x06\x03\x55"
+ "\x04\x03\x13\x1e\x43\x4f\x4d\x4f\x44\x4f\x20\x43\x65\x72\x74\x69"
+ "\x66\x69\x63\x61\x74\x69\x6f\x6e\x20\x41\x75\x74\x68\x6f\x72\x69"
+ "\x74\x79\x30\x1e\x17\x0d\x30\x36\x31\x32\x30\x31\x30\x30\x30\x30"
+ "\x30\x30\x5a\x17\x0d\x32\x39\x31\x32\x33\x31\x32\x33\x35\x39\x35"
+ "\x39\x5a\x30\x81\x81\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02"
+ "\x47\x42\x31\x1b\x30\x19\x06\x03\x55\x04\x08\x13\x12\x47\x72\x65"
+ "\x61\x74\x65\x72\x20\x4d\x61\x6e\x63\x68\x65\x73\x74\x65\x72\x31"
+ "\x10\x30\x0e\x06\x03\x55\x04\x07\x13\x07\x53\x61\x6c\x66\x6f\x72"
+ "\x64\x31\x1a\x30\x18\x06\x03\x55\x04\x0a\x13\x11\x43\x4f\x4d\x4f"
+ "\x44\x4f\x20\x43\x41\x20\x4c\x69\x6d\x69\x74\x65\x64\x31\x27\x30"
+ "\x25\x06\x03\x55\x04\x03\x13\x1e\x43\x4f\x4d\x4f\x44\x4f\x20\x43"
+ "\x65\x72\x74\x69\x66\x69\x63\x61\x74\x69\x6f\x6e\x20\x41\x75\x74"
+ "\x68\x6f\x72\x69\x74\x79\x30\x82\x01\x22\x30\x0d\x06\x09\x2a\x86"
+ "\x48\x86\xf7\x0d\x01\x01\x01\x05\x00\x03\x82\x01\x0f\x00\x30\x82"
+ "\x01\x0a\x02\x82\x01\x01\x00\xd0\x40\x8b\x8b\x72\xe3\x91\x1b\xf7"
+ "\x51\xc1\x1b\x54\x04\x98\xd3\xa9\xbf\xc1\xe6\x8a\x5d\x3b\x87\xfb"
+ "\xbb\x88\xce\x0d\xe3\x2f\x3f\x06\x96\xf0\xa2\x29\x50\x99\xae\xdb"
+ "\x3b\xa1\x57\xb0\x74\x51\x71\xcd\xed\x42\x91\x4d\x41\xfe\xa9\xc8"
+ "\xd8\x6a\x86\x77\x44\xbb\x59\x66\x97\x50\x5e\xb4\xd4\x2c\x70\x44"
+ "\xcf\xda\x37\x95\x42\x69\x3c\x30\xc4\x71\xb3\x52\xf0\x21\x4d\xa1"
+ "\xd8\xba\x39\x7c\x1c\x9e\xa3\x24\x9d\xf2\x83\x16\x98\xaa\x16\x7c"
+ "\x43\x9b\x15\x5b\xb7\xae\x34\x91\xfe\xd4\x62\x26\x18\x46\x9a\x3f"
+ "\xeb\xc1\xf9\xf1\x90\x57\xeb\xac\x7a\x0d\x8b\xdb\x72\x30\x6a\x66"
+ "\xd5\xe0\x46\xa3\x70\xdc\x68\xd9\xff\x04\x48\x89\x77\xde\xb5\xe9"
+ "\xfb\x67\x6d\x41\xe9\xbc\x39\xbd\x32\xd9\x62\x02\xf1\xb1\xa8\x3d"
+ "\x6e\x37\x9c\xe2\x2f\xe2\xd3\xa2\x26\x8b\xc6\xb8\x55\x43\x88\xe1"
+ "\x23\x3e\xa5\xd2\x24\x39\x6a\x47\xab\x00\xd4\xa1\xb3\xa9\x25\xfe"
+ "\x0d\x3f\xa7\x1d\xba\xd3\x51\xc1\x0b\xa4\xda\xac\x38\xef\x55\x50"
+ "\x24\x05\x65\x46\x93\x34\x4f\x2d\x8d\xad\xc6\xd4\x21\x19\xd2\x8e"
+ "\xca\x05\x61\x71\x07\x73\x47\xe5\x8a\x19\x12\xbd\x04\x4d\xce\x4e"
+ "\x9c\xa5\x48\xac\xbb\x26\xf7\x02\x03\x01\x00\x01\xa3\x81\x8e\x30"
+ "\x81\x8b\x30\x1d\x06\x03\x55\x1d\x0e\x04\x16\x04\x14\x0b\x58\xe5"
+ "\x8b\xc6\x4c\x15\x37\xa4\x40\xa9\x30\xa9\x21\xbe\x47\x36\x5a\x56"
+ "\xff\x30\x0e\x06\x03\x55\x1d\x0f\x01\x01\xff\x04\x04\x03\x02\x01"
+ "\x06\x30\x0f\x06\x03\x55\x1d\x13\x01\x01\xff\x04\x05\x30\x03\x01"
+ "\x01\xff\x30\x49\x06\x03\x55\x1d\x1f\x04\x42\x30\x40\x30\x3e\xa0"
+ "\x3c\xa0\x3a\x86\x38\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x6c\x2e"
+ "\x63\x6f\x6d\x6f\x64\x6f\x63\x61\x2e\x63\x6f\x6d\x2f\x43\x4f\x4d"
+ "\x4f\x44\x4f\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x69\x6f\x6e"
+ "\x41\x75\x74\x68\x6f\x72\x69\x74\x79\x2e\x63\x72\x6c\x30\x0d\x06"
+ "\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x03\x82\x01\x01"
+ "\x00\x3e\x98\x9e\x9b\xf6\x1b\xe9\xd7\x39\xb7\x78\xae\x1d\x72\x18"
+ "\x49\xd3\x87\xe4\x43\x82\xeb\x3f\xc9\xaa\xf5\xa8\xb5\xef\x55\x7c"
+ "\x21\x52\x65\xf9\xd5\x0d\xe1\x6c\xf4\x3e\x8c\x93\x73\x91\x2e\x02"
+ "\xc4\x4e\x07\x71\x6f\xc0\x8f\x38\x61\x08\xa8\x1e\x81\x0a\xc0\x2f"
+ "\x20\x2f\x41\x8b\x91\xdc\x48\x45\xbc\xf1\xc6\xde\xba\x76\x6b\x33"
+ "\xc8\x00\x2d\x31\x46\x4c\xed\xe7\x9d\xcf\x88\x94\xff\x33\xc0\x56"
+ "\xe8\x24\x86\x26\xb8\xd8\x38\x38\xdf\x2a\x6b\xdd\x12\xcc\xc7\x3f"
+ "\x47\x17\x4c\xa2\xc2\x06\x96\x09\xd6\xdb\xfe\x3f\x3c\x46\x41\xdf"
+ "\x58\xe2\x56\x0f\x3c\x3b\xc1\x1c\x93\x35\xd9\x38\x52\xac\xee\xc8"
+ "\xec\x2e\x30\x4e\x94\x35\xb4\x24\x1f\x4b\x78\x69\xda\xf2\x02\x38"
+ "\xcc\x95\x52\x93\xf0\x70\x25\x59\x9c\x20\x67\xc4\xee\xf9\x8b\x57"
+ "\x61\xf4\x92\x76\x7d\x3f\x84\x8d\x55\xb7\xe8\xe5\xac\xd5\xf1\xf5"
+ "\x19\x56\xa6\x5a\xfb\x90\x1c\xaf\x93\xeb\xe5\x1c\xd4\x67\x97\x5d"
+ "\x04\x0e\xbe\x0b\x83\xa6\x17\x83\xb9\x30\x12\xa0\xc5\x33\x15\x05"
+ "\xb9\x0d\xfb\xc7\x05\x76\xe3\xd8\x4a\x8d\xfc\x34\x17\xa3\xc6\x21"
+ "\x28\xbe\x30\x45\x31\x1e\xc7\x78\xbe\x58\x61\x38\xac\x3b\xe2\x01"
+ "\x65";
+
+char certdata2[] =
+ "\x30\x82\x03\x02\x30\x82\x02\x6b\x02\x10\x39\xca\x54\x89\xfe\x50"
+ "\x22\x32\xfe\x32\xd9\xdb\xfb\x1b\x84\x19\x30\x0d\x06\x09\x2a\x86"
+ "\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x30\x81\xc1\x31\x0b\x30\x09"
+ "\x06\x03\x55\x04\x06\x13\x02\x55\x53\x31\x17\x30\x15\x06\x03\x55"
+ "\x04\x0a\x13\x0e\x56\x65\x72\x69\x53\x69\x67\x6e\x2c\x20\x49\x6e"
+ "\x63\x2e\x31\x3c\x30\x3a\x06\x03\x55\x04\x0b\x13\x33\x43\x6c\x61"
+ "\x73\x73\x20\x31\x20\x50\x75\x62\x6c\x69\x63\x20\x50\x72\x69\x6d"
+ "\x61\x72\x79\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x69\x6f"
+ "\x6e\x20\x41\x75\x74\x68\x6f\x72\x69\x74\x79\x20\x2d\x20\x47\x32"
+ "\x31\x3a\x30\x38\x06\x03\x55\x04\x0b\x13\x31\x28\x63\x29\x20\x31"
+ "\x39\x39\x38\x20\x56\x65\x72\x69\x53\x69\x67\x6e\x2c\x20\x49\x6e"
+ "\x63\x2e\x20\x2d\x20\x46\x6f\x72\x20\x61\x75\x74\x68\x6f\x72\x69"
+ "\x7a\x65\x64\x20\x75\x73\x65\x20\x6f\x6e\x6c\x79\x31\x1f\x30\x1d"
+ "\x06\x03\x55\x04\x0b\x13\x16\x56\x65\x72\x69\x53\x69\x67\x6e\x20"
+ "\x54\x72\x75\x73\x74\x20\x4e\x65\x74\x77\x6f\x72\x6b\x30\x1e\x17"
+ "\x0d\x39\x38\x30\x35\x31\x38\x30\x30\x30\x30\x30\x30\x5a\x17\x0d"
+ "\x31\x38\x30\x35\x31\x38\x32\x33\x35\x39\x35\x39\x5a\x30\x81\xc1"
+ "\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x55\x53\x31\x17\x30"
+ "\x15\x06\x03\x55\x04\x0a\x13\x0e\x56\x65\x72\x69\x53\x69\x67\x6e"
+ "\x2c\x20\x49\x6e\x63\x2e\x31\x3c\x30\x3a\x06\x03\x55\x04\x0b\x13"
+ "\x33\x43\x6c\x61\x73\x73\x20\x31\x20\x50\x75\x62\x6c\x69\x63\x20"
+ "\x50\x72\x69\x6d\x61\x72\x79\x20\x43\x65\x72\x74\x69\x66\x69\x63"
+ "\x61\x74\x69\x6f\x6e\x20\x41\x75\x74\x68\x6f\x72\x69\x74\x79\x20"
+ "\x2d\x20\x47\x32\x31\x3a\x30\x38\x06\x03\x55\x04\x0b\x13\x31\x28"
+ "\x63\x29\x20\x31\x39\x39\x38\x20\x56\x65\x72\x69\x53\x69\x67\x6e"
+ "\x2c\x20\x49\x6e\x63\x2e\x20\x2d\x20\x46\x6f\x72\x20\x61\x75\x74"
+ "\x68\x6f\x72\x69\x7a\x65\x64\x20\x75\x73\x65\x20\x6f\x6e\x6c\x79"
+ "\x31\x1f\x30\x1d\x06\x03\x55\x04\x0b\x13\x16\x56\x65\x72\x69\x53"
+ "\x69\x67\x6e\x20\x54\x72\x75\x73\x74\x20\x4e\x65\x74\x77\x6f\x72"
+ "\x6b\x30\x81\x9f\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01"
+ "\x01\x05\x00\x03\x81\x8d\x00\x30\x81\x89\x02\x81\x81\x00\xaa\xd0"
+ "\xba\xbe\x16\x2d\xb8\x83\xd4\xca\xd2\x0f\xbc\x76\x31\xca\x94\xd8"
+ "\x1d\x93\x8c\x56\x02\xbc\xd9\x6f\x1a\x6f\x52\x36\x6e\x75\x56\x0a"
+ "\x55\xd3\xdf\x43\x87\x21\x11\x65\x8a\x7e\x8f\xbd\x21\xde\x6b\x32"
+ "\x3f\x1b\x84\x34\x95\x05\x9d\x41\x35\xeb\x92\xeb\x96\xdd\xaa\x59"
+ "\x3f\x01\x53\x6d\x99\x4f\xed\xe5\xe2\x2a\x5a\x90\xc1\xb9\xc4\xa6"
+ "\x15\xcf\xc8\x45\xeb\xa6\x5d\x8e\x9c\x3e\xf0\x64\x24\x76\xa5\xcd"
+ "\xab\x1a\x6f\xb6\xd8\x7b\x51\x61\x6e\xa6\x7f\x87\xc8\xe2\xb7\xe5"
+ "\x34\xdc\x41\x88\xea\x09\x40\xbe\x73\x92\x3d\x6b\xe7\x75\x02\x03"
+ "\x01\x00\x01\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05"
+ "\x05\x00\x03\x81\x81\x00\x8b\xf7\x1a\x10\xce\x76\x5c\x07\xab\x83"
+ "\x99\xdc\x17\x80\x6f\x34\x39\x5d\x98\x3e\x6b\x72\x2c\xe1\xc7\xa2"
+ "\x7b\x40\x29\xb9\x78\x88\xba\x4c\xc5\xa3\x6a\x5e\x9e\x6e\x7b\xe3"
+ "\xf2\x02\x41\x0c\x66\xbe\xad\xfb\xae\xa2\x14\xce\x92\xf3\xa2\x34"
+ "\x8b\xb4\xb2\xb6\x24\xf2\xe5\xd5\xe0\xc8\xe5\x62\x6d\x84\x7b\xcb"
+ "\xbe\xbb\x03\x8b\x7c\x57\xca\xf0\x37\xa9\x90\xaf\x8a\xee\x03\xbe"
+ "\x1d\x28\x9c\xd9\x26\x76\xa0\xcd\xc4\x9d\x4e\xf0\xae\x07\x16\xd5"
+ "\xbe\xaf\x57\x08\x6a\xd0\xa0\x42\x42\x42\x1e\xf4\x20\xcc\xa5\x78"
+ "\x82\x95\x26\x38\x8a\x47";
+
+char certdata3[] =
+ "\x30\x82\x04\x43\x30\x82\x03\x2b\xa0\x03\x02\x01\x02\x02\x01\x01"
+ "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x30"
+ "\x7f\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x47\x42\x31\x1b"
+ "\x30\x19\x06\x03\x55\x04\x08\x0c\x12\x47\x72\x65\x61\x74\x65\x72"
+ "\x20\x4d\x61\x6e\x63\x68\x65\x73\x74\x65\x72\x31\x10\x30\x0e\x06"
+ "\x03\x55\x04\x07\x0c\x07\x53\x61\x6c\x66\x6f\x72\x64\x31\x1a\x30"
+ "\x18\x06\x03\x55\x04\x0a\x0c\x11\x43\x6f\x6d\x6f\x64\x6f\x20\x43"
+ "\x41\x20\x4c\x69\x6d\x69\x74\x65\x64\x31\x25\x30\x23\x06\x03\x55"
+ "\x04\x03\x0c\x1c\x54\x72\x75\x73\x74\x65\x64\x20\x43\x65\x72\x74"
+ "\x69\x66\x69\x63\x61\x74\x65\x20\x53\x65\x72\x76\x69\x63\x65\x73"
+ "\x30\x1e\x17\x0d\x30\x34\x30\x31\x30\x31\x30\x30\x30\x30\x30\x30"
+ "\x5a\x17\x0d\x32\x38\x31\x32\x33\x31\x32\x33\x35\x39\x35\x39\x5a"
+ "\x30\x7f\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x47\x42\x31"
+ "\x1b\x30\x19\x06\x03\x55\x04\x08\x0c\x12\x47\x72\x65\x61\x74\x65"
+ "\x72\x20\x4d\x61\x6e\x63\x68\x65\x73\x74\x65\x72\x31\x10\x30\x0e"
+ "\x06\x03\x55\x04\x07\x0c\x07\x53\x61\x6c\x66\x6f\x72\x64\x31\x1a"
+ "\x30\x18\x06\x03\x55\x04\x0a\x0c\x11\x43\x6f\x6d\x6f\x64\x6f\x20"
+ "\x43\x41\x20\x4c\x69\x6d\x69\x74\x65\x64\x31\x25\x30\x23\x06\x03"
+ "\x55\x04\x03\x0c\x1c\x54\x72\x75\x73\x74\x65\x64\x20\x43\x65\x72"
+ "\x74\x69\x66\x69\x63\x61\x74\x65\x20\x53\x65\x72\x76\x69\x63\x65"
+ "\x73\x30\x82\x01\x22\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01"
+ "\x01\x01\x05\x00\x03\x82\x01\x0f\x00\x30\x82\x01\x0a\x02\x82\x01"
+ "\x01\x00\xdf\x71\x6f\x36\x58\x53\x5a\xf2\x36\x54\x57\x80\xc4\x74"
+ "\x08\x20\xed\x18\x7f\x2a\x1d\xe6\x35\x9a\x1e\x25\xac\x9c\xe5\x96"
+ "\x7e\x72\x52\xa0\x15\x42\xdb\x59\xdd\x64\x7a\x1a\xd0\xb8\x7b\xdd"
+ "\x39\x15\xbc\x55\x48\xc4\xed\x3a\x00\xea\x31\x11\xba\xf2\x71\x74"
+ "\x1a\x67\xb8\xcf\x33\xcc\xa8\x31\xaf\xa3\xe3\xd7\x7f\xbf\x33\x2d"
+ "\x4c\x6a\x3c\xec\x8b\xc3\x92\xd2\x53\x77\x24\x74\x9c\x07\x6e\x70"
+ "\xfc\xbd\x0b\x5b\x76\xba\x5f\xf2\xff\xd7\x37\x4b\x4a\x60\x78\xf7"
+ "\xf0\xfa\xca\x70\xb4\xea\x59\xaa\xa3\xce\x48\x2f\xa9\xc3\xb2\x0b"
+ "\x7e\x17\x72\x16\x0c\xa6\x07\x0c\x1b\x38\xcf\xc9\x62\xb7\x3f\xa0"
+ "\x93\xa5\x87\x41\xf2\xb7\x70\x40\x77\xd8\xbe\x14\x7c\xe3\xa8\xc0"
+ "\x7a\x8e\xe9\x63\x6a\xd1\x0f\x9a\xc6\xd2\xf4\x8b\x3a\x14\x04\x56"
+ "\xd4\xed\xb8\xcc\x6e\xf5\xfb\xe2\x2c\x58\xbd\x7f\x4f\x6b\x2b\xf7"
+ "\x60\x24\x58\x24\xce\x26\xef\x34\x91\x3a\xd5\xe3\x81\xd0\xb2\xf0"
+ "\x04\x02\xd7\x5b\xb7\x3e\x92\xac\x6b\x12\x8a\xf9\xe4\x05\xb0\x3b"
+ "\x91\x49\x5c\xb2\xeb\x53\xea\xf8\x9f\x47\x86\xee\xbf\x95\xc0\xc0"
+ "\x06\x9f\xd2\x5b\x5e\x11\x1b\xf4\xc7\x04\x35\x29\xd2\x55\x5c\xe4"
+ "\xed\xeb\x02\x03\x01\x00\x01\xa3\x81\xc9\x30\x81\xc6\x30\x1d\x06"
+ "\x03\x55\x1d\x0e\x04\x16\x04\x14\xc5\x7b\x58\xbd\xed\xda\x25\x69"
+ "\xd2\xf7\x59\x16\xa8\xb3\x32\xc0\x7b\x27\x5b\xf4\x30\x0e\x06\x03"
+ "\x55\x1d\x0f\x01\x01\xff\x04\x04\x03\x02\x01\x06\x30\x0f\x06\x03"
+ "\x55\x1d\x13\x01\x01\xff\x04\x05\x30\x03\x01\x01\xff\x30\x81\x83"
+ "\x06\x03\x55\x1d\x1f\x04\x7c\x30\x7a\x30\x3c\xa0\x3a\xa0\x38\x86"
+ "\x36\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x6c\x2e\x63\x6f\x6d\x6f"
+ "\x64\x6f\x63\x61\x2e\x63\x6f\x6d\x2f\x54\x72\x75\x73\x74\x65\x64"
+ "\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x53\x65\x72\x76\x69"
+ "\x63\x65\x73\x2e\x63\x72\x6c\x30\x3a\xa0\x38\xa0\x36\x86\x34\x68"
+ "\x74\x74\x70\x3a\x2f\x2f\x63\x72\x6c\x2e\x63\x6f\x6d\x6f\x64\x6f"
+ "\x2e\x6e\x65\x74\x2f\x54\x72\x75\x73\x74\x65\x64\x43\x65\x72\x74"
+ "\x69\x66\x69\x63\x61\x74\x65\x53\x65\x72\x76\x69\x63\x65\x73\x2e"
+ "\x63\x72\x6c\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05"
+ "\x05\x00\x03\x82\x01\x01\x00\xc8\x93\x81\x3b\x89\xb4\xaf\xb8\x84"
+ "\x12\x4c\x8d\xd2\xf0\xdb\x70\xba\x57\x86\x15\x34\x10\xb9\x2f\x7f"
+ "\x1e\xb0\xa8\x89\x60\xa1\x8a\xc2\x77\x0c\x50\x4a\x9b\x00\x8b\xd8"
+ "\x8b\xf4\x41\xe2\xd0\x83\x8a\x4a\x1c\x14\x06\xb0\xa3\x68\x05\x70"
+ "\x31\x30\xa7\x53\x9b\x0e\xe9\x4a\xa0\x58\x69\x67\x0e\xae\x9d\xf6"
+ "\xa5\x2c\x41\xbf\x3c\x06\x6b\xe4\x59\xcc\x6d\x10\xf1\x96\x6f\x1f"
+ "\xdf\xf4\x04\x02\xa4\x9f\x45\x3e\xc8\xd8\xfa\x36\x46\x44\x50\x3f"
+ "\x82\x97\x91\x1f\x28\xdb\x18\x11\x8c\x2a\xe4\x65\x83\x57\x12\x12"
+ "\x8c\x17\x3f\x94\x36\xfe\x5d\xb0\xc0\x04\x77\x13\xb8\xf4\x15\xd5"
+ "\x3f\x38\xcc\x94\x3a\x55\xd0\xac\x98\xf5\xba\x00\x5f\xe0\x86\x19"
+ "\x81\x78\x2f\x28\xc0\x7e\xd3\xcc\x42\x0a\xf5\xae\x50\xa0\xd1\x3e"
+ "\xc6\xa1\x71\xec\x3f\xa0\x20\x8c\x66\x3a\x89\xb4\x8e\xd4\xd8\xb1"
+ "\x4d\x25\x47\xee\x2f\x88\xc8\xb5\xe1\x05\x45\xc0\xbe\x14\x71\xde"
+ "\x7a\xfd\x8e\x7b\x7d\x4d\x08\x96\xa5\x12\x73\xf0\x2d\xca\x37\x27"
+ "\x74\x12\x27\x4c\xcb\xb6\x97\xe9\xd9\xae\x08\x6d\x5a\x39\x40\xdd"
+ "\x05\x47\x75\x6a\x5a\x21\xb3\xa3\x18\xcf\x4e\xf7\x2e\x57\xb7\x98"
+ "\x70\x5e\xc8\xc4\x78\xb0\x62";
+
+
+static int
+compare_subject(hx509_cert c1, hx509_cert c2, int *l)
+{
+ hx509_name n1, n2;
+ int ret;
+
+ ret = hx509_cert_get_subject(c1, &n1);
+ if (ret) return 1;
+ ret = hx509_cert_get_subject(c2, &n2);
+ if (ret) return 1;
+
+ *l = hx509_name_cmp(n1, n2);
+ hx509_name_free(&n1);
+ hx509_name_free(&n2);
+
+ return 0;
+}
+
+static int
+test_compare(hx509_context context)
+{
+ int ret;
+ hx509_cert c1, c2, c3;
+ int l0, l1, l2, l3;
+
+ /* check transative properties of name compare function */
+
+ c1 = hx509_cert_init_data(context, certdata1, sizeof(certdata1) - 1, NULL);
+ if (c1 == NULL) return 1;
+
+ c2 = hx509_cert_init_data(context, certdata2, sizeof(certdata2) - 1, NULL);
+ if (c2 == NULL) return 1;
+
+ c3 = hx509_cert_init_data(context, certdata3, sizeof(certdata3) - 1, NULL);
+ if (c3 == NULL) return 1;
+
+ ret = compare_subject(c1, c1, &l0);
+ if (ret) return 1;
+ ret = compare_subject(c1, c2, &l1);
+ if (ret) return 1;
+ ret = compare_subject(c1, c3, &l2);
+ if (ret) return 1;
+ ret = compare_subject(c2, c3, &l3);
+ if (ret) return 1;
+
+ if (l0 != 0) return 1;
+ if (l2 < l1) return 1;
+ if (l3 < l2) return 1;
+ if (l3 < l1) return 1;
+
+ hx509_cert_free(c1);
+ hx509_cert_free(c2);
+ hx509_cert_free(c3);
+
+ return 0;
+}
+
+static int
+test_pkinit_san(hx509_context context, const char *p, const char *realm, ...)
+{
+ KRB5PrincipalName kn;
+ GeneralName gn;
+ va_list ap;
+ size_t i, sz;
+ char *round_trip;
+ int ret;
+
+ memset(&kn, 0, sizeof(kn));
+ memset(&gn, 0, sizeof(gn));
+
+ ret = _hx509_make_pkinit_san(context, p, &gn.u.otherName.value);
+ if (ret == 0)
+ ret = decode_KRB5PrincipalName(gn.u.otherName.value.data,
+ gn.u.otherName.value.length, &kn, &sz);
+ if (ret)
+ return 1;
+ if (strcmp(realm, kn.realm) != 0)
+ return 1;
+
+ va_start(ap, realm);
+ for (i = 0; i < kn.principalName.name_string.len; i++) {
+ const char *s = va_arg(ap, const char *);
+
+ if (s == NULL || strcmp(kn.principalName.name_string.val[i], s) != 0)
+ return 1;
+ }
+ if (va_arg(ap, const char *) != NULL)
+ return 1;
+ va_end(ap);
+
+ gn.element = choice_GeneralName_otherName;
+ gn.u.otherName.type_id.length = 0;
+ gn.u.otherName.type_id.components = 0;
+ ret = der_copy_oid(&asn1_oid_id_pkinit_san, &gn.u.otherName.type_id);
+ if (ret == 0)
+ ret = hx509_general_name_unparse(&gn, &round_trip);
+ if (ret)
+ return 1;
+ if (strncmp(round_trip, "otherName: 1.3.6.1.5.2.2 KerberosPrincipalName ",
+ sizeof("otherName: 1.3.6.1.5.2.2 KerberosPrincipalName ") - 1))
+ return 1;
+ if (ret || strcmp(round_trip + sizeof("otherName: 1.3.6.1.5.2.2 KerberosPrincipalName ") - 1, p) != 0)
+ return 1;
+ free_KRB5PrincipalName(&kn);
+ free_GeneralName(&gn);
+ free(round_trip);
+ return 0;
+}
+
+static int
+test_pkinit_san_fail(hx509_context context, const char *p)
+{
+ heim_octet_string os;
+ KRB5PrincipalName kn;
+ int ret;
+
+ memset(&kn, 0, sizeof(kn));
+ ret = _hx509_make_pkinit_san(context, p, &os);
+ if (ret == 0) {
+ free(os.data);
+ return 1;
+ }
+ return 0;
+}
+
+
+int
+main(int argc, char **argv)
+{
+ hx509_context context;
+ int ret = 0;
+
+ ret = hx509_context_init(&context);
+ if (ret)
+ errx(1, "hx509_context_init failed with %d", ret);
+
+ ret += test_name(context, "CN=foo,C=SE");
+ ret += test_name(context, "CN=foo,CN=kaka,CN=FOO,DC=ad1,C=SE");
+ ret += test_name(context, "1.2.3.4=foo,C=SE");
+ ret += test_name_fail(context, "=");
+ ret += test_name_fail(context, "CN=foo,=foo");
+ ret += test_name_fail(context, "CN=foo,really-unknown-type=foo");
+
+ ret += test_expand(context, "UID=${uid},C=SE", "UID=lha,C=SE");
+ ret += test_expand(context, "UID=foo${uid},C=SE", "UID=foolha,C=SE");
+ ret += test_expand(context, "UID=${uid}bar,C=SE", "UID=lhabar,C=SE");
+ ret += test_expand(context, "UID=f${uid}b,C=SE", "UID=flhab,C=SE");
+ ret += test_expand(context, "UID=${uid}${uid},C=SE", "UID=lhalha,C=SE");
+ ret += test_expand(context, "UID=${uid}{uid},C=SE", "UID=lha{uid},C=SE");
+
+ ret += test_compare(context);
+
+ ret += test_pkinit_san(context, "foo@BAR.H5L.SE",
+ "BAR.H5L.SE", "foo", NULL);
+ ret += test_pkinit_san(context, "foo\\ bar@BAR.H5L.SE",
+ "BAR.H5L.SE", "foo bar", NULL);
+ ret += test_pkinit_san(context, "foo\\/bar@BAR.H5L.SE",
+ "BAR.H5L.SE", "foo/bar", NULL);
+ ret += test_pkinit_san(context, "foo/bar@BAR.H5L.SE",
+ "BAR.H5L.SE", "foo", "bar", NULL);
+ ret += test_pkinit_san(context, "foo\\tbar@BAR.H5L.SE",
+ "BAR.H5L.SE", "foo\tbar", NULL);
+ ret += test_pkinit_san(context, "foo\\nbar@BAR.H5L.SE",
+ "BAR.H5L.SE", "foo\nbar", NULL);
+ ret += test_pkinit_san(context, "foo@\\ BAR.H5L.SE",
+ " BAR.H5L.SE", "foo", NULL);
+ ret += test_pkinit_san(context, "foo@\\nBAR.H5L.SE",
+ "\nBAR.H5L.SE", "foo", NULL);
+ ret += test_pkinit_san_fail(context, "foo\\0bar@BAR.H5L.SE");
+
+ hx509_context_free(&context);
+
+ return !!ret;
+}
diff --git a/third_party/heimdal/lib/hx509/test_nist.in b/third_party/heimdal/lib/hx509/test_nist.in
new file mode 100644
index 0000000..09034fe
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_nist.in
@@ -0,0 +1,117 @@
+#!/bin/sh
+#
+# Copyright (c) 2004 - 2005 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# $Id$
+#
+
+srcdir="@srcdir@"
+objdir="@objdir@"
+nistdir=${objdir}/PKITS_data
+nistzip=${srcdir}/data/PKITS_data.zip
+
+stat="--statistic-file=${objdir}/statfile"
+
+hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}"
+
+# nistzip is not distributed part of the distribution
+test -f "$nistzip" || exit 77
+
+if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then
+ exit 77
+fi
+if ${hxtool} info | grep 'rand: not available' > /dev/null ; then
+ exit 77
+fi
+
+echo "nist tests"
+
+if [ ! -d "$nistdir" ] ; then
+ ( mkdir "$nistdir" && unzip -d "${nistdir}" "${nistzip}" ) >/dev/null || \
+ { rm -rf "$nistdir" ; exit 1; }
+fi
+
+ec=0
+while read id verify cert arg1 arg2 arg3 arg4 arg5 ; do
+ expr "$id" : "#" > /dev/null && continue
+
+ test "$id" = "end" && break
+
+ args=""
+ case "$arg1" in
+ *.crt) args="$args chain:FILE:$nistdir/certs/$arg1" ;;
+ *.crl) args="$args crl:FILE:$nistdir/crls/$arg1" ;;
+ *) args="$args $arg1" ;;
+ esac
+ case "$arg2" in
+ *.crt) args="$args chain:FILE:$nistdir/certs/$arg2" ;;
+ *.crl) args="$args crl:FILE:$nistdir/crls/$arg2" ;;
+ *) args="$args $arg2" ;;
+ esac
+ case "$arg3" in
+ *.crt) args="$args chain:FILE:$nistdir/certs/$arg3" ;;
+ *.crl) args="$args crl:FILE:$nistdir/crls/$arg3" ;;
+ *) args="$args $arg3" ;;
+ esac
+ case "$arg4" in
+ *.crt) args="$args chain:FILE:$nistdir/certs/$arg4" ;;
+ *.crl) args="$args crl:FILE:$nistdir/crls/$arg4" ;;
+ *) args="$args $arg4" ;;
+ esac
+ case "$arg5" in
+ *.crt) args="$args chain:FILE:$nistdir/certs/$arg5" ;;
+ *.crl) args="$args crl:FILE:$nistdir/crls/$arg5" ;;
+ *) args="$args $arg5" ;;
+ esac
+
+ args="$args anchor:FILE:$nistdir/certs/TrustAnchorRootCertificate.crt"
+ args="$args crl:FILE:$nistdir/crls/TrustAnchorRootCRL.crl"
+ args="$args cert:FILE:$nistdir/certs/$cert"
+
+ if ${hxtool} verify --time=2008-05-20 $args > /dev/null; then
+ if test "$verify" = "f"; then
+ echo ${hxtool} verify --time=2008-05-20 $args
+ echo "verify passed on fail: $id $cert"
+ ec=1
+ fi
+ elif test "$verify" = "p"; then
+ echo ${hxtool} verify --time=2008-05-20 $args
+ echo "verify failed on pass: $id $cert"
+ ec=1
+ fi
+
+done < $srcdir/data/nist-data
+
+
+echo "done!"
+
+exit $ec
diff --git a/third_party/heimdal/lib/hx509/test_nist2.in b/third_party/heimdal/lib/hx509/test_nist2.in
new file mode 100644
index 0000000..0c4276b
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_nist2.in
@@ -0,0 +1,136 @@
+#!/bin/sh
+#
+# Copyright (c) 2004 - 2008 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# $Id: test_nist.in 21787 2007-08-02 08:50:24Z lha $
+#
+
+srcdir="@srcdir@"
+objdir="@objdir@"
+nistdir=${objdir}/PKITS_data
+nistzip=${srcdir}/data/PKITS_data.zip
+egrep="@egrep@"
+
+limit="${1:-nolimit}"
+
+stat="--statistic-file=${objdir}/statfile"
+
+hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}"
+
+# nistzip is not distributed part of the distribution
+test -f "$nistzip" || exit 77
+
+if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then
+ exit 77
+fi
+if ${hxtool} info | grep 'rand: not available' > /dev/null ; then
+ exit 77
+fi
+
+#--------- Try to find unzip
+
+oldifs=$IFS
+IFS=:
+set -- $PATH
+IFS=$oldifs
+found=
+
+for p in "$@" ; do
+ test -x "$p/unzip" && { found=1 ; break; }
+done
+test "X$found" = "X" && exit 77
+
+#---------
+
+
+echo "nist tests, version 2"
+
+if [ ! -d "$nistdir" ] ; then
+ ( mkdir "$nistdir" && unzip -d "${nistdir}" "${nistzip}" ) >/dev/null || \
+ { rm -rf "$nistdir" ; exit 1; }
+fi
+
+ec=
+name=
+description=
+while read result cert other ; do
+ if expr "$result" : "#" > /dev/null; then
+ name=${cert}
+ description="${other}"
+ continue
+ fi
+
+ test nolimit != "${limit}" && ! expr "$name" : "$limit" > /dev/null && continue
+
+ test "$result" = "end" && break
+
+ args=
+ args="$args cert:FILE:$nistdir/certs/$cert"
+ args="$args chain:DIR:$nistdir/certs"
+ args="$args anchor:FILE:$nistdir/certs/TrustAnchorRootCertificate.crt"
+
+ for a in $nistdir/crls/*.crl; do
+ args="$args crl:FILE:$a"
+ done
+
+ cmd="${hxtool} verify --time=2008-05-20 $args"
+ eval ${cmd} > /dev/null
+ res=$?
+
+ case "${result},${res}" in
+ 0,0) r="PASSs";;
+ 0,*) r="FAILs";;
+ [123],0) r="FAILf";;
+ [123],*) r="PASSf";;
+ *) echo="unknown result ${result},${res}" ; exit 1 ;;
+ esac
+ if ${egrep} "^${name} FAIL" $srcdir/data/nist-result2 > /dev/null; then
+ if expr "$r" : "PASS" >/dev/null; then
+ echo "${name} passed when expected not to"
+ echo "# ${description}" > nist2-passed-${name}.tmp
+ ec=1
+ fi
+ elif ${egrep} "^${name} EITHER" $srcdir/data/nist-result2 > /dev/null; then
+ :
+ elif expr "$r" : "FAIL.*" >/dev/null ; then
+ echo "$r ${name} ${description}"
+ echo "# ${description}" > nist2-failed-${name}.tmp
+ echo "$cmd" >> nist2-failed-${name}.tmp
+ ec=1
+ fi
+
+done < $srcdir/data/nist-data2
+
+
+echo "done!"
+
+exit $ec
diff --git a/third_party/heimdal/lib/hx509/test_nist_cert.in b/third_party/heimdal/lib/hx509/test_nist_cert.in
new file mode 100644
index 0000000..8c683d6
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_nist_cert.in
@@ -0,0 +1,68 @@
+#!/bin/sh
+#
+# Copyright (c) 2006 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# $Id$
+#
+
+srcdir="@srcdir@"
+objdir="@objdir@"
+nistdir=${objdir}/PKITS_data
+nistzip=${srcdir}/data/PKITS_data.zip
+
+# nistzip is not distributed part of the distribution
+test -f "$nistzip" || exit 77
+
+stat="--statistic-file=${objdir}/statfile"
+
+hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}"
+
+if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then
+ exit 77
+fi
+if ${hxtool} info | grep 'rand: not available' > /dev/null ; then
+ exit 77
+fi
+
+if [ ! -d "$nistdir" ] ; then
+ ( mkdir "$nistdir" && cd "$nistdir" && unzip "$nistzip" ) >/dev/null || \
+ { rm -rf "$nistdir" ; exit 1; }
+fi
+
+if ${hxtool} validate DIR:$nistdir/certs > /dev/null; then
+ :
+else
+ echo "validate failed"
+ exit 1
+fi
+
+exit 0
diff --git a/third_party/heimdal/lib/hx509/test_nist_pkcs12.in b/third_party/heimdal/lib/hx509/test_nist_pkcs12.in
new file mode 100644
index 0000000..7898eee
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_nist_pkcs12.in
@@ -0,0 +1,77 @@
+#!/bin/sh
+#
+# Copyright (c) 2004 - 2005 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# $Id$
+#
+
+srcdir="@srcdir@"
+objdir="@objdir@"
+pass="--pass=PASS:password"
+nistdir=${objdir}/PKITS_data
+nistzip=${srcdir}/data/PKITS_data.zip
+
+# nistzip is not distributed part of the distribution
+test -f "$nistzip" || exit 77
+
+stat="--statistic-file=${objdir}/statfile"
+
+hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}"
+
+if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then
+ exit 77
+fi
+if ${hxtool} info | grep 'rand: not available' > /dev/null ; then
+ exit 77
+fi
+
+if [ ! -d "$nistdir" ] ; then
+ ( mkdir "$nistdir" && cd "$nistdir" && unzip "$nistzip" ) >/dev/null || \
+ { rm -rf "$nistdir" ; exit 1; }
+fi
+
+echo "nist pkcs12 tests"
+
+for a in $nistdir/pkcs12/*.p12 ; do
+
+ if ${hxtool} validate $pass PKCS12:$a > /dev/null; then
+ :
+ else
+ echo "$a failed"
+ exit 1
+ fi
+
+done
+
+echo "done!"
+
+exit 0 \ No newline at end of file
diff --git a/third_party/heimdal/lib/hx509/test_pkcs11.in b/third_party/heimdal/lib/hx509/test_pkcs11.in
new file mode 100644
index 0000000..278296a
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_pkcs11.in
@@ -0,0 +1,62 @@
+#!/bin/sh
+#
+# Copyright (c) 2008 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+
+srcdir="@srcdir@"
+objdir="@objdir@"
+
+SOFTPKCS11RC="test-rc-file.rc" \
+export SOFTPKCS11RC
+
+echo "password less"
+
+cat > test-rc-file.rc <<EOF
+certificate cert User certificate FILE:$srcdir/data/test.crt,$srcdir/data/test.key
+debug p11dbg.log
+app-fatal true
+EOF
+
+./test_soft_pkcs11 || exit 1
+
+echo "password"
+
+cat > test-rc-file.rc <<EOF
+certificate cert User certificate FILE:$srcdir/data/test.crt,$srcdir/data/test-pw.key
+debug p11dbg.log
+app-fatal true
+EOF
+
+./test_soft_pkcs11 || exit 1
+
+echo "done"
+exit 0
diff --git a/third_party/heimdal/lib/hx509/test_query.in b/third_party/heimdal/lib/hx509/test_query.in
new file mode 100644
index 0000000..d29d78a
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_query.in
@@ -0,0 +1,203 @@
+#!/bin/sh
+#
+# Copyright (c) 2005 - 2008 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# $Id$
+#
+
+srcdir="@srcdir@"
+objdir="@objdir@"
+
+stat="--statistic-file=${objdir}/statfile"
+
+hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}"
+
+echo "try printing"
+${hxtool} print \
+ --pass=PASS:foobar \
+ --info --content \
+ PKCS12:$srcdir/data/test.p12 >/dev/null 2>/dev/null || exit 1
+
+echo "try printing"
+${hxtool} print \
+ --pass=PASS:foobar \
+ --info --content \
+ FILE:$srcdir/data/kdc.crt >/dev/null 2>/dev/null || exit 1
+
+${hxtool} print \
+ --pass=PASS:foobar \
+ --info \
+ PKCS12:$srcdir/data/test.p12 >/dev/null 2>/dev/null || exit 1
+
+echo "make sure entry is found (friendlyname)"
+${hxtool} query \
+ --pass=PASS:foobar \
+ --friendlyname=friendlyname-test \
+ PKCS12:$srcdir/data/test.p12 >/dev/null 2>/dev/null || exit 1
+
+echo "make sure entry is not found (friendlyname)"
+${hxtool} query \
+ --pass=PASS:foobar \
+ --friendlyname=friendlyname-test-not \
+ PKCS12:$srcdir/data/test.p12 >/dev/null 2>/dev/null && exit 1
+
+echo "make sure entry is found (eku)"
+${hxtool} query \
+ --eku=1.3.6.1.5.2.3.5 \
+ FILE:$srcdir/data/kdc.crt >/dev/null 2>/dev/null || exit 1
+
+echo "make sure entry is not found (eku)"
+${hxtool} query \
+ --eku=1.3.6.1.5.2.3.6 \
+ FILE:$srcdir/data/kdc.crt >/dev/null 2>/dev/null && exit 1
+
+echo "make sure entry is found (friendlyname, no-pw)"
+${hxtool} query \
+ --friendlyname=friendlyname-cert \
+ PKCS12:$srcdir/data/test-nopw.p12 >/dev/null 2>/dev/null || exit 1
+
+echo "check for ca cert (friendlyname)"
+${hxtool} query \
+ --pass=PASS:foobar \
+ --friendlyname=ca \
+ PKCS12:$srcdir/data/test.p12 >/dev/null 2>/dev/null || exit 1
+
+echo "make sure entry is not found (friendlyname)"
+${hxtool} query \
+ --pass=PASS:foobar \
+ --friendlyname=friendlyname-test \
+ PKCS12:$srcdir/data/sub-cert.p12 >/dev/null 2>/dev/null && exit 1
+
+echo "make sure entry is found (friendlyname|private key)"
+${hxtool} query \
+ --pass=PASS:foobar \
+ --friendlyname=friendlyname-test \
+ --private-key \
+ PKCS12:$srcdir/data/test.p12 > /dev/null || exit 1
+
+echo "make sure entry is not found (friendlyname|private key)"
+${hxtool} query \
+ --pass=PASS:foobar \
+ --friendlyname=ca \
+ --private-key \
+ PKCS12:$srcdir/data/test.p12 >/dev/null 2>/dev/null && exit 1
+
+echo "make sure entry is found (cert ds)"
+${hxtool} query \
+ --digitalSignature \
+ FILE:$srcdir/data/test.crt >/dev/null 2>/dev/null || exit 1
+
+echo "make sure entry is found (cert ke)"
+${hxtool} query \
+ --keyEncipherment \
+ FILE:$srcdir/data/test.crt >/dev/null 2>/dev/null || exit 1
+
+echo "make sure entry is found (cert ke + ds)"
+${hxtool} query \
+ --digitalSignature \
+ --keyEncipherment \
+ FILE:$srcdir/data/test.crt >/dev/null 2>/dev/null || exit 1
+
+echo "make sure entry is found (cert-ds ds)"
+${hxtool} query \
+ --digitalSignature \
+ FILE:$srcdir/data/test-ds-only.crt >/dev/null 2>/dev/null || exit 1
+
+echo "make sure entry is not found (cert-ds ke)"
+${hxtool} query \
+ --keyEncipherment \
+ FILE:$srcdir/data/test-ds-only.crt >/dev/null 2>/dev/null && exit 1
+
+echo "make sure entry is not found (cert-ds ke + ds)"
+${hxtool} query \
+ --digitalSignature \
+ --keyEncipherment \
+ FILE:$srcdir/data/test-ds-only.crt >/dev/null 2>/dev/null && exit 1
+
+echo "make sure entry is not found (cert-ke ds)"
+${hxtool} query \
+ --digitalSignature \
+ FILE:$srcdir/data/test-ke-only.crt >/dev/null 2>/dev/null && exit 1
+
+echo "make sure entry is found (cert-ke ke)"
+${hxtool} query \
+ --keyEncipherment \
+ FILE:$srcdir/data/test-ke-only.crt >/dev/null 2>/dev/null || exit 1
+
+echo "make sure entry is not found (cert-ke ke + ds)"
+${hxtool} query \
+ --digitalSignature \
+ --keyEncipherment \
+ FILE:$srcdir/data/test-ke-only.crt >/dev/null 2>/dev/null && exit 1
+
+echo "make sure entry is found (eku) in query language"
+${hxtool} query \
+ --expr='"1.3.6.1.5.2.3.5" IN %{certificate.eku}' \
+ FILE:$srcdir/data/kdc.crt > /dev/null || exit 1
+
+echo "make sure entry is not found (eku) in query language"
+${hxtool} query \
+ --expr='"1.3.6.1.5.2.3.6" IN %{certificate.eku}' \
+ FILE:$srcdir/data/kdc.crt > /dev/null && exit 1
+
+echo "make sure entry is found (subject) in query language"
+${hxtool} query \
+ --expr='%{certificate.subject} == "CN=kdc,C=SE"' \
+ FILE:$srcdir/data/kdc.crt > /dev/null || exit 1
+
+echo "make sure entry is found using TAILMATCH (subject) in query language"
+${hxtool} query \
+ --expr='%{certificate.subject} TAILMATCH "C=SE"' \
+ FILE:$srcdir/data/kdc.crt > /dev/null || exit 1
+
+echo "make sure entry is not found using TAILMATCH (subject) in query language"
+${hxtool} query \
+ --expr='%{certificate.subject} TAILMATCH "C=FI"' \
+ FILE:$srcdir/data/kdc.crt > /dev/null && exit 1
+
+echo "make sure entry is found (issuer) in query language"
+${hxtool} query \
+ --expr='%{certificate.issuer} == "C=SE,CN=hx509 Test Root CA"' \
+ FILE:$srcdir/data/kdc.crt > /dev/null || exit 1
+
+echo "make sure entry match with EKU and TAILMATCH in query language"
+${hxtool} query \
+ --expr='"1.3.6.1.5.2.3.5" IN %{certificate.eku} AND %{certificate.subject} TAILMATCH "C=SE"' \
+ FILE:$srcdir/data/kdc.crt > /dev/null || exit 1
+
+echo "make sure entry match with hash.sha1"
+${hxtool} query \
+ --expr='"%{certificate.hash.sha1}EQ "412120212A2CBFD777DE5499ECB4724345F33F16"' \
+ FILE:$srcdir/data/kdc.crt > /dev/null || exit 1
+
+
+exit 0
diff --git a/third_party/heimdal/lib/hx509/test_req.in b/third_party/heimdal/lib/hx509/test_req.in
new file mode 100644
index 0000000..a070b1d
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_req.in
@@ -0,0 +1,135 @@
+#!/bin/sh
+#
+# Copyright (c) 2005 - 2007 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# $Id$
+#
+
+srcdir="@srcdir@"
+objdir="@objdir@"
+
+stat="--statistic-file=${objdir}/statfile"
+
+hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}"
+
+if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then
+ exit 77
+fi
+if ${hxtool} info | grep 'rand: not available' > /dev/null ; then
+ exit 77
+fi
+
+${hxtool} request-create \
+ --subject="CN=Love,DC=it,DC=su,DC=se" \
+ --key="FILE:$srcdir/data/key.der" \
+ "${objdir}/request.out" || exit 1
+
+${hxtool} request-print \
+ PKCS10:request.out > /dev/null || exit 1
+
+${hxtool} request-create \
+ --subject="CN=Love,DC=it,DC=su,DC=se" \
+ --eku=1.2.3.4.5.6.7 --eku=1.2.3.4.5.6.8 \
+ --registered=1.2.3.4.5.6.9 --eku=1.2.3.4.5.6.10 \
+ --dnsname=nutcracker.test.h5l.se \
+ --dnsname=foo.nutcracker.test.h5l.se \
+ --kerberos=HTTP/foo.nutcracker.it.su.se@TEST.H5L.SE \
+ --kerberos=host/foo.nutcracker.it.su.se@TEST.H5L.SE \
+ --email=foo@test.h5l.se \
+ --key="FILE:$srcdir/data/key.der" \
+ "${objdir}/request.out" || exit 1
+
+cat > "$objdir/expected" <<EOF
+request print
+PKCS#10 CertificationRequest:
+ name: CN=Love,DC=it,DC=su,DC=se
+ eku: {1.2.3.4.5.6.7}, {1.2.3.4.5.6.8}, {1.2.3.4.5.6.10}
+ san: rfc822Name: foo@test.h5l.se
+ san: dNSName: nutcracker.test.h5l.se
+ san: dNSName: foo.nutcracker.test.h5l.se
+ san: pkinit: HTTP/foo.nutcracker.it.su.se@TEST.H5L.SE
+ san: pkinit: host/foo.nutcracker.it.su.se@TEST.H5L.SE
+ san: registeredID: 1.2.3.4.5.6.9
+EOF
+
+# Check that we got what we wanted:
+${hxtool} request-print \
+ PKCS10:request.out > "${objdir}/actual" || exit 1
+
+diff "$objdir/expected" "${objdir}/actual" || exit 1
+
+# Check that OpenSSL can parse our request:
+if openssl version > /dev/null; then
+ openssl req -inform DER -in "${objdir}/request.out" -text | head -25 > "${objdir}/actual"
+
+ # Various versions of openssl differ slightly in their text output for our
+ # CSR. Figure out what to expect:
+ if grep "Version: 0" "${objdir}/actual" > /dev/null; then
+ v=0
+ else
+ v=1
+ fi
+ if grep "RSA Public-Key:" "${objdir}/actual" > /dev/null; then
+ k="RSA "
+ else
+ k=""
+ fi
+ # Note interpolation of $v and $k in the here doc below:
+ cat > "$objdir/expected" <<EOF
+Certificate Request:
+ Data:
+ Version: $v (0x0)
+ Subject: DC = se, DC = su, DC = it, CN = Love
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ ${k}Public-Key: (1024 bit)
+ Modulus:
+ 00:c2:aa:a2:42:b7:5b:99:a3:fd:ba:f0:9b:75:db:
+ ef:3c:9b:8c:cf:63:5f:46:d8:95:be:09:4a:a7:76:
+ 79:77:61:30:ef:0b:98:d2:47:ea:9c:09:b9:b9:b7:
+ 15:ac:4b:9c:2d:3f:f0:d9:99:9d:4d:5a:68:67:24:
+ 58:5e:65:60:13:9f:4d:dc:2f:03:1d:cd:e9:b6:33:
+ c2:5c:c6:de:c9:93:6c:ec:8d:9a:67:0e:dd:31:20:
+ ac:91:39:7a:c1:8f:39:65:ff:b3:1f:cf:7a:aa:79:
+ 8b:ed:eb:ad:a0:be:01:10:4c:5a:a7:47:1d:c6:ee:
+ 79:39:5c:c7:11:6c:b9:e7:2b
+ Exponent: 65537 (0x10001)
+ Attributes:
+ Requested Extensions:
+ X509v3 Extended Key Usage: critical
+ 1.2.3.4.5.6.7, 1.2.3.4.5.6.8, 1.2.3.4.5.6.10
+ X509v3 Subject Alternative Name:
+ email:foo@test.h5l.se, DNS:nutcracker.test.h5l.se, DNS:foo.nutcracker.test.h5l.se, othername:<unsupported>, othername:<unsupported>, Registered ID:1.2.3.4.5.6.9
+ Signature Algorithm: sha256WithRSAEncryption
+EOF
+ diff -w "${objdir}/expected" "${objdir}/actual" || exit 1
+fi
diff --git a/third_party/heimdal/lib/hx509/test_soft_pkcs11.c b/third_party/heimdal/lib/hx509/test_soft_pkcs11.c
new file mode 100644
index 0000000..cdffcf8
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_soft_pkcs11.c
@@ -0,0 +1,228 @@
+/*
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hx_locl.h"
+#include "ref/pkcs11.h"
+#include <err.h>
+
+static CK_FUNCTION_LIST_PTR func;
+
+
+static CK_RV
+find_object(CK_SESSION_HANDLE session,
+ char *id,
+ CK_OBJECT_CLASS key_class,
+ CK_OBJECT_HANDLE_PTR object)
+{
+ CK_ULONG object_count;
+ CK_RV ret;
+ CK_ATTRIBUTE search_data[] = {
+ {CKA_ID, id, 0 },
+ {CKA_CLASS, &key_class, sizeof(key_class)}
+ };
+ CK_ULONG num_search_data = sizeof(search_data)/sizeof(search_data[0]);
+
+ search_data[0].ulValueLen = strlen(id);
+
+ ret = (*func->C_FindObjectsInit)(session, search_data, num_search_data);
+ if (ret != CKR_OK)
+ return ret;
+
+ ret = (*func->C_FindObjects)(session, object, 1, &object_count);
+ if (ret != CKR_OK)
+ return ret;
+ if (object_count == 0) {
+ printf("found no object\n");
+ return 1;
+ }
+
+ ret = (*func->C_FindObjectsFinal)(session);
+ if (ret != CKR_OK)
+ return ret;
+
+ return CKR_OK;
+}
+
+static char *sighash = "hej";
+static char signature[1024];
+
+
+int
+main(int argc, char **argv)
+{
+ CK_SLOT_ID_PTR slot_ids;
+ CK_SLOT_ID slot;
+ CK_ULONG num_slots;
+ CK_RV ret;
+ CK_SLOT_INFO slot_info;
+ CK_TOKEN_INFO token_info;
+ CK_SESSION_HANDLE session;
+ CK_OBJECT_HANDLE public, private;
+
+ ret = C_GetFunctionList(&func);
+ if (ret != CKR_OK)
+ errx(1, "C_GetFunctionList failed: %d", (int)ret);
+
+ (*func->C_Initialize)(NULL_PTR);
+
+ ret = (*func->C_GetSlotList)(FALSE, NULL, &num_slots);
+ if (ret != CKR_OK)
+ errx(1, "C_GetSlotList1 failed: %d", (int)ret);
+
+ if (num_slots == 0)
+ errx(1, "no slots");
+
+ if ((slot_ids = calloc(1, num_slots * sizeof(*slot_ids))) == NULL)
+ err(1, "alloc slots failed");
+
+ ret = (*func->C_GetSlotList)(FALSE, slot_ids, &num_slots);
+ if (ret != CKR_OK)
+ errx(1, "C_GetSlotList2 failed: %d", (int)ret);
+
+ slot = slot_ids[0];
+ free(slot_ids);
+
+ ret = (*func->C_GetSlotInfo)(slot, &slot_info);
+ if (ret)
+ errx(1, "C_GetSlotInfo failed: %d", (int)ret);
+
+ if ((slot_info.flags & CKF_TOKEN_PRESENT) == 0)
+ errx(1, "no token present");
+
+ ret = (*func->C_OpenSession)(slot, CKF_SERIAL_SESSION,
+ NULL, NULL, &session);
+ if (ret != CKR_OK)
+ errx(1, "C_OpenSession failed: %d", (int)ret);
+
+ ret = (*func->C_GetTokenInfo)(slot, &token_info);
+ if (ret)
+ errx(1, "C_GetTokenInfo1 failed: %d", (int)ret);
+
+ if (token_info.flags & CKF_LOGIN_REQUIRED) {
+ ret = (*func->C_Login)(session, CKU_USER,
+ (unsigned char*)"foobar", 6);
+ if (ret != CKR_OK)
+ errx(1, "C_Login failed: %d", (int)ret);
+ }
+
+ ret = (*func->C_GetTokenInfo)(slot, &token_info);
+ if (ret)
+ errx(1, "C_GetTokenInfo2 failed: %d", (int)ret);
+
+ if (token_info.flags & CKF_LOGIN_REQUIRED)
+ errx(1, "login required, even after C_Login");
+
+ ret = find_object(session, "cert", CKO_PUBLIC_KEY, &public);
+ if (ret != CKR_OK)
+ errx(1, "find cert failed: %d", (int)ret);
+ ret = find_object(session, "cert", CKO_PRIVATE_KEY, &private);
+ if (ret != CKR_OK)
+ errx(1, "find private key failed: %d", (int)ret);
+
+ {
+ CK_ULONG ck_sigsize;
+ CK_MECHANISM mechanism;
+
+ memset(&mechanism, 0, sizeof(mechanism));
+ mechanism.mechanism = CKM_RSA_PKCS;
+
+ ret = (*func->C_SignInit)(session, &mechanism, private);
+ if (ret != CKR_OK)
+ return 1;
+
+ ck_sigsize = sizeof(signature);
+ ret = (*func->C_Sign)(session, (CK_BYTE *)sighash, strlen(sighash),
+ (CK_BYTE *)signature, &ck_sigsize);
+ if (ret != CKR_OK) {
+ printf("C_Sign failed with: %d\n", (int)ret);
+ return 1;
+ }
+
+ ret = (*func->C_VerifyInit)(session, &mechanism, public);
+ if (ret != CKR_OK)
+ return 1;
+
+ ret = (*func->C_Verify)(session, (CK_BYTE *)signature, ck_sigsize,
+ (CK_BYTE *)sighash, strlen(sighash));
+ if (ret != CKR_OK) {
+ printf("message: %d\n", (int)ret);
+ return 1;
+ }
+ }
+
+#if 0
+ {
+ CK_ULONG ck_sigsize, outsize;
+ CK_MECHANISM mechanism;
+ char outdata[1024];
+
+ memset(&mechanism, 0, sizeof(mechanism));
+ mechanism.mechanism = CKM_RSA_PKCS;
+
+ ret = (*func->C_EncryptInit)(session, &mechanism, public);
+ if (ret != CKR_OK)
+ return 1;
+
+ ck_sigsize = sizeof(signature);
+ ret = (*func->C_Encrypt)(session, (CK_BYTE *)sighash, strlen(sighash),
+ (CK_BYTE *)signature, &ck_sigsize);
+ if (ret != CKR_OK) {
+ printf("message: %d\n", (int)ret);
+ return 1;
+ }
+
+ ret = (*func->C_DecryptInit)(session, &mechanism, private);
+ if (ret != CKR_OK)
+ return 1;
+
+ outsize = sizeof(outdata);
+ ret = (*func->C_Decrypt)(session, (CK_BYTE *)signature, ck_sigsize,
+ (CK_BYTE *)outdata, &outsize);
+ if (ret != CKR_OK) {
+ printf("message: %d\n", (int)ret);
+ return 1;
+ }
+
+ if (ct_memcmp(sighash, outdata, strlen(sighash)) != 0)
+ return 1;
+ }
+#endif
+
+ ret = (*func->C_CloseSession)(session);
+ if (ret != CKR_OK)
+ return 1;
+
+ (*func->C_Finalize)(NULL_PTR);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/hx509/test_windows.in b/third_party/heimdal/lib/hx509/test_windows.in
new file mode 100644
index 0000000..c617f81
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/test_windows.in
@@ -0,0 +1,89 @@
+#!/bin/sh
+#
+# Copyright (c) 2007 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# $Id$
+#
+
+srcdir="@srcdir@"
+objdir="@objdir@"
+
+stat="--statistic-file=${objdir}/statfile"
+
+hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}"
+
+if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then
+ exit 77
+fi
+if ${hxtool} info | grep 'rand: not available' > /dev/null ; then
+ exit 77
+fi
+
+echo "Create trust anchor"
+${hxtool} issue-certificate \
+ --self-signed \
+ --issue-ca \
+ --generate-key=rsa \
+ --subject="CN=Windows-CA,DC=heimdal,DC=pki" \
+ --lifetime=10years \
+ --certificate="FILE:wca.pem" || exit 1
+
+echo "Create domain controller cert"
+${hxtool} issue-certificate \
+ --type="pkinit-kdc" \
+ --pk-init-principal="krbtgt/HEIMDAL.PKI@HEIMDAL.PKI" \
+ --hostname=kdc.heimdal.pki \
+ --generate-key=rsa \
+ --subject="CN=kdc.heimdal.pki,dc=heimdal,dc=pki" \
+ --certificate="FILE:wdc.pem" \
+ --domain-controller \
+ --crl-uri="http://www.test.h5l.se/test-hemdal-pki-crl1.crl" \
+ --ca-certificate=FILE:wca.pem || exit 1
+
+
+echo "Create user cert"
+${hxtool} issue-certificate \
+ --type="pkinit-client" \
+ --pk-init-principal="user@HEIMDAL.PKI" \
+ --generate-key=rsa \
+ --subject="CN=User,DC=heimdal,DC=pki" \
+ --ms-upn="user@heimdal.pki" \
+ --crl-uri="http://www.test.h5l.se/test-hemdal-pki-crl1.crl" \
+ --certificate="FILE:wuser.pem" \
+ --ca-certificate=FILE:wca.pem || exit 1
+
+echo "Create crl"
+${hxtool} crl-sign \
+ --crl-file=wcrl.crl \
+ --signer=FILE:wca.pem || exit 1
+
+exit 0
diff --git a/third_party/heimdal/lib/hx509/tst-crypto-available1 b/third_party/heimdal/lib/hx509/tst-crypto-available1
new file mode 100644
index 0000000..71fa741
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/tst-crypto-available1
@@ -0,0 +1,13 @@
+1.2.840.113549.1.1.11
+1.2.840.113549.1.1.5
+1.2.840.113549.1.1.5
+1.2.840.113549.1.1.4
+1.2.840.113549.1.1.2
+1.2.752.43.16.1
+2.16.840.1.101.3.4.2.1
+1.3.14.3.2.26
+1.2.840.113549.2.5
+1.2.840.113549.2.2
+1.2.840.113549.3.7
+2.16.840.1.101.3.4.1.2
+2.16.840.1.101.3.4.1.42
diff --git a/third_party/heimdal/lib/hx509/tst-crypto-available2 b/third_party/heimdal/lib/hx509/tst-crypto-available2
new file mode 100644
index 0000000..22c0920
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/tst-crypto-available2
@@ -0,0 +1,5 @@
+2.16.840.1.101.3.4.2.3
+2.16.840.1.101.3.4.2.2
+2.16.840.1.101.3.4.2.1
+1.3.14.3.2.26
+1.2.840.113549.2.5
diff --git a/third_party/heimdal/lib/hx509/tst-crypto-available3 b/third_party/heimdal/lib/hx509/tst-crypto-available3
new file mode 100644
index 0000000..0b1a855
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/tst-crypto-available3
@@ -0,0 +1,6 @@
+1.2.840.113549.1.1.11
+1.2.840.113549.1.1.5
+1.2.840.113549.1.1.5
+1.2.840.113549.1.1.4
+1.2.840.113549.1.1.2
+1.2.752.43.16.1
diff --git a/third_party/heimdal/lib/hx509/tst-crypto-select b/third_party/heimdal/lib/hx509/tst-crypto-select
new file mode 100644
index 0000000..399c883
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/tst-crypto-select
@@ -0,0 +1 @@
+1.2.840.113549.1.1.11
diff --git a/third_party/heimdal/lib/hx509/tst-crypto-select1 b/third_party/heimdal/lib/hx509/tst-crypto-select1
new file mode 100644
index 0000000..c343b57
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/tst-crypto-select1
@@ -0,0 +1 @@
+2.16.840.1.101.3.4.2.1
diff --git a/third_party/heimdal/lib/hx509/tst-crypto-select2 b/third_party/heimdal/lib/hx509/tst-crypto-select2
new file mode 100644
index 0000000..399c883
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/tst-crypto-select2
@@ -0,0 +1 @@
+1.2.840.113549.1.1.11
diff --git a/third_party/heimdal/lib/hx509/tst-crypto-select3 b/third_party/heimdal/lib/hx509/tst-crypto-select3
new file mode 100644
index 0000000..ba9f29f
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/tst-crypto-select3
@@ -0,0 +1 @@
+1.2.840.113549.1.1.4
diff --git a/third_party/heimdal/lib/hx509/tst-crypto-select4 b/third_party/heimdal/lib/hx509/tst-crypto-select4
new file mode 100644
index 0000000..749a549
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/tst-crypto-select4
@@ -0,0 +1 @@
+1.2.840.113549.1.1.5
diff --git a/third_party/heimdal/lib/hx509/tst-crypto-select5 b/third_party/heimdal/lib/hx509/tst-crypto-select5
new file mode 100644
index 0000000..399c883
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/tst-crypto-select5
@@ -0,0 +1 @@
+1.2.840.113549.1.1.11
diff --git a/third_party/heimdal/lib/hx509/tst-crypto-select6 b/third_party/heimdal/lib/hx509/tst-crypto-select6
new file mode 100644
index 0000000..749a549
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/tst-crypto-select6
@@ -0,0 +1 @@
+1.2.840.113549.1.1.5
diff --git a/third_party/heimdal/lib/hx509/tst-crypto-select7 b/third_party/heimdal/lib/hx509/tst-crypto-select7
new file mode 100644
index 0000000..9b0ac64
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/tst-crypto-select7
@@ -0,0 +1 @@
+2.16.840.1.101.3.4.1.42
diff --git a/third_party/heimdal/lib/hx509/version-script.map b/third_party/heimdal/lib/hx509/version-script.map
new file mode 100644
index 0000000..a6c81da
--- /dev/null
+++ b/third_party/heimdal/lib/hx509/version-script.map
@@ -0,0 +1,302 @@
+# $Id$
+
+HEIMDAL_X509_1.2 {
+ global:
+ _hx509_cert_assign_key;
+ _hx509_cert_get_keyusage;
+ _hx509_cert_get_version;
+ _hx509_cert_private_key;
+ _hx509_certs_keys_free;
+ _hx509_certs_keys_get;
+ _hx509_expr_eval;
+ _hx509_expr_free;
+ _hx509_expr_parse;
+ _hx509_generate_private_key;
+ _hx509_generate_private_key_bits;
+ _hx509_generate_private_key_free;
+ _hx509_generate_private_key_init;
+ _hx509_generate_private_key_is_ca;
+ _hx509_get_cert;
+ _hx509_ks_type;
+ _hx509_make_pkinit_san;
+ _hx509_map_file_os;
+ _hx509_name_from_Name;
+ _hx509_private_key_export;
+ _hx509_private_key_exportable;
+ _hx509_private_key_get_internal;
+ _hx509_private_key_oid;
+ _hx509_private_key_ref;
+ hx509_request_add_GeneralName;
+ hx509_request_add_dns_name;
+ hx509_request_add_dns_srv;
+ hx509_request_add_eku;
+ hx509_request_add_email;
+ hx509_request_add_ms_upn_name;
+ hx509_request_add_pkinit;
+ hx509_request_add_registered;
+ hx509_request_add_xmpp_name;
+ hx509_request_authorize_ku;
+ hx509_request_authorize_eku;
+ hx509_request_authorize_san;
+ hx509_request_count_unsupported;
+ hx509_request_count_unauthorized;
+ hx509_request_print;
+ hx509_request_to_pkcs10;
+ _hx509_unmap_file_os;
+ _hx509_write_file;
+ hx509_bitstring_print;
+ _hx509_ca_issue_certificate;
+ hx509_ca_sign;
+ hx509_ca_sign_self;
+ hx509_ca_tbs_add_crl_dp_uri;
+ hx509_ca_tbs_add_eku;
+ hx509_ca_tbs_add_ku;
+ hx509_ca_tbs_add_pol;
+ hx509_ca_tbs_add_pol_mapping;
+ hx509_ca_tbs_add_san;
+ hx509_ca_tbs_add_san_dnssrv;
+ hx509_ca_tbs_add_san_hardwareModuleName;
+ hx509_ca_tbs_add_san_hardwareModuleName_string;
+ hx509_ca_tbs_add_san_hostname;
+ hx509_ca_tbs_add_san_jid;
+ hx509_ca_tbs_add_san_ms_upn;
+ hx509_ca_tbs_add_san_otherName;
+ hx509_ca_tbs_add_san_permanentIdentifier;
+ hx509_ca_tbs_add_san_permanentIdentifier_string;
+ hx509_ca_tbs_add_san_pkinit;
+ hx509_ca_tbs_add_san_rfc822name;
+ hx509_ca_tbs_free;
+ hx509_ca_tbs_get_name;
+ hx509_ca_tbs_init;
+ hx509_ca_tbs_set_ca;
+ hx509_ca_tbs_set_domaincontroller;
+ hx509_ca_tbs_set_from_csr;
+ hx509_ca_tbs_set_notAfter;
+ hx509_ca_tbs_set_notAfter_lifetime;
+ hx509_ca_tbs_set_notBefore;
+ hx509_ca_tbs_set_pkinit_max_life;
+ hx509_ca_tbs_set_proxy;
+ hx509_ca_tbs_set_serialnumber;
+ hx509_ca_tbs_set_spki;
+ hx509_ca_tbs_set_subject;
+ hx509_ca_tbs_set_template;
+ hx509_ca_tbs_set_unique;
+ hx509_ca_tbs_subject_expand;
+ hx509_ca_tbs_template_units;
+ hx509_cert;
+ hx509_cert_attribute;
+ hx509_cert_binary;
+ hx509_cert_check_eku;
+ hx509_cert_cmp;
+ hx509_cert_find_subjectAltName_otherName;
+ hx509_cert_free;
+ hx509_cert_get_SPKI;
+ hx509_cert_get_SPKI_AlgorithmIdentifier;
+ hx509_cert_get_attribute;
+ hx509_cert_get_base_subject;
+ hx509_cert_get_friendly_name;
+ hx509_cert_get_issuer;
+ hx509_cert_get_notAfter;
+ hx509_cert_get_notBefore;
+ hx509_cert_get_pkinit_max_life;
+ hx509_cert_get_serialnumber;
+ hx509_cert_get_subject;
+ hx509_cert_get_issuer_unique_id;
+ hx509_cert_get_subject_unique_id;
+ hx509_cert_have_private_key;
+ hx509_cert_have_private_key_only;
+ hx509_cert_init;
+ hx509_cert_init_data;
+ hx509_cert_init_private_key;
+ hx509_cert_keyusage_print;
+ hx509_cert_public_encrypt;
+ hx509_cert_ref;
+ hx509_cert_set_friendly_name;
+ hx509_certs_add;
+ hx509_certs_append;
+ hx509_certs_end_seq;
+ hx509_certs_destroy;
+ hx509_certs_ref;
+ hx509_certs_filter;
+ hx509_certs_find;
+ hx509_certs_free;
+ hx509_certs_info;
+ hx509_certs_init;
+ hx509_certs_iter;
+ hx509_certs_iter_f;
+ hx509_certs_merge;
+ hx509_certs_next_cert;
+ hx509_certs_start_seq;
+ hx509_certs_store;
+ hx509_ci_print_names;
+ hx509_clear_error_string;
+ hx509_cms_create_signed;
+ hx509_cms_create_signed_1;
+ hx509_cms_decrypt_encrypted;
+ hx509_cms_envelope_1;
+ hx509_cms_unenvelope;
+ hx509_cms_unwrap_ContentInfo;
+ hx509_cms_verify_signed;
+ hx509_cms_verify_signed_ext;
+ hx509_cms_wrap_ContentInfo;
+ hx509_context_free;
+ hx509_context_init;
+ hx509_context_set_missing_revoke;
+ hx509_crl_add_revoked_certs;
+ hx509_crl_alloc;
+ hx509_crl_free;
+ hx509_crl_lifetime;
+ hx509_crl_sign;
+ hx509_crypto_aes128_cbc;
+ hx509_crypto_aes256_cbc;
+ hx509_crypto_allow_weak;
+ hx509_crypto_available;
+ hx509_crypto_decrypt;
+ hx509_crypto_des_rsdi_ede3_cbc;
+ hx509_crypto_destroy;
+ hx509_crypto_encrypt;
+ hx509_crypto_enctype_by_name;
+ hx509_crypto_free_algs;
+ hx509_crypto_get_params;
+ hx509_crypto_init;
+ hx509_crypto_provider;
+ hx509_crypto_select;
+ hx509_crypto_set_key_data;
+ hx509_crypto_set_key_name;
+ hx509_crypto_set_padding;
+ hx509_crypto_set_params;
+ hx509_crypto_set_random_key;
+ hx509_empty_name;
+ hx509_env_add;
+ hx509_env_add_binding;
+ hx509_env_find;
+ hx509_env_find_binding;
+ hx509_env_free;
+ hx509_env_init;
+ hx509_env_lfind;
+ hx509_err;
+ hx509_free_error_string;
+ hx509_free_octet_string_list;
+ hx509_find_private_alg;
+ hx509_general_name_unparse;
+ hx509_get_error_string;
+ hx509_get_instance;
+ hx509_get_one_cert;
+ hx509_lock_add_cert;
+ hx509_lock_add_certs;
+ hx509_lock_add_password;
+ hx509_lock_command_string;
+ hx509_lock_free;
+ hx509_lock_init;
+ hx509_lock_prompt;
+ hx509_lock_reset_certs;
+ hx509_lock_reset_passwords;
+ hx509_lock_reset_promper;
+ hx509_lock_set_prompter;
+ hx509_name_binary;
+ hx509_name_cmp;
+ hx509_name_copy;
+ hx509_name_expand;
+ hx509_name_free;
+ hx509_name_is_null_p;
+ hx509_name_normalize;
+ hx509_name_to_Name;
+ hx509_name_to_string;
+ hx509_ocsp_request;
+ hx509_ocsp_verify;
+ hx509_oid_print;
+ hx509_oid_sprint;
+ hx509_parse_name;
+ hx509_parse_private_key;
+ hx509_peer_info_add_cms_alg;
+ hx509_peer_info_alloc;
+ hx509_peer_info_free;
+ hx509_peer_info_set_cert;
+ hx509_peer_info_set_cms_algs;
+ hx509_pem_add_header;
+ hx509_pem_find_header;
+ hx509_pem_free_header;
+ hx509_pem_read;
+ hx509_pem_write;
+ hx509_print_stdout;
+ hx509_print_cert;
+ hx509_private_key_assign_rsa;
+ hx509_private_key_free;
+ hx509_private_key_private_decrypt;
+ hx509_private_key_init;
+ hx509_private_key2SPKI;
+ hx509_prompt_hidden;
+ hx509_query_alloc;
+ hx509_query_free;
+ hx509_query_match_cmp_func;
+ hx509_query_match_eku;
+ hx509_query_match_expr;
+ hx509_query_match_friendly_name;
+ hx509_query_match_issuer_serial;
+ hx509_query_match_option;
+ hx509_query_statistic_file;
+ hx509_query_unparse_stats;
+ hx509_request_get_eku;
+ hx509_request_get_exts;
+ hx509_request_get_ku;
+ hx509_request_get_name;
+ hx509_request_get_san;
+ hx509_request_get_SubjectPublicKeyInfo;
+ hx509_request_free;
+ hx509_request_init;
+ hx509_request_parse;
+ hx509_request_parse_der;
+ hx509_request_set_ku;
+ hx509_request_set_name;
+ hx509_request_set_SubjectPublicKeyInfo;
+ hx509_revoke_add_crl;
+ hx509_revoke_add_ocsp;
+ hx509_revoke_free;
+ hx509_revoke_init;
+ hx509_revoke_ocsp_print;
+ hx509_revoke_verify;
+ hx509_revoke_print;
+ hx509_set_error_string;
+ hx509_set_error_stringv;
+ hx509_signature_md5;
+ hx509_signature_rsa;
+ hx509_signature_rsa_with_md5;
+ hx509_signature_rsa_with_sha1;
+ hx509_signature_rsa_with_sha256;
+ hx509_signature_rsa_with_sha384;
+ hx509_signature_rsa_with_sha512;
+ hx509_signature_sha1;
+ hx509_signature_sha256;
+ hx509_signature_sha384;
+ hx509_signature_sha512;
+ hx509_unparse_der_name;
+ hx509_validate_cert;
+ hx509_validate_ctx_add_flags;
+ hx509_validate_ctx_free;
+ hx509_validate_ctx_init;
+ hx509_validate_ctx_set_print;
+ hx509_verify_attach_anchors;
+ hx509_verify_attach_revoke;
+ hx509_verify_ctx_f_allow_default_trustanchors;
+ hx509_verify_destroy_ctx;
+ hx509_verify_hostname;
+ hx509_verify_init_ctx;
+ hx509_verify_path;
+ hx509_verify_set_max_depth;
+ hx509_verify_set_proxy_certificate;
+ hx509_verify_set_strict_rfc3280_verification;
+ hx509_verify_set_time;
+ hx509_verify_signature;
+ hx509_xfree;
+ initialize_hx_error_table_r;
+ # pkcs11 symbols
+ C_GetFunctionList;
+ local:
+ *;
+};
+
+HEIMDAL_X509_1.3 {
+ global:
+ hx509_ca_tbs_set_signature_algorithm;
+};
+
diff --git a/third_party/heimdal/lib/ipc/Makefile.am b/third_party/heimdal/lib/ipc/Makefile.am
new file mode 100644
index 0000000..6915175
--- /dev/null
+++ b/third_party/heimdal/lib/ipc/Makefile.am
@@ -0,0 +1,72 @@
+include $(top_srcdir)/Makefile.am.common
+
+noinst_LTLIBRARIES = libheim-ipcc.la libheim-ipcs.la
+
+dist_libheim_ipcc_la_SOURCES = hi_locl.h heim_ipc_types.h client.c common.c
+dist_libheim_ipcs_la_SOURCES = hi_locl.h heim_ipc_types.h server.c common.c
+
+include_HEADERS = heim-ipc.h
+
+##
+## Enable when this is not a noinst_ library
+##
+#libheim_ipcc_la_LDFLAGS = -version-info 0:0:0
+#libheim_ipcs_la_LDFLAGS = -version-info 0:0:0
+#
+#if versionscript
+#libheim_ipcc_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-scriptc.map
+#libheim_ipcs_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-scripts.map
+#endif
+
+libheim_ipcc_la_LIBADD = \
+ $(LIB_heimbase) \
+ $(LIB_roken) \
+ $(PTHREAD_LIBADD)
+
+libheim_ipcs_la_LIBADD = $(libheim_ipcc_la_LIBADD)
+
+TESTS = $(check_PROGRAMS)
+
+noinst_PROGRAMS = tc ts ts-http
+
+ts_LDADD = libheim-ipcs.la $(LIB_roken)
+ts_http_LDADD = $(ts_LDADD)
+tc_LDADD = libheim-ipcc.la $(LIB_roken)
+
+
+EXTRA_DIST = heim_ipc.defs heim_ipc_async.defs heim_ipc_reply.defs
+
+if have_gcd
+
+# We still use dispatch_get_current_queue(), which is deprecated, and that
+# stops building on recent OS X releases unless we disable this warning.
+WFLAGS += -Wno-deprecated-declarations
+
+heim_ipc.h heim_ipcUser.c heim_ipcServer.c heim_ipcServer.h: heim_ipc.defs
+ mig -header heim_ipc.h -user heim_ipcUser.c -sheader heim_ipcServer.h -server heim_ipcServer.c -I$(srcdir) $(srcdir)/heim_ipc.defs
+
+heim_ipc_async.h heim_ipc_asyncUser.c heim_ipc_asyncServer.c heim_ipc_asyncServer.h: heim_ipc_async.defs
+ mig -header heim_ipc_async.h -user heim_ipc_asyncUser.c -sheader heim_ipc_asyncServer.h -server heim_ipc_asyncServer.c -I$(srcdir) $(srcdir)/heim_ipc_async.defs
+
+heim_ipc_reply.h heim_ipc_replyUser.c: heim_ipc_reply.defs
+ mig -header heim_ipc_reply.h -user heim_ipc_replyUser.c -sheader /dev/null -server /dev/null -I$(srcdir) $(srcdir)/heim_ipc_reply.defs
+
+built_ipcc = heim_ipc.h heim_ipcUser.c
+built_ipcc += heim_ipc_asyncServer.c heim_ipc_asyncServer.h
+
+nodist_libheim_ipcc_la_SOURCES = $(built_ipcc)
+
+built_ipcs = heim_ipcServer.c heim_ipcServer.h
+built_ipcs += heim_ipc_asyncUser.c heim_ipc_async.h
+built_ipcs += heim_ipc_reply.h heim_ipc_replyUser.c
+
+nodist_libheim_ipcs_la_SOURCES = $(built_ipcs)
+
+libheim_ipcs_la_LIBADD += -lbsm
+
+CLEANFILES = $(built_ipcc) $(built_ipcs)
+
+$(srcdir)/client.c: $(built_ipcc)
+$(srcdir)/server.c: $(built_ipcs)
+
+endif
diff --git a/third_party/heimdal/lib/ipc/client.c b/third_party/heimdal/lib/ipc/client.c
new file mode 100644
index 0000000..39e1b49
--- /dev/null
+++ b/third_party/heimdal/lib/ipc/client.c
@@ -0,0 +1,610 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hi_locl.h"
+
+#if defined(__APPLE__) && defined(HAVE_GCD)
+
+#include "heim_ipc.h"
+#include "heim_ipc_asyncServer.h"
+
+#include <dispatch/dispatch.h>
+#include <mach/mach.h>
+
+static dispatch_once_t jobqinited = 0;
+static dispatch_queue_t jobq = NULL;
+static dispatch_queue_t syncq;
+
+struct mach_ctx {
+ mach_port_t server;
+ char *name;
+};
+
+static int
+mach_release(void *ctx);
+
+static int
+mach_init(const char *service, void **ctx)
+{
+ struct mach_ctx *ipc;
+ mach_port_t sport;
+ int ret;
+
+ dispatch_once(&jobqinited, ^{
+ jobq = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
+ syncq = dispatch_queue_create("heim-ipc-syncq", NULL);
+ });
+
+ ret = bootstrap_look_up(bootstrap_port, service, &sport);
+ if (ret)
+ return ret;
+
+ ipc = malloc(sizeof(*ipc));
+ if (ipc == NULL) {
+ mach_port_destroy(mach_task_self(), sport);
+ return ENOMEM;
+ }
+
+ ipc->server = sport;
+ ipc->name = strdup(service);
+ if (ipc->name == NULL) {
+ mach_release(ipc);
+ return ENOMEM;
+ }
+
+ *ctx = ipc;
+
+ return 0;
+}
+
+static int
+mach_ipc(void *ctx,
+ const heim_idata *request, heim_idata *response,
+ heim_icred *cred)
+{
+ struct mach_ctx *ipc = ctx;
+ heim_ipc_message_inband_t requestin;
+ mach_msg_type_number_t requestin_length = 0;
+ heim_ipc_message_outband_t requestout = NULL;
+ mach_msg_type_number_t requestout_length = 0;
+ heim_ipc_message_inband_t replyin;
+ mach_msg_type_number_t replyin_length;
+ heim_ipc_message_outband_t replyout;
+ mach_msg_type_number_t replyout_length;
+ int ret, errorcode, retries = 0;
+
+ memcpy(requestin, request->data, request->length);
+ requestin_length = request->length;
+
+ while (retries < 2) {
+ __block mach_port_t sport;
+
+ dispatch_sync(syncq, ^{ sport = ipc->server; });
+
+ ret = mheim_ipc_call(sport,
+ requestin, requestin_length,
+ requestout, requestout_length,
+ &errorcode,
+ replyin, &replyin_length,
+ &replyout, &replyout_length);
+ if (ret == MACH_SEND_INVALID_DEST) {
+ mach_port_t nport;
+ /* race other threads to get a new port */
+ ret = bootstrap_look_up(bootstrap_port, ipc->name, &nport);
+ if (ret)
+ return ret;
+ dispatch_sync(syncq, ^{
+ /* check if we lost the race to lookup the port */
+ if (sport != ipc->server) {
+ mach_port_deallocate(mach_task_self(), nport);
+ } else {
+ mach_port_deallocate(mach_task_self(), ipc->server);
+ ipc->server = nport;
+ }
+ });
+ retries++;
+ } else if (ret) {
+ return ret;
+ } else
+ break;
+ }
+ if (retries >= 2)
+ return EINVAL;
+
+ if (errorcode) {
+ if (replyout_length)
+ vm_deallocate (mach_task_self (), (vm_address_t) replyout,
+ replyout_length);
+ return errorcode;
+ }
+
+ if (replyout_length) {
+ response->data = malloc(replyout_length);
+ if (response->data == NULL) {
+ vm_deallocate (mach_task_self (), (vm_address_t) replyout,
+ replyout_length);
+ return ENOMEM;
+ }
+ memcpy(response->data, replyout, replyout_length);
+ response->length = replyout_length;
+ vm_deallocate (mach_task_self (), (vm_address_t) replyout,
+ replyout_length);
+ } else {
+ response->data = malloc(replyin_length);
+ if (response->data == NULL)
+ return ENOMEM;
+ memcpy(response->data, replyin, replyin_length);
+ response->length = replyin_length;
+ }
+
+ return 0;
+}
+
+struct async_client {
+ mach_port_t mp;
+ dispatch_source_t source;
+ dispatch_queue_t queue;
+ void (*func)(void *, int, heim_idata *, heim_icred);
+ void *userctx;
+};
+
+kern_return_t
+mheim_ado_acall_reply(mach_port_t server_port,
+ audit_token_t client_creds,
+ int returnvalue,
+ heim_ipc_message_inband_t replyin,
+ mach_msg_type_number_t replyinCnt,
+ heim_ipc_message_outband_t replyout,
+ mach_msg_type_number_t replyoutCnt)
+{
+ struct async_client *c = dispatch_get_context(dispatch_get_current_queue());
+ heim_idata response;
+
+ if (returnvalue) {
+ response.data = NULL;
+ response.length = 0;
+ } else if (replyoutCnt) {
+ response.data = replyout;
+ response.length = replyoutCnt;
+ } else {
+ response.data = replyin;
+ response.length = replyinCnt;
+ }
+
+ (*c->func)(c->userctx, returnvalue, &response, NULL);
+
+ if (replyoutCnt)
+ vm_deallocate (mach_task_self (), (vm_address_t) replyout, replyoutCnt);
+
+ dispatch_source_cancel(c->source);
+
+ return 0;
+
+
+}
+
+
+static int
+mach_async(void *ctx, const heim_idata *request, void *userctx,
+ void (*func)(void *, int, heim_idata *, heim_icred))
+{
+ struct mach_ctx *ipc = ctx;
+ heim_ipc_message_inband_t requestin;
+ mach_msg_type_number_t requestin_length = 0;
+ heim_ipc_message_outband_t requestout = NULL;
+ mach_msg_type_number_t requestout_length = 0;
+ int ret, retries = 0;
+ kern_return_t kr;
+ struct async_client *c;
+
+ /* first create the service that will catch the reply from the server */
+ /* XXX these object should be cached and reused */
+
+ c = malloc(sizeof(*c));
+ if (c == NULL)
+ return ENOMEM;
+
+ kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &c->mp);
+ if (kr != KERN_SUCCESS)
+ return EINVAL;
+
+ c->queue = dispatch_queue_create("heim-ipc-async-client", NULL);
+ c->source = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, c->mp, 0, c->queue);
+ dispatch_set_context(c->queue, c);
+
+ dispatch_source_set_event_handler(c->source, ^{
+ dispatch_mig_server(c->source,
+ sizeof(union __RequestUnion__mheim_ado_mheim_aipc_subsystem),
+ mheim_aipc_server);
+ });
+
+ dispatch_source_set_cancel_handler(c->source, ^{
+ mach_port_mod_refs(mach_task_self(), c->mp,
+ MACH_PORT_RIGHT_RECEIVE, -1);
+ dispatch_release(c->queue);
+ dispatch_release(c->source);
+ free(c);
+ });
+
+ c->func = func;
+ c->userctx = userctx;
+
+ dispatch_resume(c->source);
+
+ /* ok, send the message */
+
+ memcpy(requestin, request->data, request->length);
+ requestin_length = request->length;
+
+ while (retries < 2) {
+ __block mach_port_t sport;
+
+ dispatch_sync(syncq, ^{ sport = ipc->server; });
+
+ ret = mheim_ipc_call_request(sport, c->mp,
+ requestin, requestin_length,
+ requestout, requestout_length);
+ if (ret == MACH_SEND_INVALID_DEST) {
+ ret = bootstrap_look_up(bootstrap_port, ipc->name, &sport);
+ if (ret) {
+ dispatch_source_cancel(c->source);
+ return ret;
+ }
+ mach_port_deallocate(mach_task_self(), ipc->server);
+ ipc->server = sport;
+ retries++;
+ } else if (ret) {
+ dispatch_source_cancel(c->source);
+ return ret;
+ } else
+ break;
+ }
+ if (retries >= 2) {
+ dispatch_source_cancel(c->source);
+ return EINVAL;
+ }
+
+ return 0;
+}
+
+static int
+mach_release(void *ctx)
+{
+ struct mach_ctx *ipc = ctx;
+ if (ipc->server != MACH_PORT_NULL)
+ mach_port_deallocate(mach_task_self(), ipc->server);
+ free(ipc->name);
+ free(ipc);
+ return 0;
+}
+
+#endif
+
+struct path_ctx {
+ char *path;
+ int fd;
+};
+
+static int common_release(void *);
+
+static int
+connect_unix(struct path_ctx *s)
+{
+ struct sockaddr_un addr;
+
+ addr.sun_family = AF_UNIX;
+ strlcpy(addr.sun_path, s->path, sizeof(addr.sun_path));
+
+ s->fd = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (s->fd < 0)
+ return errno;
+ rk_cloexec(s->fd);
+
+ if (connect(s->fd, (struct sockaddr *)&addr, sizeof(addr)) != 0)
+ return errno;
+
+ return 0;
+}
+
+static int
+common_path_init(const char *base,
+ const char *service,
+ const char *file,
+ void **ctx)
+{
+ struct path_ctx *s;
+
+ s = malloc(sizeof(*s));
+ if (s == NULL)
+ return ENOMEM;
+ s->fd = -1;
+
+ if (asprintf(&s->path, "%s/.heim_%s-%s", base, service, file) == -1) {
+ free(s);
+ return ENOMEM;
+ }
+
+ *ctx = s;
+ return 0;
+}
+
+static int
+unix_socket_init(const char *service,
+ void **ctx)
+{
+ const char *base = secure_getenv("HEIM_IPC_DIR");
+ int ret;
+
+ ret = common_path_init(base ? base : _PATH_VARRUN, service, "socket", ctx);
+ if (ret)
+ return ret;
+ ret = connect_unix(*ctx);
+ if (ret)
+ common_release(*ctx);
+
+ return ret;
+}
+
+static int
+unix_socket_ipc(void *ctx,
+ const heim_idata *req, heim_idata *rep,
+ heim_icred *cred)
+{
+ struct path_ctx *s = ctx;
+ uint32_t len = htonl(req->length);
+ uint32_t rv;
+ int retval;
+
+ if (cred)
+ *cred = NULL;
+
+ rep->data = NULL;
+ rep->length = 0;
+
+ if (net_write(s->fd, &len, sizeof(len)) != sizeof(len))
+ return -1;
+ if (net_write(s->fd, req->data, req->length) != (ssize_t)req->length)
+ return -1;
+
+ if (net_read(s->fd, &len, sizeof(len)) != sizeof(len))
+ return -1;
+ if (net_read(s->fd, &rv, sizeof(rv)) != sizeof(rv))
+ return -1;
+ retval = ntohl(rv);
+
+ rep->length = ntohl(len);
+ if (rep->length > 0) {
+ rep->data = malloc(rep->length);
+ if (rep->data == NULL)
+ return -1;
+ if (net_read(s->fd, rep->data, rep->length) != (ssize_t)rep->length)
+ return -1;
+ } else
+ rep->data = NULL;
+
+ return retval;
+}
+
+int
+common_release(void *ctx)
+{
+ struct path_ctx *s = ctx;
+ if (s->fd >= 0)
+ close(s->fd);
+ free(s->path);
+ free(s);
+ return 0;
+}
+
+#ifdef HAVE_DOOR_CREATE
+
+#include <door.h>
+
+#ifdef HAVE_SYS_MMAN_H
+#include <sys/mman.h>
+#endif
+
+static int
+door_init(const char *service,
+ void **ctx)
+{
+ const char *base = secure_getenv("HEIM_IPC_DIR");
+ int ret;
+ struct path_ctx *d;
+
+ ret = common_path_init(base ? base : _PATH_VARRUN, service, "door", ctx);
+ if (ret)
+ return ret;
+
+ d = (struct path_ctx *)*ctx;
+ d->fd = open(d->path, O_RDWR);
+ if (d->fd < 0) {
+ ret = errno;
+ common_release(*ctx);
+ return ret;
+ }
+
+ return 0;
+}
+
+struct door_reply {
+ int returnvalue;
+ size_t length;
+ unsigned char data[1];
+};
+
+static int
+door_ipc(void *ctx,
+ const heim_idata *request, heim_idata *response,
+ heim_icred *cred)
+{
+ struct path_ctx *d = (struct path_ctx *)ctx;
+ door_arg_t arg;
+ int ret;
+ struct door_reply *r;
+
+ arg.data_ptr = request->data;
+ arg.data_size = request->length;
+ arg.desc_ptr = NULL;
+ arg.desc_num = 0;
+ arg.rbuf = NULL;
+ arg.rsize = 0;
+
+ ret = door_call(d->fd, &arg);
+ if (ret != 0)
+ return errno;
+
+ if (arg.rsize < offsetof(struct door_reply, data))
+ return EINVAL;
+
+ r = (struct door_reply *)arg.rbuf;
+ if (r->returnvalue != 0)
+ return r->returnvalue;
+
+ if (arg.rsize < offsetof(struct door_reply, data) + r->length)
+ return ERANGE;
+
+ response->data = malloc(r->length);
+ if (response->data == NULL) {
+ munmap(arg.rbuf, arg.rsize);
+ return ENOMEM;
+ }
+
+ memcpy(response->data, r->data, r->length);
+ response->length = r->length;
+ munmap(arg.rbuf, arg.rsize);
+
+ return 0;
+}
+
+#endif /* HAVE_DOOR_CREATE */
+
+struct hipc_ops {
+ const char *prefix;
+ int (*init)(const char *, void **);
+ int (*release)(void *);
+ int (*ipc)(void *,const heim_idata *, heim_idata *, heim_icred *);
+ int (*async)(void *, const heim_idata *, void *,
+ void (*)(void *, int, heim_idata *, heim_icred));
+};
+
+struct hipc_ops ipcs[] = {
+#if defined(__APPLE__) && defined(HAVE_GCD)
+ { "MACH", mach_init, mach_release, mach_ipc, mach_async },
+#endif
+#ifdef HAVE_DOOR_CREATE
+ { "DOOR", door_init, common_release, door_ipc, NULL },
+#endif
+ { "UNIX", unix_socket_init, common_release, unix_socket_ipc, NULL }
+};
+
+struct heim_ipc {
+ struct hipc_ops *ops;
+ void *ctx;
+};
+
+
+int
+heim_ipc_init_context(const char *name, heim_ipc *ctx)
+{
+ unsigned int i;
+ int ret, any = 0;
+
+ for(i = 0; i < sizeof(ipcs)/sizeof(ipcs[0]); i++) {
+ size_t prefix_len = strlen(ipcs[i].prefix);
+ heim_ipc c;
+ if(strncmp(ipcs[i].prefix, name, prefix_len) == 0
+ && name[prefix_len] == ':') {
+ } else if (strncmp("ANY:", name, 4) == 0) {
+ prefix_len = 3;
+ any = 1;
+ } else
+ continue;
+
+ c = calloc(1, sizeof(*c));
+ if (c == NULL)
+ return ENOMEM;
+
+ c->ops = &ipcs[i];
+
+ ret = (c->ops->init)(name + prefix_len + 1, &c->ctx);
+ if (ret) {
+ free(c);
+ if (any)
+ continue;
+ return ret;
+ }
+
+ *ctx = c;
+ return 0;
+ }
+
+ return ENOENT;
+}
+
+void
+heim_ipc_free_context(heim_ipc ctx)
+{
+ (ctx->ops->release)(ctx->ctx);
+ free(ctx);
+}
+
+int
+heim_ipc_call(heim_ipc ctx, const heim_idata *snd, heim_idata *rcv,
+ heim_icred *cred)
+{
+ if (cred)
+ *cred = NULL;
+ return (ctx->ops->ipc)(ctx->ctx, snd, rcv, cred);
+}
+
+int
+heim_ipc_async(heim_ipc ctx, const heim_idata *snd, void *userctx,
+ void (*func)(void *, int, heim_idata *, heim_icred))
+{
+ if (ctx->ops->async == NULL) {
+ heim_idata rcv;
+ heim_icred cred = NULL;
+ int ret;
+
+ ret = (ctx->ops->ipc)(ctx->ctx, snd, &rcv, &cred);
+ (*func)(userctx, ret, &rcv, cred);
+ heim_ipc_free_cred(cred);
+ free(rcv.data);
+ return ret;
+ } else {
+ return (ctx->ops->async)(ctx->ctx, snd, userctx, func);
+ }
+}
diff --git a/third_party/heimdal/lib/ipc/common.c b/third_party/heimdal/lib/ipc/common.c
new file mode 100644
index 0000000..cfbe4b5
--- /dev/null
+++ b/third_party/heimdal/lib/ipc/common.c
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hi_locl.h"
+#ifdef HAVE_GCD
+#include <dispatch/dispatch.h>
+#else
+#include "heim_threads.h"
+#endif
+
+struct heim_icred {
+ uid_t uid;
+ gid_t gid;
+ pid_t pid;
+ pid_t session;
+};
+
+void
+heim_ipc_free_cred(heim_icred cred)
+{
+ free(cred);
+}
+
+uid_t
+heim_ipc_cred_get_uid(heim_icred cred)
+{
+ return cred ? cred->uid : (uid_t)-1;
+}
+
+gid_t
+heim_ipc_cred_get_gid(heim_icred cred)
+{
+ return cred ? cred->gid : (gid_t)-1;
+}
+
+pid_t
+heim_ipc_cred_get_pid(heim_icred cred)
+{
+ return cred ? cred->pid : (pid_t)0;
+}
+
+pid_t
+heim_ipc_cred_get_session(heim_icred cred)
+{
+ return cred ? cred->session : (pid_t)-1;
+}
+
+
+int
+_heim_ipc_create_cred(uid_t uid, gid_t gid, pid_t pid, pid_t session, heim_icred *cred)
+{
+ *cred = calloc(1, sizeof(**cred));
+ if (*cred == NULL)
+ return ENOMEM;
+ (*cred)->uid = uid;
+ (*cred)->gid = gid;
+ (*cred)->pid = pid;
+ (*cred)->session = session;
+ return 0;
+}
+
+#ifndef HAVE_GCD
+struct heim_isemaphore {
+ HEIMDAL_MUTEX mutex;
+#ifdef ENABLE_PTHREAD_SUPPORT
+ pthread_cond_t cond;
+#endif
+ long counter;
+};
+#endif
+
+heim_isemaphore
+heim_ipc_semaphore_create(long value)
+{
+#ifdef HAVE_GCD
+ return (heim_isemaphore)dispatch_semaphore_create(value);
+#elif !defined(ENABLE_PTHREAD_SUPPORT)
+ heim_assert(0, "no semaphore support w/o pthreads");
+ return NULL;
+#else
+ heim_isemaphore s = malloc(sizeof(*s));
+ if (s == NULL)
+ return NULL;
+ HEIMDAL_MUTEX_init(&s->mutex);
+ pthread_cond_init(&s->cond, NULL);
+ s->counter = value;
+ return s;
+#endif
+}
+
+long
+heim_ipc_semaphore_wait(heim_isemaphore s, time_t t)
+{
+#ifdef HAVE_GCD
+ uint64_t timeout;
+ if (t == HEIM_IPC_WAIT_FOREVER)
+ timeout = DISPATCH_TIME_FOREVER;
+ else
+ timeout = (uint64_t)t * NSEC_PER_SEC;
+
+ return dispatch_semaphore_wait((dispatch_semaphore_t)s, timeout);
+#elif !defined(ENABLE_PTHREAD_SUPPORT)
+ heim_assert(0, "no semaphore support w/o pthreads");
+ return 0;
+#else
+ HEIMDAL_MUTEX_lock(&s->mutex);
+ /* if counter hits below zero, we get to wait */
+ if (--s->counter < 0) {
+ int ret;
+
+ if (t == HEIM_IPC_WAIT_FOREVER)
+ ret = pthread_cond_wait(&s->cond, &s->mutex);
+ else {
+ struct timespec ts;
+ ts.tv_sec = t;
+ ts.tv_nsec = 0;
+ ret = pthread_cond_timedwait(&s->cond, &s->mutex, &ts);
+ }
+ if (ret) {
+ HEIMDAL_MUTEX_unlock(&s->mutex);
+ return errno;
+ }
+ }
+ HEIMDAL_MUTEX_unlock(&s->mutex);
+
+ return 0;
+#endif
+}
+
+long
+heim_ipc_semaphore_signal(heim_isemaphore s)
+{
+#ifdef HAVE_GCD
+ return dispatch_semaphore_signal((dispatch_semaphore_t)s);
+#elif !defined(ENABLE_PTHREAD_SUPPORT)
+ heim_assert(0, "no semaphore support w/o pthreads");
+ return EINVAL;
+#else
+ int wakeup;
+ HEIMDAL_MUTEX_lock(&s->mutex);
+ wakeup = (++s->counter == 0) ;
+ HEIMDAL_MUTEX_unlock(&s->mutex);
+ if (wakeup)
+ pthread_cond_signal(&s->cond);
+ return 0;
+#endif
+}
+
+void
+heim_ipc_semaphore_release(heim_isemaphore s)
+{
+#ifdef HAVE_GCD
+ dispatch_release((dispatch_semaphore_t)s);
+#elif !defined(ENABLE_PTHREAD_SUPPORT)
+ heim_assert(0, "no semaphore support w/o pthreads");
+#else
+ HEIMDAL_MUTEX_lock(&s->mutex);
+ if (s->counter != 0)
+ abort();
+ HEIMDAL_MUTEX_unlock(&s->mutex);
+ HEIMDAL_MUTEX_destroy(&s->mutex);
+ pthread_cond_destroy(&s->cond);
+ free(s);
+#endif
+}
+
+void
+heim_ipc_free_data(heim_idata *data)
+{
+ if (data->data)
+ free(data->data);
+ data->data = NULL;
+ data->length = 0;
+}
diff --git a/third_party/heimdal/lib/ipc/heim-ipc.h b/third_party/heimdal/lib/ipc/heim-ipc.h
new file mode 100644
index 0000000..a34e338
--- /dev/null
+++ b/third_party/heimdal/lib/ipc/heim-ipc.h
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <asn1-common.h>
+
+typedef struct heim_ipc *heim_ipc;
+typedef struct heim_sipc *heim_sipc;
+typedef struct heim_icred *heim_icred;
+typedef struct heim_isemaphore *heim_isemaphore;
+typedef struct heim_base_data heim_idata;
+typedef struct heim_sipc_call *heim_sipc_call;
+
+/* common */
+
+void
+heim_ipc_free_cred(heim_icred);
+
+uid_t
+heim_ipc_cred_get_uid(heim_icred);
+
+gid_t
+heim_ipc_cred_get_gid(heim_icred);
+
+pid_t
+heim_ipc_cred_get_pid(heim_icred);
+
+pid_t
+heim_ipc_cred_get_session(heim_icred);
+
+void
+heim_ipc_main(void);
+
+heim_isemaphore
+heim_ipc_semaphore_create(long);
+
+long
+heim_ipc_semaphore_wait(heim_isemaphore, time_t);
+
+long
+heim_ipc_semaphore_signal(heim_isemaphore);
+
+void
+heim_ipc_semaphore_release(heim_isemaphore);
+
+#define HEIM_IPC_WAIT_FOREVER ((time_t)-1)
+
+void
+heim_ipc_free_data(heim_idata *);
+
+/* client */
+
+int
+heim_ipc_init_context(const char *, heim_ipc *);
+
+void
+heim_ipc_free_context(heim_ipc);
+
+int
+heim_ipc_call(heim_ipc, const heim_idata *, heim_idata *, heim_icred *);
+
+int
+heim_ipc_async(heim_ipc, const heim_idata *, void *, void (*func)(void *, int, heim_idata *, heim_icred));
+
+/* server */
+
+#define HEIM_SIPC_TYPE_IPC 1
+#define HEIM_SIPC_TYPE_UINT32 2
+#define HEIM_SIPC_TYPE_HTTP 4
+
+typedef void
+(*heim_ipc_complete)(heim_sipc_call, int, heim_idata *);
+
+typedef void
+(*heim_ipc_callback)(void *, const heim_idata *,
+ const heim_icred, heim_ipc_complete, heim_sipc_call);
+
+
+int
+heim_sipc_launchd_mach_init(const char *, heim_ipc_callback,
+ void *, heim_sipc *);
+
+int
+heim_sipc_stream_listener(int, int, heim_ipc_callback,
+ void *, heim_sipc *);
+
+int
+heim_sipc_service_unix(const char *, heim_ipc_callback,
+ void *, heim_sipc *);
+
+int
+heim_sipc_service_door(const char *, heim_ipc_callback,
+ void *, heim_sipc *);
+
+void
+heim_sipc_timeout(time_t);
+
+void
+heim_sipc_set_timeout_handler(void (*)(void));
+
+void
+heim_sipc_free_context(heim_sipc);
diff --git a/third_party/heimdal/lib/ipc/heim_ipc.defs b/third_party/heimdal/lib/ipc/heim_ipc.defs
new file mode 100644
index 0000000..d2af7ec
--- /dev/null
+++ b/third_party/heimdal/lib/ipc/heim_ipc.defs
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <mach/std_types.defs>
+#include <mach/mach_types.defs>
+
+type heim_ipc_message_inband_t = array [ * : 2048 ] of char;
+type heim_ipc_message_outband_t = array [] of char;
+
+import "heim_ipc_types.h";
+
+subsystem mheim_ipc 1;
+userprefix mheim_ipc_;
+serverprefix mheim_do_;
+
+routine call(
+ server_port : mach_port_t;
+ ServerAuditToken client_creds : audit_token_t;
+ sreplyport reply_port : mach_port_make_send_once_t;
+ in requestin : heim_ipc_message_inband_t;
+ in requestout : heim_ipc_message_outband_t;
+ out returnvalue : int;
+ out replyin : heim_ipc_message_inband_t;
+ out replyout : heim_ipc_message_outband_t, dealloc);
+
+simpleroutine call_request(
+ server_port : mach_port_t;
+ ServerAuditToken client_creds : audit_token_t;
+ in reply_to : mach_port_make_send_once_t;
+ in requestin : heim_ipc_message_inband_t;
+ in requestout : heim_ipc_message_outband_t);
+
+
+
diff --git a/third_party/heimdal/lib/ipc/heim_ipc_async.defs b/third_party/heimdal/lib/ipc/heim_ipc_async.defs
new file mode 100644
index 0000000..406e6a2
--- /dev/null
+++ b/third_party/heimdal/lib/ipc/heim_ipc_async.defs
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <mach/std_types.defs>
+#include <mach/mach_types.defs>
+
+type heim_ipc_message_inband_t = array [ * : 2048 ] of char;
+type heim_ipc_message_outband_t = array [] of char;
+
+import "heim_ipc_types.h";
+
+subsystem mheim_aipc 201;
+userprefix mheim_aipc_;
+serverprefix mheim_ado_;
+
+simpleroutine acall_reply(
+ server_port : mach_port_move_send_once_t;
+ ServerAuditToken client_creds : audit_token_t;
+ in returnvalue : int;
+ in requestin : heim_ipc_message_inband_t;
+ in requestout : heim_ipc_message_outband_t);
+
+
+
diff --git a/third_party/heimdal/lib/ipc/heim_ipc_reply.defs b/third_party/heimdal/lib/ipc/heim_ipc_reply.defs
new file mode 100644
index 0000000..f95d0fa
--- /dev/null
+++ b/third_party/heimdal/lib/ipc/heim_ipc_reply.defs
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <mach/std_types.defs>
+#include <mach/mach_types.defs>
+
+type heim_ipc_message_inband_t = array [ * : 2048 ] of char;
+type heim_ipc_message_outband_t = array [] of char;
+
+import "heim_ipc_types.h";
+
+subsystem heim_ipc 101;
+userprefix mheim_ripc_;
+
+simpleroutine call_reply(
+ reply_port : mach_port_move_send_once_t;
+ returnvalue : int;
+ replyin : heim_ipc_message_inband_t;
+ replyout : heim_ipc_message_outband_t, dealloc);
diff --git a/third_party/heimdal/lib/ipc/heim_ipc_types.h b/third_party/heimdal/lib/ipc/heim_ipc_types.h
new file mode 100644
index 0000000..fb5c165
--- /dev/null
+++ b/third_party/heimdal/lib/ipc/heim_ipc_types.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef _HEIM_IPC_TYPES_H_
+#define _HEIM_IPC_TYPES_H_
+
+#define HEIM_KCM_BOOTSTRAP_NAME "org.h5l.Kerberos.kcm"
+
+typedef char heim_ipc_message_inband_t[2048];
+typedef char *heim_ipc_message_outband_t;
+
+#endif
diff --git a/third_party/heimdal/lib/ipc/hi_locl.h b/third_party/heimdal/lib/ipc/hi_locl.h
new file mode 100644
index 0000000..6ec28ff
--- /dev/null
+++ b/third_party/heimdal/lib/ipc/hi_locl.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#ifdef HAVE_SYS_UN_H
+#include <sys/un.h>
+#endif
+
+#include <sys/poll.h>
+
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#ifdef HAVE_GETPEERUCRED
+#include <ucred.h>
+#endif
+
+#include <krb5-types.h>
+#include <asn1-common.h>
+
+#include <heimbase.h>
+#include <base64.h>
+
+#include <heim-ipc.h>
+
+#if defined(__APPLE__) && defined(HAVE_GCD)
+#include <mach/mach.h>
+#include <servers/bootstrap.h>
+#include <dispatch/dispatch.h>
+#include <bsm/libbsm.h>
+
+#ifndef __APPLE_PRIVATE__ /* awe, using private interface */
+typedef boolean_t (*dispatch_mig_callback_t)(mach_msg_header_t *message, mach_msg_header_t *reply);
+
+mach_msg_return_t
+dispatch_mig_server(dispatch_source_t ds, size_t maxmsgsz, dispatch_mig_callback_t callback);
+#endif
+
+#endif
+
+
+#include <roken.h>
+
+int
+_heim_ipc_create_cred(uid_t, gid_t, pid_t, pid_t, heim_icred *);
diff --git a/third_party/heimdal/lib/ipc/server.c b/third_party/heimdal/lib/ipc/server.c
new file mode 100644
index 0000000..40601b9
--- /dev/null
+++ b/third_party/heimdal/lib/ipc/server.c
@@ -0,0 +1,1385 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "hi_locl.h"
+#include <assert.h>
+#include <err.h>
+
+#define MAX_PACKET_SIZE (128 * 1024)
+
+struct heim_sipc {
+ int (*release)(heim_sipc ctx);
+ heim_ipc_callback callback;
+ void *userctx;
+ void *mech;
+};
+
+#if defined(__APPLE__) && defined(HAVE_GCD)
+
+#include "heim_ipcServer.h"
+#include "heim_ipc_reply.h"
+#include "heim_ipc_async.h"
+
+static dispatch_source_t timer;
+static dispatch_queue_t timerq;
+static uint64_t timeoutvalue;
+
+static dispatch_queue_t eventq;
+
+static dispatch_queue_t workq;
+
+static void
+default_timer_ev(void)
+{
+ exit(0);
+}
+
+static void (*timer_ev)(void) = default_timer_ev;
+
+static void
+set_timer(void)
+{
+ dispatch_source_set_timer(timer,
+ dispatch_time(DISPATCH_TIME_NOW,
+ timeoutvalue * NSEC_PER_SEC),
+ timeoutvalue * NSEC_PER_SEC, 1000000);
+}
+
+static void
+init_globals(void)
+{
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ timerq = dispatch_queue_create("hiem-sipc-timer-q", NULL);
+ timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timerq);
+ dispatch_source_set_event_handler(timer, ^{ timer_ev(); } );
+
+ workq = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
+ eventq = dispatch_queue_create("heim-ipc.event-queue", NULL);
+ });
+}
+
+static void
+suspend_timer(void)
+{
+ dispatch_suspend(timer);
+}
+
+static void
+restart_timer(void)
+{
+ dispatch_sync(timerq, ^{ set_timer(); });
+ dispatch_resume(timer);
+}
+
+struct mach_service {
+ mach_port_t sport;
+ dispatch_source_t source;
+ dispatch_queue_t queue;
+};
+
+struct mach_call_ctx {
+ mach_port_t reply_port;
+ heim_icred cred;
+ heim_idata req;
+};
+
+
+static void
+mach_complete_sync(heim_sipc_call ctx, int returnvalue, heim_idata *reply)
+{
+ struct mach_call_ctx *s = (struct mach_call_ctx *)ctx;
+ heim_ipc_message_inband_t replyin;
+ mach_msg_type_number_t replyinCnt;
+ heim_ipc_message_outband_t replyout;
+ mach_msg_type_number_t replyoutCnt;
+ kern_return_t kr;
+
+ if (returnvalue) {
+ /* on error, no reply */
+ replyinCnt = 0;
+ replyout = 0; replyoutCnt = 0;
+ kr = KERN_SUCCESS;
+ } else if (reply->length < 2048) {
+ replyinCnt = reply->length;
+ memcpy(replyin, reply->data, replyinCnt);
+ replyout = 0; replyoutCnt = 0;
+ kr = KERN_SUCCESS;
+ } else {
+ replyinCnt = 0;
+ kr = vm_read(mach_task_self(),
+ (vm_address_t)reply->data, reply->length,
+ (vm_address_t *)&replyout, &replyoutCnt);
+ }
+
+ mheim_ripc_call_reply(s->reply_port, returnvalue,
+ replyin, replyinCnt,
+ replyout, replyoutCnt);
+
+ heim_ipc_free_cred(s->cred);
+ free(s->req.data);
+ free(s);
+ restart_timer();
+}
+
+static void
+mach_complete_async(heim_sipc_call ctx, int returnvalue, heim_idata *reply)
+{
+ struct mach_call_ctx *s = (struct mach_call_ctx *)ctx;
+ heim_ipc_message_inband_t replyin;
+ mach_msg_type_number_t replyinCnt;
+ heim_ipc_message_outband_t replyout;
+ mach_msg_type_number_t replyoutCnt;
+ kern_return_t kr;
+
+ if (returnvalue) {
+ /* on error, no reply */
+ replyinCnt = 0;
+ replyout = 0; replyoutCnt = 0;
+ kr = KERN_SUCCESS;
+ } else if (reply->length < 2048) {
+ replyinCnt = reply->length;
+ memcpy(replyin, reply->data, replyinCnt);
+ replyout = 0; replyoutCnt = 0;
+ kr = KERN_SUCCESS;
+ } else {
+ replyinCnt = 0;
+ kr = vm_read(mach_task_self(),
+ (vm_address_t)reply->data, reply->length,
+ (vm_address_t *)&replyout, &replyoutCnt);
+ }
+
+ kr = mheim_aipc_acall_reply(s->reply_port, returnvalue,
+ replyin, replyinCnt,
+ replyout, replyoutCnt);
+ heim_ipc_free_cred(s->cred);
+ free(s->req.data);
+ free(s);
+ restart_timer();
+}
+
+
+kern_return_t
+mheim_do_call(mach_port_t server_port,
+ audit_token_t client_creds,
+ mach_port_t reply_port,
+ heim_ipc_message_inband_t requestin,
+ mach_msg_type_number_t requestinCnt,
+ heim_ipc_message_outband_t requestout,
+ mach_msg_type_number_t requestoutCnt,
+ int *returnvalue,
+ heim_ipc_message_inband_t replyin,
+ mach_msg_type_number_t *replyinCnt,
+ heim_ipc_message_outband_t *replyout,
+ mach_msg_type_number_t *replyoutCnt)
+{
+ heim_sipc ctx = dispatch_get_context(dispatch_get_current_queue());
+ struct mach_call_ctx *s;
+ kern_return_t kr;
+ uid_t uid;
+ gid_t gid;
+ pid_t pid;
+ au_asid_t session;
+
+ *replyout = NULL;
+ *replyoutCnt = 0;
+ *replyinCnt = 0;
+
+ s = malloc(sizeof(*s));
+ if (s == NULL)
+ return KERN_MEMORY_FAILURE; /* XXX */
+
+ s->reply_port = reply_port;
+
+ audit_token_to_au32(client_creds, NULL, &uid, &gid, NULL, NULL, &pid, &session, NULL);
+
+ kr = _heim_ipc_create_cred(uid, gid, pid, session, &s->cred);
+ if (kr) {
+ free(s);
+ return kr;
+ }
+
+ suspend_timer();
+
+ if (requestinCnt) {
+ s->req.data = malloc(requestinCnt);
+ memcpy(s->req.data, requestin, requestinCnt);
+ s->req.length = requestinCnt;
+ } else {
+ s->req.data = malloc(requestoutCnt);
+ memcpy(s->req.data, requestout, requestoutCnt);
+ s->req.length = requestoutCnt;
+ }
+
+ dispatch_async(workq, ^{
+ (ctx->callback)(ctx->userctx, &s->req, s->cred,
+ mach_complete_sync, (heim_sipc_call)s);
+ });
+
+ return MIG_NO_REPLY;
+}
+
+kern_return_t
+mheim_do_call_request(mach_port_t server_port,
+ audit_token_t client_creds,
+ mach_port_t reply_port,
+ heim_ipc_message_inband_t requestin,
+ mach_msg_type_number_t requestinCnt,
+ heim_ipc_message_outband_t requestout,
+ mach_msg_type_number_t requestoutCnt)
+{
+ heim_sipc ctx = dispatch_get_context(dispatch_get_current_queue());
+ struct mach_call_ctx *s;
+ kern_return_t kr;
+ uid_t uid;
+ gid_t gid;
+ pid_t pid;
+ au_asid_t session;
+
+ s = malloc(sizeof(*s));
+ if (s == NULL)
+ return KERN_MEMORY_FAILURE; /* XXX */
+
+ s->reply_port = reply_port;
+
+ audit_token_to_au32(client_creds, NULL, &uid, &gid, NULL, NULL, &pid, &session, NULL);
+
+ kr = _heim_ipc_create_cred(uid, gid, pid, session, &s->cred);
+ if (kr) {
+ free(s);
+ return kr;
+ }
+
+ suspend_timer();
+
+ if (requestinCnt) {
+ s->req.data = malloc(requestinCnt);
+ memcpy(s->req.data, requestin, requestinCnt);
+ s->req.length = requestinCnt;
+ } else {
+ s->req.data = malloc(requestoutCnt);
+ memcpy(s->req.data, requestout, requestoutCnt);
+ s->req.length = requestoutCnt;
+ }
+
+ dispatch_async(workq, ^{
+ (ctx->callback)(ctx->userctx, &s->req, s->cred,
+ mach_complete_async, (heim_sipc_call)s);
+ });
+
+ return KERN_SUCCESS;
+}
+
+static int
+mach_init(const char *service, mach_port_t sport, heim_sipc ctx)
+{
+ struct mach_service *s;
+ char *name;
+
+ init_globals();
+
+ s = calloc(1, sizeof(*s));
+ if (s == NULL)
+ return ENOMEM;
+
+ asprintf(&name, "heim-ipc-mach-%s", service);
+
+ s->queue = dispatch_queue_create(name, NULL);
+ free(name);
+ s->sport = sport;
+
+ s->source = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV,
+ s->sport, 0, s->queue);
+ if (s->source == NULL) {
+ dispatch_release(s->queue);
+ free(s);
+ return ENOMEM;
+ }
+ ctx->mech = s;
+
+ dispatch_set_context(s->queue, ctx);
+ dispatch_set_context(s->source, s);
+
+ dispatch_source_set_event_handler(s->source, ^{
+ dispatch_mig_server(s->source, sizeof(union __RequestUnion__mheim_do_mheim_ipc_subsystem), mheim_ipc_server);
+ });
+
+ dispatch_source_set_cancel_handler(s->source, ^{
+ heim_sipc sctx = dispatch_get_context(dispatch_get_current_queue());
+ struct mach_service *st = sctx->mech;
+ mach_port_mod_refs(mach_task_self(), st->sport,
+ MACH_PORT_RIGHT_RECEIVE, -1);
+ dispatch_release(st->queue);
+ dispatch_release(st->source);
+ free(st);
+ free(sctx);
+ });
+
+ dispatch_resume(s->source);
+
+ return 0;
+}
+
+static int
+mach_release(heim_sipc ctx)
+{
+ struct mach_service *s = ctx->mech;
+ dispatch_source_cancel(s->source);
+ dispatch_release(s->source);
+ return 0;
+}
+
+static mach_port_t
+mach_checkin_or_register(const char *service)
+{
+ mach_port_t mp;
+ kern_return_t kr;
+
+ kr = bootstrap_check_in(bootstrap_port, service, &mp);
+ if (kr == KERN_SUCCESS)
+ return mp;
+
+#if __MAC_OS_X_VERSION_MIN_REQUIRED <= 1050
+ /* Pre SnowLeopard version */
+ kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &mp);
+ if (kr != KERN_SUCCESS)
+ return MACH_PORT_NULL;
+
+ kr = mach_port_insert_right(mach_task_self(), mp, mp,
+ MACH_MSG_TYPE_MAKE_SEND);
+ if (kr != KERN_SUCCESS) {
+ mach_port_destroy(mach_task_self(), mp);
+ return MACH_PORT_NULL;
+ }
+
+ kr = bootstrap_register(bootstrap_port, rk_UNCONST(service), mp);
+ if (kr != KERN_SUCCESS) {
+ mach_port_destroy(mach_task_self(), mp);
+ return MACH_PORT_NULL;
+ }
+
+ return mp;
+#else
+ return MACH_PORT_NULL;
+#endif
+}
+
+
+#endif /* __APPLE__ && HAVE_GCD */
+
+
+int
+heim_sipc_launchd_mach_init(const char *service,
+ heim_ipc_callback callback,
+ void *user, heim_sipc *ctx)
+{
+#if defined(__APPLE__) && defined(HAVE_GCD)
+ mach_port_t sport = MACH_PORT_NULL;
+ heim_sipc c = NULL;
+ int ret;
+
+ *ctx = NULL;
+
+ sport = mach_checkin_or_register(service);
+ if (sport == MACH_PORT_NULL) {
+ ret = ENOENT;
+ goto error;
+ }
+
+ c = calloc(1, sizeof(*c));
+ if (c == NULL) {
+ ret = ENOMEM;
+ goto error;
+ }
+ c->release = mach_release;
+ c->userctx = user;
+ c->callback = callback;
+
+ ret = mach_init(service, sport, c);
+ if (ret)
+ goto error;
+
+ *ctx = c;
+ return 0;
+ error:
+ if (c)
+ free(c);
+ if (sport != MACH_PORT_NULL)
+ mach_port_mod_refs(mach_task_self(), sport,
+ MACH_PORT_RIGHT_RECEIVE, -1);
+ return ret;
+#else /* !(__APPLE__ && HAVE_GCD) */
+ *ctx = NULL;
+ return EINVAL;
+#endif /* __APPLE__ && HAVE_GCD */
+}
+
+struct client {
+ int fd;
+ heim_ipc_callback callback;
+ void *userctx;
+ int flags;
+#define LISTEN_SOCKET 1
+#define WAITING_READ 2
+#define WAITING_WRITE 4
+#define WAITING_CLOSE 8
+
+#define HTTP_REPLY 16
+#define DOOR_FD 32
+
+#define INHERIT_MASK 0xffff0000
+#define INCLUDE_ERROR_CODE (1 << 16)
+#define ALLOW_HTTP (1<<17)
+#define UNIX_SOCKET (1<<18)
+ unsigned calls;
+ size_t ptr, len;
+ uint8_t *inmsg;
+ size_t olen;
+ uint8_t *outmsg;
+#ifdef HAVE_GCD
+ dispatch_source_t in;
+ dispatch_source_t out;
+#endif
+ struct {
+ uid_t uid;
+ gid_t gid;
+ pid_t pid;
+ } unixrights;
+};
+
+#ifndef HAVE_GCD
+static unsigned num_clients = 0;
+static struct client **clients = NULL;
+#endif
+
+static void handle_read(struct client *);
+static void handle_write(struct client *);
+static int maybe_close(struct client *);
+
+/*
+ * Update peer credentials from socket.
+ *
+ * SCM_CREDS can only be updated the first time there is read data to
+ * read from the filedescriptor, so if we read do it before this
+ * point, the cred data might not be is not there yet.
+ */
+
+static int
+update_client_creds(struct client *c)
+{
+#ifdef HAVE_GETPEERUCRED
+ /* Solaris 10 */
+ {
+ ucred_t *peercred = NULL;
+
+ if (getpeerucred(c->fd, &peercred) == 0) {
+ c->unixrights.uid = ucred_geteuid(peercred);
+ c->unixrights.gid = ucred_getegid(peercred);
+ c->unixrights.pid = 0;
+ ucred_free(peercred);
+ return 1;
+ }
+ }
+#endif
+#ifdef HAVE_GETPEEREID
+ /* FreeBSD, OpenBSD */
+ {
+ uid_t uid;
+ gid_t gid;
+
+ if (getpeereid(c->fd, &uid, &gid) == 0) {
+ c->unixrights.uid = uid;
+ c->unixrights.gid = gid;
+ c->unixrights.pid = 0;
+ return 1;
+ }
+ }
+#endif
+#if defined(SO_PEERCRED) && defined(__linux__)
+ /* Linux */
+ {
+ struct ucred pc;
+ socklen_t pclen = sizeof(pc);
+
+ if (getsockopt(c->fd, SOL_SOCKET, SO_PEERCRED, (void *)&pc, &pclen) == 0) {
+ c->unixrights.uid = pc.uid;
+ c->unixrights.gid = pc.gid;
+ c->unixrights.pid = pc.pid;
+ return 1;
+ }
+ }
+#endif
+#if defined(LOCAL_PEERCRED) && defined(XUCRED_VERSION)
+ {
+ struct xucred peercred;
+ socklen_t peercredlen = sizeof(peercred);
+
+ if (getsockopt(c->fd, LOCAL_PEERCRED, 1,
+ (void *)&peercred, &peercredlen) == 0
+ && peercred.cr_version == XUCRED_VERSION)
+ {
+ c->unixrights.uid = peercred.cr_uid;
+ c->unixrights.gid = peercred.cr_gid;
+ c->unixrights.pid = 0;
+ return 1;
+ }
+ }
+#endif
+#if defined(SOCKCREDSIZE) && defined(SCM_CREDS)
+ /* NetBSD */
+ if (c->unixrights.uid == (uid_t)-1) {
+ struct msghdr msg;
+ socklen_t crmsgsize;
+ void *crmsg;
+ struct cmsghdr *cmp;
+ struct sockcred *sc;
+
+ memset(&msg, 0, sizeof(msg));
+ crmsgsize = CMSG_SPACE(SOCKCREDSIZE(NGROUPS));
+ if (crmsgsize == 0)
+ return 1 ;
+
+ crmsg = malloc(crmsgsize);
+ if (crmsg == NULL)
+ goto failed_scm_creds;
+
+ memset(crmsg, 0, crmsgsize);
+
+ msg.msg_control = crmsg;
+ msg.msg_controllen = crmsgsize;
+
+ if (recvmsg(c->fd, &msg, 0) < 0) {
+ free(crmsg);
+ goto failed_scm_creds;
+ }
+
+ if (msg.msg_controllen == 0 || (msg.msg_flags & MSG_CTRUNC) != 0) {
+ free(crmsg);
+ goto failed_scm_creds;
+ }
+
+ cmp = CMSG_FIRSTHDR(&msg);
+ if (cmp->cmsg_level != SOL_SOCKET || cmp->cmsg_type != SCM_CREDS) {
+ free(crmsg);
+ goto failed_scm_creds;
+ }
+
+ sc = (struct sockcred *)(void *)CMSG_DATA(cmp);
+
+ c->unixrights.uid = sc->sc_euid;
+ c->unixrights.gid = sc->sc_egid;
+ c->unixrights.pid = 0;
+
+ free(crmsg);
+ return 1;
+ } else {
+ /* we already got the cred, just return it */
+ return 1;
+ }
+ failed_scm_creds:
+#endif
+ return 0;
+}
+
+static struct client *
+add_new_socket(int fd,
+ int flags,
+ heim_ipc_callback callback,
+ void *userctx)
+{
+ struct client *c;
+ int fileflags;
+
+ c = calloc(1, sizeof(*c));
+ if (c == NULL)
+ return NULL;
+
+ if (flags & LISTEN_SOCKET) {
+ c->fd = fd;
+ } else if (flags & DOOR_FD) {
+ c->fd = -1; /* cannot poll a door descriptor */
+ } else {
+ c->fd = accept(fd, NULL, NULL);
+ if(c->fd < 0) {
+ free(c);
+ return NULL;
+ }
+ }
+
+ c->flags = flags;
+ c->callback = callback;
+ c->userctx = userctx;
+
+ fileflags = fcntl(c->fd, F_GETFL, 0);
+ fcntl(c->fd, F_SETFL, fileflags | O_NONBLOCK);
+
+#ifdef HAVE_GCD
+ init_globals();
+
+ c->in = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ,
+ c->fd, 0, eventq);
+ c->out = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE,
+ c->fd, 0, eventq);
+
+ dispatch_source_set_event_handler(c->in, ^{
+ int rw = (c->flags & WAITING_WRITE);
+ handle_read(c);
+ if (rw == 0 && (c->flags & WAITING_WRITE))
+ dispatch_resume(c->out);
+ if ((c->flags & WAITING_READ) == 0)
+ dispatch_suspend(c->in);
+ maybe_close(c);
+ });
+ dispatch_source_set_event_handler(c->out, ^{
+ handle_write(c);
+ if ((c->flags & WAITING_WRITE) == 0) {
+ dispatch_suspend(c->out);
+ }
+ maybe_close(c);
+ });
+
+ dispatch_resume(c->in);
+#else
+ clients = erealloc(clients, sizeof(clients[0]) * (num_clients + 1));
+ clients[num_clients] = c;
+ num_clients++;
+#endif
+
+ return c;
+}
+
+static int
+maybe_close(struct client *c)
+{
+ if (c->calls != 0)
+ return 0;
+ if (c->flags & (WAITING_READ|WAITING_WRITE))
+ return 0;
+
+#ifdef HAVE_GCD
+ dispatch_source_cancel(c->in);
+ if ((c->flags & WAITING_READ) == 0)
+ dispatch_resume(c->in);
+ dispatch_release(c->in);
+
+ dispatch_source_cancel(c->out);
+ if ((c->flags & WAITING_WRITE) == 0)
+ dispatch_resume(c->out);
+ dispatch_release(c->out);
+#endif
+ close(c->fd); /* ref count fd close */
+ free(c);
+ return 1;
+}
+
+
+struct socket_call {
+ heim_idata in;
+ struct client *c;
+ heim_icred cred;
+};
+
+static void
+output_data(struct client *c, const void *data, size_t len)
+{
+ if (c->olen + len < c->olen)
+ abort();
+ c->outmsg = erealloc(c->outmsg, c->olen + len);
+ memcpy(&c->outmsg[c->olen], data, len);
+ c->olen += len;
+ c->flags |= WAITING_WRITE;
+}
+
+static void
+socket_complete(heim_sipc_call ctx, int returnvalue, heim_idata *reply)
+{
+ struct socket_call *sc = (struct socket_call *)ctx;
+ struct client *c = sc->c;
+
+ /* double complete ? */
+ if (c == NULL)
+ abort();
+
+ if ((c->flags & WAITING_CLOSE) == 0) {
+ uint32_t u32;
+
+ /* length */
+ u32 = htonl(reply->length);
+ output_data(c, &u32, sizeof(u32));
+
+ /* return value */
+ if (c->flags & INCLUDE_ERROR_CODE) {
+ u32 = htonl(returnvalue);
+ output_data(c, &u32, sizeof(u32));
+ }
+
+ /* data */
+ output_data(c, reply->data, reply->length);
+
+ /* if HTTP, close connection */
+ if (c->flags & HTTP_REPLY) {
+ c->flags |= WAITING_CLOSE;
+ c->flags &= ~WAITING_READ;
+ }
+ }
+
+ c->calls--;
+ if (sc->cred)
+ heim_ipc_free_cred(sc->cred);
+ free(sc->in.data);
+ sc->c = NULL; /* so we can catch double complete */
+ free(sc);
+
+ maybe_close(c);
+}
+
+/* remove HTTP %-quoting from buf */
+static int
+de_http(char *buf)
+{
+ unsigned char *p, *q;
+ for(p = q = (unsigned char *)buf; *p; p++, q++) {
+ if(*p == '%' && isxdigit(p[1]) && isxdigit(p[2])) {
+ unsigned int x;
+ if(sscanf((char *)p + 1, "%2x", &x) != 1)
+ return -1;
+ *q = x;
+ p += 2;
+ } else
+ *q = *p;
+ }
+ *q = '\0';
+ return 0;
+}
+
+static struct socket_call *
+handle_http_tcp(struct client *c)
+{
+ struct socket_call *cs;
+ char *s, *p, *t;
+ void *data;
+ char *proto;
+ int len;
+
+ s = (char *)c->inmsg;
+
+ p = strstr(s, "\r\n");
+ if (p == NULL)
+ return NULL;
+
+ *p = 0;
+
+ p = NULL;
+ t = strtok_r(s, " \t", &p);
+ if (t == NULL)
+ return NULL;
+
+ t = strtok_r(NULL, " \t", &p);
+ if (t == NULL)
+ return NULL;
+
+ data = malloc(strlen(t));
+ if (data == NULL)
+ return NULL;
+
+ if(*t == '/')
+ t++;
+ if(de_http(t) != 0) {
+ free(data);
+ return NULL;
+ }
+ proto = strtok_r(NULL, " \t", &p);
+ if (proto == NULL) {
+ free(data);
+ return NULL;
+ }
+ len = rk_base64_decode(t, data);
+ if(len <= 0){
+ const char *msg =
+ " 404 Not found\r\n"
+ "Server: Heimdal/" VERSION "\r\n"
+ "Cache-Control: no-cache\r\n"
+ "Pragma: no-cache\r\n"
+ "Content-type: text/html\r\n"
+ "Content-transfer-encoding: 8bit\r\n\r\n"
+ "<TITLE>404 Not found</TITLE>\r\n"
+ "<H1>404 Not found</H1>\r\n"
+ "That page doesn't exist, maybe you are looking for "
+ "<A HREF=\"http://www.h5l.org/\">Heimdal</A>?\r\n";
+ free(data);
+ output_data(c, proto, strlen(proto));
+ output_data(c, msg, strlen(msg));
+ return NULL;
+ }
+
+ cs = emalloc(sizeof(*cs));
+ cs->c = c;
+ cs->in.data = data;
+ cs->in.length = len;
+ c->ptr = 0;
+
+ {
+ const char *msg =
+ " 200 OK\r\n"
+ "Server: Heimdal/" VERSION "\r\n"
+ "Cache-Control: no-cache\r\n"
+ "Pragma: no-cache\r\n"
+ "Content-type: application/octet-stream\r\n"
+ "Content-transfer-encoding: binary\r\n\r\n";
+ output_data(c, proto, strlen(proto));
+ output_data(c, msg, strlen(msg));
+ }
+
+ return cs;
+}
+
+
+static void
+handle_read(struct client *c)
+{
+ ssize_t len;
+ uint32_t dlen;
+
+ assert((c->flags & DOOR_FD) == 0);
+
+ if (c->flags & LISTEN_SOCKET) {
+ add_new_socket(c->fd,
+ WAITING_READ | (c->flags & INHERIT_MASK),
+ c->callback,
+ c->userctx);
+ return;
+ }
+
+ if (c->ptr - c->len < 1024) {
+ c->inmsg = erealloc(c->inmsg,
+ c->len + 1024);
+ c->len += 1024;
+ }
+
+ len = read(c->fd, c->inmsg + c->ptr, c->len - c->ptr);
+ if (len <= 0) {
+ c->flags |= WAITING_CLOSE;
+ c->flags &= ~WAITING_READ;
+ return;
+ }
+ c->ptr += len;
+ if (c->ptr > c->len)
+ abort();
+
+ while (c->ptr >= sizeof(dlen)) {
+ struct socket_call *cs;
+
+ if((c->flags & ALLOW_HTTP) && c->ptr >= 4 &&
+ strncmp((char *)c->inmsg, "GET ", 4) == 0 &&
+ strncmp((char *)c->inmsg + c->ptr - 4, "\r\n\r\n", 4) == 0) {
+
+ /* remove the trailing \r\n\r\n so the string is NUL terminated */
+ c->inmsg[c->ptr - 4] = '\0';
+
+ c->flags |= HTTP_REPLY;
+
+ cs = handle_http_tcp(c);
+ if (cs == NULL) {
+ c->flags |= WAITING_CLOSE;
+ c->flags &= ~WAITING_READ;
+ break;
+ }
+ } else {
+ memcpy(&dlen, c->inmsg, sizeof(dlen));
+ dlen = ntohl(dlen);
+
+ if (dlen > MAX_PACKET_SIZE) {
+ c->flags |= WAITING_CLOSE;
+ c->flags &= ~WAITING_READ;
+ return;
+ }
+ if (dlen > c->ptr - sizeof(dlen)) {
+ break;
+ }
+
+ cs = emalloc(sizeof(*cs));
+ cs->c = c;
+ cs->in.data = emalloc(dlen);
+ memcpy(cs->in.data, c->inmsg + sizeof(dlen), dlen);
+ cs->in.length = dlen;
+ cs->cred = NULL;
+
+ c->ptr -= sizeof(dlen) + dlen;
+ memmove(c->inmsg,
+ c->inmsg + sizeof(dlen) + dlen,
+ c->ptr);
+ }
+
+ c->calls++;
+
+ if ((c->flags & UNIX_SOCKET) != 0) {
+ if (update_client_creds(c))
+ _heim_ipc_create_cred(c->unixrights.uid, c->unixrights.gid,
+ c->unixrights.pid, -1, &cs->cred);
+ }
+
+ c->callback(c->userctx, &cs->in,
+ cs->cred, socket_complete,
+ (heim_sipc_call)cs);
+ }
+}
+
+static void
+handle_write(struct client *c)
+{
+ ssize_t len;
+
+ len = write(c->fd, c->outmsg, c->olen);
+ if (len <= 0) {
+ c->flags |= WAITING_CLOSE;
+ c->flags &= ~(WAITING_WRITE);
+ } else if (c->olen != (size_t)len) {
+ memmove(&c->outmsg[0], &c->outmsg[len], c->olen - len);
+ c->olen -= len;
+ } else {
+ c->olen = 0;
+ free(c->outmsg);
+ c->outmsg = NULL;
+ c->flags &= ~(WAITING_WRITE);
+ }
+}
+
+
+#ifndef HAVE_GCD
+
+static void
+process_loop(void)
+{
+ struct pollfd *fds;
+ unsigned n;
+ unsigned num_fds;
+
+ while (num_clients > 0) {
+
+ fds = malloc(num_clients * sizeof(fds[0]));
+ if(fds == NULL)
+ abort();
+
+ num_fds = num_clients;
+
+ for (n = 0 ; n < num_fds; n++) {
+ fds[n].fd = clients[n]->fd;
+ fds[n].events = 0;
+ if (clients[n]->flags & WAITING_READ)
+ fds[n].events |= POLLIN;
+ if (clients[n]->flags & WAITING_WRITE)
+ fds[n].events |= POLLOUT;
+
+ fds[n].revents = 0;
+ }
+
+ while (poll(fds, num_fds, -1) == -1) {
+ if (errno == EINTR || errno == EAGAIN)
+ continue;
+ err(1, "poll(2) failed");
+ }
+
+ for (n = 0 ; n < num_fds; n++) {
+ if (clients[n] == NULL)
+ continue;
+ if (fds[n].revents & POLLIN)
+ handle_read(clients[n]);
+ if (fds[n].revents & POLLOUT)
+ handle_write(clients[n]);
+ if (fds[n].revents & POLLERR)
+ clients[n]->flags |= WAITING_CLOSE;
+ }
+
+ n = 0;
+ while (n < num_clients) {
+ struct client *c = clients[n];
+ if (maybe_close(c)) {
+ if (n < num_clients - 1)
+ clients[n] = clients[num_clients - 1];
+ num_clients--;
+ } else
+ n++;
+ }
+
+ free(fds);
+ }
+}
+
+#endif
+
+static int
+socket_release(heim_sipc ctx)
+{
+ struct client *c = ctx->mech;
+ c->flags |= WAITING_CLOSE;
+ return 0;
+}
+
+int
+heim_sipc_stream_listener(int fd, int type,
+ heim_ipc_callback callback,
+ void *user, heim_sipc *ctx)
+{
+ heim_sipc ct;
+ struct client *c;
+
+ if ((type & HEIM_SIPC_TYPE_IPC) && (type & (HEIM_SIPC_TYPE_UINT32|HEIM_SIPC_TYPE_HTTP)))
+ return EINVAL;
+
+ ct = calloc(1, sizeof(*ct));
+ if (ct == NULL)
+ return ENOMEM;
+
+ switch (type) {
+ case HEIM_SIPC_TYPE_IPC:
+ c = add_new_socket(fd, LISTEN_SOCKET|WAITING_READ|INCLUDE_ERROR_CODE, callback, user);
+ break;
+ case HEIM_SIPC_TYPE_UINT32:
+ c = add_new_socket(fd, LISTEN_SOCKET|WAITING_READ, callback, user);
+ break;
+ case HEIM_SIPC_TYPE_HTTP:
+ case HEIM_SIPC_TYPE_UINT32|HEIM_SIPC_TYPE_HTTP:
+ c = add_new_socket(fd, LISTEN_SOCKET|WAITING_READ|ALLOW_HTTP, callback, user);
+ break;
+ default:
+ free(ct);
+ return EINVAL;
+ }
+
+ ct->mech = c;
+ ct->release = socket_release;
+
+ c->unixrights.uid = (uid_t) -1;
+ c->unixrights.gid = (gid_t) -1;
+ c->unixrights.pid = (pid_t) 0;
+
+ *ctx = ct;
+ return 0;
+}
+
+int
+heim_sipc_service_unix(const char *service,
+ heim_ipc_callback callback,
+ void *user, heim_sipc *ctx)
+{
+ struct sockaddr_un un;
+ const char *d = secure_getenv("HEIM_IPC_DIR");
+ int fd, ret;
+
+ un.sun_family = AF_UNIX;
+
+ if (snprintf(un.sun_path, sizeof(un.sun_path),
+ "%s/.heim_%s-socket", d ? d : _PATH_VARRUN,
+ service) > sizeof(un.sun_path) + sizeof("-s") - 1)
+ return ENAMETOOLONG;
+ fd = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (fd < 0)
+ return errno;
+
+ socket_set_reuseaddr(fd, 1);
+#ifdef LOCAL_CREDS
+ {
+ int one = 1;
+ (void) setsockopt(fd, 0, LOCAL_CREDS, (void *)&one, sizeof(one));
+ }
+#endif
+
+ unlink(un.sun_path);
+
+ if (bind(fd, (struct sockaddr *)&un, sizeof(un)) < 0) {
+ close(fd);
+ return errno;
+ }
+
+ if (listen(fd, SOMAXCONN) < 0) {
+ close(fd);
+ return errno;
+ }
+
+ chmod(un.sun_path, 0666);
+
+ ret = heim_sipc_stream_listener(fd, HEIM_SIPC_TYPE_IPC,
+ callback, user, ctx);
+ if (ret == 0) {
+ struct client *c = (*ctx)->mech;
+ c->flags |= UNIX_SOCKET;
+ }
+
+ return ret;
+}
+
+#ifdef HAVE_DOOR_CREATE
+#include <door.h>
+
+#ifdef HAVE_SYS_MMAN_H
+#include <sys/mman.h>
+#endif
+
+#include "heim_threads.h"
+
+static HEIMDAL_thread_key door_key;
+
+struct door_call {
+ heim_idata in;
+ door_desc_t *dp;
+ heim_icred cred;
+};
+
+struct door_reply {
+ int returnvalue;
+ size_t length;
+ unsigned char data[1];
+};
+
+static int
+door_release(heim_sipc ctx)
+{
+ struct client *c = ctx->mech;
+ return 0;
+}
+
+static void
+door_reply_destroy(void *data)
+{
+ free(data);
+}
+
+static void
+door_key_create(void *key)
+{
+ int ret;
+
+ HEIMDAL_key_create((HEIMDAL_thread_key *)key, door_reply_destroy, ret);
+}
+
+static void
+door_complete(heim_sipc_call ctx, int returnvalue, heim_idata *reply)
+{
+ static heim_base_once_t once = HEIM_BASE_ONCE_INIT;
+ struct door_call *cs = (struct door_call *)ctx;
+ size_t rlen;
+ struct door_reply *r = NULL;
+ union {
+ struct door_reply reply;
+ char buffer[offsetof(struct door_reply, data) + BUFSIZ];
+ } replyBuf;
+
+ heim_base_once_f(&once, &door_key, door_key_create);
+
+ /* door_return() doesn't return; don't leak cred */
+ heim_ipc_free_cred(cs->cred);
+
+error_reply:
+ rlen = offsetof(struct door_reply, data);
+ if (returnvalue == 0)
+ rlen += reply->length;
+
+ /* long replies (> BUFSIZ) are allocated from the heap */
+ if (rlen > BUFSIZ) {
+ int ret;
+
+ /* door_return() doesn't return, so stash reply buffer in TLS */
+ r = realloc(HEIMDAL_getspecific(door_key), rlen);
+ if (r == NULL) {
+ returnvalue = EAGAIN; /* don't leak ENOMEM to caller */
+ goto error_reply;
+ }
+
+ HEIMDAL_setspecific(door_key, r, ret);
+ } else {
+ r = &replyBuf.reply;
+ }
+
+ r->returnvalue = returnvalue;
+ if (r->returnvalue == 0) {
+ r->length = reply->length;
+ memcpy(r->data, reply->data, reply->length);
+ } else {
+ r->length = 0;
+ }
+
+ door_return((char *)r, rlen, NULL, 0);
+}
+
+static void
+door_callback(void *cookie,
+ char *argp,
+ size_t arg_size,
+ door_desc_t *dp,
+ uint_t n_desc)
+{
+ heim_sipc c = (heim_sipc)cookie;
+ struct door_call cs = { 0 };
+ ucred_t *peercred = NULL;
+
+ if (door_ucred(&peercred) < 0)
+ return;
+
+ _heim_ipc_create_cred(ucred_geteuid(peercred),
+ ucred_getegid(peercred),
+ ucred_getpid(peercred),
+ -1,
+ &cs.cred);
+ ucred_free(peercred);
+
+ cs.dp = dp;
+ cs.in.data = argp;
+ cs.in.length = arg_size;
+
+ c->callback(c->userctx, &cs.in, cs.cred, door_complete, (heim_sipc_call)&cs);
+}
+
+int
+heim_sipc_service_door(const char *service,
+ heim_ipc_callback callback,
+ void *user, heim_sipc *ctx)
+{
+ char path[PATH_MAX];
+ int fd = -1, dfd = -1, ret;
+ heim_sipc ct = NULL;
+ struct client *c = NULL;
+
+ ct = calloc(1, sizeof(*ct));
+ if (ct == NULL) {
+ ret = ENOMEM;
+ goto cleanup;
+ }
+ ct->release = door_release;
+ ct->userctx = user;
+ ct->callback = callback;
+
+ if (snprintf(path, sizeof(path), "/var/run/.heim_%s-door",
+ service) >= sizeof(path) + sizeof("-d") - 1) {
+ ret = ENAMETOOLONG;
+ goto cleanup;
+ }
+ fd = door_create(door_callback, ct, DOOR_REFUSE_DESC | DOOR_NO_CANCEL);
+ if (fd < 0) {
+ ret = errno;
+ goto cleanup;
+ }
+
+ fdetach(path);
+ dfd = open(path, O_RDWR | O_CREAT, 0666);
+ if (dfd < 0) {
+ ret = errno;
+ goto cleanup;
+ }
+ fchmod(dfd, 0666); /* XXX */
+
+ if (fattach(fd, path) < 0) {
+ ret = errno;
+ goto cleanup;
+ }
+
+ c = add_new_socket(fd, DOOR_FD, callback, user);
+ ct->mech = c;
+
+ *ctx = ct;
+ ret = 0;
+
+cleanup:
+ if (ret != 0) {
+ free(ct);
+ free(c);
+ if (fd != -1)
+ close(fd);
+ }
+ if (dfd != -1)
+ close(dfd);
+
+ return ret;
+}
+#endif /* HAVE_DOOR_CREATE */
+
+/**
+ * Set the idle timeout value
+
+ * The timeout event handler is triggered recurrently every idle
+ * period `t'. The default action is rather draconian and just calls
+ * exit(0), so you might want to change this to something more
+ * graceful using heim_sipc_set_timeout_handler().
+ */
+
+void
+heim_sipc_timeout(time_t t)
+{
+#ifdef HAVE_GCD
+ static dispatch_once_t timeoutonce;
+ init_globals();
+ dispatch_sync(timerq, ^{
+ timeoutvalue = t;
+ set_timer();
+ });
+ dispatch_once(&timeoutonce, ^{ dispatch_resume(timer); });
+#else
+ abort();
+#endif
+}
+
+/**
+ * Set the timeout event handler
+ *
+ * Replaces the default idle timeout action.
+ */
+
+void
+heim_sipc_set_timeout_handler(void (*func)(void))
+{
+#ifdef HAVE_GCD
+ init_globals();
+ dispatch_sync(timerq, ^{ timer_ev = func; });
+#else
+ abort();
+#endif
+}
+
+
+void
+heim_sipc_free_context(heim_sipc ctx)
+{
+ (ctx->release)(ctx);
+}
+
+void
+heim_ipc_main(void)
+{
+#ifdef HAVE_GCD
+ dispatch_main();
+#else
+ process_loop();
+#endif
+}
+
diff --git a/third_party/heimdal/lib/ipc/tc.c b/third_party/heimdal/lib/ipc/tc.c
new file mode 100644
index 0000000..e366f17
--- /dev/null
+++ b/third_party/heimdal/lib/ipc/tc.c
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <krb5-types.h>
+#include <asn1-common.h>
+#include <heim-ipc.h>
+#include <getarg.h>
+#include <err.h>
+#include <roken.h>
+
+static int help_flag;
+static int version_flag;
+
+static struct getargs args[] = {
+ { "help", 'h', arg_flag, &help_flag, NULL, NULL },
+ { "version", 'v', arg_flag, &version_flag, NULL, NULL }
+};
+
+static int num_args = sizeof(args) / sizeof(args[0]);
+
+static void
+usage(int ret)
+{
+ arg_printusage (args, num_args, NULL, "");
+ exit (ret);
+}
+
+static void
+reply(void *ctx, int errorcode, heim_idata *rep, heim_icred cred)
+{
+ printf("got reply errorcode %d, rep %.*s\n", errorcode,
+ rep->length < INT_MAX ? (int)rep->length : INT_MAX,
+ (char *)rep->data);
+ heim_ipc_semaphore_signal((heim_isemaphore)ctx); /* tell caller we are done */
+}
+
+static void
+test_ipc(const char *service)
+{
+ heim_isemaphore s;
+ heim_idata req, rep;
+ heim_ipc ipc;
+ int ret;
+ char buf[128];
+
+ snprintf(buf, sizeof(buf), "testing heim IPC via %s", service);
+
+ printf("%s\n", buf);
+
+ ret = heim_ipc_init_context(service, &ipc);
+ if (ret)
+ errx(1, "heim_ipc_init_context: %d", ret);
+
+ req.length = strlen(buf);
+ req.data = buf;
+
+ ret = heim_ipc_call(ipc, &req, &rep, NULL);
+ if (ret)
+ errx(1, "heim_ipc_call: %d", ret);
+
+ s = heim_ipc_semaphore_create(0);
+ if (s == NULL)
+ errx(1, "heim_ipc_semaphore_create");
+
+ ret = heim_ipc_async(ipc, &req, s, reply);
+ if (ret)
+ errx(1, "heim_ipc_async: %d", ret);
+
+ heim_ipc_semaphore_wait(s, HEIM_IPC_WAIT_FOREVER); /* wait for reply to complete the work */
+
+ heim_ipc_free_context(ipc);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ int optidx = 0;
+
+ setprogname(argv[0]);
+
+ if (getarg(args, num_args, argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage(0);
+
+ if (version_flag) {
+ print_version(NULL);
+ exit(0);
+ }
+
+#ifdef __APPLE__
+ test_ipc("MACH:org.h5l.test-ipc");
+#endif
+ test_ipc("ANY:org.h5l.test-ipc");
+ test_ipc("UNIX:org.h5l.test-ipc");
+#ifdef HAVE_DOOR_CREATE
+ test_ipc("DOOR:org.h5l.test-ipc");
+#endif
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/ipc/ts-http.c b/third_party/heimdal/lib/ipc/ts-http.c
new file mode 100644
index 0000000..c3c3ce5
--- /dev/null
+++ b/third_party/heimdal/lib/ipc/ts-http.c
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <krb5-types.h>
+#include <heim-ipc.h>
+#include <getarg.h>
+#include <roken.h>
+
+static int help_flag;
+static int version_flag;
+
+static struct getargs args[] = {
+ { "help", 'h', arg_flag, &help_flag, NULL, NULL },
+ { "version", 'v', arg_flag, &version_flag, NULL, NULL }
+};
+
+static int num_args = sizeof(args) / sizeof(args[0]);
+
+static void
+usage(int ret)
+{
+ arg_printusage (args, num_args, NULL, "");
+ exit (ret);
+}
+
+static void
+test_service(void *ctx, const heim_idata *req,
+ const heim_icred cred,
+ heim_ipc_complete complete,
+ heim_sipc_call cctx)
+{
+ heim_idata rep;
+ printf("got request\n");
+ rep.length = 3;
+ rep.data = strdup("hej");
+ (*complete)(cctx, 0, &rep);
+}
+
+
+static void
+setup_sockets(void)
+{
+ struct addrinfo hints, *res, *res0;
+ int ret, s;
+ heim_sipc u;
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_flags = AI_PASSIVE;
+ ret = getaddrinfo(NULL, "8080", &hints, &res0);
+ if (ret)
+ errx(1, "%s", gai_strerror(ret));
+
+ for (res = res0; res ; res = res->ai_next) {
+ s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
+ if (s < 0) {
+ warn("socket");
+ continue;
+ }
+ socket_set_reuseaddr(s, 1);
+ socket_set_ipv6only(s, 1);
+
+ if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
+ warn("bind");
+ close(s);
+ continue;
+ }
+ listen(s, 5);
+ ret = heim_sipc_stream_listener(s, HEIM_SIPC_TYPE_HTTP,
+ test_service, NULL, &u);
+ if (ret)
+ errx(1, "heim_sipc_stream_listener: %d", ret);
+ }
+ freeaddrinfo(res0);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ int optidx = 0;
+
+ setprogname(argv[0]);
+
+ if (getarg(args, num_args, argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage(0);
+
+ if (version_flag) {
+ print_version(NULL);
+ exit(0);
+ }
+
+ setup_sockets();
+
+ heim_ipc_main();
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/ipc/ts.c b/third_party/heimdal/lib/ipc/ts.c
new file mode 100644
index 0000000..3ba5d65
--- /dev/null
+++ b/third_party/heimdal/lib/ipc/ts.c
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <krb5-types.h>
+#include <heim-ipc.h>
+#include <getarg.h>
+#include <roken.h>
+
+static int help_flag;
+static int version_flag;
+
+static struct getargs args[] = {
+ { "help", 'h', arg_flag, &help_flag, NULL, NULL },
+ { "version", 'v', arg_flag, &version_flag, NULL, NULL }
+};
+
+static int num_args = sizeof(args) / sizeof(args[0]);
+
+static void
+usage(int ret)
+{
+ arg_printusage (args, num_args, NULL, "");
+ exit (ret);
+}
+
+static void
+test_service(void *ctx, const heim_idata *req,
+ const heim_icred cred,
+ heim_ipc_complete complete,
+ heim_sipc_call cctx)
+{
+ heim_idata rep;
+ char buf[128];
+
+ printf("got request via %s\n", (const char *)ctx);
+ snprintf(buf, sizeof(buf), "Hello back via %s\n", (const char *)ctx);
+ rep.data = buf;
+ rep.length = strlen(buf);
+ (*complete)(cctx, 0, &rep);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ heim_sipc u;
+ int optidx = 0;
+
+ setprogname(argv[0]);
+
+ if (getarg(args, num_args, argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage(0);
+
+ if (version_flag) {
+ print_version(NULL);
+ exit(0);
+ }
+
+#if __APPLE__
+ {
+ heim_sipc mach;
+ heim_sipc_launchd_mach_init("org.h5l.test-ipc",
+ test_service, "MACH", &mach);
+ }
+#endif
+ heim_sipc_service_unix("org.h5l.test-ipc",
+ test_service, "UNIX", &u);
+#ifdef HAVE_DOOR_CREATE
+ {
+ heim_sipc door;
+ heim_sipc_service_door("org.h5l.test-ipc",
+ test_service, "DOOR", &door);
+ }
+#endif
+ heim_ipc_main();
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/ChangeLog b/third_party/heimdal/lib/kadm5/ChangeLog
new file mode 100644
index 0000000..5016827
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/ChangeLog
@@ -0,0 +1,1389 @@
+2008-04-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ipropd_master.c: Only log "sending AYT" once, pointed out by Dr
+ A V Le Blanc.
+
+
+2008-01-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * default_keys.c: Use hdb_free_keys().
+
+2008-01-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add check-cracklib.pl, flush.c,
+ sample_passwd_check.c
+
+2007-12-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * use hdb_db_dir() and hdb_default_db()
+
+2007-10-18 Love <lha@stacken.kth.se>
+
+ * init_c.c: We are getting default_client, not client. this way
+ the user can override the result.
+
+2007-09-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * iprop.8: fix spelling, From Antoine Jacoutt.
+
+2007-08-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * version-script.map: export _kadm5_unmarshal_params,
+ _kadm5_acl_check_permission
+
+ * version-script.map: export kadm5_log_ symbols.
+
+ * log.c: Unexport the specific log replay operations.
+
+2007-08-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: build sample_passwd_check.la as part of noinst.
+
+ * sample_passwd_check.c: Add missing prototype for check_length().
+
+2007-08-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * log.c: Sprinkle krb5_set_error_string().
+
+ * ipropd_slave.c: Provide better error why kadm5_log_replay
+ failed.
+
+2007-08-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ipropd_master.c: - don't push whole database to the new client
+ every time. - make slaves get the whole new database if they have
+ a newer log the the master (and thus have them go back in time).
+
+2007-08-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ipropd_slave.c: make more sane.
+
+ * ipropd_slave.c: more paranoid check that the log entires are
+ self consistant
+
+ * log.c (kadm5_log_foreach): check that the postamble contains the
+ right data.
+
+ * ipropd_master.c: Sprinkle more info about what versions the
+ master thinks about the client versions.
+
+ * ipropd_master.c: Start the server at the current version, not 0.
+
+2007-08-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ipropd_master.c: Add more logging, to figure out what is
+ happening in the master.
+
+2007-08-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add version-script for libkadm5srv.la
+
+ * version-script.map: version script fro kadm5 server libary.
+
+ * log.c: only free the orignal entries extentions if there was
+ any. Bug reported by Peter Meinecke.
+
+ * add configuration for signal file and acl file, let user select
+ hostname, catch signals and print why we are quiting, make nop
+ cause one new version, not two
+
+2007-07-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ipropd_master.c (send_diffs): make current slave's version
+ uptodate when diff have been sent.
+
+2007-07-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ipropd_slave.c: More comments and some more error checking.
+
+2007-07-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_c.c (get_cache_principal): make sure id is reset if we
+ fail. From Benjamin Bennet.
+
+2007-07-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * context_s.c (find_db_spec): match realm-less as the default
+ realm.
+
+ * Makefile.am: New library version.
+
+2007-07-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * context_s.c: Use hdb_get_dbinfo to pick up configuration.
+ ctx->config.realm can be NULL, check for that, from Bjorn S.
+
+2007-07-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_c.c: Try harder to use the right principal.
+
+2007-06-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ipropd_slave.c: Catch return value from krb5_program_setup. From
+ Steven Luo.
+
+2007-05-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * delete_s.c: Write log entry after store is successful, rename
+ out goto statments.
+
+ * randkey_s.c: Write log entry after store is successful.
+
+ * modify_s.c: Write log entry after store is successful.
+
+ * rename_s.c: indent.
+
+ * chpass_s.c: Write log entry after store is successful.
+
+ * create_s.c: Write log entry after store is successful.
+
+2007-05-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * iprop-commands.in: Add default values to make this working
+ again.
+
+ * iprop-log.c (iprop_replay): create the database with more
+ liberal mode.
+
+ * log.c: make it slightly more working.
+
+ * iprop-log.8: Document last-version.
+
+ * iprop-log.c: (last_version): print last version of the log.
+
+ * iprop-commands.in: new command last-version: print last version
+ of the log.
+
+ * log.c (kadm5_log_previous): document assumptions and make less
+ broken. Bug report from Ronny Blomme.
+
+2007-02-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * admin.h: add support to get aliases
+
+ * get_s.c: add support to get aliases
+
+2007-02-11 David Love <fx@gnu.org>
+
+ * iprop-log.8: Small fixes, from David Love.
+
+2006-12-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_c.c: if the user have a kadmin/admin initial ticket, don't
+ ask for password, just use the credential instead.
+
+2006-12-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ipropd_master.c: Use strcspn to remove \n from string returned
+ by fgets. From Björn Sandell
+
+2006-11-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_c.c (kadm_connect): clear error string before trying to
+ print a errno, this way we don't pick up a random failure code
+
+2006-11-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ipropd_slave.c: Make krb5_get_init_creds_opt_free take a context
+ argument.
+
+ * init_c.c: Make krb5_get_init_creds_opt_free take a context
+ argument.
+
+2006-10-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ent_setup.c: Try to not leak memory.
+
+2006-10-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: split build files into dist_ and noinst_ SOURCES
+
+2006-08-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * get_s.c: Add KRB5_KDB_ALLOW_DIGEST
+
+ * ent_setup.c: Add KRB5_KDB_ALLOW_DIGEST
+
+ * admin.h: Add KRB5_KDB_ALLOW_DIGEST
+
+2006-06-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-cracklib.pl: Add password reuse checking. From Harald
+ Barth.
+
+2006-06-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ent_setup.c (attr_to_flags): Add KRB5_KDB_ALLOW_KERBEROS4
+
+ * get_s.c (kadm5_s_get_principal): Add KRB5_KDB_ALLOW_KERBEROS4
+
+ * admin.h: Add KRB5_KDB_ALLOW_KERBEROS4
+
+2006-06-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ent_setup.c (attr_to_flags): Add KRB5_KDB_TRUSTED_FOR_DELEGATION
+
+2006-05-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * password_quality.c (kadm5_check_password_quality): set error
+ message in context.
+
+2006-05-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * iprop-log.c: Avoid shadowing.
+
+ * rename_s.c: Avoid shadowing.
+
+2006-05-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * privs_c.c (kadm5_c_get_privs): privs is a uint32_t, let copy it
+ that way.
+
+2006-05-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Rename u_intXX_t to uintXX_t
+
+2006-04-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * chpass_s.c,delete_s.c,get_s.c,log.c,modify_s.c,randkey_s.c,rename_s.c:
+ Pass in HDB_F_GET_ANY to all ->hdb fetch to hint what entries we are looking for
+
+ * send_recv.c: set and clear error string
+
+ * rename_s.c: Break out the that we request from principal from
+ the entry and pass it in as a separate argument.
+
+ * randkey_s.c: Break out the that we request from principal from
+ the entry and pass it in as a separate argument.
+
+ * modify_s.c: Break out the that we request from principal from
+ the entry and pass it in as a separate argument.
+
+ * log.c: Break out the that we request from principal from the
+ entry and pass it in as a separate argument.
+
+ * get_s.c: Break out the that we request from principal from the
+ entry and pass it in as a separate argument.
+
+ * delete_s.c: Break out the that we request from principal from
+ the entry and pass it in as a separate argument.
+
+ * chpass_s.c: Break out the that we request from principal from
+ the entry and pass it in as a separate argument.
+
+2006-04-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * create_s.c (create_principal*): If client doesn't send kvno,
+ make sure to set it to 1.
+
+2006-04-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * log.c: (kadm5_log_rename): handle errors better
+ Fixes Coverity, NetBSD CID#628
+
+ * log.c (kadm5_log_delete): add error handling Coverity, NetBSD
+ CID#626
+ (kadm5_log_modify): add error handling Coverity, NetBSD CID#627
+
+ * init_c.c (_kadm5_c_get_cred_cache): handle ccache case better in
+ case no client name was passed in. Coverity, NetBSD CID#919
+
+ * init_c.c (_kadm5_c_get_cred_cache): Free client principal in
+ case of error. Coverity NetBSD CID#1908
+
+2006-02-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * kadm5_err.et: (PASS_REUSE): Spelling,
+ from Václav H?la <ax@natur.cuni.cz>
+
+2006-01-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * send_recv.c: Clear error-string when introducing new errors.
+
+ * *_c.c: Clear error-string when introducing new errors.
+
+2006-01-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am (libkadm5clnt.la) doesn't depend on libhdb, remove
+ dependency
+
+2005-12-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * memset hdb_entry_ex before use
+
+2005-12-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Wrap hdb_entry with hdb_entry_ex, patch originally
+ from Andrew Bartlet
+
+2005-11-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * context_s.c (set_field): try another way to calculate the path
+ to the database/logfile/signal-socket
+
+ * log.c (kadm5_log_init): set error string on failures
+
+2005-09-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Constify password.
+
+ * admin.h: Add KRB5_TL_PKINIT_ACL.
+
+ * marshall.c (_kadm5_unmarshal_params): avoid signed-ness warnings
+
+ * get_s.c (kadm5_s_get_principal): clear error string
+
+2005-08-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * iprop-log.8: More text about iprop-log.
+
+2005-08-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * iprop.8: SEE ALSO iprop-log.
+
+ * Makefile.am: man_MANS += iprop-log.8
+
+ * iprop-log.8: Basic for documentation of iprop-log.
+
+ * remove replay_log.c, dump_log.c, and truncate_log.c, folded into
+ iprop-log.
+
+ * log.c (kadm5_log_foreach): add a context variable and pass it
+ down to `func´.
+
+ * iprop-commands.in: Move truncate_log and replay_log into
+ iprop-log.
+
+ * iprop-log.c: Move truncate_log and replay_log into iprop-log.
+
+ * Makefile.am: Move truncate_log and replay_log into iprop-log.
+
+ * Makefile.am: Make this work with a clean directory.
+
+ * ipropd_master.c: Make compile.
+
+ * ipropd_master.c: Update to new signature of kadm5_log_previous.
+
+ * log.c (kadm5_log_previous): catch errors instead of asserting
+ and set error string.
+
+ * iprop-commands.in: New program iprop-log that incorperates
+ dump_log as a subcommand, truncate_log and replay_log soon to come
+ after.
+
+ * iprop-log.c: New program iprop-log that incorperates dump_log as
+ a subcommand, truncate_log and replay_log soon to come after.
+
+ * Makefile.am: New program iprop-log that incorperates dump_log as
+ a subcommand, truncate_log and replay_log soon to come after.
+
+2005-08-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * get_s.c: Implement KADM5_LAST_PWD_CHANGE.
+
+ * set_keys.c: Set and clear password where appropriate.
+
+ * randkey_s.c: Operation modifies tl_data.
+
+ * log.c (kadm5_log_replay_modify): Check return values of
+ malloc(), replace all extensions.
+
+ * kadm5_err.et: Make BAD_TL_TYPE error more helpful.
+
+ * get_s.c: Expose KADM5_TL_DATA options to the client.
+
+ * ent_setup.c: Merge in KADM5_TL_DATA in the database.
+
+ * chpass_s.c: Operations modify extensions, mark that with
+ TL_DATA.
+
+ * admin.h: Add more TL types (password and extension).
+
+2005-06-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * constify
+
+ * ipropd_slave.c: avoid shadowing
+
+ * ipropd_master.c: rename local variable slave to s, optind ->
+ optidx
+
+ * get_princs_c.c: rename variable exp to expression
+
+ * ad.c: rename variable exp to expression
+
+ * log.c: rename shadowing len to num
+
+ * get_princs_s.c: rename variable exp to expression
+
+ * context_s.c: const poison
+
+ * common_glue.c: rename variable exp to expression
+
+2005-05-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ent_setup.c (attr_to_flags): check for KRB5_KDB_OK_AS_DELEGATE
+
+ * get_s.c (kadm5_s_get_principal): set KRB5_KDB_OK_AS_DELEGATE
+
+ * admin.h: add KRB5_KDB_OK_AS_DELEGATE, sync KRB5_TL_ flags
+
+2005-05-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * kadm5_pwcheck.3: please mdoclint
+
+2005-05-25 Dave Love <fx@gnu.org>
+
+ * kadm5_pwcheck.3: document kadm5_add_passwd_quality_verifier,
+ improve text
+
+2005-05-24 Dave Love <fx@gnu.org>
+
+ * iprop.8: Added some info about defaults, fixed some markup.
+
+2005-05-23 Dave Love <fx@gnu.org>
+
+ * ipropd_slave.c: Don't test HAVE_DAEMON since roken supplies it.
+
+ * ipropd_master.c: Don't test HAVE_DAEMON since roken supplies it.
+
+2005-05-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_c.c (_kadm5_c_init_context): fix memory leak in case of
+ failure
+
+2005-05-09 Dave Love <fx@gnu.org>
+
+ * password_quality.c (find_func): Fix off-by-one and logic error.
+ (external_passwd_quality): Improve messages.
+
+ * test_pw_quality.c (main): Call kadm5_setup_passwd_quality_check
+ and kadm5_add_passwd_quality_verifier.
+
+2005-04-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * default_keys.c: #include <err.h>, only print salt it its longer
+ then 0, use krb5_err instead of errx where appropriate
+
+2005-04-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ipropd_slave.c: add the documented option --port
+
+ * ipropd_master.c: add the documented option --port
+
+ * dump_log.c: use the newly generated units function
+
+2005-04-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * dump_log.c: use strlcpy
+
+ * password_quality.c: don't use sizeof(pointer)
+
+2005-04-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * check-cracklib.pl: external password verifier sample
+
+ * password_quality.c (kadm5_add_passwd_quality_verifier): if NULL
+ is passed in, load defaults
+
+2005-04-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * password_quality.c: add an end tag to the external password
+ quality check protocol
+
+2005-04-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * password_quality.c: add external passsword quality check builtin
+ module
+
+ [password_quality]
+ policies = external-check
+ external-program = /bin/false
+
+ To approve password a, make the test program return APPROVED on
+ stderr and fail with exit code 0.
+
+2004-10-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: bump version to 7:7:0 and 6:5:2
+
+ * default_keys.c (parse_file): use hdb_generate_key_set
+
+ * keys.c,set_keys.c: Move keyset parsing and password based keyset
+ generation into hdb. Requested by Andrew Bartlett <abartlet@samba.org>
+ for hdb-ldb backend.
+
+2004-09-23 Johan Danielsson <joda@pdc.kth.se>
+
+ * ipropd_master.c: add help strings to some options
+
+2004-09-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * chpass_s.c: deal with changed prototype for _kadm5_free_keys
+
+ * keys.c (_kadm5_free_keys): change prototype, make it use
+ krb5_context instead of a kadm5_server_context
+
+ * set_keys.c (parse_key_set): do way with static returning
+ (function) static variable and returned allocated memory
+ (_kadm5_generate_key_set): free enctypes returned by parse_key_set
+
+2004-09-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * set_keys.c: Fix memory leak, don't return stack variables From
+ Andrew Bartlett
+
+ * set_keys.c: make all_etypes const and move outside function to
+ avoid returning data on stack
+
+2004-08-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * acl.c (fetch_acl): use " \t\n" instead of just "\n" for the
+ delim of the third element, this is so we can match
+ "foo@REALM<SPC>all<SPC><SPC>*@REALM", before it just matched
+ "foo@REALM<SPC>all<SPC>*@REALM", but that is kind of lucky since
+ what really happen was that the last <SPC> was stamped out, and
+ the it never strtok_r never needed to parse over it.
+
+2004-08-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * set_keys.c (_kadm5_generate_key_set): since arcfour-hmac-md5 is
+ without salting, some people tries to add the string
+ "arcfour-hmac-md5" when they really should have used
+ "arcfour-hmac-md5:pw-salt", help them and add glue for that
+
+2004-08-18 Johan Danielsson <joda@pdc.kth.se>
+
+ * ipropd_slave.c: add --detach
+
+2004-07-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ad.c: use new tsasl interface remove debug printf add upn to
+ computer-accounts
+
+2004-06-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ad.c: implement kadm5_ad_init_with_password_ctx set more error
+ strings
+
+2004-06-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: man_MANS = kadm5_pwcheck.3
+
+ * kadm5_pwcheck.3: document new password quality api
+
+ * password_quality.c: new password check interface (old still
+ supported)
+
+ * kadm5-pwcheck.h: new password check interface
+
+2004-06-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ipropd_master.c (main): process all slaves, not just up to the
+ last slave sending data
+ (bug report from Björn Sandell <biorn@dce.chalmers.se>)
+ (*): only send one ARE_YOU_THERE
+
+2004-06-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ad.c: use krb5_set_password_using_ccache
+
+2004-06-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ad.c: try handle spn's better
+
+2004-05-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ad.c: add expiration time
+
+ * ad.c: add modify operations
+
+ * ad.c: handle create and delete
+
+2004-05-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ad.c: more code for get, handle attributes
+
+ * ad.c: more code for get, handle time stamps and bad password
+ counter
+
+ * ad.c: more code for get, only fetches kvno for now
+
+2004-05-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ad.c: add support for tsasl
+
+ * private.h: add kadm5_ad_context
+
+ * ipropd_master.c (prop_one): store the opcode in the begining of
+ the blob, not the end
+
+ * ad.c: try all ldap servers in dns, generate a random password,
+ base64(random_block(64)), XXX must make it support other then
+ ARCFOUR
+
+ * ad.c: framework for windows AD backend
+
+2004-03-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * create_s.c (kadm5_s_create_principal): remove old XXX command
+ and related code, _kadm5_set_keys will do all this now
+
+2004-02-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * set_keys.c (_kadm5_set_keys_randomly): make sure enctype to copy
+ enctype for des keys From: Andrew Bartlett <abartlet@samba.org>
+
+ * create_s.c (kadm5_s_create_principal_with_key): don't call
+ _kadm5_set_keys2, create_principal will do that for us. Set kvno
+ to 1.
+
+ * chpass_s.c (change): bump kvno
+ (kadm5_s_chpass_principal_with_key): bump kvno
+
+ * randkey_s.c (kadm5_s_randkey_principal): bump kvno
+
+ * set_keys.c (_kadm5_set_*): don't change the kvno, let the callee
+ to that
+
+2003-12-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * chpass_s.c (change): fix same-password-again by decrypting keys
+ and setting an error code From: Buck Huppmann <buckh@pobox.com>
+
+2003-12-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_c.c (_kadm5_c_init_context): catch errors from strdup and
+ other krb5_ functions
+
+2003-12-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rename_s.c (kadm5_s_rename_principal): allow principal to change
+ realm From Panasas Inc
+
+2003-12-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * destroy_c.c (kadm5_c_destroy): fix memory leaks, From Panasas,
+ Inc
+
+2003-11-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * iprop.h: don't include <krb5-private.h>
+
+ * ipropd_slave.c: stop using krb5 lib private byte-frobbing
+ functions and replace them with with krb5_storage
+
+ * ipropd_master.c: stop using krb5 lib private byte-frobbing
+ functions and replace them with with krb5_storage
+
+2003-11-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ipropd_slave.c (receive_loop): when seeking over the entries we
+ already have, skip over the trailer. From: Jeffrey Hutzelman
+ <jhutz@cmu.edu>
+
+ * dump_log.c,ipropd_master.c,ipropd_slave.c,
+ replay_log.c,truncate_log.c: parse kdc.conf
+ From: Jeffrey Hutzelman <jhutz@cmu.edu>
+
+2003-10-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: += test_pw_quality
+
+ * test_pw_quality.c: test program for verifying password quality
+ function
+
+2003-09-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add and enable check program default_keys
+
+ * default_keys.c: test program for _kadm5_generate_key_set
+
+ * init_c.c: use
+ krb5_get_init_creds_opt_alloc/krb5_get_init_creds_opt_free
+
+2003-08-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * set_keys.c (_kadm5_set_keys_randomly): remove dup return
+
+ * ipropd_master.c (main): make sure current_version is initialized
+
+2003-08-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * set_keys.c: use default_keys for the both random keys and
+ password derived keys if its defined
+
+2003-07-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ipropd_slave.c (receive_everything): switch close and rename
+ From: Alf Wachsmann <alfw@SLAC.Stanford.EDU>
+
+2003-07-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * iprop.h, ipropd_master.c, ipropd_slave.c:
+ Add probing from the server that the client is still there, also
+ make the client check that the server is probing.
+
+2003-07-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * truncate_log.c (main): add missing ``if (ret)''
+
+2003-06-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * set_keys.c (make_keys): add AES support
+
+ * set_keys.c: fix off by one in the aes case, pointed out by Ken
+ Raeburn
+
+2003-04-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * set_keys.c (_kadm5_set_keys_randomly): add
+ ETYPE_AES256_CTS_HMAC_SHA1_96 key when configuried with aes
+ support
+
+2003-04-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * send_recv.c: check return values from krb5_data_alloc
+ * log.c: check return values from krb5_data_alloc
+
+2003-04-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * dump_log.c (print_entry): check return values from
+ krb5_data_alloc
+
+2003-04-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * init_c.c (kadm_connect): if a context realm was passed in, use
+ that to form the kadmin/admin principal
+
+2003-03-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ipropd_master.c (main): make sure we don't consider dead slave
+ for select processing
+ (write_stats): use slave_stats_file variable,
+ check return value of strftime
+ (args): allow specifying slave stats file
+ (slave_dead): close the fd when the slave dies
+
+2002-10-21 Johan Danielsson <joda@pdc.kth.se>
+
+ * ipropd_slave.c (from Derrick Brashear): Propagating a large
+ database without this means the slave kdcs can get erroneous
+ HDB_NOENTRY and return the resulting errors. This creates a new db
+ handle, populates it, and moves it into place.
+
+2002-08-26 Assar Westerlund <assar@kth.se>
+
+ * ipropd_slave.c (receive_everything): type-correctness calling
+ _krb5_get_int
+
+ * context_s.c (find_db_spec): const-correctness in parameters to
+ krb5_config_get_next
+
+2002-08-16 Johan Danielsson <joda@pdc.kth.se>
+
+ * private.h: rename header file flag macro
+
+ * Makefile.am: generate kadm5-{protos,private}.h
+
+2002-08-15 Johan Danielsson <joda@pdc.kth.se>
+
+ * ipropd_master.c: check return value of krb5_sockaddr2address
+
+2002-07-04 Johan Danielsson <joda@pdc.kth.se>
+
+ * ipropd_master.c: handle slaves that come and go; add status
+ reporting (both from Love)
+
+ * iprop.h: KADM5_SLAVE_STATS
+
+2002-03-25 Jacques Vidrine <n@nectar.com>
+
+ * init_c.c (get_cred_cache): bug fix: the default credentials
+ cache was not being used if a client name was specified.
+
+2002-03-25 Johan Danielsson <joda@pdc.kth.se>
+
+ * init_c.c (get_cred_cache): when getting the default_client from
+ the cred cache, make sure the instance part is "admin"; this
+ should require fewer uses of -p
+
+2002-03-11 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkadm5srv_la_LDFLAGS): set version to 7:5:0
+ (libkadm5clnt_la_LDFLAGS): set version to 6:3:2
+
+2002-02-08 Johan Danielsson <joda@pdc.kth.se>
+
+ * init_c.c: we have to create our own param struct before
+ marshaling
+
+2001-09-05 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: link with LIB_pidfile
+
+ * iprop.h: include util.h for pidfile
+
+2001-08-31 Assar Westerlund <assar@sics.se>
+
+ * ipropd_slave.c (main): syslog with the correct name
+
+2001-08-30 Jacques Vidrine <n@nectar.com>
+
+ * ipropd_slave.c, ipropd_master.c (main): call pidfile
+
+2001-08-28 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkadm5srv_la_LDFLAGS): set version to 7:4:0
+
+2001-08-24 Assar Westerlund <assar@sics.se>
+
+ * acl.c (fetch_acl): do not return bogus flags and re-organize
+ function
+
+ * Makefile.am: rename variable name to avoid error from current
+ automake
+
+2001-08-13 Johan Danielsson <joda@pdc.kth.se>
+
+ * set_keys.c: add easier afs configuration, defaulting to the
+ local realm in lower case; also try to remove duplicate salts
+
+2001-07-12 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: add required library dependencies
+
+2001-07-03 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkadm5clnt_la_LDFLAGS): set version to 6:2:2
+
+2001-06-29 Johan Danielsson <joda@pdc.kth.se>
+
+ * init_c.c: call krb5_get_init_creds_opt_set_default_flags
+
+2001-02-19 Johan Danielsson <joda@pdc.kth.se>
+
+ * replay_log.c: add --{start-end}-version flags to replay just
+ part of the log
+
+2001-02-15 Assar Westerlund <assar@sics.se>
+
+ * ipropd_master.c (main): fix select-loop to decrement ret
+ correctly. from "Brandon S. Allbery KF8NH" <allbery@ece.cmu.edu>
+
+2001-01-30 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump versions
+
+2000-12-31 Assar Westerlund <assar@sics.se>
+
+ * init_s.c (*): handle krb5_init_context failure consistently
+ * init_c.c (init_context): handle krb5_init_context failure
+ consistently
+
+2000-12-11 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkadm5srv_la_LDFLAGS): bump version to 7:2:0
+
+2000-11-16 Assar Westerlund <assar@sics.se>
+
+ * set_keys.c (make_keys): clean-up salting loop and try not to
+ leak memory
+
+ * ipropd_master.c (main): check for fd's being too large to select
+ on
+
+2000-08-16 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkadm5srv_la_LDFLAGS): bump version to 7:1:0
+
+2000-08-10 Assar Westerlund <assar@sics.se>
+
+ * acl.c (fetch_acl): fix wrong cases, use krb5_principal_match
+
+2000-08-07 Assar Westerlund <assar@sics.se>
+
+ * ipropd_master.c (main): ignore SIGPIPE
+
+2000-08-06 Assar Westerlund <assar@sics.se>
+
+ * ipropd_slave.c (receive_everything): make `fd' an int instead of
+ a pointer. From Derrick J Brashear <shadow@dementia.org>
+
+2000-08-04 Johan Danielsson <joda@pdc.kth.se>
+
+ * admin.h: change void** to void*
+
+2000-07-25 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: bump versions to 7:0:0 and 6:0:2
+
+2000-07-24 Assar Westerlund <assar@sics.se>
+
+ * log.c (kadm5_log_get_version): rename kadm5_log_get_version_fd
+ and make a new that takes a context
+ (kadm5_log_nop): add logging of missing lengths
+ (kadm5_log_truncate): new function
+
+ * dump_log.c (print_entry): update and correct
+ * randkey_s.c: call _kadm5_bump_pw_expire
+ * truncate_log.c: new program for truncating the log
+ * Makefile.am (sbin_PROGRAMS): add truncate_log
+ (C_SOURCES): add bump_pw_expire.c
+ * bump_pw_expire.c: new function for extending password expiration
+
+2000-07-22 Assar Westerlund <assar@sics.se>
+
+ * keys.c: new file with _kadm5_free_keys, _kadm5_init_keys
+
+ * set_keys.c (free_keys, init_keys): elevate to internal kadm5
+ functions
+
+ * chpass_s.c (kadm5_s_chpass_principal_cond): new function
+ * Makefile.am (C_SOURCES): add keys.c
+ * init_c.c: remove unused variable and handle some parameters
+ being NULL
+
+2000-07-22 Johan Danielsson <joda@pdc.kth.se>
+
+ * ipropd_slave.c: use krb5_read_priv_message
+
+ * ipropd_master.c: use krb5_{read,write}_priv_message
+
+ * init_c.c: use krb5_write_priv_message
+
+2000-07-11 Johan Danielsson <joda@pdc.kth.se>
+
+ * ipropd_slave.c: no need to call gethostname, since
+ sname_to_principal will
+
+ * send_recv.c: assert that we have a connected socket
+
+ * get_princs_c.c: call _kadm5_connect
+
+ * rename_c.c: call _kadm5_connect
+
+ * randkey_c.c: call _kadm5_connect
+
+ * privs_c.c: call _kadm5_connect
+
+ * modify_c.c: call _kadm5_connect
+
+ * get_c.c: call _kadm5_connect
+
+ * delete_c.c: call _kadm5_connect
+
+ * create_c.c: call _kadm5_connect
+
+ * chpass_c.c: call _kadm5_connect
+
+ * private.h: add more fields to client context; remove prototypes
+
+ * admin.h: remove prototypes
+
+ * kadm5-protos.h: move public prototypes here
+
+ * kadm5-private.h: move private prototypes here
+
+ * init_c.c: break out connection code to separate function, and
+ defer calling it until we actually do something
+
+2000-07-07 Assar Westerlund <assar@sics.se>
+
+ * set_keys.c (make_keys): also support `[kadmin]use_v4_salt' for
+ backwards compatability
+
+2000-06-26 Johan Danielsson <joda@pdc.kth.se>
+
+ * set_keys.c (_kadm5_set_keys): rewrite this to be more easily
+ adaptable to different salts
+
+2000-06-19 Johan Danielsson <joda@pdc.kth.se>
+
+ * get_s.c: pa_* -> KRB5_PADATA_*
+
+2000-06-16 Assar Westerlund <assar@sics.se>
+
+ * ipropd_slave.c: change default keytab to default keytab (as in
+ typically FILE:/etc/krb5.keytab)
+
+2000-06-08 Assar Westerlund <assar@sics.se>
+
+ * ipropd_slave.c: bug fixes, for actually writing the full dump to
+ the database. based on a patch from Love <lha@stacken.kth.se>
+
+2000-06-07 Assar Westerlund <assar@sics.se>
+
+ * acl.c: add support for patterns of principals
+ * log.c (kadm5_log_replay_create): handle more NULL pointers
+ (should they really happen?)
+ * log.c (kadm5_log_replay_modify): handle max_life == NULL and
+ max_renew == NULL
+
+ * ipropd_master.c: use syslog. be less verbose
+ * ipropd_slave.c: use syslog
+
+2000-06-05 Assar Westerlund <assar@sics.se>
+
+ * private.h (kadm_ops): add kadm_nop more prototypes
+ * log.c (kadm5_log_set_version, kadm5_log_reinit, kadm5_log_nop,
+ kadm5_log_replay_nop): add
+ * ipropd_slave.c: and some more improvements
+ * ipropd_master.c: lots of improvements
+ * iprop.h (IPROP_PORT, IPROP_SERVICE): add
+ (iprop_cmd): add new commands
+
+ * dump_log.c: add nop
+
+2000-05-15 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkadm5clnt_la_LDFLAGS): set version to 5:1:1
+
+2000-05-12 Assar Westerlund <assar@sics.se>
+
+ * get_s.c (kadm5_s_get_principal): set life, rlife to INT_MAX as a
+ fallback. handle not having any creator.
+ * destroy_s.c (kadm5_s_destroy): free all allocated memory
+ * context_s.c (set_field): free variable if it's already set
+ (find_db_spec): malloc space for all strings
+
+2000-04-05 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (LDADD): add LIB_openldap
+
+2000-04-03 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkadm5srv_la_LDFLAGS): set version to 6:0:1
+ (libkadm5clnt_la_LDFLAGS): set version to 5:0:1
+
+2000-03-24 Assar Westerlund <assar@sics.se>
+
+ * set_keys.c (_kadm5_set_keys2): rewrite
+ (_kadm5_set_keys3): add
+
+ * private.h (struct kadm_func): add chpass_principal_with_key
+ * init_c.c (set_funcs): add chpass_principal_with_key
+
+2000-03-23 Assar Westerlund <assar@sics.se>
+
+ * context_s.c (set_funcs): add chpass_principal_with_key
+ * common_glue.c (kadm5_chpass_principal_with_key): add
+ * chpass_s.c: comment-ize and change calling convention for
+ _kadm5_set_keys*
+ * chpass_c.c (kadm5_c_chpass_principal_with_key): add
+
+2000-02-07 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkadm5clnt_la_LDFLAGS): set version to 4:2:0
+
+2000-01-28 Assar Westerlund <assar@sics.se>
+
+ * init_c.c (get_new_cache): make sure to request non-forwardable,
+ non-proxiable
+
+2000-01-06 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkadm5srv.la): bump version to 5:1:0
+
+ * context_s.c (_kadm5_s_init_context): handle params == NULL
+
+1999-12-26 Assar Westerlund <assar@sics.se>
+
+ * get_s.c (kadm5_s_get_principal): handle modified_by->principal
+ == NULL
+
+1999-12-20 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkadm5clnt_la_LDFLAGS): bump version to 4:1:0
+
+ * init_c.c (_kadm5_c_init_context): handle getting back port
+ number from admin host
+ (kadm5_c_init_with_context): remove `proto/' part before doing
+ getaddrinfo()
+
+1999-12-06 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 5:0:0 and 4:0:0
+
+ * init_c.c (kadm5_c_init_with_context): don't use unitialized
+ stuff
+
+1999-12-04 Assar Westerlund <assar@sics.se>
+
+ * replay_log.c: adapt to changed kadm5_log_foreach
+
+ * log.c (kadm5_log_foreach): change to take a
+ `kadm5_server_context'
+
+ * init_c.c: use krb5_warn{,x}
+
+ * dump_log.c: adapt to changed kadm5_log_foreach
+
+ * init_c.c: re-write to use getaddrinfo
+ * Makefile.am (install-build-headers): add dependency
+
+1999-12-03 Johan Danielsson <joda@pdc.kth.se>
+
+ * log.c (kadm5_log_foreach): pass context
+
+ * dump_log.c: print more interesting things
+
+1999-12-02 Johan Danielsson <joda@pdc.kth.se>
+
+ * ipropd_master.c (process_msg): check for short reads
+
+1999-11-25 Assar Westerlund <assar@sics.se>
+
+ * modify_s.c (kadm5_s_modify_principal): support key_data
+ (kadm5_s_modify_principal_with_key): remove
+
+ * admin.h (kadm5_s_modify_principal_with_key): remove
+
+1999-11-20 Assar Westerlund <assar@sics.se>
+
+ * context_s.c (find_db_spec): ugly cast work-around.
+
+1999-11-14 Assar Westerlund <assar@sics.se>
+
+ * context_s.c (_kadm5_s_init_context): call krb5_add_et_list so
+ that we aren't dependent on the layout of krb5_context_data
+ * init_c.c (_kadm5_c_init_context): call krb5_add_et_list so that
+ we aren't dependent on the layout of krb5_context_data
+
+1999-11-13 Assar Westerlund <assar@sics.se>
+
+ * password_quality.c (kadm5_setup_passwd_quality_check): use
+ correct types for function pointers
+
+1999-11-09 Johan Danielsson <joda@pdc.kth.se>
+
+ * randkey_s.c: always bail out if the fetch fails
+
+ * admin.h (kadm5_config_params): remove fields we're not using
+
+ * ipropd_slave.c: allow passing a realm
+
+ * ipropd_master.c: allow passing a realm
+
+ * dump_log.c: allow passing a realm
+
+ * acl.c: correctly get acl file
+
+ * private.h (kadm5_server_context): add config_params struct and
+ remove acl_file; bump protocol version number
+
+ * marshall.c: marshalling of config parameters
+
+ * init_c.c (kadm5_c_init_with_context): try to cope with old
+ servers
+
+ * init_s.c (kadm5_s_init_with_context): actually use some passed
+ values
+
+ * context_s.c (_kadm5_s_init_context): get dbname, acl_file, and
+ stash_file from the config parameters, try to figure out these if
+ they're not provided
+
+1999-11-05 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (install-build-headers): use `cp' instead of
+ INSTALL_DATA
+
+1999-11-04 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 4:0:0 and 3:0:0 (they access fields
+ directly in libkrb5's context - bad functions)
+
+ * set_keys.c (_kadm5_set_keys_randomly): set enctypes correctly in
+ the copied keys
+
+1999-10-20 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version of kadm5srv to 3:0:2 (new password
+ quality functions).
+ set version of kdam5clnt to 2:1:1 (no interface changes)
+
+ * Makefile.am (LDADD): add $(LIB_dlopen)
+
+1999-10-17 Assar Westerlund <assar@sics.se>
+
+ * randkey_s.c (kadm5_s_randkey_principal): use
+ _kadm5_set_keys_randomly
+
+ * set_keys.c (free_keys): free more memory
+ (_kadm5_set_keys): a little bit more generic
+ (_kadm5_set_keys_randomly): new function for setting random keys.
+
+1999-10-14 Assar Westerlund <assar@sics.se>
+
+ * set_keys.c (_kadm5_set_keys): ignore old keys when setting new
+ ones and always add 3 DES keys and one 3DES key
+
+1999-10-03 Assar Westerlund <assar@sics.se>
+
+ * init_c.c (_kadm5_c_init_context): use `krb5_get_krb_admin_hst'.
+ check return value from strdup
+
+1999-09-26 Assar Westerlund <assar@sics.se>
+
+ * acl.c (_kadm5_privs_to_string): forgot one strcpy_truncate ->
+ strlcpy
+
+1999-09-24 Johan Danielsson <joda@pdc.kth.se>
+
+ * dump_log.c: remove unused `optind'
+
+ * replay_log.c: remove unused `optind'
+
+1999-09-13 Assar Westerlund <assar@sics.se>
+
+ * chpass_c.c (kadm5_c_chpass_principal): new _kadm5_client_recv
+
+ * send_recv.c (_kadm5_client_recv): return result in a `krb5_data'
+ so that we avoid copying it and don't need to dimension in
+ advance. change all callers.
+
+1999-09-10 Assar Westerlund <assar@sics.se>
+
+ * password_quality.c: new file
+
+ * admin.h
+ (kadm5_setup_passwd_quality_check,kadm5_check_password_quality):
+ add prototypes
+
+ * Makefile.am (S_SOURCES): add password_quality.c
+
+1999-07-26 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: update versions to 2:0:1
+
+1999-07-24 Assar Westerlund <assar@sics.se>
+
+ * ent_setup.c (_kadm5_setup_entry): make princ_expire_time == 0
+ and pw_expiration == 0 mean never
+
+1999-07-22 Assar Westerlund <assar@sics.se>
+
+ * log.c (kadm5_log_flush): extra cast
+
+1999-07-07 Assar Westerlund <assar@sics.se>
+
+ * marshall.c (store_principal_ent): encoding princ_expire_time and
+ pw_expiration in correct order
+
+1999-06-28 Assar Westerlund <assar@sics.se>
+
+ * randkey_s.c (kadm5_s_randkey_principal): nuke old mkvno,
+ otherwise hdb will think that the new random keys are already
+ encrypted which will cause lots of confusion later.
+
+1999-06-23 Assar Westerlund <assar@sics.se>
+
+ * ent_setup.c (_kadm5_setup_entry): handle 0 == unlimited
+ correctly. From Michal Vocu <michal@karlin.mff.cuni.cz>
+
+1999-06-15 Assar Westerlund <assar@sics.se>
+
+ * init_c.c (get_cred_cache): use get_default_username
+
+1999-05-23 Assar Westerlund <assar@sics.se>
+
+ * create_s.c (create_principal): if there's no default entry the
+ mask should be zero.
+
+1999-05-21 Assar Westerlund <assar@sics.se>
+
+ * init_c.c (get_cred_cache): use $USERNAME
+
+1999-05-17 Johan Danielsson <joda@pdc.kth.se>
+
+ * init_c.c (get_cred_cache): figure out principal
+
+1999-05-05 Johan Danielsson <joda@pdc.kth.se>
+
+ * send_recv.c: cleanup _kadm5_client_{send,recv}
+
+1999-05-04 Assar Westerlund <assar@sics.se>
+
+ * set_keys.c (_kadm5_set_keys2): don't check the recently created
+ memory for NULL pointers
+
+ * private.h (_kadm5_setup_entry): change prototype
+
+ * modify_s.c: call new _kadm5_setup_entry
+
+ * ent_setup.c (_kadm5_setup_entry): change so that it takes three
+ masks, one for what bits to set and one for each of principal and
+ def containing the bits that are set there.
+
+ * create_s.c: call new _kadm5_setup_entry
+
+ * create_s.c (get_default): check return value
+ (create_principal): send wider mask to _kadm5_setup_entry
+
+1999-05-04 Johan Danielsson <joda@pdc.kth.se>
+
+ * send_recv.c (_kadm5_client_recv): handle arbitrarily sized
+ packets, check for errors
+
+ * get_c.c: check for failure from _kadm5_client_{send,recv}
+
+1999-05-04 Assar Westerlund <assar@sics.se>
+
+ * init_c.c (get_new_cache): don't abort when interrupted from
+ password prompt
+
+ * destroy_c.c (kadm5_c_destroy): check if we should destroy the
+ auth context
+
+1999-05-03 Johan Danielsson <joda@pdc.kth.se>
+
+ * chpass_s.c: fix arguments to _kadm5_set_keys2
+
+ * private.h: proto
+
+ * set_keys.c: clear mkvno
+
+ * rename_s.c: add flags to fetch and store; seal keys before
+ logging
+
+ * randkey_s.c: add flags to fetch and store; seal keys before
+ logging
+
+ * modify_s.c: add flags to fetch and store; seal keys before
+ logging
+
+ * log.c: add flags to fetch and store; seal keys before logging
+
+ * get_s.c: add flags to fetch and store; seal keys before logging
+
+ * get_princs_s.c: add flags to fetch and store; seal keys before
+ logging
+
+ * delete_s.c: add flags to fetch and store; seal keys before
+ logging
+
+ * create_s.c: add flags to fetch and store; seal keys before
+ logging
+
+ * chpass_s.c: add flags to fetch and store; seal keys before
+ logging
+
+ * Makefile.am: remove server.c
+
+ * admin.h: add prototypes
+
+ * ent_setup.c (_kadm5_setup_entry): set key_data
+
+ * set_keys.c: add _kadm5_set_keys2 to sey keys from key_data
+
+ * modify_s.c: add kadm5_s_modify_principal_with_key
+
+ * create_s.c: add kadm5_s_create_principal_with_key
+
+ * chpass_s.c: add kadm5_s_chpass_principal_with_key
+
+ * kadm5_locl.h: move stuff to private.h
+
+ * private.h: move stuff from kadm5_locl.h
+
diff --git a/third_party/heimdal/lib/kadm5/Makefile.am b/third_party/heimdal/lib/kadm5/Makefile.am
new file mode 100644
index 0000000..a6151d5
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/Makefile.am
@@ -0,0 +1,230 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+libkadm5srv_la_CPPFLAGS = -I$(srcdir)/../krb5
+libkadm5clnt_la_CPPFLAGS = -I$(srcdir)/../krb5
+
+lib_LTLIBRARIES = libkadm5srv.la libkadm5clnt.la
+libkadm5srv_la_LDFLAGS = -version-info 8:1:0
+libkadm5clnt_la_LDFLAGS = -version-info 7:1:0
+
+if versionscript
+libkadm5clnt_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script-client.map
+libkadm5srv_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+endif
+
+sbin_PROGRAMS = iprop-log
+check_PROGRAMS = default_keys
+noinst_PROGRAMS = test_pw_quality
+
+noinst_LTLIBRARIES = sample_passwd_check.la sample_hook.la
+
+sample_passwd_check_la_SOURCES = sample_passwd_check.c
+sample_passwd_check_la_LDFLAGS = -module
+
+sample_hook_la_SOURCES = sample_hook.c
+sample_hook_la_LDFLAGS = -module
+
+libkadm5srv_la_LIBADD = \
+ $(LIB_com_err) ../krb5/libkrb5.la \
+ ../hdb/libhdb.la $(LIBADD_roken)
+libkadm5clnt_la_LIBADD = \
+ $(LIB_com_err) ../krb5/libkrb5.la $(LIBADD_roken)
+
+libexec_PROGRAMS = ipropd-master ipropd-slave
+
+default_keys_SOURCES = default_keys.c
+default_keys_CPPFLAGS = -I$(srcdir)/../krb5
+
+kadm5includedir = $(includedir)/kadm5
+buildkadm5include = $(buildinclude)/kadm5
+
+dist_kadm5include_HEADERS = admin.h private.h kadm5-hook.h kadm5-pwcheck.h
+dist_kadm5include_HEADERS += $(srcdir)/kadm5-protos.h $(srcdir)/kadm5-private.h
+
+nodist_kadm5include_HEADERS = kadm5_err.h
+
+install-build-headers:: $(dist_kadm5include_HEADERS) $(nodist_kadm5include_HEADERS)
+ @foo='$(dist_kadm5include_HEADERS) $(nodist_kadm5include_HEADERS)'; \
+ for f in $$foo; do \
+ f=`basename $$f`; \
+ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \
+ else file="$$f"; fi; \
+ if cmp -s $$file $(buildkadm5include)/$$f 2> /dev/null ; then \
+ : ; else \
+ echo "cp $$file $(buildkadm5include)/$$f";\
+ cp $$file $(buildkadm5include)/$$f; \
+ fi ; \
+ done
+
+dist_libkadm5clnt_la_SOURCES = \
+ ad.c \
+ chpass_c.c \
+ client_glue.c \
+ common_glue.c \
+ create_c.c \
+ delete_c.c \
+ destroy_c.c \
+ flush_c.c \
+ free.c \
+ get_c.c \
+ get_princs_c.c \
+ init_c.c \
+ kadm5_locl.h \
+ marshall.c \
+ modify_c.c \
+ private.h \
+ privs_c.c \
+ prune_c.c \
+ randkey_c.c \
+ rename_c.c \
+ send_recv.c \
+ admin.h
+
+nodist_libkadm5clnt_la_SOURCES = \
+ kadm5_err.c \
+ kadm5_err.h
+
+dist_libkadm5srv_la_SOURCES = \
+ acl.c \
+ admin.h \
+ bump_pw_expire.c \
+ chpass_s.c \
+ common_glue.c \
+ context_s.c \
+ create_s.c \
+ delete_s.c \
+ destroy_s.c \
+ ent_setup.c \
+ error.c \
+ flush_s.c \
+ free.c \
+ get_princs_s.c \
+ get_s.c \
+ init_s.c \
+ kadm5_locl.h \
+ keys.c \
+ log.c \
+ marshall.c \
+ modify_s.c \
+ password_quality.c \
+ private.h \
+ privs_s.c \
+ prune_s.c \
+ randkey_s.c \
+ rename_s.c \
+ server_glue.c \
+ server_hooks.c \
+ setkey3_s.c \
+ set_keys.c \
+ set_modifier.c \
+ admin.h
+
+nodist_libkadm5srv_la_SOURCES = \
+ kadm5_err.c \
+ kadm5_err.h
+
+libkadm5srv_la_DEPENDENCIES = \
+ version-script.map
+
+dist_iprop_log_SOURCES = iprop-log.c
+nodist_iprop_log_SOURCES = iprop-commands.c
+
+ipropd_master_SOURCES = ipropd_master.c ipropd_common.c iprop.h kadm5_locl.h
+ipropd_master_CPPFLAGS = -I$(srcdir)/../krb5
+
+ipropd_slave_SOURCES = ipropd_slave.c ipropd_common.c iprop.h kadm5_locl.h
+ipropd_slave_CPPFLAGS = -I$(srcdir)/../krb5
+
+man_MANS = kadm5_pwcheck.3 iprop.8 iprop-log.8
+
+LDADD = \
+ libkadm5srv.la \
+ $(top_builddir)/lib/hdb/libhdb.la \
+ $(top_builddir)/lib/krb5/libkrb5.la \
+ $(top_builddir)/lib/asn1/libasn1.la \
+ $(LIB_hcrypto) \
+ $(LIB_roken) \
+ $(DB3LIB) $(DB1LIB) $(LMDBLIB) $(NDBMLIB) \
+ $(LIB_dlopen) \
+ $(LIB_pidfile)
+
+
+iprop_log_LDADD = \
+ libkadm5srv.la \
+ $(top_builddir)/lib/hdb/libhdb.la \
+ $(top_builddir)/lib/krb5/libkrb5.la \
+ $(top_builddir)/lib/asn1/libasn1.la \
+ $(LIB_hcrypto) \
+ $(top_builddir)/lib/sl/libsl.la \
+ $(LIB_readline) \
+ $(LIB_roken) \
+ $(DB3LIB) $(DB1LIB) $(LMDBLIB) $(NDBMLIB) \
+ $(LIB_dlopen) \
+ $(LIB_pidfile)
+
+iprop_log_CPPFLAGS = -I$(srcdir)/../krb5
+
+iprop-commands.c iprop-commands.h: iprop-commands.in
+ $(SLC) $(srcdir)/iprop-commands.in
+
+$(libkadm5srv_la_OBJECTS): kadm5_err.h
+$(libkadm5clnt_la_OBJECTS): kadm5_err.h
+$(iprop_log_OBJECTS): iprop-commands.h
+
+client_glue.lo server_glue.lo: $(srcdir)/common_glue.c
+
+CLEANFILES = kadm5_err.c kadm5_err.h iprop-commands.h iprop-commands.c
+
+# to help stupid solaris make
+
+kadm5_err.h: kadm5_err.et
+
+ALL_OBJECTS = $(libkadm5clnt_la_OBJECTS)
+ALL_OBJECTS += $(libkadm5srv_la_OBJECTS)
+ALL_OBJECTS += $(ipropd_master_OBJECTS)
+ALL_OBJECTS += $(ipropd_slave_OBJECTS)
+ALL_OBJECTS += $(iprop_log_OBJECTS)
+ALL_OBJECTS += $(test_pw_quality_OBJECTS)
+ALL_OBJECTS += $(sample_passwd_check_la_OBJECTS)
+ALL_OBJECTS += $(sample_hook_la_OBJECTS)
+ALL_OBJECTS += $(default_keys_OBJECTS)
+
+$(ALL_OBJECTS): $(srcdir)/kadm5-protos.h $(srcdir)/kadm5-private.h
+$(ALL_OBJECTS): kadm5_err.h
+
+KADM5_PROTOS_SRCS = $(dist_libkadm5clnt_la_SOURCES)
+KADM5_PROTOS_SRCS += $(dist_libkadm5srv_la_SOURCES)
+
+proto_opts = -q -R '^(_|kadm5_c_|kadm5_s_|kadm5_log)' -P comment
+$(srcdir)/kadm5-protos.h: $(KADM5_PROTOS_SRCS)
+ cd $(srcdir); perl ../../cf/make-proto.pl $(proto_opts) \
+ -o kadm5-protos.h \
+ $(dist_libkadm5clnt_la_SOURCES) \
+ $(dist_libkadm5srv_la_SOURCES) \
+ || rm -f kadm5-protos.h
+
+$(srcdir)/kadm5-private.h: $(KADM5_PROTOS_SRCS)
+ cd $(srcdir); perl ../../cf/make-proto.pl $(proto_opts) \
+ -p kadm5-private.h \
+ $(dist_libkadm5clnt_la_SOURCES) \
+ $(dist_libkadm5srv_la_SOURCES) \
+ || rm -f kadm5-private.h
+
+EXTRA_DIST = \
+ NTMakefile \
+ iprop-log-version.rc \
+ ipropd-master-version.rc \
+ ipropd-slave-version.rc \
+ libkadm5srv-version.rc \
+ libkadm5srv-exports.def \
+ kadm5_err.et \
+ iprop-commands.in \
+ $(man_MANS) \
+ check-cracklib.pl \
+ flush.c \
+ sample_passwd_check.c \
+ sample_hook.c \
+ version-script.map \
+ version-script-client.map
diff --git a/third_party/heimdal/lib/kadm5/NTMakefile b/third_party/heimdal/lib/kadm5/NTMakefile
new file mode 100644
index 0000000..9357a7f
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/NTMakefile
@@ -0,0 +1,296 @@
+########################################################################
+#
+# Copyright (c) 2009, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\kadm5
+
+!include ../../windows/NTMakefile.w32
+
+dist_libkadm5clnt_la_SOURCES = \
+ ad.c \
+ chpass_c.c \
+ client_glue.c \
+ common_glue.c \
+ create_c.c \
+ delete_c.c \
+ destroy_c.c \
+ flush_c.c \
+ free.c \
+ get_c.c \
+ get_princs_c.c \
+ init_c.c \
+ kadm5_locl.h \
+ marshall.c \
+ modify_c.c \
+ private.h \
+ privs_c.c \
+ prune_c.c \
+ randkey_c.c \
+ rename_c.c \
+ send_recv.c \
+ kadm5-pwcheck.h \
+ admin.h \
+ kadm5-hook.h
+
+dist_libkadm5srv_la_SOURCES = \
+ acl.c \
+ admin.h \
+ bump_pw_expire.c \
+ chpass_s.c \
+ common_glue.c \
+ context_s.c \
+ create_s.c \
+ delete_s.c \
+ destroy_s.c \
+ ent_setup.c \
+ error.c \
+ flush_s.c \
+ free.c \
+ get_princs_s.c \
+ get_s.c \
+ init_s.c \
+ kadm5_locl.h \
+ keys.c \
+ log.c \
+ marshall.c \
+ modify_s.c \
+ password_quality.c \
+ private.h \
+ privs_s.c \
+ prune_s.c \
+ randkey_s.c \
+ rename_s.c \
+ server_glue.c \
+ server_hooks.c \
+ set_keys.c \
+ setkey3_s.c \
+ set_modifier.c \
+ kadm5-pwcheck.h \
+ admin.h \
+ kadm5-hook.h
+
+LIBKADM5CLNT_OBJS= \
+ $(OBJ)\ad.obj \
+ $(OBJ)\chpass_c.obj \
+ $(OBJ)\client_glue.obj \
+ $(OBJ)\common_glue.obj \
+ $(OBJ)\create_c.obj \
+ $(OBJ)\delete_c.obj \
+ $(OBJ)\destroy_c.obj \
+ $(OBJ)\flush_c.obj \
+ $(OBJ)\free.obj \
+ $(OBJ)\get_c.obj \
+ $(OBJ)\get_princs_c.obj \
+ $(OBJ)\init_c.obj \
+ $(OBJ)\marshall.obj \
+ $(OBJ)\modify_c.obj \
+ $(OBJ)\privs_c.obj \
+ $(OBJ)\prune_c.obj \
+ $(OBJ)\randkey_c.obj \
+ $(OBJ)\rename_c.obj \
+ $(OBJ)\send_recv.obj \
+ $(OBJ)\kadm5_err.obj
+
+LIBKADM5SRV_OBJS= \
+ $(OBJ)\acl.obj \
+ $(OBJ)\bump_pw_expire.obj \
+ $(OBJ)\chpass_s.obj \
+ $(OBJ)\common_glue.obj \
+ $(OBJ)\context_s.obj \
+ $(OBJ)\create_s.obj \
+ $(OBJ)\delete_s.obj \
+ $(OBJ)\destroy_s.obj \
+ $(OBJ)\ent_setup.obj \
+ $(OBJ)\error.obj \
+ $(OBJ)\flush_s.obj \
+ $(OBJ)\free.obj \
+ $(OBJ)\get_princs_s.obj \
+ $(OBJ)\get_s.obj \
+ $(OBJ)\init_s.obj \
+ $(OBJ)\keys.obj \
+ $(OBJ)\log.obj \
+ $(OBJ)\marshall.obj \
+ $(OBJ)\modify_s.obj \
+ $(OBJ)\password_quality.obj \
+ $(OBJ)\privs_s.obj \
+ $(OBJ)\prune_s.obj \
+ $(OBJ)\randkey_s.obj \
+ $(OBJ)\rename_s.obj \
+ $(OBJ)\server_glue.obj \
+ $(OBJ)\server_hooks.obj \
+ $(OBJ)\set_keys.obj \
+ $(OBJ)\setkey3_s.obj \
+ $(OBJ)\set_modifier.obj \
+ $(OBJ)\kadm5_err.obj
+
+
+proto_opts = -q -R "^(_|kadm5_c_|kadm5_s_|kadm5_log)" -P remove
+
+$(OBJ)\kadm5-protos.h: $(dist_libkadm5srv_la_SOURCES) $(dist_libkadm5clnt_la_SOURCES)
+ $(PERL) ..\..\cf\make-proto.pl $(proto_opts) \
+ -o $@ \
+ $(dist_libkadm5srv_la_SOURCES) \
+ $(dist_libkadm5clnt_la_SOURCES) \
+ || $(RM) $@
+
+$(OBJ)\kadm5-private.h: $(dist_libkadm5srv_la_SOURCES) $(dist_libkadm5clnt_la_SOURCES)
+ $(PERL) ..\..\cf\make-proto.pl $(proto_opts) \
+ -p $@ \
+ $(dist_libkadm5srv_la_SOURCES) \
+ $(dist_libkadm5clnt_la_SOURCES) \
+ || $(RM) $@
+
+$(OBJ)\iprop-commands.c $(OBJ)\iprop-commands.h: iprop-commands.in
+ cd $(OBJ)
+ $(CP) $(SRCDIR)\iprop-commands.in $(OBJ)
+ $(BINDIR)\slc.exe iprop-commands.in
+ cd $(SRCDIR)
+
+$(OBJ)\kadm5_err.h $(OBJ)kadm5_err.c: kadm5_err.et
+ cd $(OBJ)
+ $(BINDIR)\compile_et.exe $(SRCDIR)\kadm5_err.et
+ cd $(SRCDIR)
+
+$(KADM5INCDIR)\kadm5_err.h: $(OBJ)\kadm5_err.h
+
+KADM5INCDIR=$(INCDIR)\kadm5
+
+INCFILES=\
+ $(KADM5INCDIR)\kadm5_err.h \
+ $(KADM5INCDIR)\admin.h \
+ $(KADM5INCDIR)\private.h \
+ $(KADM5INCDIR)\kadm5-hook.h \
+ $(KADM5INCDIR)\kadm5-protos.h \
+ $(KADM5INCDIR)\kadm5-private.h \
+ $(OBJ)\iprop-commands.h
+
+SBINPROGRAMS=$(SBINDIR)\iprop-log.exe
+
+LIBEXECPROGRAMS=$(LIBEXECDIR)\ipropd-master.exe $(LIBEXECDIR)\ipropd-slave.exe
+
+EXELIBDEPS= \
+ $(LIBKADM5SRV) \
+ $(LIBROKEN) \
+ $(LIBHEIMDAL) \
+ $(LIBHDB) \
+ $(LIBSQLITE) \
+ $(LIBSL) \
+ $(LIBCOMERR) \
+ $(LIBVERS)
+
+$(SBINDIR)\iprop-log.exe: $(OBJ)\iprop-log.obj $(OBJ)\iprop-commands.obj $(EXELIBDEPS) \
+ $(OBJ)\iprop-log-version.res
+ $(EXECONLINK)
+ $(EXEPREP)
+
+$(LIBEXECDIR)\ipropd-master.exe: $(OBJ)\ipropd_master.obj $(OBJ)\ipropd_common.obj \
+ $(EXELIBDEPS) $(OBJ)\ipropd-master-version.res
+ $(EXECONLINK)
+ $(EXEPREP)
+
+$(LIBEXECDIR)\ipropd-slave.exe: $(OBJ)\ipropd_slave.obj $(OBJ)\ipropd_common.obj \
+ $(EXELIBDEPS) $(OBJ)\ipropd-slave-version.res
+ $(EXECONLINK)
+ $(EXEPREP)
+
+$(LIBKADM5CLNT): $(LIBKADM5CLNT_OBJS)
+ $(LIBCON)
+
+LIBKADM5SRVRES=$(OBJ)\libkadm5srv-version.res
+
+$(LIBKADM5SRV): $(BINDIR)\libkadm5srv.dll
+
+$(BINDIR)\libkadm5srv.dll: $(LIBKADM5SRV_OBJS) $(LIBHEIMDAL) $(LIBROKEN) $(LIBHDB) $(LIBCOMERR) $(LIBSQLITE) $(LIBKADM5SRVRES) $(LIBHEIMBASE)
+ $(DLLGUILINK) -implib:$(LIBKADM5SRV) -def:libkadm5srv-exports.def
+ $(DLLPREP_NODIST)
+
+all:: $(INCFILES) $(LIBKADM5SRV) $(LIBKADM5CLNT)
+
+all-tools:: $(SBINPROGRAMS) $(LIBEXECPROGRAMS)
+
+clean::
+ -$(RM) $(INCFILES)
+ -$(RM) $(LIBKADM5CLNT)
+ -$(RM) $(LIBKADM5SRV)
+ -$(RM) $(BINDIR)\libkadm5srv.*
+ -$(RM) $(SBINPROGRAMS:.exe=.*)
+ -$(RM) $(LIBEXECPROGRAMS:.exe=.*)
+
+test:: test-binaries test-run
+
+test-binaries: \
+ $(OBJ)\default_keys.exe \
+ $(OBJ)\test_pw_quality.exe \
+ $(OBJ)\sample_passwd_check.dll \
+ $(OBJ)\sample_hook.dll
+
+$(OBJ)\default_keys.exe: $(OBJ)\default_keys.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBHDB)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_pw_quality.exe: $(OBJ)\test_pw_quality.obj \
+ $(LIBROKEN) $(LIBKADM5SRV) $(LIBVERS) $(LIBHEIMDAL)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\sample_passwd_check.dll: $(OBJ)\sample_passwd_check.obj $(LIBHEIMDAL)
+ $(DLLGUILINK) /DEF:<<
+EXPORTS
+ version DATA
+ check_length
+<<
+ $(DLLPREP_NODIST)
+
+$(OBJ)\sample_hook.dll: $(OBJ)\sample_hook.obj $(LIBKADM5SRV) $(LIBHEIMDAL)
+ $(DLLGUILINK) /DEF:<<
+EXPORTS
+ kadm5_hook_plugin_load
+<<
+ $(DLLPREP_NODIST)
+
+test-run:
+ cd $(OBJ)
+ -default_keys.exe
+ -test_pw_quality.exe
+ cd $(SRCDIR)
+
+{$(OBJ)}.h{$(KADM5INCDIR)}.h:
+ $(CP) $< $@
+
+{}.h{$(KADM5INCDIR)}.h:
+ $(CP) $< $@
+
+{}.c{$(OBJ)}.obj::
+ $(C2OBJ_P) -I$(OBJ) -I$(KADM5INCDIR)
+
+test-exports:
+ $(PERL) ..\..\cf\w32-check-exported-symbols.pl --vs version-script.map --def libkadm5srv-exports.def
+
+test:: test-exports
diff --git a/third_party/heimdal/lib/kadm5/acl.c b/third_party/heimdal/lib/kadm5/acl.c
new file mode 100644
index 0000000..f71ed99
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/acl.c
@@ -0,0 +1,242 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+static struct units acl_units[] = {
+ { "all", KADM5_PRIV_ALL },
+ { "change-password",KADM5_PRIV_CPW },
+ { "cpw", KADM5_PRIV_CPW },
+ { "list", KADM5_PRIV_LIST },
+ { "delete", KADM5_PRIV_DELETE },
+ { "modify", KADM5_PRIV_MODIFY },
+ { "add", KADM5_PRIV_ADD },
+ { "get", KADM5_PRIV_GET },
+ { "get-keys", KADM5_PRIV_GET_KEYS },
+ { NULL, 0 }
+};
+
+kadm5_ret_t
+_kadm5_string_to_privs(const char *s, uint32_t* privs)
+{
+ int flags;
+ flags = parse_flags(s, acl_units, 0);
+ if(flags < 0)
+ return KADM5_FAILURE;
+ *privs = flags;
+ return 0;
+}
+
+kadm5_ret_t
+_kadm5_privs_to_string(uint32_t privs, char *string, size_t len)
+{
+ if(privs == 0)
+ strlcpy(string, "none", len);
+ else
+ unparse_flags(privs, acl_units + 1, string, len);
+ return 0;
+}
+
+/*
+ * retrieve the right for the current caller on `princ' (NULL means all)
+ * and store them in `ret_flags'
+ * return 0 or an error.
+ */
+
+static kadm5_ret_t
+fetch_acl (kadm5_server_context *context,
+ krb5_const_principal princ,
+ unsigned *ret_flags)
+{
+ FILE *f;
+ krb5_error_code ret = 0;
+ char buf[256];
+
+ *ret_flags = 0;
+
+ /* no acl file -> no rights */
+ f = fopen(context->config.acl_file, "r");
+ if (f == NULL)
+ return 0;
+
+ while(fgets(buf, sizeof(buf), f) != NULL) {
+ char *foo = NULL, *p;
+ krb5_principal this_princ;
+ unsigned flags = 0;
+
+ p = strtok_r(buf, " \t\n", &foo);
+ if(p == NULL)
+ continue;
+ if (*p == '#') /* comment */
+ continue;
+ ret = krb5_parse_name(context->context, p, &this_princ);
+ if(ret)
+ break;
+ if(!krb5_principal_compare(context->context,
+ context->caller, this_princ)) {
+ krb5_free_principal(context->context, this_princ);
+ continue;
+ }
+ krb5_free_principal(context->context, this_princ);
+ p = strtok_r(NULL, " \t\n", &foo);
+ if(p == NULL)
+ continue;
+ ret = _kadm5_string_to_privs(p, &flags);
+ if (ret)
+ break;
+ p = strtok_r(NULL, " \t\n", &foo);
+ if (p == NULL) {
+ *ret_flags = flags;
+ break;
+ }
+ if (princ != NULL) {
+ krb5_principal pattern_princ;
+ krb5_boolean match;
+ const char *c0 = krb5_principal_get_comp_string(context->context,
+ princ, 0);
+ const char *pat_c0;
+
+ ret = krb5_parse_name(context->context, p, &pattern_princ);
+ if (ret)
+ break;
+ pat_c0 = krb5_principal_get_comp_string(context->context,
+ pattern_princ, 0);
+ match = krb5_principal_match(context->context,
+ princ, pattern_princ);
+
+ /*
+ * If `princ' is a WELLKNOWN name, then require the WELLKNOWN label
+ * be matched exactly.
+ *
+ * FIXME: We could do something similar for krbtgt and kadmin other
+ * principal types.
+ */
+ if (match && c0 && strcmp(c0, "WELLKNOWN") == 0 &&
+ (!pat_c0 || strcmp(pat_c0, "WELLKNOWN") != 0))
+ match = FALSE;
+ krb5_free_principal(context->context, pattern_princ);
+ if (match) {
+ *ret_flags = flags;
+ break;
+ }
+ }
+ }
+ fclose(f);
+ return ret;
+}
+
+krb5_boolean
+_kadm5_is_kadmin_service_p(kadm5_server_context *context)
+{
+ krb5_boolean ret;
+ krb5_principal princ;
+
+ if (krb5_parse_name(context->context, KADM5_ADMIN_SERVICE, &princ) != 0)
+ return FALSE;
+
+ ret = krb5_principal_compare(context->context, context->caller, princ);
+ krb5_free_principal(context->context, princ);
+
+ return ret;
+}
+
+/*
+ * set global acl flags in `context' for the current caller.
+ * return 0 on success or an error
+ */
+
+kadm5_ret_t
+_kadm5_acl_init(kadm5_server_context *context)
+{
+ if (_kadm5_is_kadmin_service_p(context)) {
+ context->acl_flags = KADM5_PRIV_ALL;
+ return 0;
+ }
+
+ return fetch_acl (context, NULL, &context->acl_flags);
+}
+
+/*
+ * check if `flags' allows `op'
+ * return 0 if OK or an error
+ */
+
+static kadm5_ret_t
+check_flags (unsigned op,
+ unsigned flags)
+{
+ unsigned res = ~flags & op;
+
+ if(res & KADM5_PRIV_GET)
+ return KADM5_AUTH_GET;
+ if(res & KADM5_PRIV_GET_KEYS)
+ return KADM5_AUTH_GET_KEYS;
+ if(res & KADM5_PRIV_ADD)
+ return KADM5_AUTH_ADD;
+ if(res & KADM5_PRIV_MODIFY)
+ return KADM5_AUTH_MODIFY;
+ if(res & KADM5_PRIV_DELETE)
+ return KADM5_AUTH_DELETE;
+ if(res & KADM5_PRIV_CPW)
+ return KADM5_AUTH_CHANGEPW;
+ if(res & KADM5_PRIV_LIST)
+ return KADM5_AUTH_LIST;
+ if(res)
+ return KADM5_AUTH_INSUFFICIENT;
+ return 0;
+}
+
+/*
+ * return 0 if the current caller in `context' is allowed to perform
+ * `op' on `princ' and otherwise an error
+ * princ == NULL if it's not relevant.
+ */
+
+kadm5_ret_t
+_kadm5_acl_check_permission(kadm5_server_context *context,
+ unsigned op,
+ krb5_const_principal princ)
+{
+ kadm5_ret_t ret;
+ unsigned princ_flags;
+
+ ret = check_flags (op, context->acl_flags);
+ if (ret == 0)
+ return ret;
+ ret = fetch_acl (context, princ, &princ_flags);
+ if (ret)
+ return ret;
+ return check_flags (op, princ_flags);
+}
diff --git a/third_party/heimdal/lib/kadm5/ad.c b/third_party/heimdal/lib/kadm5/ad.c
new file mode 100644
index 0000000..58ccf32
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/ad.c
@@ -0,0 +1,1489 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#define HAVE_TSASL 1
+
+#include "kadm5_locl.h"
+#if 1
+#undef OPENLDAP
+#undef HAVE_TSASL
+#endif
+#ifdef OPENLDAP
+#include <ldap.h>
+#ifdef HAVE_TSASL
+#include <tsasl.h>
+#endif
+#include <resolve.h>
+#include <base64.h>
+#endif
+
+RCSID("$Id$");
+
+#ifdef OPENLDAP
+
+#define CTX2LP(context) ((LDAP *)((context)->ldap_conn))
+#define CTX2BASE(context) ((context)->base_dn)
+
+/*
+ * userAccountControl
+ */
+
+#define UF_SCRIPT 0x00000001
+#define UF_ACCOUNTDISABLE 0x00000002
+#define UF_UNUSED_0 0x00000004
+#define UF_HOMEDIR_REQUIRED 0x00000008
+#define UF_LOCKOUT 0x00000010
+#define UF_PASSWD_NOTREQD 0x00000020
+#define UF_PASSWD_CANT_CHANGE 0x00000040
+#define UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED 0x00000080
+#define UF_TEMP_DUPLICATE_ACCOUNT 0x00000100
+#define UF_NORMAL_ACCOUNT 0x00000200
+#define UF_UNUSED_1 0x00000400
+#define UF_INTERDOMAIN_TRUST_ACCOUNT 0x00000800
+#define UF_WORKSTATION_TRUST_ACCOUNT 0x00001000
+#define UF_SERVER_TRUST_ACCOUNT 0x00002000
+#define UF_UNUSED_2 0x00004000
+#define UF_UNUSED_3 0x00008000
+#define UF_PASSWD_NOT_EXPIRE 0x00010000
+#define UF_MNS_LOGON_ACCOUNT 0x00020000
+#define UF_SMARTCARD_REQUIRED 0x00040000
+#define UF_TRUSTED_FOR_DELEGATION 0x00080000
+#define UF_NOT_DELEGATED 0x00100000
+#define UF_USE_DES_KEY_ONLY 0x00200000
+#define UF_DONT_REQUIRE_PREAUTH 0x00400000
+#define UF_UNUSED_4 0x00800000
+#define UF_UNUSED_5 0x01000000
+#define UF_UNUSED_6 0x02000000
+#define UF_UNUSED_7 0x04000000
+#define UF_UNUSED_8 0x08000000
+#define UF_UNUSED_9 0x10000000
+#define UF_UNUSED_10 0x20000000
+#define UF_UNUSED_11 0x40000000
+#define UF_UNUSED_12 0x80000000
+
+/*
+ *
+ */
+
+#ifndef HAVE_TSASL
+static int
+sasl_interact(LDAP *ld, unsigned flags, void *defaults, void *interact)
+{
+ return LDAP_SUCCESS;
+}
+#endif
+
+#if 0
+static Sockbuf_IO ldap_tsasl_io = {
+ NULL, /* sbi_setup */
+ NULL, /* sbi_remove */
+ NULL, /* sbi_ctrl */
+ NULL, /* sbi_read */
+ NULL, /* sbi_write */
+ NULL /* sbi_close */
+};
+#endif
+
+#ifdef HAVE_TSASL
+static int
+ldap_tsasl_bind_s(LDAP *ld,
+ LDAP_CONST char *dn,
+ LDAPControl **serverControls,
+ LDAPControl **clientControls,
+ const char *host)
+{
+ char *attrs[] = { "supportedSASLMechanisms", NULL };
+ struct tsasl_peer *peer = NULL;
+ struct tsasl_buffer in, out;
+ struct berval ccred, *scred;
+ LDAPMessage *m, *m0;
+ const char *mech;
+ char **vals;
+ int ret, rc;
+
+ ret = tsasl_peer_init(TSASL_FLAGS_INITIATOR | TSASL_FLAGS_CLEAR,
+ "ldap", host, &peer);
+ if (ret != TSASL_DONE) {
+ rc = LDAP_LOCAL_ERROR;
+ goto out;
+ }
+
+ rc = ldap_search_s(ld, "", LDAP_SCOPE_BASE, NULL, attrs, 0, &m0);
+ if (rc != LDAP_SUCCESS)
+ goto out;
+
+ m = ldap_first_entry(ld, m0);
+ if (m == NULL) {
+ ldap_msgfree(m0);
+ goto out;
+ }
+
+ vals = ldap_get_values(ld, m, "supportedSASLMechanisms");
+ if (vals == NULL) {
+ ldap_msgfree(m0);
+ goto out;
+ }
+
+ ret = tsasl_find_best_mech(peer, vals, &mech);
+ if (ret) {
+ ldap_msgfree(m0);
+ goto out;
+ }
+
+ ldap_msgfree(m0);
+
+ ret = tsasl_select_mech(peer, mech);
+ if (ret != TSASL_DONE) {
+ rc = LDAP_LOCAL_ERROR;
+ goto out;
+ }
+
+ in.tb_data = NULL;
+ in.tb_size = 0;
+
+ do {
+ ret = tsasl_request(peer, &in, &out);
+ if (in.tb_size != 0) {
+ free(in.tb_data);
+ in.tb_data = NULL;
+ in.tb_size = 0;
+ }
+ if (ret != TSASL_DONE && ret != TSASL_CONTINUE) {
+ rc = LDAP_AUTH_UNKNOWN;
+ goto out;
+ }
+
+ ccred.bv_val = out.tb_data;
+ ccred.bv_len = out.tb_size;
+
+ rc = ldap_sasl_bind_s(ld, dn, mech, &ccred,
+ serverControls, clientControls, &scred);
+ tsasl_buffer_free(&out);
+
+ if (rc != LDAP_SUCCESS && rc != LDAP_SASL_BIND_IN_PROGRESS) {
+ if(scred && scred->bv_len)
+ ber_bvfree(scred);
+ goto out;
+ }
+
+ in.tb_data = malloc(scred->bv_len);
+ if (in.tb_data == NULL) {
+ rc = LDAP_LOCAL_ERROR;
+ goto out;
+ }
+ memcpy(in.tb_data, scred->bv_val, scred->bv_len);
+ in.tb_size = scred->bv_len;
+ ber_bvfree(scred);
+
+ } while (rc == LDAP_SASL_BIND_IN_PROGRESS);
+
+ out:
+ if (rc == LDAP_SUCCESS) {
+#if 0
+ ber_sockbuf_add_io(ld->ld_conns->lconn_sb, &ldap_tsasl_io,
+ LBER_SBIOD_LEVEL_APPLICATION, peer);
+
+#endif
+ } else if (peer != NULL)
+ tsasl_peer_free(peer);
+
+ return rc;
+}
+#endif /* HAVE_TSASL */
+
+
+static int
+check_ldap(kadm5_ad_context *context, int ret)
+{
+ switch (ret) {
+ case LDAP_SUCCESS:
+ return 0;
+ case LDAP_SERVER_DOWN: {
+ LDAP *lp = CTX2LP(context);
+ ldap_unbind(lp);
+ context->ldap_conn = NULL;
+ free(context->base_dn);
+ context->base_dn = NULL;
+ return 1;
+ }
+ default:
+ return 1;
+ }
+}
+
+/*
+ *
+ */
+
+static void
+laddattr(char ***al, int *attrlen, char *attr)
+{
+ char **a;
+ a = realloc(*al, (*attrlen + 2) * sizeof(**al));
+ if (a == NULL)
+ return;
+ a[*attrlen] = attr;
+ a[*attrlen + 1] = NULL;
+ (*attrlen)++;
+ *al = a;
+}
+
+static kadm5_ret_t
+_kadm5_ad_connect(void *server_handle)
+{
+ kadm5_ad_context *context = server_handle;
+ struct {
+ char *server;
+ int port;
+ } *s, *servers = NULL;
+ int i, num_servers = 0;
+
+ if (context->ldap_conn)
+ return 0;
+
+ {
+ struct dns_reply *r;
+ struct resource_record *rr;
+ char *domain;
+
+ asprintf(&domain, "_ldap._tcp.%s", context->realm);
+ if (domain == NULL) {
+ krb5_set_error_message(context->context, KADM5_NO_SRV, "malloc");
+ return KADM5_NO_SRV;
+ }
+
+ r = dns_lookup(domain, "SRV");
+ free(domain);
+ if (r == NULL) {
+ krb5_set_error_message(context->context, KADM5_NO_SRV, "Didn't find ldap dns");
+ return KADM5_NO_SRV;
+ }
+
+ for (rr = r->head ; rr != NULL; rr = rr->next) {
+ if (rr->type != rk_ns_t_srv)
+ continue;
+ s = realloc(servers, sizeof(*servers) * (num_servers + 1));
+ if (s == NULL) {
+ krb5_set_error_message(context->context, KADM5_RPC_ERROR, "malloc");
+ dns_free_data(r);
+ goto fail;
+ }
+ servers = s;
+ num_servers++;
+ servers[num_servers - 1].port = rr->u.srv->port;
+ servers[num_servers - 1].server = strdup(rr->u.srv->target);
+ }
+ dns_free_data(r);
+ }
+
+ if (num_servers == 0) {
+ krb5_set_error_message(context->context, KADM5_NO_SRV, "No AD server found in DNS");
+ return KADM5_NO_SRV;
+ }
+
+ for (i = 0; i < num_servers; i++) {
+ int lret, version = LDAP_VERSION3;
+ LDAP *lp;
+
+ lp = ldap_init(servers[i].server, servers[i].port);
+ if (lp == NULL)
+ continue;
+
+ if (ldap_set_option(lp, LDAP_OPT_PROTOCOL_VERSION, &version)) {
+ ldap_unbind(lp);
+ continue;
+ }
+
+ if (ldap_set_option(lp, LDAP_OPT_REFERRALS, LDAP_OPT_OFF)) {
+ ldap_unbind(lp);
+ continue;
+ }
+
+#ifdef HAVE_TSASL
+ lret = ldap_tsasl_bind_s(lp, NULL, NULL, NULL, servers[i].server);
+
+#else
+ lret = ldap_sasl_interactive_bind_s(lp, NULL, NULL, NULL, NULL,
+ LDAP_SASL_QUIET,
+ sasl_interact, NULL);
+#endif
+ if (lret != LDAP_SUCCESS) {
+ krb5_set_error_message(context->context, 0,
+ "Couldn't contact any AD servers: %s",
+ ldap_err2string(lret));
+ ldap_unbind(lp);
+ continue;
+ }
+
+ context->ldap_conn = lp;
+ break;
+ }
+ if (i >= num_servers) {
+ goto fail;
+ }
+
+ {
+ LDAPMessage *m, *m0;
+ char **attr = NULL;
+ int attrlen = 0;
+ char **vals;
+ int ret;
+
+ laddattr(&attr, &attrlen, "defaultNamingContext");
+
+ ret = ldap_search_s(CTX2LP(context), "", LDAP_SCOPE_BASE,
+ "objectclass=*", attr, 0, &m);
+ free(attr);
+ if (check_ldap(context, ret))
+ goto fail;
+
+ if (ldap_count_entries(CTX2LP(context), m) > 0) {
+ m0 = ldap_first_entry(CTX2LP(context), m);
+ if (m0 == NULL) {
+ krb5_set_error_message(context->context, KADM5_RPC_ERROR,
+ "Error in AD ldap responce");
+ ldap_msgfree(m);
+ goto fail;
+ }
+ vals = ldap_get_values(CTX2LP(context),
+ m0, "defaultNamingContext");
+ if (vals == NULL) {
+ krb5_set_error_message(context->context, KADM5_RPC_ERROR,
+ "No naming context found");
+ goto fail;
+ }
+ context->base_dn = strdup(vals[0]);
+ } else
+ goto fail;
+ ldap_msgfree(m);
+ }
+
+ for (i = 0; i < num_servers; i++)
+ free(servers[i].server);
+ free(servers);
+
+ return 0;
+
+ fail:
+ for (i = 0; i < num_servers; i++)
+ free(servers[i].server);
+ free(servers);
+
+ if (context->ldap_conn) {
+ ldap_unbind(CTX2LP(context));
+ context->ldap_conn = NULL;
+ }
+ return KADM5_RPC_ERROR;
+}
+
+#define NTTIME_EPOCH 0x019DB1DED53E8000LL
+
+static time_t
+nt2unixtime(const char *str)
+{
+ unsigned long long t;
+ t = strtoll(str, NULL, 10);
+ t = ((t - NTTIME_EPOCH) / (long long)10000000);
+ if (t > (((time_t)(~(long long)0)) >> 1))
+ return 0;
+ return (time_t)t;
+}
+
+static long long
+unix2nttime(time_t unix_time)
+{
+ long long wt;
+ wt = unix_time * (long long)10000000 + (long long)NTTIME_EPOCH;
+ return wt;
+}
+
+/* XXX create filter in a better way */
+
+static int
+ad_find_entry(kadm5_ad_context *context,
+ const char *fqdn,
+ const char *pn,
+ char **name)
+{
+ LDAPMessage *m, *m0;
+ char *attr[] = { "distinguishedName", NULL };
+ char *filter;
+ int ret;
+
+ if (name)
+ *name = NULL;
+
+ if (fqdn)
+ asprintf(&filter,
+ "(&(objectClass=computer)(|(dNSHostName=%s)(servicePrincipalName=%s)))",
+ fqdn, pn);
+ else if(pn)
+ asprintf(&filter, "(&(objectClass=account)(userPrincipalName=%s))", pn);
+ else
+ return KADM5_RPC_ERROR;
+
+ ret = ldap_search_s(CTX2LP(context), CTX2BASE(context),
+ LDAP_SCOPE_SUBTREE,
+ filter, attr, 0, &m);
+ free(filter);
+ if (check_ldap(context, ret))
+ return KADM5_RPC_ERROR;
+
+ if (ldap_count_entries(CTX2LP(context), m) > 0) {
+ char **vals;
+ m0 = ldap_first_entry(CTX2LP(context), m);
+ vals = ldap_get_values(CTX2LP(context), m0, "distinguishedName");
+ if (vals == NULL || vals[0] == NULL) {
+ ldap_msgfree(m);
+ return KADM5_RPC_ERROR;
+ }
+ if (name)
+ *name = strdup(vals[0]);
+ ldap_msgfree(m);
+ } else
+ return KADM5_UNK_PRINC;
+
+ return 0;
+}
+
+#endif /* OPENLDAP */
+
+static kadm5_ret_t
+ad_get_cred(kadm5_ad_context *context, const char *password)
+{
+ kadm5_ret_t ret;
+ krb5_ccache cc;
+ char *service;
+ int aret;
+
+ if (context->ccache)
+ return 0;
+
+ aret = asprintf(&service, "%s/%s@%s", KRB5_TGS_NAME,
+ context->realm, context->realm);
+ if (aret == -1 || service == NULL)
+ return krb5_enomem(context->context);
+
+ ret = _kadm5_c_get_cred_cache(context->context,
+ context->client_name,
+ service,
+ password, krb5_prompter_posix,
+ NULL, NULL, &cc);
+ free(service);
+ if(ret)
+ return ret; /* XXX */
+ context->ccache = cc;
+ return 0;
+}
+
+static kadm5_ret_t
+kadm5_ad_chpass_principal(void *server_handle,
+ krb5_principal principal,
+ int keepold,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ const char *password)
+{
+ kadm5_ad_context *context = server_handle;
+ krb5_data result_code_string, result_string;
+ int result_code;
+ kadm5_ret_t ret;
+
+ if (keepold)
+ return KADM5_KEEPOLD_NOSUPP;
+
+ if (n_ks_tuple > 0)
+ return KADM5_KS_TUPLE_NOSUPP;
+
+ ret = ad_get_cred(context, NULL);
+ if (ret)
+ return ret;
+
+ krb5_data_zero (&result_code_string);
+ krb5_data_zero (&result_string);
+
+ ret = krb5_set_password_using_ccache (context->context,
+ context->ccache,
+ password,
+ principal,
+ &result_code,
+ &result_code_string,
+ &result_string);
+
+ krb5_data_free (&result_code_string);
+ krb5_data_free (&result_string);
+
+ /* XXX do mapping here on error codes */
+
+ return ret;
+}
+
+#ifdef OPENLDAP
+static const char *
+get_fqdn(krb5_context context, const krb5_principal p)
+{
+ const char *s, *hosttypes[] = { "host", "ldap", "gc", "cifs", "dns" };
+ int i;
+
+ s = krb5_principal_get_comp_string(context, p, 0);
+ if (p == NULL)
+ return NULL;
+
+ for (i = 0; i < sizeof(hosttypes)/sizeof(hosttypes[0]); i++) {
+ if (strcasecmp(s, hosttypes[i]) == 0)
+ return krb5_principal_get_comp_string(context, p, 1);
+ }
+ return 0;
+}
+#endif
+
+
+static kadm5_ret_t
+kadm5_ad_create_principal(void *server_handle,
+ kadm5_principal_ent_t entry,
+ uint32_t mask,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ const char *password)
+{
+ kadm5_ad_context *context = server_handle;
+
+ /*
+ * KADM5_PRINC_EXPIRE_TIME
+ *
+ * return 0 || KADM5_DUP;
+ */
+
+#ifdef OPENLDAP
+ LDAPMod *attrs[8], rattrs[7], *a;
+ char *useraccvals[2] = { NULL, NULL },
+ *samvals[2], *dnsvals[2], *spnvals[5], *upnvals[2], *tv[2];
+ char *ocvals_spn[] = { "top", "person", "organizationalPerson",
+ "user", "computer", NULL};
+ char *p, *realmless_p, *p_msrealm = NULL, *dn = NULL;
+ const char *fqdn;
+ char *s, *samname = NULL, *short_spn = NULL;
+ int ret, i;
+ int32_t uf_flags = 0;
+
+ if ((mask & KADM5_PRINCIPAL) == 0)
+ return KADM5_BAD_MASK;
+
+ /*
+ * We should get around to implementing this... At the moment, the
+ * the server side API is implemented but the wire protocol has not
+ * been updated.
+ */
+ if (n_ks_tuple > 0)
+ return KADM5_KS_TUPLE_NOSUPP;
+
+ for (i = 0; i < sizeof(rattrs)/sizeof(rattrs[0]); i++)
+ attrs[i] = &rattrs[i];
+ attrs[i] = NULL;
+
+ ret = ad_get_cred(context, NULL);
+ if (ret)
+ return ret;
+
+ ret = _kadm5_ad_connect(server_handle);
+ if (ret)
+ return ret;
+
+ fqdn = get_fqdn(context->context, entry->principal);
+
+ ret = krb5_unparse_name(context->context, entry->principal, &p);
+ if (ret)
+ return ret;
+
+ if (ad_find_entry(context, fqdn, p, NULL) == 0) {
+ free(p);
+ return KADM5_DUP;
+ }
+
+ if (mask & KADM5_ATTRIBUTES) {
+ if (entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX)
+ uf_flags |= UF_ACCOUNTDISABLE|UF_LOCKOUT;
+ if ((entry->attributes & KRB5_KDB_REQUIRES_PRE_AUTH) == 0)
+ uf_flags |= UF_DONT_REQUIRE_PREAUTH;
+ if (entry->attributes & KRB5_KDB_REQUIRES_HW_AUTH)
+ uf_flags |= UF_SMARTCARD_REQUIRED;
+ }
+
+ realmless_p = strdup(p);
+ if (realmless_p == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ s = strrchr(realmless_p, '@');
+ if (s)
+ *s = '\0';
+
+ if (fqdn) {
+ /* create computer account */
+ asprintf(&samname, "%s$", fqdn);
+ if (samname == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ s = strchr(samname, '.');
+ if (s) {
+ s[0] = '$';
+ s[1] = '\0';
+ }
+
+ short_spn = strdup(p);
+ if (short_spn == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ s = strchr(short_spn, '.');
+ if (s) {
+ *s = '\0';
+ } else {
+ free(short_spn);
+ short_spn = NULL;
+ }
+
+ p_msrealm = strdup(p);
+ if (p_msrealm == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ s = strrchr(p_msrealm, '@');
+ if (s) {
+ *s = '/';
+ } else {
+ free(p_msrealm);
+ p_msrealm = NULL;
+ }
+
+ asprintf(&dn, "cn=%s, cn=Computers, %s", fqdn, CTX2BASE(context));
+ if (dn == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+
+ a = &rattrs[0];
+ a->mod_op = LDAP_MOD_ADD;
+ a->mod_type = "objectClass";
+ a->mod_values = ocvals_spn;
+ a++;
+
+ a->mod_op = LDAP_MOD_ADD;
+ a->mod_type = "userAccountControl";
+ a->mod_values = useraccvals;
+ asprintf(&useraccvals[0], "%d",
+ uf_flags |
+ UF_PASSWD_NOT_EXPIRE |
+ UF_WORKSTATION_TRUST_ACCOUNT);
+ useraccvals[1] = NULL;
+ a++;
+
+ a->mod_op = LDAP_MOD_ADD;
+ a->mod_type = "sAMAccountName";
+ a->mod_values = samvals;
+ samvals[0] = samname;
+ samvals[1] = NULL;
+ a++;
+
+ a->mod_op = LDAP_MOD_ADD;
+ a->mod_type = "dNSHostName";
+ a->mod_values = dnsvals;
+ dnsvals[0] = (char *)fqdn;
+ dnsvals[1] = NULL;
+ a++;
+
+ /* XXX add even more spn's */
+ a->mod_op = LDAP_MOD_ADD;
+ a->mod_type = "servicePrincipalName";
+ a->mod_values = spnvals;
+ i = 0;
+ spnvals[i++] = p;
+ spnvals[i++] = realmless_p;
+ if (short_spn)
+ spnvals[i++] = short_spn;
+ if (p_msrealm)
+ spnvals[i++] = p_msrealm;
+ spnvals[i++] = NULL;
+ a++;
+
+ a->mod_op = LDAP_MOD_ADD;
+ a->mod_type = "userPrincipalName";
+ a->mod_values = upnvals;
+ upnvals[0] = p;
+ upnvals[1] = NULL;
+ a++;
+
+ a->mod_op = LDAP_MOD_ADD;
+ a->mod_type = "accountExpires";
+ a->mod_values = tv;
+ tv[0] = "9223372036854775807"; /* "never" */
+ tv[1] = NULL;
+ a++;
+
+ } else {
+ /* create user account */
+
+ a = &rattrs[0];
+ a->mod_op = LDAP_MOD_ADD;
+ a->mod_type = "userAccountControl";
+ a->mod_values = useraccvals;
+ asprintf(&useraccvals[0], "%d",
+ uf_flags |
+ UF_PASSWD_NOT_EXPIRE);
+ useraccvals[1] = NULL;
+ a++;
+
+ a->mod_op = LDAP_MOD_ADD;
+ a->mod_type = "sAMAccountName";
+ a->mod_values = samvals;
+ samvals[0] = realmless_p;
+ samvals[1] = NULL;
+ a++;
+
+ a->mod_op = LDAP_MOD_ADD;
+ a->mod_type = "userPrincipalName";
+ a->mod_values = upnvals;
+ upnvals[0] = p;
+ upnvals[1] = NULL;
+ a++;
+
+ a->mod_op = LDAP_MOD_ADD;
+ a->mod_type = "accountExpires";
+ a->mod_values = tv;
+ tv[0] = "9223372036854775807"; /* "never" */
+ tv[1] = NULL;
+ a++;
+ }
+
+ attrs[a - &rattrs[0]] = NULL;
+
+ ret = ldap_add_s(CTX2LP(context), dn, attrs);
+
+ out:
+ if (useraccvals[0])
+ free(useraccvals[0]);
+ if (realmless_p)
+ free(realmless_p);
+ if (samname)
+ free(samname);
+ if (short_spn)
+ free(short_spn);
+ if (p_msrealm)
+ free(p_msrealm);
+ free(p);
+
+ if (check_ldap(context, ret))
+ return KADM5_RPC_ERROR;
+
+ return 0;
+#else
+ krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function not implemented");
+ return KADM5_RPC_ERROR;
+#endif
+}
+
+static kadm5_ret_t
+kadm5_ad_delete_principal(void *server_handle, krb5_principal principal)
+{
+ kadm5_ad_context *context = server_handle;
+#ifdef OPENLDAP
+ char *p, *dn = NULL;
+ const char *fqdn;
+ int ret;
+
+ ret = ad_get_cred(context, NULL);
+ if (ret)
+ return ret;
+
+ ret = _kadm5_ad_connect(server_handle);
+ if (ret)
+ return ret;
+
+ fqdn = get_fqdn(context->context, principal);
+
+ ret = krb5_unparse_name(context->context, principal, &p);
+ if (ret)
+ return ret;
+
+ if (ad_find_entry(context, fqdn, p, &dn) != 0) {
+ free(p);
+ return KADM5_UNK_PRINC;
+ }
+
+ ret = ldap_delete_s(CTX2LP(context), dn);
+
+ free(dn);
+ free(p);
+
+ if (check_ldap(context, ret))
+ return KADM5_RPC_ERROR;
+ return 0;
+#else
+ krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function not implemented");
+ return KADM5_RPC_ERROR;
+#endif
+}
+
+static kadm5_ret_t
+kadm5_ad_destroy(void *server_handle)
+{
+ kadm5_ad_context *context = server_handle;
+
+ if (context->ccache)
+ krb5_cc_destroy(context->context, context->ccache);
+
+#ifdef OPENLDAP
+ {
+ LDAP *lp = CTX2LP(context);
+ if (lp)
+ ldap_unbind(lp);
+ if (context->base_dn)
+ free(context->base_dn);
+ }
+#endif
+ free(context->realm);
+ free(context->client_name);
+ krb5_free_principal(context->context, context->caller);
+ if(context->my_context)
+ krb5_free_context(context->context);
+ return 0;
+}
+
+static kadm5_ret_t
+kadm5_ad_flush(void *server_handle)
+{
+ kadm5_ad_context *context = server_handle;
+ krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function not implemented");
+ return KADM5_RPC_ERROR;
+}
+
+static kadm5_ret_t
+kadm5_ad_get_principal(void *server_handle,
+ krb5_principal principal,
+ kadm5_principal_ent_t entry,
+ uint32_t mask)
+{
+ kadm5_ad_context *context = server_handle;
+#ifdef OPENLDAP
+ LDAPMessage *m, *m0;
+ char **attr = NULL;
+ int attrlen = 0;
+ char *filter, *p, *q, *u;
+ int ret;
+
+ /*
+ * principal
+ * KADM5_PRINCIPAL | KADM5_KVNO | KADM5_ATTRIBUTES
+ */
+
+ /*
+ * return 0 || KADM5_DUP;
+ */
+
+ memset(entry, 0, sizeof(*entry));
+
+ if (mask & KADM5_KVNO)
+ laddattr(&attr, &attrlen, "msDS-KeyVersionNumber");
+
+ if (mask & KADM5_PRINCIPAL) {
+ laddattr(&attr, &attrlen, "userPrincipalName");
+ laddattr(&attr, &attrlen, "servicePrincipalName");
+ }
+ laddattr(&attr, &attrlen, "objectClass");
+ laddattr(&attr, &attrlen, "lastLogon");
+ laddattr(&attr, &attrlen, "badPwdCount");
+ laddattr(&attr, &attrlen, "badPasswordTime");
+ laddattr(&attr, &attrlen, "pwdLastSet");
+ laddattr(&attr, &attrlen, "accountExpires");
+ laddattr(&attr, &attrlen, "userAccountControl");
+
+ krb5_unparse_name_short(context->context, principal, &p);
+ krb5_unparse_name(context->context, principal, &u);
+
+ /* replace @ in domain part with a / */
+ q = strrchr(p, '@');
+ if (q && (p != q && *(q - 1) != '\\'))
+ *q = '/';
+
+ asprintf(&filter,
+ "(|(userPrincipalName=%s)(servicePrincipalName=%s)(servicePrincipalName=%s))",
+ u, p, u);
+ free(p);
+ free(u);
+
+ ret = ldap_search_s(CTX2LP(context), CTX2BASE(context),
+ LDAP_SCOPE_SUBTREE,
+ filter, attr, 0, &m);
+ free(attr);
+ if (check_ldap(context, ret))
+ return KADM5_RPC_ERROR;
+
+ if (ldap_count_entries(CTX2LP(context), m) > 0) {
+ char **vals;
+ m0 = ldap_first_entry(CTX2LP(context), m);
+ if (m0 == NULL) {
+ ldap_msgfree(m);
+ goto fail;
+ }
+#if 0
+ vals = ldap_get_values(CTX2LP(context), m0, "servicePrincipalName");
+ if (vals)
+ printf("servicePrincipalName %s\n", vals[0]);
+ vals = ldap_get_values(CTX2LP(context), m0, "userPrincipalName");
+ if (vals)
+ printf("userPrincipalName %s\n", vals[0]);
+ vals = ldap_get_values(CTX2LP(context), m0, "userAccountControl");
+ if (vals)
+ printf("userAccountControl %s\n", vals[0]);
+#endif
+ entry->princ_expire_time = 0;
+ if (mask & KADM5_PRINC_EXPIRE_TIME) {
+ vals = ldap_get_values(CTX2LP(context), m0, "accountExpires");
+ if (vals)
+ entry->princ_expire_time = nt2unixtime(vals[0]);
+ }
+ entry->last_success = 0;
+ if (mask & KADM5_LAST_SUCCESS) {
+ vals = ldap_get_values(CTX2LP(context), m0, "lastLogon");
+ if (vals)
+ entry->last_success = nt2unixtime(vals[0]);
+ }
+ if (mask & KADM5_LAST_FAILED) {
+ vals = ldap_get_values(CTX2LP(context), m0, "badPasswordTime");
+ if (vals)
+ entry->last_failed = nt2unixtime(vals[0]);
+ }
+ if (mask & KADM5_LAST_PWD_CHANGE) {
+ vals = ldap_get_values(CTX2LP(context), m0, "pwdLastSet");
+ if (vals)
+ entry->last_pwd_change = nt2unixtime(vals[0]);
+ }
+ if (mask & KADM5_FAIL_AUTH_COUNT) {
+ vals = ldap_get_values(CTX2LP(context), m0, "badPwdCount");
+ if (vals)
+ entry->fail_auth_count = atoi(vals[0]);
+ }
+ if (mask & KADM5_ATTRIBUTES) {
+ vals = ldap_get_values(CTX2LP(context), m0, "userAccountControl");
+ if (vals) {
+ uint32_t i;
+ i = atoi(vals[0]);
+ if (i & (UF_ACCOUNTDISABLE|UF_LOCKOUT))
+ entry->attributes |= KRB5_KDB_DISALLOW_ALL_TIX;
+ if ((i & UF_DONT_REQUIRE_PREAUTH) == 0)
+ entry->attributes |= KRB5_KDB_REQUIRES_PRE_AUTH;
+ if (i & UF_SMARTCARD_REQUIRED)
+ entry->attributes |= KRB5_KDB_REQUIRES_HW_AUTH;
+ if ((i & UF_WORKSTATION_TRUST_ACCOUNT) == 0)
+ entry->attributes |= KRB5_KDB_DISALLOW_SVR;
+ }
+ }
+ if (mask & KADM5_KVNO) {
+ vals = ldap_get_values(CTX2LP(context), m0,
+ "msDS-KeyVersionNumber");
+ if (vals)
+ entry->kvno = atoi(vals[0]);
+ else
+ entry->kvno = 0;
+ }
+ ldap_msgfree(m);
+ } else {
+ return KADM5_UNK_PRINC;
+ }
+
+ if (mask & KADM5_PRINCIPAL)
+ krb5_copy_principal(context->context, principal, &entry->principal);
+
+ return 0;
+ fail:
+ return KADM5_RPC_ERROR;
+#else
+ krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function not implemented");
+ return KADM5_RPC_ERROR;
+#endif
+}
+
+static kadm5_ret_t
+kadm5_ad_get_principals(void *server_handle,
+ const char *expression,
+ char ***principals,
+ int *count)
+{
+ kadm5_ad_context *context = server_handle;
+
+ /*
+ * KADM5_PRINCIPAL | KADM5_KVNO | KADM5_ATTRIBUTES
+ */
+
+#ifdef OPENLDAP
+ kadm5_ret_t ret;
+
+ ret = ad_get_cred(context, NULL);
+ if (ret)
+ return ret;
+
+ ret = _kadm5_ad_connect(server_handle);
+ if (ret)
+ return ret;
+
+ krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function not implemented");
+ return KADM5_RPC_ERROR;
+#else
+ krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function not implemented");
+ return KADM5_RPC_ERROR;
+#endif
+}
+
+static kadm5_ret_t
+kadm5_ad_get_privs(void *server_handle, uint32_t*privs)
+{
+ kadm5_ad_context *context = server_handle;
+ krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function not implemented");
+ return KADM5_RPC_ERROR;
+}
+
+static kadm5_ret_t
+kadm5_ad_modify_principal(void *server_handle,
+ kadm5_principal_ent_t entry,
+ uint32_t mask)
+{
+ kadm5_ad_context *context = server_handle;
+
+ /*
+ * KADM5_ATTRIBUTES
+ * KRB5_KDB_DISALLOW_ALL_TIX (| KADM5_KVNO)
+ */
+
+#ifdef OPENLDAP
+ LDAPMessage *m = NULL, *m0;
+ kadm5_ret_t ret;
+ char **attr = NULL;
+ int attrlen = 0;
+ char *p = NULL, *s = NULL, *q;
+ char **vals;
+ LDAPMod *attrs[4], rattrs[3], *a;
+ char *uaf[2] = { NULL, NULL };
+ char *kvno[2] = { NULL, NULL };
+ char *tv[2] = { NULL, NULL };
+ char *filter, *dn;
+ int i;
+
+ for (i = 0; i < sizeof(rattrs)/sizeof(rattrs[0]); i++)
+ attrs[i] = &rattrs[i];
+ attrs[i] = NULL;
+ a = &rattrs[0];
+
+ ret = _kadm5_ad_connect(server_handle);
+ if (ret)
+ return ret;
+
+ if (mask & KADM5_KVNO)
+ laddattr(&attr, &attrlen, "msDS-KeyVersionNumber");
+ if (mask & KADM5_PRINC_EXPIRE_TIME)
+ laddattr(&attr, &attrlen, "accountExpires");
+ if (mask & KADM5_ATTRIBUTES)
+ laddattr(&attr, &attrlen, "userAccountControl");
+ laddattr(&attr, &attrlen, "distinguishedName");
+
+ krb5_unparse_name(context->context, entry->principal, &p);
+
+ s = strdup(p);
+
+ q = strrchr(s, '@');
+ if (q && (p != q && *(q - 1) != '\\'))
+ *q = '\0';
+
+ asprintf(&filter,
+ "(|(userPrincipalName=%s)(servicePrincipalName=%s))",
+ s, s);
+ free(p);
+ free(s);
+
+ ret = ldap_search_s(CTX2LP(context), CTX2BASE(context),
+ LDAP_SCOPE_SUBTREE,
+ filter, attr, 0, &m);
+ free(attr);
+ free(filter);
+ if (check_ldap(context, ret))
+ return KADM5_RPC_ERROR;
+
+ if (ldap_count_entries(CTX2LP(context), m) <= 0) {
+ ret = KADM5_RPC_ERROR;
+ goto out;
+ }
+
+ m0 = ldap_first_entry(CTX2LP(context), m);
+
+ if (mask & KADM5_ATTRIBUTES) {
+ int32_t i;
+
+ vals = ldap_get_values(CTX2LP(context), m0, "userAccountControl");
+ if (vals == NULL) {
+ ret = KADM5_RPC_ERROR;
+ goto out;
+ }
+
+ i = atoi(vals[0]);
+ if (i == 0)
+ return KADM5_RPC_ERROR;
+
+ if (entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX)
+ i |= (UF_ACCOUNTDISABLE|UF_LOCKOUT);
+ else
+ i &= ~(UF_ACCOUNTDISABLE|UF_LOCKOUT);
+ if (entry->attributes & KRB5_KDB_REQUIRES_PRE_AUTH)
+ i &= ~UF_DONT_REQUIRE_PREAUTH;
+ else
+ i |= UF_DONT_REQUIRE_PREAUTH;
+ if (entry->attributes & KRB5_KDB_REQUIRES_HW_AUTH)
+ i |= UF_SMARTCARD_REQUIRED;
+ else
+ i &= UF_SMARTCARD_REQUIRED;
+ if (entry->attributes & KRB5_KDB_DISALLOW_SVR)
+ i &= ~UF_WORKSTATION_TRUST_ACCOUNT;
+ else
+ i |= UF_WORKSTATION_TRUST_ACCOUNT;
+
+ asprintf(&uaf[0], "%d", i);
+
+ a->mod_op = LDAP_MOD_REPLACE;
+ a->mod_type = "userAccountControl";
+ a->mod_values = uaf;
+ a++;
+ }
+
+ if (mask & KADM5_KVNO) {
+ vals = ldap_get_values(CTX2LP(context), m0, "msDS-KeyVersionNumber");
+ if (vals == NULL) {
+ entry->kvno = 0;
+ } else {
+ asprintf(&kvno[0], "%d", entry->kvno);
+
+ a->mod_op = LDAP_MOD_REPLACE;
+ a->mod_type = "msDS-KeyVersionNumber";
+ a->mod_values = kvno;
+ a++;
+ }
+ }
+
+ if (mask & KADM5_PRINC_EXPIRE_TIME) {
+ long long wt;
+ vals = ldap_get_values(CTX2LP(context), m0, "accountExpires");
+ if (vals == NULL) {
+ ret = KADM5_RPC_ERROR;
+ goto out;
+ }
+
+ wt = unix2nttime(entry->princ_expire_time);
+
+ asprintf(&tv[0], "%llu", wt);
+
+ a->mod_op = LDAP_MOD_REPLACE;
+ a->mod_type = "accountExpires";
+ a->mod_values = tv;
+ a++;
+ }
+
+ vals = ldap_get_values(CTX2LP(context), m0, "distinguishedName");
+ if (vals == NULL) {
+ ret = KADM5_RPC_ERROR;
+ goto out;
+ }
+ dn = vals[0];
+
+ attrs[a - &rattrs[0]] = NULL;
+
+ ret = ldap_modify_s(CTX2LP(context), dn, attrs);
+ if (check_ldap(context, ret))
+ return KADM5_RPC_ERROR;
+
+ out:
+ if (m)
+ ldap_msgfree(m);
+ if (uaf[0])
+ free(uaf[0]);
+ if (kvno[0])
+ free(kvno[0]);
+ if (tv[0])
+ free(tv[0]);
+ return ret;
+#else
+ krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function not implemented");
+ return KADM5_RPC_ERROR;
+#endif
+}
+
+/*ARGSUSED*/
+static kadm5_ret_t
+kadm5_ad_randkey_principal(void *server_handle,
+ krb5_principal principal,
+ krb5_boolean keepold,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ krb5_keyblock **keys,
+ int *n_keys)
+{
+ kadm5_ad_context *context = server_handle;
+
+ if (keepold)
+ return KADM5_KEEPOLD_NOSUPP;
+
+ /*
+ * random key
+ */
+
+#ifdef OPENLDAP
+ krb5_data result_code_string, result_string;
+ int result_code, plen;
+ kadm5_ret_t ret;
+ char *password;
+
+ *keys = NULL;
+ *n_keys = 0;
+
+ {
+ char p[64];
+ krb5_generate_random_block(p, sizeof(p));
+ plen = rk_base64_encode(p, sizeof(p), &password);
+ if (plen < 0)
+ return krb5_enomem(context->context);
+ }
+
+ ret = ad_get_cred(context, NULL);
+ if (ret) {
+ free(password);
+ return ret;
+ }
+
+ krb5_data_zero(&result_code_string);
+ krb5_data_zero(&result_string);
+
+ ret = krb5_set_password_using_ccache(context->context,
+ context->ccache,
+ password,
+ principal,
+ &result_code,
+ &result_code_string,
+ &result_string);
+ krb5_data_free(&result_code_string);
+ krb5_data_free(&result_string);
+
+ if (ret)
+ goto out;
+
+ *keys = malloc(sizeof(**keys) * 1);
+ if (*keys == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ *n_keys = 1;
+
+ ret = krb5_string_to_key(context->context,
+ ENCTYPE_ARCFOUR_HMAC_MD5,
+ password,
+ principal,
+ &(*keys)[0]);
+ if (ret) {
+ free(*keys);
+ *keys = NULL;
+ *n_keys = 0;
+ goto out;
+ }
+
+ out:
+ memset(password, 0, plen);
+ free(password);
+ return ret;
+#else
+ *keys = NULL;
+ *n_keys = 0;
+
+ krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function not implemented");
+ return KADM5_RPC_ERROR;
+#endif
+}
+
+static kadm5_ret_t
+kadm5_ad_rename_principal(void *server_handle,
+ krb5_principal from,
+ krb5_principal to)
+{
+ kadm5_ad_context *context = server_handle;
+ krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function not implemented");
+ return KADM5_RPC_ERROR;
+}
+
+static kadm5_ret_t
+kadm5_ad_chpass_principal_with_key(void *server_handle,
+ krb5_principal princ,
+ int keepold,
+ int n_key_data,
+ krb5_key_data *key_data)
+{
+ kadm5_ad_context *context = server_handle;
+ krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function not implemented");
+ return KADM5_RPC_ERROR;
+}
+
+static kadm5_ret_t
+kadm5_ad_lock(void *server_handle)
+{
+ return ENOTSUP;
+}
+
+static kadm5_ret_t
+kadm5_ad_unlock(void *server_handle)
+{
+ return ENOTSUP;
+}
+
+static void
+set_funcs(kadm5_ad_context *c)
+{
+#define SET(C, F) (C)->funcs.F = kadm5_ad_ ## F
+#define SETNOTIMP(C, F) (C)->funcs.F = 0
+ SET(c, chpass_principal);
+ SET(c, chpass_principal_with_key);
+ SET(c, create_principal);
+ SET(c, delete_principal);
+ SET(c, destroy);
+ SET(c, flush);
+ SET(c, get_principal);
+ SET(c, get_principals);
+ SET(c, get_privs);
+ SET(c, modify_principal);
+ SET(c, randkey_principal);
+ SET(c, rename_principal);
+ SET(c, lock);
+ SET(c, unlock);
+ SETNOTIMP(c, setkey_principal_3);
+}
+
+kadm5_ret_t
+kadm5_ad_init_with_password_ctx(krb5_context context,
+ const char *client_name,
+ const char *password,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ kadm5_ret_t ret;
+ kadm5_ad_context *ctx;
+
+ ctx = malloc(sizeof(*ctx));
+ if (ctx == NULL)
+ return krb5_enomem(context);
+ memset(ctx, 0, sizeof(*ctx));
+ set_funcs(ctx);
+
+ ctx->context = context;
+ krb5_add_et_list (context, initialize_kadm5_error_table_r);
+
+ ret = krb5_parse_name(ctx->context, client_name, &ctx->caller);
+ if(ret) {
+ free(ctx);
+ return ret;
+ }
+
+ if(realm_params->mask & KADM5_CONFIG_REALM) {
+ ret = 0;
+ ctx->realm = strdup(realm_params->realm);
+ if (ctx->realm == NULL)
+ ret = krb5_enomem(context);
+ } else
+ ret = krb5_get_default_realm(ctx->context, &ctx->realm);
+ if (ret) {
+ free(ctx);
+ return ret;
+ }
+
+ ctx->client_name = strdup(client_name);
+
+ if(password != NULL && *password != '\0')
+ ret = ad_get_cred(ctx, password);
+ else
+ ret = ad_get_cred(ctx, NULL);
+ if(ret) {
+ kadm5_ad_destroy(ctx);
+ free(ctx);
+ return ret;
+ }
+
+#ifdef OPENLDAP
+ ret = _kadm5_ad_connect(ctx);
+ if (ret) {
+ kadm5_ad_destroy(ctx);
+ free(ctx);
+ return ret;
+ }
+#endif
+
+ *server_handle = ctx;
+ return 0;
+}
+
+kadm5_ret_t
+kadm5_ad_init_with_password(const char *client_name,
+ const char *password,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ krb5_context context;
+ kadm5_ret_t ret;
+ kadm5_ad_context *ctx;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ return ret;
+ ret = kadm5_ad_init_with_password_ctx(context,
+ client_name,
+ password,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+ if(ret) {
+ krb5_free_context(context);
+ return ret;
+ }
+ ctx = *server_handle;
+ ctx->my_context = 1;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/admin.h b/third_party/heimdal/lib/kadm5/admin.h
new file mode 100644
index 0000000..4f8ac22
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/admin.h
@@ -0,0 +1,271 @@
+/*
+ * Copyright (c) 1997-2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+/* $Id$ */
+
+#ifndef __KADM5_ADMIN_H__
+#define __KADM5_ADMIN_H__
+
+#define KADM5_API_VERSION_1 1
+#define KADM5_API_VERSION_2 2
+
+#ifndef USE_KADM5_API_VERSION
+#define USE_KADM5_API_VERSION KADM5_API_VERSION_2
+#endif
+
+#if USE_KADM5_API_VERSION != KADM5_API_VERSION_2
+#error No support for API versions other than 2
+#endif
+
+#define KADM5_STRUCT_VERSION 0
+
+/* For kadm5_log_get_version_fd() */
+#define LOG_VERSION_LAST -1
+#define LOG_VERSION_FIRST 1
+#define LOG_VERSION_UBER 0
+
+#include <krb5.h>
+
+#define KRB5_KDB_DISALLOW_POSTDATED 0x00000001
+#define KRB5_KDB_DISALLOW_FORWARDABLE 0x00000002
+#define KRB5_KDB_DISALLOW_TGT_BASED 0x00000004
+#define KRB5_KDB_DISALLOW_RENEWABLE 0x00000008
+#define KRB5_KDB_DISALLOW_PROXIABLE 0x00000010
+#define KRB5_KDB_DISALLOW_DUP_SKEY 0x00000020
+#define KRB5_KDB_DISALLOW_ALL_TIX 0x00000040
+#define KRB5_KDB_REQUIRES_PRE_AUTH 0x00000080
+#define KRB5_KDB_REQUIRES_HW_AUTH 0x00000100
+#define KRB5_KDB_REQUIRES_PWCHANGE 0x00000200
+#define KRB5_KDB_DISALLOW_SVR 0x00001000
+#define KRB5_KDB_PWCHANGE_SERVICE 0x00002000
+#define KRB5_KDB_SUPPORT_DESMD5 0x00004000
+#define KRB5_KDB_NEW_PRINC 0x00008000
+#define KRB5_KDB_OK_AS_DELEGATE 0x00010000 /* 0x00100000 in MIT */
+#define KRB5_KDB_TRUSTED_FOR_DELEGATION 0x00020000 /* MIT has as 0x00200000 */
+#define KRB5_KDB_ALLOW_KERBEROS4 0x00040000 /* MIT doesn't have this; XXX remove */
+#define KRB5_KDB_ALLOW_DIGEST 0x00080000 /* MIT doesn't have this */
+#define KRB5_KDB_MATERIALIZE 0x00100000 /* MIT doesn't have this */
+#define KRB5_KDB_VIRTUAL_KEYS 0x00200000 /* MIT doesn't have this */
+#define KRB5_KDB_VIRTUAL 0x00400000 /* MIT doesn't have this */
+#define KRB5_KDB_DISALLOW_CLIENT 0x00800000 /* MIT doesn't have this */
+#define KRB5_KDB_NO_AUTH_DATA_REQUIRED 0x01000000 /* 0x00400000 in MIT */
+
+/*
+ * MIT has:
+ *
+ * - Same as our KRB5_KDB_TRUSTED_FOR_DELEGATION:
+ *
+ * #define KRB5_KDB_OK_TO_AUTH_AS_DELEGATE 0x00200000 // S4U2Self OK
+ *
+ * - Misc:
+ *
+ * #define KRB5_KDB_NO_AUTH_DATA_REQUIRED 0x00400000 // Don't lookup / add
+ * // authz data
+ * #define KRB5_KDB_LOCKDOWN_KEYS 0x00800000 // Don't allow
+ * // deletion of princ
+ */
+
+
+#define KADM5_PRINCIPAL 0x000001U
+#define KADM5_PRINC_EXPIRE_TIME 0x000002U
+#define KADM5_PW_EXPIRATION 0x000004U
+#define KADM5_LAST_PWD_CHANGE 0x000008U
+#define KADM5_ATTRIBUTES 0x000010U
+#define KADM5_MAX_LIFE 0x000020U
+#define KADM5_MOD_TIME 0x000040U
+#define KADM5_MOD_NAME 0x000080U
+#define KADM5_KVNO 0x000100U
+#define KADM5_MKVNO 0x000200U
+#define KADM5_AUX_ATTRIBUTES 0x000400U
+#define KADM5_POLICY 0x000800U
+#define KADM5_POLICY_CLR 0x001000U
+#define KADM5_MAX_RLIFE 0x002000U
+#define KADM5_LAST_SUCCESS 0x004000U
+#define KADM5_LAST_FAILED 0x008000U
+#define KADM5_FAIL_AUTH_COUNT 0x010000U
+#define KADM5_KEY_DATA 0x020000U
+#define KADM5_TL_DATA 0x040000U
+
+#define KADM5_PRINCIPAL_NORMAL_MASK (~(KADM5_KEY_DATA | KADM5_TL_DATA))
+
+#define KADM5_PW_MAX_LIFE 0x004000
+#define KADM5_PW_MIN_LIFE 0x008000
+#define KADM5_PW_MIN_LENGTH 0x010000
+#define KADM5_PW_MIN_CLASSES 0x020000
+#define KADM5_PW_HISTORY_NUM 0x040000
+#define KADM5_REF_COUNT 0x080000
+
+#define KADM5_POLICY_NORMAL_MASK (~0)
+
+#define KADM5_ADMIN_SERVICE "kadmin/admin"
+#define KADM5_HIST_PRINCIPAL "kadmin/history"
+#define KADM5_CHANGEPW_SERVICE "kadmin/changepw"
+
+typedef struct {
+ int16_t key_data_ver; /* Version */
+ int16_t key_data_kvno; /* Key Version */
+ int16_t key_data_type[2]; /* Array of types */
+ int16_t key_data_length[2]; /* Array of lengths */
+ void* key_data_contents[2];/* Array of pointers */
+} krb5_key_data;
+
+typedef struct _krb5_keysalt {
+ int16_t type;
+ krb5_data data; /* Length, data */
+} krb5_keysalt;
+
+typedef struct _krb5_tl_data {
+ struct _krb5_tl_data* tl_data_next;
+ int16_t tl_data_type;
+ int16_t tl_data_length;
+ void* tl_data_contents;
+} krb5_tl_data;
+
+#define KRB5_TL_LAST_PWD_CHANGE 0x0001
+#define KRB5_TL_MOD_PRINC 0x0002
+#define KRB5_TL_KADM_DATA 0x0003
+#define KRB5_TL_KADM5_E_DATA 0x0004
+#define KRB5_TL_RB1_CHALLENGE 0x0005
+#define KRB5_TL_SECURID_STATE 0x0006
+#define KRB5_TL_PASSWORD 0x0007
+#define KRB5_TL_EXTENSION 0x0008
+#define KRB5_TL_PKINIT_ACL 0x0009
+#define KRB5_TL_ALIASES 0x000a
+#define KRB5_TL_HIST_KVNO_DIFF_CLNT 0x000b
+#define KRB5_TL_HIST_KVNO_DIFF_SVC 0x000c
+#define KRB5_TL_ETYPES 0x000d
+#define KRB5_TL_KEY_ROTATION 0x000e
+#define KRB5_TL_KRB5_CONFIG 0x000f
+
+typedef struct _kadm5_principal_ent_t {
+ krb5_principal principal;
+
+ krb5_timestamp princ_expire_time;
+ krb5_timestamp last_pwd_change;
+ krb5_timestamp pw_expiration;
+ krb5_deltat max_life;
+ krb5_principal mod_name;
+ krb5_timestamp mod_date;
+ krb5_flags attributes;
+ krb5_kvno kvno;
+ krb5_kvno mkvno;
+
+ char * policy;
+ uint32_t aux_attributes;
+
+ krb5_deltat max_renewable_life;
+ krb5_timestamp last_success;
+ krb5_timestamp last_failed;
+ krb5_kvno fail_auth_count;
+ int16_t n_key_data;
+ int16_t n_tl_data;
+ krb5_tl_data *tl_data;
+ krb5_key_data *key_data;
+} kadm5_principal_ent_rec, *kadm5_principal_ent_t;
+
+typedef struct _kadm5_policy_ent_t {
+ char *policy;
+
+ uint32_t pw_min_life;
+ uint32_t pw_max_life;
+ uint32_t pw_min_length;
+ uint32_t pw_min_classes;
+ uint32_t pw_history_num;
+ uint32_t policy_refcnt;
+} kadm5_policy_ent_rec, *kadm5_policy_ent_t;
+
+#define KADM5_CONFIG_REALM (1 << 0)
+#define KADM5_CONFIG_PROFILE (1 << 1)
+#define KADM5_CONFIG_KADMIND_PORT (1 << 2)
+#define KADM5_CONFIG_ADMIN_SERVER (1 << 3)
+#define KADM5_CONFIG_DBNAME (1 << 4)
+#define KADM5_CONFIG_ADBNAME (1 << 5)
+#define KADM5_CONFIG_ADB_LOCKFILE (1 << 6)
+#define KADM5_CONFIG_ACL_FILE (1 << 7)
+#define KADM5_CONFIG_DICT_FILE (1 << 8)
+#define KADM5_CONFIG_ADMIN_KEYTAB (1 << 9)
+#define KADM5_CONFIG_MKEY_FROM_KEYBOARD (1 << 10)
+#define KADM5_CONFIG_STASH_FILE (1 << 11)
+#define KADM5_CONFIG_MKEY_NAME (1 << 12)
+#define KADM5_CONFIG_ENCTYPE (1 << 13)
+#define KADM5_CONFIG_MAX_LIFE (1 << 14)
+#define KADM5_CONFIG_MAX_RLIFE (1 << 15)
+#define KADM5_CONFIG_EXPIRATION (1 << 16)
+#define KADM5_CONFIG_FLAGS (1 << 17)
+#define KADM5_CONFIG_ENCTYPES (1 << 18)
+#define KADM5_CONFIG_READONLY_ADMIN_SERVER (1 << 19)
+#define KADM5_CONFIG_READONLY_KADMIN_PORT (1 << 20)
+
+#define KADM5_PRIV_GET (1 << 0)
+#define KADM5_PRIV_ADD (1 << 1)
+#define KADM5_PRIV_MODIFY (1 << 2)
+#define KADM5_PRIV_DELETE (1 << 3)
+#define KADM5_PRIV_LIST (1 << 4)
+#define KADM5_PRIV_CPW (1 << 5)
+#define KADM5_PRIV_GET_KEYS (1 << 6)
+
+/* Note: KADM5_PRIV_GET_KEYS not included */
+#define KADM5_PRIV_ALL (KADM5_PRIV_GET | KADM5_PRIV_ADD | KADM5_PRIV_MODIFY | KADM5_PRIV_DELETE | KADM5_PRIV_LIST | KADM5_PRIV_CPW)
+
+#define KADM5_BOGUS_KEY_DATA "\xe5\xe5\xe5\xe5"
+
+/*
+ * ABI NOTE: We can add fields at the end of this provided that we define new
+ * mask bits that must be set in the mask field when setting the new fields.
+ */
+typedef struct _kadm5_config_params {
+ uint32_t mask;
+
+ /* Client and server fields */
+ char *realm;
+ int kadmind_port;
+
+ /* client fields */
+ char *admin_server;
+
+ /* server fields */
+ char *dbname;
+ char *acl_file;
+
+ /* server library (database) fields */
+ char *stash_file;
+
+ /* read-only kadmin server */
+ char *readonly_admin_server;
+ int readonly_kadmind_port;
+} kadm5_config_params;
+
+typedef krb5_error_code kadm5_ret_t;
+
+#include "kadm5-protos.h"
+
+#endif /* __KADM5_ADMIN_H__ */
diff --git a/third_party/heimdal/lib/kadm5/bump_pw_expire.c b/third_party/heimdal/lib/kadm5/bump_pw_expire.c
new file mode 100644
index 0000000..5d72360
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/bump_pw_expire.c
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+/*
+ * extend password_expiration if it's defined
+ */
+
+kadm5_ret_t
+_kadm5_bump_pw_expire(kadm5_server_context *context,
+ hdb_entry *ent)
+{
+ if (ent->pw_end != NULL) {
+ time_t life;
+
+ life = krb5_config_get_time_default(context->context,
+ NULL,
+ 365 * 24 * 60 * 60,
+ "kadmin",
+ "password_lifetime",
+ NULL);
+
+ *(ent->pw_end) = time(NULL) + life;
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/check-cracklib.pl b/third_party/heimdal/lib/kadm5/check-cracklib.pl
new file mode 100644
index 0000000..a6fbd4c
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/check-cracklib.pl
@@ -0,0 +1,112 @@
+#!/usr/pkg/bin/perl
+#
+# Sample password verifier for Heimdals external password
+# verifier, see the chapter "Password changing" in the the info
+# documentation for more information about the protocol used.
+#
+# Three checks
+# 1. Check that password is not the principal name
+# 2. Check that the password passes cracklib
+# 3. Check that password isn't repeated for this principal
+#
+# The repeat check must be last because some clients ask
+# twice when getting "no" back and thus the error message
+# would be wrong.
+#
+# Prereqs (example versions):
+#
+# * perl (5.8.5) http://www.perl.org/
+# * cracklib (2.8.5) http://sourceforge.net/projects/cracklib
+# * Crypt-Cracklib perlmodule (0.01) http://search.cpan.org/~daniel/
+#
+# Sample dictionaries:
+# cracklib-words (1.1) http://sourceforge.net/projects/cracklib
+# miscfiles (1.4.2) http://directory.fsf.org/miscfiles.html
+#
+# Configuration for krb5.conf or kdc.conf
+#
+# [password_quality]
+# policies = builtin:external-check
+# external_program = <your-path>/check-cracklib.pl
+#
+# $Id$
+
+use strict;
+use Crypt::Cracklib;
+use Digest::MD5;
+
+# NEED TO CHANGE THESE TO MATCH YOUR SYSTEM
+my $database = '/usr/lib/cracklib_dict';
+my $historydb = '/var/heimdal/historydb';
+# NEED TO CHANGE THESE TO MATCH YOUR SYSTEM
+
+# seconds password reuse allowed (to catch retries from clients)
+my $reusetime = 60;
+
+my %params;
+
+sub check_basic
+{
+ my $principal = shift;
+ my $passwd = shift;
+
+ if ($principal eq $passwd) {
+ return "Principal name as password is not allowed";
+ }
+ return "ok";
+}
+
+sub check_repeat
+{
+ my $principal = shift;
+ my $passwd = shift;
+ my $result = 'Do not reuse passwords';
+ my %DB;
+ my $md5context = new Digest::MD5;
+ my $timenow = scalar(time());
+
+ $md5context->reset();
+ $md5context->add($principal, ":", $passwd);
+
+ my $key=$md5context->hexdigest();
+
+ dbmopen(%DB,$historydb,0600) or die "Internal: Could not open $historydb";
+ if (!$DB{$key} || ($timenow - $DB{$key} < $reusetime)) {
+ $result = "ok";
+ $DB{$key}=$timenow;
+ }
+ dbmclose(%DB) or die "Internal: Could not close $historydb";
+ return $result;
+}
+
+sub badpassword
+{
+ my $reason = shift;
+ print "$reason\n";
+ exit 0
+}
+
+while (<STDIN>) {
+ last if /^end$/;
+ if (!/^([^:]+): (.+)$/) {
+ die "key value pair not correct: $_";
+ }
+ $params{$1} = $2;
+}
+
+die "missing principal" if (!defined $params{'principal'});
+die "missing password" if (!defined $params{'new-password'});
+
+my $reason;
+
+$reason = check_basic($params{'principal'}, $params{'new-password'});
+badpassword($reason) if ($reason ne "ok");
+
+$reason = fascist_check($params{'new-password'}, $database);
+badpassword($reason) if ($reason ne "ok");
+
+$reason = check_repeat($params{'principal'}, $params{'new-password'});
+badpassword($reason) if ($reason ne "ok");
+
+print "APPROVED\n";
+exit 0
diff --git a/third_party/heimdal/lib/kadm5/chpass_c.c b/third_party/heimdal/lib/kadm5/chpass_c.c
new file mode 100644
index 0000000..1036918
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/chpass_c.c
@@ -0,0 +1,175 @@
+/*
+ * Copyright (c) 1997-2000, 2005-2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_c_chpass_principal(void *server_handle,
+ krb5_principal princ,
+ int keepold,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ const char *password)
+{
+ kadm5_client_context *context = server_handle;
+ kadm5_ret_t ret;
+ krb5_storage *sp;
+ unsigned char buf[1024];
+ int32_t tmp;
+ krb5_data reply;
+
+ /*
+ * We should get around to implementing this... At the moment, the
+ * the server side API is implemented but the wire protocol has not
+ * been updated.
+ */
+ if (n_ks_tuple > 0)
+ return KADM5_KS_TUPLE_NOSUPP;
+
+ ret = _kadm5_connect(server_handle, 1 /* want_write */);
+ if (ret)
+ return ret;
+
+ krb5_data_zero(&reply);
+
+ sp = krb5_storage_from_mem(buf, sizeof(buf));
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_store_int32(sp, kadm_chpass);
+ if (ret)
+ goto out;
+ ret = krb5_store_principal(sp, princ);
+ if (ret)
+ goto out;
+ ret = krb5_store_string(sp, password);
+ if (ret)
+ goto out;
+ ret = krb5_store_int32(sp, keepold); /* extension */
+ if (ret)
+ goto out;
+ ret = _kadm5_client_send(context, sp);
+ if (ret)
+ goto out_keep_error;
+ ret = _kadm5_client_recv(context, &reply);
+ if (ret)
+ goto out_keep_error;
+ krb5_storage_free(sp);
+ sp = krb5_storage_from_data(&reply);
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret == 0)
+ ret = tmp;
+
+ out:
+ krb5_clear_error_message(context->context);
+
+ out_keep_error:
+ krb5_storage_free(sp);
+ krb5_data_free(&reply);
+ return ret;
+}
+
+kadm5_ret_t
+kadm5_c_chpass_principal_with_key(void *server_handle,
+ krb5_principal princ,
+ int keepold,
+ int n_key_data,
+ krb5_key_data *key_data)
+{
+ kadm5_client_context *context = server_handle;
+ kadm5_ret_t ret;
+ krb5_storage *sp;
+ unsigned char buf[1024];
+ int32_t tmp;
+ krb5_data reply;
+ int i;
+
+ ret = _kadm5_connect(server_handle, 1 /* want_write */);
+ if (ret)
+ return ret;
+
+ krb5_data_zero(&reply);
+
+ sp = krb5_storage_from_mem(buf, sizeof(buf));
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_store_int32(sp, kadm_chpass_with_key);
+ if (ret)
+ goto out;
+ ret = krb5_store_principal(sp, princ);
+ if (ret)
+ goto out;
+ ret = krb5_store_int32(sp, n_key_data);
+ if (ret)
+ goto out;
+ for (i = 0; i < n_key_data; ++i) {
+ ret = kadm5_store_key_data (sp, &key_data[i]);
+ if (ret)
+ goto out;
+ }
+ ret = krb5_store_int32(sp, keepold); /* extension */
+ if (ret)
+ goto out;
+ ret = _kadm5_client_send(context, sp);
+ if (ret)
+ goto out_keep_error;
+ ret = _kadm5_client_recv(context, &reply);
+ if (ret)
+ goto out_keep_error;
+ krb5_storage_free(sp);
+ sp = krb5_storage_from_data (&reply);
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret == 0)
+ ret = tmp;
+
+ out:
+ krb5_clear_error_message(context->context);
+
+ out_keep_error:
+ krb5_storage_free(sp);
+ krb5_data_free(&reply);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kadm5/chpass_s.c b/third_party/heimdal/lib/kadm5/chpass_s.c
new file mode 100644
index 0000000..c89448f
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/chpass_s.c
@@ -0,0 +1,466 @@
+/*
+ * Copyright (c) 1997-2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+struct chpass_principal_hook_ctx {
+ kadm5_server_context *context;
+ enum kadm5_hook_stage stage;
+ krb5_error_code code;
+ krb5_const_principal princ;
+ uint32_t flags;
+ size_t n_ks_tuple;
+ krb5_key_salt_tuple *ks_tuple;
+ const char *password;
+};
+
+static krb5_error_code KRB5_LIB_CALL
+chpass_principal_hook_cb(krb5_context context,
+ const void *hook,
+ void *hookctx,
+ void *userctx)
+{
+ krb5_error_code ret;
+ const struct kadm5_hook_ftable *ftable = hook;
+ struct chpass_principal_hook_ctx *ctx = userctx;
+
+ ret = ftable->chpass(context, hookctx,
+ ctx->stage, ctx->code, ctx->princ,
+ ctx->flags, ctx->n_ks_tuple, ctx->ks_tuple,
+ ctx->password);
+ if (ret != 0 && ret != KRB5_PLUGIN_NO_HANDLE)
+ _kadm5_s_set_hook_error_message(ctx->context, ret, "chpass",
+ hook, ctx->stage);
+
+ /* only pre-commit plugins can abort */
+ if (ret == 0 || ctx->stage == KADM5_HOOK_STAGE_POSTCOMMIT)
+ ret = KRB5_PLUGIN_NO_HANDLE;
+
+ return ret;
+}
+
+static kadm5_ret_t
+chpass_principal_hook(kadm5_server_context *context,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ,
+ uint32_t flags,
+ size_t n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ const char *password)
+{
+ krb5_error_code ret;
+ struct chpass_principal_hook_ctx ctx;
+
+ ctx.context = context;
+ ctx.stage = stage;
+ ctx.code = code;
+ ctx.princ = princ;
+ ctx.flags = flags;
+ ctx.n_ks_tuple = n_ks_tuple;
+ ctx.ks_tuple = ks_tuple;
+ ctx.password = password;
+
+ ret = _krb5_plugin_run_f(context->context, &kadm5_hook_plugin_data,
+ 0, &ctx, chpass_principal_hook_cb);
+ if (ret == KRB5_PLUGIN_NO_HANDLE)
+ ret = 0;
+
+ return ret;
+}
+
+static kadm5_ret_t
+change(void *server_handle,
+ krb5_principal princ,
+ int keepold,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ const char *password,
+ int cond)
+{
+ kadm5_server_context *context = server_handle;
+ hdb_entry ent;
+ kadm5_ret_t ret;
+ Key *keys;
+ size_t num_keys;
+ int existsp = 0;
+ uint32_t hook_flags = 0;
+
+ memset(&ent, 0, sizeof(ent));
+
+ if (krb5_principal_compare(context->context, princ, context->caller) ||
+ _kadm5_enforce_pwqual_on_admin_set_p(context)) {
+ krb5_data pwd_data;
+ const char *pwd_reason;
+
+ pwd_data.data = rk_UNCONST(password);
+ pwd_data.length = strlen(password);
+
+ pwd_reason = kadm5_check_password_quality(context->context,
+ princ, &pwd_data);
+ if (pwd_reason != NULL) {
+ krb5_set_error_message(context->context, KADM5_PASS_Q_GENERIC, "%s", pwd_reason);
+ return KADM5_PASS_Q_GENERIC;
+ }
+ }
+
+ if (!context->keep_open) {
+ ret = context->db->hdb_open(context->context, context->db, O_RDWR, 0);
+ if(ret)
+ return ret;
+ }
+
+ ret = kadm5_log_init(context);
+ if (ret)
+ goto out;
+
+ ret = context->db->hdb_fetch_kvno(context->context, context->db, princ,
+ HDB_F_DECRYPT|HDB_F_GET_ANY|HDB_F_ADMIN_DATA,
+ 0, &ent);
+ if (ret)
+ goto out2;
+
+ if (keepold)
+ hook_flags |= KADM5_HOOK_FLAG_KEEPOLD;
+ if (cond)
+ hook_flags |= KADM5_HOOK_FLAG_CONDITIONAL;
+ ret = chpass_principal_hook(context, KADM5_HOOK_STAGE_PRECOMMIT,
+ 0, princ, hook_flags,
+ n_ks_tuple, ks_tuple, password);
+ if (ret)
+ goto out3;
+
+ if (keepold || cond) {
+ /*
+ * We save these for now so we can handle password history checking;
+ * we handle keepold further below.
+ */
+ ret = hdb_add_current_keys_to_history(context->context, &ent);
+ if (ret)
+ goto out3;
+ }
+
+ if (context->db->hdb_capability_flags & HDB_CAP_F_HANDLE_PASSWORDS) {
+ ret = context->db->hdb_password(context->context, context->db,
+ &ent, password, cond);
+ if (ret)
+ goto out3;
+ } else {
+
+ num_keys = ent.keys.len;
+ keys = ent.keys.val;
+
+ ent.keys.len = 0;
+ ent.keys.val = NULL;
+
+ ret = _kadm5_set_keys(context, &ent, n_ks_tuple, ks_tuple,
+ password);
+ if(ret) {
+ _kadm5_free_keys(context->context, num_keys, keys);
+ goto out3;
+ }
+ _kadm5_free_keys(context->context, num_keys, keys);
+
+ if (cond) {
+ HDB_extension *ext;
+
+ ext = hdb_find_extension(&ent, choice_HDB_extension_data_hist_keys);
+ if (ext != NULL)
+ existsp = _kadm5_exists_keys_hist(ent.keys.val,
+ ent.keys.len,
+ &ext->data.u.hist_keys);
+ }
+
+ if (existsp) {
+ ret = KADM5_PASS_REUSE;
+ krb5_set_error_message(context->context, ret,
+ "Password reuse forbidden");
+ goto out3;
+ }
+ }
+ ent.kvno++;
+
+ ent.flags.require_pwchange = 0;
+
+ if (!keepold) {
+ HDB_extension ext;
+
+ memset(&ext, 0, sizeof (ext));
+ ext.mandatory = FALSE;
+ ext.data.element = choice_HDB_extension_data_hist_keys;
+ ret = hdb_replace_extension(context->context, &ent, &ext);
+ if (ret)
+ goto out3;
+ }
+
+ ret = hdb_seal_keys(context->context, context->db, &ent);
+ if (ret)
+ goto out3;
+
+ ret = _kadm5_set_modifier(context, &ent);
+ if(ret)
+ goto out3;
+
+ ret = _kadm5_bump_pw_expire(context, &ent);
+ if (ret)
+ goto out3;
+
+ /* This logs the change for iprop and writes to the HDB */
+ ret = kadm5_log_modify(context, &ent,
+ KADM5_ATTRIBUTES | KADM5_PRINCIPAL |
+ KADM5_MOD_NAME | KADM5_MOD_TIME |
+ KADM5_KEY_DATA | KADM5_KVNO |
+ KADM5_PW_EXPIRATION | KADM5_TL_DATA);
+
+ (void) chpass_principal_hook(context, KADM5_HOOK_STAGE_POSTCOMMIT,
+ ret, princ, hook_flags,
+ n_ks_tuple, ks_tuple, password);
+
+ out3:
+ hdb_free_entry(context->context, context->db, &ent);
+ out2:
+ (void) kadm5_log_end(context);
+ out:
+ if (!context->keep_open) {
+ kadm5_ret_t ret2;
+ ret2 = context->db->hdb_close(context->context, context->db);
+ if (ret == 0 && ret2 != 0)
+ ret = ret2;
+ }
+ return _kadm5_error_code(ret);
+}
+
+
+
+/*
+ * change the password of `princ' to `password' if it's not already that.
+ */
+
+kadm5_ret_t
+kadm5_s_chpass_principal_cond(void *server_handle,
+ krb5_principal princ,
+ int keepold,
+ const char *password)
+{
+ return change (server_handle, princ, keepold, 0, NULL, password, 1);
+}
+
+/*
+ * change the password of `princ' to `password'
+ */
+
+kadm5_ret_t
+kadm5_s_chpass_principal(void *server_handle,
+ krb5_principal princ,
+ int keepold,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ const char *password)
+{
+ return change (server_handle, princ, keepold,
+ n_ks_tuple, ks_tuple, password, 0);
+}
+
+struct chpass_principal_with_key_hook_ctx {
+ kadm5_server_context *context;
+ enum kadm5_hook_stage stage;
+ krb5_error_code code;
+ krb5_const_principal princ;
+ uint32_t flags;
+ size_t n_key_data;
+ krb5_key_data *key_data;
+};
+
+static krb5_error_code KRB5_LIB_CALL
+chpass_principal_with_key_hook_cb(krb5_context context,
+ const void *hook,
+ void *hookctx,
+ void *userctx)
+{
+ krb5_error_code ret;
+ const struct kadm5_hook_ftable *ftable = hook;
+ struct chpass_principal_with_key_hook_ctx *ctx = userctx;
+
+ ret = ftable->chpass_with_key(context, hookctx,
+ ctx->stage, ctx->code, ctx->princ,
+ ctx->flags, ctx->n_key_data, ctx->key_data);
+ if (ret != 0 && ret != KRB5_PLUGIN_NO_HANDLE)
+ _kadm5_s_set_hook_error_message(ctx->context, ret, "chpass_with_key",
+ hook, ctx->stage);
+
+ /* only pre-commit plugins can abort */
+ if (ret == 0 || ctx->stage == KADM5_HOOK_STAGE_POSTCOMMIT)
+ ret = KRB5_PLUGIN_NO_HANDLE;
+
+ return ret;
+}
+
+static kadm5_ret_t
+chpass_principal_with_key_hook(kadm5_server_context *context,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ,
+ uint32_t flags,
+ size_t n_key_data,
+ krb5_key_data *key_data)
+{
+ krb5_error_code ret;
+ struct chpass_principal_with_key_hook_ctx ctx;
+
+ ctx.context = context;
+ ctx.stage = stage;
+ ctx.code = code;
+ ctx.princ = princ;
+ ctx.flags = flags;
+ ctx.n_key_data = n_key_data;
+ ctx.key_data = key_data;
+
+ ret = _krb5_plugin_run_f(context->context, &kadm5_hook_plugin_data,
+ 0, &ctx, chpass_principal_with_key_hook_cb);
+ if (ret == KRB5_PLUGIN_NO_HANDLE)
+ ret = 0;
+
+ return ret;
+}
+
+/*
+ * change keys for `princ' to `keys'
+ */
+
+kadm5_ret_t
+kadm5_s_chpass_principal_with_key(void *server_handle,
+ krb5_principal princ,
+ int keepold,
+ int n_key_data,
+ krb5_key_data *key_data)
+{
+ kadm5_server_context *context = server_handle;
+ hdb_entry ent;
+ kadm5_ret_t ret;
+ uint32_t hook_flags = 0;
+
+ memset(&ent, 0, sizeof(ent));
+ if (!context->keep_open) {
+ ret = context->db->hdb_open(context->context, context->db, O_RDWR, 0);
+ if(ret)
+ return ret;
+ }
+
+ ret = kadm5_log_init(context);
+ if (ret)
+ goto out;
+
+ ret = context->db->hdb_fetch_kvno(context->context, context->db, princ,
+ HDB_F_GET_ANY|HDB_F_ADMIN_DATA, 0, &ent);
+ if (ret == HDB_ERR_NOENTRY)
+ goto out2;
+
+ if (keepold)
+ hook_flags |= KADM5_HOOK_FLAG_KEEPOLD;
+ ret = chpass_principal_with_key_hook(context, KADM5_HOOK_STAGE_PRECOMMIT,
+ 0, princ, hook_flags,
+ n_key_data, key_data);
+ if (ret)
+ goto out3;
+
+ if (keepold) {
+ ret = hdb_add_current_keys_to_history(context->context, &ent);
+ if (ret)
+ goto out3;
+ }
+ ret = _kadm5_set_keys2(context, &ent, n_key_data, key_data);
+ if (ret)
+ goto out3;
+ ent.kvno++;
+ ret = _kadm5_set_modifier(context, &ent);
+ if (ret)
+ goto out3;
+ ret = _kadm5_bump_pw_expire(context, &ent);
+ if (ret)
+ goto out3;
+
+ if (keepold) {
+ ret = hdb_seal_keys(context->context, context->db, &ent);
+ if (ret)
+ goto out3;
+ } else {
+ HDB_extension ext;
+
+ memset(&ext, 0, sizeof (ext));
+ ext.mandatory = FALSE;
+ ext.data.element = choice_HDB_extension_data_hist_keys;
+ ext.data.u.hist_keys.len = 0;
+ ext.data.u.hist_keys.val = NULL;
+ hdb_replace_extension(context->context, &ent, &ext);
+ }
+
+ /* This logs the change for iprop and writes to the HDB */
+ ret = kadm5_log_modify(context, &ent,
+ KADM5_PRINCIPAL | KADM5_MOD_NAME |
+ KADM5_MOD_TIME | KADM5_KEY_DATA | KADM5_KVNO |
+ KADM5_PW_EXPIRATION | KADM5_TL_DATA);
+
+ (void) chpass_principal_with_key_hook(context, KADM5_HOOK_STAGE_POSTCOMMIT,
+ ret, princ, hook_flags,
+ n_key_data, key_data);
+
+ out3:
+ hdb_free_entry(context->context, context->db, &ent);
+ out2:
+ (void) kadm5_log_end(context);
+ out:
+ if (!context->keep_open) {
+ kadm5_ret_t ret2;
+ ret2 = context->db->hdb_close(context->context, context->db);
+ if (ret == 0 && ret2 != 0)
+ ret = ret2;
+ }
+ return _kadm5_error_code(ret);
+}
+
+/*
+ * Returns TRUE if password quality should be checked when passwords are
+ * being set or changed by administrators. This includes principal creation.
+ */
+krb5_boolean
+_kadm5_enforce_pwqual_on_admin_set_p(kadm5_server_context *contextp)
+{
+ if (_kadm5_is_kadmin_service_p(contextp))
+ return FALSE;
+
+ return krb5_config_get_bool_default(contextp->context, NULL, TRUE,
+ "password_quality",
+ "enforce_on_admin_set", NULL);
+}
diff --git a/third_party/heimdal/lib/kadm5/client_glue.c b/third_party/heimdal/lib/kadm5/client_glue.c
new file mode 100644
index 0000000..2783a9a
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/client_glue.c
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_init_with_password(const char *client_name,
+ const char *password,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_c_init_with_password(client_name,
+ password,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_init_with_password_ctx(krb5_context context,
+ const char *client_name,
+ const char *password,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_c_init_with_password_ctx(context,
+ client_name,
+ password,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_init_with_skey(const char *client_name,
+ const char *keytab,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_c_init_with_skey(client_name,
+ keytab,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_init_with_skey_ctx(krb5_context context,
+ const char *client_name,
+ const char *keytab,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_c_init_with_skey_ctx(context,
+ client_name,
+ keytab,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_init_with_creds(const char *client_name,
+ krb5_ccache ccache,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_c_init_with_creds(client_name,
+ ccache,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_init_with_creds_ctx(krb5_context context,
+ const char *client_name,
+ krb5_ccache ccache,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_c_init_with_creds_ctx(context,
+ client_name,
+ ccache,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
diff --git a/third_party/heimdal/lib/kadm5/common_glue.c b/third_party/heimdal/lib/kadm5/common_glue.c
new file mode 100644
index 0000000..9993b0a
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/common_glue.c
@@ -0,0 +1,437 @@
+/*
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+#define __CALL(F, P) (*((kadm5_common_context*)server_handle)->funcs.F)P
+#define __CALLABLE(F) (((kadm5_common_context*)server_handle)->funcs.F != 0)
+
+kadm5_ret_t
+kadm5_chpass_principal(void *server_handle,
+ krb5_principal princ,
+ const char *password)
+{
+ return __CALL(chpass_principal, (server_handle, princ, 0,
+ 0, NULL, password));
+}
+
+kadm5_ret_t
+kadm5_chpass_principal_3(void *server_handle,
+ krb5_principal princ,
+ krb5_boolean keepold,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ const char *password)
+{
+ return __CALL(chpass_principal, (server_handle, princ, keepold,
+ n_ks_tuple, ks_tuple, password));
+}
+
+kadm5_ret_t
+kadm5_chpass_principal_with_key(void *server_handle,
+ krb5_principal princ,
+ int n_key_data,
+ krb5_key_data *key_data)
+{
+ return __CALL(chpass_principal_with_key,
+ (server_handle, princ, 0, n_key_data, key_data));
+}
+
+kadm5_ret_t
+kadm5_chpass_principal_with_key_3(void *server_handle,
+ krb5_principal princ,
+ int keepold,
+ int n_key_data,
+ krb5_key_data *key_data)
+{
+ return __CALL(chpass_principal_with_key,
+ (server_handle, princ, keepold, n_key_data, key_data));
+}
+
+kadm5_ret_t
+kadm5_create_principal_3(void *server_handle,
+ kadm5_principal_ent_t princ,
+ uint32_t mask,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ char *password)
+{
+ return __CALL(create_principal,
+ (server_handle, princ, mask, n_ks_tuple, ks_tuple, password));
+}
+
+kadm5_ret_t
+kadm5_create_principal(void *server_handle,
+ kadm5_principal_ent_t princ,
+ uint32_t mask,
+ const char *password)
+{
+ return __CALL(create_principal,
+ (server_handle, princ, mask, 0, NULL, password));
+}
+
+kadm5_ret_t
+kadm5_delete_principal(void *server_handle,
+ krb5_principal princ)
+{
+ return __CALL(delete_principal, (server_handle, princ));
+}
+
+kadm5_ret_t
+kadm5_destroy (void *server_handle)
+{
+ return __CALL(destroy, (server_handle));
+}
+
+kadm5_ret_t
+kadm5_flush (void *server_handle)
+{
+ return __CALL(flush, (server_handle));
+}
+
+kadm5_ret_t
+kadm5_get_principal(void *server_handle,
+ krb5_principal princ,
+ kadm5_principal_ent_t out,
+ uint32_t mask)
+{
+ return __CALL(get_principal, (server_handle, princ, out, mask));
+}
+
+/**
+ * Extract decrypted keys from kadm5_principal_ent_t object. Mostly a
+ * no-op for Heimdal because we fetch the entry with decrypted keys.
+ * Sadly this is not fully a no-op, as we have to allocate a copy.
+ *
+ * @server_handle is the kadm5 handle
+ * @entry is the HDB entry for the principal in question
+ * @ktype is the enctype to get a key for, or -1 to get the first one
+ * @stype is the salttype to get a key for, or -1 to get the first match
+ * @kvno is the kvno to search for, or -1 to get the first match (highest kvno)
+ * @keyblock is where the key will be placed
+ * @keysalt, if not NULL, is where the salt will be placed
+ * @kvnop, if not NULL, is where the selected kvno will be placed
+ */
+kadm5_ret_t
+kadm5_decrypt_key(void *server_handle,
+ kadm5_principal_ent_t entry,
+ int32_t ktype, int32_t stype,
+ int32_t kvno, krb5_keyblock *keyblock,
+ krb5_keysalt *keysalt, int *kvnop)
+{
+ size_t i;
+ kadm5_server_context *context = server_handle;
+
+ if (kvno < 1 || stype != -1)
+ return KADM5_DECRYPT_USAGE_NOSUPP;
+
+ for (i = 0; i < entry->n_key_data; i++) {
+ if (ktype != entry->key_data[i].key_data_kvno)
+ continue;
+
+ keyblock->keytype = ktype;
+ keyblock->keyvalue.length = entry->key_data[i].key_data_length[0];
+ keyblock->keyvalue.data = malloc(keyblock->keyvalue.length);
+ if (keyblock->keyvalue.data == NULL)
+ return krb5_enomem(context->context);
+ memcpy(keyblock->keyvalue.data,
+ entry->key_data[i].key_data_contents[0],
+ keyblock->keyvalue.length);
+ }
+
+ return 0;
+}
+
+kadm5_ret_t
+kadm5_modify_principal(void *server_handle,
+ kadm5_principal_ent_t princ,
+ uint32_t mask)
+{
+ return __CALL(modify_principal, (server_handle, princ, mask));
+}
+
+kadm5_ret_t
+kadm5_randkey_principal(void *server_handle,
+ krb5_principal princ,
+ krb5_keyblock **new_keys,
+ int *n_keys)
+{
+ return __CALL(randkey_principal, (server_handle, princ, FALSE, 0, NULL,
+ new_keys, n_keys));
+}
+
+kadm5_ret_t
+kadm5_randkey_principal_3(void *server_handle,
+ krb5_principal princ,
+ krb5_boolean keepold,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ krb5_keyblock **new_keys,
+ int *n_keys)
+{
+ return __CALL(randkey_principal, (server_handle, princ, keepold,
+ n_ks_tuple, ks_tuple, new_keys, n_keys));
+}
+
+kadm5_ret_t
+kadm5_rename_principal(void *server_handle,
+ krb5_principal source,
+ krb5_principal target)
+{
+ return __CALL(rename_principal, (server_handle, source, target));
+}
+
+kadm5_ret_t
+kadm5_get_principals(void *server_handle,
+ const char *expression,
+ char ***princs,
+ int *count)
+{
+ return __CALL(get_principals, (server_handle, expression, princs, count));
+}
+
+kadm5_ret_t
+kadm5_get_privs(void *server_handle,
+ uint32_t *privs)
+{
+ return __CALL(get_privs, (server_handle, privs));
+}
+
+
+/**
+ * This function is allows the caller to set new keys for a principal.
+ * This is a trivial wrapper around kadm5_setkey_principal_3().
+ */
+kadm5_ret_t
+kadm5_setkey_principal(void *server_handle,
+ krb5_principal princ,
+ krb5_keyblock *new_keys,
+ int n_keys)
+{
+ return kadm5_setkey_principal_3(server_handle, princ, 0, 0, NULL,
+ new_keys, n_keys);
+}
+
+/**
+ * This function is allows the caller to set new keys for a principal.
+ * This is a simple wrapper around kadm5_get_principal() and
+ * kadm5_modify_principal().
+ */
+kadm5_ret_t
+kadm5_setkey_principal_3(void *server_handle,
+ krb5_principal princ,
+ krb5_boolean keepold,
+ int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
+ krb5_keyblock *keyblocks,
+ int n_keys)
+{
+ kadm5_principal_ent_rec princ_ent;
+ kadm5_ret_t ret;
+ krb5_key_data *new_key_data = NULL;
+ size_t i;
+ kadm5_server_context *context = server_handle;
+
+ if (n_keys < 1)
+ return EINVAL;
+ if (n_ks_tuple > 0 && n_ks_tuple != n_keys)
+ return KADM5_SETKEY3_ETYPE_MISMATCH;
+
+ /*
+ * If setkey_principal_3 is defined in the server handle, use that.
+ */
+ if (__CALLABLE(setkey_principal_3))
+ return __CALL(setkey_principal_3,
+ (server_handle, princ, keepold, n_ks_tuple, ks_tuple,
+ keyblocks, n_keys));
+
+ /*
+ * Otherwise, simulate it via a get, update, modify sequence.
+ */
+ ret = kadm5_get_principal(server_handle, princ, &princ_ent,
+ KADM5_KVNO | KADM5_PRINCIPAL | KADM5_KEY_DATA);
+ if (ret)
+ return ret;
+
+ if (keepold) {
+ new_key_data = calloc((n_keys + princ_ent.n_key_data),
+ sizeof(*new_key_data));
+ if (new_key_data == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+
+ memcpy(&new_key_data[n_keys], &princ_ent.key_data[0],
+ princ_ent.n_key_data * sizeof (princ_ent.key_data[0]));
+ } else {
+ new_key_data = calloc(n_keys, sizeof(*new_key_data));
+ if (new_key_data == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ }
+
+ princ_ent.kvno++;
+ for (i = 0; i < n_keys; i++) {
+ new_key_data[i].key_data_ver = 2;
+
+ /* Key */
+ new_key_data[i].key_data_kvno = princ_ent.kvno;
+ new_key_data[i].key_data_type[0] = keyblocks[i].keytype;
+ new_key_data[i].key_data_length[0] = keyblocks[i].keyvalue.length;
+ new_key_data[i].key_data_contents[0] =
+ malloc(keyblocks[i].keyvalue.length);
+ if (new_key_data[i].key_data_contents[0] == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ memcpy(new_key_data[i].key_data_contents[0],
+ keyblocks[i].keyvalue.data,
+ keyblocks[i].keyvalue.length);
+
+ /*
+ * Salt (but there's no salt, just salttype, which is kinda
+ * silly -- what's the point of setkey_3() then, besides
+ * keepold?!)
+ */
+ new_key_data[i].key_data_type[1] = 0;
+ if (n_ks_tuple > 0) {
+ if (ks_tuple[i].ks_enctype != keyblocks[i].keytype) {
+ ret = KADM5_SETKEY3_ETYPE_MISMATCH;
+ goto out;
+ }
+ new_key_data[i].key_data_type[1] = ks_tuple[i].ks_salttype;
+ }
+ new_key_data[i].key_data_length[1] = 0;
+ new_key_data[i].key_data_contents[1] = NULL;
+ }
+
+ /* Free old keys */
+ if (!keepold) {
+ for (i = 0; i < princ_ent.n_key_data; i++) {
+ free(princ_ent.key_data[i].key_data_contents[0]);
+ free(princ_ent.key_data[i].key_data_contents[1]);
+ }
+ }
+ free(princ_ent.key_data);
+ princ_ent.key_data = new_key_data;
+ princ_ent.n_key_data = n_keys + (keepold ? princ_ent.n_key_data : 0);
+ new_key_data = NULL;
+
+ /* Modify the principal */
+ ret = kadm5_modify_principal(server_handle, &princ_ent, KADM5_KVNO | KADM5_KEY_DATA);
+
+out:
+ if (new_key_data != NULL) {
+ for (i = 0; i < n_keys; i++) {
+ free(new_key_data[i].key_data_contents[0]);
+ free(new_key_data[i].key_data_contents[1]);
+ }
+ free(new_key_data);
+ }
+ kadm5_free_principal_ent(server_handle, &princ_ent);
+ return ret;
+}
+
+
+kadm5_ret_t
+kadm5_lock(void *server_handle)
+{
+ return __CALL(lock, (server_handle));
+}
+
+kadm5_ret_t
+kadm5_unlock(void *server_handle)
+{
+ return __CALL(unlock, (server_handle));
+}
+
+
+kadm5_ret_t
+kadm5_create_policy(void *server_handle,
+ kadm5_policy_ent_t policy, long mask)
+{
+ return KADM5_POLICY_OP_NOSUPP;
+}
+
+kadm5_ret_t
+kadm5_delete_policy(void *server_handle, char *name)
+{
+ return KADM5_POLICY_OP_NOSUPP;
+}
+
+
+kadm5_ret_t
+kadm5_modify_policy(void *server_handle, kadm5_policy_ent_t policy,
+ uint32_t mask)
+{
+ return KADM5_POLICY_OP_NOSUPP;
+}
+
+kadm5_ret_t
+kadm5_get_policy(void *server_handle, char *policy, kadm5_policy_ent_t ent)
+{
+ memset(ent, 0, sizeof (*ent));
+ return KADM5_POLICY_OP_NOSUPP;
+}
+
+
+kadm5_ret_t
+kadm5_get_policies(void *server_handle, char *exp, char ***pols, int *count)
+{
+ *count = 0;
+ *pols = NULL;
+
+ return KADM5_POLICY_OP_NOSUPP;
+}
+
+kadm5_ret_t
+kadm5_free_policy_ent(kadm5_policy_ent_t ent)
+{
+ if (ent->policy)
+ free(ent->policy);
+ /*
+ * Not clear if we should free ent or not. It might be an automatic
+ * struct, so we don't free it for now, just in case.
+ */
+ return 0;
+}
+
+kadm5_ret_t
+kadm5_prune_principal(void *server_handle,
+ krb5_principal princ,
+ int kvno)
+{
+ return __CALL(prune_principal, (server_handle, princ, kvno));
+}
diff --git a/third_party/heimdal/lib/kadm5/context_s.c b/third_party/heimdal/lib/kadm5/context_s.c
new file mode 100644
index 0000000..0c154ec
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/context_s.c
@@ -0,0 +1,312 @@
+/*
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+static kadm5_ret_t
+kadm5_s_lock(void *server_handle)
+{
+ kadm5_server_context *context = server_handle;
+ kadm5_ret_t ret;
+
+ if (context->keep_open) {
+ /*
+ * We open/close around every operation, but we retain the DB
+ * open if the DB was locked with a prior call to kadm5_lock(),
+ * so if it's open here that must be because the DB is locked.
+ */
+ heim_assert(context->db->lock_count > 0,
+ "Internal error in tracking HDB locks");
+ return KADM5_ALREADY_LOCKED;
+ }
+
+ ret = context->db->hdb_open(context->context, context->db, O_RDWR, 0);
+ if (ret)
+ return ret;
+
+ ret = context->db->hdb_lock(context->context, context->db, HDB_WLOCK);
+ if (ret) {
+ (void) context->db->hdb_close(context->context, context->db);
+ return ret;
+ }
+
+ /*
+ * Attempt to recover the log. This will generally fail on slaves,
+ * and we can't tell if we're on a slave here.
+ *
+ * Perhaps we could set a flag in the kadm5_server_context to
+ * indicate whether a read has been done without recovering the log,
+ * in which case we could fail any subsequent writes.
+ */
+ if (kadm5_log_init(context) == 0)
+ (void) kadm5_log_end(context);
+
+ context->keep_open = 1;
+ return 0;
+}
+
+static kadm5_ret_t
+kadm5_s_unlock(void *server_handle)
+{
+ kadm5_server_context *context = server_handle;
+ kadm5_ret_t ret;
+
+ if (!context->keep_open)
+ return KADM5_NOT_LOCKED;
+
+ context->keep_open = 0;
+ ret = context->db->hdb_unlock(context->context, context->db);
+ (void) context->db->hdb_close(context->context, context->db);
+ return ret;
+}
+
+static void
+set_funcs(kadm5_server_context *c)
+{
+#define SET(C, F) (C)->funcs.F = kadm5_s_ ## F
+ SET(c, chpass_principal);
+ SET(c, chpass_principal_with_key);
+ SET(c, create_principal);
+ SET(c, delete_principal);
+ SET(c, destroy);
+ SET(c, flush);
+ SET(c, get_principal);
+ SET(c, get_principals);
+ SET(c, get_privs);
+ SET(c, modify_principal);
+ SET(c, prune_principal);
+ SET(c, randkey_principal);
+ SET(c, rename_principal);
+ SET(c, lock);
+ SET(c, unlock);
+ SET(c, setkey_principal_3);
+}
+
+#ifndef NO_UNIX_SOCKETS
+
+static void
+set_socket_name(krb5_context context, struct sockaddr_un *un)
+{
+ const char *fn = kadm5_log_signal_socket(context);
+
+ memset(un, 0, sizeof(*un));
+ un->sun_family = AF_UNIX;
+ strlcpy (un->sun_path, fn, sizeof(un->sun_path));
+
+}
+#else
+
+static void
+set_socket_info(krb5_context context, struct addrinfo **info)
+{
+ kadm5_log_signal_socket_info(context, 0, info);
+}
+
+#endif
+
+static kadm5_ret_t
+find_db_spec(kadm5_server_context *ctx)
+{
+ krb5_context context = ctx->context;
+ struct hdb_dbinfo *info, *d;
+ krb5_error_code ret;
+ int aret;
+
+ if (ctx->config.realm) {
+ /* fetch the databases */
+ ret = hdb_get_dbinfo(context, &info);
+ if (ret)
+ return ret;
+
+ d = NULL;
+ while ((d = hdb_dbinfo_get_next(info, d)) != NULL) {
+ const char *p = hdb_dbinfo_get_realm(context, d);
+
+ /* match default (realm-less) */
+ if(p != NULL && strcmp(ctx->config.realm, p) != 0)
+ continue;
+
+ p = hdb_dbinfo_get_dbname(context, d);
+ if (p) {
+ ctx->config.dbname = strdup(p);
+ if (ctx->config.dbname == NULL) {
+ hdb_free_dbinfo(context, &info);
+ return krb5_enomem(context);
+ }
+ }
+
+ p = hdb_dbinfo_get_acl_file(context, d);
+ if (p) {
+ ctx->config.acl_file = strdup(p);
+ if (ctx->config.acl_file == NULL) {
+ hdb_free_dbinfo(context, &info);
+ return krb5_enomem(context);
+ }
+ }
+
+ p = hdb_dbinfo_get_mkey_file(context, d);
+ if (p) {
+ ctx->config.stash_file = strdup(p);
+ if (ctx->config.stash_file == NULL) {
+ hdb_free_dbinfo(context, &info);
+ return krb5_enomem(context);
+ }
+ }
+
+ p = hdb_dbinfo_get_log_file(context, d);
+ if (p) {
+ ctx->log_context.log_file = strdup(p);
+ if (ctx->log_context.log_file == NULL) {
+ hdb_free_dbinfo(context, &info);
+ return krb5_enomem(context);
+ }
+ }
+ break;
+ }
+ hdb_free_dbinfo(context, &info);
+ }
+
+ /* If any of the values was unset, pick up the default value */
+
+ if (ctx->config.dbname == NULL) {
+ ctx->config.dbname = strdup(hdb_default_db(context));
+ if (ctx->config.dbname == NULL)
+ return krb5_enomem(context);
+ }
+ if (ctx->config.acl_file == NULL) {
+ aret = asprintf(&ctx->config.acl_file, "%s/kadmind.acl",
+ hdb_db_dir(context));
+ if (aret == -1)
+ return krb5_enomem(context);
+ }
+ if (ctx->config.stash_file == NULL) {
+ aret = asprintf(&ctx->config.stash_file, "%s/m-key",
+ hdb_db_dir(context));
+ if (aret == -1)
+ return krb5_enomem(context);
+ }
+ if (ctx->log_context.log_file == NULL) {
+ aret = asprintf(&ctx->log_context.log_file, "%s/log",
+ hdb_db_dir(context));
+ if (aret == -1)
+ return krb5_enomem(context);
+ }
+
+#ifndef NO_UNIX_SOCKETS
+ set_socket_name(context, &ctx->log_context.socket_name);
+#else
+ set_socket_info(context, &ctx->log_context.socket_info);
+#endif
+
+ return 0;
+}
+
+kadm5_ret_t
+_kadm5_s_init_context(kadm5_server_context **ctx,
+ kadm5_config_params *params,
+ krb5_context context)
+{
+ kadm5_ret_t ret = 0;
+
+ *ctx = calloc(1, sizeof(**ctx));
+ if (*ctx == NULL)
+ return krb5_enomem(context);
+ (*ctx)->log_context.socket_fd = rk_INVALID_SOCKET;
+
+ set_funcs(*ctx);
+ (*ctx)->context = context;
+ krb5_add_et_list (context, initialize_kadm5_error_table_r);
+
+#define is_set(M) (params && params->mask & KADM5_CONFIG_ ## M)
+ if (is_set(REALM)) {
+ (*ctx)->config.realm = strdup(params->realm);
+ if ((*ctx)->config.realm == NULL)
+ return krb5_enomem(context);
+ } else {
+ ret = krb5_get_default_realm(context, &(*ctx)->config.realm);
+ if (ret)
+ return ret;
+ }
+ if (is_set(DBNAME)) {
+ (*ctx)->config.dbname = strdup(params->dbname);
+ if ((*ctx)->config.dbname == NULL)
+ return krb5_enomem(context);
+ }
+ if (is_set(ACL_FILE)) {
+ (*ctx)->config.acl_file = strdup(params->acl_file);
+ if ((*ctx)->config.acl_file == NULL)
+ return krb5_enomem(context);
+ }
+ if (is_set(STASH_FILE)) {
+ (*ctx)->config.stash_file = strdup(params->stash_file);
+ if ((*ctx)->config.stash_file == NULL)
+ return krb5_enomem(context);
+ }
+
+ find_db_spec(*ctx);
+
+ ret = _kadm5_s_init_hooks(*ctx);
+ if (ret != 0) {
+ kadm5_s_destroy(*ctx);
+ *ctx = NULL;
+ return ret;
+ }
+
+ /* PROFILE can't be specified for now */
+ /* KADMIND_PORT is supposed to be used on the server also,
+ but this doesn't make sense */
+ /* ADMIN_SERVER is client only */
+ /* ADNAME is not used at all (as far as I can tell) */
+ /* ADB_LOCKFILE ditto */
+ /* DICT_FILE */
+ /* ADMIN_KEYTAB */
+ /* MKEY_FROM_KEYBOARD is not supported */
+ /* MKEY_NAME neither */
+ /* ENCTYPE */
+ /* MAX_LIFE */
+ /* MAX_RLIFE */
+ /* EXPIRATION */
+ /* FLAGS */
+ /* ENCTYPES */
+
+ return 0;
+}
+
+HDB *
+_kadm5_s_get_db(void *server_handle)
+{
+ kadm5_server_context *context = server_handle;
+ return context->db;
+}
diff --git a/third_party/heimdal/lib/kadm5/create_c.c b/third_party/heimdal/lib/kadm5/create_c.c
new file mode 100644
index 0000000..c239beb
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/create_c.c
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 1997-2000, 2005-2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_c_create_principal(void *server_handle,
+ kadm5_principal_ent_t princ,
+ uint32_t mask,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ const char *password)
+{
+ kadm5_client_context *context = server_handle;
+ kadm5_ret_t ret;
+ krb5_storage *sp;
+ unsigned char buf[1024];
+ int32_t tmp;
+ krb5_data reply;
+
+ /*
+ * We should get around to implementing this... At the moment, the
+ * the server side API is implemented but the wire protocol has not
+ * been updated.
+ *
+ * Well, we have the etypes extension, which the kadmin ank command now
+ * adds, but that doesn't include salt types. We could, perhaps, make it
+ * so if the password is "" or NULL, we send the etypes but not the salt
+ * type, and then have the server side create random keys of just the
+ * etypes.
+ */
+ if (n_ks_tuple > 0)
+ return KADM5_KS_TUPLE_NOSUPP;
+
+ ret = _kadm5_connect(server_handle, 1 /* want_write */);
+ if (ret)
+ return ret;
+
+ krb5_data_zero(&reply);
+
+ sp = krb5_storage_from_mem(buf, sizeof(buf));
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ ret = krb5_store_int32(sp, kadm_create);
+ if (ret)
+ goto out;
+ ret = kadm5_store_principal_ent(sp, princ);
+ if (ret)
+ goto out;
+ ret = krb5_store_int32(sp, mask);
+ if (ret)
+ goto out;
+ ret = krb5_store_string(sp, password);
+ if (ret)
+ goto out;
+ ret = _kadm5_client_send(context, sp);
+ if (ret)
+ goto out_keep_error;
+ ret = _kadm5_client_recv(context, &reply);
+ if (ret)
+ goto out_keep_error;
+ krb5_storage_free(sp);
+ sp = krb5_storage_from_data(&reply);
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret == 0)
+ ret = tmp;
+
+ out:
+ krb5_clear_error_message(context->context);
+
+ out_keep_error:
+ krb5_storage_free(sp);
+ krb5_data_free(&reply);
+ return ret;
+}
+
diff --git a/third_party/heimdal/lib/kadm5/create_s.c b/third_party/heimdal/lib/kadm5/create_s.c
new file mode 100644
index 0000000..1c2ab15
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/create_s.c
@@ -0,0 +1,357 @@
+/*
+ * Copyright (c) 1997-2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+static kadm5_ret_t
+get_default(kadm5_server_context *context, krb5_principal princ,
+ kadm5_principal_ent_t def)
+{
+ kadm5_ret_t ret;
+ krb5_principal def_principal;
+ krb5_const_realm realm = krb5_principal_get_realm(context->context, princ);
+
+ ret = krb5_make_principal(context->context, &def_principal,
+ realm, "default", NULL);
+ if (ret)
+ return ret;
+ ret = kadm5_s_get_principal(context, def_principal, def,
+ KADM5_PRINCIPAL_NORMAL_MASK);
+ krb5_free_principal (context->context, def_principal);
+ return ret;
+}
+
+static kadm5_ret_t
+create_principal(kadm5_server_context *context,
+ kadm5_principal_ent_t princ,
+ uint32_t mask,
+ hdb_entry *ent,
+ uint32_t required_mask,
+ uint32_t forbidden_mask)
+{
+ kadm5_ret_t ret;
+ kadm5_principal_ent_rec defrec, *defent;
+ uint32_t def_mask;
+
+ memset(ent, 0, sizeof(*ent));
+ if((mask & required_mask) != required_mask)
+ return KADM5_BAD_MASK;
+ if((mask & forbidden_mask))
+ return KADM5_BAD_MASK;
+ if((mask & KADM5_POLICY) && strcmp(princ->policy, "default"))
+ /* XXX no real policies for now */
+ return KADM5_UNK_POLICY;
+ ret = krb5_copy_principal(context->context, princ->principal,
+ &ent->principal);
+ if(ret)
+ return ret;
+
+ defent = &defrec;
+ ret = get_default(context, princ->principal, defent);
+ if(ret) {
+ defent = NULL;
+ def_mask = 0;
+ } else {
+ def_mask = KADM5_ATTRIBUTES | KADM5_MAX_LIFE | KADM5_MAX_RLIFE;
+ }
+
+ ret = _kadm5_setup_entry(context,
+ ent, mask | def_mask,
+ princ, mask,
+ defent, def_mask);
+ if(defent)
+ kadm5_free_principal_ent(context, defent);
+ if (ret)
+ return ret;
+
+ ent->created_by.time = time(NULL);
+
+ return krb5_copy_principal(context->context, context->caller,
+ &ent->created_by.principal);
+}
+
+struct create_principal_hook_ctx {
+ kadm5_server_context *context;
+ enum kadm5_hook_stage stage;
+ krb5_error_code code;
+ kadm5_principal_ent_t princ;
+ uint32_t mask;
+ const char *password;
+};
+
+static krb5_error_code KRB5_LIB_CALL
+create_principal_hook_cb(krb5_context context,
+ const void *hook,
+ void *hookctx,
+ void *userctx)
+{
+ krb5_error_code ret;
+ const struct kadm5_hook_ftable *ftable = hook;
+ struct create_principal_hook_ctx *ctx = userctx;
+
+ ret = ftable->create(context, hookctx,
+ ctx->stage, ctx->code, ctx->princ,
+ ctx->mask, ctx->password);
+ if (ret != 0 && ret != KRB5_PLUGIN_NO_HANDLE)
+ _kadm5_s_set_hook_error_message(ctx->context, ret, "create",
+ hook, ctx->stage);
+
+ /* only pre-commit plugins can abort */
+ if (ret == 0 || ctx->stage == KADM5_HOOK_STAGE_POSTCOMMIT)
+ ret = KRB5_PLUGIN_NO_HANDLE;
+
+ return ret;
+}
+
+static kadm5_ret_t
+create_principal_hook(kadm5_server_context *context,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ kadm5_principal_ent_t princ,
+ uint32_t mask,
+ const char *password)
+{
+ krb5_error_code ret;
+ struct create_principal_hook_ctx ctx;
+
+ ctx.context = context;
+ ctx.stage = stage;
+ ctx.code = code;
+ ctx.princ = princ;
+ ctx.mask = mask;
+ ctx.password = password;
+
+ ret = _krb5_plugin_run_f(context->context, &kadm5_hook_plugin_data,
+ 0, &ctx, create_principal_hook_cb);
+ if (ret == KRB5_PLUGIN_NO_HANDLE)
+ ret = 0;
+
+ return ret;
+}
+
+kadm5_ret_t
+kadm5_s_create_principal_with_key(void *server_handle,
+ kadm5_principal_ent_t princ,
+ uint32_t mask)
+{
+ kadm5_ret_t ret;
+ hdb_entry ent;
+ kadm5_server_context *context = server_handle;
+
+ if ((mask & KADM5_KVNO) == 0) {
+ /* create_principal() through _kadm5_setup_entry(), will need this */
+ princ->kvno = 1;
+ mask |= KADM5_KVNO;
+ }
+
+ ret = create_principal_hook(context, KADM5_HOOK_STAGE_PRECOMMIT,
+ 0, princ, mask, NULL);
+ if (ret)
+ return ret;
+
+ ret = create_principal(context, princ, mask, &ent,
+ KADM5_PRINCIPAL | KADM5_KEY_DATA,
+ KADM5_LAST_PWD_CHANGE | KADM5_MOD_TIME
+ | KADM5_MOD_NAME | KADM5_MKVNO
+ | KADM5_AUX_ATTRIBUTES
+ | KADM5_POLICY_CLR | KADM5_LAST_SUCCESS
+ | KADM5_LAST_FAILED | KADM5_FAIL_AUTH_COUNT);
+ if (ret)
+ return ret;
+
+ if (!context->keep_open) {
+ ret = context->db->hdb_open(context->context, context->db, O_RDWR, 0);
+ if (ret) {
+ hdb_free_entry(context->context, context->db, &ent);
+ return ret;
+ }
+ }
+
+ ret = kadm5_log_init(context);
+ if (ret)
+ goto out;
+
+ ret = hdb_seal_keys(context->context, context->db, &ent);
+ if (ret)
+ goto out2;
+
+ /*
+ * This logs the change for iprop and writes to the HDB.
+ *
+ * Creation of would-be virtual principals w/o the materialize flag will be
+ * rejected in kadm5_log_create().
+ */
+ ret = kadm5_log_create(context, &ent);
+
+ (void) create_principal_hook(context, KADM5_HOOK_STAGE_POSTCOMMIT,
+ ret, princ, mask, NULL);
+
+ out2:
+ (void) kadm5_log_end(context);
+ out:
+ if (!context->keep_open) {
+ kadm5_ret_t ret2;
+ ret2 = context->db->hdb_close(context->context, context->db);
+ if (ret == 0 && ret2 != 0)
+ ret = ret2;
+ }
+ hdb_free_entry(context->context, context->db, &ent);
+ return _kadm5_error_code(ret);
+}
+
+
+kadm5_ret_t
+kadm5_s_create_principal(void *server_handle,
+ kadm5_principal_ent_t princ,
+ uint32_t mask,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ const char *password)
+{
+ kadm5_ret_t ret;
+ hdb_entry ent;
+ kadm5_server_context *context = server_handle;
+ int use_pw = 1;
+
+ if ((mask & KADM5_ATTRIBUTES) &&
+ (princ->attributes & (KRB5_KDB_VIRTUAL_KEYS | KRB5_KDB_VIRTUAL)) &&
+ !(princ->attributes & KRB5_KDB_MATERIALIZE)) {
+ ret = KADM5_DUP; /* XXX */
+ goto out;
+ }
+ if ((mask & KADM5_ATTRIBUTES) &&
+ (princ->attributes & KRB5_KDB_VIRTUAL_KEYS) &&
+ (princ->attributes & KRB5_KDB_VIRTUAL)) {
+ ret = KADM5_DUP; /* XXX */
+ goto out;
+ }
+
+ if ((mask & KADM5_ATTRIBUTES) &&
+ (princ->attributes & KRB5_KDB_VIRTUAL) &&
+ (princ->attributes & KRB5_KDB_MATERIALIZE))
+ princ->attributes &= ~(KRB5_KDB_MATERIALIZE | KRB5_KDB_VIRTUAL);
+
+ if (password[0] == '\0' && (mask & KADM5_KEY_DATA) && princ->n_key_data &&
+ !kadm5_all_keys_are_bogus(princ->n_key_data, princ->key_data))
+ use_pw = 0;
+
+ if (use_pw && _kadm5_enforce_pwqual_on_admin_set_p(context)) {
+ krb5_data pwd_data;
+ const char *pwd_reason;
+
+ pwd_data.data = rk_UNCONST(password);
+ pwd_data.length = strlen(password);
+
+ pwd_reason = kadm5_check_password_quality(context->context,
+ princ->principal, &pwd_data);
+ if (pwd_reason != NULL) {
+ krb5_set_error_message(context->context, KADM5_PASS_Q_DICT, "%s", pwd_reason);
+ return KADM5_PASS_Q_DICT;
+ }
+ }
+
+ if ((mask & KADM5_KVNO) == 0) {
+ /* create_principal() through _kadm5_setup_entry(), will need this */
+ princ->kvno = 1;
+ mask |= KADM5_KVNO;
+ }
+
+ ret = create_principal_hook(context, KADM5_HOOK_STAGE_PRECOMMIT,
+ 0, princ, mask, password);
+ if (ret)
+ return ret;
+
+ if (use_pw)
+ ret = create_principal(context, princ, mask, &ent,
+ KADM5_PRINCIPAL,
+ KADM5_LAST_PWD_CHANGE | KADM5_MOD_TIME
+ | KADM5_MOD_NAME | KADM5_MKVNO
+ | KADM5_AUX_ATTRIBUTES | KADM5_KEY_DATA
+ | KADM5_POLICY_CLR | KADM5_LAST_SUCCESS
+ | KADM5_LAST_FAILED | KADM5_FAIL_AUTH_COUNT);
+ else
+ ret = create_principal(context, princ, mask, &ent,
+ KADM5_PRINCIPAL | KADM5_KEY_DATA,
+ KADM5_LAST_PWD_CHANGE | KADM5_MOD_TIME
+ | KADM5_MOD_NAME | KADM5_MKVNO
+ | KADM5_AUX_ATTRIBUTES
+ | KADM5_POLICY_CLR | KADM5_LAST_SUCCESS
+ | KADM5_LAST_FAILED | KADM5_FAIL_AUTH_COUNT);
+ if (ret)
+ return ret;
+
+ if (!context->keep_open) {
+ ret = context->db->hdb_open(context->context, context->db, O_RDWR, 0);
+ if (ret) {
+ hdb_free_entry(context->context, context->db, &ent);
+ return ret;
+ }
+ }
+
+ ret = kadm5_log_init(context);
+ if (ret)
+ goto out;
+
+ free_Keys(&ent.keys);
+
+ if (use_pw) {
+ ret = _kadm5_set_keys(context, &ent, n_ks_tuple, ks_tuple, password);
+ if (ret)
+ goto out2;
+ }
+
+ ret = hdb_seal_keys(context->context, context->db, &ent);
+ if (ret)
+ goto out2;
+
+ /* This logs the change for iprop and writes to the HDB */
+ ret = kadm5_log_create(context, &ent);
+
+ (void) create_principal_hook(context, KADM5_HOOK_STAGE_POSTCOMMIT,
+ ret, princ, mask, password);
+
+ out2:
+ (void) kadm5_log_end(context);
+ out:
+ if (!context->keep_open) {
+ kadm5_ret_t ret2;
+ ret2 = context->db->hdb_close(context->context, context->db);
+ if (ret == 0 && ret2 != 0)
+ ret = ret2;
+ }
+ hdb_free_entry(context->context, context->db, &ent);
+ return _kadm5_error_code(ret);
+}
+
diff --git a/third_party/heimdal/lib/kadm5/default_keys.c b/third_party/heimdal/lib/kadm5/default_keys.c
new file mode 100644
index 0000000..c3494e5
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/default_keys.c
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+#include <err.h>
+
+RCSID("$Id$");
+
+static void
+print_keys(krb5_context context, Key *keys, size_t nkeys)
+{
+ krb5_error_code ret;
+ char *str;
+ int i;
+
+ printf("keys:\n");
+
+ for (i = 0; i < nkeys; i++) {
+
+ ret = krb5_enctype_to_string(context, keys[i].key.keytype, &str);
+ if (ret)
+ krb5_err(context, ret, 1, "krb5_enctype_to_string: %d\n",
+ (int)keys[i].key.keytype);
+
+ printf("\tenctype %s", str);
+ free(str);
+
+ if (keys[i].salt) {
+ printf(" salt: ");
+
+ switch (keys[i].salt->type) {
+ case KRB5_PW_SALT:
+ printf("pw-salt:");
+ break;
+ case KRB5_AFS3_SALT:
+ printf("afs3-salt:");
+ break;
+ default:
+ printf("unknown salt: %d", keys[i].salt->type);
+ break;
+ }
+ if (keys[i].salt->salt.length)
+ printf("%.*s", (int)keys[i].salt->salt.length,
+ (char *)keys[i].salt->salt.data);
+ }
+ printf("\n");
+ }
+ printf("end keys:\n");
+}
+
+static void
+parse_file(krb5_context context, krb5_principal principal, int no_salt)
+{
+ krb5_error_code ret;
+ size_t nkeys;
+ Key *keys;
+
+ ret = hdb_generate_key_set(context, principal, NULL, 0, &keys, &nkeys,
+ no_salt);
+ if (ret)
+ krb5_err(context, 1, ret, "hdb_generate_key_set");
+
+ print_keys(context, keys, nkeys);
+
+ hdb_free_keys(context, nkeys, keys);
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_error_code ret;
+ krb5_context context;
+ krb5_principal principal;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_init_context");
+
+ ret = krb5_parse_name(context, "lha@SU.SE", &principal);
+ if (ret)
+ krb5_err(context, ret, 1, "krb5_parse_name");
+
+ parse_file(context, principal, 0);
+ parse_file(context, principal, 1);
+
+ krb5_free_principal(context, principal);
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/delete_c.c b/third_party/heimdal/lib/kadm5/delete_c.c
new file mode 100644
index 0000000..cf06b6f
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/delete_c.c
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_c_delete_principal(void *server_handle, krb5_principal princ)
+{
+ kadm5_client_context *context = server_handle;
+ kadm5_ret_t ret;
+ krb5_storage *sp;
+ unsigned char buf[1024];
+ int32_t tmp;
+ krb5_data reply;
+
+ ret = _kadm5_connect(server_handle, 1 /* want_write */);
+ if (ret)
+ return ret;
+
+ krb5_data_zero(&reply);
+
+ sp = krb5_storage_from_mem(buf, sizeof(buf));
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_store_int32(sp, kadm_delete);
+ if (ret)
+ goto out;
+ ret = krb5_store_principal(sp, princ);
+ if (ret)
+ goto out;
+ ret = _kadm5_client_send(context, sp);
+ if (ret)
+ goto out_keep_error;
+ ret = _kadm5_client_recv(context, &reply);
+ if (ret)
+ goto out_keep_error;
+ krb5_storage_free(sp);
+ sp = krb5_storage_from_data(&reply);
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret == 0)
+ ret = tmp;
+
+ out:
+ krb5_clear_error_message(context->context);
+
+ out_keep_error:
+ krb5_storage_free(sp);
+ krb5_data_free(&reply);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kadm5/delete_s.c b/third_party/heimdal/lib/kadm5/delete_s.c
new file mode 100644
index 0000000..aa9fdb4
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/delete_s.c
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) 1997 - 2001, 2003, 2005 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+struct delete_principal_hook_ctx {
+ kadm5_server_context *context;
+ enum kadm5_hook_stage stage;
+ krb5_error_code code;
+ krb5_const_principal princ;
+};
+
+static krb5_error_code KRB5_LIB_CALL
+delete_principal_hook_cb(krb5_context context,
+ const void *hook,
+ void *hookctx,
+ void *userctx)
+{
+ krb5_error_code ret;
+ const struct kadm5_hook_ftable *ftable = hook;
+ struct delete_principal_hook_ctx *ctx = userctx;
+
+ ret = ftable->delete(context, hookctx,
+ ctx->stage, ctx->code, ctx->princ);
+ if (ret != 0 && ret != KRB5_PLUGIN_NO_HANDLE)
+ _kadm5_s_set_hook_error_message(ctx->context, ret, "delete",
+ hook, ctx->stage);
+
+ /* only pre-commit plugins can abort */
+ if (ret == 0 || ctx->stage == KADM5_HOOK_STAGE_POSTCOMMIT)
+ ret = KRB5_PLUGIN_NO_HANDLE;
+
+ return ret;
+}
+
+static kadm5_ret_t
+delete_principal_hook(kadm5_server_context *context,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ)
+{
+ krb5_error_code ret;
+ struct delete_principal_hook_ctx ctx;
+
+ ctx.context = context;
+ ctx.stage = stage;
+ ctx.code = code;
+ ctx.princ = princ;
+
+ ret = _krb5_plugin_run_f(context->context, &kadm5_hook_plugin_data,
+ 0, &ctx, delete_principal_hook_cb);
+ if (ret == KRB5_PLUGIN_NO_HANDLE)
+ ret = 0;
+
+ return ret;
+}
+
+kadm5_ret_t
+kadm5_s_delete_principal(void *server_handle, krb5_principal princ)
+{
+ kadm5_server_context *context = server_handle;
+ kadm5_ret_t ret;
+ hdb_entry ent;
+
+ memset(&ent, 0, sizeof(ent));
+ if (!context->keep_open) {
+ ret = context->db->hdb_open(context->context, context->db, O_RDWR, 0);
+ if(ret) {
+ krb5_warn(context->context, ret, "opening database");
+ return ret;
+ }
+ }
+
+ ret = kadm5_log_init(context);
+ if (ret)
+ goto out;
+
+ ret = context->db->hdb_fetch_kvno(context->context, context->db, princ,
+ HDB_F_DECRYPT|HDB_F_GET_ANY|HDB_F_ADMIN_DATA,
+ 0, &ent);
+ if (ret == HDB_ERR_NOENTRY)
+ goto out2;
+ if (ent.flags.immutable) {
+ ret = KADM5_PROTECT_PRINCIPAL;
+ goto out3;
+ }
+
+ ret = delete_principal_hook(context, KADM5_HOOK_STAGE_PRECOMMIT, 0, princ);
+ if (ret)
+ goto out3;
+
+ ret = hdb_seal_keys(context->context, context->db, &ent);
+ if (ret)
+ goto out3;
+
+ /* This logs the change for iprop and writes to the HDB */
+ ret = kadm5_log_delete(context, princ);
+
+ (void) delete_principal_hook(context, KADM5_HOOK_STAGE_POSTCOMMIT, ret, princ);
+
+ out3:
+ hdb_free_entry(context->context, context->db, &ent);
+ out2:
+ (void) kadm5_log_end(context);
+ out:
+ if (!context->keep_open) {
+ kadm5_ret_t ret2;
+ ret2 = context->db->hdb_close(context->context, context->db);
+ if (ret == 0 && ret2 != 0)
+ ret = ret2;
+ }
+ return _kadm5_error_code(ret);
+}
diff --git a/third_party/heimdal/lib/kadm5/destroy_c.c b/third_party/heimdal/lib/kadm5/destroy_c.c
new file mode 100644
index 0000000..5ed85f7
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/destroy_c.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_c_destroy(void *server_handle)
+{
+ kadm5_client_context *context = server_handle;
+
+ free(context->realm);
+ free(context->readonly_admin_server);
+ free(context->admin_server);
+ if (context->sock != rk_INVALID_SOCKET)
+ rk_closesocket(context->sock);
+ if (context->client_name)
+ free(context->client_name);
+ if (context->service_name)
+ free(context->service_name);
+ if (context->ac != NULL)
+ krb5_auth_con_free(context->context, context->ac);
+ if(context->my_context)
+ krb5_free_context(context->context);
+ free(context);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/destroy_s.c b/third_party/heimdal/lib/kadm5/destroy_s.c
new file mode 100644
index 0000000..fc86e59
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/destroy_s.c
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+/*
+ * dealloc a `kadm5_config_params'
+ */
+
+static void
+destroy_config (kadm5_config_params *c)
+{
+ free (c->realm);
+ free (c->dbname);
+ free (c->acl_file);
+ free (c->stash_file);
+}
+
+/*
+ * dealloc a kadm5_log_context
+ */
+
+static void
+destroy_kadm5_log_context (kadm5_log_context *c)
+{
+ free(c->log_file);
+ if (c->socket_fd != rk_INVALID_SOCKET)
+ rk_closesocket(c->socket_fd);
+#ifdef NO_UNIX_SOCKETS
+ if (c->socket_info) {
+ freeaddrinfo(c->socket_info);
+ c->socket_info = NULL;
+ }
+#endif
+}
+
+/*
+ * destroy a kadm5 handle
+ */
+
+kadm5_ret_t
+kadm5_s_destroy(void *server_handle)
+{
+ kadm5_ret_t ret = 0;
+ kadm5_server_context *context = server_handle;
+ krb5_context kcontext = context->context;
+
+ _kadm5_s_free_hooks(context);
+ if (context->db != NULL)
+ ret = context->db->hdb_destroy(kcontext, context->db);
+ destroy_kadm5_log_context(&context->log_context);
+ destroy_config(&context->config);
+ krb5_free_principal(kcontext, context->caller);
+ if (context->my_context)
+ krb5_free_context(kcontext);
+ free(context);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kadm5/ent_setup.c b/third_party/heimdal/lib/kadm5/ent_setup.c
new file mode 100644
index 0000000..24a7983
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/ent_setup.c
@@ -0,0 +1,272 @@
+/*
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+#define set_value(X, V) do { if((X) == NULL) (X) = malloc(sizeof(*(X))); *(X) = V; } while(0)
+#define set_null(X) do { if((X) != NULL) free((X)); (X) = NULL; } while (0)
+
+static void
+attr_to_flags(unsigned attr, HDBFlags *flags)
+{
+ flags->postdate = !(attr & KRB5_KDB_DISALLOW_POSTDATED);
+ flags->forwardable = !(attr & KRB5_KDB_DISALLOW_FORWARDABLE);
+ flags->initial = !!(attr & KRB5_KDB_DISALLOW_TGT_BASED);
+ flags->renewable = !(attr & KRB5_KDB_DISALLOW_RENEWABLE);
+ flags->proxiable = !(attr & KRB5_KDB_DISALLOW_PROXIABLE);
+ /* DUP_SKEY */
+ flags->invalid = !!(attr & KRB5_KDB_DISALLOW_ALL_TIX);
+ flags->require_preauth = !!(attr & KRB5_KDB_REQUIRES_PRE_AUTH);
+ flags->require_pwchange = !!(attr & KRB5_KDB_REQUIRES_PWCHANGE);
+ /* HW_AUTH */
+ flags->server = !(attr & KRB5_KDB_DISALLOW_SVR);
+ flags->change_pw = !!(attr & KRB5_KDB_PWCHANGE_SERVICE);
+ flags->client = !(attr & KRB5_KDB_DISALLOW_CLIENT);
+ flags->ok_as_delegate = !!(attr & KRB5_KDB_OK_AS_DELEGATE);
+ flags->trusted_for_delegation = !!(attr & KRB5_KDB_TRUSTED_FOR_DELEGATION);
+ flags->allow_kerberos4 = !!(attr & KRB5_KDB_ALLOW_KERBEROS4);
+ flags->allow_digest = !!(attr & KRB5_KDB_ALLOW_DIGEST);
+ flags->materialize = !!(attr & KRB5_KDB_MATERIALIZE);
+ flags->virtual_keys = !!(attr & KRB5_KDB_VIRTUAL_KEYS);
+ flags->virtual = !!(attr & KRB5_KDB_VIRTUAL);
+ flags->no_auth_data_reqd = !!(attr & KRB5_KDB_NO_AUTH_DATA_REQUIRED);
+}
+
+/*
+ * Modify the `ent' according to `tl_data'.
+ */
+
+static kadm5_ret_t
+perform_tl_data(krb5_context context,
+ HDB *db,
+ hdb_entry *ent,
+ const krb5_tl_data *tl_data)
+{
+ kadm5_ret_t ret = 0;
+
+ if (tl_data->tl_data_type == KRB5_TL_PASSWORD) {
+ heim_utf8_string pw = tl_data->tl_data_contents;
+
+ if (pw[tl_data->tl_data_length] != '\0')
+ return KADM5_BAD_TL_TYPE;
+
+ ret = hdb_entry_set_password(context, db, ent, pw);
+
+ } else if (tl_data->tl_data_type == KRB5_TL_LAST_PWD_CHANGE) {
+ unsigned long t;
+ unsigned char *s;
+
+ if (tl_data->tl_data_length != 4)
+ return KADM5_BAD_TL_TYPE;
+
+ s = tl_data->tl_data_contents;
+
+ (void) _krb5_get_int(s, &t, tl_data->tl_data_length);
+ ret = hdb_entry_set_pw_change_time(context, ent, t);
+
+ } else if (tl_data->tl_data_type == KRB5_TL_KEY_ROTATION) {
+ HDB_Ext_KeyRotation *prev_kr = 0;
+ HDB_extension *prev_ext;
+ HDB_extension ext;
+
+ ext.mandatory = 0;
+ ext.data.element = choice_HDB_extension_data_key_rotation;
+ prev_ext = hdb_find_extension(ent, ext.data.element);
+ if (prev_ext)
+ prev_kr = &prev_ext->data.u.key_rotation;
+ ret = decode_HDB_Ext_KeyRotation(tl_data->tl_data_contents,
+ tl_data->tl_data_length,
+ &ext.data.u.key_rotation, NULL);
+ if (ret == 0)
+ ret = hdb_validate_key_rotations(context, prev_kr,
+ &ext.data.u.key_rotation);
+ if (ret == 0)
+ ret = hdb_replace_extension(context, ent, &ext);
+ free_HDB_extension(&ext);
+ } else if (tl_data->tl_data_type == KRB5_TL_EXTENSION) {
+ HDB_extension ext;
+
+ ret = decode_HDB_extension(tl_data->tl_data_contents,
+ tl_data->tl_data_length,
+ &ext,
+ NULL);
+ if (ret)
+ return KADM5_BAD_TL_TYPE;
+
+ if (ext.data.element == choice_HDB_extension_data_key_rotation) {
+ HDB_extension *prev_ext = hdb_find_extension(ent,
+ ext.data.element);
+ HDB_Ext_KeyRotation *prev_kr = 0;
+
+ if (prev_ext)
+ prev_kr = &prev_ext->data.u.key_rotation;
+ ret = hdb_validate_key_rotations(context, prev_kr,
+ &ext.data.u.key_rotation);
+ }
+ if (ret)
+ ret = KADM5_BAD_TL_TYPE; /* XXX Need new error code */
+ if (ret == 0)
+ ret = hdb_replace_extension(context, ent, &ext);
+ free_HDB_extension(&ext);
+ } else if (tl_data->tl_data_type == KRB5_TL_ETYPES) {
+ if (!ent->etypes &&
+ (ent->etypes = calloc(1,
+ sizeof(ent->etypes[0]))) == NULL)
+ ret = krb5_enomem(context);
+ if (ent->etypes)
+ free_HDB_EncTypeList(ent->etypes);
+ if (ret == 0)
+ ret = decode_HDB_EncTypeList(tl_data->tl_data_contents,
+ tl_data->tl_data_length,
+ ent->etypes, NULL);
+ if (ret)
+ return KADM5_BAD_TL_TYPE;
+ } else if (tl_data->tl_data_type == KRB5_TL_ALIASES) {
+ return 0;
+ } else {
+ return KADM5_BAD_TL_TYPE;
+ }
+ return ret;
+}
+
+static void
+default_flags(hdb_entry *ent)
+{
+ ent->flags.client = 1;
+ ent->flags.server = 1;
+ ent->flags.forwardable = 1;
+ ent->flags.proxiable = 1;
+ ent->flags.renewable = 1;
+ ent->flags.postdate = 1;
+}
+
+
+/*
+ * Create the hdb entry `ent' based on data from `princ' with
+ * `princ_mask' specifying what fields to be gotten from there and
+ * `mask' specifying what fields we want filled in.
+ */
+
+kadm5_ret_t
+_kadm5_setup_entry(kadm5_server_context *context,
+ hdb_entry *ent,
+ uint32_t mask,
+ kadm5_principal_ent_t princ,
+ uint32_t princ_mask,
+ kadm5_principal_ent_t def,
+ uint32_t def_mask)
+{
+ if(mask & KADM5_PRINC_EXPIRE_TIME
+ && princ_mask & KADM5_PRINC_EXPIRE_TIME) {
+ if (princ->princ_expire_time)
+ set_value(ent->valid_end, princ->princ_expire_time);
+ else
+ set_null(ent->valid_end);
+ }
+ if(mask & KADM5_PW_EXPIRATION
+ && princ_mask & KADM5_PW_EXPIRATION) {
+ if (princ->pw_expiration)
+ set_value(ent->pw_end, princ->pw_expiration);
+ else
+ set_null(ent->pw_end);
+ }
+ if(mask & KADM5_ATTRIBUTES) {
+ if (princ_mask & KADM5_ATTRIBUTES) {
+ attr_to_flags(princ->attributes, &ent->flags);
+ } else if(def_mask & KADM5_ATTRIBUTES) {
+ attr_to_flags(def->attributes, &ent->flags);
+ ent->flags.invalid = 0;
+ } else {
+ default_flags(ent);
+ }
+ }
+
+ if(mask & KADM5_MAX_LIFE) {
+ if(princ_mask & KADM5_MAX_LIFE) {
+ if(princ->max_life)
+ set_value(ent->max_life, princ->max_life);
+ else
+ set_null(ent->max_life);
+ } else if(def_mask & KADM5_MAX_LIFE) {
+ if(def->max_life)
+ set_value(ent->max_life, def->max_life);
+ else
+ set_null(ent->max_life);
+ }
+ }
+ if(mask & KADM5_KVNO
+ && (princ_mask & KADM5_KVNO)) {
+ krb5_error_code ret;
+
+ ret = hdb_change_kvno(context->context, princ->kvno, ent);
+ if (ret && ret != HDB_ERR_KVNO_NOT_FOUND)
+ return ret;
+ ent->kvno = princ->kvno; /* force it */
+ }
+ if(mask & KADM5_MAX_RLIFE) {
+ if(princ_mask & KADM5_MAX_RLIFE) {
+ if(princ->max_renewable_life)
+ set_value(ent->max_renew, princ->max_renewable_life);
+ else
+ set_null(ent->max_renew);
+ } else if(def_mask & KADM5_MAX_RLIFE) {
+ if(def->max_renewable_life)
+ set_value(ent->max_renew, def->max_renewable_life);
+ else
+ set_null(ent->max_renew);
+ }
+ }
+ if(mask & KADM5_KEY_DATA
+ && princ_mask & KADM5_KEY_DATA) {
+ _kadm5_set_keys2(context, ent,
+ princ->n_key_data, princ->key_data);
+ }
+ if(mask & KADM5_TL_DATA) {
+ krb5_tl_data *tl;
+
+ for (tl = princ->tl_data; tl != NULL; tl = tl->tl_data_next) {
+ kadm5_ret_t ret;
+ ret = perform_tl_data(context->context, context->db, ent, tl);
+ if (ret)
+ return ret;
+ }
+ }
+ if(mask & KADM5_FAIL_AUTH_COUNT) {
+ /* XXX */
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/error.c b/third_party/heimdal/lib/kadm5/error.c
new file mode 100644
index 0000000..e6a6dec
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/error.c
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+_kadm5_error_code(kadm5_ret_t code)
+{
+ switch(code){
+ case HDB_ERR_EXISTS:
+ return KADM5_DUP;
+ case HDB_ERR_NOENTRY:
+ return KADM5_UNK_PRINC;
+ }
+ return code;
+}
diff --git a/third_party/heimdal/lib/kadm5/flush.c b/third_party/heimdal/lib/kadm5/flush.c
new file mode 100644
index 0000000..4409fe6
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/flush.c
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_s_flush(void *server_handle)
+{
+ return 0;
+}
+
+kadm5_ret_t
+kadm5_c_flush(void *server_handle)
+{
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/flush_c.c b/third_party/heimdal/lib/kadm5/flush_c.c
new file mode 100644
index 0000000..c1a2a0a
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/flush_c.c
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_c_flush(void *server_handle)
+{
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/flush_s.c b/third_party/heimdal/lib/kadm5/flush_s.c
new file mode 100644
index 0000000..9a52458
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/flush_s.c
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_s_flush(void *server_handle)
+{
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/free.c b/third_party/heimdal/lib/kadm5/free.c
new file mode 100644
index 0000000..e8bb0f9
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/free.c
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+void
+kadm5_free_key_data(void *server_handle,
+ int16_t *n_key_data,
+ krb5_key_data *key_data)
+{
+ int i;
+ for(i = 0; i < *n_key_data; i++){
+ if(key_data[i].key_data_contents[0]){
+ memset(key_data[i].key_data_contents[0],
+ 0,
+ key_data[i].key_data_length[0]);
+ free(key_data[i].key_data_contents[0]);
+ }
+ if(key_data[i].key_data_contents[1])
+ free(key_data[i].key_data_contents[1]);
+ }
+ *n_key_data = 0;
+}
+
+
+void
+kadm5_free_principal_ent(void *server_handle,
+ kadm5_principal_ent_t princ)
+{
+ kadm5_server_context *context = server_handle;
+
+ if (princ->principal)
+ krb5_free_principal(context->context, princ->principal);
+ if (princ->mod_name)
+ krb5_free_principal(context->context, princ->mod_name);
+ kadm5_free_key_data(server_handle, &princ->n_key_data, princ->key_data);
+ while (princ->n_tl_data && princ->tl_data) {
+ krb5_tl_data *tp;
+ tp = princ->tl_data;
+ princ->tl_data = tp->tl_data_next;
+ princ->n_tl_data--;
+ memset(tp->tl_data_contents, 0, tp->tl_data_length);
+ free(tp->tl_data_contents);
+ free(tp);
+ }
+ free(princ->key_data);
+ free(princ->policy);
+}
+
+void
+kadm5_free_name_list(void *server_handle,
+ char **names,
+ int *count)
+{
+ int i;
+ for(i = 0; i < *count; i++)
+ free(names[i]);
+ free(names);
+ *count = 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/get_c.c b/third_party/heimdal/lib/kadm5/get_c.c
new file mode 100644
index 0000000..5b2bcca
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/get_c.c
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 1997 - 2000, 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_c_get_principal(void *server_handle,
+ krb5_principal princ,
+ kadm5_principal_ent_t ent,
+ uint32_t mask)
+{
+ kadm5_client_context *context = server_handle;
+ kadm5_ret_t ret;
+ krb5_storage *sp;
+ unsigned char buf[1024];
+ int32_t tmp;
+ krb5_data reply;
+
+ ret = _kadm5_connect(server_handle, 0 /* want_write */);
+ if (ret)
+ return ret;
+
+ krb5_data_zero(&reply);
+
+ sp = krb5_storage_from_mem(buf, sizeof(buf));
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_store_int32(sp, kadm_get);
+ if (ret)
+ goto out;
+ ret = krb5_store_principal(sp, princ);
+ if (ret)
+ goto out;
+ ret = krb5_store_int32(sp, mask);
+ if (ret)
+ goto out;
+ ret = _kadm5_client_send(context, sp);
+ if (ret)
+ goto out_keep_error;
+ ret = _kadm5_client_recv(context, &reply);
+ if (ret)
+ goto out_keep_error;
+ krb5_storage_free(sp);
+ sp = krb5_storage_from_data(&reply);
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret == 0)
+ ret = tmp;
+
+ out:
+ krb5_clear_error_message(context->context);
+
+ out_keep_error:
+ if (ret == 0)
+ kadm5_ret_principal_ent(sp, ent);
+ krb5_storage_free(sp);
+ krb5_data_free(&reply);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kadm5/get_princs_c.c b/third_party/heimdal/lib/kadm5/get_princs_c.c
new file mode 100644
index 0000000..4998223
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/get_princs_c.c
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_c_get_principals(void *server_handle,
+ const char *expression,
+ char ***princs,
+ int *count)
+{
+ kadm5_client_context *context = server_handle;
+ kadm5_ret_t ret;
+ krb5_storage *sp;
+ unsigned char buf[1024];
+ int32_t tmp;
+ krb5_data reply;
+ int i;
+
+ *count = 0;
+ *princs = NULL;
+
+ ret = _kadm5_connect(server_handle, 0 /* want_write */);
+ if (ret)
+ return ret;
+
+ krb5_data_zero(&reply);
+
+ sp = krb5_storage_from_mem(buf, sizeof(buf));
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_store_int32(sp, kadm_get_princs);
+ if (ret)
+ goto out;
+ ret = krb5_store_int32(sp, expression != NULL);
+ if (ret)
+ goto out;
+ if (expression) {
+ ret = krb5_store_string(sp, expression);
+ if (ret)
+ goto out;
+ }
+ ret = _kadm5_client_send(context, sp);
+ if (ret)
+ goto out_keep_error;
+ ret = _kadm5_client_recv(context, &reply);
+ if (ret)
+ goto out_keep_error;
+ krb5_storage_free(sp);
+ sp = krb5_storage_from_data (&reply);
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret == 0)
+ ret = tmp;
+
+ if (ret)
+ goto out;
+
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret)
+ goto out;
+
+ *princs = calloc(tmp + 1, sizeof(**princs));
+ if (*princs == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ for (i = 0; i < tmp; i++) {
+ ret = krb5_ret_string(sp, &(*princs)[i]);
+ if (ret)
+ goto out;
+ }
+ *count = tmp;
+
+ out:
+ krb5_clear_error_message(context->context);
+
+ out_keep_error:
+ krb5_storage_free(sp);
+ krb5_data_free(&reply);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kadm5/get_princs_s.c b/third_party/heimdal/lib/kadm5/get_princs_s.c
new file mode 100644
index 0000000..27fac2b
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/get_princs_s.c
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) 1997, 1998, 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+struct foreach_data {
+ const char *exp;
+ char *exp2;
+ char **princs;
+ int count;
+};
+
+static krb5_error_code
+add_princ(krb5_context context, struct foreach_data *d, char *princ)
+{
+ char **tmp;
+ tmp = realloc(d->princs, (d->count + 1) * sizeof(*tmp));
+ if (tmp == NULL)
+ return krb5_enomem(context);
+ d->princs = tmp;
+ d->princs[d->count++] = princ;
+ return 0;
+}
+
+static krb5_error_code
+foreach(krb5_context context, HDB *db, hdb_entry *ent, void *data)
+{
+ struct foreach_data *d = data;
+ char *princ;
+ krb5_error_code ret;
+ ret = krb5_unparse_name(context, ent->principal, &princ);
+ if(ret)
+ return ret;
+ if(d->exp){
+ if(fnmatch(d->exp, princ, 0) == 0 || fnmatch(d->exp2, princ, 0) == 0)
+ ret = add_princ(context, d, princ);
+ else
+ free(princ);
+ }else{
+ ret = add_princ(context, d, princ);
+ }
+ if(ret)
+ free(princ);
+ return ret;
+}
+
+kadm5_ret_t
+kadm5_s_get_principals(void *server_handle,
+ const char *expression,
+ char ***princs,
+ int *count)
+{
+ struct foreach_data d;
+ kadm5_server_context *context = server_handle;
+ kadm5_ret_t ret;
+
+ if (!context->keep_open) {
+ ret = context->db->hdb_open(context->context, context->db, O_RDONLY, 0);
+ if (ret) {
+ krb5_warn(context->context, ret, "opening database");
+ return ret;
+ }
+ }
+ d.exp = expression;
+ {
+ krb5_realm r;
+ int aret;
+
+ ret = krb5_get_default_realm(context->context, &r);
+ if (ret)
+ goto out;
+ aret = asprintf(&d.exp2, "%s@%s", expression, r);
+ free(r);
+ if (aret == -1 || d.exp2 == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ }
+ d.princs = NULL;
+ d.count = 0;
+ ret = hdb_foreach(context->context, context->db, HDB_F_ADMIN_DATA, foreach, &d);
+
+ if (ret == 0)
+ ret = add_princ(context->context, &d, NULL);
+ if (ret == 0){
+ *princs = d.princs;
+ *count = d.count - 1;
+ } else
+ kadm5_free_name_list(context, d.princs, &d.count);
+ free(d.exp2);
+ out:
+ if (!context->keep_open)
+ context->db->hdb_close(context->context, context->db);
+ return _kadm5_error_code(ret);
+}
diff --git a/third_party/heimdal/lib/kadm5/get_s.c b/third_party/heimdal/lib/kadm5/get_s.c
new file mode 100644
index 0000000..0c87343
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/get_s.c
@@ -0,0 +1,411 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <krb5_locl.h>
+#include "kadm5_locl.h"
+#include <assert.h>
+
+RCSID("$Id$");
+
+static kadm5_ret_t
+add_tl_data(kadm5_principal_ent_t ent, int16_t type,
+ const void *data, size_t size)
+{
+ krb5_tl_data *tl;
+
+ tl = calloc(1, sizeof(*tl));
+ if (tl == NULL)
+ return _kadm5_error_code(ENOMEM);
+
+ tl->tl_data_type = type;
+ tl->tl_data_length = size;
+ tl->tl_data_contents = malloc(size);
+ if (tl->tl_data_contents == NULL && size != 0) {
+ free(tl);
+ return _kadm5_error_code(ENOMEM);
+ }
+ memcpy(tl->tl_data_contents, data, size);
+
+ tl->tl_data_next = ent->tl_data;
+ ent->tl_data = tl;
+ ent->n_tl_data++;
+
+ return 0;
+}
+
+static
+krb5_error_code
+copy_keyset_to_kadm5(kadm5_server_context *context, krb5_kvno kvno,
+ size_t n_keys, Key *keys, krb5_salt *salt,
+ kadm5_principal_ent_t out)
+{
+ size_t i;
+ Key *key;
+ krb5_key_data *kd;
+ krb5_data *sp;
+ krb5_error_code ret = 0;
+
+ for (i = 0; i < n_keys; i++) {
+ key = &keys[i];
+ kd = &out->key_data[out->n_key_data];
+ kd->key_data_ver = 2;
+ kd->key_data_kvno = kvno;
+ kd->key_data_type[0] = key->key.keytype;
+ if(key->salt)
+ kd->key_data_type[1] = key->salt->type;
+ else
+ kd->key_data_type[1] = KRB5_PADATA_PW_SALT;
+ /* setup key */
+ kd->key_data_length[0] = key->key.keyvalue.length;
+ kd->key_data_contents[0] = malloc(kd->key_data_length[0]);
+ if(kd->key_data_contents[0] == NULL && kd->key_data_length[0] != 0){
+ ret = krb5_enomem(context->context);
+ break;
+ }
+ memcpy(kd->key_data_contents[0], key->key.keyvalue.data,
+ kd->key_data_length[0]);
+ /* setup salt */
+ if(key->salt)
+ sp = &key->salt->salt;
+ else
+ sp = &salt->saltvalue;
+ kd->key_data_length[1] = sp->length;
+ kd->key_data_contents[1] = malloc(kd->key_data_length[1]);
+ if(kd->key_data_length[1] != 0
+ && kd->key_data_contents[1] == NULL) {
+ memset(kd->key_data_contents[0], 0, kd->key_data_length[0]);
+ ret = krb5_enomem(context->context);
+ break;
+ }
+ memcpy(kd->key_data_contents[1], sp->data, kd->key_data_length[1]);
+ out->n_key_data++;
+ }
+
+ return ret;
+}
+
+kadm5_ret_t
+kadm5_s_get_principal(void *server_handle,
+ krb5_principal princ,
+ kadm5_principal_ent_t out,
+ uint32_t mask)
+{
+ kadm5_server_context *context = server_handle;
+ kadm5_ret_t ret;
+ hdb_entry ent;
+ unsigned int flags = HDB_F_GET_ANY | HDB_F_ADMIN_DATA;
+
+ if ((mask & KADM5_KEY_DATA) || (mask & KADM5_KVNO))
+ flags |= HDB_F_ALL_KVNOS | HDB_F_DECRYPT;
+
+ memset(&ent, 0, sizeof(ent));
+ memset(out, 0, sizeof(*out));
+
+ if (!context->keep_open) {
+ ret = context->db->hdb_open(context->context, context->db, O_RDONLY, 0);
+ if (ret)
+ return ret;
+ }
+
+ /*
+ * We may want to attempt to recover the log on read operations, but we
+ * because the HDB/log lock order is reversed on slaves, in order to avoid
+ * lock contention from kadm5srv apps we need to make sure that the the HDB
+ * open for read-write is optimistic and attempts only a non-blocking lock,
+ * and if it doesn't get it then it should fallback to read-only. But we
+ * don't have that option in the hdb_open() interface at this time.
+ *
+ * For now we won't attempt to recover the log.
+ */
+
+ ret = hdb_fetch_kvno(context->context, context->db, princ, flags,
+ 0 /*timestamp*/, 0/*etype*/, 0/*kvno*/, &ent);
+
+ if (!context->keep_open)
+ context->db->hdb_close(context->context, context->db);
+ if(ret)
+ return _kadm5_error_code(ret);
+
+ if(mask & KADM5_PRINCIPAL)
+ ret = krb5_copy_principal(context->context, ent.principal,
+ &out->principal);
+ if(ret)
+ goto out;
+ if(mask & KADM5_PRINC_EXPIRE_TIME && ent.valid_end)
+ out->princ_expire_time = *ent.valid_end;
+ if(mask & KADM5_PW_EXPIRATION && ent.pw_end)
+ out->pw_expiration = *ent.pw_end;
+ if(mask & KADM5_LAST_PWD_CHANGE)
+ hdb_entry_get_pw_change_time(&ent, &out->last_pwd_change);
+ if(mask & KADM5_ATTRIBUTES){
+ out->attributes |= ent.flags.postdate ? 0 : KRB5_KDB_DISALLOW_POSTDATED;
+ out->attributes |= ent.flags.forwardable ? 0 : KRB5_KDB_DISALLOW_FORWARDABLE;
+ out->attributes |= ent.flags.initial ? KRB5_KDB_DISALLOW_TGT_BASED : 0;
+ out->attributes |= ent.flags.renewable ? 0 : KRB5_KDB_DISALLOW_RENEWABLE;
+ out->attributes |= ent.flags.proxiable ? 0 : KRB5_KDB_DISALLOW_PROXIABLE;
+ out->attributes |= ent.flags.invalid ? KRB5_KDB_DISALLOW_ALL_TIX : 0;
+ out->attributes |= ent.flags.require_preauth ? KRB5_KDB_REQUIRES_PRE_AUTH : 0;
+ out->attributes |= ent.flags.require_pwchange ? KRB5_KDB_REQUIRES_PWCHANGE : 0;
+ out->attributes |= ent.flags.client ? 0 : KRB5_KDB_DISALLOW_CLIENT;
+ out->attributes |= ent.flags.server ? 0 : KRB5_KDB_DISALLOW_SVR;
+ out->attributes |= ent.flags.change_pw ? KRB5_KDB_PWCHANGE_SERVICE : 0;
+ out->attributes |= ent.flags.ok_as_delegate ? KRB5_KDB_OK_AS_DELEGATE : 0;
+ out->attributes |= ent.flags.trusted_for_delegation ? KRB5_KDB_TRUSTED_FOR_DELEGATION : 0;
+ out->attributes |= ent.flags.allow_kerberos4 ? KRB5_KDB_ALLOW_KERBEROS4 : 0;
+ out->attributes |= ent.flags.allow_digest ? KRB5_KDB_ALLOW_DIGEST : 0;
+ out->attributes |= ent.flags.virtual_keys ? KRB5_KDB_VIRTUAL_KEYS : 0;
+ out->attributes |= ent.flags.virtual ? KRB5_KDB_VIRTUAL : 0;
+ out->attributes |= ent.flags.no_auth_data_reqd ? KRB5_KDB_NO_AUTH_DATA_REQUIRED : 0;
+ }
+ if(mask & KADM5_MAX_LIFE) {
+ if(ent.max_life)
+ out->max_life = *ent.max_life;
+ else
+ out->max_life = INT_MAX;
+ }
+ if(mask & KADM5_MOD_TIME) {
+ if(ent.modified_by)
+ out->mod_date = ent.modified_by->time;
+ else
+ out->mod_date = ent.created_by.time;
+ }
+ if(mask & KADM5_MOD_NAME) {
+ if(ent.modified_by) {
+ if (ent.modified_by->principal != NULL)
+ ret = krb5_copy_principal(context->context,
+ ent.modified_by->principal,
+ &out->mod_name);
+ } else if(ent.created_by.principal != NULL)
+ ret = krb5_copy_principal(context->context,
+ ent.created_by.principal,
+ &out->mod_name);
+ else
+ out->mod_name = NULL;
+ }
+ if(ret)
+ goto out;
+
+ if(mask & KADM5_KVNO)
+ out->kvno = ent.kvno;
+ if(mask & KADM5_MKVNO) {
+ size_t n;
+ out->mkvno = 0; /* XXX */
+ for(n = 0; n < ent.keys.len; n++)
+ if(ent.keys.val[n].mkvno) {
+ out->mkvno = *ent.keys.val[n].mkvno; /* XXX this isn't right */
+ break;
+ }
+ }
+#if 0 /* XXX implement */
+ if(mask & KADM5_AUX_ATTRIBUTES)
+ ;
+ if(mask & KADM5_LAST_SUCCESS)
+ ;
+ if(mask & KADM5_LAST_FAILED)
+ ;
+ if(mask & KADM5_FAIL_AUTH_COUNT)
+ ;
+#endif
+ if(mask & KADM5_POLICY) {
+ HDB_extension *ext;
+
+ ext = hdb_find_extension(&ent, choice_HDB_extension_data_policy);
+ if (ext == NULL) {
+ out->policy = strdup("default");
+ /* It's OK if we retun NULL instead of "default" */
+ } else {
+ out->policy = strdup(ext->data.u.policy);
+ if (out->policy == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ }
+ }
+ if(mask & KADM5_MAX_RLIFE) {
+ if(ent.max_renew)
+ out->max_renewable_life = *ent.max_renew;
+ else
+ out->max_renewable_life = INT_MAX;
+ }
+ if(mask & KADM5_KEY_DATA){
+ size_t i;
+ size_t n_keys = ent.keys.len;
+ krb5_salt salt;
+ HDB_extension *ext;
+ HDB_Ext_KeySet *hist_keys = NULL;
+
+ /* Don't return stale keys to kadm5 clients */
+ ret = hdb_prune_keys(context->context, &ent);
+ if (ret)
+ goto out;
+ ext = hdb_find_extension(&ent, choice_HDB_extension_data_hist_keys);
+ if (ext != NULL)
+ hist_keys = &ext->data.u.hist_keys;
+
+ krb5_get_pw_salt(context->context, ent.principal, &salt);
+ for (i = 0; hist_keys != NULL && i < hist_keys->len; i++)
+ n_keys += hist_keys->val[i].keys.len;
+ out->key_data = malloc(n_keys * sizeof(*out->key_data));
+ if (out->key_data == NULL && n_keys != 0) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ out->n_key_data = 0;
+ ret = copy_keyset_to_kadm5(context, ent.kvno, ent.keys.len,
+ ent.keys.val, &salt, out);
+ if (ret)
+ goto out;
+ for (i = 0; hist_keys != NULL && i < hist_keys->len; i++) {
+ ret = copy_keyset_to_kadm5(context, hist_keys->val[i].kvno,
+ hist_keys->val[i].keys.len,
+ hist_keys->val[i].keys.val,
+ &salt, out);
+ if (ret)
+ goto out;
+ }
+ krb5_free_salt(context->context, salt);
+ assert( out->n_key_data == n_keys );
+ }
+ assert(ret == 0);
+ if(mask & KADM5_TL_DATA) {
+ time_t last_pw_expire;
+ const HDB_Ext_PKINIT_acl *acl;
+ const HDB_Ext_Aliases *aliases;
+ const HDB_Ext_KeyRotation *kr;
+ heim_octet_string krb5_config;
+
+ if (ent.etypes) {
+ krb5_data buf;
+ size_t len;
+
+ ASN1_MALLOC_ENCODE(HDB_EncTypeList, buf.data, buf.length,
+ ent.etypes, &len, ret);
+ if (ret == 0) {
+ ret = add_tl_data(out, KRB5_TL_ETYPES, buf.data, buf.length);
+ free(buf.data);
+ }
+ if (ret)
+ goto out;
+ }
+
+ ret = hdb_entry_get_pw_change_time(&ent, &last_pw_expire);
+ if (ret == 0 && last_pw_expire) {
+ unsigned char buf[4];
+ _krb5_put_int(buf, last_pw_expire, sizeof(buf));
+ ret = add_tl_data(out, KRB5_TL_LAST_PWD_CHANGE, buf, sizeof(buf));
+ if (ret)
+ goto out;
+ }
+
+ ret = hdb_entry_get_krb5_config(&ent, &krb5_config);
+ if (ret == 0 && krb5_config.length) {
+ ret = add_tl_data(out, KRB5_TL_KRB5_CONFIG, krb5_config.data,
+ krb5_config.length);
+ if (ret)
+ goto out;
+ }
+ /*
+ * If the client was allowed to get key data, let it have the
+ * password too.
+ */
+ if (mask & KADM5_KEY_DATA) {
+ heim_utf8_string pw;
+
+ /* XXX But not if the client doesn't have ext-keys */
+ ret = hdb_entry_get_password(context->context,
+ context->db, &ent, &pw);
+ if (ret == 0) {
+ ret = add_tl_data(out, KRB5_TL_PASSWORD, pw, strlen(pw) + 1);
+ free(pw);
+ if (ret)
+ goto out;
+ }
+ krb5_clear_error_message(context->context);
+ }
+
+ ret = hdb_entry_get_pkinit_acl(&ent, &acl);
+ if (ret == 0 && acl) {
+ krb5_data buf;
+ size_t len;
+
+ ASN1_MALLOC_ENCODE(HDB_Ext_PKINIT_acl, buf.data, buf.length,
+ acl, &len, ret);
+ if (ret)
+ goto out;
+ if (len != buf.length)
+ krb5_abortx(context->context,
+ "internal ASN.1 encoder error");
+ ret = add_tl_data(out, KRB5_TL_PKINIT_ACL, buf.data, buf.length);
+ free(buf.data);
+ if (ret)
+ goto out;
+ }
+
+ ret = hdb_entry_get_aliases(&ent, &aliases);
+ if (ret == 0 && aliases) {
+ krb5_data buf;
+ size_t len;
+
+ ASN1_MALLOC_ENCODE(HDB_Ext_Aliases, buf.data, buf.length,
+ aliases, &len, ret);
+ if (ret)
+ goto out;
+ if (len != buf.length)
+ krb5_abortx(context->context,
+ "internal ASN.1 encoder error");
+ ret = add_tl_data(out, KRB5_TL_ALIASES, buf.data, buf.length);
+ free(buf.data);
+ if (ret)
+ goto out;
+ }
+
+ ret = hdb_entry_get_key_rotation(context->context, &ent, &kr);
+ if (ret == 0 && kr) {
+ krb5_data buf;
+ size_t len;
+
+ ASN1_MALLOC_ENCODE(HDB_Ext_KeyRotation, buf.data, buf.length,
+ kr, &len, ret);
+ if (ret == 0)
+ ret = add_tl_data(out, KRB5_TL_KEY_ROTATION, buf.data, buf.length);
+ free(buf.data);
+ }
+ }
+
+ out:
+ if (ret)
+ kadm5_free_principal_ent(context, out);
+ hdb_free_entry(context->context, context->db, &ent);
+
+ return _kadm5_error_code(ret);
+}
diff --git a/third_party/heimdal/lib/kadm5/init_c.c b/third_party/heimdal/lib/kadm5/init_c.c
new file mode 100644
index 0000000..5d585d1
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/init_c.c
@@ -0,0 +1,868 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+#include <sys/types.h>
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+
+RCSID("$Id$");
+
+static kadm5_ret_t
+kadm5_c_lock(void *server_handle)
+{
+ return ENOTSUP;
+}
+
+static kadm5_ret_t
+kadm5_c_unlock(void *server_handle)
+{
+ return ENOTSUP;
+}
+
+static void
+set_funcs(kadm5_client_context *c)
+{
+#define SET(C, F) (C)->funcs.F = kadm5 ## _c_ ## F
+#define SETNOTIMP(C, F) (C)->funcs.F = 0
+ SET(c, chpass_principal);
+ SET(c, chpass_principal_with_key);
+ SET(c, create_principal);
+ SET(c, delete_principal);
+ SET(c, destroy);
+ SET(c, flush);
+ SET(c, get_principal);
+ SET(c, get_principals);
+ SET(c, get_privs);
+ SET(c, modify_principal);
+ SET(c, prune_principal);
+ SET(c, randkey_principal);
+ SET(c, rename_principal);
+ SET(c, lock);
+ SET(c, unlock);
+ SETNOTIMP(c, setkey_principal_3);
+}
+
+kadm5_ret_t
+_kadm5_c_init_context(kadm5_client_context **ctx,
+ kadm5_config_params *params,
+ krb5_context context)
+{
+ krb5_error_code ret;
+ char *colon;
+
+ *ctx = malloc(sizeof(**ctx));
+ if (*ctx == NULL)
+ return krb5_enomem(context);
+ memset(*ctx, 0, sizeof(**ctx));
+ krb5_add_et_list(context, initialize_kadm5_error_table_r);
+ set_funcs(*ctx);
+ (*ctx)->context = context;
+ if (params->mask & KADM5_CONFIG_REALM) {
+ ret = 0;
+ (*ctx)->realm = strdup(params->realm);
+ if ((*ctx)->realm == NULL)
+ ret = krb5_enomem(context);
+ } else
+ ret = krb5_get_default_realm((*ctx)->context, &(*ctx)->realm);
+ if (ret) {
+ free(*ctx);
+ return ret;
+ }
+
+ /*
+ * FIXME: If we have a hostlist, we should use the hostlist so that if we
+ * can't reach one server we try another.
+ */
+ if (params->mask & KADM5_CONFIG_ADMIN_SERVER)
+ (*ctx)->admin_server = strdup(params->admin_server);
+ else {
+ char **hostlist;
+
+ ret = krb5_get_krb_admin_hst(context, &(*ctx)->realm, &hostlist);
+ if (ret) {
+ free((*ctx)->realm);
+ free(*ctx);
+ return ret;
+ }
+ (*ctx)->admin_server = strdup(*hostlist);
+ krb5_free_krbhst(context, hostlist);
+ }
+
+ if ((*ctx)->admin_server == NULL) {
+ free((*ctx)->realm);
+ free(*ctx);
+ return krb5_enomem(context);
+ }
+ colon = strchr((*ctx)->admin_server, ':');
+ if (colon != NULL)
+ *colon++ = '\0';
+
+ (*ctx)->kadmind_port = 0;
+
+ if (params->mask & KADM5_CONFIG_KADMIND_PORT)
+ (*ctx)->kadmind_port = params->kadmind_port;
+ else if (colon != NULL) {
+ char *end;
+
+ (*ctx)->kadmind_port = htons(strtol(colon, &end, 0));
+ }
+ if ((*ctx)->kadmind_port == 0)
+ (*ctx)->kadmind_port = krb5_getportbyname(context, "kerberos-adm",
+ "tcp", 749);
+
+ if (params->mask & KADM5_CONFIG_READONLY_ADMIN_SERVER) {
+ (*ctx)->readonly_admin_server = strdup(params->readonly_admin_server);
+ if ((*ctx)->readonly_admin_server == NULL) {
+ free((*ctx)->realm);
+ free(*ctx);
+ return krb5_enomem(context);
+ }
+ } else {
+ char **hostlist;
+
+ ret = krb5_get_krb_readonly_admin_hst(context, &(*ctx)->realm,
+ &hostlist);
+ if (ret == 0) {
+ (*ctx)->readonly_admin_server = strdup(*hostlist);
+ krb5_free_krbhst(context, hostlist);
+ if ((*ctx)->readonly_admin_server == NULL) {
+ free((*ctx)->realm);
+ free(*ctx);
+ return krb5_enomem(context);
+ }
+ }
+ }
+ if ((*ctx)->readonly_admin_server) {
+ colon = strchr((*ctx)->readonly_admin_server, ':');
+ if (colon != NULL)
+ *colon++ = '\0';
+
+ } else {
+ colon = NULL;
+ }
+
+ (*ctx)->readonly_kadmind_port = 0;
+ if (params->mask & KADM5_CONFIG_READONLY_KADMIN_PORT)
+ (*ctx)->readonly_kadmind_port = params->readonly_kadmind_port;
+ else if (colon != NULL) {
+ char *end;
+
+ (*ctx)->readonly_kadmind_port = htons(strtol(colon, &end, 0));
+ }
+ if ((*ctx)->readonly_kadmind_port == 0)
+ (*ctx)->readonly_kadmind_port = (*ctx)->kadmind_port;
+ return 0;
+}
+
+static krb5_error_code
+get_kadm_ticket(krb5_context context,
+ krb5_ccache id,
+ krb5_principal client,
+ const char *server_name)
+{
+ krb5_error_code ret;
+ krb5_creds in, *out;
+
+ memset(&in, 0, sizeof(in));
+ in.client = client;
+ ret = krb5_parse_name(context, server_name, &in.server);
+ if(ret)
+ return ret;
+ ret = krb5_get_credentials(context, 0, id, &in, &out);
+ if(ret == 0)
+ krb5_free_creds(context, out);
+ krb5_free_principal(context, in.server);
+ return ret;
+}
+
+static krb5_error_code
+get_new_cache(krb5_context context,
+ krb5_principal client,
+ const char *password,
+ krb5_prompter_fct prompter,
+ const char *keytab,
+ const char *server_name,
+ krb5_ccache *ret_cache)
+{
+ krb5_error_code ret;
+ krb5_creds cred;
+ krb5_get_init_creds_opt *opt;
+ krb5_ccache id;
+
+ ret = krb5_get_init_creds_opt_alloc (context, &opt);
+ if (ret)
+ return ret;
+
+ krb5_get_init_creds_opt_set_default_flags(context, "kadmin",
+ krb5_principal_get_realm(context,
+ client),
+ opt);
+
+
+ krb5_get_init_creds_opt_set_forwardable (opt, FALSE);
+ krb5_get_init_creds_opt_set_proxiable (opt, FALSE);
+
+ if(password == NULL && prompter == NULL) {
+ krb5_keytab kt;
+ if(keytab == NULL)
+ ret = krb5_kt_default(context, &kt);
+ else
+ ret = krb5_kt_resolve(context, keytab, &kt);
+ if(ret) {
+ krb5_get_init_creds_opt_free(context, opt);
+ return ret;
+ }
+ ret = krb5_get_init_creds_keytab (context,
+ &cred,
+ client,
+ kt,
+ 0,
+ server_name,
+ opt);
+ krb5_kt_close(context, kt);
+ } else {
+ ret = krb5_get_init_creds_password (context,
+ &cred,
+ client,
+ password,
+ prompter,
+ NULL,
+ 0,
+ server_name,
+ opt);
+ }
+ krb5_get_init_creds_opt_free(context, opt);
+ switch(ret){
+ case 0:
+ break;
+ case KRB5_LIBOS_PWDINTR: /* don't print anything if it was just C-c:ed */
+ case KRB5KRB_AP_ERR_BAD_INTEGRITY:
+ case KRB5KRB_AP_ERR_MODIFIED:
+ return KADM5_BAD_PASSWORD;
+ default:
+ return ret;
+ }
+ ret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &id);
+ if(ret)
+ return ret;
+ ret = krb5_cc_initialize (context, id, cred.client);
+ if (ret)
+ return ret;
+ ret = krb5_cc_store_cred (context, id, &cred);
+ if (ret)
+ return ret;
+ krb5_free_cred_contents (context, &cred);
+ *ret_cache = id;
+ return 0;
+}
+
+/*
+ * Check the credential cache `id´ to figure out what principal to use
+ * when talking to the kadmind. If there is a initial kadmin/admin@
+ * credential in the cache, use that client principal. Otherwise, use
+ * the client principals first component and add /admin to the
+ * principal.
+ */
+
+static krb5_error_code
+get_cache_principal(krb5_context context,
+ krb5_ccache *id,
+ krb5_principal *client)
+{
+ krb5_error_code ret;
+ const char *name, *inst;
+ krb5_principal p1, p2;
+
+ ret = krb5_cc_default(context, id);
+ if(ret) {
+ *id = NULL;
+ return ret;
+ }
+
+ ret = krb5_cc_get_principal(context, *id, &p1);
+ if(ret) {
+ krb5_cc_close(context, *id);
+ *id = NULL;
+ return ret;
+ }
+
+ ret = krb5_make_principal(context, &p2, NULL,
+ "kadmin", "admin", NULL);
+ if (ret) {
+ krb5_cc_close(context, *id);
+ *id = NULL;
+ krb5_free_principal(context, p1);
+ return ret;
+ }
+
+ {
+ krb5_creds in, *out;
+ krb5_kdc_flags flags;
+
+ flags.i = 0;
+ memset(&in, 0, sizeof(in));
+
+ in.client = p1;
+ in.server = p2;
+
+ /* check for initial ticket kadmin/admin */
+ ret = krb5_get_credentials_with_flags(context, KRB5_GC_CACHED, flags,
+ *id, &in, &out);
+ krb5_free_principal(context, p2);
+ if (ret == 0) {
+ if (out->flags.b.initial) {
+ *client = p1;
+ krb5_free_creds(context, out);
+ return 0;
+ }
+ krb5_free_creds(context, out);
+ }
+ }
+ krb5_cc_close(context, *id);
+ *id = NULL;
+
+ name = krb5_principal_get_comp_string(context, p1, 0);
+ inst = krb5_principal_get_comp_string(context, p1, 1);
+ if(inst == NULL || strcmp(inst, "admin") != 0) {
+ ret = krb5_make_principal(context, &p2, NULL, name, "admin", NULL);
+ krb5_free_principal(context, p1);
+ if(ret != 0)
+ return ret;
+
+ *client = p2;
+ return 0;
+ }
+
+ *client = p1;
+
+ return 0;
+}
+
+krb5_error_code
+_kadm5_c_get_cred_cache(krb5_context context,
+ const char *client_name,
+ const char *server_name,
+ const char *password,
+ krb5_prompter_fct prompter,
+ const char *keytab,
+ krb5_ccache ccache,
+ krb5_ccache *ret_cache)
+{
+ krb5_error_code ret;
+ krb5_ccache id = NULL;
+ krb5_principal default_client = NULL, client = NULL;
+
+ /* treat empty password as NULL */
+ if(password && *password == '\0')
+ password = NULL;
+ if(server_name == NULL)
+ server_name = KADM5_ADMIN_SERVICE;
+
+ if(client_name != NULL) {
+ ret = krb5_parse_name(context, client_name, &client);
+ if(ret)
+ return ret;
+ }
+
+ if(ccache != NULL) {
+ id = ccache;
+ ret = krb5_cc_get_principal(context, id, &client);
+ if(ret)
+ return ret;
+ } else {
+ /* get principal from default cache, ok if this doesn't work */
+
+ ret = get_cache_principal(context, &id, &default_client);
+ if (ret) {
+ /*
+ * No client was specified by the caller and we cannot
+ * determine the client from a credentials cache.
+ */
+ char userbuf[128];
+ const char *user = NULL;
+
+#ifndef WIN32
+ if (geteuid() == 0)
+ user = roken_get_loginname(userbuf, sizeof(userbuf));
+#endif
+ if (user == NULL)
+ user = roken_get_username(userbuf, sizeof(userbuf));
+ if (user == NULL) {
+ krb5_set_error_message(context, KADM5_FAILURE, "Unable to find local user name");
+ krb5_free_principal(context, client);
+ return KADM5_FAILURE;
+ }
+ ret = krb5_make_principal(context, &default_client,
+ NULL, user, "admin", NULL);
+ if (ret) {
+ krb5_free_principal(context, client);
+ return ret;
+ }
+ }
+ }
+
+
+ /*
+ * No client was specified by the caller, but we have a client
+ * from the default credentials cache.
+ */
+ if (client == NULL && default_client != NULL)
+ client = default_client;
+
+
+ if(id && client && (default_client == NULL ||
+ krb5_principal_compare(context, client, default_client) != 0)) {
+ ret = get_kadm_ticket(context, id, client, server_name);
+ if(ret == 0) {
+ *ret_cache = id;
+ krb5_free_principal(context, default_client);
+ if (default_client != client)
+ krb5_free_principal(context, client);
+ return 0;
+ }
+ if(ccache != NULL)
+ /* couldn't get ticket from cache */
+ return -1;
+ }
+ /* get creds via AS request */
+ if(id && (id != ccache))
+ krb5_cc_close(context, id);
+ if (client != default_client)
+ krb5_free_principal(context, default_client);
+
+ ret = get_new_cache(context, client, password, prompter, keytab,
+ server_name, ret_cache);
+ krb5_free_principal(context, client);
+ return ret;
+}
+
+static kadm5_ret_t
+kadm_connect(kadm5_client_context *ctx)
+{
+ kadm5_ret_t ret;
+ krb5_principal server = NULL;
+ krb5_ccache cc = NULL;
+ rk_socket_t s = rk_INVALID_SOCKET;
+ struct addrinfo *ai, *a;
+ struct addrinfo hints;
+ int free_ai = 0;
+ int error;
+ int kadmin_port = 0;
+ const char *admin_server = NULL;
+ char portstr[NI_MAXSERV];
+ const char *hostname, *slash;
+ char *service_name = NULL;
+ krb5_context context = ctx->context;
+ int writable = 0;
+
+ if (ctx->ac)
+ krb5_auth_con_free(context, ctx->ac);
+ ctx->ac = NULL;
+
+ if (!ctx->want_write) {
+ admin_server = ctx->readonly_admin_server;
+ kadmin_port = ctx->readonly_kadmind_port;
+ }
+ if (admin_server == NULL) {
+ admin_server = ctx->admin_server;
+ writable = 1;
+ }
+ if (kadmin_port < 1)
+ kadmin_port = ctx->kadmind_port;
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_protocol = IPPROTO_TCP;
+
+ snprintf(portstr, sizeof(portstr), "%u", ntohs(kadmin_port));
+
+ hostname = admin_server;
+ slash = strchr(hostname, '/');
+ if (slash != NULL)
+ hostname = slash + 1;
+
+ error = getaddrinfo(hostname, portstr, &hints, &ai);
+ if (error) {
+ ret = KADM5_BAD_SERVER_NAME;
+ goto out;
+ }
+
+ free_ai = 1;
+ for (a = ai; a != NULL; a = a->ai_next) {
+ s = socket(a->ai_family, a->ai_socktype, a->ai_protocol);
+ if (s < 0)
+ continue;
+ if (connect(s, a->ai_addr, a->ai_addrlen) < 0) {
+ krb5_warn(context, errno, "connect(%s)", hostname);
+ rk_closesocket(s);
+ s = rk_INVALID_SOCKET;
+ continue;
+ }
+ break;
+ }
+ if (a == NULL) {
+ krb5_set_error_message(context, ret = KADM5_FAILURE,
+ "failed to contact %s", hostname);
+ goto out;
+ }
+ ret = _kadm5_c_get_cred_cache(context,
+ ctx->client_name,
+ ctx->service_name,
+ NULL, ctx->prompter, ctx->keytab,
+ ctx->ccache, &cc);
+ if (ret)
+ goto out;
+
+ if (ctx->realm)
+ error = asprintf(&service_name, "%s@%s", KADM5_ADMIN_SERVICE,
+ ctx->realm);
+ else
+ error = asprintf(&service_name, "%s", KADM5_ADMIN_SERVICE);
+
+ if (error == -1 || service_name == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ ret = krb5_parse_name(context, service_name, &server);
+ if (ret)
+ goto out;
+
+ ret = krb5_sendauth(context, &ctx->ac, &s,
+ KADMIN_APPL_VERSION, NULL,
+ server, AP_OPTS_MUTUAL_REQUIRED,
+ NULL, NULL, cc, NULL, NULL, NULL);
+ if (ret == 0) {
+ krb5_data params;
+ kadm5_config_params p;
+ memset(&p, 0, sizeof(p));
+ if(ctx->realm) {
+ p.mask |= KADM5_CONFIG_REALM;
+ p.realm = ctx->realm;
+ }
+ ret = _kadm5_marshal_params(context, &p, &params);
+ if (ret == 0) {
+ ret = krb5_write_priv_message(context, ctx->ac, &s, &params);
+ krb5_data_free(&params);
+ }
+ }
+
+ if (ret == 0) {
+ ctx->sock = s;
+ ctx->connected_to_writable = !!writable;
+ }
+
+out:
+ free(service_name);
+ krb5_cc_close(context, cc);
+ krb5_free_principal(context, server);
+ if (free_ai)
+ freeaddrinfo(ai);
+ if (ret) {
+ if (s != rk_INVALID_SOCKET)
+ rk_closesocket(s);
+ krb5_auth_con_free(context, ctx->ac);
+ ctx->ac = NULL;
+ }
+ return ret;
+}
+
+kadm5_ret_t
+_kadm5_connect(void *handle, int want_write)
+{
+ kadm5_client_context *ctx = handle;
+
+ /*
+ * Reconnect? Note that we don't reconnect to read-only kadmin servers if
+ * we're already connected to a writable kadmin server because we sometimes
+ * get a principal record after writing it. We really need the application
+ * upstairs to tell us when to stop hogging writable kadmin servers.
+ *
+ * FIXME: Add an API for marking a kadm5_client_context as not needing to
+ * connect to writable kadmin servers.
+ */
+ ctx->want_write = !!want_write;
+ if (ctx->sock != rk_INVALID_SOCKET && want_write &&
+ !ctx->connected_to_writable) {
+ rk_closesocket(ctx->sock);
+ ctx->sock = rk_INVALID_SOCKET;
+ }
+ if (ctx->sock == rk_INVALID_SOCKET)
+ return kadm_connect(ctx);
+ return 0;
+}
+
+static kadm5_ret_t
+kadm5_c_init_with_context(krb5_context context,
+ const char *client_name,
+ const char *password,
+ krb5_prompter_fct prompter,
+ const char *keytab,
+ krb5_ccache ccache,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ kadm5_ret_t ret;
+ kadm5_client_context *ctx = NULL;
+ krb5_ccache cc;
+
+ ret = _kadm5_c_init_context(&ctx, realm_params, context);
+ if (ret)
+ return ret;
+
+ if (password != NULL && *password != '\0') {
+ ret = _kadm5_c_get_cred_cache(context,
+ client_name,
+ service_name,
+ password, prompter, keytab, ccache, &cc);
+ if (ret) {
+ kadm5_c_destroy(ctx);
+ return ret;
+ }
+ ccache = cc;
+ }
+
+
+ if (client_name != NULL)
+ ctx->client_name = strdup(client_name);
+ else
+ ctx->client_name = NULL;
+ if (service_name != NULL)
+ ctx->service_name = strdup(service_name);
+ else
+ ctx->service_name = NULL;
+ ctx->prompter = prompter;
+ ctx->keytab = keytab;
+ ctx->ccache = ccache;
+ /* maybe we should copy the params here */
+ ctx->sock = -1;
+
+ *server_handle = ctx;
+ return 0;
+}
+
+static kadm5_ret_t
+init_context(const char *client_name,
+ const char *password,
+ krb5_prompter_fct prompter,
+ const char *keytab,
+ krb5_ccache ccache,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ krb5_context context;
+ kadm5_ret_t ret;
+ kadm5_server_context *ctx;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ return ret;
+ ret = kadm5_c_init_with_context(context,
+ client_name,
+ password,
+ prompter,
+ keytab,
+ ccache,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+ if(ret){
+ krb5_free_context(context);
+ return ret;
+ }
+ ctx = *server_handle;
+ ctx->my_context = 1;
+ return 0;
+}
+
+kadm5_ret_t
+kadm5_c_init_with_password_ctx(krb5_context context,
+ const char *client_name,
+ const char *password,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_c_init_with_context(context,
+ client_name,
+ password,
+ krb5_prompter_posix,
+ NULL,
+ NULL,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_c_init_with_password(const char *client_name,
+ const char *password,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return init_context(client_name,
+ password,
+ krb5_prompter_posix,
+ NULL,
+ NULL,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_c_init_with_skey_ctx(krb5_context context,
+ const char *client_name,
+ const char *keytab,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_c_init_with_context(context,
+ client_name,
+ NULL,
+ NULL,
+ keytab,
+ NULL,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+
+kadm5_ret_t
+kadm5_c_init_with_skey(const char *client_name,
+ const char *keytab,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return init_context(client_name,
+ NULL,
+ NULL,
+ keytab,
+ NULL,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_c_init_with_creds_ctx(krb5_context context,
+ const char *client_name,
+ krb5_ccache ccache,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_c_init_with_context(context,
+ client_name,
+ NULL,
+ NULL,
+ NULL,
+ ccache,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_c_init_with_creds(const char *client_name,
+ krb5_ccache ccache,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return init_context(client_name,
+ NULL,
+ NULL,
+ NULL,
+ ccache,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+#if 0
+kadm5_ret_t
+kadm5_init(char *client_name, char *pass,
+ char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+}
+#endif
+
diff --git a/third_party/heimdal/lib/kadm5/init_s.c b/third_party/heimdal/lib/kadm5/init_s.c
new file mode 100644
index 0000000..1b1d7f2
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/init_s.c
@@ -0,0 +1,265 @@
+/*
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+#include <fcntl.h>
+
+
+static kadm5_ret_t
+kadm5_s_init_with_context(krb5_context context,
+ const char *client_name,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ kadm5_ret_t ret;
+ kadm5_server_context *ctx = NULL;
+ char *dbname;
+ char *stash_file;
+
+ *server_handle = NULL;
+ ret = _kadm5_s_init_context(&ctx, realm_params, context);
+ if (ret) {
+ kadm5_s_destroy(ctx);
+ return ret;
+ }
+
+ if (realm_params->mask & KADM5_CONFIG_DBNAME)
+ dbname = realm_params->dbname;
+ else
+ dbname = ctx->config.dbname;
+
+ if (realm_params->mask & KADM5_CONFIG_STASH_FILE)
+ stash_file = realm_params->stash_file;
+ else
+ stash_file = ctx->config.stash_file;
+
+ assert(dbname != NULL);
+ assert(stash_file != NULL);
+ assert(ctx->config.acl_file != NULL);
+ assert(ctx->log_context.log_file != NULL);
+#ifndef NO_UNIX_SOCKETS
+ assert(ctx->log_context.socket_name.sun_path[0] != '\0');
+#else
+ assert(ctx->log_context.socket_info != NULL);
+#endif
+
+ ret = hdb_create(ctx->context, &ctx->db, dbname);
+ if (ret == 0)
+ ret = hdb_set_master_keyfile(ctx->context,
+ ctx->db, stash_file);
+ if (ret) {
+ kadm5_s_destroy(ctx);
+ return ret;
+ }
+
+ ctx->log_context.log_fd = -1;
+
+#ifndef NO_UNIX_SOCKETS
+ ctx->log_context.socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
+#else
+ ctx->log_context.socket_fd = socket(ctx->log_context.socket_info->ai_family,
+ ctx->log_context.socket_info->ai_socktype,
+ ctx->log_context.socket_info->ai_protocol);
+#endif
+
+ if (ctx->log_context.socket_fd != rk_INVALID_SOCKET)
+ socket_set_nonblocking(ctx->log_context.socket_fd, 1);
+
+ ret = krb5_parse_name(ctx->context, client_name, &ctx->caller);
+ if (ret == 0)
+ ret = _kadm5_acl_init(ctx);
+ if (ret)
+ kadm5_s_destroy(ctx);
+ else
+ *server_handle = ctx;
+ return ret;
+}
+
+kadm5_ret_t
+kadm5_s_init_with_password_ctx(krb5_context context,
+ const char *client_name,
+ const char *password,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_s_init_with_context(context,
+ client_name,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_s_init_with_password(const char *client_name,
+ const char *password,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ krb5_context context;
+ kadm5_ret_t ret;
+ kadm5_server_context *ctx;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ return ret;
+ ret = kadm5_s_init_with_password_ctx(context,
+ client_name,
+ password,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+ if(ret){
+ krb5_free_context(context);
+ return ret;
+ }
+ ctx = *server_handle;
+ ctx->my_context = 1;
+ return 0;
+}
+
+kadm5_ret_t
+kadm5_s_init_with_skey_ctx(krb5_context context,
+ const char *client_name,
+ const char *keytab,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_s_init_with_context(context,
+ client_name,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_s_init_with_skey(const char *client_name,
+ const char *keytab,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ krb5_context context;
+ kadm5_ret_t ret;
+ kadm5_server_context *ctx;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ return ret;
+ ret = kadm5_s_init_with_skey_ctx(context,
+ client_name,
+ keytab,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+ if(ret){
+ krb5_free_context(context);
+ return ret;
+ }
+ ctx = *server_handle;
+ ctx->my_context = 1;
+ return 0;
+}
+
+kadm5_ret_t
+kadm5_s_init_with_creds_ctx(krb5_context context,
+ const char *client_name,
+ krb5_ccache ccache,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_s_init_with_context(context,
+ client_name,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_s_init_with_creds(const char *client_name,
+ krb5_ccache ccache,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ krb5_context context;
+ kadm5_ret_t ret;
+ kadm5_server_context *ctx;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ return ret;
+ ret = kadm5_s_init_with_creds_ctx(context,
+ client_name,
+ ccache,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+ if(ret){
+ krb5_free_context(context);
+ return ret;
+ }
+ ctx = *server_handle;
+ ctx->my_context = 1;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/iprop-commands.in b/third_party/heimdal/lib/kadm5/iprop-commands.in
new file mode 100644
index 0000000..5b59e5a
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/iprop-commands.in
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+/* $Id$ */
+
+command = {
+ name = "dump"
+ option = {
+ long = "config-file"
+ short = "c"
+ type = "string"
+ help = "configuration file"
+ argument = "file"
+ }
+ option = {
+ long = "no-lock"
+ short = "n"
+ type = "flag"
+ help = "don't lock iprop log"
+ }
+ option = {
+ long = "reverse"
+ short = "R"
+ type = "flag"
+ help = "dump the log in reverse order"
+ }
+ option = {
+ long = "realm"
+ short = "r"
+ type = "string"
+ help = "realm"
+ }
+ function = "iprop_dump"
+ help = "Prints the iprop transaction log in text."
+ max_args = "1"
+}
+command = {
+ name = "truncate"
+ option = {
+ long = "config-file"
+ short = "c"
+ type = "string"
+ help = "configuration file"
+ argument = "file"
+ }
+ option = {
+ long = "realm"
+ short = "r"
+ type = "string"
+ help = "realm"
+ }
+ option = {
+ long = "keep-entries"
+ short = "K"
+ type = "integer"
+ help = "number of entries to keep"
+ default = "-1"
+ }
+ option = {
+ long = "max-bytes"
+ short = "B"
+ type = "integer"
+ help = "keep entries that fit in the given number of bytes"
+ default = "-1"
+ }
+ option = {
+ long = "reset"
+ short = "R"
+ type = "flag"
+ help = "reset the log to version 1; forces full propagation"
+ default = "0";
+ }
+ function = "iprop_truncate"
+ help = "Truncate the log, preserve the version number. Keeps 100 entries by default."
+ max_args = "1"
+}
+command = {
+ name = "replay"
+ option = {
+ long = "start-version"
+ type = "integer"
+ help = "start replay with this version"
+ argument = "version-number"
+ default = "-1"
+ }
+ option = {
+ long = "end-version"
+ type = "integer"
+ help = "end replay with this version"
+ argument = "version-number"
+ default = "-1"
+ }
+ option = {
+ long = "config-file"
+ short = "c"
+ type = "string"
+ help = "configuration file"
+ argument = "file"
+ }
+ option = {
+ long = "realm"
+ short = "r"
+ type = "string"
+ help = "realm"
+ }
+ function = "iprop_replay"
+ help = "Replay the log on the database."
+ max_args = "1"
+}
+command = {
+ name = "last-version"
+ option = {
+ long = "config-file"
+ short = "c"
+ type = "string"
+ help = "configuration file"
+ argument = "file"
+ }
+ option = {
+ long = "no-lock"
+ short = "n"
+ type = "flag"
+ help = "don't lock iprop log"
+ }
+ option = {
+ long = "realm"
+ short = "r"
+ type = "string"
+ help = "realm"
+ }
+ function = "last_version"
+ help = "Print the last version of the log-file."
+}
+command = {
+ name = "signal"
+ option = {
+ long = "config-file"
+ short = "c"
+ type = "string"
+ help = "configuration file"
+ argument = "file"
+ }
+ option = {
+ long = "realm"
+ short = "r"
+ type = "string"
+ help = "realm"
+ }
+ function = "signal_master"
+ help = "Print the last version of the log-file."
+ max_args = "0"
+}
+command = {
+ name = "help"
+ argument = "command"
+ max_args = "1"
+ function = "help"
+}
diff --git a/third_party/heimdal/lib/kadm5/iprop-log-version.rc b/third_party/heimdal/lib/kadm5/iprop-log-version.rc
new file mode 100644
index 0000000..b8a2295
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/iprop-log-version.rc
@@ -0,0 +1,36 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#define RC_FILE_TYPE VFT_APP
+#define RC_FILE_DESC_0409 "IProp Log Tool"
+#define RC_FILE_ORIG_0409 "iprop-log.exe"
+
+#include "../../windows/version.rc"
diff --git a/third_party/heimdal/lib/kadm5/iprop-log.8 b/third_party/heimdal/lib/kadm5/iprop-log.8
new file mode 100644
index 0000000..f34d800
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/iprop-log.8
@@ -0,0 +1,254 @@
+.\" $Id$
+.\"
+.\" Copyright (c) 2005 - 2007 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd February 18, 2007
+.Dt IPROP-LOG 8
+.Os
+.Sh NAME
+.Nm iprop-log
+.Nd examine and maintain the iprop log file
+.Sh SYNOPSIS
+.Nm
+.Op Fl Fl version
+.Op Fl h | Fl Fl help
+.Ar command
+.Pp
+.Nm iprop-log truncate
+.Oo Fl c Ar file \*(Ba Xo
+.Fl Fl config-file= Ns Ar file
+.Xc
+.Oc
+.Oo Fl r Ar string \*(Ba Xo
+.Fl Fl realm= Ns Ar string
+.Xc
+.Oc
+.Oo Fl K Ar integer \*(Ba Xo
+.Fl Fl keep-entries= Ns Ar integer
+.Xc
+.Oc
+.Oo Fl B Ar integer \*(Ba Xo
+.Fl Fl max-bytes= Ns Ar integer
+.Xc
+.Oc
+.Oo Fl R \*(Ba Xo
+.Fl Fl reset
+.Xc
+.Oc
+.Op Fl h | Fl Fl help
+.Op Ar log-file
+.Pp
+.Nm iprop-log dump
+.Oo Fl c Ar file \*(Ba Xo
+.Fl Fl config-file= Ns Ar file
+.Xc
+.Oc
+.Oo Fl r Ar string \*(Ba Xo
+.Fl Fl realm= Ns Ar string
+.Xc
+.Oc
+.Oo Fl n \*(Ba Xo
+.Fl Fl no-lock
+.Xc
+.Oc
+.Oo Fl R \*(Ba Xo
+.Fl Fl reverse
+.Xc
+.Oc
+.Op Fl h | Fl Fl help
+.Op Ar log-file
+.Pp
+.Nm iprop-log replay
+.Op Fl Fl start-version= Ns Ar version-number
+.Op Fl Fl end-version= Ns Ar version-number
+.Oo Fl c Ar file \*(Ba Xo
+.Fl Fl config-file= Ns Ar file
+.Xc
+.Oc
+.Oo Fl r Ar string \*(Ba Xo
+.Fl Fl realm= Ns Ar string
+.Xc
+.Oc
+.Op Fl h | Fl Fl help
+.Op Ar log-file
+.Pp
+.Nm iprop-log last-version
+.Oo Fl c Ar file \*(Ba Xo
+.Fl Fl config-file= Ns Ar file
+.Xc
+.Oc
+.Oo Fl r Ar string \*(Ba Xo
+.Fl Fl realm= Ns Ar string
+.Xc
+.Oc
+.Oo Fl n \*(Ba Xo
+.Fl Fl no-lock
+.Xc
+.Oc
+.Op Fl h | Fl Fl help
+.Op Ar log-files
+.Pp
+.Nm iprop-log signal
+.Oo Fl c Ar file \*(Ba Xo
+.Fl Fl config-file= Ns Ar file
+.Xc
+.Oc
+.Oo Fl r Ar string \*(Ba Xo
+.Fl Fl realm= Ns Ar string
+.Xc
+.Oc
+.Op Fl h | Fl Fl help
+.Pp
+.Sh DESCRIPTION
+Supported options:
+.Bl -tag -width Ds
+.It Fl Fl version
+.It Fl h , Fl Fl help
+.El
+.Pp
+command can be one of the following:
+.Bl -tag -width truncate
+.It truncate
+.Bl -tag -width Ds
+.It Fl c Ar file , Fl Fl config-file= Ns Ar file
+configuration file
+.It Fl r Ar string , Fl Fl realm= Ns Ar string
+realm
+.It Xo
+.Fl K Ar integer ,
+.Fl Fl keep-entries= Ns Ar integer
+.Xc
+.It Xo
+.Fl B Ar integer ,
+.Fl Fl max-bytes= Ns Ar integer
+.Xc
+.It Xo
+.Fl R ,
+.Fl Fl reset
+.Xc
+.El
+.Pp
+If
+.Fl Fl reset
+is given, then the given, configured, or default log file will be
+truncated and will start at version 1. This forces full propagations to
+all slave KDCs.
+.Pp
+Otherwise the log will be truncated but some entries will be preserved,
+as specified by the
+.Fl Fl keep-entries
+and/or
+.Fl Fl max-bytes
+options. The largest number of
+.Fl Fl keep-entries
+entries that are available and fit in the given
+.Fl Fl max-bytes
+option will be used. The
+.Fl Fl keep-entries option defaults to 100, and the
+.Fl Fl max-bytes
+option defaults to the
+.Ar log-max-size
+parameter in the configuration.
+.Pp
+.It dump
+.Bl -tag -width Ds
+.It Fl c Ar file , Fl Fl config-file= Ns Ar file
+configuration file
+.It Xo
+.Fl r Ar string ,
+.Fl Fl realm= Ns Ar string
+.Xc
+realm
+.It Xo
+.Fl n Ar string ,
+.Fl Fl no-lock
+.Xc
+.It Xo
+.Fl R Ar string ,
+.Fl Fl reverse
+.Xc
+.El
+.Pp
+Print out all entries in the given, configured, or default log file to
+standard output. If the
+.Fl n
+option is used then don't lock the iprop log file. If the
+.Fl R
+option is used, then print the entries in reverse order
+(this can be useful when the log is very large).
+.It replay
+.Bl -tag -width Ds
+.It Fl Fl start-version= Ns Ar version-number
+start replay with this version
+.It Xo
+.Fl Fl end-version= Ns Ar version-number
+.Xc
+end replay with this version
+.It Fl c Ar file , Fl Fl config-file= Ns Ar file
+configuration file
+.It Fl r Ar string , Fl Fl realm= Ns Ar string
+realm
+.El
+.Pp
+Replay the changes from specified entries (or all if none is specified)
+in the given, configured, or default transaction log file to the
+database.
+.It last-version
+.Bl -tag -width Ds
+.It Fl c Ar file , Fl Fl config-file= Ns Ar file
+configuration file
+.It Fl r Ar string , Fl Fl realm= Ns Ar string
+realm
+.It Xo
+.Fl n Ar string ,
+.Fl Fl no-lock
+.Xc
+.El
+.Pp
+prints the version of the last record in each of the given log files, or
+the configured, or the default log file if none is given.
+.It signal
+.Bl -tag -width Ds
+.It Fl c Ar file , Fl Fl config-file= Ns Ar file
+configuration file
+.It Fl r Ar string , Fl Fl realm= Ns Ar string
+realm
+.El
+.Pp
+Signals the ipropd-master daemon to send updates to slaves. Normally
+kadmin does this every time it writes to the database, so this should
+rarely be needed.
+.El
+.Sh SEE ALSO
+.Xr iprop 8
diff --git a/third_party/heimdal/lib/kadm5/iprop-log.c b/third_party/heimdal/lib/kadm5/iprop-log.c
new file mode 100644
index 0000000..a2ad51e
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/iprop-log.c
@@ -0,0 +1,653 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "iprop.h"
+#include <sl.h>
+#include <parse_time.h>
+#include "iprop-commands.h"
+
+RCSID("$Id$");
+
+static krb5_context context;
+
+static kadm5_server_context *
+get_kadmin_context(const char *config_file, char *realm)
+{
+ kadm5_config_params conf;
+ krb5_error_code ret;
+ void *kadm_handle;
+ char *file = NULL;
+ char **files;
+ int aret;
+
+ if (config_file == NULL) {
+ aret = asprintf(&file, "%s/kdc.conf", hdb_db_dir(context));
+ if (aret == -1 || file == NULL)
+ errx(1, "out of memory");
+ config_file = file;
+ }
+
+ ret = krb5_prepend_config_files_default(config_file, &files);
+ free(file);
+ if (ret)
+ krb5_err(context, 1, ret, "getting configuration files");
+
+ ret = krb5_set_config_files(context, files);
+ krb5_free_config_files(files);
+ if (ret)
+ krb5_err(context, 1, ret, "reading configuration files");
+
+ memset(&conf, 0, sizeof(conf));
+ if(realm) {
+ conf.mask |= KADM5_CONFIG_REALM;
+ conf.realm = realm;
+ }
+
+ ret = kadm5_init_with_password_ctx (context,
+ KADM5_ADMIN_SERVICE,
+ NULL,
+ KADM5_ADMIN_SERVICE,
+ &conf, 0, 0,
+ &kadm_handle);
+ if (ret)
+ krb5_err (context, 1, ret, "kadm5_init_with_password_ctx");
+
+ return (kadm5_server_context *)kadm_handle;
+}
+
+/*
+ * dump log
+ */
+
+static const char *op_names[] = {
+ "get",
+ "delete",
+ "create",
+ "rename",
+ "chpass",
+ "modify",
+ "randkey",
+ "get_privs",
+ "get_princs",
+ "chpass_with_key",
+ "nop"
+};
+
+static kadm5_ret_t
+print_entry(kadm5_server_context *server_context,
+ uint32_t ver,
+ time_t timestamp,
+ enum kadm_ops op,
+ uint32_t len,
+ krb5_storage *sp,
+ void *ctx)
+{
+ char t[256];
+ const char *entry_kind = ctx;
+ int32_t mask;
+ int32_t nop_time;
+ uint32_t nop_ver;
+ hdb_entry ent;
+ krb5_principal source;
+ char *name1, *name2;
+ krb5_data data;
+ krb5_context scontext = server_context->context;
+ krb5_error_code ret;
+
+ krb5_data_zero(&data);
+
+ strftime(t, sizeof(t), "%Y-%m-%d %H:%M:%S", localtime(&timestamp));
+
+ if((int)op < (int)kadm_get || (int)op > (int)kadm_nop) {
+ printf("unknown op: %d\n", op);
+ return 0;
+ }
+
+ printf ("%s%s: ver = %u, timestamp = %s, len = %u\n",
+ entry_kind, op_names[op], ver, t, len);
+ switch(op) {
+ case kadm_delete:
+ ret = krb5_ret_principal(sp, &source);
+ if (ret == 0)
+ ret = krb5_unparse_name(scontext, source, &name1);
+ if (ret)
+ krb5_err(scontext, 1, ret, "Failed to read a delete record");
+ printf(" %s\n", name1);
+ free(name1);
+ krb5_free_principal(scontext, source);
+ break;
+ case kadm_rename:
+ ret = krb5_data_alloc(&data, len);
+ if (ret == 0)
+ ret = krb5_ret_principal(sp, &source);
+ if (ret == 0 && krb5_storage_read(sp, data.data, data.length) == -1)
+ ret = errno;
+ if (ret == 0)
+ ret = hdb_value2entry(scontext, &data, &ent);
+ if (ret == 0)
+ ret = krb5_unparse_name(scontext, source, &name1);
+ if (ret == 0)
+ ret = krb5_unparse_name(scontext, ent.principal, &name2);
+ if (ret)
+ krb5_err(scontext, 1, ret, "Failed to read a rename record");
+ printf(" %s -> %s\n", name1, name2);
+ free(name1);
+ free(name2);
+ krb5_free_principal(scontext, source);
+ free_hdb_entry(&ent);
+ break;
+ case kadm_create:
+ ret = krb5_data_alloc(&data, len);
+ if (ret == 0 && krb5_storage_read(sp, data.data, data.length) == -1)
+ ret = errno;
+ if (ret == 0)
+ ret = hdb_value2entry(scontext, &data, &ent);
+ if (ret)
+ krb5_err(scontext, 1, ret, "Failed to read a create record");
+ mask = ~0;
+ goto foo;
+ case kadm_modify:
+ ret = krb5_data_alloc(&data, len);
+ if (ret == 0)
+ ret = krb5_ret_int32(sp, &mask);
+ if (ret == 0 && krb5_storage_read(sp, data.data, data.length) == -1)
+ ret = errno;
+ if (ret == 0)
+ ret = hdb_value2entry(scontext, &data, &ent);
+ if (ret)
+ krb5_err(scontext, 1, ret, "Failed to read a modify record");
+ foo:
+ if(ent.principal /* mask & KADM5_PRINCIPAL */) {
+ ret = krb5_unparse_name(scontext, ent.principal, &name1);
+ if (ret)
+ krb5_err(scontext, 1, ret,
+ "Failed to process a create or modify record");
+ printf(" principal = %s\n", name1);
+ free(name1);
+ }
+ if(mask & KADM5_PRINC_EXPIRE_TIME) {
+ if(ent.valid_end == NULL) {
+ strlcpy(t, "never", sizeof(t));
+ } else {
+ strftime(t, sizeof(t), "%Y-%m-%d %H:%M:%S",
+ localtime(ent.valid_end));
+ }
+ printf(" expires = %s\n", t);
+ }
+ if(mask & KADM5_PW_EXPIRATION) {
+ if(ent.pw_end == NULL) {
+ strlcpy(t, "never", sizeof(t));
+ } else {
+ strftime(t, sizeof(t), "%Y-%m-%d %H:%M:%S",
+ localtime(ent.pw_end));
+ }
+ printf(" password exp = %s\n", t);
+ }
+ if(mask & KADM5_LAST_PWD_CHANGE) {
+ }
+ if(mask & KADM5_ATTRIBUTES) {
+ unparse_flags(HDBFlags2int(ent.flags),
+ asn1_HDBFlags_units(), t, sizeof(t));
+ printf(" attributes = %s\n", t);
+ }
+ if(mask & KADM5_MAX_LIFE) {
+ if(ent.max_life == NULL)
+ strlcpy(t, "for ever", sizeof(t));
+ else
+ unparse_time(*ent.max_life, t, sizeof(t));
+ printf(" max life = %s\n", t);
+ }
+ if(mask & KADM5_MAX_RLIFE) {
+ if(ent.max_renew == NULL)
+ strlcpy(t, "for ever", sizeof(t));
+ else
+ unparse_time(*ent.max_renew, t, sizeof(t));
+ printf(" max rlife = %s\n", t);
+ }
+ if(mask & KADM5_MOD_TIME) {
+ printf(" mod time\n");
+ }
+ if(mask & KADM5_MOD_NAME) {
+ printf(" mod name\n");
+ }
+ if(mask & KADM5_KVNO) {
+ printf(" kvno = %d\n", ent.kvno);
+ }
+ if(mask & KADM5_MKVNO) {
+ printf(" mkvno\n");
+ }
+ if(mask & KADM5_AUX_ATTRIBUTES) {
+ printf(" aux attributes\n");
+ }
+ if(mask & KADM5_POLICY) {
+ printf(" policy\n");
+ }
+ if(mask & KADM5_POLICY_CLR) {
+ printf(" mod time\n");
+ }
+ if(mask & KADM5_LAST_SUCCESS) {
+ printf(" last success\n");
+ }
+ if(mask & KADM5_LAST_FAILED) {
+ printf(" last failed\n");
+ }
+ if(mask & KADM5_FAIL_AUTH_COUNT) {
+ printf(" fail auth count\n");
+ }
+ if(mask & KADM5_KEY_DATA) {
+ printf(" key data\n");
+ }
+ if(mask & KADM5_TL_DATA) {
+ printf(" tl data\n");
+ }
+ free_hdb_entry(&ent);
+ break;
+ case kadm_nop :
+ if (len == 16) {
+ uint64_t off;
+ ret = krb5_ret_uint64(sp, &off);
+ if (ret)
+ krb5_err(scontext, 1, ret, "Failed to read a no-op record");
+ printf("uberblock offset %llu ", (unsigned long long)off);
+ } else {
+ printf("nop");
+ }
+ if (len == 16 || len == 8) {
+ ret = krb5_ret_int32(sp, &nop_time);
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &nop_ver);
+ if (ret)
+ krb5_err(scontext, 1, ret, "Failed to read a no-op record");
+
+ timestamp = nop_time;
+ strftime(t, sizeof(t), "%Y-%m-%d %H:%M:%S", localtime(&timestamp));
+ printf("timestamp %s version %u", t, nop_ver);
+ }
+ printf("\n");
+ break;
+ default:
+ krb5_errx(scontext, 1, "Unknown record type");
+ }
+ krb5_data_free(&data);
+
+ return 0;
+}
+
+int
+iprop_dump(struct dump_options *opt, int argc, char **argv)
+{
+ kadm5_server_context *server_context;
+ krb5_error_code ret;
+ enum kadm_iter_opts iter_opts_1st = 0;
+ enum kadm_iter_opts iter_opts_2nd = 0;
+ char *desc_1st = "";
+ char *desc_2nd = "";
+
+ server_context = get_kadmin_context(opt->config_file_string,
+ opt->realm_string);
+
+ if (argc > 0) {
+ free(server_context->log_context.log_file);
+ server_context->log_context.log_file = strdup(argv[0]);
+ if (server_context->log_context.log_file == NULL)
+ krb5_err(context, 1, errno, "strdup");
+ }
+
+ if (opt->reverse_flag) {
+ iter_opts_1st = kadm_backward | kadm_unconfirmed;
+ iter_opts_2nd = kadm_backward | kadm_confirmed;
+ desc_1st = "unconfirmed ";
+ } else {
+ iter_opts_1st = kadm_forward | kadm_confirmed;
+ iter_opts_2nd = kadm_forward | kadm_unconfirmed;
+ desc_2nd = "unconfirmed";
+ }
+
+ if (opt->no_lock_flag) {
+ ret = kadm5_log_init_sharedlock(server_context, LOCK_NB);
+ if (ret == EAGAIN || ret == EWOULDBLOCK) {
+ warnx("Not locking the iprop log");
+ ret = kadm5_log_init_nolock(server_context);
+ if (ret)
+ krb5_err(context, 1, ret, "kadm5_log_init_nolock");
+ }
+ } else {
+ warnx("If this command appears to block, try the --no-lock option");
+ ret = kadm5_log_init_sharedlock(server_context, 0);
+ if (ret)
+ krb5_err(context, 1, ret, "kadm5_log_init_sharedlock");
+ }
+
+ ret = kadm5_log_foreach(server_context, iter_opts_1st,
+ NULL, print_entry, desc_1st);
+ if (ret)
+ krb5_warn(context, ret, "kadm5_log_foreach");
+
+ ret = kadm5_log_foreach(server_context, iter_opts_2nd,
+ NULL, print_entry, desc_2nd);
+ if (ret)
+ krb5_warn(context, ret, "kadm5_log_foreach");
+
+ ret = kadm5_log_end (server_context);
+ if (ret)
+ krb5_warn(context, ret, "kadm5_log_end");
+
+ kadm5_destroy(server_context);
+ return 0;
+}
+
+int
+iprop_truncate(struct truncate_options *opt, int argc, char **argv)
+{
+ kadm5_server_context *server_context;
+ krb5_error_code ret;
+
+ server_context = get_kadmin_context(opt->config_file_string,
+ opt->realm_string);
+
+ if (argc > 0) {
+ free(server_context->log_context.log_file);
+ server_context->log_context.log_file = strdup(argv[0]);
+ if (server_context->log_context.log_file == NULL)
+ krb5_err(context, 1, errno, "strdup");
+ }
+
+ if (opt->keep_entries_integer < 0 &&
+ opt->max_bytes_integer < 0) {
+ opt->keep_entries_integer = 100;
+ opt->max_bytes_integer = 0;
+ }
+ if (opt->keep_entries_integer < 0)
+ opt->keep_entries_integer = 0;
+ if (opt->max_bytes_integer < 0)
+ opt->max_bytes_integer = 0;
+
+ if (opt->reset_flag) {
+ /* First recover unconfirmed records */
+ ret = kadm5_log_init(server_context);
+ if (ret == 0)
+ ret = kadm5_log_reinit(server_context, 0);
+ } else {
+ ret = kadm5_log_init(server_context);
+ if (ret)
+ krb5_err(context, 1, ret, "kadm5_log_init");
+ ret = kadm5_log_truncate(server_context, opt->keep_entries_integer,
+ opt->max_bytes_integer);
+ }
+ if (ret)
+ krb5_err(context, 1, ret, "kadm5_log_truncate");
+
+ kadm5_log_signal_master(server_context);
+
+ kadm5_destroy(server_context);
+ return 0;
+}
+
+int
+last_version(struct last_version_options *opt, int argc, char **argv)
+{
+ kadm5_server_context *server_context;
+ char *alt_argv[2] = { NULL, NULL };
+ krb5_error_code ret;
+ uint32_t version;
+ size_t i;
+
+ server_context = get_kadmin_context(opt->config_file_string,
+ opt->realm_string);
+
+ if (argc == 0) {
+ alt_argv[0] = strdup(server_context->log_context.log_file);
+ if (alt_argv[0] == NULL)
+ krb5_err(context, 1, errno, "strdup");
+ argv = alt_argv;
+ argc = 1;
+ }
+
+ for (i = 0; i < argc; i++) {
+ free(server_context->log_context.log_file);
+ server_context->log_context.log_file = strdup(argv[i]);
+ if (server_context->log_context.log_file == NULL)
+ krb5_err(context, 1, errno, "strdup");
+
+ if (opt->no_lock_flag) {
+ ret = kadm5_log_init_sharedlock(server_context, LOCK_NB);
+ if (ret == EAGAIN || ret == EWOULDBLOCK) {
+ warnx("Not locking the iprop log");
+ ret = kadm5_log_init_nolock(server_context);
+ if (ret)
+ krb5_err(context, 1, ret, "kadm5_log_init_nolock");
+ }
+ } else {
+ warnx("If this command appears to block, try the "
+ "--no-lock option");
+ ret = kadm5_log_init_sharedlock(server_context, 0);
+ if (ret)
+ krb5_err(context, 1, ret, "kadm5_log_init_sharedlock");
+ }
+
+ ret = kadm5_log_get_version (server_context, &version);
+ if (ret)
+ krb5_err (context, 1, ret, "kadm5_log_get_version");
+
+ ret = kadm5_log_end (server_context);
+ if (ret)
+ krb5_warn(context, ret, "kadm5_log_end");
+
+ printf("version: %lu\n", (unsigned long)version);
+ }
+
+ kadm5_destroy(server_context);
+ free(alt_argv[0]);
+ return 0;
+}
+
+int
+signal_master(struct signal_options *opt, int argc, char **argv)
+{
+ kadm5_server_context *server_context;
+
+ server_context = get_kadmin_context(opt->config_file_string,
+ opt->realm_string);
+
+ kadm5_log_signal_master(server_context);
+
+ kadm5_destroy(server_context);
+ return 0;
+}
+
+/*
+ * Replay log
+ */
+
+int start_version = -1;
+int end_version = -1;
+
+static kadm5_ret_t
+apply_entry(kadm5_server_context *server_context,
+ uint32_t ver,
+ time_t timestamp,
+ enum kadm_ops op,
+ uint32_t len,
+ krb5_storage *sp,
+ void *ctx)
+{
+ struct replay_options *opt = ctx;
+ krb5_error_code ret;
+
+ if((opt->start_version_integer != -1 && ver < (uint32_t)opt->start_version_integer) ||
+ (opt->end_version_integer != -1 && ver > (uint32_t)opt->end_version_integer)) {
+ /* XXX skip this entry */
+ return 0;
+ }
+ printf ("ver %u... ", ver);
+ fflush (stdout);
+
+ ret = kadm5_log_replay(server_context, op, ver, len, sp);
+ if (ret)
+ krb5_warn (server_context->context, ret, "kadm5_log_replay");
+
+ printf ("done\n");
+
+ return 0;
+}
+
+int
+iprop_replay(struct replay_options *opt, int argc, char **argv)
+{
+ kadm5_server_context *server_context;
+ krb5_error_code ret;
+
+ server_context = get_kadmin_context(opt->config_file_string,
+ opt->realm_string);
+
+ if (argc > 0) {
+ free(server_context->log_context.log_file);
+ server_context->log_context.log_file = strdup(argv[0]);
+ if (server_context->log_context.log_file == NULL)
+ krb5_err(context, 1, errno, "strdup");
+ }
+
+ ret = server_context->db->hdb_open(context,
+ server_context->db,
+ O_RDWR | O_CREAT, 0600);
+ if (ret)
+ krb5_err (context, 1, ret, "db->open");
+
+ ret = kadm5_log_init (server_context);
+ if (ret)
+ krb5_err (context, 1, ret, "kadm5_log_init");
+
+ ret = kadm5_log_foreach(server_context,
+ kadm_forward | kadm_confirmed | kadm_unconfirmed,
+ NULL, apply_entry, opt);
+ if(ret)
+ krb5_warn(context, ret, "kadm5_log_foreach");
+ ret = kadm5_log_end (server_context);
+ if (ret)
+ krb5_warn(context, ret, "kadm5_log_end");
+ ret = server_context->db->hdb_close (context, server_context->db);
+ if (ret)
+ krb5_err (context, 1, ret, "db->close");
+
+ kadm5_destroy(server_context);
+ return 0;
+}
+
+static int help_flag;
+static int version_flag;
+
+static struct getargs args[] = {
+ { "version", 0, arg_flag, &version_flag,
+ NULL, NULL
+ },
+ { "help", 'h', arg_flag, &help_flag,
+ NULL, NULL
+ }
+};
+
+static int num_args = sizeof(args) / sizeof(args[0]);
+
+int
+help(void *opt, int argc, char **argv)
+{
+ if(argc == 0) {
+ sl_help(commands, 1, argv - 1 /* XXX */);
+ } else {
+ SL_cmd *c = sl_match (commands, argv[0], 0);
+ if(c == NULL) {
+ fprintf (stderr, "No such command: %s. "
+ "Try \"help\" for a list of commands\n",
+ argv[0]);
+ } else {
+ if(c->func) {
+ static char shelp[] = "--help";
+ char *fake[3];
+ fake[0] = argv[0];
+ fake[1] = shelp;
+ fake[2] = NULL;
+ (*c->func)(2, fake);
+ fprintf(stderr, "\n");
+ }
+ if(c->help && *c->help)
+ fprintf (stderr, "%s\n", c->help);
+ if((++c)->name && c->func == NULL) {
+ int f = 0;
+ fprintf (stderr, "Synonyms:");
+ while (c->name && c->func == NULL) {
+ fprintf (stderr, "%s%s", f ? ", " : " ", (c++)->name);
+ f = 1;
+ }
+ fprintf (stderr, "\n");
+ }
+ }
+ }
+ return 0;
+}
+
+static void
+usage(int status)
+{
+ arg_printusage(args, num_args, NULL, "command");
+ exit(status);
+}
+
+int
+main(int argc, char **argv)
+{
+ int optidx = 0;
+ krb5_error_code ret;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, num_args, argc, argv, &optidx))
+ usage(1);
+ if(help_flag)
+ usage(0);
+ if(version_flag) {
+ print_version(NULL);
+ exit(0);
+ }
+ argc -= optidx;
+ argv += optidx;
+ if(argc == 0)
+ usage(1);
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_init_context failed with: %d\n", ret);
+
+ ret = sl_command(commands, argc, argv);
+ if(ret == -1)
+ warnx ("unrecognized command: %s", argv[0]);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kadm5/iprop.8 b/third_party/heimdal/lib/kadm5/iprop.8
new file mode 100644
index 0000000..b881c44
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/iprop.8
@@ -0,0 +1,208 @@
+.\" $Id$
+.\"
+.\" Copyright (c) 2005 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.Dd May 24, 2005
+.Dt IPROP 8
+.Os
+.Sh NAME
+.Nm iprop ,
+.Nm ipropd-master ,
+.Nm ipropd-slave
+.Nd propagate transactions from a Heimdal Kerberos master KDC to slave KDCs
+.Sh SYNOPSIS
+.Nm ipropd-master
+.Oo Fl c Ar string \*(Ba Xo
+.Fl Fl config-file= Ns Ar string
+.Xc
+.Oc
+.Oo Fl r Ar string \*(Ba Xo
+.Fl Fl realm= Ns Ar string
+.Xc
+.Oc
+.Oo Fl k Ar kspec \*(Ba Xo
+.Fl Fl keytab= Ns Ar kspec
+.Xc
+.Oc
+.Oo Fl d Ar file \*(Ba Xo
+.Fl Fl database= Ns Ar file
+.Xc
+.Oc
+.Op Fl Fl slave-stats-file= Ns Ar file
+.Op Fl Fl time-missing= Ns Ar time
+.Op Fl Fl time-gone= Ns Ar time
+.Op Fl Fl detach
+.Op Fl Fl version
+.Op Fl Fl help
+.Nm ipropd-slave
+.Oo Fl c Ar string \*(Ba Xo Fl Fl config-file= Ns Ar string Xc Oc
+.Oo Fl r Ar string \*(Ba Xo Fl Fl realm= Ns Ar string Xc Oc
+.Oo Fl d Ar file \*(Ba Xo Fl Fl database= Ns Ar file Xc Oc
+.Oo Fl k Ar kspec \*(Ba Xo Fl Fl keytab= Ns Ar kspec Xc Oc
+.Op Fl Fl statusfile= Ns Ar file
+.Op Fl Fl hostname= Ns Ar hostname
+.Op Fl Fl port= Ns Ar port
+.Op Fl Fl time-lost= Ns Ar time
+.Op Fl Fl async-hdb
+.Op Fl Fl detach
+.Op Fl Fl version
+.Op Fl Fl help
+.Ar master
+.Sh DESCRIPTION
+.Nm ipropd-master
+is used to propagate changes to a Heimdal Kerberos database from the
+master Kerberos server on which it runs to slave Kerberos servers
+running
+.Nm ipropd-slave .
+.Pp
+The slaves are specified by the contents of the
+.Pa slaves
+file in the KDC's database directory, e.g.\&
+.Pa /var/heimdal/slaves .
+This has principals one per-line of the form
+.Dl iprop/ Ns Ar slave Ns @ Ns Ar REALM
+where
+.Ar slave
+is the hostname of the slave server in the given
+.Ar REALM ,
+e.g.\&
+.Dl iprop/kerberos-1.example.com@EXAMPLE.COM
+On a slave, the argument
+.Fa master
+specifies the hostname of the master server from which to receive updates.
+.Pp
+In contrast to
+.Xr hprop 8 ,
+which sends the whole database to the slaves regularly,
+.Nm
+normally sends only the changes as they happen on the master.
+The master keeps track of all the changes by assigning a version
+number to every transaction to the database.
+The slaves know which was the latest version they saw, and in this
+way it can be determined if they are in sync or not.
+A log of all the transactions is kept on the master.
+When a slave is at an older version than the oldest one in the log,
+the whole database has to be sent.
+.Pp
+The log of transactions is also used to implement a two-phase commit
+(with roll-forward for recovery) method of updating the HDB.
+Transactions are first recorded in the log, then in the HDB, then
+the log is updated to mark the transaction as committed.
+.Pp
+The changes are propagated over a secure channel (on port 2121 by
+default).
+This should normally be defined as
+.Dq iprop/tcp
+in
+.Pa /etc/services
+or another source of the services database.
+The master and slaves
+must each have access to a keytab with keys for the
+.Nm iprop
+service principal on the local host.
+.Pp
+There is a keep-alive feature logged in the master's
+.Pa slave-stats
+file (e.g.\&
+.Pa /var/heimdal/slave-stats ) .
+.Pp
+Note that hierarchical replication is supported by running
+an
+.Nm ipropd-master
+on the same KDC as an
+.Nm ipropd-slave .
+.Pp
+Supported options for
+.Nm ipropd-master :
+.Bl -tag -width Ds
+.It Fl c Ar string , Fl Fl config-file= Ns Ar string
+.It Fl r Ar string , Fl Fl realm= Ns Ar string
+.It Fl k Ar kspec , Fl Fl keytab= Ns Ar kspec
+Keytab for authenticating
+.Nm ipropd-slave
+clients.
+.It Fl d Ar file , Fl Fl database= Ns Ar file
+Database (default per KDC)
+.It Fl Fl slave-stats-file= Ns Ar file
+File for slave status information.
+.It Fl Fl time-missing= Ns Ar time
+Time before slave is polled for presence (default 2 min).
+.It Fl Fl time-gone= Ns Ar time
+Time of inactivity after which a slave is considered gone (default 5 min).
+.It Fl Fl detach
+Detach from console.
+.It Fl Fl version
+.It Fl Fl help
+.El
+.Pp
+Supported options for
+.Nm ipropd-slave :
+.Bl -tag -width Ds
+.It Fl c Ar string , Fl Fl config-file= Ns Ar string
+.It Fl r Ar string , Fl Fl realm= Ns Ar string
+.It Fl d Ar file , Fl Fl database= Ns Ar file
+Database (default per KDC)
+.It Fl k Ar kspec , Fl Fl keytab= Ns Ar kspec
+Keytab with client credentials for authenticating to
+.Nm ipropd-master .
+.It Fl Fl status-file= Ns Ar file
+.It Fl Fl hostname= Ns Ar hostname
+Hostname for client principal if different from actual hostname.
+.It Fl Fl port= Ns Ar port
+.It Fl Fl time-lost= Ns Ar time
+time before server is considered lost (default 5 min)
+.It Fl Fl async-hdb
+Use asynchronous writes.
+This is very useful for very busy sites or sites with very large
+HDBs.
+.It Fl Fl detach
+Detach from console.
+.It Fl Fl version
+.It Fl Fl help
+.El
+Time arguments for the relevant options above may be specified in forms
+like 5 min, 300 s, or simply a number of seconds.
+.Sh FILES
+.Pa slaves ,
+.Pa slave-stats
+in the database directory.
+.Pa ipropd-master.pid ,
+.Pa ipropd-slave.pid
+in the database directory, or in the directory named by the
+.Ev HEIM_PIDFILE_DIR
+environment variable.
+.Sh SEE ALSO
+.Xr krb5.conf 5 ,
+.Xr hprop 8 ,
+.Xr hpropd 8 ,
+.Xr iprop-log 8 ,
+.Xr kdc 8 .
diff --git a/third_party/heimdal/lib/kadm5/iprop.h b/third_party/heimdal/lib/kadm5/iprop.h
new file mode 100644
index 0000000..945fb90
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/iprop.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 1998-2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __IPROP_H__
+#define __IPROP_H__
+
+#include "kadm5_locl.h"
+#include <getarg.h>
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif
+#ifdef HAVE_UTIL_H
+#include <util.h>
+#endif
+
+#include <parse_time.h>
+
+#define IPROP_VERSION "iprop-0.0"
+
+#define IPROP_NAME "iprop"
+
+#define IPROP_SERVICE "iprop"
+
+#define IPROP_PORT 2121
+
+enum iprop_cmd { I_HAVE = 1,
+ FOR_YOU = 2,
+ TELL_YOU_EVERYTHING = 3,
+ ONE_PRINC = 4,
+ NOW_YOU_HAVE = 5,
+ ARE_YOU_THERE = 6,
+ I_AM_HERE = 7,
+ YOU_HAVE_LAST_VERSION = 8
+};
+
+extern sig_atomic_t exit_flag;
+void setup_signal(void);
+
+enum ipropd_exit_code {
+ IPROPD_DONE = 0,
+ IPROPD_RESTART = 1,
+ IPROPD_RESTART_SLOW = 2,
+ IPROPD_FATAL = 3,
+};
+
+int restarter(krb5_context, size_t *);
+
+#endif /* __IPROP_H__ */
diff --git a/third_party/heimdal/lib/kadm5/ipropd-master-version.rc b/third_party/heimdal/lib/kadm5/ipropd-master-version.rc
new file mode 100644
index 0000000..f51a891
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/ipropd-master-version.rc
@@ -0,0 +1,36 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#define RC_FILE_TYPE VFT_APP
+#define RC_FILE_DESC_0409 "IProp Master"
+#define RC_FILE_ORIG_0409 "ipropd-master.exe"
+
+#include "../../windows/version.rc"
diff --git a/third_party/heimdal/lib/kadm5/ipropd-slave-version.rc b/third_party/heimdal/lib/kadm5/ipropd-slave-version.rc
new file mode 100644
index 0000000..a1cee87
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/ipropd-slave-version.rc
@@ -0,0 +1,36 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#define RC_FILE_TYPE VFT_APP
+#define RC_FILE_DESC_0409 "IProp Slave"
+#define RC_FILE_ORIG_0409 "ipropd-slave.exe"
+
+#include "../../windows/version.rc"
diff --git a/third_party/heimdal/lib/kadm5/ipropd_common.c b/third_party/heimdal/lib/kadm5/ipropd_common.c
new file mode 100644
index 0000000..1decfe3
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/ipropd_common.c
@@ -0,0 +1,266 @@
+/*
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "iprop.h"
+
+#if defined(HAVE_FORK) && defined(HAVE_WAITPID)
+#include <sys/types.h>
+#include <sys/wait.h>
+#endif
+
+sig_atomic_t exit_flag;
+
+static RETSIGTYPE
+sigterm(int sig)
+{
+ exit_flag = sig;
+}
+
+void
+setup_signal(void)
+{
+#ifdef HAVE_SIGACTION
+ {
+ struct sigaction sa;
+
+ memset(&sa, 0, sizeof(sa));
+ sa.sa_flags = 0;
+ sa.sa_handler = sigterm;
+ sigemptyset(&sa.sa_mask);
+
+ sigaction(SIGINT, &sa, NULL);
+ sigaction(SIGTERM, &sa, NULL);
+ sigaction(SIGXCPU, &sa, NULL);
+
+ sa.sa_handler = SIG_IGN;
+ sigaction(SIGPIPE, &sa, NULL);
+ }
+#else
+ signal(SIGINT, sigterm);
+ signal(SIGTERM, sigterm);
+#ifndef NO_SIGXCPU
+ signal(SIGXCPU, sigterm);
+#endif
+#ifndef NO_SIGPIPE
+ signal(SIGPIPE, SIG_IGN);
+#endif
+#endif
+}
+
+/*
+ * Fork a child to run the service, and restart it if it dies.
+ *
+ * Returns -1 if not supported, else a file descriptor that the service
+ * should select() for. Any events on that file descriptor should cause
+ * the caller to exit immediately, as that means that the restarter
+ * exited.
+ *
+ * The service's normal exit status values should be should be taken
+ * from enum ipropd_exit_code. IPROPD_FATAL causes the restarter to
+ * stop restarting the service and to exit.
+ *
+ * A count of restarts is output via the `countp' argument, if it is
+ * non-NULL. This is useful for testing this function (e.g., kill the
+ * restarter after N restarts and check that the child gets the signal
+ * sent to it).
+ *
+ * This requires fork() and waitpid() (otherwise returns -1). Ignoring
+ * SIGCHLD, of course, would be bad.
+ *
+ * We could support this on Windows by spawning a child with mostly the
+ * same arguments as the restarter process.
+ */
+int
+restarter(krb5_context context, size_t *countp)
+{
+#if defined(HAVE_FORK) && defined(HAVE_WAITPID)
+ struct timeval tmout;
+ pid_t pid = -1;
+ pid_t wpid = -1;
+ int status;
+ int fds[2];
+ int fds2[2];
+ size_t count = 0;
+ fd_set readset;
+
+ fds[0] = -1;
+ fds[1] = -1;
+ fds2[0] = -1;
+ fds2[1] = -1;
+
+ signal(SIGCHLD, SIG_DFL);
+
+ while (!exit_flag) {
+ /* Close the pipe ends we keep open */
+ if (fds[1] != -1)
+ (void) close(fds[1]);
+ if (fds2[0] != -1)
+ (void) close(fds2[1]);
+
+ /* A pipe so the child can detect the parent's death */
+ if (pipe(fds) == -1) {
+ krb5_err(context, 1, errno,
+ "Could not setup pipes in service restarter");
+ }
+
+ /* A pipe so the parent can detect the child's death */
+ if (pipe(fds2) == -1) {
+ krb5_err(context, 1, errno,
+ "Could not setup pipes in service restarter");
+ }
+
+ fflush(stdout);
+ fflush(stderr);
+
+ pid = fork();
+ if (pid == -1)
+ krb5_err(context, 1, errno, "Could not fork in service restarter");
+ if (pid == 0) {
+ if (countp != NULL)
+ *countp = count;
+ (void) close(fds[1]);
+ (void) close(fds2[0]);
+ return fds[0];
+ }
+
+ count++;
+
+ (void) close(fds[0]);
+ (void) close(fds2[1]);
+
+ do {
+ wpid = waitpid(pid, &status, 0);
+ } while (wpid == -1 && errno == EINTR && !exit_flag);
+ if (wpid == -1 && errno == EINTR)
+ break; /* We were signaled; gotta kill the child and exit */
+ if (wpid == -1) {
+ if (errno != ECHILD) {
+ warn("waitpid() failed; killing restarter's child process");
+ kill(pid, SIGTERM);
+ }
+ krb5_err(context, 1, errno, "restarter failed waiting for child");
+ }
+
+ assert(wpid == pid);
+ wpid = -1;
+ pid = -1;
+ if (WIFEXITED(status)) {
+ switch (WEXITSTATUS(status)) {
+ case IPROPD_DONE:
+ exit(0);
+ case IPROPD_RESTART_SLOW:
+ if (exit_flag)
+ exit(1);
+ krb5_warnx(context, "Waiting 2 minutes to restart");
+ sleep(120);
+ continue;
+ case IPROPD_FATAL:
+ krb5_errx(context, WEXITSTATUS(status),
+ "Sockets and pipes not supported for "
+ "iprop log files");
+ case IPROPD_RESTART:
+ default:
+ if (exit_flag)
+ exit(1);
+ /* Add exponential backoff (with max backoff)? */
+ krb5_warnx(context, "Waiting 30 seconds to restart");
+ sleep(30);
+ continue;
+ }
+ }
+ /* else */
+ krb5_warnx(context, "Child was killed; waiting 30 seconds to restart");
+ sleep(30);
+ }
+
+ if (pid == -1)
+ exit(0); /* No dead child to reap; done */
+
+ assert(pid > 0);
+ if (wpid != pid) {
+ warnx("Interrupted; killing child (pid %ld) with %d",
+ (long)pid, exit_flag);
+ krb5_warnx(context, "Interrupted; killing child (pid %ld) with %d",
+ (long)pid, exit_flag);
+ kill(pid, exit_flag);
+
+ /* Wait up to one second for the child */
+ tmout.tv_sec = 1;
+ tmout.tv_usec = 0;
+ FD_ZERO(&readset);
+ FD_SET(fds2[0], &readset);
+ /* We don't care why select() returns */
+ (void) select(fds2[0] + 1, &readset, NULL, NULL, &tmout);
+ /*
+ * We haven't reaped the child yet; if it's a zombie, then
+ * SIGKILLing it won't hurt. If it's not a zombie yet, well,
+ * we're out of patience.
+ */
+ kill(pid, SIGKILL);
+ do {
+ wpid = waitpid(pid, &status, 0);
+ } while (wpid != pid && errno == EINTR);
+ if (wpid == -1)
+ krb5_err(context, 1, errno, "restarter failed waiting for child");
+ }
+
+ /* Finally, the child is dead and reaped */
+ if (WIFEXITED(status))
+ exit(WEXITSTATUS(status));
+ if (WIFSIGNALED(status)) {
+ switch (WTERMSIG(status)) {
+ case SIGTERM:
+ case SIGXCPU:
+ case SIGINT:
+ exit(0);
+ default:
+ /*
+ * Attempt to set the same exit status for the parent as for
+ * the child.
+ */
+ kill(getpid(), WTERMSIG(status));
+ /*
+ * We can get past the self-kill if we inherited a SIG_IGN
+ * disposition that the child reset to SIG_DFL.
+ */
+ }
+ }
+ exit(1);
+#else
+ if (countp != NULL)
+ *countp = 0;
+ errno = ENOTSUP;
+ return -1;
+#endif
+}
+
diff --git a/third_party/heimdal/lib/kadm5/ipropd_master.c b/third_party/heimdal/lib/kadm5/ipropd_master.c
new file mode 100644
index 0000000..b3f7d81
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/ipropd_master.c
@@ -0,0 +1,1877 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "iprop.h"
+#include <rtbl.h>
+
+static krb5_log_facility *log_facility;
+
+static int verbose;
+
+static const char *slave_stats_file;
+static const char *slave_stats_temp_file;
+static const char *slave_time_missing = "2 min";
+static const char *slave_time_gone = "5 min";
+
+static int time_before_missing;
+static int time_before_gone;
+
+const char *master_hostname;
+const char *pidfile_basename;
+
+static krb5_socket_t
+make_signal_socket (krb5_context context)
+{
+#ifndef NO_UNIX_SOCKETS
+ struct sockaddr_un addr;
+ const char *fn;
+ krb5_socket_t fd;
+
+ fn = kadm5_log_signal_socket(context);
+
+ fd = socket (AF_UNIX, SOCK_DGRAM, 0);
+ if (fd < 0)
+ krb5_err (context, 1, errno, "socket AF_UNIX");
+ memset (&addr, 0, sizeof(addr));
+ addr.sun_family = AF_UNIX;
+ strlcpy (addr.sun_path, fn, sizeof(addr.sun_path));
+ unlink (addr.sun_path);
+ if (bind (fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
+ krb5_err (context, 1, errno, "bind %s", addr.sun_path);
+ return fd;
+#else
+ struct addrinfo *ai = NULL;
+ krb5_socket_t fd;
+
+ kadm5_log_signal_socket_info(context, 1, &ai);
+
+ fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
+ if (rk_IS_BAD_SOCKET(fd))
+ krb5_err (context, 1, rk_SOCK_ERRNO, "socket AF=%d", ai->ai_family);
+
+ if (rk_IS_SOCKET_ERROR( bind (fd, ai->ai_addr, ai->ai_addrlen) ))
+ krb5_err (context, 1, rk_SOCK_ERRNO, "bind");
+ return fd;
+#endif
+}
+
+static krb5_socket_t
+make_listen_socket (krb5_context context, const char *port_str)
+{
+ krb5_socket_t fd;
+ int one = 1;
+ struct sockaddr_in addr;
+
+ fd = socket (AF_INET, SOCK_STREAM, 0);
+ if (rk_IS_BAD_SOCKET(fd))
+ krb5_err (context, 1, rk_SOCK_ERRNO, "socket AF_INET");
+ (void) setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof(one));
+ memset (&addr, 0, sizeof(addr));
+ addr.sin_family = AF_INET;
+
+ if (port_str) {
+ addr.sin_port = krb5_getportbyname (context,
+ port_str, "tcp",
+ 0);
+ if (addr.sin_port == 0) {
+ char *ptr;
+ long port;
+
+ port = strtol (port_str, &ptr, 10);
+ if (port == 0 && ptr == port_str)
+ krb5_errx (context, 1, "bad port `%s'", port_str);
+ addr.sin_port = htons(port);
+ }
+ } else {
+ addr.sin_port = krb5_getportbyname (context, IPROP_SERVICE,
+ "tcp", IPROP_PORT);
+ }
+ if(bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
+ krb5_err (context, 1, errno, "bind");
+ if (listen(fd, SOMAXCONN) < 0)
+ krb5_err (context, 1, errno, "listen");
+ return fd;
+}
+
+
+struct slave {
+ krb5_socket_t fd;
+ struct sockaddr_in addr;
+ char *name;
+ krb5_auth_context ac;
+ uint32_t version;
+ uint32_t version_tstamp;
+ uint32_t version_ack;
+ time_t seen;
+ unsigned long flags;
+#define SLAVE_F_DEAD 0x1
+#define SLAVE_F_AYT 0x2
+#define SLAVE_F_READY 0x4
+ /*
+ * We'll use non-blocking I/O so no slave can hold us back.
+ *
+ * We call the state left over from a partial write a "tail".
+ *
+ * The krb5_data holding an KRB-PRIV will be the write buffer.
+ */
+ struct {
+ /* Every message we send is a KRB-PRIV with a 4-byte length prefixed */
+ uint8_t header_buf[4];
+ krb5_data header;
+ krb5_data packet;
+ size_t packet_off;
+ /* For send_complete() we need an sp as part of the tail */
+ krb5_storage *dump;
+ uint32_t vno;
+ } tail;
+ struct {
+ uint8_t header_buf[4];
+ krb5_data packet;
+ size_t offset;
+ int hlen;
+ } input;
+ /*
+ * Continuation for fair diff sending we send N entries at a time.
+ */
+ struct {
+ off_t off_next_version; /* offset in log of next diff */
+ uint32_t initial_version; /* at time of previous diff */
+ uint32_t initial_tstamp; /* at time of previous diff */
+ uint32_t last_version_sent;
+ int more; /* need to send more diffs */
+ } next_diff;
+ struct slave *next;
+};
+
+typedef struct slave slave;
+
+static int
+check_acl (krb5_context context, const char *name)
+{
+ const char *fn;
+ FILE *fp;
+ char buf[256];
+ int ret = 1;
+ char *slavefile = NULL;
+
+ if (asprintf(&slavefile, "%s/slaves", hdb_db_dir(context)) == -1
+ || slavefile == NULL)
+ errx(1, "out of memory");
+
+ fn = krb5_config_get_string_default(context,
+ NULL,
+ slavefile,
+ "kdc",
+ "iprop-acl",
+ NULL);
+
+ fp = fopen (fn, "r");
+ free(slavefile);
+ if (fp == NULL)
+ return 1;
+ while (fgets(buf, sizeof(buf), fp) != NULL) {
+ buf[strcspn(buf, "\r\n")] = '\0';
+ if (strcmp (buf, name) == 0) {
+ ret = 0;
+ break;
+ }
+ }
+ fclose (fp);
+ return ret;
+}
+
+static void
+slave_seen(slave *s)
+{
+ s->flags &= ~SLAVE_F_AYT;
+ s->seen = time(NULL);
+}
+
+static int
+slave_missing_p (slave *s)
+{
+ if (time(NULL) > s->seen + time_before_missing)
+ return 1;
+ return 0;
+}
+
+static int
+slave_gone_p (slave *s)
+{
+ if (time(NULL) > s->seen + time_before_gone)
+ return 1;
+ return 0;
+}
+
+static void
+slave_dead(krb5_context context, slave *s)
+{
+ krb5_warnx(context, "slave %s dead", s->name);
+
+ if (!rk_IS_BAD_SOCKET(s->fd)) {
+ rk_closesocket (s->fd);
+ s->fd = rk_INVALID_SOCKET;
+ }
+ s->flags |= SLAVE_F_DEAD;
+ slave_seen(s);
+}
+
+static void
+remove_slave (krb5_context context, slave *s, slave **root)
+{
+ slave **p;
+
+ if (!rk_IS_BAD_SOCKET(s->fd))
+ rk_closesocket (s->fd);
+ if (s->name)
+ free (s->name);
+ if (s->ac)
+ krb5_auth_con_free (context, s->ac);
+
+ /* Free any pending input/output state */
+ krb5_data_free(&s->input.packet);
+ krb5_data_free(&s->tail.packet);
+ krb5_storage_free(s->tail.dump);
+
+ for (p = root; *p; p = &(*p)->next)
+ if (*p == s) {
+ *p = s->next;
+ break;
+ }
+ free (s);
+}
+
+static void
+add_slave (krb5_context context, krb5_keytab keytab, slave **root,
+ krb5_socket_t fd)
+{
+ krb5_principal server;
+ krb5_error_code ret;
+ slave *s;
+ socklen_t addr_len;
+ krb5_ticket *ticket = NULL;
+ char hostname[128];
+
+ s = calloc(1, sizeof(*s));
+ if (s == NULL) {
+ krb5_warnx (context, "add_slave: no memory");
+ return;
+ }
+ s->name = NULL;
+ s->ac = NULL;
+ s->input.packet.data = NULL;
+ s->tail.header.data = NULL;
+ s->tail.packet.data = NULL;
+ s->tail.dump = NULL;
+
+ addr_len = sizeof(s->addr);
+ s->fd = accept (fd, (struct sockaddr *)&s->addr, &addr_len);
+ if (rk_IS_BAD_SOCKET(s->fd)) {
+ krb5_warn (context, rk_SOCK_ERRNO, "accept");
+ goto error;
+ }
+
+ if (master_hostname)
+ strlcpy(hostname, master_hostname, sizeof(hostname));
+ else
+ gethostname(hostname, sizeof(hostname));
+
+ ret = krb5_sname_to_principal (context, hostname, IPROP_NAME,
+ KRB5_NT_SRV_HST, &server);
+ if (ret) {
+ krb5_warn (context, ret, "krb5_sname_to_principal");
+ goto error;
+ }
+
+ ret = krb5_recvauth (context, &s->ac, &s->fd,
+ IPROP_VERSION, server, 0, keytab, &ticket);
+
+ /*
+ * We'll be doing non-blocking I/O only after authentication. We don't
+ * want to get stuck talking to any one slave.
+ *
+ * If we get a partial write, we'll finish writing when the socket becomes
+ * writable.
+ *
+ * Partial reads will be treated as EOF, causing the slave to be marked
+ * dead.
+ *
+ * To do non-blocking I/O for authentication we'll have to implement our
+ * own krb5_recvauth().
+ */
+ socket_set_nonblocking(s->fd, 1);
+
+ /*
+ * We write message lengths separately from the payload, and may do
+ * back-to-back small writes when flushing pending input and then a new
+ * update. Avoid Nagle delays.
+ */
+#if defined(IPPROTO_TCP) && defined(TCP_NODELAY)
+ {
+ int nodelay = 1;
+ (void) setsockopt(s->fd, IPPROTO_TCP, TCP_NODELAY,
+ (void *)&nodelay, sizeof(nodelay));
+ }
+#endif
+
+ krb5_free_principal (context, server);
+ if (ret) {
+ krb5_warn (context, ret, "krb5_recvauth");
+ goto error;
+ }
+ ret = krb5_unparse_name (context, ticket->client, &s->name);
+ krb5_free_ticket (context, ticket);
+ if (ret) {
+ krb5_warn (context, ret, "krb5_unparse_name");
+ goto error;
+ }
+ if (check_acl (context, s->name)) {
+ krb5_warnx (context, "%s not in acl", s->name);
+ goto error;
+ }
+
+ {
+ slave *l = *root;
+
+ while (l) {
+ if (strcmp(l->name, s->name) == 0)
+ break;
+ l = l->next;
+ }
+ if (l) {
+ if (l->flags & SLAVE_F_DEAD) {
+ remove_slave(context, l, root);
+ } else {
+ krb5_warnx (context, "second connection from %s", s->name);
+ goto error;
+ }
+ }
+ }
+
+ krb5_warnx (context, "connection from %s", s->name);
+
+ s->version = 0;
+ s->version_ack = 0;
+ s->flags = 0;
+ slave_seen(s);
+ s->next = *root;
+ *root = s;
+ return;
+error:
+ remove_slave(context, s, root);
+}
+
+static int
+dump_one (krb5_context context, HDB *db, hdb_entry *entry, void *v)
+{
+ krb5_error_code ret;
+ krb5_storage *dump = (krb5_storage *)v;
+ krb5_storage *sp;
+ krb5_data data;
+
+ ret = hdb_entry2value (context, entry, &data);
+ if (ret)
+ return ret;
+ ret = krb5_data_realloc (&data, data.length + 4);
+ if (ret)
+ goto done;
+ memmove ((char *)data.data + 4, data.data, data.length - 4);
+ sp = krb5_storage_from_data(&data);
+ if (sp == NULL) {
+ ret = krb5_enomem(context);
+ goto done;
+ }
+ ret = krb5_store_uint32(sp, ONE_PRINC);
+ krb5_storage_free(sp);
+
+ if (ret == 0)
+ ret = krb5_store_data(dump, data);
+
+done:
+ krb5_data_free (&data);
+ return ret;
+}
+
+static int
+write_dump (krb5_context context, krb5_storage *dump,
+ const char *database, uint32_t current_version)
+{
+ krb5_error_code ret;
+ krb5_storage *sp;
+ HDB *db;
+ krb5_data data;
+ char buf[8];
+
+ /* we assume that the caller has obtained an exclusive lock */
+
+ ret = krb5_storage_truncate(dump, 0);
+ if (ret)
+ return ret;
+
+ if (krb5_storage_seek(dump, 0, SEEK_SET) != 0)
+ return errno;
+
+ /*
+ * First we store zero as the HDB version, this will indicate to a
+ * later reader that the dumpfile is invalid. We later write the
+ * correct version in the file after we have written all of the
+ * messages. A dump with a zero version will not be considered
+ * to be valid.
+ */
+
+ ret = krb5_store_uint32(dump, 0);
+ if (ret)
+ return ret;
+
+ ret = hdb_create (context, &db, database);
+ if (ret)
+ krb5_err (context, IPROPD_RESTART, ret, "hdb_create: %s", database);
+ ret = db->hdb_open (context, db, O_RDONLY, 0);
+ if (ret)
+ krb5_err (context, IPROPD_RESTART, ret, "db->open");
+
+ sp = krb5_storage_from_mem (buf, 4);
+ if (sp == NULL)
+ krb5_errx (context, IPROPD_RESTART, "krb5_storage_from_mem");
+ krb5_store_uint32 (sp, TELL_YOU_EVERYTHING);
+ krb5_storage_free (sp);
+
+ data.data = buf;
+ data.length = 4;
+
+ ret = krb5_store_data(dump, data);
+ if (ret) {
+ krb5_warn (context, ret, "write_dump");
+ return ret;
+ }
+
+ ret = hdb_foreach (context, db, HDB_F_ADMIN_DATA, dump_one, dump);
+ if (ret) {
+ krb5_warn (context, ret, "write_dump: hdb_foreach");
+ return ret;
+ }
+
+ (*db->hdb_close)(context, db);
+ (*db->hdb_destroy)(context, db);
+
+ sp = krb5_storage_from_mem (buf, 8);
+ if (sp == NULL)
+ krb5_errx (context, IPROPD_RESTART, "krb5_storage_from_mem");
+ ret = krb5_store_uint32(sp, NOW_YOU_HAVE);
+ if (ret == 0)
+ krb5_store_uint32(sp, current_version);
+ krb5_storage_free (sp);
+
+ data.length = 8;
+
+ if (ret == 0)
+ ret = krb5_store_data(dump, data);
+
+ /*
+ * We must ensure that the entire valid dump is written to disk
+ * before we write the current version at the front thus making
+ * it a valid dump file. If we crash around here, this can be
+ * important upon reboot.
+ */
+
+ if (ret == 0)
+ ret = krb5_storage_fsync(dump);
+
+ if (ret == 0 && krb5_storage_seek(dump, 0, SEEK_SET) == -1)
+ ret = errno;
+
+ /* Write current version at the front making the dump valid */
+
+ if (ret == 0)
+ ret = krb5_store_uint32(dump, current_version);
+
+ /*
+ * We don't need to fsync(2) after the real version is written as
+ * it is not a disaster if it doesn't make it to disk if we crash.
+ * After all, we'll just create a new dumpfile.
+ */
+
+ if (ret == 0)
+ krb5_warnx(context, "wrote new dumpfile (version %u)",
+ current_version);
+ else
+ krb5_warn(context, ret, "failed to write new dumpfile (version %u)",
+ current_version);
+
+ return ret;
+}
+
+static int
+mk_priv_tail(krb5_context context, slave *s, krb5_data *data)
+{
+ uint32_t len;
+ int ret;
+
+ ret = krb5_mk_priv(context, s->ac, data, &s->tail.packet, NULL);
+ if (ret)
+ return ret;
+
+ len = s->tail.packet.length;
+ _krb5_put_int(s->tail.header_buf, len, sizeof(s->tail.header_buf));
+ s->tail.header.length = sizeof(s->tail.header_buf);
+ s->tail.header.data = s->tail.header_buf;
+ return 0;
+}
+
+static int
+have_tail(slave *s)
+{
+ return s->tail.header.length || s->tail.packet.length || s->tail.dump;
+}
+
+static int
+more_diffs(slave *s)
+{
+ return s->next_diff.more;
+}
+
+#define SEND_COMPLETE_MAX_RECORDS 50
+#define SEND_DIFFS_MAX_RECORDS 50
+
+static int
+send_tail(krb5_context context, slave *s)
+{
+ krb5_data data;
+ ssize_t bytes = 0;
+ size_t rem = 0;
+ size_t n;
+ int ret;
+
+ if (! have_tail(s))
+ return 0;
+
+ /*
+ * For the case where we're continuing a send_complete() send up to
+ * SEND_COMPLETE_MAX_RECORDS records now, and the rest asynchronously
+ * later. This ensures that sending a complete dump to a slow-to-drain
+ * client does not prevent others from getting serviced.
+ */
+ for (n = 0; n < SEND_COMPLETE_MAX_RECORDS; n++) {
+ if (! have_tail(s))
+ return 0;
+
+ if (s->tail.header.length) {
+ bytes = krb5_net_write(context, &s->fd,
+ s->tail.header.data,
+ s->tail.header.length);
+ if (bytes < 0)
+ goto err;
+
+ s->tail.header.length -= bytes;
+ s->tail.header.data = (char *)s->tail.header.data + bytes;
+ rem = s->tail.header.length;
+ if (rem)
+ goto ewouldblock;
+ }
+
+ if (s->tail.packet.length) {
+ bytes = krb5_net_write(context, &s->fd,
+ (char *)s->tail.packet.data + s->tail.packet_off,
+ s->tail.packet.length - s->tail.packet_off);
+ if (bytes < 0)
+ goto err;
+ s->tail.packet_off += bytes;
+ if (bytes)
+ slave_seen(s);
+ rem = s->tail.packet.length - s->tail.packet_off;
+ if (rem)
+ goto ewouldblock;
+
+ krb5_data_free(&s->tail.packet);
+ s->tail.packet_off = 0;
+ }
+
+ if (s->tail.dump == NULL)
+ return 0;
+
+ /*
+ * We're in the middle of a send_complete() that was interrupted by
+ * EWOULDBLOCK. Continue the sending of the dump.
+ */
+ ret = krb5_ret_data(s->tail.dump, &data);
+ if (ret == HEIM_ERR_EOF) {
+ krb5_storage_free(s->tail.dump);
+ s->tail.dump = NULL;
+ s->version = s->tail.vno;
+ return 0;
+ }
+
+ if (ret) {
+ krb5_warn(context, ret, "failed to read entry from dump!");
+ } else {
+ ret = mk_priv_tail(context, s, &data);
+ krb5_data_free(&data);
+ if (ret == 0)
+ continue;
+ krb5_warn(context, ret, "failed to make and send a KRB-PRIV to %s",
+ s->name);
+ }
+
+ slave_dead(context, s);
+ return ret;
+ }
+
+ if (ret == 0 && s->tail.dump != NULL)
+ return EWOULDBLOCK;
+
+err:
+ if (errno != EAGAIN && errno != EWOULDBLOCK) {
+ krb5_warn(context, ret = errno,
+ "error sending diffs to now-dead slave %s", s->name);
+ slave_dead(context, s);
+ return ret;
+ }
+
+ewouldblock:
+ if (verbose)
+ krb5_warnx(context, "would block writing %llu bytes to slave %s",
+ (unsigned long long)rem, s->name);
+ return EWOULDBLOCK;
+}
+
+static int
+send_complete(krb5_context context, slave *s, const char *database,
+ uint32_t current_version, uint32_t oldest_version,
+ uint32_t initial_log_tstamp)
+{
+ krb5_error_code ret;
+ krb5_storage *dump = NULL;
+ uint32_t vno = 0;
+ int fd = -1;
+ struct stat st;
+ char *dfn;
+
+ ret = asprintf(&dfn, "%s/ipropd.dumpfile", hdb_db_dir(context));
+ if (ret == -1 || !dfn)
+ return krb5_enomem(context);
+
+ fd = open(dfn, O_CREAT|O_RDWR, 0600);
+ if (fd == -1) {
+ ret = errno;
+ krb5_warn(context, ret, "Cannot open/create iprop dumpfile %s", dfn);
+ free(dfn);
+ return ret;
+ }
+ free(dfn);
+
+ dump = krb5_storage_from_fd(fd);
+ if (!dump) {
+ ret = errno;
+ krb5_warn(context, ret, "krb5_storage_from_fd");
+ goto done;
+ }
+
+ for (;;) {
+ ret = flock(fd, LOCK_SH);
+ if (ret == -1) {
+ ret = errno;
+ krb5_warn(context, ret, "flock(fd, LOCK_SH)");
+ goto done;
+ }
+
+ if (krb5_storage_seek(dump, 0, SEEK_SET) == (off_t)-1) {
+ ret = errno;
+ krb5_warn(context, ret, "krb5_storage_seek(dump, 0, SEEK_SET)");
+ goto done;
+ }
+
+ vno = 0;
+ ret = krb5_ret_uint32(dump, &vno);
+ if (ret && ret != HEIM_ERR_EOF) {
+ krb5_warn(context, ret, "krb5_ret_uint32(dump, &vno)");
+ goto done;
+ }
+
+ if (fstat(fd, &st) == -1) {
+ ret = errno;
+ krb5_warn(context, ret, "send_complete: could not stat dump file");
+ goto done;
+ }
+
+ /*
+ * If the current dump has an appropriate version, then we can
+ * break out of the loop and send the file below.
+ */
+ if (ret == 0 && vno != 0 && st.st_mtime > initial_log_tstamp &&
+ vno >= oldest_version && vno <= current_version)
+ break;
+
+ if (verbose)
+ krb5_warnx(context, "send_complete: dumping HDB");
+
+ /*
+ * Otherwise, we may need to write a new dump file. We
+ * obtain an exclusive lock on the fd. Because this is
+ * not guaranteed to be an upgrade of our existing shared
+ * lock, someone else may have written a new dumpfile while
+ * we were waiting and so we must first check the vno of
+ * the dump to see if that happened. If it did, we need
+ * to go back to the top of the loop so that we can downgrade
+ * our lock to a shared one.
+ */
+
+ ret = flock(fd, LOCK_EX);
+ if (ret == -1) {
+ ret = errno;
+ krb5_warn(context, ret, "flock(fd, LOCK_EX)");
+ goto done;
+ }
+
+ ret = krb5_storage_seek(dump, 0, SEEK_SET);
+ if (ret == -1) {
+ ret = errno;
+ krb5_warn(context, ret, "krb5_storage_seek(dump, 0, SEEK_SET)");
+ goto done;
+ }
+
+ vno = 0;
+ ret = krb5_ret_uint32(dump, &vno);
+ if (ret && ret != HEIM_ERR_EOF) {
+ krb5_warn(context, ret, "krb5_ret_uint32(dump, &vno)");
+ goto done;
+ }
+
+ if (fstat(fd, &st) == -1) {
+ ret = errno;
+ krb5_warn(context, ret, "send_complete: could not stat dump file");
+ goto done;
+ }
+
+ /* check if someone wrote a better version for us */
+ if (ret == 0 && vno != 0 && st.st_mtime > initial_log_tstamp &&
+ vno >= oldest_version && vno <= current_version)
+ continue;
+
+ /* Now, we know that we must write a new dump file. */
+
+ ret = write_dump(context, dump, database, current_version);
+ if (ret)
+ goto done;
+
+ /*
+ * And we must continue to the top of the loop so that we can
+ * downgrade to a shared lock.
+ */
+ }
+
+ /*
+ * Leaving the above loop, dump should have a ptr right after the initial
+ * 4 byte DB version number and we should have a shared lock on the file
+ * (which we may have just created), so we are reading to start sending
+ * the data down the wire.
+ *
+ * Note: (krb5_storage_from_fd() dup()'s the fd)
+ */
+
+ s->tail.dump = dump;
+ s->tail.vno = vno;
+ dump = NULL;
+ ret = send_tail(context, s);
+
+done:
+ if (fd != -1)
+ close(fd);
+ if (dump)
+ krb5_storage_free(dump);
+ return ret;
+}
+
+static int
+send_are_you_there (krb5_context context, slave *s)
+{
+ krb5_storage *sp;
+ krb5_data data;
+ char buf[4];
+ int ret;
+
+ if (s->flags & (SLAVE_F_DEAD|SLAVE_F_AYT))
+ return 0;
+
+ /*
+ * Write any remainder of previous write, if we can. If we'd block we'll
+ * return EWOULDBLOCK.
+ */
+ ret = send_tail(context, s);
+ if (ret)
+ return ret;
+
+ krb5_warnx(context, "slave %s missing, sending AYT", s->name);
+
+ s->flags |= SLAVE_F_AYT;
+
+ data.data = buf;
+ data.length = 4;
+
+ sp = krb5_storage_from_mem (buf, 4);
+ if (sp == NULL) {
+ krb5_warnx (context, "are_you_there: krb5_data_alloc");
+ slave_dead(context, s);
+ return ENOMEM;
+ }
+ ret = krb5_store_uint32(sp, ARE_YOU_THERE);
+ krb5_storage_free (sp);
+
+ if (ret == 0)
+ ret = mk_priv_tail(context, s, &data);
+ if (ret == 0)
+ ret = send_tail(context, s);
+ if (ret && ret != EWOULDBLOCK) {
+ krb5_warn(context, ret, "are_you_there");
+ slave_dead(context, s);
+ }
+ return ret;
+}
+
+static int
+diffready(krb5_context context, slave *s)
+{
+ /*
+ * Don't send any diffs until slave has sent an I_HAVE telling us the
+ * initial version number!
+ */
+ if ((s->flags & SLAVE_F_READY) == 0)
+ return 0;
+
+ if (s->flags & SLAVE_F_DEAD) {
+ if (verbose)
+ krb5_warnx(context, "not sending diffs to dead slave %s", s->name);
+ return 0;
+ }
+
+ /* Write any remainder of previous write, if we can. */
+ if (send_tail(context, s) != 0)
+ return 0;
+
+ return 1;
+}
+
+static int
+nodiffs(krb5_context context, slave *s, uint32_t current_version)
+{
+ krb5_storage *sp;
+ krb5_data data;
+ int ret;
+
+ if (s->version < current_version)
+ return 0;
+
+ /*
+ * If we had sent a partial diff, and now they're caught up, then there's
+ * no more.
+ */
+ s->next_diff.more = 0;
+
+ if (verbose)
+ krb5_warnx(context, "slave %s version %ld already sent", s->name,
+ (long)s->version);
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ krb5_errx(context, IPROPD_RESTART, "krb5_storage_from_mem");
+
+ ret = krb5_store_uint32(sp, YOU_HAVE_LAST_VERSION);
+ if (ret == 0) {
+ krb5_data_zero(&data);
+ ret = krb5_storage_to_data(sp, &data);
+ }
+ krb5_storage_free(sp);
+ if (ret == 0) {
+ ret = mk_priv_tail(context, s, &data);
+ krb5_data_free(&data);
+ }
+ if (ret == 0)
+ send_tail(context, s);
+
+ return 1;
+}
+
+/*
+ * Lock the log and return initial version and timestamp
+ */
+static int
+get_first(kadm5_server_context *server_context, int log_fd,
+ uint32_t *initial_verp, uint32_t *initial_timep)
+{
+ krb5_context context = server_context->context;
+ int ret;
+
+ /*
+ * We don't want to perform tight retry loops on log access errors, so on
+ * error mark the slave dead. The slave reconnect after a delay...
+ */
+ if (flock(log_fd, LOCK_SH) == -1) {
+ krb5_warn(context, errno, "could not obtain shared lock on log file");
+ return -1;
+ }
+
+ ret = kadm5_log_get_version_fd(server_context, log_fd, LOG_VERSION_FIRST,
+ initial_verp, initial_timep);
+ if (ret == HEIM_ERR_EOF)
+ ret = kadm5_log_get_version_fd(server_context, log_fd,
+ LOG_VERSION_UBER, initial_verp,
+ initial_timep);
+ if (ret != 0) {
+ flock(log_fd, LOCK_UN);
+ krb5_warn(context, ret, "could not read initial log entry");
+ return -1;
+ }
+
+ return 0;
+}
+
+/*-
+ * Find the left end of the diffs in the log we want to send.
+ *
+ * - On success, return a positive offset to the first new entry, retaining
+ * a read lock on the log file.
+ * - On error, return a negative offset, with the lock released.
+ * - If we simply find no successor entry in the log, return zero
+ * with the lock released, which indicates that fallback to send_complete()
+ * is needed.
+ */
+static off_t
+get_left(kadm5_server_context *server_context, slave *s, krb5_storage *sp,
+ int log_fd, uint32_t current_version,
+ uint32_t *initial_verp, uint32_t *initial_timep)
+{
+ krb5_context context = server_context->context;
+ off_t pos;
+ off_t left;
+ int ret;
+
+ for (;;) {
+ uint32_t ver = s->version;
+
+ /* This acquires a read lock on success */
+ ret = get_first(server_context, log_fd,
+ initial_verp, initial_timep);
+ if (ret != 0)
+ return -1;
+
+ /* When the slave version is out of range, send the whole database. */
+ if (ver == 0 || ver < *initial_verp || ver > current_version) {
+ flock(log_fd, LOCK_UN);
+ return 0;
+ }
+
+ /* Avoid seeking past the last committed record */
+ if (kadm5_log_goto_end(server_context, sp) != 0 ||
+ (pos = krb5_storage_seek(sp, 0, SEEK_CUR)) < 0)
+ goto err;
+
+ /*
+ * First try to see if we can find it quickly by seeking to the right
+ * end of the previous diff sent.
+ */
+ if (s->next_diff.last_version_sent > 0 &&
+ s->next_diff.off_next_version > 0 &&
+ s->next_diff.off_next_version < pos &&
+ s->next_diff.initial_version == *initial_verp &&
+ s->next_diff.initial_tstamp == *initial_timep) {
+ /*
+ * Sanity check that the left version matches what we wanted, the
+ * log may have been truncated since.
+ */
+ left = s->next_diff.off_next_version;
+ if (krb5_storage_seek(sp, left, SEEK_SET) != left)
+ goto err;
+ if (kadm5_log_next(context, sp, &ver, NULL, NULL, NULL) == 0 &&
+ ver == s->next_diff.last_version_sent + 1)
+ return left;
+ }
+
+ if (krb5_storage_seek(sp, pos, SEEK_SET) != pos)
+ goto err;
+
+ /*
+ * Drop the lock and try to find the left entry by seeking backward
+ * from the end of the end of the log. If we succeed, re-acquire the
+ * lock, update "next_diff", and retry the fast-path.
+ */
+ flock(log_fd, LOCK_UN);
+
+ /* Slow path: seek backwards, entry by entry, from the end */
+ for (;;) {
+ enum kadm_ops op;
+ uint32_t len;
+
+ ret = kadm5_log_previous(context, sp, &ver, NULL, &op, &len);
+ if (ret)
+ return -1;
+ left = krb5_storage_seek(sp, -16, SEEK_CUR);
+ if (left < 0)
+ return left;
+ if (ver == s->version + 1)
+ break;
+
+ /*
+ * We don't expect to reach the slave's version, unless the log
+ * has been modified after we released the lock.
+ */
+ if (ver == s->version) {
+ krb5_warnx(context, "iprop log truncated while sending diffs "
+ "to slave?? ver = %lu", (unsigned long)ver);
+ return -1;
+ }
+
+ /* If we've reached the uber record, send the complete database */
+ if (left == 0 || (ver == 0 && op == kadm_nop))
+ return 0;
+ }
+ assert(ver == s->version + 1);
+
+ /* Set up the fast-path pre-conditions */
+ s->next_diff.last_version_sent = s->version;
+ s->next_diff.off_next_version = left;
+ s->next_diff.initial_version = *initial_verp;
+ s->next_diff.initial_tstamp = *initial_timep;
+
+ /*
+ * If we loop then we're hoping to hit the fast path so we can return a
+ * non-zero, positive left offset with the lock held.
+ *
+ * We just updated the fast path pre-conditions, so unless a log
+ * truncation event happens between the point where we dropped the lock
+ * and the point where we rearcuire it above, we will hit the fast
+ * path.
+ */
+ }
+
+ err:
+ flock(log_fd, LOCK_UN);
+ return -1;
+}
+
+static off_t
+get_right(krb5_context context, int log_fd, krb5_storage *sp,
+ int lastver, slave *s, off_t left, uint32_t *verp)
+{
+ int ret = 0;
+ int i = 0;
+ uint32_t ver = s->version;
+ off_t right = krb5_storage_seek(sp, left, SEEK_SET);
+
+ if (right <= 0) {
+ flock(log_fd, LOCK_UN);
+ return -1;
+ }
+
+ /* The "lastver" bound should preclude us reaching EOF */
+ for (; ret == 0 && i < SEND_DIFFS_MAX_RECORDS && ver < lastver; ++i) {
+ uint32_t logver;
+
+ ret = kadm5_log_next(context, sp, &logver, NULL, NULL, NULL);
+ if (logver != ++ver)
+ ret = KADM5_LOG_CORRUPT;
+ }
+
+ if (ret == 0)
+ right = krb5_storage_seek(sp, 0, SEEK_CUR);
+ else
+ right = -1;
+ if (right <= 0) {
+ flock(log_fd, LOCK_UN);
+ return -1;
+ }
+ *verp = ver;
+ return right;
+}
+
+static void
+send_diffs(kadm5_server_context *server_context, slave *s, int log_fd,
+ const char *database, uint32_t current_version)
+{
+ krb5_context context = server_context->context;
+ krb5_storage *sp;
+ uint32_t initial_version;
+ uint32_t initial_tstamp;
+ uint32_t ver = 0;
+ off_t left = 0;
+ off_t right = 0;
+ krb5_ssize_t bytes;
+ krb5_data data;
+ int ret = 0;
+
+ if (!diffready(context, s) || nodiffs(context, s, current_version))
+ return;
+
+ if (verbose)
+ krb5_warnx(context, "sending diffs to live-seeming slave %s", s->name);
+
+ sp = krb5_storage_from_fd(log_fd);
+ if (sp == NULL)
+ krb5_err(context, IPROPD_RESTART_SLOW, ENOMEM,
+ "send_diffs: out of memory");
+
+ left = get_left(server_context, s, sp, log_fd, current_version,
+ &initial_version, &initial_tstamp);
+ if (left < 0) {
+ krb5_storage_free(sp);
+ slave_dead(context, s);
+ return;
+ }
+
+ if (left == 0) {
+ /* Slave's version is not in the log, fall back on send_complete() */
+ krb5_storage_free(sp);
+ send_complete(context, s, database, current_version,
+ initial_version, initial_tstamp);
+ return;
+ }
+
+ /* We still hold the read lock, if right > 0 */
+ right = get_right(server_context->context, log_fd, sp, current_version,
+ s, left, &ver);
+ if (right == left) {
+ flock(log_fd, LOCK_UN);
+ krb5_storage_free(sp);
+ return;
+ }
+ if (right < left) {
+ assert(right < 0);
+ krb5_storage_free(sp);
+ slave_dead(context, s);
+ return;
+ }
+
+ if (krb5_storage_seek(sp, left, SEEK_SET) != left) {
+ ret = errno ? errno : EIO;
+ flock(log_fd, LOCK_UN);
+ krb5_warn(context, ret, "send_diffs: krb5_storage_seek");
+ krb5_storage_free(sp);
+ slave_dead(context, s);
+ return;
+ }
+
+ ret = krb5_data_alloc(&data, right - left + 4);
+ if (ret) {
+ flock(log_fd, LOCK_UN);
+ krb5_warn(context, ret, "send_diffs: krb5_data_alloc");
+ krb5_storage_free(sp);
+ slave_dead(context, s);
+ return;
+ }
+
+ bytes = krb5_storage_read(sp, (char *)data.data + 4, data.length - 4);
+ flock(log_fd, LOCK_UN);
+ krb5_storage_free(sp);
+ if (bytes != data.length - 4)
+ krb5_errx(context, IPROPD_RESTART, "locked log truncated???");
+
+ sp = krb5_storage_from_data(&data);
+ if (sp == NULL) {
+ krb5_err(context, IPROPD_RESTART_SLOW, ENOMEM, "out of memory");
+ return;
+ }
+ krb5_store_uint32(sp, FOR_YOU);
+ krb5_storage_free(sp);
+
+ ret = mk_priv_tail(context, s, &data);
+ krb5_data_free(&data);
+ if (ret == 0) {
+ /* Save the fast-path continuation */
+ s->next_diff.last_version_sent = ver;
+ s->next_diff.off_next_version = right;
+ s->next_diff.initial_version = initial_version;
+ s->next_diff.initial_tstamp = initial_tstamp;
+ s->next_diff.more = ver < current_version;
+ ret = send_tail(context, s);
+
+ krb5_warnx(context,
+ "syncing slave %s from version %lu to version %lu",
+ s->name, (unsigned long)s->version,
+ (unsigned long)ver);
+ s->version = ver;
+ }
+
+ if (ret && ret != EWOULDBLOCK) {
+ krb5_warn(context, ret, "send_diffs: making or sending "
+ "KRB-PRIV message");
+ slave_dead(context, s);
+ return;
+ }
+ slave_seen(s);
+ return;
+}
+
+/* Sensible bound on slave message size */
+#define SLAVE_MSG_MAX 65536
+
+static int
+fill_input(krb5_context context, slave *s)
+{
+ krb5_error_code ret;
+
+ if (s->input.hlen < 4) {
+ uint8_t *buf = s->input.header_buf + s->input.hlen;
+ size_t len = 4 - s->input.hlen;
+ krb5_ssize_t bytes = krb5_net_read(context, &s->fd, buf, len);
+
+ if (bytes == 0)
+ return HEIM_ERR_EOF;
+ if (bytes < 0) {
+ if (errno == EWOULDBLOCK || errno == EAGAIN)
+ return EWOULDBLOCK;
+ return errno ? errno : EIO;
+ }
+ s->input.hlen += bytes;
+ if (bytes < len)
+ return EWOULDBLOCK;
+
+ buf = s->input.header_buf;
+ len = ((unsigned long)buf[0] << 24) | (buf[1] << 16)
+ | (buf[2] << 8) | buf[3];
+ if (len > SLAVE_MSG_MAX)
+ return EINVAL;
+ ret = krb5_data_alloc(&s->input.packet, len);
+ if (ret != 0)
+ return ret;
+ }
+
+ if (s->input.offset < s->input.packet.length) {
+ u_char *buf = (u_char *)s->input.packet.data + s->input.offset;
+ size_t len = s->input.packet.length - s->input.offset;
+ krb5_ssize_t bytes = krb5_net_read(context, &s->fd, buf, len);
+
+ if (bytes == 0)
+ return HEIM_ERR_EOF;
+ if (bytes < 0) {
+ if (errno == EWOULDBLOCK || errno == EAGAIN)
+ return EWOULDBLOCK;
+ return errno ? errno : EIO;
+ }
+ s->input.offset += bytes;
+ if (bytes != len)
+ return EWOULDBLOCK;
+ }
+ return 0;
+}
+
+static int
+read_msg(krb5_context context, slave *s, krb5_data *out)
+{
+ int ret = fill_input(context, s);
+
+ if (ret != 0)
+ return ret;
+
+ ret = krb5_rd_priv(context, s->ac, &s->input.packet, out, NULL);
+
+ /* Prepare for next packet */
+ krb5_data_free(&s->input.packet);
+ s->input.offset = 0;
+ s->input.hlen = 0;
+
+ return ret;
+}
+
+static int
+process_msg(kadm5_server_context *server_context, slave *s, int log_fd,
+ const char *database, uint32_t current_version)
+{
+ krb5_context context = server_context->context;
+ int ret = 0;
+ krb5_data out;
+ krb5_storage *sp;
+ uint32_t tmp;
+
+ ret = read_msg(context, s, &out);
+ if (ret) {
+ if (ret != EWOULDBLOCK)
+ krb5_warn(context, ret, "error reading message from %s", s->name);
+ return ret;
+ }
+
+ sp = krb5_storage_from_mem(out.data, out.length);
+ if (sp == NULL) {
+ krb5_warnx(context, "process_msg: no memory");
+ krb5_data_free(&out);
+ return 1;
+ }
+ if (krb5_ret_uint32(sp, &tmp) != 0) {
+ krb5_warnx(context, "process_msg: client send too short command");
+ krb5_data_free(&out);
+ return 1;
+ }
+ switch (tmp) {
+ case I_HAVE :
+ ret = krb5_ret_uint32(sp, &tmp);
+ if (ret != 0) {
+ krb5_warnx(context, "process_msg: client send too little I_HAVE data");
+ break;
+ }
+ /*
+ * XXX Make the slave send the timestamp as well, and try to get it
+ * here, and pass it to send_diffs().
+ */
+ /*
+ * New slave whose version number we've not yet seen. If the version
+ * number is zero, the slave has no data, and we'll send a complete
+ * database (that happens in send_diffs()). Otherwise, we'll record a
+ * non-zero initial version and attempt an incremental update.
+ *
+ * NOTE!: Once the slave is "ready" (its first I_HAVE has conveyed its
+ * initial version), we MUST NOT update s->version to the slave's
+ * I_HAVE version, since we may already have sent later updates, and
+ * MUST NOT send them again, otherwise we can get further and further
+ * out of sync resending larger and larger diffs. The "not yet ready"
+ * is an essential precondition for setting s->version to the value
+ * in the I_HAVE message. This happens only once when the slave
+ * first connects.
+ */
+ if (!(s->flags & SLAVE_F_READY)) {
+ if (current_version < tmp) {
+ krb5_warnx(context, "Slave %s (version %u) has later version "
+ "than the master (version %u) OUT OF SYNC",
+ s->name, tmp, current_version);
+ /* Force send_complete() */
+ tmp = 0;
+ }
+ /*
+ * Mark the slave as ready for updates based on incoming signals.
+ * Prior to the initial I_HAVE, we don't know the slave's version
+ * number, and MUST not send it anything, since we'll needlessly
+ * attempt to send the whole database!
+ */
+ s->version = tmp;
+ s->flags |= SLAVE_F_READY;
+ if (verbose)
+ krb5_warnx(context, "slave %s ready for updates from version %u",
+ s->name, tmp);
+ }
+ if ((s->version_ack = tmp) < s->version)
+ break;
+ send_diffs(server_context, s, log_fd, database, current_version);
+ break;
+ case I_AM_HERE :
+ if (verbose)
+ krb5_warnx(context, "slave %s is there", s->name);
+ break;
+ case ARE_YOU_THERE:
+ case FOR_YOU :
+ default :
+ krb5_warnx(context, "Ignoring command %d", tmp);
+ break;
+ }
+
+ krb5_data_free(&out);
+ krb5_storage_free(sp);
+
+ slave_seen(s);
+
+ return ret;
+}
+
+#define SLAVE_NAME "Name"
+#define SLAVE_ADDRESS "Address"
+#define SLAVE_VERSION "Version"
+#define SLAVE_STATUS "Status"
+#define SLAVE_SEEN "Last Seen"
+
+static void
+init_stats_names(krb5_context context)
+{
+ const char *fn = NULL;
+ char *buf = NULL;
+
+ if (slave_stats_file)
+ fn = slave_stats_file;
+ else if ((fn = krb5_config_get_string(context, NULL, "kdc",
+ "iprop-stats", NULL)) == NULL) {
+ if (asprintf(&buf, "%s/slaves-stats", hdb_db_dir(context)) != -1
+ && buf != NULL)
+ fn = buf;
+ buf = NULL;
+ }
+ if (fn != NULL) {
+ slave_stats_file = fn;
+ if (asprintf(&buf, "%s.tmp", fn) != -1 && buf != NULL)
+ slave_stats_temp_file = buf;
+ }
+}
+
+static void
+write_master_down(krb5_context context)
+{
+ char str[100];
+ time_t t = time(NULL);
+ FILE *fp = NULL;
+
+ if (slave_stats_temp_file != NULL)
+ fp = fopen(slave_stats_temp_file, "w");
+ if (fp == NULL)
+ return;
+ if (krb5_format_time(context, t, str, sizeof(str), TRUE) == 0)
+ fprintf(fp, "master down at %s\n", str);
+ else
+ fprintf(fp, "master down\n");
+
+ if (fclose(fp) != EOF)
+ (void) rk_rename(slave_stats_temp_file, slave_stats_file);
+}
+
+static void
+write_stats(krb5_context context, slave *slaves, uint32_t current_version)
+{
+ char str[100];
+ rtbl_t tbl;
+ time_t t = time(NULL);
+ FILE *fp = NULL;
+
+ if (slave_stats_temp_file != NULL)
+ fp = fopen(slave_stats_temp_file, "w");
+ if (fp == NULL)
+ return;
+
+ if (krb5_format_time(context, t, str, sizeof(str), TRUE))
+ snprintf(str, sizeof(str), "<unknown-time>");
+ fprintf(fp, "Status for slaves, last updated: %s\n\n", str);
+
+ fprintf(fp, "Master version: %lu\n\n", (unsigned long)current_version);
+
+ tbl = rtbl_create();
+ if (tbl == NULL) {
+ fclose(fp);
+ return;
+ }
+
+ rtbl_add_column(tbl, SLAVE_NAME, 0);
+ rtbl_add_column(tbl, SLAVE_ADDRESS, 0);
+ rtbl_add_column(tbl, SLAVE_VERSION, RTBL_ALIGN_RIGHT);
+ rtbl_add_column(tbl, SLAVE_STATUS, 0);
+ rtbl_add_column(tbl, SLAVE_SEEN, 0);
+
+ rtbl_set_prefix(tbl, " ");
+ rtbl_set_column_prefix(tbl, SLAVE_NAME, "");
+
+ while (slaves) {
+ krb5_address addr;
+ krb5_error_code ret;
+ rtbl_add_column_entry(tbl, SLAVE_NAME, slaves->name);
+ ret = krb5_sockaddr2address (context,
+ (struct sockaddr*)&slaves->addr, &addr);
+ if(ret == 0) {
+ krb5_print_address(&addr, str, sizeof(str), NULL);
+ krb5_free_address(context, &addr);
+ rtbl_add_column_entry(tbl, SLAVE_ADDRESS, str);
+ } else
+ rtbl_add_column_entry(tbl, SLAVE_ADDRESS, "<unknown>");
+
+ snprintf(str, sizeof(str), "%u", (unsigned)slaves->version_ack);
+ rtbl_add_column_entry(tbl, SLAVE_VERSION, str);
+
+ if (slaves->flags & SLAVE_F_DEAD)
+ rtbl_add_column_entry(tbl, SLAVE_STATUS, "Down");
+ else
+ rtbl_add_column_entry(tbl, SLAVE_STATUS, "Up");
+
+ ret = krb5_format_time(context, slaves->seen, str, sizeof(str), TRUE);
+ if (ret)
+ rtbl_add_column_entry(tbl, SLAVE_SEEN, "<error-formatting-time>");
+ else
+ rtbl_add_column_entry(tbl, SLAVE_SEEN, str);
+
+ slaves = slaves->next;
+ }
+
+ rtbl_format(tbl, fp);
+ rtbl_destroy(tbl);
+
+ if (fclose(fp) != EOF)
+ (void) rk_rename(slave_stats_temp_file, slave_stats_file);
+}
+
+
+static char sHDB[] = "HDBGET:";
+static char *realm;
+static int version_flag;
+static int help_flag;
+static char *keytab_str = sHDB;
+static char *database;
+static char *config_file;
+static char *port_str;
+static int detach_from_console;
+static int daemon_child = -1;
+
+static struct getargs args[] = {
+ { "config-file", 'c', arg_string, &config_file, NULL, NULL },
+ { "realm", 'r', arg_string, &realm, NULL, NULL },
+ { "keytab", 'k', arg_string, &keytab_str,
+ "keytab to get authentication from", "kspec" },
+ { "database", 'd', arg_string, &database, "database", "file"},
+ { "slave-stats-file", 0, arg_string, rk_UNCONST(&slave_stats_file),
+ "file for slave status information", "file"},
+ { "time-missing", 0, arg_string, rk_UNCONST(&slave_time_missing),
+ "time before slave is polled for presence", "time"},
+ { "time-gone", 0, arg_string, rk_UNCONST(&slave_time_gone),
+ "time of inactivity after which a slave is considered gone", "time"},
+ { "port", 0, arg_string, &port_str,
+ "port ipropd will listen to", "port"},
+ { "detach", 0, arg_flag, &detach_from_console,
+ "detach from console", NULL },
+ { "daemon-child", 0, arg_integer, &daemon_child,
+ "private argument, do not use", NULL },
+ { "pidfile-basename", 0, arg_string, &pidfile_basename,
+ "basename of pidfile; private argument for testing", "NAME" },
+ { "hostname", 0, arg_string, rk_UNCONST(&master_hostname),
+ "hostname of master (if not same as hostname)", "hostname" },
+ { "verbose", 0, arg_flag, &verbose, NULL, NULL },
+ { "version", 0, arg_flag, &version_flag, NULL, NULL },
+ { "help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+static int num_args = sizeof(args) / sizeof(args[0]);
+
+int
+main(int argc, char **argv)
+{
+ krb5_error_code ret;
+ krb5_context context;
+ void *kadm_handle;
+ kadm5_server_context *server_context;
+ kadm5_config_params conf;
+ krb5_socket_t signal_fd, listen_fd;
+ int log_fd;
+ slave *slaves = NULL;
+ uint32_t current_version = 0, old_version = 0;
+ krb5_keytab keytab;
+ char **files;
+ int aret;
+ int optidx = 0;
+ int restarter_fd = -1;
+ struct stat st;
+
+ setprogname(argv[0]);
+
+ if (getarg(args, num_args, argc, argv, &optidx))
+ krb5_std_usage(1, args, num_args);
+
+ if (help_flag)
+ krb5_std_usage(0, args, num_args);
+
+ if (version_flag) {
+ print_version(NULL);
+ exit(0);
+ }
+
+ if (detach_from_console && daemon_child == -1)
+ daemon_child = roken_detach_prep(argc, argv, "--daemon-child");
+ rk_pidfile(pidfile_basename);
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_init_context failed: %d", ret);
+
+ setup_signal();
+
+ if (config_file == NULL) {
+ aret = asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context));
+ if (aret == -1 || config_file == NULL)
+ errx(1, "out of memory");
+ }
+
+ ret = krb5_prepend_config_files_default(config_file, &files);
+ if (ret)
+ krb5_err(context, 1, ret, "getting configuration files");
+
+ ret = krb5_set_config_files(context, files);
+ krb5_free_config_files(files);
+ if (ret)
+ krb5_err(context, 1, ret, "reading configuration files");
+
+ init_stats_names(context);
+
+ time_before_gone = parse_time (slave_time_gone, "s");
+ if (time_before_gone < 0)
+ krb5_errx (context, 1, "couldn't parse time: %s", slave_time_gone);
+ time_before_missing = parse_time (slave_time_missing, "s");
+ if (time_before_missing < 0)
+ krb5_errx (context, 1, "couldn't parse time: %s", slave_time_missing);
+
+ krb5_openlog(context, "ipropd-master", &log_facility);
+ krb5_set_warn_dest(context, log_facility);
+
+ ret = krb5_kt_register(context, &hdb_get_kt_ops);
+ if(ret)
+ krb5_err(context, 1, ret, "krb5_kt_register");
+
+ ret = krb5_kt_resolve(context, keytab_str, &keytab);
+ if(ret)
+ krb5_err(context, 1, ret, "krb5_kt_resolve: %s", keytab_str);
+
+ memset(&conf, 0, sizeof(conf));
+ if(realm) {
+ conf.mask |= KADM5_CONFIG_REALM;
+ conf.realm = realm;
+ }
+ ret = kadm5_init_with_skey_ctx (context,
+ KADM5_ADMIN_SERVICE,
+ NULL,
+ KADM5_ADMIN_SERVICE,
+ &conf, 0, 0,
+ &kadm_handle);
+ if (ret)
+ krb5_err (context, 1, ret, "kadm5_init_with_password_ctx");
+
+ server_context = (kadm5_server_context *)kadm_handle;
+
+ log_fd = open (server_context->log_context.log_file, O_RDONLY, 0);
+ if (log_fd < 0)
+ krb5_err (context, 1, errno, "open %s",
+ server_context->log_context.log_file);
+
+ if (fstat(log_fd, &st) == -1)
+ krb5_err(context, 1, errno, "stat %s",
+ server_context->log_context.log_file);
+
+ if (flock(log_fd, LOCK_SH) == -1)
+ krb5_err(context, 1, errno, "shared flock %s",
+ server_context->log_context.log_file);
+ kadm5_log_get_version_fd(server_context, log_fd, LOG_VERSION_LAST,
+ &current_version, NULL);
+ flock(log_fd, LOCK_UN);
+
+ signal_fd = make_signal_socket (context);
+ listen_fd = make_listen_socket (context, port_str);
+
+ krb5_warnx(context, "ipropd-master started at version: %lu",
+ (unsigned long)current_version);
+
+ roken_detach_finish(NULL, daemon_child);
+ restarter_fd = restarter(context, NULL);
+
+ while (exit_flag == 0){
+ slave *p;
+ fd_set readset, writeset;
+ int max_fd = 0;
+ struct timeval to = {30, 0};
+ uint32_t vers;
+ struct stat st2;;
+
+#ifndef NO_LIMIT_FD_SETSIZE
+ if (signal_fd >= FD_SETSIZE || listen_fd >= FD_SETSIZE ||
+ restarter_fd >= FD_SETSIZE)
+ krb5_errx (context, IPROPD_RESTART, "fd too large");
+#endif
+
+ FD_ZERO(&readset);
+ FD_ZERO(&writeset);
+ FD_SET(signal_fd, &readset);
+ max_fd = max(max_fd, signal_fd);
+ FD_SET(listen_fd, &readset);
+ max_fd = max(max_fd, listen_fd);
+ if (restarter_fd > -1) {
+ FD_SET(restarter_fd, &readset);
+ max_fd = max(max_fd, restarter_fd);
+ }
+
+ for (p = slaves; p != NULL; p = p->next) {
+ if (p->flags & SLAVE_F_DEAD)
+ continue;
+ FD_SET(p->fd, &readset);
+ if (have_tail(p) || more_diffs(p))
+ FD_SET(p->fd, &writeset);
+ max_fd = max(max_fd, p->fd);
+ }
+
+ ret = select(max_fd + 1, &readset, &writeset, NULL, &to);
+ if (ret < 0) {
+ if (errno == EINTR)
+ continue;
+ else
+ krb5_err (context, IPROPD_RESTART, errno, "select");
+ }
+
+ if (stat(server_context->log_context.log_file, &st2) == -1) {
+ krb5_warn(context, errno, "could not stat log file by path");
+ st2 = st;
+ }
+
+ if (st2.st_dev != st.st_dev || st2.st_ino != st.st_ino) {
+ (void) close(log_fd);
+
+ log_fd = open(server_context->log_context.log_file, O_RDONLY, 0);
+ if (log_fd < 0)
+ krb5_err(context, IPROPD_RESTART_SLOW, errno, "open %s",
+ server_context->log_context.log_file);
+
+ if (fstat(log_fd, &st) == -1)
+ krb5_err(context, IPROPD_RESTART_SLOW, errno, "stat %s",
+ server_context->log_context.log_file);
+
+ if (flock(log_fd, LOCK_SH) == -1)
+ krb5_err(context, IPROPD_RESTART, errno, "shared flock %s",
+ server_context->log_context.log_file);
+ kadm5_log_get_version_fd(server_context, log_fd, LOG_VERSION_LAST,
+ &current_version, NULL);
+ flock(log_fd, LOCK_UN);
+ }
+
+ if (ret == 0) {
+ /* Recover from failed transactions */
+ if (kadm5_log_init_nb(server_context) == 0)
+ kadm5_log_end(server_context);
+
+ if (flock(log_fd, LOCK_SH) == -1)
+ krb5_err(context, IPROPD_RESTART, errno,
+ "could not lock log file");
+ kadm5_log_get_version_fd(server_context, log_fd, LOG_VERSION_LAST,
+ &current_version, NULL);
+ flock(log_fd, LOCK_UN);
+
+ if (current_version > old_version) {
+ if (verbose)
+ krb5_warnx(context,
+ "Missed a signal, updating slaves %lu to %lu",
+ (unsigned long)old_version,
+ (unsigned long)current_version);
+ for (p = slaves; p != NULL; p = p->next) {
+ if (p->flags & SLAVE_F_DEAD)
+ continue;
+ send_diffs(server_context, p, log_fd, database,
+ current_version);
+ }
+ old_version = current_version;
+ }
+ }
+
+ if (ret && FD_ISSET(restarter_fd, &readset)) {
+ exit_flag = SIGTERM;
+ break;
+ }
+
+ if (ret && FD_ISSET(signal_fd, &readset)) {
+#ifndef NO_UNIX_SOCKETS
+ struct sockaddr_un peer_addr;
+#else
+ struct sockaddr_storage peer_addr;
+#endif
+ socklen_t peer_len = sizeof(peer_addr);
+
+ if(recvfrom(signal_fd, (void *)&vers, sizeof(vers), 0,
+ (struct sockaddr *)&peer_addr, &peer_len) < 0) {
+ krb5_warn (context, errno, "recvfrom");
+ continue;
+ }
+ --ret;
+ assert(ret >= 0);
+ old_version = current_version;
+ if (flock(log_fd, LOCK_SH) == -1)
+ krb5_err(context, IPROPD_RESTART, errno, "shared flock %s",
+ server_context->log_context.log_file);
+ kadm5_log_get_version_fd(server_context, log_fd, LOG_VERSION_LAST,
+ &current_version, NULL);
+ flock(log_fd, LOCK_UN);
+ if (current_version != old_version) {
+ /*
+ * If current_version < old_version then the log got
+ * truncated and we'll end up doing full propagations.
+ *
+ * Truncating the log when the current version is
+ * numerically small can lead to race conditions.
+ * Ideally we should identify log versions as
+ * {init_or_trunc_time, vno}, then we could not have any
+ * such race conditions, but this would either require
+ * breaking backwards compatibility for the protocol or
+ * adding new messages to it.
+ */
+ if (verbose)
+ krb5_warnx(context,
+ "Got a signal, updating slaves %lu to %lu",
+ (unsigned long)old_version,
+ (unsigned long)current_version);
+ for (p = slaves; p != NULL; p = p->next) {
+ if (p->flags & SLAVE_F_DEAD)
+ continue;
+ send_diffs(server_context, p, log_fd, database,
+ current_version);
+ }
+ } else {
+ if (verbose)
+ krb5_warnx(context,
+ "Got a signal, but no update in log version %lu",
+ (unsigned long)current_version);
+ }
+ }
+
+ for (p = slaves; p != NULL; p = p->next) {
+ if (!(p->flags & SLAVE_F_DEAD) &&
+ FD_ISSET(p->fd, &writeset) &&
+ ((have_tail(p) && send_tail(context, p) == 0) ||
+ (!have_tail(p) && more_diffs(p)))) {
+ send_diffs(server_context, p, log_fd, database,
+ current_version);
+ }
+ }
+
+ for(p = slaves; p != NULL; p = p->next) {
+ if (p->flags & SLAVE_F_DEAD)
+ continue;
+ if (ret && FD_ISSET(p->fd, &readset)) {
+ --ret;
+ assert(ret >= 0);
+ ret = process_msg(server_context, p, log_fd, database,
+ current_version);
+ if (ret && ret != EWOULDBLOCK)
+ slave_dead(context, p);
+ } else if (slave_gone_p (p))
+ slave_dead(context, p);
+ else if (slave_missing_p (p))
+ send_are_you_there (context, p);
+ }
+
+ if (ret && FD_ISSET(listen_fd, &readset)) {
+ add_slave (context, keytab, &slaves, listen_fd);
+ --ret;
+ assert(ret >= 0);
+ }
+ write_stats(context, slaves, current_version);
+ }
+
+ if(exit_flag == SIGINT || exit_flag == SIGTERM)
+ krb5_warnx(context, "%s terminated", getprogname());
+#ifdef SIGXCPU
+ else if(exit_flag == SIGXCPU)
+ krb5_warnx(context, "%s CPU time limit exceeded", getprogname());
+#endif
+ else
+ krb5_warnx(context, "%s unexpected exit reason: %ld",
+ getprogname(), (long)exit_flag);
+
+ write_master_down(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/ipropd_slave.c b/third_party/heimdal/lib/kadm5/ipropd_slave.c
new file mode 100644
index 0000000..2b1be00
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/ipropd_slave.c
@@ -0,0 +1,1162 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "iprop.h"
+
+RCSID("$Id$");
+
+static const char *config_name = "ipropd-slave";
+
+static int verbose;
+static int async_hdb = 0;
+
+static krb5_log_facility *log_facility;
+static char five_min[] = "5 min";
+static char *server_time_lost = five_min;
+static int time_before_lost;
+static const char *slave_str;
+static const char *pidfile_basename;
+static char *realm;
+
+static int
+connect_to_master (krb5_context context, const char *master,
+ const char *port_str)
+{
+ char port[NI_MAXSERV];
+ struct addrinfo *ai, *a;
+ struct addrinfo hints;
+ int error;
+ int one = 1;
+ int s = -1;
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_socktype = SOCK_STREAM;
+
+ if (port_str == NULL) {
+ snprintf(port, sizeof(port), "%u", IPROP_PORT);
+ port_str = port;
+ }
+
+ error = getaddrinfo(master, port_str, &hints, &ai);
+ if (error) {
+ krb5_warnx(context, "Failed to get address of to %s: %s",
+ master, gai_strerror(error));
+ return -1;
+ }
+
+ for (a = ai; a != NULL; a = a->ai_next) {
+ char node[NI_MAXHOST];
+ error = getnameinfo(a->ai_addr, a->ai_addrlen,
+ node, sizeof(node), NULL, 0, NI_NUMERICHOST);
+ if (error)
+ strlcpy(node, "[unknown-addr]", sizeof(node));
+
+ s = socket(a->ai_family, a->ai_socktype, a->ai_protocol);
+ if (s < 0)
+ continue;
+ if (connect(s, a->ai_addr, a->ai_addrlen) < 0) {
+ krb5_warn(context, errno, "connection failed to %s[%s]",
+ master, node);
+ close(s);
+ continue;
+ }
+ krb5_warnx(context, "connection successful "
+ "to master: %s[%s]", master, node);
+ break;
+ }
+ freeaddrinfo(ai);
+
+ if (a == NULL)
+ return -1;
+
+ if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)) < 0)
+ krb5_warn(context, errno, "setsockopt(SO_KEEPALIVE) failed");
+
+ /*
+ * We write message lengths separately from the payload, avoid Nagle
+ * delays.
+ */
+#if defined(IPPROTO_TCP) && defined(TCP_NODELAY)
+ (void) setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
+ (void *)&one, sizeof(one));
+#endif
+
+ return s;
+}
+
+static void
+get_creds(krb5_context context, const char *keytab_str,
+ krb5_ccache *cache, const char *serverhost)
+{
+ krb5_keytab keytab;
+ krb5_principal client;
+ krb5_error_code ret;
+ krb5_get_init_creds_opt *init_opts;
+ krb5_creds creds;
+ char *server;
+ char keytab_buf[256];
+ int aret;
+
+ if (keytab_str == NULL) {
+ ret = krb5_kt_default_name (context, keytab_buf, sizeof(keytab_buf));
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_kt_default_name");
+ keytab_str = keytab_buf;
+ }
+
+ ret = krb5_kt_resolve(context, keytab_str, &keytab);
+ if(ret)
+ krb5_err(context, 1, ret, "%s", keytab_str);
+
+ ret = krb5_sname_to_principal(context, slave_str, IPROP_NAME,
+ KRB5_NT_SRV_HST, &client);
+ if (ret) krb5_err(context, 1, ret, "krb5_sname_to_principal");
+ if (realm)
+ ret = krb5_principal_set_realm(context, client, realm);
+ if (ret) krb5_err(context, 1, ret, "krb5_principal_set_realm");
+
+ ret = krb5_get_init_creds_opt_alloc(context, &init_opts);
+ if (ret) krb5_err(context, 1, ret, "krb5_get_init_creds_opt_alloc");
+
+ aret = asprintf (&server, "%s/%s", IPROP_NAME, serverhost);
+ if (aret == -1 || server == NULL)
+ krb5_errx (context, 1, "malloc: no memory");
+
+ ret = krb5_get_init_creds_keytab(context, &creds, client, keytab,
+ 0, server, init_opts);
+ free (server);
+ krb5_get_init_creds_opt_free(context, init_opts);
+ if(ret) krb5_err(context, 1, ret, "krb5_get_init_creds");
+
+ ret = krb5_kt_close(context, keytab);
+ if(ret) krb5_err(context, 1, ret, "krb5_kt_close");
+
+ ret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, cache);
+ if(ret) krb5_err(context, 1, ret, "krb5_cc_new_unique");
+
+ ret = krb5_cc_initialize(context, *cache, creds.client);
+ if(ret) krb5_err(context, 1, ret, "krb5_cc_initialize");
+
+ ret = krb5_cc_store_cred(context, *cache, &creds);
+ if(ret) krb5_err(context, 1, ret, "krb5_cc_store_cred");
+
+ krb5_free_cred_contents(context, &creds);
+ krb5_free_principal(context, client);
+}
+
+static krb5_error_code
+ihave(krb5_context context, krb5_auth_context auth_context,
+ int fd, uint32_t version)
+{
+ int ret;
+ u_char buf[8];
+ krb5_storage *sp;
+ krb5_data data;
+
+ sp = krb5_storage_from_mem(buf, 8);
+ if (sp == NULL)
+ krb5_err(context, IPROPD_RESTART_SLOW, ENOMEM, "Out of memory");
+ ret = krb5_store_uint32(sp, I_HAVE);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, version);
+ krb5_storage_free(sp);
+ data.length = 8;
+ data.data = buf;
+
+ if (ret == 0) {
+ if (verbose)
+ krb5_warnx(context, "telling master we are at %u", version);
+
+ ret = krb5_write_priv_message(context, auth_context, &fd, &data);
+ if (ret)
+ krb5_warn(context, ret, "krb5_write_message");
+ }
+ return ret;
+}
+
+#ifndef EDQUOT
+/* There's no EDQUOT on WIN32, for example */
+#define EDQUOT ENOSPC
+#endif
+
+static int
+append_to_log_file(krb5_context context,
+ kadm5_server_context *server_context,
+ krb5_storage *sp, off_t start, ssize_t slen)
+{
+ size_t len;
+ ssize_t sret;
+ off_t log_off;
+ int ret, ret2;
+ void *buf;
+
+ if (verbose)
+ krb5_warnx(context, "appending diffs to log");
+
+ if (slen == 0)
+ return 0;
+ if (slen < 0)
+ return EINVAL;
+ len = slen;
+ if (len != slen)
+ return EOVERFLOW;
+
+ buf = malloc(len);
+ if (buf == NULL && len != 0)
+ return krb5_enomem(context);
+
+ if (krb5_storage_seek(sp, start, SEEK_SET) != start) {
+ krb5_errx(context, IPROPD_RESTART,
+ "krb5_storage_seek() failed"); /* can't happen */
+ }
+ sret = krb5_storage_read(sp, buf, len);
+ if (sret < 0)
+ return errno;
+ if (len != (size_t)sret) {
+ /* Can't happen */
+ krb5_errx(context, IPROPD_RESTART,
+ "short krb5_storage_read() from memory buffer");
+ }
+ log_off = lseek(server_context->log_context.log_fd, 0, SEEK_CUR);
+ if (log_off == -1)
+ return errno;
+
+ /*
+ * Use net_write() so we get an errno if less that len bytes were
+ * written.
+ */
+ sret = net_write(server_context->log_context.log_fd, buf, len);
+ free(buf);
+ if (sret != slen)
+ ret = errno;
+ else
+ ret = fsync(server_context->log_context.log_fd);
+ if (ret == 0)
+ return 0;
+ krb5_warn(context, ret,
+ "Failed to write iprop log fd %d %llu bytes at offset %lld: %d",
+ server_context->log_context.log_fd, (unsigned long long)len,
+ (long long)log_off, ret);
+
+ /*
+ * Attempt to recover from this. First, truncate the log file
+ * and reset the fd offset. Failure to do this -> unlink the
+ * log file and re-create it. Since we're the slave, we ought to be
+ * able to recover from the log being unlinked...
+ */
+ if (ftruncate(server_context->log_context.log_fd, log_off) == -1 ||
+ lseek(server_context->log_context.log_fd, log_off, SEEK_SET) == -1) {
+ (void) kadm5_log_end(server_context);
+ if (unlink(server_context->log_context.log_file) == -1) {
+ krb5_err(context, IPROPD_FATAL, errno,
+ "Failed to recover from failure to write log "
+ "entries from master to disk");
+ }
+ ret2 = kadm5_log_init(server_context);
+ if (ret2) {
+ krb5_err(context, IPROPD_RESTART_SLOW, ret2,
+ "Failed to initialize log to recover from "
+ "failure to write log entries from master to disk");
+ }
+ }
+ if (ret == ENOSPC || ret == EDQUOT || ret == EFBIG) {
+ /* Unlink the file in these cases. */
+ krb5_warn(context, IPROPD_RESTART_SLOW,
+ "Failed to write log entries from master to disk");
+ (void) kadm5_log_end(server_context);
+ if (unlink(server_context->log_context.log_file) == -1) {
+ krb5_err(context, IPROPD_FATAL, errno,
+ "Failed to recover from failure to write log "
+ "entries from master to disk");
+ }
+ ret2 = kadm5_log_init(server_context);
+ if (ret2) {
+ krb5_err(context, IPROPD_RESTART_SLOW, ret2,
+ "Failed to initialize log to recover from "
+ "failure to write log entries from master to disk");
+ }
+ return ret;
+ }
+ /*
+ * All other errors we treat as fatal here. This includes, for
+ * example, EIO and EPIPE (sorry, can't log to pipes nor sockets).
+ */
+ krb5_err(context, IPROPD_FATAL, ret,
+ "Failed to write log entries from master to disk");
+}
+
+static int
+receive_loop(krb5_context context,
+ krb5_storage *sp,
+ kadm5_server_context *server_context)
+{
+ int ret;
+ off_t left, right, off;
+ uint32_t len, vers;
+
+ if (verbose)
+ krb5_warnx(context, "receiving diffs");
+
+ ret = kadm5_log_exclusivelock(server_context);
+ if (ret)
+ krb5_err(context, IPROPD_RESTART, ret,
+ "Failed to lock iprop log for writes");
+
+ /*
+ * Seek to the first entry in the message from the master that is
+ * past the current version of the local database.
+ */
+ do {
+ uint32_t timestamp;
+ uint32_t op;
+
+ if ((ret = krb5_ret_uint32(sp, &vers)) == HEIM_ERR_EOF) {
+ krb5_warnx(context, "master sent no new iprop entries");
+ return 0;
+ }
+
+ /*
+ * TODO We could do more to validate the entries from the master
+ * here. And we could use/reuse more kadm5_log_*() code here.
+ *
+ * Alternatively we should trust that the master sent us exactly
+ * what we needed and just write this to the log file and let
+ * kadm5_log_recover() do the rest.
+ */
+ if (ret || krb5_ret_uint32(sp, &timestamp) != 0 ||
+ krb5_ret_uint32(sp, &op) != 0 ||
+ krb5_ret_uint32(sp, &len) != 0) {
+
+ /*
+ * This shouldn't happen. Reconnecting probably won't help
+ * if it does happen, but by reconnecting we get a chance to
+ * connect to a new master if a new one is configured.
+ */
+ krb5_warnx(context, "iprop entries from master were truncated");
+ return EINVAL;
+ }
+ if (vers > server_context->log_context.version) {
+ break;
+ }
+ off = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (krb5_storage_seek(sp, len + 8, SEEK_CUR) != off + len + 8) {
+ krb5_warnx(context, "iprop entries from master were truncated");
+ return EINVAL;
+ }
+ if (verbose) {
+ krb5_warnx(context, "diff contains old log record version "
+ "%u %lld %u length %u",
+ vers, (long long)timestamp, op, len);
+ }
+ } while(vers <= server_context->log_context.version);
+
+ /*
+ * Read the remaining entries into memory...
+ */
+ /* SEEK_CUR is a header into the first entry we care about */
+ left = krb5_storage_seek(sp, -16, SEEK_CUR);
+ right = krb5_storage_seek(sp, 0, SEEK_END);
+ if (right - left < 24 + len) {
+ krb5_warnx(context, "iprop entries from master were truncated");
+ return EINVAL;
+ }
+
+ /*
+ * ...and then write them out to the on-disk log.
+ */
+
+ ret = append_to_log_file(context, server_context, sp, left, right - left);
+ if (ret)
+ return ret;
+
+ /*
+ * Replay the new entries.
+ */
+ if (verbose)
+ krb5_warnx(context, "replaying entries from master");
+ ret = kadm5_log_recover(server_context, kadm_recover_replay);
+ if (ret) {
+ krb5_warn(context, ret, "replay failed");
+ return ret;
+ }
+
+ ret = kadm5_log_get_version(server_context, &vers);
+ if (ret) {
+ krb5_warn(context, ret,
+ "could not get log version after applying diffs!");
+ return ret;
+ }
+ if (verbose)
+ krb5_warnx(context, "slave at version %u", vers);
+
+ if (vers != server_context->log_context.version) {
+ krb5_warnx(context, "slave's log_context version (%u) is "
+ "inconsistent with log's version (%u)",
+ server_context->log_context.version, vers);
+ }
+
+ return 0;
+}
+
+static int
+receive(krb5_context context,
+ krb5_storage *sp,
+ kadm5_server_context *server_context)
+{
+ krb5_error_code ret, ret2;
+ HDB *mydb = server_context->db;
+
+ ret = mydb->hdb_open(context, server_context->db, O_RDWR | O_CREAT, 0600);
+ if (ret)
+ krb5_err(context, IPROPD_RESTART_SLOW, ret, "db->open");
+
+ (void) mydb->hdb_set_sync(context, mydb, !async_hdb);
+ ret2 = receive_loop(context, sp, server_context);
+ if (ret2)
+ krb5_warn(context, ret2, "receive from ipropd-master had errors");
+
+ ret = mydb->hdb_close(context, server_context->db);
+ if (ret)
+ krb5_err(context, IPROPD_RESTART_SLOW, ret, "db->close");
+
+ (void) kadm5_log_sharedlock(server_context);
+ if (verbose)
+ krb5_warnx(context, "downgraded iprop log lock to shared");
+ kadm5_log_signal_master(server_context);
+ if (verbose)
+ krb5_warnx(context, "signaled master for hierarchical iprop");
+ return ret2;
+}
+
+static void
+send_im_here(krb5_context context, int fd,
+ krb5_auth_context auth_context)
+{
+ krb5_storage *sp;
+ krb5_data data;
+ krb5_error_code ret;
+
+ ret = krb5_data_alloc(&data, 4);
+ if (ret)
+ krb5_err(context, IPROPD_RESTART, ret, "send_im_here");
+
+ sp = krb5_storage_from_data (&data);
+ if (sp == NULL)
+ krb5_errx(context, IPROPD_RESTART, "krb5_storage_from_data");
+ ret = krb5_store_uint32(sp, I_AM_HERE);
+ krb5_storage_free(sp);
+
+ if (ret == 0) {
+ ret = krb5_write_priv_message(context, auth_context, &fd, &data);
+ krb5_data_free(&data);
+
+ if (ret)
+ krb5_err(context, IPROPD_RESTART, ret, "krb5_write_priv_message");
+
+ if (verbose)
+ krb5_warnx(context, "pinged master");
+ }
+
+ return;
+}
+
+static void
+reinit_log(krb5_context context,
+ kadm5_server_context *server_context,
+ uint32_t vno)
+{
+ krb5_error_code ret;
+
+ if (verbose)
+ krb5_warnx(context, "truncating log on slave");
+
+ ret = kadm5_log_reinit(server_context, vno);
+ if (ret)
+ krb5_err(context, IPROPD_RESTART_SLOW, ret, "kadm5_log_reinit");
+ (void) kadm5_log_sharedlock(server_context);
+ if (verbose)
+ krb5_warnx(context, "downgraded iprop log lock to shared");
+}
+
+
+static krb5_error_code
+receive_everything(krb5_context context, int fd,
+ kadm5_server_context *server_context,
+ krb5_auth_context auth_context)
+{
+ int ret;
+ krb5_data data;
+ uint32_t vno = 0;
+ uint32_t opcode;
+ krb5_storage *sp;
+
+ char *dbname;
+ HDB *mydb;
+
+ krb5_warnx(context, "receive complete database");
+
+ ret = kadm5_log_exclusivelock(server_context);
+ if (ret)
+ krb5_err(context, IPROPD_RESTART, ret,
+ "Failed to lock iprop log for writes");
+ if (server_context->db->hdb_method_name) {
+ ret = asprintf(&dbname, "%.*s:%s-NEW",
+ (int) strlen(server_context->db->hdb_method_name) - 1,
+ server_context->db->hdb_method_name,
+ server_context->db->hdb_name);
+ } else {
+ ret = asprintf(&dbname, "%s-NEW", server_context->db->hdb_name);
+ }
+ if (ret == -1)
+ krb5_err(context, IPROPD_RESTART, ENOMEM, "asprintf");
+ ret = hdb_create(context, &mydb, dbname);
+ if(ret)
+ krb5_err(context, IPROPD_RESTART, ret, "hdb_create");
+ free(dbname);
+
+ ret = hdb_set_master_keyfile(context,
+ mydb, server_context->config.stash_file);
+ if(ret)
+ krb5_err(context, IPROPD_RESTART, ret, "hdb_set_master_keyfile");
+
+ /* I really want to use O_EXCL here, but given that I can't easily clean
+ up on error, I won't */
+ ret = mydb->hdb_open(context, mydb, O_RDWR | O_CREAT | O_TRUNC, 0600);
+ if (ret)
+ krb5_err(context, IPROPD_RESTART, ret, "db->open");
+
+ (void) mydb->hdb_set_sync(context, mydb, 0);
+
+ sp = NULL;
+ krb5_data_zero(&data);
+ do {
+ ret = krb5_read_priv_message(context, auth_context, &fd, &data);
+
+ if (ret) {
+ krb5_warn(context, ret, "krb5_read_priv_message");
+ goto cleanup;
+ }
+
+ sp = krb5_storage_from_data(&data);
+ if (sp == NULL)
+ krb5_errx(context, IPROPD_RESTART, "krb5_storage_from_data");
+ krb5_ret_uint32(sp, &opcode);
+ if (opcode == ONE_PRINC) {
+ krb5_data fake_data;
+ hdb_entry entry;
+
+ krb5_storage_free(sp);
+
+ fake_data.data = (char *)data.data + 4;
+ fake_data.length = data.length - 4;
+
+ memset(&entry, 0, sizeof(entry));
+
+ ret = hdb_value2entry(context, &fake_data, &entry);
+ if (ret)
+ krb5_err(context, IPROPD_RESTART, ret, "hdb_value2entry");
+ ret = mydb->hdb_store(server_context->context,
+ mydb,
+ 0, &entry);
+ if (ret)
+ krb5_err(context, IPROPD_RESTART_SLOW, ret, "hdb_store");
+
+ hdb_free_entry(context, mydb, &entry);
+ krb5_data_free(&data);
+ } else if (opcode == NOW_YOU_HAVE)
+ ;
+ else
+ krb5_errx(context, 1, "strange opcode %d", opcode);
+ } while (opcode == ONE_PRINC);
+
+ if (opcode != NOW_YOU_HAVE)
+ krb5_errx(context, IPROPD_RESTART_SLOW,
+ "receive_everything: strange %d", opcode);
+
+ krb5_ret_uint32(sp, &vno);
+ krb5_storage_free(sp);
+
+ reinit_log(context, server_context, vno);
+
+ ret = mydb->hdb_set_sync(context, mydb, !async_hdb);
+ if (ret)
+ krb5_err(context, IPROPD_RESTART_SLOW, ret, "failed to sync the received HDB");
+ ret = mydb->hdb_close(context, mydb);
+ if (ret)
+ krb5_err(context, IPROPD_RESTART_SLOW, ret, "db->close");
+
+ ret = mydb->hdb_rename(context, mydb, server_context->db->hdb_name);
+ if (ret)
+ krb5_err(context, IPROPD_RESTART_SLOW, ret, "db->rename");
+
+
+ return 0;
+
+ cleanup:
+ krb5_data_free(&data);
+
+ if (ret)
+ krb5_err(context, IPROPD_RESTART_SLOW, ret, "db->close");
+
+ ret = mydb->hdb_destroy(context, mydb);
+ if (ret)
+ krb5_err(context, IPROPD_RESTART, ret, "db->destroy");
+
+ krb5_warnx(context, "receive complete database, version %ld", (long)vno);
+ return ret;
+}
+
+static void
+slave_status(krb5_context context,
+ const char *file,
+ const char *status, ...)
+ __attribute__ ((__format__ (__printf__, 3, 4)));
+
+
+static void
+slave_status(krb5_context context,
+ const char *file,
+ const char *fmt, ...)
+{
+ char *status;
+ char *fmt2;
+ va_list args;
+ int len;
+
+ if (asprintf(&fmt2, "%s\n", fmt) == -1 || fmt2 == NULL) {
+ (void) unlink(file);
+ return;
+ }
+ va_start(args, fmt);
+ len = vasprintf(&status, fmt2, args);
+ free(fmt2);
+ va_end(args);
+ if (len < 0 || status == NULL) {
+ (void) unlink(file);
+ return;
+ }
+ rk_dumpdata(file, status, len);
+ krb5_warnx(context, "slave status change: %s", status);
+ free(status);
+}
+
+static void
+is_up_to_date(krb5_context context, const char *file,
+ kadm5_server_context *server_context)
+{
+ krb5_error_code ret;
+ char buf[80];
+ ret = krb5_format_time(context, time(NULL), buf, sizeof(buf), 1);
+ if (ret) {
+ unlink(file);
+ return;
+ }
+ slave_status(context, file, "up-to-date with version: %lu at %s",
+ (unsigned long)server_context->log_context.version, buf);
+}
+
+static char *database;
+static char *status_file;
+static char *config_file;
+static int version_flag;
+static int help_flag;
+static char *keytab_str;
+static char *port_str;
+static int detach_from_console;
+static int daemon_child = -1;
+
+static struct getargs args[] = {
+ { "config-file", 'c', arg_string, &config_file, NULL, NULL },
+ { "realm", 'r', arg_string, &realm, NULL, NULL },
+ { "database", 'd', arg_string, &database, "database", "file"},
+ { "keytab", 'k', arg_string, &keytab_str,
+ "keytab to get authentication from", "kspec" },
+ { "time-lost", 0, arg_string, &server_time_lost,
+ "time before server is considered lost", "time" },
+ { "status-file", 0, arg_string, &status_file,
+ "file to write out status into", "file" },
+ { "port", 0, arg_string, &port_str,
+ "port ipropd-slave will connect to", "port"},
+ { "detach", 0, arg_flag, &detach_from_console,
+ "detach from console", NULL },
+ { "daemon-child", 0, arg_integer, &daemon_child,
+ "private argument, do not use", NULL },
+ { "pidfile-basename", 0, arg_string, &pidfile_basename,
+ "basename of pidfile; private argument for testing", "NAME" },
+ { "async-hdb", 'a', arg_flag, &async_hdb, NULL, NULL },
+ { "hostname", 0, arg_string, rk_UNCONST(&slave_str),
+ "hostname of slave (if not same as hostname)", "hostname" },
+ { "verbose", 0, arg_flag, &verbose, NULL, NULL },
+ { "version", 0, arg_flag, &version_flag, NULL, NULL },
+ { "help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+
+static int num_args = sizeof(args) / sizeof(args[0]);
+
+static void
+usage(int status)
+{
+ arg_printusage(args, num_args, NULL, "master");
+ exit(status);
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_error_code ret, ret2;
+ krb5_context context;
+ krb5_auth_context auth_context;
+ void *kadm_handle;
+ kadm5_server_context *server_context;
+ kadm5_config_params conf;
+ int master_fd;
+ krb5_ccache ccache;
+ krb5_principal server;
+ char **files;
+ int optidx = 0;
+ time_t reconnect_min;
+ time_t backoff;
+ time_t reconnect_max;
+ time_t reconnect;
+ time_t before = 0;
+ int restarter_fd = -1;
+
+ const char *master;
+
+ setprogname(argv[0]);
+
+ if (getarg(args, num_args, argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage(0);
+
+ if (version_flag) {
+ print_version(NULL);
+ exit(0);
+ }
+
+ if (detach_from_console && daemon_child == -1)
+ daemon_child = roken_detach_prep(argc, argv, "--daemon-child");
+ rk_pidfile(pidfile_basename);
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ setup_signal();
+
+ if (config_file == NULL) {
+ if (asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context)) == -1
+ || config_file == NULL)
+ errx(1, "out of memory");
+ }
+
+ ret = krb5_prepend_config_files_default(config_file, &files);
+ if (ret)
+ krb5_err(context, 1, ret, "getting configuration files");
+
+ ret = krb5_set_config_files(context, files);
+ krb5_free_config_files(files);
+ if (ret)
+ krb5_err(context, 1, ret, "reading configuration files");
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (argc != 1)
+ usage(1);
+
+ master = argv[0];
+
+ if (status_file == NULL) {
+ if (asprintf(&status_file, "%s/ipropd-slave-status", hdb_db_dir(context)) < 0 || status_file == NULL)
+ krb5_errx(context, 1, "can't allocate status file buffer");
+ }
+
+ krb5_openlog(context, "ipropd-slave", &log_facility);
+ krb5_set_warn_dest(context, log_facility);
+
+ slave_status(context, status_file, "bootstrapping");
+
+ ret = krb5_kt_register(context, &hdb_get_kt_ops);
+ if(ret)
+ krb5_err(context, 1, ret, "krb5_kt_register");
+
+ time_before_lost = parse_time (server_time_lost, "s");
+ if (time_before_lost < 0)
+ krb5_errx (context, 1, "couldn't parse time: %s", server_time_lost);
+
+ slave_status(context, status_file, "getting credentials from keytab/database");
+
+ memset(&conf, 0, sizeof(conf));
+ if(realm) {
+ conf.mask |= KADM5_CONFIG_REALM;
+ conf.realm = realm;
+ }
+ if (database) {
+ conf.mask |= KADM5_CONFIG_DBNAME;
+ conf.dbname = database;
+ }
+ ret = kadm5_init_with_password_ctx (context,
+ KADM5_ADMIN_SERVICE,
+ NULL,
+ KADM5_ADMIN_SERVICE,
+ &conf, 0, 0,
+ &kadm_handle);
+ if (ret)
+ krb5_err (context, 1, ret, "kadm5_init_with_password_ctx");
+
+ server_context = (kadm5_server_context *)kadm_handle;
+
+ slave_status(context, status_file, "creating log file");
+
+ ret = server_context->db->hdb_open(context,
+ server_context->db,
+ O_RDWR | O_CREAT, 0600);
+ if (ret)
+ krb5_err (context, 1, ret, "db->open");
+
+ ret = kadm5_log_init(server_context);
+ if (ret)
+ krb5_err(context, 1, ret, "kadm5_log_init");
+ (void) kadm5_log_sharedlock(server_context);
+ if (verbose)
+ krb5_warnx(context, "downgraded iprop log lock to shared");
+
+ ret = server_context->db->hdb_close(context, server_context->db);
+ if (ret)
+ krb5_err(context, 1, ret, "db->close");
+
+ get_creds(context, keytab_str, &ccache, master);
+
+ ret = krb5_sname_to_principal (context, master, IPROP_NAME,
+ KRB5_NT_SRV_HST, &server);
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_sname_to_principal");
+
+ auth_context = NULL;
+ master_fd = -1;
+
+ krb5_appdefault_time(context, config_name, NULL, "reconnect-min",
+ 10, &reconnect_min);
+ krb5_appdefault_time(context, config_name, NULL, "reconnect-max",
+ 300, &reconnect_max);
+ krb5_appdefault_time(context, config_name, NULL, "reconnect-backoff",
+ 10, &backoff);
+ reconnect = reconnect_min;
+
+ slave_status(context, status_file, "ipropd-slave started");
+
+ roken_detach_finish(NULL, daemon_child);
+ restarter_fd = restarter(context, NULL);
+
+ while (!exit_flag) {
+ struct timeval to;
+ time_t now, elapsed;
+ fd_set readset;
+ int connected = FALSE;
+
+#ifndef NO_LIMIT_FD_SETSIZE
+ if (restarter_fd >= FD_SETSIZE)
+ krb5_errx(context, IPROPD_RESTART, "fd too large");
+#endif
+
+ FD_ZERO(&readset);
+ if (restarter_fd > -1)
+ FD_SET(restarter_fd, &readset);
+
+ now = time(NULL);
+ elapsed = now - before;
+
+ if (elapsed < reconnect) {
+ time_t left = reconnect - elapsed;
+ krb5_warnx(context, "sleeping %d seconds before "
+ "retrying to connect", (int)left);
+ to.tv_sec = left;
+ to.tv_usec = 0;
+ if (select(restarter_fd + 1, &readset, NULL, NULL, &to) == 1) {
+ exit_flag = SIGTERM;
+ continue;
+ }
+ }
+ before = now;
+
+ slave_status(context, status_file, "connecting to master: %s\n", master);
+
+ master_fd = connect_to_master (context, master, port_str);
+ if (master_fd < 0)
+ goto retry;
+
+ reconnect = reconnect_min;
+
+ if (auth_context) {
+ krb5_auth_con_free(context, auth_context);
+ auth_context = NULL;
+ krb5_cc_destroy(context, ccache);
+ get_creds(context, keytab_str, &ccache, master);
+ }
+ if (verbose)
+ krb5_warnx(context, "authenticating to master");
+ ret = krb5_sendauth (context, &auth_context, &master_fd,
+ IPROP_VERSION, NULL, server,
+ AP_OPTS_MUTUAL_REQUIRED, NULL, NULL,
+ ccache, NULL, NULL, NULL);
+ if (ret) {
+ krb5_warn (context, ret, "krb5_sendauth");
+ goto retry;
+ }
+
+ krb5_warnx(context, "ipropd-slave started at version: %ld",
+ (long)server_context->log_context.version);
+
+ ret = ihave(context, auth_context, master_fd,
+ server_context->log_context.version);
+ if (ret)
+ goto retry;
+
+ connected = TRUE;
+
+ if (verbose)
+ krb5_warnx(context, "connected to master");
+
+ slave_status(context, status_file, "connected to master, waiting instructions");
+
+ while (connected && !exit_flag) {
+ krb5_data out;
+ krb5_storage *sp;
+ uint32_t tmp;
+ int max_fd;
+
+#ifndef NO_LIMIT_FD_SETSIZE
+ if (master_fd >= FD_SETSIZE)
+ krb5_errx(context, IPROPD_RESTART, "fd too large");
+ if (restarter_fd >= FD_SETSIZE)
+ krb5_errx(context, IPROPD_RESTART, "fd too large");
+ max_fd = max(restarter_fd, master_fd);
+#endif
+
+ FD_ZERO(&readset);
+ FD_SET(master_fd, &readset);
+ if (restarter_fd != -1)
+ FD_SET(restarter_fd, &readset);
+
+ to.tv_sec = time_before_lost;
+ to.tv_usec = 0;
+
+ ret = select (max_fd + 1,
+ &readset, NULL, NULL, &to);
+ if (ret < 0) {
+ if (errno == EINTR)
+ continue;
+ else
+ krb5_err (context, 1, errno, "select");
+ }
+ if (ret == 0) {
+ krb5_warnx(context, "server didn't send a message "
+ "in %d seconds", time_before_lost);
+ connected = FALSE;
+ continue;
+ }
+
+ if (restarter_fd > -1 && FD_ISSET(restarter_fd, &readset)) {
+ if (verbose)
+ krb5_warnx(context, "slave restarter exited");
+ exit_flag = SIGTERM;
+ }
+
+ if (!FD_ISSET(master_fd, &readset))
+ continue;
+
+ if (verbose)
+ krb5_warnx(context, "message from master");
+
+ ret = krb5_read_priv_message(context, auth_context, &master_fd, &out);
+ if (ret) {
+ krb5_warn(context, ret, "krb5_read_priv_message");
+ connected = FALSE;
+ continue;
+ }
+
+ sp = krb5_storage_from_mem (out.data, out.length);
+ if (sp == NULL)
+ krb5_err(context, IPROPD_RESTART, errno, "krb5_storage_from_mem");
+ ret = krb5_ret_uint32(sp, &tmp);
+ if (ret == HEIM_ERR_EOF) {
+ krb5_warn(context, ret, "master sent zero-length message");
+ connected = FALSE;
+ continue;
+ }
+ if (ret != 0) {
+ krb5_warn(context, ret, "couldn't read master's message");
+ connected = FALSE;
+ continue;
+ }
+
+ /*
+ * It's unclear why we open th HDB and call kadm5_log_init() here.
+ *
+ * We don't need it to process the log entries we receive in the
+ * FOR_YOU case: we already call kadm5_log_recover() in receive() /
+ * receive_loop(). Maybe it's just just in case, though at the
+ * cost of synchronization with ipropd-master if we're running one
+ * for hierarchical iprop.
+ */
+ ret = server_context->db->hdb_open(context,
+ server_context->db,
+ O_RDWR | O_CREAT, 0600);
+ if (ret)
+ krb5_err (context, 1, ret, "db->open while handling a "
+ "message from the master");
+ ret = kadm5_log_init(server_context);
+ if (ret) {
+ krb5_err(context, IPROPD_RESTART, ret, "kadm5_log_init while "
+ "handling a message from the master");
+ }
+ (void) kadm5_log_sharedlock(server_context);
+ if (verbose)
+ krb5_warnx(context, "downgraded iprop log lock to shared");
+
+ ret = server_context->db->hdb_close (context, server_context->db);
+ if (ret)
+ krb5_err (context, 1, ret, "db->close while handling a "
+ "message from the master");
+
+ switch (tmp) {
+ case FOR_YOU :
+ if (verbose)
+ krb5_warnx(context, "master sent us diffs");
+ ret2 = receive(context, sp, server_context);
+ if (ret2)
+ krb5_warn(context, ret2,
+ "receive from ipropd-master had errors");
+ ret = ihave(context, auth_context, master_fd,
+ server_context->log_context.version);
+ if (ret || ret2)
+ connected = FALSE;
+
+ /*
+ * If it returns an error, receive() may nonetheless
+ * have committed some entries successfully, so we must
+ * update the slave_status even if there were errors.
+ */
+ is_up_to_date(context, status_file, server_context);
+ break;
+ case TELL_YOU_EVERYTHING :
+ if (verbose)
+ krb5_warnx(context, "master sent us a full dump");
+ ret = receive_everything(context, master_fd, server_context,
+ auth_context);
+ (void) kadm5_log_sharedlock(server_context);
+ if (ret == 0) {
+ ret = ihave(context, auth_context, master_fd,
+ server_context->log_context.version);
+ }
+ if (ret)
+ connected = FALSE;
+ else
+ is_up_to_date(context, status_file, server_context);
+ if (verbose)
+ krb5_warnx(context, "downgraded iprop log lock to shared");
+ kadm5_log_signal_master(server_context);
+ if (verbose)
+ krb5_warnx(context, "signaled master for hierarchical iprop");
+ break;
+ case ARE_YOU_THERE :
+ if (verbose)
+ krb5_warnx(context, "master sent us a ping");
+ is_up_to_date(context, status_file, server_context);
+ /*
+ * We used to send an I_HAVE here. But the master may send
+ * ARE_YOU_THERE messages in response to local, possibly-
+ * transient errors, and if that happens and we respond with an
+ * I_HAVE then we'll loop hard if the error was not transient.
+ *
+ * So we don't ihave() here.
+ */
+ send_im_here(context, master_fd, auth_context);
+ break;
+ case YOU_HAVE_LAST_VERSION:
+ if (verbose)
+ krb5_warnx(context, "master tells us we are up to date");
+ is_up_to_date(context, status_file, server_context);
+ break;
+ case NOW_YOU_HAVE :
+ case I_HAVE :
+ case ONE_PRINC :
+ case I_AM_HERE :
+ default :
+ krb5_warnx (context, "Ignoring command %d", tmp);
+ break;
+ }
+ krb5_storage_free (sp);
+ krb5_data_free (&out);
+
+ }
+
+ slave_status(context, status_file, "disconnected from master");
+ retry:
+ if (connected == FALSE)
+ krb5_warnx (context, "disconnected for server");
+
+ if (exit_flag)
+ krb5_warnx (context, "got an exit signal");
+
+ if (master_fd >= 0)
+ close(master_fd);
+
+ reconnect += backoff;
+ if (reconnect > reconnect_max) {
+ slave_status(context, status_file, "disconnected from master for a long time");
+ reconnect = reconnect_max;
+ }
+ }
+
+ if (status_file) {
+ /* XXX It'd be better to leave it saying we're not here */
+ unlink(status_file);
+ }
+
+ if (0);
+#ifndef NO_SIGXCPU
+ else if(exit_flag == SIGXCPU)
+ krb5_warnx(context, "%s CPU time limit exceeded", getprogname());
+#endif
+ else if(exit_flag == SIGINT || exit_flag == SIGTERM)
+ krb5_warnx(context, "%s terminated", getprogname());
+ else
+ krb5_warnx(context, "%s unexpected exit reason: %ld",
+ getprogname(), (long)exit_flag);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/kadm5-hook.h b/third_party/heimdal/lib/kadm5/kadm5-hook.h
new file mode 100644
index 0000000..7d47f55
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/kadm5-hook.h
@@ -0,0 +1,151 @@
+/*
+ * Copyright 2010
+ * The Board of Trustees of the Leland Stanford Junior University
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef KADM5_HOOK_H
+#define KADM5_HOOK_H 1
+
+#define KADM5_HOOK_VERSION_V1 1
+
+#include <heimbase-svc.h>
+
+/*
+ * Each hook is called before the operation using KADM5_STAGE_PRECOMMIT and
+ * then after the operation using KADM5_STAGE_POSTCOMMIT. If the hook returns
+ * failure during precommit, the operation is aborted without changes to the
+ * database. All post-commit hook are invoked if the operation was attempted.
+ *
+ * Note that unlike libkrb5 plugins, returning success does not prevent other
+ * plugins being called (i.e. it is equivalent to KRB5_PLUGIN_NO_HANDLE).
+ */
+enum kadm5_hook_stage {
+ KADM5_HOOK_STAGE_PRECOMMIT,
+ KADM5_HOOK_STAGE_POSTCOMMIT
+};
+
+#define KADM5_HOOK_FLAG_KEEPOLD 0x1 /* keep old password */
+#define KADM5_HOOK_FLAG_CONDITIONAL 0x2 /* only change password if different */
+
+typedef struct kadm5_hook_ftable {
+ HEIM_PLUGIN_FTABLE_COMMON_ELEMENTS(krb5_context);
+
+ const char *name;
+ const char *vendor;
+
+ /*
+ * Hook functions; NULL functions are ignored. code is only valid on
+ * post-commit hooks and represents the result of the commit. Post-
+ * commit hooks are not called if a pre-commit hook aborted the call.
+ */
+ krb5_error_code (KRB5_CALLCONV *chpass)(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ,
+ uint32_t flags,
+ size_t n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ const char *password);
+
+ krb5_error_code (KRB5_CALLCONV *chpass_with_key)(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ,
+ uint32_t flags,
+ size_t n_key_data,
+ krb5_key_data *key_data);
+
+ krb5_error_code (KRB5_CALLCONV *create)(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ kadm5_principal_ent_t ent,
+ uint32_t mask,
+ const char *password);
+
+ krb5_error_code (KRB5_CALLCONV *modify)(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ kadm5_principal_ent_t ent,
+ uint32_t mask);
+
+ krb5_error_code (KRB5_CALLCONV *delete)(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ);
+
+ krb5_error_code (KRB5_CALLCONV *randkey)(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ);
+
+ krb5_error_code (KRB5_CALLCONV *rename)(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal source,
+ krb5_const_principal target);
+
+ krb5_error_code (KRB5_CALLCONV *set_keys)(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ,
+ uint32_t flags,
+ size_t n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ size_t n_keys,
+ krb5_keyblock *keyblocks);
+
+ krb5_error_code (KRB5_CALLCONV *prune)(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ,
+ int kvno);
+
+} kadm5_hook_ftable;
+
+/*
+ * libkadm5srv expects a symbol named kadm5_hook_plugin_load that must be a
+ * function of type kadm5_hook_plugin_load_t.
+ */
+typedef krb5_error_code
+(KRB5_CALLCONV *kadm5_hook_plugin_load_t)(krb5_context context,
+ krb5_get_instance_func_t *func,
+ size_t *n_hooks,
+ const kadm5_hook_ftable *const **hooks);
+
+#endif /* !KADM5_HOOK_H */
diff --git a/third_party/heimdal/lib/kadm5/kadm5-pwcheck.h b/third_party/heimdal/lib/kadm5/kadm5-pwcheck.h
new file mode 100644
index 0000000..70cbae5
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/kadm5-pwcheck.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef KADM5_PWCHECK_H
+#define KADM5_PWCHECK_H 1
+
+
+#define KADM5_PASSWD_VERSION_V0 0
+#define KADM5_PASSWD_VERSION_V1 1
+
+typedef const char* (*kadm5_passwd_quality_check_func_v0)(krb5_context,
+ krb5_principal,
+ krb5_data*);
+
+/*
+ * The 4th argument, is a tuning parameter for the quality check
+ * function, the lib/caller will providing it for the password quality
+ * module.
+ */
+
+typedef int
+(*kadm5_passwd_quality_check_func)(krb5_context context,
+ krb5_principal principal,
+ krb5_data *password,
+ const char *tuning,
+ char *message,
+ size_t length);
+
+struct kadm5_pw_policy_check_func {
+ const char *name;
+ kadm5_passwd_quality_check_func func;
+};
+
+struct kadm5_pw_policy_verifier {
+ const char *name;
+ int version;
+ const char *vendor;
+ const struct kadm5_pw_policy_check_func *funcs;
+};
+
+#endif /* KADM5_PWCHECK_H */
diff --git a/third_party/heimdal/lib/kadm5/kadm5_err.et b/third_party/heimdal/lib/kadm5/kadm5_err.et
new file mode 100644
index 0000000..e9a3a0b
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/kadm5_err.et
@@ -0,0 +1,114 @@
+#
+# Error messages for the kadm5 library
+#
+# This might look like a com_err file, but is not
+#
+id "$Id$"
+
+error_table ovk kadm5
+
+prefix KADM5
+error_code FAILURE, "Operation failed for unspecified reason"
+error_code AUTH_GET, "Operation requires `get' privilege"
+error_code AUTH_ADD, "Operation requires `add' privilege"
+error_code AUTH_MODIFY, "Operation requires `modify' privilege"
+error_code AUTH_DELETE, "Operation requires `delete' privilege"
+error_code AUTH_INSUFFICIENT, "Insufficient authorization for operation"
+error_code BAD_DB, "Database inconsistency detected"
+error_code DUP, "Principal or policy already exists"
+error_code RPC_ERROR, "Communication failure with server"
+error_code NO_SRV, "No administration server found for realm"
+error_code BAD_HIST_KEY, "Password history principal key version mismatch"
+error_code NOT_INIT, "Connection to server not initialized"
+error_code UNK_PRINC, "Principal does not exist"
+error_code UNK_POLICY, "Policy does not exist"
+error_code BAD_MASK, "Invalid field mask for operation"
+error_code BAD_CLASS, "Invalid number of character classes"
+error_code BAD_LENGTH, "Invalid password length"
+error_code BAD_POLICY, "Invalid policy name"
+error_code BAD_PRINCIPAL, "Invalid principal name."
+error_code BAD_AUX_ATTR, "Invalid auxillary attributes"
+error_code BAD_HISTORY, "Invalid password history count"
+error_code BAD_MIN_PASS_LIFE, "Password minimum life is greater than password maximum life"
+error_code PASS_Q_TOOSHORT, "Password is too short"
+error_code PASS_Q_CLASS, "Password does not contain enough character classes"
+error_code PASS_Q_DICT, "Password is in the password dictionary"
+error_code PASS_REUSE, "Can't reuse password"
+error_code PASS_TOOSOON, "Current password's minimum life has not expired"
+error_code POLICY_REF, "Policy is in use"
+error_code INIT, "Connection to server already initialized"
+error_code BAD_PASSWORD, "Incorrect password"
+error_code PROTECT_PRINCIPAL, "Can't change protected principal"
+error_code BAD_SERVER_HANDLE, "Programmer error! Bad Admin server handle"
+error_code BAD_STRUCT_VERSION, "Programmer error! Bad API structure version"
+error_code OLD_STRUCT_VERSION, "API structure version specified by application is no longer supported"
+error_code NEW_STRUCT_VERSION, "API structure version specified by application is unknown to libraries"
+error_code BAD_API_VERSION, "Programmer error! Bad API version"
+error_code OLD_LIB_API_VERSION, "API version specified by application is no longer supported by libraries"
+error_code OLD_SERVER_API_VERSION,"API version specified by application is no longer supported by server"
+error_code NEW_LIB_API_VERSION, "API version specified by application is unknown to libraries"
+error_code NEW_SERVER_API_VERSION,"API version specified by application is unknown to server"
+error_code SECURE_PRINC_MISSING,"Database error! Required principal missing"
+error_code NO_RENAME_SALT, "The salt type of the specified principal does not support renaming"
+error_code BAD_CLIENT_PARAMS, "Invalid configuration parameter for remote KADM5 client"
+error_code BAD_SERVER_PARAMS, "Invalid configuration parameter for local KADM5 client."
+error_code AUTH_LIST, "Operation requires `list' privilege"
+error_code AUTH_CHANGEPW, "Operation requires `change-password' privilege"
+error_code BAD_TL_TYPE, "Invalid tagged data list element type"
+error_code MISSING_CONF_PARAMS, "Required parameters in kdc.conf missing"
+error_code BAD_SERVER_NAME, "Bad krb5 admin server hostname"
+error_code KS_TUPLE_NOSUPP, "Key/salt tuples not supported by this function"
+error_code SETKEY3_ETYPE_MISMATCH, "Key/salt tuples don't match keys"
+error_code DECRYPT_USAGE_NOSUPP, "Given usage of kadm5_decrypt() not supported"
+error_code POLICY_OP_NOSUPP, "Policy operations not supported"
+error_code KEEPOLD_NOSUPP, "Keep old keys option not supported"
+error_code AUTH_GET_KEYS, "Operation requires `get-keys' privilege"
+error_code ALREADY_LOCKED, "Database already locked"
+error_code NOT_LOCKED, "Database not locked"
+error_code LOG_CORRUPT, "Incremental propagation log got corrupted"
+error_code LOG_NEEDS_UPGRADE, "Incremental propagation log must be upgraded"
+error_code BAD_SERVER_HOOK, "Bad KADM5 server hook"
+error_code SERVER_HOOK_NOT_FOUND, "Cannot find KADM5 server hook"
+error_code OLD_SERVER_HOOK_VERSION, "KADM5 server hook is too old for this version of Heimdal"
+error_code NEW_SERVER_HOOK_VERSION, "KADM5 server hook is too new for this version of Heimdal"
+error_code READ_ONLY, "Database is read-only; try primary server"
+error_code PASS_Q_GENERIC, "Unspecified password quality failure"
+
+
+# MIT has:
+#
+# - GSS_ERROR sandwiched by AUTH_CHANGEPW and BAD_TL_TYPE
+# error_code GSS_ERROR, "GSS-API (or Kerberos) error"
+
+# - AUTH_SETKEY, SETKEY_DUP_ENCTYPES, and SETV4KEY_INVAL_ENCTYPE, sandwiched by
+# BAD_SERVER_NAME and SETKEY3_ETYPE_MISMATCH
+# error_code AUTH_SETKEY, "Operation requires ``set-key'' privilege"
+# error_code SETKEY_DUP_ENCTYPES, "Multiple values for single or folded enctype"
+# error_code SETV4KEY_INVAL_ENCTYPE, "Invalid enctype for setv4key"
+
+# - all of the following after SETKEY3_ETYPE_MISMATCH
+# error_code MISSING_KRB5_CONF_PARAMS, "Missing parameters in krb5.conf required for kadmin client"
+# error_code XDR_FAILURE, "XDR encoding error"
+# error_code CANT_RESOLVE, "Cannot resolve network address for admin server in requested realm"
+# error_code BAD_KEYSALTS, "Invalid key/salt tuples"
+# error_code SETKEY_BAD_KVNO, "Invalid multiple or duplicate kvnos in setkey operation"
+# error_code AUTH_EXTRACT, "Operation requires ``extract-keys'' privilege"
+# error_code PROTECT_KEYS, "Principal keys are locked down"
+# error_code AUTH_INITIAL, "Operation requires initial ticket"
+
+# AUTH_EXTRACT is the same as our AUTH_GET_KEYS
+# MISSING_KRB5_CONF_PARAMS is the same as our MISSING_CONF_PARAMS
+
+# We have a number of errors not in MIT:
+# - KS_TUPLE_NOSUPP (no longer relevant)
+# - DECRYPT_USAGE_NOSUPP (could be replaced with some other, no?)
+# - POLICY_OP_NOSUPP (could be made irrelevant)
+# - ALREADY_LOCKED (in MIT KDB locks are recursive)
+# - NOT_LOCKED (KRB5_KDB_NOTLOCKED in MIT)
+# - LOG_CORRUPT (unique to Heimdal)
+# - LOG_NEEDS_UPGRADE (unique to Heimdal)
+# - BAD_SERVER_HOOK (unique to Heimdal, not used in-tree)
+# - SERVER_HOOK_NOT_FOUND (unique to Heimdal, not used in-tree)
+# - OLD_SERVER_HOOK_VERSION (unique to Heimdal, not used in-tree)
+# - NEW_SERVER_HOOK_VERSION (unique to Heimdal, not used in-tree)
+# - READ_ONLY (should not be unique to Heimdal, but is)
diff --git a/third_party/heimdal/lib/kadm5/kadm5_locl.h b/third_party/heimdal/lib/kadm5/kadm5_locl.h
new file mode 100644
index 0000000..cb0b1b4
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/kadm5_locl.h
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 1997-2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __KADM5_LOCL_H__
+#define __KADM5_LOCL_H__
+
+#include <config.h>
+#include <roken.h>
+#include <heimbase.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <assert.h>
+#include <limits.h>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_SYS_FILE_H
+#include <sys/file.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETINET_TCP_H
+#include <netinet/tcp.h>
+#endif
+#ifdef HAVE_SYS_UN_H
+#include <sys/un.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#include <fnmatch.h>
+#include <krb5_locl.h>
+#include "admin.h"
+#include "kadm5_err.h"
+#include <hdb.h>
+#include <der.h>
+#include <parse_units.h>
+#include "private.h"
+
+#endif /* __KADM5_LOCL_H__ */
diff --git a/third_party/heimdal/lib/kadm5/kadm5_pwcheck.3 b/third_party/heimdal/lib/kadm5/kadm5_pwcheck.3
new file mode 100644
index 0000000..5174d9b
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/kadm5_pwcheck.3
@@ -0,0 +1,159 @@
+.\" Copyright (c) 2003 - 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd February 29, 2004
+.Dt KADM5_PWCHECK 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_pwcheck ,
+.Nm kadm5_setup_passwd_quality_check ,
+.Nm kadm5_add_passwd_quality_verifier ,
+.Nm kadm5_check_password_quality
+.Nd Heimdal warning and error functions
+.Sh LIBRARY
+Kerberos 5 Library (libkadm5srv, -lkadm5srv)
+.Sh SYNOPSIS
+.In kadm5-protos.h
+.In kadm5-pwcheck.h
+.Ft void
+.Fo kadm5_setup_passwd_quality_check
+.Fa "krb5_context context"
+.Fa "const char *check_library"
+.Fa "const char *check_function"
+.Fc
+.Ft "krb5_error_code"
+.Fo kadm5_add_passwd_quality_verifier
+.Fa "krb5_context context"
+.Fa "const char *check_library"
+.Fc
+.Ft "const char *"
+.Fo kadm5_check_password_quality
+.Fa "krb5_context context"
+.Fa "krb5_principal principal"
+.Fa "krb5_data *pwd_data"
+.Fc
+.Ft int
+.Fo "(*kadm5_passwd_quality_check_func)"
+.Fa "krb5_context context"
+.Fa "krb5_principal principal"
+.Fa "krb5_data *password"
+.Fa "const char *tuning"
+.Fa "char *message"
+.Fa "size_t length"
+.Fc
+.Sh DESCRIPTION
+These functions perform the quality check for the heimdal database
+library.
+.Pp
+There are two versions of the shared object API; the old version (0)
+is deprecated, but still supported. The new version (1) supports
+multiple password quality checking policies in the same shared object.
+See below for details.
+.Pp
+The password quality checker will run all policies that are
+configured by the user. If any policy rejects the password, the password
+will be rejected.
+.Pp
+Policy names are of the form
+.Ql module-name:policy-name
+or, if the the policy name is unique enough, just
+.Ql policy-name .
+.Sh IMPLEMENTING A PASSWORD QUALITY CHECKING SHARED OBJECT
+(This refers to the version 1 API only.)
+.Pp
+Module shared objects may conveniently be compiled and linked with
+.Xr libtool 1 .
+An object needs to export a symbol called
+.Ql kadm5_password_verifier
+of the type
+.Ft "struct kadm5_pw_policy_verifier" .
+.Pp
+Its
+.Ft name
+and
+.Ft vendor
+fields should contain the obvious information.
+.Ft name
+must match the
+.Ql module-name
+portion of the policy name (the part before the colon), if the policy name
+contains a colon, or the policy will not be run.
+.Ft version
+should be
+.Dv KADM5_PASSWD_VERSION_V1 .
+.Pp
+.Ft funcs
+contains an array of
+.Ft "struct kadm5_pw_policy_check_func"
+structures that is terminated with an entry whose
+.Ft name
+component is
+.Dv NULL .
+The
+.Ft name
+field of the array must match the
+.Ql policy-name
+portion of a policy name (the part after the colon, or the complete policy
+name if there is no colon) specified by the user or the policy will not be
+run. The
+.Ft func
+fields of the array elements are functions that are exported by the
+module to be called to check the password. They get the following
+arguments: the Kerberos context, principal, password, a tuning parameter, and
+a pointer to a message buffer and its length. The tuning parameter
+for the quality check function is currently always
+.Dv NULL .
+If the password is acceptable, the function returns zero. Otherwise
+it returns non-zero and fills in the message buffer with an
+appropriate explanation.
+.Sh RUNNING THE CHECKS
+.Nm kadm5_setup_passwd_quality_check
+sets up type 0 checks. It sets up all type 0 checks defined in
+.Xr krb5.conf 5
+if called with the last two arguments null.
+.Pp
+.Nm kadm5_add_passwd_quality_verifier
+sets up type 1 checks. It sets up all type 1 tests defined in
+.Xr krb5.conf 5
+if called with a null second argument.
+.Nm kadm5_check_password_quality
+runs the checks in the order in which they are defined in
+.Xr krb5.conf 5
+and the order in which they occur in a
+module's
+.Ft funcs
+array until one returns non-zero.
+.Sh SEE ALSO
+.Xr libtool 1 ,
+.Xr krb5 3 ,
+.Xr krb5.conf 5
diff --git a/third_party/heimdal/lib/kadm5/keys.c b/third_party/heimdal/lib/kadm5/keys.c
new file mode 100644
index 0000000..ed7cc83
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/keys.c
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+/*
+ * free all the memory used by (len, keys)
+ */
+
+void
+_kadm5_free_keys (krb5_context context,
+ int len, Key *keys)
+{
+ hdb_free_keys(context, len, keys);
+}
+
+/*
+ * null-ify `len', `keys'
+ */
+
+void
+_kadm5_init_keys (Key *keys, int len)
+{
+ int i;
+
+ for (i = 0; i < len; ++i) {
+ keys[i].mkvno = NULL;
+ keys[i].salt = NULL;
+ keys[i].key.keyvalue.length = 0;
+ keys[i].key.keyvalue.data = NULL;
+ }
+}
+
+
+/*
+ * return 1 if any key in `keys1, len1' exists in `keys2, len2'
+ */
+static int
+_kadm5_exists_keys(Key *keys1, int len1, Key *keys2, int len2)
+{
+ size_t i, j;
+ size_t optimize;
+
+ for (i = 0; i < len1; ++i) {
+ optimize = 0;
+ for (j = 0; j < len2; j++) {
+ if ((keys1[i].salt != NULL && keys2[j].salt == NULL)
+ || (keys1[i].salt == NULL && keys2[j].salt != NULL))
+ continue;
+
+ if (keys1[i].salt != NULL) {
+ if (keys1[i].salt->type != keys2[j].salt->type)
+ continue;
+ if (keys1[i].salt->salt.length != keys2[j].salt->salt.length)
+ continue;
+ if (memcmp (keys1[i].salt->salt.data, keys2[j].salt->salt.data,
+ keys1[i].salt->salt.length) != 0)
+ continue;
+ }
+ if (keys1[i].key.keytype != keys2[j].key.keytype)
+ continue;
+ optimize = 1;
+ if (keys1[i].key.keyvalue.length != keys2[j].key.keyvalue.length)
+ continue;
+ if (memcmp (keys1[i].key.keyvalue.data, keys2[j].key.keyvalue.data,
+ keys1[i].key.keyvalue.length) != 0)
+ continue;
+
+ return 1;
+ }
+
+ /*
+ * Optimization: no need to check all of keys1[] if one there
+ * was one key in keys2[] with matching enctype and salt but not
+ * matching key. Assumption: all keys in keys1[] and keys2[]
+ * are output by string2key.
+ */
+ if (optimize)
+ return 0;
+ }
+ return 0;
+}
+
+/*
+ * return 1 if any key in `keys1, len1' exists in hist_keys
+ */
+int
+_kadm5_exists_keys_hist(Key *keys1, int len1, HDB_Ext_KeySet *hist_keys)
+{
+ size_t i;
+
+ for (i = 0; i < hist_keys->len; i++) {
+ if (_kadm5_exists_keys(keys1, len1,
+ hist_keys->val[i].keys.val,
+ hist_keys->val[i].keys.len))
+ return 1;
+ }
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/libkadm5srv-exports.def b/third_party/heimdal/lib/kadm5/libkadm5srv-exports.def
new file mode 100644
index 0000000..72ba417
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/libkadm5srv-exports.def
@@ -0,0 +1,91 @@
+EXPORTS
+;! kadm5_ad_init_with_password
+;! kadm5_ad_init_with_password_ctx
+ kadm5_add_passwd_quality_verifier
+ kadm5_all_keys_are_bogus
+ kadm5_check_password_quality
+ kadm5_chpass_principal
+ kadm5_chpass_principal_3
+ kadm5_chpass_principal_with_key
+ kadm5_chpass_principal_with_key_3
+ kadm5_create_policy
+ kadm5_create_principal
+ kadm5_create_principal_3
+ kadm5_decrypt_key
+ kadm5_delete_policy
+ kadm5_delete_principal
+ kadm5_destroy
+ kadm5_flush
+ kadm5_free_key_data
+ kadm5_free_name_list
+ kadm5_free_policy_ent
+ kadm5_free_principal_ent
+ kadm5_get_instance
+ kadm5_get_policies
+ kadm5_get_policy
+ kadm5_get_principal
+ kadm5_get_principals
+ kadm5_get_privs
+ kadm5_init_with_creds
+ kadm5_init_with_creds_ctx
+ kadm5_init_with_password
+ kadm5_init_with_password_ctx
+ kadm5_init_with_skey
+ kadm5_init_with_skey_ctx
+ kadm5_lock
+ kadm5_modify_policy
+ kadm5_modify_principal
+ kadm5_prune_principal
+ kadm5_randkey_principal
+ kadm5_randkey_principal_3
+ kadm5_rename_principal
+ kadm5_ret_key_data
+ kadm5_ret_principal_ent
+ kadm5_ret_principal_ent_mask
+ kadm5_ret_tl_data
+ kadm5_setkey_principal
+ kadm5_setkey_principal_3
+ kadm5_setup_passwd_quality_check
+ kadm5_some_keys_are_bogus
+ kadm5_store_key_data
+ kadm5_store_principal_ent
+ kadm5_store_principal_ent_mask
+ kadm5_store_principal_ent_nokeys
+ kadm5_store_tl_data
+ kadm5_unlock
+ kadm5_s_init_with_password_ctx
+ kadm5_s_init_with_password
+ kadm5_s_init_with_skey_ctx
+ kadm5_s_init_with_skey
+ kadm5_s_init_with_creds_ctx
+ kadm5_s_init_with_creds
+ kadm5_s_chpass_principal_cond
+ kadm5_s_create_principal_with_key
+ kadm5_log_exclusivelock
+ kadm5_log_set_version
+ kadm5_log_sharedlock
+ kadm5_log_signal_master
+;! kadm5_log_signal_socket
+ kadm5_log_signal_socket_info ;!
+ kadm5_log_previous
+ kadm5_log_goto_first
+ kadm5_log_goto_end
+ kadm5_log_foreach
+ kadm5_log_get_version_fd
+ kadm5_log_get_version
+ kadm5_log_recover
+ kadm5_log_replay
+ kadm5_log_end
+ kadm5_log_reinit
+ kadm5_log_init
+ kadm5_log_init_nb
+ kadm5_log_init_nolock
+ kadm5_log_init_sharedlock
+ kadm5_log_next
+ kadm5_log_nop
+ kadm5_log_truncate
+ kadm5_log_modify
+ _kadm5_acl_check_permission
+ _kadm5_unmarshal_params
+ _kadm5_s_get_db
+ _kadm5_privs_to_string
diff --git a/third_party/heimdal/lib/kadm5/libkadm5srv-version.rc b/third_party/heimdal/lib/kadm5/libkadm5srv-version.rc
new file mode 100644
index 0000000..065c18f
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/libkadm5srv-version.rc
@@ -0,0 +1,36 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#define RC_FILE_TYPE VFT_DLL
+#define RC_FILE_DESC_0409 "Heimdal Kerberos v5 Administration Library"
+#define RC_FILE_ORIG_0409 "libkadm5srv.dll"
+
+#include "../../windows/version.rc"
diff --git a/third_party/heimdal/lib/kadm5/log.c b/third_party/heimdal/lib/kadm5/log.c
new file mode 100644
index 0000000..4f66426
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/log.c
@@ -0,0 +1,2756 @@
+/*
+ * Copyright (c) 1997 - 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+#include "heim_threads.h"
+
+RCSID("$Id$");
+
+/*
+ * A log consists of a sequence of records of this form:
+ *
+ * version number 4 bytes -\
+ * time in seconds 4 bytes +> preamble --+> header
+ * operation (enum kadm_ops) 4 bytes -/ /
+ * n, length of payload 4 bytes --------------+
+ * PAYLOAD DATA... n bytes
+ * n, length of payload 4 bytes ----------------+> trailer
+ * version number 4 bytes ->postamble ---/
+ *
+ * I.e., records have a header and a trailer so that knowing the offset
+ * of an record's start or end one can traverse the log forwards and
+ * backwards.
+ *
+ * The log always starts with a nop record (uber record) that contains the
+ * offset (8 bytes) of the first unconfirmed record (typically EOF), and the
+ * version number and timestamp of the preceding last confirmed record:
+ *
+ * offset of next new record 8 bytes
+ * last record time 4 bytes
+ * last record version number 4 bytes
+ *
+ * When an iprop slave receives a complete database, it saves that version as
+ * the last confirmed version, without writing any other records to the log. We
+ * use that version as the basis for further updates.
+ *
+ * kadm5 write operations are done in this order:
+ *
+ * - replay unconfirmed log records
+ * - write (append) and fsync() the log record for the kadm5 update
+ * - update the HDB (which includes fsync() or moral equivalent)
+ * - update the log uber record to mark the log record written as
+ * confirmed (not fsync()ed)
+ *
+ * This makes it possible and safe to seek to the logical end of the log
+ * (that is, the end of the last confirmed record) without traversing
+ * the whole log forward from offset zero. Unconfirmed records (which
+ * -currently- should never be more than one) can then be found (and
+ * rolled forward) by traversing forward from the logical end of the
+ * log. The trailers make it possible to traverse the log backwards
+ * from the logical end.
+ *
+ * This also makes the log + the HDB a two-phase commit with
+ * roll-forward system.
+ *
+ * HDB entry exists and HDB entry does not exist errors occurring during
+ * replay of unconfirmed records are ignored. This is because the
+ * corresponding HDB update might have completed. But also because a
+ * change to add aliases to a principal can fail because we don't check
+ * for alias conflicts before going ahead with the write operation.
+ *
+ * Non-sensical and incomplete log records found during roll-forward are
+ * truncated. A log record is non-sensical if its header and trailer
+ * don't match.
+ *
+ * Recovery (by rolling forward) occurs at the next read or write by a
+ * kadm5 API reader (e.g., kadmin), but not by an hdb API reader (e.g.,
+ * the KDC). This means that, e.g., a principal rename could fail in
+ * between the store and the delete, and recovery might not take place
+ * until the next write operation.
+ *
+ * The log record payload format for create is:
+ *
+ * DER-encoded HDB_entry n bytes
+ *
+ * The log record payload format for update is:
+ *
+ * mask 4 bytes
+ * DER-encoded HDB_entry n-4 bytes
+ *
+ * The log record payload format for delete is:
+ *
+ * krb5_store_principal n bytes
+ *
+ * The log record payload format for rename is:
+ *
+ * krb5_store_principal m bytes (old principal name)
+ * DER-encoded HDB_entry n-m bytes (new record)
+ *
+ * The log record payload format for nop varies:
+ *
+ * - The zeroth record in new logs is a nop with a 16 byte payload:
+ *
+ * offset of end of last confirmed record 8 bytes
+ * timestamp of last confirmed record 4 bytes
+ * version number of last confirmed record 4 bytes
+ *
+ * - New non-zeroth nop records:
+ *
+ * nop type 4 bytes
+ *
+ * - Old nop records:
+ *
+ * version number 4 bytes
+ * timestamp 4 bytes
+ *
+ * Upon initialization, the log's uber record will have version 1, and
+ * will be followed by a nop record with version 2. The version numbers
+ * of additional records will be monotonically increasing.
+ *
+ * Truncation (kadm5_log_truncate()) takes some N > 0 records from the
+ * tail of the log and writes them to the beginning of the log after an
+ * uber record whose version will then be one less than the first of
+ * those records.
+ *
+ * On masters the log should never have more than one unconfirmed
+ * record, but slaves append all of a master's "diffs" and then call
+ * kadm5_log_recover() to recover.
+ */
+
+/*
+ * HDB and log lock order on the master:
+ *
+ * 1) open and lock the HDB
+ * 2) open and lock the log
+ * 3) do something
+ * 4) unlock and close the log
+ * 5) repeat (2)..(4) if desired
+ * 6) unlock and close the HDB
+ *
+ * The kadmin -l lock command can be used to hold the HDB open and
+ * locked for multiple operations.
+ *
+ * HDB and log lock order on the slave:
+ *
+ * 1) open and lock the log
+ * 2) open and lock the HDB
+ * 3) replay entries
+ * 4) unlock and close the HDB
+ * 5) repeat (2)..(4) until signaled
+ * 6) unlock and close the HDB
+ *
+ * The slave doesn't want to allow other local writers, after all, thus
+ * the order is reversed. This means that using "kadmin -l" on a slave
+ * will deadlock with ipropd-slave -- don't do that.
+ */
+
+#define LOG_HEADER_SZ ((off_t)(sizeof(uint32_t) * 4))
+#define LOG_TRAILER_SZ ((off_t)(sizeof(uint32_t) * 2))
+#define LOG_WRAPPER_SZ ((off_t)(LOG_HEADER_SZ + LOG_TRAILER_SZ))
+#define LOG_UBER_LEN ((off_t)(sizeof(uint64_t) + sizeof(uint32_t) * 2))
+#define LOG_UBER_SZ ((off_t)(LOG_WRAPPER_SZ + LOG_UBER_LEN))
+
+#define LOG_NOPEEK 0
+#define LOG_DOPEEK 1
+
+/*
+ * Read the header of the record starting at the current offset into sp.
+ *
+ * Preserves sp's offset on success if `peek', else skips the header.
+ *
+ * Preserves sp's offset on failure where possible.
+ */
+static kadm5_ret_t
+get_header(krb5_storage *sp, int peek, uint32_t *verp, uint32_t *tstampp,
+ enum kadm_ops *opp, uint32_t *lenp)
+{
+ krb5_error_code ret;
+ uint32_t tstamp, op, len;
+ off_t off, new_off;
+
+ if (tstampp == NULL)
+ tstampp = &tstamp;
+ if (lenp == NULL)
+ lenp = &len;
+
+ *verp = 0;
+ *tstampp = 0;
+ if (opp != NULL)
+ *opp = kadm_nop;
+ *lenp = 0;
+
+ off = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (off < 0)
+ return errno;
+ ret = krb5_ret_uint32(sp, verp);
+ if (ret == HEIM_ERR_EOF) {
+ (void) krb5_storage_seek(sp, off, SEEK_SET);
+ return HEIM_ERR_EOF;
+ }
+ if (ret)
+ goto log_corrupt;
+ ret = krb5_ret_uint32(sp, tstampp);
+ if (ret)
+ goto log_corrupt;
+
+ /* Note: sizeof(*opp) might not == sizeof(op) */
+ ret = krb5_ret_uint32(sp, &op);
+ if (ret)
+ goto log_corrupt;
+ if (opp != NULL)
+ *opp = op;
+
+ ret = krb5_ret_uint32(sp, lenp);
+ if (ret)
+ goto log_corrupt;
+
+ /* Restore offset if requested */
+ if (peek == LOG_DOPEEK) {
+ new_off = krb5_storage_seek(sp, off, SEEK_SET);
+ if (new_off == -1)
+ return errno;
+ if (new_off != off)
+ return EIO;
+ }
+
+ return 0;
+
+log_corrupt:
+ (void) krb5_storage_seek(sp, off, SEEK_SET);
+ return KADM5_LOG_CORRUPT;
+}
+
+/*
+ * Seek to the start of the preceding record's header and returns its
+ * offset. If sp is at offset zero this sets *verp = 0 and returns 0.
+ *
+ * Does not verify the header of the previous entry.
+ *
+ * On error returns -1, setting errno (possibly to a kadm5_ret_t or
+ * krb5_error_code value) and preserves sp's offset where possible.
+ */
+static off_t
+seek_prev(krb5_storage *sp, uint32_t *verp, uint32_t *lenp)
+{
+ krb5_error_code ret;
+ uint32_t len, ver;
+ off_t off_len;
+ off_t off, new_off;
+
+ if (lenp == NULL)
+ lenp = &len;
+ if (verp == NULL)
+ verp = &ver;
+
+ *verp = 0;
+ *lenp = 0;
+
+ off = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (off < 0)
+ return off;
+ if (off == 0)
+ return 0;
+
+ /* Check that `off' allows for the record's header and trailer */
+ if (off < LOG_WRAPPER_SZ)
+ goto log_corrupt;
+
+ /* Get the previous entry's length and version from its trailer */
+ new_off = krb5_storage_seek(sp, -8, SEEK_CUR);
+ if (new_off == -1)
+ return -1;
+ if (new_off != off - 8) {
+ errno = EIO;
+ return -1;
+ }
+ ret = krb5_ret_uint32(sp, lenp);
+ if (ret)
+ goto log_corrupt;
+
+ /* Check for overflow/sign extension */
+ off_len = (off_t)*lenp;
+ if (off_len < 0 || *lenp != (uint32_t)off_len)
+ goto log_corrupt;
+
+ ret = krb5_ret_uint32(sp, verp);
+ if (ret)
+ goto log_corrupt;
+
+ /* Check that `off' allows for the record */
+ if (off < LOG_WRAPPER_SZ + off_len)
+ goto log_corrupt;
+
+ /* Seek backwards to the entry's start */
+ new_off = krb5_storage_seek(sp, -(LOG_WRAPPER_SZ + off_len), SEEK_CUR);
+ if (new_off == -1)
+ return -1;
+ if (new_off != off - (LOG_WRAPPER_SZ + off_len)) {
+ errno = EIO;
+ return -1;
+ }
+ return new_off;
+
+log_corrupt:
+ (void) krb5_storage_seek(sp, off, SEEK_SET);
+ errno = KADM5_LOG_CORRUPT;
+ return -1;
+}
+
+/*
+ * Seek to the start of the next entry's header.
+ *
+ * On error returns -1 and preserves sp's offset.
+ */
+static off_t
+seek_next(krb5_storage *sp)
+{
+ krb5_error_code ret;
+ uint32_t ver, ver2, len, len2;
+ enum kadm_ops op;
+ uint32_t tstamp;
+ off_t off, off_len, new_off;
+
+ off = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (off < 0)
+ return off;
+
+ errno = get_header(sp, LOG_NOPEEK, &ver, &tstamp, &op, &len);
+ if (errno)
+ return -1;
+
+ /* Check for overflow */
+ off_len = len;
+ if (off_len < 0)
+ goto log_corrupt;
+
+ new_off = krb5_storage_seek(sp, off_len, SEEK_CUR);
+ if (new_off == -1) {
+ (void) krb5_storage_seek(sp, off, SEEK_SET);
+ return -1;
+ }
+ if (new_off != off + LOG_HEADER_SZ + off_len)
+ goto log_corrupt;
+ ret = krb5_ret_uint32(sp, &len2);
+ if (ret || len2 != len)
+ goto log_corrupt;
+ ret = krb5_ret_uint32(sp, &ver2);
+ if (ret || ver2 != ver)
+ goto log_corrupt;
+ new_off = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (new_off == -1) {
+ (void) krb5_storage_seek(sp, off, SEEK_SET);
+ return -1;
+ }
+ if (new_off != off + off_len + LOG_WRAPPER_SZ)
+ goto log_corrupt;
+
+ return off + off_len + LOG_WRAPPER_SZ;
+
+log_corrupt:
+ (void) krb5_storage_seek(sp, off, SEEK_SET);
+ errno = KADM5_LOG_CORRUPT;
+ return -1;
+}
+
+/*
+ * Get the version of the entry ending at the current offset into sp.
+ * If it is the uber record, return its nominal version instead.
+ *
+ * Returns HEIM_ERR_EOF if sp is at offset zero.
+ *
+ * Preserves sp's offset.
+ */
+static kadm5_ret_t
+get_version_prev(krb5_storage *sp, uint32_t *verp, uint32_t *tstampp)
+{
+ krb5_error_code ret;
+ uint32_t ver, ver2, len, len2;
+ off_t off, prev_off, new_off;
+
+ *verp = 0;
+ if (tstampp != NULL)
+ *tstampp = 0;
+
+ off = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (off < 0)
+ return errno;
+ if (off == 0)
+ return HEIM_ERR_EOF;
+
+ /* Read the trailer and seek back */
+ prev_off = seek_prev(sp, &ver, &len);
+ if (prev_off == -1)
+ return errno;
+
+ /* Uber record? Return nominal version. */
+ if (prev_off == 0 && len == LOG_UBER_LEN && ver == 0) {
+ /* Skip 8 byte offset and 4 byte time */
+ if (krb5_storage_seek(sp, LOG_HEADER_SZ + 12, SEEK_SET)
+ != LOG_HEADER_SZ + 12)
+ return errno;
+ ret = krb5_ret_uint32(sp, verp);
+ if (krb5_storage_seek(sp, 0, SEEK_SET) != 0)
+ return errno;
+ if (ret != 0)
+ return ret;
+ } else {
+ *verp = ver;
+ }
+
+ /* Verify that the trailer matches header */
+ ret = get_header(sp, LOG_NOPEEK, &ver2, tstampp, NULL, &len2);
+ if (ret || ver != ver2 || len != len2)
+ goto log_corrupt;
+
+ /* Preserve offset */
+ new_off = krb5_storage_seek(sp, off, SEEK_SET);
+ if (new_off == -1)
+ return errno;
+ if (new_off != off) {
+ errno = EIO;
+ return errno;
+ }
+ return 0;
+
+log_corrupt:
+ (void) krb5_storage_seek(sp, off, SEEK_SET);
+ return KADM5_LOG_CORRUPT;
+}
+
+static size_t
+get_max_log_size(krb5_context context)
+{
+ off_t n;
+
+ /* Use database-label-specific lookup? No, ETOOHARD. */
+ /* Default to 50MB max log size */
+ n = krb5_config_get_int_default(context, NULL, 52428800,
+ "kdc",
+ "log-max-size",
+ NULL);
+ if (n >= 4 * (LOG_UBER_LEN + LOG_WRAPPER_SZ) && n == (size_t)n)
+ return (size_t)n;
+ return 0;
+}
+
+static kadm5_ret_t truncate_if_needed(kadm5_server_context *);
+
+/*
+ * Get the version and timestamp metadata of either the first, or last
+ * confirmed entry in the log.
+ *
+ * If `which' is LOG_VERSION_UBER, then this gets the version number of the uber
+ * uber record which must be 0, or else we need to upgrade the log.
+ *
+ * If `which' is LOG_VERSION_FIRST, then this gets the metadata for the
+ * logically first entry past the uberblock, or returns HEIM_ERR_EOF if
+ * only the uber record is present.
+ *
+ * If `which' is LOG_VERSION_LAST, then this gets metadata for the last
+ * confirmed entry's version and timestamp. If only the uber record is present,
+ * then the version will be its "nominal" version, which may differ from its
+ * actual version (0).
+ *
+ * The `fd''s offset will be set to the start of the header of the entry
+ * identified by `which'.
+ */
+kadm5_ret_t
+kadm5_log_get_version_fd(kadm5_server_context *server_context, int fd,
+ int which, uint32_t *ver, uint32_t *tstamp)
+{
+ kadm5_ret_t ret = 0;
+ krb5_storage *sp;
+ enum kadm_ops op = kadm_get;
+ uint32_t len = 0;
+ uint32_t tmp;
+
+ if (fd == -1)
+ return 0; /* /dev/null */
+
+ if (tstamp == NULL)
+ tstamp = &tmp;
+
+ *ver = 0;
+ *tstamp = 0;
+
+ sp = krb5_storage_from_fd(fd);
+ if (sp == NULL)
+ return errno ? errno : ENOMEM;
+
+ switch (which) {
+ case LOG_VERSION_LAST:
+ ret = kadm5_log_goto_end(server_context, sp);
+ if (ret == 0)
+ ret = get_version_prev(sp, ver, tstamp);
+ break;
+ case LOG_VERSION_FIRST:
+ ret = kadm5_log_goto_first(server_context, sp);
+ if (ret == 0)
+ ret = get_header(sp, LOG_DOPEEK, ver, tstamp, NULL, NULL);
+ break;
+ case LOG_VERSION_UBER:
+ if (krb5_storage_seek(sp, 0, SEEK_SET) == 0)
+ ret = get_header(sp, LOG_DOPEEK, ver, tstamp, &op, &len);
+ else
+ ret = errno;
+ if (ret == 0 && (op != kadm_nop || len != LOG_UBER_LEN || *ver != 0))
+ ret = KADM5_LOG_NEEDS_UPGRADE;
+ break;
+ default:
+ ret = ENOTSUP;
+ break;
+ }
+
+ krb5_storage_free(sp);
+ return ret;
+}
+
+/* Get the version of the last confirmed entry in the log */
+kadm5_ret_t
+kadm5_log_get_version(kadm5_server_context *server_context, uint32_t *ver)
+{
+ return kadm5_log_get_version_fd(server_context,
+ server_context->log_context.log_fd,
+ LOG_VERSION_LAST, ver, NULL);
+}
+
+/* Sets the version in the context, but NOT in the log */
+kadm5_ret_t
+kadm5_log_set_version(kadm5_server_context *context, uint32_t vno)
+{
+ kadm5_log_context *log_context = &context->log_context;
+
+ log_context->version = vno;
+ return 0;
+}
+
+/*
+ * Open the log and setup server_context->log_context
+ */
+static kadm5_ret_t
+log_open(kadm5_server_context *server_context, int lock_mode)
+{
+ int fd = -1;
+ int lock_it = 0;
+ int lock_nb = 0;
+ int oflags = O_RDWR;
+ kadm5_ret_t ret;
+ kadm5_log_context *log_context = &server_context->log_context;
+
+ if (lock_mode & LOCK_NB) {
+ lock_mode &= ~LOCK_NB;
+ lock_nb = LOCK_NB;
+ }
+
+ if (lock_mode == log_context->lock_mode && log_context->log_fd != -1)
+ return 0;
+
+ if (strcmp(log_context->log_file, "/dev/null") == 0) {
+ /* log_context->log_fd should be -1 here */
+ return 0;
+ }
+
+ if (log_context->log_fd != -1) {
+ /* Lock or change lock */
+ fd = log_context->log_fd;
+ if (lseek(fd, 0, SEEK_SET) == -1)
+ return errno;
+ lock_it = (lock_mode != log_context->lock_mode);
+ } else {
+ /* Open and lock */
+ if (lock_mode != LOCK_UN)
+ oflags |= O_CREAT;
+ fd = open(log_context->log_file, oflags, 0600);
+ if (fd < 0) {
+ ret = errno;
+ krb5_set_error_message(server_context->context, ret,
+ "log_open: open %s", log_context->log_file);
+ return ret;
+ }
+ lock_it = (lock_mode != LOCK_UN);
+ }
+ if (lock_it && flock(fd, lock_mode | lock_nb) < 0) {
+ ret = errno;
+ krb5_set_error_message(server_context->context, ret,
+ "log_open: flock %s", log_context->log_file);
+ if (fd != log_context->log_fd)
+ (void) close(fd);
+ return ret;
+ }
+
+ log_context->log_fd = fd;
+ log_context->lock_mode = lock_mode;
+ log_context->read_only = (lock_mode != LOCK_EX);
+
+ return 0;
+}
+
+/*
+ * Open the log and setup server_context->log_context
+ */
+static kadm5_ret_t
+log_init(kadm5_server_context *server_context, int lock_mode)
+{
+ int fd;
+ struct stat st;
+ uint32_t vno;
+ size_t maxbytes = get_max_log_size(server_context->context);
+ kadm5_ret_t ret;
+ kadm5_log_context *log_context = &server_context->log_context;
+
+ if (strcmp(log_context->log_file, "/dev/null") == 0) {
+ /* log_context->log_fd should be -1 here */
+ return 0;
+ }
+
+ ret = log_open(server_context, lock_mode);
+ if (ret)
+ return ret;
+
+ fd = log_context->log_fd;
+ if (!log_context->read_only) {
+ if (fstat(fd, &st) == -1)
+ ret = errno;
+ if (ret == 0 && st.st_size == 0) {
+ /* Write first entry */
+ log_context->version = 0;
+ ret = kadm5_log_nop(server_context, kadm_nop_plain);
+ if (ret == 0)
+ return 0; /* no need to truncate_if_needed(): it's not */
+ }
+ if (ret == 0) {
+ ret = kadm5_log_get_version_fd(server_context, fd,
+ LOG_VERSION_UBER, &vno, NULL);
+
+ /* Upgrade the log if it was an old-style log */
+ if (ret == KADM5_LOG_NEEDS_UPGRADE)
+ ret = kadm5_log_truncate(server_context, 0, maxbytes / 4);
+ }
+ if (ret == 0)
+ ret = kadm5_log_recover(server_context, kadm_recover_replay);
+ }
+
+ if (ret == 0) {
+ ret = kadm5_log_get_version_fd(server_context, fd, LOG_VERSION_LAST,
+ &log_context->version, NULL);
+ if (ret == HEIM_ERR_EOF)
+ ret = 0;
+ }
+
+ if (ret == 0)
+ ret = truncate_if_needed(server_context);
+
+ if (ret != 0)
+ (void) kadm5_log_end(server_context);
+ return ret;
+}
+
+/* Open the log with an exclusive lock */
+kadm5_ret_t
+kadm5_log_init(kadm5_server_context *server_context)
+{
+ return log_init(server_context, LOCK_EX);
+}
+
+/* Upgrade log lock to exclusive */
+kadm5_ret_t
+kadm5_log_exclusivelock(kadm5_server_context *server_context)
+{
+ kadm5_log_context *log_context = &server_context->log_context;
+
+ if (log_context->lock_mode == LOCK_EX)
+ return 0;
+ if (log_context->log_fd == -1)
+ return EINVAL;
+ if (flock(log_context->log_fd, LOCK_EX) < 0)
+ return errno;
+ log_context->read_only = 0;
+ log_context->lock_mode = LOCK_EX;
+ return 0;
+}
+
+/* Downgrade log lock to shared */
+kadm5_ret_t
+kadm5_log_sharedlock(kadm5_server_context *server_context)
+{
+ kadm5_log_context *log_context = &server_context->log_context;
+
+ if (log_context->lock_mode == LOCK_SH)
+ return 0;
+ if (log_context->log_fd == -1)
+ return EINVAL;
+ if (flock(log_context->log_fd, LOCK_SH) < 0)
+ return errno;
+ log_context->read_only = 1;
+ log_context->lock_mode = LOCK_SH;
+ return 0;
+}
+
+/* Open the log with an exclusive non-blocking lock */
+kadm5_ret_t
+kadm5_log_init_nb(kadm5_server_context *server_context)
+{
+ return log_init(server_context, LOCK_EX | LOCK_NB);
+}
+
+/* Open the log with no locks */
+kadm5_ret_t
+kadm5_log_init_nolock(kadm5_server_context *server_context)
+{
+ return log_init(server_context, LOCK_UN);
+}
+
+/* Open the log with a shared lock */
+kadm5_ret_t
+kadm5_log_init_sharedlock(kadm5_server_context *server_context, int lock_flags)
+{
+ return log_init(server_context, LOCK_SH | lock_flags);
+}
+
+/*
+ * Reinitialize the log and open it
+ */
+kadm5_ret_t
+kadm5_log_reinit(kadm5_server_context *server_context, uint32_t vno)
+{
+ int ret;
+ kadm5_log_context *log_context = &server_context->log_context;
+
+ ret = log_open(server_context, LOCK_EX);
+ if (ret)
+ return ret;
+ if (log_context->log_fd != -1) {
+ if (ftruncate(log_context->log_fd, 0) < 0) {
+ ret = errno;
+ return ret;
+ }
+ if (lseek(log_context->log_fd, 0, SEEK_SET) < 0) {
+ ret = errno;
+ return ret;
+ }
+ }
+
+ /* Write uber entry and truncation nop with version `vno` */
+ log_context->version = vno;
+ return kadm5_log_nop(server_context, kadm_nop_plain);
+}
+
+/* Close the server_context->log_context. */
+kadm5_ret_t
+kadm5_log_end(kadm5_server_context *server_context)
+{
+ kadm5_log_context *log_context = &server_context->log_context;
+ kadm5_ret_t ret = 0;
+ int fd = log_context->log_fd;
+
+ if (fd != -1) {
+ if (log_context->lock_mode != LOCK_UN) {
+ if (flock(fd, LOCK_UN) == -1 && errno == EBADF)
+ ret = errno;
+ }
+ if (ret != EBADF && close(fd) == -1)
+ ret = errno;
+ }
+ log_context->log_fd = -1;
+ log_context->lock_mode = LOCK_UN;
+ return ret;
+}
+
+/*
+ * Write the version, timestamp, and op for a new entry.
+ *
+ * Note that the sp should be a krb5_storage_emem(), not a file.
+ *
+ * On success the sp's offset will be where the length of the payload
+ * should be written.
+ */
+static kadm5_ret_t
+kadm5_log_preamble(kadm5_server_context *context,
+ krb5_storage *sp,
+ enum kadm_ops op,
+ uint32_t vno)
+{
+ kadm5_log_context *log_context = &context->log_context;
+ time_t now = time(NULL);
+ kadm5_ret_t ret;
+
+ ret = krb5_store_uint32(sp, vno);
+ if (ret)
+ return ret;
+ ret = krb5_store_uint32(sp, now);
+ if (ret)
+ return ret;
+ log_context->last_time = now;
+
+ if (op < kadm_first || op > kadm_last)
+ return ERANGE;
+ return krb5_store_uint32(sp, op);
+}
+
+/* Writes the version part of the trailer */
+static kadm5_ret_t
+kadm5_log_postamble(kadm5_log_context *context,
+ krb5_storage *sp,
+ uint32_t vno)
+{
+ return krb5_store_uint32(sp, vno);
+}
+
+/*
+ * Signal the ipropd-master about changes to the log.
+ */
+/*
+ * XXX Get rid of the ifdef by having a sockaddr in log_context in both
+ * cases.
+ *
+ * XXX Better yet, just connect to the master's socket that slaves
+ * connect to, and then disconnect. The master should then check the
+ * log on every connection accepted. Then we wouldn't need IPC to
+ * signal the master.
+ */
+void
+kadm5_log_signal_master(kadm5_server_context *context)
+{
+ kadm5_log_context *log_context = &context->log_context;
+#ifndef NO_UNIX_SOCKETS
+ sendto(log_context->socket_fd,
+ (void *)&log_context->version,
+ sizeof(log_context->version),
+ 0,
+ (struct sockaddr *)&log_context->socket_name,
+ sizeof(log_context->socket_name));
+#else
+ sendto(log_context->socket_fd,
+ (void *)&log_context->version,
+ sizeof(log_context->version),
+ 0,
+ log_context->socket_info->ai_addr,
+ log_context->socket_info->ai_addrlen);
+#endif
+}
+
+/*
+ * Write sp's contents (which must be a fully formed record, complete
+ * with header, payload, and trailer) to the log and fsync the log.
+ *
+ * Does not free sp.
+ */
+
+static kadm5_ret_t
+kadm5_log_flush(kadm5_server_context *context, krb5_storage *sp)
+{
+ kadm5_log_context *log_context = &context->log_context;
+ kadm5_ret_t ret;
+ krb5_data data;
+ size_t len;
+ krb5_ssize_t bytes;
+ uint32_t new_ver, prev_ver;
+ off_t off, end;
+
+ if (strcmp(log_context->log_file, "/dev/null") == 0)
+ return 0;
+
+ if (log_context->read_only)
+ return EROFS;
+
+ if (krb5_storage_seek(sp, 0, SEEK_SET) == -1)
+ return errno;
+
+ ret = get_header(sp, LOG_DOPEEK, &new_ver, NULL, NULL, NULL);
+ if (ret)
+ return ret;
+
+ ret = krb5_storage_to_data(sp, &data);
+ if (ret)
+ return ret;
+
+ /* Abandon the emem storage reference */
+ sp = krb5_storage_from_fd(log_context->log_fd);
+ if (sp == NULL) {
+ krb5_data_free(&data);
+ return krb5_enomem(context->context);
+ }
+
+ /* Check that we are at the end of the log and fail if not */
+ off = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (off == -1) {
+ krb5_data_free(&data);
+ krb5_storage_free(sp);
+ return errno;
+ }
+ end = krb5_storage_seek(sp, 0, SEEK_END);
+ if (end == -1) {
+ krb5_data_free(&data);
+ krb5_storage_free(sp);
+ return errno;
+ }
+ if (end != off) {
+ krb5_data_free(&data);
+ krb5_storage_free(sp);
+ return KADM5_LOG_CORRUPT;
+ }
+
+ /* Enforce monotonically incremented versioning of records */
+ if (seek_prev(sp, &prev_ver, NULL) == -1 ||
+ krb5_storage_seek(sp, end, SEEK_SET) == -1) {
+ ret = errno;
+ krb5_data_free(&data);
+ krb5_storage_free(sp);
+ return ret;
+ }
+
+ if (prev_ver != 0 && prev_ver != log_context->version)
+ return EINVAL; /* Internal error, really; just a consistency check */
+
+ if (prev_ver != 0 && new_ver != prev_ver + 1) {
+ krb5_warnx(context->context, "refusing to write a log record "
+ "with non-monotonic version (new: %u, old: %u)",
+ new_ver, prev_ver);
+ return KADM5_LOG_CORRUPT;
+ }
+
+ len = data.length;
+ bytes = krb5_storage_write(sp, data.data, len);
+ krb5_data_free(&data);
+ if (bytes != len) {
+ krb5_storage_free(sp);
+ ret = bytes == -1 ? errno : KADM5_LOG_CORRUPT;
+ krb5_warn(context->context, ret, "short write to iprop log file");
+ return ret;
+ }
+ if (bytes != (krb5_ssize_t)len) {
+ krb5_storage_free(sp);
+ return EIO;
+ }
+
+ ret = krb5_storage_fsync(sp);
+ krb5_storage_free(sp);
+ if (ret)
+ return ret;
+
+ /* Retain the nominal database version when flushing the uber record */
+ if (new_ver != 0)
+ log_context->version = new_ver;
+ return 0;
+}
+
+/*
+ * Add a `create' operation to the log and perform the create against the HDB.
+ */
+kadm5_ret_t
+kadm5_log_create(kadm5_server_context *context, hdb_entry *entry)
+{
+ krb5_storage *sp;
+ krb5_ssize_t bytes;
+ kadm5_ret_t ret;
+ krb5_data value;
+ hdb_entry ent, existing;
+ kadm5_log_context *log_context = &context->log_context;
+
+ memset(&existing, 0, sizeof(existing));
+ memset(&ent, 0, sizeof(ent));
+ ent = *entry;
+
+ /*
+ * Do not allow creation of concrete entries within namespaces unless
+ * explicitly requested.
+ */
+ ret = hdb_fetch_kvno(context->context, context->db, entry->principal, 0,
+ 0, 0, 0, &existing);
+ if (ret != 0 && ret != HDB_ERR_NOENTRY)
+ return ret;
+ if (ret == 0 && !ent.flags.materialize &&
+ (existing.flags.virtual || existing.flags.virtual_keys)) {
+ hdb_free_entry(context->context, context->db, &existing);
+ return HDB_ERR_EXISTS;
+ }
+ if (ret == 0)
+ hdb_free_entry(context->context, context->db, &existing);
+ ent.flags.materialize = 0; /* Clear in stored entry */
+
+ /*
+ * If we're not logging then we can't recover-to-perform, so just
+ * perform.
+ */
+ if (strcmp(log_context->log_file, "/dev/null") == 0)
+ return context->db->hdb_store(context->context, context->db, 0, &ent);
+
+ /*
+ * Test for any conflicting entries before writing the log. If we commit
+ * to the log we'll end-up rolling forward on recovery, but that would be
+ * wrong if the initial create is rejected.
+ */
+ ret = context->db->hdb_store(context->context, context->db,
+ HDB_F_PRECHECK, &ent);
+ if (ret == 0)
+ ret = hdb_entry2value(context->context, entry, &value);
+ if (ret)
+ return ret;
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ ret = krb5_enomem(context->context);
+ if (ret == 0)
+ ret = kadm5_log_preamble(context, sp, kadm_create,
+ log_context->version + 1);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, value.length);
+ if (ret == 0) {
+ bytes = krb5_storage_write(sp, value.data, value.length);
+ if (bytes != (krb5_ssize_t)value.length)
+ ret = bytes == -1 ? errno : krb5_enomem(context->context);
+ }
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, value.length);
+ if (ret == 0)
+ ret = kadm5_log_postamble(log_context, sp,
+ log_context->version + 1);
+ if (ret == 0)
+ ret = kadm5_log_flush(context, sp);
+ krb5_storage_free(sp);
+ krb5_data_free(&value);
+ if (ret == 0)
+ ret = kadm5_log_recover(context, kadm_recover_commit);
+ return ret;
+}
+
+/*
+ * Read the data of a create log record from `sp' and change the
+ * database.
+ */
+static kadm5_ret_t
+kadm5_log_replay_create(kadm5_server_context *context,
+ uint32_t ver,
+ uint32_t len,
+ krb5_storage *sp)
+{
+ krb5_error_code ret;
+ krb5_data data;
+ hdb_entry ent;
+
+ memset(&ent, 0, sizeof(ent));
+
+ ret = krb5_data_alloc(&data, len);
+ if (ret) {
+ krb5_set_error_message(context->context, ret, "out of memory");
+ return ret;
+ }
+ krb5_storage_read(sp, data.data, len);
+ ret = hdb_value2entry(context->context, &data, &ent);
+ krb5_data_free(&data);
+ if (ret) {
+ krb5_set_error_message(context->context, ret,
+ "Unmarshaling hdb entry in log failed, "
+ "version: %ld", (long)ver);
+ return ret;
+ }
+ ret = context->db->hdb_store(context->context, context->db, 0, &ent);
+ hdb_free_entry(context->context, context->db, &ent);
+ return ret;
+}
+
+/*
+ * Add a `delete' operation to the log.
+ */
+kadm5_ret_t
+kadm5_log_delete(kadm5_server_context *context,
+ krb5_principal princ)
+{
+ kadm5_ret_t ret;
+ kadm5_log_context *log_context = &context->log_context;
+ krb5_storage *sp;
+ uint32_t len = 0; /* So dumb compilers don't warn */
+ off_t end_off = 0; /* Ditto; this allows de-indentation by two levels */
+ off_t off;
+
+ if (strcmp(log_context->log_file, "/dev/null") == 0)
+ return context->db->hdb_remove(context->context, context->db, 0,
+ princ);
+ ret = context->db->hdb_remove(context->context, context->db,
+ HDB_F_PRECHECK, princ);
+ if (ret)
+ return ret;
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ ret = krb5_enomem(context->context);
+ if (ret == 0)
+ ret = kadm5_log_preamble(context, sp, kadm_delete,
+ log_context->version + 1);
+ if (ret) {
+ krb5_storage_free(sp);
+ return ret;
+ }
+
+ /*
+ * Write a 0 length which we overwrite once we know the length of
+ * the principal name payload.
+ */
+ off = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (off == -1)
+ ret = errno;
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, 0);
+ if (ret == 0)
+ ret = krb5_store_principal(sp, princ);
+ if (ret == 0) {
+ end_off = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (end_off == -1)
+ ret = errno;
+ else if (end_off < off)
+ ret = KADM5_LOG_CORRUPT;
+ }
+ if (ret == 0) {
+ /* We wrote sizeof(uint32_t) + payload length bytes */
+ len = (uint32_t)(end_off - off);
+ if (end_off - off != len || len < sizeof(len))
+ ret = KADM5_LOG_CORRUPT;
+ else
+ len -= sizeof(len);
+ }
+ if (ret == 0 && krb5_storage_seek(sp, off, SEEK_SET) == -1)
+ ret = errno;
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, len);
+ if (ret == 0 && krb5_storage_seek(sp, end_off, SEEK_SET) == -1)
+ ret = errno;
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, len);
+ if (ret == 0)
+ ret = kadm5_log_postamble(log_context, sp,
+ log_context->version + 1);
+ if (ret == 0)
+ ret = kadm5_log_flush(context, sp);
+ if (ret == 0)
+ ret = kadm5_log_recover(context, kadm_recover_commit);
+ krb5_storage_free(sp);
+ return ret;
+}
+
+/*
+ * Read a `delete' log operation from `sp' and apply it.
+ */
+static kadm5_ret_t
+kadm5_log_replay_delete(kadm5_server_context *context,
+ uint32_t ver, uint32_t len, krb5_storage *sp)
+{
+ krb5_error_code ret;
+ krb5_principal principal;
+
+ ret = krb5_ret_principal(sp, &principal);
+ if (ret) {
+ krb5_set_error_message(context->context, ret, "Failed to read deleted "
+ "principal from log version: %ld", (long)ver);
+ return ret;
+ }
+
+ ret = context->db->hdb_remove(context->context, context->db, 0, principal);
+ krb5_free_principal(context->context, principal);
+ return ret;
+}
+
+static kadm5_ret_t kadm5_log_replay_rename(kadm5_server_context *,
+ uint32_t, uint32_t,
+ krb5_storage *);
+
+/*
+ * Add a `rename' operation to the log.
+ */
+kadm5_ret_t
+kadm5_log_rename(kadm5_server_context *context,
+ krb5_principal source,
+ hdb_entry *entry)
+{
+ krb5_storage *sp;
+ krb5_ssize_t bytes;
+ kadm5_ret_t ret;
+ uint32_t len = 0; /* So dumb compilers don't warn */
+ off_t end_off = 0; /* Ditto; this allows de-indentation by two levels */
+ off_t off;
+ krb5_data value;
+ hdb_entry ent;
+ kadm5_log_context *log_context = &context->log_context;
+
+ memset(&ent, 0, sizeof(ent));
+ ent = *entry;
+
+ if (strcmp(log_context->log_file, "/dev/null") == 0) {
+ ret = context->db->hdb_store(context->context, context->db, 0, &ent);
+ if (ret == 0)
+ return context->db->hdb_remove(context->context, context->db, 0,
+ source);
+ return ret;
+ }
+
+ /*
+ * Pre-check that the transaction will succeed.
+ *
+ * Note that rename doesn't work to swap a principal's canonical
+ * name with one of its aliases. To make that work would require
+ * adding an hdb_rename() method for renaming principals (there's an
+ * hdb_rename() method already, but for renaming the HDB), which is
+ * ETOOMUCHWORK for the time being.
+ */
+ ret = context->db->hdb_store(context->context, context->db,
+ HDB_F_PRECHECK, &ent);
+ if (ret == 0)
+ ret = context->db->hdb_remove(context->context, context->db,
+ HDB_F_PRECHECK, source);
+ if (ret)
+ return ret;
+
+ sp = krb5_storage_emem();
+ krb5_data_zero(&value);
+ if (sp == NULL)
+ ret = krb5_enomem(context->context);
+ if (ret == 0)
+ ret = kadm5_log_preamble(context, sp, kadm_rename,
+ log_context->version + 1);
+ if (ret == 0)
+ ret = hdb_entry2value(context->context, entry, &value);
+ if (ret) {
+ krb5_data_free(&value);
+ krb5_storage_free(sp);
+ return ret;
+ }
+
+ /*
+ * Write a zero length which we'll overwrite once we know the length of the
+ * payload.
+ */
+ off = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (off == -1)
+ ret = errno;
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, 0);
+ if (ret == 0)
+ ret = krb5_store_principal(sp, source);
+ if (ret == 0) {
+ errno = 0;
+ bytes = krb5_storage_write(sp, value.data, value.length);
+ if (bytes != (krb5_ssize_t)value.length)
+ ret = bytes == -1 ? errno : krb5_enomem(context->context);
+ }
+ if (ret == 0) {
+ end_off = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (end_off == -1)
+ ret = errno;
+ else if (end_off < off)
+ ret = KADM5_LOG_CORRUPT;
+ }
+ if (ret == 0) {
+ /* We wrote sizeof(uint32_t) + payload length bytes */
+ len = (uint32_t)(end_off - off);
+ if (end_off - off != len || len < sizeof(len))
+ ret = KADM5_LOG_CORRUPT;
+ else
+ len -= sizeof(len);
+ if (ret == 0 && krb5_storage_seek(sp, off, SEEK_SET) == -1)
+ ret = errno;
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, len);
+ if (ret == 0 && krb5_storage_seek(sp, end_off, SEEK_SET) == -1)
+ ret = errno;
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, len);
+ if (ret == 0)
+ ret = kadm5_log_postamble(log_context, sp,
+ log_context->version + 1);
+ if (ret == 0)
+ ret = kadm5_log_flush(context, sp);
+ if (ret == 0)
+ ret = kadm5_log_recover(context, kadm_recover_commit);
+ }
+ krb5_data_free(&value);
+ krb5_storage_free(sp);
+ return ret;
+}
+
+/*
+ * Read a `rename' log operation from `sp' and apply it.
+ */
+
+static kadm5_ret_t
+kadm5_log_replay_rename(kadm5_server_context *context,
+ uint32_t ver,
+ uint32_t len,
+ krb5_storage *sp)
+{
+ krb5_error_code ret;
+ krb5_principal source;
+ hdb_entry target_ent;
+ krb5_data value;
+ off_t off;
+ size_t princ_len, data_len;
+
+ memset(&target_ent, 0, sizeof(target_ent));
+
+ off = krb5_storage_seek(sp, 0, SEEK_CUR);
+ ret = krb5_ret_principal(sp, &source);
+ if (ret) {
+ krb5_set_error_message(context->context, ret, "Failed to read renamed "
+ "principal in log, version: %ld", (long)ver);
+ return ret;
+ }
+ princ_len = krb5_storage_seek(sp, 0, SEEK_CUR) - off;
+ data_len = len - princ_len;
+ ret = krb5_data_alloc(&value, data_len);
+ if (ret) {
+ krb5_free_principal (context->context, source);
+ return ret;
+ }
+ krb5_storage_read(sp, value.data, data_len);
+ ret = hdb_value2entry(context->context, &value, &target_ent);
+ krb5_data_free(&value);
+ if (ret) {
+ krb5_free_principal(context->context, source);
+ return ret;
+ }
+ ret = context->db->hdb_store(context->context, context->db,
+ 0, &target_ent);
+ hdb_free_entry(context->context, context->db, &target_ent);
+ if (ret) {
+ krb5_free_principal(context->context, source);
+ return ret;
+ }
+ ret = context->db->hdb_remove(context->context, context->db, 0, source);
+ krb5_free_principal(context->context, source);
+
+ return ret;
+}
+
+/*
+ * Add a `modify' operation to the log.
+ */
+kadm5_ret_t
+kadm5_log_modify(kadm5_server_context *context,
+ hdb_entry *entry,
+ uint32_t mask)
+{
+ krb5_storage *sp;
+ krb5_ssize_t bytes;
+ kadm5_ret_t ret;
+ krb5_data value;
+ uint32_t len;
+ hdb_entry ent;
+ kadm5_log_context *log_context = &context->log_context;
+
+ memset(&ent, 0, sizeof(ent));
+ ent = *entry;
+
+ if (strcmp(log_context->log_file, "/dev/null") == 0)
+ return context->db->hdb_store(context->context, context->db,
+ HDB_F_REPLACE, &ent);
+
+ ret = context->db->hdb_store(context->context, context->db,
+ HDB_F_PRECHECK | HDB_F_REPLACE, &ent);
+ if (ret)
+ return ret;
+
+ sp = krb5_storage_emem();
+ krb5_data_zero(&value);
+ if (sp == NULL)
+ ret = krb5_enomem(context->context);
+ if (ret == 0)
+ ret = hdb_entry2value(context->context, entry, &value);
+ if (ret) {
+ krb5_data_free(&value);
+ krb5_storage_free(sp);
+ return ret;
+ }
+
+ len = value.length + sizeof(len);
+ if (value.length > len || len > INT32_MAX)
+ ret = E2BIG;
+ if (ret == 0)
+ ret = kadm5_log_preamble(context, sp, kadm_modify,
+ log_context->version + 1);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, len);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, mask);
+ if (ret == 0) {
+ bytes = krb5_storage_write(sp, value.data, value.length);
+ if (bytes != (krb5_ssize_t)value.length)
+ ret = bytes == -1 ? errno : krb5_enomem(context->context);
+ }
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, len);
+ if (ret == 0)
+ ret = kadm5_log_postamble(log_context, sp,
+ log_context->version + 1);
+ if (ret == 0)
+ ret = kadm5_log_flush(context, sp);
+ if (ret == 0)
+ ret = kadm5_log_recover(context, kadm_recover_commit);
+ krb5_data_free(&value);
+ krb5_storage_free(sp);
+ return ret;
+}
+
+/*
+ * Read a `modify' log operation from `sp' and apply it.
+ */
+static kadm5_ret_t
+kadm5_log_replay_modify(kadm5_server_context *context,
+ uint32_t ver,
+ uint32_t len,
+ krb5_storage *sp)
+{
+ krb5_error_code ret;
+ uint32_t mask;
+ krb5_data value;
+ hdb_entry ent, log_ent;
+
+ memset(&log_ent, 0, sizeof(log_ent));
+
+ ret = krb5_ret_uint32(sp, &mask);
+ if (ret)
+ return ret;
+ len -= 4;
+ ret = krb5_data_alloc (&value, len);
+ if (ret) {
+ krb5_set_error_message(context->context, ret, "out of memory");
+ return ret;
+ }
+ errno = 0;
+ if (krb5_storage_read (sp, value.data, len) != (krb5_ssize_t)len) {
+ ret = errno ? errno : EIO;
+ return ret;
+ }
+ ret = hdb_value2entry (context->context, &value, &log_ent);
+ krb5_data_free(&value);
+ if (ret)
+ return ret;
+
+ memset(&ent, 0, sizeof(ent));
+ /* NOTE: We do not use hdb_fetch_kvno() here */
+ ret = context->db->hdb_fetch_kvno(context->context, context->db,
+ log_ent.principal,
+ HDB_F_DECRYPT|HDB_F_ALL_KVNOS|
+ HDB_F_GET_ANY|HDB_F_ADMIN_DATA, 0, &ent);
+ if (ret)
+ goto out;
+ if (mask & KADM5_PRINC_EXPIRE_TIME) {
+ if (log_ent.valid_end == NULL) {
+ ent.valid_end = NULL;
+ } else {
+ if (ent.valid_end == NULL) {
+ ent.valid_end = malloc(sizeof(*ent.valid_end));
+ if (ent.valid_end == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ }
+ *ent.valid_end = *log_ent.valid_end;
+ }
+ }
+ if (mask & KADM5_PW_EXPIRATION) {
+ if (log_ent.pw_end == NULL) {
+ ent.pw_end = NULL;
+ } else {
+ if (ent.pw_end == NULL) {
+ ent.pw_end = malloc(sizeof(*ent.pw_end));
+ if (ent.pw_end == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ }
+ *ent.pw_end = *log_ent.pw_end;
+ }
+ }
+ if (mask & KADM5_LAST_PWD_CHANGE) {
+ krb5_warnx (context->context,
+ "Unimplemented mask KADM5_LAST_PWD_CHANGE");
+ }
+ if (mask & KADM5_ATTRIBUTES) {
+ ent.flags = log_ent.flags;
+ }
+ if (mask & KADM5_MAX_LIFE) {
+ if (log_ent.max_life == NULL) {
+ ent.max_life = NULL;
+ } else {
+ if (ent.max_life == NULL) {
+ ent.max_life = malloc (sizeof(*ent.max_life));
+ if (ent.max_life == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ }
+ *ent.max_life = *log_ent.max_life;
+ }
+ }
+ if ((mask & KADM5_MOD_TIME) && (mask & KADM5_MOD_NAME)) {
+ if (ent.modified_by == NULL) {
+ ent.modified_by = malloc(sizeof(*ent.modified_by));
+ if (ent.modified_by == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ } else
+ free_Event(ent.modified_by);
+ ret = copy_Event(log_ent.modified_by, ent.modified_by);
+ if (ret) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ }
+ if (mask & KADM5_KVNO) {
+ ent.kvno = log_ent.kvno;
+ }
+ if (mask & KADM5_MKVNO) {
+ krb5_warnx(context->context, "Unimplemented mask KADM5_KVNO");
+ }
+ if (mask & KADM5_AUX_ATTRIBUTES) {
+ krb5_warnx(context->context,
+ "Unimplemented mask KADM5_AUX_ATTRIBUTES");
+ }
+ if (mask & KADM5_POLICY_CLR) {
+ krb5_warnx(context->context, "Unimplemented mask KADM5_POLICY_CLR");
+ }
+ if (mask & KADM5_MAX_RLIFE) {
+ if (log_ent.max_renew == NULL) {
+ ent.max_renew = NULL;
+ } else {
+ if (ent.max_renew == NULL) {
+ ent.max_renew = malloc (sizeof(*ent.max_renew));
+ if (ent.max_renew == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out;
+ }
+ }
+ *ent.max_renew = *log_ent.max_renew;
+ }
+ }
+ if (mask & KADM5_LAST_SUCCESS) {
+ krb5_warnx(context->context, "Unimplemented mask KADM5_LAST_SUCCESS");
+ }
+ if (mask & KADM5_LAST_FAILED) {
+ krb5_warnx(context->context, "Unimplemented mask KADM5_LAST_FAILED");
+ }
+ if (mask & KADM5_FAIL_AUTH_COUNT) {
+ krb5_warnx(context->context,
+ "Unimplemented mask KADM5_FAIL_AUTH_COUNT");
+ }
+ if (mask & KADM5_KEY_DATA) {
+ size_t num;
+ size_t i;
+
+ /*
+ * We don't need to do anything about key history here because
+ * the log entry contains a complete entry, including hdb
+ * extensions. We do need to make sure that KADM5_TL_DATA is in
+ * the mask though, since that's what it takes to update the
+ * extensions (see below).
+ */
+ mask |= KADM5_TL_DATA;
+
+ for (i = 0; i < ent.keys.len; ++i)
+ free_Key(&ent.keys.val[i]);
+ free (ent.keys.val);
+
+ num = log_ent.keys.len;
+
+ ent.keys.len = num;
+ ent.keys.val = malloc(len * sizeof(*ent.keys.val));
+ if (ent.keys.val == NULL) {
+ krb5_enomem(context->context);
+ goto out;
+ }
+ for (i = 0; i < ent.keys.len; ++i) {
+ ret = copy_Key(&log_ent.keys.val[i],
+ &ent.keys.val[i]);
+ if (ret) {
+ krb5_set_error_message(context->context, ret, "out of memory");
+ goto out;
+ }
+ }
+ }
+ if ((mask & KADM5_TL_DATA) && log_ent.etypes) {
+ if (ent.etypes)
+ free_HDB_EncTypeList(ent.etypes);
+ free(ent.etypes);
+ ent.etypes = calloc(1, sizeof(*ent.etypes));
+ if (ent.etypes == NULL)
+ ret = ENOMEM;
+ if (ret == 0)
+ ret = copy_HDB_EncTypeList(log_ent.etypes, ent.etypes);
+ if (ret) {
+ ret = krb5_enomem(context->context);
+ free(ent.etypes);
+ ent.etypes = NULL;
+ goto out;
+ }
+ }
+
+ if ((mask & KADM5_TL_DATA) && log_ent.extensions) {
+ if (ent.extensions) {
+ free_HDB_extensions(ent.extensions);
+ free(ent.extensions);
+ ent.extensions = NULL;
+ }
+
+ ent.extensions = calloc(1, sizeof(*ent.extensions));
+ if (ent.extensions == NULL)
+ ret = ENOMEM;
+
+ if (ret == 0)
+ ret = copy_HDB_extensions(log_ent.extensions,
+ ent.extensions);
+ if (ret) {
+ ret = krb5_enomem(context->context);
+ free(ent.extensions);
+ ent.extensions = NULL;
+ goto out;
+ }
+ }
+ ret = context->db->hdb_store(context->context, context->db,
+ HDB_F_REPLACE, &ent);
+ out:
+ hdb_free_entry(context->context, context->db, &ent);
+ hdb_free_entry(context->context, context->db, &log_ent);
+ return ret;
+}
+
+/*
+ * Update the first entry (which should be a `nop'), the "uber-entry".
+ */
+static kadm5_ret_t
+log_update_uber(kadm5_server_context *context, off_t off)
+{
+ kadm5_log_context *log_context = &context->log_context;
+ kadm5_ret_t ret = 0;
+ krb5_storage *sp, *mem_sp;
+ krb5_data data;
+ uint32_t op, len;
+ ssize_t bytes;
+
+ if (strcmp(log_context->log_file, "/dev/null") == 0)
+ return 0;
+
+ if (log_context->read_only)
+ return EROFS;
+
+ krb5_data_zero(&data);
+
+ mem_sp = krb5_storage_emem();
+ if (mem_sp == NULL)
+ return krb5_enomem(context->context);
+
+ sp = krb5_storage_from_fd(log_context->log_fd);
+ if (sp == NULL) {
+ krb5_storage_free(mem_sp);
+ return krb5_enomem(context->context);
+ }
+
+ /* Skip first entry's version and timestamp */
+ if (krb5_storage_seek(sp, 8, SEEK_SET) == -1) {
+ ret = errno;
+ goto out;
+ }
+
+ /* If the first entry is not a nop, there's nothing we can do here */
+ ret = krb5_ret_uint32(sp, &op);
+ if (ret || op != kadm_nop)
+ goto out;
+
+ /* If the first entry is not a 16-byte nop, ditto */
+ ret = krb5_ret_uint32(sp, &len);
+ if (ret || len != LOG_UBER_LEN)
+ goto out;
+
+ /*
+ * Try to make the writes here as close to atomic as possible: a
+ * single write() call.
+ */
+ ret = krb5_store_uint64(mem_sp, off);
+ if (ret)
+ goto out;
+ ret = krb5_store_uint32(mem_sp, log_context->last_time);
+ if (ret)
+ goto out;
+ ret = krb5_store_uint32(mem_sp, log_context->version);
+ if (ret)
+ goto out;
+
+ krb5_storage_to_data(mem_sp, &data);
+ bytes = krb5_storage_write(sp, data.data, data.length);
+ if (bytes < 0)
+ ret = errno;
+ else if (bytes != data.length)
+ ret = EIO;
+
+ /*
+ * We don't fsync() this write because we can recover if the write
+ * doesn't complete, though for now we don't have code for properly
+ * dealing with the offset not getting written completely.
+ *
+ * We should probably have two copies of the offset so we can use
+ * one copy to verify the other, and when they don't match we could
+ * traverse the whole log forwards, replaying just the last entry.
+ */
+
+out:
+ if (ret == 0)
+ kadm5_log_signal_master(context);
+ krb5_data_free(&data);
+ krb5_storage_free(sp);
+ krb5_storage_free(mem_sp);
+ if (lseek(log_context->log_fd, off, SEEK_SET) == -1)
+ ret = ret ? ret : errno;
+
+ return ret;
+}
+
+/*
+ * Add a `nop' operation to the log. Does not close the log.
+ */
+kadm5_ret_t
+kadm5_log_nop(kadm5_server_context *context, enum kadm_nop_type nop_type)
+{
+ krb5_storage *sp;
+ kadm5_ret_t ret;
+ kadm5_log_context *log_context = &context->log_context;
+ off_t off;
+ uint32_t vno = log_context->version;
+
+ if (strcmp(log_context->log_file, "/dev/null") == 0)
+ return 0;
+
+ off = lseek(log_context->log_fd, 0, SEEK_CUR);
+ if (off == -1)
+ return errno;
+
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ return krb5_enomem(context->context);
+
+ ret = kadm5_log_preamble(context, sp, kadm_nop, off == 0 ? 0 : vno + 1);
+ if (ret)
+ goto out;
+
+ if (off == 0) {
+ /*
+ * First entry (uber-entry) gets room for offset of next new
+ * entry and time and version of last entry.
+ */
+ ret = krb5_store_uint32(sp, LOG_UBER_LEN);
+ /* These get overwritten with the same values below */
+ if (ret == 0)
+ ret = krb5_store_uint64(sp, LOG_UBER_SZ);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, log_context->last_time);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, vno);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, LOG_UBER_LEN);
+ } else if (nop_type == kadm_nop_plain) {
+ ret = krb5_store_uint32(sp, 0);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, 0);
+ } else {
+ ret = krb5_store_uint32(sp, sizeof(uint32_t));
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, nop_type);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, sizeof(uint32_t));
+ }
+
+ if (ret == 0)
+ ret = kadm5_log_postamble(log_context, sp, off == 0 ? 0 : vno + 1);
+ if (ret == 0)
+ ret = kadm5_log_flush(context, sp);
+
+ if (ret == 0 && off == 0 && nop_type != kadm_nop_plain)
+ ret = kadm5_log_nop(context, nop_type);
+
+ if (ret == 0 && off != 0)
+ ret = kadm5_log_recover(context, kadm_recover_commit);
+
+out:
+ krb5_storage_free(sp);
+ return ret;
+}
+
+/*
+ * Read a `nop' log operation from `sp' and "apply" it (there's nothing
+ * to do).
+ *
+ * FIXME Actually, if the nop payload is 4 bytes and contains an enum
+ * kadm_nop_type value of kadm_nop_trunc then we should truncate the
+ * log, and if it contains a kadm_nop_close then we should rename a new
+ * log into place. However, this is not implemented yet.
+ */
+static kadm5_ret_t
+kadm5_log_replay_nop(kadm5_server_context *context,
+ uint32_t ver,
+ uint32_t len,
+ krb5_storage *sp)
+{
+ return 0;
+}
+
+struct replay_cb_data {
+ size_t count;
+ uint32_t ver;
+ enum kadm_recover_mode mode;
+};
+
+
+/*
+ * Recover or perform the initial commit of an unconfirmed log entry
+ */
+static kadm5_ret_t
+recover_replay(kadm5_server_context *context,
+ uint32_t ver, time_t timestamp, enum kadm_ops op,
+ uint32_t len, krb5_storage *sp, void *ctx)
+{
+ struct replay_cb_data *data = ctx;
+ kadm5_ret_t ret;
+ off_t off;
+
+ /* On initial commit there must be just one pending unconfirmed entry */
+ if (data->count > 0 && data->mode == kadm_recover_commit)
+ return KADM5_LOG_CORRUPT;
+
+ /* We're at the start of the payload; compute end of entry offset */
+ off = krb5_storage_seek(sp, 0, SEEK_CUR) + len + LOG_TRAILER_SZ;
+
+ /* We cannot perform log recovery on LDAP and such backends */
+ if (data->mode == kadm_recover_replay &&
+ (context->db->hdb_capability_flags & HDB_CAP_F_SHARED_DIRECTORY))
+ ret = 0;
+ else
+ ret = kadm5_log_replay(context, op, ver, len, sp);
+ switch (ret) {
+ case HDB_ERR_NOENTRY:
+ case HDB_ERR_EXISTS:
+ if (data->mode != kadm_recover_replay)
+ return ret;
+ case 0:
+ break;
+ case KADM5_LOG_CORRUPT:
+ return -1;
+ default:
+ krb5_warn(context->context, ret, "unexpected error while replaying");
+ return -1;
+ }
+ data->count++;
+ data->ver = ver;
+
+ /*
+ * With replay we may be making multiple HDB changes. We must sync the
+ * confirmation of each one before moving on to the next. Otherwise, we
+ * might attempt to replay multiple already applied updates, and this may
+ * introduce unintended intermediate states or fail to yield the same final
+ * result.
+ */
+ kadm5_log_set_version(context, ver);
+ ret = log_update_uber(context, off);
+ if (ret == 0 && data->mode != kadm_recover_commit)
+ ret = krb5_storage_fsync(sp);
+ return ret;
+}
+
+
+kadm5_ret_t
+kadm5_log_recover(kadm5_server_context *context, enum kadm_recover_mode mode)
+{
+ kadm5_ret_t ret;
+ krb5_storage *sp;
+ struct replay_cb_data replay_data;
+
+ replay_data.count = 0;
+ replay_data.ver = 0;
+ replay_data.mode = mode;
+
+ sp = krb5_storage_from_fd(context->log_context.log_fd);
+ if (sp == NULL)
+ return errno ? errno : EIO;
+ ret = kadm5_log_goto_end(context, sp);
+
+ if (ret == 0)
+ ret = kadm5_log_foreach(context, kadm_forward | kadm_unconfirmed,
+ NULL, recover_replay, &replay_data);
+ if (ret == 0 && mode == kadm_recover_commit && replay_data.count != 1)
+ ret = KADM5_LOG_CORRUPT;
+ krb5_storage_free(sp);
+ return ret;
+}
+
+/*
+ * Call `func' for each log record in the log in `context'.
+ *
+ * `func' is optional.
+ *
+ * If `func' returns -1 then log traversal terminates and this returns 0.
+ * Otherwise `func''s return is returned if there are no other errors.
+ */
+kadm5_ret_t
+kadm5_log_foreach(kadm5_server_context *context,
+ enum kadm_iter_opts iter_opts,
+ off_t *off_lastp,
+ kadm5_ret_t (*func)(kadm5_server_context *server_context,
+ uint32_t ver, time_t timestamp,
+ enum kadm_ops op, uint32_t len,
+ krb5_storage *sp, void *ctx),
+ void *ctx)
+{
+ kadm5_ret_t ret = 0;
+ int fd = context->log_context.log_fd;
+ krb5_storage *sp;
+ off_t off_last;
+ off_t this_entry = 0;
+ off_t log_end = 0;
+
+ if (strcmp(context->log_context.log_file, "/dev/null") == 0)
+ return 0;
+
+ if (off_lastp == NULL)
+ off_lastp = &off_last;
+ *off_lastp = -1;
+
+ if (((iter_opts & kadm_forward) && (iter_opts & kadm_backward)) ||
+ (!(iter_opts & kadm_confirmed) && !(iter_opts & kadm_unconfirmed)))
+ return EINVAL;
+
+ if ((iter_opts & kadm_forward) && (iter_opts & kadm_confirmed) &&
+ (iter_opts & kadm_unconfirmed)) {
+ /*
+ * We want to traverse all log entries, confirmed or not, from
+ * the start, then there's no need to kadm5_log_goto_end()
+ * -- no reason to try to find the end.
+ */
+ sp = krb5_storage_from_fd(fd);
+ if (sp == NULL)
+ return errno ? errno : ENOMEM;
+
+ log_end = krb5_storage_seek(sp, 0, SEEK_END);
+ if (log_end == -1 ||
+ krb5_storage_seek(sp, 0, SEEK_SET) == -1) {
+ ret = errno;
+ krb5_storage_free(sp);
+ return ret;
+ }
+ } else {
+ /* Get the end of the log based on the uber entry */
+ sp = krb5_storage_from_fd(fd);
+ if (sp == NULL)
+ return errno ? errno : ENOMEM;
+ ret = kadm5_log_goto_end(context, sp);
+ if (ret != 0)
+ return ret;
+ log_end = krb5_storage_seek(sp, 0, SEEK_CUR);
+ }
+
+ *off_lastp = log_end;
+
+ if ((iter_opts & kadm_forward) && (iter_opts & kadm_confirmed)) {
+ /* Start at the beginning */
+ if (krb5_storage_seek(sp, 0, SEEK_SET) == -1) {
+ ret = errno;
+ krb5_storage_free(sp);
+ return ret;
+ }
+ } else if ((iter_opts & kadm_backward) && (iter_opts & kadm_unconfirmed)) {
+ /*
+ * We're at the confirmed end but need to be at the unconfirmed
+ * end. Skip forward to the real end, re-entering to do it.
+ */
+ ret = kadm5_log_foreach(context, kadm_forward | kadm_unconfirmed,
+ &log_end, NULL, NULL);
+ if (ret)
+ return ret;
+ if (krb5_storage_seek(sp, log_end, SEEK_SET) == -1) {
+ ret = errno;
+ krb5_storage_free(sp);
+ return ret;
+ }
+ }
+
+ for (;;) {
+ uint32_t ver, ver2, len, len2;
+ uint32_t tstamp;
+ time_t timestamp;
+ enum kadm_ops op;
+
+ if ((iter_opts & kadm_backward)) {
+ off_t o;
+
+ o = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (o == 0 ||
+ ((iter_opts & kadm_unconfirmed) && o <= *off_lastp))
+ break;
+ ret = kadm5_log_previous(context->context, sp, &ver,
+ &timestamp, &op, &len);
+ if (ret)
+ break;
+
+ /* Offset is now at payload of current entry */
+
+ o = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (o == -1) {
+ ret = errno;
+ break;
+ }
+ this_entry = o - LOG_HEADER_SZ;
+ if (this_entry < 0) {
+ ret = KADM5_LOG_CORRUPT;
+ break;
+ }
+ } else {
+ /* Offset is now at start of current entry, read header */
+ this_entry = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (!(iter_opts & kadm_unconfirmed) && this_entry == log_end)
+ break;
+ ret = get_header(sp, LOG_NOPEEK, &ver, &tstamp, &op, &len);
+ if (ret == HEIM_ERR_EOF) {
+ ret = 0;
+ break;
+ }
+ timestamp = tstamp;
+ if (ret)
+ break;
+ /* Offset is now at payload of current entry */
+ }
+
+ /* Validate trailer before calling the callback */
+ if (krb5_storage_seek(sp, len, SEEK_CUR) == -1) {
+ ret = errno;
+ break;
+ }
+
+ ret = krb5_ret_uint32(sp, &len2);
+ if (ret)
+ break;
+ ret = krb5_ret_uint32(sp, &ver2);
+ if (ret)
+ break;
+ if (len != len2 || ver != ver2) {
+ ret = KADM5_LOG_CORRUPT;
+ break;
+ }
+
+ /* Rewind to start of payload and call callback if we have one */
+ if (krb5_storage_seek(sp, this_entry + LOG_HEADER_SZ,
+ SEEK_SET) == -1) {
+ ret = errno;
+ break;
+ }
+
+ if (func != NULL) {
+ ret = (*func)(context, ver, timestamp, op, len, sp, ctx);
+ if (ret) {
+ /* Callback signals desire to stop by returning -1 */
+ if (ret == -1)
+ ret = 0;
+ break;
+ }
+ }
+ if ((iter_opts & kadm_forward)) {
+ off_t o;
+
+ o = krb5_storage_seek(sp, this_entry+LOG_WRAPPER_SZ+len, SEEK_SET);
+ if (o == -1) {
+ ret = errno;
+ break;
+ }
+ if (o > log_end)
+ *off_lastp = o;
+ } else if ((iter_opts & kadm_backward)) {
+ /*
+ * Rewind to the start of this entry so kadm5_log_previous()
+ * can find the previous one.
+ */
+ if (krb5_storage_seek(sp, this_entry, SEEK_SET) == -1) {
+ ret = errno;
+ break;
+ }
+ }
+ }
+ if ((ret == HEIM_ERR_EOF || ret == KADM5_LOG_CORRUPT) &&
+ (iter_opts & kadm_forward) &&
+ context->log_context.lock_mode == LOCK_EX) {
+ /*
+ * Truncate partially written last log entry so we can write
+ * again.
+ */
+ ret = krb5_storage_truncate(sp, this_entry);
+ if (ret == 0 &&
+ krb5_storage_seek(sp, this_entry, SEEK_SET) == -1)
+ ret = errno;
+ krb5_warnx(context->context, "Truncating log at partial or "
+ "corrupt %s entry",
+ this_entry > log_end ? "unconfirmed" : "confirmed");
+ }
+ krb5_storage_free(sp);
+ return ret;
+}
+
+/*
+ * Go to the first record, which, if we have an uber record, will be
+ * the second record.
+ */
+kadm5_ret_t
+kadm5_log_goto_first(kadm5_server_context *server_context, krb5_storage *sp)
+{
+ enum kadm_ops op;
+ uint32_t ver, len;
+ kadm5_ret_t ret;
+
+ if (krb5_storage_seek(sp, 0, SEEK_SET) == -1)
+ return KADM5_LOG_CORRUPT;
+
+ ret = get_header(sp, LOG_DOPEEK, &ver, NULL, &op, &len);
+ if (ret)
+ return ret;
+ if (op == kadm_nop && len == LOG_UBER_LEN && seek_next(sp) == -1)
+ return KADM5_LOG_CORRUPT;
+ return 0;
+}
+
+/*
+ * Go to end of log.
+ */
+kadm5_ret_t
+kadm5_log_goto_end(kadm5_server_context *server_context, krb5_storage *sp)
+{
+ krb5_error_code ret = 0;
+ enum kadm_ops op;
+ uint32_t ver, len;
+ uint32_t tstamp;
+ uint64_t off;
+
+ if (krb5_storage_seek(sp, 0, SEEK_SET) == -1)
+ return errno;
+ ret = get_header(sp, LOG_NOPEEK, &ver, &tstamp, &op, &len);
+ if (ret == HEIM_ERR_EOF) {
+ (void) krb5_storage_seek(sp, 0, SEEK_SET);
+ return 0;
+ }
+ if (ret == KADM5_LOG_CORRUPT)
+ goto truncate;
+ if (ret)
+ return ret;
+
+ if (op == kadm_nop && len == LOG_UBER_LEN) {
+ /* New style log */
+ ret = krb5_ret_uint64(sp, &off);
+ if (ret)
+ goto truncate;
+
+ if (krb5_storage_seek(sp, off, SEEK_SET) == -1)
+ return ret;
+
+ if (off >= LOG_UBER_SZ) {
+ ret = get_version_prev(sp, &ver, NULL);
+ if (ret == 0)
+ return 0;
+ }
+ /* Invalid offset in uber entry */
+ goto truncate;
+ }
+
+ /* Old log with no uber entry */
+ if (krb5_storage_seek(sp, 0, SEEK_END) == -1) {
+ static int warned = 0;
+ if (!warned) {
+ warned = 1;
+ krb5_warnx(server_context->context,
+ "Old log found; truncate it to upgrade");
+ }
+ }
+ ret = get_version_prev(sp, &ver, NULL);
+ if (ret)
+ goto truncate;
+ return 0;
+
+truncate:
+ /* If we can, truncate */
+ if (server_context->log_context.lock_mode == LOCK_EX) {
+ ret = kadm5_log_reinit(server_context, 0);
+ if (ret == 0) {
+ krb5_warn(server_context->context, ret,
+ "Invalid log; truncating to recover");
+ if (krb5_storage_seek(sp, 0, SEEK_END) >= 0)
+ return 0;
+ }
+ }
+ ret = KADM5_LOG_CORRUPT;
+ krb5_warn(server_context->context, ret,
+ "Invalid log; truncate to recover");
+ return ret;
+}
+
+/*
+ * Return the next log entry.
+ *
+ * The pointer in `sp' is assumed to be at the end of an entry. On success,
+ * the `sp' pointer is set to the next entry (not the data portion). In case
+ * of error, it's not changed at all.
+ */
+kadm5_ret_t
+kadm5_log_next(krb5_context context,
+ krb5_storage *sp,
+ uint32_t *verp,
+ time_t *tstampp,
+ enum kadm_ops *opp,
+ uint32_t *lenp)
+{
+ uint32_t len = 0;
+ uint32_t len2 = 0;
+ uint32_t ver = verp ? *verp : 0;
+ uint32_t ver2;
+ uint32_t tstamp = tstampp ? *tstampp : 0;
+ enum kadm_ops op = kadm_nop;
+ off_t off = krb5_storage_seek(sp, 0, SEEK_CUR);
+ kadm5_ret_t ret = get_header(sp, LOG_NOPEEK, &ver, &tstamp, &op, &len);
+
+ /* Validate the trailer */
+ if (ret == 0 && krb5_storage_seek(sp, len, SEEK_CUR) == -1)
+ ret = errno;
+
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &len2);
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &ver2);
+ if (ret == 0 && (len != len2 || ver != ver2))
+ ret = KADM5_LOG_CORRUPT;
+ if (ret != 0) {
+ (void) krb5_storage_seek(sp, off, SEEK_SET);
+ return ret;
+ }
+
+ if (verp)
+ *verp = ver;
+ if (tstampp)
+ *tstampp = tstamp;
+ if (opp)
+ *opp = op;
+ if (lenp)
+ *lenp = len;
+ return 0;
+}
+
+/*
+ * Return previous log entry.
+ *
+ * The pointer in `sp' is assumed to be at the top of the entry after
+ * previous entry (e.g., at EOF). On success, the `sp' pointer is set to
+ * data portion of previous entry. In case of error, it's not changed
+ * at all.
+ */
+kadm5_ret_t
+kadm5_log_previous(krb5_context context,
+ krb5_storage *sp,
+ uint32_t *verp,
+ time_t *tstampp,
+ enum kadm_ops *opp,
+ uint32_t *lenp)
+{
+ krb5_error_code ret;
+ off_t oldoff;
+ uint32_t ver2, len2;
+ uint32_t tstamp;
+
+ oldoff = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (oldoff == -1)
+ goto log_corrupt;
+
+ /* This reads the physical version of the uber record */
+ if (seek_prev(sp, verp, lenp) == -1)
+ goto log_corrupt;
+
+ ret = get_header(sp, LOG_NOPEEK, &ver2, &tstamp, opp, &len2);
+ if (ret) {
+ (void) krb5_storage_seek(sp, oldoff, SEEK_SET);
+ return ret;
+ }
+ if (tstampp)
+ *tstampp = tstamp;
+ if (ver2 != *verp || len2 != *lenp)
+ goto log_corrupt;
+
+ return 0;
+
+log_corrupt:
+ (void) krb5_storage_seek(sp, oldoff, SEEK_SET);
+ return KADM5_LOG_CORRUPT;
+}
+
+/*
+ * Replay a record from the log
+ */
+
+kadm5_ret_t
+kadm5_log_replay(kadm5_server_context *context,
+ enum kadm_ops op,
+ uint32_t ver,
+ uint32_t len,
+ krb5_storage *sp)
+{
+ switch (op) {
+ case kadm_create :
+ return kadm5_log_replay_create(context, ver, len, sp);
+ case kadm_delete :
+ return kadm5_log_replay_delete(context, ver, len, sp);
+ case kadm_rename :
+ return kadm5_log_replay_rename(context, ver, len, sp);
+ case kadm_modify :
+ return kadm5_log_replay_modify(context, ver, len, sp);
+ case kadm_nop :
+ return kadm5_log_replay_nop(context, ver, len, sp);
+ default :
+ /*
+ * FIXME This default arm makes it difficult to add new kadm_ops
+ * values.
+ */
+ krb5_set_error_message(context->context, KADM5_FAILURE,
+ "Unsupported replay op %d", (int)op);
+ (void) krb5_storage_seek(sp, len, SEEK_CUR);
+ return KADM5_FAILURE;
+ }
+}
+
+struct load_entries_data {
+ krb5_data *entries;
+ unsigned char *p;
+ uint32_t first;
+ uint32_t last;
+ size_t bytes;
+ size_t nentries;
+ size_t maxbytes;
+ size_t maxentries;
+};
+
+
+/*
+ * Prepend one entry with header and trailer to the entry buffer, stopping when
+ * we've reached either of the byte or entry-count limits (if non-zero).
+ *
+ * This is a two-pass algorithm:
+ *
+ * In the first pass, when entries->entries == NULL, we compute the space
+ * required, and count the entries that fit up from zero.
+ *
+ * In the second pass we fill the buffer, and count the entries back down to
+ * zero. The space used must be an exact fit, and the number of entries must
+ * reach zero at that point or an error is returned.
+ *
+ * The caller MUST check that entries->nentries == 0 at the end of the second
+ * pass.
+ */
+static kadm5_ret_t
+load_entries_cb(kadm5_server_context *server_context,
+ uint32_t ver,
+ time_t timestamp,
+ enum kadm_ops op,
+ uint32_t len,
+ krb5_storage *sp,
+ void *ctx)
+{
+ struct load_entries_data *entries = ctx;
+ kadm5_ret_t ret;
+ ssize_t bytes;
+ size_t entry_len = len + LOG_WRAPPER_SZ;
+ unsigned char *base;
+
+ if (entries->entries == NULL) {
+ size_t total = entries->bytes + entry_len;
+
+ /*
+ * First run: find the size of krb5_data buffer needed.
+ *
+ * If the log was huge we'd have to perhaps open a temp file for this.
+ * For now KISS.
+ */
+ if ((op == kadm_nop && entry_len == LOG_UBER_SZ) ||
+ entry_len < len /*overflow?*/ ||
+ (entries->maxbytes > 0 && total > entries->maxbytes) ||
+ total < entries->bytes /*overflow?*/ ||
+ (entries->maxentries > 0 && entries->nentries == entries->maxentries))
+ return -1; /* stop iteration */
+ entries->bytes = total;
+ entries->first = ver;
+ if (entries->nentries++ == 0)
+ entries->last = ver;
+ return 0;
+ }
+
+ /* Second run: load the data into memory */
+ base = (unsigned char *)entries->entries->data;
+ if (entries->p - base < entry_len && entries->p != base) {
+ /*
+ * This can't happen normally: we stop the log record iteration
+ * above before we get here. This could happen if someone wrote
+ * garbage to the log while we were traversing it. We return an
+ * error instead of asserting.
+ */
+ return KADM5_LOG_CORRUPT;
+ }
+
+ /*
+ * sp here is a krb5_storage_from_fd() of the log file, and the
+ * offset pointer points at the current log record payload.
+ *
+ * Seek back to the start of the record poayload so we can read the
+ * whole record.
+ */
+ if (krb5_storage_seek(sp, -LOG_HEADER_SZ, SEEK_CUR) == -1)
+ return errno;
+
+ /*
+ * We read the header, payload, and trailer into the buffer we have, that
+ * many bytes before the previous record we read.
+ */
+ errno = 0;
+ bytes = krb5_storage_read(sp, entries->p - entry_len, entry_len);
+ ret = errno;
+ if (bytes < 0 || bytes != entry_len)
+ return ret ? ret : EIO;
+
+ entries->first = ver;
+ --entries->nentries;
+ entries->p -= entry_len;
+ return (entries->p == base) ? -1 : 0;
+}
+
+
+/*
+ * Serialize a tail fragment of the log as a krb5_data, this is constrained to
+ * at most `maxbytes' bytes and to at most `maxentries' entries if not zero.
+ */
+static kadm5_ret_t
+load_entries(kadm5_server_context *context, krb5_data *p,
+ size_t maxentries, size_t maxbytes,
+ uint32_t *first, uint32_t *last)
+{
+ struct load_entries_data entries;
+ kadm5_ret_t ret;
+ unsigned char *base;
+
+ krb5_data_zero(p);
+
+ *first = 0;
+
+ memset(&entries, 0, sizeof(entries));
+ entries.entries = NULL;
+ entries.p = NULL;
+ entries.maxentries = maxentries;
+ entries.maxbytes = maxbytes;
+
+ /* Figure out how many bytes it will take */
+ ret = kadm5_log_foreach(context, kadm_backward | kadm_confirmed,
+ NULL, load_entries_cb, &entries);
+ if (ret)
+ return ret;
+
+ /*
+ * If no entries fit our limits, we do not truncate, instead the caller can
+ * call kadm5_log_reinit() if desired.
+ */
+ if (entries.bytes == 0)
+ return 0;
+
+ ret = krb5_data_alloc(p, entries.bytes);
+ if (ret)
+ return ret;
+
+ *first = entries.first;
+ *last = entries.last;
+ entries.entries = p;
+ base = (unsigned char *)entries.entries->data;
+ entries.p = base + entries.bytes;
+
+ ret = kadm5_log_foreach(context, kadm_backward | kadm_confirmed,
+ NULL, load_entries_cb, &entries);
+ if (ret == 0 &&
+ (entries.nentries || entries.p != base || entries.first != *first))
+ ret = KADM5_LOG_CORRUPT;
+ if (ret)
+ krb5_data_free(p);
+ return ret;
+}
+
+/*
+ * Truncate the log, retaining at most `keep' entries and at most `maxbytes'.
+ * If `maxbytes' is zero, keep at most the default log size limit.
+ */
+kadm5_ret_t
+kadm5_log_truncate(kadm5_server_context *context, size_t keep, size_t maxbytes)
+{
+ kadm5_ret_t ret;
+ uint32_t first, last, last_tstamp;
+ time_t now = time(NULL);
+ krb5_data entries;
+ krb5_storage *sp;
+ ssize_t bytes;
+ uint64_t sz;
+ off_t off;
+
+ if (maxbytes == 0)
+ maxbytes = get_max_log_size(context->context);
+
+ if (strcmp(context->log_context.log_file, "/dev/null") == 0)
+ return 0;
+
+ if (context->log_context.read_only)
+ return EROFS;
+
+ /* Get the desired records. */
+ krb5_data_zero(&entries);
+ ret = load_entries(context, &entries, keep, maxbytes, &first, &last);
+ if (ret)
+ return ret;
+
+ if (first == 0) {
+ /*
+ * No records found/fit within resource limits. The caller should call
+ * kadm5_log_reinit(context) to truly truncate and reset the log to
+ * version 0, else call again with better limits.
+ */
+ krb5_data_free(&entries);
+ return EINVAL;
+ }
+
+ /* Check that entries.length won't overflow off_t */
+ sz = LOG_UBER_SZ + entries.length;
+ off = (off_t)sz;
+ if (off < 0 || off != sz || sz < entries.length) {
+ krb5_data_free(&entries);
+ return EOVERFLOW; /* caller should ask for fewer entries */
+ }
+
+ /* Truncate to zero size and seek to zero offset */
+ if (ftruncate(context->log_context.log_fd, 0) < 0 ||
+ lseek(context->log_context.log_fd, 0, SEEK_SET) < 0) {
+ krb5_data_free(&entries);
+ return errno;
+ }
+
+ /*
+ * Write the uber record and then the records loaded. Confirm the entries
+ * after writing them.
+ *
+ * If we crash then the log may not have all the entries we want, and
+ * replaying only some of the entries will leave us in a bad state.
+ * Additionally, we don't have mathematical proof that replaying the last
+ * N>1 entries is always idempotent. And though we believe we can make
+ * such replays idempotent, they would still leave the HDB with
+ * intermediate states that would not have occurred on the master.
+ *
+ * By initially setting the offset in the uber record to 0, the log will be
+ * seen as invalid should we crash here, thus the only
+ * harm will be that we'll reinitialize the log and force full props.
+ *
+ * We can't use the normal kadm5_log_*() machinery for this because
+ * we must set specific version numbers and timestamps. To keep
+ * things simple we don't try to do a single atomic write here as we
+ * do in kadm5_log_flush().
+ *
+ * We really do want to keep the new first entry's version and
+ * timestamp so we don't trip up iprop.
+ *
+ * Keep this in sync with kadm5_log_nop().
+ */
+ sp = krb5_storage_from_fd(context->log_context.log_fd);
+ if (sp == NULL) {
+ ret = errno;
+ krb5_warn(context->context, ret, "Unable to keep entries");
+ krb5_data_free(&entries);
+ return errno;
+ }
+ ret = krb5_store_uint32(sp, 0);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, now);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, kadm_nop); /* end of preamble */
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, LOG_UBER_LEN); /* end of header */
+ if (ret == 0)
+ ret = krb5_store_uint64(sp, LOG_UBER_SZ);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, now);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, last);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, LOG_UBER_LEN);
+ if (ret == 0)
+ ret = krb5_store_uint32(sp, 0); /* end of trailer */
+ if (ret == 0) {
+ bytes = krb5_storage_write(sp, entries.data, entries.length);
+ if (bytes != entries.length)
+ ret = bytes == -1 ? errno : EIO;
+ }
+ if (ret == 0)
+ ret = krb5_storage_fsync(sp);
+ /* Confirm all the records now */
+ if (ret == 0) {
+ if (krb5_storage_seek(sp, LOG_HEADER_SZ, SEEK_SET) == -1)
+ ret = errno;
+ }
+ if (ret == 0)
+ ret = krb5_store_uint64(sp, off);
+ krb5_data_free(&entries);
+ krb5_storage_free(sp);
+
+ if (ret) {
+ krb5_warn(context->context, ret, "Unable to keep entries");
+ (void) ftruncate(context->log_context.log_fd, LOG_UBER_SZ);
+ (void) lseek(context->log_context.log_fd, 0, SEEK_SET);
+ return ret;
+ }
+
+ /* Done. Now rebuild the log_context state. */
+ (void) lseek(context->log_context.log_fd, off, SEEK_SET);
+ sp = krb5_storage_from_fd(context->log_context.log_fd);
+ if (sp == NULL)
+ return errno ? errno : krb5_enomem(context->context);
+ ret = kadm5_log_goto_end(context, sp);
+ if (ret == 0) {
+ ret = get_version_prev(sp, &context->log_context.version, &last_tstamp);
+ if (ret == 0)
+ context->log_context.last_time = last_tstamp;
+ }
+ krb5_storage_free(sp);
+ return ret;
+}
+
+/*
+ * "Truncate" the log if not read only and over the desired maximum size. We
+ * attempt to retain 1/4 of the existing storage.
+ *
+ * Called after successful log recovery, so at this point we must have no
+ * unconfirmed entries in the log.
+ */
+static kadm5_ret_t
+truncate_if_needed(kadm5_server_context *context)
+{
+ kadm5_ret_t ret = 0;
+ kadm5_log_context *log_context = &context->log_context;
+ size_t maxbytes;
+ struct stat st;
+
+ if (log_context->log_fd == -1 || log_context->read_only)
+ return 0;
+ if (strcmp(context->log_context.log_file, "/dev/null") == 0)
+ return 0;
+
+ maxbytes = get_max_log_size(context->context);
+ if (maxbytes <= 0)
+ return 0;
+
+ if (fstat(log_context->log_fd, &st) == -1)
+ return errno;
+ if (st.st_size == (size_t)st.st_size && (size_t)st.st_size <= maxbytes)
+ return 0;
+
+ /* Shrink the log by a factor of 4 */
+ ret = kadm5_log_truncate(context, 0, maxbytes/4);
+ return ret == EINVAL ? 0 : ret;
+}
+
+#ifndef NO_UNIX_SOCKETS
+
+static char *default_signal = NULL;
+static HEIMDAL_MUTEX signal_mutex = HEIMDAL_MUTEX_INITIALIZER;
+
+const char *
+kadm5_log_signal_socket(krb5_context context)
+{
+ int ret = 0;
+
+ HEIMDAL_MUTEX_lock(&signal_mutex);
+ if (!default_signal)
+ ret = asprintf(&default_signal, "%s/signal", hdb_db_dir(context));
+ if (ret == -1)
+ default_signal = NULL;
+ HEIMDAL_MUTEX_unlock(&signal_mutex);
+
+ return krb5_config_get_string_default(context,
+ NULL,
+ default_signal,
+ "kdc",
+ "signal_socket",
+ NULL);
+}
+
+#else /* NO_UNIX_SOCKETS */
+
+#define SIGNAL_SOCKET_HOST "127.0.0.1"
+#define SIGNAL_SOCKET_PORT "12701"
+
+kadm5_ret_t
+kadm5_log_signal_socket_info(krb5_context context,
+ int server_end,
+ struct addrinfo **ret_addrs)
+{
+ struct addrinfo hints;
+ struct addrinfo *addrs = NULL;
+ kadm5_ret_t ret = KADM5_FAILURE;
+ int wsret;
+
+ memset(&hints, 0, sizeof(hints));
+
+ hints.ai_flags = AI_NUMERICHOST;
+ if (server_end)
+ hints.ai_flags |= AI_PASSIVE;
+ hints.ai_family = AF_INET;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_protocol = IPPROTO_TCP;
+
+ wsret = getaddrinfo(SIGNAL_SOCKET_HOST,
+ SIGNAL_SOCKET_PORT,
+ &hints, &addrs);
+
+ if (wsret != 0) {
+ krb5_set_error_message(context, KADM5_FAILURE,
+ "%s", gai_strerror(wsret));
+ goto done;
+ }
+
+ if (addrs == NULL) {
+ krb5_set_error_message(context, KADM5_FAILURE,
+ "getaddrinfo() failed to return address list");
+ goto done;
+ }
+
+ *ret_addrs = addrs;
+ addrs = NULL;
+ ret = 0;
+
+ done:
+ if (addrs)
+ freeaddrinfo(addrs);
+ return ret;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/kadm5/marshall.c b/third_party/heimdal/lib/kadm5/marshall.c
new file mode 100644
index 0000000..9d24233
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/marshall.c
@@ -0,0 +1,474 @@
+/*
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+#define CHECK(e) do { if ((ret = e)) goto out; } while (0)
+
+int
+kadm5_some_keys_are_bogus(size_t n_keys, krb5_key_data *keys)
+{
+ size_t i;
+
+ for (i = 0; i < n_keys; i++) {
+ krb5_key_data *key = &keys[i];
+ if (key->key_data_length[0] == sizeof(KADM5_BOGUS_KEY_DATA) - 1 &&
+ ct_memcmp(key->key_data_contents[1], KADM5_BOGUS_KEY_DATA,
+ key->key_data_length[0]) == 0)
+ return 1;
+ }
+ return 0;
+}
+
+int
+kadm5_all_keys_are_bogus(size_t n_keys, krb5_key_data *keys)
+{
+ size_t i;
+
+ if (n_keys == 0)
+ return 0;
+
+ for (i = 0; i < n_keys; i++) {
+ krb5_key_data *key = &keys[i];
+ if (key->key_data_length[0] != sizeof(KADM5_BOGUS_KEY_DATA) - 1 ||
+ ct_memcmp(key->key_data_contents[1], KADM5_BOGUS_KEY_DATA,
+ key->key_data_length[0]) != 0)
+ return 0;
+ }
+ return 1;
+}
+
+kadm5_ret_t
+kadm5_store_key_data(krb5_storage *sp,
+ krb5_key_data *key)
+{
+ kadm5_ret_t ret;
+ krb5_data c;
+
+ CHECK(krb5_store_int32(sp, key->key_data_ver));
+ CHECK(krb5_store_int32(sp, key->key_data_kvno));
+ CHECK(krb5_store_int32(sp, key->key_data_type[0]));
+ c.length = key->key_data_length[0];
+ c.data = key->key_data_contents[0];
+ CHECK(krb5_store_data(sp, c));
+ CHECK(krb5_store_int32(sp, key->key_data_type[1]));
+ c.length = key->key_data_length[1];
+ c.data = key->key_data_contents[1];
+ CHECK(krb5_store_data(sp, c));
+
+out:
+ return ret;
+}
+
+kadm5_ret_t
+kadm5_store_fake_key_data(krb5_storage *sp,
+ krb5_key_data *key)
+{
+ kadm5_ret_t ret;
+ krb5_data c;
+
+ CHECK(krb5_store_int32(sp, key->key_data_ver));
+ CHECK(krb5_store_int32(sp, key->key_data_kvno));
+ CHECK(krb5_store_int32(sp, key->key_data_type[0]));
+
+ /*
+ * This is the key contents. We want it to be obvious to the client
+ * (if it really did want the keys) that the key won't work.
+ * 32-bit keys are no good for any enctype, so that should do.
+ * Clients that didn't need keys will ignore this, and clients that
+ * did want keys will either fail or they'll, say, create bogus
+ * keytab entries that will subsequently fail to be useful.
+ */
+ c.length = sizeof (KADM5_BOGUS_KEY_DATA) - 1;
+ c.data = KADM5_BOGUS_KEY_DATA;
+ CHECK(krb5_store_data(sp, c));
+
+ /* This is the salt -- no need to send garbage */
+ CHECK(krb5_store_int32(sp, key->key_data_type[1]));
+ c.length = key->key_data_length[1];
+ c.data = key->key_data_contents[1];
+ CHECK(krb5_store_data(sp, c));
+
+out:
+ return ret;
+}
+
+kadm5_ret_t
+kadm5_ret_key_data(krb5_storage *sp,
+ krb5_key_data *key)
+{
+ kadm5_ret_t ret;
+ krb5_data c;
+ int32_t tmp;
+
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret == 0) {
+ key->key_data_ver = tmp;
+ ret = krb5_ret_int32(sp, &tmp);
+ }
+ if (ret == 0) {
+ key->key_data_kvno = tmp;
+ ret = krb5_ret_int32(sp, &tmp);
+ }
+ if (ret == 0) {
+ key->key_data_type[0] = tmp;
+ ret = krb5_ret_data(sp, &c);
+ }
+ if (ret == 0) {
+ key->key_data_length[0] = c.length;
+ key->key_data_contents[0] = c.data;
+ ret = krb5_ret_int32(sp, &tmp);
+ }
+ if (ret == 0) {
+ key->key_data_type[1] = tmp;
+ ret = krb5_ret_data(sp, &c);
+ }
+ if (ret == 0) {
+ key->key_data_length[1] = c.length;
+ key->key_data_contents[1] = c.data;
+ return 0;
+ }
+ return KADM5_FAILURE;
+}
+
+kadm5_ret_t
+kadm5_store_tl_data(krb5_storage *sp,
+ krb5_tl_data *tl)
+{
+ kadm5_ret_t ret;
+ krb5_data c;
+
+ CHECK(krb5_store_int32(sp, tl->tl_data_type));
+ c.length = tl->tl_data_length;
+ c.data = tl->tl_data_contents;
+ CHECK(krb5_store_data(sp, c));
+
+out:
+ return ret;
+}
+
+kadm5_ret_t
+kadm5_ret_tl_data(krb5_storage *sp,
+ krb5_tl_data *tl)
+{
+ kadm5_ret_t ret;
+ krb5_data c;
+ int32_t tmp;
+
+ CHECK(krb5_ret_int32(sp, &tmp));
+ tl->tl_data_type = tmp;
+ CHECK(krb5_ret_data(sp, &c));
+ tl->tl_data_length = c.length;
+ tl->tl_data_contents = c.data;
+
+out:
+ return ret;
+}
+
+static kadm5_ret_t
+store_principal_ent(krb5_storage *sp,
+ kadm5_principal_ent_t princ,
+ uint32_t mask, int wkeys)
+{
+ kadm5_ret_t ret = 0;
+ int i;
+
+ if (mask & KADM5_PRINCIPAL)
+ CHECK(krb5_store_principal(sp, princ->principal));
+ if (mask & KADM5_PRINC_EXPIRE_TIME)
+ CHECK(krb5_store_int32(sp, princ->princ_expire_time));
+ if (mask & KADM5_PW_EXPIRATION)
+ CHECK(krb5_store_int32(sp, princ->pw_expiration));
+ if (mask & KADM5_LAST_PWD_CHANGE)
+ CHECK(krb5_store_int32(sp, princ->last_pwd_change));
+ if (mask & KADM5_MAX_LIFE)
+ CHECK(krb5_store_int32(sp, princ->max_life));
+ if (mask & KADM5_MOD_NAME) {
+ CHECK(krb5_store_int32(sp, princ->mod_name != NULL));
+ if(princ->mod_name)
+ CHECK(krb5_store_principal(sp, princ->mod_name));
+ }
+ if (mask & KADM5_MOD_TIME)
+ CHECK(krb5_store_int32(sp, princ->mod_date));
+ if (mask & KADM5_ATTRIBUTES)
+ CHECK(krb5_store_int32(sp, princ->attributes));
+ if (mask & KADM5_KVNO)
+ CHECK(krb5_store_int32(sp, princ->kvno));
+ if (mask & KADM5_MKVNO)
+ CHECK(krb5_store_int32(sp, princ->mkvno));
+ if (mask & KADM5_POLICY) {
+ CHECK(krb5_store_int32(sp, princ->policy != NULL));
+ if(princ->policy)
+ CHECK(krb5_store_string(sp, princ->policy));
+ }
+ if (mask & KADM5_AUX_ATTRIBUTES)
+ CHECK(krb5_store_int32(sp, princ->aux_attributes));
+ if (mask & KADM5_MAX_RLIFE)
+ CHECK(krb5_store_int32(sp, princ->max_renewable_life));
+ if (mask & KADM5_LAST_SUCCESS)
+ CHECK(krb5_store_int32(sp, princ->last_success));
+ if (mask & KADM5_LAST_FAILED)
+ CHECK(krb5_store_int32(sp, princ->last_failed));
+ if (mask & KADM5_FAIL_AUTH_COUNT)
+ CHECK(krb5_store_int32(sp, princ->fail_auth_count));
+ if (mask & KADM5_KEY_DATA) {
+ CHECK(krb5_store_int32(sp, princ->n_key_data));
+ for(i = 0; i < princ->n_key_data; i++) {
+ if (wkeys)
+ CHECK(kadm5_store_key_data(sp, &princ->key_data[i]));
+ else
+ CHECK(kadm5_store_fake_key_data(sp, &princ->key_data[i]));
+ }
+ }
+ if (mask & KADM5_TL_DATA) {
+ krb5_tl_data *tp;
+
+ CHECK(krb5_store_int32(sp, princ->n_tl_data));
+ for (tp = princ->tl_data; tp; tp = tp->tl_data_next)
+ CHECK(kadm5_store_tl_data(sp, tp));
+ }
+
+out:
+ return ret;
+}
+
+
+kadm5_ret_t
+kadm5_store_principal_ent(krb5_storage *sp,
+ kadm5_principal_ent_t princ)
+{
+ return store_principal_ent (sp, princ, ~0, 1);
+}
+
+kadm5_ret_t
+kadm5_store_principal_ent_nokeys(krb5_storage *sp,
+ kadm5_principal_ent_t princ)
+{
+ return store_principal_ent (sp, princ, ~0, 0);
+}
+
+kadm5_ret_t
+kadm5_store_principal_ent_mask(krb5_storage *sp,
+ kadm5_principal_ent_t princ,
+ uint32_t mask)
+{
+ kadm5_ret_t ret;
+
+ ret = krb5_store_int32(sp, mask);
+ if (ret == 0)
+ ret = store_principal_ent(sp, princ, mask, 1);
+ return ret;
+}
+
+static kadm5_ret_t
+ret_principal_ent(krb5_storage *sp,
+ kadm5_principal_ent_t princ,
+ uint32_t mask)
+{
+ kadm5_ret_t ret = 0;
+ int i;
+ int32_t tmp;
+
+ if (mask & KADM5_PRINCIPAL)
+ CHECK(krb5_ret_principal(sp, &princ->principal));
+
+ if (mask & KADM5_PRINC_EXPIRE_TIME) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->princ_expire_time = tmp;
+ }
+ if (mask & KADM5_PW_EXPIRATION) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->pw_expiration = tmp;
+ }
+ if (mask & KADM5_LAST_PWD_CHANGE) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->last_pwd_change = tmp;
+ }
+ if (mask & KADM5_MAX_LIFE) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->max_life = tmp;
+ }
+ if (mask & KADM5_MOD_NAME) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ if(tmp)
+ CHECK(krb5_ret_principal(sp, &princ->mod_name));
+ else
+ princ->mod_name = NULL;
+ }
+ if (mask & KADM5_MOD_TIME) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->mod_date = tmp;
+ }
+ if (mask & KADM5_ATTRIBUTES) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->attributes = tmp;
+ }
+ if (mask & KADM5_KVNO) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->kvno = tmp;
+ }
+ if (mask & KADM5_MKVNO) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->mkvno = tmp;
+ }
+ if (mask & KADM5_POLICY) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ if(tmp)
+ CHECK(krb5_ret_string(sp, &princ->policy));
+ else
+ princ->policy = NULL;
+ }
+ if (mask & KADM5_AUX_ATTRIBUTES) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->aux_attributes = tmp;
+ }
+ if (mask & KADM5_MAX_RLIFE) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->max_renewable_life = tmp;
+ }
+ if (mask & KADM5_LAST_SUCCESS) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->last_success = tmp;
+ }
+ if (mask & KADM5_LAST_FAILED) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->last_failed = tmp;
+ }
+ if (mask & KADM5_FAIL_AUTH_COUNT) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->fail_auth_count = tmp;
+ }
+ if (mask & KADM5_KEY_DATA) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->n_key_data = tmp;
+ princ->key_data = malloc(princ->n_key_data * sizeof(*princ->key_data));
+ if (princ->key_data == NULL && princ->n_key_data != 0)
+ return ENOMEM;
+ for(i = 0; i < princ->n_key_data; i++)
+ ret = kadm5_ret_key_data(sp, &princ->key_data[i]);
+ }
+ if (mask & KADM5_TL_DATA) {
+ CHECK(krb5_ret_int32(sp, &tmp));
+ princ->n_tl_data = tmp;
+ princ->tl_data = NULL;
+ for(i = 0; i < princ->n_tl_data; i++){
+ krb5_tl_data *tp = malloc(sizeof(*tp));
+ if (tp == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ ret = kadm5_ret_tl_data(sp, tp);
+ if (ret == 0) {
+ tp->tl_data_next = princ->tl_data;
+ princ->tl_data = tp;
+ } else {
+ free(tp);
+ goto out;
+ }
+ }
+ }
+
+out:
+ /* Can't free princ here -- we don't have a context */
+ return ret;
+}
+
+kadm5_ret_t
+kadm5_ret_principal_ent(krb5_storage *sp,
+ kadm5_principal_ent_t princ)
+{
+ return ret_principal_ent (sp, princ, ~0);
+}
+
+kadm5_ret_t
+kadm5_ret_principal_ent_mask(krb5_storage *sp,
+ kadm5_principal_ent_t princ,
+ uint32_t *mask)
+{
+ kadm5_ret_t ret;
+ int32_t tmp;
+
+ ret = krb5_ret_int32 (sp, &tmp);
+ if (ret) {
+ *mask = 0;
+ return ret;
+ }
+ *mask = tmp;
+ return ret_principal_ent (sp, princ, *mask);
+}
+
+kadm5_ret_t
+_kadm5_marshal_params(krb5_context context,
+ kadm5_config_params *params,
+ krb5_data *out)
+{
+ kadm5_ret_t ret;
+
+ krb5_storage *sp = krb5_storage_emem();
+ if (sp == NULL)
+ return krb5_enomem(context);
+
+ ret = krb5_store_int32(sp, params->mask & (KADM5_CONFIG_REALM));
+ if (ret == 0 && (params->mask & KADM5_CONFIG_REALM))
+ ret = krb5_store_string(sp, params->realm);
+ if (ret == 0)
+ ret = krb5_storage_to_data(sp, out);
+ krb5_storage_free(sp);
+ return ret;
+}
+
+kadm5_ret_t
+_kadm5_unmarshal_params(krb5_context context,
+ krb5_data *in,
+ kadm5_config_params *params)
+{
+ kadm5_ret_t ret;
+ krb5_storage *sp;
+ int32_t mask;
+
+ sp = krb5_storage_from_data(in);
+ if (sp == NULL)
+ return ENOMEM;
+
+ ret = krb5_ret_int32(sp, &mask);
+ if (ret)
+ goto out;
+ params->mask = mask;
+
+ if(params->mask & KADM5_CONFIG_REALM)
+ ret = krb5_ret_string(sp, &params->realm);
+ out:
+ krb5_storage_free(sp);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kadm5/modify_c.c b/third_party/heimdal/lib/kadm5/modify_c.c
new file mode 100644
index 0000000..a38cb33
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/modify_c.c
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_c_modify_principal(void *server_handle,
+ kadm5_principal_ent_t princ,
+ uint32_t mask)
+{
+ kadm5_client_context *context = server_handle;
+ kadm5_ret_t ret;
+ krb5_storage *sp;
+ unsigned char buf[1024];
+ int32_t tmp;
+ krb5_data reply;
+
+ ret = _kadm5_connect(server_handle, 1 /* want_write */);
+ if (ret)
+ return ret;
+
+ krb5_data_zero(&reply);
+
+ sp = krb5_storage_from_mem(buf, sizeof(buf));
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_store_int32(sp, kadm_modify);
+ if (ret)
+ goto out;
+ ret = kadm5_store_principal_ent(sp, princ);
+ if (ret)
+ goto out;
+ ret = krb5_store_int32(sp, mask);
+ if (ret)
+ goto out;
+ ret = _kadm5_client_send(context, sp);
+ if (ret)
+ goto out_keep_error;
+ ret = _kadm5_client_recv(context, &reply);
+ if (ret)
+ goto out_keep_error;
+ krb5_storage_free(sp);
+ sp = krb5_storage_from_data(&reply);
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret == 0)
+ ret = tmp;
+
+ out:
+ krb5_clear_error_message(context->context);
+
+ out_keep_error:
+ krb5_storage_free(sp);
+ krb5_data_free(&reply);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kadm5/modify_s.c b/third_party/heimdal/lib/kadm5/modify_s.c
new file mode 100644
index 0000000..2159caf
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/modify_s.c
@@ -0,0 +1,215 @@
+/*
+ * Copyright (c) 1997-2001, 2003, 2005-2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+struct modify_principal_hook_ctx {
+ kadm5_server_context *context;
+ enum kadm5_hook_stage stage;
+ krb5_error_code code;
+ kadm5_principal_ent_t princ;
+ uint32_t mask;
+};
+
+static krb5_error_code KRB5_LIB_CALL
+modify_principal_hook_cb(krb5_context context,
+ const void *hook,
+ void *hookctx,
+ void *userctx)
+{
+ krb5_error_code ret;
+ const struct kadm5_hook_ftable *ftable = hook;
+ struct modify_principal_hook_ctx *ctx = userctx;
+
+ ret = ftable->modify(context, hookctx, ctx->stage,
+ ctx->code, ctx->princ, ctx->mask);
+ if (ret != 0 && ret != KRB5_PLUGIN_NO_HANDLE)
+ _kadm5_s_set_hook_error_message(ctx->context, ret, "modify",
+ hook, ctx->stage);
+
+ /* only pre-commit plugins can abort */
+ if (ret == 0 || ctx->stage == KADM5_HOOK_STAGE_POSTCOMMIT)
+ ret = KRB5_PLUGIN_NO_HANDLE;
+
+ return ret;
+}
+
+static kadm5_ret_t
+modify_principal_hook(kadm5_server_context *context,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ kadm5_principal_ent_t princ,
+ uint32_t mask)
+{
+ krb5_error_code ret;
+ struct modify_principal_hook_ctx ctx;
+
+ ctx.context = context;
+ ctx.stage = stage;
+ ctx.code = code;
+ ctx.princ = princ;
+ ctx.mask = mask;
+
+ ret = _krb5_plugin_run_f(context->context, &kadm5_hook_plugin_data,
+ 0, &ctx, modify_principal_hook_cb);
+ if (ret == KRB5_PLUGIN_NO_HANDLE)
+ ret = 0;
+
+ return ret;
+}
+
+static kadm5_ret_t
+modify_principal(void *server_handle,
+ kadm5_principal_ent_t princ,
+ uint32_t mask,
+ uint32_t forbidden_mask)
+{
+ kadm5_server_context *context = server_handle;
+ hdb_entry ent;
+ kadm5_ret_t ret;
+
+ memset(&ent, 0, sizeof(ent));
+
+ if((mask & forbidden_mask))
+ return KADM5_BAD_MASK;
+ if((mask & KADM5_POLICY) && strcmp(princ->policy, "default") != 0)
+ return KADM5_UNK_POLICY;
+
+ if (!context->keep_open) {
+ ret = context->db->hdb_open(context->context, context->db, O_RDWR, 0);
+ if(ret)
+ return ret;
+ }
+
+ ret = kadm5_log_init(context);
+ if (ret)
+ goto out;
+
+ /*
+ * NOTE: We do not use hdb_fetch_kvno() here, which means we'll
+ * automatically reject modifications of would-be virtual principals.
+ */
+ ret = context->db->hdb_fetch_kvno(context->context, context->db,
+ princ->principal,
+ HDB_F_DECRYPT|HDB_F_GET_ANY|HDB_F_ADMIN_DATA,
+ 0, &ent);
+ if (ret)
+ goto out2;
+
+ ret = modify_principal_hook(context, KADM5_HOOK_STAGE_PRECOMMIT,
+ 0, princ, mask);
+ if (ret)
+ goto out3;
+ /*
+ * XXX Make sure that _kadm5_setup_entry() checks that the time of last
+ * change in `ent' matches the one in `princ'.
+ */
+ ret = _kadm5_setup_entry(context, &ent, mask, princ, mask, NULL, 0);
+ if (ret)
+ goto out3;
+ ret = _kadm5_set_modifier(context, &ent);
+ if (ret)
+ goto out3;
+
+ /*
+ * If any keys are bogus, disallow the modify. If the keys were
+ * bogus as stored in the HDB we could allow those through, but
+ * distinguishing that case from a pre-1.6 client using add_enctype
+ * without the get-keys privilege requires more work (mainly: checking that
+ * the bogus keys in princ->key_data[] have corresponding bogus keys in ent
+ * before calling _kadm5_setup_entry()).
+ */
+ if ((mask & KADM5_KEY_DATA) &&
+ kadm5_some_keys_are_bogus(princ->n_key_data, princ->key_data)) {
+ ret = KADM5_AUTH_GET_KEYS; /* Not quite appropriate, but it'll do */
+ goto out3;
+ }
+
+ ret = hdb_seal_keys(context->context, context->db, &ent);
+ if (ret)
+ goto out3;
+
+ if ((mask & KADM5_POLICY)) {
+ HDB_extension ext;
+
+ memset(&ext, 0, sizeof(ext));
+ /* XXX should be TRUE, but we don't yet support policies */
+ ext.mandatory = FALSE;
+ ext.data.element = choice_HDB_extension_data_policy;
+ ext.data.u.policy = strdup(princ->policy);
+ if (ext.data.u.policy == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out3;
+ }
+ /* This calls free_HDB_extension(), freeing ext.data.u.policy */
+ ret = hdb_replace_extension(context->context, &ent, &ext);
+ free(ext.data.u.policy);
+ if (ret)
+ goto out3;
+ }
+
+ /* This logs the change for iprop and writes to the HDB */
+ ret = kadm5_log_modify(context, &ent,
+ mask | KADM5_MOD_NAME | KADM5_MOD_TIME);
+
+ (void) modify_principal_hook(context, KADM5_HOOK_STAGE_POSTCOMMIT,
+ ret, princ, mask);
+
+ out3:
+ hdb_free_entry(context->context, context->db, &ent);
+ out2:
+ (void) kadm5_log_end(context);
+ out:
+ if (!context->keep_open) {
+ kadm5_ret_t ret2;
+ ret2 = context->db->hdb_close(context->context, context->db);
+ if (ret == 0 && ret2 != 0)
+ ret = ret2;
+ }
+ return _kadm5_error_code(ret);
+}
+
+
+kadm5_ret_t
+kadm5_s_modify_principal(void *server_handle,
+ kadm5_principal_ent_t princ,
+ uint32_t mask)
+{
+ return modify_principal(server_handle, princ, mask,
+ KADM5_LAST_PWD_CHANGE | KADM5_MOD_TIME
+ | KADM5_MOD_NAME | KADM5_MKVNO
+ | KADM5_AUX_ATTRIBUTES | KADM5_LAST_SUCCESS
+ | KADM5_LAST_FAILED);
+}
diff --git a/third_party/heimdal/lib/kadm5/password_quality.c b/third_party/heimdal/lib/kadm5/password_quality.c
new file mode 100644
index 0000000..84c1d39
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/password_quality.c
@@ -0,0 +1,508 @@
+/*
+ * Copyright (c) 1997-2000, 2003-2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+#include "kadm5-pwcheck.h"
+
+#ifdef HAVE_SYS_WAIT_H
+#include <sys/wait.h>
+#endif
+
+static int
+min_length_passwd_quality (krb5_context context,
+ krb5_principal principal,
+ krb5_data *pwd,
+ const char *opaque,
+ char *message,
+ size_t length)
+{
+ uint32_t min_length = krb5_config_get_int_default(context, NULL, 6,
+ "password_quality",
+ "min_length",
+ NULL);
+
+ if (pwd->length < min_length) {
+ strlcpy(message, "Password too short", length);
+ return 1;
+ } else
+ return 0;
+}
+
+static const char *
+min_length_passwd_quality_v0 (krb5_context context,
+ krb5_principal principal,
+ krb5_data *pwd)
+{
+ static char message[1024];
+ int ret;
+
+ message[0] = '\0';
+
+ ret = min_length_passwd_quality(context, principal, pwd, NULL,
+ message, sizeof(message));
+ if (ret)
+ return message;
+ return NULL;
+}
+
+
+static int
+char_class_passwd_quality (krb5_context context,
+ krb5_principal principal,
+ krb5_data *pwd,
+ const char *opaque,
+ char *message,
+ size_t length)
+{
+ const char *classes[] = {
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
+ "abcdefghijklmnopqrstuvwxyz",
+ "1234567890",
+ " !\"#$%&'()*+,-./:;<=>?@\\]^_`{|}~"
+ };
+ int counter = 0, req_classes;
+ size_t i, len;
+ char *pw;
+
+ req_classes = krb5_config_get_int_default(context, NULL, 3,
+ "password_quality",
+ "min_classes",
+ NULL);
+
+ len = pwd->length + 1;
+ pw = malloc(len);
+ if (pw == NULL) {
+ strlcpy(message, "out of memory", length);
+ return 1;
+ }
+ strlcpy(pw, pwd->data, len);
+ len = strlen(pw);
+
+ for (i = 0; i < sizeof(classes)/sizeof(classes[0]); i++) {
+ if (strcspn(pw, classes[i]) < len)
+ counter++;
+ }
+ memset(pw, 0, pwd->length + 1);
+ free(pw);
+ if (counter < req_classes) {
+ snprintf(message, length,
+ "Password doesn't meet complexity requirement.\n"
+ "Add more characters from at least %d of the\n"
+ "following classes:\n"
+ "1. English uppercase characters (A through Z)\n"
+ "2. English lowercase characters (a through z)\n"
+ "3. Base 10 digits (0 through 9)\n"
+ "4. Nonalphanumeric characters (e.g., !, $, #, %%)", req_classes);
+ return 1;
+ }
+ return 0;
+}
+
+static int
+external_passwd_quality (krb5_context context,
+ krb5_principal principal,
+ krb5_data *pwd,
+ const char *opaque,
+ char *message,
+ size_t length)
+{
+ krb5_error_code ret;
+ const char *program;
+ char *p;
+ pid_t child;
+ int status;
+ char reply[1024];
+ FILE *in = NULL, *out = NULL, *error = NULL;
+
+ if (memchr(pwd->data, '\n', pwd->length) != NULL) {
+ snprintf(message, length, "password contains newline, "
+ "not valid for external test");
+ return 1;
+ }
+
+ program = krb5_config_get_string(context, NULL,
+ "password_quality",
+ "external_program",
+ NULL);
+ if (program == NULL) {
+ snprintf(message, length, "external password quality "
+ "program not configured");
+ return 1;
+ }
+
+ ret = krb5_unparse_name(context, principal, &p);
+ if (ret) {
+ strlcpy(message, "out of memory", length);
+ return 1;
+ }
+
+ child = pipe_execv(&in, &out, &error, program, program, p, NULL);
+ if (child < 0) {
+ snprintf(message, length, "external password quality "
+ "program failed to execute for principal %s", p);
+ free(p);
+ return 1;
+ }
+
+ fprintf(in, "principal: %s\n"
+ "new-password: %.*s\n"
+ "end\n",
+ p, (int)pwd->length, (char *)pwd->data);
+
+ fclose(in);
+
+ if (fgets(reply, sizeof(reply), out) == NULL) {
+
+ if (fgets(reply, sizeof(reply), error) == NULL) {
+ snprintf(message, length, "external password quality "
+ "program failed without error");
+
+ } else {
+ reply[strcspn(reply, "\n")] = '\0';
+ snprintf(message, length, "External password quality "
+ "program failed: %s", reply);
+ }
+
+ fclose(out);
+ fclose(error);
+ wait_for_process(child);
+ free(p);
+ return 1;
+ }
+ reply[strcspn(reply, "\n")] = '\0';
+
+ fclose(out);
+ fclose(error);
+
+ status = wait_for_process(child);
+
+ if (SE_IS_ERROR(status) || SE_PROCSTATUS(status) != 0) {
+ snprintf(message, length, "external program failed: %s", reply);
+ free(p);
+ return 1;
+ }
+
+ if (strcmp(reply, "APPROVED") != 0) {
+ snprintf(message, length, "%s", reply);
+ free(p);
+ return 1;
+ }
+
+ free(p);
+
+ return 0;
+}
+
+
+static kadm5_passwd_quality_check_func_v0 passwd_quality_check =
+ min_length_passwd_quality_v0;
+
+struct kadm5_pw_policy_check_func builtin_funcs[] = {
+ { "minimum-length", min_length_passwd_quality },
+ { "character-class", char_class_passwd_quality },
+ { "external-check", external_passwd_quality },
+ { NULL, NULL }
+};
+struct kadm5_pw_policy_verifier builtin_verifier = {
+ "builtin",
+ KADM5_PASSWD_VERSION_V1,
+ "Heimdal builtin",
+ builtin_funcs
+};
+
+static struct kadm5_pw_policy_verifier **verifiers;
+static int num_verifiers;
+
+/*
+ * setup the password quality hook
+ */
+
+void
+kadm5_setup_passwd_quality_check(krb5_context context,
+ const char *check_library,
+ const char *check_function)
+{
+#ifdef HAVE_DLOPEN
+ void *handle;
+ void *sym;
+ int *version;
+ const char *tmp;
+
+ if(check_library == NULL) {
+ tmp = krb5_config_get_string(context, NULL,
+ "password_quality",
+ "check_library",
+ NULL);
+ if(tmp != NULL)
+ check_library = tmp;
+ }
+ if(check_function == NULL) {
+ tmp = krb5_config_get_string(context, NULL,
+ "password_quality",
+ "check_function",
+ NULL);
+ if(tmp != NULL)
+ check_function = tmp;
+ }
+ if(check_library != NULL && check_function == NULL)
+ check_function = "passwd_check";
+
+ if(check_library == NULL)
+ return;
+ handle = dlopen(check_library, RTLD_NOW | RTLD_LOCAL | RTLD_GROUP);
+ if(handle == NULL) {
+ krb5_warnx(context, "failed to open `%s'", check_library);
+ return;
+ }
+ version = (int *) dlsym(handle, "version");
+ if(version == NULL) {
+ krb5_warnx(context,
+ "didn't find `version' symbol in `%s'", check_library);
+ dlclose(handle);
+ return;
+ }
+ if(*version != KADM5_PASSWD_VERSION_V0) {
+ krb5_warnx(context,
+ "version of loaded library is %d (expected %d)",
+ *version, KADM5_PASSWD_VERSION_V0);
+ dlclose(handle);
+ return;
+ }
+ sym = dlsym(handle, check_function);
+ if(sym == NULL) {
+ krb5_warnx(context,
+ "didn't find `%s' symbol in `%s'",
+ check_function, check_library);
+ dlclose(handle);
+ return;
+ }
+ passwd_quality_check = (kadm5_passwd_quality_check_func_v0) sym;
+#endif /* HAVE_DLOPEN */
+}
+
+#ifdef HAVE_DLOPEN
+
+static krb5_error_code
+add_verifier(krb5_context context, const char *check_library)
+{
+ struct kadm5_pw_policy_verifier *v, **tmp;
+ void *handle;
+ int i;
+
+ handle = dlopen(check_library, RTLD_NOW | RTLD_LOCAL | RTLD_GROUP);
+ if(handle == NULL) {
+ krb5_warnx(context, "failed to open `%s'", check_library);
+ return ENOENT;
+ }
+ v = (struct kadm5_pw_policy_verifier *) dlsym(handle, "kadm5_password_verifier");
+ if(v == NULL) {
+ krb5_warnx(context,
+ "didn't find `kadm5_password_verifier' symbol "
+ "in `%s'", check_library);
+ dlclose(handle);
+ return ENOENT;
+ }
+ if(v->version != KADM5_PASSWD_VERSION_V1) {
+ krb5_warnx(context,
+ "version of loaded library is %d (expected %d)",
+ v->version, KADM5_PASSWD_VERSION_V1);
+ dlclose(handle);
+ return EINVAL;
+ }
+ for (i = 0; i < num_verifiers; i++) {
+ if (strcmp(v->name, verifiers[i]->name) == 0)
+ break;
+ }
+ if (i < num_verifiers) {
+ krb5_warnx(context, "password verifier library `%s' is already loaded",
+ v->name);
+ dlclose(handle);
+ return 0;
+ }
+
+ tmp = realloc(verifiers, (num_verifiers + 1) * sizeof(*verifiers));
+ if (tmp == NULL) {
+ krb5_warnx(context, "out of memory");
+ dlclose(handle);
+ return 0;
+ }
+ verifiers = tmp;
+ verifiers[num_verifiers] = v;
+ num_verifiers++;
+
+ return 0;
+}
+
+#endif
+
+krb5_error_code
+kadm5_add_passwd_quality_verifier(krb5_context context,
+ const char *check_library)
+{
+#ifdef HAVE_DLOPEN
+
+ if(check_library == NULL) {
+ krb5_error_code ret = 0;
+ char **strs;
+ char **tmp;
+
+ strs = krb5_config_get_strings(context, NULL,
+ "password_quality",
+ "policy_libraries",
+ NULL);
+ if (strs == NULL)
+ return 0;
+
+ for (tmp = strs; *tmp; tmp++) {
+ ret = add_verifier(context, *tmp);
+ if (ret)
+ break;
+ }
+ krb5_config_free_strings(strs);
+ return ret;
+ } else {
+ return add_verifier(context, check_library);
+ }
+#else
+ return 0;
+#endif /* HAVE_DLOPEN */
+}
+
+/*
+ *
+ */
+
+static const struct kadm5_pw_policy_check_func *
+find_func(krb5_context context, const char *name)
+{
+ const struct kadm5_pw_policy_check_func *f;
+ char *module = NULL;
+ const char *p, *func;
+ int i;
+
+ p = strchr(name, ':');
+ if (p) {
+ size_t len = p - name + 1;
+ func = p + 1;
+ module = malloc(len);
+ if (module == NULL)
+ return NULL;
+ strlcpy(module, name, len);
+ } else
+ func = name;
+
+ /* Find module in loaded modules first */
+ for (i = 0; i < num_verifiers; i++) {
+ if (module && strcmp(module, verifiers[i]->name) != 0)
+ continue;
+ for (f = verifiers[i]->funcs; f->name ; f++)
+ if (strcmp(func, f->name) == 0) {
+ if (module)
+ free(module);
+ return f;
+ }
+ }
+ /* Lets try try the builtin modules */
+ if (module == NULL || strcmp(module, "builtin") == 0) {
+ for (f = builtin_verifier.funcs; f->name ; f++)
+ if (strcmp(func, f->name) == 0) {
+ if (module)
+ free(module);
+ return f;
+ }
+ }
+ if (module)
+ free(module);
+ return NULL;
+}
+
+const char *
+kadm5_check_password_quality (krb5_context context,
+ krb5_principal principal,
+ krb5_data *pwd_data)
+{
+ const struct kadm5_pw_policy_check_func *proc;
+ static char error_msg[1024];
+ const char *msg;
+ char **v, **vp;
+ int ret;
+
+ /*
+ * Check if we should use the old version of policy function.
+ */
+
+ v = krb5_config_get_strings(context, NULL,
+ "password_quality",
+ "policies",
+ NULL);
+ if (v == NULL) {
+ msg = (*passwd_quality_check) (context, principal, pwd_data);
+ if (msg)
+ krb5_set_error_message(context, 0, "password policy failed: %s", msg);
+ return msg;
+ }
+
+ error_msg[0] = '\0';
+
+ msg = NULL;
+ for(vp = v; *vp; vp++) {
+ proc = find_func(context, *vp);
+ if (proc == NULL) {
+ msg = "failed to find password verifier function";
+ krb5_set_error_message(context, 0, "Failed to find password policy "
+ "function: %s", *vp);
+ break;
+ }
+ ret = (proc->func)(context, principal, pwd_data, NULL,
+ error_msg, sizeof(error_msg));
+ if (ret) {
+ krb5_set_error_message(context, 0, "Password policy "
+ "%s failed with %s",
+ proc->name, error_msg);
+ msg = error_msg;
+ break;
+ }
+ }
+ krb5_config_free_strings(v);
+
+ /* If the default quality check isn't used, lets check that the
+ * old quality function the user have set too */
+ if (msg == NULL && passwd_quality_check != min_length_passwd_quality_v0) {
+ msg = (*passwd_quality_check) (context, principal, pwd_data);
+ if (msg)
+ krb5_set_error_message(context, 0, "(old) password policy "
+ "failed with %s", msg);
+
+ }
+ return msg;
+}
diff --git a/third_party/heimdal/lib/kadm5/private.h b/third_party/heimdal/lib/kadm5/private.h
new file mode 100644
index 0000000..88c2f28
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/private.h
@@ -0,0 +1,208 @@
+/*
+ * Copyright (c) 1997-2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __kadm5_privatex_h__
+#define __kadm5_privatex_h__
+
+#include "kadm5-hook.h"
+
+#ifdef HAVE_SYS_UN_H
+#include <sys/un.h>
+#endif
+
+struct kadm_func {
+ kadm5_ret_t (*chpass_principal) (void *, krb5_principal, int,
+ int, krb5_key_salt_tuple*, const char*);
+ kadm5_ret_t (*create_principal) (void*, kadm5_principal_ent_t, uint32_t,
+ int, krb5_key_salt_tuple *,
+ const char*);
+ kadm5_ret_t (*delete_principal) (void*, krb5_principal);
+ kadm5_ret_t (*destroy) (void*);
+ kadm5_ret_t (*flush) (void*);
+ kadm5_ret_t (*get_principal) (void*, krb5_principal,
+ kadm5_principal_ent_t, uint32_t);
+ kadm5_ret_t (*get_principals) (void*, const char*, char***, int*);
+ kadm5_ret_t (*get_privs) (void*, uint32_t*);
+ kadm5_ret_t (*modify_principal) (void*, kadm5_principal_ent_t, uint32_t);
+ kadm5_ret_t (*randkey_principal) (void*, krb5_principal, krb5_boolean, int,
+ krb5_key_salt_tuple*, krb5_keyblock**,
+ int*);
+ kadm5_ret_t (*rename_principal) (void*, krb5_principal, krb5_principal);
+ kadm5_ret_t (*chpass_principal_with_key) (void *, krb5_principal, int,
+ int, krb5_key_data *);
+ kadm5_ret_t (*lock) (void *);
+ kadm5_ret_t (*unlock) (void *);
+ kadm5_ret_t (*setkey_principal_3) (void *, krb5_principal, krb5_boolean,
+ int, krb5_key_salt_tuple *,
+ krb5_keyblock *, int);
+ kadm5_ret_t (*prune_principal) (void *, krb5_principal, int);
+};
+
+typedef struct kadm5_hook_context {
+ void *dsohandle;
+ const kadm5_hook_ftable *hook;
+ void *data;
+} kadm5_hook_context;
+
+/* XXX should be integrated */
+typedef struct kadm5_common_context {
+ krb5_context context;
+ krb5_boolean my_context;
+ struct kadm_func funcs;
+ void *data;
+} kadm5_common_context;
+
+typedef struct kadm5_log_peer {
+ int fd;
+ char *name;
+ krb5_auth_context ac;
+ struct kadm5_log_peer *next;
+} kadm5_log_peer;
+
+typedef struct kadm5_log_context {
+ char *log_file;
+ int log_fd;
+ int read_only;
+ int lock_mode;
+ uint32_t version;
+ time_t last_time;
+#ifndef NO_UNIX_SOCKETS
+ struct sockaddr_un socket_name;
+#else
+ struct addrinfo *socket_info;
+#endif
+ krb5_socket_t socket_fd;
+} kadm5_log_context;
+
+typedef struct kadm5_server_context {
+ krb5_context context;
+ krb5_boolean my_context;
+ struct kadm_func funcs;
+ /* */
+ kadm5_config_params config;
+ HDB *db;
+ int keep_open;
+ krb5_principal caller;
+ unsigned acl_flags;
+ kadm5_log_context log_context;
+ size_t num_hooks;
+ kadm5_hook_context **hooks;
+} kadm5_server_context;
+
+typedef struct kadm5_client_context {
+ krb5_context context;
+ krb5_boolean my_context;
+ struct kadm_func funcs;
+ /* */
+ krb5_auth_context ac;
+ char *realm;
+ char *admin_server;
+ int kadmind_port;
+ krb5_socket_t sock;
+ char *client_name;
+ char *service_name;
+ krb5_prompter_fct prompter;
+ const char *keytab;
+ krb5_ccache ccache;
+ kadm5_config_params *realm_params;
+ char *readonly_admin_server;
+ int readonly_kadmind_port;
+ unsigned int want_write:1;
+ unsigned int connected_to_writable:1;
+} kadm5_client_context;
+
+typedef struct kadm5_ad_context {
+ krb5_context context;
+ krb5_boolean my_context;
+ struct kadm_func funcs;
+ /* */
+ kadm5_config_params config;
+ krb5_principal caller;
+ krb5_ccache ccache;
+ char *client_name;
+ char *realm;
+ void *ldap_conn;
+ char *base_dn;
+} kadm5_ad_context;
+
+/*
+ * This enum is used in the iprop log file and on the wire in the iprop
+ * protocol. DO NOT CHANGE, except to add new op types at the end, and
+ * look for places in lib/kadm5/log.c to update.
+ */
+enum kadm_ops {
+ kadm_get,
+ kadm_delete,
+ kadm_create,
+ kadm_rename,
+ kadm_chpass,
+ kadm_modify,
+ kadm_randkey,
+ kadm_get_privs,
+ kadm_get_princs,
+ kadm_chpass_with_key,
+ kadm_nop,
+ kadm_prune,
+ kadm_first = kadm_get,
+ kadm_last = kadm_prune
+};
+
+/* FIXME nop types are currently not implemented */
+enum kadm_nop_type {
+ kadm_nop_plain, /* plain nop, not relevance except as uberblock */
+ kadm_nop_trunc, /* indicates that the master truncated the log */
+ kadm_nop_close /* indicates that the master closed this log */
+};
+
+enum kadm_iter_opts {
+ kadm_forward = 1,
+ kadm_backward = 2,
+ kadm_confirmed = 4,
+ kadm_unconfirmed = 8
+};
+
+enum kadm_recover_mode {
+ kadm_recover_commit,
+ kadm_recover_replay
+};
+
+#define KADMIN_APPL_VERSION "KADM0.1"
+#define KADMIN_OLD_APPL_VERSION "KADM0.0"
+
+extern struct heim_plugin_data kadm5_hook_plugin_data;
+
+#include "kadm5-private.h"
+
+#endif /* __kadm5_privatex_h__ */
diff --git a/third_party/heimdal/lib/kadm5/privs_c.c b/third_party/heimdal/lib/kadm5/privs_c.c
new file mode 100644
index 0000000..b6879cf
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/privs_c.c
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_c_get_privs(void *server_handle, uint32_t *privs)
+{
+ kadm5_client_context *context = server_handle;
+ kadm5_ret_t ret;
+ krb5_storage *sp;
+ unsigned char buf[1024];
+ int32_t tmp;
+ krb5_data reply;
+
+ *privs = 0;
+
+ ret = _kadm5_connect(server_handle, 0 /* want_write */);
+ if (ret)
+ return ret;
+
+ krb5_data_zero(&reply);
+
+ sp = krb5_storage_from_mem(buf, sizeof(buf));
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_store_int32(sp, kadm_get_privs);
+ if (ret)
+ goto out;
+ ret = _kadm5_client_send(context, sp);
+ if (ret)
+ goto out_keep_error;
+ ret = _kadm5_client_recv(context, &reply);
+ if (ret)
+ goto out_keep_error;
+ krb5_storage_free(sp);
+ sp = krb5_storage_from_data(&reply);
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret == 0)
+ ret = tmp;
+ if (ret == 0)
+ krb5_ret_uint32(sp, privs);
+
+ out:
+ krb5_clear_error_message(context->context);
+
+ out_keep_error:
+ krb5_storage_free(sp);
+ krb5_data_free (&reply);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kadm5/privs_s.c b/third_party/heimdal/lib/kadm5/privs_s.c
new file mode 100644
index 0000000..bfe298d
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/privs_s.c
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_s_get_privs(void *server_handle, uint32_t *privs)
+{
+ kadm5_server_context *context = server_handle;
+ *privs = context->acl_flags;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/prune_c.c b/third_party/heimdal/lib/kadm5/prune_c.c
new file mode 100644
index 0000000..70a1dcb
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/prune_c.c
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2018 Cesnet z.s.p.o.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_c_prune_principal(void *server_handle, krb5_principal princ, int kvno)
+{
+ kadm5_client_context *context = server_handle;
+ kadm5_ret_t ret, ret2;
+ krb5_storage *sp = NULL;
+ unsigned char buf[1024];
+ krb5_data reply;
+
+ krb5_data_zero(&reply);
+ ret = _kadm5_connect(server_handle, 1 /* want_write */);
+ if (ret == 0 && (sp = krb5_storage_from_mem(buf, sizeof(buf))) == NULL)
+ ret = krb5_enomem(context->context);
+ if (ret == 0)
+ ret = krb5_store_int32(sp, kadm_prune);
+ if (ret == 0)
+ ret = krb5_store_principal(sp, princ);
+ if (ret == 0)
+ ret = krb5_store_int32(sp, kvno);
+ if (ret == 0)
+ ret = _kadm5_client_send(context, sp);
+ if (ret == 0)
+ ret = _kadm5_client_recv(context, &reply);
+ krb5_storage_free(sp);
+ sp = NULL;
+ if (ret == 0 && (sp = krb5_storage_from_data(&reply)) == NULL)
+ ret = krb5_enomem(context->context);
+ if (ret == 0)
+ ret = krb5_ret_int32(sp, &ret2);
+ if (ret == 0) {
+ krb5_clear_error_message(context->context);
+ ret = ret2;
+ }
+ krb5_data_free(&reply);
+ krb5_storage_free(sp);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kadm5/prune_s.c b/third_party/heimdal/lib/kadm5/prune_s.c
new file mode 100644
index 0000000..96133f2
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/prune_s.c
@@ -0,0 +1,149 @@
+/*
+ * Copyright (c) 2018 Cesnet z.s.p.o.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+struct prune_principal_hook_ctx {
+ kadm5_server_context *context;
+ enum kadm5_hook_stage stage;
+ krb5_error_code code;
+ krb5_const_principal princ;
+ int kvno;
+};
+
+static krb5_error_code KRB5_LIB_CALL
+prune_principal_hook_cb(krb5_context context,
+ const void *hook,
+ void *hookctx,
+ void *userctx)
+{
+ krb5_error_code ret;
+ const struct kadm5_hook_ftable *ftable = hook;
+ struct prune_principal_hook_ctx *ctx = userctx;
+
+ ret = ftable->prune(context, hookctx,
+ ctx->stage, ctx->code, ctx->princ, ctx->kvno);
+ if (ret != 0 && ret != KRB5_PLUGIN_NO_HANDLE)
+ _kadm5_s_set_hook_error_message(ctx->context, ret, "prune",
+ hook, ctx->stage);
+
+ /* only pre-commit plugins can abort */
+ if (ret == 0 || ctx->stage == KADM5_HOOK_STAGE_POSTCOMMIT)
+ ret = KRB5_PLUGIN_NO_HANDLE;
+
+ return ret;
+}
+
+static kadm5_ret_t
+prune_principal_hook(kadm5_server_context *context,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ,
+ int kvno)
+{
+ krb5_error_code ret;
+ struct prune_principal_hook_ctx ctx;
+
+ ctx.context = context;
+ ctx.stage = stage;
+ ctx.code = code;
+ ctx.princ = princ;
+ ctx.kvno = kvno;
+
+ ret = _krb5_plugin_run_f(context->context, &kadm5_hook_plugin_data,
+ 0, &ctx, prune_principal_hook_cb);
+ if (ret == KRB5_PLUGIN_NO_HANDLE)
+ ret = 0;
+
+ return ret;
+}
+
+kadm5_ret_t
+kadm5_s_prune_principal(void *server_handle,
+ krb5_principal princ,
+ int kvno)
+{
+ kadm5_server_context *context = server_handle;
+ hdb_entry ent;
+ kadm5_ret_t ret;
+
+ memset(&ent, 0, sizeof(ent));
+ if (!context->keep_open) {
+ ret = context->db->hdb_open(context->context, context->db, O_RDWR, 0);
+ if(ret)
+ return ret;
+ }
+
+ ret = kadm5_log_init(context);
+ if (ret)
+ goto out;
+
+ /* NOTE: We do not use hdb_fetch_kvno() here */
+ ret = context->db->hdb_fetch_kvno(context->context, context->db, princ,
+ HDB_F_DECRYPT|HDB_F_GET_ANY|HDB_F_ADMIN_DATA,
+ 0, &ent);
+ if (ret)
+ goto out2;
+
+ ret = prune_principal_hook(context, KADM5_HOOK_STAGE_PRECOMMIT,
+ 0, princ, kvno);
+ if (ret)
+ goto out3;
+
+ ret = hdb_prune_keys_kvno(context->context, &ent, kvno);
+ if (ret)
+ goto out3;
+
+ ret = hdb_seal_keys(context->context, context->db, &ent);
+ if (ret)
+ goto out3;
+
+ ret = kadm5_log_modify(context, &ent, KADM5_KEY_DATA);
+
+ (void) prune_principal_hook(context, KADM5_HOOK_STAGE_POSTCOMMIT,
+ ret, princ, kvno);
+
+out3:
+ hdb_free_entry(context->context, context->db, &ent);
+out2:
+ (void) kadm5_log_end(context);
+out:
+ if (!context->keep_open) {
+ kadm5_ret_t ret2;
+ ret2 = context->db->hdb_close(context->context, context->db);
+ if (ret == 0 && ret2 != 0)
+ ret = ret2;
+ }
+ return _kadm5_error_code(ret);
+}
diff --git a/third_party/heimdal/lib/kadm5/randkey_c.c b/third_party/heimdal/lib/kadm5/randkey_c.c
new file mode 100644
index 0000000..cb0ec86
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/randkey_c.c
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_c_randkey_principal(void *server_handle,
+ krb5_principal princ,
+ krb5_boolean keepold,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ krb5_keyblock **new_keys,
+ int *n_keys)
+{
+ kadm5_client_context *context = server_handle;
+ kadm5_ret_t ret;
+ krb5_storage *sp;
+ unsigned char buf[1536];
+ int32_t tmp;
+ size_t i;
+ krb5_data reply;
+ krb5_keyblock *k;
+
+ ret = _kadm5_connect(server_handle, 1 /* want_write */);
+ if (ret)
+ return ret;
+
+ krb5_data_zero(&reply);
+
+ sp = krb5_storage_from_mem(buf, sizeof(buf));
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+
+ /*
+ * NOTE WELL: This message is extensible. It currently consists of:
+ *
+ * - opcode (kadm_randkey)
+ * - principal name (princ)
+ *
+ * followed by optional items, each of which must be present if
+ * there are any items following them that are also present:
+ *
+ * - keepold boolean (whether to delete old kvnos)
+ * - number of key/salt type tuples
+ * - array of {enctype, salttype}
+ *
+ * Eventually we may add:
+ *
+ * - opaque string2key parameters (salt, rounds, ...)
+ */
+ ret = krb5_store_int32(sp, kadm_randkey);
+ if (ret == 0)
+ ret = krb5_store_principal(sp, princ);
+
+ if (ret == 0 && (keepold == TRUE || n_ks_tuple > 0))
+ ret = krb5_store_uint32(sp, keepold);
+ if (ret == 0 && n_ks_tuple > 0)
+ ret = krb5_store_uint32(sp, n_ks_tuple);
+ for (i = 0; ret == 0 && i < n_ks_tuple; i++) {
+ ret = krb5_store_int32(sp, ks_tuple[i].ks_enctype);
+ if (ret == 0)
+ ret = krb5_store_int32(sp, ks_tuple[i].ks_salttype);
+ }
+ /* Future extensions go here */
+ if (ret)
+ goto out;
+
+ ret = _kadm5_client_send(context, sp);
+ if (ret)
+ goto out_keep_error;
+ ret = _kadm5_client_recv(context, &reply);
+ if (ret)
+ goto out_keep_error;
+ krb5_storage_free(sp);
+ sp = krb5_storage_from_data(&reply);
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret == 0)
+ ret = tmp;
+ if (ret)
+ goto out;
+
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret)
+ goto out;
+ if (tmp < 0) {
+ ret = EOVERFLOW;
+ goto out;
+ }
+ k = calloc(tmp, sizeof(*k));
+ if (k == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ for (i = 0; ret == 0 && i < tmp; i++) {
+ ret = krb5_ret_keyblock(sp, &k[i]);
+ if (ret)
+ break;
+ }
+ if (ret == 0 && n_keys && new_keys) {
+ *n_keys = tmp;
+ *new_keys = k;
+ } else {
+ krb5_free_keyblock_contents(context->context, &k[i]);
+ for (; i > 0; i--)
+ krb5_free_keyblock_contents(context->context, &k[i - 1]);
+ free(k);
+ }
+
+ out:
+ krb5_clear_error_message(context->context);
+
+ out_keep_error:
+ krb5_storage_free(sp);
+ krb5_data_free(&reply);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kadm5/randkey_s.c b/third_party/heimdal/lib/kadm5/randkey_s.c
new file mode 100644
index 0000000..cb36967
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/randkey_s.c
@@ -0,0 +1,204 @@
+/*
+ * Copyright (c) 1997-2001, 2003-2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+struct randkey_principal_hook_ctx {
+ kadm5_server_context *context;
+ enum kadm5_hook_stage stage;
+ krb5_error_code code;
+ krb5_const_principal princ;
+};
+
+static krb5_error_code KRB5_LIB_CALL
+randkey_principal_hook_cb(krb5_context context,
+ const void *hook,
+ void *hookctx,
+ void *userctx)
+{
+ krb5_error_code ret;
+ const struct kadm5_hook_ftable *ftable = hook;
+ struct randkey_principal_hook_ctx *ctx = userctx;
+
+ ret = ftable->randkey(context, hookctx,
+ ctx->stage, ctx->code, ctx->princ);
+ if (ret != 0 && ret != KRB5_PLUGIN_NO_HANDLE)
+ _kadm5_s_set_hook_error_message(ctx->context, ret, "randkey",
+ hook, ctx->stage);
+
+ /* only pre-commit plugins can abort */
+ if (ret == 0 || ctx->stage == KADM5_HOOK_STAGE_POSTCOMMIT)
+ ret = KRB5_PLUGIN_NO_HANDLE;
+
+ return ret;
+}
+
+static kadm5_ret_t
+randkey_principal_hook(kadm5_server_context *context,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ)
+{
+ krb5_error_code ret;
+ struct randkey_principal_hook_ctx ctx;
+
+ ctx.context = context;
+ ctx.stage = stage;
+ ctx.code = code;
+ ctx.princ = princ;
+
+ ret = _krb5_plugin_run_f(context->context, &kadm5_hook_plugin_data,
+ 0, &ctx, randkey_principal_hook_cb);
+ if (ret == KRB5_PLUGIN_NO_HANDLE)
+ ret = 0;
+
+ return ret;
+}
+
+/*
+ * Set the keys of `princ' to random values, returning the random keys
+ * in `new_keys', `n_keys'.
+ */
+
+kadm5_ret_t
+kadm5_s_randkey_principal(void *server_handle,
+ krb5_principal princ,
+ krb5_boolean keepold,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ krb5_keyblock **new_keys,
+ int *n_keys)
+{
+ kadm5_server_context *context = server_handle;
+ hdb_entry ent;
+ kadm5_ret_t ret;
+ size_t i;
+
+ memset(&ent, 0, sizeof(ent));
+ if (!context->keep_open) {
+ ret = context->db->hdb_open(context->context, context->db, O_RDWR, 0);
+ if(ret)
+ return ret;
+ }
+
+ ret = kadm5_log_init(context);
+ if (ret)
+ goto out;
+
+ /* NOTE: We do not use hdb_fetch_kvno() here (maybe we should) */
+ ret = context->db->hdb_fetch_kvno(context->context, context->db, princ,
+ HDB_F_DECRYPT|HDB_F_GET_ANY|HDB_F_ADMIN_DATA,
+ 0, &ent);
+ if(ret)
+ goto out2;
+
+ ret = randkey_principal_hook(context, KADM5_HOOK_STAGE_PRECOMMIT, 0, princ);
+ if (ret)
+ goto out3;
+
+ if (keepold) {
+ ret = hdb_add_current_keys_to_history(context->context, &ent);
+ if (ret == 0 && keepold == 1)
+ ret = hdb_prune_keys_kvno(context->context, &ent, 0);
+ if (ret)
+ goto out3;
+ } else {
+ /* Remove all key history */
+ ret = hdb_clear_extension(context->context, &ent,
+ choice_HDB_extension_data_hist_keys);
+ if (ret)
+ goto out3;
+ }
+
+ ret = _kadm5_set_keys_randomly(context, &ent, n_ks_tuple, ks_tuple,
+ new_keys, n_keys);
+ if (ret)
+ goto out3;
+ ent.kvno++;
+
+ ent.flags.require_pwchange = 0;
+
+ ret = _kadm5_set_modifier(context, &ent);
+ if(ret)
+ goto out4;
+ ret = _kadm5_bump_pw_expire(context, &ent);
+ if (ret)
+ goto out4;
+
+ if (keepold) {
+ ret = hdb_seal_keys(context->context, context->db, &ent);
+ if (ret)
+ goto out4;
+ } else {
+ HDB_extension ext;
+
+ memset(&ext, 0, sizeof (ext));
+ ext.mandatory = FALSE;
+ ext.data.element = choice_HDB_extension_data_hist_keys;
+ ext.data.u.hist_keys.len = 0;
+ ext.data.u.hist_keys.val = NULL;
+ hdb_replace_extension(context->context, &ent, &ext);
+ }
+
+ /* This logs the change for iprop and writes to the HDB */
+ ret = kadm5_log_modify(context, &ent,
+ KADM5_ATTRIBUTES | KADM5_PRINCIPAL |
+ KADM5_MOD_NAME | KADM5_MOD_TIME |
+ KADM5_KEY_DATA | KADM5_KVNO |
+ KADM5_PW_EXPIRATION | KADM5_TL_DATA);
+
+ (void) randkey_principal_hook(context, KADM5_HOOK_STAGE_POSTCOMMIT, ret, princ);
+
+ out4:
+ if (ret) {
+ for (i = 0; i < *n_keys; ++i)
+ krb5_free_keyblock_contents(context->context, &(*new_keys)[i]);
+ free (*new_keys);
+ *new_keys = NULL;
+ *n_keys = 0;
+ }
+ out3:
+ hdb_free_entry(context->context, context->db, &ent);
+ out2:
+ (void) kadm5_log_end(context);
+ out:
+ if (!context->keep_open) {
+ kadm5_ret_t ret2;
+ ret2 = context->db->hdb_close(context->context, context->db);
+ if (ret == 0 && ret2 != 0)
+ ret = ret2;
+ }
+ return _kadm5_error_code(ret);
+}
diff --git a/third_party/heimdal/lib/kadm5/rename_c.c b/third_party/heimdal/lib/kadm5/rename_c.c
new file mode 100644
index 0000000..fb2cdc5
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/rename_c.c
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_c_rename_principal(void *server_handle,
+ krb5_principal source,
+ krb5_principal target)
+{
+ kadm5_client_context *context = server_handle;
+ kadm5_ret_t ret;
+ krb5_storage *sp;
+ unsigned char buf[1024];
+ int32_t tmp;
+ krb5_data reply;
+
+ ret = _kadm5_connect(server_handle, 1 /* want_write */);
+ if (ret)
+ return ret;
+
+ krb5_data_zero(&reply);
+
+ sp = krb5_storage_from_mem(buf, sizeof(buf));
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+
+ ret = krb5_store_int32(sp, kadm_rename);
+ if (ret)
+ goto out;
+ ret = krb5_store_principal(sp, source);
+ if (ret)
+ goto out;
+ ret = krb5_store_principal(sp, target);
+ if (ret)
+ goto out;
+ ret = _kadm5_client_send(context, sp);
+ if (ret)
+ goto out_keep_error;
+ ret = _kadm5_client_recv(context, &reply);
+ if (ret)
+ goto out_keep_error;
+ krb5_storage_free(sp);
+ sp = krb5_storage_from_data(&reply);
+ if (sp == NULL) {
+ ret = krb5_enomem(context->context);
+ goto out_keep_error;
+ }
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret == 0)
+ ret = tmp;
+
+ out:
+ krb5_clear_error_message(context->context);
+
+ out_keep_error:
+ krb5_storage_free(sp);
+ krb5_data_free(&reply);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kadm5/rename_s.c b/third_party/heimdal/lib/kadm5/rename_s.c
new file mode 100644
index 0000000..9143318
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/rename_s.c
@@ -0,0 +1,188 @@
+/*
+ * Copyright (c) 1997 - 2001, 2003, 2005 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+struct rename_principal_hook_ctx {
+ kadm5_server_context *context;
+ enum kadm5_hook_stage stage;
+ krb5_error_code code;
+ krb5_const_principal source, target;
+};
+
+static krb5_error_code KRB5_LIB_CALL
+rename_principal_hook_cb(krb5_context context,
+ const void *hook,
+ void *hookctx,
+ void *userctx)
+{
+ krb5_error_code ret;
+ const struct kadm5_hook_ftable *ftable = hook;
+ struct rename_principal_hook_ctx *ctx = userctx;
+
+ ret = ftable->rename(context, hookctx,
+ ctx->stage, ctx->code,
+ ctx->source, ctx->target);
+ if (ret != 0 && ret != KRB5_PLUGIN_NO_HANDLE)
+ _kadm5_s_set_hook_error_message(ctx->context, ret, "rename",
+ hook, ctx->stage);
+
+ /* only pre-commit plugins can abort */
+ if (ret == 0 || ctx->stage == KADM5_HOOK_STAGE_POSTCOMMIT)
+ ret = KRB5_PLUGIN_NO_HANDLE;
+
+ return ret;
+}
+
+static kadm5_ret_t
+rename_principal_hook(kadm5_server_context *context,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal source,
+ krb5_const_principal target)
+{
+ krb5_error_code ret;
+ struct rename_principal_hook_ctx ctx;
+
+ ctx.context = context;
+ ctx.stage = stage;
+ ctx.code = code;
+ ctx.source = source;
+ ctx.target = target;
+
+ ret = _krb5_plugin_run_f(context->context, &kadm5_hook_plugin_data,
+ 0, &ctx, rename_principal_hook_cb);
+ if (ret == KRB5_PLUGIN_NO_HANDLE)
+ ret = 0;
+
+ return ret;
+}
+
+kadm5_ret_t
+kadm5_s_rename_principal(void *server_handle,
+ krb5_principal source,
+ krb5_principal target)
+{
+ kadm5_server_context *context = server_handle;
+ kadm5_ret_t ret;
+ hdb_entry ent;
+ krb5_principal oldname;
+ size_t i;
+
+ memset(&ent, 0, sizeof(ent));
+ if (krb5_principal_compare(context->context, source, target))
+ return KADM5_DUP; /* XXX is this right? */
+ if (!context->keep_open) {
+ ret = context->db->hdb_open(context->context, context->db, O_RDWR, 0);
+ if(ret)
+ return ret;
+ }
+
+ ret = kadm5_log_init(context);
+ if (ret)
+ goto out;
+
+ /* NOTE: We do not use hdb_fetch_kvno() here */
+ ret = context->db->hdb_fetch_kvno(context->context, context->db,
+ source,
+ HDB_F_DECRYPT|HDB_F_GET_ANY|HDB_F_ADMIN_DATA,
+ 0, &ent);
+ if (ret)
+ goto out2;
+ oldname = ent.principal;
+
+ ret = rename_principal_hook(context, KADM5_HOOK_STAGE_PRECOMMIT,
+ 0, source, target);
+ if (ret)
+ goto out3;
+
+ ret = _kadm5_set_modifier(context, &ent);
+ if (ret)
+ goto out3;
+ {
+ /* fix salt */
+ Salt salt;
+ krb5_salt salt2;
+ memset(&salt, 0, sizeof(salt));
+ ret = krb5_get_pw_salt(context->context, source, &salt2);
+ if (ret)
+ goto out3;
+ salt.type = hdb_pw_salt;
+ salt.salt = salt2.saltvalue;
+ for(i = 0; i < ent.keys.len; i++){
+ if(ent.keys.val[i].salt == NULL){
+ ent.keys.val[i].salt =
+ malloc(sizeof(*ent.keys.val[i].salt));
+ if (ent.keys.val[i].salt == NULL)
+ ret = krb5_enomem(context->context);
+ else
+ ret = copy_Salt(&salt, ent.keys.val[i].salt);
+ if (ret)
+ break;
+ }
+ }
+ krb5_free_salt(context->context, salt2);
+ }
+ if (ret)
+ goto out3;
+
+ /* Borrow target */
+ ent.principal = target;
+ ret = hdb_seal_keys(context->context, context->db, &ent);
+ if (ret)
+ goto out3;
+
+ /* This logs the change for iprop and writes to the HDB */
+ ret = kadm5_log_rename(context, source, &ent);
+
+ (void) rename_principal_hook(context, KADM5_HOOK_STAGE_POSTCOMMIT,
+ ret, source, target);
+
+ out3:
+ ent.principal = oldname; /* Unborrow target */
+ hdb_free_entry(context->context, context->db, &ent);
+
+ out2:
+ (void) kadm5_log_end(context);
+ out:
+ if (!context->keep_open) {
+ kadm5_ret_t ret2;
+ ret2 = context->db->hdb_close(context->context, context->db);
+ if (ret == 0 && ret2 != 0)
+ ret = ret2;
+ }
+ return _kadm5_error_code(ret);
+}
+
diff --git a/third_party/heimdal/lib/kadm5/sample_hook.c b/third_party/heimdal/lib/kadm5/sample_hook.c
new file mode 100644
index 0000000..03ac32b
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/sample_hook.c
@@ -0,0 +1,286 @@
+/*
+ * Copyright (c) 2018-2019, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <assert.h>
+
+#include <krb5.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "admin.h"
+#include "kadm5-hook.h"
+
+/*
+ * Sample kadm5 hook plugin that just logs when it is called. Install it
+ * somewhere and configure the path in the [kadmin] section of krb5.conf.
+ * e.g.
+ *
+ * [kadmin]
+ * plugin_dir = /usr/local/heimdal/lib/plugin/kadm5
+ *
+ */
+
+static char sample_data_1, sample_data_2;
+
+static krb5_error_code
+sample_log(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ const char *tag,
+ krb5_error_code code,
+ krb5_const_principal princ)
+{
+ char *p = NULL;
+ int which = 0;
+
+ /* verify we get called with the right contex tpointer */
+ if (data == &sample_data_1)
+ which = 1;
+ else if (data == &sample_data_2)
+ which = 2;
+
+ assert(which != 0);
+
+ /* code should always be zero on pre-commit */
+ assert(code == 0 || stage == KADM5_HOOK_STAGE_POSTCOMMIT);
+
+ if (princ)
+ (void) krb5_unparse_name(context, princ, &p);
+
+ krb5_warn(context, code, "sample_hook_%d: %s %s hook princ '%s'", which, tag,
+ stage == KADM5_HOOK_STAGE_PRECOMMIT ? "pre-commit" : "post-commit",
+ p != NULL ? p : "<unknown>");
+
+ krb5_xfree(p);
+
+ /* returning zero and KRB5_PLUGIN_NO_HANDLE are the same for hook plugins */
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+sample_init_1(krb5_context context, void **data)
+{
+ *data = &sample_data_1;
+ krb5_warn(context, 0, "sample_hook_1: initializing");
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+sample_init_2(krb5_context context, void **data)
+{
+ *data = &sample_data_2;
+ krb5_warn(context, 0, "sample_hook_2: initializing");
+ return 0;
+}
+
+static void KRB5_CALLCONV
+sample_fini(void *data)
+{
+ krb5_warn(NULL, 0, "sample_fini: finalizing");
+}
+
+static krb5_error_code KRB5_CALLCONV
+sample_chpass_hook(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ,
+ uint32_t flags,
+ size_t n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ const char *password)
+{
+ return sample_log(context, data, stage, "chpass", code, princ);
+}
+
+static krb5_error_code KRB5_CALLCONV
+sample_chpass_with_key_hook(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ,
+ uint32_t flags,
+ size_t n_key_data,
+ krb5_key_data *key_data)
+{
+ return sample_log(context, data, stage, "chpass_with_key", code, princ);
+}
+
+static krb5_error_code KRB5_CALLCONV
+sample_create_hook(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ kadm5_principal_ent_t ent,
+ uint32_t mask,
+ const char *password)
+{
+ return sample_log(context, data, stage, "create", code, ent->principal);
+}
+
+static krb5_error_code KRB5_CALLCONV
+sample_modify_hook(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ kadm5_principal_ent_t ent,
+ uint32_t mask)
+{
+ return sample_log(context, data, stage, "modify", code, ent->principal);
+}
+
+static krb5_error_code KRB5_CALLCONV
+sample_delete_hook(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ)
+{
+ return sample_log(context, data, stage, "delete", code, princ);
+}
+
+static krb5_error_code KRB5_CALLCONV
+sample_randkey_hook(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ)
+{
+ return sample_log(context, data, stage, "randkey", code, princ);
+}
+
+static krb5_error_code KRB5_CALLCONV
+sample_rename_hook(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal source,
+ krb5_const_principal target)
+{
+ return sample_log(context, data, stage, "rename", code, source);
+}
+
+static krb5_error_code KRB5_CALLCONV
+sample_set_keys_hook(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ,
+ uint32_t flags,
+ size_t n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ size_t n_keys,
+ krb5_keyblock *keyblocks)
+{
+ return sample_log(context, data, stage, "set_keys", code, princ);
+}
+
+static krb5_error_code KRB5_CALLCONV
+sample_prune_hook(krb5_context context,
+ void *data,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ,
+ int kvno)
+{
+ return sample_log(context, data, stage, "prune", code, princ);
+}
+
+
+static const kadm5_hook_ftable sample_hook_1 = {
+ KADM5_HOOK_VERSION_V1,
+ sample_init_1,
+ sample_fini,
+ "sample_hook_1",
+ "Heimdal",
+ sample_chpass_hook,
+ sample_chpass_with_key_hook,
+ sample_create_hook,
+ sample_modify_hook,
+ sample_delete_hook,
+ sample_randkey_hook,
+ sample_rename_hook,
+ sample_set_keys_hook,
+ sample_prune_hook,
+};
+
+static const kadm5_hook_ftable sample_hook_2 = {
+ KADM5_HOOK_VERSION_V1,
+ sample_init_2,
+ sample_fini,
+ "sample_hook_2",
+ "Heimdal",
+ sample_chpass_hook,
+ sample_chpass_with_key_hook,
+ sample_create_hook,
+ sample_modify_hook,
+ sample_delete_hook,
+ sample_randkey_hook,
+ sample_rename_hook,
+ sample_set_keys_hook,
+ sample_prune_hook,
+};
+
+/* Arrays of pointers, because hooks may be different versions/sizes */
+static const kadm5_hook_ftable *const sample_hooks[] = {
+ &sample_hook_1,
+ &sample_hook_2,
+};
+
+krb5_error_code
+kadm5_hook_plugin_load(krb5_context context,
+ krb5_get_instance_func_t *get_instance,
+ size_t *num_hooks,
+ const kadm5_hook_ftable *const **hooks);
+
+static uintptr_t KRB5_LIB_CALL
+sample_hook_get_instance(const char *libname)
+{
+ if (strcmp(libname, "kadm5") == 0)
+ return kadm5_get_instance(libname);
+ else if (strcmp(libname, "krb5") == 0)
+ return krb5_get_instance(libname);
+
+ return 0;
+}
+
+krb5_error_code
+kadm5_hook_plugin_load(krb5_context context,
+ krb5_get_instance_func_t *get_instance,
+ size_t *num_hooks,
+ const kadm5_hook_ftable *const **hooks)
+{
+ *get_instance = sample_hook_get_instance;
+ *num_hooks = sizeof(sample_hooks) / sizeof(sample_hooks[0]);
+ *hooks = sample_hooks;
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/sample_passwd_check.c b/third_party/heimdal/lib/kadm5/sample_passwd_check.c
new file mode 100644
index 0000000..6df9513
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/sample_passwd_check.c
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/* $Id$ */
+
+#include <string.h>
+#include <stdlib.h>
+#include <krb5.h>
+
+const char* check_length(krb5_context, krb5_principal, krb5_data *);
+
+/* specify the api-version this library conforms to */
+
+int version = 0;
+
+/* just check the length of the password, this is what the default
+ check does, but this lets you specify the minimum length in
+ krb5.conf */
+const char*
+check_length(krb5_context context,
+ krb5_principal prinipal,
+ krb5_data *password)
+{
+ int min_length = krb5_config_get_int_default(context, NULL, 6,
+ "password_quality",
+ "min_length",
+ NULL);
+ if(password->length < min_length)
+ return "Password too short";
+ return NULL;
+}
+
+#ifdef DICTPATH
+
+/* use cracklib to check password quality; this requires a patch for
+ cracklib that can be found at
+ ftp://ftp.pdc.kth.se/pub/krb/src/cracklib.patch */
+
+const char*
+check_cracklib(krb5_context context,
+ krb5_principal principal,
+ krb5_data *password)
+{
+ char *s = malloc(password->length + 1);
+ char *msg;
+ char *strings[2];
+ if(s == NULL)
+ return NULL; /* XXX */
+ strings[0] = principal->name.name_string.val[0]; /* XXX */
+ strings[1] = NULL;
+ memcpy(s, password->data, password->length);
+ s[password->length] = '\0';
+ msg = FascistCheck(s, DICTPATH, strings);
+ memset(s, 0, password->length);
+ free(s);
+ return msg;
+}
+#endif
diff --git a/third_party/heimdal/lib/kadm5/send_recv.c b/third_party/heimdal/lib/kadm5/send_recv.c
new file mode 100644
index 0000000..cf52fcd
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/send_recv.c
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 1997-2003, 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+_kadm5_client_send(kadm5_client_context *context, krb5_storage *sp)
+{
+ krb5_data msg, out;
+ krb5_error_code ret;
+ size_t len;
+ krb5_storage *sock;
+
+ assert(context->sock != rk_INVALID_SOCKET);
+
+ len = krb5_storage_seek(sp, 0, SEEK_CUR);
+ ret = krb5_data_alloc(&msg, len);
+ if (ret) {
+ krb5_clear_error_message(context->context);
+ return ret;
+ }
+ krb5_storage_seek(sp, 0, SEEK_SET);
+ krb5_storage_read(sp, msg.data, msg.length);
+
+ ret = krb5_mk_priv(context->context, context->ac, &msg, &out, NULL);
+ krb5_data_free(&msg);
+ if(ret)
+ return ret;
+
+ sock = krb5_storage_from_socket(context->sock);
+ if(sock == NULL) {
+ krb5_data_free(&out);
+ return krb5_enomem(context->context);
+ }
+
+ ret = krb5_store_data(sock, out);
+ if (ret)
+ krb5_clear_error_message(context->context);
+ krb5_storage_free(sock);
+ krb5_data_free(&out);
+ return ret;
+}
+
+kadm5_ret_t
+_kadm5_client_recv(kadm5_client_context *context, krb5_data *reply)
+{
+ krb5_error_code ret;
+ krb5_data data;
+ krb5_storage *sock;
+
+ sock = krb5_storage_from_socket(context->sock);
+ if (sock == NULL)
+ return krb5_enomem(context->context);
+ ret = krb5_ret_data(sock, &data);
+
+ krb5_storage_free(sock);
+ krb5_clear_error_message(context->context);
+ if(ret == KRB5_CC_END)
+ return KADM5_RPC_ERROR;
+ else if(ret)
+ return ret;
+
+ ret = krb5_rd_priv(context->context, context->ac, &data, reply, NULL);
+ krb5_data_free(&data);
+ return ret;
+}
+
diff --git a/third_party/heimdal/lib/kadm5/server_glue.c b/third_party/heimdal/lib/kadm5/server_glue.c
new file mode 100644
index 0000000..4b430b6
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/server_glue.c
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+kadm5_init_with_password(const char *client_name,
+ const char *password,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_s_init_with_password(client_name,
+ password,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_init_with_password_ctx(krb5_context context,
+ const char *client_name,
+ const char *password,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_s_init_with_password_ctx(context,
+ client_name,
+ password,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_init_with_skey(const char *client_name,
+ const char *keytab,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_s_init_with_skey(client_name,
+ keytab,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_init_with_skey_ctx(krb5_context context,
+ const char *client_name,
+ const char *keytab,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_s_init_with_skey_ctx(context,
+ client_name,
+ keytab,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_init_with_creds(const char *client_name,
+ krb5_ccache ccache,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_s_init_with_creds(client_name,
+ ccache,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
+
+kadm5_ret_t
+kadm5_init_with_creds_ctx(krb5_context context,
+ const char *client_name,
+ krb5_ccache ccache,
+ const char *service_name,
+ kadm5_config_params *realm_params,
+ unsigned long struct_version,
+ unsigned long api_version,
+ void **server_handle)
+{
+ return kadm5_s_init_with_creds_ctx(context,
+ client_name,
+ ccache,
+ service_name,
+ realm_params,
+ struct_version,
+ api_version,
+ server_handle);
+}
diff --git a/third_party/heimdal/lib/kadm5/server_hooks.c b/third_party/heimdal/lib/kadm5/server_hooks.c
new file mode 100644
index 0000000..0973382
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/server_hooks.c
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2018, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "kadm5_locl.h"
+
+static const char *kadm5_hook_plugin_deps[] = {
+ "kadm5",
+ "krb5",
+ NULL
+};
+
+struct heim_plugin_data kadm5_hook_plugin_data = {
+ "kadm5",
+ "kadm5_hook",
+ KADM5_HOOK_VERSION_V1,
+ kadm5_hook_plugin_deps,
+ kadm5_get_instance
+};
+
+void
+_kadm5_s_set_hook_error_message(kadm5_server_context *context,
+ krb5_error_code ret,
+ const char *op,
+ const struct kadm5_hook_ftable *hook,
+ enum kadm5_hook_stage stage)
+{
+ assert(ret != 0);
+
+ krb5_set_error_message(context->context, ret,
+ "%s hook `%s' failed %s-commit",
+ op, hook->name,
+ stage == KADM5_HOOK_STAGE_PRECOMMIT ? "pre" : "post");
+}
+
+kadm5_ret_t
+_kadm5_s_init_hooks(kadm5_server_context *ctx)
+{
+ krb5_context context = ctx->context;
+ char **dirs;
+
+ dirs = krb5_config_get_strings(context, NULL, "kadmin",
+ "plugin_dir", NULL);
+ if (dirs == NULL)
+ return 0;
+
+ _krb5_load_plugins(context, "kadm5", (const char **)dirs);
+ krb5_config_free_strings(dirs);
+
+ return 0;
+}
+
+void
+_kadm5_s_free_hooks(kadm5_server_context *ctx)
+{
+ _krb5_unload_plugins(ctx->context, "kadm5");
+}
+
+uintptr_t KRB5_LIB_CALL
+kadm5_get_instance(const char *libname)
+{
+ static const char *instance = "libkadm5";
+
+ if (strcmp(libname, "kadm5") == 0)
+ return (uintptr_t)instance;
+ else if (strcmp(libname, "krb5") == 0)
+ return krb5_get_instance(libname);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/set_keys.c b/third_party/heimdal/lib/kadm5/set_keys.c
new file mode 100644
index 0000000..c30c5d8
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/set_keys.c
@@ -0,0 +1,420 @@
+/*
+ * Copyright (c) 1997 - 2001, 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+/*
+ * Set the keys of `ent' to the string-to-key of `password'
+ */
+
+kadm5_ret_t
+_kadm5_set_keys(kadm5_server_context *context,
+ hdb_entry *ent,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ const char *password)
+{
+ Key *keys;
+ size_t num_keys;
+ kadm5_ret_t ret;
+
+ ret = hdb_generate_key_set_password_with_ks_tuple(context->context,
+ ent->principal,
+ password,
+ ks_tuple, n_ks_tuple,
+ &keys, &num_keys);
+ if (ret)
+ return ret;
+
+ _kadm5_free_keys (context->context, ent->keys.len, ent->keys.val);
+ ent->keys.val = keys;
+ ent->keys.len = num_keys;
+
+ hdb_entry_set_pw_change_time(context->context, ent, 0);
+
+ if (krb5_config_get_bool_default(context->context, NULL, FALSE,
+ "kadmin", "save-password", NULL))
+ {
+ ret = hdb_entry_set_password(context->context, context->db,
+ ent, password);
+ if (ret)
+ return ret;
+ }
+
+ return 0;
+}
+
+static void
+setup_Key(Key *k, Salt *s, krb5_key_data *kd, size_t kd_offset)
+{
+ memset(k, 0, sizeof (*k)); /* sets mkvno and salt */
+ k->key.keytype = kd[kd_offset].key_data_type[0];
+ k->key.keyvalue.length = kd[kd_offset].key_data_length[0];
+ k->key.keyvalue.data = kd[kd_offset].key_data_contents[0];
+
+ if(kd[kd_offset].key_data_ver == 2) {
+ memset(s, 0, sizeof (*s));
+ s->type = kd[kd_offset].key_data_type[1];
+ s->salt.length = kd[kd_offset].key_data_length[1];
+ s->salt.data = kd[kd_offset].key_data_contents[1];
+ k->salt = s;
+ }
+}
+
+/*
+ * Set the keys of `ent' to (`n_key_data', `key_data')
+ */
+
+kadm5_ret_t
+_kadm5_set_keys2(kadm5_server_context *context,
+ hdb_entry *ent,
+ int16_t n_key_data,
+ krb5_key_data *key_data)
+{
+ krb5_error_code ret;
+ size_t i, k;
+ HDB_extension ext;
+ HDB_extension *extp = NULL;
+ HDB_Ext_KeySet *hist_keys = &ext.data.u.hist_keys;
+ Key key;
+ Salt salt;
+ Keys keys;
+ hdb_keyset hkset;
+ krb5_kvno kvno = -1;
+ int one_key_set = 1;
+ int replace_hist_keys = 0;
+
+ if (n_key_data == 0) {
+ /* Clear all keys! */
+ ret = hdb_clear_extension(context->context, ent,
+ choice_HDB_extension_data_hist_keys);
+ if (ret)
+ return ret;
+ free_Keys(&ent->keys);
+ return 0;
+ }
+
+ memset(&keys, 0, sizeof (keys));
+ memset(&hkset, 0, sizeof (hkset)); /* set set_time */
+ memset(&ext, 0, sizeof (ext));
+ ext.mandatory = FALSE;
+ ext.data.element = choice_HDB_extension_data_hist_keys;
+ memset(hist_keys, 0, sizeof (*hist_keys));
+
+ for (i = 0; i < n_key_data; i++) {
+ if (kvno != -1 && kvno != key_data[i].key_data_kvno) {
+ one_key_set = 0;
+ break;
+ }
+ kvno = key_data[i].key_data_kvno;
+ }
+ if (one_key_set) {
+ /*
+ * If we're updating KADM5_KEY_DATA with a single keyset then we
+ * assume we must be setting the principal's kvno as well!
+ *
+ * Just have to be careful about old clients that might have
+ * sent 0 as the kvno... This may seem ugly, but it's the price
+ * of backwards compatibility with pre-multi-kvno kadmin clients
+ * (besides, who's to say that updating KADM5_KEY_DATA requires
+ * updating the entry's kvno?)
+ *
+ * Note that we do nothing special for the case where multiple
+ * keysets are given but the entry's kvno is not set and not in
+ * the given set of keysets. If this happens we'll just update
+ * the key history only and leave the current keyset alone.
+ */
+ if (kvno == 0) {
+ /* Force kvno to 1 if it was 0; (ank would do this anyways) */
+ if (ent->kvno == 0)
+ ent->kvno = 1;
+ /* Below we need key_data[*].kvno to be reasonable */
+ for (i = 0; i < n_key_data; i++)
+ key_data[i].key_data_kvno = ent->kvno;
+ } else {
+ /*
+ * Or force the entry's kvno to match the one from the new,
+ * singular keyset
+ */
+ ent->kvno = kvno;
+ }
+ }
+
+ for (i = 0; i < n_key_data; i++) {
+ if (key_data[i].key_data_kvno == ent->kvno) {
+ /* A current key; add to current key set */
+ setup_Key(&key, &salt, key_data, i);
+ ret = add_Keys(&keys, &key);
+ if (ret)
+ goto out;
+ continue;
+ }
+
+ /*
+ * This kvno is historical. Build an hdb_keyset for keys of
+ * this enctype and add them to the new key history.
+ */
+ for (k = 0; k < hist_keys->len; k++) {
+ if (hist_keys->val[k].kvno == key_data[i].key_data_kvno)
+ break;
+ }
+ if (hist_keys->len > k &&
+ hist_keys->val[k].kvno == key_data[i].key_data_kvno)
+ /* We've added all keys of this kvno already (see below) */
+ continue;
+
+ memset(&hkset, 0, sizeof (hkset)); /* set set_time */
+ hkset.kvno = key_data[i].key_data_kvno;
+ for (k = 0; k < n_key_data; k++) {
+ /* Find all keys of this kvno and add them to the new keyset */
+ if (key_data[k].key_data_kvno != hkset.kvno)
+ continue;
+
+ setup_Key(&key, &salt, key_data, k);
+ ret = add_Keys(&hkset.keys, &key);
+ if (ret) {
+ free_hdb_keyset(&hkset);
+ goto out;
+ }
+ }
+ ret = add_HDB_Ext_KeySet(hist_keys, &hkset);
+ free_hdb_keyset(&hkset);
+ if (ret)
+ goto out;
+ replace_hist_keys = 1;
+ }
+
+ if (replace_hist_keys)
+ /* No key history given -> leave it alone */
+ extp = hdb_find_extension(ent, choice_HDB_extension_data_hist_keys);
+ if (extp != NULL) {
+ HDB_Ext_KeySet *old_hist_keys;
+
+ /*
+ * Try to keep the very useful set_time values from the old hist
+ * keys. kadm5 loses this info, so this heuristic is the best we
+ * can do.
+ */
+ old_hist_keys = &extp->data.u.hist_keys;
+ for (i = 0; i < old_hist_keys->len; i++) {
+ if (old_hist_keys->val[i].set_time == NULL)
+ continue;
+ for (k = 0; k < hist_keys->len; k++) {
+ if (hist_keys->val[k].kvno != old_hist_keys->val[k].kvno)
+ continue;
+ hist_keys->val[k].set_time = old_hist_keys->val[k].set_time;
+ old_hist_keys->val[k].set_time = NULL;
+ }
+ }
+ }
+
+ if (replace_hist_keys) {
+ /* If hist keys not given in key_data then don't blow away hist_keys */
+ ret = hdb_replace_extension(context->context, ent, &ext);
+ if (ret)
+ goto out;
+ }
+
+ /*
+ * A structure copy is more efficient here than this would be:
+ *
+ * copy_Keys(&keys, &ent->keys);
+ * free_Keys(&keys);
+ *
+ * Of course, the above hdb_replace_extension() is not at all efficient...
+ */
+ free_HDB_extension(&ext);
+ free_Keys(&ent->keys);
+ free_hdb_keyset(&hkset);
+ ent->keys = keys;
+ hdb_entry_set_pw_change_time(context->context, ent, 0);
+ hdb_entry_clear_password(context->context, ent);
+
+ return 0;
+
+out:
+ free_Keys(&keys);
+ free_HDB_extension(&ext);
+ return ret;
+}
+
+/*
+ * Set the keys of `ent' to `n_keys, keys'
+ */
+
+kadm5_ret_t
+_kadm5_set_keys3(kadm5_server_context *context,
+ hdb_entry *ent,
+ int n_keys,
+ krb5_keyblock *keyblocks)
+{
+ krb5_error_code ret;
+ int i;
+ unsigned len;
+ Key *keys;
+
+ len = n_keys;
+ keys = malloc (len * sizeof(*keys));
+ if (keys == NULL && len != 0)
+ return krb5_enomem(context->context);
+
+ _kadm5_init_keys (keys, len);
+
+ for(i = 0; i < n_keys; i++) {
+ keys[i].mkvno = NULL;
+ ret = krb5_copy_keyblock_contents (context->context,
+ &keyblocks[i],
+ &keys[i].key);
+ if(ret)
+ goto out;
+ keys[i].salt = NULL;
+ }
+ _kadm5_free_keys (context->context, ent->keys.len, ent->keys.val);
+ ent->keys.len = len;
+ ent->keys.val = keys;
+
+ hdb_entry_set_pw_change_time(context->context, ent, 0);
+ hdb_entry_clear_password(context->context, ent);
+
+ return 0;
+ out:
+ _kadm5_free_keys (context->context, len, keys);
+ return ret;
+}
+
+/*
+ *
+ */
+
+static int
+is_des_key_p(int keytype)
+{
+ return keytype == ETYPE_DES_CBC_CRC ||
+ keytype == ETYPE_DES_CBC_MD4 ||
+ keytype == ETYPE_DES_CBC_MD5;
+}
+
+
+/*
+ * Set the keys of `ent' to random keys and return them in `n_keys'
+ * and `new_keys'.
+ */
+
+kadm5_ret_t
+_kadm5_set_keys_randomly (kadm5_server_context *context,
+ hdb_entry *ent,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ krb5_keyblock **new_keys,
+ int *n_keys)
+{
+ krb5_keyblock *kblock = NULL;
+ kadm5_ret_t ret = 0;
+ int des_keyblock;
+ size_t i, num_keys;
+ Key *keys;
+
+ ret = hdb_generate_key_set(context->context, ent->principal,
+ ks_tuple, n_ks_tuple, &keys, &num_keys, 1);
+ if (ret)
+ return ret;
+
+ kblock = malloc(num_keys * sizeof(kblock[0]));
+ if (kblock == NULL) {
+ ret = krb5_enomem(context->context);
+ _kadm5_free_keys (context->context, num_keys, keys);
+ return ret;
+ }
+ memset(kblock, 0, num_keys * sizeof(kblock[0]));
+
+ des_keyblock = -1;
+ for (i = 0; i < num_keys; i++) {
+
+ /*
+ * To make sure all des keys are the the same we generate only
+ * the first one and then copy key to all other des keys.
+ */
+
+ if (des_keyblock != -1 && is_des_key_p(keys[i].key.keytype)) {
+ ret = krb5_copy_keyblock_contents (context->context,
+ &kblock[des_keyblock],
+ &kblock[i]);
+ if (ret)
+ goto out;
+ kblock[i].keytype = keys[i].key.keytype;
+ } else {
+ ret = krb5_generate_random_keyblock (context->context,
+ keys[i].key.keytype,
+ &kblock[i]);
+ if (ret)
+ goto out;
+
+ if (is_des_key_p(keys[i].key.keytype))
+ des_keyblock = i;
+ }
+
+ ret = krb5_copy_keyblock_contents (context->context,
+ &kblock[i],
+ &keys[i].key);
+ if (ret)
+ goto out;
+ }
+
+out:
+ if(ret) {
+ for (i = 0; i < num_keys; ++i)
+ krb5_free_keyblock_contents(context->context, &kblock[i]);
+ free(kblock);
+ _kadm5_free_keys(context->context, num_keys, keys);
+ return ret;
+ }
+
+ _kadm5_free_keys(context->context, ent->keys.len, ent->keys.val);
+ ent->keys.val = keys;
+ ent->keys.len = num_keys;
+ if (n_keys && new_keys) {
+ *new_keys = kblock;
+ *n_keys = num_keys;
+ } else {
+ for (i = 0; i < num_keys; ++i)
+ krb5_free_keyblock_contents(context->context, &kblock[i]);
+ free(kblock);
+ }
+
+ hdb_entry_set_pw_change_time(context->context, ent, 0);
+ hdb_entry_clear_password(context->context, ent);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/set_modifier.c b/third_party/heimdal/lib/kadm5/set_modifier.c
new file mode 100644
index 0000000..dd0e427
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/set_modifier.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+RCSID("$Id$");
+
+kadm5_ret_t
+_kadm5_set_modifier(kadm5_server_context *context,
+ hdb_entry *ent)
+{
+ kadm5_ret_t ret;
+ if(ent->modified_by == NULL){
+ ent->modified_by = malloc(sizeof(*ent->modified_by));
+ if(ent->modified_by == NULL)
+ return krb5_enomem(context->context);
+ } else
+ free_Event(ent->modified_by);
+ ent->modified_by->time = time(NULL);
+ ret = krb5_copy_principal(context->context, context->caller,
+ &ent->modified_by->principal);
+ return ret;
+}
+
diff --git a/third_party/heimdal/lib/kadm5/setkey3_s.c b/third_party/heimdal/lib/kadm5/setkey3_s.c
new file mode 100644
index 0000000..584c194
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/setkey3_s.c
@@ -0,0 +1,220 @@
+/*
+ * Copyright (c) 1997-2001, 2003, 2005-2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kadm5_locl.h"
+
+struct setkey_principal_hook_ctx {
+ kadm5_server_context *context;
+ enum kadm5_hook_stage stage;
+ krb5_error_code code;
+ krb5_const_principal princ;
+ uint32_t flags;
+ size_t n_ks_tuple;
+ krb5_key_salt_tuple *ks_tuple;
+ size_t n_keys;
+ krb5_keyblock *keys;
+};
+
+static krb5_error_code KRB5_LIB_CALL
+setkey_principal_hook_cb(krb5_context context,
+ const void *hook,
+ void *hookctx,
+ void *userctx)
+{
+ krb5_error_code ret;
+ const struct kadm5_hook_ftable *ftable = hook;
+ struct setkey_principal_hook_ctx *ctx = userctx;
+
+ ret = ftable->set_keys(context, hookctx,
+ ctx->stage, ctx->code,
+ ctx->princ, ctx->flags,
+ ctx->n_ks_tuple, ctx->ks_tuple,
+ ctx->n_keys, ctx->keys);
+ if (ret != 0 && ret != KRB5_PLUGIN_NO_HANDLE)
+ _kadm5_s_set_hook_error_message(ctx->context, ret, "setkey",
+ hook, ctx->stage);
+
+ /* only pre-commit plugins can abort */
+ if (ret == 0 || ctx->stage == KADM5_HOOK_STAGE_POSTCOMMIT)
+ ret = KRB5_PLUGIN_NO_HANDLE;
+
+ return ret;
+}
+
+static kadm5_ret_t
+setkey_principal_hook(kadm5_server_context *context,
+ enum kadm5_hook_stage stage,
+ krb5_error_code code,
+ krb5_const_principal princ,
+ uint32_t flags,
+ size_t n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ size_t n_keys,
+ krb5_keyblock *keyblocks)
+{
+ krb5_error_code ret;
+ struct setkey_principal_hook_ctx ctx;
+
+ ctx.context = context;
+ ctx.stage = stage;
+ ctx.code = code;
+ ctx.princ = princ;
+ ctx.flags = flags;
+ ctx.n_ks_tuple = n_ks_tuple;
+ ctx.ks_tuple = ks_tuple;
+ ctx.n_keys = n_keys;
+ ctx.keys = keyblocks;
+
+ ret = _krb5_plugin_run_f(context->context, &kadm5_hook_plugin_data,
+ 0, &ctx, setkey_principal_hook_cb);
+ if (ret == KRB5_PLUGIN_NO_HANDLE)
+ ret = 0;
+
+ return ret;
+}
+
+/**
+ * Server-side function to set new keys for a principal.
+ */
+kadm5_ret_t
+kadm5_s_setkey_principal_3(void *server_handle,
+ krb5_principal princ,
+ krb5_boolean keepold,
+ int n_ks_tuple,
+ krb5_key_salt_tuple *ks_tuple,
+ krb5_keyblock *keyblocks, int n_keys)
+{
+ kadm5_server_context *context = server_handle;
+ hdb_entry ent;
+ kadm5_ret_t ret = 0;
+ size_t i;
+
+ memset(&ent, 0, sizeof(ent));
+ if (!context->keep_open)
+ ret = context->db->hdb_open(context->context, context->db, O_RDWR, 0);
+ if (ret)
+ return ret;
+
+ ret = kadm5_log_init(context);
+ if (ret) {
+ if (!context->keep_open)
+ context->db->hdb_close(context->context, context->db);
+ return ret;
+ }
+
+ /* NOTE: We do not use hdb_fetch_kvno() here (maybe we should?) */
+ ret = context->db->hdb_fetch_kvno(context->context, context->db, princ,
+ HDB_F_DECRYPT|HDB_F_GET_ANY|HDB_F_ADMIN_DATA,
+ 0, &ent);
+ if (ret) {
+ (void) kadm5_log_end(context);
+ if (!context->keep_open)
+ context->db->hdb_close(context->context, context->db);
+ return ret;
+ }
+
+ ret = setkey_principal_hook(context, KADM5_HOOK_STAGE_PRECOMMIT, 0,
+ princ, keepold ? KADM5_HOOK_FLAG_KEEPOLD : 0,
+ n_ks_tuple, ks_tuple, n_keys, keyblocks);
+ if (ret) {
+ (void) kadm5_log_end(context);
+ if (!context->keep_open)
+ context->db->hdb_close(context->context, context->db);
+ return ret;
+ }
+
+ if (keepold) {
+ ret = hdb_add_current_keys_to_history(context->context, &ent);
+ } else
+ ret = hdb_clear_extension(context->context, &ent,
+ choice_HDB_extension_data_hist_keys);
+
+ /*
+ * Though in practice all real calls to this function will pass an empty
+ * ks_tuple, and cannot in any case employ any salts that require
+ * additional data, we go the extra mile to set any requested salt type
+ * along with a zero length salt value. While we're at it we check that
+ * each ks_tuple's enctype matches the corresponding key enctype.
+ */
+ if (ret == 0) {
+ free_Keys(&ent.keys);
+ for (i = 0; i < n_keys; ++i) {
+ Key k;
+ Salt s;
+
+ k.mkvno = 0;
+ k.key = keyblocks[i];
+ if (n_ks_tuple == 0)
+ k.salt = 0;
+ else {
+ if (ks_tuple[i].ks_enctype != keyblocks[i].keytype) {
+ ret = KADM5_SETKEY3_ETYPE_MISMATCH;
+ break;
+ }
+ s.type = ks_tuple[i].ks_salttype;
+ s.salt.data = 0;
+ s.opaque = 0;
+ k.salt = &s;
+ }
+ if ((ret = add_Keys(&ent.keys, &k)) != 0)
+ break;
+ }
+ }
+
+ if (ret == 0) {
+ ent.kvno++;
+ ent.flags.require_pwchange = 0;
+ hdb_entry_set_pw_change_time(context->context, &ent, 0);
+ hdb_entry_clear_password(context->context, &ent);
+
+ if ((ret = hdb_seal_keys(context->context, context->db,
+ &ent)) == 0
+ && (ret = _kadm5_set_modifier(context, &ent)) == 0
+ && (ret = _kadm5_bump_pw_expire(context, &ent)) == 0)
+ ret = kadm5_log_modify(context, &ent,
+ KADM5_ATTRIBUTES | KADM5_PRINCIPAL |
+ KADM5_MOD_NAME | KADM5_MOD_TIME |
+ KADM5_KEY_DATA | KADM5_KVNO |
+ KADM5_PW_EXPIRATION | KADM5_TL_DATA);
+ }
+
+ (void) setkey_principal_hook(context, KADM5_HOOK_STAGE_POSTCOMMIT, ret,
+ princ, keepold, n_ks_tuple, ks_tuple,
+ n_keys, keyblocks);
+
+ hdb_free_entry(context->context, context->db, &ent);
+ (void) kadm5_log_end(context);
+ if (!context->keep_open)
+ context->db->hdb_close(context->context, context->db);
+ return _kadm5_error_code(ret);
+}
diff --git a/third_party/heimdal/lib/kadm5/test_pw_quality.c b/third_party/heimdal/lib/kadm5/test_pw_quality.c
new file mode 100644
index 0000000..6544afd
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/test_pw_quality.c
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2003, 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <string.h>
+#include <stdlib.h>
+#include <getarg.h>
+
+#include <roken.h>
+#include <krb5.h>
+
+#include "admin.h"
+
+static int version_flag;
+static int help_flag;
+static char *principal;
+static char *password;
+
+static struct getargs args[] = {
+ { "principal", 0, arg_string, &principal, NULL, NULL },
+ { "password", 0, arg_string, &password, NULL, NULL },
+ { "version", 0, arg_flag, &version_flag, NULL, NULL },
+ { "help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+int num_args = sizeof(args) / sizeof(args[0]);
+
+int
+main(int argc, char **argv)
+{
+ krb5_error_code ret;
+ krb5_context context;
+ krb5_principal p;
+ const char *s;
+ krb5_data pw_data;
+
+ krb5_program_setup(&context, argc, argv, args, num_args, NULL);
+
+ if(help_flag)
+ krb5_std_usage(0, args, num_args);
+ if(version_flag) {
+ print_version(NULL);
+ exit(0);
+ }
+
+ if (principal == NULL)
+ krb5_errx(context, 1, "no principal given");
+ if (password == NULL)
+ krb5_errx(context, 1, "no password given");
+
+ ret = krb5_parse_name(context, principal, &p);
+ if (ret)
+ krb5_errx(context, 1, "krb5_parse_name: %s", principal);
+
+ pw_data.data = password;
+ pw_data.length = strlen(password);
+
+ kadm5_setup_passwd_quality_check (context, NULL, NULL);
+ ret = kadm5_add_passwd_quality_verifier(context, NULL);
+ if (ret)
+ krb5_errx(context, 1, "kadm5_add_passwd_quality_verifier");
+
+ s = kadm5_check_password_quality (context, p, &pw_data);
+ if (s)
+ krb5_errx(context, 1, "kadm5_check_password_quality:\n%s", s);
+
+ krb5_free_principal(context, p);
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/kadm5/version-script-client.map b/third_party/heimdal/lib/kadm5/version-script-client.map
new file mode 100644
index 0000000..4d89fab
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/version-script-client.map
@@ -0,0 +1,61 @@
+HEIMDAL_KADM5_CLIENT_1.0 {
+ global:
+ et_kadm5_error_table;
+ initialize_kadm5_error_table;
+ initialize_kadm5_error_table_r;
+ kadm5_ad_init_with_password;
+ kadm5_ad_init_with_password_ctx;
+ kadm5_all_keys_are_bogus;
+ kadm5_c_chpass_principal;
+ kadm5_c_chpass_principal_with_key;
+ kadm5_c_create_principal;
+ kadm5_c_delete_principal;
+ kadm5_c_destroy;
+ kadm5_c_flush;
+ kadm5_c_get_principal;
+ kadm5_c_get_principals;
+ kadm5_c_get_privs;
+ kadm5_c_init_with_creds;
+ kadm5_c_init_with_creds_ctx;
+ kadm5_c_init_with_password;
+ kadm5_c_init_with_password_ctx;
+ kadm5_c_init_with_skey;
+ kadm5_c_init_with_skey_ctx;
+ kadm5_c_modify_principal;
+ kadm5_c_prune_principal;
+ kadm5_c_randkey_principal;
+ kadm5_c_rename_principal;
+ kadm5_chpass_principal;
+ kadm5_chpass_principal_with_key;
+ kadm5_create_principal;
+ kadm5_delete_principal;
+ kadm5_destroy;
+ kadm5_flush;
+ kadm5_free_key_data;
+ kadm5_free_name_list;
+ kadm5_free_principal_ent;
+ kadm5_get_principal;
+ kadm5_get_principals;
+ kadm5_get_privs;
+ kadm5_init_with_creds;
+ kadm5_init_with_creds_ctx;
+ kadm5_init_with_password;
+ kadm5_init_with_password_ctx;
+ kadm5_init_with_skey;
+ kadm5_init_with_skey_ctx;
+ kadm5_modify_principal;
+ kadm5_randkey_principal;
+ kadm5_randkey_principal_3;
+ kadm5_rename_principal;
+ kadm5_ret_key_data;
+ kadm5_ret_principal_ent;
+ kadm5_ret_principal_ent_mask;
+ kadm5_ret_tl_data;
+ kadm5_some_keys_are_bogus;
+ kadm5_store_key_data;
+ kadm5_store_principal_ent;
+ kadm5_store_principal_ent_mask;
+ kadm5_store_tl_data;
+ local:
+ *;
+};
diff --git a/third_party/heimdal/lib/kadm5/version-script.map b/third_party/heimdal/lib/kadm5/version-script.map
new file mode 100644
index 0000000..e4b4100
--- /dev/null
+++ b/third_party/heimdal/lib/kadm5/version-script.map
@@ -0,0 +1,96 @@
+# $Id$
+
+HEIMDAL_KAMD5_SERVER_1.0 {
+ global:
+ kadm5_ad_init_with_password;
+ kadm5_ad_init_with_password_ctx;
+ kadm5_all_keys_are_bogus;
+ kadm5_add_passwd_quality_verifier;
+ kadm5_check_password_quality;
+ kadm5_chpass_principal;
+ kadm5_chpass_principal_3;
+ kadm5_chpass_principal_with_key;
+ kadm5_chpass_principal_with_key_3;
+ kadm5_create_policy;
+ kadm5_create_principal;
+ kadm5_create_principal_3;
+ kadm5_delete_principal;
+ kadm5_destroy;
+ kadm5_decrypt_key;
+ kadm5_delete_policy;
+ kadm5_flush;
+ kadm5_free_key_data;
+ kadm5_free_name_list;
+ kadm5_free_policy_ent;
+ kadm5_free_principal_ent;
+ kadm5_get_instance;
+ kadm5_get_policy;
+ kadm5_get_policies;
+ kadm5_get_principal;
+ kadm5_get_principals;
+ kadm5_get_privs;
+ kadm5_init_with_creds;
+ kadm5_init_with_creds_ctx;
+ kadm5_init_with_password;
+ kadm5_init_with_password_ctx;
+ kadm5_init_with_skey;
+ kadm5_init_with_skey_ctx;
+ kadm5_lock;
+ kadm5_modify_principal;
+ kadm5_modify_policy;
+ kadm5_prune_principal;
+ kadm5_randkey_principal;
+ kadm5_randkey_principal_3;
+ kadm5_rename_principal;
+ kadm5_ret_key_data;
+ kadm5_ret_principal_ent;
+ kadm5_ret_principal_ent_mask;
+ kadm5_ret_tl_data;
+ kadm5_setup_passwd_quality_check;
+ kadm5_setkey_principal;
+ kadm5_setkey_principal_3;
+ kadm5_some_keys_are_bogus;
+ kadm5_store_key_data;
+ kadm5_store_principal_ent;
+ kadm5_store_principal_ent_mask;
+ kadm5_store_principal_ent_nokeys;
+ kadm5_store_tl_data;
+ kadm5_unlock;
+ kadm5_s_init_with_password_ctx;
+ kadm5_s_init_with_password;
+ kadm5_s_init_with_skey_ctx;
+ kadm5_s_init_with_skey;
+ kadm5_s_init_with_creds_ctx;
+ kadm5_s_init_with_creds;
+ kadm5_s_chpass_principal_cond;
+ kadm5_s_create_principal_with_key;
+ kadm5_log_exclusivelock;
+ kadm5_log_set_version;
+ kadm5_log_sharedlock;
+ kadm5_log_signal_master;
+ kadm5_log_signal_socket;
+ kadm5_log_previous;
+ kadm5_log_goto_first;
+ kadm5_log_goto_end;
+ kadm5_log_foreach;
+ kadm5_log_get_version_fd;
+ kadm5_log_get_version;
+ kadm5_log_recover;
+ kadm5_log_replay;
+ kadm5_log_end;
+ kadm5_log_reinit;
+ kadm5_log_init;
+ kadm5_log_init_nb;
+ kadm5_log_init_nolock;
+ kadm5_log_init_sharedlock;
+ kadm5_log_next;
+ kadm5_log_nop;
+ kadm5_log_truncate;
+ kadm5_log_modify;
+ _kadm5_acl_check_permission;
+ _kadm5_unmarshal_params;
+ _kadm5_s_get_db;
+ _kadm5_privs_to_string;
+ local:
+ *;
+};
diff --git a/third_party/heimdal/lib/kafs/ChangeLog b/third_party/heimdal/lib/kafs/ChangeLog
new file mode 100644
index 0000000..302146a
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/ChangeLog
@@ -0,0 +1,572 @@
+2008-07-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * common.c: Try afs/cell@REALM before afs@REALM since that is what
+ OpenAFS folks have been saying is best pratices for some time
+ now. Patch from Derrick Brashear.
+
+2008-04-15 Love Hörnquist Åstrand <lha@it.su.se>
+ * afssys.c: Avoid using entry points depending on _IOWR if there
+ is no _IOWR (on cygwin).
+
+2007-07-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: New library version.
+
+2007-05-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * kafs.h: Add VIOCSETTOK2
+
+2006-10-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: unbreak previous
+
+ * Makefile.am: split dist and nodist sources
+
+2006-10-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add more files
+
+2006-05-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * kafs.3: Spelling, from Björn Sandell.
+
+2006-04-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * afssys.c: use afs_ioctlnum, From Tomas Olsson <tol@it.su.se>
+
+2006-04-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * afssys.c: Try harder to get the pioctl to work via the /proc or
+ /dev interface, OpenAFS choose to reuse the same ioctl number,
+ while Arla didn't. Also, try new ioctl before the the old
+ syscalls.
+
+ * afskrb5.c (afslog_uid_int): use the simpler
+ krb5_principal_get_realm function.
+
+2005-12-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Remove dependency on config.h, breaks IRIX build,
+ could depend on libkafs_la_OBJECTS, but that is just asking for
+ trubble.
+
+2005-10-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * afssys.c (k_hasafs_recheck): new function, allow rechecking if
+ AFS client have started now, internaly it resets the internal
+ state from k_hasafs() and retry retry the probing. The problem
+ with calling k_hasaf() is that is plays around with signals, and
+ that cases problem for some systems/applications.
+
+2005-10-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * kafs_locl.h: Maybe include <sys/sysctl.h>.
+
+ * afssys.c: Mac OS X 10.4 needs a runtime check if we are going to
+ use the syscall, there is no cpp define to use to check the
+ version. Every after 10.0 (darwin 8.0) uses the /dev/ version of
+ the pioctl.
+
+2005-10-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * afssys.c: Support the new MacOS X 10.4 ioctl interface that is a
+ device node. Patched from Tomas Olson <tol@it.su.se>.
+
+2005-08-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * afskrb5.c: Default to use 2b tokens.
+
+2005-06-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * common.c: rename index to idx
+
+ * afssys.c (k_afs_cell_of_file): unconst path
+
+2005-06-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * use struct kafs_data everywhere, don't mix with the typedef
+ kafs_data
+
+ * roken_rename.h: rename more resolve.c symbols
+
+ * afssys.c: Don't building map_syscall_name_to_number where its
+ not used.
+
+2005-02-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: bump version to 4:1:4
+
+2005-02-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * kafs.h: de-__P
+
+2004-12-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * afskrb5.c: s/KEYTYPE_DES/ETYPE_DES_CBC_CRC/
+
+2004-08-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * afssysdefs.h: ifdef protect AFS_SYSCALL for DragonFly since they
+ still define __FreeBSD__ (and __FreeBSD_version), but claim that
+ they will stop doing it some time...
+
+ * afssysdefs.h: dragonflybsd uses 339 just like freebsd5
+
+2004-06-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * afssys.c: s/arla/nnpfs/
+
+ * afssys.c: support the linux /proc/fs/mumel/afs_ioctl afs
+ "syscall" interface
+
+2004-01-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * common.c: search paths for AFS configuration files for the
+ OpenAFS MacOS X, fix comment
+
+ * kafs.h: search paths for AFS configuration files for the OpenAFS
+ MacOS X
+
+2003-12-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * common.c: add _PATH_ARLA_OPENBSD & c/o
+
+ * kafs.h: add _PATH_ARLA_OPENBSD & c/o
+
+2003-11-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * common.c: typo, Bruno Rohee <bruno@rohee.com>
+
+2003-11-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * kafs.3: spelling, partly from jmc <jmc@prioris.mini.pw.edu.pl>
+
+2003-09-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * afskrb5.c (krb5_afslog_uid_home): be even more friendly to the
+ user and fetch context and id ourself
+
+2003-09-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * afskrb5.c (afslog_uid_int): just belive that realm hint the user
+ passed us
+
+2003-07-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: always include v4 symbols
+
+ * afskrb.c: provide dummy krb_ function to there is no need to
+ bump major
+
+2003-06-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * afskrb5.c (v5_convert): rename one of the two c to cred4
+
+2003-04-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * common.c, kafs.h: drop the int argument (the error code) from
+ the logging function
+
+2003-04-22 Johan Danielsson <joda@pdc.kth.se>
+
+ * afskrb5.c (v5_convert): better match what other functions do
+ with values from krb5.conf, like case insensitivity
+
+2003-04-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * kafs.3: Change .Fd #include <header.h> to .In header.h
+ from Thomas Klausner <wiz@netbsd.org>
+
+2003-04-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: (libkafs_la_LDFLAGS): update version
+
+ * Makefile.am (ROKEN_SRCS): drop strupr.c
+
+ * kafs.3: document kafs_set_verbose
+
+ * common.c (kafs_set_verbose): add function that (re)sets the
+ logging function
+ (_kafs_try_get_cred): add function that does (krb_data->get_cred) to
+ make logging easier (that is now done in this function)
+ (*): use _kafs_try_get_cred
+
+ * afskrb5.c (get_cred): handle that inst can be the empty string too
+ (v5_convert): use _kafs_foldup
+ (krb5_afslog_uid_home): set name
+ (krb5_afslog_uid_home): ditto
+
+ * afskrb.c (krb_afslog_uid_home): set name
+ (krb_afslog_uid_home): ditto
+
+ * kafs_locl.h (kafs_data): add name
+ (_kafs_foldup): internally export
+
+2003-04-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * kafs.3: tell that cell-name is uppercased
+
+ * Makefile.am: add INCLUDE_krb4 when using krb4, add INCLUDE_des
+ when using krb5, add strupr.c
+
+ * afskrb5.c: Check the cell part of the name, not the realm part
+ when checking if 2b should be used. The reson is afs@REALM might
+ have updated their servers but not afs/cell@REALM. Add constant
+ KAFS_RXKAD_2B_KVNO.
+
+2003-04-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * kafs.3: s/kerberos/Kerberos/
+
+2003-03-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * kafs.3: spelling, from <jmc@prioris.mini.pw.edu.pl>
+
+ * kafs.3: document the kafs_settoken functions write about the
+ krb5_appdefault option for kerberos 5 afs tokens fix prototypes
+
+2003-03-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * afskrb5.c (kafs_settoken5): change signature to include a
+ krb5_context, use v5_convert
+ (v5_convert): new function, converts a krb5_ccreds to a kafs_token in
+ three diffrent ways, not at all, local 524/2b, and using 524
+ (v5_to_kt): add code to do local 524/2b
+ (get_cred): use v5_convert
+
+
+ * kafs.h (kafs_settoken5): change signature to include a
+ krb5_context
+
+ * Makefile.am: always build the libkafs library now that the
+ kerberos 5 can stand on their own
+
+ * kafs.3: expose the krb5 functions
+
+ * common.c (kafs_settoken_rxkad): move all content kerberos
+ version from kafs_settoken to kafs_settoken_rxkad
+ (_kafs_fixup_viceid): move the fixup the timestamp to make client
+ happy code here.
+ (_kafs_v4_to_kt): move all the kerberos 4 dependant parts from
+ kafs_settoken here.
+ (*): adapt to kafs_token
+
+ * afskrb5.c (kafs_settoken5): new function, inserts a krb5_creds
+ into kernel
+ (v5_to_kt): new function, stores a krb5_creds in struct kafs_token
+ (get_cred): add a appdefault boolean ("libkafs", realm, "afs-use-524")
+ that can used to toggle if there should v5 token should be used
+ directly or converted via 524 first.
+
+ * afskrb.c: move kafs_settoken here, use struct kafs_token
+
+ * kafs_locl.h: include krb5-v4compat.h if needed, define an
+ internal structure struct kafs_token that carries around for rxkad
+ data that is independant of kerberos version
+
+2003-02-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * dlfcn.h: s/intialize/initialize, from
+ <jmc@prioris.mini.pw.edu.pl>
+
+2003-02-08 Assar Westerlund <assar@kth.se>
+
+ * afssysdefs.h: fix FreeBSD section
+
+2003-02-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * afssysdefs.h: use syscall 208 on openbsd (all version) use
+ syscall 339 on freebsd 5.0 and later, use 210 on 4.x and earlier
+
+2002-08-28 Johan Danielsson <joda@pdc.kth.se>
+
+ * kafs.3: move around sections (from NetBSD)
+
+2002-05-31 Assar Westerlund <assar@pdc.kth.se>
+
+ * common.c: remove the trial of afs@REALM for cell != realm, it
+ tries to use the wrong key for foreign cells
+
+2002-05-20 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: version number
+
+2002-04-18 Johan Danielsson <joda@pdc.kth.se>
+
+ * common.c (find_cells): make file parameter const
+
+2001-11-01 Assar Westerlund <assar@sics.se>
+
+ * add strsep, and bump version to 3:3:3
+
+2001-10-27 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkafs_la_LDFLAGS): set version to 3:2:3
+
+2001-10-24 Assar Westerlund <assar@sics.se>
+
+ * afskrb.c (afslog_uid_int): handle krb_get_tf_fullname that
+ cannot take NULLs
+ (such as the MIT one)
+
+2001-10-22 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (ROKEN_SRCS): add strlcpy.c
+
+2001-10-09 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (ROKEN_SRCS): add strtok_r.c
+ * roken_rename.h (dns_srv_order): rename correctly
+ (strtok_r): add renaming
+
+2001-09-10 Assar Westerlund <assar@sics.se>
+
+ * kafs.h, common.c: look for configuration files in /etc/arla (the
+ location in debian's arla package)
+
+2001-08-26 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: handle both krb5 and krb4 cases
+
+2001-07-19 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkafs_la_LDFLAGS): set version to 3:0:3
+
+2001-07-12 Assar Westerlund <assar@sics.se>
+
+ * common.c: look in /etc/openafs for debian openafs
+ * kafs.h: add paths for openafs debian (/etc/openafs)
+
+ * Makefile.am: add required library dependencies
+
+2001-07-03 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkafs_la_LDFLAGS): set versoin to 2:4:2
+
+2001-06-19 Assar Westerlund <assar@sics.se>
+
+ * common.c (_kafs_realm_of_cell): changed to first try exact match
+ in CellServDB, then exact match in DNS, and finally in-exact match
+ in CellServDB
+
+2001-05-18 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: only build resolve.c if doing renaming
+
+2001-02-12 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am, roken_rename.h: add rename of dns functions
+
+2000-12-11 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkafs_la_LDFLAGS): set version to 2:3:2
+
+2000-11-17 Assar Westerlund <assar@sics.se>
+
+ * afssysdefs.h: solaris 8 apperently uses 65
+
+2000-09-19 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkafs_la_LDFLAGS): bump version to 2:2:2
+
+2000-09-12 Johan Danielsson <joda@pdc.kth.se>
+
+ * dlfcn.c: correct arguments to some snprintf:s
+
+2000-07-25 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: bump version to 2:1:2
+
+2000-04-03 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 2:0:2
+
+2000-03-20 Assar Westerlund <assar@sics.se>
+
+ * afssysdefs.h: make versions later than 5.7 of solaris also use
+ 73
+
+2000-03-16 Assar Westerlund <assar@sics.se>
+
+ * afskrb.c (afslog_uid_int): use krb_get_tf_fullname instead of
+ krb_get_default_principal
+
+2000-03-15 Assar Westerlund <assar@sics.se>
+
+ * afssys.c (map_syscall_name_to_number): ignore # at
+ beginning-of-line
+
+2000-03-13 Assar Westerlund <assar@sics.se>
+
+ * afssysdefs.h: add 230 for MacOS X per information from
+ <warner.c@apple.com>
+
+1999-12-06 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 1:2:1
+
+1999-11-22 Assar Westerlund <assar@sics.se>
+
+ * afskrb5.c (afslog_uid_int): handle d->realm == NULL
+
+1999-11-17 Assar Westerlund <assar@sics.se>
+
+ * afskrb5.c (afslog_uid_int): don't look at the local realm at
+ all. just use the realm from the ticket file.
+
+1999-10-20 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 1:1:1
+
+ * afskrb5.c (get_cred): always request a DES key
+
+Mon Oct 18 17:40:21 1999 Bjoern Groenvall <bg@mummel.sics.se>
+
+ * common.c (find_cells): Trim trailing whitespace from
+ cellname. Lines starting with # are regarded as comments.
+
+Fri Oct 8 18:17:22 1999 Bjoern Groenvall <bg@mummel.sics.se>
+
+ * afskrb.c, common.c : Change code to make a clear distinction
+ between hinted realm and ticket realm.
+
+ * kafs_locl.h: Added argument realm_hint.
+
+ * common.c (_kafs_get_cred): Change code to acquire the ``best''
+ possible ticket. Use cross-cell authentication only as method of
+ last resort.
+
+ * afskrb.c (afslog_uid_int): Add realm_hint argument and extract
+ realm from ticket file.
+
+ * afskrb5.c (afslog_uid_int): Added argument realm_hint.
+
+1999-10-03 Assar Westerlund <assar@sics.se>
+
+ * afskrb5.c (get_cred): update to new krb524_convert_creds_kdc
+
+1999-08-12 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: ignore the comlicated aix construct if !krb4
+
+1999-07-26 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 1:0:1
+
+1999-07-22 Assar Westerlund <assar@sics.se>
+
+ * afssysdefs.h: define AFS_SYSCALL to 73 for Solaris 2.7
+
+1999-07-07 Assar Westerlund <assar@sics.se>
+
+ * afskrb5.c (krb5_realm_of_cell): new function
+
+ * afskrb.c (krb_realm_of_cell): new function
+ (afslog_uid_int): call krb_get_lrealm correctly
+
+1999-06-15 Assar Westerlund <assar@sics.se>
+
+ * common.c (realm_of_cell): rename to _kafs_realm_of_cell and
+ un-staticize
+
+Fri Mar 19 14:52:29 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: add version-info
+
+Thu Mar 18 11:24:02 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: include Makefile.am.common
+
+Sat Feb 27 19:46:21 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: remove EXTRA_DATA (as of autoconf 2.13/automake
+ 1.4)
+
+Thu Feb 11 22:57:37 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: set AIX_SRC also if !AIX
+
+Tue Dec 1 14:45:15 1998 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: fix AIX linkage
+
+Sun Nov 22 10:40:44 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (WFLAGS): set
+
+Sat Nov 21 16:55:19 1998 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * afskrb5.c: add homedir support
+
+Sun Sep 6 20:16:27 1998 Assar Westerlund <assar@sics.se>
+
+ * add new functionality for specifying the homedir to krb_afslog
+ et al
+
+Thu Jul 16 01:27:19 1998 Assar Westerlund <assar@sics.se>
+
+ * afssys.c: reorganize order of definitions.
+ (try_one, try_two): conditionalize
+
+Thu Jul 9 18:31:52 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * common.c (realm_of_cell): make the dns fallback work
+
+Wed Jul 8 01:39:44 1998 Assar Westerlund <assar@sics.se>
+
+ * afssys.c (map_syscall_name_to_number): new function for finding
+ the number of a syscall given the name on solaris
+ (k_hasafs): try using map_syscall_name_to_number
+
+Tue Jun 30 17:19:00 1998 Assar Westerlund <assar@sics.se>
+
+ * afssys.c: rewrite and add support for environment variable
+ AFS_SYSCALL
+
+ * Makefile.in (distclean): don't remove roken_rename.h
+
+Fri May 29 19:03:20 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (roken_rename.h): remove dependency
+
+Mon May 25 05:25:54 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (clean): try to remove shared library debris
+
+Sun Apr 19 09:58:40 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in: add symlink magic for linux
+
+Sat Apr 4 15:08:48 1998 Assar Westerlund <assar@sics.se>
+
+ * kafs.h: add arla paths
+
+ * common.c (_kafs_afslog_all_local_cells): Try _PATH_ARLA_*
+ (_realm_of_cell): Try _PATH_ARLA_CELLSERVDB
+
+Thu Feb 19 14:50:22 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * common.c: Don't store expired tokens (this broke when using
+ pag-less rsh-sessions, and `non-standard' ticket files).
+
+Thu Feb 12 11:20:15 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * Makefile.in: Install/uninstall one library at a time.
+
+Thu Feb 12 05:38:58 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (install): one library at a time.
+
+Mon Feb 9 23:40:32 1998 Assar Westerlund <assar@sics.se>
+
+ * common.c (find_cells): ignore empty lines
+
+Tue Jan 6 04:25:58 1998 Assar Westerlund <assar@sics.se>
+
+ * afssysdefs.h (AFS_SYSCALL): add FreeBSD
+
+Fri Jan 2 17:08:24 1998 Assar Westerlund <assar@sics.se>
+
+ * kafs.h: new VICEIOCTL's. From <rb@stacken.kth.se>
+
+ * afssysdefs.h: Add OpenBSD
diff --git a/third_party/heimdal/lib/kafs/Makefile.am b/third_party/heimdal/lib/kafs/Makefile.am
new file mode 100644
index 0000000..50d4878
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/Makefile.am
@@ -0,0 +1,96 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+WFLAGS += $(WFLAGS_ENUM_CONV)
+
+AM_CPPFLAGS += $(AFS_EXTRA_DEFS) $(ROKEN_RENAME)
+
+if KRB5
+DEPLIB_krb5 = ../krb5/libkrb5.la $(LIB_hcrypto)
+krb5_am_workaround = -I$(top_srcdir)/lib/krb5
+else
+DEPLIB_krb5 =
+krb5_am_workaround =
+endif # KRB5
+AM_CPPFLAGS += $(krb5_am_workaround)
+
+
+if AIX
+AFSL_EXP = $(srcdir)/afsl.exp
+
+if AIX4
+AFS_EXTRA_LD = -bnoentry
+else
+AFS_EXTRA_LD = -e _nostart
+endif
+
+if AIX_DYNAMIC_AFS
+AIX_SRC =
+AFS_EXTRA_LIBS = afslib.so
+AFS_EXTRA_DEFS =
+else
+AIX_SRC = afslib.c
+AFS_EXTRA_LIBS =
+AFS_EXTRA_DEFS = -DSTATIC_AFS
+endif
+
+else
+AFSL_EXP =
+AIX_SRC =
+endif # AIX
+
+libkafs_la_LIBADD = $(DEPLIB_krb5) $(LIBADD_roken)
+
+lib_LTLIBRARIES = libkafs.la
+libkafs_la_LDFLAGS = -version-info 5:1:5
+foodir = $(libdir)
+foo_DATA = $(AFS_EXTRA_LIBS)
+# EXTRA_DATA = afslib.so
+
+CLEANFILES= $(AFS_EXTRA_LIBS) $(ROKEN_SRCS)
+
+include_HEADERS = kafs.h
+
+if KRB5
+afskrb5_c =
+endif
+
+if do_roken_rename
+ROKEN_SRCS = resolve.c strtok_r.c strlcpy.c strsep.c
+endif
+
+dist_libkafs_la_SOURCES = \
+ afssys.c \
+ afskrb5.c \
+ rxkad_kdf.c \
+ common.c \
+ $(AIX_SRC) \
+ kafs_locl.h \
+ afssysdefs.h \
+ roken_rename.h
+
+nodist_libkafs_la_SOURCES = $(ROKEN_SRCS)
+
+EXTRA_libkafs_la_SOURCES = afskrb5.c afslib.c
+
+EXTRA_DIST = NTMakefile afsl.exp afslib.exp $(man_MANS)
+
+man_MANS = kafs.3
+
+# AIX: this almost works with gcc, but somehow it fails to use the
+# correct ld, use ld instead
+afslib.so: afslib.o
+ ld -o $@ -bM:SRE -bI:$(srcdir)/afsl.exp -bE:$(srcdir)/afslib.exp $(AFS_EXTRA_LD) afslib.o -lc
+
+resolve.c:
+ $(LN_S) $(srcdir)/../roken/resolve.c .
+
+strtok_r.c:
+ $(LN_S) $(srcdir)/../roken/strtok_r.c .
+
+strlcpy.c:
+ $(LN_S) $(srcdir)/../roken/strlcpy.c .
+
+strsep.c:
+ $(LN_S) $(srcdir)/../roken/strsep.c .
diff --git a/third_party/heimdal/lib/kafs/NTMakefile b/third_party/heimdal/lib/kafs/NTMakefile
new file mode 100644
index 0000000..4cff342
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/NTMakefile
@@ -0,0 +1,35 @@
+########################################################################
+#
+# Copyright (c) 2009, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\kafs
+
+!include ../../windows/NTMakefile.w32
+
diff --git a/third_party/heimdal/lib/kafs/afskrb5.c b/third_party/heimdal/lib/kafs/afskrb5.c
new file mode 100644
index 0000000..0077016
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/afskrb5.c
@@ -0,0 +1,353 @@
+/*
+ * Copyright (c) 1995-2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kafs_locl.h"
+
+struct krb5_kafs_data {
+ krb5_context context;
+ krb5_ccache id;
+ krb5_const_realm realm;
+};
+
+enum {
+ KAFS_RXKAD_2B_KVNO = 213,
+ KAFS_RXKAD_K5_KVNO = 256
+};
+
+static int
+v5_to_kt(krb5_creds *cred, uid_t uid, struct kafs_token *kt, int local524)
+{
+ int kvno, ret;
+
+ kt->ticket = NULL;
+
+ if (local524) {
+ Ticket t;
+ unsigned char *buf;
+ size_t buf_len;
+ size_t len;
+
+ kvno = KAFS_RXKAD_2B_KVNO;
+
+ ret = decode_Ticket(cred->ticket.data, cred->ticket.length, &t, &len);
+ if (ret)
+ return ret;
+ if (t.tkt_vno != 5)
+ return -1;
+
+ ASN1_MALLOC_ENCODE(EncryptedData, buf, buf_len, &t.enc_part,
+ &len, ret);
+ free_Ticket(&t);
+ if (ret)
+ return ret;
+ if(buf_len != len) {
+ free(buf);
+ return KRB5KRB_ERR_GENERIC;
+ }
+
+ kt->ticket = buf;
+ kt->ticket_len = buf_len;
+
+ } else {
+ kvno = KAFS_RXKAD_K5_KVNO;
+ kt->ticket = malloc(cred->ticket.length);
+ if (kt->ticket == NULL)
+ return ENOMEM;
+ kt->ticket_len = cred->ticket.length;
+ memcpy(kt->ticket, cred->ticket.data, kt->ticket_len);
+ }
+
+
+ /*
+ * Build a struct ClearToken
+ */
+
+ ret = _kafs_derive_des_key(cred->session.keytype,
+ cred->session.keyvalue.data,
+ cred->session.keyvalue.length,
+ kt->ct.HandShakeKey);
+ if (ret) {
+ free(kt->ticket);
+ kt->ticket = NULL;
+ return ret;
+ }
+ kt->ct.AuthHandle = kvno;
+ kt->ct.ViceId = uid;
+ kt->ct.BeginTimestamp = cred->times.starttime;
+ kt->ct.EndTimestamp = cred->times.endtime;
+
+ _kafs_fixup_viceid(&kt->ct, uid);
+
+ return 0;
+}
+
+static krb5_error_code
+v5_convert(krb5_context context, krb5_ccache id,
+ krb5_creds *cred, uid_t uid,
+ const char *cell,
+ struct kafs_token *kt)
+{
+ krb5_error_code ret;
+ char *c, *val;
+
+ c = strdup(cell);
+ if (c == NULL)
+ return ENOMEM;
+ _kafs_foldup(c, c);
+ krb5_appdefault_string (context, "libkafs",
+ c,
+ "afs-use-524", "2b", &val);
+ free(c);
+
+ if (strcasecmp(val, "local") == 0 ||
+ strcasecmp(val, "2b") == 0)
+ ret = v5_to_kt(cred, uid, kt, 1);
+ else
+ ret = v5_to_kt(cred, uid, kt, 0);
+
+ free(val);
+ return ret;
+}
+
+
+/*
+ *
+ */
+
+static int
+get_cred(struct kafs_data *data, const char *name, const char *inst,
+ const char *realm, uid_t uid, struct kafs_token *kt)
+{
+ krb5_error_code ret;
+ krb5_creds in_creds, *out_creds;
+ struct krb5_kafs_data *d = data->data;
+ int invalid;
+
+ memset(&in_creds, 0, sizeof(in_creds));
+
+ ret = krb5_make_principal(d->context, &in_creds.server,
+ realm, name, inst, NULL);
+ if(ret)
+ return ret;
+ ret = krb5_cc_get_principal(d->context, d->id, &in_creds.client);
+ if(ret){
+ krb5_free_principal(d->context, in_creds.server);
+ return ret;
+ }
+
+ /* check if des is disable, and in that case enable it for afs */
+ invalid = krb5_enctype_valid(d->context, ETYPE_DES_CBC_CRC);
+ if (invalid)
+ krb5_enctype_enable(d->context, ETYPE_DES_CBC_CRC);
+
+ ret = krb5_get_credentials(d->context, 0, d->id, &in_creds, &out_creds);
+
+ if (invalid)
+ krb5_enctype_disable(d->context, ETYPE_DES_CBC_CRC);
+
+ krb5_free_principal(d->context, in_creds.server);
+ krb5_free_principal(d->context, in_creds.client);
+ if(ret)
+ return ret;
+
+ ret = v5_convert(d->context, d->id, out_creds, uid,
+ (inst != NULL && inst[0] != '\0') ? inst : realm, kt);
+ krb5_free_creds(d->context, out_creds);
+
+ return ret;
+}
+
+static const char *
+get_error(struct kafs_data *data, int error)
+{
+ struct krb5_kafs_data *d = data->data;
+ return krb5_get_error_message(d->context, error);
+}
+
+static void
+free_error(struct kafs_data *data, const char *str)
+{
+ struct krb5_kafs_data *d = data->data;
+ krb5_free_error_message(d->context, str);
+}
+
+static krb5_error_code
+afslog_uid_int(struct kafs_data *data, const char *cell, const char *rh,
+ uid_t uid, const char *homedir)
+{
+ krb5_error_code ret;
+ struct kafs_token kt;
+ krb5_principal princ;
+ const char *trealm; /* ticket realm */
+ struct krb5_kafs_data *d = data->data;
+
+ if (cell == 0 || cell[0] == 0)
+ return _kafs_afslog_all_local_cells (data, uid, homedir);
+
+ ret = krb5_cc_get_principal (d->context, d->id, &princ);
+ if (ret)
+ return ret;
+
+ trealm = krb5_principal_get_realm (d->context, princ);
+
+ kt.ticket = NULL;
+ ret = _kafs_get_cred(data, cell, d->realm, trealm, uid, &kt);
+ krb5_free_principal (d->context, princ);
+
+ if(ret == 0) {
+ ret = kafs_settoken_rxkad(cell, &kt.ct, kt.ticket, kt.ticket_len);
+ free(kt.ticket);
+ }
+ return ret;
+}
+
+static char *
+get_realm(struct kafs_data *data, const char *host)
+{
+ struct krb5_kafs_data *d = data->data;
+ krb5_realm *realms;
+ char *r;
+ if(krb5_get_host_realm(d->context, host, &realms))
+ return NULL;
+ r = strdup(realms[0]);
+ krb5_free_host_realm(d->context, realms);
+ return r;
+}
+
+krb5_error_code
+krb5_afslog_uid_home(krb5_context context,
+ krb5_ccache id,
+ const char *cell,
+ krb5_const_realm realm,
+ uid_t uid,
+ const char *homedir)
+{
+ struct kafs_data kd;
+ struct krb5_kafs_data d;
+ krb5_error_code ret;
+
+ kd.name = "krb5";
+ kd.afslog_uid = afslog_uid_int;
+ kd.get_cred = get_cred;
+ kd.get_realm = get_realm;
+ kd.get_error = get_error;
+ kd.free_error = free_error;
+ kd.data = &d;
+ if (context == NULL) {
+ ret = krb5_init_context(&d.context);
+ if (ret)
+ return ret;
+ } else
+ d.context = context;
+ if (id == NULL) {
+ ret = krb5_cc_default(d.context, &d.id);
+ if (ret)
+ goto out;
+ } else
+ d.id = id;
+ d.realm = realm;
+ ret = afslog_uid_int(&kd, cell, 0, uid, homedir);
+ if (id == NULL)
+ krb5_cc_close(context, d.id);
+ out:
+ if (context == NULL)
+ krb5_free_context(d.context);
+ return ret;
+}
+
+krb5_error_code
+krb5_afslog_uid(krb5_context context,
+ krb5_ccache id,
+ const char *cell,
+ krb5_const_realm realm,
+ uid_t uid)
+{
+ return krb5_afslog_uid_home (context, id, cell, realm, uid, NULL);
+}
+
+krb5_error_code
+krb5_afslog(krb5_context context,
+ krb5_ccache id,
+ const char *cell,
+ krb5_const_realm realm)
+{
+ return krb5_afslog_uid (context, id, cell, realm, getuid());
+}
+
+krb5_error_code
+krb5_afslog_home(krb5_context context,
+ krb5_ccache id,
+ const char *cell,
+ krb5_const_realm realm,
+ const char *homedir)
+{
+ return krb5_afslog_uid_home (context, id, cell, realm, getuid(), homedir);
+}
+
+/*
+ *
+ */
+
+krb5_error_code
+krb5_realm_of_cell(const char *cell, char **realm)
+{
+ struct kafs_data kd;
+
+ kd.name = "krb5";
+ kd.get_realm = get_realm;
+ kd.get_error = get_error;
+ kd.free_error = free_error;
+ return _kafs_realm_of_cell(&kd, cell, realm);
+}
+
+/*
+ *
+ */
+
+int
+kafs_settoken5(krb5_context context, const char *cell, uid_t uid,
+ krb5_creds *cred)
+{
+ struct kafs_token kt;
+ int ret;
+
+ ret = v5_convert(context, NULL, cred, uid, cell, &kt);
+ if (ret)
+ return ret;
+
+ ret = kafs_settoken_rxkad(cell, &kt.ct, kt.ticket, kt.ticket_len);
+
+ free(kt.ticket);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kafs/afsl.exp b/third_party/heimdal/lib/kafs/afsl.exp
new file mode 100644
index 0000000..4d2b00e
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/afsl.exp
@@ -0,0 +1,6 @@
+#!/unix
+
+* This mumbo jumbo creates entry points to syscalls in _AIX
+
+lpioctl syscall
+lsetpag syscall
diff --git a/third_party/heimdal/lib/kafs/afslib.c b/third_party/heimdal/lib/kafs/afslib.c
new file mode 100644
index 0000000..f2ef848
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/afslib.c
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * This file is only used with AIX
+ */
+
+#include "kafs_locl.h"
+
+int
+aix_pioctl(char *a_path,
+ int o_opcode,
+ struct ViceIoctl *a_paramsP,
+ int a_followSymlinks)
+{
+ return lpioctl(a_path, o_opcode, a_paramsP, a_followSymlinks);
+}
+
+int
+aix_setpag(void)
+{
+ return lsetpag();
+}
diff --git a/third_party/heimdal/lib/kafs/afslib.exp b/third_party/heimdal/lib/kafs/afslib.exp
new file mode 100644
index 0000000..f288717
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/afslib.exp
@@ -0,0 +1,3 @@
+#!
+aix_pioctl
+aix_setpag
diff --git a/third_party/heimdal/lib/kafs/afssys.c b/third_party/heimdal/lib/kafs/afssys.c
new file mode 100644
index 0000000..b400626
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/afssys.c
@@ -0,0 +1,630 @@
+/*
+ * Copyright (c) 1995 - 2000, 2002, 2004, 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kafs_locl.h"
+
+struct procdata {
+ unsigned long param4;
+ unsigned long param3;
+ unsigned long param2;
+ unsigned long param1;
+ unsigned long syscall;
+};
+#ifdef __GNU__
+#define _IOT_procdata _IOT(_IOTS(long), 5, 0, 0, 0, 0)
+#define VIOC_SYSCALL_PROC _IOW('C', 1, struct procdata)
+#else
+#define VIOC_SYSCALL_PROC _IOW('C', 1, void *)
+#endif
+
+struct devdata {
+ unsigned long syscall;
+ unsigned long param1;
+ unsigned long param2;
+ unsigned long param3;
+ unsigned long param4;
+ unsigned long param5;
+ unsigned long param6;
+ unsigned long retval;
+};
+#ifdef __GNU__
+#define _IOT_devdata _IOT(_IOTS(long), 8, 0, 0, 0, 0)
+#endif
+#ifdef _IOWR
+#define VIOC_SYSCALL_DEV _IOWR('C', 2, struct devdata)
+#define VIOC_SYSCALL_DEV_OPENAFS _IOWR('C', 1, struct devdata)
+#endif
+
+#ifdef _IOW
+#ifdef _ILP32
+struct sundevdata {
+ uint32_t param6;
+ uint32_t param5;
+ uint32_t param4;
+ uint32_t param3;
+ uint32_t param2;
+ uint32_t param1;
+ uint32_t syscall;
+};
+#define VIOC_SUN_SYSCALL_DEV _IOW('C', 2, struct sundevdata)
+#else
+struct sundevdata {
+ uint64_t param6;
+ uint64_t param5;
+ uint64_t param4;
+ uint64_t param3;
+ uint64_t param2;
+ uint64_t param1;
+ uint64_t syscall;
+};
+#define VIOC_SUN_SYSCALL_DEV _IOW('C', 1, struct sundevdata)
+#endif
+#endif /* _IOW */
+
+
+int _kafs_debug; /* this should be done in a better way */
+
+#define UNKNOWN_ENTRY_POINT (-1)
+#define NO_ENTRY_POINT 0
+#define SINGLE_ENTRY_POINT 1
+#define MULTIPLE_ENTRY_POINT 2
+#define SINGLE_ENTRY_POINT2 3
+#define SINGLE_ENTRY_POINT3 4
+#define LINUX_PROC_POINT 5
+#define AIX_ENTRY_POINTS 6
+#define MACOS_DEV_POINT 7
+#define SUN_PROC_POINT 8
+
+static int afs_entry_point = UNKNOWN_ENTRY_POINT;
+#if defined(AFS_SYSCALL) || defined(AFS_SYSCALL2) || defined(AFS_SYSCALL3) || defined(AFS_PIOCTL)
+static int afs_syscalls[2];
+#endif
+static char *afs_ioctlpath;
+static unsigned long afs_ioctlnum;
+
+/* Magic to get AIX syscalls to work */
+#ifdef _AIX
+
+static int (*Pioctl)(char*, int, struct ViceIoctl*, int);
+static int (*Setpag)(void);
+
+#include "dlfcn.h"
+
+/*
+ *
+ */
+
+static int
+try_aix(void)
+{
+#ifdef STATIC_AFS_SYSCALLS
+ Pioctl = aix_pioctl;
+ Setpag = aix_setpag;
+#else
+ void *ptr;
+ char path[MaxPathLen], *p;
+ /*
+ * If we are root or running setuid don't trust AFSLIBPATH!
+ */
+ if (getuid() != 0 && (p = secure_getenv("AFSLIBPATH")) != NULL)
+ strlcpy(path, p, sizeof(path));
+ else
+ snprintf(path, sizeof(path), "%s/afslib.so", LIBDIR);
+
+ ptr = dlopen(path, RTLD_NOW);
+ if(ptr == NULL) {
+ if(_kafs_debug) {
+ if(errno == ENOEXEC && (p = dlerror()) != NULL)
+ fprintf(stderr, "dlopen(%s): %s\n", path, p);
+ else if (errno != ENOENT)
+ fprintf(stderr, "dlopen(%s): %s\n", path, strerror(errno));
+ }
+ return 1;
+ }
+ Setpag = (int (*)(void))dlsym(ptr, "aix_setpag");
+ Pioctl = (int (*)(char*, int,
+ struct ViceIoctl*, int))dlsym(ptr, "aix_pioctl");
+#endif
+ afs_entry_point = AIX_ENTRY_POINTS;
+ return 0;
+}
+#endif /* _AIX */
+
+/*
+ * This probably only works under Solaris and could get confused if
+ * there's a /etc/name_to_sysnum file.
+ */
+
+#if defined(AFS_SYSCALL) || defined(AFS_SYSCALL2) || defined(AFS_SYSCALL3)
+
+#define _PATH_ETC_NAME_TO_SYSNUM "/etc/name_to_sysnum"
+
+static int
+map_syscall_name_to_number (const char *str, int *res)
+{
+ FILE *f;
+ char buf[256];
+ size_t str_len = strlen (str);
+
+ f = fopen (_PATH_ETC_NAME_TO_SYSNUM, "r");
+ if (f == NULL)
+ return -1;
+ while (fgets (buf, sizeof(buf), f) != NULL) {
+ if (buf[0] == '#')
+ continue;
+
+ if (strncmp (str, buf, str_len) == 0) {
+ char *begptr = buf + str_len;
+ char *endptr;
+ long val = strtol (begptr, &endptr, 0);
+
+ if (val != 0 && endptr != begptr) {
+ fclose (f);
+ *res = val;
+ return 0;
+ }
+ }
+ }
+ fclose (f);
+ return -1;
+}
+#endif
+
+static int
+try_ioctlpath(const char *path, unsigned long ioctlnum, int entrypoint)
+{
+ int fd, ret, saved_errno;
+
+ fd = open(path, O_RDWR);
+ if (fd < 0)
+ return 1;
+ switch (entrypoint) {
+ case LINUX_PROC_POINT: {
+ struct procdata data = { 0, 0, 0, 0, AFSCALL_PIOCTL };
+ data.param2 = (unsigned long)VIOCGETTOK;
+ ret = ioctl(fd, ioctlnum, &data);
+ break;
+ }
+ case MACOS_DEV_POINT: {
+ struct devdata data = { AFSCALL_PIOCTL, 0, 0, 0, 0, 0, 0, 0 };
+ data.param2 = (unsigned long)VIOCGETTOK;
+ ret = ioctl(fd, ioctlnum, &data);
+ break;
+ }
+ case SUN_PROC_POINT: {
+ struct sundevdata data = { 0, 0, 0, 0, 0, 0, AFSCALL_PIOCTL };
+ data.param2 = (unsigned long)VIOCGETTOK;
+ ret = ioctl(fd, ioctlnum, &data);
+ break;
+ }
+ default:
+ abort();
+ }
+ saved_errno = errno;
+ close(fd);
+ /*
+ * Be quite liberal in what error are ok, the first is the one
+ * that should trigger given that params is NULL.
+ */
+ if (ret &&
+ (saved_errno != EFAULT &&
+ saved_errno != EDOM &&
+ saved_errno != ENOTCONN))
+ return 1;
+ afs_ioctlnum = ioctlnum;
+ afs_ioctlpath = strdup(path);
+ if (afs_ioctlpath == NULL)
+ return 1;
+ afs_entry_point = entrypoint;
+ return 0;
+}
+
+static int
+do_ioctl(void *data)
+{
+ int fd, ret, saved_errno;
+ fd = open(afs_ioctlpath, O_RDWR);
+ if (fd < 0) {
+ errno = EINVAL;
+ return -1;
+ }
+ ret = ioctl(fd, afs_ioctlnum, data);
+ saved_errno = errno;
+ close(fd);
+ errno = saved_errno;
+ return ret;
+}
+
+int
+k_pioctl(char *a_path,
+ int o_opcode,
+ struct ViceIoctl *a_paramsP,
+ int a_followSymlinks)
+{
+#ifndef NO_AFS
+ switch(afs_entry_point){
+#if defined(AFS_SYSCALL) || defined(AFS_SYSCALL2) || defined(AFS_SYSCALL3)
+ case SINGLE_ENTRY_POINT:
+ case SINGLE_ENTRY_POINT2:
+ case SINGLE_ENTRY_POINT3:
+ return syscall(afs_syscalls[0], AFSCALL_PIOCTL,
+ a_path, o_opcode, a_paramsP, a_followSymlinks);
+#endif
+#if defined(AFS_PIOCTL)
+ case MULTIPLE_ENTRY_POINT:
+ return syscall(afs_syscalls[0],
+ a_path, o_opcode, a_paramsP, a_followSymlinks);
+#endif
+ case LINUX_PROC_POINT: {
+ struct procdata data = { 0, 0, 0, 0, AFSCALL_PIOCTL };
+ data.param1 = (unsigned long)a_path;
+ data.param2 = (unsigned long)o_opcode;
+ data.param3 = (unsigned long)a_paramsP;
+ data.param4 = (unsigned long)a_followSymlinks;
+ return do_ioctl(&data);
+ }
+ case MACOS_DEV_POINT: {
+ struct devdata data = { AFSCALL_PIOCTL, 0, 0, 0, 0, 0, 0, 0 };
+ int ret;
+
+ data.param1 = (unsigned long)a_path;
+ data.param2 = (unsigned long)o_opcode;
+ data.param3 = (unsigned long)a_paramsP;
+ data.param4 = (unsigned long)a_followSymlinks;
+
+ ret = do_ioctl(&data);
+ if (ret)
+ return ret;
+
+ return data.retval;
+ }
+ case SUN_PROC_POINT: {
+ struct sundevdata data = { 0, 0, 0, 0, 0, 0, AFSCALL_PIOCTL };
+ data.param1 = (unsigned long)a_path;
+ data.param2 = (unsigned long)o_opcode;
+ data.param3 = (unsigned long)a_paramsP;
+ data.param4 = (unsigned long)a_followSymlinks;
+ return do_ioctl(&data);
+ }
+#ifdef _AIX
+ case AIX_ENTRY_POINTS:
+ return Pioctl(a_path, o_opcode, a_paramsP, a_followSymlinks);
+#endif
+ }
+ errno = ENOSYS;
+#ifdef SIGSYS
+ kill(getpid(), SIGSYS); /* You lose! */
+#endif
+#endif /* NO_AFS */
+ return -1;
+}
+
+int
+k_afs_cell_of_file(const char *path, char *cell, int len)
+{
+ struct ViceIoctl parms;
+ parms.in = NULL;
+ parms.in_size = 0;
+ parms.out = cell;
+ parms.out_size = len;
+ return k_pioctl(rk_UNCONST(path), VIOC_FILE_CELL_NAME, &parms, 1);
+}
+
+int
+k_unlog(void)
+{
+ struct ViceIoctl parms;
+ memset(&parms, 0, sizeof(parms));
+ return k_pioctl(0, VIOCUNLOG, &parms, 0);
+}
+
+int
+k_setpag(void)
+{
+#ifndef NO_AFS
+ switch(afs_entry_point){
+#if defined(AFS_SYSCALL) || defined(AFS_SYSCALL2) || defined(AFS_SYSCALL3)
+ case SINGLE_ENTRY_POINT:
+ case SINGLE_ENTRY_POINT2:
+ case SINGLE_ENTRY_POINT3:
+ return syscall(afs_syscalls[0], AFSCALL_SETPAG);
+#endif
+#if defined(AFS_PIOCTL)
+ case MULTIPLE_ENTRY_POINT:
+ return syscall(afs_syscalls[1]);
+#endif
+ case LINUX_PROC_POINT: {
+ struct procdata data = { 0, 0, 0, 0, AFSCALL_SETPAG };
+ return do_ioctl(&data);
+ }
+ case MACOS_DEV_POINT: {
+ struct devdata data = { AFSCALL_SETPAG, 0, 0, 0, 0, 0, 0, 0 };
+ int ret = do_ioctl(&data);
+ if (ret)
+ return ret;
+ return data.retval;
+ }
+ case SUN_PROC_POINT: {
+ struct sundevdata data = { 0, 0, 0, 0, 0, 0, AFSCALL_SETPAG };
+ return do_ioctl(&data);
+ }
+#ifdef _AIX
+ case AIX_ENTRY_POINTS:
+ return Setpag();
+#endif
+ }
+
+ errno = ENOSYS;
+#ifdef SIGSYS
+ kill(getpid(), SIGSYS); /* You lose! */
+#endif
+#endif /* NO_AFS */
+ return -1;
+}
+
+static jmp_buf catch_SIGSYS;
+
+#ifdef SIGSYS
+
+static RETSIGTYPE
+SIGSYS_handler(int sig)
+{
+ errno = 0;
+ signal(SIGSYS, SIGSYS_handler); /* Need to reinstall handler on SYSV */
+ longjmp(catch_SIGSYS, 1);
+}
+
+#endif
+
+/*
+ * Try to see if `syscall' is a pioctl. Return 0 iff succesful.
+ */
+
+#if defined(AFS_SYSCALL) || defined(AFS_SYSCALL2) || defined(AFS_SYSCALL3)
+static int
+try_one (int syscall_num)
+{
+ struct ViceIoctl parms;
+ memset(&parms, 0, sizeof(parms));
+
+ if (setjmp(catch_SIGSYS) == 0) {
+ syscall(syscall_num, AFSCALL_PIOCTL,
+ 0, VIOCSETTOK, &parms, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
+ if (errno == EINVAL) {
+ afs_entry_point = SINGLE_ENTRY_POINT;
+ afs_syscalls[0] = syscall_num;
+ return 0;
+ }
+ }
+ return 1;
+}
+#endif
+
+/*
+ * Try to see if `syscall_pioctl' is a pioctl syscall. Return 0 iff
+ * succesful.
+ *
+ */
+
+#ifdef AFS_PIOCTL
+static int
+try_two (int syscall_pioctl, int syscall_setpag)
+{
+ struct ViceIoctl parms;
+ memset(&parms, 0, sizeof(parms));
+
+ if (setjmp(catch_SIGSYS) == 0) {
+ syscall(syscall_pioctl,
+ 0, VIOCSETTOK, &parms, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
+ if (errno == EINVAL) {
+ afs_entry_point = MULTIPLE_ENTRY_POINT;
+ afs_syscalls[0] = syscall_pioctl;
+ afs_syscalls[1] = syscall_setpag;
+ return 0;
+ }
+ }
+ return 1;
+}
+#endif
+
+int
+k_hasafs(void)
+{
+#if !defined(NO_AFS) && defined(SIGSYS)
+ RETSIGTYPE (*saved_func)(int);
+#endif
+ int saved_errno, ret;
+ char *env = NULL;
+
+ env = secure_getenv("AFS_SYSCALL");
+
+ /*
+ * Already checked presence of AFS syscalls?
+ */
+ if (afs_entry_point != UNKNOWN_ENTRY_POINT)
+ return afs_entry_point != NO_ENTRY_POINT;
+
+ /*
+ * Probe kernel for AFS specific syscalls,
+ * they (currently) come in two flavors.
+ * If the syscall is absent we recive a SIGSYS.
+ */
+ afs_entry_point = NO_ENTRY_POINT;
+
+ saved_errno = errno;
+#ifndef NO_AFS
+#ifdef SIGSYS
+ saved_func = signal(SIGSYS, SIGSYS_handler);
+#endif
+ if (env && strstr(env, "..") == NULL) {
+
+ if (strncmp("/proc/", env, 6) == 0) {
+ if (try_ioctlpath(env, VIOC_SYSCALL_PROC, LINUX_PROC_POINT) == 0)
+ goto done;
+ }
+ if (strncmp("/dev/", env, 5) == 0) {
+#ifdef VIOC_SYSCALL_DEV
+ if (try_ioctlpath(env, VIOC_SYSCALL_DEV, MACOS_DEV_POINT) == 0)
+ goto done;
+#endif
+#ifdef VIOC_SYSCALL_DEV_OPENAFS
+ if (try_ioctlpath(env,VIOC_SYSCALL_DEV_OPENAFS,MACOS_DEV_POINT) ==0)
+ goto done;
+#endif
+ }
+ }
+
+ ret = try_ioctlpath("/proc/fs/openafs/afs_ioctl",
+ VIOC_SYSCALL_PROC, LINUX_PROC_POINT);
+ if (ret == 0)
+ goto done;
+ ret = try_ioctlpath("/proc/fs/nnpfs/afs_ioctl",
+ VIOC_SYSCALL_PROC, LINUX_PROC_POINT);
+ if (ret == 0)
+ goto done;
+
+#ifdef VIOC_SYSCALL_DEV_OPENAFS
+ ret = try_ioctlpath("/dev/openafs_ioctl",
+ VIOC_SYSCALL_DEV_OPENAFS, MACOS_DEV_POINT);
+ if (ret == 0)
+ goto done;
+#endif
+#ifdef VIOC_SYSCALL_DEV
+ ret = try_ioctlpath("/dev/nnpfs_ioctl", VIOC_SYSCALL_DEV, MACOS_DEV_POINT);
+ if (ret == 0)
+ goto done;
+#endif
+#ifdef VIOC_SUN_SYSCALL_DEV
+ ret = try_ioctlpath("/dev/afs", VIOC_SUN_SYSCALL_DEV, SUN_PROC_POINT);
+ if (ret == 0)
+ goto done;
+#endif
+
+
+#if defined(AFS_SYSCALL) || defined(AFS_SYSCALL2) || defined(AFS_SYSCALL3)
+ {
+ int tmp;
+
+ if (env != NULL) {
+ if (sscanf (env, "%d", &tmp) == 1) {
+ if (try_one (tmp) == 0)
+ goto done;
+ } else {
+ char *end = NULL;
+ char *p;
+ char *s = strdup (env);
+
+ if (s != NULL) {
+ for (p = strtok_r (s, ",", &end);
+ p != NULL;
+ p = strtok_r (NULL, ",", &end)) {
+ if (map_syscall_name_to_number (p, &tmp) == 0)
+ if (try_one (tmp) == 0) {
+ free (s);
+ goto done;
+ }
+ }
+ free (s);
+ }
+ }
+ }
+ }
+#endif /* AFS_SYSCALL || AFS_SYSCALL2 || AFS_SYSCALL3 */
+
+#ifdef AFS_SYSCALL
+ if (try_one (AFS_SYSCALL) == 0)
+ goto done;
+#endif /* AFS_SYSCALL */
+
+#ifdef AFS_PIOCTL
+ {
+ int tmp[2];
+
+ if (env != NULL && sscanf (env, "%d%d", &tmp[0], &tmp[1]) == 2)
+ if (try_two (tmp[0], tmp[1]) == 2)
+ goto done;
+ }
+#endif /* AFS_PIOCTL */
+
+#ifdef AFS_PIOCTL
+ if (try_two (AFS_PIOCTL, AFS_SETPAG) == 0)
+ goto done;
+#endif /* AFS_PIOCTL */
+
+#ifdef AFS_SYSCALL2
+ if (try_one (AFS_SYSCALL2) == 0)
+ goto done;
+#endif /* AFS_SYSCALL2 */
+
+#ifdef AFS_SYSCALL3
+ if (try_one (AFS_SYSCALL3) == 0)
+ goto done;
+#endif /* AFS_SYSCALL3 */
+
+#ifdef _AIX
+#if 0
+ if (env != NULL) {
+ char *pos = NULL;
+ char *pioctl_name;
+ char *setpag_name;
+
+ pioctl_name = strtok_r (env, ", \t", &pos);
+ if (pioctl_name != NULL) {
+ setpag_name = strtok_r (NULL, ", \t", &pos);
+ if (setpag_name != NULL)
+ if (try_aix (pioctl_name, setpag_name) == 0)
+ goto done;
+ }
+ }
+#endif
+
+ if(try_aix() == 0)
+ goto done;
+#endif
+
+
+done:
+#ifdef SIGSYS
+ signal(SIGSYS, saved_func);
+#endif
+#endif /* NO_AFS */
+ errno = saved_errno;
+ return afs_entry_point != NO_ENTRY_POINT;
+}
+
+int
+k_hasafs_recheck(void)
+{
+ afs_entry_point = UNKNOWN_ENTRY_POINT;
+ return k_hasafs();
+}
diff --git a/third_party/heimdal/lib/kafs/afssysdefs.h b/third_party/heimdal/lib/kafs/afssysdefs.h
new file mode 100644
index 0000000..18734e3
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/afssysdefs.h
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 1995 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+/*
+ * This section is for machines using single entry point AFS syscalls!
+ * and/or
+ * This section is for machines using multiple entry point AFS syscalls!
+ *
+ * SunOS 4 is an example of single entry point and sgi of multiple
+ * entry point syscalls.
+ */
+
+#if SunOS == 40
+#define AFS_SYSCALL 31
+#endif
+
+#if SunOS >= 50 && SunOS < 57
+#define AFS_SYSCALL 105
+#endif
+
+#if SunOS == 57
+#define AFS_SYSCALL 73
+#endif
+
+#if SunOS >= 58
+#define AFS_SYSCALL 65
+#endif
+
+#if defined(__hpux)
+#define AFS_SYSCALL 50
+#define AFS_SYSCALL2 49
+#define AFS_SYSCALL3 48
+#endif
+
+#if defined(_AIX)
+/* _AIX is too weird */
+#endif
+
+#if defined(__sgi)
+#define AFS_PIOCTL (64+1000)
+#define AFS_SETPAG (65+1000)
+#endif
+
+#if defined(__osf__)
+#define AFS_SYSCALL 232
+#define AFS_SYSCALL2 258
+#endif
+
+#if defined(__ultrix)
+#define AFS_SYSCALL 31
+#endif
+
+#if defined(__FreeBSD__)
+#if __FreeBSD_version >= 500000
+#define AFS_SYSCALL 339
+#else
+#define AFS_SYSCALL 210
+#endif
+#endif /* __FreeBSD__ */
+
+#ifdef __DragonFly__
+#ifndef AFS_SYSCALL
+#define AFS_SYSCALL 339
+#endif
+#endif
+
+#ifdef __OpenBSD__
+#define AFS_SYSCALL 208
+#endif
+
+#if defined(__NetBSD__)
+#define AFS_SYSCALL 210
+#endif
+
+#ifdef SYS_afs_syscall
+#define AFS_SYSCALL3 SYS_afs_syscall
+#endif
diff --git a/third_party/heimdal/lib/kafs/common.c b/third_party/heimdal/lib/kafs/common.c
new file mode 100644
index 0000000..ff42cf7
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/common.c
@@ -0,0 +1,469 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "kafs_locl.h"
+
+#define AUTH_SUPERUSER "afs"
+
+/*
+ * Here only ASCII characters are relevant.
+ */
+
+#define IsAsciiLower(c) ('a' <= (c) && (c) <= 'z')
+
+#define ToAsciiUpper(c) ((c) - 'a' + 'A')
+
+static void (*kafs_verbose)(void *, const char *);
+static void *kafs_verbose_ctx;
+
+void
+_kafs_foldup(char *a, const char *b)
+{
+ for (; *b; a++, b++)
+ if (IsAsciiLower(*b))
+ *a = ToAsciiUpper(*b);
+ else
+ *a = *b;
+ *a = '\0';
+}
+
+void
+kafs_set_verbose(void (*f)(void *, const char *), void *ctx)
+{
+ if (f) {
+ kafs_verbose = f;
+ kafs_verbose_ctx = ctx;
+ }
+}
+
+int
+kafs_settoken_rxkad(const char *cell, struct ClearToken *ct,
+ void *ticket, size_t ticket_len)
+{
+ struct ViceIoctl parms;
+ char buf[2048], *t;
+ int32_t sizeof_x;
+
+ t = buf;
+ /*
+ * length of secret token followed by secret token
+ */
+ sizeof_x = ticket_len;
+ memcpy(t, &sizeof_x, sizeof(sizeof_x));
+ t += sizeof(sizeof_x);
+ memcpy(t, ticket, sizeof_x);
+ t += sizeof_x;
+ /*
+ * length of clear token followed by clear token
+ */
+ sizeof_x = sizeof(*ct);
+ memcpy(t, &sizeof_x, sizeof(sizeof_x));
+ t += sizeof(sizeof_x);
+ memcpy(t, ct, sizeof_x);
+ t += sizeof_x;
+
+ /*
+ * do *not* mark as primary cell
+ */
+ sizeof_x = 0;
+ memcpy(t, &sizeof_x, sizeof(sizeof_x));
+ t += sizeof(sizeof_x);
+ /*
+ * follow with cell name
+ */
+ sizeof_x = strlen(cell) + 1;
+ memcpy(t, cell, sizeof_x);
+ t += sizeof_x;
+
+ /*
+ * Build argument block
+ */
+ parms.in = buf;
+ parms.in_size = t - buf;
+ parms.out = 0;
+ parms.out_size = 0;
+
+ return k_pioctl(0, VIOCSETTOK, &parms, 0);
+}
+
+void
+_kafs_fixup_viceid(struct ClearToken *ct, uid_t uid)
+{
+#define ODD(x) ((x) & 1)
+ /* According to Transarc conventions ViceId is valid iff
+ * (EndTimestamp - BeginTimestamp) is odd. By decrementing EndTime
+ * the transformations:
+ *
+ * (issue_date, life) -> (StartTime, EndTime) -> (issue_date, life)
+ * preserves the original values.
+ */
+ if (uid != 0) /* valid ViceId */
+ {
+ if (!ODD(ct->EndTimestamp - ct->BeginTimestamp))
+ ct->EndTimestamp--;
+ }
+ else /* not valid ViceId */
+ {
+ if (ODD(ct->EndTimestamp - ct->BeginTimestamp))
+ ct->EndTimestamp--;
+ }
+}
+
+/* Try to get a db-server for an AFS cell from a AFSDB record */
+
+static int
+dns_find_cell(const char *cell, char *dbserver, size_t len)
+{
+ struct rk_dns_reply *r;
+ int ok = -1;
+ r = rk_dns_lookup(cell, "afsdb");
+ if(r){
+ struct rk_resource_record *rr = r->head;
+ while(rr){
+ if(rr->type == rk_ns_t_afsdb && rr->u.afsdb->preference == 1){
+ strlcpy(dbserver,
+ rr->u.afsdb->domain,
+ len);
+ ok = 0;
+ break;
+ }
+ rr = rr->next;
+ }
+ rk_dns_free_data(r);
+ }
+ return ok;
+}
+
+
+/*
+ * Try to find the cells we should try to klog to in "file".
+ */
+static void
+find_cells(const char *file, char ***cells, int *idx)
+{
+ FILE *f;
+ char cell[64];
+ int i;
+ int ind = *idx;
+
+ f = fopen(file, "r");
+ if (f == NULL)
+ return;
+ while (fgets(cell, sizeof(cell), f)) {
+ char *t;
+ t = cell + strlen(cell);
+ for (; t >= cell; t--)
+ if (*t == '\n' || *t == '\t' || *t == ' ')
+ *t = 0;
+ if (cell[0] == '\0' || cell[0] == '#')
+ continue;
+ for(i = 0; i < ind; i++)
+ if(strcmp((*cells)[i], cell) == 0)
+ break;
+ if(i == ind){
+ char **tmp;
+
+ tmp = realloc(*cells, (ind + 1) * sizeof(**cells));
+ if (tmp == NULL)
+ break;
+ *cells = tmp;
+ (*cells)[ind] = strdup(cell);
+ if ((*cells)[ind] == NULL)
+ break;
+ ++ind;
+ }
+ }
+ fclose(f);
+ *idx = ind;
+}
+
+/*
+ * Get tokens for all cells[]
+ */
+static int
+afslog_cells(struct kafs_data *data, char **cells, int max, uid_t uid,
+ const char *homedir)
+{
+ int ret = 0;
+ int i;
+ for (i = 0; i < max; i++) {
+ int er = (*data->afslog_uid)(data, cells[i], 0, uid, homedir);
+ if (er)
+ ret = er;
+ }
+ return ret;
+}
+
+int
+_kafs_afslog_all_local_cells(struct kafs_data *data,
+ uid_t uid, const char *homedir)
+{
+ int ret;
+ char **cells = NULL;
+ int idx = 0;
+
+ if (homedir == NULL)
+ homedir = getenv("HOME");
+ if (homedir != NULL) {
+ char home[MaxPathLen];
+ snprintf(home, sizeof(home), "%s/.TheseCells", homedir);
+ find_cells(home, &cells, &idx);
+ }
+ find_cells(_PATH_THESECELLS, &cells, &idx);
+ find_cells(_PATH_THISCELL, &cells, &idx);
+ find_cells(_PATH_ARLA_THESECELLS, &cells, &idx);
+ find_cells(_PATH_ARLA_THISCELL, &cells, &idx);
+ find_cells(_PATH_OPENAFS_DEBIAN_THESECELLS, &cells, &idx);
+ find_cells(_PATH_OPENAFS_DEBIAN_THISCELL, &cells, &idx);
+ find_cells(_PATH_OPENAFS_MACOSX_THESECELLS, &cells, &idx);
+ find_cells(_PATH_OPENAFS_MACOSX_THISCELL, &cells, &idx);
+ find_cells(_PATH_ARLA_DEBIAN_THESECELLS, &cells, &idx);
+ find_cells(_PATH_ARLA_DEBIAN_THISCELL, &cells, &idx);
+ find_cells(_PATH_ARLA_OPENBSD_THESECELLS, &cells, &idx);
+ find_cells(_PATH_ARLA_OPENBSD_THISCELL, &cells, &idx);
+
+ ret = afslog_cells(data, cells, idx, uid, homedir);
+ while(idx > 0)
+ free(cells[--idx]);
+ free(cells);
+ return ret;
+}
+
+
+static int
+file_find_cell(struct kafs_data *data,
+ const char *cell, char **realm, int exact)
+{
+ FILE *F;
+ char buf[1024];
+ char *p;
+ int ret = -1;
+
+ if ((F = fopen(_PATH_CELLSERVDB, "r"))
+ || (F = fopen(_PATH_ARLA_CELLSERVDB, "r"))
+ || (F = fopen(_PATH_OPENAFS_DEBIAN_CELLSERVDB, "r"))
+ || (F = fopen(_PATH_OPENAFS_MACOSX_CELLSERVDB, "r"))
+ || (F = fopen(_PATH_ARLA_DEBIAN_CELLSERVDB, "r"))) {
+ while (fgets(buf, sizeof(buf), F)) {
+ int cmp;
+
+ if (buf[0] != '>')
+ continue; /* Not a cell name line, try next line */
+ p = buf;
+ strsep(&p, " \t\n#");
+
+ if (exact)
+ cmp = strcmp(buf + 1, cell);
+ else
+ cmp = strncmp(buf + 1, cell, strlen(cell));
+
+ if (cmp == 0) {
+ /*
+ * We found the cell name we're looking for.
+ * Read next line on the form ip-address '#' hostname
+ */
+ if (fgets(buf, sizeof(buf), F) == NULL)
+ break; /* Read failed, give up */
+ p = strchr(buf, '#');
+ if (p == NULL)
+ break; /* No '#', give up */
+ p++;
+ if (buf[strlen(buf) - 1] == '\n')
+ buf[strlen(buf) - 1] = '\0';
+ *realm = (*data->get_realm)(data, p);
+ if (*realm && **realm != '\0')
+ ret = 0;
+ break; /* Won't try any more */
+ }
+ }
+ fclose(F);
+ }
+ return ret;
+}
+
+/* Find the realm associated with cell. Do this by opening CellServDB
+ file and getting the realm-of-host for the first VL-server for the
+ cell.
+
+ This does not work when the VL-server is living in one realm, but
+ the cell it is serving is living in another realm.
+
+ Return 0 on success, -1 otherwise.
+ */
+
+int
+_kafs_realm_of_cell(struct kafs_data *data,
+ const char *cell, char **realm)
+{
+ char buf[1024];
+ int ret;
+
+ ret = file_find_cell(data, cell, realm, 1);
+ if (ret == 0)
+ return ret;
+ if (dns_find_cell(cell, buf, sizeof(buf)) == 0) {
+ *realm = (*data->get_realm)(data, buf);
+ if(*realm != NULL)
+ return 0;
+ }
+ return file_find_cell(data, cell, realm, 0);
+}
+
+static int
+_kafs_try_get_cred(struct kafs_data *data, const char *user, const char *cell,
+ const char *realm, uid_t uid, struct kafs_token *kt)
+{
+ int ret;
+
+ ret = (*data->get_cred)(data, user, cell, realm, uid, kt);
+ if (kafs_verbose) {
+ const char *estr = (*data->get_error)(data, ret);
+ char *str;
+ int aret;
+
+ aret = asprintf(&str, "%s tried afs%s%s@%s -> %s (%d)",
+ data->name, cell ? "/" : "",
+ cell ? cell : "", realm, estr ? estr : "unknown", ret);
+ if (aret != -1) {
+ (*kafs_verbose)(kafs_verbose_ctx, str);
+ free(str);
+ } else {
+ (*kafs_verbose)(kafs_verbose_ctx, "out of memory");
+ }
+ if (estr)
+ (*data->free_error)(data, estr);
+ }
+
+ return ret;
+}
+
+
+int
+_kafs_get_cred(struct kafs_data *data,
+ const char *cell,
+ const char *realm_hint,
+ const char *realm,
+ uid_t uid,
+ struct kafs_token *kt)
+{
+ int ret = -1;
+ char *vl_realm;
+ char CELL[64];
+
+ /* We're about to find the realm that holds the key for afs in
+ * the specified cell. The problem is that null-instance
+ * afs-principals are common and that hitting the wrong realm might
+ * yield the wrong afs key. The following assumptions were made.
+ *
+ * Any realm passed to us is preferred.
+ *
+ * If there is a realm with the same name as the cell, it is most
+ * likely the correct realm to talk to.
+ *
+ * In most (maybe even all) cases the database servers of the cell
+ * will live in the realm we are looking for.
+ *
+ * Try the local realm, but if the previous cases fail, this is
+ * really a long shot.
+ *
+ */
+
+ /* comments on the ordering of these tests */
+
+ /* If the user passes a realm, she probably knows something we don't
+ * know and we should try afs@realm_hint.
+ */
+
+ if (realm_hint) {
+ ret = _kafs_try_get_cred(data, AUTH_SUPERUSER,
+ cell, realm_hint, uid, kt);
+ if (ret == 0) return 0;
+ ret = _kafs_try_get_cred(data, AUTH_SUPERUSER,
+ NULL, realm_hint, uid, kt);
+ if (ret == 0) return 0;
+ }
+
+ _kafs_foldup(CELL, cell);
+
+ /*
+ * If the AFS servers have a file /usr/afs/etc/krb.conf containing
+ * REALM we still don't have to resort to cross-cell authentication.
+ * Try afs.cell@REALM.
+ */
+ ret = _kafs_try_get_cred(data, AUTH_SUPERUSER,
+ cell, realm, uid, kt);
+ if (ret == 0) return 0;
+
+ /*
+ * If cell == realm we don't need no cross-cell authentication.
+ * Try afs@REALM.
+ */
+ if (strcmp(CELL, realm) == 0) {
+ ret = _kafs_try_get_cred(data, AUTH_SUPERUSER,
+ NULL, realm, uid, kt);
+ if (ret == 0) return 0;
+ }
+
+ /*
+ * We failed to get ``first class tickets'' for afs,
+ * fall back to cross-cell authentication.
+ * Try afs@CELL.
+ * Try afs.cell@CELL.
+ */
+ ret = _kafs_try_get_cred(data, AUTH_SUPERUSER,
+ NULL, CELL, uid, kt);
+ if (ret == 0) return 0;
+ ret = _kafs_try_get_cred(data, AUTH_SUPERUSER,
+ cell, CELL, uid, kt);
+ if (ret == 0) return 0;
+
+ /*
+ * Perhaps the cell doesn't correspond to any realm?
+ * Use realm of first volume location DB server.
+ * Try afs.cell@VL_REALM.
+ * Try afs@VL_REALM???
+ */
+ if (_kafs_realm_of_cell(data, cell, &vl_realm) == 0
+ && strcmp(vl_realm, realm) != 0
+ && strcmp(vl_realm, CELL) != 0) {
+ ret = _kafs_try_get_cred(data, AUTH_SUPERUSER,
+ cell, vl_realm, uid, kt);
+ if (ret)
+ ret = _kafs_try_get_cred(data, AUTH_SUPERUSER,
+ NULL, vl_realm, uid, kt);
+ free(vl_realm);
+ if (ret == 0) return 0;
+ }
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kafs/kafs.3 b/third_party/heimdal/lib/kafs/kafs.3
new file mode 100644
index 0000000..d44e35e
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/kafs.3
@@ -0,0 +1,296 @@
+.\" Copyright (c) 1998 - 2006 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 1, 2006
+.Os HEIMDAL
+.Dt KAFS 3
+.Sh NAME
+.Nm k_hasafs ,
+.Nm k_hasafs_recheck ,
+.Nm k_pioctl ,
+.Nm k_unlog ,
+.Nm k_setpag ,
+.Nm k_afs_cell_of_file ,
+.Nm kafs_set_verbose ,
+.Nm kafs_settoken_rxkad ,
+.Nm kafs_settoken ,
+.Nm krb_afslog ,
+.Nm krb_afslog_uid ,
+.Nm kafs_settoken5 ,
+.Nm krb5_afslog ,
+.Nm krb5_afslog_uid
+.Nd AFS library
+.Sh LIBRARY
+AFS cache manager access library (libkafs, -lkafs)
+.Sh SYNOPSIS
+.In kafs.h
+.Ft int
+.Fn k_afs_cell_of_file "const char *path" "char *cell" "int len"
+.Ft int
+.Fn k_hasafs "void"
+.Ft int
+.Fn k_hasafs_recheck "void"
+.Ft int
+.Fn k_pioctl "char *a_path" "int o_opcode" "struct ViceIoctl *a_paramsP" "int a_followSymlinks"
+.Ft int
+.Fn k_setpag "void"
+.Ft int
+.Fn k_unlog "void"
+.Ft void
+.Fn kafs_set_verbose "void (*func)(void *, const char *, int)" "void *"
+.Ft int
+.Fn kafs_settoken_rxkad "const char *cell" "struct ClearToken *token" "void *ticket" "size_t ticket_len"
+.Ft int
+.Fn kafs_settoken "const char *cell" "uid_t uid" "CREDENTIALS *c"
+.Fn krb_afslog "char *cell" "char *realm"
+.Ft int
+.Fn krb_afslog_uid "char *cell" "char *realm" "uid_t uid"
+.Ft krb5_error_code
+.Fn krb5_afslog_uid "krb5_context context" "krb5_ccache id" "const char *cell" "krb5_const_realm realm" "uid_t uid"
+.Ft int
+.Fn kafs_settoken5 "const char *cell" "uid_t uid" "krb5_creds *c"
+.Ft krb5_error_code
+.Fn krb5_afslog "krb5_context context" "krb5_ccache id" "const char *cell" "krb5_const_realm realm"
+.Sh DESCRIPTION
+.Fn k_hasafs
+initializes some library internal structures, and tests for the
+presence of AFS in the kernel, none of the other functions should be
+called before
+.Fn k_hasafs
+is called, or if it fails.
+.Pp
+.Fn k_hasafs_recheck
+forces a recheck if a AFS client has started since last time
+.Fn k_hasafs
+or
+.Fn k_hasafs_recheck
+was called.
+.Pp
+.Fn kafs_set_verbose
+set a log function that will be called each time the kafs library does
+something important so that the application using libkafs can output
+verbose logging.
+Calling the function
+.Fa kafs_set_verbose
+with the function argument set to
+.Dv NULL
+will stop libkafs from calling the logging function (if set).
+.Pp
+.Fn kafs_settoken_rxkad
+set
+.Li rxkad
+with the
+.Fa token
+and
+.Fa ticket
+(that have the length
+.Fa ticket_len )
+for a given
+.Fa cell .
+.Pp
+.Fn kafs_settoken
+and
+.Fn kafs_settoken5
+work the same way as
+.Fn kafs_settoken_rxkad
+but internally converts the Kerberos 4 or 5 credential to a afs
+cleartoken and ticket.
+.Pp
+.Fn krb_afslog ,
+and
+.Fn krb_afslog_uid
+obtains new tokens (and possibly tickets) for the specified
+.Fa cell
+and
+.Fa realm .
+If
+.Fa cell
+is
+.Dv NULL ,
+the local cell is used. If
+.Fa realm
+is
+.Dv NULL ,
+the function tries to guess what realm to use. Unless you have some good knowledge of what cell or realm to use, you should pass
+.Dv NULL .
+.Fn krb_afslog
+will use the real user-id for the
+.Dv ViceId
+field in the token,
+.Fn krb_afslog_uid
+will use
+.Fa uid .
+.Pp
+.Fn krb5_afslog ,
+and
+.Fn krb5_afslog_uid
+are the Kerberos 5 equivalents of
+.Fn krb_afslog ,
+and
+.Fn krb_afslog_uid .
+.Pp
+.Fn krb5_afslog ,
+.Fn kafs_settoken5
+can be configured to behave differently via a
+.Nm krb5_appdefault
+option
+.Li afs-use-524
+in
+.Pa krb5.conf .
+Possible values for
+.Li afs-use-524
+are:
+.Bl -tag -width local
+.It yes
+use the 524 server in the realm to convert the ticket
+.It no
+use the Kerberos 5 ticket directly, can be used with if the afs cell
+support 2b token.
+.It local, 2b
+convert the Kerberos 5 credential to a 2b token locally (the same work
+as a 2b 524 server should have done).
+.El
+.Pp
+Example:
+.Pp
+.Bd -literal
+[appdefaults]
+ SU.SE = { afs-use-524 = local }
+ PDC.KTH.SE = { afs-use-524 = yes }
+ afs-use-524 = yes
+.Ed
+.Pp
+libkafs will use the
+.Li libkafs
+as application name when running the
+.Nm krb5_appdefault
+function call.
+.Pp
+The (uppercased) cell name is used as the realm to the
+.Nm krb5_appdefault function.
+.Pp
+.\" The extra arguments are the ubiquitous context, and the cache id where
+.\" to store any obtained tickets. Since AFS servers normally can't handle
+.\" Kerberos 5 tickets directly, these functions will first obtain version
+.\" 5 tickets for the requested cells, and then convert them to version 4
+.\" tickets, that can be stashed in the kernel. To convert tickets the
+.\" .Fn krb524_convert_creds_kdc
+.\" function will be used.
+.\" .Pp
+.Fn k_afs_cell_of_file
+will in
+.Fa cell
+return the cell of a specified file, no more than
+.Fa len
+characters is put in
+.Fa cell .
+.Pp
+.Fn k_pioctl
+does a
+.Fn pioctl
+system call with the specified arguments. This function is equivalent to
+.Fn lpioctl .
+.Pp
+.Fn k_setpag
+initializes a new PAG.
+.Pp
+.Fn k_unlog
+removes destroys all tokens in the current PAG.
+.Sh RETURN VALUES
+.Fn k_hasafs
+returns 1 if AFS is present in the kernel, 0 otherwise.
+.Fn krb_afslog
+and
+.Fn krb_afslog_uid
+returns 0 on success, or a Kerberos error number on failure.
+.Fn k_afs_cell_of_file ,
+.Fn k_pioctl ,
+.Fn k_setpag ,
+and
+.Fn k_unlog
+all return the value of the underlaying system call, 0 on success.
+.Sh ENVIRONMENT
+The following environment variable affect the mode of operation of
+.Nm kafs :
+.Bl -tag -width AFS_SYSCALL
+.It Ev AFS_SYSCALL
+Normally,
+.Nm kafs
+will try to figure out the correct system call(s) that are used by AFS
+by itself. If it does not manage to do that, or does it incorrectly,
+you can set this variable to the system call number or list of system
+call numbers that should be used.
+.El
+.Sh EXAMPLES
+The following code from
+.Nm login
+will obtain a new PAG and tokens for the local cell and the cell of
+the users home directory.
+.Bd -literal
+if (k_hasafs()) {
+ char cell[64];
+ k_setpag();
+ if(k_afs_cell_of_file(pwd->pw_dir, cell, sizeof(cell)) == 0)
+ krb_afslog(cell, NULL);
+ krb_afslog(NULL, NULL);
+}
+.Ed
+.Sh ERRORS
+If any of these functions (apart from
+.Fn k_hasafs )
+is called without AFS being present in the kernel, the process will
+usually (depending on the operating system) receive a SIGSYS signal.
+.Sh SEE ALSO
+.Xr krb5_appdefault 3 ,
+.Xr krb5.conf 5
+.Rs
+.%A Transarc Corporation
+.%J AFS-3 Programmer's Reference
+.%T File Server/Cache Manager Interface
+.%D 1991
+.Re
+.Sh FILES
+libkafs will search for
+.Pa ThisCell and
+.Pa TheseCells
+in the following locations:
+.Pa /usr/vice/etc ,
+.Pa /etc/openafs ,
+.Pa /var/db/openafs/etc ,
+.Pa /usr/arla/etc ,
+.Pa /etc/arla ,
+and
+.Pa /etc/afs
+.Sh BUGS
+.Ev AFS_SYSCALL
+has no effect under AIX.
diff --git a/third_party/heimdal/lib/kafs/kafs.h b/third_party/heimdal/lib/kafs/kafs.h
new file mode 100644
index 0000000..6f6eb63
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/kafs.h
@@ -0,0 +1,216 @@
+/*
+ * Copyright (c) 1995 - 2001, 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __KAFS_H
+#define __KAFS_H
+
+/* XXX must include krb5.h or krb.h */
+
+/* sys/ioctl.h must be included manually before kafs.h */
+
+/*
+ */
+#define AFSCALL_PIOCTL 20
+#define AFSCALL_SETPAG 21
+
+#ifndef _VICEIOCTL
+#ifdef __GNU__
+#define _IOT_ViceIoctl _IOT(_IOTS(caddr_t), 2, _IOTS(short), 2, 0, 0)
+#endif
+#define _VICEIOCTL(id) ((unsigned int ) _IOW('V', id, struct ViceIoctl))
+#define _AFSCIOCTL(id) ((unsigned int ) _IOW('C', id, struct ViceIoctl))
+#endif /* _VICEIOCTL */
+
+#define VIOCSETAL _VICEIOCTL(1)
+#define VIOCGETAL _VICEIOCTL(2)
+#define VIOCSETTOK _VICEIOCTL(3)
+#define VIOCGETVOLSTAT _VICEIOCTL(4)
+#define VIOCSETVOLSTAT _VICEIOCTL(5)
+#define VIOCFLUSH _VICEIOCTL(6)
+#define VIOCGETTOK _VICEIOCTL(8)
+#define VIOCUNLOG _VICEIOCTL(9)
+#define VIOCCKSERV _VICEIOCTL(10)
+#define VIOCCKBACK _VICEIOCTL(11)
+#define VIOCCKCONN _VICEIOCTL(12)
+#define VIOCWHEREIS _VICEIOCTL(14)
+#define VIOCACCESS _VICEIOCTL(20)
+#define VIOCUNPAG _VICEIOCTL(21)
+#define VIOCGETFID _VICEIOCTL(22)
+#define VIOCSETCACHESIZE _VICEIOCTL(24)
+#define VIOCFLUSHCB _VICEIOCTL(25)
+#define VIOCNEWCELL _VICEIOCTL(26)
+#define VIOCGETCELL _VICEIOCTL(27)
+#define VIOC_AFS_DELETE_MT_PT _VICEIOCTL(28)
+#define VIOC_AFS_STAT_MT_PT _VICEIOCTL(29)
+#define VIOC_FILE_CELL_NAME _VICEIOCTL(30)
+#define VIOC_GET_WS_CELL _VICEIOCTL(31)
+#define VIOC_AFS_MARINER_HOST _VICEIOCTL(32)
+#define VIOC_GET_PRIMARY_CELL _VICEIOCTL(33)
+#define VIOC_VENUSLOG _VICEIOCTL(34)
+#define VIOC_GETCELLSTATUS _VICEIOCTL(35)
+#define VIOC_SETCELLSTATUS _VICEIOCTL(36)
+#define VIOC_FLUSHVOLUME _VICEIOCTL(37)
+#define VIOC_AFS_SYSNAME _VICEIOCTL(38)
+#define VIOC_EXPORTAFS _VICEIOCTL(39)
+#define VIOCGETCACHEPARAMS _VICEIOCTL(40)
+#define VIOC_GCPAGS _VICEIOCTL(48)
+
+#define VIOCGETTOK2 _AFSCIOCTL(7)
+#define VIOCSETTOK2 _AFSCIOCTL(8)
+
+struct ViceIoctl {
+ caddr_t in, out;
+ unsigned short in_size;
+ unsigned short out_size;
+};
+
+struct ClearToken {
+ int32_t AuthHandle;
+ char HandShakeKey[8];
+ int32_t ViceId;
+ int32_t BeginTimestamp;
+ int32_t EndTimestamp;
+};
+
+/* Use k_hasafs() to probe if the machine supports AFS syscalls.
+ The other functions will generate a SIGSYS if AFS is not supported */
+
+int k_hasafs (void);
+int k_hasafs_recheck (void);
+
+int krb_afslog (const char *cell, const char *realm);
+int krb_afslog_uid (const char *cell, const char *realm, uid_t uid);
+int krb_afslog_home (const char *cell, const char *realm,
+ const char *homedir);
+int krb_afslog_uid_home (const char *cell, const char *realm, uid_t uid,
+ const char *homedir);
+
+int krb_realm_of_cell (const char *cell, char **realm);
+
+/* compat */
+#define k_afsklog krb_afslog
+#define k_afsklog_uid krb_afslog_uid
+
+int k_pioctl (char *a_path,
+ int o_opcode,
+ struct ViceIoctl *a_paramsP,
+ int a_followSymlinks);
+int k_unlog (void);
+int k_setpag (void);
+int k_afs_cell_of_file (const char *path, char *cell, int len);
+
+
+
+/* XXX */
+#ifdef KFAILURE
+#define KRB_H_INCLUDED
+#endif
+
+#ifdef KRB5_RECVAUTH_IGNORE_VERSION
+#define KRB5_H_INCLUDED
+#endif
+
+void kafs_set_verbose (void (*kafs_verbose)(void *, const char *), void *);
+int kafs_settoken_rxkad (const char *, struct ClearToken *,
+ void *ticket, size_t ticket_len);
+#ifdef KRB_H_INCLUDED
+int kafs_settoken (const char*, uid_t, CREDENTIALS*);
+#endif
+#ifdef KRB5_H_INCLUDED
+int kafs_settoken5 (krb5_context, const char*, uid_t, krb5_creds*);
+#endif
+
+
+#ifdef KRB5_H_INCLUDED
+krb5_error_code krb5_afslog_uid (krb5_context context,
+ krb5_ccache id,
+ const char *cell,
+ krb5_const_realm realm,
+ uid_t uid);
+krb5_error_code krb5_afslog (krb5_context context,
+ krb5_ccache id,
+ const char *cell,
+ krb5_const_realm realm);
+krb5_error_code krb5_afslog_uid_home (krb5_context context,
+ krb5_ccache id,
+ const char *cell,
+ krb5_const_realm realm,
+ uid_t uid,
+ const char *homedir);
+
+krb5_error_code krb5_afslog_home (krb5_context context,
+ krb5_ccache id,
+ const char *cell,
+ krb5_const_realm realm,
+ const char *homedir);
+
+krb5_error_code krb5_realm_of_cell (const char *cell, char **realm);
+
+#endif
+
+
+#define _PATH_VICE "/usr/vice/etc/"
+#define _PATH_THISCELL _PATH_VICE "ThisCell"
+#define _PATH_CELLSERVDB _PATH_VICE "CellServDB"
+#define _PATH_THESECELLS _PATH_VICE "TheseCells"
+
+#define _PATH_ARLA_VICE "/usr/arla/etc/"
+#define _PATH_ARLA_THISCELL _PATH_ARLA_VICE "ThisCell"
+#define _PATH_ARLA_CELLSERVDB _PATH_ARLA_VICE "CellServDB"
+#define _PATH_ARLA_THESECELLS _PATH_ARLA_VICE "TheseCells"
+
+#define _PATH_OPENAFS_DEBIAN_VICE "/etc/openafs/"
+#define _PATH_OPENAFS_DEBIAN_THISCELL _PATH_OPENAFS_DEBIAN_VICE "ThisCell"
+#define _PATH_OPENAFS_DEBIAN_CELLSERVDB _PATH_OPENAFS_DEBIAN_VICE "CellServDB"
+#define _PATH_OPENAFS_DEBIAN_THESECELLS _PATH_OPENAFS_DEBIAN_VICE "TheseCells"
+
+#define _PATH_OPENAFS_MACOSX_VICE "/var/db/openafs/etc/"
+#define _PATH_OPENAFS_MACOSX_THISCELL _PATH_OPENAFS_MACOSX_VICE "ThisCell"
+#define _PATH_OPENAFS_MACOSX_CELLSERVDB _PATH_OPENAFS_MACOSX_VICE "CellServDB"
+#define _PATH_OPENAFS_MACOSX_THESECELLS _PATH_OPENAFS_MACOSX_VICE "TheseCells"
+
+#define _PATH_ARLA_DEBIAN_VICE "/etc/arla/"
+#define _PATH_ARLA_DEBIAN_THISCELL _PATH_ARLA_DEBIAN_VICE "ThisCell"
+#define _PATH_ARLA_DEBIAN_CELLSERVDB _PATH_ARLA_DEBIAN_VICE "CellServDB"
+#define _PATH_ARLA_DEBIAN_THESECELLS _PATH_ARLA_DEBIAN_VICE "TheseCells"
+
+#define _PATH_ARLA_OPENBSD_VICE "/etc/afs/"
+#define _PATH_ARLA_OPENBSD_THISCELL _PATH_ARLA_OPENBSD_VICE "ThisCell"
+#define _PATH_ARLA_OPENBSD_CELLSERVDB _PATH_ARLA_OPENBSD_VICE "CellServDB"
+#define _PATH_ARLA_OPENBSD_THESECELLS _PATH_ARLA_OPENBSD_VICE "TheseCells"
+
+extern int _kafs_debug;
+
+#endif /* __KAFS_H */
diff --git a/third_party/heimdal/lib/kafs/kafs_locl.h b/third_party/heimdal/lib/kafs/kafs_locl.h
new file mode 100644
index 0000000..6f34ca6
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/kafs_locl.h
@@ -0,0 +1,163 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __KAFS_LOCL_H__
+#define __KAFS_LOCL_H__
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <setjmp.h>
+#include <errno.h>
+
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#if defined(HAVE_SYS_IOCTL_H) && SunOS != 40
+#include <sys/ioctl.h>
+#endif
+#ifdef HAVE_SYS_FILIO_H
+#include <sys/filio.h>
+#endif
+#ifdef HAVE_SYS_SYSCTL_H
+#include <sys/sysctl.h>
+#endif
+
+#ifdef HAVE_SYS_SYSCALL_H
+#include <sys/syscall.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+#ifdef HAVE_NETINET6_IN6_H
+#include <netinet6/in6.h>
+#endif
+
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+#ifdef HAVE_RESOLV_H
+#include <resolv.h>
+#endif
+#include <roken.h>
+
+#ifdef KRB5
+#include <krb5.h>
+#endif
+#ifdef KRB5
+#include "crypto-headers.h"
+#include <krb5-v4compat.h>
+typedef struct credentials CREDENTIALS;
+#endif /* KRB5 */
+#ifndef NO_AFS
+#include <kafs.h>
+#endif
+
+#include <resolve.h>
+
+#include "afssysdefs.h"
+
+struct kafs_data;
+struct kafs_token;
+typedef int (*afslog_uid_func_t)(struct kafs_data *,
+ const char *,
+ const char *,
+ uid_t,
+ const char *);
+
+typedef int (*get_cred_func_t)(struct kafs_data*, const char*, const char*,
+ const char*, uid_t, struct kafs_token *);
+
+typedef char* (*get_realm_func_t)(struct kafs_data*, const char*);
+
+struct kafs_data {
+ const char *name;
+ afslog_uid_func_t afslog_uid;
+ get_cred_func_t get_cred;
+ get_realm_func_t get_realm;
+ const char *(*get_error)(struct kafs_data *, int);
+ void (*free_error)(struct kafs_data *, const char *);
+ void *data;
+};
+
+struct kafs_token {
+ struct ClearToken ct;
+ void *ticket;
+ size_t ticket_len;
+};
+
+void _kafs_foldup(char *, const char *);
+
+int _kafs_afslog_all_local_cells(struct kafs_data*, uid_t, const char*);
+
+int _kafs_get_cred(struct kafs_data*, const char*, const char*, const char *,
+ uid_t, struct kafs_token *);
+
+int
+_kafs_realm_of_cell(struct kafs_data *, const char *, char **);
+
+int
+_kafs_v4_to_kt(CREDENTIALS *, uid_t, struct kafs_token *);
+
+void
+_kafs_fixup_viceid(struct ClearToken *, uid_t);
+
+int
+_kafs_derive_des_key(krb5_enctype, void *, size_t, char[8]);
+
+#ifdef _AIX
+int aix_pioctl(char*, int, struct ViceIoctl*, int);
+int aix_setpag(void);
+#endif
+
+#endif /* __KAFS_LOCL_H__ */
diff --git a/third_party/heimdal/lib/kafs/roken_rename.h b/third_party/heimdal/lib/kafs/roken_rename.h
new file mode 100644
index 0000000..26da265
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/roken_rename.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2001-2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __roken_rename_h__
+#define __roken_rename_h__
+
+/*
+ * Libroken routines that are added libkafs
+ */
+
+#define _resolve_debug _kafs_resolve_debug
+
+#define rk_dns_free_data _kafs_dns_free_data
+#define rk_dns_lookup _kafs_dns_lookup
+#define rk_dns_string_to_type _kafs_dns_string_to_type
+#define rk_dns_type_to_string _kafs_dns_type_to_string
+#define rk_dns_srv_order _kafs_dns_srv_order
+#define rk_dns_make_query _kafs_dns_make_query
+#define rk_dns_free_query _kafs_dns_free_query
+#define rk_dns_parse_reply _kafs_dns_parse_reply
+
+#ifndef HAVE_STRTOK_R
+#define rk_strtok_r _kafs_strtok_r
+#endif
+#ifndef HAVE_STRLCPY
+#define rk_strlcpy _kafs_strlcpy
+#endif
+#ifndef HAVE_STRSEP
+#define rk_strsep _kafs_strsep
+#endif
+
+#endif /* __roken_rename_h__ */
diff --git a/third_party/heimdal/lib/kafs/rxkad_kdf.c b/third_party/heimdal/lib/kafs/rxkad_kdf.c
new file mode 100644
index 0000000..5af391e
--- /dev/null
+++ b/third_party/heimdal/lib/kafs/rxkad_kdf.c
@@ -0,0 +1,221 @@
+/*
+ * Copyright (c) 1995-2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2013-2014 Carnegie Mellon University
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2013 by the Massachusetts Institute of Technology
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#define HC_DEPRECATED_CRYPTO
+#include "kafs_locl.h"
+
+static int rxkad_derive_des_key(const void *, size_t, char[8]);
+static int compress_parity_bits(void *, size_t *);
+
+/**
+ * Use NIST SP800-108 with HMAC(MD5) in counter mode as the PRF to derive a
+ * des key from another type of key.
+ *
+ * L is 64, as we take 64 random bits and turn them into a 56-bit des key.
+ * The output of hmac_md5 is 128 bits; we take the first 64 only, so n
+ * properly should be 1. However, we apply a slight variation due to the
+ * possibility of producing a weak des key. If the output key is weak, do NOT
+ * simply correct it, instead, the counter is advanced and the next output
+ * used. As such, we code so as to have n be the full 255 permitted by our
+ * encoding of the counter i in an 8-bit field. L itself is encoded as a
+ * 32-bit field, big-endian. We use the constant string "rxkad" as a label
+ * for this key derivation, the standard NUL byte separator, and omit a
+ * key-derivation context. The input key is unique to the krb5 service ticket,
+ * which is unlikely to be used in an other location. If it is used in such
+ * a fashion, both locations will derive the same des key from the PRF, but
+ * this is no different from if a krb5 des key had been used in the same way,
+ * as traditional krb5 rxkad uses the ticket session key directly as the token
+ * key.
+ *
+ * @param[in] in pointer to input key data
+ * @param[in] insize length of input key data
+ * @param[out] out 8-byte buffer to hold the derived key
+ *
+ * @return Returns 0 to indicate success, or an error code.
+ *
+ * @retval KRB5DES_WEAK_KEY Successive derivation attempts with all
+ * 255 possible counter values each produced weak DES keys. This input
+ * cannot be used to produce a usable key.
+ */
+static int
+rxkad_derive_des_key(const void *in, size_t insize, char out[8])
+{
+ unsigned char i;
+ static unsigned char label[] = "rxkad";
+ /* bits of output, as 32 bit word, MSB first */
+ static unsigned char Lbuf[4] = { 0, 0, 0, 64 };
+ /* only needs to be 16 for md5, but lets be sure it fits */
+ unsigned char tmp[64];
+ unsigned int mdsize;
+ DES_cblock ktmp;
+ HMAC_CTX mctx;
+
+ /* stop when 8 bit counter wraps to 0 */
+ for (i = 1; i; i++) {
+ HMAC_CTX_init(&mctx);
+ if (HMAC_Init_ex(&mctx, in, insize, EVP_md5(), NULL) == 0) {
+ HMAC_CTX_cleanup(&mctx);
+ return ENOMEM;
+ }
+ HMAC_Update(&mctx, &i, 1);
+ HMAC_Update(&mctx, label, sizeof(label)); /* includes label and separator */
+ HMAC_Update(&mctx, Lbuf, 4);
+ mdsize = sizeof(tmp);
+ HMAC_Final(&mctx, tmp, &mdsize);
+ HMAC_CTX_cleanup(&mctx);
+ memcpy(ktmp, tmp, 8);
+ DES_set_odd_parity(&ktmp);
+ if (!DES_is_weak_key(&ktmp)) {
+ memcpy(out, ktmp, 8);
+ return 0;
+ }
+ }
+ return KRB5DES_WEAK_KEY;
+}
+
+/**
+ * This is the inverse of the random-to-key for 3des specified in
+ * rfc3961, converting blocks of 8 bytes to blocks of 7 bytes by distributing
+ * the bits of each 8th byte as the lsb of the previous 7 bytes.
+ *
+ * @param[in,out] buffer Buffer containing the key to be converted
+ * @param[in,out] bufsiz Points to the size of the key data. On
+ * return, this is updated to reflect the size of the compressed data.
+ *
+ * @return Returns 0 to indicate success, or an error code.
+ *
+ * @retval KRB5_BAD_KEYSIZE The key size was not a multiple of 8 bytes.
+ */
+static int
+compress_parity_bits(void *buffer, size_t *bufsiz)
+{
+ unsigned char *cb, tmp;
+ int i, j, nk;
+
+ if (*bufsiz % 8 != 0)
+ return KRB5_BAD_KEYSIZE;
+ cb = (unsigned char *)buffer;
+ nk = *bufsiz / 8;
+ for (i = 0; i < nk; i++) {
+ tmp = cb[8 * i + 7] >> 1;
+ for (j = 0; j < 7; j++) {
+ cb[8 * i + j] &= 0xfe;
+ cb[8 * i + j] |= tmp & 0x1;
+ tmp >>= 1;
+ }
+ }
+ for (i = 1; i < nk; i++)
+ memmove(cb + 7 * i, cb + 8 * i, 7);
+ *bufsiz = 7 * nk;
+ return 0;
+}
+
+/**
+ * Derive a DES key for use with rxkad and fcrypt from a given Kerberos
+ * key of (almost) any type. This function encodes enctype-specific
+ * knowledge about how to derive a DES key from a given key type.
+ * If given a des key, use it directly; otherwise, perform any parity
+ * fixup that may be needed and pass through to the hmad-md5 bits.
+ *
+ * @param[in] enctype Kerberos enctype of the input key
+ * @param[in] keydata Input key data
+ * @param[in] keylen Size of input key data
+ * @param[out] output 8-byte buffer to hold the derived key
+ *
+ * @return Returns 0 to indicate success, or an error code.
+ *
+ * @retval KRB5_PROG_ETYPE_NOSUPP The enctype is one for which rxkad-kdf
+ * is not supported. This includes several reserved enctypes, enctype
+ * values used in PKINIT to stand for CMS algorithm identifiers, and all
+ * private-use (negative) enctypes.
+ *
+ * @retval KRB5_BAD_KEYSIZE The key size was not a multiple of 8 bytes
+ * (for 3DES key types), exactly 8 bytes (for DES key types), or at least
+ * 8 bytes (for other key types).
+ *
+ * @retval KRB5DES_WEAK_KEY Successive derivation attempts with all
+ * 255 possible counter values each produced weak DES keys. This input
+ * cannot be used to produce a usable key.
+ */
+int
+_kafs_derive_des_key(krb5_enctype enctype, void *keydata, size_t keylen,
+ char output[8])
+{
+ int ret = 0;
+
+ switch ((int)enctype) {
+ case ETYPE_DES_CBC_CRC:
+ case ETYPE_DES_CBC_MD4:
+ case ETYPE_DES_CBC_MD5:
+ if (keylen != 8)
+ return KRB5_BAD_KEYSIZE;
+
+ /* Extract session key */
+ memcpy(output, keydata, 8);
+ break;
+ case ETYPE_NULL:
+ case 4:
+ case 6:
+ case 8:
+ case 9:
+ case 10:
+ case 11:
+ case 12:
+ case 13:
+ case 14:
+ case 15:
+ return KRB5_PROG_ETYPE_NOSUPP;
+ /*In order to become a "Cryptographic Key" as specified in
+ * SP800-108, it must be indistinguishable from a random bitstring. */
+ case ETYPE_DES3_CBC_MD5:
+ case ETYPE_OLD_DES3_CBC_SHA1:
+ case ETYPE_DES3_CBC_SHA1:
+ ret = compress_parity_bits(keydata, &keylen);
+ if (ret)
+ return ret;
+ fallthrough;
+ default:
+ if (enctype < 0)
+ return KRB5_PROG_ETYPE_NOSUPP;
+ if (keylen < 7)
+ return KRB5_BAD_KEYSIZE;
+ ret = rxkad_derive_des_key(keydata, keylen, output);
+ }
+ return ret;
+}
diff --git a/third_party/heimdal/lib/kdfs/ChangeLog b/third_party/heimdal/lib/kdfs/ChangeLog
new file mode 100644
index 0000000..c4bc2a3
--- /dev/null
+++ b/third_party/heimdal/lib/kdfs/ChangeLog
@@ -0,0 +1,28 @@
+2002-08-12 Johan Danielsson <joda@pdc.kth.se>
+
+ * k5dfspag.c: don't use ## in string concatenation
+
+2002-03-11 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkdfs_la_LDFLAGS): set versoin to 0:2:0
+
+2002-01-23 Assar Westerlund <assar@sics.se>
+
+ * k5dfspag.c: use SIG_DFL and not SIG_IGN for SIGCHLD.
+ from "Todd C. Miller" <Todd.Miller@courtesan.com>
+
+2001-02-07 Assar Westerlund <assar@sics.se>
+
+ * k5dfspag.c: add config.h
+
+2000-12-11 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libkdfs_la_LDFLAGS): set version to 0:1:0
+
+2000-07-02 Assar Westerlund <assar@sics.se>
+
+ * k5dfspag.c: use krb5.h instead of krb5_locl.h
+
+ * initial import from Ake Sandgren <ake@cs.umu.se>
+
+
diff --git a/third_party/heimdal/lib/kdfs/Makefile.am b/third_party/heimdal/lib/kdfs/Makefile.am
new file mode 100644
index 0000000..e31b240
--- /dev/null
+++ b/third_party/heimdal/lib/kdfs/Makefile.am
@@ -0,0 +1,12 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+lib_LTLIBRARIES = libkdfs.la
+
+libkdfs_la_SOURCES = \
+ k5dfspag.c
+
+libkdfs_la_LDFLAGS = -version-info 0:3:0
+
+EXTRA_DIST = NTMakefile
diff --git a/third_party/heimdal/lib/kdfs/NTMakefile b/third_party/heimdal/lib/kdfs/NTMakefile
new file mode 100644
index 0000000..4ec8f31
--- /dev/null
+++ b/third_party/heimdal/lib/kdfs/NTMakefile
@@ -0,0 +1,35 @@
+########################################################################
+#
+# Copyright (c) 2009, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\kdfs
+
+!include ../../windows/NTMakefile.w32
+
diff --git a/third_party/heimdal/lib/kdfs/k5dfspag.c b/third_party/heimdal/lib/kdfs/k5dfspag.c
new file mode 100644
index 0000000..9db2555
--- /dev/null
+++ b/third_party/heimdal/lib/kdfs/k5dfspag.c
@@ -0,0 +1,368 @@
+/*
+ * lib/krb5/os/k5dfspag.c
+ *
+ * New Kerberos module to issue the DFS PAG syscalls.
+ * It also contains the routine to fork and exec the
+ * k5dcecon routine to do most of the work.
+ *
+ * This file is designed to be as independent of DCE
+ * and DFS as possible. The only dependencies are on
+ * the syscall numbers. If DFS not running or not installed,
+ * the sig handlers will catch and the signal and
+ * will continue.
+ *
+ * krb5_dfs_newpag and krb5_dfs_getpag should not be real
+ * Kerberos routines, since they should be setpag and getpag
+ * in the DCE library, but without the DCE baggage.
+ * Thus they don't have context, and don't return a krb5 error.
+ *
+ *
+ *
+ * krb5_dfs_pag()
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+RCSID("$Id$");
+
+#include <krb5.h>
+
+#ifdef DCE
+
+#include <stdio.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <fcntl.h>
+#include <sys/param.h>
+
+/* Only run this DFS PAG code on systems with POSIX
+ * All that we are interested in dor:, AIX 4.x,
+ * Solaris 2.5.x, HPUX 10.x Even SunOS 4.1.4, AIX 3.2.5
+ * and SGI 5.3 are OK. This simplifies
+ * the build/configure which I don't want to change now.
+ * All of them also have waitpid as well.
+ */
+
+#define POSIX_SETJMP
+#define POSIX_SIGNALS
+#define HAVE_WAITPID
+
+#include <signal.h>
+#include <setjmp.h>
+#ifndef POSIX_SETJMP
+#undef sigjmp_buf
+#undef sigsetjmp
+#undef siglongjmp
+#define sigjmp_buf jmp_buf
+#define sigsetjmp(j,s) setjmp(j)
+#define siglongjmp longjmp
+#endif
+
+#ifdef POSIX_SIGNALS
+typedef struct sigaction handler;
+#define handler_init(H,F) (sigemptyset(&(H).sa_mask), \
+ (H).sa_flags=0, \
+ (H).sa_handler=(F))
+#define handler_swap(S,NEW,OLD) sigaction(S, &NEW, &OLD)
+#define handler_set(S,OLD) sigaction(S, &OLD, NULL)
+#else
+typedef sigtype (*handler)();
+#define handler_init(H,F) ((H) = (F))
+#define handler_swap(S,NEW,OLD) ((OLD) = signal ((S), (NEW)))
+#define handler_set(S,OLD) (signal ((S), (OLD)))
+#endif
+
+#define krb5_sigtype void
+#define WAIT_USES_INT
+typedef krb5_sigtype sigtype;
+
+
+/*
+ * Need some syscall numbers based on different systems.
+ * These are based on:
+ * HPUX 10.10 /opt/dce/include/dcedfs/syscall.h
+ * Solaris 2.5 /opt/dcelocal/share/include/dcedfs/syscall.h
+ * AIX 4.2 - needs some funny games with load and kafs_syscall
+ * to get the kernel extentions. There should be a better way!
+ *
+ * DEE 5/27/97
+ *
+ */
+
+
+#define AFSCALL_SETPAG 2
+#define AFSCALL_GETPAG 11
+
+#if defined(sun)
+#define AFS_SYSCALL 72
+
+#elif defined(hpux)
+/* assume HPUX 10 + or is it 50 */
+#define AFS_SYSCALL 326
+
+#elif defined(_AIX)
+#ifndef DPAGAIX
+#define DPAGAIX LIBEXECDIR "/dpagaix"
+#endif
+int *load();
+static int (*dpagaix)(int, int, int, int, int, int) = 0;
+
+#elif defined(sgi) || defined(_sgi)
+#define AFS_SYSCALL 206+1000
+
+#else
+#define AFS_SYSCALL (Unknown_DFS_AFS_SYSCALL)
+#endif
+
+
+#ifdef WAIT_USES_INT
+ int wait_status;
+#else /* WAIT_USES_INT */
+ union wait wait_status;
+#endif /* WAIT_USES_INT */
+
+#ifndef K5DCECON
+#define K5DCECON LIBEXECDIR "/k5dcecon"
+#endif
+
+/*
+ * mysig()
+ *
+ * signal handler if DFS not running
+ *
+ */
+
+static sigjmp_buf setpag_buf;
+
+static sigtype mysig()
+{
+ siglongjmp(setpag_buf, 1);
+}
+
+/*
+ * krb5_dfs_pag_syscall()
+ *
+ * wrapper for the syscall with signal handlers
+ *
+ */
+
+static int krb5_dfs_pag_syscall(opt1,opt2)
+ int opt1;
+ int opt2;
+{
+ handler sa1, osa1;
+ handler sa2, osa2;
+ int pag = -2;
+
+ handler_init (sa1, mysig);
+ handler_init (sa2, mysig);
+ handler_swap (SIGSYS, sa1, osa1);
+ handler_swap (SIGSEGV, sa2, osa2);
+
+ if (sigsetjmp(setpag_buf, 1) == 0) {
+
+#if defined(_AIX)
+ if (!dpagaix)
+ dpagaix = load(DPAGAIX, 0, 0);
+ if (dpagaix)
+ pag = (*dpagaix)(opt1, opt2, 0, 0, 0, 0);
+#else
+ pag = syscall(AFS_SYSCALL, opt1, opt2, 0, 0, 0, 0);
+#endif
+
+ handler_set (SIGSYS, osa1);
+ handler_set (SIGSEGV, osa2);
+ return(pag);
+ }
+
+ /* syscall failed! return 0 */
+ handler_set (SIGSYS, osa1);
+ handler_set (SIGSEGV, osa2);
+ return(-2);
+}
+
+/*
+ * krb5_dfs_newpag()
+ *
+ * issue a DCE/DFS setpag system call to set the newpag
+ * for this process. This takes advantage of a currently
+ * undocumented feature of the Transarc port of DFS.
+ * Even in DCE 1.2.2 for which the source is available,
+ * (but no vendors have released), this feature is not
+ * there, but it should be, or could be added.
+ * If new_pag is zero, then the syscall will get a new pag
+ * and return its value.
+ */
+
+int krb5_dfs_newpag(new_pag)
+ int new_pag;
+{
+ return(krb5_dfs_pag_syscall(AFSCALL_SETPAG, new_pag));
+}
+
+/*
+ * krb5_dfs_getpag()
+ *
+ * get the current PAG. Used mostly as a test.
+ */
+
+int krb5_dfs_getpag()
+{
+ return(krb5_dfs_pag_syscall(AFSCALL_GETPAG, 0));
+}
+
+/*
+ * krb5_dfs_pag()
+ *
+ * Given a principal and local username,
+ * fork and exec the k5dcecon module to create
+ * refresh or join a new DCE/DFS
+ * Process Authentication Group (PAG)
+ *
+ * This routine should be called after krb5_kuserok has
+ * determined that this combination of local user and
+ * principal are acceptable for the local host.
+ *
+ * It should also be called after a forwarded ticket has
+ * been received, and the KRB5CCNAME environment variable
+ * has been set to point at it. k5dcecon will convert this
+ * to a new DCE context and a new pag and replace KRB5CCNAME
+ * in the environment.
+ *
+ * If there is no forwarded ticket, k5dcecon will attempt
+ * to join an existing PAG for the same principal and local
+ * user.
+ *
+ * And it should be called before access to the home directory
+ * as this may be in DFS, not accessible by root, and require
+ * the PAG to have been setup.
+ *
+ * The krb5_afs_pag can be called after this routine to
+ * use the the cache obtained by k5dcecon to get an AFS token.
+ * DEE - 7/97
+ */
+
+int krb5_dfs_pag(context, flag, principal, luser)
+ krb5_context context;
+ int flag; /* 1 if a forwarded TGT is to be used */
+ krb5_principal principal;
+ const char *luser;
+
+{
+
+ struct stat stx;
+ int fd[2];
+ int i,j;
+ int pid;
+ int new_pag;
+ int pag;
+ char newccname[MAXPATHLEN] = "";
+ char *princ;
+ int err;
+ struct sigaction newsig, oldsig;
+
+#ifdef WAIT_USES_INT
+ int wait_status;
+#else /* WAIT_USES_INT */
+ union wait wait_status;
+#endif /* WAIT_USES_INT */
+
+ if (krb5_unparse_name(context, principal, &princ))
+ return(0);
+
+ /* test if DFS is running or installed */
+ if (krb5_dfs_getpag() == -2)
+ return(0); /* DFS not running, don't try */
+
+ if (pipe(fd) == -1)
+ return(0);
+
+ /* Make sure that telnetd.c's SIGCHLD action don't happen right now... */
+ memset((char *)&newsig, 0, sizeof(newsig));
+ newsig.sa_handler = SIG_DFL;
+ sigaction(SIGCHLD, &newsig, &oldsig);
+
+ pid = fork();
+ if (pid <0)
+ return(0);
+
+ if (pid == 0) { /* child process */
+
+ close(1); /* close stdout */
+ dup(fd[1]); /* point stdout at pipe here */
+ close(fd[0]); /* don't use end of pipe here */
+ close(fd[1]); /* pipe now as stdout */
+
+ execl(K5DCECON, "k5dcecon",
+ (flag) ? "-f" : "-s" ,
+ "-l", luser,
+ "-p", princ, (char *)0);
+
+ exit(127); /* incase execl fails */
+ }
+
+ /* parent, wait for child to finish */
+
+ close(fd[1]); /* don't need this end of pipe */
+
+/* #if defined(sgi) || defined(_sgi) */
+ /* wait_status.w_status = 0; */
+ /* waitpid((pid_t) pid, &wait_status.w_status, 0); */
+/* #else */
+
+
+ wait_status = 0;
+#ifdef HAVE_WAITPID
+ err = waitpid((pid_t) pid, &wait_status, 0);
+#else /* HAVE_WAITPID */
+ err = wait4(pid, &wait_status, 0, (struct rusage *) NULL);
+#endif /* HAVE_WAITPID */
+/* #endif */
+
+ sigaction(SIGCHLD, &oldsig, 0);
+ if (WIFEXITED(wait_status)){
+ if (WEXITSTATUS(wait_status) == 0) {
+ i = 1;
+ j = 0;
+ while (i != 0) {
+ i = read(fd[0], &newccname[j], sizeof(newccname)-1-j);
+ if ( i > 0)
+ j += i;
+ if (j >= sizeof(newccname)-1)
+ i = 0;
+ }
+ close(fd[0]);
+ if (j > 0) {
+ newccname[j] = '\0';
+ esetenv("KRB5CCNAME",newccname,1);
+ sscanf(&newccname[j-8],"%8x",&new_pag);
+ if (new_pag && strncmp("FILE:/opt/dcelocal/var/security/creds/dcecred_", newccname, 46) == 0) {
+ if((pag = krb5_dfs_newpag(new_pag)) != -2) {
+ return(pag);
+ }
+ }
+ }
+ }
+ }
+ return(0); /* something not right */
+}
+
+#else /* DCE */
+
+/*
+ * krb5_dfs_pag - dummy version for the lib for systems
+ * which don't have DFS, or the needed setpag kernel code.
+ */
+
+krb5_boolean
+krb5_dfs_pag(context, principal, luser)
+ krb5_context context;
+ krb5_principal principal;
+ const char *luser;
+{
+ return(0);
+}
+
+#endif /* DCE */
diff --git a/third_party/heimdal/lib/krb5/Makefile.am b/third_party/heimdal/lib/krb5/Makefile.am
new file mode 100644
index 0000000..c1345c2
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/Makefile.am
@@ -0,0 +1,455 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+WFLAGS += $(WFLAGS_ENUM_CONV)
+
+AM_CPPFLAGS += -I../com_err -I$(srcdir)/../com_err -I../base -I$(srcdir)/../base $(INCLUDE_sqlite3) $(INCLUDE_libintl) $(INCLUDE_openssl_crypto)
+
+bin_PROGRAMS = verify_krb5_conf
+
+noinst_PROGRAMS = \
+ krbhst-test \
+ test_alname \
+ test_crypto \
+ test_forward \
+ test_get_addrs \
+ test_gic \
+ test_kuserok \
+ test_renew \
+ test_rfc3961
+
+
+noinst_LTLIBRARIES = \
+ librfc3961.la
+
+TESTS = \
+ aes-test \
+ derived-key-test \
+ n-fold-test \
+ parse-name-test \
+ pseudo-random-test \
+ store-test \
+ string-to-key-test \
+ test_acl \
+ test_addr \
+ test_cc \
+ test_config \
+ test_fx \
+ test_prf \
+ test_store \
+ test_crypto_wrapping \
+ test_keytab \
+ test_mem \
+ test_pac \
+ test_plugin \
+ test_princ \
+ test_pkinit_dh2key \
+ test_pknistkdf \
+ test_time \
+ test_expand_toks \
+ test_x500
+
+check_DATA = test_config_strings.out
+
+check_PROGRAMS = $(TESTS) test_hostname test_ap-req test_canon test_set_kvno0 \
+ test_mkforwardable
+
+LDADD = libkrb5.la \
+ $(LIB_hcrypto) \
+ $(top_builddir)/lib/asn1/libasn1.la \
+ $(top_builddir)/lib/wind/libwind.la \
+ $(LIB_heimbase) $(LIB_roken)
+
+if HAVE_KEYUTILS
+test_cc_LDADD = $(LDADD) -lkeyutils
+else
+test_cc_LDADD = $(LDADD)
+endif
+
+if PKINIT
+LIB_pkinit = ../hx509/libhx509.la
+endif
+
+if have_scc
+use_sqlite = $(LIB_sqlite3)
+endif
+
+libkrb5_la_LIBADD = \
+ $(top_builddir)/lib/asn1/libasn1.la \
+ $(top_builddir)/lib/ipc/libheim-ipcc.la \
+ $(top_builddir)/lib/wind/libwind.la \
+ $(top_builddir)/lib/base/libheimbase.la \
+ $(top_builddir)/lib/hx509/libhx509.la \
+ $(LIB_openssl_crypto) \
+ $(use_sqlite) \
+ $(LIB_com_err) \
+ $(LIB_hcrypto) \
+ $(LIB_libintl) \
+ $(LIBADD_roken) \
+ $(PTHREAD_LIBADD) \
+ $(LIB_add_key) \
+ $(LIB_door_create)
+
+librfc3961_la_LIBADD = \
+ $(top_builddir)/lib/asn1/libasn1.la \
+ $(top_builddir)/lib/ipc/libheim-ipcc.la \
+ $(top_builddir)/lib/wind/libwind.la \
+ $(LIB_pkinit) \
+ $(use_sqlite) \
+ $(LIB_com_err) \
+ $(LIB_hcrypto) \
+ $(LIB_libintl) \
+ $(LIBADD_roken) \
+ $(PTHREAD_LIBADD) \
+ $(LIB_add_key) \
+ $(LIB_door_create)
+
+lib_LTLIBRARIES = libkrb5.la
+
+ERR_FILES = krb5_err.c krb_err.c k524_err.c k5e1_err.c kx509_err.c
+
+libkrb5_la_CPPFLAGS = \
+ -DBUILD_KRB5_LIB \
+ $(AM_CPPFLAGS) \
+ -DHEIMDAL_LOCALEDIR='"$(localedir)"'
+
+librfc3961_la_CPPFLAGS = \
+ -DBUILD_KRB5_LIB \
+ $(AM_CPPFLAGS) \
+ -DHEIMDAL_LOCALEDIR='"$(localedir)"'
+
+dist_libkrb5_la_SOURCES = \
+ acache.c \
+ acl.c \
+ add_et_list.c \
+ addr_families.c \
+ an2ln_plugin.h \
+ aname_to_localname.c \
+ appdefault.c \
+ asn1_glue.c \
+ auth_context.c \
+ authdata.c \
+ build_ap_req.c \
+ build_auth.c \
+ cache.c \
+ ccache_plugin.h \
+ changepw.c \
+ codec.c \
+ config_file.c \
+ convert_creds.c \
+ constants.c \
+ context.c \
+ copy_host_realm.c \
+ crc.c \
+ creds.c \
+ crypto.c \
+ crypto.h \
+ crypto-aes-sha1.c \
+ crypto-aes-sha2.c \
+ crypto-algs.c \
+ crypto-arcfour.c \
+ crypto-des.c \
+ crypto-des-common.c \
+ crypto-des3.c \
+ crypto-evp.c \
+ crypto-null.c \
+ crypto-pk.c \
+ crypto-rand.c \
+ doxygen.c \
+ data.c \
+ db_plugin.c \
+ db_plugin.h \
+ dcache.c \
+ deprecated.c \
+ digest.c \
+ eai_to_heim_errno.c \
+ enomem.c \
+ error_string.c \
+ expand_hostname.c \
+ expand_path.c \
+ fast.c \
+ fcache.c \
+ free.c \
+ free_host_realm.c \
+ generate_seq_number.c \
+ generate_subkey.c \
+ get_addrs.c \
+ get_cred.c \
+ get_default_principal.c \
+ get_default_realm.c \
+ get_for_creds.c \
+ get_host_realm.c \
+ get_in_tkt.c \
+ get_port.c \
+ init_creds.c \
+ init_creds_pw.c \
+ kcm.c \
+ kcm.h \
+ keyblock.c \
+ keytab.c \
+ keytab_any.c \
+ keytab_file.c \
+ keytab_keyfile.c \
+ keytab_memory.c \
+ krb5_locl.h \
+ krb5-v4compat.h \
+ krcache.c \
+ krbhst.c \
+ kuserok.c \
+ kuserok_plugin.h \
+ kx509.c \
+ log.c \
+ mcache.c \
+ misc.c \
+ mk_cred.c \
+ mk_error.c \
+ mk_priv.c \
+ mk_rep.c \
+ mk_req.c \
+ mk_req_ext.c \
+ mk_safe.c \
+ mit_glue.c \
+ net_read.c \
+ net_write.c \
+ n-fold.c \
+ pac.c \
+ padata.c \
+ pcache.c \
+ pkinit.c \
+ pkinit-ec.c \
+ principal.c \
+ prog_setup.c \
+ prompter_posix.c \
+ rd_cred.c \
+ rd_error.c \
+ rd_priv.c \
+ rd_rep.c \
+ rd_req.c \
+ rd_safe.c \
+ read_message.c \
+ recvauth.c \
+ replay.c \
+ salt.c \
+ salt-aes-sha1.c \
+ salt-aes-sha2.c \
+ salt-arcfour.c \
+ salt-des.c \
+ salt-des3.c \
+ sp800-108-kdf.c \
+ scache.c \
+ send_to_kdc.c \
+ sendauth.c \
+ set_default_realm.c \
+ sock_principal.c \
+ store.c \
+ store-int.c \
+ store-int.h \
+ store_emem.c \
+ store_fd.c \
+ store_mem.c \
+ store_sock.c \
+ store_stdio.c \
+ plugin.c \
+ ticket.c \
+ time.c \
+ transited.c \
+ verify_init.c \
+ verify_user.c \
+ version.c \
+ warn.c \
+ write_message.c
+
+nodist_libkrb5_la_SOURCES = \
+ $(ERR_FILES)
+
+libkrb5_la_DEPENDENCIES = \
+ version-script.map
+
+libkrb5_la_LDFLAGS = -version-info 26:0:0
+if FRAMEWORK_COREFOUNDATION
+libkrb5_la_LDFLAGS += -framework CoreFoundation
+endif
+
+if versionscript
+libkrb5_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+endif
+
+ALL_OBJECTS = $(libkrb5_la_OBJECTS)
+ALL_OBJECTS += $(verify_krb5_conf_OBJECTS)
+ALL_OBJECTS += $(librfc3961_la_OBJECTS)
+ALL_OBJECTS += $(librfc3961_la_OBJECTS)
+ALL_OBJECTS += $(krbhst_test_OBJECTS)
+ALL_OBJECTS += $(test_alname_OBJECTS)
+ALL_OBJECTS += $(test_crypto_OBJECTS)
+ALL_OBJECTS += $(test_forward_OBJECTS)
+ALL_OBJECTS += $(test_get_addrs_OBJECTS)
+ALL_OBJECTS += $(test_gic_OBJECTS)
+ALL_OBJECTS += $(test_kuserok_OBJECTS)
+ALL_OBJECTS += $(test_renew_OBJECTS)
+ALL_OBJECTS += $(test_rfc3961_OBJECTS)
+
+$(ALL_OBJECTS): $(srcdir)/krb5-protos.h $(srcdir)/krb5-private.h
+$(ALL_OBJECTS): krb5_err.h k524_err.h k5e1_err.h \
+ krb_err.h k524_err.h kx509_err.h
+
+librfc3961_la_SOURCES = \
+ crc.c \
+ crypto.c \
+ crypto.h \
+ crypto-aes-sha1.c \
+ crypto-aes-sha2.c \
+ crypto-algs.c \
+ crypto-arcfour.c \
+ crypto-des.c \
+ crypto-des-common.c \
+ crypto-des3.c \
+ crypto-evp.c \
+ crypto-null.c \
+ crypto-pk.c \
+ crypto-rand.c \
+ crypto-stubs.c \
+ data.c \
+ enomem.c \
+ error_string.c \
+ keyblock.c \
+ n-fold.c \
+ salt.c \
+ salt-aes-sha1.c \
+ salt-aes-sha2.c \
+ salt-arcfour.c \
+ salt-des.c \
+ salt-des3.c \
+ sp800-108-kdf.c \
+ store-int.c \
+ warn.c
+
+test_rfc3961_LDADD = \
+ librfc3961.la \
+ $(top_builddir)/lib/asn1/libasn1.la \
+ $(top_builddir)/lib/wind/libwind.la \
+ $(LIB_hcrypto) \
+ $(LIB_roken)
+
+if DEVELOPER_MODE
+headerdeps = $(dist_libkrb5_la_SOURCES)
+endif
+
+$(srcdir)/krb5-protos.h: $(headerdeps)
+ @cd $(srcdir) && perl ../../cf/make-proto.pl -E KRB5_LIB -q -P comment -o krb5-protos.h $(dist_libkrb5_la_SOURCES) || rm -f krb5-protos.h
+
+$(srcdir)/krb5-private.h: $(headerdeps)
+ @cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p krb5-private.h $(dist_libkrb5_la_SOURCES) || rm -f krb5-private.h
+
+man_MANS = \
+ kerberos.8 \
+ krb5.conf.5 \
+ krb5-plugin.7 \
+ krb524_convert_creds_kdc.3 \
+ krb5_425_conv_principal.3 \
+ krb5_acl_match_file.3 \
+ krb5_aname_to_localname.3 \
+ krb5_appdefault.3 \
+ krb5_auth_context.3 \
+ krb5_c_make_checksum.3 \
+ krb5_check_transited.3 \
+ krb5_create_checksum.3 \
+ krb5_creds.3 \
+ krb5_digest.3 \
+ krb5_eai_to_heim_errno.3 \
+ krb5_encrypt.3 \
+ krb5_find_padata.3 \
+ krb5_generate_random_block.3 \
+ krb5_get_all_client_addrs.3 \
+ krb5_get_credentials.3 \
+ krb5_get_creds.3 \
+ krb5_get_forwarded_creds.3 \
+ krb5_get_in_cred.3 \
+ krb5_get_init_creds.3 \
+ krb5_get_krbhst.3 \
+ krb5_getportbyname.3 \
+ krb5_init_context.3 \
+ krb5_is_thread_safe.3 \
+ krb5_krbhst_init.3 \
+ krb5_mk_req.3 \
+ krb5_mk_safe.3 \
+ krb5_openlog.3 \
+ krb5_parse_name.3 \
+ krb5_principal.3 \
+ krb5_rcache.3 \
+ krb5_rd_error.3 \
+ krb5_rd_safe.3 \
+ krb5_set_default_realm.3 \
+ krb5_set_password.3 \
+ krb5_string_to_key.3 \
+ krb5_timeofday.3 \
+ krb5_verify_init_creds.3 \
+ krb5_verify_user.3 \
+ verify_krb5_conf.8
+
+dist_include_HEADERS = \
+ krb5.h \
+ $(srcdir)/krb5-protos.h \
+ krb5_ccapi.h
+
+noinst_HEADERS = $(srcdir)/krb5-private.h
+
+
+nodist_include_HEADERS = krb5_err.h k524_err.h k5e1_err.h kx509_err.h
+
+# XXX use nobase_include_HEADERS = krb5/locate_plugin.h
+krb5dir = $(includedir)/krb5
+krb5_HEADERS = \
+ an2ln_plugin.h \
+ ccache_plugin.h \
+ db_plugin.h \
+ kuserok_plugin.h \
+ locate_plugin.h \
+ send_to_kdc_plugin.h
+
+build_HEADERZ = \
+ $(krb5_HEADERS) \
+ krb_err.h
+
+CLEANFILES = \
+ test_config_strings.out \
+ test-store-data \
+ krb5_err.c krb5_err.h \
+ krb_err.c krb_err.h \
+ k524_err.c k524_err.h \
+ k5e1_err.c k5e1_err.h \
+ kx509_err.c kx509_err.h
+
+$(libkrb5_la_OBJECTS): krb5_err.h krb_err.h k524_err.h k5e1_err.h kx509_err.h
+
+test_config_strings.out: test_config_strings.cfg
+ $(CP) $(srcdir)/test_config_strings.cfg test_config_strings.out
+
+EXTRA_DIST = \
+ NTMakefile \
+ dll.c \
+ libkrb5-exports.def.in \
+ verify_krb5_conf-version.rc \
+ krb5_err.et \
+ krb_err.et \
+ k524_err.et \
+ k5e1_err.et \
+ kx509_err.et \
+ $(man_MANS) \
+ version-script.map \
+ test_config_strings.cfg \
+ krb5.moduli
+
+#sysconf_DATA = krb5.moduli
+
+# to help stupid solaris make
+
+krb5_err.h: krb5_err.et
+
+krb_err.h: krb_err.et
+
+k524_err.h: k524_err.et
+
+k5e1_err.h: k5e1_err.et
+
+kx509_err.h: kx509_err.et
diff --git a/third_party/heimdal/lib/krb5/NTMakefile b/third_party/heimdal/lib/krb5/NTMakefile
new file mode 100644
index 0000000..40ca0fb
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/NTMakefile
@@ -0,0 +1,544 @@
+########################################################################
+#
+# Copyright (c) 2009 - 2017, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\krb5
+
+intcflags=-I$(SRCDIR) -I$(SRCDIR)\..\com_err -I$(SRCDIR)\..\base
+
+!include ../../windows/NTMakefile.w32
+
+libkrb5_OBJS = \
+ $(OBJ)\acache.obj \
+ $(OBJ)\acl.obj \
+ $(OBJ)\add_et_list.obj \
+ $(OBJ)\addr_families.obj \
+ $(OBJ)\aname_to_localname.obj \
+ $(OBJ)\appdefault.obj \
+ $(OBJ)\asn1_glue.obj \
+ $(OBJ)\auth_context.obj \
+ $(OBJ)\authdata.obj \
+ $(OBJ)\build_ap_req.obj \
+ $(OBJ)\build_auth.obj \
+ $(OBJ)\cache.obj \
+ $(OBJ)\changepw.obj \
+ $(OBJ)\codec.obj \
+ $(OBJ)\config_file.obj \
+ $(OBJ)\constants.obj \
+ $(OBJ)\context.obj \
+ $(OBJ)\convert_creds.obj \
+ $(OBJ)\copy_host_realm.obj \
+ $(OBJ)\crc.obj \
+ $(OBJ)\creds.obj \
+ $(OBJ)\crypto.obj \
+ $(OBJ)\crypto-aes-sha1.obj \
+ $(OBJ)\crypto-aes-sha2.obj \
+ $(OBJ)\crypto-algs.obj \
+ $(OBJ)\crypto-arcfour.obj \
+ $(OBJ)\crypto-des-common.obj \
+ $(OBJ)\crypto-des.obj \
+ $(OBJ)\crypto-des3.obj \
+ $(OBJ)\crypto-evp.obj \
+ $(OBJ)\crypto-null.obj \
+ $(OBJ)\crypto-pk.obj \
+ $(OBJ)\crypto-rand.obj \
+ $(OBJ)\data.obj \
+ $(OBJ)\dcache.obj \
+ $(OBJ)\db_plugin.obj \
+ $(OBJ)\deprecated.obj \
+ $(OBJ)\digest.obj \
+ $(OBJ)\dll.obj \
+ $(OBJ)\eai_to_heim_errno.obj \
+ $(OBJ)\enomem.obj \
+ $(OBJ)\error_string.obj \
+ $(OBJ)\expand_hostname.obj \
+ $(OBJ)\expand_path.obj \
+ $(OBJ)\fast.obj \
+ $(OBJ)\fcache.obj \
+ $(OBJ)\free.obj \
+ $(OBJ)\free_host_realm.obj \
+ $(OBJ)\generate_seq_number.obj \
+ $(OBJ)\generate_subkey.obj \
+ $(OBJ)\get_addrs.obj \
+ $(OBJ)\get_cred.obj \
+ $(OBJ)\get_default_principal.obj \
+ $(OBJ)\get_default_realm.obj \
+ $(OBJ)\get_for_creds.obj \
+ $(OBJ)\get_host_realm.obj \
+ $(OBJ)\get_in_tkt.obj \
+ $(OBJ)\get_port.obj \
+ $(OBJ)\init_creds.obj \
+ $(OBJ)\init_creds_pw.obj \
+ $(OBJ)\kcm.obj \
+ $(OBJ)\keyblock.obj \
+ $(OBJ)\keytab.obj \
+ $(OBJ)\keytab_any.obj \
+ $(OBJ)\keytab_file.obj \
+ $(OBJ)\keytab_keyfile.obj \
+ $(OBJ)\keytab_memory.obj \
+ $(OBJ)\krbhst.obj \
+ $(OBJ)\kuserok.obj \
+ $(OBJ)\kx509.obj \
+ $(OBJ)\log.obj \
+ $(OBJ)\mcache.obj \
+ $(OBJ)\misc.obj \
+ $(OBJ)\mit_glue.obj \
+ $(OBJ)\mk_cred.obj \
+ $(OBJ)\mk_error.obj \
+ $(OBJ)\mk_priv.obj \
+ $(OBJ)\mk_rep.obj \
+ $(OBJ)\mk_req.obj \
+ $(OBJ)\mk_req_ext.obj \
+ $(OBJ)\mk_safe.obj \
+ $(OBJ)\net_read.obj \
+ $(OBJ)\net_write.obj \
+ $(OBJ)\n-fold.obj \
+ $(OBJ)\pac.obj \
+ $(OBJ)\padata.obj \
+ $(OBJ)\pcache.obj \
+ $(OBJ)\pkinit.obj \
+ $(OBJ)\pkinit-ec.obj \
+ $(OBJ)\plugin.obj \
+ $(OBJ)\principal.obj \
+ $(OBJ)\prog_setup.obj \
+ $(OBJ)\prompter_posix.obj \
+ $(OBJ)\rd_cred.obj \
+ $(OBJ)\rd_error.obj \
+ $(OBJ)\rd_priv.obj \
+ $(OBJ)\rd_rep.obj \
+ $(OBJ)\rd_req.obj \
+ $(OBJ)\rd_safe.obj \
+ $(OBJ)\read_message.obj \
+ $(OBJ)\recvauth.obj \
+ $(OBJ)\replay.obj \
+ $(OBJ)\salt-aes-sha1.obj \
+ $(OBJ)\salt-aes-sha2.obj \
+ $(OBJ)\salt-arcfour.obj \
+ $(OBJ)\salt-des.obj \
+ $(OBJ)\salt-des3.obj \
+ $(OBJ)\salt.obj \
+ $(OBJ)\scache.obj \
+ $(OBJ)\send_to_kdc.obj \
+ $(OBJ)\sendauth.obj \
+ $(OBJ)\set_default_realm.obj \
+ $(OBJ)\sock_principal.obj \
+ $(OBJ)\sp800-108-kdf.obj \
+ $(OBJ)\store.obj \
+ $(OBJ)\store-int.obj \
+ $(OBJ)\store_emem.obj \
+ $(OBJ)\store_fd.obj \
+ $(OBJ)\store_mem.obj \
+ $(OBJ)\store_sock.obj \
+ $(OBJ)\store_stdio.obj \
+ $(OBJ)\ticket.obj \
+ $(OBJ)\time.obj \
+ $(OBJ)\transited.obj \
+ $(OBJ)\verify_init.obj \
+ $(OBJ)\verify_user.obj \
+ $(OBJ)\version.obj \
+ $(OBJ)\warn.obj \
+ $(OBJ)\write_message.obj
+
+libkrb5_gen_OBJS= \
+ $(OBJ)\krb5_err.obj \
+ $(OBJ)\krb_err.obj \
+ $(OBJ)\k524_err.obj \
+ $(OBJ)\k5e1_err.obj
+
+INCFILES= \
+ $(INCDIR)\k524_err.h \
+ $(INCDIR)\k5e1_err.h \
+ $(INCDIR)\kx509_err.h \
+ $(INCDIR)\kcm.h \
+ $(INCDIR)\krb_err.h \
+ $(INCDIR)\krb5.h \
+ $(INCDIR)\krb5_ccapi.h \
+ $(INCDIR)\krb5_err.h \
+ $(INCDIR)\krb5_locl.h \
+ $(INCDIR)\krb5-protos.h \
+ $(INCDIR)\krb5-private.h \
+ $(INCDIR)\krb5-v4compat.h \
+ $(INCDIR)\crypto.h \
+ $(INCDIR)\an2ln_plugin.h \
+ $(INCDIR)\ccache_plugin.h \
+ $(INCDIR)\db_plugin.h \
+ $(INCDIR)\kuserok_plugin.h \
+ $(INCDIR)\locate_plugin.h \
+ $(INCDIR)\send_to_kdc_plugin.h
+
+all:: $(INCFILES)
+
+clean::
+ -$(RM) $(INCFILES)
+
+dist_libkrb5_la_SOURCES = \
+ acache.c \
+ acl.c \
+ add_et_list.c \
+ addr_families.c \
+ aname_to_localname.c \
+ appdefault.c \
+ asn1_glue.c \
+ auth_context.c \
+ authdata.c \
+ build_ap_req.c \
+ build_auth.c \
+ cache.c \
+ changepw.c \
+ codec.c \
+ config_file.c \
+ constants.c \
+ context.c \
+ copy_host_realm.c \
+ crc.c \
+ creds.c \
+ crypto.c \
+ crypto.h \
+ crypto-aes-sha1.c \
+ crypto-aes-sha2.c \
+ crypto-algs.c \
+ crypto-arcfour.c \
+ crypto-des.c \
+ crypto-des-common.c \
+ crypto-des3.c \
+ crypto-evp.c \
+ crypto-pk.c \
+ crypto-rand.c \
+ db_plugin.c \
+ doxygen.c \
+ data.c \
+ dcache.c \
+ deprecated.c \
+ digest.c \
+ eai_to_heim_errno.c \
+ enomem.c \
+ error_string.c \
+ expand_hostname.c \
+ expand_path.c \
+ fast.c \
+ fcache.c \
+ free.c \
+ free_host_realm.c \
+ generate_seq_number.c \
+ generate_subkey.c \
+ get_addrs.c \
+ get_cred.c \
+ get_default_principal.c \
+ get_default_realm.c \
+ get_for_creds.c \
+ get_host_realm.c \
+ get_in_tkt.c \
+ get_port.c \
+ init_creds.c \
+ init_creds_pw.c \
+ kcm.c \
+ kcm.h \
+ keyblock.c \
+ keytab.c \
+ keytab_any.c \
+ keytab_file.c \
+ keytab_keyfile.c \
+ keytab_memory.c \
+ krb5_locl.h \
+ krb5-v4compat.h \
+ krbhst.c \
+ kuserok.c \
+ kx509.c \
+ log.c \
+ mcache.c \
+ misc.c \
+ mk_cred.c \
+ mk_error.c \
+ mk_priv.c \
+ mk_rep.c \
+ mk_req.c \
+ mk_req_ext.c \
+ mk_safe.c \
+ mit_glue.c \
+ net_read.c \
+ net_write.c \
+ n-fold.c \
+ pac.c \
+ padata.c \
+ pkinit.c \
+ pkinit-ec.c \
+ plugin.c \
+ principal.c \
+ prog_setup.c \
+ prompter_posix.c \
+ rd_cred.c \
+ rd_error.c \
+ rd_priv.c \
+ rd_rep.c \
+ rd_req.c \
+ rd_safe.c \
+ read_message.c \
+ recvauth.c \
+ replay.c \
+ salt.c \
+ salt-aes-sha1.c \
+ salt-aes-sha2.c \
+ salt-arcfour.c \
+ salt-des.c \
+ salt-des3.c \
+ scache.c \
+ send_to_kdc.c \
+ sendauth.c \
+ set_default_realm.c \
+ sock_principal.c \
+ sp800-108-kdf.c \
+ store.c \
+ store-int.c \
+ store-int.h \
+ store_emem.c \
+ store_fd.c \
+ store_mem.c \
+ store_sock.c \
+ store_stdio.c \
+ pcache.c \
+ plugin.c \
+ ticket.c \
+ time.c \
+ transited.c \
+ verify_init.c \
+ verify_user.c \
+ version.c \
+ warn.c \
+ write_message.c
+
+$(OBJ)\krb5-protos.h: $(dist_libkrb5_la_SOURCES)
+ $(PERL) ..\..\cf\make-proto.pl -E KRB5_LIB -q -P remove -o $(OBJ)\krb5-protos.h $(dist_libkrb5_la_SOURCES) || $(RM) -f $(OBJ)\krb5-protos.h
+
+$(OBJ)\krb5-private.h: $(dist_libkrb5_la_SOURCES)
+ $(PERL) ..\..\cf\make-proto.pl -q -P remove -p $(OBJ)\krb5-private.h $(dist_libkrb5_la_SOURCES) || $(RM) -f $(OBJ)\krb5-private.h
+
+$(OBJ)\krb5_err.c $(OBJ)\krb5_err.h: krb5_err.et
+ cd $(OBJ)
+ $(BINDIR)\compile_et.exe $(SRCDIR)\krb5_err.et
+ cd $(SRCDIR)
+
+$(OBJ)\krb_err.c $(OBJ)\krb_err.h: krb_err.et
+ cd $(OBJ)
+ $(BINDIR)\compile_et.exe $(SRCDIR)\krb_err.et
+ cd $(SRCDIR)
+
+$(OBJ)\k524_err.c $(OBJ)\k524_err.h: k524_err.et
+ cd $(OBJ)
+ $(BINDIR)\compile_et.exe $(SRCDIR)\k524_err.et
+ cd $(SRCDIR)
+
+$(OBJ)\k5e1_err.c $(OBJ)\k5e1_err.h: k5e1_err.et
+ cd $(OBJ)
+ $(BINDIR)\compile_et.exe $(SRCDIR)\k5e1_err.et
+ cd $(SRCDIR)
+
+$(OBJ)\kx509_err.c $(OBJ)\kx509_err.h: kx509_err.et
+ cd $(OBJ)
+ $(BINDIR)\compile_et.exe $(SRCDIR)\kx509_err.et
+ cd $(SRCDIR)
+
+#----------------------------------------------------------------------
+# libkrb5
+
+$(LIBKRB5): $(libkrb5_OBJS) $(libkrb5_gen_OBJS)
+ $(LIBCON_C) -OUT:$@ $(LIBHEIMBASE) $(LIB_openssl_crypto) @<<
+$(libkrb5_OBJS: =
+)
+$(libkrb5_gen_OBJS: =
+)
+<<
+
+all:: $(LIBKRB5)
+
+clean::
+ -$(RM) $(LIBKRB5)
+
+$(OBJ)\libkrb5-exports.def: libkrb5-exports.def.in $(INCDIR)\config.h
+ $(CPREPROCESSOUT) libkrb5-exports.def.in > $@ || $(RM) $@
+
+all:: $(OBJ)\libkrb5-exports.def
+
+clean::
+ -$(RM) $(OBJ)\libkrb5-exports.def
+
+#----------------------------------------------------------------------
+# librfc3961
+
+librfc3961_OBJS=\
+ $(OBJ)\crc.obj \
+ $(OBJ)\crypto.obj \
+ $(OBJ)\crypto-aes-sha1.obj \
+ $(OBJ)\crypto-aes-sha2.obj \
+ $(OBJ)\crypto-algs.obj \
+ $(OBJ)\crypto-arcfour.obj \
+ $(OBJ)\crypto-des.obj \
+ $(OBJ)\crypto-des-common.obj \
+ $(OBJ)\crypto-des3.obj \
+ $(OBJ)\crypto-evp.obj \
+ $(OBJ)\crypto-null.obj \
+ $(OBJ)\crypto-pk.obj \
+ $(OBJ)\crypto-rand.obj \
+ $(OBJ)\crypto-stubs.obj \
+ $(OBJ)\data.obj \
+ $(OBJ)\error_string.obj \
+ $(OBJ)\keyblock.obj \
+ $(OBJ)\n-fold.obj \
+ $(OBJ)\salt.obj \
+ $(OBJ)\salt-aes-sha1.obj \
+ $(OBJ)\salt-aes-sha2.obj \
+ $(OBJ)\salt-arcfour.obj \
+ $(OBJ)\salt-des.obj \
+ $(OBJ)\salt-des3.obj \
+ $(OBJ)\sp800-108-kdf.obj \
+ $(OBJ)\store-int.obj \
+ $(OBJ)\warn.obj
+
+$(LIBRFC3961): $(librfc3961_OBJS)
+ $(LIBCON)
+
+all:: $(LIBRFC3961)
+
+clean::
+ -$(RM) $(LIBRFC3961)
+
+#----------------------------------------------------------------------
+# Tools
+
+all-tools:: $(BINDIR)\verify_krb5_conf.exe
+
+clean::
+ -$(RM) $(BINDIR)\verify_krb5_conf.*
+
+$(BINDIR)\verify_krb5_conf.exe: $(OBJ)\verify_krb5_conf.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBVERS) $(OBJ)\verify_krb5_conf-version.res
+ $(EXECONLINK)
+ $(EXEPREP)
+
+{}.c{$(OBJ)}.obj::
+ $(C2OBJ_P) -DBUILD_KRB5_LIB -DASN1_LIB
+
+{$(OBJ)}.c{$(OBJ)}.obj::
+ $(C2OBJ_P) -DBUILD_KRB5_LIB -DASN1_LIB
+
+#----------------------------------------------------------------------
+# Tests
+
+test:: test-binaries test-files test-run
+
+test_binaries = \
+ $(OBJ)\aes-test.exe \
+ $(OBJ)\derived-key-test.exe \
+ $(OBJ)\krbhst-test.exe \
+ $(OBJ)\n-fold-test.exe \
+ $(OBJ)\parse-name-test.exe \
+ $(OBJ)\pseudo-random-test.exe \
+ $(OBJ)\store-test.exe \
+ $(OBJ)\string-to-key-test.exe \
+ $(OBJ)\test_acl.exe \
+ $(OBJ)\test_addr.exe \
+ $(OBJ)\test_alname.exe \
+ $(OBJ)\test_cc.exe \
+ $(OBJ)\test_config.exe \
+ $(OBJ)\test_crypto.exe \
+ $(OBJ)\test_crypto_wrapping.exe \
+ $(OBJ)\test_forward.exe \
+ $(OBJ)\test_get_addrs.exe \
+ $(OBJ)\test_hostname.exe \
+ $(OBJ)\test_keytab.exe \
+ $(OBJ)\test_kuserok.exe \
+ $(OBJ)\test_mem.exe \
+ $(OBJ)\test_pac.exe \
+ $(OBJ)\test_pkinit_dh2key.exe \
+ $(OBJ)\test_pknistkdf.exe \
+ $(OBJ)\test_plugin.exe \
+ $(OBJ)\test_prf.exe \
+ $(OBJ)\test_princ.exe \
+ $(OBJ)\test_renew.exe \
+ $(OBJ)\test_store.exe \
+ $(OBJ)\test_time.exe \
+
+test-binaries: $(test_binaries) $(OBJ)\test_rfc3961.exe
+
+test-files: $(OBJ)\test_config_strings.out
+
+$(OBJ)\test_config_strings.out: test_config_strings.cfg
+ $(CP) $** $@
+
+test-run:
+ cd $(OBJ)
+ -aes-test.exe
+ -derived-key-test.exe
+ -krbhst-test.exe
+ -n-fold-test.exe
+ -parse-name-test.exe
+ -pseudo-random-test.exe
+ -store-test.exe
+ -string-to-key-test.exe
+ -test_acl.exe
+ -test_addr.exe
+# Skip alname due to lack of .k5login and "root"
+# -test_alname.exe
+ -test_cc.exe
+ -test_config.exe
+ -test_crypto.exe
+ -test_crypto_wrapping.exe
+# Skip forward due to need for existing hostname
+# -test_forward.exe
+ -test_get_addrs.exe
+ -test_hostname.exe
+ -test_keytab.exe
+# Skip kuserok requires principal and localname
+# -test_kuserok.exe
+ -test_mem.exe
+ -test_pac.exe
+ -test_pkinit_dh2key.exe
+ -test_pknistkdf.exe
+ -test_plugin.exe
+ -test_prf.exe
+ -test_renew.exe
+ -test_rfc3961.exe
+ -test_store.exe
+ -test_time.exe
+ cd $(SRCDIR)
+
+$(test_binaries): $$(@R).obj $(LIBHEIMDAL) $(LIBVERS) $(LIBROKEN) $(LIBHEIMBASE)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test_rfc3961.exe: $(OBJ)\test_rfc3961.obj $(LIBRFC3961) $(LIBHEIMDAL) $(LIBVERS) $(LIBCOMERR) $(LIBROKEN) $(LIBHEIMBASE)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(test_binaries:.exe=.obj): $$(@B).c
+ $(C2OBJ_C) -Fo$@ -Fd$(@D)\ $** -DBlah
+
+test-exports:
+ $(PERL) ..\..\cf\w32-check-exported-symbols.pl --vs version-script.map --def libkrb5-exports.def.in
+
+test:: test-exports
diff --git a/third_party/heimdal/lib/krb5/acache.c b/third_party/heimdal/lib/krb5/acache.c
new file mode 100644
index 0000000..63d56c4
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/acache.c
@@ -0,0 +1,1127 @@
+/*
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include <krb5_ccapi.h>
+
+#ifndef KCM_IS_API_CACHE
+
+static HEIMDAL_MUTEX acc_mutex = HEIMDAL_MUTEX_INITIALIZER;
+static cc_initialize_func init_func;
+static void (KRB5_CALLCONV *set_target_uid)(uid_t);
+static void (KRB5_CALLCONV *clear_target)(void);
+
+#ifdef HAVE_DLOPEN
+static void *cc_handle;
+#endif
+
+typedef struct krb5_acc {
+ char *cache_name;
+ char *cache_subsidiary;
+ cc_context_t context;
+ cc_ccache_t ccache;
+} krb5_acc;
+
+static krb5_error_code KRB5_CALLCONV acc_close(krb5_context, krb5_ccache);
+
+#define ACACHE(X) ((krb5_acc *)(X)->data.data)
+
+static const struct {
+ cc_int32 error;
+ krb5_error_code ret;
+} cc_errors[] = {
+ { ccErrBadName, KRB5_CC_BADNAME },
+ { ccErrCredentialsNotFound, KRB5_CC_NOTFOUND },
+ { ccErrCCacheNotFound, KRB5_FCC_NOFILE },
+ { ccErrContextNotFound, KRB5_CC_NOTFOUND },
+ { ccIteratorEnd, KRB5_CC_END },
+ { ccErrNoMem, KRB5_CC_NOMEM },
+ { ccErrServerUnavailable, KRB5_CC_NOSUPP },
+ { ccErrInvalidCCache, KRB5_CC_BADNAME },
+ { ccNoError, 0 }
+};
+
+static krb5_error_code
+translate_cc_error(krb5_context context, cc_int32 error)
+{
+ size_t i;
+ krb5_clear_error_message(context);
+ for(i = 0; i < sizeof(cc_errors)/sizeof(cc_errors[0]); i++)
+ if (cc_errors[i].error == error)
+ return cc_errors[i].ret;
+ return KRB5_FCC_INTERNAL;
+}
+
+static krb5_error_code
+init_ccapi(krb5_context context)
+{
+ const char *lib = NULL;
+ char *explib = NULL;
+
+ HEIMDAL_MUTEX_lock(&acc_mutex);
+ if (init_func) {
+ HEIMDAL_MUTEX_unlock(&acc_mutex);
+ if (context)
+ krb5_clear_error_message(context);
+ return 0;
+ }
+
+ if (context)
+ lib = krb5_config_get_string(context, NULL,
+ "libdefaults", "ccapi_library",
+ NULL);
+ if (lib == NULL) {
+#ifdef __APPLE__
+ lib = "/System/Library/Frameworks/Kerberos.framework/Kerberos";
+#elif defined(_WIN32)
+ lib = "%{LIBDIR}/libkrb5_cc.dll";
+#else
+ lib = "%{LIBDIR}/libkrb5_cc.so";
+#endif
+ }
+
+#ifdef HAVE_DLOPEN
+
+ if (_krb5_expand_path_tokens(context, lib, 0, &explib) == 0) {
+ cc_handle = dlopen(explib, RTLD_LAZY|RTLD_LOCAL|RTLD_GROUP);
+ free(explib);
+ }
+
+ if (cc_handle == NULL) {
+ HEIMDAL_MUTEX_unlock(&acc_mutex);
+ krb5_set_error_message(context, KRB5_CC_NOSUPP,
+ N_("Failed to load API cache module %s", "file"),
+ lib);
+ return KRB5_CC_NOSUPP;
+ }
+
+ init_func = (cc_initialize_func)dlsym(cc_handle, "cc_initialize");
+ set_target_uid = (void (KRB5_CALLCONV *)(uid_t))
+ dlsym(cc_handle, "krb5_ipc_client_set_target_uid");
+ clear_target = (void (KRB5_CALLCONV *)(void))
+ dlsym(cc_handle, "krb5_ipc_client_clear_target");
+ HEIMDAL_MUTEX_unlock(&acc_mutex);
+ if (init_func == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOSUPP,
+ N_("Failed to find cc_initialize"
+ "in %s: %s", "file, error"), lib, dlerror());
+ dlclose(cc_handle);
+ return KRB5_CC_NOSUPP;
+ }
+
+ return 0;
+#else
+ HEIMDAL_MUTEX_unlock(&acc_mutex);
+ krb5_set_error_message(context, KRB5_CC_NOSUPP,
+ N_("no support for shared object", ""));
+ return KRB5_CC_NOSUPP;
+#endif
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_heim_krb5_ipc_client_set_target_uid(uid_t uid)
+{
+ init_ccapi(NULL);
+ if (set_target_uid != NULL)
+ (*set_target_uid)(uid);
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_heim_krb5_ipc_client_clear_target(void)
+{
+ init_ccapi(NULL);
+ if (clear_target != NULL)
+ (*clear_target)();
+}
+
+static krb5_error_code
+make_cred_from_ccred(krb5_context context,
+ const cc_credentials_v5_t *incred,
+ krb5_creds *cred)
+{
+ krb5_error_code ret;
+ unsigned int i;
+
+ memset(cred, 0, sizeof(*cred));
+
+ ret = krb5_parse_name(context, incred->client, &cred->client);
+ if (ret)
+ goto fail;
+
+ ret = krb5_parse_name(context, incred->server, &cred->server);
+ if (ret)
+ goto fail;
+
+ cred->session.keytype = incred->keyblock.type;
+ cred->session.keyvalue.length = incred->keyblock.length;
+ cred->session.keyvalue.data = malloc(incred->keyblock.length);
+ if (cred->session.keyvalue.data == NULL)
+ goto nomem;
+ memcpy(cred->session.keyvalue.data, incred->keyblock.data,
+ incred->keyblock.length);
+
+ cred->times.authtime = incred->authtime;
+ cred->times.starttime = incred->starttime;
+ cred->times.endtime = incred->endtime;
+ cred->times.renew_till = incred->renew_till;
+
+ ret = krb5_data_copy(&cred->ticket,
+ incred->ticket.data,
+ incred->ticket.length);
+ if (ret)
+ goto nomem;
+
+ ret = krb5_data_copy(&cred->second_ticket,
+ incred->second_ticket.data,
+ incred->second_ticket.length);
+ if (ret)
+ goto nomem;
+
+ cred->authdata.val = NULL;
+ cred->authdata.len = 0;
+
+ cred->addresses.val = NULL;
+ cred->addresses.len = 0;
+
+ for (i = 0; incred->authdata && incred->authdata[i]; i++)
+ ;
+
+ if (i) {
+ cred->authdata.val = calloc(i, sizeof(cred->authdata.val[0]));
+ if (cred->authdata.val == NULL)
+ goto nomem;
+ cred->authdata.len = i;
+ for (i = 0; i < cred->authdata.len; i++) {
+ cred->authdata.val[i].ad_type = incred->authdata[i]->type;
+ ret = krb5_data_copy(&cred->authdata.val[i].ad_data,
+ incred->authdata[i]->data,
+ incred->authdata[i]->length);
+ if (ret)
+ goto nomem;
+ }
+ }
+
+ for (i = 0; incred->addresses && incred->addresses[i]; i++)
+ ;
+
+ if (i) {
+ cred->addresses.val = calloc(i, sizeof(cred->addresses.val[0]));
+ if (cred->addresses.val == NULL)
+ goto nomem;
+ cred->addresses.len = i;
+
+ for (i = 0; i < cred->addresses.len; i++) {
+ cred->addresses.val[i].addr_type = incred->addresses[i]->type;
+ ret = krb5_data_copy(&cred->addresses.val[i].address,
+ incred->addresses[i]->data,
+ incred->addresses[i]->length);
+ if (ret)
+ goto nomem;
+ }
+ }
+
+ cred->flags.i = 0;
+ if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_FORWARDABLE)
+ cred->flags.b.forwardable = 1;
+ if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_FORWARDED)
+ cred->flags.b.forwarded = 1;
+ if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_PROXIABLE)
+ cred->flags.b.proxiable = 1;
+ if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_PROXY)
+ cred->flags.b.proxy = 1;
+ if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_MAY_POSTDATE)
+ cred->flags.b.may_postdate = 1;
+ if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_POSTDATED)
+ cred->flags.b.postdated = 1;
+ if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_INVALID)
+ cred->flags.b.invalid = 1;
+ if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_RENEWABLE)
+ cred->flags.b.renewable = 1;
+ if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_INITIAL)
+ cred->flags.b.initial = 1;
+ if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_PRE_AUTH)
+ cred->flags.b.pre_authent = 1;
+ if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_HW_AUTH)
+ cred->flags.b.hw_authent = 1;
+ if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_TRANSIT_POLICY_CHECKED)
+ cred->flags.b.transited_policy_checked = 1;
+ if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_OK_AS_DELEGATE)
+ cred->flags.b.ok_as_delegate = 1;
+ if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_ANONYMOUS)
+ cred->flags.b.anonymous = 1;
+
+ return 0;
+
+nomem:
+ ret = krb5_enomem(context);
+
+fail:
+ krb5_free_cred_contents(context, cred);
+ return ret;
+}
+
+static void
+free_ccred(cc_credentials_v5_t *cred)
+{
+ int i;
+
+ if (cred->addresses) {
+ for (i = 0; cred->addresses[i] != 0; i++) {
+ if (cred->addresses[i]->data)
+ free(cred->addresses[i]->data);
+ free(cred->addresses[i]);
+ }
+ free(cred->addresses);
+ }
+ if (cred->server)
+ free(cred->server);
+ if (cred->client)
+ free(cred->client);
+ memset(cred, 0, sizeof(*cred));
+}
+
+static krb5_error_code
+make_ccred_from_cred(krb5_context context,
+ const krb5_creds *incred,
+ cc_credentials_v5_t *cred)
+{
+ krb5_error_code ret;
+ size_t i;
+
+ memset(cred, 0, sizeof(*cred));
+
+ ret = krb5_unparse_name(context, incred->client, &cred->client);
+ if (ret)
+ goto fail;
+
+ ret = krb5_unparse_name(context, incred->server, &cred->server);
+ if (ret)
+ goto fail;
+
+ cred->keyblock.type = incred->session.keytype;
+ cred->keyblock.length = incred->session.keyvalue.length;
+ cred->keyblock.data = incred->session.keyvalue.data;
+
+ cred->authtime = incred->times.authtime;
+ cred->starttime = incred->times.starttime;
+ cred->endtime = incred->times.endtime;
+ cred->renew_till = incred->times.renew_till;
+
+ cred->ticket.length = incred->ticket.length;
+ cred->ticket.data = incred->ticket.data;
+
+ cred->second_ticket.length = incred->second_ticket.length;
+ cred->second_ticket.data = incred->second_ticket.data;
+
+ /* XXX this one should also be filled in */
+ cred->authdata = NULL;
+
+ cred->addresses = calloc(incred->addresses.len + 1,
+ sizeof(cred->addresses[0]));
+ if (cred->addresses == NULL) {
+
+ ret = ENOMEM;
+ goto fail;
+ }
+
+ for (i = 0; i < incred->addresses.len; i++) {
+ cc_data *addr;
+ addr = malloc(sizeof(*addr));
+ if (addr == NULL) {
+ ret = ENOMEM;
+ goto fail;
+ }
+ addr->type = incred->addresses.val[i].addr_type;
+ addr->length = incred->addresses.val[i].address.length;
+ addr->data = malloc(addr->length);
+ if (addr->data == NULL) {
+ free(addr);
+ ret = ENOMEM;
+ goto fail;
+ }
+ memcpy(addr->data, incred->addresses.val[i].address.data,
+ addr->length);
+ cred->addresses[i] = addr;
+ }
+ cred->addresses[i] = NULL;
+
+ cred->ticket_flags = 0;
+ if (incred->flags.b.forwardable)
+ cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_FORWARDABLE;
+ if (incred->flags.b.forwarded)
+ cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_FORWARDED;
+ if (incred->flags.b.proxiable)
+ cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_PROXIABLE;
+ if (incred->flags.b.proxy)
+ cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_PROXY;
+ if (incred->flags.b.may_postdate)
+ cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_MAY_POSTDATE;
+ if (incred->flags.b.postdated)
+ cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_POSTDATED;
+ if (incred->flags.b.invalid)
+ cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_INVALID;
+ if (incred->flags.b.renewable)
+ cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_RENEWABLE;
+ if (incred->flags.b.initial)
+ cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_INITIAL;
+ if (incred->flags.b.pre_authent)
+ cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_PRE_AUTH;
+ if (incred->flags.b.hw_authent)
+ cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_HW_AUTH;
+ if (incred->flags.b.transited_policy_checked)
+ cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_TRANSIT_POLICY_CHECKED;
+ if (incred->flags.b.ok_as_delegate)
+ cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_OK_AS_DELEGATE;
+ if (incred->flags.b.anonymous)
+ cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_ANONYMOUS;
+
+ return 0;
+
+fail:
+ free_ccred(cred);
+
+ krb5_clear_error_message(context);
+ return ret;
+}
+
+static cc_int32
+get_cc_name(krb5_acc *a)
+{
+ cc_string_t name;
+ cc_int32 error;
+
+ error = (*a->ccache->func->get_name)(a->ccache, &name);
+ if (error)
+ return error;
+
+ a->cache_name = strdup(name->data);
+ (*name->func->release)(name);
+ if (a->cache_name == NULL)
+ return ccErrNoMem;
+ return ccNoError;
+}
+
+
+static krb5_error_code KRB5_CALLCONV
+acc_get_name_2(krb5_context context,
+ krb5_ccache id,
+ const char **name,
+ const char **colname,
+ const char **subsidiary)
+{
+ krb5_error_code ret = 0;
+ krb5_acc *a = ACACHE(id);
+ int32_t error;
+
+ if (name)
+ *name = NULL;
+ if (colname)
+ *colname = NULL;
+ if (subsidiary)
+ *subsidiary = NULL;
+ if (a->cache_subsidiary == NULL) {
+ krb5_principal principal = NULL;
+
+ ret = _krb5_get_default_principal_local(context, &principal);
+ if (ret == 0)
+ ret = krb5_unparse_name(context, principal, &a->cache_subsidiary);
+ krb5_free_principal(context, principal);
+ if (ret)
+ return ret;
+ }
+
+ if (a->cache_name == NULL) {
+ error = (*a->context->func->create_new_ccache)(a->context,
+ cc_credentials_v5,
+ a->cache_subsidiary,
+ &a->ccache);
+ if (error == ccNoError)
+ error = get_cc_name(a);
+ if (error != ccNoError)
+ ret = translate_cc_error(context, error);
+ }
+ if (name)
+ *name = a->cache_name;
+ if (colname)
+ *colname = "";
+ if (subsidiary)
+ *subsidiary = a->cache_subsidiary;
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_alloc(krb5_context context, krb5_ccache *id)
+{
+ krb5_error_code ret;
+ cc_int32 error;
+ krb5_acc *a;
+
+ ret = init_ccapi(context);
+ if (ret)
+ return ret;
+
+ ret = krb5_data_alloc(&(*id)->data, sizeof(*a));
+ if (ret) {
+ krb5_clear_error_message(context);
+ return ret;
+ }
+
+ a = ACACHE(*id);
+ a->cache_subsidiary = NULL;
+ a->cache_name = NULL;
+ a->context = NULL;
+ a->ccache = NULL;
+
+ error = (*init_func)(&a->context, ccapi_version_3, NULL, NULL);
+ if (error) {
+ krb5_data_free(&(*id)->data);
+ return translate_cc_error(context, error);
+ }
+
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_resolve_2(krb5_context context, krb5_ccache *id, const char *res, const char *sub)
+{
+ krb5_error_code ret;
+ cc_time_t offset;
+ cc_int32 error;
+ krb5_acc *a;
+ char *s = NULL;
+
+ ret = acc_alloc(context, id);
+ if (ret)
+ return ret;
+
+ a = ACACHE(*id);
+
+ if (sub) {
+ /*
+ * For API there's no such thing as a collection name, there's only the
+ * default collection. Though we could perhaps put a CCAPI shared
+ * object path in the collection name.
+ *
+ * So we'll treat (res && !sub) and (!res && sub) as the same cases.
+ *
+ * See also the KCM ccache type, where we have similar considerations.
+ */
+ if (asprintf(&s, "%s%s%s", res && *res ? res : "",
+ res && *res ? ":" : "", sub) == -1 || s == NULL ||
+ (a->cache_subsidiary = strdup(sub)) == NULL) {
+ acc_close(context, *id);
+ free(s);
+ return krb5_enomem(context);
+ }
+ res = s;
+ /*
+ * XXX With a bit of extra refactoring we could use the collection name
+ * as the path to the shared object implementing CCAPI... For now we
+ * ignore the collection name.
+ */
+ }
+
+ error = (*a->context->func->open_ccache)(a->context, res, &a->ccache);
+ if (error == ccErrCCacheNotFound) {
+ a->ccache = NULL;
+ a->cache_name = NULL;
+ free(s);
+ return 0;
+ }
+ if (error == ccNoError)
+ error = get_cc_name(a);
+ if (error != ccNoError) {
+ acc_close(context, *id);
+ *id = NULL;
+ free(s);
+ return translate_cc_error(context, error);
+ }
+
+ error = (*a->ccache->func->get_kdc_time_offset)(a->ccache,
+ cc_credentials_v5,
+ &offset);
+ if (error == 0)
+ context->kdc_sec_offset = offset;
+ free(s);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_gen_new(krb5_context context, krb5_ccache *id)
+{
+ return acc_alloc(context, id);
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_initialize(krb5_context context,
+ krb5_ccache id,
+ krb5_principal primary_principal)
+{
+ krb5_acc *a = ACACHE(id);
+ krb5_error_code ret;
+ int32_t error;
+ char *name;
+
+ ret = krb5_unparse_name(context, primary_principal, &name);
+ if (ret)
+ return ret;
+
+ if (a->cache_name == NULL) {
+ error = (*a->context->func->create_new_ccache)(a->context,
+ cc_credentials_v5,
+ name,
+ &a->ccache);
+ free(name);
+ if (error == ccNoError)
+ error = get_cc_name(a);
+ } else {
+ cc_credentials_iterator_t iter;
+ cc_credentials_t ccred;
+
+ error = (*a->ccache->func->new_credentials_iterator)(a->ccache, &iter);
+ if (error) {
+ free(name);
+ return translate_cc_error(context, error);
+ }
+
+ while (1) {
+ error = (*iter->func->next)(iter, &ccred);
+ if (error)
+ break;
+ (*a->ccache->func->remove_credentials)(a->ccache, ccred);
+ (*ccred->func->release)(ccred);
+ }
+ (*iter->func->release)(iter);
+
+ error = (*a->ccache->func->set_principal)(a->ccache,
+ cc_credentials_v5,
+ name);
+ }
+
+ if (error == 0 && context->kdc_sec_offset)
+ error = (*a->ccache->func->set_kdc_time_offset)(a->ccache,
+ cc_credentials_v5,
+ context->kdc_sec_offset);
+
+ return translate_cc_error(context, error);
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_close(krb5_context context,
+ krb5_ccache id)
+{
+ krb5_acc *a = ACACHE(id);
+
+ if (a->ccache) {
+ (*a->ccache->func->release)(a->ccache);
+ a->ccache = NULL;
+ }
+ if (a->cache_name) {
+ free(a->cache_name);
+ a->cache_name = NULL;
+ }
+ if (a->context) {
+ (*a->context->func->release)(a->context);
+ a->context = NULL;
+ }
+ krb5_data_free(&id->data);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_destroy(krb5_context context,
+ krb5_ccache id)
+{
+ krb5_acc *a = ACACHE(id);
+ cc_int32 error = 0;
+
+ if (a->ccache) {
+ error = (*a->ccache->func->destroy)(a->ccache);
+ a->ccache = NULL;
+ }
+ if (a->context) {
+ error = (a->context->func->release)(a->context);
+ a->context = NULL;
+ }
+ return translate_cc_error(context, error);
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_store_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_creds *creds)
+{
+ krb5_acc *a = ACACHE(id);
+ cc_credentials_union cred;
+ cc_credentials_v5_t v5cred;
+ krb5_error_code ret;
+ cc_int32 error;
+
+ if (a->ccache == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOTFOUND,
+ N_("No API credential found", ""));
+ return KRB5_CC_NOTFOUND;
+ }
+
+ cred.version = cc_credentials_v5;
+ cred.credentials.credentials_v5 = &v5cred;
+
+ ret = make_ccred_from_cred(context,
+ creds,
+ &v5cred);
+ if (ret)
+ return ret;
+
+ error = (*a->ccache->func->store_credentials)(a->ccache, &cred);
+ if (error)
+ ret = translate_cc_error(context, error);
+
+ free_ccred(&v5cred);
+
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_get_principal(krb5_context context,
+ krb5_ccache id,
+ krb5_principal *principal)
+{
+ krb5_acc *a = ACACHE(id);
+ krb5_error_code ret;
+ int32_t error;
+ cc_string_t name;
+
+ if (a->ccache == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOTFOUND,
+ N_("No API credential found", ""));
+ return KRB5_CC_NOTFOUND;
+ }
+
+ error = (*a->ccache->func->get_principal)(a->ccache,
+ cc_credentials_v5,
+ &name);
+ if (error)
+ return translate_cc_error(context, error);
+
+ ret = krb5_parse_name(context, name->data, principal);
+
+ (*name->func->release)(name);
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_get_first (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+ cc_credentials_iterator_t iter;
+ krb5_acc *a = ACACHE(id);
+ int32_t error;
+
+ if (a->ccache == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOTFOUND,
+ N_("No API credential found", ""));
+ return KRB5_CC_NOTFOUND;
+ }
+
+ error = (*a->ccache->func->new_credentials_iterator)(a->ccache, &iter);
+ if (error) {
+ krb5_clear_error_message(context);
+ return ENOENT;
+ }
+ *cursor = iter;
+ return 0;
+}
+
+
+static krb5_error_code KRB5_CALLCONV
+acc_get_next (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor,
+ krb5_creds *creds)
+{
+ cc_credentials_iterator_t iter = *cursor;
+ cc_credentials_t cred;
+ krb5_error_code ret;
+ int32_t error;
+
+ while (1) {
+ error = (*iter->func->next)(iter, &cred);
+ if (error)
+ return translate_cc_error(context, error);
+ if (cred->data->version == cc_credentials_v5)
+ break;
+ (*cred->func->release)(cred);
+ }
+
+ ret = make_cred_from_ccred(context,
+ cred->data->credentials.credentials_v5,
+ creds);
+ (*cred->func->release)(cred);
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_end_get (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+ cc_credentials_iterator_t iter = *cursor;
+ (*iter->func->release)(iter);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_remove_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_flags which,
+ krb5_creds *cred)
+{
+ cc_credentials_iterator_t iter;
+ krb5_acc *a = ACACHE(id);
+ cc_credentials_t ccred;
+ krb5_error_code ret;
+ cc_int32 error;
+ char *client, *server;
+
+ if (a->ccache == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOTFOUND,
+ N_("No API credential found", ""));
+ return KRB5_CC_NOTFOUND;
+ }
+
+ if (cred->client) {
+ ret = krb5_unparse_name(context, cred->client, &client);
+ if (ret)
+ return ret;
+ } else
+ client = NULL;
+
+ ret = krb5_unparse_name(context, cred->server, &server);
+ if (ret) {
+ free(client);
+ return ret;
+ }
+
+ error = (*a->ccache->func->new_credentials_iterator)(a->ccache, &iter);
+ if (error) {
+ free(server);
+ free(client);
+ return translate_cc_error(context, error);
+ }
+
+ ret = KRB5_CC_NOTFOUND;
+ while (1) {
+ cc_credentials_v5_t *v5cred;
+
+ error = (*iter->func->next)(iter, &ccred);
+ if (error)
+ break;
+
+ if (ccred->data->version != cc_credentials_v5)
+ goto next;
+
+ v5cred = ccred->data->credentials.credentials_v5;
+
+ if (client && strcmp(v5cred->client, client) != 0)
+ goto next;
+
+ if (strcmp(v5cred->server, server) != 0)
+ goto next;
+
+ (*a->ccache->func->remove_credentials)(a->ccache, ccred);
+ ret = 0;
+ next:
+ (*ccred->func->release)(ccred);
+ }
+
+ (*iter->func->release)(iter);
+
+ if (ret)
+ krb5_set_error_message(context, ret,
+ N_("Can't find credential %s in cache",
+ "principal"), server);
+ free(server);
+ free(client);
+
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_set_flags(krb5_context context,
+ krb5_ccache id,
+ krb5_flags flags)
+{
+ return 0;
+}
+
+static int KRB5_CALLCONV
+acc_get_version(krb5_context context,
+ krb5_ccache id)
+{
+ return 0;
+}
+
+struct cache_iter {
+ cc_context_t context;
+ cc_ccache_iterator_t iter;
+};
+
+static krb5_error_code KRB5_CALLCONV
+acc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor)
+{
+ struct cache_iter *iter;
+ krb5_error_code ret;
+ cc_int32 error;
+
+ ret = init_ccapi(context);
+ if (ret)
+ return ret;
+
+ iter = calloc(1, sizeof(*iter));
+ if (iter == NULL)
+ return krb5_enomem(context);
+
+ error = (*init_func)(&iter->context, ccapi_version_3, NULL, NULL);
+ if (error) {
+ free(iter);
+ return translate_cc_error(context, error);
+ }
+
+ error = (*iter->context->func->new_ccache_iterator)(iter->context,
+ &iter->iter);
+ if (error) {
+ free(iter);
+ krb5_clear_error_message(context);
+ return ENOENT;
+ }
+ *cursor = iter;
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_get_cache_next(krb5_context context, krb5_cc_cursor cursor, krb5_ccache *id)
+{
+ struct cache_iter *iter = cursor;
+ cc_ccache_t cache;
+ krb5_acc *a;
+ krb5_error_code ret;
+ int32_t error;
+
+ error = (*iter->iter->func->next)(iter->iter, &cache);
+ if (error)
+ return translate_cc_error(context, error);
+
+ ret = _krb5_cc_allocate(context, &krb5_acc_ops, id);
+ if (ret) {
+ (*cache->func->release)(cache);
+ return ret;
+ }
+
+ ret = acc_alloc(context, id);
+ if (ret) {
+ (*cache->func->release)(cache);
+ free(*id);
+ return ret;
+ }
+
+ a = ACACHE(*id);
+ a->ccache = cache;
+
+ error = get_cc_name(a);
+ if (error) {
+ acc_close(context, *id);
+ *id = NULL;
+ return translate_cc_error(context, error);
+ }
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_end_cache_get(krb5_context context, krb5_cc_cursor cursor)
+{
+ struct cache_iter *iter = cursor;
+
+ (*iter->iter->func->release)(iter->iter);
+ iter->iter = NULL;
+ (*iter->context->func->release)(iter->context);
+ iter->context = NULL;
+ free(iter);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_move(krb5_context context, krb5_ccache from, krb5_ccache to)
+{
+ krb5_error_code ret;
+ krb5_acc *afrom = ACACHE(from);
+ krb5_acc *ato = ACACHE(to);
+ int32_t error;
+
+ if (ato->ccache == NULL) {
+ cc_string_t name;
+
+ error = (*afrom->ccache->func->get_principal)(afrom->ccache,
+ cc_credentials_v5,
+ &name);
+ if (error)
+ return translate_cc_error(context, error);
+
+ error = (*ato->context->func->create_new_ccache)(ato->context,
+ cc_credentials_v5,
+ name->data,
+ &ato->ccache);
+ (*name->func->release)(name);
+ if (error)
+ return translate_cc_error(context, error);
+ }
+
+ error = (*ato->ccache->func->move)(afrom->ccache, ato->ccache);
+ ret = translate_cc_error(context, error);
+ if (ret == 0)
+ krb5_cc_destroy(context, from);
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_get_default_name(krb5_context context, char **str)
+{
+ krb5_error_code ret;
+ cc_context_t cc;
+ cc_string_t name;
+ int32_t error;
+
+ ret = init_ccapi(context);
+ if (ret)
+ return ret;
+
+ error = (*init_func)(&cc, ccapi_version_3, NULL, NULL);
+ if (error)
+ return translate_cc_error(context, error);
+
+ error = (*cc->func->get_default_ccache_name)(cc, &name);
+ if (error) {
+ (*cc->func->release)(cc);
+ return translate_cc_error(context, error);
+ }
+
+ error = asprintf(str, "API:%s", name->data);
+ (*name->func->release)(name);
+ (*cc->func->release)(cc);
+
+ if (error < 0 || *str == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_set_default(krb5_context context, krb5_ccache id)
+{
+ krb5_acc *a = ACACHE(id);
+ cc_int32 error;
+
+ if (a->ccache == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOTFOUND,
+ N_("No API credential found", ""));
+ return KRB5_CC_NOTFOUND;
+ }
+
+ error = (*a->ccache->func->set_default)(a->ccache);
+ if (error)
+ return translate_cc_error(context, error);
+
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_lastchange(krb5_context context, krb5_ccache id, krb5_timestamp *mtime)
+{
+ krb5_acc *a = ACACHE(id);
+ cc_int32 error;
+ cc_time_t t;
+
+ if (a->ccache == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOTFOUND,
+ N_("No API credential found", ""));
+ return KRB5_CC_NOTFOUND;
+ }
+
+ error = (*a->ccache->func->get_change_time)(a->ccache, &t);
+ if (error)
+ return translate_cc_error(context, error);
+
+ *mtime = t;
+
+ return 0;
+}
+
+/**
+ * Variable containing the API based credential cache implemention.
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_VARIABLE const krb5_cc_ops krb5_acc_ops = {
+ KRB5_CC_OPS_VERSION_5,
+ "API",
+ NULL,
+ NULL,
+ acc_gen_new,
+ acc_initialize,
+ acc_destroy,
+ acc_close,
+ acc_store_cred,
+ NULL, /* acc_retrieve */
+ acc_get_principal,
+ acc_get_first,
+ acc_get_next,
+ acc_end_get,
+ acc_remove_cred,
+ acc_set_flags,
+ acc_get_version,
+ acc_get_cache_first,
+ acc_get_cache_next,
+ acc_end_cache_get,
+ acc_move,
+ acc_get_default_name,
+ acc_set_default,
+ acc_lastchange,
+ NULL,
+ NULL,
+ acc_get_name_2,
+ acc_resolve_2
+};
+
+#endif
diff --git a/third_party/heimdal/lib/krb5/acl.c b/third_party/heimdal/lib/krb5/acl.c
new file mode 100644
index 0000000..d319614
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/acl.c
@@ -0,0 +1,293 @@
+/*
+ * Copyright (c) 2000 - 2002, 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include <fnmatch.h>
+
+struct acl_field {
+ enum { acl_string, acl_fnmatch, acl_retval } type;
+ union {
+ const char *cstr;
+ char **retv;
+ } u;
+ struct acl_field *next, **last;
+};
+
+static void
+free_retv(struct acl_field *acl)
+{
+ while(acl != NULL) {
+ if (acl->type == acl_retval) {
+ if (*acl->u.retv)
+ free(*acl->u.retv);
+ *acl->u.retv = NULL;
+ }
+ acl = acl->next;
+ }
+}
+
+static void
+acl_free_list(struct acl_field *acl, int retv)
+{
+ struct acl_field *next;
+ if (retv)
+ free_retv(acl);
+ while(acl != NULL) {
+ next = acl->next;
+ free(acl);
+ acl = next;
+ }
+}
+
+static krb5_error_code
+acl_parse_format(krb5_context context,
+ struct acl_field **acl_ret,
+ const char *format,
+ va_list ap)
+{
+ const char *p;
+ struct acl_field *acl = NULL, *tmp;
+
+ for(p = format; *p != '\0'; p++) {
+ tmp = malloc(sizeof(*tmp));
+ if(tmp == NULL) {
+ acl_free_list(acl, 0);
+ return krb5_enomem(context);
+ }
+ if(*p == 's') {
+ tmp->type = acl_string;
+ tmp->u.cstr = va_arg(ap, const char*);
+ } else if(*p == 'f') {
+ tmp->type = acl_fnmatch;
+ tmp->u.cstr = va_arg(ap, const char*);
+ } else if(*p == 'r') {
+ tmp->type = acl_retval;
+ tmp->u.retv = va_arg(ap, char **);
+ *tmp->u.retv = NULL;
+ } else {
+ krb5_set_error_message(context, EINVAL,
+ N_("Unknown format specifier %c while "
+ "parsing ACL", "specifier"), *p);
+ acl_free_list(acl, 0);
+ free(tmp);
+ return EINVAL;
+ }
+ tmp->next = NULL;
+ if(acl == NULL)
+ acl = tmp;
+ else
+ *acl->last = tmp;
+ acl->last = &tmp->next;
+ }
+ *acl_ret = acl;
+ return 0;
+}
+
+static krb5_boolean
+acl_match_field(krb5_context context,
+ const char *string,
+ struct acl_field *field)
+{
+ if(field->type == acl_string) {
+ return strcmp(field->u.cstr, string) == 0;
+ } else if(field->type == acl_fnmatch) {
+ return !fnmatch(field->u.cstr, string, 0);
+ } else if(field->type == acl_retval) {
+ *field->u.retv = strdup(string);
+ return TRUE;
+ }
+ return FALSE;
+}
+
+static krb5_boolean
+acl_match_acl(krb5_context context,
+ struct acl_field *acl,
+ const char *string)
+{
+ char buf[256];
+ while(strsep_copy(&string, " \t", buf, sizeof(buf)) != -1) {
+ if(buf[0] == '\0')
+ continue; /* skip ws */
+ if (acl == NULL)
+ return FALSE;
+ if(!acl_match_field(context, buf, acl)) {
+ return FALSE;
+ }
+ acl = acl->next;
+ }
+ if (acl)
+ return FALSE;
+ return TRUE;
+}
+
+/**
+ * krb5_acl_match_string matches ACL format against a string.
+ *
+ * The ACL format has three format specifiers: s, f, and r. Each
+ * specifier will retrieve one argument from the variable arguments
+ * for either matching or storing data. The input string is split up
+ * using " " (space) and "\t" (tab) as a delimiter; multiple and "\t"
+ * in a row are considered to be the same.
+ *
+ * List of format specifiers:
+ * - s Matches a string using strcmp(3) (case sensitive).
+ * - f Matches the string with fnmatch(3). Theflags
+ * argument (the last argument) passed to the fnmatch function is 0.
+ * - r Returns a copy of the string in the char ** passed in; the copy
+ * must be freed with free(3). There is no need to free(3) the
+ * string on error: the function will clean up and set the pointer
+ * to NULL.
+ *
+ * @param context Kerberos 5 context
+ * @param string string to match with
+ * @param format format to match
+ * @param ... parameter to format string
+ *
+ * @return Return an error code or 0.
+ *
+ *
+ * @code
+ * char *s;
+ *
+ * ret = krb5_acl_match_string(context, "foo", "s", "foo");
+ * if (ret)
+ * krb5_errx(context, 1, "acl didn't match");
+ * ret = krb5_acl_match_string(context, "foo foo baz/kaka",
+ * "ss", "foo", &s, "foo/\\*");
+ * if (ret) {
+ * // no need to free(s) on error
+ * assert(s == NULL);
+ * krb5_errx(context, 1, "acl didn't match");
+ * }
+ * free(s);
+ * @endcode
+ *
+ * @sa krb5_acl_match_file
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_acl_match_string(krb5_context context,
+ const char *string,
+ const char *format,
+ ...)
+{
+ krb5_error_code ret;
+ krb5_boolean found;
+ struct acl_field *acl;
+
+ va_list ap;
+ va_start(ap, format);
+ ret = acl_parse_format(context, &acl, format, ap);
+ va_end(ap);
+ if(ret)
+ return ret;
+
+ found = acl_match_acl(context, acl, string);
+ acl_free_list(acl, !found);
+ if (found) {
+ return 0;
+ } else {
+ krb5_set_error_message(context, EACCES, N_("ACL did not match", ""));
+ return EACCES;
+ }
+}
+
+/**
+ * krb5_acl_match_file matches ACL format against each line in a file
+ * using krb5_acl_match_string(). Lines starting with # are treated
+ * like comments and ignored.
+ *
+ * @param context Kerberos 5 context.
+ * @param file file with acl listed in the file.
+ * @param format format to match.
+ * @param ... parameter to format string.
+ *
+ * @return Return an error code or 0.
+ *
+ * @sa krb5_acl_match_string
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_acl_match_file(krb5_context context,
+ const char *file,
+ const char *format,
+ ...)
+{
+ krb5_error_code ret;
+ struct acl_field *acl = NULL;
+ char buf[256];
+ va_list ap;
+ FILE *f;
+ krb5_boolean found;
+
+ f = fopen(file, "r");
+ if(f == NULL) {
+ int save_errno = errno;
+ rk_strerror_r(save_errno, buf, sizeof(buf));
+ krb5_set_error_message(context, save_errno,
+ N_("open(%s): %s", "file, errno"),
+ file, buf);
+ return save_errno;
+ }
+ rk_cloexec_file(f);
+
+ va_start(ap, format);
+ ret = acl_parse_format(context, &acl, format, ap);
+ va_end(ap);
+ if(ret) {
+ fclose(f);
+ return ret;
+ }
+
+ found = FALSE;
+ while(fgets(buf, sizeof(buf), f)) {
+ if(buf[0] == '#')
+ continue;
+ if(acl_match_acl(context, acl, buf)) {
+ found = TRUE;
+ break;
+ }
+ free_retv(acl);
+ }
+
+ fclose(f);
+ acl_free_list(acl, !found);
+ if (found) {
+ return 0;
+ } else {
+ krb5_set_error_message(context, EACCES, N_("ACL did not match", ""));
+ return EACCES;
+ }
+}
diff --git a/third_party/heimdal/lib/krb5/add_et_list.c b/third_party/heimdal/lib/krb5/add_et_list.c
new file mode 100644
index 0000000..1a289ee
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/add_et_list.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ * Add a specified list of error messages to the et list in context.
+ * Call func (probably a comerr-generated function) with a pointer to
+ * the current et_list.
+ *
+ * @param context A kerberos context.
+ * @param func The generated com_err et function.
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_add_et_list(krb5_context context, void (*func)(struct et_list **))
+{
+ return heim_add_et_list(context->hcontext, func);
+}
diff --git a/third_party/heimdal/lib/krb5/addr_families.c b/third_party/heimdal/lib/krb5/addr_families.c
new file mode 100644
index 0000000..864c9cd
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/addr_families.c
@@ -0,0 +1,1574 @@
+/*
+ * Copyright (c) 1997-2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+struct addr_operations {
+ int af;
+ krb5_address_type atype;
+ size_t max_sockaddr_size;
+ krb5_error_code (*sockaddr2addr)(const struct sockaddr *, krb5_address *);
+ krb5_error_code (*sockaddr2port)(const struct sockaddr *, int16_t *);
+ void (*addr2sockaddr)(const krb5_address *, struct sockaddr *,
+ krb5_socklen_t *sa_size, int port);
+ void (*h_addr2sockaddr)(const char *, struct sockaddr *, krb5_socklen_t *, int);
+ krb5_error_code (*h_addr2addr)(const char *, krb5_address *);
+ krb5_boolean (*uninteresting)(const struct sockaddr *);
+ krb5_boolean (*is_loopback)(const struct sockaddr *);
+ void (*anyaddr)(struct sockaddr *, krb5_socklen_t *, int);
+ int (*print_addr)(const krb5_address *, char *, size_t);
+ int (*parse_addr)(krb5_context, const char*, krb5_address *);
+ int (*order_addr)(krb5_context, const krb5_address*, const krb5_address*);
+ int (*free_addr)(krb5_context, krb5_address*);
+ int (*copy_addr)(krb5_context, const krb5_address*, krb5_address*);
+ int (*mask_boundary)(krb5_context, const krb5_address*, unsigned long,
+ krb5_address*, krb5_address*);
+};
+
+/*
+ * AF_INET - aka IPv4 implementation
+ */
+
+static krb5_error_code
+ipv4_sockaddr2addr (const struct sockaddr *sa, krb5_address *a)
+{
+ const struct sockaddr_in *sin4 = (const struct sockaddr_in *)sa;
+ unsigned char buf[4];
+
+ a->addr_type = KRB5_ADDRESS_INET;
+ memcpy (buf, &sin4->sin_addr, 4);
+ return krb5_data_copy(&a->address, buf, 4);
+}
+
+static krb5_error_code
+ipv4_sockaddr2port (const struct sockaddr *sa, int16_t *port)
+{
+ const struct sockaddr_in *sin4 = (const struct sockaddr_in *)sa;
+
+ *port = sin4->sin_port;
+ return 0;
+}
+
+static void
+ipv4_addr2sockaddr (const krb5_address *a,
+ struct sockaddr *sa,
+ krb5_socklen_t *sa_size,
+ int port)
+{
+ struct sockaddr_in tmp;
+
+ memset (&tmp, 0, sizeof(tmp));
+ tmp.sin_family = AF_INET;
+ memcpy (&tmp.sin_addr, a->address.data, 4);
+ tmp.sin_port = port;
+ memcpy(sa, &tmp, min(sizeof(tmp), *sa_size));
+ *sa_size = sizeof(tmp);
+}
+
+static void
+ipv4_h_addr2sockaddr(const char *addr,
+ struct sockaddr *sa,
+ krb5_socklen_t *sa_size,
+ int port)
+{
+ struct sockaddr_in tmp;
+
+ memset (&tmp, 0, sizeof(tmp));
+ tmp.sin_family = AF_INET;
+ tmp.sin_port = port;
+ tmp.sin_addr = *((const struct in_addr *)addr);
+ memcpy(sa, &tmp, min(sizeof(tmp), *sa_size));
+ *sa_size = sizeof(tmp);
+}
+
+static krb5_error_code
+ipv4_h_addr2addr (const char *addr,
+ krb5_address *a)
+{
+ unsigned char buf[4];
+
+ a->addr_type = KRB5_ADDRESS_INET;
+ memcpy(buf, addr, 4);
+ return krb5_data_copy(&a->address, buf, 4);
+}
+
+/*
+ * Are there any addresses that should be considered `uninteresting'?
+ */
+
+static krb5_boolean
+ipv4_uninteresting (const struct sockaddr *sa)
+{
+ const struct sockaddr_in *sin4 = (const struct sockaddr_in *)sa;
+
+ if (sin4->sin_addr.s_addr == INADDR_ANY)
+ return TRUE;
+
+ return FALSE;
+}
+
+static krb5_boolean
+ipv4_is_loopback (const struct sockaddr *sa)
+{
+ const struct sockaddr_in *sin4 = (const struct sockaddr_in *)sa;
+
+ if ((ntohl(sin4->sin_addr.s_addr) >> 24) == IN_LOOPBACKNET)
+ return TRUE;
+
+ return FALSE;
+}
+
+static void
+ipv4_anyaddr (struct sockaddr *sa, krb5_socklen_t *sa_size, int port)
+{
+ struct sockaddr_in tmp;
+
+ memset (&tmp, 0, sizeof(tmp));
+ tmp.sin_family = AF_INET;
+ tmp.sin_port = port;
+ tmp.sin_addr.s_addr = INADDR_ANY;
+ memcpy(sa, &tmp, min(sizeof(tmp), *sa_size));
+ *sa_size = sizeof(tmp);
+}
+
+static int
+ipv4_print_addr (const krb5_address *addr, char *str, size_t len)
+{
+ struct in_addr ia;
+
+ memcpy (&ia, addr->address.data, 4);
+
+ return snprintf (str, len, "IPv4:%s", inet_ntoa(ia));
+}
+
+static int
+ipv4_parse_addr (krb5_context context, const char *address, krb5_address *addr)
+{
+ const char *p;
+ struct in_addr a;
+
+ p = strchr(address, ':');
+ if(p) {
+ p++;
+ if(strncasecmp(address, "ip:", p - address) != 0 &&
+ strncasecmp(address, "ip4:", p - address) != 0 &&
+ strncasecmp(address, "ipv4:", p - address) != 0 &&
+ strncasecmp(address, "inet:", p - address) != 0)
+ return -1;
+ } else
+ p = address;
+ if(inet_aton(p, &a) == 0)
+ return -1;
+ addr->addr_type = KRB5_ADDRESS_INET;
+ if(krb5_data_alloc(&addr->address, 4) != 0)
+ return -1;
+ _krb5_put_int(addr->address.data, ntohl(a.s_addr), addr->address.length);
+ return 0;
+}
+
+static int
+ipv4_mask_boundary(krb5_context context, const krb5_address *inaddr,
+ unsigned long len, krb5_address *low, krb5_address *high)
+{
+ unsigned long ia;
+ uint32_t l, h, m = 0xffffffff;
+
+ if (len > 32) {
+ krb5_set_error_message(context, KRB5_PROG_ATYPE_NOSUPP,
+ N_("IPv4 prefix too large (%ld)", "len"), len);
+ return KRB5_PROG_ATYPE_NOSUPP;
+ }
+ m = m << (32 - len);
+
+ _krb5_get_int(inaddr->address.data, &ia, inaddr->address.length);
+
+ l = ia & m;
+ h = l | ~m;
+
+ low->addr_type = KRB5_ADDRESS_INET;
+ if(krb5_data_alloc(&low->address, 4) != 0)
+ return -1;
+ _krb5_put_int(low->address.data, l, low->address.length);
+
+ high->addr_type = KRB5_ADDRESS_INET;
+ if(krb5_data_alloc(&high->address, 4) != 0) {
+ krb5_free_address(context, low);
+ return -1;
+ }
+ _krb5_put_int(high->address.data, h, high->address.length);
+
+ return 0;
+}
+
+
+/*
+ * AF_INET6 - aka IPv6 implementation
+ */
+
+#ifdef HAVE_IPV6
+
+static krb5_error_code
+ipv6_sockaddr2addr (const struct sockaddr *sa, krb5_address *a)
+{
+ const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)sa;
+
+ if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
+ unsigned char buf[4];
+
+ a->addr_type = KRB5_ADDRESS_INET;
+#ifndef IN6_ADDR_V6_TO_V4
+#ifdef IN6_EXTRACT_V4ADDR
+#define IN6_ADDR_V6_TO_V4(x) (&IN6_EXTRACT_V4ADDR(x))
+#else
+#define IN6_ADDR_V6_TO_V4(x) ((const struct in_addr *)&(x)->s6_addr[12])
+#endif
+#endif
+ memcpy (buf, IN6_ADDR_V6_TO_V4(&sin6->sin6_addr), 4);
+ return krb5_data_copy(&a->address, buf, 4);
+ } else {
+ a->addr_type = KRB5_ADDRESS_INET6;
+ return krb5_data_copy(&a->address,
+ &sin6->sin6_addr,
+ sizeof(sin6->sin6_addr));
+ }
+}
+
+static krb5_error_code
+ipv6_sockaddr2port (const struct sockaddr *sa, int16_t *port)
+{
+ const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)sa;
+
+ *port = sin6->sin6_port;
+ return 0;
+}
+
+static void
+ipv6_addr2sockaddr (const krb5_address *a,
+ struct sockaddr *sa,
+ krb5_socklen_t *sa_size,
+ int port)
+{
+ struct sockaddr_in6 tmp;
+
+ memset (&tmp, 0, sizeof(tmp));
+ tmp.sin6_family = AF_INET6;
+ memcpy (&tmp.sin6_addr, a->address.data, sizeof(tmp.sin6_addr));
+ tmp.sin6_port = port;
+ memcpy(sa, &tmp, min(sizeof(tmp), *sa_size));
+ *sa_size = sizeof(tmp);
+}
+
+static void
+ipv6_h_addr2sockaddr(const char *addr,
+ struct sockaddr *sa,
+ krb5_socklen_t *sa_size,
+ int port)
+{
+ struct sockaddr_in6 tmp;
+
+ memset (&tmp, 0, sizeof(tmp));
+ tmp.sin6_family = AF_INET6;
+ tmp.sin6_port = port;
+ tmp.sin6_addr = *((const struct in6_addr *)addr);
+ memcpy(sa, &tmp, min(sizeof(tmp), *sa_size));
+ *sa_size = sizeof(tmp);
+}
+
+static krb5_error_code
+ipv6_h_addr2addr (const char *addr,
+ krb5_address *a)
+{
+ a->addr_type = KRB5_ADDRESS_INET6;
+ return krb5_data_copy(&a->address, addr, sizeof(struct in6_addr));
+}
+
+/*
+ *
+ */
+
+static krb5_boolean
+ipv6_uninteresting (const struct sockaddr *sa)
+{
+ const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)sa;
+ const struct in6_addr *in6 = (const struct in6_addr *)&sin6->sin6_addr;
+
+ return IN6_IS_ADDR_LINKLOCAL(in6)
+ || IN6_IS_ADDR_V4COMPAT(in6);
+}
+
+static krb5_boolean
+ipv6_is_loopback (const struct sockaddr *sa)
+{
+ const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)sa;
+ const struct in6_addr *in6 = (const struct in6_addr *)&sin6->sin6_addr;
+
+ return (IN6_IS_ADDR_LOOPBACK(in6));
+}
+
+static void
+ipv6_anyaddr (struct sockaddr *sa, krb5_socklen_t *sa_size, int port)
+{
+ struct sockaddr_in6 tmp;
+
+ memset (&tmp, 0, sizeof(tmp));
+ tmp.sin6_family = AF_INET6;
+ tmp.sin6_port = port;
+ tmp.sin6_addr = in6addr_any;
+ *sa_size = sizeof(tmp);
+}
+
+static int
+ipv6_print_addr (const krb5_address *addr, char *str, size_t len)
+{
+ char buf[128], buf2[3];
+ if(inet_ntop(AF_INET6, addr->address.data, buf, sizeof(buf)) == NULL)
+ {
+ /* XXX this is pretty ugly, but better than abort() */
+ size_t i;
+ unsigned char *p = addr->address.data;
+ buf[0] = '\0';
+ for(i = 0; i < addr->address.length; i++) {
+ snprintf(buf2, sizeof(buf2), "%02x", p[i]);
+ if(i > 0 && (i & 1) == 0)
+ strlcat(buf, ":", sizeof(buf));
+ strlcat(buf, buf2, sizeof(buf));
+ }
+ }
+ return snprintf(str, len, "IPv6:%s", buf);
+}
+
+static int
+ipv6_parse_addr (krb5_context context, const char *address, krb5_address *addr)
+{
+ int ret;
+ struct in6_addr in6;
+ const char *p;
+
+ p = strchr(address, ':');
+ if(p) {
+ p++;
+ if(strncasecmp(address, "ip6:", p - address) == 0 ||
+ strncasecmp(address, "ipv6:", p - address) == 0 ||
+ strncasecmp(address, "inet6:", p - address) == 0)
+ address = p;
+ }
+
+ ret = inet_pton(AF_INET6, address, &in6.s6_addr);
+ if(ret == 1) {
+ addr->addr_type = KRB5_ADDRESS_INET6;
+ ret = krb5_data_alloc(&addr->address, sizeof(in6.s6_addr));
+ if (ret)
+ return -1;
+ memcpy(addr->address.data, in6.s6_addr, sizeof(in6.s6_addr));
+ return 0;
+ }
+ return -1;
+}
+
+static int
+ipv6_mask_boundary(krb5_context context, const krb5_address *inaddr,
+ unsigned long len, krb5_address *low, krb5_address *high)
+{
+ struct in6_addr addr, laddr, haddr;
+ uint32_t m;
+ int i, sub_len;
+
+ if (len > 128) {
+ krb5_set_error_message(context, KRB5_PROG_ATYPE_NOSUPP,
+ N_("IPv6 prefix too large (%ld)", "length"), len);
+ return KRB5_PROG_ATYPE_NOSUPP;
+ }
+
+ if (inaddr->address.length != sizeof(addr)) {
+ krb5_set_error_message(context, KRB5_PROG_ATYPE_NOSUPP,
+ N_("IPv6 addr bad length", ""));
+ return KRB5_PROG_ATYPE_NOSUPP;
+ }
+
+ memcpy(&addr, inaddr->address.data, inaddr->address.length);
+
+ for (i = 0; i < 16; i++) {
+ sub_len = min(8, len);
+
+ m = 0xff << (8 - sub_len);
+
+ laddr.s6_addr[i] = addr.s6_addr[i] & m;
+ haddr.s6_addr[i] = (addr.s6_addr[i] & m) | ~m;
+
+ if (len > 8)
+ len -= 8;
+ else
+ len = 0;
+ }
+
+ low->addr_type = KRB5_ADDRESS_INET6;
+ if (krb5_data_alloc(&low->address, sizeof(laddr.s6_addr)) != 0)
+ return -1;
+ memcpy(low->address.data, laddr.s6_addr, sizeof(laddr.s6_addr));
+
+ high->addr_type = KRB5_ADDRESS_INET6;
+ if (krb5_data_alloc(&high->address, sizeof(haddr.s6_addr)) != 0) {
+ krb5_free_address(context, low);
+ return -1;
+ }
+ memcpy(high->address.data, haddr.s6_addr, sizeof(haddr.s6_addr));
+
+ return 0;
+}
+
+#endif /* IPv6 */
+
+#ifndef HEIMDAL_SMALLER
+
+/*
+ * table
+ */
+
+#define KRB5_ADDRESS_ARANGE (-100)
+
+struct arange {
+ krb5_address low;
+ krb5_address high;
+};
+
+static int
+arange_parse_addr (krb5_context context,
+ const char *address, krb5_address *addr)
+{
+ char buf[1024], *p;
+ krb5_address low0, high0;
+ struct arange *a;
+ krb5_error_code ret;
+
+ if(strncasecmp(address, "RANGE:", 6) != 0)
+ return -1;
+
+ address += 6;
+
+ p = strrchr(address, '/');
+ if (p) {
+ krb5_addresses addrmask;
+ char *q;
+ long num;
+
+ if (strlcpy(buf, address, sizeof(buf)) > sizeof(buf))
+ return -1;
+ buf[p - address] = '\0';
+ ret = krb5_parse_address(context, buf, &addrmask);
+ if (ret)
+ return ret;
+ if(addrmask.len != 1) {
+ krb5_free_addresses(context, &addrmask);
+ return -1;
+ }
+
+ address += p - address + 1;
+
+ num = strtol(address, &q, 10);
+ if (q == address || *q != '\0' || num < 0) {
+ krb5_free_addresses(context, &addrmask);
+ return -1;
+ }
+
+ ret = krb5_address_prefixlen_boundary(context, &addrmask.val[0], num,
+ &low0, &high0);
+ krb5_free_addresses(context, &addrmask);
+ if (ret)
+ return ret;
+
+ } else {
+ krb5_addresses low, high;
+
+ strsep_copy(&address, "-", buf, sizeof(buf));
+ ret = krb5_parse_address(context, buf, &low);
+ if(ret)
+ return ret;
+ if(low.len != 1) {
+ krb5_free_addresses(context, &low);
+ return -1;
+ }
+
+ strsep_copy(&address, "-", buf, sizeof(buf));
+ ret = krb5_parse_address(context, buf, &high);
+ if(ret) {
+ krb5_free_addresses(context, &low);
+ return ret;
+ }
+
+ if(high.len != 1 || high.val[0].addr_type != low.val[0].addr_type) {
+ krb5_free_addresses(context, &low);
+ krb5_free_addresses(context, &high);
+ return -1;
+ }
+
+ ret = krb5_copy_address(context, &high.val[0], &high0);
+ if (ret == 0) {
+ ret = krb5_copy_address(context, &low.val[0], &low0);
+ if (ret)
+ krb5_free_address(context, &high0);
+ }
+ krb5_free_addresses(context, &low);
+ krb5_free_addresses(context, &high);
+ if (ret)
+ return ret;
+ }
+
+ ret = krb5_data_alloc(&addr->address, sizeof(*a));
+ if (ret) {
+ krb5_free_address(context, &low0);
+ krb5_free_address(context, &high0);
+ return ret;
+ }
+
+ addr->addr_type = KRB5_ADDRESS_ARANGE;
+ a = addr->address.data;
+
+ if(krb5_address_order(context, &low0, &high0) < 0) {
+ a->low = low0;
+ a->high = high0;
+ } else {
+ a->low = high0;
+ a->high = low0;
+ }
+ return 0;
+}
+
+static int
+arange_free (krb5_context context, krb5_address *addr)
+{
+ struct arange *a;
+ a = addr->address.data;
+ krb5_free_address(context, &a->low);
+ krb5_free_address(context, &a->high);
+ krb5_data_free(&addr->address);
+ return 0;
+}
+
+
+static int
+arange_copy (krb5_context context, const krb5_address *inaddr,
+ krb5_address *outaddr)
+{
+ krb5_error_code ret;
+ struct arange *i, *o;
+
+ outaddr->addr_type = KRB5_ADDRESS_ARANGE;
+ ret = krb5_data_alloc(&outaddr->address, sizeof(*o));
+ if(ret)
+ return ret;
+ i = inaddr->address.data;
+ o = outaddr->address.data;
+ ret = krb5_copy_address(context, &i->low, &o->low);
+ if(ret) {
+ krb5_data_free(&outaddr->address);
+ return ret;
+ }
+ ret = krb5_copy_address(context, &i->high, &o->high);
+ if(ret) {
+ krb5_free_address(context, &o->low);
+ krb5_data_free(&outaddr->address);
+ return ret;
+ }
+ return 0;
+}
+
+static int
+arange_print_addr (const krb5_address *addr, char *str, size_t len)
+{
+ struct arange *a;
+ krb5_error_code ret;
+ size_t l, size, ret_len;
+
+ a = addr->address.data;
+
+ l = strlcpy(str, "RANGE:", len);
+ ret_len = l;
+ if (l > len)
+ l = len;
+ size = l;
+
+ ret = krb5_print_address (&a->low, str + size, len - size, &l);
+ if (ret)
+ return ret;
+ ret_len += l;
+ if (len - size > l)
+ size += l;
+ else
+ size = len;
+
+ l = strlcat(str + size, "-", len - size);
+ ret_len += l;
+ if (len - size > l)
+ size += l;
+ else
+ size = len;
+
+ ret = krb5_print_address (&a->high, str + size, len - size, &l);
+ if (ret)
+ return ret;
+ ret_len += l;
+
+ return ret_len;
+}
+
+static int
+arange_order_addr(krb5_context context,
+ const krb5_address *addr1,
+ const krb5_address *addr2)
+{
+ int tmp1, tmp2, sign;
+ struct arange *a;
+ const krb5_address *a2;
+
+ if(addr1->addr_type == KRB5_ADDRESS_ARANGE) {
+ a = addr1->address.data;
+ a2 = addr2;
+ sign = 1;
+ } else if(addr2->addr_type == KRB5_ADDRESS_ARANGE) {
+ a = addr2->address.data;
+ a2 = addr1;
+ sign = -1;
+ } else {
+ abort();
+ UNREACHABLE(return 0);
+ }
+
+ if(a2->addr_type == KRB5_ADDRESS_ARANGE) {
+ struct arange *b = a2->address.data;
+ tmp1 = krb5_address_order(context, &a->low, &b->low);
+ if(tmp1 != 0)
+ return sign * tmp1;
+ return sign * krb5_address_order(context, &a->high, &b->high);
+ } else if(a2->addr_type == a->low.addr_type) {
+ tmp1 = krb5_address_order(context, &a->low, a2);
+ if(tmp1 > 0)
+ return sign;
+ tmp2 = krb5_address_order(context, &a->high, a2);
+ if(tmp2 < 0)
+ return -sign;
+ return 0;
+ } else {
+ return sign * (addr1->addr_type - addr2->addr_type);
+ }
+}
+
+#endif /* HEIMDAL_SMALLER */
+
+static int
+addrport_print_addr (const krb5_address *addr, char *str, size_t len)
+{
+ krb5_error_code ret;
+ krb5_address addr1, addr2;
+ uint16_t port = 0;
+ size_t ret_len = 0, l, size = 0;
+ krb5_storage *sp;
+
+ sp = krb5_storage_from_data((krb5_data*)rk_UNCONST(&addr->address));
+ if (sp == NULL)
+ return ENOMEM;
+
+ /* for totally obscure reasons, these are not in network byteorder */
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_LE);
+
+ krb5_storage_seek(sp, 2, SEEK_CUR); /* skip first two bytes */
+ krb5_ret_address(sp, &addr1);
+
+ krb5_storage_seek(sp, 2, SEEK_CUR); /* skip two bytes */
+ krb5_ret_address(sp, &addr2);
+ krb5_storage_free(sp);
+ if(addr2.addr_type == KRB5_ADDRESS_IPPORT && addr2.address.length == 2) {
+ unsigned long value;
+ _krb5_get_int(addr2.address.data, &value, 2);
+ port = value;
+ }
+ l = strlcpy(str, "ADDRPORT:", len);
+ ret_len += l;
+ if (len > l)
+ size += l;
+ else
+ size = len;
+
+ ret = krb5_print_address(&addr1, str + size, len - size, &l);
+ if (ret)
+ return ret;
+ ret_len += l;
+ if (len - size > l)
+ size += l;
+ else
+ size = len;
+
+ ret = snprintf(str + size, len - size, ",PORT=%u", port);
+ if (ret < 0)
+ return EINVAL;
+ ret_len += ret;
+ return ret_len;
+}
+
+static struct addr_operations at[] = {
+ {
+ AF_INET, KRB5_ADDRESS_INET, sizeof(struct sockaddr_in),
+ ipv4_sockaddr2addr,
+ ipv4_sockaddr2port,
+ ipv4_addr2sockaddr,
+ ipv4_h_addr2sockaddr,
+ ipv4_h_addr2addr,
+ ipv4_uninteresting,
+ ipv4_is_loopback,
+ ipv4_anyaddr,
+ ipv4_print_addr,
+ ipv4_parse_addr,
+ NULL,
+ NULL,
+ NULL,
+ ipv4_mask_boundary
+ },
+#ifdef HAVE_IPV6
+ {
+ AF_INET6, KRB5_ADDRESS_INET6, sizeof(struct sockaddr_in6),
+ ipv6_sockaddr2addr,
+ ipv6_sockaddr2port,
+ ipv6_addr2sockaddr,
+ ipv6_h_addr2sockaddr,
+ ipv6_h_addr2addr,
+ ipv6_uninteresting,
+ ipv6_is_loopback,
+ ipv6_anyaddr,
+ ipv6_print_addr,
+ ipv6_parse_addr,
+ NULL,
+ NULL,
+ NULL,
+ ipv6_mask_boundary
+ } ,
+#endif
+#ifndef HEIMDAL_SMALLER
+ /* fake address type */
+ {
+ KRB5_ADDRESS_ARANGE, KRB5_ADDRESS_ARANGE, sizeof(struct arange),
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ arange_print_addr,
+ arange_parse_addr,
+ arange_order_addr,
+ arange_free,
+ arange_copy,
+ NULL
+ },
+#endif
+ {
+ KRB5_ADDRESS_ADDRPORT, KRB5_ADDRESS_ADDRPORT, 0,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ addrport_print_addr,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+ }
+};
+
+static size_t num_addrs = sizeof(at) / sizeof(at[0]);
+
+static size_t max_sockaddr_size = 0;
+
+/*
+ * generic functions
+ */
+
+static struct addr_operations *
+find_af(int af)
+{
+ size_t i;
+
+ for (i = 0; i < num_addrs; i++) {
+ if (af == at[i].af)
+ return &at[i];
+ }
+ return NULL;
+}
+
+static struct addr_operations *
+find_atype(krb5_address_type atype)
+{
+ size_t i;
+
+ for (i = 0; i < num_addrs; i++) {
+ if (atype == at[i].atype)
+ return &at[i];
+ }
+ return NULL;
+}
+
+/**
+ * krb5_sockaddr2address stores a address a "struct sockaddr" sa in
+ * the krb5_address addr.
+ *
+ * @param context a Keberos context
+ * @param sa a struct sockaddr to extract the address from
+ * @param addr an Kerberos 5 address to store the address in.
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_sockaddr2address (krb5_context context,
+ const struct sockaddr *sa, krb5_address *addr)
+{
+ struct addr_operations *a = find_af(sa->sa_family);
+ if (a == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+ N_("Address family %d not supported", ""),
+ sa->sa_family);
+ return KRB5_PROG_ATYPE_NOSUPP;
+ }
+ return (*a->sockaddr2addr)(sa, addr);
+}
+
+/**
+ * krb5_sockaddr2port extracts a port (if possible) from a "struct
+ * sockaddr.
+ *
+ * @param context a Keberos context
+ * @param sa a struct sockaddr to extract the port from
+ * @param port a pointer to an int16_t store the port in.
+ *
+ * @return Return an error code or 0. Will return
+ * KRB5_PROG_ATYPE_NOSUPP in case address type is not supported.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_sockaddr2port (krb5_context context,
+ const struct sockaddr *sa, int16_t *port)
+{
+ struct addr_operations *a = find_af(sa->sa_family);
+ if (a == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+ N_("Address family %d not supported", ""),
+ sa->sa_family);
+ return KRB5_PROG_ATYPE_NOSUPP;
+ }
+ return (*a->sockaddr2port)(sa, port);
+}
+
+/**
+ * krb5_addr2sockaddr sets the "struct sockaddr sockaddr" from addr
+ * and port. The argument sa_size should initially contain the size of
+ * the sa and after the call, it will contain the actual length of the
+ * address. In case of the sa is too small to fit the whole address,
+ * the up to *sa_size will be stored, and then *sa_size will be set to
+ * the required length.
+ *
+ * @param context a Keberos context
+ * @param addr the address to copy the from
+ * @param sa the struct sockaddr that will be filled in
+ * @param sa_size pointer to length of sa, and after the call, it will
+ * contain the actual length of the address.
+ * @param port set port in sa.
+ *
+ * @return Return an error code or 0. Will return
+ * KRB5_PROG_ATYPE_NOSUPP in case address type is not supported.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_addr2sockaddr (krb5_context context,
+ const krb5_address *addr,
+ struct sockaddr *sa,
+ krb5_socklen_t *sa_size,
+ int port)
+{
+ struct addr_operations *a = find_atype(addr->addr_type);
+
+ if (a == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+ N_("Address type %d not supported",
+ "krb5_address type"),
+ addr->addr_type);
+ return KRB5_PROG_ATYPE_NOSUPP;
+ }
+ if (a->addr2sockaddr == NULL) {
+ krb5_set_error_message (context,
+ KRB5_PROG_ATYPE_NOSUPP,
+ N_("Can't convert address type %d to sockaddr", ""),
+ addr->addr_type);
+ return KRB5_PROG_ATYPE_NOSUPP;
+ }
+ (*a->addr2sockaddr)(addr, sa, sa_size, port);
+ return 0;
+}
+
+/**
+ * krb5_max_sockaddr_size returns the max size of the .Li struct
+ * sockaddr that the Kerberos library will return.
+ *
+ * @return Return an size_t of the maximum struct sockaddr.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL
+krb5_max_sockaddr_size (void)
+{
+ if (max_sockaddr_size == 0) {
+ size_t i;
+
+ for (i = 0; i < num_addrs; i++)
+ max_sockaddr_size = max(max_sockaddr_size, at[i].max_sockaddr_size);
+ }
+ return max_sockaddr_size;
+}
+
+/**
+ * krb5_sockaddr_uninteresting returns TRUE for all .Fa sa that the
+ * kerberos library thinks are uninteresting. One example are link
+ * local addresses.
+ *
+ * @param sa pointer to struct sockaddr that might be interesting.
+ *
+ * @return Return a non zero for uninteresting addresses.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_sockaddr_uninteresting(const struct sockaddr *sa)
+{
+ struct addr_operations *a = find_af(sa->sa_family);
+ if (a == NULL || a->uninteresting == NULL)
+ return TRUE;
+ return (*a->uninteresting)(sa);
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_sockaddr_is_loopback(const struct sockaddr *sa)
+{
+ struct addr_operations *a = find_af(sa->sa_family);
+ if (a == NULL || a->is_loopback == NULL)
+ return TRUE;
+ return (*a->is_loopback)(sa);
+}
+
+/**
+ * krb5_h_addr2sockaddr initializes a "struct sockaddr sa" from af and
+ * the "struct hostent" (see gethostbyname(3) ) h_addr_list
+ * component. The argument sa_size should initially contain the size
+ * of the sa, and after the call, it will contain the actual length of
+ * the address.
+ *
+ * @param context a Keberos context
+ * @param af addresses
+ * @param addr address
+ * @param sa returned struct sockaddr
+ * @param sa_size size of sa
+ * @param port port to set in sa.
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_h_addr2sockaddr (krb5_context context,
+ int af,
+ const char *addr, struct sockaddr *sa,
+ krb5_socklen_t *sa_size,
+ int port)
+{
+ struct addr_operations *a = find_af(af);
+ if (a == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+ "Address family %d not supported", af);
+ return KRB5_PROG_ATYPE_NOSUPP;
+ }
+ (*a->h_addr2sockaddr)(addr, sa, sa_size, port);
+ return 0;
+}
+
+/**
+ * krb5_h_addr2addr works like krb5_h_addr2sockaddr with the exception
+ * that it operates on a krb5_address instead of a struct sockaddr.
+ *
+ * @param context a Keberos context
+ * @param af address family
+ * @param haddr host address from struct hostent.
+ * @param addr returned krb5_address.
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_h_addr2addr (krb5_context context,
+ int af,
+ const char *haddr, krb5_address *addr)
+{
+ struct addr_operations *a = find_af(af);
+ if (a == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+ N_("Address family %d not supported", ""), af);
+ return KRB5_PROG_ATYPE_NOSUPP;
+ }
+ return (*a->h_addr2addr)(haddr, addr);
+}
+
+/**
+ * krb5_anyaddr fills in a "struct sockaddr sa" that can be used to
+ * bind(2) to. The argument sa_size should initially contain the size
+ * of the sa, and after the call, it will contain the actual length
+ * of the address.
+ *
+ * @param context a Keberos context
+ * @param af address family
+ * @param sa sockaddr
+ * @param sa_size lenght of sa.
+ * @param port for to fill into sa.
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_anyaddr (krb5_context context,
+ int af,
+ struct sockaddr *sa,
+ krb5_socklen_t *sa_size,
+ int port)
+{
+ struct addr_operations *a = find_af (af);
+
+ if (a == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+ N_("Address family %d not supported", ""), af);
+ return KRB5_PROG_ATYPE_NOSUPP;
+ }
+
+ (*a->anyaddr)(sa, sa_size, port);
+ return 0;
+}
+
+/**
+ * krb5_print_address prints the address in addr to the string string
+ * that have the length len. If ret_len is not NULL, it will be filled
+ * with the length of the string if size were unlimited (not including
+ * the final NUL) .
+ *
+ * @param addr address to be printed
+ * @param str pointer string to print the address into
+ * @param len length that will fit into area pointed to by "str".
+ * @param ret_len return length the str.
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_print_address (const krb5_address *addr,
+ char *str, size_t len, size_t *ret_len)
+{
+ struct addr_operations *a = find_atype(addr->addr_type);
+ int ret;
+
+ if (a == NULL || a->print_addr == NULL) {
+ char *s;
+ int l;
+ size_t i;
+
+ s = str;
+ l = snprintf(s, len, "TYPE_%d:", addr->addr_type);
+ if (l < 0 || (size_t)l >= len)
+ return EINVAL;
+ s += l;
+ len -= l;
+ for(i = 0; i < addr->address.length; i++) {
+ l = snprintf(s, len, "%02x", ((char*)addr->address.data)[i]);
+ if (l < 0 || (size_t)l >= len)
+ return EINVAL;
+ len -= l;
+ s += l;
+ }
+ if(ret_len != NULL)
+ *ret_len = s - str;
+ return 0;
+ }
+ ret = (*a->print_addr)(addr, str, len);
+ if (ret < 0)
+ return EINVAL;
+ if(ret_len != NULL)
+ *ret_len = ret;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_parse_address_no_lookup(krb5_context context,
+ const char *string,
+ krb5_addresses *addresses)
+{
+ int i;
+
+ addresses->len = 0;
+ addresses->val = NULL;
+
+ for(i = 0; i < num_addrs; i++) {
+ if(at[i].parse_addr) {
+ krb5_address addr;
+ if((*at[i].parse_addr)(context, string, &addr) == 0) {
+ ALLOC_SEQ(addresses, 1);
+ if (addresses->val == NULL)
+ return krb5_enomem(context);
+ addresses->val[0] = addr;
+ return 0;
+ }
+ }
+ }
+
+ return -1;
+}
+
+/**
+ * krb5_parse_address returns the resolved hostname in string to the
+ * krb5_addresses addresses .
+ *
+ * @param context a Keberos context
+ * @param string
+ * @param addresses
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_parse_address(krb5_context context,
+ const char *string,
+ krb5_addresses *addresses)
+{
+ krb5_error_code ret;
+ int i, n;
+ struct addrinfo *ai, *a;
+ struct addrinfo hint;
+ int error;
+ int save_errno;
+
+ addresses->len = 0;
+ addresses->val = NULL;
+
+ ret = _krb5_parse_address_no_lookup(context, string, addresses);
+ if (ret == 0 || ret != -1)
+ return ret;
+
+ /* if not parsed as numeric address, do a name lookup */
+ memset(&hint, 0, sizeof(hint));
+ hint.ai_family = AF_UNSPEC;
+ error = getaddrinfo (string, NULL, &hint, &ai);
+ if (error) {
+ krb5_error_code ret2;
+ save_errno = errno;
+ ret2 = krb5_eai_to_heim_errno(save_errno, error);
+ krb5_set_error_message (context, ret2, "%s: %s",
+ string, gai_strerror(error));
+ return ret2;
+ }
+
+ n = 0;
+ for (a = ai; a != NULL; a = a->ai_next)
+ ++n;
+
+ ALLOC_SEQ(addresses, n);
+ if (addresses->val == NULL) {
+ freeaddrinfo(ai);
+ return krb5_enomem(context);
+ }
+
+ addresses->len = 0;
+ for (a = ai, i = 0; a != NULL; a = a->ai_next) {
+ if (krb5_sockaddr2address (context, a->ai_addr, &addresses->val[i]))
+ continue;
+ if(krb5_address_search(context, &addresses->val[i], addresses)) {
+ krb5_free_address(context, &addresses->val[i]);
+ continue;
+ }
+ i++;
+ addresses->len = i;
+ }
+ freeaddrinfo (ai);
+ return 0;
+}
+
+/**
+ * krb5_address_order compares the addresses addr1 and addr2 so that
+ * it can be used for sorting addresses. If the addresses are the same
+ * address krb5_address_order will return 0. Behavies like memcmp(2).
+ *
+ * @param context a Keberos context
+ * @param addr1 krb5_address to compare
+ * @param addr2 krb5_address to compare
+ *
+ * @return < 0 if address addr1 in "less" then addr2. 0 if addr1 and
+ * addr2 is the same address, > 0 if addr2 is "less" then addr1.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_address_order(krb5_context context,
+ const krb5_address *addr1,
+ const krb5_address *addr2)
+{
+ /* this sucks; what if both addresses have order functions, which
+ should we call? this works for now, though */
+ struct addr_operations *a;
+ a = find_atype(addr1->addr_type);
+ if(a == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+ N_("Address family %d not supported", ""),
+ addr1->addr_type);
+ return KRB5_PROG_ATYPE_NOSUPP;
+ }
+ if(a->order_addr != NULL)
+ return (*a->order_addr)(context, addr1, addr2);
+ a = find_atype(addr2->addr_type);
+ if(a == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+ N_("Address family %d not supported", ""),
+ addr2->addr_type);
+ return KRB5_PROG_ATYPE_NOSUPP;
+ }
+ if(a->order_addr != NULL)
+ return (*a->order_addr)(context, addr1, addr2);
+
+ if(addr1->addr_type != addr2->addr_type)
+ return addr1->addr_type - addr2->addr_type;
+ if(addr1->address.length != addr2->address.length)
+ return addr1->address.length - addr2->address.length;
+ return memcmp (addr1->address.data,
+ addr2->address.data,
+ addr1->address.length);
+}
+
+/**
+ * krb5_address_compare compares the addresses addr1 and addr2.
+ * Returns TRUE if the two addresses are the same.
+ *
+ * @param context a Keberos context
+ * @param addr1 address to compare
+ * @param addr2 address to compare
+ *
+ * @return Return an TRUE is the address are the same FALSE if not
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_address_compare(krb5_context context,
+ const krb5_address *addr1,
+ const krb5_address *addr2)
+{
+ return krb5_address_order (context, addr1, addr2) == 0;
+}
+
+/**
+ * krb5_address_search checks if the address addr is a member of the
+ * address set list addrlist .
+ *
+ * @param context a Keberos context.
+ * @param addr address to search for.
+ * @param addrlist list of addresses to look in for addr.
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_address_search(krb5_context context,
+ const krb5_address *addr,
+ const krb5_addresses *addrlist)
+{
+ size_t i;
+
+ for (i = 0; i < addrlist->len; ++i)
+ if (krb5_address_compare (context, addr, &addrlist->val[i]))
+ return TRUE;
+ return FALSE;
+}
+
+/**
+ * krb5_free_address frees the data stored in the address that is
+ * alloced with any of the krb5_address functions.
+ *
+ * @param context a Keberos context
+ * @param address addresss to be freed.
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_free_address(krb5_context context,
+ krb5_address *address)
+{
+ struct addr_operations *a = find_atype (address->addr_type);
+ if(a != NULL && a->free_addr != NULL)
+ return (*a->free_addr)(context, address);
+ krb5_data_free (&address->address);
+ memset(address, 0, sizeof(*address));
+ return 0;
+}
+
+/**
+ * krb5_free_addresses frees the data stored in the address that is
+ * alloced with any of the krb5_address functions.
+ *
+ * @param context a Keberos context
+ * @param addresses addressses to be freed.
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_free_addresses(krb5_context context,
+ krb5_addresses *addresses)
+{
+ free_HostAddresses(addresses);
+ return 0;
+}
+
+/**
+ * krb5_copy_address copies the content of address
+ * inaddr to outaddr.
+ *
+ * @param context a Keberos context
+ * @param inaddr pointer to source address
+ * @param outaddr pointer to destination address
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_address(krb5_context context,
+ const krb5_address *inaddr,
+ krb5_address *outaddr)
+{
+ struct addr_operations *a = find_af (inaddr->addr_type);
+ if(a != NULL && a->copy_addr != NULL)
+ return (*a->copy_addr)(context, inaddr, outaddr);
+ return copy_HostAddress(inaddr, outaddr);
+}
+
+/**
+ * krb5_copy_addresses copies the content of addresses
+ * inaddr to outaddr.
+ *
+ * @param context a Keberos context
+ * @param inaddr pointer to source addresses
+ * @param outaddr pointer to destination addresses
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_addresses(krb5_context context,
+ const krb5_addresses *inaddr,
+ krb5_addresses *outaddr)
+{
+ size_t i;
+ ALLOC_SEQ(outaddr, inaddr->len);
+ if(inaddr->len > 0 && outaddr->val == NULL)
+ return krb5_enomem(context);
+ for(i = 0; i < inaddr->len; i++)
+ krb5_copy_address(context, &inaddr->val[i], &outaddr->val[i]);
+ return 0;
+}
+
+/**
+ * krb5_append_addresses adds the set of addresses in source to
+ * dest. While copying the addresses, duplicates are also sorted out.
+ *
+ * @param context a Keberos context
+ * @param dest destination of copy operation
+ * @param source adresses that are going to be added to dest
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_append_addresses(krb5_context context,
+ krb5_addresses *dest,
+ const krb5_addresses *source)
+{
+ krb5_address *tmp;
+ krb5_error_code ret;
+ size_t i;
+ if(source->len > 0) {
+ tmp = realloc(dest->val, (dest->len + source->len) * sizeof(*tmp));
+ if (tmp == NULL)
+ return krb5_enomem(context);
+ dest->val = tmp;
+ for(i = 0; i < source->len; i++) {
+ /* skip duplicates */
+ if(krb5_address_search(context, &source->val[i], dest))
+ continue;
+ ret = krb5_copy_address(context,
+ &source->val[i],
+ &dest->val[dest->len]);
+ if(ret)
+ return ret;
+ dest->len++;
+ }
+ }
+ return 0;
+}
+
+/**
+ * Create an address of type KRB5_ADDRESS_ADDRPORT from (addr, port)
+ *
+ * @param context a Keberos context
+ * @param res built address from addr/port
+ * @param addr address to use
+ * @param port port to use
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_make_addrport (krb5_context context,
+ krb5_address **res, const krb5_address *addr, int16_t port)
+{
+ krb5_error_code ret;
+ size_t len = addr->address.length + 2 + 4 * 4;
+ u_char *p;
+
+ /* XXX Make this assume port == 0 -> port is absent */
+
+ *res = malloc (sizeof(**res));
+ if (*res == NULL)
+ return krb5_enomem(context);
+ (*res)->addr_type = KRB5_ADDRESS_ADDRPORT;
+ ret = krb5_data_alloc (&(*res)->address, len);
+ if (ret) {
+ free (*res);
+ *res = NULL;
+ return krb5_enomem(context);
+ }
+ p = (*res)->address.data;
+ *p++ = 0;
+ *p++ = 0;
+ *p++ = (addr->addr_type ) & 0xFF;
+ *p++ = (addr->addr_type >> 8) & 0xFF;
+
+ *p++ = (addr->address.length ) & 0xFF;
+ *p++ = (addr->address.length >> 8) & 0xFF;
+ *p++ = (addr->address.length >> 16) & 0xFF;
+ *p++ = (addr->address.length >> 24) & 0xFF;
+
+ memcpy (p, addr->address.data, addr->address.length);
+ p += addr->address.length;
+
+ *p++ = 0;
+ *p++ = 0;
+ *p++ = (KRB5_ADDRESS_IPPORT ) & 0xFF;
+ *p++ = (KRB5_ADDRESS_IPPORT >> 8) & 0xFF;
+
+ *p++ = (2 ) & 0xFF;
+ *p++ = (2 >> 8) & 0xFF;
+ *p++ = (2 >> 16) & 0xFF;
+ *p++ = (2 >> 24) & 0xFF;
+
+ memcpy (p, &port, 2);
+
+ return 0;
+}
+
+/**
+ * Calculate the boundary addresses of `inaddr'/`prefixlen' and store
+ * them in `low' and `high'.
+ *
+ * @param context a Keberos context
+ * @param inaddr address in prefixlen that the bondery searched
+ * @param prefixlen width of boundery
+ * @param low lowest address
+ * @param high highest address
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_address
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_address_prefixlen_boundary(krb5_context context,
+ const krb5_address *inaddr,
+ unsigned long prefixlen,
+ krb5_address *low,
+ krb5_address *high)
+{
+ struct addr_operations *a = find_atype (inaddr->addr_type);
+ if(a != NULL && a->mask_boundary != NULL)
+ return (*a->mask_boundary)(context, inaddr, prefixlen, low, high);
+ krb5_set_error_message(context, KRB5_PROG_ATYPE_NOSUPP,
+ N_("Address family %d doesn't support "
+ "address mask operation", ""),
+ inaddr->addr_type);
+ return KRB5_PROG_ATYPE_NOSUPP;
+}
diff --git a/third_party/heimdal/lib/krb5/aes-test.c b/third_party/heimdal/lib/krb5/aes-test.c
new file mode 100644
index 0000000..01522dd
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/aes-test.c
@@ -0,0 +1,1056 @@
+/*
+ * Copyright (c) 2003-2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <hex.h>
+#include <err.h>
+#include <assert.h>
+
+static int verbose = 0;
+
+static void
+hex_dump_data(const void *data, size_t length)
+{
+ char *p;
+
+ hex_encode(data, length, &p);
+ printf("%s\n", p);
+ free(p);
+}
+
+struct {
+ char *password;
+ char *salt;
+ int saltlen;
+ int iterations;
+ krb5_enctype enctype;
+ size_t keylen;
+ char *pbkdf2;
+ char *key;
+} keys[] = {
+ {
+ "password",
+ "\x10\xDF\x9D\xD7\x83\xE5\xBC\x8A\xCE\xA1\x73\x0E\x74\x35\x5F\x61"
+ "ATHENA.MIT.EDUraeburn",
+ 37,
+ 32768,
+ KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128,
+ 16,
+ NULL,
+ "\x08\x9B\xCA\x48\xB1\x05\xEA\x6E\xA7\x7C\xA5\xD2\xF3\x9D\xC5\xE7"
+ },
+ {
+ "password",
+ "\x10\xDF\x9D\xD7\x83\xE5\xBC\x8A\xCE\xA1\x73\x0E\x74\x35\x5F\x61"
+ "ATHENA.MIT.EDUraeburn",
+ 37,
+ 32768,
+ KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192,
+ 32,
+ NULL,
+ "\x45\xBD\x80\x6D\xBF\x6A\x83\x3A\x9C\xFF\xC1\xC9\x45\x89\xA2\x22"
+ "\x36\x7A\x79\xBC\x21\xC4\x13\x71\x89\x06\xE9\xF5\x78\xA7\x84\x67"
+ },
+ {
+ "password", "ATHENA.MIT.EDUraeburn", -1,
+ 1,
+ ETYPE_AES128_CTS_HMAC_SHA1_96, 16,
+ "\xcd\xed\xb5\x28\x1b\xb2\xf8\x01\x56\x5a\x11\x22\xb2\x56\x35\x15",
+ "\x42\x26\x3c\x6e\x89\xf4\xfc\x28\xb8\xdf\x68\xee\x09\x79\x9f\x15"
+ },
+ {
+ "password", "ATHENA.MIT.EDUraeburn", -1,
+ 1,
+ ETYPE_AES256_CTS_HMAC_SHA1_96, 32,
+ "\xcd\xed\xb5\x28\x1b\xb2\xf8\x01\x56\x5a\x11\x22\xb2\x56\x35\x15"
+ "\x0a\xd1\xf7\xa0\x4b\xb9\xf3\xa3\x33\xec\xc0\xe2\xe1\xf7\x08\x37",
+ "\xfe\x69\x7b\x52\xbc\x0d\x3c\xe1\x44\x32\xba\x03\x6a\x92\xe6\x5b"
+ "\xbb\x52\x28\x09\x90\xa2\xfa\x27\x88\x39\x98\xd7\x2a\xf3\x01\x61"
+ },
+ {
+ "password", "ATHENA.MIT.EDUraeburn", -1,
+ 2,
+ ETYPE_AES128_CTS_HMAC_SHA1_96, 16,
+ "\x01\xdb\xee\x7f\x4a\x9e\x24\x3e\x98\x8b\x62\xc7\x3c\xda\x93\x5d",
+ "\xc6\x51\xbf\x29\xe2\x30\x0a\xc2\x7f\xa4\x69\xd6\x93\xbd\xda\x13"
+ },
+ {
+ "password", "ATHENA.MIT.EDUraeburn", -1,
+ 2,
+ ETYPE_AES256_CTS_HMAC_SHA1_96, 32,
+ "\x01\xdb\xee\x7f\x4a\x9e\x24\x3e\x98\x8b\x62\xc7\x3c\xda\x93\x5d"
+ "\xa0\x53\x78\xb9\x32\x44\xec\x8f\x48\xa9\x9e\x61\xad\x79\x9d\x86",
+ "\xa2\xe1\x6d\x16\xb3\x60\x69\xc1\x35\xd5\xe9\xd2\xe2\x5f\x89\x61"
+ "\x02\x68\x56\x18\xb9\x59\x14\xb4\x67\xc6\x76\x22\x22\x58\x24\xff"
+ },
+ {
+ "password", "ATHENA.MIT.EDUraeburn", -1,
+ 1200,
+ ETYPE_AES128_CTS_HMAC_SHA1_96, 16,
+ "\x5c\x08\xeb\x61\xfd\xf7\x1e\x4e\x4e\xc3\xcf\x6b\xa1\xf5\x51\x2b",
+ "\x4c\x01\xcd\x46\xd6\x32\xd0\x1e\x6d\xbe\x23\x0a\x01\xed\x64\x2a"
+ },
+ {
+ "password", "ATHENA.MIT.EDUraeburn", -1,
+ 1200,
+ ETYPE_AES256_CTS_HMAC_SHA1_96, 32,
+ "\x5c\x08\xeb\x61\xfd\xf7\x1e\x4e\x4e\xc3\xcf\x6b\xa1\xf5\x51\x2b"
+ "\xa7\xe5\x2d\xdb\xc5\xe5\x14\x2f\x70\x8a\x31\xe2\xe6\x2b\x1e\x13",
+ "\x55\xa6\xac\x74\x0a\xd1\x7b\x48\x46\x94\x10\x51\xe1\xe8\xb0\xa7"
+ "\x54\x8d\x93\xb0\xab\x30\xa8\xbc\x3f\xf1\x62\x80\x38\x2b\x8c\x2a"
+ },
+ {
+ "password", "\x12\x34\x56\x78\x78\x56\x34\x12", 8,
+ 5,
+ ETYPE_AES128_CTS_HMAC_SHA1_96, 16,
+ "\xd1\xda\xa7\x86\x15\xf2\x87\xe6\xa1\xc8\xb1\x20\xd7\x06\x2a\x49",
+ "\xe9\xb2\x3d\x52\x27\x37\x47\xdd\x5c\x35\xcb\x55\xbe\x61\x9d\x8e"
+ },
+ {
+ "password", "\x12\x34\x56\x78\x78\x56\x34\x12", 8,
+ 5,
+ ETYPE_AES256_CTS_HMAC_SHA1_96, 32,
+ "\xd1\xda\xa7\x86\x15\xf2\x87\xe6\xa1\xc8\xb1\x20\xd7\x06\x2a\x49"
+ "\x3f\x98\xd2\x03\xe6\xbe\x49\xa6\xad\xf4\xfa\x57\x4b\x6e\x64\xee",
+ "\x97\xa4\xe7\x86\xbe\x20\xd8\x1a\x38\x2d\x5e\xbc\x96\xd5\x90\x9c"
+ "\xab\xcd\xad\xc8\x7c\xa4\x8f\x57\x45\x04\x15\x9f\x16\xc3\x6e\x31"
+ },
+ {
+ "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
+ "pass phrase equals block size", -1,
+ 1200,
+ ETYPE_AES128_CTS_HMAC_SHA1_96, 16,
+ "\x13\x9c\x30\xc0\x96\x6b\xc3\x2b\xa5\x5f\xdb\xf2\x12\x53\x0a\xc9",
+ "\x59\xd1\xbb\x78\x9a\x82\x8b\x1a\xa5\x4e\xf9\xc2\x88\x3f\x69\xed"
+ },
+ {
+ "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
+ "pass phrase equals block size", -1,
+ 1200,
+ ETYPE_AES256_CTS_HMAC_SHA1_96, 32,
+ "\x13\x9c\x30\xc0\x96\x6b\xc3\x2b\xa5\x5f\xdb\xf2\x12\x53\x0a\xc9"
+ "\xc5\xec\x59\xf1\xa4\x52\xf5\xcc\x9a\xd9\x40\xfe\xa0\x59\x8e\xd1",
+ "\x89\xad\xee\x36\x08\xdb\x8b\xc7\x1f\x1b\xfb\xfe\x45\x94\x86\xb0"
+ "\x56\x18\xb7\x0c\xba\xe2\x20\x92\x53\x4e\x56\xc5\x53\xba\x4b\x34"
+ },
+ {
+ "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
+ "pass phrase exceeds block size", -1,
+ 1200,
+ ETYPE_AES128_CTS_HMAC_SHA1_96, 16,
+ "\x9c\xca\xd6\xd4\x68\x77\x0c\xd5\x1b\x10\xe6\xa6\x87\x21\xbe\x61",
+ "\xcb\x80\x05\xdc\x5f\x90\x17\x9a\x7f\x02\x10\x4c\x00\x18\x75\x1d"
+ },
+ {
+ "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
+ "pass phrase exceeds block size", -1,
+ 1200,
+ ETYPE_AES256_CTS_HMAC_SHA1_96, 32,
+ "\x9c\xca\xd6\xd4\x68\x77\x0c\xd5\x1b\x10\xe6\xa6\x87\x21\xbe\x61"
+ "\x1a\x8b\x4d\x28\x26\x01\xdb\x3b\x36\xbe\x92\x46\x91\x5e\xc8\x2a",
+ "\xd7\x8c\x5c\x9c\xb8\x72\xa8\xc9\xda\xd4\x69\x7f\x0b\xb5\xb2\xd2"
+ "\x14\x96\xc8\x2b\xeb\x2c\xae\xda\x21\x12\xfc\xee\xa0\x57\x40\x1b"
+ },
+ {
+ "\xf0\x9d\x84\x9e" /* g-clef */, "EXAMPLE.COMpianist", -1,
+ 50,
+ ETYPE_AES128_CTS_HMAC_SHA1_96, 16,
+ "\x6b\x9c\xf2\x6d\x45\x45\x5a\x43\xa5\xb8\xbb\x27\x6a\x40\x3b\x39",
+ "\xf1\x49\xc1\xf2\xe1\x54\xa7\x34\x52\xd4\x3e\x7f\xe6\x2a\x56\xe5"
+ },
+ {
+ "\xf0\x9d\x84\x9e" /* g-clef */, "EXAMPLE.COMpianist", -1,
+ 50,
+ ETYPE_AES256_CTS_HMAC_SHA1_96, 32,
+ "\x6b\x9c\xf2\x6d\x45\x45\x5a\x43\xa5\xb8\xbb\x27\x6a\x40\x3b\x39"
+ "\xe7\xfe\x37\xa0\xc4\x1e\x02\xc2\x81\xff\x30\x69\xe1\xe9\x4f\x52",
+ "\x4b\x6d\x98\x39\xf8\x44\x06\xdf\x1f\x09\xcc\x16\x6d\xb4\xb8\x3c"
+ "\x57\x18\x48\xb7\x84\xa3\xd6\xbd\xc3\x46\x58\x9a\x3e\x39\x3f\x9e"
+ },
+ {
+ "foo", "", -1,
+ 0,
+ ETYPE_ARCFOUR_HMAC_MD5, 16,
+ NULL,
+ "\xac\x8e\x65\x7f\x83\xdf\x82\xbe\xea\x5d\x43\xbd\xaf\x78\x00\xcc"
+ },
+ {
+ "test", "", -1,
+ 0,
+ ETYPE_ARCFOUR_HMAC_MD5, 16,
+ NULL,
+ "\x0c\xb6\x94\x88\x05\xf7\x97\xbf\x2a\x82\x80\x79\x73\xb8\x95\x37"
+ }
+};
+
+static int
+string_to_key_test(krb5_context context)
+{
+ krb5_data password, opaque;
+ krb5_error_code ret;
+ krb5_salt salt;
+ int i, val = 0;
+ char iter[4];
+
+ for (i = 0; i < sizeof(keys)/sizeof(keys[0]); i++) {
+
+ password.data = keys[i].password;
+ password.length = strlen(password.data);
+
+ salt.salttype = KRB5_PW_SALT;
+ salt.saltvalue.data = keys[i].salt;
+ if (keys[i].saltlen == -1)
+ salt.saltvalue.length = strlen(salt.saltvalue.data);
+ else
+ salt.saltvalue.length = keys[i].saltlen;
+
+ opaque.data = iter;
+ opaque.length = sizeof(iter);
+ _krb5_put_int(iter, keys[i].iterations, 4);
+
+ if (keys[i].pbkdf2) {
+ unsigned char keyout[32];
+
+ if (keys[i].keylen > sizeof(keyout))
+ abort();
+
+ PKCS5_PBKDF2_HMAC(password.data, password.length,
+ salt.saltvalue.data, salt.saltvalue.length,
+ keys[i].iterations, EVP_sha1(),
+ keys[i].keylen, keyout);
+
+ if (memcmp(keyout, keys[i].pbkdf2, keys[i].keylen) != 0) {
+ krb5_warnx(context, "%d: pbkdf2", i);
+ val = 1;
+ hex_dump_data(keyout, keys[i].keylen);
+ continue;
+ }
+
+ if (verbose) {
+ printf("PBKDF2:\n");
+ hex_dump_data(keyout, keys[i].keylen);
+ }
+ }
+
+ {
+ krb5_keyblock key;
+
+ ret = krb5_string_to_key_data_salt_opaque (context,
+ keys[i].enctype,
+ password,
+ salt,
+ opaque,
+ &key);
+ if (ret) {
+ krb5_warn(context, ret, "%d: string_to_key_data_salt_opaque",
+ i);
+ val = 1;
+ continue;
+ }
+
+ if (key.keyvalue.length != keys[i].keylen) {
+ krb5_warnx(context, "%d: key wrong length (%lu/%lu)",
+ i, (unsigned long)key.keyvalue.length,
+ (unsigned long)keys[i].keylen);
+ val = 1;
+ continue;
+ }
+
+ if (memcmp(key.keyvalue.data, keys[i].key, keys[i].keylen) != 0) {
+ krb5_warnx(context, "%d: key wrong", i);
+ val = 1;
+ hex_dump_data(key.keyvalue.data, key.keyvalue.length);
+ hex_dump_data(keys[i].key, keys[i].keylen);
+ continue;
+ }
+
+ if (verbose) {
+ printf("key:\n");
+ hex_dump_data(key.keyvalue.data, key.keyvalue.length);
+ }
+ krb5_free_keyblock_contents(context, &key);
+ }
+ }
+ return val;
+}
+
+static int
+krb_enc(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ krb5_data *cipher,
+ krb5_data *clear)
+{
+ krb5_data decrypt;
+ krb5_error_code ret;
+
+ krb5_data_zero(&decrypt);
+
+ ret = krb5_decrypt(context,
+ crypto,
+ usage,
+ cipher->data,
+ cipher->length,
+ &decrypt);
+
+ if (ret) {
+ krb5_warn(context, ret, "krb5_decrypt");
+ return ret;
+ }
+
+ if (decrypt.length != clear->length ||
+ memcmp(decrypt.data, clear->data, decrypt.length) != 0) {
+ krb5_warnx(context, "clear text not same");
+ return EINVAL;
+ }
+
+ krb5_data_free(&decrypt);
+
+ return 0;
+}
+
+static int
+krb_enc_iov2(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ size_t cipher_len,
+ krb5_data *clear)
+{
+ krb5_crypto_iov iov[4];
+ krb5_data decrypt;
+ int ret;
+ char *p, *q;
+ size_t len, i;
+
+ p = clear->data;
+ len = clear->length;
+
+ iov[0].flags = KRB5_CRYPTO_TYPE_HEADER;
+ krb5_crypto_length(context, crypto, iov[0].flags, &iov[0].data.length);
+ iov[0].data.data = emalloc(iov[0].data.length);
+
+ iov[1].flags = KRB5_CRYPTO_TYPE_DATA;
+ iov[1].data.length = len;
+ iov[1].data.data = emalloc(iov[1].data.length);
+ memcpy(iov[1].data.data, p, iov[1].data.length);
+
+ /* padding buffer */
+ iov[2].flags = KRB5_CRYPTO_TYPE_PADDING;
+ krb5_crypto_length(context, crypto, KRB5_CRYPTO_TYPE_PADDING, &iov[2].data.length);
+ iov[2].data.data = emalloc(iov[2].data.length);
+
+ iov[3].flags = KRB5_CRYPTO_TYPE_TRAILER;
+ krb5_crypto_length(context, crypto, iov[3].flags, &iov[3].data.length);
+ iov[3].data.data = emalloc(iov[3].data.length);
+
+ ret = krb5_encrypt_iov_ivec(context, crypto, usage,
+ iov, sizeof(iov)/sizeof(iov[0]), NULL);
+ if (ret)
+ errx(1, "encrypt iov failed: %d", ret);
+
+ /* check len */
+ for (i = 0, len = 0; i < sizeof(iov)/sizeof(iov[0]); i++)
+ len += iov[i].data.length;
+ if (len != cipher_len)
+ errx(1, "cipher len wrong");
+
+ /*
+ * Plain decrypt
+ */
+
+ p = q = emalloc(len);
+ for (i = 0; i < sizeof(iov)/sizeof(iov[0]); i++) {
+ memcpy(q, iov[i].data.data, iov[i].data.length);
+ q += iov[i].data.length;
+ }
+
+ ret = krb5_decrypt(context, crypto, usage, p, len, &decrypt);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_decrypt");
+ else
+ krb5_data_free(&decrypt);
+
+ free(p);
+
+ /*
+ * Now decrypt use iov
+ */
+
+ /* padding turn into data */
+ p = q = emalloc(iov[1].data.length + iov[2].data.length);
+
+ memcpy(q, iov[1].data.data, iov[1].data.length);
+ q += iov[1].data.length;
+ memcpy(q, iov[2].data.data, iov[2].data.length);
+
+ free(iov[1].data.data);
+ free(iov[2].data.data);
+
+ iov[1].data.data = p;
+ iov[1].data.length += iov[2].data.length;
+
+ iov[2].flags = KRB5_CRYPTO_TYPE_EMPTY;
+ iov[2].data.length = 0;
+
+ ret = krb5_decrypt_iov_ivec(context, crypto, usage,
+ iov, sizeof(iov)/sizeof(iov[0]), NULL);
+ free(iov[0].data.data);
+ free(iov[3].data.data);
+
+ if (ret)
+ krb5_err(context, 1, ret, "decrypt iov failed: %d", ret);
+
+ if (clear->length != iov[1].data.length)
+ errx(1, "length incorrect");
+
+ p = clear->data;
+ if (memcmp(iov[1].data.data, p, iov[1].data.length) != 0)
+ errx(1, "iov[1] incorrect");
+
+ free(iov[1].data.data);
+
+ return 0;
+}
+
+
+static int
+krb_enc_iov(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ krb5_data *cipher,
+ krb5_data *clear)
+{
+ krb5_crypto_iov iov[3];
+ int ret;
+ char *p;
+ size_t len;
+
+ p = cipher->data;
+ len = cipher->length;
+
+ iov[0].flags = KRB5_CRYPTO_TYPE_HEADER;
+ krb5_crypto_length(context, crypto, iov[0].flags, &iov[0].data.length);
+ iov[0].data.data = emalloc(iov[0].data.length);
+ memcpy(iov[0].data.data, p, iov[0].data.length);
+ p += iov[0].data.length;
+ len -= iov[0].data.length;
+
+ iov[1].flags = KRB5_CRYPTO_TYPE_TRAILER;
+ krb5_crypto_length(context, crypto, iov[1].flags, &iov[1].data.length);
+ iov[1].data.data = emalloc(iov[1].data.length);
+ memcpy(iov[1].data.data, p + len - iov[1].data.length, iov[1].data.length);
+ len -= iov[1].data.length;
+
+ iov[2].flags = KRB5_CRYPTO_TYPE_DATA;
+ iov[2].data.length = len;
+ iov[2].data.data = emalloc(len);
+ memcpy(iov[2].data.data, p, len);
+
+ ret = krb5_decrypt_iov_ivec(context, crypto, usage,
+ iov, sizeof(iov)/sizeof(iov[0]), NULL);
+ if (ret)
+ krb5_err(context, 1, ret, "krb_enc_iov decrypt iov failed: %d", ret);
+
+ if (clear->length != iov[2].data.length)
+ errx(1, "length incorrect");
+
+ p = clear->data;
+ if (memcmp(iov[2].data.data, p, iov[2].data.length) != 0)
+ errx(1, "iov[2] incorrect");
+
+ free(iov[0].data.data);
+ free(iov[1].data.data);
+ free(iov[2].data.data);
+
+
+ return 0;
+}
+
+static int
+krb_checksum_iov(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ krb5_data *plain,
+ krb5_data *verify)
+{
+ krb5_crypto_iov iov[3];
+ int ret;
+ char *p;
+ size_t len;
+
+ p = plain->data;
+ len = plain->length;
+
+ iov[0].flags = KRB5_CRYPTO_TYPE_CHECKSUM;
+ if (verify) {
+ iov[0].data = *verify;
+ } else {
+ krb5_crypto_length(context, crypto, iov[0].flags, &iov[0].data.length);
+ iov[0].data.data = emalloc(iov[0].data.length);
+ }
+
+ iov[1].flags = KRB5_CRYPTO_TYPE_DATA;
+ iov[1].data.length = len;
+ iov[1].data.data = p;
+
+ iov[2].flags = KRB5_CRYPTO_TYPE_TRAILER;
+ krb5_crypto_length(context, crypto, iov[0].flags, &iov[2].data.length);
+ iov[2].data.data = malloc(iov[2].data.length);
+
+ if (verify == NULL) {
+ ret = krb5_create_checksum_iov(context, crypto, usage,
+ iov, sizeof(iov)/sizeof(iov[0]), NULL);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_create_checksum_iov failed");
+ }
+
+ ret = krb5_verify_checksum_iov(context, crypto, usage, iov, sizeof(iov)/sizeof(iov[0]), NULL);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_verify_checksum_iov");
+
+ if (verify == NULL)
+ free(iov[0].data.data);
+ free(iov[2].data.data);
+
+ return 0;
+}
+
+
+static int
+krb_enc_mit(krb5_context context,
+ krb5_enctype enctype,
+ krb5_keyblock *key,
+ unsigned usage,
+ krb5_data *cipher,
+ krb5_data *clear)
+{
+#ifndef HEIMDAL_SMALLER
+ krb5_error_code ret;
+ krb5_enc_data e;
+ krb5_data decrypt;
+ size_t len;
+
+ e.kvno = 0;
+ e.enctype = enctype;
+ e.ciphertext = *cipher;
+
+ ret = krb5_c_decrypt(context, *key, usage, NULL, &e, &decrypt);
+ if (ret)
+ return ret;
+
+ if (decrypt.length != clear->length ||
+ memcmp(decrypt.data, clear->data, decrypt.length) != 0) {
+ krb5_warnx(context, "clear text not same");
+ return EINVAL;
+ }
+
+ krb5_data_free(&decrypt);
+
+ ret = krb5_c_encrypt_length(context, enctype, clear->length, &len);
+ if (ret)
+ return ret;
+
+ if (len != cipher->length) {
+ krb5_warnx(context, "c_encrypt_length wrong %lu != %lu",
+ (unsigned long)len, (unsigned long)cipher->length);
+ return EINVAL;
+ }
+#endif /* HEIMDAL_SMALLER */
+ return 0;
+}
+
+struct {
+ krb5_enctype enctype;
+ unsigned usage;
+ size_t keylen;
+ void *key;
+ size_t elen;
+ void* edata;
+ size_t plen;
+ void *pdata;
+ size_t clen; /* checksum length */
+ void *cdata; /* checksum data */
+} krbencs[] = {
+ {
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ 7,
+ 32,
+ "\x47\x75\x69\x64\x65\x6c\x69\x6e\x65\x73\x20\x74\x6f\x20\x41\x75"
+ "\x74\x68\x6f\x72\x73\x20\x6f\x66\x20\x49\x6e\x74\x65\x72\x6e\x65",
+ 44,
+ "\xcf\x79\x8f\x0d\x76\xf3\xe0\xbe\x8e\x66\x94\x70\xfa\xcc\x9e\x91"
+ "\xa9\xec\x1c\x5c\x21\xfb\x6e\xef\x1a\x7a\xc8\xc1\xcc\x5a\x95\x24"
+ "\x6f\x9f\xf4\xd5\xbe\x5d\x59\x97\x44\xd8\x47\xcd",
+ 16,
+ "\x54\x68\x69\x73\x20\x69\x73\x20\x61\x20\x74\x65\x73\x74\x2e\x0a",
+ 0,
+ NULL
+ },
+ {
+ KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128,
+ 2,
+ 16,
+ "\x37\x05\xD9\x60\x80\xC1\x77\x28\xA0\xE8\x00\xEA\xB6\xE0\xD2\x3C",
+ 32,
+ "\xEF\x85\xFB\x89\x0B\xB8\x47\x2F\x4D\xAB\x20\x39\x4D\xCA\x78\x1D"
+ "\xAD\x87\x7E\xDA\x39\xD5\x0C\x87\x0C\x0D\x5A\x0A\x8E\x48\xC7\x18",
+ 0,
+ "",
+ 0,
+ NULL
+ },
+ {
+ KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128,
+ 2,
+ 16,
+ "\x37\x05\xD9\x60\x80\xC1\x77\x28\xA0\xE8\x00\xEA\xB6\xE0\xD2\x3C",
+ 38,
+ "\x84\xD7\xF3\x07\x54\xED\x98\x7B\xAB\x0B\xF3\x50\x6B\xEB\x09\xCF"
+ "\xB5\x54\x02\xCE\xF7\xE6\x87\x7C\xE9\x9E\x24\x7E\x52\xD1\x6E\xD4"
+ "\x42\x1D\xFD\xF8\x97\x6C",
+ 6,
+ "\x00\x01\x02\x03\x04\x05",
+ 0,
+ NULL
+ },
+ {
+ KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128,
+ 2,
+ 16,
+ "\x37\x05\xD9\x60\x80\xC1\x77\x28\xA0\xE8\x00\xEA\xB6\xE0\xD2\x3C",
+ 48,
+ "\x35\x17\xD6\x40\xF5\x0D\xDC\x8A\xD3\x62\x87\x22\xB3\x56\x9D\x2A"
+ "\xE0\x74\x93\xFA\x82\x63\x25\x40\x80\xEA\x65\xC1\x00\x8E\x8F\xC2"
+ "\x95\xFB\x48\x52\xE7\xD8\x3E\x1E\x7C\x48\xC3\x7E\xEB\xE6\xB0\xD3",
+ 16,
+ "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F",
+ 0,
+ NULL
+ },
+ {
+ KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128,
+ 2,
+ 16,
+ "\x37\x05\xD9\x60\x80\xC1\x77\x28\xA0\xE8\x00\xEA\xB6\xE0\xD2\x3C",
+ 53,
+ "\x72\x0F\x73\xB1\x8D\x98\x59\xCD\x6C\xCB\x43\x46\x11\x5C\xD3\x36"
+ "\xC7\x0F\x58\xED\xC0\xC4\x43\x7C\x55\x73\x54\x4C\x31\xC8\x13\xBC"
+ "\xE1\xE6\xD0\x72\xC1\x86\xB3\x9A\x41\x3C\x2F\x92\xCA\x9B\x83\x34"
+ "\xA2\x87\xFF\xCB\xFC",
+ 21,
+ "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
+ "\x10\x11\x12\x13\x14",
+ 16,
+ "\xD7\x83\x67\x18\x66\x43\xD6\x7B\x41\x1C\xBA\x91\x39\xFC\x1D\xEE"
+ },
+ {
+ KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192,
+ 2,
+ 32,
+ "\x6D\x40\x4D\x37\xFA\xF7\x9F\x9D\xF0\xD3\x35\x68\xD3\x20\x66\x98"
+ "\x00\xEB\x48\x36\x47\x2E\xA8\xA0\x26\xD1\x6B\x71\x82\x46\x0C\x52",
+ 40,
+ "\x41\xF5\x3F\xA5\xBF\xE7\x02\x6D\x91\xFA\xF9\xBE\x95\x91\x95\xA0"
+ "\x58\x70\x72\x73\xA9\x6A\x40\xF0\xA0\x19\x60\x62\x1A\xC6\x12\x74"
+ "\x8B\x9B\xBF\xBE\x7E\xB4\xCE\x3C",
+ 0,
+ "",
+ 0,
+ NULL
+ },
+ {
+ KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192,
+ 2,
+ 32,
+ "\x6D\x40\x4D\x37\xFA\xF7\x9F\x9D\xF0\xD3\x35\x68\xD3\x20\x66\x98"
+ "\x00\xEB\x48\x36\x47\x2E\xA8\xA0\x26\xD1\x6B\x71\x82\x46\x0C\x52",
+ 46,
+ "\x4E\xD7\xB3\x7C\x2B\xCA\xC8\xF7\x4F\x23\xC1\xCF\x07\xE6\x2B\xC7"
+ "\xB7\x5F\xB3\xF6\x37\xB9\xF5\x59\xC7\xF6\x64\xF6\x9E\xAB\x7B\x60"
+ "\x92\x23\x75\x26\xEA\x0D\x1F\x61\xCB\x20\xD6\x9D\x10\xF2",
+ 6,
+ "\x00\x01\x02\x03\x04\x05",
+ 0,
+ NULL
+ },
+ {
+ KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192,
+ 2,
+ 32,
+ "\x6D\x40\x4D\x37\xFA\xF7\x9F\x9D\xF0\xD3\x35\x68\xD3\x20\x66\x98"
+ "\x00\xEB\x48\x36\x47\x2E\xA8\xA0\x26\xD1\x6B\x71\x82\x46\x0C\x52",
+ 56,
+ "\xBC\x47\xFF\xEC\x79\x98\xEB\x91\xE8\x11\x5C\xF8\xD1\x9D\xAC\x4B"
+ "\xBB\xE2\xE1\x63\xE8\x7D\xD3\x7F\x49\xBE\xCA\x92\x02\x77\x64\xF6"
+ "\x8C\xF5\x1F\x14\xD7\x98\xC2\x27\x3F\x35\xDF\x57\x4D\x1F\x93\x2E"
+ "\x40\xC4\xFF\x25\x5B\x36\xA2\x66",
+ 16,
+ "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F",
+ 0,
+ NULL
+ },
+ {
+ KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192,
+ 2,
+ 32,
+ "\x6D\x40\x4D\x37\xFA\xF7\x9F\x9D\xF0\xD3\x35\x68\xD3\x20\x66\x98"
+ "\x00\xEB\x48\x36\x47\x2E\xA8\xA0\x26\xD1\x6B\x71\x82\x46\x0C\x52",
+ 61,
+ "\x40\x01\x3E\x2D\xF5\x8E\x87\x51\x95\x7D\x28\x78\xBC\xD2\xD6\xFE"
+ "\x10\x1C\xCF\xD5\x56\xCB\x1E\xAE\x79\xDB\x3C\x3E\xE8\x64\x29\xF2"
+ "\xB2\xA6\x02\xAC\x86\xFE\xF6\xEC\xB6\x47\xD6\x29\x5F\xAE\x07\x7A"
+ "\x1F\xEB\x51\x75\x08\xD2\xC1\x6B\x41\x92\xE0\x1F\x62",
+ 21,
+ "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
+ "\x10\x11\x12\x13\x14",
+ 24,
+ "\x45\xEE\x79\x15\x67\xEE\xFC\xA3\x7F\x4A\xC1\xE0\x22\x2D\xE8\x0D"
+ "\x43\xC3\xBF\xA0\x66\x99\x67\x2A"
+ }
+};
+
+static int
+krb_enc_test(krb5_context context)
+{
+ krb5_error_code ret;
+ krb5_crypto crypto;
+ krb5_keyblock kb;
+ krb5_data cipher, plain;
+ int i;
+
+ for (i = 0; i < sizeof(krbencs)/sizeof(krbencs[0]); i++) {
+
+ kb.keytype = krbencs[i].enctype;
+ kb.keyvalue.length = krbencs[i].keylen;
+ kb.keyvalue.data = krbencs[i].key;
+
+ ret = krb5_crypto_init(context, &kb, krbencs[i].enctype, &crypto);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_init failed with %d for test %d",
+ ret, i);
+
+ cipher.length = krbencs[i].elen;
+ cipher.data = krbencs[i].edata;
+ plain.length = krbencs[i].plen;
+ plain.data = krbencs[i].pdata;
+
+ ret = krb_enc(context, crypto, krbencs[i].usage, &cipher, &plain);
+
+ if (ret)
+ krb5_err(context, 1, ret, "krb_enc failed with %d for test %d",
+ ret, i);
+
+ ret = krb_enc_iov(context, crypto, krbencs[i].usage, &cipher, &plain);
+ if (ret)
+ krb5_err(context, 1, ret, "krb_enc_iov failed with %d for test %d",
+ ret, i);
+
+ ret = krb_enc_iov2(context, crypto, krbencs[i].usage,
+ cipher.length, &plain);
+ if (ret)
+ krb5_err(context, 1, ret, "krb_enc_iov2 failed with %d for test %d",
+ ret, i);
+
+ ret = krb_checksum_iov(context, crypto, krbencs[i].usage, &plain, NULL);
+ if (ret)
+ krb5_err(context, 1, ret,
+ "krb_checksum_iov failed with %d for test %d", ret, i);
+
+ if (krbencs[i].cdata) {
+ krb5_data checksum;
+
+ checksum.length = krbencs[i].clen;
+ checksum.data = krbencs[i].cdata;
+
+ ret = krb_checksum_iov(context, crypto, krbencs[i].usage,
+ &plain, &checksum);
+ if (ret)
+ krb5_err(context, 1, ret,
+ "krb_checksum_iov(2) failed with %d for test %d",
+ ret, i);
+ }
+
+ krb5_crypto_destroy(context, crypto);
+
+ ret = krb_enc_mit(context, krbencs[i].enctype, &kb,
+ krbencs[i].usage, &cipher, &plain);
+ if (ret)
+ krb5_err(context, 1, ret, "krb_enc_mit failed with %d for test %d",
+ ret, i);
+ }
+
+ return 0;
+}
+
+static int
+iov_test(krb5_context context, krb5_enctype enctype)
+{
+ krb5_error_code ret;
+ krb5_crypto crypto;
+ krb5_keyblock key;
+ krb5_data signonly, in, in2;
+ krb5_crypto_iov iov[6];
+ size_t len, i;
+ unsigned char *base, *p;
+
+ ret = krb5_generate_random_keyblock(context, enctype, &key);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_generate_random_keyblock");
+
+ ret = krb5_crypto_init(context, &key, 0, &crypto);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_init");
+
+
+ ret = krb5_crypto_length(context, crypto, KRB5_CRYPTO_TYPE_HEADER, &len);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_length");
+
+ signonly.data = "This should be signed";
+ signonly.length = strlen(signonly.data);
+ in.data = "inputdata";
+ in.length = strlen(in.data);
+
+ in2.data = "INPUTDATA";
+ in2.length = strlen(in2.data);
+
+
+ memset(iov, 0, sizeof(iov));
+
+ iov[0].flags = KRB5_CRYPTO_TYPE_HEADER;
+ iov[1].flags = KRB5_CRYPTO_TYPE_DATA;
+ iov[1].data = in;
+ iov[2].flags = KRB5_CRYPTO_TYPE_SIGN_ONLY;
+ iov[2].data = signonly;
+ iov[3].flags = KRB5_CRYPTO_TYPE_EMPTY;
+ iov[4].flags = KRB5_CRYPTO_TYPE_PADDING;
+ iov[5].flags = KRB5_CRYPTO_TYPE_TRAILER;
+
+ ret = krb5_crypto_length_iov(context, crypto, iov,
+ sizeof(iov)/sizeof(iov[0]));
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_length_iov");
+
+ for (len = 0, i = 0; i < sizeof(iov)/sizeof(iov[0]); i++) {
+ if (iov[i].flags == KRB5_CRYPTO_TYPE_SIGN_ONLY)
+ continue;
+ len += iov[i].data.length;
+ }
+
+ base = emalloc(len);
+
+ /*
+ * Allocate data for the fields
+ */
+
+ for (p = base, i = 0; i < sizeof(iov)/sizeof(iov[0]); i++) {
+ if (iov[i].flags == KRB5_CRYPTO_TYPE_SIGN_ONLY)
+ continue;;
+ iov[i].data.data = p;
+ p += iov[i].data.length;
+ }
+ assert(iov[1].data.length == in.length);
+ memcpy(iov[1].data.data, in.data, iov[1].data.length);
+
+ /*
+ * Encrypt
+ */
+
+ ret = krb5_encrypt_iov_ivec(context, crypto, 7, iov,
+ sizeof(iov)/sizeof(iov[0]), NULL);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_encrypt_iov_ivec");
+
+ /*
+ * Decrypt
+ */
+
+ ret = krb5_decrypt_iov_ivec(context, crypto, 7,
+ iov, sizeof(iov)/sizeof(iov[0]), NULL);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_decrypt_iov_ivec");
+
+ /*
+ * Verify data
+ */
+
+ if (krb5_data_cmp(&iov[1].data, &in) != 0)
+ krb5_errx(context, 1, "decrypted data not same");
+
+ /*
+ * Free memory
+ */
+
+ free(base);
+
+ /* Set up for second try */
+
+ iov[3].flags = KRB5_CRYPTO_TYPE_DATA;
+ iov[3].data = in;
+
+ ret = krb5_crypto_length_iov(context, crypto,
+ iov, sizeof(iov)/sizeof(iov[0]));
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_length_iov");
+
+ for (len = 0, i = 0; i < sizeof(iov)/sizeof(iov[0]); i++) {
+ if (iov[i].flags == KRB5_CRYPTO_TYPE_SIGN_ONLY)
+ continue;
+ len += iov[i].data.length;
+ }
+
+ base = emalloc(len);
+
+ /*
+ * Allocate data for the fields
+ */
+
+ for (p = base, i = 0; i < sizeof(iov)/sizeof(iov[0]); i++) {
+ if (iov[i].flags == KRB5_CRYPTO_TYPE_SIGN_ONLY)
+ continue;;
+ iov[i].data.data = p;
+ p += iov[i].data.length;
+ }
+ assert(iov[1].data.length == in.length);
+ memcpy(iov[1].data.data, in.data, iov[1].data.length);
+
+ assert(iov[3].data.length == in2.length);
+ memcpy(iov[3].data.data, in2.data, iov[3].data.length);
+
+
+
+ /*
+ * Encrypt
+ */
+
+ ret = krb5_encrypt_iov_ivec(context, crypto, 7,
+ iov, sizeof(iov)/sizeof(iov[0]), NULL);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_encrypt_iov_ivec");
+
+ /*
+ * Decrypt
+ */
+
+ ret = krb5_decrypt_iov_ivec(context, crypto, 7,
+ iov, sizeof(iov)/sizeof(iov[0]), NULL);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_decrypt_iov_ivec");
+
+ /*
+ * Verify data
+ */
+
+ if (krb5_data_cmp(&iov[1].data, &in) != 0)
+ krb5_errx(context, 1, "decrypted data 2.1 not same");
+
+ if (krb5_data_cmp(&iov[3].data, &in2) != 0)
+ krb5_errx(context, 1, "decrypted data 2.2 not same");
+
+ /*
+ * Free memory
+ */
+
+ free(base);
+
+ krb5_crypto_destroy(context, crypto);
+
+ krb5_free_keyblock_contents(context, &key);
+
+ return 0;
+}
+
+
+
+static int
+random_to_key(krb5_context context)
+{
+ krb5_error_code ret;
+ krb5_keyblock key;
+
+ ret = krb5_random_to_key(context,
+ ETYPE_DES3_CBC_SHA1,
+ "\x21\x39\x04\x58\x6A\xBD\x7F"
+ "\x21\x39\x04\x58\x6A\xBD\x7F"
+ "\x21\x39\x04\x58\x6A\xBD\x7F",
+ 21,
+ &key);
+ if (ret){
+ krb5_warn(context, ret, "random_to_key");
+ return 1;
+ }
+ if (key.keyvalue.length != 24)
+ return 1;
+
+ if (memcmp(key.keyvalue.data,
+ "\x20\x38\x04\x58\x6b\xbc\x7f\xc7"
+ "\x20\x38\x04\x58\x6b\xbc\x7f\xc7"
+ "\x20\x38\x04\x58\x6b\xbc\x7f\xc7",
+ 24) != 0)
+ return 1;
+
+ krb5_free_keyblock_contents(context, &key);
+
+ return 0;
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_error_code ret;
+ krb5_context context;
+ int val = 0;
+
+ if (argc > 1 && strcmp(argv[1], "-v") == 0)
+ verbose = 1;
+
+ ret = krb5_init_context (&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ val |= string_to_key_test(context);
+
+ val |= krb_enc_test(context);
+ val |= random_to_key(context);
+ val |= iov_test(context, KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96);
+ val |= iov_test(context, KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128);
+ val |= iov_test(context, KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192);
+
+ if (verbose && val == 0)
+ printf("all ok\n");
+ if (val)
+ printf("tests failed\n");
+
+ krb5_free_context(context);
+
+ return val;
+}
diff --git a/third_party/heimdal/lib/krb5/an2ln_plugin.h b/third_party/heimdal/lib/krb5/an2ln_plugin.h
new file mode 100644
index 0000000..b592f23
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/an2ln_plugin.h
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIMDAL_KRB5_AN2LN_PLUGIN_H
+#define HEIMDAL_KRB5_AN2LN_PLUGIN_H 1
+
+#include <heimbase-svc.h>
+
+#define KRB5_PLUGIN_AN2LN "an2ln"
+#define KRB5_PLUGIN_AN2LN_VERSION_0 0
+
+typedef krb5_error_code (KRB5_LIB_CALL *set_result_f)(void *, const char *);
+
+/** @struct krb5plugin_an2ln_ftable_desc
+ *
+ * @brief Description of the krb5_aname_to_lname(3) plugin facility.
+ *
+ * The krb5_aname_to_lname(3) function is pluggable. The plugin is
+ * named KRB5_PLUGIN_AN2LN ("an2ln"), with a single minor version,
+ * KRB5_PLUGIN_AN2LN_VERSION_0 (0).
+ *
+ * The plugin for krb5_aname_to_lname(3) consists of a data symbol
+ * referencing a structure of type krb5plugin_an2ln_ftable, with four
+ * fields:
+ *
+ * @param init Plugin initialization function (see krb5-plugin(7))
+ *
+ * @param minor_version The plugin minor version number (0)
+ *
+ * @param fini Plugin finalization function
+ *
+ * @param an2ln Plugin aname_to_lname function
+ *
+ * The an2ln field is the plugin entry point that performs the
+ * traditional aname_to_lname operation however the plugin desires. It
+ * is invoked in no particular order relative to other an2ln plugins,
+ * but it has a 'rule' argument that indicates which plugin is intended
+ * to act on the rule. The plugin an2ln function must return
+ * KRB5_PLUGIN_NO_HANDLE if the rule is not applicable to it.
+ *
+ * The plugin an2ln function has the following arguments, in this order:
+ *
+ * -# plug_ctx, the context value output by the plugin's init function
+ * -# context, a krb5_context
+ * -# rule, the aname_to_lname rule being evaluated (from krb5.conf(5))
+ * -# aname, the krb5_principal to be mapped to an lname
+ * -# set_res_f, a function the plugin must call to set its result
+ * -# set_res_ctx, the first argument to set_res_f (the second is the result lname string)
+ *
+ * @ingroup krb5_support
+ */
+typedef struct krb5plugin_an2ln_ftable_desc {
+ HEIM_PLUGIN_FTABLE_COMMON_ELEMENTS(krb5_context);
+ krb5_error_code (KRB5_LIB_CALL *an2ln)(void *, krb5_context, const char *,
+ krb5_const_principal, set_result_f, void *);
+} krb5plugin_an2ln_ftable;
+
+#endif /* HEIMDAL_KRB5_AN2LN_PLUGIN_H */
+
diff --git a/third_party/heimdal/lib/krb5/aname_to_localname.c b/third_party/heimdal/lib/krb5/aname_to_localname.c
new file mode 100644
index 0000000..11f270d
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/aname_to_localname.c
@@ -0,0 +1,469 @@
+/*
+ * Copyright (c) 1997 - 1999, 2002 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <string.h>
+#include "krb5_locl.h"
+#include "an2ln_plugin.h"
+#include "db_plugin.h"
+
+/* Default plugin (DB using binary search of sorted text file) follows */
+static krb5_error_code KRB5_LIB_CALL an2ln_def_plug_init(krb5_context, void **);
+static void KRB5_LIB_CALL an2ln_def_plug_fini(void *);
+static krb5_error_code KRB5_LIB_CALL an2ln_def_plug_an2ln(void *, krb5_context, const char *,
+ krb5_const_principal, set_result_f,
+ void *);
+
+static krb5plugin_an2ln_ftable an2ln_def_plug = {
+ 0,
+ an2ln_def_plug_init,
+ an2ln_def_plug_fini,
+ an2ln_def_plug_an2ln,
+};
+
+/* Plugin engine code follows */
+struct plctx {
+ krb5_const_principal aname;
+ heim_string_t luser;
+ const char *rule;
+};
+
+static krb5_error_code KRB5_LIB_CALL
+set_res(void *userctx, const char *res)
+{
+ struct plctx *plctx = userctx;
+ plctx->luser = heim_string_create(res);
+ if (plctx->luser == NULL)
+ return ENOMEM;
+ return 0;
+}
+
+static krb5_error_code KRB5_LIB_CALL
+plcallback(krb5_context context,
+ const void *plug, void *plugctx, void *userctx)
+{
+ const krb5plugin_an2ln_ftable *locate = plug;
+ struct plctx *plctx = userctx;
+
+ if (plctx->luser)
+ return 0;
+
+ return locate->an2ln(plugctx, context, plctx->rule, plctx->aname, set_res, plctx);
+}
+
+static const char *an2ln_plugin_deps[] = { "krb5", NULL };
+
+static struct heim_plugin_data
+an2ln_plugin_data = {
+ "krb5",
+ KRB5_PLUGIN_AN2LN,
+ KRB5_PLUGIN_AN2LN_VERSION_0,
+ an2ln_plugin_deps,
+ krb5_get_instance
+};
+
+static krb5_error_code
+an2ln_plugin(krb5_context context, const char *rule, krb5_const_principal aname,
+ size_t lnsize, char *lname)
+{
+ krb5_error_code ret;
+ struct plctx ctx;
+
+ ctx.rule = rule;
+ ctx.aname = aname;
+ ctx.luser = NULL;
+
+ /*
+ * Order of plugin invocation is non-deterministic, but there should
+ * really be no more than one plugin that can handle any given kind
+ * rule, so the effect should be deterministic anyways.
+ */
+ ret = _krb5_plugin_run_f(context, &an2ln_plugin_data,
+ 0, &ctx, plcallback);
+ if (ret != 0) {
+ heim_release(ctx.luser);
+ return ret;
+ }
+
+ if (ctx.luser == NULL)
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ if (strlcpy(lname, heim_string_get_utf8(ctx.luser), lnsize) >= lnsize)
+ ret = KRB5_CONFIG_NOTENUFSPACE;
+
+ heim_release(ctx.luser);
+ return ret;
+}
+
+static void
+reg_def_plugins_once(void *ctx)
+{
+ krb5_context context = ctx;
+
+ krb5_plugin_register(context, PLUGIN_TYPE_DATA, KRB5_PLUGIN_AN2LN,
+ &an2ln_def_plug);
+}
+
+static int
+princ_realm_is_default(krb5_context context,
+ krb5_const_principal aname)
+{
+ krb5_error_code ret;
+ krb5_realm *lrealms = NULL;
+ krb5_realm *r;
+ int valid;
+
+ ret = krb5_get_default_realms(context, &lrealms);
+ if (ret)
+ return 0;
+
+ valid = 0;
+ for (r = lrealms; *r != NULL; ++r) {
+ if (strcmp (*r, aname->realm) == 0) {
+ valid = 1;
+ break;
+ }
+ }
+ krb5_free_host_realm (context, lrealms);
+ return valid;
+}
+
+/*
+ * This function implements MIT's auth_to_local_names configuration for
+ * configuration compatibility. Specifically:
+ *
+ * [realms]
+ * <realm-name> = {
+ * auth_to_local_names = {
+ * <unparsed-principal-name> = <username>
+ * }
+ * }
+ *
+ * If multiple usernames are configured then the last one is taken.
+ *
+ * The configuration can only be expected to hold a relatively small
+ * number of mappings. For lots of mappings use a DB.
+ */
+static krb5_error_code
+an2ln_local_names(krb5_context context,
+ krb5_const_principal aname,
+ size_t lnsize,
+ char *lname)
+{
+ krb5_error_code ret;
+ char *unparsed;
+ char **values;
+ char *res;
+ size_t i;
+
+ if (!princ_realm_is_default(context, aname))
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ ret = krb5_unparse_name_flags(context, aname,
+ KRB5_PRINCIPAL_UNPARSE_NO_REALM,
+ &unparsed);
+ if (ret)
+ return ret;
+
+ ret = KRB5_PLUGIN_NO_HANDLE;
+ values = krb5_config_get_strings(context, NULL, "realms", aname->realm,
+ "auth_to_local_names", unparsed, NULL);
+ free(unparsed);
+ if (!values)
+ return ret;
+ /* Take the last value, just like MIT */
+ for (res = NULL, i = 0; values[i]; i++)
+ res = values[i];
+ if (res) {
+ ret = 0;
+ if (strlcpy(lname, res, lnsize) >= lnsize)
+ ret = KRB5_CONFIG_NOTENUFSPACE;
+
+ if (!*res || strcmp(res, ":") == 0)
+ ret = KRB5_NO_LOCALNAME;
+ }
+
+ krb5_config_free_strings(values);
+ return ret;
+}
+
+/*
+ * Heimdal's default aname2lname mapping.
+ */
+static krb5_error_code
+an2ln_default(krb5_context context,
+ char *rule,
+ krb5_const_principal aname,
+ size_t lnsize, char *lname)
+{
+ krb5_error_code ret;
+ const char *res;
+ int root_princs_ok;
+
+ if (strcmp(rule, "NONE") == 0)
+ return KRB5_NO_LOCALNAME;
+
+ if (strcmp(rule, "DEFAULT") == 0)
+ root_princs_ok = 0;
+ else if (strcmp(rule, "HEIMDAL_DEFAULT") == 0)
+ root_princs_ok = 1;
+ else
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ if (!princ_realm_is_default(context, aname))
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ if (aname->name.name_string.len == 1) {
+ /*
+ * One component principal names in default realm -> the one
+ * component is the username.
+ */
+ res = aname->name.name_string.val[0];
+ } else if (root_princs_ok && aname->name.name_string.len == 2 &&
+ strcmp (aname->name.name_string.val[1], "root") == 0) {
+ /*
+ * Two-component principal names in default realm where the
+ * first component is "root" -> root IFF the principal is in
+ * root's .k5login (or whatever krb5_kuserok() does).
+ */
+ krb5_principal rootprinc;
+ krb5_boolean userok;
+
+ res = "root";
+
+ ret = krb5_copy_principal(context, aname, &rootprinc);
+ if (ret)
+ return ret;
+
+ userok = _krb5_kuserok(context, rootprinc, res, FALSE);
+ krb5_free_principal(context, rootprinc);
+ if (!userok)
+ return KRB5_NO_LOCALNAME;
+ } else {
+ return KRB5_PLUGIN_NO_HANDLE;
+ }
+
+ if (strlcpy(lname, res, lnsize) >= lnsize)
+ return KRB5_CONFIG_NOTENUFSPACE;
+
+ return 0;
+}
+
+/**
+ * Map a principal name to a local username.
+ *
+ * Returns 0 on success, KRB5_NO_LOCALNAME if no mapping was found, or
+ * some Kerberos or system error.
+ *
+ * Inputs:
+ *
+ * @param context A krb5_context
+ * @param aname A principal name
+ * @param lnsize The size of the buffer into which the username will be written
+ * @param lname The buffer into which the username will be written
+ *
+ * @ingroup krb5_support
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_aname_to_localname(krb5_context context,
+ krb5_const_principal aname,
+ size_t lnsize,
+ char *lname)
+{
+ static heim_base_once_t reg_def_plugins = HEIM_BASE_ONCE_INIT;
+ krb5_error_code ret;
+ krb5_realm realm;
+ size_t i;
+ char **rules = NULL;
+ char *rule;
+
+ if (lnsize)
+ lname[0] = '\0';
+
+ heim_base_once_f(&reg_def_plugins, context, reg_def_plugins_once);
+
+ /* Try MIT's auth_to_local_names config first */
+ ret = an2ln_local_names(context, aname, lnsize, lname);
+ if (ret != KRB5_PLUGIN_NO_HANDLE)
+ return ret;
+
+ ret = krb5_get_default_realm(context, &realm);
+ if (ret)
+ return ret;
+
+ rules = krb5_config_get_strings(context, NULL, "realms", realm,
+ "auth_to_local", NULL);
+ krb5_xfree(realm);
+ if (!rules) {
+ /* Heimdal's default rule */
+ ret = an2ln_default(context, "HEIMDAL_DEFAULT", aname, lnsize, lname);
+ if (ret == KRB5_PLUGIN_NO_HANDLE)
+ return KRB5_NO_LOCALNAME;
+ return ret;
+ }
+
+ /*
+ * MIT rules.
+ *
+ * Note that RULEs and DBs only have white-list functionality,
+ * thus RULEs and DBs that we don't understand we simply ignore.
+ *
+ * This means that plugins that implement black-lists are
+ * dangerous: if a black-list plugin isn't found, the black-list
+ * won't be enforced. But black-lists are dangerous anyways.
+ */
+ for (ret = KRB5_PLUGIN_NO_HANDLE, i = 0; rules[i]; i++) {
+ rule = rules[i];
+
+ /* Try NONE, DEFAULT, and HEIMDAL_DEFAULT rules */
+ ret = an2ln_default(context, rule, aname, lnsize, lname);
+ if (ret == KRB5_PLUGIN_NO_HANDLE)
+ /* Try DB, RULE, ... plugins */
+ ret = an2ln_plugin(context, rule, aname, lnsize, lname);
+
+ if (ret == 0 && lnsize && !lname[0])
+ continue; /* Success but no lname?! lies! */
+ else if (ret != KRB5_PLUGIN_NO_HANDLE)
+ break;
+ }
+
+ if (ret == KRB5_PLUGIN_NO_HANDLE) {
+ if (lnsize)
+ lname[0] = '\0';
+ ret = KRB5_NO_LOCALNAME;
+ }
+
+ krb5_config_free_strings(rules);
+ return ret;
+}
+
+static krb5_error_code KRB5_LIB_CALL
+an2ln_def_plug_init(krb5_context context, void **ctx)
+{
+ *ctx = NULL;
+ return 0;
+}
+
+static void KRB5_LIB_CALL
+an2ln_def_plug_fini(void *ctx)
+{
+}
+
+static heim_base_once_t sorted_text_db_init_once = HEIM_BASE_ONCE_INIT;
+
+static void
+sorted_text_db_init_f(void *arg)
+{
+ (void) heim_db_register("sorted-text", NULL, &heim_sorted_text_file_dbtype);
+}
+
+static krb5_error_code KRB5_LIB_CALL
+an2ln_def_plug_an2ln(void *plug_ctx, krb5_context context,
+ const char *rule,
+ krb5_const_principal aname,
+ set_result_f set_res_f, void *set_res_ctx)
+{
+ krb5_error_code ret;
+ const char *an2ln_db_fname;
+ heim_db_t dbh = NULL;
+ heim_dict_t db_options;
+ heim_data_t k, v;
+ heim_error_t error;
+ char *unparsed = NULL;
+ char *value = NULL;
+
+ _krb5_load_db_plugins(context);
+ heim_base_once_f(&sorted_text_db_init_once, NULL, sorted_text_db_init_f);
+
+ if (strncmp(rule, "DB:", strlen("DB:")) != 0)
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ an2ln_db_fname = &rule[strlen("DB:")];
+ if (!*an2ln_db_fname)
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ ret = krb5_unparse_name(context, aname, &unparsed);
+ if (ret)
+ return ret;
+
+ db_options = heim_dict_create(11);
+ if (db_options != NULL)
+ heim_dict_set_value(db_options, HSTR("read-only"),
+ heim_number_create(1));
+ dbh = heim_db_create(NULL, an2ln_db_fname, db_options, &error);
+ if (dbh == NULL) {
+ krb5_set_error_message(context, heim_error_get_code(error),
+ N_("Couldn't open aname2lname-text-db", ""));
+ ret = KRB5_PLUGIN_NO_HANDLE;
+ goto cleanup;
+ }
+
+ /* Binary search; file should be sorted (in C locale) */
+ k = heim_data_ref_create(unparsed, strlen(unparsed), NULL);
+ if (k == NULL) {
+ ret = krb5_enomem(context);
+ goto cleanup;
+ }
+ v = heim_db_copy_value(dbh, NULL, k, &error);
+ heim_release(k);
+ if (v == NULL && error != NULL) {
+ krb5_set_error_message(context, heim_error_get_code(error),
+ N_("Lookup in aname2lname-text-db failed", ""));
+ ret = heim_error_get_code(error);
+ goto cleanup;
+ } else if (v == NULL) {
+ ret = KRB5_PLUGIN_NO_HANDLE;
+ goto cleanup;
+ } else {
+ /* found */
+ if (heim_data_get_length(v) == 0) {
+ krb5_set_error_message(context, ret,
+ N_("Principal mapped to empty username", ""));
+ ret = KRB5_NO_LOCALNAME;
+ goto cleanup;
+ }
+ value = strndup(heim_data_get_ptr(v), heim_data_get_length(v));
+ heim_release(v);
+ if (value == NULL) {
+ ret = krb5_enomem(context);
+ goto cleanup;
+ }
+ ret = set_res_f(set_res_ctx, value);
+ }
+
+cleanup:
+ heim_release(dbh);
+ free(unparsed);
+ free(value);
+ return ret;
+}
+
diff --git a/third_party/heimdal/lib/krb5/appdefault.c b/third_party/heimdal/lib/krb5/appdefault.c
new file mode 100644
index 0000000..d4e963d
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/appdefault.c
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2000 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_appdefault_boolean(krb5_context context, const char *appname,
+ krb5_const_realm realm, const char *option,
+ krb5_boolean def_val, krb5_boolean *ret_val)
+{
+
+ if(appname == NULL)
+ appname = getprogname();
+
+ def_val = krb5_config_get_bool_default(context, NULL, def_val,
+ "libdefaults", option, NULL);
+ if(realm != NULL)
+ def_val = krb5_config_get_bool_default(context, NULL, def_val,
+ "realms", realm, option, NULL);
+
+ def_val = krb5_config_get_bool_default(context, NULL, def_val,
+ "appdefaults",
+ option,
+ NULL);
+ if(realm != NULL)
+ def_val = krb5_config_get_bool_default(context, NULL, def_val,
+ "appdefaults",
+ realm,
+ option,
+ NULL);
+ if(appname != NULL) {
+ def_val = krb5_config_get_bool_default(context, NULL, def_val,
+ "appdefaults",
+ appname,
+ option,
+ NULL);
+ if(realm != NULL)
+ def_val = krb5_config_get_bool_default(context, NULL, def_val,
+ "appdefaults",
+ appname,
+ realm,
+ option,
+ NULL);
+ }
+ *ret_val = def_val;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_appdefault_string(krb5_context context, const char *appname,
+ krb5_const_realm realm, const char *option,
+ const char *def_val, char **ret_val)
+{
+ if(appname == NULL)
+ appname = getprogname();
+
+ def_val = krb5_config_get_string_default(context, NULL, def_val,
+ "libdefaults", option, NULL);
+ if(realm != NULL)
+ def_val = krb5_config_get_string_default(context, NULL, def_val,
+ "realms", realm, option, NULL);
+
+ def_val = krb5_config_get_string_default(context, NULL, def_val,
+ "appdefaults",
+ option,
+ NULL);
+ if(realm != NULL)
+ def_val = krb5_config_get_string_default(context, NULL, def_val,
+ "appdefaults",
+ realm,
+ option,
+ NULL);
+ if(appname != NULL) {
+ def_val = krb5_config_get_string_default(context, NULL, def_val,
+ "appdefaults",
+ appname,
+ option,
+ NULL);
+ if(realm != NULL)
+ def_val = krb5_config_get_string_default(context, NULL, def_val,
+ "appdefaults",
+ appname,
+ realm,
+ option,
+ NULL);
+ }
+ if(def_val != NULL)
+ *ret_val = strdup(def_val);
+ else
+ *ret_val = NULL;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_appdefault_time(krb5_context context, const char *appname,
+ krb5_const_realm realm, const char *option,
+ time_t def_val, time_t *ret_val)
+{
+ krb5_deltat t;
+ char *val;
+
+ krb5_appdefault_string(context, appname, realm, option, NULL, &val);
+ if (val == NULL) {
+ *ret_val = def_val;
+ return;
+ }
+ if (krb5_string_to_deltat(val, &t))
+ *ret_val = def_val;
+ else
+ *ret_val = t;
+ free(val);
+}
diff --git a/third_party/heimdal/lib/krb5/asn1_glue.c b/third_party/heimdal/lib/krb5/asn1_glue.c
new file mode 100644
index 0000000..16eda2f
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/asn1_glue.c
@@ -0,0 +1,162 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ *
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_principal2principalname(PrincipalName *p,
+ krb5_const_principal from)
+{
+ return copy_PrincipalName(&from->name, p);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_principalname2krb5_principal (krb5_context context,
+ krb5_principal *principal,
+ const PrincipalName from,
+ const Realm realm)
+{
+ krb5_error_code ret;
+ krb5_principal p;
+
+ p = calloc(1, sizeof(*p));
+ if (p == NULL)
+ return krb5_enomem(context);
+ ret = copy_PrincipalName(&from, &p->name);
+ if (ret) {
+ free(p);
+ return ret;
+ }
+ p->realm = strdup(realm);
+ if (p->realm == NULL) {
+ free_PrincipalName(&p->name);
+ free(p);
+ return krb5_enomem(context);
+ }
+ *principal = p;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_ticket2krb5_principal(krb5_context context,
+ krb5_principal *principal,
+ const EncTicketPart *ticket,
+ const AuthorizationData *authenticator_ad)
+{
+ krb5_error_code ret;
+ krb5_principal p = NULL;
+
+ *principal = NULL;
+
+ ret = _krb5_principalname2krb5_principal(context,
+ &p,
+ ticket->cname,
+ ticket->crealm);
+ if (ret == 0 &&
+ (p->nameattrs = calloc(1, sizeof(p->nameattrs[0]))) == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0)
+ p->nameattrs->authenticated = 1;
+ if (ret == 0 &&
+ (p->nameattrs->source =
+ calloc(1, sizeof(p->nameattrs->source[0]))) == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0) {
+ p->nameattrs->source->element =
+ choice_PrincipalNameAttrSrc_enc_ticket_part;
+ ret = copy_EncTicketPart(ticket,
+ &p->nameattrs->source->u.enc_ticket_part);
+ /* NOTE: we don't want to keep a copy of the session key here! */
+ if (ret == 0)
+ der_free_octet_string(&p->nameattrs->source->u.enc_ticket_part.key.keyvalue);
+ }
+ if (ret == 0 && authenticator_ad) {
+ p->nameattrs->authenticator_ad =
+ calloc(1, sizeof(p->nameattrs->authenticator_ad[0]));
+ if (p->nameattrs->authenticator_ad == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0)
+ ret = copy_AuthorizationData(authenticator_ad,
+ p->nameattrs->authenticator_ad);
+ }
+
+ if (ret == 0)
+ *principal = p;
+ else
+ krb5_free_principal(context, p);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_kdcrep2krb5_principal(krb5_context context,
+ krb5_principal *principal,
+ const EncKDCRepPart *kdcrep)
+{
+ krb5_error_code ret;
+ krb5_principal p = NULL;
+
+ *principal = NULL;
+
+ ret = _krb5_principalname2krb5_principal(context,
+ &p,
+ kdcrep->sname,
+ kdcrep->srealm);
+ if (ret == 0 &&
+ (p->nameattrs = calloc(1, sizeof(p->nameattrs[0]))) == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0)
+ p->nameattrs->authenticated = 1;
+ if (ret == 0 &&
+ (p->nameattrs->source =
+ calloc(1, sizeof(p->nameattrs->source[0]))) == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0) {
+ p->nameattrs->source->element =
+ choice_PrincipalNameAttrSrc_enc_kdc_rep_part;
+ ret = copy_EncKDCRepPart(kdcrep,
+ &p->nameattrs->source->u.enc_kdc_rep_part);
+ /* NOTE: we don't want to keep a copy of the session key here! */
+ if (ret == 0)
+ der_free_octet_string(&p->nameattrs->source->u.enc_kdc_rep_part.key.keyvalue);
+ }
+
+ if (ret == 0)
+ *principal = p;
+ else
+ krb5_free_principal(context, p);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/auth_context.c b/third_party/heimdal/lib/krb5/auth_context.c
new file mode 100644
index 0000000..8b43b63
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/auth_context.c
@@ -0,0 +1,621 @@
+/*
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ * Allocate and initialize an autentication context.
+ *
+ * @param context A kerberos context.
+ * @param auth_context The authentication context to be initialized.
+ *
+ * Use krb5_auth_con_free() to release the memory when done using the context.
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_init(krb5_context context,
+ krb5_auth_context *auth_context)
+{
+ krb5_auth_context p;
+
+ ALLOC(p, 1);
+ if (!p)
+ return krb5_enomem(context);
+ memset(p, 0, sizeof(*p));
+ ALLOC(p->authenticator, 1);
+ if (!p->authenticator) {
+ free(p);
+ return krb5_enomem(context);
+ }
+ memset (p->authenticator, 0, sizeof(*p->authenticator));
+ p->flags = KRB5_AUTH_CONTEXT_DO_TIME;
+
+ p->local_address = NULL;
+ p->remote_address = NULL;
+ p->local_port = 0;
+ p->remote_port = 0;
+ p->keytype = KRB5_ENCTYPE_NULL;
+ p->cksumtype = CKSUMTYPE_NONE;
+ p->auth_data = NULL;
+ *auth_context = p;
+ return 0;
+}
+
+/**
+ * Deallocate an authentication context previously initialized with
+ * krb5_auth_con_init().
+ *
+ * @param context A kerberos context.
+ * @param auth_context The authentication context to be deallocated.
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_free(krb5_context context,
+ krb5_auth_context auth_context)
+{
+ if (auth_context != NULL) {
+ if (auth_context->authenticator)
+ krb5_free_authenticator(context, &auth_context->authenticator);
+ if(auth_context->local_address){
+ free_HostAddress(auth_context->local_address);
+ free(auth_context->local_address);
+ }
+ if(auth_context->remote_address){
+ free_HostAddress(auth_context->remote_address);
+ free(auth_context->remote_address);
+ }
+ krb5_free_keyblock(context, auth_context->keyblock);
+ krb5_free_keyblock(context, auth_context->remote_subkey);
+ krb5_free_keyblock(context, auth_context->local_subkey);
+ if (auth_context->auth_data) {
+ free_AuthorizationData(auth_context->auth_data);
+ free(auth_context->auth_data);
+ }
+ free (auth_context);
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setflags(krb5_context context,
+ krb5_auth_context auth_context,
+ int32_t flags)
+{
+ auth_context->flags = flags;
+ return 0;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getflags(krb5_context context,
+ krb5_auth_context auth_context,
+ int32_t *flags)
+{
+ *flags = auth_context->flags;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_addflags(krb5_context context,
+ krb5_auth_context auth_context,
+ int32_t addflags,
+ int32_t *flags)
+{
+ if (flags)
+ *flags = auth_context->flags;
+ auth_context->flags |= addflags;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_removeflags(krb5_context context,
+ krb5_auth_context auth_context,
+ int32_t removeflags,
+ int32_t *flags)
+{
+ if (flags)
+ *flags = auth_context->flags;
+ auth_context->flags &= ~removeflags;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setaddrs(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_address *local_addr,
+ krb5_address *remote_addr)
+{
+ if (local_addr) {
+ if (auth_context->local_address)
+ krb5_free_address (context, auth_context->local_address);
+ else
+ if ((auth_context->local_address = malloc(sizeof(krb5_address))) == NULL)
+ return krb5_enomem(context);
+ krb5_copy_address(context, local_addr, auth_context->local_address);
+ }
+ if (remote_addr) {
+ if (auth_context->remote_address)
+ krb5_free_address (context, auth_context->remote_address);
+ else
+ if ((auth_context->remote_address = malloc(sizeof(krb5_address))) == NULL)
+ return krb5_enomem(context);
+ krb5_copy_address(context, remote_addr, auth_context->remote_address);
+ }
+ return 0;
+}
+
+/**
+ * Update the authentication context \a auth_context with the local
+ * and remote addresses from socket \a fd, according to \a flags.
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_genaddrs(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_socket_t fd, int flags)
+{
+ krb5_error_code ret;
+ krb5_address local_k_address, remote_k_address;
+ krb5_address *lptr = NULL, *rptr = NULL;
+ struct sockaddr_storage ss_local, ss_remote;
+ struct sockaddr *local = (struct sockaddr *)&ss_local;
+ struct sockaddr *remote = (struct sockaddr *)&ss_remote;
+ socklen_t len;
+
+ if(flags & KRB5_AUTH_CONTEXT_GENERATE_LOCAL_ADDR) {
+ if (auth_context->local_address == NULL) {
+ len = sizeof(ss_local);
+ if(rk_IS_SOCKET_ERROR(getsockname(fd, local, &len))) {
+ char buf[128];
+ ret = rk_SOCK_ERRNO;
+ rk_strerror_r(ret, buf, sizeof(buf));
+ krb5_set_error_message(context, ret, "getsockname: %s", buf);
+ goto out;
+ }
+ ret = krb5_sockaddr2address (context, local, &local_k_address);
+ if(ret) goto out;
+ if(flags & KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR) {
+ krb5_sockaddr2port (context, local, &auth_context->local_port);
+ } else
+ auth_context->local_port = 0;
+ lptr = &local_k_address;
+ }
+ }
+ if(flags & KRB5_AUTH_CONTEXT_GENERATE_REMOTE_ADDR) {
+ len = sizeof(ss_remote);
+ if(rk_IS_SOCKET_ERROR(getpeername(fd, remote, &len))) {
+ char buf[128];
+ ret = rk_SOCK_ERRNO;
+ rk_strerror_r(ret, buf, sizeof(buf));
+ krb5_set_error_message(context, ret, "getpeername: %s", buf);
+ goto out;
+ }
+ ret = krb5_sockaddr2address (context, remote, &remote_k_address);
+ if(ret) goto out;
+ if(flags & KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR) {
+ krb5_sockaddr2port (context, remote, &auth_context->remote_port);
+ } else
+ auth_context->remote_port = 0;
+ rptr = &remote_k_address;
+ }
+ ret = krb5_auth_con_setaddrs (context,
+ auth_context,
+ lptr,
+ rptr);
+ out:
+ if (lptr)
+ krb5_free_address (context, lptr);
+ if (rptr)
+ krb5_free_address (context, rptr);
+ return ret;
+
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setaddrs_from_fd (krb5_context context,
+ krb5_auth_context auth_context,
+ void *p_fd)
+{
+ krb5_socket_t fd = *(krb5_socket_t *)p_fd;
+ int flags = 0;
+ if(auth_context->local_address == NULL)
+ flags |= KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR;
+ if(auth_context->remote_address == NULL)
+ flags |= KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR;
+ return krb5_auth_con_genaddrs(context, auth_context, fd, flags);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getaddrs(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_address **local_addr,
+ krb5_address **remote_addr)
+{
+ if(*local_addr)
+ krb5_free_address (context, *local_addr);
+ *local_addr = malloc (sizeof(**local_addr));
+ if (*local_addr == NULL)
+ return krb5_enomem(context);
+ krb5_copy_address(context,
+ auth_context->local_address,
+ *local_addr);
+
+ if(*remote_addr)
+ krb5_free_address (context, *remote_addr);
+ *remote_addr = malloc (sizeof(**remote_addr));
+ if (*remote_addr == NULL) {
+ krb5_free_address (context, *local_addr);
+ *local_addr = NULL;
+ return krb5_enomem(context);
+ }
+ krb5_copy_address(context,
+ auth_context->remote_address,
+ *remote_addr);
+ return 0;
+}
+
+/* coverity[+alloc : arg-*2] */
+static krb5_error_code
+copy_key(krb5_context context,
+ krb5_keyblock *in,
+ krb5_keyblock **out)
+{
+ *out = NULL;
+ if (in)
+ return krb5_copy_keyblock(context, in, out);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getkey(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_keyblock **keyblock)
+{
+ return copy_key(context, auth_context->keyblock, keyblock);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getlocalsubkey(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_keyblock **keyblock)
+{
+ return copy_key(context, auth_context->local_subkey, keyblock);
+}
+
+/* coverity[+alloc : arg-*2] */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getremotesubkey(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_keyblock **keyblock)
+{
+ return copy_key(context, auth_context->remote_subkey, keyblock);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setkey(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_keyblock *keyblock)
+{
+ if(auth_context->keyblock)
+ krb5_free_keyblock(context, auth_context->keyblock);
+ return copy_key(context, keyblock, &auth_context->keyblock);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setlocalsubkey(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_keyblock *keyblock)
+{
+ if(auth_context->local_subkey)
+ krb5_free_keyblock(context, auth_context->local_subkey);
+ return copy_key(context, keyblock, &auth_context->local_subkey);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_generatelocalsubkey(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_keyblock *key)
+{
+ krb5_error_code ret;
+ krb5_keyblock *subkey;
+
+ ret = krb5_generate_subkey_extended (context, key,
+ auth_context->keytype,
+ &subkey);
+ if(ret)
+ return ret;
+ if(auth_context->local_subkey)
+ krb5_free_keyblock(context, auth_context->local_subkey);
+ auth_context->local_subkey = subkey;
+ return 0;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setremotesubkey(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_keyblock *keyblock)
+{
+ if(auth_context->remote_subkey)
+ krb5_free_keyblock(context, auth_context->remote_subkey);
+ return copy_key(context, keyblock, &auth_context->remote_subkey);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setcksumtype(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_cksumtype cksumtype)
+{
+ auth_context->cksumtype = cksumtype;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getcksumtype(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_cksumtype *cksumtype)
+{
+ *cksumtype = auth_context->cksumtype;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setkeytype (krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_keytype keytype)
+{
+ auth_context->keytype = keytype;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getkeytype (krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_keytype *keytype)
+{
+ *keytype = auth_context->keytype;
+ return 0;
+}
+
+krb5_error_code
+_krb5_add_1auth_data(krb5_context context,
+ krb5int32 ad_type, krb5_data *ad_data, int critical,
+ krb5_authdata **dst)
+{
+ AuthorizationDataElement e;
+
+ e.ad_type = ad_type;
+ e.ad_data = *ad_data;
+
+ if (!critical) {
+ AuthorizationData ad;
+ krb5_error_code ret;
+ krb5_data ir;
+ size_t len;
+
+ /* Build an AD-IF-RELEVANT with the new element inside it */
+ ad.len = 0;
+ ad.val = NULL;
+ ret = add_AuthorizationData(&ad, &e);
+
+ /* Encode the AD-IF-RELEVANT */
+ if (ret == 0)
+ ASN1_MALLOC_ENCODE(AuthorizationData, ir.data, ir.length, &ad,
+ &len, ret);
+ if (ret == 0 && ir.length != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ /* Re-enter to add the encoded AD-IF-RELEVANT */
+ ret = _krb5_add_1auth_data(context, KRB5_AUTHDATA_IF_RELEVANT, &ir, 1,
+ dst);
+
+ free_AuthorizationData(&ad);
+ krb5_data_free(&ir);
+ return ret;
+ }
+
+ if (*dst == NULL) {
+ ALLOC(*dst, 1);
+ if (*dst == NULL)
+ return krb5_enomem(context);
+ }
+ return add_AuthorizationData(*dst, &e);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_add_AuthorizationData(krb5_context context,
+ krb5_auth_context auth_context,
+ int type,
+ krb5_data *data)
+{
+ if (auth_context->auth_data == NULL) {
+ auth_context->auth_data = calloc(1, sizeof(*auth_context->auth_data));
+ if (auth_context->auth_data == NULL)
+ return krb5_enomem(context);
+ }
+ return _krb5_add_1auth_data(context, type, data, 1,
+ &auth_context->auth_data);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_add_AuthorizationDataIfRelevant(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5int32 type,
+ krb5_data *data)
+{
+ if (auth_context->auth_data == NULL) {
+ auth_context->auth_data = calloc(1, sizeof(*auth_context->auth_data));
+ if (auth_context->auth_data == NULL)
+ return krb5_enomem(context);
+ }
+ return _krb5_add_1auth_data(context, type, data, 0,
+ &auth_context->auth_data);
+}
+
+
+
+#if 0
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setenctype(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_enctype etype)
+{
+ if(auth_context->keyblock)
+ krb5_free_keyblock(context, auth_context->keyblock);
+ ALLOC(auth_context->keyblock, 1);
+ if(auth_context->keyblock == NULL)
+ return krb5_enomem(context);
+ auth_context->keyblock->keytype = etype;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getenctype(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_enctype *etype)
+{
+ krb5_abortx(context, "unimplemented krb5_auth_getenctype called");
+}
+#endif
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getlocalseqnumber(krb5_context context,
+ krb5_auth_context auth_context,
+ int32_t *seqnumber)
+{
+ *seqnumber = auth_context->local_seqnumber;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setlocalseqnumber (krb5_context context,
+ krb5_auth_context auth_context,
+ int32_t seqnumber)
+{
+ auth_context->local_seqnumber = seqnumber;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getremoteseqnumber(krb5_context context,
+ krb5_auth_context auth_context,
+ int32_t *seqnumber)
+{
+ *seqnumber = auth_context->remote_seqnumber;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setremoteseqnumber (krb5_context context,
+ krb5_auth_context auth_context,
+ int32_t seqnumber)
+{
+ auth_context->remote_seqnumber = seqnumber;
+ return 0;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getauthenticator(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_authenticator *authenticator)
+{
+ *authenticator = malloc(sizeof(**authenticator));
+ if (*authenticator == NULL)
+ return krb5_enomem(context);
+
+ return copy_Authenticator(auth_context->authenticator,
+ *authenticator);
+}
+
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_authenticator(krb5_context context,
+ krb5_authenticator *authenticator)
+{
+ free_Authenticator (*authenticator);
+ free (*authenticator);
+ *authenticator = NULL;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setuserkey(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_keyblock *keyblock)
+{
+ if(auth_context->keyblock)
+ krb5_free_keyblock(context, auth_context->keyblock);
+ return krb5_copy_keyblock(context, keyblock, &auth_context->keyblock);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getrcache(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_rcache *rcache)
+{
+ *rcache = auth_context->rcache;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setrcache(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_rcache rcache)
+{
+ auth_context->rcache = rcache;
+ return 0;
+}
+
+#if 0 /* not implemented */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_initivector(krb5_context context,
+ krb5_auth_context auth_context)
+{
+ krb5_abortx(context, "unimplemented krb5_auth_con_initivector called");
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setivector(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_pointer ivector)
+{
+ krb5_abortx(context, "unimplemented krb5_auth_con_setivector called");
+}
+
+#endif /* not implemented */
diff --git a/third_party/heimdal/lib/krb5/authdata.c b/third_party/heimdal/lib/krb5/authdata.c
new file mode 100644
index 0000000..ac42661
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/authdata.c
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 1997-2021 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * Copyright (c) 2021 Isaac Boukris
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/*
+ * Add the AuthorizationData `data´ of `type´ to the last element in
+ * the sequence of authorization_data in `tkt´ wrapped in an IF_RELEVANT
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_kdc_tkt_add_if_relevant_ad(krb5_context context,
+ EncTicketPart *tkt,
+ int type,
+ const krb5_data *data)
+{
+ krb5_error_code ret;
+ size_t size = 0;
+
+ if (tkt->authorization_data == NULL) {
+ tkt->authorization_data = calloc(1, sizeof(*tkt->authorization_data));
+ if (tkt->authorization_data == NULL) {
+ return krb5_enomem(context);
+ }
+ }
+
+ /* add the entry to the last element */
+ {
+ AuthorizationData ad = { 0, NULL };
+ AuthorizationDataElement ade;
+
+ ade.ad_type = type;
+ ade.ad_data = *data;
+
+ ret = add_AuthorizationData(&ad, &ade);
+ if (ret) {
+ krb5_set_error_message(context, ret, "add AuthorizationData failed");
+ return ret;
+ }
+
+ ade.ad_type = KRB5_AUTHDATA_IF_RELEVANT;
+
+ ASN1_MALLOC_ENCODE(AuthorizationData,
+ ade.ad_data.data, ade.ad_data.length,
+ &ad, &size, ret);
+ free_AuthorizationData(&ad);
+ if (ret) {
+ krb5_set_error_message(context, ret, "ASN.1 encode of "
+ "AuthorizationData failed");
+ return ret;
+ }
+ if (ade.ad_data.length != size)
+ krb5_abortx(context, "internal asn.1 encoder error");
+
+ ret = add_AuthorizationData(tkt->authorization_data, &ade);
+ der_free_octet_string(&ade.ad_data);
+ if (ret) {
+ krb5_set_error_message(context, ret, "add AuthorizationData failed");
+ return ret;
+ }
+ }
+
+ return 0;
+}
+
+/*
+ * Insert a PAC wrapped in AD-IF-RELEVANT container as the first AD element,
+ * as some clients such as Windows may fail to parse it otherwise.
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_kdc_tkt_insert_pac(krb5_context context,
+ EncTicketPart *tkt,
+ const krb5_data *data)
+{
+ AuthorizationDataElement ade;
+ unsigned int i;
+ krb5_error_code ret;
+
+ ret = _kdc_tkt_add_if_relevant_ad(context, tkt, KRB5_AUTHDATA_WIN2K_PAC,
+ data);
+ if (ret)
+ return ret;
+
+ heim_assert(tkt->authorization_data->len != 0, "No authorization_data!");
+ ade = tkt->authorization_data->val[tkt->authorization_data->len - 1];
+ for (i = 0; i < tkt->authorization_data->len - 1; i++) {
+ tkt->authorization_data->val[i + 1] = tkt->authorization_data->val[i];
+ }
+ tkt->authorization_data->val[0] = ade;
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/build_ap_req.c b/third_party/heimdal/lib/krb5/build_ap_req.c
new file mode 100644
index 0000000..0101952
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/build_ap_req.c
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_build_ap_req (krb5_context context,
+ krb5_enctype enctype,
+ krb5_creds *cred,
+ krb5_flags ap_options,
+ krb5_data authenticator,
+ krb5_data *retdata)
+{
+ krb5_error_code ret = 0;
+ AP_REQ ap;
+ size_t len;
+
+ ap.pvno = 5;
+ ap.msg_type = krb_ap_req;
+ memset(&ap.ap_options, 0, sizeof(ap.ap_options));
+ ap.ap_options.use_session_key = (ap_options & AP_OPTS_USE_SESSION_KEY) > 0;
+ ap.ap_options.mutual_required = (ap_options & AP_OPTS_MUTUAL_REQUIRED) > 0;
+
+ decode_Ticket(cred->ticket.data, cred->ticket.length, &ap.ticket, &len);
+ ap.authenticator.etype = enctype;
+ ap.authenticator.kvno = NULL;
+ ap.authenticator.cipher = authenticator;
+
+ ASN1_MALLOC_ENCODE(AP_REQ, retdata->data, retdata->length, &ap, &len, ret);
+ if (ret == 0 && retdata->length != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+ free_AP_REQ(&ap);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/build_auth.c b/third_party/heimdal/lib/krb5/build_auth.c
new file mode 100644
index 0000000..3e00125
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/build_auth.c
@@ -0,0 +1,267 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+static krb5_error_code
+add_auth_data(krb5_context context,
+ AuthorizationData *src,
+ AuthorizationData **dst)
+{
+ krb5_error_code ret = 0;
+ size_t i;
+
+ if (*dst == NULL &&
+ (*dst = calloc(1, sizeof(**dst))) == NULL)
+ return krb5_enomem(context);
+ for (i = 0; ret == 0 && i < src->len; i++)
+ ret = add_AuthorizationData(*dst, &src->val[i]);
+ return ret;
+}
+
+static krb5_error_code
+add_etypelist(krb5_context context,
+ krb5_authdata *auth_data)
+{
+ AuthorizationDataElement ade;
+ EtypeList etypes;
+ krb5_error_code ret;
+ krb5_data e;
+ size_t len = 0;
+
+ ret = _krb5_init_etype(context, KRB5_PDU_NONE,
+ &etypes.len, &etypes.val,
+ NULL);
+ if (ret)
+ return ret;
+
+ ASN1_MALLOC_ENCODE(EtypeList, e.data, e.length, &etypes, &len, ret);
+ if (ret) {
+ free_EtypeList(&etypes);
+ return ret;
+ }
+ if(e.length != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+ free_EtypeList(&etypes);
+
+ ade.ad_type = KRB5_AUTHDATA_GSS_API_ETYPE_NEGOTIATION;
+ ade.ad_data = e;
+
+ ret = add_AuthorizationData(auth_data, &ade);
+
+ krb5_data_free(&e);
+
+ return ret;
+}
+
+static krb5_error_code
+add_ap_options(krb5_context context,
+ krb5_authdata *auth_data)
+{
+ krb5_error_code ret;
+ AuthorizationDataElement ade;
+ krb5_boolean require_cb;
+ uint8_t ap_options[4];
+
+ require_cb = krb5_config_get_bool_default(context, NULL, FALSE,
+ "libdefaults",
+ "client_aware_channel_bindings",
+ NULL);
+
+ if (!require_cb)
+ return 0;
+
+ ap_options[0] = (KERB_AP_OPTIONS_CBT >> 0 ) & 0xFF;
+ ap_options[1] = (KERB_AP_OPTIONS_CBT >> 8 ) & 0xFF;
+ ap_options[2] = (KERB_AP_OPTIONS_CBT >> 16) & 0xFF;
+ ap_options[3] = (KERB_AP_OPTIONS_CBT >> 24) & 0xFF;
+
+ ade.ad_type = KRB5_AUTHDATA_AP_OPTIONS;
+ ade.ad_data.length = sizeof(ap_options);
+ ade.ad_data.data = ap_options;
+
+ ret = add_AuthorizationData(auth_data, &ade);
+
+ return ret;
+}
+
+static krb5_error_code
+make_ap_authdata(krb5_context context,
+ krb5_authdata **auth_data)
+{
+ krb5_error_code ret;
+ AuthorizationData ad;
+ krb5_data ir;
+ size_t len;
+
+ ad.len = 0;
+ ad.val = NULL;
+
+ ret = add_etypelist(context, &ad);
+ if (ret)
+ return ret;
+
+ /*
+ * Windows has a bug and only looks for first occurrence of AD-IF-RELEVANT
+ * in the AP authenticator when looking for AD-AP-OPTIONS. Make sure to
+ * bundle it together with etypes.
+ */
+ ret = add_ap_options(context, &ad);
+ if (ret) {
+ free_AuthorizationData(&ad);
+ return ret;
+ }
+
+ ASN1_MALLOC_ENCODE(AuthorizationData, ir.data, ir.length, &ad, &len, ret);
+ if (ret) {
+ free_AuthorizationData(&ad);
+ return ret;
+ }
+ if(ir.length != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ ret = _krb5_add_1auth_data(context, KRB5_AUTHDATA_IF_RELEVANT, &ir, 1,
+ auth_data);
+
+ free_AuthorizationData(&ad);
+ krb5_data_free(&ir);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_build_authenticator (krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_enctype enctype,
+ krb5_creds *cred,
+ Checksum *cksum,
+ krb5_data *result,
+ krb5_key_usage usage)
+{
+ Authenticator auth;
+ u_char *buf = NULL;
+ size_t buf_size;
+ size_t len = 0;
+ krb5_error_code ret;
+ krb5_crypto crypto;
+
+ memset(&auth, 0, sizeof(auth));
+
+ auth.authenticator_vno = 5;
+ ret = copy_Realm(&cred->client->realm, &auth.crealm);
+ if (ret)
+ goto fail;
+ ret = copy_PrincipalName(&cred->client->name, &auth.cname);
+ if (ret)
+ goto fail;
+
+ krb5_us_timeofday (context, &auth.ctime, &auth.cusec);
+
+ ret = krb5_auth_con_getlocalsubkey(context, auth_context, &auth.subkey);
+ if(ret)
+ goto fail;
+
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) {
+ if(auth_context->local_seqnumber == 0)
+ krb5_generate_seq_number (context,
+ &cred->session,
+ &auth_context->local_seqnumber);
+ ALLOC(auth.seq_number, 1);
+ if(auth.seq_number == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ *auth.seq_number = auth_context->local_seqnumber;
+ } else
+ auth.seq_number = NULL;
+ auth.authorization_data = NULL;
+
+ if (cksum) {
+ ALLOC(auth.cksum, 1);
+ if (auth.cksum == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ ret = copy_Checksum(cksum, auth.cksum);
+ if (ret)
+ goto fail;
+
+ if (auth.cksum->cksumtype == CKSUMTYPE_GSSAPI) {
+ /*
+ * This is not GSS-API specific, we only enable it for
+ * GSS for now
+ */
+ ret = make_ap_authdata(context, &auth.authorization_data);
+ if (ret)
+ goto fail;
+ }
+ }
+
+ /* Copy other authz data from auth_context */
+ if (auth_context->auth_data) {
+ ret = add_auth_data(context, auth_context->auth_data, &auth.authorization_data);
+ if (ret)
+ goto fail;
+ }
+
+ /* XXX - Copy more to auth_context? */
+
+ auth_context->authenticator->ctime = auth.ctime;
+ auth_context->authenticator->cusec = auth.cusec;
+
+ ASN1_MALLOC_ENCODE(Authenticator, buf, buf_size, &auth, &len, ret);
+ if (ret)
+ goto fail;
+ if(buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ ret = krb5_crypto_init(context, &cred->session, enctype, &crypto);
+ if (ret)
+ goto fail;
+ ret = krb5_encrypt (context,
+ crypto,
+ usage /* KRB5_KU_AP_REQ_AUTH */,
+ buf,
+ len,
+ result);
+ krb5_crypto_destroy(context, crypto);
+
+ if (ret)
+ goto fail;
+
+ fail:
+ free_Authenticator (&auth);
+ free (buf);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/cache.c b/third_party/heimdal/lib/krb5/cache.c
new file mode 100644
index 0000000..75083f8
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/cache.c
@@ -0,0 +1,2300 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ * @page krb5_ccache_intro The credential cache functions
+ * @section section_krb5_ccache Kerberos credential caches
+ *
+ * krb5_ccache structure holds a Kerberos credential cache.
+ *
+ * Heimdal support the follow types of credential caches:
+ *
+ * - SCC
+ * Store the credential in a database
+ * - FILE
+ * Store the credential in memory
+ * - MEMORY
+ * Store the credential in memory
+ * - API
+ * A credential cache server based solution for Mac OS X
+ * - KCM
+ * A credential cache server based solution for all platforms
+ *
+ * @subsection Example
+ *
+ * This is a minimalistic version of klist:
+@code
+#include <krb5.h>
+
+int
+main (int argc, char **argv)
+{
+ krb5_context context;
+ krb5_cc_cursor cursor;
+ krb5_error_code ret;
+ krb5_ccache id;
+ krb5_creds creds;
+
+ if (krb5_init_context (&context) != 0)
+ errx(1, "krb5_context");
+
+ ret = krb5_cc_default (context, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_default");
+
+ ret = krb5_cc_start_seq_get(context, id, &cursor);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_start_seq_get");
+
+ while((ret = krb5_cc_next_cred(context, id, &cursor, &creds)) == 0){
+ char *principal;
+
+ krb5_unparse_name(context, creds.server, &principal);
+ printf("principal: %s\\n", principal);
+ free(principal);
+ krb5_free_cred_contents (context, &creds);
+ }
+ ret = krb5_cc_end_seq_get(context, id, &cursor);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_end_seq_get");
+
+ krb5_cc_close(context, id);
+
+ krb5_free_context(context);
+ return 0;
+}
+* @endcode
+*/
+
+static const krb5_cc_ops *
+cc_get_prefix_ops(krb5_context context,
+ const char *prefix,
+ const char **residual);
+
+/**
+ * Add a new ccache type with operations `ops', overwriting any
+ * existing one if `override'.
+ *
+ * @param context a Kerberos context
+ * @param ops type of plugin symbol
+ * @param override flag to select if the registration is to overide
+ * an existing ops with the same name.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_register(krb5_context context,
+ const krb5_cc_ops *ops,
+ krb5_boolean override)
+{
+ int i;
+
+ for(i = 0; i < context->num_cc_ops && context->cc_ops[i]->prefix; i++) {
+ if(strcmp(context->cc_ops[i]->prefix, ops->prefix) == 0) {
+ if(!override) {
+ krb5_set_error_message(context,
+ KRB5_CC_TYPE_EXISTS,
+ N_("cache type %s already exists", "type"),
+ ops->prefix);
+ return KRB5_CC_TYPE_EXISTS;
+ }
+ break;
+ }
+ }
+ if(i == context->num_cc_ops) {
+ const krb5_cc_ops **o = realloc(rk_UNCONST(context->cc_ops),
+ (context->num_cc_ops + 1) *
+ sizeof(context->cc_ops[0]));
+ if(o == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOMEM,
+ N_("malloc: out of memory", ""));
+ return KRB5_CC_NOMEM;
+ }
+ context->cc_ops = o;
+ context->cc_ops[context->num_cc_ops] = NULL;
+ context->num_cc_ops++;
+ }
+ context->cc_ops[i] = ops;
+ return 0;
+}
+
+/*
+ * Allocate the memory for a `id' and the that function table to
+ * `ops'. Returns 0 or and error code.
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_cc_allocate(krb5_context context,
+ const krb5_cc_ops *ops,
+ krb5_ccache *id)
+{
+ krb5_ccache p;
+
+ p = calloc(1, sizeof(*p));
+ if (p == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOMEM,
+ N_("malloc: out of memory", ""));
+ return KRB5_CC_NOMEM;
+ }
+ p->ops = ops;
+ *id = p;
+
+ return 0;
+}
+
+/*
+ * Allocate memory for a new ccache in `id' with operations `ops'
+ * and name `residual'. Return 0 or an error code.
+ */
+
+static krb5_error_code
+allocate_ccache(krb5_context context,
+ const krb5_cc_ops *ops,
+ const char *residual,
+ const char *subsidiary,
+ krb5_ccache *id)
+{
+ krb5_error_code ret = 0;
+ char *exp_residual = NULL;
+ int filepath;
+
+ filepath = (strcmp("FILE", ops->prefix) == 0
+ || strcmp("DIR", ops->prefix) == 0
+ || strcmp("SCC", ops->prefix) == 0);
+
+ if (residual)
+ ret = _krb5_expand_path_tokens(context, residual, filepath, &exp_residual);
+ if (ret == 0)
+ ret = _krb5_cc_allocate(context, ops, id);
+
+ if (ret == 0) {
+ if ((*id)->ops->version < KRB5_CC_OPS_VERSION_5
+ || (*id)->ops->resolve_2 == NULL) {
+ ret = (*id)->ops->resolve(context, id, exp_residual);
+ } else {
+ ret = (*id)->ops->resolve_2(context, id, exp_residual, subsidiary);
+ }
+ }
+ if (ret) {
+ free(*id);
+ *id = NULL;
+ }
+ free(exp_residual);
+ return ret;
+}
+
+
+/**
+ * Find and allocate a ccache in `id' from the specification in `residual'.
+ * If the ccache name doesn't contain any colon, interpret it as a file name.
+ *
+ * @param context a Kerberos context.
+ * @param name string name of a credential cache.
+ * @param id return pointer to a found credential cache.
+ *
+ * @return Return 0 or an error code. In case of an error, id is set
+ * to NULL, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_resolve(krb5_context context,
+ const char *name,
+ krb5_ccache *id)
+{
+ const krb5_cc_ops *ops;
+ const char *residual = NULL;
+
+ *id = NULL;
+
+ ops = cc_get_prefix_ops(context, name, &residual);
+ if (ops == NULL)
+ ops = &krb5_fcc_ops; /* residual will point to name */
+
+ return allocate_ccache(context, ops, residual, NULL, id);
+}
+
+#ifdef _WIN32
+static const char *
+get_default_cc_type_win32(krb5_context context)
+{
+ krb5_error_code ret;
+ krb5_ccache id;
+
+ /*
+ * If the MSLSA ccache type has a principal name,
+ * use it as the default.
+ */
+ ret = krb5_cc_resolve(context, "MSLSA:", &id);
+ if (ret == 0) {
+ krb5_principal princ;
+ ret = krb5_cc_get_principal(context, id, &princ);
+ krb5_cc_close(context, id);
+ if (ret == 0) {
+ krb5_free_principal(context, princ);
+ return "MSLSA";
+ }
+ }
+
+ /*
+ * If the API: ccache can be resolved,
+ * use it as the default.
+ */
+ ret = krb5_cc_resolve(context, "API:", &id);
+ if (ret == 0) {
+ krb5_cc_close(context, id);
+ return "API";
+ }
+
+ return NULL;
+}
+#endif /* _WIN32 */
+
+static const char *
+get_default_cc_type(krb5_context context, int simple)
+{
+ const char *def_ccname;
+ const char *def_cctype =
+ krb5_config_get_string_default(context, NULL,
+ secure_getenv("KRB5CCTYPE"),
+ "libdefaults", "default_cc_type", NULL);
+ const char *def_cccol =
+ krb5_config_get_string(context, NULL, "libdefaults",
+ "default_cc_collection", NULL);
+ const krb5_cc_ops *ops;
+
+ if (!simple && (def_ccname = krb5_cc_default_name(context))) {
+ ops = cc_get_prefix_ops(context, def_ccname, NULL);
+ if (ops)
+ return ops->prefix;
+ }
+ if (!def_cctype && def_cccol) {
+ ops = cc_get_prefix_ops(context, def_cccol, NULL);
+ if (ops)
+ return ops->prefix;
+ }
+#ifdef _WIN32
+ if (def_cctype == NULL)
+ def_cctype = get_default_cc_type_win32(context);
+#endif
+ if (def_cctype == NULL)
+ def_cctype = KRB5_DEFAULT_CCTYPE->prefix;
+ return def_cctype;
+}
+
+/**
+ * Find and allocate a ccache in `id' for the subsidiary cache named by
+ * `subsidiary' in the collection named by `collection'.
+ *
+ * @param context a Kerberos context.
+ * @param cctype string name of a credential cache collection type.
+ * @param collection string name of a credential cache collection.
+ * @param subsidiary string name of a credential cache in a collection.
+ * @param id return pointer to a found credential cache.
+ *
+ * @return Return 0 or an error code. In case of an error, id is set
+ * to NULL, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_resolve_sub(krb5_context context,
+ const char *cctype,
+ const char *collection,
+ const char *subsidiary,
+ krb5_ccache *id)
+{
+ const krb5_cc_ops *ops = NULL;
+
+ *id = NULL;
+
+ /* Get the cctype from the collection, maybe */
+ if (cctype == NULL && collection)
+ ops = cc_get_prefix_ops(context, collection, &collection);
+
+ if (ops == NULL)
+ ops = cc_get_prefix_ops(context, get_default_cc_type(context, 0), NULL);
+
+ if (ops == NULL) {
+ krb5_set_error_message(context, KRB5_CC_UNKNOWN_TYPE,
+ N_("unknown ccache type %s", ""), cctype);
+ return KRB5_CC_UNKNOWN_TYPE;
+ }
+
+ return allocate_ccache(context, ops, collection, subsidiary, id);
+}
+
+
+/**
+ * Find and allocate a ccache in `id' from the specification in `residual', but
+ * specific to the given principal `principal' by using the principal name as
+ * the name of a "subsidiary" credentials cache in the collection named by
+ * `name'. If the ccache name doesn't contain any colon, interpret it as a
+ * file name.
+ *
+ * @param context a Kerberos context.
+ * @param name string name of a credential cache.
+ * @param principal principal name of desired credentials.
+ * @param id return pointer to a found credential cache.
+ *
+ * @return Return 0 or an error code. In case of an error, id is set
+ * to NULL, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_resolve_for(krb5_context context,
+ const char *cctype,
+ const char *name,
+ krb5_const_principal principal,
+ krb5_ccache *id)
+{
+ krb5_error_code ret;
+ char *p, *s;
+
+ *id = NULL;
+
+ ret = krb5_unparse_name(context, principal, &p);
+ if (ret)
+ return ret;
+ /*
+ * Subsidiary components cannot have various chars in them that are used as
+ * separators. ':' is used for subsidiary separators in all ccache types
+ * except FILE, where '+' is used instead because we can't use ':' in file
+ * paths on Windows and because ':' is not in the POSIX safe set.
+ */
+ for (s = p; *s; s++) {
+ switch (s[0]) {
+ case ':':
+ case '+':
+ case '/':
+ case '\\':
+ s[0] = '-';
+ default: break;
+ }
+ }
+ ret = krb5_cc_resolve_sub(context, cctype, name, p, id);
+ free(p);
+ return ret;
+}
+
+/**
+ * Generates a new unique ccache of `type` in `id'. If `type' is NULL,
+ * the library chooses the default credential cache type. The supplied
+ * `hint' (that can be NULL) is a string that the credential cache
+ * type can use to base the name of the credential on, this is to make
+ * it easier for the user to differentiate the credentials.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_new_unique(krb5_context context, const char *type,
+ const char *hint, krb5_ccache *id)
+{
+ const krb5_cc_ops *ops;
+ krb5_error_code ret;
+
+ if (type == NULL)
+ type = get_default_cc_type(context, 1);
+
+ ops = krb5_cc_get_prefix_ops(context, type);
+ if (ops == NULL) {
+ krb5_set_error_message(context, KRB5_CC_UNKNOWN_TYPE,
+ "Credential cache type %s is unknown", type);
+ return KRB5_CC_UNKNOWN_TYPE;
+ }
+
+ ret = _krb5_cc_allocate(context, ops, id);
+ if (ret)
+ return ret;
+ ret = (*id)->ops->gen_new(context, id);
+ if (ret) {
+ free(*id);
+ *id = NULL;
+ }
+ return ret;
+}
+
+/**
+ * Return the name of the ccache `id'
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_cc_get_name(krb5_context context,
+ krb5_ccache id)
+{
+ const char *name = NULL;
+
+ if (id->ops->version < KRB5_CC_OPS_VERSION_5
+ || id->ops->get_name_2 == NULL)
+ return id->ops->get_name(context, id);
+
+ (void) id->ops->get_name_2(context, id, &name, NULL, NULL);
+ return name;
+}
+
+/**
+ * Return the name of the ccache collection associated with `id'
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_cc_get_collection(krb5_context context, krb5_ccache id)
+{
+ const char *name = NULL;
+
+ if (id->ops->version < KRB5_CC_OPS_VERSION_5
+ || id->ops->get_name_2 == NULL)
+ return NULL;
+
+ (void) id->ops->get_name_2(context, id, NULL, &name, NULL);
+ return name;
+}
+
+/**
+ * Return the name of the subsidiary ccache of `id'
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_cc_get_subsidiary(krb5_context context, krb5_ccache id)
+{
+ const char *name = NULL;
+
+ if (id->ops->version >= KRB5_CC_OPS_VERSION_5
+ && id->ops->get_name_2 != NULL)
+ (void) id->ops->get_name_2(context, id, NULL, NULL, &name);
+ return name;
+}
+
+/**
+ * Return the type of the ccache `id'.
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_cc_get_type(krb5_context context,
+ krb5_ccache id)
+{
+ return id->ops->prefix;
+}
+
+/**
+ * Return the complete resolvable name the cache
+
+ * @param context a Kerberos context
+ * @param id return pointer to a found credential cache
+ * @param str the returned name of a credential cache, free with krb5_xfree()
+ *
+ * @return Returns 0 or an error (and then *str is set to NULL).
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_full_name(krb5_context context,
+ krb5_ccache id,
+ char **str)
+{
+ const char *type, *name;
+
+ *str = NULL;
+
+ type = krb5_cc_get_type(context, id);
+ if (type == NULL) {
+ krb5_set_error_message(context, KRB5_CC_UNKNOWN_TYPE,
+ "cache have no name of type");
+ return KRB5_CC_UNKNOWN_TYPE;
+ }
+
+ name = krb5_cc_get_name(context, id);
+ if (name == NULL) {
+ krb5_set_error_message(context, KRB5_CC_BADNAME,
+ "cache of type %s have no name", type);
+ return KRB5_CC_BADNAME;
+ }
+
+ if (asprintf(str, "%s:%s", type, name) == -1) {
+ *str = NULL;
+ return krb5_enomem(context);
+ }
+ return 0;
+}
+
+/**
+ * Return krb5_cc_ops of a the ccache `id'.
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION const krb5_cc_ops * KRB5_LIB_CALL
+krb5_cc_get_ops(krb5_context context, krb5_ccache id)
+{
+ return id->ops;
+}
+
+/*
+ * Expand variables in `str' into `res'
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_expand_default_cc_name(krb5_context context, const char *str, char **res)
+{
+ int filepath;
+
+ filepath = (strncmp("FILE:", str, 5) == 0
+ || strncmp("DIR:", str, 4) == 0
+ || strncmp("SCC:", str, 4) == 0);
+
+ return _krb5_expand_path_tokens(context, str, filepath, res);
+}
+
+/*
+ * Return non-zero if envirnoment that will determine default krb5cc
+ * name has changed.
+ */
+
+static int
+environment_changed(krb5_context context)
+{
+ const char *e;
+
+ /* if the cc name was set, don't change it */
+ if (context->default_cc_name_set)
+ return 0;
+
+ /* XXX performance: always ask KCM/API if default name has changed */
+ if (context->default_cc_name &&
+ (strncmp(context->default_cc_name, "KCM:", 4) == 0 ||
+ strncmp(context->default_cc_name, "API:", 4) == 0))
+ return 1;
+
+ e = secure_getenv("KRB5CCNAME");
+ if (e == NULL) {
+ if (context->default_cc_name_env) {
+ free(context->default_cc_name_env);
+ context->default_cc_name_env = NULL;
+ return 1;
+ }
+ } else {
+ if (context->default_cc_name_env == NULL)
+ return 1;
+ if (strcmp(e, context->default_cc_name_env) != 0)
+ return 1;
+ }
+ return 0;
+}
+
+/**
+ * Switch the default default credential cache for a specific
+ * credcache type (and name for some implementations).
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_switch(krb5_context context, krb5_ccache id)
+{
+#ifdef _WIN32
+ _krb5_set_default_cc_name_to_registry(context, id);
+#endif
+
+ if (id->ops->version == KRB5_CC_OPS_VERSION_0
+ || id->ops->set_default == NULL)
+ return 0;
+
+ return (*id->ops->set_default)(context, id);
+}
+
+/**
+ * Return true if the default credential cache support switch
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_cc_support_switch(krb5_context context, const char *type)
+{
+ const krb5_cc_ops *ops;
+
+ ops = krb5_cc_get_prefix_ops(context, type);
+ if (ops && ops->version > KRB5_CC_OPS_VERSION_0 && ops->set_default)
+ return 1;
+ return FALSE;
+}
+
+/**
+ * Set the default cc name for `context' to `name'.
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_set_default_name(krb5_context context, const char *name)
+{
+ krb5_error_code ret = 0;
+ char *p = NULL;
+
+ if (name == NULL) {
+ const char *e;
+
+ if ((e = secure_getenv("KRB5CCNAME"))) {
+ if ((p = strdup(e)) == NULL)
+ return krb5_enomem(context);
+
+ free(context->default_cc_name_env);
+ context->default_cc_name_env = p;
+
+ if ((p = strdup(e)) == NULL)
+ return krb5_enomem(context);
+
+ /*
+ * We're resetting the default ccache name. Recall that we got
+ * this from the environment, which might change.
+ */
+ context->default_cc_name_set = 0;
+ } else if ((e = krb5_cc_configured_default_name(context))) {
+ if ((p = strdup(e)) == NULL)
+ return krb5_enomem(context);
+
+ /*
+ * Since $KRB5CCNAME was not set, and since we got the default
+ * ccache name from configuration, we'll not want
+ * environment_changed() to return true to avoid re-doing the
+ * krb5_cc_configured_default_name() call unnecessarily.
+ *
+ * XXX Perhaps if we got the ccache name from the registry then
+ * we'd want to recheck it? If so we might need an indication
+ * from krb5_cc_configured_default_name() about that!
+ */
+ context->default_cc_name_set = 1;
+ }
+ } else {
+ int filepath = (strncmp("FILE:", name, 5) == 0 ||
+ strncmp("DIR:", name, 4) == 0 ||
+ strncmp("SCC:", name, 4) == 0);
+
+ ret = _krb5_expand_path_tokens(context, name, filepath, &p);
+ if (ret)
+ return ret;
+
+ /*
+ * Since the default ccache name was set explicitly, we won't want
+ * environment_changed() to return true until the default ccache name
+ * is reset.
+ */
+ context->default_cc_name_set = 1;
+ }
+
+ free(context->default_cc_name);
+ context->default_cc_name = p;
+ return 0;
+}
+
+/**
+ * Return a pointer to a context static string containing the default
+ * ccache name.
+ *
+ * @return String to the default credential cache name.
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_cc_default_name(krb5_context context)
+{
+ if (context->default_cc_name == NULL || environment_changed(context))
+ krb5_cc_set_default_name(context, NULL);
+
+ return context->default_cc_name;
+}
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+krb5_cc_configured_default_name(krb5_context context)
+{
+ krb5_error_code ret = 0;
+#ifdef _WIN32
+ krb5_ccache id;
+#endif
+ const char *cfg;
+ char *expanded;
+ const krb5_cc_ops *ops;
+
+ if (context->configured_default_cc_name)
+ return context->configured_default_cc_name;
+
+#ifdef _WIN32
+ if ((expanded = _krb5_get_default_cc_name_from_registry(context)))
+ return context->configured_default_cc_name = expanded;
+#endif
+
+ /* If there's a configured default, expand the tokens and use it */
+ cfg = krb5_config_get_string(context, NULL, "libdefaults",
+ "default_cc_name", NULL);
+ if (cfg == NULL)
+ cfg = krb5_config_get_string(context, NULL, "libdefaults",
+ "default_ccache_name", NULL);
+ if (cfg) {
+ ret = _krb5_expand_default_cc_name(context, cfg, &expanded);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ "token expansion failed for %s", cfg);
+ return NULL;
+ }
+ return context->configured_default_cc_name = expanded;
+ }
+
+ /* Else try a configured default ccache type's default */
+ cfg = get_default_cc_type(context, 1);
+ if ((ops = krb5_cc_get_prefix_ops(context, cfg)) == NULL) {
+ krb5_set_error_message(context, KRB5_CC_UNKNOWN_TYPE,
+ "unknown configured credential cache "
+ "type %s", cfg);
+ return NULL;
+ }
+
+ /* The get_default_name() method expands any tokens */
+ ret = (*ops->get_default_name)(context, &expanded);
+ if (ret) {
+ krb5_set_error_message(context, ret, "failed to find a default "
+ "ccache for default ccache type %s", cfg);
+ return NULL;
+ }
+ return context->configured_default_cc_name = expanded;
+}
+
+KRB5_LIB_FUNCTION char * KRB5_LIB_CALL
+krb5_cccol_get_default_ccname(krb5_context context)
+{
+ const char *cfg = get_default_cc_type(context, 1);
+ char *cccol_default_ccname;
+ const krb5_cc_ops *ops = krb5_cc_get_prefix_ops(context, cfg);
+
+ (void) (*ops->get_default_name)(context, &cccol_default_ccname);
+ return cccol_default_ccname;
+}
+
+/**
+ * Open the default ccache in `id'.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_default(krb5_context context,
+ krb5_ccache *id)
+{
+ const char *p = krb5_cc_default_name(context);
+
+ *id = NULL;
+ if (p == NULL)
+ return krb5_enomem(context);
+ return krb5_cc_resolve(context, p, id);
+}
+
+/**
+ * Open the named subsidiary cache from the default ccache collection in `id'.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_default_sub(krb5_context context,
+ const char *subsidiary,
+ krb5_ccache *id)
+{
+ return krb5_cc_resolve_sub(context, get_default_cc_type(context, 0), NULL,
+ subsidiary, id);
+}
+
+/**
+ * Open the default ccache in `id' that corresponds to the given principal.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_default_for(krb5_context context,
+ krb5_const_principal principal,
+ krb5_ccache *id)
+{
+ return krb5_cc_resolve_for(context, get_default_cc_type(context, 0), NULL,
+ principal, id);
+}
+
+/**
+ * Create a new ccache in `id' for `primary_principal'.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_initialize(krb5_context context,
+ krb5_ccache id,
+ krb5_principal primary_principal)
+{
+ krb5_error_code ret;
+
+ ret = (*id->ops->init)(context, id, primary_principal);
+ if (ret == 0) {
+ id->cc_kx509_done = 0;
+ id->cc_initialized = 1;
+ id->cc_need_start_realm = 1;
+ id->cc_start_tgt_stored = 0;
+ }
+ return ret;
+}
+
+
+/**
+ * Remove the ccache `id'.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_destroy(krb5_context context,
+ krb5_ccache id)
+{
+ krb5_error_code ret2 = 0;
+ krb5_error_code ret;
+ krb5_data d;
+
+ /*
+ * Destroy associated hx509 PKIX credential store created by krb5_kx509*().
+ */
+ if (krb5_cc_get_config(context, id, NULL, "kx509store", &d) == 0) {
+ char *name;
+
+ if ((name = strndup(d.data, d.length)) == NULL) {
+ ret2 = krb5_enomem(context);
+ } else {
+ hx509_certs certs;
+ ret = hx509_certs_init(context->hx509ctx, name, 0, NULL, &certs);
+ if (ret == 0)
+ ret2 = hx509_certs_destroy(context->hx509ctx, &certs);
+ else
+ hx509_certs_free(&certs);
+ free(name);
+ }
+ }
+
+ ret = (*id->ops->destroy)(context, id);
+ (void) krb5_cc_close(context, id);
+ return ret ? ret : ret2;
+}
+
+/**
+ * Stop using the ccache `id' and free the related resources.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_close(krb5_context context,
+ krb5_ccache id)
+{
+ krb5_error_code ret;
+
+ if (!id)
+ return 0;
+
+ /*
+ * We want to automatically acquire a PKIX credential using kx509.
+ *
+ * This can be slow if we're generating an RSA key. Plus it means talking
+ * to the KDC.
+ *
+ * We only want to do this when:
+ *
+ * - krb5_cc_initialize() was called on this ccache handle,
+ * - a start TGT was stored (actually, a cross-realm TGT would do),
+ *
+ * and
+ *
+ * - we aren't creating a gss_cred_id_t for a delegated credential.
+ *
+ * We only have a heuristic for the last condition: that `id' is not a
+ * MEMORY ccache, which is what's used for delegated credentials.
+ *
+ * We really only want to do this when storing a credential in a user's
+ * default ccache, but we leave it to krb5_kx509() to do that check.
+ *
+ * XXX Perhaps we should do what krb5_kx509() does here, and just call
+ * krb5_kx509_ext() (renamed to krb5_kx509()). Then we wouldn't need
+ * the delegated cred handle heuristic.
+ */
+ if (id->cc_initialized && id->cc_start_tgt_stored && !id->cc_kx509_done &&
+ strcmp("MEMORY", krb5_cc_get_type(context, id)) != 0) {
+ krb5_boolean enabled;
+
+ krb5_appdefault_boolean(context, NULL, NULL, "enable_kx509", FALSE,
+ &enabled);
+ if (enabled) {
+ _krb5_debug(context, 2, "attempting to fetch a certificate using "
+ "kx509");
+ ret = krb5_kx509(context, id, NULL);
+ if (ret)
+ _krb5_debug(context, 2, "failed to fetch a certificate");
+ else
+ _krb5_debug(context, 2, "fetched a certificate");
+ }
+ }
+
+ ret = (*id->ops->close)(context, id);
+ free(id);
+ return ret;
+}
+
+/**
+ * Store `creds' in the ccache `id'.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_store_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_creds *creds)
+{
+ krb5_error_code ret;
+ krb5_data realm;
+ const char *cfg = "";
+
+ /* Automatic cc_config-setting and other actions */
+ if (krb5_principal_get_num_comp(context, creds->server) > 1 &&
+ krb5_is_config_principal(context, creds->server))
+ cfg = krb5_principal_get_comp_string(context, creds->server, 1);
+
+ if (id->cc_initialized && !id->cc_need_start_realm &&
+ strcmp(cfg, "start_realm") == 0)
+ return 0;
+
+ ret = (*id->ops->store)(context, id, creds);
+ if (ret)
+ return ret;
+
+ if (id->cc_initialized && !id->cc_start_tgt_stored &&
+ id->cc_need_start_realm &&
+ krb5_principal_is_root_krbtgt(context, creds->server)) {
+ /* Mark the first root TGT's realm as the start realm */
+ id->cc_start_tgt_stored = 1;
+ realm.length = strlen(creds->server->realm);
+ realm.data = creds->server->realm;
+ (void) krb5_cc_set_config(context, id, NULL, "start_realm", &realm);
+ id->cc_need_start_realm = 0;
+ } else if (id->cc_initialized && id->cc_start_tgt_stored &&
+ !id->cc_kx509_done && strcmp(cfg, "kx509cert") == 0) {
+ /*
+ * Do not attempt kx509 at cc close time -- we're copying a ccache and
+ * we've already got a cert (and private key).
+ */
+ id->cc_kx509_done = 1;
+ } else if (id->cc_initialized && id->cc_start_tgt_stored &&
+ !id->cc_kx509_done && strcmp(cfg, "kx509_service_status") == 0) {
+ /*
+ * Do not attempt kx509 at cc close time -- we're copying a ccache and
+ * we know the kx509 service is not available.
+ */
+ id->cc_kx509_done = 1;
+ } else if (id->cc_initialized && strcmp(cfg, "start_realm") == 0) {
+ /*
+ * If the caller is storing a start_realm ccconfig, then stop looking
+ * for root TGTs to mark as the start_realm.
+ *
+ * By honoring any start_realm cc config stored, we interop both, with
+ * ccache implementations that don't preserve insertion order, and
+ * Kerberos implementations that store this cc config before the TGT.
+ */
+ id->cc_need_start_realm = 0;
+ }
+ return ret;
+}
+
+/**
+ * Retrieve the credential identified by `mcreds' (and `whichfields')
+ * from `id' in `creds'. 'creds' must be free by the caller using
+ * krb5_free_cred_contents.
+ *
+ * @param context A Kerberos 5 context
+ * @param id a Kerberos 5 credential cache
+ * @param whichfields what fields to use for matching credentials, same
+ * flags as whichfields in krb5_compare_creds()
+ * @param mcreds template credential to use for comparing
+ * @param creds returned credential, free with krb5_free_cred_contents()
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_retrieve_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_flags whichfields,
+ const krb5_creds *mcreds,
+ krb5_creds *creds)
+{
+ krb5_error_code ret;
+ krb5_cc_cursor cursor;
+
+ if (id->ops->retrieve != NULL) {
+ return (*id->ops->retrieve)(context, id, whichfields,
+ mcreds, creds);
+ }
+
+ ret = krb5_cc_start_seq_get(context, id, &cursor);
+ if (ret)
+ return ret;
+ while((ret = krb5_cc_next_cred(context, id, &cursor, creds)) == 0){
+ if(krb5_compare_creds(context, whichfields, mcreds, creds)){
+ ret = 0;
+ break;
+ }
+ krb5_free_cred_contents (context, creds);
+ }
+ krb5_cc_end_seq_get(context, id, &cursor);
+ return ret;
+}
+
+/**
+ * Return the principal of `id' in `principal'.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_principal(krb5_context context,
+ krb5_ccache id,
+ krb5_principal *principal)
+{
+ return (*id->ops->get_princ)(context, id, principal);
+}
+
+/**
+ * Start iterating over `id', `cursor' is initialized to the
+ * beginning. Caller must free the cursor with krb5_cc_end_seq_get().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_start_seq_get (krb5_context context,
+ const krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+ return (*id->ops->get_first)(context, id, cursor);
+}
+
+/**
+ * Retrieve the next cred pointed to by (`id', `cursor') in `creds'
+ * and advance `cursor'.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_next_cred (krb5_context context,
+ const krb5_ccache id,
+ krb5_cc_cursor *cursor,
+ krb5_creds *creds)
+{
+ return (*id->ops->get_next)(context, id, cursor, creds);
+}
+
+/**
+ * Destroy the cursor `cursor'.
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_end_seq_get (krb5_context context,
+ const krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+ return (*id->ops->end_get)(context, id, cursor);
+}
+
+/**
+ * Remove the credential identified by `cred', `which' from `id'.
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_remove_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_flags which,
+ krb5_creds *cred)
+{
+ if(id->ops->remove_cred == NULL) {
+ krb5_set_error_message(context,
+ EACCES,
+ "ccache %s does not support remove_cred",
+ id->ops->prefix);
+ return EACCES; /* XXX */
+ }
+ return (*id->ops->remove_cred)(context, id, which, cred);
+}
+
+/**
+ * Set the flags of `id' to `flags'.
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_set_flags(krb5_context context,
+ krb5_ccache id,
+ krb5_flags flags)
+{
+ return (*id->ops->set_flags)(context, id, flags);
+}
+
+/**
+ * Get the flags of `id', store them in `flags'.
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_flags(krb5_context context,
+ krb5_ccache id,
+ krb5_flags *flags)
+{
+ *flags = 0;
+ return 0;
+}
+
+/**
+ * Copy the contents of `from' to `to' if the given match function
+ * return true.
+ *
+ * @param context A Kerberos 5 context.
+ * @param from the cache to copy data from.
+ * @param to the cache to copy data to.
+ * @param match a match function that should return TRUE if cred argument should be copied, if NULL, all credentials are copied.
+ * @param matchctx context passed to match function.
+ * @param matched set to true if there was a credential that matched, may be NULL.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_copy_match_f(krb5_context context,
+ const krb5_ccache from,
+ krb5_ccache to,
+ krb5_boolean (*match)(krb5_context, void *, const krb5_creds *),
+ void *matchctx,
+ unsigned int *matched)
+{
+ krb5_error_code ret;
+ krb5_cc_cursor cursor;
+ krb5_creds cred;
+ krb5_principal princ;
+
+ if (matched)
+ *matched = 0;
+
+ ret = krb5_cc_get_principal(context, from, &princ);
+ if (ret)
+ return ret;
+ ret = krb5_cc_initialize(context, to, princ);
+ if (ret) {
+ krb5_free_principal(context, princ);
+ return ret;
+ }
+ ret = krb5_cc_start_seq_get(context, from, &cursor);
+ if (ret) {
+ krb5_free_principal(context, princ);
+ return ret;
+ }
+
+ while ((ret = krb5_cc_next_cred(context, from, &cursor, &cred)) == 0) {
+ if (match == NULL || (*match)(context, matchctx, &cred)) {
+ if (matched)
+ (*matched)++;
+ ret = krb5_cc_store_cred(context, to, &cred);
+ if (ret)
+ break;
+ }
+ krb5_free_cred_contents(context, &cred);
+ }
+ krb5_cc_end_seq_get(context, from, &cursor);
+ krb5_free_principal(context, princ);
+ if (ret == KRB5_CC_END)
+ ret = 0;
+ return ret;
+}
+
+/**
+ * Just like krb5_cc_copy_match_f(), but copy everything.
+ *
+ * @ingroup @krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_copy_cache(krb5_context context,
+ const krb5_ccache from,
+ krb5_ccache to)
+{
+ return krb5_cc_copy_match_f(context, from, to, NULL, NULL, NULL);
+}
+
+/**
+ * Return the version of `id'.
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_version(krb5_context context,
+ const krb5_ccache id)
+{
+ if(id->ops->get_version)
+ return (*id->ops->get_version)(context, id);
+ else
+ return 0;
+}
+
+/**
+ * Clear `mcreds' so it can be used with krb5_cc_retrieve_cred
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_cc_clear_mcred(krb5_creds *mcred)
+{
+ memset(mcred, 0, sizeof(*mcred));
+}
+
+/**
+ * Get the cc ops that is registered in `context' to handle the
+ * prefix. prefix can be a complete credential cache name or a
+ * prefix, the function will only use part up to the first colon (:)
+ * if there is one. If prefix the argument is NULL, the default ccache
+ * implemtation is returned.
+ *
+ * @return Returns NULL if ops not found.
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION const krb5_cc_ops * KRB5_LIB_CALL
+krb5_cc_get_prefix_ops(krb5_context context, const char *prefix)
+{
+ return cc_get_prefix_ops(context, prefix, NULL);
+}
+
+/**
+ * Get the cc ops that is registered in `context' to handle the
+ * prefix. prefix can be a complete credential cache name or a
+ * prefix, the function will only use part up to the first colon (:)
+ * if there is one. If prefix the argument is NULL, the default ccache
+ * implementation is returned.
+ *
+ * If residual is non-NULL, it is set to the residual component of
+ * prefix (if present) or the prefix itself.
+ *
+ * @return Returns NULL if ops not found.
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+static const krb5_cc_ops *
+cc_get_prefix_ops(krb5_context context,
+ const char *prefix,
+ const char **residual)
+{
+ int i;
+
+ if (residual)
+ *residual = prefix;
+
+ if (prefix == NULL)
+ return KRB5_DEFAULT_CCTYPE;
+
+ /* Is absolute path? Or UNC path? */
+ if (ISPATHSEP(prefix[0]))
+ return &krb5_fcc_ops;
+
+#ifdef _WIN32
+ /* Is drive letter? */
+ if (isalpha(prefix[0]) && prefix[1] == ':')
+ return &krb5_fcc_ops;
+#endif
+
+ for(i = 0; i < context->num_cc_ops && context->cc_ops[i]->prefix; i++) {
+ size_t prefix_len = strlen(context->cc_ops[i]->prefix);
+
+ if (strncmp(context->cc_ops[i]->prefix, prefix, prefix_len) == 0 &&
+ (prefix[prefix_len] == ':' || prefix[prefix_len] == '\0')) {
+ if (residual) {
+ if (prefix[prefix_len] == ':' && prefix[prefix_len + 1] != '\0')
+ *residual = &prefix[prefix_len + 1];
+ else
+ *residual = NULL;
+ }
+
+ return context->cc_ops[i];
+ }
+ }
+
+ return NULL;
+}
+
+struct krb5_cc_cache_cursor_data {
+ const krb5_cc_ops *ops;
+ krb5_cc_cursor cursor;
+};
+
+/**
+ * Start iterating over all caches of specified type. See also
+ * krb5_cccol_cursor_new().
+
+ * @param context A Kerberos 5 context
+ * @param type optional type to iterate over, if NULL, the default cache is used.
+ * @param cursor cursor should be freed with krb5_cc_cache_end_seq_get().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_cache_get_first (krb5_context context,
+ const char *type,
+ krb5_cc_cache_cursor *cursor)
+{
+ const krb5_cc_ops *ops;
+ krb5_error_code ret;
+
+ if (type == NULL)
+ type = krb5_cc_default_name(context);
+
+ ops = krb5_cc_get_prefix_ops(context, type);
+ if (ops == NULL) {
+ krb5_set_error_message(context, KRB5_CC_UNKNOWN_TYPE,
+ "Unknown type \"%s\" when iterating "
+ "trying to iterate the credential caches", type);
+ return KRB5_CC_UNKNOWN_TYPE;
+ }
+
+ if (ops->get_cache_first == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOSUPP,
+ N_("Credential cache type %s doesn't support "
+ "iterations over caches", "type"),
+ ops->prefix);
+ return KRB5_CC_NOSUPP;
+ }
+
+ *cursor = calloc(1, sizeof(**cursor));
+ if (*cursor == NULL)
+ return krb5_enomem(context);
+
+ (*cursor)->ops = ops;
+
+ ret = ops->get_cache_first(context, &(*cursor)->cursor);
+ if (ret) {
+ free(*cursor);
+ *cursor = NULL;
+ }
+ return ret;
+}
+
+/**
+ * Retrieve the next cache pointed to by (`cursor') in `id'
+ * and advance `cursor'.
+ *
+ * @param context A Kerberos 5 context
+ * @param cursor the iterator cursor, returned by krb5_cc_cache_get_first()
+ * @param id next ccache
+ *
+ * @return Return 0 or an error code. Returns KRB5_CC_END when the end
+ * of caches is reached, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_cache_next (krb5_context context,
+ krb5_cc_cache_cursor cursor,
+ krb5_ccache *id)
+{
+ return cursor->ops->get_cache_next(context, cursor->cursor, id);
+}
+
+/**
+ * Destroy the cursor `cursor'.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_cache_end_seq_get (krb5_context context,
+ krb5_cc_cache_cursor cursor)
+{
+ krb5_error_code ret;
+ ret = cursor->ops->end_cache_get(context, cursor->cursor);
+ cursor->ops = NULL;
+ free(cursor);
+ return ret;
+}
+
+/**
+ * Search for a matching credential cache that have the
+ * `principal' as the default principal. On success, `id' needs to be
+ * freed with krb5_cc_close() or krb5_cc_destroy().
+ *
+ * @param context A Kerberos 5 context
+ * @param client The principal to search for
+ * @param id the returned credential cache
+ *
+ * @return On failure, error code is returned and `id' is set to NULL.
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_cache_match (krb5_context context,
+ krb5_principal client,
+ krb5_ccache *id)
+{
+ krb5_cccol_cursor cursor;
+ krb5_error_code ret;
+ krb5_ccache cache = NULL;
+ krb5_ccache expired_match = NULL;
+
+ *id = NULL;
+
+ ret = krb5_cccol_cursor_new (context, &cursor);
+ if (ret)
+ return ret;
+
+ while (krb5_cccol_cursor_next(context, cursor, &cache) == 0 && cache != NULL) {
+ krb5_principal principal;
+ krb5_boolean match;
+ time_t lifetime;
+
+ ret = krb5_cc_get_principal(context, cache, &principal);
+ if (ret)
+ goto next;
+
+ if (client->name.name_string.len == 0)
+ match = (strcmp(client->realm, principal->realm) == 0);
+ else
+ match = krb5_principal_compare(context, principal, client);
+ krb5_free_principal(context, principal);
+
+ if (!match)
+ goto next;
+
+ if (expired_match == NULL &&
+ (krb5_cc_get_lifetime(context, cache, &lifetime) != 0 || lifetime == 0)) {
+ expired_match = cache;
+ cache = NULL;
+ goto next;
+ }
+ break;
+
+ next:
+ if (cache)
+ krb5_cc_close(context, cache);
+ cache = NULL;
+ }
+
+ krb5_cccol_cursor_free(context, &cursor);
+
+ if (cache == NULL && expired_match) {
+ cache = expired_match;
+ expired_match = NULL;
+ } else if (expired_match) {
+ krb5_cc_close(context, expired_match);
+ } else if (cache == NULL) {
+ char *str;
+
+ (void) krb5_unparse_name(context, client, &str);
+ krb5_set_error_message(context, KRB5_CC_NOTFOUND,
+ N_("Principal %s not found in any "
+ "credential cache", ""),
+ str ? str : "<out of memory>");
+ if (str)
+ free(str);
+ return KRB5_CC_NOTFOUND;
+ }
+
+ *id = cache;
+
+ return 0;
+}
+
+/**
+ * Move the content from one credential cache to another. The
+ * operation is an atomic switch.
+ *
+ * @param context a Kerberos context
+ * @param from the credential cache to move the content from
+ * @param to the credential cache to move the content to
+
+ * @return On sucess, from is destroyed and closed. On failure, error code is
+ * returned and from and to are both still allocated; see
+ * krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_move(krb5_context context, krb5_ccache from, krb5_ccache to)
+{
+ krb5_error_code ret = ENOTSUP;
+ krb5_principal princ = NULL;
+
+ if (to->ops->move &&
+ strcmp(from->ops->prefix, to->ops->prefix) == 0) {
+ /*
+ * NOTE: to->ops->move() is expected to call
+ * krb5_cc_destroy(context, from) on success.
+ */
+ ret = (*to->ops->move)(context, from, to);
+ if (ret == 0)
+ return 0;
+ if (ret != EXDEV && ret != ENOTSUP && ret != KRB5_CC_NOSUPP &&
+ ret != KRB5_FCC_INTERNAL)
+ return ret;
+ /* Fallback to high-level copy */
+ } /* Else high-level copy */
+
+ /*
+ * Initialize destination, copy the source's contents to the destination,
+ * then destroy the source on success.
+ *
+ * It'd be nice if we could destroy any half-built destination if the copy
+ * fails, but the interface is not documented as doing so.
+ */
+ ret = krb5_cc_get_principal(context, from, &princ);
+ if (ret == 0)
+ ret = krb5_cc_initialize(context, to, princ);
+ krb5_free_principal(context, princ);
+ if (ret == 0)
+ ret = krb5_cc_copy_cache(context, from, to);
+ if (ret == 0)
+ krb5_cc_destroy(context, from);
+ return ret;
+}
+
+#define KRB5_CONF_NAME "krb5_ccache_conf_data"
+#define KRB5_REALM_NAME "X-CACHECONF:"
+
+static krb5_error_code
+build_conf_principals(krb5_context context, krb5_ccache id,
+ krb5_const_principal principal,
+ const char *name, krb5_creds *cred)
+{
+ krb5_principal client;
+ krb5_error_code ret;
+ char *pname = NULL;
+
+ memset(cred, 0, sizeof(*cred));
+
+ ret = krb5_cc_get_principal(context, id, &client);
+ if (ret)
+ return ret;
+
+ if (principal) {
+ ret = krb5_unparse_name(context, principal, &pname);
+ if (ret)
+ return ret;
+ }
+
+ ret = krb5_make_principal(context, &cred->server,
+ KRB5_REALM_NAME,
+ KRB5_CONF_NAME, name, pname, NULL);
+ free(pname);
+ if (ret) {
+ krb5_free_principal(context, client);
+ return ret;
+ }
+ ret = krb5_copy_principal(context, client, &cred->client);
+ krb5_free_principal(context, client);
+ return ret;
+}
+
+/**
+ * Return TRUE (non zero) if the principal is a configuration
+ * principal (generated part of krb5_cc_set_config()). Returns FALSE
+ * (zero) if not a configuration principal.
+ *
+ * @param context a Kerberos context
+ * @param principal principal to check if it a configuration principal
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_is_config_principal(krb5_context context,
+ krb5_const_principal principal)
+{
+ if (strcmp(principal->realm, KRB5_REALM_NAME) != 0)
+ return FALSE;
+
+ if (principal->name.name_string.len == 0 ||
+ strcmp(principal->name.name_string.val[0], KRB5_CONF_NAME) != 0)
+ return FALSE;
+
+ return TRUE;
+}
+
+/**
+ * Store some configuration for the credential cache in the cache.
+ * Existing configuration under the same name is over-written.
+ *
+ * @param context a Kerberos context
+ * @param id the credential cache to store the data for
+ * @param principal configuration for a specific principal, if
+ * NULL, global for the whole cache.
+ * @param name name under which the configuraion is stored.
+ * @param data data to store, if NULL, configure is removed.
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_set_config(krb5_context context, krb5_ccache id,
+ krb5_const_principal principal,
+ const char *name, krb5_data *data)
+{
+ krb5_error_code ret;
+ krb5_creds cred;
+
+ ret = build_conf_principals(context, id, principal, name, &cred);
+ if (ret)
+ goto out;
+
+ /* Remove old configuration */
+ ret = krb5_cc_remove_cred(context, id, 0, &cred);
+ if (ret && ret != KRB5_CC_NOTFOUND && ret != KRB5_CC_NOSUPP &&
+ ret != KRB5_FCC_INTERNAL)
+ goto out;
+
+ if (data) {
+ /* not that anyone care when this expire */
+ cred.times.authtime = time(NULL);
+ cred.times.endtime = cred.times.authtime + 3600 * 24 * 30;
+
+ ret = krb5_data_copy(&cred.ticket, data->data, data->length);
+ if (ret)
+ goto out;
+
+ ret = krb5_cc_store_cred(context, id, &cred);
+ }
+
+out:
+ krb5_free_cred_contents (context, &cred);
+ return ret;
+}
+
+/**
+ * Get some configuration for the credential cache in the cache.
+ *
+ * @param context a Kerberos context
+ * @param id the credential cache to store the data for
+ * @param principal configuration for a specific principal, if
+ * NULL, global for the whole cache.
+ * @param name name under which the configuraion is stored.
+ * @param data data to fetched, free with krb5_data_free()
+ * @return 0 on success, KRB5_CC_NOTFOUND or KRB5_CC_END if not found,
+ * or other system error.
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_config(krb5_context context, krb5_ccache id,
+ krb5_const_principal principal,
+ const char *name, krb5_data *data)
+{
+ krb5_creds mcred, cred;
+ krb5_error_code ret;
+
+ memset(&cred, 0, sizeof(cred));
+ krb5_data_zero(data);
+
+ ret = build_conf_principals(context, id, principal, name, &mcred);
+ if (ret)
+ goto out;
+
+ ret = krb5_cc_retrieve_cred(context, id, 0, &mcred, &cred);
+ if (ret)
+ goto out;
+
+ ret = krb5_data_copy(data, cred.ticket.data, cred.ticket.length);
+
+out:
+ krb5_free_cred_contents (context, &cred);
+ krb5_free_cred_contents (context, &mcred);
+ return ret;
+}
+
+/*
+ *
+ */
+
+struct krb5_cccol_cursor_data {
+ int idx;
+ krb5_cc_cache_cursor cursor;
+};
+
+/**
+ * Get a new cache interation cursor that will interate over all
+ * credentials caches independent of type.
+ *
+ * @param context a Kerberos context
+ * @param cursor passed into krb5_cccol_cursor_next() and free with krb5_cccol_cursor_free().
+ *
+ * @return Returns 0 or and error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cccol_cursor_new(krb5_context context, krb5_cccol_cursor *cursor)
+{
+ *cursor = calloc(1, sizeof(**cursor));
+ if (*cursor == NULL)
+ return krb5_enomem(context);
+ (*cursor)->idx = 0;
+ (*cursor)->cursor = NULL;
+
+ return 0;
+}
+
+/**
+ * Get next credential cache from the iteration.
+ *
+ * @param context A Kerberos 5 context
+ * @param cursor the iteration cursor
+ * @param cache the returned cursor, pointer is set to NULL on failure
+ * and a cache on success. The returned cache needs to be freed
+ * with krb5_cc_close() or destroyed with krb5_cc_destroy().
+ * MIT Kerberos behavies slightly diffrent and sets cache to NULL
+ * when all caches are iterated over and return 0.
+ *
+ * @return Return 0 or and error, KRB5_CC_END is returned at the end
+ * of iteration. See krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cccol_cursor_next(krb5_context context, krb5_cccol_cursor cursor,
+ krb5_ccache *cache)
+{
+ krb5_error_code ret = 0;
+
+ *cache = NULL;
+
+ while (cursor->idx < context->num_cc_ops) {
+
+ if (cursor->cursor == NULL) {
+ ret = krb5_cc_cache_get_first (context,
+ context->cc_ops[cursor->idx]->prefix,
+ &cursor->cursor);
+ if (ret) {
+ cursor->idx++;
+ continue;
+ }
+ }
+ ret = krb5_cc_cache_next(context, cursor->cursor, cache);
+ if (ret == 0)
+ break;
+
+ krb5_cc_cache_end_seq_get(context, cursor->cursor);
+ cursor->cursor = NULL;
+ if (ret != KRB5_CC_END)
+ break;
+
+ cursor->idx++;
+ }
+ if (cursor->idx >= context->num_cc_ops) {
+ krb5_set_error_message(context, KRB5_CC_END,
+ N_("Reached end of credential caches", ""));
+ return KRB5_CC_END;
+ }
+
+ return ret;
+}
+
+/**
+ * End an iteration and free all resources, can be done before end is reached.
+ *
+ * @param context A Kerberos 5 context
+ * @param cursor the iteration cursor to be freed.
+ *
+ * @return Return 0 or and error, KRB5_CC_END is returned at the end
+ * of iteration. See krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cccol_cursor_free(krb5_context context, krb5_cccol_cursor *cursor)
+{
+ krb5_cccol_cursor c = *cursor;
+
+ *cursor = NULL;
+ if (c) {
+ if (c->cursor)
+ krb5_cc_cache_end_seq_get(context, c->cursor);
+ free(c);
+ }
+ return 0;
+}
+
+/**
+ * Return the last time the credential cache was modified.
+ *
+ * @param context A Kerberos 5 context
+ * @param id The credential cache to probe
+ * @param mtime the last modification time, set to 0 on error.
+
+ * @return Return 0 or and error. See krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_last_change_time(krb5_context context,
+ krb5_ccache id,
+ krb5_timestamp *mtime)
+{
+ *mtime = 0;
+
+ if (id->ops->version < KRB5_CC_OPS_VERSION_2
+ || id->ops->lastchange == NULL)
+ return KRB5_CC_NOSUPP;
+
+ return (*id->ops->lastchange)(context, id, mtime);
+}
+
+/**
+ * Return the last modfication time for a cache collection. The query
+ * can be limited to a specific cache type. If the function return 0
+ * and mtime is 0, there was no credentials in the caches.
+ *
+ * @param context A Kerberos 5 context
+ * @param type The credential cache to probe, if NULL, all type are traversed.
+ * @param mtime the last modification time, set to 0 on error.
+
+ * @return Return 0 or and error. See krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cccol_last_change_time(krb5_context context,
+ const char *type,
+ krb5_timestamp *mtime)
+{
+ krb5_cccol_cursor cursor;
+ krb5_error_code ret;
+ krb5_ccache id;
+ krb5_timestamp t = 0;
+
+ *mtime = 0;
+
+ ret = krb5_cccol_cursor_new (context, &cursor);
+ if (ret)
+ return ret;
+
+ while (krb5_cccol_cursor_next(context, cursor, &id) == 0 && id != NULL) {
+
+ if (type && strcmp(krb5_cc_get_type(context, id), type) != 0)
+ continue;
+
+ ret = krb5_cc_last_change_time(context, id, &t);
+ krb5_cc_close(context, id);
+ if (ret)
+ continue;
+ if (t > *mtime)
+ *mtime = t;
+ }
+
+ krb5_cccol_cursor_free(context, &cursor);
+
+ return 0;
+}
+/**
+ * Return a friendly name on credential cache. Free the result with krb5_xfree().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_friendly_name(krb5_context context,
+ krb5_ccache id,
+ char **name)
+{
+ krb5_error_code ret;
+ krb5_data data;
+
+ ret = krb5_cc_get_config(context, id, NULL, "FriendlyName", &data);
+ if (ret) {
+ krb5_principal principal;
+ ret = krb5_cc_get_principal(context, id, &principal);
+ if (ret)
+ return ret;
+ ret = krb5_unparse_name(context, principal, name);
+ krb5_free_principal(context, principal);
+ } else {
+ ret = asprintf(name, "%.*s", (int)data.length, (char *)data.data);
+ krb5_data_free(&data);
+ if (ret <= 0)
+ ret = krb5_enomem(context);
+ else
+ ret = 0;
+ }
+
+ return ret;
+}
+
+/**
+ * Set the friendly name on credential cache.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_set_friendly_name(krb5_context context,
+ krb5_ccache id,
+ const char *name)
+{
+ krb5_data data;
+
+ data.data = rk_UNCONST(name);
+ data.length = strlen(name);
+
+ return krb5_cc_set_config(context, id, NULL, "FriendlyName", &data);
+}
+
+/**
+ * Get the lifetime of the initial ticket in the cache
+ *
+ * Get the lifetime of the initial ticket in the cache, if the initial
+ * ticket was not found, the error code KRB5_CC_END is returned.
+ *
+ * @param context A Kerberos 5 context.
+ * @param id a credential cache
+ * @param t the relative lifetime of the initial ticket
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_lifetime(krb5_context context, krb5_ccache id, time_t *t)
+{
+ krb5_data config_start_realm;
+ char *start_realm;
+ krb5_cc_cursor cursor;
+ krb5_error_code ret;
+ krb5_creds cred;
+ time_t now, endtime = 0;
+
+ *t = 0;
+ krb5_timeofday(context, &now);
+
+ ret = krb5_cc_get_config(context, id, NULL, "start_realm", &config_start_realm);
+ if (ret == 0) {
+ start_realm = strndup(config_start_realm.data, config_start_realm.length);
+ krb5_data_free(&config_start_realm);
+ } else {
+ krb5_principal client;
+
+ ret = krb5_cc_get_principal(context, id, &client);
+ if (ret)
+ return ret;
+ start_realm = strdup(krb5_principal_get_realm(context, client));
+ krb5_free_principal(context, client);
+ }
+ if (start_realm == NULL)
+ return krb5_enomem(context);
+
+ ret = krb5_cc_start_seq_get(context, id, &cursor);
+ if (ret) {
+ free(start_realm);
+ return ret;
+ }
+
+ while ((ret = krb5_cc_next_cred(context, id, &cursor, &cred)) == 0) {
+ /**
+ * If we find the start krbtgt in the cache, use that as the lifespan.
+ */
+ if (krb5_principal_is_root_krbtgt(context, cred.server) &&
+ strcmp(cred.server->realm, start_realm) == 0) {
+ if (now < cred.times.endtime)
+ endtime = cred.times.endtime;
+ krb5_free_cred_contents(context, &cred);
+ break;
+ }
+ /*
+ * Skip config entries
+ */
+ if (krb5_is_config_principal(context, cred.server)) {
+ krb5_free_cred_contents(context, &cred);
+ continue;
+ }
+ /**
+ * If there was no krbtgt, use the shortest lifetime of
+ * service tickets that have yet to expire. If all
+ * credentials are expired, krb5_cc_get_lifetime() will fail.
+ */
+ if ((endtime == 0 || cred.times.endtime < endtime) && now < cred.times.endtime)
+ endtime = cred.times.endtime;
+ krb5_free_cred_contents(context, &cred);
+ }
+ free(start_realm);
+
+ /* if we found an endtime use that */
+ if (endtime) {
+ *t = endtime - now;
+ ret = 0;
+ }
+
+ krb5_cc_end_seq_get(context, id, &cursor);
+
+ return ret;
+}
+
+/**
+ * Set the time offset betwen the client and the KDC
+ *
+ * If the backend doesn't support KDC offset, use the context global setting.
+ *
+ * @param context A Kerberos 5 context.
+ * @param id a credential cache
+ * @param offset the offset in seconds
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat offset)
+{
+ if (id->ops->version < KRB5_CC_OPS_VERSION_3
+ || id->ops->set_kdc_offset == NULL) {
+ context->kdc_sec_offset = offset;
+ context->kdc_usec_offset = 0;
+ return 0;
+ }
+ return (*id->ops->set_kdc_offset)(context, id, offset);
+}
+
+/**
+ * Get the time offset betwen the client and the KDC
+ *
+ * If the backend doesn't support KDC offset, use the context global setting.
+ *
+ * @param context A Kerberos 5 context.
+ * @param id a credential cache
+ * @param offset the offset in seconds
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat *offset)
+{
+ if (id->ops->version < KRB5_CC_OPS_VERSION_3
+ || id->ops->get_kdc_offset == NULL) {
+ *offset = context->kdc_sec_offset;
+ return 0;
+ }
+ return (*id->ops->get_kdc_offset)(context, id, offset);
+}
+
+#ifdef _WIN32
+#define REGPATH_MIT_KRB5 "SOFTWARE\\MIT\\Kerberos5"
+
+static char *
+_get_default_cc_name_from_registry(krb5_context context, HKEY hkBase)
+{
+ HKEY hk_k5 = 0;
+ LONG code;
+ char *ccname = NULL;
+
+ code = RegOpenKeyEx(hkBase,
+ REGPATH_MIT_KRB5,
+ 0, KEY_READ, &hk_k5);
+
+ if (code != ERROR_SUCCESS)
+ return NULL;
+
+ ccname = heim_parse_reg_value_as_string(context->hcontext, hk_k5, "ccname",
+ REG_NONE, 0);
+
+ RegCloseKey(hk_k5);
+
+ return ccname;
+}
+
+KRB5_LIB_FUNCTION char * KRB5_LIB_CALL
+_krb5_get_default_cc_name_from_registry(krb5_context context)
+{
+ char *ccname;
+
+ ccname = _get_default_cc_name_from_registry(context, HKEY_CURRENT_USER);
+ if (ccname == NULL)
+ ccname = _get_default_cc_name_from_registry(context,
+ HKEY_LOCAL_MACHINE);
+
+ return ccname;
+}
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+_krb5_set_default_cc_name_to_registry(krb5_context context, krb5_ccache id)
+{
+ HKEY hk_k5 = 0;
+ LONG code;
+ int ret = -1;
+ char * ccname = NULL;
+
+ code = RegOpenKeyEx(HKEY_CURRENT_USER,
+ REGPATH_MIT_KRB5,
+ 0, KEY_READ|KEY_WRITE, &hk_k5);
+
+ if (code != ERROR_SUCCESS)
+ return -1;
+
+ ret = asprintf(&ccname, "%s:%s", krb5_cc_get_type(context, id), krb5_cc_get_name(context, id));
+ if (ret < 0)
+ goto cleanup;
+
+ ret = heim_store_string_to_reg_value(context->hcontext, hk_k5, "ccname",
+ REG_SZ, ccname, -1, 0);
+
+ cleanup:
+
+ if (ccname)
+ free(ccname);
+
+ RegCloseKey(hk_k5);
+
+ return ret;
+}
+#endif
diff --git a/third_party/heimdal/lib/krb5/ccache_plugin.h b/third_party/heimdal/lib/krb5/ccache_plugin.h
new file mode 100644
index 0000000..e0fda4c
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/ccache_plugin.h
@@ -0,0 +1,46 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#ifndef HEIMDAL_KRB5_CCACHE_PLUGIN_H
+#define HEIMDAL_KRB5_CCACHE_PLUGIN_H 1
+
+#include <krb5.h>
+#include <common_plugin.h>
+
+#define KRB5_PLUGIN_CCACHE "ccache_ops"
+
+krb5_error_code KRB5_CALLCONV
+ccache_ops_plugin_load(krb5_context context,
+ krb5_get_instance_func_t *func,
+ size_t *n_ftables,
+ heim_plugin_common_ftable_p **ftables);
+
+#endif /* HEIMDAL_KRB5_CCACHE_PLUGIN_H */
diff --git a/third_party/heimdal/lib/krb5/changepw.c b/third_party/heimdal/lib/krb5/changepw.c
new file mode 100644
index 0000000..12f0b15
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/changepw.c
@@ -0,0 +1,860 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#undef __attribute__
+#define __attribute__(X)
+
+
+static void
+str2data (krb5_data *d,
+ const char *fmt,
+ ...) __attribute__ ((__format__ (__printf__, 2, 3)));
+
+static void
+str2data (krb5_data *d,
+ const char *fmt,
+ ...)
+{
+ va_list args;
+ char *str;
+
+ va_start(args, fmt);
+ d->length = vasprintf (&str, fmt, args);
+ va_end(args);
+ d->data = str;
+}
+
+/*
+ * Change password protocol defined by
+ * draft-ietf-cat-kerb-chg-password-02.txt
+ *
+ * Share the response part of the protocol with MS set password
+ * (RFC3244)
+ */
+
+static krb5_error_code
+chgpw_send_request (krb5_context context,
+ krb5_auth_context *auth_context,
+ krb5_creds *creds,
+ krb5_principal targprinc,
+ int is_stream,
+ rk_socket_t sock,
+ const char *passwd,
+ const char *host)
+{
+ krb5_error_code ret;
+ krb5_data ap_req_data;
+ krb5_data krb_priv_data;
+ krb5_data passwd_data;
+ size_t len;
+ u_char header[6];
+ struct iovec iov[3];
+ struct msghdr msghdr;
+
+ if (is_stream)
+ return KRB5_KPASSWD_MALFORMED;
+
+ if (targprinc &&
+ krb5_principal_compare(context, creds->client, targprinc) != TRUE)
+ return KRB5_KPASSWD_MALFORMED;
+
+ krb5_data_zero (&ap_req_data);
+
+ ret = krb5_mk_req_extended (context,
+ auth_context,
+ AP_OPTS_MUTUAL_REQUIRED | AP_OPTS_USE_SUBKEY,
+ NULL, /* in_data */
+ creds,
+ &ap_req_data);
+ if (ret)
+ return ret;
+
+ passwd_data.data = rk_UNCONST(passwd);
+ passwd_data.length = strlen(passwd);
+
+ krb5_data_zero (&krb_priv_data);
+
+ ret = krb5_mk_priv (context,
+ *auth_context,
+ &passwd_data,
+ &krb_priv_data,
+ NULL);
+ if (ret)
+ goto out2;
+
+ len = 6 + ap_req_data.length + krb_priv_data.length;
+ header[0] = (len >> 8) & 0xFF;
+ header[1] = (len >> 0) & 0xFF;
+ header[2] = 0;
+ header[3] = 1;
+ header[4] = (ap_req_data.length >> 8) & 0xFF;
+ header[5] = (ap_req_data.length >> 0) & 0xFF;
+
+ memset(&msghdr, 0, sizeof(msghdr));
+ msghdr.msg_name = NULL;
+ msghdr.msg_namelen = 0;
+ msghdr.msg_iov = iov;
+ msghdr.msg_iovlen = sizeof(iov)/sizeof(*iov);
+#if 0
+ msghdr.msg_control = NULL;
+ msghdr.msg_controllen = 0;
+#endif
+
+ iov[0].iov_base = (void*)header;
+ iov[0].iov_len = 6;
+ iov[1].iov_base = ap_req_data.data;
+ iov[1].iov_len = ap_req_data.length;
+ iov[2].iov_base = krb_priv_data.data;
+ iov[2].iov_len = krb_priv_data.length;
+
+ if (rk_IS_SOCKET_ERROR( sendmsg (sock, &msghdr, 0) )) {
+ ret = rk_SOCK_ERRNO;
+ krb5_set_error_message(context, ret, "sendmsg %s: %s",
+ host, strerror(ret));
+ }
+
+ krb5_data_free (&krb_priv_data);
+out2:
+ krb5_data_free (&ap_req_data);
+ return ret;
+}
+
+/*
+ * Set password protocol as defined by RFC3244 --
+ * Microsoft Windows 2000 Kerberos Change Password and Set Password Protocols
+ */
+
+static krb5_error_code
+setpw_send_request (krb5_context context,
+ krb5_auth_context *auth_context,
+ krb5_creds *creds,
+ krb5_principal targprinc,
+ int is_stream,
+ rk_socket_t sock,
+ const char *passwd,
+ const char *host)
+{
+ krb5_error_code ret;
+ krb5_data ap_req_data;
+ krb5_data krb_priv_data;
+ krb5_data pwd_data;
+ ChangePasswdDataMS chpw;
+ size_t len = 0;
+ u_char header[4 + 6];
+ u_char *p;
+ struct iovec iov[3];
+ struct msghdr msghdr;
+
+ krb5_data_zero (&ap_req_data);
+
+ ret = krb5_mk_req_extended (context,
+ auth_context,
+ AP_OPTS_MUTUAL_REQUIRED | AP_OPTS_USE_SUBKEY,
+ NULL, /* in_data */
+ creds,
+ &ap_req_data);
+ if (ret)
+ return ret;
+
+ chpw.newpasswd.length = strlen(passwd);
+ chpw.newpasswd.data = rk_UNCONST(passwd);
+ if (targprinc) {
+ chpw.targname = &targprinc->name;
+ chpw.targrealm = &targprinc->realm;
+ } else {
+ chpw.targname = NULL;
+ chpw.targrealm = NULL;
+ }
+
+ ASN1_MALLOC_ENCODE(ChangePasswdDataMS, pwd_data.data, pwd_data.length,
+ &chpw, &len, ret);
+ if (ret) {
+ krb5_data_free (&ap_req_data);
+ return ret;
+ }
+
+ if(pwd_data.length != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ ret = krb5_mk_priv (context,
+ *auth_context,
+ &pwd_data,
+ &krb_priv_data,
+ NULL);
+ if (ret)
+ goto out2;
+
+ len = 6 + ap_req_data.length + krb_priv_data.length;
+ p = header;
+ if (is_stream) {
+ _krb5_put_int(p, len, 4);
+ p += 4;
+ }
+ *p++ = (len >> 8) & 0xFF;
+ *p++ = (len >> 0) & 0xFF;
+ *p++ = 0xff;
+ *p++ = 0x80;
+ *p++ = (ap_req_data.length >> 8) & 0xFF;
+ *p = (ap_req_data.length >> 0) & 0xFF;
+
+ memset(&msghdr, 0, sizeof(msghdr));
+ msghdr.msg_name = NULL;
+ msghdr.msg_namelen = 0;
+ msghdr.msg_iov = iov;
+ msghdr.msg_iovlen = sizeof(iov)/sizeof(*iov);
+#if 0
+ msghdr.msg_control = NULL;
+ msghdr.msg_controllen = 0;
+#endif
+
+ iov[0].iov_base = (void*)header;
+ if (is_stream)
+ iov[0].iov_len = 10;
+ else
+ iov[0].iov_len = 6;
+ iov[1].iov_base = ap_req_data.data;
+ iov[1].iov_len = ap_req_data.length;
+ iov[2].iov_base = krb_priv_data.data;
+ iov[2].iov_len = krb_priv_data.length;
+
+ if (rk_IS_SOCKET_ERROR( sendmsg (sock, &msghdr, 0) )) {
+ ret = rk_SOCK_ERRNO;
+ krb5_set_error_message(context, ret, "sendmsg %s: %s",
+ host, strerror(ret));
+ }
+
+ krb5_data_free (&krb_priv_data);
+out2:
+ krb5_data_free (&ap_req_data);
+ krb5_data_free (&pwd_data);
+ return ret;
+}
+
+static krb5_error_code
+process_reply (krb5_context context,
+ krb5_auth_context auth_context,
+ int is_stream,
+ rk_socket_t sock,
+ int *result_code,
+ krb5_data *result_code_string,
+ krb5_data *result_string,
+ const char *host)
+{
+ krb5_error_code ret;
+ u_char reply[1024 * 3];
+ size_t len;
+ uint16_t pkt_len, pkt_ver;
+ krb5_data ap_rep_data;
+ int save_errno;
+
+ len = 0;
+ if (is_stream) {
+ while (len < sizeof(reply)) {
+ unsigned long size;
+
+ ret = recvfrom (sock, reply + len, sizeof(reply) - len,
+ 0, NULL, NULL);
+ if (rk_IS_SOCKET_ERROR(ret)) {
+ save_errno = rk_SOCK_ERRNO;
+ krb5_set_error_message(context, save_errno,
+ "recvfrom %s: %s",
+ host, strerror(save_errno));
+ return save_errno;
+ } else if (ret == 0) {
+ krb5_set_error_message(context, 1,"recvfrom timeout %s", host);
+ return 1;
+ }
+ len += ret;
+ if (len < 4)
+ continue;
+ _krb5_get_int(reply, &size, 4);
+ if (size + 4 < len)
+ continue;
+ if (sizeof(reply) - 4 < size) {
+ krb5_set_error_message(context, ERANGE, "size from server too large %s", host);
+ return ERANGE;
+ }
+ memmove(reply, reply + 4, size);
+ len = size;
+ break;
+ }
+ if (len == sizeof(reply)) {
+ krb5_set_error_message(context, ENOMEM,
+ N_("Message too large from %s", "host"),
+ host);
+ return ENOMEM;
+ }
+ } else {
+ ret = recvfrom (sock, reply, sizeof(reply), 0, NULL, NULL);
+ if (rk_IS_SOCKET_ERROR(ret)) {
+ save_errno = rk_SOCK_ERRNO;
+ krb5_set_error_message(context, save_errno,
+ "recvfrom %s: %s",
+ host, strerror(save_errno));
+ return save_errno;
+ }
+ len = ret;
+ }
+
+ if (len < 6) {
+ str2data (result_string, "server %s sent to too short message "
+ "(%llu bytes)", host, (unsigned long long)len);
+ *result_code = KRB5_KPASSWD_MALFORMED;
+ return 0;
+ }
+
+ pkt_len = (reply[0] << 8) | (reply[1]);
+ pkt_ver = (reply[2] << 8) | (reply[3]);
+
+ if ((pkt_len != len) || (reply[1] == 0x7e || reply[1] == 0x5e)) {
+ KRB_ERROR error;
+ size_t size;
+ u_char *p;
+
+ memset(&error, 0, sizeof(error));
+
+ ret = decode_KRB_ERROR(reply, len, &error, &size);
+ if (ret)
+ return ret;
+
+ if (error.e_data->length < 2) {
+ str2data(result_string, "server %s sent too short "
+ "e_data to print anything usable", host);
+ free_KRB_ERROR(&error);
+ *result_code = KRB5_KPASSWD_MALFORMED;
+ return 0;
+ }
+
+ p = error.e_data->data;
+ *result_code = (p[0] << 8) | p[1];
+ if (error.e_data->length == 2)
+ str2data(result_string, "server only sent error code");
+ else
+ krb5_data_copy (result_string,
+ p + 2,
+ error.e_data->length - 2);
+ free_KRB_ERROR(&error);
+ return 0;
+ }
+
+ if (pkt_len != len) {
+ str2data (result_string, "client: wrong len in reply");
+ *result_code = KRB5_KPASSWD_MALFORMED;
+ return 0;
+ }
+ if (pkt_ver != KRB5_KPASSWD_VERS_CHANGEPW) {
+ str2data (result_string,
+ "client: wrong version number (%d)", pkt_ver);
+ *result_code = KRB5_KPASSWD_MALFORMED;
+ return 0;
+ }
+
+ ap_rep_data.data = reply + 6;
+ ap_rep_data.length = (reply[4] << 8) | (reply[5]);
+
+ if (reply + len < (u_char *)ap_rep_data.data + ap_rep_data.length) {
+ str2data (result_string, "client: wrong AP len in reply");
+ *result_code = KRB5_KPASSWD_MALFORMED;
+ return 0;
+ }
+
+ if (ap_rep_data.length) {
+ krb5_ap_rep_enc_part *ap_rep;
+ krb5_data priv_data;
+ u_char *p;
+
+ priv_data.data = (u_char*)ap_rep_data.data + ap_rep_data.length;
+ priv_data.length = len - ap_rep_data.length - 6;
+
+ ret = krb5_rd_rep (context,
+ auth_context,
+ &ap_rep_data,
+ &ap_rep);
+ if (ret)
+ return ret;
+
+ krb5_free_ap_rep_enc_part (context, ap_rep);
+
+ ret = krb5_rd_priv (context,
+ auth_context,
+ &priv_data,
+ result_code_string,
+ NULL);
+ if (ret) {
+ krb5_data_free (result_code_string);
+ return ret;
+ }
+
+ if (result_code_string->length < 2) {
+ *result_code = KRB5_KPASSWD_MALFORMED;
+ str2data (result_string,
+ "client: bad length in result");
+ return 0;
+ }
+
+ p = result_code_string->data;
+
+ *result_code = (p[0] << 8) | p[1];
+ krb5_data_copy (result_string,
+ (unsigned char*)result_code_string->data + 2,
+ result_code_string->length - 2);
+ return 0;
+ } else {
+ KRB_ERROR error;
+ size_t size;
+ u_char *p;
+
+ ret = decode_KRB_ERROR(reply + 6, len - 6, &error, &size);
+ if (ret) {
+ return ret;
+ }
+ if (error.e_data->length < 2) {
+ krb5_warnx (context, "too short e_data to print anything usable");
+ return 1; /* XXX */
+ }
+
+ p = error.e_data->data;
+ *result_code = (p[0] << 8) | p[1];
+ krb5_data_copy (result_string,
+ p + 2,
+ error.e_data->length - 2);
+ return 0;
+ }
+}
+
+
+/*
+ * change the password using the credentials in `creds' (for the
+ * principal indicated in them) to `newpw', storing the result of
+ * the operation in `result_*' and an error code or 0.
+ */
+
+typedef krb5_error_code (*kpwd_send_request) (krb5_context,
+ krb5_auth_context *,
+ krb5_creds *,
+ krb5_principal,
+ int,
+ rk_socket_t,
+ const char *,
+ const char *);
+typedef krb5_error_code (*kpwd_process_reply) (krb5_context,
+ krb5_auth_context,
+ int,
+ rk_socket_t,
+ int *,
+ krb5_data *,
+ krb5_data *,
+ const char *);
+
+static struct kpwd_proc {
+ const char *name;
+ int flags;
+#define SUPPORT_TCP 1
+#define SUPPORT_UDP 2
+ kpwd_send_request send_req;
+ kpwd_process_reply process_rep;
+} procs[] = {
+ {
+ "MS set password",
+ SUPPORT_TCP|SUPPORT_UDP,
+ setpw_send_request,
+ process_reply
+ },
+ {
+ "change password",
+ SUPPORT_UDP,
+ chgpw_send_request,
+ process_reply
+ },
+ { NULL, 0, NULL, NULL }
+};
+
+/*
+ *
+ */
+
+static krb5_error_code
+change_password_loop (krb5_context context,
+ krb5_creds *creds,
+ krb5_principal targprinc,
+ const char *newpw,
+ int *result_code,
+ krb5_data *result_code_string,
+ krb5_data *result_string,
+ struct kpwd_proc *proc)
+{
+ krb5_error_code ret;
+ krb5_auth_context auth_context = NULL;
+ krb5_krbhst_handle handle = NULL;
+ krb5_krbhst_info *hi;
+ rk_socket_t sock;
+ unsigned int i;
+ int done = 0;
+ krb5_realm realm;
+
+ if (targprinc)
+ realm = targprinc->realm;
+ else
+ realm = creds->client->realm;
+
+ ret = krb5_auth_con_init (context, &auth_context);
+ if (ret)
+ return ret;
+
+ krb5_auth_con_setflags (context, auth_context,
+ KRB5_AUTH_CONTEXT_DO_SEQUENCE);
+
+ ret = krb5_krbhst_init (context, realm, KRB5_KRBHST_CHANGEPW, &handle);
+ if (ret)
+ goto out;
+
+ while (!done && (ret = krb5_krbhst_next(context, handle, &hi)) == 0) {
+ struct addrinfo *ai, *a;
+ int is_stream;
+
+ switch (hi->proto) {
+ case KRB5_KRBHST_UDP:
+ if ((proc->flags & SUPPORT_UDP) == 0)
+ continue;
+ is_stream = 0;
+ break;
+ case KRB5_KRBHST_TCP:
+ if ((proc->flags & SUPPORT_TCP) == 0)
+ continue;
+ is_stream = 1;
+ break;
+ default:
+ continue;
+ }
+
+ ret = krb5_krbhst_get_addrinfo(context, hi, &ai);
+ if (ret)
+ continue;
+
+ for (a = ai; !done && a != NULL; a = a->ai_next) {
+ int replied = 0;
+
+ sock = socket (a->ai_family, a->ai_socktype | SOCK_CLOEXEC, a->ai_protocol);
+ if (rk_IS_BAD_SOCKET(sock))
+ continue;
+ rk_cloexec(sock);
+
+ ret = connect(sock, a->ai_addr, a->ai_addrlen);
+ if (rk_IS_SOCKET_ERROR(ret)) {
+ rk_closesocket (sock);
+ goto out;
+ }
+
+ ret = krb5_auth_con_genaddrs (context, auth_context, sock,
+ KRB5_AUTH_CONTEXT_GENERATE_LOCAL_ADDR);
+ if (ret) {
+ rk_closesocket (sock);
+ goto out;
+ }
+
+ for (i = 0; !done && i < 5; ++i) {
+ fd_set fdset;
+ struct timeval tv;
+
+ if (!replied) {
+ replied = 0;
+
+ ret = (*proc->send_req) (context,
+ &auth_context,
+ creds,
+ targprinc,
+ is_stream,
+ sock,
+ newpw,
+ hi->hostname);
+ if (ret) {
+ rk_closesocket(sock);
+ goto out;
+ }
+ }
+
+#ifndef NO_LIMIT_FD_SETSIZE
+ if (sock >= FD_SETSIZE) {
+ ret = ERANGE;
+ krb5_set_error_message(context, ret,
+ "fd %d too large", sock);
+ rk_closesocket (sock);
+ goto out;
+ }
+#endif
+
+ FD_ZERO(&fdset);
+ FD_SET(sock, &fdset);
+ tv.tv_usec = 0;
+ tv.tv_sec = 1 + (1 << i);
+
+ ret = select (sock + 1, &fdset, NULL, NULL, &tv);
+ if (rk_IS_SOCKET_ERROR(ret) && rk_SOCK_ERRNO != EINTR) {
+ rk_closesocket(sock);
+ goto out;
+ }
+ if (ret == 1) {
+ ret = (*proc->process_rep) (context,
+ auth_context,
+ is_stream,
+ sock,
+ result_code,
+ result_code_string,
+ result_string,
+ hi->hostname);
+ if (ret == 0)
+ done = 1;
+ else if (i > 0 && ret == KRB5KRB_AP_ERR_MUT_FAIL)
+ replied = 1;
+ } else {
+ ret = KRB5_KDC_UNREACH;
+ }
+ }
+ rk_closesocket (sock);
+ }
+ }
+
+ out:
+ krb5_krbhst_free (context, handle);
+ krb5_auth_con_free (context, auth_context);
+
+ if (ret == KRB5_KDC_UNREACH) {
+ krb5_set_error_message(context,
+ ret,
+ N_("Unable to reach any changepw server "
+ " in realm %s", "realm"), realm);
+ *result_code = KRB5_KPASSWD_HARDERROR;
+ }
+ return ret;
+}
+
+#ifndef HEIMDAL_SMALLER
+
+static struct kpwd_proc *
+find_chpw_proto(const char *name)
+{
+ struct kpwd_proc *p;
+ for (p = procs; p->name != NULL; p++) {
+ if (strcmp(p->name, name) == 0)
+ return p;
+ }
+ return NULL;
+}
+
+/**
+ * Deprecated: krb5_change_password() is deprecated, use krb5_set_password().
+ *
+ * @param context a Keberos context
+ * @param creds
+ * @param newpw
+ * @param result_code
+ * @param result_code_string
+ * @param result_string
+ *
+ * @return On sucess password is changed.
+
+ * @ingroup @krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_change_password (krb5_context context,
+ krb5_creds *creds,
+ const char *newpw,
+ int *result_code,
+ krb5_data *result_code_string,
+ krb5_data *result_string)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ struct kpwd_proc *p = find_chpw_proto("change password");
+
+ *result_code = KRB5_KPASSWD_MALFORMED;
+ result_code_string->data = result_string->data = NULL;
+ result_code_string->length = result_string->length = 0;
+
+ if (p == NULL)
+ return KRB5_KPASSWD_MALFORMED;
+
+ return change_password_loop(context, creds, NULL, newpw,
+ result_code, result_code_string,
+ result_string, p);
+}
+#endif /* HEIMDAL_SMALLER */
+
+/**
+ * Change password using creds.
+ *
+ * @param context a Keberos context
+ * @param creds The initial kadmin/passwd for the principal or an admin principal
+ * @param newpw The new password to set
+ * @param targprinc if unset, the client principal from creds is used
+ * @param result_code Result code, KRB5_KPASSWD_SUCCESS is when password is changed.
+ * @param result_code_string binary message from the server, contains
+ * at least the result_code.
+ * @param result_string A message from the kpasswd service or the
+ * library in human printable form. The string is NUL terminated.
+ *
+ * @return On sucess and *result_code is KRB5_KPASSWD_SUCCESS, the password is changed.
+
+ * @ingroup @krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_password(krb5_context context,
+ krb5_creds *creds,
+ const char *newpw,
+ krb5_principal targprinc,
+ int *result_code,
+ krb5_data *result_code_string,
+ krb5_data *result_string)
+{
+ krb5_principal principal = NULL;
+ krb5_error_code ret = 0;
+ int i;
+
+ *result_code = KRB5_KPASSWD_MALFORMED;
+ krb5_data_zero(result_code_string);
+ krb5_data_zero(result_string);
+
+ if (targprinc == NULL) {
+ ret = krb5_copy_principal(context, creds->client, &principal);
+ if (ret)
+ return ret;
+ } else
+ principal = targprinc;
+
+ for (i = 0; procs[i].name != NULL; i++) {
+ *result_code = 0;
+ ret = change_password_loop(context, creds, principal, newpw,
+ result_code, result_code_string,
+ result_string,
+ &procs[i]);
+ if (ret == 0 && *result_code == 0)
+ break;
+ }
+
+ if (targprinc == NULL)
+ krb5_free_principal(context, principal);
+ return ret;
+}
+
+/*
+ *
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_password_using_ccache(krb5_context context,
+ krb5_ccache ccache,
+ const char *newpw,
+ krb5_principal targprinc,
+ int *result_code,
+ krb5_data *result_code_string,
+ krb5_data *result_string)
+{
+ krb5_creds creds, *credsp;
+ krb5_error_code ret;
+ krb5_principal principal = NULL;
+
+ *result_code = KRB5_KPASSWD_MALFORMED;
+ result_code_string->data = result_string->data = NULL;
+ result_code_string->length = result_string->length = 0;
+
+ memset(&creds, 0, sizeof(creds));
+
+ if (targprinc == NULL) {
+ ret = krb5_cc_get_principal(context, ccache, &principal);
+ if (ret)
+ return ret;
+ } else
+ principal = targprinc;
+
+ ret = krb5_make_principal(context, &creds.server,
+ krb5_principal_get_realm(context, principal),
+ "kadmin", "changepw", NULL);
+ if (ret)
+ goto out;
+
+ ret = krb5_cc_get_principal(context, ccache, &creds.client);
+ if (ret) {
+ krb5_free_principal(context, creds.server);
+ goto out;
+ }
+
+ ret = krb5_get_credentials(context, 0, ccache, &creds, &credsp);
+ krb5_free_principal(context, creds.server);
+ krb5_free_principal(context, creds.client);
+ if (ret)
+ goto out;
+
+ ret = krb5_set_password(context,
+ credsp,
+ newpw,
+ principal,
+ result_code,
+ result_code_string,
+ result_string);
+
+ krb5_free_creds(context, credsp);
+
+ return ret;
+ out:
+ if (targprinc == NULL)
+ krb5_free_principal(context, principal);
+ return ret;
+}
+
+/*
+ *
+ */
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_passwd_result_to_string (krb5_context context,
+ int result)
+{
+ static const char *strings[] = {
+ "Success",
+ "Malformed",
+ "Hard error",
+ "Auth error",
+ "Soft error" ,
+ "Access denied",
+ "Bad version",
+ "Initial flag needed"
+ };
+
+ if (result < 0 || result > KRB5_KPASSWD_INITIAL_FLAG_NEEDED)
+ return "unknown result code";
+ else
+ return strings[result];
+}
diff --git a/third_party/heimdal/lib/krb5/codec.c b/third_party/heimdal/lib/krb5/codec.c
new file mode 100644
index 0000000..5e754c6
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/codec.c
@@ -0,0 +1,214 @@
+/*
+ * Copyright (c) 1998 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#ifndef HEIMDAL_SMALLER
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decode_EncTicketPart (krb5_context context,
+ const void *data,
+ size_t length,
+ EncTicketPart *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return decode_EncTicketPart(data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_encode_EncTicketPart (krb5_context context,
+ void *data,
+ size_t length,
+ EncTicketPart *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return encode_EncTicketPart(data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decode_EncASRepPart (krb5_context context,
+ const void *data,
+ size_t length,
+ EncASRepPart *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return decode_EncASRepPart(data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_encode_EncASRepPart (krb5_context context,
+ void *data,
+ size_t length,
+ EncASRepPart *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return encode_EncASRepPart(data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decode_EncTGSRepPart (krb5_context context,
+ const void *data,
+ size_t length,
+ EncTGSRepPart *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return decode_EncTGSRepPart(data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_encode_EncTGSRepPart (krb5_context context,
+ void *data,
+ size_t length,
+ EncTGSRepPart *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return encode_EncTGSRepPart(data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decode_EncAPRepPart (krb5_context context,
+ const void *data,
+ size_t length,
+ EncAPRepPart *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return decode_EncAPRepPart(data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_encode_EncAPRepPart (krb5_context context,
+ void *data,
+ size_t length,
+ EncAPRepPart *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return encode_EncAPRepPart(data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decode_Authenticator (krb5_context context,
+ const void *data,
+ size_t length,
+ Authenticator *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return decode_Authenticator(data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_encode_Authenticator (krb5_context context,
+ void *data,
+ size_t length,
+ Authenticator *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return encode_Authenticator(data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decode_EncKrbCredPart (krb5_context context,
+ const void *data,
+ size_t length,
+ EncKrbCredPart *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return decode_EncKrbCredPart(data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_encode_EncKrbCredPart (krb5_context context,
+ void *data,
+ size_t length,
+ EncKrbCredPart *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return encode_EncKrbCredPart (data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decode_ETYPE_INFO (krb5_context context,
+ const void *data,
+ size_t length,
+ ETYPE_INFO *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return decode_ETYPE_INFO(data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_encode_ETYPE_INFO (krb5_context context,
+ void *data,
+ size_t length,
+ ETYPE_INFO *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return encode_ETYPE_INFO (data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decode_ETYPE_INFO2 (krb5_context context,
+ const void *data,
+ size_t length,
+ ETYPE_INFO2 *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return decode_ETYPE_INFO2(data, length, t, len);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_encode_ETYPE_INFO2 (krb5_context context,
+ void *data,
+ size_t length,
+ ETYPE_INFO2 *t,
+ size_t *len)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return encode_ETYPE_INFO2 (data, length, t, len);
+}
+
+#endif /* HEIMDAL_SMALLER */
diff --git a/third_party/heimdal/lib/krb5/config_file.c b/third_party/heimdal/lib/krb5/config_file.c
new file mode 100644
index 0000000..22eff10
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/config_file.c
@@ -0,0 +1,758 @@
+/*
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#if defined(HAVE_FRAMEWORK_COREFOUNDATION)
+#include <CoreFoundation/CoreFoundation.h>
+#endif
+
+/**
+ * Parse configuration files in the given directory and add the result
+ * into res. Only files whose names consist only of alphanumeric
+ * characters, hyphen, and underscore, will be parsed, though files
+ * ending in ".conf" will also be parsed.
+ *
+ * This interface can be used to parse several configuration directories
+ * into one resulting krb5_config_section by calling it repeatably.
+ *
+ * @param context a Kerberos 5 context.
+ * @param dname a directory name to a Kerberos configuration file
+ * @param res the returned result, must be free with krb5_free_config_files().
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_config_parse_dir_multi(krb5_context context,
+ const char *dname,
+ krb5_config_section **res)
+{
+ krb5_error_code ret;
+ heim_config_section *section = NULL;
+
+ if (res == NULL)
+ return EINVAL;
+
+ *res = NULL;
+
+ ret = heim_config_parse_dir_multi(context->hcontext, dname, &section);
+ if (ret == HEIM_ERR_CONFIG_BADFORMAT)
+ return KRB5_CONFIG_BADFORMAT;
+ if (ret)
+ return ret;
+ *res = (krb5_config_section *)section;
+ return 0;
+}
+
+/**
+ * Parse a configuration file and add the result into res. This
+ * interface can be used to parse several configuration files into one
+ * resulting krb5_config_section by calling it repeatably.
+ *
+ * @param context a Kerberos 5 context.
+ * @param fname a file name to a Kerberos configuration file
+ * @param res the returned result, must be free with krb5_free_config_files().
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_config_parse_file_multi(krb5_context context,
+ const char *fname,
+ krb5_config_section **res)
+{
+ krb5_error_code ret;
+ heim_config_section *section = NULL;
+
+ if (res == NULL)
+ return EINVAL;
+
+ *res = NULL;
+
+ ret = heim_config_parse_file_multi(context->hcontext, fname, &section);
+ if (ret == HEIM_ERR_CONFIG_BADFORMAT)
+ return KRB5_CONFIG_BADFORMAT;
+ if (ret)
+ return ret;
+ *res = (krb5_config_section *)section;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_config_parse_file(krb5_context context,
+ const char *fname,
+ krb5_config_section **res)
+{
+ return krb5_config_parse_file_multi(context, fname, res);
+}
+
+/**
+ * Free configuration file section, the result of
+ * krb5_config_parse_file() and krb5_config_parse_file_multi().
+ *
+ * @param context A Kerberos 5 context
+ * @param s the configuration section to free
+ *
+ * @return returns 0 on successes, otherwise an error code, see
+ * krb5_get_error_message()
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_config_file_free(krb5_context context, krb5_config_section *s)
+{
+ return heim_config_file_free(context->hcontext, (heim_config_section *)s);
+}
+
+#ifndef HEIMDAL_SMALLER
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_config_copy(krb5_context context,
+ krb5_config_section *c,
+ krb5_config_section **res)
+{
+ krb5_error_code ret;
+ heim_config_section *section = NULL;
+
+ if (res == NULL)
+ return EINVAL;
+
+ *res = NULL;
+ ret = heim_config_copy(context->hcontext, (heim_config_section *)c, &section);
+ if (ret)
+ return ret;
+ *res = (krb5_config_section *)section;
+ return 0;
+}
+
+#endif /* HEIMDAL_SMALLER */
+
+KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL
+_krb5_config_get_next(krb5_context context,
+ const krb5_config_section *c,
+ const krb5_config_binding **pointer,
+ int type,
+ ...)
+{
+ const char *ret;
+ va_list args;
+
+ va_start(args, type);
+ ret = heim_config_vget_next(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ (const heim_config_binding **)pointer, type, args);
+ va_end(args);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL
+_krb5_config_vget_next(krb5_context context,
+ const krb5_config_section *c,
+ const krb5_config_binding **pointer,
+ int type,
+ va_list args)
+{
+ return heim_config_vget_next(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ (const heim_config_binding **)pointer, type, args);
+}
+
+KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL
+_krb5_config_get(krb5_context context,
+ const krb5_config_section *c,
+ int type,
+ ...)
+{
+ const void *ret;
+ va_list args;
+
+ va_start(args, type);
+ ret = heim_config_vget(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ type, args);
+ va_end(args);
+ return ret;
+}
+
+
+KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL
+_krb5_config_vget(krb5_context context,
+ const krb5_config_section *c,
+ int type,
+ va_list args)
+{
+ return heim_config_vget(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ type, args);
+}
+
+/**
+ * Get a list of configuration binding list for more processing
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return NULL if configuration list is not found, a list otherwise
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION const krb5_config_binding * KRB5_LIB_CALL
+krb5_config_get_list(krb5_context context,
+ const krb5_config_section *c,
+ ...)
+{
+ const heim_config_binding *ret;
+ va_list args;
+
+ va_start(args, c);
+ ret = heim_config_vget_list(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ args);
+ va_end(args);
+ return (const krb5_config_binding *)ret;
+}
+
+/**
+ * Get a list of configuration binding list for more processing
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param args a va_list of arguments
+ *
+ * @return NULL if configuration list is not found, a list otherwise
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION const krb5_config_binding * KRB5_LIB_CALL
+krb5_config_vget_list(krb5_context context,
+ const krb5_config_section *c,
+ va_list args)
+{
+ const heim_config_binding *ret;
+
+ ret = heim_config_vget_list(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ args);
+ return (const krb5_config_binding *)ret;
+}
+
+/**
+ * Returns a "const char *" to a string in the configuration database.
+ * The string may not be valid after a reload of the configuration
+ * database so a caller should make a local copy if it needs to keep
+ * the string.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return NULL if configuration string not found, a string otherwise
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_config_get_string(krb5_context context,
+ const krb5_config_section *c,
+ ...)
+{
+ const char *ret;
+ va_list args;
+
+ va_start(args, c);
+ ret = heim_config_vget_string(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ args);
+ va_end(args);
+ return ret;
+}
+
+/**
+ * Like krb5_config_get_string(), but uses a va_list instead of ...
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param args a va_list of arguments
+ *
+ * @return NULL if configuration string not found, a string otherwise
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_config_vget_string(krb5_context context,
+ const krb5_config_section *c,
+ va_list args)
+{
+ return heim_config_vget_string(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ args);
+}
+
+/**
+ * Like krb5_config_vget_string(), but instead of returning NULL,
+ * instead return a default value.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param def_value the default value to return if no configuration
+ * found in the database.
+ * @param args a va_list of arguments
+ *
+ * @return a configuration string
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_config_vget_string_default(krb5_context context,
+ const krb5_config_section *c,
+ const char *def_value,
+ va_list args)
+{
+ return heim_config_vget_string_default(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ def_value, args);
+}
+
+/**
+ * Like krb5_config_get_string(), but instead of returning NULL,
+ * instead return a default value.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param def_value the default value to return if no configuration
+ * found in the database.
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return a configuration string
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_config_get_string_default(krb5_context context,
+ const krb5_config_section *c,
+ const char *def_value,
+ ...)
+{
+ const char *ret;
+ va_list args;
+
+ va_start(args, def_value);
+ ret = heim_config_vget_string_default(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ def_value, args);
+ va_end(args);
+ return ret;
+}
+
+/**
+ * Get a list of configuration strings, free the result with
+ * krb5_config_free_strings().
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param args a va_list of arguments
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION char ** KRB5_LIB_CALL
+krb5_config_vget_strings(krb5_context context,
+ const krb5_config_section *c,
+ va_list args)
+{
+ return heim_config_vget_strings(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ args);
+}
+
+/**
+ * Get a list of configuration strings, free the result with
+ * krb5_config_free_strings().
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION char** KRB5_LIB_CALL
+krb5_config_get_strings(krb5_context context,
+ const krb5_config_section *c,
+ ...)
+{
+ va_list ap;
+ char **ret;
+ va_start(ap, c);
+ ret = heim_config_vget_strings(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ ap);
+ va_end(ap);
+ return ret;
+}
+
+/**
+ * Free the resulting strings from krb5_config-get_strings() and
+ * krb5_config_vget_strings().
+ *
+ * @param strings strings to free
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_config_free_strings(char **strings)
+{
+ heim_config_free_strings(strings);
+}
+
+/**
+ * Like krb5_config_get_bool_default() but with a va_list list of
+ * configuration selection.
+ *
+ * Configuration value to a boolean value, where yes/true and any
+ * non-zero number means TRUE and other value is FALSE.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param def_value the default value to return if no configuration
+ * found in the database.
+ * @param args a va_list of arguments
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_config_vget_bool_default(krb5_context context,
+ const krb5_config_section *c,
+ krb5_boolean def_value,
+ va_list args)
+{
+ return heim_config_vget_bool_default(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ def_value, args);
+}
+
+/**
+ * krb5_config_get_bool() will convert the configuration
+ * option value to a boolean value, where yes/true and any non-zero
+ * number means TRUE and other value is FALSE.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param args a va_list of arguments
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_config_vget_bool(krb5_context context,
+ const krb5_config_section *c,
+ va_list args)
+{
+ return heim_config_vget_bool_default(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ FALSE, args);
+}
+
+/**
+ * krb5_config_get_bool_default() will convert the configuration
+ * option value to a boolean value, where yes/true and any non-zero
+ * number means TRUE and other value is FALSE.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param def_value the default value to return if no configuration
+ * found in the database.
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_config_get_bool_default(krb5_context context,
+ const krb5_config_section *c,
+ krb5_boolean def_value,
+ ...)
+{
+ va_list ap;
+ krb5_boolean ret;
+ va_start(ap, def_value);
+ ret = heim_config_vget_bool_default(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ def_value, ap);
+ va_end(ap);
+ return ret;
+}
+
+/**
+ * Like krb5_config_get_bool() but with a va_list list of
+ * configuration selection.
+ *
+ * Configuration value to a boolean value, where yes/true and any
+ * non-zero number means TRUE and other value is FALSE.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_config_get_bool (krb5_context context,
+ const krb5_config_section *c,
+ ...)
+{
+ va_list ap;
+ krb5_boolean ret;
+ va_start(ap, c);
+ ret = krb5_config_vget_bool (context, c, ap);
+ va_end(ap);
+ return ret;
+}
+
+/**
+ * Get the time from the configuration file using a relative time.
+ *
+ * Like krb5_config_get_time_default() but with a va_list list of
+ * configuration selection.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param def_value the default value to return if no configuration
+ * found in the database.
+ * @param args a va_list of arguments
+ *
+ * @return parsed the time (or def_value on parse error)
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_config_vget_time_default(krb5_context context,
+ const krb5_config_section *c,
+ int def_value,
+ va_list args)
+{
+ return heim_config_vget_time_default(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ def_value, args);
+}
+
+/**
+ * Get the time from the configuration file using a relative time, for example: 1h30s
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param args a va_list of arguments
+ *
+ * @return parsed the time or -1 on error
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_config_vget_time(krb5_context context,
+ const krb5_config_section *c,
+ va_list args)
+{
+ return heim_config_vget_time_default(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ -1, args);
+}
+
+/**
+ * Get the time from the configuration file using a relative time, for example: 1h30s
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param def_value the default value to return if no configuration
+ * found in the database.
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return parsed the time (or def_value on parse error)
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_config_get_time_default(krb5_context context,
+ const krb5_config_section *c,
+ int def_value,
+ ...)
+{
+ va_list ap;
+ int ret;
+ va_start(ap, def_value);
+ ret = heim_config_vget_time_default(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ def_value, ap);
+ va_end(ap);
+ return ret;
+}
+
+/**
+ * Get the time from the configuration file using a relative time, for example: 1h30s
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from context
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return parsed the time or -1 on error
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_config_get_time(krb5_context context,
+ const krb5_config_section *c,
+ ...)
+{
+ va_list ap;
+ int ret;
+ va_start(ap, c);
+ ret = heim_config_vget_time(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ ap);
+ va_end(ap);
+ return ret;
+}
+
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_config_vget_int_default(krb5_context context,
+ const krb5_config_section *c,
+ int def_value,
+ va_list args)
+{
+ return heim_config_vget_int_default(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ def_value, args);
+}
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_config_vget_int(krb5_context context,
+ const krb5_config_section *c,
+ va_list args)
+{
+ return heim_config_vget_int_default(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ -1, args);
+}
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_config_get_int_default(krb5_context context,
+ const krb5_config_section *c,
+ int def_value,
+ ...)
+{
+ va_list ap;
+ int ret;
+ va_start(ap, def_value);
+ ret = heim_config_vget_int_default(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ def_value, ap);
+ va_end(ap);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_config_get_int(krb5_context context,
+ const krb5_config_section *c,
+ ...)
+{
+ va_list ap;
+ int ret;
+ va_start(ap, c);
+ ret = heim_config_vget_int(context->hcontext,
+ (const heim_config_section *)(c ? c : context->cf),
+ ap);
+ va_end(ap);
+ return ret;
+}
+
+
+#ifndef HEIMDAL_SMALLER
+/**
+ * Deprecated: configuration files are not strings
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_config_parse_string_multi(krb5_context context,
+ const char *string,
+ krb5_config_section **res)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ krb5_error_code ret;
+ heim_config_section *section = NULL;
+
+ if (res == NULL)
+ return EINVAL;
+
+ *res = NULL;
+ ret = heim_config_parse_string_multi(context->hcontext, string, &section);
+ if (ret == HEIM_ERR_CONFIG_BADFORMAT)
+ return KRB5_CONFIG_BADFORMAT;
+ if (ret)
+ return ret;
+ *res = (krb5_config_section *)section;
+ return 0;
+}
+#endif
diff --git a/third_party/heimdal/lib/krb5/constants.c b/third_party/heimdal/lib/krb5/constants.c
new file mode 100644
index 0000000..42b460f
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/constants.c
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 1997-2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_VARIABLE const char *krb5_config_file =
+#ifdef KRB5_DEFAULT_CONFIG_FILE
+KRB5_DEFAULT_CONFIG_FILE
+#else
+#ifdef __APPLE__
+"~/Library/Preferences/com.apple.Kerberos.plist" PATH_SEP
+"/Library/Preferences/com.apple.Kerberos.plist" PATH_SEP
+"~/Library/Preferences/edu.mit.Kerberos" PATH_SEP
+"/Library/Preferences/edu.mit.Kerberos" PATH_SEP
+#endif /* __APPLE__ */
+"~/.krb5/config" PATH_SEP
+SYSCONFDIR "/krb5.conf" PATH_SEP
+#ifdef _WIN32
+"%{COMMON_APPDATA}/Kerberos/krb5.conf" PATH_SEP
+"%{WINDOWS}/krb5.ini"
+#else /* _WIN32 */
+"/etc/krb5.conf"
+#endif /* _WIN32 */
+#endif /* KRB5_DEFAULT_CONFIG_FILE */
+;
+
+KRB5_LIB_VARIABLE const char *krb5_defkeyname = KEYTAB_DEFAULT;
+
+KRB5_LIB_VARIABLE const char *krb5_cc_type_api = "API";
+KRB5_LIB_VARIABLE const char *krb5_cc_type_file = "FILE";
+KRB5_LIB_VARIABLE const char *krb5_cc_type_memory = "MEMORY";
+KRB5_LIB_VARIABLE const char *krb5_cc_type_kcm = "KCM";
+KRB5_LIB_VARIABLE const char *krb5_cc_type_scc = "SCC";
+KRB5_LIB_VARIABLE const char *krb5_cc_type_dcc = "DIR";
+KRB5_LIB_VARIABLE const char *krb5_cc_type_keyring = "KEYRING";
diff --git a/third_party/heimdal/lib/krb5/context.c b/third_party/heimdal/lib/krb5/context.c
new file mode 100644
index 0000000..4040a98
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/context.c
@@ -0,0 +1,1473 @@
+/*
+ * Copyright (c) 1997 - 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#undef KRB5_DEPRECATED_FUNCTION
+#define KRB5_DEPRECATED_FUNCTION(x)
+
+#include "krb5_locl.h"
+#include <assert.h>
+#include <com_err.h>
+
+static void _krb5_init_ets(krb5_context);
+
+#define INIT_FIELD(C, T, E, D, F) \
+ (C)->E = krb5_config_get_ ## T ## _default ((C), NULL, (D), \
+ "libdefaults", F, NULL)
+
+#define INIT_FLAG(C, O, V, D, F) \
+ do { \
+ if (krb5_config_get_bool_default((C), NULL, (D),"libdefaults", F, NULL)) { \
+ (C)->O |= V; \
+ } \
+ } while(0)
+
+static krb5_error_code
+copy_enctypes(krb5_context context,
+ const krb5_enctype *in,
+ krb5_enctype **out);
+
+/*
+ * Set the list of etypes `ret_etypes' from the configuration variable
+ * `name'
+ */
+
+static krb5_error_code
+set_etypes (krb5_context context,
+ const char *name,
+ krb5_enctype **ret_enctypes)
+{
+ char **etypes_str;
+ krb5_enctype *etypes = NULL;
+
+ etypes_str = krb5_config_get_strings(context, NULL, "libdefaults",
+ name, NULL);
+ if(etypes_str){
+ int i, j, k;
+ for(i = 0; etypes_str[i]; i++);
+ etypes = malloc((i+1) * sizeof(*etypes));
+ if (etypes == NULL) {
+ krb5_config_free_strings (etypes_str);
+ return krb5_enomem(context);
+ }
+ for(j = 0, k = 0; j < i; j++) {
+ krb5_enctype e;
+ if(krb5_string_to_enctype(context, etypes_str[j], &e) != 0)
+ continue;
+ if (krb5_enctype_valid(context, e) != 0)
+ continue;
+ etypes[k++] = e;
+ }
+ etypes[k] = ETYPE_NULL;
+ krb5_config_free_strings(etypes_str);
+ }
+ *ret_enctypes = etypes;
+ return 0;
+}
+
+/*
+ * read variables from the configuration file and set in `context'
+ */
+
+static krb5_error_code
+init_context_from_config_file(krb5_context context)
+{
+ krb5_error_code ret;
+ const char * tmp;
+ char **s;
+ krb5_enctype *tmptypes = NULL;
+
+ INIT_FIELD(context, time, max_skew, 5 * 60, "clockskew");
+ INIT_FIELD(context, time, kdc_timeout, 30, "kdc_timeout");
+ INIT_FIELD(context, time, host_timeout, 3, "host_timeout");
+ INIT_FIELD(context, int, max_retries, 3, "max_retries");
+
+ INIT_FIELD(context, string, http_proxy, NULL, "http_proxy");
+
+ ret = krb5_config_get_bool_default(context, NULL, FALSE,
+ "libdefaults",
+ "allow_weak_crypto", NULL);
+ if (ret) {
+ krb5_enctype_enable(context, ETYPE_DES_CBC_CRC);
+ krb5_enctype_enable(context, ETYPE_DES_CBC_MD4);
+ krb5_enctype_enable(context, ETYPE_DES_CBC_MD5);
+ krb5_enctype_enable(context, ETYPE_DES_CBC_NONE);
+ krb5_enctype_enable(context, ETYPE_DES_CFB64_NONE);
+ krb5_enctype_enable(context, ETYPE_DES_PCBC_NONE);
+ }
+
+ ret = set_etypes (context, "default_etypes", &tmptypes);
+ if(ret)
+ return ret;
+ free(context->etypes);
+ context->etypes = tmptypes;
+
+ /* The etypes member may change during the lifetime
+ * of the context. To be able to reset it to
+ * config value, we keep another copy.
+ */
+ free(context->cfg_etypes);
+ context->cfg_etypes = NULL;
+ if (tmptypes) {
+ ret = copy_enctypes(context, tmptypes, &context->cfg_etypes);
+ if (ret)
+ return ret;
+ }
+
+ ret = set_etypes (context, "default_etypes_des", &tmptypes);
+ if(ret)
+ return ret;
+ free(context->etypes_des);
+ context->etypes_des = tmptypes;
+
+ ret = set_etypes (context, "default_as_etypes", &tmptypes);
+ if(ret)
+ return ret;
+ free(context->as_etypes);
+ context->as_etypes = tmptypes;
+
+ ret = set_etypes (context, "default_tgs_etypes", &tmptypes);
+ if(ret)
+ return ret;
+ free(context->tgs_etypes);
+ context->tgs_etypes = tmptypes;
+
+ ret = set_etypes (context, "permitted_enctypes", &tmptypes);
+ if(ret)
+ return ret;
+ free(context->permitted_enctypes);
+ context->permitted_enctypes = tmptypes;
+
+ INIT_FIELD(context, string, default_keytab,
+ KEYTAB_DEFAULT, "default_keytab_name");
+
+ INIT_FIELD(context, string, default_keytab_modify,
+ NULL, "default_keytab_modify_name");
+
+ INIT_FIELD(context, string, time_fmt,
+ "%Y-%m-%dT%H:%M:%S", "time_format");
+
+ INIT_FIELD(context, string, date_fmt,
+ "%Y-%m-%d", "date_format");
+
+ INIT_FIELD(context, bool, log_utc,
+ FALSE, "log_utc");
+
+ context->no_ticket_store =
+ getenv("KRB5_NO_TICKET_STORE") != NULL;
+
+ /* init dns-proxy slime */
+ tmp = krb5_config_get_string(context, NULL, "libdefaults",
+ "dns_proxy", NULL);
+ if(tmp)
+ roken_gethostby_setup(context->http_proxy, tmp);
+ krb5_free_host_realm (context, context->default_realms);
+ context->default_realms = NULL;
+
+ {
+ krb5_addresses addresses;
+ char **adr, **a;
+
+ krb5_set_extra_addresses(context, NULL);
+ adr = krb5_config_get_strings(context, NULL,
+ "libdefaults",
+ "extra_addresses",
+ NULL);
+ memset(&addresses, 0, sizeof(addresses));
+ for(a = adr; a && *a; a++) {
+ ret = krb5_parse_address(context, *a, &addresses);
+ if (ret == 0) {
+ krb5_add_extra_addresses(context, &addresses);
+ krb5_free_addresses(context, &addresses);
+ }
+ }
+ krb5_config_free_strings(adr);
+
+ krb5_set_ignore_addresses(context, NULL);
+ adr = krb5_config_get_strings(context, NULL,
+ "libdefaults",
+ "ignore_addresses",
+ NULL);
+ memset(&addresses, 0, sizeof(addresses));
+ for(a = adr; a && *a; a++) {
+ ret = krb5_parse_address(context, *a, &addresses);
+ if (ret == 0) {
+ krb5_add_ignore_addresses(context, &addresses);
+ krb5_free_addresses(context, &addresses);
+ }
+ }
+ krb5_config_free_strings(adr);
+ }
+
+ INIT_FIELD(context, bool, scan_interfaces, TRUE, "scan_interfaces");
+ INIT_FIELD(context, int, fcache_vno, 0, "fcache_version");
+ /* prefer dns_lookup_kdc over srv_lookup. */
+ INIT_FIELD(context, bool, srv_lookup, TRUE, "srv_lookup");
+ INIT_FIELD(context, bool, srv_lookup, context->srv_lookup, "dns_lookup_kdc");
+ INIT_FIELD(context, int, large_msg_size, 1400, "large_message_size");
+ INIT_FIELD(context, int, max_msg_size, 1000 * 1024, "maximum_message_size");
+ INIT_FLAG(context, flags, KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME, TRUE, "dns_canonicalize_hostname");
+ INIT_FLAG(context, flags, KRB5_CTX_F_CHECK_PAC, TRUE, "check_pac");
+ INIT_FLAG(context, flags, KRB5_CTX_F_ENFORCE_OK_AS_DELEGATE, FALSE, "enforce_ok_as_delegate");
+ INIT_FLAG(context, flags, KRB5_CTX_F_REPORT_CANONICAL_CLIENT_NAME, FALSE, "report_canonical_client_name");
+
+ /* report_canonical_client_name implies check_pac */
+ if (context->flags & KRB5_CTX_F_REPORT_CANONICAL_CLIENT_NAME)
+ context->flags |= KRB5_CTX_F_CHECK_PAC;
+
+ free(context->default_cc_name);
+ context->default_cc_name = NULL;
+ context->default_cc_name_set = 0;
+ free(context->configured_default_cc_name);
+ context->configured_default_cc_name = NULL;
+
+ tmp = secure_getenv("KRB5_TRACE");
+ if (tmp)
+ heim_add_debug_dest(context->hcontext, "libkrb5", tmp);
+ s = krb5_config_get_strings(context, NULL, "logging", "krb5", NULL);
+ if (s) {
+ char **p;
+
+ for (p = s; *p; p++)
+ heim_add_debug_dest(context->hcontext, "libkrb5", *p);
+ krb5_config_free_strings(s);
+ }
+
+ tmp = krb5_config_get_string(context, NULL, "libdefaults",
+ "check-rd-req-server", NULL);
+ if (tmp == NULL)
+ tmp = secure_getenv("KRB5_CHECK_RD_REQ_SERVER");
+ if(tmp) {
+ if (strcasecmp(tmp, "ignore") == 0)
+ context->flags |= KRB5_CTX_F_RD_REQ_IGNORE;
+ }
+ ret = krb5_config_get_bool_default(context, NULL, TRUE,
+ "libdefaults",
+ "fcache_strict_checking", NULL);
+ if (ret)
+ context->flags |= KRB5_CTX_F_FCACHE_STRICT_CHECKING;
+
+ return 0;
+}
+
+static krb5_error_code
+cc_ops_register(krb5_context context)
+{
+ context->cc_ops = NULL;
+ context->num_cc_ops = 0;
+
+#ifndef KCM_IS_API_CACHE
+ krb5_cc_register(context, &krb5_acc_ops, TRUE);
+#endif
+ krb5_cc_register(context, &krb5_fcc_ops, TRUE);
+ krb5_cc_register(context, &krb5_dcc_ops, TRUE);
+ krb5_cc_register(context, &krb5_mcc_ops, TRUE);
+#ifdef HAVE_SCC
+ krb5_cc_register(context, &krb5_scc_ops, TRUE);
+#endif
+#ifdef HAVE_KCM
+#ifdef KCM_IS_API_CACHE
+ krb5_cc_register(context, &krb5_akcm_ops, TRUE);
+#endif
+ krb5_cc_register(context, &krb5_kcm_ops, TRUE);
+#endif
+#if defined(HAVE_KEYUTILS_H)
+ krb5_cc_register(context, &krb5_krcc_ops, TRUE);
+#endif
+ _krb5_load_ccache_plugins(context);
+ return 0;
+}
+
+static krb5_error_code
+cc_ops_copy(krb5_context context, const krb5_context src_context)
+{
+ const krb5_cc_ops **cc_ops;
+
+ context->cc_ops = NULL;
+ context->num_cc_ops = 0;
+
+ if (src_context->num_cc_ops == 0)
+ return 0;
+
+ cc_ops = malloc(sizeof(cc_ops[0]) * src_context->num_cc_ops);
+ if (cc_ops == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOMEM,
+ N_("malloc: out of memory", ""));
+ return KRB5_CC_NOMEM;
+ }
+
+ memcpy(rk_UNCONST(cc_ops), src_context->cc_ops,
+ sizeof(cc_ops[0]) * src_context->num_cc_ops);
+ context->cc_ops = cc_ops;
+ context->num_cc_ops = src_context->num_cc_ops;
+
+ return 0;
+}
+
+static krb5_error_code
+kt_ops_register(krb5_context context)
+{
+ context->num_kt_types = 0;
+ context->kt_types = NULL;
+
+ krb5_kt_register (context, &krb5_fkt_ops);
+ krb5_kt_register (context, &krb5_wrfkt_ops);
+ krb5_kt_register (context, &krb5_javakt_ops);
+ krb5_kt_register (context, &krb5_mkt_ops);
+#ifndef HEIMDAL_SMALLER
+ krb5_kt_register (context, &krb5_akf_ops);
+#endif
+ krb5_kt_register (context, &krb5_any_ops);
+ return 0;
+}
+
+static krb5_error_code
+kt_ops_copy(krb5_context context, const krb5_context src_context)
+{
+ context->num_kt_types = 0;
+ context->kt_types = NULL;
+
+ if (src_context->num_kt_types == 0)
+ return 0;
+
+ context->kt_types = malloc(sizeof(context->kt_types[0]) * src_context->num_kt_types);
+ if (context->kt_types == NULL)
+ return krb5_enomem(context);
+
+ context->num_kt_types = src_context->num_kt_types;
+ memcpy(context->kt_types, src_context->kt_types,
+ sizeof(context->kt_types[0]) * src_context->num_kt_types);
+
+ return 0;
+}
+
+static const char *sysplugin_dirs[] = {
+#ifdef _WIN32
+ "$ORIGIN",
+#else
+ "$ORIGIN/../lib/plugin/krb5",
+#endif
+#ifdef __APPLE__
+ LIBDIR "/plugin/krb5",
+#ifdef HEIM_PLUGINS_SEARCH_SYSTEM
+ "/Library/KerberosPlugins/KerberosFrameworkPlugins",
+ "/System/Library/KerberosPlugins/KerberosFrameworkPlugins",
+#endif
+#endif
+ NULL
+};
+
+static void
+init_context_once(void *ctx)
+{
+ krb5_context context = ctx;
+ char **dirs;
+
+#ifdef _WIN32
+ dirs = rk_UNCONST(sysplugin_dirs);
+#else
+ dirs = krb5_config_get_strings(context, NULL, "libdefaults",
+ "plugin_dir", NULL);
+ if (dirs == NULL)
+ dirs = rk_UNCONST(sysplugin_dirs);
+#endif
+
+ _krb5_load_plugins(context, "krb5", (const char **)dirs);
+
+ if (dirs != rk_UNCONST(sysplugin_dirs))
+ krb5_config_free_strings(dirs);
+
+ bindtextdomain(HEIMDAL_TEXTDOMAIN, HEIMDAL_LOCALEDIR);
+}
+
+/**
+ * Initializes the context structure and reads the configuration file
+ * /etc/krb5.conf. The structure should be freed by calling
+ * krb5_free_context() when it is no longer being used.
+ *
+ * @param context pointer to returned context
+ *
+ * @return Returns 0 to indicate success. Otherwise an errno code is
+ * returned. Failure means either that something bad happened during
+ * initialization (typically ENOMEM) or that Kerberos should not be
+ * used ENXIO. If the function returns HEIM_ERR_RANDOM_OFFLINE, the
+ * random source is not available and later Kerberos calls might fail.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_context(krb5_context *context)
+{
+ static heim_base_once_t init_context = HEIM_BASE_ONCE_INIT;
+ krb5_context p;
+ krb5_error_code ret;
+ char **files;
+ uint8_t rnd;
+
+ *context = NULL;
+
+ /**
+ * krb5_init_context() will get one random byte to make sure our
+ * random is alive. Assumption is that once the non blocking
+ * source allows us to pull bytes, its all seeded and allows us to
+ * pull more bytes.
+ *
+ * Most Kerberos users calls krb5_init_context(), so this is
+ * useful point where we can do the checking.
+ */
+ ret = krb5_generate_random(&rnd, sizeof(rnd));
+ if (ret)
+ return ret;
+
+ p = calloc(1, sizeof(*p));
+ if(!p)
+ return ENOMEM;
+
+ if ((p->hcontext = heim_context_init()) == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ if (!issuid())
+ p->flags |= KRB5_CTX_F_HOMEDIR_ACCESS;
+
+ ret = krb5_get_default_config_files(&files);
+ if(ret)
+ goto out;
+ ret = krb5_set_config_files(p, files);
+ krb5_free_config_files(files);
+ if(ret)
+ goto out;
+
+ /* done enough to load plugins */
+ heim_base_once_f(&init_context, p, init_context_once);
+
+ /* init error tables */
+ _krb5_init_ets(p);
+ cc_ops_register(p);
+ kt_ops_register(p);
+
+#ifdef PKINIT
+ ret = hx509_context_init(&p->hx509ctx);
+ if (ret)
+ goto out;
+#endif
+ if (rk_SOCK_INIT())
+ p->flags |= KRB5_CTX_F_SOCKETS_INITIALIZED;
+
+out:
+ if (ret) {
+ krb5_free_context(p);
+ p = NULL;
+ } else {
+ heim_context_set_log_utc(p->hcontext, p->log_utc);
+ }
+ *context = p;
+ return ret;
+}
+
+#ifndef HEIMDAL_SMALLER
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_permitted_enctypes(krb5_context context,
+ krb5_enctype **etypes)
+{
+ return krb5_get_default_in_tkt_etypes(context, KRB5_PDU_NONE, etypes);
+}
+
+/*
+ *
+ */
+
+static krb5_error_code
+copy_etypes (krb5_context context,
+ krb5_enctype *enctypes,
+ krb5_enctype **ret_enctypes)
+{
+ unsigned int i;
+
+ for (i = 0; enctypes[i]; i++)
+ ;
+ i++;
+
+ *ret_enctypes = malloc(sizeof(enctypes[0]) * i);
+ if (*ret_enctypes == NULL)
+ return krb5_enomem(context);
+ memcpy(*ret_enctypes, enctypes, sizeof(enctypes[0]) * i);
+ return 0;
+}
+
+/**
+ * Make a copy for the Kerberos 5 context, the new krb5_context shoud
+ * be freed with krb5_free_context().
+ *
+ * @param context the Kerberos context to copy
+ * @param out the copy of the Kerberos, set to NULL error.
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_context(krb5_context context, krb5_context *out)
+{
+ krb5_error_code ret;
+ krb5_context p;
+
+ *out = NULL;
+
+ p = calloc(1, sizeof(*p));
+ if (p == NULL)
+ return krb5_enomem(context);
+
+ if ((p->hcontext = heim_context_init()) == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ heim_context_set_log_utc(p->hcontext, context->log_utc);
+
+ if (context->default_cc_name &&
+ (p->default_cc_name = strdup(context->default_cc_name)) == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ if (context->default_cc_name_env &&
+ (p->default_cc_name_env =
+ strdup(context->default_cc_name_env)) == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ if (context->configured_default_cc_name &&
+ (p->configured_default_cc_name =
+ strdup(context->configured_default_cc_name)) == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ if (context->etypes) {
+ ret = copy_etypes(context, context->etypes, &p->etypes);
+ if (ret)
+ goto out;
+ }
+ if (context->cfg_etypes) {
+ ret = copy_etypes(context, context->cfg_etypes, &p->cfg_etypes);
+ if (ret)
+ goto out;
+ }
+ if (context->etypes_des) {
+ ret = copy_etypes(context, context->etypes_des, &p->etypes_des);
+ if (ret)
+ goto out;
+ }
+
+ if (context->default_realms) {
+ ret = krb5_copy_host_realm(context,
+ context->default_realms, &p->default_realms);
+ if (ret)
+ goto out;
+ }
+
+ ret = _krb5_config_copy(context, context->cf, &p->cf);
+ if (ret)
+ goto out;
+
+ /* XXX should copy */
+ _krb5_init_ets(p);
+
+ cc_ops_copy(p, context);
+ kt_ops_copy(p, context);
+
+ ret = krb5_set_extra_addresses(p, context->extra_addresses);
+ if (ret)
+ goto out;
+ ret = krb5_set_extra_addresses(p, context->ignore_addresses);
+ if (ret)
+ goto out;
+
+ ret = _krb5_copy_send_to_kdc_func(p, context);
+ if (ret)
+ goto out;
+
+ *out = p;
+
+ return 0;
+
+ out:
+ krb5_free_context(p);
+ return ret;
+}
+
+#endif
+
+/**
+ * Frees the krb5_context allocated by krb5_init_context().
+ *
+ * @param context context to be freed.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_context(krb5_context context)
+{
+ _krb5_free_name_canon_rules(context, context->name_canon_rules);
+ free(context->default_cc_name);
+ free(context->default_cc_name_env);
+ free(context->configured_default_cc_name);
+ free(context->etypes);
+ free(context->cfg_etypes);
+ free(context->etypes_des);
+ free(context->permitted_enctypes);
+ free(context->tgs_etypes);
+ free(context->as_etypes);
+ krb5_free_host_realm (context, context->default_realms);
+ krb5_config_file_free (context, context->cf);
+ free(rk_UNCONST(context->cc_ops));
+ free(context->kt_types);
+ krb5_clear_error_message(context);
+ krb5_set_extra_addresses(context, NULL);
+ krb5_set_ignore_addresses(context, NULL);
+ krb5_set_send_to_kdc_func(context, NULL, NULL);
+
+#ifdef PKINIT
+ hx509_context_free(&context->hx509ctx);
+#endif
+
+ if (context->flags & KRB5_CTX_F_SOCKETS_INITIALIZED) {
+ rk_SOCK_EXIT();
+ }
+
+ heim_context_free(&context->hcontext);
+ memset(context, 0, sizeof(*context));
+ free(context);
+}
+
+/**
+ * Reinit the context from a new set of filenames.
+ *
+ * @param context context to add configuration too.
+ * @param filenames array of filenames, end of list is indicated with a NULL filename.
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_config_files(krb5_context context, char **filenames)
+{
+ krb5_error_code ret;
+ heim_config_binding *tmp = NULL;
+
+ if ((ret = heim_set_config_files(context->hcontext, filenames,
+ &tmp)))
+ return ret;
+ krb5_config_file_free(context, context->cf);
+ context->cf = (krb5_config_binding *)tmp;
+ return init_context_from_config_file(context);
+}
+
+#ifndef HEIMDAL_SMALLER
+/**
+ * Reinit the context from configuration file contents in a C string.
+ * This should only be used in tests.
+ *
+ * @param context context to add configuration too.
+ * @param config configuration.
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_config(krb5_context context, const char *config)
+{
+ krb5_error_code ret;
+ krb5_config_binding *tmp = NULL;
+
+ if ((ret = krb5_config_parse_string_multi(context, config, &tmp)))
+ return ret;
+#if 0
+ /* with this enabled and if there are no config files, Kerberos is
+ considererd disabled */
+ if (tmp == NULL)
+ return ENXIO;
+#endif
+
+ krb5_config_file_free(context, context->cf);
+ context->cf = tmp;
+ ret = init_context_from_config_file(context);
+ return ret;
+}
+#endif
+
+/*
+ * `pq' isn't free, it's up the the caller
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_prepend_config_files(const char *filelist, char **pq, char ***ret_pp)
+{
+ return heim_prepend_config_files(filelist, pq, ret_pp);
+}
+
+/**
+ * Prepend the filename to the global configuration list.
+ *
+ * @param filelist a filename to add to the default list of filename
+ * @param pfilenames return array of filenames, should be freed with krb5_free_config_files().
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_prepend_config_files_default(const char *filelist, char ***pfilenames)
+{
+ return heim_prepend_config_files_default(filelist, krb5_config_file,
+ "KRB5_CONFIG", pfilenames);
+}
+
+/**
+ * Get the global configuration list.
+ *
+ * @param pfilenames return array of filenames, should be freed with krb5_free_config_files().
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_default_config_files(char ***pfilenames)
+{
+ if (pfilenames == NULL)
+ return EINVAL;
+ return heim_get_default_config_files(krb5_config_file, "KRB5_CONFIG",
+ pfilenames);
+}
+
+/**
+ * Free a list of configuration files.
+ *
+ * @param filenames list, terminated with a NULL pointer, to be
+ * freed. NULL is an valid argument.
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_config_files(char **filenames)
+{
+ heim_free_config_files(filenames);
+}
+
+/**
+ * Returns the list of Kerberos encryption types sorted in order of
+ * most preferred to least preferred encryption type. Note that some
+ * encryption types might be disabled, so you need to check with
+ * krb5_enctype_valid() before using the encryption type.
+ *
+ * @return list of enctypes, terminated with ETYPE_NULL. Its a static
+ * array completed into the Kerberos library so the content doesn't
+ * need to be freed.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION const krb5_enctype * KRB5_LIB_CALL
+krb5_kerberos_enctypes(krb5_context context)
+{
+ static const krb5_enctype p[] = {
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ ETYPE_AES128_CTS_HMAC_SHA1_96,
+ ETYPE_AES256_CTS_HMAC_SHA384_192,
+ ETYPE_AES128_CTS_HMAC_SHA256_128,
+ ETYPE_DES3_CBC_SHA1,
+ ETYPE_ARCFOUR_HMAC_MD5,
+ ETYPE_NULL
+ };
+
+ static const krb5_enctype weak[] = {
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ ETYPE_AES128_CTS_HMAC_SHA1_96,
+ ETYPE_AES256_CTS_HMAC_SHA384_192,
+ ETYPE_AES128_CTS_HMAC_SHA256_128,
+ ETYPE_DES3_CBC_SHA1,
+ ETYPE_DES3_CBC_MD5,
+ ETYPE_ARCFOUR_HMAC_MD5,
+ ETYPE_DES_CBC_MD5,
+ ETYPE_DES_CBC_MD4,
+ ETYPE_DES_CBC_CRC,
+ ETYPE_NULL
+ };
+
+ /*
+ * if the list of enctypes enabled by "allow_weak_crypto"
+ * are valid, then return the former default enctype list
+ * that contained the weak entries.
+ */
+ if (krb5_enctype_valid(context, ETYPE_DES_CBC_CRC) == 0 &&
+ krb5_enctype_valid(context, ETYPE_DES_CBC_MD4) == 0 &&
+ krb5_enctype_valid(context, ETYPE_DES_CBC_MD5) == 0 &&
+ krb5_enctype_valid(context, ETYPE_DES_CBC_NONE) == 0 &&
+ krb5_enctype_valid(context, ETYPE_DES_CFB64_NONE) == 0 &&
+ krb5_enctype_valid(context, ETYPE_DES_PCBC_NONE) == 0)
+ return weak;
+
+ return p;
+}
+
+/*
+ *
+ */
+
+static krb5_error_code
+copy_enctypes(krb5_context context,
+ const krb5_enctype *in,
+ krb5_enctype **out)
+{
+ krb5_enctype *p = NULL;
+ size_t m, n;
+
+ for (n = 0; in[n]; n++)
+ ;
+ n++;
+ ALLOC(p, n);
+ if(p == NULL)
+ return krb5_enomem(context);
+ for (n = 0, m = 0; in[n]; n++) {
+ if (krb5_enctype_valid(context, in[n]) != 0)
+ continue;
+ p[m++] = in[n];
+ }
+ p[m] = KRB5_ENCTYPE_NULL;
+ if (m == 0) {
+ free(p);
+ krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("no valid enctype set", ""));
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ *out = p;
+ return 0;
+}
+
+
+/*
+ * set `etype' to a malloced list of the default enctypes
+ */
+
+static krb5_error_code
+default_etypes(krb5_context context, krb5_enctype **etype)
+{
+ const krb5_enctype *p = krb5_kerberos_enctypes(context);
+ return copy_enctypes(context, p, etype);
+}
+
+/**
+ * Set the default encryption types that will be use in communcation
+ * with the KDC, clients and servers.
+ *
+ * @param context Kerberos 5 context.
+ * @param etypes Encryption types, array terminated with ETYPE_NULL (0).
+ * A value of NULL resets the encryption types to the defaults set in the
+ * configuration file.
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_default_in_tkt_etypes(krb5_context context,
+ const krb5_enctype *etypes)
+{
+ krb5_error_code ret;
+ krb5_enctype *p = NULL;
+
+ if(!etypes) {
+ etypes = context->cfg_etypes;
+ }
+
+ if(etypes) {
+ ret = copy_enctypes(context, etypes, &p);
+ if (ret)
+ return ret;
+ }
+ if(context->etypes)
+ free(context->etypes);
+ context->etypes = p;
+ return 0;
+}
+
+/**
+ * Get the default encryption types that will be use in communcation
+ * with the KDC, clients and servers.
+ *
+ * @param context Kerberos 5 context.
+ * @param pdu_type request type (AS, TGS or none)
+ * @param etypes Encryption types, array terminated with
+ * ETYPE_NULL(0), caller should free array with krb5_xfree():
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_default_in_tkt_etypes(krb5_context context,
+ krb5_pdu pdu_type,
+ krb5_enctype **etypes)
+{
+ krb5_enctype *enctypes = NULL;
+ krb5_error_code ret;
+ krb5_enctype *p;
+
+ heim_assert(pdu_type == KRB5_PDU_AS_REQUEST ||
+ pdu_type == KRB5_PDU_TGS_REQUEST ||
+ pdu_type == KRB5_PDU_NONE, "unexpected pdu type");
+
+ if (pdu_type == KRB5_PDU_AS_REQUEST && context->as_etypes != NULL)
+ enctypes = context->as_etypes;
+ else if (pdu_type == KRB5_PDU_TGS_REQUEST && context->tgs_etypes != NULL)
+ enctypes = context->tgs_etypes;
+ else if (context->etypes != NULL)
+ enctypes = context->etypes;
+
+ if (enctypes != NULL) {
+ ret = copy_enctypes(context, enctypes, &p);
+ if (ret)
+ return ret;
+ } else {
+ ret = default_etypes(context, &p);
+ if (ret)
+ return ret;
+ }
+ *etypes = p;
+ return 0;
+}
+
+/**
+ * Init the built-in ets in the Kerberos library.
+ *
+ * @param context kerberos context to add the ets too
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_init_ets(krb5_context context)
+{
+}
+
+static void
+_krb5_init_ets(krb5_context context)
+{
+ heim_add_et_list(context->hcontext, initialize_krb5_error_table_r);
+ heim_add_et_list(context->hcontext, initialize_asn1_error_table_r);
+ heim_add_et_list(context->hcontext, initialize_heim_error_table_r);
+
+ heim_add_et_list(context->hcontext, initialize_k524_error_table_r);
+ heim_add_et_list(context->hcontext, initialize_k5e1_error_table_r);
+
+#ifdef COM_ERR_BINDDOMAIN_krb5
+ bindtextdomain(COM_ERR_BINDDOMAIN_krb5, HEIMDAL_LOCALEDIR);
+ bindtextdomain(COM_ERR_BINDDOMAIN_asn1, HEIMDAL_LOCALEDIR);
+ bindtextdomain(COM_ERR_BINDDOMAIN_heim, HEIMDAL_LOCALEDIR);
+ bindtextdomain(COM_ERR_BINDDOMAIN_k524, HEIMDAL_LOCALEDIR);
+#endif
+
+#ifdef PKINIT
+ heim_add_et_list(context->hcontext, initialize_hx_error_table_r);
+#ifdef COM_ERR_BINDDOMAIN_hx
+ bindtextdomain(COM_ERR_BINDDOMAIN_hx, HEIMDAL_LOCALEDIR);
+#endif
+#endif
+}
+
+/**
+ * Make the kerberos library default to the admin KDC.
+ *
+ * @param context Kerberos 5 context.
+ * @param flag boolean flag to select if the use the admin KDC or not.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_set_use_admin_kdc (krb5_context context, krb5_boolean flag)
+{
+ context->use_admin_kdc = flag;
+}
+
+/**
+ * Make the kerberos library default to the admin KDC.
+ *
+ * @param context Kerberos 5 context.
+ *
+ * @return boolean flag to telling the context will use admin KDC as the default KDC.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_get_use_admin_kdc (krb5_context context)
+{
+ return context->use_admin_kdc;
+}
+
+/**
+ * Add extra address to the address list that the library will add to
+ * the client's address list when communicating with the KDC.
+ *
+ * @param context Kerberos 5 context.
+ * @param addresses addreses to add
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_add_extra_addresses(krb5_context context, krb5_addresses *addresses)
+{
+
+ if(context->extra_addresses)
+ return krb5_append_addresses(context,
+ context->extra_addresses, addresses);
+ else
+ return krb5_set_extra_addresses(context, addresses);
+}
+
+/**
+ * Set extra address to the address list that the library will add to
+ * the client's address list when communicating with the KDC.
+ *
+ * @param context Kerberos 5 context.
+ * @param addresses addreses to set
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_extra_addresses(krb5_context context, const krb5_addresses *addresses)
+{
+ if(context->extra_addresses)
+ krb5_free_addresses(context, context->extra_addresses);
+
+ if(addresses == NULL) {
+ if(context->extra_addresses != NULL) {
+ free(context->extra_addresses);
+ context->extra_addresses = NULL;
+ }
+ return 0;
+ }
+ if(context->extra_addresses == NULL) {
+ context->extra_addresses = malloc(sizeof(*context->extra_addresses));
+ if (context->extra_addresses == NULL)
+ return krb5_enomem(context);
+ }
+ return krb5_copy_addresses(context, addresses, context->extra_addresses);
+}
+
+/**
+ * Get extra address to the address list that the library will add to
+ * the client's address list when communicating with the KDC.
+ *
+ * @param context Kerberos 5 context.
+ * @param addresses addreses to set
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_extra_addresses(krb5_context context, krb5_addresses *addresses)
+{
+ if(context->extra_addresses == NULL) {
+ memset(addresses, 0, sizeof(*addresses));
+ return 0;
+ }
+ return krb5_copy_addresses(context,context->extra_addresses, addresses);
+}
+
+/**
+ * Add extra addresses to ignore when fetching addresses from the
+ * underlaying operating system.
+ *
+ * @param context Kerberos 5 context.
+ * @param addresses addreses to ignore
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_add_ignore_addresses(krb5_context context, krb5_addresses *addresses)
+{
+
+ if(context->ignore_addresses)
+ return krb5_append_addresses(context,
+ context->ignore_addresses, addresses);
+ else
+ return krb5_set_ignore_addresses(context, addresses);
+}
+
+/**
+ * Set extra addresses to ignore when fetching addresses from the
+ * underlaying operating system.
+ *
+ * @param context Kerberos 5 context.
+ * @param addresses addreses to ignore
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_ignore_addresses(krb5_context context, const krb5_addresses *addresses)
+{
+ if(context->ignore_addresses)
+ krb5_free_addresses(context, context->ignore_addresses);
+ if(addresses == NULL) {
+ if(context->ignore_addresses != NULL) {
+ free(context->ignore_addresses);
+ context->ignore_addresses = NULL;
+ }
+ return 0;
+ }
+ if(context->ignore_addresses == NULL) {
+ context->ignore_addresses = malloc(sizeof(*context->ignore_addresses));
+ if (context->ignore_addresses == NULL)
+ return krb5_enomem(context);
+ }
+ return krb5_copy_addresses(context, addresses, context->ignore_addresses);
+}
+
+/**
+ * Get extra addresses to ignore when fetching addresses from the
+ * underlaying operating system.
+ *
+ * @param context Kerberos 5 context.
+ * @param addresses list addreses ignored
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_ignore_addresses(krb5_context context, krb5_addresses *addresses)
+{
+ if(context->ignore_addresses == NULL) {
+ memset(addresses, 0, sizeof(*addresses));
+ return 0;
+ }
+ return krb5_copy_addresses(context, context->ignore_addresses, addresses);
+}
+
+/**
+ * Set version of fcache that the library should use.
+ *
+ * @param context Kerberos 5 context.
+ * @param version version number.
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_fcache_version(krb5_context context, int version)
+{
+ context->fcache_vno = version;
+ return 0;
+}
+
+/**
+ * Get version of fcache that the library should use.
+ *
+ * @param context Kerberos 5 context.
+ * @param version version number.
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_fcache_version(krb5_context context, int *version)
+{
+ *version = context->fcache_vno;
+ return 0;
+}
+
+/**
+ * Runtime check if the Kerberos library was complied with thread support.
+ *
+ * @return TRUE if the library was compiled with thread support, FALSE if not.
+ *
+ * @ingroup krb5
+ */
+
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_is_thread_safe(void)
+{
+#ifdef ENABLE_PTHREAD_SUPPORT
+ return TRUE;
+#else
+ return FALSE;
+#endif
+}
+
+/**
+ * Set if the library should use DNS to canonicalize hostnames.
+ *
+ * @param context Kerberos 5 context.
+ * @param flag if its dns canonicalizion is used or not.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_set_dns_canonicalize_hostname (krb5_context context, krb5_boolean flag)
+{
+ if (flag)
+ context->flags |= KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME;
+ else
+ context->flags &= ~KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME;
+}
+
+/**
+ * Get if the library uses DNS to canonicalize hostnames.
+ *
+ * @param context Kerberos 5 context.
+ *
+ * @return return non zero if the library uses DNS to canonicalize hostnames.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_get_dns_canonicalize_hostname (krb5_context context)
+{
+ return (context->flags & KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME) ? 1 : 0;
+}
+
+/**
+ * Get current offset in time to the KDC.
+ *
+ * @param context Kerberos 5 context.
+ * @param sec seconds part of offset.
+ * @param usec micro seconds part of offset.
+ *
+ * @return returns zero
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_kdc_sec_offset (krb5_context context, int32_t *sec, int32_t *usec)
+{
+ if (sec)
+ *sec = context->kdc_sec_offset;
+ if (usec)
+ *usec = context->kdc_usec_offset;
+ return 0;
+}
+
+/**
+ * Set current offset in time to the KDC.
+ *
+ * @param context Kerberos 5 context.
+ * @param sec seconds part of offset.
+ * @param usec micro seconds part of offset.
+ *
+ * @return returns zero
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_kdc_sec_offset (krb5_context context, int32_t sec, int32_t usec)
+{
+ context->kdc_sec_offset = sec;
+ if (usec >= 0)
+ context->kdc_usec_offset = usec;
+ return 0;
+}
+
+/**
+ * Get max time skew allowed.
+ *
+ * @param context Kerberos 5 context.
+ *
+ * @return timeskew in seconds.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION time_t KRB5_LIB_CALL
+krb5_get_max_time_skew (krb5_context context)
+{
+ return context->max_skew;
+}
+
+/**
+ * Set max time skew allowed.
+ *
+ * @param context Kerberos 5 context.
+ * @param t timeskew in seconds.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_set_max_time_skew (krb5_context context, time_t t)
+{
+ context->max_skew = t;
+}
+
+/*
+ * Init encryption types in len, val with etypes.
+ *
+ * @param context Kerberos 5 context.
+ * @param pdu_type type of pdu
+ * @param len output length of val.
+ * @param val output array of enctypes.
+ * @param etypes etypes to set val and len to, if NULL, use default enctypes.
+
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_init_etype(krb5_context context,
+ krb5_pdu pdu_type,
+ unsigned *len,
+ krb5_enctype **val,
+ const krb5_enctype *etypes)
+{
+ krb5_error_code ret;
+
+ if (etypes == NULL)
+ ret = krb5_get_default_in_tkt_etypes(context, pdu_type, val);
+ else
+ ret = copy_enctypes(context, etypes, val);
+ if (ret)
+ return ret;
+
+ if (len) {
+ *len = 0;
+ while ((*val)[*len] != KRB5_ENCTYPE_NULL)
+ (*len)++;
+ }
+ return 0;
+}
+
+/*
+ * Allow homedir access
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+_krb5_homedir_access(krb5_context context)
+{
+ if (context)
+ return !!(context->flags & KRB5_CTX_F_HOMEDIR_ACCESS);
+ return !issuid();
+}
+
+/**
+ * Enable and disable home directory access on either the global state
+ * or the krb5_context state. By calling krb5_set_home_dir_access()
+ * with context set to NULL, the global state is configured otherwise
+ * the state for the krb5_context is modified.
+ *
+ * For home directory access to be allowed, both the global state and
+ * the krb5_context state have to be allowed.
+ *
+ * @param context a Kerberos 5 context or NULL
+ * @param allow allow if TRUE home directory
+ * @return the old value
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_set_home_dir_access(krb5_context context, krb5_boolean allow)
+{
+ krb5_boolean old = _krb5_homedir_access(context);
+
+ if (context) {
+ if (allow)
+ context->flags |= KRB5_CTX_F_HOMEDIR_ACCESS;
+ else
+ context->flags &= ~KRB5_CTX_F_HOMEDIR_ACCESS;
+ heim_context_set_homedir_access(context->hcontext, allow ? 1 : 0);
+ }
+
+ return old;
+}
+
diff --git a/third_party/heimdal/lib/krb5/convert_creds.c b/third_party/heimdal/lib/krb5/convert_creds.c
new file mode 100644
index 0000000..fc371c6
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/convert_creds.c
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include "krb5-v4compat.h"
+
+#ifndef HEIMDAL_SMALLER
+
+/**
+ * Convert the v5 credentials in in_cred to v4-dito in v4creds. This
+ * is done by sending them to the 524 function in the KDC. If
+ * `in_cred' doesn't contain a DES session key, then a new one is
+ * gotten from the KDC and stored in the cred cache `ccache'.
+ *
+ * @param context Kerberos 5 context.
+ * @param in_cred the credential to convert
+ * @param v4creds the converted credential
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5_v4compat
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb524_convert_creds_kdc(krb5_context context,
+ krb5_creds *in_cred,
+ struct credentials *v4creds)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ memset(v4creds, 0, sizeof(*v4creds));
+ krb5_set_error_message(context, EINVAL,
+ N_("krb524_convert_creds_kdc not supported", ""));
+ return EINVAL;
+}
+
+/**
+ * Convert the v5 credentials in in_cred to v4-dito in v4creds,
+ * check the credential cache ccache before checking with the KDC.
+ *
+ * @param context Kerberos 5 context.
+ * @param ccache credential cache used to check for des-ticket.
+ * @param in_cred the credential to convert
+ * @param v4creds the converted credential
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5_v4compat
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb524_convert_creds_kdc_ccache(krb5_context context,
+ krb5_ccache ccache,
+ krb5_creds *in_cred,
+ struct credentials *v4creds)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ memset(v4creds, 0, sizeof(*v4creds));
+ krb5_set_error_message(context, EINVAL,
+ N_("krb524_convert_creds_kdc_ccache not supported", ""));
+ return EINVAL;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/krb5/copy_host_realm.c b/third_party/heimdal/lib/krb5/copy_host_realm.c
new file mode 100644
index 0000000..f68d0d7
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/copy_host_realm.c
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ * Copy the list of realms from `from' to `to'.
+ *
+ * @param context Kerberos 5 context.
+ * @param from list of realms to copy from.
+ * @param to list of realms to copy to, free list of krb5_free_host_realm().
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_host_realm(krb5_context context,
+ const krb5_realm *from,
+ krb5_realm **to)
+{
+ unsigned int n, i;
+ const krb5_realm *p;
+
+ for (n = 1, p = from; *p != NULL; ++p)
+ ++n;
+
+ *to = calloc (n, sizeof(**to));
+ if (*to == NULL)
+ return krb5_enomem(context);
+
+ for (i = 0, p = from; *p != NULL; ++p, ++i) {
+ (*to)[i] = strdup(*p);
+ if ((*to)[i] == NULL) {
+ krb5_free_host_realm (context, *to);
+ return krb5_enomem(context);
+ }
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/crc.c b/third_party/heimdal/lib/krb5/crc.c
new file mode 100644
index 0000000..3090760
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crc.c
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+static u_long table[256];
+
+#define CRC_GEN 0xEDB88320L
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_crc_init_table(void)
+{
+ static int flag = 0;
+ unsigned long crc, poly;
+ unsigned int i, j;
+
+ if(flag) return;
+ poly = CRC_GEN;
+ for (i = 0; i < 256; i++) {
+ crc = i;
+ for (j = 8; j > 0; j--) {
+ if (crc & 1) {
+ crc = (crc >> 1) ^ poly;
+ } else {
+ crc >>= 1;
+ }
+ }
+ table[i] = crc;
+ }
+ flag = 1;
+}
+
+KRB5_LIB_FUNCTION uint32_t KRB5_LIB_CALL
+_krb5_crc_update (const char *p, size_t len, uint32_t res)
+{
+ while (len--)
+ res = table[(res ^ *p++) & 0xFF] ^ (res >> 8);
+ return res & 0xFFFFFFFF;
+}
diff --git a/third_party/heimdal/lib/krb5/creds.c b/third_party/heimdal/lib/krb5/creds.c
new file mode 100644
index 0000000..d62a70a
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/creds.c
@@ -0,0 +1,282 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ * Free content of krb5_creds.
+ *
+ * @param context Kerberos 5 context.
+ * @param c krb5_creds to free.
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_free_cred_contents (krb5_context context, krb5_creds *c)
+{
+ krb5_free_principal (context, c->client);
+ c->client = NULL;
+ krb5_free_principal (context, c->server);
+ c->server = NULL;
+ krb5_free_keyblock_contents (context, &c->session);
+ krb5_data_free (&c->ticket);
+ krb5_data_free (&c->second_ticket);
+ free_AuthorizationData (&c->authdata);
+ krb5_free_addresses (context, &c->addresses);
+ memset(c, 0, sizeof(*c));
+ return 0;
+}
+
+/**
+ * Copy content of krb5_creds.
+ *
+ * @param context Kerberos 5 context.
+ * @param incred source credential
+ * @param c destination credential, free with krb5_free_cred_contents().
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_creds_contents (krb5_context context,
+ const krb5_creds *incred,
+ krb5_creds *c)
+{
+ krb5_error_code ret;
+
+ memset(c, 0, sizeof(*c));
+ ret = krb5_copy_principal (context, incred->client, &c->client);
+ if (ret)
+ goto fail;
+ ret = krb5_copy_principal (context, incred->server, &c->server);
+ if (ret)
+ goto fail;
+ ret = krb5_copy_keyblock_contents (context, &incred->session, &c->session);
+ if (ret)
+ goto fail;
+ c->times = incred->times;
+ ret = krb5_data_copy (&c->ticket,
+ incred->ticket.data,
+ incred->ticket.length);
+ if (ret)
+ goto fail;
+ ret = krb5_data_copy (&c->second_ticket,
+ incred->second_ticket.data,
+ incred->second_ticket.length);
+ if (ret)
+ goto fail;
+ ret = copy_AuthorizationData(&incred->authdata, &c->authdata);
+ if (ret)
+ goto fail;
+ ret = krb5_copy_addresses (context,
+ &incred->addresses,
+ &c->addresses);
+ if (ret)
+ goto fail;
+ c->flags = incred->flags;
+ return 0;
+
+fail:
+ krb5_free_cred_contents (context, c);
+ return ret;
+}
+
+/**
+ * Copy krb5_creds.
+ *
+ * @param context Kerberos 5 context.
+ * @param incred source credential
+ * @param outcred destination credential, free with krb5_free_creds().
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_creds (krb5_context context,
+ const krb5_creds *incred,
+ krb5_creds **outcred)
+{
+ krb5_creds *c;
+
+ c = calloc(1, sizeof(*c));
+ if (c == NULL)
+ return krb5_enomem(context);
+ *outcred = c;
+ return krb5_copy_creds_contents (context, incred, c);
+}
+
+/**
+ * Free krb5_creds.
+ *
+ * @param context Kerberos 5 context.
+ * @param c krb5_creds to free.
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_free_creds (krb5_context context, krb5_creds *c)
+{
+ if (c != NULL)
+ krb5_free_cred_contents(context, c);
+ free(c);
+ return 0;
+}
+
+/* XXX this do not belong here */
+static krb5_boolean
+krb5_times_equal(const krb5_times *a, const krb5_times *b)
+{
+ return a->starttime == b->starttime &&
+ a->authtime == b->authtime &&
+ a->endtime == b->endtime &&
+ a->renew_till == b->renew_till;
+}
+
+/**
+ * Return TRUE if `mcreds' and `creds' are equal (`whichfields'
+ * determines what equal means).
+ *
+ *
+ * The following flags, set in whichfields affects the comparison:
+ * - KRB5_TC_MATCH_SRV_NAMEONLY Consider all realms equal when comparing the service principal.
+ * - KRB5_TC_MATCH_KEYTYPE Compare enctypes.
+ * - KRB5_TC_MATCH_FLAGS_EXACT Make sure that the ticket flags are identical.
+ * - KRB5_TC_MATCH_FLAGS Make sure that all ticket flags set in mcreds are also present in creds .
+ * - KRB5_TC_MATCH_TIMES_EXACT Compares the ticket times exactly.
+ * - KRB5_TC_MATCH_TIMES Compares only the expiration times of the creds.
+ * - KRB5_TC_MATCH_AUTHDATA Compares the authdata fields.
+ * - KRB5_TC_MATCH_2ND_TKT Compares the second tickets (used by user-to-user authentication).
+ * - KRB5_TC_MATCH_IS_SKEY Compares the existence of the second ticket.
+ *
+ * @param context Kerberos 5 context.
+ * @param whichfields which fields to compare.
+ * @param mcreds cred to compare with.
+ * @param creds cred to compare with.
+ *
+ * @return return TRUE if mcred and creds are equal, FALSE if not.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_compare_creds(krb5_context context, krb5_flags whichfields,
+ const krb5_creds * mcreds, const krb5_creds * creds)
+{
+ krb5_boolean match = TRUE;
+
+ if (match && mcreds->server) {
+ if (whichfields & (KRB5_TC_DONT_MATCH_REALM | KRB5_TC_MATCH_SRV_NAMEONLY))
+ match = krb5_principal_compare_any_realm (context, mcreds->server,
+ creds->server);
+ else
+ match = krb5_principal_compare (context, mcreds->server,
+ creds->server);
+ }
+
+ if (match && mcreds->client) {
+ if(whichfields & KRB5_TC_DONT_MATCH_REALM)
+ match = krb5_principal_compare_any_realm (context, mcreds->client,
+ creds->client);
+ else
+ match = krb5_principal_compare (context, mcreds->client,
+ creds->client);
+ }
+
+ if (match && (whichfields & KRB5_TC_MATCH_KEYTYPE))
+ match = mcreds->session.keytype == creds->session.keytype;
+
+ if (match && (whichfields & KRB5_TC_MATCH_FLAGS_EXACT))
+ match = mcreds->flags.i == creds->flags.i;
+
+ if (match && (whichfields & KRB5_TC_MATCH_FLAGS))
+ match = (creds->flags.i & mcreds->flags.i) == mcreds->flags.i;
+
+ if (match && (whichfields & KRB5_TC_MATCH_TIMES_EXACT))
+ match = krb5_times_equal(&mcreds->times, &creds->times);
+
+ if (match && (whichfields & KRB5_TC_MATCH_TIMES))
+ /* compare only expiration times */
+ match = (mcreds->times.renew_till <= creds->times.renew_till) &&
+ (mcreds->times.endtime <= creds->times.endtime);
+
+ if (match && (whichfields & KRB5_TC_MATCH_AUTHDATA)) {
+ unsigned int i;
+ if(mcreds->authdata.len != creds->authdata.len)
+ match = FALSE;
+ else
+ for(i = 0; match && i < mcreds->authdata.len; i++)
+ match = (mcreds->authdata.val[i].ad_type ==
+ creds->authdata.val[i].ad_type) &&
+ (krb5_data_cmp(&mcreds->authdata.val[i].ad_data,
+ &creds->authdata.val[i].ad_data) == 0);
+ }
+ if (match && (whichfields & KRB5_TC_MATCH_2ND_TKT))
+ match = (krb5_data_cmp(&mcreds->second_ticket, &creds->second_ticket) == 0);
+
+ if (match && (whichfields & KRB5_TC_MATCH_IS_SKEY))
+ match = ((mcreds->second_ticket.length == 0) ==
+ (creds->second_ticket.length == 0));
+
+ return match;
+}
+
+/**
+ * Returns the ticket flags for the credentials in creds.
+ * See also krb5_ticket_get_flags().
+ *
+ * @param creds credential to get ticket flags from
+ *
+ * @return ticket flags
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION unsigned long KRB5_LIB_CALL
+krb5_creds_get_ticket_flags(krb5_creds *creds)
+{
+ return TicketFlags2int(creds->flags.b);
+}
diff --git a/third_party/heimdal/lib/krb5/crypto-aes-sha1.c b/third_party/heimdal/lib/krb5/crypto-aes-sha1.c
new file mode 100644
index 0000000..1f3760d
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crypto-aes-sha1.c
@@ -0,0 +1,177 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/*
+ * AES
+ */
+
+static struct _krb5_key_type keytype_aes128_sha1 = {
+ KRB5_ENCTYPE_AES128_CTS_HMAC_SHA1_96,
+ "aes-128",
+ 128,
+ 16,
+ sizeof(struct _krb5_evp_schedule),
+ NULL,
+ _krb5_evp_schedule,
+ _krb5_AES_SHA1_salt,
+ NULL,
+ _krb5_evp_cleanup,
+ EVP_aes_128_cbc
+};
+
+static struct _krb5_key_type keytype_aes256_sha1 = {
+ KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96,
+ "aes-256",
+ 256,
+ 32,
+ sizeof(struct _krb5_evp_schedule),
+ NULL,
+ _krb5_evp_schedule,
+ _krb5_AES_SHA1_salt,
+ NULL,
+ _krb5_evp_cleanup,
+ EVP_aes_256_cbc
+};
+
+struct _krb5_checksum_type _krb5_checksum_hmac_sha1_aes128 = {
+ CKSUMTYPE_HMAC_SHA1_96_AES_128,
+ "hmac-sha1-96-aes128",
+ 64,
+ 12,
+ F_KEYED | F_CPROOF | F_DERIVED,
+ _krb5_SP_HMAC_SHA1_checksum,
+ _krb5_SP_HMAC_SHA1_verify
+};
+
+struct _krb5_checksum_type _krb5_checksum_hmac_sha1_aes256 = {
+ CKSUMTYPE_HMAC_SHA1_96_AES_256,
+ "hmac-sha1-96-aes256",
+ 64,
+ 12,
+ F_KEYED | F_CPROOF | F_DERIVED,
+ _krb5_SP_HMAC_SHA1_checksum,
+ _krb5_SP_HMAC_SHA1_verify
+};
+
+static krb5_error_code
+AES_SHA1_PRF(krb5_context context,
+ krb5_crypto crypto,
+ const krb5_data *in,
+ krb5_data *out)
+{
+ struct _krb5_checksum_type *ct = crypto->et->checksum;
+ struct krb5_crypto_iov iov[1];
+ krb5_error_code ret;
+ Checksum result;
+ krb5_keyblock *derived;
+
+ result.cksumtype = ct->type;
+ ret = krb5_data_alloc(&result.checksum, ct->checksumsize);
+ if (ret) {
+ krb5_set_error_message(context, ret, N_("malloc: out memory", ""));
+ return ret;
+ }
+
+ iov[0].data = *in;
+ iov[0].flags = KRB5_CRYPTO_TYPE_DATA;
+ ret = (*ct->checksum)(context, crypto, NULL, 0, iov, 1, &result);
+ if (ret) {
+ krb5_data_free(&result.checksum);
+ return ret;
+ }
+
+ if (result.checksum.length < crypto->et->blocksize)
+ krb5_abortx(context, "internal prf error");
+
+ derived = NULL;
+ ret = krb5_derive_key(context, crypto->key.key,
+ crypto->et->type, "prf", 3, &derived);
+ if (ret)
+ krb5_abortx(context, "krb5_derive_key");
+
+ ret = krb5_data_alloc(out, crypto->et->blocksize);
+ if (ret)
+ krb5_abortx(context, "malloc failed");
+
+ {
+ const EVP_CIPHER *c = (*crypto->et->keytype->evp)();
+ EVP_CIPHER_CTX ctx;
+
+ EVP_CIPHER_CTX_init(&ctx); /* ivec all zero */
+ EVP_CipherInit_ex(&ctx, c, NULL, derived->keyvalue.data, NULL, 1);
+ EVP_Cipher(&ctx, out->data, result.checksum.data,
+ crypto->et->blocksize);
+ EVP_CIPHER_CTX_cleanup(&ctx);
+ }
+
+ krb5_data_free(&result.checksum);
+ krb5_free_keyblock(context, derived);
+
+ return ret;
+}
+
+struct _krb5_encryption_type _krb5_enctype_aes128_cts_hmac_sha1 = {
+ ETYPE_AES128_CTS_HMAC_SHA1_96,
+ "aes128-cts-hmac-sha1-96",
+ "aes128-cts",
+ 16,
+ 1,
+ 16,
+ &keytype_aes128_sha1,
+ &_krb5_checksum_sha1,
+ &_krb5_checksum_hmac_sha1_aes128,
+ F_DERIVED | F_RFC3961_ENC | F_RFC3961_KDF,
+ _krb5_evp_encrypt_cts,
+ _krb5_evp_encrypt_iov_cts,
+ 16,
+ AES_SHA1_PRF
+};
+
+struct _krb5_encryption_type _krb5_enctype_aes256_cts_hmac_sha1 = {
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ "aes256-cts-hmac-sha1-96",
+ "aes256-cts",
+ 16,
+ 1,
+ 16,
+ &keytype_aes256_sha1,
+ &_krb5_checksum_sha1,
+ &_krb5_checksum_hmac_sha1_aes256,
+ F_DERIVED | F_RFC3961_ENC | F_RFC3961_KDF,
+ _krb5_evp_encrypt_cts,
+ _krb5_evp_encrypt_iov_cts,
+ 16,
+ AES_SHA1_PRF
+};
diff --git a/third_party/heimdal/lib/krb5/crypto-aes-sha2.c b/third_party/heimdal/lib/krb5/crypto-aes-sha2.c
new file mode 100644
index 0000000..94ec9a1
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crypto-aes-sha2.c
@@ -0,0 +1,199 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/*
+ * AES HMAC-SHA2
+ */
+
+krb5_error_code
+_krb5_aes_sha2_md_for_enctype(krb5_context context,
+ krb5_enctype enctype,
+ const EVP_MD **md)
+{
+ switch (enctype) {
+ case ETYPE_AES128_CTS_HMAC_SHA256_128:
+ *md = EVP_sha256();
+ break;
+ case ETYPE_AES256_CTS_HMAC_SHA384_192:
+ *md = EVP_sha384();
+ break;
+ default:
+ return KRB5_PROG_ETYPE_NOSUPP;
+ break;
+ }
+ return 0;
+}
+
+static krb5_error_code
+SP_HMAC_SHA2_checksum(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *result)
+{
+ krb5_error_code ret;
+ const EVP_MD *md;
+ unsigned char hmac[EVP_MAX_MD_SIZE];
+ unsigned int hmaclen = sizeof(hmac);
+
+ ret = _krb5_aes_sha2_md_for_enctype(context, key->key->keytype, &md);
+ if (ret)
+ return ret;
+
+ ret = _krb5_evp_hmac_iov(context, crypto, key, iov, niov, hmac,
+ &hmaclen, md, NULL);
+ if (ret)
+ return ret;
+
+ heim_assert(result->checksum.length <= hmaclen, "SHA2 internal error");
+
+ memcpy(result->checksum.data, hmac, result->checksum.length);
+
+ return 0;
+}
+
+static struct _krb5_key_type keytype_aes128_sha2 = {
+ KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128,
+ "aes-128-sha2",
+ 128,
+ 16,
+ sizeof(struct _krb5_evp_schedule),
+ NULL,
+ _krb5_evp_schedule,
+ _krb5_AES_SHA2_salt,
+ NULL,
+ _krb5_evp_cleanup,
+ EVP_aes_128_cbc
+};
+
+static struct _krb5_key_type keytype_aes256_sha2 = {
+ KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192,
+ "aes-256-sha2",
+ 256,
+ 32,
+ sizeof(struct _krb5_evp_schedule),
+ NULL,
+ _krb5_evp_schedule,
+ _krb5_AES_SHA2_salt,
+ NULL,
+ _krb5_evp_cleanup,
+ EVP_aes_256_cbc
+};
+
+struct _krb5_checksum_type _krb5_checksum_hmac_sha256_128_aes128 = {
+ CKSUMTYPE_HMAC_SHA256_128_AES128,
+ "hmac-sha256-128-aes128",
+ 64,
+ 16,
+ F_KEYED | F_CPROOF | F_DERIVED,
+ SP_HMAC_SHA2_checksum,
+ NULL
+};
+
+struct _krb5_checksum_type _krb5_checksum_hmac_sha384_192_aes256 = {
+ CKSUMTYPE_HMAC_SHA384_192_AES256,
+ "hmac-sha384-192-aes256",
+ 128,
+ 24,
+ F_KEYED | F_CPROOF | F_DERIVED,
+ SP_HMAC_SHA2_checksum,
+ NULL
+};
+
+static krb5_error_code
+AES_SHA2_PRF(krb5_context context,
+ krb5_crypto crypto,
+ const krb5_data *in,
+ krb5_data *out)
+{
+ krb5_error_code ret;
+ krb5_data label;
+ const EVP_MD *md = NULL;
+
+ ret = _krb5_aes_sha2_md_for_enctype(context, crypto->et->type, &md);
+ if (ret)
+ return ret;
+
+ label.data = "prf";
+ label.length = 3;
+
+ ret = krb5_data_alloc(out, EVP_MD_size(md));
+ if (ret)
+ return ret;
+
+ ret = _krb5_SP800_108_HMAC_KDF(context, &crypto->key.key->keyvalue,
+ &label, in, md, out);
+
+ if (ret)
+ krb5_data_free(out);
+
+ return ret;
+}
+
+struct _krb5_encryption_type _krb5_enctype_aes128_cts_hmac_sha256_128 = {
+ ETYPE_AES128_CTS_HMAC_SHA256_128,
+ "aes128-cts-hmac-sha256-128",
+ "aes128-cts-sha256",
+ 16,
+ 1,
+ 16,
+ &keytype_aes128_sha2,
+ NULL, /* should never be called */
+ &_krb5_checksum_hmac_sha256_128_aes128,
+ F_DERIVED | F_ENC_THEN_CKSUM | F_SP800_108_HMAC_KDF,
+ _krb5_evp_encrypt_cts,
+ NULL,
+ 16,
+ AES_SHA2_PRF
+};
+
+struct _krb5_encryption_type _krb5_enctype_aes256_cts_hmac_sha384_192 = {
+ ETYPE_AES256_CTS_HMAC_SHA384_192,
+ "aes256-cts-hmac-sha384-192",
+ "aes256-cts-sha384",
+ 16,
+ 1,
+ 16,
+ &keytype_aes256_sha2,
+ NULL, /* should never be called */
+ &_krb5_checksum_hmac_sha384_192_aes256,
+ F_DERIVED | F_ENC_THEN_CKSUM | F_SP800_108_HMAC_KDF,
+ _krb5_evp_encrypt_cts,
+ NULL,
+ 16,
+ AES_SHA2_PRF
+};
diff --git a/third_party/heimdal/lib/krb5/crypto-algs.c b/third_party/heimdal/lib/krb5/crypto-algs.c
new file mode 100644
index 0000000..eb21fce
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crypto-algs.c
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#ifndef HEIMDAL_SMALLER
+#define DES3_OLD_ENCTYPE 1
+#endif
+
+struct _krb5_checksum_type *_krb5_checksum_types[] = {
+ &_krb5_checksum_none,
+#ifdef HEIM_WEAK_CRYPTO
+ &_krb5_checksum_crc32,
+ &_krb5_checksum_rsa_md4,
+ &_krb5_checksum_rsa_md4_des,
+ &_krb5_checksum_rsa_md5_des,
+#endif
+#ifdef DES3_OLD_ENCTYPE
+ &_krb5_checksum_rsa_md5_des3,
+#endif
+ &_krb5_checksum_rsa_md5,
+ &_krb5_checksum_sha1,
+ &_krb5_checksum_hmac_sha1_des3,
+ &_krb5_checksum_hmac_sha1_aes128,
+ &_krb5_checksum_hmac_sha1_aes256,
+ &_krb5_checksum_hmac_sha256_128_aes128,
+ &_krb5_checksum_hmac_sha384_192_aes256,
+ &_krb5_checksum_hmac_md5,
+ &_krb5_checksum_sha256,
+ &_krb5_checksum_sha384,
+ &_krb5_checksum_sha512
+};
+
+int _krb5_num_checksums
+ = sizeof(_krb5_checksum_types) / sizeof(_krb5_checksum_types[0]);
+
+/*
+ * these should currently be in reverse preference order.
+ * (only relevant for !F_PSEUDO) */
+
+struct _krb5_encryption_type *_krb5_etypes[] = {
+ &_krb5_enctype_aes256_cts_hmac_sha384_192,
+ &_krb5_enctype_aes128_cts_hmac_sha256_128,
+ &_krb5_enctype_aes256_cts_hmac_sha1,
+ &_krb5_enctype_aes128_cts_hmac_sha1,
+ &_krb5_enctype_des3_cbc_sha1,
+ &_krb5_enctype_des3_cbc_none, /* used by the gss-api mech */
+ &_krb5_enctype_arcfour_hmac_md5,
+#ifdef DES3_OLD_ENCTYPE
+ &_krb5_enctype_des3_cbc_md5,
+ &_krb5_enctype_old_des3_cbc_sha1,
+#endif
+#ifdef HEIM_WEAK_CRYPTO
+ &_krb5_enctype_des_cbc_md5,
+ &_krb5_enctype_des_cbc_md4,
+ &_krb5_enctype_des_cbc_crc,
+ &_krb5_enctype_des_cbc_none,
+ &_krb5_enctype_des_cfb64_none,
+ &_krb5_enctype_des_pcbc_none,
+#endif
+ &_krb5_enctype_null
+};
+
+int _krb5_num_etypes = sizeof(_krb5_etypes) / sizeof(_krb5_etypes[0]);
diff --git a/third_party/heimdal/lib/krb5/crypto-arcfour.c b/third_party/heimdal/lib/krb5/crypto-arcfour.c
new file mode 100644
index 0000000..28fc52e
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crypto-arcfour.c
@@ -0,0 +1,368 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * ARCFOUR
+ */
+
+#include "krb5_locl.h"
+
+static struct _krb5_key_type keytype_arcfour = {
+ KRB5_ENCTYPE_ARCFOUR_HMAC_MD5,
+ "arcfour",
+ 128,
+ 16,
+ sizeof(struct _krb5_evp_schedule),
+ NULL,
+ _krb5_evp_schedule,
+ _krb5_arcfour_salt,
+ NULL,
+ _krb5_evp_cleanup,
+ EVP_rc4
+};
+
+/*
+ * checksum according to section 5. of draft-brezak-win2k-krb-rc4-hmac-03.txt
+ */
+
+krb5_error_code
+_krb5_HMAC_MD5_checksum(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *result)
+{
+ EVP_MD_CTX *m;
+ struct _krb5_checksum_type *c = _krb5_find_checksum (CKSUMTYPE_RSA_MD5);
+ const char signature[] = "signaturekey";
+ Checksum ksign_c;
+ struct _krb5_key_data ksign;
+ krb5_keyblock kb;
+ unsigned char t[4];
+ unsigned char tmp[16];
+ unsigned char ksign_c_data[16];
+ krb5_error_code ret;
+ int i;
+
+ if (crypto != NULL) {
+ if (crypto->mdctx == NULL)
+ crypto->mdctx = EVP_MD_CTX_create();
+ if (crypto->mdctx == NULL)
+ return krb5_enomem(context);
+ m = crypto->mdctx;
+ } else
+ m = EVP_MD_CTX_create();
+
+ ksign_c.checksum.length = sizeof(ksign_c_data);
+ ksign_c.checksum.data = ksign_c_data;
+ ret = _krb5_internal_hmac(context, crypto, c, signature, sizeof(signature),
+ 0, key, &ksign_c);
+ if (ret)
+ goto out;
+
+ ksign.key = &kb;
+ kb.keyvalue = ksign_c.checksum;
+ EVP_DigestInit_ex(m, EVP_md5(), NULL);
+ t[0] = (usage >> 0) & 0xFF;
+ t[1] = (usage >> 8) & 0xFF;
+ t[2] = (usage >> 16) & 0xFF;
+ t[3] = (usage >> 24) & 0xFF;
+ EVP_DigestUpdate(m, t, 4);
+ for (i = 0; i < niov; i++) {
+ if (_krb5_crypto_iov_should_sign(&iov[i]))
+ EVP_DigestUpdate(m, iov[i].data.data, iov[i].data.length);
+ }
+ EVP_DigestFinal_ex (m, tmp, NULL);
+
+ ret = _krb5_internal_hmac(context, crypto, c, tmp, sizeof(tmp), 0, &ksign, result);
+out:
+ if (crypto == NULL)
+ EVP_MD_CTX_destroy(m);
+
+ return ret;
+}
+
+struct _krb5_checksum_type _krb5_checksum_hmac_md5 = {
+ CKSUMTYPE_HMAC_MD5,
+ "hmac-md5",
+ 64,
+ 16,
+ F_KEYED | F_CPROOF,
+ _krb5_HMAC_MD5_checksum,
+ NULL
+};
+
+/*
+ * section 6 of draft-brezak-win2k-krb-rc4-hmac-03
+ *
+ * warning: not for small children
+ */
+
+static krb5_error_code
+ARCFOUR_subencrypt(krb5_context context,
+ struct _krb5_key_data *key,
+ void *data,
+ size_t len,
+ unsigned usage,
+ void *ivec)
+{
+ EVP_CIPHER_CTX ctx;
+ struct _krb5_checksum_type *c = _krb5_find_checksum (CKSUMTYPE_RSA_MD5);
+ Checksum k1_c, k2_c, k3_c, cksum;
+ struct _krb5_key_data ke;
+ krb5_keyblock kb;
+ unsigned char t[4];
+ unsigned char *cdata = data;
+ unsigned char k1_c_data[16], k2_c_data[16], k3_c_data[16];
+ krb5_error_code ret;
+
+ if (len < 16) {
+ return KRB5KRB_AP_ERR_INAPP_CKSUM;
+ }
+
+ t[0] = (usage >> 0) & 0xFF;
+ t[1] = (usage >> 8) & 0xFF;
+ t[2] = (usage >> 16) & 0xFF;
+ t[3] = (usage >> 24) & 0xFF;
+
+ k1_c.checksum.length = sizeof(k1_c_data);
+ k1_c.checksum.data = k1_c_data;
+
+ ret = _krb5_internal_hmac(context, NULL, c, t, sizeof(t), 0, key, &k1_c);
+ if (ret)
+ krb5_abortx(context, "hmac failed");
+
+ memcpy (k2_c_data, k1_c_data, sizeof(k1_c_data));
+
+ k2_c.checksum.length = sizeof(k2_c_data);
+ k2_c.checksum.data = k2_c_data;
+
+ ke.key = &kb;
+ kb.keyvalue = k2_c.checksum;
+
+ cksum.checksum.length = 16;
+ cksum.checksum.data = data;
+
+ ret = _krb5_internal_hmac(context, NULL, c, cdata + 16, len - 16, 0, &ke, &cksum);
+ if (ret)
+ krb5_abortx(context, "hmac failed");
+
+ ke.key = &kb;
+ kb.keyvalue = k1_c.checksum;
+
+ k3_c.checksum.length = sizeof(k3_c_data);
+ k3_c.checksum.data = k3_c_data;
+
+ ret = _krb5_internal_hmac(context, NULL, c, data, 16, 0, &ke, &k3_c);
+ if (ret)
+ krb5_abortx(context, "hmac failed");
+
+ EVP_CIPHER_CTX_init(&ctx);
+
+ EVP_CipherInit_ex(&ctx, EVP_rc4(), NULL, k3_c.checksum.data, NULL, 1);
+ EVP_Cipher(&ctx, cdata + 16, cdata + 16, len - 16);
+ EVP_CIPHER_CTX_cleanup(&ctx);
+
+ memset_s(k1_c_data, sizeof(k1_c_data), 0, sizeof(k1_c_data));
+ memset_s(k2_c_data, sizeof(k2_c_data), 0, sizeof(k2_c_data));
+ memset_s(k3_c_data, sizeof(k3_c_data), 0, sizeof(k3_c_data));
+ return 0;
+}
+
+static krb5_error_code
+ARCFOUR_subdecrypt(krb5_context context,
+ struct _krb5_key_data *key,
+ void *data,
+ size_t len,
+ unsigned usage,
+ void *ivec)
+{
+ EVP_CIPHER_CTX ctx;
+ struct _krb5_checksum_type *c = _krb5_find_checksum (CKSUMTYPE_RSA_MD5);
+ Checksum k1_c, k2_c, k3_c, cksum;
+ struct _krb5_key_data ke;
+ krb5_keyblock kb;
+ unsigned char t[4];
+ unsigned char *cdata = data;
+ unsigned char k1_c_data[16], k2_c_data[16], k3_c_data[16];
+ unsigned char cksum_data[16];
+ krb5_error_code ret;
+
+ if (len < 16) {
+ return KRB5KRB_AP_ERR_INAPP_CKSUM;
+ }
+
+ t[0] = (usage >> 0) & 0xFF;
+ t[1] = (usage >> 8) & 0xFF;
+ t[2] = (usage >> 16) & 0xFF;
+ t[3] = (usage >> 24) & 0xFF;
+
+ k1_c.checksum.length = sizeof(k1_c_data);
+ k1_c.checksum.data = k1_c_data;
+
+ ret = _krb5_internal_hmac(context, NULL, c, t, sizeof(t), 0, key, &k1_c);
+ if (ret)
+ krb5_abortx(context, "hmac failed");
+
+ memcpy (k2_c_data, k1_c_data, sizeof(k1_c_data));
+
+ k2_c.checksum.length = sizeof(k2_c_data);
+ k2_c.checksum.data = k2_c_data;
+
+ ke.key = &kb;
+ kb.keyvalue = k1_c.checksum;
+
+ k3_c.checksum.length = sizeof(k3_c_data);
+ k3_c.checksum.data = k3_c_data;
+
+ ret = _krb5_internal_hmac(context, NULL, c, cdata, 16, 0, &ke, &k3_c);
+ if (ret)
+ krb5_abortx(context, "hmac failed");
+
+ EVP_CIPHER_CTX_init(&ctx);
+ EVP_CipherInit_ex(&ctx, EVP_rc4(), NULL, k3_c.checksum.data, NULL, 0);
+ EVP_Cipher(&ctx, cdata + 16, cdata + 16, len - 16);
+ EVP_CIPHER_CTX_cleanup(&ctx);
+
+ ke.key = &kb;
+ kb.keyvalue = k2_c.checksum;
+
+ cksum.checksum.length = 16;
+ cksum.checksum.data = cksum_data;
+
+ ret = _krb5_internal_hmac(context, NULL, c, cdata + 16, len - 16, 0, &ke, &cksum);
+ if (ret)
+ krb5_abortx(context, "hmac failed");
+
+ memset_s(k1_c_data, sizeof(k1_c_data), 0, sizeof(k1_c_data));
+ memset_s(k2_c_data, sizeof(k2_c_data), 0, sizeof(k2_c_data));
+ memset_s(k3_c_data, sizeof(k3_c_data), 0, sizeof(k3_c_data));
+
+ if (ct_memcmp (cksum.checksum.data, data, 16) != 0) {
+ krb5_clear_error_message (context);
+ return KRB5KRB_AP_ERR_BAD_INTEGRITY;
+ } else {
+ return 0;
+ }
+}
+
+/*
+ * convert the usage numbers used in
+ * draft-ietf-cat-kerb-key-derivation-00.txt to the ones in
+ * draft-brezak-win2k-krb-rc4-hmac-04.txt
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_usage2arcfour(krb5_context context, unsigned *usage)
+{
+ switch (*usage) {
+ case KRB5_KU_AS_REP_ENC_PART : /* 3 */
+ *usage = 8;
+ return 0;
+ case KRB5_KU_USAGE_SEAL : /* 22 */
+ *usage = 13;
+ return 0;
+ case KRB5_KU_USAGE_SIGN : /* 23 */
+ *usage = 15;
+ return 0;
+ case KRB5_KU_USAGE_SEQ: /* 24 */
+ *usage = 0;
+ return 0;
+ default :
+ return 0;
+ }
+}
+
+static krb5_error_code
+ARCFOUR_encrypt(krb5_context context,
+ struct _krb5_key_data *key,
+ void *data,
+ size_t len,
+ krb5_boolean encryptp,
+ int usage,
+ void *ivec)
+{
+ krb5_error_code ret;
+ unsigned keyusage = usage;
+
+ if((ret = _krb5_usage2arcfour (context, &keyusage)) != 0)
+ return ret;
+
+ if (encryptp)
+ return ARCFOUR_subencrypt (context, key, data, len, keyusage, ivec);
+ else
+ return ARCFOUR_subdecrypt (context, key, data, len, keyusage, ivec);
+}
+
+static krb5_error_code
+ARCFOUR_prf(krb5_context context,
+ krb5_crypto crypto,
+ const krb5_data *in,
+ krb5_data *out)
+{
+ struct _krb5_checksum_type *c = _krb5_find_checksum(CKSUMTYPE_SHA1);
+ krb5_error_code ret;
+ Checksum res;
+
+ ret = krb5_data_alloc(out, c->checksumsize);
+ if (ret)
+ return ret;
+
+ res.checksum.data = out->data;
+ res.checksum.length = out->length;
+
+ ret = _krb5_internal_hmac(context, crypto, c, in->data, in->length, 0, &crypto->key, &res);
+ if (ret)
+ krb5_data_free(out);
+ return 0;
+}
+
+
+struct _krb5_encryption_type _krb5_enctype_arcfour_hmac_md5 = {
+ ETYPE_ARCFOUR_HMAC_MD5,
+ "arcfour-hmac-md5",
+ "rc4-hmac",
+ 1,
+ 1,
+ 8,
+ &keytype_arcfour,
+ &_krb5_checksum_hmac_md5,
+ &_krb5_checksum_hmac_md5,
+ F_SPECIAL | F_WEAK | F_OLD,
+ ARCFOUR_encrypt,
+ NULL,
+ 0,
+ ARCFOUR_prf
+};
diff --git a/third_party/heimdal/lib/krb5/crypto-des-common.c b/third_party/heimdal/lib/krb5/crypto-des-common.c
new file mode 100644
index 0000000..a8344ae
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crypto-des-common.c
@@ -0,0 +1,158 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* Functions which are used by both single and triple DES enctypes */
+
+#include "krb5_locl.h"
+
+/*
+ * A = A xor B. A & B are 8 bytes.
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_xor8(unsigned char *a, const unsigned char *b)
+{
+ a[0] ^= b[0];
+ a[1] ^= b[1];
+ a[2] ^= b[2];
+ a[3] ^= b[3];
+ a[4] ^= b[4];
+ a[5] ^= b[5];
+ a[6] ^= b[6];
+ a[7] ^= b[7];
+}
+
+#if defined(DES3_OLD_ENCTYPE) || defined(HEIM_WEAK_CRYPTO)
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_des_checksum(krb5_context context,
+ const EVP_MD *evp_md,
+ struct _krb5_key_data *key,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *cksum)
+{
+ struct _krb5_evp_schedule *ctx = key->schedule->data;
+ EVP_MD_CTX *m;
+ DES_cblock ivec;
+ int i;
+ unsigned char *p = cksum->checksum.data;
+
+ krb5_generate_random_block(p, 8);
+
+ m = EVP_MD_CTX_create();
+ if (m == NULL)
+ return krb5_enomem(context);
+
+ EVP_DigestInit_ex(m, evp_md, NULL);
+ EVP_DigestUpdate(m, p, 8);
+ for (i = 0; i < niov; i++) {
+ if (_krb5_crypto_iov_should_sign(&iov[i]))
+ EVP_DigestUpdate(m, iov[i].data.data, iov[i].data.length);
+ }
+ EVP_DigestFinal_ex (m, p + 8, NULL);
+ EVP_MD_CTX_destroy(m);
+ memset_s(&ivec, sizeof(ivec), 0, sizeof(ivec));
+ EVP_CipherInit_ex(&ctx->ectx, NULL, NULL, NULL, (void *)&ivec, -1);
+ EVP_Cipher(&ctx->ectx, p, p, 24);
+
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_des_verify(krb5_context context,
+ const EVP_MD *evp_md,
+ struct _krb5_key_data *key,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *C)
+{
+ struct _krb5_evp_schedule *ctx = key->schedule->data;
+ EVP_MD_CTX *m;
+ unsigned char tmp[24];
+ unsigned char res[16];
+ DES_cblock ivec;
+ krb5_error_code ret = 0;
+ int i;
+
+ m = EVP_MD_CTX_create();
+ if (m == NULL)
+ return krb5_enomem(context);
+
+ memset_s(&ivec, sizeof(ivec), 0, sizeof(ivec));
+ EVP_CipherInit_ex(&ctx->dctx, NULL, NULL, NULL, (void *)&ivec, -1);
+ EVP_Cipher(&ctx->dctx, tmp, C->checksum.data, 24);
+
+ EVP_DigestInit_ex(m, evp_md, NULL);
+ EVP_DigestUpdate(m, tmp, 8); /* confounder */
+ for (i = 0; i < niov; i++) {
+ if (_krb5_crypto_iov_should_sign(&iov[i]))
+ EVP_DigestUpdate(m, iov[i].data.data, iov[i].data.length);
+ }
+ EVP_DigestFinal_ex (m, res, NULL);
+ EVP_MD_CTX_destroy(m);
+ if(ct_memcmp(res, tmp + 8, sizeof(res)) != 0) {
+ krb5_clear_error_message (context);
+ ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
+ }
+ memset_s(tmp, sizeof(tmp), 0, sizeof(tmp));
+ memset_s(res, sizeof(res), 0, sizeof(res));
+ return ret;
+}
+
+#endif
+
+static krb5_error_code
+RSA_MD5_checksum(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *C)
+{
+ if (_krb5_evp_digest_iov(crypto, iov, niov, C->checksum.data,
+ NULL, EVP_md5(), NULL) != 1)
+ krb5_abortx(context, "md5 checksum failed");
+
+ return 0;
+}
+
+struct _krb5_checksum_type _krb5_checksum_rsa_md5 = {
+ CKSUMTYPE_RSA_MD5,
+ "rsa-md5",
+ 64,
+ 16,
+ F_CPROOF,
+ RSA_MD5_checksum,
+ NULL
+};
diff --git a/third_party/heimdal/lib/krb5/crypto-des.c b/third_party/heimdal/lib/krb5/crypto-des.c
new file mode 100644
index 0000000..c569295
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crypto-des.c
@@ -0,0 +1,403 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#ifdef HEIM_WEAK_CRYPTO
+
+
+static void
+krb5_DES_random_key(krb5_context context,
+ krb5_keyblock *key)
+{
+ DES_cblock *k = key->keyvalue.data;
+ do {
+ krb5_generate_random_block(k, sizeof(DES_cblock));
+ DES_set_odd_parity(k);
+ } while(DES_is_weak_key(k));
+}
+
+static void
+krb5_DES_schedule_old(krb5_context context,
+ struct _krb5_key_type *kt,
+ struct _krb5_key_data *key)
+{
+ DES_set_key_unchecked(key->key->keyvalue.data, key->schedule->data);
+}
+
+static void
+krb5_DES_random_to_key(krb5_context context,
+ krb5_keyblock *key,
+ const void *data,
+ size_t size)
+{
+ DES_cblock *k = key->keyvalue.data;
+ memcpy(k, data, key->keyvalue.length);
+ DES_set_odd_parity(k);
+ if(DES_is_weak_key(k))
+ _krb5_xor8(*k, (const unsigned char*)"\0\0\0\0\0\0\0\xf0");
+}
+
+static struct _krb5_key_type keytype_des_old = {
+ ETYPE_DES_CBC_CRC,
+ "des-old",
+ 56,
+ 8,
+ sizeof(DES_key_schedule),
+ krb5_DES_random_key,
+ krb5_DES_schedule_old,
+ _krb5_des_salt,
+ krb5_DES_random_to_key,
+ NULL,
+ NULL
+};
+
+static struct _krb5_key_type keytype_des = {
+ ETYPE_DES_CBC_CRC,
+ "des",
+ 56,
+ 8,
+ sizeof(struct _krb5_evp_schedule),
+ krb5_DES_random_key,
+ _krb5_evp_schedule,
+ _krb5_des_salt,
+ krb5_DES_random_to_key,
+ _krb5_evp_cleanup,
+ EVP_des_cbc
+};
+
+static krb5_error_code
+CRC32_checksum(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *C)
+{
+ uint32_t crc = 0;
+ unsigned char *r = C->checksum.data;
+ int i;
+
+ _krb5_crc_init_table ();
+
+ for (i = 0; i < niov; i++) {
+ if (_krb5_crypto_iov_should_sign(&iov[i]))
+ crc = _krb5_crc_update(iov[i].data.data, iov[i].data.length, crc);
+ }
+
+ r[0] = crc & 0xff;
+ r[1] = (crc >> 8) & 0xff;
+ r[2] = (crc >> 16) & 0xff;
+ r[3] = (crc >> 24) & 0xff;
+ return 0;
+}
+
+static krb5_error_code
+RSA_MD4_checksum(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *C)
+{
+ if (_krb5_evp_digest_iov(crypto, iov, niov, C->checksum.data,
+ NULL, EVP_md4(), NULL) != 1)
+ krb5_abortx(context, "md4 checksum failed");
+ return 0;
+}
+
+static krb5_error_code
+RSA_MD4_DES_checksum(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *cksum)
+{
+ return _krb5_des_checksum(context, EVP_md4(), key, iov, niov, cksum);
+}
+
+static krb5_error_code
+RSA_MD4_DES_verify(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *C)
+{
+ return _krb5_des_verify(context, EVP_md4(), key, iov, niov, C);
+}
+
+static krb5_error_code
+RSA_MD5_DES_checksum(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *C)
+{
+ return _krb5_des_checksum(context, EVP_md5(), key, iov, niov, C);
+}
+
+static krb5_error_code
+RSA_MD5_DES_verify(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *C)
+{
+ return _krb5_des_verify(context, EVP_md5(), key, iov, niov, C);
+}
+
+struct _krb5_checksum_type _krb5_checksum_crc32 = {
+ CKSUMTYPE_CRC32,
+ "crc32",
+ 1,
+ 4,
+ 0,
+ CRC32_checksum,
+ NULL
+};
+
+struct _krb5_checksum_type _krb5_checksum_rsa_md4 = {
+ CKSUMTYPE_RSA_MD4,
+ "rsa-md4",
+ 64,
+ 16,
+ F_CPROOF,
+ RSA_MD4_checksum,
+ NULL
+};
+
+struct _krb5_checksum_type _krb5_checksum_rsa_md4_des = {
+ CKSUMTYPE_RSA_MD4_DES,
+ "rsa-md4-des",
+ 64,
+ 24,
+ F_KEYED | F_CPROOF | F_VARIANT,
+ RSA_MD4_DES_checksum,
+ RSA_MD4_DES_verify
+};
+
+struct _krb5_checksum_type _krb5_checksum_rsa_md5_des = {
+ CKSUMTYPE_RSA_MD5_DES,
+ "rsa-md5-des",
+ 64,
+ 24,
+ F_KEYED | F_CPROOF | F_VARIANT,
+ RSA_MD5_DES_checksum,
+ RSA_MD5_DES_verify
+};
+
+static krb5_error_code
+evp_des_encrypt_null_ivec(krb5_context context,
+ struct _krb5_key_data *key,
+ void *data,
+ size_t len,
+ krb5_boolean encryptp,
+ int usage,
+ void *ignore_ivec)
+{
+ struct _krb5_evp_schedule *ctx = key->schedule->data;
+ EVP_CIPHER_CTX *c;
+ DES_cblock ivec;
+ memset(&ivec, 0, sizeof(ivec));
+ c = encryptp ? &ctx->ectx : &ctx->dctx;
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, (void *)&ivec, -1);
+ EVP_Cipher(c, data, data, len);
+ return 0;
+}
+
+static krb5_error_code
+evp_des_encrypt_key_ivec(krb5_context context,
+ struct _krb5_key_data *key,
+ void *data,
+ size_t len,
+ krb5_boolean encryptp,
+ int usage,
+ void *ignore_ivec)
+{
+ struct _krb5_evp_schedule *ctx = key->schedule->data;
+ EVP_CIPHER_CTX *c;
+ DES_cblock ivec;
+ memcpy(&ivec, key->key->keyvalue.data, sizeof(ivec));
+ c = encryptp ? &ctx->ectx : &ctx->dctx;
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, (void *)&ivec, -1);
+ EVP_Cipher(c, data, data, len);
+ return 0;
+}
+
+static krb5_error_code
+DES_CFB64_encrypt_null_ivec(krb5_context context,
+ struct _krb5_key_data *key,
+ void *data,
+ size_t len,
+ krb5_boolean encryptp,
+ int usage,
+ void *ignore_ivec)
+{
+ DES_cblock ivec;
+ int num = 0;
+ DES_key_schedule *s = key->schedule->data;
+ memset(&ivec, 0, sizeof(ivec));
+
+ DES_cfb64_encrypt(data, data, len, s, &ivec, &num, encryptp);
+ return 0;
+}
+
+static krb5_error_code
+DES_PCBC_encrypt_key_ivec(krb5_context context,
+ struct _krb5_key_data *key,
+ void *data,
+ size_t len,
+ krb5_boolean encryptp,
+ int usage,
+ void *ignore_ivec)
+{
+ DES_cblock ivec;
+ DES_key_schedule *s = key->schedule->data;
+ memcpy(&ivec, key->key->keyvalue.data, sizeof(ivec));
+
+ DES_pcbc_encrypt(data, data, len, s, &ivec, encryptp);
+ return 0;
+}
+
+struct _krb5_encryption_type _krb5_enctype_des_cbc_crc = {
+ ETYPE_DES_CBC_CRC,
+ "des-cbc-crc",
+ NULL,
+ 8,
+ 8,
+ 8,
+ &keytype_des,
+ &_krb5_checksum_crc32,
+ NULL,
+ F_DISABLED|F_WEAK|F_OLD,
+ evp_des_encrypt_key_ivec,
+ NULL,
+ 0,
+ NULL
+};
+
+struct _krb5_encryption_type _krb5_enctype_des_cbc_md4 = {
+ ETYPE_DES_CBC_MD4,
+ "des-cbc-md4",
+ NULL,
+ 8,
+ 8,
+ 8,
+ &keytype_des,
+ &_krb5_checksum_rsa_md4,
+ &_krb5_checksum_rsa_md4_des,
+ F_DISABLED|F_WEAK|F_OLD,
+ evp_des_encrypt_null_ivec,
+ NULL,
+ 0,
+ NULL
+};
+
+struct _krb5_encryption_type _krb5_enctype_des_cbc_md5 = {
+ ETYPE_DES_CBC_MD5,
+ "des-cbc-md5",
+ NULL,
+ 8,
+ 8,
+ 8,
+ &keytype_des,
+ &_krb5_checksum_rsa_md5,
+ &_krb5_checksum_rsa_md5_des,
+ F_DISABLED|F_WEAK|F_OLD,
+ evp_des_encrypt_null_ivec,
+ NULL,
+ 0,
+ NULL
+};
+
+struct _krb5_encryption_type _krb5_enctype_des_cbc_none = {
+ ETYPE_DES_CBC_NONE,
+ "des-cbc-none",
+ NULL,
+ 8,
+ 8,
+ 0,
+ &keytype_des,
+ &_krb5_checksum_none,
+ NULL,
+ F_PSEUDO|F_DISABLED|F_WEAK|F_OLD,
+ evp_des_encrypt_null_ivec,
+ NULL,
+ 0,
+ NULL
+};
+
+struct _krb5_encryption_type _krb5_enctype_des_cfb64_none = {
+ ETYPE_DES_CFB64_NONE,
+ "des-cfb64-none",
+ NULL,
+ 1,
+ 1,
+ 0,
+ &keytype_des_old,
+ &_krb5_checksum_none,
+ NULL,
+ F_PSEUDO|F_DISABLED|F_WEAK|F_OLD,
+ DES_CFB64_encrypt_null_ivec,
+ NULL,
+ 0,
+ NULL
+};
+
+struct _krb5_encryption_type _krb5_enctype_des_pcbc_none = {
+ ETYPE_DES_PCBC_NONE,
+ "des-pcbc-none",
+ NULL,
+ 8,
+ 8,
+ 0,
+ &keytype_des_old,
+ &_krb5_checksum_none,
+ NULL,
+ F_PSEUDO|F_DISABLED|F_WEAK|F_OLD,
+ DES_PCBC_encrypt_key_ivec,
+ NULL,
+ 0,
+ NULL
+};
+#endif /* HEIM_WEAK_CRYPTO */
diff --git a/third_party/heimdal/lib/krb5/crypto-des3.c b/third_party/heimdal/lib/krb5/crypto-des3.c
new file mode 100644
index 0000000..d231921
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crypto-des3.c
@@ -0,0 +1,292 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/*
+ *
+ */
+
+static void
+DES3_random_key(krb5_context context,
+ krb5_keyblock *key)
+{
+ DES_cblock *k = key->keyvalue.data;
+ do {
+ krb5_generate_random_block(k, 3 * sizeof(DES_cblock));
+ DES_set_odd_parity(&k[0]);
+ DES_set_odd_parity(&k[1]);
+ DES_set_odd_parity(&k[2]);
+ } while(DES_is_weak_key(&k[0]) ||
+ DES_is_weak_key(&k[1]) ||
+ DES_is_weak_key(&k[2]));
+}
+
+static krb5_error_code
+DES3_prf(krb5_context context,
+ krb5_crypto crypto,
+ const krb5_data *in,
+ krb5_data *out)
+{
+ struct _krb5_checksum_type *ct = crypto->et->checksum;
+ struct krb5_crypto_iov iov[1];
+ krb5_error_code ret;
+ Checksum result;
+ krb5_keyblock *derived;
+
+ result.cksumtype = ct->type;
+ ret = krb5_data_alloc(&result.checksum, ct->checksumsize);
+ if (ret) {
+ krb5_set_error_message(context, ret, N_("malloc: out memory", ""));
+ return ret;
+ }
+
+ iov[0].data = *in;
+ iov[0].flags = KRB5_CRYPTO_TYPE_DATA;
+ ret = (*ct->checksum)(context, crypto, NULL, 0, iov, 1, &result);
+ if (ret) {
+ krb5_data_free(&result.checksum);
+ return ret;
+ }
+
+ if (result.checksum.length < crypto->et->blocksize)
+ krb5_abortx(context, "internal prf error");
+
+ derived = NULL;
+ ret = krb5_derive_key(context, crypto->key.key,
+ crypto->et->type, "prf", 3, &derived);
+ if (ret)
+ krb5_abortx(context, "krb5_derive_key");
+
+ ret = krb5_data_alloc(out, crypto->et->prf_length);
+ if (ret)
+ krb5_abortx(context, "malloc failed");
+
+ {
+ const EVP_CIPHER *c = (*crypto->et->keytype->evp)();
+ EVP_CIPHER_CTX ctx;
+
+ EVP_CIPHER_CTX_init(&ctx); /* ivec all zero */
+ EVP_CipherInit_ex(&ctx, c, NULL, derived->keyvalue.data, NULL, 1);
+ EVP_Cipher(&ctx, out->data, result.checksum.data,
+ crypto->et->prf_length);
+ EVP_CIPHER_CTX_cleanup(&ctx);
+ }
+
+ krb5_data_free(&result.checksum);
+ krb5_free_keyblock(context, derived);
+
+ return ret;
+}
+
+#ifdef DES3_OLD_ENCTYPE
+static struct _krb5_key_type keytype_des3 = {
+ ETYPE_OLD_DES3_CBC_SHA1,
+ "des3",
+ 168,
+ 24,
+ sizeof(struct _krb5_evp_schedule),
+ DES3_random_key,
+ _krb5_evp_schedule,
+ _krb5_des3_salt,
+ _krb5_DES3_random_to_key,
+ _krb5_evp_cleanup,
+ EVP_des_ede3_cbc
+};
+#endif
+
+static struct _krb5_key_type keytype_des3_derived = {
+ ETYPE_OLD_DES3_CBC_SHA1,
+ "des3",
+ 168,
+ 24,
+ sizeof(struct _krb5_evp_schedule),
+ DES3_random_key,
+ _krb5_evp_schedule,
+ _krb5_des3_salt_derived,
+ _krb5_DES3_random_to_key,
+ _krb5_evp_cleanup,
+ EVP_des_ede3_cbc
+};
+
+#ifdef DES3_OLD_ENCTYPE
+static krb5_error_code
+RSA_MD5_DES3_checksum(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *C)
+{
+ return _krb5_des_checksum(context, EVP_md5(), key, iov, niov, C);
+}
+
+static krb5_error_code
+RSA_MD5_DES3_verify(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *C)
+{
+ return _krb5_des_verify(context, EVP_md5(), key, iov, niov, C);
+}
+
+struct _krb5_checksum_type _krb5_checksum_rsa_md5_des3 = {
+ CKSUMTYPE_RSA_MD5_DES3,
+ "rsa-md5-des3",
+ 64,
+ 24,
+ F_KEYED | F_CPROOF | F_VARIANT,
+ RSA_MD5_DES3_checksum,
+ RSA_MD5_DES3_verify
+};
+#endif
+
+struct _krb5_checksum_type _krb5_checksum_hmac_sha1_des3 = {
+ CKSUMTYPE_HMAC_SHA1_DES3,
+ "hmac-sha1-des3",
+ 64,
+ 20,
+ F_KEYED | F_CPROOF | F_DERIVED,
+ _krb5_SP_HMAC_SHA1_checksum,
+ NULL
+};
+
+#ifdef DES3_OLD_ENCTYPE
+struct _krb5_encryption_type _krb5_enctype_des3_cbc_md5 = {
+ ETYPE_DES3_CBC_MD5,
+ "des3-cbc-md5",
+ NULL,
+ 8,
+ 8,
+ 8,
+ &keytype_des3,
+ &_krb5_checksum_rsa_md5,
+ &_krb5_checksum_rsa_md5_des3,
+ F_OLD,
+ _krb5_evp_encrypt,
+ _krb5_evp_encrypt_iov,
+ 0,
+ NULL
+};
+#endif
+
+struct _krb5_encryption_type _krb5_enctype_des3_cbc_sha1 = {
+ ETYPE_DES3_CBC_SHA1,
+ "des3-cbc-sha1",
+ NULL,
+ 8,
+ 8,
+ 8,
+ &keytype_des3_derived,
+ &_krb5_checksum_sha1,
+ &_krb5_checksum_hmac_sha1_des3,
+ F_DERIVED | F_RFC3961_ENC | F_RFC3961_KDF | F_OLD,
+ _krb5_evp_encrypt,
+ _krb5_evp_encrypt_iov,
+ 16,
+ DES3_prf
+};
+
+#ifdef DES3_OLD_ENCTYPE
+struct _krb5_encryption_type _krb5_enctype_old_des3_cbc_sha1 = {
+ ETYPE_OLD_DES3_CBC_SHA1,
+ "old-des3-cbc-sha1",
+ NULL,
+ 8,
+ 8,
+ 8,
+ &keytype_des3,
+ &_krb5_checksum_sha1,
+ &_krb5_checksum_hmac_sha1_des3,
+ F_OLD,
+ _krb5_evp_encrypt,
+ _krb5_evp_encrypt_iov,
+ 0,
+ NULL
+};
+#endif
+
+struct _krb5_encryption_type _krb5_enctype_des3_cbc_none = {
+ ETYPE_DES3_CBC_NONE,
+ "des3-cbc-none",
+ NULL,
+ 8,
+ 8,
+ 0,
+ &keytype_des3_derived,
+ &_krb5_checksum_none,
+ NULL,
+ F_PSEUDO | F_OLD,
+ _krb5_evp_encrypt,
+ _krb5_evp_encrypt_iov,
+ 0,
+ NULL
+};
+
+void
+_krb5_DES3_random_to_key(krb5_context context,
+ krb5_keyblock *key,
+ const void *data,
+ size_t size)
+{
+ unsigned char *x = key->keyvalue.data;
+ const u_char *q = data;
+ DES_cblock *k;
+ int i, j;
+
+ memset(key->keyvalue.data, 0, key->keyvalue.length);
+ for (i = 0; i < 3; ++i) {
+ unsigned char foo;
+ for (j = 0; j < 7; ++j) {
+ unsigned char b = q[7 * i + j];
+
+ x[8 * i + j] = b;
+ }
+ foo = 0;
+ for (j = 6; j >= 0; --j) {
+ foo |= q[7 * i + j] & 1;
+ foo <<= 1;
+ }
+ x[8 * i + 7] = foo;
+ }
+ k = key->keyvalue.data;
+ for (i = 0; i < 3; i++) {
+ DES_set_odd_parity(&k[i]);
+ if(DES_is_weak_key(&k[i]))
+ _krb5_xor8(k[i], (const unsigned char*)"\0\0\0\0\0\0\0\xf0");
+ }
+}
diff --git a/third_party/heimdal/lib/krb5/crypto-evp.c b/third_party/heimdal/lib/krb5/crypto-evp.c
new file mode 100644
index 0000000..a03cdca
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crypto-evp.c
@@ -0,0 +1,671 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+void
+_krb5_evp_schedule(krb5_context context,
+ struct _krb5_key_type *kt,
+ struct _krb5_key_data *kd)
+{
+ struct _krb5_evp_schedule *key = kd->schedule->data;
+ const EVP_CIPHER *c = (*kt->evp)();
+
+ EVP_CIPHER_CTX_init(&key->ectx);
+ EVP_CIPHER_CTX_init(&key->dctx);
+
+ EVP_CipherInit_ex(&key->ectx, c, NULL, kd->key->keyvalue.data, NULL, 1);
+ EVP_CipherInit_ex(&key->dctx, c, NULL, kd->key->keyvalue.data, NULL, 0);
+}
+
+void
+_krb5_evp_cleanup(krb5_context context, struct _krb5_key_data *kd)
+{
+ struct _krb5_evp_schedule *key = kd->schedule->data;
+ EVP_CIPHER_CTX_cleanup(&key->ectx);
+ EVP_CIPHER_CTX_cleanup(&key->dctx);
+}
+
+int
+_krb5_evp_digest_iov(krb5_crypto crypto,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ void *hash,
+ unsigned int *hsize,
+ const EVP_MD *md,
+ ENGINE *engine)
+{
+ EVP_MD_CTX *ctx;
+ int ret, i;
+ krb5_data current = {0,0};
+
+ if (crypto != NULL) {
+ if (crypto->mdctx == NULL)
+ crypto->mdctx = EVP_MD_CTX_create();
+ if (crypto->mdctx == NULL)
+ return 0;
+ ctx = crypto->mdctx;
+ } else
+ ctx = EVP_MD_CTX_create();
+
+ ret = EVP_DigestInit_ex(ctx, md, engine);
+ if (ret != 1)
+ goto out;
+
+ for (i = 0; i < niov; i++) {
+ if (_krb5_crypto_iov_should_sign(&iov[i])) {
+ if ((char *)current.data + current.length == iov[i].data.data) {
+ current.length += iov[i].data.length;
+ } else {
+ if (current.data) {
+ ret = EVP_DigestUpdate(ctx, current.data, current.length);
+ if (ret != 1)
+ goto out;
+ }
+ current = iov[i].data;
+ }
+ }
+ }
+
+ if (current.data) {
+ ret = EVP_DigestUpdate(ctx, current.data, current.length);
+ if (ret != 1)
+ goto out;
+ }
+
+ ret = EVP_DigestFinal_ex(ctx, hash, hsize);
+
+out:
+ if (crypto == NULL)
+ EVP_MD_CTX_destroy(ctx);
+
+ return ret;
+}
+
+krb5_error_code
+_krb5_evp_hmac_iov(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ void *hmac,
+ unsigned int *hmaclen,
+ const EVP_MD *md,
+ ENGINE *engine)
+{
+ HMAC_CTX *ctx;
+ krb5_data current = {0, 0};
+ int i;
+
+ if (crypto != NULL) {
+ if (crypto->hmacctx == NULL)
+ crypto->hmacctx = HMAC_CTX_new();
+ ctx = crypto->hmacctx;
+ } else {
+ ctx = HMAC_CTX_new();
+ }
+ if (ctx == NULL)
+ return krb5_enomem(context);
+
+ if (HMAC_Init_ex(ctx, key->key->keyvalue.data, key->key->keyvalue.length,
+ md, engine) == 0) {
+ HMAC_CTX_free(ctx);
+ return krb5_enomem(context);
+ }
+
+ for (i = 0; i < niov; i++) {
+ if (_krb5_crypto_iov_should_sign(&iov[i])) {
+ if ((char *)current.data + current.length == iov[i].data.data) {
+ current.length += iov[i].data.length;
+ } else {
+ if (current.data)
+ HMAC_Update(ctx, current.data, current.length);
+ current = iov[i].data;
+ }
+ }
+ }
+
+ if (current.data)
+ HMAC_Update(ctx, current.data, current.length);
+
+ HMAC_Final(ctx, hmac, hmaclen);
+
+ if (crypto == NULL)
+ HMAC_CTX_free(ctx);
+
+ return 0;
+}
+
+krb5_error_code
+_krb5_evp_encrypt(krb5_context context,
+ struct _krb5_key_data *key,
+ void *data,
+ size_t len,
+ krb5_boolean encryptp,
+ int usage,
+ void *ivec)
+{
+ struct _krb5_evp_schedule *ctx = key->schedule->data;
+ EVP_CIPHER_CTX *c;
+ c = encryptp ? &ctx->ectx : &ctx->dctx;
+ if (ivec == NULL) {
+ /* alloca ? */
+ size_t len2 = EVP_CIPHER_CTX_iv_length(c);
+ void *loiv = malloc(len2);
+ if (loiv == NULL)
+ return krb5_enomem(context);
+ memset(loiv, 0, len2);
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, loiv, -1);
+ free(loiv);
+ } else
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, ivec, -1);
+ EVP_Cipher(c, data, data, len);
+ return 0;
+}
+
+struct _krb5_evp_iov_cursor
+{
+ struct krb5_crypto_iov *iov;
+ int niov;
+ krb5_data current;
+ int nextidx;
+};
+
+static const unsigned char zero_ivec[EVP_MAX_BLOCK_LENGTH] = { 0 };
+
+static inline int
+_krb5_evp_iov_should_encrypt(struct krb5_crypto_iov *iov)
+{
+ return (iov->flags == KRB5_CRYPTO_TYPE_DATA
+ || iov->flags == KRB5_CRYPTO_TYPE_HEADER
+ || iov->flags == KRB5_CRYPTO_TYPE_PADDING);
+}
+/*
+ * If we have a group of iovecs which have been split up from
+ * a single common buffer, expand the 'current' iovec out to
+ * be as large as possible.
+ */
+
+static inline void
+_krb5_evp_iov_cursor_expand(struct _krb5_evp_iov_cursor *cursor)
+{
+ if (cursor->nextidx == cursor->niov)
+ return;
+
+ while (_krb5_evp_iov_should_encrypt(&cursor->iov[cursor->nextidx])) {
+ if (cursor->iov[cursor->nextidx].data.length != 0 &&
+ ((char *)cursor->current.data + cursor->current.length
+ != cursor->iov[cursor->nextidx].data.data)) {
+ return;
+ }
+ cursor->current.length += cursor->iov[cursor->nextidx].data.length;
+ cursor->nextidx++;
+ }
+
+ return;
+}
+
+/* Move the cursor along to the start of the next block to be
+ * encrypted */
+static inline void
+_krb5_evp_iov_cursor_nextcrypt(struct _krb5_evp_iov_cursor *cursor)
+{
+ for (; cursor->nextidx < cursor->niov; cursor->nextidx++) {
+ if (_krb5_evp_iov_should_encrypt(&cursor->iov[cursor->nextidx])
+ && cursor->iov[cursor->nextidx].data.length != 0) {
+ cursor->current = cursor->iov[cursor->nextidx].data;
+ cursor->nextidx++;
+ _krb5_evp_iov_cursor_expand(cursor);
+ return;
+ }
+ }
+
+ cursor->current.length = 0; /* No matches, so we're done here */
+}
+
+static inline void
+_krb5_evp_iov_cursor_init(struct _krb5_evp_iov_cursor *cursor,
+ struct krb5_crypto_iov *iov, int niov)
+{
+ memset(cursor, 0, sizeof(struct _krb5_evp_iov_cursor));
+
+ cursor->iov = iov;
+ cursor->niov = niov;
+ cursor->nextidx = 0;
+
+ /* Move along to the first block we're going to be encrypting */
+ _krb5_evp_iov_cursor_nextcrypt(cursor);
+}
+
+static inline void
+_krb5_evp_iov_cursor_advance(struct _krb5_evp_iov_cursor *cursor,
+ size_t amount)
+{
+ while (amount > 0) {
+ if (cursor->current.length > amount) {
+ cursor->current.data = (char *)cursor->current.data + amount;
+ cursor->current.length -= amount;
+ return;
+ }
+ amount -= cursor->current.length;
+ _krb5_evp_iov_cursor_nextcrypt(cursor);
+ }
+}
+
+static inline int
+_krb5_evp_iov_cursor_done(struct _krb5_evp_iov_cursor *cursor)
+{
+ return (cursor->nextidx == cursor->niov && cursor->current.length == 0);
+}
+
+/* Fill a memory buffer with data from one or more iovecs. Doesn't
+ * advance the passed in cursor - use outcursor for the position
+ * at the end
+ */
+static inline void
+_krb5_evp_iov_cursor_fillbuf(struct _krb5_evp_iov_cursor *cursor,
+ unsigned char *buf, size_t length,
+ struct _krb5_evp_iov_cursor *outcursor)
+{
+ struct _krb5_evp_iov_cursor cursorint;
+
+ cursorint = *cursor;
+
+ while (length > 0 && !_krb5_evp_iov_cursor_done(&cursorint)) {
+ if (cursorint.current.length > length) {
+ memcpy(buf, cursorint.current.data, length);
+ _krb5_evp_iov_cursor_advance(&cursorint, length);
+ length = 0;
+ } else {
+ memcpy(buf, cursorint.current.data, cursorint.current.length);
+ length -= cursorint.current.length;
+ buf += cursorint.current.length;
+ _krb5_evp_iov_cursor_nextcrypt(&cursorint);
+ }
+ }
+
+ if (outcursor != NULL)
+ *outcursor = cursorint;
+}
+
+/* Fill an iovec from a memory buffer. Always advances the cursor to
+ * the end of the filled region
+ */
+static inline void
+_krb5_evp_iov_cursor_fillvec(struct _krb5_evp_iov_cursor *cursor,
+ unsigned char *buf, size_t length)
+{
+ while (length > 0 && !_krb5_evp_iov_cursor_done(cursor)) {
+ if (cursor->current.length > length) {
+ memcpy(cursor->current.data, buf, length);
+ _krb5_evp_iov_cursor_advance(cursor, length);
+ length = 0;
+ } else {
+ memcpy(cursor->current.data, buf, cursor->current.length);
+ length -= cursor->current.length;
+ buf += cursor->current.length;
+ _krb5_evp_iov_cursor_nextcrypt(cursor);
+ }
+ }
+}
+
+static size_t
+_krb5_evp_iov_cryptlength(struct krb5_crypto_iov *iov, int niov)
+{
+ int i;
+ size_t length = 0;
+
+ for (i = 0; i < niov; i++) {
+ if (_krb5_evp_iov_should_encrypt(&iov[i]))
+ length += iov[i].data.length;
+ }
+
+ return length;
+}
+
+int
+_krb5_evp_encrypt_iov(krb5_context context,
+ struct _krb5_key_data *key,
+ struct krb5_crypto_iov *iov,
+ int niov,
+ krb5_boolean encryptp,
+ int usage,
+ void *ivec)
+{
+ size_t blocksize, blockmask, wholeblocks;
+ struct _krb5_evp_schedule *ctx = key->schedule->data;
+ unsigned char tmp[EVP_MAX_BLOCK_LENGTH];
+ EVP_CIPHER_CTX *c;
+ struct _krb5_evp_iov_cursor cursor;
+
+ c = encryptp ? &ctx->ectx : &ctx->dctx;
+
+ blocksize = EVP_CIPHER_CTX_block_size(c);
+
+ blockmask = ~(blocksize - 1);
+
+ if (ivec)
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, ivec, -1);
+ else
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1);
+
+ _krb5_evp_iov_cursor_init(&cursor, iov, niov);
+
+ while (!_krb5_evp_iov_cursor_done(&cursor)) {
+
+ /* Number of bytes of data in this iovec that are in whole blocks */
+ wholeblocks = cursor.current.length & ~blockmask;
+
+ if (wholeblocks != 0) {
+ EVP_Cipher(c, cursor.current.data,
+ cursor.current.data, wholeblocks);
+ _krb5_evp_iov_cursor_advance(&cursor, wholeblocks);
+ }
+
+ /* If there's a partial block of data remaining in the current
+ * iovec, steal enough from subsequent iovecs to form a whole block */
+ if (cursor.current.length > 0 && cursor.current.length < blocksize) {
+ /* Build up a block's worth of data in tmp, leaving the cursor
+ * pointing at where we started */
+ _krb5_evp_iov_cursor_fillbuf(&cursor, tmp, blocksize, NULL);
+
+ EVP_Cipher(c, tmp, tmp, blocksize);
+
+ /* Copy the data in tmp back into the iovecs that it came from,
+ * advancing the cursor */
+ _krb5_evp_iov_cursor_fillvec(&cursor, tmp, blocksize);
+ }
+ }
+
+ return 0;
+}
+
+int
+_krb5_evp_encrypt_iov_cts(krb5_context context,
+ struct _krb5_key_data *key,
+ struct krb5_crypto_iov *iov,
+ int niov,
+ krb5_boolean encryptp,
+ int usage,
+ void *ivec)
+{
+ size_t blocksize, blockmask, wholeblocks, length;
+ size_t remaining, partiallen;
+ struct _krb5_evp_iov_cursor cursor, lastpos;
+ struct _krb5_evp_schedule *ctx = key->schedule->data;
+ unsigned char tmp[EVP_MAX_BLOCK_LENGTH], tmp2[EVP_MAX_BLOCK_LENGTH];
+ unsigned char tmp3[EVP_MAX_BLOCK_LENGTH], ivec2[EVP_MAX_BLOCK_LENGTH];
+ EVP_CIPHER_CTX *c;
+ int i;
+
+ c = encryptp ? &ctx->ectx : &ctx->dctx;
+
+ blocksize = EVP_CIPHER_CTX_block_size(c);
+ blockmask = ~(blocksize - 1);
+
+ length = _krb5_evp_iov_cryptlength(iov, niov);
+
+ if (length < blocksize) {
+ krb5_set_error_message(context, EINVAL,
+ "message block too short");
+ return EINVAL;
+ }
+
+ if (length == blocksize)
+ return _krb5_evp_encrypt_iov(context, key, iov, niov,
+ encryptp, usage, ivec);
+
+ if (ivec)
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, ivec, -1);
+ else
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1);
+
+ if (encryptp) {
+ /* On our first pass, we want to process everything but the
+ * final partial block */
+ remaining = ((length - 1) & blockmask);
+ partiallen = length - remaining;
+
+ memset(&lastpos, 0, sizeof(lastpos)); /* Keep the compiler happy */
+ } else {
+ /* Decryption needs to leave 2 whole blocks and a partial for
+ * further processing */
+ if (length > 2 * blocksize) {
+ remaining = (((length - 1) / blocksize) * blocksize) - (blocksize*2);
+ partiallen = length - remaining - (blocksize * 2);
+ } else {
+ remaining = 0;
+ partiallen = length - blocksize;
+ }
+ }
+
+ _krb5_evp_iov_cursor_init(&cursor, iov, niov);
+ while (remaining > 0) {
+ /* If the iovec has more data than we need, just use it */
+ if (cursor.current.length >= remaining) {
+ EVP_Cipher(c, cursor.current.data, cursor.current.data, remaining);
+
+ if (encryptp) {
+ /* We've just encrypted the last block of data. Make a copy
+ * of it (and its location) for the CTS dance, below */
+ lastpos = cursor;
+ _krb5_evp_iov_cursor_advance(&lastpos, remaining - blocksize);
+ memcpy(ivec2, lastpos.current.data, blocksize);
+ }
+
+ _krb5_evp_iov_cursor_advance(&cursor, remaining);
+ remaining = 0;
+ } else {
+ /* Use as much as we can, firstly all of the whole blocks */
+ wholeblocks = cursor.current.length & blockmask;
+
+ if (wholeblocks > 0) {
+ EVP_Cipher(c, cursor.current.data, cursor.current.data,
+ wholeblocks);
+ _krb5_evp_iov_cursor_advance(&cursor, wholeblocks);
+ remaining -= wholeblocks;
+ }
+
+ /* Then, if we have partial data left, steal enough from subsequent
+ * iovecs to make a whole block */
+ if (cursor.current.length > 0 && cursor.current.length < blocksize) {
+ if (encryptp && remaining == blocksize)
+ lastpos = cursor;
+
+ _krb5_evp_iov_cursor_fillbuf(&cursor, ivec2, blocksize, NULL);
+ EVP_Cipher(c, ivec2, ivec2, blocksize);
+ _krb5_evp_iov_cursor_fillvec(&cursor, ivec2, blocksize);
+
+ remaining -= blocksize;
+ }
+ }
+ }
+
+ /* Encryption */
+ if (encryptp) {
+ /* Copy the partial block into tmp */
+ _krb5_evp_iov_cursor_fillbuf(&cursor, tmp, partiallen, NULL);
+
+ /* XOR the final partial block with ivec2 */
+ for (i = 0; i < partiallen; i++)
+ tmp[i] = tmp[i] ^ ivec2[i];
+ for (; i < blocksize; i++)
+ tmp[i] = 0 ^ ivec2[i]; /* XOR 0s if partial block exhausted */
+
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1);
+ EVP_Cipher(c, tmp, tmp, blocksize);
+
+ _krb5_evp_iov_cursor_fillvec(&lastpos, tmp, blocksize);
+ _krb5_evp_iov_cursor_fillvec(&cursor, ivec2, partiallen);
+
+ if (ivec)
+ memcpy(ivec, tmp, blocksize);
+
+ return 0;
+ }
+
+ /* Decryption */
+
+ /* Make a copy of the 2nd last full ciphertext block in ivec2 before
+ * decrypting it. If no such block exists, use ivec or zero_ivec */
+ if (length <= blocksize * 2) {
+ if (ivec)
+ memcpy(ivec2, ivec, blocksize);
+ else
+ memcpy(ivec2, zero_ivec, blocksize);
+ } else {
+ _krb5_evp_iov_cursor_fillbuf(&cursor, ivec2, blocksize, NULL);
+ EVP_Cipher(c, tmp, ivec2, blocksize);
+ _krb5_evp_iov_cursor_fillvec(&cursor, tmp, blocksize);
+ }
+
+ lastpos = cursor; /* Remember where the last block is */
+ _krb5_evp_iov_cursor_fillbuf(&cursor, tmp, blocksize, &cursor);
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1);
+ EVP_Cipher(c, tmp2, tmp, blocksize); /* tmp eventually becomes output ivec */
+
+ _krb5_evp_iov_cursor_fillbuf(&cursor, tmp3, partiallen, NULL);
+
+ memcpy(tmp3 + partiallen, tmp2 + partiallen, blocksize - partiallen); /* xor 0 */
+ for (i = 0; i < partiallen; i++)
+ tmp2[i] = tmp2[i] ^ tmp3[i];
+
+ _krb5_evp_iov_cursor_fillvec(&cursor, tmp2, partiallen);
+
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1);
+ EVP_Cipher(c, tmp3, tmp3, blocksize);
+
+ for (i = 0; i < blocksize; i++)
+ tmp3[i] ^= ivec2[i];
+
+ _krb5_evp_iov_cursor_fillvec(&lastpos, tmp3, blocksize);
+
+ if (ivec)
+ memcpy(ivec, tmp, blocksize);
+
+ return 0;
+}
+
+krb5_error_code
+_krb5_evp_encrypt_cts(krb5_context context,
+ struct _krb5_key_data *key,
+ void *data,
+ size_t len,
+ krb5_boolean encryptp,
+ int usage,
+ void *ivec)
+{
+ size_t i, blocksize;
+ struct _krb5_evp_schedule *ctx = key->schedule->data;
+ unsigned char tmp[EVP_MAX_BLOCK_LENGTH], ivec2[EVP_MAX_BLOCK_LENGTH];
+ EVP_CIPHER_CTX *c;
+ unsigned char *p;
+
+ c = encryptp ? &ctx->ectx : &ctx->dctx;
+
+ blocksize = EVP_CIPHER_CTX_block_size(c);
+
+ if (len < blocksize) {
+ krb5_set_error_message(context, EINVAL,
+ "message block too short");
+ return EINVAL;
+ } else if (len == blocksize) {
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1);
+ EVP_Cipher(c, data, data, len);
+ return 0;
+ }
+
+ if (ivec)
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, ivec, -1);
+ else
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1);
+
+ if (encryptp) {
+
+ p = data;
+ i = ((len - 1) / blocksize) * blocksize;
+ EVP_Cipher(c, p, p, i);
+ p += i - blocksize;
+ len -= i;
+ memcpy(ivec2, p, blocksize);
+
+ for (i = 0; i < len; i++)
+ tmp[i] = p[i + blocksize] ^ ivec2[i];
+ for (; i < blocksize; i++)
+ tmp[i] = 0 ^ ivec2[i];
+
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1);
+ EVP_Cipher(c, p, tmp, blocksize);
+
+ memcpy(p + blocksize, ivec2, len);
+ if (ivec)
+ memcpy(ivec, p, blocksize);
+ } else {
+ unsigned char tmp2[EVP_MAX_BLOCK_LENGTH], tmp3[EVP_MAX_BLOCK_LENGTH];
+
+ p = data;
+ if (len > blocksize * 2) {
+ /* remove last two blocks and round up, decrypt this with cbc, then do cts dance */
+ i = ((((len - blocksize * 2) + blocksize - 1) / blocksize) * blocksize);
+ memcpy(ivec2, p + i - blocksize, blocksize);
+ EVP_Cipher(c, p, p, i);
+ p += i;
+ len -= i + blocksize;
+ } else {
+ if (ivec)
+ memcpy(ivec2, ivec, blocksize);
+ else
+ memcpy(ivec2, zero_ivec, blocksize);
+ len -= blocksize;
+ }
+
+ memcpy(tmp, p, blocksize);
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1);
+ EVP_Cipher(c, tmp2, p, blocksize);
+
+ memcpy(tmp3, p + blocksize, len);
+ memcpy(tmp3 + len, tmp2 + len, blocksize - len); /* xor 0 */
+
+ for (i = 0; i < len; i++)
+ p[i + blocksize] = tmp2[i] ^ tmp3[i];
+
+ EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1);
+ EVP_Cipher(c, p, tmp3, blocksize);
+
+ for (i = 0; i < blocksize; i++)
+ p[i] ^= ivec2[i];
+ if (ivec)
+ memcpy(ivec, tmp, blocksize);
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/crypto-null.c b/third_party/heimdal/lib/krb5/crypto-null.c
new file mode 100644
index 0000000..a62a57f
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crypto-null.c
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#ifndef HEIMDAL_SMALLER
+#define DES3_OLD_ENCTYPE 1
+#endif
+
+static struct _krb5_key_type keytype_null = {
+ KRB5_ENCTYPE_NULL,
+ "null",
+ 0,
+ 0,
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+static krb5_error_code
+NONE_checksum(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *C)
+{
+ return 0;
+}
+
+struct _krb5_checksum_type _krb5_checksum_none = {
+ CKSUMTYPE_NONE,
+ "none",
+ 1,
+ 0,
+ 0,
+ NONE_checksum,
+ NULL
+};
+
+static krb5_error_code
+NULL_encrypt(krb5_context context,
+ struct _krb5_key_data *key,
+ void *data,
+ size_t len,
+ krb5_boolean encryptp,
+ int usage,
+ void *ivec)
+{
+ return 0;
+}
+
+struct _krb5_encryption_type _krb5_enctype_null = {
+ ETYPE_NULL,
+ "null",
+ NULL,
+ 1,
+ 1,
+ 0,
+ &keytype_null,
+ &_krb5_checksum_none,
+ NULL,
+ F_DISABLED | F_OLD,
+ NULL_encrypt,
+ NULL,
+ 0,
+ NULL
+};
diff --git a/third_party/heimdal/lib/krb5/crypto-pk.c b/third_party/heimdal/lib/krb5/crypto-pk.c
new file mode 100644
index 0000000..24a07cd
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crypto-pk.c
@@ -0,0 +1,295 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#include <pkinit_asn1.h>
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_pk_octetstring2key(krb5_context context,
+ krb5_enctype type,
+ const void *dhdata,
+ size_t dhsize,
+ const heim_octet_string *c_n,
+ const heim_octet_string *k_n,
+ krb5_keyblock *key)
+{
+ struct _krb5_encryption_type *et = _krb5_find_enctype(type);
+ krb5_error_code ret;
+ size_t keylen, offset;
+ void *keydata;
+ unsigned char counter;
+ unsigned char shaoutput[SHA_DIGEST_LENGTH];
+ EVP_MD_CTX *m;
+
+ if(et == NULL) {
+ krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("encryption type %d not supported", ""),
+ type);
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ keylen = (et->keytype->bits + 7) / 8;
+
+ keydata = malloc(keylen);
+ if (keydata == NULL)
+ return krb5_enomem(context);
+
+ m = EVP_MD_CTX_create();
+ if (m == NULL) {
+ free(keydata);
+ return krb5_enomem(context);
+ }
+
+ counter = 0;
+ offset = 0;
+ do {
+
+ EVP_DigestInit_ex(m, EVP_sha1(), NULL);
+ EVP_DigestUpdate(m, &counter, 1);
+ EVP_DigestUpdate(m, dhdata, dhsize);
+
+ if (c_n)
+ EVP_DigestUpdate(m, c_n->data, c_n->length);
+ if (k_n)
+ EVP_DigestUpdate(m, k_n->data, k_n->length);
+
+ EVP_DigestFinal_ex(m, shaoutput, NULL);
+
+ memcpy((unsigned char *)keydata + offset,
+ shaoutput,
+ min(keylen - offset, sizeof(shaoutput)));
+
+ offset += sizeof(shaoutput);
+ counter++;
+ } while(offset < keylen);
+ memset_s(shaoutput, sizeof(shaoutput), 0, sizeof(shaoutput));
+
+ EVP_MD_CTX_destroy(m);
+
+ ret = krb5_random_to_key(context, type, keydata, keylen, key);
+ memset_s(keydata, sizeof(keylen), 0, sizeof(keylen));
+ free(keydata);
+ return ret;
+}
+
+static krb5_error_code
+encode_uvinfo(krb5_context context, krb5_const_principal p, krb5_data *data)
+{
+ KRB5PrincipalName pn;
+ krb5_error_code ret;
+ size_t size = 0;
+
+ pn.principalName = p->name;
+ pn.realm = p->realm;
+
+ ASN1_MALLOC_ENCODE(KRB5PrincipalName, data->data, data->length,
+ &pn, &size, ret);
+ if (ret) {
+ krb5_data_zero(data);
+ krb5_set_error_message(context, ret,
+ N_("Failed to encode KRB5PrincipalName", ""));
+ return ret;
+ }
+ if (data->length != size)
+ krb5_abortx(context, "asn1 compiler internal error");
+ return 0;
+}
+
+static krb5_error_code
+encode_otherinfo(krb5_context context,
+ const AlgorithmIdentifier *ai,
+ krb5_const_principal client,
+ krb5_const_principal server,
+ krb5_enctype enctype,
+ const krb5_data *as_req,
+ const krb5_data *pk_as_rep,
+ const Ticket *ticket,
+ krb5_data *other)
+{
+ PkinitSP80056AOtherInfo otherinfo;
+ PkinitSuppPubInfo pubinfo;
+ krb5_error_code ret;
+ krb5_data pub;
+ size_t size = 0;
+
+ krb5_data_zero(other);
+ memset(&otherinfo, 0, sizeof(otherinfo));
+ memset(&pubinfo, 0, sizeof(pubinfo));
+
+ pubinfo.enctype = enctype;
+ pubinfo.as_REQ = *as_req;
+ pubinfo.pk_as_rep = *pk_as_rep;
+ pubinfo.ticket = *ticket;
+ ASN1_MALLOC_ENCODE(PkinitSuppPubInfo, pub.data, pub.length,
+ &pubinfo, &size, ret);
+ if (ret) {
+ krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+ return ret;
+ }
+ if (pub.length != size)
+ krb5_abortx(context, "asn1 compiler internal error");
+
+ ret = encode_uvinfo(context, client, &otherinfo.partyUInfo);
+ if (ret) {
+ free(pub.data);
+ return ret;
+ }
+ ret = encode_uvinfo(context, server, &otherinfo.partyVInfo);
+ if (ret) {
+ free(otherinfo.partyUInfo.data);
+ free(pub.data);
+ return ret;
+ }
+
+ otherinfo.algorithmID = *ai;
+ otherinfo.suppPubInfo = &pub;
+
+ ASN1_MALLOC_ENCODE(PkinitSP80056AOtherInfo, other->data, other->length,
+ &otherinfo, &size, ret);
+ free(otherinfo.partyUInfo.data);
+ free(otherinfo.partyVInfo.data);
+ free(pub.data);
+ if (ret) {
+ krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+ return ret;
+ }
+ if (other->length != size)
+ krb5_abortx(context, "asn1 compiler internal error");
+
+ return 0;
+}
+
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_pk_kdf(krb5_context context,
+ const struct AlgorithmIdentifier *ai,
+ const void *dhdata,
+ size_t dhsize,
+ krb5_const_principal client,
+ krb5_const_principal server,
+ krb5_enctype enctype,
+ const krb5_data *as_req,
+ const krb5_data *pk_as_rep,
+ const Ticket *ticket,
+ krb5_keyblock *key)
+{
+ struct _krb5_encryption_type *et;
+ krb5_error_code ret;
+ krb5_data other;
+ size_t keylen, offset;
+ uint32_t counter;
+ unsigned char *keydata;
+ unsigned char shaoutput[SHA512_DIGEST_LENGTH];
+ const EVP_MD *md;
+ EVP_MD_CTX *m;
+
+ if (der_heim_oid_cmp(&asn1_oid_id_pkinit_kdf_ah_sha1, &ai->algorithm) == 0) {
+ md = EVP_sha1();
+ } else if (der_heim_oid_cmp(&asn1_oid_id_pkinit_kdf_ah_sha256, &ai->algorithm) == 0) {
+ md = EVP_sha256();
+ } else if (der_heim_oid_cmp(&asn1_oid_id_pkinit_kdf_ah_sha512, &ai->algorithm) == 0) {
+ md = EVP_sha512();
+ } else {
+ krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("KDF not supported", ""));
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ if (ai->parameters != NULL &&
+ (ai->parameters->length != 2 ||
+ memcmp(ai->parameters->data, "\x05\x00", 2) != 0))
+ {
+ krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("kdf params not NULL or the NULL-type",
+ ""));
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+
+ et = _krb5_find_enctype(enctype);
+ if(et == NULL) {
+ krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("encryption type %d not supported", ""),
+ enctype);
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ keylen = (et->keytype->bits + 7) / 8;
+
+ keydata = malloc(keylen);
+ if (keydata == NULL)
+ return krb5_enomem(context);
+
+ ret = encode_otherinfo(context, ai, client, server,
+ enctype, as_req, pk_as_rep, ticket, &other);
+ if (ret) {
+ free(keydata);
+ return ret;
+ }
+
+ m = EVP_MD_CTX_create();
+ if (m == NULL) {
+ free(keydata);
+ free(other.data);
+ return krb5_enomem(context);
+ }
+
+ offset = 0;
+ counter = 1;
+ do {
+ unsigned char cdata[4];
+
+ EVP_DigestInit_ex(m, md, NULL);
+ _krb5_put_int(cdata, counter, 4);
+ EVP_DigestUpdate(m, cdata, 4);
+ EVP_DigestUpdate(m, dhdata, dhsize);
+ EVP_DigestUpdate(m, other.data, other.length);
+
+ EVP_DigestFinal_ex(m, shaoutput, NULL);
+
+ memcpy((unsigned char *)keydata + offset,
+ shaoutput,
+ min(keylen - offset, EVP_MD_CTX_size(m)));
+
+ offset += EVP_MD_CTX_size(m);
+ counter++;
+ } while(offset < keylen);
+ memset_s(shaoutput, sizeof(shaoutput), 0, sizeof(shaoutput));
+
+ EVP_MD_CTX_destroy(m);
+ free(other.data);
+
+ ret = krb5_random_to_key(context, enctype, keydata, keylen, key);
+ memset_s(keydata, sizeof(keylen), 0, sizeof(keylen));
+ free(keydata);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/crypto-rand.c b/third_party/heimdal/lib/krb5/crypto-rand.c
new file mode 100644
index 0000000..7b126c6
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crypto-rand.c
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#undef HEIMDAL_WARN_UNUSED_RESULT_ATTRIBUTE
+#define HEIMDAL_WARN_UNUSED_RESULT_ATTRIBUTE
+
+#define ENTROPY_NEEDED 128
+
+static HEIMDAL_MUTEX crypto_mutex = HEIMDAL_MUTEX_INITIALIZER;
+
+static int
+seed_something(void)
+{
+#ifndef NO_RANDFILE
+ char buf[1024], seedfile[256];
+
+ /* If there is a seed file, load it. But such a file cannot be trusted,
+ so use 0 for the entropy estimate */
+ if (RAND_file_name(seedfile, sizeof(seedfile))) {
+ int fd;
+ fd = open(seedfile, O_RDONLY | O_BINARY | O_CLOEXEC);
+ if (fd >= 0) {
+ ssize_t ret;
+ rk_cloexec(fd);
+ ret = read(fd, buf, sizeof(buf));
+ if (ret > 0)
+ RAND_add(buf, ret, 0.0);
+ close(fd);
+ } else
+ seedfile[0] = '\0';
+ } else
+ seedfile[0] = '\0';
+#endif
+
+ /* Calling RAND_status() will try to use /dev/urandom if it exists so
+ we do not have to deal with it. */
+ if (RAND_status() != 1) {
+ /* TODO: Once a Windows CryptoAPI RAND method is defined, we
+ can use that and failover to another method. */
+ }
+
+ if (RAND_status() == 1) {
+#ifndef NO_RANDFILE
+ /* Update the seed file */
+ if (seedfile[0])
+ RAND_write_file(seedfile);
+#endif
+
+ return 0;
+ } else
+ return -1;
+}
+
+/**
+ * Fill buffer buf with len bytes of PRNG randomness that is ok to use
+ * for key generation, padding and public diclosing the randomness w/o
+ * disclosing the randomness source.
+ *
+ * This function can fail, and callers must check the return value.
+ *
+ * @param buf a buffer to fill with randomness
+ * @param len length of memory that buf points to.
+ *
+ * @return return 0 on success or HEIM_ERR_RANDOM_OFFLINE if the
+ * funcation failed to initialize the randomness source.
+ *
+ * @ingroup krb5_crypto
+ */
+
+HEIMDAL_WARN_UNUSED_RESULT_ATTRIBUTE
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_generate_random(void *buf, size_t len)
+{
+ static int rng_initialized = 0;
+ int ret;
+
+ HEIMDAL_MUTEX_lock(&crypto_mutex);
+ if (!rng_initialized) {
+ if (seed_something()) {
+ HEIMDAL_MUTEX_unlock(&crypto_mutex);
+ return HEIM_ERR_RANDOM_OFFLINE;
+ }
+ rng_initialized = 1;
+ }
+ if (RAND_bytes(buf, len) <= 0)
+ ret = HEIM_ERR_RANDOM_OFFLINE;
+ else
+ ret = 0;
+ HEIMDAL_MUTEX_unlock(&crypto_mutex);
+
+ return ret;
+}
+
+/**
+ * Fill buffer buf with len bytes of PRNG randomness that is ok to use
+ * for key generation, padding and public diclosing the randomness w/o
+ * disclosing the randomness source.
+ *
+ * This function can NOT fail, instead it will abort() and program will crash.
+ *
+ * If this function is called after a successful krb5_init_context(),
+ * the chance of it failing is low due to that krb5_init_context()
+ * pulls out some random, and quite commonly the randomness sources
+ * will not fail once it have started to produce good output,
+ * /dev/urandom behavies that way.
+ *
+ * @param buf a buffer to fill with randomness
+ * @param len length of memory that buf points to.
+ *
+ * @ingroup krb5_crypto
+ */
+
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_generate_random_block(void *buf, size_t len)
+{
+ int ret = krb5_generate_random(buf, len);
+ if (ret)
+ krb5_abortx(NULL, "Failed to generate random block");
+}
diff --git a/third_party/heimdal/lib/krb5/crypto-stubs.c b/third_party/heimdal/lib/krb5/crypto-stubs.c
new file mode 100644
index 0000000..5251f88
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crypto-stubs.c
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <krb5_locl.h>
+
+/* These are stub functions for the standalone RFC3961 crypto library */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_context(krb5_context *context)
+{
+ krb5_context p;
+
+ *context = NULL;
+
+ /* should have a run_once */
+ bindtextdomain(HEIMDAL_TEXTDOMAIN, HEIMDAL_LOCALEDIR);
+
+ p = calloc(1, sizeof(*p));
+ if(!p)
+ return ENOMEM;
+
+ *context = p;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_context(krb5_context context)
+{
+ krb5_clear_error_message(context);
+
+ if (context->flags & KRB5_CTX_F_SOCKETS_INITIALIZED) {
+ rk_SOCK_EXIT();
+ }
+
+ memset(context, 0, sizeof(*context));
+ free(context);
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+_krb5_homedir_access(krb5_context context) {
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_log(krb5_context context,
+ krb5_log_facility *fac,
+ int level,
+ const char *fmt,
+ ...)
+{
+ return 0;
+}
+
+void KRB5_LIB_FUNCTION
+_krb5_debug(krb5_context context,
+ int level,
+ const char *fmt,
+ ...)
+{
+}
+
+
+/* This function is currently just used to get the location of the EGD
+ * socket. If we're not using an EGD, then we can just return NULL */
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_config_get_string (krb5_context context,
+ const krb5_config_section *c,
+ ...)
+{
+ return NULL;
+}
diff --git a/third_party/heimdal/lib/krb5/crypto.c b/third_party/heimdal/lib/krb5/crypto.c
new file mode 100644
index 0000000..2fb4f06
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crypto.c
@@ -0,0 +1,3264 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+struct _krb5_key_usage {
+ unsigned usage;
+ struct _krb5_key_data key;
+};
+
+
+#ifndef HEIMDAL_SMALLER
+#define DES3_OLD_ENCTYPE 1
+#endif
+
+static krb5_error_code _get_derived_key(krb5_context, krb5_crypto,
+ unsigned, struct _krb5_key_data**);
+static struct _krb5_key_data *_new_derived_key(krb5_crypto crypto, unsigned usage);
+
+static void free_key_schedule(krb5_context,
+ struct _krb5_key_data *,
+ struct _krb5_encryption_type *);
+
+/*
+ * Converts etype to a user readable string and sets as a side effect
+ * the krb5_error_message containing this string. Returns
+ * KRB5_PROG_ETYPE_NOSUPP in not the conversion of the etype failed in
+ * which case the error code of the etype convesion is returned.
+ */
+
+static krb5_error_code
+unsupported_enctype(krb5_context context, krb5_enctype etype)
+{
+ krb5_error_code ret;
+ char *name;
+
+ ret = krb5_enctype_to_string(context, etype, &name);
+ if (ret)
+ return ret;
+
+ krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("Encryption type %s not supported", ""),
+ name);
+ free(name);
+ return KRB5_PROG_ETYPE_NOSUPP;
+}
+
+/*
+ *
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_enctype_keysize(krb5_context context,
+ krb5_enctype type,
+ size_t *keysize)
+{
+ struct _krb5_encryption_type *et = _krb5_find_enctype(type);
+ if(et == NULL) {
+ return unsupported_enctype (context, type);
+ }
+ *keysize = et->keytype->size;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_enctype_keybits(krb5_context context,
+ krb5_enctype type,
+ size_t *keybits)
+{
+ struct _krb5_encryption_type *et = _krb5_find_enctype(type);
+ if(et == NULL) {
+ return unsupported_enctype (context, type);
+ }
+ *keybits = et->keytype->bits;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_generate_random_keyblock(krb5_context context,
+ krb5_enctype type,
+ krb5_keyblock *key)
+{
+ krb5_error_code ret;
+ struct _krb5_encryption_type *et = _krb5_find_enctype(type);
+ if(et == NULL) {
+ return unsupported_enctype (context, type);
+ }
+ ret = krb5_data_alloc(&key->keyvalue, et->keytype->size);
+ if(ret)
+ return ret;
+ key->keytype = type;
+ if(et->keytype->random_key)
+ (*et->keytype->random_key)(context, key);
+ else
+ krb5_generate_random_block(key->keyvalue.data,
+ key->keyvalue.length);
+ return 0;
+}
+
+static krb5_error_code
+_key_schedule(krb5_context context,
+ struct _krb5_key_data *key)
+{
+ krb5_error_code ret;
+ struct _krb5_encryption_type *et;
+ struct _krb5_key_type *kt;
+
+ if (key->schedule != NULL)
+ return 0;
+
+ et = _krb5_find_enctype(key->key->keytype);
+
+ if (et == NULL) {
+ return unsupported_enctype (context,
+ key->key->keytype);
+ }
+
+ kt = et->keytype;
+
+ if(kt->schedule == NULL)
+ return 0;
+ ALLOC(key->schedule, 1);
+ if (key->schedule == NULL)
+ return krb5_enomem(context);
+ ret = krb5_data_alloc(key->schedule, kt->schedule_size);
+ if(ret) {
+ free(key->schedule);
+ key->schedule = NULL;
+ return ret;
+ }
+ (*kt->schedule)(context, kt, key);
+ return 0;
+}
+
+/************************************************************
+ * *
+ ************************************************************/
+
+static krb5_error_code
+EVP_unkeyed_checksum(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *C,
+ const EVP_MD *md)
+{
+ if (_krb5_evp_digest_iov(crypto,
+ iov, niov,
+ C->checksum.data, NULL,
+ md, NULL) != 1)
+ krb5_abortx(context, "unkeyed checksum failed");
+
+ return 0;
+}
+
+#define EVP_SHA_CHECKSUM(name) \
+ \
+ static krb5_error_code \
+ SHA ## name ##_checksum(krb5_context context, \
+ krb5_crypto crypto, \
+ struct _krb5_key_data *key, \
+ unsigned usage, \
+ const struct krb5_crypto_iov *iov, \
+ int niov, \
+ Checksum *C) \
+ { \
+ return EVP_unkeyed_checksum(context, crypto, key, \
+ usage, iov, niov, \
+ C, EVP_sha##name()); \
+ }
+
+EVP_SHA_CHECKSUM(1)
+EVP_SHA_CHECKSUM(256)
+EVP_SHA_CHECKSUM(384)
+EVP_SHA_CHECKSUM(512)
+
+/* HMAC according to RFC2104 */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_internal_hmac_iov(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_checksum_type *cm,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ struct _krb5_key_data *keyblock,
+ Checksum *result)
+{
+ unsigned char *ipad, *opad;
+ unsigned char *key;
+ struct krb5_crypto_iov *working;
+ size_t key_len;
+ size_t i;
+
+ ipad = malloc(cm->blocksize);
+ if (ipad == NULL)
+ return ENOMEM;
+
+ opad = malloc(cm->blocksize + cm->checksumsize);
+ if (opad == NULL) {
+ free(ipad);
+ return ENOMEM;
+ }
+
+ working = calloc(niov + 1, sizeof(struct krb5_crypto_iov));
+ if (working == NULL) {
+ free(ipad);
+ free(opad);
+ return ENOMEM;
+ }
+
+ memset(ipad, 0x36, cm->blocksize);
+ memset(opad, 0x5c, cm->blocksize);
+
+ if(keyblock->key->keyvalue.length > cm->blocksize){
+ working[0].data = keyblock->key->keyvalue;
+ working[0].flags = KRB5_CRYPTO_TYPE_DATA;
+ (*cm->checksum)(context,
+ crypto,
+ keyblock,
+ usage,
+ working,
+ 1,
+ result);
+ key = result->checksum.data;
+ key_len = result->checksum.length;
+ } else {
+ key = keyblock->key->keyvalue.data;
+ key_len = keyblock->key->keyvalue.length;
+ }
+ for(i = 0; i < key_len; i++){
+ ipad[i] ^= key[i];
+ opad[i] ^= key[i];
+ }
+
+ working[0].data.data = ipad;
+ working[0].data.length = cm->blocksize;
+ working[0].flags = KRB5_CRYPTO_TYPE_DATA;
+ for (i = 0; i < niov; i++)
+ working[i + 1] = iov[i];
+
+ (*cm->checksum)(context, crypto, keyblock, usage, working, niov + 1, result);
+ memcpy(opad + cm->blocksize, result->checksum.data,
+ result->checksum.length);
+
+ working[0].data.data = opad;
+ working[0].data.length = cm->blocksize + cm->checksumsize;
+ working[0].flags = KRB5_CRYPTO_TYPE_DATA;
+ (*cm->checksum)(context, crypto, keyblock, usage, working, 1, result);
+ memset(ipad, 0, cm->blocksize);
+ free(ipad);
+ memset(opad, 0, cm->blocksize + cm->checksumsize);
+ free(opad);
+ free(working);
+
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_internal_hmac(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_checksum_type *cm,
+ const void *data,
+ size_t len,
+ unsigned usage,
+ struct _krb5_key_data *keyblock,
+ Checksum *result)
+{
+ struct krb5_crypto_iov iov[1];
+
+ iov[0].data.data = (void *) data;
+ iov[0].data.length = len;
+ iov[0].flags = KRB5_CRYPTO_TYPE_DATA;
+ return _krb5_internal_hmac_iov(context, crypto, cm, usage, iov, 1,
+ keyblock, result);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_hmac(krb5_context context,
+ krb5_cksumtype cktype,
+ const void *data,
+ size_t len,
+ unsigned usage,
+ krb5_keyblock *key,
+ Checksum *result)
+{
+ struct _krb5_checksum_type *c = _krb5_find_checksum(cktype);
+ struct _krb5_key_data kd;
+
+ krb5_error_code ret;
+
+ if (c == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+ N_("checksum type %d not supported", ""),
+ cktype);
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+ }
+
+ kd.key = key;
+ kd.schedule = NULL;
+
+ ret = _krb5_internal_hmac(context, NULL, c, data, len, usage, &kd, result);
+
+ if (kd.schedule)
+ krb5_free_data(context, kd.schedule);
+
+ return ret;
+}
+
+krb5_error_code
+_krb5_SP_HMAC_SHA1_checksum(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *result)
+{
+ krb5_error_code ret;
+ unsigned char hmac[EVP_MAX_MD_SIZE];
+ unsigned int hmaclen = sizeof(hmac);
+
+ ret = _krb5_evp_hmac_iov(context, crypto, key, iov, niov, hmac, &hmaclen,
+ EVP_sha1(), NULL);
+ if (ret)
+ return ret;
+
+ heim_assert(result->checksum.length <= hmaclen,
+ "SHA1 checksum too short");
+ memcpy(result->checksum.data, hmac, result->checksum.length);
+
+ return 0;
+}
+
+krb5_error_code
+_krb5_SP_HMAC_SHA1_verify(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov,
+ int niov,
+ Checksum *verify)
+{
+ krb5_error_code ret;
+ unsigned char hmac[EVP_MAX_MD_SIZE];
+ unsigned int hmaclen = sizeof(hmac);
+ krb5_data data;
+
+ ret = _krb5_evp_hmac_iov(context, crypto, key, iov, niov, hmac, &hmaclen,
+ EVP_sha1(), NULL);
+ if (ret)
+ return ret;
+
+ data.data = hmac;
+ data.length = min(hmaclen, verify->checksum.length);
+
+ if(krb5_data_ct_cmp(&data, &verify->checksum) != 0)
+ return KRB5KRB_AP_ERR_BAD_INTEGRITY;
+
+ return 0;
+}
+
+#define SHA_CHECKSUM(name, blocksize, outputsize) \
+ struct _krb5_checksum_type _krb5_checksum_sha##name = { \
+ CKSUMTYPE_SHA##name, \
+ "sha" #name, \
+ blocksize, \
+ outputsize, \
+ F_CPROOF, \
+ SHA##name##_checksum, \
+ NULL \
+ };
+
+SHA_CHECKSUM(1, 64, 20);
+SHA_CHECKSUM(256, 64, 32);
+SHA_CHECKSUM(384, 128, 48);
+SHA_CHECKSUM(512, 128, 64);
+
+KRB5_LIB_FUNCTION struct _krb5_checksum_type * KRB5_LIB_CALL
+_krb5_find_checksum(krb5_cksumtype type)
+{
+ int i;
+ for(i = 0; i < _krb5_num_checksums; i++)
+ if(_krb5_checksum_types[i]->type == type)
+ return _krb5_checksum_types[i];
+ return NULL;
+}
+
+static krb5_error_code
+get_checksum_key(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage, /* not krb5_key_usage */
+ struct _krb5_checksum_type *ct,
+ struct _krb5_key_data **key)
+{
+ krb5_error_code ret = 0;
+ struct _krb5_checksum_type *kct = NULL;
+
+ if (crypto == NULL) {
+ krb5_set_error_message(context, KRB5_BAD_ENCTYPE,
+ N_("Checksum type %s is keyed but no "
+ "crypto context (key) was passed in", ""),
+ ct->name);
+ return KRB5_BAD_ENCTYPE;
+ }
+ kct = crypto->et->keyed_checksum;
+ if (kct == NULL || kct->type != ct->type) {
+ krb5_set_error_message(context, KRB5_BAD_ENCTYPE,
+ N_("Checksum type %s is keyed, but "
+ "the key type %s passed didnt have that checksum "
+ "type as the keyed type", ""),
+ ct->name, crypto->et->name);
+ return KRB5_BAD_ENCTYPE;
+ }
+
+ if(ct->flags & F_DERIVED)
+ ret = _get_derived_key(context, crypto, usage, key);
+ else if(ct->flags & F_VARIANT) {
+ size_t i;
+
+ *key = _new_derived_key(crypto, 0xff/* KRB5_KU_RFC1510_VARIANT */);
+ if (*key == NULL)
+ return krb5_enomem(context);
+ ret = krb5_copy_keyblock(context, crypto->key.key, &(*key)->key);
+ if(ret)
+ return ret;
+ for(i = 0; i < (*key)->key->keyvalue.length; i++)
+ ((unsigned char*)(*key)->key->keyvalue.data)[i] ^= 0xF0;
+ } else {
+ *key = &crypto->key;
+ }
+ if(ret == 0)
+ ret = _key_schedule(context, *key);
+ return ret;
+}
+
+static krb5_error_code
+create_checksum_iov(krb5_context context,
+ struct _krb5_checksum_type *ct,
+ krb5_crypto crypto,
+ unsigned usage,
+ struct krb5_crypto_iov *iov,
+ int niov,
+ krb5_flags flags,
+ Checksum *result)
+{
+ krb5_error_code ret;
+ struct _krb5_key_data *dkey;
+
+ if (ct->flags & F_DISABLED) {
+ krb5_clear_error_message (context);
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+ }
+ if (ct->flags & F_KEYED) {
+ ret = get_checksum_key(context, crypto, usage, ct, &dkey);
+ if (ret)
+ return ret;
+ } else if ((flags & KRB5_CRYPTO_FLAG_ALLOW_UNKEYED_CHECKSUM) == 0) {
+ return EINVAL;
+ } else
+ dkey = NULL;
+
+ result->cksumtype = ct->type;
+
+ return (*ct->checksum)(context, crypto, dkey, usage, iov, niov, result);
+}
+
+static krb5_error_code
+create_checksum (krb5_context context,
+ struct _krb5_checksum_type *ct,
+ krb5_crypto crypto,
+ unsigned usage,
+ void *data,
+ size_t len,
+ krb5_flags flags,
+ Checksum *result)
+{
+ int ret;
+ struct krb5_crypto_iov iov[1];
+
+ ret = krb5_data_alloc(&result->checksum, ct->checksumsize);
+ if (ret)
+ return ret;
+
+ iov[0].data.data = data;
+ iov[0].data.length = len;
+ iov[0].flags = KRB5_CRYPTO_TYPE_DATA;
+
+ return create_checksum_iov(context, ct, crypto, usage, iov, 1, flags, result);
+}
+
+static int
+arcfour_checksum_p(struct _krb5_checksum_type *ct, krb5_crypto crypto)
+{
+ return (ct->type == CKSUMTYPE_HMAC_MD5) &&
+ (crypto->key.key->keytype == KEYTYPE_ARCFOUR);
+}
+
+static inline krb5_flags
+crypto_flags(krb5_crypto crypto)
+{
+ /* If caller didn't specify a key, unkeyed checksums are the only option */
+ if (crypto == NULL)
+ return KRB5_CRYPTO_FLAG_ALLOW_UNKEYED_CHECKSUM;
+ else
+ return crypto->flags;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_create_checksum(krb5_context context,
+ krb5_crypto crypto,
+ krb5_key_usage usage,
+ int type,
+ void *data,
+ size_t len,
+ Checksum *result)
+{
+ struct _krb5_checksum_type *ct = NULL;
+ unsigned keyusage;
+
+ /* type 0 -> pick from crypto */
+ if (type) {
+ ct = _krb5_find_checksum(type);
+ } else if (crypto) {
+ ct = crypto->et->keyed_checksum;
+ if (ct == NULL)
+ ct = crypto->et->checksum;
+ }
+
+ if(ct == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+ N_("checksum type %d not supported", ""),
+ type);
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+ }
+
+ if (arcfour_checksum_p(ct, crypto)) {
+ keyusage = usage;
+ _krb5_usage2arcfour(context, &keyusage);
+ } else
+ keyusage = CHECKSUM_USAGE(usage);
+
+ return create_checksum(context, ct, crypto, keyusage, data, len,
+ crypto_flags(crypto), result);
+}
+
+static krb5_error_code
+verify_checksum_iov(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage, /* not krb5_key_usage */
+ struct krb5_crypto_iov *iov,
+ int niov,
+ krb5_flags flags,
+ Checksum *cksum)
+{
+ krb5_error_code ret;
+ struct _krb5_key_data *dkey;
+ Checksum c;
+ struct _krb5_checksum_type *ct;
+
+ ct = _krb5_find_checksum(cksum->cksumtype);
+ if (ct == NULL || (ct->flags & F_DISABLED)) {
+ krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+ N_("checksum type %d not supported", ""),
+ cksum->cksumtype);
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+ }
+ if(ct->checksumsize != cksum->checksum.length) {
+ krb5_clear_error_message (context);
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_BAD_INTEGRITY,
+ N_("Decrypt integrity check failed for checksum type %s, "
+ "length was %u, expected %u", ""),
+ ct->name, (unsigned)cksum->checksum.length,
+ (unsigned)ct->checksumsize);
+
+ return KRB5KRB_AP_ERR_BAD_INTEGRITY; /* XXX */
+ }
+ if (ct->flags & F_KEYED) {
+ ret = get_checksum_key(context, crypto, usage, ct, &dkey);
+ if (ret)
+ return ret;
+ } else if ((flags & KRB5_CRYPTO_FLAG_ALLOW_UNKEYED_CHECKSUM) == 0) {
+ krb5_clear_error_message (context);
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_BAD_INTEGRITY,
+ N_("Unkeyed checksum type %s provided where keyed "
+ "checksum was expected", ""), ct->name);
+
+ return KRB5KRB_AP_ERR_INAPP_CKSUM;
+ } else
+ dkey = NULL;
+
+ /*
+ * If checksum have a verify function, lets use that instead of
+ * calling ->checksum and then compare result.
+ */
+
+ if(ct->verify) {
+ ret = (*ct->verify)(context, crypto, dkey, usage, iov, niov, cksum);
+ if (ret)
+ krb5_set_error_message(context, ret,
+ N_("Decrypt integrity check failed for checksum "
+ "type %s, key type %s", ""),
+ ct->name, (crypto != NULL)? crypto->et->name : "(none)");
+ return ret;
+ }
+
+ ret = krb5_data_alloc (&c.checksum, ct->checksumsize);
+ if (ret)
+ return ret;
+
+ ret = (*ct->checksum)(context, crypto, dkey, usage, iov, niov, &c);
+ if (ret) {
+ krb5_data_free(&c.checksum);
+ return ret;
+ }
+
+ if(krb5_data_ct_cmp(&c.checksum, &cksum->checksum) != 0) {
+ ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
+ krb5_set_error_message(context, ret,
+ N_("Decrypt integrity check failed for checksum "
+ "type %s, key type %s", ""),
+ ct->name, crypto ? crypto->et->name : "(unkeyed)");
+ } else {
+ ret = 0;
+ }
+ krb5_data_free (&c.checksum);
+ return ret;
+}
+
+static krb5_error_code
+verify_checksum(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage, /* not krb5_key_usage */
+ void *data,
+ size_t len,
+ krb5_flags flags,
+ Checksum *cksum)
+{
+ struct krb5_crypto_iov iov[1];
+
+ iov[0].data.data = data;
+ iov[0].data.length = len;
+ iov[0].flags = KRB5_CRYPTO_TYPE_DATA;
+
+ return verify_checksum_iov(context, crypto, usage, iov, 1, flags, cksum);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verify_checksum(krb5_context context,
+ krb5_crypto crypto,
+ krb5_key_usage usage,
+ void *data,
+ size_t len,
+ Checksum *cksum)
+{
+ struct _krb5_checksum_type *ct;
+ unsigned keyusage;
+
+ ct = _krb5_find_checksum(cksum->cksumtype);
+ if(ct == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+ N_("checksum type %d not supported", ""),
+ cksum->cksumtype);
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+ }
+
+ if (arcfour_checksum_p(ct, crypto)) {
+ keyusage = usage;
+ _krb5_usage2arcfour(context, &keyusage);
+ } else
+ keyusage = CHECKSUM_USAGE(usage);
+
+ return verify_checksum(context, crypto, keyusage,
+ data, len, crypto_flags(crypto), cksum);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_get_checksum_type(krb5_context context,
+ krb5_crypto crypto,
+ krb5_cksumtype *type)
+{
+ struct _krb5_checksum_type *ct = NULL;
+
+ if (crypto != NULL) {
+ ct = crypto->et->keyed_checksum;
+ if (ct == NULL)
+ ct = crypto->et->checksum;
+ }
+
+ if (ct == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+ N_("checksum type not found", ""));
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+ }
+
+ *type = ct->type;
+
+ return 0;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_checksumsize(krb5_context context,
+ krb5_cksumtype type,
+ size_t *size)
+{
+ struct _krb5_checksum_type *ct = _krb5_find_checksum(type);
+ if(ct == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+ N_("checksum type %d not supported", ""),
+ type);
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+ }
+ *size = ct->checksumsize;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_checksum_is_keyed(krb5_context context,
+ krb5_cksumtype type)
+{
+ struct _krb5_checksum_type *ct = _krb5_find_checksum(type);
+ if(ct == NULL) {
+ if (context)
+ krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+ N_("checksum type %d not supported", ""),
+ type);
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+ }
+ return ct->flags & F_KEYED;
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_checksum_is_collision_proof(krb5_context context,
+ krb5_cksumtype type)
+{
+ struct _krb5_checksum_type *ct = _krb5_find_checksum(type);
+ if(ct == NULL) {
+ if (context)
+ krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+ N_("checksum type %d not supported", ""),
+ type);
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+ }
+ return ct->flags & F_CPROOF;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_checksum_disable(krb5_context context,
+ krb5_cksumtype type)
+{
+ struct _krb5_checksum_type *ct = _krb5_find_checksum(type);
+ if(ct == NULL) {
+ if (context)
+ krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+ N_("checksum type %d not supported", ""),
+ type);
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+ }
+ ct->flags |= F_DISABLED;
+ return 0;
+}
+
+/************************************************************
+ * *
+ ************************************************************/
+
+KRB5_LIB_FUNCTION struct _krb5_encryption_type * KRB5_LIB_CALL
+_krb5_find_enctype(krb5_enctype type)
+{
+ int i;
+ for(i = 0; i < _krb5_num_etypes; i++)
+ if(_krb5_etypes[i]->type == type)
+ return _krb5_etypes[i];
+ return NULL;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_enctype_to_string(krb5_context context,
+ krb5_enctype etype,
+ char **string)
+{
+ struct _krb5_encryption_type *e;
+ e = _krb5_find_enctype(etype);
+ if(e == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("encryption type %d not supported", ""),
+ etype);
+ *string = NULL;
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ *string = strdup(e->name);
+ if (*string == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_string_to_enctype(krb5_context context,
+ const char *string,
+ krb5_enctype *etype)
+{
+ int i;
+ for(i = 0; i < _krb5_num_etypes; i++) {
+ if(strcasecmp(_krb5_etypes[i]->name, string) == 0){
+ *etype = _krb5_etypes[i]->type;
+ return 0;
+ }
+ if(_krb5_etypes[i]->alias != NULL &&
+ strcasecmp(_krb5_etypes[i]->alias, string) == 0){
+ *etype = _krb5_etypes[i]->type;
+ return 0;
+ }
+ }
+ krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("encryption type %s not supported", ""),
+ string);
+ return KRB5_PROG_ETYPE_NOSUPP;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_enctype_to_keytype(krb5_context context,
+ krb5_enctype etype,
+ krb5_keytype *keytype)
+{
+ struct _krb5_encryption_type *e = _krb5_find_enctype(etype);
+ if(e == NULL) {
+ return unsupported_enctype (context, etype);
+ }
+ *keytype = e->keytype->type; /* XXX */
+ return 0;
+}
+
+/**
+ * Check if a enctype is valid, return 0 if it is.
+ *
+ * @param context Kerberos context
+ * @param etype enctype to check if its valid or not
+ *
+ * @return Return an error code for an failure or 0 on success (enctype valid).
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_enctype_valid(krb5_context context,
+ krb5_enctype etype)
+{
+ struct _krb5_encryption_type *e = _krb5_find_enctype(etype);
+ if(e && (e->flags & F_DISABLED) == 0)
+ return 0;
+ if (context == NULL)
+ return KRB5_PROG_ETYPE_NOSUPP;
+ if(e == NULL) {
+ return unsupported_enctype (context, etype);
+ }
+ /* Must be (e->flags & F_DISABLED) */
+ krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("encryption type %s is disabled", ""),
+ e->name);
+ return KRB5_PROG_ETYPE_NOSUPP;
+}
+
+/**
+ * Return the coresponding encryption type for a checksum type.
+ *
+ * @param context Kerberos context
+ * @param ctype The checksum type to get the result enctype for
+ * @param etype The returned encryption, when the matching etype is
+ * not found, etype is set to ETYPE_NULL.
+ *
+ * @return Return an error code for an failure or 0 on success.
+ * @ingroup krb5_crypto
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cksumtype_to_enctype(krb5_context context,
+ krb5_cksumtype ctype,
+ krb5_enctype *etype)
+{
+ int i;
+
+ *etype = ETYPE_NULL;
+
+ for(i = 0; i < _krb5_num_etypes; i++) {
+ if(_krb5_etypes[i]->keyed_checksum &&
+ _krb5_etypes[i]->keyed_checksum->type == ctype)
+ {
+ *etype = _krb5_etypes[i]->type;
+ return 0;
+ }
+ }
+
+ krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+ N_("checksum type %d not supported", ""),
+ (int)ctype);
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cksumtype_valid(krb5_context context,
+ krb5_cksumtype ctype)
+{
+ struct _krb5_checksum_type *c = _krb5_find_checksum(ctype);
+ if (c == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+ N_("checksum type %d not supported", ""),
+ ctype);
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+ }
+ if (c->flags & F_DISABLED) {
+ krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+ N_("checksum type %s is disabled", ""),
+ c->name);
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+ }
+ return 0;
+}
+
+static krb5_boolean
+derived_crypto(krb5_context context,
+ krb5_crypto crypto)
+{
+ return (crypto->et->flags & F_DERIVED) != 0;
+}
+
+#define CHECKSUMSIZE(C) ((C)->checksumsize)
+#define CHECKSUMTYPE(C) ((C)->type)
+
+static krb5_error_code
+encrypt_internal_derived(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ const void *data,
+ size_t len,
+ krb5_data *result,
+ void *ivec)
+{
+ size_t sz, block_sz, checksum_sz, total_sz;
+ Checksum cksum;
+ unsigned char *p, *q;
+ krb5_error_code ret;
+ struct _krb5_key_data *dkey;
+ const struct _krb5_encryption_type *et = crypto->et;
+
+ checksum_sz = CHECKSUMSIZE(et->keyed_checksum);
+
+ sz = et->confoundersize + len;
+ block_sz = (sz + et->padsize - 1) &~ (et->padsize - 1); /* pad */
+ total_sz = block_sz + checksum_sz;
+ p = calloc(1, total_sz);
+ if (p == NULL)
+ return krb5_enomem(context);
+
+ q = p;
+ krb5_generate_random_block(q, et->confoundersize); /* XXX */
+ q += et->confoundersize;
+ memcpy(q, data, len);
+
+ ret = create_checksum(context,
+ et->keyed_checksum,
+ crypto,
+ INTEGRITY_USAGE(usage),
+ p,
+ block_sz,
+ 0,
+ &cksum);
+ if(ret == 0 && cksum.checksum.length != checksum_sz) {
+ free_Checksum (&cksum);
+ krb5_clear_error_message (context);
+ ret = KRB5_CRYPTO_INTERNAL;
+ }
+ if(ret)
+ goto fail;
+ memcpy(p + block_sz, cksum.checksum.data, cksum.checksum.length);
+ free_Checksum (&cksum);
+ ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey);
+ if(ret)
+ goto fail;
+ ret = _key_schedule(context, dkey);
+ if(ret)
+ goto fail;
+ ret = (*et->encrypt)(context, dkey, p, block_sz, 1, usage, ivec);
+ if (ret)
+ goto fail;
+ result->data = p;
+ result->length = total_sz;
+ return 0;
+ fail:
+ memset(p, 0, total_sz);
+ free(p);
+ return ret;
+}
+
+static krb5_error_code
+encrypt_internal_enc_then_cksum(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ const void *data,
+ size_t len,
+ krb5_data *result,
+ void *ivec)
+{
+ size_t sz, block_sz, checksum_sz, total_sz;
+ Checksum cksum;
+ unsigned char *p, *q, *ivc = NULL;
+ krb5_error_code ret;
+ struct _krb5_key_data *dkey;
+ const struct _krb5_encryption_type *et = crypto->et;
+
+ checksum_sz = CHECKSUMSIZE(et->keyed_checksum);
+
+ sz = et->confoundersize + len;
+ block_sz = (sz + et->padsize - 1) &~ (et->padsize - 1); /* pad */
+ total_sz = block_sz + checksum_sz;
+ p = calloc(1, total_sz);
+ if (p == NULL)
+ return krb5_enomem(context);
+
+ q = p;
+ krb5_generate_random_block(q, et->confoundersize); /* XXX */
+ q += et->confoundersize;
+ memcpy(q, data, len);
+
+ ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey);
+ if(ret)
+ goto fail;
+ ret = _key_schedule(context, dkey);
+ if(ret)
+ goto fail;
+
+ /* XXX EVP style update API would avoid needing to allocate here */
+ ivc = malloc(et->blocksize + block_sz);
+ if (ivc == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ if (ivec)
+ memcpy(ivc, ivec, et->blocksize);
+ else
+ memset(ivc, 0, et->blocksize);
+
+ ret = (*et->encrypt)(context, dkey, p, block_sz, 1, usage, ivec);
+ if (ret)
+ goto fail;
+ memcpy(&ivc[et->blocksize], p, block_sz);
+
+ ret = create_checksum(context,
+ et->keyed_checksum,
+ crypto,
+ INTEGRITY_USAGE(usage),
+ ivc,
+ et->blocksize + block_sz,
+ 0,
+ &cksum);
+ if(ret == 0 && cksum.checksum.length != checksum_sz) {
+ free_Checksum (&cksum);
+ krb5_clear_error_message (context);
+ ret = KRB5_CRYPTO_INTERNAL;
+ }
+ if(ret)
+ goto fail;
+ memcpy(p + block_sz, cksum.checksum.data, cksum.checksum.length);
+ free_Checksum (&cksum);
+ result->data = p;
+ result->length = total_sz;
+ free(ivc);
+ return 0;
+ fail:
+ memset_s(p, total_sz, 0, total_sz);
+ free(p);
+ free(ivc);
+ return ret;
+}
+
+static krb5_error_code
+encrypt_internal(krb5_context context,
+ krb5_crypto crypto,
+ const void *data,
+ size_t len,
+ krb5_data *result,
+ void *ivec)
+{
+ size_t sz, block_sz, checksum_sz;
+ Checksum cksum;
+ unsigned char *p, *q;
+ krb5_error_code ret;
+ const struct _krb5_encryption_type *et = crypto->et;
+
+ checksum_sz = CHECKSUMSIZE(et->checksum);
+
+ sz = et->confoundersize + checksum_sz + len;
+ block_sz = (sz + et->padsize - 1) &~ (et->padsize - 1); /* pad */
+ p = calloc(1, block_sz);
+ if (p == NULL)
+ return krb5_enomem(context);
+
+ q = p;
+ krb5_generate_random_block(q, et->confoundersize); /* XXX */
+ q += et->confoundersize;
+ memset(q, 0, checksum_sz);
+ q += checksum_sz;
+ memcpy(q, data, len);
+
+ ret = create_checksum(context,
+ et->checksum,
+ crypto,
+ 0,
+ p,
+ block_sz,
+ KRB5_CRYPTO_FLAG_ALLOW_UNKEYED_CHECKSUM,
+ &cksum);
+ if(ret == 0 && cksum.checksum.length != checksum_sz) {
+ krb5_clear_error_message (context);
+ free_Checksum(&cksum);
+ ret = KRB5_CRYPTO_INTERNAL;
+ }
+ if(ret)
+ goto fail;
+ memcpy(p + et->confoundersize, cksum.checksum.data, cksum.checksum.length);
+ free_Checksum(&cksum);
+ ret = _key_schedule(context, &crypto->key);
+ if(ret)
+ goto fail;
+ ret = (*et->encrypt)(context, &crypto->key, p, block_sz, 1, 0, ivec);
+ if (ret) {
+ memset(p, 0, block_sz);
+ free(p);
+ return ret;
+ }
+ result->data = p;
+ result->length = block_sz;
+ return 0;
+ fail:
+ memset(p, 0, block_sz);
+ free(p);
+ return ret;
+}
+
+static krb5_error_code
+encrypt_internal_special(krb5_context context,
+ krb5_crypto crypto,
+ int usage,
+ const void *data,
+ size_t len,
+ krb5_data *result,
+ void *ivec)
+{
+ struct _krb5_encryption_type *et = crypto->et;
+ size_t cksum_sz = CHECKSUMSIZE(et->checksum);
+ size_t sz = len + cksum_sz + et->confoundersize;
+ char *tmp, *p;
+ krb5_error_code ret;
+
+ tmp = malloc (sz);
+ if (tmp == NULL)
+ return krb5_enomem(context);
+ p = tmp;
+ memset (p, 0, cksum_sz);
+ p += cksum_sz;
+ krb5_generate_random_block(p, et->confoundersize);
+ p += et->confoundersize;
+ memcpy (p, data, len);
+ ret = (*et->encrypt)(context, &crypto->key, tmp, sz, TRUE, usage, ivec);
+ if (ret) {
+ memset(tmp, 0, sz);
+ free(tmp);
+ return ret;
+ }
+ result->data = tmp;
+ result->length = sz;
+ return 0;
+}
+
+static krb5_error_code
+decrypt_internal_derived(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ void *data,
+ size_t len,
+ krb5_data *result,
+ void *ivec)
+{
+ size_t checksum_sz;
+ Checksum cksum;
+ unsigned char *p;
+ krb5_error_code ret;
+ struct _krb5_key_data *dkey;
+ struct _krb5_encryption_type *et = crypto->et;
+ unsigned long l;
+
+ checksum_sz = CHECKSUMSIZE(et->keyed_checksum);
+ if (len < checksum_sz + et->confoundersize) {
+ krb5_set_error_message(context, KRB5_BAD_MSIZE,
+ N_("Encrypted data shorter then "
+ "checksum + confunder", ""));
+ return KRB5_BAD_MSIZE;
+ }
+
+ if (((len - checksum_sz) % et->padsize) != 0) {
+ krb5_clear_error_message(context);
+ return KRB5_BAD_MSIZE;
+ }
+
+ p = malloc(len);
+ if (len != 0 && p == NULL)
+ return krb5_enomem(context);
+ memcpy(p, data, len);
+
+ len -= checksum_sz;
+
+ ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey);
+ if(ret) {
+ free(p);
+ return ret;
+ }
+ ret = _key_schedule(context, dkey);
+ if(ret) {
+ free(p);
+ return ret;
+ }
+ ret = (*et->encrypt)(context, dkey, p, len, 0, usage, ivec);
+ if (ret) {
+ free(p);
+ return ret;
+ }
+
+ cksum.checksum.data = p + len;
+ cksum.checksum.length = checksum_sz;
+ cksum.cksumtype = CHECKSUMTYPE(et->keyed_checksum);
+
+ ret = verify_checksum(context,
+ crypto,
+ INTEGRITY_USAGE(usage),
+ p,
+ len,
+ 0,
+ &cksum);
+ if(ret) {
+ free(p);
+ return ret;
+ }
+ l = len - et->confoundersize;
+ memmove(p, p + et->confoundersize, l);
+ result->data = realloc(p, l);
+ if(result->data == NULL && l != 0) {
+ free(p);
+ return krb5_enomem(context);
+ }
+ result->length = l;
+ return 0;
+}
+
+static krb5_error_code
+decrypt_internal_enc_then_cksum(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ void *data,
+ size_t len,
+ krb5_data *result,
+ void *ivec)
+{
+ size_t checksum_sz;
+ Checksum cksum;
+ unsigned char *p;
+ krb5_error_code ret;
+ struct _krb5_key_data *dkey;
+ struct _krb5_encryption_type *et = crypto->et;
+ unsigned long l;
+
+ checksum_sz = CHECKSUMSIZE(et->keyed_checksum);
+ if (len < checksum_sz + et->confoundersize) {
+ krb5_set_error_message(context, KRB5_BAD_MSIZE,
+ N_("Encrypted data shorter then "
+ "checksum + confunder", ""));
+ return KRB5_BAD_MSIZE;
+ }
+
+ if (((len - checksum_sz) % et->padsize) != 0) {
+ krb5_clear_error_message(context);
+ return KRB5_BAD_MSIZE;
+ }
+
+ len -= checksum_sz;
+
+ p = malloc(et->blocksize + len);
+ if (p == NULL)
+ return krb5_enomem(context);
+
+ if (ivec)
+ memcpy(p, ivec, et->blocksize);
+ else
+ memset(p, 0, et->blocksize);
+ memcpy(&p[et->blocksize], data, len);
+
+ cksum.checksum.data = (unsigned char *)data + len;
+ cksum.checksum.length = checksum_sz;
+ cksum.cksumtype = CHECKSUMTYPE(et->keyed_checksum);
+
+ ret = verify_checksum(context,
+ crypto,
+ INTEGRITY_USAGE(usage),
+ p,
+ et->blocksize + len,
+ 0,
+ &cksum);
+ if(ret) {
+ free(p);
+ return ret;
+ }
+
+ ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey);
+ if(ret) {
+ free(p);
+ return ret;
+ }
+ ret = _key_schedule(context, dkey);
+ if(ret) {
+ free(p);
+ return ret;
+ }
+ ret = (*et->encrypt)(context, dkey, &p[et->blocksize], len, 0, usage, ivec);
+ if (ret) {
+ free(p);
+ return ret;
+ }
+
+ l = len - et->confoundersize;
+ memmove(p, p + et->blocksize + et->confoundersize, l);
+ result->data = realloc(p, l);
+ if(result->data == NULL && l != 0) {
+ free(p);
+ return krb5_enomem(context);
+ }
+ result->length = l;
+ return 0;
+}
+
+static krb5_error_code
+decrypt_internal(krb5_context context,
+ krb5_crypto crypto,
+ void *data,
+ size_t len,
+ krb5_data *result,
+ void *ivec)
+{
+ krb5_error_code ret;
+ unsigned char *p;
+ Checksum cksum;
+ size_t checksum_sz, l;
+ struct _krb5_encryption_type *et = crypto->et;
+
+ if ((len % et->padsize) != 0) {
+ krb5_clear_error_message(context);
+ return KRB5_BAD_MSIZE;
+ }
+ checksum_sz = CHECKSUMSIZE(et->checksum);
+ if (len < checksum_sz + et->confoundersize) {
+ krb5_set_error_message(context, KRB5_BAD_MSIZE,
+ N_("Encrypted data shorter then "
+ "checksum + confunder", ""));
+ return KRB5_BAD_MSIZE;
+ }
+
+ p = malloc(len);
+ if (len != 0 && p == NULL)
+ return krb5_enomem(context);
+ memcpy(p, data, len);
+
+ ret = _key_schedule(context, &crypto->key);
+ if(ret) {
+ free(p);
+ return ret;
+ }
+ ret = (*et->encrypt)(context, &crypto->key, p, len, 0, 0, ivec);
+ if (ret) {
+ free(p);
+ return ret;
+ }
+ ret = krb5_data_copy(&cksum.checksum, p + et->confoundersize, checksum_sz);
+ if(ret) {
+ free(p);
+ return ret;
+ }
+ memset(p + et->confoundersize, 0, checksum_sz);
+ cksum.cksumtype = CHECKSUMTYPE(et->checksum);
+ ret = verify_checksum(context, NULL, 0, p, len,
+ KRB5_CRYPTO_FLAG_ALLOW_UNKEYED_CHECKSUM, &cksum);
+ free_Checksum(&cksum);
+ if(ret) {
+ free(p);
+ return ret;
+ }
+ l = len - et->confoundersize - checksum_sz;
+ memmove(p, p + et->confoundersize + checksum_sz, l);
+ result->data = realloc(p, l);
+ if(result->data == NULL && l != 0) {
+ free(p);
+ return krb5_enomem(context);
+ }
+ result->length = l;
+ return 0;
+}
+
+static krb5_error_code
+decrypt_internal_special(krb5_context context,
+ krb5_crypto crypto,
+ int usage,
+ void *data,
+ size_t len,
+ krb5_data *result,
+ void *ivec)
+{
+ struct _krb5_encryption_type *et = crypto->et;
+ size_t cksum_sz = CHECKSUMSIZE(et->checksum);
+ size_t sz = len - cksum_sz - et->confoundersize;
+ unsigned char *p;
+ krb5_error_code ret;
+
+ if ((len % et->padsize) != 0) {
+ krb5_clear_error_message(context);
+ return KRB5_BAD_MSIZE;
+ }
+ if (len < cksum_sz + et->confoundersize) {
+ krb5_set_error_message(context, KRB5_BAD_MSIZE,
+ N_("Encrypted data shorter then "
+ "checksum + confunder", ""));
+ return KRB5_BAD_MSIZE;
+ }
+
+ p = malloc (len);
+ if (p == NULL)
+ return krb5_enomem(context);
+ memcpy(p, data, len);
+
+ ret = (*et->encrypt)(context, &crypto->key, p, len, FALSE, usage, ivec);
+ if (ret) {
+ free(p);
+ return ret;
+ }
+
+ memmove (p, p + cksum_sz + et->confoundersize, sz);
+ result->data = realloc(p, sz);
+ if(result->data == NULL && sz != 0) {
+ free(p);
+ return krb5_enomem(context);
+ }
+ result->length = sz;
+ return 0;
+}
+
+static krb5_crypto_iov *
+iov_find(krb5_crypto_iov *data, size_t num_data, unsigned type)
+{
+ size_t i;
+ for (i = 0; i < num_data; i++)
+ if (data[i].flags == type)
+ return &data[i];
+ return NULL;
+}
+
+static size_t
+iov_enc_data_len(krb5_crypto_iov *data, int num_data)
+{
+ size_t i, len;
+
+ for (len = 0, i = 0; i < num_data; i++) {
+ if (data[i].flags != KRB5_CRYPTO_TYPE_DATA)
+ continue;
+ len += data[i].data.length;
+ }
+
+ return len;
+}
+
+static size_t
+iov_sign_data_len(krb5_crypto_iov *data, int num_data)
+{
+ size_t i, len;
+
+ for (len = 0, i = 0; i < num_data; i++) {
+ /* Can't use should_sign, because we must only count data, not
+ * header/trailer */
+ if (data[i].flags == KRB5_CRYPTO_TYPE_DATA ||
+ data[i].flags == KRB5_CRYPTO_TYPE_SIGN_ONLY)
+ len += data[i].data.length;
+ }
+
+ return len;
+}
+
+static krb5_error_code
+iov_coalesce(krb5_context context,
+ krb5_data *prefix,
+ krb5_crypto_iov *data,
+ int num_data,
+ krb5_boolean inc_sign_data,
+ krb5_data *out)
+{
+ unsigned char *p, *q;
+ krb5_crypto_iov *hiv, *piv;
+ size_t len;
+ unsigned int i;
+
+ hiv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_HEADER);
+
+ piv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_PADDING);
+
+ len = 0;
+ if (prefix)
+ len += prefix->length;
+ len += hiv->data.length;
+ if (inc_sign_data)
+ len += iov_sign_data_len(data, num_data);
+ else
+ len += iov_enc_data_len(data, num_data);
+ if (piv)
+ len += piv->data.length;
+
+ p = q = malloc(len);
+ if (p == NULL)
+ return krb5_enomem(context);
+
+ if (prefix) {
+ memcpy(q, prefix->data, prefix->length);
+ q += prefix->length;
+ }
+ memcpy(q, hiv->data.data, hiv->data.length);
+ q += hiv->data.length;
+ for (i = 0; i < num_data; i++) {
+ if (data[i].flags == KRB5_CRYPTO_TYPE_DATA ||
+ (inc_sign_data && data[i].flags == KRB5_CRYPTO_TYPE_SIGN_ONLY)) {
+ memcpy(q, data[i].data.data, data[i].data.length);
+ q += data[i].data.length;
+ }
+ }
+ if (piv)
+ memset(q, 0, piv->data.length);
+
+ out->length = len;
+ out->data = p;
+
+ return 0;
+}
+
+static krb5_error_code
+iov_uncoalesce(krb5_context context,
+ krb5_data *enc_data,
+ krb5_crypto_iov *data,
+ int num_data)
+{
+ unsigned char *q = enc_data->data;
+ krb5_crypto_iov *hiv, *piv;
+ unsigned int i;
+
+ hiv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_HEADER);
+
+ piv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_PADDING);
+
+ memcpy(hiv->data.data, q, hiv->data.length);
+ q += hiv->data.length;
+
+ for (i = 0; i < num_data; i++) {
+ if (data[i].flags != KRB5_CRYPTO_TYPE_DATA)
+ continue;
+ memcpy(data[i].data.data, q, data[i].data.length);
+ q += data[i].data.length;
+ }
+ if (piv)
+ memcpy(piv->data.data, q, piv->data.length);
+
+ return 0;
+}
+
+static krb5_error_code
+iov_pad_validate(const struct _krb5_encryption_type *et,
+ krb5_crypto_iov *data,
+ int num_data,
+ krb5_crypto_iov **ppiv)
+{
+ krb5_crypto_iov *piv;
+ size_t sz, headersz, block_sz, pad_sz, len;
+
+ len = iov_enc_data_len(data, num_data);
+
+ headersz = et->confoundersize;
+
+ sz = headersz + len;
+ block_sz = (sz + et->padsize - 1) &~ (et->padsize - 1); /* pad */
+
+ pad_sz = block_sz - sz;
+
+ piv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_PADDING);
+ /* its ok to have no TYPE_PADDING if there is no padding */
+ if (piv == NULL && pad_sz != 0)
+ return KRB5_BAD_MSIZE;
+ if (piv) {
+ if (piv->data.length < pad_sz)
+ return KRB5_BAD_MSIZE;
+ piv->data.length = pad_sz;
+ if (pad_sz)
+ memset(piv->data.data, 0, pad_sz);
+ else
+ piv = NULL;
+ }
+
+ *ppiv = piv;
+ return 0;
+}
+
+/**
+ * Inline encrypt a kerberos message
+ *
+ * @param context Kerberos context
+ * @param crypto Kerberos crypto context
+ * @param usage Key usage for this buffer
+ * @param data array of buffers to process
+ * @param num_data length of array
+ * @param ivec initial cbc/cts vector
+ *
+ * @return Return an error code or 0.
+ * @ingroup krb5_crypto
+ *
+ * Kerberos encrypted data look like this:
+ *
+ * 1. KRB5_CRYPTO_TYPE_HEADER
+ * 2. array [1,...] KRB5_CRYPTO_TYPE_DATA and array [0,...]
+ * KRB5_CRYPTO_TYPE_SIGN_ONLY in any order, however the receiver
+ * have to aware of the order. KRB5_CRYPTO_TYPE_SIGN_ONLY is
+ * commonly used headers and trailers.
+ * 3. KRB5_CRYPTO_TYPE_PADDING, at least on padsize long if padsize > 1
+ * 4. KRB5_CRYPTO_TYPE_TRAILER
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_encrypt_iov_ivec(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ krb5_crypto_iov *data,
+ int num_data,
+ void *ivec)
+{
+ size_t headersz, trailersz;
+ Checksum cksum;
+ krb5_data enc_data, sign_data;
+ krb5_error_code ret;
+ struct _krb5_key_data *dkey;
+ const struct _krb5_encryption_type *et = crypto->et;
+ krb5_crypto_iov *tiv, *piv, *hiv;
+
+ if (num_data < 0) {
+ krb5_clear_error_message(context);
+ return KRB5_CRYPTO_INTERNAL;
+ }
+
+ if(!derived_crypto(context, crypto)) {
+ krb5_clear_error_message(context);
+ return KRB5_CRYPTO_INTERNAL;
+ }
+
+ krb5_data_zero(&enc_data);
+ krb5_data_zero(&sign_data);
+
+ headersz = et->confoundersize;
+ trailersz = CHECKSUMSIZE(et->keyed_checksum);
+
+ /* header */
+ hiv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_HEADER);
+ if (hiv == NULL || hiv->data.length != headersz)
+ return KRB5_BAD_MSIZE;
+ krb5_generate_random_block(hiv->data.data, hiv->data.length);
+
+ /* padding */
+ ret = iov_pad_validate(et, data, num_data, &piv);
+ if(ret)
+ goto cleanup;
+
+ /* trailer */
+ tiv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_TRAILER);
+ if (tiv == NULL || tiv->data.length != trailersz) {
+ ret = KRB5_BAD_MSIZE;
+ goto cleanup;
+ }
+
+ if (et->flags & F_ENC_THEN_CKSUM) {
+ unsigned char old_ivec[EVP_MAX_IV_LENGTH];
+ krb5_data ivec_data;
+
+ heim_assert(et->blocksize <= sizeof(old_ivec),
+ "blocksize too big for ivec buffer");
+
+ ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey);
+ if(ret)
+ goto cleanup;
+
+ ret = _key_schedule(context, dkey);
+ if(ret)
+ goto cleanup;
+
+ if (ivec)
+ memcpy(old_ivec, ivec, et->blocksize);
+ else
+ memset(old_ivec, 0, et->blocksize);
+
+ if (et->encrypt_iov != NULL) {
+ ret = (*et->encrypt_iov)(context, dkey, data, num_data, 1, usage,
+ ivec);
+ if (ret)
+ goto cleanup;
+ } else {
+ ret = iov_coalesce(context, NULL, data, num_data, FALSE, &enc_data);
+ if (ret)
+ goto cleanup;
+
+ ret = (*et->encrypt)(context, dkey, enc_data.data, enc_data.length,
+ 1, usage, ivec);
+ if (ret)
+ goto cleanup;
+
+ ret = iov_uncoalesce(context, &enc_data, data, num_data);
+ if (ret)
+ goto cleanup;
+ }
+
+ ivec_data.length = et->blocksize;
+ ivec_data.data = old_ivec;
+
+ ret = iov_coalesce(context, &ivec_data, data, num_data, TRUE, &sign_data);
+ if(ret)
+ goto cleanup;
+
+ ret = create_checksum(context,
+ et->keyed_checksum,
+ crypto,
+ INTEGRITY_USAGE(usage),
+ sign_data.data,
+ sign_data.length,
+ 0,
+ &cksum);
+
+ if(ret == 0 && cksum.checksum.length != trailersz) {
+ free_Checksum (&cksum);
+ krb5_clear_error_message (context);
+ ret = KRB5_CRYPTO_INTERNAL;
+ }
+ if (ret)
+ goto cleanup;
+
+ /* save cksum at end */
+ memcpy(tiv->data.data, cksum.checksum.data, cksum.checksum.length);
+ free_Checksum (&cksum);
+
+ } else {
+ cksum.checksum = tiv->data;
+ ret = create_checksum_iov(context,
+ et->keyed_checksum,
+ crypto,
+ INTEGRITY_USAGE(usage),
+ data,
+ num_data,
+ 0,
+ &cksum);
+ if (ret)
+ goto cleanup;
+
+ /* create_checksum may realloc the derived key space, so any keys
+ * obtained before it was called may no longer be valid */
+ ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey);
+ if(ret)
+ goto cleanup;
+
+ ret = _key_schedule(context, dkey);
+ if(ret)
+ goto cleanup;
+
+ if (et->encrypt_iov != NULL) {
+ ret = (*et->encrypt_iov)(context, dkey, data, num_data, 1, usage,
+ ivec);
+ if (ret)
+ goto cleanup;
+ } else {
+ ret = iov_coalesce(context, NULL, data, num_data, FALSE, &enc_data);
+ if (ret)
+ goto cleanup;
+
+ ret = (*et->encrypt)(context, dkey, enc_data.data, enc_data.length,
+ 1, usage, ivec);
+ if (ret)
+ goto cleanup;
+
+ ret = iov_uncoalesce(context, &enc_data, data, num_data);
+ if (ret)
+ goto cleanup;
+ }
+ }
+
+cleanup:
+ if (enc_data.data) {
+ memset_s(enc_data.data, enc_data.length, 0, enc_data.length);
+ krb5_data_free(&enc_data);
+ }
+ if (sign_data.data) {
+ memset_s(sign_data.data, sign_data.length, 0, sign_data.length);
+ krb5_data_free(&sign_data);
+ }
+ return ret;
+}
+
+/**
+ * Inline decrypt a Kerberos message.
+ *
+ * @param context Kerberos context
+ * @param crypto Kerberos crypto context
+ * @param usage Key usage for this buffer
+ * @param data array of buffers to process
+ * @param num_data length of array
+ * @param ivec initial cbc/cts vector
+ *
+ * @return Return an error code or 0.
+ * @ingroup krb5_crypto
+ *
+ * 1. KRB5_CRYPTO_TYPE_HEADER
+ * 2. one KRB5_CRYPTO_TYPE_DATA and array [0,...] of KRB5_CRYPTO_TYPE_SIGN_ONLY in
+ * any order, however the receiver have to aware of the
+ * order. KRB5_CRYPTO_TYPE_SIGN_ONLY is commonly used unencrypoted
+ * protocol headers and trailers. The output data will be of same
+ * size as the input data or shorter.
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decrypt_iov_ivec(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ krb5_crypto_iov *data,
+ unsigned int num_data,
+ void *ivec)
+{
+ Checksum cksum;
+ krb5_data enc_data, sign_data;
+ krb5_error_code ret;
+ struct _krb5_key_data *dkey;
+ struct _krb5_encryption_type *et = crypto->et;
+ krb5_crypto_iov *tiv, *hiv;
+
+ if(!derived_crypto(context, crypto)) {
+ krb5_clear_error_message(context);
+ return KRB5_CRYPTO_INTERNAL;
+ }
+
+ /* header */
+ hiv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_HEADER);
+ if (hiv == NULL || hiv->data.length != et->confoundersize)
+ return KRB5_BAD_MSIZE;
+
+ /* trailer */
+ tiv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_TRAILER);
+ if (tiv->data.length != CHECKSUMSIZE(et->keyed_checksum))
+ return KRB5_BAD_MSIZE;
+
+ /* padding */
+ if ((iov_enc_data_len(data, num_data) % et->padsize) != 0) {
+ krb5_clear_error_message(context);
+ return KRB5_BAD_MSIZE;
+ }
+
+ krb5_data_zero(&enc_data);
+ krb5_data_zero(&sign_data);
+
+ if (!(et->flags & F_ENC_THEN_CKSUM)) {
+ ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey);
+ if(ret)
+ goto cleanup;
+
+ ret = _key_schedule(context, dkey);
+ if(ret)
+ goto cleanup;
+
+ if (et->encrypt_iov != NULL) {
+ ret = (*et->encrypt_iov)(context, dkey, data, num_data,
+ 0, usage, ivec);
+ if(ret)
+ goto cleanup;
+ } else {
+ ret = iov_coalesce(context, NULL, data, num_data, FALSE, &enc_data);
+ if(ret)
+ goto cleanup;
+
+ ret = (*et->encrypt)(context, dkey, enc_data.data, enc_data.length,
+ 0, usage, ivec);
+ if(ret)
+ goto cleanup;
+
+ ret = iov_uncoalesce(context, &enc_data, data, num_data);
+ if(ret)
+ goto cleanup;
+ }
+
+ cksum.checksum.data = tiv->data.data;
+ cksum.checksum.length = tiv->data.length;
+ cksum.cksumtype = CHECKSUMTYPE(et->keyed_checksum);
+
+ ret = verify_checksum_iov(context, crypto, INTEGRITY_USAGE(usage),
+ data, num_data, 0, &cksum);
+ if(ret)
+ goto cleanup;
+ } else {
+ krb5_data ivec_data;
+ static unsigned char zero_ivec[EVP_MAX_IV_LENGTH];
+
+ heim_assert(et->blocksize <= sizeof(zero_ivec),
+ "blocksize too big for ivec buffer");
+
+ ivec_data.length = et->blocksize;
+ ivec_data.data = ivec ? ivec : zero_ivec;
+
+ ret = iov_coalesce(context, &ivec_data, data, num_data, TRUE, &sign_data);
+ if(ret)
+ goto cleanup;
+
+ cksum.checksum.data = tiv->data.data;
+ cksum.checksum.length = tiv->data.length;
+ cksum.cksumtype = CHECKSUMTYPE(et->keyed_checksum);
+
+ ret = verify_checksum(context,
+ crypto,
+ INTEGRITY_USAGE(usage),
+ sign_data.data,
+ sign_data.length,
+ 0,
+ &cksum);
+ if(ret)
+ goto cleanup;
+
+ ret = iov_coalesce(context, NULL, data, num_data, FALSE, &enc_data);
+ if(ret)
+ goto cleanup;
+
+ ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey);
+ if(ret)
+ goto cleanup;
+
+ ret = _key_schedule(context, dkey);
+ if(ret)
+ goto cleanup;
+
+ ret = (*et->encrypt)(context, dkey, enc_data.data, enc_data.length,
+ 0, usage, ivec);
+ if(ret)
+ goto cleanup;
+
+ ret = iov_uncoalesce(context, &enc_data, data, num_data);
+ if(ret)
+ goto cleanup;
+ }
+
+cleanup:
+ if (enc_data.data) {
+ memset_s(enc_data.data, enc_data.length, 0, enc_data.length);
+ krb5_data_free(&enc_data);
+ }
+ if (sign_data.data) {
+ memset_s(sign_data.data, sign_data.length, 0, sign_data.length);
+ krb5_data_free(&sign_data);
+ }
+ return ret;
+}
+
+/**
+ * Create a Kerberos message checksum.
+ *
+ * @param context Kerberos context
+ * @param crypto Kerberos crypto context
+ * @param usage Key usage for this buffer
+ * @param data array of buffers to process
+ * @param num_data length of array
+ * @param type output data
+ *
+ * @return Return an error code or 0.
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_create_checksum_iov(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ krb5_crypto_iov *data,
+ unsigned int num_data,
+ krb5_cksumtype *type)
+{
+ Checksum cksum;
+ krb5_crypto_iov *civ;
+ struct _krb5_checksum_type *ct;
+ unsigned keyusage;
+ krb5_error_code ret;
+
+ civ = iov_find(data, num_data, KRB5_CRYPTO_TYPE_CHECKSUM);
+ if (civ == NULL)
+ return KRB5_BAD_MSIZE;
+
+ ct = crypto->et->keyed_checksum;
+ if (ct == NULL)
+ ct = crypto->et->checksum;
+
+ if(ct == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+ N_("checksum type not found", ""));
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+ }
+
+ if (arcfour_checksum_p(ct, crypto)) {
+ keyusage = usage;
+ _krb5_usage2arcfour(context, &keyusage);
+ } else
+ keyusage = CHECKSUM_USAGE(usage);
+
+ if (ct->checksumsize > civ->data.length) {
+ krb5_set_error_message(context, KRB5_BAD_MSIZE,
+ N_("Checksum larger then input buffer", ""));
+ return KRB5_BAD_MSIZE;
+ }
+
+ cksum.checksum = civ->data;
+ ret = create_checksum_iov(context, ct, crypto, keyusage,
+ data, num_data, crypto_flags(crypto), &cksum);
+
+ if (ret == 0 && type)
+ *type = cksum.cksumtype;
+
+ return ret;
+}
+
+/**
+ * Verify a Kerberos message checksum.
+ *
+ * @param context Kerberos context
+ * @param crypto Kerberos crypto context
+ * @param usage Key usage for this buffer
+ * @param data array of buffers to process
+ * @param num_data length of array
+ * @param type return checksum type if not NULL
+ *
+ * @return Return an error code or 0.
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verify_checksum_iov(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ krb5_crypto_iov *data,
+ unsigned int num_data,
+ krb5_cksumtype *type)
+{
+ struct _krb5_encryption_type *et = crypto->et;
+ struct _krb5_checksum_type *ct;
+ Checksum cksum;
+ krb5_crypto_iov *civ;
+ krb5_error_code ret;
+ unsigned keyusage;
+
+ civ = iov_find(data, num_data, KRB5_CRYPTO_TYPE_CHECKSUM);
+ if (civ == NULL)
+ return KRB5_BAD_MSIZE;
+
+ cksum.cksumtype = CHECKSUMTYPE(et->keyed_checksum);
+ cksum.checksum.length = civ->data.length;
+ cksum.checksum.data = civ->data.data;
+
+ ct = _krb5_find_checksum(cksum.cksumtype);
+ if(ct == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+ N_("checksum type %d not supported", ""),
+ cksum.cksumtype);
+ return KRB5_PROG_SUMTYPE_NOSUPP;
+ }
+
+ if (arcfour_checksum_p(ct, crypto)) {
+ keyusage = usage;
+ _krb5_usage2arcfour(context, &keyusage);
+ } else
+ keyusage = CHECKSUM_USAGE(usage);
+
+ ret = verify_checksum_iov(context, crypto, keyusage, data, num_data,
+ crypto_flags(crypto), &cksum);
+
+ if (ret == 0 && type)
+ *type = cksum.cksumtype;
+
+ return ret;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_length(krb5_context context,
+ krb5_crypto crypto,
+ int type,
+ size_t *len)
+{
+ if (!derived_crypto(context, crypto)) {
+ krb5_set_error_message(context, EINVAL, "not a derived crypto");
+ return EINVAL;
+ }
+
+ switch(type) {
+ case KRB5_CRYPTO_TYPE_EMPTY:
+ *len = 0;
+ return 0;
+ case KRB5_CRYPTO_TYPE_HEADER:
+ *len = crypto->et->blocksize;
+ return 0;
+ case KRB5_CRYPTO_TYPE_DATA:
+ case KRB5_CRYPTO_TYPE_SIGN_ONLY:
+ /* len must already been filled in */
+ return 0;
+ case KRB5_CRYPTO_TYPE_PADDING:
+ if (crypto->et->padsize > 1)
+ *len = crypto->et->padsize;
+ else
+ *len = 0;
+ return 0;
+ case KRB5_CRYPTO_TYPE_TRAILER:
+ if (crypto->et->keyed_checksum)
+ *len = CHECKSUMSIZE(crypto->et->keyed_checksum);
+ else
+ *len = 0;
+ return 0;
+ case KRB5_CRYPTO_TYPE_CHECKSUM:
+ if (crypto->et->keyed_checksum)
+ *len = CHECKSUMSIZE(crypto->et->keyed_checksum);
+ else
+ *len = CHECKSUMSIZE(crypto->et->checksum);
+ return 0;
+ }
+ krb5_set_error_message(context, EINVAL,
+ "%d not a supported type", type);
+ return EINVAL;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_length_iov(krb5_context context,
+ krb5_crypto crypto,
+ krb5_crypto_iov *data,
+ unsigned int num_data)
+{
+ krb5_error_code ret;
+ size_t i;
+
+ for (i = 0; i < num_data; i++) {
+ ret = krb5_crypto_length(context, crypto,
+ data[i].flags,
+ &data[i].data.length);
+ if (ret)
+ return ret;
+ }
+ return 0;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_encrypt_ivec(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ const void *data,
+ size_t len,
+ krb5_data *result,
+ void *ivec)
+{
+ krb5_error_code ret;
+
+ switch (crypto->et->flags & F_CRYPTO_MASK) {
+ case F_RFC3961_ENC:
+ ret = encrypt_internal_derived(context, crypto, usage,
+ data, len, result, ivec);
+ break;
+ case F_SPECIAL:
+ ret = encrypt_internal_special (context, crypto, usage,
+ data, len, result, ivec);
+ break;
+ case F_ENC_THEN_CKSUM:
+ ret = encrypt_internal_enc_then_cksum(context, crypto, usage,
+ data, len, result, ivec);
+ break;
+ default:
+ ret = encrypt_internal(context, crypto, data, len, result, ivec);
+ break;
+ }
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_encrypt(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ const void *data,
+ size_t len,
+ krb5_data *result)
+{
+ return krb5_encrypt_ivec(context, crypto, usage, data, len, result, NULL);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_encrypt_EncryptedData(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ void *data,
+ size_t len,
+ int kvno,
+ EncryptedData *result)
+{
+ result->etype = CRYPTO_ETYPE(crypto);
+ if(kvno){
+ ALLOC(result->kvno, 1);
+ *result->kvno = kvno;
+ }else
+ result->kvno = NULL;
+ return krb5_encrypt(context, crypto, usage, data, len, &result->cipher);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decrypt_ivec(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ void *data,
+ size_t len,
+ krb5_data *result,
+ void *ivec)
+{
+ krb5_error_code ret;
+
+ switch (crypto->et->flags & F_CRYPTO_MASK) {
+ case F_RFC3961_ENC:
+ ret = decrypt_internal_derived(context, crypto, usage,
+ data, len, result, ivec);
+ break;
+ case F_SPECIAL:
+ ret = decrypt_internal_special(context, crypto, usage,
+ data, len, result, ivec);
+ break;
+ case F_ENC_THEN_CKSUM:
+ ret = decrypt_internal_enc_then_cksum(context, crypto, usage,
+ data, len, result, ivec);
+ break;
+ default:
+ ret = decrypt_internal(context, crypto, data, len, result, ivec);
+ break;
+ }
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decrypt(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ void *data,
+ size_t len,
+ krb5_data *result)
+{
+ return krb5_decrypt_ivec (context, crypto, usage, data, len, result,
+ NULL);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decrypt_EncryptedData(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ const EncryptedData *e,
+ krb5_data *result)
+{
+ return krb5_decrypt(context, crypto, usage,
+ e->cipher.data, e->cipher.length, result);
+}
+
+/************************************************************
+ * *
+ ************************************************************/
+
+static krb5_error_code
+derive_key_rfc3961(krb5_context context,
+ struct _krb5_encryption_type *et,
+ struct _krb5_key_data *key,
+ const void *constant,
+ size_t len)
+{
+
+ unsigned char *k = NULL;
+ unsigned int nblocks = 0, i;
+ krb5_error_code ret = 0;
+ struct _krb5_key_type *kt = et->keytype;
+
+ if(et->blocksize * 8 < kt->bits || len != et->blocksize) {
+ nblocks = (kt->bits + et->blocksize * 8 - 1) / (et->blocksize * 8);
+ k = malloc(nblocks * et->blocksize);
+ if(k == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ ret = _krb5_n_fold(constant, len, k, et->blocksize);
+ if (ret) {
+ krb5_enomem(context);
+ goto out;
+ }
+
+ for(i = 0; i < nblocks; i++) {
+ if(i > 0)
+ memcpy(k + i * et->blocksize,
+ k + (i - 1) * et->blocksize,
+ et->blocksize);
+ ret = (*et->encrypt)(context, key, k + i * et->blocksize,
+ et->blocksize, 1, 0, NULL);
+ if (ret) {
+ krb5_set_error_message(context, ret, N_("encrypt failed", ""));
+ goto out;
+ }
+ }
+ } else {
+ /* this case is probably broken, but won't be run anyway */
+ void *c = malloc(len);
+ size_t res_len = (kt->bits + 7) / 8;
+
+ if(len != 0 && c == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ memcpy(c, constant, len);
+ ret = (*et->encrypt)(context, key, c, len, 1, 0, NULL);
+ if (ret) {
+ free(c);
+ krb5_set_error_message(context, ret, N_("encrypt failed", ""));
+ goto out;
+ }
+ k = malloc(res_len);
+ if(res_len != 0 && k == NULL) {
+ free(c);
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ ret = _krb5_n_fold(c, len, k, res_len);
+ free(c);
+ if (ret) {
+ krb5_enomem(context);
+ goto out;
+ }
+ }
+
+ if (kt->type == KRB5_ENCTYPE_OLD_DES3_CBC_SHA1)
+ _krb5_DES3_random_to_key(context, key->key, k, nblocks * et->blocksize);
+ else
+ memcpy(key->key->keyvalue.data, k, key->key->keyvalue.length);
+
+ out:
+ if (k) {
+ memset_s(k, nblocks * et->blocksize, 0, nblocks * et->blocksize);
+ free(k);
+ }
+ return ret;
+}
+
+static krb5_error_code
+derive_key_sp800_hmac(krb5_context context,
+ struct _krb5_encryption_type *et,
+ struct _krb5_key_data *key,
+ const void *constant,
+ size_t len)
+{
+ krb5_error_code ret;
+ struct _krb5_key_type *kt = et->keytype;
+ krb5_data label;
+ const EVP_MD *md = NULL;
+ const unsigned char *c = constant;
+ size_t key_len;
+ krb5_data K1;
+
+ ret = _krb5_aes_sha2_md_for_enctype(context, kt->type, &md);
+ if (ret)
+ return ret;
+
+ /*
+ * PRF usage: not handled here (output cannot be longer)
+ * Integrity usage: truncated hash (half length)
+ * Encryption usage: base key length
+ */
+ if (len == 5 && (c[4] == 0x99 || c[4] == 0x55))
+ key_len = EVP_MD_size(md) / 2;
+ else
+ key_len = kt->size;
+
+ ret = krb5_data_alloc(&K1, key_len);
+ if (ret)
+ return ret;
+
+ label.data = (void *)constant;
+ label.length = len;
+
+ ret = _krb5_SP800_108_HMAC_KDF(context, &key->key->keyvalue,
+ &label, NULL, md, &K1);
+ if (ret == 0) {
+ if (key->key->keyvalue.length > key_len)
+ key->key->keyvalue.length = key_len;
+ memcpy(key->key->keyvalue.data, K1.data, key_len);
+ }
+
+ memset_s(K1.data, K1.length, 0, K1.length);
+ krb5_data_free(&K1);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_derive_key(krb5_context context,
+ struct _krb5_encryption_type *et,
+ struct _krb5_key_data *key,
+ const void *constant,
+ size_t len)
+{
+ krb5_error_code ret;
+
+ ret = _key_schedule(context, key);
+ if(ret)
+ return ret;
+
+ switch (et->flags & F_KDF_MASK) {
+ case F_RFC3961_KDF:
+ ret = derive_key_rfc3961(context, et, key, constant, len);
+ break;
+ case F_SP800_108_HMAC_KDF:
+ ret = derive_key_sp800_hmac(context, et, key, constant, len);
+ break;
+ default:
+ ret = KRB5_CRYPTO_INTERNAL;
+ krb5_set_error_message(context, ret,
+ N_("derive_key() called with unknown keytype (%u)", ""),
+ et->keytype->type);
+ break;
+ }
+
+ if (key->schedule) {
+ free_key_schedule(context, key, et);
+ key->schedule = NULL;
+ }
+
+ return ret;
+}
+
+static struct _krb5_key_data *
+_new_derived_key(krb5_crypto crypto, unsigned usage)
+{
+ struct _krb5_key_usage *d = crypto->key_usage;
+ d = realloc(d, (crypto->num_key_usage + 1) * sizeof(*d));
+ if(d == NULL)
+ return NULL;
+ crypto->key_usage = d;
+ d += crypto->num_key_usage++;
+ memset(d, 0, sizeof(*d));
+ d->usage = usage;
+ return &d->key;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_derive_key(krb5_context context,
+ const krb5_keyblock *key,
+ krb5_enctype etype,
+ const void *constant,
+ size_t constant_len,
+ krb5_keyblock **derived_key)
+{
+ krb5_error_code ret;
+ struct _krb5_encryption_type *et;
+ struct _krb5_key_data d;
+
+ *derived_key = NULL;
+
+ et = _krb5_find_enctype (etype);
+ if (et == NULL) {
+ return unsupported_enctype (context, etype);
+ }
+
+ ret = krb5_copy_keyblock(context, key, &d.key);
+ if (ret)
+ return ret;
+
+ d.schedule = NULL;
+ ret = _krb5_derive_key(context, et, &d, constant, constant_len);
+ if (ret == 0)
+ ret = krb5_copy_keyblock(context, d.key, derived_key);
+ _krb5_free_key_data(context, &d, et);
+ return ret;
+}
+
+static krb5_error_code
+_get_derived_key(krb5_context context,
+ krb5_crypto crypto,
+ unsigned usage,
+ struct _krb5_key_data **key)
+{
+ int i;
+ struct _krb5_key_data *d;
+ unsigned char constant[5];
+
+ *key = NULL;
+ for(i = 0; i < crypto->num_key_usage; i++)
+ if(crypto->key_usage[i].usage == usage) {
+ *key = &crypto->key_usage[i].key;
+ return 0;
+ }
+ d = _new_derived_key(crypto, usage);
+ if (d == NULL)
+ return krb5_enomem(context);
+ *key = d;
+ krb5_copy_keyblock(context, crypto->key.key, &d->key);
+ _krb5_put_int(constant, usage, sizeof(constant));
+ return _krb5_derive_key(context, crypto->et, d, constant, sizeof(constant));
+}
+
+/**
+ * Create a crypto context used for all encryption and signature
+ * operation. The encryption type to use is taken from the key, but
+ * can be overridden with the enctype parameter. This can be useful
+ * for encryptions types which is compatiable (DES for example).
+ *
+ * To free the crypto context, use krb5_crypto_destroy().
+ *
+ * @param context Kerberos context
+ * @param key the key block information with all key data
+ * @param etype the encryption type
+ * @param crypto the resulting crypto context
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_init(krb5_context context,
+ const krb5_keyblock *key,
+ krb5_enctype etype,
+ krb5_crypto *crypto)
+{
+ krb5_error_code ret;
+ ALLOC(*crypto, 1);
+ if (*crypto == NULL)
+ return krb5_enomem(context);
+ if(etype == ETYPE_NULL)
+ etype = key->keytype;
+ (*crypto)->et = _krb5_find_enctype(etype);
+ if((*crypto)->et == NULL || ((*crypto)->et->flags & F_DISABLED)) {
+ free(*crypto);
+ *crypto = NULL;
+ return unsupported_enctype(context, etype);
+ }
+ if((*crypto)->et->keytype->size != key->keyvalue.length) {
+ free(*crypto);
+ *crypto = NULL;
+ krb5_set_error_message (context, KRB5_BAD_KEYSIZE,
+ "encryption key has bad length");
+ return KRB5_BAD_KEYSIZE;
+ }
+ ret = krb5_copy_keyblock(context, key, &(*crypto)->key.key);
+ if(ret) {
+ free(*crypto);
+ *crypto = NULL;
+ return ret;
+ }
+ (*crypto)->key.schedule = NULL;
+ (*crypto)->num_key_usage = 0;
+ (*crypto)->key_usage = NULL;
+ (*crypto)->flags = 0;
+ return 0;
+}
+
+static void
+free_key_schedule(krb5_context context,
+ struct _krb5_key_data *key,
+ struct _krb5_encryption_type *et)
+{
+ if (et->keytype->cleanup)
+ (*et->keytype->cleanup)(context, key);
+ memset(key->schedule->data, 0, key->schedule->length);
+ krb5_free_data(context, key->schedule);
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_free_key_data(krb5_context context, struct _krb5_key_data *key,
+ struct _krb5_encryption_type *et)
+{
+ krb5_free_keyblock(context, key->key);
+ if(key->schedule) {
+ free_key_schedule(context, key, et);
+ key->schedule = NULL;
+ }
+}
+
+static void
+free_key_usage(krb5_context context, struct _krb5_key_usage *ku,
+ struct _krb5_encryption_type *et)
+{
+ _krb5_free_key_data(context, &ku->key, et);
+}
+
+/**
+ * Free a crypto context created by krb5_crypto_init().
+ *
+ * @param context Kerberos context
+ * @param crypto crypto context to free
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_destroy(krb5_context context,
+ krb5_crypto crypto)
+{
+ int i;
+
+ for(i = 0; i < crypto->num_key_usage; i++)
+ free_key_usage(context, &crypto->key_usage[i], crypto->et);
+ free(crypto->key_usage);
+ _krb5_free_key_data(context, &crypto->key, crypto->et);
+
+ if (crypto->mdctx)
+ EVP_MD_CTX_destroy(crypto->mdctx);
+
+ if (crypto->hmacctx)
+ HMAC_CTX_free(crypto->hmacctx);
+
+ free (crypto);
+ return 0;
+}
+
+/**
+ * Return the blocksize used algorithm referenced by the crypto context
+ *
+ * @param context Kerberos context
+ * @param crypto crypto context to query
+ * @param blocksize the resulting blocksize
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_getblocksize(krb5_context context,
+ krb5_crypto crypto,
+ size_t *blocksize)
+{
+ *blocksize = crypto->et->blocksize;
+ return 0;
+}
+
+/**
+ * Return the encryption type used by the crypto context
+ *
+ * @param context Kerberos context
+ * @param crypto crypto context to query
+ * @param enctype the resulting encryption type
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_getenctype(krb5_context context,
+ krb5_crypto crypto,
+ krb5_enctype *enctype)
+{
+ *enctype = crypto->et->type;
+ return 0;
+}
+
+/**
+ * Return the padding size used by the crypto context
+ *
+ * @param context Kerberos context
+ * @param crypto crypto context to query
+ * @param padsize the return padding size
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_getpadsize(krb5_context context,
+ krb5_crypto crypto,
+ size_t *padsize)
+{
+ *padsize = crypto->et->padsize;
+ return 0;
+}
+
+/**
+ * Return the confounder size used by the crypto context
+ *
+ * @param context Kerberos context
+ * @param crypto crypto context to query
+ * @param confoundersize the returned confounder size
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_getconfoundersize(krb5_context context,
+ krb5_crypto crypto,
+ size_t *confoundersize)
+{
+ *confoundersize = crypto->et->confoundersize;
+ return 0;
+}
+
+
+/**
+ * Disable encryption type
+ *
+ * @param context Kerberos 5 context
+ * @param enctype encryption type to disable
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_enctype_disable(krb5_context context,
+ krb5_enctype enctype)
+{
+ struct _krb5_encryption_type *et = _krb5_find_enctype(enctype);
+ if(et == NULL) {
+ if (context)
+ krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("encryption type %d not supported", ""),
+ enctype);
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ et->flags |= F_DISABLED;
+ return 0;
+}
+
+/**
+ * Enable encryption type
+ *
+ * @param context Kerberos 5 context
+ * @param enctype encryption type to enable
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_enctype_enable(krb5_context context,
+ krb5_enctype enctype)
+{
+ struct _krb5_encryption_type *et = _krb5_find_enctype(enctype);
+ if(et == NULL) {
+ if (context)
+ krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("encryption type %d not supported", ""),
+ enctype);
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ et->flags &= ~F_DISABLED;
+ return 0;
+}
+
+/**
+ * Enable or disable all weak encryption types
+ *
+ * @param context Kerberos 5 context
+ * @param enable true to enable, false to disable
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_allow_weak_crypto(krb5_context context,
+ krb5_boolean enable)
+{
+ int i;
+
+ for(i = 0; i < _krb5_num_etypes; i++)
+ if(_krb5_etypes[i]->flags & F_WEAK) {
+ if(enable)
+ _krb5_etypes[i]->flags &= ~F_DISABLED;
+ else
+ _krb5_etypes[i]->flags |= F_DISABLED;
+ }
+ return 0;
+}
+
+/**
+ * Returns is the encryption is strong or weak
+ *
+ * @param context Kerberos 5 context
+ * @param enctype encryption type to probe
+ *
+ * @return Returns true if encryption type is weak or is not supported.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_is_enctype_weak(krb5_context context, krb5_enctype enctype)
+{
+ struct _krb5_encryption_type *et = _krb5_find_enctype(enctype);
+ if(et == NULL || (et->flags & F_WEAK))
+ return TRUE;
+ return FALSE;
+}
+
+/**
+ * Returns whether the encryption type is new or old
+ *
+ * @param context Kerberos 5 context
+ * @param enctype encryption type to probe
+ *
+ * @return Returns true if encryption type is old or is not supported.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_is_enctype_old(krb5_context context, krb5_enctype enctype)
+{
+ struct _krb5_encryption_type *et = _krb5_find_enctype(enctype);
+ if (!et || (et->flags & F_OLD))
+ return TRUE;
+ return FALSE;
+}
+
+/**
+ * Returns whether the encryption type should use randomly generated salts
+ *
+ * @param context Kerberos 5 context
+ * @param enctype encryption type to probe
+ *
+ * @return Returns true if generated salts should have random component
+ *
+ * @ingroup krb5_crypto
+ */
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+_krb5_enctype_requires_random_salt(krb5_context context,
+ krb5_enctype enctype)
+{
+ struct _krb5_encryption_type *et;
+
+ et = _krb5_find_enctype (enctype);
+
+ return et && (et->flags & F_SP800_108_HMAC_KDF);
+}
+
+static size_t
+wrapped_length (krb5_context context,
+ krb5_crypto crypto,
+ size_t data_len)
+{
+ struct _krb5_encryption_type *et = crypto->et;
+ size_t padsize = et->padsize;
+ size_t checksumsize = CHECKSUMSIZE(et->checksum);
+ size_t res;
+
+ res = et->confoundersize + checksumsize + data_len;
+ res = (res + padsize - 1) / padsize * padsize;
+ return res;
+}
+
+static size_t
+wrapped_length_dervied (krb5_context context,
+ krb5_crypto crypto,
+ size_t data_len)
+{
+ struct _krb5_encryption_type *et = crypto->et;
+ size_t padsize = et->padsize;
+ size_t res;
+
+ res = et->confoundersize + data_len;
+ res = (res + padsize - 1) / padsize * padsize;
+ if (et->keyed_checksum)
+ res += et->keyed_checksum->checksumsize;
+ else
+ res += et->checksum->checksumsize;
+ return res;
+}
+
+/*
+ * Return the size of an encrypted packet of length `data_len'
+ */
+
+KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL
+krb5_get_wrapped_length (krb5_context context,
+ krb5_crypto crypto,
+ size_t data_len)
+{
+ if (derived_crypto (context, crypto))
+ return wrapped_length_dervied (context, crypto, data_len);
+ else
+ return wrapped_length (context, crypto, data_len);
+}
+
+/*
+ * Return the size of an encrypted packet of length `data_len'
+ */
+
+static size_t
+crypto_overhead (krb5_context context,
+ krb5_crypto crypto)
+{
+ struct _krb5_encryption_type *et = crypto->et;
+ size_t res;
+
+ res = CHECKSUMSIZE(et->checksum);
+ res += et->confoundersize;
+ if (et->padsize > 1)
+ res += et->padsize;
+ return res;
+}
+
+static size_t
+crypto_overhead_dervied (krb5_context context,
+ krb5_crypto crypto)
+{
+ struct _krb5_encryption_type *et = crypto->et;
+ size_t res;
+
+ if (et->keyed_checksum)
+ res = CHECKSUMSIZE(et->keyed_checksum);
+ else
+ res = CHECKSUMSIZE(et->checksum);
+ res += et->confoundersize;
+ if (et->padsize > 1)
+ res += et->padsize;
+ return res;
+}
+
+KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL
+krb5_crypto_overhead (krb5_context context, krb5_crypto crypto)
+{
+ if (derived_crypto (context, crypto))
+ return crypto_overhead_dervied (context, crypto);
+ else
+ return crypto_overhead (context, crypto);
+}
+
+/**
+ * Converts the random bytestring to a protocol key according to
+ * Kerberos crypto frame work. It may be assumed that all the bits of
+ * the input string are equally random, even though the entropy
+ * present in the random source may be limited.
+ *
+ * @param context Kerberos 5 context
+ * @param type the enctype resulting key will be of
+ * @param data input random data to convert to a key
+ * @param size size of input random data, at least krb5_enctype_keysize() long
+ * @param key key, output key, free with krb5_free_keyblock_contents()
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_random_to_key(krb5_context context,
+ krb5_enctype type,
+ const void *data,
+ size_t size,
+ krb5_keyblock *key)
+{
+ krb5_error_code ret;
+ struct _krb5_encryption_type *et = _krb5_find_enctype(type);
+ if(et == NULL) {
+ krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("encryption type %d not supported", ""),
+ type);
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ if ((et->keytype->bits + 7) / 8 > size) {
+ krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("encryption key %s needs %d bytes "
+ "of random to make an encryption key "
+ "out of it", ""),
+ et->name, (int)et->keytype->size);
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ ret = krb5_data_alloc(&key->keyvalue, et->keytype->size);
+ if(ret)
+ return ret;
+ key->keytype = type;
+ if (et->keytype->random_to_key)
+ (*et->keytype->random_to_key)(context, key, data, size);
+ else
+ memcpy(key->keyvalue.data, data, et->keytype->size);
+
+ return 0;
+}
+
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_prf_length(krb5_context context,
+ krb5_enctype type,
+ size_t *length)
+{
+ struct _krb5_encryption_type *et = _krb5_find_enctype(type);
+
+ if(et == NULL || et->prf_length == 0) {
+ krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("encryption type %d not supported", ""),
+ type);
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+
+ *length = et->prf_length;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_prf(krb5_context context,
+ const krb5_crypto crypto,
+ const krb5_data *input,
+ krb5_data *output)
+{
+ struct _krb5_encryption_type *et = crypto->et;
+
+ krb5_data_zero(output);
+
+ if(et->prf == NULL) {
+ krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+ "kerberos prf for %s not supported",
+ et->name);
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+
+ return (*et->prf)(context, crypto, input, output);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_prfplus(krb5_context context,
+ const krb5_crypto crypto,
+ const krb5_data *input,
+ size_t length,
+ krb5_data *output)
+{
+ krb5_error_code ret;
+ krb5_data input2;
+ unsigned char i = 1;
+ unsigned char *p;
+
+ krb5_data_zero(&input2);
+ krb5_data_zero(output);
+
+ krb5_clear_error_message(context);
+
+ ret = krb5_data_alloc(output, length);
+ if (ret) goto out;
+ ret = krb5_data_alloc(&input2, input->length + 1);
+ if (ret) goto out;
+
+ krb5_clear_error_message(context);
+
+ memcpy(((unsigned char *)input2.data) + 1, input->data, input->length);
+
+ p = output->data;
+
+ while (length) {
+ krb5_data block;
+
+ ((unsigned char *)input2.data)[0] = i++;
+
+ ret = krb5_crypto_prf(context, crypto, &input2, &block);
+ if (ret)
+ goto out;
+
+ if (block.length < length) {
+ memcpy(p, block.data, block.length);
+ length -= block.length;
+ } else {
+ memcpy(p, block.data, length);
+ length = 0;
+ }
+ p += block.length;
+ krb5_data_free(&block);
+ }
+
+ out:
+ krb5_data_free(&input2);
+ if (ret)
+ krb5_data_free(output);
+ return ret;
+}
+
+/**
+ * The FX-CF2 key derivation function, used in FAST and preauth framework.
+ *
+ * @param context Kerberos 5 context
+ * @param crypto1 first key to combine
+ * @param crypto2 second key to combine
+ * @param pepper1 factor to combine with first key to garante uniqueness
+ * @param pepper2 factor to combine with second key to garante uniqueness
+ * @param enctype the encryption type of the resulting key
+ * @param res allocated key, free with krb5_free_keyblock_contents()
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_fx_cf2(krb5_context context,
+ const krb5_crypto crypto1,
+ const krb5_crypto crypto2,
+ krb5_data *pepper1,
+ krb5_data *pepper2,
+ krb5_enctype enctype,
+ krb5_keyblock *res)
+{
+ krb5_error_code ret;
+ krb5_data os1, os2;
+ size_t i, keysize;
+
+ memset(res, 0, sizeof(*res));
+ krb5_data_zero(&os1);
+ krb5_data_zero(&os2);
+
+ ret = krb5_enctype_keybits(context, enctype, &keysize);
+ if (ret)
+ return ret;
+ keysize = (keysize + 7) / 8;
+
+ ret = krb5_crypto_prfplus(context, crypto1, pepper1, keysize, &os1);
+ if (ret)
+ goto out;
+ ret = krb5_crypto_prfplus(context, crypto2, pepper2, keysize, &os2);
+ if (ret)
+ goto out;
+
+ res->keytype = enctype;
+ {
+ unsigned char *p1 = os1.data, *p2 = os2.data;
+ for (i = 0; i < keysize; i++)
+ p1[i] ^= p2[i];
+ }
+ ret = krb5_random_to_key(context, enctype, os1.data, keysize, res);
+ out:
+ krb5_data_free(&os1);
+ krb5_data_free(&os2);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_crypto_set_flags(krb5_context context,
+ krb5_crypto crypto,
+ krb5_flags flags)
+{
+ crypto->flags |= flags;
+}
+
+#ifndef HEIMDAL_SMALLER
+
+/**
+ * Deprecated: keytypes doesn't exists, they are really enctypes.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_keytype_to_enctypes (krb5_context context,
+ krb5_keytype keytype,
+ unsigned *len,
+ krb5_enctype **val)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ int i;
+ unsigned n = 0;
+ krb5_enctype *ret;
+
+ for (i = _krb5_num_etypes - 1; i >= 0; --i) {
+ if (_krb5_etypes[i]->keytype->type == keytype
+ && !(_krb5_etypes[i]->flags & F_PSEUDO)
+ && krb5_enctype_valid(context, _krb5_etypes[i]->type) == 0)
+ ++n;
+ }
+ if (n == 0) {
+ krb5_set_error_message(context, KRB5_PROG_KEYTYPE_NOSUPP,
+ "Keytype have no mapping");
+ return KRB5_PROG_KEYTYPE_NOSUPP;
+ }
+
+ ret = malloc(n * sizeof(*ret));
+ if (ret == NULL && n != 0)
+ return krb5_enomem(context);
+ n = 0;
+ for (i = _krb5_num_etypes - 1; i >= 0; --i) {
+ if (_krb5_etypes[i]->keytype->type == keytype
+ && !(_krb5_etypes[i]->flags & F_PSEUDO)
+ && krb5_enctype_valid(context, _krb5_etypes[i]->type) == 0)
+ ret[n++] = _krb5_etypes[i]->type;
+ }
+ *len = n;
+ *val = ret;
+ return 0;
+}
+
+/**
+ * Deprecated: keytypes doesn't exists, they are really enctypes.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+/* if two enctypes have compatible keys */
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_enctypes_compatible_keys(krb5_context context,
+ krb5_enctype etype1,
+ krb5_enctype etype2)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ struct _krb5_encryption_type *e1 = _krb5_find_enctype(etype1);
+ struct _krb5_encryption_type *e2 = _krb5_find_enctype(etype2);
+ return e1 != NULL && e2 != NULL && e1->keytype == e2->keytype;
+}
+
+#endif /* HEIMDAL_SMALLER */
diff --git a/third_party/heimdal/lib/krb5/crypto.h b/third_party/heimdal/lib/krb5/crypto.h
new file mode 100644
index 0000000..d02f841
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/crypto.h
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) 1997 - 2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef HEIMDAL_SMALLER
+#define DES3_OLD_ENCTYPE 1
+#endif
+
+struct _krb5_key_data {
+ krb5_keyblock *key;
+ krb5_data *schedule;
+};
+
+struct _krb5_key_usage;
+
+#define CRYPTO_ETYPE(C) ((C)->et->type)
+
+/* bits for `flags' below */
+#define F_KEYED 0x0001 /* checksum is keyed */
+#define F_CPROOF 0x0002 /* checksum is collision proof */
+#define F_DERIVED 0x0004 /* uses derived keys */
+#define F_VARIANT 0x0008 /* uses `variant' keys (6.4.3) */
+#define F_PSEUDO 0x0010 /* not a real protocol type */
+#define F_DISABLED 0x0020 /* enctype/checksum disabled */
+#define F_WEAK 0x0040 /* enctype is considered weak */
+#define F_OLD 0x0080 /* enctype is old */
+
+#define F_RFC3961_ENC 0x0100 /* RFC3961 simplified profile */
+#define F_SPECIAL 0x0200 /* backwards */
+#define F_ENC_THEN_CKSUM 0x0400 /* checksum is over encrypted data */
+#define F_CRYPTO_MASK 0x0F00
+
+#define F_RFC3961_KDF 0x1000 /* RFC3961 KDF */
+#define F_SP800_108_HMAC_KDF 0x2000 /* SP800-108 HMAC KDF */
+#define F_KDF_MASK 0xF000
+
+struct salt_type {
+ krb5_salttype type;
+ const char *name;
+ krb5_error_code (*string_to_key)(krb5_context, krb5_enctype, krb5_data,
+ krb5_salt, krb5_data, krb5_keyblock*);
+};
+
+struct _krb5_key_type {
+ krb5_enctype type;
+ const char *name;
+ size_t bits;
+ size_t size;
+ size_t schedule_size;
+ void (*random_key)(krb5_context, krb5_keyblock*);
+ void (*schedule)(krb5_context, struct _krb5_key_type *, struct _krb5_key_data *);
+ struct salt_type *string_to_key;
+ void (*random_to_key)(krb5_context, krb5_keyblock*, const void*, size_t);
+ void (*cleanup)(krb5_context, struct _krb5_key_data *);
+ const EVP_CIPHER *(*evp)(void);
+};
+
+struct _krb5_checksum_type {
+ krb5_cksumtype type;
+ const char *name;
+ size_t blocksize;
+ size_t checksumsize;
+ unsigned flags;
+ krb5_error_code (*checksum)(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov, int niov,
+ Checksum *csum);
+ krb5_error_code (*verify)(krb5_context context,
+ krb5_crypto crypto,
+ struct _krb5_key_data *key,
+ unsigned usage,
+ const struct krb5_crypto_iov *iov, int niov,
+ Checksum *csum);
+};
+
+struct _krb5_encryption_type {
+ krb5_enctype type;
+ const char *name;
+ const char *alias;
+ size_t blocksize;
+ size_t padsize;
+ size_t confoundersize;
+ struct _krb5_key_type *keytype;
+ struct _krb5_checksum_type *checksum;
+ struct _krb5_checksum_type *keyed_checksum;
+ unsigned flags;
+ krb5_error_code (*encrypt)(krb5_context context,
+ struct _krb5_key_data *key,
+ void *data, size_t len,
+ krb5_boolean encryptp,
+ int usage,
+ void *ivec);
+ krb5_error_code (*encrypt_iov)(krb5_context context,
+ struct _krb5_key_data *key,
+ krb5_crypto_iov *iov, int niov,
+ krb5_boolean encryptp,
+ int usage,
+ void *ivec);
+ size_t prf_length;
+ krb5_error_code (*prf)(krb5_context,
+ krb5_crypto, const krb5_data *, krb5_data *);
+};
+
+#define ENCRYPTION_USAGE(U) (((uint32_t)(U) << 8) | 0xAA)
+#define INTEGRITY_USAGE(U) (((uint32_t)(U) << 8) | 0x55)
+#define CHECKSUM_USAGE(U) (((uint32_t)(U) << 8) | 0x99)
+
+/* Checksums */
+
+extern struct _krb5_checksum_type _krb5_checksum_none;
+extern struct _krb5_checksum_type _krb5_checksum_crc32;
+extern struct _krb5_checksum_type _krb5_checksum_rsa_md4;
+extern struct _krb5_checksum_type _krb5_checksum_rsa_md4_des;
+extern struct _krb5_checksum_type _krb5_checksum_rsa_md5_des;
+extern struct _krb5_checksum_type _krb5_checksum_rsa_md5_des3;
+extern struct _krb5_checksum_type _krb5_checksum_rsa_md5;
+extern struct _krb5_checksum_type _krb5_checksum_hmac_sha1_des3;
+extern struct _krb5_checksum_type _krb5_checksum_hmac_sha1_aes128;
+extern struct _krb5_checksum_type _krb5_checksum_hmac_sha1_aes256;
+extern struct _krb5_checksum_type _krb5_checksum_hmac_sha256_128_aes128;
+extern struct _krb5_checksum_type _krb5_checksum_hmac_sha384_192_aes256;
+extern struct _krb5_checksum_type _krb5_checksum_hmac_md5;
+extern struct _krb5_checksum_type _krb5_checksum_sha1;
+extern struct _krb5_checksum_type _krb5_checksum_sha256;
+extern struct _krb5_checksum_type _krb5_checksum_sha384;
+extern struct _krb5_checksum_type _krb5_checksum_sha512;
+
+extern struct _krb5_checksum_type *_krb5_checksum_types[];
+extern int _krb5_num_checksums;
+
+/* Salts */
+
+extern struct salt_type _krb5_AES_SHA1_salt[];
+extern struct salt_type _krb5_AES_SHA2_salt[];
+extern struct salt_type _krb5_arcfour_salt[];
+extern struct salt_type _krb5_des_salt[];
+extern struct salt_type _krb5_des3_salt[];
+extern struct salt_type _krb5_des3_salt_derived[];
+
+/* Encryption types */
+
+extern struct _krb5_encryption_type _krb5_enctype_aes256_cts_hmac_sha1;
+extern struct _krb5_encryption_type _krb5_enctype_aes128_cts_hmac_sha1;
+extern struct _krb5_encryption_type _krb5_enctype_aes128_cts_hmac_sha256_128;
+extern struct _krb5_encryption_type _krb5_enctype_aes256_cts_hmac_sha384_192;
+extern struct _krb5_encryption_type _krb5_enctype_des3_cbc_sha1;
+extern struct _krb5_encryption_type _krb5_enctype_des3_cbc_md5;
+extern struct _krb5_encryption_type _krb5_enctype_des3_cbc_none;
+extern struct _krb5_encryption_type _krb5_enctype_arcfour_hmac_md5;
+extern struct _krb5_encryption_type _krb5_enctype_des_cbc_md5;
+extern struct _krb5_encryption_type _krb5_enctype_old_des3_cbc_sha1;
+extern struct _krb5_encryption_type _krb5_enctype_des_cbc_crc;
+extern struct _krb5_encryption_type _krb5_enctype_des_cbc_md4;
+extern struct _krb5_encryption_type _krb5_enctype_des_cbc_md5;
+extern struct _krb5_encryption_type _krb5_enctype_des_cbc_none;
+extern struct _krb5_encryption_type _krb5_enctype_des_cfb64_none;
+extern struct _krb5_encryption_type _krb5_enctype_des_pcbc_none;
+extern struct _krb5_encryption_type _krb5_enctype_null;
+
+extern struct _krb5_encryption_type *_krb5_etypes[];
+extern int _krb5_num_etypes;
+
+static inline int
+_krb5_crypto_iov_should_sign(const struct krb5_crypto_iov *iov)
+{
+ return (iov->flags == KRB5_CRYPTO_TYPE_DATA
+ || iov->flags == KRB5_CRYPTO_TYPE_SIGN_ONLY
+ || iov->flags == KRB5_CRYPTO_TYPE_HEADER
+ || iov->flags == KRB5_CRYPTO_TYPE_PADDING);
+}
+
+/* NO_HCRYPTO_POLLUTION is defined in pkinit-ec.c. See commentary there. */
+#ifndef NO_HCRYPTO_POLLUTION
+/* Interface to the EVP crypto layer provided by hcrypto */
+struct _krb5_evp_schedule {
+ /*
+ * Normally we'd say EVP_CIPHER_CTX here, but! this header gets
+ * included in lib/krb5/pkinit-ec.c
+ */
+ EVP_CIPHER_CTX ectx;
+ EVP_CIPHER_CTX dctx;
+};
+
+struct krb5_crypto_data {
+ struct _krb5_encryption_type *et;
+ struct _krb5_key_data key;
+ EVP_MD_CTX *mdctx;
+ HMAC_CTX *hmacctx;
+ int num_key_usage;
+ struct _krb5_key_usage *key_usage;
+ krb5_flags flags;
+};
+
+/*
+ * Allow generation and verification of unkeyed checksums even when
+ * key material is available.
+ */
+#define KRB5_CRYPTO_FLAG_ALLOW_UNKEYED_CHECKSUM 0x01
+
+#endif
diff --git a/third_party/heimdal/lib/krb5/data.c b/third_party/heimdal/lib/krb5/data.c
new file mode 100644
index 0000000..abfa053
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/data.c
@@ -0,0 +1,228 @@
+/*
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ * Reset the (potentially uninitialized) krb5_data structure.
+ *
+ * @param p krb5_data to reset.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_data_zero(krb5_data *p)
+{
+ p->length = 0;
+ p->data = NULL;
+}
+
+/**
+ * Free the content of krb5_data structure, its ok to free a zeroed
+ * structure (with memset() or krb5_data_zero()). When done, the
+ * structure will be zeroed. The same function is called
+ * krb5_free_data_contents() in MIT Kerberos.
+ *
+ * @param p krb5_data to free.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_data_free(krb5_data *p)
+{
+ free(p->data);
+ krb5_data_zero(p);
+}
+
+/**
+ * Free krb5_data (and its content).
+ *
+ * @param context Kerberos 5 context.
+ * @param p krb5_data to free.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_data(krb5_context context,
+ krb5_data *p)
+{
+ krb5_data_free(p);
+ free(p);
+}
+
+/**
+ * Allocate data of and krb5_data.
+ *
+ * @param p krb5_data to allocate.
+ * @param len size to allocate.
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_data_alloc(krb5_data *p, int len)
+{
+ p->data = malloc(len);
+ if(len && p->data == NULL)
+ return ENOMEM;
+ p->length = len;
+ return 0;
+}
+
+/**
+ * Grow (or shrink) the content of krb5_data to a new size.
+ *
+ * @param p krb5_data to free.
+ * @param len new size.
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_data_realloc(krb5_data *p, int len)
+{
+ void *tmp;
+ tmp = realloc(p->data, len);
+ if(len && !tmp)
+ return ENOMEM;
+ p->data = tmp;
+ p->length = len;
+ return 0;
+}
+
+/**
+ * Copy the data of len into the krb5_data.
+ *
+ * @param p krb5_data to copy into.
+ * @param data data to copy..
+ * @param len new size.
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_data_copy(krb5_data *p, const void *data, size_t len)
+{
+ if (len) {
+ if(krb5_data_alloc(p, len))
+ return ENOMEM;
+ memcpy(p->data, data, len);
+ } else
+ p->data = NULL;
+ p->length = len;
+ return 0;
+}
+
+/**
+ * Copy the data into a newly allocated krb5_data.
+ *
+ * @param context Kerberos 5 context.
+ * @param indata the krb5_data data to copy
+ * @param outdata new krb5_date to copy too. Free with krb5_free_data().
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_data(krb5_context context,
+ const krb5_data *indata,
+ krb5_data **outdata)
+{
+ krb5_error_code ret;
+ ALLOC(*outdata, 1);
+ if(*outdata == NULL)
+ return krb5_enomem(context);
+ ret = der_copy_octet_string(indata, *outdata);
+ if(ret) {
+ krb5_clear_error_message (context);
+ free(*outdata);
+ *outdata = NULL;
+ }
+ return ret;
+}
+
+/**
+ * Compare to data.
+ *
+ * @param data1 krb5_data to compare
+ * @param data2 krb5_data to compare
+ *
+ * @return return the same way as memcmp(), useful when sorting.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_data_cmp(const krb5_data *data1, const krb5_data *data2)
+{
+ size_t len = data1->length < data2->length ? data1->length : data2->length;
+ int cmp = memcmp(data1->data, data2->data, len);
+
+ if (cmp == 0)
+ return data1->length - data2->length;
+ return cmp;
+}
+
+/**
+ * Compare to data not exposing timing information from the checksum data
+ *
+ * @param data1 krb5_data to compare
+ * @param data2 krb5_data to compare
+ *
+ * @return returns zero for same data, otherwise non zero.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_data_ct_cmp(const krb5_data *data1, const krb5_data *data2)
+{
+ if (data1->length != data2->length)
+ return data1->length - data2->length;
+ return ct_memcmp(data1->data, data2->data, data1->length);
+}
diff --git a/third_party/heimdal/lib/krb5/db_plugin.c b/third_party/heimdal/lib/krb5/db_plugin.c
new file mode 100644
index 0000000..2933bd8
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/db_plugin.c
@@ -0,0 +1,41 @@
+/*
+ */
+
+#include "krb5_locl.h"
+#include "db_plugin.h"
+
+/* Default plugin (DB using binary search of sorted text file) follows */
+static heim_base_once_t db_plugins_once = HEIM_BASE_ONCE_INIT;
+
+static krb5_error_code KRB5_LIB_CALL
+db_plugins_plcallback(krb5_context context, const void *plug, void *plugctx,
+ void *userctx)
+{
+ return 0;
+}
+
+static const char *db_plugin_deps[] = { "krb5", NULL };
+
+static struct heim_plugin_data
+db_plugin_data = {
+ "krb5",
+ KRB5_PLUGIN_DB,
+ KRB5_PLUGIN_DB_VERSION_0,
+ db_plugin_deps,
+ krb5_get_instance
+};
+
+static void
+db_plugins_init(void *arg)
+{
+ krb5_context context = arg;
+ (void)_krb5_plugin_run_f(context, &db_plugin_data, 0, NULL,
+ db_plugins_plcallback);
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_load_db_plugins(krb5_context context)
+{
+ heim_base_once_f(&db_plugins_once, context, db_plugins_init);
+}
+
diff --git a/third_party/heimdal/lib/krb5/db_plugin.h b/third_party/heimdal/lib/krb5/db_plugin.h
new file mode 100644
index 0000000..ab676d5
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/db_plugin.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2011, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIMDAL_KRB5_DB_PLUGIN_H
+#define HEIMDAL_KRB5_DB_PLUGIN_H 1
+
+#include <heimbase-svc.h>
+
+#define KRB5_PLUGIN_DB "krb5_db_plug"
+#define KRB5_PLUGIN_DB_VERSION_0 0
+
+/** @struct krb5plugin_db_ftable_desc
+ *
+ * @brief Description of the krb5 DB plugin facility.
+ *
+ * The krb5_aname_to_lname(3) function's DB rule is pluggable. The
+ * plugin is named KRB5_PLUGIN_DB ("krb5_db_plug"), with a single minor
+ * version, KRB5_PLUGIN_DB_VERSION_0 (0).
+ *
+ * The plugin consists of a data symbol referencing a structure of type
+ * krb5plugin_db_ftable_desc, with three fields:
+ *
+ * @param init Plugin initialization function (see krb5-plugin(7))
+ *
+ * @param minor_version The plugin minor version number (0)
+ *
+ * @param fini Plugin finalization function
+ *
+ * The init entry point is expected to call heim_db_register(). The
+ * fini entry point is expected to do nothing.
+ *
+ * @ingroup krb5_support
+ */
+typedef struct krb5plugin_db_ftable_desc {
+ HEIM_PLUGIN_FTABLE_COMMON_ELEMENTS(krb5_context);
+} krb5plugin_db_ftable;
+
+#endif /* HEIMDAL_KRB5_DB_PLUGIN_H */
+
diff --git a/third_party/heimdal/lib/krb5/dcache.c b/third_party/heimdal/lib/krb5/dcache.c
new file mode 100644
index 0000000..af88aed
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/dcache.c
@@ -0,0 +1,855 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+typedef struct krb5_dcache{
+ krb5_ccache fcache;
+ char *name;
+ char *dir;
+ char *sub;
+ unsigned int default_candidate:1;
+} krb5_dcache;
+
+#define DCACHE(X) ((krb5_dcache*)(X)->data.data)
+#define D2FCACHE(X) ((X)->fcache)
+
+static krb5_error_code KRB5_CALLCONV dcc_close(krb5_context, krb5_ccache);
+static krb5_error_code KRB5_CALLCONV dcc_get_default_name(krb5_context, char **);
+static krb5_error_code KRB5_CALLCONV dcc_set_default(krb5_context, krb5_ccache);
+
+/*
+ * Make subsidiary filesystem safe by mapping / and : to -. If the subsidiary
+ * is longer than 128 bytes, then truncate.
+ * In all cases, "tkt." is prefixed to be compatible with the DIR requirement
+ * that subsidiary ccache files be named tkt*.
+ *
+ * Thus host/foo.bar.baz@BAR.BAZ -> tkt.host-foo.bar.baz@BAR.BAZ.
+ *
+ * In particular, no filesystem component separators will be emitted, and . and
+ * .. will never be traversed.
+ */
+static krb5_error_code
+fs_encode_subsidiary(krb5_context context,
+ krb5_dcache *dc,
+ const char *subsidiary,
+ char **res)
+{
+ size_t len = strlen(subsidiary);
+ size_t i;
+
+ *res = NULL;
+ if (asprintf(res, "tkt.%s", subsidiary) == -1 || *res == NULL)
+ return krb5_enomem(context);
+ for (i = sizeof("tkt.") - 1; i < len; i++) {
+ switch ((*res)[i]) {
+#ifdef WIN32
+ case '\\': (*res)[0] = '-'; break;
+#endif
+ case '/': (*res)[0] = '-'; break;
+ case ':': (*res)[0] = '-'; break;
+ default: break;
+ }
+ }
+
+ /* Hopefully this will work on all filesystems */
+ if (len > 128 - sizeof("tkt.") - 1)
+ (*res)[127] = '\0';
+ return 0;
+}
+
+static char *
+primary_create(krb5_dcache *dc)
+{
+ char *primary = NULL;
+ int asprintf_ret = asprintf(&primary, "%s/primary", dc->dir);
+ if (asprintf_ret == -1 || primary == NULL) {
+ return NULL;
+ }
+
+ return primary;
+}
+
+static int
+is_filename_cacheish(const char *name)
+{
+ size_t i;
+
+ if (strncmp(name, "tkt", sizeof("tkt") - 1) != 0)
+ return 0;
+ for (i = sizeof("tkt") - 1; name[i]; i++)
+ if (ISPATHSEP(name[i]))
+ return 0;
+ return 1;
+}
+
+static krb5_error_code
+set_default_cache(krb5_context context, krb5_dcache *dc, const char *residual)
+{
+ char *path = NULL, *primary = NULL;
+ krb5_error_code ret;
+ struct iovec iov[2];
+ size_t len;
+ int fd = -1;
+ int asprintf_ret;
+
+ asprintf_ret = asprintf(&path, "%s/primary-XXXXXX", dc->dir);
+ if (asprintf_ret == -1 || path == NULL) {
+ return krb5_enomem(context);
+ }
+
+ fd = mkstemp(path);
+ if (fd < 0) {
+ ret = errno;
+ goto out;
+ }
+ rk_cloexec(fd);
+#ifndef _WIN32
+ if (fchmod(fd, S_IRUSR | S_IWUSR) < 0) {
+ ret = errno;
+ goto out;
+ }
+#endif
+ len = strlen(residual);
+
+ iov[0].iov_base = rk_UNCONST(residual);
+ iov[0].iov_len = len;
+ iov[1].iov_base = "\n";
+ iov[1].iov_len = 1;
+
+ if (writev(fd, iov, sizeof(iov)/sizeof(iov[0])) != len + 1) {
+ ret = errno;
+ goto out;
+ }
+
+ primary = primary_create(dc);
+ if (primary == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ if (rename(path, primary) < 0) {
+ ret = errno;
+ goto out;
+ }
+
+ close(fd);
+ fd = -1;
+
+ ret = 0;
+ out:
+ if (fd >= 0) {
+ (void)unlink(path);
+ close(fd);
+ }
+ if (path)
+ free(path);
+ if (primary)
+ free(primary);
+
+ return ret;
+}
+
+static krb5_error_code
+get_default_cache(krb5_context context, krb5_dcache *dc,
+ const char *subsidiary, char **residual)
+{
+ krb5_error_code ret;
+ char buf[MAXPATHLEN];
+ char *primary = NULL;
+ FILE *f;
+
+ *residual = NULL;
+ if (subsidiary)
+ return fs_encode_subsidiary(context, dc, subsidiary, residual);
+
+ primary = primary_create(dc);
+ if (primary == NULL)
+ return krb5_enomem(context);
+
+ f = fopen(primary, "r");
+ if (f == NULL) {
+ if (errno == ENOENT) {
+ free(primary);
+ *residual = strdup("tkt");
+ if (*residual == NULL)
+ return krb5_enomem(context);
+ return 0;
+ }
+ ret = errno;
+ krb5_set_error_message(context, ret, "failed to open %s", primary);
+ free(primary);
+ return ret;
+ }
+
+ if (fgets(buf, sizeof(buf), f) == NULL) {
+ ret = ferror(f);
+ fclose(f);
+ krb5_set_error_message(context, ret, "read file %s", primary);
+ free(primary);
+ return ret;
+ }
+ fclose(f);
+
+ buf[strcspn(buf, "\r\n")] = '\0';
+
+ if (!is_filename_cacheish(buf)) {
+ krb5_set_error_message(context, KRB5_CC_FORMAT,
+ "name in %s is not a cache (doesn't start with tkt)", primary);
+ free(primary);
+ return KRB5_CC_FORMAT;
+ }
+
+ free(primary);
+
+ *residual = strdup(buf);
+ if (*residual == NULL)
+ return krb5_enomem(context);
+
+ return 0;
+}
+
+
+
+static krb5_error_code KRB5_CALLCONV
+dcc_get_name_2(krb5_context context,
+ krb5_ccache id,
+ const char **name,
+ const char **dir,
+ const char **sub)
+{
+ krb5_dcache *dc = DCACHE(id);
+
+ if (name)
+ *name = dc->name;
+ if (dir)
+ *dir = dc->dir;
+ if (sub)
+ *sub = dc->sub;
+ return 0;
+}
+
+
+static krb5_error_code
+verify_directory(krb5_context context, const char *path)
+{
+ struct stat sb;
+
+ if (!path[0]) {
+ krb5_set_error_message(context, EINVAL,
+ N_("DIR empty directory component", ""));
+ return EINVAL;
+ }
+
+ if (stat(path, &sb) != 0) {
+ if (errno == ENOENT) {
+ /* XXX should use mkdirx_np() */
+ if (rk_mkdir(path, S_IRWXU) == 0)
+ return 0;
+
+ krb5_set_error_message(context, ENOENT,
+ N_("DIR directory %s doesn't exists", ""), path);
+ return ENOENT;
+ } else {
+ int ret = errno;
+ krb5_set_error_message(context, ret,
+ N_("DIR directory %s is bad: %s", ""), path, strerror(ret));
+ return errno;
+ }
+ }
+ if (!S_ISDIR(sb.st_mode)) {
+ krb5_set_error_message(context, KRB5_CC_BADNAME,
+ N_("DIR directory %s is not a directory", ""), path);
+ return KRB5_CC_BADNAME;
+ }
+
+ return 0;
+}
+
+static void
+dcc_release(krb5_context context, krb5_dcache *dc)
+{
+ if (dc->fcache)
+ krb5_cc_close(context, dc->fcache);
+ free(dc->sub);
+ free(dc->dir);
+ free(dc->name);
+ memset(dc, 0, sizeof(*dc));
+ free(dc);
+}
+
+static krb5_error_code
+get_default_dir(krb5_context context, char **res)
+{
+ krb5_error_code ret;
+ char *s;
+
+ if ((ret = dcc_get_default_name(context, &s)))
+ return ret;
+ if (strncmp(s, "DIR:", sizeof("DIR:") - 1) != 0) {
+ *res = s;
+ s = NULL;
+ } else if ((*res = strdup(s + sizeof("DIR:") - 1)) == NULL) {
+ ret = krb5_enomem(context);
+ }
+ free(s);
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_resolve_2(krb5_context context,
+ krb5_ccache *id,
+ const char *res,
+ const char *sub)
+{
+ krb5_error_code ret;
+ krb5_dcache *dc = NULL;
+ char *filename = NULL;
+ size_t len;
+ int has_pathsep = 0;
+
+ if (sub) {
+ /*
+ * Here `res' has the directory name (or, if NULL, refers to the
+ * default DIR cccol), and `sub' has the "subsidiary" name, to which
+ * we'll prefix "tkt." (though we will insist only on "tkt" later).
+ */
+ if ((dc = calloc(1, sizeof(*dc))) == NULL ||
+ asprintf(&dc->sub, "tkt.%s", sub) == -1 || dc->sub == NULL) {
+ free(dc);
+ return krb5_enomem(context);
+ }
+ if (res && res[0] && (dc->dir = strdup(res)) == NULL) {
+ free(dc->sub);
+ free(dc);
+ return krb5_enomem(context);
+ } else if ((!res || !res[0]) && (ret = get_default_dir(context, &dc->dir))) {
+ free(dc->sub);
+ free(dc);
+ return ret;
+ }
+ } else {
+ const char *p;
+ int is_drive_letter_colon = 0;
+
+ /*
+ * Here `res' has whatever string followed "DIR:", and we need to parse
+ * it into `dc->dir' and `dc->sub'.
+ *
+ * Conventions we support for DIR cache naming:
+ *
+ * - DIR:path:NAME ---> FILE:path/tktNAME
+ * - DIR::path/tktNAME ---> FILE:path/tktNAME
+ * - DIR::NAME ---> FILE:${default_DIR_cccol_path}/tktNAME
+ * \-> FILE:/tmp/krb5cc_${uid}_dir/tktNAME
+ * - DIR:path ---> FILE:path/$(cat primary) or FILE:path/tkt
+ *
+ */
+
+ if (*res == '\0' || (res[0] == ':' && res[1] == '\0')) {
+ /* XXX Why not? */
+ krb5_set_error_message(context, KRB5_CC_FORMAT,
+ N_("\"DIR:\" is not a valid ccache name", ""));
+ return KRB5_CC_FORMAT;
+ }
+
+#ifdef WIN32
+ has_pathsep = strchr(res, '\\') != NULL;
+#endif
+ has_pathsep |= strchr(res, '/') != NULL;
+
+ if ((dc = calloc(1, sizeof(*dc))) == NULL)
+ return krb5_enomem(context);
+
+ p = strrchr(res, ':');
+#ifdef WIN32
+ is_drive_letter_colon =
+ p && ((res[0] == ':' && res[1] != ':' && p - res == 2) ||
+ (res[0] != ':' && p - res == 1));
+#endif
+
+ if (res[0] != ':' && p && !is_drive_letter_colon) {
+ /* DIR:path:NAME */
+ if ((dc->dir = strndup(res, (p - res))) == NULL ||
+ asprintf(&dc->sub, "tkt.%s", p + 1) < 0 || dc->sub == NULL) {
+ dcc_release(context, dc);
+ return krb5_enomem(context);
+ }
+ } else if (res[0] == ':' && has_pathsep) {
+ char *q;
+
+ /* DIR::path/tktNAME (the "tkt" must be there; we'll check) */
+ if ((dc->dir = strdup(&res[1])) == NULL) {
+ dcc_release(context, dc);
+ return krb5_enomem(context);
+ }
+#ifdef _WIN32
+ q = strrchr(dc->dir, '\\');
+ if (q == NULL || ((p = strrchr(dc->dir, '/')) && q < p))
+#endif
+ q = strrchr(dc->dir, '/');
+ *q++ = '\0';
+ if ((dc->sub = strdup(q)) == NULL) {
+ dcc_release(context, dc);
+ return krb5_enomem(context);
+ }
+ } else if (res[0] == ':') {
+ /* DIR::NAME -- no path component separators in NAME */
+ if ((ret = get_default_dir(context, &dc->dir))) {
+ dcc_release(context, dc);
+ return ret;
+ }
+ if (asprintf(&dc->sub, "tkt.%s", res + 1) < 0 || dc->sub == NULL) {
+ dcc_release(context, dc);
+ return krb5_enomem(context);
+ }
+ } else {
+ /* DIR:path */
+ if ((dc->dir = strdup(res)) == NULL) {
+ dcc_release(context, dc);
+ return krb5_enomem(context);
+ }
+
+ if ((ret = get_default_cache(context, dc, NULL, &dc->sub))) {
+ dcc_release(context, dc);
+ return ret;
+ }
+ }
+ }
+
+ /* Strip off extra slashes on the end */
+ for (len = strlen(dc->dir);
+ len && ISPATHSEP(dc->dir[len - 1]);
+ len--)
+ dc->dir[len - 1] = '\0';
+
+ /* If we got here then `dc->dir' and `dc->sub' must both be set */
+
+ if ((ret = verify_directory(context, dc->dir))) {
+ dcc_release(context, dc);
+ return ret;
+ }
+ if (!is_filename_cacheish(dc->sub)) {
+ krb5_set_error_message(context, KRB5_CC_FORMAT,
+ N_("Name %s is not a cache "
+ "(doesn't start with tkt)", ""), dc->sub);
+ dcc_release(context, dc);
+ return KRB5_CC_FORMAT;
+ }
+ if (asprintf(&dc->name, ":%s/%s", dc->dir, dc->sub) == -1 ||
+ dc->name == NULL ||
+ asprintf(&filename, "FILE%s", dc->name) == -1 || filename == NULL) {
+ dcc_release(context, dc);
+ return krb5_enomem(context);
+ }
+
+ ret = krb5_cc_resolve(context, filename, &dc->fcache);
+ free(filename);
+ if (ret) {
+ dcc_release(context, dc);
+ return ret;
+ }
+
+ dc->default_candidate = 1;
+ (*id)->data.data = dc;
+ (*id)->data.length = sizeof(*dc);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_gen_new(krb5_context context, krb5_ccache *id)
+{
+ krb5_error_code ret;
+ char *def_dir = NULL;
+ char *name = NULL;
+ int fd = -1;
+
+ ret = get_default_dir(context, &def_dir);
+ if (ret == 0)
+ ret = verify_directory(context, def_dir);
+ if (ret == 0 &&
+ (asprintf(&name, "DIR::%s/tktXXXXXX", def_dir) == -1 || name == NULL))
+ ret = krb5_enomem(context);
+ if (ret == 0 && (fd = mkstemp(name + sizeof("DIR::") - 1)) == -1)
+ ret = errno;
+ if (ret == 0)
+ ret = dcc_resolve_2(context, id, name + sizeof("DIR:") - 1, NULL);
+
+ free(def_dir);
+ free(name);
+ if (fd != -1)
+ close(fd);
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_initialize(krb5_context context,
+ krb5_ccache id,
+ krb5_principal primary_principal)
+{
+ krb5_dcache *dc = DCACHE(id);
+ return krb5_cc_initialize(context, D2FCACHE(dc), primary_principal);
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_close(krb5_context context,
+ krb5_ccache id)
+{
+ krb5_dcache *dc = DCACHE(id);
+ krb5_principal p = NULL;
+ struct stat st;
+ char *primary = NULL;
+
+ /*
+ * If there's no default cache, but we're closing one, and the one we're
+ * closing has been initialized, then make it the default. This makes the
+ * first cache created the default.
+ *
+ * FIXME We should check if `D2FCACHE(dc)' has live credentials.
+ */
+ if (dc->default_candidate && D2FCACHE(dc) &&
+ krb5_cc_get_principal(context, D2FCACHE(dc), &p) == 0 &&
+ (primary = primary_create(dc)) &&
+ (stat(primary, &st) == -1 || !S_ISREG(st.st_mode) || st.st_size == 0))
+ dcc_set_default(context, id);
+ krb5_free_principal(context, p);
+ free(primary);
+ dcc_release(context, DCACHE(id));
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_destroy(krb5_context context,
+ krb5_ccache id)
+{
+ krb5_dcache *dc = DCACHE(id);
+ krb5_ccache fcache = D2FCACHE(dc);
+ dc->fcache = NULL;
+ return krb5_cc_destroy(context, fcache);
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_store_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_creds *creds)
+{
+ krb5_dcache *dc = DCACHE(id);
+ return krb5_cc_store_cred(context, D2FCACHE(dc), creds);
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_get_principal(krb5_context context,
+ krb5_ccache id,
+ krb5_principal *principal)
+{
+ krb5_dcache *dc = DCACHE(id);
+ return krb5_cc_get_principal(context, D2FCACHE(dc), principal);
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_get_first (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+ krb5_dcache *dc = DCACHE(id);
+ return krb5_cc_start_seq_get(context, D2FCACHE(dc), cursor);
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_get_next (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor,
+ krb5_creds *creds)
+{
+ krb5_dcache *dc = DCACHE(id);
+ return krb5_cc_next_cred(context, D2FCACHE(dc), cursor, creds);
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_end_get (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+ krb5_dcache *dc = DCACHE(id);
+ return krb5_cc_end_seq_get(context, D2FCACHE(dc), cursor);
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_remove_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_flags which,
+ krb5_creds *cred)
+{
+ krb5_dcache *dc = DCACHE(id);
+ return krb5_cc_remove_cred(context, D2FCACHE(dc), which, cred);
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_set_flags(krb5_context context,
+ krb5_ccache id,
+ krb5_flags flags)
+{
+ krb5_dcache *dc = DCACHE(id);
+ return krb5_cc_set_flags(context, D2FCACHE(dc), flags);
+}
+
+static int KRB5_CALLCONV
+dcc_get_version(krb5_context context,
+ krb5_ccache id)
+{
+ krb5_dcache *dc = DCACHE(id);
+ return krb5_cc_get_version(context, D2FCACHE(dc));
+}
+
+struct dcache_iter {
+ char *primary;
+ krb5_dcache *dc;
+ DIR *d;
+ unsigned int first:1;
+};
+
+static krb5_error_code KRB5_CALLCONV
+dcc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor)
+{
+ struct dcache_iter *iter = NULL;
+ const char *name = krb5_cc_default_name(context);
+ size_t len;
+ char *p;
+
+ *cursor = NULL;
+
+ if (strncmp(name, "DIR:", sizeof("DIR:") - 1) != 0) {
+ krb5_set_error_message(context, KRB5_CC_FORMAT,
+ N_("Can't list DIR caches unless its the default type", ""));
+ return KRB5_CC_FORMAT;
+ }
+
+ if ((iter = calloc(1, sizeof(*iter))) == NULL ||
+ (iter->dc = calloc(1, sizeof(iter->dc[0]))) == NULL ||
+ (iter->dc->dir = strdup(name + sizeof("DIR:") - 1)) == NULL) {
+ if (iter)
+ free(iter->dc);
+ free(iter);
+ return krb5_enomem(context);
+ }
+ iter->first = 1;
+ p = strrchr(iter->dc->dir, ':');
+#ifdef WIN32
+ if (p == iter->dc->dir + 1)
+ p = NULL;
+#endif
+ if (p)
+ *p = '\0';
+
+ /* Strip off extra slashes on the end */
+ for (len = strlen(iter->dc->dir);
+ len && ISPATHSEP(iter->dc->dir[len - 1]);
+ len--) {
+ iter->dc->dir[len - 1] = '\0';
+ }
+
+ if ((iter->d = opendir(iter->dc->dir)) == NULL) {
+ krb5_set_error_message(context, KRB5_CC_FORMAT,
+ N_("Can't open DIR %s: %s", ""),
+ iter->dc->dir, strerror(errno));
+ free(iter->dc->dir);
+ free(iter->dc);
+ free(iter);
+ return KRB5_CC_FORMAT;
+ }
+
+ *cursor = iter;
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_get_cache_next(krb5_context context, krb5_cc_cursor cursor, krb5_ccache *id)
+{
+ struct dcache_iter *iter = cursor;
+ krb5_error_code ret;
+ struct stat st;
+ struct dirent *dentry;
+ char *p = NULL;
+
+ *id = NULL;
+ if (iter == NULL)
+ return krb5_einval(context, 2);
+
+ /* Emit primary subsidiary first */
+ if (iter->first &&
+ get_default_cache(context, iter->dc, NULL, &iter->primary) == 0 &&
+ iter->primary && is_filename_cacheish(iter->primary)) {
+ iter->first = 0;
+ ret = KRB5_CC_END;
+ if (asprintf(&p, "FILE:%s/%s", iter->dc->dir, iter->primary) > -1 && p != NULL &&
+ stat(p + sizeof("FILE:") - 1, &st) == 0 && S_ISREG(st.st_mode))
+ ret = krb5_cc_resolve(context, p, id);
+ if (p == NULL)
+ return krb5_enomem(context);
+ free(p);
+ if (ret == 0)
+ return ret;
+ p = NULL;
+ }
+
+ iter->first = 0;
+ for (dentry = readdir(iter->d); dentry; dentry = readdir(iter->d)) {
+ if (!is_filename_cacheish(dentry->d_name) ||
+ (iter->primary && strcmp(dentry->d_name, iter->primary) == 0))
+ continue;
+ p = NULL;
+ ret = KRB5_CC_END;
+ if (asprintf(&p, "FILE:%s/%s", iter->dc->dir, dentry->d_name) > -1 &&
+ p != NULL &&
+ stat(p + sizeof("FILE:") - 1, &st) == 0 && S_ISREG(st.st_mode))
+ ret = krb5_cc_resolve(context, p, id);
+ free(p);
+ if (p == NULL)
+ return krb5_enomem(context);
+ if (ret == 0)
+ return ret;
+ }
+ return KRB5_CC_END;
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_end_cache_get(krb5_context context, krb5_cc_cursor cursor)
+{
+ struct dcache_iter *iter = cursor;
+
+ if (iter == NULL)
+ return krb5_einval(context, 2);
+
+ (void) closedir(iter->d);
+ free(iter->dc->dir);
+ free(iter->dc);
+ free(iter->primary);
+ free(iter);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_move(krb5_context context, krb5_ccache from, krb5_ccache to)
+{
+ krb5_dcache *dcfrom = DCACHE(from);
+ krb5_dcache *dcto = DCACHE(to);
+
+ dcfrom->default_candidate = 0;
+ dcto->default_candidate = 1;
+ return krb5_cc_move(context, D2FCACHE(dcfrom), D2FCACHE(dcto));
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_get_default_name(krb5_context context, char **str)
+{
+ const char *def_cc_colname =
+ krb5_config_get_string_default(context, NULL, KRB5_DEFAULT_CCNAME_DIR,
+ "libdefaults", "default_cc_collection",
+ NULL);
+
+ /* [libdefaults] default_cc_collection is for testing */
+ if (strncmp(def_cc_colname, "DIR:", sizeof("DIR:") - 1) != 0)
+ def_cc_colname = KRB5_DEFAULT_CCNAME_DIR;
+ return _krb5_expand_default_cc_name(context, def_cc_colname, str);
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_set_default(krb5_context context, krb5_ccache id)
+{
+ krb5_dcache *dc = DCACHE(id);
+
+ if (dc->sub == NULL)
+ return ENOENT;
+ return set_default_cache(context, dc, dc->sub);
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_lastchange(krb5_context context, krb5_ccache id, krb5_timestamp *mtime)
+{
+ krb5_dcache *dc = DCACHE(id);
+ return krb5_cc_last_change_time(context, D2FCACHE(dc), mtime);
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat kdc_offset)
+{
+ krb5_dcache *dc = DCACHE(id);
+ return krb5_cc_set_kdc_offset(context, D2FCACHE(dc), kdc_offset);
+}
+
+static krb5_error_code KRB5_CALLCONV
+dcc_get_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat *kdc_offset)
+{
+ krb5_dcache *dc = DCACHE(id);
+ return krb5_cc_get_kdc_offset(context, D2FCACHE(dc), kdc_offset);
+}
+
+
+/**
+ * Variable containing the DIR based credential cache implemention.
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_VARIABLE const krb5_cc_ops krb5_dcc_ops = {
+ KRB5_CC_OPS_VERSION_5,
+ "DIR",
+ NULL,
+ NULL,
+ dcc_gen_new,
+ dcc_initialize,
+ dcc_destroy,
+ dcc_close,
+ dcc_store_cred,
+ NULL, /* dcc_retrieve */
+ dcc_get_principal,
+ dcc_get_first,
+ dcc_get_next,
+ dcc_end_get,
+ dcc_remove_cred,
+ dcc_set_flags,
+ dcc_get_version,
+ dcc_get_cache_first,
+ dcc_get_cache_next,
+ dcc_end_cache_get,
+ dcc_move,
+ dcc_get_default_name,
+ dcc_set_default,
+ dcc_lastchange,
+ dcc_set_kdc_offset,
+ dcc_get_kdc_offset,
+ dcc_get_name_2,
+ dcc_resolve_2
+};
diff --git a/third_party/heimdal/lib/krb5/deprecated.c b/third_party/heimdal/lib/krb5/deprecated.c
new file mode 100644
index 0000000..0efa162
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/deprecated.c
@@ -0,0 +1,726 @@
+/*
+ * Copyright (c) 1997 - 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef __GNUC__
+/* For some GCCs there's no way to shut them up about deprecated functions */
+#define KRB5_DEPRECATED_FUNCTION(x)
+#endif
+
+#include "krb5_locl.h"
+
+
+#undef __attribute__
+#define __attribute__(x)
+
+#ifndef HEIMDAL_SMALLER
+
+/**
+ * Same as krb5_data_free(). MIT compat.
+ *
+ * Deprecated: use krb5_data_free().
+ *
+ * @param context Kerberos 5 context.
+ * @param data krb5_data to free.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_data_contents(krb5_context context, krb5_data *data)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ krb5_data_free(data);
+}
+
+/**
+ * Deprecated: keytypes doesn't exists, they are really enctypes.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_keytype_to_enctypes_default (krb5_context context,
+ krb5_keytype keytype,
+ unsigned *len,
+ krb5_enctype **val)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ unsigned int i, n;
+ krb5_enctype *ret;
+
+ if (keytype != (krb5_keytype)KEYTYPE_DES || context->etypes_des == NULL)
+ return krb5_keytype_to_enctypes (context, keytype, len, val);
+
+ for (n = 0; context->etypes_des[n]; ++n)
+ ;
+ ret = malloc (n * sizeof(*ret));
+ if (ret == NULL && n != 0)
+ return krb5_enomem(context);
+ for (i = 0; i < n; ++i)
+ ret[i] = context->etypes_des[i];
+ *len = n;
+ *val = ret;
+ return 0;
+}
+
+
+static struct {
+ const char *name;
+ krb5_keytype type;
+} keys[] = {
+ { "null", KRB5_ENCTYPE_NULL },
+ { "des", KRB5_ENCTYPE_DES_CBC_CRC },
+ { "des3", KRB5_ENCTYPE_OLD_DES3_CBC_SHA1 },
+ { "aes-128", KRB5_ENCTYPE_AES128_CTS_HMAC_SHA1_96 },
+ { "aes-256", KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96 },
+ { "arcfour", KRB5_ENCTYPE_ARCFOUR_HMAC_MD5 },
+ { "arcfour-56", KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56 }
+};
+
+static int num_keys = sizeof(keys) / sizeof(keys[0]);
+
+/**
+ * Deprecated: keytypes doesn't exists, they are really enctypes in
+ * most cases, use krb5_enctype_to_string().
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_keytype_to_string(krb5_context context,
+ krb5_keytype keytype,
+ char **string)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ const char *name = NULL;
+ int i;
+
+ for(i = 0; i < num_keys; i++) {
+ if(keys[i].type == keytype) {
+ name = keys[i].name;
+ break;
+ }
+ }
+
+ if(i >= num_keys) {
+ krb5_set_error_message(context, KRB5_PROG_KEYTYPE_NOSUPP,
+ "key type %d not supported", keytype);
+ return KRB5_PROG_KEYTYPE_NOSUPP;
+ }
+ *string = strdup(name);
+ if (*string == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+/**
+ * Deprecated: keytypes doesn't exists, they are really enctypes in
+ * most cases, use krb5_string_to_enctype().
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_string_to_keytype(krb5_context context,
+ const char *string,
+ krb5_keytype *keytype)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ char *end;
+ int i;
+
+ for(i = 0; i < num_keys; i++)
+ if(strcasecmp(keys[i].name, string) == 0){
+ *keytype = keys[i].type;
+ return 0;
+ }
+
+ /* check if the enctype is a number */
+ *keytype = strtol(string, &end, 0);
+ if(*end == '\0' && *keytype != 0) {
+ if (krb5_enctype_valid(context, *keytype) == 0)
+ return 0;
+ }
+
+ krb5_set_error_message(context, KRB5_PROG_KEYTYPE_NOSUPP,
+ "key type %s not supported", string);
+ return KRB5_PROG_KEYTYPE_NOSUPP;
+}
+
+/**
+ * Deprecated: use krb5_get_init_creds() and friends.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_CALLCONV
+krb5_password_key_proc (krb5_context context,
+ krb5_enctype type,
+ krb5_salt salt,
+ krb5_const_pointer keyseed,
+ krb5_keyblock **key)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ krb5_error_code ret;
+ const char *password = (const char *)keyseed;
+ char buf[BUFSIZ];
+
+ *key = malloc (sizeof (**key));
+ if (*key == NULL)
+ return krb5_enomem(context);
+ if (password == NULL) {
+ if(UI_UTIL_read_pw_string (buf, sizeof(buf), "Password: ", 0)) {
+ free (*key);
+ krb5_clear_error_message(context);
+ return KRB5_LIBOS_PWDINTR;
+ }
+ password = buf;
+ }
+ ret = krb5_string_to_key_salt (context, type, password, salt, *key);
+ memset_s(buf, sizeof(buf), 0, sizeof(buf));
+ return ret;
+}
+
+/**
+ * Deprecated: use krb5_get_init_creds() and friends.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_in_tkt_with_password (krb5_context context,
+ krb5_flags options,
+ krb5_addresses *addrs,
+ const krb5_enctype *etypes,
+ const krb5_preauthtype *pre_auth_types,
+ const char *password,
+ krb5_ccache ccache,
+ krb5_creds *creds,
+ krb5_kdc_rep *ret_as_reply)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return krb5_get_in_tkt (context,
+ options,
+ addrs,
+ etypes,
+ pre_auth_types,
+ krb5_password_key_proc,
+ password,
+ NULL,
+ NULL,
+ creds,
+ ccache,
+ ret_as_reply);
+}
+
+static krb5_error_code KRB5_CALLCONV
+krb5_skey_key_proc (krb5_context context,
+ krb5_enctype type,
+ krb5_salt salt,
+ krb5_const_pointer keyseed,
+ krb5_keyblock **key)
+{
+ return krb5_copy_keyblock (context, keyseed, key);
+}
+
+/**
+ * Deprecated: use krb5_get_init_creds() and friends.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_in_tkt_with_skey (krb5_context context,
+ krb5_flags options,
+ krb5_addresses *addrs,
+ const krb5_enctype *etypes,
+ const krb5_preauthtype *pre_auth_types,
+ const krb5_keyblock *key,
+ krb5_ccache ccache,
+ krb5_creds *creds,
+ krb5_kdc_rep *ret_as_reply)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ if(key == NULL)
+ return krb5_get_in_tkt_with_keytab (context,
+ options,
+ addrs,
+ etypes,
+ pre_auth_types,
+ NULL,
+ ccache,
+ creds,
+ ret_as_reply);
+ else
+ return krb5_get_in_tkt (context,
+ options,
+ addrs,
+ etypes,
+ pre_auth_types,
+ krb5_skey_key_proc,
+ key,
+ NULL,
+ NULL,
+ creds,
+ ccache,
+ ret_as_reply);
+}
+
+/**
+ * Deprecated: use krb5_get_init_creds() and friends.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_CALLCONV
+krb5_keytab_key_proc (krb5_context context,
+ krb5_enctype enctype,
+ krb5_salt salt,
+ krb5_const_pointer keyseed,
+ krb5_keyblock **key)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ krb5_keytab_key_proc_args *args = rk_UNCONST(keyseed);
+ krb5_keytab keytab = args->keytab;
+ krb5_principal principal = args->principal;
+ krb5_error_code ret;
+ krb5_keytab real_keytab;
+ krb5_keytab_entry entry;
+
+ if(keytab == NULL)
+ krb5_kt_default(context, &real_keytab);
+ else
+ real_keytab = keytab;
+
+ ret = krb5_kt_get_entry (context, real_keytab, principal,
+ 0, enctype, &entry);
+ if (ret == 0) {
+ ret = krb5_copy_keyblock (context, &entry.keyblock, key);
+ krb5_kt_free_entry(context, &entry);
+ }
+
+ if (keytab == NULL)
+ krb5_kt_close (context, real_keytab);
+ return ret;
+}
+
+/**
+ * Deprecated: use krb5_get_init_creds() and friends.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_in_tkt_with_keytab (krb5_context context,
+ krb5_flags options,
+ krb5_addresses *addrs,
+ const krb5_enctype *etypes,
+ const krb5_preauthtype *pre_auth_types,
+ krb5_keytab keytab,
+ krb5_ccache ccache,
+ krb5_creds *creds,
+ krb5_kdc_rep *ret_as_reply)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ krb5_keytab_key_proc_args a;
+
+ a.principal = creds->client;
+ a.keytab = keytab;
+
+ return krb5_get_in_tkt (context,
+ options,
+ addrs,
+ etypes,
+ pre_auth_types,
+ krb5_keytab_key_proc,
+ &a,
+ NULL,
+ NULL,
+ creds,
+ ccache,
+ ret_as_reply);
+}
+
+/**
+ * Generate a new ccache of type `ops' in `id'.
+ *
+ * Deprecated: use krb5_cc_new_unique() instead.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_gen_new(krb5_context context,
+ const krb5_cc_ops *ops,
+ krb5_ccache *id)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return krb5_cc_new_unique(context, ops->prefix, NULL, id);
+}
+
+/**
+ * Deprecated: use krb5_principal_get_realm()
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_realm * KRB5_LIB_CALL
+krb5_princ_realm(krb5_context context,
+ krb5_principal principal)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return &principal->realm;
+}
+
+
+/**
+ * Deprecated: use krb5_principal_set_realm()
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_princ_set_realm(krb5_context context,
+ krb5_principal principal,
+ krb5_realm *realm)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ principal->realm = *realm;
+}
+
+/**
+ * Deprecated: use krb5_free_cred_contents()
+ *
+ * @ingroup krb5_deprecated
+ */
+
+/* keep this for compatibility with older code */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_free_creds_contents (krb5_context context, krb5_creds *c)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return krb5_free_cred_contents (context, c);
+}
+
+/**
+ * Free the error message returned by krb5_get_error_string().
+ *
+ * Deprecated: use krb5_free_error_message()
+ *
+ * @param context Kerberos context
+ * @param str error message to free
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_error_string(krb5_context context, char *str)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ krb5_free_error_message(context, str);
+}
+
+/**
+ * Set the error message returned by krb5_get_error_string().
+ *
+ * Deprecated: use krb5_get_error_message()
+ *
+ * @param context Kerberos context
+ * @param fmt error message to free
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_error_string(krb5_context context, const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 2, 3)))
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ krb5_vset_error_message (context, 0, fmt, ap);
+ va_end(ap);
+ return 0;
+}
+
+/**
+ * Set the error message returned by krb5_get_error_string(),
+ * deprecated, use krb5_set_error_message().
+ *
+ * Deprecated: use krb5_vset_error_message()
+ *
+ * @param context Kerberos context
+ * @param fmt error message to free
+ * @param args variable argument list vector
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_vset_error_string(krb5_context context, const char *fmt, va_list args)
+ __attribute__ ((__format__ (__printf__, 2, 0)))
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ krb5_vset_error_message(context, 0, fmt, args);
+ return 0;
+}
+
+/**
+ * Clear the error message returned by krb5_get_error_string().
+ *
+ * Deprecated: use krb5_clear_error_message()
+ *
+ * @param context Kerberos context
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_clear_error_string(krb5_context context)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ krb5_clear_error_message(context);
+}
+
+/**
+ * Deprecated: use krb5_get_credentials_with_flags().
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_cred_from_kdc_opt(krb5_context context,
+ krb5_ccache ccache,
+ krb5_creds *in_creds,
+ krb5_creds **out_creds,
+ krb5_creds ***ret_tgts,
+ krb5_flags flags)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ krb5_kdc_flags f;
+ f.i = flags;
+ return _krb5_get_cred_kdc_any(context, f, ccache, NULL,
+ in_creds, NULL, NULL,
+ out_creds, ret_tgts);
+}
+
+/**
+ * Deprecated: use krb5_get_credentials_with_flags().
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_cred_from_kdc(krb5_context context,
+ krb5_ccache ccache,
+ krb5_creds *in_creds,
+ krb5_creds **out_creds,
+ krb5_creds ***ret_tgts)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return krb5_get_cred_from_kdc_opt(context, ccache,
+ in_creds, out_creds, ret_tgts, 0);
+}
+
+/**
+ * Deprecated: use krb5_xfree().
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_unparsed_name(krb5_context context, char *str)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ krb5_xfree(str);
+}
+
+/**
+ * Deprecated: use krb5_generate_subkey_extended()
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_generate_subkey(krb5_context context,
+ const krb5_keyblock *key,
+ krb5_keyblock **subkey)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ return krb5_generate_subkey_extended(context, key, ETYPE_NULL, subkey);
+}
+
+/**
+ * Deprecated: use krb5_auth_con_getremoteseqnumber()
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_getremoteseqnumber(krb5_context context,
+ krb5_auth_context auth_context,
+ int32_t *seqnumber)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ *seqnumber = auth_context->remote_seqnumber;
+ return 0;
+}
+
+/**
+ * Return the error message in context. On error or no error string,
+ * the function returns NULL.
+ *
+ * @param context Kerberos 5 context
+ *
+ * @return an error string, needs to be freed with
+ * krb5_free_error_message(). The functions return NULL on error.
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+krb5_get_error_string(krb5_context context)
+ KRB5_DEPRECATED_FUNCTION("Use krb5_get_error_message instead")
+{
+ return heim_get_error_string(context->hcontext);
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_have_error_string(krb5_context context)
+ KRB5_DEPRECATED_FUNCTION("Use krb5_get_error_message instead")
+{
+ return heim_have_error_string(context->hcontext);
+}
+
+struct send_to_kdc {
+ krb5_send_to_kdc_func func;
+ void *data;
+};
+
+/*
+ * Send the data `send' to one host from `handle` and get back the reply
+ * in `receive'.
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_sendto (krb5_context context,
+ const krb5_data *send_data,
+ krb5_krbhst_handle handle,
+ krb5_data *receive)
+{
+ krb5_error_code ret;
+ krb5_sendto_ctx ctx;
+
+ ret = krb5_sendto_ctx_alloc(context, &ctx);
+ if (ret)
+ return ret;
+ _krb5_sendto_ctx_set_krb5hst(context, ctx, handle);
+
+ ret = krb5_sendto_context(context, ctx, send_data, (char *)_krb5_krbhst_get_realm(handle), receive);
+ krb5_sendto_ctx_free(context, ctx);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_sendto_kdc(krb5_context context,
+ const krb5_data *send_data,
+ const krb5_realm *realm,
+ krb5_data *receive)
+{
+ return krb5_sendto_kdc_flags(context, send_data, realm, receive, 0);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_sendto_kdc_flags(krb5_context context,
+ const krb5_data *send_data,
+ const krb5_realm *realm,
+ krb5_data *receive,
+ int flags)
+{
+ krb5_error_code ret;
+ krb5_sendto_ctx ctx;
+
+ ret = krb5_sendto_ctx_alloc(context, &ctx);
+ if (ret)
+ return ret;
+ krb5_sendto_ctx_add_flags(ctx, flags);
+ krb5_sendto_ctx_set_func(ctx, _krb5_kdc_retry, NULL);
+
+ ret = krb5_sendto_context(context, ctx, send_data, *realm, receive);
+ krb5_sendto_ctx_free(context, ctx);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_send_to_kdc_func(krb5_context context,
+ krb5_send_to_kdc_func func,
+ void *data)
+{
+ free(context->send_to_kdc);
+ if (func == NULL) {
+ context->send_to_kdc = NULL;
+ return 0;
+ }
+
+ context->send_to_kdc = malloc(sizeof(*context->send_to_kdc));
+ if (context->send_to_kdc == NULL) {
+ krb5_set_error_message(context, ENOMEM,
+ N_("malloc: out of memory", ""));
+ return ENOMEM;
+ }
+
+ context->send_to_kdc->func = func;
+ context->send_to_kdc->data = data;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_copy_send_to_kdc_func(krb5_context context, krb5_context to)
+{
+ if (context->send_to_kdc)
+ return krb5_set_send_to_kdc_func(to,
+ context->send_to_kdc->func,
+ context->send_to_kdc->data);
+ else
+ return krb5_set_send_to_kdc_func(to, NULL, NULL);
+}
+
+#endif /* HEIMDAL_SMALLER */
diff --git a/third_party/heimdal/lib/krb5/derived-key-test.c b/third_party/heimdal/lib/krb5/derived-key-test.c
new file mode 100644
index 0000000..0e92764
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/derived-key-test.c
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+
+enum { MAXSIZE = 32 };
+
+static struct testcase {
+ krb5_enctype enctype;
+ unsigned char constant[MAXSIZE];
+ size_t constant_len;
+ unsigned char key[MAXSIZE];
+ unsigned char res[MAXSIZE];
+} tests[] = {
+ {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0x55}, 5,
+ {0xdc, 0xe0, 0x6b, 0x1f, 0x64, 0xc8, 0x57, 0xa1, 0x1c, 0x3d, 0xb5, 0x7c, 0x51, 0x89, 0x9b, 0x2c, 0xc1, 0x79, 0x10, 0x08, 0xce, 0x97, 0x3b, 0x92},
+ {0x92, 0x51, 0x79, 0xd0, 0x45, 0x91, 0xa7, 0x9b, 0x5d, 0x31, 0x92, 0xc4, 0xa7, 0xe9, 0xc2, 0x89, 0xb0, 0x49, 0xc7, 0x1f, 0x6e, 0xe6, 0x04, 0xcd}},
+ {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0xaa}, 5,
+ {0x5e, 0x13, 0xd3, 0x1c, 0x70, 0xef, 0x76, 0x57, 0x46, 0x57, 0x85, 0x31, 0xcb, 0x51, 0xc1, 0x5b, 0xf1, 0x1c, 0xa8, 0x2c, 0x97, 0xce, 0xe9, 0xf2},
+ {0x9e, 0x58, 0xe5, 0xa1, 0x46, 0xd9, 0x94, 0x2a, 0x10, 0x1c, 0x46, 0x98, 0x45, 0xd6, 0x7a, 0x20, 0xe3, 0xc4, 0x25, 0x9e, 0xd9, 0x13, 0xf2, 0x07}},
+ {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0x55}, 5,
+ {0x98, 0xe6, 0xfd, 0x8a, 0x04, 0xa4, 0xb6, 0x85, 0x9b, 0x75, 0xa1, 0x76, 0x54, 0x0b, 0x97, 0x52, 0xba, 0xd3, 0xec, 0xd6, 0x10, 0xa2, 0x52, 0xbc},
+ {0x13, 0xfe, 0xf8, 0x0d, 0x76, 0x3e, 0x94, 0xec, 0x6d, 0x13, 0xfd, 0x2c, 0xa1, 0xd0, 0x85, 0x07, 0x02, 0x49, 0xda, 0xd3, 0x98, 0x08, 0xea, 0xbf}},
+ {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0xaa}, 5,
+ {0x62, 0x2a, 0xec, 0x25, 0xa2, 0xfe, 0x2c, 0xad, 0x70, 0x94, 0x68, 0x0b, 0x7c, 0x64, 0x94, 0x02, 0x80, 0x08, 0x4c, 0x1a, 0x7c, 0xec, 0x92, 0xb5},
+ {0xf8, 0xdf, 0xbf, 0x04, 0xb0, 0x97, 0xe6, 0xd9, 0xdc, 0x07, 0x02, 0x68, 0x6b, 0xcb, 0x34, 0x89, 0xd9, 0x1f, 0xd9, 0xa4, 0x51, 0x6b, 0x70, 0x3e}},
+ {ETYPE_DES3_CBC_SHA1, {0x6b, 0x65, 0x72, 0x62, 0x65, 0x72, 0x6f, 0x73}, 8,
+ {0xd3, 0xf8, 0x29, 0x8c, 0xcb, 0x16, 0x64, 0x38, 0xdc, 0xb9, 0xb9, 0x3e, 0xe5, 0xa7, 0x62, 0x92, 0x86, 0xa4, 0x91, 0xf8, 0x38, 0xf8, 0x02, 0xfb},
+ {0x23, 0x70, 0xda, 0x57, 0x5d, 0x2a, 0x3d, 0xa8, 0x64, 0xce, 0xbf, 0xdc, 0x52, 0x04, 0xd5, 0x6d, 0xf7, 0x79, 0xa7, 0xdf, 0x43, 0xd9, 0xda, 0x43}},
+ {ETYPE_DES3_CBC_SHA1, {0x63, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65}, 7,
+ {0xb5, 0x5e, 0x98, 0x34, 0x67, 0xe5, 0x51, 0xb3, 0xe5, 0xd0, 0xe5, 0xb6, 0xc8, 0x0d, 0x45, 0x76, 0x94, 0x23, 0xa8, 0x73, 0xdc, 0x62, 0xb3, 0x0e},
+ {0x01, 0x26, 0x38, 0x8a, 0xad, 0xc8, 0x1a, 0x1f, 0x2a, 0x62, 0xbc, 0x45, 0xf8, 0xd5, 0xc1, 0x91, 0x51, 0xba, 0xcd, 0xd5, 0xcb, 0x79, 0x8a, 0x3e}},
+ {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0x55}, 5,
+ {0xc1, 0x08, 0x16, 0x49, 0xad, 0xa7, 0x43, 0x62, 0xe6, 0xa1, 0x45, 0x9d, 0x01, 0xdf, 0xd3, 0x0d, 0x67, 0xc2, 0x23, 0x4c, 0x94, 0x07, 0x04, 0xda},
+ {0x34, 0x80, 0x57, 0xec, 0x98, 0xfd, 0xc4, 0x80, 0x16, 0x16, 0x1c, 0x2a, 0x4c, 0x7a, 0x94, 0x3e, 0x92, 0xae, 0x49, 0x2c, 0x98, 0x91, 0x75, 0xf7}},
+ {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0xaa}, 5,
+ {0x5d, 0x15, 0x4a, 0xf2, 0x38, 0xf4, 0x67, 0x13, 0x15, 0x57, 0x19, 0xd5, 0x5e, 0x2f, 0x1f, 0x79, 0x0d, 0xd6, 0x61, 0xf2, 0x79, 0xa7, 0x91, 0x7c},
+ {0xa8, 0x80, 0x8a, 0xc2, 0x67, 0xda, 0xda, 0x3d, 0xcb, 0xe9, 0xa7, 0xc8, 0x46, 0x26, 0xfb, 0xc7, 0x61, 0xc2, 0x94, 0xb0, 0x13, 0x15, 0xe5, 0xc1}},
+ {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0x55}, 5,
+ {0x79, 0x85, 0x62, 0xe0, 0x49, 0x85, 0x2f, 0x57, 0xdc, 0x8c, 0x34, 0x3b, 0xa1, 0x7f, 0x2c, 0xa1, 0xd9, 0x73, 0x94, 0xef, 0xc8, 0xad, 0xc4, 0x43},
+ {0xc8, 0x13, 0xf8, 0x8a, 0x3b, 0xe3, 0xb3, 0x34, 0xf7, 0x54, 0x25, 0xce, 0x91, 0x75, 0xfb, 0xe3, 0xc8, 0x49, 0x3b, 0x89, 0xc8, 0x70, 0x3b, 0x49}},
+ {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0xaa}, 5,
+ {0x26, 0xdc, 0xe3, 0x34, 0xb5, 0x45, 0x29, 0x2f, 0x2f, 0xea, 0xb9, 0xa8, 0x70, 0x1a, 0x89, 0xa4, 0xb9, 0x9e, 0xb9, 0x94, 0x2c, 0xec, 0xd0, 0x16},
+ {0xf4, 0x8f, 0xfd, 0x6e, 0x83, 0xf8, 0x3e, 0x73, 0x54, 0xe6, 0x94, 0xfd, 0x25, 0x2c, 0xf8, 0x3b, 0xfe, 0x58, 0xf7, 0xd5, 0xba, 0x37, 0xec, 0x5d}},
+ {ETYPE_AES128_CTS_HMAC_SHA256_128, {0x00, 0x00, 0x00, 0x02, 0x99}, 5,
+ {0x37, 0x05, 0xD9, 0x60, 0x80, 0xC1, 0x77, 0x28, 0xA0, 0xE8, 0x00, 0xEA, 0xB6, 0xE0, 0xD2, 0x3C},
+ {0xB3, 0x1A, 0x01, 0x8A, 0x48, 0xF5, 0x47, 0x76, 0xF4, 0x03, 0xE9, 0xA3, 0x96, 0x32, 0x5D, 0xC3}},
+ {ETYPE_AES128_CTS_HMAC_SHA256_128, {0x00, 0x00, 0x00, 0x02, 0xAA}, 5,
+ {0x37, 0x05, 0xD9, 0x60, 0x80, 0xC1, 0x77, 0x28, 0xA0, 0xE8, 0x00, 0xEA, 0xB6, 0xE0, 0xD2, 0x3C},
+ {0x9B, 0x19, 0x7D, 0xD1, 0xE8, 0xC5, 0x60, 0x9D, 0x6E, 0x67, 0xC3, 0xE3, 0x7C, 0x62, 0xC7, 0x2E}},
+ {ETYPE_AES128_CTS_HMAC_SHA256_128, {0x00, 0x00, 0x00, 0x02, 0x55}, 5,
+ {0x37, 0x05, 0xD9, 0x60, 0x80, 0xC1, 0x77, 0x28, 0xA0, 0xE8, 0x00, 0xEA, 0xB6, 0xE0, 0xD2, 0x3C},
+ {0x9F, 0xDA, 0x0E, 0x56, 0xAB, 0x2D, 0x85, 0xE1, 0x56, 0x9A, 0x68, 0x86, 0x96, 0xC2, 0x6A, 0x6C}},
+ {ETYPE_AES256_CTS_HMAC_SHA384_192, {0x00, 0x00, 0x00, 0x02, 0x99}, 5,
+ {0x6D, 0x40, 0x4D, 0x37, 0xFA, 0xF7, 0x9F, 0x9D, 0xF0, 0xD3, 0x35, 0x68, 0xD3, 0x20, 0x66, 0x98,
+ 0x00, 0xEB, 0x48, 0x36, 0x47, 0x2E, 0xA8, 0xA0, 0x26, 0xD1, 0x6B, 0x71, 0x82, 0x46, 0x0C, 0x52},
+ {0xEF, 0x57, 0x18, 0xBE, 0x86, 0xCC, 0x84, 0x96, 0x3D, 0x8B, 0xBB, 0x50, 0x31, 0xE9, 0xF5, 0xC4,
+ 0xBA, 0x41, 0xF2, 0x8F, 0xAF, 0x69, 0xE7, 0x3D }},
+ {ETYPE_AES256_CTS_HMAC_SHA384_192, {0x00, 0x00, 0x00, 0x02, 0xAA}, 5,
+ {0x6D, 0x40, 0x4D, 0x37, 0xFA, 0xF7, 0x9F, 0x9D, 0xF0, 0xD3, 0x35, 0x68, 0xD3, 0x20, 0x66, 0x98,
+ 0x00, 0xEB, 0x48, 0x36, 0x47, 0x2E, 0xA8, 0xA0, 0x26, 0xD1, 0x6B, 0x71, 0x82, 0x46, 0x0C, 0x52},
+ {0x56, 0xAB, 0x22, 0xBE, 0xE6, 0x3D, 0x82, 0xD7, 0xBC, 0x52, 0x27, 0xF6, 0x77, 0x3F, 0x8E, 0xA7,
+ 0xA5, 0xEB, 0x1C, 0x82, 0x51, 0x60, 0xC3, 0x83, 0x12, 0x98, 0x0C, 0x44, 0x2E, 0x5C, 0x7E, 0x49}},
+ {ETYPE_AES256_CTS_HMAC_SHA384_192, {0x00, 0x00, 0x00, 0x02, 0x55}, 5,
+ {0x6D, 0x40, 0x4D, 0x37, 0xFA, 0xF7, 0x9F, 0x9D, 0xF0, 0xD3, 0x35, 0x68, 0xD3, 0x20, 0x66, 0x98,
+ 0x00, 0xEB, 0x48, 0x36, 0x47, 0x2E, 0xA8, 0xA0, 0x26, 0xD1, 0x6B, 0x71, 0x82, 0x46, 0x0C, 0x52},
+ {0x69, 0xB1, 0x65, 0x14, 0xE3, 0xCD, 0x8E, 0x56, 0xB8, 0x20, 0x10, 0xD5, 0xC7, 0x30, 0x12, 0xB6,
+ 0x22, 0xC4, 0xD0, 0x0F, 0xFC, 0x23, 0xED, 0x1F}},
+ {0, {0}, 0, {0}, {0}}
+};
+
+int
+main(int argc, char **argv)
+{
+ struct testcase *t;
+ krb5_context context;
+ krb5_error_code ret;
+ int val = 0;
+
+ ret = krb5_init_context (&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ for (t = tests; t->enctype != 0; ++t) {
+ krb5_keyblock key;
+ krb5_keyblock *dkey;
+
+ key.keytype = t->enctype;
+ krb5_enctype_keysize(context, t->enctype, &key.keyvalue.length);
+ key.keyvalue.data = t->key;
+
+ ret = krb5_derive_key(context, &key, t->enctype, t->constant,
+ t->constant_len, &dkey);
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_derive_key");
+ if (memcmp (dkey->keyvalue.data, t->res, dkey->keyvalue.length) != 0) {
+ const unsigned char *p = dkey->keyvalue.data;
+ int i;
+
+ printf ("derive_key failed (enctype %d)\n", t->enctype);
+ printf ("should be: ");
+ for (i = 0; i < dkey->keyvalue.length; ++i)
+ printf ("%02x", t->res[i]);
+ printf ("\nresult was: ");
+ for (i = 0; i < dkey->keyvalue.length; ++i)
+ printf ("%02x", p[i]);
+ printf ("\n");
+ val = 1;
+ }
+ krb5_free_keyblock(context, dkey);
+ }
+ krb5_free_context(context);
+
+ return val;
+}
diff --git a/third_party/heimdal/lib/krb5/digest.c b/third_party/heimdal/lib/krb5/digest.c
new file mode 100644
index 0000000..7be2492
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/digest.c
@@ -0,0 +1,1165 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include "digest_asn1.h"
+
+#ifndef HEIMDAL_SMALLER
+
+struct krb5_digest_data {
+ char *cbtype;
+ char *cbbinding;
+
+ DigestInit init;
+ DigestInitReply initReply;
+ DigestRequest request;
+ DigestResponse response;
+};
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_alloc(krb5_context context, krb5_digest *digest)
+{
+ krb5_digest d;
+
+ d = calloc(1, sizeof(*d));
+ if (d == NULL) {
+ *digest = NULL;
+ return krb5_enomem(context);
+ }
+ *digest = d;
+
+ return 0;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_digest_free(krb5_digest digest)
+{
+ if (digest == NULL)
+ return;
+ free_DigestInit(&digest->init);
+ free_DigestInitReply(&digest->initReply);
+ free_DigestRequest(&digest->request);
+ free_DigestResponse(&digest->response);
+ memset(digest, 0, sizeof(*digest));
+ free(digest);
+ return;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_server_cb(krb5_context context,
+ krb5_digest digest,
+ const char *type,
+ const char *binding)
+{
+ if (digest->init.channel) {
+ krb5_set_error_message(context, EINVAL,
+ N_("server channel binding already set", ""));
+ return EINVAL;
+ }
+ digest->init.channel = calloc(1, sizeof(*digest->init.channel));
+ if (digest->init.channel == NULL)
+ goto error;
+
+ digest->init.channel->cb_type = strdup(type);
+ if (digest->init.channel->cb_type == NULL)
+ goto error;
+
+ digest->init.channel->cb_binding = strdup(binding);
+ if (digest->init.channel->cb_binding == NULL)
+ goto error;
+ return 0;
+ error:
+ if (digest->init.channel) {
+ free(digest->init.channel->cb_type);
+ free(digest->init.channel->cb_binding);
+ free(digest->init.channel);
+ digest->init.channel = NULL;
+ }
+ return krb5_enomem(context);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_type(krb5_context context,
+ krb5_digest digest,
+ const char *type)
+{
+ if (digest->init.type) {
+ krb5_set_error_message(context, EINVAL, "client type already set");
+ return EINVAL;
+ }
+ digest->init.type = strdup(type);
+ if (digest->init.type == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_hostname(krb5_context context,
+ krb5_digest digest,
+ const char *hostname)
+{
+ if (digest->init.hostname) {
+ krb5_set_error_message(context, EINVAL, "server hostname already set");
+ return EINVAL;
+ }
+ digest->init.hostname = malloc(sizeof(*digest->init.hostname));
+ if (digest->init.hostname == NULL)
+ return krb5_enomem(context);
+ *digest->init.hostname = strdup(hostname);
+ if (*digest->init.hostname == NULL) {
+ free(digest->init.hostname);
+ digest->init.hostname = NULL;
+ return krb5_enomem(context);
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+krb5_digest_get_server_nonce(krb5_context context,
+ krb5_digest digest)
+{
+ return digest->initReply.nonce;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_server_nonce(krb5_context context,
+ krb5_digest digest,
+ const char *nonce)
+{
+ if (digest->request.serverNonce) {
+ krb5_set_error_message(context, EINVAL, N_("nonce already set", ""));
+ return EINVAL;
+ }
+ digest->request.serverNonce = strdup(nonce);
+ if (digest->request.serverNonce == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+krb5_digest_get_opaque(krb5_context context,
+ krb5_digest digest)
+{
+ return digest->initReply.opaque;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_opaque(krb5_context context,
+ krb5_digest digest,
+ const char *opaque)
+{
+ if (digest->request.opaque) {
+ krb5_set_error_message(context, EINVAL, "opaque already set");
+ return EINVAL;
+ }
+ digest->request.opaque = strdup(opaque);
+ if (digest->request.opaque == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+krb5_digest_get_identifier(krb5_context context,
+ krb5_digest digest)
+{
+ if (digest->initReply.identifier == NULL)
+ return NULL;
+ return *digest->initReply.identifier;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_identifier(krb5_context context,
+ krb5_digest digest,
+ const char *id)
+{
+ if (digest->request.identifier) {
+ krb5_set_error_message(context, EINVAL, N_("identifier already set", ""));
+ return EINVAL;
+ }
+ digest->request.identifier = calloc(1, sizeof(*digest->request.identifier));
+ if (digest->request.identifier == NULL)
+ return krb5_enomem(context);
+ *digest->request.identifier = strdup(id);
+ if (*digest->request.identifier == NULL) {
+ free(digest->request.identifier);
+ digest->request.identifier = NULL;
+ return krb5_enomem(context);
+ }
+ return 0;
+}
+
+static krb5_error_code
+digest_request(krb5_context context,
+ krb5_realm realm,
+ krb5_ccache ccache,
+ krb5_key_usage usage,
+ const DigestReqInner *ireq,
+ DigestRepInner *irep)
+{
+ DigestREQ req;
+ DigestREP rep;
+ krb5_error_code ret;
+ krb5_data data, data2;
+ size_t size = 0;
+ krb5_crypto crypto = NULL;
+ krb5_auth_context ac = NULL;
+ krb5_principal principal = NULL;
+ krb5_ccache id = NULL;
+ krb5_realm r = NULL;
+
+ krb5_data_zero(&data);
+ krb5_data_zero(&data2);
+ memset(&req, 0, sizeof(req));
+ memset(&rep, 0, sizeof(rep));
+
+ if (ccache == NULL) {
+ ret = krb5_cc_default(context, &id);
+ if (ret)
+ goto out;
+ } else
+ id = ccache;
+
+ if (realm == NULL) {
+ ret = krb5_get_default_realm(context, &r);
+ if (ret)
+ goto out;
+ } else
+ r = realm;
+
+ /*
+ *
+ */
+
+ ret = krb5_make_principal(context, &principal,
+ r, KRB5_DIGEST_NAME, r, NULL);
+ if (ret)
+ goto out;
+
+ ASN1_MALLOC_ENCODE(DigestReqInner, data.data, data.length,
+ ireq, &size, ret);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to encode digest inner request", ""));
+ goto out;
+ }
+ if (size != data.length)
+ krb5_abortx(context, "ASN.1 internal encoder error");
+
+ ret = krb5_mk_req_exact(context, &ac,
+ AP_OPTS_USE_SUBKEY|AP_OPTS_MUTUAL_REQUIRED,
+ principal, NULL, id, &req.apReq);
+ if (ret)
+ goto out;
+
+ {
+ krb5_keyblock *key;
+
+ ret = krb5_auth_con_getlocalsubkey(context, ac, &key);
+ if (ret)
+ goto out;
+ if (key == NULL) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret,
+ N_("Digest failed to get local subkey", ""));
+ goto out;
+ }
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ krb5_free_keyblock (context, key);
+ if (ret)
+ goto out;
+ }
+
+ ret = krb5_encrypt_EncryptedData(context, crypto, usage,
+ data.data, data.length, 0,
+ &req.innerReq);
+ if (ret)
+ goto out;
+
+ krb5_data_free(&data);
+
+ ASN1_MALLOC_ENCODE(DigestREQ, data.data, data.length,
+ &req, &size, ret);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to encode DigestREQest", ""));
+ goto out;
+ }
+ if (size != data.length)
+ krb5_abortx(context, "ASN.1 internal encoder error");
+
+ ret = krb5_sendto_kdc(context, &data, &r, &data2);
+ if (ret)
+ goto out;
+
+ ret = decode_DigestREP(data2.data, data2.length, &rep, NULL);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to parse digest response", ""));
+ goto out;
+ }
+
+ {
+ krb5_ap_rep_enc_part *repl;
+
+ ret = krb5_rd_rep(context, ac, &rep.apRep, &repl);
+ if (ret)
+ goto out;
+
+ krb5_free_ap_rep_enc_part(context, repl);
+ }
+ {
+ krb5_keyblock *key;
+
+ ret = krb5_auth_con_getremotesubkey(context, ac, &key);
+ if (ret)
+ goto out;
+ if (key == NULL) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret,
+ N_("Digest reply have no remote subkey", ""));
+ goto out;
+ }
+
+ krb5_crypto_destroy(context, crypto);
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ krb5_free_keyblock (context, key);
+ if (ret)
+ goto out;
+ }
+
+ krb5_data_free(&data);
+ ret = krb5_decrypt_EncryptedData(context, crypto, usage,
+ &rep.innerRep, &data);
+ if (ret)
+ goto out;
+
+ ret = decode_DigestRepInner(data.data, data.length, irep, NULL);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to decode digest inner reply", ""));
+ goto out;
+ }
+
+ out:
+ if (ccache == NULL && id)
+ krb5_cc_close(context, id);
+ if (realm == NULL && r)
+ free(r);
+ if (crypto)
+ krb5_crypto_destroy(context, crypto);
+ if (ac)
+ krb5_auth_con_free(context, ac);
+ if (principal)
+ krb5_free_principal(context, principal);
+
+ krb5_data_free(&data);
+ krb5_data_free(&data2);
+
+ free_DigestREQ(&req);
+ free_DigestREP(&rep);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_init_request(krb5_context context,
+ krb5_digest digest,
+ krb5_realm realm,
+ krb5_ccache ccache)
+{
+ DigestReqInner ireq;
+ DigestRepInner irep;
+ krb5_error_code ret;
+
+ memset(&ireq, 0, sizeof(ireq));
+ memset(&irep, 0, sizeof(irep));
+
+ if (digest->init.type == NULL) {
+ krb5_set_error_message(context, EINVAL,
+ N_("Type missing from init req", ""));
+ return EINVAL;
+ }
+
+ ireq.element = choice_DigestReqInner_init;
+ ireq.u.init = digest->init;
+
+ ret = digest_request(context, realm, ccache,
+ KRB5_KU_DIGEST_ENCRYPT, &ireq, &irep);
+ if (ret)
+ goto out;
+
+ if (irep.element == choice_DigestRepInner_error) {
+ ret = irep.u.error.code;
+ krb5_set_error_message(context, ret, N_("Digest init error: %s", ""),
+ irep.u.error.reason);
+ goto out;
+ }
+
+ if (irep.element != choice_DigestRepInner_initReply) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret,
+ N_("digest reply not an initReply", ""));
+ goto out;
+ }
+
+ ret = copy_DigestInitReply(&irep.u.initReply, &digest->initReply);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to copy initReply", ""));
+ goto out;
+ }
+
+ out:
+ free_DigestRepInner(&irep);
+
+ return ret;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_client_nonce(krb5_context context,
+ krb5_digest digest,
+ const char *nonce)
+{
+ if (digest->request.clientNonce) {
+ krb5_set_error_message(context, EINVAL,
+ N_("clientNonce already set", ""));
+ return EINVAL;
+ }
+ digest->request.clientNonce =
+ calloc(1, sizeof(*digest->request.clientNonce));
+ if (digest->request.clientNonce == NULL)
+ return krb5_enomem(context);
+ *digest->request.clientNonce = strdup(nonce);
+ if (*digest->request.clientNonce == NULL) {
+ free(digest->request.clientNonce);
+ digest->request.clientNonce = NULL;
+ return krb5_enomem(context);
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_digest(krb5_context context,
+ krb5_digest digest,
+ const char *dgst)
+{
+ if (digest->request.digest) {
+ krb5_set_error_message(context, EINVAL,
+ N_("digest already set", ""));
+ return EINVAL;
+ }
+ digest->request.digest = strdup(dgst);
+ if (digest->request.digest == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_username(krb5_context context,
+ krb5_digest digest,
+ const char *username)
+{
+ if (digest->request.username) {
+ krb5_set_error_message(context, EINVAL, "username already set");
+ return EINVAL;
+ }
+ digest->request.username = strdup(username);
+ if (digest->request.username == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_authid(krb5_context context,
+ krb5_digest digest,
+ const char *authid)
+{
+ if (digest->request.authid) {
+ krb5_set_error_message(context, EINVAL, "authid already set");
+ return EINVAL;
+ }
+ digest->request.authid = malloc(sizeof(*digest->request.authid));
+ if (digest->request.authid == NULL)
+ return krb5_enomem(context);
+ *digest->request.authid = strdup(authid);
+ if (*digest->request.authid == NULL) {
+ free(digest->request.authid);
+ digest->request.authid = NULL;
+ return krb5_enomem(context);
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_authentication_user(krb5_context context,
+ krb5_digest digest,
+ krb5_principal authentication_user)
+{
+ krb5_error_code ret;
+
+ if (digest->request.authentication_user) {
+ krb5_set_error_message(context, EINVAL,
+ N_("authentication_user already set", ""));
+ return EINVAL;
+ }
+ ret = krb5_copy_principal(context,
+ authentication_user,
+ &digest->request.authentication_user);
+ if (ret)
+ return ret;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_realm(krb5_context context,
+ krb5_digest digest,
+ const char *realm)
+{
+ if (digest->request.realm) {
+ krb5_set_error_message(context, EINVAL, "realm already set");
+ return EINVAL;
+ }
+ digest->request.realm = malloc(sizeof(*digest->request.realm));
+ if (digest->request.realm == NULL)
+ return krb5_enomem(context);
+ *digest->request.realm = strdup(realm);
+ if (*digest->request.realm == NULL) {
+ free(digest->request.realm);
+ digest->request.realm = NULL;
+ return krb5_enomem(context);
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_method(krb5_context context,
+ krb5_digest digest,
+ const char *method)
+{
+ if (digest->request.method) {
+ krb5_set_error_message(context, EINVAL,
+ N_("method already set", ""));
+ return EINVAL;
+ }
+ digest->request.method = malloc(sizeof(*digest->request.method));
+ if (digest->request.method == NULL)
+ return krb5_enomem(context);
+ *digest->request.method = strdup(method);
+ if (*digest->request.method == NULL) {
+ free(digest->request.method);
+ digest->request.method = NULL;
+ return krb5_enomem(context);
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_uri(krb5_context context,
+ krb5_digest digest,
+ const char *uri)
+{
+ if (digest->request.uri) {
+ krb5_set_error_message(context, EINVAL, N_("uri already set", ""));
+ return EINVAL;
+ }
+ digest->request.uri = malloc(sizeof(*digest->request.uri));
+ if (digest->request.uri == NULL)
+ return krb5_enomem(context);
+ *digest->request.uri = strdup(uri);
+ if (*digest->request.uri == NULL) {
+ free(digest->request.uri);
+ digest->request.uri = NULL;
+ return krb5_enomem(context);
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_nonceCount(krb5_context context,
+ krb5_digest digest,
+ const char *nonce_count)
+{
+ if (digest->request.nonceCount) {
+ krb5_set_error_message(context, EINVAL,
+ N_("nonceCount already set", ""));
+ return EINVAL;
+ }
+ digest->request.nonceCount =
+ malloc(sizeof(*digest->request.nonceCount));
+ if (digest->request.nonceCount == NULL)
+ return krb5_enomem(context);
+ *digest->request.nonceCount = strdup(nonce_count);
+ if (*digest->request.nonceCount == NULL) {
+ free(digest->request.nonceCount);
+ digest->request.nonceCount = NULL;
+ return krb5_enomem(context);
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_set_qop(krb5_context context,
+ krb5_digest digest,
+ const char *qop)
+{
+ if (digest->request.qop) {
+ krb5_set_error_message(context, EINVAL, "qop already set");
+ return EINVAL;
+ }
+ digest->request.qop = malloc(sizeof(*digest->request.qop));
+ if (digest->request.qop == NULL)
+ return krb5_enomem(context);
+ *digest->request.qop = strdup(qop);
+ if (*digest->request.qop == NULL) {
+ free(digest->request.qop);
+ digest->request.qop = NULL;
+ return krb5_enomem(context);
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_digest_set_responseData(krb5_context context,
+ krb5_digest digest,
+ const char *response)
+{
+ digest->request.responseData = strdup(response);
+ if (digest->request.responseData == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_request(krb5_context context,
+ krb5_digest digest,
+ krb5_realm realm,
+ krb5_ccache ccache)
+{
+ DigestReqInner ireq;
+ DigestRepInner irep;
+ krb5_error_code ret;
+
+ memset(&ireq, 0, sizeof(ireq));
+ memset(&irep, 0, sizeof(irep));
+
+ ireq.element = choice_DigestReqInner_digestRequest;
+ ireq.u.digestRequest = digest->request;
+
+ if (digest->request.type == NULL) {
+ if (digest->init.type == NULL) {
+ krb5_set_error_message(context, EINVAL,
+ N_("Type missing from req", ""));
+ return EINVAL;
+ }
+ ireq.u.digestRequest.type = digest->init.type;
+ }
+
+ if (ireq.u.digestRequest.digest == NULL) {
+ static char md5[] = "md5";
+ ireq.u.digestRequest.digest = md5;
+ }
+
+ ret = digest_request(context, realm, ccache,
+ KRB5_KU_DIGEST_ENCRYPT, &ireq, &irep);
+ if (ret)
+ return ret;
+
+ if (irep.element == choice_DigestRepInner_error) {
+ ret = irep.u.error.code;
+ krb5_set_error_message(context, ret,
+ N_("Digest response error: %s", ""),
+ irep.u.error.reason);
+ goto out;
+ }
+
+ if (irep.element != choice_DigestRepInner_response) {
+ krb5_set_error_message(context, EINVAL,
+ N_("digest reply not an DigestResponse", ""));
+ ret = EINVAL;
+ goto out;
+ }
+
+ ret = copy_DigestResponse(&irep.u.response, &digest->response);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to copy initReply,", ""));
+ goto out;
+ }
+
+ out:
+ free_DigestRepInner(&irep);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_digest_rep_get_status(krb5_context context,
+ krb5_digest digest)
+{
+ return digest->response.success ? TRUE : FALSE;
+}
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+krb5_digest_get_rsp(krb5_context context,
+ krb5_digest digest)
+{
+ if (digest->response.rsp == NULL)
+ return NULL;
+ return *digest->response.rsp;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_get_tickets(krb5_context context,
+ krb5_digest digest,
+ Ticket **tickets)
+{
+ *tickets = NULL;
+ return 0;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_get_client_binding(krb5_context context,
+ krb5_digest digest,
+ char **type,
+ char **binding)
+{
+ if (digest->response.channel) {
+ *type = strdup(digest->response.channel->cb_type);
+ *binding = strdup(digest->response.channel->cb_binding);
+ if (*type == NULL || *binding == NULL) {
+ free(*type);
+ free(*binding);
+ return krb5_enomem(context);
+ }
+ } else {
+ *type = NULL;
+ *binding = NULL;
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_get_session_key(krb5_context context,
+ krb5_digest digest,
+ krb5_data *data)
+{
+ krb5_error_code ret;
+
+ krb5_data_zero(data);
+ if (digest->response.session_key == NULL)
+ return 0;
+ ret = der_copy_octet_string(digest->response.session_key, data);
+ if (ret)
+ krb5_clear_error_message(context);
+
+ return ret;
+}
+
+struct krb5_ntlm_data {
+ NTLMInit init;
+ NTLMInitReply initReply;
+ NTLMRequest request;
+ NTLMResponse response;
+};
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_alloc(krb5_context context,
+ krb5_ntlm *ntlm)
+{
+ *ntlm = calloc(1, sizeof(**ntlm));
+ if (*ntlm == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_free(krb5_context context, krb5_ntlm ntlm)
+{
+ free_NTLMInit(&ntlm->init);
+ free_NTLMInitReply(&ntlm->initReply);
+ free_NTLMRequest(&ntlm->request);
+ free_NTLMResponse(&ntlm->response);
+ memset(ntlm, 0, sizeof(*ntlm));
+ free(ntlm);
+ return 0;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_init_request(krb5_context context,
+ krb5_ntlm ntlm,
+ krb5_realm realm,
+ krb5_ccache ccache,
+ uint32_t flags,
+ const char *hostname,
+ const char *domainname)
+{
+ DigestReqInner ireq;
+ DigestRepInner irep;
+ krb5_error_code ret;
+
+ memset(&ireq, 0, sizeof(ireq));
+ memset(&irep, 0, sizeof(irep));
+
+ ntlm->init.flags = flags;
+ if (hostname) {
+ ALLOC(ntlm->init.hostname, 1);
+ *ntlm->init.hostname = strdup(hostname);
+ }
+ if (domainname) {
+ ALLOC(ntlm->init.domain, 1);
+ *ntlm->init.domain = strdup(domainname);
+ }
+
+ ireq.element = choice_DigestReqInner_ntlmInit;
+ ireq.u.ntlmInit = ntlm->init;
+
+ ret = digest_request(context, realm, ccache,
+ KRB5_KU_DIGEST_ENCRYPT, &ireq, &irep);
+ if (ret)
+ goto out;
+
+ if (irep.element == choice_DigestRepInner_error) {
+ ret = irep.u.error.code;
+ krb5_set_error_message(context, ret, N_("Digest init error: %s", ""),
+ irep.u.error.reason);
+ goto out;
+ }
+
+ if (irep.element != choice_DigestRepInner_ntlmInitReply) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret,
+ N_("ntlm reply not an initReply", ""));
+ goto out;
+ }
+
+ ret = copy_NTLMInitReply(&irep.u.ntlmInitReply, &ntlm->initReply);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to copy initReply", ""));
+ goto out;
+ }
+
+ out:
+ free_DigestRepInner(&irep);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_init_get_flags(krb5_context context,
+ krb5_ntlm ntlm,
+ uint32_t *flags)
+{
+ *flags = ntlm->initReply.flags;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_init_get_challenge(krb5_context context,
+ krb5_ntlm ntlm,
+ krb5_data *challenge)
+{
+ krb5_error_code ret;
+
+ ret = der_copy_octet_string(&ntlm->initReply.challenge, challenge);
+ if (ret)
+ krb5_clear_error_message(context);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_init_get_opaque(krb5_context context,
+ krb5_ntlm ntlm,
+ krb5_data *opaque)
+{
+ krb5_error_code ret;
+
+ ret = der_copy_octet_string(&ntlm->initReply.opaque, opaque);
+ if (ret)
+ krb5_clear_error_message(context);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_init_get_targetname(krb5_context context,
+ krb5_ntlm ntlm,
+ char **name)
+{
+ *name = strdup(ntlm->initReply.targetname);
+ if (*name == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_init_get_targetinfo(krb5_context context,
+ krb5_ntlm ntlm,
+ krb5_data *data)
+{
+ krb5_error_code ret;
+
+ if (ntlm->initReply.targetinfo == NULL) {
+ krb5_data_zero(data);
+ return 0;
+ }
+
+ ret = krb5_data_copy(data,
+ ntlm->initReply.targetinfo->data,
+ ntlm->initReply.targetinfo->length);
+ if (ret) {
+ krb5_clear_error_message(context);
+ return ret;
+ }
+ return 0;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_request(krb5_context context,
+ krb5_ntlm ntlm,
+ krb5_realm realm,
+ krb5_ccache ccache)
+{
+ DigestReqInner ireq;
+ DigestRepInner irep;
+ krb5_error_code ret;
+
+ memset(&ireq, 0, sizeof(ireq));
+ memset(&irep, 0, sizeof(irep));
+
+ ireq.element = choice_DigestReqInner_ntlmRequest;
+ ireq.u.ntlmRequest = ntlm->request;
+
+ ret = digest_request(context, realm, ccache,
+ KRB5_KU_DIGEST_ENCRYPT, &ireq, &irep);
+ if (ret)
+ return ret;
+
+ if (irep.element == choice_DigestRepInner_error) {
+ ret = irep.u.error.code;
+ krb5_set_error_message(context, ret,
+ N_("NTLM response error: %s", ""),
+ irep.u.error.reason);
+ goto out;
+ }
+
+ if (irep.element != choice_DigestRepInner_ntlmResponse) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret,
+ N_("NTLM reply not an NTLMResponse", ""));
+ goto out;
+ }
+
+ ret = copy_NTLMResponse(&irep.u.ntlmResponse, &ntlm->response);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to copy NTLMResponse", ""));
+ goto out;
+ }
+
+ out:
+ free_DigestRepInner(&irep);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_req_set_flags(krb5_context context,
+ krb5_ntlm ntlm,
+ uint32_t flags)
+{
+ ntlm->request.flags = flags;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_req_set_username(krb5_context context,
+ krb5_ntlm ntlm,
+ const char *username)
+{
+ ntlm->request.username = strdup(username);
+ if (ntlm->request.username == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_req_set_targetname(krb5_context context,
+ krb5_ntlm ntlm,
+ const char *targetname)
+{
+ ntlm->request.targetname = strdup(targetname);
+ if (ntlm->request.targetname == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_req_set_lm(krb5_context context,
+ krb5_ntlm ntlm,
+ void *hash, size_t len)
+{
+ ntlm->request.lm.data = malloc(len);
+ if (ntlm->request.lm.data == NULL && len != 0)
+ return krb5_enomem(context);
+ ntlm->request.lm.length = len;
+ memcpy(ntlm->request.lm.data, hash, len);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_req_set_ntlm(krb5_context context,
+ krb5_ntlm ntlm,
+ void *hash, size_t len)
+{
+ ntlm->request.ntlm.data = malloc(len);
+ if (ntlm->request.ntlm.data == NULL && len != 0)
+ return krb5_enomem(context);
+ ntlm->request.ntlm.length = len;
+ memcpy(ntlm->request.ntlm.data, hash, len);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_req_set_opaque(krb5_context context,
+ krb5_ntlm ntlm,
+ krb5_data *opaque)
+{
+ ntlm->request.opaque.data = malloc(opaque->length);
+ if (ntlm->request.opaque.data == NULL && opaque->length != 0)
+ return krb5_enomem(context);
+ ntlm->request.opaque.length = opaque->length;
+ memcpy(ntlm->request.opaque.data, opaque->data, opaque->length);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_req_set_session(krb5_context context,
+ krb5_ntlm ntlm,
+ void *sessionkey, size_t length)
+{
+ ntlm->request.sessionkey = calloc(1, sizeof(*ntlm->request.sessionkey));
+ if (ntlm->request.sessionkey == NULL)
+ return krb5_enomem(context);
+ ntlm->request.sessionkey->data = malloc(length);
+ if (ntlm->request.sessionkey->data == NULL && length != 0)
+ return krb5_enomem(context);
+ memcpy(ntlm->request.sessionkey->data, sessionkey, length);
+ ntlm->request.sessionkey->length = length;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_ntlm_rep_get_status(krb5_context context,
+ krb5_ntlm ntlm)
+{
+ return ntlm->response.success ? TRUE : FALSE;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_rep_get_sessionkey(krb5_context context,
+ krb5_ntlm ntlm,
+ krb5_data *data)
+{
+ if (ntlm->response.sessionkey == NULL) {
+ krb5_set_error_message(context, EINVAL,
+ N_("no ntlm session key", ""));
+ return EINVAL;
+ }
+ krb5_clear_error_message(context);
+ return krb5_data_copy(data,
+ ntlm->response.sessionkey->data,
+ ntlm->response.sessionkey->length);
+}
+
+/**
+ * Get the supported/allowed mechanism for this principal.
+ *
+ * @param context A Keberos context.
+ * @param realm The realm of the KDC.
+ * @param ccache The credential cache to use when talking to the KDC.
+ * @param flags The supported mechanism.
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_digest
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_digest_probe(krb5_context context,
+ krb5_realm realm,
+ krb5_ccache ccache,
+ unsigned *flags)
+{
+ DigestReqInner ireq;
+ DigestRepInner irep;
+ krb5_error_code ret;
+
+ memset(&ireq, 0, sizeof(ireq));
+ memset(&irep, 0, sizeof(irep));
+
+ ireq.element = choice_DigestReqInner_supportedMechs;
+
+ ret = digest_request(context, realm, ccache,
+ KRB5_KU_DIGEST_ENCRYPT, &ireq, &irep);
+ if (ret)
+ goto out;
+
+ if (irep.element == choice_DigestRepInner_error) {
+ ret = irep.u.error.code;
+ krb5_set_error_message(context, ret, "Digest probe error: %s",
+ irep.u.error.reason);
+ goto out;
+ }
+
+ if (irep.element != choice_DigestRepInner_supportedMechs) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret, "Digest reply not an probe");
+ goto out;
+ }
+
+ *flags = DigestTypes2int(irep.u.supportedMechs);
+
+ out:
+ free_DigestRepInner(&irep);
+
+ return ret;
+}
+
+#endif /* HEIMDAL_SMALLER */
diff --git a/third_party/heimdal/lib/krb5/dll.c b/third_party/heimdal/lib/krb5/dll.c
new file mode 100644
index 0000000..80d9fa4
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/dll.c
@@ -0,0 +1,76 @@
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include<windows.h>
+
+extern void heim_w32_service_thread_detach(void *);
+
+HINSTANCE _krb5_hInstance = NULL;
+
+#if NTDDI_VERSION >= NTDDI_VISTA
+extern BOOL WINAPI
+_hc_w32crypto_DllMain(HINSTANCE hinstDLL,
+ DWORD fdwReason,
+ LPVOID lpvReserved);
+#endif
+
+BOOL WINAPI DllMain(HINSTANCE hinstDLL,
+ DWORD fdwReason,
+ LPVOID lpvReserved)
+{
+#if NTDDI_VERSION >= NTDDI_VISTA
+ BOOL ret;
+
+ ret = _hc_w32crypto_DllMain(hinstDLL, fdwReason, lpvReserved);
+ if (!ret)
+ return ret;
+#endif
+
+ switch (fdwReason) {
+ case DLL_PROCESS_ATTACH:
+
+ _krb5_hInstance = hinstDLL;
+ return TRUE;
+
+ case DLL_PROCESS_DETACH:
+ return FALSE;
+
+ case DLL_THREAD_ATTACH:
+ return FALSE;
+
+ case DLL_THREAD_DETACH:
+ heim_w32_service_thread_detach(NULL);
+ return FALSE;
+ }
+
+ return FALSE;
+}
+
diff --git a/third_party/heimdal/lib/krb5/doxygen.c b/third_party/heimdal/lib/krb5/doxygen.c
new file mode 100644
index 0000000..e9266c9
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/doxygen.c
@@ -0,0 +1,700 @@
+/*
+ * Copyright (c) 2007-2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ *
+ */
+
+/*! @mainpage Heimdal Kerberos 5 library
+ *
+ * @section intro Introduction
+ *
+ * Heimdal libkrb5 library is a implementation of the Kerberos
+ * protocol.
+ *
+ * Kerberos is a system for authenticating users and services on a
+ * network. It is built upon the assumption that the network is
+ * ``unsafe''. For example, data sent over the network can be
+ * eavesdropped and altered, and addresses can also be faked.
+ * Therefore they cannot be used for authentication purposes.
+ *
+ *
+ * - @ref krb5_introduction
+ * - @ref krb5_principal_intro
+ * - @ref krb5_ccache_intro
+ * - @ref krb5_keytab_intro
+ *
+ * If you want to know more about the file formats that is used by
+ * Heimdal, please see: @ref krb5_fileformats
+ *
+ * The project web page: http://www.h5l.org/
+ *
+ */
+
+/** @defgroup krb5 Heimdal Kerberos 5 library */
+/** @defgroup krb5_address Heimdal Kerberos 5 address functions */
+/** @defgroup krb5_principal Heimdal Kerberos 5 principal functions */
+/** @defgroup krb5_ccache Heimdal Kerberos 5 credential cache functions */
+/** @defgroup krb5_crypto Heimdal Kerberos 5 cryptography functions */
+/** @defgroup krb5_credential Heimdal Kerberos 5 credential handing functions */
+/** @defgroup krb5_deprecated Heimdal Kerberos 5 deprecated functions */
+/** @defgroup krb5_digest Heimdal Kerberos 5 digest service */
+/** @defgroup krb5_error Heimdal Kerberos 5 error reporting functions */
+/** @defgroup krb5_keytab Heimdal Kerberos 5 keytab handling functions */
+/** @defgroup krb5_ticket Heimdal Kerberos 5 ticket functions */
+/** @defgroup krb5_pac Heimdal Kerberos 5 PAC handling functions */
+/** @defgroup krb5_v4compat Heimdal Kerberos 4 compatiblity functions */
+/** @defgroup krb5_storage Heimdal Kerberos 5 storage functions */
+/** @defgroup krb5_support Heimdal Kerberos 5 support functions */
+/** @defgroup krb5_auth Heimdal Kerberos 5 authentication functions */
+
+
+/**
+ * @page krb5_introduction Introduction to the Kerberos 5 API
+ * @section api_overview Kerberos 5 API Overview
+ *
+ * All functions are documented in manual pages. This section tries
+ * to give an overview of the major components used in Kerberos
+ * library, and point to where to look for a specific function.
+ *
+ * @subsection intro_krb5_context Kerberos context
+ *
+ * A kerberos context (krb5_context) holds all per thread state. All
+ * global variables that are context specific are stored in this
+ * structure, including default encryption types, credential cache
+ * (for example, a ticket file), and default realms.
+ *
+ * The internals of the structure should never be accessed directly,
+ * functions exist for extracting information.
+ *
+ * See the manual page for krb5_init_context() how to create a context
+ * and module @ref krb5 for more information about the functions.
+ *
+ * @subsection intro_krb5_auth_context Kerberos authentication context
+ *
+ * Kerberos authentication context (krb5_auth_context) holds all
+ * context related to an authenticated connection, in a similar way to
+ * the kerberos context that holds the context for the thread or
+ * process.
+ *
+ * The krb5_auth_context is used by various functions that are
+ * directly related to authentication between the
+ * server/client. Example of data that this structure contains are
+ * various flags, addresses of client and server, port numbers,
+ * keyblocks (and subkeys), sequence numbers, replay cache, and
+ * checksum types.
+ *
+ * @subsection intro_krb5_principal Kerberos principal
+ *
+ * The Kerberos principal is the structure that identifies a user or
+ * service in Kerberos. The structure that holds the principal is the
+ * krb5_principal. There are function to extract the realm and
+ * elements of the principal, but most applications have no reason to
+ * inspect the content of the structure.
+ *
+ * The are several ways to create a principal (with different degree of
+ * portability), and one way to free it.
+ *
+ * See also the page @ref krb5_principal_intro for more information and also
+ * module @ref krb5_principal.
+ *
+ * @subsection intro_krb5_ccache Credential cache
+ *
+ * A credential cache holds the tickets for a user. A given user can
+ * have several credential caches, one for each realm where the user
+ * have the initial tickets (the first krbtgt).
+ *
+ * The credential cache data can be stored internally in different
+ * way, each of them for different proposes. File credential (FILE)
+ * caches and processes based (KCM) caches are for permanent
+ * storage. While memory caches (MEMORY) are local caches to the local
+ * process.
+ *
+ * Caches are opened with krb5_cc_resolve() or created with
+ * krb5_cc_new_unique().
+ *
+ * If the cache needs to be opened again (using krb5_cc_resolve())
+ * krb5_cc_close() will close the handle, but not the remove the
+ * cache. krb5_cc_destroy() will zero out the cache, remove the cache
+ * so it can no longer be referenced.
+ *
+ * See also @ref krb5_ccache_intro and @ref krb5_ccache .
+ *
+ * @subsection intro_krb5_error_code Kerberos errors
+ *
+ * Kerberos errors are based on the com_err library. All error codes are
+ * 32-bit signed numbers, the first 24 bits define what subsystem the
+ * error originates from, and last 8 bits are 255 error codes within the
+ * library. Each error code have fixed string associated with it. For
+ * example, the error-code -1765328383 have the symbolic name
+ * KRB5KDC_ERR_NAME_EXP, and associated error string ``Client's entry in
+ * database has expired''.
+ *
+ * This is a great improvement compared to just getting one of the unix
+ * error-codes back. However, Heimdal have an extention to pass back
+ * customised errors messages. Instead of getting ``Key table entry not
+ * found'', the user might back ``failed to find
+ * host/host.example.com\@EXAMLE.COM(kvno 3) in keytab /etc/krb5.keytab
+ * (des-cbc-crc)''. This improves the chance that the user find the
+ * cause of the error so you should use the customised error message
+ * whenever it's available.
+ *
+ * See also module @ref krb5_error .
+ *
+ *
+ * @subsection intro_krb5_keytab Keytab management
+ *
+ * A keytab is a storage for locally stored keys. Heimdal includes keytab
+ * support for Kerberos 5 keytabs, Kerberos 4 srvtab, AFS-KeyFile's,
+ * and for storing keys in memory.
+ *
+ * Keytabs are used for servers and long-running services.
+ *
+ * See also @ref krb5_keytab_intro and @ref krb5_keytab .
+ *
+ * @subsection intro_krb5_crypto Kerberos crypto
+ *
+ * Heimdal includes a implementation of the Kerberos crypto framework,
+ * all crypto operations. To create a crypto context call krb5_crypto_init().
+ *
+ * See also module @ref krb5_crypto .
+ *
+ * @section kerberos5_client Walkthrough of a sample Kerberos 5 client
+ *
+ * This example contains parts of a sample TCP Kerberos 5 clients, if you
+ * want a real working client, please look in appl/test directory in
+ * the Heimdal distribution.
+ *
+ * All Kerberos error-codes that are returned from kerberos functions in
+ * this program are passed to krb5_err, that will print a
+ * descriptive text of the error code and exit. Graphical programs can
+ * convert error-code to a human readable error-string with the
+ * krb5_get_error_message() function.
+ *
+ * Note that you should not use any Kerberos function before
+ * krb5_init_context() have completed successfully. That is the
+ * reason err() is used when krb5_init_context() fails.
+ *
+ * First the client needs to call krb5_init_context to initialise
+ * the Kerberos 5 library. This is only needed once per thread
+ * in the program. If the function returns a non-zero value it indicates
+ * that either the Kerberos implementation is failing or it's disabled on
+ * this host.
+ *
+ * @code
+ * #include <krb5.h>
+ *
+ * int
+ * main(int argc, char **argv)
+ * {
+ * krb5_context context;
+ *
+ * if (krb5_init_context(&context))
+ * errx (1, "krb5_context");
+ * @endcode
+ *
+ * Now the client wants to connect to the host at the other end. The
+ * preferred way of doing this is using getaddrinfo (for
+ * operating system that have this function implemented), since getaddrinfo
+ * is neutral to the address type and can use any protocol that is available.
+ *
+ * @code
+ * struct addrinfo *ai, *a;
+ * struct addrinfo hints;
+ * int error;
+ *
+ * memset (&hints, 0, sizeof(hints));
+ * hints.ai_socktype = SOCK_STREAM;
+ * hints.ai_protocol = IPPROTO_TCP;
+ *
+ * error = getaddrinfo (hostname, "pop3", &hints, &ai);
+ * if (error)
+ * errx (1, "%s: %s", hostname, gai_strerror(error));
+ *
+ * for (a = ai; a != NULL; a = a->ai_next) {
+ * int s;
+ *
+ * s = socket (a->ai_family, a->ai_socktype, a->ai_protocol);
+ * if (s < 0)
+ * continue;
+ * if (connect (s, a->ai_addr, a->ai_addrlen) < 0) {
+ * warn ("connect(%s)", hostname);
+ * close (s);
+ * continue;
+ * }
+ * freeaddrinfo (ai);
+ * ai = NULL;
+ * }
+ * if (ai) {
+ * freeaddrinfo (ai);
+ * errx ("failed to contact %s", hostname);
+ * }
+ * @endcode
+ *
+ * Before authenticating, an authentication context needs to be
+ * created. This context keeps all information for one (to be) authenticated
+ * connection (see krb5_auth_context).
+ *
+ * @code
+ * status = krb5_auth_con_init (context, &auth_context);
+ * if (status)
+ * krb5_err (context, 1, status, "krb5_auth_con_init");
+ * @endcode
+ *
+ * For setting the address in the authentication there is a help function
+ * krb5_auth_con_setaddrs_from_fd() that does everything that is needed
+ * when given a connected file descriptor to the socket.
+ *
+ * @code
+ * status = krb5_auth_con_setaddrs_from_fd (context,
+ * auth_context,
+ * &sock);
+ * if (status)
+ * krb5_err (context, 1, status,
+ * "krb5_auth_con_setaddrs_from_fd");
+ * @endcode
+ *
+ * The next step is to build a server principal for the service we want
+ * to connect to. (See also krb5_sname_to_principal().)
+ *
+ * @code
+ * status = krb5_sname_to_principal (context,
+ * hostname,
+ * service,
+ * KRB5_NT_SRV_HST,
+ * &server);
+ * if (status)
+ * krb5_err (context, 1, status, "krb5_sname_to_principal");
+ * @endcode
+ *
+ * The client principal is not passed to krb5_sendauth()
+ * function, this causes the krb5_sendauth() function to try to figure it
+ * out itself.
+ *
+ * The server program is using the function krb5_recvauth() to
+ * receive the Kerberos 5 authenticator.
+ *
+ * In this case, mutual authentication will be tried. That means that the server
+ * will authenticate to the client. Using mutual authentication
+ * is required to avoid man-in-the-middle attacks, since it enables the user to
+ * verify that they are talking to the right server (a server that knows the key).
+ *
+ * If you are using a non-blocking socket you will need to do all work of
+ * krb5_sendauth() yourself. Basically you need to send over the
+ * authenticator from krb5_mk_req() and, in case of mutual
+ * authentication, verifying the result from the server with
+ * krb5_rd_rep().
+ *
+ * @code
+ * status = krb5_sendauth (context,
+ * &auth_context,
+ * &sock,
+ * VERSION,
+ * NULL,
+ * server,
+ * AP_OPTS_MUTUAL_REQUIRED,
+ * NULL,
+ * NULL,
+ * NULL,
+ * NULL,
+ * NULL,
+ * NULL);
+ * if (status)
+ * krb5_err (context, 1, status, "krb5_sendauth");
+ * @endcode
+ *
+ * Once authentication has been performed, it is time to send some
+ * data. First we create a krb5_data structure, then we sign it with
+ * krb5_mk_safe() using the auth_context that contains the
+ * session-key that was exchanged in the
+ * krb5_sendauth()/krb5_recvauth() authentication
+ * sequence.
+ *
+ * @code
+ * data.data = "hej";
+ * data.length = 3;
+ *
+ * krb5_data_zero (&packet);
+ *
+ * status = krb5_mk_safe (context,
+ * auth_context,
+ * &data,
+ * &packet,
+ * NULL);
+ * if (status)
+ * krb5_err (context, 1, status, "krb5_mk_safe");
+ * @endcode
+ *
+ * And send it over the network.
+ *
+ * @code
+ * len = packet.length;
+ * net_len = htonl(len);
+ *
+ * if (krb5_net_write (context, &sock, &net_len, 4) != 4)
+ * err (1, "krb5_net_write");
+ * if (krb5_net_write (context, &sock, packet.data, len) != len)
+ * err (1, "krb5_net_write");
+ * @endcode
+ *
+ * To send encrypted (and signed) data krb5_mk_priv() should be
+ * used instead. krb5_mk_priv() works the same way as
+ * krb5_mk_safe(), with the exception that it encrypts the data
+ * in addition to signing it.
+ *
+ * @code
+ * data.data = "hemligt";
+ * data.length = 7;
+ *
+ * krb5_data_free (&packet);
+ *
+ * status = krb5_mk_priv (context,
+ * auth_context,
+ * &data,
+ * &packet,
+ * NULL);
+ * if (status)
+ * krb5_err (context, 1, status, "krb5_mk_priv");
+ * @endcode
+ *
+ * And send it over the network.
+ *
+ * @code
+ * len = packet.length;
+ * net_len = htonl(len);
+ *
+ * if (krb5_net_write (context, &sock, &net_len, 4) != 4)
+ * err (1, "krb5_net_write");
+ * if (krb5_net_write (context, &sock, packet.data, len) != len)
+ * err (1, "krb5_net_write");
+ *
+ * @endcode
+ *
+ * The server is using krb5_rd_safe() and
+ * krb5_rd_priv() to verify the signature and decrypt the packet.
+ *
+ * @section intro_krb5_verify_user Validating a password in an application
+ *
+ * See the manual page for krb5_verify_user().
+ *
+ * @section mit_differences API differences to MIT Kerberos
+ *
+ * This section is somewhat disorganised, but so far there is no overall
+ * structure to the differences, though some of the have their root in
+ * that Heimdal uses an ASN.1 compiler and MIT doesn't.
+ *
+ * @subsection mit_krb5_principal Principal and realms
+ *
+ * Heimdal stores the realm as a krb5_realm, that is a char *.
+ * MIT Kerberos uses a krb5_data to store a realm.
+ *
+ * In Heimdal krb5_principal doesn't contain the component
+ * name_type; it's instead stored in component
+ * name.name_type. To get and set the nametype in Heimdal, use
+ * krb5_principal_get_type() and
+ * krb5_principal_set_type().
+ *
+ * For more information about principal and realms, see
+ * krb5_principal.
+ *
+ * @subsection mit_krb5_error_code Error messages
+ *
+ * To get the error string, Heimdal uses
+ * krb5_get_error_message(). This is to return custom error messages
+ * (like ``Can't find host/datan.example.com\@CODE.COM in
+ * /etc/krb5.conf.'' instead of a ``Key table entry not found'' that
+ * error_message returns.
+ *
+ * Heimdal uses a threadsafe(r) version of the com_err interface; the
+ * global com_err table isn't initialised. Then
+ * error_message returns quite a boring error string (just
+ * the error code itself).
+ *
+ *
+ */
+
+/**
+ *
+ *
+ * @page krb5_fileformats File formats
+ *
+ * @section fileformats File formats
+ *
+ * This section documents the diffrent file formats that are used in
+ * Heimdal and other Kerberos implementations.
+ *
+ * @subsection file_keytab keytab
+ *
+ * The keytab binary format is not a standard format. The format has
+ * evolved and may continue to. It is however understood by several
+ * Kerberos implementations including Heimdal, MIT, Sun's Java ktab and
+ * are created by the ktpass.exe utility from Windows. So it has
+ * established itself as the defacto format for storing Kerberos keys.
+ *
+ * The following C-like structure definitions illustrate the MIT keytab
+ * file format. All values are in network byte order. All text is ASCII.
+ *
+ * @code
+ * keytab {
+ * uint16_t file_format_version; # 0x502
+ * keytab_entry entries[*];
+ * };
+ *
+ * keytab_entry {
+ * int32_t size;
+ * uint16_t num_components; # subtract 1 if version 0x501
+ * counted_octet_string realm;
+ * counted_octet_string components[num_components];
+ * uint32_t name_type; # not present if version 0x501
+ * uint32_t timestamp;
+ * uint8_t vno8;
+ * keyblock key;
+ * uint32_t vno; #only present if >= 4 bytes left in entry
+ * uint32_t flags; #only present if >= 4 bytes left in entry
+ * };
+ *
+ * counted_octet_string {
+ * uint16_t length;
+ * uint8_t data[length];
+ * };
+ *
+ * keyblock {
+ * uint16_t type;
+ * counted_octet_string;
+ * };
+ * @endcode
+ *
+ * All numbers are stored in network byteorder (big endian) format.
+ *
+ * The keytab file format begins with the 16 bit file_format_version which
+ * at the time this document was authored is 0x502. The format of older
+ * keytabs is described at the end of this document.
+ *
+ * The file_format_version is immediately followed by an array of
+ * keytab_entry structures which are prefixed with a 32 bit size indicating
+ * the number of bytes that follow in the entry. Note that the size should be
+ * evaluated as signed. This is because a negative value indicates that the
+ * entry is in fact empty (e.g. it has been deleted) and that the negative
+ * value of that negative value (which is of course a positive value) is
+ * the offset to the next keytab_entry. Based on these size values alone
+ * the entire keytab file can be traversed.
+ *
+ * The size is followed by a 16 bit num_components field indicating the
+ * number of counted_octet_string components in the components array.
+ *
+ * The num_components field is followed by a counted_octet_string
+ * representing the realm of the principal.
+ *
+ * A counted_octet_string is simply an array of bytes prefixed with a 16
+ * bit length. For the realm and name components, the counted_octet_string
+ * bytes are ASCII encoded text with no zero terminator.
+ *
+ * Following the realm is the components array that represents the name of
+ * the principal. The text of these components may be joined with slashs
+ * to construct the typical SPN representation. For example, the service
+ * principal HTTP/www.foo.net\@FOO.NET would consist of name components
+ * "HTTP" followed by "www.foo.net".
+ *
+ * Following the components array is the 32 bit name_type (e.g. 1 is
+ * KRB5_NT_PRINCIPAL, 2 is KRB5_NT_SRV_INST, 5 is KRB5_NT_UID, etc). In
+ * practice the name_type is almost certainly 1 meaning KRB5_NT_PRINCIPAL.
+ *
+ * The 32 bit timestamp indicates the time the key was established for that
+ * principal. The value represents the number of seconds since Jan 1, 1970.
+ *
+ * The 8 bit vno8 field is the version number of the key. This value is
+ * overridden by the 32 bit vno field if it is present. The vno8 field is
+ * filled with the lower 8 bits of the 32 bit protocol kvno field.
+ *
+ * The keyblock structure consists of a 16 bit value indicating the
+ * encryption type and is a counted_octet_string containing the key. The
+ * encryption type is the same as the Kerberos standard (e.g. 3 is
+ * des-cbc-md5, 23 is arcfour-hmac-md5, etc).
+ *
+ * The last field of the keytab_entry structure is optional. If the size of
+ * the keytab_entry indicates that there are at least 4 bytes remaining,
+ * a 32 bit value representing the key version number is present. This
+ * value supersedes the 8 bit vno8 value preceeding the keyblock.
+ *
+ * Older keytabs with a file_format_version of 0x501 are different in
+ * three ways:
+ *
+ * - All integers are in host byte order [1].
+ * - The num_components field is 1 too large (i.e. after decoding, decrement by 1).
+ * - The 32 bit name_type field is not present.
+ *
+ * [1] The file_format_version field should really be treated as two
+ * separate 8 bit quantities representing the major and minor version
+ * number respectively.
+ *
+ * @subsection file_hdb_dump Heimdal database dump file
+ *
+ * Format of the Heimdal text dump file as of Heimdal 0.6.3:
+ *
+ * Each line in the dump file is one entry in the database.
+ *
+ * Each field of a line is separated by one or more spaces, with the
+ * exception of fields consisting of principals containing spaces, where
+ * space can be quoted with \ and \ is quoted by \.
+ *
+ * Fields and their types are:
+ *
+ * @code
+ * Quoted principal (quote character is \) [string]
+ * Keys [keys]
+ * Created by [event]
+ * Modified by [event optional]
+ * Valid start time [time optional]
+ * Valid end time [time optional]
+ * Password end valid time [time optional]
+ * Max lifetime of ticket [time optional]
+ * Max renew time of ticket [integer optional]
+ * Flags [hdb flags]
+ * Generation number [generation optional]
+ * Extensions [extentions optional]
+ * @endcode
+ *
+ * Fields following these silently are ignored.
+ *
+ * All optional fields will be skipped if they fail to parse (or comprise
+ * the optional field marker of "-", w/o quotes).
+ *
+ * Example:
+ *
+ * @code
+ * fred\@CODE.COM 27:1:16:e8b4c8fc7e60b9e641dcf4cff3f08a701d982a2f89ba373733d26ca59ba6c789666f6b8bfcf169412bb1e5dceb9b33cda29f3412:-:1:3:4498a933881178c744f4232172dcd774c64e81fa6d05ecdf643a7e390624a0ebf3c7407a:-:1:2:b01934b13eb795d76f3a80717d469639b4da0cfb644161340ef44fdeb375e54d684dbb85:-:1:1:ea8e16d8078bf60c781da90f508d4deccba70595258b9d31888d33987cd31af0c9cced2e:- 20020415130120:admin\@CODE.COM 20041221112428:fred\@CODE.COM - - - 86400 604800 126 20020415130120:793707:28 -
+ * @endcode
+ *
+ * Encoding of types are as follows:
+ *
+ * - keys
+ *
+ * @code
+ * kvno:[masterkvno:keytype:keydata:salt]{zero or more separated by :}
+ * @endcode
+ *
+ * kvno is the key version number.
+ *
+ * keydata is hex-encoded
+ *
+ * masterkvno is the kvno of the database master key. If this field is
+ * empty, the kadmin load and merge operations will encrypt the key data
+ * with the master key if there is one. Otherwise the key data will be
+ * imported asis.
+ *
+ * salt is encoded as "-" (no/default salt) or
+ *
+ * @code
+ * salt-type /
+ * salt-type / "string"
+ * salt-type / hex-encoded-data
+ * @endcode
+ *
+ * keytype is the protocol enctype number; see enum ENCTYPE in
+ * include/krb5_asn1.h for values.
+ *
+ * Example:
+ * @code
+ * 27:1:16:e8b4c8fc7e60b9e641dcf4cff3f08a701d982a2f89ba373733d26ca59ba6c789666f6b8bfcf169412bb1e5dceb9b33cda29f3412:-:1:3:4498a933881178c744f4232172dcd774c64e81fa6d05ecdf643a7e390624a0ebf3c7407a:-:1:2:b01934b13eb795d76f3a80717d469639b4da0cfb644161340ef44fdeb375e54d684dbb85:-:1:1:ea8e16d8078bf60c781da90f508d4deccba70595258b9d31888d33987cd31af0c9cced2e:-
+ * @endcode
+ *
+ *
+ * @code
+ * kvno=27,{key: masterkvno=1,keytype=des3-cbc-sha1,keydata=..., default salt}...
+ * @endcode
+ *
+ * - time
+ *
+ * Format of the time is: YYYYmmddHHMMSS, corresponding to strftime
+ * format "%Y%m%d%k%M%S".
+ *
+ * Time is expressed in UTC.
+ *
+ * Time can be optional (using -), when the time 0 is used.
+ *
+ * Example:
+ *
+ * @code
+ * 20041221112428
+ * @endcode
+ *
+ * - event
+ *
+ * @code
+ * time:principal
+ * @endcode
+ *
+ * time is as given in format time
+ *
+ * principal is a string. Not quoting it may not work in earlier
+ * versions of Heimdal.
+ *
+ * Example:
+ * @code
+ * 20041221112428:bloggs\@CODE.COM
+ * @endcode
+ *
+ * - hdb flags
+ *
+ * Integer encoding of HDB flags, see HDBFlags in lib/hdb/hdb.asn1. Each
+ * bit in the integer is the same as the bit in the specification.
+ *
+ * - generation:
+ *
+ * @code
+ * time:usec:gen
+ * @endcode
+ *
+ *
+ * usec is a the microsecond, integer.
+ * gen is generation number, integer.
+ *
+ * The generation can be defaulted (using '-') or the empty string
+ *
+ * - extensions:
+ *
+ * @code
+ * first-hex-encoded-HDB-Extension[:second-...]
+ * @endcode
+ *
+ * HDB-extension is encoded the DER encoded HDB-Extension from
+ * lib/hdb/hdb.asn1. Consumers HDB extensions should be aware that
+ * unknown entires needs to be preserved even thought the ASN.1 data
+ * content might be unknown. There is a critical flag in the data to show
+ * to the KDC that the entry MUST be understod if the entry is to be
+ * used.
+ *
+ *
+ */
diff --git a/third_party/heimdal/lib/krb5/eai_to_heim_errno.c b/third_party/heimdal/lib/krb5/eai_to_heim_errno.c
new file mode 100644
index 0000000..a6e14ab
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/eai_to_heim_errno.c
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2000 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ * Convert the getaddrinfo() error code to a Kerberos et error code.
+ *
+ * @param eai_errno contains the error code from getaddrinfo().
+ * @param system_error should have the value of errno after the failed getaddrinfo().
+ *
+ * @return Kerberos error code representing the EAI errors.
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_eai_to_heim_errno(int eai_errno, int system_error)
+{
+ switch(eai_errno) {
+ case EAI_NOERROR:
+ return 0;
+#ifdef EAI_ADDRFAMILY
+ case EAI_ADDRFAMILY:
+ return HEIM_EAI_ADDRFAMILY;
+#endif
+ case EAI_AGAIN:
+ return HEIM_EAI_AGAIN;
+ case EAI_BADFLAGS:
+ return HEIM_EAI_BADFLAGS;
+ case EAI_FAIL:
+ return HEIM_EAI_FAIL;
+ case EAI_FAMILY:
+ return HEIM_EAI_FAMILY;
+ case EAI_MEMORY:
+ return HEIM_EAI_MEMORY;
+#if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME
+ case EAI_NODATA:
+ return HEIM_EAI_NODATA;
+#endif
+#ifdef WSANO_DATA
+ case WSANO_DATA:
+ return HEIM_EAI_NODATA;
+#endif
+ case EAI_NONAME:
+ return HEIM_EAI_NONAME;
+ case EAI_SERVICE:
+ return HEIM_EAI_SERVICE;
+ case EAI_SOCKTYPE:
+ return HEIM_EAI_SOCKTYPE;
+#ifdef EAI_SYSTEM
+ case EAI_SYSTEM:
+ return system_error;
+#endif
+ default:
+ return HEIM_EAI_UNKNOWN; /* XXX */
+ }
+}
+
+/**
+ * Convert the gethostname() error code (h_error) to a Kerberos et
+ * error code.
+ *
+ * @param eai_errno contains the error code from gethostname().
+ *
+ * @return Kerberos error code representing the gethostname errors.
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_h_errno_to_heim_errno(int eai_errno)
+{
+ switch(eai_errno) {
+ case 0:
+ return 0;
+ case HOST_NOT_FOUND:
+ return HEIM_EAI_NONAME;
+ case TRY_AGAIN:
+ return HEIM_EAI_AGAIN;
+ case NO_RECOVERY:
+ return HEIM_EAI_FAIL;
+ case NO_DATA:
+ return HEIM_EAI_NONAME;
+ default:
+ return HEIM_EAI_UNKNOWN; /* XXX */
+ }
+}
diff --git a/third_party/heimdal/lib/krb5/enomem.c b/third_party/heimdal/lib/krb5/enomem.c
new file mode 100644
index 0000000..b4444e5
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/enomem.c
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#undef krb5_enomem
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_enomem(krb5_context context)
+{
+ krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
+ return ENOMEM;
+}
diff --git a/third_party/heimdal/lib/krb5/error_string.c b/third_party/heimdal/lib/krb5/error_string.c
new file mode 100644
index 0000000..da86b37
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/error_string.c
@@ -0,0 +1,236 @@
+/*
+ * Copyright (c) 2001, 2003, 2005 - 2020 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#undef __attribute__
+#define __attribute__(x)
+
+/**
+ * Clears the error message from the Kerberos 5 context.
+ *
+ * @param context The Kerberos 5 context to clear
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_clear_error_message(krb5_context context)
+{
+ heim_clear_error_message(context->hcontext);
+}
+
+/**
+ * Set the context full error string for a specific error code.
+ * The error that is stored should be internationalized.
+ *
+ * The if context is NULL, no error string is stored.
+ *
+ * @param context Kerberos 5 context
+ * @param ret The error code
+ * @param fmt Error string for the error code
+ * @param ... printf(3) style parameters.
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_set_error_message(krb5_context context, krb5_error_code ret,
+ const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 3, 4)))
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ krb5_vset_error_message (context, ret, fmt, ap);
+ va_end(ap);
+}
+
+/**
+ * Set the context full error string for a specific error code.
+ *
+ * The if context is NULL, no error string is stored.
+ *
+ * @param context Kerberos 5 context
+ * @param ret The error code
+ * @param fmt Error string for the error code
+ * @param args printf(3) style parameters.
+ *
+ * @ingroup krb5_error
+ */
+
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_vset_error_message(krb5_context context, krb5_error_code ret,
+ const char *fmt, va_list args)
+ __attribute__ ((__format__ (__printf__, 3, 0)))
+{
+ const char *msg;
+
+ if (context == NULL)
+ return;
+
+ heim_vset_error_message(context->hcontext, ret, fmt, args);
+ msg = heim_get_error_message(context->hcontext, ret);
+ if (msg) {
+ _krb5_debug(context, 100, "error message: %s: %d", msg, ret);
+ heim_free_error_message(context->hcontext, msg);
+ }
+}
+
+/**
+ * Prepend the context full error string for a specific error code.
+ * The error that is stored should be internationalized.
+ *
+ * The if context is NULL, no error string is stored.
+ *
+ * @param context Kerberos 5 context
+ * @param ret The error code
+ * @param fmt Error string for the error code
+ * @param ... printf(3) style parameters.
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_prepend_error_message(krb5_context context, krb5_error_code ret,
+ const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 3, 4)))
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ krb5_vprepend_error_message(context, ret, fmt, ap);
+ va_end(ap);
+}
+
+/**
+ * Prepend the contexts's full error string for a specific error code.
+ *
+ * The if context is NULL, no error string is stored.
+ *
+ * @param context Kerberos 5 context
+ * @param ret The error code
+ * @param fmt Error string for the error code
+ * @param args printf(3) style parameters.
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_vprepend_error_message(krb5_context context, krb5_error_code ret,
+ const char *fmt, va_list args)
+ __attribute__ ((__format__ (__printf__, 3, 0)))
+{
+ if (context)
+ heim_vprepend_error_message(context->hcontext, ret, fmt, args);
+}
+
+/**
+ * Return the error message for `code' in context. On memory
+ * allocation error the function returns NULL.
+ *
+ * @param context Kerberos 5 context
+ * @param code Error code related to the error
+ *
+ * @return an error string, needs to be freed with
+ * krb5_free_error_message(). The functions return NULL on error.
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+krb5_get_error_message(krb5_context context, krb5_error_code code)
+{
+ const char *cstr = NULL;
+
+ if (code == 0)
+ return strdup("Success");
+
+ /*
+ * The MIT version of this function ignores the krb5_context
+ * and several widely deployed applications call krb5_get_error_message()
+ * with a NULL context in order to translate an error code as a
+ * replacement for error_message(). Another reason a NULL context
+ * might be provided is if the krb5_init_context() call itself
+ * failed.
+ */
+ if (context == NULL && krb5_init_context(&context) == 0) {
+ cstr = heim_get_error_message(context->hcontext, code);
+ krb5_free_context(context);
+ } else if (context) {
+ cstr = heim_get_error_message(context->hcontext, code);
+ } else {
+ cstr = heim_get_error_message(NULL, code);
+ }
+ return cstr;
+}
+
+
+/**
+ * Free the error message returned by krb5_get_error_message().
+ *
+ * @param context Kerberos context
+ * @param msg error message to free, returned byg
+ * krb5_get_error_message().
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_error_message(krb5_context context, const char *msg)
+{
+ heim_free_error_message(context ? context->hcontext : NULL, msg);
+}
+
+
+/**
+ * Return the error string for the error code. The caller must not
+ * free the string.
+ *
+ * This function is deprecated since its not threadsafe.
+ *
+ * @param context Kerberos 5 context.
+ * @param code Kerberos error code.
+ *
+ * @return the error message matching code
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_get_err_text(krb5_context context, krb5_error_code code)
+ KRB5_DEPRECATED_FUNCTION("Use krb5_get_error_message instead")
+{
+ return krb5_get_error_message(context, code);
+}
diff --git a/third_party/heimdal/lib/krb5/expand_hostname.c b/third_party/heimdal/lib/krb5/expand_hostname.c
new file mode 100644
index 0000000..5023d16
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/expand_hostname.c
@@ -0,0 +1,177 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+static krb5_error_code
+copy_hostname(krb5_context context,
+ const char *orig_hostname,
+ char **new_hostname)
+{
+ *new_hostname = strdup (orig_hostname);
+ if (*new_hostname == NULL)
+ return krb5_enomem(context);
+ strlwr (*new_hostname);
+ return 0;
+}
+
+/**
+ * krb5_expand_hostname() tries to make orig_hostname into a more
+ * canonical one in the newly allocated space returned in
+ * new_hostname.
+
+ * @param context a Keberos context
+ * @param orig_hostname hostname to canonicalise.
+ * @param new_hostname output hostname, caller must free hostname with
+ * krb5_xfree().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_expand_hostname (krb5_context context,
+ const char *orig_hostname,
+ char **new_hostname)
+{
+ struct addrinfo *ai, *a, hints;
+ int error;
+
+ if ((context->flags & KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME) == 0)
+ return copy_hostname (context, orig_hostname, new_hostname);
+
+ memset (&hints, 0, sizeof(hints));
+ hints.ai_flags = AI_CANONNAME;
+
+ error = getaddrinfo (orig_hostname, NULL, &hints, &ai);
+ if (error)
+ return copy_hostname (context, orig_hostname, new_hostname);
+ for (a = ai; a != NULL; a = a->ai_next) {
+ if (a->ai_canonname != NULL) {
+ *new_hostname = strdup (a->ai_canonname);
+ freeaddrinfo (ai);
+ if (*new_hostname == NULL)
+ return krb5_enomem(context);
+ else
+ return 0;
+ }
+ }
+ freeaddrinfo (ai);
+ return copy_hostname (context, orig_hostname, new_hostname);
+}
+
+/*
+ * handle the case of the hostname being unresolvable and thus identical
+ */
+
+static krb5_error_code
+vanilla_hostname (krb5_context context,
+ const char *orig_hostname,
+ char **new_hostname,
+ char ***realms)
+{
+ krb5_error_code ret;
+
+ ret = copy_hostname (context, orig_hostname, new_hostname);
+ if (ret)
+ return ret;
+ strlwr (*new_hostname);
+
+ ret = krb5_get_host_realm (context, *new_hostname, realms);
+ if (ret) {
+ free (*new_hostname);
+ return ret;
+ }
+ return 0;
+}
+
+/**
+ * krb5_expand_hostname_realms() expands orig_hostname to a name we
+ * believe to be a hostname in newly allocated space in new_hostname
+ * and return the realms new_hostname is believed to belong to in
+ * realms.
+ *
+ * @param context a Keberos context
+ * @param orig_hostname hostname to canonicalise.
+ * @param new_hostname output hostname, caller must free hostname with
+ * krb5_xfree().
+ * @param realms output possible realms, is an array that is terminated
+ * with NULL. Caller must free with krb5_free_host_realm().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_expand_hostname_realms (krb5_context context,
+ const char *orig_hostname,
+ char **new_hostname,
+ char ***realms)
+{
+ struct addrinfo *ai, *a, hints;
+ int error;
+ krb5_error_code ret = 0;
+
+ if ((context->flags & KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME) == 0)
+ return vanilla_hostname (context, orig_hostname, new_hostname,
+ realms);
+
+ memset (&hints, 0, sizeof(hints));
+ hints.ai_flags = AI_CANONNAME;
+
+ error = getaddrinfo (orig_hostname, NULL, &hints, &ai);
+ if (error)
+ return vanilla_hostname (context, orig_hostname, new_hostname,
+ realms);
+
+ for (a = ai; a != NULL; a = a->ai_next) {
+ if (a->ai_canonname != NULL) {
+ ret = copy_hostname (context, a->ai_canonname, new_hostname);
+ if (ret) {
+ freeaddrinfo (ai);
+ return ret;
+ }
+ strlwr (*new_hostname);
+ ret = krb5_get_host_realm (context, *new_hostname, realms);
+ if (ret == 0) {
+ freeaddrinfo (ai);
+ return 0;
+ }
+ free (*new_hostname);
+ }
+ }
+ freeaddrinfo(ai);
+ return vanilla_hostname (context, orig_hostname, new_hostname, realms);
+}
diff --git a/third_party/heimdal/lib/krb5/expand_path.c b/third_party/heimdal/lib/krb5/expand_path.c
new file mode 100644
index 0000000..a040235
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/expand_path.c
@@ -0,0 +1,94 @@
+
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include "krb5_locl.h"
+
+#include <stdarg.h>
+
+/**
+ * Internal function to expand tokens in paths.
+ *
+ * Inputs:
+ *
+ * @context A krb5_context
+ * @path_in The path to expand tokens from
+ * @filepath True if the value is a filesystem path (converts slashes to
+ * backslashes on Windows)
+ * @ppath_out The expanded path
+ *
+ * Outputs:
+ *
+ * @ppath_out Path with expanded tokens (caller must free() this)
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_expand_path_tokens(krb5_context context,
+ const char *path_in,
+ int filepath,
+ char **ppath_out)
+{
+ return heim_expand_path_tokens(context ? context->hcontext : NULL, path_in,
+ filepath, ppath_out, NULL);
+}
+
+/**
+ * Internal function to expand tokens in paths.
+ *
+ * Inputs:
+ *
+ * @context A krb5_context
+ * @path_in The path to expand tokens from
+ * @filepath True if the value is a filesystem path (converts slashes to
+ * backslashes on Windows)
+ * @ppath_out The expanded path
+ * @... Variable number of pairs of strings, the first of each
+ * being a token (e.g., "luser") and the second a string to
+ * replace it with. The list is terminated by a NULL.
+ *
+ * Outputs:
+ *
+ * @ppath_out Path with expanded tokens (caller must free() this)
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_expand_path_tokensv(krb5_context context,
+ const char *path_in,
+ int filepath,
+ char **ppath_out, ...)
+{
+ krb5_error_code ret;
+ va_list ap;
+
+ va_start(ap, ppath_out);
+ ret = heim_expand_path_tokensv(context->hcontext, path_in, filepath, ppath_out, ap);
+ va_end(ap);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/fast.c b/third_party/heimdal/lib/krb5/fast.c
new file mode 100644
index 0000000..8389354
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/fast.c
@@ -0,0 +1,962 @@
+/*
+ * Copyright (c) 2011 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#ifndef WIN32
+#include <heim-ipc.h>
+#endif
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_fast_cf2(krb5_context context,
+ krb5_keyblock *key1,
+ const char *pepper1,
+ krb5_keyblock *key2,
+ const char *pepper2,
+ krb5_keyblock *armorkey,
+ krb5_crypto *armor_crypto)
+{
+ krb5_crypto crypto1, crypto2;
+ krb5_data pa1, pa2;
+ krb5_error_code ret;
+
+ ret = krb5_crypto_init(context, key1, 0, &crypto1);
+ if (ret)
+ return ret;
+
+ ret = krb5_crypto_init(context, key2, 0, &crypto2);
+ if (ret) {
+ krb5_crypto_destroy(context, crypto1);
+ return ret;
+ }
+
+ pa1.data = rk_UNCONST(pepper1);
+ pa1.length = strlen(pepper1);
+ pa2.data = rk_UNCONST(pepper2);
+ pa2.length = strlen(pepper2);
+
+ ret = krb5_crypto_fx_cf2(context, crypto1, crypto2, &pa1, &pa2,
+ key1->keytype, armorkey);
+ krb5_crypto_destroy(context, crypto1);
+ krb5_crypto_destroy(context, crypto2);
+ if (ret)
+ return ret;
+
+ if (armor_crypto) {
+ ret = krb5_crypto_init(context, armorkey, 0, armor_crypto);
+ if (ret)
+ krb5_free_keyblock_contents(context, armorkey);
+ }
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_fast_armor_key(krb5_context context,
+ krb5_keyblock *subkey,
+ krb5_keyblock *sessionkey,
+ krb5_keyblock *armorkey,
+ krb5_crypto *armor_crypto)
+{
+ return _krb5_fast_cf2(context,
+ subkey,
+ "subkeyarmor",
+ sessionkey,
+ "ticketarmor",
+ armorkey,
+ armor_crypto);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_fast_explicit_armor_key(krb5_context context,
+ krb5_keyblock *armorkey,
+ krb5_keyblock *subkey,
+ krb5_keyblock *explicit_armorkey,
+ krb5_crypto *explicit_armor_crypto)
+{
+ return _krb5_fast_cf2(context,
+ armorkey,
+ "explicitarmor",
+ subkey,
+ "tgsarmor",
+ explicit_armorkey,
+ explicit_armor_crypto);
+}
+
+static krb5_error_code
+check_fast(krb5_context context, struct krb5_fast_state *state)
+{
+ if (state && (state->flags & KRB5_FAST_EXPECTED)) {
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+ "Expected FAST, but no FAST "
+ "was in the response from the KDC");
+ return KRB5KRB_AP_ERR_MODIFIED;
+ }
+ return 0;
+}
+
+static krb5_error_code
+make_local_fast_ap_fxarmor(krb5_context context,
+ krb5_ccache armor_ccache,
+ krb5_const_realm realm,
+ krb5_data *armor_value,
+ krb5_keyblock *armor_key,
+ krb5_crypto *armor_crypto)
+{
+ krb5_auth_context auth_context = NULL;
+ krb5_creds cred, *credp = NULL;
+ krb5_error_code ret;
+ krb5_data empty;
+ krb5_const_realm tgs_realm;
+
+ if (armor_ccache == NULL) {
+ krb5_set_error_message(context, EINVAL,
+ "Armor credential cache required");
+ return EINVAL;
+ }
+
+ krb5_data_zero(&empty);
+ memset(&cred, 0, sizeof(cred));
+
+ ret = krb5_auth_con_init (context, &auth_context);
+ if (ret)
+ goto out;
+
+ ret = krb5_cc_get_principal(context, armor_ccache, &cred.client);
+ if (ret)
+ goto out;
+
+ /*
+ * Make sure we don't ask for a krbtgt/WELLKNOWN:ANONYMOUS
+ */
+ if (krb5_principal_is_anonymous(context, cred.client,
+ KRB5_ANON_MATCH_UNAUTHENTICATED))
+ tgs_realm = realm;
+ else
+ tgs_realm = cred.client->realm;
+
+ ret = krb5_make_principal(context, &cred.server,
+ tgs_realm,
+ KRB5_TGS_NAME,
+ tgs_realm,
+ NULL);
+ if (ret)
+ goto out;
+
+ ret = krb5_get_credentials(context, 0, armor_ccache, &cred, &credp);
+ if (ret)
+ goto out;
+
+ ret = krb5_auth_con_add_AuthorizationData(context, auth_context,
+ KRB5_AUTHDATA_FX_FAST_ARMOR,
+ &empty);
+ if (ret)
+ goto out;
+
+ ret = krb5_mk_req_extended(context,
+ &auth_context,
+ AP_OPTS_USE_SUBKEY,
+ NULL,
+ credp,
+ armor_value);
+ if (ret)
+ goto out;
+
+ ret = _krb5_fast_armor_key(context,
+ auth_context->local_subkey,
+ auth_context->keyblock,
+ armor_key,
+ armor_crypto);
+ if (ret)
+ goto out;
+
+ out:
+ if (auth_context)
+ krb5_auth_con_free(context, auth_context);
+ if (credp)
+ krb5_free_creds(context, credp);
+ krb5_free_principal(context, cred.server);
+ krb5_free_principal(context, cred.client);
+
+ return ret;
+}
+
+#ifndef WIN32
+static heim_base_once_t armor_service_once = HEIM_BASE_ONCE_INIT;
+static heim_ipc armor_service = NULL;
+
+static void
+fast_armor_init_ipc(void *ctx)
+{
+ heim_ipc *ipc = ctx;
+ heim_ipc_init_context("ANY:org.h5l.armor-service", ipc);
+}
+#endif
+
+static krb5_error_code
+make_fast_ap_fxarmor(krb5_context context,
+ struct krb5_fast_state *state,
+ krb5_const_realm realm,
+ KrbFastArmor **armor)
+{
+ KrbFastArmor *fxarmor = NULL;
+ krb5_error_code ret;
+
+ *armor = NULL;
+
+ ALLOC(fxarmor, 1);
+ if (fxarmor == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ if (state->flags & KRB5_FAST_AP_ARMOR_SERVICE) {
+#ifdef WIN32
+ krb5_set_error_message(context, ENOTSUP, "Fast armor IPC service not supportted yet on Windows");
+ ret = ENOTSUP;
+ goto out;
+#else
+ KERB_ARMOR_SERVICE_REPLY msg;
+ krb5_data request, reply;
+
+ heim_base_once_f(&armor_service_once, &armor_service, fast_armor_init_ipc);
+ if (armor_service == NULL) {
+ krb5_set_error_message(context, ENOENT, "Failed to open fast armor service");
+ ret = ENOENT;
+ goto out;
+ }
+
+ krb5_data_zero(&reply);
+
+ request.data = rk_UNCONST(realm);
+ request.length = strlen(realm);
+
+ ret = heim_ipc_call(armor_service, &request, &reply, NULL);
+ if (ret) {
+ krb5_set_error_message(context, ret, "Failed to get armor service credential");
+ goto out;
+ }
+
+ ret = decode_KERB_ARMOR_SERVICE_REPLY(reply.data, reply.length, &msg, NULL);
+ krb5_data_free(&reply);
+ if (ret)
+ goto out;
+
+ ret = copy_KrbFastArmor(fxarmor, &msg.armor);
+ if (ret) {
+ free_KERB_ARMOR_SERVICE_REPLY(&msg);
+ goto out;
+ }
+
+ ret = krb5_copy_keyblock_contents(context, &msg.armor_key, &state->armor_key);
+ free_KERB_ARMOR_SERVICE_REPLY(&msg);
+ if (ret)
+ goto out;
+
+ ret = krb5_crypto_init(context, &state->armor_key, 0, &state->armor_crypto);
+ if (ret)
+ goto out;
+#endif /* WIN32 */
+ } else {
+ fxarmor->armor_type = 1;
+
+ ret = make_local_fast_ap_fxarmor(context,
+ state->armor_ccache,
+ realm,
+ &fxarmor->armor_value,
+ &state->armor_key,
+ &state->armor_crypto);
+ if (ret)
+ goto out;
+ }
+
+
+ *armor = fxarmor;
+ fxarmor = NULL;
+
+ out:
+ if (fxarmor) {
+ free_KrbFastArmor(fxarmor);
+ free(fxarmor);
+ }
+ return ret;
+}
+
+static krb5_error_code
+unwrap_fast_rep(krb5_context context,
+ struct krb5_fast_state *state,
+ PA_DATA *pa,
+ KrbFastResponse *fastrep)
+{
+ PA_FX_FAST_REPLY fxfastrep;
+ krb5_error_code ret;
+
+ memset(&fxfastrep, 0, sizeof(fxfastrep));
+
+ ret = decode_PA_FX_FAST_REPLY(pa->padata_value.data,
+ pa->padata_value.length,
+ &fxfastrep, NULL);
+ if (ret)
+ return ret;
+
+ if (fxfastrep.element == choice_PA_FX_FAST_REPLY_armored_data) {
+ krb5_data data;
+
+ ret = krb5_decrypt_EncryptedData(context,
+ state->armor_crypto,
+ KRB5_KU_FAST_REP,
+ &fxfastrep.u.armored_data.enc_fast_rep,
+ &data);
+ if (ret)
+ goto out;
+
+ ret = decode_KrbFastResponse(data.data, data.length, fastrep, NULL);
+ krb5_data_free(&data);
+ if (ret)
+ goto out;
+
+ } else {
+ ret = KRB5KDC_ERR_PREAUTH_FAILED;
+ goto out;
+ }
+
+ out:
+ free_PA_FX_FAST_REPLY(&fxfastrep);
+
+ return ret;
+}
+
+static krb5_error_code
+set_anon_principal(krb5_context context, PrincipalName **p)
+{
+
+ ALLOC((*p), 1);
+ if (*p == NULL)
+ goto fail;
+
+ (*p)->name_type = KRB5_NT_PRINCIPAL;
+
+ ALLOC_SEQ(&(*p)->name_string, 2);
+ if ((*p)->name_string.val == NULL)
+ goto fail;
+
+ (*p)->name_string.val[0] = strdup(KRB5_WELLKNOWN_NAME);
+ if ((*p)->name_string.val[0] == NULL)
+ goto fail;
+
+ (*p)->name_string.val[1] = strdup(KRB5_ANON_NAME);
+ if ((*p)->name_string.val[1] == NULL)
+ goto fail;
+
+ return 0;
+ fail:
+ if (*p) {
+ if ((*p)->name_string.val) {
+ free((*p)->name_string.val[0]);
+ free((*p)->name_string.val[1]);
+ free((*p)->name_string.val);
+ }
+ free(*p);
+ }
+
+ return krb5_enomem(context);
+}
+
+krb5_error_code
+_krb5_fast_create_armor(krb5_context context,
+ struct krb5_fast_state *state,
+ const char *realm)
+{
+ krb5_error_code ret;
+
+ if (state->armor_crypto == NULL) {
+ if (state->armor_ccache || state->armor_ac || (state->flags & KRB5_FAST_AP_ARMOR_SERVICE)) {
+ /*
+ * Instead of keeping state in FX_COOKIE in the KDC, we
+ * rebuild a new armor key for every request, because this
+ * is what the MIT KDC expect and RFC6113 is vage about
+ * what the behavior should be.
+ */
+ state->type = choice_PA_FX_FAST_REQUEST_armored_data;
+ } else {
+ return check_fast(context, state);
+ }
+ }
+
+ if (state->type == choice_PA_FX_FAST_REQUEST_armored_data) {
+ if (state->armor_crypto) {
+ krb5_crypto_destroy(context, state->armor_crypto);
+ state->armor_crypto = NULL;
+ }
+ if (state->strengthen_key) {
+ krb5_free_keyblock(context, state->strengthen_key);
+ state->strengthen_key = NULL;
+ }
+ krb5_free_keyblock_contents(context, &state->armor_key);
+
+ /*
+ * If we have a armor auth context, its because the caller
+ * wants us to do an implicit FAST armor (TGS-REQ).
+ */
+ if (state->armor_ac) {
+ heim_assert((state->flags & KRB5_FAST_AS_REQ) == 0, "FAST AS with AC");
+
+ ret = _krb5_fast_armor_key(context,
+ state->armor_ac->local_subkey,
+ state->armor_ac->keyblock,
+ &state->armor_key,
+ &state->armor_crypto);
+ if (ret)
+ goto out;
+ } else {
+ heim_assert((state->flags & KRB5_FAST_AS_REQ) != 0, "FAST TGS without AC");
+
+ if (state->armor_data) {
+ free_KrbFastArmor(state->armor_data);
+ free(state->armor_data);
+ state->armor_data = NULL;
+ }
+ ret = make_fast_ap_fxarmor(context, state, realm,
+ &state->armor_data);
+ if (ret)
+ goto out;
+ }
+ } else {
+ heim_abort("unknown state type: %d", (int)state->type);
+ }
+ out:
+ return ret;
+}
+
+
+krb5_error_code
+_krb5_fast_wrap_req(krb5_context context,
+ struct krb5_fast_state *state,
+ KDC_REQ *req)
+{
+ PA_FX_FAST_REQUEST fxreq;
+ krb5_error_code ret;
+ KrbFastReq fastreq;
+ krb5_data data, aschecksum_data, tgschecksum_data;
+ const krb5_data *checksum_data = NULL;
+ size_t size = 0;
+ krb5_boolean readd_padata_to_outer = FALSE;
+
+ if (state->flags & KRB5_FAST_DISABLED) {
+ _krb5_debug(context, 10, "fast disabled, not doing any fast wrapping");
+ return 0;
+ }
+
+ memset(&fxreq, 0, sizeof(fxreq));
+ memset(&fastreq, 0, sizeof(fastreq));
+ krb5_data_zero(&data);
+ krb5_data_zero(&aschecksum_data);
+ krb5_data_zero(&tgschecksum_data);
+
+ if (state->armor_crypto == NULL)
+ return check_fast(context, state);
+
+ state->flags |= KRB5_FAST_EXPECTED;
+
+ fastreq.fast_options.hide_client_names = 1;
+
+ ret = copy_KDC_REQ_BODY(&req->req_body, &fastreq.req_body);
+ if (ret)
+ goto out;
+
+ /*
+ * In the case of a AS-REQ, remove all account names. Want to this
+ * for TGS-REQ too, but due to layering this is tricky.
+ *
+ * 1. TGS-REQ need checksum of REQ-BODY
+ * 2. FAST needs checksum of TGS-REQ, so, FAST needs to happen after TGS-REQ
+ * 3. FAST privacy mangaling needs to happen before TGS-REQ does the checksum in 1.
+ *
+ * So lets not modify the bits for now for TGS-REQ
+ */
+ if (state->flags & KRB5_FAST_AS_REQ) {
+ free_KDC_REQ_BODY(&req->req_body);
+
+ req->req_body.realm = strdup(KRB5_ANON_REALM);
+ if (req->req_body.realm == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ ret = set_anon_principal(context, &req->req_body.cname);
+ if (ret)
+ goto out;
+
+ ALLOC(req->req_body.till, 1);
+ *req->req_body.till = 0;
+
+ ASN1_MALLOC_ENCODE(KDC_REQ_BODY,
+ aschecksum_data.data,
+ aschecksum_data.length,
+ &req->req_body,
+ &size, ret);
+ if (ret)
+ goto out;
+ heim_assert(aschecksum_data.length == size, "ASN.1 internal error");
+
+ checksum_data = &aschecksum_data;
+
+ if (req->padata) {
+ ret = copy_METHOD_DATA(req->padata, &fastreq.padata);
+ free_METHOD_DATA(req->padata);
+ if (ret)
+ goto out;
+ }
+ } else {
+ const PA_DATA *tgs_req_ptr = NULL;
+ int tgs_req_idx = 0;
+ size_t i;
+
+ heim_assert(req->padata != NULL, "req->padata is NULL");
+
+ tgs_req_ptr = krb5_find_padata(req->padata->val,
+ req->padata->len,
+ KRB5_PADATA_TGS_REQ,
+ &tgs_req_idx);
+ heim_assert(tgs_req_ptr != NULL, "KRB5_PADATA_TGS_REQ not found");
+ heim_assert(tgs_req_idx == 0, "KRB5_PADATA_TGS_REQ not first");
+
+ tgschecksum_data.data = tgs_req_ptr->padata_value.data;
+ tgschecksum_data.length = tgs_req_ptr->padata_value.length;
+ checksum_data = &tgschecksum_data;
+
+ /*
+ * Now copy all remaining once to
+ * the fastreq.padata and clear
+ * them in the outer req first,
+ * and remember to readd them later.
+ */
+ readd_padata_to_outer = TRUE;
+
+ for (i = 1; i < req->padata->len; i++) {
+ PA_DATA *val = &req->padata->val[i];
+
+ ret = krb5_padata_add(context,
+ &fastreq.padata,
+ val->padata_type,
+ val->padata_value.data,
+ val->padata_value.length);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("malloc: out of memory", ""));
+ goto out;
+ }
+ val->padata_value.data = NULL;
+ val->padata_value.length = 0;
+ }
+
+ /*
+ * Only TGS-REQ remaining
+ */
+ req->padata->len = 1;
+ }
+
+ if (req->padata == NULL) {
+ ALLOC(req->padata, 1);
+ if (req->padata == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ }
+
+ ASN1_MALLOC_ENCODE(KrbFastReq, data.data, data.length, &fastreq, &size, ret);
+ if (ret)
+ goto out;
+ heim_assert(data.length == size, "ASN.1 internal error");
+
+ fxreq.element = state->type;
+
+ if (state->type == choice_PA_FX_FAST_REQUEST_armored_data) {
+ fxreq.u.armored_data.armor = state->armor_data;
+ state->armor_data = NULL;
+
+ heim_assert(state->armor_crypto != NULL,
+ "FAST armor key missing when FAST started");
+
+ ret = krb5_create_checksum(context, state->armor_crypto,
+ KRB5_KU_FAST_REQ_CHKSUM, 0,
+ checksum_data->data,
+ checksum_data->length,
+ &fxreq.u.armored_data.req_checksum);
+ if (ret)
+ goto out;
+
+ ret = krb5_encrypt_EncryptedData(context, state->armor_crypto,
+ KRB5_KU_FAST_ENC,
+ data.data,
+ data.length,
+ 0,
+ &fxreq.u.armored_data.enc_fast_req);
+ krb5_data_free(&data);
+ if (ret)
+ goto out;
+
+ } else {
+ krb5_data_free(&data);
+ heim_assert(false, "unknown FAST type, internal error");
+ }
+
+ ASN1_MALLOC_ENCODE(PA_FX_FAST_REQUEST, data.data, data.length, &fxreq, &size, ret);
+ if (ret)
+ goto out;
+ heim_assert(data.length == size, "ASN.1 internal error");
+
+
+ ret = krb5_padata_add(context, req->padata, KRB5_PADATA_FX_FAST, data.data, data.length);
+ if (ret)
+ goto out;
+ krb5_data_zero(&data);
+
+ if (readd_padata_to_outer) {
+ size_t i;
+
+ for (i = 0; i < fastreq.padata.len; i++) {
+ PA_DATA *val = &fastreq.padata.val[i];
+
+ ret = krb5_padata_add(context,
+ req->padata,
+ val->padata_type,
+ val->padata_value.data,
+ val->padata_value.length);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("malloc: out of memory", ""));
+ goto out;
+ }
+ val->padata_value.data = NULL;
+ val->padata_value.length = 0;
+ }
+ }
+
+ out:
+ free_KrbFastReq(&fastreq);
+ free_PA_FX_FAST_REQUEST(&fxreq);
+ krb5_data_free(&data);
+ krb5_data_free(&aschecksum_data);
+
+ return ret;
+}
+
+krb5_error_code
+_krb5_fast_unwrap_error(krb5_context context,
+ int32_t nonce,
+ struct krb5_fast_state *state,
+ METHOD_DATA *md,
+ KRB_ERROR *error)
+{
+ KrbFastResponse fastrep;
+ krb5_error_code ret;
+ PA_DATA *pa;
+ int idx;
+
+ if (state->armor_crypto == NULL)
+ return check_fast(context, state);
+
+ memset(&fastrep, 0, sizeof(fastrep));
+
+ idx = 0;
+ pa = krb5_find_padata(md->val, md->len, KRB5_PADATA_FX_FAST, &idx);
+ if (pa == NULL) {
+ ret = KRB5_KDCREP_MODIFIED;
+ krb5_set_error_message(context, ret,
+ N_("FAST fast response is missing FX-FAST", ""));
+ goto out;
+ }
+
+ ret = unwrap_fast_rep(context, state, pa, &fastrep);
+ if (ret)
+ goto out;
+
+ if (fastrep.strengthen_key || nonce != (int32_t)fastrep.nonce) {
+ ret = KRB5KDC_ERR_PREAUTH_FAILED;
+ goto out;
+ }
+
+ idx = 0;
+ pa = krb5_find_padata(fastrep.padata.val, fastrep.padata.len, KRB5_PADATA_FX_ERROR, &idx);
+ if (pa == NULL) {
+ ret = KRB5_KDCREP_MODIFIED;
+ krb5_set_error_message(context, ret, N_("No wrapped error", ""));
+ goto out;
+ }
+
+ free_KRB_ERROR(error);
+
+ ret = krb5_rd_error(context, &pa->padata_value, error);
+ if (ret)
+ goto out;
+
+ if (error->e_data)
+ _krb5_debug(context, 10, "FAST wrapped KBB_ERROR contained e_data: %d",
+ (int)error->e_data->length);
+
+ free_METHOD_DATA(md);
+ md->val = fastrep.padata.val;
+ md->len = fastrep.padata.len;
+
+ fastrep.padata.val = NULL;
+ fastrep.padata.len = 0;
+
+ out:
+ free_KrbFastResponse(&fastrep);
+ return ret;
+}
+
+krb5_error_code
+_krb5_fast_unwrap_kdc_rep(krb5_context context, int32_t nonce,
+ krb5_data *chksumdata,
+ struct krb5_fast_state *state, AS_REP *rep)
+{
+ KrbFastResponse fastrep;
+ krb5_error_code ret;
+ PA_DATA *pa = NULL;
+ int idx = 0;
+
+ if (state == NULL || state->armor_crypto == NULL || rep->padata == NULL)
+ return check_fast(context, state);
+
+ /* find PA_FX_FAST_REPLY */
+
+ pa = krb5_find_padata(rep->padata->val, rep->padata->len,
+ KRB5_PADATA_FX_FAST, &idx);
+ if (pa == NULL)
+ return check_fast(context, state);
+
+ memset(&fastrep, 0, sizeof(fastrep));
+
+ ret = unwrap_fast_rep(context, state, pa, &fastrep);
+ if (ret)
+ goto out;
+
+ free_METHOD_DATA(rep->padata);
+ ret = copy_METHOD_DATA(&fastrep.padata, rep->padata);
+ if (ret)
+ goto out;
+
+ if (fastrep.strengthen_key) {
+ if (state->strengthen_key)
+ krb5_free_keyblock(context, state->strengthen_key);
+
+ ret = krb5_copy_keyblock(context, fastrep.strengthen_key, &state->strengthen_key);
+ if (ret)
+ goto out;
+ }
+
+ if (nonce != (int32_t)fastrep.nonce) {
+ ret = KRB5KDC_ERR_PREAUTH_FAILED;
+ goto out;
+ }
+ if (fastrep.finished) {
+ PrincipalName cname;
+ krb5_realm crealm = NULL;
+
+ if (chksumdata == NULL) {
+ ret = KRB5KDC_ERR_PREAUTH_FAILED;
+ goto out;
+ }
+
+ ret = krb5_verify_checksum(context, state->armor_crypto,
+ KRB5_KU_FAST_FINISHED,
+ chksumdata->data, chksumdata->length,
+ &fastrep.finished->ticket_checksum);
+ if (ret)
+ goto out;
+
+ /* update */
+ ret = copy_Realm(&fastrep.finished->crealm, &crealm);
+ if (ret)
+ goto out;
+ free_Realm(&rep->crealm);
+ rep->crealm = crealm;
+
+ ret = copy_PrincipalName(&fastrep.finished->cname, &cname);
+ if (ret)
+ goto out;
+ free_PrincipalName(&rep->cname);
+ rep->cname = cname;
+ } else if (chksumdata) {
+ /* expected fastrep.finish but didn't get it */
+ ret = KRB5KDC_ERR_PREAUTH_FAILED;
+ }
+
+ out:
+ free_KrbFastResponse(&fastrep);
+ return ret;
+}
+
+void
+_krb5_fast_free(krb5_context context, struct krb5_fast_state *state)
+{
+ if (state->armor_ccache) {
+ if (state->flags & KRB5_FAST_ANON_PKINIT_ARMOR)
+ krb5_cc_destroy(context, state->armor_ccache);
+ else
+ krb5_cc_close(context, state->armor_ccache);
+ }
+ if (state->armor_service)
+ krb5_free_principal(context, state->armor_service);
+ if (state->armor_crypto)
+ krb5_crypto_destroy(context, state->armor_crypto);
+ if (state->strengthen_key)
+ krb5_free_keyblock(context, state->strengthen_key);
+ krb5_free_keyblock_contents(context, &state->armor_key);
+ if (state->armor_data) {
+ free_KrbFastArmor(state->armor_data);
+ free(state->armor_data);
+ }
+
+ if (state->anon_pkinit_ctx)
+ krb5_init_creds_free(context, state->anon_pkinit_ctx);
+ if (state->anon_pkinit_opt)
+ krb5_get_init_creds_opt_free(context, state->anon_pkinit_opt);
+
+ memset(state, 0, sizeof(*state));
+}
+
+krb5_error_code
+_krb5_fast_anon_pkinit_step(krb5_context context,
+ krb5_init_creds_context ctx,
+ struct krb5_fast_state *state,
+ krb5_data *in,
+ krb5_data *out,
+ krb5_krbhst_info *hostinfo,
+ unsigned int *flags)
+{
+ krb5_error_code ret;
+ krb5_const_realm realm = _krb5_init_creds_get_cred_client(context, ctx)->realm;
+ krb5_init_creds_context anon_pk_ctx;
+ krb5_principal principal = NULL, anon_pk_client;
+ krb5_ccache ccache = NULL;
+ krb5_creds cred;
+ krb5_data data = { 3, rk_UNCONST("yes") };
+
+ memset(&cred, 0, sizeof(cred));
+
+ if (state->anon_pkinit_opt == NULL) {
+ ret = krb5_get_init_creds_opt_alloc(context, &state->anon_pkinit_opt);
+ if (ret)
+ goto out;
+
+ krb5_get_init_creds_opt_set_tkt_life(state->anon_pkinit_opt, 60);
+ krb5_get_init_creds_opt_set_anonymous(state->anon_pkinit_opt, TRUE);
+
+ ret = krb5_make_principal(context, &principal, realm,
+ KRB5_WELLKNOWN_NAME, KRB5_ANON_NAME, NULL);
+ if (ret)
+ return ret;
+
+ ret = krb5_get_init_creds_opt_set_pkinit(context,
+ state->anon_pkinit_opt,
+ principal,
+ NULL, NULL, NULL, NULL,
+ KRB5_GIC_OPT_PKINIT_ANONYMOUS |
+ KRB5_GIC_OPT_PKINIT_NO_KDC_ANCHOR,
+ NULL, NULL, NULL);
+ if (ret)
+ goto out;
+
+ ret = krb5_init_creds_init(context, principal, NULL, NULL,
+ _krb5_init_creds_get_cred_starttime(context, ctx),
+ state->anon_pkinit_opt,
+ &state->anon_pkinit_ctx);
+ if (ret)
+ goto out;
+ }
+
+ anon_pk_ctx = state->anon_pkinit_ctx;
+
+ ret = krb5_init_creds_step(context, anon_pk_ctx, in, out, hostinfo, flags);
+ if (ret ||
+ (*flags & KRB5_INIT_CREDS_STEP_FLAG_CONTINUE))
+ goto out;
+
+ ret = krb5_process_last_request(context, state->anon_pkinit_opt, anon_pk_ctx);
+ if (ret)
+ goto out;
+
+ ret = krb5_cc_new_unique(context, "MEMORY", NULL, &ccache);
+ if (ret)
+ goto out;
+
+ ret = krb5_init_creds_get_creds(context, anon_pk_ctx, &cred);
+ if (ret)
+ goto out;
+
+ if (!cred.flags.b.enc_pa_rep) {
+ ret = KRB5KDC_ERR_BADOPTION; /* KDC does not support FAST */
+ goto out;
+ }
+
+ anon_pk_client = _krb5_init_creds_get_cred_client(context, anon_pk_ctx);
+
+ ret = krb5_cc_initialize(context, ccache, anon_pk_client);
+ if (ret)
+ goto out;
+
+ ret = krb5_cc_store_cred(context, ccache, &cred);
+ if (ret)
+ goto out;
+
+ ret = krb5_cc_set_config(context, ccache, cred.server,
+ "fast_avail", &data);
+ if (ret && ret != KRB5_CC_NOSUPP)
+ return ret;
+
+ if (_krb5_pk_is_kdc_verified(context, state->anon_pkinit_opt))
+ state->flags |= KRB5_FAST_KDC_VERIFIED;
+ else
+ state->flags &= ~(KRB5_FAST_KDC_VERIFIED);
+
+ state->armor_ccache = ccache;
+ ccache = NULL;
+
+ krb5_init_creds_free(context, state->anon_pkinit_ctx);
+ state->anon_pkinit_ctx = NULL;
+
+ krb5_get_init_creds_opt_free(context, state->anon_pkinit_opt);
+ state->anon_pkinit_opt = NULL;
+
+ *flags |= KRB5_INIT_CREDS_STEP_FLAG_CONTINUE;
+
+out:
+ krb5_free_principal(context, principal);
+ krb5_free_cred_contents(context, &cred);
+ if (ccache)
+ krb5_cc_destroy(context, ccache);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/fcache.c b/third_party/heimdal/lib/krb5/fcache.c
new file mode 100644
index 0000000..30dff35
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/fcache.c
@@ -0,0 +1,1693 @@
+/*
+ * Copyright (c) 1997 - 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+typedef struct krb5_fcache{
+ char *filename;
+ char *res;
+ char *sub;
+ char *tmpfn;
+ int version;
+}krb5_fcache;
+
+struct fcc_cursor {
+ int fd;
+ off_t cred_start;
+ off_t cred_end;
+ krb5_storage *sp;
+};
+
+#define KRB5_FCC_FVNO_1 1
+#define KRB5_FCC_FVNO_2 2
+#define KRB5_FCC_FVNO_3 3
+#define KRB5_FCC_FVNO_4 4
+
+#define FCC_TAG_DELTATIME 1
+
+#define FCACHE(X) ((krb5_fcache*)(X)->data.data)
+
+#define FILENAME(X) (FCACHE(X)->filename)
+#define TMPFILENAME(X) (FCACHE(X)->tmpfn)
+#define RESFILENAME(X) (FCACHE(X)->res)
+#define SUBFILENAME(X) (FCACHE(X)->sub)
+
+#define FCC_CURSOR(C) ((struct fcc_cursor*)(C))
+
+static krb5_error_code KRB5_CALLCONV
+fcc_get_name_2(krb5_context context,
+ krb5_ccache id,
+ const char **name,
+ const char **colname,
+ const char **sub)
+{
+ if (FCACHE(id) == NULL)
+ return KRB5_CC_NOTFOUND;
+
+ if (name)
+ *name = FILENAME(id);
+ if (colname)
+ *colname = FILENAME(id);
+ if (sub)
+ *sub = NULL;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+_krb5_xlock(krb5_context context, int fd, krb5_boolean exclusive,
+ const char *filename)
+{
+ int ret;
+#ifdef HAVE_FCNTL
+ struct flock l;
+
+ l.l_start = 0;
+ l.l_len = 0;
+ l.l_type = exclusive ? F_WRLCK : F_RDLCK;
+ l.l_whence = SEEK_SET;
+ ret = fcntl(fd, F_SETLKW, &l);
+#else
+ ret = flock(fd, exclusive ? LOCK_EX : LOCK_SH);
+#endif
+ if(ret < 0)
+ ret = errno;
+ if(ret == EACCES) /* fcntl can return EACCES instead of EAGAIN */
+ ret = EAGAIN;
+
+ switch (ret) {
+ case 0:
+ break;
+ case EINVAL: /* filesystem doesn't support locking, let the user have it */
+ ret = 0;
+ break;
+ case EAGAIN:
+ krb5_set_error_message(context, ret,
+ N_("timed out locking cache file %s", "file"),
+ filename);
+ break;
+ default: {
+ char buf[128];
+ rk_strerror_r(ret, buf, sizeof(buf));
+ krb5_set_error_message(context, ret,
+ N_("error locking cache file %s: %s",
+ "file, error"), filename, buf);
+ break;
+ }
+ }
+ return ret;
+}
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+_krb5_xunlock(krb5_context context, int fd)
+{
+ int ret;
+#ifdef HAVE_FCNTL
+ struct flock l;
+ l.l_start = 0;
+ l.l_len = 0;
+ l.l_type = F_UNLCK;
+ l.l_whence = SEEK_SET;
+ ret = fcntl(fd, F_SETLKW, &l);
+#else
+ ret = flock(fd, LOCK_UN);
+#endif
+ if (ret < 0)
+ ret = errno;
+ switch (ret) {
+ case 0:
+ break;
+ case EINVAL: /* filesystem doesn't support locking, let the user have it */
+ ret = 0;
+ break;
+ default: {
+ char buf[128];
+ rk_strerror_r(ret, buf, sizeof(buf));
+ krb5_set_error_message(context, ret,
+ N_("Failed to unlock file: %s", ""), buf);
+ break;
+ }
+ }
+ return ret;
+}
+
+static krb5_error_code
+write_storage(krb5_context context, krb5_storage *sp, int fd)
+{
+ krb5_error_code ret;
+ krb5_data data;
+ ssize_t sret;
+
+ ret = krb5_storage_to_data(sp, &data);
+ if (ret) {
+ krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+ return ret;
+ }
+ sret = write(fd, data.data, data.length);
+ ret = (sret != (ssize_t)data.length);
+ krb5_data_free(&data);
+ if (ret) {
+ ret = errno;
+ krb5_set_error_message(context, ret,
+ N_("Failed to write FILE credential data", ""));
+ return ret;
+ }
+ return 0;
+}
+
+
+static krb5_error_code KRB5_CALLCONV
+fcc_lock(krb5_context context, krb5_ccache id,
+ int fd, krb5_boolean exclusive)
+{
+ krb5_error_code ret;
+ const char *name;
+
+ if (exclusive == FALSE)
+ return 0;
+ ret = fcc_get_name_2(context, id, &name, NULL, NULL);
+ if (ret == 0)
+ ret = _krb5_xlock(context, fd, exclusive, name);
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_get_default_name(krb5_context, char **);
+
+/*
+ * This is the character used to separate the residual from the subsidiary name
+ * when both are given. It's tempting to use ':' just as we do in the ccache
+ * names, but we can't on Windows.
+ */
+#define FILESUBSEP "+"
+#define FILESUBSEPCHR ((FILESUBSEP)[0])
+
+static krb5_error_code KRB5_CALLCONV
+fcc_resolve_2(krb5_context context,
+ krb5_ccache *id,
+ const char *res,
+ const char *sub)
+{
+ krb5_fcache *f;
+ char *freeme = NULL;
+
+ if (res == NULL && sub == NULL)
+ return krb5_einval(context, 3);
+ if (res == NULL) {
+ krb5_error_code ret;
+
+ if ((ret = fcc_get_default_name(context, &freeme)))
+ return ret;
+ res = freeme + sizeof("FILE:") - 1;
+ } else if (!sub && (sub = strchr(res, FILESUBSEPCHR))) {
+ if (sub[1] == '\0') {
+ sub = NULL;
+ } else {
+ /* `res' has a subsidiary component, so split on it */
+ if ((freeme = strndup(res, sub - res)) == NULL)
+ return krb5_enomem(context);
+ res = freeme;
+ sub++;
+ }
+ }
+
+ if ((f = calloc(1, sizeof(*f))) == NULL ||
+ (f->res = strdup(res)) == NULL ||
+ (f->sub = sub ? strdup(sub) : NULL) == (sub ? NULL : "") ||
+ asprintf(&f->filename, "%s%s%s",
+ res, sub ? FILESUBSEP : "", sub ? sub : "") == -1 ||
+ f->filename == NULL) {
+ if (f) {
+ free(f->filename);
+ free(f->res);
+ free(f->sub);
+ }
+ free(f);
+ free(freeme);
+ return krb5_enomem(context);
+ }
+ f->tmpfn = NULL;
+ f->version = 0;
+ (*id)->data.data = f;
+ (*id)->data.length = sizeof(*f);
+
+ free(freeme);
+ return 0;
+}
+
+/*
+ * Try to scrub the contents of `filename' safely.
+ */
+
+static int
+scrub_file (int fd)
+{
+ off_t pos;
+ char buf[128];
+
+ pos = lseek(fd, 0, SEEK_END);
+ if (pos < 0)
+ return errno;
+ if (lseek(fd, 0, SEEK_SET) < 0)
+ return errno;
+ memset(buf, 0, sizeof(buf));
+ while(pos > 0) {
+ ssize_t tmp;
+ size_t wr = sizeof(buf);
+ if (wr > pos)
+ wr = (size_t)pos;
+ tmp = write(fd, buf, wr);
+
+ if (tmp < 0)
+ return errno;
+ pos -= tmp;
+ }
+#ifdef _MSC_VER
+ _commit (fd);
+#else
+ fsync (fd);
+#endif
+ return 0;
+}
+
+/*
+ * Erase `filename' if it exists, trying to remove the contents if
+ * it's `safe'. We always try to remove the file, it it exists. It's
+ * only overwritten if it's a regular file (not a symlink and not a
+ * hardlink)
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_erase_file(krb5_context context, const char *filename)
+{
+ int fd;
+ struct stat sb1, sb2;
+ int ret;
+
+ ret = lstat (filename, &sb1);
+ if (ret < 0) {
+ if(errno == ENOENT)
+ return 0;
+ else
+ return errno;
+ }
+
+ fd = open(filename, O_RDWR | O_BINARY | O_CLOEXEC | O_NOFOLLOW);
+ if(fd < 0) {
+ if(errno == ENOENT)
+ return 0;
+ else
+ return errno;
+ }
+ rk_cloexec(fd);
+ ret = _krb5_xlock(context, fd, 1, filename);
+ if (ret) {
+ close(fd);
+ return ret;
+ }
+ if (unlink(filename) < 0) {
+ ret = errno;
+ close (fd);
+ krb5_set_error_message(context, errno,
+ N_("krb5_cc_destroy: unlinking \"%s\": %s", ""),
+ filename, strerror(ret));
+ return ret;
+ }
+ ret = fstat(fd, &sb2);
+ if (ret < 0) {
+ ret = errno;
+ close (fd);
+ return ret;
+ }
+
+ /* check if someone was playing with symlinks */
+
+ if (sb1.st_dev != sb2.st_dev || sb1.st_ino != sb2.st_ino) {
+ close(fd);
+ return EPERM;
+ }
+
+ /* there are still hard links to this file */
+
+ if (sb2.st_nlink != 0) {
+ close(fd);
+ return 0;
+ }
+
+ ret = scrub_file(fd);
+ close(fd);
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_gen_new(krb5_context context, krb5_ccache *id)
+{
+ char *file = NULL, *exp_file = NULL;
+ krb5_error_code ret;
+ krb5_fcache *f;
+ int fd;
+
+ f = calloc(1, sizeof(*f));
+ if(f == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOMEM,
+ N_("malloc: out of memory", ""));
+ return KRB5_CC_NOMEM;
+ }
+ f->tmpfn = NULL;
+ /*
+ * XXX We should asprintf(&file, "%s:XXXXXX", KRB5_DEFAULT_CCNAME_FILE)
+ * instead so that new unique FILE ccaches can be found in the user's
+ * default collection.
+ * */
+ ret = asprintf(&file, "%sXXXXXX", KRB5_DEFAULT_CCFILE_ROOT);
+ if(ret < 0 || file == NULL) {
+ free(f);
+ krb5_set_error_message(context, KRB5_CC_NOMEM,
+ N_("malloc: out of memory", ""));
+ return KRB5_CC_NOMEM;
+ }
+ ret = _krb5_expand_path_tokens(context, file, 1, &exp_file);
+ free(file);
+ if (ret) {
+ free(f);
+ return ret;
+ }
+
+ file = exp_file;
+
+ fd = mkostemp(exp_file, O_CLOEXEC);
+ if(fd < 0) {
+ ret = (krb5_error_code)errno;
+ krb5_set_error_message(context, ret, N_("mkstemp %s failed", ""), exp_file);
+ free(f);
+ free(exp_file);
+ return ret;
+ }
+ close(fd);
+ f->filename = exp_file;
+ f->res = strdup(exp_file); /* XXX See above commentary about collection */
+ f->sub = NULL;
+ f->version = 0;
+ (*id)->data.data = f;
+ (*id)->data.length = sizeof(*f);
+ return 0;
+}
+
+static void
+storage_set_flags(krb5_context context, krb5_storage *sp, int vno)
+{
+ int flags = 0;
+ switch(vno) {
+ case KRB5_FCC_FVNO_1:
+ flags |= KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONENTS;
+ flags |= KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE;
+ flags |= KRB5_STORAGE_HOST_BYTEORDER;
+ break;
+ case KRB5_FCC_FVNO_2:
+ flags |= KRB5_STORAGE_HOST_BYTEORDER;
+ break;
+ case KRB5_FCC_FVNO_3:
+ flags |= KRB5_STORAGE_KEYBLOCK_KEYTYPE_TWICE;
+ break;
+ case KRB5_FCC_FVNO_4:
+ break;
+ default:
+ krb5_abortx(context,
+ "storage_set_flags called with bad vno (%x)", vno);
+ }
+ krb5_storage_set_flags(sp, flags);
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_open(krb5_context context,
+ krb5_ccache id,
+ const char *operation,
+ int *fd_ret,
+ int flags,
+ mode_t mode)
+{
+ krb5_boolean exclusive = ((flags | O_WRONLY) == flags ||
+ (flags | O_RDWR) == flags);
+ krb5_error_code ret;
+ const char *filename;
+ struct stat sb1, sb2;
+#ifndef _WIN32
+ struct stat sb3;
+ size_t tries = 3;
+#endif
+ int strict_checking;
+ int fd;
+
+ flags |= O_BINARY | O_CLOEXEC | O_NOFOLLOW;
+
+ *fd_ret = -1;
+
+ if (FCACHE(id) == NULL)
+ return krb5_einval(context, 2);
+
+ if ((flags & O_EXCL)) {
+ /*
+ * FIXME Instead of mkostemp()... we could instead try to use a .new
+ * file... with care. Or the O_TMPFILE / linkat() extensions. We need
+ * a roken / heimbase abstraction for that.
+ */
+ if (TMPFILENAME(id))
+ (void) unlink(TMPFILENAME(id));
+ free(TMPFILENAME(id));
+ TMPFILENAME(id) = NULL;
+ if (asprintf(&TMPFILENAME(id), "%s-XXXXXX", FILENAME(id)) < 0 ||
+ TMPFILENAME(id) == NULL)
+ return krb5_enomem(context);
+ if ((fd = mkostemp(TMPFILENAME(id), O_CLOEXEC)) == -1) {
+ krb5_set_error_message(context, ret = errno,
+ N_("Could not make temp ccache FILE:%s", ""),
+ TMPFILENAME(id));
+ free(TMPFILENAME(id));
+ TMPFILENAME(id) = NULL;
+ return ret;
+ }
+ goto out;
+ }
+
+ filename = TMPFILENAME(id) ? TMPFILENAME(id) : FILENAME(id);
+ strict_checking = (flags & O_CREAT) == 0 &&
+ (context->flags & KRB5_CTX_F_FCACHE_STRICT_CHECKING) != 0;
+
+#ifndef WIN32
+again:
+#endif
+ memset(&sb1, 0, sizeof(sb1));
+ ret = lstat(filename, &sb1);
+ if (ret == 0) {
+ if (!S_ISREG(sb1.st_mode)) {
+ krb5_set_error_message(context, EPERM,
+ N_("Refuses to open symlinks for caches FILE:%s", ""), filename);
+ return EPERM;
+ }
+ } else if (errno != ENOENT || !(flags & O_CREAT)) {
+ krb5_set_error_message(context, errno, N_("%s lstat(%s)", "file, error"),
+ operation, filename);
+ return errno;
+ }
+
+ fd = open(filename, flags, mode);
+ if(fd < 0) {
+ char buf[128];
+ ret = errno;
+ rk_strerror_r(ret, buf, sizeof(buf));
+ krb5_set_error_message(context, ret, N_("%s open(%s): %s", "file, error"),
+ operation, filename, buf);
+ return ret;
+ }
+ rk_cloexec(fd);
+
+ ret = fstat(fd, &sb2);
+ if (ret < 0) {
+ krb5_clear_error_message(context);
+ close(fd);
+ return errno;
+ }
+
+ if (!S_ISREG(sb2.st_mode)) {
+ krb5_set_error_message(context, EPERM, N_("Refuses to open non files caches: FILE:%s", ""), filename);
+ close(fd);
+ return EPERM;
+ }
+
+#ifndef _WIN32
+ if (sb1.st_dev && sb1.st_ino &&
+ (sb1.st_dev != sb2.st_dev || sb1.st_ino != sb2.st_ino)) {
+ /*
+ * Perhaps we raced with a rename(). To complain about
+ * symlinks in that case would cause unnecessary concern, so
+ * we check for that possibility and loop. This has no
+ * TOCTOU problems because we redo the open(). We could also
+ * not do any of this checking if O_NOFOLLOW != 0...
+ */
+ close(fd);
+ ret = lstat(filename, &sb3);
+ if (ret || sb1.st_dev != sb2.st_dev ||
+ sb3.st_dev != sb2.st_dev || sb3.st_ino != sb2.st_ino) {
+ krb5_set_error_message(context, EPERM, N_("Refuses to open possible symlink for caches: FILE:%s", ""), filename);
+ return EPERM;
+ }
+ if (--tries == 0) {
+ krb5_set_error_message(context, EPERM, N_("Raced too many times with renames of FILE:%s", ""), filename);
+ return EPERM;
+ }
+ goto again;
+ }
+#endif
+
+ /*
+ * /tmp (or wherever default ccaches go) might not be on its own
+ * filesystem, or on a filesystem different /etc, say, and even if
+ * it were, suppose a user hard-links another's ccache to her
+ * default ccache, then runs a set-uid program that will user her
+ * default ccache (even if it ignores KRB5CCNAME)...
+ *
+ * Default ccache locations should really be on per-user non-tmp
+ * locations on tmpfs "run" directories. But we don't know here
+ * that this is the case. Thus: no hard-links, no symlinks.
+ */
+ if (sb2.st_nlink != 1) {
+ krb5_set_error_message(context, EPERM, N_("Refuses to open hardlinks for caches FILE:%s", ""), filename);
+ close(fd);
+ return EPERM;
+ }
+
+ if (strict_checking) {
+#ifndef _WIN32
+ /*
+ * XXX WIN32: Needs to have ACL checking code!
+ * st_mode comes out as 100666, and st_uid is no use.
+ */
+ /*
+ * XXX Should probably add options to improve control over this
+ * check. We might want strict checking of everything except
+ * this.
+ */
+ if (sb2.st_uid != geteuid()) {
+ krb5_set_error_message(context, EPERM, N_("Refuses to open cache files not own by myself FILE:%s (owned by %d)", ""), filename, (int)sb2.st_uid);
+ close(fd);
+ return EPERM;
+ }
+ if ((sb2.st_mode & 077) != 0) {
+ krb5_set_error_message(context, EPERM,
+ N_("Refuses to open group/other readable files FILE:%s", ""), filename);
+ close(fd);
+ return EPERM;
+ }
+#endif
+ }
+
+out:
+ if((ret = fcc_lock(context, id, fd, exclusive)) != 0) {
+ close(fd);
+ return ret;
+ }
+ *fd_ret = fd;
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_initialize(krb5_context context,
+ krb5_ccache id,
+ krb5_principal primary_principal)
+{
+ krb5_fcache *f = FCACHE(id);
+ int ret = 0;
+ int fd;
+
+ if (f == NULL)
+ return krb5_einval(context, 2);
+
+ /*
+ * fcc_open() will notice the O_EXCL and will make a temporary file that
+ * will later be renamed into place.
+ */
+ ret = fcc_open(context, id, "initialize", &fd, O_RDWR | O_CREAT | O_EXCL, 0600);
+ if(ret)
+ return ret;
+ {
+ krb5_storage *sp;
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ return krb5_enomem(context);
+ krb5_storage_set_eof_code(sp, KRB5_CC_END);
+ if(context->fcache_vno != 0)
+ f->version = context->fcache_vno;
+ else
+ f->version = KRB5_FCC_FVNO_4;
+ if (ret == 0)
+ ret = krb5_store_int8(sp, 5);
+ if (ret == 0)
+ ret = krb5_store_int8(sp, f->version);
+ storage_set_flags(context, sp, f->version);
+ if(f->version == KRB5_FCC_FVNO_4 && ret == 0) {
+ /* V4 stuff */
+ if (context->kdc_sec_offset) {
+ if (ret == 0)
+ ret = krb5_store_int16 (sp, 12); /* length */
+ if (ret == 0)
+ ret = krb5_store_int16 (sp, FCC_TAG_DELTATIME); /* Tag */
+ if (ret == 0)
+ ret = krb5_store_int16 (sp, 8); /* length of data */
+ if (ret == 0)
+ ret = krb5_store_int32 (sp, context->kdc_sec_offset);
+ if (ret == 0)
+ ret = krb5_store_int32 (sp, context->kdc_usec_offset);
+ } else {
+ if (ret == 0)
+ ret = krb5_store_int16 (sp, 0);
+ }
+ }
+ if (ret == 0)
+ ret = krb5_store_principal(sp, primary_principal);
+
+ if (ret == 0)
+ ret = write_storage(context, sp, fd);
+
+ krb5_storage_free(sp);
+ }
+ if (close(fd) < 0)
+ if (ret == 0) {
+ char buf[128];
+ ret = errno;
+ rk_strerror_r(ret, buf, sizeof(buf));
+ krb5_set_error_message(context, ret, N_("close %s: %s", ""),
+ FILENAME(id), buf);
+ }
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_close(krb5_context context,
+ krb5_ccache id)
+{
+ if (FCACHE(id) == NULL)
+ return krb5_einval(context, 2);
+
+ if (TMPFILENAME(id))
+ (void) unlink(TMPFILENAME(id));
+ free(TMPFILENAME(id));
+ free(RESFILENAME(id));
+ free(SUBFILENAME(id));
+ free(FILENAME(id));
+ krb5_data_free(&id->data);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_destroy(krb5_context context,
+ krb5_ccache id)
+{
+ if (FCACHE(id) == NULL)
+ return krb5_einval(context, 2);
+
+ if (TMPFILENAME(id))
+ (void) _krb5_erase_file(context, TMPFILENAME(id));
+ return _krb5_erase_file(context, FILENAME(id));
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_store_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_creds *creds)
+{
+ int ret;
+ int fd;
+
+ ret = fcc_open(context, id, "store", &fd, O_WRONLY | O_APPEND, 0);
+ if(ret)
+ return ret;
+ {
+ krb5_storage *sp;
+
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ return krb5_enomem(context);
+ krb5_storage_set_eof_code(sp, KRB5_CC_END);
+ storage_set_flags(context, sp, FCACHE(id)->version);
+ ret = krb5_store_creds(sp, creds);
+ if (ret == 0)
+ ret = write_storage(context, sp, fd);
+ krb5_storage_free(sp);
+ }
+ if (close(fd) < 0) {
+ if (ret == 0) {
+ char buf[128];
+ ret = errno;
+ rk_strerror_r(ret, buf, sizeof(buf));
+ krb5_set_error_message(context, ret, N_("close %s: %s", ""),
+ FILENAME(id), buf);
+ }
+ }
+ if (ret == 0 && TMPFILENAME(id) &&
+ !krb5_is_config_principal(context, creds->server)) {
+
+ /*
+ * Portability note: there's no need to have WIN32 or other code here
+ * for odd rename cases because rk_rename() is meant to handle that.
+ */
+ ret = rk_rename(TMPFILENAME(id), FILENAME(id));
+ if (ret == 0) {
+ free(TMPFILENAME(id));
+ TMPFILENAME(id) = NULL;
+ } else {
+ ret = errno;
+ }
+ }
+ return ret;
+}
+
+static krb5_error_code
+init_fcc(krb5_context context,
+ krb5_ccache id,
+ const char *operation,
+ krb5_storage **ret_sp,
+ int *ret_fd,
+ krb5_deltat *kdc_offset)
+{
+ int fd;
+ int8_t pvno, tag;
+ krb5_storage *sp;
+ krb5_error_code ret;
+
+ *ret_fd = -1;
+ *ret_sp = NULL;
+ if (kdc_offset)
+ *kdc_offset = 0;
+
+ ret = fcc_open(context, id, operation, &fd, O_RDONLY, 0);
+ if(ret)
+ return ret;
+
+ sp = krb5_storage_stdio_from_fd(fd, "r");
+ if(sp == NULL) {
+ krb5_clear_error_message(context);
+ ret = ENOMEM;
+ goto out;
+ }
+ krb5_storage_set_eof_code(sp, KRB5_CC_END);
+ ret = krb5_ret_int8(sp, &pvno);
+ if (ret != 0) {
+ if(ret == KRB5_CC_END) {
+ ret = ENOENT;
+ krb5_set_error_message(context, ret,
+ N_("Empty credential cache file: %s", ""),
+ FILENAME(id));
+ } else
+ krb5_set_error_message(context, ret, N_("Error reading pvno "
+ "in cache file: %s", ""),
+ FILENAME(id));
+ goto out;
+ }
+ if (pvno != 5) {
+ ret = KRB5_CCACHE_BADVNO;
+ krb5_set_error_message(context, ret, N_("Bad version number in credential "
+ "cache file: %s", ""),
+ FILENAME(id));
+ goto out;
+ }
+ ret = krb5_ret_int8(sp, &tag); /* should not be host byte order */
+ if (ret != 0) {
+ ret = KRB5_CC_FORMAT;
+ krb5_set_error_message(context, ret, "Error reading tag in "
+ "cache file: %s", FILENAME(id));
+ goto out;
+ }
+ FCACHE(id)->version = tag;
+ storage_set_flags(context, sp, FCACHE(id)->version);
+ switch (tag) {
+ case KRB5_FCC_FVNO_4: {
+ int16_t length;
+
+ ret = krb5_ret_int16 (sp, &length);
+ if(ret) {
+ ret = KRB5_CC_FORMAT;
+ krb5_set_error_message(context, ret,
+ N_("Error reading tag length in "
+ "cache file: %s", ""), FILENAME(id));
+ goto out;
+ }
+ while(length > 0) {
+ int16_t dtag, data_len;
+ int i;
+ int8_t dummy;
+
+ ret = krb5_ret_int16 (sp, &dtag);
+ if(ret) {
+ ret = KRB5_CC_FORMAT;
+ krb5_set_error_message(context, ret, N_("Error reading dtag in "
+ "cache file: %s", ""),
+ FILENAME(id));
+ goto out;
+ }
+ ret = krb5_ret_int16 (sp, &data_len);
+ if(ret) {
+ ret = KRB5_CC_FORMAT;
+ krb5_set_error_message(context, ret,
+ N_("Error reading dlength "
+ "in cache file: %s",""),
+ FILENAME(id));
+ goto out;
+ }
+ switch (dtag) {
+ case FCC_TAG_DELTATIME : {
+ int32_t offset;
+
+ ret = krb5_ret_int32 (sp, &offset);
+ ret |= krb5_ret_int32 (sp, &context->kdc_usec_offset);
+ if(ret) {
+ ret = KRB5_CC_FORMAT;
+ krb5_set_error_message(context, ret,
+ N_("Error reading kdc_sec in "
+ "cache file: %s", ""),
+ FILENAME(id));
+ goto out;
+ }
+ context->kdc_sec_offset = offset;
+ if (kdc_offset)
+ *kdc_offset = offset;
+ break;
+ }
+ default :
+ for (i = 0; i < data_len; ++i) {
+ ret = krb5_ret_int8 (sp, &dummy);
+ if(ret) {
+ ret = KRB5_CC_FORMAT;
+ krb5_set_error_message(context, ret,
+ N_("Error reading unknown "
+ "tag in cache file: %s", ""),
+ FILENAME(id));
+ goto out;
+ }
+ }
+ break;
+ }
+ length -= 4 + data_len;
+ }
+ break;
+ }
+ case KRB5_FCC_FVNO_3:
+ case KRB5_FCC_FVNO_2:
+ case KRB5_FCC_FVNO_1:
+ break;
+ default :
+ ret = KRB5_CCACHE_BADVNO;
+ krb5_set_error_message(context, ret,
+ N_("Unknown version number (%d) in "
+ "credential cache file: %s", ""),
+ (int)tag, FILENAME(id));
+ goto out;
+ }
+ *ret_sp = sp;
+ *ret_fd = fd;
+
+ return 0;
+ out:
+ if(sp != NULL)
+ krb5_storage_free(sp);
+ close(fd);
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_get_principal(krb5_context context,
+ krb5_ccache id,
+ krb5_principal *principal)
+{
+ krb5_error_code ret;
+ int fd;
+ krb5_storage *sp;
+
+ ret = init_fcc (context, id, "get-principal", &sp, &fd, NULL);
+ if (ret)
+ return ret;
+ ret = krb5_ret_principal(sp, principal);
+ if (ret)
+ krb5_clear_error_message(context);
+ krb5_storage_free(sp);
+ close(fd);
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_end_get(krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor);
+
+static krb5_error_code KRB5_CALLCONV
+fcc_get_first(krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+ krb5_error_code ret;
+ krb5_principal principal;
+
+ if (FCACHE(id) == NULL)
+ return krb5_einval(context, 2);
+
+ *cursor = calloc(1, sizeof(struct fcc_cursor));
+ if (*cursor == NULL) {
+ krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
+ return ENOMEM;
+ }
+
+ ret = init_fcc(context, id, "get-first", &FCC_CURSOR(*cursor)->sp,
+ &FCC_CURSOR(*cursor)->fd, NULL);
+ if (ret) {
+ free(*cursor);
+ *cursor = NULL;
+ return ret;
+ }
+ ret = krb5_ret_principal (FCC_CURSOR(*cursor)->sp, &principal);
+ if(ret) {
+ krb5_clear_error_message(context);
+ fcc_end_get(context, id, cursor);
+ return ret;
+ }
+ krb5_free_principal (context, principal);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_get_next (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor,
+ krb5_creds *creds)
+{
+ krb5_error_code ret;
+
+ if (FCACHE(id) == NULL)
+ return krb5_einval(context, 2);
+
+ if (FCC_CURSOR(*cursor) == NULL)
+ return krb5_einval(context, 3);
+
+ FCC_CURSOR(*cursor)->cred_start =
+ krb5_storage_seek(FCC_CURSOR(*cursor)->sp, 0, SEEK_CUR);
+
+ ret = krb5_ret_creds(FCC_CURSOR(*cursor)->sp, creds);
+ if (ret)
+ krb5_clear_error_message(context);
+
+ FCC_CURSOR(*cursor)->cred_end =
+ krb5_storage_seek(FCC_CURSOR(*cursor)->sp, 0, SEEK_CUR);
+
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_end_get (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+
+ if (FCACHE(id) == NULL)
+ return krb5_einval(context, 2);
+
+ if (FCC_CURSOR(*cursor) == NULL)
+ return krb5_einval(context, 3);
+
+ krb5_storage_free(FCC_CURSOR(*cursor)->sp);
+ close (FCC_CURSOR(*cursor)->fd);
+ free(*cursor);
+ *cursor = NULL;
+ return 0;
+}
+
+static void KRB5_CALLCONV
+cred_delete(krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor,
+ krb5_creds *cred)
+{
+ krb5_error_code ret;
+ krb5_storage *sp;
+ krb5_data orig_cred_data;
+ unsigned char *cred_data_in_file = NULL;
+ off_t new_cred_sz;
+ struct stat sb1, sb2;
+ int fd = -1;
+ ssize_t bytes;
+ krb5_const_realm srealm = krb5_principal_get_realm(context, cred->server);
+
+ /* This is best-effort code; if we lose track of errors here it's OK */
+
+ heim_assert(FCC_CURSOR(*cursor)->cred_start < FCC_CURSOR(*cursor)->cred_end,
+ "fcache internal error");
+
+ krb5_data_zero(&orig_cred_data);
+
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ return;
+ krb5_storage_set_eof_code(sp, KRB5_CC_END);
+ storage_set_flags(context, sp, FCACHE(id)->version);
+
+ /* Get a copy of what the cred should look like in the file; see below */
+ ret = krb5_store_creds(sp, cred);
+ if (ret)
+ goto out;
+
+ ret = krb5_storage_to_data(sp, &orig_cred_data);
+ if (ret)
+ goto out;
+ krb5_storage_free(sp);
+
+ cred_data_in_file = malloc(orig_cred_data.length);
+ if (cred_data_in_file == NULL)
+ goto out;
+
+ /*
+ * Mark the cred expired; krb5_cc_retrieve_cred() callers should use
+ * KRB5_TC_MATCH_TIMES, so this should be good enough...
+ */
+ cred->times.endtime = 0;
+
+ /* ...except for config creds because we don't check their endtimes */
+ if (srealm && strcmp(srealm, "X-CACHECONF:") == 0) {
+ ret = krb5_principal_set_realm(context, cred->server, "X-RMED-CONF:");
+ if (ret)
+ goto out;
+ }
+
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ goto out;
+ krb5_storage_set_eof_code(sp, KRB5_CC_END);
+ storage_set_flags(context, sp, FCACHE(id)->version);
+
+ ret = krb5_store_creds(sp, cred);
+
+ /* The new cred must be the same size as the old cred */
+ new_cred_sz = krb5_storage_seek(sp, 0, SEEK_END);
+ if (new_cred_sz != orig_cred_data.length || new_cred_sz !=
+ (FCC_CURSOR(*cursor)->cred_end - FCC_CURSOR(*cursor)->cred_start)) {
+ /* XXX This really can't happen. Assert like above? */
+ krb5_set_error_message(context, EINVAL,
+ N_("Credential deletion failed on ccache "
+ "FILE:%s: new credential size did not "
+ "match old credential size", ""),
+ FILENAME(id));
+ goto out;
+ }
+
+ ret = fcc_open(context, id, "remove_cred", &fd, O_RDWR, 0);
+ if (ret)
+ goto out;
+
+ /*
+ * Check that we're updating the same file where we got the
+ * cred's offset, else we'd be corrupting a new ccache.
+ */
+ if (fstat(FCC_CURSOR(*cursor)->fd, &sb1) == -1 ||
+ fstat(fd, &sb2) == -1)
+ goto out;
+ if (sb1.st_dev != sb2.st_dev || sb1.st_ino != sb2.st_ino)
+ goto out;
+
+ /*
+ * Make sure what we overwrite is what we expected.
+ *
+ * FIXME: We *really* need the ccache v4 tag for ccache ID. This
+ * check that we're only overwriting something that looks exactly
+ * like what we want to is probably good enough in practice, but
+ * it's not guaranteed to work.
+ */
+ if (lseek(fd, FCC_CURSOR(*cursor)->cred_start, SEEK_SET) == (off_t)-1)
+ goto out;
+ bytes = read(fd, cred_data_in_file, orig_cred_data.length);
+ if (bytes != orig_cred_data.length)
+ goto out;
+ if (memcmp(orig_cred_data.data, cred_data_in_file, bytes) != 0)
+ goto out;
+ if (lseek(fd, FCC_CURSOR(*cursor)->cred_start, SEEK_SET) == (off_t)-1)
+ goto out;
+ ret = write_storage(context, sp, fd);
+out:
+ if (fd > -1) {
+ if (close(fd) < 0 && ret == 0) {
+ krb5_set_error_message(context, errno, N_("close %s", ""),
+ FILENAME(id));
+ }
+ }
+ krb5_data_free(&orig_cred_data);
+ free(cred_data_in_file);
+ krb5_storage_free(sp);
+ return;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_remove_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_flags which,
+ krb5_creds *mcred)
+{
+ krb5_error_code ret, ret2;
+ krb5_cc_cursor cursor;
+ krb5_creds found_cred;
+
+ if (FCACHE(id) == NULL)
+ return krb5_einval(context, 2);
+
+ ret = krb5_cc_start_seq_get(context, id, &cursor);
+ if (ret)
+ return ret;
+ while ((ret = krb5_cc_next_cred(context, id, &cursor, &found_cred)) == 0) {
+ if (!krb5_compare_creds(context, which, mcred, &found_cred)) {
+ krb5_free_cred_contents(context, &found_cred);
+ continue;
+ }
+ cred_delete(context, id, &cursor, &found_cred);
+ krb5_free_cred_contents(context, &found_cred);
+ }
+ ret2 = krb5_cc_end_seq_get(context, id, &cursor);
+ if (ret2) /* not expected to fail */
+ return ret2;
+ if (ret == KRB5_CC_END)
+ return 0;
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_set_flags(krb5_context context,
+ krb5_ccache id,
+ krb5_flags flags)
+{
+ if (FCACHE(id) == NULL)
+ return krb5_einval(context, 2);
+
+ return 0; /* XXX */
+}
+
+static int KRB5_CALLCONV
+fcc_get_version(krb5_context context,
+ krb5_ccache id)
+{
+ if (FCACHE(id) == NULL)
+ return -1;
+
+ return FCACHE(id)->version;
+}
+
+static const char *
+my_basename(const char *fn)
+{
+ const char *base, *p;
+
+ if (strncmp(fn, "FILE:", sizeof("FILE:") - 1) == 0)
+ fn += sizeof("FILE:") - 1;
+ for (p = base = fn; *p; p++) {
+#ifdef WIN32
+ if (*p == '/' || *p == '\\')
+ base = p + 1;
+#else
+ if (*p == '/')
+ base = p + 1;
+#endif
+ }
+ return base;
+}
+
+/* We could use an rk_dirname()... */
+static char *
+my_dirname(const char *fn)
+{
+ size_t len, i;
+ char *dname;
+
+ if (strncmp(fn, "FILE:", sizeof("FILE:") - 1) == 0)
+ fn += sizeof("FILE:") - 1;
+
+ if ((dname = strdup(fn)) == NULL)
+ return NULL;
+ len = strlen(dname);
+ for (i = 0; i < len; i++) {
+#ifdef WIN32
+ if (dname[len - i] == '\\' ||
+ dname[len - i] == '/') {
+ dname[len - i] = '\0';
+ break;
+ }
+#else
+ if (dname[len - i] == '/') {
+ dname[len - i] = '\0';
+ break;
+ }
+#endif
+ }
+ if (i < len)
+ return dname;
+ free(dname);
+ return strdup(".");
+}
+
+/*
+ * This checks that a directory entry matches a required basename and has a
+ * non-empty subsidiary component.
+ */
+static int
+matchbase(const char *fn, const char *base, size_t baselen)
+{
+ return strncmp(fn, base, baselen) == 0 &&
+ (fn[baselen] == FILESUBSEPCHR && fn[baselen + 1] != '\0');
+}
+
+/*
+ * Check if `def_locs' contains `name' (which must be the default ccache name),
+ * in which case the caller may look for subsidiaries of all of `def_locs'.
+ *
+ * This is needed because the collection iterators don't take a base location
+ * as an argument, so we can only search default locations, but only if the
+ * current default ccache name is indeed a default (as opposed to from
+ * KRB5CCNAME being set in the environment pointing to a non-default name).
+ */
+static krb5_error_code
+is_default_collection(krb5_context context, const char *name,
+ const char * const *def_locs, int *res)
+{
+ krb5_error_code ret;
+ const char *def_loc[2] = { KRB5_DEFAULT_CCNAME_FILE, NULL };
+ const char *sep;
+ size_t namelen;
+ size_t i;
+
+ *res = 0;
+ if (name == NULL) {
+ *res = 1;
+ return 0;
+ }
+ if ((sep = strchr(name, FILESUBSEPCHR)))
+ namelen = (size_t)(sep - name);
+ else
+ namelen = strlen(name);
+ if (def_locs == NULL)
+ def_locs = def_loc;
+ for (i = 0; !(*res) && def_locs[i]; i++) {
+ char *e = NULL;
+
+ if ((ret = _krb5_expand_default_cc_name(context, def_locs[i], &e)))
+ return ret;
+ *res = strncmp(e, name, namelen) == 0 &&
+ (sep == NULL || e[namelen] == FILESUBSEPCHR || e[namelen] == '\0');
+ free(e);
+ }
+ return 0;
+}
+
+/*
+ * Collection iterator cursor.
+ *
+ * There may be an array of locations, and for each location we'll try
+ * resolving it, as well as doing a readdir() of the dirname of it and output
+ * all ccache names in that directory that begin with the current location and
+ * end in "+${subsidiary}".
+ */
+struct fcache_iter {
+ const char *curr_location;
+ char *def_ccname; /* The default ccname */
+ char **locations; /* All the other places we'll look for a ccache */
+ char *dname; /* dirname() of curr_location */
+ DIR *d;
+ struct dirent *dentry;
+ int location; /* Index of `locations' */
+ unsigned int first:1;
+ unsigned int dead:1;
+};
+
+/* Initiate FILE collection iteration */
+static krb5_error_code KRB5_CALLCONV
+fcc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor)
+{
+ struct fcache_iter *iter = NULL;
+ krb5_error_code ret;
+ const char *def_ccname = NULL;
+ char **def_locs = NULL;
+ int is_def_coll = 0;
+
+ if (krb5_config_get_bool_default(context, NULL, FALSE, "libdefaults",
+ "enable_file_cache_iteration", NULL)) {
+ def_ccname = krb5_cc_default_name(context);
+ def_locs = krb5_config_get_strings(context, NULL, "libdefaults",
+ "default_file_cache_collections",
+ NULL);
+ }
+
+ /*
+ * Note: do not allow krb5_cc_default_name() to recurse via
+ * krb5_cc_cache_match().
+ * Note that context->default_cc_name will be NULL even though
+ * KRB5CCNAME is set in the environment if neither krb5_cc_default_name()
+ * nor krb5_cc_set_default_name() have been called.
+ */
+
+ /*
+ * Figure out if the current default ccache name is a really a default one
+ * so we know whether to search any other default FILE collection
+ * locations.
+ */
+ if ((ret = is_default_collection(context, def_ccname,
+ (const char **)def_locs,
+ &is_def_coll)))
+ goto out;
+
+ /* Setup the cursor */
+ if ((iter = calloc(1, sizeof(*iter))) == NULL ||
+ (def_ccname && (iter->def_ccname = strdup(def_ccname)) == NULL)) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ if (is_def_coll) {
+ /* Since def_ccname is in the `def_locs', we'll include those */
+ iter->locations = def_locs;
+ free(iter->def_ccname);
+ iter->def_ccname = NULL;
+ def_locs = NULL;
+ } else {
+ /* Since def_ccname is NOT in the `def_locs', we'll exclude those */
+ iter->locations = NULL;
+ }
+ iter->curr_location = NULL;
+ iter->location = -1; /* Pre-incremented */
+ iter->first = 1;
+ iter->dname = NULL;
+ iter->d = NULL;
+ *cursor = iter;
+ iter = NULL;
+ ret = 0;
+
+out:
+ krb5_config_free_strings(def_locs);
+ free(iter);
+ return ret;
+}
+
+/* Pick the next location as the `iter->curr_location' */
+static krb5_error_code
+next_location(krb5_context context, struct fcache_iter *iter)
+{
+ if (iter->first && iter->def_ccname) {
+ iter->curr_location = iter->def_ccname;
+ iter->first = 0;
+ return 0;
+ }
+ iter->first = 0;
+
+ if (iter->d)
+ closedir(iter->d);
+ iter->d = NULL;
+ iter->curr_location = NULL;
+ if (iter->locations &&
+ (iter->curr_location = iter->locations[++(iter->location)]))
+ return 0;
+
+ iter->dead = 1; /* Do not run off the end of iter->locations */
+ return KRB5_CC_END;
+}
+
+/* Output the next match for `iter->curr_location' from readdir() */
+static krb5_error_code
+next_dir_match(krb5_context context, struct fcache_iter *iter, char **fn)
+{
+ struct stat st;
+ const char *base = my_basename(iter->curr_location);
+ size_t baselen = strlen(base);
+ char *s;
+
+ *fn = NULL;
+ if (iter->d == NULL)
+ return 0;
+ for (iter->dentry = readdir(iter->d);
+ iter->dentry;
+ iter->dentry = readdir(iter->d)) {
+ if (!matchbase(iter->dentry->d_name, base, baselen))
+ continue;
+ if (asprintf(&s, "FILE:%s/%s", iter->dname, iter->dentry->d_name) == -1 ||
+ s == NULL)
+ return krb5_enomem(context);
+ if (stat(s + sizeof("FILE:") - 1, &st) == 0 && S_ISREG(st.st_mode)) {
+ *fn = s;
+ return 0;
+ }
+ free(s);
+ }
+ iter->curr_location = NULL;
+ closedir(iter->d);
+ iter->d = NULL;
+ return 0;
+}
+
+/* See if the given `ccname' is a FILE ccache we can resolve */
+static krb5_error_code
+try1(krb5_context context, const char *ccname, krb5_ccache *id)
+{
+ krb5_error_code ret;
+ krb5_ccache cc;
+
+ ret = krb5_cc_resolve(context, ccname, &cc);
+ if (ret == ENOMEM)
+ return ret;
+ if (ret == 0) {
+ if (strcmp(krb5_cc_get_type(context, cc), "FILE") == 0) {
+ *id = cc;
+ cc = NULL;
+ }
+ krb5_cc_close(context, cc);
+ }
+ return 0;
+}
+
+/* Output the next FILE ccache in the FILE ccache collection */
+static krb5_error_code KRB5_CALLCONV
+fcc_get_cache_next(krb5_context context, krb5_cc_cursor cursor, krb5_ccache *id)
+{
+ struct fcache_iter *iter = cursor;
+ krb5_error_code ret;
+ char *name = NULL;
+
+ *id = NULL;
+ if (iter == NULL)
+ return krb5_einval(context, 2);
+
+ /* Do not run off the end of iter->locations */
+ if (iter->dead)
+ return KRB5_CC_END;
+
+ if (!iter->curr_location) {
+ /* Next base location */
+ if ((ret = next_location(context, iter)))
+ return ret;
+ /* Output the current base location */
+ if ((ret = try1(context, iter->curr_location, id)) || *id)
+ return ret;
+ }
+
+ /* Look for subsidiaries of iter->curr_location */
+ if (!iter->d) {
+ free(iter->dname);
+ if ((iter->dname = my_dirname(iter->curr_location)) == NULL)
+ return krb5_enomem(context);
+ if ((iter->d = opendir(iter->dname)) == NULL) {
+ /* Dirname ENOENT -> next location */
+ if ((ret = next_location(context, iter)))
+ return ret;
+ /* Tail-recurse */
+ return fcc_get_cache_next(context, cursor, id);
+ }
+ }
+ for (ret = next_dir_match(context, iter, &name);
+ ret == 0 && name != NULL;
+ ret = next_dir_match(context, iter, &name)) {
+ if ((ret = try1(context, name, id)) || *id) {
+ free(name);
+ return ret;
+ }
+ free(name);
+ }
+
+ /* Directory listing exhausted -> go to next location, tail-recurse */
+ if ((ret = next_location(context, iter)))
+ return ret;
+ return fcc_get_cache_next(context, cursor, id);
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_end_cache_get(krb5_context context, krb5_cc_cursor cursor)
+{
+ struct fcache_iter *iter = cursor;
+
+ if (iter == NULL)
+ return krb5_einval(context, 2);
+
+ krb5_config_free_strings(iter->locations);
+ if (iter->d)
+ closedir(iter->d);
+ free(iter->def_ccname);
+ free(iter->dname);
+ free(iter);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_move(krb5_context context, krb5_ccache from, krb5_ccache to)
+{
+ krb5_error_code ret = 0;
+ krb5_fcache *f = FCACHE(from);
+ krb5_fcache *t = FCACHE(to);
+
+ if (f->tmpfn) {
+ /*
+ * If `from' has a temp file and we haven't renamed it into place yet,
+ * then we should rename TMPFILENAME(from) to FILENAME(to).
+ *
+ * This can only happen if we're moving a ccache where only cc config
+ * entries, or no entries, have been written. That's not likely.
+ */
+ if (rk_rename(f->tmpfn, t->filename)) {
+ ret = errno;
+ } else {
+ free(f->tmpfn);
+ f->tmpfn = NULL;
+ }
+ } else if (rk_rename(f->filename, t->filename)) {
+ ret = errno;
+ }
+ /*
+ * We need only close from -- we can't destroy it since the rename
+ * succeeded, which "destroyed" it at its old name.
+ */
+ if (ret == 0)
+ krb5_cc_close(context, from);
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_get_default_name(krb5_context context, char **str)
+{
+ return _krb5_expand_default_cc_name(context,
+ KRB5_DEFAULT_CCNAME_FILE,
+ str);
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_set_default_cache(krb5_context context, krb5_ccache id)
+{
+ krb5_error_code ret;
+ krb5_ccache dest;
+ char *s = NULL;
+
+ if (SUBFILENAME(id) == NULL)
+ return 0; /* Already a primary */
+ if (asprintf(&s, "FILE:%s", RESFILENAME(id)) == -1 || s == NULL)
+ return krb5_enomem(context);
+
+ /*
+ * We can't hard-link, since we refuse to open ccaches with st_nlink > 1,
+ * and we can't rename() the ccache because the old name should remain
+ * available. Ergo, we copy the ccache.
+ */
+ ret = krb5_cc_resolve(context, s, &dest);
+ if (ret == 0)
+ ret = krb5_cc_copy_cache(context, id, dest);
+ free(s);
+ if (ret)
+ krb5_set_error_message(context, ret,
+ N_("Failed to copy subsidiary cache file %s to "
+ "default %s", ""), FILENAME(id),
+ RESFILENAME(id));
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_lastchange(krb5_context context, krb5_ccache id, krb5_timestamp *mtime)
+{
+ krb5_error_code ret;
+ struct stat sb;
+ int fd;
+
+ ret = fcc_open(context, id, "lastchange", &fd, O_RDONLY, 0);
+ if(ret)
+ return ret;
+ ret = fstat(fd, &sb);
+ close(fd);
+ if (ret) {
+ ret = errno;
+ krb5_set_error_message(context, ret, N_("Failed to stat cache file", ""));
+ return ret;
+ }
+ *mtime = sb.st_mtime;
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat kdc_offset)
+{
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_get_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat *kdc_offset)
+{
+ krb5_error_code ret;
+ krb5_storage *sp = NULL;
+ int fd;
+ ret = init_fcc(context, id, "get-kdc-offset", &sp, &fd, kdc_offset);
+ if (sp)
+ krb5_storage_free(sp);
+ close(fd);
+
+ return ret;
+}
+
+
+/**
+ * Variable containing the FILE based credential cache implemention.
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_VARIABLE const krb5_cc_ops krb5_fcc_ops = {
+ KRB5_CC_OPS_VERSION_5,
+ "FILE",
+ NULL,
+ NULL,
+ fcc_gen_new,
+ fcc_initialize,
+ fcc_destroy,
+ fcc_close,
+ fcc_store_cred,
+ NULL, /* fcc_retrieve */
+ fcc_get_principal,
+ fcc_get_first,
+ fcc_get_next,
+ fcc_end_get,
+ fcc_remove_cred,
+ fcc_set_flags,
+ fcc_get_version,
+ fcc_get_cache_first,
+ fcc_get_cache_next,
+ fcc_end_cache_get,
+ fcc_move,
+ fcc_get_default_name,
+ fcc_set_default_cache,
+ fcc_lastchange,
+ fcc_set_kdc_offset,
+ fcc_get_kdc_offset,
+ fcc_get_name_2,
+ fcc_resolve_2
+};
diff --git a/third_party/heimdal/lib/krb5/free.c b/third_party/heimdal/lib/krb5/free.c
new file mode 100644
index 0000000..5bb33b4
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/free.c
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 1997 - 1999, 2004 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_free_kdc_rep(krb5_context context, krb5_kdc_rep *rep)
+{
+ free_KDC_REP(&rep->kdc_rep);
+ free_EncTGSRepPart(&rep->enc_part);
+ free_KRB_ERROR(&rep->error);
+ memset(rep, 0, sizeof(*rep));
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_xfree (void *ptr)
+{
+ free (ptr);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/free_host_realm.c b/third_party/heimdal/lib/krb5/free_host_realm.c
new file mode 100644
index 0000000..0932674
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/free_host_realm.c
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 1997, 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ * Free all memory allocated by `realmlist'
+ *
+ * @param context A Kerberos 5 context.
+ * @param realmlist realmlist to free, NULL is ok
+ *
+ * @return a Kerberos error code, always 0.
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_free_host_realm(krb5_context context,
+ krb5_realm *realmlist)
+{
+ krb5_realm *p;
+
+ if(realmlist == NULL)
+ return 0;
+ for (p = realmlist; *p; ++p)
+ free (*p);
+ free (realmlist);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/generate_seq_number.c b/third_party/heimdal/lib/krb5/generate_seq_number.c
new file mode 100644
index 0000000..6001d69
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/generate_seq_number.c
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_generate_seq_number(krb5_context context,
+ const krb5_keyblock *key,
+ uint32_t *seqno)
+{
+ if (RAND_bytes((void *)seqno, sizeof(*seqno)) <= 0)
+ krb5_abortx(context, "Failed to generate random block");
+ /* MIT used signed numbers, lets not stomp into that space directly */
+ *seqno &= 0x3fffffff;
+ if (*seqno == 0)
+ *seqno = 1;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/generate_subkey.c b/third_party/heimdal/lib/krb5/generate_subkey.c
new file mode 100644
index 0000000..767d94c
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/generate_subkey.c
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ * Generate subkey, from keyblock
+ *
+ * @param context kerberos context
+ * @param key session key
+ * @param etype encryption type of subkey, if ETYPE_NULL, use key's enctype
+ * @param subkey returned new, free with krb5_free_keyblock().
+ *
+ * @return 0 on success or a Kerberos 5 error code
+ *
+* @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_generate_subkey_extended(krb5_context context,
+ const krb5_keyblock *key,
+ krb5_enctype etype,
+ krb5_keyblock **subkey)
+{
+ krb5_error_code ret;
+
+ ALLOC(*subkey, 1);
+ if (*subkey == NULL)
+ return krb5_enomem(context);
+
+ if (etype == ETYPE_NULL)
+ etype = key->keytype; /* use session key etype */
+
+ /* XXX should we use the session key as input to the RF? */
+ ret = krb5_generate_random_keyblock(context, etype, *subkey);
+ if (ret != 0) {
+ free(*subkey);
+ *subkey = NULL;
+ }
+
+ return ret;
+}
+
diff --git a/third_party/heimdal/lib/krb5/get_addrs.c b/third_party/heimdal/lib/krb5/get_addrs.c
new file mode 100644
index 0000000..8246504
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/get_addrs.c
@@ -0,0 +1,283 @@
+/*
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#ifdef __osf__
+/* hate */
+struct rtentry;
+struct mbuf;
+#endif
+#ifdef HAVE_NET_IF_H
+#include <net/if.h>
+#endif
+#include <ifaddrs.h>
+
+static krb5_error_code
+gethostname_fallback (krb5_context context, krb5_addresses *res)
+{
+ krb5_error_code ret;
+ char hostname[MAXHOSTNAMELEN];
+ struct hostent *hostent;
+
+ if (gethostname (hostname, sizeof(hostname))) {
+ ret = errno;
+ krb5_set_error_message(context, ret, "gethostname: %s", strerror(ret));
+ return ret;
+ }
+ hostent = roken_gethostbyname (hostname);
+ if (hostent == NULL) {
+ ret = errno;
+ krb5_set_error_message (context, ret, "gethostbyname %s: %s",
+ hostname, strerror(ret));
+ return ret;
+ }
+ res->len = 1;
+ res->val = malloc (sizeof(*res->val));
+ if (res->val == NULL)
+ return krb5_enomem(context);
+ res->val[0].addr_type = hostent->h_addrtype;
+ res->val[0].address.data = NULL;
+ res->val[0].address.length = 0;
+ ret = krb5_data_copy (&res->val[0].address,
+ hostent->h_addr,
+ hostent->h_length);
+ if (ret) {
+ free (res->val);
+ return ret;
+ }
+ return 0;
+}
+
+enum {
+ LOOP = 1, /* do include loopback addrs */
+ LOOP_IF_NONE = 2, /* include loopback addrs if no others */
+ EXTRA_ADDRESSES = 4, /* include extra addresses */
+ SCAN_INTERFACES = 8 /* scan interfaces for addresses */
+};
+
+/*
+ * Try to figure out the addresses of all configured interfaces with a
+ * lot of magic ioctls.
+ */
+
+static krb5_error_code
+find_all_addresses (krb5_context context, krb5_addresses *res, int flags)
+{
+ struct sockaddr sa_zero;
+ struct ifaddrs *ifa0, *ifa;
+ krb5_error_code ret = ENXIO;
+ unsigned int num, idx;
+ krb5_addresses ignore_addresses;
+
+ if (getifaddrs(&ifa0) == -1) {
+ ret = errno;
+ krb5_set_error_message(context, ret, "getifaddrs: %s", strerror(ret));
+ return (ret);
+ }
+
+ memset(&sa_zero, 0, sizeof(sa_zero));
+
+ /* First, count all the ifaddrs. */
+ for (ifa = ifa0, num = 0; ifa != NULL; ifa = ifa->ifa_next, num++)
+ /* nothing */;
+
+ if (num == 0) {
+ freeifaddrs(ifa0);
+ krb5_set_error_message(context, ENXIO, N_("no addresses found", ""));
+ return (ENXIO);
+ }
+
+ if (flags & EXTRA_ADDRESSES) {
+ /* we'll remove the addresses we don't care about */
+ ret = krb5_get_ignore_addresses(context, &ignore_addresses);
+ if(ret)
+ return ret;
+ }
+
+ /* Allocate storage for them. */
+ res->val = calloc(num, sizeof(*res->val));
+ if (res->val == NULL) {
+ if (flags & EXTRA_ADDRESSES)
+ krb5_free_addresses(context, &ignore_addresses);
+ freeifaddrs(ifa0);
+ return krb5_enomem(context);
+ }
+
+ /* Now traverse the list. */
+ for (ifa = ifa0, idx = 0; ifa != NULL; ifa = ifa->ifa_next) {
+ if ((ifa->ifa_flags & IFF_UP) == 0)
+ continue;
+ if (ifa->ifa_addr == NULL)
+ continue;
+ if (memcmp(ifa->ifa_addr, &sa_zero, sizeof(sa_zero)) == 0)
+ continue;
+ if (krb5_sockaddr_uninteresting(ifa->ifa_addr))
+ continue;
+ if (krb5_sockaddr_is_loopback(ifa->ifa_addr) && (flags & LOOP) == 0)
+ /* We'll deal with the LOOP_IF_NONE case later. */
+ continue;
+
+ ret = krb5_sockaddr2address(context, ifa->ifa_addr, &res->val[idx]);
+ if (ret) {
+ /*
+ * The most likely error here is going to be "Program
+ * lacks support for address type". This is no big
+ * deal -- just continue, and we'll listen on the
+ * addresses who's type we *do* support.
+ */
+ continue;
+ }
+ /* possibly skip this address? */
+ if((flags & EXTRA_ADDRESSES) &&
+ krb5_address_search(context, &res->val[idx], &ignore_addresses)) {
+ krb5_free_address(context, &res->val[idx]);
+ flags &= ~LOOP_IF_NONE; /* we actually found an address,
+ so don't add any loop-back
+ addresses */
+ continue;
+ }
+
+ idx++;
+ }
+
+ /*
+ * If no addresses were found, and LOOP_IF_NONE is set, then find
+ * the loopback addresses and add them to our list.
+ */
+ if ((flags & LOOP_IF_NONE) != 0 && idx == 0) {
+ for (ifa = ifa0; ifa != NULL; ifa = ifa->ifa_next) {
+ if ((ifa->ifa_flags & IFF_UP) == 0)
+ continue;
+ if (ifa->ifa_addr == NULL)
+ continue;
+ if (memcmp(ifa->ifa_addr, &sa_zero, sizeof(sa_zero)) == 0)
+ continue;
+ if (krb5_sockaddr_uninteresting(ifa->ifa_addr))
+ continue;
+ if (!krb5_sockaddr_is_loopback(ifa->ifa_addr))
+ continue;
+ if ((ifa->ifa_flags & IFF_LOOPBACK) == 0)
+ /* Presumably loopback addrs are only used on loopback ifs! */
+ continue;
+ ret = krb5_sockaddr2address(context,
+ ifa->ifa_addr, &res->val[idx]);
+ if (ret)
+ continue; /* We don't consider this failure fatal */
+ if((flags & EXTRA_ADDRESSES) &&
+ krb5_address_search(context, &res->val[idx],
+ &ignore_addresses)) {
+ krb5_free_address(context, &res->val[idx]);
+ continue;
+ }
+ idx++;
+ }
+ }
+
+ if (flags & EXTRA_ADDRESSES)
+ krb5_free_addresses(context, &ignore_addresses);
+ freeifaddrs(ifa0);
+ if (ret) {
+ free(res->val);
+ res->val = NULL;
+ } else
+ res->len = idx; /* Now a count. */
+ return (ret);
+}
+
+static krb5_error_code
+get_addrs_int (krb5_context context, krb5_addresses *res, int flags)
+{
+ krb5_error_code ret = -1;
+
+ res->len = 0;
+ res->val = NULL;
+
+ if (flags & SCAN_INTERFACES) {
+ ret = find_all_addresses (context, res, flags);
+ if(ret || res->len == 0)
+ ret = gethostname_fallback (context, res);
+ } else {
+ ret = 0;
+ }
+
+ if(ret == 0 && (flags & EXTRA_ADDRESSES)) {
+ krb5_addresses a;
+ /* append user specified addresses */
+ ret = krb5_get_extra_addresses(context, &a);
+ if(ret) {
+ krb5_free_addresses(context, res);
+ return ret;
+ }
+ ret = krb5_append_addresses(context, res, &a);
+ if(ret) {
+ krb5_free_addresses(context, res);
+ return ret;
+ }
+ krb5_free_addresses(context, &a);
+ }
+ if(res->len == 0) {
+ free(res->val);
+ res->val = NULL;
+ }
+ return ret;
+}
+
+/*
+ * Try to get all addresses, but return the one corresponding to
+ * `hostname' if we fail.
+ *
+ * Only include loopback address if there are no other.
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_all_client_addrs (krb5_context context, krb5_addresses *res)
+{
+ int flags = LOOP_IF_NONE | EXTRA_ADDRESSES;
+
+ if (context->scan_interfaces)
+ flags |= SCAN_INTERFACES;
+
+ return get_addrs_int (context, res, flags);
+}
+
+/*
+ * Try to get all local addresses that a server should listen to.
+ * If that fails, we return the address corresponding to `hostname'.
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_all_server_addrs (krb5_context context, krb5_addresses *res)
+{
+ return get_addrs_int (context, res, LOOP | SCAN_INTERFACES);
+}
diff --git a/third_party/heimdal/lib/krb5/get_cred.c b/third_party/heimdal/lib/krb5/get_cred.c
new file mode 100644
index 0000000..6e48846
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/get_cred.c
@@ -0,0 +1,2026 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 - 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include <assert.h>
+
+static krb5_error_code
+get_cred_kdc_capath(krb5_context, krb5_kdc_flags,
+ krb5_ccache, struct krb5_fast_state *,
+ krb5_creds *, krb5_principal,
+ Ticket *, const char *, const char *,
+ krb5_creds **, krb5_creds ***);
+
+/*
+ * Take the `body' and encode it into `padata' using the credentials
+ * in `creds'.
+ */
+
+static krb5_error_code
+make_pa_tgs_req(krb5_context context,
+ krb5_auth_context *ac,
+ KDC_REQ_BODY *body,
+ krb5_ccache ccache,
+ krb5_creds *creds,
+ krb5_data *tgs_req)
+{
+ krb5_error_code ret;
+ krb5_data in_data;
+ size_t buf_size;
+ size_t len = 0;
+ uint8_t *buf;
+
+ ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, body, &len, ret);
+ if (ret)
+ return ret;
+
+ if(buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ in_data.length = len;
+ in_data.data = buf;
+ ret = _krb5_mk_req_internal(context, ac, 0, &in_data,
+ creds, tgs_req,
+ KRB5_KU_TGS_REQ_AUTH_CKSUM,
+ KRB5_KU_TGS_REQ_AUTH);
+ free (buf);
+ return ret;
+}
+
+/*
+ * Set the `enc-authorization-data' in `req_body' based on `authdata'
+ */
+
+static krb5_error_code
+set_auth_data (krb5_context context,
+ KDC_REQ_BODY *req_body,
+ krb5_authdata *authdata,
+ krb5_keyblock *subkey)
+{
+ if(authdata->len) {
+ size_t len = 0, buf_size;
+ unsigned char *buf;
+ krb5_crypto crypto;
+ krb5_error_code ret;
+
+ ASN1_MALLOC_ENCODE(AuthorizationData, buf, buf_size, authdata,
+ &len, ret);
+ if (ret)
+ return ret;
+ if (buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ ALLOC(req_body->enc_authorization_data, 1);
+ if (req_body->enc_authorization_data == NULL) {
+ free (buf);
+ return krb5_enomem(context);
+ }
+ ret = krb5_crypto_init(context, subkey, 0, &crypto);
+ if (ret) {
+ free (buf);
+ free (req_body->enc_authorization_data);
+ req_body->enc_authorization_data = NULL;
+ return ret;
+ }
+ ret = krb5_encrypt_EncryptedData(context,
+ crypto,
+ KRB5_KU_TGS_REQ_AUTH_DAT_SUBKEY,
+ buf,
+ len,
+ 0,
+ req_body->enc_authorization_data);
+ free (buf);
+ krb5_crypto_destroy(context, crypto);
+ return ret;
+ } else {
+ req_body->enc_authorization_data = NULL;
+ return 0;
+ }
+}
+
+/*
+ * Create a tgs-req in `t' with `addresses', `flags', `second_ticket'
+ * (if not-NULL), `in_creds', `krbtgt', and returning the generated
+ * subkey in `subkey'.
+ */
+
+static krb5_error_code
+init_tgs_req (krb5_context context,
+ krb5_ccache ccache,
+ struct krb5_fast_state *state,
+ krb5_addresses *addresses,
+ krb5_kdc_flags flags,
+ Ticket *second_ticket,
+ krb5_creds *in_creds,
+ krb5_creds *krbtgt,
+ unsigned nonce,
+ const METHOD_DATA *padata,
+ krb5_keyblock **subkey,
+ TGS_REQ *t)
+{
+ krb5_auth_context ac = NULL;
+ krb5_error_code ret = 0;
+ krb5_data tgs_req;
+
+ krb5_data_zero(&tgs_req);
+ memset(t, 0, sizeof(*t));
+
+ t->pvno = 5;
+ t->msg_type = krb_tgs_req;
+ if (in_creds->session.keytype) {
+ ALLOC_SEQ(&t->req_body.etype, 1);
+ if(t->req_body.etype.val == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ t->req_body.etype.val[0] = in_creds->session.keytype;
+ } else {
+ ret = _krb5_init_etype(context,
+ KRB5_PDU_TGS_REQUEST,
+ &t->req_body.etype.len,
+ &t->req_body.etype.val,
+ NULL);
+ }
+ if (ret)
+ goto fail;
+ t->req_body.addresses = addresses;
+ t->req_body.kdc_options = flags.b;
+ t->req_body.kdc_options.forwardable = krbtgt->flags.b.forwardable;
+ t->req_body.kdc_options.renewable = krbtgt->flags.b.renewable;
+ t->req_body.kdc_options.proxiable = krbtgt->flags.b.proxiable;
+ ret = copy_Realm(&in_creds->server->realm, &t->req_body.realm);
+ if (ret)
+ goto fail;
+ ALLOC(t->req_body.sname, 1);
+ if (t->req_body.sname == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+
+ /* some versions of some code might require that the client be
+ present in TGS-REQs, but this is clearly against the spec */
+
+ ret = copy_PrincipalName(&in_creds->server->name, t->req_body.sname);
+ if (ret)
+ goto fail;
+
+ if (krbtgt->times.starttime) {
+ ALLOC(t->req_body.from, 1);
+ if(t->req_body.from == NULL){
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ *t->req_body.from = in_creds->times.starttime;
+ }
+
+ /* req_body.till should be NULL if there is no endtime specified,
+ but old MIT code (like DCE secd) doesn't like that */
+ ALLOC(t->req_body.till, 1);
+ if(t->req_body.till == NULL){
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ *t->req_body.till = in_creds->times.endtime;
+
+ if (t->req_body.kdc_options.renewable && krbtgt->times.renew_till) {
+ ALLOC(t->req_body.rtime, 1);
+ if(t->req_body.rtime == NULL){
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ *t->req_body.rtime = in_creds->times.renew_till;
+ }
+
+ t->req_body.nonce = nonce;
+ if(second_ticket){
+ ALLOC(t->req_body.additional_tickets, 1);
+ if (t->req_body.additional_tickets == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ ALLOC_SEQ(t->req_body.additional_tickets, 1);
+ if (t->req_body.additional_tickets->val == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ ret = copy_Ticket(second_ticket, t->req_body.additional_tickets->val);
+ if (ret)
+ goto fail;
+ }
+
+ ret = krb5_auth_con_init(context, &ac);
+ if(ret)
+ goto fail;
+
+ ret = krb5_auth_con_generatelocalsubkey(context, ac, &krbtgt->session);
+ if (ret)
+ goto fail;
+
+ if (state) {
+ krb5_data empty;
+
+ krb5_data_zero(&empty);
+ ret = krb5_auth_con_add_AuthorizationData(context, ac,
+ KRB5_AUTHDATA_FX_FAST_USED,
+ &empty);
+ if (ret)
+ goto fail;
+ }
+
+ ret = set_auth_data(context, &t->req_body,
+ &in_creds->authdata, ac->local_subkey);
+ if (ret)
+ goto fail;
+
+ ret = make_pa_tgs_req(context,
+ &ac,
+ &t->req_body,
+ ccache,
+ krbtgt,
+ &tgs_req);
+ if(ret)
+ goto fail;
+
+ /*
+ * Add KRB5_PADATA_TGS_REQ first
+ * followed by all others.
+ */
+
+ if (t->padata == NULL) {
+ ALLOC(t->padata, 1);
+ if (t->padata == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ }
+
+ ret = krb5_padata_add(context, t->padata, KRB5_PADATA_TGS_REQ,
+ tgs_req.data, tgs_req.length);
+ if (ret)
+ goto fail;
+
+ krb5_data_zero(&tgs_req);
+
+ {
+ size_t i;
+ for (i = 0; i < padata->len; i++) {
+ const PA_DATA *val1 = &padata->val[i];
+ PA_DATA val2;
+
+ ret = copy_PA_DATA(val1, &val2);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("malloc: out of memory", ""));
+ goto fail;
+ }
+
+ ret = krb5_padata_add(context, t->padata,
+ val2.padata_type,
+ val2.padata_value.data,
+ val2.padata_value.length);
+ if (ret) {
+ free_PA_DATA(&val2);
+
+ krb5_set_error_message(context, ret,
+ N_("malloc: out of memory", ""));
+ goto fail;
+ }
+ }
+ }
+
+ if (state) {
+ state->armor_ac = ac;
+ ret = _krb5_fast_create_armor(context, state, NULL);
+ state->armor_ac = NULL;
+ if (ret)
+ goto fail;
+
+ ret = _krb5_fast_wrap_req(context, state, t);
+ if (ret)
+ goto fail;
+
+ /* Its ok if there is no fast in the TGS-REP, older heimdal only support it in the AS code path */
+ state->flags &= ~KRB5_FAST_EXPECTED;
+ }
+
+ ret = krb5_auth_con_getlocalsubkey(context, ac, subkey);
+ if (ret)
+ goto fail;
+
+fail:
+ if (ac)
+ krb5_auth_con_free(context, ac);
+ if (ret) {
+ t->req_body.addresses = NULL;
+ free_TGS_REQ (t);
+ }
+ krb5_data_free(&tgs_req);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_get_krbtgt(krb5_context context,
+ krb5_ccache id,
+ krb5_realm realm,
+ krb5_creds **cred)
+{
+ krb5_error_code ret;
+ krb5_creds tmp_cred;
+
+ memset(&tmp_cred, 0, sizeof(tmp_cred));
+
+ ret = krb5_cc_get_principal(context, id, &tmp_cred.client);
+ if (ret)
+ return ret;
+
+ if (realm == NULL)
+ realm = tmp_cred.client->realm;
+
+ ret = krb5_make_principal(context,
+ &tmp_cred.server,
+ realm,
+ KRB5_TGS_NAME,
+ realm,
+ NULL);
+ if(ret) {
+ krb5_free_principal(context, tmp_cred.client);
+ return ret;
+ }
+ /*
+ * The forwardable TGT might not be the start TGT, in which case, it is
+ * generally, but not always already cached. Just in case, get it again if
+ * lost.
+ */
+ ret = krb5_get_credentials(context,
+ 0,
+ id,
+ &tmp_cred,
+ cred);
+ krb5_free_principal(context, tmp_cred.client);
+ krb5_free_principal(context, tmp_cred.server);
+ if(ret)
+ return ret;
+ return 0;
+}
+
+static krb5_error_code
+fast_tgs_strengthen_key(krb5_context context,
+ struct krb5_fast_state *state,
+ krb5_keyblock *reply_key,
+ krb5_keyblock *extract_key)
+{
+ krb5_error_code ret;
+
+ if (state && state->strengthen_key) {
+ _krb5_debug(context, 5, "_krb5_fast_tgs_strengthen_key");
+
+ if (state->strengthen_key->keytype != reply_key->keytype) {
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+ N_("strengthen_key %d not same enctype as reply key %d", ""),
+ state->strengthen_key->keytype, reply_key->keytype);
+ return KRB5KRB_AP_ERR_MODIFIED;
+ }
+
+ ret = _krb5_fast_cf2(context,
+ state->strengthen_key,
+ "strengthenkey",
+ reply_key,
+ "replykey",
+ extract_key,
+ NULL);
+ if (ret)
+ return ret;
+ } else {
+ ret = krb5_copy_keyblock_contents(context, reply_key, extract_key);
+ if (ret)
+ return ret;
+ }
+
+ return 0;
+}
+
+/* DCE compatible decrypt proc */
+static krb5_error_code KRB5_CALLCONV
+decrypt_tkt_with_subkey (krb5_context context,
+ krb5_keyblock *key,
+ krb5_key_usage usage,
+ krb5_const_pointer skey,
+ krb5_kdc_rep *dec_rep)
+{
+ struct krb5_decrypt_tkt_with_subkey_state *state;
+ krb5_error_code ret = 0;
+ krb5_data data;
+ size_t size;
+ krb5_crypto crypto;
+ krb5_keyblock extract_key;
+
+ state = (struct krb5_decrypt_tkt_with_subkey_state *)skey;
+
+ assert(usage == 0);
+
+ krb5_data_zero(&data);
+
+ /*
+ * start out with trying with subkey if we have one
+ */
+ if (state->subkey) {
+ ret = fast_tgs_strengthen_key(context, state->fast_state,
+ state->subkey, &extract_key);
+ if (ret)
+ return ret;
+
+ ret = krb5_crypto_init(context, &extract_key, 0, &crypto);
+ krb5_free_keyblock_contents(context, &extract_key);
+ if (ret)
+ return ret;
+ ret = krb5_decrypt_EncryptedData (context,
+ crypto,
+ KRB5_KU_TGS_REP_ENC_PART_SUB_KEY,
+ &dec_rep->kdc_rep.enc_part,
+ &data);
+ /*
+ * If the is Windows 2000 DC, we need to retry with key usage
+ * 8 when doing ARCFOUR.
+ */
+ if (ret && state->subkey->keytype == ETYPE_ARCFOUR_HMAC_MD5) {
+ ret = krb5_decrypt_EncryptedData(context,
+ crypto,
+ 8,
+ &dec_rep->kdc_rep.enc_part,
+ &data);
+ }
+ krb5_crypto_destroy(context, crypto);
+ }
+ if (state->subkey == NULL || ret) {
+ ret = fast_tgs_strengthen_key(context, state->fast_state, key, &extract_key);
+ if (ret)
+ return ret;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ return ret;
+ ret = krb5_decrypt_EncryptedData (context,
+ crypto,
+ KRB5_KU_TGS_REP_ENC_PART_SESSION,
+ &dec_rep->kdc_rep.enc_part,
+ &data);
+ krb5_crypto_destroy(context, crypto);
+ }
+ if (ret)
+ return ret;
+
+ ret = decode_EncASRepPart(data.data,
+ data.length,
+ &dec_rep->enc_part,
+ &size);
+ if (ret)
+ ret = decode_EncTGSRepPart(data.data,
+ data.length,
+ &dec_rep->enc_part,
+ &size);
+ if (ret)
+ krb5_set_error_message(context, ret,
+ N_("Failed to decode encpart in ticket", ""));
+ krb5_data_free (&data);
+ return ret;
+}
+
+static krb5_error_code
+get_cred_kdc(krb5_context context,
+ krb5_ccache id,
+ struct krb5_fast_state *fast_state,
+ krb5_kdc_flags flags,
+ krb5_addresses *addresses,
+ krb5_creds *in_creds,
+ krb5_creds *krbtgt,
+ krb5_principal impersonate_principal,
+ Ticket *second_ticket,
+ const char *kdc_hostname,
+ const char *sitename,
+ krb5_creds *out_creds)
+{
+ TGS_REQ req;
+ krb5_data enc;
+ krb5_data resp;
+ krb5_kdc_rep rep;
+ krb5_error_code ret;
+ unsigned nonce;
+ krb5_keyblock *subkey = NULL;
+ size_t len = 0;
+ Ticket second_ticket_data;
+ METHOD_DATA padata;
+
+ memset(&rep, 0, sizeof(rep));
+ krb5_data_zero(&resp);
+ krb5_data_zero(&enc);
+ padata.val = NULL;
+ padata.len = 0;
+
+ krb5_generate_random_block(&nonce, sizeof(nonce));
+ nonce &= 0xffffffff;
+
+ if(flags.b.enc_tkt_in_skey && second_ticket == NULL){
+ ret = decode_Ticket(in_creds->second_ticket.data,
+ in_creds->second_ticket.length,
+ &second_ticket_data, &len);
+ if(ret)
+ return ret;
+ second_ticket = &second_ticket_data;
+ }
+
+
+ if (impersonate_principal) {
+ krb5_crypto crypto;
+ PA_S4U2Self self;
+ krb5_data data;
+ void *buf;
+ size_t size = 0;
+
+ self.name = impersonate_principal->name;
+ self.realm = impersonate_principal->realm;
+ self.auth = estrdup("Kerberos");
+
+ ret = _krb5_s4u2self_to_checksumdata(context, &self, &data);
+ if (ret) {
+ free(self.auth);
+ goto out;
+ }
+
+ ret = krb5_crypto_init(context, &krbtgt->session, 0, &crypto);
+ if (ret) {
+ free(self.auth);
+ krb5_data_free(&data);
+ goto out;
+ }
+
+ ret = krb5_create_checksum(context,
+ crypto,
+ KRB5_KU_OTHER_CKSUM,
+ 0,
+ data.data,
+ data.length,
+ &self.cksum);
+ krb5_crypto_destroy(context, crypto);
+ krb5_data_free(&data);
+ if (ret) {
+ free(self.auth);
+ goto out;
+ }
+
+ ASN1_MALLOC_ENCODE(PA_S4U2Self, buf, len, &self, &size, ret);
+ free(self.auth);
+ free_Checksum(&self.cksum);
+ if (ret)
+ goto out;
+ if (len != size)
+ krb5_abortx(context, "internal asn1 error");
+
+ ret = krb5_padata_add(context, &padata, KRB5_PADATA_FOR_USER, buf, len);
+ if (ret)
+ goto out;
+ }
+
+ ret = init_tgs_req (context,
+ id,
+ fast_state,
+ addresses,
+ flags,
+ second_ticket,
+ in_creds,
+ krbtgt,
+ nonce,
+ &padata,
+ &subkey,
+ &req);
+ if (ret)
+ goto out;
+
+ ASN1_MALLOC_ENCODE(TGS_REQ, enc.data, enc.length, &req, &len, ret);
+ if (ret)
+ goto out;
+ if(enc.length != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ /* don't free addresses */
+ req.req_body.addresses = NULL;
+ free_TGS_REQ(&req);
+
+ /*
+ * Send and receive
+ */
+ {
+ krb5_sendto_ctx stctx;
+ ret = krb5_sendto_ctx_alloc(context, &stctx);
+ if (ret)
+ return ret;
+ krb5_sendto_ctx_set_func(stctx, _krb5_kdc_retry, NULL);
+
+ if (kdc_hostname)
+ krb5_sendto_set_hostname(context, stctx, kdc_hostname);
+ if (sitename)
+ krb5_sendto_set_sitename(context, stctx, sitename);
+
+ ret = krb5_sendto_context (context, stctx, &enc,
+ krbtgt->server->name.name_string.val[1],
+ &resp);
+ krb5_sendto_ctx_free(context, stctx);
+ }
+ if(ret)
+ goto out;
+
+ if(decode_TGS_REP(resp.data, resp.length, &rep.kdc_rep, &len) == 0) {
+ struct krb5_decrypt_tkt_with_subkey_state state;
+ unsigned eflags = 0;
+ krb5_data data;
+ size_t size;
+
+ ASN1_MALLOC_ENCODE(Ticket, data.data, data.length,
+ &rep.kdc_rep.ticket, &size, ret);
+ if (ret)
+ goto out;
+ heim_assert(data.length == size, "ASN.1 internal error");
+
+ ret = _krb5_fast_unwrap_kdc_rep(context, nonce, &data,
+ fast_state, &rep.kdc_rep);
+ krb5_data_free(&data);
+ if (ret)
+ goto out;
+
+ ret = krb5_copy_principal(context,
+ in_creds->client,
+ &out_creds->client);
+ if(ret)
+ goto out;
+ ret = krb5_copy_principal(context,
+ in_creds->server,
+ &out_creds->server);
+ if(ret)
+ goto out;
+ /* this should go someplace else */
+ out_creds->times.endtime = in_creds->times.endtime;
+
+ /* XXX should do better testing */
+ if (flags.b.cname_in_addl_tkt || impersonate_principal)
+ eflags |= EXTRACT_TICKET_ALLOW_CNAME_MISMATCH;
+ if (flags.b.request_anonymous)
+ eflags |= EXTRACT_TICKET_MATCH_ANON;
+
+ state.subkey = subkey;
+ state.fast_state = fast_state;
+
+ ret = _krb5_extract_ticket(context,
+ &rep,
+ out_creds,
+ &krbtgt->session,
+ NULL,
+ 0,
+ &krbtgt->addresses,
+ nonce,
+ eflags,
+ NULL,
+ decrypt_tkt_with_subkey,
+ &state);
+ } else if(krb5_rd_error(context, &resp, &rep.error) == 0) {
+ METHOD_DATA md;
+
+ memset(&md, 0, sizeof(md));
+
+ if (rep.error.e_data) {
+ ret = decode_METHOD_DATA(rep.error.e_data->data,
+ rep.error.e_data->length,
+ &md, NULL);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to decode METHOD-DATA", ""));
+ goto out;
+ }
+ }
+
+ ret = _krb5_fast_unwrap_error(context, nonce, fast_state, &md, &rep.error);
+ free_METHOD_DATA(&md);
+ if (ret)
+ goto out;
+
+ ret = krb5_error_from_rd_error(context, &rep.error, in_creds);
+
+ /* log the failure */
+ if (_krb5_have_debug(context, 5)) {
+ const char *str = krb5_get_error_message(context, ret);
+ _krb5_debug(context, 5, "parse_tgs_rep: KRB-ERROR %d/%s", ret, str);
+ krb5_free_error_message(context, str);
+ }
+ } else if(resp.length > 0 && ((char*)resp.data)[0] == 4) {
+ ret = KRB5KRB_AP_ERR_V4_REPLY;
+ krb5_clear_error_message(context);
+ } else {
+ ret = KRB5KRB_AP_ERR_MSG_TYPE;
+ krb5_clear_error_message(context);
+ }
+
+out:
+ krb5_free_kdc_rep(context, &rep);
+ if (second_ticket == &second_ticket_data)
+ free_Ticket(&second_ticket_data);
+ free_METHOD_DATA(&padata);
+ krb5_data_free(&resp);
+ krb5_data_free(&enc);
+ if(subkey)
+ krb5_free_keyblock(context, subkey);
+ return ret;
+
+}
+
+/*
+ * same as above, just get local addresses first if the krbtgt have
+ * them and the realm is not addressless
+ */
+
+static krb5_error_code
+get_cred_kdc_address(krb5_context context,
+ krb5_ccache id,
+ struct krb5_fast_state *fast_state,
+ krb5_kdc_flags flags,
+ krb5_addresses *addrs,
+ krb5_creds *in_creds,
+ krb5_creds *krbtgt,
+ krb5_principal impersonate_principal,
+ Ticket *second_ticket,
+ const char *kdc_hostname,
+ const char *sitename,
+ krb5_creds *out_creds)
+{
+ krb5_error_code ret;
+ krb5_addresses addresses = { 0, NULL };
+
+ /*
+ * Inherit the address-ness of the krbtgt if the address is not
+ * specified.
+ */
+
+ if (addrs == NULL && krbtgt->addresses.len != 0) {
+ krb5_boolean noaddr;
+
+ krb5_appdefault_boolean(context, NULL, krbtgt->server->realm,
+ "no-addresses", FALSE, &noaddr);
+
+ if (!noaddr) {
+ ret = krb5_get_all_client_addrs(context, &addresses);
+ if (ret)
+ return ret;
+ /* XXX this sucks. */
+ addrs = &addresses;
+ if(addresses.len == 0)
+ addrs = NULL;
+ }
+ }
+ ret = get_cred_kdc(context, id, fast_state, flags, addrs,
+ in_creds, krbtgt, impersonate_principal,
+ second_ticket, kdc_hostname, sitename, out_creds);
+ krb5_free_addresses(context, &addresses);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_kdc_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_kdc_flags flags,
+ krb5_addresses *addresses,
+ Ticket *second_ticket,
+ krb5_creds *in_creds,
+ krb5_creds **out_creds
+ )
+{
+ krb5_error_code ret;
+ krb5_creds *krbtgt;
+ struct krb5_fast_state fast_state;
+
+ memset(&fast_state, 0, sizeof(fast_state));
+
+ *out_creds = calloc(1, sizeof(**out_creds));
+ if(*out_creds == NULL)
+ return krb5_enomem(context);
+ ret = _krb5_get_krbtgt (context,
+ id,
+ in_creds->server->realm,
+ &krbtgt);
+ if(ret) {
+ free(*out_creds);
+ *out_creds = NULL;
+ return ret;
+ }
+ ret = get_cred_kdc(context, id, &fast_state, flags,
+ addresses, in_creds, krbtgt,
+ NULL, NULL, NULL, NULL, *out_creds);
+ krb5_free_creds (context, krbtgt);
+ _krb5_fast_free(context, &fast_state);
+ if(ret) {
+ free(*out_creds);
+ *out_creds = NULL;
+ }
+ return ret;
+}
+
+static int
+not_found(krb5_context context, krb5_const_principal p, krb5_error_code code)
+{
+ krb5_error_code ret;
+ char *str;
+ const char *err;
+
+ ret = krb5_unparse_name(context, p, &str);
+ if(ret) {
+ krb5_clear_error_message(context);
+ return code;
+ }
+ err = krb5_get_error_message(context, code);
+ krb5_set_error_message(context, code, N_("%s (%s)", ""), err, str);
+ krb5_free_error_message(context, err);
+ free(str);
+ return code;
+}
+
+static krb5_error_code
+find_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_principal server,
+ krb5_creds **tgts,
+ krb5_creds *out_creds)
+{
+ krb5_error_code ret;
+ krb5_creds mcreds;
+
+ krb5_cc_clear_mcred(&mcreds);
+ mcreds.server = server;
+ krb5_timeofday(context, &mcreds.times.endtime);
+ ret = krb5_cc_retrieve_cred(context, id,
+ KRB5_TC_DONT_MATCH_REALM |
+ KRB5_TC_MATCH_TIMES,
+ &mcreds, out_creds);
+ if(ret == 0)
+ return 0;
+ while(tgts && *tgts){
+ if(krb5_compare_creds(context, KRB5_TC_DONT_MATCH_REALM,
+ &mcreds, *tgts)){
+ ret = krb5_copy_creds_contents(context, *tgts, out_creds);
+ return ret;
+ }
+ tgts++;
+ }
+ return not_found(context, server, KRB5_CC_NOTFOUND);
+}
+
+static krb5_error_code
+add_cred(krb5_context context, krb5_creds const *tkt, krb5_creds ***tgts)
+{
+ int i;
+ krb5_error_code ret;
+ krb5_creds **tmp = *tgts;
+
+ for(i = 0; tmp && tmp[i]; i++); /* XXX */
+ tmp = realloc(tmp, (i+2)*sizeof(*tmp));
+ if(tmp == NULL)
+ return krb5_enomem(context);
+ *tgts = tmp;
+ ret = krb5_copy_creds(context, tkt, &tmp[i]);
+ tmp[i+1] = NULL;
+ return ret;
+}
+
+static krb5_error_code
+get_cred_kdc_capath_worker(krb5_context context,
+ krb5_kdc_flags flags,
+ krb5_ccache ccache,
+ struct krb5_fast_state *fast_state,
+ krb5_creds *in_creds,
+ krb5_const_realm try_realm,
+ krb5_principal impersonate_principal,
+ Ticket *second_ticket,
+ const char *kdc_hostname,
+ const char *sitename,
+ krb5_creds **out_creds,
+ krb5_creds ***ret_tgts)
+{
+ krb5_error_code ret;
+ krb5_creds *tgt = NULL;
+ krb5_creds tmp_creds;
+ krb5_const_realm client_realm, server_realm;
+ int ok_as_delegate = 1;
+
+ *out_creds = calloc(1, sizeof(**out_creds));
+ if (*out_creds == NULL)
+ return krb5_enomem(context);
+
+ memset(&tmp_creds, 0, sizeof(tmp_creds));
+
+ client_realm = krb5_principal_get_realm(context, in_creds->client);
+ server_realm = krb5_principal_get_realm(context, in_creds->server);
+ ret = krb5_copy_principal(context, in_creds->client, &tmp_creds.client);
+ if (ret)
+ goto out;
+
+ ret = krb5_make_principal(context,
+ &tmp_creds.server,
+ try_realm,
+ KRB5_TGS_NAME,
+ server_realm,
+ NULL);
+ if (ret)
+ goto out;
+
+ {
+ krb5_creds tgts;
+
+ /*
+ * If we have krbtgt/server_realm@try_realm cached, use it and we're
+ * done.
+ */
+ ret = find_cred(context, ccache, tmp_creds.server,
+ *ret_tgts, &tgts);
+ if (ret == 0) {
+ /* only allow implicit ok_as_delegate if the realm is the clients realm */
+ if (strcmp(try_realm, client_realm) != 0
+ || strcmp(try_realm, server_realm) != 0) {
+ ok_as_delegate = tgts.flags.b.ok_as_delegate;
+ }
+
+ ret = get_cred_kdc_address(context, ccache, fast_state,
+ flags, NULL,
+ in_creds, &tgts,
+ impersonate_principal,
+ second_ticket,
+ kdc_hostname,
+ sitename,
+ *out_creds);
+ krb5_free_cred_contents(context, &tgts);
+ if (ret == 0 &&
+ !krb5_principal_compare(context, in_creds->server,
+ (*out_creds)->server)) {
+ ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
+ }
+ if (ret == 0 && ok_as_delegate == 0)
+ (*out_creds)->flags.b.ok_as_delegate = 0;
+
+ goto out;
+ }
+ }
+
+ if (krb5_realm_compare(context, in_creds->client, in_creds->server)) {
+ ret = not_found(context, in_creds->server, KRB5_CC_NOTFOUND);
+ goto out;
+ }
+
+ /*
+ * XXX This can loop forever, plus we recurse, so we can't just keep a
+ * count here. The count would have to get passed around by reference.
+ *
+ * The KDCs check for transit loops for us, and capath data is finite, so
+ * in fact we'll fall out of this loop at some point. We should do our own
+ * transit loop checking (like get_cred_kdc_referral()), and we should
+ * impose a max number of iterations altogether. But barring malicious or
+ * broken KDCs, this is good enough.
+ */
+ while (1) {
+ heim_general_string tgt_inst;
+
+ ret = get_cred_kdc_capath(context, flags, ccache, fast_state,
+ &tmp_creds, NULL, NULL,
+ kdc_hostname, sitename,
+ &tgt, ret_tgts);
+ if (ret)
+ goto out;
+
+ /*
+ * if either of the chain or the ok_as_delegate was stripped
+ * by the kdc, make sure we strip it too.
+ */
+ if (ok_as_delegate == 0 || tgt->flags.b.ok_as_delegate == 0) {
+ ok_as_delegate = 0;
+ tgt->flags.b.ok_as_delegate = 0;
+ }
+
+ ret = add_cred(context, tgt, ret_tgts);
+ if (ret)
+ goto out;
+ tgt_inst = tgt->server->name.name_string.val[1];
+ if (strcmp(tgt_inst, server_realm) == 0)
+ break;
+ krb5_free_principal(context, tmp_creds.server);
+ tmp_creds.server = NULL;
+ ret = krb5_make_principal(context, &tmp_creds.server,
+ tgt_inst, KRB5_TGS_NAME, server_realm, NULL);
+ if (ret)
+ goto out;
+ ret = krb5_free_creds(context, tgt);
+ tgt = NULL;
+ if (ret)
+ goto out;
+ }
+
+ ret = get_cred_kdc_address(context, ccache, fast_state, flags, NULL,
+ in_creds, tgt, impersonate_principal,
+ second_ticket, kdc_hostname, sitename, *out_creds);
+ if (ret == 0 &&
+ !krb5_principal_compare(context, in_creds->server,
+ (*out_creds)->server)) {
+ krb5_free_cred_contents(context, *out_creds);
+ ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
+ }
+ if (ret == 0 && ok_as_delegate == 0)
+ (*out_creds)->flags.b.ok_as_delegate = 0;
+
+out:
+ if (ret) {
+ krb5_free_creds(context, *out_creds);
+ *out_creds = NULL;
+ }
+ if (tmp_creds.server)
+ krb5_free_principal(context, tmp_creds.server);
+ if (tmp_creds.client)
+ krb5_free_principal(context, tmp_creds.client);
+ if (tgt)
+ krb5_free_creds(context, tgt);
+ return ret;
+}
+
+/*
+get_cred(server)
+ creds = cc_get_cred(server)
+ if(creds) return creds
+ tgt = cc_get_cred(krbtgt/server_realm@any_realm)
+ if(tgt)
+ return get_cred_tgt(server, tgt)
+ if(client_realm == server_realm)
+ return NULL
+ tgt = get_cred(krbtgt/server_realm@client_realm)
+ while(tgt_inst != server_realm)
+ tgt = get_cred(krbtgt/server_realm@tgt_inst)
+ return get_cred_tgt(server, tgt)
+ */
+
+static krb5_error_code
+get_cred_kdc_capath(krb5_context context,
+ krb5_kdc_flags flags,
+ krb5_ccache ccache,
+ struct krb5_fast_state *fast_state,
+ krb5_creds *in_creds,
+ krb5_principal impersonate_principal,
+ Ticket *second_ticket,
+ const char *kdc_hostname,
+ const char *sitename,
+ krb5_creds **out_creds,
+ krb5_creds ***ret_tgts)
+{
+ krb5_error_code ret;
+ krb5_const_realm client_realm, server_realm, try_realm;
+
+ client_realm = krb5_principal_get_realm(context, in_creds->client);
+ server_realm = krb5_principal_get_realm(context, in_creds->server);
+
+ try_realm = client_realm;
+ ret = get_cred_kdc_capath_worker(context, flags, ccache, fast_state,
+ in_creds, try_realm, impersonate_principal,
+ second_ticket, kdc_hostname, sitename,
+ out_creds, ret_tgts);
+
+ if (ret == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN) {
+ try_realm = krb5_config_get_string(context, NULL, "capaths",
+ client_realm, server_realm, NULL);
+
+ if (try_realm != NULL && strcmp(try_realm, client_realm) != 0) {
+ ret = get_cred_kdc_capath_worker(context, flags, ccache, fast_state,
+ in_creds, try_realm, impersonate_principal,
+ second_ticket, kdc_hostname, sitename,
+ out_creds, ret_tgts);
+ }
+ }
+
+ return ret;
+}
+
+static krb5_boolean skip_referrals(krb5_principal server,
+ krb5_kdc_flags *flags)
+{
+ return server->name.name_string.len < 2 && !flags->b.canonicalize;
+}
+
+/*
+ * Get a service ticket from a KDC by chasing referrals from a start realm.
+ *
+ * All referral TGTs produced in the process are thrown away when we're done.
+ * We don't store them, and we don't allow other search mechanisms (capaths) to
+ * use referral TGTs produced here.
+ */
+static krb5_error_code
+get_cred_kdc_referral(krb5_context context,
+ krb5_kdc_flags flags,
+ krb5_ccache ccache,
+ struct krb5_fast_state *fast_state,
+ krb5_creds *in_creds,
+ krb5_principal impersonate_principal,
+ Ticket *second_ticket,
+ const char *kdc_hostname,
+ const char *sitename,
+ krb5_creds **out_creds)
+{
+ krb5_realm start_realm = NULL;
+ krb5_data config_start_realm;
+ krb5_error_code ret;
+ krb5_creds tgt, referral, ticket;
+ krb5_creds **referral_tgts = NULL; /* used for loop detection */
+ int loop = 0;
+ int ok_as_delegate = 1;
+ int want_tgt;
+ size_t i;
+
+ if (skip_referrals(in_creds->server, &flags)) {
+ krb5_set_error_message(context, KRB5KDC_ERR_PATH_NOT_ACCEPTED,
+ N_("Name too short to do referals, skipping", ""));
+ return KRB5KDC_ERR_PATH_NOT_ACCEPTED;
+ }
+
+ memset(&tgt, 0, sizeof(tgt));
+ memset(&ticket, 0, sizeof(ticket));
+
+ flags.b.canonicalize = 1;
+
+ *out_creds = NULL;
+
+
+ ret = krb5_cc_get_config(context, ccache, NULL, "start_realm", &config_start_realm);
+ if (ret == 0) {
+ start_realm = strndup(config_start_realm.data, config_start_realm.length);
+ krb5_data_free(&config_start_realm);
+ } else {
+ start_realm = strdup(krb5_principal_get_realm(context, in_creds->client));
+ }
+ if (start_realm == NULL)
+ return krb5_enomem(context);
+
+ /* find tgt for the clients base realm */
+ {
+ krb5_principal tgtname;
+
+ ret = krb5_make_principal(context, &tgtname,
+ start_realm,
+ KRB5_TGS_NAME,
+ start_realm,
+ NULL);
+ if (ret) {
+ free(start_realm);
+ return ret;
+ }
+
+ ret = find_cred(context, ccache, tgtname, NULL, &tgt);
+ krb5_free_principal(context, tgtname);
+ if (ret) {
+ free(start_realm);
+ return ret;
+ }
+ }
+
+ /*
+ * If the desired service principal service/host@REALM is not a TGT, start
+ * by asking for a ticket for service/host@START_REALM and process referrals
+ * from there.
+ *
+ * However, when we ask for a TGT, krbtgt/A@B, we're actually looking for a
+ * path to realm B, so that we can explicitly obtain a ticket for krbtgt/A
+ * from B, and not some other realm. Therefore, in this case our starting
+ * point will be krbtgt/B@START_REALM. Only once we obtain a ticket for
+ * krbtgt/B@some-transit, do we switch to requesting krbtgt/A@B on our
+ * final request.
+ */
+ referral = *in_creds;
+ want_tgt = in_creds->server->realm[0] != '\0' &&
+ krb5_principal_is_krbtgt(context, in_creds->server);
+ if (!want_tgt)
+ ret = krb5_copy_principal(context, in_creds->server, &referral.server);
+ else
+ ret = krb5_make_principal(context, &referral.server, start_realm,
+ KRB5_TGS_NAME, in_creds->server->realm, NULL);
+
+ if (ret) {
+ krb5_free_cred_contents(context, &tgt);
+ free(start_realm);
+ return ret;
+ }
+ if (!want_tgt)
+ ret = krb5_principal_set_realm(context, referral.server, start_realm);
+ free(start_realm);
+ start_realm = NULL;
+ if (ret) {
+ krb5_free_cred_contents(context, &tgt);
+ krb5_free_principal(context, referral.server);
+ return ret;
+ }
+
+ while (loop++ < 17) {
+ krb5_creds **tickets;
+ krb5_creds mcreds;
+ char *referral_realm;
+
+ /* Use cache if we are not doing impersonation or contrained deleg */
+ if (impersonate_principal == NULL && !flags.b.cname_in_addl_tkt) {
+ krb5_cc_clear_mcred(&mcreds);
+ mcreds.server = referral.server;
+ krb5_timeofday(context, &mcreds.times.endtime);
+ ret = krb5_cc_retrieve_cred(context, ccache, KRB5_TC_MATCH_TIMES,
+ &mcreds, &ticket);
+ } else
+ ret = EINVAL;
+
+ if (ret) {
+ ret = get_cred_kdc_address(context, ccache, fast_state, flags, NULL,
+ &referral, &tgt, impersonate_principal,
+ second_ticket, kdc_hostname, sitename, &ticket);
+ if (ret)
+ goto out;
+ }
+
+ /*
+ * Did we get the right ticket?
+ *
+ * If we weren't asking for a TGT, then we don't mind if we took a realm
+ * change (referral.server has a referral realm, not necessarily the
+ * original).
+ *
+ * However, if we were looking for a TGT (which wouldn't be the start
+ * TGT, since that one must be in the ccache) then we actually want the
+ * one from the realm we wanted, since otherwise a _referral_ will
+ * confuse us and we will store that referral. In Heimdal we mostly
+ * never ask krb5_get_cred*() for TGTs, but some sites have code to ask
+ * for a ktbgt/REMOTE.REALM@REMOTE.REALM, and one could always use
+ * kgetcred(1) to get here asking for a krbtgt/C@D and we need to handle
+ * the case where last hop we get is krbtgt/C@B (in which case we must
+ * stop so we don't beat up on B for the remaining tries).
+ */
+ if (!want_tgt &&
+ krb5_principal_compare(context, referral.server, ticket.server))
+ break;
+
+ if (!krb5_principal_is_krbtgt(context, ticket.server)) {
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_NOT_US,
+ N_("Got back an non krbtgt "
+ "ticket referrals", ""));
+ ret = KRB5KRB_AP_ERR_NOT_US;
+ goto out;
+ }
+
+ referral_realm = ticket.server->name.name_string.val[1];
+
+ /* check that there are no referrals loops */
+ tickets = referral_tgts;
+
+ krb5_cc_clear_mcred(&mcreds);
+ mcreds.server = ticket.server;
+
+ while (tickets && *tickets){
+ if (krb5_compare_creds(context,
+ KRB5_TC_DONT_MATCH_REALM,
+ &mcreds,
+ *tickets)) {
+ krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
+ N_("Referral from %s "
+ "loops back to realm %s", ""),
+ tgt.server->realm,
+ referral_realm);
+ ret = KRB5_GET_IN_TKT_LOOP;
+ goto out;
+ }
+ tickets++;
+ }
+
+ /*
+ * if either of the chain or the ok_as_delegate was stripped
+ * by the kdc, make sure we strip it too.
+ */
+
+ if (ok_as_delegate == 0 || ticket.flags.b.ok_as_delegate == 0) {
+ ok_as_delegate = 0;
+ ticket.flags.b.ok_as_delegate = 0;
+ }
+
+ _krb5_debug(context, 6, "get_cred_kdc_referral: got referral "
+ "to %s from %s", referral_realm, referral.server->realm);
+ ret = add_cred(context, &ticket, &referral_tgts);
+ if (ret)
+ goto out;
+
+ /* try realm in the referral */
+ if (!want_tgt || strcmp(referral_realm, in_creds->server->realm) != 0)
+ ret = krb5_principal_set_realm(context,
+ referral.server,
+ referral_realm);
+ else {
+ /*
+ * Now that we have a ticket for the desired realm, we reset
+ * want_tgt and reinstate the desired principal so that the we can
+ * match it and break out of the loop.
+ */
+ want_tgt = 0;
+ krb5_free_principal(context, referral.server);
+ referral.server = NULL;
+ ret = krb5_copy_principal(context, in_creds->server, &referral.server);
+ }
+ krb5_free_cred_contents(context, &tgt);
+ tgt = ticket;
+ memset(&ticket, 0, sizeof(ticket));
+ if (ret)
+ goto out;
+ }
+
+ ret = krb5_copy_creds(context, &ticket, out_creds);
+
+out:
+ for (i = 0; referral_tgts && referral_tgts[i]; i++)
+ krb5_free_creds(context, referral_tgts[i]);
+ free(referral_tgts);
+ krb5_free_principal(context, referral.server);
+ krb5_free_cred_contents(context, &tgt);
+ krb5_free_cred_contents(context, &ticket);
+ return ret;
+}
+
+
+/*
+ * Glue function between referrals version and old client chasing
+ * codebase.
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_get_cred_kdc_any(krb5_context context,
+ krb5_kdc_flags flags,
+ krb5_ccache ccache,
+ struct krb5_fast_state *fast_state,
+ krb5_creds *in_creds,
+ krb5_principal impersonate_principal,
+ Ticket *second_ticket,
+ krb5_creds **out_creds,
+ krb5_creds ***ret_tgts)
+{
+ char *kdc_hostname = NULL;
+ char *sitename = NULL;
+ krb5_error_code ret;
+ krb5_deltat offset;
+ krb5_data data;
+
+ krb5_data_zero(&data);
+
+ /*
+ * If we are using LKDC, lets pull out the addreses from the
+ * ticket and use that.
+ */
+
+ ret = krb5_cc_get_config(context, ccache, NULL, "lkdc-hostname", &data);
+ if (ret == 0) {
+ if ((kdc_hostname = strndup(data.data, data.length)) == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ krb5_data_free(&data);
+ }
+
+ ret = krb5_cc_get_config(context, ccache, NULL, "sitename", &data);
+ if (ret == 0) {
+ if ((sitename = strndup(data.data, data.length)) == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ krb5_data_free(&data);
+ }
+
+ ret = krb5_cc_get_kdc_offset(context, ccache, &offset);
+ if (ret == 0) {
+ context->kdc_sec_offset = offset;
+ context->kdc_usec_offset = 0;
+ }
+
+ if (strcmp(in_creds->server->realm, "") != 0) {
+ /*
+ * Non-empty realm? Try capaths first. We might have local
+ * policy (capaths) to honor.
+ */
+ ret = get_cred_kdc_capath(context,
+ flags,
+ ccache,
+ fast_state,
+ in_creds,
+ impersonate_principal,
+ second_ticket,
+ kdc_hostname,
+ sitename,
+ out_creds,
+ ret_tgts);
+ if (ret == 0 || skip_referrals(in_creds->server, &flags))
+ goto out;
+ }
+
+ /* Otherwise try referrals */
+ ret = get_cred_kdc_referral(context,
+ flags,
+ ccache,
+ fast_state,
+ in_creds,
+ impersonate_principal,
+ second_ticket,
+ kdc_hostname,
+ sitename,
+ out_creds);
+
+out:
+ krb5_data_free(&data);
+ free(kdc_hostname);
+ free(sitename);
+ return ret;
+}
+
+static krb5_error_code
+check_cc(krb5_context context, krb5_flags options, krb5_ccache ccache,
+ krb5_creds *in_creds, krb5_creds *out_creds)
+{
+ krb5_error_code ret;
+ krb5_timestamp now;
+ krb5_creds mcreds = *in_creds;
+
+ krb5_timeofday(context, &now);
+
+ if (!(options & KRB5_GC_EXPIRED_OK) &&
+ mcreds.times.endtime < now) {
+ mcreds.times.renew_till = 0;
+ krb5_timeofday(context, &mcreds.times.endtime);
+ options |= KRB5_TC_MATCH_TIMES;
+ }
+
+ if (mcreds.server->name.name_type == KRB5_NT_SRV_HST_NEEDS_CANON) {
+ /* Avoid name canonicalization in krb5_cc_retrieve_cred() */
+ krb5_principal_set_type(context, mcreds.server, KRB5_NT_SRV_HST);
+ }
+
+ if (options & KRB5_GC_ANONYMOUS) {
+ ret = krb5_make_principal(context,
+ &mcreds.client,
+ krb5_principal_get_realm(context, mcreds.client),
+ KRB5_WELLKNOWN_NAME,
+ KRB5_ANON_NAME,
+ NULL);
+ if (ret)
+ return ret;
+ }
+
+ ret = krb5_cc_retrieve_cred(context, ccache,
+ (options &
+ (KRB5_TC_DONT_MATCH_REALM |
+ KRB5_TC_MATCH_KEYTYPE |
+ KRB5_TC_MATCH_TIMES)),
+ &mcreds, out_creds);
+
+ if (options & KRB5_GC_ANONYMOUS)
+ krb5_free_principal(context, mcreds.client);
+
+ if (ret == 0 && out_creds->server->realm &&
+ out_creds->server->realm[0] == '\0') {
+ Ticket ticket;
+
+ /*
+ * We only write tickets to the ccache that have been validated, as in,
+ * the sname/srealm from the KDC-REP enc-part have been checked to
+ * match the sname/realm from the Ticket from the KDC-REP.
+ *
+ * Our caller needs the canonical realm of the service in order to be
+ * able to get forwarded credentials for it when destination-TGT
+ * forwarding is enabled.
+ *
+ * As well, gss_init_sec_context() ought to arrange for
+ * gss_inquire_context() to output the canonical acceptor name on the
+ * initiator side.
+ */
+ ret = decode_Ticket(out_creds->ticket.data, out_creds->ticket.length,
+ &ticket, NULL);
+ if (ret == 0) {
+ ret = krb5_principal_set_realm(context, out_creds->server,
+ ticket.realm);
+ free_Ticket(&ticket);
+ } else {
+ krb5_free_cred_contents(context, out_creds);
+ }
+ }
+ return ret;
+}
+
+static void
+store_cred(krb5_context context, krb5_ccache ccache,
+ krb5_const_principal server_princ, krb5_creds *creds)
+{
+ if (context->no_ticket_store)
+ return;
+ if (!krb5_principal_compare(context, creds->server, server_princ) &&
+ !krb5_principal_is_krbtgt(context, server_princ)) {
+ krb5_principal tmp_princ = creds->server;
+ /*
+ * Store the cred with the pre-canon server princ first so it
+ * can be found quickly in the future.
+ */
+ creds->server = (krb5_principal)server_princ;
+ krb5_cc_store_cred(context, ccache, creds);
+ creds->server = tmp_princ;
+ /* Then store again with the canonicalized server princ */
+ }
+ krb5_cc_store_cred(context, ccache, creds);
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_credentials_with_flags(krb5_context context,
+ krb5_flags options,
+ krb5_kdc_flags flags,
+ krb5_ccache ccache,
+ krb5_creds *in_creds,
+ krb5_creds **out_creds)
+{
+ struct krb5_fast_state fast_state;
+ krb5_error_code ret;
+ krb5_name_canon_iterator name_canon_iter = NULL;
+ krb5_name_canon_rule_options rule_opts;
+ krb5_const_principal try_princ = NULL;
+ krb5_principal save_princ = in_creds->server;
+ krb5_creds **tgts;
+ krb5_creds *res_creds;
+ int i;
+
+ memset(&fast_state, 0, sizeof(fast_state));
+
+ if (_krb5_have_debug(context, 5)) {
+ char *unparsed;
+
+ ret = krb5_unparse_name(context, in_creds->server, &unparsed);
+ if (ret) {
+ _krb5_debug(context, 5, "krb5_get_creds: unable to display "
+ "requested service principal");
+ } else {
+ _krb5_debug(context, 5, "krb5_get_creds: requesting a ticket "
+ "for %s", unparsed);
+ free(unparsed);
+ }
+ }
+
+ if (in_creds->session.keytype) {
+ ret = krb5_enctype_valid(context, in_creds->session.keytype);
+ if (ret)
+ return ret;
+ options |= KRB5_TC_MATCH_KEYTYPE;
+ }
+
+ *out_creds = NULL;
+ res_creds = calloc(1, sizeof(*res_creds));
+ if (res_creds == NULL)
+ return krb5_enomem(context);
+
+ ret = krb5_name_canon_iterator_start(context, in_creds->server,
+ &name_canon_iter);
+ if (ret)
+ goto out;
+
+next_rule:
+ krb5_free_cred_contents(context, res_creds);
+ memset(res_creds, 0, sizeof (*res_creds));
+ ret = krb5_name_canon_iterate(context, &name_canon_iter, &try_princ,
+ &rule_opts);
+ in_creds->server = rk_UNCONST(try_princ);
+ if (ret)
+ goto out;
+
+ if (name_canon_iter == NULL) {
+ if (options & KRB5_GC_CACHED)
+ ret = KRB5_CC_NOTFOUND;
+ else
+ ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
+ goto out;
+ }
+
+ ret = check_cc(context, options, ccache, in_creds, res_creds);
+ if (ret == 0) {
+ *out_creds = res_creds;
+ res_creds = NULL;
+ goto out;
+ } else if(ret != KRB5_CC_END) {
+ goto out;
+ }
+ if (options & KRB5_GC_CACHED)
+ goto next_rule;
+
+ if(options & KRB5_GC_USER_USER)
+ flags.b.enc_tkt_in_skey = 1;
+ if (flags.b.enc_tkt_in_skey)
+ options |= KRB5_GC_NO_STORE;
+
+ tgts = NULL;
+ ret = _krb5_get_cred_kdc_any(context, flags, ccache, &fast_state,
+ in_creds, NULL, NULL, out_creds, &tgts);
+ for (i = 0; tgts && tgts[i]; i++) {
+ if ((options & KRB5_GC_NO_STORE) == 0)
+ krb5_cc_store_cred(context, ccache, tgts[i]);
+ krb5_free_creds(context, tgts[i]);
+ }
+ free(tgts);
+
+ /* We don't yet have TGS w/ FAST, so we can't protect KBR-ERRORs */
+ if (ret == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN &&
+ !(rule_opts & KRB5_NCRO_USE_FAST))
+ goto next_rule;
+
+ if(ret == 0 && (options & KRB5_GC_NO_STORE) == 0)
+ store_cred(context, ccache, in_creds->server, *out_creds);
+
+ if (ret == 0 && _krb5_have_debug(context, 5)) {
+ char *unparsed;
+
+ ret = krb5_unparse_name(context, (*out_creds)->server, &unparsed);
+ if (ret) {
+ _krb5_debug(context, 5, "krb5_get_creds: unable to display "
+ "service principal");
+ } else {
+ _krb5_debug(context, 5, "krb5_get_creds: got a ticket for %s",
+ unparsed);
+ free(unparsed);
+ }
+ }
+
+out:
+ in_creds->server = save_princ;
+ krb5_free_creds(context, res_creds);
+ krb5_free_name_canon_iterator(context, name_canon_iter);
+ _krb5_fast_free(context, &fast_state);
+ if (ret)
+ return not_found(context, in_creds->server, ret);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_credentials(krb5_context context,
+ krb5_flags options,
+ krb5_ccache ccache,
+ krb5_creds *in_creds,
+ krb5_creds **out_creds)
+{
+ krb5_kdc_flags flags;
+ flags.i = 0;
+ return krb5_get_credentials_with_flags(context, options, flags,
+ ccache, in_creds, out_creds);
+}
+
+struct krb5_get_creds_opt_data {
+ krb5_principal self;
+ krb5_flags options;
+ krb5_enctype enctype;
+ Ticket *ticket;
+};
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_creds_opt_alloc(krb5_context context, krb5_get_creds_opt *opt)
+{
+ *opt = calloc(1, sizeof(**opt));
+ if (*opt == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_creds_opt_free(krb5_context context, krb5_get_creds_opt opt)
+{
+ if (opt->self)
+ krb5_free_principal(context, opt->self);
+ if (opt->ticket) {
+ free_Ticket(opt->ticket);
+ free(opt->ticket);
+ }
+ memset(opt, 0, sizeof(*opt));
+ free(opt);
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_creds_opt_set_options(krb5_context context,
+ krb5_get_creds_opt opt,
+ krb5_flags options)
+{
+ opt->options = options;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_creds_opt_add_options(krb5_context context,
+ krb5_get_creds_opt opt,
+ krb5_flags options)
+{
+ opt->options |= options;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_creds_opt_set_enctype(krb5_context context,
+ krb5_get_creds_opt opt,
+ krb5_enctype enctype)
+{
+ opt->enctype = enctype;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_creds_opt_set_impersonate(krb5_context context,
+ krb5_get_creds_opt opt,
+ krb5_const_principal self)
+{
+ if (opt->self)
+ krb5_free_principal(context, opt->self);
+ return krb5_copy_principal(context, self, &opt->self);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_creds_opt_set_ticket(krb5_context context,
+ krb5_get_creds_opt opt,
+ const Ticket *ticket)
+{
+ if (opt->ticket) {
+ free_Ticket(opt->ticket);
+ free(opt->ticket);
+ opt->ticket = NULL;
+ }
+ if (ticket) {
+ krb5_error_code ret;
+
+ opt->ticket = malloc(sizeof(*ticket));
+ if (opt->ticket == NULL)
+ return krb5_enomem(context);
+ ret = copy_Ticket(ticket, opt->ticket);
+ if (ret) {
+ free(opt->ticket);
+ opt->ticket = NULL;
+ krb5_set_error_message(context, ret,
+ N_("malloc: out of memory", ""));
+ return ret;
+ }
+ }
+ return 0;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_creds(krb5_context context,
+ krb5_get_creds_opt opt,
+ krb5_ccache ccache,
+ krb5_const_principal inprinc,
+ krb5_creds **out_creds)
+{
+ struct krb5_fast_state fast_state;
+ krb5_kdc_flags flags;
+ krb5_flags options;
+ krb5_creds in_creds;
+ krb5_error_code ret;
+ krb5_creds **tgts;
+ krb5_creds *res_creds;
+ krb5_const_principal try_princ = NULL;
+ krb5_name_canon_iterator name_canon_iter = NULL;
+ krb5_name_canon_rule_options rule_opts;
+ int i;
+ int type;
+ const char *comp;
+
+ memset(&fast_state, 0, sizeof(fast_state));
+ memset(&in_creds, 0, sizeof(in_creds));
+ in_creds.server = rk_UNCONST(inprinc);
+
+ if (_krb5_have_debug(context, 5)) {
+ char *unparsed;
+
+ ret = krb5_unparse_name(context, in_creds.server, &unparsed);
+ if (ret) {
+ _krb5_debug(context, 5, "krb5_get_creds: unable to display "
+ "requested service principal");
+ } else {
+ _krb5_debug(context, 5, "krb5_get_creds: requesting a ticket "
+ "for %s", unparsed);
+ free(unparsed);
+ }
+ }
+
+ if (opt && opt->enctype) {
+ ret = krb5_enctype_valid(context, opt->enctype);
+ if (ret)
+ return ret;
+ }
+
+ ret = krb5_cc_get_principal(context, ccache, &in_creds.client);
+ if (ret)
+ return ret;
+
+ if (opt)
+ options = opt->options;
+ else
+ options = 0;
+ flags.i = 0;
+
+ *out_creds = NULL;
+ res_creds = calloc(1, sizeof(*res_creds));
+ if (res_creds == NULL) {
+ krb5_free_principal(context, in_creds.client);
+ return krb5_enomem(context);
+ }
+
+ if (opt && opt->enctype) {
+ in_creds.session.keytype = opt->enctype;
+ options |= KRB5_TC_MATCH_KEYTYPE;
+ }
+
+ ret = krb5_name_canon_iterator_start(context, in_creds.server,
+ &name_canon_iter);
+ if (ret)
+ goto out;
+
+next_rule:
+ ret = krb5_name_canon_iterate(context, &name_canon_iter, &try_princ,
+ &rule_opts);
+ in_creds.server = rk_UNCONST(try_princ);
+ if (ret)
+ goto out;
+
+ if (name_canon_iter == NULL) {
+ if (options & KRB5_GC_CACHED)
+ ret = KRB5_CC_NOTFOUND;
+ else
+ ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
+ goto out;
+ }
+
+ if ((options & KRB5_GC_CONSTRAINED_DELEGATION) == 0) {
+ ret = check_cc(context, options, ccache, &in_creds, res_creds);
+ if (ret == 0) {
+ *out_creds = res_creds;
+ res_creds = NULL;
+ goto out;
+ } else if (ret != KRB5_CC_END) {
+ goto out;
+ }
+ }
+ if (options & KRB5_GC_CACHED)
+ goto next_rule;
+
+ type = krb5_principal_get_type(context, try_princ);
+ comp = krb5_principal_get_comp_string(context, try_princ, 0);
+ if ((type == KRB5_NT_SRV_HST || type == KRB5_NT_UNKNOWN) &&
+ comp != NULL && strcmp(comp, "host") == 0)
+ flags.b.canonicalize = 1;
+ if (rule_opts & KRB5_NCRO_NO_REFERRALS)
+ flags.b.canonicalize = 0;
+ else
+ flags.b.canonicalize = (options & KRB5_GC_CANONICALIZE) ? 1 : 0;
+ if (options & KRB5_GC_USER_USER) {
+ flags.b.enc_tkt_in_skey = 1;
+ options |= KRB5_GC_NO_STORE;
+ }
+ if (options & KRB5_GC_FORWARDABLE)
+ flags.b.forwardable = 1;
+ if (options & KRB5_GC_NO_TRANSIT_CHECK)
+ flags.b.disable_transited_check = 1;
+ if (options & KRB5_GC_CONSTRAINED_DELEGATION)
+ flags.b.cname_in_addl_tkt = 1;
+ if (options & KRB5_GC_ANONYMOUS)
+ flags.b.request_anonymous = 1;
+
+ tgts = NULL;
+ ret = _krb5_get_cred_kdc_any(context, flags, ccache, &fast_state,
+ &in_creds, opt ? opt->self : 0,
+ opt ? opt->ticket : 0, out_creds,
+ &tgts);
+ for (i = 0; tgts && tgts[i]; i++) {
+ if ((options & KRB5_GC_NO_STORE) == 0)
+ krb5_cc_store_cred(context, ccache, tgts[i]);
+ krb5_free_creds(context, tgts[i]);
+ }
+ free(tgts);
+
+ /* We don't yet have TGS w/ FAST, so we can't protect KBR-ERRORs */
+ if (ret == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN &&
+ !(rule_opts & KRB5_NCRO_USE_FAST))
+ goto next_rule;
+
+ if (ret == 0 && (options & KRB5_GC_NO_STORE) == 0)
+ store_cred(context, ccache, inprinc, *out_creds);
+
+ if (ret == 0 && _krb5_have_debug(context, 5)) {
+ char *unparsed;
+
+ ret = krb5_unparse_name(context, (*out_creds)->server, &unparsed);
+ if (ret) {
+ _krb5_debug(context, 5, "krb5_get_creds: unable to display "
+ "service principal");
+ } else {
+ _krb5_debug(context, 5, "krb5_get_creds: got a ticket for %s",
+ unparsed);
+ free(unparsed);
+ }
+ }
+
+out:
+ _krb5_fast_free(context, &fast_state);
+ krb5_free_creds(context, res_creds);
+ krb5_free_principal(context, in_creds.client);
+ krb5_free_name_canon_iterator(context, name_canon_iter);
+ if (ret)
+ return not_found(context, inprinc, ret);
+ return ret;
+}
+
+/*
+ *
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_renewed_creds(krb5_context context,
+ krb5_creds *creds,
+ krb5_const_principal client,
+ krb5_ccache ccache,
+ const char *in_tkt_service)
+{
+ krb5_error_code ret;
+ krb5_kdc_flags flags;
+ krb5_creds in, *template, *out = NULL;
+
+ memset(&in, 0, sizeof(in));
+ memset(creds, 0, sizeof(*creds));
+
+ ret = krb5_copy_principal(context, client, &in.client);
+ if (ret)
+ return ret;
+
+ if (in_tkt_service) {
+ ret = krb5_parse_name(context, in_tkt_service, &in.server);
+ if (ret) {
+ krb5_free_principal(context, in.client);
+ return ret;
+ }
+ } else {
+ const char *realm = krb5_principal_get_realm(context, client);
+
+ ret = krb5_make_principal(context, &in.server, realm, KRB5_TGS_NAME,
+ realm, NULL);
+ if (ret) {
+ krb5_free_principal(context, in.client);
+ return ret;
+ }
+ }
+
+ flags.i = 0;
+ flags.b.renewable = flags.b.renew = 1;
+
+ /*
+ * Get template from old credential cache for the same entry, if
+ * this failes, no worries.
+ */
+ ret = krb5_get_credentials(context, KRB5_GC_CACHED, ccache, &in, &template);
+ if (ret == 0) {
+ flags.b.forwardable = template->flags.b.forwardable;
+ flags.b.proxiable = template->flags.b.proxiable;
+ krb5_free_creds (context, template);
+ }
+
+ ret = krb5_get_kdc_cred(context, ccache, flags, NULL, NULL, &in, &out);
+ krb5_free_principal(context, in.client);
+ krb5_free_principal(context, in.server);
+ if (ret)
+ return ret;
+
+ ret = krb5_copy_creds_contents(context, out, creds);
+ krb5_free_creds(context, out);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/get_default_principal.c b/third_party/heimdal/lib/krb5/get_default_principal.c
new file mode 100644
index 0000000..3548074
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/get_default_principal.c
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/*
+ * Try to find out what's a reasonable default principal.
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_get_default_principal_local (krb5_context context,
+ krb5_principal *princ)
+{
+ const char *user = NULL;
+ const char *second_component = NULL;
+ char userbuf[128];
+
+ *princ = NULL;
+
+ /*
+ * NOTE: We prefer getlogin_r() (via roken_get_loginname()) to using $USER,
+ * $LOGNAME, or getpwuid_r() (via roken_get_username()), in that
+ * order, otherwise we won't figure out to output
+ * <username>/root@DEFAULT_REALM.
+ */
+#ifndef WIN32
+ if (geteuid() == 0)
+ user = roken_get_loginname(userbuf, sizeof(userbuf));
+#endif
+ if (user == NULL)
+ user = roken_get_username(userbuf, sizeof(userbuf));
+ if (user == NULL) {
+ krb5_set_error_message(context, ENOTTY,
+ N_("unable to figure out current principal",
+ ""));
+ return ENOTTY; /* XXX */
+ }
+
+#ifndef WIN32
+ if (!issuid() && getuid() == 0 && strcmp(user, "root") != 0)
+ second_component = "root"; /* We'll use <user>/root */
+#endif
+ return krb5_make_principal(context, princ, NULL, user,
+ second_component, NULL);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_default_principal (krb5_context context,
+ krb5_principal *princ)
+{
+ krb5_error_code ret;
+ krb5_ccache id;
+
+ *princ = NULL;
+
+ ret = krb5_cc_default (context, &id);
+ if (ret == 0) {
+ ret = krb5_cc_get_principal (context, id, princ);
+ krb5_cc_close (context, id);
+ if (ret == 0)
+ return 0;
+ }
+
+ return _krb5_get_default_principal_local(context, princ);
+}
diff --git a/third_party/heimdal/lib/krb5/get_default_realm.c b/third_party/heimdal/lib/krb5/get_default_realm.c
new file mode 100644
index 0000000..81a55bb
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/get_default_realm.c
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 1997 - 2001, 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/*
+ * Return a NULL-terminated list of default realms in `realms'.
+ * Free this memory with krb5_free_host_realm.
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_default_realms (krb5_context context,
+ krb5_realm **realms)
+{
+ if (context->default_realms == NULL) {
+ krb5_error_code ret = krb5_set_default_realm (context, NULL);
+ if (ret)
+ return KRB5_CONFIG_NODEFREALM;
+ }
+
+ return krb5_copy_host_realm (context,
+ context->default_realms,
+ realms);
+}
+
+/*
+ * Return the first default realm. For compatibility.
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_default_realm(krb5_context context,
+ krb5_realm *realm)
+{
+ krb5_error_code ret;
+ char *res;
+
+ if (context->default_realms == NULL
+ || context->default_realms[0] == NULL) {
+ krb5_clear_error_message(context);
+ ret = krb5_set_default_realm (context, NULL);
+ if (ret)
+ return ret;
+ }
+
+ res = strdup (context->default_realms[0]);
+ if (res == NULL)
+ return krb5_enomem(context);
+ *realm = res;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/get_for_creds.c b/third_party/heimdal/lib/krb5/get_for_creds.c
new file mode 100644
index 0000000..3a6be10
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/get_for_creds.c
@@ -0,0 +1,367 @@
+/*
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+static krb5_error_code set_tgs_creds(krb5_context, krb5_ccache,
+ krb5_const_principal,
+ krb5_const_principal, krb5_creds *);
+static krb5_error_code get_cred(krb5_context, krb5_ccache, krb5_creds *,
+ krb5_flags, const char *, krb5_creds **);
+static krb5_error_code get_addresses(krb5_context, krb5_ccache, krb5_creds *,
+ const char *, krb5_addresses *);
+
+static krb5_error_code
+add_addrs(krb5_context context,
+ krb5_addresses *addr,
+ struct addrinfo *ai)
+{
+ krb5_error_code ret;
+ unsigned n, i;
+ void *tmp;
+ struct addrinfo *a;
+
+ n = 0;
+ for (a = ai; a != NULL; a = a->ai_next)
+ ++n;
+
+ tmp = realloc(addr->val, (addr->len + n) * sizeof(*addr->val));
+ if (tmp == NULL && (addr->len + n) != 0) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ addr->val = tmp;
+ for (i = addr->len; i < (addr->len + n); ++i) {
+ addr->val[i].addr_type = 0;
+ krb5_data_zero(&addr->val[i].address);
+ }
+ i = addr->len;
+ for (a = ai; a != NULL; a = a->ai_next) {
+ krb5_address ad;
+
+ ret = krb5_sockaddr2address (context, a->ai_addr, &ad);
+ if (ret == 0) {
+ if (krb5_address_search(context, &ad, addr))
+ krb5_free_address(context, &ad);
+ else
+ addr->val[i++] = ad;
+ }
+ else if (ret == KRB5_PROG_ATYPE_NOSUPP)
+ krb5_clear_error_message (context);
+ else
+ goto fail;
+ addr->len = i;
+ }
+ return 0;
+fail:
+ krb5_free_addresses (context, addr);
+ return ret;
+}
+
+/**
+ * Forward credentials for client to host hostname, making them
+ * forwardable if forwardable, and returning the blob of data to sent
+ * in out_data. If hostname == NULL, pick it from server.
+ *
+ * If the server's realm is configured for delegation of destination
+ * TGTs, forward a TGT for the server realm, rather than the client
+ * realm. This works better with destinations on the far side of a
+ * firewall. We also forward the destination TGT when the client
+ * TGT is not available (we may have just the destination TGT).
+ *
+ * @param context A kerberos 5 context.
+ * @param auth_context the auth context with the key to encrypt the out_data.
+ * @param hostname the host to forward the tickets too.
+ * @param client the client to delegate from.
+ * @param server the server to delegate the credential too.
+ * @param ccache credential cache to use.
+ * @param forwardable make the forwarded ticket forwabledable.
+ * @param out_data the resulting credential.
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_fwd_tgt_creds(krb5_context context,
+ krb5_auth_context auth_context,
+ const char *hostname,
+ krb5_const_principal client,
+ krb5_const_principal server,
+ krb5_ccache ccache,
+ int forwardable,
+ krb5_data *out_data)
+{
+ krb5_flags flags = 0;
+ krb5_creds creds;
+ krb5_error_code ret;
+
+ flags |= KDC_OPT_FORWARDED;
+
+ if (forwardable)
+ flags |= KDC_OPT_FORWARDABLE;
+
+ if (hostname == NULL &&
+ krb5_principal_get_type(context, server) == KRB5_NT_SRV_HST) {
+ const char *inst = krb5_principal_get_comp_string(context, server, 0);
+ const char *host = krb5_principal_get_comp_string(context, server, 1);
+
+ if (inst != NULL &&
+ strcmp(inst, "host") == 0 &&
+ host != NULL &&
+ krb5_principal_get_comp_string(context, server, 2) == NULL)
+ hostname = host;
+ }
+
+ /*
+ * Fill-in the request creds, the server principal will be the TGS
+ * of either the client's or the server's realm.
+ */
+ ret = set_tgs_creds(context, ccache, client, server, &creds);
+ if (ret)
+ return ret;
+
+ ret = krb5_get_forwarded_creds (context,
+ auth_context,
+ ccache,
+ flags,
+ hostname,
+ &creds,
+ out_data);
+
+ krb5_free_cred_contents(context, &creds);
+ return ret;
+}
+
+/**
+ * Gets tickets forwarded to hostname. If the tickets that are
+ * forwarded are address-less, the forwarded tickets will also be
+ * address-less.
+ *
+ * If the ticket have any address, hostname will be used for figure
+ * out the address to forward the ticket too. This since this might
+ * use DNS, its insecure and also doesn't represent configured all
+ * addresses of the host. For example, the host might have two
+ * adresses, one IPv4 and one IPv6 address where the later is not
+ * published in DNS. This IPv6 address might be used communications
+ * and thus the resulting ticket useless.
+ *
+ * @param context A kerberos 5 context.
+ * @param auth_context the auth context with the key to encrypt the out_data.
+ * @param ccache credential cache to use
+ * @param flags the flags to control the resulting ticket flags
+ * @param hostname the host to forward the tickets too.
+ * @param in_creds the in client and server ticket names. The client
+ * and server components forwarded to the remote host.
+ * @param out_data the resulting credential.
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_forwarded_creds (krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_ccache ccache,
+ krb5_flags flags,
+ const char *hostname,
+ krb5_creds *in_creds,
+ krb5_data *out_data)
+{
+ krb5_error_code ret;
+ krb5_creds *creds;
+
+ /* Obtain the requested TGT */
+ ret = get_cred(context, ccache, in_creds, flags, hostname, &creds);
+ if (ret)
+ return ret;
+
+ /* Forward obtained creds */
+ ret = _krb5_mk_1cred(context, auth_context, creds, out_data, NULL);
+ krb5_free_creds(context, creds);
+ return ret;
+}
+
+/*
+ * Get a TGT for forwarding to hostname. If the client TGT is
+ * addressless, the forwarded ticket will also be addressless.
+ *
+ * If the TGT has any addresses, hostname will be used to determine
+ * the address to forward the ticket to. Thus, since this might use DNS,
+ * it's insecure and also may not capture all the addresses of the host.
+ * In general addressless tickets are more robust, be it at a small
+ * security penalty.
+ *
+ * @param context A kerberos 5 context.
+ * @param ccache The credential cache to use
+ * @param creds Creds with client and server principals
+ * @param flags The flags to control the resulting ticket flags
+ * @param hostname The hostname of server
+ * @param out_creds The resulting credential
+ *
+ * @return Return an error code or 0.
+ */
+
+static krb5_error_code
+get_cred(krb5_context context,
+ krb5_ccache ccache,
+ krb5_creds *creds,
+ krb5_flags flags,
+ const char *hostname,
+ krb5_creds **out_creds)
+{
+ krb5_error_code ret;
+ krb5_kdc_flags kdc_flags;
+ krb5_addresses addrs;
+
+ addrs.len = 0;
+ addrs.val = NULL;
+ ret = get_addresses(context, ccache, creds, hostname, &addrs);
+ if (ret)
+ return ret;
+
+ kdc_flags.b = int2KDCOptions(flags);
+ ret = krb5_get_kdc_cred(context, ccache, kdc_flags, &addrs, NULL,
+ creds, out_creds);
+
+ krb5_free_addresses(context, &addrs);
+ return ret;
+}
+
+static krb5_error_code
+set_tgs_creds(krb5_context context,
+ krb5_ccache ccache,
+ krb5_const_principal client,
+ krb5_const_principal server,
+ krb5_creds *creds)
+{
+ krb5_error_code ret;
+ krb5_const_realm client_realm;
+ krb5_const_realm server_realm;
+ krb5_boolean fwd_dest_tgt;
+ krb5_creds *client_tgt;
+
+ client_realm = krb5_principal_get_realm(context, client);
+ server_realm = krb5_principal_get_realm(context, server);
+
+ memset (creds, 0, sizeof(*creds));
+ ret = krb5_copy_principal(context, client, &creds->client);
+ if (ret)
+ return ret;
+ ret = krb5_make_principal(context, &creds->server, client_realm,
+ KRB5_TGS_NAME, client_realm, NULL);
+ if (ret) {
+ krb5_free_principal(context, creds->client);
+ return ret;
+ }
+
+ /*
+ * Optionally delegate a TGT for the server's realm, rather than
+ * the client's. Do this also when we don't have a client realm TGT.
+ *
+ * XXX: Note, when we have a start-realm, and delegate-destination-tgt
+ * is not set, we must use the start-realm.
+ */
+ krb5_appdefault_boolean(context, NULL, server_realm,
+ "delegate-destination-tgt", FALSE, &fwd_dest_tgt);
+
+ if (!fwd_dest_tgt) {
+ ret = krb5_get_credentials(context, KRB5_GC_CACHED, ccache, creds,
+ &client_tgt);
+ if (ret == 0) {
+ krb5_free_creds(context, client_tgt);
+ return ret;
+ }
+ }
+
+ /*
+ * Client TGT inapplicable or unavailable
+ */
+ krb5_free_principal(context, creds->server);
+ creds->server = 0;
+ return krb5_make_principal(context, &creds->server, server_realm,
+ KRB5_TGS_NAME, server_realm, NULL);
+}
+
+/*
+ * Obtain address list for hostname if server realm policy is not addressless.
+ */
+static krb5_error_code
+get_addresses(krb5_context context,
+ krb5_ccache ccache,
+ krb5_creds *creds,
+ const char *hostname,
+ krb5_addresses *addrs)
+{
+ krb5_error_code ret;
+ krb5_creds *ticket;
+ krb5_const_realm realm;
+ krb5_boolean noaddr;
+ struct addrinfo *ai;
+ int eai;
+
+ if (hostname == 0)
+ return 0;
+
+ ret = krb5_get_credentials(context, 0, ccache, creds, &ticket);
+ if (ret == 0) {
+ noaddr = (ticket->addresses.len == 0) ? TRUE : FALSE;
+ krb5_free_creds(context, ticket);
+ } else {
+ realm = krb5_principal_get_realm(context, creds->server);
+ krb5_appdefault_boolean(context, NULL, realm, "no-addresses",
+ KRB5_ADDRESSLESS_DEFAULT, &noaddr);
+ }
+
+ if (noaddr)
+ return 0;
+
+ /* Need addresses, get the address of the remote host. */
+
+ eai = getaddrinfo (hostname, NULL, NULL, &ai);
+ if (eai) {
+ ret = krb5_eai_to_heim_errno(eai, errno);
+ krb5_set_error_message(context, ret,
+ N_("resolving host %s failed: %s",
+ "hostname, error"),
+ hostname, gai_strerror(eai));
+ return ret;
+ }
+
+ ret = add_addrs(context, addrs, ai);
+ freeaddrinfo(ai);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/get_host_realm.c b/third_party/heimdal/lib/krb5/get_host_realm.c
new file mode 100644
index 0000000..955d546
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/get_host_realm.c
@@ -0,0 +1,300 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include <resolve.h>
+
+/* To automagically find the correct realm of a host (without
+ * [domain_realm] in krb5.conf) add a text record for your domain with
+ * the name of your realm, like this:
+ *
+ * _kerberos IN TXT "FOO.SE"
+ *
+ * The search is recursive, so you can add entries for specific
+ * hosts. To find the realm of host a.b.c, it first tries
+ * _kerberos.a.b.c, then _kerberos.b.c and so on.
+ *
+ * This method is described in draft-ietf-cat-krb-dns-locate-03.txt.
+ *
+ */
+
+static int
+copy_txt_to_realms(krb5_context context,
+ const char *domain,
+ struct rk_resource_record *head,
+ krb5_realm **realms)
+{
+ struct rk_resource_record *rr;
+ unsigned int n, i;
+
+ for(n = 0, rr = head; rr; rr = rr->next)
+ if (rr->type == rk_ns_t_txt)
+ ++n;
+
+ if (n == 0)
+ return -1;
+
+ *realms = malloc ((n + 1) * sizeof(krb5_realm));
+ if (*realms == NULL)
+ return krb5_enomem(context);;
+
+ for (i = 0; i < n + 1; ++i)
+ (*realms)[i] = NULL;
+
+ for (i = 0, rr = head; rr; rr = rr->next) {
+ if (rr->type == rk_ns_t_txt) {
+ char *tmp = NULL;
+ int invalid_tld = 1;
+
+ /* Check for a gTLD controlled interruption */
+ if (strcmp("Your DNS configuration needs immediate "
+ "attention see https://icann.org/namecollision",
+ rr->u.txt) != 0) {
+ invalid_tld = 0;
+ tmp = strdup(rr->u.txt);
+ }
+ if (tmp == NULL) {
+ for (i = 0; i < n; ++i)
+ free ((*realms)[i]);
+ free (*realms);
+ if (invalid_tld) {
+ krb5_warnx(context,
+ "Realm lookup failed: "
+ "Domain '%s' needs immediate attention "
+ "see https://icann.org/namecollision",
+ domain);
+ return KRB5_KDC_UNREACH;
+ }
+ return krb5_enomem(context);;
+ }
+ (*realms)[i] = tmp;
+ ++i;
+ }
+ }
+ return 0;
+}
+
+static int
+dns_find_realm(krb5_context context,
+ const char *domain,
+ krb5_realm **realms)
+{
+ static const char *default_labels[] = { "_kerberos", NULL };
+ char dom[MAXHOSTNAMELEN];
+ struct rk_dns_reply *r;
+ const char **labels;
+ char **config_labels;
+ int i, ret = 0;
+
+ config_labels = krb5_config_get_strings(context, NULL, "libdefaults",
+ "dns_lookup_realm_labels", NULL);
+ if(config_labels != NULL)
+ labels = (const char **)config_labels;
+ else
+ labels = default_labels;
+ if(*domain == '.')
+ domain++;
+ for (i = 0; labels[i] != NULL; i++) {
+ ret = snprintf(dom, sizeof(dom), "%s.%s.", labels[i], domain);
+ if(ret < 0 || (size_t)ret >= sizeof(dom)) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ r = rk_dns_lookup(dom, "TXT");
+ if(r != NULL) {
+ ret = copy_txt_to_realms(context, domain, r->head, realms);
+ rk_dns_free_data(r);
+ if(ret == 0)
+ goto out;
+ }
+ }
+ krb5_set_error_message(context, KRB5_KDC_UNREACH,
+ "Realm lookup failed: "
+ "No DNS TXT record for %s",
+ domain);
+ ret = KRB5_KDC_UNREACH;
+out:
+ if (config_labels)
+ krb5_config_free_strings(config_labels);
+ return ret;
+}
+
+/*
+ * Try to figure out what realms host in `domain' belong to from the
+ * configuration file.
+ */
+
+static int
+config_find_realm(krb5_context context,
+ const char *domain,
+ krb5_realm **realms)
+{
+ char **tmp = krb5_config_get_strings (context, NULL,
+ "domain_realm",
+ domain,
+ NULL);
+
+ if (tmp == NULL)
+ return -1;
+ *realms = tmp;
+ return 0;
+}
+
+/*
+ * This function assumes that `host' is a FQDN (and doesn't handle the
+ * special case of host == NULL either).
+ * Try to find mapping in the config file or DNS and it that fails,
+ * fall back to guessing
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_get_host_realm_int(krb5_context context,
+ const char *host,
+ krb5_boolean use_dns,
+ krb5_realm **realms)
+{
+ const char *p, *q;
+ const char *port;
+ krb5_boolean dns_locate_enable;
+ krb5_error_code ret = 0;
+
+ /* Strip off any trailing ":port" suffix. */
+ port = strchr(host, ':');
+ if (port != NULL) {
+ host = strndup(host, port - host);
+ if (host == NULL)
+ return krb5_enomem(context);
+ }
+
+ dns_locate_enable = krb5_config_get_bool_default(context, NULL, TRUE,
+ "libdefaults", "dns_lookup_realm", NULL);
+ for (p = host; p != NULL; p = strchr (p + 1, '.')) {
+ if (config_find_realm(context, p, realms) == 0) {
+ if (strcasecmp(*realms[0], "dns_locate") != 0)
+ break;
+ krb5_free_host_realm(context, *realms);
+ *realms = NULL;
+ if (!use_dns)
+ continue;
+ for (q = host; q != NULL; q = strchr(q + 1, '.'))
+ if (dns_find_realm(context, q, realms) == 0)
+ break;
+ if (q)
+ break;
+ } else if (use_dns && dns_locate_enable) {
+ if (dns_find_realm(context, p, realms) == 0)
+ break;
+ }
+ }
+
+ /*
+ * If 'p' is NULL, we did not find an explicit realm mapping in either the
+ * configuration file or DNS. Try the hostname suffix as a last resort.
+ *
+ * XXX: If we implement a KDC-specific variant of this function just for
+ * referrals, we could check whether we have a cross-realm TGT for the
+ * realm in question, and if not try the parent (loop again).
+ */
+ if (p == NULL) {
+ p = strchr(host, '.');
+ if (p != NULL) {
+ p++;
+ *realms = malloc(2 * sizeof(krb5_realm));
+ if (*realms != NULL &&
+ ((*realms)[0] = strdup(p)) != NULL) {
+ strupr((*realms)[0]);
+ (*realms)[1] = NULL;
+ } else {
+ free(*realms);
+ ret = krb5_enomem(context);
+ }
+ } else {
+ krb5_set_error_message(context, KRB5_ERR_HOST_REALM_UNKNOWN,
+ N_("unable to find realm of host %s", ""),
+ host);
+ ret = KRB5_ERR_HOST_REALM_UNKNOWN;
+ }
+ }
+
+ /* If 'port' is not NULL, we have a copy of 'host' to free. */
+ if (port)
+ free((void *)host);
+ return ret;
+}
+
+/*
+ * Return the realm(s) of `host' as a NULL-terminated list in
+ * `realms'. Free `realms' with krb5_free_host_realm().
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_host_realm(krb5_context context,
+ const char *targethost,
+ krb5_realm **realms)
+{
+ const char *host = targethost;
+ char hostname[MAXHOSTNAMELEN];
+ krb5_error_code ret;
+ int use_dns;
+
+ if (host == NULL) {
+ if (gethostname (hostname, sizeof(hostname))) {
+ *realms = NULL;
+ return errno;
+ }
+ host = hostname;
+ }
+
+ /*
+ * If our local hostname is without components, don't even try to dns.
+ */
+
+ use_dns = (strchr(host, '.') != NULL);
+
+ ret = _krb5_get_host_realm_int (context, host, use_dns, realms);
+ if (ret && targethost != NULL) {
+ /*
+ * If there was no realm mapping for the host (and we wasn't
+ * looking for ourself), guess at the local realm, maybe our
+ * KDC knows better then we do and we get a referral back.
+ */
+ ret = krb5_get_default_realms(context, realms);
+ if (ret) {
+ krb5_set_error_message(context, KRB5_ERR_HOST_REALM_UNKNOWN,
+ N_("Unable to find realm of host %s", ""),
+ host);
+ return KRB5_ERR_HOST_REALM_UNKNOWN;
+ }
+ }
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/get_in_tkt.c b/third_party/heimdal/lib/krb5/get_in_tkt.c
new file mode 100644
index 0000000..c19fc69
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/get_in_tkt.c
@@ -0,0 +1,555 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#define KRB5_DEPRECATED_FUNCTION(x)
+
+#include "krb5_locl.h"
+
+#ifndef HEIMDAL_SMALLER
+
+static krb5_error_code
+make_pa_enc_timestamp(krb5_context context, PA_DATA *pa,
+ krb5_enctype etype, krb5_keyblock *key)
+{
+ PA_ENC_TS_ENC p;
+ unsigned char *buf;
+ size_t buf_size;
+ size_t len = 0;
+ EncryptedData encdata;
+ krb5_error_code ret;
+ int32_t usec;
+ int usec2;
+ krb5_crypto crypto;
+
+ krb5_us_timeofday (context, &p.patimestamp, &usec);
+ usec2 = usec;
+ p.pausec = &usec2;
+
+ ASN1_MALLOC_ENCODE(PA_ENC_TS_ENC, buf, buf_size, &p, &len, ret);
+ if (ret)
+ return ret;
+ if(buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret) {
+ free(buf);
+ return ret;
+ }
+ ret = krb5_encrypt_EncryptedData(context,
+ crypto,
+ KRB5_KU_PA_ENC_TIMESTAMP,
+ buf,
+ len,
+ 0,
+ &encdata);
+ free(buf);
+ krb5_crypto_destroy(context, crypto);
+ if (ret)
+ return ret;
+
+ ASN1_MALLOC_ENCODE(EncryptedData, buf, buf_size, &encdata, &len, ret);
+ free_EncryptedData(&encdata);
+ if (ret)
+ return ret;
+ if(buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+ pa->padata_type = KRB5_PADATA_ENC_TIMESTAMP;
+ pa->padata_value.length = len;
+ pa->padata_value.data = buf;
+ return 0;
+}
+
+static krb5_error_code
+add_padata(krb5_context context,
+ METHOD_DATA *md,
+ krb5_principal client,
+ krb5_key_proc key_proc,
+ krb5_const_pointer keyseed,
+ krb5_enctype *enctypes,
+ unsigned netypes,
+ krb5_salt *salt)
+{
+ krb5_error_code ret;
+ PA_DATA *pa2;
+ krb5_salt salt2;
+ krb5_enctype *ep;
+ size_t i;
+
+ if(salt == NULL) {
+ /* default to standard salt */
+ ret = krb5_get_pw_salt (context, client, &salt2);
+ if (ret)
+ return ret;
+ salt = &salt2;
+ }
+ if (!enctypes) {
+ enctypes = context->etypes;
+ netypes = 0;
+ for (ep = enctypes; *ep != ETYPE_NULL; ep++)
+ netypes++;
+ }
+ pa2 = realloc (md->val, (md->len + netypes) * sizeof(*md->val));
+ if (pa2 == NULL)
+ return krb5_enomem(context);
+ md->val = pa2;
+
+ for (i = 0; i < netypes; ++i) {
+ krb5_keyblock *key;
+
+ ret = (*key_proc)(context, enctypes[i], *salt, keyseed, &key);
+ if (ret)
+ continue;
+ ret = make_pa_enc_timestamp (context, &md->val[md->len],
+ enctypes[i], key);
+ krb5_free_keyblock (context, key);
+ if (ret)
+ return ret;
+ ++md->len;
+ }
+ if(salt == &salt2)
+ krb5_free_salt(context, salt2);
+ return 0;
+}
+
+static krb5_error_code
+init_as_req (krb5_context context,
+ KDCOptions opts,
+ krb5_creds *creds,
+ const krb5_addresses *addrs,
+ const krb5_enctype *etypes,
+ const krb5_preauthtype *ptypes,
+ const krb5_preauthdata *preauth,
+ krb5_key_proc key_proc,
+ krb5_const_pointer keyseed,
+ unsigned nonce,
+ AS_REQ *a)
+{
+ krb5_error_code ret;
+ krb5_salt salt;
+
+ memset(a, 0, sizeof(*a));
+
+ a->pvno = 5;
+ a->msg_type = krb_as_req;
+ a->req_body.kdc_options = opts;
+ a->req_body.cname = malloc(sizeof(*a->req_body.cname));
+ if (a->req_body.cname == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ a->req_body.sname = malloc(sizeof(*a->req_body.sname));
+ if (a->req_body.sname == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ ret = _krb5_principal2principalname (a->req_body.cname, creds->client);
+ if (ret)
+ goto fail;
+ ret = _krb5_principal2principalname (a->req_body.sname, creds->server);
+ if (ret)
+ goto fail;
+ ret = copy_Realm(&creds->client->realm, &a->req_body.realm);
+ if (ret)
+ goto fail;
+
+ if(creds->times.starttime) {
+ a->req_body.from = malloc(sizeof(*a->req_body.from));
+ if (a->req_body.from == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ *a->req_body.from = creds->times.starttime;
+ }
+ if(creds->times.endtime){
+ ALLOC(a->req_body.till, 1);
+ *a->req_body.till = creds->times.endtime;
+ }
+ if(creds->times.renew_till){
+ a->req_body.rtime = malloc(sizeof(*a->req_body.rtime));
+ if (a->req_body.rtime == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ *a->req_body.rtime = creds->times.renew_till;
+ }
+ a->req_body.nonce = nonce;
+ ret = _krb5_init_etype(context,
+ KRB5_PDU_AS_REQUEST,
+ &a->req_body.etype.len,
+ &a->req_body.etype.val,
+ etypes);
+ if (ret)
+ goto fail;
+
+ /*
+ * This means no addresses
+ */
+
+ if (addrs && addrs->len == 0) {
+ a->req_body.addresses = NULL;
+ } else {
+ a->req_body.addresses = malloc(sizeof(*a->req_body.addresses));
+ if (a->req_body.addresses == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+
+ if (addrs)
+ ret = krb5_copy_addresses(context, addrs, a->req_body.addresses);
+ else {
+ ret = krb5_get_all_client_addrs (context, a->req_body.addresses);
+ if(ret == 0 && a->req_body.addresses->len == 0) {
+ free(a->req_body.addresses);
+ a->req_body.addresses = NULL;
+ }
+ }
+ if (ret)
+ return ret;
+ }
+
+ a->req_body.enc_authorization_data = NULL;
+ a->req_body.additional_tickets = NULL;
+
+ if(preauth != NULL) {
+ size_t i;
+ ALLOC(a->padata, 1);
+ if(a->padata == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ a->padata->val = NULL;
+ a->padata->len = 0;
+ for(i = 0; i < preauth->len; i++) {
+ if(preauth->val[i].type == KRB5_PADATA_ENC_TIMESTAMP){
+ size_t j;
+
+ for(j = 0; j < preauth->val[i].info.len; j++) {
+ krb5_salt *sp = &salt;
+ if(preauth->val[i].info.val[j].salttype)
+ salt.salttype = *preauth->val[i].info.val[j].salttype;
+ else
+ salt.salttype = KRB5_PW_SALT;
+ if(preauth->val[i].info.val[j].salt)
+ salt.saltvalue = *preauth->val[i].info.val[j].salt;
+ else
+ if(salt.salttype == KRB5_PW_SALT)
+ sp = NULL;
+ else
+ krb5_data_zero(&salt.saltvalue);
+ ret = add_padata(context, a->padata, creds->client,
+ key_proc, keyseed,
+ &preauth->val[i].info.val[j].etype, 1,
+ sp);
+ if (ret == 0)
+ break;
+ }
+ }
+ }
+ } else
+ /* not sure this is the way to use `ptypes' */
+ if (ptypes == NULL || *ptypes == KRB5_PADATA_NONE)
+ a->padata = NULL;
+ else if (*ptypes == KRB5_PADATA_ENC_TIMESTAMP) {
+ ALLOC(a->padata, 1);
+ if (a->padata == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ a->padata->len = 0;
+ a->padata->val = NULL;
+
+ /* make a v5 salted pa-data */
+ add_padata(context, a->padata, creds->client,
+ key_proc, keyseed, a->req_body.etype.val,
+ a->req_body.etype.len, NULL);
+
+ /* make a v4 salted pa-data */
+ salt.salttype = KRB5_PW_SALT;
+ krb5_data_zero(&salt.saltvalue);
+ add_padata(context, a->padata, creds->client,
+ key_proc, keyseed, a->req_body.etype.val,
+ a->req_body.etype.len, &salt);
+ } else {
+ ret = KRB5_PREAUTH_BAD_TYPE;
+ krb5_set_error_message (context, ret,
+ N_("pre-auth type %d not supported", ""),
+ *ptypes);
+ goto fail;
+ }
+ return 0;
+fail:
+ free_AS_REQ(a);
+ return ret;
+}
+
+static int
+set_ptypes(krb5_context context,
+ KRB_ERROR *error,
+ const krb5_preauthtype **ptypes,
+ krb5_preauthdata **preauth)
+{
+ static krb5_preauthdata preauth2;
+ static krb5_preauthtype ptypes2[] = { KRB5_PADATA_ENC_TIMESTAMP, KRB5_PADATA_NONE };
+
+ if(error->e_data) {
+ METHOD_DATA md;
+ size_t i;
+ decode_METHOD_DATA(error->e_data->data,
+ error->e_data->length,
+ &md,
+ NULL);
+ for(i = 0; i < md.len; i++){
+ switch(md.val[i].padata_type){
+ case KRB5_PADATA_ENC_TIMESTAMP:
+ *ptypes = ptypes2;
+ break;
+ case KRB5_PADATA_ETYPE_INFO:
+ *preauth = &preauth2;
+ ALLOC_SEQ(*preauth, 1);
+ (*preauth)->val[0].type = KRB5_PADATA_ENC_TIMESTAMP;
+ decode_ETYPE_INFO(md.val[i].padata_value.data,
+ md.val[i].padata_value.length,
+ &(*preauth)->val[0].info,
+ NULL);
+ break;
+ default:
+ break;
+ }
+ }
+ free_METHOD_DATA(&md);
+ } else {
+ *ptypes = ptypes2;
+ }
+ return(1);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_in_cred(krb5_context context,
+ krb5_flags options,
+ const krb5_addresses *addrs,
+ const krb5_enctype *etypes,
+ const krb5_preauthtype *ptypes,
+ const krb5_preauthdata *preauth,
+ krb5_key_proc key_proc,
+ krb5_const_pointer keyseed,
+ krb5_decrypt_proc decrypt_proc,
+ krb5_const_pointer decryptarg,
+ krb5_creds *creds,
+ krb5_kdc_rep *ret_as_reply)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ krb5_error_code ret;
+ AS_REQ a;
+ krb5_kdc_rep rep;
+ krb5_data req, resp;
+ size_t len = 0;
+ krb5_salt salt;
+ krb5_keyblock *key;
+ size_t size;
+ KDCOptions opts;
+ PA_DATA *pa;
+ krb5_enctype etype;
+ krb5_preauthdata *my_preauth = NULL;
+ unsigned nonce;
+ int done;
+
+ opts = int2KDCOptions(options);
+
+ krb5_generate_random_block (&nonce, sizeof(nonce));
+ nonce &= 0xffffffff;
+
+ do {
+ done = 1;
+ ret = init_as_req (context,
+ opts,
+ creds,
+ addrs,
+ etypes,
+ ptypes,
+ preauth,
+ key_proc,
+ keyseed,
+ nonce,
+ &a);
+ if (my_preauth) {
+ free_ETYPE_INFO(&my_preauth->val[0].info);
+ free (my_preauth->val);
+ my_preauth = NULL;
+ }
+ if (ret)
+ return ret;
+
+ ASN1_MALLOC_ENCODE(AS_REQ, req.data, req.length, &a, &len, ret);
+ free_AS_REQ(&a);
+ if (ret)
+ return ret;
+ if(len != req.length)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ ret = krb5_sendto_kdc (context, &req, &creds->client->realm, &resp);
+ krb5_data_free(&req);
+ if (ret)
+ return ret;
+
+ memset (&rep, 0, sizeof(rep));
+ ret = decode_AS_REP(resp.data, resp.length, &rep.kdc_rep, &size);
+ if(ret) {
+ /* let's try to parse it as a KRB-ERROR */
+ KRB_ERROR error;
+ int ret2;
+
+ ret2 = krb5_rd_error(context, &resp, &error);
+ if(ret2 && resp.data && ((char*)resp.data)[0] == 4)
+ ret = KRB5KRB_AP_ERR_V4_REPLY;
+ krb5_data_free(&resp);
+ if (ret2 == 0) {
+ ret = krb5_error_from_rd_error(context, &error, creds);
+ /* if no preauth was set and KDC requires it, give it
+ one more try */
+ if (!ptypes && !preauth
+ && ret == KRB5KDC_ERR_PREAUTH_REQUIRED
+ && set_ptypes(context, &error, &ptypes, &my_preauth)) {
+ done = 0;
+ preauth = my_preauth;
+ krb5_free_error_contents(context, &error);
+ krb5_clear_error_message(context);
+ continue;
+ }
+ if(ret_as_reply)
+ ret_as_reply->error = error;
+ else
+ free_KRB_ERROR (&error);
+ return ret;
+ }
+ return ret;
+ }
+ krb5_data_free(&resp);
+ } while(!done);
+
+ pa = NULL;
+ etype = rep.kdc_rep.enc_part.etype;
+ if(rep.kdc_rep.padata){
+ int i = 0;
+ pa = krb5_find_padata(rep.kdc_rep.padata->val, rep.kdc_rep.padata->len,
+ KRB5_PADATA_PW_SALT, &i);
+ if(pa == NULL) {
+ i = 0;
+ pa = krb5_find_padata(rep.kdc_rep.padata->val,
+ rep.kdc_rep.padata->len,
+ KRB5_PADATA_AFS3_SALT, &i);
+ }
+ }
+ if(pa) {
+ salt.salttype = (krb5_salttype)pa->padata_type;
+ salt.saltvalue = pa->padata_value;
+
+ ret = (*key_proc)(context, etype, salt, keyseed, &key);
+ } else {
+ /* make a v5 salted pa-data */
+ ret = krb5_get_pw_salt (context, creds->client, &salt);
+
+ if (ret)
+ goto out;
+ ret = (*key_proc)(context, etype, salt, keyseed, &key);
+ krb5_free_salt(context, salt);
+ }
+ if (ret)
+ goto out;
+
+ {
+ unsigned flags = EXTRACT_TICKET_TIMESYNC;
+ if (opts.request_anonymous)
+ flags |= EXTRACT_TICKET_ALLOW_SERVER_MISMATCH | EXTRACT_TICKET_MATCH_ANON;
+
+ ret = _krb5_extract_ticket(context,
+ &rep,
+ creds,
+ key,
+ keyseed,
+ KRB5_KU_AS_REP_ENC_PART,
+ NULL,
+ nonce,
+ flags,
+ NULL,
+ decrypt_proc,
+ decryptarg);
+ }
+ memset (key->keyvalue.data, 0, key->keyvalue.length);
+ krb5_free_keyblock_contents (context, key);
+ free (key);
+
+out:
+ if (ret == 0 && ret_as_reply)
+ *ret_as_reply = rep;
+ else
+ krb5_free_kdc_rep (context, &rep);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_in_tkt(krb5_context context,
+ krb5_flags options,
+ const krb5_addresses *addrs,
+ const krb5_enctype *etypes,
+ const krb5_preauthtype *ptypes,
+ krb5_key_proc key_proc,
+ krb5_const_pointer keyseed,
+ krb5_decrypt_proc decrypt_proc,
+ krb5_const_pointer decryptarg,
+ krb5_creds *creds,
+ krb5_ccache ccache,
+ krb5_kdc_rep *ret_as_reply)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ krb5_error_code ret;
+
+ ret = krb5_get_in_cred (context,
+ options,
+ addrs,
+ etypes,
+ ptypes,
+ NULL,
+ key_proc,
+ keyseed,
+ decrypt_proc,
+ decryptarg,
+ creds,
+ ret_as_reply);
+ if(ret)
+ return ret;
+ if (ccache)
+ ret = krb5_cc_store_cred (context, ccache, creds);
+ return ret;
+}
+
+#endif /* HEIMDAL_SMALLER */
diff --git a/third_party/heimdal/lib/krb5/get_port.c b/third_party/heimdal/lib/krb5/get_port.c
new file mode 100644
index 0000000..93d9433
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/get_port.c
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 1997-2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_getportbyname (krb5_context context,
+ const char *service,
+ const char *proto,
+ int default_port)
+{
+ struct servent *sp;
+
+ if ((sp = roken_getservbyname (service, proto)) == NULL) {
+#if 0
+ krb5_warnx(context, "%s/%s unknown service, using default port %d",
+ service, proto, default_port);
+#endif
+ return htons(default_port);
+ } else
+ return sp->s_port;
+}
diff --git a/third_party/heimdal/lib/krb5/init_creds.c b/third_party/heimdal/lib/krb5/init_creds.c
new file mode 100644
index 0000000..b34e3eb
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/init_creds.c
@@ -0,0 +1,436 @@
+/*
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#undef __attribute__
+#define __attribute__(x)
+
+/**
+ * @page krb5_init_creds_intro The initial credential handing functions
+ * @section section_krb5_init_creds Initial credential
+ *
+ * Functions to get initial credentials: @ref krb5_credential .
+ */
+
+/**
+ * Allocate a new krb5_get_init_creds_opt structure, free with
+ * krb5_get_init_creds_opt_free().
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_opt_alloc(krb5_context context,
+ krb5_get_init_creds_opt **opt)
+{
+ krb5_get_init_creds_opt *o;
+
+ *opt = NULL;
+ o = calloc(1, sizeof(*o));
+ if (o == NULL)
+ return krb5_enomem(context);
+
+ o->opt_private = calloc(1, sizeof(*o->opt_private));
+ if (o->opt_private == NULL) {
+ free(o);
+ return krb5_enomem(context);
+ }
+ o->opt_private->refcount = 1;
+ *opt = o;
+ return 0;
+}
+
+/**
+ * Free krb5_get_init_creds_opt structure.
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_free(krb5_context context,
+ krb5_get_init_creds_opt *opt)
+{
+ if (opt == NULL || opt->opt_private == NULL)
+ return;
+ if (opt->opt_private->refcount < 1) /* abort ? */
+ return;
+ if (--opt->opt_private->refcount == 0) {
+ _krb5_get_init_creds_opt_free_pkinit(opt);
+ free(opt->opt_private);
+ }
+ memset(opt, 0, sizeof(*opt));
+ free(opt);
+}
+
+static int
+get_config_time (krb5_context context,
+ const char *realm,
+ const char *name,
+ int def)
+{
+ int ret;
+
+ ret = krb5_config_get_time (context, NULL,
+ "realms",
+ realm,
+ name,
+ NULL);
+ if (ret >= 0)
+ return ret;
+ ret = krb5_config_get_time (context, NULL,
+ "libdefaults",
+ name,
+ NULL);
+ if (ret >= 0)
+ return ret;
+ return def;
+}
+
+static krb5_boolean
+get_config_bool (krb5_context context,
+ krb5_boolean def_value,
+ const char *realm,
+ const char *name)
+{
+ krb5_boolean b;
+
+ b = krb5_config_get_bool_default(context, NULL, def_value,
+ "realms", realm, name, NULL);
+ if (b != def_value)
+ return b;
+ b = krb5_config_get_bool_default (context, NULL, def_value,
+ "libdefaults", name, NULL);
+ if (b != def_value)
+ return b;
+ return def_value;
+}
+
+/*
+ * set all the values in `opt' to the appropriate values for
+ * application `appname' (default to getprogname() if NULL), and realm
+ * `realm'. First looks in [appdefaults] but falls back to
+ * [realms] or [libdefaults] for some of the values.
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_default_flags(krb5_context context,
+ const char *appname,
+ krb5_const_realm realm,
+ krb5_get_init_creds_opt *opt)
+{
+ krb5_boolean b;
+ time_t t;
+
+ b = get_config_bool (context, KRB5_FORWARDABLE_DEFAULT,
+ realm, "forwardable");
+ krb5_appdefault_boolean(context, appname, realm, "forwardable", b, &b);
+ krb5_get_init_creds_opt_set_forwardable(opt, b);
+
+ b = get_config_bool (context, FALSE, realm, "proxiable");
+ krb5_appdefault_boolean(context, appname, realm, "proxiable", b, &b);
+ krb5_get_init_creds_opt_set_proxiable (opt, b);
+
+ krb5_appdefault_time(context, appname, realm, "ticket_lifetime", 0, &t);
+ if (t == 0)
+ t = get_config_time (context, realm, "ticket_lifetime", 0);
+ if(t != 0)
+ krb5_get_init_creds_opt_set_tkt_life(opt, t);
+
+ krb5_appdefault_time(context, appname, realm, "renew_lifetime", 0, &t);
+ if (t == 0)
+ t = get_config_time (context, realm, "renew_lifetime", 0);
+ if(t != 0)
+ krb5_get_init_creds_opt_set_renew_life(opt, t);
+
+ krb5_appdefault_boolean(context, appname, realm, "no-addresses",
+ KRB5_ADDRESSLESS_DEFAULT, &b);
+ krb5_get_init_creds_opt_set_addressless (context, opt, b);
+
+#if 0
+ krb5_appdefault_boolean(context, appname, realm, "anonymous", FALSE, &b);
+ krb5_get_init_creds_opt_set_anonymous (opt, b);
+
+ krb5_get_init_creds_opt_set_etype_list(opt, enctype,
+ etype_str.num_strings);
+
+ krb5_get_init_creds_opt_set_salt(krb5_get_init_creds_opt *opt,
+ krb5_data *salt);
+
+ krb5_get_init_creds_opt_set_preauth_list(krb5_get_init_creds_opt *opt,
+ krb5_preauthtype *preauth_list,
+ int preauth_list_length);
+#endif
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_change_password_prompt(krb5_get_init_creds_opt *opt,
+ int change_password_prompt)
+{
+ opt->flags |= KRB5_GET_INIT_CREDS_OPT_CHANGE_PASSWORD_PROMPT;
+ opt->change_password_prompt = change_password_prompt;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_tkt_life(krb5_get_init_creds_opt *opt,
+ krb5_deltat tkt_life)
+{
+ opt->flags |= KRB5_GET_INIT_CREDS_OPT_TKT_LIFE;
+ opt->tkt_life = tkt_life;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_renew_life(krb5_get_init_creds_opt *opt,
+ krb5_deltat renew_life)
+{
+ opt->flags |= KRB5_GET_INIT_CREDS_OPT_RENEW_LIFE;
+ opt->renew_life = renew_life;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_forwardable(krb5_get_init_creds_opt *opt,
+ int forwardable)
+{
+ opt->flags |= KRB5_GET_INIT_CREDS_OPT_FORWARDABLE;
+ opt->forwardable = forwardable;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_proxiable(krb5_get_init_creds_opt *opt,
+ int proxiable)
+{
+ opt->flags |= KRB5_GET_INIT_CREDS_OPT_PROXIABLE;
+ opt->proxiable = proxiable;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_etype_list(krb5_get_init_creds_opt *opt,
+ krb5_enctype *etype_list,
+ int etype_list_length)
+{
+ opt->flags |= KRB5_GET_INIT_CREDS_OPT_ETYPE_LIST;
+ opt->etype_list = etype_list;
+ opt->etype_list_length = etype_list_length;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_address_list(krb5_get_init_creds_opt *opt,
+ krb5_addresses *addresses)
+{
+ opt->flags |= KRB5_GET_INIT_CREDS_OPT_ADDRESS_LIST;
+ opt->address_list = addresses;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_preauth_list(krb5_get_init_creds_opt *opt,
+ krb5_preauthtype *preauth_list,
+ int preauth_list_length)
+{
+ opt->flags |= KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST;
+ opt->preauth_list_length = preauth_list_length;
+ opt->preauth_list = preauth_list;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_salt(krb5_get_init_creds_opt *opt,
+ krb5_data *salt)
+{
+ opt->flags |= KRB5_GET_INIT_CREDS_OPT_SALT;
+ opt->salt = salt;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_anonymous(krb5_get_init_creds_opt *opt,
+ int anonymous)
+{
+ opt->flags |= KRB5_GET_INIT_CREDS_OPT_ANONYMOUS;
+ opt->anonymous = anonymous;
+}
+
+static krb5_error_code
+require_ext_opt(krb5_context context,
+ krb5_get_init_creds_opt *opt,
+ const char *type)
+{
+ if (opt->opt_private == NULL) {
+ krb5_set_error_message(context, EINVAL,
+ N_("%s on non extendable opt", ""), type);
+ return EINVAL;
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_pa_password(krb5_context context,
+ krb5_get_init_creds_opt *opt,
+ const char *password,
+ krb5_s2k_proc key_proc)
+{
+ krb5_error_code ret;
+ ret = require_ext_opt(context, opt, "init_creds_opt_set_pa_password");
+ if (ret)
+ return ret;
+ opt->opt_private->password = password;
+ opt->opt_private->key_proc = key_proc;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_pac_request(krb5_context context,
+ krb5_get_init_creds_opt *opt,
+ krb5_boolean req_pac)
+{
+ krb5_error_code ret;
+ ret = require_ext_opt(context, opt, "init_creds_opt_set_pac_req");
+ if (ret)
+ return ret;
+ opt->opt_private->req_pac = req_pac ?
+ KRB5_INIT_CREDS_TRISTATE_TRUE :
+ KRB5_INIT_CREDS_TRISTATE_FALSE;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_addressless(krb5_context context,
+ krb5_get_init_creds_opt *opt,
+ krb5_boolean addressless)
+{
+ krb5_error_code ret;
+ ret = require_ext_opt(context, opt, "init_creds_opt_set_pac_req");
+ if (ret)
+ return ret;
+ if (addressless)
+ opt->opt_private->addressless = KRB5_INIT_CREDS_TRISTATE_TRUE;
+ else
+ opt->opt_private->addressless = KRB5_INIT_CREDS_TRISTATE_FALSE;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_canonicalize(krb5_context context,
+ krb5_get_init_creds_opt *opt,
+ krb5_boolean req)
+{
+ krb5_error_code ret;
+ ret = require_ext_opt(context, opt, "init_creds_opt_set_canonicalize");
+ if (ret)
+ return ret;
+ if (req)
+ opt->opt_private->flags |= KRB5_INIT_CREDS_CANONICALIZE;
+ else
+ opt->opt_private->flags &= ~KRB5_INIT_CREDS_CANONICALIZE;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_win2k(krb5_context context,
+ krb5_get_init_creds_opt *opt,
+ krb5_boolean req)
+{
+ krb5_error_code ret;
+ ret = require_ext_opt(context, opt, "init_creds_opt_set_win2k");
+ if (ret)
+ return ret;
+ if (req) {
+ opt->opt_private->flags |= KRB5_INIT_CREDS_NO_C_CANON_CHECK;
+ opt->opt_private->flags |= KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK;
+ opt->opt_private->flags |= KRB5_INIT_CREDS_PKINIT_NO_KRBTGT_OTHERNAME_CHECK;
+ } else {
+ opt->opt_private->flags &= ~KRB5_INIT_CREDS_NO_C_CANON_CHECK;
+ opt->opt_private->flags &= ~KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK;
+ opt->opt_private->flags &= ~KRB5_INIT_CREDS_PKINIT_NO_KRBTGT_OTHERNAME_CHECK;
+ }
+ return 0;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_process_last_req(krb5_context context,
+ krb5_get_init_creds_opt *opt,
+ krb5_gic_process_last_req func,
+ void *ctx)
+{
+ krb5_error_code ret;
+ ret = require_ext_opt(context, opt, "init_creds_opt_set_process_last_req");
+ if (ret)
+ return ret;
+
+ opt->opt_private->lr.func = func;
+ opt->opt_private->lr.ctx = ctx;
+
+ return 0;
+}
+
+
+#ifndef HEIMDAL_SMALLER
+
+/**
+ * Deprecated: use krb5_get_init_creds_opt_alloc().
+ *
+ * The reason krb5_get_init_creds_opt_init() is deprecated is that
+ * krb5_get_init_creds_opt is a static structure and for ABI reason it
+ * can't grow, ie can't add new functionality.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_init(krb5_get_init_creds_opt *opt)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ memset (opt, 0, sizeof(*opt));
+}
+
+/**
+ * Deprecated: use the new krb5_init_creds_init() and
+ * krb5_init_creds_get_error().
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_opt_get_error(krb5_context context,
+ krb5_get_init_creds_opt *opt,
+ KRB_ERROR **error)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ *error = calloc(1, sizeof(**error));
+ if (*error == NULL)
+ return krb5_enomem(context);
+
+ return 0;
+}
+
+#endif /* HEIMDAL_SMALLER */
diff --git a/third_party/heimdal/lib/krb5/init_creds_pw.c b/third_party/heimdal/lib/krb5/init_creds_pw.c
new file mode 100644
index 0000000..9257886
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/init_creds_pw.c
@@ -0,0 +1,4011 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 - 2010 Apple Inc. All rights reserved.
+ * Portions Copyright (c) 2021, PADL Software Pty Ltd. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#include <heimbasepriv.h>
+
+struct pa_info_data {
+ krb5_enctype etype;
+ krb5_salt salt;
+ krb5_data *s2kparams;
+};
+
+struct krb5_gss_init_ctx_data {
+ krb5_gssic_step step;
+ krb5_gssic_finish finish;
+ krb5_gssic_release_cred release_cred;
+ krb5_gssic_delete_sec_context delete_sec_context;
+
+ const struct gss_OID_desc_struct *mech;
+ struct gss_cred_id_t_desc_struct *cred;
+
+ struct {
+ unsigned int release_cred : 1;
+ } flags;
+};
+
+struct krb5_get_init_creds_ctx {
+ KDCOptions flags;
+ krb5_creds cred;
+ krb5_addresses *addrs;
+ krb5_enctype *etypes;
+ krb5_preauthtype *pre_auth_types;
+ char *in_tkt_service;
+ unsigned nonce;
+ unsigned pk_nonce;
+
+ krb5_data req_buffer;
+ AS_REQ as_req;
+ int pa_counter;
+
+ /* password and keytab_data is freed on completion */
+ char *password;
+ krb5_keytab_key_proc_args *keytab_data;
+
+ krb5_pointer *keyseed;
+ krb5_s2k_proc keyproc;
+
+ krb5_get_init_creds_tristate req_pac;
+
+ krb5_pk_init_ctx pk_init_ctx;
+ krb5_gss_init_ctx gss_init_ctx;
+ int ic_flags;
+
+ char *kdc_hostname;
+ char *sitename;
+
+ struct {
+ unsigned int change_password:1;
+ unsigned int change_password_prompt:1;
+ unsigned int allow_enc_pa_rep:1;
+ unsigned int allow_save_as_reply_key:1;
+ } runflags;
+
+ struct pa_info_data paid;
+
+ METHOD_DATA md;
+ KRB_ERROR error;
+ EncKDCRepPart enc_part;
+
+ krb5_prompter_fct prompter;
+ void *prompter_data;
+ int warned_user;
+
+ struct pa_info_data *ppaid;
+
+ struct krb5_fast_state fast_state;
+ krb5_enctype as_enctype;
+ krb5_keyblock *as_reply_key;
+
+ /* current and available pa mechansm in this exchange */
+ struct pa_auth_mech *pa_mech;
+ heim_array_t available_pa_mechs;
+ const char *pa_used;
+
+ struct {
+ struct timeval run_time;
+ } stats;
+};
+
+static void
+free_paid(krb5_context context, struct pa_info_data *ppaid)
+{
+ krb5_free_salt(context, ppaid->salt);
+ if (ppaid->s2kparams)
+ krb5_free_data(context, ppaid->s2kparams);
+ memset(ppaid, 0, sizeof(*ppaid));
+}
+
+static krb5_error_code KRB5_CALLCONV
+default_s2k_func(krb5_context context, krb5_enctype type,
+ krb5_const_pointer keyseed,
+ krb5_salt salt, krb5_data *s2kparms,
+ krb5_keyblock **key)
+{
+ krb5_error_code ret;
+ krb5_data password;
+ krb5_data opaque;
+
+ if (_krb5_have_debug(context, 5)) {
+ char *str = NULL;
+ ret = krb5_enctype_to_string(context, type, &str);
+ if (ret)
+ return ret;
+
+ _krb5_debug(context, 5, "krb5_get_init_creds: using default_s2k_func: %s (%d)", str, (int)type);
+ free(str);
+ }
+
+ password.data = rk_UNCONST(keyseed);
+ password.length = keyseed ? strlen(keyseed) : 0;
+ if (s2kparms)
+ opaque = *s2kparms;
+ else
+ krb5_data_zero(&opaque);
+
+ *key = malloc(sizeof(**key));
+ if (*key == NULL)
+ return krb5_enomem(context);
+ ret = krb5_string_to_key_data_salt_opaque(context, type, password,
+ salt, opaque, *key);
+ if (ret) {
+ free(*key);
+ *key = NULL;
+ }
+ return ret;
+}
+
+static void
+free_gss_init_ctx(krb5_context context, krb5_gss_init_ctx gssic)
+{
+ if (gssic == NULL)
+ return;
+
+ if (gssic->flags.release_cred)
+ gssic->release_cred(context, gssic, gssic->cred);
+ free(gssic);
+}
+
+static void
+free_init_creds_ctx(krb5_context context, krb5_init_creds_context ctx)
+{
+ if (ctx->etypes)
+ free(ctx->etypes);
+ if (ctx->pre_auth_types)
+ free (ctx->pre_auth_types);
+ if (ctx->in_tkt_service)
+ free(ctx->in_tkt_service);
+ if (ctx->keytab_data)
+ free(ctx->keytab_data);
+ if (ctx->password) {
+ size_t len;
+ len = strlen(ctx->password);
+ memset_s(ctx->password, len, 0, len);
+ free(ctx->password);
+ }
+ free_gss_init_ctx(context, ctx->gss_init_ctx);
+ /*
+ * FAST state
+ */
+ _krb5_fast_free(context, &ctx->fast_state);
+ if (ctx->as_reply_key)
+ krb5_free_keyblock(context, ctx->as_reply_key);
+
+ krb5_data_free(&ctx->req_buffer);
+ krb5_free_cred_contents(context, &ctx->cred);
+ free_METHOD_DATA(&ctx->md);
+ free_EncKDCRepPart(&ctx->enc_part);
+ free_KRB_ERROR(&ctx->error);
+ free_AS_REQ(&ctx->as_req);
+
+ heim_release(ctx->available_pa_mechs);
+ heim_release(ctx->pa_mech);
+ ctx->pa_mech = NULL;
+ free(ctx->kdc_hostname);
+ free(ctx->sitename);
+ free_paid(context, &ctx->paid);
+ memset_s(ctx, sizeof(*ctx), 0, sizeof(*ctx));
+}
+
+static krb5_deltat
+get_config_time (krb5_context context,
+ const char *realm,
+ const char *name,
+ int def)
+{
+ krb5_deltat ret;
+
+ ret = krb5_config_get_time (context, NULL,
+ "realms",
+ realm,
+ name,
+ NULL);
+ if (ret >= 0)
+ return ret;
+ ret = krb5_config_get_time (context, NULL,
+ "libdefaults",
+ name,
+ NULL);
+ if (ret >= 0)
+ return ret;
+ return def;
+}
+
+static krb5_error_code
+init_cred (krb5_context context,
+ krb5_creds *cred,
+ krb5_principal client,
+ krb5_deltat start_time,
+ krb5_get_init_creds_opt *options)
+{
+ krb5_error_code ret;
+ krb5_deltat tmp;
+ krb5_timestamp now;
+
+ krb5_timeofday (context, &now);
+
+ memset (cred, 0, sizeof(*cred));
+
+ if (client)
+ ret = krb5_copy_principal(context, client, &cred->client);
+ else
+ ret = krb5_get_default_principal(context, &cred->client);
+ if (ret)
+ goto out;
+
+ if (start_time)
+ cred->times.starttime = now + start_time;
+
+ if (options->flags & KRB5_GET_INIT_CREDS_OPT_TKT_LIFE)
+ tmp = options->tkt_life;
+ else
+ tmp = KRB5_TKT_LIFETIME_DEFAULT;
+ cred->times.endtime = now + tmp;
+
+ if ((options->flags & KRB5_GET_INIT_CREDS_OPT_RENEW_LIFE)) {
+ if (options->renew_life > 0)
+ tmp = options->renew_life;
+ else
+ tmp = KRB5_TKT_RENEW_LIFETIME_DEFAULT;
+ cred->times.renew_till = now + tmp;
+ }
+
+ return 0;
+
+out:
+ krb5_free_cred_contents (context, cred);
+ return ret;
+}
+
+/*
+ * Print a message (str) to the user about the expiration in `lr'
+ */
+
+static void
+report_expiration (krb5_context context,
+ krb5_prompter_fct prompter,
+ krb5_data *data,
+ const char *str,
+ time_t now)
+{
+ char *p = NULL;
+
+ if (asprintf(&p, "%s%s", str, ctime(&now)) < 0 || p == NULL)
+ return;
+ (*prompter)(context, data, NULL, p, 0, NULL);
+ free(p);
+}
+
+/*
+ * Check the context, and in the case there is a expiration warning,
+ * use the prompter to print the warning.
+ *
+ * @param context A Kerberos 5 context.
+ * @param options An GIC options structure
+ * @param ctx The krb5_init_creds_context check for expiration.
+ */
+
+krb5_error_code
+krb5_process_last_request(krb5_context context,
+ krb5_get_init_creds_opt *options,
+ krb5_init_creds_context ctx)
+{
+ LastReq *lr;
+ size_t i;
+
+ /*
+ * First check if there is a API consumer.
+ */
+
+ lr = &ctx->enc_part.last_req;
+
+ if (options && options->opt_private && options->opt_private->lr.func) {
+ krb5_last_req_entry **lre;
+
+ lre = calloc(lr->len + 1, sizeof(*lre));
+ if (lre == NULL)
+ return krb5_enomem(context);
+
+ for (i = 0; i < lr->len; i++) {
+ lre[i] = calloc(1, sizeof(*lre[i]));
+ if (lre[i] == NULL)
+ break;
+ lre[i]->lr_type = lr->val[i].lr_type;
+ lre[i]->value = lr->val[i].lr_value;
+ }
+
+ (*options->opt_private->lr.func)(context, lre,
+ options->opt_private->lr.ctx);
+
+ for (i = 0; i < lr->len; i++)
+ free(lre[i]);
+ free(lre);
+ }
+
+ return krb5_init_creds_warn_user(context, ctx);
+}
+
+/**
+ * Warn the user using prompter in the krb5_init_creds_context about
+ * possible password and account expiration.
+ *
+ * @param context a Kerberos 5 context.
+ * @param ctx a krb5_init_creds_context context.
+ *
+ * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message().
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_warn_user(krb5_context context,
+ krb5_init_creds_context ctx)
+{
+ krb5_timestamp sec;
+ krb5_const_realm realm;
+ krb5_enctype weak_enctype = KRB5_ENCTYPE_NULL;
+ LastReq *lr;
+ unsigned i;
+ time_t t;
+
+ if (ctx->prompter == NULL)
+ return 0;
+
+ if (ctx->warned_user)
+ return 0;
+
+ ctx->warned_user = 1;
+
+ krb5_timeofday (context, &sec);
+
+ realm = krb5_principal_get_realm (context, ctx->cred.client);
+ lr = &ctx->enc_part.last_req;
+
+ t = sec + get_config_time (context,
+ realm,
+ "warn_pwexpire",
+ 7 * 24 * 60 * 60);
+
+ for (i = 0; i < lr->len; ++i) {
+ if (lr->val[i].lr_value <= t) {
+ switch (lr->val[i].lr_type) {
+ case LR_PW_EXPTIME :
+ report_expiration(context, ctx->prompter,
+ ctx->prompter_data,
+ "Your password will expire at ",
+ lr->val[i].lr_value);
+ break;
+ case LR_ACCT_EXPTIME :
+ report_expiration(context, ctx->prompter,
+ ctx->prompter_data,
+ "Your account will expire at ",
+ lr->val[i].lr_value);
+ break;
+ default:
+ break;
+ }
+ }
+ }
+
+ if (krb5_is_enctype_weak(context, ctx->as_enctype))
+ weak_enctype = ctx->as_enctype;
+ else if (krb5_is_enctype_weak(context, ctx->cred.session.keytype))
+ weak_enctype = ctx->cred.session.keytype;
+
+ if (ctx->prompter && weak_enctype != KRB5_ENCTYPE_NULL) {
+ int suppress = krb5_config_get_bool_default(context, NULL, false,
+ "libdefaults",
+ "suppress_weak_enctype", NULL);
+ if (!suppress) {
+ char *str = NULL, *p = NULL;
+ int aret;
+
+ (void) krb5_enctype_to_string(context, weak_enctype, &str);
+ aret = asprintf(&p, "Encryption type %s(%d) used for authentication is weak and will be deprecated",
+ str ? str : "unknown", weak_enctype);
+ if (aret >= 0 && p) {
+ (*ctx->prompter)(context, ctx->prompter_data, NULL, p, 0, NULL);
+ free(p);
+ }
+ free(str);
+ }
+ }
+
+ return 0;
+}
+
+static krb5_addresses no_addrs = { 0, NULL };
+
+static krb5_error_code
+get_init_creds_common(krb5_context context,
+ krb5_principal client,
+ krb5_prompter_fct prompter,
+ void *prompter_data,
+ krb5_deltat start_time,
+ krb5_get_init_creds_opt *options,
+ krb5_init_creds_context ctx)
+{
+ krb5_get_init_creds_opt *default_opt = NULL;
+ krb5_error_code ret;
+ krb5_enctype *etypes;
+ krb5_preauthtype *pre_auth_types;
+
+ memset(ctx, 0, sizeof(*ctx));
+
+ if (options == NULL) {
+ const char *realm = krb5_principal_get_realm(context, client);
+
+ ret = krb5_get_init_creds_opt_alloc(context, &default_opt);
+ if (ret)
+ return ret;
+ options = default_opt;
+ krb5_get_init_creds_opt_set_default_flags(context, NULL, realm, options);
+ }
+
+ if (options->opt_private) {
+ if (options->opt_private->password) {
+ ret = krb5_init_creds_set_password(context, ctx,
+ options->opt_private->password);
+ if (ret)
+ goto out;
+ }
+
+ ctx->keyproc = options->opt_private->key_proc;
+ ctx->req_pac = options->opt_private->req_pac;
+ ctx->pk_init_ctx = options->opt_private->pk_init_ctx;
+ ctx->ic_flags = options->opt_private->flags;
+ } else
+ ctx->req_pac = KRB5_INIT_CREDS_TRISTATE_UNSET;
+
+ if (ctx->keyproc == NULL)
+ ctx->keyproc = default_s2k_func;
+
+ if (ctx->ic_flags & KRB5_INIT_CREDS_CANONICALIZE)
+ ctx->flags.canonicalize = 1;
+ if (krb5_principal_get_type(context, client) == KRB5_NT_ENTERPRISE_PRINCIPAL)
+ ctx->flags.canonicalize = 1;
+
+ ctx->pre_auth_types = NULL;
+ ctx->addrs = NULL;
+ ctx->etypes = NULL;
+ ctx->pre_auth_types = NULL;
+
+ ret = init_cred(context, &ctx->cred, client, start_time, options);
+ if (ret)
+ goto out;
+
+ ret = krb5_init_creds_set_service(context, ctx, NULL);
+ if (ret)
+ goto out;
+
+ if (options->flags & KRB5_GET_INIT_CREDS_OPT_FORWARDABLE)
+ ctx->flags.forwardable = options->forwardable;
+
+ if (options->flags & KRB5_GET_INIT_CREDS_OPT_PROXIABLE)
+ ctx->flags.proxiable = options->proxiable;
+
+ if (start_time)
+ ctx->flags.postdated = 1;
+ if (ctx->cred.times.renew_till)
+ ctx->flags.renewable = 1;
+ if (options->flags & KRB5_GET_INIT_CREDS_OPT_ADDRESS_LIST) {
+ ctx->addrs = options->address_list;
+ } else if (options->opt_private) {
+ switch (options->opt_private->addressless) {
+ case KRB5_INIT_CREDS_TRISTATE_UNSET:
+#if KRB5_ADDRESSLESS_DEFAULT == TRUE
+ ctx->addrs = &no_addrs;
+#else
+ ctx->addrs = NULL;
+#endif
+ break;
+ case KRB5_INIT_CREDS_TRISTATE_FALSE:
+ ctx->addrs = NULL;
+ break;
+ case KRB5_INIT_CREDS_TRISTATE_TRUE:
+ ctx->addrs = &no_addrs;
+ break;
+ }
+ }
+ if (options->flags & KRB5_GET_INIT_CREDS_OPT_ETYPE_LIST) {
+ if (ctx->etypes)
+ free(ctx->etypes);
+
+ etypes = malloc((options->etype_list_length + 1)
+ * sizeof(krb5_enctype));
+ if (etypes == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ memcpy (etypes, options->etype_list,
+ options->etype_list_length * sizeof(krb5_enctype));
+ etypes[options->etype_list_length] = ETYPE_NULL;
+ ctx->etypes = etypes;
+ }
+ if (options->flags & KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST) {
+ pre_auth_types = malloc((options->preauth_list_length + 1)
+ * sizeof(krb5_preauthtype));
+ if (pre_auth_types == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ memcpy (pre_auth_types, options->preauth_list,
+ options->preauth_list_length * sizeof(krb5_preauthtype));
+ pre_auth_types[options->preauth_list_length] = KRB5_PADATA_NONE;
+ ctx->pre_auth_types = pre_auth_types;
+ }
+ if (options->flags & KRB5_GET_INIT_CREDS_OPT_ANONYMOUS)
+ ctx->flags.request_anonymous = options->anonymous;
+
+ ctx->prompter = prompter;
+ ctx->prompter_data = prompter_data;
+
+ if ((options->flags & KRB5_GET_INIT_CREDS_OPT_CHANGE_PASSWORD_PROMPT) &&
+ !options->change_password_prompt)
+ ctx->runflags.change_password_prompt = 0;
+ else
+ ctx->runflags.change_password_prompt = ctx->prompter != NULL;
+
+ out:
+ if (default_opt)
+ krb5_get_init_creds_opt_free(context, default_opt);
+ return ret;
+}
+
+static krb5_error_code
+change_password (krb5_context context,
+ krb5_principal client,
+ const char *password,
+ char *newpw,
+ size_t newpw_sz,
+ krb5_prompter_fct prompter,
+ void *data,
+ krb5_get_init_creds_opt *old_options)
+{
+ krb5_prompt prompts[2];
+ krb5_error_code ret;
+ krb5_creds cpw_cred;
+ char buf1[BUFSIZ], buf2[BUFSIZ];
+ krb5_data password_data[2];
+ int result_code;
+ krb5_data result_code_string;
+ krb5_data result_string;
+ char *p;
+ krb5_get_init_creds_opt *options;
+
+ heim_assert(prompter != NULL, "unexpected NULL prompter");
+
+ memset (&cpw_cred, 0, sizeof(cpw_cred));
+
+ ret = krb5_get_init_creds_opt_alloc(context, &options);
+ if (ret)
+ return ret;
+ krb5_get_init_creds_opt_set_tkt_life (options, 60);
+ krb5_get_init_creds_opt_set_forwardable (options, FALSE);
+ krb5_get_init_creds_opt_set_proxiable (options, FALSE);
+ if (old_options &&
+ (old_options->flags & KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST))
+ krb5_get_init_creds_opt_set_preauth_list(options,
+ old_options->preauth_list,
+ old_options->preauth_list_length);
+ if (old_options &&
+ (old_options->flags & KRB5_GET_INIT_CREDS_OPT_CHANGE_PASSWORD_PROMPT))
+ krb5_get_init_creds_opt_set_change_password_prompt(options,
+ old_options->change_password_prompt);
+
+ krb5_data_zero (&result_code_string);
+ krb5_data_zero (&result_string);
+
+ ret = krb5_get_init_creds_password (context,
+ &cpw_cred,
+ client,
+ password,
+ prompter,
+ data,
+ 0,
+ "kadmin/changepw",
+ options);
+ krb5_get_init_creds_opt_free(context, options);
+ if (ret)
+ goto out;
+
+ for(;;) {
+ password_data[0].data = buf1;
+ password_data[0].length = sizeof(buf1);
+
+ prompts[0].hidden = 1;
+ prompts[0].prompt = "New password: ";
+ prompts[0].reply = &password_data[0];
+ prompts[0].type = KRB5_PROMPT_TYPE_NEW_PASSWORD;
+
+ password_data[1].data = buf2;
+ password_data[1].length = sizeof(buf2);
+
+ prompts[1].hidden = 1;
+ prompts[1].prompt = "Repeat new password: ";
+ prompts[1].reply = &password_data[1];
+ prompts[1].type = KRB5_PROMPT_TYPE_NEW_PASSWORD_AGAIN;
+
+ ret = (*prompter) (context, data, NULL, "Changing password",
+ 2, prompts);
+ if (ret) {
+ memset (buf1, 0, sizeof(buf1));
+ memset (buf2, 0, sizeof(buf2));
+ goto out;
+ }
+
+ if (strcmp (buf1, buf2) == 0)
+ break;
+ memset (buf1, 0, sizeof(buf1));
+ memset (buf2, 0, sizeof(buf2));
+ }
+
+ ret = krb5_set_password (context,
+ &cpw_cred,
+ buf1,
+ client,
+ &result_code,
+ &result_code_string,
+ &result_string);
+ if (ret)
+ goto out;
+
+ if (asprintf(&p, "%s: %.*s\n",
+ result_code ? "Error" : "Success",
+ (int)result_string.length,
+ result_string.length > 0 ? (char*)result_string.data : "") < 0)
+ {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ /* return the result */
+ (*prompter) (context, data, NULL, p, 0, NULL);
+
+ if (result_code == 0) {
+ strlcpy (newpw, buf1, newpw_sz);
+ ret = 0;
+ } else {
+ krb5_set_error_message(context, ret = KRB5_CHPW_FAIL,
+ N_("failed changing password: %s", ""), p);
+ }
+ free (p);
+
+out:
+ memset_s(buf1, sizeof(buf1), 0, sizeof(buf1));
+ memset_s(buf2, sizeof(buf2), 0, sizeof(buf2));
+ krb5_data_free (&result_string);
+ krb5_data_free (&result_code_string);
+ krb5_free_cred_contents (context, &cpw_cred);
+ return ret;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_keyblock_key_proc (krb5_context context,
+ krb5_keytype type,
+ krb5_data *salt,
+ krb5_const_pointer keyseed,
+ krb5_keyblock **key)
+{
+ return krb5_copy_keyblock (context, keyseed, key);
+}
+
+/*
+ *
+ */
+
+static krb5_error_code
+init_as_req (krb5_context context,
+ KDCOptions opts,
+ const krb5_creds *creds,
+ const krb5_addresses *addrs,
+ const krb5_enctype *etypes,
+ AS_REQ *a)
+{
+ krb5_error_code ret;
+
+ memset(a, 0, sizeof(*a));
+
+ a->pvno = 5;
+ a->msg_type = krb_as_req;
+ a->req_body.kdc_options = opts;
+ a->req_body.cname = calloc(1, sizeof(*a->req_body.cname));
+ if (a->req_body.cname == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ a->req_body.sname = calloc(1, sizeof(*a->req_body.sname));
+ if (a->req_body.sname == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+
+ ret = _krb5_principal2principalname (a->req_body.cname, creds->client);
+ if (ret)
+ goto fail;
+ ret = copy_Realm(&creds->client->realm, &a->req_body.realm);
+ if (ret)
+ goto fail;
+
+ ret = _krb5_principal2principalname (a->req_body.sname, creds->server);
+ if (ret)
+ goto fail;
+
+ if(creds->times.starttime) {
+ a->req_body.from = malloc(sizeof(*a->req_body.from));
+ if (a->req_body.from == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ *a->req_body.from = creds->times.starttime;
+ }
+ if(creds->times.endtime){
+ if ((ALLOC(a->req_body.till, 1)) != NULL)
+ *a->req_body.till = creds->times.endtime;
+ else {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ }
+ if(creds->times.renew_till){
+ a->req_body.rtime = malloc(sizeof(*a->req_body.rtime));
+ if (a->req_body.rtime == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ *a->req_body.rtime = creds->times.renew_till;
+ }
+ a->req_body.nonce = 0;
+ ret = _krb5_init_etype(context,
+ KRB5_PDU_AS_REQUEST,
+ &a->req_body.etype.len,
+ &a->req_body.etype.val,
+ etypes);
+ if (ret)
+ goto fail;
+
+ /*
+ * This means no addresses
+ */
+
+ if (addrs && addrs->len == 0) {
+ a->req_body.addresses = NULL;
+ } else {
+ a->req_body.addresses = malloc(sizeof(*a->req_body.addresses));
+ if (a->req_body.addresses == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+
+ if (addrs)
+ ret = krb5_copy_addresses(context, addrs, a->req_body.addresses);
+ else {
+ ret = krb5_get_all_client_addrs (context, a->req_body.addresses);
+ if(ret == 0 && a->req_body.addresses->len == 0) {
+ free(a->req_body.addresses);
+ a->req_body.addresses = NULL;
+ }
+ }
+ if (ret)
+ goto fail;
+ }
+
+ a->req_body.enc_authorization_data = NULL;
+ a->req_body.additional_tickets = NULL;
+
+ a->padata = NULL;
+
+ return 0;
+ fail:
+ free_AS_REQ(a);
+ memset_s(a, sizeof(*a), 0, sizeof(*a));
+ return ret;
+}
+
+
+static krb5_error_code
+set_paid(struct pa_info_data *paid, krb5_context context,
+ krb5_enctype etype,
+ krb5_salttype salttype, void *salt_string, size_t salt_len,
+ krb5_data *s2kparams)
+{
+ paid->etype = etype;
+ paid->salt.salttype = salttype;
+ paid->salt.saltvalue.data = malloc(salt_len + 1);
+ if (paid->salt.saltvalue.data == NULL) {
+ krb5_clear_error_message(context);
+ return krb5_enomem(context);
+ }
+ memcpy(paid->salt.saltvalue.data, salt_string, salt_len);
+ ((char *)paid->salt.saltvalue.data)[salt_len] = '\0';
+ paid->salt.saltvalue.length = salt_len;
+ if (s2kparams) {
+ krb5_error_code ret;
+
+ ret = krb5_copy_data(context, s2kparams, &paid->s2kparams);
+ if (ret) {
+ krb5_clear_error_message(context);
+ krb5_free_salt(context, paid->salt);
+ return ret;
+ }
+ } else
+ paid->s2kparams = NULL;
+
+ return 0;
+}
+
+static struct pa_info_data *
+pa_etype_info2(krb5_context context,
+ const krb5_principal client,
+ const AS_REQ *asreq,
+ struct pa_info_data *paid,
+ heim_octet_string *data)
+{
+ krb5_error_code ret;
+ ETYPE_INFO2 e;
+ size_t sz;
+ size_t i, j;
+
+ memset(&e, 0, sizeof(e));
+ ret = decode_ETYPE_INFO2(data->data, data->length, &e, &sz);
+ if (ret)
+ goto out;
+ if (e.len == 0)
+ goto out;
+ for (j = 0; j < asreq->req_body.etype.len; j++) {
+ for (i = 0; i < e.len; i++) {
+
+ if (krb5_enctype_valid(context, e.val[i].etype) != 0)
+ continue;
+
+ if (asreq->req_body.etype.val[j] == e.val[i].etype) {
+ krb5_salt salt;
+ if (e.val[i].salt == NULL)
+ ret = krb5_get_pw_salt(context, client, &salt);
+ else {
+ salt.saltvalue.data = *e.val[i].salt;
+ salt.saltvalue.length = strlen(*e.val[i].salt);
+ ret = 0;
+ }
+ if (ret == 0)
+ ret = set_paid(paid, context, e.val[i].etype,
+ KRB5_PW_SALT,
+ salt.saltvalue.data,
+ salt.saltvalue.length,
+ e.val[i].s2kparams);
+ if (e.val[i].salt == NULL)
+ krb5_free_salt(context, salt);
+ if (ret == 0) {
+ free_ETYPE_INFO2(&e);
+ return paid;
+ }
+ }
+ }
+ }
+ out:
+ free_ETYPE_INFO2(&e);
+ return NULL;
+}
+
+static struct pa_info_data *
+pa_etype_info(krb5_context context,
+ const krb5_principal client,
+ const AS_REQ *asreq,
+ struct pa_info_data *paid,
+ heim_octet_string *data)
+{
+ krb5_error_code ret;
+ ETYPE_INFO e;
+ size_t sz;
+ size_t i, j;
+
+ memset(&e, 0, sizeof(e));
+ ret = decode_ETYPE_INFO(data->data, data->length, &e, &sz);
+ if (ret)
+ goto out;
+ if (e.len == 0)
+ goto out;
+ for (j = 0; j < asreq->req_body.etype.len; j++) {
+ for (i = 0; i < e.len; i++) {
+
+ if (krb5_enctype_valid(context, e.val[i].etype) != 0)
+ continue;
+
+ if (asreq->req_body.etype.val[j] == e.val[i].etype) {
+ krb5_salt salt;
+ salt.salttype = KRB5_PW_SALT;
+ if (e.val[i].salt == NULL)
+ ret = krb5_get_pw_salt(context, client, &salt);
+ else {
+ salt.saltvalue = *e.val[i].salt;
+ ret = 0;
+ }
+ if (e.val[i].salttype)
+ salt.salttype = *e.val[i].salttype;
+ if (ret == 0) {
+ ret = set_paid(paid, context, e.val[i].etype,
+ salt.salttype,
+ salt.saltvalue.data,
+ salt.saltvalue.length,
+ NULL);
+ if (e.val[i].salt == NULL)
+ krb5_free_salt(context, salt);
+ }
+ if (ret == 0) {
+ free_ETYPE_INFO(&e);
+ return paid;
+ }
+ }
+ }
+ }
+ out:
+ free_ETYPE_INFO(&e);
+ return NULL;
+}
+
+static struct pa_info_data *
+pa_pw_or_afs3_salt(krb5_context context,
+ const krb5_principal client,
+ const AS_REQ *asreq,
+ struct pa_info_data *paid,
+ heim_octet_string *data)
+{
+ krb5_error_code ret;
+ if (paid->etype == KRB5_ENCTYPE_NULL)
+ return NULL;
+ if (krb5_enctype_valid(context, paid->etype) != 0)
+ return NULL;
+
+ ret = set_paid(paid, context,
+ paid->etype,
+ paid->salt.salttype,
+ data->data,
+ data->length,
+ NULL);
+ if (ret)
+ return NULL;
+ return paid;
+}
+
+
+static krb5_error_code
+make_pa_enc_timestamp(krb5_context context, METHOD_DATA *md,
+ krb5_enctype etype, krb5_keyblock *key)
+{
+ PA_ENC_TS_ENC p;
+ unsigned char *buf;
+ size_t buf_size;
+ size_t len = 0;
+ EncryptedData encdata;
+ krb5_error_code ret;
+ int32_t usec;
+ int usec2;
+ krb5_crypto crypto;
+
+ krb5_us_timeofday (context, &p.patimestamp, &usec);
+ usec2 = usec;
+ p.pausec = &usec2;
+
+ ASN1_MALLOC_ENCODE(PA_ENC_TS_ENC, buf, buf_size, &p, &len, ret);
+ if (ret)
+ return ret;
+ if(buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret) {
+ free(buf);
+ return ret;
+ }
+ ret = krb5_encrypt_EncryptedData(context,
+ crypto,
+ KRB5_KU_PA_ENC_TIMESTAMP,
+ buf,
+ len,
+ 0,
+ &encdata);
+ free(buf);
+ krb5_crypto_destroy(context, crypto);
+ if (ret)
+ return ret;
+
+ ASN1_MALLOC_ENCODE(EncryptedData, buf, buf_size, &encdata, &len, ret);
+ free_EncryptedData(&encdata);
+ if (ret)
+ return ret;
+ if(buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ ret = krb5_padata_add(context, md, KRB5_PADATA_ENC_TIMESTAMP, buf, len);
+ if (ret)
+ free(buf);
+ return ret;
+}
+
+static krb5_error_code
+add_enc_ts_padata(krb5_context context,
+ METHOD_DATA *md,
+ krb5_principal client,
+ krb5_s2k_proc keyproc,
+ krb5_const_pointer keyseed,
+ krb5_enctype *enctypes,
+ unsigned netypes,
+ krb5_salt *salt,
+ krb5_data *s2kparams)
+{
+ krb5_error_code ret;
+ krb5_salt salt2;
+ krb5_enctype *ep;
+ size_t i;
+
+ memset(&salt2, 0, sizeof(salt2));
+
+ if(salt == NULL) {
+ /* default to standard salt */
+ ret = krb5_get_pw_salt (context, client, &salt2);
+ if (ret)
+ return ret;
+ salt = &salt2;
+ }
+ if (!enctypes) {
+ enctypes = context->etypes;
+ netypes = 0;
+ for (ep = enctypes; *ep != ETYPE_NULL; ep++)
+ netypes++;
+ }
+
+ for (i = 0; i < netypes; ++i) {
+ krb5_keyblock *key;
+
+ _krb5_debug(context, 5, "krb5_get_init_creds: using ENC-TS with enctype %d", enctypes[i]);
+
+ ret = (*keyproc)(context, enctypes[i], keyseed,
+ *salt, s2kparams, &key);
+ if (ret)
+ continue;
+ ret = make_pa_enc_timestamp (context, md, enctypes[i], key);
+ krb5_free_keyblock (context, key);
+ if (ret)
+ return ret;
+ }
+ if(salt == &salt2)
+ krb5_free_salt(context, salt2);
+ return 0;
+}
+
+static krb5_error_code
+pa_data_to_md_ts_enc(krb5_context context,
+ const AS_REQ *a,
+ const krb5_principal client,
+ krb5_init_creds_context ctx,
+ struct pa_info_data *ppaid,
+ METHOD_DATA *md)
+{
+ if (ctx->keyproc == NULL || ctx->keyseed == NULL)
+ return 0;
+
+ if (ppaid) {
+ add_enc_ts_padata(context, md, client,
+ ctx->keyproc, ctx->keyseed,
+ &ppaid->etype, 1,
+ &ppaid->salt, ppaid->s2kparams);
+ } else {
+ krb5_salt salt;
+
+ _krb5_debug(context, 5, "krb5_get_init_creds: pa-info not found, guessing salt");
+
+ /* make a v5 salted pa-data */
+ add_enc_ts_padata(context, md, client,
+ ctx->keyproc, ctx->keyseed,
+ a->req_body.etype.val, a->req_body.etype.len,
+ NULL, NULL);
+
+ /* make a v4 salted pa-data */
+ salt.salttype = KRB5_PW_SALT;
+ krb5_data_zero(&salt.saltvalue);
+ add_enc_ts_padata(context, md, client,
+ ctx->keyproc, ctx->keyseed,
+ a->req_body.etype.val, a->req_body.etype.len,
+ &salt, NULL);
+ }
+ return 0;
+}
+
+static krb5_error_code
+pa_data_to_key_plain(krb5_context context,
+ const krb5_principal client,
+ krb5_init_creds_context ctx,
+ krb5_salt salt,
+ krb5_data *s2kparams,
+ krb5_enctype etype,
+ krb5_keyblock **key)
+{
+ krb5_error_code ret;
+
+ ret = (*ctx->keyproc)(context, etype, ctx->keyseed,
+ salt, s2kparams, key);
+ return ret;
+}
+
+struct pkinit_context {
+ unsigned int win2k : 1;
+ unsigned int used_pkinit : 1;
+};
+
+
+static krb5_error_code
+pa_data_to_md_pkinit(krb5_context context,
+ const AS_REQ *a,
+ const krb5_principal client,
+ int win2k,
+ krb5_init_creds_context ctx,
+ METHOD_DATA *md)
+{
+ if (ctx->pk_init_ctx == NULL)
+ return 0;
+#ifdef PKINIT
+ return _krb5_pk_mk_padata(context,
+ ctx->pk_init_ctx,
+ ctx->ic_flags,
+ win2k,
+ &a->req_body,
+ ctx->pk_nonce,
+ md);
+#else
+ krb5_set_error_message(context, EINVAL,
+ N_("no support for PKINIT compiled in", ""));
+ return EINVAL;
+#endif
+}
+
+static krb5_error_code
+pkinit_configure_ietf(krb5_context context, krb5_init_creds_context ctx, void *pa_ctx)
+{
+ struct pkinit_context *pkinit_ctx = pa_ctx;
+
+ pkinit_ctx->win2k = 0;
+
+ if (ctx->pk_init_ctx == NULL)
+ return HEIM_ERR_PA_CANT_CONTINUE;
+
+ return 0;
+}
+
+static krb5_error_code
+pkinit_configure_win(krb5_context context, krb5_init_creds_context ctx, void *pa_ctx)
+{
+ struct pkinit_context *pkinit_ctx = pa_ctx;
+
+ pkinit_ctx->win2k = 1;
+ pkinit_ctx->used_pkinit = 0;
+
+ if (ctx->pk_init_ctx == NULL)
+ return HEIM_ERR_PA_CANT_CONTINUE;
+
+ return 0;
+}
+
+static krb5_error_code
+pkinit_step(krb5_context context, krb5_init_creds_context ctx, void *pa_ctx, PA_DATA *pa, const AS_REQ *a,
+ const AS_REP *rep, const krb5_krbhst_info *hi, METHOD_DATA *in_md, METHOD_DATA *out_md)
+{
+ krb5_error_code ret = HEIM_ERR_PA_CANT_CONTINUE;
+ struct pkinit_context *pkinit_ctx = pa_ctx;
+
+ if (rep == NULL) {
+ if (pkinit_ctx->used_pkinit) {
+ krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
+ "Already tried PKINIT(%s), looping",
+ pkinit_ctx->win2k ? "win2k" : "ietf");
+ } else {
+ ret = pa_data_to_md_pkinit(context, a, ctx->cred.client,
+ (pkinit_ctx->win2k != 0),
+ ctx, out_md);
+ if (ret == 0)
+ ret = HEIM_ERR_PA_CONTINUE_NEEDED;
+
+ pkinit_ctx->used_pkinit = 1;
+ }
+ } else if (pa) {
+ ret = _krb5_pk_rd_pa_reply(context,
+ a->req_body.realm,
+ ctx->pk_init_ctx,
+ rep->enc_part.etype,
+ hi,
+ ctx->pk_nonce,
+ &ctx->req_buffer,
+ pa,
+ &ctx->fast_state.reply_key);
+ if (ret == 0)
+ ctx->runflags.allow_save_as_reply_key = 1;
+ }
+
+ return ret;
+}
+
+static void
+pkinit_release(void *pa_ctx)
+{
+}
+
+/*
+ * GSS-API pre-authentication support
+ */
+
+struct pa_gss_context {
+ struct gss_ctx_id_t_desc_struct *context_handle;
+ int open;
+};
+
+static krb5_error_code
+pa_gss_configure(krb5_context context,
+ krb5_init_creds_context ctx,
+ void *pa_ctx)
+{
+ krb5_gss_init_ctx gssic = ctx->gss_init_ctx;
+ struct pa_gss_context *pa_gss_ctx = pa_ctx;
+
+ if (gssic == NULL)
+ return HEIM_ERR_PA_CANT_CONTINUE;
+
+ pa_gss_ctx->context_handle = NULL;
+ pa_gss_ctx->open = 0;
+
+ return 0;
+}
+
+static krb5_error_code
+pa_data_to_md_gss(krb5_context context,
+ const AS_REQ *a,
+ const krb5_creds *creds,
+ krb5_init_creds_context ctx,
+ struct pa_gss_context *pa_gss_ctx,
+ PA_DATA *pa,
+ METHOD_DATA *out_md)
+{
+ krb5_error_code ret;
+ krb5_gss_init_ctx gssic = ctx->gss_init_ctx;
+ krb5_data req_body;
+ krb5_data *input_token, output_token;
+ size_t len = 0;
+
+ krb5_data_zero(&req_body);
+ krb5_data_zero(&output_token);
+
+ input_token = pa ? &pa->padata_value : NULL;
+
+ if ((input_token == NULL || input_token->length == 0) &&
+ pa_gss_ctx->context_handle) {
+ krb5_set_error_message(context, HEIM_ERR_PA_CANT_CONTINUE,
+ "Missing GSS preauthentication data from KDC");
+ return HEIM_ERR_PA_CANT_CONTINUE;
+ }
+
+ ASN1_MALLOC_ENCODE(KDC_REQ_BODY, req_body.data, req_body.length,
+ &ctx->as_req.req_body, &len, ret);
+ if (ret)
+ goto out;
+ heim_assert(req_body.length == len, "ASN.1 internal error");
+
+ ret = gssic->step(context, gssic, creds, &pa_gss_ctx->context_handle,
+ ctx->flags, &req_body,
+ input_token, &output_token);
+
+ /*
+ * If FAST authenticated the KDC (which will be the case unless anonymous
+ * PKINIT was used without KDC certificate validation) then we can relax
+ * the mutual authentication requirement.
+ */
+ if (ret == KRB5_MUTUAL_FAILED &&
+ (ctx->fast_state.flags & KRB5_FAST_EXPECTED) &&
+ (ctx->fast_state.flags & KRB5_FAST_KDC_VERIFIED))
+ ret = 0;
+ if (ret == 0) {
+ /*
+ * Always require a strengthen key if FAST was used, to avoid a MITM
+ * attack that could result in unintended privilege escalation should
+ * the KDC add positive authorization data from the armor ticket.
+ */
+ if ((ctx->fast_state.flags & KRB5_FAST_EXPECTED) &&
+ ctx->fast_state.strengthen_key == NULL) {
+ krb5_set_error_message(context, HEIM_ERR_PA_CANT_CONTINUE,
+ "FAST GSS pre-authentication without strengthen key");
+ ret = KRB5_KDCREP_MODIFIED;
+ goto out;
+ }
+
+ pa_gss_ctx->open = 1;
+ }
+
+ if (output_token.length) {
+ ret = krb5_padata_add(context, out_md, KRB5_PADATA_GSS,
+ output_token.data, output_token.length);
+ if (ret)
+ goto out;
+
+ krb5_data_zero(&output_token);
+ }
+
+out:
+ krb5_data_free(&output_token);
+ krb5_data_free(&req_body);
+
+ return ret;
+}
+
+static krb5_error_code
+pa_gss_step(krb5_context context,
+ krb5_init_creds_context ctx,
+ void *pa_ctx,
+ PA_DATA *pa,
+ const AS_REQ *a,
+ const AS_REP *rep,
+ const krb5_krbhst_info *hi,
+ METHOD_DATA *in_md,
+ METHOD_DATA *out_md)
+{
+ krb5_error_code ret;
+ krb5_principal cname;
+ krb5_gss_init_ctx gssic = ctx->gss_init_ctx;
+ struct pa_gss_context *pa_gss_ctx = pa_ctx;
+
+ heim_assert(gssic != NULL, "invalid context passed to pa_gss_step");
+
+ if (!pa_gss_ctx->open) {
+ ret = pa_data_to_md_gss(context, a, &ctx->cred, ctx,
+ pa_gss_ctx, pa, out_md);
+ if (ret == HEIM_ERR_PA_CONTINUE_NEEDED && rep) {
+ krb5_set_error_message(context, KRB5_PREAUTH_FAILED,
+ "KDC sent AS-REP before GSS "
+ "pre-authentication completed");
+ ret = KRB5_KDCREP_MODIFIED;
+ } else if (ret == 0 && rep == NULL) {
+ ret = HEIM_ERR_PA_CONTINUE_NEEDED; /* odd number of legs */
+ }
+ if (ret)
+ return ret;
+ } else if (pa && pa->padata_value.length) {
+ krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
+ "Already completed GSS pre-authentication");
+ return KRB5_GET_IN_TKT_LOOP;
+ } else if (rep == NULL) {
+ krb5_set_error_message(context, KRB5_PREAUTH_FAILED,
+ "Completed GSS pre-authentication before KDC");
+ return KRB5_PREAUTH_FAILED;
+ }
+
+ heim_assert(pa_gss_ctx->open,
+ "GSS pre-authentication incomplete");
+
+ ret = gssic->finish(context, gssic, &ctx->cred,
+ pa_gss_ctx->context_handle, ctx->nonce,
+ rep->enc_part.etype, &cname,
+ &ctx->fast_state.reply_key);
+ if (ret)
+ return ret;
+
+ {
+ char *from = NULL;
+ char *to = NULL;
+
+ if (krb5_unparse_name(context, ctx->cred.client, &from) == 0) {
+ if (krb5_unparse_name(context, cname, &to) == 0) {
+ _krb5_debug(context, 1, "pa_gss_step: %s as %s",
+ from, to);
+ krb5_xfree(to);
+ }
+ krb5_xfree(from);
+ }
+ }
+
+ if (krb5_principal_is_federated(context, ctx->cred.client)) {
+ /*
+ * The well-known federated name will be replaced with the cname
+ * in the AS-REP, but save the locally mapped initiator name in the
+ * cred for logging.
+ */
+ krb5_free_principal(context, ctx->cred.client);
+ ctx->cred.client = cname;
+
+ ctx->ic_flags |= KRB5_INIT_CREDS_NO_C_CANON_CHECK;
+ } else {
+ krb5_free_principal(context, cname);
+ }
+
+ ctx->runflags.allow_save_as_reply_key = 1;
+
+ gssic->delete_sec_context(context, gssic, pa_gss_ctx->context_handle);
+ pa_gss_ctx->context_handle = NULL;
+ pa_gss_ctx->open = 0;
+
+ return 0;
+}
+
+static krb5_error_code
+pa_gss_restart(krb5_context context,
+ krb5_init_creds_context ctx,
+ void *pa_ctx)
+{
+ krb5_gss_init_ctx gssic = ctx->gss_init_ctx;
+ struct pa_gss_context *pa_gss_ctx = pa_ctx;
+
+ if (gssic == NULL)
+ return HEIM_ERR_PA_CANT_CONTINUE;
+
+ gssic->delete_sec_context(context, gssic, pa_gss_ctx->context_handle);
+ pa_gss_ctx->context_handle = NULL;
+ pa_gss_ctx->open = 0;
+
+ return 0;
+}
+
+static void
+pa_gss_release(void *pa_ctx)
+{
+}
+
+krb5_error_code
+_krb5_make_pa_enc_challenge(krb5_context context,
+ krb5_crypto crypto,
+ krb5_key_usage usage,
+ METHOD_DATA *md)
+{
+ PA_ENC_TS_ENC p;
+ unsigned char *buf;
+ size_t buf_size;
+ size_t len = 0;
+ EncryptedData encdata;
+ krb5_error_code ret;
+ int32_t usec;
+ int usec2;
+
+ krb5_us_timeofday (context, &p.patimestamp, &usec);
+ usec2 = usec;
+ p.pausec = &usec2;
+
+ ASN1_MALLOC_ENCODE(PA_ENC_TS_ENC, buf, buf_size, &p, &len, ret);
+ if (ret)
+ return ret;
+ if(buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ ret = krb5_encrypt_EncryptedData(context,
+ crypto,
+ usage,
+ buf,
+ len,
+ 0,
+ &encdata);
+ free(buf);
+ if (ret)
+ return ret;
+
+ ASN1_MALLOC_ENCODE(EncryptedData, buf, buf_size, &encdata, &len, ret);
+ free_EncryptedData(&encdata);
+ if (ret)
+ return ret;
+ if(buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ ret = krb5_padata_add(context, md, KRB5_PADATA_ENCRYPTED_CHALLENGE, buf, len);
+ if (ret)
+ free(buf);
+ return ret;
+}
+
+krb5_error_code
+_krb5_validate_pa_enc_challenge(krb5_context context,
+ krb5_crypto crypto,
+ krb5_key_usage usage,
+ EncryptedData *enc_data,
+ const char *peer_name)
+{
+ krb5_error_code ret;
+ krb5_data ts_data;
+ PA_ENC_TS_ENC p;
+ time_t timestamp;
+ int32_t usec;
+ size_t size;
+
+ ret = krb5_decrypt_EncryptedData(context, crypto, usage, enc_data, &ts_data);
+ if (ret)
+ return ret;
+
+ ret = decode_PA_ENC_TS_ENC(ts_data.data,
+ ts_data.length,
+ &p,
+ &size);
+ krb5_data_free(&ts_data);
+ if(ret){
+ ret = KRB5KDC_ERR_PREAUTH_FAILED;
+ _krb5_debug(context, 5, "Failed to decode PA-ENC-TS_ENC -- %s", peer_name);
+ goto out;
+ }
+
+ krb5_us_timeofday(context, &timestamp, &usec);
+
+ if (krb5_time_abs(timestamp, p.patimestamp) > context->max_skew) {
+ char client_time[100];
+
+ krb5_format_time(context, p.patimestamp,
+ client_time, sizeof(client_time), TRUE);
+
+ ret = KRB5KRB_AP_ERR_SKEW;
+ _krb5_debug(context, 0, "Too large time skew, "
+ "client time %s is out by %u > %d seconds -- %s",
+ client_time,
+ (unsigned)krb5_time_abs(timestamp, p.patimestamp),
+ (int)context->max_skew,
+ peer_name);
+ } else {
+ ret = 0;
+ }
+
+ out:
+ free_PA_ENC_TS_ENC(&p);
+
+ return ret;
+}
+
+
+static struct pa_info_data *
+process_pa_info(krb5_context, const krb5_principal, const AS_REQ *, struct pa_info_data *, METHOD_DATA *);
+
+
+static krb5_error_code
+enc_chal_step(krb5_context context, krb5_init_creds_context ctx, void *pa_ctx, PA_DATA *pa, const AS_REQ *a,
+ const AS_REP *rep, const krb5_krbhst_info *hi, METHOD_DATA *in_md, METHOD_DATA *out_md)
+{
+ struct pa_info_data paid, *ppaid;
+ krb5_keyblock challengekey;
+ krb5_data pepper1, pepper2;
+ krb5_crypto crypto = NULL;
+ krb5_enctype aenctype;
+ krb5_error_code ret;
+
+ memset(&paid, 0, sizeof(paid));
+
+ if (rep == NULL)
+ paid.etype = KRB5_ENCTYPE_NULL;
+ else
+ paid.etype = rep->enc_part.etype;
+ ppaid = process_pa_info(context, ctx->cred.client, a, &paid, in_md);
+
+ /*
+ * If we don't have ppaid, ts because the KDC have not sent any
+ * salt info, lets to the first roundtrip so the KDC have a chance
+ * to send any.
+ */
+ if (ppaid == NULL) {
+ _krb5_debug(context, 5, "no ppaid found");
+ return HEIM_ERR_PA_CONTINUE_NEEDED;
+ }
+ if (ppaid->etype == KRB5_ENCTYPE_NULL) {
+ return HEIM_ERR_PA_CANT_CONTINUE;
+ }
+
+ if (ctx->fast_state.reply_key)
+ krb5_free_keyblock(context, ctx->fast_state.reply_key);
+
+ ret = pa_data_to_key_plain(context, ctx->cred.client, ctx,
+ ppaid->salt, ppaid->s2kparams, ppaid->etype,
+ &ctx->fast_state.reply_key);
+ free_paid(context, &paid);
+ if (ret) {
+ _krb5_debug(context, 5, "enc-chal: failed to build key");
+ return ret;
+ }
+
+ ret = krb5_crypto_init(context, ctx->fast_state.reply_key, 0, &crypto);
+ if (ret)
+ return ret;
+
+ krb5_crypto_getenctype(context, ctx->fast_state.armor_crypto, &aenctype);
+
+ pepper1.data = rep ? "kdcchallengearmor" : "clientchallengearmor";
+ pepper1.length = strlen(pepper1.data);
+ pepper2.data = "challengelongterm";
+ pepper2.length = strlen(pepper2.data);
+
+ ret = krb5_crypto_fx_cf2(context, ctx->fast_state.armor_crypto, crypto,
+ &pepper1, &pepper2, aenctype,
+ &challengekey);
+ krb5_crypto_destroy(context, crypto);
+ if (ret)
+ return ret;
+
+ ret = krb5_crypto_init(context, &challengekey, 0, &crypto);
+ krb5_free_keyblock_contents(context, &challengekey);
+ if (ret)
+ return ret;
+
+ if (rep) {
+ EncryptedData enc_data;
+ size_t size;
+
+ _krb5_debug(context, 5, "ENC_CHAL rep key");
+
+ if (ctx->fast_state.strengthen_key == NULL) {
+ krb5_crypto_destroy(context, crypto);
+ _krb5_debug(context, 5, "ENC_CHAL w/o strengthen_key");
+ return KRB5_KDCREP_MODIFIED;
+ }
+
+ if (pa == NULL) {
+ krb5_crypto_destroy(context, crypto);
+ _krb5_debug(context, 0, "KDC response missing");
+ return HEIM_ERR_PA_CANT_CONTINUE;
+ }
+
+ ret = decode_EncryptedData(pa->padata_value.data,
+ pa->padata_value.length,
+ &enc_data,
+ &size);
+ if (ret) {
+ ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
+ _krb5_debug(context, 5, "Failed to decode ENC_CHAL KDC reply");
+ return ret;
+ }
+
+ ret = _krb5_validate_pa_enc_challenge(context, crypto,
+ KRB5_KU_ENC_CHALLENGE_KDC,
+ &enc_data,
+ "KDC");
+ free_EncryptedData(&enc_data);
+ krb5_crypto_destroy(context, crypto);
+
+ return ret;
+
+ } else {
+
+ ret = _krb5_make_pa_enc_challenge(context, crypto,
+ KRB5_KU_ENC_CHALLENGE_CLIENT,
+ out_md);
+ krb5_crypto_destroy(context, crypto);
+ if (ret) {
+ _krb5_debug(context, 5, "enc-chal: failed build enc challenge");
+ return ret;
+ }
+
+ return HEIM_ERR_PA_CONTINUE_NEEDED;
+ }
+}
+
+struct enc_ts_context {
+ int used_pa_types;
+#define USED_ENC_TS_GUESS 4
+#define USED_ENC_TS_INFO 8
+#define USED_ENC_TS_RENEG 16
+ krb5_principal user;
+};
+
+static krb5_error_code
+enc_ts_restart(krb5_context context, krb5_init_creds_context ctx, void *pa_ctx)
+{
+ struct enc_ts_context *pactx = (struct enc_ts_context *)pa_ctx;
+ pactx->used_pa_types = 0;
+ krb5_free_principal(context, pactx->user);
+ pactx->user = NULL;
+ return 0;
+}
+
+static krb5_error_code
+enc_ts_step(krb5_context context, krb5_init_creds_context ctx, void *pa_ctx, PA_DATA *pa,
+ const AS_REQ *a,
+ const AS_REP *rep,
+ const krb5_krbhst_info *hi,
+ METHOD_DATA *in_md, METHOD_DATA *out_md)
+{
+ struct enc_ts_context *pactx = (struct enc_ts_context *)pa_ctx;
+ struct pa_info_data paid, *ppaid;
+ krb5_error_code ret;
+ const char *state;
+ unsigned flag;
+
+ /*
+ * Keep track of the user we used so that we can restart
+ * authentication when we get referrals.
+ */
+
+ if (pactx->user && !krb5_principal_compare(context, pactx->user, ctx->cred.client)) {
+ pactx->used_pa_types = 0;
+ krb5_free_principal(context, pactx->user);
+ pactx->user = NULL;
+ }
+
+ if (pactx->user == NULL) {
+ ret = krb5_copy_principal(context, ctx->cred.client, &pactx->user);
+ if (ret)
+ return ret;
+ }
+
+ memset(&paid, 0, sizeof(paid));
+
+ if (rep == NULL)
+ paid.etype = KRB5_ENCTYPE_NULL;
+ else
+ paid.etype = rep->enc_part.etype;
+
+ ppaid = process_pa_info(context, ctx->cred.client, a, &paid, in_md);
+
+ if (rep) {
+ /*
+ * Some KDC's don't send salt info in the reply when there is
+ * success pre-auth happned before, so use cached copy (or
+ * even better, if there is just one pre-auth, save reply-key).
+ */
+ if (ppaid == NULL && ctx->paid.etype != KRB5_ENCTYPE_NULL) {
+ ppaid = &ctx->paid;
+
+ } else if (ppaid == NULL) {
+ _krb5_debug(context, 0, "no paid when building key, build a default salt structure ?");
+ return HEIM_ERR_PA_CANT_CONTINUE;
+ }
+
+ ret = pa_data_to_key_plain(context, ctx->cred.client, ctx,
+ ppaid->salt, ppaid->s2kparams, rep->enc_part.etype,
+ &ctx->fast_state.reply_key);
+ free_paid(context, &paid);
+ return ret;
+ }
+
+ /*
+ * If we don't have ppaid, ts because the KDC have not sent any
+ * salt info, lets to the first roundtrip so the KDC have a chance
+ * to send any.
+ *
+ * Don't bother guessing, it sounds like a good idea until you run
+ * into KDCs that are doing failed auth counting based on the
+ * ENC_TS tries.
+ *
+ * Stashing the salt for the next run is a diffrent issue and
+ * could be considered in the future.
+ */
+
+ if (ppaid == NULL) {
+ _krb5_debug(context, 5,
+ "TS-ENC: waiting for KDC to set pw-salt/etype_info{,2}");
+ return HEIM_ERR_PA_CONTINUE_NEEDED;
+ }
+ if (ppaid->etype == KRB5_ENCTYPE_NULL) {
+ free_paid(context, &paid);
+ _krb5_debug(context, 5,
+ "TS-ENC: kdc proposes enctype NULL ?");
+ return HEIM_ERR_PA_CANT_CONTINUE;
+ }
+
+ /*
+ * We have to allow the KDC to re-negotiate the PA-TS data
+ * once, this is since the in the case of a windows read only
+ * KDC that doesn't have the keys simply guesses what the
+ * master is supposed to support. In the case where this
+ * breaks in when the RO-KDC is a newer version the the RW-KDC
+ * and the RO-KDC announced a enctype that the older doesn't
+ * support.
+ */
+ if (pactx->used_pa_types & USED_ENC_TS_INFO) {
+ flag = USED_ENC_TS_RENEG;
+ state = "reneg";
+ } else {
+ flag = USED_ENC_TS_INFO;
+ state = "info";
+ }
+
+ if (pactx->used_pa_types & flag) {
+ free_paid(context, &paid);
+ krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
+ "Already tried ENC-TS-%s, looping", state);
+ return KRB5_GET_IN_TKT_LOOP;
+ }
+
+ pactx->used_pa_types |= flag;
+
+ free_paid(context, &ctx->paid);
+ ctx->paid = *ppaid;
+
+ ret = pa_data_to_md_ts_enc(context, a, ctx->cred.client, ctx, ppaid, out_md);
+ if (ret)
+ return ret;
+
+ return HEIM_ERR_PA_CONTINUE_NEEDED;
+}
+
+static void
+enc_ts_release(void *pa_ctx)
+{
+ struct enc_ts_context *pactx = (struct enc_ts_context *)pa_ctx;
+
+ if (pactx->user)
+ krb5_free_principal(NULL, pactx->user);
+}
+
+static krb5_error_code
+pa_pac_step(krb5_context context, krb5_init_creds_context ctx, void *pa_ctx, PA_DATA *pa, const AS_REQ *a,
+ const AS_REP *rep, const krb5_krbhst_info *hi,
+ METHOD_DATA *in_md, METHOD_DATA *out_md)
+{
+ size_t len = 0, length;
+ krb5_error_code ret;
+ PA_PAC_REQUEST req;
+ void *buf;
+
+ switch (ctx->req_pac) {
+ case KRB5_INIT_CREDS_TRISTATE_UNSET:
+ return 0; /* don't bother */
+ case KRB5_INIT_CREDS_TRISTATE_TRUE:
+ req.include_pac = 1;
+ break;
+ case KRB5_INIT_CREDS_TRISTATE_FALSE:
+ req.include_pac = 0;
+ }
+
+ ASN1_MALLOC_ENCODE(PA_PAC_REQUEST, buf, length,
+ &req, &len, ret);
+ if (ret)
+ return ret;
+ heim_assert(len == length, "internal error in ASN.1 encoder");
+
+ ret = krb5_padata_add(context, out_md, KRB5_PADATA_PA_PAC_REQUEST, buf, len);
+ if (ret)
+ free(buf);
+
+ return 0;
+}
+
+static krb5_error_code
+pa_enc_pa_rep_step(krb5_context context, krb5_init_creds_context ctx, void *pa_ctx, PA_DATA *pa, const AS_REQ *a,
+ const AS_REP *rep, const krb5_krbhst_info *hi,
+ METHOD_DATA *in_md, METHOD_DATA *out_md)
+{
+ if (ctx->runflags.allow_enc_pa_rep)
+ return krb5_padata_add(context, out_md, KRB5_PADATA_REQ_ENC_PA_REP, NULL, 0);
+
+ return 0;
+}
+
+static krb5_error_code
+pa_fx_cookie_step(krb5_context context,
+ krb5_init_creds_context ctx,
+ void *pa_ctx,
+ PA_DATA *pa,
+ const AS_REQ *a,
+ const AS_REP *rep,
+ const krb5_krbhst_info *hi,
+ METHOD_DATA *in_md,
+ METHOD_DATA *out_md)
+{
+ krb5_error_code ret;
+ void *cookie;
+ PA_DATA *pad;
+ int idx = 0;
+
+ pad = krb5_find_padata(in_md->val, in_md->len, KRB5_PADATA_FX_COOKIE, &idx);
+ if (pad == NULL) {
+ /*
+ * RFC 6113 5.4.3: PA-FX-COOKIE MUST be included if the KDC
+ * expects at least one more message from the client.
+ */
+ if (ctx->error.error_code == KRB5_KDC_ERR_MORE_PREAUTH_DATA_REQUIRED)
+ return KRB5_PREAUTH_FAILED;
+ else
+ return 0;
+ }
+
+ cookie = malloc(pad->padata_value.length);
+ if (cookie == NULL)
+ return krb5_enomem(context);
+
+ memcpy(cookie, pad->padata_value.data, pad->padata_value.length);
+
+ ret = krb5_padata_add(context, out_md, KRB5_PADATA_FX_COOKIE,
+ cookie, pad->padata_value.length);
+ if (ret)
+ free(cookie);
+ else
+ _krb5_debug(context, 5, "Mirrored FX-COOKIE to KDC");
+
+ return ret;
+}
+
+typedef struct pa_info_data *(*pa_salt_info_f)(krb5_context, const krb5_principal, const AS_REQ *, struct pa_info_data *, heim_octet_string *);
+typedef krb5_error_code (*pa_configure_f)(krb5_context, krb5_init_creds_context, void *);
+typedef krb5_error_code (*pa_restart_f)(krb5_context, krb5_init_creds_context, void *);
+typedef krb5_error_code (*pa_step_f)(krb5_context, krb5_init_creds_context, void *, PA_DATA *, const AS_REQ *, const AS_REP *, const krb5_krbhst_info *, METHOD_DATA *, METHOD_DATA *);
+typedef void (*pa_release_f)(void *);
+
+struct patype {
+ int type;
+ char *name;
+ int flags;
+#define PA_F_ANNOUNCE 1
+#define PA_F_CONFIG 2
+#define PA_F_FAST 4 /* available inside FAST */
+#define PA_F_NOT_FAST 8 /* only available without FAST */
+ size_t pa_ctx_size;
+ pa_salt_info_f salt_info;
+ /**
+ * Return 0 if the PA-mechanism is available and optionally set pa_ctx pointer to non-NULL.
+ */
+ pa_configure_f configure;
+ /**
+ * Return 0 if the PA-mechanism can be restarted (time skew, referrals, etc)
+ */
+ pa_restart_f restart;
+ /**
+ * Return 0 if the when complete, HEIM_ERR_PA_CONTINUE_NEEDED if more steps are require
+ */
+ pa_step_f step;
+ pa_release_f release;
+} patypes[] = {
+ {
+ KRB5_PADATA_PK_AS_REP,
+ "PKINIT(IETF)",
+ PA_F_FAST | PA_F_NOT_FAST,
+ sizeof(struct pkinit_context),
+ NULL,
+ pkinit_configure_ietf,
+ NULL,
+ pkinit_step,
+ pkinit_release
+ },
+ {
+ KRB5_PADATA_PK_AS_REP_19,
+ "PKINIT(win)",
+ PA_F_FAST | PA_F_NOT_FAST,
+ sizeof(struct pkinit_context),
+ NULL,
+ pkinit_configure_win,
+ NULL,
+ pkinit_step,
+ pkinit_release
+ },
+ {
+ KRB5_PADATA_GSS,
+ "GSS",
+ PA_F_FAST | PA_F_NOT_FAST,
+ sizeof(struct pa_gss_context),
+ NULL,
+ pa_gss_configure,
+ pa_gss_restart,
+ pa_gss_step,
+ pa_gss_release
+ },
+ {
+ KRB5_PADATA_ENCRYPTED_CHALLENGE,
+ "ENCRYPTED_CHALLENGE",
+ PA_F_FAST,
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ enc_chal_step,
+ NULL
+ },
+ {
+ KRB5_PADATA_ENC_TIMESTAMP,
+ "ENCRYPTED_TIMESTAMP",
+ PA_F_NOT_FAST,
+ sizeof(struct enc_ts_context),
+ NULL,
+ NULL,
+ enc_ts_restart,
+ enc_ts_step,
+ enc_ts_release
+ },
+ {
+ KRB5_PADATA_PA_PAC_REQUEST,
+ "PA_PAC_REQUEST",
+ PA_F_CONFIG,
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ pa_pac_step,
+ NULL
+ },
+ {
+ KRB5_PADATA_REQ_ENC_PA_REP,
+ "REQ-ENC-PA-REP",
+ PA_F_CONFIG,
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ pa_enc_pa_rep_step,
+ NULL
+ },
+ {
+ KRB5_PADATA_FX_COOKIE,
+ "FX-COOKIE",
+ PA_F_CONFIG,
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ pa_fx_cookie_step,
+ NULL
+ },
+#define patype_salt(n, f) { KRB5_PADATA_##n, #n, 0, 0, f, NULL, NULL, NULL, NULL }
+ patype_salt(ETYPE_INFO2, pa_etype_info2),
+ patype_salt(ETYPE_INFO, pa_etype_info),
+ patype_salt(PW_SALT, pa_pw_or_afs3_salt),
+ patype_salt(AFS3_SALT, pa_pw_or_afs3_salt),
+#undef patype_salt
+ /* below are just for pretty printing */
+#define patype_info(n) { KRB5_PADATA_##n, #n, 0, 0, NULL, NULL, NULL, NULL, NULL }
+ patype_info(AUTHENTICATION_SET),
+ patype_info(AUTH_SET_SELECTED),
+ patype_info(FX_FAST),
+ patype_info(FX_ERROR),
+ patype_info(PKINIT_KX),
+ patype_info(PK_AS_REQ)
+#undef patype_info
+};
+
+static const char *
+get_pa_type_name(int type)
+{
+ size_t n;
+ for (n = 0; n < sizeof(patypes)/sizeof(patypes[0]); n++)
+ if (type == patypes[n].type)
+ return patypes[n].name;
+ return "unknown";
+}
+
+/*
+ *
+ */
+
+struct pa_auth_mech {
+ struct patype *patype;
+ struct pa_auth_mech *next; /* when doing authentication sets */
+ char pactx[1];
+};
+
+/*
+ *
+ */
+
+static struct pa_info_data *
+process_pa_info(krb5_context context,
+ const krb5_principal client,
+ const AS_REQ *asreq,
+ struct pa_info_data *paid,
+ METHOD_DATA *md)
+{
+ struct pa_info_data *p = NULL;
+ PA_DATA *pa;
+ size_t i;
+
+ if (md == NULL)
+ return NULL;
+
+ for (i = 0; p == NULL && i < sizeof(patypes)/sizeof(patypes[0]); i++) {
+ int idx = 0;
+
+ if (patypes[i].salt_info == NULL)
+ continue;
+
+ pa = krb5_find_padata(md->val, md->len, patypes[i].type, &idx);
+ if (pa == NULL)
+ continue;
+
+ paid->salt.salttype = (krb5_salttype)patypes[i].type;
+ p = patypes[i].salt_info(context, client, asreq, paid, &pa->padata_value);
+ }
+ return p;
+}
+
+static krb5_error_code
+pa_announce(krb5_context context,
+ int types,
+ krb5_init_creds_context ctx,
+ METHOD_DATA *in_md,
+ METHOD_DATA *out_md)
+{
+ krb5_error_code ret = 0;
+ size_t n;
+
+ for (n = 0; ret == 0 && n < sizeof(patypes)/sizeof(patypes[0]); n++) {
+ if ((patypes[n].flags & types) == 0)
+ continue;
+
+ if (patypes[n].step)
+ patypes[n].step(context, ctx, NULL, NULL, NULL, NULL, NULL, in_md, out_md);
+ else
+ ret = krb5_padata_add(context, out_md, patypes[n].type, NULL, 0);
+ }
+ return ret;
+}
+
+
+static void HEIM_CALLCONV
+mech_dealloc(void *ctx)
+{
+ struct pa_auth_mech *pa_mech = ctx;
+ if (pa_mech->patype->release)
+ pa_mech->patype->release((void *)&pa_mech->pactx[0]);
+}
+
+struct heim_type_data pa_auth_mech_object = {
+ HEIM_TID_PA_AUTH_MECH,
+ "heim-pa-mech-context",
+ NULL,
+ mech_dealloc,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+static struct pa_auth_mech *
+pa_mech_create(krb5_context context, krb5_init_creds_context ctx, int pa_type)
+{
+ struct pa_auth_mech *pa_mech;
+ struct patype *patype = NULL;
+ size_t n;
+
+ for (n = 0; patype == NULL && n < sizeof(patypes)/sizeof(patypes[0]); n++) {
+ if (patypes[n].type == pa_type)
+ patype = &patypes[n];
+ }
+ if (patype == NULL)
+ return NULL;
+
+ pa_mech = _heim_alloc_object(&pa_auth_mech_object, sizeof(*pa_mech) - 1 + patype->pa_ctx_size);
+ if (pa_mech == NULL)
+ return NULL;
+
+ pa_mech->patype = patype;
+
+ if (pa_mech->patype->configure) {
+ krb5_error_code ret;
+
+ ret = pa_mech->patype->configure(context, ctx, &pa_mech->pactx[0]);
+ if (ret) {
+ heim_release(pa_mech);
+ return NULL;
+ }
+ }
+
+ _krb5_debug(context, 5, "Adding PA mech: %s", patype->name);
+
+ return pa_mech;
+}
+
+static void
+pa_mech_add(krb5_context context, krb5_init_creds_context ctx, int pa_type)
+{
+ struct pa_auth_mech *mech;
+
+ mech = pa_mech_create(context, ctx, pa_type);
+ if (mech) {
+ heim_array_append_value(ctx->available_pa_mechs, mech);
+ heim_release(mech);
+ }
+}
+
+static krb5_error_code
+pa_configure(krb5_context context,
+ krb5_init_creds_context ctx,
+ METHOD_DATA *in_md)
+{
+ ctx->available_pa_mechs = heim_array_create();
+
+ if (ctx->gss_init_ctx) {
+ pa_mech_add(context, ctx, KRB5_PADATA_GSS);
+ } else if (ctx->pk_init_ctx) {
+ pa_mech_add(context, ctx, KRB5_PADATA_PK_AS_REP);
+ pa_mech_add(context, ctx, KRB5_PADATA_PK_AS_REP_19);
+ } else if (ctx->keyproc || ctx->keyseed || ctx->prompter) {
+ pa_mech_add(context, ctx, KRB5_PADATA_ENCRYPTED_CHALLENGE);
+ pa_mech_add(context, ctx, KRB5_PADATA_ENC_TIMESTAMP);
+ }
+ /* XXX setup context based on KDC reply */
+
+ return 0;
+}
+
+static krb5_error_code
+pa_restart(krb5_context context,
+ krb5_init_creds_context ctx)
+{
+ krb5_error_code ret = HEIM_ERR_PA_CANT_CONTINUE;
+
+ if (ctx->pa_mech && ctx->pa_mech->patype->restart)
+ ret = ctx->pa_mech->patype->restart(context, ctx, (void *)&ctx->pa_mech->pactx[0]);
+
+ return ret;
+}
+
+
+static krb5_error_code
+pa_step(krb5_context context,
+ krb5_init_creds_context ctx,
+ const AS_REQ *a,
+ const AS_REP *rep,
+ const krb5_krbhst_info *hi,
+ METHOD_DATA *in_md,
+ METHOD_DATA *out_md)
+{
+ krb5_error_code ret;
+ PA_DATA *pa = NULL;
+ int idx;
+
+ next:
+ do {
+ if (ctx->pa_mech == NULL) {
+ size_t len = heim_array_get_length(ctx->available_pa_mechs);
+ if (len == 0) {
+ _krb5_debug(context, 0, "no more available_pa_mechs to try");
+ return HEIM_ERR_NO_MORE_PA_MECHS;
+ }
+
+ ctx->pa_mech = heim_array_copy_value(ctx->available_pa_mechs, 0);
+ heim_array_delete_value(ctx->available_pa_mechs, 0);
+ }
+
+ if (ctx->fast_state.armor_crypto) {
+ if ((ctx->pa_mech->patype->flags & PA_F_FAST) == 0) {
+ _krb5_debug(context, 0, "pa-mech %s dropped under FAST (not supported)",
+ ctx->pa_mech->patype->name);
+ heim_release(ctx->pa_mech);
+ ctx->pa_mech = NULL;
+ continue;
+ }
+ } else {
+ if ((ctx->pa_mech->patype->flags & PA_F_NOT_FAST) == 0) {
+ _krb5_debug(context, 0, "dropped pa-mech %s since not running under FAST",
+ ctx->pa_mech->patype->name);
+ heim_release(ctx->pa_mech);
+ ctx->pa_mech = NULL;
+ continue;
+ }
+ }
+
+ _krb5_debug(context, 0, "pa-mech trying: %s, searching for %d",
+ ctx->pa_mech->patype->name, ctx->pa_mech->patype->type);
+
+ idx = 0;
+ if (in_md)
+ pa = krb5_find_padata(in_md->val, in_md->len, ctx->pa_mech->patype->type, &idx);
+ else
+ pa = NULL;
+
+ } while (ctx->pa_mech == NULL);
+
+ _krb5_debug(context, 5, "Stepping pa-mech: %s", ctx->pa_mech->patype->name);
+
+ ret = ctx->pa_mech->patype->step(context, ctx, (void *)&ctx->pa_mech->pactx[0], pa, a, rep, hi, in_md, out_md);
+ _krb5_debug(context, 10, "PA type %s returned %d", ctx->pa_mech->patype->name, ret);
+ if (ret == 0) {
+ struct pa_auth_mech *next_pa = ctx->pa_mech->next;
+
+ if (next_pa) {
+ _krb5_debug(context, 5, "Next PA type in set is: %s",
+ next_pa->patype->name);
+ ret = HEIM_ERR_PA_CONTINUE_NEEDED;
+ } else if (rep == NULL) {
+ _krb5_debug(context, 5, "PA %s done, but no ticket in sight!!!",
+ ctx->pa_mech->patype->name);
+ ret = HEIM_ERR_PA_CANT_CONTINUE;
+ } else {
+ ctx->pa_used = ctx->pa_mech->patype->name;
+ }
+
+ heim_retain(next_pa);
+ heim_release(ctx->pa_mech);
+ ctx->pa_mech = next_pa;
+ }
+
+ if (ret == HEIM_ERR_PA_CANT_CONTINUE) {
+ if (ctx->pa_mech) {
+ _krb5_debug(context, 5, "Dropping PA type %s", ctx->pa_mech->patype->name);
+ heim_release(ctx->pa_mech);
+ ctx->pa_mech = NULL;
+ }
+ goto next;
+ } else if (ret == HEIM_ERR_PA_CONTINUE_NEEDED) {
+ _krb5_debug(context, 5, "Continue needed for %s", ctx->pa_mech->patype->name);
+ } else if (ret != 0) {
+ _krb5_debug(context, 5, "Other error from mech %s: %d", ctx->pa_mech->patype->name, ret);
+ heim_release(ctx->pa_mech);
+ ctx->pa_mech = NULL;
+ }
+
+ return ret;
+}
+
+static void
+log_kdc_pa_types(krb5_context context, METHOD_DATA *in_md)
+{
+ if (_krb5_have_debug(context, 5)) {
+ unsigned i;
+ _krb5_debug(context, 5, "KDC sent %d patypes", in_md->len);
+ for (i = 0; i < in_md->len; i++)
+ _krb5_debug(context, 5, "KDC sent PA-DATA type: %d (%s)",
+ in_md->val[i].padata_type,
+ get_pa_type_name(in_md->val[i].padata_type));
+ }
+}
+
+/*
+ * Assumes caller always will free `out_md', even on error.
+ */
+
+static krb5_error_code
+process_pa_data_to_md(krb5_context context,
+ const krb5_creds *creds,
+ const AS_REQ *a,
+ krb5_init_creds_context ctx,
+ METHOD_DATA *in_md,
+ METHOD_DATA **out_md)
+{
+ krb5_error_code ret;
+
+ ALLOC(*out_md, 1);
+ if (*out_md == NULL) {
+ return krb5_enomem(context);
+ }
+ (*out_md)->len = 0;
+ (*out_md)->val = NULL;
+
+ log_kdc_pa_types(context, in_md);
+
+ ret = pa_step(context, ctx, a, NULL, NULL, in_md, *out_md);
+ if (ret == HEIM_ERR_PA_CONTINUE_NEEDED) {
+ _krb5_debug(context, 0, "pamech need more stepping");
+ } else if (ret == 0) {
+ _krb5_debug(context, 0, "pamech done step");
+ } else {
+ return ret;
+ }
+
+ /*
+ * Send announcement (what we support) and configuration (user
+ * introduced behavior change)
+ */
+ ret = pa_announce(context, PA_F_ANNOUNCE|PA_F_CONFIG, ctx, in_md, *out_md);
+
+ /*
+ *
+ */
+
+ if ((*out_md)->len == 0) {
+ free(*out_md);
+ *out_md = NULL;
+ }
+
+ return ret;
+}
+
+static krb5_error_code
+process_pa_data_to_key(krb5_context context,
+ krb5_init_creds_context ctx,
+ krb5_creds *creds,
+ AS_REQ *a,
+ AS_REP *rep,
+ const krb5_krbhst_info *hi,
+ krb5_keyblock **key)
+{
+ struct pa_info_data paid, *ppaid = NULL;
+ krb5_error_code ret;
+ krb5_enctype etype = rep->enc_part.etype;
+
+ memset(&paid, 0, sizeof(paid));
+
+ if (rep->padata)
+ log_kdc_pa_types(context, rep->padata);
+
+ if (rep->padata) {
+ paid.etype = etype;
+ ppaid = process_pa_info(context, creds->client, a, &paid,
+ rep->padata);
+ }
+ if (ppaid == NULL) {
+ if (ctx->paid.etype == KRB5_ENCTYPE_NULL) {
+ ctx->paid.etype = etype;
+ ctx->paid.s2kparams = NULL;
+ ret = krb5_get_pw_salt (context, creds->client, &ctx->paid.salt);
+ if (ret)
+ return ret;
+ }
+ }
+
+ ret = pa_step(context, ctx, a, rep, hi, rep->padata, NULL);
+ if (ret == HEIM_ERR_PA_CONTINUE_NEEDED) {
+ _krb5_debug(context, 0, "In final stretch and pa require more stepping ?");
+ return ret;
+ } else if (ret == 0) {
+ _krb5_debug(context, 0, "final pamech done step");
+ goto out;
+ } else {
+ return ret;
+ }
+ out:
+ free_paid(context, &paid);
+ return ret;
+}
+
+/*
+ *
+ */
+
+static krb5_error_code
+capture_lkdc_domain(krb5_context context,
+ krb5_init_creds_context ctx)
+{
+ size_t len;
+
+ len = strlen(_krb5_wellknown_lkdc);
+
+ if (ctx->kdc_hostname != NULL ||
+ strncmp(ctx->cred.client->realm, _krb5_wellknown_lkdc, len) != 0 ||
+ ctx->cred.client->realm[len] != ':')
+ return 0;
+
+ ctx->kdc_hostname = strdup(&ctx->cred.client->realm[len + 1]);
+
+ _krb5_debug(context, 5, "krb5_get_init_creds: setting LKDC hostname to: %s",
+ ctx->kdc_hostname);
+ return 0;
+}
+
+/**
+ * Start a new context to get a new initial credential.
+ *
+ * @param context A Kerberos 5 context.
+ * @param client The Kerberos principal to get the credential for, if
+ * NULL is given, the default principal is used as determined by
+ * krb5_get_default_principal().
+ * @param prompter
+ * @param prompter_data
+ * @param start_time the time the ticket should start to be valid or 0 for now.
+ * @param options a options structure, can be NULL for default options.
+ * @param rctx A new allocated free with krb5_init_creds_free().
+ *
+ * @return 0 for success or an Kerberos 5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_init(krb5_context context,
+ krb5_principal client,
+ krb5_prompter_fct prompter,
+ void *prompter_data,
+ krb5_deltat start_time,
+ krb5_get_init_creds_opt *options,
+ krb5_init_creds_context *rctx)
+{
+ krb5_init_creds_context ctx;
+ krb5_error_code ret;
+
+ *rctx = NULL;
+
+ ctx = calloc(1, sizeof(*ctx));
+ if (ctx == NULL)
+ return krb5_enomem(context);
+
+ ret = get_init_creds_common(context, client, prompter, prompter_data,
+ start_time, options, ctx);
+ if (ret) {
+ free(ctx);
+ return ret;
+ }
+
+ /* Set a new nonce. */
+ /* FIXME should generate a new nonce for each AS-REQ */
+ krb5_generate_random_block (&ctx->nonce, sizeof(ctx->nonce));
+ ctx->nonce &= 0x7fffffff;
+ /* XXX these just needs to be the same when using Windows PK-INIT */
+ ctx->pk_nonce = ctx->nonce;
+
+ ctx->prompter = prompter;
+ ctx->prompter_data = prompter_data;
+
+ /* pick up hostname from LKDC realm name */
+ ret = capture_lkdc_domain(context, ctx);
+ if (ret) {
+ free_init_creds_ctx(context, ctx);
+ return ret;
+ }
+
+ ctx->runflags.allow_enc_pa_rep = 1;
+
+ ctx->fast_state.flags |= KRB5_FAST_AS_REQ;
+
+ *rctx = ctx;
+
+ return ret;
+}
+
+/**
+ * Set the KDC hostname for the initial request, it will not be
+ * considered in referrals to another KDC.
+ *
+ * @param context a Kerberos 5 context.
+ * @param ctx a krb5_init_creds_context context.
+ * @param hostname the hostname for the KDC of realm
+ *
+ * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message().
+ * @ingroup krb5_credential
+ */
+
+krb5_error_code KRB5_LIB_FUNCTION
+krb5_init_creds_set_kdc_hostname(krb5_context context,
+ krb5_init_creds_context ctx,
+ const char *hostname)
+{
+ if (ctx->kdc_hostname)
+ free(ctx->kdc_hostname);
+ ctx->kdc_hostname = strdup(hostname);
+ if (ctx->kdc_hostname == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+/**
+ * Set the sitename for the request
+ *
+ */
+
+krb5_error_code KRB5_LIB_FUNCTION
+krb5_init_creds_set_sitename(krb5_context context,
+ krb5_init_creds_context ctx,
+ const char *sitename)
+{
+ if (ctx->sitename)
+ free(ctx->sitename);
+ ctx->sitename = strdup(sitename);
+ if (ctx->sitename == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+/**
+ * Sets the service that the is requested. This call is only neede for
+ * special initial tickets, by default the a krbtgt is fetched in the default realm.
+ *
+ * @param context a Kerberos 5 context.
+ * @param ctx a krb5_init_creds_context context.
+ * @param service the service given as a string, for example
+ * "kadmind/admin". If NULL, the default krbtgt in the clients
+ * realm is set.
+ *
+ * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message().
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_service(krb5_context context,
+ krb5_init_creds_context ctx,
+ const char *service)
+{
+ krb5_const_realm client_realm;
+ krb5_principal principal;
+ krb5_error_code ret;
+
+ client_realm = krb5_principal_get_realm (context, ctx->cred.client);
+
+ if (service) {
+ ret = krb5_parse_name (context, service, &principal);
+ if (ret)
+ return ret;
+ ret = krb5_principal_set_realm (context, principal, client_realm);
+ if (ret) {
+ krb5_free_principal(context, principal);
+ return ret;
+ }
+ } else {
+ ret = krb5_make_principal(context, &principal,
+ client_realm, KRB5_TGS_NAME, client_realm,
+ NULL);
+ if (ret)
+ return ret;
+ }
+
+ /*
+ * This is for Windows RODC that are picky about what name type
+ * the server principal have, and the really strange part is that
+ * they are picky about the AS-REQ name type and not the TGS-REQ
+ * later. Oh well.
+ */
+
+ if (krb5_principal_is_krbtgt(context, principal))
+ krb5_principal_set_type(context, principal, KRB5_NT_SRV_INST);
+
+ krb5_free_principal(context, ctx->cred.server);
+ ctx->cred.server = principal;
+
+ return 0;
+}
+
+/**
+ * Sets the password that will use for the request.
+ *
+ * @param context a Kerberos 5 context.
+ * @param ctx ctx krb5_init_creds_context context.
+ * @param password the password to use.
+ *
+ * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message().
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_password(krb5_context context,
+ krb5_init_creds_context ctx,
+ const char *password)
+{
+ if (ctx->password) {
+ size_t len;
+ len = strlen(ctx->password);
+ memset_s(ctx->password, len, 0, len);
+ free(ctx->password);
+ }
+ if (password) {
+ ctx->password = strdup(password);
+ if (ctx->password == NULL)
+ return krb5_enomem(context);
+ ctx->keyseed = (void *) ctx->password;
+ } else {
+ ctx->keyseed = NULL;
+ ctx->password = NULL;
+ }
+
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+keytab_key_proc(krb5_context context, krb5_enctype enctype,
+ krb5_const_pointer keyseed,
+ krb5_salt salt, krb5_data *s2kparms,
+ krb5_keyblock **key)
+{
+ krb5_keytab_key_proc_args *args = rk_UNCONST(keyseed);
+ krb5_keytab keytab = args->keytab;
+ krb5_principal principal = args->principal;
+ krb5_error_code ret;
+ krb5_keytab real_keytab = NULL;
+ krb5_keytab_entry entry;
+
+ if (keytab == NULL) {
+ ret = krb5_kt_default(context, &real_keytab);
+ if (ret)
+ return ret;
+ keytab = real_keytab;
+ }
+
+ ret = krb5_kt_get_entry (context, keytab, principal, 0, enctype, &entry);
+ if (ret == 0) {
+ ret = krb5_copy_keyblock(context, &entry.keyblock, key);
+ krb5_kt_free_entry(context, &entry);
+ }
+
+ krb5_kt_close(context, real_keytab);
+ return ret;
+}
+
+
+/**
+ * Set the keytab to use for authentication.
+ *
+ * @param context a Kerberos 5 context.
+ * @param ctx ctx krb5_init_creds_context context.
+ * @param keytab the keytab to read the key from.
+ *
+ * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message().
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_keytab(krb5_context context,
+ krb5_init_creds_context ctx,
+ krb5_keytab keytab)
+{
+ krb5_keytab_key_proc_args *a;
+ krb5_keytab_entry entry;
+ krb5_kt_cursor cursor;
+ krb5_enctype *etypes = NULL;
+ krb5_error_code ret;
+ size_t netypes = 0;
+ int kvno = 0, found = 0;
+ unsigned n;
+
+ a = malloc(sizeof(*a));
+ if (a == NULL)
+ return krb5_enomem(context);
+
+ a->principal = ctx->cred.client;
+ a->keytab = keytab;
+
+ ctx->keytab_data = a;
+ ctx->keyseed = (void *)a;
+ ctx->keyproc = keytab_key_proc;
+
+ /*
+ * We need to the KDC what enctypes we support for this keytab,
+ * esp if the keytab is really a password based entry, then the
+ * KDC might have more enctypes in the database then what we have
+ * in the keytab.
+ */
+
+ ret = krb5_kt_start_seq_get(context, keytab, &cursor);
+ if(ret)
+ goto out;
+
+ while(krb5_kt_next_entry(context, keytab, &entry, &cursor) == 0){
+ void *ptr;
+
+ if (!krb5_principal_compare(context, entry.principal, ctx->cred.client))
+ goto next;
+
+ found = 1;
+
+ /* check if we ahve this kvno already */
+ if (entry.vno > kvno) {
+ /* remove old list of etype */
+ if (etypes)
+ free(etypes);
+ etypes = NULL;
+ netypes = 0;
+ kvno = entry.vno;
+ } else if (entry.vno != kvno)
+ goto next;
+
+ /* check if enctype is supported */
+ if (krb5_enctype_valid(context, entry.keyblock.keytype) != 0)
+ goto next;
+
+ /*
+ * If user already provided a enctype list, use that as an
+ * additonal filter.
+ */
+ if (ctx->etypes) {
+ for (n = 0; ctx->etypes[n] != KRB5_ENCTYPE_NULL; n++) {
+ if (ctx->etypes[n] == entry.keyblock.keytype)
+ break;
+ }
+ if (ctx->etypes[n] == KRB5_ENCTYPE_NULL)
+ goto next;
+ }
+
+ /* add enctype to supported list */
+ ptr = realloc(etypes, sizeof(etypes[0]) * (netypes + 2));
+ if (ptr == NULL) {
+ free(etypes);
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ etypes = ptr;
+ etypes[netypes] = entry.keyblock.keytype;
+ etypes[netypes + 1] = ETYPE_NULL;
+ netypes++;
+ next:
+ krb5_kt_free_entry(context, &entry);
+ }
+ krb5_kt_end_seq_get(context, keytab, &cursor);
+
+ if (etypes) {
+ if (ctx->etypes)
+ free(ctx->etypes);
+ ctx->etypes = etypes;
+ }
+
+ out:
+ if (!found) {
+ if (ret == 0)
+ ret = KRB5_KT_NOTFOUND;
+ _krb5_kt_principal_not_found(context, ret, keytab, ctx->cred.client, 0, 0);
+ }
+
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+keyblock_key_proc(krb5_context context, krb5_enctype enctype,
+ krb5_const_pointer keyseed,
+ krb5_salt salt, krb5_data *s2kparms,
+ krb5_keyblock **key)
+{
+ return krb5_copy_keyblock (context, keyseed, key);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_keyblock(krb5_context context,
+ krb5_init_creds_context ctx,
+ krb5_keyblock *keyblock)
+{
+ ctx->keyseed = (void *)keyblock;
+ ctx->keyproc = keyblock_key_proc;
+
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_fast_ccache(krb5_context context,
+ krb5_init_creds_context ctx,
+ krb5_ccache fast_ccache)
+{
+ ctx->fast_state.armor_ccache = fast_ccache;
+ ctx->fast_state.flags |= KRB5_FAST_REQUIRED;
+ ctx->fast_state.flags |= KRB5_FAST_KDC_VERIFIED;
+ return 0;
+}
+
+static krb5_error_code
+validate_pkinit_fx(krb5_context context,
+ krb5_init_creds_context ctx,
+ AS_REP *rep,
+ krb5_keyblock *ticket_sessionkey)
+{
+ PA_DATA *pa = NULL;
+ int idx = 0;
+
+ if (rep->padata)
+ pa = krb5_find_padata(rep->padata->val, rep->padata->len, KRB5_PADATA_PKINIT_KX, &idx);
+
+ if (pa == NULL) {
+ if (ctx->flags.request_anonymous && ctx->pk_init_ctx) {
+ /* XXX handle the case where pkinit is not used */
+ krb5_set_error_message(context, KRB5_KDCREP_MODIFIED,
+ N_("Requested anonymous with PKINIT and KDC didn't set PKINIT_KX", ""));
+ return KRB5_KDCREP_MODIFIED;
+ }
+
+ return 0;
+ }
+
+ heim_assert(ctx->fast_state.reply_key != NULL, "must have a reply key at this stage");
+
+ return _krb5_pk_kx_confirm(context,
+ ctx->pk_init_ctx,
+ ctx->fast_state.reply_key,
+ ticket_sessionkey,
+ pa);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_fast_ap_armor_service(krb5_context context,
+ krb5_init_creds_context ctx,
+ krb5_const_principal armor_service)
+{
+ krb5_error_code ret;
+
+ if (ctx->fast_state.armor_service)
+ krb5_free_principal(context, ctx->fast_state.armor_service);
+ if (armor_service) {
+ ret = krb5_copy_principal(context, armor_service, &ctx->fast_state.armor_service);
+ if (ret)
+ return ret;
+ } else {
+ ctx->fast_state.armor_service = NULL;
+ }
+ ctx->fast_state.flags |= KRB5_FAST_AP_ARMOR_SERVICE;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_fast_anon_pkinit(krb5_context context,
+ krb5_init_creds_context ctx)
+{
+ if (ctx->fast_state.armor_ccache)
+ return EINVAL;
+
+ ctx->fast_state.flags |= KRB5_FAST_REQUIRED;
+ ctx->fast_state.flags |= KRB5_FAST_ANON_PKINIT_ARMOR;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_init_creds_set_fast_anon_pkinit_optimistic(krb5_context context,
+ krb5_init_creds_context ctx)
+{
+ if (ctx->fast_state.armor_ccache)
+ return EINVAL;
+
+ ctx->fast_state.flags |= KRB5_FAST_REQUIRED;
+ ctx->fast_state.flags |= KRB5_FAST_ANON_PKINIT_ARMOR;
+ ctx->fast_state.flags |= KRB5_FAST_OPTIMISTIC;
+ return 0;
+}
+
+static size_t
+available_padata_count(METHOD_DATA *md)
+{
+ size_t i, count = 0;
+
+ for (i = 0; i < md->len; i++) {
+ PA_DATA *pa = &md->val[i];
+
+ if (pa->padata_type == KRB5_PADATA_FX_COOKIE ||
+ pa->padata_type == KRB5_PADATA_FX_ERROR)
+ continue;
+
+ count++;
+ }
+
+ return count;
+}
+
+static krb5_error_code
+init_creds_step(krb5_context context,
+ krb5_init_creds_context ctx,
+ krb5_data *in,
+ krb5_data *out,
+ krb5_krbhst_info *hostinfo,
+ unsigned int *flags)
+{
+ struct timeval start_time, end_time;
+ krb5_data checksum_data;
+ krb5_error_code ret;
+ size_t len = 0;
+ size_t size;
+ AS_REQ req2;
+
+ gettimeofday(&start_time, NULL);
+
+ krb5_data_zero(out);
+ krb5_data_zero(&checksum_data);
+
+ if (ctx->as_req.req_body.cname == NULL) {
+ ret = init_as_req(context, ctx->flags, &ctx->cred,
+ ctx->addrs, ctx->etypes, &ctx->as_req);
+ if (ret)
+ return ret;
+ if (ctx->fast_state.flags & KRB5_FAST_REQUIRED)
+ ;
+ else if (ctx->fast_state.flags & KRB5_FAST_AP_ARMOR_SERVICE)
+ /* Check with armor service if there is FAST */;
+ else
+ ctx->fast_state.flags |= KRB5_FAST_DISABLED;
+
+
+ /* XXX should happen after we get back reply from KDC */
+ pa_configure(context, ctx, NULL);
+ }
+
+#define MAX_PA_COUNTER 15
+ if (ctx->pa_counter > MAX_PA_COUNTER) {
+ krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
+ N_("Looping %d times while getting "
+ "initial credentials", ""),
+ ctx->pa_counter);
+ return KRB5_GET_IN_TKT_LOOP;
+ }
+ ctx->pa_counter++;
+
+ _krb5_debug(context, 5, "krb5_get_init_creds: loop %d", ctx->pa_counter);
+
+ /* Lets process the input packet */
+ if (in && in->length) {
+ krb5_kdc_rep rep;
+
+ memset(&rep, 0, sizeof(rep));
+
+ _krb5_debug(context, 5, "krb5_get_init_creds: processing input");
+
+ ret = decode_AS_REP(in->data, in->length, &rep.kdc_rep, &size);
+ if (ret == 0) {
+ unsigned eflags = EXTRACT_TICKET_AS_REQ | EXTRACT_TICKET_TIMESYNC;
+ krb5_data data;
+
+ /*
+ * Unwrap AS-REP
+ */
+ ASN1_MALLOC_ENCODE(Ticket, data.data, data.length,
+ &rep.kdc_rep.ticket, &size, ret);
+ if (ret)
+ goto out;
+ heim_assert(data.length == size, "ASN.1 internal error");
+
+ ret = _krb5_fast_unwrap_kdc_rep(context, ctx->nonce, &data,
+ &ctx->fast_state, &rep.kdc_rep);
+ krb5_data_free(&data);
+ if (ret)
+ goto out;
+
+ /*
+ * Now check and extract the ticket
+ */
+
+ if (ctx->flags.canonicalize) {
+ eflags |= EXTRACT_TICKET_ALLOW_SERVER_MISMATCH;
+ eflags |= EXTRACT_TICKET_MATCH_REALM;
+ }
+ if (ctx->ic_flags & KRB5_INIT_CREDS_NO_C_CANON_CHECK)
+ eflags |= EXTRACT_TICKET_ALLOW_CNAME_MISMATCH;
+ if (ctx->flags.request_anonymous)
+ eflags |= EXTRACT_TICKET_MATCH_ANON;
+
+ ret = process_pa_data_to_key(context, ctx, &ctx->cred,
+ &ctx->as_req, &rep.kdc_rep,
+ hostinfo, &ctx->fast_state.reply_key);
+ if (ret) {
+ free_AS_REP(&rep.kdc_rep);
+ goto out;
+ }
+
+ if (ctx->fast_state.strengthen_key) {
+ krb5_keyblock result;
+
+ _krb5_debug(context, 5, "krb5_get_init_creds: FAST strengthen_key");
+
+ ret = _krb5_fast_cf2(context,
+ ctx->fast_state.strengthen_key,
+ "strengthenkey",
+ ctx->fast_state.reply_key,
+ "replykey",
+ &result,
+ NULL);
+ if (ret) {
+ free_AS_REP(&rep.kdc_rep);
+ goto out;
+ }
+
+ ctx->runflags.allow_save_as_reply_key = 1;
+
+ krb5_free_keyblock_contents(context, ctx->fast_state.reply_key);
+ *ctx->fast_state.reply_key = result;
+ }
+
+ _krb5_debug(context, 5, "krb5_get_init_creds: extracting ticket");
+
+ ret = _krb5_extract_ticket(context,
+ &rep,
+ &ctx->cred,
+ ctx->fast_state.reply_key,
+ NULL,
+ KRB5_KU_AS_REP_ENC_PART,
+ NULL,
+ ctx->nonce,
+ eflags,
+ &ctx->req_buffer,
+ NULL,
+ NULL);
+
+ if (ret == 0)
+ ret = copy_EncKDCRepPart(&rep.enc_part, &ctx->enc_part);
+ if (ret == 0)
+ ret = validate_pkinit_fx(context, ctx, &rep.kdc_rep, &ctx->cred.session);
+
+ ctx->as_enctype = ctx->fast_state.reply_key->keytype;
+
+ if (ctx->runflags.allow_save_as_reply_key) {
+ ctx->as_reply_key = ctx->fast_state.reply_key;
+ ctx->fast_state.reply_key = NULL;
+ } else {
+ krb5_free_keyblock(context, ctx->fast_state.reply_key);
+ ctx->fast_state.reply_key = NULL;
+ }
+ ctx->ic_flags |= KRB5_INIT_CREDS_DONE;
+ *flags = 0;
+
+ free_AS_REP(&rep.kdc_rep);
+ free_EncASRepPart(&rep.enc_part);
+
+ gettimeofday(&end_time, NULL);
+ timevalsub(&end_time, &start_time);
+ timevaladd(&ctx->stats.run_time, &end_time);
+
+ _krb5_debug(context, 1, "krb5_get_init_creds: wc: %lld.%06ld",
+ (long long)ctx->stats.run_time.tv_sec,
+ (long)ctx->stats.run_time.tv_usec);
+ return ret;
+
+ } else {
+ /* let's try to parse it as a KRB-ERROR */
+
+ _krb5_debug(context, 5, "krb5_get_init_creds: got an KRB-ERROR from KDC");
+
+ free_KRB_ERROR(&ctx->error);
+
+ ret = krb5_rd_error(context, in, &ctx->error);
+ if(ret && in->length && ((char*)in->data)[0] == 4)
+ ret = KRB5KRB_AP_ERR_V4_REPLY;
+ if (ret) {
+ _krb5_debug(context, 5, "krb5_get_init_creds: failed to read error");
+ goto out;
+ }
+
+ /*
+ * Unwrap method-data, if there is any,
+ * fast_unwrap_error() below might replace it with a
+ * wrapped version if we are using FAST.
+ */
+
+ free_METHOD_DATA(&ctx->md);
+ memset(&ctx->md, 0, sizeof(ctx->md));
+
+ if (ctx->error.e_data) {
+ krb5_error_code ret2;
+
+ ret2 = decode_METHOD_DATA(ctx->error.e_data->data,
+ ctx->error.e_data->length,
+ &ctx->md,
+ NULL);
+ if (ret2) {
+ /*
+ * Just ignore any error, the error will be pushed
+ * out from krb5_error_from_rd_error() if there
+ * was one.
+ */
+ _krb5_debug(context, 5, N_("Failed to decode METHOD-DATA", ""));
+ }
+ }
+
+ /*
+ * Unwrap KRB-ERROR, we are always calling this so that
+ * FAST can tell us if your peer KDC suddenly dropped FAST
+ * wrapping and its really an attacker's packet (or a bug
+ * in the KDC).
+ */
+ ret = _krb5_fast_unwrap_error(context, ctx->nonce, &ctx->fast_state,
+ &ctx->md, &ctx->error);
+ if (ret)
+ goto out;
+
+ /*
+ *
+ */
+
+ ret = krb5_error_from_rd_error(context, &ctx->error, &ctx->cred);
+
+ /* log the failure */
+ if (_krb5_have_debug(context, 5)) {
+ const char *str = krb5_get_error_message(context, ret);
+ _krb5_debug(context, 5, "krb5_get_init_creds: KRB-ERROR %d/%s", ret, str);
+ krb5_free_error_message(context, str);
+ }
+
+ /*
+ * Handle special error codes
+ */
+
+ if (ret == KRB5KDC_ERR_PREAUTH_REQUIRED
+ || ret == KRB5_KDC_ERR_MORE_PREAUTH_DATA_REQUIRED
+ || ret == KRB5KDC_ERR_ETYPE_NOSUPP)
+ {
+ /*
+ * If no preauth was set and KDC requires it, give it one
+ * more try.
+ *
+ * If the KDC returned KRB5KDC_ERR_ETYPE_NOSUPP, just loop
+ * one more time since that might mean we are dealing with
+ * a Windows KDC that is confused about what enctypes are
+ * available.
+ */
+
+ if (available_padata_count(&ctx->md) == 0) {
+ krb5_set_error_message(context, ret,
+ N_("Preauth required but no preauth "
+ "options sent by KDC", ""));
+ goto out;
+ }
+ } else if (ret == KRB5KRB_AP_ERR_SKEW && context->kdc_sec_offset == 0) {
+ /*
+ * Try adapt to timeskrew when we are using pre-auth, and
+ * if there was a time skew, try again.
+ */
+ krb5_set_real_time(context, ctx->error.stime, -1);
+ if (context->kdc_sec_offset)
+ ret = 0;
+
+ _krb5_debug(context, 10, "init_creds: err skew updating kdc offset to %d",
+ context->kdc_sec_offset);
+ if (ret)
+ goto out;
+
+ pa_restart(context, ctx);
+
+ } else if (ret == KRB5_KDC_ERR_WRONG_REALM && ctx->flags.canonicalize) {
+ /* client referral to a new realm */
+ char *ref_realm;
+
+ if (ctx->error.crealm == NULL) {
+ krb5_set_error_message(context, ret,
+ N_("Got a client referral, not but no realm", ""));
+ goto out;
+ }
+ ref_realm = *ctx->error.crealm;
+
+ _krb5_debug(context, 5, "krb5_get_init_creds: referral to realm %s",
+ ref_realm);
+
+ /*
+ * If its a krbtgt, lets updat the requested krbtgt too
+ */
+ if (krb5_principal_is_krbtgt(context, ctx->cred.server)) {
+
+ free(ctx->cred.server->name.name_string.val[1]);
+ ctx->cred.server->name.name_string.val[1] = strdup(ref_realm);
+ if (ctx->cred.server->name.name_string.val[1] == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ free_PrincipalName(ctx->as_req.req_body.sname);
+ ret = _krb5_principal2principalname(ctx->as_req.req_body.sname, ctx->cred.server);
+ if (ret)
+ goto out;
+ }
+
+ free(ctx->as_req.req_body.realm);
+ ret = copy_Realm(&ref_realm, &ctx->as_req.req_body.realm);
+ if (ret)
+ goto out;
+
+ ret = krb5_principal_set_realm(context,
+ ctx->cred.client,
+ *ctx->error.crealm);
+ if (ret)
+ goto out;
+
+ ret = krb5_unparse_name(context, ctx->cred.client, &ref_realm);
+ if (ret == 0) {
+ _krb5_debug(context, 5, "krb5_get_init_creds: got referral to %s", ref_realm);
+ krb5_xfree(ref_realm);
+ }
+
+ pa_restart(context, ctx);
+
+ } else if (ret == KRB5KDC_ERR_KEY_EXP && ctx->runflags.change_password == 0 &&
+ ctx->runflags.change_password_prompt) {
+ char buf2[1024];
+
+ ctx->runflags.change_password = 1;
+
+ ctx->prompter(context, ctx->prompter_data, NULL, N_("Password has expired", ""), 0, NULL);
+
+ /* try to avoid recursion */
+ if (ctx->in_tkt_service != NULL && strcmp(ctx->in_tkt_service, "kadmin/changepw") == 0)
+ goto out;
+
+ /* don't include prompter in runtime */
+ gettimeofday(&end_time, NULL);
+ timevalsub(&end_time, &start_time);
+ timevaladd(&ctx->stats.run_time, &end_time);
+
+ ret = change_password(context,
+ ctx->cred.client,
+ ctx->password,
+ buf2,
+ sizeof(buf2),
+ ctx->prompter,
+ ctx->prompter_data,
+ NULL);
+ if (ret)
+ goto out;
+
+ gettimeofday(&start_time, NULL);
+
+ krb5_init_creds_set_password(context, ctx, buf2);
+
+ pa_restart(context, ctx);
+
+ } else if (ret == KRB5KDC_ERR_PREAUTH_FAILED) {
+
+ /*
+ * Old MIT KDC can't handle KRB5_PADATA_REQ_ENC_PA_REP,
+ * so drop it and try again. But only try that for MIT
+ * Kerberos servers by keying of no METHOD-DATA.
+ */
+ if (ctx->runflags.allow_enc_pa_rep) {
+ if (ctx->md.len != 0) {
+ _krb5_debug(context, 10, "Server sent PA data with KRB-ERROR, "
+ "so not a pre 1.7 MIT KDC and won't retry w/o ENC-PA-REQ");
+ goto out;
+ }
+ _krb5_debug(context, 10, "Disabling allow_enc_pa_rep and trying again");
+ ctx->runflags.allow_enc_pa_rep = 0;
+ goto retry;
+ }
+
+ if (ctx->fast_state.flags & KRB5_FAST_DISABLED) {
+ _krb5_debug(context, 10, "FAST disabled and got preauth failed");
+ goto out;
+ }
+
+ retry:
+ pa_restart(context, ctx);
+
+ } else if (ctx->fast_state.flags & KRB5_FAST_OPTIMISTIC) {
+ _krb5_debug(context, 10,
+ "Some other error %d failed with optimistic FAST, trying w/o FAST", ret);
+
+ ctx->fast_state.flags &= ~KRB5_FAST_OPTIMISTIC;
+ ctx->fast_state.flags &= ~KRB5_FAST_REQUIRED;
+ ctx->fast_state.flags &= ~KRB5_FAST_ANON_PKINIT_ARMOR;
+ ctx->fast_state.flags |= KRB5_FAST_DISABLED;
+ pa_restart(context, ctx);
+ } else {
+ /* some other error code from the KDC, lets' return it to the user */
+ goto out;
+ }
+ }
+ }
+
+ if (ctx->as_req.padata) {
+ free_METHOD_DATA(ctx->as_req.padata);
+ free(ctx->as_req.padata);
+ ctx->as_req.padata = NULL;
+ }
+
+ ret = _krb5_fast_create_armor(context, &ctx->fast_state,
+ ctx->cred.client->realm);
+ if (ret)
+ goto out;
+
+ /* Set a new nonce. */
+ ctx->as_req.req_body.nonce = ctx->nonce;
+
+
+ /*
+ * Step and announce PA-DATA
+ */
+
+ ret = process_pa_data_to_md(context, &ctx->cred, &ctx->as_req, ctx,
+ &ctx->md, &ctx->as_req.padata);
+ if (ret)
+ goto out;
+
+
+ /*
+ * Wrap with FAST
+ */
+ ret = copy_AS_REQ(&ctx->as_req, &req2);
+ if (ret)
+ goto out;
+
+ ret = _krb5_fast_wrap_req(context,
+ &ctx->fast_state,
+ &req2);
+
+ krb5_data_free(&checksum_data);
+ if (ret) {
+ free_AS_REQ(&req2);
+ goto out;
+ }
+
+ krb5_data_free(&ctx->req_buffer);
+
+ ASN1_MALLOC_ENCODE(AS_REQ,
+ ctx->req_buffer.data, ctx->req_buffer.length,
+ &req2, &len, ret);
+ free_AS_REQ(&req2);
+ if (ret)
+ goto out;
+ if(len != ctx->req_buffer.length)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ out->data = ctx->req_buffer.data;
+ out->length = ctx->req_buffer.length;
+
+ *flags = KRB5_INIT_CREDS_STEP_FLAG_CONTINUE;
+
+ gettimeofday(&end_time, NULL);
+ timevalsub(&end_time, &start_time);
+ timevaladd(&ctx->stats.run_time, &end_time);
+
+ return 0;
+ out:
+ return ret;
+}
+
+/**
+ * The core loop if krb5_get_init_creds() function family. Create the
+ * packets and have the caller send them off to the KDC.
+ *
+ * If the caller want all work been done for them, use
+ * krb5_init_creds_get() instead.
+ *
+ * @param context a Kerberos 5 context.
+ * @param ctx ctx krb5_init_creds_context context.
+ * @param in input data from KDC, first round it should be reset by krb5_data_zer().
+ * @param out reply to KDC.
+ * @param hostinfo KDC address info, first round it can be NULL.
+ * @param flags status of the round, if
+ * KRB5_INIT_CREDS_STEP_FLAG_CONTINUE is set, continue one more round.
+ *
+ * @return 0 for success, or an Kerberos 5 error code, see
+ * krb5_get_error_message().
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_step(krb5_context context,
+ krb5_init_creds_context ctx,
+ krb5_data *in,
+ krb5_data *out,
+ krb5_krbhst_info *hostinfo,
+ unsigned int *flags)
+{
+ krb5_error_code ret;
+ krb5_data empty;
+
+ krb5_data_zero(&empty);
+
+ if ((ctx->fast_state.flags & KRB5_FAST_ANON_PKINIT_ARMOR) &&
+ ctx->fast_state.armor_ccache == NULL) {
+ ret = _krb5_fast_anon_pkinit_step(context, ctx, &ctx->fast_state,
+ in, out, hostinfo, flags);
+ if (ret && (ctx->fast_state.flags & KRB5_FAST_OPTIMISTIC)) {
+ _krb5_debug(context, 5, "Preauth failed with optimistic "
+ "FAST, trying w/o FAST");
+ ctx->fast_state.flags &= ~KRB5_FAST_OPTIMISTIC;
+ ctx->fast_state.flags &= ~KRB5_FAST_REQUIRED;
+ ctx->fast_state.flags &= ~KRB5_FAST_ANON_PKINIT_ARMOR;
+ } else if (ret ||
+ ((*flags & KRB5_INIT_CREDS_STEP_FLAG_CONTINUE) == 0) ||
+ out->length)
+ return ret;
+
+ in = &empty;
+ }
+
+ return init_creds_step(context, ctx, in, out, hostinfo, flags);
+}
+
+/**
+ * Extract the newly acquired credentials from krb5_init_creds_context
+ * context.
+ *
+ * @param context A Kerberos 5 context.
+ * @param ctx
+ * @param cred credentials, free with krb5_free_cred_contents().
+ *
+ * @return 0 for sucess or An Kerberos error code, see krb5_get_error_message().
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_get_creds(krb5_context context,
+ krb5_init_creds_context ctx,
+ krb5_creds *cred)
+{
+ return krb5_copy_creds_contents(context, &ctx->cred, cred);
+}
+
+/**
+ * Extract the as-reply key from the context.
+ *
+ * Only allowed when the as-reply-key is not directly derived from the
+ * password like PK-INIT, GSS, FAST hardened key, etc.
+ *
+ * @param context A Kerberos 5 context.
+ * @param ctx ctx krb5_init_creds_context context.
+ * @param as_reply_key keyblock, free with krb5_free_keyblock_contents().
+ *
+ * @return 0 for sucess or An Kerberos error code, see krb5_get_error_message().
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_get_as_reply_key(krb5_context context,
+ krb5_init_creds_context ctx,
+ krb5_keyblock *as_reply_key)
+{
+ if (ctx->as_reply_key == NULL)
+ return KRB5KDC_ERR_PREAUTH_REQUIRED;
+ return krb5_copy_keyblock_contents(context, ctx->as_reply_key, as_reply_key);
+}
+
+KRB5_LIB_FUNCTION krb5_timestamp KRB5_LIB_CALL
+_krb5_init_creds_get_cred_starttime(krb5_context context, krb5_init_creds_context ctx)
+{
+ return ctx->cred.times.starttime;
+}
+
+KRB5_LIB_FUNCTION krb5_timestamp KRB5_LIB_CALL
+_krb5_init_creds_get_cred_endtime(krb5_context context, krb5_init_creds_context ctx)
+{
+ return ctx->cred.times.endtime;
+}
+
+KRB5_LIB_FUNCTION krb5_principal KRB5_LIB_CALL
+_krb5_init_creds_get_cred_client(krb5_context context, krb5_init_creds_context ctx)
+{
+ return ctx->cred.client;
+}
+
+/**
+ * Get the last error from the transaction.
+ *
+ * @return Returns 0 or an error code
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_get_error(krb5_context context,
+ krb5_init_creds_context ctx,
+ KRB_ERROR *error)
+{
+ krb5_error_code ret;
+
+ ret = copy_KRB_ERROR(&ctx->error, error);
+ if (ret)
+ krb5_enomem(context);
+
+ return ret;
+}
+
+/**
+ * Store config
+ *
+ * @param context A Kerberos 5 context.
+ * @param ctx The krb5_init_creds_context to free.
+ * @param id store
+ *
+ * @return Returns 0 or an error code
+ *
+ * @ingroup krb5_credential
+ */
+
+krb5_error_code KRB5_LIB_FUNCTION
+krb5_init_creds_store_config(krb5_context context,
+ krb5_init_creds_context ctx,
+ krb5_ccache id)
+{
+ krb5_error_code ret;
+
+ if (ctx->kdc_hostname) {
+ krb5_data data;
+ data.length = strlen(ctx->kdc_hostname);
+ data.data = ctx->kdc_hostname;
+
+ ret = krb5_cc_set_config(context, id, NULL, "lkdc-hostname", &data);
+ if (ret)
+ return ret;
+ }
+ if (ctx->sitename) {
+ krb5_data data;
+ data.length = strlen(ctx->sitename);
+ data.data = ctx->sitename;
+
+ ret = krb5_cc_set_config(context, id, NULL, "sitename", &data);
+ if (ret)
+ return ret;
+ }
+
+ return 0;
+}
+
+/**
+ *
+ * @ingroup krb5_credential
+ */
+
+krb5_error_code
+krb5_init_creds_store(krb5_context context,
+ krb5_init_creds_context ctx,
+ krb5_ccache id)
+{
+ krb5_error_code ret;
+
+ if (ctx->cred.client == NULL) {
+ ret = KRB5KDC_ERR_PREAUTH_REQUIRED;
+ krb5_set_error_message(context, ret, "init creds not completed yet");
+ return ret;
+ }
+
+ ret = krb5_cc_initialize(context, id, ctx->cred.client);
+ if (ret)
+ return ret;
+
+ ret = krb5_cc_store_cred(context, id, &ctx->cred);
+ if (ret)
+ return ret;
+
+ if (ctx->cred.flags.b.enc_pa_rep) {
+ krb5_data data = { 3, rk_UNCONST("yes") };
+ ret = krb5_cc_set_config(context, id, ctx->cred.server,
+ "fast_avail", &data);
+ if (ret && ret != KRB5_CC_NOSUPP)
+ return ret;
+ }
+
+ return 0;
+}
+
+/**
+ * Free the krb5_init_creds_context allocated by krb5_init_creds_init().
+ *
+ * @param context A Kerberos 5 context.
+ * @param ctx The krb5_init_creds_context to free.
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_init_creds_free(krb5_context context,
+ krb5_init_creds_context ctx)
+{
+ free_init_creds_ctx(context, ctx);
+ free(ctx);
+}
+
+/**
+ * Get new credentials as setup by the krb5_init_creds_context.
+ *
+ * @param context A Kerberos 5 context.
+ * @param ctx The krb5_init_creds_context to process.
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_get(krb5_context context, krb5_init_creds_context ctx)
+{
+ krb5_sendto_ctx stctx = NULL;
+ krb5_krbhst_info *hostinfo = NULL;
+ krb5_error_code ret;
+ krb5_data in, out;
+ unsigned int flags = 0;
+
+ krb5_data_zero(&in);
+ krb5_data_zero(&out);
+
+ ret = krb5_sendto_ctx_alloc(context, &stctx);
+ if (ret)
+ goto out;
+ krb5_sendto_ctx_set_func(stctx, _krb5_kdc_retry, NULL);
+
+ if (ctx->kdc_hostname)
+ krb5_sendto_set_hostname(context, stctx, ctx->kdc_hostname);
+ if (ctx->sitename)
+ krb5_sendto_set_sitename(context, stctx, ctx->sitename);
+
+ while (1) {
+ struct timeval nstart, nend;
+
+ flags = 0;
+ ret = krb5_init_creds_step(context, ctx, &in, &out, hostinfo, &flags);
+ krb5_data_free(&in);
+ if (ret)
+ goto out;
+
+ if ((flags & KRB5_INIT_CREDS_STEP_FLAG_CONTINUE) == 0)
+ break;
+
+ gettimeofday(&nstart, NULL);
+
+ ret = krb5_sendto_context (context, stctx, &out,
+ ctx->cred.client->realm, &in);
+ if (ret)
+ goto out;
+
+ gettimeofday(&nend, NULL);
+ timevalsub(&nend, &nstart);
+ timevaladd(&ctx->stats.run_time, &nend);
+ }
+
+ out:
+ if (stctx)
+ krb5_sendto_ctx_free(context, stctx);
+
+ return ret;
+}
+
+/**
+ * Get new credentials using password.
+ *
+ * @ingroup krb5_credential
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_password(krb5_context context,
+ krb5_creds *creds,
+ krb5_principal client,
+ const char *password,
+ krb5_prompter_fct prompter,
+ void *data,
+ krb5_deltat start_time,
+ const char *in_tkt_service,
+ krb5_get_init_creds_opt *options)
+{
+ krb5_init_creds_context ctx;
+ char buf[BUFSIZ], buf2[BUFSIZ];
+ krb5_error_code ret;
+ int chpw = 0;
+
+ again:
+ ret = krb5_init_creds_init(context, client, prompter, data, start_time, options, &ctx);
+ if (ret)
+ goto out;
+
+ ret = krb5_init_creds_set_service(context, ctx, in_tkt_service);
+ if (ret)
+ goto out;
+
+ if (prompter != NULL && ctx->password == NULL && password == NULL) {
+ krb5_prompt prompt;
+ krb5_data password_data;
+ char *p, *q = NULL;
+ int aret;
+
+ ret = krb5_unparse_name(context, client, &p);
+ if (ret)
+ goto out;
+
+ aret = asprintf(&q, "%s's Password: ", p);
+ free (p);
+ if (aret == -1 || q == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ prompt.prompt = q;
+ password_data.data = buf;
+ password_data.length = sizeof(buf);
+ prompt.hidden = 1;
+ prompt.reply = &password_data;
+ prompt.type = KRB5_PROMPT_TYPE_PASSWORD;
+
+ ret = (*prompter) (context, data, NULL, NULL, 1, &prompt);
+ free (q);
+ if (ret) {
+ memset_s(buf, sizeof(buf), 0, sizeof(buf));
+ ret = KRB5_LIBOS_PWDINTR;
+ krb5_clear_error_message (context);
+ goto out;
+ }
+ password = password_data.data;
+ }
+
+ if (password) {
+ ret = krb5_init_creds_set_password(context, ctx, password);
+ if (ret)
+ goto out;
+ }
+
+ ret = krb5_init_creds_get(context, ctx);
+
+ if (ret == 0)
+ krb5_process_last_request(context, options, ctx);
+
+
+ if (ret == KRB5KDC_ERR_KEY_EXPIRED && chpw == 0) {
+ /* try to avoid recursion */
+ if (in_tkt_service != NULL && strcmp(in_tkt_service, "kadmin/changepw") == 0)
+ goto out;
+
+ /* don't try to change password if no prompter or prompting disabled */
+ if (!ctx->runflags.change_password_prompt)
+ goto out;
+
+ ret = change_password (context,
+ client,
+ ctx->password,
+ buf2,
+ sizeof(buf2),
+ prompter,
+ data,
+ options);
+ if (ret)
+ goto out;
+ password = buf2;
+ chpw = 1;
+ krb5_init_creds_free(context, ctx);
+ goto again;
+ }
+
+ out:
+ if (ret == 0)
+ krb5_init_creds_get_creds(context, ctx, creds);
+
+ if (ctx)
+ krb5_init_creds_free(context, ctx);
+
+ memset_s(buf, sizeof(buf), 0, sizeof(buf));
+ memset_s(buf2, sizeof(buf), 0, sizeof(buf2));
+ return ret;
+}
+
+/**
+ * Get new credentials using keyblock.
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_keyblock(krb5_context context,
+ krb5_creds *creds,
+ krb5_principal client,
+ krb5_keyblock *keyblock,
+ krb5_deltat start_time,
+ const char *in_tkt_service,
+ krb5_get_init_creds_opt *options)
+{
+ krb5_init_creds_context ctx;
+ krb5_error_code ret;
+
+ memset(creds, 0, sizeof(*creds));
+
+ ret = krb5_init_creds_init(context, client, NULL, NULL, start_time, options, &ctx);
+ if (ret)
+ goto out;
+
+ ret = krb5_init_creds_set_service(context, ctx, in_tkt_service);
+ if (ret)
+ goto out;
+
+ ret = krb5_init_creds_set_keyblock(context, ctx, keyblock);
+ if (ret)
+ goto out;
+
+ ret = krb5_init_creds_get(context, ctx);
+
+ if (ret == 0)
+ krb5_process_last_request(context, options, ctx);
+
+ out:
+ if (ret == 0)
+ krb5_init_creds_get_creds(context, ctx, creds);
+
+ if (ctx)
+ krb5_init_creds_free(context, ctx);
+
+ return ret;
+}
+
+/**
+ * Get new credentials using keytab.
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_keytab(krb5_context context,
+ krb5_creds *creds,
+ krb5_principal client,
+ krb5_keytab keytab,
+ krb5_deltat start_time,
+ const char *in_tkt_service,
+ krb5_get_init_creds_opt *options)
+{
+ krb5_init_creds_context ctx;
+ krb5_keytab_entry ktent;
+ krb5_error_code ret;
+
+ memset(&ktent, 0, sizeof(ktent));
+ memset(creds, 0, sizeof(*creds));
+
+ if (strcmp(client->realm, "") == 0) {
+ /*
+ * Referral realm. We have a keytab, so pick a realm by
+ * matching in the keytab.
+ */
+ ret = krb5_kt_get_entry(context, keytab, client, 0, 0, &ktent);
+ if (ret == 0)
+ client = ktent.principal;
+ }
+
+ ret = krb5_init_creds_init(context, client, NULL, NULL, start_time, options, &ctx);
+ if (ret)
+ goto out;
+
+ ret = krb5_init_creds_set_service(context, ctx, in_tkt_service);
+ if (ret)
+ goto out;
+
+ ret = krb5_init_creds_set_keytab(context, ctx, keytab);
+ if (ret)
+ goto out;
+
+ ret = krb5_init_creds_get(context, ctx);
+ if (ret == 0)
+ krb5_process_last_request(context, options, ctx);
+
+ out:
+ krb5_kt_free_entry(context, &ktent);
+ if (ret == 0)
+ krb5_init_creds_get_creds(context, ctx, creds);
+
+ if (ctx)
+ krb5_init_creds_free(context, ctx);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_init_creds_set_gss_mechanism(krb5_context context,
+ krb5_gss_init_ctx gssic,
+ const struct gss_OID_desc_struct *gss_mech)
+{
+ gssic->mech = gss_mech; /* OIDs are interned, so no copy required */
+}
+
+KRB5_LIB_FUNCTION const struct gss_OID_desc_struct * KRB5_LIB_CALL
+_krb5_init_creds_get_gss_mechanism(krb5_context context,
+ krb5_gss_init_ctx gssic)
+{
+ return gssic->mech;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_init_creds_set_gss_cred(krb5_context context,
+ krb5_gss_init_ctx gssic,
+ struct gss_cred_id_t_desc_struct *gss_cred)
+{
+ if (gssic->cred != gss_cred && gssic->flags.release_cred)
+ gssic->release_cred(context, gssic, gssic->cred);
+
+ gssic->cred = gss_cred;
+ gssic->flags.release_cred = 1;
+}
+
+KRB5_LIB_FUNCTION const struct gss_cred_id_t_desc_struct * KRB5_LIB_CALL
+_krb5_init_creds_get_gss_cred(krb5_context context,
+ krb5_gss_init_ctx gssic)
+{
+ return gssic->cred;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_init_creds_init_gss(krb5_context context,
+ krb5_init_creds_context ctx,
+ krb5_gssic_step step,
+ krb5_gssic_finish finish,
+ krb5_gssic_release_cred release_cred,
+ krb5_gssic_delete_sec_context delete_sec_context,
+ const struct gss_cred_id_t_desc_struct *gss_cred,
+ const struct gss_OID_desc_struct *gss_mech,
+ unsigned int flags)
+{
+ krb5_gss_init_ctx gssic;
+
+ gssic = calloc(1, sizeof(*gssic));
+ if (gssic == NULL)
+ return krb5_enomem(context);
+
+ if (ctx->gss_init_ctx)
+ free_gss_init_ctx(context, ctx->gss_init_ctx);
+ ctx->gss_init_ctx = gssic;
+
+ gssic->cred = (struct gss_cred_id_t_desc_struct *)gss_cred;
+ gssic->mech = gss_mech;
+ if (flags & KRB5_GSS_IC_FLAG_RELEASE_CRED)
+ gssic->flags.release_cred = 1;
+
+ gssic->step = step;
+ gssic->finish = finish;
+ gssic->release_cred = release_cred;
+ gssic->delete_sec_context = delete_sec_context;
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/k524_err.et b/third_party/heimdal/lib/krb5/k524_err.et
new file mode 100644
index 0000000..4827b39
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/k524_err.et
@@ -0,0 +1,20 @@
+#
+# Error messages for the k524 functions
+#
+# This might look like a com_err file, but is not
+#
+id "$Id$"
+
+error_table k524
+
+prefix KRB524
+error_code BADKEY, "wrong keytype in ticket"
+error_code BADADDR, "incorrect network address"
+error_code BADPRINC, "cannot convert V5 principal" #unused
+error_code BADREALM, "V5 realm name longer than V4 maximum" #unused
+error_code V4ERR, "kerberos V4 error server"
+error_code ENCFULL, "encoding too large at server"
+error_code DECEMPTY, "decoding out of data" #unused
+error_code NOTRESP, "service not responding" #unused
+end
+
diff --git a/third_party/heimdal/lib/krb5/k5e1_err.et b/third_party/heimdal/lib/krb5/k5e1_err.et
new file mode 100644
index 0000000..19414f1
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/k5e1_err.et
@@ -0,0 +1,13 @@
+id "$Id$"
+
+error_table k5e1
+
+index 4
+
+prefix KRB5_DCC
+error_code CANNOT_CREATE, "Can't create new subsidiary cache"
+
+prefix KRB5_KCC
+error_code INVALID_ANCHOR, "Invalid keyring anchor name"
+error_code UNKNOWN_VERSION, "Unknown keyring collection version"
+error_code INVALID_UID, "Invalid UID in persistent keyring name"
diff --git a/third_party/heimdal/lib/krb5/kcm.c b/third_party/heimdal/lib/krb5/kcm.c
new file mode 100644
index 0000000..a75fc03
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/kcm.c
@@ -0,0 +1,1506 @@
+/*
+ * Copyright (c) 2005, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#ifdef HAVE_KCM
+/*
+ * Client library for Kerberos Credentials Manager (KCM) daemon
+ */
+
+#include "kcm.h"
+#include <heim-ipc.h>
+
+static krb5_error_code
+kcm_set_kdc_offset(krb5_context, krb5_ccache, krb5_deltat);
+
+static const char *kcm_ipc_name = "ANY:org.h5l.kcm";
+
+typedef struct krb5_kcmcache {
+ char *name;
+} krb5_kcmcache;
+
+typedef struct krb5_kcm_cursor {
+ unsigned long offset;
+ unsigned long length;
+ kcmuuid_t *uuids;
+} *krb5_kcm_cursor;
+
+
+#define KCMCACHE(X) ((krb5_kcmcache *)(X)->data.data)
+#define CACHENAME(X) (KCMCACHE(X)->name)
+#define KCMCURSOR(C) ((krb5_kcm_cursor)(C))
+
+static HEIMDAL_MUTEX kcm_mutex = HEIMDAL_MUTEX_INITIALIZER;
+static heim_ipc kcm_ipc = NULL;
+
+static krb5_error_code
+kcm_send_request(krb5_context context,
+ krb5_storage *request,
+ krb5_data *response_data)
+{
+ krb5_error_code ret = 0;
+ krb5_data request_data;
+
+ krb5_data_zero(response_data);
+
+ HEIMDAL_MUTEX_lock(&kcm_mutex);
+ if (kcm_ipc == NULL)
+ ret = heim_ipc_init_context(kcm_ipc_name, &kcm_ipc);
+ HEIMDAL_MUTEX_unlock(&kcm_mutex);
+ if (ret)
+ return KRB5_CC_NOSUPP;
+
+ ret = krb5_storage_to_data(request, &request_data);
+ if (ret) {
+ return krb5_enomem(context);
+ }
+
+ ret = heim_ipc_call(kcm_ipc, &request_data, response_data, NULL);
+ krb5_data_free(&request_data);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kcm_storage_request(krb5_context context,
+ uint16_t opcode,
+ krb5_storage **storage_p)
+{
+ krb5_storage *sp;
+ krb5_error_code ret;
+
+ *storage_p = NULL;
+
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ return krb5_enomem(context);
+
+ /* Send MAJOR | VERSION | OPCODE */
+ ret = krb5_store_int8(sp, KCM_PROTOCOL_VERSION_MAJOR);
+ if (ret)
+ goto fail;
+ ret = krb5_store_int8(sp, KCM_PROTOCOL_VERSION_MINOR);
+ if (ret)
+ goto fail;
+ ret = krb5_store_int16(sp, opcode);
+ if (ret)
+ goto fail;
+
+ *storage_p = sp;
+ fail:
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to encode KCM request", ""));
+ krb5_storage_free(sp);
+ }
+
+ return ret;
+}
+
+/*
+ * A sort of a state() for caches -- we use this to see if the local default
+ * cache name for KCM happens to exist. See kcm_alloc() below.
+ */
+static krb5_error_code
+kcm_stat(krb5_context context, const char *name)
+{
+ krb5_error_code ret;
+ krb5_storage *request = NULL;
+ krb5_data response_data;
+
+ krb5_data_zero(&response_data);
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_GET_PRINCIPAL, &request);
+ if (ret == 0)
+ ret = krb5_store_stringz(request, name);
+ if (ret == 0)
+ ret = krb5_kcm_call(context, request, NULL, &response_data);
+ krb5_storage_free(request);
+ krb5_data_free(&response_data);
+ return ret;
+}
+
+static krb5_error_code kcm_get_default_name(krb5_context,
+ const krb5_cc_ops *,
+ const char *, char **);
+
+static krb5_error_code
+kcm_alloc(krb5_context context,
+ const krb5_cc_ops *ops,
+ const char *residual,
+ const char *sub,
+ krb5_ccache *id)
+{
+ krb5_error_code ret;
+ krb5_kcmcache *k;
+ size_t ops_prefix_len = strlen(ops->prefix);
+ size_t plen = 0;
+ size_t local_def_name_len;
+ char *local_def_name = NULL; /* Our idea of default KCM cache name */
+ char *kcm_def_name = NULL; /* KCM's knowledge of default cache name */
+ int aret;
+
+ /* Get the KCM:%{UID} default */
+ if (ops == &krb5_kcm_ops)
+ ret = _krb5_expand_default_cc_name(context, KRB5_DEFAULT_CCNAME_KCM_KCM, &local_def_name);
+ else
+ ret = _krb5_expand_default_cc_name(context, KRB5_DEFAULT_CCNAME_KCM_API, &local_def_name);
+ if (ret)
+ return ret;
+ local_def_name_len = strlen(local_def_name);
+
+ /* Get the default ccache name from KCM if possible */
+ (void) kcm_get_default_name(context, ops, NULL, &kcm_def_name);
+
+ /*
+ * We have a sticky situation in that applications that call
+ * krb5_cc_default() will be getting the locally configured or compiled-in
+ * default KCM cache name, which may not exist in the user's KCM session,
+ * and which the KCM daemon may not be able to alias to the actual default
+ * for the user's session.
+ *
+ * To deal with this we heuristically detect when an application uses the
+ * default KCM ccache name.
+ *
+ * If the residual happens to be the local default KCM name we may end up
+ * using whatever the default KCM cache name is instead of the local
+ * default.
+ *
+ * Note that here `residual' may be any of:
+ *
+ * - %{UID}
+ * - %{UID}:
+ * - %{UID}:<subsidiary>
+ * - <something not starting with %{UID}:>
+ * - <empty string>
+ * - <NULL>
+ *
+ * Only the first two count as "maybe I mean the default KCM cache".
+ */
+ if (residual && !sub &&
+ strncmp(residual, local_def_name + ops_prefix_len + 1,
+ local_def_name_len - (ops_prefix_len + 1)) == 0) {
+ if (residual[local_def_name_len - (ops_prefix_len + 1)] == '\0' ||
+ (residual[local_def_name_len - (ops_prefix_len + 1)] == ':' &&
+ residual[local_def_name_len - ops_prefix_len] == '\0')) {
+ /*
+ * If we got a default cache name from KCM and the requested default
+ * cache does not exist, use the former.
+ */
+ if (kcm_def_name && kcm_stat(context, residual))
+ residual = kcm_def_name + ops_prefix_len + 1;
+ }
+ }
+
+ if (residual && residual[0] == '\0')
+ residual = NULL;
+ if (sub && sub[0] == '\0')
+ sub = NULL;
+
+ if (residual == NULL && sub == NULL) {
+ /* Use the default cache name, either from KCM or local default */
+ if (kcm_def_name)
+ residual = kcm_def_name + ops_prefix_len + 1;
+ else
+ residual = local_def_name + ops_prefix_len + 1;
+ }
+
+ if (residual) {
+ /* KCM cache names must start with {UID} or {UID}: */
+ if (residual[0] != '0')
+ plen = strspn(residual, "0123456789");
+ if (plen && residual[plen] != ':' && residual[plen] != '\0')
+ plen = 0;
+ /*
+ * If `plen', then residual is such a residual, else we'll want to
+ * prefix the {UID}:.
+ */
+ }
+
+ k = calloc(1, sizeof(*k));
+ if (k == NULL) {
+ free(local_def_name);
+ free(kcm_def_name);
+ return krb5_enomem(context);
+ }
+ k->name = NULL;
+
+ if (residual == NULL && sub == NULL) {
+ /* One more way to get a default */
+ aret = asprintf(&k->name, "%llu", (unsigned long long)getuid());
+ } else if (residual == NULL) {
+ /*
+ * Treat the subsidiary as the residual (maybe this will turn out to be
+ * wrong).
+ */
+ aret = asprintf(&k->name, "%llu:%s", (unsigned long long)getuid(),
+ sub);
+ } else if (plen) {
+ /* The residual is a UID */
+ aret = asprintf(&k->name, "%s%s%s", residual,
+ sub ? ":" : "", sub ? sub : "");
+ } else if (sub == NULL) {
+ /* The residual is NOT a UID */
+ aret = asprintf(&k->name, "%llu:%s", (unsigned long long)getuid(),
+ residual);
+ } else {
+ /* Ditto, plus we have a subsidiary. `residual && sub && !plen' */
+ aret = asprintf(&k->name, "%llu:%s:%s", (unsigned long long)getuid(),
+ residual, sub);
+ }
+ if (aret == -1 || k->name == NULL) {
+ free(local_def_name);
+ free(kcm_def_name);
+ free(k);
+ return krb5_enomem(context);
+ }
+
+ free(local_def_name);
+ free(kcm_def_name);
+ (*id)->data.data = k;
+ (*id)->data.length = sizeof(*k);
+
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kcm_call(krb5_context context,
+ krb5_storage *request,
+ krb5_storage **response_p,
+ krb5_data *response_data_p)
+{
+ krb5_data response_data;
+ krb5_error_code ret;
+ int32_t status;
+ krb5_storage *response;
+
+ if (response_p != NULL)
+ *response_p = NULL;
+
+ krb5_data_zero(&response_data);
+ ret = kcm_send_request(context, request, &response_data);
+ if (ret) {
+ krb5_data_free(&response_data);
+ return ret;
+ }
+
+ response = krb5_storage_from_data(&response_data);
+ if (response == NULL) {
+ krb5_data_free(&response_data);
+ return KRB5_CC_IO;
+ }
+
+ ret = krb5_ret_int32(response, &status);
+ if (ret) {
+ krb5_storage_free(response);
+ krb5_data_free(&response_data);
+ return KRB5_CC_FORMAT;
+ }
+
+ if (status) {
+ krb5_storage_free(response);
+ krb5_data_free(&response_data);
+ return status;
+ }
+
+ if (response_p != NULL) {
+ *response_data_p = response_data;
+ *response_p = response;
+
+ return 0;
+ }
+
+ krb5_storage_free(response);
+ krb5_data_free(&response_data);
+
+ return 0;
+}
+
+static void
+kcm_free(krb5_context context, krb5_ccache *id)
+{
+ krb5_kcmcache *k = KCMCACHE(*id);
+
+ if (k != NULL) {
+ free(k->name);
+ memset_s(k, sizeof(*k), 0, sizeof(*k));
+ krb5_data_free(&(*id)->data);
+ }
+}
+
+static krb5_error_code KRB5_CALLCONV
+kcm_get_name_2(krb5_context context,
+ krb5_ccache id,
+ const char **name,
+ const char **col,
+ const char **sub)
+{
+ /*
+ * TODO:
+ *
+ * - name should be <IPC-name>:<cache-name>
+ * - col should be <IPC-name>
+ * - sub should be <cache-name>
+ */
+ if (name)
+ *name = CACHENAME(id);
+ if (col)
+ *col = NULL;
+ if (sub)
+ *sub = CACHENAME(id);
+ return 0;
+}
+
+static krb5_error_code
+kcm_resolve_2_kcm(krb5_context context,
+ krb5_ccache *id,
+ const char *res,
+ const char *sub)
+{
+ /*
+ * For now, for KCM the `res' is the `sub'.
+ *
+ * TODO: We should use `res' as the IPC name instead of the one currently
+ * hard-coded in `kcm_ipc_name'.
+ */
+ return kcm_alloc(context, &krb5_kcm_ops, res, sub, id);
+}
+
+static krb5_error_code
+kcm_resolve_2_api(krb5_context context,
+ krb5_ccache *id,
+ const char *res,
+ const char *sub)
+{
+ /*
+ * For now, for KCM the `res' is the `sub'.
+ *
+ * TODO: We should use `res' as the IPC name instead of the one currently
+ * hard-coded in `kcm_ipc_name'.
+ */
+ return kcm_alloc(context, &krb5_akcm_ops, res, sub, id);
+}
+
+/*
+ * Request:
+ *
+ * Response:
+ * NameZ
+ */
+static krb5_error_code
+kcm_gen_new(krb5_context context, const krb5_cc_ops *ops, krb5_ccache *id)
+{
+ krb5_kcmcache *k;
+ krb5_error_code ret;
+ krb5_storage *request, *response;
+ krb5_data response_data;
+
+ ret = kcm_alloc(context, ops, NULL, NULL, id);
+ if (ret)
+ return ret;
+
+ k = KCMCACHE(*id);
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_GEN_NEW, &request);
+ if (ret) {
+ kcm_free(context, id);
+ return ret;
+ }
+
+ ret = krb5_kcm_call(context, request, &response, &response_data);
+ if (ret) {
+ krb5_storage_free(request);
+ kcm_free(context, id);
+ return ret;
+ }
+
+ free(k->name);
+ k->name = NULL;
+ ret = krb5_ret_stringz(response, &k->name);
+ if (ret)
+ ret = KRB5_CC_IO;
+
+ krb5_storage_free(request);
+ krb5_storage_free(response);
+ krb5_data_free(&response_data);
+
+ if (ret)
+ kcm_free(context, id);
+
+ return ret;
+}
+
+static krb5_error_code
+kcm_gen_new_kcm(krb5_context context, krb5_ccache *id)
+{
+ return kcm_gen_new(context, &krb5_kcm_ops, id);
+}
+
+static krb5_error_code
+kcm_gen_new_api(krb5_context context, krb5_ccache *id)
+{
+ return kcm_gen_new(context, &krb5_akcm_ops, id);
+}
+
+/*
+ * Request:
+ * NameZ
+ * Principal
+ *
+ * Response:
+ *
+ */
+static krb5_error_code
+kcm_initialize(krb5_context context,
+ krb5_ccache id,
+ krb5_principal primary_principal)
+{
+ krb5_error_code ret;
+ krb5_kcmcache *k = KCMCACHE(id);
+ krb5_storage *request;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_INITIALIZE, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, k->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_store_principal(request, primary_principal);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_kcm_call(context, request, NULL, NULL);
+
+ krb5_storage_free(request);
+
+ if (context->kdc_sec_offset)
+ kcm_set_kdc_offset(context, id, context->kdc_sec_offset);
+
+ return ret;
+}
+
+static krb5_error_code
+kcm_close(krb5_context context,
+ krb5_ccache id)
+{
+ kcm_free(context, &id);
+ return 0;
+}
+
+/*
+ * Request:
+ * NameZ
+ *
+ * Response:
+ *
+ */
+static krb5_error_code
+kcm_destroy(krb5_context context,
+ krb5_ccache id)
+{
+ krb5_error_code ret;
+ krb5_kcmcache *k = KCMCACHE(id);
+ krb5_storage *request;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_DESTROY, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, k->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_kcm_call(context, request, NULL, NULL);
+
+ krb5_storage_free(request);
+ return ret;
+}
+
+/*
+ * Request:
+ * NameZ
+ * Creds
+ *
+ * Response:
+ *
+ */
+static krb5_error_code
+kcm_store_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_creds *creds)
+{
+ krb5_error_code ret;
+ krb5_kcmcache *k = KCMCACHE(id);
+ krb5_storage *request;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_STORE, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, k->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_store_creds(request, creds);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_kcm_call(context, request, NULL, NULL);
+
+ krb5_storage_free(request);
+ return ret;
+}
+
+#if 0
+/*
+ * Request:
+ * NameZ
+ * WhichFields
+ * MatchCreds
+ *
+ * Response:
+ * Creds
+ *
+ */
+static krb5_error_code
+kcm_retrieve(krb5_context context,
+ krb5_ccache id,
+ krb5_flags which,
+ const krb5_creds *mcred,
+ krb5_creds *creds)
+{
+ krb5_error_code ret;
+ krb5_kcmcache *k = KCMCACHE(id);
+ krb5_storage *request, *response;
+ krb5_data response_data;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_RETRIEVE, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, k->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_store_int32(request, which);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_store_creds_tag(request, rk_UNCONST(mcred));
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_kcm_call(context, request, &response, &response_data);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_ret_creds(response, creds);
+ if (ret)
+ ret = KRB5_CC_IO;
+
+ krb5_storage_free(request);
+ krb5_storage_free(response);
+ krb5_data_free(&response_data);
+
+ return ret;
+}
+#endif
+
+/*
+ * Request:
+ * NameZ
+ *
+ * Response:
+ * Principal
+ */
+static krb5_error_code
+kcm_get_principal(krb5_context context,
+ krb5_ccache id,
+ krb5_principal *principal)
+{
+ krb5_error_code ret;
+ krb5_kcmcache *k = KCMCACHE(id);
+ krb5_storage *request, *response;
+ krb5_data response_data;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_GET_PRINCIPAL, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, k->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_kcm_call(context, request, &response, &response_data);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_ret_principal(response, principal);
+ if (ret)
+ ret = KRB5_CC_IO;
+
+ krb5_storage_free(request);
+ krb5_storage_free(response);
+ krb5_data_free(&response_data);
+
+ return ret;
+}
+
+/*
+ * Request:
+ * NameZ
+ *
+ * Response:
+ * Cursor
+ *
+ */
+static krb5_error_code
+kcm_get_first (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+ krb5_error_code ret;
+ krb5_kcm_cursor c;
+ krb5_kcmcache *k = KCMCACHE(id);
+ krb5_storage *request, *response;
+ krb5_data response_data;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_GET_CRED_UUID_LIST, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, k->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_kcm_call(context, request, &response, &response_data);
+ krb5_storage_free(request);
+ if (ret)
+ return ret;
+
+ c = calloc(1, sizeof(*c));
+ if (c == NULL) {
+ ret = krb5_enomem(context);
+ return ret;
+ }
+
+ while (1) {
+ ssize_t sret;
+ kcmuuid_t uuid;
+ void *ptr;
+
+ sret = krb5_storage_read(response, &uuid, sizeof(uuid));
+ if (sret == 0) {
+ ret = 0;
+ break;
+ } else if (sret != sizeof(uuid)) {
+ ret = EINVAL;
+ break;
+ }
+
+ ptr = realloc(c->uuids, sizeof(c->uuids[0]) * (c->length + 1));
+ if (ptr == NULL) {
+ free(c->uuids);
+ free(c);
+ return krb5_enomem(context);
+ }
+ c->uuids = ptr;
+
+ memcpy(&c->uuids[c->length], &uuid, sizeof(uuid));
+ c->length += 1;
+ }
+
+ krb5_storage_free(response);
+ krb5_data_free(&response_data);
+
+ if (ret) {
+ free(c->uuids);
+ free(c);
+ return ret;
+ }
+
+ *cursor = c;
+
+ return 0;
+}
+
+/*
+ * Request:
+ * NameZ
+ * Cursor
+ *
+ * Response:
+ * Creds
+ */
+static krb5_error_code
+kcm_get_next (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor,
+ krb5_creds *creds)
+{
+ krb5_error_code ret;
+ krb5_kcmcache *k = KCMCACHE(id);
+ krb5_kcm_cursor c = KCMCURSOR(*cursor);
+ krb5_storage *request, *response;
+ krb5_data response_data;
+ ssize_t sret;
+
+ again:
+
+ if (c->offset >= c->length)
+ return KRB5_CC_END;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_GET_CRED_BY_UUID, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, k->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ sret = krb5_storage_write(request,
+ &c->uuids[c->offset],
+ sizeof(c->uuids[c->offset]));
+ c->offset++;
+ if (sret != sizeof(c->uuids[c->offset])) {
+ krb5_storage_free(request);
+ return krb5_enomem(context);
+ }
+
+ ret = krb5_kcm_call(context, request, &response, &response_data);
+ krb5_storage_free(request);
+ if (ret == KRB5_CC_END) {
+ goto again;
+ } else if (ret)
+ return ret;
+
+ ret = krb5_ret_creds(response, creds);
+ if (ret)
+ ret = KRB5_CC_IO;
+
+ krb5_storage_free(response);
+ krb5_data_free(&response_data);
+
+ return ret;
+}
+
+/*
+ * Request:
+ * NameZ
+ * Cursor
+ *
+ * Response:
+ *
+ */
+static krb5_error_code
+kcm_end_get (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+ krb5_kcm_cursor c = KCMCURSOR(*cursor);
+
+ free(c->uuids);
+ free(c);
+
+ *cursor = NULL;
+
+ return 0;
+}
+
+/*
+ * Request:
+ * NameZ
+ * WhichFields
+ * MatchCreds
+ *
+ * Response:
+ *
+ */
+static krb5_error_code
+kcm_remove_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_flags which,
+ krb5_creds *cred)
+{
+ krb5_error_code ret;
+ krb5_kcmcache *k = KCMCACHE(id);
+ krb5_storage *request;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_REMOVE_CRED, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, k->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_store_int32(request, which);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_store_creds_tag(request, cred);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_kcm_call(context, request, NULL, NULL);
+
+ krb5_storage_free(request);
+ return ret;
+}
+
+static krb5_error_code
+kcm_set_flags(krb5_context context,
+ krb5_ccache id,
+ krb5_flags flags)
+{
+ krb5_error_code ret;
+ krb5_kcmcache *k = KCMCACHE(id);
+ krb5_storage *request;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_SET_FLAGS, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, k->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_store_int32(request, flags);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_kcm_call(context, request, NULL, NULL);
+
+ krb5_storage_free(request);
+ return ret;
+}
+
+static int
+kcm_get_version(krb5_context context,
+ krb5_ccache id)
+{
+ return 0;
+}
+
+/*
+ * Send nothing
+ * get back list of uuids
+ */
+
+static krb5_error_code
+kcm_get_cache_first(krb5_context context, krb5_cc_cursor *cursor)
+{
+ krb5_error_code ret;
+ krb5_kcm_cursor c;
+ krb5_storage *request, *response;
+ krb5_data response_data;
+
+ *cursor = NULL;
+
+ c = calloc(1, sizeof(*c));
+ if (c == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_GET_CACHE_UUID_LIST, &request);
+ if (ret)
+ goto out;
+
+ ret = krb5_kcm_call(context, request, &response, &response_data);
+ krb5_storage_free(request);
+ if (ret)
+ goto out;
+
+ while (1) {
+ ssize_t sret;
+ kcmuuid_t uuid;
+ void *ptr;
+
+ sret = krb5_storage_read(response, &uuid, sizeof(uuid));
+ if (sret == 0) {
+ ret = 0;
+ break;
+ } else if (sret != sizeof(uuid)) {
+ ret = EINVAL;
+ goto out;
+ }
+
+ ptr = realloc(c->uuids, sizeof(c->uuids[0]) * (c->length + 1));
+ if (ptr == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ c->uuids = ptr;
+
+ memcpy(&c->uuids[c->length], &uuid, sizeof(uuid));
+ c->length += 1;
+ }
+
+ krb5_storage_free(response);
+ krb5_data_free(&response_data);
+
+ out:
+ if (ret && c) {
+ free(c->uuids);
+ free(c);
+ } else
+ *cursor = c;
+
+ return ret;
+}
+
+/*
+ * Send uuid
+ * Recv cache name
+ */
+
+static krb5_error_code
+kcm_get_cache_next(krb5_context context, krb5_cc_cursor cursor, const krb5_cc_ops *ops, krb5_ccache *id)
+{
+ krb5_error_code ret;
+ krb5_kcm_cursor c = KCMCURSOR(cursor);
+ krb5_storage *request, *response;
+ krb5_data response_data;
+ ssize_t sret;
+ char *name;
+
+ *id = NULL;
+
+ again:
+
+ if (c->offset >= c->length)
+ return KRB5_CC_END;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_GET_CACHE_BY_UUID, &request);
+ if (ret)
+ return ret;
+
+ sret = krb5_storage_write(request,
+ &c->uuids[c->offset],
+ sizeof(c->uuids[c->offset]));
+ c->offset++;
+ if (sret != sizeof(c->uuids[c->offset])) {
+ krb5_storage_free(request);
+ return krb5_enomem(context);
+ }
+
+ ret = krb5_kcm_call(context, request, &response, &response_data);
+ krb5_storage_free(request);
+ if (ret == KRB5_CC_END)
+ goto again;
+ else if (ret)
+ return ret;
+
+ ret = krb5_ret_stringz(response, &name);
+ krb5_storage_free(response);
+ krb5_data_free(&response_data);
+
+ if (ret == 0) {
+ ret = _krb5_cc_allocate(context, ops, id);
+ if (ret == 0)
+ ret = kcm_alloc(context, ops, name, NULL, id);
+ krb5_xfree(name);
+ }
+
+ return ret;
+}
+
+static krb5_error_code
+kcm_get_cache_next_kcm(krb5_context context, krb5_cc_cursor cursor, krb5_ccache *id)
+{
+#ifndef KCM_IS_API_CACHE
+ return kcm_get_cache_next(context, cursor, &krb5_kcm_ops, id);
+#else
+ return KRB5_CC_END;
+#endif
+}
+
+static krb5_error_code
+kcm_get_cache_next_api(krb5_context context, krb5_cc_cursor cursor, krb5_ccache *id)
+{
+ return kcm_get_cache_next(context, cursor, &krb5_akcm_ops, id);
+}
+
+
+static krb5_error_code
+kcm_end_cache_get(krb5_context context, krb5_cc_cursor cursor)
+{
+ krb5_kcm_cursor c = KCMCURSOR(cursor);
+
+ free(c->uuids);
+ free(c);
+ return 0;
+}
+
+
+static krb5_error_code
+kcm_move(krb5_context context, krb5_ccache from, krb5_ccache to)
+{
+ krb5_error_code ret;
+ krb5_kcmcache *oldk = KCMCACHE(from);
+ krb5_kcmcache *newk = KCMCACHE(to);
+ krb5_storage *request;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_MOVE_CACHE, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, oldk->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_store_stringz(request, newk->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+ ret = krb5_kcm_call(context, request, NULL, NULL);
+
+ krb5_storage_free(request);
+
+ if (ret == 0)
+ krb5_cc_destroy(context, from);
+ return ret;
+}
+
+static krb5_error_code
+kcm_get_default_name(krb5_context context, const krb5_cc_ops *ops,
+ const char *defstr, char **str)
+{
+ krb5_error_code ret;
+ krb5_storage *request, *response;
+ krb5_data response_data;
+ char *name;
+ int aret;
+
+ *str = NULL;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_GET_DEFAULT_CACHE, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_kcm_call(context, request, &response, &response_data);
+ krb5_storage_free(request);
+ if (ret) {
+ if (defstr)
+ return _krb5_expand_default_cc_name(context, defstr, str);
+ return ret;
+ }
+
+ ret = krb5_ret_stringz(response, &name);
+ krb5_storage_free(response);
+ krb5_data_free(&response_data);
+ if (ret)
+ return ret;
+
+ aret = asprintf(str, "%s:%s", ops->prefix, name);
+ free(name);
+ if (aret == -1 || *str == NULL)
+ return krb5_enomem(context);
+
+ return 0;
+}
+
+static krb5_error_code
+kcm_get_default_name_api(krb5_context context, char **str)
+{
+ return kcm_get_default_name(context, &krb5_akcm_ops,
+ KRB5_DEFAULT_CCNAME_KCM_API, str);
+}
+
+static krb5_error_code
+kcm_get_default_name_kcm(krb5_context context, char **str)
+{
+ return kcm_get_default_name(context, &krb5_kcm_ops,
+ KRB5_DEFAULT_CCNAME_KCM_KCM, str);
+}
+
+static krb5_error_code
+kcm_set_default(krb5_context context, krb5_ccache id)
+{
+ krb5_error_code ret;
+ krb5_storage *request;
+ krb5_kcmcache *k = KCMCACHE(id);
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_SET_DEFAULT_CACHE, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, k->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_kcm_call(context, request, NULL, NULL);
+ krb5_storage_free(request);
+
+ return ret;
+}
+
+static krb5_error_code
+kcm_lastchange(krb5_context context, krb5_ccache id, krb5_timestamp *mtime)
+{
+ *mtime = time(NULL);
+ return 0;
+}
+
+static krb5_error_code
+kcm_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat kdc_offset)
+{
+ krb5_kcmcache *k = KCMCACHE(id);
+ krb5_error_code ret;
+ krb5_storage *request;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_SET_KDC_OFFSET, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, k->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+ ret = krb5_store_int32(request, kdc_offset);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_kcm_call(context, request, NULL, NULL);
+ krb5_storage_free(request);
+
+ return ret;
+}
+
+static krb5_error_code
+kcm_get_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat *kdc_offset)
+{
+ krb5_kcmcache *k = KCMCACHE(id);
+ krb5_error_code ret;
+ krb5_storage *request, *response;
+ krb5_data response_data;
+ int32_t offset;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_GET_KDC_OFFSET, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, k->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_kcm_call(context, request, &response, &response_data);
+ krb5_storage_free(request);
+ if (ret)
+ return ret;
+
+ ret = krb5_ret_int32(response, &offset);
+ krb5_storage_free(response);
+ krb5_data_free(&response_data);
+ if (ret)
+ return ret;
+
+ *kdc_offset = offset;
+
+ return 0;
+}
+
+/**
+ * Variable containing the KCM based credential cache implemention.
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_VARIABLE const krb5_cc_ops krb5_kcm_ops = {
+ KRB5_CC_OPS_VERSION_5,
+ "KCM",
+ NULL,
+ NULL,
+ kcm_gen_new_kcm,
+ kcm_initialize,
+ kcm_destroy,
+ kcm_close,
+ kcm_store_cred,
+ NULL /* kcm_retrieve */,
+ kcm_get_principal,
+ kcm_get_first,
+ kcm_get_next,
+ kcm_end_get,
+ kcm_remove_cred,
+ kcm_set_flags,
+ kcm_get_version,
+ kcm_get_cache_first,
+ kcm_get_cache_next_kcm,
+ kcm_end_cache_get,
+ kcm_move,
+ kcm_get_default_name_kcm,
+ kcm_set_default,
+ kcm_lastchange,
+ kcm_set_kdc_offset,
+ kcm_get_kdc_offset,
+ kcm_get_name_2,
+ kcm_resolve_2_kcm
+};
+
+KRB5_LIB_VARIABLE const krb5_cc_ops krb5_akcm_ops = {
+ KRB5_CC_OPS_VERSION_5,
+ "API",
+ NULL,
+ NULL,
+ kcm_gen_new_api,
+ kcm_initialize,
+ kcm_destroy,
+ kcm_close,
+ kcm_store_cred,
+ NULL /* kcm_retrieve */,
+ kcm_get_principal,
+ kcm_get_first,
+ kcm_get_next,
+ kcm_end_get,
+ kcm_remove_cred,
+ kcm_set_flags,
+ kcm_get_version,
+ kcm_get_cache_first,
+ kcm_get_cache_next_api,
+ kcm_end_cache_get,
+ kcm_move,
+ kcm_get_default_name_api,
+ kcm_set_default,
+ kcm_lastchange,
+ NULL,
+ NULL,
+ kcm_get_name_2,
+ kcm_resolve_2_api
+};
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+_krb5_kcm_is_running(krb5_context context)
+{
+ krb5_error_code ret;
+ krb5_ccache_data ccdata;
+ krb5_ccache id = &ccdata;
+ krb5_boolean running;
+
+ ret = kcm_alloc(context, NULL, NULL, NULL, &id);
+ if (ret)
+ return 0;
+
+ running = (_krb5_kcm_noop(context, id) == 0);
+
+ kcm_free(context, &id);
+
+ return running;
+}
+
+/*
+ * Request:
+ *
+ * Response:
+ *
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_kcm_noop(krb5_context context,
+ krb5_ccache id)
+{
+ krb5_error_code ret;
+ krb5_storage *request;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_NOOP, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_kcm_call(context, request, NULL, NULL);
+
+ krb5_storage_free(request);
+ return ret;
+}
+
+
+/*
+ * Request:
+ * NameZ
+ * ServerPrincipalPresent
+ * ServerPrincipal OPTIONAL
+ * Key
+ *
+ * Repsonse:
+ *
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_kcm_get_initial_ticket(krb5_context context,
+ krb5_ccache id,
+ krb5_principal server,
+ krb5_keyblock *key)
+{
+ krb5_kcmcache *k = KCMCACHE(id);
+ krb5_error_code ret;
+ krb5_storage *request;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_GET_INITIAL_TICKET, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, k->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_store_int8(request, (server == NULL) ? 0 : 1);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ if (server != NULL) {
+ ret = krb5_store_principal(request, server);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+ }
+
+ ret = krb5_store_keyblock(request, *key);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_kcm_call(context, request, NULL, NULL);
+
+ krb5_storage_free(request);
+ return ret;
+}
+
+
+/*
+ * Request:
+ * NameZ
+ * KDCFlags
+ * EncryptionType
+ * ServerPrincipal
+ *
+ * Repsonse:
+ *
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_kcm_get_ticket(krb5_context context,
+ krb5_ccache id,
+ krb5_kdc_flags flags,
+ krb5_enctype enctype,
+ krb5_principal server)
+{
+ krb5_error_code ret;
+ krb5_kcmcache *k = KCMCACHE(id);
+ krb5_storage *request;
+
+ ret = krb5_kcm_storage_request(context, KCM_OP_GET_TICKET, &request);
+ if (ret)
+ return ret;
+
+ ret = krb5_store_stringz(request, k->name);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_store_int32(request, flags.i);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_store_int32(request, enctype);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_store_principal(request, server);
+ if (ret) {
+ krb5_storage_free(request);
+ return ret;
+ }
+
+ ret = krb5_kcm_call(context, request, NULL, NULL);
+
+ krb5_storage_free(request);
+ return ret;
+}
+
+#endif /* HAVE_KCM */
diff --git a/third_party/heimdal/lib/krb5/kcm.h b/third_party/heimdal/lib/krb5/kcm.h
new file mode 100644
index 0000000..ba484b9
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/kcm.h
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2005, PADL Software Pty Ltd.
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of PADL Software nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef __KCM_H__
+#define __KCM_H__
+
+/*
+ * KCM protocol definitions
+ */
+
+#define KCM_PROTOCOL_VERSION_MAJOR 2
+#define KCM_PROTOCOL_VERSION_MINOR 0
+
+typedef unsigned char kcmuuid_t[16];
+
+typedef enum kcm_operation {
+ KCM_OP_NOOP,
+ KCM_OP_GET_NAME,
+ KCM_OP_RESOLVE,
+ KCM_OP_GEN_NEW,
+ KCM_OP_INITIALIZE,
+ KCM_OP_DESTROY,
+ KCM_OP_STORE,
+ KCM_OP_RETRIEVE,
+ KCM_OP_GET_PRINCIPAL,
+ KCM_OP_GET_CRED_UUID_LIST,
+ KCM_OP_GET_CRED_BY_UUID,
+ KCM_OP_REMOVE_CRED,
+ KCM_OP_SET_FLAGS,
+ KCM_OP_CHOWN,
+ KCM_OP_CHMOD,
+ KCM_OP_GET_INITIAL_TICKET,
+ KCM_OP_GET_TICKET,
+ KCM_OP_MOVE_CACHE,
+ KCM_OP_GET_CACHE_UUID_LIST,
+ KCM_OP_GET_CACHE_BY_UUID,
+ KCM_OP_GET_DEFAULT_CACHE,
+ KCM_OP_SET_DEFAULT_CACHE,
+ KCM_OP_GET_KDC_OFFSET,
+ KCM_OP_SET_KDC_OFFSET,
+ /* NTLM operations */
+ KCM_OP_ADD_NTLM_CRED,
+ KCM_OP_HAVE_NTLM_CRED,
+ KCM_OP_DEL_NTLM_CRED,
+ KCM_OP_DO_NTLM_AUTH,
+ KCM_OP_GET_NTLM_USER_LIST,
+ KCM_OP_MAX
+} kcm_operation;
+
+#define KCM_NTLM_FLAG_SESSIONKEY 1
+#define KCM_NTLM_FLAG_NTLM2_SESSION 2
+#define KCM_NTLM_FLAG_KEYEX 4
+#define KCM_NTLM_FLAG_AV_GUEST 8
+
+#endif /* __KCM_H__ */
+
diff --git a/third_party/heimdal/lib/krb5/kerberos.8 b/third_party/heimdal/lib/krb5/kerberos.8
new file mode 100644
index 0000000..fdcea04
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/kerberos.8
@@ -0,0 +1,115 @@
+.\" Copyright (c) 2000 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd Jun 27, 2013
+.Dt KERBEROS 8
+.Os HEIMDAL
+.Sh NAME
+.Nm kerberos
+.Nd introduction to the Kerberos system
+.Sh DESCRIPTION
+Kerberos is a network authentication system. Its purpose is to
+securely authenticate users and services in an insecure network
+environment.
+.Pp
+This is done with a Kerberos server acting as a trusted third party,
+keeping a database with secret keys for all users and services
+(collectively called
+.Em principals ) .
+.Pp
+Each principal belongs to exactly one
+.Em realm ,
+which is the administrative domain in Kerberos. A realm usually
+corresponds to an organisation, and the realm should normally be
+derived from that organisation's domain name. A realm is served by one
+or more Kerberos servers.
+.Pp
+The authentication process involves exchange of
+.Sq tickets
+and
+.Sq authenticators
+which together prove the principal's identity.
+.Pp
+When you login to the Kerberos system, either through the normal
+system login or with the
+.Xr kinit 1
+program, you acquire a
+.Em ticket granting ticket
+which allows you to get new tickets for other services, such as
+.Ic telnet
+or
+.Ic ftp ,
+without giving your password.
+.Pp
+For more information on how Kerberos works, see the tutorial at
+.Lk https://kerberos.org/software/tutorial.html
+or the informal
+.Dq dialogue
+at
+.Lk https://web.mit.edu/kerberos/dialogue.html .
+.Pp
+For setup instructions see the Heimdal Texinfo manual.
+.Sh SEE ALSO
+.Xr ftp 1 ,
+.Xr kdestroy 1 ,
+.Xr kinit 1 ,
+.Xr klist 1 ,
+.Xr kpasswd 1 ,
+.Xr telnet 1 ,
+.Xr krb5 3 ,
+.Xr krb5.conf 5 ,
+.Xr kadmin 1 ,
+.Xr kdc 8 ,
+.Xr ktutil 1
+.Sh HISTORY
+The Kerberos authentication system was developed in the late 1980's as
+part of the Athena Project at the Massachusetts Institute of
+Technology. Versions one through three never reached outside MIT, but
+version 4 was (and still is) quite popular, especially in the academic
+community, but is also used in commercial products like the AFS
+filesystem.
+.Pp
+The problems with version 4 are that it has many limitations, the code
+was not too well written (since it had been developed over a long
+time), and it has a number of known security problems. To resolve many
+of these issues work on version five started, and resulted in IETF RFC
+1510 in 1993. IETF RFC 1510 was obsoleted in 2005 with IETF RFC 4120,
+also known as Kerberos clarifications. With the arrival of IETF RFC
+4120, the work on adding extensibility and internationalization have
+started (Kerberos extensions), and a new RFC will hopefully appear
+soon.
+.Pp
+This manual page is part of the
+.Nm Heimdal
+Kerberos 5 distribution, which has been in development at the Royal
+Institute of Technology in Stockholm, Sweden, since about 1997.
diff --git a/third_party/heimdal/lib/krb5/keyblock.c b/third_party/heimdal/lib/krb5/keyblock.c
new file mode 100644
index 0000000..317bed3
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/keyblock.c
@@ -0,0 +1,203 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ * Zero out a keyblock
+ *
+ * @param keyblock keyblock to zero out
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_keyblock_zero(krb5_keyblock *keyblock)
+{
+ keyblock->keytype = 0;
+ krb5_data_zero(&keyblock->keyvalue);
+}
+
+/**
+ * Free a keyblock's content, also zero out the content of the keyblock.
+ *
+ * @param context a Kerberos 5 context
+ * @param keyblock keyblock content to free, NULL is valid argument
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_keyblock_contents(krb5_context context,
+ krb5_keyblock *keyblock)
+{
+ if(keyblock) {
+ if (keyblock->keyvalue.data != NULL)
+ memset_s(keyblock->keyvalue.data, keyblock->keyvalue.length,
+ 0, keyblock->keyvalue.length);
+ krb5_data_free (&keyblock->keyvalue);
+ keyblock->keytype = KRB5_ENCTYPE_NULL;
+ }
+}
+
+/**
+ * Free a keyblock, also zero out the content of the keyblock, uses
+ * krb5_free_keyblock_contents() to free the content.
+ *
+ * @param context a Kerberos 5 context
+ * @param keyblock keyblock to free, NULL is valid argument
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_keyblock(krb5_context context,
+ krb5_keyblock *keyblock)
+{
+ if(keyblock){
+ krb5_free_keyblock_contents(context, keyblock);
+ free(keyblock);
+ }
+}
+
+/**
+ * Copy a keyblock, free the output keyblock with
+ * krb5_free_keyblock_contents().
+ *
+ * @param context a Kerberos 5 context
+ * @param inblock the key to copy
+ * @param to the output key.
+ *
+ * @return 0 on success or a Kerberos 5 error code
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_keyblock_contents (krb5_context context,
+ const krb5_keyblock *inblock,
+ krb5_keyblock *to)
+{
+ return copy_EncryptionKey(inblock, to);
+}
+
+/**
+ * Copy a keyblock, free the output keyblock with
+ * krb5_free_keyblock().
+ *
+ * @param context a Kerberos 5 context
+ * @param inblock the key to copy
+ * @param to the output key.
+ *
+ * @return 0 on success or a Kerberos 5 error code
+ *
+ * @ingroup krb5_crypto
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_keyblock (krb5_context context,
+ const krb5_keyblock *inblock,
+ krb5_keyblock **to)
+{
+ krb5_error_code ret;
+ krb5_keyblock *k;
+
+ *to = NULL;
+
+ k = calloc (1, sizeof(*k));
+ if (k == NULL)
+ return krb5_enomem(context);
+
+ ret = krb5_copy_keyblock_contents (context, inblock, k);
+ if (ret) {
+ free(k);
+ return ret;
+ }
+ *to = k;
+ return 0;
+}
+
+/**
+ * Get encryption type of a keyblock.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_enctype KRB5_LIB_CALL
+krb5_keyblock_get_enctype(const krb5_keyblock *block)
+{
+ return block->keytype;
+}
+
+/**
+ * Fill in `key' with key data of type `enctype' from `data' of length
+ * `size'. Key should be freed using krb5_free_keyblock_contents().
+ *
+ * @return 0 on success or a Kerberos 5 error code
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_keyblock_init(krb5_context context,
+ krb5_enctype type,
+ const void *data,
+ size_t size,
+ krb5_keyblock *key)
+{
+ krb5_error_code ret;
+ size_t len;
+
+ memset(key, 0, sizeof(*key));
+
+ ret = krb5_enctype_keysize(context, type, &len);
+ if (ret)
+ return ret;
+
+ if (len != size) {
+ krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+ "Encryption key %d is %lu bytes "
+ "long, %lu was passed in",
+ type, (unsigned long)len, (unsigned long)size);
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ ret = krb5_data_copy(&key->keyvalue, data, len);
+ if(ret) {
+ krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+ return ret;
+ }
+ key->keytype = type;
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/keytab.c b/third_party/heimdal/lib/krb5/keytab.c
new file mode 100644
index 0000000..559d640
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/keytab.c
@@ -0,0 +1,975 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ * @page krb5_keytab_intro The keytab handing functions
+ * @section section_krb5_keytab Kerberos Keytabs
+ *
+ * See the library functions here: @ref krb5_keytab
+ *
+ * Keytabs are long term key storage for servers, their equvalment of
+ * password files.
+ *
+ * Normally the only function that useful for server are to specify
+ * what keytab to use to other core functions like krb5_rd_req()
+ * krb5_kt_resolve(), and krb5_kt_close().
+ *
+ * @subsection krb5_keytab_names Keytab names
+ *
+ * A keytab name is on the form type:residual. The residual part is
+ * specific to each keytab-type.
+ *
+ * When a keytab-name is resolved, the type is matched with an internal
+ * list of keytab types. If there is no matching keytab type,
+ * the default keytab is used. The current default type is FILE.
+ *
+ * The default value can be changed in the configuration file
+ * /etc/krb5.conf by setting the variable
+ * [defaults]default_keytab_name.
+ *
+ * The keytab types that are implemented in Heimdal are:
+ * - file
+ * store the keytab in a file, the type's name is FILE . The
+ * residual part is a filename. For compatibility with other
+ * Kerberos implemtation WRFILE and JAVA14 is also accepted. WRFILE
+ * has the same format as FILE. JAVA14 have a format that is
+ * compatible with older versions of MIT kerberos and SUN's Java
+ * based installation. They store a truncted kvno, so when the knvo
+ * excess 255, they are truncted in this format.
+ *
+ * - keytab
+ * store the keytab in a AFS keyfile (usually /usr/afs/etc/KeyFile ),
+ * the type's name is AFSKEYFILE. The residual part is a filename.
+ *
+ * - memory
+ * The keytab is stored in a memory segment. This allows sensitive
+ * and/or temporary data not to be stored on disk. The type's name
+ * is MEMORY. Each MEMORY keytab is referenced counted by and
+ * opened by the residual name, so two handles can point to the
+ * same memory area. When the last user closes using krb5_kt_close()
+ * the keytab, the keys in they keytab is memset() to zero and freed
+ * and can no longer be looked up by name.
+ *
+ *
+ * @subsection krb5_keytab_example Keytab example
+ *
+ * This is a minimalistic version of ktutil.
+ *
+ * @code
+int
+main (int argc, char **argv)
+{
+ krb5_context context;
+ krb5_keytab keytab;
+ krb5_kt_cursor cursor;
+ krb5_keytab_entry entry;
+ krb5_error_code ret;
+ char *principal;
+
+ if (krb5_init_context (&context) != 0)
+ errx(1, "krb5_context");
+
+ ret = krb5_kt_default (context, &keytab);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_default");
+
+ ret = krb5_kt_start_seq_get(context, keytab, &cursor);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_start_seq_get");
+ while((ret = krb5_kt_next_entry(context, keytab, &entry, &cursor)) == 0){
+ krb5_unparse_name(context, entry.principal, &principal);
+ printf("principal: %s\n", principal);
+ free(principal);
+ krb5_kt_free_entry(context, &entry);
+ }
+ ret = krb5_kt_end_seq_get(context, keytab, &cursor);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_end_seq_get");
+ ret = krb5_kt_close(context, keytab);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_close");
+ krb5_free_context(context);
+ return 0;
+}
+ * @endcode
+ *
+ */
+
+
+/**
+ * Register a new keytab backend.
+ *
+ * @param context a Keberos context.
+ * @param ops a backend to register.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_register(krb5_context context,
+ const krb5_kt_ops *ops)
+{
+ struct krb5_keytab_data *tmp;
+
+ if (strlen(ops->prefix) > KRB5_KT_PREFIX_MAX_LEN - 1) {
+ krb5_set_error_message(context, KRB5_KT_BADNAME,
+ N_("can't register cache type, prefix too long", ""));
+ return KRB5_KT_BADNAME;
+ }
+
+ tmp = realloc(context->kt_types,
+ (context->num_kt_types + 1) * sizeof(*context->kt_types));
+ if(tmp == NULL)
+ return krb5_enomem(context);
+ memcpy(&tmp[context->num_kt_types], ops,
+ sizeof(tmp[context->num_kt_types]));
+ context->kt_types = tmp;
+ context->num_kt_types++;
+ return 0;
+}
+
+static const char *
+keytab_name(const char *name, const char **type, size_t *type_len)
+{
+ const char *residual;
+
+ residual = strchr(name, ':');
+
+ if (residual == NULL ||
+ ISPATHSEP(name[0])
+#ifdef _WIN32
+ /* Avoid treating <drive>:<path> as a keytab type
+ * specification */
+ || name + 1 == residual
+#endif
+ ) {
+
+ *type = "FILE";
+ *type_len = strlen(*type);
+ residual = name;
+ } else {
+ *type = name;
+ *type_len = residual - name;
+ residual++;
+ }
+
+ return residual;
+}
+
+/**
+ * Resolve the keytab name (of the form `type:residual') in `name'
+ * into a keytab in `id'.
+ *
+ * @param context a Keberos context.
+ * @param name name to resolve
+ * @param id resulting keytab, free with krb5_kt_close().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_resolve(krb5_context context,
+ const char *name,
+ krb5_keytab *id)
+{
+ krb5_keytab k;
+ int i;
+ const char *type, *residual;
+ size_t type_len;
+ krb5_error_code ret;
+
+ residual = keytab_name(name, &type, &type_len);
+
+ for(i = 0; i < context->num_kt_types; i++) {
+ if(strncasecmp(type, context->kt_types[i].prefix, type_len) == 0)
+ break;
+ }
+ if(i == context->num_kt_types) {
+ krb5_set_error_message(context, KRB5_KT_UNKNOWN_TYPE,
+ N_("unknown keytab type %.*s", "type"),
+ (int)type_len, type);
+ return KRB5_KT_UNKNOWN_TYPE;
+ }
+
+ k = malloc (sizeof(*k));
+ if (k == NULL)
+ return krb5_enomem(context);
+ memcpy(k, &context->kt_types[i], sizeof(*k));
+ k->data = NULL;
+ ret = (*k->resolve)(context, residual, k);
+ if(ret) {
+ free(k);
+ k = NULL;
+ }
+ *id = k;
+ return ret;
+}
+
+/*
+ * Default ktname from context with possible environment
+ * override
+ */
+static const char *default_ktname(krb5_context context)
+{
+ const char *tmp = NULL;
+
+ tmp = secure_getenv("KRB5_KTNAME");
+ if(tmp != NULL)
+ return tmp;
+ return context->default_keytab;
+}
+
+/**
+ * copy the name of the default keytab into `name'.
+ *
+ * @param context a Keberos context.
+ * @param name buffer where the name will be written
+ * @param namesize length of name
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_default_name(krb5_context context, char *name, size_t namesize)
+{
+ if (strlcpy (name, default_ktname(context), namesize) >= namesize) {
+ krb5_clear_error_message (context);
+ return KRB5_CONFIG_NOTENUFSPACE;
+ }
+ return 0;
+}
+
+/**
+ * Copy the name of the default modify keytab into `name'.
+ *
+ * @param context a Keberos context.
+ * @param name buffer where the name will be written
+ * @param namesize length of name
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_default_modify_name(krb5_context context, char *name, size_t namesize)
+{
+ const char *kt;
+
+ if(context->default_keytab_modify == NULL) {
+ kt = default_ktname(context);
+
+ if (strncasecmp(kt, "ANY:", 4) == 0) {
+ size_t len = strcspn(kt + 4, ",");
+ if (len >= namesize) {
+ krb5_clear_error_message(context);
+ return KRB5_CONFIG_NOTENUFSPACE;
+ }
+ strlcpy(name, kt + 4, namesize);
+ name[len] = '\0';
+ return 0;
+ }
+ } else
+ kt = context->default_keytab_modify;
+ if (strlcpy (name, kt, namesize) >= namesize) {
+ krb5_clear_error_message (context);
+ return KRB5_CONFIG_NOTENUFSPACE;
+ }
+ return 0;
+}
+
+/**
+ * Set `id' to the default keytab.
+ *
+ * @param context a Keberos context.
+ * @param id the new default keytab.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_default(krb5_context context, krb5_keytab *id)
+{
+ return krb5_kt_resolve (context, default_ktname(context), id);
+}
+
+/**
+ * Read the key identified by `(principal, vno, enctype)' from the
+ * keytab in `keyprocarg' (the default if == NULL) into `*key'.
+ *
+ * @param context a Keberos context.
+ * @param keyprocarg
+ * @param principal
+ * @param vno
+ * @param enctype
+ * @param key
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_read_service_key(krb5_context context,
+ krb5_pointer keyprocarg,
+ krb5_principal principal,
+ krb5_kvno vno,
+ krb5_enctype enctype,
+ krb5_keyblock **key)
+{
+ krb5_keytab keytab = NULL; /* Quiet lint */
+ krb5_keytab_entry entry;
+ krb5_error_code ret;
+
+ memset(&entry, 0, sizeof(entry));
+ if (keyprocarg)
+ ret = krb5_kt_resolve (context, keyprocarg, &keytab);
+ else
+ ret = krb5_kt_default (context, &keytab);
+
+ if (ret)
+ return ret;
+
+ ret = krb5_kt_get_entry (context, keytab, principal, vno, enctype, &entry);
+ if (ret == 0) {
+ ret = krb5_copy_keyblock (context, &entry.keyblock, key);
+ krb5_kt_free_entry(context, &entry);
+ }
+ krb5_kt_close (context, keytab);
+ return ret;
+}
+
+/**
+ * Return the type of the `keytab' in the string `prefix of length
+ * `prefixsize'.
+ *
+ * @param context a Keberos context.
+ * @param keytab the keytab to get the prefix for
+ * @param prefix prefix buffer
+ * @param prefixsize length of prefix buffer
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_get_type(krb5_context context,
+ krb5_keytab keytab,
+ char *prefix,
+ size_t prefixsize)
+{
+ strlcpy(prefix, keytab->prefix, prefixsize);
+ return 0;
+}
+
+/**
+ * Retrieve the name of the keytab `keytab' into `name', `namesize'
+ *
+ * @param context a Keberos context.
+ * @param keytab the keytab to get the name for.
+ * @param name name buffer.
+ * @param namesize size of name buffer.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_get_name(krb5_context context,
+ krb5_keytab keytab,
+ char *name,
+ size_t namesize)
+{
+ return (*keytab->get_name)(context, keytab, name, namesize);
+}
+
+/**
+ * Retrieve the full name of the keytab `keytab' and store the name in
+ * `str'.
+ *
+ * @param context a Keberos context.
+ * @param keytab keytab to get name for.
+ * @param str the name of the keytab name, usee krb5_xfree() to free
+ * the string. On error, *str is set to NULL.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_get_full_name(krb5_context context,
+ krb5_keytab keytab,
+ char **str)
+{
+ char type[KRB5_KT_PREFIX_MAX_LEN];
+ char name[MAXPATHLEN];
+ krb5_error_code ret;
+
+ *str = NULL;
+
+ ret = krb5_kt_get_type(context, keytab, type, sizeof(type));
+ if (ret)
+ return ret;
+
+ ret = krb5_kt_get_name(context, keytab, name, sizeof(name));
+ if (ret)
+ return ret;
+
+ if (asprintf(str, "%s:%s", type, name) == -1) {
+ *str = NULL;
+ return krb5_enomem(context);
+ }
+
+ return 0;
+}
+
+/**
+ * Finish using the keytab in `id'. All resources will be released,
+ * even on errors.
+ *
+ * @param context a Keberos context.
+ * @param id keytab to close.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_close(krb5_context context,
+ krb5_keytab id)
+{
+ krb5_error_code ret = 0;
+
+ if (id) {
+ ret = (id->close)(context, id);
+ memset(id, 0, sizeof(*id));
+ free(id);
+ }
+ return ret;
+}
+
+/**
+ * Destroy (remove) the keytab in `id'. All resources will be released,
+ * even on errors, does the equvalment of krb5_kt_close() on the resources.
+ *
+ * @param context a Keberos context.
+ * @param id keytab to destroy.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_destroy(krb5_context context,
+ krb5_keytab id)
+{
+ krb5_error_code ret;
+
+ ret = (*id->destroy)(context, id);
+ krb5_kt_close(context, id);
+ return ret;
+}
+
+/*
+ * Match any aliases in keytab `entry' with `principal'.
+ */
+
+static krb5_boolean
+compare_aliases(krb5_context context,
+ krb5_keytab_entry *entry,
+ krb5_const_principal principal)
+{
+ unsigned int i;
+ if (entry->aliases == NULL)
+ return FALSE;
+ for (i = 0; i < entry->aliases->len; i++)
+ if (krb5_principal_compare(context, &entry->aliases->val[i], principal))
+ return TRUE;
+ return FALSE;
+}
+
+/**
+ * Compare `entry' against `principal, vno, enctype'.
+ * Any of `principal, vno, enctype' might be 0 which acts as a wildcard.
+ * Return TRUE if they compare the same, FALSE otherwise.
+ *
+ * @param context a Keberos context.
+ * @param entry an entry to match with.
+ * @param principal principal to match, NULL matches all principals.
+ * @param vno key version to match, 0 matches all key version numbers.
+ * @param enctype encryption type to match, 0 matches all encryption types.
+ *
+ * @return Return TRUE or match, FALSE if not matched.
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_kt_compare(krb5_context context,
+ krb5_keytab_entry *entry,
+ krb5_const_principal principal,
+ krb5_kvno vno,
+ krb5_enctype enctype)
+{
+ /* krb5_principal_compare() does not special-case the referral realm */
+ if (principal != NULL && strcmp(principal->realm, "") == 0 &&
+ !(krb5_principal_compare_any_realm(context, entry->principal, principal) ||
+ compare_aliases(context, entry, principal))) {
+ return FALSE;
+ } else if (principal != NULL && strcmp(principal->realm, "") != 0 &&
+ !(krb5_principal_compare(context, entry->principal, principal) ||
+ compare_aliases(context, entry, principal))) {
+ return FALSE;
+ }
+ if (vno && vno != entry->vno)
+ return FALSE;
+ if (enctype && enctype != entry->keyblock.keytype)
+ return FALSE;
+ return TRUE;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_kt_principal_not_found(krb5_context context,
+ krb5_error_code ret,
+ krb5_keytab id,
+ krb5_const_principal principal,
+ krb5_enctype enctype,
+ int kvno)
+{
+ char kvno_str[25];
+ char *enctype_str = NULL;
+ char *kt_name = NULL;
+ char *princ = NULL;
+
+ (void) krb5_unparse_name(context, principal, &princ);
+ (void) krb5_kt_get_full_name(context, id, &kt_name);
+ if (enctype)
+ (void) krb5_enctype_to_string(context, enctype, &enctype_str);
+
+ if (kvno)
+ snprintf(kvno_str, sizeof(kvno_str), "(kvno %d)", kvno);
+ else
+ kvno_str[0] = '\0';
+
+ krb5_set_error_message(context, ret,
+ N_("Failed to find %s%s in keytab %s (%s)",
+ "principal, kvno, keytab file, enctype"),
+ princ ? princ : "<unknown>",
+ kvno_str,
+ kt_name ? kt_name : "unknown keytab",
+ enctype_str ? enctype_str : "unknown enctype");
+ free(princ);
+ free(kt_name);
+ free(enctype_str);
+ return ret;
+}
+
+static krb5_error_code
+krb5_kt_get_entry_wrapped(krb5_context context,
+ krb5_keytab id,
+ krb5_const_principal principal,
+ krb5_kvno kvno,
+ krb5_enctype enctype,
+ krb5_keytab_entry *entry)
+{
+ krb5_keytab_entry tmp;
+ krb5_error_code ret;
+ krb5_kt_cursor cursor;
+
+ if(id->get)
+ return (*id->get)(context, id, principal, kvno, enctype, entry);
+
+ memset(&tmp, 0, sizeof(tmp));
+ ret = krb5_kt_start_seq_get (context, id, &cursor);
+ if (ret) {
+ /* This is needed for krb5_verify_init_creds, but keep error
+ * string from previous error for the human. */
+ context->error_code = KRB5_KT_NOTFOUND;
+ return KRB5_KT_NOTFOUND;
+ }
+
+ entry->vno = 0;
+ while (krb5_kt_next_entry(context, id, &tmp, &cursor) == 0) {
+ if (krb5_kt_compare(context, &tmp, principal, 0, enctype)) {
+ /* the file keytab might only store the lower 8 bits of
+ the kvno, so only compare those bits */
+ if (kvno == tmp.vno
+ || (tmp.vno < 256 && kvno % 256 == tmp.vno)) {
+ krb5_kt_copy_entry_contents (context, &tmp, entry);
+ krb5_kt_free_entry (context, &tmp);
+ krb5_kt_end_seq_get(context, id, &cursor);
+ return 0;
+ } else if (kvno == 0 && tmp.vno > entry->vno) {
+ if (entry->vno)
+ krb5_kt_free_entry (context, entry);
+ krb5_kt_copy_entry_contents (context, &tmp, entry);
+ }
+ }
+ krb5_kt_free_entry(context, &tmp);
+ }
+ krb5_kt_end_seq_get (context, id, &cursor);
+ if (entry->vno == 0)
+ return _krb5_kt_principal_not_found(context, KRB5_KT_NOTFOUND,
+ id, principal, enctype, kvno);
+ return 0;
+}
+
+/**
+ * Retrieve the keytab entry for `principal, kvno, enctype' into `entry'
+ * from the keytab `id'. Matching is done like krb5_kt_compare().
+ *
+ * @param context a Keberos context.
+ * @param id a keytab.
+ * @param principal principal to match, NULL matches all principals.
+ * @param kvno key version to match, 0 matches all key version numbers.
+ * @param enctype encryption type to match, 0 matches all encryption types.
+ * @param entry the returned entry, free with krb5_kt_free_entry().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_get_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_const_principal principal,
+ krb5_kvno kvno,
+ krb5_enctype enctype,
+ krb5_keytab_entry *entry)
+{
+ krb5_error_code ret;
+ krb5_const_principal try_princ;
+ krb5_name_canon_iterator name_canon_iter;
+
+ if (!principal)
+ /* Use `NULL' instead of `principal' to quiet static analizers */
+ return krb5_kt_get_entry_wrapped(context, id, NULL, kvno, enctype,
+ entry);
+
+ ret = krb5_name_canon_iterator_start(context, principal, &name_canon_iter);
+ if (ret)
+ return ret;
+
+ do {
+ ret = krb5_name_canon_iterate(context, &name_canon_iter, &try_princ,
+ NULL);
+ if (ret)
+ break;
+ if (try_princ == NULL) {
+ ret = KRB5_KT_NOTFOUND;
+ continue;
+ }
+ ret = krb5_kt_get_entry_wrapped(context, id, try_princ, kvno,
+ enctype, entry);
+ } while (ret == KRB5_KT_NOTFOUND && name_canon_iter);
+
+ if (ret && ret != KRB5_KT_NOTFOUND)
+ krb5_set_error_message(context, ret,
+ N_("Name canon failed while searching keytab",
+ ""));
+ krb5_free_name_canon_iterator(context, name_canon_iter);
+ return ret;
+}
+
+/**
+ * Copy the contents of `in' into `out'.
+ *
+ * @param context a Keberos context.
+ * @param in the keytab entry to copy.
+ * @param out the copy of the keytab entry, free with krb5_kt_free_entry().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_copy_entry_contents(krb5_context context,
+ const krb5_keytab_entry *in,
+ krb5_keytab_entry *out)
+{
+ krb5_error_code ret;
+
+ memset(out, 0, sizeof(*out));
+
+ ret = krb5_copy_principal (context, in->principal, &out->principal);
+ if (ret)
+ return ret;
+ ret = krb5_copy_keyblock_contents (context,
+ &in->keyblock,
+ &out->keyblock);
+ if (ret) {
+ krb5_free_principal(context, out->principal);
+ memset(out, 0, sizeof(*out));
+ return ret;
+ }
+ out->vno = in->vno;
+ out->timestamp = in->timestamp;
+ return 0;
+}
+
+/**
+ * Free the contents of `entry'.
+ *
+ * @param context a Keberos context.
+ * @param entry the entry to free
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_free_entry(krb5_context context,
+ krb5_keytab_entry *entry)
+{
+ krb5_free_principal (context, entry->principal);
+ krb5_free_keyblock_contents (context, &entry->keyblock);
+ memset(entry, 0, sizeof(*entry));
+ return 0;
+}
+
+/**
+ * Set `cursor' to point at the beginning of `id'.
+ *
+ * @param context a Keberos context.
+ * @param id a keytab.
+ * @param cursor a newly allocated cursor, free with krb5_kt_end_seq_get().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_start_seq_get(krb5_context context,
+ krb5_keytab id,
+ krb5_kt_cursor *cursor)
+{
+ if(id->start_seq_get == NULL) {
+ krb5_set_error_message(context, HEIM_ERR_OPNOTSUPP,
+ N_("start_seq_get is not supported "
+ "in the %s keytab type", ""),
+ id->prefix);
+ return HEIM_ERR_OPNOTSUPP;
+ }
+ return (*id->start_seq_get)(context, id, cursor);
+}
+
+/**
+ * Get the next entry from keytab, advance the cursor. On last entry
+ * the function will return KRB5_KT_END.
+ *
+ * @param context a Keberos context.
+ * @param id a keytab.
+ * @param entry the returned entry, free with krb5_kt_free_entry().
+ * @param cursor the cursor of the iteration.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_next_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry,
+ krb5_kt_cursor *cursor)
+{
+ if(id->next_entry == NULL) {
+ krb5_set_error_message(context, HEIM_ERR_OPNOTSUPP,
+ N_("next_entry is not supported in the %s "
+ " keytab", ""),
+ id->prefix);
+ return HEIM_ERR_OPNOTSUPP;
+ }
+ memset(entry, 0x0, sizeof(*entry));
+ return (*id->next_entry)(context, id, entry, cursor);
+}
+
+/**
+ * Release all resources associated with `cursor'.
+ *
+ * @param context a Keberos context.
+ * @param id a keytab.
+ * @param cursor the cursor to free.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_end_seq_get(krb5_context context,
+ krb5_keytab id,
+ krb5_kt_cursor *cursor)
+{
+ if(id->end_seq_get == NULL) {
+ krb5_set_error_message(context, HEIM_ERR_OPNOTSUPP,
+ "end_seq_get is not supported in the %s "
+ " keytab", id->prefix);
+ return HEIM_ERR_OPNOTSUPP;
+ }
+ return (*id->end_seq_get)(context, id, cursor);
+}
+
+/**
+ * Add the entry in `entry' to the keytab `id'.
+ *
+ * @param context a Keberos context.
+ * @param id a keytab.
+ * @param entry the entry to add
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_add_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry)
+{
+ if(id->add == NULL) {
+ krb5_set_error_message(context, KRB5_KT_NOWRITE,
+ N_("Add is not supported in the %s keytab", ""),
+ id->prefix);
+ return KRB5_KT_NOWRITE;
+ }
+ entry->timestamp = time(NULL);
+ return (*id->add)(context, id,entry);
+}
+
+/**
+ * Remove an entry from the keytab, matching is done using
+ * krb5_kt_compare().
+
+ * @param context a Keberos context.
+ * @param id a keytab.
+ * @param entry the entry to remove
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_remove_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry)
+{
+ if(id->remove == NULL) {
+ krb5_set_error_message(context, KRB5_KT_NOWRITE,
+ N_("Remove is not supported in the %s keytab", ""),
+ id->prefix);
+ return KRB5_KT_NOWRITE;
+ }
+ return (*id->remove)(context, id, entry);
+}
+
+/**
+ * Return true if the keytab exists and have entries
+ *
+ * @param context a Keberos context.
+ * @param id a keytab.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_have_content(krb5_context context,
+ krb5_keytab id)
+{
+ krb5_keytab_entry entry;
+ krb5_kt_cursor cursor;
+ krb5_error_code ret;
+ char *name;
+
+ memset(&entry, 0, sizeof(entry));
+ ret = krb5_kt_start_seq_get(context, id, &cursor);
+ if (ret)
+ goto notfound;
+
+ ret = krb5_kt_next_entry(context, id, &entry, &cursor);
+ krb5_kt_end_seq_get(context, id, &cursor);
+ if (ret)
+ goto notfound;
+
+ krb5_kt_free_entry(context, &entry);
+
+ return 0;
+
+ notfound:
+ ret = krb5_kt_get_full_name(context, id, &name);
+ if (ret == 0) {
+ krb5_set_error_message(context, KRB5_KT_NOTFOUND,
+ N_("No entry in keytab: %s", ""), name);
+ free(name);
+ }
+ return KRB5_KT_NOTFOUND;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_kt_client_default_name(krb5_context context, char **name)
+{
+ const char *tmp;
+
+ tmp = secure_getenv("KRB5_CLIENT_KTNAME");
+ if (tmp == NULL)
+ tmp = krb5_config_get_string(context, NULL,
+ "libdefaults",
+ "default_client_keytab_name", NULL);
+ if (tmp == NULL)
+ tmp = CLIENT_KEYTAB_DEFAULT;
+
+ return _krb5_expand_path_tokens(context, tmp, 1, name);
+}
diff --git a/third_party/heimdal/lib/krb5/keytab_any.c b/third_party/heimdal/lib/krb5/keytab_any.c
new file mode 100644
index 0000000..6663d17
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/keytab_any.c
@@ -0,0 +1,260 @@
+/*
+ * Copyright (c) 2001-2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+struct any_data {
+ krb5_keytab kt;
+ char *name;
+ struct any_data *next;
+};
+
+static void
+free_list (krb5_context context, struct any_data *a)
+{
+ struct any_data *next;
+
+ for (; a != NULL; a = next) {
+ next = a->next;
+ free (a->name);
+ if(a->kt)
+ krb5_kt_close(context, a->kt);
+ free (a);
+ }
+}
+
+static krb5_error_code KRB5_CALLCONV
+any_resolve(krb5_context context, const char *name, krb5_keytab id)
+{
+ struct any_data *a, *a0 = NULL, *prev = NULL;
+ krb5_error_code ret;
+ char buf[256];
+
+ while (strsep_copy(&name, ",", buf, sizeof(buf)) != -1) {
+ a = calloc(1, sizeof(*a));
+ if (a == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ if (a0 == NULL) {
+ a0 = a;
+ a->name = strdup(buf);
+ if (a->name == NULL) {
+ ret = krb5_enomem(context);
+ goto fail;
+ }
+ } else
+ a->name = NULL;
+ if (prev != NULL)
+ prev->next = a;
+ a->next = NULL;
+ ret = krb5_kt_resolve (context, buf, &a->kt);
+ if (ret)
+ goto fail;
+ prev = a;
+ }
+ if (a0 == NULL) {
+ krb5_set_error_message(context, ENOENT, N_("empty ANY: keytab", ""));
+ return ENOENT;
+ }
+ id->data = a0;
+ return 0;
+ fail:
+ free_list (context, a0);
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+any_get_name (krb5_context context,
+ krb5_keytab id,
+ char *name,
+ size_t namesize)
+{
+ struct any_data *a = id->data;
+ strlcpy(name, a->name, namesize);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+any_close (krb5_context context,
+ krb5_keytab id)
+{
+ struct any_data *a = id->data;
+
+ free_list (context, a);
+ return 0;
+}
+
+struct any_cursor_extra_data {
+ struct any_data *a;
+ krb5_kt_cursor cursor;
+};
+
+static krb5_error_code KRB5_CALLCONV
+any_start_seq_get(krb5_context context,
+ krb5_keytab id,
+ krb5_kt_cursor *c)
+{
+ struct any_data *a = id->data;
+ struct any_cursor_extra_data *ed;
+ krb5_error_code ret;
+
+ c->data = malloc (sizeof(struct any_cursor_extra_data));
+ if(c->data == NULL)
+ return krb5_enomem(context);
+ ed = (struct any_cursor_extra_data *)c->data;
+ for (ed->a = a; ed->a != NULL; ed->a = ed->a->next) {
+ ret = krb5_kt_start_seq_get(context, ed->a->kt, &ed->cursor);
+ if (ret == 0)
+ break;
+ }
+ if (ed->a == NULL) {
+ free (c->data);
+ c->data = NULL;
+ krb5_clear_error_message (context);
+ return KRB5_KT_END;
+ }
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+any_next_entry (krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry,
+ krb5_kt_cursor *cursor)
+{
+ krb5_error_code ret, ret2;
+ struct any_cursor_extra_data *ed;
+
+ ed = (struct any_cursor_extra_data *)cursor->data;
+ do {
+ ret = krb5_kt_next_entry(context, ed->a->kt, entry, &ed->cursor);
+ if (ret == 0)
+ return 0;
+ else if (ret != KRB5_KT_END)
+ return ret;
+
+ ret2 = krb5_kt_end_seq_get (context, ed->a->kt, &ed->cursor);
+ if (ret2)
+ return ret2;
+ while ((ed->a = ed->a->next) != NULL) {
+ ret2 = krb5_kt_start_seq_get(context, ed->a->kt, &ed->cursor);
+ if (ret2 == 0)
+ break;
+ }
+ if (ed->a == NULL) {
+ krb5_clear_error_message (context);
+ return KRB5_KT_END;
+ }
+ } while (1);
+}
+
+static krb5_error_code KRB5_CALLCONV
+any_end_seq_get(krb5_context context,
+ krb5_keytab id,
+ krb5_kt_cursor *cursor)
+{
+ krb5_error_code ret = 0;
+ struct any_cursor_extra_data *ed;
+
+ ed = (struct any_cursor_extra_data *)cursor->data;
+ if (ed->a != NULL)
+ ret = krb5_kt_end_seq_get(context, ed->a->kt, &ed->cursor);
+ free (ed);
+ cursor->data = NULL;
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+any_add_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry)
+{
+ struct any_data *a = id->data;
+ krb5_error_code ret;
+ while(a != NULL) {
+ ret = krb5_kt_add_entry(context, a->kt, entry);
+ if(ret != 0 && ret != KRB5_KT_NOWRITE) {
+ krb5_set_error_message(context, ret,
+ N_("failed to add entry to %s", ""),
+ a->name);
+ return ret;
+ }
+ a = a->next;
+ }
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+any_remove_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry)
+{
+ struct any_data *a = id->data;
+ krb5_error_code ret;
+ krb5_boolean found = FALSE;
+ while(a != NULL) {
+ ret = krb5_kt_remove_entry(context, a->kt, entry);
+ if(ret == 0)
+ found = TRUE;
+ else {
+ if(ret != KRB5_KT_NOWRITE && ret != KRB5_KT_NOTFOUND) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to remove keytab "
+ "entry from %s", "keytab name"),
+ a->name);
+ return ret;
+ }
+ }
+ a = a->next;
+ }
+ if(!found)
+ return KRB5_KT_NOTFOUND;
+ return 0;
+}
+
+const krb5_kt_ops krb5_any_ops = {
+ "ANY",
+ any_resolve,
+ any_get_name,
+ any_close,
+ NULL, /* destroy */
+ NULL, /* get */
+ any_start_seq_get,
+ any_next_entry,
+ any_end_seq_get,
+ any_add_entry,
+ any_remove_entry,
+ NULL,
+ 0
+};
diff --git a/third_party/heimdal/lib/krb5/keytab_file.c b/third_party/heimdal/lib/krb5/keytab_file.c
new file mode 100644
index 0000000..61b5d6d
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/keytab_file.c
@@ -0,0 +1,856 @@
+/*
+ * Copyright (c) 1997 - 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#define KRB5_KT_VNO_1 1
+#define KRB5_KT_VNO_2 2
+#define KRB5_KT_VNO KRB5_KT_VNO_2
+
+#define KRB5_KT_FL_JAVA 1
+
+
+/* file operations -------------------------------------------- */
+
+struct fkt_data {
+ char *filename;
+ int flags;
+};
+
+static krb5_error_code
+krb5_kt_ret_data(krb5_context context,
+ krb5_storage *sp,
+ krb5_data *data)
+{
+ krb5_error_code ret;
+ krb5_ssize_t bytes;
+ int16_t size;
+
+ ret = krb5_ret_int16(sp, &size);
+ if(ret)
+ return ret;
+ data->length = size;
+ data->data = malloc(size);
+ if (data->data == NULL)
+ return krb5_enomem(context);
+ bytes = krb5_storage_read(sp, data->data, size);
+ if (bytes != size)
+ return (bytes == -1) ? errno : KRB5_KT_END;
+ return 0;
+}
+
+static krb5_error_code
+krb5_kt_ret_string(krb5_context context,
+ krb5_storage *sp,
+ heim_general_string *data)
+{
+ krb5_error_code ret;
+ krb5_ssize_t bytes;
+ int16_t size;
+
+ ret = krb5_ret_int16(sp, &size);
+ if(ret)
+ return ret;
+ *data = malloc(size + 1);
+ if (*data == NULL)
+ return krb5_enomem(context);
+ bytes = krb5_storage_read(sp, *data, size);
+ (*data)[size] = '\0';
+ if (bytes != size)
+ return (bytes == -1) ? errno : KRB5_KT_END;
+ return 0;
+}
+
+static krb5_error_code
+krb5_kt_store_data(krb5_context context,
+ krb5_storage *sp,
+ krb5_data data)
+{
+ krb5_error_code ret;
+ krb5_ssize_t bytes;
+
+ ret = krb5_store_int16(sp, data.length);
+ if (ret != 0)
+ return ret;
+ bytes = krb5_storage_write(sp, data.data, data.length);
+ if (bytes != (int)data.length)
+ return bytes == -1 ? errno : KRB5_KT_END;
+ return 0;
+}
+
+static krb5_error_code
+krb5_kt_store_string(krb5_storage *sp,
+ heim_general_string data)
+{
+ krb5_error_code ret;
+ krb5_ssize_t bytes;
+ size_t len = strlen(data);
+
+ ret = krb5_store_int16(sp, len);
+ if (ret != 0)
+ return ret;
+ bytes = krb5_storage_write(sp, data, len);
+ if (bytes != (int)len)
+ return bytes == -1 ? errno : KRB5_KT_END;
+ return 0;
+}
+
+static krb5_error_code
+krb5_kt_ret_keyblock(krb5_context context,
+ struct fkt_data *fkt,
+ krb5_storage *sp,
+ krb5_keyblock *p)
+{
+ int ret;
+ int16_t tmp;
+
+ ret = krb5_ret_int16(sp, &tmp); /* keytype + etype */
+ if(ret) {
+ krb5_set_error_message(context, ret,
+ N_("Cant read keyblock from file %s", ""),
+ fkt->filename);
+ return ret;
+ }
+ p->keytype = tmp;
+ ret = krb5_kt_ret_data(context, sp, &p->keyvalue);
+ if (ret)
+ krb5_set_error_message(context, ret,
+ N_("Cant read keyblock from file %s", ""),
+ fkt->filename);
+ return ret;
+}
+
+static krb5_error_code
+krb5_kt_store_keyblock(krb5_context context,
+ struct fkt_data *fkt,
+ krb5_storage *sp,
+ krb5_keyblock *p)
+{
+ int ret;
+
+ ret = krb5_store_int16(sp, p->keytype); /* keytype + etype */
+ if(ret) {
+ krb5_set_error_message(context, ret,
+ N_("Cant store keyblock to file %s", ""),
+ fkt->filename);
+ return ret;
+ }
+ ret = krb5_kt_store_data(context, sp, p->keyvalue);
+ if (ret)
+ krb5_set_error_message(context, ret,
+ N_("Cant store keyblock to file %s", ""),
+ fkt->filename);
+ return ret;
+}
+
+
+static krb5_error_code
+krb5_kt_ret_principal(krb5_context context,
+ struct fkt_data *fkt,
+ krb5_storage *sp,
+ krb5_principal *princ)
+{
+ size_t i;
+ int ret;
+ krb5_principal p;
+ int16_t len;
+
+ ALLOC(p, 1);
+ if(p == NULL)
+ return krb5_enomem(context);
+
+ ret = krb5_ret_int16(sp, &len);
+ if(ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed decoding length of "
+ "keytab principal in keytab file %s", ""),
+ fkt->filename);
+ goto out;
+ }
+ if(krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONENTS))
+ len--;
+ if (len < 0) {
+ ret = KRB5_KT_END;
+ krb5_set_error_message(context, ret,
+ N_("Keytab principal contains "
+ "invalid length in keytab %s", ""),
+ fkt->filename);
+ goto out;
+ }
+ ret = krb5_kt_ret_string(context, sp, &p->realm);
+ if(ret) {
+ krb5_set_error_message(context, ret,
+ N_("Can't read realm from keytab: %s", ""),
+ fkt->filename);
+ goto out;
+ }
+ p->name.name_string.val = calloc(len, sizeof(*p->name.name_string.val));
+ if(p->name.name_string.val == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ p->name.name_string.len = len;
+ for(i = 0; i < p->name.name_string.len; i++){
+ ret = krb5_kt_ret_string(context, sp, p->name.name_string.val + i);
+ if(ret) {
+ krb5_set_error_message(context, ret,
+ N_("Can't read principal from "
+ "keytab: %s", ""),
+ fkt->filename);
+ goto out;
+ }
+ }
+ if (krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE))
+ p->name.name_type = KRB5_NT_UNKNOWN;
+ else {
+ int32_t tmp32;
+ ret = krb5_ret_int32(sp, &tmp32);
+ p->name.name_type = tmp32;
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Can't read name-type from "
+ "keytab: %s", ""),
+ fkt->filename);
+ goto out;
+ }
+ }
+ *princ = p;
+ return 0;
+out:
+ krb5_free_principal(context, p);
+ return ret;
+}
+
+static krb5_error_code
+krb5_kt_store_principal(krb5_context context,
+ krb5_storage *sp,
+ krb5_principal p)
+{
+ size_t i;
+ int ret;
+
+ if(krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONENTS))
+ ret = krb5_store_int16(sp, p->name.name_string.len + 1);
+ else
+ ret = krb5_store_int16(sp, p->name.name_string.len);
+ if(ret) return ret;
+ ret = krb5_kt_store_string(sp, p->realm);
+ if(ret) return ret;
+ for(i = 0; i < p->name.name_string.len; i++){
+ ret = krb5_kt_store_string(sp, p->name.name_string.val[i]);
+ if(ret)
+ return ret;
+ }
+ if(!krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE)) {
+ ret = krb5_store_int32(sp, p->name.name_type);
+ if(ret)
+ return ret;
+ }
+
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fkt_resolve(krb5_context context, const char *name, krb5_keytab id)
+{
+ struct fkt_data *d;
+
+ d = malloc(sizeof(*d));
+ if(d == NULL)
+ return krb5_enomem(context);
+ d->filename = strdup(name);
+ if(d->filename == NULL) {
+ free(d);
+ return krb5_enomem(context);
+ }
+ d->flags = 0;
+ id->data = d;
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fkt_resolve_java14(krb5_context context, const char *name, krb5_keytab id)
+{
+ krb5_error_code ret;
+
+ ret = fkt_resolve(context, name, id);
+ if (ret == 0) {
+ struct fkt_data *d = id->data;
+ d->flags |= KRB5_KT_FL_JAVA;
+ }
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fkt_close(krb5_context context, krb5_keytab id)
+{
+ struct fkt_data *d = id->data;
+ free(d->filename);
+ free(d);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fkt_destroy(krb5_context context, krb5_keytab id)
+{
+ struct fkt_data *d = id->data;
+ _krb5_erase_file(context, d->filename);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fkt_get_name(krb5_context context,
+ krb5_keytab id,
+ char *name,
+ size_t namesize)
+{
+ /* This function is XXX */
+ struct fkt_data *d = id->data;
+ strlcpy(name, d->filename, namesize);
+ return 0;
+}
+
+static void
+storage_set_flags(krb5_context context, krb5_storage *sp, int vno)
+{
+ int flags = 0;
+ switch(vno) {
+ case KRB5_KT_VNO_1:
+ flags |= KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONENTS;
+ flags |= KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE;
+ flags |= KRB5_STORAGE_HOST_BYTEORDER;
+ break;
+ case KRB5_KT_VNO_2:
+ break;
+ default:
+ krb5_warnx(context,
+ "storage_set_flags called with bad vno (%d)", vno);
+ }
+ krb5_storage_set_flags(sp, flags);
+}
+
+static krb5_error_code
+fkt_start_seq_get_int(krb5_context context,
+ krb5_keytab id,
+ int flags,
+ int exclusive,
+ krb5_kt_cursor *c)
+{
+ int8_t pvno, tag;
+ krb5_error_code ret;
+ struct fkt_data *d = id->data;
+ const char *stdio_mode = "rb";
+
+ memset(c, 0, sizeof(*c));
+ c->fd = open (d->filename, flags);
+ if (c->fd < 0) {
+ ret = errno;
+ krb5_set_error_message(context, ret,
+ N_("keytab %s open failed: %s", ""),
+ d->filename, strerror(ret));
+ return ret;
+ }
+ rk_cloexec(c->fd);
+ ret = _krb5_xlock(context, c->fd, exclusive, d->filename);
+ if (ret) {
+ close(c->fd);
+ return ret;
+ }
+ if ((flags & O_ACCMODE) == O_RDWR && (flags & O_APPEND))
+ stdio_mode = "ab+";
+ else if ((flags & O_ACCMODE) == O_RDWR)
+ stdio_mode = "rb+";
+ else if ((flags & O_ACCMODE) == O_WRONLY)
+ stdio_mode = "wb";
+ c->sp = krb5_storage_stdio_from_fd(c->fd, stdio_mode);
+ if (c->sp == NULL) {
+ close(c->fd);
+ return krb5_enomem(context);
+ }
+ krb5_storage_set_eof_code(c->sp, KRB5_KT_END);
+ ret = krb5_ret_int8(c->sp, &pvno);
+ if(ret) {
+ krb5_storage_free(c->sp);
+ close(c->fd);
+ krb5_clear_error_message(context);
+ return ret;
+ }
+ if(pvno != 5) {
+ krb5_storage_free(c->sp);
+ close(c->fd);
+ krb5_clear_error_message (context);
+ return KRB5_KEYTAB_BADVNO;
+ }
+ ret = krb5_ret_int8(c->sp, &tag);
+ if (ret) {
+ krb5_storage_free(c->sp);
+ close(c->fd);
+ krb5_clear_error_message(context);
+ return ret;
+ }
+ id->version = tag;
+ storage_set_flags(context, c->sp, id->version);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fkt_start_seq_get(krb5_context context,
+ krb5_keytab id,
+ krb5_kt_cursor *c)
+{
+ return fkt_start_seq_get_int(context, id, O_RDONLY | O_BINARY | O_CLOEXEC, 0, c);
+}
+
+static krb5_error_code
+fkt_next_entry_int(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry,
+ krb5_kt_cursor *cursor,
+ off_t *start,
+ off_t *end)
+{
+ struct fkt_data *d = id->data;
+ int32_t len;
+ int ret;
+ int8_t tmp8;
+ int32_t tmp32;
+ uint32_t utmp32;
+ off_t pos, curpos;
+
+ pos = krb5_storage_seek(cursor->sp, 0, SEEK_CUR);
+loop:
+ ret = krb5_ret_int32(cursor->sp, &len);
+ if (ret)
+ return ret;
+ if(len < 0) {
+ pos = krb5_storage_seek(cursor->sp, -len, SEEK_CUR);
+ goto loop;
+ }
+ ret = krb5_kt_ret_principal (context, d, cursor->sp, &entry->principal);
+ if (ret)
+ goto out;
+ ret = krb5_ret_uint32(cursor->sp, &utmp32);
+ entry->timestamp = utmp32;
+ if (ret)
+ goto out;
+ ret = krb5_ret_int8(cursor->sp, &tmp8);
+ if (ret)
+ goto out;
+ entry->vno = tmp8;
+ ret = krb5_kt_ret_keyblock (context, d, cursor->sp, &entry->keyblock);
+ if (ret)
+ goto out;
+ /* there might be a 32 bit kvno here
+ * if it's zero, assume that the 8bit one was right,
+ * otherwise trust the new value */
+ curpos = krb5_storage_seek(cursor->sp, 0, SEEK_CUR);
+ if(len + 4 + pos - curpos >= 4) {
+ ret = krb5_ret_int32(cursor->sp, &tmp32);
+ if (ret == 0 && tmp32 != 0)
+ entry->vno = tmp32;
+ }
+ /* there might be a flags field here */
+ if(len + 4 + pos - curpos >= 8) {
+ ret = krb5_ret_uint32(cursor->sp, &utmp32);
+ if (ret == 0)
+ entry->flags = utmp32;
+ } else
+ entry->flags = 0;
+
+ entry->aliases = NULL;
+
+ if(start) *start = pos;
+ if(end) *end = pos + 4 + len;
+ out:
+ if (ret)
+ krb5_kt_free_entry(context, entry);
+ krb5_storage_seek(cursor->sp, pos + 4 + len, SEEK_SET);
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fkt_next_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry,
+ krb5_kt_cursor *cursor)
+{
+ return fkt_next_entry_int(context, id, entry, cursor, NULL, NULL);
+}
+
+static krb5_error_code KRB5_CALLCONV
+fkt_end_seq_get(krb5_context context,
+ krb5_keytab id,
+ krb5_kt_cursor *cursor)
+{
+ krb5_storage_free(cursor->sp);
+ close(cursor->fd);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fkt_setup_keytab(krb5_context context,
+ krb5_keytab id,
+ krb5_storage *sp)
+{
+ krb5_error_code ret;
+ ret = krb5_store_int8(sp, 5);
+ if(ret)
+ return ret;
+ if(id->version == 0)
+ id->version = KRB5_KT_VNO;
+ return krb5_store_int8 (sp, id->version);
+}
+
+static krb5_error_code KRB5_CALLCONV
+fkt_add_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry)
+{
+ int ret;
+ int fd;
+ krb5_storage *sp;
+ krb5_ssize_t bytes;
+ struct fkt_data *d = id->data;
+ krb5_data keytab;
+ int32_t len;
+
+ fd = open(d->filename, O_RDWR | O_BINARY | O_CLOEXEC);
+ if (fd < 0) {
+ fd = open(d->filename, O_RDWR | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, 0600);
+ if (fd < 0) {
+ ret = errno;
+ krb5_set_error_message(context, ret,
+ N_("open(%s): %s", ""), d->filename,
+ strerror(ret));
+ return ret;
+ }
+ rk_cloexec(fd);
+
+ ret = _krb5_xlock(context, fd, 1, d->filename);
+ if (ret) {
+ close(fd);
+ return ret;
+ }
+ sp = krb5_storage_stdio_from_fd(fd, "wb+");
+ if (sp == NULL) {
+ close(fd);
+ return krb5_enomem(context);
+ }
+ krb5_storage_set_eof_code(sp, KRB5_KT_END);
+ ret = fkt_setup_keytab(context, id, sp);
+ if (ret) {
+ goto out;
+ }
+ storage_set_flags(context, sp, id->version);
+ } else {
+ int8_t pvno, tag;
+
+ rk_cloexec(fd);
+
+ ret = _krb5_xlock(context, fd, 1, d->filename);
+ if (ret) {
+ close(fd);
+ return ret;
+ }
+ sp = krb5_storage_stdio_from_fd(fd, "wb+");
+ if (sp == NULL) {
+ (void) close(fd);
+ return ret;
+ }
+ krb5_storage_set_eof_code(sp, KRB5_KT_END);
+ ret = krb5_ret_int8(sp, &pvno);
+ if(ret) {
+ /* we probably have a zero byte file, so try to set it up
+ properly */
+ ret = fkt_setup_keytab(context, id, sp);
+ if(ret) {
+ krb5_set_error_message(context, ret,
+ N_("%s: keytab is corrupted: %s", ""),
+ d->filename, strerror(ret));
+ goto out;
+ }
+ storage_set_flags(context, sp, id->version);
+ } else {
+ if(pvno != 5) {
+ ret = KRB5_KEYTAB_BADVNO;
+ krb5_set_error_message(context, ret,
+ N_("Bad version in keytab %s", ""),
+ d->filename);
+ goto out;
+ }
+ ret = krb5_ret_int8 (sp, &tag);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("failed reading tag from "
+ "keytab %s", ""),
+ d->filename);
+ goto out;
+ }
+ id->version = tag;
+ storage_set_flags(context, sp, id->version);
+ }
+ }
+
+ {
+ krb5_storage *emem;
+ emem = krb5_storage_emem();
+ if(emem == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ ret = krb5_kt_store_principal(context, emem, entry->principal);
+ if(ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed storing principal "
+ "in keytab %s", ""),
+ d->filename);
+ krb5_storage_free(emem);
+ goto out;
+ }
+ ret = krb5_store_int32 (emem, entry->timestamp);
+ if(ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed storing timpstamp "
+ "in keytab %s", ""),
+ d->filename);
+ krb5_storage_free(emem);
+ goto out;
+ }
+ ret = krb5_store_int8 (emem, entry->vno % 256);
+ if(ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed storing kvno "
+ "in keytab %s", ""),
+ d->filename);
+ krb5_storage_free(emem);
+ goto out;
+ }
+ ret = krb5_kt_store_keyblock (context, d, emem, &entry->keyblock);
+ if(ret) {
+ krb5_storage_free(emem);
+ goto out;
+ }
+ if ((d->flags & KRB5_KT_FL_JAVA) == 0) {
+ ret = krb5_store_int32 (emem, entry->vno);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed storing extended kvno "
+ "in keytab %s", ""),
+ d->filename);
+ krb5_storage_free(emem);
+ goto out;
+ }
+ ret = krb5_store_uint32 (emem, entry->flags);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed storing extended kvno "
+ "in keytab %s", ""),
+ d->filename);
+ krb5_storage_free(emem);
+ goto out;
+ }
+ }
+
+ ret = krb5_storage_to_data(emem, &keytab);
+ krb5_storage_free(emem);
+ if(ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed converting keytab entry "
+ "to memory block for keytab %s", ""),
+ d->filename);
+ goto out;
+ }
+ }
+
+ while(1) {
+ off_t here;
+
+ here = krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (here == -1) {
+ ret = errno;
+ krb5_set_error_message(context, ret,
+ N_("Failed writing keytab block "
+ "in keytab %s: %s", ""),
+ d->filename, strerror(ret));
+ goto out;
+ }
+ ret = krb5_ret_int32(sp, &len);
+ if (ret) {
+ /* There could have been a partial length. Recover! */
+ (void) krb5_storage_truncate(sp, here);
+ len = keytab.length;
+ break;
+ }
+ if(len < 0) {
+ len = -len;
+ if(len >= (int)keytab.length) {
+ krb5_storage_seek(sp, -4, SEEK_CUR);
+ break;
+ }
+ }
+ krb5_storage_seek(sp, len, SEEK_CUR);
+ }
+ ret = krb5_store_int32(sp, len);
+ if (ret != 0)
+ goto out;
+ bytes = krb5_storage_write(sp, keytab.data, keytab.length);
+ if (bytes != keytab.length) {
+ ret = bytes == -1 ? errno : KRB5_KT_END;
+ krb5_set_error_message(context, ret,
+ N_("Failed writing keytab block "
+ "in keytab %s: %s", ""),
+ d->filename, strerror(ret));
+ }
+ memset(keytab.data, 0, keytab.length);
+ krb5_data_free(&keytab);
+ out:
+ if (ret == 0)
+ ret = krb5_storage_fsync(sp);
+ krb5_storage_free(sp);
+ close(fd);
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fkt_remove_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry)
+{
+ struct fkt_data *fkt = id->data;
+ krb5_ssize_t bytes;
+ krb5_keytab_entry e;
+ krb5_kt_cursor cursor;
+ off_t pos_start, pos_end;
+ int found = 0;
+ krb5_error_code ret;
+
+ ret = fkt_start_seq_get_int(context, id, O_RDWR | O_BINARY | O_CLOEXEC, 1, &cursor);
+ if (ret != 0) {
+ const char *emsg = krb5_get_error_message(context, ret);
+
+ krb5_set_error_message(context, ret,
+ N_("Could not open keytab file for write: %s: %s", ""),
+ fkt->filename,
+ emsg);
+ krb5_free_error_message(context, emsg);
+ return ret;
+ }
+ while (ret == 0 &&
+ (ret = fkt_next_entry_int(context, id, &e, &cursor,
+ &pos_start, &pos_end)) == 0) {
+ if (krb5_kt_compare(context, &e, entry->principal,
+ entry->vno, entry->keyblock.keytype)) {
+ int32_t len;
+ unsigned char buf[128];
+ found = 1;
+ krb5_storage_seek(cursor.sp, pos_start, SEEK_SET);
+ len = pos_end - pos_start - 4;
+ ret = krb5_store_int32(cursor.sp, -len);
+ memset(buf, 0, sizeof(buf));
+ while (ret == 0 && len > 0) {
+ bytes = krb5_storage_write(cursor.sp, buf,
+ min((size_t)len, sizeof(buf)));
+ if (bytes != min((size_t)len, sizeof(buf))) {
+ ret = bytes == -1 ? errno : KRB5_KT_END;
+ break;
+ }
+ len -= min((size_t)len, sizeof(buf));
+ }
+ }
+ krb5_kt_free_entry(context, &e);
+ }
+ (void) krb5_kt_end_seq_get(context, id, &cursor);
+ if (ret == KRB5_KT_END)
+ ret = 0;
+ if (ret) {
+ const char *emsg = krb5_get_error_message(context, ret);
+
+ krb5_set_error_message(context, ret,
+ N_("Could not remove keytab entry from %s: %s", ""),
+ fkt->filename,
+ emsg);
+ krb5_free_error_message(context, emsg);
+ } else if (!found) {
+ krb5_clear_error_message(context);
+ return KRB5_KT_NOTFOUND;
+ }
+ return ret;
+}
+
+const krb5_kt_ops krb5_fkt_ops = {
+ "FILE",
+ fkt_resolve,
+ fkt_get_name,
+ fkt_close,
+ fkt_destroy,
+ NULL, /* get */
+ fkt_start_seq_get,
+ fkt_next_entry,
+ fkt_end_seq_get,
+ fkt_add_entry,
+ fkt_remove_entry,
+ NULL,
+ 0
+};
+
+const krb5_kt_ops krb5_wrfkt_ops = {
+ "WRFILE",
+ fkt_resolve,
+ fkt_get_name,
+ fkt_close,
+ fkt_destroy,
+ NULL, /* get */
+ fkt_start_seq_get,
+ fkt_next_entry,
+ fkt_end_seq_get,
+ fkt_add_entry,
+ fkt_remove_entry,
+ NULL,
+ 0
+};
+
+const krb5_kt_ops krb5_javakt_ops = {
+ "JAVA14",
+ fkt_resolve_java14,
+ fkt_get_name,
+ fkt_close,
+ fkt_destroy,
+ NULL, /* get */
+ fkt_start_seq_get,
+ fkt_next_entry,
+ fkt_end_seq_get,
+ fkt_add_entry,
+ fkt_remove_entry,
+ NULL,
+ 0
+};
diff --git a/third_party/heimdal/lib/krb5/keytab_keyfile.c b/third_party/heimdal/lib/krb5/keytab_keyfile.c
new file mode 100644
index 0000000..af3ac86
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/keytab_keyfile.c
@@ -0,0 +1,456 @@
+/*
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#ifndef HEIMDAL_SMALLER
+
+/* afs keyfile operations --------------------------------------- */
+
+/*
+ * Minimum tools to handle the AFS KeyFile.
+ *
+ * Format of the KeyFile is:
+ * <int32_t numkeys> {[<int32_t kvno> <char[8] deskey>] * numkeys}
+ *
+ * It just adds to the end of the keyfile, deleting isn't implemented.
+ * Use your favorite text/hex editor to delete keys.
+ *
+ */
+
+#define AFS_SERVERTHISCELL "/usr/afs/etc/ThisCell"
+#define AFS_SERVERMAGICKRBCONF "/usr/afs/etc/krb.conf"
+
+struct akf_data {
+ uint32_t num_entries;
+ char *filename;
+ char *cell;
+ char *realm;
+};
+
+/*
+ * set `d->cell' and `d->realm'
+ */
+
+static int
+get_cell_and_realm (krb5_context context, struct akf_data *d)
+{
+ FILE *f;
+ char buf[BUFSIZ], *cp;
+ int ret;
+
+ f = fopen (AFS_SERVERTHISCELL, "r");
+ if (f == NULL) {
+ ret = errno;
+ krb5_set_error_message (context, ret,
+ N_("Open ThisCell %s: %s", ""),
+ AFS_SERVERTHISCELL,
+ strerror(ret));
+ return ret;
+ }
+ if (fgets (buf, sizeof(buf), f) == NULL) {
+ fclose (f);
+ krb5_set_error_message (context, EINVAL,
+ N_("No cell in ThisCell file %s", ""),
+ AFS_SERVERTHISCELL);
+ return EINVAL;
+ }
+ buf[strcspn(buf, "\n")] = '\0';
+ fclose(f);
+
+ d->cell = strdup (buf);
+ if (d->cell == NULL)
+ return krb5_enomem(context);
+
+ f = fopen (AFS_SERVERMAGICKRBCONF, "r");
+ if (f != NULL) {
+ if (fgets (buf, sizeof(buf), f) == NULL) {
+ free (d->cell);
+ d->cell = NULL;
+ fclose (f);
+ krb5_set_error_message (context, EINVAL,
+ N_("No realm in ThisCell file %s", ""),
+ AFS_SERVERMAGICKRBCONF);
+ return EINVAL;
+ }
+ buf[strcspn(buf, "\n")] = '\0';
+ fclose(f);
+ }
+ /* uppercase */
+ for (cp = buf; *cp != '\0'; cp++)
+ *cp = toupper((unsigned char)*cp);
+
+ d->realm = strdup (buf);
+ if (d->realm == NULL) {
+ free (d->cell);
+ d->cell = NULL;
+ return krb5_enomem(context);
+ }
+ return 0;
+}
+
+/*
+ * init and get filename
+ */
+
+static krb5_error_code KRB5_CALLCONV
+akf_resolve(krb5_context context, const char *name, krb5_keytab id)
+{
+ int ret;
+ struct akf_data *d = calloc(1, sizeof (struct akf_data));
+
+ if (d == NULL)
+ return krb5_enomem(context);
+
+ d->num_entries = 0;
+ ret = get_cell_and_realm (context, d);
+ if (ret) {
+ free (d);
+ return ret;
+ }
+ d->filename = strdup (name);
+ if (d->filename == NULL) {
+ free (d->cell);
+ free (d->realm);
+ free (d);
+ return krb5_enomem(context);
+ }
+ id->data = d;
+
+ return 0;
+}
+
+/*
+ * cleanup
+ */
+
+static krb5_error_code KRB5_CALLCONV
+akf_close(krb5_context context, krb5_keytab id)
+{
+ struct akf_data *d = id->data;
+
+ free (d->filename);
+ free (d->cell);
+ free (d);
+ return 0;
+}
+
+/*
+ * Return filename
+ */
+
+static krb5_error_code KRB5_CALLCONV
+akf_get_name(krb5_context context,
+ krb5_keytab id,
+ char *name,
+ size_t name_sz)
+{
+ struct akf_data *d = id->data;
+
+ strlcpy (name, d->filename, name_sz);
+ return 0;
+}
+
+/*
+ * Init
+ */
+
+static krb5_error_code KRB5_CALLCONV
+akf_start_seq_get(krb5_context context,
+ krb5_keytab id,
+ krb5_kt_cursor *c)
+{
+ int32_t ret;
+ struct akf_data *d = id->data;
+
+ c->fd = open (d->filename, O_RDONLY | O_BINARY | O_CLOEXEC, 0600);
+ if (c->fd < 0) {
+ ret = errno;
+ krb5_set_error_message(context, ret,
+ N_("keytab afs keyfile open %s failed: %s", ""),
+ d->filename, strerror(ret));
+ return ret;
+ }
+
+ c->data = NULL;
+ c->sp = krb5_storage_from_fd(c->fd);
+ if (c->sp == NULL) {
+ close(c->fd);
+ krb5_clear_error_message (context);
+ return KRB5_KT_NOTFOUND;
+ }
+ krb5_storage_set_eof_code(c->sp, KRB5_KT_END);
+
+ ret = krb5_ret_uint32(c->sp, &d->num_entries);
+ if(ret || d->num_entries > INT_MAX / 8) {
+ krb5_storage_free(c->sp);
+ close(c->fd);
+ krb5_clear_error_message (context);
+ if(ret == KRB5_KT_END)
+ return KRB5_KT_NOTFOUND;
+ return ret;
+ }
+
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+akf_next_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry,
+ krb5_kt_cursor *cursor)
+{
+ struct akf_data *d = id->data;
+ int32_t kvno;
+ off_t pos;
+ int ret;
+
+ pos = krb5_storage_seek(cursor->sp, 0, SEEK_CUR);
+
+ if ((pos - 4) / (4 + 8) >= d->num_entries)
+ return KRB5_KT_END;
+
+ ret = krb5_make_principal (context, &entry->principal,
+ d->realm, "afs", d->cell, NULL);
+ if (ret)
+ goto out;
+
+ ret = krb5_ret_int32(cursor->sp, &kvno);
+ if (ret) {
+ krb5_free_principal (context, entry->principal);
+ goto out;
+ }
+
+ entry->vno = kvno;
+
+ if (cursor->data)
+ entry->keyblock.keytype = ETYPE_DES_CBC_MD5;
+ else
+ entry->keyblock.keytype = ETYPE_DES_CBC_CRC;
+ entry->keyblock.keyvalue.length = 8;
+ entry->keyblock.keyvalue.data = malloc (8);
+ if (entry->keyblock.keyvalue.data == NULL) {
+ krb5_free_principal (context, entry->principal);
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ ret = krb5_storage_read(cursor->sp, entry->keyblock.keyvalue.data, 8);
+ if(ret != 8)
+ ret = (ret < 0) ? errno : KRB5_KT_END;
+ else
+ ret = 0;
+
+ entry->timestamp = time(NULL);
+ entry->flags = 0;
+ entry->aliases = NULL;
+
+ out:
+ if (cursor->data) {
+ krb5_storage_seek(cursor->sp, pos + 4 + 8, SEEK_SET);
+ cursor->data = NULL;
+ } else
+ cursor->data = cursor;
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+akf_end_seq_get(krb5_context context,
+ krb5_keytab id,
+ krb5_kt_cursor *cursor)
+{
+ krb5_storage_free(cursor->sp);
+ close(cursor->fd);
+ cursor->data = NULL;
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+akf_add_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry)
+{
+ struct akf_data *d = id->data;
+ int fd, created = 0;
+ krb5_error_code ret;
+ int32_t len;
+ krb5_storage *sp;
+
+
+ if (entry->keyblock.keyvalue.length != 8)
+ return 0;
+ switch(entry->keyblock.keytype) {
+ case ETYPE_DES_CBC_CRC:
+ case ETYPE_DES_CBC_MD4:
+ case ETYPE_DES_CBC_MD5:
+ break;
+ default:
+ return 0;
+ }
+
+ fd = open (d->filename, O_RDWR | O_BINARY | O_CLOEXEC);
+ if (fd < 0) {
+ fd = open (d->filename,
+ O_RDWR | O_BINARY | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
+ if (fd < 0) {
+ ret = errno;
+ krb5_set_error_message(context, ret,
+ N_("open keyfile(%s): %s", ""),
+ d->filename,
+ strerror(ret));
+ return ret;
+ }
+ created = 1;
+ }
+
+ sp = krb5_storage_from_fd(fd);
+ if(sp == NULL) {
+ close(fd);
+ return krb5_enomem(context);
+ }
+ if (created)
+ len = 0;
+ else {
+ if(krb5_storage_seek(sp, 0, SEEK_SET) < 0) {
+ ret = errno;
+ krb5_storage_free(sp);
+ close(fd);
+ krb5_set_error_message(context, ret,
+ N_("seeking in keyfile: %s", ""),
+ strerror(ret));
+ return ret;
+ }
+
+ ret = krb5_ret_int32(sp, &len);
+ if(ret) {
+ krb5_storage_free(sp);
+ close(fd);
+ return ret;
+ }
+ }
+
+ /*
+ * Make sure we don't add the entry twice, assumes the DES
+ * encryption types are all the same key.
+ */
+ if (len > 0) {
+ int32_t kvno;
+ int i;
+
+ for (i = 0; i < len; i++) {
+ ret = krb5_ret_int32(sp, &kvno);
+ if (ret) {
+ krb5_set_error_message (context, ret,
+ N_("Failed getting kvno from keyfile", ""));
+ goto out;
+ }
+ if(krb5_storage_seek(sp, 8, SEEK_CUR) < 0) {
+ ret = errno;
+ krb5_set_error_message (context, ret,
+ N_("Failed seeing in keyfile: %s", ""),
+ strerror(ret));
+ goto out;
+ }
+ if (kvno == entry->vno) {
+ ret = 0;
+ goto out;
+ }
+ }
+ }
+
+ len++;
+
+ if(krb5_storage_seek(sp, 0, SEEK_SET) < 0) {
+ ret = errno;
+ krb5_set_error_message (context, ret,
+ N_("Failed seeing in keyfile: %s", ""),
+ strerror(ret));
+ goto out;
+ }
+
+ ret = krb5_store_int32(sp, len);
+ if(ret) {
+ ret = errno;
+ krb5_set_error_message (context, ret,
+ N_("keytab keyfile failed new length", ""));
+ goto out;
+ }
+
+ if(krb5_storage_seek(sp, (len - 1) * (8 + 4), SEEK_CUR) < 0) {
+ ret = errno;
+ krb5_set_error_message (context, ret,
+ N_("seek to end: %s", ""), strerror(ret));
+ goto out;
+ }
+
+ ret = krb5_store_int32(sp, entry->vno);
+ if(ret) {
+ krb5_set_error_message(context, ret,
+ N_("keytab keyfile failed store kvno", ""));
+ goto out;
+ }
+ ret = krb5_storage_write(sp, entry->keyblock.keyvalue.data,
+ entry->keyblock.keyvalue.length);
+ if(ret != entry->keyblock.keyvalue.length) {
+ if (ret < 0)
+ ret = errno;
+ else
+ ret = ENOTTY;
+ krb5_set_error_message(context, ret,
+ N_("keytab keyfile failed to add key", ""));
+ goto out;
+ }
+ ret = 0;
+out:
+ krb5_storage_free(sp);
+ close (fd);
+ return ret;
+}
+
+const krb5_kt_ops krb5_akf_ops = {
+ "AFSKEYFILE",
+ akf_resolve,
+ akf_get_name,
+ akf_close,
+ NULL, /* destroy */
+ NULL, /* get */
+ akf_start_seq_get,
+ akf_next_entry,
+ akf_end_seq_get,
+ akf_add_entry,
+ NULL, /* remove */
+ NULL,
+ 0
+};
+
+#endif /* HEIMDAL_SMALLER */
diff --git a/third_party/heimdal/lib/krb5/keytab_memory.c b/third_party/heimdal/lib/krb5/keytab_memory.c
new file mode 100644
index 0000000..87953a6
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/keytab_memory.c
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/* memory operations -------------------------------------------- */
+
+struct mkt_data {
+ krb5_keytab_entry *entries;
+ int num_entries;
+ char *name;
+ int refcount;
+ struct mkt_data *next;
+};
+
+/* this mutex protects mkt_head, ->refcount, and ->next
+ * content is not protected (name is static and need no protection)
+ */
+static HEIMDAL_MUTEX mkt_mutex = HEIMDAL_MUTEX_INITIALIZER;
+static struct mkt_data *mkt_head;
+
+
+static krb5_error_code KRB5_CALLCONV
+mkt_resolve(krb5_context context, const char *name, krb5_keytab id)
+{
+ struct mkt_data *d;
+
+ HEIMDAL_MUTEX_lock(&mkt_mutex);
+
+ for (d = mkt_head; d != NULL; d = d->next)
+ if (strcmp(d->name, name) == 0)
+ break;
+ if (d) {
+ if (d->refcount < 1)
+ krb5_abortx(context, "Double close on memory keytab, "
+ "refcount < 1 %d", d->refcount);
+ d->refcount++;
+ id->data = d;
+ HEIMDAL_MUTEX_unlock(&mkt_mutex);
+ return 0;
+ }
+
+ d = calloc(1, sizeof(*d));
+ if(d == NULL) {
+ HEIMDAL_MUTEX_unlock(&mkt_mutex);
+ return krb5_enomem(context);
+ }
+ d->name = strdup(name);
+ if (d->name == NULL) {
+ HEIMDAL_MUTEX_unlock(&mkt_mutex);
+ free(d);
+ return krb5_enomem(context);
+ }
+ d->entries = NULL;
+ d->num_entries = 0;
+ d->refcount = 1;
+ d->next = mkt_head;
+ mkt_head = d;
+ HEIMDAL_MUTEX_unlock(&mkt_mutex);
+ id->data = d;
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mkt_close(krb5_context context, krb5_keytab id)
+{
+ struct mkt_data *d = id->data, **dp;
+ int i;
+
+ HEIMDAL_MUTEX_lock(&mkt_mutex);
+ if (d->refcount < 1)
+ krb5_abortx(context,
+ "krb5 internal error, memory keytab refcount < 1 on close");
+
+ if (--d->refcount > 0) {
+ HEIMDAL_MUTEX_unlock(&mkt_mutex);
+ return 0;
+ }
+ for (dp = &mkt_head; *dp != NULL; dp = &(*dp)->next) {
+ if (*dp == d) {
+ *dp = d->next;
+ break;
+ }
+ }
+ HEIMDAL_MUTEX_unlock(&mkt_mutex);
+
+ free(d->name);
+ for(i = 0; i < d->num_entries; i++)
+ krb5_kt_free_entry(context, &d->entries[i]);
+ free(d->entries);
+ free(d);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mkt_get_name(krb5_context context,
+ krb5_keytab id,
+ char *name,
+ size_t namesize)
+{
+ struct mkt_data *d = id->data;
+ strlcpy(name, d->name, namesize);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mkt_start_seq_get(krb5_context context,
+ krb5_keytab id,
+ krb5_kt_cursor *c)
+{
+ /* XXX */
+ c->fd = 0;
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mkt_next_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry,
+ krb5_kt_cursor *c)
+{
+ struct mkt_data *d = id->data;
+ if(c->fd >= d->num_entries)
+ return KRB5_KT_END;
+ return krb5_kt_copy_entry_contents(context, &d->entries[c->fd++], entry);
+}
+
+static krb5_error_code KRB5_CALLCONV
+mkt_end_seq_get(krb5_context context,
+ krb5_keytab id,
+ krb5_kt_cursor *cursor)
+{
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mkt_add_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry)
+{
+ struct mkt_data *d = id->data;
+ krb5_keytab_entry *tmp;
+ tmp = realloc(d->entries, (d->num_entries + 1) * sizeof(*d->entries));
+ if (tmp == NULL)
+ return krb5_enomem(context);
+ d->entries = tmp;
+ return krb5_kt_copy_entry_contents(context, entry,
+ &d->entries[d->num_entries++]);
+}
+
+static krb5_error_code KRB5_CALLCONV
+mkt_remove_entry(krb5_context context,
+ krb5_keytab id,
+ krb5_keytab_entry *entry)
+{
+ struct mkt_data *d = id->data;
+ krb5_keytab_entry *e, *end;
+ int found = 0;
+
+ if (d->num_entries == 0) {
+ krb5_clear_error_message(context);
+ return KRB5_KT_NOTFOUND;
+ }
+
+ /* do this backwards to minimize copying */
+ for(end = d->entries + d->num_entries, e = end - 1; e >= d->entries; e--) {
+ if(krb5_kt_compare(context, e, entry->principal,
+ entry->vno, entry->keyblock.keytype)) {
+ krb5_kt_free_entry(context, e);
+ memmove(e, e + 1, (end - e - 1) * sizeof(*e));
+ memset(end - 1, 0, sizeof(*end));
+ d->num_entries--;
+ end--;
+ found = 1;
+ }
+ }
+ if (!found) {
+ krb5_clear_error_message (context);
+ return KRB5_KT_NOTFOUND;
+ }
+ e = realloc(d->entries, d->num_entries * sizeof(*d->entries));
+ if(e != NULL || d->num_entries == 0)
+ d->entries = e;
+ return 0;
+}
+
+const krb5_kt_ops krb5_mkt_ops = {
+ "MEMORY",
+ mkt_resolve,
+ mkt_get_name,
+ mkt_close,
+ NULL, /* destroy */
+ NULL, /* get */
+ mkt_start_seq_get,
+ mkt_next_entry,
+ mkt_end_seq_get,
+ mkt_add_entry,
+ mkt_remove_entry,
+ NULL,
+ 0
+};
diff --git a/third_party/heimdal/lib/krb5/krb5-plugin.7 b/third_party/heimdal/lib/krb5/krb5-plugin.7
new file mode 100644
index 0000000..0b1e729
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5-plugin.7
@@ -0,0 +1,359 @@
+.\" Copyright (c) 1999 - 2005 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd December 21, 2011
+.Dt KRB5-PLUGIN 7
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5-plugin
+.Nd plugin interface for Heimdal
+.Sh SYNOPSIS
+.In krb5.h
+.In krb5/an2ln_plugin.h
+.In krb5/ccache_plugin.h
+.In krb5/db_plugin.h
+.In krb5/kuserok_plugin.h
+.In krb5/locate_plugin.h
+.In krb5/send_to_kdc_plugin.h
+.Sh DESCRIPTION
+Heimdal has a plugin interface. Plugins may be statically linked into
+Heimdal and registered via the
+.Xr krb5_plugin_register 3
+function, or they may be dynamically loaded from shared objects present
+in the Heimdal plugins directories.
+.Pp
+Plugins consist of a C struct whose struct name is given in the
+associated header file, such as, for example,
+.Va krb5plugin_kuserok_ftable
+and a pointer to which is either registered via
+.Xr krb5_plugin_register 3
+or via a plugin load function exported by a shared object.
+Plugin load functions should be named by concatenating the name defined in the
+associated header file with the string "plugin_load" (e.g.
+"krb5_plugin_kuserok_plugin_load" for the plugin for
+.Xr krb5_kuserok 3
+).
+The plugin load function must be of type
+.Va heim_plugin_load_ft
+which is:
+.Bd -literal -offset indent
+krb5_error_code HEIM_CALLCONV
+my_plugin_load(heim_pcontext context,
+ krb5_get_instance_func_t *get_instance,
+ size_t *num_plugins,
+ heim_plugin_common_ftable_cp **plugins);
+
+.Ed
+where
+.Va HEIM_CALLCONV
+is
+.Va __stdcall
+on Windows.
+.Pp
+The plugin should set the get_instance output parameter to the a
+function that will return the instances of its library
+dependencies. For example:
+.Bd -literal -offset indent
+static uintptr_t HEIM_LIB_CALL
+my_plugin_get_instance(const char *name)
+{
+ if (strcmp(name, "krb5") == 0)
+ return krb5_get_instance(name);
+ return 0;
+}
+.Ed
+.Pp
+The
+.Va get_instance
+function is used to check that dynamically-linked plugins are
+linked with the same Heimdal shared objects as the one loading
+and running the plugin.
+.Pp
+The output parameters
+.Va plugins
+and
+.Va n_plugins
+output an array of pointers to function tabls, and the number of
+those, respectively.
+.Pp
+The plugin structs for all plugin types always begin with the same three
+common fields:
+.Bl -enum -compact
+.It
+.Va minor_version
+, an int. Plugin minor versions are defined in each plugin type's
+associated header file.
+.It
+.Va init
+, a pointer to a function with two arguments, a
+.Va heim_pcontext
+(which for krb5 plugins is actually a krb5_context),
+and a
+.Va void **
+, returning a heim_error_code. This function will be called to
+initialize a plugin-specific context in the form of a
+.Va void *
+that will be output through the init function's second argument.
+.It
+.Va fini
+, a pointer to a function of one argument, a
+.Va void *
+, consisting of the plugin's context to be destroyed, and
+returning
+.Va void.
+.El
+.Pp
+Each plugin type may add fields to this struct following the above
+three. Plugins are typically invoked in no particular order until one
+succeeds or fails, or all return a special return value that indicates
+that the plugin was not applicable. For krb5 plugins,
+.Va KRB5_PLUGIN_NO_HANDLE
+indicates that the plugin was not applicable.
+.Pp
+Heimdal plugin callers either invoke all plugins until one returns an
+error or all return
+.Va KRB5_PLUGIN_NO_HANDLE
+, or invoke all plugins until one returns a value other than
+.Va KRB5_PLUGIN_NO_HANDLE
+with the expectation that only one plugin would return success and all
+oters would return
+.Va KRB5_PLUGIN_NO_HANDLE.
+Thus Heimdal plugin invokation can be deterministic in spite of
+non-deterministic invocation order.
+.Pp
+There is a database plugin system intended for many of the uses of
+databases in Heimdal. The plugin is expected to call
+.Xr heim_db_register 3
+from its
+.Va init
+entry point to register a DB type. The DB plugin's
+.Va fini
+function must do nothing, and the plugin must not provide any other
+entry points.
+.Pp
+The krb5_kuserok plugin adds a single field to its struct: a pointer to
+a function that implements kuserok functionality with the following
+form:
+.Bd -literal -offset indent
+static krb5_error_code
+kuserok(void *plug_ctx, krb5_context context, const char *rule,
+ unsigned int flags, const char *k5login_dir,
+ const char *luser, krb5_const_principal principal,
+ krb5_boolean *result)
+.Ed
+.Pp
+The
+.Va luser
+,
+.Va principal
+and
+.Va result
+arguments are self-explanatory (see
+.Xr krb5_kuserok 3
+). The
+.Va plug_ctx
+argument is the context output by the plugin's init function. The
+.Va rule
+argument is a kuserok rule from the krb5.conf file; each plugin is invoked once
+for each rule until all plugins fail or one succeeds. The
+.Va k5login_dir
+argument provides an alternative k5login file location, if not NULL.
+The
+.Va flags
+argument indicates whether the plugin may call
+.Xr krb5_aname_to_localname 3
+(KUSEROK_ANAME_TO_LNAME_OK), and whether k5login databases are expected to be
+authoritative (KUSEROK_K5LOGIN_IS_AUTHORITATIVE).
+.Pp
+The plugin for
+.Xr krb5_aname_to_localname 3
+is named "an2ln" and has a single extra field for the plugin struct:
+.Bd -literal -offset indent
+typedef krb5_error_code (*set_result_f)(void *, const char *);
+
+static krb5_error_code
+an2ln(void *plug_ctx, krb5_context context, const char *rule,
+ krb5_const_principal aname, set_result_f set_res_f, void *set_res_ctx)
+.Ed
+.Pp
+The arguments for the
+.Va an2ln
+plugin are similar to those of the kuserok plugin, but the result, being
+a string, is set by calling the
+.Va set_res_f
+function argument with the
+.Va set_res_ctx
+and result string as arguments. The
+.Va set_res_f
+function will make a copy of the string.
+.Sh FILES
+.Bl -tag -compact
+.It Pa libdir/plugin/krb5/*
+Shared objects containing plugins for Heimdal.
+.El
+.Sh EXAMPLES
+.Pp
+An example an2ln plugin that maps principals to a constant "nouser"
+follows:
+.Pp
+.Bd -literal -offset indent
+#include <krb5/an2ln_plugin.h>
+
+/* Note that `context' here is actually a krb5_context value */
+static krb5_error_code KRB5_CALLCONV
+nouser_plug_init(heim_pcontext context, void **ctx)
+{
+ *ctx = NULL;
+ return 0;
+}
+
+static void KRB5_CALLCONV nouser_plug_fini(void *ctx) { }
+
+static krb5_error_code KRB5_CALLCONV
+nouser_plug_an2ln(void *plug_ctx, krb5_context context,
+ const char *rule,
+ krb5_const_principal aname,
+ set_result_f set_res_f, void *set_res_ctx)
+{
+ krb5_error_code ret;
+
+ if (strcmp(rule, "NOUSER") != 0)
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ ret = set_res_f(set_res_ctx, "nouser");
+
+ return ret;
+}
+
+krb5plugin_an2ln_ftable an2ln = {
+ KRB5_PLUGIN_AN2LN_VERSION_0,
+ nouser_plug_init,
+ nouser_plug_fini,
+ nouser_plug_an2ln,
+};
+
+static const krb5plugin_an2ln_ftable *const plugins[] = {
+ &an2ln
+};
+
+static uintptr_t
+an2ln_get_instance(const char *libname)
+{
+ if (strcmp(libname, "krb5") == 0)
+ return krb5_get_instance(libname);
+
+ return 0;
+}
+
+/* Note that `context' here is actually a krb5_context value */
+krb5_error_code
+an2ln_plugin_load(heim_pcontext context,
+ krb5_get_instance_func_t *get_instance,
+ size_t *num_plugins,
+ const krb5plugin_an2ln_ftable * const **pplugins)
+{
+ *get_instance = an2ln_get_instance;
+ *num_plugins = sizeof(plugins) / sizeof(plugins[0]);
+ *pplugins = plugins;
+ return 0;
+}
+.Ed
+.Pp
+An example kuserok plugin that rejects all requests follows. (Note that
+there exists a built-in plugin with this functionality; see
+.Xr krb5_kuserok 3
+).
+.Pp
+.Bd -literal -offset indent
+#include <krb5/kuserok_plugin.h>
+
+static krb5_error_code KRB5_CALLCONV
+reject_plug_init(heim_context context, void **ctx)
+{
+ *ctx = NULL;
+ return 0;
+}
+
+static void KRB5_CALLCONV reject_plug_fini(void *ctx) { }
+
+static krb5_error_code KRB5_CALLCONV
+reject_plug_kuserok(void *plug_ctx, krb5_context context, const char *rule,
+ unsigned int flags, const char *k5login_dir,
+ const char *luser, krb5_const_principal principal,
+ krb5_boolean *result)
+{
+ if (strcmp(rule, "REJECT") != 0)
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ *result = FALSE;
+ return 0;
+}
+
+static krb5plugin_kuserok_ftable kuserok = {
+ KRB5_PLUGIN_KUSEROK_VERSION_0,
+ reject_plug_init,
+ reject_plug_fini,
+ reject_plug_kuserok,
+};
+
+static const krb5plugin_kuserok_ftable *const plugins[] = {
+ &kuserok
+};
+
+static uintptr_t
+kuserok_get_instance(const char *libname)
+{
+ if (strcmp(libname, "krb5") == 0)
+ return krb5_get_instance(libname);
+
+ return 0;
+}
+
+krb5_error_code
+krb5_plugin_kuserok_plugin_load(
+ heim_context context,
+ krb5_get_instance_func_t *get_instance,
+ size_t *num_plugins,
+ const krb5plugin_kuserok_ftable * const **pplugins)
+{
+ *krb5_instance = kuserok_get_instance;
+ *num_plugins = sizeof(plugins) / sizeof(plugins[0]);
+ *pplugins = plugins;
+ return 0;
+}
+
+.Ed
+.Sh SEE ALSO
+.Xr krb5_plugin_register 3
+.Xr krb5_kuserok 3
+.Xr krb5_aname_to_localname 3
diff --git a/third_party/heimdal/lib/krb5/krb5-v4compat.h b/third_party/heimdal/lib/krb5/krb5-v4compat.h
new file mode 100644
index 0000000..2992976
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5-v4compat.h
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __KRB5_V4COMPAT_H__
+#define __KRB5_V4COMPAT_H__
+
+#include "krb_err.h"
+
+/*
+ * This file must only be included with v4 compat glue stuff in
+ * heimdal sources.
+ *
+ * It MUST NOT be installed.
+ */
+
+#define KRB_PROT_VERSION 4
+
+#define AUTH_MSG_KDC_REQUEST (1<<1)
+#define AUTH_MSG_KDC_REPLY (2<<1)
+#define AUTH_MSG_APPL_REQUEST (3<<1)
+#define AUTH_MSG_APPL_REQUEST_MUTUAL (4<<1)
+#define AUTH_MSG_ERR_REPLY (5<<1)
+#define AUTH_MSG_PRIVATE (6<<1)
+#define AUTH_MSG_SAFE (7<<1)
+#define AUTH_MSG_APPL_ERR (8<<1)
+#define AUTH_MSG_KDC_FORWARD (9<<1)
+#define AUTH_MSG_KDC_RENEW (10<<1)
+#define AUTH_MSG_DIE (63<<1)
+
+/* General definitions */
+#define KSUCCESS 0
+#define KFAILURE 255
+
+/* */
+
+#define MAX_KTXT_LEN 1250
+
+#define ANAME_SZ 40
+#define REALM_SZ 40
+#define SNAME_SZ 40
+#define INST_SZ 40
+
+struct ktext {
+ unsigned int length; /* Length of the text */
+ unsigned char dat[MAX_KTXT_LEN]; /* The data itself */
+ uint32_t mbz; /* zero to catch runaway strings */
+};
+
+struct credentials {
+ char service[ANAME_SZ]; /* Service name */
+ char instance[INST_SZ]; /* Instance */
+ char realm[REALM_SZ]; /* Auth domain */
+ char session[8]; /* Session key */
+ int lifetime; /* Lifetime */
+ int kvno; /* Key version number */
+ struct ktext ticket_st; /* The ticket itself */
+ int32_t issue_date; /* The issue time */
+ char pname[ANAME_SZ]; /* Principal's name */
+ char pinst[INST_SZ]; /* Principal's instance */
+};
+
+#define TKTLIFENUMFIXED 64
+#define TKTLIFEMINFIXED 0x80
+#define TKTLIFEMAXFIXED 0xBF
+#define TKTLIFENOEXPIRE 0xFF
+#define MAXTKTLIFETIME (30*24*3600) /* 30 days */
+#ifndef NEVERDATE
+#define NEVERDATE ((time_t)0x7fffffffL)
+#endif
+
+#define KERB_ERR_NULL_KEY 10
+
+#define CLOCK_SKEW 5*60
+
+#ifndef TKT_ROOT
+#define TKT_ROOT "%{TEMP}/tkt"
+#endif
+
+struct _krb5_krb_auth_data {
+ int8_t k_flags; /* Flags from ticket */
+ char *pname; /* Principal's name */
+ char *pinst; /* His Instance */
+ char *prealm; /* His Realm */
+ uint32_t checksum; /* Data checksum (opt) */
+ krb5_keyblock session; /* Session Key */
+ unsigned char life; /* Life of ticket */
+ uint32_t time_sec; /* Time ticket issued */
+ uint32_t address; /* Address in ticket */
+};
+
+KRB5_LIB_FUNCTION time_t KRB5_LIB_CALL
+_krb5_krb_life_to_time (int, int);
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+_krb5_krb_time_to_life (time_t, time_t);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_krb_tf_setup (krb5_context, struct credentials *,
+ const char *, int);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_krb_dest_tkt(krb5_context, const char *);
+
+#define krb_time_to_life _krb5_krb_time_to_life
+#define krb_life_to_time _krb5_krb_life_to_time
+
+#endif /* __KRB5_V4COMPAT_H__ */
diff --git a/third_party/heimdal/lib/krb5/krb5.conf.5 b/third_party/heimdal/lib/krb5/krb5.conf.5
new file mode 100644
index 0000000..8a9623e
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5.conf.5
@@ -0,0 +1,1442 @@
+.\" Copyright (c) 1999 - 2005 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 4, 2005
+.Dt KRB5.CONF 5
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5.conf
+.Nd configuration file for Kerberos 5
+.Sh SYNOPSIS
+.In krb5.h
+.Sh DESCRIPTION
+The
+.Nm
+file specifies several configuration parameters for the Kerberos 5
+library, as well as for some programs.
+.Pp
+The file consists of one or more sections, containing a number of
+bindings.
+The value of each binding can be either a string or a list of other
+bindings.
+The grammar looks like:
+.Bd -literal -offset indent
+file:
+ /* empty */
+ sections
+ includes
+
+sections:
+ section sections
+ section
+
+section:
+ '[' section_name ']' bindings
+
+section_name:
+ STRING
+
+bindings:
+ binding bindings
+ binding
+
+binding:
+ name '=' STRING
+ name '=' '{' bindings '}'
+
+name:
+ STRING
+
+includes:
+ 'include' path
+ 'includedir' path
+
+path: STRING
+
+.Ed
+.Li STRINGs
+consists of one or more non-whitespace characters.
+.Pp
+Files and directories may be included by absolute path, with percent
+token expansion (see the TOKEN EXPANSION section). Including a
+directory causes all files in the directory to be included as if each
+file had been included separately, but only files whose names consist of
+alphanumeric, hyphen, and underscore are included, though they may also
+end in '.conf'.
+.Pp
+STRINGs that are specified later in this man-page uses the following
+notation.
+.Bl -tag -width "xxx" -offset indent
+.It boolean
+values can be either yes/true or no/false.
+.It time
+values can be a list of year, month, day, hour, min, second.
+Example: 1 month 2 days 30 min.
+If no unit is given, seconds is assumed.
+.It etypes
+valid encryption types are: des-cbc-crc, des-cbc-md4, des-cbc-md5,
+des3-cbc-sha1, arcfour-hmac-md5, aes128-cts-hmac-sha1-96, aes256-cts-hmac-sha1-96,
+aes128-cts-hmac-sha256-128, and aes256-cts-hmac-sha384-192.
+.It address
+an address can be either a IPv4 or a IPv6 address.
+.El
+.Pp
+Currently recognised sections and bindings are:
+.Bl -tag -width "xxx" -offset indent
+.It Li [appdefaults]
+Specifies the default values to be used for Kerberos applications.
+You can specify defaults per application, realm, or a combination of
+these.
+The preference order is:
+.Bl -enum -compact
+.It
+.Va application Va realm Va option
+.It
+.Va application Va option
+.It
+.Va realm Va option
+.It
+.Va option
+.El
+.Pp
+The supported options are:
+.Bl -tag -width "xxx" -offset indent
+.It Li forwardable = Va boolean
+When obtaining initial credentials, make the credentials forwardable.
+.It Li proxiable = Va boolean
+When obtaining initial credentials, make the credentials proxiable.
+.It Li no-addresses = Va boolean
+When obtaining initial credentials, request them for an empty set of
+addresses, making the tickets valid from any address.
+.It Li ticket_lifetime = Va time
+Default ticket lifetime.
+.It Li renew_lifetime = Va time
+Default renewable ticket lifetime.
+.It Li encrypt = Va boolean
+Use encryption, when available.
+.It Li forward = Va boolean
+Forward credentials to remote host (for
+.Xr rsh 1 ,
+.Xr telnet 1 ,
+etc).
+.It Li historical_anon_pkinit = Va boolean
+Enable legacy anonymous pkinit command-line syntax.
+With this option set to
+.Li true,
+the
+.Xr kinit 1
+.Fl Fl anonymous
+command with no principal argument specified will request an anonymous pkinit
+ticket from the default realm.
+If a principal argument is specified, it is used as an explicit realm name for
+anonymous pkinit even without an
+.Li @
+prefix.
+.It Li delegate-destination-tgt = Va boolean
+When forwarding credentials to a remote host, forward a TGT for the
+realm of the destination host rather than a TGT for the user's realm.
+This is useful when hosts in the remote realm should not or cannot
+(e.g. firewalled from user realm's KDC) obtain tickets for services
+in the user's realm. When the user's realm and the host's realm are
+the same, this parameter has no effect. The setting can be applied
+to a single realm as follows:
+.Bd -literal -offset indent
+EXAMPLE.COM = {
+ delegate-destination-tgt = true
+}
+.Ed
+.El
+.It Li [libdefaults]
+.Bl -tag -width "xxx" -offset indent
+.It Li default_realm = Va REALM
+Default realm to use, this is also known as your
+.Dq local realm .
+The default is the result of
+.Fn krb5_get_host_realm "local hostname" .
+.It Li allow_weak_crypto = Va boolean
+are weak crypto algorithms allowed to be used, among others, DES is
+considered weak.
+.It Li clockskew = Va time
+Maximum time differential (in seconds) allowed when comparing
+times.
+Default is 300 seconds (five minutes).
+.It Li kdc_timeout = Va time
+Maximum time to wait for a reply from the kdc, default is 3 seconds.
+.It Li capath = {
+.Bl -tag -width "xxx" -offset indent
+.It Va destination-realm Li = Va next-hop-realm
+.It ...
+.It Li }
+.El
+This is deprecated, see the
+.Li capaths
+section below.
+.It Li default_cc_type = Va cctype
+sets the default credentials type.
+.It Li default_cc_name = Va ccname
+the default credentials cache name.
+If you want to change the type only use
+.Li default_cc_type .
+The string can contain variables that are expanded at runtime. See the TOKEN
+EXPANSION section.
+.It Li default_file_cache_collections = Va FILE:/path/with/tokens ...
+This multi-valued parameter allows more than one path to be
+configured for the FILE credentials cache type to look in. The FILE
+credentials cache type will also consider file names whose prefixes
+match these and end in
+.Va +name
+as subsidiary caches in the collection. The values of this
+parameter are subject to token expansion. See the TOKEN EXPANSION
+section.
+.It Li enable_file_cache_iteration = Va boolean
+If enabled, the
+.Va FILE
+credential cache type will support iteration of all subsidiary
+caches in the default collection, meaning that
+.Xr kinit 1
+.Va -l
+option will list them. This does require scanning the directory
+containing a given
+.Va FILE
+ccache, which, if it is
+.Va /tmp
+may be a slow operation. Defaults to false.
+.It Li default_etypes = Va etypes ...
+A list of default encryption types to use. (Default: all enctypes if
+allow_weak_crypto = TRUE, else all enctypes except single DES enctypes.)
+.It Li default_as_etypes = Va etypes ...
+A list of default encryption types to use in AS requests. (Default: the
+value of default_etypes.)
+.It Li default_tgs_etypes = Va etypes ...
+A list of default encryption types to use in TGS requests. (Default:
+the value of default_etypes.)
+.It Li default_etypes_des = Va etypes ...
+A list of default encryption types to use when requesting a DES credential.
+.It Li default_keytab_name = Va keytab
+The keytab to use if no other is specified, default is
+.Dq FILE:/etc/krb5.keytab .
+.It Li default_client_keytab_name = Va keytab
+The keytab to use for client credential acquisition if no other is
+specified, default is
+.Dq FILE:%{LOCALSTATEDIR}/user/%{euid}/client.keytab .
+See the TOKEN EXPANSION section.
+.It Li dns_lookup_kdc = Va boolean
+Use DNS SRV records to lookup KDC services location.
+.It Li dns_lookup_realm = Va boolean
+Use DNS TXT records to lookup domain to realm mappings.
+.It Li enforce_ok_as_delegate = Va boolean
+If this flag to true, GSSAPI credential delegation will be
+disabled when the
+.Ar ok-as-delegate
+flag is not set in the service ticket.
+If this flag is false, the
+.Ar ok-as-delegate
+ticket flag is only enforced when an application specifically
+requests enforcement.
+The default value is false.
+.It Li kdc_timesync = Va boolean
+Try to keep track of the time differential between the local machine
+and the KDC, and then compensate for that when issuing requests.
+.It Li max_retries = Va number
+The max number of times to try to contact each KDC.
+.It Li large_msg_size = Va number
+The threshold where protocols with tiny maximum message sizes are not
+considered usable to send messages to the KDC.
+.It Li ticket_lifetime = Va time
+Default ticket lifetime.
+.It Li renew_lifetime = Va time
+Default renewable ticket lifetime.
+.It Li forwardable = Va boolean
+When obtaining initial credentials, make the credentials forwardable.
+This option is also valid in the [realms] section.
+.It Li proxiable = Va boolean
+When obtaining initial credentials, make the credentials proxiable.
+This option is also valid in the [realms] section.
+.It Li verify_ap_req_nofail = Va boolean
+If enabled, failure to verify credentials against a local key is a
+fatal error.
+The application has to be able to read the corresponding service key
+for this to work.
+Some applications, like
+.Xr su 1 ,
+enable this option unconditionally.
+.It Li warn_pwexpire = Va time
+How soon to warn for expiring password.
+Default is seven days.
+.It Li http_proxy = Va proxy-spec
+A HTTP-proxy to use when talking to the KDC via HTTP.
+.It Li dns_proxy = Va proxy-spec
+Enable using DNS via HTTP.
+.It Li extra_addresses = Va address ...
+A list of addresses to get tickets for along with all local addresses.
+.It Li time_format = Va string
+How to print time strings in logs, this string is passed to
+.Xr strftime 3 .
+.It Li date_format = Va string
+How to print date strings in logs, this string is passed to
+.Xr strftime 3 .
+.It Li log_utc = Va boolean
+Write log-entries using UTC instead of your local time zone.
+.It Li scan_interfaces = Va boolean
+Scan all network interfaces for addresses, as opposed to simply using
+the address associated with the system's host name.
+.It Li fcache_version = Va int
+Use file credential cache format version specified.
+.It Li fcc-mit-ticketflags = Va boolean
+Use MIT compatible format for file credential cache.
+It's the field ticketflags that is stored in reverse bit order for
+older than Heimdal 0.7.
+Setting this flag to
+.Dv TRUE
+makes it store the MIT way, this is default for Heimdal 0.7.
+.It Li check-rd-req-server
+If set to "ignore", the framework will ignore any of the server input to
+.Xr krb5_rd_req 3 ,
+this is very useful when the GSS-API server input the
+wrong server name into the gss_accept_sec_context call.
+.It Li k5login_directory = Va directory
+Alternative location for user .k5login files. This option is provided
+for compatibility with MIT krb5 configuration files. This path is
+subject to percent token expansion (see TOKEN EXPANSION).
+.It Li k5login_authoritative = Va boolean
+If true then if a principal is not found in k5login files then
+.Xr krb5_userok 3
+will not fallback on principal to username mapping. This option is
+provided for compatibility with MIT krb5 configuration files.
+.It Li kuserok = Va rule ...
+Specifies
+.Xr krb5_userok 3
+behavior. If multiple values are given, then
+.Xr krb5_userok 3
+will evaluate them in order until one succeeds or all fail. Rules are
+implemented by plugins, with three built-in plugins
+described below. Default: USER-K5LOGIN SIMPLE DENY.
+.It Li kuserok = Va DENY
+If set and evaluated then
+.Xr krb5_userok 3
+will deny access to the given username no matter what the principal name
+might be.
+.It Li kuserok = Va SIMPLE
+If set and evaluated then
+.Xr krb5_userok 3
+will use principal to username mapping (see auth_to_local below). If
+the principal maps to the requested username then access is allowed.
+.It Li kuserok = Va SYSTEM-K5LOGIN[:directory]
+If set and evaluated then
+.Xr krb5_userok 3
+will use k5login files named after the
+.Va luser
+argument to
+.Xr krb5_userok 3
+in the given directory or in
+.Pa /etc/k5login.d/ .
+K5login files are text files, with each line containing just a principal
+name; principals apearing in a user's k5login file are permitted access
+to the user's account. Note: this rule performs no ownership nor
+permissions checks on k5login files; proper ownership and
+permissions/ACLs are expected due to the k5login location being a
+system location.
+.It Li kuserok = Va USER-K5LOGIN
+If set and evaluated then
+.Xr krb5_userok 3
+will use
+.Pa ~luser/.k5login
+and
+.Pa ~luser/.k5login.d/* .
+User k5login files and directories must be owned by the user and must
+not have world nor group write permissions.
+.It Li aname2lname-text-db = Va filename
+The named file must be a sorted (in increasing order) text file where
+every line consists of an unparsed principal name optionally followed by
+whitespace and a username. The aname2lname function will do a binary
+search on this file, if configured, looking for lines that match the
+given principal name, and if found the given username will be used, or,
+if the username is missing, an error will be returned. If the file
+doesn't exist, or if no matching line is found then other plugins will
+be allowed to run.
+.It Li fcache_strict_checking
+strict checking in FILE credential caches that owner, no symlink and
+permissions is correct.
+.It Li moduli = Va FILE
+Names a file that contains acceptable modular Diffie-Hellman
+groups for PKINIT.
+The given file should contain lines with whitespace-separated
+fields in this order:
+.Va name, nbits, p, g, q .
+Lines starting with a
+.Va #
+are comments.
+.It Li pkinit_dh_min_bits = Va NUMBER
+PKINIT client's minimum acceptable modular Diffie-Hellman public
+key size in bits.
+.It Li enable-kx509 = Va boolean
+Enable use of kx509 so that every TGT that can has a corresponding
+PKIX certificate. Default: false.
+.It Li kx509_gen_key_type = Va public-key-type
+Type of public key for kx509 private key generation. Defaults to
+.Va rsa
+and currently only
+.Va rsa
+is supported.
+.It Li kx509_gen_rsa_key_size = Va number-of-bits
+RSA key size for kx509. Defaults to 2048.
+.It Li kx509_store = path
+A file path into which to write a certificate obtained with
+kx509, and its private key, when attempting kx509 optimistically
+using credentials from a default ccache. Tokens will be
+expanded.
+.It Li kx509_hostname = Va hostname
+If set, then the kx509 client will use this hostname for the
+kx509 service. This can also be set in the
+.Li [realm]
+section on a per-realm basis. If not set then a TGS name will be
+used.
+.It Li name_canon_rules = Va rules
+One or more service principal name canonicalization rules. Each rule
+consists of one or more tokens separated by colon (':'). Currently
+these rules are used only for hostname canonicalization (usually when
+getting a service ticket, from a ccache or a TGS, but also when
+acquiring GSS initiator credentials from a keytab). These rules can be
+used to implement DNS resolver-like search lists without having to use
+DNS.
+.Pp
+NOTE: Name canonicalization rules are an experimental feature.
+.Pp
+The first token is a rule type, one of:
+.Va as-is,
+.Va qualify, or
+.Va nss.
+.Pp
+Any remaining tokens must be options tokens:
+.Va use_fast
+(use FAST to protect TGS exchanges; currently not supported),
+.Va use_dnssec
+(use DNSSEC to protect hostname lookups; currently not supported),
+.Va ccache_only
+,
+.Va use_referrals,
+.Va no_referrals,
+.Va lookup_realm,
+.Va mindots=N,
+.Va maxdots=N,
+.Va order=N,
+domain=
+.Va domain,
+realm=
+.Va realm,
+match_domain=
+.Va domain,
+and match_realm=
+.Va realm.
+.Pp
+When trying to obtain a service ticket for a host-based service
+principal name, name canonicalization rules are applied to that name in
+the order given, one by one, until one succeds (a service ticket is
+obtained), or all fail. Similarly when acquiring GSS initiator
+credentials from a keytab, and when comparing a non-canonical GSS name
+to a canonical one.
+.Pp
+For each rule the system checks that the hostname has at least
+.Va mindots
+periods (if given) in it, at most
+.Va maxdots
+periods (if given), that the hostname ends in the given
+.Va match_domain
+(if given),
+and that the realm of the principal matches the
+.Va match_realm
+(if given).
+.Pp
+.Va As-is
+rules leave the hostname unmodified but may set a realm.
+.Va Qualify
+rules qualify the hostname with the given
+.Va domain
+and also may set the realm.
+The
+.Va nss
+rule uses the system resolver to lookup the host's canonical name and is
+usually not secure. Note that using the
+.Va nss
+rule type implies having to have principal aliases in the HDB (though
+not necessarily in keytabs).
+.Pp
+The empty realm denotes "ask the client's realm's TGS". The empty realm
+may be set as well as matched.
+.Pp
+The order in which rules are applied is as follows: first all the rules
+with explicit
+.Va order
+then all other rules in the order in which they appear. If any two
+rules have the same explicit
+.Va order ,
+their order of appearance in krb5.conf breaks the tie. Explicitly
+specifying order can be useful where tools read and write the
+configuration file without preserving parameter order.
+.Pp
+Malformed rules are ignored.
+.It Li allow_hierarchical_capaths = Va boolean
+When validating cross-realm transit paths, absent any explicit capath from the
+client realm to the server realm, allow a hierarchical transit path via the
+common ancestor domain of the two realms.
+Defaults to true.
+Note, absent an explicit setting, hierarchical capaths are always used by
+the KDC when generating a referral to a destination with which is no direct
+trust.
+.It Li client_aware_channel_bindings = Va boolean
+If this flag is true, then all application protocol authentication
+requests will be flagged to indicate that the application supports
+channel bindings when operating over a secure channel.
+The default value is false.
+.It Li check_pac = Va boolean
+If this flag is true and a Windows Privilege Attribute Certificate (PAC)
+is present in the ticket authorization data, then
+.Xr krb5_rd_req 3
+will validate the PAC before returning success. The default value is true.
+.It Li report_canonical_client_name = Va boolean
+If this flag is true, then the canonical client name from the PAC will
+be used instead of the client name in the ticket. The default value is false.
+Note that setting it to true implicitly sets
+.Va check_pac
+to true.
+.El
+.It Li [domain_realm]
+This is a list of mappings from DNS domain to Kerberos realm.
+.Pp
+It is used by the client and the TGS both to determine the realm
+of host-based service principal names based on the principal's
+hostname component.
+.Pp
+The client may try DNS to determine a host's realm; see the
+`dns_lookup_realm' parameter, and see below.
+.Pp
+The TGS will issue a referral when a host-based service does not
+exist in the requested realm but can be mapped with these rules
+to a different realm.
+The TGS will also issue a referral when a host-based service
+exists in the requested realm as an alias of a service in another
+realm.
+.Pp
+Each binding in this section looks like:
+.Pp
+.Dl domain = realm
+.Pp
+The domain can be either a full name of a host or a trailing
+component, in the latter case the domain-string should start with a
+period.
+The trailing component only matches hosts that are in the same domain, ie
+.Dq .example.com
+matches
+.Dq foo.example.com ,
+but not
+.Dq foo.test.example.com .
+.Pp
+The realm may be the token `dns_locate', in which case the actual
+realm will be determined using DNS (independently of the setting
+of the `dns_lookup_realm' option).
+.It Li [realms]
+.Bl -tag -width "xxx" -offset indent
+.It Va REALM Li = {
+.Bl -tag -width "xxx" -offset indent
+.It Li kdc = Va [service/]host[:port]
+Specifies a list of kdcs for this realm.
+If the optional
+.Va port
+is absent, the
+default value for the
+.Dq kerberos/udp
+.Dq kerberos/tcp ,
+and
+.Dq http/tcp
+port (depending on service) will be used.
+The kdcs will be used in the order that they are specified.
+.Pp
+The optional
+.Va service
+specifies over what medium the kdc should be
+contacted.
+Possible services are
+.Dq udp ,
+.Dq tcp ,
+and
+.Dq http .
+Http can also be written as
+.Dq http:// .
+Default service is
+.Dq udp
+and
+.Dq tcp .
+.It Li admin_server = Va host[:port]
+Specifies the admin server for this realm, where all the modifications
+to the database are performed.
+.It Li kpasswd_server = Va host[:port]
+Points to the server where all the password changes are performed.
+If there is no such entry, the kpasswd port on the admin_server host
+will be tried.
+.It Li tgs_require_subkey
+a boolan variable that defaults to false.
+Old DCE secd (pre 1.1) might need this to be true.
+.It Li auth_to_local_names = {
+.Bl -tag -width "xxx" -offset indent
+.It Va principal_name = Va username
+The given
+.Va principal_name
+will be mapped to the given
+.Va username
+if the
+.Va REALM
+is a default realm.
+.El
+.It Li }
+.It Li auth_to_local = HEIMDAL_DEFAULT
+Use the Heimdal default principal to username mapping.
+Applies to principals from the
+.Va REALM
+if and only if
+.Va REALM
+is a default realm.
+.It Li auth_to_local = DEFAULT
+Use the MIT default principal to username mapping.
+Applies to principals from the
+.Va REALM
+if and only if
+.Va REALM
+is a default realm.
+.It Li auth_to_local = DB:/path/to/db.txt
+Use a binary search of the given DB. The DB must be a flat-text
+file sortedf in the "C" locale, with each record being a line
+(separated by either LF or CRLF) consisting of a principal name
+followed by whitespace followed by a username.
+Applies to principals from the
+.Va REALM
+if and only if
+.Va REALM
+is a default realm.
+.It Li auth_to_local = DB:/path/to/db
+Use the given DB, if there's a plugin for it.
+Applies to principals from the
+.Va REALM
+if and only if
+.Va REALM
+is a default realm.
+.It Li auth_to_local = RULE:...
+Use the given rule, if there's a plugin for it.
+Applies to principals from the
+.Va REALM
+if and only if
+.Va REALM
+is a default realm.
+.It Li auth_to_local = NONE
+No additional principal to username mapping is done. Note that
+.Va auth_to_local_names
+and any preceding
+.Va auth_to_local
+rules have precedence.
+.It Li pkinit_require_eku = BOOL
+If
+.Va true
+then the KDC PKINIT Extended Key Usage (EKU) OID (1.3.6.5.2.3.5)
+must be present in KDCs' PKINIT certificates.
+Defaults to
+.Va true .
+.It Li pkinit_require_krbtgt_otherName = BOOL
+If
+.Va true
+then the PKINIT Subject Alternative Name (SAN) for the TGS must
+be present in KDCs' PKINIT certificates, and must match their
+realm.
+Defaults to
+.Va true .
+.It Li pkinit_require_hostname_match = BOOL
+If
+.Va true
+then KDCs' PKINIT certificates must match their hostnames.
+Defaults to
+.Va false .
+.It Li pkinit_trustedCertifiers = BOOL
+If
+.Va true
+then PKINIT client will tell KDCs which trust anchors it trusts.
+Defaults to
+.Va true .
+.It Li disable_pac = BOOL
+If
+.Va true
+then the KDC will not sign tickets with PAC, which disables S4U2Proxy support.
+Defaults to
+.Va false .
+.El
+.It Li }
+.El
+.It Li [capaths]
+.Bl -tag -width "xxx" -offset indent
+.It Va client-realm Li = {
+.Bl -tag -width "xxx" -offset indent
+.It Va server-realm Li = Va hop-realm ...
+This serves two purposes. First the first listed
+.Va hop-realm
+tells a client which realm it should contact in order to ultimately
+obtain credentials for a service in the
+.Va server-realm .
+Secondly, it tells the KDC (and other servers) which realms are
+allowed in a multi-hop traversal from
+.Va client-realm
+to
+.Va server-realm .
+Except for the client case, the order of the realms are not important.
+.El
+.It Va }
+.El
+.It Li [logging]
+.Bl -tag -width "xxx" -offset indent
+.It Va entity Li = Va destination
+Specifies that
+.Va entity
+should use the specified
+.Li destination
+for logging.
+See the
+.Xr krb5_openlog 3
+manual page for a list of defined destinations.
+.El
+.It Li [kdc]
+.Bl -tag -width "xxx" -offset indent
+.It Li database Li = {
+.Bl -tag -width "xxx" -offset indent
+.It Li dbname Li = Va [DATBASETYPE:]DATABASENAME
+Use this database for this realm. The
+.Va DATABASETYPE
+should be one of 'lmdb', 'db3', 'db1', 'db', 'sqlite', or 'ldap'.
+See the info documetation how to configure different database backends.
+.It Li realm Li = Va REALM
+Specifies the realm that will be stored in this database.
+It realm isn't set, it will used as the default database, there can
+only be one entry that doesn't have a
+.Li realm
+stanza.
+.It Li mkey_file Li = Pa FILENAME
+Use this keytab file for the master key of this database.
+If not specified
+.Va DATABASENAME Ns .mkey
+will be used.
+.It Li acl_file Li = PA FILENAME
+Use this file for the ACL list of this database.
+.It Li log_file Li = Pa FILENAME
+Use this file as the log of changes performed to the database.
+This file is used by
+.Nm ipropd-master
+for propagating changes to slaves. It is also used by
+.Nm kadmind
+and
+.Nm kadmin
+(when used with the
+.Li -l
+option), and by all applications using
+.Nm libkadm5
+with the local backend, for two-phase commit functionality. Slaves also
+use this. Setting this to
+.Nm /dev/null
+disables two-phase commit and incremental propagation. Use
+.Nm iprop-log
+to show the contents of this log file.
+.It Li log-max-size = Pa number
+When the log reaches this size (in bytes), the log will be truncated,
+saving some entries, and keeping the latest version number so as to not
+disrupt incremental propagation. If set to a negative value then
+automatic log truncation will be disabled. Defaults to 52428800 (50MB).
+.El
+.It Li }
+.It Li max-request = Va SIZE
+Maximum size of a kdc request.
+.It Li require-preauth = Va BOOL
+If set pre-authentication is required.
+.It Li ports = Va "list of ports"
+List of ports the kdc should listen to.
+.It Li addresses = Va "list of interfaces"
+List of addresses the kdc should bind to.
+.It Li enable-http = Va BOOL
+Should the kdc answer kdc-requests over http.
+.It Li tgt-use-strongest-session-key = Va BOOL
+If this is TRUE then the KDC will prefer the strongest key from the
+client's AS-REQ or TGS-REQ enctype list for the ticket session key that
+is supported by the KDC and the target principal when the target
+principal is a krbtgt principal. Else it will prefer the first key from
+the client's AS-REQ enctype list that is also supported by the KDC and
+the target principal. Defaults to FALSE.
+.It Li svc-use-strongest-session-key = Va BOOL
+Like tgt-use-strongest-session-key, but applies to the session key
+enctype of tickets for services other than krbtgt principals. Defaults
+to FALSE.
+.It Li preauth-use-strongest-session-key = Va BOOL
+If TRUE then select the strongest possible enctype from the client's
+AS-REQ for PA-ETYPE-INFO2 (i.e., for password-based pre-authentication).
+Else pick the first supported enctype from the client's AS-REQ. Defaults
+to FALSE.
+.It Li use-strongest-server-key = Va BOOL
+If TRUE then the KDC picks, for the ticket encrypted part's key, the
+first supported enctype from the target service principal's hdb entry's
+current keyset. Else the KDC picks the first supported enctype from the
+target service principal's hdb entry's current keyset. Defaults to TRUE.
+.It Li check-ticket-addresses = Va BOOL
+Verify the addresses in the tickets used in tgs requests.
+.\" XXX
+.It Li warn_ticket_addresses = Va BOOL
+Warn about, but allow, usage of tickets from hosts that don't match the
+addresses in the tickets.
+.It Li allow-null-ticket-addresses = Va BOOL
+Allow address-less tickets.
+.\" XXX
+.It Li enable_fast = Va BOOL
+Enable RFC 6113 FAST support, this is enabled by default.
+.It Li enable_armored_pa_enc_timestamp = Va BOOL
+Enable armored encrypted timestamp pre-authentication with key
+strengthening.
+RFC 6113 says not to use PA-ENC-TIMESTAMP in FAST armored tunnels
+as there is a newer replacement, PA-ENC-CHALLENGE, but for
+interoperability with earlier versions of Heimdal, this is
+enabled by default for now.
+.It Li enable_unarmored_pa_enc_timestamp = Va BOOL
+Enable unarmored encrypted timestamp pre-authentication.
+Enabled by default for now, but in a future release will be
+disabled.
+.It Li enable-pkinit = Va BOOL
+Enable PKINIT (disabled by default).
+.It Li allow-anonymous = Va BOOL
+If the kdc is allowed to hand out anonymous tickets.
+.It Li synthetic_clients = Va BOOL
+If enabled then the KDC will issue tickets for clients that don't
+exist in the HDB provided that they use PKINIT, that PKINIT is
+enabled, and that the client's have certificates with PKINIT
+subject alternative names (SANs).
+.It Li synthetic_clients_max_life = Va TIME
+Maximum ticket lifetime for synthetic clients.
+Default: 5 minutes.
+.It Li synthetic_clients_max_renew = Va TIME
+Maximum ticket renewable lifetime for synthetic clients.
+Default: 5 minutes.
+.It Li pkinit_identity = Va HX509-STORE
+This is an HX509 store containing the KDC's PKINIT credential
+(private key and end-entity certificate).
+This is single valued, though multiple stores can be specified by
+separating them with commas.
+An
+.Va HX509-STORE
+is of the form
+.Va TYPE:name
+where
+.Va TYPE
+is one of
+.Va FILE, Va PEM-FILE, Va DER-FILE, Va PKCS12, Va PKCS11,
+or on OX X,
+.Va KEYCHAIN .
+The form of the
+.Va name
+depends on the
+.Va TYPE .
+For
+.Va FILE, Va PEM-FILE, Va DER-FILE,
+and
+.Va PKCS12
+the
+.Va name
+is a file path.
+See the Heimdal hx509 documentation for more information.
+.It Li pkinit_pool = Va HX509-STORE
+This is a multi-valued parameter naming one or more stores of
+intermediate certification authority (CA) certificates for the
+KDC's end entity certificate.
+.It Li pkinit_anchors = Va HX509-STORE
+This is a multi-valued parameter naming one or more stores of
+anchors for PKINIT client certificates.
+Note that the
+.Va DIR
+type of
+.Va HX509-STORE
+is also supported here.
+.Va DIR
+type stores are OpenSSL-style CA certificate hash directories.
+.It Li pkinit_kdc_ocsp = Va PATH
+This names a file whose contents is the DER encoding of an
+OCSPResponse for the KDC's end entity certificate.
+.It Li pkinit_kdc_friendly_name = Va NAME
+This is an optional friendly name of the KDC's end entity
+certificate.
+This is only helpful when the
+.Li pkinit_identity
+store contains many credentials.
+.It Li pkinit_principal_in_certificate = Va BOOL
+If set to
+.Va true
+then the KDC will match AS-REQ client principal names to the
+PKINIT
+.Va subjectAlternativeName
+values from the clients' certificates.
+Defaults to
+.Va true .
+.It Li pkinit_dh_min_bits = Va NUMBER
+Minimum acceptable modular Diffie-Hellman public key size in
+bits.
+.It Li pkinit_max_life_from_cert_extension = Va BOOL
+If set to
+.Va true
+then the KDC will override the
+.Va max_life
+attribute of the client principal's HDB record with a maximum
+ticket life taken from a certificate extension with OID
+.Va { iso(1) member-body(2) se(752) su(43) heim-pkix(16) 4 }
+and the DER encoding of an
+.Va INTEGER
+number of seconds.
+Alternatively, if the extended key usage OID
+.Va { iso(1) member-body(2) se(752) su(43) heim-pkix(16) 3 }
+is included in the client's certificate, then the
+.Va notAfter
+minus the current time will be used.
+.It Li pkinit_max_life_bound = Va TIME
+If set, this will be a hard bound on the maximum ticket lifetime
+taken from the client's certificate.
+As usual,
+.Va TIME
+can be given as a number followed by a unit, such as
+.Dq 2d
+for
+.Dq two days .
+.It Li pkinit_max_life_from_cert = Va TIME
+If set, this will override the
+.Va max_life
+attribute of the client principal's HDB record with the
+.Va notAfter
+of the client's certificate minus the current time, bounded to
+the given relative
+.Va TIME
+unless the
+.Li pkinit_max_life_from_cert_extension
+parameter is set and the client's certificate has that extension.
+As usual,
+.Va TIME
+can be given as a number followed by a unit, such as
+.Dq 2d
+for
+.Dq two days .
+.It Li enable_gss_preauth = Va boolean
+Enables pre-authentication using a GSS-API mechanism supported by the client and KDC.
+The GSS-API initiator and AS request client names must match, unless the
+.Li WELLKNOWN/FEDERATED
+name was used in the AS request, in which case the AS reply will contain the
+GSS-API initiator name. Authorization and mapping behavior may be customized
+by plugins. If synthetic clients are enabled, then the GSS-API initiator need
+not exist in the local database. GSS-API pre-authentication is disabled by
+default.
+.It Li enable_gss_auth_data = Va boolean
+When using GSS-API pre-authentication, includes a Kerberos authorization data
+element containing naming attributes associated with the GSS-API initiator. This
+is disabled by default as it may significantly increase the size of returned
+tickets.
+.It Li gss_mechanisms_allowed = Va mechs ...
+A list of GSS-API mechanisms that may be used for GSS-API pre-authentication.
+.It Li gss_cross_realm_mechanisms_allowed = Va mechs ...
+A list of GSS-API mechanisms that, when using the default authorization
+mechanism, will be permitted to map Kerberos principals in foreign realms. The
+list is empty by default. Initiator names from mechanisms not on this list will
+be mapped to an enterprise principal in the AS-REQ realm. This option is
+intended to avoid conflating GSS-API pre-authentication and Kerberos
+cross-realm authentication. The behavior is provided by the default
+authorization mechanism and will be overridden by an authorization plugin.
+Mechanisms may be identified by dot-separated OID or a short name.
+.It Li historical_anon_realm = Va boolean
+Enables pre-7.0 non-RFC-comformant KDC behavior.
+With this option set to
+.Li true
+the client realm in anonymous pkinit AS replies will be the requested realm,
+rather than the RFC-conformant
+.Li WELLKNOWN:ANONYMOUS
+realm.
+This can have a security impact on servers that expect to grant access to
+anonymous-but-authenticated to the KDC users of the realm in question:
+they would also grant access to unauthenticated anonymous users.
+As such, it is not recommend to set this option to
+.Li true.
+.It Li encode_as_rep_as_tgs_rep = Va BOOL
+Encode as-rep as tgs-rep to be compatible with mistakes older DCE secd did.
+.\" XXX
+.It Li kdc_warn_pwexpire = Va TIME
+The time before expiration that the user should be warned that her
+password is about to expire.
+.It Li logging = Va Logging
+What type of logging the kdc should use, see also [logging]/kdc.
+.It Li hdb-ldap-structural-object Va structural object
+If the LDAP backend is used for storing principals, this is the
+structural object that will be used when creating and when reading
+objects.
+The default value is account .
+.It Li hdb-ldap-create-base Va creation dn
+is the dn that will be appended to the principal when creating entries.
+Default value is the search dn.
+.It Li enable-digest = Va BOOL
+Should the kdc answer digest requests. The default is FALSE.
+.It Li digests_allowed = Va list of digests
+Specifies the digests the kdc will reply to. The default is
+.Li ntlm-v2 .
+.It Li enable-kx509 = Va boolean
+Enables kx509 service.
+.Pp
+The kx509 service is configurable for a number of cases:
+.Bl -tag -width "" -offset indent
+.It Li default certificates for user or service principals,
+.It Li non-default certificate requests including subject alternative names (SAN) and extended key usage (EKU) certificate extensions, for either client, server, or mixed usage.
+.El
+.Pp
+Distinct configurations are supported for all of these cases as
+shown below:
+.Bd -literal -offset indent
+[kdc]
+ enable-kx509 = yes | no
+ require_csr = yes | no
+ require_initial_kca_tickets = yes | no
+ realm = {
+ <REALM> = {
+ kx509 = {
+ <label> = {
+ <param> = <value>
+ }
+ hostbased_service = {
+ <service> = {
+ <param> = <value>
+ }
+ }
+ }
+ }
+ }
+.Ed
+where
+.Va label
+is one of:
+.Bl -tag -width "xxx" -offset indent
+.It Li user
+for default certificates for user principals,
+.It Li root_user
+for default certificates for root user principals,
+.It Li admin_user
+for default certificates for admin user principals,
+.It Li hostbased_service
+for default certificates for host-based service principals, in which case the
+service name is used as shown above,
+.It Li client
+for non-default client certificates,
+.It Li server
+for non-default server certificates,
+.It Li mixed
+for non-default client and server certificates.
+.El
+and where the parameters are as follows:
+.Bl -tag -width "xxx" -offset indent
+.It Li ca = Va file
+Specifies the PEM credentials for the kx509 / bx509d certification
+authority.
+If not specified for any specific use-case, then that use-case
+will be disabled.
+.It Li max_cert_lifetime = Va NUMunit
+Specifies the maximum certificate lifetime as a decimal number
+and an optional unit (the default unit is
+.Dq day
+).
+.It Li force_cert_lifetime = Va NUMunit
+Specifies a minimum certificate lifetime as a decimal number and
+an optional unit (the default unit is
+.Dq day
+).
+.It Li allow_extra_lifetime = Va boolean
+Indicates whether a client may request longer lifetimes than
+their authentication credentials.
+Defaults to false.
+.It Li require_initial_kca_tickets = Va boolean
+Specified whether to require that tickets for the
+.Li kca_service
+service principal be INITIAL.
+This may be set on a per-realm basis as well as globally.
+Defaults to true for the global setting.
+.It Li include_pkinit_san = Va boolean
+If true then the kx509 client principal's name and realm will be
+included in an
+.Li id-pkinit-san
+subject alternative name certificate extension.
+This can be set on a per-realm basis as well as globally.
+Defaults to true for the global setting.
+.It Li email_domain = Va domain
+If set then the kx509 client user principal's name at the given
+domain will be included in an
+.Li rfc822Name
+subject alternative name certificate extension.
+This can be set on a per-realm basis as well as globally.
+Defaults to false for the global setting.
+.It Li include_dnsname_san = Va boolean
+If true then a kx509 host-based or domain-based client
+principal's hostname will be included in an
+.Li dNSName
+subject alternative name certificate extension, with the
+downcased realm as the domainname. This can be set on a
+per-realm basis as well as
+globally. Defaults to false for the global setting.
+.It Li ekus = Va OID
+List of OIDs to include as EKUs.
+.It Li subject_name = Va DN
+Specifies a subject name that should either be empty or contain
+variable interpolation as described below for
+.Va template_cert .
+The subject may be the empty string, causing the issued
+certificates' subject names to be empty.
+.It Li template_cert = Va store
+Specifies the hx509 store (e.g.,
+.Va PEM-FILE:path )
+with a template
+for the certificates to be issued to kx509 clients whose
+principal names have one component (i.e., are user principals).
+A template is a certificate with variables to be interpolated in
+the subjectName. The following variables can be interpolated in
+the subject name using
+.Va ${variable}
+syntax:
+.Bl -tag -width "xxx" -offset indent
+.It principal-name
+The full name of the kx509 client principal.
+.It principal-name-without-realm
+The full name of the kx509 client principal, excluding the realm name.
+.It principal-name-realm
+The name of the client principal's realm.
+.It principal-component0
+The first component of the client principal.
+.It principal-component1
+The second component of the client principal.
+.It principal-component2
+The third component of the client principal.
+.It principal-service-name
+The name of the service.
+.It principal-host-name
+The name of the host.
+.El
+.Pp
+If a template and subject name are not specified and no default
+SANs are configured, then no certificate will be issued.
+Otherwise if a template and subject name are not specified, then
+subject of the certificate will be empty.
+.El
+.El
+.Pp
+.It Li [hdb]
+.Bl -tag -width "xxx" -offset indent
+.It Li db-dir = Va path
+This parameter defines a directory that can contain:
+.Bl -tag -width "xxx" -offset indent
+.It Va kdc.conf
+A configuration file with the same format as krb5.conf that will
+be included.
+.It Va m-key
+The master key file.
+.It Va kdc.log
+The default logfile for the KDC when a logfile is not specified in
+.Li [logging]
+.It Va kadm5.acl
+The access controls for
+.Nm kadmind .
+.It Va log
+The (binary) log of transactions used for
+.Nm HDB
+replication via the
+.Nm iprop
+protocol.
+See
+.Nm iprop-log(1)
+for more detail.
+.It Va pki-mapping
+The default PKINIT mapping file if one is not specified in
+.Va [kdc] pkinit_mappings_file .
+.El
+and other files related to
+.Nm iprop
+operation.
+.It Li new_service_key_delay = Va time
+Sets a bias such that new keys are not taken into service until
+after the given time has passed since they were set.
+This is useful for key rotation on concrete principals shared by
+multiple instances of an application: set this time to twice or
+more the keytab fetch period used by applications.
+.It Li enable_virtual_hostbased_princs = Va boolean
+Heimdal supports a notion of virtual host-based service
+principals whose keys are derived from those of a base namespace
+principal of the form
+.Nm WELLKNOWN/HOSTBASED-NAMESPACE/svc/hostname .
+The service name can be wild-carded as
+.Va _ .
+Non-wildcarded services have to be listed in the
+.Li virtual_hostbased_princ_svcs
+parameter (see below).
+This parameter enables this feature, which is disabled by
+default.
+.It Li virtual_hostbased_princ_ndots = Va Integer
+Minimum number of label-separating periods in virtual host-based
+service principals' hostname component.
+.It Li virtual_hostbased_princ_maxdots = Va Integer
+Maximum number of label-separating periods in namespaces'
+hostname component.
+.It Li virtual_hostbased_princ_svcs = Va service-name
+This multi-valued parameter lists service names not to wildcard
+when searching for a namespace for a virtual host-based service
+principal.
+Other service names will have keys derived from a matching
+namespace with a wild-carded service name.
+This allows one to have different attributes for different
+services.
+For example, the
+.Nm "host"
+service can be configured to have the ok-as-delegate flag while
+all others do not.
+.El
+.Pp
+.It Li [bx509]
+This section contains online certification authority configuration, much
+like
+.Li kx509
+in the
+.Li [kdc]
+section, but with the
+.Li kx509
+layer removed.
+.Bd -literal -offset indent
+[kdc]
+ realm = {
+ <REALM> = {
+ ...
+ }
+ }
+.Ed
+.It Li [get-tgt]
+.Bl -tag -width "xxx" -offset indent
+.It Li no_addresses = Va BOOL
+If set to
+.Va true
+then the
+.Va /get-tgt
+end-point of the
+.Xr bx509d 8
+service will issue address-less TGTs.
+If set to
+.Va false
+then the
+.Va /get-tgt
+end-point of the
+.Xr bx509d 8
+service will include the client's IP address in the TGT it issues
+it.
+Defaults to
+.Va true .
+.It Li allow_addresses = Va BOOL
+If set to
+.Va true
+then the
+.Va /get-tgt
+end-point of the
+.Xr bx509d 8
+service will add arbitrary addresses requested by clients to the
+TGTs it issues them.
+Defaults to
+.Va false .
+.El
+.Pp
+Certification authority related parameters are as for
+.Va bx509 .
+.It Li [kadmin]
+.Bl -tag -width "xxx" -offset indent
+.It Li password_lifetime = Va time
+If a principal already have its password set for expiration, this is
+the time it will be valid for after a change.
+.It Li default_keys = Va keytypes...
+For each entry in
+.Va default_keys
+try to parse it as a sequence of
+.Va etype:salttype:salt
+syntax of this if something like:
+.Pp
+[(des|des3|etype):](pw-salt|afs3-salt)[:string]
+.Pp
+If
+.Ar etype
+is omitted it means everything, and if string is omitted it means the
+default salt string (for that principal and encryption type).
+Additional special values of keytypes are:
+.Bl -tag -width "xxx" -offset indent
+.It Li v5
+The Kerberos 5 salt
+.Va pw-salt
+.El
+.It Li default_key_rules = Va {
+.Bl -tag -width "xxx" -offset indent
+.It Va globing-rule Li = Va keytypes...
+a globbing rule to matching a principal, and when true, use the
+keytypes as specified the same format as [kadmin]default_keys .
+.El
+.It Li }
+.It Li prune-key-history = Va BOOL
+When adding keys to the key history, drop keys that are too old to match
+unexpired tickets (based on the principal's maximum ticket lifetime).
+If the KDC keystore is later compromised traffic protected with the
+discarded older keys may remain protected. This also keeps the HDB
+records for principals with key history from growing without bound.
+The default (backwards compatible) value is "false".
+.It Li use_v4_salt = Va BOOL
+When true, this is the same as
+.Pp
+.Va default_keys = Va des3:pw-salt Va v4
+.Pp
+and is only left for backwards compatibility.
+.It Li [password_quality]
+Check the Password quality assurance in the info documentation for
+more information.
+.Bl -tag -width "xxx" -offset indent
+.It Li check_library = Va library-name
+Library name that contains the password check_function
+.It Li check_function = Va function-name
+Function name for checking passwords in check_library
+.It Li policy_libraries = Va library1 ... libraryN
+List of libraries that can do password policy checks
+.It Li policies = Va policy1 ... policyN
+List of policy names to apply to the password. Builtin policies are
+among other minimum-length, character-class, external-check.
+.El
+.El
+.El
+.Sh TOKEN EXPANSION
+The values of some parameters are subject to percent token expansion.
+Expansions supported on all platforms:
+.Bl -tag -width "xxx" -offset indent
+.It %{LIBDIR}
+The install location of Heimdal libraries.
+.It %{BINDIR}
+The install location of Heimdal user programs.
+.It %{LIBEXEC}
+The install location of Heimdal services.
+.It %{SBINDIR}
+The install location of Heimdal admin programs.
+.It %{username}
+The current username.
+.It %{TEMP}
+A temporary directory.
+.It %{USERID}
+The current user's SID (Windows) or effective user ID (POSIX).
+.It %{uid}
+The current user's SID (Windows) or real user ID (POSIX). On POSIX it is best
+to use the
+.Va %{euid}
+token instead (see below).
+.It %{null}
+The empty string.
+.El
+.Pp
+Expansions supported on POSIX-like platforms:
+.Bl -tag -width "xxx" -offset indent
+.It %{euid}
+The current effective user ID.
+.It %{loginname}
+The username of the logged-in user for this terminal.
+.It %{LOCALSTATEDIR}
+The install location of Heimdal databases.
+.El
+.Pp
+On Windows, several additional tokens can also be expanded:
+.Bl -tag -width "xxx" -offset indent
+.It %{APPDATA}
+Roaming application data (for current user).
+.It %{COMMON_APPDATA}
+Application data (all users).
+.It %{LOCAL_APPDATA}
+Local application data (for current user).
+.It %{SYSTEM}
+Windows System folder.
+.It %{WINDOWS}
+Windows folder.
+.It %{USERCONFIG}
+Per user Heimdal configuration file path.
+.It %{COMMONCONFIG}
+Common Heimdal configuration file path.
+.El
+.Sh ENVIRONMENT
+.Ev KRB5_CONFIG
+points to the configuration file to read.
+.Sh FILES
+.Bl -tag -width "/etc/krb5.conf"
+.It Pa /etc/krb5.conf
+configuration file for Kerberos 5.
+.El
+.Sh EXAMPLES
+.Bd -literal -offset indent
+[libdefaults]
+ default_realm = FOO.SE
+ name_canon_rules = as-is:realm=FOO.SE
+ name_canon_rules = qualify:domain=foo.se:realm=FOO.SE
+ name_canon_rules = qualify:domain=bar.se:realm=FOO.SE
+ name_canon_rules = nss
+[domain_realm]
+ .foo.se = FOO.SE
+ .bar.se = FOO.SE
+[realms]
+ FOO.SE = {
+ kdc = kerberos.foo.se
+ default_domain = foo.se
+ }
+[logging]
+ kdc = FILE:/var/heimdal/kdc.log
+ kdc = SYSLOG:INFO
+ default = SYSLOG:INFO:USER
+[kadmin]
+ default_key_rules = {
+ */ppp@* = arcfour-hmac-md5:pw-salt
+ }
+.Ed
+.Sh DIAGNOSTICS
+Since
+.Nm
+is read and parsed by the krb5 library, there is not a lot of
+opportunities for programs to report parsing errors in any useful
+format.
+To help overcome this problem, there is a program
+.Nm verify_krb5_conf
+that reads
+.Nm
+and tries to emit useful diagnostics from parsing errors.
+Note that this program does not have any way of knowing what options
+are actually used and thus cannot warn about unknown or misspelled
+ones.
+.Sh SEE ALSO
+.Xr kinit 1 ,
+.Xr krb5_openlog 3 ,
+.Xr strftime 3 ,
+.Xr verify_krb5_conf 8
diff --git a/third_party/heimdal/lib/krb5/krb5.h b/third_party/heimdal/lib/krb5/krb5.h
new file mode 100644
index 0000000..e4a9e7e
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5.h
@@ -0,0 +1,1069 @@
+/*
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __KRB5_H__
+#define __KRB5_H__
+
+#include <time.h>
+#include <krb5-types.h>
+
+#include <asn1_err.h>
+#include <krb5_err.h>
+#include <heim_err.h>
+#include <k524_err.h>
+#include <k5e1_err.h>
+
+#include <krb5_asn1.h>
+typedef Krb5Int32 krb5int32;
+typedef Krb5UInt32 krb5uint32;
+
+/* name confusion with MIT */
+#ifndef KRB5KDC_ERR_KEY_EXP
+#define KRB5KDC_ERR_KEY_EXP KRB5KDC_ERR_KEY_EXPIRED
+#endif
+
+#ifdef _WIN32
+#define KRB5_CALLCONV __stdcall
+#define KRB5_LIB_CALL __stdcall
+#else
+#define KRB5_CALLCONV
+#define KRB5_LIB_CALL
+#endif
+
+/* simple constants */
+
+#ifndef TRUE
+#define TRUE 1
+#define FALSE 0
+#endif
+
+typedef int krb5_boolean;
+
+typedef int32_t krb5_error_code;
+
+typedef int32_t krb5_kvno;
+
+typedef uint32_t krb5_flags;
+
+typedef void *krb5_pointer;
+typedef const void *krb5_const_pointer;
+
+struct krb5_crypto_data;
+typedef struct krb5_crypto_data *krb5_crypto;
+
+struct krb5_get_creds_opt_data;
+typedef struct krb5_get_creds_opt_data *krb5_get_creds_opt;
+
+struct krb5_digest_data;
+typedef struct krb5_digest_data *krb5_digest;
+struct krb5_ntlm_data;
+typedef struct krb5_ntlm_data *krb5_ntlm;
+
+struct krb5_pac_data;
+typedef struct krb5_pac_data *krb5_pac;
+typedef const struct krb5_pac_data *krb5_const_pac;
+
+typedef struct krb5_rd_req_in_ctx_data *krb5_rd_req_in_ctx;
+typedef struct krb5_rd_req_out_ctx_data *krb5_rd_req_out_ctx;
+
+typedef CKSUMTYPE krb5_cksumtype;
+
+typedef Checksum krb5_checksum;
+
+typedef ENCTYPE krb5_enctype;
+
+typedef struct krb5_get_init_creds_ctx *krb5_init_creds_context;
+
+typedef heim_octet_string krb5_data;
+
+/* PKINIT related forward declarations */
+struct ContentInfo;
+struct krb5_pk_identity;
+struct krb5_pk_cert;
+
+/* krb5_enc_data is a mit compat structure */
+typedef struct krb5_enc_data {
+ krb5_enctype enctype;
+ krb5_kvno kvno;
+ krb5_data ciphertext;
+} krb5_enc_data;
+
+/* alternative names */
+#define ENCTYPE_NULL KRB5_ENCTYPE_NULL
+#define ENCTYPE_DES_CBC_CRC KRB5_ENCTYPE_DES_CBC_CRC
+#define ENCTYPE_DES_CBC_MD4 KRB5_ENCTYPE_DES_CBC_MD4
+#define ENCTYPE_DES_CBC_MD5 KRB5_ENCTYPE_DES_CBC_MD5
+#define ENCTYPE_DES3_CBC_MD5 KRB5_ENCTYPE_DES3_CBC_MD5
+#define ENCTYPE_OLD_DES3_CBC_SHA1 KRB5_ENCTYPE_OLD_DES3_CBC_SHA1
+#define ENCTYPE_SIGN_DSA_GENERATE KRB5_ENCTYPE_SIGN_DSA_GENERATE
+#define ENCTYPE_ENCRYPT_RSA_PRIV KRB5_ENCTYPE_ENCRYPT_RSA_PRIV
+#define ENCTYPE_ENCRYPT_RSA_PUB KRB5_ENCTYPE_ENCRYPT_RSA_PUB
+#define ENCTYPE_DES3_CBC_SHA1 KRB5_ENCTYPE_DES3_CBC_SHA1
+#define ENCTYPE_AES128_CTS_HMAC_SHA1_96 KRB5_ENCTYPE_AES128_CTS_HMAC_SHA1_96
+#define ENCTYPE_AES256_CTS_HMAC_SHA1_96 KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96
+#define ENCTYPE_ARCFOUR_HMAC KRB5_ENCTYPE_ARCFOUR_HMAC_MD5
+#define ENCTYPE_ARCFOUR_HMAC_MD5 KRB5_ENCTYPE_ARCFOUR_HMAC_MD5
+#define ENCTYPE_ARCFOUR_HMAC_MD5_56 KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56
+#define ENCTYPE_ENCTYPE_PK_CROSS KRB5_ENCTYPE_ENCTYPE_PK_CROSS
+#define ENCTYPE_DES_CBC_NONE KRB5_ENCTYPE_DES_CBC_NONE
+#define ENCTYPE_DES3_CBC_NONE KRB5_ENCTYPE_DES3_CBC_NONE
+#define ENCTYPE_DES_CFB64_NONE KRB5_ENCTYPE_DES_CFB64_NONE
+#define ENCTYPE_DES_PCBC_NONE KRB5_ENCTYPE_DES_PCBC_NONE
+#define ETYPE_NULL KRB5_ENCTYPE_NULL
+#define ETYPE_DES_CBC_CRC KRB5_ENCTYPE_DES_CBC_CRC
+#define ETYPE_DES_CBC_MD4 KRB5_ENCTYPE_DES_CBC_MD4
+#define ETYPE_DES_CBC_MD5 KRB5_ENCTYPE_DES_CBC_MD5
+#define ETYPE_DES3_CBC_MD5 KRB5_ENCTYPE_DES3_CBC_MD5
+#define ETYPE_OLD_DES3_CBC_SHA1 KRB5_ENCTYPE_OLD_DES3_CBC_SHA1
+#define ETYPE_SIGN_DSA_GENERATE KRB5_ENCTYPE_SIGN_DSA_GENERATE
+#define ETYPE_ENCRYPT_RSA_PRIV KRB5_ENCTYPE_ENCRYPT_RSA_PRIV
+#define ETYPE_ENCRYPT_RSA_PUB KRB5_ENCTYPE_ENCRYPT_RSA_PUB
+#define ETYPE_DES3_CBC_SHA1 KRB5_ENCTYPE_DES3_CBC_SHA1
+#define ETYPE_AES128_CTS_HMAC_SHA1_96 KRB5_ENCTYPE_AES128_CTS_HMAC_SHA1_96
+#define ETYPE_AES256_CTS_HMAC_SHA1_96 KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96
+#define ETYPE_AES128_CTS_HMAC_SHA256_128 KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128
+#define ETYPE_AES256_CTS_HMAC_SHA384_192 KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192
+#define ETYPE_ARCFOUR_HMAC_MD5 KRB5_ENCTYPE_ARCFOUR_HMAC_MD5
+#define ETYPE_ARCFOUR_HMAC_MD5_56 KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56
+#define ETYPE_ENCTYPE_PK_CROSS KRB5_ENCTYPE_ENCTYPE_PK_CROSS
+#define ETYPE_ARCFOUR_MD4 KRB5_ENCTYPE_ARCFOUR_MD4
+#define ETYPE_ARCFOUR_HMAC_OLD KRB5_ENCTYPE_ARCFOUR_HMAC_OLD
+#define ETYPE_ARCFOUR_HMAC_OLD_EXP KRB5_ENCTYPE_ARCFOUR_HMAC_OLD_EXP
+#define ETYPE_DES_CBC_NONE KRB5_ENCTYPE_DES_CBC_NONE
+#define ETYPE_DES3_CBC_NONE KRB5_ENCTYPE_DES3_CBC_NONE
+#define ETYPE_DES_CFB64_NONE KRB5_ENCTYPE_DES_CFB64_NONE
+#define ETYPE_DES_PCBC_NONE KRB5_ENCTYPE_DES_PCBC_NONE
+#define ETYPE_DIGEST_MD5_NONE KRB5_ENCTYPE_DIGEST_MD5_NONE
+#define ETYPE_CRAM_MD5_NONE KRB5_ENCTYPE_CRAM_MD5_NONE
+#define DOMAIN_X500_COMPRESS domain_X500_Compress
+
+/* PDU types */
+typedef enum krb5_pdu {
+ KRB5_PDU_ERROR = 0,
+ KRB5_PDU_TICKET = 1,
+ KRB5_PDU_AS_REQUEST = 2,
+ KRB5_PDU_AS_REPLY = 3,
+ KRB5_PDU_TGS_REQUEST = 4,
+ KRB5_PDU_TGS_REPLY = 5,
+ KRB5_PDU_AP_REQUEST = 6,
+ KRB5_PDU_AP_REPLY = 7,
+ KRB5_PDU_KRB_SAFE = 8,
+ KRB5_PDU_KRB_PRIV = 9,
+ KRB5_PDU_KRB_CRED = 10,
+ KRB5_PDU_NONE = 11 /* See krb5_get_permitted_enctypes() */
+} krb5_pdu;
+
+typedef PADATA_TYPE krb5_preauthtype;
+
+typedef enum krb5_key_usage {
+ KRB5_KU_PA_ENC_TIMESTAMP = 1,
+ /* AS-REQ PA-ENC-TIMESTAMP padata timestamp, encrypted with the
+ client key (section 5.4.1) */
+ KRB5_KU_TICKET = 2,
+ /* AS-REP Ticket and TGS-REP Ticket (includes tgs session key or
+ application session key), encrypted with the service key
+ (section 5.4.2) */
+ KRB5_KU_AS_REP_ENC_PART = 3,
+ /* AS-REP encrypted part (includes tgs session key or application
+ session key), encrypted with the client key (section 5.4.2) */
+ KRB5_KU_TGS_REQ_AUTH_DAT_SESSION = 4,
+ /* TGS-REQ KDC-REQ-BODY AuthorizationData, encrypted with the tgs
+ session key (section 5.4.1) */
+ KRB5_KU_TGS_REQ_AUTH_DAT_SUBKEY = 5,
+ /* TGS-REQ KDC-REQ-BODY AuthorizationData, encrypted with the tgs
+ authenticator subkey (section 5.4.1) */
+ KRB5_KU_TGS_REQ_AUTH_CKSUM = 6,
+ /* TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator cksum, keyed
+ with the tgs session key (sections 5.3.2, 5.4.1) */
+ KRB5_KU_TGS_REQ_AUTH = 7,
+ /* TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator (includes tgs
+ authenticator subkey), encrypted with the tgs session key
+ (section 5.3.2) */
+ KRB5_KU_TGS_REP_ENC_PART_SESSION = 8,
+ /* TGS-REP encrypted part (includes application session key),
+ encrypted with the tgs session key (section 5.4.2) */
+ KRB5_KU_TGS_REP_ENC_PART_SUB_KEY = 9,
+ /* TGS-REP encrypted part (includes application session key),
+ encrypted with the tgs authenticator subkey (section 5.4.2) */
+ KRB5_KU_AP_REQ_AUTH_CKSUM = 10,
+ /* AP-REQ Authenticator cksum, keyed with the application session
+ key (section 5.3.2) */
+ KRB5_KU_AP_REQ_AUTH = 11,
+ /* AP-REQ Authenticator (includes application authenticator
+ subkey), encrypted with the application session key (section
+ 5.3.2) */
+ KRB5_KU_AP_REQ_ENC_PART = 12,
+ /* AP-REP encrypted part (includes application session subkey),
+ encrypted with the application session key (section 5.5.2) */
+ KRB5_KU_KRB_PRIV = 13,
+ /* KRB-PRIV encrypted part, encrypted with a key chosen by the
+ application (section 5.7.1) */
+ KRB5_KU_KRB_CRED = 14,
+ /* KRB-CRED encrypted part, encrypted with a key chosen by the
+ application (section 5.8.1) */
+ KRB5_KU_KRB_SAFE_CKSUM = 15,
+ /* KRB-SAFE cksum, keyed with a key chosen by the application
+ (section 5.6.1) */
+ KRB5_KU_OTHER_ENCRYPTED = 16,
+ /* Data which is defined in some specification outside of
+ Kerberos to be encrypted using an RFC1510 encryption type. */
+ KRB5_KU_OTHER_CKSUM = 17,
+ /* Data which is defined in some specification outside of
+ Kerberos to be checksummed using an RFC1510 checksum type. */
+ KRB5_KU_KRB_ERROR = 18,
+ /* Krb-error checksum */
+ KRB5_KU_AD_KDC_ISSUED = 19,
+ /* AD-KDCIssued checksum */
+ KRB5_KU_MANDATORY_TICKET_EXTENSION = 20,
+ /* Checksum for Mandatory Ticket Extensions */
+ KRB5_KU_AUTH_DATA_TICKET_EXTENSION = 21,
+ /* Checksum in Authorization Data in Ticket Extensions */
+ KRB5_KU_USAGE_SEAL = 22,
+ /* seal in GSSAPI krb5 mechanism */
+ KRB5_KU_USAGE_SIGN = 23,
+ /* sign in GSSAPI krb5 mechanism */
+ KRB5_KU_USAGE_SEQ = 24,
+ /* SEQ in GSSAPI krb5 mechanism */
+ KRB5_KU_USAGE_ACCEPTOR_SEAL = 22,
+ /* acceptor sign in GSSAPI CFX krb5 mechanism */
+ KRB5_KU_USAGE_ACCEPTOR_SIGN = 23,
+ /* acceptor seal in GSSAPI CFX krb5 mechanism */
+ KRB5_KU_USAGE_INITIATOR_SEAL = 24,
+ /* initiator sign in GSSAPI CFX krb5 mechanism */
+ KRB5_KU_USAGE_INITIATOR_SIGN = 25,
+ /* initiator seal in GSSAPI CFX krb5 mechanism */
+ KRB5_KU_PA_SERVER_REFERRAL_DATA = 22,
+ /* encrypted server referral data */
+ KRB5_KU_SAM_CHECKSUM = 25,
+ /* Checksum for the SAM-CHECKSUM field */
+ KRB5_KU_SAM_ENC_TRACK_ID = 26,
+ /* Encryption of the SAM-TRACK-ID field */
+ KRB5_KU_PA_SERVER_REFERRAL = 26,
+ /* Keyusage for the server referral in a TGS req */
+ KRB5_KU_SAM_ENC_NONCE_SAD = 27,
+ /* Defined in [MS-SFU] */
+ KRB5_KU_PA_S4U_X509_USER_REQUEST = 26,
+ /* Defined in [MS-SFU] */
+ KRB5_KU_PA_S4U_X509_USER_REPLY = 27,
+ /* Encryption of the SAM-NONCE-OR-SAD field */
+ KRB5_KU_PA_PKINIT_KX = 44,
+ /* Encryption type of the kdc session contribution in pk-init */
+ KRB5_KU_AS_REQ = 56,
+ /* Checksum of over the AS-REQ send by the KDC in PA-REQ-ENC-PA-REP */
+ KRB5_KU_FAST_REQ_CHKSUM = 50,
+ /* FAST armor checksum */
+ KRB5_KU_FAST_ENC = 51,
+ /* FAST armor encryption */
+ KRB5_KU_FAST_REP = 52,
+ /* FAST armor reply */
+ KRB5_KU_FAST_FINISHED = 53,
+ /* FAST finished checksum */
+ KRB5_KU_ENC_CHALLENGE_CLIENT = 54,
+ /* fast challenge from client */
+ KRB5_KU_ENC_CHALLENGE_KDC = 55,
+ /* fast challenge from kdc */
+ KRB5_KU_DIGEST_ENCRYPT = -18,
+ /* Encryption key usage used in the digest encryption field */
+ KRB5_KU_DIGEST_OPAQUE = -19,
+ /* Checksum key usage used in the digest opaque field */
+ KRB5_KU_KRB5SIGNEDPATH = -21,
+ /* Checksum key usage on KRB5SignedPath */
+ KRB5_KU_CANONICALIZED_NAMES = -23,
+ /* Checksum key usage on PA-CANONICALIZED */
+ KRB5_KU_H5L_COOKIE = -25
+ /* encrypted foo */
+} krb5_key_usage;
+
+typedef krb5_key_usage krb5_keyusage;
+
+typedef enum krb5_salttype {
+ KRB5_PW_SALT = KRB5_PADATA_PW_SALT,
+ KRB5_AFS3_SALT = KRB5_PADATA_AFS3_SALT
+}krb5_salttype;
+
+typedef struct krb5_salt {
+ krb5_salttype salttype;
+ krb5_data saltvalue;
+} krb5_salt;
+
+typedef ETYPE_INFO krb5_preauthinfo;
+
+typedef struct {
+ krb5_preauthtype type;
+ krb5_preauthinfo info; /* list of preauthinfo for this type */
+} krb5_preauthdata_entry;
+
+typedef struct krb5_preauthdata {
+ unsigned len;
+ krb5_preauthdata_entry *val;
+}krb5_preauthdata;
+
+typedef enum krb5_address_type {
+ KRB5_ADDRESS_INET = 2,
+ KRB5_ADDRESS_NETBIOS = 20,
+ KRB5_ADDRESS_INET6 = 24,
+ KRB5_ADDRESS_ADDRPORT = 256,
+ KRB5_ADDRESS_IPPORT = 257
+} krb5_address_type;
+
+enum {
+ AP_OPTS_USE_SESSION_KEY = 1,
+ AP_OPTS_MUTUAL_REQUIRED = 2,
+ AP_OPTS_USE_SUBKEY = 4 /* library internal */
+};
+
+typedef HostAddress krb5_address;
+
+typedef HostAddresses krb5_addresses;
+
+typedef krb5_enctype krb5_keytype;
+
+enum krb5_keytype_old {
+ KEYTYPE_NULL = ETYPE_NULL,
+ KEYTYPE_DES = ETYPE_DES_CBC_CRC,
+ KEYTYPE_DES3 = ETYPE_OLD_DES3_CBC_SHA1,
+ KEYTYPE_AES128 = ETYPE_AES128_CTS_HMAC_SHA1_96,
+ KEYTYPE_AES256 = ETYPE_AES256_CTS_HMAC_SHA1_96,
+ KEYTYPE_ARCFOUR = ETYPE_ARCFOUR_HMAC_MD5,
+ KEYTYPE_ARCFOUR_56 = ETYPE_ARCFOUR_HMAC_MD5_56
+};
+
+typedef EncryptionKey krb5_keyblock;
+
+typedef AP_REQ krb5_ap_req;
+
+struct krb5_cc_ops;
+
+#define KRB5_DEFAULT_CCFILE_ROOT "%{TEMP}/krb5cc_"
+
+#define KRB5_DEFAULT_CCROOT "FILE:" KRB5_DEFAULT_CCFILE_ROOT
+
+#define KRB5_ACCEPT_NULL_ADDRESSES(C) \
+ krb5_config_get_bool_default((C), NULL, TRUE, \
+ "libdefaults", "accept_null_addresses", \
+ NULL)
+
+typedef void *krb5_cc_cursor;
+typedef struct krb5_cccol_cursor_data *krb5_cccol_cursor;
+
+typedef struct krb5_ccache_data {
+ const struct krb5_cc_ops *ops;
+ krb5_data data;
+ unsigned int cc_initialized:1; /* if 1: krb5_cc_initialize() called */
+ unsigned int cc_need_start_realm:1;
+ unsigned int cc_start_tgt_stored:1;
+ unsigned int cc_kx509_done:1;
+}krb5_ccache_data;
+
+typedef struct krb5_ccache_data *krb5_ccache;
+
+typedef struct krb5_context_data *krb5_context;
+
+typedef Realm krb5_realm;
+typedef const char *krb5_const_realm; /* stupid language */
+
+#define krb5_realm_length(r) strlen(r)
+#define krb5_realm_data(r) (r)
+
+typedef Principal krb5_principal_data;
+typedef struct Principal *krb5_principal;
+typedef const struct Principal *krb5_const_principal;
+typedef struct Principals *krb5_principals;
+
+typedef time_t krb5_deltat;
+typedef time_t krb5_timestamp;
+
+typedef struct krb5_times {
+ krb5_timestamp authtime;
+ krb5_timestamp starttime;
+ krb5_timestamp endtime;
+ krb5_timestamp renew_till;
+} krb5_times;
+
+typedef union {
+ TicketFlags b;
+ krb5_flags i;
+} krb5_ticket_flags;
+
+/* options for krb5_get_in_tkt() */
+#define KDC_OPT_FORWARDABLE (1 << 1)
+#define KDC_OPT_FORWARDED (1 << 2)
+#define KDC_OPT_PROXIABLE (1 << 3)
+#define KDC_OPT_PROXY (1 << 4)
+#define KDC_OPT_ALLOW_POSTDATE (1 << 5)
+#define KDC_OPT_POSTDATED (1 << 6)
+#define KDC_OPT_RENEWABLE (1 << 8)
+#define KDC_OPT_REQUEST_ANONYMOUS (1 << 14)
+#define KDC_OPT_DISABLE_TRANSITED_CHECK (1 << 26)
+#define KDC_OPT_RENEWABLE_OK (1 << 27)
+#define KDC_OPT_ENC_TKT_IN_SKEY (1 << 28)
+#define KDC_OPT_RENEW (1 << 30)
+#define KDC_OPT_VALIDATE (1 << 31)
+
+typedef union {
+ KDCOptions b;
+ krb5_flags i;
+} krb5_kdc_flags;
+
+/* flags for krb5_verify_ap_req */
+
+#define KRB5_VERIFY_AP_REQ_IGNORE_INVALID (1 << 0)
+#define KRB5_VERIFY_AP_REQ_IGNORE_ADDRS (1 << 1)
+
+#define KRB5_GC_CACHED (1U << 0)
+#define KRB5_GC_USER_USER (1U << 1)
+#define KRB5_GC_EXPIRED_OK (1U << 2)
+#define KRB5_GC_NO_STORE (1U << 3)
+#define KRB5_GC_FORWARDABLE (1U << 4)
+#define KRB5_GC_NO_TRANSIT_CHECK (1U << 5)
+#define KRB5_GC_CONSTRAINED_DELEGATION (1U << 6)
+#define KRB5_GC_CANONICALIZE (1U << 7)
+#define KRB5_GC_ANONYMOUS (1U << 8)
+
+/* constants for compare_creds (and cc_retrieve_cred) */
+#define KRB5_TC_DONT_MATCH_REALM (1U << 31)
+#define KRB5_TC_MATCH_KEYTYPE (1U << 30)
+#define KRB5_TC_MATCH_KTYPE KRB5_TC_MATCH_KEYTYPE /* MIT name */
+#define KRB5_TC_MATCH_SRV_NAMEONLY (1 << 29)
+#define KRB5_TC_MATCH_FLAGS_EXACT (1 << 28)
+#define KRB5_TC_MATCH_FLAGS (1 << 27)
+#define KRB5_TC_MATCH_TIMES_EXACT (1 << 26)
+#define KRB5_TC_MATCH_TIMES (1 << 25)
+#define KRB5_TC_MATCH_AUTHDATA (1 << 24)
+#define KRB5_TC_MATCH_2ND_TKT (1 << 23)
+#define KRB5_TC_MATCH_IS_SKEY (1 << 22)
+
+/* constants for get_flags and set_flags */
+#define KRB5_TC_OPENCLOSE 0x00000001
+#define KRB5_TC_NOTICKET 0x00000002
+
+typedef AuthorizationData krb5_authdata;
+
+typedef KRB_ERROR krb5_error;
+
+typedef struct krb5_creds {
+ krb5_principal client;
+ krb5_principal server;
+ krb5_keyblock session;
+ krb5_times times;
+ krb5_data ticket;
+ krb5_data second_ticket;
+ krb5_authdata authdata;
+ krb5_addresses addresses;
+ krb5_ticket_flags flags;
+} krb5_creds;
+
+typedef struct krb5_cc_cache_cursor_data *krb5_cc_cache_cursor;
+
+#define KRB5_CC_OPS_VERSION_0 0
+#define KRB5_CC_OPS_VERSION_1 1
+#define KRB5_CC_OPS_VERSION_2 2
+#define KRB5_CC_OPS_VERSION_3 3
+#define KRB5_CC_OPS_VERSION_5 5
+
+/* Only extend the structure. Do not change signatures. */
+typedef struct krb5_cc_ops {
+ /* Version 0 */
+ int version;
+ const char *prefix;
+ const char* (KRB5_CALLCONV * get_name)(krb5_context, krb5_ccache);
+ krb5_error_code (KRB5_CALLCONV * resolve)(krb5_context, krb5_ccache *, const char *);
+ krb5_error_code (KRB5_CALLCONV * gen_new)(krb5_context, krb5_ccache *);
+ krb5_error_code (KRB5_CALLCONV * init)(krb5_context, krb5_ccache, krb5_principal);
+ krb5_error_code (KRB5_CALLCONV * destroy)(krb5_context, krb5_ccache);
+ krb5_error_code (KRB5_CALLCONV * close)(krb5_context, krb5_ccache);
+ krb5_error_code (KRB5_CALLCONV * store)(krb5_context, krb5_ccache, krb5_creds*);
+ krb5_error_code (KRB5_CALLCONV * retrieve)(krb5_context, krb5_ccache,
+ krb5_flags, const krb5_creds*, krb5_creds *);
+ krb5_error_code (KRB5_CALLCONV * get_princ)(krb5_context, krb5_ccache, krb5_principal*);
+ krb5_error_code (KRB5_CALLCONV * get_first)(krb5_context, krb5_ccache, krb5_cc_cursor *);
+ krb5_error_code (KRB5_CALLCONV * get_next)(krb5_context, krb5_ccache,
+ krb5_cc_cursor*, krb5_creds*);
+ krb5_error_code (KRB5_CALLCONV * end_get)(krb5_context, krb5_ccache, krb5_cc_cursor*);
+ krb5_error_code (KRB5_CALLCONV * remove_cred)(krb5_context, krb5_ccache,
+ krb5_flags, krb5_creds*);
+ krb5_error_code (KRB5_CALLCONV * set_flags)(krb5_context, krb5_ccache, krb5_flags);
+ int (KRB5_CALLCONV * get_version)(krb5_context, krb5_ccache);
+ krb5_error_code (KRB5_CALLCONV * get_cache_first)(krb5_context, krb5_cc_cursor *);
+ krb5_error_code (KRB5_CALLCONV * get_cache_next)(krb5_context, krb5_cc_cursor,
+ krb5_ccache *);
+ krb5_error_code (KRB5_CALLCONV * end_cache_get)(krb5_context, krb5_cc_cursor);
+ krb5_error_code (KRB5_CALLCONV * move)(krb5_context, krb5_ccache, krb5_ccache);
+ krb5_error_code (KRB5_CALLCONV * get_default_name)(krb5_context, char **);
+ /* Version 1 */
+ krb5_error_code (KRB5_CALLCONV * set_default)(krb5_context, krb5_ccache);
+ /* Version 2 */
+ krb5_error_code (KRB5_CALLCONV * lastchange)(krb5_context, krb5_ccache, krb5_timestamp *);
+ /* Version 3 */
+ krb5_error_code (KRB5_CALLCONV * set_kdc_offset)(krb5_context, krb5_ccache, krb5_deltat);
+ krb5_error_code (KRB5_CALLCONV * get_kdc_offset)(krb5_context, krb5_ccache, krb5_deltat *);
+ /* Version 5 */
+ krb5_error_code (KRB5_CALLCONV * get_name_2)(krb5_context, krb5_ccache,
+ const char **id, const char **res,
+ const char **sub);
+ krb5_error_code (KRB5_CALLCONV * resolve_2)(krb5_context, krb5_ccache *id, const char *res,
+ const char *sub);
+ /* Add new functions here for versions 6 and above */
+} krb5_cc_ops;
+
+/*
+ * krb5_config_binding is identical to struct heim_config_binding
+ * within heimbase.h. Its format is public and used by callers of
+ * krb5_config_get_list() and krb5_config_vget_list().
+ */
+enum krb5_config_type {
+ krb5_config_string,
+ krb5_config_list,
+};
+struct krb5_config_binding {
+ enum krb5_config_type type;
+ char *name;
+ struct krb5_config_binding *next;
+ union {
+ char *string;
+ struct krb5_config_binding *list;
+ void *generic;
+ } u;
+};
+
+typedef struct krb5_config_binding krb5_config_binding;
+typedef krb5_config_binding krb5_config_section;
+
+typedef struct krb5_ticket {
+ EncTicketPart ticket;
+ krb5_principal client;
+ krb5_principal server;
+} krb5_ticket;
+
+typedef Authenticator krb5_authenticator_data;
+
+typedef krb5_authenticator_data *krb5_authenticator;
+
+struct krb5_rcache_data;
+typedef struct krb5_rcache_data *krb5_rcache;
+typedef Authenticator krb5_donot_replay;
+
+#define KRB5_STORAGE_HOST_BYTEORDER 0x01 /* old */
+#define KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONENTS 0x02
+#define KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE 0x04
+#define KRB5_STORAGE_KEYBLOCK_KEYTYPE_TWICE 0x08
+#define KRB5_STORAGE_BYTEORDER_MASK 0x70
+#define KRB5_STORAGE_BYTEORDER_BE 0x00 /* default */
+#define KRB5_STORAGE_BYTEORDER_PACKED 0x10
+#define KRB5_STORAGE_BYTEORDER_LE 0x20
+#define KRB5_STORAGE_BYTEORDER_HOST 0x40
+#define KRB5_STORAGE_CREDS_FLAGS_WRONG_BITORDER 0x80
+
+struct krb5_storage_data;
+typedef struct krb5_storage_data krb5_storage;
+
+typedef struct krb5_keytab_entry {
+ krb5_principal principal;
+ krb5_kvno vno;
+ krb5_keyblock keyblock;
+ uint32_t timestamp;
+ uint32_t flags;
+ krb5_principals aliases;
+} krb5_keytab_entry;
+
+typedef struct krb5_kt_cursor {
+ int fd;
+ krb5_storage *sp;
+ void *data;
+} krb5_kt_cursor;
+
+struct krb5_keytab_data;
+
+typedef struct krb5_keytab_data *krb5_keytab;
+
+#define KRB5_KT_PREFIX_MAX_LEN 30
+
+struct krb5_keytab_data {
+ const char *prefix;
+ krb5_error_code (KRB5_CALLCONV * resolve)(krb5_context, const char*, krb5_keytab);
+ krb5_error_code (KRB5_CALLCONV * get_name)(krb5_context, krb5_keytab, char*, size_t);
+ krb5_error_code (KRB5_CALLCONV * close)(krb5_context, krb5_keytab);
+ krb5_error_code (KRB5_CALLCONV * destroy)(krb5_context, krb5_keytab);
+ krb5_error_code (KRB5_CALLCONV * get)(krb5_context, krb5_keytab, krb5_const_principal,
+ krb5_kvno, krb5_enctype, krb5_keytab_entry*);
+ krb5_error_code (KRB5_CALLCONV * start_seq_get)(krb5_context, krb5_keytab, krb5_kt_cursor*);
+ krb5_error_code (KRB5_CALLCONV * next_entry)(krb5_context, krb5_keytab,
+ krb5_keytab_entry*, krb5_kt_cursor*);
+ krb5_error_code (KRB5_CALLCONV * end_seq_get)(krb5_context, krb5_keytab, krb5_kt_cursor*);
+ krb5_error_code (KRB5_CALLCONV * add)(krb5_context, krb5_keytab, krb5_keytab_entry*);
+ krb5_error_code (KRB5_CALLCONV * remove)(krb5_context, krb5_keytab, krb5_keytab_entry*);
+ void *data;
+ int32_t version;
+};
+
+typedef struct krb5_keytab_data krb5_kt_ops;
+
+struct krb5_keytab_key_proc_args {
+ krb5_keytab keytab;
+ krb5_principal principal;
+};
+
+typedef struct krb5_keytab_key_proc_args krb5_keytab_key_proc_args;
+
+typedef struct krb5_replay_data {
+ krb5_timestamp timestamp;
+ int32_t usec;
+ uint32_t seq;
+} krb5_replay_data;
+
+/* flags for krb5_auth_con_setflags */
+enum {
+ KRB5_AUTH_CONTEXT_DO_TIME = 1,
+ KRB5_AUTH_CONTEXT_RET_TIME = 2,
+ KRB5_AUTH_CONTEXT_DO_SEQUENCE = 4,
+ KRB5_AUTH_CONTEXT_RET_SEQUENCE = 8,
+ KRB5_AUTH_CONTEXT_PERMIT_ALL = 16,
+ KRB5_AUTH_CONTEXT_USE_SUBKEY = 32,
+ KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED = 64
+};
+
+/* flags for krb5_auth_con_genaddrs */
+enum {
+ KRB5_AUTH_CONTEXT_GENERATE_LOCAL_ADDR = 1,
+ KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR = 3,
+ KRB5_AUTH_CONTEXT_GENERATE_REMOTE_ADDR = 4,
+ KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR = 12
+};
+
+typedef struct krb5_auth_context_data {
+ unsigned int flags;
+
+ krb5_address *local_address;
+ krb5_address *remote_address;
+ int16_t local_port;
+ int16_t remote_port;
+ krb5_keyblock *keyblock;
+ krb5_keyblock *local_subkey;
+ krb5_keyblock *remote_subkey;
+
+ uint32_t local_seqnumber;
+ uint32_t remote_seqnumber;
+
+ krb5_authenticator authenticator;
+
+ krb5_pointer i_vector;
+
+ krb5_rcache rcache;
+
+ krb5_keytype keytype; /* ¿requested key type ? */
+ krb5_cksumtype cksumtype; /* ¡requested checksum type! */
+
+ AuthorizationData *auth_data;
+
+}krb5_auth_context_data, *krb5_auth_context;
+
+typedef struct {
+ KDC_REP kdc_rep;
+ EncKDCRepPart enc_part;
+ KRB_ERROR error;
+} krb5_kdc_rep;
+
+extern const char *heimdal_version, *heimdal_long_version;
+
+typedef void (KRB5_CALLCONV * krb5_log_log_func_t)(krb5_context,
+ const char*,
+ const char*,
+ void*);
+typedef void (KRB5_CALLCONV * krb5_log_close_func_t)(void*);
+
+typedef struct heim_log_facility_s krb5_log_facility;
+
+typedef EncAPRepPart krb5_ap_rep_enc_part;
+
+#define KRB5_RECVAUTH_IGNORE_VERSION 1
+
+#define KRB5_SENDAUTH_VERSION "KRB5_SENDAUTH_V1.0"
+
+#define KRB5_TGS_NAME_SIZE (6)
+#define KRB5_TGS_NAME ("krbtgt")
+#define KRB5_WELLKNOWN_NAME ("WELLKNOWN")
+#define KRB5_ANON_NAME ("ANONYMOUS")
+#define KRB5_ANON_REALM ("WELLKNOWN:ANONYMOUS")
+#define KRB5_FEDERATED_NAME ("FEDERATED")
+#define KRB5_FEDERATED_REALM ("WELLKNOWN:FEDERATED")
+#define KRB5_WELLKNOWN_ORG_H5L_REALM ("WELLKNOWN:ORG.H5L")
+#define KRB5_DIGEST_NAME ("digest")
+
+#define KRB5_PKU2U_REALM_NAME ("WELLKNOWN:PKU2U")
+#define KRB5_LKDC_REALM_NAME ("WELLKNOWN:COM.APPLE.LKDC")
+
+#define KRB5_GSS_HOSTBASED_SERVICE_NAME ("WELLKNOWN:ORG.H5L.HOSTBASED-SERVICE")
+#define KRB5_GSS_REFERALS_REALM_NAME ("WELLKNOWN:ORG.H5L.REFERALS-REALM")
+
+typedef enum {
+ KRB5_PROMPT_TYPE_PASSWORD = 0x1,
+ KRB5_PROMPT_TYPE_NEW_PASSWORD = 0x2,
+ KRB5_PROMPT_TYPE_NEW_PASSWORD_AGAIN = 0x3,
+ KRB5_PROMPT_TYPE_PREAUTH = 0x4,
+ KRB5_PROMPT_TYPE_INFO = 0x5
+} krb5_prompt_type;
+
+typedef struct _krb5_prompt {
+ const char *prompt;
+ int hidden;
+ krb5_data *reply;
+ krb5_prompt_type type;
+} krb5_prompt;
+
+typedef int (KRB5_CALLCONV * krb5_prompter_fct)(krb5_context /*context*/,
+ void * /*data*/,
+ const char * /*name*/,
+ const char * /*banner*/,
+ int /*num_prompts*/,
+ krb5_prompt /*prompts*/[]);
+typedef krb5_error_code (KRB5_CALLCONV * krb5_key_proc)(krb5_context /*context*/,
+ krb5_enctype /*type*/,
+ krb5_salt /*salt*/,
+ krb5_const_pointer /*keyseed*/,
+ krb5_keyblock ** /*key*/);
+typedef krb5_error_code (KRB5_CALLCONV * krb5_decrypt_proc)(krb5_context /*context*/,
+ krb5_keyblock * /*key*/,
+ krb5_key_usage /*usage*/,
+ krb5_const_pointer /*decrypt_arg*/,
+ krb5_kdc_rep * /*dec_rep*/);
+typedef krb5_error_code (KRB5_CALLCONV * krb5_s2k_proc)(krb5_context /*context*/,
+ krb5_enctype /*type*/,
+ krb5_const_pointer /*keyseed*/,
+ krb5_salt /*salt*/,
+ krb5_data * /*s2kparms*/,
+ krb5_keyblock ** /*key*/);
+
+struct _krb5_get_init_creds_opt_private;
+
+struct _krb5_get_init_creds_opt {
+ krb5_flags flags;
+ krb5_deltat tkt_life;
+ krb5_deltat renew_life;
+ int forwardable;
+ int proxiable;
+ int anonymous;
+ int change_password_prompt;
+ krb5_enctype *etype_list;
+ int etype_list_length;
+ krb5_addresses *address_list;
+ /* XXX the next three should not be used, as they may be
+ removed later */
+ krb5_preauthtype *preauth_list;
+ int preauth_list_length;
+ krb5_data *salt;
+ struct _krb5_get_init_creds_opt_private *opt_private;
+};
+
+typedef struct _krb5_get_init_creds_opt krb5_get_init_creds_opt;
+
+#define KRB5_GET_INIT_CREDS_OPT_TKT_LIFE 0x0001
+#define KRB5_GET_INIT_CREDS_OPT_RENEW_LIFE 0x0002
+#define KRB5_GET_INIT_CREDS_OPT_FORWARDABLE 0x0004
+#define KRB5_GET_INIT_CREDS_OPT_PROXIABLE 0x0008
+#define KRB5_GET_INIT_CREDS_OPT_ETYPE_LIST 0x0010
+#define KRB5_GET_INIT_CREDS_OPT_ADDRESS_LIST 0x0020
+#define KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST 0x0040
+#define KRB5_GET_INIT_CREDS_OPT_SALT 0x0080 /* no supported */
+#define KRB5_GET_INIT_CREDS_OPT_ANONYMOUS 0x0100
+#define KRB5_GET_INIT_CREDS_OPT_DISABLE_TRANSITED_CHECK 0x0200
+#define KRB5_GET_INIT_CREDS_OPT_CHANGE_PASSWORD_PROMPT 0x0400
+
+/* krb5_init_creds_step flags argument */
+#define KRB5_INIT_CREDS_STEP_FLAG_CONTINUE 0x0001
+
+typedef struct _krb5_verify_init_creds_opt {
+ krb5_flags flags;
+ int ap_req_nofail;
+} krb5_verify_init_creds_opt;
+
+#define KRB5_VERIFY_INIT_CREDS_OPT_AP_REQ_NOFAIL 0x0001
+
+typedef struct krb5_verify_opt {
+ unsigned int flags;
+ krb5_ccache ccache;
+ krb5_keytab keytab;
+ krb5_boolean secure;
+ const char *service;
+} krb5_verify_opt;
+
+#define KRB5_VERIFY_LREALMS 1
+#define KRB5_VERIFY_NO_ADDRESSES 2
+
+#define KRB5_KPASSWD_VERS_CHANGEPW 1
+#define KRB5_KPASSWD_VERS_SETPW 0xff80
+
+#define KRB5_KPASSWD_SUCCESS 0
+#define KRB5_KPASSWD_MALFORMED 1
+#define KRB5_KPASSWD_HARDERROR 2
+#define KRB5_KPASSWD_AUTHERROR 3
+#define KRB5_KPASSWD_SOFTERROR 4
+#define KRB5_KPASSWD_ACCESSDENIED 5
+#define KRB5_KPASSWD_BAD_VERSION 6
+#define KRB5_KPASSWD_INITIAL_FLAG_NEEDED 7
+
+#define KPASSWD_PORT 464
+
+/* types for the new krbhst interface */
+struct krb5_krbhst_data;
+typedef struct krb5_krbhst_data *krb5_krbhst_handle;
+
+#define KRB5_KRBHST_KDC 1
+#define KRB5_KRBHST_ADMIN 2
+#define KRB5_KRBHST_CHANGEPW 3
+#define KRB5_KRBHST_KRB524 4
+#define KRB5_KRBHST_KCA 5
+#define KRB5_KRBHST_READONLY_ADMIN 6
+#define KRB5_KRBHST_TKTBRIDGEAP 7
+
+typedef struct krb5_krbhst_info {
+ enum { KRB5_KRBHST_UDP,
+ KRB5_KRBHST_TCP,
+ KRB5_KRBHST_HTTP } proto;
+ unsigned short port;
+ unsigned short def_port;
+ struct addrinfo *ai;
+ struct krb5_krbhst_info *next;
+ char hostname[1]; /* has to come last */
+} krb5_krbhst_info;
+
+/* flags for krb5_krbhst_init_flags (and krb5_send_to_kdc_flags) */
+enum {
+ KRB5_KRBHST_FLAGS_MASTER = 1,
+ KRB5_KRBHST_FLAGS_LARGE_MSG = 2
+};
+
+typedef krb5_error_code (*krb5_sendto_prexmit)(krb5_context, int, void *, int, krb5_data *);
+typedef krb5_error_code
+(KRB5_CALLCONV * krb5_send_to_kdc_func)(krb5_context, void *, krb5_krbhst_info *, time_t,
+ const krb5_data *, krb5_data *);
+
+/** flags for krb5_parse_name_flags */
+enum {
+ KRB5_PRINCIPAL_PARSE_NO_REALM = 1, /**< Require that there are no realm */
+ KRB5_PRINCIPAL_PARSE_REQUIRE_REALM = 2, /**< Require a realm present */
+ KRB5_PRINCIPAL_PARSE_ENTERPRISE = 4, /**< Parse as a NT-ENTERPRISE name */
+ KRB5_PRINCIPAL_PARSE_IGNORE_REALM = 8, /**< Ignore realm if present */
+ KRB5_PRINCIPAL_PARSE_NO_DEF_REALM = 16 /**< Don't default the realm */
+};
+
+/** flags for krb5_unparse_name_flags */
+enum {
+ KRB5_PRINCIPAL_UNPARSE_SHORT = 1, /**< No realm if it is the default realm */
+ KRB5_PRINCIPAL_UNPARSE_NO_REALM = 2, /**< No realm */
+ KRB5_PRINCIPAL_UNPARSE_DISPLAY = 4 /**< No quoting */
+};
+
+typedef struct krb5_sendto_ctx_data *krb5_sendto_ctx;
+
+#define KRB5_SENDTO_DONE 0
+#define KRB5_SENDTO_RESET 1
+#define KRB5_SENDTO_CONTINUE 2
+#define KRB5_SENDTO_TIMEOUT 3
+#define KRB5_SENDTO_INITIAL 4
+#define KRB5_SENDTO_FILTER 5
+#define KRB5_SENDTO_FAILED 6
+#define KRB5_SENDTO_KRBHST 7
+
+typedef krb5_error_code
+(KRB5_CALLCONV * krb5_sendto_ctx_func)(krb5_context, krb5_sendto_ctx, void *,
+ const krb5_data *, int *);
+
+enum krb5_plugin_type {
+ PLUGIN_TYPE_DATA = 1,
+ PLUGIN_TYPE_FUNC /* no longer supported */
+};
+
+/*
+ * Since <krb5/common_plugin.h> is new with Heimdal 8, users looking to write
+ * portable plugins across Heimdal 7 and 8 need a conditional compilation
+ * predicate from a header file that does exist in both major releases. This
+ * is as good a place as any to define a plugin source-compatibility version
+ * number.
+ *
+ * When this macro is defined and is equal to 1, the Heimdal 8 plugin source
+ * API, and <krb5/common_plugin.h> header are available and should be used.
+ *
+ * In Heimdal 7, this macro is not defined, and <krb5/common_plugin.h> may not
+ * be available.
+ */
+#define KRB5_PLUGIN_COMMON_SPI_VERSION 1
+
+#define KRB5_PLUGIN_INVOKE_ALL 1
+
+typedef uintptr_t
+(KRB5_LIB_CALL *krb5_get_instance_func_t)(const char *);
+
+struct credentials; /* this is to keep the compiler happy */
+struct getargs;
+struct sockaddr;
+
+/**
+ * Semi private, not stable yet
+ */
+
+typedef struct krb5_crypto_iov {
+ unsigned int flags;
+ /* ignored */
+#define KRB5_CRYPTO_TYPE_EMPTY 0
+ /* OUT krb5_crypto_length(KRB5_CRYPTO_TYPE_HEADER) */
+#define KRB5_CRYPTO_TYPE_HEADER 1
+ /* IN and OUT */
+#define KRB5_CRYPTO_TYPE_DATA 2
+ /* IN */
+#define KRB5_CRYPTO_TYPE_SIGN_ONLY 3
+ /* (only for encryption) OUT krb5_crypto_length(KRB5_CRYPTO_TYPE_TRAILER) */
+#define KRB5_CRYPTO_TYPE_PADDING 4
+ /* OUT krb5_crypto_length(KRB5_CRYPTO_TYPE_TRAILER) */
+#define KRB5_CRYPTO_TYPE_TRAILER 5
+ /* OUT krb5_crypto_length(KRB5_CRYPTO_TYPE_CHECKSUM) */
+#define KRB5_CRYPTO_TYPE_CHECKSUM 6
+ krb5_data data;
+} krb5_crypto_iov;
+
+
+/* Glue for MIT */
+
+typedef struct {
+ int32_t lr_type;
+ krb5_timestamp value;
+} krb5_last_req_entry;
+
+typedef krb5_error_code
+(KRB5_CALLCONV * krb5_gic_process_last_req)(krb5_context, krb5_last_req_entry **, void *);
+
+typedef struct {
+ krb5_enctype ks_enctype;
+ krb5int32 ks_salttype;
+}krb5_key_salt_tuple;
+
+/*
+ * Name canonicalization rule options
+ */
+
+typedef enum krb5_name_canon_rule_options {
+ KRB5_NCRO_GC_ONLY = 1 << 0,
+ KRB5_NCRO_USE_REFERRALS = 1 << 1,
+ KRB5_NCRO_NO_REFERRALS = 1 << 2,
+ KRB5_NCRO_USE_FAST = 1 << 3,
+ KRB5_NCRO_USE_DNSSEC = 1 << 4,
+ KRB5_NCRO_LOOKUP_REALM = 1 << 5
+} krb5_name_canon_rule_options;
+
+typedef struct krb5_name_canon_rule_data *krb5_name_canon_rule;
+typedef const struct krb5_name_canon_rule_data *krb5_const_name_canon_rule;
+typedef struct krb5_name_canon_iterator_data *krb5_name_canon_iterator;
+
+/*
+ * krb5_get_init_creds_opt_set_pkinit flags
+ */
+
+#define KRB5_GIC_OPT_PKINIT_USE_ENCKEY 2 /* use RSA, not DH */
+#define KRB5_GIC_OPT_PKINIT_ANONYMOUS 4 /* anonymous PKINIT */
+#define KRB5_GIC_OPT_PKINIT_BTMM 8 /* reserved by Apple */
+#define KRB5_GIC_OPT_PKINIT_NO_KDC_ANCHOR 16 /* do not authenticate KDC */
+
+/*
+ * _krb5_principal_is_anonymous() flags
+ */
+#define KRB5_ANON_MATCH_AUTHENTICATED 1 /* authenticated with anon flag */
+#define KRB5_ANON_MATCH_UNAUTHENTICATED 2 /* anonymous PKINIT */
+#define KRB5_ANON_IGNORE_NAME_TYPE 4 /* don't check the name type */
+#define KRB5_ANON_MATCH_ANY ( KRB5_ANON_MATCH_AUTHENTICATED | \
+ KRB5_ANON_MATCH_UNAUTHENTICATED )
+#define KRB5_ANON_MATCH_ANY_NONT ( KRB5_ANON_MATCH_ANY | \
+ KRB5_ANON_IGNORE_NAME_TYPE )
+
+/*
+ *
+ */
+
+struct hx509_certs_data;
+typedef struct krb5_kx509_req_ctx_data *krb5_kx509_req_ctx;
+
+#include <krb5-protos.h>
+
+/* variables */
+
+extern KRB5_LIB_VARIABLE const char *krb5_config_file;
+extern KRB5_LIB_VARIABLE const char *krb5_defkeyname;
+
+
+extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_acc_ops;
+extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_dcc_ops;
+extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_fcc_ops;
+extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_mcc_ops;
+extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_kcm_ops;
+extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_akcm_ops;
+extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_scc_ops;
+extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_krcc_ops;
+
+extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_fkt_ops;
+extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_wrfkt_ops;
+extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_javakt_ops;
+extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_mkt_ops;
+extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_akf_ops;
+extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_any_ops;
+
+extern KRB5_LIB_VARIABLE const char *krb5_cc_type_api;
+extern KRB5_LIB_VARIABLE const char *krb5_cc_type_file;
+extern KRB5_LIB_VARIABLE const char *krb5_cc_type_memory;
+extern KRB5_LIB_VARIABLE const char *krb5_cc_type_kcm;
+extern KRB5_LIB_VARIABLE const char *krb5_cc_type_scc;
+extern KRB5_LIB_VARIABLE const char *krb5_cc_type_dcc;
+extern KRB5_LIB_VARIABLE const char *krb5_cc_type_keyring;
+
+/* clang analyzer workarounds */
+
+#ifdef __clang_analyzer__
+/*
+ * The clang analyzer (lint) can't know that krb5_enomem() always returns
+ * non-zero, so code like:
+ *
+ * if ((x = malloc(...)) == NULL)
+ * ret = krb5_enomem(context)
+ * if (ret == 0)
+ * *x = ...;
+ *
+ * causes false positives.
+ *
+ * The fix is to make krb5_enomem() a macro that always evaluates to ENOMEM.
+ */
+#define krb5_enomem(c) (krb5_enomem(c), ENOMEM)
+#endif
+
+#endif /* __KRB5_H__ */
+
diff --git a/third_party/heimdal/lib/krb5/krb5.moduli b/third_party/heimdal/lib/krb5/krb5.moduli
new file mode 100644
index 0000000..a27bae5
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5.moduli
@@ -0,0 +1,3 @@
+# $Id$
+# comment security-bits-decimal secure-prime(p)-hex generator(g)-hex (q)-hex
+rfc3526-MODP-group14 1760 FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF 02 7FFFFFFFFFFFFFFFE487ED5110B4611A62633145C06E0E68948127044533E63A0105DF531D89CD9128A5043CC71A026EF7CA8CD9E69D218D98158536F92F8A1BA7F09AB6B6A8E122F242DABB312F3F637A262174D31BF6B585FFAE5B7A035BF6F71C35FDAD44CFD2D74F9208BE258FF324943328F6722D9EE1003E5C50B1DF82CC6D241B0E2AE9CD348B1FD47E9267AFC1B2AE91EE51D6CB0E3179AB1042A95DCF6A9483B84B4B36B3861AA7255E4C0278BA3604650C10BE19482F23171B671DF1CF3B960C074301CD93C1D17603D147DAE2AEF837A62964EF15E5FB4AAC0B8C1CCAA4BE754AB5728AE9130C4C7D02880AB9472D455655347FFFFFFFFFFFFFFF
diff --git a/third_party/heimdal/lib/krb5/krb524_convert_creds_kdc.3 b/third_party/heimdal/lib/krb5/krb524_convert_creds_kdc.3
new file mode 100644
index 0000000..511eabd
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb524_convert_creds_kdc.3
@@ -0,0 +1,86 @@
+.\" Copyright (c) 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd March 20, 2004
+.Dt KRB524_CONVERT_CREDS_KDC 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb524_convert_creds_kdc ,
+.Nm krb524_convert_creds_kdc_ccache
+.Nd converts Kerberos 5 credentials to Kerberos 4 credentials
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fo krb524_convert_creds_kdc
+.Fa "krb5_context context"
+.Fa "krb5_creds *in_cred"
+.Fa "struct credentials *v4creds"
+.Fc
+.Ft krb5_error_code
+.Fo krb524_convert_creds_kdc_ccache
+.Fa "krb5_context context"
+.Fa "krb5_ccache ccache"
+.Fa "krb5_creds *in_cred"
+.Fa "struct credentials *v4creds"
+.Fc
+.Sh DESCRIPTION
+Convert the Kerberos 5 credential to Kerberos 4 credential.
+This is done by sending them to the 524 service in the KDC.
+.Pp
+.Fn krb524_convert_creds_kdc
+converts the Kerberos 5 credential in
+.Fa in_cred
+to Kerberos 4 credential that is stored in
+.Fa credentials .
+.Pp
+.Fn krb524_convert_creds_kdc_ccache
+is different from
+.Fn krb524_convert_creds_kdc
+in that way that if
+.Fa in_cred
+doesn't contain a DES session key, then a new one is fetched from the
+KDC and stored in the cred cache
+.Fa ccache ,
+and then the KDC is queried to convert the credential.
+.Pp
+This interfaces are used to make the migration to Kerberos 5 from
+Kerberos 4 easier.
+There are few services that still need Kerberos 4, and this is mainly
+for compatibility for those services.
+Some services, like AFS, really have Kerberos 5 supports, but still
+uses the 524 interface to make the migration easier.
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5.conf 5
diff --git a/third_party/heimdal/lib/krb5/krb5_425_conv_principal.3 b/third_party/heimdal/lib/krb5/krb5_425_conv_principal.3
new file mode 100644
index 0000000..49028f4
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_425_conv_principal.3
@@ -0,0 +1,224 @@
+.\" Copyright (c) 1997-2003 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd September 3, 2003
+.Dt KRB5_425_CONV_PRINCIPAL 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_425_conv_principal ,
+.Nm krb5_425_conv_principal_ext ,
+.Nm krb5_524_conv_principal
+.Nd converts to and from version 4 principals
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fn krb5_425_conv_principal "krb5_context context" "const char *name" "const char *instance" "const char *realm" "krb5_principal *principal"
+.Ft krb5_error_code
+.Fn krb5_425_conv_principal_ext "krb5_context context" "const char *name" "const char *instance" "const char *realm" "krb5_boolean (*func)(krb5_context, krb5_principal)" "krb5_boolean resolve" "krb5_principal *principal"
+.Ft krb5_error_code
+.Fn krb5_524_conv_principal "krb5_context context" "const krb5_principal principal" "char *name" "char *instance" "char *realm"
+.Sh DESCRIPTION
+Converting between version 4 and version 5 principals can at best be
+described as a mess.
+.Pp
+A version 4 principal consists of a name, an instance, and a realm. A
+version 5 principal consists of one or more components, and a
+realm. In some cases also the first component/name will differ between
+version 4 and version 5. Furthermore the second component of a host
+principal will be the fully qualified domain name of the host in
+question, while the instance of a version 4 principal will only
+contain the first part (short hostname). Because of these problems
+the conversion between principals will have to be site customized.
+.Pp
+.Fn krb5_425_conv_principal_ext
+will try to convert a version 4 principal, given by
+.Fa name ,
+.Fa instance ,
+and
+.Fa realm ,
+to a version 5 principal. This can result in several possible
+principals, and if
+.Fa func
+is non-NULL, it will be called for each candidate principal.
+.Fa func
+should return true if the principal was
+.Dq good .
+To accomplish this,
+.Fn krb5_425_conv_principal_ext
+will look up the name in
+.Pa krb5.conf .
+It first looks in the
+.Li v4_name_convert/host
+subsection, which should contain a list of version 4 names whose
+instance should be treated as a hostname. This list can be specified
+for each realm (in the
+.Li realms
+section), or in the
+.Li libdefaults
+section. If the name is found the resulting name of the principal
+will be the value of this binding. The instance is then first looked
+up in
+.Li v4_instance_convert
+for the specified realm. If found the resulting value will be used as
+instance (this can be used for special cases), no further attempts
+will be made to find a conversion if this fails (with
+.Fa func ) .
+If the
+.Fa resolve
+parameter is true, the instance will be looked up with
+.Fn gethostbyname .
+This can be a time consuming, error prone, and unsafe operation. Next
+a list of hostnames will be created from the instance and the
+.Li v4_domains
+variable, which should contain a list of possible domains for the
+specific realm.
+.Pp
+On the other hand, if the name is not found in a
+.Li host
+section, it is looked up in a
+.Li v4_name_convert/plain
+binding. If found here the name will be converted, but the instance
+will be untouched.
+.Pp
+This list of default host-type conversions is compiled-in:
+.Bd -literal -offset indent
+v4_name_convert = {
+ host = {
+ ftp = ftp
+ hprop = hprop
+ imap = imap
+ pop = pop
+ rcmd = host
+ smtp = smtp
+ }
+}
+.Ed
+.Pp
+It will only be used if there isn't an entry for these names in the
+config file, so you can override these defaults.
+.Pp
+.Fn krb5_425_conv_principal
+will call
+.Fn krb5_425_conv_principal_ext
+with
+.Dv NULL
+as
+.Fa func ,
+and the value of
+.Li v4_instance_resolve
+(from the
+.Li libdefaults
+section) as
+.Fa resolve .
+.Pp
+.Fn krb5_524_conv_principal
+basically does the opposite of
+.Fn krb5_425_conv_principal ,
+it just doesn't have to look up any names, but will instead truncate
+instances found to belong to a host principal. The
+.Fa name ,
+.Fa instance ,
+and
+.Fa realm
+should be at least 40 characters long.
+.Sh EXAMPLES
+Since this is confusing an example is in place.
+.Pp
+Assume that we have the
+.Dq foo.com ,
+and
+.Dq bar.com
+domains that have shared a single version 4 realm, FOO.COM. The version 4
+.Pa krb.realms
+file looked like:
+.Bd -literal -offset indent
+foo.com FOO.COM
+\&.foo.com FOO.COM
+\&.bar.com FOO.COM
+.Ed
+.Pp
+A
+.Pa krb5.conf
+file that covers this case might look like:
+.Bd -literal -offset indent
+[libdefaults]
+ v4_instance_resolve = yes
+[realms]
+ FOO.COM = {
+ kdc = kerberos.foo.com
+ v4_instance_convert = {
+ foo = foo.com
+ }
+ v4_domains = foo.com
+ }
+.Ed
+.Pp
+With this setup and the following host table:
+.Bd -literal -offset indent
+foo.com
+a-host.foo.com
+b-host.bar.com
+.Ed
+the following conversions will be made:
+.Bd -literal -offset indent
+rcmd.a-host -\*(Gt host/a-host.foo.com
+ftp.b-host -\*(Gt ftp/b-host.bar.com
+pop.foo -\*(Gt pop/foo.com
+ftp.other -\*(Gt ftp/other.foo.com
+other.a-host -\*(Gt other/a-host
+.Ed
+.Pp
+The first three are what you expect. If you remove the
+.Dq v4_domains ,
+the fourth entry will result in an error (since the host
+.Dq other
+can't be found). Even if
+.Dq a-host
+is a valid host name, the last entry will not be converted, since the
+.Dq other
+name is not known to represent a host-type principal.
+If you turn off
+.Dq v4_instance_resolve
+the second example will result in
+.Dq ftp/b-host.foo.com
+(because of the default domain). And all of this is of course only
+valid if you have working name resolving.
+.Sh SEE ALSO
+.Xr krb5_build_principal 3 ,
+.Xr krb5_free_principal 3 ,
+.Xr krb5_parse_name 3 ,
+.Xr krb5_sname_to_principal 3 ,
+.Xr krb5_unparse_name 3 ,
+.Xr krb5.conf 5
diff --git a/third_party/heimdal/lib/krb5/krb5_acl_match_file.3 b/third_party/heimdal/lib/krb5/krb5_acl_match_file.3
new file mode 100644
index 0000000..a1eb1e4
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_acl_match_file.3
@@ -0,0 +1,111 @@
+.\" Copyright (c) 2004, 2006 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 12, 2006
+.Dt KRB5_ACL_MATCH_FILE 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_acl_match_file ,
+.Nm krb5_acl_match_string
+.Nd ACL matching functions
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.Ft krb5_error_code
+.Fo krb5_acl_match_file
+.Fa "krb5_context context"
+.Fa "const char *file"
+.Fa "const char *format"
+.Fa "..."
+.Fc
+.Ft krb5_error_code
+.Fo krb5_acl_match_string
+.Fa "krb5_context context"
+.Fa "const char *string"
+.Fa "const char *format"
+.Fa "..."
+.Fc
+.Sh DESCRIPTION
+.Nm krb5_acl_match_file
+matches ACL format against each line in a file.
+Lines starting with # are treated like comments and ignored.
+.Pp
+.Nm krb5_acl_match_string
+matches ACL format against a string.
+.Pp
+The ACL format has three format specifiers: s, f, and r.
+Each specifier will retrieve one argument from the variable arguments
+for either matching or storing data.
+The input string is split up using " " and "\et" as a delimiter; multiple
+" " and "\et" in a row are considered to be the same.
+.Pp
+.Bl -tag -width "fXX" -offset indent
+.It s
+Matches a string using
+.Xr strcmp 3
+(case sensitive).
+.It f
+Matches the string with
+.Xr fnmatch 3 .
+The
+.Fa flags
+argument (the last argument) passed to the fnmatch function is 0.
+.It r
+Returns a copy of the string in the char ** passed in; the copy must be
+freed with
+.Xr free 3 .
+There is no need to
+.Xr free 3
+the string on error: the function will clean up and set the pointer to
+.Dv NULL .
+.El
+.Pp
+All unknown format specifiers cause an error.
+.Sh EXAMPLES
+.Bd -literal -offset indent
+char *s;
+
+ret = krb5_acl_match_string(context, "foo", "s", "foo");
+if (ret)
+ krb5_errx(context, 1, "acl didn't match");
+ret = krb5_acl_match_string(context, "foo foo baz/kaka",
+ "ss", "foo", &s, "foo/*");
+if (ret) {
+ /* no need to free(s) on error */
+ assert(s == NULL);
+ krb5_errx(context, 1, "acl didn't match");
+}
+free(s);
+.Ed
+.Sh SEE ALSO
+.Xr krb5 3
diff --git a/third_party/heimdal/lib/krb5/krb5_aname_to_localname.3 b/third_party/heimdal/lib/krb5/krb5_aname_to_localname.3
new file mode 100644
index 0000000..a50e935
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_aname_to_localname.3
@@ -0,0 +1,80 @@
+.\" Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd February 18, 2006
+.Dt KRB5_ANAME_TO_LOCALNAME 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_aname_to_localname
+.Nd converts a principal to a system local name
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_boolean
+.Fo krb5_aname_to_localname
+.Fa "krb5_context context"
+.Fa "krb5_const_principal name"
+.Fa "size_t lnsize"
+.Fa "char *lname"
+.Fc
+.Sh DESCRIPTION
+This function takes a principal
+.Fa name ,
+verifies that it is in the local realm (using
+.Fn krb5_get_default_realms )
+and then returns the local name of the principal.
+.Pp
+If
+.Fa name
+isn't in one of the local realms an error is returned.
+.Pp
+If the size
+.Fa ( lnsize )
+of the local name
+.Fa ( lname )
+is too small, an error is returned.
+.Pp
+.Fn krb5_aname_to_localname
+should only be use by an application that implements protocols that
+don't transport the login name and thus needs to convert a principal
+to a local name.
+.Pp
+Protocols should be designed so that they authenticate using
+Kerberos, send over the login name and then verify the principal
+that is authenticated is allowed to login and the login name.
+A way to check if a user is allowed to login is using the function
+.Fn krb5_kuserok .
+.Sh SEE ALSO
+.Xr krb5_get_default_realms 3 ,
+.Xr krb5_kuserok 3
diff --git a/third_party/heimdal/lib/krb5/krb5_appdefault.3 b/third_party/heimdal/lib/krb5/krb5_appdefault.3
new file mode 100644
index 0000000..780c2ff
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_appdefault.3
@@ -0,0 +1,88 @@
+.\" Copyright (c) 2000 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd July 25, 2000
+.Dt KRB5_APPDEFAULT 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_appdefault_boolean ,
+.Nm krb5_appdefault_string ,
+.Nm krb5_appdefault_time
+.Nd get application configuration value
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft void
+.Fn krb5_appdefault_boolean "krb5_context context" "const char *appname" "krb5_realm realm" "const char *option" "krb5_boolean def_val" "krb5_boolean *ret_val"
+.Ft void
+.Fn krb5_appdefault_string "krb5_context context" "const char *appname" "krb5_realm realm" "const char *option" "const char *def_val" "char **ret_val"
+.Ft void
+.Fn krb5_appdefault_time "krb5_context context" "const char *appname" "krb5_realm realm" "const char *option" "time_t def_val" "time_t *ret_val"
+.Sh DESCRIPTION
+These functions get application defaults from the
+.Dv appdefaults
+section of the
+.Xr krb5.conf 5
+configuration file. These defaults can be specified per application,
+and/or per realm.
+.Pp
+These values will be looked for in
+.Xr krb5.conf 5 ,
+in order of descending importance.
+.Bd -literal -offset indent
+[appdefaults]
+ appname = {
+ realm = {
+ option = value
+ }
+ }
+ appname = {
+ option = value
+ }
+ realm = {
+ option = value
+ }
+ option = value
+.Ed
+.Fa appname
+is the name of the application, and
+.Fa realm
+is the realm name. If the realm is omitted it will not be used for
+resolving values.
+.Fa def_val
+is the value to return if no value is found in
+.Xr krb5.conf 5 .
+.Sh SEE ALSO
+.Xr krb5_config 3 ,
+.Xr krb5.conf 5
diff --git a/third_party/heimdal/lib/krb5/krb5_auth_context.3 b/third_party/heimdal/lib/krb5/krb5_auth_context.3
new file mode 100644
index 0000000..b627e48
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_auth_context.3
@@ -0,0 +1,395 @@
+.\" Copyright (c) 2001 - 2005 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 17, 2005
+.Dt KRB5_AUTH_CONTEXT 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_auth_con_addflags ,
+.Nm krb5_auth_con_free ,
+.Nm krb5_auth_con_genaddrs ,
+.Nm krb5_auth_con_generatelocalsubkey ,
+.Nm krb5_auth_con_getaddrs ,
+.Nm krb5_auth_con_getauthenticator ,
+.Nm krb5_auth_con_getflags ,
+.Nm krb5_auth_con_getkey ,
+.Nm krb5_auth_con_getlocalsubkey ,
+.Nm krb5_auth_con_getrcache ,
+.Nm krb5_auth_con_getremotesubkey ,
+.Nm krb5_auth_con_getuserkey ,
+.Nm krb5_auth_con_init ,
+.Nm krb5_auth_con_initivector ,
+.Nm krb5_auth_con_removeflags ,
+.Nm krb5_auth_con_setaddrs ,
+.Nm krb5_auth_con_setaddrs_from_fd ,
+.Nm krb5_auth_con_setflags ,
+.Nm krb5_auth_con_setivector ,
+.Nm krb5_auth_con_setkey ,
+.Nm krb5_auth_con_setlocalsubkey ,
+.Nm krb5_auth_con_setrcache ,
+.Nm krb5_auth_con_setremotesubkey ,
+.Nm krb5_auth_con_setuserkey ,
+.Nm krb5_auth_context ,
+.Nm krb5_auth_getcksumtype ,
+.Nm krb5_auth_getkeytype ,
+.Nm krb5_auth_getlocalseqnumber ,
+.Nm krb5_auth_getremoteseqnumber ,
+.Nm krb5_auth_setcksumtype ,
+.Nm krb5_auth_setkeytype ,
+.Nm krb5_auth_setlocalseqnumber ,
+.Nm krb5_auth_setremoteseqnumber ,
+.Nm krb5_free_authenticator
+.Nd manage authentication on connection level
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fo krb5_auth_con_init
+.Fa "krb5_context context"
+.Fa "krb5_auth_context *auth_context"
+.Fc
+.Ft void
+.Fo krb5_auth_con_free
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_auth_con_setflags
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fa "int32_t flags"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_auth_con_getflags
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fa "int32_t *flags"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_auth_con_addflags
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fa "int32_t addflags"
+.Fa "int32_t *flags"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_auth_con_removeflags
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fa "int32_t removelags"
+.Fa "int32_t *flags"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_auth_con_setaddrs
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fa "krb5_address *local_addr"
+.Fa "krb5_address *remote_addr"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_auth_con_getaddrs
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fa "krb5_address **local_addr"
+.Fa "krb5_address **remote_addr"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_auth_con_genaddrs
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fa "int fd"
+.Fa "int flags"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_auth_con_setaddrs_from_fd
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fa "void *p_fd"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_auth_con_getkey
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fa "krb5_keyblock **keyblock"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_auth_con_getlocalsubkey
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fa "krb5_keyblock **keyblock"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_auth_con_getremotesubkey
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fa "krb5_keyblock **keyblock"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_auth_con_generatelocalsubkey
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fa krb5_keyblock *key"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_auth_con_initivector
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_auth_con_setivector
+.Fa "krb5_context context"
+.Fa "krb5_auth_context *auth_context"
+.Fa "krb5_pointer ivector"
+.Fc
+.Ft void
+.Fo krb5_free_authenticator
+.Fa "krb5_context context"
+.Fa "krb5_authenticator *authenticator"
+.Fc
+.Sh DESCRIPTION
+The
+.Nm krb5_auth_context
+structure holds all context related to an authenticated connection, in
+a similar way to
+.Nm krb5_context
+that holds the context for the thread or process.
+.Nm krb5_auth_context
+is used by various functions that are directly related to
+authentication between the server/client. Example of data that this
+structure contains are various flags, addresses of client and server,
+port numbers, keyblocks (and subkeys), sequence numbers, replay cache,
+and checksum-type.
+.Pp
+.Fn krb5_auth_con_init
+allocates and initializes the
+.Nm krb5_auth_context
+structure. Default values can be changed with
+.Fn krb5_auth_con_setcksumtype
+and
+.Fn krb5_auth_con_setflags .
+The
+.Nm auth_context
+structure must be freed by
+.Fn krb5_auth_con_free .
+.Pp
+.Fn krb5_auth_con_getflags ,
+.Fn krb5_auth_con_setflags ,
+.Fn krb5_auth_con_addflags
+and
+.Fn krb5_auth_con_removeflags
+gets and modifies the flags for a
+.Nm krb5_auth_context
+structure. Possible flags to set are:
+.Bl -tag -width Ds
+.It Dv KRB5_AUTH_CONTEXT_DO_SEQUENCE
+Generate and check sequence-number on each packet.
+.It Dv KRB5_AUTH_CONTEXT_DO_TIME
+Check timestamp on incoming packets.
+.It Dv KRB5_AUTH_CONTEXT_RET_SEQUENCE , Dv KRB5_AUTH_CONTEXT_RET_TIME
+Return sequence numbers and time stamps in the outdata parameters.
+.It Dv KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED
+will force
+.Fn krb5_get_forwarded_creds
+and
+.Fn krb5_fwd_tgt_creds
+to create unencrypted )
+.Dv KRB5_ENCTYPE_NULL )
+credentials.
+This is for use with old MIT server and JAVA based servers as
+they can't handle encrypted
+.Dv KRB-CRED .
+Note that sending such
+.Dv KRB-CRED
+is clear exposes crypto keys and tickets and is insecure,
+make sure the packet is encrypted in the protocol.
+.Xr krb5_rd_cred 3 ,
+.Xr krb5_rd_priv 3 ,
+.Xr krb5_rd_safe 3 ,
+.Xr krb5_mk_priv 3
+and
+.Xr krb5_mk_safe 3 .
+Setting this flag requires that parameter to be passed to these
+functions.
+.Pp
+The flags
+.Dv KRB5_AUTH_CONTEXT_DO_TIME
+also modifies the behavior the function
+.Fn krb5_get_forwarded_creds
+by removing the timestamp in the forward credential message, this have
+backward compatibility problems since not all versions of the heimdal
+supports timeless credentional messages.
+Is very useful since it always the sender of the message to cache
+forward message and thus avoiding a round trip to the KDC for each
+time a credential is forwarded.
+The same functionality can be obtained by using address-less tickets.
+.\".It Dv KRB5_AUTH_CONTEXT_PERMIT_ALL
+.El
+.Pp
+.Fn krb5_auth_con_setaddrs ,
+.Fn krb5_auth_con_setaddrs_from_fd
+and
+.Fn krb5_auth_con_getaddrs
+gets and sets the addresses that are checked when a packet is received.
+It is mandatory to set an address for the remote
+host. If the local address is not set, it iss deduced from the underlaying
+operating system.
+.Fn krb5_auth_con_getaddrs
+will call
+.Fn krb5_free_address
+on any address that is passed in
+.Fa local_addr
+or
+.Fa remote_addr .
+.Fn krb5_auth_con_setaddr
+allows passing in a
+.Dv NULL
+pointer as
+.Fa local_addr
+and
+.Fa remote_addr ,
+in that case it will just not set that address.
+.Pp
+.Fn krb5_auth_con_setaddrs_from_fd
+fetches the addresses from a file descriptor.
+.Pp
+.Fn krb5_auth_con_genaddrs
+fetches the address information from the given file descriptor
+.Fa fd
+depending on the bitmap argument
+.Fa flags .
+.Pp
+Possible values on
+.Fa flags
+are:
+.Bl -tag -width Ds
+.It Va KRB5_AUTH_CONTEXT_GENERATE_LOCAL_ADDR
+fetches the local address from
+.Fa fd .
+.It Va KRB5_AUTH_CONTEXT_GENERATE_REMOTE_ADDR
+fetches the remote address from
+.Fa fd .
+.El
+.Pp
+.Fn krb5_auth_con_setkey ,
+.Fn krb5_auth_con_setuserkey
+and
+.Fn krb5_auth_con_getkey
+gets and sets the key used for this auth context. The keyblock returned by
+.Fn krb5_auth_con_getkey
+should be freed with
+.Fn krb5_free_keyblock .
+The keyblock send into
+.Fn krb5_auth_con_setkey
+is copied into the
+.Nm krb5_auth_context ,
+and thus no special handling is needed.
+.Dv NULL
+is not a valid keyblock to
+.Fn krb5_auth_con_setkey .
+.Pp
+.Fn krb5_auth_con_setuserkey
+is only useful when doing user to user authentication.
+.Fn krb5_auth_con_setkey
+is equivalent to
+.Fn krb5_auth_con_setuserkey .
+.Pp
+.Fn krb5_auth_con_getlocalsubkey ,
+.Fn krb5_auth_con_setlocalsubkey ,
+.Fn krb5_auth_con_getremotesubkey
+and
+.Fn krb5_auth_con_setremotesubkey
+gets and sets the keyblock for the local and remote subkey.
+The keyblock returned by
+.Fn krb5_auth_con_getlocalsubkey
+and
+.Fn krb5_auth_con_getremotesubkey
+must be freed with
+.Fn krb5_free_keyblock .
+.Pp
+.Fn krb5_auth_setcksumtype
+and
+.Fn krb5_auth_getcksumtype
+sets and gets the checksum type that should be used for this
+connection.
+.Pp
+.Fn krb5_auth_con_generatelocalsubkey
+generates a local subkey that have the same encryption type as
+.Fa key .
+.Pp
+.Fn krb5_auth_getremoteseqnumber
+.Fn krb5_auth_setremoteseqnumber ,
+.Fn krb5_auth_getlocalseqnumber
+and
+.Fn krb5_auth_setlocalseqnumber
+gets and sets the sequence-number for the local and remote
+sequence-number counter.
+.Pp
+.Fn krb5_auth_setkeytype
+and
+.Fn krb5_auth_getkeytype
+gets and gets the keytype of the keyblock in
+.Nm krb5_auth_context .
+.Pp
+.Fn krb5_auth_con_getauthenticator
+Retrieves the authenticator that was used during mutual
+authentication. The
+.Dv authenticator
+returned should be freed by calling
+.Fn krb5_free_authenticator .
+.Pp
+.Fn krb5_auth_con_getrcache
+and
+.Fn krb5_auth_con_setrcache
+gets and sets the replay-cache.
+.Pp
+.Fn krb5_auth_con_initivector
+allocates memory for and zeros the initial vector in the
+.Fa auth_context
+keyblock.
+.Pp
+.Fn krb5_auth_con_setivector
+sets the i_vector portion of
+.Fa auth_context
+to
+.Fa ivector .
+.Pp
+.Fn krb5_free_authenticator
+free the content of
+.Fa authenticator
+and
+.Fa authenticator
+itself.
+.Sh SEE ALSO
+.Xr krb5_context 3 ,
+.Xr kerberos 8
diff --git a/third_party/heimdal/lib/krb5/krb5_c_make_checksum.3 b/third_party/heimdal/lib/krb5/krb5_c_make_checksum.3
new file mode 100644
index 0000000..66402d4
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_c_make_checksum.3
@@ -0,0 +1,297 @@
+.\" Copyright (c) 2003 - 2006 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd Nov 17, 2006
+.Dt KRB5_C_MAKE_CHECKSUM 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_c_block_size ,
+.Nm krb5_c_decrypt ,
+.Nm krb5_c_encrypt ,
+.Nm krb5_c_encrypt_length ,
+.Nm krb5_c_enctype_compare ,
+.Nm krb5_c_get_checksum ,
+.Nm krb5_c_is_coll_proof_cksum ,
+.Nm krb5_c_is_keyed_cksum ,
+.Nm krb5_c_keylength ,
+.Nm krb5_c_make_checksum ,
+.Nm krb5_c_make_random_key ,
+.Nm krb5_c_set_checksum ,
+.Nm krb5_c_valid_cksumtype ,
+.Nm krb5_c_valid_enctype ,
+.Nm krb5_c_verify_checksum ,
+.Nm krb5_c_checksum_length
+.Nd Kerberos 5 crypto API
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Pp
+.Ft krb5_error_code
+.Fo krb5_c_block_size
+.Fa "krb5_context context"
+.Fa "krb5_enctype enctype"
+.Fa "size_t *blocksize"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_c_decrypt
+.Fa "krb5_context context"
+.Fa "const krb5_keyblock key"
+.Fa "krb5_keyusage usage"
+.Fa "const krb5_data *ivec"
+.Fa "krb5_enc_data *input"
+.Fa "krb5_data *output"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_c_encrypt
+.Fa "krb5_context context"
+.Fa "const krb5_keyblock *key"
+.Fa "krb5_keyusage usage"
+.Fa "const krb5_data *ivec"
+.Fa "const krb5_data *input"
+.Fa "krb5_enc_data *output"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_c_encrypt_length
+.Fa "krb5_context context"
+.Fa "krb5_enctype enctype"
+.Fa "size_t inputlen"
+.Fa "size_t *length"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_c_enctype_compare
+.Fa "krb5_context context"
+.Fa "krb5_enctype e1"
+.Fa "krb5_enctype e2"
+.Fa "krb5_boolean *similar"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_c_make_random_key
+.Fa "krb5_context context"
+.Fa "krb5_enctype enctype"
+.Fa "krb5_keyblock *random_key"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_c_make_checksum
+.Fa "krb5_context context"
+.Fa "krb5_cksumtype cksumtype"
+.Fa "const krb5_keyblock *key"
+.Fa "krb5_keyusage usage"
+.Fa "const krb5_data *input"
+.Fa "krb5_checksum *cksum"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_c_verify_checksum
+.Fa "krb5_context context"
+.Fa "const krb5_keyblock *key"
+.Fa "krb5_keyusage usage"
+.Fa "const krb5_data *data"
+.Fa "const krb5_checksum *cksum"
+.Fa "krb5_boolean *valid"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_c_checksum_length
+.Fa "krb5_context context"
+.Fa "krb5_cksumtype cksumtype"
+.Fa "size_t *length"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_c_get_checksum
+.Fa "krb5_context context"
+.Fa "const krb5_checksum *cksum"
+.Fa "krb5_cksumtype *type"
+.Fa "krb5_data **data"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_c_set_checksum
+.Fa "krb5_context context"
+.Fa "krb5_checksum *cksum"
+.Fa "krb5_cksumtype type"
+.Fa "const krb5_data *data"
+.Fc
+.Ft krb5_boolean
+.Fo krb5_c_valid_enctype
+.Fa krb5_enctype etype"
+.Fc
+.Ft krb5_boolean
+.Fo krb5_c_valid_cksumtype
+.Fa "krb5_cksumtype ctype"
+.Fc
+.Ft krb5_boolean
+.Fo krb5_c_is_coll_proof_cksum
+.Fa "krb5_cksumtype ctype"
+.Fc
+.Ft krb5_boolean
+.Fo krb5_c_is_keyed_cksum
+.Fa "krb5_cksumtype ctype"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_c_keylengths
+.Fa "krb5_context context"
+.Fa "krb5_enctype enctype"
+.Fa "size_t *inlength"
+.Fa "size_t *keylength"
+.Fc
+.Sh DESCRIPTION
+The functions starting with krb5_c are compat functions with MIT kerberos.
+.Pp
+The
+.Li krb5_enc_data
+structure holds and encrypted data.
+There are two public accessible members of
+.Li krb5_enc_data .
+.Li enctype
+that holds the encryption type of the data encrypted and
+.Li ciphertext
+that is a
+.Ft krb5_data
+that might contain the encrypted data.
+.Pp
+.Fn krb5_c_block_size
+returns the blocksize of the encryption type.
+.Pp
+.Fn krb5_c_decrypt
+decrypts
+.Fa input
+and store the data in
+.Fa output.
+If
+.Fa ivec
+is
+.Dv NULL
+the default initialization vector for that encryption type will be used.
+.Pp
+.Fn krb5_c_encrypt
+encrypts the plaintext in
+.Fa input
+and store the ciphertext in
+.Fa output .
+.Pp
+.Fn krb5_c_encrypt_length
+returns the length the encrypted data given the plaintext length.
+.Pp
+.Fn krb5_c_enctype_compare
+compares to encryption types and returns if they use compatible
+encryption key types.
+.Pp
+.Fn krb5_c_make_checksum
+creates a checksum
+.Fa cksum
+with the checksum type
+.Fa cksumtype
+of the data in
+.Fa data .
+.Fa key
+and
+.Fa usage
+are used if the checksum is a keyed checksum type.
+Returns 0 or an error code.
+.Pp
+.Fn krb5_c_verify_checksum
+verifies the checksum
+of
+.Fa data
+in
+.Fa cksum
+that was created with
+.Fa key
+using the key usage
+.Fa usage .
+.Fa verify
+is set to non-zero if the checksum verifies correctly and zero if not.
+Returns 0 or an error code.
+.Pp
+.Fn krb5_c_checksum_length
+returns the length of the checksum.
+.Pp
+.Fn krb5_c_set_checksum
+sets the
+.Li krb5_checksum
+structure given
+.Fa type
+and
+.Fa data .
+The content of
+.Fa cksum
+should be freeed with
+.Fn krb5_c_free_checksum_contents .
+.Pp
+.Fn krb5_c_get_checksum
+retrieves the components of the
+.Li krb5_checksum .
+structure.
+.Fa data
+should be free with
+.Fn krb5_free_data .
+If some either of
+.Fa data
+or
+.Fa checksum
+is not needed for the application,
+.Dv NULL
+can be passed in.
+.Pp
+.Fn krb5_c_valid_enctype
+returns true if
+.Fa etype
+is a valid encryption type.
+.Pp
+.Fn krb5_c_valid_cksumtype
+returns true if
+.Fa ctype
+is a valid checksum type.
+.Pp
+.Fn krb5_c_is_keyed_cksum
+return true if
+.Fa ctype
+is a keyed checksum type.
+.Pp
+.Fn krb5_c_is_coll_proof_cksum
+returns true if
+.Fa ctype
+is a collision proof checksum type.
+.Pp
+.Fn krb5_c_keylengths
+return the minimum length
+.Fa ( inlength )
+bytes needed to create a key and the
+length
+.Fa ( keylength )
+of the resulting key
+for the
+.Fa enctype .
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5_create_checksum 3 ,
+.Xr krb5_free_data 3 ,
+.Xr kerberos 8
diff --git a/third_party/heimdal/lib/krb5/krb5_ccapi.h b/third_party/heimdal/lib/krb5/krb5_ccapi.h
new file mode 100644
index 0000000..ed7b848
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_ccapi.h
@@ -0,0 +1,239 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef KRB5_CCAPI_H
+#define KRB5_CCAPI_H 1
+
+#include <krb5-types.h>
+
+#if defined(__APPLE__) && (defined(__ppc__) || defined(__ppc64__) || defined(__i386__) || defined(__x86_64__))
+#pragma pack(push,2)
+#endif
+
+enum {
+ cc_credentials_v5 = 2
+};
+
+enum {
+ ccapi_version_3 = 3,
+ ccapi_version_4 = 4
+};
+
+enum {
+ ccNoError = 0,
+
+ ccIteratorEnd = 201,
+ ccErrBadParam,
+ ccErrNoMem,
+ ccErrInvalidContext,
+ ccErrInvalidCCache,
+
+ ccErrInvalidString, /* 206 */
+ ccErrInvalidCredentials,
+ ccErrInvalidCCacheIterator,
+ ccErrInvalidCredentialsIterator,
+ ccErrInvalidLock,
+
+ ccErrBadName, /* 211 */
+ ccErrBadCredentialsVersion,
+ ccErrBadAPIVersion,
+ ccErrContextLocked,
+ ccErrContextUnlocked,
+
+ ccErrCCacheLocked, /* 216 */
+ ccErrCCacheUnlocked,
+ ccErrBadLockType,
+ ccErrNeverDefault,
+ ccErrCredentialsNotFound,
+
+ ccErrCCacheNotFound, /* 221 */
+ ccErrContextNotFound,
+ ccErrServerUnavailable,
+ ccErrServerInsecure,
+ ccErrServerCantBecomeUID,
+
+ ccErrTimeOffsetNotSet /* 226 */
+};
+
+typedef int32_t cc_int32;
+typedef uint32_t cc_uint32;
+typedef struct cc_context_t *cc_context_t;
+typedef struct cc_ccache_t *cc_ccache_t;
+typedef struct cc_ccache_iterator_t *cc_ccache_iterator_t;
+typedef struct cc_credentials_v5_t cc_credentials_v5_t;
+typedef struct cc_credentials_t *cc_credentials_t;
+typedef struct cc_credentials_iterator_t *cc_credentials_iterator_t;
+typedef struct cc_string_t *cc_string_t;
+typedef cc_uint32 cc_time_t;
+
+typedef struct cc_data {
+ cc_uint32 type;
+ cc_uint32 length;
+ void *data;
+} cc_data;
+
+struct cc_credentials_v5_t {
+ char *client;
+ char *server;
+ cc_data keyblock;
+ cc_time_t authtime;
+ cc_time_t starttime;
+ cc_time_t endtime;
+ cc_time_t renew_till;
+ cc_uint32 is_skey;
+ cc_uint32 ticket_flags;
+#define KRB5_CCAPI_TKT_FLG_FORWARDABLE 0x40000000
+#define KRB5_CCAPI_TKT_FLG_FORWARDED 0x20000000
+#define KRB5_CCAPI_TKT_FLG_PROXIABLE 0x10000000
+#define KRB5_CCAPI_TKT_FLG_PROXY 0x08000000
+#define KRB5_CCAPI_TKT_FLG_MAY_POSTDATE 0x04000000
+#define KRB5_CCAPI_TKT_FLG_POSTDATED 0x02000000
+#define KRB5_CCAPI_TKT_FLG_INVALID 0x01000000
+#define KRB5_CCAPI_TKT_FLG_RENEWABLE 0x00800000
+#define KRB5_CCAPI_TKT_FLG_INITIAL 0x00400000
+#define KRB5_CCAPI_TKT_FLG_PRE_AUTH 0x00200000
+#define KRB5_CCAPI_TKT_FLG_HW_AUTH 0x00100000
+#define KRB5_CCAPI_TKT_FLG_TRANSIT_POLICY_CHECKED 0x00080000
+#define KRB5_CCAPI_TKT_FLG_OK_AS_DELEGATE 0x00040000
+#define KRB5_CCAPI_TKT_FLG_ANONYMOUS 0x00020000
+ cc_data **addresses;
+ cc_data ticket;
+ cc_data second_ticket;
+ cc_data **authdata;
+};
+
+
+typedef struct cc_string_functions {
+ cc_int32 (*release)(cc_string_t);
+} cc_string_functions;
+
+struct cc_string_t {
+ const char *data;
+ const cc_string_functions *func;
+};
+
+typedef struct cc_credentials_union {
+ cc_int32 version;
+ union {
+ cc_credentials_v5_t* credentials_v5;
+ } credentials;
+} cc_credentials_union;
+
+struct cc_credentials_functions {
+ cc_int32 (*release)(cc_credentials_t);
+ cc_int32 (*compare)(cc_credentials_t, cc_credentials_t, cc_uint32*);
+};
+
+struct cc_credentials_t {
+ const cc_credentials_union* data;
+ const struct cc_credentials_functions* func;
+};
+
+struct cc_credentials_iterator_functions {
+ cc_int32 (*release)(cc_credentials_iterator_t);
+ cc_int32 (*next)(cc_credentials_iterator_t, cc_credentials_t*);
+};
+
+struct cc_credentials_iterator_t {
+ const struct cc_credentials_iterator_functions *func;
+};
+
+struct cc_ccache_iterator_functions {
+ cc_int32 (*release) (cc_ccache_iterator_t);
+ cc_int32 (*next)(cc_ccache_iterator_t, cc_ccache_t*);
+};
+
+struct cc_ccache_iterator_t {
+ const struct cc_ccache_iterator_functions* func;
+};
+
+typedef struct cc_ccache_functions {
+ cc_int32 (*release)(cc_ccache_t);
+ cc_int32 (*destroy)(cc_ccache_t);
+ cc_int32 (*set_default)(cc_ccache_t);
+ cc_int32 (*get_credentials_version)(cc_ccache_t, cc_uint32*);
+ cc_int32 (*get_name)(cc_ccache_t, cc_string_t*);
+ cc_int32 (*get_principal)(cc_ccache_t, cc_uint32, cc_string_t*);
+ cc_int32 (*set_principal)(cc_ccache_t, cc_uint32, const char*);
+ cc_int32 (*store_credentials)(cc_ccache_t, const cc_credentials_union*);
+ cc_int32 (*remove_credentials)(cc_ccache_t, cc_credentials_t);
+ cc_int32 (*new_credentials_iterator)(cc_ccache_t,
+ cc_credentials_iterator_t*);
+ cc_int32 (*move)(cc_ccache_t, cc_ccache_t);
+ cc_int32 (*lock)(cc_ccache_t, cc_uint32, cc_uint32);
+ cc_int32 (*unlock)(cc_ccache_t);
+ cc_int32 (*get_last_default_time)(cc_ccache_t, cc_time_t*);
+ cc_int32 (*get_change_time)(cc_ccache_t, cc_time_t*);
+ cc_int32 (*compare)(cc_ccache_t, cc_ccache_t, cc_uint32*);
+ cc_int32 (*get_kdc_time_offset)(cc_ccache_t, cc_int32, cc_time_t *);
+ cc_int32 (*set_kdc_time_offset)(cc_ccache_t, cc_int32, cc_time_t);
+ cc_int32 (*clear_kdc_time_offset)(cc_ccache_t, cc_int32);
+} cc_ccache_functions;
+
+struct cc_ccache_t {
+ const cc_ccache_functions *func;
+};
+
+struct cc_context_functions {
+ cc_int32 (*release)(cc_context_t);
+ cc_int32 (*get_change_time)(cc_context_t, cc_time_t *);
+ cc_int32 (*get_default_ccache_name)(cc_context_t, cc_string_t*);
+ cc_int32 (*open_ccache)(cc_context_t, const char*, cc_ccache_t *);
+ cc_int32 (*open_default_ccache)(cc_context_t, cc_ccache_t*);
+ cc_int32 (*create_ccache)(cc_context_t,const char*, cc_uint32,
+ const char*, cc_ccache_t*);
+ cc_int32 (*create_default_ccache)(cc_context_t, cc_uint32,
+ const char*, cc_ccache_t*);
+ cc_int32 (*create_new_ccache)(cc_context_t, cc_uint32,
+ const char*, cc_ccache_t*);
+ cc_int32 (*new_ccache_iterator)(cc_context_t, cc_ccache_iterator_t*);
+ cc_int32 (*lock)(cc_context_t, cc_uint32, cc_uint32);
+ cc_int32 (*unlock)(cc_context_t);
+ cc_int32 (*compare)(cc_context_t, cc_context_t, cc_uint32*);
+};
+
+struct cc_context_t {
+ const struct cc_context_functions* func;
+};
+
+typedef cc_int32
+(*cc_initialize_func)(cc_context_t*, cc_int32, cc_int32 *, char const **);
+
+#if defined(__APPLE__) && (defined(__ppc__) || defined(__ppc64__) || defined(__i386__) || defined(__x86_64__))
+#pragma pack(pop)
+#endif
+
+
+#endif /* KRB5_CCAPI_H */
diff --git a/third_party/heimdal/lib/krb5/krb5_check_transited.3 b/third_party/heimdal/lib/krb5/krb5_check_transited.3
new file mode 100644
index 0000000..4d4dae3
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_check_transited.3
@@ -0,0 +1,106 @@
+.\" Copyright (c) 2004, 2006 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 1, 2006
+.Dt KRB5_CHECK_TRANSITED 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_check_transited ,
+.Nm krb5_check_transited_realms ,
+.Nm krb5_domain_x500_decode ,
+.Nm krb5_domain_x500_encode
+.Nd realm transit verification and encoding/decoding functions
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fo krb5_check_transited
+.Fa "krb5_context context"
+.Fa "krb5_const_realm client_realm"
+.Fa "krb5_const_realm server_realm"
+.Fa "krb5_realm *realms"
+.Fa "int num_realms"
+.Fa "int *bad_realm"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_check_transited_realms
+.Fa "krb5_context context"
+.Fa "const char *const *realms"
+.Fa "int num_realms"
+.Fa "int *bad_realm"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_domain_x500_decode
+.Fa "krb5_context context"
+.Fa "krb5_data tr"
+.Fa "char ***realms"
+.Fa "int *num_realms"
+.Fa "const char *client_realm"
+.Fa "const char *server_realm"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_domain_x500_encode
+.Fa "char **realms"
+.Fa "int num_realms"
+.Fa "krb5_data *encoding"
+.Fc
+.Sh DESCRIPTION
+.Fn krb5_check_transited
+checks the path from
+.Fa client_realm
+to
+.Fa server_realm
+where
+.Fa realms
+and
+.Fa num_realms
+is the realms between them.
+If the function returns an error value,
+.Fa bad_realm
+will be set to the realm in the list causing the error.
+.Fn krb5_check_transited
+is used internally by the KDC and libkrb5 and should not be called by
+client applications.
+.Pp
+.Fn krb5_check_transited_realms
+is deprecated.
+.Pp
+.Fn krb5_domain_x500_encode
+and
+.Fn krb5_domain_x500_decode
+encodes and decodes the realm names in the X500 format that Kerberos
+uses to describe the transited realms in krbtgts.
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5.conf 5
diff --git a/third_party/heimdal/lib/krb5/krb5_create_checksum.3 b/third_party/heimdal/lib/krb5/krb5_create_checksum.3
new file mode 100644
index 0000000..06d806e
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_create_checksum.3
@@ -0,0 +1,226 @@
+.\" Copyright (c) 1999-2005 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd August 12, 2005
+.Dt NAME 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_checksum ,
+.Nm krb5_checksum_disable ,
+.Nm krb5_checksum_is_collision_proof ,
+.Nm krb5_checksum_is_keyed ,
+.Nm krb5_checksumsize ,
+.Nm krb5_cksumtype_valid ,
+.Nm krb5_copy_checksum ,
+.Nm krb5_create_checksum ,
+.Nm krb5_crypto_get_checksum_type
+.Nm krb5_free_checksum ,
+.Nm krb5_free_checksum_contents ,
+.Nm krb5_hmac ,
+.Nm krb5_verify_checksum
+.Nd creates, handles and verifies checksums
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Pp
+.Li "typedef Checksum krb5_checksum;"
+.Ft void
+.Fo krb5_checksum_disable
+.Fa "krb5_context context"
+.Fa "krb5_cksumtype type"
+.Fc
+.Ft krb5_boolean
+.Fo krb5_checksum_is_collision_proof
+.Fa "krb5_context context"
+.Fa "krb5_cksumtype type"
+.Fc
+.Ft krb5_boolean
+.Fo krb5_checksum_is_keyed
+.Fa "krb5_context context"
+.Fa "krb5_cksumtype type"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_cksumtype_valid
+.Fa "krb5_context context"
+.Fa "krb5_cksumtype ctype"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_checksumsize
+.Fa "krb5_context context"
+.Fa "krb5_cksumtype type"
+.Fa "size_t *size"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_create_checksum
+.Fa "krb5_context context"
+.Fa "krb5_crypto crypto"
+.Fa "krb5_key_usage usage"
+.Fa "int type"
+.Fa "void *data"
+.Fa "size_t len"
+.Fa "Checksum *result"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_verify_checksum
+.Fa "krb5_context context"
+.Fa "krb5_crypto crypto"
+.Fa "krb5_key_usage usage"
+.Fa "void *data"
+.Fa "size_t len"
+.Fa "Checksum *cksum"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_crypto_get_checksum_type
+.Fa "krb5_context context"
+.Fa "krb5_crypto crypto"
+.Fa "krb5_cksumtype *type"
+.Fc
+.Ft void
+.Fo krb5_free_checksum
+.Fa "krb5_context context"
+.Fa "krb5_checksum *cksum"
+.Fc
+.Ft void
+.Fo krb5_free_checksum_contents
+.Fa "krb5_context context"
+.Fa "krb5_checksum *cksum"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_hmac
+.Fa "krb5_context context"
+.Fa "krb5_cksumtype cktype"
+.Fa "const void *data"
+.Fa "size_t len"
+.Fa "unsigned usage"
+.Fa "krb5_keyblock *key"
+.Fa "Checksum *result"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_copy_checksum
+.Fa "krb5_context context"
+.Fa "const krb5_checksum *old"
+.Fa "krb5_checksum **new"
+.Fc
+.Sh DESCRIPTION
+The
+.Li krb5_checksum
+structure holds a Kerberos checksum.
+There is no component inside
+.Li krb5_checksum
+that is directly referable.
+.Pp
+The functions are used to create and verify checksums.
+.Fn krb5_create_checksum
+creates a checksum of the specified data, and puts it in
+.Fa result .
+If
+.Fa crypto
+is
+.Dv NULL ,
+.Fa usage_or_type
+specifies the checksum type to use; it must not be keyed. Otherwise
+.Fa crypto
+is an encryption context created by
+.Fn krb5_crypto_init ,
+and
+.Fa usage_or_type
+specifies a key-usage.
+.Pp
+.Fn krb5_verify_checksum
+verifies the
+.Fa checksum
+against the provided data.
+.Pp
+.Fn krb5_checksum_is_collision_proof
+returns true is the specified checksum is collision proof (that it's
+very unlikely that two strings has the same hash value, and that it's
+hard to find two strings that has the same hash). Examples of
+collision proof checksums are MD5, and SHA1, while CRC32 is not.
+.Pp
+.Fn krb5_checksum_is_keyed
+returns true if the specified checksum type is keyed (that the hash
+value is a function of both the data, and a separate key). Examples of
+keyed hash algorithms are HMAC-SHA1-DES3, and RSA-MD5-DES. The
+.Dq plain
+hash functions MD5, and SHA1 are not keyed.
+.Pp
+.Fn krb5_crypto_get_checksum_type
+returns the checksum type that will be used when creating a checksum for the given
+.Fa crypto
+context.
+This function is useful in combination with
+.Fn krb5_checksumsize
+when you want to know the size a checksum will
+use when you create it.
+.Pp
+.Fn krb5_cksumtype_valid
+returns 0 or an error if the checksumtype is implemented and not
+currently disabled in this kerberos library.
+.Pp
+.Fn krb5_checksumsize
+returns the size of the outdata of checksum function.
+.Pp
+.Fn krb5_copy_checksum
+returns a copy of the checksum
+.Fn krb5_free_checksum
+should use used to free the
+.Fa new
+checksum.
+.Pp
+.Fn krb5_free_checksum
+free the checksum and the content of the checksum.
+.Pp
+.Fn krb5_free_checksum_contents
+frees the content of checksum in
+.Fa cksum .
+.Pp
+.Fn krb5_hmac
+calculates the HMAC over
+.Fa data
+(with length
+.Fa len )
+using the keyusage
+.Fa usage
+and keyblock
+.Fa key .
+Note that keyusage is not always used in checksums.
+.Pp
+.Nm krb5_checksum_disable
+globally disables the checksum type.
+.\" .Sh EXAMPLE
+.\" .Sh BUGS
+.Sh SEE ALSO
+.Xr krb5_crypto_init 3 ,
+.Xr krb5_c_encrypt 3 ,
+.Xr krb5_encrypt 3
diff --git a/third_party/heimdal/lib/krb5/krb5_creds.3 b/third_party/heimdal/lib/krb5/krb5_creds.3
new file mode 100644
index 0000000..b22550e
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_creds.3
@@ -0,0 +1,119 @@
+.\" Copyright (c) 2004, 2006 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 1, 2006
+.Dt KRB5_CREDS 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_creds ,
+.Nm krb5_copy_creds ,
+.Nm krb5_copy_creds_contents ,
+.Nm krb5_free_creds ,
+.Nm krb5_free_cred_contents
+.Nd Kerberos 5 credential handling functions
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fo krb5_copy_creds
+.Fa "krb5_context context"
+.Fa "const krb5_creds *incred"
+.Fa "krb5_creds **outcred"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_copy_creds_contents
+.Fa "krb5_context context"
+.Fa "const krb5_creds *incred"
+.Fa "krb5_creds *outcred"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_free_creds
+.Fa "krb5_context context"
+.Fa "krb5_creds *outcred"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_free_cred_contents
+.Fa "krb5_context context"
+.Fa "krb5_creds *cred"
+.Fc
+.Sh DESCRIPTION
+.Vt krb5_creds
+holds Kerberos credentials:
+.Bd -literal -offset
+typedef struct krb5_creds {
+ krb5_principal client;
+ krb5_principal server;
+ krb5_keyblock session;
+ krb5_times times;
+ krb5_data ticket;
+ krb5_data second_ticket;
+ krb5_authdata authdata;
+ krb5_addresses addresses;
+ krb5_ticket_flags flags;
+} krb5_creds;
+.Ed
+.Pp
+.Fn krb5_copy_creds
+makes a copy of
+.Fa incred
+to
+.Fa outcred .
+.Fa outcred
+should be freed with
+.Fn krb5_free_creds
+by the caller.
+.Pp
+.Fn krb5_copy_creds_contents
+makes a copy of the content of
+.Fa incred
+to
+.Fa outcreds .
+.Fa outcreds
+should be freed by the called with
+.Fn krb5_free_creds_contents .
+.Pp
+.Fn krb5_free_creds
+frees the content of the
+.Fa cred
+structure and the structure itself.
+.Pp
+.Fn krb5_free_cred_contents
+frees the content of the
+.Fa cred
+structure.
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5_compare_creds 3 ,
+.Xr krb5_get_init_creds 3 ,
+.Xr kerberos 8
diff --git a/third_party/heimdal/lib/krb5/krb5_digest.3 b/third_party/heimdal/lib/krb5/krb5_digest.3
new file mode 100644
index 0000000..11d4db4
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_digest.3
@@ -0,0 +1,260 @@
+.\" Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd February 18, 2007
+.Dt KRB5_DIGEST 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_digest ,
+.Nm krb5_digest_alloc ,
+.Nm krb5_digest_free ,
+.Nm krb5_digest_set_server_cb ,
+.Nm krb5_digest_set_type ,
+.Nm krb5_digest_set_hostname ,
+.Nm krb5_digest_get_server_nonce ,
+.Nm krb5_digest_set_server_nonce ,
+.Nm krb5_digest_get_opaque ,
+.Nm krb5_digest_set_opaque ,
+.Nm krb5_digest_get_identifier ,
+.Nm krb5_digest_set_identifier ,
+.Nm krb5_digest_init_request ,
+.Nm krb5_digest_set_client_nonce ,
+.Nm krb5_digest_set_digest ,
+.Nm krb5_digest_set_username ,
+.Nm krb5_digest_set_authid ,
+.Nm krb5_digest_set_authentication_user ,
+.Nm krb5_digest_set_realm ,
+.Nm krb5_digest_set_method ,
+.Nm krb5_digest_set_uri ,
+.Nm krb5_digest_set_nonceCount ,
+.Nm krb5_digest_set_qop ,
+.Nm krb5_digest_request ,
+.Nm krb5_digest_get_responseData ,
+.Nm krb5_digest_get_rsp ,
+.Nm krb5_digest_get_tickets ,
+.Nm krb5_digest_get_client_binding ,
+.Nm krb5_digest_get_a1_hash
+.Nd remote digest (HTTP-DIGEST, SASL, CHAP) support
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Pp
+.Li "typedef struct krb5_digest *krb5_digest;"
+.Pp
+.Ft krb5_error_code
+.Fo krb5_digest_alloc
+.Fa "krb5_context context"
+.Fa "krb5_digest *digest"
+.Fc
+.Ft void
+.Fo krb5_digest_free
+.Fa "krb5_digest digest"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_type
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *type"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_server_cb
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *type"
+.Fa "const char *binding"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_hostname
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *hostname"
+.Fc
+.Ft "const char *"
+.Fo krb5_digest_get_server_nonce
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_server_nonce
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *nonce"
+.Fc
+.Ft "const char *"
+.Fo krb5_digest_get_opaque
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_opaque
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *opaque"
+.Fc
+.Ft "const char *"
+.Fo krb5_digest_get_identifier
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_identifier
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *id"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_init_request
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "krb5_realm realm"
+.Fa "krb5_ccache ccache"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_client_nonce
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *nonce"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_digest
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *dgst"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_username
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *username"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_authid
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *authid"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_authentication_user
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "krb5_principal authentication_user"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_realm
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *realm"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_method
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *method"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_uri
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *uri"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_nonceCount
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *nonce_count"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_set_qop
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "const char *qop"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_request
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "krb5_realm realm"
+.Fa "krb5_ccache ccache"
+.Fc
+.Ft "const char *"
+.Fo krb5_digest_get_responseData
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fc
+.Ft "const char *"
+.Fo krb5_digest_get_rsp
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_get_tickets
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "Ticket **tickets"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_get_client_binding
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "char **type"
+.Fa "char **binding"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_digest_get_a1_hash
+.Fa "krb5_context context"
+.Fa "krb5_digest digest"
+.Fa "krb5_data *data"
+.Fc
+.Sh DESCRIPTION
+The
+.Fn krb5_digest_alloc
+function allocatates the
+.Fa digest
+structure. The structure should be freed with
+.Fn krb5_digest_free
+when it is no longer being used.
+.Pp
+.Fn krb5_digest_alloc
+returns 0 to indicate success.
+Otherwise an kerberos code is returned and the pointer that
+.Fa digest
+points to is set to
+.Dv NULL .
+.Pp
+.Fn krb5_digest_free
+free the structure
+.Fa digest .
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr kerberos 8
diff --git a/third_party/heimdal/lib/krb5/krb5_eai_to_heim_errno.3 b/third_party/heimdal/lib/krb5/krb5_eai_to_heim_errno.3
new file mode 100644
index 0000000..0c83a33
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_eai_to_heim_errno.3
@@ -0,0 +1,68 @@
+.\" Copyright (c) 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd April 13, 2004
+.Dt KRB5_EAI_TO_HEIM_ERRNO 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_eai_to_heim_errno ,
+.Nm krb5_h_errno_to_heim_errno
+.Nd convert resolver error code to com_err error codes
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fo krb5_eai_to_heim_errno
+.Fa "int eai_errno"
+.Fa "int system_error"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_h_errno_to_heim_errno
+.Fa "int eai_errno"
+.Fc
+.Sh DESCRIPTION
+.Fn krb5_eai_to_heim_errno
+and
+.Fn krb5_h_errno_to_heim_errno
+convert
+.Xr getaddrinfo 3 ,
+.Xr getnameinfo 3 ,
+and
+.Xr h_errno 3
+to com_err error code that are used by Heimdal, this is useful for for
+function returning kerberos errors and needs to communicate failures
+from resolver function.
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr kerberos 8
diff --git a/third_party/heimdal/lib/krb5/krb5_encrypt.3 b/third_party/heimdal/lib/krb5/krb5_encrypt.3
new file mode 100644
index 0000000..2b1f587
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_encrypt.3
@@ -0,0 +1,278 @@
+.\" Copyright (c) 1999 - 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd March 20, 2004
+.Dt KRB5_ENCRYPT 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_crypto_getblocksize ,
+.Nm krb5_crypto_getconfoundersize
+.Nm krb5_crypto_getenctype ,
+.Nm krb5_crypto_getpadsize ,
+.Nm krb5_crypto_overhead ,
+.Nm krb5_decrypt ,
+.Nm krb5_decrypt_EncryptedData ,
+.Nm krb5_decrypt_ivec ,
+.Nm krb5_decrypt_ticket ,
+.Nm krb5_encrypt ,
+.Nm krb5_encrypt_EncryptedData ,
+.Nm krb5_encrypt_ivec ,
+.Nm krb5_enctype_disable ,
+.Nm krb5_enctype_keysize ,
+.Nm krb5_enctype_to_string ,
+.Nm krb5_enctype_valid ,
+.Nm krb5_get_wrapped_length ,
+.Nm krb5_string_to_enctype
+.Nd "encrypt and decrypt data, set and get encryption type parameters"
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fo krb5_encrypt
+.Fa "krb5_context context"
+.Fa "krb5_crypto crypto"
+.Fa "unsigned usage"
+.Fa "void *data"
+.Fa "size_t len"
+.Fa "krb5_data *result"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_encrypt_EncryptedData
+.Fa "krb5_context context"
+.Fa "krb5_crypto crypto"
+.Fa "unsigned usage"
+.Fa "void *data"
+.Fa "size_t len"
+.Fa "int kvno"
+.Fa "EncryptedData *result"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_encrypt_ivec
+.Fa "krb5_context context"
+.Fa "krb5_crypto crypto"
+.Fa "unsigned usage"
+.Fa "void *data"
+.Fa "size_t len"
+.Fa "krb5_data *result"
+.Fa "void *ivec"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_decrypt
+.Fa "krb5_context context"
+.Fa "krb5_crypto crypto"
+.Fa "unsigned usage"
+.Fa "void *data"
+.Fa "size_t len"
+.Fa "krb5_data *result"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_decrypt_EncryptedData
+.Fa "krb5_context context"
+.Fa "krb5_crypto crypto"
+.Fa "unsigned usage"
+.Fa "EncryptedData *e"
+.Fa "krb5_data *result"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_decrypt_ivec
+.Fa "krb5_context context"
+.Fa "krb5_crypto crypto"
+.Fa "unsigned usage"
+.Fa "void *data"
+.Fa "size_t len"
+.Fa "krb5_data *result"
+.Fa "void *ivec"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_decrypt_ticket
+.Fa "krb5_context context"
+.Fa "Ticket *ticket"
+.Fa "krb5_keyblock *key"
+.Fa "EncTicketPart *out"
+.Fa "krb5_flags flags"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_crypto_getblocksize
+.Fa "krb5_context context"
+.Fa "size_t *blocksize"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_crypto_getenctype
+.Fa "krb5_context context"
+.Fa "krb5_crypto crypto"
+.Fa "krb5_enctype *enctype"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_crypto_getpadsize
+.Fa "krb5_context context"
+.Fa size_t *padsize"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_crypto_getconfoundersize
+.Fa "krb5_context context"
+.Fa "krb5_crypto crypto"
+.Fa size_t *confoundersize"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_enctype_keysize
+.Fa "krb5_context context"
+.Fa "krb5_enctype type"
+.Fa "size_t *keysize"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_crypto_overhead
+.Fa "krb5_context context"
+.Fa size_t *padsize"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_string_to_enctype
+.Fa "krb5_context context"
+.Fa "const char *string"
+.Fa "krb5_enctype *etype"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_enctype_to_string
+.Fa "krb5_context context"
+.Fa "krb5_enctype etype"
+.Fa "char **string"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_enctype_valid
+.Fa "krb5_context context"
+.Fa "krb5_enctype etype"
+.Fc
+.Ft void
+.Fo krb5_enctype_disable
+.Fa "krb5_context context"
+.Fa "krb5_enctype etype"
+.Fc
+.Ft size_t
+.Fo krb5_get_wrapped_length
+.Fa "krb5_context context"
+.Fa "krb5_crypto crypto"
+.Fa "size_t data_len"
+.Fc
+.Sh DESCRIPTION
+These functions are used to encrypt and decrypt data.
+.Pp
+.Fn krb5_encrypt_ivec
+puts the encrypted version of
+.Fa data
+(of size
+.Fa len )
+in
+.Fa result .
+If the encryption type supports using derived keys,
+.Fa usage
+should be the appropriate key-usage.
+.Fa ivec
+is a pointer to a initial IV, it is modified to the end IV at the end of
+the round.
+Ivec should be the size of
+If
+.Dv NULL
+is passed in, the default IV is used.
+.Fn krb5_encrypt
+does the same as
+.Fn krb5_encrypt_ivec
+but with
+.Fa ivec
+being
+.Dv NULL .
+.Fn krb5_encrypt_EncryptedData
+does the same as
+.Fn krb5_encrypt ,
+but it puts the encrypted data in a
+.Fa EncryptedData
+structure instead. If
+.Fa kvno
+is not zero, it will be put in the (optional)
+.Fa kvno
+field in the
+.Fa EncryptedData .
+.Pp
+.Fn krb5_decrypt_ivec ,
+.Fn krb5_decrypt ,
+and
+.Fn krb5_decrypt_EncryptedData
+works similarly.
+.Pp
+.Fn krb5_decrypt_ticket
+decrypts the encrypted part of
+.Fa ticket
+with
+.Fa key .
+.Fn krb5_decrypt_ticket
+also verifies the timestamp in the ticket, invalid flag and if the KDC
+haven't verified the transited path, the transit path.
+.Pp
+.Fn krb5_enctype_keysize ,
+.Fn krb5_crypto_getconfoundersize ,
+.Fn krb5_crypto_getblocksize ,
+.Fn krb5_crypto_getenctype ,
+.Fn krb5_crypto_getpadsize ,
+.Fn krb5_crypto_overhead
+all returns various (sometimes) useful information from a crypto context.
+.Fn krb5_crypto_overhead
+is the combination of krb5_crypto_getconfoundersize,
+krb5_crypto_getblocksize and krb5_crypto_getpadsize and return the
+maximum overhead size.
+.Pp
+.Fn krb5_enctype_to_string
+converts a encryption type number to a string that can be printable
+and stored. The strings returned should be freed with
+.Xr free 3 .
+.Pp
+.Fn krb5_string_to_enctype
+converts a encryption type strings to a encryption type number that
+can use used for other Kerberos crypto functions.
+.Pp
+.Fn krb5_enctype_valid
+returns 0 if the encrypt is supported and not disabled, otherwise and
+error code is returned.
+.Pp
+.Fn krb5_enctype_disable
+(globally, for all contextes) disables the
+.Fa enctype .
+.Pp
+.Fn krb5_get_wrapped_length
+returns the size of an encrypted packet by
+.Fa crypto
+of length
+.Fa data_len .
+.\" .Sh EXAMPLE
+.\" .Sh BUGS
+.Sh SEE ALSO
+.Xr krb5_create_checksum 3 ,
+.Xr krb5_crypto_init 3
diff --git a/third_party/heimdal/lib/krb5/krb5_err.et b/third_party/heimdal/lib/krb5/krb5_err.et
new file mode 100644
index 0000000..1a64c14
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_err.et
@@ -0,0 +1,314 @@
+#
+# Error messages for the krb5 library
+#
+# This might look like a com_err file, but is not
+#
+# Do try to keep this in sync with MIT's.
+#
+id "$Id$"
+
+error_table krb5
+
+prefix KRB5KDC_ERR
+error_code NONE, "No error"
+error_code NAME_EXP, "Client's entry in database has expired"
+error_code SERVICE_EXP, "Server's entry in database has expired"
+error_code BAD_PVNO, "Requested protocol version not supported"
+error_code C_OLD_MAST_KVNO, "Client's key is encrypted in an old master key"
+error_code S_OLD_MAST_KVNO, "Server's key is encrypted in an old master key"
+error_code C_PRINCIPAL_UNKNOWN, "Client not found in Kerberos database"
+error_code S_PRINCIPAL_UNKNOWN, "Server not found in Kerberos database"
+error_code PRINCIPAL_NOT_UNIQUE,"Principal has multiple entries in Kerberos database"
+error_code NULL_KEY, "Client or server has a null key"
+error_code CANNOT_POSTDATE, "Ticket is ineligible for postdating"
+error_code NEVER_VALID, "Requested effective lifetime is negative or too short"
+error_code POLICY, "KDC policy rejects request"
+error_code BADOPTION, "KDC can't fulfill requested option"
+error_code ETYPE_NOSUPP, "KDC has no support for encryption type"
+error_code SUMTYPE_NOSUPP, "KDC has no support for checksum type"
+error_code PADATA_TYPE_NOSUPP, "KDC has no support for padata type"
+error_code TRTYPE_NOSUPP, "KDC has no support for transited type"
+error_code CLIENT_REVOKED, "Clients credentials have been revoked"
+error_code SERVICE_REVOKED, "Credentials for server have been revoked"
+error_code TGT_REVOKED, "TGT has been revoked"
+error_code CLIENT_NOTYET, "Client not yet valid - try again later"
+error_code SERVICE_NOTYET, "Server not yet valid - try again later"
+error_code KEY_EXPIRED, "Password has expired"
+error_code PREAUTH_FAILED, "Preauthentication failed"
+error_code PREAUTH_REQUIRED, "Additional pre-authentication required"
+error_code SERVER_NOMATCH, "Requested server and ticket don't match"
+error_code KDC_ERR_MUST_USE_USER2USER, "Server principal valid for user2user only"
+error_code PATH_NOT_ACCEPTED, "KDC Policy rejects transited path"
+error_code SVC_UNAVAILABLE, "A service is not available"
+
+index 31
+prefix KRB5KRB_AP
+error_code ERR_BAD_INTEGRITY, "Decrypt integrity check failed"
+error_code ERR_TKT_EXPIRED, "Ticket expired"
+error_code ERR_TKT_NYV, "Ticket not yet valid"
+error_code ERR_REPEAT, "Request is a replay"
+error_code ERR_NOT_US, "The ticket isn't for us"
+error_code ERR_BADMATCH, "Ticket/authenticator don't match"
+error_code ERR_SKEW, "Clock skew too great"
+error_code ERR_BADADDR, "Incorrect net address"
+error_code ERR_BADVERSION, "Protocol version mismatch"
+error_code ERR_MSG_TYPE, "Invalid message type"
+error_code ERR_MODIFIED, "Message stream modified"
+error_code ERR_BADORDER, "Message out of order"
+error_code ERR_ILL_CR_TKT, "Invalid cross-realm ticket"
+error_code ERR_BADKEYVER, "Key version is not available"
+error_code ERR_NOKEY, "Service key not available"
+error_code ERR_MUT_FAIL, "Mutual authentication failed"
+error_code ERR_BADDIRECTION, "Incorrect message direction"
+error_code ERR_METHOD, "Alternative authentication method required"
+error_code ERR_BADSEQ, "Incorrect sequence number in message"
+error_code ERR_INAPP_CKSUM, "Inappropriate type of checksum in message"
+error_code PATH_NOT_ACCEPTED, "Policy rejects transited path"
+
+prefix KRB5KRB_ERR
+error_code RESPONSE_TOO_BIG, "Response too big for UDP, retry with TCP"
+# 53-59 are reserved
+index 60
+error_code GENERIC, "Generic error (see e-text)"
+error_code FIELD_TOOLONG, "Field is too long for this implementation"
+
+# pkinit
+index 62
+prefix KRB5_KDC_ERR
+error_code CLIENT_NOT_TRUSTED, "Client not trusted"
+error_code KDC_NOT_TRUSTED, "KDC not trusted"
+error_code INVALID_SIG, "Invalid signature"
+error_code DH_KEY_PARAMETERS_NOT_ACCEPTED, "DH parameters not accepted"
+
+index 68
+prefix KRB5_KDC_ERR
+error_code WRONG_REALM, "Wrong realm"
+
+index 69
+prefix KRB5_AP_ERR
+error_code USER_TO_USER_REQUIRED, "User to user required"
+
+index 70
+prefix KRB5_KDC_ERR
+error_code CANT_VERIFY_CERTIFICATE, "Cannot verify certificate"
+error_code INVALID_CERTIFICATE, "Certificate invalid"
+error_code REVOKED_CERTIFICATE, "Certificate revoked"
+error_code REVOCATION_STATUS_UNKNOWN, "Revocation status unknown"
+error_code REVOCATION_STATUS_UNAVAILABLE, "Revocation status unavailable"
+error_code CLIENT_NAME_MISMATCH, "Client name mismatch in certificate"
+error_code INCONSISTENT_KEY_PURPOSE, "Inconsistent key purpose"
+error_code DIGEST_IN_CERT_NOT_ACCEPTED, "Digest in certificate not accepted"
+error_code PA_CHECKSUM_MUST_BE_INCLUDED, "paChecksum must be included"
+error_code DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED, "Digest in signedData not accepted"
+error_code PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED, "Public key encryption not supported"
+
+## these are never used
+#index 85
+#prefix KRB5_IAKERB
+#error_code ERR_KDC_NOT_FOUND, "IAKERB proxy could not find a KDC"
+#error_code ERR_KDC_NO_RESPONSE, "IAKERB proxy never reeived a response from a KDC"
+
+index 91
+error_code MORE_PREAUTH_DATA_REQUIRED, "More pre-authentication data required"
+
+index 93
+error_code UNKNOWN_CRITICAL_FAST_OPTIONS, "Unknown critical FAST options"
+
+index 94
+error_code INVALID_HASH_ALG, "Invalid OTP digest algorithm"
+error_code INVALID_ITERATION_COUNT, "Invalid OTP iteration count"
+
+# 97-99 are reserved
+
+index 100
+error_code NO_ACCEPTABLE_KDF, "No acceptable KDF offered"
+
+# 101-127 are reserved
+
+index 128
+prefix
+error_code KRB5_ERR_RCSID, "$Id$"
+
+error_code KRB5_LIBOS_BADLOCKFLAG, "Invalid flag for file lock mode"
+error_code KRB5_LIBOS_CANTREADPWD, "Cannot read password"
+error_code KRB5_LIBOS_BADPWDMATCH, "Password mismatch"
+error_code KRB5_LIBOS_PWDINTR, "Password read interrupted"
+
+error_code KRB5_PARSE_ILLCHAR, "Invalid character in component name"
+error_code KRB5_PARSE_MALFORMED, "Malformed representation of principal"
+
+error_code KRB5_CONFIG_CANTOPEN, "Can't open/find configuration file"
+error_code KRB5_CONFIG_BADFORMAT, "Improper format of configuration file"
+error_code KRB5_CONFIG_NOTENUFSPACE, "Insufficient space to return complete information"
+
+error_code KRB5_BADMSGTYPE, "Invalid message type specified for encoding"
+
+error_code KRB5_CC_BADNAME, "Credential cache name malformed"
+error_code KRB5_CC_UNKNOWN_TYPE, "Unknown credential cache type"
+error_code KRB5_CC_NOTFOUND, "Matching credential not found"
+error_code KRB5_CC_END, "End of credential cache reached"
+
+error_code KRB5_NO_TKT_SUPPLIED, "Request did not supply a ticket"
+
+error_code KRB5KRB_AP_WRONG_PRINC, "Wrong principal in request"
+error_code KRB5KRB_AP_ERR_TKT_INVALID, "Ticket has invalid flag set"
+
+error_code KRB5_PRINC_NOMATCH, "Requested principal and ticket don't match"
+error_code KRB5_KDCREP_MODIFIED, "KDC reply did not match expectations"
+error_code KRB5_KDCREP_SKEW, "Clock skew too great in KDC reply"
+error_code KRB5_IN_TKT_REALM_MISMATCH, "Client/server realm mismatch in initial ticket request"
+
+error_code KRB5_PROG_ETYPE_NOSUPP, "Program lacks support for encryption type"
+error_code KRB5_PROG_KEYTYPE_NOSUPP, "Program lacks support for key type"
+error_code KRB5_WRONG_ETYPE, "Requested encryption type not used in message"
+error_code KRB5_PROG_SUMTYPE_NOSUPP, "Program lacks support for checksum type"
+
+error_code KRB5_REALM_UNKNOWN, "Cannot find KDC for requested realm"
+error_code KRB5_SERVICE_UNKNOWN, "Kerberos service unknown"
+error_code KRB5_KDC_UNREACH, "Cannot contact any KDC for requested realm"
+error_code KRB5_NO_LOCALNAME, "No local name found for principal name"
+
+error_code KRB5_MUTUAL_FAILED, "Mutual authentication failed"
+
+# some of these should be combined/supplanted by system codes
+
+error_code KRB5_RC_TYPE_EXISTS, "Replay cache type is already registered"
+error_code KRB5_RC_MALLOC, "No more memory to allocate (in replay cache code)"
+error_code KRB5_RC_TYPE_NOTFOUND, "Replay cache type is unknown"
+error_code KRB5_RC_UNKNOWN, "Generic unknown RC error"
+error_code KRB5_RC_REPLAY, "Message is a replay"
+error_code KRB5_RC_IO, "Replay I/O operation failed XXX"
+error_code KRB5_RC_NOIO, "Replay cache type does not support non-volatile storage"
+error_code KRB5_RC_PARSE, "Replay cache name parse/format error"
+
+error_code KRB5_RC_IO_EOF, "End-of-file on replay cache I/O"
+error_code KRB5_RC_IO_MALLOC, "No more memory to allocate (in replay cache I/O code)"
+error_code KRB5_RC_IO_PERM, "Permission denied in replay cache code"
+error_code KRB5_RC_IO_IO, "I/O error in replay cache i/o code"
+error_code KRB5_RC_IO_UNKNOWN, "Generic unknown RC/IO error"
+error_code KRB5_RC_IO_SPACE, "Insufficient system space to store replay information"
+
+error_code KRB5_TRANS_CANTOPEN, "Can't open/find realm translation file"
+error_code KRB5_TRANS_BADFORMAT, "Improper format of realm translation file"
+
+error_code KRB5_LNAME_CANTOPEN, "Can't open/find lname translation database"
+error_code KRB5_LNAME_NOTRANS, "No translation available for requested principal"
+error_code KRB5_LNAME_BADFORMAT, "Improper format of translation database entry"
+
+error_code KRB5_CRYPTO_INTERNAL, "Cryptosystem internal error"
+
+error_code KRB5_KT_BADNAME, "Key table name malformed"
+error_code KRB5_KT_UNKNOWN_TYPE, "Unknown Key table type"
+error_code KRB5_KT_NOTFOUND, "Key table entry not found"
+error_code KRB5_KT_END, "End of key table reached"
+error_code KRB5_KT_NOWRITE, "Cannot write to specified key table"
+error_code KRB5_KT_IOERR, "Error writing to key table"
+
+error_code KRB5_NO_TKT_IN_RLM, "Cannot find ticket for requested realm"
+error_code KRB5DES_BAD_KEYPAR, "DES key has bad parity"
+error_code KRB5DES_WEAK_KEY, "DES key is a weak key"
+
+error_code KRB5_BAD_ENCTYPE, "Bad encryption type"
+error_code KRB5_BAD_KEYSIZE, "Key size is incompatible with encryption type"
+error_code KRB5_BAD_MSIZE, "Message size is incompatible with encryption type"
+
+error_code KRB5_CC_TYPE_EXISTS, "Credentials cache type is already registered."
+error_code KRB5_KT_TYPE_EXISTS, "Key table type is already registered."
+
+error_code KRB5_CC_IO, "Credentials cache I/O operation failed XXX"
+error_code KRB5_FCC_PERM, "Credentials cache file permissions incorrect"
+error_code KRB5_FCC_NOFILE, "No credentials cache file found"
+error_code KRB5_FCC_INTERNAL, "Internal file credentials cache error"
+error_code KRB5_CC_WRITE, "Error writing to credentials cache file"
+error_code KRB5_CC_NOMEM, "No more memory to allocate (in credentials cache code)"
+error_code KRB5_CC_FORMAT, "Bad format in credentials cache"
+error_code KRB5_CC_NOT_KTYPE, "No credentials found with supported encryption types"
+
+# errors for dual tgt library calls
+error_code KRB5_INVALID_FLAGS, "Invalid KDC option combination (library internal error)"
+error_code KRB5_NO_2ND_TKT, "Request missing second ticket"
+
+error_code KRB5_NOCREDS_SUPPLIED, "No credentials supplied to library routine"
+
+# errors for sendauth (and recvauth)
+
+error_code KRB5_SENDAUTH_BADAUTHVERS, "Bad sendauth version was sent"
+error_code KRB5_SENDAUTH_BADAPPLVERS, "Bad application version was sent (via sendauth)"
+error_code KRB5_SENDAUTH_BADRESPONSE, "Bad response (during sendauth exchange)"
+error_code KRB5_SENDAUTH_REJECTED, "Server rejected authentication (during sendauth exchange)"
+
+# errors for preauthentication
+
+error_code KRB5_PREAUTH_BAD_TYPE, "Unsupported preauthentication type"
+error_code KRB5_PREAUTH_NO_KEY, "Required preauthentication key not supplied"
+error_code KRB5_PREAUTH_FAILED, "Generic preauthentication failure"
+
+# version number errors
+
+error_code KRB5_RCACHE_BADVNO, "Unsupported replay cache format version number"
+error_code KRB5_CCACHE_BADVNO, "Unsupported credentials cache format version number"
+error_code KRB5_KEYTAB_BADVNO, "Unsupported key table format version number"
+
+#
+#
+
+error_code KRB5_PROG_ATYPE_NOSUPP, "Program lacks support for address type"
+error_code KRB5_RC_REQUIRED, "Message replay detection requires rcache parameter"
+error_code KRB5_ERR_BAD_HOSTNAME, "Hostname cannot be canonicalized"
+error_code KRB5_ERR_HOST_REALM_UNKNOWN, "Cannot determine realm for host"
+error_code KRB5_SNAME_UNSUPP_NAMETYPE, "Conversion to service principal undefined for name type"
+
+error_code KRB5KRB_AP_ERR_V4_REPLY, "Initial Ticket response appears to be Version 4"
+error_code KRB5_REALM_CANT_RESOLVE, "Cannot resolve KDC for requested realm"
+error_code KRB5_TKT_NOT_FORWARDABLE, "Requesting ticket can't get forwardable tickets"
+error_code KRB5_FWD_BAD_PRINCIPAL, "Bad principal name while trying to forward credentials"
+
+error_code KRB5_GET_IN_TKT_LOOP, "Looping detected inside krb5_get_in_tkt"
+error_code KRB5_CONFIG_NODEFREALM, "Configuration file does not specify default realm"
+
+error_code KRB5_SAM_UNSUPPORTED, "Bad SAM flags in obtain_sam_padata"
+error_code KRB5_SAM_INVALID_ETYPE, "Invalid encryption type in SAM challenge"
+error_code KRB5_SAM_NO_CHECKSUM, "Missing checksum in SAM challenge"
+error_code KRB5_SAM_BAD_CHECKSUM, "Bad checksum in SAM challenge"
+
+error_code KRB5_KT_NAME_TOOLONG, "Keytab name too long"
+error_code KRB5_KT_KVNONOTFOUND, "Key version number for principal in key table is incorrect"
+error_code KRB5_APPL_EXPIRED, "This application has expired"
+error_code KRB5_LIB_EXPIRED, "This Krb5 library has expired"
+
+error_code KRB5_CHPW_PWDNULL, "New password cannot be zero length"
+error_code KRB5_CHPW_FAIL, "Password change failed"
+error_code KRB5_KT_FORMAT, "Bad format in keytab"
+
+error_code KRB5_NOPERM_ETYPE, "Encryption type not permitted"
+error_code KRB5_CONFIG_ETYPE_NOSUPP, "No supported encryption types (config file error?)"
+
+error_code KRB5_OBSOLETE_FN, "Program called an obsolete, deleted function"
+
+error_code KRB5_EAI_FAIL, "unknown getaddrinfo failure"
+error_code KRB5_EAI_NODATA, "no data available for host/domain name"
+error_code KRB5_EAI_NONAME, "host/domain name not found"
+error_code KRB5_EAI_SERVICE, "service name unknown"
+
+error_code KRB5_ERR_NUMERIC_REALM, "Cannot determine realm for numeric host address"
+
+error_code KRB5_ERR_BAD_S2K_PARAMS, "Invalid key generation parameters from KDC"
+
+error_code KRB5_ERR_NO_SERVICE, "Service not available"
+
+index 247
+error_code KRB5_CC_NOSUPP, "Credential cache function not supported"
+error_code KRB5_DELTAT_BADFORMAT, "Invalid format of Kerberos lifetime or clock skew string"
+error_code KRB5_PLUGIN_NO_HANDLE, "Supplied data not handled by this plugin"
+error_code KRB5_PLUGIN_OP_NOTSUPP, "Plugin does not support the operaton"
+
+error_code KRB5_ERR_INVALID_UTF8, "Invalid UTF-8 string"
+error_code KRB5_ERR_FAST_REQUIRED, "FAST protected pre-authentication required but not supported by KDC"
+
+error_code KRB5_LOCAL_ADDR_REQUIRED, "Auth context must contain local address"
+error_code KRB5_REMOTE_ADDR_REQUIRED, "Auth context must contain remote address"
+
+error_code KRB5_TRACE_NOSUPP, "Tracing unsupported"
+
+
+end
diff --git a/third_party/heimdal/lib/krb5/krb5_find_padata.3 b/third_party/heimdal/lib/krb5/krb5_find_padata.3
new file mode 100644
index 0000000..377a2cb
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_find_padata.3
@@ -0,0 +1,87 @@
+.\" Copyright (c) 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd March 21, 2004
+.Dt KRB5_FIND_PADATA 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_find_padata ,
+.Nm krb5_padata_add
+.Nd Kerberos 5 pre-authentication data handling functions
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Pp
+.Ft "PA_DATA *"
+.Fo krb5_find_padata
+.Fa "PA_DATA *val"
+.Fa "unsigned len"
+.Fa "int type"
+.Fa "int *index"
+.Fc
+.Ft int
+.Fo krb5_padata_add
+.Fa "krb5_context context"
+.Fa "METHOD_DATA *md"
+.Fa "int type"
+.Fa "void *buf"
+.Fa "size_t len"
+.Fc
+.Sh DESCRIPTION
+.Fn krb5_find_padata
+tries to find the pre-authentication data entry of type
+.Fa type
+in the array
+.Fa val
+of length
+.Fa len .
+The search is started at entry pointed out by
+.Fa *index
+(zero based indexing).
+If the type isn't found,
+.Dv NULL
+is returned.
+.Pp
+.Fn krb5_padata_add
+adds a pre-authentication data entry of type
+.Fa type
+pointed out by
+.Fa buf
+and
+.Fa len
+to
+.Fa md .
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr kerberos 8
diff --git a/third_party/heimdal/lib/krb5/krb5_generate_random_block.3 b/third_party/heimdal/lib/krb5/krb5_generate_random_block.3
new file mode 100644
index 0000000..8fad949
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_generate_random_block.3
@@ -0,0 +1,57 @@
+.\" Copyright (c) 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd March 21, 2004
+.Dt KRB5_GENERATE_RANDOM_BLOCK 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_generate_random_block
+.Nd Kerberos 5 random functions
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft void
+.Fo krb5_generate_random_block
+.Fa "void *buf"
+.Fa "size_t len"
+.Fc
+.Sh DESCRIPTION
+.Fn krb5_generate_random_block
+generates a cryptographically strong pseudo-random block into the buffer
+.Fa buf
+of length
+.Fa len .
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5.conf 5
diff --git a/third_party/heimdal/lib/krb5/krb5_get_all_client_addrs.3 b/third_party/heimdal/lib/krb5/krb5_get_all_client_addrs.3
new file mode 100644
index 0000000..56a5322
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_get_all_client_addrs.3
@@ -0,0 +1,74 @@
+.\" Copyright (c) 2001 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd July 1, 2001
+.Dt KRB5_GET_ADDRS 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_get_all_client_addrs ,
+.Nm krb5_get_all_server_addrs
+.Nd return local addresses
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft "krb5_error_code"
+.Fn krb5_get_all_client_addrs "krb5_context context" "krb5_addresses *addrs"
+.Ft "krb5_error_code"
+.Fn krb5_get_all_server_addrs "krb5_context context" "krb5_addresses *addrs"
+.Sh DESCRIPTION
+These functions return in
+.Fa addrs
+a list of addresses associated with the local
+host.
+.Pp
+The server variant returns all configured interface addresses (if
+possible), including loop-back addresses. This is useful if you want
+to create sockets to listen to.
+.Pp
+The client version will also scan local interfaces (can be turned off
+by setting
+.Li libdefaults/scan_interfaces
+to false in
+.Pa krb5.conf ) ,
+but will not include loop-back addresses, unless there are no other
+addresses found. It will remove all addresses included in
+.Li libdefaults/ignore_addresses
+but will unconditionally include addresses in
+.Li libdefaults/extra_addresses .
+.Pp
+The returned addresses should be freed by calling
+.Fn krb5_free_addresses .
+.\".Sh EXAMPLE
+.Sh SEE ALSO
+.Xr krb5_free_addresses 3
diff --git a/third_party/heimdal/lib/krb5/krb5_get_credentials.3 b/third_party/heimdal/lib/krb5/krb5_get_credentials.3
new file mode 100644
index 0000000..112f308
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_get_credentials.3
@@ -0,0 +1,181 @@
+.\" Copyright (c) 2004 - 2005 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd July 26, 2004
+.Dt KRB5_GET_CREDENTIALS 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_get_credentials ,
+.Nm krb5_get_credentials_with_flags ,
+.Nm krb5_get_kdc_cred ,
+.Nm krb5_get_renewed_creds
+.Nd get credentials from the KDC using krbtgt
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fo krb5_get_credentials
+.Fa "krb5_context context"
+.Fa "krb5_flags options"
+.Fa "krb5_ccache ccache"
+.Fa "krb5_creds *in_creds"
+.Fa "krb5_creds **out_creds"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_credentials_with_flags
+.Fa "krb5_context context"
+.Fa "krb5_flags options"
+.Fa "krb5_kdc_flags flags"
+.Fa "krb5_ccache ccache"
+.Fa "krb5_creds *in_creds"
+.Fa "krb5_creds **out_creds"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_kdc_cred
+.Fa "krb5_context context"
+.Fa "krb5_ccache id"
+.Fa "krb5_kdc_flags flags"
+.Fa "krb5_addresses *addresses"
+.Fa "Ticket *second_ticket"
+.Fa "krb5_creds *in_creds"
+.Fa "krb5_creds **out_creds"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_renewed_creds
+.Fa "krb5_context context"
+.Fa "krb5_creds *creds"
+.Fa "krb5_const_principal client"
+.Fa "krb5_ccache ccache"
+.Fa "const char *in_tkt_service"
+.Fc
+.Sh DESCRIPTION
+.Fn krb5_get_credentials_with_flags
+get credentials specified by
+.Fa in_creds->server
+and
+.Fa in_creds->client
+(the rest of the
+.Fa in_creds
+structure is ignored)
+by first looking in the
+.Fa ccache
+and if doesn't exists or is expired, fetch the credential from the KDC
+using the krbtgt in
+.Fa ccache .
+The credential is returned in
+.Fa out_creds
+and should be freed using the function
+.Fn krb5_free_creds .
+.Pp
+Valid flags to pass into
+.Fa options
+argument are:
+.Pp
+.Bl -tag -width "KRB5_GC_EXPIRED_OK" -compact
+.It KRB5_GC_CACHED
+Only check the
+.Fa ccache ,
+don't got out on network to fetch credential.
+.It KRB5_GC_USER_USER
+Request a user to user ticket.
+This option doesn't store the resulting user to user credential in
+the
+.Fa ccache .
+.It KRB5_GC_EXPIRED_OK
+returns the credential even if it is expired, default behavior is trying
+to refetch the credential from the KDC.
+.El
+.Pp
+.Fa Flags
+are KDCOptions, note the caller must fill in the bit-field and not
+use the integer associated structure.
+.Pp
+.Fn krb5_get_credentials
+works the same way as
+.Fn krb5_get_credentials_with_flags
+except that the
+.Fa flags
+field is missing.
+.Pp
+.Fn krb5_get_kdc_cred
+does the same as the functions above, but the caller must fill in all
+the information andits closer to the wire protocol.
+.Pp
+.Fn krb5_get_renewed_creds
+renews a credential given by
+.Fa in_tkt_service
+(if
+.Dv NULL
+the default
+.Li krbtgt )
+using the credential cache
+.Fa ccache .
+The result is stored in
+.Fa creds
+and should be freed using
+.Fa krb5_free_creds .
+.Sh EXAMPLES
+Here is a example function that get a credential from a credential cache
+.Fa id
+or the KDC and returns it to the caller.
+.Bd -literal
+#include <krb5.h>
+
+int
+getcred(krb5_context context, krb5_ccache id, krb5_creds **creds)
+{
+ krb5_error_code ret;
+ krb5_creds in;
+
+ ret = krb5_parse_name(context, "client@EXAMPLE.COM",
+ &in.client);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_parse_name(context, "host/server.example.com@EXAMPLE.COM",
+ &in.server);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_get_credentials(context, 0, id, &in, creds);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_get_credentials");
+
+ return 0;
+}
+.Ed
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5_get_forwarded_creds 3 ,
+.Xr krb5.conf 5
diff --git a/third_party/heimdal/lib/krb5/krb5_get_creds.3 b/third_party/heimdal/lib/krb5/krb5_get_creds.3
new file mode 100644
index 0000000..35e861e
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_get_creds.3
@@ -0,0 +1,173 @@
+.\" Copyright (c) 2006 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd June 15, 2006
+.Dt KRB5_GET_CREDS 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_get_creds ,
+.Nm krb5_get_creds_opt_add_options ,
+.Nm krb5_get_creds_opt_alloc ,
+.Nm krb5_get_creds_opt_free ,
+.Nm krb5_get_creds_opt_set_enctype ,
+.Nm krb5_get_creds_opt_set_impersonate ,
+.Nm krb5_get_creds_opt_set_options ,
+.Nm krb5_get_creds_opt_set_ticket
+.Nd get credentials from the KDC
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fo krb5_get_creds
+.Fa "krb5_context context"
+.Fa "krb5_get_creds_opt opt"
+.Fa "krb5_ccache ccache"
+.Fa "krb5_const_principal inprinc"
+.Fa "krb5_creds **out_creds"
+.Fc
+.Ft void
+.Fo krb5_get_creds_opt_add_options
+.Fa "krb5_context context"
+.Fa "krb5_get_creds_opt opt"
+.Fa "krb5_flags options"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_creds_opt_alloc
+.Fa "krb5_context context"
+.Fa "krb5_get_creds_opt *opt"
+.Fc
+.Ft void
+.Fo krb5_get_creds_opt_free
+.Fa "krb5_context context"
+.Fa "krb5_get_creds_opt opt"
+.Fc
+.Ft void
+.Fo krb5_get_creds_opt_set_enctype
+.Fa "krb5_context context"
+.Fa "krb5_get_creds_opt opt"
+.Fa "krb5_enctype enctype"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_creds_opt_set_impersonate
+.Fa "krb5_context context"
+.Fa "krb5_get_creds_opt opt"
+.Fa "krb5_const_principal self"
+.Fc
+.Ft void
+.Fo krb5_get_creds_opt_set_options
+.Fa "krb5_context context"
+.Fa "krb5_get_creds_opt opt"
+.Fa "krb5_flags options"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_creds_opt_set_ticket
+.Fa "krb5_context context"
+.Fa "krb5_get_creds_opt opt"
+.Fa "const Ticket *ticket"
+.Fc
+.Sh DESCRIPTION
+.Fn krb5_get_creds
+fetches credentials specified by
+.Fa opt
+by first looking in the
+.Fa ccache ,
+and then it doesn't exists, fetch the credential from the KDC
+using the krbtgts in
+.Fa ccache .
+The credential is returned in
+.Fa out_creds
+and should be freed using the function
+.Fn krb5_free_creds .
+.Pp
+The structure
+.Li krb5_get_creds_opt
+controls the behavior of
+.Fn krb5_get_creds .
+The structure is opaque to consumers that can set the content of the
+structure with accessors functions. All accessor functions make copies
+of the data that is passed into accessor functions, so external
+consumers free the memory before calling
+.Fn krb5_get_creds .
+.Pp
+The structure
+.Li krb5_get_creds_opt
+is allocated with
+.Fn krb5_get_creds_opt_alloc
+and freed with
+.Fn krb5_get_creds_opt_free .
+The free function also frees the content of the structure set by the
+accessor functions.
+.Pp
+.Fn krb5_get_creds_opt_add_options
+and
+.Fn krb5_get_creds_opt_set_options
+adds and sets options to the
+.Li krb5_get_creds_opt
+structure .
+The possible options to set are
+.Bl -tag -width "KRB5_GC_USER_USER" -compact
+.It KRB5_GC_CACHED
+Only check the
+.Fa ccache ,
+don't got out on network to fetch credential.
+.It KRB5_GC_USER_USER
+request a user to user ticket.
+This options doesn't store the resulting user to user credential in
+the
+.Fa ccache .
+.It KRB5_GC_EXPIRED_OK
+returns the credential even if it is expired, default behavior is trying
+to refetch the credential from the KDC.
+.It KRB5_GC_NO_STORE
+Do not store the resulting credentials in the
+.Fa ccache .
+.El
+.Pp
+.Fn krb5_get_creds_opt_set_enctype
+sets the preferred encryption type of the application. Don't set this
+unless you have to since if there is no match in the KDC, the function
+call will fail.
+.Pp
+.Fn krb5_get_creds_opt_set_impersonate
+sets the principal to impersonate., Returns a ticket that have the
+impersonation principal as a client and the requestor as the
+service. Note that the requested principal have to be the same as the
+client principal in the krbtgt.
+.Pp
+.Fn krb5_get_creds_opt_set_ticket
+sets the extra ticket used in user-to-user or contrained delegation use case.
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5_get_credentials 3 ,
+.Xr krb5.conf 5
diff --git a/third_party/heimdal/lib/krb5/krb5_get_forwarded_creds.3 b/third_party/heimdal/lib/krb5/krb5_get_forwarded_creds.3
new file mode 100644
index 0000000..a648317
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_get_forwarded_creds.3
@@ -0,0 +1,79 @@
+.\" Copyright (c) 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd July 26, 2004
+.Dt KRB5_GET_FORWARDED_CREDS 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_get_forwarded_creds ,
+.Nm krb5_fwd_tgt_creds
+.Nd get forwarded credentials from the KDC
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fo krb5_get_forwarded_creds
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fa "krb5_ccache ccache"
+.Fa "krb5_flags flags"
+.Fa "const char *hostname"
+.Fa "krb5_creds *in_creds"
+.Fa "krb5_data *out_data"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_fwd_tgt_creds
+.Fa "krb5_context context"
+.Fa "krb5_auth_context auth_context"
+.Fa "const char *hostname"
+.Fa "krb5_principal client"
+.Fa "krb5_principal server"
+.Fa "krb5_ccache ccache"
+.Fa "int forwardable"
+.Fa "krb5_data *out_data"
+.Fc
+.Sh DESCRIPTION
+.Fn krb5_get_forwarded_creds
+and
+.Fn krb5_fwd_tgt_creds
+get tickets forwarded to
+.Fa hostname.
+If the tickets that are forwarded are address-less, the forwarded
+tickets will also be address-less, otherwise
+.Fa hostname
+will be used for figure out the address to forward the ticket too.
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5_get_credentials 3 ,
+.Xr krb5.conf 5
diff --git a/third_party/heimdal/lib/krb5/krb5_get_in_cred.3 b/third_party/heimdal/lib/krb5/krb5_get_in_cred.3
new file mode 100644
index 0000000..c415aec
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_get_in_cred.3
@@ -0,0 +1,274 @@
+.\" Copyright (c) 2003 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 31, 2003
+.Dt KRB5_GET_IN_TKT 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_get_in_tkt ,
+.Nm krb5_get_in_cred ,
+.Nm krb5_get_in_tkt_with_password ,
+.Nm krb5_get_in_tkt_with_keytab ,
+.Nm krb5_get_in_tkt_with_skey ,
+.Nm krb5_free_kdc_rep ,
+.Nm krb5_password_key_proc
+.Nd deprecated initial authentication functions
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Pp
+.Ft krb5_error_code
+.Fo krb5_get_in_tkt
+.Fa "krb5_context context"
+.Fa "krb5_flags options"
+.Fa "const krb5_addresses *addrs"
+.Fa "const krb5_enctype *etypes"
+.Fa "const krb5_preauthtype *ptypes"
+.Fa "krb5_key_proc key_proc"
+.Fa "krb5_const_pointer keyseed"
+.Fa "krb5_decrypt_proc decrypt_proc"
+.Fa "krb5_const_pointer decryptarg"
+.Fa "krb5_creds *creds"
+.Fa "krb5_ccache ccache"
+.Fa "krb5_kdc_rep *ret_as_reply"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_in_cred
+.Fa "krb5_context context"
+.Fa "krb5_flags options"
+.Fa "const krb5_addresses *addrs"
+.Fa "const krb5_enctype *etypes"
+.Fa "const krb5_preauthtype *ptypes"
+.Fa "const krb5_preauthdata *preauth"
+.Fa "krb5_key_proc key_proc"
+.Fa "krb5_const_pointer keyseed"
+.Fa "krb5_decrypt_proc decrypt_proc"
+.Fa "krb5_const_pointer decryptarg"
+.Fa "krb5_creds *creds"
+.Fa "krb5_kdc_rep *ret_as_reply"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_in_tkt_with_password
+.Fa "krb5_context context"
+.Fa "krb5_flags options"
+.Fa "krb5_addresses *addrs"
+.Fa "const krb5_enctype *etypes"
+.Fa "const krb5_preauthtype *pre_auth_types"
+.Fa "const char *password"
+.Fa "krb5_ccache ccache"
+.Fa "krb5_creds *creds"
+.Fa "krb5_kdc_rep *ret_as_reply"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_in_tkt_with_keytab
+.Fa "krb5_context context"
+.Fa "krb5_flags options"
+.Fa "krb5_addresses *addrs"
+.Fa "const krb5_enctype *etypes"
+.Fa "const krb5_preauthtype *pre_auth_types"
+.Fa "krb5_keytab keytab"
+.Fa "krb5_ccache ccache"
+.Fa "krb5_creds *creds"
+.Fa "krb5_kdc_rep *ret_as_reply"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_in_tkt_with_skey
+.Fa "krb5_context context"
+.Fa "krb5_flags options"
+.Fa "krb5_addresses *addrs"
+.Fa "const krb5_enctype *etypes"
+.Fa "const krb5_preauthtype *pre_auth_types"
+.Fa "const krb5_keyblock *key"
+.Fa "krb5_ccache ccache"
+.Fa "krb5_creds *creds"
+.Fa "krb5_kdc_rep *ret_as_reply"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_free_kdc_rep
+.Fa "krb5_context context"
+.Fa "krb5_kdc_rep *rep"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_password_key_proc
+.Fa "krb5_context context"
+.Fa "krb5_enctype type"
+.Fa "krb5_salt salt"
+.Fa "krb5_const_pointer keyseed"
+.Fa "krb5_keyblock **key"
+.Fc
+.Sh DESCRIPTION
+.Bf Em
+All the functions in this manual page are deprecated in the MIT
+implementation, and will soon be deprecated in Heimdal too, don't use them.
+.Ef
+.Pp
+Getting initial credential ticket for a principal.
+.Nm krb5_get_in_cred
+is the function all other krb5_get_in function uses to fetch tickets.
+The other krb5_get_in function are more specialized and therefor
+somewhat easier to use.
+.Pp
+If your need is only to verify a user and password, consider using
+.Xr krb5_verify_user 3
+instead, it have a much simpler interface.
+.Pp
+.Nm krb5_get_in_tkt
+and
+.Nm krb5_get_in_cred
+fetches initial credential, queries after key using the
+.Fa key_proc
+argument.
+The differences between the two function is that
+.Nm krb5_get_in_tkt
+stores the credential in a
+.Li krb5_creds
+while
+.Nm krb5_get_in_cred
+stores the credential in a
+.Li krb5_ccache .
+.Pp
+.Nm krb5_get_in_tkt_with_password ,
+.Nm krb5_get_in_tkt_with_keytab ,
+and
+.Nm krb5_get_in_tkt_with_skey
+does the same work as
+.Nm krb5_get_in_cred
+but are more specialized.
+.Pp
+.Nm krb5_get_in_tkt_with_password
+uses the clients password to authenticate.
+If the password argument is
+.Dv NULL
+the user user queried with the default password query function.
+.Pp
+.Nm krb5_get_in_tkt_with_keytab
+searches the given keytab for a service entry for the client principal.
+If the keytab is
+.Dv NULL
+the default keytab is used.
+.Pp
+.Nm krb5_get_in_tkt_with_skey
+uses a key to get the initial credential.
+.Pp
+There are some common arguments to the krb5_get_in functions, these are:
+.Pp
+.Fa options
+are the
+.Dv KDC_OPT
+flags.
+.Pp
+.Fa etypes
+is a
+.Dv NULL
+terminated array of encryption types that the client approves.
+.Pp
+.Fa addrs
+a list of the addresses that the initial ticket.
+If it is
+.Dv NULL
+the list will be generated by the library.
+.Pp
+.Fa pre_auth_types
+a
+.Dv NULL
+terminated array of pre-authentication types.
+If
+.Fa pre_auth_types
+is
+.Dv NULL
+the function will try without pre-authentication and return those
+pre-authentication that the KDC returned.
+.Pp
+.Fa ret_as_reply
+will (if not
+.Dv NULL )
+be filled in with the response of the KDC and should be free with
+.Fn krb5_free_kdc_rep .
+.Pp
+.Fa key_proc
+is a pointer to a function that should return a key salted appropriately.
+Using
+.Dv NULL
+will use the default password query function.
+.Pp
+.Fa decrypt_proc
+Using
+.Dv NULL
+will use the default decryption function.
+.Pp
+.Fa decryptarg
+will be passed to the decryption function
+.Fa decrypt_proc .
+.Pp
+.Fa creds
+creds should be filled in with the template for a credential that
+should be requested.
+The client and server elements of the creds structure must be filled in.
+Upon return of the function it will be contain the content of the
+requested credential
+.Fa ( krb5_get_in_cred ) ,
+or it will be freed with
+.Xr krb5_free_creds 3
+(all the other krb5_get_in functions).
+.Pp
+.Fa ccache
+will store the credential in the credential cache
+.Fa ccache .
+The credential cache will not be initialized, thats up the the caller.
+.Pp
+.Nm krb5_password_key_proc
+is a library function that is suitable using as the
+.Fa krb5_key_proc
+argument to
+.Nm krb5_get_in_cred
+or
+.Nm krb5_get_in_tkt .
+.Fa keyseed
+should be a pointer to a
+.Dv NUL
+terminated string or
+.Dv NULL .
+.Nm krb5_password_key_proc
+will query the user for the pass on the console if the password isn't
+given as the argument
+.Fa keyseed .
+.Pp
+.Fn krb5_free_kdc_rep
+frees the content of
+.Fa rep .
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5_verify_user 3 ,
+.Xr krb5.conf 5 ,
+.Xr kerberos 8
diff --git a/third_party/heimdal/lib/krb5/krb5_get_init_creds.3 b/third_party/heimdal/lib/krb5/krb5_get_init_creds.3
new file mode 100644
index 0000000..11257b9
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_get_init_creds.3
@@ -0,0 +1,403 @@
+.\" Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd Sep 16, 2006
+.Dt KRB5_GET_INIT_CREDS 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_get_init_creds ,
+.Nm krb5_get_init_creds_keytab ,
+.Nm krb5_get_init_creds_opt ,
+.Nm krb5_get_init_creds_opt_alloc ,
+.Nm krb5_get_init_creds_opt_free ,
+.Nm krb5_get_init_creds_opt_init ,
+.Nm krb5_get_init_creds_opt_set_address_list ,
+.Nm krb5_get_init_creds_opt_set_addressless ,
+.Nm krb5_get_init_creds_opt_set_anonymous ,
+.Nm krb5_get_init_creds_opt_set_default_flags ,
+.Nm krb5_get_init_creds_opt_set_etype_list ,
+.Nm krb5_get_init_creds_opt_set_forwardable ,
+.Nm krb5_get_init_creds_opt_set_pa_password ,
+.Nm krb5_get_init_creds_opt_set_paq_request ,
+.Nm krb5_get_init_creds_opt_set_preauth_list ,
+.Nm krb5_get_init_creds_opt_set_proxiable ,
+.Nm krb5_get_init_creds_opt_set_renew_life ,
+.Nm krb5_get_init_creds_opt_set_salt ,
+.Nm krb5_get_init_creds_opt_set_tkt_life ,
+.Nm krb5_get_init_creds_opt_set_canonicalize ,
+.Nm krb5_get_init_creds_opt_set_win2k ,
+.Nm krb5_get_init_creds_password ,
+.Nm krb5_prompt ,
+.Nm krb5_prompter_posix
+.Nd Kerberos 5 initial authentication functions
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Pp
+.Ft krb5_get_init_creds_opt;
+.Pp
+.Ft krb5_error_code
+.Fo krb5_get_init_creds_opt_alloc
+.Fa "krb5_context context"
+.Fa "krb5_get_init_creds_opt **opt"
+.Fc
+.Ft void
+.Fo krb5_get_init_creds_opt_free
+.Fa "krb5_context context"
+.Fa "krb5_get_init_creds_opt *opt"
+.Fc
+.Ft void
+.Fo krb5_get_init_creds_opt_init
+.Fa "krb5_get_init_creds_opt *opt"
+.Fc
+.Ft void
+.Fo krb5_get_init_creds_opt_set_address_list
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "krb5_addresses *addresses"
+.Fc
+.Ft void
+.Fo krb5_get_init_creds_opt_set_addressless
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "krb5_boolean addressless"
+.Fc
+.Ft void
+.Fo krb5_get_init_creds_opt_set_anonymous
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "int anonymous"
+.Fc
+.Ft void
+.Fo krb5_get_init_creds_opt_set_change_password_prompt
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "int change_password_prompt"
+.Fc
+.Ft void
+.Fo krb5_get_init_creds_opt_set_default_flags
+.Fa "krb5_context context"
+.Fa "const char *appname"
+.Fa "krb5_const_realm realm"
+.Fa "krb5_get_init_creds_opt *opt"
+.Fc
+.Ft void
+.Fo krb5_get_init_creds_opt_set_etype_list
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "krb5_enctype *etype_list"
+.Fa "int etype_list_length"
+.Fc
+.Ft void
+.Fo krb5_get_init_creds_opt_set_forwardable
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "int forwardable"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_init_creds_opt_set_pa_password
+.Fa "krb5_context context"
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "const char *password"
+.Fa "krb5_s2k_proc key_proc"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_init_creds_opt_set_paq_request
+.Fa "krb5_context context"
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "krb5_boolean req_pac"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_init_creds_opt_set_pkinit
+.Fa "krb5_context context"
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "const char *cert_file"
+.Fa "const char *key_file"
+.Fa "const char *x509_anchors"
+.Fa "int flags"
+.Fa "char *password"
+.Fc
+.Ft void
+.Fo krb5_get_init_creds_opt_set_preauth_list
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "krb5_preauthtype *preauth_list"
+.Fa "int preauth_list_length"
+.Fc
+.Ft void
+.Fo krb5_get_init_creds_opt_set_proxiable
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "int proxiable"
+.Fc
+.Ft void
+.Fo krb5_get_init_creds_opt_set_renew_life
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "krb5_deltat renew_life"
+.Fc
+.Ft void
+.Fo krb5_get_init_creds_opt_set_salt
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "krb5_data *salt"
+.Fc
+.Ft void
+.Fo krb5_get_init_creds_opt_set_tkt_life
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "krb5_deltat tkt_life"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_init_creds_opt_set_canonicalize
+.Fa "krb5_context context"
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "krb5_boolean req"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_init_creds_opt_set_win2k
+.Fa "krb5_context context"
+.Fa "krb5_get_init_creds_opt *opt"
+.Fa "krb5_boolean req"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_init_creds
+.Fa "krb5_context context"
+.Fa "krb5_creds *creds"
+.Fa "krb5_principal client"
+.Fa "krb5_prompter_fct prompter"
+.Fa "void *prompter_data"
+.Fa "krb5_deltat start_time"
+.Fa "const char *in_tkt_service"
+.Fa "krb5_get_init_creds_opt *options"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_init_creds_password
+.Fa "krb5_context context"
+.Fa "krb5_creds *creds"
+.Fa "krb5_principal client"
+.Fa "const char *password"
+.Fa "krb5_prompter_fct prompter"
+.Fa "void *prompter_data"
+.Fa "krb5_deltat start_time"
+.Fa "const char *in_tkt_service"
+.Fa "krb5_get_init_creds_opt *in_options"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_init_creds_keytab
+.Fa "krb5_context context"
+.Fa "krb5_creds *creds"
+.Fa "krb5_principal client"
+.Fa "krb5_keytab keytab"
+.Fa "krb5_deltat start_time"
+.Fa "const char *in_tkt_service"
+.Fa "krb5_get_init_creds_opt *options"
+.Fc
+.Ft int
+.Fo krb5_prompter_posix
+.Fa "krb5_context context"
+.Fa "void *data"
+.Fa "const char *name"
+.Fa "const char *banner"
+.Fa "int num_prompts"
+.Fa "krb5_prompt prompts[]"
+.Fc
+.Sh DESCRIPTION
+Getting initial credential ticket for a principal.
+That may include changing an expired password, and doing preauthentication.
+This interface that replaces the deprecated
+.Fa krb5_in_tkt
+and
+.Fa krb5_in_cred
+functions.
+.Pp
+If you only want to verify a username and password, consider using
+.Xr krb5_verify_user 3
+instead, since it also verifies that initial credentials with using a
+keytab to make sure the response was from the KDC.
+.Pp
+First a
+.Li krb5_get_init_creds_opt
+structure is initialized
+with
+.Fn krb5_get_init_creds_opt_alloc
+or
+.Fn krb5_get_init_creds_opt_init .
+.Fn krb5_get_init_creds_opt_alloc
+allocates a extendible structures that needs to be freed with
+.Fn krb5_get_init_creds_opt_free .
+The structure may be modified by any of the
+.Fn krb5_get_init_creds_opt_set
+functions to change request parameters and authentication information.
+.Pp
+If the caller want to use the default options,
+.Dv NULL
+can be passed instead.
+.Pp
+The the actual request to the KDC is done by any of the
+.Fn krb5_get_init_creds ,
+.Fn krb5_get_init_creds_password ,
+or
+.Fn krb5_get_init_creds_keytab
+functions.
+.Fn krb5_get_init_creds
+is the least specialized function and can, with the right in data,
+behave like the latter two.
+The latter two are there for compatibility with older releases and
+they are slightly easier to use.
+.Pp
+.Li krb5_prompt
+is a structure containing the following elements:
+.Bd -literal
+typedef struct {
+ const char *prompt;
+ int hidden;
+ krb5_data *reply;
+ krb5_prompt_type type
+} krb5_prompt;
+.Ed
+.Pp
+.Fa prompt
+is the prompt that should shown to the user
+If
+.Fa hidden
+is set, the prompter function shouldn't echo the output to the display
+device.
+.Fa reply
+must be preallocated; it will not be allocated by the prompter
+function.
+Possible values for the
+.Fa type
+element are:
+.Pp
+.Bl -tag -width Ds -compact -offset indent
+.It KRB5_PROMPT_TYPE_PASSWORD
+.It KRB5_PROMPT_TYPE_NEW_PASSWORD
+.It KRB5_PROMPT_TYPE_NEW_PASSWORD_AGAIN
+.It KRB5_PROMPT_TYPE_PREAUTH
+.It KRB5_PROMPT_TYPE_INFO
+.El
+.Pp
+.Fn krb5_prompter_posix
+is the default prompter function in a POSIX environment.
+It matches the
+.Fa krb5_prompter_fct
+and can be used in the
+.Fa krb5_get_init_creds
+functions.
+.Fn krb5_prompter_posix
+doesn't require
+.Fa prompter_data.
+.Pp
+If the
+.Fa start_time
+is zero, then the requested ticket will be valid
+beginning immediately.
+Otherwise, the
+.Fa start_time
+indicates how far in the future the ticket should be postdated.
+.Pp
+If the
+.Fa in_tkt_service
+name is
+.Dv non-NULL ,
+that principal name will be
+used as the server name for the initial ticket request.
+The realm of the name specified will be ignored and will be set to the
+realm of the client name.
+If no in_tkt_service name is specified,
+krbtgt/CLIENT-REALM@CLIENT-REALM will be used.
+.Pp
+For the rest of arguments, a configuration or library default will be
+used if no value is specified in the options structure.
+.Pp
+.Fn krb5_get_init_creds_opt_set_address_list
+sets the list of
+.Fa addresses
+that is should be stored in the ticket.
+.Pp
+.Fn krb5_get_init_creds_opt_set_addressless
+controls if the ticket is requested with addresses or not,
+.Fn krb5_get_init_creds_opt_set_address_list
+overrides this option.
+.Pp
+.Fn krb5_get_init_creds_opt_set_anonymous
+make the request anonymous if the
+.Fa anonymous
+parameter is non-zero.
+.Pp
+.Fn krb5_get_init_creds_opt_set_default_flags
+sets the default flags using the configuration file.
+.Pp
+.Fn krb5_get_init_creds_opt_set_etype_list
+set a list of enctypes that the client is willing to support in the
+request.
+.Pp
+.Fn krb5_get_init_creds_opt_set_forwardable
+request a forwardable ticket.
+.Pp
+.Fn krb5_get_init_creds_opt_set_pa_password
+set the
+.Fa password
+and
+.Fa key_proc
+that is going to be used to get a new ticket.
+.Fa password
+or
+.Fa key_proc
+can be
+.Dv NULL
+if the caller wants to use the default values.
+If the
+.Fa password
+is unset and needed, the user will be prompted for it.
+.Pp
+.Fn krb5_get_init_creds_opt_set_paq_request
+sets the password that is going to be used to get a new ticket.
+.Pp
+.Fn krb5_get_init_creds_opt_set_preauth_list
+sets the list of client-supported preauth types.
+.Pp
+.Fn krb5_get_init_creds_opt_set_proxiable
+makes the request proxiable.
+.Pp
+.Fn krb5_get_init_creds_opt_set_renew_life
+sets the requested renewable lifetime.
+.Pp
+.Fn krb5_get_init_creds_opt_set_salt
+sets the salt that is going to be used in the request.
+.Pp
+.Fn krb5_get_init_creds_opt_set_tkt_life
+sets requested ticket lifetime.
+.Pp
+.Fn krb5_get_init_creds_opt_set_canonicalize
+requests that the KDC canonicalize the client principal if possible.
+.Pp
+.Fn krb5_get_init_creds_opt_set_win2k
+turns on compatibility with Windows 2000.
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5_creds 3 ,
+.Xr krb5_verify_user 3 ,
+.Xr krb5.conf 5 ,
+.Xr kerberos 8
diff --git a/third_party/heimdal/lib/krb5/krb5_get_krbhst.3 b/third_party/heimdal/lib/krb5/krb5_get_krbhst.3
new file mode 100644
index 0000000..55fb8f2
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_get_krbhst.3
@@ -0,0 +1,86 @@
+.\" Copyright (c) 2001 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd April 24, 2005
+.Dt KRB5_GET_KRBHST 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_get_krbhst ,
+.Nm krb5_get_krb_admin_hst ,
+.Nm krb5_get_krb_changepw_hst ,
+.Nm krb5_get_krb524hst ,
+.Nm krb5_free_krbhst
+.Nd lookup Kerberos KDC hosts
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fn krb5_get_krbhst "krb5_context context" "const krb5_realm *realm" "char ***hostlist"
+.Ft krb5_error_code
+.Fn krb5_get_krb_admin_hst "krb5_context context" "const krb5_realm *realm" "char ***hostlist"
+.Ft krb5_error_code
+.Fn krb5_get_krb_changepw_hst "krb5_context context" "const krb5_realm *realm" "char ***hostlist"
+.Ft krb5_error_code
+.Fn krb5_get_krb524hst "krb5_context context" "const krb5_realm *realm" "char ***hostlist"
+.Ft krb5_error_code
+.Fn krb5_free_krbhst "krb5_context context" "char **hostlist"
+.Sh DESCRIPTION
+These functions implement the old API to get a list of Kerberos hosts,
+and are thus similar to the
+.Fn krb5_krbhst_init
+functions. However, since these functions returns
+.Em all
+hosts in one go, they potentially have to do more lookups than
+necessary. These functions remain for compatibility reasons.
+.Pp
+After a call to one of these functions,
+.Fa hostlist
+is a
+.Dv NULL
+terminated list of strings, pointing to the requested Kerberos hosts. These should be freed with
+.Fn krb5_free_krbhst
+when done with.
+.Sh EXAMPLES
+The following code will print the KDCs of the realm
+.Dq MY.REALM .
+.Bd -literal -offset indent
+char **hosts, **p;
+krb5_get_krbhst(context, "MY.REALM", &hosts);
+for(p = hosts; *p; p++)
+ printf("%s\\n", *p);
+krb5_free_krbhst(context, hosts);
+.Ed
+.\" .Sh BUGS
+.Sh SEE ALSO
+.Xr krb5_krbhst_init 3
diff --git a/third_party/heimdal/lib/krb5/krb5_getportbyname.3 b/third_party/heimdal/lib/krb5/krb5_getportbyname.3
new file mode 100644
index 0000000..0e9b7cb
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_getportbyname.3
@@ -0,0 +1,67 @@
+.\" Copyright (c) 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd August 15, 2004
+.Dt NAME 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_getportbyname
+.Nd get port number by name
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft int
+.Fo krb5_getportbyname
+.Fa "krb5_context context"
+.Fa "const char *service"
+.Fa "const char *proto"
+.Fa "int default_port"
+.Fc
+.Sh DESCRIPTION
+.Fn krb5_getportbyname
+gets the port number for
+.Fa service /
+.Fa proto
+pair from the global service table for and returns it in network order.
+If it isn't found in the global table, the
+.Fa default_port
+(given in host order)
+is returned.
+.Sh EXAMPLE
+.Bd -literal
+int port = krb5_getportbyname(context, "kerberos", "tcp", 88);
+.Ed
+.\" .Sh BUGS
+.Sh SEE ALSO
+.Xr krb5 3
diff --git a/third_party/heimdal/lib/krb5/krb5_init_context.3 b/third_party/heimdal/lib/krb5/krb5_init_context.3
new file mode 100644
index 0000000..3a6199b
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_init_context.3
@@ -0,0 +1,308 @@
+.\" Copyright (c) 2001 - 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd December 8, 2004
+.Dt KRB5_CONTEXT 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_add_et_list ,
+.Nm krb5_add_extra_addresses ,
+.Nm krb5_add_ignore_addresses ,
+.Nm krb5_context ,
+.Nm krb5_free_config_files ,
+.Nm krb5_free_context ,
+.Nm krb5_get_default_config_files ,
+.Nm krb5_get_dns_canonize_hostname ,
+.Nm krb5_get_extra_addresses ,
+.Nm krb5_get_fcache_version ,
+.Nm krb5_get_ignore_addresses ,
+.Nm krb5_get_kdc_sec_offset ,
+.Nm krb5_get_max_time_skew ,
+.Nm krb5_get_use_admin_kdc
+.Nm krb5_init_context ,
+.Nm krb5_init_ets ,
+.Nm krb5_prepend_config_files ,
+.Nm krb5_prepend_config_files_default ,
+.Nm krb5_set_config_files ,
+.Nm krb5_set_dns_canonize_hostname ,
+.Nm krb5_set_extra_addresses ,
+.Nm krb5_set_fcache_version ,
+.Nm krb5_set_ignore_addresses ,
+.Nm krb5_set_max_time_skew ,
+.Nm krb5_set_use_admin_kdc ,
+.Nd create, modify and delete krb5_context structures
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Pp
+.Li "struct krb5_context;"
+.Pp
+.Ft krb5_error_code
+.Fo krb5_init_context
+.Fa "krb5_context *context"
+.Fc
+.Ft void
+.Fo krb5_free_context
+.Fa "krb5_context context"
+.Fc
+.Ft void
+.Fo krb5_init_ets
+.Fa "krb5_context context"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_add_et_list
+.Fa "krb5_context context"
+.Fa "void (*func)(struct et_list **)"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_add_extra_addresses
+.Fa "krb5_context context"
+.Fa "krb5_addresses *addresses"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_set_extra_addresses
+.Fa "krb5_context context"
+.Fa "const krb5_addresses *addresses"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_extra_addresses
+.Fa "krb5_context context"
+.Fa "krb5_addresses *addresses"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_add_ignore_addresses
+.Fa "krb5_context context"
+.Fa "krb5_addresses *addresses"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_set_ignore_addresses
+.Fa "krb5_context context"
+.Fa "const krb5_addresses *addresses"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_ignore_addresses
+.Fa "krb5_context context"
+.Fa "krb5_addresses *addresses"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_set_fcache_version
+.Fa "krb5_context context"
+.Fa "int version"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_fcache_version
+.Fa "krb5_context context"
+.Fa "int *version"
+.Fc
+.Ft void
+.Fo krb5_set_dns_canonize_hostname
+.Fa "krb5_context context"
+.Fa "krb5_boolean flag"
+.Fc
+.Ft krb5_boolean
+.Fo krb5_get_dns_canonize_hostname
+.Fa "krb5_context context"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_kdc_sec_offset
+.Fa "krb5_context context"
+.Fa "int32_t *sec"
+.Fa "int32_t *usec"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_set_config_files
+.Fa "krb5_context context"
+.Fa "char **filenames"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_prepend_config_files
+.Fa "const char *filelist"
+.Fa "char **pq"
+.Fa "char ***ret_pp"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_prepend_config_files_default
+.Fa "const char *filelist"
+.Fa "char ***pfilenames"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_default_config_files
+.Fa "char ***pfilenames"
+.Fc
+.Ft void
+.Fo krb5_free_config_files
+.Fa "char **filenames"
+.Fc
+.Ft void
+.Fo krb5_set_use_admin_kdc
+.Fa "krb5_context context"
+.Fa "krb5_boolean flag"
+.Fc
+.Ft krb5_boolean
+.Fo krb5_get_use_admin_kdc
+.Fa "krb5_context context"
+.Fc
+.Ft time_t
+.Fo krb5_get_max_time_skew
+.Fa "krb5_context context"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_set_max_time_skew
+.Fa "krb5_context context"
+.Fa "time_t time"
+.Fc
+.Sh DESCRIPTION
+The
+.Fn krb5_init_context
+function initializes the
+.Fa context
+structure and reads the configuration file
+.Pa /etc/krb5.conf .
+.Pp
+The structure should be freed by calling
+.Fn krb5_free_context
+when it is no longer being used.
+.Pp
+.Fn krb5_init_context
+returns 0 to indicate success.
+Otherwise an errno code is returned.
+Failure means either that something bad happened during initialization
+(typically
+.Bq ENOMEM )
+or that Kerberos should not be used
+.Bq ENXIO .
+.Pp
+.Fn krb5_init_ets
+adds all
+.Xr com_err 3
+libs to
+.Fa context .
+This is done by
+.Fn krb5_init_context .
+.Pp
+.Fn krb5_add_et_list
+adds a
+.Xr com_err 3
+error-code handler
+.Fa func
+to the specified
+.Fa context .
+The error handler must generated by the the re-rentrant version of the
+.Xr compile_et 1
+program.
+.Fn krb5_add_extra_addresses
+add a list of addresses that should be added when requesting tickets.
+.Pp
+.Fn krb5_add_ignore_addresses
+add a list of addresses that should be ignored when requesting tickets.
+.Pp
+.Fn krb5_get_extra_addresses
+get the list of addresses that should be added when requesting tickets.
+.Pp
+.Fn krb5_get_ignore_addresses
+get the list of addresses that should be ignored when requesting tickets.
+.Pp
+.Fn krb5_set_ignore_addresses
+set the list of addresses that should be ignored when requesting tickets.
+.Pp
+.Fn krb5_set_extra_addresses
+set the list of addresses that should be added when requesting tickets.
+.Pp
+.Fn krb5_set_fcache_version
+sets the version of file credentials caches that should be used.
+.Pp
+.Fn krb5_get_fcache_version
+gets the version of file credentials caches that should be used.
+.Pp
+.Fn krb5_set_dns_canonize_hostname
+sets if the context is configured to canonicalize hostnames using DNS.
+.Pp
+.Fn krb5_get_dns_canonize_hostname
+returns if the context is configured to canonicalize hostnames using DNS.
+.Pp
+.Fn krb5_get_kdc_sec_offset
+returns the offset between the localtime and the KDC's time.
+.Fa sec
+and
+.Fa usec
+are both optional argument and
+.Dv NULL
+can be passed in.
+.Pp
+.Fn krb5_set_config_files
+set the list of configuration files to use and re-initialize the
+configuration from the files.
+.Pp
+.Fn krb5_prepend_config_files
+parse the
+.Fa filelist
+and prepend the result to the already existing list
+.Fa pq
+The result is returned in
+.Fa ret_pp
+and should be freed with
+.Fn krb5_free_config_files .
+.Pp
+.Fn krb5_prepend_config_files_default
+parse the
+.Fa filelist
+and append that to the default
+list of configuration files.
+.Pp
+.Fn krb5_get_default_config_files
+get a list of default configuration files.
+.Pp
+.Fn krb5_free_config_files
+free a list of configuration files returned by
+.Fn krb5_get_default_config_files ,
+.Fn krb5_prepend_config_files_default ,
+or
+.Fn krb5_prepend_config_files .
+.Pp
+.Fn krb5_set_use_admin_kdc
+sets if all KDC requests should go admin KDC.
+.Pp
+.Fn krb5_get_use_admin_kdc
+gets if all KDC requests should go admin KDC.
+.Pp
+.Fn krb5_get_max_time_skew
+and
+.Fn krb5_set_max_time_skew
+get and sets the maximum allowed time skew between client and server.
+.Sh SEE ALSO
+.Xr errno 2 ,
+.Xr krb5 3 ,
+.Xr krb5_config 3 ,
+.Xr krb5_context 3 ,
+.Xr kerberos 8
diff --git a/third_party/heimdal/lib/krb5/krb5_is_thread_safe.3 b/third_party/heimdal/lib/krb5/krb5_is_thread_safe.3
new file mode 100644
index 0000000..1a73e85
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_is_thread_safe.3
@@ -0,0 +1,58 @@
+.\" Copyright (c) 2005 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 5, 2006
+.Dt KRB5_IS_THREAD_SAFE 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_is_thread_safe
+.Nd "is the Kerberos library compiled with multithread support"
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_boolean
+.Fn krb5_is_thread_safe "void"
+.Sh DESCRIPTION
+.Nm
+returns
+.Dv TRUE
+if the library was compiled with with multithread support.
+If the library isn't compiled, the consumer have to use a global lock
+to make sure Kerboros functions are not called at the same time by
+different threads.
+.\" .Sh EXAMPLE
+.\" .Sh BUGS
+.Sh SEE ALSO
+.Xr krb5_create_checksum 3 ,
+.Xr krb5_encrypt 3
diff --git a/third_party/heimdal/lib/krb5/krb5_krbhst_init.3 b/third_party/heimdal/lib/krb5/krb5_krbhst_init.3
new file mode 100644
index 0000000..8abb00f
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_krbhst_init.3
@@ -0,0 +1,174 @@
+.\" Copyright (c) 2001-2005 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 10, 2005
+.Dt KRB5_KRBHST_INIT 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_krbhst_init ,
+.Nm krb5_krbhst_init_flags ,
+.Nm krb5_krbhst_next ,
+.Nm krb5_krbhst_next_as_string ,
+.Nm krb5_krbhst_reset ,
+.Nm krb5_krbhst_free ,
+.Nm krb5_krbhst_format_string ,
+.Nm krb5_krbhst_get_addrinfo
+.Nd lookup Kerberos KDC hosts
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fn krb5_krbhst_init "krb5_context context" "const char *realm" "unsigned int type" "krb5_krbhst_handle *handle"
+.Ft krb5_error_code
+.Fn krb5_krbhst_init_flags "krb5_context context" "const char *realm" "unsigned int type" "int flags" "krb5_krbhst_handle *handle"
+.Ft krb5_error_code
+.Fn "krb5_krbhst_next" "krb5_context context" "krb5_krbhst_handle handle" "krb5_krbhst_info **host"
+.Ft krb5_error_code
+.Fn krb5_krbhst_next_as_string "krb5_context context" "krb5_krbhst_handle handle" "char *hostname" "size_t hostlen"
+.Ft void
+.Fn krb5_krbhst_reset "krb5_context context" "krb5_krbhst_handle handle"
+.Ft void
+.Fn krb5_krbhst_free "krb5_context context" "krb5_krbhst_handle handle"
+.Ft krb5_error_code
+.Fn krb5_krbhst_format_string "krb5_context context" "const krb5_krbhst_info *host" "char *hostname" "size_t hostlen"
+.Ft krb5_error_code
+.Fn krb5_krbhst_get_addrinfo "krb5_context context" "krb5_krbhst_info *host" "struct addrinfo **ai"
+.Sh DESCRIPTION
+These functions are used to sequence through all Kerberos hosts of a
+particular realm and service. The service type can be the KDCs, the
+administrative servers, the password changing servers, or the servers
+for Kerberos 4 ticket conversion.
+.Pp
+First a handle to a particular service is obtained by calling
+.Fn krb5_krbhst_init
+(or
+.Fn krb5_krbhst_init_flags )
+with the
+.Fa realm
+of interest and the type of service to lookup. The
+.Fa type
+can be one of:
+.Pp
+.Bl -tag -width Ds -compact -offset indent
+.It KRB5_KRBHST_KDC
+.It KRB5_KRBHST_ADMIN
+.It KRB5_KRBHST_CHANGEPW
+.It KRB5_KRBHST_KRB524
+.El
+.Pp
+The
+.Fa handle
+is returned to the caller, and should be passed to the other
+functions.
+.Pp
+The
+.Fa flag
+argument to
+.Nm krb5_krbhst_init_flags
+is the same flags as
+.Fn krb5_send_to_kdc_flags
+uses.
+Possible values are:
+.Pp
+.Bl -tag -width KRB5_KRBHST_FLAGS_LARGE_MSG -compact -offset indent
+.It KRB5_KRBHST_FLAGS_MASTER
+only talk to master (readwrite) KDC
+.It KRB5_KRBHST_FLAGS_LARGE_MSG
+this is a large message, so use transport that can handle that.
+.El
+.Pp
+For each call to
+.Fn krb5_krbhst_next
+information on a new host is returned. The former function returns in
+.Fa host
+a pointer to a structure containing information about the host, such
+as protocol, hostname, and port:
+.Bd -literal -offset indent
+typedef struct krb5_krbhst_info {
+ enum { KRB5_KRBHST_UDP,
+ KRB5_KRBHST_TCP,
+ KRB5_KRBHST_HTTP } proto;
+ unsigned short port;
+ struct addrinfo *ai;
+ struct krb5_krbhst_info *next;
+ char hostname[1];
+} krb5_krbhst_info;
+.Ed
+.Pp
+The related function,
+.Fn krb5_krbhst_next_as_string ,
+return the same information as a URL-like string.
+.Pp
+When there are no more hosts, these functions return
+.Dv KRB5_KDC_UNREACH .
+.Pp
+To re-iterate over all hosts, call
+.Fn krb5_krbhst_reset
+and the next call to
+.Fn krb5_krbhst_next
+will return the first host.
+.Pp
+When done with the handle,
+.Fn krb5_krbhst_free
+should be called.
+.Pp
+To use a
+.Va krb5_krbhst_info ,
+there are two functions:
+.Fn krb5_krbhst_format_string
+that will return a printable representation of that struct
+and
+.Fn krb5_krbhst_get_addrinfo
+that will return a
+.Va struct addrinfo
+that can then be used for communicating with the server mentioned.
+.Sh EXAMPLES
+The following code will print the KDCs of the realm
+.Dq MY.REALM :
+.Bd -literal -offset indent
+krb5_krbhst_handle handle;
+char host[MAXHOSTNAMELEN];
+krb5_krbhst_init(context, "MY.REALM", KRB5_KRBHST_KDC, &handle);
+while(krb5_krbhst_next_as_string(context, handle,
+ host, sizeof(host)) == 0)
+ printf("%s\\n", host);
+krb5_krbhst_free(context, handle);
+.Ed
+.\" .Sh BUGS
+.Sh SEE ALSO
+.Xr getaddrinfo 3 ,
+.Xr krb5_get_krbhst 3 ,
+.Xr krb5_send_to_kdc_flags 3
+.Sh HISTORY
+These functions first appeared in Heimdal 0.3g.
diff --git a/third_party/heimdal/lib/krb5/krb5_locl.h b/third_party/heimdal/lib/krb5/krb5_locl.h
new file mode 100644
index 0000000..91751c1
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_locl.h
@@ -0,0 +1,485 @@
+/*
+ * Copyright (c) 1997-2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __KRB5_LOCL_H__
+#define __KRB5_LOCL_H__
+
+#include <config.h>
+#include <roken.h>
+
+#include <ctype.h>
+
+#ifdef HAVE_POLL_H
+#include <sys/poll.h>
+#endif
+
+#include <krb5-types.h>
+
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_MMAN_H
+#include <sys/mman.h>
+#endif
+
+#if defined(HAVE_SYS_IOCTL_H) && SunOS != 40
+#include <sys/ioctl.h>
+#endif
+#ifdef HAVE_PWD_H
+#undef _POSIX_PTHREAD_SEMANTICS
+/* This gets us the 5-arg getpwnam_r on Solaris 9. */
+#define _POSIX_PTHREAD_SEMANTICS
+#include <pwd.h>
+#endif
+
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif
+#ifdef _AIX
+struct mbuf;
+#endif
+#ifdef HAVE_SYS_FILIO_H
+#include <sys/filio.h>
+#endif
+#ifdef HAVE_SYS_FILE_H
+#include <sys/file.h>
+#endif
+
+#include <com_err.h>
+
+#include <heimbase.h>
+
+#define HEIMDAL_TEXTDOMAIN "heimdal_krb5"
+
+#ifdef LIBINTL
+#include <libintl.h>
+#undef N_
+#define N_(x,y) dgettext(HEIMDAL_TEXTDOMAIN, x)
+#else
+#undef N_
+#define N_(x,y) (x)
+#define bindtextdomain(package, localedir)
+#endif
+
+
+#ifdef HAVE_CRYPT_H
+#undef des_encrypt
+#define des_encrypt wingless_pigs_mostly_fail_to_fly
+#include <crypt.h>
+#undef des_encrypt
+#endif
+
+#ifdef HAVE_DOOR_CREATE
+#include <door.h>
+#endif
+
+#include <parse_time.h>
+#include <base64.h>
+
+#include <wind.h>
+
+/*
+ * We use OpenSSL for EC, but to do this we need to disable cross-references
+ * between OpenSSL and hcrypto bn.h and such. Source files that use OpenSSL EC
+ * must define HEIM_NO_CRYPTO_HDRS before including this file.
+ */
+#define HC_DEPRECATED_CRYPTO
+#ifndef HEIM_NO_CRYPTO_HDRS
+#include "crypto-headers.h"
+#endif
+
+
+#include <krb5_asn1.h>
+typedef Krb5Int32 krb5int32;
+typedef Krb5UInt32 krb5uint32;
+#include <pkinit_asn1.h>
+
+struct send_to_kdc;
+
+/* XXX glue for pkinit */
+struct hx509_certs_data;
+struct krb5_pk_identity;
+struct krb5_pk_cert;
+struct ContentInfo;
+struct AlgorithmIdentifier;
+typedef struct krb5_pk_init_ctx_data *krb5_pk_init_ctx;
+struct krb5_dh_moduli;
+struct krb5_fast_state;
+struct krb5_gss_init_ctx_data;
+
+/* v4 glue */
+struct _krb5_krb_auth_data;
+
+struct krb5_gss_init_ctx_data;
+typedef struct krb5_gss_init_ctx_data *krb5_gss_init_ctx;
+
+struct gss_ctx_id_t_desc_struct;
+struct gss_cred_id_t_desc_struct;
+struct gss_OID_desc_struct;
+
+#include <der.h>
+
+#include <krb5.h>
+#include <krb5_err.h>
+#include <k5e1_err.h>
+#include <asn1_err.h>
+#ifdef PKINIT
+#include <hx509.h>
+#endif
+
+#include "crypto.h"
+
+typedef krb5_error_code (KRB5_LIB_CALL *krb5_gssic_step)(
+ krb5_context,
+ krb5_gss_init_ctx,
+ const krb5_creds *,
+ struct gss_ctx_id_t_desc_struct **,
+ KDCOptions options,
+ krb5_data *,
+ krb5_data *,
+ krb5_data *);
+
+typedef krb5_error_code (KRB5_LIB_CALL *krb5_gssic_finish)(
+ krb5_context,
+ krb5_gss_init_ctx,
+ const krb5_creds *,
+ struct gss_ctx_id_t_desc_struct *,
+ krb5int32,
+ krb5_enctype,
+ krb5_principal *,
+ krb5_keyblock **);
+
+typedef void (KRB5_LIB_CALL *krb5_gssic_release_cred)(
+ krb5_context,
+ krb5_gss_init_ctx,
+ struct gss_cred_id_t_desc_struct *);
+
+typedef void (KRB5_LIB_CALL *krb5_gssic_delete_sec_context)(
+ krb5_context,
+ krb5_gss_init_ctx,
+ struct gss_ctx_id_t_desc_struct *);
+
+#define KRB5_GSS_IC_FLAG_RELEASE_CRED 1
+
+#include <krb5-private.h>
+
+#include "heim_threads.h"
+
+extern const char _krb5_wellknown_lkdc[];
+
+#define ALLOC(X, N) (X) = calloc((N), sizeof(*(X)))
+#define ALLOC_SEQ(X, N) do { (X)->len = (N); ALLOC((X)->val, (N)); } while(0)
+
+#define krb5_einval(context, argnum) _krb5_einval((context), __func__, (argnum))
+
+#ifndef PATH_SEP
+#define PATH_SEP ":"
+#endif
+
+/* should this be public? */
+#define KEYTAB_DEFAULT "FILE:" SYSCONFDIR "/krb5.keytab"
+#define KEYTAB_DEFAULT_MODIFY "FILE:" SYSCONFDIR "/krb5.keytab"
+
+#ifndef CLIENT_KEYTAB_DEFAULT
+#define CLIENT_KEYTAB_DEFAULT "FILE:" LOCALSTATEDIR "/user/%{euid}/client.keytab";
+#endif
+
+#define MODULI_FILE SYSCONFDIR "/krb5.moduli"
+
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+
+#ifndef O_CLOEXEC
+#define O_CLOEXEC 0
+#endif
+
+#ifndef SOCK_CLOEXEC
+#define SOCK_CLOEXEC 0
+#endif
+
+
+#define KRB5_BUFSIZ 2048
+
+typedef enum {
+ KRB5_INIT_CREDS_TRISTATE_UNSET = 0,
+ KRB5_INIT_CREDS_TRISTATE_TRUE,
+ KRB5_INIT_CREDS_TRISTATE_FALSE
+} krb5_get_init_creds_tristate;
+
+struct _krb5_get_init_creds_opt_private {
+ int refcount;
+ /* ENC_TIMESTAMP */
+ const char *password;
+ krb5_s2k_proc key_proc;
+ /* PA_PAC_REQUEST */
+ krb5_get_init_creds_tristate req_pac;
+ /* PKINIT */
+ krb5_pk_init_ctx pk_init_ctx;
+ krb5_get_init_creds_tristate addressless;
+ int flags;
+#define KRB5_INIT_CREDS_DONE 1
+#define KRB5_INIT_CREDS_CANONICALIZE 2
+#define KRB5_INIT_CREDS_NO_C_CANON_CHECK 4
+#define KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK 8
+#define KRB5_INIT_CREDS_PKINIT_KX_VALID 32
+#define KRB5_INIT_CREDS_PKINIT_NO_KRBTGT_OTHERNAME_CHECK 64
+ struct {
+ krb5_gic_process_last_req func;
+ void *ctx;
+ } lr;
+};
+
+typedef uint32_t krb5_enctype_set;
+
+/*
+ * Do not remove or reorder the fields of this structure.
+ * Fields that are no longer used should be marked "deprecated".
+ * New fields should always be appended to the end of the
+ * structure.
+ *
+ * Although this structure is internal it is shared with
+ * plugins and such changes will result in data corruption
+ * if plugins are not built with a matching version.
+ */
+typedef struct krb5_context_data {
+ heim_context hcontext;
+ krb5_enctype *etypes;
+ krb5_enctype *cfg_etypes;
+ krb5_enctype *etypes_des;/* deprecated */
+ krb5_enctype *as_etypes;
+ krb5_enctype *tgs_etypes;
+ krb5_enctype *permitted_enctypes;
+ char **default_realms;
+ time_t max_skew;
+ time_t kdc_timeout;
+ time_t host_timeout;
+ unsigned max_retries;
+ int32_t kdc_sec_offset;
+ int32_t kdc_usec_offset;
+ krb5_config_section *cf;
+ const krb5_cc_ops **cc_ops;
+ int num_cc_ops;
+ const char *http_proxy;
+ const char *time_fmt;
+ krb5_boolean log_utc;
+ const char *default_keytab;
+ const char *default_keytab_modify;
+ krb5_boolean use_admin_kdc;
+ krb5_addresses *extra_addresses;
+ krb5_boolean scan_interfaces; /* `ifconfig -a' */
+ krb5_boolean srv_lookup; /* do SRV lookups */
+ krb5_boolean srv_try_txt; /* try TXT records also */
+ int32_t fcache_vno; /* create cache files w/ this
+ version */
+ int num_kt_types; /* # of registered keytab types */
+ struct krb5_keytab_data *kt_types; /* registered keytab types */
+ const char *date_fmt;
+ krb5_error_code error_code;
+ krb5_addresses *ignore_addresses;
+ char *default_cc_name;
+ char *default_cc_name_env;
+ char *configured_default_cc_name;
+ int default_cc_name_set;
+ int large_msg_size;
+ int max_msg_size;
+ int tgs_negative_timeout; /* timeout for TGS negative cache */
+ int flags;
+#define KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME 1
+#define KRB5_CTX_F_CHECK_PAC 2
+#define KRB5_CTX_F_HOMEDIR_ACCESS 4
+#define KRB5_CTX_F_SOCKETS_INITIALIZED 8
+#define KRB5_CTX_F_RD_REQ_IGNORE 16
+#define KRB5_CTX_F_FCACHE_STRICT_CHECKING 32
+#define KRB5_CTX_F_ENFORCE_OK_AS_DELEGATE 64
+#define KRB5_CTX_F_REPORT_CANONICAL_CLIENT_NAME 128
+ struct send_to_kdc *send_to_kdc;
+#ifdef PKINIT
+ hx509_context hx509ctx;
+#endif
+ unsigned int num_kdc_requests;
+ krb5_name_canon_rule name_canon_rules;
+ size_t config_include_depth;
+ krb5_boolean no_ticket_store; /* Don't store service tickets */
+} krb5_context_data;
+
+#define KRB5_DEFAULT_CCNAME_FILE "FILE:%{TEMP}/krb5cc_%{uid}"
+#define KRB5_DEFAULT_CCNAME_DIR "DIR:%{TEMP}/krb5cc_%{uid}_dir/"
+#define KRB5_DEFAULT_CCNAME_API "API:"
+#define KRB5_DEFAULT_CCNAME_KCM_KCM "KCM:%{uid}"
+#define KRB5_DEFAULT_CCNAME_KCM_API "API:%{uid}"
+
+#define EXTRACT_TICKET_ALLOW_CNAME_MISMATCH 1
+#define EXTRACT_TICKET_ALLOW_SERVER_MISMATCH 2
+#define EXTRACT_TICKET_MATCH_REALM 4
+#define EXTRACT_TICKET_AS_REQ 8
+#define EXTRACT_TICKET_TIMESYNC 16
+#define EXTRACT_TICKET_MATCH_ANON 32
+
+/*
+ * Configurable options
+ */
+
+#ifndef KRB5_DEFAULT_CCTYPE
+#ifdef __APPLE__
+#define KRB5_DEFAULT_CCTYPE (&krb5_acc_ops)
+#else
+#define KRB5_DEFAULT_CCTYPE (&krb5_fcc_ops)
+#endif
+#endif
+
+#ifndef KRB5_ADDRESSLESS_DEFAULT
+#define KRB5_ADDRESSLESS_DEFAULT TRUE
+#endif
+
+#ifndef KRB5_FORWARDABLE_DEFAULT
+#define KRB5_FORWARDABLE_DEFAULT TRUE
+#endif
+
+#ifndef KRB5_CONFIGURATION_CHANGE_NOTIFY_NAME
+#define KRB5_CONFIGURATION_CHANGE_NOTIFY_NAME "org.h5l.Kerberos.configuration-changed"
+#endif
+
+#ifndef KRB5_FALLBACK_DEFAULT
+#define KRB5_FALLBACK_DEFAULT TRUE
+#endif
+
+#ifndef KRB5_TKT_LIFETIME_DEFAULT
+# define KRB5_TKT_LIFETIME_DEFAULT 15778800 /* seconds */
+#endif
+
+#ifndef KRB5_TKT_RENEW_LIFETIME_DEFAULT
+# define KRB5_TKT_RENEW_LIFETIME_DEFAULT 15778800 /* seconds */
+#endif
+
+#ifdef PKINIT
+
+struct krb5_pk_identity {
+ hx509_verify_ctx verify_ctx;
+ hx509_certs certs;
+ hx509_cert cert;
+ hx509_certs anchors;
+ hx509_certs certpool;
+ hx509_revoke_ctx revokectx;
+ int flags;
+#define PKINIT_BTMM 1
+#define PKINIT_NO_KDC_ANCHOR 2
+};
+
+enum krb5_pk_type {
+ PKINIT_WIN2K = 1,
+ PKINIT_27 = 2
+};
+
+enum keyex_enum { USE_RSA, USE_DH, USE_ECDH };
+
+struct krb5_pk_init_ctx_data {
+ struct krb5_pk_identity *id;
+ enum keyex_enum keyex;
+ union {
+ DH *dh;
+ void *eckey;
+ } u;
+ krb5_data *clientDHNonce;
+ struct krb5_dh_moduli **m;
+ hx509_peer_info peer;
+ enum krb5_pk_type type;
+ unsigned int require_binding:1;
+ unsigned int require_eku:1;
+ unsigned int require_krbtgt_otherName:1;
+ unsigned int require_hostname_match:1;
+ unsigned int trustedCertifiers:1;
+ unsigned int anonymous:1;
+ unsigned int kdc_verified:1;
+};
+
+#endif /* PKINIT */
+
+struct krb5_fast_state {
+ enum PA_FX_FAST_REQUEST_enum type;
+ unsigned int flags;
+#define KRB5_FAST_REPLY_KEY_USE_TO_ENCRYPT_THE_REPLY 0x0001
+#define KRB5_FAST_REPLY_KEY_USE_IN_TRANSACTION 0x0002
+#define KRB5_FAST_KDC_REPLY_KEY_REPLACED 0x0004
+#define KRB5_FAST_REPLY_REPLY_VERIFIED 0x0008
+#define KRB5_FAST_STRONG 0x0010
+#define KRB5_FAST_EXPECTED 0x0020 /* in exchange with KDC, fast was discovered */
+#define KRB5_FAST_REQUIRED 0x0040 /* fast required by action of caller */
+#define KRB5_FAST_DISABLED 0x0080
+
+#define KRB5_FAST_AP_ARMOR_SERVICE 0x0100
+#define KRB5_FAST_OPTIMISTIC 0x0200 /* Optimistic try, like Anon + PKINIT or service fast bit */
+#define KRB5_FAST_REQUIRE_ENC_PA 0x0400
+
+#define KRB5_FAST_AS_REQ 0x1000
+#define KRB5_FAST_ANON_PKINIT_ARMOR 0x2000
+#define KRB5_FAST_KDC_VERIFIED 0x4000
+
+ krb5_keyblock *reply_key;
+ krb5_ccache armor_ccache;
+ krb5_auth_context armor_ac;
+ KrbFastArmor *armor_data;
+ krb5_principal armor_service;
+ krb5_crypto armor_crypto;
+ krb5_keyblock armor_key;
+ krb5_keyblock *strengthen_key;
+
+ /* KRB5_FAST_ANON_PKINIT_ARMOR */
+ krb5_get_init_creds_opt *anon_pkinit_opt;
+ krb5_init_creds_context anon_pkinit_ctx;
+};
+
+struct krb5_decrypt_tkt_with_subkey_state {
+ krb5_keyblock *subkey;
+ struct krb5_fast_state *fast_state;
+};
+
+#define ISTILDE(x) (x == '~')
+#ifdef _WIN32
+# define ISPATHSEP(x) (x == '/' || x =='\\')
+#else
+# define ISPATHSEP(x) (x == '/')
+#endif
+
+/* Flag in KRB5_AUTHDATA_AP_OPTIONS */
+#define KERB_AP_OPTIONS_CBT 0x00004000
+
+/* Flag in PAC_ATTRIBUTES_INFO */
+#define KRB5_PAC_WAS_REQUESTED 0x1
+#define KRB5_PAC_WAS_GIVEN_IMPLICITLY 0x2
+
+#endif /* __KRB5_LOCL_H__ */
diff --git a/third_party/heimdal/lib/krb5/krb5_mk_req.3 b/third_party/heimdal/lib/krb5/krb5_mk_req.3
new file mode 100644
index 0000000..41701b0
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_mk_req.3
@@ -0,0 +1,187 @@
+.\" Copyright (c) 2005 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd August 27, 2005
+.Dt KRB5_MK_REQ 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_mk_req ,
+.Nm krb5_mk_req_exact ,
+.Nm krb5_mk_req_extended ,
+.Nm krb5_rd_req ,
+.Nm krb5_rd_req_with_keyblock ,
+.Nm krb5_mk_rep ,
+.Nm krb5_mk_rep_exact ,
+.Nm krb5_mk_rep_extended ,
+.Nm krb5_rd_rep ,
+.Nm krb5_build_ap_req ,
+.Nm krb5_verify_ap_req
+.Nd create and read application authentication request
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fo krb5_mk_req
+.Fa "krb5_context context"
+.Fa "krb5_auth_context *auth_context"
+.Fa "const krb5_flags ap_req_options"
+.Fa "const char *service"
+.Fa "const char *hostname"
+.Fa "krb5_data *in_data"
+.Fa "krb5_ccache ccache"
+.Fa "krb5_data *outbuf"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_mk_req_extended
+.Fa "krb5_context context"
+.Fa "krb5_auth_context *auth_context"
+.Fa "const krb5_flags ap_req_options"
+.Fa "krb5_data *in_data"
+.Fa "krb5_creds *in_creds"
+.Fa "krb5_data *outbuf"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_rd_req
+.Fa "krb5_context context"
+.Fa "krb5_auth_context *auth_context"
+.Fa "const krb5_data *inbuf"
+.Fa "krb5_const_principal server"
+.Fa "krb5_keytab keytab"
+.Fa "krb5_flags *ap_req_options"
+.Fa "krb5_ticket **ticket"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_build_ap_req
+.Fa "krb5_context context"
+.Fa "krb5_enctype enctype"
+.Fa "krb5_creds *cred"
+.Fa "krb5_flags ap_options"
+.Fa "krb5_data authenticator"
+.Fa "krb5_data *retdata"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_verify_ap_req
+.Fa "krb5_context context"
+.Fa "krb5_auth_context *auth_context"
+.Fa "krb5_ap_req *ap_req"
+.Fa "krb5_const_principal server"
+.Fa "krb5_keyblock *keyblock"
+.Fa "krb5_flags flags"
+.Fa "krb5_flags *ap_req_options"
+.Fa "krb5_ticket **ticket"
+.Fc
+.Sh DESCRIPTION
+The functions documented in this manual page document the functions
+that facilitates the exchange between a Kerberos client and server.
+They are the core functions used in the authentication exchange
+between the client and the server.
+.Pp
+The
+.Nm krb5_mk_req
+and
+.Nm krb5_mk_req_extended
+creates the Kerberos message
+.Dv KRB_AP_REQ
+that is sent from the client to the server as the first packet in a client/server exchange. The result that should be sent to server is stored in
+.Fa outbuf .
+.Pp
+.Fa auth_context
+should be allocated with
+.Fn krb5_auth_con_init
+or
+.Dv NULL
+passed in, in that case, it will be allocated and freed internally.
+.Pp
+The input data
+.Fa in_data
+will have a checksum calculated over it and checksum will be
+transported in the message to the server.
+.Pp
+.Fa ap_req_options
+can be set to one or more of the following flags:
+.Pp
+.Bl -tag -width indent
+.It Dv AP_OPTS_USE_SESSION_KEY
+Use the session key when creating the request, used for user to user
+authentication.
+.It Dv AP_OPTS_MUTUAL_REQUIRED
+Mark the request as mutual authenticate required so that the receiver
+returns a mutual authentication packet.
+.El
+.Pp
+The
+.Nm krb5_rd_req
+read the AP_REQ in
+.Fa inbuf
+and verify and extract the content.
+If
+.Fa server
+is specified, that server will be fetched from the
+.Fa keytab
+and used unconditionally.
+If
+.Fa server
+is
+.Dv NULL ,
+the
+.Fa keytab
+will be search for a matching principal.
+.Pp
+The
+.Fa keytab
+argument specifies what keytab to search for receiving principals.
+The arguments
+.Fa ap_req_options
+and
+.Fa ticket
+returns the content.
+.Pp
+When the AS-REQ is a user to user request, neither of
+.Fa keytab
+or
+.Fa principal
+are used, instead
+.Fn krb5_rd_req
+expects the session key to be set in
+.Fa auth_context .
+.Pp
+The
+.Nm krb5_verify_ap_req
+and
+.Nm krb5_build_ap_req
+both constructs and verify the AP_REQ message, should not be used by
+external code.
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5.conf 5
diff --git a/third_party/heimdal/lib/krb5/krb5_mk_safe.3 b/third_party/heimdal/lib/krb5/krb5_mk_safe.3
new file mode 100644
index 0000000..e8f4559
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_mk_safe.3
@@ -0,0 +1,82 @@
+.\" Copyright (c) 2003 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 1, 2006
+.Dt KRB5_MK_SAFE 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_mk_safe ,
+.Nm krb5_mk_priv
+.Nd generates integrity protected and/or encrypted messages
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Pp
+.Ft krb5_error_code
+.Fn krb5_mk_priv "krb5_context context" "krb5_auth_context auth_context" "const krb5_data *userdata" "krb5_data *outbuf" "krb5_replay_data *outdata"
+.Ft krb5_error_code
+.Fn krb5_mk_safe "krb5_context context" "krb5_auth_context auth_context" "const krb5_data *userdata" "krb5_data *outbuf" "krb5_replay_data *outdata"
+.Sh DESCRIPTION
+.Fn krb5_mk_safe
+and
+.Fn krb5_mk_priv
+formats
+.Li KRB-SAFE
+(integrity protected)
+and
+.Li KRB-PRIV
+(also encrypted)
+messages into
+.Fa outbuf .
+The actual message data is taken from
+.Fa userdata .
+If the
+.Dv KRB5_AUTH_CONTEXT_DO_SEQUENCE
+or
+.Dv KRB5_AUTH_CONTEXT_DO_TIME
+flags are set in the
+.Fa auth_context ,
+sequence numbers and time stamps are generated.
+If the
+.Dv KRB5_AUTH_CONTEXT_RET_SEQUENCE
+or
+.Dv KRB5_AUTH_CONTEXT_RET_TIME
+flags are set
+they are also returned in the
+.Fa outdata
+parameter.
+.Sh SEE ALSO
+.Xr krb5_auth_con_init 3 ,
+.Xr krb5_rd_priv 3 ,
+.Xr krb5_rd_safe 3
diff --git a/third_party/heimdal/lib/krb5/krb5_openlog.3 b/third_party/heimdal/lib/krb5/krb5_openlog.3
new file mode 100644
index 0000000..09de9d0
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_openlog.3
@@ -0,0 +1,305 @@
+.\" Copyright (c) 1997, 1999, 2001 - 2002 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.Dd August 6, 1997
+.Dt KRB5_OPENLOG 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_initlog ,
+.Nm krb5_openlog ,
+.Nm krb5_closelog ,
+.Nm krb5_addlog_dest ,
+.Nm krb5_addlog_func ,
+.Nm krb5_log ,
+.Nm krb5_vlog ,
+.Nm krb5_log_msg ,
+.Nm krb5_vlog_msg
+.Nd Heimdal logging functions
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft "typedef void"
+.Fn "\*(lp*krb5_log_log_func_t\*(rp" "const char *time" "const char *message" "void *data"
+.Ft "typedef void"
+.Fn "\*(lp*krb5_log_close_func_t\*(rp" "void *data"
+.Ft krb5_error_code
+.Fn krb5_addlog_dest "krb5_context context" "krb5_log_facility *facility" "const char *destination"
+.Ft krb5_error_code
+.Fn krb5_addlog_func "krb5_context context" "krb5_log_facility *facility" "int min" "int max" "krb5_log_log_func_t log" "krb5_log_close_func_t close" "void *data"
+.Ft krb5_error_code
+.Fn krb5_closelog "krb5_context context" "krb5_log_facility *facility"
+.Ft krb5_error_code
+.Fn krb5_initlog "krb5_context context" "const char *program" "krb5_log_facility **facility"
+.Ft krb5_error_code
+.Fn krb5_log "krb5_context context" "krb5_log_facility *facility" "int level" "const char *format" "..."
+.Ft krb5_error_code
+.Fn krb5_log_msg "krb5_context context" "krb5_log_facility *facility" "char **reply" "int level" "const char *format" "..."
+.Ft krb5_error_code
+.Fn krb5_openlog "krb5_context context" "const char *program" "krb5_log_facility **facility"
+.Ft krb5_error_code
+.Fn krb5_vlog "krb5_context context" "krb5_log_facility *facility" "int level" "const char *format" "va_list arglist"
+.Ft krb5_error_code
+.Fn krb5_vlog_msg "krb5_context context" "krb5_log_facility *facility" "char **reply" "int level" "const char *format" "va_list arglist"
+.Sh DESCRIPTION
+These functions logs messages to one or more destinations.
+.Pp
+The
+.Fn krb5_openlog
+function creates a logging
+.Fa facility ,
+that is used to log messages. A facility consists of one or more
+destinations (which can be files or syslog or some other device). The
+.Fa program
+parameter should be the generic name of the program that is doing the
+logging. This name is used to lookup which destinations to use. This
+information is contained in the
+.Li logging
+section of the
+.Pa krb5.conf
+configuration file. If no entry is found for
+.Fa program ,
+the entry for
+.Li default
+is used, or if that is missing too,
+.Li SYSLOG
+will be used as destination.
+.Pp
+To close a logging facility, use the
+.Fn krb5_closelog
+function.
+.Pp
+To log a message to a facility use one of the functions
+.Fn krb5_log ,
+.Fn krb5_log_msg ,
+.Fn krb5_vlog ,
+or
+.Fn krb5_vlog_msg .
+The functions ending in
+.Li _msg
+return in
+.Fa reply
+a pointer to the message that just got logged. This string is allocated,
+and should be freed with
+.Fn free .
+The
+.Fa format
+is a standard
+.Fn printf
+style format string (but see the BUGS section).
+.Pp
+If you want better control of where things gets logged, you can instead of using
+.Fn krb5_openlog
+call
+.Fn krb5_initlog ,
+which just initializes a facility, but doesn't define any actual logging
+destinations. You can then add destinations with the
+.Fn krb5_addlog_dest
+and
+.Fn krb5_addlog_func
+functions. The first of these takes a string specifying a logging
+destination, and adds this to the facility. If you want to do some
+non-standard logging you can use the
+.Fn krb5_addlog_func
+function, which takes a function to use when logging.
+The
+.Fa log
+function is called for each message with
+.Fa time
+being a string specifying the current time, and
+.Fa message
+the message to log.
+.Fa close
+is called when the facility is closed. You can pass application specific data in the
+.Fa data
+parameter. The
+.Fa min
+and
+.Fa max
+parameter are the same as in a destination (defined below). To specify a
+max of infinity, pass -1.
+.Pp
+.Fn krb5_openlog
+calls
+.Fn krb5_initlog
+and then calls
+.Fn krb5_addlog_dest
+for each destination found.
+.Ss Destinations
+The defined destinations (as specified in
+.Pa krb5.conf )
+follows:
+.Bl -tag -width "xxx" -offset indent
+.It Li STDERR
+This logs to the program's stderr.
+.It Li EFILE: Ns Pa /file
+Log to the specified file if it exists, otherwise do nothing.
+All writes will be appended to the end of the file and the file
+will be re-opened for each new write.
+Non-existence of the file is cached for 1 second which reduces
+the potential performance impact significantly.
+This is useful for defining a trace file which can be enabled
+without restarting a server.
+.It Li FILE: Ns Pa /file
+Log to the specified file.
+All writes will be appended to the end of the file and the file
+will be re-opened for each new write.
+.It Li FILE= Ns Pa /file
+On the first write, this form will
+.Xr truncate 2
+the file and then append all subsequent messages whilst keeping the
+file descriptor open.
+This form is mainly for compatibility with MIT libkrb5.
+.It Li DEVICE= Ns Pa /device
+This logs to the specified device, at present this is the same as
+.Li FILE:/device .
+.It Li CONSOLE
+Log to the console, this is the same as
+.Li DEVICE=/dev/console .
+.It Li SYSLOG Ns Op :priority Ns Op :facility
+Send messages to the syslog system, using priority, and facility. To
+get the name for one of these, you take the name of the macro passed
+to
+.Xr syslog 3 ,
+and remove the leading
+.Li LOG_
+.No ( Li LOG_NOTICE
+becomes
+.Li NOTICE ) .
+The default values (as well as the values used for unrecognised
+values), are
+.Li ERR ,
+and
+.Li AUTH ,
+respectively. See
+.Xr syslog 3
+for a list of priorities and facilities.
+.El
+.Pp
+Each destination may optionally be prepended with a range of logging
+levels, specified as
+.Li min-max/ .
+If the
+.Fa level
+parameter to
+.Fn krb5_log
+is within this range (inclusive) the message gets logged to this
+destination, otherwise not. Either of the min and max valued may be
+omitted, in this case min is assumed to be 0, and max is assumed to
+be 3.
+If you don't include a dash, both min and max get set to the
+specified value.
+.Pp
+The paths specified are subject to token expansion.
+For the purposes of logging, the most interesting token
+expansion is
+.ar %{strftime:<string>}
+which calls
+.Xr strftime 3
+on
+.Ar <string>
+with the localised current time of day.
+.Ss Levels
+Each log message has a level as follows:
+.Bl -tag -width "xxx" -offset indent
+.It 0
+Critical conditions.
+This is a condition that should be corrected immediately, such as a
+corrupted Kerberos database.
+.It 1
+Errors.
+These are errors that occur in the normal processing of requests.
+.It 2
+Warning messages.
+On the KDC, this includes malformed requests and requests that
+are out of policy.
+.It 3
+Informational messages.
+.It 4-6
+Debugging messages with increasing obscurity as the level rises.
+.It 7
+Tracing messages.
+These messages may be high volume and are likely to impact
+performance significantly.
+Notably, tracing messages may be emitted whilst locks are held.
+.El
+.Sh EXAMPLES
+.Bd -literal -offset indent
+[logging]
+ kdc = 0/FILE:/var/log/kdc.log
+ kdc = 1-/SYSLOG:INFO:USER
+ default = STDERR
+.Ed
+.Pp
+This will log all messages from the
+.Nm kdc
+program with level 0 to
+.Pa /var/log/kdc.log ,
+other messages will be logged to syslog with priority
+.Li LOG_INFO ,
+and facility
+.Li LOG_USER .
+.Bd -literal -offset indent
+[logging]
+ kdc = FILE:/var/log/kdc-%{strftime:%Y%m%d%H}
+ kdc = 4-/EFILE:/tmp/kdc-trace
+.Ed
+.Pp
+This will log all messages from the
+.Nm kdc
+program with level 0 to 3 (inclusively) to a file whose
+name is generated using
+.Xr strftime 3 .
+As the file is
+.Xr open 2 ed
+each time a log message is written, this can be used to write
+automatically rotating log files.
+All of the KDC debugging messages will be written into
+.Pa /tmp/kdc-trace
+but only if it exists.
+.Sh SEE ALSO
+.Xr syslog 3 ,
+.Xr krb5.conf 5
+.Sh BUGS
+These functions use
+.Fn asprintf
+to format the message. If your operating system does not have a working
+.Fn asprintf ,
+a replacement will be used. At present this replacement does not handle
+some correct conversion specifications (like floating point numbers). Until
+this is fixed, the use of these conversions should be avoided.
+.Pp
+If logging is done to the syslog facility, these functions might not be
+thread-safe, depending on the implementation of
+.Fn openlog ,
+and
+.Fn syslog .
diff --git a/third_party/heimdal/lib/krb5/krb5_parse_name.3 b/third_party/heimdal/lib/krb5/krb5_parse_name.3
new file mode 100644
index 0000000..85acc72
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_parse_name.3
@@ -0,0 +1,67 @@
+.\" Copyright (c) 1997 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 1, 2006
+.Dt KRB5_PARSE_NAME 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_parse_name
+.Nd string to principal conversion
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fn krb5_parse_name "krb5_context context" "const char *name" "krb5_principal *principal"
+.Sh DESCRIPTION
+.Fn krb5_parse_name
+converts a string representation of a principal name to
+.Nm krb5_principal .
+The
+.Fa principal
+will point to allocated data that should be freed with
+.Fn krb5_free_principal .
+.Pp
+The string should consist of one or more name components separated with slashes
+.Pq Dq / ,
+optionally followed with an
+.Dq @
+and a realm name. A slash or @ may be contained in a name component by
+quoting it with a backslash
+.Pq Dq \e .
+A realm should not contain slashes or colons.
+.Sh SEE ALSO
+.Xr krb5_build_principal 3 ,
+.Xr krb5_free_principal 3 ,
+.Xr krb5_sname_to_principal 3 ,
+.Xr krb5_unparse_name 3
diff --git a/third_party/heimdal/lib/krb5/krb5_principal.3 b/third_party/heimdal/lib/krb5/krb5_principal.3
new file mode 100644
index 0000000..c8d2fec
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_principal.3
@@ -0,0 +1,371 @@
+.\" Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 1, 2006
+.Dt KRB5_PRINCIPAL 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_get_default_principal ,
+.Nm krb5_principal ,
+.Nm krb5_build_principal ,
+.Nm krb5_build_principal_ext ,
+.Nm krb5_build_principal_va ,
+.Nm krb5_build_principal_va_ext ,
+.Nm krb5_copy_principal ,
+.Nm krb5_free_principal ,
+.Nm krb5_make_principal ,
+.Nm krb5_parse_name ,
+.Nm krb5_parse_name_flags ,
+.Nm krb5_parse_nametype ,
+.Nm krb5_princ_set_realm ,
+.Nm krb5_principal_compare ,
+.Nm krb5_principal_compare_any_realm ,
+.Nm krb5_principal_get_comp_string ,
+.Nm krb5_principal_get_realm ,
+.Nm krb5_principal_get_type ,
+.Nm krb5_principal_match ,
+.Nm krb5_principal_set_type ,
+.Nm krb5_realm_compare ,
+.Nm krb5_sname_to_principal ,
+.Nm krb5_sock_to_principal ,
+.Nm krb5_unparse_name ,
+.Nm krb5_unparse_name_flags ,
+.Nm krb5_unparse_name_fixed ,
+.Nm krb5_unparse_name_fixed_flags ,
+.Nm krb5_unparse_name_fixed_short ,
+.Nm krb5_unparse_name_short
+.Nd Kerberos 5 principal handling functions
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Pp
+.Li krb5_principal ;
+.Ft void
+.Fn krb5_free_principal "krb5_context context" "krb5_principal principal"
+.Ft krb5_error_code
+.Fn krb5_parse_name "krb5_context context" "const char *name" "krb5_principal *principal"
+.Ft krb5_error_code
+.Fn krb5_parse_name_flags "krb5_context context" "const char *name" "int flags" "krb5_principal *principal"
+.Ft krb5_error_code
+.Fn "krb5_unparse_name" "krb5_context context" "krb5_const_principal principal" "char **name"
+.Ft krb5_error_code
+.Fn "krb5_unparse_name_flags" "krb5_context context" "krb5_const_principal principal" "int flags" "char **name"
+.Ft krb5_error_code
+.Fn krb5_unparse_name_fixed "krb5_context context" "krb5_const_principal principal" "char *name" "size_t len"
+.Ft krb5_error_code
+.Fn krb5_unparse_name_fixed_flags "krb5_context context" "krb5_const_principal principal" "int flags" "char *name" "size_t len"
+.Ft krb5_error_code
+.Fn "krb5_unparse_name_short" "krb5_context context" "krb5_const_principal principal" "char **name"
+.Ft krb5_error_code
+.Fn krb5_unparse_name_fixed_short "krb5_context context" "krb5_const_principal principal" "char *name" "size_t len"
+.Ft void
+.Fn krb5_princ_set_realm "krb5_context context" "krb5_principal principal" "krb5_realm *realm"
+.Ft krb5_error_code
+.Fn krb5_build_principal "krb5_context context" "krb5_principal *principal" "int rlen" "krb5_const_realm realm" "..."
+.Ft krb5_error_code
+.Fn krb5_build_principal_va "krb5_context context" "krb5_principal *principal" "int rlen" "krb5_const_realm realm" "va_list ap"
+.Ft krb5_error_code
+.Fn "krb5_build_principal_ext" "krb5_context context" "krb5_principal *principal" "int rlen" "krb5_const_realm realm" "..."
+.Ft krb5_error_code
+.Fn krb5_build_principal_va_ext "krb5_context context" "krb5_principal *principal" "int rlen" "krb5_const_realm realm" "va_list ap"
+.Ft krb5_error_code
+.Fn krb5_make_principal "krb5_context context" "krb5_principal *principal" "krb5_const_realm realm" "..."
+.Ft krb5_error_code
+.Fn krb5_copy_principal "krb5_context context" "krb5_const_principal inprinc" "krb5_principal *outprinc"
+.Ft krb5_boolean
+.Fn krb5_principal_compare "krb5_context context" "krb5_const_principal princ1" "krb5_const_principal princ2"
+.Ft krb5_boolean
+.Fn krb5_principal_compare_any_realm "krb5_context context" "krb5_const_principal princ1" "krb5_const_principal princ2"
+.Ft "const char *"
+.Fn krb5_principal_get_comp_string "krb5_context context" "krb5_const_principal principal" "unsigned int component"
+.Ft "const char *"
+.Fn krb5_principal_get_realm "krb5_context context" "krb5_const_principal principal"
+.Ft int
+.Fn krb5_principal_get_type "krb5_context context" "krb5_const_principal principal"
+.Ft krb5_boolean
+.Fn krb5_principal_match "krb5_context context" "krb5_const_principal principal" "krb5_const_principal pattern"
+.Ft void
+.Fn krb5_principal_set_type "krb5_context context" "krb5_principal principal" "int type"
+.Ft krb5_boolean
+.Fn krb5_realm_compare "krb5_context context" "krb5_const_principal princ1" "krb5_const_principal princ2"
+.Ft krb5_error_code
+.Fn krb5_sname_to_principal "krb5_context context" "const char *hostname" "const char *sname" "int32_t type" "krb5_principal *ret_princ"
+.Ft krb5_error_code
+.Fn krb5_sock_to_principal "krb5_context context" "int socket" "const char *sname" "int32_t type" "krb5_principal *principal"
+.Ft krb5_error_code
+.Fn krb5_get_default_principal "krb5_context context" "krb5_principal *princ"
+.Ft krb5_error_code
+.Fn krb5_parse_nametype "krb5_context context" "const char *str" "int32_t *type"
+.Sh DESCRIPTION
+.Li krb5_principal
+holds the name of a user or service in Kerberos.
+.Pp
+A principal has two parts, a
+.Li PrincipalName
+and a
+.Li realm .
+The PrincipalName consists of one or more components. In printed form,
+the components are separated by /.
+The PrincipalName also has a name-type.
+.Pp
+Examples of a principal are
+.Li nisse/root@EXAMPLE.COM
+and
+.Li host/datan.kth.se@KTH.SE .
+.Fn krb5_parse_name
+and
+.Fn krb5_parse_name_flags
+passes a principal name in
+.Fa name
+to the kerberos principal structure.
+.Fn krb5_parse_name_flags
+takes an extra
+.Fa flags
+argument the following flags can be passed in
+.Bl -tag -width Ds
+.It Dv KRB5_PRINCIPAL_PARSE_NO_REALM
+requires the input string to be without a realm, and no realm is
+stored in the
+.Fa principal
+return argument.
+.It Dv KRB5_PRINCIPAL_PARSE_REQUIRE_REALM
+requires the input string to with a realm.
+.El
+.Pp
+.Fn krb5_unparse_name
+and
+.Fn krb5_unparse_name_flags
+prints the principal
+.Fa princ
+to the string
+.Fa name .
+.Fa name
+should be freed with
+.Xr free 3 .
+To the
+.Fa flags
+argument the following flags can be passed in
+.Bl -tag -width Ds
+.It Dv KRB5_PRINCIPAL_UNPARSE_SHORT
+no realm if the realm is one of the local realms.
+.It Dv KRB5_PRINCIPAL_UNPARSE_NO_REALM
+never include any realm in the principal name.
+.It Dv KRB5_PRINCIPAL_UNPARSE_DISPLAY
+don't quote
+.El
+On failure
+.Fa name
+is set to
+.Dv NULL .
+.Fn krb5_unparse_name_fixed
+and
+.Fn krb5_unparse_name_fixed_flags
+behaves just like
+.Fn krb5_unparse ,
+but instead unparses the principal into a fixed size buffer.
+.Pp
+.Fn krb5_unparse_name_short
+just returns the principal without the realm if the principal is
+in the default realm. If the principal isn't, the full name is
+returned.
+.Fn krb5_unparse_name_fixed_short
+works just like
+.Fn krb5_unparse_name_short
+but on a fixed size buffer.
+.Pp
+.Fn krb5_build_principal
+builds a principal from the realm
+.Fa realm
+that has the length
+.Fa rlen .
+The following arguments form the components of the principal.
+The list of components is terminated with
+.Dv NULL .
+.Pp
+.Fn krb5_build_principal_va
+works like
+.Fn krb5_build_principal
+using vargs.
+.Pp
+.Fn krb5_build_principal_ext
+and
+.Fn krb5_build_principal_va_ext
+take a list of length-value pairs, the list is terminated with a zero
+length.
+.Pp
+.Fn krb5_make_principal
+works the same way as
+.Fn krb5_build_principal ,
+except it figures out the length of the realm itself.
+.Pp
+.Fn krb5_copy_principal
+makes a copy of a principal.
+The copy needs to be freed with
+.Fn krb5_free_principal .
+.Pp
+.Fn krb5_principal_compare
+compares the two principals, including realm of the principals and returns
+.Dv TRUE
+if they are the same and
+.Dv FALSE
+if not.
+.Pp
+.Fn krb5_principal_compare_any_realm
+works the same way as
+.Fn krb5_principal_compare
+but doesn't compare the realm component of the principal.
+.Pp
+.Fn krb5_realm_compare
+compares the realms of the two principals and returns
+.Dv TRUE
+is they are the same, and
+.Dv FALSE
+if not.
+.Pp
+.Fn krb5_principal_match
+matches a
+.Fa principal
+against a
+.Fa pattern .
+The pattern is a globbing expression, where each component (separated
+by /) is matched against the corresponding component of the principal.
+.Pp
+The
+.Fn krb5_principal_get_realm
+and
+.Fn krb5_principal_get_comp_string
+functions return parts of the
+.Fa principal ,
+either the realm or a specific component.
+Both functions return string pointers to data inside the principal, so
+they are valid only as long as the principal exists.
+.Pp
+The
+.Fa component
+argument to
+.Fn krb5_principal_get_comp_string
+is the index of the component to return, from zero to the total number of
+components minus one. If the index is out of range
+.Dv NULL
+is returned.
+.Pp
+.Fn krb5_principal_get_realm
+and
+.Fn krb5_principal_get_comp_string
+are replacements for
+.Fn krb5_princ_component
+and related macros, described as internal in the MIT API
+specification.
+Unlike the macros, these functions return strings, not
+.Dv krb5_data .
+A reason to return
+.Dv krb5_data
+was that it was believed that principal components could contain
+binary data, but this belief was unfounded, and it has been decided
+that principal components are infact UTF8, so it's safe to use zero
+terminated strings.
+.Pp
+It's generally not necessary to look at the components of a principal.
+.Pp
+.Fn krb5_principal_get_type
+and
+.Fn krb5_principal_set_type
+get and sets the name type for a principal.
+Name type handling is tricky and not often needed,
+don't use this unless you know what you do.
+.Pp
+.Fn krb5_sname_to_principal
+and
+.Fn krb5_sock_to_principal
+are for easy creation of
+.Dq service
+principals that can, for instance, be used to lookup a key in a keytab.
+For both functions the
+.Fa sname
+parameter will be used for the first component of the created principal.
+If
+.Fa sname
+is
+.Dv NULL ,
+.Dq host
+will be used instead.
+.Pp
+.Fn krb5_sname_to_principal
+will use the passed
+.Fa hostname
+for the second component.
+If
+.Fa type
+is
+.Dv KRB5_NT_SRV_HST
+this name will be looked up with
+.Fn gethostbyname .
+If
+.Fa hostname
+is
+.Dv NULL ,
+the local hostname will be used.
+.Pp
+.Fn krb5_sock_to_principal
+will use the
+.Dq sockname
+of the passed
+.Fa socket ,
+which should be a bound
+.Dv AF_INET
+or
+.Dv AF_INET6
+socket.
+There must be a mapping between the address and
+.Dq sockname .
+The function may try to resolve the name in DNS.
+.Pp
+.Fn krb5_get_default_principal
+tries to find out what's a reasonable default principal by looking at
+the environment it is running in.
+.Pp
+.Fn krb5_parse_nametype
+parses and returns the name type integer value in
+.Fa type .
+On failure the function returns an error code and set the error
+string.
+.\" .Sh EXAMPLES
+.Sh SEE ALSO
+.Xr krb5_config 3 ,
+.Xr krb5.conf 5
+.Sh BUGS
+You can not have a NUL in a component in some of the variable argument
+functions above.
+Until someone can give a good example of where it would be a good idea
+to have NUL's in a component, this will not be fixed.
diff --git a/third_party/heimdal/lib/krb5/krb5_rcache.3 b/third_party/heimdal/lib/krb5/krb5_rcache.3
new file mode 100644
index 0000000..5b121b8
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_rcache.3
@@ -0,0 +1,163 @@
+.\" Copyright (c) 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 1, 2006
+.Dt KRB5_RCACHE 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_rcache ,
+.Nm krb5_rc_close ,
+.Nm krb5_rc_default ,
+.Nm krb5_rc_default_name ,
+.Nm krb5_rc_default_type ,
+.Nm krb5_rc_destroy ,
+.Nm krb5_rc_expunge ,
+.Nm krb5_rc_get_lifespan ,
+.Nm krb5_rc_get_name ,
+.Nm krb5_rc_get_type ,
+.Nm krb5_rc_initialize ,
+.Nm krb5_rc_recover ,
+.Nm krb5_rc_resolve ,
+.Nm krb5_rc_resolve_full ,
+.Nm krb5_rc_resolve_type ,
+.Nm krb5_rc_store ,
+.Nm krb5_get_server_rcache
+.Nd Kerberos 5 replay cache
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Pp
+.Li "struct krb5_rcache;"
+.Pp
+.Ft krb5_error_code
+.Fo krb5_rc_close
+.Fa "krb5_context context"
+.Fa "krb5_rcache id"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_rc_default
+.Fa "krb5_context context"
+.Fa "krb5_rcache *id"
+.Fc
+.Ft "const char *"
+.Fo krb5_rc_default_name
+.Fa "krb5_context context"
+.Fc
+.Ft "const char *"
+.Fo krb5_rc_default_type
+.Fa "krb5_context context"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_rc_destroy
+.Fa "krb5_context context"
+.Fa "krb5_rcache id"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_rc_expunge
+.Fa "krb5_context context"
+.Fa "krb5_rcache id"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_rc_get_lifespan
+.Fa "krb5_context context"
+.Fa "krb5_rcache id"
+.Fa "krb5_deltat *auth_lifespan"
+.Fc
+.Ft "const char*"
+.Fo krb5_rc_get_name
+.Fa "krb5_context context"
+.Fa "krb5_rcache id"
+.Fc
+.Ft "const char*"
+.Fo "krb5_rc_get_type"
+.Fa "krb5_context context"
+.Fa "krb5_rcache id"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_rc_initialize
+.Fa "krb5_context context"
+.Fa "krb5_rcache id"
+.Fa "krb5_deltat auth_lifespan"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_rc_recover
+.Fa "krb5_context context"
+.Fa "krb5_rcache id"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_rc_resolve
+.Fa "krb5_context context"
+.Fa "krb5_rcache id"
+.Fa "const char *name"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_rc_resolve_full
+.Fa "krb5_context context"
+.Fa "krb5_rcache *id"
+.Fa "const char *string_name"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_rc_resolve_type
+.Fa "krb5_context context"
+.Fa "krb5_rcache *id"
+.Fa "const char *type"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_rc_store
+.Fa "krb5_context context"
+.Fa "krb5_rcache id"
+.Fa "krb5_donot_replay *rep"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_server_rcache
+.Fa "krb5_context context"
+.Fa "const krb5_data *piece"
+.Fa "krb5_rcache *id"
+.Fc
+.Sh DESCRIPTION
+The
+.Li krb5_rcache
+structure holds a storage element that is used for data manipulation.
+The structure contains no public accessible elements.
+.Pp
+.Fn krb5_rc_initialize
+Creates the reply cache
+.Fa id
+and sets it lifespan to
+.Fa auth_lifespan .
+If the cache already exists, the content is destroyed.
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5_data 3 ,
+.Xr kerberos 8
diff --git a/third_party/heimdal/lib/krb5/krb5_rd_error.3 b/third_party/heimdal/lib/krb5/krb5_rd_error.3
new file mode 100644
index 0000000..19c092e
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_rd_error.3
@@ -0,0 +1,98 @@
+.\" Copyright (c) 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd July 26, 2004
+.Dt KRB5_RD_ERROR 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_rd_error ,
+.Nm krb5_free_error ,
+.Nm krb5_free_error_contents ,
+.Nm krb5_error_from_rd_error
+.Nd parse, free and read error from KRB-ERROR message
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fo krb5_rd_error
+.Fa "krb5_context context"
+.Fa "const krb5_data *msg"
+.Fa "KRB_ERROR *result"
+.Fc
+.Ft void
+.Fo krb5_free_error
+.Fa "krb5_context context"
+.Fa "krb5_error *error"
+.Fc
+.Ft void
+.Fo krb5_free_error_contents
+.Fa "krb5_context context"
+.Fa "krb5_error *error"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_error_from_rd_error
+.Fa "krb5_context context"
+.Fa "const krb5_error *error"
+.Fa "const krb5_creds *creds"
+.Fc
+.Sh DESCRIPTION
+Usually applications never needs to parse and understand Kerberos
+error messages since higher level functions will parse and push up the
+error in the krb5_context.
+These functions are described for completeness.
+.Pp
+.Fn krb5_rd_error
+parses and returns the kerboeros error message, the structure should be freed with
+.Fn krb5_free_error_contents
+when the caller is done with the structure.
+.Pp
+.Fn krb5_free_error
+frees the content and the memory region holding the structure iself.
+.Pp
+.Fn krb5_free_error_contents
+free the content of the KRB-ERROR message.
+.Pp
+.Fn krb5_error_from_rd_error
+will parse the error message and set the error buffer in krb5_context
+to the error string passed back or the matching error code in the
+KRB-ERROR message.
+Caller should pick up the message with
+.Fn krb5_get_error_string 3
+(don't forget to free the returned string with
+.Fn krb5_free_error_string ) .
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5_set_error_string 3 ,
+.Xr krb5_get_error_string 3 ,
+.Xr krb5.conf 5
diff --git a/third_party/heimdal/lib/krb5/krb5_rd_safe.3 b/third_party/heimdal/lib/krb5/krb5_rd_safe.3
new file mode 100644
index 0000000..bb6294e
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_rd_safe.3
@@ -0,0 +1,81 @@
+.\" Copyright (c) 2003 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 1, 2006
+.Dt KRB5_RD_SAFE 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_rd_safe ,
+.Nm krb5_rd_priv
+.Nd verifies authenticity of messages
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Pp
+.Ft krb5_error_code
+.Fn krb5_rd_priv "krb5_context context" "krb5_auth_context auth_context" "const krb5_data *inbuf" "krb5_data *outbuf" "krb5_replay_data *outdata"
+.Ft krb5_error_code
+.Fn krb5_rd_safe "krb5_context context" "krb5_auth_context auth_context" "const krb5_data *inbuf" "krb5_data *outbuf" "krb5_replay_data *outdata"
+.Sh DESCRIPTION
+.Fn krb5_rd_safe
+and
+.Fn krb5_rd_priv
+parses
+.Li KRB-SAFE
+and
+.Li KRB-PRIV
+messages (as generated by
+.Xr krb5_mk_safe 3
+and
+.Xr krb5_mk_priv 3 )
+from
+.Fa inbuf
+and verifies its integrity. The user data part of the message in put
+in
+.Fa outbuf .
+The encryption state, including keyblocks and addresses, is taken from
+.Fa auth_context .
+If the
+.Dv KRB5_AUTH_CONTEXT_RET_SEQUENCE
+or
+.Dv KRB5_AUTH_CONTEXT_RET_TIME
+flags are set in the
+.Fa auth_context
+the sequence number and time are returned in the
+.Fa outdata
+parameter.
+.Sh SEE ALSO
+.Xr krb5_auth_con_init 3 ,
+.Xr krb5_mk_priv 3 ,
+.Xr krb5_mk_safe 3
diff --git a/third_party/heimdal/lib/krb5/krb5_set_default_realm.3 b/third_party/heimdal/lib/krb5/krb5_set_default_realm.3
new file mode 100644
index 0000000..867da30
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_set_default_realm.3
@@ -0,0 +1,164 @@
+.\" Copyright (c) 2003 - 2005 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd April 24, 2005
+.Dt KRB5_SET_DEFAULT_REALM 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_copy_host_realm ,
+.Nm krb5_free_host_realm ,
+.Nm krb5_get_default_realm ,
+.Nm krb5_get_default_realms ,
+.Nm krb5_get_host_realm ,
+.Nm krb5_set_default_realm
+.Nd default and host realm read and manipulation routines
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fo krb5_copy_host_realm
+.Fa "krb5_context context"
+.Fa "const krb5_realm *from"
+.Fa "krb5_realm **to"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_free_host_realm
+.Fa "krb5_context context"
+.Fa "krb5_realm *realmlist"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_default_realm
+.Fa "krb5_context context"
+.Fa "krb5_realm *realm"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_default_realms
+.Fa "krb5_context context"
+.Fa "krb5_realm **realm"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_host_realm
+.Fa "krb5_context context"
+.Fa "const char *host"
+.Fa "krb5_realm **realms"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_set_default_realm
+.Fa "krb5_context context"
+.Fa "const char *realm"
+.Fc
+.Sh DESCRIPTION
+.Fn krb5_copy_host_realm
+copies the list of realms from
+.Fa from
+to
+.Fa to .
+.Fa to
+should be freed by the caller using
+.Fa krb5_free_host_realm .
+.Pp
+.Fn krb5_free_host_realm
+frees all memory allocated by
+.Fa realmlist .
+.Pp
+.Fn krb5_get_default_realm
+returns the first default realm for this host.
+The realm returned should be freed with
+.Fn krb5_xfree .
+.Pp
+.Fn krb5_get_default_realms
+returns a
+.Dv NULL
+terminated list of default realms for this context.
+Realms returned by
+.Fn krb5_get_default_realms
+should be freed with
+.Fn krb5_free_host_realm .
+.Pp
+.Fn krb5_get_host_realm
+returns a
+.Dv NULL
+terminated list of realms for
+.Fa host
+by looking up the information in the
+.Li [domain_realm]
+in
+.Pa krb5.conf
+or in
+.Li DNS .
+If the mapping in
+.Li [domain_realm]
+results in the string
+.Li dns_locate ,
+DNS is used to lookup the realm.
+.Pp
+When using
+.Li DNS
+to a resolve the domain for the host a.b.c,
+.Fn krb5_get_host_realm
+looks for a
+.Dv TXT
+resource record named
+.Li _kerberos.a.b.c ,
+and if not found, it strips off the first component and tries a again
+(_kerberos.b.c) until it reaches the root.
+.Pp
+If there is no configuration or DNS information found,
+.Fn krb5_get_host_realm
+assumes it can use the domain part of the
+.Fa host
+to form a realm.
+Caller must free
+.Fa realmlist
+with
+.Fn krb5_free_host_realm .
+.Pp
+.Fn krb5_set_default_realm
+sets the default realm for the
+.Fa context .
+If
+.Dv NULL
+is used as a
+.Fa realm ,
+the
+.Li [libdefaults]default_realm
+stanza in
+.Pa krb5.conf
+is used.
+If there is no such stanza in the configuration file, the
+.Fn krb5_get_host_realm
+function is used to form a default realm.
+.Sh SEE ALSO
+.Xr free 3 ,
+.Xr krb5.conf 5
diff --git a/third_party/heimdal/lib/krb5/krb5_set_password.3 b/third_party/heimdal/lib/krb5/krb5_set_password.3
new file mode 100644
index 0000000..14cd299
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_set_password.3
@@ -0,0 +1,143 @@
+.\" Copyright (c) 2003 - 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd July 15, 2004
+.Dt KRB5_SET_PASSWORD 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_change_password ,
+.Nm krb5_set_password ,
+.Nm krb5_set_password_using_ccache ,
+.Nm krb5_passwd_result_to_string
+.Nd change password functions
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fo krb5_change_password
+.Fa "krb5_context context"
+.Fa "krb5_creds *creds"
+.Fa "char *newpw"
+.Fa "int *result_code"
+.Fa "krb5_data *result_code_string"
+.Fa "krb5_data *result_string"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_set_password
+.Fa "krb5_context context"
+.Fa "krb5_creds *creds"
+.Fa "char *newpw"
+.Fa "krb5_principal targprinc"
+.Fa "int *result_code"
+.Fa "krb5_data *result_code_string"
+.Fa "krb5_data *result_string"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_set_password_using_ccache
+.Fa "krb5_context context"
+.Fa "krb5_ccache ccache"
+.Fa "char *newpw"
+.Fa "krb5_principal targprinc"
+.Fa "int *result_code"
+.Fa "krb5_data *result_code_string"
+.Fa "krb5_data *result_string"
+.Fc
+.Ft "const char *"
+.Fo krb5_passwd_result_to_string
+.Fa "krb5_context context"
+.Fa "int result"
+.Fc
+.Sh DESCRIPTION
+These functions change the password for a given principal.
+.Pp
+.Fn krb5_set_password
+and
+.Fn krb5_set_password_using_ccache
+are the newer of the three functions, and use a newer version of the
+protocol (and also fall back to the older set-password protocol if the
+newer protocol doesn't work).
+.Pp
+.Fn krb5_change_password
+sets the password
+.Fa newpasswd
+for the client principal in
+.Fa creds .
+The server principal of creds must be
+.Li kadmin/changepw .
+.Pp
+.Fn krb5_set_password
+and
+.Fn krb5_set_password_using_ccache
+change the password for the principal
+.Fa targprinc .
+.Pp
+.Fn krb5_set_password
+requires that the credential for
+.Li kadmin/changepw@REALM
+is in
+.Fa creds .
+If the user caller isn't an administrator, this credential
+needs to be an initial credential, see
+.Xr krb5_get_init_creds 3
+how to get such credentials.
+.Pp
+.Fn krb5_set_password_using_ccache
+will get the credential from
+.Fa ccache .
+.Pp
+If
+.Fa targprinc
+is
+.Dv NULL ,
+.Fn krb5_set_password_using_ccache
+uses the the default principal in
+.Fa ccache
+and
+.Fn krb5_set_password
+uses the global the default principal.
+.Pp
+All three functions return an error in
+.Fa result_code
+and maybe an error string to print in
+.Fa result_string .
+.Pp
+.Fn krb5_passwd_result_to_string
+returns an human readable string describing the error code in
+.Fa result_code
+from the
+.Fn krb5_set_password
+functions.
+.Sh SEE ALSO
+.Xr krb5_ccache 3 ,
+.Xr krb5_init_context 3
diff --git a/third_party/heimdal/lib/krb5/krb5_string_to_key.3 b/third_party/heimdal/lib/krb5/krb5_string_to_key.3
new file mode 100644
index 0000000..c77d459
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_string_to_key.3
@@ -0,0 +1,156 @@
+.\" Copyright (c) 2004 - 2006 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd July 10, 2006
+.Dt KRB5_STRING_TO_KEY 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_string_to_key ,
+.Nm krb5_string_to_key_data ,
+.Nm krb5_string_to_key_data_salt ,
+.Nm krb5_string_to_key_data_salt_opaque ,
+.Nm krb5_string_to_key_salt ,
+.Nm krb5_string_to_key_salt_opaque ,
+.Nm krb5_get_pw_salt ,
+.Nm krb5_free_salt
+.Nd turns a string to a Kerberos key
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fo krb5_string_to_key
+.Fa "krb5_context context"
+.Fa "krb5_enctype enctype"
+.Fa "const char *password"
+.Fa "krb5_principal principal"
+.Fa "krb5_keyblock *key"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_string_to_key_data
+.Fa "krb5_context context"
+.Fa "krb5_enctype enctype"
+.Fa "krb5_data password"
+.Fa "krb5_principal principal"
+.Fa "krb5_keyblock *key"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_string_to_key_data_salt
+.Fa "krb5_context context"
+.Fa "krb5_enctype enctype"
+.Fa "krb5_data password"
+.Fa "krb5_salt salt"
+.Fa "krb5_keyblock *key"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_string_to_key_data_salt_opaque
+.Fa "krb5_context context"
+.Fa "krb5_enctype enctype"
+.Fa "krb5_data password"
+.Fa "krb5_salt salt"
+.Fa "krb5_data opaque"
+.Fa "krb5_keyblock *key"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_string_to_key_salt
+.Fa "krb5_context context"
+.Fa "krb5_enctype enctype"
+.Fa "const char *password"
+.Fa "krb5_salt salt"
+.Fa "krb5_keyblock *key"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_string_to_key_salt_opaque
+.Fa "krb5_context context"
+.Fa "krb5_enctype enctype"
+.Fa "const char *password"
+.Fa "krb5_salt salt"
+.Fa "krb5_data opaque"
+.Fa "krb5_keyblock *key"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_get_pw_salt
+.Fa "krb5_context context"
+.Fa "krb5_const_principal principal"
+.Fa "krb5_salt *salt"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_free_salt
+.Fa "krb5_context context"
+.Fa "krb5_salt salt"
+.Fc
+.Sh DESCRIPTION
+The string to key functions convert a string to a kerberos key.
+.Pp
+.Fn krb5_string_to_key_data_salt_opaque
+is the function that does all the work, the rest of the functions are
+just wrappers around
+.Fn krb5_string_to_key_data_salt_opaque
+that calls it with default values.
+.Pp
+.Fn krb5_string_to_key_data_salt_opaque
+transforms the
+.Fa password
+with the given salt-string
+.Fa salt
+and the opaque, encryption type specific parameter
+.Fa opaque
+to a encryption key
+.Fa key
+according to the string to key function associated with
+.Fa enctype .
+.Pp
+The
+.Fa key
+should be freed with
+.Fn krb5_free_keyblock_contents .
+.Pp
+If one of the functions that doesn't take a
+.Li krb5_salt
+as it argument
+.Fn krb5_get_pw_salt
+is used to get the salt value.
+.Pp
+.Fn krb5_get_pw_salt
+get the default password salt for a principal, use
+.Fn krb5_free_salt
+to free the salt when done.
+.Pp
+.Fn krb5_free_salt
+frees the content of
+.Fa salt .
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5_data 3 ,
+.Xr krb5_keyblock 3 ,
+.Xr kerberos 8
diff --git a/third_party/heimdal/lib/krb5/krb5_timeofday.3 b/third_party/heimdal/lib/krb5/krb5_timeofday.3
new file mode 100644
index 0000000..f491c6b
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_timeofday.3
@@ -0,0 +1,118 @@
+.\" $Id$
+.\"
+.\" Copyright (c) 2001, 2003, 2006 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd September 16, 2006
+.Dt KRB5_TIMEOFDAY 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_timeofday ,
+.Nm krb5_set_real_time ,
+.Nm krb5_us_timeofday ,
+.Nm krb5_format_time ,
+.Nm krb5_string_to_deltat
+.Nd Kerberos 5 time handling functions
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Pp
+.Li krb5_timestamp ;
+.Pp
+.Li krb5_deltat ;
+.Ft krb5_error_code
+.Fo krb5_set_real_time
+.Fa "krb5_context context"
+.Fa "krb5_timestamp sec"
+.Fa "int32_t usec"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_timeofday
+.Fa "krb5_context context"
+.Fa "krb5_timestamp *timeret"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_us_timeofday
+.Fa "krb5_context context"
+.Fa "krb5_timestamp *sec"
+.Fa "int32_t *usec"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_format_time
+.Fa "krb5_context context"
+.Fa "time_t t"
+.Fa "char *s"
+.Fa "size_t len"
+.Fa "krb5_boolean include_time"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_string_to_deltat
+.Fa "const char *string"
+.Fa "krb5_deltat *deltat"
+.Fc
+.Sh DESCRIPTION
+.Nm krb5_set_real_time
+sets the absolute time that the caller knows the KDC has.
+With this the Kerberos library can calculate the relative
+difference between the KDC time and the local system time and store it
+in the
+.Fa context .
+With this information the Kerberos library can adjust all time stamps
+in Kerberos packages.
+.Pp
+.Fn krb5_timeofday
+returns the current time, but adjusted with the time difference
+between the local host and the KDC.
+.Fn krb5_us_timeofday
+also returns microseconds.
+.Pp
+.Nm krb5_format_time
+formats the time
+.Fa t
+into the string
+.Fa s
+of length
+.Fa len .
+If
+.Fa include_time
+is set, the time is set include_time.
+.Pp
+.Nm krb5_string_to_deltat
+parses delta time
+.Fa string
+into
+.Fa deltat .
+.Sh SEE ALSO
+.Xr gettimeofday 2 ,
+.Xr krb5 3
diff --git a/third_party/heimdal/lib/krb5/krb5_verify_init_creds.3 b/third_party/heimdal/lib/krb5/krb5_verify_init_creds.3
new file mode 100644
index 0000000..0fe9582
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_verify_init_creds.3
@@ -0,0 +1,103 @@
+.\" Copyright (c) 2003 - 2006 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 1, 2006
+.Dt KRB5_VERIFY_INIT_CREDS 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_verify_init_creds_opt_init ,
+.Nm krb5_verify_init_creds_opt_set_ap_req_nofail ,
+.Nm krb5_verify_init_creds
+.Nd "verifies a credential cache is correct by using a local keytab"
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Pp
+.Li "struct krb5_verify_init_creds_opt;"
+.Ft void
+.Fo krb5_verify_init_creds_opt_init
+.Fa "krb5_verify_init_creds_opt *options"
+.Fc
+.Ft void
+.Fo krb5_verify_init_creds_opt_set_ap_req_nofail
+.Fa "krb5_verify_init_creds_opt *options"
+.Fa "int ap_req_nofail"
+.Fc
+.Ft krb5_error_code
+.Fo krb5_verify_init_creds
+.Fa "krb5_context context"
+.Fa "krb5_creds *creds"
+.Fa "krb5_principal ap_req_server"
+.Fa "krb5_ccache *ccache"
+.Fa "krb5_verify_init_creds_opt *options"
+.Fc
+.Sh DESCRIPTION
+The
+.Nm krb5_verify_init_creds
+function verifies the initial tickets with the local keytab to make
+sure the response of the KDC was spoof-ed.
+.Pp
+.Nm krb5_verify_init_creds
+will use principal
+.Fa ap_req_server
+from the local keytab, if
+.Dv NULL
+is passed in, the code will guess the local hostname and use that to
+form host/hostname/GUESSED-REALM-FOR-HOSTNAME.
+.Fa creds
+is the credential that
+.Nm krb5_verify_init_creds
+should verify.
+If
+.Fa ccache
+is given
+.Fn krb5_verify_init_creds
+stores all credentials it fetched from the KDC there, otherwise it
+will use a memory credential cache that is destroyed when done.
+.Pp
+.Fn krb5_verify_init_creds_opt_init
+cleans the the structure, must be used before trying to pass it in to
+.Fn krb5_verify_init_creds .
+.Pp
+.Fn krb5_verify_init_creds_opt_set_ap_req_nofail
+controls controls the behavior if
+.Fa ap_req_server
+doesn't exists in the local keytab or in the KDC's database, if it's
+true, the error will be ignored. Note that this use is possible
+insecure.
+.Sh SEE ALSO
+.Xr krb5 3 ,
+.Xr krb5_get_init_creds 3 ,
+.Xr krb5_verify_user 3 ,
+.Xr krb5.conf 5
diff --git a/third_party/heimdal/lib/krb5/krb5_verify_user.3 b/third_party/heimdal/lib/krb5/krb5_verify_user.3
new file mode 100644
index 0000000..a32986d
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb5_verify_user.3
@@ -0,0 +1,241 @@
+.\" Copyright (c) 2001 - 2006 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd May 1, 2006
+.Dt KRB5_VERIFY_USER 3
+.Os HEIMDAL
+.Sh NAME
+.Nm krb5_verify_user ,
+.Nm krb5_verify_user_lrealm ,
+.Nm krb5_verify_user_opt ,
+.Nm krb5_verify_opt_init ,
+.Nm krb5_verify_opt_alloc ,
+.Nm krb5_verify_opt_free ,
+.Nm krb5_verify_opt_set_ccache ,
+.Nm krb5_verify_opt_set_flags ,
+.Nm krb5_verify_opt_set_service ,
+.Nm krb5_verify_opt_set_secure ,
+.Nm krb5_verify_opt_set_keytab
+.Nd Heimdal password verifying functions
+.Sh LIBRARY
+Kerberos 5 Library (libkrb5, -lkrb5)
+.Sh SYNOPSIS
+.In krb5.h
+.Ft krb5_error_code
+.Fn "krb5_verify_user" "krb5_context context" " krb5_principal principal" "krb5_ccache ccache" "const char *password" "krb5_boolean secure" "const char *service"
+.Ft krb5_error_code
+.Fn "krb5_verify_user_lrealm" "krb5_context context" "krb5_principal principal" "krb5_ccache ccache" "const char *password" "krb5_boolean secure" "const char *service"
+.Ft void
+.Fn krb5_verify_opt_init "krb5_verify_opt *opt"
+.Ft void
+.Fn krb5_verify_opt_alloc "krb5_verify_opt **opt"
+.Ft void
+.Fn krb5_verify_opt_free "krb5_verify_opt *opt"
+.Ft void
+.Fn krb5_verify_opt_set_ccache "krb5_verify_opt *opt" "krb5_ccache ccache"
+.Ft void
+.Fn krb5_verify_opt_set_keytab "krb5_verify_opt *opt" "krb5_keytab keytab"
+.Ft void
+.Fn krb5_verify_opt_set_secure "krb5_verify_opt *opt" "krb5_boolean secure"
+.Ft void
+.Fn krb5_verify_opt_set_service "krb5_verify_opt *opt" "const char *service"
+.Ft void
+.Fn krb5_verify_opt_set_flags "krb5_verify_opt *opt" "unsigned int flags"
+.Ft krb5_error_code
+.Fo krb5_verify_user_opt
+.Fa "krb5_context context"
+.Fa "krb5_principal principal"
+.Fa "const char *password"
+.Fa "krb5_verify_opt *opt"
+.Fc
+.Sh DESCRIPTION
+The
+.Nm krb5_verify_user
+function verifies the password supplied by a user.
+The principal whose password will be verified is specified in
+.Fa principal .
+New tickets will be obtained as a side-effect and stored in
+.Fa ccache
+(if
+.Dv NULL ,
+the default ccache is used).
+.Fn krb5_verify_user
+will call
+.Fn krb5_cc_initialize
+on the given
+.Fa ccache ,
+so
+.Fa ccache
+must only initialized with
+.Fn krb5_cc_resolve
+or
+.Fn krb5_cc_gen_new .
+If the password is not supplied in
+.Fa password
+(and is given as
+.Dv NULL )
+the user will be prompted for it.
+If
+.Fa secure
+the ticket will be verified against the locally stored service key
+.Fa service
+(by default
+.Ql host
+if given as
+.Dv NULL
+).
+.Pp
+The
+.Fn krb5_verify_user_lrealm
+function does the same, except that it ignores the realm in
+.Fa principal
+and tries all the local realms (see
+.Xr krb5.conf 5 ) .
+After a successful return, the principal is set to the authenticated
+realm. If the call fails, the principal will not be meaningful, and
+should only be freed with
+.Xr krb5_free_principal 3 .
+.Pp
+.Fn krb5_verify_opt_alloc
+and
+.Fn krb5_verify_opt_free
+allocates and frees a
+.Li krb5_verify_opt .
+You should use the the alloc and free function instead of allocation
+the structure yourself, this is because in a future release the
+structure wont be exported.
+.Pp
+.Fn krb5_verify_opt_init
+resets all opt to default values.
+.Pp
+None of the krb5_verify_opt_set function makes a copy of the data
+structure that they are called with. It's up the caller to free them
+after the
+.Fn krb5_verify_user_opt
+is called.
+.Pp
+.Fn krb5_verify_opt_set_ccache
+sets the
+.Fa ccache
+that user of
+.Fa opt
+will use. If not set, the default credential cache will be used.
+.Pp
+.Fn krb5_verify_opt_set_keytab
+sets the
+.Fa keytab
+that user of
+.Fa opt
+will use. If not set, the default keytab will be used.
+.Pp
+.Fn krb5_verify_opt_set_secure
+if
+.Fa secure
+if true, the password verification will require that the ticket will
+be verified against the locally stored service key. If not set,
+default value is true.
+.Pp
+.Fn krb5_verify_opt_set_service
+sets the
+.Fa service
+principal that user of
+.Fa opt
+will use. If not set, the
+.Ql host
+service will be used.
+.Pp
+.Fn krb5_verify_opt_set_flags
+sets
+.Fa flags
+that user of
+.Fa opt
+will use.
+If the flag
+.Dv KRB5_VERIFY_LREALMS
+is used, the
+.Fa principal
+will be modified like
+.Fn krb5_verify_user_lrealm
+modifies it.
+.Pp
+.Fn krb5_verify_user_opt
+function verifies the
+.Fa password
+supplied by a user.
+The principal whose password will be verified is specified in
+.Fa principal .
+Options the to the verification process is pass in in
+.Fa opt .
+.Sh EXAMPLES
+Here is a example program that verifies a password. it uses the
+.Ql host/`hostname`
+service principal in
+.Pa krb5.keytab .
+.Bd -literal
+#include <krb5.h>
+
+int
+main(int argc, char **argv)
+{
+ char *user;
+ krb5_error_code error;
+ krb5_principal princ;
+ krb5_context context;
+
+ if (argc != 2)
+ errx(1, "usage: verify_passwd <principal-name>");
+
+ user = argv[1];
+
+ if (krb5_init_context(&context) < 0)
+ errx(1, "krb5_init_context");
+
+ if ((error = krb5_parse_name(context, user, &princ)) != 0)
+ krb5_err(context, 1, error, "krb5_parse_name");
+
+ error = krb5_verify_user(context, princ, NULL, NULL, TRUE, NULL);
+ if (error)
+ krb5_err(context, 1, error, "krb5_verify_user");
+
+ return 0;
+}
+.Ed
+.Sh SEE ALSO
+.Xr krb5_cc_gen_new 3 ,
+.Xr krb5_cc_initialize 3 ,
+.Xr krb5_cc_resolve 3 ,
+.Xr krb5_err 3 ,
+.Xr krb5_free_principal 3 ,
+.Xr krb5_init_context 3 ,
+.Xr krb5_kt_default 3 ,
+.Xr krb5.conf 5
diff --git a/third_party/heimdal/lib/krb5/krb_err.et b/third_party/heimdal/lib/krb5/krb_err.et
new file mode 100644
index 0000000..f7dbb6c
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krb_err.et
@@ -0,0 +1,63 @@
+#
+# Error messages for the krb4 library
+#
+# This might look like a com_err file, but is not
+#
+id "$Id: krb_err.et,v 1.7 1998/03/29 14:19:52 bg Exp $"
+
+error_table krb
+
+prefix KRB4ET
+ec KSUCCESS, "Kerberos 4 successful"
+ec KDC_NAME_EXP, "Kerberos 4 principal expired"
+ec KDC_SERVICE_EXP, "Kerberos 4 service expired"
+ec KDC_AUTH_EXP, "Kerberos 4 auth expired"
+ec KDC_PKT_VER, "Incorrect Kerberos 4 master key version"
+ec KDC_P_MKEY_VER, "Incorrect Kerberos 4 master key version"
+ec KDC_S_MKEY_VER, "Incorrect Kerberos 4 master key version"
+ec KDC_BYTE_ORDER, "Kerberos 4 byte order unknown"
+ec KDC_PR_UNKNOWN, "Kerberos 4 principal unknown"
+ec KDC_PR_N_UNIQUE, "Kerberos 4 principal not unique"
+ec KDC_NULL_KEY, "Kerberos 4 principal has null key"
+index 20
+ec KDC_GEN_ERR, "Generic error from KDC (Kerberos 4)"
+ec GC_TKFIL, "Can't read Kerberos 4 ticket file"
+ec GC_NOTKT, "Can't find Kerberos 4 ticket or TGT"
+index 26
+ec MK_AP_TGTEXP, "Kerberos 4 TGT Expired"
+index 31
+ec RD_AP_UNDEC, "Kerberos 4: Can't decode authenticator"
+ec RD_AP_EXP, "Kerberos 4 ticket expired"
+ec RD_AP_NYV, "Kerberos 4 ticket not yet valid"
+ec RD_AP_REPEAT, "Kerberos 4: Repeated request"
+ec RD_AP_NOT_US, "The Kerberos 4 ticket isn't for us"
+ec RD_AP_INCON, "Kerberos 4 request inconsistent"
+ec RD_AP_TIME, "Kerberos 4: delta_t too big"
+ec RD_AP_BADD, "Kerberos 4: incorrect net address"
+ec RD_AP_VERSION, "Kerberos protocol not version 4"
+ec RD_AP_MSG_TYPE, "Kerberos 4: invalid msg type"
+ec RD_AP_MODIFIED, "Kerberos 4: message stream modified"
+ec RD_AP_ORDER, "Kerberos 4: message out of order"
+ec RD_AP_UNAUTHOR, "Kerberos 4: unauthorized request"
+index 51
+ec GT_PW_NULL, "Kerberos 4: current PW is null"
+ec GT_PW_BADPW, "Kerberos 4: Incorrect current password"
+ec GT_PW_PROT, "Kerberos 4 protocol error"
+ec GT_PW_KDCERR, "Error returned by KDC (Kerberos 4)"
+ec GT_PW_NULLTKT, "Null Kerberos 4 ticket returned by KDC"
+ec SKDC_RETRY, "Kerberos 4: Retry count exceeded"
+ec SKDC_CANT, "Kerberos 4: Can't send request"
+index 61
+ec INTK_W_NOTALL, "Kerberos 4: not all tickets returned"
+ec INTK_BADPW, "Kerberos 4: incorrect password"
+ec INTK_PROT, "Kerberos 4: Protocol Error"
+index 70
+ec INTK_ERR, "Other error in Kerberos 4"
+ec AD_NOTGT, "Don't have Kerberos 4 ticket-granting ticket"
+index 76
+ec NO_TKT_FIL, "No Kerberos 4 ticket file found"
+ec TKT_FIL_ACC, "Couldn't access Kerberos 4 ticket file"
+ec TKT_FIL_LCK, "Couldn't lock Kerberos 4 ticket file"
+ec TKT_FIL_FMT, "Bad Kerberos 4 ticket file format"
+ec TKT_FIL_INI, "Kerberos 4: tf_init not called first"
+ec KNAME_FMT, "Bad Kerberos 4 name format"
diff --git a/third_party/heimdal/lib/krb5/krbhst-test.c b/third_party/heimdal/lib/krb5/krbhst-test.c
new file mode 100644
index 0000000..cd388ec
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krbhst-test.c
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2001 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#include <err.h>
+#include <getarg.h>
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "[realms ...]");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_error_code ret;
+ int i, j;
+ krb5_context context;
+ int types[] = {KRB5_KRBHST_KDC, KRB5_KRBHST_ADMIN, KRB5_KRBHST_CHANGEPW,
+ KRB5_KRBHST_KRB524};
+ const char *type_str[] = {"kdc", "admin", "changepw", "krb524"};
+ int optidx = 0;
+
+ setprogname (argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ krb5_err(NULL, 1, ret, "Failed to initialize context");
+ for(i = 0; i < argc; i++) {
+ krb5_krbhst_handle handle;
+ char host[MAXHOSTNAMELEN];
+
+ for (j = 0; j < sizeof(types)/sizeof(*types); ++j) {
+ printf ("%s for %s:\n", type_str[j], argv[i]);
+
+ ret = krb5_krbhst_init(context, argv[i], types[j], &handle);
+ if (ret)
+ krb5_err(context, 1, ret, "Could not init krbhst iterator");
+ while ((ret = krb5_krbhst_next_as_string(context, handle, host,
+ sizeof(host))) == 0)
+ printf("\thost: %s\n", host);
+ krb5_krbhst_reset(context, handle);
+ printf("\n");
+ if (ret)
+ krb5_err(context, 1, ret, "Could not iterate all krbhst");
+ }
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/krbhst.c b/third_party/heimdal/lib/krb5/krbhst.c
new file mode 100644
index 0000000..3688d6a
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krbhst.c
@@ -0,0 +1,1275 @@
+/*
+ * Copyright (c) 2001 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include <resolve.h>
+#include "locate_plugin.h"
+
+static int
+string_to_proto(const char *string)
+{
+ if(strcasecmp(string, "udp") == 0)
+ return KRB5_KRBHST_UDP;
+ else if(strcasecmp(string, "tcp") == 0)
+ return KRB5_KRBHST_TCP;
+ else if(strcasecmp(string, "http") == 0)
+ return KRB5_KRBHST_HTTP;
+ return -1;
+}
+
+static int
+is_invalid_tld_srv_target(const char *target)
+{
+ return (strncmp("your-dns-needs-immediate-attention.",
+ target, 35) == 0
+ && strchr(&target[35], '.') == NULL);
+}
+
+/*
+ * set `res' and `count' to the result of looking up SRV RR in DNS for
+ * `proto', `proto', `realm' using `dns_type'.
+ * if `port' != 0, force that port number
+ */
+
+static krb5_error_code
+srv_find_realm(krb5_context context, krb5_krbhst_info ***res, int *count,
+ const char *realm, const char *dns_type, const char *sitename,
+ const char *proto, const char *service, int port)
+{
+ char domain[1024];
+ struct rk_dns_reply *r;
+ struct rk_resource_record *rr;
+ int num_srv;
+ int proto_num;
+ int def_port;
+
+ *res = NULL;
+ *count = 0;
+
+ proto_num = string_to_proto(proto);
+ if(proto_num < 0) {
+ krb5_set_error_message(context, EINVAL,
+ N_("unknown protocol `%s' to lookup", ""),
+ proto);
+ return EINVAL;
+ }
+
+ if(proto_num == KRB5_KRBHST_HTTP)
+ def_port = ntohs(krb5_getportbyname (context, "http", "tcp", 80));
+ else if(port == 0)
+ def_port = ntohs(krb5_getportbyname (context, service, proto, 88));
+ else
+ def_port = port;
+
+ if (sitename)
+ snprintf(domain, sizeof(domain), "_%s._%s.%s._sites.%s.",
+ service, proto, sitename, realm);
+ else
+ snprintf(domain, sizeof(domain), "_%s._%s.%s.", service, proto, realm);
+
+ r = rk_dns_lookup(domain, dns_type);
+ if(r == NULL) {
+ _krb5_debug(context, 0,
+ "DNS lookup failed domain: %s", domain);
+ return KRB5_KDC_UNREACH;
+ }
+
+ for(num_srv = 0, rr = r->head; rr; rr = rr->next)
+ if(rr->type == rk_ns_t_srv) {
+ if (num_srv >= INT_MAX) {
+ rk_dns_free_data(r);
+ return KRB5_KDC_UNREACH;
+ }
+ if (num_srv >= SIZE_MAX / sizeof(**res)) {
+ rk_dns_free_data(r);
+ return KRB5_KDC_UNREACH;
+ }
+ num_srv++;
+ }
+
+ if (num_srv == 0) {
+ _krb5_debug(context, 0,
+ "DNS SRV RR lookup domain nodata: %s", domain);
+ rk_dns_free_data(r);
+ return KRB5_KDC_UNREACH;
+ }
+
+ *res = malloc(num_srv * sizeof(**res));
+ if(*res == NULL) {
+ rk_dns_free_data(r);
+ return krb5_enomem(context);
+ }
+
+ rk_dns_srv_order(r);
+
+ for(num_srv = 0, rr = r->head; rr; rr = rr->next)
+ if(rr->type == rk_ns_t_srv) {
+ krb5_krbhst_info *hi = NULL;
+ size_t len;
+ int invalid_tld = 1;
+
+ /* Test for top-level domain controlled interruptions */
+ if (!is_invalid_tld_srv_target(rr->u.srv->target)) {
+ invalid_tld = 0;
+ len = strlen(rr->u.srv->target);
+ hi = calloc(1, sizeof(*hi) + len);
+ }
+ if(hi == NULL) {
+ rk_dns_free_data(r);
+ while(--num_srv >= 0)
+ free((*res)[num_srv]);
+ free(*res);
+ *res = NULL;
+ if (invalid_tld) {
+ krb5_warnx(context,
+ "Domain lookup failed: "
+ "Realm %s needs immediate attention "
+ "see https://icann.org/namecollision",
+ realm);
+ return KRB5_KDC_UNREACH;
+ }
+ return krb5_enomem(context);
+ }
+ (*res)[num_srv++] = hi;
+
+ hi->proto = proto_num;
+
+ hi->def_port = def_port;
+ if (port != 0)
+ hi->port = port;
+ else
+ hi->port = rr->u.srv->port;
+
+ strlcpy(hi->hostname, rr->u.srv->target, len + 1);
+ }
+
+ *count = num_srv;
+
+ rk_dns_free_data(r);
+ return 0;
+}
+
+
+struct krb5_krbhst_data {
+ const char *config_param;
+ const char *srv_label;
+ char *realm;
+ unsigned int flags;
+ int def_port;
+ int port; /* hardwired port number if != 0 */
+#define KD_CONFIG 0x0001
+#define KD_SRV_UDP 0x0002
+#define KD_SRV_TCP 0x0004
+#define KD_SITE_SRV_UDP 0x0008
+#define KD_SITE_SRV_TCP 0x0010
+#define KD_SRV_HTTP 0x0020
+#define KD_SRV_KKDCP 0x0040
+#define KD_FALLBACK 0x0080
+#define KD_CONFIG_EXISTS 0x0100
+#define KD_LARGE_MSG 0x0200
+#define KD_PLUGIN 0x0400
+#define KD_HOSTNAMES 0x0800
+ krb5_error_code (*get_next)(krb5_context, struct krb5_krbhst_data *,
+ krb5_krbhst_info**);
+
+ char *hostname;
+ char *sitename;
+ unsigned int fallback_count;
+
+ struct krb5_krbhst_info *hosts, **index, **end;
+};
+
+static krb5_boolean
+krbhst_empty(const struct krb5_krbhst_data *kd)
+{
+ return kd->index == &kd->hosts;
+}
+
+/*
+ * Return the default protocol for the `kd' (either TCP or UDP)
+ */
+
+static int
+krbhst_get_default_proto(struct krb5_krbhst_data *kd)
+{
+ if (kd->flags & KD_LARGE_MSG)
+ return KRB5_KRBHST_TCP;
+ return KRB5_KRBHST_UDP;
+}
+
+static int
+krbhst_get_default_port(struct krb5_krbhst_data *kd)
+{
+ return kd->def_port;
+}
+
+/*
+ *
+ */
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+_krb5_krbhst_get_realm(krb5_krbhst_handle handle)
+{
+ return handle->realm;
+}
+
+/*
+ * parse `spec' into a krb5_krbhst_info, defaulting the port to `def_port'
+ * and forcing it to `port' if port != 0
+ */
+
+static struct krb5_krbhst_info*
+parse_hostspec(krb5_context context, struct krb5_krbhst_data *kd,
+ const char *spec, int def_port, int port)
+{
+ const char *p = spec, *q;
+ struct krb5_krbhst_info *hi;
+
+ hi = calloc(1, sizeof(*hi) + strlen(spec));
+ if(hi == NULL)
+ return NULL;
+
+ hi->proto = krbhst_get_default_proto(kd);
+
+ if(strncmp(p, "http://", 7) == 0){
+ hi->proto = KRB5_KRBHST_HTTP;
+ p += 7;
+ } else if(strncmp(p, "http/", 5) == 0) {
+ hi->proto = KRB5_KRBHST_HTTP;
+ p += 5;
+ def_port = ntohs(krb5_getportbyname (context, "http", "tcp", 80));
+ }else if(strncmp(p, "tcp/", 4) == 0){
+ hi->proto = KRB5_KRBHST_TCP;
+ p += 4;
+ } else if(strncmp(p, "udp/", 4) == 0) {
+ hi->proto = KRB5_KRBHST_UDP;
+ p += 4;
+ }
+
+ if (p[0] == '[' && (q = strchr(p, ']')) != NULL) {
+ /* if address looks like [foo:bar] or [foo:bar]: its a ipv6
+ adress, strip of [] */
+ memcpy(hi->hostname, &p[1], q - p - 1);
+ hi->hostname[q - p - 1] = '\0';
+ p = q + 1;
+ /* get trailing : */
+ if (p[0] == ':')
+ p++;
+ } else if(strsep_copy(&p, ":", hi->hostname, strlen(spec) + 1) < 0) {
+ /* copy everything before : */
+ free(hi);
+ return NULL;
+ }
+ /* get rid of trailing /, and convert to lower case */
+ hi->hostname[strcspn(hi->hostname, "/")] = '\0';
+ strlwr(hi->hostname);
+
+ hi->port = hi->def_port = def_port;
+ if(p != NULL && p[0]) {
+ char *end;
+ hi->port = strtol(p, &end, 0);
+ if(end == p) {
+ free(hi);
+ return NULL;
+ }
+ }
+ if (port)
+ hi->port = port;
+ return hi;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_free_krbhst_info(krb5_krbhst_info *hi)
+{
+ if (hi->ai != NULL)
+ freeaddrinfo(hi->ai);
+ free(hi);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_krbhost_info_move(krb5_context context,
+ krb5_krbhst_info *from,
+ krb5_krbhst_info **to)
+{
+ size_t hostnamelen = strlen(from->hostname);
+ /* trailing NUL is included in structure */
+ *to = calloc(1, sizeof(**to) + hostnamelen);
+ if (*to == NULL)
+ return krb5_enomem(context);
+
+ (*to)->proto = from->proto;
+ (*to)->port = from->port;
+ (*to)->def_port = from->def_port;
+ (*to)->ai = from->ai;
+ from->ai = NULL;
+ (*to)->next = NULL;
+ memcpy((*to)->hostname, from->hostname, hostnamelen + 1);
+ return 0;
+}
+
+
+static void
+append_host_hostinfo(struct krb5_krbhst_data *kd, struct krb5_krbhst_info *host)
+{
+ struct krb5_krbhst_info *h;
+
+ for(h = kd->hosts; h; h = h->next)
+ if(h->proto == host->proto &&
+ h->port == host->port &&
+ strcmp(h->hostname, host->hostname) == 0) {
+ _krb5_free_krbhst_info(host);
+ return;
+ }
+ *kd->end = host;
+ kd->end = &host->next;
+}
+
+static krb5_error_code
+append_host_string(krb5_context context, struct krb5_krbhst_data *kd,
+ const char *host, int def_port, int port)
+{
+ struct krb5_krbhst_info *hi;
+
+ hi = parse_hostspec(context, kd, host, def_port, port);
+ if(hi == NULL)
+ return krb5_enomem(context);
+
+ append_host_hostinfo(kd, hi);
+ return 0;
+}
+
+/*
+ * return a readable representation of `host' in `hostname, hostlen'
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_krbhst_format_string(krb5_context context, const krb5_krbhst_info *host,
+ char *hostname, size_t hostlen)
+{
+ const char *proto = "";
+ if(host->proto == KRB5_KRBHST_TCP)
+ proto = "tcp/";
+ else if(host->proto == KRB5_KRBHST_HTTP)
+ proto = "http://";
+ if (host->port != host->def_port)
+ snprintf(hostname, hostlen, "%s%s:%d", proto, host->hostname, (int)host->port);
+ else
+ snprintf(hostname, hostlen, "%s%s", proto, host->hostname);
+ return 0;
+}
+
+/*
+ * create a getaddrinfo `hints' based on `proto'
+ */
+
+static void
+make_hints(struct addrinfo *hints, int proto)
+{
+ memset(hints, 0, sizeof(*hints));
+ hints->ai_family = AF_UNSPEC;
+ switch(proto) {
+ case KRB5_KRBHST_UDP :
+ hints->ai_socktype = SOCK_DGRAM;
+ break;
+ case KRB5_KRBHST_HTTP :
+ case KRB5_KRBHST_TCP :
+ hints->ai_socktype = SOCK_STREAM;
+ break;
+ }
+}
+
+/**
+ * Return an `struct addrinfo *' for a KDC host.
+ *
+ * Returns an the struct addrinfo in in that corresponds to the
+ * information in `host'. free:ing is handled by krb5_krbhst_free, so
+ * the returned ai must not be released.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_krbhst_get_addrinfo(krb5_context context, krb5_krbhst_info *host,
+ struct addrinfo **ai)
+{
+ int ret = 0;
+
+ if (host->ai == NULL) {
+ struct addrinfo hints;
+ char portstr[NI_MAXSERV];
+
+ snprintf (portstr, sizeof(portstr), "%d", host->port);
+ make_hints(&hints, host->proto);
+
+ ret = getaddrinfo(host->hostname, portstr, &hints, &host->ai);
+ if (ret) {
+ ret = krb5_eai_to_heim_errno(ret, errno);
+ goto out;
+ }
+ }
+ out:
+ *ai = host->ai;
+ return ret;
+}
+
+static krb5_boolean
+get_next(struct krb5_krbhst_data *kd, krb5_krbhst_info **host)
+{
+ struct krb5_krbhst_info *hi = kd ? *kd->index : NULL;
+ if(hi != NULL) {
+ *host = hi;
+ kd->index = &(*kd->index)->next;
+ return TRUE;
+ }
+ return FALSE;
+}
+
+static void
+srv_get_hosts(krb5_context context, struct krb5_krbhst_data *kd,
+ const char *sitename, const char *proto, const char *service)
+{
+ krb5_error_code ret;
+ krb5_krbhst_info **res;
+ int count, i;
+
+ if (krb5_realm_is_lkdc(kd->realm))
+ return;
+
+ ret = srv_find_realm(context, &res, &count, kd->realm, "SRV",
+ sitename, proto, service, kd->port);
+ _krb5_debug(context, 2, "searching DNS for realm %s %s.%s -> %d",
+ kd->realm, proto, service, ret);
+ if (ret)
+ return;
+ for(i = 0; i < count; i++)
+ append_host_hostinfo(kd, res[i]);
+ free(res);
+}
+
+/*
+ * read the configuration for `conf_string', defaulting to kd->def_port and
+ * forcing it to `kd->port' if kd->port != 0
+ */
+
+static void
+config_get_hosts(krb5_context context, struct krb5_krbhst_data *kd,
+ const char *conf_string)
+{
+ int i;
+ char **hostlist;
+ hostlist = krb5_config_get_strings(context, NULL,
+ "realms", kd->realm, conf_string, NULL);
+
+ _krb5_debug(context, 2, "configuration file for realm %s%s found",
+ kd->realm, hostlist ? "" : " not");
+
+ if(hostlist == NULL)
+ return;
+ kd->flags |= KD_CONFIG_EXISTS;
+ for(i = 0; hostlist && hostlist[i] != NULL; i++)
+ append_host_string(context, kd, hostlist[i], kd->def_port, kd->port);
+
+ krb5_config_free_strings(hostlist);
+}
+
+/*
+ * as a fallback, look for `serv_string.kd->realm' (typically
+ * kerberos.REALM, kerberos-1.REALM, ...
+ * `port' is the default port for the service, and `proto' the
+ * protocol
+ */
+
+static krb5_error_code
+fallback_get_hosts(krb5_context context, struct krb5_krbhst_data *kd,
+ const char *serv_string, int port, int proto)
+{
+ char *host = NULL;
+ int ret;
+ struct addrinfo *ai;
+ struct addrinfo hints;
+ char portstr[NI_MAXSERV];
+
+ ret = krb5_config_get_bool_default(context, NULL, KRB5_FALLBACK_DEFAULT,
+ "libdefaults", "use_fallback", NULL);
+ if (!ret) {
+ kd->flags |= KD_FALLBACK;
+ return 0;
+ }
+
+ _krb5_debug(context, 2, "fallback lookup %d for realm %s (service %s)",
+ kd->fallback_count, kd->realm, serv_string);
+
+ /*
+ * Don't try forever in case the DNS server keep returning us
+ * entries (like wildcard entries or the .nu TLD)
+ *
+ * Also don't try LKDC realms since fallback wont work on them at all.
+ */
+ if(kd->fallback_count >= 5 || krb5_realm_is_lkdc(kd->realm)) {
+ kd->flags |= KD_FALLBACK;
+ return 0;
+ }
+
+ if(kd->fallback_count == 0)
+ ret = asprintf(&host, "%s.%s.", serv_string, kd->realm);
+ else
+ ret = asprintf(&host, "%s-%d.%s.",
+ serv_string, kd->fallback_count, kd->realm);
+
+ if (ret < 0 || host == NULL)
+ return krb5_enomem(context);
+
+ make_hints(&hints, proto);
+ snprintf(portstr, sizeof(portstr), "%d", port);
+ ret = getaddrinfo(host, portstr, &hints, &ai);
+ if (ret) {
+ /* no more hosts, so we're done here */
+ free(host);
+ kd->flags |= KD_FALLBACK;
+ } else {
+ struct krb5_krbhst_info *hi;
+ size_t hostlen;
+
+ /* Check for ICANN gTLD Name Collision address (127.0.53.53) */
+ if (ai->ai_family == AF_INET) {
+ struct sockaddr_in *sin = (struct sockaddr_in *)ai->ai_addr;
+ if (sin->sin_addr.s_addr == htonl(0x7f003535)) {
+ krb5_warnx(context,
+ "Fallback lookup failed: "
+ "Realm %s needs immediate attention "
+ "see https://icann.org/namecollision",
+ kd->realm);
+ freeaddrinfo(ai);
+ return KRB5_KDC_UNREACH;
+ }
+ }
+
+ hostlen = strlen(host);
+ hi = calloc(1, sizeof(*hi) + hostlen);
+ if(hi == NULL) {
+ free(host);
+ freeaddrinfo(ai);
+ return krb5_enomem(context);
+ }
+
+ hi->proto = proto;
+ hi->port = hi->def_port = port;
+ hi->ai = ai;
+ memmove(hi->hostname, host, hostlen);
+ hi->hostname[hostlen] = '\0';
+ free(host);
+ append_host_hostinfo(kd, hi);
+ kd->fallback_count++;
+ }
+ return 0;
+}
+
+/*
+ * Fetch hosts from plugin
+ */
+
+static krb5_error_code
+add_plugin_host(struct krb5_krbhst_data *kd,
+ const char *host,
+ const char *port,
+ int portnum,
+ int proto)
+{
+ struct krb5_krbhst_info *hi;
+ struct addrinfo hints, *ai;
+ size_t hostlen;
+ int ret;
+
+ make_hints(&hints, proto);
+ ret = getaddrinfo(host, port, &hints, &ai);
+ if (ret)
+ return 0;
+
+ hostlen = strlen(host);
+
+ hi = calloc(1, sizeof(*hi) + hostlen);
+ if (hi == NULL) {
+ freeaddrinfo(ai);
+ return ENOMEM;
+ }
+
+ hi->proto = proto;
+ hi->port = hi->def_port = portnum;
+ hi->ai = ai;
+ memmove(hi->hostname, host, hostlen);
+ hi->hostname[hostlen] = '\0';
+ append_host_hostinfo(kd, hi);
+
+ return 0;
+}
+
+static krb5_error_code
+add_locate(void *ctx, int type, struct sockaddr *addr)
+{
+ struct krb5_krbhst_data *kd = ctx;
+ char host[NI_MAXHOST], port[NI_MAXSERV];
+ socklen_t socklen;
+ krb5_error_code ret;
+ int proto, portnum;
+
+ socklen = socket_sockaddr_size(addr);
+ portnum = socket_get_port(addr);
+
+ ret = getnameinfo(addr, socklen, host, sizeof(host), port, sizeof(port),
+ NI_NUMERICHOST|NI_NUMERICSERV);
+ if (ret != 0)
+ return 0;
+
+ if (kd->port)
+ snprintf(port, sizeof(port), "%d", kd->port);
+ else if (atoi(port) == 0)
+ snprintf(port, sizeof(port), "%d", krbhst_get_default_port(kd));
+
+ proto = krbhst_get_default_proto(kd);
+
+ ret = add_plugin_host(kd, host, port, portnum, proto);
+ if (ret)
+ return ret;
+
+ /*
+ * This is really kind of broken and should be solved a different
+ * way, some sites block UDP, and we don't, in the general case,
+ * fall back to TCP, that should also be done. But since that
+ * should require us to invert the whole "find kdc" stack, let put
+ * this in for now.
+ */
+
+ if (proto == KRB5_KRBHST_UDP) {
+ ret = add_plugin_host(kd, host, port, portnum, KRB5_KRBHST_TCP);
+ if (ret)
+ return ret;
+ }
+
+ return 0;
+}
+
+struct plctx {
+ enum locate_service_type type;
+ struct krb5_krbhst_data *kd;
+ unsigned long flags;
+};
+
+static KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+plcallback(krb5_context context,
+ const void *plug, void *plugctx, void *userctx)
+{
+ const krb5plugin_service_locate_ftable *locate = plug;
+ struct plctx *plctx = userctx;
+
+ if (locate->minor_version >= KRB5_PLUGIN_LOCATE_VERSION_2)
+ return locate->lookup(plugctx, plctx->flags, plctx->type, plctx->kd->realm, 0, 0, add_locate, plctx->kd);
+
+ if (plctx->flags & KRB5_PLF_ALLOW_HOMEDIR)
+ return locate->old_lookup(plugctx, plctx->type, plctx->kd->realm, 0, 0, add_locate, plctx->kd);
+
+ return KRB5_PLUGIN_NO_HANDLE;
+}
+
+static const char *locate_plugin_deps[] = { "krb5", NULL };
+
+static struct heim_plugin_data
+locate_plugin_data = {
+ "krb5",
+ KRB5_PLUGIN_LOCATE,
+ KRB5_PLUGIN_LOCATE_VERSION_0,
+ locate_plugin_deps,
+ krb5_get_instance
+};
+
+static void
+plugin_get_hosts(krb5_context context,
+ struct krb5_krbhst_data *kd,
+ enum locate_service_type type)
+{
+ struct plctx ctx = { type, kd, 0 };
+
+ if (_krb5_homedir_access(context))
+ ctx.flags |= KRB5_PLF_ALLOW_HOMEDIR;
+
+ _krb5_plugin_run_f(context, &locate_plugin_data,
+ 0, &ctx, plcallback);
+}
+
+/*
+ *
+ */
+
+static void
+hostnames_get_hosts(krb5_context context,
+ struct krb5_krbhst_data *kd,
+ const char *type)
+{
+ kd->flags |= KD_HOSTNAMES;
+ if (kd->hostname)
+ append_host_string(context, kd, kd->hostname, kd->def_port, kd->port);
+}
+
+
+/*
+ *
+ */
+
+static krb5_error_code
+kdc_get_next(krb5_context context,
+ struct krb5_krbhst_data *kd,
+ krb5_krbhst_info **host)
+{
+ krb5_error_code ret;
+
+ if ((kd->flags & KD_HOSTNAMES) == 0) {
+ hostnames_get_hosts(context, kd, "kdc");
+ if(get_next(kd, host))
+ return 0;
+ }
+
+ if ((kd->flags & KD_PLUGIN) == 0) {
+ plugin_get_hosts(context, kd, locate_service_kdc);
+ kd->flags |= KD_PLUGIN;
+ if(get_next(kd, host))
+ return 0;
+ }
+
+ if((kd->flags & KD_CONFIG) == 0) {
+ config_get_hosts(context, kd, kd->config_param);
+ kd->flags |= KD_CONFIG;
+ if(get_next(kd, host))
+ return 0;
+ }
+
+ if (kd->flags & KD_CONFIG_EXISTS) {
+ _krb5_debug(context, 1,
+ "Configuration exists for realm %s, wont go to DNS",
+ kd->realm);
+ return KRB5_KDC_UNREACH;
+ }
+
+ if(context->srv_lookup) {
+ if(kd->sitename && (kd->flags & KD_SITE_SRV_TCP) == 0) {
+ srv_get_hosts(context, kd, kd->sitename, "tcp", "kerberos");
+ kd->flags |= KD_SITE_SRV_TCP;
+ if(get_next(kd, host))
+ return 0;
+ }
+
+ if((kd->flags & KD_SRV_UDP) == 0 && (kd->flags & KD_LARGE_MSG) == 0) {
+ srv_get_hosts(context, kd, NULL, "udp", kd->srv_label);
+ kd->flags |= KD_SRV_UDP;
+ if(get_next(kd, host))
+ return 0;
+ }
+
+ if((kd->flags & KD_SRV_TCP) == 0) {
+ srv_get_hosts(context, kd, NULL, "tcp", kd->srv_label);
+ kd->flags |= KD_SRV_TCP;
+ if(get_next(kd, host))
+ return 0;
+ }
+ if((kd->flags & KD_SRV_HTTP) == 0) {
+ srv_get_hosts(context, kd, NULL, "http", kd->srv_label);
+ kd->flags |= KD_SRV_HTTP;
+ if(get_next(kd, host))
+ return 0;
+ }
+ }
+
+ while((kd->flags & KD_FALLBACK) == 0) {
+ ret = fallback_get_hosts(context, kd, "kerberos",
+ kd->def_port,
+ krbhst_get_default_proto(kd));
+ if(ret)
+ return ret;
+ if(get_next(kd, host))
+ return 0;
+ }
+
+ _krb5_debug(context, 0, "No KDC entries found for %s", kd->realm);
+
+ return KRB5_KDC_UNREACH; /* XXX */
+}
+
+static krb5_error_code
+admin_get_next(krb5_context context,
+ struct krb5_krbhst_data *kd,
+ krb5_krbhst_info **host)
+{
+ krb5_error_code ret;
+
+ if ((kd->flags & KD_PLUGIN) == 0) {
+ plugin_get_hosts(context, kd, locate_service_kadmin);
+ kd->flags |= KD_PLUGIN;
+ if(get_next(kd, host))
+ return 0;
+ }
+
+ if((kd->flags & KD_CONFIG) == 0) {
+ config_get_hosts(context, kd, kd->config_param);
+ kd->flags |= KD_CONFIG;
+ if(get_next(kd, host))
+ return 0;
+ }
+
+ if (kd->flags & KD_CONFIG_EXISTS) {
+ _krb5_debug(context, 1,
+ "Configuration exists for realm %s, wont go to DNS",
+ kd->realm);
+ return KRB5_KDC_UNREACH;
+ }
+
+ if(context->srv_lookup) {
+ if((kd->flags & KD_SRV_TCP) == 0) {
+ srv_get_hosts(context, kd, NULL, "tcp", kd->srv_label);
+ kd->flags |= KD_SRV_TCP;
+ if(get_next(kd, host))
+ return 0;
+ }
+ }
+
+ if (krbhst_empty(kd)
+ && (kd->flags & KD_FALLBACK) == 0) {
+ ret = fallback_get_hosts(context, kd, "kerberos",
+ kd->def_port,
+ krbhst_get_default_proto(kd));
+ if(ret)
+ return ret;
+ kd->flags |= KD_FALLBACK;
+ if(get_next(kd, host))
+ return 0;
+ }
+
+ _krb5_debug(context, 0, "No admin entries found for realm %s", kd->realm);
+
+ return KRB5_KDC_UNREACH; /* XXX */
+}
+
+static krb5_error_code
+kpasswd_get_next(krb5_context context,
+ struct krb5_krbhst_data *kd,
+ krb5_krbhst_info **host)
+{
+ krb5_error_code ret;
+
+ if ((kd->flags & KD_PLUGIN) == 0) {
+ plugin_get_hosts(context, kd, locate_service_kpasswd);
+ kd->flags |= KD_PLUGIN;
+ if(get_next(kd, host))
+ return 0;
+ }
+
+ if((kd->flags & KD_CONFIG) == 0) {
+ config_get_hosts(context, kd, kd->config_param);
+ kd->flags |= KD_CONFIG;
+ if(get_next(kd, host))
+ return 0;
+ }
+
+ if (kd->flags & KD_CONFIG_EXISTS) {
+ _krb5_debug(context, 1,
+ "Configuration exists for realm %s, wont go to DNS",
+ kd->realm);
+ return KRB5_KDC_UNREACH;
+ }
+
+ if(context->srv_lookup) {
+ if((kd->flags & KD_SRV_UDP) == 0) {
+ srv_get_hosts(context, kd, NULL, "udp", kd->srv_label);
+ kd->flags |= KD_SRV_UDP;
+ if(get_next(kd, host))
+ return 0;
+ }
+ if((kd->flags & KD_SRV_TCP) == 0) {
+ srv_get_hosts(context, kd, NULL, "tcp", kd->srv_label);
+ kd->flags |= KD_SRV_TCP;
+ if(get_next(kd, host))
+ return 0;
+ }
+ }
+
+ /* no matches -> try admin */
+
+ if (krbhst_empty(kd)) {
+ kd->flags = 0;
+ kd->port = kd->def_port;
+ kd->get_next = admin_get_next;
+ ret = (*kd->get_next)(context, kd, host);
+ if (ret == 0)
+ (*host)->proto = krbhst_get_default_proto(kd);
+ return ret;
+ }
+
+ _krb5_debug(context, 0, "No kpasswd entries found for realm %s", kd->realm);
+
+ return KRB5_KDC_UNREACH;
+}
+
+static void KRB5_CALLCONV
+krbhost_dealloc(void *ptr)
+{
+ struct krb5_krbhst_data *handle = (struct krb5_krbhst_data *)ptr;
+ krb5_krbhst_info *h, *next;
+
+ for (h = handle->hosts; h != NULL; h = next) {
+ next = h->next;
+ _krb5_free_krbhst_info(h);
+ }
+ if (handle->hostname)
+ free(handle->hostname);
+ if (handle->sitename)
+ free(handle->sitename);
+
+ free(handle->realm);
+}
+
+static struct krb5_krbhst_data*
+common_init(krb5_context context,
+ const char *config_param,
+ const char *srv_label,
+ const char *service,
+ const char *realm,
+ int flags)
+{
+ struct krb5_krbhst_data *kd;
+
+ if ((kd = heim_alloc(sizeof(*kd), "krbhst-context", krbhost_dealloc)) == NULL)
+ return NULL;
+
+ if((kd->realm = strdup(realm)) == NULL) {
+ heim_release(kd);
+ return NULL;
+ }
+
+ kd->config_param = config_param;
+ kd->srv_label = srv_label;
+
+ _krb5_debug(context, 2, "Trying to find service %s for realm %s flags %x",
+ service, realm, flags);
+
+ /* For 'realms' without a . do not even think of going to DNS */
+ if (!strchr(realm, '.'))
+ kd->flags |= KD_CONFIG_EXISTS;
+
+ if (flags & KRB5_KRBHST_FLAGS_LARGE_MSG)
+ kd->flags |= KD_LARGE_MSG;
+ kd->end = kd->index = &kd->hosts;
+ return kd;
+}
+
+/*
+ * initialize `handle' to look for hosts of type `type' in realm `realm'
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_krbhst_init(krb5_context context,
+ const char *realm,
+ unsigned int type,
+ krb5_krbhst_handle *handle)
+{
+ return krb5_krbhst_init_flags(context, realm, type, 0, handle);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_krbhst_init_flags(krb5_context context,
+ const char *realm,
+ unsigned int type,
+ int flags,
+ krb5_krbhst_handle *handle)
+{
+ struct krb5_krbhst_data *kd;
+ krb5_error_code (*next)(krb5_context, struct krb5_krbhst_data *,
+ krb5_krbhst_info **);
+ int def_port;
+ const char *config_param;
+ const char *srv_label;
+ const char *service;
+
+ *handle = NULL;
+
+ switch(type) {
+ case KRB5_KRBHST_KDC:
+ next = kdc_get_next;
+ def_port = ntohs(krb5_getportbyname(context, "kerberos", "udp", 88));
+ config_param = "kdc";
+ srv_label = "kerberos";
+ service = "kdc";
+ break;
+ case KRB5_KRBHST_ADMIN:
+ next = admin_get_next;
+ def_port = ntohs(krb5_getportbyname(context, "kerberos-adm",
+ "tcp", 749));
+ config_param = "admin_server";
+ srv_label = "kerberos-adm";
+ service = "admin";
+ break;
+ case KRB5_KRBHST_READONLY_ADMIN:
+ next = admin_get_next;
+ def_port = ntohs(krb5_getportbyname(context, "kerberos-adm",
+ "tcp", 749));
+ config_param = "readonly_admin_server";
+ srv_label = "kerberos-adm-readonly";
+ service = "admin";
+ break;
+ case KRB5_KRBHST_CHANGEPW:
+ next = kpasswd_get_next;
+ def_port = ntohs(krb5_getportbyname(context, "kpasswd", "udp",
+ KPASSWD_PORT));
+ config_param = "kpasswd_server";
+ srv_label = "kpasswd";
+ service = "change_password";
+ break;
+ case KRB5_KRBHST_TKTBRIDGEAP:
+ next = kdc_get_next;
+ def_port = ntohs(krb5_getportbyname(context, "kerberos", "tcp", 88));
+ config_param = "tktbridgeap";
+ srv_label = "kerberos-tkt-bridge";
+ service = "kdc";
+ break;
+ default:
+ krb5_set_error_message(context, ENOTTY,
+ N_("unknown krbhst type (%u)", ""), type);
+ return ENOTTY;
+ }
+ if((kd = common_init(context, config_param, srv_label, service, realm,
+ flags)) == NULL)
+ return ENOMEM;
+ kd->get_next = next;
+ kd->def_port = def_port;
+ *handle = kd;
+ return 0;
+}
+
+/*
+ * return the next host information from `handle' in `host'
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_krbhst_next(krb5_context context,
+ krb5_krbhst_handle handle,
+ krb5_krbhst_info **host)
+{
+ if(get_next(handle, host))
+ return 0;
+
+ return (*handle->get_next)(context, handle, host);
+}
+
+/*
+ * return the next host information from `handle' as a host name
+ * in `hostname' (or length `hostlen)
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_krbhst_next_as_string(krb5_context context,
+ krb5_krbhst_handle handle,
+ char *hostname,
+ size_t hostlen)
+{
+ krb5_error_code ret;
+ krb5_krbhst_info *host;
+ ret = krb5_krbhst_next(context, handle, &host);
+ if(ret)
+ return ret;
+ return krb5_krbhst_format_string(context, host, hostname, hostlen);
+}
+
+/*
+ *
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_krbhst_set_hostname(krb5_context context,
+ krb5_krbhst_handle handle,
+ const char *hostname)
+{
+ if (handle->hostname)
+ free(handle->hostname);
+ handle->hostname = strdup(hostname);
+ if (handle->hostname == NULL)
+ return ENOMEM;
+ return 0;
+}
+
+krb5_error_code KRB5_LIB_FUNCTION
+krb5_krbhst_set_sitename(krb5_context context,
+ krb5_krbhst_handle handle,
+ const char *sitename)
+{
+ if (handle->sitename)
+ free(handle->sitename);
+ handle->sitename = strdup(sitename);
+ if (handle->sitename == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_krbhst_reset(krb5_context context, krb5_krbhst_handle handle)
+{
+ handle->index = &handle->hosts;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_krbhst_free(krb5_context context, krb5_krbhst_handle handle)
+{
+ heim_release(handle);
+}
+
+#ifndef HEIMDAL_SMALLER
+
+/* backwards compatibility ahead */
+
+static krb5_error_code
+gethostlist(krb5_context context, const char *realm,
+ unsigned int type, char ***hostlist)
+{
+ krb5_error_code ret;
+ int nhost = 0;
+ krb5_krbhst_handle handle;
+ char host[MAXHOSTNAMELEN];
+ krb5_krbhst_info *hostinfo;
+
+ ret = krb5_krbhst_init(context, realm, type, &handle);
+ if (ret)
+ return ret;
+
+ while (krb5_krbhst_next(context, handle, &hostinfo) == 0)
+ nhost++;
+ if (nhost == 0) {
+ krb5_set_error_message(context, KRB5_KDC_UNREACH,
+ N_("No KDC found for realm %s", ""), realm);
+ krb5_krbhst_free(context, handle);
+ return KRB5_KDC_UNREACH;
+ }
+ *hostlist = calloc(nhost + 1, sizeof(**hostlist));
+ if (*hostlist == NULL) {
+ krb5_krbhst_free(context, handle);
+ return krb5_enomem(context);
+ }
+
+ krb5_krbhst_reset(context, handle);
+ nhost = 0;
+ while (krb5_krbhst_next_as_string(context, handle,
+ host, sizeof(host)) == 0) {
+ if (((*hostlist)[nhost++] = strdup(host)) == NULL) {
+ krb5_free_krbhst(context, *hostlist);
+ krb5_krbhst_free(context, handle);
+ return krb5_enomem(context);
+ }
+ }
+ (*hostlist)[nhost] = NULL;
+ krb5_krbhst_free(context, handle);
+ return 0;
+}
+
+/*
+ * Return a malloced list of kadmin-hosts for `realm' in `hostlist'
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_krb_admin_hst(krb5_context context,
+ const krb5_realm *realm,
+ char ***hostlist)
+{
+ return gethostlist(context, *realm, KRB5_KRBHST_ADMIN, hostlist);
+}
+
+/*
+ * Return a malloced list of writable kadmin-hosts for `realm' in `hostlist'
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_krb_readonly_admin_hst(krb5_context context,
+ const krb5_realm *realm,
+ char ***hostlist)
+{
+ return gethostlist(context, *realm, KRB5_KRBHST_READONLY_ADMIN, hostlist);
+}
+
+/*
+ * return an malloced list of changepw-hosts for `realm' in `hostlist'
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_krb_changepw_hst (krb5_context context,
+ const krb5_realm *realm,
+ char ***hostlist)
+{
+ return gethostlist(context, *realm, KRB5_KRBHST_CHANGEPW, hostlist);
+}
+
+/*
+ * return an malloced list of 524-hosts for `realm' in `hostlist'
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_krb524hst (krb5_context context,
+ const krb5_realm *realm,
+ char ***hostlist)
+{
+ return gethostlist(context, *realm, KRB5_KRBHST_KRB524, hostlist);
+}
+
+/*
+ * return an malloced list of KDC's for `realm' in `hostlist'
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_krbhst (krb5_context context,
+ const krb5_realm *realm,
+ char ***hostlist)
+{
+ return gethostlist(context, *realm, KRB5_KRBHST_KDC, hostlist);
+}
+
+/*
+ * free all the memory allocated in `hostlist'
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_free_krbhst (krb5_context context,
+ char **hostlist)
+{
+ char **p;
+
+ for (p = hostlist; *p; ++p)
+ free (*p);
+ free (hostlist);
+ return 0;
+}
+
+#endif /* HEIMDAL_SMALLER */
diff --git a/third_party/heimdal/lib/krb5/krcache.c b/third_party/heimdal/lib/krb5/krcache.c
new file mode 100644
index 0000000..9e99221
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/krcache.c
@@ -0,0 +1,2075 @@
+/*
+ * Copyright (c) 2006 The Regents of the University of Michigan.
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2018, AuriStor, Inc.
+ *
+ * Permission is granted to use, copy, create derivative works
+ * and redistribute this software and such derivative works
+ * for any purpose, so long as the name of The University of
+ * Michigan is not used in any advertising or publicity
+ * pertaining to the use of distribution of this software
+ * without specific, written prior authorization. If the
+ * above copyright notice or any other identification of the
+ * University of Michigan is included in any copy of any
+ * portion of this software, then the disclaimer below must
+ * also be included.
+ *
+ * THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION
+ * FROM THE UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY
+ * PURPOSE, AND WITHOUT WARRANTY BY THE UNIVERSITY OF
+ * MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
+ * WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
+ * REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE
+ * FOR ANY DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR
+ * CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM ARISING
+ * OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN
+ * IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGES.
+ */
+/*
+ * Copyright 1990,1991,1992,1993,1994,2000,2004 Massachusetts Institute of
+ * Technology. All Rights Reserved.
+ *
+ * Original stdio support copyright 1995 by Cygnus Support.
+ *
+ * Export of this software from the United States of America may
+ * require a specific license from the United States Government.
+ * It is the responsibility of any person or organization contemplating
+ * export to obtain such a license before exporting.
+ *
+ * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
+ * distribute this software and its documentation for any purpose and
+ * without fee is hereby granted, provided that the above copyright
+ * notice appear in all copies and that both that copyright notice and
+ * this permission notice appear in supporting documentation, and that
+ * the name of M.I.T. not be used in advertising or publicity pertaining
+ * to distribution of the software without specific, written prior
+ * permission. Furthermore if you modify this software you must label
+ * your software as modified software and not distribute it in such a
+ * fashion that it might be confused with the original M.I.T. software.
+ * M.I.T. makes no representations about the suitability of
+ * this software for any purpose. It is provided "as is" without express
+ * or implied warranty.
+ */
+
+/*
+ * This file implements a collection-enabled credential cache type where the
+ * credentials are stored in the Linux keyring facility.
+ *
+ * A residual of this type can have three forms:
+ * anchor:collection:subsidiary
+ * anchor:collection
+ * collection
+ *
+ * The anchor name is "process", "thread", or "legacy" and determines where we
+ * search for keyring collections. In the third form, the anchor name is
+ * presumed to be "legacy". The anchor keyring for legacy caches is the
+ * session keyring.
+ *
+ * If the subsidiary name is present, the residual identifies a single cache
+ * within a collection. Otherwise, the residual identifies the collection
+ * itself. When a residual identifying a collection is resolved, the
+ * collection's primary key is looked up (or initialized, using the collection
+ * name as the subsidiary name), and the resulting cache's name will use the
+ * first name form and will identify the primary cache.
+ *
+ * Keyring collections are named "_krb_<collection>" and are linked from the
+ * anchor keyring. The keys within a keyring collection are links to cache
+ * keyrings, plus a link to one user key named "krb_ccache:primary" which
+ * contains a serialized representation of the collection version (currently 1)
+ * and the primary name of the collection.
+ *
+ * Cache keyrings contain one user key per credential which contains a
+ * serialized representation of the credential. There is also one user key
+ * named "__krb5_princ__" which contains a serialized representation of the
+ * cache's default principal.
+ *
+ * If the anchor name is "legacy", then the initial primary cache (the one
+ * named with the collection name) is also linked to the session keyring, and
+ * we look for a cache in that location when initializing the collection. This
+ * extra link allows that cache to be visible to old versions of the KEYRING
+ * cache type, and allows us to see caches created by that code.
+ */
+
+#include "krb5_locl.h"
+
+#ifdef HAVE_KEYUTILS_H
+
+#include <keyutils.h>
+
+/*
+ * We try to use the big_key key type for credentials except in legacy caches.
+ * We fall back to the user key type if the kernel does not support big_key.
+ * If the library doesn't support keyctl_get_persistent(), we don't even try
+ * big_key since the two features were added at the same time.
+ */
+#ifdef HAVE_KEYCTL_GET_PERSISTENT
+#define KRCC_CRED_KEY_TYPE "big_key"
+#else
+#define KRCC_CRED_KEY_TYPE "user"
+#endif
+
+/*
+ * We use the "user" key type for collection primary names, for cache principal
+ * names, and for credentials in legacy caches.
+ */
+#define KRCC_KEY_TYPE_USER "user"
+
+/*
+ * We create ccaches as separate keyrings
+ */
+#define KRCC_KEY_TYPE_KEYRING "keyring"
+
+/*
+ * Special name of the key within a ccache keyring
+ * holding principal information
+ */
+#define KRCC_SPEC_PRINC_KEYNAME "__krb5_princ__"
+
+/*
+ * Special name for the key to communicate the name(s)
+ * of credentials caches to be used for requests.
+ * This should currently contain a single name, but
+ * in the future may contain a list that may be
+ * intelligently chosen from.
+ */
+#define KRCC_SPEC_CCACHE_SET_KEYNAME "__krb5_cc_set__"
+
+/*
+ * This name identifies the key containing the name of the current primary
+ * cache within a collection.
+ */
+#define KRCC_COLLECTION_PRIMARY "krb_ccache:primary"
+
+/*
+ * If the library context does not specify a keyring collection, unique ccaches
+ * will be created within this collection.
+ */
+#define KRCC_DEFAULT_UNIQUE_COLLECTION "session:__krb5_unique__"
+
+/*
+ * Collection keyring names begin with this prefix. We use a prefix so that a
+ * cache keyring with the collection name itself can be linked directly into
+ * the anchor, for legacy session keyring compatibility.
+ */
+#define KRCC_CCCOL_PREFIX "_krb_"
+
+/*
+ * For the "persistent" anchor type, we look up or create this fixed keyring
+ * name within the per-UID persistent keyring.
+ */
+#define KRCC_PERSISTENT_KEYRING_NAME "_krb"
+
+/*
+ * Name of the key holding time offsets for the individual cache
+ */
+#define KRCC_TIME_OFFSETS "__krb5_time_offsets__"
+
+/*
+ * Keyring name prefix and length of random name part
+ */
+#define KRCC_NAME_PREFIX "krb_ccache_"
+#define KRCC_NAME_RAND_CHARS 8
+
+#define KRCC_COLLECTION_VERSION 1
+
+#define KRCC_PERSISTENT_ANCHOR "persistent"
+#define KRCC_PROCESS_ANCHOR "process"
+#define KRCC_THREAD_ANCHOR "thread"
+#define KRCC_SESSION_ANCHOR "session"
+#define KRCC_USER_ANCHOR "user"
+#define KRCC_LEGACY_ANCHOR "legacy"
+
+#if SIZEOF_KEY_SERIAL_T != 4
+/* lockless implementation assumes 32-bit key serials */
+#error only 32-bit key serial numbers supported by this version of keyring ccache
+#endif
+
+typedef heim_base_atomic(key_serial_t) atomic_key_serial_t;
+
+typedef union _krb5_krcache_and_princ_id {
+ heim_base_atomic(uint64_t) krcu_cache_and_princ_id;
+ struct {
+ atomic_key_serial_t cache_id; /* keyring ID representing ccache */
+ atomic_key_serial_t princ_id; /* key ID holding principal info */
+ } krcu_id;
+ #define krcu_cache_id krcu_id.cache_id
+ #define krcu_princ_id krcu_id.princ_id
+} krb5_krcache_and_princ_id;
+
+/*
+ * This represents a credentials cache "file" where cache_id is the keyring
+ * serial number for this credentials cache "file". Each key in the keyring
+ * contains a separate key.
+ *
+ * Thread-safe as long as caches are not destroyed whilst other threads are
+ * using them.
+ */
+typedef struct _krb5_krcache {
+ char *krc_name; /* Name for this credentials cache */
+ char *krc_collection;
+ char *krc_subsidiary;
+ heim_base_atomic(krb5_timestamp) krc_changetime; /* update time, does not decrease (mutable) */
+ krb5_krcache_and_princ_id krc_id; /* cache and principal IDs (mutable) */
+ #define krc_cache_and_principal_id krc_id.krcu_cache_and_princ_id
+ #define krc_cache_id krc_id.krcu_id.cache_id
+ #define krc_princ_id krc_id.krcu_id.princ_id
+ key_serial_t krc_coll_id; /* collection containing this cache keyring */
+ krb5_boolean krc_is_legacy; /* */
+} krb5_krcache;
+
+#define KRCACHE(X) ((krb5_krcache *)(X)->data.data)
+
+static krb5_error_code KRB5_CALLCONV
+krcc_get_first(krb5_context, krb5_ccache id, krb5_cc_cursor *cursor);
+
+static krb5_error_code KRB5_CALLCONV
+krcc_get_next(krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor,
+ krb5_creds *creds);
+
+static krb5_error_code KRB5_CALLCONV
+krcc_end_get(krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor);
+
+static krb5_error_code KRB5_CALLCONV
+krcc_end_cache_get(krb5_context context, krb5_cc_cursor cursor);
+
+static krb5_error_code
+clear_cache_keyring(krb5_context context, atomic_key_serial_t *pcache_id);
+
+static krb5_error_code
+alloc_cache(krb5_context context,
+ key_serial_t collection_id,
+ key_serial_t cache_id,
+ const char *anchor_name,
+ const char *collection_name,
+ const char *subsidiary_name,
+ krb5_krcache **data);
+
+static krb5_error_code
+save_principal(krb5_context context,
+ key_serial_t cache_id,
+ krb5_const_principal princ,
+ atomic_key_serial_t *pprinc_id);
+
+static krb5_error_code
+save_time_offsets(krb5_context context,
+ key_serial_t cache_id,
+ int32_t sec_offset,
+ int32_t usec_offset);
+
+static void
+update_change_time(krb5_context context,
+ krb5_timestamp now,
+ krb5_krcache *d);
+
+/*
+ * GET_PERSISTENT(uid) acquires the persistent keyring for uid, or falls back
+ * to the user keyring if uid matches the current effective uid.
+ */
+
+static key_serial_t
+get_persistent_fallback(uid_t uid)
+{
+ return (uid == geteuid()) ? KEY_SPEC_USER_KEYRING : -1;
+}
+
+#ifdef HAVE_KEYCTL_GET_PERSISTENT
+#define GET_PERSISTENT get_persistent_real
+static key_serial_t
+get_persistent_real(uid_t uid)
+{
+ key_serial_t key;
+
+ key = keyctl_get_persistent(uid, KEY_SPEC_PROCESS_KEYRING);
+
+ return (key == -1 && errno == ENOTSUP) ? get_persistent_fallback(uid) : key;
+}
+#else
+#define GET_PERSISTENT get_persistent_fallback
+#endif
+
+/*
+ * If a process has no explicitly set session keyring, KEY_SPEC_SESSION_KEYRING
+ * will resolve to the user session keyring for ID lookup and reading, but in
+ * some kernel versions, writing to that special keyring will instead create a
+ * new empty session keyring for the process. We do not want that; the keys we
+ * create would be invisible to other processes. We can work around that
+ * behavior by explicitly writing to the user session keyring when it matches
+ * the session keyring. This function returns the keyring we should write to
+ * for the session anchor.
+ */
+static key_serial_t
+session_write_anchor(void)
+{
+ key_serial_t s, u;
+
+ s = keyctl_get_keyring_ID(KEY_SPEC_SESSION_KEYRING, 0);
+ u = keyctl_get_keyring_ID(KEY_SPEC_USER_SESSION_KEYRING, 0);
+
+ return (s == u) ? KEY_SPEC_USER_SESSION_KEYRING : KEY_SPEC_SESSION_KEYRING;
+}
+
+/*
+ * Find or create a keyring within parent with the given name. If possess is
+ * nonzero, also make sure the key is linked from possess. This is necessary
+ * to ensure that we have possession rights on the key when the parent is the
+ * user or persistent keyring.
+ */
+static krb5_error_code
+find_or_create_keyring(key_serial_t parent,
+ key_serial_t possess,
+ const char *name,
+ atomic_key_serial_t *pkey)
+{
+ key_serial_t key;
+
+ key = keyctl_search(parent, KRCC_KEY_TYPE_KEYRING, name, possess);
+ if (key == -1) {
+ if (possess != 0) {
+ key = add_key(KRCC_KEY_TYPE_KEYRING, name, NULL, 0, possess);
+ if (key == -1 || keyctl_link(key, parent) == -1)
+ return errno;
+ } else {
+ key = add_key(KRCC_KEY_TYPE_KEYRING, name, NULL, 0, parent);
+ if (key == -1)
+ return errno;
+ }
+ }
+
+ heim_base_atomic_store(pkey, key);
+
+ return 0;
+}
+
+/*
+ * Parse a residual name into an anchor name, a collection name, and possibly a
+ * subsidiary name.
+ */
+static krb5_error_code
+parse_residual(krb5_context context,
+ const char *residual,
+ char **panchor_name,
+ char **pcollection_name,
+ char **psubsidiary_name)
+{
+ char *anchor_name = NULL;
+ char *collection_name = NULL;
+ char *subsidiary_name = NULL;
+ const char *sep;
+
+ *panchor_name = NULL;
+ *pcollection_name = NULL;
+ *psubsidiary_name = NULL;
+
+ if (residual == NULL)
+ residual = "";
+
+ /* Parse out the anchor name. Use the legacy anchor if not present. */
+ sep = strchr(residual, ':');
+ if (sep == NULL) {
+ anchor_name = strdup(KRCC_LEGACY_ANCHOR);
+ if (anchor_name == NULL)
+ goto nomem;
+ } else {
+ anchor_name = strndup(residual, sep - residual);
+ if (anchor_name == NULL)
+ goto nomem;
+ residual = sep + 1;
+ }
+
+ /* Parse out the collection and subsidiary name. */
+ sep = strchr(residual, ':');
+ if (sep == NULL) {
+ collection_name = strdup(residual);
+ if (collection_name == NULL)
+ goto nomem;
+ } else {
+ collection_name = strndup(residual, sep - residual);
+ if (collection_name == NULL)
+ goto nomem;
+
+ subsidiary_name = strdup(sep + 1);
+ if (subsidiary_name == NULL)
+ goto nomem;
+ }
+
+ *panchor_name = anchor_name;
+ *pcollection_name = collection_name;
+ *psubsidiary_name = subsidiary_name;
+
+ return 0;
+
+nomem:
+ free(anchor_name);
+ free(collection_name);
+ free(subsidiary_name);
+
+ return krb5_enomem(context);
+}
+
+/*
+ * Return TRUE if residual identifies a subsidiary cache which should be linked
+ * into the anchor so it can be visible to old code. This is the case if the
+ * residual has the legacy anchor and the subsidiary name matches the
+ * collection name.
+ */
+static krb5_boolean
+is_legacy_cache_name_p(const char *residual)
+{
+ const char *sep, *aname, *cname, *sname;
+ size_t alen, clen, legacy_len = sizeof(KRCC_LEGACY_ANCHOR) - 1;
+
+ /* Get pointers to the anchor, collection, and subsidiary names. */
+ aname = residual;
+ sep = strchr(residual, ':');
+ if (sep == NULL)
+ return FALSE;
+
+ alen = sep - aname;
+ cname = sep + 1;
+ sep = strchr(cname, ':');
+ if (sep == NULL)
+ return FALSE;
+
+ clen = sep - cname;
+ sname = sep + 1;
+
+ return alen == legacy_len && clen == strlen(sname) &&
+ strncmp(aname, KRCC_LEGACY_ANCHOR, alen) == 0 &&
+ strncmp(cname, sname, clen) == 0;
+}
+
+/*
+ * If the default cache name for context is a KEYRING cache, parse its residual
+ * string. Otherwise set all outputs to NULL.
+ */
+static krb5_error_code
+get_default(krb5_context context,
+ char **panchor_name,
+ char **pcollection_name,
+ char **psubsidiary_name)
+{
+ const char *defname;
+
+ *panchor_name = *pcollection_name = *psubsidiary_name = NULL;
+
+ defname = krb5_cc_default_name(context);
+ if (defname == NULL || strncmp(defname, "KEYRING:", 8) != 0)
+ return 0;
+
+ return parse_residual(context, defname + 8,
+ panchor_name, pcollection_name, psubsidiary_name);
+}
+
+/* Create a residual identifying a subsidiary cache. */
+static krb5_error_code
+make_subsidiary_residual(krb5_context context,
+ const char *anchor_name,
+ const char *collection_name,
+ const char *subsidiary_name,
+ char **presidual)
+{
+ if (asprintf(presidual, "%s:%s:%s", anchor_name, collection_name,
+ subsidiary_name ? subsidiary_name : "tkt") < 0) {
+ *presidual = NULL;
+ return krb5_enomem(context);
+ }
+
+ return 0;
+}
+
+/*
+ * Retrieve or create a keyring for collection_name within the anchor, and set
+ * *collection_id to its serial number.
+ */
+static krb5_error_code
+get_collection(krb5_context context,
+ const char *anchor_name,
+ const char *collection_name,
+ atomic_key_serial_t *pcollection_id)
+{
+ krb5_error_code ret;
+ key_serial_t persistent_id, anchor_id, possess_id = 0;
+ char *ckname, *cnend;
+ uid_t uidnum;
+
+ heim_base_atomic_init(pcollection_id, 0);
+
+ if (!anchor_name || !collection_name)
+ return KRB5_KCC_INVALID_ANCHOR;
+
+ if (strcmp(anchor_name, KRCC_PERSISTENT_ANCHOR) == 0) {
+ /*
+ * The collection name is a uid (or empty for the current effective
+ * uid), and we look up a fixed keyring name within the persistent
+ * keyring for that uid. We link it to the process keyring to ensure
+ * that we have possession rights on the collection key.
+ */
+ if (*collection_name != '\0') {
+ errno = 0;
+ uidnum = (uid_t)strtol(collection_name, &cnend, 10);
+ if (errno || *cnend != '\0')
+ return KRB5_KCC_INVALID_UID;
+ } else {
+ uidnum = geteuid();
+ }
+
+ persistent_id = GET_PERSISTENT(uidnum);
+ if (persistent_id == -1)
+ return KRB5_KCC_INVALID_UID;
+
+ return find_or_create_keyring(persistent_id, KEY_SPEC_PROCESS_KEYRING,
+ KRCC_PERSISTENT_KEYRING_NAME,
+ pcollection_id);
+ }
+
+ if (strcmp(anchor_name, KRCC_PROCESS_ANCHOR) == 0) {
+ anchor_id = KEY_SPEC_PROCESS_KEYRING;
+ } else if (strcmp(anchor_name, KRCC_THREAD_ANCHOR) == 0) {
+ anchor_id = KEY_SPEC_THREAD_KEYRING;
+ } else if (strcmp(anchor_name, KRCC_SESSION_ANCHOR) == 0) {
+ anchor_id = session_write_anchor();
+ } else if (strcmp(anchor_name, KRCC_USER_ANCHOR) == 0) {
+ /*
+ * The user keyring does not confer possession, so we need to link the
+ * collection to the process keyring to maintain possession rights.
+ */
+ anchor_id = KEY_SPEC_USER_KEYRING;
+ possess_id = KEY_SPEC_PROCESS_KEYRING;
+ } else if (strcmp(anchor_name, KRCC_LEGACY_ANCHOR) == 0) {
+ anchor_id = session_write_anchor();
+ } else {
+ return KRB5_KCC_INVALID_ANCHOR;
+ }
+
+ /* Look up the collection keyring name within the anchor keyring. */
+ if (asprintf(&ckname, "%s%s", KRCC_CCCOL_PREFIX, collection_name) == -1)
+ return krb5_enomem(context);
+
+ ret = find_or_create_keyring(anchor_id, possess_id, ckname,
+ pcollection_id);
+ free(ckname);
+
+ return ret;
+}
+
+/* Store subsidiary_name into the primary index key for collection_id. */
+static krb5_error_code
+set_primary_name(krb5_context context,
+ key_serial_t collection_id,
+ const char *subsidiary_name)
+{
+ krb5_error_code ret;
+ krb5_storage *sp;
+ krb5_data payload;
+ key_serial_t key;
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", ""));
+ return KRB5_CC_NOMEM;
+ }
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_BE);
+
+ ret = krb5_store_int32(sp, KRCC_COLLECTION_VERSION);
+ if (ret)
+ goto cleanup;
+
+ ret = krb5_store_string(sp, subsidiary_name);
+ if (ret)
+ goto cleanup;
+
+ ret = krb5_storage_to_data(sp, &payload);
+ if (ret)
+ goto cleanup;
+
+ key = add_key(KRCC_KEY_TYPE_USER, KRCC_COLLECTION_PRIMARY,
+ payload.data, payload.length, collection_id);
+ ret = (key == -1) ? errno : 0;
+ krb5_data_free(&payload);
+
+cleanup:
+ krb5_storage_free(sp);
+
+ return ret;
+}
+
+static krb5_error_code
+parse_index(krb5_context context,
+ int32_t *version,
+ char **primary,
+ const unsigned char *payload,
+ size_t psize)
+{
+ krb5_error_code ret;
+ krb5_data payload_data;
+ krb5_storage *sp;
+
+ payload_data.length = psize;
+ payload_data.data = rk_UNCONST(payload);
+
+ sp = krb5_storage_from_data(&payload_data);
+ if (sp == NULL)
+ return KRB5_CC_NOMEM;
+
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_BE);
+
+ ret = krb5_ret_int32(sp, version);
+ if (ret == 0)
+ ret = krb5_ret_string(sp, primary);
+
+ krb5_storage_free(sp);
+
+ return ret;
+}
+
+/*
+ * Get or initialize the primary name within collection_id and set
+ * *subsidiary to its value. If initializing a legacy collection, look
+ * for a legacy cache and add it to the collection.
+ */
+static krb5_error_code
+get_primary_name(krb5_context context,
+ const char *anchor_name,
+ const char *collection_name,
+ key_serial_t collection_id,
+ char **psubsidiary)
+{
+ krb5_error_code ret;
+ key_serial_t primary_id, legacy;
+ void *payload = NULL;
+ int payloadlen;
+ int32_t version;
+ char *subsidiary_name = NULL;
+
+ *psubsidiary = NULL;
+
+ primary_id = keyctl_search(collection_id, KRCC_KEY_TYPE_USER,
+ KRCC_COLLECTION_PRIMARY, 0);
+ if (primary_id == -1) {
+ /*
+ * Initialize the primary key using the collection name. We can't name
+ * a key with the empty string, so map that to an arbitrary string.
+ */
+ subsidiary_name = strdup((*collection_name == '\0') ? "tkt" :
+ collection_name);
+ if (subsidiary_name == NULL) {
+ ret = krb5_enomem(context);
+ goto cleanup;
+ }
+
+ ret = set_primary_name(context, collection_id, subsidiary_name);
+ if (ret)
+ goto cleanup;
+
+ if (strcmp(anchor_name, KRCC_LEGACY_ANCHOR) == 0) {
+ /*
+ * Look for a cache created by old code. If we find one, add it to
+ * the collection.
+ */
+ legacy = keyctl_search(KEY_SPEC_SESSION_KEYRING,
+ KRCC_KEY_TYPE_KEYRING, subsidiary_name, 0);
+ if (legacy != -1 && keyctl_link(legacy, collection_id) == -1) {
+ ret = errno;
+ goto cleanup;
+ }
+ }
+ } else {
+ /* Read, parse, and free the primary key's payload. */
+ payloadlen = keyctl_read_alloc(primary_id, &payload);
+ if (payloadlen == -1) {
+ ret = errno;
+ goto cleanup;
+ }
+ ret = parse_index(context, &version, &subsidiary_name, payload,
+ payloadlen);
+ if (ret)
+ goto cleanup;
+
+ if (version != KRCC_COLLECTION_VERSION) {
+ ret = KRB5_KCC_UNKNOWN_VERSION;
+ goto cleanup;
+ }
+ }
+
+ *psubsidiary = subsidiary_name;
+ subsidiary_name = NULL;
+
+cleanup:
+ free(payload);
+ free(subsidiary_name);
+
+ return ret;
+}
+
+/*
+ * Note: MIT keyring code uses krb5int_random_string() as if the second argument
+ * is a character count rather than a size. The function below takes a character
+ * count to match the usage in this file correctly.
+ */
+static krb5_error_code
+generate_random_string(krb5_context context, char *s, size_t slen)
+{
+ static char chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
+ char *p;
+ size_t i;
+
+ p = malloc(slen);
+ if (p == NULL)
+ return krb5_enomem(context);
+
+ krb5_generate_random_block(p, slen);
+
+ for (i = 0; i < slen; i++)
+ s[i] = chars[p[i] % (sizeof(chars) - 1)];
+
+ s[i] = '\0';
+ free(p);
+
+ return 0;
+}
+
+/*
+ * Create a keyring with a unique random name within collection_id. Set
+ * *subsidiary to its name and *cache_id to its key serial number.
+ */
+static krb5_error_code
+add_unique_keyring(krb5_context context,
+ key_serial_t collection_id,
+ char **psubsidiary,
+ key_serial_t *pcache_id)
+{
+ key_serial_t key;
+ krb5_error_code ret;
+ char uniquename[sizeof(KRCC_NAME_PREFIX) + KRCC_NAME_RAND_CHARS];
+ int prefixlen = sizeof(KRCC_NAME_PREFIX) - 1;
+ int tries;
+
+ *psubsidiary = NULL;
+ *pcache_id = 0;
+
+ memcpy(uniquename, KRCC_NAME_PREFIX, sizeof(KRCC_NAME_PREFIX));
+
+ for (key = -1, tries = 0; tries < 5; tries++) {
+ ret = generate_random_string(context, uniquename + prefixlen,
+ KRCC_NAME_RAND_CHARS);
+ if (ret)
+ return ret;
+
+ key = keyctl_search(collection_id, KRCC_KEY_TYPE_KEYRING, uniquename, 0);
+ if (key == -1) {
+ /* Name does not already exist. Create it to reserve the name. */
+ key = add_key(KRCC_KEY_TYPE_KEYRING, uniquename, NULL, 0, collection_id);
+ if (key == -1)
+ return errno;
+ break;
+ }
+ }
+
+ *psubsidiary = strdup(uniquename);
+ if (*psubsidiary == NULL)
+ return krb5_enomem(context);
+
+ *pcache_id = key;
+
+ return 0;
+}
+
+static krb5_error_code
+add_cred_key(const char *name,
+ const void *payload,
+ size_t plen,
+ key_serial_t cache_id,
+ krb5_boolean legacy_type,
+ key_serial_t *pkey)
+{
+ key_serial_t key;
+
+ *pkey = -1;
+
+ if (!legacy_type) {
+ /* Try the preferred cred key type; fall back if no kernel support. */
+ key = add_key(KRCC_CRED_KEY_TYPE, name, payload, plen, cache_id);
+ if (key != -1) {
+ *pkey = key;
+ return 0;
+ } else if (errno != EINVAL && errno != ENODEV)
+ return errno;
+ }
+
+ /* Use the user key type. */
+ key = add_key(KRCC_KEY_TYPE_USER, name, payload, plen, cache_id);
+ if (key == -1)
+ return errno;
+
+ *pkey = key;
+
+ return 0;
+}
+
+static void
+update_keyring_expiration(krb5_context context,
+ krb5_ccache id,
+ key_serial_t cache_id,
+ krb5_timestamp now)
+{
+ krb5_cc_cursor cursor;
+ krb5_creds creds;
+ krb5_timestamp endtime = 0;
+ unsigned int timeout;
+
+ /*
+ * We have no way to know what is the actual timeout set on the keyring.
+ * We also cannot keep track of it in a local variable as another process
+ * can always modify the keyring independently, so just always enumerate
+ * all start TGT keys and find out the highest endtime time.
+ */
+ if (krcc_get_first(context, id, &cursor) != 0)
+ return;
+
+ for (;;) {
+ if (krcc_get_next(context, id, &cursor, &creds) != 0)
+ break;
+ if (creds.times.endtime > endtime)
+ endtime = creds.times.endtime;
+ krb5_free_cred_contents(context, &creds);
+ }
+ (void) krcc_end_get(context, id, &cursor);
+
+ if (endtime == 0) /* No creds with end times */
+ return;
+
+ /*
+ * Setting the timeout to zero would reset the timeout, so we set it to one
+ * second instead if creds are already expired.
+ */
+ timeout = endtime > now ? endtime - now : 1;
+ (void) keyctl_set_timeout(cache_id, timeout);
+}
+
+/*
+ * Create or overwrite the cache keyring, and set the default principal.
+ */
+static krb5_error_code
+initialize_internal(krb5_context context,
+ krb5_ccache id,
+ krb5_const_principal princ)
+{
+ krb5_krcache *data = KRCACHE(id);
+ krb5_error_code ret;
+ const char *cache_name, *p;
+ krb5_krcache_and_princ_id ids;
+
+ if (data == NULL)
+ return krb5_einval(context, 2);
+
+ memset(&ids, 0, sizeof(ids));
+ ids.krcu_cache_and_princ_id = heim_base_atomic_load(&data->krc_cache_and_principal_id);
+
+ ret = clear_cache_keyring(context, &ids.krcu_cache_id);
+ if (ret)
+ return ret;
+
+ if (ids.krcu_cache_id == 0) {
+ /*
+ * The key didn't exist at resolve time, or was destroyed after resolving.
+ * Check again and create the key if it still isn't there.
+ */
+ p = strrchr(data->krc_name, ':');
+ cache_name = (p != NULL) ? p + 1 : data->krc_name;
+ ret = find_or_create_keyring(data->krc_coll_id, 0, cache_name, &ids.krcu_cache_id);
+ if (ret)
+ return ret;
+ }
+
+ /*
+ * If this is the legacy cache in a legacy session collection, link it
+ * directly to the session keyring so that old code can see it.
+ */
+ if (is_legacy_cache_name_p(data->krc_name))
+ (void) keyctl_link(ids.krcu_cache_id, session_write_anchor());
+
+ if (princ != NULL) {
+ ret = save_principal(context, ids.krcu_cache_id, princ, &ids.krcu_princ_id);
+ if (ret)
+ return ret;
+ } else
+ ids.krcu_princ_id = 0;
+
+ /*
+ * Save time offset if it is valid and this is not a legacy cache. Legacy
+ * applications would fail to parse the new key in the cache keyring.
+ */
+ if (context->kdc_sec_offset && !is_legacy_cache_name_p(data->krc_name)) {
+ ret = save_time_offsets(context,
+ ids.krcu_cache_id,
+ context->kdc_sec_offset,
+ context->kdc_usec_offset);
+ if (ret)
+ return ret;
+ }
+
+ /* update cache and principal IDs atomically */
+ heim_base_atomic_store(&data->krc_cache_and_principal_id, ids.krcu_cache_and_princ_id);
+
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+krcc_initialize(krb5_context context, krb5_ccache id, krb5_principal princ)
+{
+ krb5_krcache *data = KRCACHE(id);
+ krb5_error_code ret;
+
+ if (data == NULL)
+ return krb5_einval(context, 2);
+
+ if (princ == NULL)
+ return KRB5_CC_BADNAME;
+
+ ret = initialize_internal(context, id, princ);
+ if (ret == 0)
+ update_change_time(context, 0, data);
+
+ return ret;
+}
+
+/* Release the ccache handle. */
+static krb5_error_code KRB5_CALLCONV
+krcc_close(krb5_context context, krb5_ccache id)
+{
+ krb5_krcache *data = KRCACHE(id);
+
+ if (data == NULL)
+ return krb5_einval(context, 2);
+
+ free(data->krc_subsidiary);
+ free(data->krc_collection);
+ free(data->krc_name);
+ krb5_data_free(&id->data);
+
+ return 0;
+}
+
+/*
+ * Clear out a ccache keyring, unlinking all keys within it.
+ */
+static krb5_error_code
+clear_cache_keyring(krb5_context context,
+ atomic_key_serial_t *pcache_id)
+{
+ int res;
+ key_serial_t cache_id = heim_base_atomic_load(pcache_id);
+
+ _krb5_debug(context, 10, "clear_cache_keyring: cache_id %d\n", cache_id);
+
+ if (cache_id != 0) {
+ res = keyctl_clear(cache_id);
+ if (res == -1 && (errno == EACCES || errno == ENOKEY)) {
+ /*
+ * Possibly the keyring was destroyed between krcc_resolve() and now;
+ * if we really don't have permission, we will fail later.
+ */
+ res = 0;
+ heim_base_atomic_store(pcache_id, 0);
+ }
+ if (res == -1)
+ return errno;
+ }
+
+ return 0;
+}
+
+/* Destroy the cache keyring */
+static krb5_error_code KRB5_CALLCONV
+krcc_destroy(krb5_context context, krb5_ccache id)
+{
+ krb5_error_code ret = 0;
+ krb5_krcache *data = KRCACHE(id);
+ int res;
+
+ if (data == NULL)
+ return krb5_einval(context, 2);
+
+ /* no atomics, destroy is not thread-safe */
+ (void) clear_cache_keyring(context, &data->krc_cache_id);
+
+ if (data->krc_cache_id != 0) {
+ res = keyctl_unlink(data->krc_cache_id, data->krc_coll_id);
+ if (res < 0) {
+ ret = errno;
+ _krb5_debug(context, 10, "unlinking key %d from ring %d: %s",
+ data->krc_cache_id, data->krc_coll_id, error_message(errno));
+ }
+ /* If this is a legacy cache, unlink it from the session anchor. */
+ if (is_legacy_cache_name_p(data->krc_name))
+ (void) keyctl_unlink(data->krc_cache_id, session_write_anchor());
+ }
+
+ heim_base_atomic_store(&data->krc_princ_id, 0);
+
+ /* krcc_close is called by libkrb5, do not double-free */
+ return ret;
+}
+
+/* Create a cache handle for a cache ID. */
+static krb5_error_code
+make_cache(krb5_context context,
+ key_serial_t collection_id,
+ key_serial_t cache_id,
+ const char *anchor_name,
+ const char *collection_name,
+ const char *subsidiary_name,
+ krb5_ccache *cache)
+{
+ krb5_error_code ret;
+ krb5_krcache *data;
+ key_serial_t princ_id = 0;
+
+ /* Determine the key containing principal information, if present. */
+ princ_id = keyctl_search(cache_id, KRCC_KEY_TYPE_USER, KRCC_SPEC_PRINC_KEYNAME, 0);
+ if (princ_id == -1)
+ princ_id = 0;
+
+ ret = alloc_cache(context, collection_id, cache_id,
+ anchor_name, collection_name, subsidiary_name, &data);
+ if (ret)
+ return ret;
+
+ if (*cache == NULL) {
+ ret = _krb5_cc_allocate(context, &krb5_krcc_ops, cache);
+ if (ret) {
+ free(data->krc_name);
+ free(data);
+ return ret;
+ }
+ }
+
+ data->krc_princ_id = princ_id;
+
+ (*cache)->data.data = data;
+ (*cache)->data.length = sizeof(*data);
+
+ return 0;
+}
+
+/* Create a keyring ccache handle for the given residual string. */
+static krb5_error_code KRB5_CALLCONV
+krcc_resolve_2(krb5_context context,
+ krb5_ccache *id,
+ const char *residual,
+ const char *sub)
+{
+ krb5_error_code ret;
+ atomic_key_serial_t collection_id;
+ key_serial_t cache_id;
+ char *anchor_name = NULL, *collection_name = NULL, *subsidiary_name = NULL;
+
+ ret = parse_residual(context, residual, &anchor_name, &collection_name,
+ &subsidiary_name);
+ if (ret)
+ goto cleanup;
+ if (sub) {
+ free(subsidiary_name);
+ if ((subsidiary_name = strdup(sub)) == NULL) {
+ ret = krb5_enomem(context);
+ goto cleanup;
+ }
+ }
+
+ ret = get_collection(context, anchor_name, collection_name, &collection_id);
+ if (ret)
+ goto cleanup;
+
+ if (subsidiary_name == NULL) {
+ /* Retrieve or initialize the primary name for the collection. */
+ ret = get_primary_name(context, anchor_name, collection_name,
+ collection_id, &subsidiary_name);
+ if (ret)
+ goto cleanup;
+ }
+
+ /* Look up the cache keyring ID, if the cache is already initialized. */
+ cache_id = keyctl_search(collection_id, KRCC_KEY_TYPE_KEYRING,
+ subsidiary_name, 0);
+ if (cache_id < 0)
+ cache_id = 0;
+
+ ret = make_cache(context, collection_id, cache_id, anchor_name,
+ collection_name, subsidiary_name, id);
+ if (ret)
+ goto cleanup;
+
+cleanup:
+ free(anchor_name);
+ free(collection_name);
+ free(subsidiary_name);
+
+ return ret;
+}
+
+struct krcc_cursor {
+ size_t numkeys;
+ size_t currkey;
+ key_serial_t princ_id;
+ key_serial_t offsets_id;
+ key_serial_t *keys;
+};
+
+/* Prepare for a sequential iteration over the cache keyring. */
+static krb5_error_code
+krcc_get_first(krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+ struct krcc_cursor *krcursor;
+ krb5_krcache *data = KRCACHE(id);
+ key_serial_t cache_id;
+ void *keys;
+ long size;
+
+ if (data == NULL)
+ return krb5_einval(context, 2);
+
+ cache_id = heim_base_atomic_load(&data->krc_cache_id);
+ if (cache_id == 0)
+ return KRB5_FCC_NOFILE;
+
+ size = keyctl_read_alloc(cache_id, &keys);
+ if (size == -1) {
+ _krb5_debug(context, 10, "Error getting from keyring: %s\n",
+ strerror(errno));
+ return KRB5_CC_IO;
+ }
+
+ krcursor = calloc(1, sizeof(*krcursor));
+ if (krcursor == NULL) {
+ free(keys);
+ return KRB5_CC_NOMEM;
+ }
+
+ krcursor->princ_id = heim_base_atomic_load(&data->krc_princ_id);
+ krcursor->offsets_id = keyctl_search(cache_id, KRCC_KEY_TYPE_USER,
+ KRCC_TIME_OFFSETS, 0);
+ krcursor->numkeys = size / sizeof(key_serial_t);
+ krcursor->keys = keys;
+
+ *cursor = krcursor;
+
+ return 0;
+}
+
+static krb5_error_code
+keyctl_read_krb5_data(key_serial_t keyid, krb5_data *payload)
+{
+ krb5_data_zero(payload);
+
+ payload->length = keyctl_read_alloc(keyid, &payload->data);
+
+ return (payload->length == -1) ? KRB5_FCC_NOFILE : 0;
+}
+
+/* Get the next credential from the cache keyring. */
+static krb5_error_code KRB5_CALLCONV
+krcc_get_next(krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor,
+ krb5_creds *creds)
+{
+ struct krcc_cursor *krcursor;
+ krb5_error_code ret;
+ krb5_data payload;
+ krb5_storage *sp;
+
+ memset(creds, 0, sizeof(krb5_creds));
+
+ krcursor = *cursor;
+ if (krcursor == NULL)
+ return KRB5_CC_END;
+
+ if (krcursor->currkey >= krcursor->numkeys)
+ return KRB5_CC_END;
+
+ /*
+ * If we're pointing at the entry with the principal, or at the key
+ * with the time offsets, skip it.
+ */
+ while (krcursor->keys[krcursor->currkey] == krcursor->princ_id ||
+ krcursor->keys[krcursor->currkey] == krcursor->offsets_id) {
+ krcursor->currkey++;
+ if (krcursor->currkey >= krcursor->numkeys)
+ return KRB5_CC_END;
+ }
+
+ ret = keyctl_read_krb5_data(krcursor->keys[krcursor->currkey], &payload);
+ if (ret) {
+ _krb5_debug(context, 10, "Error reading key %d: %s\n",
+ krcursor->keys[krcursor->currkey],
+ strerror(errno));
+ return ret;
+ }
+ krcursor->currkey++;
+
+ sp = krb5_storage_from_data(&payload);
+ if (sp == NULL) {
+ ret = KRB5_CC_IO;
+ } else {
+ ret = krb5_ret_creds(sp, creds);
+ krb5_storage_free(sp);
+ }
+
+ krb5_data_free(&payload);
+
+ return ret;
+}
+
+/* Release an iteration cursor. */
+static krb5_error_code KRB5_CALLCONV
+krcc_end_get(krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor)
+{
+ struct krcc_cursor *krcursor = *cursor;
+
+ if (krcursor != NULL) {
+ free(krcursor->keys);
+ free(krcursor);
+ }
+
+ *cursor = NULL;
+
+ return 0;
+}
+
+/* Create keyring data for a credential cache. */
+static krb5_error_code
+alloc_cache(krb5_context context,
+ key_serial_t collection_id,
+ key_serial_t cache_id,
+ const char *anchor_name,
+ const char *collection_name,
+ const char *subsidiary_name,
+ krb5_krcache **pdata)
+{
+ krb5_error_code ret;
+ krb5_krcache *data;
+
+ *pdata = NULL;
+
+ data = calloc(1, sizeof(*data));
+ if (data == NULL)
+ return KRB5_CC_NOMEM;
+
+ ret = make_subsidiary_residual(context, anchor_name, collection_name,
+ subsidiary_name, &data->krc_name);
+ if (ret ||
+ (data->krc_collection = strdup(collection_name)) == NULL ||
+ (data->krc_subsidiary = strdup(subsidiary_name ? subsidiary_name : "tkt")) == NULL) {
+ if (data) {
+ free(data->krc_collection);
+ free(data->krc_name);
+ }
+ free(data);
+ if (ret == 0)
+ ret = krb5_enomem(context);
+ return ret;
+ }
+
+ heim_base_atomic_init(&data->krc_princ_id, 0);
+ heim_base_atomic_init(&data->krc_cache_id, cache_id);
+ data->krc_coll_id = collection_id;
+ data->krc_changetime = 0;
+ data->krc_is_legacy = (strcmp(anchor_name, KRCC_LEGACY_ANCHOR) == 0);
+
+ update_change_time(context, 0, data);
+
+ *pdata = data;
+
+ return 0;
+}
+
+/* Create a new keyring cache with a unique name. */
+static krb5_error_code KRB5_CALLCONV
+krcc_gen_new(krb5_context context, krb5_ccache *id)
+{
+ krb5_error_code ret;
+ char *anchor_name, *collection_name, *subsidiary_name;
+ char *new_subsidiary_name = NULL, *new_residual = NULL;
+ krb5_krcache *data;
+ atomic_key_serial_t collection_id;
+ key_serial_t cache_id = 0;
+
+ /* Determine the collection in which we will create the cache.*/
+ ret = get_default(context, &anchor_name, &collection_name,
+ &subsidiary_name);
+ if (ret)
+ return ret;
+
+ if (anchor_name == NULL) {
+ ret = parse_residual(context, KRCC_DEFAULT_UNIQUE_COLLECTION, &anchor_name,
+ &collection_name, &subsidiary_name);
+ if (ret)
+ return ret;
+ }
+ if (subsidiary_name != NULL) {
+ krb5_set_error_message(context, KRB5_DCC_CANNOT_CREATE,
+ N_("Can't create new subsidiary cache because default cache "
+ "is already a subsidiary", ""));
+ ret = KRB5_DCC_CANNOT_CREATE;
+ goto cleanup;
+ }
+
+ /* Make a unique keyring within the chosen collection. */
+ ret = get_collection(context, anchor_name, collection_name, &collection_id);
+ if (ret)
+ goto cleanup;
+
+ ret = add_unique_keyring(context, collection_id, &new_subsidiary_name, &cache_id);
+ if (ret)
+ goto cleanup;
+
+ ret = alloc_cache(context, collection_id, cache_id,
+ anchor_name, collection_name, new_subsidiary_name,
+ &data);
+ if (ret)
+ goto cleanup;
+
+ (*id)->data.data = data;
+ (*id)->data.length = sizeof(*data);
+
+cleanup:
+ free(anchor_name);
+ free(collection_name);
+ free(subsidiary_name);
+ free(new_subsidiary_name);
+ free(new_residual);
+
+ return ret;
+}
+
+/* Return an alias to the residual string of the cache. */
+static krb5_error_code KRB5_CALLCONV
+krcc_get_name_2(krb5_context context,
+ krb5_ccache id,
+ const char **name,
+ const char **collection_name,
+ const char **subsidiary_name)
+{
+ krb5_krcache *data = KRCACHE(id);
+
+ if (data == NULL)
+ return krb5_einval(context, 2);
+
+ if (name)
+ *name = data->krc_name;
+ if (collection_name)
+ *collection_name = data->krc_collection;
+ if (subsidiary_name)
+ *subsidiary_name = data->krc_subsidiary;
+ return 0;
+}
+
+/* Retrieve a copy of the default principal, if the cache is initialized. */
+static krb5_error_code KRB5_CALLCONV
+krcc_get_principal(krb5_context context,
+ krb5_ccache id,
+ krb5_principal *princ)
+{
+ krb5_krcache *data = KRCACHE(id);
+ krb5_error_code ret;
+ krb5_storage *sp = NULL;
+ krb5_data payload;
+ krb5_krcache_and_princ_id ids;
+
+ krb5_data_zero(&payload);
+ *princ = NULL;
+
+ if (data == NULL)
+ return krb5_einval(context, 2);
+
+ memset(&ids, 0, sizeof(ids));
+ ids.krcu_cache_and_princ_id = heim_base_atomic_load(&data->krc_cache_and_principal_id);
+ if (ids.krcu_cache_id == 0 || ids.krcu_princ_id == 0) {
+ ret = KRB5_FCC_NOFILE;
+ krb5_set_error_message(context, ret,
+ N_("Credentials cache keyring '%s' not found", ""),
+ data->krc_name);
+ goto cleanup;
+ }
+
+ ret = keyctl_read_krb5_data(ids.krcu_princ_id, &payload);
+ if (ret) {
+ _krb5_debug(context, 10, "Reading principal key %d: %s\n",
+ ids.krcu_princ_id, strerror(errno));
+ goto cleanup;
+ }
+
+ sp = krb5_storage_from_data(&payload);
+ if (sp == NULL) {
+ ret = KRB5_CC_IO;
+ goto cleanup;
+ }
+
+ ret = krb5_ret_principal(sp, princ);
+ if (ret)
+ goto cleanup;
+
+cleanup:
+ krb5_storage_free(sp);
+ krb5_data_free(&payload);
+
+ return ret;
+}
+
+/* Remove a cred from the cache keyring */
+static krb5_error_code KRB5_CALLCONV
+krcc_remove_cred(krb5_context context, krb5_ccache id,
+ krb5_flags which, krb5_creds *mcred)
+{
+ krb5_krcache *data = KRCACHE(id);
+ krb5_error_code ret, ret2;
+ krb5_cc_cursor cursor;
+ krb5_creds found_cred;
+ krb5_krcache_and_princ_id ids;
+
+ if (data == NULL)
+ return krb5_einval(context, 2);
+
+ ret = krcc_get_first(context, id, &cursor);
+ if (ret)
+ return ret;
+
+ memset(&ids, 0, sizeof(ids));
+ ids.krcu_cache_and_princ_id = heim_base_atomic_load(&data->krc_cache_and_principal_id);
+
+ while ((ret = krcc_get_next(context, id, &cursor, &found_cred)) == 0) {
+ struct krcc_cursor *krcursor = cursor;
+
+ if (!krb5_compare_creds(context, which, mcred, &found_cred)) {
+ krb5_free_cred_contents(context, &found_cred);
+ continue;
+ }
+
+ _krb5_debug(context, 10, "Removing cred %d from cache_id %d, princ_id %d\n",
+ krcursor->keys[krcursor->currkey - 1],
+ ids.krcu_cache_id, ids.krcu_princ_id);
+
+ keyctl_invalidate(krcursor->keys[krcursor->currkey - 1]);
+ krcursor->keys[krcursor->currkey - 1] = 0;
+ krb5_free_cred_contents(context, &found_cred);
+ }
+
+ ret2 = krcc_end_get(context, id, &cursor);
+ if (ret == KRB5_CC_END)
+ ret = ret2;
+
+ return ret;
+}
+
+/* Set flags on the cache. (We don't care about any flags.) */
+static krb5_error_code KRB5_CALLCONV
+krcc_set_flags(krb5_context context, krb5_ccache id, krb5_flags flags)
+{
+ return 0;
+}
+
+static int KRB5_CALLCONV
+krcc_get_version(krb5_context context, krb5_ccache id)
+{
+ return 0;
+}
+
+/* Store a credential in the cache keyring. */
+static krb5_error_code KRB5_CALLCONV
+krcc_store(krb5_context context, krb5_ccache id, krb5_creds *creds)
+{
+ krb5_error_code ret;
+ krb5_krcache *data = KRCACHE(id);
+ krb5_storage *sp = NULL;
+ char *keyname = NULL;
+ key_serial_t cred_key, cache_id;
+ krb5_timestamp now;
+ krb5_data payload;
+
+ krb5_data_zero(&payload);
+
+ if (data == NULL)
+ return krb5_einval(context, 2);
+
+ cache_id = heim_base_atomic_load(&data->krc_cache_id);
+ if (cache_id == 0)
+ return KRB5_FCC_NOFILE;
+
+ ret = krb5_unparse_name(context, creds->server, &keyname);
+ if (ret)
+ goto cleanup;
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", ""));
+ ret = KRB5_CC_NOMEM;
+ goto cleanup;
+ }
+
+ ret = krb5_store_creds(sp, creds);
+ if (ret)
+ goto cleanup;
+
+ ret = krb5_storage_to_data(sp, &payload);
+ if (ret)
+ goto cleanup;
+
+ _krb5_debug(context, 10, "krcc_store: adding new key '%s' to keyring %d\n",
+ keyname, cache_id);
+ ret = add_cred_key(keyname, payload.data, payload.length, cache_id,
+ data->krc_is_legacy, &cred_key);
+ if (ret)
+ goto cleanup;
+
+ ret = krb5_timeofday(context, &now);
+ if (ret)
+ goto cleanup;
+
+ update_change_time(context, now, data);
+
+ /* Set timeout on credential key */
+ if (creds->times.endtime > now)
+ (void) keyctl_set_timeout(cred_key, creds->times.endtime - now);
+
+ /* Set timeout on credential cache keyring */
+ update_keyring_expiration(context, id, cache_id, now);
+
+cleanup:
+ krb5_data_free(&payload);
+ krb5_storage_free(sp);
+ krb5_xfree(keyname);
+
+ return ret;
+}
+
+/*
+ * Get the cache's last modification time. (This is currently broken; it
+ * returns only the last change made using this handle.)
+ */
+static krb5_error_code KRB5_CALLCONV
+krcc_lastchange(krb5_context context,
+ krb5_ccache id,
+ krb5_timestamp *change_time)
+{
+ krb5_krcache *data = KRCACHE(id);
+
+ if (data == NULL)
+ return krb5_einval(context, 2);
+
+ *change_time = heim_base_atomic_load(&data->krc_changetime);
+
+ return 0;
+}
+
+static krb5_error_code
+save_principal(krb5_context context,
+ key_serial_t cache_id,
+ krb5_const_principal princ,
+ atomic_key_serial_t *pprinc_id)
+{
+ krb5_error_code ret;
+ krb5_storage *sp;
+ key_serial_t newkey;
+ krb5_data payload;
+
+ krb5_data_zero(&payload);
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", ""));
+ return KRB5_CC_NOMEM;
+ }
+
+ ret = krb5_store_principal(sp, princ);
+ if (ret) {
+ krb5_storage_free(sp);
+ return ret;
+ }
+
+ ret = krb5_storage_to_data(sp, &payload);
+ if (ret) {
+ krb5_storage_free(sp);
+ return ret;
+ }
+
+ krb5_storage_free(sp);
+ {
+ krb5_error_code tmp;
+ char *princname = NULL;
+
+ tmp = krb5_unparse_name(context, princ, &princname);
+ _krb5_debug(context, 10, "save_principal: adding new key '%s' "
+ "to keyring %d for principal '%s'\n",
+ KRCC_SPEC_PRINC_KEYNAME, cache_id,
+ tmp ? "<unknown>" : princname);
+ if (tmp == 0)
+ krb5_xfree(princname);
+ }
+
+ /* Add new key into keyring */
+ newkey = add_key(KRCC_KEY_TYPE_USER, KRCC_SPEC_PRINC_KEYNAME,
+ payload.data, payload.length, cache_id);
+ if (newkey == -1) {
+ ret = errno;
+ _krb5_debug(context, 10, "Error adding principal key: %s\n", strerror(ret));
+ } else {
+ ret = 0;
+ heim_base_atomic_store(pprinc_id, newkey);
+ }
+
+ krb5_data_free(&payload);
+
+ return ret;
+}
+
+/* Add a key to the cache keyring containing the given time offsets. */
+static krb5_error_code
+save_time_offsets(krb5_context context,
+ key_serial_t cache_id,
+ int32_t sec_offset,
+ int32_t usec_offset)
+{
+ krb5_error_code ret;
+ key_serial_t newkey;
+ krb5_storage *sp;
+ krb5_data payload;
+
+ krb5_data_zero(&payload);
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", ""));
+ return KRB5_CC_NOMEM;
+ }
+
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_BE);
+
+ ret = krb5_store_int32(sp, sec_offset);
+ if (ret == 0)
+ ret = krb5_store_int32(sp, usec_offset);
+ if (ret) {
+ krb5_storage_free(sp);
+ return ret;
+ }
+
+ ret = krb5_storage_to_data(sp, &payload);
+ if (ret) {
+ krb5_storage_free(sp);
+ return ret;
+ }
+
+ krb5_storage_free(sp);
+
+ newkey = add_key(KRCC_KEY_TYPE_USER, KRCC_TIME_OFFSETS, payload.data,
+ payload.length, cache_id);
+ ret = newkey == -1 ? errno : 0;
+
+ krb5_data_free(&payload);
+
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+krcc_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat offset)
+{
+ krb5_krcache *data = KRCACHE(id);
+ key_serial_t cache_id;
+ krb5_error_code ret;
+
+ if (data == NULL)
+ return krb5_einval(context, 2);
+
+ cache_id = heim_base_atomic_load(&data->krc_cache_id);
+
+ ret = save_time_offsets(context, cache_id, (int32_t)offset, 0);
+ if (ret == 0)
+ update_change_time(context, 0, data);
+
+ return ret;
+}
+
+/* Retrieve and parse the key in the cache keyring containing time offsets. */
+static krb5_error_code KRB5_CALLCONV
+krcc_get_kdc_offset(krb5_context context,
+ krb5_ccache id,
+ krb5_deltat *offset)
+{
+ krb5_krcache *data = KRCACHE(id);
+ krb5_error_code ret = 0;
+ key_serial_t key, cache_id;
+ krb5_storage *sp = NULL;
+ krb5_data payload;
+ int32_t sec_offset = 0;
+
+ if (data == NULL)
+ return krb5_einval(context, 2);
+
+ krb5_data_zero(&payload);
+
+ cache_id = heim_base_atomic_load(&data->krc_cache_id);
+ if (cache_id == 0) {
+ ret = KRB5_FCC_NOFILE;
+ goto cleanup;
+ }
+
+ key = keyctl_search(cache_id, KRCC_KEY_TYPE_USER, KRCC_TIME_OFFSETS, 0);
+ if (key == -1) {
+ ret = ENOENT;
+ goto cleanup;
+ }
+
+ ret = keyctl_read_krb5_data(key, &payload);
+ if (ret) {
+ _krb5_debug(context, 10, "Reading time offsets key %d: %s\n",
+ key, strerror(errno));
+ goto cleanup;
+ }
+
+ sp = krb5_storage_from_data(&payload);
+ if (sp == NULL) {
+ ret = krb5_enomem(context);;
+ goto cleanup;
+ }
+
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_BE);
+
+ ret = krb5_ret_int32(sp, &sec_offset);
+ /*
+ * We can't output nor use the usec_offset here, so we don't bother to read
+ * it, though we do write it.
+ */
+
+cleanup:
+ *offset = sec_offset;
+ krb5_storage_free(sp);
+ krb5_data_free(&payload);
+ return ret;
+}
+
+struct krcc_iter {
+ atomic_key_serial_t collection_id;
+ char *anchor_name;
+ char *collection_name;
+ char *subsidiary_name;
+ char *primary_name;
+ krb5_boolean first;
+ long num_keys;
+ long next_key;
+ key_serial_t *keys;
+};
+
+static krb5_error_code KRB5_CALLCONV
+krcc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor)
+{
+ struct krcc_iter *iter;
+ krb5_error_code ret;
+ void *keys;
+ long size;
+
+ *cursor = NULL;
+
+ iter = calloc(1, sizeof(*iter));
+ if (iter == NULL) {
+ ret = krb5_enomem(context);
+ goto error;
+ }
+ iter->first = TRUE;
+
+ ret = get_default(context, &iter->anchor_name, &iter->collection_name,
+ &iter->subsidiary_name);
+ if (ret)
+ goto error;
+
+ /* If there is no default collection, return an empty cursor. */
+ if (iter->anchor_name == NULL) {
+ *cursor = iter;
+ return 0;
+ }
+
+ ret = get_collection(context, iter->anchor_name, iter->collection_name,
+ &iter->collection_id);
+ if (ret)
+ goto error;
+
+ if (iter->subsidiary_name == NULL) {
+ ret = get_primary_name(context, iter->anchor_name,
+ iter->collection_name, iter->collection_id,
+ &iter->primary_name);
+ if (ret)
+ goto error;
+
+ size = keyctl_read_alloc(iter->collection_id, &keys);
+ if (size == -1) {
+ ret = errno;
+ goto error;
+ }
+ iter->keys = keys;
+ iter->num_keys = size / sizeof(key_serial_t);
+ }
+
+ *cursor = iter;
+
+ return 0;
+
+error:
+ krcc_end_cache_get(context, iter);
+
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+krcc_get_cache_next(krb5_context context,
+ krb5_cc_cursor cursor,
+ krb5_ccache *cache)
+{
+ krb5_error_code ret;
+ struct krcc_iter *iter = cursor;
+ key_serial_t key, cache_id = 0;
+ const char *first_name, *keytype, *sep, *subsidiary_name;
+ size_t keytypelen;
+ char *description = NULL;
+
+ *cache = NULL;
+
+ /* No keyring available */
+ if (iter->collection_id == 0)
+ return KRB5_CC_END;
+
+ if (iter->first) {
+ /*
+ * Look for the primary cache for a collection cursor, or the
+ * subsidiary cache for a subsidiary cursor.
+ */
+ iter->first = FALSE;
+ first_name = (iter->primary_name != NULL) ? iter->primary_name :
+ iter->subsidiary_name;
+ cache_id = keyctl_search(iter->collection_id, KRCC_KEY_TYPE_KEYRING,
+ first_name, 0);
+ if (cache_id != -1) {
+ return make_cache(context, iter->collection_id, cache_id,
+ iter->anchor_name, iter->collection_name,
+ first_name, cache);
+ }
+ }
+
+ /* A subsidiary cursor yields at most the first cache. */
+ if (iter->subsidiary_name != NULL)
+ return KRB5_CC_END;
+
+ keytype = KRCC_KEY_TYPE_KEYRING ";";
+ keytypelen = strlen(keytype);
+
+ for (ret = KRB5_CC_END; iter->next_key < iter->num_keys; iter->next_key++) {
+ free(description);
+ description = NULL;
+
+ /*
+ * Get the key description, which should have the form:
+ * typename;UID;GID;permissions;description
+ */
+ key = iter->keys[iter->next_key];
+ if (keyctl_describe_alloc(key, &description) < 0)
+ continue;
+ sep = strrchr(description, ';');
+ if (sep == NULL)
+ continue;
+ subsidiary_name = sep + 1;
+
+ /* Skip this key if it isn't a keyring. */
+ if (strncmp(description, keytype, keytypelen) != 0)
+ continue;
+
+ /* Don't repeat the primary cache. */
+ if (iter->primary_name &&
+ strcmp(subsidiary_name, iter->primary_name) == 0)
+ continue;
+
+ /* We found a valid key */
+ iter->next_key++;
+ ret = make_cache(context, iter->collection_id, key, iter->anchor_name,
+ iter->collection_name, subsidiary_name, cache);
+ break;
+ }
+
+ free(description);
+
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+krcc_end_cache_get(krb5_context context, krb5_cc_cursor cursor)
+{
+ struct krcc_iter *iter = cursor;
+
+ if (iter != NULL) {
+ free(iter->anchor_name);
+ free(iter->collection_name);
+ free(iter->subsidiary_name);
+ free(iter->primary_name);
+ free(iter->keys);
+
+ memset(iter, 0, sizeof(*iter));
+ free(iter);
+ }
+
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+krcc_set_default(krb5_context context, krb5_ccache id)
+{
+ krb5_krcache *data = KRCACHE(id);
+ krb5_error_code ret;
+ char *anchor_name, *collection_name, *subsidiary_name;
+ atomic_key_serial_t collection_id;
+
+ if (data == NULL)
+ return krb5_einval(context, 2);
+
+ ret = parse_residual(context, data->krc_name,
+ &anchor_name, &collection_name, &subsidiary_name);
+ if (ret)
+ goto cleanup;
+
+ ret = get_collection(context, anchor_name, collection_name, &collection_id);
+ if (ret)
+ goto cleanup;
+
+ ret = set_primary_name(context, collection_id, subsidiary_name);
+ if (ret)
+ goto cleanup;
+
+cleanup:
+ free(anchor_name);
+ free(collection_name);
+ free(subsidiary_name);
+
+ return ret;
+}
+
+/*
+ * Utility routine: called by krcc_* functions to keep
+ * result of krcc_last_change_time up to date.
+ */
+static void
+update_change_time(krb5_context context, krb5_timestamp now, krb5_krcache *data)
+{
+ krb5_timestamp old;
+
+ if (now == 0)
+ krb5_timeofday(context, &now);
+
+ old = heim_base_exchange_time_t(&data->krc_changetime, now);
+ if (old > now) /* don't go backwards */
+ heim_base_atomic_store(&data->krc_changetime, old + 1);
+}
+
+static int
+move_key_to_new_keyring(key_serial_t parent, key_serial_t key,
+ char *desc, int desc_len, void *data)
+{
+ key_serial_t cache_id = *(key_serial_t *)data;
+
+ if (parent) {
+ if (keyctl_link(key, cache_id) == -1 ||
+ keyctl_unlink(key, parent) == -1)
+ return -1;
+ }
+
+ return 0;
+}
+
+/* Move contents of one ccache to another; destroys from cache */
+static krb5_error_code KRB5_CALLCONV
+krcc_move(krb5_context context, krb5_ccache from, krb5_ccache to)
+{
+ krb5_krcache *krfrom = KRCACHE(from);
+ krb5_krcache *krto = KRCACHE(to);
+ krb5_error_code ret;
+ krb5_timestamp now;
+ key_serial_t to_cache_id;
+
+ if (krfrom == NULL || krto == NULL)
+ return krb5_einval(context, 2);
+
+ ret = initialize_internal(context, to, NULL);
+ if (ret)
+ return ret;
+
+ krb5_timeofday(context, &now);
+ to_cache_id = heim_base_atomic_load(&krto->krc_cache_id);
+
+ if (krfrom->krc_cache_id != 0) {
+ ret = recursive_key_scan(krfrom->krc_cache_id,
+ move_key_to_new_keyring, &to_cache_id);
+ if (ret)
+ return KRB5_CC_IO;
+
+ if (keyctl_unlink(krfrom->krc_cache_id, krfrom->krc_coll_id) == -1)
+ return errno;
+
+ heim_base_exchange_32(&krto->krc_princ_id, krfrom->krc_princ_id);
+ }
+
+ update_change_time(context, now, krto);
+ krb5_cc_destroy(context, from);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+krcc_get_default_name(krb5_context context, char **str)
+{
+ *str = strdup("KEYRING:");
+ if (*str == NULL)
+ return krb5_enomem(context);
+
+ return 0;
+}
+
+/*
+ * ccache implementation storing credentials in the Linux keyring facility
+ * The default is to put them at the session keyring level.
+ * If "KEYRING:process:" or "KEYRING:thread:" is specified, then they will
+ * be stored at the process or thread level respectively.
+ */
+KRB5_LIB_VARIABLE const krb5_cc_ops krb5_krcc_ops = {
+ KRB5_CC_OPS_VERSION_5,
+ "KEYRING",
+ NULL,
+ NULL,
+ krcc_gen_new,
+ krcc_initialize,
+ krcc_destroy,
+ krcc_close,
+ krcc_store,
+ NULL, /* retrieve */
+ krcc_get_principal,
+ krcc_get_first,
+ krcc_get_next,
+ krcc_end_get,
+ krcc_remove_cred,
+ krcc_set_flags,
+ krcc_get_version,
+ krcc_get_cache_first,
+ krcc_get_cache_next,
+ krcc_end_cache_get,
+ krcc_move,
+ krcc_get_default_name,
+ krcc_set_default,
+ krcc_lastchange,
+ krcc_set_kdc_offset,
+ krcc_get_kdc_offset,
+ krcc_get_name_2,
+ krcc_resolve_2
+};
+
+#endif /* HAVE_KEYUTILS_H */
diff --git a/third_party/heimdal/lib/krb5/kuserok.c b/third_party/heimdal/lib/krb5/kuserok.c
new file mode 100644
index 0000000..9d689ca
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/kuserok.c
@@ -0,0 +1,753 @@
+/*
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include "kuserok_plugin.h"
+#include <dirent.h>
+
+#ifndef SYSTEM_K5LOGIN_DIR
+/*
+ * System k5login location. File namess in this directory are expected
+ * to be usernames and to contain a list of principals allowed to login
+ * as the user named the same as the file.
+ */
+#define SYSTEM_K5LOGIN_DIR SYSCONFDIR "/k5login.d"
+#endif
+
+/* Plugin framework bits */
+
+struct plctx {
+ const char *rule;
+ const char *k5login_dir;
+ const char *luser;
+ krb5_const_principal principal;
+ unsigned int flags;
+ krb5_boolean result;
+};
+
+static krb5_error_code KRB5_LIB_CALL
+plcallback(krb5_context context, const void *plug, void *plugctx, void *userctx)
+{
+ const krb5plugin_kuserok_ftable *locate = plug;
+ struct plctx *plctx = userctx;
+
+ return locate->kuserok(plugctx, context, plctx->rule, plctx->flags,
+ plctx->k5login_dir, plctx->luser, plctx->principal,
+ &plctx->result);
+}
+
+static krb5_error_code plugin_reg_ret;
+static krb5plugin_kuserok_ftable kuserok_simple_plug;
+static krb5plugin_kuserok_ftable kuserok_sys_k5login_plug;
+static krb5plugin_kuserok_ftable kuserok_user_k5login_plug;
+static krb5plugin_kuserok_ftable kuserok_deny_plug;
+
+static void
+reg_def_plugins_once(void *ctx)
+{
+ krb5_error_code ret;
+ krb5_context context = ctx;
+
+ plugin_reg_ret = krb5_plugin_register(context, PLUGIN_TYPE_DATA,
+ KRB5_PLUGIN_KUSEROK,
+ &kuserok_simple_plug);
+ ret = krb5_plugin_register(context, PLUGIN_TYPE_DATA,
+ KRB5_PLUGIN_KUSEROK, &kuserok_sys_k5login_plug);
+ if (!plugin_reg_ret)
+ plugin_reg_ret = ret;
+ ret = krb5_plugin_register(context, PLUGIN_TYPE_DATA,
+ KRB5_PLUGIN_KUSEROK, &kuserok_user_k5login_plug);
+ if (!plugin_reg_ret)
+ plugin_reg_ret = ret;
+ ret = krb5_plugin_register(context, PLUGIN_TYPE_DATA,
+ KRB5_PLUGIN_KUSEROK, &kuserok_deny_plug);
+ if (!plugin_reg_ret)
+ plugin_reg_ret = ret;
+}
+
+/**
+ * This function is designed to be portable for Win32 and POSIX. The
+ * design does lead to multiple getpwnam_r() calls, but this is probably
+ * not a big deal.
+ *
+ * Inputs:
+ *
+ * @param context A krb5_context
+ * @param filename Name of item to introspection
+ * @param is_system_location TRUE if the dir/file are system locations or
+ * FALSE if they are user home directory locations
+ * @param dir Directory (optional)
+ * @param dirlstat A pointer to struct stat for the directory (optional)
+ * @param file File (optional)
+ * @param owner Name of user that is expected to own the file
+ */
+
+static krb5_error_code
+check_owner_dir(krb5_context context,
+ const char *filename,
+ krb5_boolean is_system_location,
+ DIR *dir,
+ struct stat *dirlstat,
+ const char *owner)
+{
+#ifdef _WIN32
+ /*
+ * XXX Implement this!
+ *
+ * The thing to do is to call _get_osfhandle() on fileno(file) and
+ * dirfd(dir) to get HANDLEs to the same, then call
+ * GetSecurityInfo() on those HANDLEs to get the security descriptor
+ * (SD), then check the owner and DACL. Checking the DACL sounds
+ * like a lot of work (what, derive a mode from the ACL the way
+ * NFSv4 servers do?). Checking the owner means doing an LSARPC
+ * lookup at least (to get the user's SID).
+ */
+ if (is_system_location || owner == NULL)
+ return 0;
+ krb5_set_error_message(context, EACCES,
+ "User k5login files not supported on Windows");
+ return EACCES;
+#else
+ struct passwd pw, *pwd = NULL;
+ char pwbuf[2048];
+ struct stat st;
+
+ heim_assert(owner != NULL, "no directory owner ?");
+
+ if (getpwnam_r(owner, &pw, pwbuf, sizeof(pwbuf), &pwd) != 0) {
+ krb5_set_error_message(context, errno,
+ "User unknown %s (getpwnam_r())", owner);
+ return EACCES;
+ }
+ if (pwd == NULL) {
+ krb5_set_error_message(context, EACCES, "no user %s", owner);
+ return EACCES;
+ }
+
+ if (fstat(dirfd(dir), &st) == -1) {
+ krb5_set_error_message(context, EACCES,
+ "fstat(%s) of k5login.d failed",
+ filename);
+ return EACCES;
+ }
+ if (!S_ISDIR(st.st_mode)) {
+ krb5_set_error_message(context, ENOTDIR, "%s not a directory",
+ filename);
+ return ENOTDIR;
+ }
+ if (st.st_dev != dirlstat->st_dev || st.st_ino != dirlstat->st_ino) {
+ krb5_set_error_message(context, EACCES,
+ "%s was renamed during kuserok "
+ "operation", filename);
+ return EACCES;
+ }
+ if ((st.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
+ krb5_set_error_message(context, EACCES,
+ "%s has world and/or group write "
+ "permissions", filename);
+ return EACCES;
+ }
+ if (pwd->pw_uid != st.st_uid && st.st_uid != 0) {
+ krb5_set_error_message(context, EACCES,
+ "%s not owned by the user (%s) or root",
+ filename, owner);
+ return EACCES;
+ }
+
+ return 0;
+#endif
+}
+
+static krb5_error_code
+check_owner_file(krb5_context context,
+ const char *filename,
+ FILE *file, const char *owner)
+{
+#ifdef _WIN32
+ /*
+ * XXX Implement this!
+ *
+ * The thing to do is to call _get_osfhandle() on fileno(file) and
+ * dirfd(dir) to get HANDLEs to the same, then call
+ * GetSecurityInfo() on those HANDLEs to get the security descriptor
+ * (SD), then check the owner and DACL. Checking the DACL sounds
+ * like a lot of work (what, derive a mode from the ACL the way
+ * NFSv4 servers do?). Checking the owner means doing an LSARPC
+ * lookup at least (to get the user's SID).
+ */
+ if (owner == NULL)
+ return 0;
+
+ krb5_set_error_message(context, EACCES,
+ "User k5login files not supported on Windows");
+ return EACCES;
+#else
+ struct passwd pw, *pwd = NULL;
+ char pwbuf[2048];
+ struct stat st;
+
+ if (owner == NULL)
+ return 0;
+
+ if (getpwnam_r(owner, &pw, pwbuf, sizeof(pwbuf), &pwd) != 0) {
+ krb5_set_error_message(context, errno,
+ "User unknown %s (getpwnam_r())", owner);
+ return EACCES;
+ }
+ if (pwd == NULL) {
+ krb5_set_error_message(context, EACCES, "no user %s", owner);
+ return EACCES;
+ }
+
+ if (fstat(fileno(file), &st) == -1) {
+ krb5_set_error_message(context, EACCES, "fstat(%s) of k5login failed",
+ filename);
+ return EACCES;
+ }
+ if (S_ISDIR(st.st_mode)) {
+ krb5_set_error_message(context, EISDIR, "k5login: %s is a directory",
+ filename);
+ return EISDIR;
+ }
+ if ((st.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
+ krb5_set_error_message(context, EISDIR,
+ "k5login %s has world and/or group write "
+ "permissions", filename);
+ return EACCES;
+ }
+ if (pwd->pw_uid != st.st_uid && st.st_uid != 0) {
+ krb5_set_error_message(context, EACCES,
+ "k5login %s not owned by the user or root",
+ filename);
+ return EACCES;
+ }
+
+ return 0;
+#endif
+}
+
+
+/* see if principal is mentioned in the filename access file, return
+ TRUE (in result) if so, FALSE otherwise */
+
+static krb5_error_code
+check_one_file(krb5_context context,
+ const char *filename,
+ const char *owner,
+ krb5_boolean is_system_location,
+ krb5_const_principal principal,
+ krb5_boolean *result)
+{
+ FILE *f;
+ char buf[BUFSIZ];
+ krb5_error_code ret;
+
+ *result = FALSE;
+
+ f = fopen(filename, "r");
+ if (f == NULL)
+ return errno;
+ rk_cloexec_file(f);
+
+ ret = check_owner_file(context, filename, f, owner);
+ if (ret)
+ goto out;
+
+ while (fgets(buf, sizeof(buf), f) != NULL) {
+ krb5_principal tmp;
+ char *newline = buf + strcspn(buf, "\n");
+
+ if (*newline != '\n') {
+ int c;
+ c = fgetc(f);
+ if (c != EOF) {
+ while (c != EOF && c != '\n')
+ c = fgetc(f);
+ /* line was too long, so ignore it */
+ continue;
+ }
+ }
+ *newline = '\0';
+ ret = krb5_parse_name(context, buf, &tmp);
+ if (ret)
+ continue;
+ *result = krb5_principal_compare(context, principal, tmp);
+ krb5_free_principal(context, tmp);
+ if (*result) {
+ fclose (f);
+ return 0;
+ }
+ }
+
+out:
+ fclose(f);
+ return 0;
+}
+
+static krb5_error_code
+check_directory(krb5_context context,
+ const char *dirname,
+ const char *owner,
+ krb5_boolean is_system_location,
+ krb5_const_principal principal,
+ krb5_boolean *result)
+{
+ DIR *d;
+ struct dirent *dent;
+ char filename[MAXPATHLEN];
+ size_t len;
+ krb5_error_code ret = 0;
+ struct stat st;
+
+ *result = FALSE;
+
+ if (lstat(dirname, &st) < 0)
+ return errno;
+
+ if (!S_ISDIR(st.st_mode)) {
+ krb5_set_error_message(context, ENOTDIR, "k5login.d not a directory");
+ return ENOTDIR;
+ }
+
+ if ((d = opendir(dirname)) == NULL) {
+ krb5_set_error_message(context, ENOTDIR, "Could not open k5login.d");
+ return errno;
+ }
+
+ ret = check_owner_dir(context, dirname, is_system_location, d, &st, owner);
+ if (ret)
+ goto out;
+
+ while ((dent = readdir(d)) != NULL) {
+ /*
+ * XXX: Should we also skip files whose names start with "."?
+ * Vim ".filename.swp" files are also good candidates to skip.
+ * Once we ignore "#*" and "*~", it is not clear what other
+ * heuristics to apply.
+ */
+ if (strcmp(dent->d_name, ".") == 0 ||
+ strcmp(dent->d_name, "..") == 0 ||
+ dent->d_name[0] == '#' || /* emacs autosave */
+ dent->d_name[strlen(dent->d_name) - 1] == '~') /* emacs backup */
+ continue;
+ len = snprintf(filename, sizeof(filename), "%s/%s", dirname, dent->d_name);
+ /* Skip too-long filenames that got truncated by snprintf() */
+ if (len < sizeof(filename)) {
+ ret = check_one_file(context, filename, owner, is_system_location,
+ principal, result);
+ if (ret == 0 && *result == TRUE)
+ break;
+ }
+ ret = 0; /* don't propagate errors upstream */
+ }
+
+out:
+ closedir(d);
+ return ret;
+}
+
+static krb5_error_code
+check_an2ln(krb5_context context,
+ krb5_const_principal principal,
+ const char *luser,
+ krb5_boolean *result)
+{
+ krb5_error_code ret;
+ char *lname;
+
+#if 0
+ /* XXX Should we make this an option? */
+ /* multi-component principals can never match */
+ if (krb5_principal_get_comp_string(context, principal, 1) != NULL) {
+ *result = FALSE;
+ return 0;
+ }
+#endif
+
+ lname = malloc(strlen(luser) + 1);
+ if (lname == NULL)
+ return krb5_enomem(context);
+ ret = krb5_aname_to_localname(context, principal, strlen(luser)+1, lname);
+ if (ret)
+ goto out;
+ if (strcmp(lname, luser) == 0)
+ *result = TRUE;
+ else
+ *result = FALSE;
+
+out:
+ free(lname);
+ return 0;
+
+}
+
+/**
+ * This function takes the name of a local user and checks if
+ * principal is allowed to log in as that user.
+ *
+ * The user may have a ~/.k5login file listing principals that are
+ * allowed to login as that user. If that file does not exist, all
+ * principals with a only one component that is identical to the
+ * username, and a realm considered local, are allowed access.
+ *
+ * The .k5login file must contain one principal per line, be owned by
+ * user and not be writable by group or other (but must be readable by
+ * anyone).
+ *
+ * Note that if the file exists, no implicit access rights are given
+ * to user@@LOCALREALM.
+ *
+ * Optionally, a set of files may be put in ~/.k5login.d (a
+ * directory), in which case they will all be checked in the same
+ * manner as .k5login. The files may be called anything, but files
+ * starting with a hash (#) , or ending with a tilde (~) are
+ * ignored. Subdirectories are not traversed. Note that this directory
+ * may not be checked by other Kerberos implementations.
+ *
+ * If no configuration file exists, match user against local domains,
+ * ie luser@@LOCAL-REALMS-IN-CONFIGURATION-FILES.
+ *
+ * @param context Kerberos 5 context.
+ * @param principal principal to check if allowed to login
+ * @param luser local user id
+ *
+ * @return returns TRUE if access should be granted, FALSE otherwise.
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_kuserok(krb5_context context,
+ krb5_principal principal,
+ const char *luser)
+{
+ return _krb5_kuserok(context, principal, luser, TRUE);
+}
+
+
+static const char *kuserok_plugin_deps[] = { "krb5", NULL };
+
+static struct heim_plugin_data
+kuserok_plugin_data = {
+ "krb5",
+ KRB5_PLUGIN_KUSEROK,
+ KRB5_PLUGIN_KUSEROK_VERSION_0,
+ kuserok_plugin_deps,
+ krb5_get_instance
+};
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+_krb5_kuserok(krb5_context context,
+ krb5_principal principal,
+ const char *luser,
+ krb5_boolean an2ln_ok)
+{
+ static heim_base_once_t reg_def_plugins = HEIM_BASE_ONCE_INIT;
+ krb5_error_code ret;
+ struct plctx ctx;
+ char **rules;
+
+ /*
+ * XXX we should have a struct with a krb5_context field and a
+ * krb5_error_code fied and pass the address of that as the ctx
+ * argument of heim_base_once_f(). For now we use a static to
+ * communicate failures. Actually, we ignore failures anyways,
+ * since we can't return them.
+ */
+ heim_base_once_f(&reg_def_plugins, context, reg_def_plugins_once);
+
+ ctx.flags = 0;
+ ctx.luser = luser;
+ ctx.principal = principal;
+ ctx.result = FALSE;
+
+ ctx.k5login_dir = krb5_config_get_string(context, NULL, "libdefaults",
+ "k5login_directory", NULL);
+
+ if (an2ln_ok)
+ ctx.flags |= KUSEROK_ANAME_TO_LNAME_OK;
+
+ if (krb5_config_get_bool_default(context, NULL, FALSE, "libdefaults",
+ "k5login_authoritative", NULL))
+ ctx.flags |= KUSEROK_K5LOGIN_IS_AUTHORITATIVE;
+
+ if ((ctx.flags & KUSEROK_K5LOGIN_IS_AUTHORITATIVE) && plugin_reg_ret)
+ return plugin_reg_ret; /* fail safe */
+
+ rules = krb5_config_get_strings(context, NULL, "libdefaults",
+ "kuserok", NULL);
+ if (rules == NULL) {
+ /* Default: check ~/.k5login */
+ ctx.rule = "USER-K5LOGIN";
+
+ ret = plcallback(context, &kuserok_user_k5login_plug, NULL, &ctx);
+ if (ret == 0)
+ goto out;
+
+ ctx.rule = "SIMPLE";
+ ret = plcallback(context, &kuserok_simple_plug, NULL, &ctx);
+ if (ret == 0)
+ goto out;
+
+ ctx.result = FALSE;
+ } else {
+ size_t n;
+
+ for (n = 0; rules[n]; n++) {
+ ctx.rule = rules[n];
+
+ ret = _krb5_plugin_run_f(context, &kuserok_plugin_data,
+ 0, &ctx, plcallback);
+ if (ret != KRB5_PLUGIN_NO_HANDLE)
+ goto out;
+ }
+ }
+
+out:
+ krb5_config_free_strings(rules);
+
+ return ctx.result;
+}
+
+/*
+ * Simple kuserok: check that the lname for the aname matches luser.
+ */
+
+static krb5_error_code KRB5_LIB_CALL
+kuserok_simple_plug_f(void *plug_ctx, krb5_context context, const char *rule,
+ unsigned int flags, const char *k5login_dir,
+ const char *luser, krb5_const_principal principal,
+ krb5_boolean *result)
+{
+ krb5_error_code ret;
+
+ if (strcmp(rule, "SIMPLE") != 0 || (flags & KUSEROK_ANAME_TO_LNAME_OK) == 0)
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ ret = check_an2ln(context, principal, luser, result);
+ if (ret == 0 && *result == FALSE)
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ return 0;
+}
+
+/*
+ * Check k5login files in a system location, rather than in home
+ * directories.
+ */
+
+static krb5_error_code KRB5_LIB_CALL
+kuserok_sys_k5login_plug_f(void *plug_ctx, krb5_context context,
+ const char *rule, unsigned int flags,
+ const char *k5login_dir, const char *luser,
+ krb5_const_principal principal, krb5_boolean *result)
+{
+ char filename[MAXPATHLEN];
+ size_t len;
+ const char *profile_dir = NULL;
+ krb5_error_code ret;
+
+ *result = FALSE;
+
+ if (strcmp(rule, "SYSTEM-K5LOGIN") != 0 &&
+ strncmp(rule, "SYSTEM-K5LOGIN:", strlen("SYSTEM-K5LOGIN:")) != 0)
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ profile_dir = strchr(rule, ':');
+ if (profile_dir == NULL)
+ profile_dir = k5login_dir ? k5login_dir : SYSTEM_K5LOGIN_DIR;
+ else
+ profile_dir++;
+
+ len = snprintf(filename, sizeof(filename), "%s/%s", profile_dir, luser);
+ if (len < sizeof(filename)) {
+ ret = check_one_file(context, filename, NULL, TRUE, principal, result);
+
+ if (ret == 0 &&
+ ((flags & KUSEROK_K5LOGIN_IS_AUTHORITATIVE) || *result == TRUE))
+ return 0;
+ }
+
+ *result = FALSE;
+ return KRB5_PLUGIN_NO_HANDLE;
+}
+
+/*
+ * Check ~luser/.k5login and/or ~/luser/.k5login.d
+ */
+
+static krb5_error_code KRB5_LIB_CALL
+kuserok_user_k5login_plug_f(void *plug_ctx, krb5_context context,
+ const char *rule, unsigned int flags,
+ const char *k5login_dir, const char *luser,
+ krb5_const_principal principal,
+ krb5_boolean *result)
+{
+#ifdef _WIN32
+ return KRB5_PLUGIN_NO_HANDLE;
+#else
+ char *path;
+ char *path_exp;
+ const char *profile_dir = NULL;
+ krb5_error_code ret;
+ krb5_boolean found_file = FALSE;
+ struct passwd pw, *pwd = NULL;
+ char pwbuf[2048];
+
+ if (strcmp(rule, "USER-K5LOGIN") != 0)
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ profile_dir = k5login_dir;
+ if (profile_dir == NULL) {
+ /* Don't deadlock with gssd or anything of the sort */
+ if (!_krb5_homedir_access(context))
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ if (getpwnam_r(luser, &pw, pwbuf, sizeof(pwbuf), &pwd) != 0) {
+ krb5_set_error_message(context, errno, "User unknown (getpwnam_r())");
+ return KRB5_PLUGIN_NO_HANDLE;
+ }
+ if (pwd == NULL) {
+ krb5_set_error_message(context, errno, "User unknown (getpwnam())");
+ return KRB5_PLUGIN_NO_HANDLE;
+ }
+ profile_dir = pwd->pw_dir;
+ }
+
+#define KLOGIN "/.k5login"
+
+ if (asprintf(&path, "%s/.k5login.d", profile_dir) == -1)
+ return krb5_enomem(context);
+
+ ret = _krb5_expand_path_tokensv(context, path, 1, &path_exp,
+ "luser", luser, NULL);
+ free(path);
+ if (ret)
+ return ret;
+ path = path_exp;
+
+ /* check user's ~/.k5login */
+ path[strlen(path) - strlen(".d")] = '\0';
+ ret = check_one_file(context, path, luser, FALSE, principal, result);
+
+ /*
+ * A match in ~/.k5login is sufficient. A non-match, falls through to the
+ * .k5login.d code below.
+ */
+ if (ret == 0 && *result == TRUE) {
+ free(path);
+ return 0;
+ }
+ if (ret != ENOENT)
+ found_file = TRUE;
+
+ /*
+ * A match in ~/.k5login.d/somefile is sufficient. A non-match, falls
+ * through to the code below that handles negative results.
+ *
+ * XXX: put back the .d; clever|hackish? you decide
+ */
+ path[strlen(path)] = '.';
+ ret = check_directory(context, path, luser, FALSE, principal, result);
+ free(path);
+ if (ret == 0 && *result == TRUE)
+ return 0;
+ if (ret != ENOENT && ret != ENOTDIR)
+ found_file = TRUE;
+
+ /*
+ * When either ~/.k5login or ~/.k5login.d/ exists, but neither matches
+ * and we're authoritative, we're done. Otherwise, give other plugins
+ * a chance.
+ */
+ *result = FALSE;
+ if (found_file && (flags & KUSEROK_K5LOGIN_IS_AUTHORITATIVE))
+ return 0;
+ return KRB5_PLUGIN_NO_HANDLE;
+#endif
+}
+
+static krb5_error_code KRB5_LIB_CALL
+kuserok_deny_plug_f(void *plug_ctx, krb5_context context, const char *rule,
+ unsigned int flags, const char *k5login_dir,
+ const char *luser, krb5_const_principal principal,
+ krb5_boolean *result)
+{
+ if (strcmp(rule, "DENY") != 0)
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ *result = FALSE;
+ return 0;
+}
+
+static krb5_error_code KRB5_LIB_CALL
+kuser_ok_null_plugin_init(krb5_context context, void **ctx)
+{
+ *ctx = NULL;
+ return 0;
+}
+
+static void KRB5_LIB_CALL
+kuser_ok_null_plugin_fini(void *ctx)
+{
+ return;
+}
+
+static krb5plugin_kuserok_ftable kuserok_simple_plug = {
+ KRB5_PLUGIN_KUSEROK_VERSION_0,
+ kuser_ok_null_plugin_init,
+ kuser_ok_null_plugin_fini,
+ kuserok_simple_plug_f,
+};
+
+static krb5plugin_kuserok_ftable kuserok_sys_k5login_plug = {
+ KRB5_PLUGIN_KUSEROK_VERSION_0,
+ kuser_ok_null_plugin_init,
+ kuser_ok_null_plugin_fini,
+ kuserok_sys_k5login_plug_f,
+};
+
+static krb5plugin_kuserok_ftable kuserok_user_k5login_plug = {
+ KRB5_PLUGIN_KUSEROK_VERSION_0,
+ kuser_ok_null_plugin_init,
+ kuser_ok_null_plugin_fini,
+ kuserok_user_k5login_plug_f,
+};
+
+static krb5plugin_kuserok_ftable kuserok_deny_plug = {
+ KRB5_PLUGIN_KUSEROK_VERSION_0,
+ kuser_ok_null_plugin_init,
+ kuser_ok_null_plugin_fini,
+ kuserok_deny_plug_f,
+};
+
diff --git a/third_party/heimdal/lib/krb5/kuserok_plugin.h b/third_party/heimdal/lib/krb5/kuserok_plugin.h
new file mode 100644
index 0000000..7c3f3b4
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/kuserok_plugin.h
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2011, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef HEIMDAL_KRB5_KUSEROK_PLUGIN_H
+#define HEIMDAL_KRB5_KUSEROK_PLUGIN_H 1
+
+#include <heimbase-svc.h>
+
+#define KRB5_PLUGIN_KUSEROK "krb5_plugin_kuserok"
+#define KRB5_PLUGIN_KUSEROK_VERSION_0 0
+
+/** @struct krb5plugin_kuserok_ftable_desc
+ *
+ * @brief Description of the krb5_kuserok(3) plugin facility.
+ *
+ * The krb5_kuserok(3) function is pluggable. The plugin is named
+ * KRB5_PLUGIN_KUSEROK ("krb5_plugin_kuserok"), with a single minor
+ * version, KRB5_PLUGIN_KUSEROK_VERSION_0 (0).
+ *
+ * The plugin for krb5_kuserok(3) consists of a data symbol referencing
+ * a structure of type krb5plugin_kuserok_ftable, with four fields:
+ *
+ * @param init Plugin initialization function (see krb5-plugin(7))
+ *
+ * @param minor_version The plugin minor version number (0)
+ *
+ * @param fini Plugin finalization function
+ *
+ * @param kuserok Plugin kuserok function
+ *
+ * The kuserok field is the plugin entry point that performs the
+ * traditional kuserok operation however the plugin desires. It is
+ * invoked in no particular order relative to other kuserok plugins, but
+ * it has a 'rule' argument that indicates which plugin is intended to
+ * act on the rule. The plugin kuserok function must return
+ * KRB5_PLUGIN_NO_HANDLE if the rule is not applicable to it.
+ *
+ * The plugin kuserok function has the following arguments, in this
+ * order:
+ *
+ * -# plug_ctx, the context value output by the plugin's init function
+ * -# context, a krb5_context
+ * -# rule, the kuserok rule being evaluated (from krb5.conf(5))
+ * -# flags
+ * -# k5login_dir, configured location of k5login per-user files if any
+ * -# luser, name of the local user account to which principal is attempting to access.
+ * -# principal, the krb5_principal trying to access the luser account
+ * -# result, a krb5_boolean pointer where the plugin will output its result
+ *
+ * @ingroup krb5_support
+ */
+typedef struct krb5plugin_kuserok_ftable_desc {
+ HEIM_PLUGIN_FTABLE_COMMON_ELEMENTS(krb5_context);
+ krb5_error_code (KRB5_LIB_CALL *kuserok)(void *, krb5_context, const char *,
+ unsigned int, const char *, const char *,
+ krb5_const_principal,
+ krb5_boolean *);
+} krb5plugin_kuserok_ftable;
+
+#define KUSEROK_ANAME_TO_LNAME_OK 1
+#define KUSEROK_K5LOGIN_IS_AUTHORITATIVE 2
+
+#endif /* HEIMDAL_KRB5_KUSEROK_PLUGIN_H */
diff --git a/third_party/heimdal/lib/krb5/kx509.c b/third_party/heimdal/lib/krb5/kx509.c
new file mode 100644
index 0000000..7525739
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/kx509.c
@@ -0,0 +1,1323 @@
+/*
+ * Copyright (c) 2019 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include <kx509_asn1.h>
+#include <kx509_err.h>
+#include "../hx509/hx_locl.h" /* XXX find a better way */
+#include "hx509-private.h"
+
+/*
+ * This file implements a client for the kx509 protocol -- a Kerberized online
+ * CA that can issue a Certificate to a client that authenticates using
+ * Kerberos.
+ *
+ * The kx509 protocol is the inverse of PKINIT. Whereas PKINIT allows users
+ * with PKIX credentials to acquire Kerberos credentials, the kx509 protocol
+ * allows users with Kerberos credentials to acquire PKIX credentials.
+ *
+ * I.e., kx509 is a bridge, just like PKINIT.
+ *
+ * The kx509 protocol is very simple, and very limited.
+ *
+ * A request consists of a DER-encoded Kx509Request message prefixed with four
+ * bytes identifying the protocol (see `version_2_0' below).
+ *
+ * A Kx509Request message contains an AP-REQ, a public key, and an HMAC of the
+ * public key made with the session key of the AP-REQ's ticket.
+ *
+ * The service principal can be either kca_service/hostname.fqdn or
+ * krbtgt/REALM (a Heimdal innovation).
+ *
+ * If a request is missing a public key, then the request is a probe intended
+ * to discover whether the service is enabled, thus helping the client avoid
+ * a possibly-slow private key generation operation.
+ *
+ * The response is a DER-encoded Kx509Response also prefixed with
+ * `version_2_0', and contains: an optional error code and error text, an
+ * optional certificate (for the success case), and an optional HMAC of those
+ * fields that is present when the service was able to verify the AP-REQ.
+ *
+ * Limitations:
+ *
+ * - no proof of possession for the public key
+ * - only RSA keys are supported
+ * - no way to express options (e.g., what KUs, EKUs, or SANs are desired)
+ * - no sub-session key usage
+ * - no reflection protection other than the HMAC's forgery protection and the
+ * fact that the client could tell that a reflected attack isn't success
+ *
+ * Future directions:
+ *
+ * - Since the public key field of the request is an OCTET STRING, we could
+ * send a CSR, or even an expired certificate (possibly self-signed,
+ * possibly one issued earlier) that can serve as a template.
+ *
+ * This solves the first three limitations, as it allows the client to
+ * demonstrate proof of possession, allows arbitrary public key types, and
+ * allows the client to express desires about the to-be-issued certificate.
+ *
+ * - Use the AP-REQ's Authenticator's sub-session key for the HMAC, and derive
+ * per-direction sub-sub-keys.
+ *
+ * - We might design a new protocol that better fits the RFC4120 KDC message
+ * framework.
+ */
+
+static const unsigned char version_2_0[4] = {0 , 0, 2, 0};
+
+struct krb5_kx509_req_ctx_data {
+ krb5_auth_context ac;
+ krb5_data given_csr;
+ hx509_request csr;
+ Kx509CSRPlus csr_plus;
+ char *realm; /* Realm to which to send request */
+ krb5_keyblock *hmac_key; /* For HMAC validation */
+ hx509_private_key *keys;
+ hx509_private_key priv_key;
+ unsigned int expect_chain;
+};
+
+/**
+ * Create a kx509 request context.
+ *
+ * @param context The Kerberos library context
+ * @param out Where to place the kx509 request context
+ *
+ * @return A krb5 error code.
+ */
+krb5_error_code
+krb5_kx509_ctx_init(krb5_context context, krb5_kx509_req_ctx *out)
+{
+ krb5_kx509_req_ctx ctx;
+ krb5_error_code ret;
+ hx509_name name = NULL;
+
+ ALLOC(ctx, 1);
+ if (ctx == NULL)
+ return krb5_enomem(context);
+ ctx->given_csr.data = NULL;
+ ctx->priv_key = NULL;
+ ctx->hmac_key = NULL;
+ ctx->realm = NULL;
+ ctx->keys = NULL;
+ ctx->csr = NULL;
+ ret = hx509_request_init(context->hx509ctx, &ctx->csr);
+ if (ret == 0)
+ ret = hx509_parse_name(context->hx509ctx, "", &name);
+ if (ret == 0)
+ ret = hx509_request_set_name(context->hx509ctx, ctx->csr, name);
+ if (ret == 0)
+ ret = krb5_auth_con_init(context, &ctx->ac);
+ if (name)
+ hx509_name_free(&name);
+ if (ret == 0)
+ *out = ctx;
+ else
+ krb5_kx509_ctx_free(context, &ctx);
+ return ret;
+}
+
+/**
+ * Free a kx509 request context.
+ *
+ * @param context The Kerberos library context
+ * @param ctxp Pointer to krb5 request context to free
+ *
+ * @return A krb5 error code.
+ */
+void
+krb5_kx509_ctx_free(krb5_context context, krb5_kx509_req_ctx *ctxp)
+{
+ krb5_kx509_req_ctx ctx = *ctxp;
+
+ *ctxp = NULL;
+ if (ctx == NULL)
+ return;
+ krb5_free_keyblock(context, ctx->hmac_key);
+ krb5_auth_con_free(context, ctx->ac);
+ free_Kx509CSRPlus(&ctx->csr_plus);
+ free(ctx->realm);
+ hx509_request_free(&ctx->csr);
+ krb5_data_free(&ctx->given_csr);
+ hx509_private_key_free(&ctx->priv_key);
+ _hx509_certs_keys_free(context->hx509ctx, ctx->keys);
+ free(ctx);
+}
+
+/**
+ * Set a realm to send kx509 request to, if different from the client's.
+ *
+ * @param context The Kerberos library context
+ * @param ctx The kx509 request context
+ * @param realm Realm name
+ *
+ * @return A krb5 error code.
+ */
+krb5_error_code
+krb5_kx509_ctx_set_realm(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ const char *realm)
+{
+ return ((kx509_ctx->realm = strdup(realm)) == NULL) ?
+ krb5_enomem(context) : 0;
+}
+
+/**
+ * Sets a CSR for a kx509 request.
+ *
+ * Normally kx509 will generate a CSR (and even a private key for it)
+ * automatically. If a CSR is given then kx509 will use it instead of
+ * generating one.
+ *
+ * @param context The Kerberos library context
+ * @param ctx The kx509 request context
+ * @param csr_der A DER-encoded PKCS#10 CSR
+ *
+ * @return A krb5 error code.
+ */
+krb5_error_code
+krb5_kx509_ctx_set_csr_der(krb5_context context,
+ krb5_kx509_req_ctx ctx,
+ krb5_data *csr_der)
+{
+ krb5_data_free(&ctx->given_csr);
+ return krb5_data_copy(&ctx->given_csr, csr_der->data, csr_der->length);
+}
+
+/**
+ * Adds an EKU as an additional desired Certificate Extension or in the CSR if
+ * the caller does not set a CSR.
+ *
+ * @param context The Kerberos library context
+ * @param ctx The kx509 request context
+ * @param oids A string representation of an OID
+ *
+ * @return A krb5 error code.
+ */
+krb5_error_code
+krb5_kx509_ctx_add_eku(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ const char *oids)
+{
+ krb5_error_code ret;
+ heim_oid oid;
+
+ ret = der_parse_heim_oid(oids, NULL, &oid);
+ if (ret == 0)
+ hx509_request_add_eku(context->hx509ctx, kx509_ctx->csr, &oid);
+ der_free_oid(&oid);
+ return ret;
+}
+
+/**
+ * Adds a dNSName SAN (domainname, hostname) as an additional desired
+ * Certificate Extension or in the CSR if the caller does not set a CSR.
+ *
+ * @param context The Kerberos library context
+ * @param ctx The kx509 request context
+ * @param dname A string containing a DNS domainname
+ *
+ * @return A krb5 error code.
+ */
+krb5_error_code
+krb5_kx509_ctx_add_san_dns_name(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ const char *dname)
+{
+ return hx509_request_add_dns_name(context->hx509ctx, kx509_ctx->csr,
+ dname);
+}
+
+/**
+ * Adds an xmppAddr SAN (jabber address) as an additional desired Certificate
+ * Extension or in the CSR if the caller does not set a CSR.
+ *
+ * @param context The Kerberos library context
+ * @param ctx The kx509 request context
+ * @param jid A string containing a Jabber address
+ *
+ * @return A krb5 error code.
+ */
+krb5_error_code
+krb5_kx509_ctx_add_san_xmpp(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ const char *jid)
+{
+ return hx509_request_add_xmpp_name(context->hx509ctx, kx509_ctx->csr, jid);
+}
+
+/**
+ * Adds an rfc822Name SAN (e-mail address) as an additional desired Certificate
+ * Extension or in the CSR if the caller does not set a CSR.
+ *
+ * @param context The Kerberos library context
+ * @param ctx The kx509 request context
+ * @param email A string containing an e-mail address
+ *
+ * @return A krb5 error code.
+ */
+krb5_error_code
+krb5_kx509_ctx_add_san_rfc822Name(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ const char *email)
+{
+ return hx509_request_add_email(context->hx509ctx, kx509_ctx->csr, email);
+}
+
+/**
+ * Adds an pkinit SAN (Kerberos principal name) as an additional desired
+ * Certificate Extension or in the CSR if the caller does not set a CSR.
+ *
+ * @param context The Kerberos library context
+ * @param ctx The kx509 request context
+ * @param pname A string containing a representation of a Kerberos principal
+ * name
+ *
+ * @return A krb5 error code.
+ */
+krb5_error_code
+krb5_kx509_ctx_add_san_pkinit(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ const char *pname)
+{
+ return hx509_request_add_pkinit(context->hx509ctx, kx509_ctx->csr, pname);
+}
+
+/**
+ * Adds a Microsoft-style UPN (user principal name) as an additional desired
+ * Certificate Extension or in the CSR if the caller does not set a CSR.
+ *
+ * @param context The Kerberos library context
+ * @param ctx The kx509 request context
+ * @param upn A string containing a representation of a UPN
+ *
+ * @return A krb5 error code.
+ */
+krb5_error_code
+krb5_kx509_ctx_add_san_ms_upn(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ const char *upn)
+{
+ return hx509_request_add_ms_upn_name(context->hx509ctx, kx509_ctx->csr,
+ upn);
+}
+
+/**
+ * Adds an registeredID SAN (OID) as an additional desired Certificate
+ * Extension or in the CSR if the caller does not set a CSR.
+ *
+ * @param context The Kerberos library context
+ * @param ctx The kx509 request context
+ * @param oids A string representation of an OID
+ *
+ * @return A krb5 error code.
+ */
+krb5_error_code
+krb5_kx509_ctx_add_san_registeredID(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ const char *oids)
+{
+ krb5_error_code ret;
+ heim_oid oid;
+
+ ret = der_parse_heim_oid(oids, NULL, &oid);
+ if (ret == 0)
+ hx509_request_add_registered(context->hx509ctx, kx509_ctx->csr, &oid);
+ der_free_oid(&oid);
+ return ret;
+}
+
+static krb5_error_code
+load_priv_key(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ const char *fn)
+{
+ hx509_private_key *keys = NULL;
+ hx509_certs certs = NULL;
+ krb5_error_code ret;
+
+ ret = hx509_certs_init(context->hx509ctx, fn, 0, NULL, &certs);
+ if (ret == ENOENT)
+ return 0;
+ if (ret == 0)
+ ret = _hx509_certs_keys_get(context->hx509ctx, certs, &keys);
+ if (ret == 0 && keys[0] == NULL)
+ ret = ENOENT;
+ if (ret == 0)
+ kx509_ctx->priv_key = _hx509_private_key_ref(keys[0]);
+ if (ret) {
+ char *emsg = hx509_get_error_string(context->hx509ctx, ret);
+
+ krb5_set_error_message(context, ret, "Could not load private key "
+ "from %s for kx509: %s", fn, emsg);
+ hx509_free_error_string(emsg);
+ }
+ hx509_certs_free(&certs);
+ return ret;
+}
+
+/**
+ * Set a private key.
+ *
+ * @param context The Kerberos library context
+ * @param ctx The kx509 request context
+ * @param store The name of a PKIX credential store
+ *
+ * @return A krb5 error code.
+ */
+krb5_error_code
+krb5_kx509_ctx_set_key(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ const char *store)
+{
+ SubjectPublicKeyInfo key;
+ krb5_error_code ret;
+
+ memset(&key, 0, sizeof(key));
+ hx509_private_key_free(&kx509_ctx->priv_key);
+ _hx509_certs_keys_free(context->hx509ctx, kx509_ctx->keys);
+ kx509_ctx->keys = NULL;
+ ret = load_priv_key(context, kx509_ctx, store);
+ if (ret == 0)
+ ret = hx509_private_key2SPKI(context->hx509ctx, kx509_ctx->priv_key,
+ &key);
+ if (ret == 0)
+ ret = hx509_request_set_SubjectPublicKeyInfo(context->hx509ctx,
+ kx509_ctx->csr, &key);
+ free_SubjectPublicKeyInfo(&key);
+ return ret;
+}
+
+static krb5_error_code
+gen_priv_key(krb5_context context,
+ const char *gen_type,
+ unsigned long gen_bits,
+ hx509_private_key *key)
+{
+ struct hx509_generate_private_context *key_gen_ctx = NULL;
+ krb5_error_code ret;
+
+ _krb5_debug(context, 1, "kx509: gen priv key");
+ if (strcmp(gen_type, "rsa") != 0) {
+ krb5_set_error_message(context, ENOTSUP, "Key type %s is not "
+ "supported for kx509; only \"rsa\" is "
+ "supported for kx509 at this time",
+ gen_type);
+ return ENOTSUP;
+ }
+
+ ret = _hx509_generate_private_key_init(context->hx509ctx,
+ ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+ &key_gen_ctx);
+ if (ret == 0)
+ ret = _hx509_generate_private_key_bits(context->hx509ctx, key_gen_ctx, gen_bits);
+
+ if (ret == 0)
+ ret = _hx509_generate_private_key(context->hx509ctx, key_gen_ctx, key);
+ _hx509_generate_private_key_free(&key_gen_ctx);
+ if (ret) {
+ char *emsg = hx509_get_error_string(context->hx509ctx, ret);
+
+ krb5_set_error_message(context, ret,
+ "Could not generate a private key: %s", emsg);
+ hx509_free_error_string(emsg);
+ }
+ return ret;
+}
+
+/**
+ * Generate a private key.
+ *
+ * @param context The Kerberos library context
+ * @param ctx The kx509 request context
+ * @param gen_type The type of key (default: rsa)
+ * @param gen_bits The size of the key (for non-ECC, really, for RSA)
+ *
+ * @return A krb5 error code.
+ */
+krb5_error_code
+krb5_kx509_ctx_gen_key(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ const char *gen_type,
+ int gen_bits)
+{
+ SubjectPublicKeyInfo key;
+ krb5_error_code ret;
+
+ memset(&key, 0, sizeof(key));
+
+ if (gen_type == NULL) {
+ gen_type = krb5_config_get_string_default(context, NULL, "rsa",
+ "libdefaults",
+ "kx509_gen_key_type", NULL);
+ }
+ if (gen_bits == 0) {
+ /*
+ * The key size is really only for non-ECC, of which we'll only support
+ * RSA. For ECC key sizes will either be implied by the `key_type' or
+ * will have to be a magic value that allows us to pick from some small
+ * set of curves (e.g., 255 == Curve25519).
+ */
+ gen_bits = krb5_config_get_int_default(context, NULL, 2048,
+ "libdefaults",
+ "kx509_gen_rsa_key_size", NULL);
+ }
+ hx509_private_key_free(&kx509_ctx->priv_key);
+ _hx509_certs_keys_free(context->hx509ctx, kx509_ctx->keys);
+ kx509_ctx->keys = NULL;
+
+ ret = gen_priv_key(context, gen_type, gen_bits, &kx509_ctx->priv_key);
+ if (ret == 0)
+ ret = hx509_private_key2SPKI(context->hx509ctx, kx509_ctx->priv_key,
+ &key);
+ if (ret == 0)
+ ret = hx509_request_set_SubjectPublicKeyInfo(context->hx509ctx,
+ kx509_ctx->csr, &key);
+ free_SubjectPublicKeyInfo(&key);
+ return ret;
+}
+
+/* Set a cc config entry indicating that the kx509 service is not available */
+static void
+store_kx509_disabled(krb5_context context, const char *realm, krb5_ccache cc)
+{
+ krb5_data data;
+
+ if (!cc)
+ return;
+
+ data.data = (void *)(uintptr_t)realm;
+ data.length = strlen(realm);
+ krb5_cc_set_config(context, cc, NULL, "kx509_service_realm", &data);
+ data.data = "disabled";
+ data.length = strlen(data.data);
+ krb5_cc_set_config(context, cc, NULL, "kx509_service_status", &data);
+}
+
+static int KRB5_CALLCONV
+certs_export_func(hx509_context context, void *d, hx509_cert c)
+{
+ heim_octet_string os;
+ Certificates *cs = d;
+ Certificate c2;
+ int ret;
+
+ ret = hx509_cert_binary(context, c, &os);
+ if (ret)
+ return ret;
+ ret = decode_Certificate(os.data, os.length, &c2, NULL);
+ der_free_octet_string(&os);
+ if (ret)
+ return ret;
+ ret = add_Certificates(cs, &c2);
+ free_Certificate(&c2);
+ return ret;
+}
+
+static krb5_error_code
+certs_export(hx509_context context, hx509_certs certs, heim_octet_string *out)
+{
+ Certificates cs;
+ size_t len;
+ int ret;
+
+ cs.len = 0;
+ cs.val = 0;
+ ret = hx509_certs_iter_f(context, certs, certs_export_func, &cs);
+ if (ret == 0)
+ ASN1_MALLOC_ENCODE(Certificates, out->data, out->length, &cs, &len, ret);
+ free_Certificates(&cs);
+ return ret;
+}
+
+/* Store the private key and certificate where requested */
+static krb5_error_code
+store(krb5_context context,
+ const char *hx509_store,
+ const char *realm,
+ krb5_ccache cc,
+ hx509_private_key key,
+ hx509_cert cert,
+ hx509_certs chain)
+{
+ heim_octet_string hdata;
+ krb5_error_code ret = 0;
+ krb5_data data;
+
+ krb5_clear_error_message(context);
+
+ if (cc) {
+ /* Record the realm we used */
+ data.data = (void *)(uintptr_t)realm;
+ data.length = strlen(realm);
+ krb5_cc_set_config(context, cc, NULL, "kx509_service_realm", &data);
+
+ /* Serialize and store the certificate in the ccache */
+ ret = hx509_cert_binary(context->hx509ctx, cert, &hdata);
+ if (ret == 0)
+ ret = krb5_cc_set_config(context, cc, NULL, "kx509cert", &hdata);
+ der_free_octet_string(&hdata);
+
+ if (ret == 0 && key) {
+ /*
+ * Serialized and store the key in the ccache. Use PKCS#8 so that we
+ * store the algorithm OID too, which is needed in order to be able to
+ * read the private key back.
+ */
+ if (ret == 0)
+ ret = _hx509_private_key_export(context->hx509ctx, key,
+ HX509_KEY_FORMAT_PKCS8, &hdata);
+ if (ret == 0)
+ ret = krb5_cc_set_config(context, cc, NULL, "kx509key", &hdata);
+ der_free_octet_string(&hdata);
+ if (ret)
+ krb5_set_error_message(context, ret, "Could not store kx509 "
+ "private key and certificate in ccache %s",
+ krb5_cc_get_name(context, cc));
+ }
+
+ if (ret == 0 && chain) {
+ ret = certs_export(context->hx509ctx, chain, &hdata);
+ if (ret == 0)
+ ret = krb5_cc_set_config(context, cc, NULL, "kx509cert-chain",
+ &hdata);
+ der_free_octet_string(&hdata);
+ }
+ }
+
+ /* Store the private key and cert in an hx509 store */
+ if (hx509_store != NULL) {
+ hx509_certs certs;
+
+ if (key)
+ _hx509_cert_assign_key(cert, key); /* store both in the same store */
+
+ ret = hx509_certs_init(context->hx509ctx, hx509_store,
+ HX509_CERTS_CREATE, NULL, &certs);
+ if (ret == 0)
+ ret = hx509_certs_add(context->hx509ctx, certs, cert);
+ if (ret == 0 && chain != NULL)
+ ret = hx509_certs_merge(context->hx509ctx, certs, chain);
+ if (ret == 0)
+ ret = hx509_certs_store(context->hx509ctx, certs, 0, NULL);
+ hx509_certs_free(&certs);
+ if (ret)
+ krb5_prepend_error_message(context, ret, "Could not store kx509 "
+ "private key and certificate in key "
+ "store %s", hx509_store);
+ }
+
+ /* Store the name of the hx509 store in the ccache too */
+ if (cc && hx509_store) {
+ data.data = (void *)(uintptr_t)hx509_store;
+ data.length = strlen(hx509_store);
+ (void) krb5_cc_set_config(context, cc, NULL, "kx509store", &data);
+ }
+ return ret;
+}
+
+/* Make a Kx509CSRPlus or a raw SPKI */
+static krb5_error_code
+mk_kx509_req_body(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ krb5_data *out)
+{
+ krb5_error_code ret;
+ size_t len;
+
+ if (krb5_config_get_bool_default(context, NULL, FALSE,
+ "realms", kx509_ctx->realm,
+ "kx509_req_use_raw_spki", NULL)) {
+ SubjectPublicKeyInfo spki;
+
+ /* Interop with old kx509 servers, send a raw SPKI, not a CSR */
+ out->data = NULL;
+ out->length = 0;
+ memset(&spki, 0, sizeof(spki));
+ ret = hx509_private_key2SPKI(context->hx509ctx,
+ kx509_ctx->priv_key, &spki);
+ if (ret == 0) {
+ out->length = spki.subjectPublicKey.length >> 3;
+ out->data = spki.subjectPublicKey.data;
+ }
+ kx509_ctx->expect_chain = 0;
+ return ret;
+ }
+
+ /*
+ * New kx509 servers use a CSR for proof of possession, and send back a
+ * chain of certificates, with the issued certificate first.
+ */
+ kx509_ctx->expect_chain = 1;
+
+ if (kx509_ctx->given_csr.length) {
+ krb5_data exts_der;
+
+ exts_der.data = NULL;
+ exts_der.length = 0;
+
+ /* Use the given CSR */
+ ret = der_copy_octet_string(&kx509_ctx->given_csr,
+ &kx509_ctx->csr_plus.csr);
+
+ /*
+ * Extract the desired Certificate Extensions from our internal
+ * as-yet-unsigned CSR, then decode them into place in the
+ * Kx509CSRPlus.
+ */
+ if (ret == 0)
+ ret = hx509_request_get_exts(context->hx509ctx,
+ kx509_ctx->csr,
+ &exts_der);
+ if (ret == 0 && exts_der.data && exts_der.length &&
+ (kx509_ctx->csr_plus.exts =
+ calloc(1, sizeof (kx509_ctx->csr_plus.exts[0]))) == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0 && exts_der.data && exts_der.length)
+ ret = decode_Extensions(exts_der.data, exts_der.length,
+ kx509_ctx->csr_plus.exts, NULL);
+ krb5_data_free(&exts_der);
+ } else {
+ /*
+ * Sign and use our internal CSR, which will carry all our desired
+ * Certificate Extensions as an extReq CSR Attribute.
+ */
+ ret = hx509_request_to_pkcs10(context->hx509ctx,
+ kx509_ctx->csr,
+ kx509_ctx->priv_key,
+ &kx509_ctx->csr_plus.csr);
+ }
+ if (ret == 0)
+ ASN1_MALLOC_ENCODE(Kx509CSRPlus, out->data, out->length,
+ &kx509_ctx->csr_plus, &len, ret);
+ return ret;
+}
+
+static krb5_error_code
+get_start_realm(krb5_context context,
+ krb5_ccache cc,
+ krb5_const_principal princ,
+ char **out)
+{
+ krb5_error_code ret;
+ krb5_data d;
+
+ ret = krb5_cc_get_config(context, cc, NULL, "start_realm", &d);
+ if (ret == 0) {
+ *out = strndup(d.data, d.length);
+ krb5_data_free(&d);
+ } else if (princ) {
+ *out = strdup(krb5_principal_get_realm(context, princ));
+ } else {
+ krb5_principal ccprinc = NULL;
+
+ ret = krb5_cc_get_principal(context, cc, &ccprinc);
+ if (ret)
+ return ret;
+ *out = strdup(krb5_principal_get_realm(context, ccprinc));
+ krb5_free_principal(context, ccprinc);
+ }
+ return (*out) ? 0 : krb5_enomem(context);
+}
+
+/*
+ * Make a request, which is a DER-encoded Kx509Request with version_2_0
+ * prefixed to it.
+ *
+ * If no private key is given, then a probe request will be made.
+ */
+static krb5_error_code
+mk_kx509_req(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ krb5_ccache incc,
+ hx509_private_key private_key,
+ krb5_data *req)
+{
+ unsigned char digest[SHA_DIGEST_LENGTH];
+ SubjectPublicKeyInfo spki;
+ struct Kx509Request kx509_req;
+ krb5_data pre_req;
+ krb5_error_code ret = 0;
+ krb5_creds this_cred;
+ krb5_creds *cred = NULL;
+ HMAC_CTX ctx;
+ const char *hostname;
+ char *start_realm = NULL;
+ size_t len = 0;
+
+ krb5_data_zero(&pre_req);
+ memset(&spki, 0, sizeof(spki));
+ memset(&this_cred, 0, sizeof(this_cred));
+ memset(&kx509_req, 0, sizeof(kx509_req));
+ kx509_req.pk_hash.data = digest;
+ kx509_req.pk_hash.length = SHA_DIGEST_LENGTH;
+
+ if (private_key || kx509_ctx->given_csr.data) {
+ /* Encode the CSR or public key for use in the request */
+ ret = mk_kx509_req_body(context, kx509_ctx, &kx509_req.pk_key);
+ } else {
+ /* Probe */
+ kx509_req.pk_key.data = NULL;
+ kx509_req.pk_key.length = 0;
+ }
+
+ if (ret == 0)
+ ret = krb5_cc_get_principal(context, incc, &this_cred.client);
+ if (ret == 0)
+ ret = get_start_realm(context, incc, this_cred.client, &start_realm);
+ if (ret == 0 && kx509_ctx->realm == NULL)
+ ret = krb5_kx509_ctx_set_realm(context, kx509_ctx, start_realm);
+ if (ret == 0) {
+ /*
+ * The kx509 protocol as deployed uses kca_service/kdc_hostname, but
+ * this is inconvenient in libkrb5: we want to be able to use the
+ * send_to_kdc machinery, and since the Heimdal KDC is also the kx509
+ * service, we want not to have to specify kx509 hosts separately from
+ * KDCs.
+ *
+ * We'd much rather use krbtgt/CLIENT_REALM@REQUESTED_REALM. What
+ * we do is assume all KDCs for `realm' support the kx509 service and
+ * then sendto the KDCs for that realm while using a hostbased service
+ * if still desired.
+ *
+ * Note that upstairs we try to get the start_realm cc config, so if
+ * realm wasn't given to krb5_kx509_ext(), then it should be set to
+ * that already unless there's no start_realm cc config, in which case
+ * we'll use the ccache's default client principal's realm.
+ */
+ hostname = krb5_config_get_string(context, NULL, "realms",
+ kx509_ctx->realm, "kx509_hostname",
+ NULL);
+ if (hostname == NULL)
+ hostname = krb5_config_get_string(context, NULL, "libdefaults",
+ "kx509_hostname", NULL);
+ if (hostname) {
+ ret = krb5_sname_to_principal(context, hostname, "kca_service",
+ KRB5_NT_SRV_HST, &this_cred.server);
+ if (ret == 0)
+ ret = krb5_principal_set_realm(context, this_cred.server,
+ kx509_ctx->realm);
+ } else {
+ ret = krb5_make_principal(context, &this_cred.server,
+ start_realm,
+ KRB5_TGS_NAME,
+ kx509_ctx->realm,
+ NULL);
+ }
+ }
+
+ /* Make the AP-REQ and extract the HMAC key */
+ if (ret == 0)
+ ret = krb5_get_credentials(context, 0, incc, &this_cred, &cred);
+ if (ret == 0)
+ ret = krb5_mk_req_extended(context, &kx509_ctx->ac, AP_OPTS_USE_SUBKEY,
+ NULL, cred, &kx509_req.authenticator);
+ krb5_free_keyblock(context, kx509_ctx->hmac_key);
+ kx509_ctx->hmac_key = NULL;
+ if (ret == 0)
+ ret = krb5_auth_con_getkey(context, kx509_ctx->ac,
+ &kx509_ctx->hmac_key);
+
+ if (ret)
+ goto out;
+
+ /* Add the the key and HMAC to the message */
+ HMAC_CTX_init(&ctx);
+ if (HMAC_Init_ex(&ctx, kx509_ctx->hmac_key->keyvalue.data,
+ kx509_ctx->hmac_key->keyvalue.length,
+ EVP_sha1(), NULL) == 0) {
+ HMAC_CTX_cleanup(&ctx);
+ ret = krb5_enomem(context);
+ } else {
+ HMAC_Update(&ctx, version_2_0, sizeof(version_2_0));
+ if (private_key || kx509_ctx->given_csr.data) {
+ HMAC_Update(&ctx, kx509_req.pk_key.data, kx509_req.pk_key.length);
+ } else {
+ /* Probe */
+ HMAC_Update(&ctx, kx509_req.authenticator.data, kx509_req.authenticator.length);
+ }
+ HMAC_Final(&ctx, kx509_req.pk_hash.data, 0);
+ HMAC_CTX_cleanup(&ctx);
+ }
+
+ /* Encode the message, prefix `version_2_0', output the result */
+ if (ret == 0)
+ ASN1_MALLOC_ENCODE(Kx509Request, pre_req.data, pre_req.length, &kx509_req, &len, ret);
+ if (ret == 0)
+ ret = krb5_data_alloc(req, pre_req.length + sizeof(version_2_0));
+ if (ret == 0) {
+ memcpy(req->data, version_2_0, sizeof(version_2_0));
+ memcpy(((unsigned char *)req->data) + sizeof(version_2_0),
+ pre_req.data, pre_req.length);
+ }
+
+out:
+ free(start_realm);
+ free(pre_req.data);
+ krb5_free_creds(context, cred);
+ kx509_req.pk_hash.data = NULL;
+ kx509_req.pk_hash.length = 0;
+ free_Kx509Request(&kx509_req);
+ free_SubjectPublicKeyInfo(&spki);
+ krb5_free_cred_contents(context, &this_cred);
+ if (ret == 0 && req->length != len + sizeof(version_2_0)) {
+ krb5_data_free(req);
+ krb5_set_error_message(context, ret = ERANGE,
+ "Could not make a kx509 request");
+ }
+ return ret;
+}
+
+static krb5_error_code
+rd_chain(krb5_context context,
+ heim_octet_string *d,
+ hx509_cert *cert,
+ hx509_certs *chain,
+ heim_error_t *herr)
+{
+ krb5_error_code ret;
+ Certificates certs;
+ size_t i, len;
+
+ *cert = NULL;
+ *chain = NULL;
+
+ if ((ret = decode_Certificates(d->data, d->length, &certs, &len)))
+ return ret;
+ if (certs.len == 0) {
+ *herr = heim_error_create(EINVAL, "Server sent empty Certificate list");
+ return EINVAL;
+ }
+ *cert = hx509_cert_init(context->hx509ctx, &certs.val[0], herr);
+ if (*cert == NULL) {
+ free_Certificates(&certs);
+ return errno;
+ }
+ if (certs.len == 1)
+ _krb5_debug(context, 1, "kx509 server sent certificate but no chain");
+ else
+ _krb5_debug(context, 1, "kx509 server sent %llu certificates",
+ (unsigned long long)certs.len);
+
+ ret = hx509_certs_init(context->hx509ctx, "MEMORY:anonymous",
+ HX509_CERTS_CREATE, NULL, chain);
+ if (ret) {
+ hx509_cert_free(*cert);
+ *cert = NULL;
+ free_Certificates(&certs);
+ return ret;
+ }
+
+ for (i = 1; ret == 0 && i < certs.len; i++) {
+ hx509_cert c = hx509_cert_init(context->hx509ctx, &certs.val[i], herr);
+
+ if (c == NULL)
+ ret = errno;
+ else
+ ret = hx509_certs_add(context->hx509ctx, *chain, c);
+ hx509_cert_free(c);
+ }
+ free_Certificates(&certs);
+ if (ret) {
+ hx509_certs_free(chain);
+ hx509_cert_free(*cert);
+ *cert = NULL;
+ }
+ return ret;
+}
+
+/* Parse and validate a kx509 reply */
+static krb5_error_code
+rd_kx509_resp(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ krb5_data *rep,
+ hx509_cert *cert,
+ hx509_certs *chain)
+{
+ unsigned char digest[SHA_DIGEST_LENGTH];
+ Kx509Response r;
+ krb5_error_code code = 0;
+ krb5_error_code ret = 0;
+ heim_string_t hestr;
+ heim_error_t herr = NULL;
+ const char *estr;
+ HMAC_CTX ctx;
+ size_t hdr_len = sizeof(version_2_0);
+ size_t len;
+
+ *cert = NULL;
+ *chain = NULL;
+
+ /* Strip `version_2_0' prefix */
+ if (rep->length < hdr_len || memcmp(rep->data, version_2_0, hdr_len) != 0) {
+ krb5_set_error_message(context, ENOTSUP,
+ "KDC does not support kx509 protocol");
+ return ENOTSUP; /* XXX */
+ }
+
+ /* Decode */
+ ret = decode_Kx509Response(((unsigned char *)rep->data) + 4,
+ rep->length - 4, &r, &len);
+ if (ret == 0 && len + hdr_len != rep->length)
+ ret = EINVAL; /* XXX */
+ if (ret) {
+ krb5_set_error_message(context, ret, "kx509 response is not valid");
+ return ret;
+ }
+
+ HMAC_CTX_init(&ctx);
+ if (HMAC_Init_ex(&ctx, kx509_ctx->hmac_key->keyvalue.data,
+ kx509_ctx->hmac_key->keyvalue.length, EVP_sha1(), NULL) == 0) {
+ free_Kx509Response(&r);
+ HMAC_CTX_cleanup(&ctx);
+ return krb5_enomem(context);
+ }
+
+ HMAC_Update(&ctx, version_2_0, sizeof(version_2_0));
+
+ {
+ int32_t t = r.error_code;
+ unsigned char encint[sizeof(t) + 1];
+ size_t k;
+
+ /*
+ * RFC6717 says this about how the error-code is included in the HMAC:
+ *
+ * o DER representation of the error-code exclusive of the tag and
+ * length, if it is present.
+ *
+ * So we use der_put_integer(), which encodes from the right.
+ *
+ * RFC6717 does not constrain the error-code's range. We assume it to
+ * be a 32-bit, signed integer, for which we'll need no more than 5
+ * bytes.
+ */
+ ret = der_put_integer(&encint[sizeof(encint) - 1],
+ sizeof(encint), &t, &k);
+ if (ret == 0)
+ HMAC_Update(&ctx, &encint[sizeof(encint)] - k, k);
+
+ /* Normalize error code */
+ if (r.error_code == 0) {
+ code = 0; /* No error */
+ } else if (r.error_code < 0) {
+ code = KRB5KRB_ERR_GENERIC; /* ??? */
+ } else if (r.error_code <= KX509_ERR_SRV_OVERLOADED) {
+ /*
+ * RFC6717 (kx509) error code. These are actually not used on the
+ * wire in any existing implementations that we are aware of. Just
+ * in case, however, we'll map these.
+ */
+ code = KX509_ERR_CLNT_FATAL + r.error_code;
+ } else if (r.error_code < kx509_krb5_error_base) {
+ /* Unknown error codes */
+ code = KRB5KRB_ERR_GENERIC;
+ } else {
+ /*
+ * Heimdal-specific enhancement to RFC6171: Kerberos wire protocol
+ * error codes.
+ */
+ code = KRB5KDC_ERR_NONE + r.error_code - kx509_krb5_error_base;
+ if (code >= KRB5_ERR_RCSID)
+ code = KRB5KRB_ERR_GENERIC;
+ if (code == KRB5KDC_ERR_NONE)
+ code = 0;
+ }
+ }
+ if (r.certificate)
+ HMAC_Update(&ctx, r.certificate->data, r.certificate->length);
+ if (r.e_text)
+ HMAC_Update(&ctx, *r.e_text, strlen(*r.e_text));
+ HMAC_Final(&ctx, &digest, 0);
+ HMAC_CTX_cleanup(&ctx);
+
+ if (r.hash == NULL) {
+ /*
+ * No HMAC -> unauthenticated [error] response.
+ *
+ * Do not output any certificate.
+ */
+ free_Kx509Response(&r);
+ return code;
+ }
+
+ /*
+ * WARNING: We do not validate that `r.certificate' is a DER-encoded
+ * Certificate, not here, and we don't use a different HMAC key
+ * for the response than for the request.
+ *
+ * If ever we start sending a Certificate as the Kx509Request
+ * pk-key field, then we'll have a reflection attack. As the
+ * Certificate we'd send in that case will be expired, the
+ * reflection attack would be just a DoS.
+ */
+ if (r.hash->length != sizeof(digest) ||
+ ct_memcmp(r.hash->data, digest, sizeof(digest)) != 0) {
+ krb5_set_error_message(context, KRB5KDC_ERR_PREAUTH_FAILED,
+ "kx509 response MAC mismatch");
+ free_Kx509Response(&r);
+ return KRB5KRB_AP_ERR_BAD_INTEGRITY;
+ }
+
+ if (r.certificate == NULL) {
+ /* Authenticated response, either an error or probe success */
+ free_Kx509Response(&r);
+ if (code != KRB5KDC_ERR_POLICY && kx509_ctx->priv_key == NULL)
+ return 0; /* Probe success */
+ return code ? code : KRB5KDC_ERR_POLICY; /* Not a probe -> must fail */
+ }
+
+ /* Import the certificate payload */
+ if (kx509_ctx->expect_chain) {
+ ret = rd_chain(context, r.certificate, cert, chain, &herr);
+ } else {
+ *cert = hx509_cert_init_data(context->hx509ctx, r.certificate->data,
+ r.certificate->length, &herr);
+ if (!*cert)
+ ret = errno;
+ }
+ free_Kx509Response(&r);
+ if (*cert) {
+ heim_release(herr);
+ return 0;
+ }
+
+ hestr = herr ? heim_error_copy_string(herr) : NULL;
+ estr = hestr ? heim_string_get_utf8(hestr) : "(no error message)";
+ krb5_set_error_message(context, ret, "Could not parse certificate "
+ "produced by kx509 KDC: %s (%ld)",
+ estr,
+ herr ? (long)heim_error_get_code(herr) : 0L);
+
+ heim_release(hestr);
+ heim_release(herr);
+ return HEIM_PKINIT_CERTIFICATE_INVALID; /* XXX */
+}
+
+/*
+ * Make a request, send it, get the response, parse it, and store the
+ * private key and certificate.
+ */
+static krb5_error_code
+kx509_core(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ krb5_ccache incc,
+ const char *hx509_store,
+ krb5_ccache outcc)
+{
+ krb5_error_code ret;
+ hx509_certs chain = NULL;
+ hx509_cert cert = NULL;
+ krb5_data req, resp;
+
+ krb5_data_zero(&req);
+ krb5_data_zero(&resp);
+
+ /* Make the kx509 request */
+ ret = mk_kx509_req(context, kx509_ctx, incc, kx509_ctx->priv_key, &req);
+
+ /* Send the kx509 request and get the response */
+ if (ret == 0)
+ ret = krb5_sendto_context(context, NULL, &req,
+ kx509_ctx->realm, &resp);
+ if (ret == 0)
+ ret = rd_kx509_resp(context, kx509_ctx, &resp, &cert, &chain);
+
+ /* Store the key and cert! */
+ if (ret == 0 && cert && (kx509_ctx->priv_key || kx509_ctx->given_csr.data))
+ ret = store(context, hx509_store, kx509_ctx->realm, outcc,
+ kx509_ctx->priv_key, cert, chain);
+ else if (ret == KRB5KDC_ERR_POLICY)
+ /* Probe failed -> record that the realm does not support kx509 */
+ store_kx509_disabled(context, kx509_ctx->realm, outcc);
+
+ hx509_certs_free(&chain);
+ hx509_cert_free(cert);
+ krb5_data_free(&resp);
+ krb5_data_free(&req);
+ return ret;
+}
+
+/**
+ * Use the kx509 v2 protocol to get a certificate for the client principal.
+ *
+ * Given a private key this function will get a certificate. If no private key
+ * is given, one will be generated.
+ *
+ * The private key and certificate will be stored in the given PKIX credential
+ * store (e.g, "PEM-FILE:/path/to/file.pem") and/or given output ccache. When
+ * stored in a ccache, the DER-encoded Certificate will be stored as the data
+ * payload of a "cc config" named "kx509cert", while the key will be stored as
+ * a DER-encoded PKCS#8 PrivateKeyInfo in a cc config named "kx509key".
+ *
+ * @param context The Kerberos library context
+ * @param kx509_ctx A kx509 request context
+ * @param incc A credential cache (if NULL use default ccache)
+ * @param hx509_store An PKIX credential store into which to store the private
+ * key and certificate (e.g, "PEM-FILE:/path/to/file.pem")
+ * @param outcc A ccache into which to store the private key and certificate
+ * (mandatory)
+ *
+ * @return A krb5 error code.
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kx509_ext(krb5_context context,
+ krb5_kx509_req_ctx kx509_ctx,
+ krb5_ccache incc,
+ const char *hx509_store,
+ krb5_ccache outcc)
+{
+ krb5_ccache def_cc = NULL;
+ krb5_error_code ret;
+
+ if (incc == NULL) {
+ if ((ret = krb5_cc_default(context, &def_cc)))
+ return ret;
+ incc = def_cc;
+ }
+
+ if (kx509_ctx->realm == NULL &&
+ (ret = get_start_realm(context, incc, NULL, &kx509_ctx->realm))) {
+ if (def_cc)
+ krb5_cc_close(context, def_cc);
+ return ret;
+ }
+
+ if (kx509_ctx->priv_key || kx509_ctx->given_csr.data) {
+ /* If given a private key, use it */
+ ret = kx509_core(context, kx509_ctx, incc, hx509_store, outcc);
+ if (def_cc)
+ krb5_cc_close(context, def_cc);
+ return ret;
+ }
+
+ /*
+ * No private key given, so we generate one.
+ *
+ * However, before taking the hit for generating a keypair we probe to see
+ * if we're likely to succeeed.
+ */
+
+ /* Probe == call kx509_core() w/o a private key */
+ ret = kx509_core(context, kx509_ctx, incc, NULL, outcc);
+ if (ret == 0 && kx509_ctx->given_csr.data == NULL)
+ ret = krb5_kx509_ctx_gen_key(context, kx509_ctx, NULL, 0);
+ if (ret == 0)
+ ret = kx509_core(context, kx509_ctx, incc, hx509_store, outcc);
+
+ if (def_cc)
+ krb5_cc_close(context, def_cc);
+ return ret;
+}
+
+/**
+ * Generates a public key and uses the kx509 v2 protocol to get a certificate
+ * for that key and the client principal's subject name.
+ *
+ * The private key and certificate will be stored in the given ccache, and also
+ * in a corresponding PKIX credential store if one is configured via
+ * [libdefaults] kx509_store.
+ *
+ * XXX NOTE: Dicey feature here... Review carefully!
+ *
+ * @param context The Kerberos library context
+ * @param cc A credential cache
+ * @param realm A realm from which to get the certificate (uses the client
+ * principal's realm if NULL)
+ *
+ * @return A krb5 error code.
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kx509(krb5_context context, krb5_ccache cc, const char *realm)
+{
+ krb5_kx509_req_ctx kx509_ctx;
+ krb5_error_code ret;
+ const char *defcc;
+ char *ccache_full_name = NULL;
+ char *store_exp = NULL;
+
+ ret = krb5_kx509_ctx_init(context, &kx509_ctx);
+ if (ret)
+ return ret;
+ if (realm)
+ ret = krb5_kx509_ctx_set_realm(context, kx509_ctx, realm);
+
+ /*
+ * The idea is that IF we are asked to do kx509 w/ creds from a default
+ * ccache THEN we should store the kx509 certificate (if we get one) and
+ * private key in the default hx509 store for kx509.
+ *
+ * Ideally we could have HTTP user-agents and/or TLS libraries look for
+ * client certificates and private keys in that default hx509 store.
+ *
+ * Of course, those user-agents / libraries should be configured to use
+ * those credentials with specific hostnames/domainnames, not the entire
+ * Internet, as the latter leaks the user's identity to the world.
+ *
+ * So we check if the full name for `cc' is the same as that of the default
+ * ccache name, and if so we get the [libdefaults] kx509_store string and
+ * expand it, then use it.
+ */
+ if (ret == 0 &&
+ (defcc = krb5_cc_configured_default_name(context)) &&
+ krb5_cc_get_full_name(context, cc, &ccache_full_name) == 0 &&
+ strcmp(defcc, ccache_full_name) == 0) {
+
+ /* Find an hx509 store */
+ const char *store = krb5_config_get_string(context, NULL,
+ "libdefaults",
+ "kx509_store", NULL);
+ if (store)
+ ret = _krb5_expand_path_tokens(context, store, 1, &store_exp);
+
+ /*
+ * If there's a private key in the store already, we'll use it, else
+ * we'll let krb5_kx509_ext() generate one, so we ignore this return
+ * value:
+ */
+ (void) krb5_kx509_ctx_set_key(context, kx509_ctx, store);
+ }
+
+ /*
+ * If we did settle on a default hx509 store, we'll use it for reading the
+ * private key from (if it exists) as well as for storing the certificate
+ * (and private key) into, which may save us some key generation cycles.
+ */
+ if (ret == 0)
+ ret = krb5_kx509_ext(context, kx509_ctx, cc, store_exp, cc);
+ krb5_kx509_ctx_free(context, &kx509_ctx);
+ free(ccache_full_name);
+ free(store_exp);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/kx509_err.et b/third_party/heimdal/lib/krb5/kx509_err.et
new file mode 100644
index 0000000..0be3907
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/kx509_err.et
@@ -0,0 +1,39 @@
+#
+# Error messages for the krb5 library
+#
+# This might look like a com_err file, but is not
+#
+
+# RFC6171 says:
+#
+# +------------+-----------------------------+------------------------+
+# | error-code | Condition | Example |
+# +------------+-----------------------------+------------------------+
+# | 1 | Permanent problem with | Incompatible version |
+# | | client request | |
+# | 2 | Solvable problem with | Expired Kerberos |
+# | | client request | credentials |
+# | 3 | Temporary problem with | Packet loss |
+# | | client request | |
+# | 4 | Permanent problem with the | Internal |
+# | | server | misconfiguration |
+# | 5 | Temporary problem with the | Server overloaded |
+# | | server | |
+# +------------+-----------------------------+------------------------+
+#
+# Error 3 makes no sense on the wire, and in the library it only makes sense as
+# a timeout, so we'll name it KX509_ERR_TIMEOUT.
+
+# Error table names must be no more than four characters...
+error_table kx59
+
+prefix KX509_ERR
+
+error_code NONE, "Kx509 success"
+error_code CLNT_FATAL, "Kx509 request error, possibly unsupported version"
+error_code CLNT_SOLVABLE, "Kx509 request error such as expired credentials"
+error_code TIMEOUT, "Kx509 request timed out"
+error_code SRV_FATAL, "Permanent server problem"
+error_code SRV_OVERLOADED, "Kx509 server is overloaded"
+
+end
diff --git a/third_party/heimdal/lib/krb5/libkrb5-exports.def.in b/third_party/heimdal/lib/krb5/libkrb5-exports.def.in
new file mode 100644
index 0000000..191a0c4
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/libkrb5-exports.def.in
@@ -0,0 +1,895 @@
+EXPORTS
+ krb524_convert_creds_kdc
+ krb524_convert_creds_kdc_ccache
+ krb5_abort
+ krb5_abortx
+ krb5_acl_match_file
+ krb5_acl_match_string
+ krb5_add_et_list
+ krb5_add_extra_addresses
+ krb5_add_ignore_addresses
+ krb5_addlog_dest
+ krb5_addlog_func
+ krb5_addr2sockaddr
+ krb5_address_compare
+ krb5_address_order
+ krb5_address_prefixlen_boundary
+ krb5_address_search
+ krb5_allow_weak_crypto
+ krb5_aname_to_localname
+ krb5_anyaddr
+ krb5_appdefault_boolean
+ krb5_appdefault_string
+ krb5_appdefault_time
+ krb5_append_addresses
+ krb5_auth_con_addflags
+ krb5_auth_con_add_AuthorizationData
+ krb5_auth_con_add_AuthorizationDataIfRelevant
+ krb5_auth_con_free
+ krb5_auth_con_genaddrs
+ krb5_auth_con_generatelocalsubkey
+ krb5_auth_con_getaddrs
+ krb5_auth_con_getauthenticator
+ krb5_auth_con_getcksumtype
+ krb5_auth_con_getflags
+ krb5_auth_con_getkey
+ krb5_auth_con_getkeytype
+ krb5_auth_con_getlocalseqnumber
+ krb5_auth_con_getlocalsubkey
+ krb5_auth_con_getrcache
+ krb5_auth_con_getremoteseqnumber
+ krb5_auth_con_getremotesubkey
+ krb5_auth_con_init
+ krb5_auth_con_removeflags
+ krb5_auth_con_setaddrs
+ krb5_auth_con_setaddrs_from_fd
+ krb5_auth_con_setcksumtype
+ krb5_auth_con_setflags
+ krb5_auth_con_setkey
+ krb5_auth_con_setkeytype
+ krb5_auth_con_setlocalseqnumber
+ krb5_auth_con_setlocalsubkey
+ krb5_auth_con_setrcache
+ krb5_auth_con_setremoteseqnumber
+ krb5_auth_con_setremotesubkey
+ krb5_auth_con_setuserkey
+ krb5_auth_getremoteseqnumber
+ krb5_build_ap_req
+ krb5_build_principal
+ krb5_build_principal_ext
+ krb5_build_principal_va
+ krb5_build_principal_va_ext
+ krb5_c_block_size
+ krb5_c_checksum_length
+ krb5_c_decrypt
+ krb5_c_encrypt
+ krb5_c_encrypt_length
+ krb5_c_enctype_compare
+ krb5_c_get_checksum
+ krb5_c_is_coll_proof_cksum
+ krb5_c_is_keyed_cksum
+ krb5_c_keylengths
+ krb5_c_make_checksum
+ krb5_c_make_random_key
+ krb5_c_prf
+ krb5_c_prf_length
+ krb5_c_random_make_octets ;!
+ krb5_c_set_checksum
+ krb5_c_valid_cksumtype
+ krb5_c_valid_enctype
+ krb5_c_verify_checksum
+ krb5_cc_cache_end_seq_get
+ krb5_cc_cache_get_first
+ krb5_cc_cache_match
+ krb5_cc_cache_next
+ krb5_cc_clear_mcred
+ krb5_cc_close
+ krb5_cc_configured_default_name
+ krb5_cc_copy_cache
+ krb5_cc_copy_creds ;!
+ krb5_cc_copy_match_f
+ krb5_cc_default
+ krb5_cc_default_sub
+ krb5_cc_default_for
+ krb5_cc_default_name
+ krb5_cc_destroy
+ krb5_cc_end_seq_get
+ krb5_cc_gen_new
+ krb5_cc_get_config
+ krb5_cc_get_friendly_name
+ krb5_cc_get_full_name
+ krb5_cc_get_kdc_offset
+ krb5_cc_get_lifetime
+ krb5_cc_get_name
+ krb5_cc_get_ops
+ krb5_cc_get_prefix_ops
+ krb5_cc_get_principal
+ krb5_cc_get_type
+ krb5_cc_get_version
+ krb5_cc_initialize
+ krb5_cc_last_change_time
+ krb5_cc_move
+ krb5_cc_new_unique
+ krb5_cc_next_cred
+;! krb5_cc_next_cred_match
+ krb5_cc_register
+ krb5_cc_remove_cred
+ krb5_cc_resolve
+ krb5_cc_resolve_sub
+ krb5_cc_resolve_for
+ krb5_cc_retrieve_cred
+ krb5_cc_set_config
+ krb5_cc_set_default_name
+ krb5_cc_set_flags
+ krb5_cc_set_kdc_offset
+ krb5_cc_start_seq_get
+ krb5_cc_store_cred
+ krb5_cc_support_switch
+ krb5_cc_switch
+ krb5_cc_set_friendly_name
+ krb5_change_password
+ krb5_check_transited
+ krb5_check_transited_realms
+ krb5_checksum_disable
+ krb5_checksum_free
+ krb5_checksum_is_collision_proof
+ krb5_checksum_is_keyed
+ krb5_checksumsize
+ krb5_cksumtype_to_enctype
+ krb5_cksumtype_valid
+ krb5_clear_error_string
+ krb5_clear_error_message
+ krb5_closelog
+ krb5_compare_creds
+ krb5_config_file_free
+ krb5_config_free_strings
+; _krb5_config_get
+ krb5_config_get_bool
+ krb5_config_get_bool_default
+ krb5_config_get_int
+ krb5_config_get_int_default
+ krb5_config_get_list
+; _krb5_config_get_next
+ krb5_config_get_string
+ krb5_config_get_string_default
+ krb5_config_get_strings
+ krb5_config_get_time
+ krb5_config_get_time_default
+ krb5_config_parse_file
+ krb5_config_parse_file_multi
+ krb5_config_parse_string_multi
+; _krb5_config_vget
+ krb5_config_vget_bool
+ krb5_config_vget_bool_default
+ krb5_config_vget_int
+ krb5_config_vget_int_default
+ krb5_config_vget_list
+; _krb5_config_vget_next
+ krb5_config_vget_string
+ krb5_config_vget_string_default
+ krb5_config_vget_strings
+ krb5_config_vget_time
+ krb5_config_vget_time_default
+ krb5_copy_address
+ krb5_copy_addresses
+ krb5_copy_checksum
+ krb5_copy_context
+ krb5_copy_creds
+ krb5_copy_creds_contents
+ krb5_copy_data
+ krb5_copy_host_realm
+ krb5_copy_keyblock
+ krb5_copy_keyblock_contents
+ krb5_copy_principal
+ krb5_copy_ticket
+ krb5_create_checksum
+ krb5_create_checksum_iov
+ krb5_crypto_destroy
+ krb5_crypto_fx_cf2
+ krb5_crypto_get_checksum_type
+ krb5_crypto_getblocksize
+ krb5_crypto_getconfoundersize
+ krb5_crypto_getenctype
+ krb5_crypto_getpadsize
+ krb5_crypto_init
+ krb5_crypto_overhead
+ krb5_crypto_prf
+ krb5_crypto_prfplus
+ krb5_crypto_prf_length
+ krb5_crypto_length
+ krb5_crypto_length_iov
+ krb5_decrypt_iov_ivec
+ krb5_encrypt_iov_ivec
+ krb5_data_alloc
+ krb5_data_cmp
+ krb5_data_copy
+ krb5_data_ct_cmp
+ krb5_data_free
+ krb5_data_realloc
+ krb5_data_zero
+ krb5_debug
+ krb5_decode_Authenticator
+ krb5_decode_ETYPE_INFO2
+ krb5_decode_ETYPE_INFO
+ krb5_decode_EncAPRepPart
+ krb5_decode_EncASRepPart
+ krb5_decode_EncKrbCredPart
+ krb5_decode_EncTGSRepPart
+ krb5_decode_EncTicketPart
+ krb5_decode_ap_req
+ krb5_decrypt
+ krb5_decrypt_EncryptedData
+ krb5_decrypt_ivec
+ krb5_decrypt_ticket
+ krb5_derive_key
+ krb5_digest_alloc
+ krb5_digest_free
+ krb5_digest_get_client_binding
+ krb5_digest_get_identifier
+ krb5_digest_get_opaque
+ krb5_digest_get_rsp
+ krb5_digest_get_server_nonce
+ krb5_digest_get_session_key
+ krb5_digest_get_tickets
+ krb5_digest_init_request
+ krb5_digest_probe
+ krb5_digest_rep_get_status
+ krb5_digest_request
+ krb5_digest_set_authentication_user
+ krb5_digest_set_authid
+ krb5_digest_set_client_nonce
+ krb5_digest_set_digest
+ krb5_digest_set_hostname
+ krb5_digest_set_identifier
+ krb5_digest_set_method
+ krb5_digest_set_nonceCount
+ krb5_digest_set_opaque
+ krb5_digest_set_qop
+ krb5_digest_set_realm
+ krb5_digest_set_responseData
+ krb5_digest_set_server_cb
+ krb5_digest_set_server_nonce
+ krb5_digest_set_type
+ krb5_digest_set_uri
+ krb5_digest_set_username
+ krb5_domain_x500_decode
+ krb5_domain_x500_encode
+ krb5_eai_to_heim_errno
+ krb5_encode_Authenticator
+ krb5_encode_ETYPE_INFO2
+ krb5_encode_ETYPE_INFO
+ krb5_encode_EncAPRepPart
+ krb5_encode_EncASRepPart
+ krb5_encode_EncKrbCredPart
+ krb5_encode_EncTGSRepPart
+ krb5_encode_EncTicketPart
+ krb5_encrypt
+ krb5_encrypt_EncryptedData
+ krb5_encrypt_ivec
+ krb5_enctype_enable
+ krb5_enctype_disable
+ krb5_enctype_keybits
+ krb5_enctype_keysize
+ krb5_enctype_to_keytype
+ krb5_enctype_to_string
+ krb5_enctype_valid
+ krb5_enctypes_compatible_keys
+ krb5_enomem
+ krb5_err
+ krb5_error_from_rd_error
+ krb5_errx
+ krb5_expand_hostname
+ krb5_expand_hostname_realms
+ krb5_find_padata
+ krb5_format_time
+ krb5_free_address
+ krb5_free_addresses
+ krb5_free_ap_rep_enc_part
+ krb5_free_authenticator
+ krb5_free_checksum
+ krb5_free_checksum_contents
+ krb5_free_config_files
+ krb5_free_context
+ krb5_free_cred_contents
+ krb5_free_creds
+ krb5_free_creds_contents
+ krb5_free_data
+ krb5_free_data_contents
+ krb5_free_default_realm
+ krb5_free_error
+ krb5_free_error_contents
+ krb5_free_error_string
+ krb5_free_error_message
+ krb5_free_host_realm
+ krb5_free_kdc_rep
+ krb5_free_keyblock
+ krb5_free_keyblock_contents
+ krb5_free_krbhst
+ krb5_free_principal
+ krb5_free_salt
+ krb5_free_ticket
+ krb5_free_unparsed_name
+ krb5_fwd_tgt_creds
+ krb5_generate_random_block
+ krb5_generate_random_keyblock
+ krb5_generate_seq_number
+ krb5_generate_subkey
+ krb5_generate_subkey_extended
+ krb5_get_all_client_addrs
+ krb5_get_all_server_addrs
+ krb5_get_cred_from_kdc
+ krb5_get_cred_from_kdc_opt
+ krb5_get_credentials
+ krb5_get_credentials_with_flags
+ krb5_get_creds
+ krb5_get_creds_opt_add_options
+ krb5_get_creds_opt_alloc
+ krb5_get_creds_opt_free
+ krb5_get_creds_opt_set_enctype
+ krb5_get_creds_opt_set_impersonate
+ krb5_get_creds_opt_set_options
+ krb5_get_creds_opt_set_ticket
+ krb5_get_default_config_files
+ krb5_get_default_in_tkt_etypes
+ krb5_get_default_principal
+ krb5_get_default_realm
+ krb5_get_default_realms
+ krb5_get_dns_canonicalize_hostname
+ krb5_get_err_text
+ krb5_get_error_message
+ krb5_get_error_string
+ krb5_get_extra_addresses
+ krb5_get_fcache_version
+ krb5_get_forwarded_creds
+ krb5_get_host_realm
+ krb5_get_ignore_addresses
+ krb5_get_in_cred
+; krb5_cccol_last_change_time
+ krb5_get_in_tkt
+ krb5_get_in_tkt_with_keytab
+ krb5_get_in_tkt_with_password
+ krb5_get_in_tkt_with_skey
+;! krb5_get_init_creds
+ krb5_get_init_creds_keyblock
+ krb5_get_init_creds_keytab
+ krb5_get_init_creds_opt_alloc
+ krb5_get_init_creds_opt_free
+ krb5_get_init_creds_opt_get_error
+ krb5_get_init_creds_opt_init
+ krb5_get_init_creds_opt_set_address_list
+ krb5_get_init_creds_opt_set_addressless
+ krb5_get_init_creds_opt_set_anonymous
+ krb5_get_init_creds_opt_set_change_password_prompt
+ krb5_get_init_creds_opt_set_canonicalize
+ krb5_get_init_creds_opt_set_default_flags
+ krb5_get_init_creds_opt_set_etype_list
+ krb5_get_init_creds_opt_set_forwardable
+ krb5_get_init_creds_opt_set_pa_password
+ krb5_get_init_creds_opt_set_pac_request
+ krb5_get_init_creds_opt_set_pkinit
+ krb5_get_init_creds_opt_set_preauth_list
+ krb5_get_init_creds_opt_set_process_last_req
+ krb5_get_init_creds_opt_set_proxiable
+ krb5_get_init_creds_opt_set_renew_life
+ krb5_get_init_creds_opt_set_salt
+ krb5_get_init_creds_opt_set_tkt_life
+ krb5_get_init_creds_opt_set_win2k
+ krb5_get_init_creds_password
+ krb5_get_instance
+ krb5_get_kdc_cred
+ krb5_get_kdc_sec_offset
+ krb5_get_krb524hst
+ krb5_get_krb_admin_hst
+ krb5_get_krb_changepw_hst
+ krb5_get_krb_readonly_admin_hst
+ krb5_get_krbhst
+ krb5_get_max_time_skew
+ krb5_get_pw_salt
+ krb5_get_renewed_creds
+ krb5_get_server_rcache
+ krb5_get_use_admin_kdc
+ krb5_get_validated_creds ;!
+ krb5_get_warn_dest
+ krb5_get_wrapped_length
+ krb5_getportbyname
+ krb5_h_addr2addr
+ krb5_h_addr2sockaddr
+ krb5_h_errno_to_heim_errno
+ krb5_have_error_string
+ krb5_have_debug
+ krb5_hmac
+ krb5_init_context
+ krb5_init_ets
+ krb5_initlog
+ krb5_is_config_principal
+ krb5_is_enctype_old
+ krb5_is_enctype_weak
+ krb5_is_thread_safe
+#ifdef HAVE_KCM
+ krb5_kcm_call
+ krb5_kcm_storage_request
+#endif
+ krb5_kerberos_enctypes
+ krb5_keyblock_get_enctype
+ krb5_keyblock_init
+ krb5_keyblock_key_proc
+ krb5_keyblock_zero
+ krb5_keytab_key_proc
+ krb5_keytype_to_enctypes
+ krb5_keytype_to_enctypes_default
+ krb5_keytype_to_string
+ krb5_krbhst_format_string
+ krb5_krbhst_free
+ krb5_krbhst_get_addrinfo
+ krb5_krbhst_init
+ krb5_krbhst_init_flags
+ krb5_krbhst_next
+ krb5_krbhst_next_as_string
+ krb5_krbhst_reset
+ krb5_kt_add_entry
+ krb5_kt_close
+ krb5_kt_compare
+ krb5_kt_copy_entry_contents
+ krb5_kt_default
+ krb5_kt_default_modify_name
+ krb5_kt_default_name
+ krb5_kt_destroy
+ krb5_kt_end_seq_get
+ krb5_kt_free_entry
+ krb5_kt_get_entry
+ krb5_kt_get_full_name
+ krb5_kt_get_name
+ krb5_kt_get_type
+ krb5_kt_have_content
+ krb5_kt_next_entry
+ krb5_kt_read_service_key
+ krb5_kt_register
+ krb5_kt_remove_entry
+ krb5_kt_resolve
+ krb5_kt_start_seq_get
+ krb5_kuserok
+ krb5_kx509
+ krb5_kx509_ctx_add_eku
+ krb5_kx509_ctx_add_san_dns_name
+ krb5_kx509_ctx_add_san_ms_upn
+ krb5_kx509_ctx_add_san_pkinit
+ krb5_kx509_ctx_add_san_registeredID
+ krb5_kx509_ctx_add_san_rfc822Name
+ krb5_kx509_ctx_add_san_xmpp
+ krb5_kx509_ctx_free
+ krb5_kx509_ctx_init
+ krb5_kx509_ctx_set_csr_der
+ krb5_kx509_ctx_set_key
+ krb5_kx509_ctx_set_realm
+ krb5_kx509_ext
+ krb5_log
+ krb5_log_msg
+ krb5_make_addrport
+ krb5_make_principal
+ krb5_max_sockaddr_size
+ krb5_mk_1cred
+ krb5_mk_error
+ krb5_mk_error_ext
+ krb5_mk_ncred
+ krb5_mk_priv
+ krb5_mk_rep
+ krb5_mk_req
+ krb5_mk_req_exact
+ krb5_mk_req_extended
+ krb5_mk_safe
+ krb5_net_read
+ krb5_net_write
+ krb5_net_write_block
+ krb5_ntlm_alloc
+ krb5_ntlm_free
+ krb5_ntlm_init_get_challenge
+ krb5_ntlm_init_get_flags
+ krb5_ntlm_init_get_opaque
+ krb5_ntlm_init_get_targetinfo
+ krb5_ntlm_init_get_targetname
+ krb5_ntlm_init_request
+ krb5_ntlm_rep_get_sessionkey
+ krb5_ntlm_rep_get_status
+ krb5_ntlm_req_set_flags
+ krb5_ntlm_req_set_lm
+ krb5_ntlm_req_set_ntlm
+ krb5_ntlm_req_set_opaque
+ krb5_ntlm_req_set_session
+ krb5_ntlm_req_set_targetname
+ krb5_ntlm_req_set_username
+ krb5_ntlm_request
+ krb5_openlog
+ krb5_pac_add_buffer
+ krb5_pac_free
+ krb5_pac_get_buffer
+ _krb5_pac_get_buffer_by_name
+ krb5_pac_get_kdc_checksum_info
+ krb5_pac_get_types
+ krb5_pac_init
+ krb5_pac_parse
+ krb5_pac_verify
+ krb5_padata_add
+ _krb5_parse_address_no_lookup
+ krb5_parse_address
+ krb5_parse_name
+ krb5_parse_name_flags
+ krb5_parse_nametype
+ krb5_passwd_result_to_string
+ krb5_password_key_proc
+ krb5_get_permitted_enctypes
+ krb5_plugin_register
+ krb5_prepend_config_files
+ krb5_prepend_config_files_default
+ krb5_prepend_error_message
+ krb5_princ_realm
+ krb5_princ_set_realm
+ krb5_principal_compare
+ krb5_principal_compare_any_realm
+ krb5_principal_get_comp_string
+ krb5_principal_get_num_comp
+ krb5_principal_get_realm
+ krb5_principal_get_type
+ krb5_principal_is_anonymous
+ krb5_principal_is_federated
+ krb5_principal_is_krbtgt
+ krb5_principal_is_root_krbtgt
+ krb5_principal_match
+ krb5_principal_set_comp_string
+ krb5_principal_set_realm
+ krb5_principal_set_type
+ krb5_print_address
+ krb5_program_setup
+ krb5_prompter_posix
+ krb5_random_to_key
+ krb5_rc_close
+ krb5_rc_default
+ krb5_rc_default_name
+ krb5_rc_default_type
+ krb5_rc_destroy
+ krb5_rc_expunge
+ krb5_rc_get_lifespan
+ krb5_rc_get_name
+ krb5_rc_get_type
+ krb5_rc_initialize
+ krb5_rc_recover
+ krb5_rc_resolve
+ krb5_rc_resolve_full
+ krb5_rc_resolve_type
+ krb5_rc_store
+ krb5_rd_cred2
+ krb5_rd_cred
+ krb5_rd_error
+ krb5_rd_priv
+ krb5_rd_rep
+ krb5_rd_req
+ krb5_rd_req_ctx
+ krb5_rd_req_in_ctx_alloc
+ krb5_rd_req_in_ctx_free
+ krb5_rd_req_in_set_keyblock
+ krb5_rd_req_in_set_keytab
+ krb5_rd_req_in_set_pac_check
+ krb5_rd_req_out_ctx_free
+ krb5_rd_req_out_get_ap_req_options
+ krb5_rd_req_out_get_keyblock
+ krb5_rd_req_out_get_ticket
+ krb5_rd_req_with_keyblock
+ krb5_rd_safe
+ krb5_read_message
+ krb5_read_priv_message
+ krb5_read_safe_message
+ krb5_realm_compare
+ krb5_recvauth
+ krb5_recvauth_match_version
+ krb5_ret_address
+ krb5_ret_addrs
+ krb5_ret_authdata
+ krb5_ret_creds
+ krb5_ret_creds_tag
+ krb5_ret_data
+ krb5_ret_int16
+ krb5_ret_int32
+ krb5_ret_int64
+ krb5_ret_int8
+ krb5_ret_keyblock
+ krb5_ret_principal
+ krb5_ret_string
+ krb5_ret_stringnl
+ krb5_ret_stringz
+ krb5_ret_times
+ krb5_ret_uint16
+ krb5_ret_uint32
+ krb5_ret_uint64
+ krb5_ret_uint8
+ krb5_salttype_to_string
+ krb5_sendauth
+ krb5_sendto
+ krb5_sendto_context
+ krb5_sendto_ctx_add_flags
+ krb5_sendto_ctx_alloc
+ krb5_sendto_ctx_free
+ krb5_sendto_ctx_get_flags
+ krb5_sendto_ctx_set_func
+ krb5_sendto_ctx_set_type
+ krb5_sendto_kdc
+ krb5_sendto_kdc_flags
+ krb5_sendto_set_hostname
+ krb5_sendto_set_sitename
+ krb5_set_config
+ krb5_set_config_files
+ krb5_set_debug_dest
+ krb5_set_default_in_tkt_etypes
+ krb5_set_default_realm
+ krb5_set_dns_canonicalize_hostname
+ krb5_set_error_message
+ krb5_set_error_string
+ krb5_set_extra_addresses
+ krb5_set_fcache_version
+ krb5_set_home_dir_access
+ krb5_set_ignore_addresses
+ krb5_set_kdc_sec_offset
+ krb5_set_log_dest
+ krb5_set_max_time_skew
+ krb5_set_password
+ krb5_set_password_using_ccache
+ krb5_set_real_time
+ krb5_set_send_to_kdc_func
+ krb5_set_use_admin_kdc
+ krb5_set_warn_dest
+ krb5_sname_to_principal
+ krb5_sock_to_principal
+ krb5_sockaddr2address
+ krb5_sockaddr2port
+ krb5_sockaddr_uninteresting
+ krb5_std_usage
+ krb5_storage_clear_flags
+ krb5_storage_emem
+ krb5_storage_free
+ krb5_storage_from_data
+ krb5_storage_from_fd
+ krb5_storage_from_mem
+ krb5_storage_from_readonly_mem
+ krb5_storage_from_socket
+ krb5_storage_fsync
+ krb5_storage_get_byteorder
+ krb5_storage_get_eof_code
+ krb5_storage_is_flags
+ krb5_storage_read
+ krb5_storage_stdio_from_fd
+ krb5_storage_seek
+ krb5_storage_set_byteorder
+ krb5_storage_set_eof_code
+ krb5_storage_set_flags
+ krb5_storage_set_max_alloc
+ krb5_storage_to_data
+ krb5_storage_truncate
+ krb5_storage_write
+ krb5_store_address
+ krb5_store_addrs
+ krb5_store_authdata
+ krb5_store_bytes
+ krb5_store_creds
+ krb5_store_creds_tag
+ krb5_store_data
+ krb5_store_datalen
+ krb5_store_int16
+ krb5_store_int32
+ krb5_store_int64
+ krb5_store_int8
+ krb5_store_keyblock
+ krb5_store_principal
+ krb5_store_string
+ krb5_store_stringnl
+ krb5_store_stringz
+ krb5_store_times
+ krb5_store_uint16
+ krb5_store_uint32
+ krb5_store_uint64
+ krb5_store_uint8
+ krb5_string_to_deltat
+ krb5_string_to_enctype
+ krb5_string_to_key
+ krb5_string_to_key_data
+ krb5_string_to_key_data_salt
+ krb5_string_to_key_data_salt_opaque
+ krb5_string_to_key_derived
+ krb5_string_to_key_salt
+ krb5_string_to_key_salt_opaque
+ krb5_string_to_keysalts2
+ krb5_string_to_keytype
+ krb5_string_to_salttype
+ krb5_ticket_get_authorization_data_type
+ krb5_ticket_get_client
+ krb5_ticket_get_endtime
+ krb5_ticket_get_times
+ krb5_ticket_get_server
+ krb5_timeofday
+ krb5_unparse_name
+ krb5_unparse_name_fixed
+ krb5_unparse_name_fixed_flags
+ krb5_unparse_name_fixed_short
+ krb5_unparse_name_flags
+ krb5_unparse_name_short
+ krb5_us_timeofday
+ krb5_vabort
+ krb5_vabortx
+ krb5_verify_ap_req2
+ krb5_verify_ap_req
+ krb5_verify_authenticator_checksum
+ krb5_verify_checksum
+ krb5_verify_checksum_iov
+ krb5_verify_init_creds
+ krb5_verify_init_creds_opt_init
+ krb5_verify_init_creds_opt_set_ap_req_nofail
+ krb5_verify_opt_alloc
+ krb5_verify_opt_free
+ krb5_verify_opt_init
+ krb5_verify_opt_set_ccache
+ krb5_verify_opt_set_flags
+ krb5_verify_opt_set_keytab
+ krb5_verify_opt_set_secure
+ krb5_verify_opt_set_service
+ krb5_verify_user
+ krb5_verify_user_lrealm
+ krb5_verify_user_opt
+ krb5_verr
+ krb5_verrx
+ krb5_vlog
+ krb5_vlog_msg
+ krb5_vprepend_error_message
+ krb5_vset_error_message
+ krb5_vset_error_string
+ krb5_vwarn
+ krb5_vwarnx
+ krb5_warn
+ krb5_warnx
+ krb5_write_message
+ krb5_write_priv_message
+ krb5_write_safe_message
+ krb5_xfree
+ krb5_cccol_last_change_time
+ krb5_cccol_cursor_new
+ krb5_cccol_cursor_next
+ krb5_cccol_cursor_free
+ krb5_cccol_get_default_ccname
+
+ ; com_err error tables
+ initialize_krb5_error_table_r
+ initialize_krb5_error_table
+ initialize_krb_error_table_r
+ initialize_krb_error_table
+ initialize_heim_error_table_r
+ initialize_heim_error_table
+ initialize_k524_error_table_r
+ initialize_k524_error_table
+ initialize_k5e1_error_table_r
+ initialize_k5e1_error_table
+
+ ; variables
+ krb5_mcc_ops DATA
+ krb5_acc_ops DATA
+ krb5_fcc_ops DATA
+#ifdef HAVE_SCC
+ krb5_scc_ops DATA
+#endif
+#ifdef HAVE_KCM
+ krb5_kcm_ops DATA
+#endif
+#ifdef HAVE_KEYUTILS
+ krb5_krcc_ops DATA
+#endif
+ krb5_wrfkt_ops DATA
+ krb5_mkt_ops DATA
+ krb5_akf_ops DATA
+ krb5_any_ops DATA
+ heimdal_version DATA
+ heimdal_long_version DATA
+ krb5_config_file DATA
+ krb5_defkeyname DATA
+ krb5_cc_type_api DATA
+ krb5_cc_type_file DATA
+ krb5_cc_type_memory DATA
+ krb5_cc_type_kcm DATA
+ krb5_cc_type_keyring DATA
+ krb5_cc_type_scc DATA
+
+ ; Shared with GSSAPI krb5
+ _krb5_crc_init_table
+ _krb5_crc_update
+ _krb5_get_krbtgt
+ _krb5_build_authenticator
+ _krb5_kt_client_default_name
+ _krb5_have_debug
+ _krb5_SP800_108_HMAC_KDF
+ _krb5_get_ad
+
+ ; Shared with GSSAPI preauth wrapper
+ _krb5_init_creds_set_gss_mechanism
+ _krb5_init_creds_get_gss_mechanism
+ _krb5_init_creds_set_gss_cred
+ _krb5_init_creds_get_gss_cred
+ _krb5_init_creds_init_gss
+
+ ; Private init_creds API
+ _krb5_init_creds_get_cred_starttime
+ _krb5_init_creds_get_cred_endtime
+ _krb5_init_creds_get_cred_client
+
+ ; Shared with libkadm5
+ _krb5_load_plugins
+ _krb5_unload_plugins
+
+ ; Shared with libkdc
+ _krb5_AES_SHA1_string_to_default_iterator
+ _krb5_AES_SHA2_string_to_default_iterator
+ _krb5_dh_group_ok
+ _krb5_get_host_realm_int
+ _krb5_get_int
+ _krb5_get_int64
+ _krb5_pac_sign
+ _krb5_pac_get_attributes_info
+ _krb5_pac_get_canon_principal
+ _krb5_kdc_pac_sign_ticket
+ _krb5_kdc_pac_ticket_parse
+ _kdc_tkt_insert_pac
+ _kdc_tkt_add_if_relevant_ad
+ _krb5_parse_moduli
+ _krb5_pk_kdf
+ _krb5_pk_load_id
+ _krb5_pk_mk_ContentInfo
+ _krb5_pk_octetstring2key
+ _krb5_plugin_run_f
+ _krb5_enctype_requires_random_salt
+ _krb5_principal2principalname
+ _krb5_principalname2krb5_principal
+ _krb5_kdcrep2krb5_principal
+ _krb5_ticket2krb5_principal
+ _krb5_put_int
+ _krb5_s4u2self_to_checksumdata
+ _krb5_HMAC_MD5_checksum
+ _krb5_crypto_set_flags
+ _krb5_expand_path_tokens ;!
+ _krb5_make_pa_enc_challenge
+ _krb5_validate_pa_enc_challenge
+
+ ; kinit helper
+ krb5_get_init_creds_opt_set_pkinit_user_certs
+ krb5_pk_enterprise_cert
+
+ krb5_auth_con_getsendsubkey
+ krb5_init_creds_free
+ krb5_init_creds_get
+ krb5_init_creds_get_as_reply_key
+ krb5_init_creds_get_creds
+ krb5_init_creds_get_error
+ krb5_init_creds_init
+ krb5_init_creds_set_fast_anon_pkinit
+ _krb5_init_creds_set_fast_anon_pkinit_optimistic
+ krb5_init_creds_set_fast_ccache
+ krb5_init_creds_set_keytab
+ krb5_init_creds_set_kdc_hostname
+ krb5_init_creds_set_password
+ krb5_init_creds_set_service
+ krb5_init_creds_set_sitename
+ krb5_init_creds_step
+ krb5_init_creds_store
+ krb5_init_creds_store_config
+ krb5_init_creds_warn_user
+ krb5_process_last_request
+
+ ; testing
+;! _krb5_aes_cts_encrypt
+ krb5_time_abs;
+ _krb5_n_fold
+ _krb5_expand_default_cc_name
+
+ ; FAST
+ _krb5_fast_cf2
+ _krb5_fast_armor_key
+ _krb5_fast_explicit_armor_key
+
+ ; Recent additions
+ krb5_cc_type_dcc;
+ krb5_dcc_ops;
+ _krb5_expand_path_tokensv;
+ _krb5_find_capath;
+ _krb5_free_capath;
diff --git a/third_party/heimdal/lib/krb5/locate_plugin.h b/third_party/heimdal/lib/krb5/locate_plugin.h
new file mode 100644
index 0000000..7fcb5ec
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/locate_plugin.h
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIMDAL_KRB5_LOCATE_PLUGIN_H
+#define HEIMDAL_KRB5_LOCATE_PLUGIN_H 1
+
+#include <heimbase-svc.h>
+
+#define KRB5_PLUGIN_LOCATE "service_locator"
+#define KRB5_PLUGIN_LOCATE_VERSION 1
+#define KRB5_PLUGIN_LOCATE_VERSION_0 0
+#define KRB5_PLUGIN_LOCATE_VERSION_1 1
+#define KRB5_PLUGIN_LOCATE_VERSION_2 2
+
+enum locate_service_type {
+ locate_service_kdc = 1,
+ locate_service_master_kdc,
+ locate_service_kadmin,
+ locate_service_krb524,
+ locate_service_kpasswd
+};
+
+typedef krb5_error_code
+(KRB5_CALLCONV *krb5plugin_service_locate_lookup)
+ (void *, unsigned long, enum locate_service_type,
+ const char *, int, int,
+ int (*)(void *,int,struct sockaddr *),
+ void *);
+
+#define KRB5_PLF_ALLOW_HOMEDIR 1
+
+typedef krb5_error_code
+(KRB5_CALLCONV *krb5plugin_service_locate_lookup_old)
+ (void *, enum locate_service_type,
+ const char *, int, int,
+ int (*)(void *,int,struct sockaddr *),
+ void *);
+
+
+typedef struct krb5plugin_service_locate_ftable {
+ HEIM_PLUGIN_FTABLE_COMMON_ELEMENTS(krb5_context);
+ krb5plugin_service_locate_lookup_old old_lookup;
+ krb5plugin_service_locate_lookup lookup; /* version 2 */
+} krb5plugin_service_locate_ftable;
+
+#endif /* HEIMDAL_KRB5_LOCATE_PLUGIN_H */
+
diff --git a/third_party/heimdal/lib/krb5/log.c b/third_party/heimdal/lib/krb5/log.c
new file mode 100644
index 0000000..306431a
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/log.c
@@ -0,0 +1,252 @@
+/*
+ * Copyright (c) 1997-2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include <assert.h>
+#include <vis.h>
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_initlog(krb5_context context,
+ const char *program,
+ krb5_log_facility **fac)
+{
+ return heim_initlog(context->hcontext, program, fac);
+}
+
+struct krb5_addlog_func_wrapper {
+ krb5_context context;
+ krb5_log_log_func_t log_func;
+ krb5_log_close_func_t close_func;
+ void *data;
+};
+
+static void HEIM_CALLCONV
+krb5_addlog_func_wrapper_log(heim_context hcontext,
+ const char *prefix,
+ const char *msg,
+ void *data)
+{
+ struct krb5_addlog_func_wrapper *w = data;
+
+ w->log_func(w->context,
+ prefix,
+ msg,
+ w->data);
+}
+
+static void HEIM_CALLCONV
+krb5_addlog_func_wrapper_close(void *data)
+{
+ struct krb5_addlog_func_wrapper *w = data;
+
+ w->close_func(w->data);
+ free(w);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_addlog_func(krb5_context context,
+ krb5_log_facility *fac,
+ int min,
+ int max,
+ krb5_log_log_func_t log_func,
+ krb5_log_close_func_t close_func,
+ void *data)
+{
+ struct krb5_addlog_func_wrapper *w = NULL;
+
+ w = calloc(1, sizeof(*w));
+ if (w == NULL)
+ return krb5_enomem(context);
+
+ w->context = context;
+ w->log_func = log_func;
+ w->close_func = close_func;
+ w->data = data;
+
+ return heim_addlog_func(context->hcontext, fac, min, max,
+ krb5_addlog_func_wrapper_log,
+ krb5_addlog_func_wrapper_close,
+ w);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_addlog_dest(krb5_context context, krb5_log_facility *f, const char *orig)
+{
+ return heim_addlog_dest(context->hcontext, f, orig);
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_openlog(krb5_context context,
+ const char *program,
+ krb5_log_facility **fac)
+{
+ krb5_error_code ret;
+ char **p;
+
+ p = krb5_config_get_strings(context, NULL, "logging", program, NULL);
+ if (p == NULL)
+ p = krb5_config_get_strings(context, NULL, "logging", "default", NULL);
+ ret = heim_openlog(context->hcontext, program, (const char **)p, fac);
+ krb5_config_free_strings(p);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_closelog(krb5_context context,
+ krb5_log_facility *fac)
+{
+ heim_closelog(context->hcontext, fac);
+ return 0;
+}
+
+#undef __attribute__
+#define __attribute__(X)
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_vlog_msg(krb5_context context,
+ krb5_log_facility *fac,
+ char **reply,
+ int level,
+ const char *fmt,
+ va_list ap)
+ __attribute__ ((__format__ (__printf__, 5, 0)))
+{
+ return heim_vlog_msg(context->hcontext, fac, reply, level, fmt, ap);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_vlog(krb5_context context,
+ krb5_log_facility *fac,
+ int level,
+ const char *fmt,
+ va_list ap)
+ __attribute__ ((__format__ (__printf__, 4, 0)))
+{
+ return heim_vlog_msg(context->hcontext, fac, NULL, level, fmt, ap);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_log_msg(krb5_context context,
+ krb5_log_facility *fac,
+ int level,
+ char **reply,
+ const char *fmt,
+ ...)
+ __attribute__ ((__format__ (__printf__, 5, 6)))
+{
+ va_list ap;
+ krb5_error_code ret;
+
+ va_start(ap, fmt);
+ ret = heim_vlog_msg(context->hcontext, fac, reply, level, fmt, ap);
+ va_end(ap);
+ return ret;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_log(krb5_context context,
+ krb5_log_facility *fac,
+ int level,
+ const char *fmt,
+ ...)
+ __attribute__ ((__format__ (__printf__, 4, 5)))
+{
+ va_list ap;
+ krb5_error_code ret;
+
+ va_start(ap, fmt);
+ ret = heim_vlog(context->hcontext, fac, level, fmt, ap);
+ va_end(ap);
+ return ret;
+}
+
+void KRB5_LIB_FUNCTION
+_krb5_debug(krb5_context context,
+ int level,
+ const char *fmt,
+ ...)
+ __attribute__ ((__format__ (__printf__, 3, 4)))
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ if (context && context->hcontext)
+ heim_vdebug(context->hcontext, level, fmt, ap);
+ va_end(ap);
+}
+
+void KRB5_LIB_FUNCTION
+krb5_debug(krb5_context context,
+ int level,
+ const char *fmt,
+ ...)
+ __attribute__ ((__format__ (__printf__, 3, 4)))
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ if (context && context->hcontext)
+ heim_vdebug(context->hcontext, level, fmt, ap);
+ va_end(ap);
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+_krb5_have_debug(krb5_context context, int level)
+{
+ if (context == NULL || context->hcontext == NULL)
+ return 0;
+ return heim_have_debug(context->hcontext, level);
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_have_debug(krb5_context context, int level)
+{
+ return _krb5_have_debug(context, level);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_debug_dest(krb5_context context, const char *program,
+ const char *log_spec)
+{
+ return heim_add_debug_dest(context->hcontext, program, log_spec);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_log_dest(krb5_context context, krb5_log_facility *fac)
+{
+ return heim_set_log_dest(context->hcontext, fac);
+}
diff --git a/third_party/heimdal/lib/krb5/mcache.c b/third_party/heimdal/lib/krb5/mcache.c
new file mode 100644
index 0000000..fdd5674
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/mcache.c
@@ -0,0 +1,623 @@
+/*
+ * Copyright (c) 1997-2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+typedef struct krb5_mcache {
+ char *name;
+ unsigned int refcnt;
+ unsigned int anonymous:1;
+ unsigned int dead:1;
+ krb5_principal primary_principal;
+ struct link {
+ krb5_creds cred;
+ struct link *next;
+ } *creds;
+ struct krb5_mcache *next;
+ time_t mtime;
+ krb5_deltat kdc_offset;
+ HEIMDAL_MUTEX mutex;
+} krb5_mcache;
+
+static HEIMDAL_MUTEX mcc_mutex = HEIMDAL_MUTEX_INITIALIZER;
+static struct krb5_mcache *mcc_head;
+
+#define MCACHE(X) ((krb5_mcache *)(X)->data.data)
+
+#define MISDEAD(X) ((X)->dead)
+
+static krb5_error_code KRB5_CALLCONV
+mcc_get_name_2(krb5_context context,
+ krb5_ccache id,
+ const char **name,
+ const char **col,
+ const char **sub)
+{
+ if (name)
+ *name = MCACHE(id)->name;
+ if (col)
+ *col = NULL;
+ if (sub)
+ *sub = MCACHE(id)->name;
+ return 0;
+}
+
+static krb5_error_code
+mcc_alloc(krb5_context context, const char *name, krb5_mcache **out)
+{
+ krb5_mcache *m, *m_c;
+ size_t counter = 0;
+ int ret = 0;
+ unsigned create_anonymous = 0;
+
+ *out = NULL;
+ ALLOC(m, 1);
+ if(m == NULL)
+ return krb5_enomem(context);
+
+again:
+ if (counter > 3) {
+ free(m->name);
+ free(m);
+ return EAGAIN; /* XXX */
+ }
+ if(name == NULL) {
+ ret = asprintf(&m->name, "u%p-%llu", m, (unsigned long long)counter);
+ } else if (strcmp(name, "anonymous") == 0) {
+ ret = asprintf(&m->name, "anonymous-%p-%llu", m, (unsigned long long)counter);
+ create_anonymous = 1;
+ } else {
+ m->name = strdup(name);
+ }
+ if(ret < 0 || m->name == NULL) {
+ free(m);
+ return krb5_enomem(context);
+ }
+
+ /* check for dups first */
+ HEIMDAL_MUTEX_lock(&mcc_mutex);
+ for (m_c = mcc_head; m_c != NULL; m_c = m_c->next)
+ if (strcmp(m->name, m_c->name) == 0)
+ break;
+ if (m_c) {
+ if (name && !create_anonymous) {
+ /* We raced with another thread to create this cache */
+ free(m->name);
+ free(m);
+ m = m_c;
+ HEIMDAL_MUTEX_lock(&(m->mutex));
+ m->refcnt++;
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ } else {
+ /* How likely are we to conflict on new_unique anyways?? */
+ counter++;
+ free(m->name);
+ m->name = NULL;
+ HEIMDAL_MUTEX_unlock(&mcc_mutex);
+ goto again;
+ }
+ HEIMDAL_MUTEX_unlock(&mcc_mutex);
+ *out = m;
+ return 0;
+ }
+
+ m->anonymous = create_anonymous;
+ m->dead = 0;
+ m->refcnt = 1;
+ m->primary_principal = NULL;
+ m->creds = NULL;
+ m->mtime = time(NULL);
+ m->kdc_offset = 0;
+ m->next = mcc_head;
+ HEIMDAL_MUTEX_init(&(m->mutex));
+ mcc_head = m;
+ HEIMDAL_MUTEX_unlock(&mcc_mutex);
+ *out = m;
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_resolve_2(krb5_context context,
+ krb5_ccache *id,
+ const char *res,
+ const char *sub)
+{
+ krb5_error_code ret;
+ krb5_mcache *m;
+
+ if ((ret = mcc_alloc(context, sub && *sub ? sub : res, &m)))
+ return ret;
+
+ (*id)->data.data = m;
+ (*id)->data.length = sizeof(*m);
+
+ return 0;
+}
+
+
+static krb5_error_code KRB5_CALLCONV
+mcc_gen_new(krb5_context context, krb5_ccache *id)
+{
+ krb5_error_code ret;
+ krb5_mcache *m;
+
+ if ((ret = mcc_alloc(context, NULL, &m)))
+ return ret;
+
+ (*id)->data.data = m;
+ (*id)->data.length = sizeof(*m);
+
+ return 0;
+}
+
+static void KRB5_CALLCONV
+mcc_destroy_internal(krb5_context context,
+ krb5_mcache *m)
+{
+ struct link *l;
+
+ if (m->primary_principal != NULL) {
+ krb5_free_principal (context, m->primary_principal);
+ m->primary_principal = NULL;
+ }
+ m->dead = 1;
+
+ l = m->creds;
+ while (l != NULL) {
+ struct link *old;
+
+ krb5_free_cred_contents (context, &l->cred);
+ old = l;
+ l = l->next;
+ free (old);
+ }
+
+ m->creds = NULL;
+ return;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_initialize(krb5_context context,
+ krb5_ccache id,
+ krb5_principal primary_principal)
+{
+ krb5_mcache *m = MCACHE(id);
+ krb5_error_code ret = 0;
+ HEIMDAL_MUTEX_lock(&(m->mutex));
+ heim_assert(m->refcnt != 0, "resurection released mcache");
+ /*
+ * It's important to destroy any existing
+ * creds here, that matches the baheviour
+ * of all other backends and also the
+ * MEMORY: backend in MIT.
+ */
+ mcc_destroy_internal(context, m);
+ m->dead = 0;
+ m->kdc_offset = 0;
+ m->mtime = time(NULL);
+ ret = krb5_copy_principal (context,
+ primary_principal,
+ &m->primary_principal);
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return ret;
+}
+
+static int
+mcc_close_internal(krb5_mcache *m)
+{
+ HEIMDAL_MUTEX_lock(&(m->mutex));
+ heim_assert(m->refcnt != 0, "closed dead cache mcache");
+ if (--m->refcnt != 0) {
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return 0;
+ }
+ if (MISDEAD(m)) {
+ free(m->name);
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return 1;
+ }
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_close(krb5_context context,
+ krb5_ccache id)
+{
+ krb5_mcache *m = MCACHE(id);
+
+ if (mcc_close_internal(MCACHE(id))) {
+ HEIMDAL_MUTEX_destroy(&(m->mutex));
+ krb5_data_free(&id->data);
+ }
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_destroy(krb5_context context,
+ krb5_ccache id)
+{
+ krb5_mcache **n, *m = MCACHE(id);
+
+ HEIMDAL_MUTEX_lock(&mcc_mutex);
+ HEIMDAL_MUTEX_lock(&(m->mutex));
+ if (m->refcnt == 0)
+ {
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ HEIMDAL_MUTEX_unlock(&mcc_mutex);
+ krb5_abortx(context, "mcc_destroy: refcnt already 0");
+ }
+
+ if (!MISDEAD(m)) {
+ /* if this is an active mcache, remove it from the linked
+ list, and free all data */
+ for(n = &mcc_head; n && *n; n = &(*n)->next) {
+ if(m == *n) {
+ *n = m->next;
+ break;
+ }
+ }
+ mcc_destroy_internal(context, m);
+ }
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ HEIMDAL_MUTEX_unlock(&mcc_mutex);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_store_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_creds *creds)
+{
+ krb5_mcache *m = MCACHE(id);
+ krb5_error_code ret;
+ struct link *l;
+
+ HEIMDAL_MUTEX_lock(&(m->mutex));
+ if (MISDEAD(m))
+ {
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return ENOENT;
+ }
+
+ l = malloc (sizeof(*l));
+ if (l == NULL)
+ return krb5_enomem(context);
+ l->next = m->creds;
+ m->creds = l;
+ memset (&l->cred, 0, sizeof(l->cred));
+ ret = krb5_copy_creds_contents (context, creds, &l->cred);
+ if (ret) {
+ m->creds = l->next;
+ free (l);
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return ret;
+ }
+ m->mtime = time(NULL);
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_get_principal(krb5_context context,
+ krb5_ccache id,
+ krb5_principal *principal)
+{
+ krb5_mcache *m = MCACHE(id);
+ krb5_error_code ret = 0;
+
+ HEIMDAL_MUTEX_lock(&(m->mutex));
+ if (MISDEAD(m) || m->primary_principal == NULL) {
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return ENOENT;
+ }
+ ret = krb5_copy_principal (context,
+ m->primary_principal,
+ principal);
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_get_first (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+ krb5_mcache *m = MCACHE(id);
+
+ HEIMDAL_MUTEX_lock(&(m->mutex));
+ if (MISDEAD(m)) {
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return ENOENT;
+ }
+ *cursor = m->creds;
+
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_get_next (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor,
+ krb5_creds *creds)
+{
+ krb5_mcache *m = MCACHE(id);
+ struct link *l;
+
+ HEIMDAL_MUTEX_lock(&(m->mutex));
+ if (MISDEAD(m)) {
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return ENOENT;
+ }
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+
+ l = *cursor;
+ if (l != NULL) {
+ *cursor = l->next;
+ return krb5_copy_creds_contents (context,
+ &l->cred,
+ creds);
+ } else
+ return KRB5_CC_END;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_end_get (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_remove_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_flags which,
+ krb5_creds *mcreds)
+{
+ krb5_mcache *m = MCACHE(id);
+ struct link **q, *p;
+
+ HEIMDAL_MUTEX_lock(&(m->mutex));
+
+ for(q = &m->creds, p = *q; p; p = *q) {
+ if(krb5_compare_creds(context, which, mcreds, &p->cred)) {
+ *q = p->next;
+ krb5_free_cred_contents(context, &p->cred);
+ free(p);
+ m->mtime = time(NULL);
+ } else
+ q = &p->next;
+ }
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_set_flags(krb5_context context,
+ krb5_ccache id,
+ krb5_flags flags)
+{
+ return 0; /* XXX */
+}
+
+struct mcache_iter {
+ krb5_mcache *cache;
+};
+
+static krb5_mcache *
+mcc_get_cache_find_next_internal(krb5_mcache *next)
+{
+ HEIMDAL_MUTEX_lock(&mcc_mutex);
+ for (; next != NULL && next->anonymous; next = next->next) {
+ /* noop: iterate over all anonymous entries */
+ }
+ if (next != NULL) {
+ HEIMDAL_MUTEX_lock(&(next->mutex));
+ next->refcnt++;
+ HEIMDAL_MUTEX_unlock(&(next->mutex));
+ next = next->next;
+ }
+ HEIMDAL_MUTEX_unlock(&mcc_mutex);
+
+ return next;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor)
+{
+ struct mcache_iter *iter;
+
+ iter = calloc(1, sizeof(*iter));
+ if (iter == NULL)
+ return krb5_enomem(context);
+
+ iter->cache = mcc_get_cache_find_next_internal(mcc_head);
+
+ *cursor = iter;
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_get_cache_next(krb5_context context, krb5_cc_cursor cursor, krb5_ccache *id)
+{
+ struct mcache_iter *iter = cursor;
+ krb5_error_code ret;
+ krb5_mcache *m;
+
+ if (iter->cache == NULL)
+ return KRB5_CC_END;
+
+ m = iter->cache;
+ iter->cache = mcc_get_cache_find_next_internal(m);
+
+ ret = _krb5_cc_allocate(context, &krb5_mcc_ops, id);
+ if (ret)
+ return ret;
+
+ (*id)->data.data = m;
+ (*id)->data.length = sizeof(*m);
+
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_end_cache_get(krb5_context context, krb5_cc_cursor cursor)
+{
+ struct mcache_iter *iter = cursor;
+
+ if (iter->cache)
+ mcc_close_internal(iter->cache);
+ iter->cache = NULL;
+ free(iter);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_move(krb5_context context, krb5_ccache from, krb5_ccache to)
+{
+ krb5_mcache *mfrom = MCACHE(from), *mto = MCACHE(to);
+ struct link *creds;
+ krb5_principal principal;
+ krb5_mcache **n;
+
+ HEIMDAL_MUTEX_lock(&mcc_mutex);
+
+ /* drop the from cache from the linked list to avoid lookups */
+ for(n = &mcc_head; n && *n; n = &(*n)->next) {
+ if(mfrom == *n) {
+ *n = mfrom->next;
+ break;
+ }
+ }
+
+ HEIMDAL_MUTEX_lock(&(mfrom->mutex));
+ HEIMDAL_MUTEX_lock(&(mto->mutex));
+ /* swap creds */
+ creds = mto->creds;
+ mto->creds = mfrom->creds;
+ mfrom->creds = creds;
+ /* swap principal */
+ principal = mto->primary_principal;
+ mto->primary_principal = mfrom->primary_principal;
+ mfrom->primary_principal = principal;
+
+ mto->mtime = mfrom->mtime = time(NULL);
+
+ HEIMDAL_MUTEX_unlock(&(mfrom->mutex));
+ HEIMDAL_MUTEX_unlock(&(mto->mutex));
+ HEIMDAL_MUTEX_unlock(&mcc_mutex);
+
+ krb5_cc_destroy(context, from);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_default_name(krb5_context context, char **str)
+{
+ *str = strdup("MEMORY:");
+ if (*str == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_lastchange(krb5_context context, krb5_ccache id, krb5_timestamp *mtime)
+{
+ krb5_mcache *m = MCACHE(id);
+ HEIMDAL_MUTEX_lock(&(m->mutex));
+ *mtime = m->mtime;
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat kdc_offset)
+{
+ krb5_mcache *m = MCACHE(id);
+ HEIMDAL_MUTEX_lock(&(m->mutex));
+ m->kdc_offset = kdc_offset;
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_get_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat *kdc_offset)
+{
+ krb5_mcache *m = MCACHE(id);
+ HEIMDAL_MUTEX_lock(&(m->mutex));
+ *kdc_offset = m->kdc_offset;
+ HEIMDAL_MUTEX_unlock(&(m->mutex));
+ return 0;
+}
+
+
+/**
+ * Variable containing the MEMORY based credential cache implemention.
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_VARIABLE const krb5_cc_ops krb5_mcc_ops = {
+ KRB5_CC_OPS_VERSION_5,
+ "MEMORY",
+ NULL,
+ NULL,
+ mcc_gen_new,
+ mcc_initialize,
+ mcc_destroy,
+ mcc_close,
+ mcc_store_cred,
+ NULL, /* mcc_retrieve */
+ mcc_get_principal,
+ mcc_get_first,
+ mcc_get_next,
+ mcc_end_get,
+ mcc_remove_cred,
+ mcc_set_flags,
+ NULL,
+ mcc_get_cache_first,
+ mcc_get_cache_next,
+ mcc_end_cache_get,
+ mcc_move,
+ mcc_default_name,
+ NULL,
+ mcc_lastchange,
+ mcc_set_kdc_offset,
+ mcc_get_kdc_offset,
+ mcc_get_name_2,
+ mcc_resolve_2
+};
diff --git a/third_party/heimdal/lib/krb5/misc.c b/third_party/heimdal/lib/krb5/misc.c
new file mode 100644
index 0000000..baf165c
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/misc.c
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#ifdef HAVE_EXECINFO_H
+#include <execinfo.h>
+#endif
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_s4u2self_to_checksumdata(krb5_context context,
+ const PA_S4U2Self *self,
+ krb5_data *data)
+{
+ krb5_error_code ret;
+ krb5_ssize_t ssize;
+ krb5_storage *sp;
+ size_t size;
+ size_t i;
+
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ return krb5_enomem(context);
+ krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
+ ret = krb5_store_int32(sp, self->name.name_type);
+ if (ret) {
+ krb5_clear_error_message(context);
+ return ret;
+ }
+ for (i = 0; i < self->name.name_string.len; i++) {
+ size = strlen(self->name.name_string.val[i]);
+ ssize = krb5_storage_write(sp, self->name.name_string.val[i], size);
+ if (ssize != (krb5_ssize_t)size)
+ return krb5_enomem(context);
+ }
+ size = strlen(self->realm);
+ ssize = krb5_storage_write(sp, self->realm, size);
+ if (ssize != (krb5_ssize_t)size)
+ return krb5_enomem(context);
+ size = strlen(self->auth);
+ ssize = krb5_storage_write(sp, self->auth, size);
+ if (ssize != (krb5_ssize_t)size)
+ return krb5_enomem(context);
+
+ ret = krb5_storage_to_data(sp, data);
+ krb5_storage_free(sp);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_debug_backtrace(krb5_context context)
+{
+#if defined(HAVE_BACKTRACE) && defined(HAVE_BACKTRACE_SYMBOLS) && !defined(HEIMDAL_SMALLER)
+ void *stack[128];
+ char **strs = NULL;
+ int i, frames = backtrace(stack, sizeof(stack) / sizeof(stack[0]));
+ if (frames > 0)
+ strs = backtrace_symbols(stack, frames);
+ if (strs) {
+ for (i = 0; i < frames; i++)
+ _krb5_debug(context, 10, "frame %d: %s", i, strs[i]);
+ free(strs);
+ }
+#endif
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_einval(krb5_context context, const char *func, unsigned long argn)
+{
+#ifndef HEIMDAL_SMALLER
+ krb5_set_error_message(context, EINVAL,
+ N_("programmer error: invalid argument to %s argument %lu",
+ "function:line"),
+ func, argn);
+ if (_krb5_have_debug(context, 10)) {
+ _krb5_debug(context, 10, "invalid argument to function %s argument %lu",
+ func, argn);
+ _krb5_debug_backtrace(context);
+ }
+#endif
+ return EINVAL;
+}
diff --git a/third_party/heimdal/lib/krb5/mit_glue.c b/third_party/heimdal/lib/krb5/mit_glue.c
new file mode 100644
index 0000000..44725f1
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/mit_glue.c
@@ -0,0 +1,434 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#ifndef HEIMDAL_SMALLER
+
+/*
+ * Glue for MIT API
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_make_checksum(krb5_context context,
+ krb5_cksumtype cksumtype,
+ const krb5_keyblock *key,
+ krb5_keyusage usage,
+ const krb5_data *input,
+ krb5_checksum *cksum)
+{
+ krb5_error_code ret;
+ krb5_crypto crypto;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ return ret;
+
+ ret = krb5_create_checksum(context, crypto, usage, cksumtype,
+ input->data, input->length, cksum);
+ krb5_crypto_destroy(context, crypto);
+
+ return ret ;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_verify_checksum(krb5_context context, const krb5_keyblock *key,
+ krb5_keyusage usage, const krb5_data *data,
+ const krb5_checksum *cksum, krb5_boolean *valid)
+{
+ krb5_error_code ret;
+ krb5_crypto crypto;
+
+ *valid = 0;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ return ret;
+
+ ret = krb5_verify_checksum(context, crypto, usage,
+ data->data, data->length, rk_UNCONST(cksum));
+ krb5_crypto_destroy(context, crypto);
+
+ if (ret == 0) {
+ *valid = 1;
+ }
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_get_checksum(krb5_context context, const krb5_checksum *cksum,
+ krb5_cksumtype *type, krb5_data **data)
+{
+ krb5_error_code ret;
+
+ if (type)
+ *type = cksum->cksumtype;
+ if (data) {
+ *data = malloc(sizeof(**data));
+ if (*data == NULL)
+ return krb5_enomem(context);
+
+ ret = der_copy_octet_string(&cksum->checksum, *data);
+ if (ret) {
+ free(*data);
+ *data = NULL;
+ return ret;
+ }
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_set_checksum(krb5_context context, krb5_checksum *cksum,
+ krb5_cksumtype type, const krb5_data *data)
+{
+ cksum->cksumtype = type;
+ return der_copy_octet_string(data, &cksum->checksum);
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_checksum (krb5_context context, krb5_checksum *cksum)
+{
+ krb5_checksum_free(context, cksum);
+ free(cksum);
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_checksum_contents(krb5_context context, krb5_checksum *cksum)
+{
+ krb5_checksum_free(context, cksum);
+ memset(cksum, 0, sizeof(*cksum));
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_checksum_free(krb5_context context, krb5_checksum *cksum)
+{
+ free_Checksum(cksum);
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_c_valid_enctype (krb5_enctype etype)
+{
+ return !krb5_enctype_valid(NULL, etype);
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_c_valid_cksumtype(krb5_cksumtype ctype)
+{
+ return krb5_cksumtype_valid(NULL, ctype);
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_c_is_coll_proof_cksum(krb5_cksumtype ctype)
+{
+ return krb5_checksum_is_collision_proof(NULL, ctype);
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_c_is_keyed_cksum(krb5_cksumtype ctype)
+{
+ return krb5_checksum_is_keyed(NULL, ctype);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_checksum (krb5_context context,
+ const krb5_checksum *old,
+ krb5_checksum **new)
+{
+ *new = malloc(sizeof(**new));
+ if (*new == NULL)
+ return krb5_enomem(context);
+ return copy_Checksum(old, *new);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_checksum_length (krb5_context context, krb5_cksumtype cksumtype,
+ size_t *length)
+{
+ return krb5_checksumsize(context, cksumtype, length);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_block_size(krb5_context context,
+ krb5_enctype enctype,
+ size_t *blocksize)
+{
+ krb5_error_code ret;
+ krb5_crypto crypto;
+ krb5_keyblock key;
+
+ ret = krb5_generate_random_keyblock(context, enctype, &key);
+ if (ret)
+ return ret;
+
+ ret = krb5_crypto_init(context, &key, 0, &crypto);
+ krb5_free_keyblock_contents(context, &key);
+ if (ret)
+ return ret;
+ ret = krb5_crypto_getblocksize(context, crypto, blocksize);
+ krb5_crypto_destroy(context, crypto);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_decrypt(krb5_context context,
+ const krb5_keyblock key,
+ krb5_keyusage usage,
+ const krb5_data *ivec,
+ krb5_enc_data *input,
+ krb5_data *output)
+{
+ krb5_error_code ret;
+ krb5_crypto crypto;
+
+ ret = krb5_crypto_init(context, &key, input->enctype, &crypto);
+ if (ret)
+ return ret;
+
+ if (ivec) {
+ size_t blocksize;
+
+ ret = krb5_crypto_getblocksize(context, crypto, &blocksize);
+ if (ret) {
+ krb5_crypto_destroy(context, crypto);
+ return ret;
+ }
+
+ if (blocksize > ivec->length) {
+ krb5_crypto_destroy(context, crypto);
+ return KRB5_BAD_MSIZE;
+ }
+ }
+
+ ret = krb5_decrypt_ivec(context, crypto, usage,
+ input->ciphertext.data, input->ciphertext.length,
+ output,
+ ivec ? ivec->data : NULL);
+
+ krb5_crypto_destroy(context, crypto);
+
+ return ret ;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_encrypt(krb5_context context,
+ const krb5_keyblock *key,
+ krb5_keyusage usage,
+ const krb5_data *ivec,
+ const krb5_data *input,
+ krb5_enc_data *output)
+{
+ krb5_error_code ret;
+ krb5_crypto crypto;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ return ret;
+
+ if (ivec) {
+ size_t blocksize;
+
+ ret = krb5_crypto_getblocksize(context, crypto, &blocksize);
+ if (ret) {
+ krb5_crypto_destroy(context, crypto);
+ return ret;
+ }
+
+ if (blocksize > ivec->length) {
+ krb5_crypto_destroy(context, crypto);
+ return KRB5_BAD_MSIZE;
+ }
+ }
+
+ ret = krb5_encrypt_ivec(context, crypto, usage,
+ input->data, input->length,
+ &output->ciphertext,
+ ivec ? ivec->data : NULL);
+ output->kvno = 0;
+ krb5_crypto_getenctype(context, crypto, &output->enctype);
+
+ krb5_crypto_destroy(context, crypto);
+
+ return ret ;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_encrypt_length(krb5_context context,
+ krb5_enctype enctype,
+ size_t inputlen,
+ size_t *length)
+{
+ krb5_error_code ret;
+ krb5_crypto crypto;
+ krb5_keyblock key;
+
+ ret = krb5_generate_random_keyblock(context, enctype, &key);
+ if (ret)
+ return ret;
+
+ ret = krb5_crypto_init(context, &key, 0, &crypto);
+ krb5_free_keyblock_contents(context, &key);
+ if (ret)
+ return ret;
+
+ *length = krb5_get_wrapped_length(context, crypto, inputlen);
+ krb5_crypto_destroy(context, crypto);
+
+ return 0;
+}
+
+/**
+ * Deprecated: keytypes doesn't exists, they are really enctypes.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_enctype_compare(krb5_context context,
+ krb5_enctype e1,
+ krb5_enctype e2,
+ krb5_boolean *similar)
+ KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+ *similar = (e1 == e2);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_make_random_key(krb5_context context,
+ krb5_enctype enctype,
+ krb5_keyblock *random_key)
+{
+ return krb5_generate_random_keyblock(context, enctype, random_key);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_keylengths(krb5_context context,
+ krb5_enctype enctype,
+ size_t *ilen,
+ size_t *keylen)
+{
+ krb5_error_code ret;
+
+ ret = krb5_enctype_keybits(context, enctype, ilen);
+ if (ret)
+ return ret;
+ *ilen = (*ilen + 7) / 8;
+ return krb5_enctype_keysize(context, enctype, keylen);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_prf_length(krb5_context context,
+ krb5_enctype type,
+ size_t *length)
+{
+ return krb5_crypto_prf_length(context, type, length);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_prf(krb5_context context,
+ const krb5_keyblock *key,
+ const krb5_data *input,
+ krb5_data *output)
+{
+ krb5_crypto crypto;
+ krb5_error_code ret;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ return ret;
+
+ ret = krb5_crypto_prf(context, crypto, input, output);
+ krb5_crypto_destroy(context, crypto);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_random_make_octets(krb5_context context, krb5_data * data)
+{
+ krb5_generate_random_block(data->data, data->length);
+ return 0;
+}
+
+/**
+ * MIT compat glue
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_copy_creds(krb5_context context,
+ const krb5_ccache from,
+ krb5_ccache to)
+{
+ return krb5_cc_copy_cache(context, from, to);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getsendsubkey(krb5_context context, krb5_auth_context auth_context,
+ krb5_keyblock **keyblock)
+{
+ return krb5_auth_con_getlocalsubkey(context, auth_context, keyblock);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getrecvsubkey(krb5_context context, krb5_auth_context auth_context,
+ krb5_keyblock **keyblock)
+{
+ return krb5_auth_con_getremotesubkey(context, auth_context, keyblock);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setsendsubkey(krb5_context context, krb5_auth_context auth_context,
+ krb5_keyblock *keyblock)
+{
+ return krb5_auth_con_setlocalsubkey(context, auth_context, keyblock);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setrecvsubkey(krb5_context context, krb5_auth_context auth_context,
+ krb5_keyblock *keyblock)
+{
+ return krb5_auth_con_setremotesubkey(context, auth_context, keyblock);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_free_default_realm(krb5_context context, krb5_realm realm)
+{
+ return krb5_xfree(realm);
+}
+
+#endif /* HEIMDAL_SMALLER */
diff --git a/third_party/heimdal/lib/krb5/mk_cred.c b/third_party/heimdal/lib/krb5/mk_cred.c
new file mode 100644
index 0000000..41e858f
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/mk_cred.c
@@ -0,0 +1,324 @@
+/*
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#define CHECKED_ALLOC(dst) do { \
+ if ((ALLOC(dst, 1)) == NULL) { \
+ ret = krb5_enomem(context); \
+ goto out; \
+ } \
+ } while (0)
+
+#define CHECKED_COPY(cp_func, dst, src) do { \
+ if (cp_func(src, dst)) { \
+ ret = krb5_enomem(context); \
+ goto out; \
+ } \
+ } while (0)
+#define CHECKED_COPY_PPC2KCI(cp_func, dst, src) \
+ CHECKED_COPY(cp_func, krb_cred_info->dst, &ppcreds[i]->src)
+
+#define CHECKED_ALLOC_ASSIGN(dst, src) do { \
+ if ((ALLOC(dst, 1)) == NULL) { \
+ ret = krb5_enomem(context); \
+ goto out; \
+ } else \
+ *dst = src; \
+ } while (0)
+#define CHECKED_ALLOC_ASSIGN_PPC2KCI(dst, src) \
+ CHECKED_ALLOC_ASSIGN(krb_cred_info->dst, ppcreds[i]->src)
+
+#define CHECKED_ALLOC_COPY(cp_func, dst, src) do { \
+ if ((ALLOC(dst, 1)) == NULL || cp_func(src, dst)) { \
+ ret = krb5_enomem(context); \
+ goto out; \
+ } \
+ } while (0)
+#define CHECKED_ALLOC_COPY_PPC2KCI(cp_func, dst, src) \
+ CHECKED_ALLOC_COPY(cp_func, krb_cred_info->dst, &ppcreds[i]->src)
+
+/**
+ * Make a KRB-CRED PDU with N credentials.
+ *
+ * @param context A kerberos 5 context.
+ * @param auth_context The auth context with the key to encrypt the out_data.
+ * @param ppcreds A null-terminated array of credentials to forward.
+ * @param ppdata The output KRB-CRED (to be freed by caller).
+ * @param replay_data (unused).
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_credential
+ */
+
+/* ARGSUSED */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_mk_ncred(krb5_context context, krb5_auth_context auth_context,
+ krb5_creds **ppcreds, krb5_data **ppdata,
+ krb5_replay_data *replay_data)
+{
+ krb5_error_code ret;
+ krb5_data out_data;
+
+ ret = _krb5_mk_ncred(context, auth_context, ppcreds, &out_data,
+ replay_data);
+ if (ret == 0) {
+ /*
+ * MIT allocates the return structure for no good reason. We do
+ * likewise as, in this case, incompatibility is the greater evil.
+ */
+ *ppdata = calloc(1, sizeof(**ppdata));
+ if (*ppdata) {
+ **ppdata = out_data;
+ } else {
+ krb5_data_free(&out_data);
+ ret = krb5_enomem(context);
+ }
+ }
+
+ return ret;
+}
+
+/* ARGSUSED */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_mk_ncred(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_creds **ppcreds,
+ krb5_data *out_data,
+ krb5_replay_data *replay_data)
+{
+ krb5_error_code ret;
+ EncKrbCredPart enc_krb_cred_part;
+ KrbCredInfo *krb_cred_info;
+ krb5_crypto crypto;
+ KRB_CRED cred;
+ unsigned char *buf = NULL;
+ size_t ncreds, i;
+ size_t buf_size;
+ size_t len;
+
+ /*
+ * The ownership of 'buf' is re-assigned to a containing structure
+ * multiple times. We enforce an invariant, either buf is non-zero
+ * and we own it, or buf is zero and it is freed or some structure
+ * owns any storage previously allocated as 'buf'.
+ */
+#define CHOWN_BUF(x, buf) do { (x) = (buf); (buf) = 0; } while (0)
+#define DISOWN_BUF(buf) do { free(buf); (buf) = 0; } while (0)
+
+ for (ncreds = 0; ppcreds[ncreds]; ncreds++)
+ ;
+
+ memset (&cred, 0, sizeof(cred));
+ memset (&enc_krb_cred_part, 0, sizeof(enc_krb_cred_part));
+ cred.pvno = 5;
+ cred.msg_type = krb_cred;
+ ALLOC_SEQ(&cred.tickets, ncreds);
+ if (cred.tickets.val == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ ALLOC_SEQ(&enc_krb_cred_part.ticket_info, ncreds);
+ if (enc_krb_cred_part.ticket_info.val == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ for (i = 0; i < ncreds; i++) {
+ ret = decode_Ticket(ppcreds[i]->ticket.data,
+ ppcreds[i]->ticket.length,
+ &cred.tickets.val[i],
+ &len);/* don't care about len */
+ if (ret)
+ goto out;
+
+ /* fill ticket_info.val[i] */
+ krb_cred_info = &enc_krb_cred_part.ticket_info.val[i];
+
+ CHECKED_COPY(copy_EncryptionKey,
+ &krb_cred_info->key, &ppcreds[i]->session);
+ CHECKED_ALLOC_COPY_PPC2KCI(copy_Realm, prealm, client->realm);
+ CHECKED_ALLOC_COPY_PPC2KCI(copy_PrincipalName, pname, client->name);
+ CHECKED_ALLOC_ASSIGN_PPC2KCI(flags, flags.b);
+ CHECKED_ALLOC_ASSIGN_PPC2KCI(authtime, times.authtime);
+ CHECKED_ALLOC_ASSIGN_PPC2KCI(starttime, times.starttime);
+ CHECKED_ALLOC_ASSIGN_PPC2KCI(endtime, times.endtime);
+ CHECKED_ALLOC_ASSIGN_PPC2KCI(renew_till, times.renew_till);
+ CHECKED_ALLOC_COPY_PPC2KCI(copy_Realm, srealm, server->realm);
+ CHECKED_ALLOC_COPY_PPC2KCI(copy_PrincipalName, sname, server->name);
+ CHECKED_ALLOC_COPY_PPC2KCI(copy_HostAddresses, caddr, addresses);
+ }
+
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) {
+ krb5_timestamp sec;
+ int32_t usec;
+
+ krb5_us_timeofday (context, &sec, &usec);
+
+ CHECKED_ALLOC_ASSIGN(enc_krb_cred_part.timestamp, sec);
+ CHECKED_ALLOC_ASSIGN(enc_krb_cred_part.usec, usec);
+ } else {
+ enc_krb_cred_part.timestamp = NULL;
+ enc_krb_cred_part.usec = NULL;
+ /* XXX Er, shouldn't we set the seq nums?? */
+ }
+
+ /* XXX: Is this needed? */
+ if (auth_context->local_address && auth_context->local_port) {
+ ret = krb5_make_addrport(context,
+ &enc_krb_cred_part.s_address,
+ auth_context->local_address,
+ auth_context->local_port);
+ if (ret)
+ goto out;
+ }
+
+ /* XXX: Is this needed? */
+ if (auth_context->remote_address) {
+ if (auth_context->remote_port) {
+ /*
+ * XXX: Should we be checking "no-addresses" for
+ * the receiving realm?
+ */
+ ret = krb5_make_addrport(context,
+ &enc_krb_cred_part.r_address,
+ auth_context->remote_address,
+ auth_context->remote_port);
+ if (ret)
+ goto out;
+ } else {
+ /*
+ * XXX Ugly, make krb5_make_addrport() handle missing port
+ * number (i.e., port == 0), then remove this else.
+ */
+ CHECKED_ALLOC(enc_krb_cred_part.r_address);
+ ret = krb5_copy_address(context, auth_context->remote_address,
+ enc_krb_cred_part.r_address);
+ if (ret)
+ goto out;
+ }
+ }
+
+ /* encode EncKrbCredPart */
+ ASN1_MALLOC_ENCODE(EncKrbCredPart, buf, buf_size,
+ &enc_krb_cred_part, &len, ret);
+ if (ret)
+ goto out;
+
+ /**
+ * Some older of the MIT gssapi library used clear-text tickets
+ * (warped inside AP-REQ encryption), use the krb5_auth_context
+ * flag KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED to support those
+ * tickets. The session key is used otherwise to encrypt the
+ * forwarded ticket.
+ */
+
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED) {
+ cred.enc_part.etype = KRB5_ENCTYPE_NULL;
+ cred.enc_part.kvno = NULL;
+ CHOWN_BUF(cred.enc_part.cipher.data, buf);
+ cred.enc_part.cipher.length = buf_size;
+ } else {
+ /*
+ * Here older versions then 0.7.2 of Heimdal used the local or
+ * remote subkey. That is wrong, the session key should be
+ * used. Heimdal 0.7.2 and newer have code to try both in the
+ * receiving end.
+ */
+
+ ret = krb5_crypto_init(context, auth_context->keyblock, 0, &crypto);
+ if (ret == 0)
+ ret = krb5_encrypt_EncryptedData(context,
+ crypto,
+ KRB5_KU_KRB_CRED,
+ buf,
+ len,
+ 0,
+ &cred.enc_part);
+ if (ret)
+ goto out;
+ DISOWN_BUF(buf);
+ krb5_crypto_destroy(context, crypto);
+ }
+
+ ASN1_MALLOC_ENCODE(KRB_CRED, buf, buf_size, &cred, &len, ret);
+ if (ret)
+ goto out;
+
+ CHOWN_BUF(out_data->data, buf);
+ out_data->length = len;
+ ret = 0;
+
+ out:
+ free_EncKrbCredPart(&enc_krb_cred_part);
+ free_KRB_CRED(&cred);
+ free(buf);
+ return ret;
+}
+
+/**
+ * Make a KRB-CRED PDU with 1 credential.
+ *
+ * @param context A kerberos 5 context.
+ * @param auth_context The auth context with the key to encrypt the out_data.
+ * @param ppcred A credential to forward.
+ * @param ppdata The output KRB-CRED (to be freed by caller).
+ * @param replay_data (unused).
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_credential
+ */
+
+/* ARGSUSED */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_mk_1cred(krb5_context context, krb5_auth_context auth_context,
+ krb5_creds *ppcred, krb5_data **ppdata,
+ krb5_replay_data *replay_data)
+{
+ krb5_creds *ppcreds[2] = { ppcred, NULL };
+
+ return krb5_mk_ncred(context, auth_context, ppcreds, ppdata, replay_data);
+}
+
+/* ARGSUSED */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_mk_1cred(krb5_context context, krb5_auth_context auth_context,
+ krb5_creds *ppcred, krb5_data *ppdata,
+ krb5_replay_data *replay_data)
+{
+ krb5_creds *ppcreds[2] = { ppcred, NULL };
+
+ return _krb5_mk_ncred(context, auth_context, ppcreds, ppdata, replay_data);
+}
diff --git a/third_party/heimdal/lib/krb5/mk_error.c b/third_party/heimdal/lib/krb5/mk_error.c
new file mode 100644
index 0000000..7f0be71
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/mk_error.c
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_mk_error_ext(krb5_context context,
+ krb5_error_code error_code,
+ const char *e_text,
+ const krb5_data *e_data,
+ const krb5_principal server,
+ const PrincipalName *client_name,
+ const Realm *client_realm,
+ time_t *client_time,
+ int *client_usec,
+ krb5_data *reply)
+{
+ const char *e_text2 = NULL;
+ KRB_ERROR msg;
+ krb5_timestamp sec;
+ int32_t usec;
+ size_t len = 0;
+ krb5_error_code ret = 0;
+
+ krb5_us_timeofday (context, &sec, &usec);
+
+ memset(&msg, 0, sizeof(msg));
+ msg.pvno = 5;
+ msg.msg_type = krb_error;
+ msg.stime = sec;
+ msg.susec = usec;
+ msg.ctime = client_time;
+ msg.cusec = client_usec;
+ /* Make sure we only send `protocol' error codes */
+ if(error_code < KRB5KDC_ERR_NONE || error_code >= KRB5_ERR_RCSID) {
+ if(e_text == NULL)
+ e_text = e_text2 = krb5_get_error_message(context, error_code);
+ error_code = KRB5KRB_ERR_GENERIC;
+ }
+ msg.error_code = error_code - KRB5KDC_ERR_NONE;
+ if (e_text)
+ msg.e_text = rk_UNCONST(&e_text);
+ if (e_data)
+ msg.e_data = rk_UNCONST(e_data);
+ if(server){
+ msg.realm = server->realm;
+ msg.sname = server->name;
+ }else{
+ static char unspec[] = "<unspecified realm>";
+ msg.realm = unspec;
+ }
+ msg.crealm = rk_UNCONST(client_realm);
+ msg.cname = rk_UNCONST(client_name);
+
+ ASN1_MALLOC_ENCODE(KRB_ERROR, reply->data, reply->length, &msg, &len, ret);
+ if (e_text2)
+ krb5_free_error_message(context, e_text2);
+ if (ret)
+ return ret;
+ if(reply->length != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_mk_error(krb5_context context,
+ krb5_error_code error_code,
+ const char *e_text,
+ const krb5_data *e_data,
+ const krb5_principal client,
+ const krb5_principal server,
+ time_t *client_time,
+ int *client_usec,
+ krb5_data *reply)
+{
+ const PrincipalName *client_name = NULL;
+ const Realm *client_realm = NULL;
+
+ if (client) {
+ client_realm = &client->realm;
+ client_name = &client->name;
+ }
+
+ return krb5_mk_error_ext(context, error_code, e_text, e_data,
+ server, client_name, client_realm,
+ client_time, client_usec, reply);
+}
diff --git a/third_party/heimdal/lib/krb5/mk_priv.c b/third_party/heimdal/lib/krb5/mk_priv.c
new file mode 100644
index 0000000..e3b2f91
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/mk_priv.c
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_mk_priv(krb5_context context,
+ krb5_auth_context auth_context,
+ const krb5_data *userdata,
+ krb5_data *outbuf,
+ krb5_replay_data *outdata)
+{
+ krb5_error_code ret;
+ KRB_PRIV s;
+ EncKrbPrivPart part;
+ u_char *buf = NULL;
+ size_t buf_size;
+ size_t len = 0;
+ krb5_crypto crypto;
+ krb5_keyblock *key;
+ krb5_replay_data rdata;
+
+ if ((auth_context->flags &
+ (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)) &&
+ outdata == NULL)
+ return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */
+
+ if (auth_context->local_subkey)
+ key = auth_context->local_subkey;
+ else if (auth_context->remote_subkey)
+ key = auth_context->remote_subkey;
+ else
+ key = auth_context->keyblock;
+
+ memset(&rdata, 0, sizeof(rdata));
+
+ part.user_data = *userdata;
+
+ krb5_us_timeofday (context, &rdata.timestamp, &rdata.usec);
+
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) {
+ part.timestamp = &rdata.timestamp;
+ part.usec = &rdata.usec;
+ } else {
+ part.timestamp = NULL;
+ part.usec = NULL;
+ }
+
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_RET_TIME) {
+ outdata->timestamp = rdata.timestamp;
+ outdata->usec = rdata.usec;
+ }
+
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) {
+ rdata.seq = auth_context->local_seqnumber;
+ part.seq_number = &rdata.seq;
+ } else
+ part.seq_number = NULL;
+
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_RET_SEQUENCE)
+ outdata->seq = auth_context->local_seqnumber;
+
+ part.s_address = auth_context->local_address;
+ part.r_address = auth_context->remote_address;
+
+ krb5_data_zero (&s.enc_part.cipher);
+
+ ASN1_MALLOC_ENCODE(EncKrbPrivPart, buf, buf_size, &part, &len, ret);
+ if (ret)
+ goto fail;
+ if (buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ s.pvno = 5;
+ s.msg_type = krb_priv;
+ s.enc_part.etype = key->keytype;
+ s.enc_part.kvno = NULL;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret) {
+ free (buf);
+ return ret;
+ }
+ ret = krb5_encrypt (context,
+ crypto,
+ KRB5_KU_KRB_PRIV,
+ buf + buf_size - len,
+ len,
+ &s.enc_part.cipher);
+ krb5_crypto_destroy(context, crypto);
+ if (ret) {
+ free(buf);
+ return ret;
+ }
+ free(buf);
+
+
+ ASN1_MALLOC_ENCODE(KRB_PRIV, buf, buf_size, &s, &len, ret);
+ if (ret)
+ goto fail;
+ if (buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ krb5_data_free (&s.enc_part.cipher);
+
+ ret = krb5_data_copy(outbuf, buf + buf_size - len, len);
+ if (ret) {
+ free(buf);
+ return krb5_enomem(context);
+ }
+ free (buf);
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE)
+ auth_context->local_seqnumber =
+ (auth_context->local_seqnumber + 1) & 0xFFFFFFFF;
+ return 0;
+
+ fail:
+ free (buf);
+ krb5_data_free (&s.enc_part.cipher);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/mk_rep.c b/third_party/heimdal/lib/krb5/mk_rep.c
new file mode 100644
index 0000000..bd24c6e
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/mk_rep.c
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_mk_rep(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_data *outbuf)
+{
+ krb5_error_code ret;
+ AP_REP ap;
+ EncAPRepPart body;
+ u_char *buf = NULL;
+ size_t buf_size;
+ size_t len = 0;
+ krb5_crypto crypto;
+
+ ap.pvno = 5;
+ ap.msg_type = krb_ap_rep;
+
+ memset (&body, 0, sizeof(body));
+
+ body.ctime = auth_context->authenticator->ctime;
+ body.cusec = auth_context->authenticator->cusec;
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_USE_SUBKEY) {
+ if (auth_context->local_subkey == NULL) {
+ ret = krb5_auth_con_generatelocalsubkey(context,
+ auth_context,
+ auth_context->keyblock);
+ if(ret) {
+ free_EncAPRepPart(&body);
+ return ret;
+ }
+ }
+ ret = krb5_copy_keyblock(context, auth_context->local_subkey,
+ &body.subkey);
+ if (ret) {
+ free_EncAPRepPart(&body);
+ return krb5_enomem(context);
+ }
+ } else
+ body.subkey = NULL;
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) {
+ if(auth_context->local_seqnumber == 0)
+ krb5_generate_seq_number (context,
+ auth_context->keyblock,
+ &auth_context->local_seqnumber);
+ ALLOC(body.seq_number, 1);
+ if (body.seq_number == NULL) {
+ free_EncAPRepPart(&body);
+ return krb5_enomem(context);
+ }
+ *(body.seq_number) = auth_context->local_seqnumber;
+ } else
+ body.seq_number = NULL;
+
+ ap.enc_part.etype = auth_context->keyblock->keytype;
+ ap.enc_part.kvno = NULL;
+
+ ASN1_MALLOC_ENCODE(EncAPRepPart, buf, buf_size, &body, &len, ret);
+ free_EncAPRepPart (&body);
+ if(ret)
+ return ret;
+ if (buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+ ret = krb5_crypto_init(context, auth_context->keyblock,
+ 0 /* ap.enc_part.etype */, &crypto);
+ if (ret) {
+ free (buf);
+ return ret;
+ }
+ ret = krb5_encrypt (context,
+ crypto,
+ KRB5_KU_AP_REQ_ENC_PART,
+ buf + buf_size - len,
+ len,
+ &ap.enc_part.cipher);
+ krb5_crypto_destroy(context, crypto);
+ free(buf);
+ if (ret)
+ return ret;
+
+ ASN1_MALLOC_ENCODE(AP_REP, outbuf->data, outbuf->length, &ap, &len, ret);
+ if (ret == 0 && outbuf->length != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+ free_AP_REP (&ap);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/mk_req.c b/third_party/heimdal/lib/krb5/mk_req.c
new file mode 100644
index 0000000..44e6c8b
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/mk_req.c
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_mk_req_exact(krb5_context context,
+ krb5_auth_context *auth_context,
+ const krb5_flags ap_req_options,
+ const krb5_principal server,
+ krb5_data *in_data,
+ krb5_ccache ccache,
+ krb5_data *outbuf)
+{
+ krb5_error_code ret;
+ krb5_creds this_cred, *cred;
+
+ memset(&this_cred, 0, sizeof(this_cred));
+
+ ret = krb5_cc_get_principal(context, ccache, &this_cred.client);
+
+ if(ret)
+ return ret;
+
+ ret = krb5_copy_principal (context, server, &this_cred.server);
+ if (ret) {
+ krb5_free_cred_contents (context, &this_cred);
+ return ret;
+ }
+
+ this_cred.times.endtime = 0;
+ if (auth_context && *auth_context && (*auth_context)->keytype)
+ this_cred.session.keytype = (*auth_context)->keytype;
+
+ ret = krb5_get_credentials (context, 0, ccache, &this_cred, &cred);
+ krb5_free_cred_contents(context, &this_cred);
+ if (ret)
+ return ret;
+
+ ret = krb5_mk_req_extended (context,
+ auth_context,
+ ap_req_options,
+ in_data,
+ cred,
+ outbuf);
+ krb5_free_creds(context, cred);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_mk_req(krb5_context context,
+ krb5_auth_context *auth_context,
+ const krb5_flags ap_req_options,
+ const char *service,
+ const char *hostname,
+ krb5_data *in_data,
+ krb5_ccache ccache,
+ krb5_data *outbuf)
+{
+ krb5_error_code ret;
+ char **realms;
+ char *real_hostname;
+ krb5_principal server;
+
+ ret = krb5_expand_hostname_realms (context, hostname,
+ &real_hostname, &realms);
+ if (ret)
+ return ret;
+
+ ret = krb5_build_principal (context, &server,
+ strlen(*realms),
+ *realms,
+ service,
+ real_hostname,
+ NULL);
+ free (real_hostname);
+ krb5_free_host_realm (context, realms);
+ if (ret)
+ return ret;
+ ret = krb5_mk_req_exact (context, auth_context, ap_req_options,
+ server, in_data, ccache, outbuf);
+ krb5_free_principal (context, server);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/mk_req_ext.c b/third_party/heimdal/lib/krb5/mk_req_ext.c
new file mode 100644
index 0000000..a8a07f1
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/mk_req_ext.c
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_mk_req_internal(krb5_context context,
+ krb5_auth_context *auth_context,
+ const krb5_flags ap_req_options,
+ krb5_data *in_data,
+ krb5_creds *in_creds,
+ krb5_data *outbuf,
+ krb5_key_usage checksum_usage,
+ krb5_key_usage encrypt_usage)
+{
+ krb5_error_code ret;
+ krb5_data authenticator;
+ Checksum c;
+ Checksum *c_opt;
+ krb5_auth_context ac;
+
+ if(auth_context) {
+ if(*auth_context == NULL)
+ ret = krb5_auth_con_init(context, auth_context);
+ else
+ ret = 0;
+ ac = *auth_context;
+ } else
+ ret = krb5_auth_con_init(context, &ac);
+ if(ret)
+ return ret;
+
+ if(ac->local_subkey == NULL && (ap_req_options & AP_OPTS_USE_SUBKEY)) {
+ ret = krb5_auth_con_generatelocalsubkey(context,
+ ac,
+ &in_creds->session);
+ if(ret)
+ goto out;
+ }
+
+ krb5_free_keyblock(context, ac->keyblock);
+ ret = krb5_copy_keyblock(context, &in_creds->session, &ac->keyblock);
+ if (ret)
+ goto out;
+
+ /*
+ * Use the default checksum type except for some interoperability cases
+ * with older MIT, DCE and Windows KDCs.
+ */
+ if (in_data) {
+ krb5_crypto crypto;
+ krb5_cksumtype checksum_type = CKSUMTYPE_NONE;
+
+ if (ac->keyblock->keytype == ETYPE_DES_CBC_CRC)
+ checksum_type = CKSUMTYPE_RSA_MD4;
+ else if (ac->keyblock->keytype == ETYPE_DES_CBC_MD4 ||
+ ac->keyblock->keytype == ETYPE_DES_CBC_MD5 ||
+ ac->keyblock->keytype == ETYPE_ARCFOUR_HMAC_MD5 ||
+ ac->keyblock->keytype == ETYPE_ARCFOUR_HMAC_MD5_56)
+ checksum_type = CKSUMTYPE_RSA_MD5;
+ else
+ checksum_type = CKSUMTYPE_NONE;
+
+ ret = krb5_crypto_init(context, ac->keyblock, 0, &crypto);
+ if (ret)
+ goto out;
+
+ _krb5_crypto_set_flags(context, crypto, KRB5_CRYPTO_FLAG_ALLOW_UNKEYED_CHECKSUM);
+ ret = krb5_create_checksum(context,
+ crypto,
+ checksum_usage,
+ checksum_type,
+ in_data->data,
+ in_data->length,
+ &c);
+ krb5_crypto_destroy(context, crypto);
+ c_opt = &c;
+ } else {
+ c_opt = NULL;
+ }
+
+ if (ret)
+ goto out;
+
+ ret = _krb5_build_authenticator(context,
+ ac,
+ ac->keyblock->keytype,
+ in_creds,
+ c_opt,
+ &authenticator,
+ encrypt_usage);
+ if (c_opt)
+ free_Checksum (c_opt);
+ if (ret)
+ goto out;
+
+ ret = krb5_build_ap_req (context, ac->keyblock->keytype,
+ in_creds, ap_req_options, authenticator, outbuf);
+out:
+ if(auth_context == NULL)
+ krb5_auth_con_free(context, ac);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_mk_req_extended(krb5_context context,
+ krb5_auth_context *auth_context,
+ const krb5_flags ap_req_options,
+ krb5_data *in_data,
+ krb5_creds *in_creds,
+ krb5_data *outbuf)
+{
+ return _krb5_mk_req_internal (context,
+ auth_context,
+ ap_req_options,
+ in_data,
+ in_creds,
+ outbuf,
+ KRB5_KU_AP_REQ_AUTH_CKSUM,
+ KRB5_KU_AP_REQ_AUTH);
+}
diff --git a/third_party/heimdal/lib/krb5/mk_safe.c b/third_party/heimdal/lib/krb5/mk_safe.c
new file mode 100644
index 0000000..b327e1c
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/mk_safe.c
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_mk_safe(krb5_context context,
+ krb5_auth_context auth_context,
+ const krb5_data *userdata,
+ krb5_data *outbuf,
+ krb5_replay_data *outdata)
+{
+ krb5_error_code ret;
+ KRB_SAFE s;
+ u_char *buf = NULL;
+ size_t buf_size;
+ size_t len = 0;
+ krb5_crypto crypto;
+ krb5_keyblock *key;
+ krb5_replay_data rdata;
+
+ if ((auth_context->flags &
+ (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)) &&
+ outdata == NULL)
+ return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */
+
+ if (auth_context->local_subkey)
+ key = auth_context->local_subkey;
+ else if (auth_context->remote_subkey)
+ key = auth_context->remote_subkey;
+ else
+ key = auth_context->keyblock;
+
+ s.pvno = 5;
+ s.msg_type = krb_safe;
+
+ memset(&rdata, 0, sizeof(rdata));
+
+ s.safe_body.user_data = *userdata;
+
+ krb5_us_timeofday (context, &rdata.timestamp, &rdata.usec);
+
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) {
+ s.safe_body.timestamp = &rdata.timestamp;
+ s.safe_body.usec = &rdata.usec;
+ } else {
+ s.safe_body.timestamp = NULL;
+ s.safe_body.usec = NULL;
+ }
+
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_RET_TIME) {
+ outdata->timestamp = rdata.timestamp;
+ outdata->usec = rdata.usec;
+ }
+
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) {
+ rdata.seq = auth_context->local_seqnumber;
+ s.safe_body.seq_number = &rdata.seq;
+ } else
+ s.safe_body.seq_number = NULL;
+
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_RET_SEQUENCE)
+ outdata->seq = auth_context->local_seqnumber;
+
+ s.safe_body.s_address = auth_context->local_address;
+ s.safe_body.r_address = auth_context->remote_address;
+
+ s.cksum.cksumtype = 0;
+ s.cksum.checksum.data = NULL;
+ s.cksum.checksum.length = 0;
+
+ ASN1_MALLOC_ENCODE(KRB_SAFE, buf, buf_size, &s, &len, ret);
+ if (ret)
+ return ret;
+ if(buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret) {
+ free (buf);
+ return ret;
+ }
+ ret = krb5_create_checksum(context,
+ crypto,
+ KRB5_KU_KRB_SAFE_CKSUM,
+ 0,
+ buf,
+ len,
+ &s.cksum);
+ krb5_crypto_destroy(context, crypto);
+ if (ret) {
+ free (buf);
+ return ret;
+ }
+
+ free(buf);
+ ASN1_MALLOC_ENCODE(KRB_SAFE, buf, buf_size, &s, &len, ret);
+ free_Checksum (&s.cksum);
+ if(ret)
+ return ret;
+ if(buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ outbuf->length = len;
+ outbuf->data = buf;
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE)
+ auth_context->local_seqnumber =
+ (auth_context->local_seqnumber + 1) & 0xFFFFFFFF;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/n-fold-test.c b/third_party/heimdal/lib/krb5/n-fold-test.c
new file mode 100644
index 0000000..2938b44
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/n-fold-test.c
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+
+enum { MAXSIZE = 24 };
+
+static struct testcase {
+ const char *str;
+ unsigned n;
+ unsigned char res[MAXSIZE];
+} tests[] = {
+ {"012345", 8,
+ {0xbe, 0x07, 0x26, 0x31, 0x27, 0x6b, 0x19, 0x55}
+ },
+ {"basch", 24,
+ {0x1a, 0xab, 0x6b, 0x42, 0x96, 0x4b, 0x98, 0xb2, 0x1f, 0x8c, 0xde,
+ 0x2d, 0x24, 0x48, 0xba, 0x34, 0x55, 0xd7, 0x86, 0x2c, 0x97, 0x31,
+ 0x64, 0x3f}
+ },
+ {"eichin", 24,
+ {0x65, 0x69, 0x63, 0x68, 0x69, 0x6e, 0x4b, 0x73, 0x2b, 0x4b,
+ 0x1b, 0x43, 0xda, 0x1a, 0x5b, 0x99, 0x5a, 0x58, 0xd2, 0xc6, 0xd0,
+ 0xd2, 0xdc, 0xca}
+ },
+ {"sommerfeld", 24,
+ {0x2f, 0x7a, 0x98, 0x55, 0x7c, 0x6e, 0xe4, 0xab, 0xad, 0xf4,
+ 0xe7, 0x11, 0x92, 0xdd, 0x44, 0x2b, 0xd4, 0xff, 0x53, 0x25, 0xa5,
+ 0xde, 0xf7, 0x5c}
+ },
+ {"MASSACHVSETTS INSTITVTE OF TECHNOLOGY", 24,
+ {0xdb, 0x3b, 0x0d, 0x8f, 0x0b, 0x06, 0x1e, 0x60, 0x32, 0x82,
+ 0xb3, 0x08, 0xa5, 0x08, 0x41, 0x22, 0x9a, 0xd7, 0x98, 0xfa, 0xb9,
+ 0x54, 0x0c, 0x1b}
+ },
+ {"assar@NADA.KTH.SE", 24,
+ {0x5c, 0x06, 0xc3, 0x4d, 0x2c, 0x89, 0x05, 0xbe, 0x7a, 0x51,
+ 0x83, 0x6c, 0xd6, 0xf8, 0x1c, 0x4b, 0x7a, 0x93, 0x49, 0x16, 0x5a,
+ 0xb3, 0xfa, 0xa9}
+ },
+ {"testKRBTEST.MIT.EDUtestkey", 24,
+ {0x50, 0x2c, 0xf8, 0x29, 0x78, 0xe5, 0xfb, 0x1a, 0x29, 0x06,
+ 0xbd, 0x22, 0x28, 0x91, 0x56, 0xc0, 0x06, 0xa0, 0xdc, 0xf5, 0xb6,
+ 0xc2, 0xda, 0x6c}
+ },
+ {"password", 7,
+ {0x78, 0xa0, 0x7b, 0x6c, 0xaf, 0x85, 0xfa}
+ },
+ {"Rough Consensus, and Running Code", 8,
+ {0xbb, 0x6e, 0xd3, 0x08, 0x70, 0xb7, 0xf0, 0xe0},
+ },
+ {"password", 21,
+ {0x59, 0xe4, 0xa8, 0xca, 0x7c, 0x03, 0x85, 0xc3, 0xc3, 0x7b, 0x3f,
+ 0x6d, 0x20, 0x00, 0x24, 0x7c, 0xb6, 0xe6, 0xbd, 0x5b, 0x3e},
+ },
+ {"MASSACHVSETTS INSTITVTE OF TECHNOLOGY", 24,
+ {0xdb, 0x3b, 0x0d, 0x8f, 0x0b, 0x06, 0x1e, 0x60, 0x32, 0x82, 0xb3,
+ 0x08, 0xa5, 0x08, 0x41, 0x22, 0x9a, 0xd7, 0x98, 0xfa, 0xb9, 0x54,
+ 0x0c, 0x1b}
+ },
+ {NULL, 0, {0}}
+};
+
+int
+main(int argc, char **argv)
+{
+ unsigned char data[MAXSIZE];
+ struct testcase *t;
+ int ret = 0;
+
+ for (t = tests; t->str; ++t) {
+ int i;
+
+ ret = _krb5_n_fold (t->str, strlen(t->str), data, t->n);
+ if (ret)
+ errx(1, "out of memory");
+ if (memcmp (data, t->res, t->n) != 0) {
+ printf ("n-fold(\"%s\", %d) failed\n", t->str, t->n);
+ printf ("should be: ");
+ for (i = 0; i < t->n; ++i)
+ printf ("%02x", t->res[i]);
+ printf ("\nresult was: ");
+ for (i = 0; i < t->n; ++i)
+ printf ("%02x", data[i]);
+ printf ("\n");
+ ret = 1;
+ }
+ }
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/n-fold.c b/third_party/heimdal/lib/krb5/n-fold.c
new file mode 100644
index 0000000..ba3150d
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/n-fold.c
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+
+static void
+rr13(uint8_t *dst1, uint8_t *dst2, uint8_t *src, size_t len)
+{
+ int bytes = (len + 7) / 8;
+ int i;
+ const int bits = 13 % len;
+
+ for (i = 0; i < bytes; i++) {
+ int bb;
+ int b1, s1, b2, s2;
+ /* calculate first bit position of this byte */
+ bb = 8 * i - bits;
+ while(bb < 0)
+ bb += len;
+ /* byte offset and shift count */
+ b1 = bb / 8;
+ s1 = bb % 8;
+
+ if (bb + 8 > bytes * 8)
+ /* watch for wraparound */
+ s2 = (len + 8 - s1) % 8;
+ else
+ s2 = 8 - s1;
+ b2 = (b1 + 1) % bytes;
+ dst1[i] = (src[b1] << s1) | (src[b2] >> s2);
+ dst2[i] = dst1[i];
+ }
+
+ return;
+}
+
+/*
+ * Add `b' to `a', both being one's complement numbers.
+ * This function assumes that inputs *a, *b are aligned
+ * to 4 bytes.
+ */
+static void
+add1(uint8_t *a, uint8_t *b, size_t len)
+{
+ int i;
+ int carry = 0;
+ uint32_t x;
+ uint32_t left, right;
+
+ for (i = len - 1; (i+1) % 4; i--) {
+ x = a[i] + b[i] + carry;
+ carry = x > 0xff;
+ a[i] = x & 0xff;
+ }
+
+ for (i = len / 4 - 1; i >= 0; i--) {
+ left = ntohl(((uint32_t *)a)[i]);
+ right = ntohl(((uint32_t *)b)[i]);
+ x = left + right + carry;
+ carry = x < left || x < right;
+ ((uint32_t *)a)[i] = x;
+ }
+
+ for (i = len - 1; (i+1) % 4; i--) {
+ x = a[i] + carry;
+ carry = x > 0xff;
+ a[i] = x & 0xff;
+ }
+
+ for (i = len / 4 - 1; carry && i >= 0; i--) {
+ left = ((uint32_t *)a)[i];
+ x = left + carry;
+ carry = x < left;
+ ((uint32_t *)a)[i] = x;
+ }
+
+ for (i = len / 4 - 1; i >=0; i--)
+ ((uint32_t *)a)[i] = htonl(((uint32_t *)a)[i]);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_n_fold(const void *str, size_t len, void *key, size_t size)
+{
+ /* if len < size we need at most N * len bytes, ie < 2 * size;
+ if len > size we need at most 2 * len */
+ size_t maxlen = 2 * max(size, len);
+ size_t l = 0;
+ uint8_t *tmp;
+ uint8_t *tmpbuf;
+ uint8_t *buf1;
+ uint8_t *buf2;
+
+ tmp = malloc(maxlen + 2 * len);
+ if (tmp == NULL)
+ return ENOMEM;
+
+ buf1 = tmp + maxlen;
+ buf2 = tmp + maxlen + len;
+
+ memset(key, 0, size);
+ memcpy(buf1, str, len);
+ memcpy(tmp, buf1, len);
+ do {
+ l += len;
+ while(l >= size) {
+ add1(key, tmp, size);
+ l -= size;
+ if(l == 0)
+ break;
+ memmove(tmp, tmp + size, l);
+ }
+ rr13(tmp + l, buf2, buf1, len * 8);
+ tmpbuf = buf1;
+ buf1 = buf2;
+ buf2 = tmpbuf;
+ } while(l != 0);
+
+ memset(tmp, 0, maxlen + 2 * len);
+ free(tmp);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/net_read.c b/third_party/heimdal/lib/krb5/net_read.c
new file mode 100644
index 0000000..70b1800
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/net_read.c
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 1997, 1998, 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ * Read \a len bytes from socket \a p_fd into buffer \a buf.
+ * Block until \a len bytes are read or until an error.
+ *
+ * @return If successful, the number of bytes read: \a len.
+ * On end-of-file, 0.
+ * On error, less than 0 (if single-threaded, the error can be found
+ * in the errno global variable).
+ */
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
+krb5_net_read (krb5_context context,
+ void *p_fd,
+ void *buf,
+ size_t len)
+{
+ krb5_socket_t fd = *((krb5_socket_t *)p_fd);
+ return net_read(fd, buf, len);
+}
diff --git a/third_party/heimdal/lib/krb5/net_write.c b/third_party/heimdal/lib/krb5/net_write.c
new file mode 100644
index 0000000..289b965
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/net_write.c
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 1997, 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
+krb5_net_write (krb5_context context,
+ void *p_fd,
+ const void *buf,
+ size_t len)
+{
+ krb5_socket_t fd = *((krb5_socket_t *)p_fd);
+ return net_write(fd, buf, len);
+}
+
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
+krb5_net_write_block(krb5_context context,
+ void *p_fd,
+ const void *buf,
+ size_t len,
+ time_t timeout)
+{
+ krb5_socket_t fd = *((krb5_socket_t *)p_fd);
+ int ret;
+ struct timeval tv, *tvp;
+ const char *cbuf = (const char *)buf;
+ size_t rem = len;
+ ssize_t count;
+ fd_set wfds;
+
+ do {
+ FD_ZERO(&wfds);
+ FD_SET(fd, &wfds);
+
+ if (timeout != 0) {
+ tv.tv_sec = timeout;
+ tv.tv_usec = 0;
+ tvp = &tv;
+ } else
+ tvp = NULL;
+
+ ret = select(fd + 1, NULL, &wfds, NULL, tvp);
+ if (rk_IS_SOCKET_ERROR(ret)) {
+ if (rk_SOCK_ERRNO == EINTR)
+ continue;
+ return -1;
+ }
+
+#ifdef HAVE_WINSOCK
+ if (ret == 0) {
+ WSASetLastError( WSAETIMEDOUT );
+ return 0;
+ }
+
+ count = send (fd, cbuf, rem, 0);
+
+ if (rk_IS_SOCKET_ERROR(count)) {
+ return -1;
+ }
+
+#else
+ if (ret == 0) {
+ return 0;
+ }
+
+ if (!FD_ISSET(fd, &wfds)) {
+ errno = ETIMEDOUT;
+ return -1;
+ }
+
+ count = write (fd, cbuf, rem);
+
+ if (count < 0) {
+ if (errno == EINTR)
+ continue;
+ else
+ return count;
+ }
+
+#endif
+
+ cbuf += count;
+ rem -= count;
+
+ } while (rem > 0);
+
+ return len;
+}
diff --git a/third_party/heimdal/lib/krb5/pac.c b/third_party/heimdal/lib/krb5/pac.c
new file mode 100644
index 0000000..e58ab90
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/pac.c
@@ -0,0 +1,2130 @@
+/*
+ * Copyright (c) 2006 - 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#include <heimbasepriv.h>
+#include <wind.h>
+#include <assert.h>
+
+/*
+ * https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pac/3341cfa2-6ef5-42e0-b7bc-4544884bf399
+ */
+struct PAC_INFO_BUFFER {
+ uint32_t type; /* ULONG ulType in the original */
+ uint32_t buffersize; /* ULONG cbBufferSize in the original */
+ uint64_t offset; /* ULONG64 Offset in the original
+ * this being the offset from the beginning of the
+ * struct PACTYPE to the beginning of the buffer
+ * containing data of type ulType
+ */
+};
+
+/*
+ * https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pac/6655b92f-ab06-490b-845d-037e6987275f
+ */
+struct PACTYPE {
+ uint32_t numbuffers; /* named cBuffers of type ULONG in the original */
+ uint32_t version; /* Named Version of type ULONG in the original */
+ struct PAC_INFO_BUFFER buffers[1]; /* an ellipsis (...) in the original */
+};
+
+/*
+ * A PAC starts with a PACTYPE header structure that is followed by an array of
+ * numbuffers PAC_INFO_BUFFER structures, each of which points to a buffer
+ * beyond the last PAC_INFO_BUFFER structures.
+ */
+
+struct krb5_pac_data {
+ struct PACTYPE *pac;
+ krb5_data data;
+ struct PAC_INFO_BUFFER *server_checksum;
+ struct PAC_INFO_BUFFER *privsvr_checksum;
+ struct PAC_INFO_BUFFER *logon_name;
+ struct PAC_INFO_BUFFER *upn_dns_info;
+ struct PAC_INFO_BUFFER *ticket_checksum;
+ struct PAC_INFO_BUFFER *attributes_info;
+ struct PAC_INFO_BUFFER *full_checksum;
+ krb5_data ticket_sign_data;
+
+ /* PAC_UPN_DNS_INFO */
+ krb5_principal upn_princ;
+ uint32_t upn_flags;
+ krb5_principal canon_princ;
+ krb5_data sid;
+
+ /* PAC_ATTRIBUTES_INFO */
+ uint64_t pac_attributes;
+};
+
+#define PAC_ALIGNMENT 8
+
+#define PACTYPE_SIZE 8
+#define PAC_INFO_BUFFER_SIZE 16
+
+#define PAC_LOGON_INFO 1
+#define PAC_CREDENTIALS_INFO 2
+#define PAC_SERVER_CHECKSUM 6
+#define PAC_PRIVSVR_CHECKSUM 7
+#define PAC_LOGON_NAME 10
+#define PAC_CONSTRAINED_DELEGATION 11
+#define PAC_UPN_DNS_INFO 12
+#define PAC_TICKET_CHECKSUM 16
+#define PAC_ATTRIBUTES_INFO 17
+#define PAC_REQUESTOR_SID 18
+#define PAC_FULL_CHECKSUM 19
+
+/* Flag in PAC_UPN_DNS_INFO */
+#define PAC_EXTRA_LOGON_INFO_FLAGS_UPN_DEFAULTED 0x1
+#define PAC_EXTRA_LOGON_INFO_FLAGS_HAS_SAM_NAME_AND_SID 0x2
+
+#define CHECK(r,f,l) \
+ do { \
+ if (((r) = f ) != 0) { \
+ krb5_clear_error_message(context); \
+ goto l; \
+ } \
+ } while(0)
+
+static const char zeros[PAC_ALIGNMENT];
+
+static void HEIM_CALLCONV
+pac_dealloc(void *ctx)
+{
+ krb5_pac pac = (krb5_pac)ctx;
+
+ krb5_data_free(&pac->data);
+ krb5_data_free(&pac->ticket_sign_data);
+
+ if (pac->upn_princ) {
+ free_Principal(pac->upn_princ);
+ free(pac->upn_princ);
+ }
+ if (pac->canon_princ) {
+ free_Principal(pac->canon_princ);
+ free(pac->canon_princ);
+ }
+ krb5_data_free(&pac->sid);
+
+ free(pac->pac);
+}
+
+struct heim_type_data pac_object = {
+ HEIM_TID_PAC,
+ "heim-pac",
+ NULL,
+ pac_dealloc,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+/*
+ * Returns the size of the PACTYPE header + the PAC_INFO_BUFFER array. This is
+ * also the end of the whole thing, and any offsets to buffers from
+ * thePAC_INFO_BUFFER[] entries have to be beyond it.
+ */
+static krb5_error_code
+pac_header_size(krb5_context context, uint32_t num_buffers, uint32_t *result)
+{
+ krb5_error_code ret;
+ uint32_t header_size;
+
+ /* Guard against integer overflow */
+ if (num_buffers > UINT32_MAX / PAC_INFO_BUFFER_SIZE) {
+ ret = EOVERFLOW;
+ krb5_set_error_message(context, ret, "PAC has too many buffers");
+ return ret;
+ }
+ header_size = PAC_INFO_BUFFER_SIZE * num_buffers;
+
+ /* Guard against integer overflow */
+ if (header_size > UINT32_MAX - PACTYPE_SIZE) {
+ ret = EOVERFLOW;
+ krb5_set_error_message(context, ret, "PAC has too many buffers");
+ return ret;
+ }
+ header_size += PACTYPE_SIZE;
+
+ *result = header_size;
+
+ return 0;
+}
+
+/* Output `size' + `addend' + padding for alignment if it doesn't overflow */
+static krb5_error_code
+pac_aligned_size(krb5_context context,
+ uint32_t size,
+ uint32_t addend,
+ uint32_t *aligned_size)
+{
+ krb5_error_code ret;
+
+ if (size > UINT32_MAX - addend ||
+ (size + addend) > UINT32_MAX - (PAC_ALIGNMENT - 1)) {
+ ret = EOVERFLOW;
+ krb5_set_error_message(context, ret, "integer overrun");
+ return ret;
+ }
+ size += addend;
+ size += PAC_ALIGNMENT - 1;
+ size &= ~(PAC_ALIGNMENT - 1);
+ *aligned_size = size;
+ return 0;
+}
+
+/*
+ * HMAC-MD5 checksum over any key (needed for the PAC routines)
+ */
+
+static krb5_error_code
+HMAC_MD5_any_checksum(krb5_context context,
+ const krb5_keyblock *key,
+ const void *data,
+ size_t len,
+ unsigned usage,
+ Checksum *result)
+{
+ struct _krb5_key_data local_key;
+ struct krb5_crypto_iov iov;
+ krb5_error_code ret;
+
+ memset(&local_key, 0, sizeof(local_key));
+
+ ret = krb5_copy_keyblock(context, key, &local_key.key);
+ if (ret)
+ return ret;
+
+ ret = krb5_data_alloc (&result->checksum, 16);
+ if (ret) {
+ krb5_free_keyblock(context, local_key.key);
+ return ret;
+ }
+
+ result->cksumtype = CKSUMTYPE_HMAC_MD5;
+ iov.data.data = (void *)data;
+ iov.data.length = len;
+ iov.flags = KRB5_CRYPTO_TYPE_DATA;
+
+ ret = _krb5_HMAC_MD5_checksum(context, NULL, &local_key, usage, &iov, 1,
+ result);
+ if (ret)
+ krb5_data_free(&result->checksum);
+
+ krb5_free_keyblock(context, local_key.key);
+ return ret;
+}
+
+
+/*
+ *
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_pac_parse(krb5_context context, const void *ptr, size_t len,
+ krb5_pac *pac)
+{
+ krb5_error_code ret = 0;
+ krb5_pac p;
+ krb5_storage *sp = NULL;
+ uint32_t i, num_buffers, version, header_size = 0;
+ uint32_t prev_start = 0;
+ uint32_t prev_end = 0;
+
+ *pac = NULL;
+ p = _heim_alloc_object(&pac_object, sizeof(*p));
+ if (p)
+ sp = krb5_storage_from_readonly_mem(ptr, len);
+ if (sp == NULL)
+ ret = krb5_enomem(context);
+ if (ret == 0) {
+ krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
+ ret = krb5_ret_uint32(sp, &num_buffers);
+ }
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &version);
+ if (ret == 0 && num_buffers < 1)
+ krb5_set_error_message(context, ret = EINVAL,
+ N_("PAC has too few buffers", ""));
+ if (ret == 0 && num_buffers > 1000)
+ krb5_set_error_message(context, ret = EINVAL,
+ N_("PAC has too many buffers", ""));
+ if (ret == 0 && version != 0)
+ krb5_set_error_message(context, ret = EINVAL,
+ N_("PAC has wrong version %d", ""),
+ (int)version);
+ if (ret == 0)
+ ret = pac_header_size(context, num_buffers, &header_size);
+ if (ret == 0 && header_size > len)
+ krb5_set_error_message(context, ret = EOVERFLOW,
+ N_("PAC encoding invalid, would overflow buffers", ""));
+ if (ret == 0)
+ p->pac = calloc(1, header_size);
+ if (ret == 0 && p->pac == NULL)
+ ret = krb5_enomem(context);
+
+ if (ret == 0) {
+ p->pac->numbuffers = num_buffers;
+ p->pac->version = version;
+ }
+
+ for (i = 0; ret == 0 && i < p->pac->numbuffers; i++) {
+ ret = krb5_ret_uint32(sp, &p->pac->buffers[i].type);
+ if (ret == 0)
+ ret = krb5_ret_uint32(sp, &p->pac->buffers[i].buffersize);
+ if (ret == 0)
+ ret = krb5_ret_uint64(sp, &p->pac->buffers[i].offset);
+ if (ret)
+ break;
+
+ /* Consistency checks (we don't check for wasted space) */
+ if (p->pac->buffers[i].offset & (PAC_ALIGNMENT - 1)) {
+ krb5_set_error_message(context, ret = EINVAL,
+ N_("PAC out of alignment", ""));
+ break;
+ }
+ if (p->pac->buffers[i].offset > len ||
+ p->pac->buffers[i].buffersize > len ||
+ len - p->pac->buffers[i].offset < p->pac->buffers[i].buffersize) {
+ krb5_set_error_message(context, ret = EOVERFLOW,
+ N_("PAC buffer overflow", ""));
+ break;
+ }
+ if (p->pac->buffers[i].offset < header_size) {
+ krb5_set_error_message(context, ret = EINVAL,
+ N_("PAC offset inside header: %lu %lu", ""),
+ (unsigned long)p->pac->buffers[i].offset,
+ (unsigned long)header_size);
+ break;
+ }
+
+ /*
+ * We'd like to check for non-overlapping of buffers, but the buffers
+ * need not be in the same order as the PAC_INFO_BUFFER[] entries
+ * pointing to them! To fully check for overlap we'd have to have an
+ * O(N^2) loop after we parse all the PAC_INFO_BUFFER[].
+ *
+ * But we can check that each buffer does not overlap the previous
+ * buffer.
+ */
+ if (prev_start) {
+ if (p->pac->buffers[i].offset >= prev_start &&
+ p->pac->buffers[i].offset < prev_end) {
+ krb5_set_error_message(context, ret = EINVAL,
+ N_("PAC overlap", ""));
+ break;
+ }
+ if (p->pac->buffers[i].offset < prev_start &&
+ p->pac->buffers[i].offset +
+ p->pac->buffers[i].buffersize > prev_start) {
+ krb5_set_error_message(context, ret = EINVAL,
+ N_("PAC overlap", ""));
+ break;
+ }
+ }
+ prev_start = p->pac->buffers[i].offset;
+ prev_end = p->pac->buffers[i].offset + p->pac->buffers[i].buffersize;
+
+ /* Let's save pointers to buffers we'll need later */
+ switch (p->pac->buffers[i].type) {
+ case PAC_SERVER_CHECKSUM:
+ if (p->server_checksum)
+ krb5_set_error_message(context, ret = EINVAL,
+ N_("PAC has multiple server checksums", ""));
+ else
+ p->server_checksum = &p->pac->buffers[i];
+ break;
+ case PAC_PRIVSVR_CHECKSUM:
+ if (p->privsvr_checksum)
+ krb5_set_error_message(context, ret = EINVAL,
+ N_("PAC has multiple KDC checksums", ""));
+ else
+ p->privsvr_checksum = &p->pac->buffers[i];
+ break;
+ case PAC_LOGON_NAME:
+ if (p->logon_name)
+ krb5_set_error_message(context, ret = EINVAL,
+ N_("PAC has multiple logon names", ""));
+ else
+ p->logon_name = &p->pac->buffers[i];
+ break;
+ case PAC_UPN_DNS_INFO:
+ if (p->upn_dns_info)
+ krb5_set_error_message(context, ret = EINVAL,
+ N_("PAC has multiple UPN DNS info buffers", ""));
+ else
+ p->upn_dns_info = &p->pac->buffers[i];
+ break;
+ case PAC_TICKET_CHECKSUM:
+ if (p->ticket_checksum)
+ krb5_set_error_message(context, ret = EINVAL,
+ N_("PAC has multiple ticket checksums", ""));
+ else
+ p->ticket_checksum = &p->pac->buffers[i];
+ break;
+ case PAC_ATTRIBUTES_INFO:
+ if (p->attributes_info)
+ krb5_set_error_message(context, ret = EINVAL,
+ N_("PAC has multiple attributes info buffers", ""));
+ else
+ p->attributes_info = &p->pac->buffers[i];
+ break;
+ case PAC_FULL_CHECKSUM:
+ if (p->full_checksum)
+ krb5_set_error_message(context, ret = EINVAL,
+ N_("PAC has multiple full checksums", ""));
+ else
+ p->full_checksum = &p->pac->buffers[i];
+ break;
+ default: break;
+ }
+ }
+
+ if (ret == 0)
+ ret = krb5_data_copy(&p->data, ptr, len);
+ if (ret == 0) {
+ *pac = p;
+ p = NULL;
+ }
+ if (sp)
+ krb5_storage_free(sp);
+ krb5_pac_free(context, p);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_pac_init(krb5_context context, krb5_pac *pac)
+{
+ krb5_error_code ret;
+ krb5_pac p;
+
+ p = _heim_alloc_object(&pac_object, sizeof(*p));
+ if (p == NULL) {
+ return krb5_enomem(context);
+ }
+
+ p->pac = calloc(1, sizeof(*p->pac));
+ if (p->pac == NULL) {
+ krb5_pac_free(context, p);
+ return krb5_enomem(context);
+ }
+
+ ret = krb5_data_alloc(&p->data, PACTYPE_SIZE);
+ if (ret) {
+ free (p->pac);
+ krb5_pac_free(context, p);
+ return krb5_enomem(context);
+ }
+ memset(p->data.data, 0, p->data.length);
+
+ *pac = p;
+ return 0;
+}
+
+/**
+ * Add a PAC buffer `nd' of type `type' to the pac `p'.
+ *
+ * @param context
+ * @param p
+ * @param type
+ * @param nd
+ *
+ * @return 0 on success or a Kerberos or system error.
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_pac_add_buffer(krb5_context context, krb5_pac p,
+ uint32_t type, const krb5_data *nd)
+{
+ krb5_error_code ret;
+ void *ptr;
+ size_t old_len = p->data.length;
+ uint32_t len, offset, header_size;
+ uint32_t i;
+ uint32_t num_buffers;
+
+ assert(nd->data != NULL);
+
+ num_buffers = p->pac->numbuffers;
+ ret = pac_header_size(context, num_buffers + 1, &header_size);
+ if (ret)
+ return ret;
+
+ ptr = realloc(p->pac, header_size);
+ if (ptr == NULL)
+ return krb5_enomem(context);
+
+ p->pac = ptr;
+ p->pac->buffers[num_buffers].type = 0;
+ p->pac->buffers[num_buffers].buffersize = 0;
+ p->pac->buffers[num_buffers].offset = 0;
+
+ /*
+ * Check that we can adjust all the buffer offsets in the existing
+ * PAC_INFO_BUFFERs, since changing the size of PAC_INFO_BUFFER[] means
+ * changing the offsets of buffers following that array.
+ *
+ * We don't adjust them until we can't fail.
+ */
+ for (i = 0; i < num_buffers; i++) {
+ if (p->pac->buffers[i].offset > UINT32_MAX - PAC_INFO_BUFFER_SIZE) {
+ krb5_set_error_message(context, ret = EOVERFLOW,
+ "too many / too large PAC buffers");
+ return ret;
+ }
+ }
+
+ /*
+ * The new buffer's offset must be past the end of the buffers we have
+ * (p->data), which is the sum of the header and p->data.length.
+ */
+
+ /* Set offset = p->data.length + PAC_INFO_BUFFER_SIZE + alignment */
+ ret = pac_aligned_size(context, p->data.length, PAC_INFO_BUFFER_SIZE, &offset);
+ if (ret == 0)
+ /* Set the new length = offset + nd->length + alignment */
+ ret = pac_aligned_size(context, offset, nd->length, &len);
+ if (ret) {
+ krb5_set_error_message(context, ret, "PAC buffer too large");
+ return ret;
+ }
+ ret = krb5_data_realloc(&p->data, len);
+ if (ret) {
+ krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+ return ret;
+ }
+
+ /* Zero out the new allocation to zero out any padding */
+ memset((char *)p->data.data + old_len, 0, len - old_len);
+
+ p->pac->buffers[num_buffers].type = type;
+ p->pac->buffers[num_buffers].buffersize = nd->length;
+ p->pac->buffers[num_buffers].offset = offset;
+
+ /* Adjust all the buffer offsets in the existing PAC_INFO_BUFFERs now */
+ for (i = 0; i < num_buffers; i++)
+ p->pac->buffers[i].offset += PAC_INFO_BUFFER_SIZE;
+
+ /*
+ * Make place for new PAC INFO BUFFER header
+ */
+ header_size -= PAC_INFO_BUFFER_SIZE;
+ memmove((unsigned char *)p->data.data + header_size + PAC_INFO_BUFFER_SIZE,
+ (unsigned char *)p->data.data + header_size ,
+ old_len - header_size);
+ /* Clear the space where we would put the new PAC_INFO_BUFFER[] element */
+ memset((unsigned char *)p->data.data + header_size, 0,
+ PAC_INFO_BUFFER_SIZE);
+
+ /*
+ * Copy in new data part
+ */
+ memcpy((unsigned char *)p->data.data + offset, nd->data, nd->length);
+ p->pac->numbuffers += 1;
+ return 0;
+}
+
+/**
+ * Get the PAC buffer of specific type from the pac.
+ *
+ * @param context Kerberos 5 context.
+ * @param p the pac structure returned by krb5_pac_parse().
+ * @param type type of buffer to get
+ * @param data return data, free with krb5_data_free().
+ *
+ * @return Returns 0 to indicate success, ENOENT to indicate that a buffer of
+ * the given type was not found, or a Kerberos or system error code.
+ *
+ * @ingroup krb5_pac
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_pac_get_buffer(krb5_context context, krb5_const_pac p,
+ uint32_t type, krb5_data *data)
+{
+ krb5_error_code ret;
+ uint32_t i;
+
+ for (i = 0; i < p->pac->numbuffers; i++) {
+ size_t len = p->pac->buffers[i].buffersize;
+ size_t offset = p->pac->buffers[i].offset;
+
+ if (p->pac->buffers[i].type != type)
+ continue;
+
+ if (!data)
+ return 0;
+
+ ret = krb5_data_copy(data, (unsigned char *)p->data.data + offset, len);
+ if (ret)
+ krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+ return ret;
+ }
+ krb5_set_error_message(context, ENOENT, "No PAC buffer of type %lu was found",
+ (unsigned long)type);
+ return ENOENT;
+}
+
+static struct {
+ uint32_t type;
+ krb5_data name;
+} pac_buffer_name_map[] = {
+#define PAC_MAP_ENTRY(type, name) { PAC_##type, { sizeof(name) - 1, name } }
+ PAC_MAP_ENTRY(LOGON_INFO, "logon-info" ),
+ PAC_MAP_ENTRY(CREDENTIALS_INFO, "credentials-info" ),
+ PAC_MAP_ENTRY(SERVER_CHECKSUM, "server-checksum" ),
+ PAC_MAP_ENTRY(PRIVSVR_CHECKSUM, "privsvr-checksum" ),
+ PAC_MAP_ENTRY(LOGON_NAME, "client-info" ),
+ PAC_MAP_ENTRY(CONSTRAINED_DELEGATION, "delegation-info" ),
+ PAC_MAP_ENTRY(UPN_DNS_INFO, "upn-dns-info" ),
+ PAC_MAP_ENTRY(TICKET_CHECKSUM, "ticket-checksum" ),
+ PAC_MAP_ENTRY(ATTRIBUTES_INFO, "attributes-info" ),
+ PAC_MAP_ENTRY(REQUESTOR_SID, "requestor-sid" )
+};
+
+/*
+ *
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_pac_get_buffer_by_name(krb5_context context, krb5_const_pac p,
+ const krb5_data *name, krb5_data *data)
+{
+ size_t i;
+
+ for (i = 0;
+ i < sizeof(pac_buffer_name_map) / sizeof(pac_buffer_name_map[0]);
+ i++) {
+ if (krb5_data_cmp(name, &pac_buffer_name_map[i].name) == 0)
+ return krb5_pac_get_buffer(context, p, pac_buffer_name_map[i].type, data);
+ }
+
+ krb5_set_error_message(context, ENOENT, "No PAC buffer with name %.*s was found",
+ (int)name->length, (char *)name->data);
+ return ENOENT;
+}
+
+/*
+ *
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_pac_get_types(krb5_context context,
+ krb5_const_pac p,
+ size_t *len,
+ uint32_t **types)
+{
+ size_t i;
+
+ *types = calloc(p->pac->numbuffers, sizeof(**types));
+ if (*types == NULL) {
+ *len = 0;
+ return krb5_enomem(context);
+ }
+ for (i = 0; i < p->pac->numbuffers; i++)
+ (*types)[i] = p->pac->buffers[i].type;
+ *len = p->pac->numbuffers;
+
+ return 0;
+}
+
+/*
+ *
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_pac_free(krb5_context context, krb5_pac pac)
+{
+ heim_release(pac);
+}
+
+/*
+ *
+ */
+
+static krb5_error_code
+verify_checksum(krb5_context context,
+ const struct PAC_INFO_BUFFER *sig,
+ const krb5_data *data,
+ void *ptr, size_t len,
+ const krb5_keyblock *key,
+ krb5_boolean strict_cksumtype_match)
+{
+ krb5_storage *sp = NULL;
+ uint32_t type;
+ krb5_error_code ret;
+ Checksum cksum;
+ size_t cksumsize;
+
+ memset(&cksum, 0, sizeof(cksum));
+
+ sp = krb5_storage_from_mem((char *)data->data + sig->offset,
+ sig->buffersize);
+ if (sp == NULL)
+ return krb5_enomem(context);
+
+ krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
+
+ CHECK(ret, krb5_ret_uint32(sp, &type), out);
+ cksum.cksumtype = type;
+
+ ret = krb5_checksumsize(context, type, &cksumsize);
+ if (ret)
+ goto out;
+
+ /* Allow for RODCIdentifier trailer, see MS-PAC 2.8 */
+ if (cksumsize > (sig->buffersize - krb5_storage_seek(sp, 0, SEEK_CUR))) {
+ ret = EINVAL;
+ goto out;
+ }
+ cksum.checksum.length = cksumsize;
+ cksum.checksum.data = malloc(cksum.checksum.length);
+ if (cksum.checksum.data == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ ret = krb5_storage_read(sp, cksum.checksum.data, cksum.checksum.length);
+ if (ret != (int)cksum.checksum.length) {
+ ret = KRB5KRB_AP_ERR_INAPP_CKSUM;
+ krb5_set_error_message(context, ret, "PAC checksum missing checksum");
+ goto out;
+ }
+
+ if (!krb5_checksum_is_keyed(context, cksum.cksumtype)) {
+ ret = KRB5KRB_AP_ERR_INAPP_CKSUM;
+ krb5_set_error_message(context, ret, "Checksum type %d not keyed",
+ cksum.cksumtype);
+ goto out;
+ }
+
+ /* If the checksum is HMAC-MD5, the checksum type is not tied to
+ * the key type, instead the HMAC-MD5 checksum is applied blindly
+ * on whatever key is used for this connection, avoiding issues
+ * with unkeyed checksums on des-cbc-md5 and des-cbc-crc. See
+ * http://comments.gmane.org/gmane.comp.encryption.kerberos.devel/8743
+ * for the same issue in MIT, and
+ * http://blogs.msdn.com/b/openspecification/archive/2010/01/01/verifying-the-server-signature-in-kerberos-privilege-account-certificate.aspx
+ * for Microsoft's explaination */
+
+ if (cksum.cksumtype == CKSUMTYPE_HMAC_MD5 && !strict_cksumtype_match) {
+ Checksum local_checksum;
+
+ memset(&local_checksum, 0, sizeof(local_checksum));
+
+ ret = HMAC_MD5_any_checksum(context, key, ptr, len,
+ KRB5_KU_OTHER_CKSUM, &local_checksum);
+
+ if (ret != 0 || krb5_data_ct_cmp(&local_checksum.checksum, &cksum.checksum) != 0) {
+ ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
+ krb5_set_error_message(context, ret,
+ N_("PAC integrity check failed for "
+ "hmac-md5 checksum", ""));
+ }
+ krb5_data_free(&local_checksum.checksum);
+
+ } else {
+ krb5_crypto crypto = NULL;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ goto out;
+
+ ret = krb5_verify_checksum(context, crypto, KRB5_KU_OTHER_CKSUM,
+ ptr, len, &cksum);
+ krb5_crypto_destroy(context, crypto);
+ }
+ free(cksum.checksum.data);
+ krb5_storage_free(sp);
+
+ return ret;
+
+out:
+ if (cksum.checksum.data)
+ free(cksum.checksum.data);
+ if (sp)
+ krb5_storage_free(sp);
+ return ret;
+}
+
+static krb5_error_code
+create_checksum(krb5_context context,
+ const krb5_keyblock *key,
+ uint32_t cksumtype,
+ void *data, size_t datalen,
+ void *sig, size_t siglen)
+{
+ krb5_crypto crypto = NULL;
+ krb5_error_code ret;
+ Checksum cksum;
+
+ /* If the checksum is HMAC-MD5, the checksum type is not tied to
+ * the key type, instead the HMAC-MD5 checksum is applied blindly
+ * on whatever key is used for this connection, avoiding issues
+ * with unkeyed checksums on des-cbc-md5 and des-cbc-crc. See
+ * http://comments.gmane.org/gmane.comp.encryption.kerberos.devel/8743
+ * for the same issue in MIT, and
+ * http://blogs.msdn.com/b/openspecification/archive/2010/01/01/verifying-the-server-signature-in-kerberos-privilege-account-certificate.aspx
+ * for Microsoft's explaination */
+
+ if (cksumtype == (uint32_t)CKSUMTYPE_HMAC_MD5) {
+ ret = HMAC_MD5_any_checksum(context, key, data, datalen,
+ KRB5_KU_OTHER_CKSUM, &cksum);
+ if (ret)
+ return ret;
+ } else {
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ return ret;
+
+ ret = krb5_create_checksum(context, crypto, KRB5_KU_OTHER_CKSUM, 0,
+ data, datalen, &cksum);
+ krb5_crypto_destroy(context, crypto);
+ if (ret)
+ return ret;
+ }
+ if (cksum.checksum.length != siglen) {
+ krb5_set_error_message(context, EINVAL, "pac checksum wrong length");
+ free_Checksum(&cksum);
+ return EINVAL;
+ }
+
+ memcpy(sig, cksum.checksum.data, siglen);
+ free_Checksum(&cksum);
+
+ return 0;
+}
+
+static krb5_error_code
+parse_upn_dns_info(krb5_context context,
+ const struct PAC_INFO_BUFFER *upndnsinfo,
+ const krb5_data *data,
+ krb5_principal *upn_princ,
+ uint32_t *flags,
+ krb5_principal *canon_princ,
+ krb5_data *sid)
+{
+ krb5_error_code ret;
+ krb5_storage *sp = NULL;
+ uint16_t upn_length, upn_offset;
+ uint16_t dns_domain_name_length, dns_domain_name_offset;
+ uint16_t canon_princ_length, canon_princ_offset;
+ uint16_t sid_length, sid_offset;
+ char *upn = NULL;
+ char *dns_domain_name = NULL;
+ char *sam_name = NULL;
+
+ *upn_princ = NULL;
+ *flags = 0;
+ *canon_princ = NULL;
+ krb5_data_zero(sid);
+
+ sp = krb5_storage_from_readonly_mem((const char *)data->data + upndnsinfo->offset,
+ upndnsinfo->buffersize);
+ if (sp == NULL)
+ return krb5_enomem(context);
+
+ krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
+
+ CHECK(ret, krb5_ret_uint16(sp, &upn_length), out);
+ CHECK(ret, krb5_ret_uint16(sp, &upn_offset), out);
+ CHECK(ret, krb5_ret_uint16(sp, &dns_domain_name_length), out);
+ CHECK(ret, krb5_ret_uint16(sp, &dns_domain_name_offset), out);
+ CHECK(ret, krb5_ret_uint32(sp, flags), out);
+
+ if (*flags & PAC_EXTRA_LOGON_INFO_FLAGS_HAS_SAM_NAME_AND_SID) {
+ CHECK(ret, krb5_ret_uint16(sp, &canon_princ_length), out);
+ CHECK(ret, krb5_ret_uint16(sp, &canon_princ_offset), out);
+ CHECK(ret, krb5_ret_uint16(sp, &sid_length), out);
+ CHECK(ret, krb5_ret_uint16(sp, &sid_offset), out);
+ } else {
+ canon_princ_length = canon_princ_offset = 0;
+ sid_length = sid_offset = 0;
+ }
+
+ if (upn_offset) {
+ CHECK(ret, _krb5_ret_utf8_from_ucs2le_at_offset(sp, upn_offset,
+ upn_length, &upn), out);
+ }
+ CHECK(ret, _krb5_ret_utf8_from_ucs2le_at_offset(sp, dns_domain_name_offset,
+ dns_domain_name_length, &dns_domain_name), out);
+ if ((*flags & PAC_EXTRA_LOGON_INFO_FLAGS_HAS_SAM_NAME_AND_SID) && canon_princ_offset) {
+ CHECK(ret, _krb5_ret_utf8_from_ucs2le_at_offset(sp, canon_princ_offset,
+ canon_princ_length, &sam_name), out);
+ }
+
+ if (upn_offset) {
+ ret = krb5_parse_name_flags(context,
+ upn,
+ KRB5_PRINCIPAL_PARSE_ENTERPRISE |
+ KRB5_PRINCIPAL_PARSE_NO_DEF_REALM,
+ upn_princ);
+ if (ret)
+ goto out;
+
+ ret = krb5_principal_set_realm(context, *upn_princ, dns_domain_name);
+ if (ret)
+ goto out;
+ }
+
+ if (canon_princ_offset) {
+ ret = krb5_parse_name_flags(context,
+ sam_name,
+ KRB5_PRINCIPAL_PARSE_NO_REALM |
+ KRB5_PRINCIPAL_PARSE_NO_DEF_REALM,
+ canon_princ);
+ if (ret)
+ goto out;
+
+ ret = krb5_principal_set_realm(context, *canon_princ, dns_domain_name);
+ if (ret)
+ goto out;
+ }
+
+ if (sid_offset)
+ CHECK(ret, _krb5_ret_data_at_offset(sp, sid_offset, sid_length, sid), out);
+
+out:
+ free(upn);
+ free(dns_domain_name);
+ free(sam_name);
+
+ krb5_storage_free(sp);
+
+ return ret;
+}
+
+/*
+ *
+ */
+
+#define NTTIME_EPOCH 0x019DB1DED53E8000LL
+
+static uint64_t
+unix2nttime(time_t unix_time)
+{
+ long long wt;
+ wt = unix_time * (uint64_t)10000000 + (uint64_t)NTTIME_EPOCH;
+ return wt;
+}
+
+static krb5_error_code
+verify_logonname(krb5_context context,
+ const struct PAC_INFO_BUFFER *logon_name,
+ const krb5_data *data,
+ time_t authtime,
+ krb5_const_principal principal)
+{
+ krb5_error_code ret;
+ uint32_t time1, time2;
+ krb5_storage *sp = NULL;
+ uint16_t len;
+ char *s = NULL;
+ char *principal_string = NULL;
+ char *logon_string = NULL;
+
+ sp = krb5_storage_from_readonly_mem((const char *)data->data + logon_name->offset,
+ logon_name->buffersize);
+ if (sp == NULL)
+ return krb5_enomem(context);
+
+ krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
+
+ CHECK(ret, krb5_ret_uint32(sp, &time1), out);
+ CHECK(ret, krb5_ret_uint32(sp, &time2), out);
+
+ {
+ uint64_t t1, t2;
+ t1 = unix2nttime(authtime);
+ t2 = ((uint64_t)time2 << 32) | time1;
+ /*
+ * When neither the ticket nor the PAC set an explicit authtime,
+ * both times are zero, but relative to different time scales.
+ * So we must compare "not set" values without converting to a
+ * common time reference.
+ */
+ if (t1 != t2 && (t2 != 0 && authtime != 0)) {
+ krb5_storage_free(sp);
+ krb5_set_error_message(context, EINVAL, "PAC timestamp mismatch");
+ return EINVAL;
+ }
+ }
+ CHECK(ret, krb5_ret_uint16(sp, &len), out);
+ if (len == 0) {
+ krb5_storage_free(sp);
+ krb5_set_error_message(context, EINVAL, "PAC logon name length missing");
+ return EINVAL;
+ }
+
+ s = malloc(len);
+ if (s == NULL) {
+ krb5_storage_free(sp);
+ return krb5_enomem(context);
+ }
+ ret = krb5_storage_read(sp, s, len);
+ if (ret != len) {
+ krb5_storage_free(sp);
+ krb5_set_error_message(context, EINVAL, "Failed to read PAC logon name");
+ return EINVAL;
+ }
+ krb5_storage_free(sp);
+ {
+ size_t ucs2len = len / 2;
+ uint16_t *ucs2;
+ size_t u8len;
+ unsigned int flags = WIND_RW_LE;
+
+ ucs2 = malloc(sizeof(ucs2[0]) * ucs2len);
+ if (ucs2 == NULL)
+ return krb5_enomem(context);
+
+ ret = wind_ucs2read(s, len, &flags, ucs2, &ucs2len);
+ free(s);
+ if (ret) {
+ free(ucs2);
+ krb5_set_error_message(context, ret, "Failed to convert string to UCS-2");
+ return ret;
+ }
+ ret = wind_ucs2utf8_length(ucs2, ucs2len, &u8len);
+ if (ret) {
+ free(ucs2);
+ krb5_set_error_message(context, ret, "Failed to count length of UCS-2 string");
+ return ret;
+ }
+ u8len += 1; /* Add space for NUL */
+ logon_string = malloc(u8len);
+ if (logon_string == NULL) {
+ free(ucs2);
+ return krb5_enomem(context);
+ }
+ ret = wind_ucs2utf8(ucs2, ucs2len, logon_string, &u8len);
+ free(ucs2);
+ if (ret) {
+ free(logon_string);
+ krb5_set_error_message(context, ret, "Failed to convert to UTF-8");
+ return ret;
+ }
+ }
+ ret = krb5_unparse_name_flags(context, principal,
+ KRB5_PRINCIPAL_UNPARSE_NO_REALM |
+ KRB5_PRINCIPAL_UNPARSE_DISPLAY,
+ &principal_string);
+ if (ret) {
+ free(logon_string);
+ return ret;
+ }
+
+ if (strcmp(logon_string, principal_string) != 0) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret, "PAC logon name [%s] mismatch principal name [%s]",
+ logon_string, principal_string);
+ }
+ free(logon_string);
+ free(principal_string);
+ return ret;
+out:
+ krb5_storage_free(sp);
+ return ret;
+}
+
+/*
+ *
+ */
+
+static krb5_error_code
+build_logon_name(krb5_context context,
+ time_t authtime,
+ krb5_const_principal principal,
+ krb5_data *logon)
+{
+ krb5_error_code ret;
+ krb5_storage *sp;
+ uint64_t t;
+ char *s, *s2 = NULL;
+ size_t s2_len;
+
+ t = unix2nttime(authtime);
+
+ krb5_data_zero(logon);
+
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ return krb5_enomem(context);
+
+ krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
+
+ CHECK(ret, krb5_store_uint32(sp, t & 0xffffffff), out);
+ CHECK(ret, krb5_store_uint32(sp, t >> 32), out);
+
+ ret = krb5_unparse_name_flags(context, principal,
+ KRB5_PRINCIPAL_UNPARSE_NO_REALM |
+ KRB5_PRINCIPAL_UNPARSE_DISPLAY,
+ &s);
+ if (ret)
+ goto out;
+
+ {
+ size_t ucs2_len;
+ uint16_t *ucs2;
+ unsigned int flags;
+
+ ret = wind_utf8ucs2_length(s, &ucs2_len);
+ if (ret) {
+ krb5_set_error_message(context, ret, "Principal %s is not valid UTF-8", s);
+ free(s);
+ return ret;
+ }
+
+ ucs2 = malloc(sizeof(ucs2[0]) * ucs2_len);
+ if (ucs2 == NULL) {
+ free(s);
+ return krb5_enomem(context);
+ }
+
+ ret = wind_utf8ucs2(s, ucs2, &ucs2_len);
+ if (ret) {
+ free(ucs2);
+ krb5_set_error_message(context, ret, "Principal %s is not valid UTF-8", s);
+ free(s);
+ return ret;
+ } else
+ free(s);
+
+ s2_len = (ucs2_len + 1) * 2;
+ s2 = malloc(s2_len);
+ if (s2 == NULL) {
+ free(ucs2);
+ return krb5_enomem(context);
+ }
+
+ flags = WIND_RW_LE;
+ ret = wind_ucs2write(ucs2, ucs2_len,
+ &flags, s2, &s2_len);
+ free(ucs2);
+ if (ret) {
+ free(s2);
+ krb5_set_error_message(context, ret, "Failed to write to UCS-2 buffer");
+ return ret;
+ }
+
+ /*
+ * we do not want zero termination
+ */
+ s2_len = ucs2_len * 2;
+ }
+
+ CHECK(ret, krb5_store_uint16(sp, s2_len), out);
+
+ ret = krb5_storage_write(sp, s2, s2_len);
+ if (ret != (int)s2_len) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ ret = krb5_storage_to_data(sp, logon);
+
+ out:
+ free(s2);
+ krb5_storage_free(sp);
+ return ret;
+}
+
+static krb5_error_code
+parse_attributes_info(krb5_context context,
+ const struct PAC_INFO_BUFFER *attributes_info,
+ const krb5_data *data,
+ uint64_t *pac_attributes)
+{
+ krb5_error_code ret;
+ krb5_storage *sp = NULL;
+ uint32_t flags_length;
+
+ *pac_attributes = 0;
+
+ sp = krb5_storage_from_readonly_mem((const char *)data->data + attributes_info->offset,
+ attributes_info->buffersize);
+ if (sp == NULL)
+ return krb5_enomem(context);
+
+ krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
+
+ ret = krb5_ret_uint32(sp, &flags_length);
+ if (ret == 0) {
+ if (flags_length > 32)
+ ret = krb5_ret_uint64(sp, pac_attributes);
+ else {
+ uint32_t pac_attributes32 = 0;
+ ret = krb5_ret_uint32(sp, &pac_attributes32);
+ *pac_attributes = pac_attributes32;
+ }
+ }
+
+ krb5_storage_free(sp);
+
+ return ret;
+}
+
+/**
+ * Verify the PAC.
+ *
+ * @param context Kerberos 5 context.
+ * @param pac the pac structure returned by krb5_pac_parse().
+ * @param authtime The time of the ticket the PAC belongs to.
+ * @param principal the principal to verify.
+ * @param server The service key, may be given.
+ * @param privsvr The KDC key, may be given.
+
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5_pac
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_pac_verify(krb5_context context,
+ const krb5_pac pac,
+ time_t authtime,
+ krb5_const_principal principal,
+ const krb5_keyblock *server,
+ const krb5_keyblock *privsvr)
+{
+ krb5_error_code ret;
+ /*
+ * If we are in the KDC, we expect back a full signature in the PAC
+ *
+ * This is set up as a seperate variable to make it easier if a
+ * subsequent patch is added to make this configurable in the
+ * krb5.conf (or forced into the krb5_context via Samba)
+ */
+ krb5_boolean expect_full_sig = privsvr != NULL;
+
+ /*
+ * If we are on the KDC, then we trust we are not in a realm with
+ * buggy Windows 2008 or similar era DCs that give our HMAC-MD5
+ * sigatures over AES keys. DES is also already gone.
+ */
+ krb5_boolean strict_cksumtype_match = expect_full_sig;
+
+ if (pac->server_checksum == NULL) {
+ krb5_set_error_message(context, EINVAL, "PAC missing server checksum");
+ return EINVAL;
+ }
+ if (pac->privsvr_checksum == NULL) {
+ krb5_set_error_message(context, EINVAL, "PAC missing kdc checksum");
+ return EINVAL;
+ }
+ if (pac->logon_name == NULL) {
+ krb5_set_error_message(context, EINVAL, "PAC missing logon name");
+ return EINVAL;
+ }
+ if (expect_full_sig && pac->full_checksum == NULL) {
+ krb5_set_error_message(context, EINVAL, "PAC missing full checksum");
+ return EINVAL;
+ }
+
+ if (principal != NULL) {
+ ret = verify_logonname(context, pac->logon_name, &pac->data, authtime,
+ principal);
+ if (ret)
+ return ret;
+ }
+
+ if (pac->server_checksum->buffersize < 4 ||
+ pac->privsvr_checksum->buffersize < 4)
+ return EINVAL;
+
+ if (server != NULL || privsvr != NULL)
+ {
+ krb5_data *copy;
+
+ /*
+ * in the service case, clean out data option of the privsvr and
+ * server checksum before checking the checksum.
+ */
+
+ ret = krb5_copy_data(context, &pac->data, &copy);
+ if (ret)
+ return ret;
+
+ memset((char *)copy->data + pac->server_checksum->offset + 4,
+ 0,
+ pac->server_checksum->buffersize - 4);
+
+ memset((char *)copy->data + pac->privsvr_checksum->offset + 4,
+ 0,
+ pac->privsvr_checksum->buffersize - 4);
+
+ if (server != NULL) {
+ ret = verify_checksum(context,
+ pac->server_checksum,
+ &pac->data,
+ copy->data,
+ copy->length,
+ server,
+ strict_cksumtype_match);
+ if (ret) {
+ krb5_free_data(context, copy);
+ return ret;
+ }
+ }
+
+ if (privsvr != NULL && pac->full_checksum != NULL) {
+ /*
+ * in the full checksum case, also clean out the full
+ * checksum before verifying it.
+ */
+ memset((char *)copy->data + pac->full_checksum->offset + 4,
+ 0,
+ pac->full_checksum->buffersize - 4);
+
+ ret = verify_checksum(context,
+ pac->full_checksum,
+ &pac->data,
+ copy->data,
+ copy->length,
+ privsvr,
+ strict_cksumtype_match);
+ if (ret) {
+ krb5_free_data(context, copy);
+ return ret;
+ }
+ }
+
+ krb5_free_data(context, copy);
+ }
+ if (privsvr) {
+ /* The priv checksum covers the server checksum */
+ ret = verify_checksum(context,
+ pac->privsvr_checksum,
+ &pac->data,
+ (char *)pac->data.data
+ + pac->server_checksum->offset + 4,
+ pac->server_checksum->buffersize - 4,
+ privsvr,
+ strict_cksumtype_match);
+ if (ret)
+ return ret;
+
+ if (pac->ticket_sign_data.length != 0) {
+ if (pac->ticket_checksum == NULL) {
+ krb5_set_error_message(context, EINVAL,
+ "PAC missing ticket checksum");
+ return EINVAL;
+ }
+
+ ret = verify_checksum(context, pac->ticket_checksum, &pac->data,
+ pac->ticket_sign_data.data,
+ pac->ticket_sign_data.length, privsvr,
+ strict_cksumtype_match);
+ if (ret)
+ return ret;
+ }
+ }
+
+ if (pac->upn_dns_info &&
+ pac->upn_princ == NULL && pac->canon_princ == NULL && pac->sid.data == NULL) {
+ ret = parse_upn_dns_info(context, pac->upn_dns_info, &pac->data,
+ &pac->upn_princ, &pac->upn_flags,
+ &pac->canon_princ, &pac->sid);
+ if (ret)
+ return ret;
+ }
+
+ if (pac->attributes_info) {
+ ret = parse_attributes_info(context, pac->attributes_info, &pac->data,
+ &pac->pac_attributes);
+ if (ret)
+ return ret;
+ }
+
+ return 0;
+}
+
+/*
+ *
+ */
+
+static krb5_error_code
+fill_zeros(krb5_context context, krb5_storage *sp, size_t len)
+{
+ ssize_t sret;
+ size_t l;
+
+ while (len) {
+ l = len;
+ if (l > sizeof(zeros))
+ l = sizeof(zeros);
+ sret = krb5_storage_write(sp, zeros, l);
+ if (sret != l)
+ return krb5_enomem(context);
+
+ len -= sret;
+ }
+ return 0;
+}
+
+static krb5_error_code
+pac_checksum(krb5_context context,
+ const krb5_keyblock *key,
+ uint32_t *cksumtype,
+ size_t *cksumsize)
+{
+ krb5_cksumtype cktype;
+ krb5_error_code ret;
+ krb5_crypto crypto = NULL;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ return ret;
+
+ ret = krb5_crypto_get_checksum_type(context, crypto, &cktype);
+ krb5_crypto_destroy(context, crypto);
+ if (ret)
+ return ret;
+
+ if (krb5_checksum_is_keyed(context, cktype) == FALSE) {
+ *cksumtype = CKSUMTYPE_HMAC_MD5;
+ *cksumsize = 16;
+ }
+
+ ret = krb5_checksumsize(context, cktype, cksumsize);
+ if (ret)
+ return ret;
+
+ *cksumtype = (uint32_t)cktype;
+
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_pac_sign(krb5_context context,
+ krb5_pac p,
+ time_t authtime,
+ krb5_const_principal principal,
+ const krb5_keyblock *server_key,
+ const krb5_keyblock *priv_key,
+ uint16_t rodc_id,
+ krb5_const_principal upn_princ,
+ krb5_const_principal canon_princ,
+ krb5_boolean add_full_sig,
+ uint64_t *pac_attributes, /* optional */
+ krb5_data *data)
+{
+ krb5_error_code ret;
+ krb5_storage *sp = NULL, *spdata = NULL;
+ uint32_t end;
+ size_t server_size, priv_size;
+ uint32_t server_offset = 0, priv_offset = 0, ticket_offset = 0, full_offset = 0;
+ uint32_t server_cksumtype = 0, priv_cksumtype = 0;
+ uint32_t num = 0;
+ uint32_t i, sz;
+ krb5_data logon, d;
+
+ krb5_data_zero(&d);
+ krb5_data_zero(&logon);
+
+ /*
+ * Set convenience buffer pointers.
+ *
+ * This could really stand to be moved to krb5_pac_add_buffer() and/or
+ * utility function, so that when this function gets called they must
+ * already have been set.
+ */
+ for (i = 0; i < p->pac->numbuffers; i++) {
+ if (p->pac->buffers[i].type == PAC_SERVER_CHECKSUM) {
+ if (p->server_checksum == NULL) {
+ p->server_checksum = &p->pac->buffers[i];
+ }
+ if (p->server_checksum != &p->pac->buffers[i]) {
+ ret = KRB5KDC_ERR_BADOPTION;
+ krb5_set_error_message(context, ret,
+ N_("PAC has multiple server checksums", ""));
+ goto out;
+ }
+ } else if (p->pac->buffers[i].type == PAC_PRIVSVR_CHECKSUM) {
+ if (p->privsvr_checksum == NULL) {
+ p->privsvr_checksum = &p->pac->buffers[i];
+ }
+ if (p->privsvr_checksum != &p->pac->buffers[i]) {
+ ret = KRB5KDC_ERR_BADOPTION;
+ krb5_set_error_message(context, ret,
+ N_("PAC has multiple KDC checksums", ""));
+ goto out;
+ }
+ } else if (p->pac->buffers[i].type == PAC_LOGON_NAME) {
+ if (p->logon_name == NULL) {
+ p->logon_name = &p->pac->buffers[i];
+ }
+ if (p->logon_name != &p->pac->buffers[i]) {
+ ret = KRB5KDC_ERR_BADOPTION;
+ krb5_set_error_message(context, ret,
+ N_("PAC has multiple logon names", ""));
+ goto out;
+ }
+ } else if (p->pac->buffers[i].type == PAC_UPN_DNS_INFO) {
+ if (p->upn_dns_info == NULL) {
+ p->upn_dns_info = &p->pac->buffers[i];
+ }
+ if (p->upn_dns_info != &p->pac->buffers[i]) {
+ ret = KRB5KDC_ERR_BADOPTION;
+ krb5_set_error_message(context, ret,
+ N_("PAC has multiple UPN DNS info buffers", ""));
+ goto out;
+ }
+ } else if (p->pac->buffers[i].type == PAC_TICKET_CHECKSUM) {
+ if (p->ticket_checksum == NULL) {
+ p->ticket_checksum = &p->pac->buffers[i];
+ }
+ if (p->ticket_checksum != &p->pac->buffers[i]) {
+ ret = KRB5KDC_ERR_BADOPTION;
+ krb5_set_error_message(context, ret,
+ N_("PAC has multiple ticket checksums", ""));
+ goto out;
+ }
+ } else if (p->pac->buffers[i].type == PAC_ATTRIBUTES_INFO) {
+ if (p->attributes_info == NULL) {
+ p->attributes_info = &p->pac->buffers[i];
+ }
+ if (p->attributes_info != &p->pac->buffers[i]) {
+ ret = KRB5KDC_ERR_BADOPTION;
+ krb5_set_error_message(context, ret,
+ N_("PAC has multiple attributes info buffers", ""));
+ goto out;
+ }
+ } else if (p->pac->buffers[i].type == PAC_FULL_CHECKSUM) {
+ if (p->full_checksum == NULL) {
+ p->full_checksum = &p->pac->buffers[i];
+ }
+ if (p->full_checksum != &p->pac->buffers[i]) {
+ ret = KRB5KDC_ERR_BADOPTION;
+ krb5_set_error_message(context, ret,
+ N_("PAC has multiple full checksums", ""));
+ goto out;
+ }
+ }
+ }
+
+ /* Count missing-but-necessary buffers */
+ if (p->logon_name == NULL)
+ num++;
+ if (p->server_checksum == NULL)
+ num++;
+ if (p->privsvr_checksum == NULL)
+ num++;
+ if (p->ticket_sign_data.length != 0 && p->ticket_checksum == NULL)
+ num++;
+ if (add_full_sig && p->full_checksum == NULL)
+ num++;
+
+ /* Allocate any missing-but-necessary buffers */
+ if (num) {
+ void *ptr;
+ uint32_t old_len, len;
+
+ if (p->pac->numbuffers > UINT32_MAX - num) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret, "integer overrun");
+ goto out;
+ }
+ ret = pac_header_size(context, p->pac->numbuffers, &old_len);
+ if (ret == 0)
+ ret = pac_header_size(context, p->pac->numbuffers + num, &len);
+ if (ret)
+ goto out;
+
+ ptr = realloc(p->pac, len);
+ if (ptr == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ memset((char *)ptr + old_len, 0, len - old_len);
+ p->pac = ptr;
+
+
+ if (p->logon_name == NULL) {
+ p->logon_name = &p->pac->buffers[p->pac->numbuffers++];
+ p->logon_name->type = PAC_LOGON_NAME;
+ }
+ if (p->server_checksum == NULL) {
+ p->server_checksum = &p->pac->buffers[p->pac->numbuffers++];
+ p->server_checksum->type = PAC_SERVER_CHECKSUM;
+ }
+ if (p->privsvr_checksum == NULL) {
+ p->privsvr_checksum = &p->pac->buffers[p->pac->numbuffers++];
+ p->privsvr_checksum->type = PAC_PRIVSVR_CHECKSUM;
+ }
+ if (p->ticket_sign_data.length != 0 && p->ticket_checksum == NULL) {
+ p->ticket_checksum = &p->pac->buffers[p->pac->numbuffers++];
+ p->ticket_checksum->type = PAC_TICKET_CHECKSUM;
+ }
+ if (add_full_sig && p->full_checksum == NULL) {
+ p->full_checksum = &p->pac->buffers[p->pac->numbuffers++];
+ memset(p->full_checksum, 0, sizeof(*p->full_checksum));
+ p->full_checksum->type = PAC_FULL_CHECKSUM;
+ }
+ }
+
+ /* Calculate LOGON NAME */
+ ret = build_logon_name(context, authtime, principal, &logon);
+
+ /* Set lengths for checksum */
+ if (ret == 0)
+ ret = pac_checksum(context, server_key, &server_cksumtype, &server_size);
+
+ if (ret == 0)
+ ret = pac_checksum(context, priv_key, &priv_cksumtype, &priv_size);
+
+ /* Encode PAC */
+ if (ret == 0) {
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ ret = krb5_enomem(context);
+ }
+
+ if (ret == 0) {
+ krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
+ spdata = krb5_storage_emem();
+ if (spdata == NULL)
+ ret = krb5_enomem(context);
+ }
+
+ if (ret)
+ goto out;
+
+ krb5_storage_set_flags(spdata, KRB5_STORAGE_BYTEORDER_LE);
+
+ /* `sp' has the header, `spdata' has the buffers */
+ CHECK(ret, krb5_store_uint32(sp, p->pac->numbuffers), out);
+ CHECK(ret, krb5_store_uint32(sp, p->pac->version), out);
+
+ ret = pac_header_size(context, p->pac->numbuffers, &end);
+ if (ret)
+ goto out;
+
+ /*
+ * For each buffer we write its contents to `spdata' and then append the
+ * PAC_INFO_BUFFER for that buffer into the header in `sp'. The logical
+ * end of the whole thing is kept in `end', which functions as the offset
+ * to write in the buffer's PAC_INFO_BUFFER, then we update it at the
+ * bottom so that the next buffer can be written there.
+ *
+ * TODO? Maybe rewrite all of this so that:
+ *
+ * - we use krb5_pac_add_buffer() to add the buffers we produce
+ * - we use the krb5_data of the concatenated buffers that's maintained by
+ * krb5_pac_add_buffer() so we don't need `spdata' here
+ *
+ * We do way too much here, and that makes this code hard to read. Plus we
+ * throw away all the work done in krb5_pac_add_buffer(). On the other
+ * hand, krb5_pac_add_buffer() has to loop over all the buffers, so if we
+ * call krb5_pac_add_buffer() here in a loop, we'll be accidentally
+ * quadratic, but we only need to loop over adding the buffers we add,
+ * which is very few, so not quite quadratic. We should also cap the
+ * number of buffers we're willing to accept in a PAC we parse to something
+ * reasonable, like a few tens.
+ */
+ for (i = 0; i < p->pac->numbuffers; i++) {
+ uint32_t len;
+ size_t sret;
+ void *ptr = NULL;
+
+ /* store data */
+
+ if (p->pac->buffers[i].type == PAC_SERVER_CHECKSUM) {
+ if (server_size > UINT32_MAX - 4) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret, "integer overrun");
+ goto out;
+ }
+ len = server_size + 4;
+ if (end > UINT32_MAX - 4) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret, "integer overrun");
+ goto out;
+ }
+ server_offset = end + 4;
+ CHECK(ret, krb5_store_uint32(spdata, server_cksumtype), out);
+ CHECK(ret, fill_zeros(context, spdata, server_size), out);
+ } else if (p->pac->buffers[i].type == PAC_PRIVSVR_CHECKSUM) {
+ if (priv_size > UINT32_MAX - 4) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret, "integer overrun");
+ goto out;
+ }
+ len = priv_size + 4;
+ if (end > UINT32_MAX - 4) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret, "integer overrun");
+ goto out;
+ }
+ priv_offset = end + 4;
+ CHECK(ret, krb5_store_uint32(spdata, priv_cksumtype), out);
+ CHECK(ret, fill_zeros(context, spdata, priv_size), out);
+ if (rodc_id != 0) {
+ if (len > UINT32_MAX - sizeof(rodc_id)) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret, "integer overrun");
+ goto out;
+ }
+ len += sizeof(rodc_id);
+ CHECK(ret, fill_zeros(context, spdata, sizeof(rodc_id)), out);
+ }
+ } else if (p->ticket_sign_data.length != 0 &&
+ p->pac->buffers[i].type == PAC_TICKET_CHECKSUM) {
+ if (priv_size > UINT32_MAX - 4) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret, "integer overrun");
+ goto out;
+ }
+ len = priv_size + 4;
+ if (end > UINT32_MAX - 4) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret, "integer overrun");
+ goto out;
+ }
+ ticket_offset = end + 4;
+ CHECK(ret, krb5_store_uint32(spdata, priv_cksumtype), out);
+ CHECK(ret, fill_zeros(context, spdata, priv_size), out);
+ if (rodc_id != 0) {
+ if (len > UINT32_MAX - sizeof(rodc_id)) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret, "integer overrun");
+ goto out;
+ }
+ len += sizeof(rodc_id);
+ CHECK(ret, krb5_store_uint16(spdata, rodc_id), out);
+ }
+ } else if (add_full_sig &&
+ p->pac->buffers[i].type == PAC_FULL_CHECKSUM) {
+ if (priv_size > UINT32_MAX - 4) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret, "integer overrun");
+ goto out;
+ }
+ len = priv_size + 4;
+ if (end > UINT32_MAX - 4) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret, "integer overrun");
+ goto out;
+ }
+ full_offset = end + 4;
+ CHECK(ret, krb5_store_uint32(spdata, priv_cksumtype), out);
+ CHECK(ret, fill_zeros(context, spdata, priv_size), out);
+ if (rodc_id != 0) {
+ if (len > UINT32_MAX - sizeof(rodc_id)) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret, "integer overrun");
+ goto out;
+ }
+ len += sizeof(rodc_id);
+ CHECK(ret, fill_zeros(context, spdata, sizeof(rodc_id)), out);
+ }
+ } else if (p->pac->buffers[i].type == PAC_LOGON_NAME) {
+ len = krb5_storage_write(spdata, logon.data, logon.length);
+ if (logon.length != len) {
+ ret = KRB5KDC_ERR_BADOPTION;
+ goto out;
+ }
+ } else {
+ len = p->pac->buffers[i].buffersize;
+ ptr = (char *)p->data.data + p->pac->buffers[i].offset;
+
+ sret = krb5_storage_write(spdata, ptr, len);
+ if (sret != len) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ /* XXX if not aligned, fill_zeros */
+ }
+
+ /* write header */
+ CHECK(ret, krb5_store_uint32(sp, p->pac->buffers[i].type), out);
+ CHECK(ret, krb5_store_uint32(sp, len), out);
+ CHECK(ret, krb5_store_uint64(sp, end), out); /* offset */
+
+ /* advance data endpointer and align */
+ {
+ uint32_t e;
+
+ ret = pac_aligned_size(context, end, len, &e);
+ if (ret == 0 && end + len != e)
+ ret = fill_zeros(context, spdata, e - (end + len));
+ if (ret)
+ goto out;
+ end = e;
+ }
+
+ }
+
+ /* assert (server_offset != 0 && priv_offset != 0); */
+
+ /* export PAC */
+ if (ret == 0)
+ ret = krb5_storage_to_data(spdata, &d);
+ if (ret == 0) {
+ sz = krb5_storage_write(sp, d.data, d.length);
+ if (sz != d.length) {
+ krb5_data_free(&d);
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ }
+ krb5_data_free(&d);
+
+ if (ret == 0)
+ ret = krb5_storage_to_data(sp, &d);
+
+ /* sign */
+ if (ret == 0 && p->ticket_sign_data.length)
+ ret = create_checksum(context, priv_key, priv_cksumtype,
+ p->ticket_sign_data.data,
+ p->ticket_sign_data.length,
+ (char *)d.data + ticket_offset, priv_size);
+ if (ret == 0 && add_full_sig)
+ ret = create_checksum(context, priv_key, priv_cksumtype,
+ d.data, d.length,
+ (char *)d.data + full_offset, priv_size);
+ if (ret == 0 && add_full_sig && rodc_id != 0) {
+ void *buf = (char *)d.data + full_offset + priv_size;
+ krb5_storage *rs = krb5_storage_from_mem(buf, sizeof(rodc_id));
+ if (rs == NULL)
+ ret = krb5_enomem(context);
+ else
+ krb5_storage_set_flags(rs, KRB5_STORAGE_BYTEORDER_LE);
+ if (ret == 0)
+ ret = krb5_store_uint16(rs, rodc_id);
+ krb5_storage_free(rs);
+ }
+ if (ret == 0)
+ ret = create_checksum(context, server_key, server_cksumtype,
+ d.data, d.length,
+ (char *)d.data + server_offset, server_size);
+ if (ret == 0)
+ ret = create_checksum(context, priv_key, priv_cksumtype,
+ (char *)d.data + server_offset, server_size,
+ (char *)d.data + priv_offset, priv_size);
+ if (ret == 0 && rodc_id != 0) {
+ void *buf = (char *)d.data + priv_offset + priv_size;
+ krb5_storage *rs = krb5_storage_from_mem(buf, sizeof(rodc_id));
+ if (rs == NULL)
+ ret = krb5_enomem(context);
+ else
+ krb5_storage_set_flags(rs, KRB5_STORAGE_BYTEORDER_LE);
+ if (ret == 0)
+ ret = krb5_store_uint16(rs, rodc_id);
+ krb5_storage_free(rs);
+ }
+
+ if (ret)
+ goto out;
+
+ /* done */
+ *data = d;
+
+ krb5_data_free(&logon);
+ krb5_storage_free(sp);
+ krb5_storage_free(spdata);
+
+ return 0;
+out:
+ krb5_data_free(&d);
+ krb5_data_free(&logon);
+ if (sp)
+ krb5_storage_free(sp);
+ if (spdata)
+ krb5_storage_free(spdata);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_pac_get_kdc_checksum_info(krb5_context context,
+ krb5_const_pac pac,
+ krb5_cksumtype *cstype,
+ uint16_t *rodc_id)
+{
+ krb5_error_code ret;
+ krb5_storage *sp = NULL;
+ const struct PAC_INFO_BUFFER *sig;
+ size_t cksumsize, prefix;
+ uint32_t type = 0;
+
+ *cstype = 0;
+ *rodc_id = 0;
+
+ sig = pac->privsvr_checksum;
+ if (sig == NULL) {
+ krb5_set_error_message(context, KRB5KDC_ERR_BADOPTION,
+ "PAC missing kdc checksum");
+ return KRB5KDC_ERR_BADOPTION;
+ }
+
+ sp = krb5_storage_from_mem((char *)pac->data.data + sig->offset,
+ sig->buffersize);
+ if (sp == NULL)
+ return krb5_enomem(context);
+
+ krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
+
+ ret = krb5_ret_uint32(sp, &type);
+ if (ret)
+ goto out;
+
+ ret = krb5_checksumsize(context, type, &cksumsize);
+ if (ret)
+ goto out;
+
+ prefix = krb5_storage_seek(sp, 0, SEEK_CUR);
+
+ if ((sig->buffersize - prefix) >= cksumsize + 2) {
+ krb5_storage_seek(sp, cksumsize, SEEK_CUR);
+ ret = krb5_ret_uint16(sp, rodc_id);
+ if (ret)
+ goto out;
+ }
+
+ *cstype = type;
+
+out:
+ krb5_storage_free(sp);
+
+ return ret;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_pac_get_canon_principal(krb5_context context,
+ krb5_const_pac pac,
+ krb5_principal *canon_princ)
+{
+ *canon_princ = NULL;
+
+ if (pac->canon_princ == NULL) {
+ krb5_set_error_message(context, ENOENT,
+ "PAC missing UPN DNS info buffer");
+ return ENOENT;
+ }
+
+ return krb5_copy_principal(context, pac->canon_princ, canon_princ);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_pac_get_attributes_info(krb5_context context,
+ krb5_const_pac pac,
+ uint64_t *pac_attributes)
+{
+ *pac_attributes = 0;
+
+ if (pac->attributes_info == NULL) {
+ krb5_set_error_message(context, ENOENT,
+ "PAC missing attributes info buffer");
+ return ENOENT;
+ }
+
+ *pac_attributes = pac->pac_attributes;
+
+ return 0;
+}
+
+static unsigned char single_zero = '\0';
+static krb5_data single_zero_pac = { 1, &single_zero };
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_kdc_pac_ticket_parse(krb5_context context,
+ EncTicketPart *tkt,
+ krb5_boolean *signedticket,
+ krb5_pac *ppac)
+{
+ AuthorizationData *ad = tkt->authorization_data;
+ krb5_pac pac = NULL;
+ unsigned i, j;
+ size_t len = 0;
+ krb5_error_code ret = 0;
+
+ *signedticket = FALSE;
+ *ppac = NULL;
+
+ if (ad == NULL || ad->len == 0)
+ return 0;
+
+ for (i = 0; i < ad->len; i++) {
+ AuthorizationData child;
+
+ if (ad->val[i].ad_type == KRB5_AUTHDATA_WIN2K_PAC) {
+ ret = KRB5KDC_ERR_BADOPTION;
+ goto out;
+ }
+
+ if (ad->val[i].ad_type != KRB5_AUTHDATA_IF_RELEVANT)
+ continue;
+
+ ret = decode_AuthorizationData(ad->val[i].ad_data.data,
+ ad->val[i].ad_data.length,
+ &child,
+ NULL);
+ if (ret) {
+ krb5_set_error_message(context, ret, "Failed to decode "
+ "AD-IF-RELEVANT with %d", ret);
+ goto out;
+ }
+
+ for (j = 0; j < child.len; j++) {
+ krb5_data adifr_data = ad->val[i].ad_data;
+ krb5_data pac_data = child.val[j].ad_data;
+ krb5_data recoded_adifr;
+
+ if (child.val[j].ad_type != KRB5_AUTHDATA_WIN2K_PAC)
+ continue;
+
+ if (pac != NULL) {
+ free_AuthorizationData(&child);
+ ret = KRB5KDC_ERR_BADOPTION;
+ goto out;
+ }
+
+ ret = krb5_pac_parse(context,
+ pac_data.data,
+ pac_data.length,
+ &pac);
+ if (ret) {
+ free_AuthorizationData(&child);
+ goto out;
+ }
+
+ if (pac->ticket_checksum == NULL)
+ continue;
+
+ /*
+ * Encode the ticket with the PAC replaced with a single zero
+ * byte, to be used as input data to the ticket signature.
+ */
+
+ child.val[j].ad_data = single_zero_pac;
+
+ ASN1_MALLOC_ENCODE(AuthorizationData, recoded_adifr.data,
+ recoded_adifr.length, &child, &len, ret);
+ if (recoded_adifr.length != len)
+ krb5_abortx(context, "Internal error in ASN.1 encoder");
+
+ child.val[j].ad_data = pac_data;
+
+ if (ret) {
+ free_AuthorizationData(&child);
+ goto out;
+ }
+
+ ad->val[i].ad_data = recoded_adifr;
+
+ ASN1_MALLOC_ENCODE(EncTicketPart,
+ pac->ticket_sign_data.data,
+ pac->ticket_sign_data.length, tkt, &len,
+ ret);
+ if (pac->ticket_sign_data.length != len)
+ krb5_abortx(context, "Internal error in ASN.1 encoder");
+
+ ad->val[i].ad_data = adifr_data;
+ krb5_data_free(&recoded_adifr);
+
+ if (ret) {
+ free_AuthorizationData(&child);
+ goto out;
+ }
+
+ *signedticket = TRUE;
+ }
+ free_AuthorizationData(&child);
+ }
+
+out:
+ if (ret) {
+ krb5_pac_free(context, pac);
+ return ret;
+ }
+
+ *ppac = pac;
+
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_kdc_pac_sign_ticket(krb5_context context,
+ const krb5_pac pac,
+ krb5_const_principal client,
+ const krb5_keyblock *server_key,
+ const krb5_keyblock *kdc_key,
+ uint16_t rodc_id,
+ krb5_const_principal upn,
+ krb5_const_principal canon_name,
+ krb5_boolean add_ticket_sig,
+ krb5_boolean add_full_sig,
+ EncTicketPart *tkt,
+ uint64_t *pac_attributes) /* optional */
+{
+ krb5_error_code ret;
+ krb5_data tkt_data;
+ krb5_data rspac;
+
+ krb5_data_zero(&rspac);
+ krb5_data_zero(&tkt_data);
+
+ krb5_data_free(&pac->ticket_sign_data);
+
+ if (add_ticket_sig) {
+ size_t len = 0;
+
+ ret = _kdc_tkt_insert_pac(context, tkt, &single_zero_pac);
+ if (ret)
+ return ret;
+
+ ASN1_MALLOC_ENCODE(EncTicketPart, tkt_data.data, tkt_data.length,
+ tkt, &len, ret);
+ if(tkt_data.length != len)
+ krb5_abortx(context, "Internal error in ASN.1 encoder");
+ if (ret)
+ return ret;
+
+ ret = remove_AuthorizationData(tkt->authorization_data, 0);
+ if (ret) {
+ krb5_data_free(&tkt_data);
+ return ret;
+ }
+
+ pac->ticket_sign_data = tkt_data;
+ }
+
+ ret = _krb5_pac_sign(context, pac, tkt->authtime, client, server_key,
+ kdc_key, rodc_id, upn, canon_name,
+ add_full_sig,
+ pac_attributes, &rspac);
+ if (ret == 0)
+ ret = _kdc_tkt_insert_pac(context, tkt, &rspac);
+ krb5_data_free(&rspac);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/padata.c b/third_party/heimdal/lib/krb5/padata.c
new file mode 100644
index 0000000..71c9a7f
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/padata.c
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION PA_DATA * KRB5_LIB_CALL
+krb5_find_padata(PA_DATA *val, unsigned len, int type, int *idx)
+{
+ for(; *idx < (int)len; (*idx)++)
+ if(val[*idx].padata_type == (unsigned)type)
+ return val + *idx;
+ return NULL;
+}
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_padata_add(krb5_context context, METHOD_DATA *md,
+ int type, void *buf, size_t len)
+{
+ PA_DATA *pa;
+
+ pa = realloc (md->val, (md->len + 1) * sizeof(*md->val));
+ if (pa == NULL)
+ return krb5_enomem(context);
+ md->val = pa;
+
+ pa[md->len].padata_type = type;
+ pa[md->len].padata_value.length = len;
+ pa[md->len].padata_value.data = buf;
+ md->len++;
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/parse-name-test.c b/third_party/heimdal/lib/krb5/parse-name-test.c
new file mode 100644
index 0000000..bb2fc02
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/parse-name-test.c
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+
+enum { MAX_COMPONENTS = 3 };
+
+static struct testcase {
+ const char *input_string;
+ const char *output_string;
+ krb5_realm realm;
+ unsigned ncomponents;
+ char *comp_val[MAX_COMPONENTS];
+ int realmp;
+} tests[] = {
+ {"", "@", "", 1, {""}, FALSE},
+ {"a", "a@", "", 1, {"a"}, FALSE},
+ {"\\n", "\\n@", "", 1, {"\n"}, FALSE},
+ {"\\ ", "\\ @", "", 1, {" "}, FALSE},
+ {"\\t", "\\t@", "", 1, {"\t"}, FALSE},
+ {"\\b", "\\b@", "", 1, {"\b"}, FALSE},
+ {"\\\\", "\\\\@", "", 1, {"\\"}, FALSE},
+ {"\\/", "\\/@", "", 1, {"/"}, FALSE},
+ {"\\@", "\\@@", "", 1, {"@"}, FALSE},
+ {"@", "@", "", 1, {""}, TRUE},
+ {"a/b", "a/b@", "", 2, {"a", "b"}, FALSE},
+ {"a/", "a/@", "", 2, {"a", ""}, FALSE},
+ {"a\\//\\/", "a\\//\\/@", "", 2, {"a/", "/"}, FALSE},
+ {"/a", "/a@", "", 2, {"", "a"}, FALSE},
+ {"\\@@\\@", "\\@@\\@", "@", 1, {"@"}, TRUE},
+ {"a/b/c", "a/b/c@", "", 3, {"a", "b", "c"}, FALSE},
+ {NULL, NULL, "", 0, { NULL }, FALSE}};
+
+int
+main(int argc, char **argv)
+{
+ struct testcase *t;
+ krb5_context context;
+ krb5_error_code ret;
+ int val = 0;
+
+ ret = krb5_init_context (&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ /* to enable realm-less principal name above */
+
+ krb5_set_default_realm(context, "");
+
+ for (t = tests; t->input_string; ++t) {
+ krb5_principal princ;
+ int i, j;
+ char name_buf[1024];
+ char *s;
+
+ ret = krb5_parse_name(context, t->input_string, &princ);
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_parse_name %s",
+ t->input_string);
+ if (strcmp (t->realm, princ->realm) != 0) {
+ printf ("wrong realm (\"%s\" should be \"%s\")"
+ " for \"%s\"\n",
+ princ->realm, t->realm,
+ t->input_string);
+ val = 1;
+ }
+
+ if (t->ncomponents != princ->name.name_string.len) {
+ printf ("wrong number of components (%u should be %u)"
+ " for \"%s\"\n",
+ princ->name.name_string.len, t->ncomponents,
+ t->input_string);
+ val = 1;
+ } else {
+ for (i = 0; i < t->ncomponents; ++i) {
+ if (strcmp(t->comp_val[i],
+ princ->name.name_string.val[i]) != 0) {
+ printf ("bad component %d (\"%s\" should be \"%s\")"
+ " for \"%s\"\n",
+ i,
+ princ->name.name_string.val[i],
+ t->comp_val[i],
+ t->input_string);
+ val = 1;
+ }
+ }
+ }
+ for (j = 0; j < strlen(t->output_string); ++j) {
+ ret = krb5_unparse_name_fixed(context, princ,
+ name_buf, j);
+ if (ret != ERANGE) {
+ printf ("unparse_name %s with length %d should have failed\n",
+ t->input_string, j);
+ val = 1;
+ break;
+ }
+ }
+ ret = krb5_unparse_name_fixed(context, princ,
+ name_buf, sizeof(name_buf));
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_unparse_name_fixed");
+
+ if (strcmp (t->output_string, name_buf) != 0) {
+ printf ("failed comparing the re-parsed"
+ " (\"%s\" should be \"%s\")\n",
+ name_buf, t->output_string);
+ val = 1;
+ }
+
+ ret = krb5_unparse_name(context, princ, &s);
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_unparse_name");
+
+ if (strcmp (t->output_string, s) != 0) {
+ printf ("failed comparing the re-parsed"
+ " (\"%s\" should be \"%s\"\n",
+ s, t->output_string);
+ val = 1;
+ }
+ free(s);
+
+ if (!t->realmp) {
+ for (j = 0; j < strlen(t->input_string); ++j) {
+ ret = krb5_unparse_name_fixed_short(context, princ,
+ name_buf, j);
+ if (ret != ERANGE) {
+ printf ("unparse_name_short %s with length %d"
+ " should have failed\n",
+ t->input_string, j);
+ val = 1;
+ break;
+ }
+ }
+ ret = krb5_unparse_name_fixed_short(context, princ,
+ name_buf, sizeof(name_buf));
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_unparse_name_fixed");
+
+ if (strcmp (t->input_string, name_buf) != 0) {
+ printf ("failed comparing the re-parsed"
+ " (\"%s\" should be \"%s\")\n",
+ name_buf, t->input_string);
+ val = 1;
+ }
+
+ ret = krb5_unparse_name_short(context, princ, &s);
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_unparse_name_short");
+
+ if (strcmp (t->input_string, s) != 0) {
+ printf ("failed comparing the re-parsed"
+ " (\"%s\" should be \"%s\"\n",
+ s, t->input_string);
+ val = 1;
+ }
+ free(s);
+ }
+ krb5_free_principal (context, princ);
+ }
+ krb5_free_context(context);
+ return val;
+}
diff --git a/third_party/heimdal/lib/krb5/pcache.c b/third_party/heimdal/lib/krb5/pcache.c
new file mode 100644
index 0000000..51913ba
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/pcache.c
@@ -0,0 +1,81 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include "krb5_locl.h"
+#include "ccache_plugin.h"
+#ifdef HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+#include <assert.h>
+
+/*
+ * cc_plugin_register_to_context is executed once per krb5_init_context().
+ * Its job is to register the plugin's krb5_cc_ops structure with the
+ * krb5_context.
+ */
+
+static krb5_error_code KRB5_LIB_CALL
+cc_plugin_register_to_context(krb5_context context, const void *plug, void *plugctx, void *userctx)
+{
+ krb5_cc_ops *ccops = (krb5_cc_ops *)plugctx;
+ krb5_error_code ret;
+
+ if (ccops == NULL)
+ return KRB5_PLUGIN_NO_HANDLE;
+
+ ret = krb5_cc_register(context, ccops, TRUE);
+ if (ret != 0)
+ *((krb5_error_code *)userctx) = ret;
+
+ return KRB5_PLUGIN_NO_HANDLE;
+}
+
+static const char *ccache_plugin_deps[] = { "krb5", NULL };
+
+static struct heim_plugin_data
+ccache_plugin_data = {
+ "krb5",
+ KRB5_PLUGIN_CCACHE,
+ 0,
+ ccache_plugin_deps,
+ krb5_get_instance
+};
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_load_ccache_plugins(krb5_context context)
+{
+ krb5_error_code userctx = 0;
+
+ (void)_krb5_plugin_run_f(context, &ccache_plugin_data, 0,
+ &userctx, cc_plugin_register_to_context);
+
+ return userctx;
+}
diff --git a/third_party/heimdal/lib/krb5/pkinit-ec.c b/third_party/heimdal/lib/krb5/pkinit-ec.c
new file mode 100644
index 0000000..33bc62c
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/pkinit-ec.c
@@ -0,0 +1,241 @@
+/*
+ * Copyright (c) 2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <roken.h>
+
+#ifdef PKINIT
+
+/*
+ * As with the other *-ec.c files in Heimdal, this is a bit of a hack.
+ *
+ * The idea is to use OpenSSL for EC because hcrypto doesn't have the
+ * required functionality at this time. To do this we segregate
+ * EC-using code into separate source files and then we arrange for them
+ * to get the OpenSSL headers and not the conflicting hcrypto ones.
+ *
+ * Because of auto-generated *-private.h headers, we end up needing to
+ * make sure various types are defined before we include them, thus the
+ * strange header include order here.
+ */
+
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+#include <openssl/ec.h>
+#include <openssl/ecdh.h>
+#include <openssl/evp.h>
+#include <openssl/bn.h>
+#define HEIM_NO_CRYPTO_HDRS
+#endif
+
+/*
+ * NO_HCRYPTO_POLLUTION -> don't refer to hcrypto type/function names
+ * that we don't need in this file and which would clash with OpenSSL's
+ * in ways that are difficult to address in cleaner ways.
+ *
+ * In the medium- to long-term what we should do is move all PK in
+ * Heimdal to the newer EVP interfaces for PK and then nothing outside
+ * lib/hcrypto should ever have to include OpenSSL headers, and -more
+ * specifically- the only thing that should ever have to include OpenSSL
+ * headers is the OpenSSL backend to hcrypto.
+ */
+#define NO_HCRYPTO_POLLUTION
+
+#include "krb5_locl.h"
+#include <hcrypto/des.h>
+#include <cms_asn1.h>
+#include <pkcs8_asn1.h>
+#include <pkcs9_asn1.h>
+#include <pkcs12_asn1.h>
+#include <pkinit_asn1.h>
+#include <asn1_err.h>
+
+#include <der.h>
+
+krb5_error_code
+_krb5_build_authpack_subjectPK_EC(krb5_context context,
+ krb5_pk_init_ctx ctx,
+ AuthPack *a)
+{
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+ krb5_error_code ret;
+ ECParameters ecp;
+ unsigned char *p;
+ size_t size;
+ int xlen;
+
+ /* copy in public key, XXX find the best curve that the server support or use the clients curve if possible */
+
+ ecp.element = choice_ECParameters_namedCurve;
+ ret = der_copy_oid(&asn1_oid_id_ec_group_secp256r1,
+ &ecp.u.namedCurve);
+ if (ret)
+ return ret;
+
+ ALLOC(a->clientPublicValue->algorithm.parameters, 1);
+ if (a->clientPublicValue->algorithm.parameters == NULL) {
+ free_ECParameters(&ecp);
+ return krb5_enomem(context);
+ }
+ ASN1_MALLOC_ENCODE(ECParameters, p, xlen, &ecp, &size, ret);
+ free_ECParameters(&ecp);
+ if (ret)
+ return ret;
+ if ((int)size != xlen)
+ krb5_abortx(context, "asn1 internal error");
+
+ a->clientPublicValue->algorithm.parameters->data = p;
+ a->clientPublicValue->algorithm.parameters->length = size;
+
+ /* copy in public key */
+
+ ret = der_copy_oid(&asn1_oid_id_ecPublicKey,
+ &a->clientPublicValue->algorithm.algorithm);
+ if (ret)
+ return ret;
+
+ ctx->u.eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
+ if (ctx->u.eckey == NULL)
+ return krb5_enomem(context);
+
+ ret = EC_KEY_generate_key(ctx->u.eckey);
+ if (ret != 1)
+ return EINVAL;
+
+ xlen = i2o_ECPublicKey(ctx->u.eckey, NULL);
+ if (xlen <= 0)
+ return EINVAL;
+
+ p = malloc(xlen);
+ if (p == NULL)
+ return krb5_enomem(context);
+
+ a->clientPublicValue->subjectPublicKey.data = p;
+
+ xlen = i2o_ECPublicKey(ctx->u.eckey, &p);
+ if (xlen <= 0) {
+ a->clientPublicValue->subjectPublicKey.data = NULL;
+ free(p);
+ return EINVAL;
+ }
+
+ a->clientPublicValue->subjectPublicKey.length = xlen * 8;
+
+ return 0;
+
+ /* XXX verify that this is right with RFC3279 */
+#else
+ krb5_set_error_message(context, ENOTSUP,
+ N_("PKINIT: ECDH not supported", ""));
+ return ENOTSUP;
+#endif
+}
+
+krb5_error_code
+_krb5_pk_rd_pa_reply_ecdh_compute_key(krb5_context context,
+ krb5_pk_init_ctx ctx,
+ const unsigned char *in,
+ size_t in_sz,
+ unsigned char **out,
+ int *out_sz)
+{
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+ krb5_error_code ret = 0;
+ int dh_gen_keylen;
+
+ const EC_GROUP *group;
+ EC_KEY *public = NULL;
+
+ group = EC_KEY_get0_group(ctx->u.eckey);
+
+ public = EC_KEY_new();
+ if (public == NULL)
+ return krb5_enomem(context);
+ if (EC_KEY_set_group(public, group) != 1) {
+ EC_KEY_free(public);
+ return krb5_enomem(context);
+ }
+
+ if (o2i_ECPublicKey(&public, &in, in_sz) == NULL) {
+ EC_KEY_free(public);
+ ret = KRB5KRB_ERR_GENERIC;
+ krb5_set_error_message(context, ret,
+ N_("PKINIT: Can't parse ECDH public key", ""));
+ return ret;
+ }
+
+ *out_sz = (EC_GROUP_get_degree(group) + 7) / 8;
+ if (*out_sz < 0)
+ return EOVERFLOW;
+ *out = malloc(*out_sz);
+ if (*out == NULL) {
+ EC_KEY_free(public);
+ return krb5_enomem(context);
+ }
+ dh_gen_keylen = ECDH_compute_key(*out, *out_sz,
+ EC_KEY_get0_public_key(public),
+ ctx->u.eckey, NULL);
+ EC_KEY_free(public);
+ if (dh_gen_keylen <= 0) {
+ ret = KRB5KRB_ERR_GENERIC;
+ dh_gen_keylen = 0;
+ krb5_set_error_message(context, ret,
+ N_("PKINIT: Can't compute ECDH public key", ""));
+ free(*out);
+ *out = NULL;
+ *out_sz = 0;
+ }
+ *out_sz = dh_gen_keylen;
+
+ return ret;
+#else
+ krb5_set_error_message(context, ENOTSUP,
+ N_("PKINIT: ECDH not supported", ""));
+ return ENOTSUP;
+#endif
+}
+
+void
+_krb5_pk_eckey_free(void *eckey)
+{
+#ifdef HAVE_HCRYPTO_W_OPENSSL
+ EC_KEY_free(eckey);
+#endif
+}
+
+#else
+
+static char lib_krb5_pkinit_ec_c = '\0';
+
+#endif
diff --git a/third_party/heimdal/lib/krb5/pkinit.c b/third_party/heimdal/lib/krb5/pkinit.c
new file mode 100644
index 0000000..c9a6e3e
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/pkinit.c
@@ -0,0 +1,2674 @@
+/*
+ * Copyright (c) 2003 - 2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+struct krb5_dh_moduli {
+ char *name;
+ unsigned long bits;
+ heim_integer p;
+ heim_integer g;
+ heim_integer q;
+};
+
+#ifdef PKINIT
+
+#include <cms_asn1.h>
+#include <pkcs8_asn1.h>
+#include <pkcs9_asn1.h>
+#include <pkcs12_asn1.h>
+#include <pkinit_asn1.h>
+#include <asn1_err.h>
+
+#include <der.h>
+
+struct krb5_pk_cert {
+ hx509_cert cert;
+};
+
+static void
+pk_copy_error(krb5_context context,
+ hx509_context hx509ctx,
+ int hxret,
+ const char *fmt,
+ ...)
+ __attribute__ ((__format__ (__printf__, 4, 5)));
+
+/*
+ *
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_pk_cert_free(struct krb5_pk_cert *cert)
+{
+ if (cert->cert) {
+ hx509_cert_free(cert->cert);
+ }
+ free(cert);
+}
+
+static krb5_error_code
+BN_to_integer(krb5_context context, BIGNUM *bn, heim_integer *integer)
+{
+ integer->length = BN_num_bytes(bn);
+ integer->data = malloc(integer->length);
+ if (integer->data == NULL) {
+ krb5_clear_error_message(context);
+ return ENOMEM;
+ }
+ BN_bn2bin(bn, integer->data);
+ integer->negative = BN_is_negative(bn);
+ return 0;
+}
+
+static BIGNUM *
+integer_to_BN(krb5_context context, const char *field, const heim_integer *f)
+{
+ BIGNUM *bn;
+
+ bn = BN_bin2bn((const unsigned char *)f->data, f->length, NULL);
+ if (bn == NULL) {
+ krb5_set_error_message(context, ENOMEM,
+ N_("PKINIT: parsing BN failed %s", ""), field);
+ return NULL;
+ }
+ BN_set_negative(bn, f->negative);
+ return bn;
+}
+
+static krb5_error_code
+select_dh_group(krb5_context context, DH *dh, unsigned long bits,
+ struct krb5_dh_moduli **moduli)
+{
+ const struct krb5_dh_moduli *m;
+
+ if (moduli[0] == NULL) {
+ krb5_set_error_message(context, EINVAL,
+ N_("Did not find a DH group parameter "
+ "matching requirement of %lu bits", ""),
+ bits);
+ return EINVAL;
+ }
+
+ if (bits == 0) {
+ m = moduli[1]; /* XXX */
+ if (m == NULL)
+ m = moduli[0]; /* XXX */
+ } else {
+ int i;
+ for (i = 0; moduli[i] != NULL; i++) {
+ if (bits < moduli[i]->bits)
+ break;
+ }
+ if (moduli[i] == NULL) {
+ krb5_set_error_message(context, EINVAL,
+ N_("Did not find a DH group parameter "
+ "matching requirement of %lu bits", ""),
+ bits);
+ return EINVAL;
+ }
+ m = moduli[i];
+ }
+
+ dh->p = integer_to_BN(context, "p", &m->p);
+ if (dh->p == NULL)
+ return ENOMEM;
+ dh->g = integer_to_BN(context, "g", &m->g);
+ if (dh->g == NULL)
+ return ENOMEM;
+ dh->q = integer_to_BN(context, "q", &m->q);
+ if (dh->q == NULL)
+ return ENOMEM;
+
+ return 0;
+}
+
+struct certfind {
+ const char *type;
+ const heim_oid *oid;
+};
+
+/*
+ * Try searchin the key by to use by first looking for for PK-INIT
+ * EKU, then the Microsoft smart card EKU and last, no special EKU at all.
+ */
+
+static krb5_error_code
+find_cert(krb5_context context, struct krb5_pk_identity *id,
+ hx509_query *q, hx509_cert *cert)
+{
+ struct certfind cf[4] = {
+ { "MobileMe EKU", NULL },
+ { "PKINIT EKU", NULL },
+ { "MS EKU", NULL },
+ { "any (or no)", NULL }
+ };
+ int ret = HX509_CERT_NOT_FOUND;
+ size_t i, start = 1;
+ unsigned oids[] = { 1, 2, 840, 113635, 100, 3, 2, 1 };
+ const heim_oid mobileMe = { sizeof(oids)/sizeof(oids[0]), oids };
+
+
+ if (id->flags & PKINIT_BTMM)
+ start = 0;
+
+ cf[0].oid = &mobileMe;
+ cf[1].oid = &asn1_oid_id_pkekuoid;
+ cf[2].oid = &asn1_oid_id_pkinit_ms_eku;
+ cf[3].oid = NULL;
+
+ for (i = start; i < sizeof(cf)/sizeof(cf[0]); i++) {
+ ret = hx509_query_match_eku(q, cf[i].oid);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed setting %s OID", cf[i].type);
+ return ret;
+ }
+
+ ret = hx509_certs_find(context->hx509ctx, id->certs, q, cert);
+ if (ret == 0)
+ break;
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed finding certificate with %s OID", cf[i].type);
+ }
+ return ret;
+}
+
+
+static krb5_error_code
+create_signature(krb5_context context,
+ const heim_oid *eContentType,
+ krb5_data *eContent,
+ struct krb5_pk_identity *id,
+ hx509_peer_info peer,
+ krb5_data *sd_data)
+{
+ int ret, flags = 0;
+
+ if (id->cert == NULL)
+ flags |= HX509_CMS_SIGNATURE_NO_SIGNER;
+
+ ret = hx509_cms_create_signed_1(context->hx509ctx,
+ flags,
+ eContentType,
+ eContent->data,
+ eContent->length,
+ NULL,
+ id->cert,
+ peer,
+ NULL,
+ id->certs,
+ sd_data);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Create CMS signedData");
+ return ret;
+ }
+
+ return 0;
+}
+
+static int KRB5_LIB_CALL
+cert2epi(hx509_context context, void *ctx, hx509_cert c)
+{
+ ExternalPrincipalIdentifiers *ids = ctx;
+ ExternalPrincipalIdentifier id;
+ hx509_name subject = NULL;
+ void *p;
+ int ret;
+
+ if (ids->len > 10)
+ return 0;
+
+ memset(&id, 0, sizeof(id));
+
+ ret = hx509_cert_get_subject(c, &subject);
+ if (ret)
+ return ret;
+
+ if (hx509_name_is_null_p(subject) != 0) {
+
+ id.subjectName = calloc(1, sizeof(*id.subjectName));
+ if (id.subjectName == NULL) {
+ hx509_name_free(&subject);
+ free_ExternalPrincipalIdentifier(&id);
+ return ENOMEM;
+ }
+
+ ret = hx509_name_binary(subject, id.subjectName);
+ if (ret) {
+ hx509_name_free(&subject);
+ free_ExternalPrincipalIdentifier(&id);
+ return ret;
+ }
+ }
+ hx509_name_free(&subject);
+
+
+ id.issuerAndSerialNumber = calloc(1, sizeof(*id.issuerAndSerialNumber));
+ if (id.issuerAndSerialNumber == NULL) {
+ free_ExternalPrincipalIdentifier(&id);
+ return ENOMEM;
+ }
+
+ {
+ IssuerAndSerialNumber iasn;
+ hx509_name issuer;
+ size_t size = 0;
+
+ memset(&iasn, 0, sizeof(iasn));
+
+ ret = hx509_cert_get_issuer(c, &issuer);
+ if (ret) {
+ free_ExternalPrincipalIdentifier(&id);
+ return ret;
+ }
+
+ ret = hx509_name_to_Name(issuer, &iasn.issuer);
+ hx509_name_free(&issuer);
+ if (ret) {
+ free_ExternalPrincipalIdentifier(&id);
+ return ret;
+ }
+
+ ret = hx509_cert_get_serialnumber(c, &iasn.serialNumber);
+ if (ret) {
+ free_IssuerAndSerialNumber(&iasn);
+ free_ExternalPrincipalIdentifier(&id);
+ return ret;
+ }
+
+ ASN1_MALLOC_ENCODE(IssuerAndSerialNumber,
+ id.issuerAndSerialNumber->data,
+ id.issuerAndSerialNumber->length,
+ &iasn, &size, ret);
+ free_IssuerAndSerialNumber(&iasn);
+ if (ret) {
+ free_ExternalPrincipalIdentifier(&id);
+ return ret;
+ }
+ if (id.issuerAndSerialNumber->length != size)
+ abort();
+ }
+
+ id.subjectKeyIdentifier = NULL;
+
+ p = realloc(ids->val, sizeof(ids->val[0]) * (ids->len + 1));
+ if (p == NULL) {
+ free_ExternalPrincipalIdentifier(&id);
+ return ENOMEM;
+ }
+
+ ids->val = p;
+ ids->val[ids->len] = id;
+ ids->len++;
+
+ return 0;
+}
+
+static krb5_error_code
+build_edi(krb5_context context,
+ hx509_context hx509ctx,
+ hx509_certs certs,
+ ExternalPrincipalIdentifiers *ids)
+{
+ return hx509_certs_iter_f(hx509ctx, certs, cert2epi, ids);
+}
+
+static krb5_error_code
+build_auth_pack(krb5_context context,
+ unsigned nonce,
+ krb5_pk_init_ctx ctx,
+ const KDC_REQ_BODY *body,
+ AuthPack *a)
+{
+ size_t buf_size, len = 0;
+ krb5_error_code ret;
+ void *buf;
+ krb5_timestamp sec;
+ int32_t usec;
+ Checksum checksum;
+
+ krb5_clear_error_message(context);
+
+ memset(&checksum, 0, sizeof(checksum));
+
+ krb5_us_timeofday(context, &sec, &usec);
+ a->pkAuthenticator.ctime = sec;
+ a->pkAuthenticator.nonce = nonce;
+
+ ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, body, &len, ret);
+ if (ret)
+ return ret;
+ if (buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ ret = krb5_create_checksum(context,
+ NULL,
+ 0,
+ CKSUMTYPE_SHA1,
+ buf,
+ len,
+ &checksum);
+ free(buf);
+ if (ret)
+ return ret;
+
+ ALLOC(a->pkAuthenticator.paChecksum, 1);
+ if (a->pkAuthenticator.paChecksum == NULL) {
+ return krb5_enomem(context);
+ }
+
+ ret = krb5_data_copy(a->pkAuthenticator.paChecksum,
+ checksum.checksum.data, checksum.checksum.length);
+ free_Checksum(&checksum);
+ if (ret)
+ return ret;
+
+ if (ctx->keyex == USE_DH || ctx->keyex == USE_ECDH) {
+ const char *moduli_file;
+ unsigned long dh_min_bits;
+ krb5_data dhbuf;
+ size_t size = 0;
+
+ krb5_data_zero(&dhbuf);
+
+
+
+ moduli_file = krb5_config_get_string(context, NULL,
+ "libdefaults",
+ "moduli",
+ NULL);
+
+ dh_min_bits =
+ krb5_config_get_int_default(context, NULL, 0,
+ "libdefaults",
+ "pkinit_dh_min_bits",
+ NULL);
+
+ ret = _krb5_parse_moduli(context, moduli_file, &ctx->m);
+ if (ret)
+ return ret;
+
+ ctx->u.dh = DH_new();
+ if (ctx->u.dh == NULL)
+ return krb5_enomem(context);
+
+ ret = select_dh_group(context, ctx->u.dh, dh_min_bits, ctx->m);
+ if (ret)
+ return ret;
+
+ if (DH_generate_key(ctx->u.dh) != 1) {
+ krb5_set_error_message(context, ENOMEM,
+ N_("pkinit: failed to generate DH key", ""));
+ return ENOMEM;
+ }
+
+
+ if (1 /* support_cached_dh */) {
+ ALLOC(a->clientDHNonce, 1);
+ if (a->clientDHNonce == NULL) {
+ krb5_clear_error_message(context);
+ return ENOMEM;
+ }
+ ret = krb5_data_alloc(a->clientDHNonce, 40);
+ if (a->clientDHNonce == NULL) {
+ krb5_clear_error_message(context);
+ return ret;
+ }
+ RAND_bytes(a->clientDHNonce->data, a->clientDHNonce->length);
+ ret = krb5_copy_data(context, a->clientDHNonce,
+ &ctx->clientDHNonce);
+ if (ret)
+ return ret;
+ }
+
+ ALLOC(a->clientPublicValue, 1);
+ if (a->clientPublicValue == NULL)
+ return ENOMEM;
+
+ if (ctx->keyex == USE_DH) {
+ DH *dh = ctx->u.dh;
+ DomainParameters dp;
+ heim_integer dh_pub_key;
+
+ ret = der_copy_oid(&asn1_oid_id_dhpublicnumber,
+ &a->clientPublicValue->algorithm.algorithm);
+ if (ret)
+ return ret;
+
+ memset(&dp, 0, sizeof(dp));
+
+ ret = BN_to_integer(context, dh->p, &dp.p);
+ if (ret) {
+ free_DomainParameters(&dp);
+ return ret;
+ }
+ ret = BN_to_integer(context, dh->g, &dp.g);
+ if (ret) {
+ free_DomainParameters(&dp);
+ return ret;
+ }
+ if (dh->q && BN_num_bits(dh->q)) {
+ /*
+ * The q parameter is required, but MSFT made it optional.
+ * It's only required in order to verify the domain parameters
+ * -- the security of the DH group --, but we validate groups
+ * against known groups rather than accepting arbitrary groups
+ * chosen by the peer, so we really don't need to have put it
+ * on the wire. Because these are Oakley groups, and the
+ * primes are Sophie Germain primes, q is p>>1 and we can
+ * compute it on the fly like MIT Kerberos does, but we'd have
+ * to implement BN_rshift1().
+ */
+ dp.q = calloc(1, sizeof(*dp.q));
+ if (dp.q == NULL) {
+ free_DomainParameters(&dp);
+ return ENOMEM;
+ }
+ ret = BN_to_integer(context, dh->q, dp.q);
+ if (ret) {
+ free_DomainParameters(&dp);
+ return ret;
+ }
+ }
+ dp.j = NULL;
+ dp.validationParms = NULL;
+
+ a->clientPublicValue->algorithm.parameters =
+ malloc(sizeof(*a->clientPublicValue->algorithm.parameters));
+ if (a->clientPublicValue->algorithm.parameters == NULL) {
+ free_DomainParameters(&dp);
+ return ret;
+ }
+
+ ASN1_MALLOC_ENCODE(DomainParameters,
+ a->clientPublicValue->algorithm.parameters->data,
+ a->clientPublicValue->algorithm.parameters->length,
+ &dp, &size, ret);
+ free_DomainParameters(&dp);
+ if (ret)
+ return ret;
+ if (size != a->clientPublicValue->algorithm.parameters->length)
+ krb5_abortx(context, "Internal ASN1 encoder error");
+
+ ret = BN_to_integer(context, dh->pub_key, &dh_pub_key);
+ if (ret)
+ return ret;
+
+ ASN1_MALLOC_ENCODE(DHPublicKey, dhbuf.data, dhbuf.length,
+ &dh_pub_key, &size, ret);
+ der_free_heim_integer(&dh_pub_key);
+ if (ret)
+ return ret;
+ if (size != dhbuf.length)
+ krb5_abortx(context, "asn1 internal error");
+ a->clientPublicValue->subjectPublicKey.length = dhbuf.length * 8;
+ a->clientPublicValue->subjectPublicKey.data = dhbuf.data;
+ } else if (ctx->keyex == USE_ECDH) {
+ ret = _krb5_build_authpack_subjectPK_EC(context, ctx, a);
+ if (ret)
+ return ret;
+ } else
+ krb5_abortx(context, "internal error");
+ }
+
+ {
+ a->supportedCMSTypes = calloc(1, sizeof(*a->supportedCMSTypes));
+ if (a->supportedCMSTypes == NULL)
+ return ENOMEM;
+
+ ret = hx509_crypto_available(context->hx509ctx, HX509_SELECT_ALL,
+ ctx->id->cert,
+ &a->supportedCMSTypes->val,
+ &a->supportedCMSTypes->len);
+ if (ret)
+ return ret;
+ }
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_pk_mk_ContentInfo(krb5_context context,
+ const krb5_data *buf,
+ const heim_oid *oid,
+ struct ContentInfo *content_info)
+{
+ krb5_error_code ret;
+
+ ret = der_copy_oid(oid, &content_info->contentType);
+ if (ret)
+ return ret;
+ ALLOC(content_info->content, 1);
+ if (content_info->content == NULL)
+ return ENOMEM;
+ content_info->content->data = malloc(buf->length);
+ if (content_info->content->data == NULL)
+ return ENOMEM;
+ memcpy(content_info->content->data, buf->data, buf->length);
+ content_info->content->length = buf->length;
+ return 0;
+}
+
+static krb5_error_code
+pk_mk_padata(krb5_context context,
+ krb5_pk_init_ctx ctx,
+ const KDC_REQ_BODY *req_body,
+ unsigned nonce,
+ METHOD_DATA *md)
+{
+ struct ContentInfo content_info;
+ krb5_error_code ret;
+ const heim_oid *oid = NULL;
+ size_t size = 0;
+ krb5_data buf, sd_buf;
+ int pa_type = -1;
+
+ krb5_data_zero(&buf);
+ krb5_data_zero(&sd_buf);
+ memset(&content_info, 0, sizeof(content_info));
+
+ if (ctx->type == PKINIT_WIN2K) {
+ AuthPack_Win2k ap;
+ krb5_timestamp sec;
+ int32_t usec;
+
+ memset(&ap, 0, sizeof(ap));
+
+ /* fill in PKAuthenticator */
+ ret = copy_PrincipalName(req_body->sname, &ap.pkAuthenticator.kdcName);
+ if (ret) {
+ free_AuthPack_Win2k(&ap);
+ krb5_clear_error_message(context);
+ goto out;
+ }
+ ret = copy_Realm(&req_body->realm, &ap.pkAuthenticator.kdcRealm);
+ if (ret) {
+ free_AuthPack_Win2k(&ap);
+ krb5_clear_error_message(context);
+ goto out;
+ }
+
+ krb5_us_timeofday(context, &sec, &usec);
+ ap.pkAuthenticator.ctime = sec;
+ ap.pkAuthenticator.cusec = usec;
+ ap.pkAuthenticator.nonce = nonce;
+
+ ASN1_MALLOC_ENCODE(AuthPack_Win2k, buf.data, buf.length,
+ &ap, &size, ret);
+ free_AuthPack_Win2k(&ap);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed encoding AuthPackWin: %d", ""),
+ (int)ret);
+ goto out;
+ }
+ if (buf.length != size)
+ krb5_abortx(context, "internal ASN1 encoder error");
+
+ oid = &asn1_oid_id_pkcs7_data;
+ } else if (ctx->type == PKINIT_27) {
+ AuthPack ap;
+
+ memset(&ap, 0, sizeof(ap));
+
+ ret = build_auth_pack(context, nonce, ctx, req_body, &ap);
+ if (ret) {
+ free_AuthPack(&ap);
+ goto out;
+ }
+
+ ASN1_MALLOC_ENCODE(AuthPack, buf.data, buf.length, &ap, &size, ret);
+ free_AuthPack(&ap);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed encoding AuthPack: %d", ""),
+ (int)ret);
+ goto out;
+ }
+ if (buf.length != size)
+ krb5_abortx(context, "internal ASN1 encoder error");
+
+ oid = &asn1_oid_id_pkauthdata;
+ } else
+ krb5_abortx(context, "internal pkinit error");
+
+ ret = create_signature(context, oid, &buf, ctx->id,
+ ctx->peer, &sd_buf);
+ krb5_data_free(&buf);
+ if (ret)
+ goto out;
+
+ ret = hx509_cms_wrap_ContentInfo(&asn1_oid_id_pkcs7_signedData, &sd_buf, &buf);
+ krb5_data_free(&sd_buf);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("ContentInfo wrapping of signedData failed",""));
+ goto out;
+ }
+
+ if (ctx->type == PKINIT_WIN2K) {
+ PA_PK_AS_REQ_Win2k winreq;
+
+ pa_type = KRB5_PADATA_PK_AS_REQ_WIN;
+
+ memset(&winreq, 0, sizeof(winreq));
+
+ winreq.signed_auth_pack = buf;
+
+ ASN1_MALLOC_ENCODE(PA_PK_AS_REQ_Win2k, buf.data, buf.length,
+ &winreq, &size, ret);
+ free_PA_PK_AS_REQ_Win2k(&winreq);
+
+ } else if (ctx->type == PKINIT_27) {
+ PA_PK_AS_REQ req;
+
+ pa_type = KRB5_PADATA_PK_AS_REQ;
+
+ memset(&req, 0, sizeof(req));
+ req.signedAuthPack = buf;
+
+ if (ctx->trustedCertifiers) {
+
+ req.trustedCertifiers = calloc(1, sizeof(*req.trustedCertifiers));
+ if (req.trustedCertifiers == NULL) {
+ ret = krb5_enomem(context);
+ free_PA_PK_AS_REQ(&req);
+ goto out;
+ }
+ ret = build_edi(context, context->hx509ctx,
+ ctx->id->anchors, req.trustedCertifiers);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("pk-init: failed to build "
+ "trustedCertifiers", ""));
+ free_PA_PK_AS_REQ(&req);
+ goto out;
+ }
+ }
+ req.kdcPkId = NULL;
+
+ ASN1_MALLOC_ENCODE(PA_PK_AS_REQ, buf.data, buf.length,
+ &req, &size, ret);
+
+ free_PA_PK_AS_REQ(&req);
+
+ } else
+ krb5_abortx(context, "internal pkinit error");
+ if (ret) {
+ krb5_set_error_message(context, ret, "PA-PK-AS-REQ %d", (int)ret);
+ goto out;
+ }
+ if (buf.length != size)
+ krb5_abortx(context, "Internal ASN1 encoder error");
+
+ ret = krb5_padata_add(context, md, pa_type, buf.data, buf.length);
+ if (ret)
+ free(buf.data);
+
+ if (ret == 0)
+ ret = krb5_padata_add(context, md, KRB5_PADATA_PK_AS_09_BINDING, NULL, 0);
+
+ out:
+ free_ContentInfo(&content_info);
+
+ return ret;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_pk_mk_padata(krb5_context context,
+ void *c,
+ int ic_flags,
+ int win2k,
+ const KDC_REQ_BODY *req_body,
+ unsigned nonce,
+ METHOD_DATA *md)
+{
+ krb5_pk_init_ctx ctx = c;
+ int win2k_compat;
+
+ if (ctx->id->certs == NULL && ctx->anonymous == 0) {
+ krb5_set_error_message(context, HEIM_PKINIT_NO_PRIVATE_KEY,
+ N_("PKINIT: No user certificate given", ""));
+ return HEIM_PKINIT_NO_PRIVATE_KEY;
+ }
+
+ win2k_compat = krb5_config_get_bool_default(context, NULL,
+ win2k,
+ "realms",
+ req_body->realm,
+ "pkinit_win2k",
+ NULL);
+
+ if (win2k_compat) {
+ ctx->require_binding =
+ krb5_config_get_bool_default(context, NULL,
+ TRUE,
+ "realms",
+ req_body->realm,
+ "pkinit_win2k_require_binding",
+ NULL);
+ ctx->type = PKINIT_WIN2K;
+ } else
+ ctx->type = PKINIT_27;
+
+ ctx->require_eku =
+ krb5_config_get_bool_default(context, NULL,
+ TRUE,
+ "realms",
+ req_body->realm,
+ "pkinit_require_eku",
+ NULL);
+ if (ic_flags & KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK)
+ ctx->require_eku = 0;
+ if (ctx->id->flags & (PKINIT_BTMM | PKINIT_NO_KDC_ANCHOR))
+ ctx->require_eku = 0;
+
+ ctx->require_krbtgt_otherName =
+ krb5_config_get_bool_default(context, NULL,
+ TRUE,
+ "realms",
+ req_body->realm,
+ "pkinit_require_krbtgt_otherName",
+ NULL);
+ if (ic_flags & KRB5_INIT_CREDS_PKINIT_NO_KRBTGT_OTHERNAME_CHECK)
+ ctx->require_krbtgt_otherName = FALSE;
+
+ ctx->require_hostname_match =
+ krb5_config_get_bool_default(context, NULL,
+ FALSE,
+ "realms",
+ req_body->realm,
+ "pkinit_require_hostname_match",
+ NULL);
+
+ ctx->trustedCertifiers =
+ krb5_config_get_bool_default(context, NULL,
+ TRUE,
+ "realms",
+ req_body->realm,
+ "pkinit_trustedCertifiers",
+ NULL);
+
+ return pk_mk_padata(context, ctx, req_body, nonce, md);
+}
+
+static krb5_error_code
+pk_verify_sign(krb5_context context,
+ const void *data,
+ size_t length,
+ struct krb5_pk_identity *id,
+ heim_oid *contentType,
+ krb5_data *content,
+ struct krb5_pk_cert **signer)
+{
+ hx509_certs signer_certs;
+ int ret;
+ unsigned flags = 0, verify_flags = 0;
+
+ *signer = NULL;
+
+ if (id->flags & PKINIT_BTMM) {
+ flags |= HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH;
+ flags |= HX509_CMS_VS_NO_KU_CHECK;
+ flags |= HX509_CMS_VS_NO_VALIDATE;
+ }
+ if (id->flags & PKINIT_NO_KDC_ANCHOR)
+ flags |= HX509_CMS_VS_NO_VALIDATE;
+
+ ret = hx509_cms_verify_signed_ext(context->hx509ctx,
+ id->verify_ctx,
+ flags,
+ data,
+ length,
+ NULL,
+ id->certpool,
+ contentType,
+ content,
+ &signer_certs,
+ &verify_flags);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "CMS verify signed failed");
+ return ret;
+ }
+
+ heim_assert((verify_flags & HX509_CMS_VSE_VALIDATED) ||
+ (id->flags & PKINIT_NO_KDC_ANCHOR),
+ "Either PKINIT signer must be validated, or NO_KDC_ANCHOR must be set");
+
+ if ((verify_flags & HX509_CMS_VSE_VALIDATED) == 0)
+ goto out;
+
+ *signer = calloc(1, sizeof(**signer));
+ if (*signer == NULL) {
+ krb5_clear_error_message(context);
+ ret = ENOMEM;
+ goto out;
+ }
+
+ ret = hx509_get_one_cert(context->hx509ctx, signer_certs, &(*signer)->cert);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed to get on of the signer certs");
+ goto out;
+ }
+
+ out:
+ hx509_certs_free(&signer_certs);
+ if (ret) {
+ if (*signer) {
+ hx509_cert_free((*signer)->cert);
+ free(*signer);
+ *signer = NULL;
+ }
+ }
+
+ return ret;
+}
+
+static krb5_error_code
+get_reply_key_win(krb5_context context,
+ const krb5_data *content,
+ unsigned nonce,
+ krb5_keyblock **key)
+{
+ ReplyKeyPack_Win2k key_pack;
+ krb5_error_code ret;
+ size_t size;
+
+ ret = decode_ReplyKeyPack_Win2k(content->data,
+ content->length,
+ &key_pack,
+ &size);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("PKINIT decoding reply key failed", ""));
+ free_ReplyKeyPack_Win2k(&key_pack);
+ return ret;
+ }
+
+ if ((unsigned)key_pack.nonce != nonce) {
+ krb5_set_error_message(context, ret,
+ N_("PKINIT enckey nonce is wrong", ""));
+ free_ReplyKeyPack_Win2k(&key_pack);
+ return KRB5KRB_AP_ERR_MODIFIED;
+ }
+
+ *key = malloc (sizeof (**key));
+ if (*key == NULL) {
+ free_ReplyKeyPack_Win2k(&key_pack);
+ return krb5_enomem(context);
+ }
+
+ ret = copy_EncryptionKey(&key_pack.replyKey, *key);
+ free_ReplyKeyPack_Win2k(&key_pack);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("PKINIT failed copying reply key", ""));
+ free(*key);
+ *key = NULL;
+ }
+
+ return ret;
+}
+
+static krb5_error_code
+get_reply_key(krb5_context context,
+ const krb5_data *content,
+ const krb5_data *req_buffer,
+ krb5_keyblock **key)
+{
+ ReplyKeyPack key_pack;
+ krb5_error_code ret;
+ size_t size;
+
+ ret = decode_ReplyKeyPack(content->data,
+ content->length,
+ &key_pack,
+ &size);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("PKINIT decoding reply key failed", ""));
+ free_ReplyKeyPack(&key_pack);
+ return ret;
+ }
+
+ {
+ krb5_crypto crypto;
+
+ /*
+ * XXX Verify kp.replyKey is a allowed enctype in the
+ * configuration file
+ */
+
+ ret = krb5_crypto_init(context, &key_pack.replyKey, 0, &crypto);
+ if (ret) {
+ free_ReplyKeyPack(&key_pack);
+ return ret;
+ }
+
+ ret = krb5_verify_checksum(context, crypto, 6,
+ req_buffer->data, req_buffer->length,
+ &key_pack.asChecksum);
+ krb5_crypto_destroy(context, crypto);
+ if (ret) {
+ free_ReplyKeyPack(&key_pack);
+ return ret;
+ }
+ }
+
+ *key = malloc (sizeof (**key));
+ if (*key == NULL) {
+ free_ReplyKeyPack(&key_pack);
+ return krb5_enomem(context);
+ }
+
+ ret = copy_EncryptionKey(&key_pack.replyKey, *key);
+ free_ReplyKeyPack(&key_pack);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("PKINIT failed copying reply key", ""));
+ free(*key);
+ *key = NULL;
+ }
+
+ return ret;
+}
+
+
+static krb5_error_code
+pk_verify_host(krb5_context context,
+ const char *realm,
+ const krb5_krbhst_info *hi,
+ struct krb5_pk_init_ctx_data *ctx,
+ struct krb5_pk_cert *host)
+{
+ krb5_error_code ret = 0;
+
+ if (ctx->require_eku) {
+ ret = hx509_cert_check_eku(context->hx509ctx, host->cert,
+ &asn1_oid_id_pkkdcekuoid, 0);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("No PK-INIT KDC EKU in kdc certificate", ""));
+ return ret;
+ }
+ }
+ if (ctx->require_krbtgt_otherName) {
+ hx509_octet_string_list list;
+ size_t i;
+ int matched = 0;
+
+ ret = hx509_cert_find_subjectAltName_otherName(context->hx509ctx,
+ host->cert,
+ &asn1_oid_id_pkinit_san,
+ &list);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to find the PK-INIT "
+ "subjectAltName in the KDC "
+ "certificate", ""));
+
+ return ret;
+ }
+
+ /*
+ * subjectAltNames are multi-valued, and a single KDC may serve
+ * multiple realms. The SAN validation here must accept
+ * the KDC's cert if *any* of the SANs match the expected KDC.
+ * It is OK for *some* of the SANs to not match, provided at least
+ * one does.
+ */
+ for (i = 0; matched == 0 && i < list.len; i++) {
+ KRB5PrincipalName r;
+
+ ret = decode_KRB5PrincipalName(list.val[i].data,
+ list.val[i].length,
+ &r,
+ NULL);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to decode the PK-INIT "
+ "subjectAltName in the "
+ "KDC certificate", ""));
+
+ break;
+ }
+
+ if (r.principalName.name_string.len == 2 &&
+ strcmp(r.principalName.name_string.val[0], KRB5_TGS_NAME) == 0
+ && strcmp(r.principalName.name_string.val[1], realm) == 0
+ && strcmp(r.realm, realm) == 0)
+ matched = 1;
+
+ free_KRB5PrincipalName(&r);
+ }
+ hx509_free_octet_string_list(&list);
+
+ if (matched == 0 &&
+ (ctx->id->flags & PKINIT_NO_KDC_ANCHOR) == 0) {
+ ret = KRB5_KDC_ERR_INVALID_CERTIFICATE;
+ /* XXX: Lost in translation... */
+ krb5_set_error_message(context, ret,
+ N_("KDC have wrong realm name in "
+ "the certificate", ""));
+ }
+ }
+ if (ret)
+ return ret;
+
+ if (hi) {
+ ret = hx509_verify_hostname(context->hx509ctx, host->cert,
+ ctx->require_hostname_match,
+ HX509_HN_HOSTNAME,
+ hi->hostname,
+ hi->ai->ai_addr, hi->ai->ai_addrlen);
+
+ if (ret)
+ krb5_set_error_message(context, ret,
+ N_("Address mismatch in "
+ "the KDC certificate", ""));
+ }
+ return ret;
+}
+
+static krb5_error_code
+pk_rd_pa_reply_enckey(krb5_context context,
+ int type,
+ const heim_octet_string *indata,
+ const heim_oid *dataType,
+ const char *realm,
+ krb5_pk_init_ctx ctx,
+ krb5_enctype etype,
+ const krb5_krbhst_info *hi,
+ unsigned nonce,
+ const krb5_data *req_buffer,
+ PA_DATA *pa,
+ krb5_keyblock **key)
+{
+ krb5_error_code ret;
+ struct krb5_pk_cert *host = NULL;
+ krb5_data content;
+ heim_octet_string unwrapped;
+ heim_oid contentType = { 0, NULL };
+ int flags = HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT;
+
+ if (der_heim_oid_cmp(&asn1_oid_id_pkcs7_envelopedData, dataType)) {
+ krb5_set_error_message(context, EINVAL,
+ N_("PKINIT: Invalid content type", ""));
+ return EINVAL;
+ }
+
+ if (ctx->type == PKINIT_WIN2K)
+ flags |= HX509_CMS_UE_ALLOW_WEAK;
+
+ ret = hx509_cms_unenvelope(context->hx509ctx,
+ ctx->id->certs,
+ flags,
+ indata->data,
+ indata->length,
+ NULL,
+ 0,
+ &contentType,
+ &content);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed to unenvelope CMS data in PK-INIT reply");
+ return ret;
+ }
+ der_free_oid(&contentType);
+
+ /* win2k uses ContentInfo */
+ if (type == PKINIT_WIN2K) {
+ heim_oid type2;
+
+ ret = hx509_cms_unwrap_ContentInfo(&content, &type2, &unwrapped, NULL);
+ if (ret) {
+ /* windows LH with interesting CMS packets */
+ size_t ph = 1 + der_length_len(content.length);
+ unsigned char *ptr = malloc(content.length + ph);
+ size_t l;
+
+ memcpy(ptr + ph, content.data, content.length);
+
+ ret = der_put_length_and_tag (ptr + ph - 1, ph, content.length,
+ ASN1_C_UNIV, CONS, UT_Sequence, &l);
+ if (ret) {
+ free(ptr);
+ return ret;
+ }
+ free(content.data);
+ content.data = ptr;
+ content.length += ph;
+
+ ret = hx509_cms_unwrap_ContentInfo(&content, &type2, &unwrapped, NULL);
+ if (ret)
+ goto out;
+ }
+ if (der_heim_oid_cmp(&type2, &asn1_oid_id_pkcs7_signedData)) {
+ ret = EINVAL; /* XXX */
+ krb5_set_error_message(context, ret,
+ N_("PKINIT: Invalid content type", ""));
+ der_free_oid(&type2);
+ der_free_octet_string(&unwrapped);
+ goto out;
+ }
+ der_free_oid(&type2);
+ krb5_data_free(&content);
+ ret = krb5_data_copy(&content, unwrapped.data, unwrapped.length);
+ der_free_octet_string(&unwrapped);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("malloc: out of memory", ""));
+ goto out;
+ }
+ }
+
+ ret = pk_verify_sign(context,
+ content.data,
+ content.length,
+ ctx->id,
+ &contentType,
+ &unwrapped,
+ &host);
+ if (ret == 0) {
+ krb5_data_free(&content);
+ ret = krb5_data_copy(&content, unwrapped.data, unwrapped.length);
+ der_free_octet_string(&unwrapped);
+ }
+ if (ret)
+ goto out;
+
+ heim_assert(host || (ctx->id->flags & PKINIT_NO_KDC_ANCHOR),
+ "KDC signature must be verified unless PKINIT_NO_KDC_ANCHOR set");
+
+ if (host) {
+ /* make sure that it is the kdc's certificate */
+ ret = pk_verify_host(context, realm, hi, ctx, host);
+ if (ret)
+ goto out;
+
+ ctx->kdc_verified = 1;
+ }
+
+#if 0
+ if (type == PKINIT_WIN2K) {
+ if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkcs7_data) != 0) {
+ ret = KRB5KRB_AP_ERR_MSG_TYPE;
+ krb5_set_error_message(context, ret, "PKINIT: reply key, wrong oid");
+ goto out;
+ }
+ } else {
+ if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkrkeydata) != 0) {
+ ret = KRB5KRB_AP_ERR_MSG_TYPE;
+ krb5_set_error_message(context, ret, "PKINIT: reply key, wrong oid");
+ goto out;
+ }
+ }
+#endif
+
+ switch(type) {
+ case PKINIT_WIN2K:
+ ret = get_reply_key(context, &content, req_buffer, key);
+ if (ret != 0 && ctx->require_binding == 0)
+ ret = get_reply_key_win(context, &content, nonce, key);
+ break;
+ case PKINIT_27:
+ ret = get_reply_key(context, &content, req_buffer, key);
+ break;
+ }
+ if (ret)
+ goto out;
+
+ /* XXX compare given etype with key->etype */
+
+ out:
+ if (host)
+ _krb5_pk_cert_free(host);
+ der_free_oid(&contentType);
+ krb5_data_free(&content);
+
+ return ret;
+}
+
+/*
+ * RFC 8062 section 7:
+ *
+ * The client then decrypts the KDC contribution key and verifies that
+ * the ticket session key in the returned ticket is the combined key of
+ * the KDC contribution key and the reply key.
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_pk_kx_confirm(krb5_context context,
+ krb5_pk_init_ctx ctx,
+ krb5_keyblock *reply_key,
+ krb5_keyblock *session_key,
+ PA_DATA *pa_pkinit_kx)
+{
+ krb5_error_code ret;
+ EncryptedData ed;
+ krb5_keyblock ck, sk_verify;
+ krb5_crypto ck_crypto = NULL;
+ krb5_crypto rk_crypto = NULL;
+ size_t len;
+ krb5_data data;
+ krb5_data p1 = { sizeof("PKINIT") - 1, "PKINIT" };
+ krb5_data p2 = { sizeof("KEYEXCHANGE") - 1, "KEYEXCHANGE" };
+
+ heim_assert(ctx != NULL, "PKINIT context is non-NULL");
+ heim_assert(reply_key != NULL, "reply key is non-NULL");
+ heim_assert(session_key != NULL, "session key is non-NULL");
+
+ /* PA-PKINIT-KX is optional unless anonymous */
+ if (pa_pkinit_kx == NULL)
+ return ctx->anonymous ? KRB5_KDCREP_MODIFIED : 0;
+
+ memset(&ed, 0, sizeof(ed));
+ krb5_keyblock_zero(&ck);
+ krb5_keyblock_zero(&sk_verify);
+ krb5_data_zero(&data);
+
+ ret = decode_EncryptedData(pa_pkinit_kx->padata_value.data,
+ pa_pkinit_kx->padata_value.length,
+ &ed, &len);
+ if (ret)
+ goto out;
+
+ if (len != pa_pkinit_kx->padata_value.length) {
+ ret = KRB5_KDCREP_MODIFIED;
+ goto out;
+ }
+
+ ret = krb5_crypto_init(context, reply_key, 0, &rk_crypto);
+ if (ret)
+ goto out;
+
+ ret = krb5_decrypt_EncryptedData(context, rk_crypto,
+ KRB5_KU_PA_PKINIT_KX,
+ &ed, &data);
+ if (ret)
+ goto out;
+
+ ret = decode_EncryptionKey(data.data, data.length,
+ &ck, &len);
+ if (ret)
+ goto out;
+
+ ret = krb5_crypto_init(context, &ck, 0, &ck_crypto);
+ if (ret)
+ goto out;
+
+ ret = krb5_crypto_fx_cf2(context, ck_crypto, rk_crypto,
+ &p1, &p2, session_key->keytype,
+ &sk_verify);
+ if (ret)
+ goto out;
+
+ if (sk_verify.keytype != session_key->keytype ||
+ krb5_data_ct_cmp(&sk_verify.keyvalue, &session_key->keyvalue) != 0) {
+ ret = KRB5_KDCREP_MODIFIED;
+ goto out;
+ }
+
+out:
+ free_EncryptedData(&ed);
+ krb5_free_keyblock_contents(context, &ck);
+ krb5_free_keyblock_contents(context, &sk_verify);
+ if (ck_crypto)
+ krb5_crypto_destroy(context, ck_crypto);
+ if (rk_crypto)
+ krb5_crypto_destroy(context, rk_crypto);
+ krb5_data_free(&data);
+
+ return ret;
+}
+
+static krb5_error_code
+pk_rd_pa_reply_dh(krb5_context context,
+ const heim_octet_string *indata,
+ const heim_oid *dataType,
+ const char *realm,
+ krb5_pk_init_ctx ctx,
+ krb5_enctype etype,
+ const krb5_krbhst_info *hi,
+ const DHNonce *c_n,
+ const DHNonce *k_n,
+ unsigned nonce,
+ PA_DATA *pa,
+ krb5_keyblock **key)
+{
+ const unsigned char *p;
+ unsigned char *dh_gen_key = NULL;
+ struct krb5_pk_cert *host = NULL;
+ BIGNUM *kdc_dh_pubkey = NULL;
+ KDCDHKeyInfo kdc_dh_info;
+ heim_oid contentType = { 0, NULL };
+ krb5_data content;
+ krb5_error_code ret;
+ int dh_gen_keylen = 0;
+ size_t size;
+
+ krb5_data_zero(&content);
+ memset(&kdc_dh_info, 0, sizeof(kdc_dh_info));
+
+ if (der_heim_oid_cmp(&asn1_oid_id_pkcs7_signedData, dataType)) {
+ krb5_set_error_message(context, EINVAL,
+ N_("PKINIT: Invalid content type", ""));
+ return EINVAL;
+ }
+
+ ret = pk_verify_sign(context,
+ indata->data,
+ indata->length,
+ ctx->id,
+ &contentType,
+ &content,
+ &host);
+ if (ret)
+ goto out;
+
+ heim_assert(host || (ctx->id->flags & PKINIT_NO_KDC_ANCHOR),
+ "KDC signature must be verified unless PKINIT_NO_KDC_ANCHOR set");
+
+ if (host) {
+ /* make sure that it is the kdc's certificate */
+ ret = pk_verify_host(context, realm, hi, ctx, host);
+ if (ret)
+ goto out;
+
+ ctx->kdc_verified = 1;
+ }
+
+ if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkdhkeydata)) {
+ ret = KRB5KRB_AP_ERR_MSG_TYPE;
+ krb5_set_error_message(context, ret,
+ N_("pkinit - dh reply contains wrong oid", ""));
+ goto out;
+ }
+
+ ret = decode_KDCDHKeyInfo(content.data,
+ content.length,
+ &kdc_dh_info,
+ &size);
+
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("pkinit - failed to decode "
+ "KDC DH Key Info", ""));
+ goto out;
+ }
+
+ if (kdc_dh_info.nonce != nonce) {
+ ret = KRB5KRB_AP_ERR_MODIFIED;
+ krb5_set_error_message(context, ret,
+ N_("PKINIT: DH nonce is wrong", ""));
+ goto out;
+ }
+
+ if (kdc_dh_info.dhKeyExpiration) {
+ if (k_n == NULL) {
+ ret = KRB5KRB_ERR_GENERIC;
+ krb5_set_error_message(context, ret,
+ N_("pkinit; got key expiration "
+ "without server nonce", ""));
+ goto out;
+ }
+ if (c_n == NULL) {
+ ret = KRB5KRB_ERR_GENERIC;
+ krb5_set_error_message(context, ret,
+ N_("pkinit; got DH reuse but no "
+ "client nonce", ""));
+ goto out;
+ }
+ } else {
+ if (k_n) {
+ ret = KRB5KRB_ERR_GENERIC;
+ krb5_set_error_message(context, ret,
+ N_("pkinit: got server nonce "
+ "without key expiration", ""));
+ goto out;
+ }
+ c_n = NULL;
+ }
+
+
+ p = kdc_dh_info.subjectPublicKey.data;
+ size = (kdc_dh_info.subjectPublicKey.length + 7) / 8;
+
+ if (ctx->keyex == USE_DH) {
+ DHPublicKey k;
+ ret = decode_DHPublicKey(p, size, &k, NULL);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("pkinit: can't decode "
+ "without key expiration", ""));
+ goto out;
+ }
+
+ kdc_dh_pubkey = integer_to_BN(context, "DHPublicKey", &k);
+ free_DHPublicKey(&k);
+ if (kdc_dh_pubkey == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+
+ size = DH_size(ctx->u.dh);
+
+ dh_gen_key = malloc(size);
+ if (dh_gen_key == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ dh_gen_keylen = DH_compute_key(dh_gen_key, kdc_dh_pubkey, ctx->u.dh);
+ if (dh_gen_keylen == -1) {
+ ret = KRB5KRB_ERR_GENERIC;
+ dh_gen_keylen = 0;
+ krb5_set_error_message(context, ret,
+ N_("PKINIT: Can't compute Diffie-Hellman key", ""));
+ goto out;
+ }
+ if (dh_gen_keylen < (int)size) {
+ size -= dh_gen_keylen;
+ memmove(dh_gen_key + size, dh_gen_key, dh_gen_keylen);
+ memset(dh_gen_key, 0, size);
+ }
+
+ } else {
+ ret = _krb5_pk_rd_pa_reply_ecdh_compute_key(context, ctx, p,
+ size, &dh_gen_key,
+ &dh_gen_keylen);
+ if (ret)
+ goto out;
+ }
+
+ if (dh_gen_keylen <= 0) {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret,
+ N_("PKINIT: resulting DH key <= 0", ""));
+ dh_gen_keylen = 0;
+ goto out;
+ }
+
+ *key = malloc (sizeof (**key));
+ if (*key == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ ret = _krb5_pk_octetstring2key(context,
+ etype,
+ dh_gen_key, dh_gen_keylen,
+ c_n, k_n,
+ *key);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("PKINIT: can't create key from DH key", ""));
+ free(*key);
+ *key = NULL;
+ goto out;
+ }
+
+ out:
+ if (kdc_dh_pubkey)
+ BN_free(kdc_dh_pubkey);
+ if (dh_gen_key) {
+ memset(dh_gen_key, 0, dh_gen_keylen);
+ free(dh_gen_key);
+ }
+ if (host)
+ _krb5_pk_cert_free(host);
+ if (content.data)
+ krb5_data_free(&content);
+ der_free_oid(&contentType);
+ free_KDCDHKeyInfo(&kdc_dh_info);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_pk_rd_pa_reply(krb5_context context,
+ const char *realm,
+ void *c,
+ krb5_enctype etype,
+ const krb5_krbhst_info *hi,
+ unsigned nonce,
+ const krb5_data *req_buffer,
+ PA_DATA *pa,
+ krb5_keyblock **key)
+{
+ krb5_pk_init_ctx ctx = c;
+ krb5_error_code ret;
+ size_t size;
+
+ /* Check for IETF PK-INIT first */
+ if (ctx->type == PKINIT_27) {
+ PA_PK_AS_REP rep;
+ heim_octet_string os, data;
+ heim_oid oid;
+
+ if (pa->padata_type != KRB5_PADATA_PK_AS_REP) {
+ krb5_set_error_message(context, EINVAL,
+ N_("PKINIT: wrong padata recv", ""));
+ return EINVAL;
+ }
+
+ ret = decode_PA_PK_AS_REP(pa->padata_value.data,
+ pa->padata_value.length,
+ &rep,
+ &size);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to decode pkinit AS rep", ""));
+ return ret;
+ }
+
+ switch (rep.element) {
+ case choice_PA_PK_AS_REP_dhInfo:
+ _krb5_debug(context, 5, "krb5_get_init_creds: using pkinit dh");
+ os = rep.u.dhInfo.dhSignedData;
+ break;
+ case choice_PA_PK_AS_REP_encKeyPack:
+ _krb5_debug(context, 5, "krb5_get_init_creds: using kinit enc reply key");
+ os = rep.u.encKeyPack;
+ break;
+ default: {
+ PA_PK_AS_REP_BTMM btmm;
+ free_PA_PK_AS_REP(&rep);
+ memset(&rep, 0, sizeof(rep));
+
+ _krb5_debug(context, 5, "krb5_get_init_creds: using BTMM kinit enc reply key");
+
+ ret = decode_PA_PK_AS_REP_BTMM(pa->padata_value.data,
+ pa->padata_value.length,
+ &btmm,
+ &size);
+ if (ret) {
+ krb5_set_error_message(context, EINVAL,
+ N_("PKINIT: -27 reply "
+ "invalid content type", ""));
+ return EINVAL;
+ }
+
+ if (btmm.dhSignedData || btmm.encKeyPack == NULL) {
+ free_PA_PK_AS_REP_BTMM(&btmm);
+ ret = EINVAL;
+ krb5_set_error_message(context, ret,
+ N_("DH mode not supported for BTMM mode", ""));
+ return ret;
+ }
+
+ /*
+ * Transform to IETF style PK-INIT reply so that free works below
+ */
+
+ rep.element = choice_PA_PK_AS_REP_encKeyPack;
+ rep.u.encKeyPack.data = btmm.encKeyPack->data;
+ rep.u.encKeyPack.length = btmm.encKeyPack->length;
+ btmm.encKeyPack->data = NULL;
+ btmm.encKeyPack->length = 0;
+ free_PA_PK_AS_REP_BTMM(&btmm);
+ os = rep.u.encKeyPack;
+ }
+ }
+
+ ret = hx509_cms_unwrap_ContentInfo(&os, &oid, &data, NULL);
+ if (ret) {
+ free_PA_PK_AS_REP(&rep);
+ krb5_set_error_message(context, ret,
+ N_("PKINIT: failed to unwrap CI", ""));
+ return ret;
+ }
+
+ switch (rep.element) {
+ case choice_PA_PK_AS_REP_dhInfo:
+ ret = pk_rd_pa_reply_dh(context, &data, &oid, realm, ctx, etype, hi,
+ ctx->clientDHNonce,
+ rep.u.dhInfo.serverDHNonce,
+ nonce, pa, key);
+ break;
+ case choice_PA_PK_AS_REP_encKeyPack:
+ ret = pk_rd_pa_reply_enckey(context, PKINIT_27, &data, &oid, realm,
+ ctx, etype, hi, nonce, req_buffer, pa, key);
+ break;
+ default:
+ krb5_abortx(context, "pk-init as-rep case not possible to happen");
+ }
+ der_free_octet_string(&data);
+ der_free_oid(&oid);
+ free_PA_PK_AS_REP(&rep);
+
+ } else if (ctx->type == PKINIT_WIN2K) {
+ PA_PK_AS_REP_Win2k w2krep;
+
+ /* Check for Windows encoding of the AS-REP pa data */
+
+#if 0 /* should this be ? */
+ if (pa->padata_type != KRB5_PADATA_PK_AS_REP) {
+ krb5_set_error_message(context, EINVAL,
+ "PKINIT: wrong padata recv");
+ return EINVAL;
+ }
+#endif
+
+ memset(&w2krep, 0, sizeof(w2krep));
+
+ ret = decode_PA_PK_AS_REP_Win2k(pa->padata_value.data,
+ pa->padata_value.length,
+ &w2krep,
+ &size);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("PKINIT: Failed decoding windows "
+ "pkinit reply %d", ""), (int)ret);
+ return ret;
+ }
+
+ krb5_clear_error_message(context);
+
+ switch (w2krep.element) {
+ case choice_PA_PK_AS_REP_Win2k_encKeyPack: {
+ heim_octet_string data;
+ heim_oid oid;
+
+ ret = hx509_cms_unwrap_ContentInfo(&w2krep.u.encKeyPack,
+ &oid, &data, NULL);
+ free_PA_PK_AS_REP_Win2k(&w2krep);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("PKINIT: failed to unwrap CI", ""));
+ return ret;
+ }
+
+ ret = pk_rd_pa_reply_enckey(context, PKINIT_WIN2K, &data, &oid, realm,
+ ctx, etype, hi, nonce, req_buffer, pa, key);
+ der_free_octet_string(&data);
+ der_free_oid(&oid);
+
+ break;
+ }
+ default:
+ free_PA_PK_AS_REP_Win2k(&w2krep);
+ ret = EINVAL;
+ krb5_set_error_message(context, ret,
+ N_("PKINIT: win2k reply invalid "
+ "content type", ""));
+ break;
+ }
+
+ } else {
+ ret = EINVAL;
+ krb5_set_error_message(context, ret,
+ N_("PKINIT: unknown reply type", ""));
+ }
+
+ return ret;
+}
+
+struct prompter {
+ krb5_context context;
+ krb5_prompter_fct prompter;
+ void *prompter_data;
+};
+
+static int
+hx_pass_prompter(void *data, const hx509_prompt *prompter)
+{
+ krb5_error_code ret;
+ krb5_prompt prompt;
+ krb5_data password_data;
+ struct prompter *p = data;
+
+ password_data.data = prompter->reply.data;
+ password_data.length = prompter->reply.length;
+
+ prompt.prompt = prompter->prompt;
+ prompt.hidden = hx509_prompt_hidden(prompter->type);
+ prompt.reply = &password_data;
+
+ switch (prompter->type) {
+ case HX509_PROMPT_TYPE_INFO:
+ prompt.type = KRB5_PROMPT_TYPE_INFO;
+ break;
+ case HX509_PROMPT_TYPE_PASSWORD:
+ case HX509_PROMPT_TYPE_QUESTION:
+ default:
+ prompt.type = KRB5_PROMPT_TYPE_PASSWORD;
+ break;
+ }
+
+ ret = (*p->prompter)(p->context, p->prompter_data, NULL, NULL, 1, &prompt);
+ if (ret) {
+ memset (prompter->reply.data, 0, prompter->reply.length);
+ return 1;
+ }
+ return 0;
+}
+
+static krb5_error_code
+_krb5_pk_set_user_id(krb5_context context,
+ krb5_principal principal,
+ krb5_pk_init_ctx ctx,
+ struct hx509_certs_data *certs)
+{
+ hx509_certs c = hx509_certs_ref(certs);
+ hx509_query *q = NULL;
+ int ret;
+
+ if (ctx->id->certs)
+ hx509_certs_free(&ctx->id->certs);
+ if (ctx->id->cert) {
+ hx509_cert_free(ctx->id->cert);
+ ctx->id->cert = NULL;
+ }
+
+ ctx->id->certs = c;
+ ctx->anonymous = 0;
+
+ ret = hx509_query_alloc(context->hx509ctx, &q);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Allocate query to find signing certificate");
+ return ret;
+ }
+
+ hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
+ hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
+
+ if (principal && strncmp("LKDC:SHA1.", krb5_principal_get_realm(context, principal), 9) == 0) {
+ ctx->id->flags |= PKINIT_BTMM;
+ }
+
+ ret = find_cert(context, ctx->id, q, &ctx->id->cert);
+ hx509_query_free(context->hx509ctx, q);
+
+ if (ret == 0 && _krb5_have_debug(context, 2)) {
+ hx509_name name;
+ char *str, *sn;
+ heim_integer i;
+
+ ret = hx509_cert_get_subject(ctx->id->cert, &name);
+ if (ret)
+ goto out;
+
+ ret = hx509_name_to_string(name, &str);
+ hx509_name_free(&name);
+ if (ret)
+ goto out;
+
+ ret = hx509_cert_get_serialnumber(ctx->id->cert, &i);
+ if (ret) {
+ free(str);
+ goto out;
+ }
+
+ ret = der_print_hex_heim_integer(&i, &sn);
+ der_free_heim_integer(&i);
+ if (ret) {
+ free(str);
+ goto out;
+ }
+
+ _krb5_debug(context, 2, "using cert: subject: %s sn: %s", str, sn);
+ free(str);
+ free(sn);
+ }
+ out:
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_pk_load_id(krb5_context context,
+ struct krb5_pk_identity **ret_id,
+ const char *user_id,
+ const char *anchor_id,
+ char * const *chain_list,
+ char * const *revoke_list,
+ krb5_prompter_fct prompter,
+ void *prompter_data,
+ char *password)
+{
+ struct krb5_pk_identity *id = NULL;
+ struct prompter p;
+ krb5_error_code ret;
+
+ *ret_id = NULL;
+
+ /* load cert */
+
+ id = calloc(1, sizeof(*id));
+ if (id == NULL)
+ return krb5_enomem(context);
+
+ if (user_id) {
+ hx509_lock lock;
+
+ ret = hx509_lock_init(context->hx509ctx, &lock);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret, "Failed init lock");
+ goto out;
+ }
+
+ if (password && password[0])
+ hx509_lock_add_password(lock, password);
+
+ if (prompter) {
+ p.context = context;
+ p.prompter = prompter;
+ p.prompter_data = prompter_data;
+
+ ret = hx509_lock_set_prompter(lock, hx_pass_prompter, &p);
+ if (ret) {
+ hx509_lock_free(lock);
+ goto out;
+ }
+ }
+
+ ret = hx509_certs_init(context->hx509ctx, user_id, 0, lock, &id->certs);
+ hx509_lock_free(lock);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed to init cert certs");
+ goto out;
+ }
+ } else {
+ id->certs = NULL;
+ }
+
+ ret = hx509_certs_init(context->hx509ctx, anchor_id, 0, NULL, &id->anchors);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed to init anchors");
+ goto out;
+ }
+
+ ret = hx509_certs_init(context->hx509ctx, "MEMORY:pkinit-cert-chain",
+ 0, NULL, &id->certpool);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed to init chain");
+ goto out;
+ }
+
+ while (chain_list && *chain_list) {
+ ret = hx509_certs_append(context->hx509ctx, id->certpool,
+ NULL, *chain_list);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed to load chain %s",
+ *chain_list);
+ goto out;
+ }
+ chain_list++;
+ }
+
+ if (revoke_list) {
+ ret = hx509_revoke_init(context->hx509ctx, &id->revokectx);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed init revoke list");
+ goto out;
+ }
+
+ while (*revoke_list) {
+ ret = hx509_revoke_add_crl(context->hx509ctx,
+ id->revokectx,
+ *revoke_list);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed load revoke list");
+ goto out;
+ }
+ revoke_list++;
+ }
+ } else
+ hx509_context_set_missing_revoke(context->hx509ctx, 1);
+
+ ret = hx509_verify_init_ctx(context->hx509ctx, &id->verify_ctx);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed init verify context");
+ goto out;
+ }
+
+ hx509_verify_attach_anchors(id->verify_ctx, id->anchors);
+ hx509_verify_attach_revoke(id->verify_ctx, id->revokectx);
+
+ out:
+ if (ret) {
+ hx509_verify_destroy_ctx(id->verify_ctx);
+ hx509_certs_free(&id->certs);
+ hx509_certs_free(&id->anchors);
+ hx509_certs_free(&id->certpool);
+ hx509_revoke_free(&id->revokectx);
+ free(id);
+ } else
+ *ret_id = id;
+
+ return ret;
+}
+
+/*
+ *
+ */
+
+static void
+pk_copy_error(krb5_context context,
+ hx509_context hx509ctx,
+ int hxret,
+ const char *fmt,
+ ...)
+{
+ va_list va;
+ char *s, *f;
+ int ret;
+
+ va_start(va, fmt);
+ ret = vasprintf(&f, fmt, va);
+ va_end(va);
+ if (ret == -1 || f == NULL) {
+ krb5_clear_error_message(context);
+ return;
+ }
+
+ s = hx509_get_error_string(hx509ctx, hxret);
+ if (s == NULL) {
+ krb5_clear_error_message(context);
+ free(f);
+ return;
+ }
+ krb5_set_error_message(context, hxret, "%s: %s", f, s);
+ free(s);
+ free(f);
+}
+
+static int
+parse_integer(krb5_context context, char **p, const char *file, int lineno,
+ const char *name, heim_integer *integer)
+{
+ int ret;
+ char *p1;
+ p1 = strsep(p, " \t");
+ if (p1 == NULL) {
+ krb5_set_error_message(context, EINVAL,
+ N_("moduli file %s missing %s on line %d", ""),
+ file, name, lineno);
+ return EINVAL;
+ }
+ ret = der_parse_hex_heim_integer(p1, integer);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("moduli file %s failed parsing %s "
+ "on line %d", ""),
+ file, name, lineno);
+ return ret;
+ }
+
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_parse_moduli_line(krb5_context context,
+ const char *file,
+ int lineno,
+ char *p,
+ struct krb5_dh_moduli **m)
+{
+ struct krb5_dh_moduli *m1;
+ char *p1;
+ int ret;
+
+ *m = NULL;
+
+ m1 = calloc(1, sizeof(*m1));
+ if (m1 == NULL)
+ return krb5_enomem(context);
+
+ while (isspace((unsigned char)*p))
+ p++;
+ if (*p == '#') {
+ free(m1);
+ return 0;
+ }
+ ret = EINVAL;
+
+ p1 = strsep(&p, " \t");
+ if (p1 == NULL) {
+ krb5_set_error_message(context, ret,
+ N_("moduli file %s missing name on line %d", ""),
+ file, lineno);
+ goto out;
+ }
+ m1->name = strdup(p1);
+ if (m1->name == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ p1 = strsep(&p, " \t");
+ if (p1 == NULL) {
+ krb5_set_error_message(context, ret,
+ N_("moduli file %s missing bits on line %d", ""),
+ file, lineno);
+ goto out;
+ }
+
+ m1->bits = atoi(p1);
+ if (m1->bits == 0) {
+ krb5_set_error_message(context, ret,
+ N_("moduli file %s have un-parsable "
+ "bits on line %d", ""), file, lineno);
+ goto out;
+ }
+
+ ret = parse_integer(context, &p, file, lineno, "p", &m1->p);
+ if (ret)
+ goto out;
+ ret = parse_integer(context, &p, file, lineno, "g", &m1->g);
+ if (ret)
+ goto out;
+ ret = parse_integer(context, &p, file, lineno, "q", &m1->q);
+ if (ret) {
+ m1->q.negative = 0;
+ m1->q.length = 0;
+ m1->q.data = 0;
+ krb5_clear_error_message(context);
+ }
+
+ *m = m1;
+
+ return 0;
+ out:
+ free(m1->name);
+ der_free_heim_integer(&m1->p);
+ der_free_heim_integer(&m1->g);
+ der_free_heim_integer(&m1->q);
+ free(m1);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_free_moduli(struct krb5_dh_moduli **moduli)
+{
+ int i;
+ for (i = 0; moduli[i] != NULL; i++) {
+ free(moduli[i]->name);
+ der_free_heim_integer(&moduli[i]->p);
+ der_free_heim_integer(&moduli[i]->g);
+ der_free_heim_integer(&moduli[i]->q);
+ free(moduli[i]);
+ }
+ free(moduli);
+}
+
+static const char *default_moduli_RFC2412_MODP_group2 =
+ /* name */
+ "RFC2412-MODP-group2 "
+ /* bits */
+ "1024 "
+ /* p */
+ "FFFFFFFF" "FFFFFFFF" "C90FDAA2" "2168C234" "C4C6628B" "80DC1CD1"
+ "29024E08" "8A67CC74" "020BBEA6" "3B139B22" "514A0879" "8E3404DD"
+ "EF9519B3" "CD3A431B" "302B0A6D" "F25F1437" "4FE1356D" "6D51C245"
+ "E485B576" "625E7EC6" "F44C42E9" "A637ED6B" "0BFF5CB6" "F406B7ED"
+ "EE386BFB" "5A899FA5" "AE9F2411" "7C4B1FE6" "49286651" "ECE65381"
+ "FFFFFFFF" "FFFFFFFF "
+ /* g */
+ "02 "
+ /* q */
+ "7FFFFFFF" "FFFFFFFF" "E487ED51" "10B4611A" "62633145" "C06E0E68"
+ "94812704" "4533E63A" "0105DF53" "1D89CD91" "28A5043C" "C71A026E"
+ "F7CA8CD9" "E69D218D" "98158536" "F92F8A1B" "A7F09AB6" "B6A8E122"
+ "F242DABB" "312F3F63" "7A262174" "D31BF6B5" "85FFAE5B" "7A035BF6"
+ "F71C35FD" "AD44CFD2" "D74F9208" "BE258FF3" "24943328" "F67329C0"
+ "FFFFFFFF" "FFFFFFFF";
+
+static const char *default_moduli_rfc3526_MODP_group14 =
+ /* name */
+ "rfc3526-MODP-group14 "
+ /* bits */
+ "1760 "
+ /* p */
+ "FFFFFFFF" "FFFFFFFF" "C90FDAA2" "2168C234" "C4C6628B" "80DC1CD1"
+ "29024E08" "8A67CC74" "020BBEA6" "3B139B22" "514A0879" "8E3404DD"
+ "EF9519B3" "CD3A431B" "302B0A6D" "F25F1437" "4FE1356D" "6D51C245"
+ "E485B576" "625E7EC6" "F44C42E9" "A637ED6B" "0BFF5CB6" "F406B7ED"
+ "EE386BFB" "5A899FA5" "AE9F2411" "7C4B1FE6" "49286651" "ECE45B3D"
+ "C2007CB8" "A163BF05" "98DA4836" "1C55D39A" "69163FA8" "FD24CF5F"
+ "83655D23" "DCA3AD96" "1C62F356" "208552BB" "9ED52907" "7096966D"
+ "670C354E" "4ABC9804" "F1746C08" "CA18217C" "32905E46" "2E36CE3B"
+ "E39E772C" "180E8603" "9B2783A2" "EC07A28F" "B5C55DF0" "6F4C52C9"
+ "DE2BCBF6" "95581718" "3995497C" "EA956AE5" "15D22618" "98FA0510"
+ "15728E5A" "8AACAA68" "FFFFFFFF" "FFFFFFFF "
+ /* g */
+ "02 "
+ /* q */
+ "7FFFFFFF" "FFFFFFFF" "E487ED51" "10B4611A" "62633145" "C06E0E68"
+ "94812704" "4533E63A" "0105DF53" "1D89CD91" "28A5043C" "C71A026E"
+ "F7CA8CD9" "E69D218D" "98158536" "F92F8A1B" "A7F09AB6" "B6A8E122"
+ "F242DABB" "312F3F63" "7A262174" "D31BF6B5" "85FFAE5B" "7A035BF6"
+ "F71C35FD" "AD44CFD2" "D74F9208" "BE258FF3" "24943328" "F6722D9E"
+ "E1003E5C" "50B1DF82" "CC6D241B" "0E2AE9CD" "348B1FD4" "7E9267AF"
+ "C1B2AE91" "EE51D6CB" "0E3179AB" "1042A95D" "CF6A9483" "B84B4B36"
+ "B3861AA7" "255E4C02" "78BA3604" "650C10BE" "19482F23" "171B671D"
+ "F1CF3B96" "0C074301" "CD93C1D1" "7603D147" "DAE2AEF8" "37A62964"
+ "EF15E5FB" "4AAC0B8C" "1CCAA4BE" "754AB572" "8AE9130C" "4C7D0288"
+ "0AB9472D" "45565534" "7FFFFFFF" "FFFFFFFF";
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_parse_moduli(krb5_context context, const char *file,
+ struct krb5_dh_moduli ***moduli)
+{
+ /* name bits P G Q */
+ krb5_error_code ret;
+ struct krb5_dh_moduli **m = NULL, **m2;
+ char buf[4096];
+ FILE *f;
+ int lineno = 0, n = 0;
+
+ *moduli = NULL;
+
+ m = calloc(1, sizeof(m[0]) * 3);
+ if (m == NULL)
+ return krb5_enomem(context);
+
+ strlcpy(buf, default_moduli_rfc3526_MODP_group14, sizeof(buf));
+ ret = _krb5_parse_moduli_line(context, "builtin", 1, buf, &m[0]);
+ if (ret) {
+ _krb5_free_moduli(m);
+ return ret;
+ }
+ n++;
+
+ strlcpy(buf, default_moduli_RFC2412_MODP_group2, sizeof(buf));
+ ret = _krb5_parse_moduli_line(context, "builtin", 1, buf, &m[1]);
+ if (ret) {
+ _krb5_free_moduli(m);
+ return ret;
+ }
+ n++;
+
+
+ if (file == NULL)
+ file = MODULI_FILE;
+
+ {
+ char *exp_file;
+
+ if (_krb5_expand_path_tokens(context, file, 1, &exp_file) == 0) {
+ f = fopen(exp_file, "r");
+ krb5_xfree(exp_file);
+ } else {
+ f = NULL;
+ }
+ }
+
+ if (f == NULL) {
+ *moduli = m;
+ return 0;
+ }
+ rk_cloexec_file(f);
+
+ while(fgets(buf, sizeof(buf), f) != NULL) {
+ struct krb5_dh_moduli *element;
+
+ buf[strcspn(buf, "\n")] = '\0';
+ lineno++;
+
+ m2 = realloc(m, (n + 2) * sizeof(m[0]));
+ if (m2 == NULL) {
+ _krb5_free_moduli(m);
+ return krb5_enomem(context);
+ }
+ m = m2;
+
+ m[n] = NULL;
+
+ ret = _krb5_parse_moduli_line(context, file, lineno, buf, &element);
+ if (ret) {
+ _krb5_free_moduli(m);
+ return ret;
+ }
+ if (element == NULL)
+ continue;
+
+ m[n] = element;
+ m[n + 1] = NULL;
+ n++;
+ }
+ *moduli = m;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_dh_group_ok(krb5_context context, unsigned long bits,
+ heim_integer *p, heim_integer *g, heim_integer *q,
+ struct krb5_dh_moduli **moduli,
+ char **name)
+{
+ int i;
+
+ if (name)
+ *name = NULL;
+
+ for (i = 0; moduli[i] != NULL; i++) {
+ if (der_heim_integer_cmp(&moduli[i]->g, g) == 0 &&
+ der_heim_integer_cmp(&moduli[i]->p, p) == 0 &&
+ (q == NULL || moduli[i]->q.length == 0 ||
+ der_heim_integer_cmp(&moduli[i]->q, q) == 0))
+ {
+ if (bits && bits > moduli[i]->bits) {
+ krb5_set_error_message(context,
+ KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED,
+ N_("PKINIT: DH group parameter %s "
+ "no accepted, not enough bits "
+ "generated", ""),
+ moduli[i]->name);
+ return KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
+ }
+ if (name)
+ *name = strdup(moduli[i]->name);
+ return 0;
+ }
+ }
+ krb5_set_error_message(context,
+ KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED,
+ N_("PKINIT: DH group parameter no ok", ""));
+ return KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
+}
+#endif /* PKINIT */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_get_init_creds_opt_free_pkinit(krb5_get_init_creds_opt *opt)
+{
+#ifdef PKINIT
+ krb5_pk_init_ctx ctx;
+
+ if (opt->opt_private == NULL || opt->opt_private->pk_init_ctx == NULL)
+ return;
+ ctx = opt->opt_private->pk_init_ctx;
+ switch (ctx->keyex) {
+ case USE_DH:
+ if (ctx->u.dh)
+ DH_free(ctx->u.dh);
+ break;
+ case USE_RSA:
+ break;
+ case USE_ECDH:
+ if (ctx->u.eckey)
+ _krb5_pk_eckey_free(ctx->u.eckey);
+ break;
+ }
+ if (ctx->id) {
+ hx509_verify_destroy_ctx(ctx->id->verify_ctx);
+ hx509_certs_free(&ctx->id->certs);
+ hx509_cert_free(ctx->id->cert);
+ hx509_certs_free(&ctx->id->anchors);
+ hx509_certs_free(&ctx->id->certpool);
+
+ if (ctx->clientDHNonce) {
+ krb5_free_data(NULL, ctx->clientDHNonce);
+ ctx->clientDHNonce = NULL;
+ }
+ if (ctx->m)
+ _krb5_free_moduli(ctx->m);
+ free(ctx->id);
+ ctx->id = NULL;
+ }
+ free(opt->opt_private->pk_init_ctx);
+ opt->opt_private->pk_init_ctx = NULL;
+#endif
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_pkinit(krb5_context context,
+ krb5_get_init_creds_opt *opt,
+ krb5_principal principal,
+ const char *user_id,
+ const char *x509_anchors,
+ char * const * pool,
+ char * const * pki_revoke,
+ int flags,
+ krb5_prompter_fct prompter,
+ void *prompter_data,
+ char *password)
+{
+#ifdef PKINIT
+ krb5_error_code ret;
+ char **freeme1 = NULL;
+ char **freeme2 = NULL;
+ char *anchors = NULL;
+
+ if (opt->opt_private == NULL) {
+ krb5_set_error_message(context, EINVAL,
+ N_("PKINIT: on non extendable opt", ""));
+ return EINVAL;
+ }
+
+ opt->opt_private->pk_init_ctx =
+ calloc(1, sizeof(*opt->opt_private->pk_init_ctx));
+ if (opt->opt_private->pk_init_ctx == NULL)
+ return krb5_enomem(context);
+ opt->opt_private->pk_init_ctx->require_binding = 0;
+ opt->opt_private->pk_init_ctx->require_eku = 1;
+ opt->opt_private->pk_init_ctx->require_krbtgt_otherName = 1;
+ opt->opt_private->pk_init_ctx->peer = NULL;
+
+ /* XXX implement krb5_appdefault_strings */
+ if (pool == NULL)
+ pool = freeme1 = krb5_config_get_strings(context, NULL, "appdefaults",
+ "pkinit_pool", NULL);
+
+ if (pki_revoke == NULL)
+ pki_revoke = freeme2 = krb5_config_get_strings(context, NULL,
+ "appdefaults",
+ "pkinit_revoke", NULL);
+
+ if (x509_anchors == NULL) {
+ krb5_appdefault_string(context, "kinit",
+ krb5_principal_get_realm(context, principal),
+ "pkinit_anchors", NULL, &anchors);
+ x509_anchors = anchors;
+ }
+
+ if (flags & KRB5_GIC_OPT_PKINIT_ANONYMOUS)
+ opt->opt_private->pk_init_ctx->anonymous = 1;
+
+ if ((flags & KRB5_GIC_OPT_PKINIT_NO_KDC_ANCHOR) == 0 &&
+ x509_anchors == NULL) {
+ krb5_set_error_message(context, HEIM_PKINIT_NO_VALID_CA,
+ N_("PKINIT: No anchor given", ""));
+ return HEIM_PKINIT_NO_VALID_CA;
+ }
+
+ ret = _krb5_pk_load_id(context,
+ &opt->opt_private->pk_init_ctx->id,
+ user_id,
+ x509_anchors,
+ pool,
+ pki_revoke,
+ prompter,
+ prompter_data,
+ password);
+ krb5_config_free_strings(freeme2);
+ krb5_config_free_strings(freeme1);
+ free(anchors);
+ if (ret) {
+ free(opt->opt_private->pk_init_ctx);
+ opt->opt_private->pk_init_ctx = NULL;
+ return ret;
+ }
+ if (flags & KRB5_GIC_OPT_PKINIT_BTMM)
+ opt->opt_private->pk_init_ctx->id->flags |= PKINIT_BTMM;
+ if (principal && krb5_principal_is_lkdc(context, principal))
+ opt->opt_private->pk_init_ctx->id->flags |= PKINIT_BTMM;
+ if (flags & KRB5_GIC_OPT_PKINIT_NO_KDC_ANCHOR)
+ opt->opt_private->pk_init_ctx->id->flags |= PKINIT_NO_KDC_ANCHOR;
+
+ if (opt->opt_private->pk_init_ctx->id->certs) {
+ ret = _krb5_pk_set_user_id(context,
+ principal,
+ opt->opt_private->pk_init_ctx,
+ opt->opt_private->pk_init_ctx->id->certs);
+ if (ret) {
+ free(opt->opt_private->pk_init_ctx);
+ opt->opt_private->pk_init_ctx = NULL;
+ return ret;
+ }
+ } else
+ opt->opt_private->pk_init_ctx->id->cert = NULL;
+
+ if ((flags & KRB5_GIC_OPT_PKINIT_USE_ENCKEY) == 0) {
+ hx509_context hx509ctx = context->hx509ctx;
+ hx509_cert cert = opt->opt_private->pk_init_ctx->id->cert;
+
+ opt->opt_private->pk_init_ctx->keyex = USE_DH;
+
+ /*
+ * If its a ECDSA certs, lets select ECDSA as the keyex algorithm.
+ */
+ if (cert) {
+ AlgorithmIdentifier alg;
+
+ ret = hx509_cert_get_SPKI_AlgorithmIdentifier(hx509ctx, cert, &alg);
+ if (ret == 0) {
+ if (der_heim_oid_cmp(&alg.algorithm, &asn1_oid_id_ecPublicKey) == 0)
+ opt->opt_private->pk_init_ctx->keyex = USE_ECDH;
+ free_AlgorithmIdentifier(&alg);
+ }
+ }
+
+ } else {
+ opt->opt_private->pk_init_ctx->keyex = USE_RSA;
+
+ if (opt->opt_private->pk_init_ctx->id->certs == NULL) {
+ krb5_set_error_message(context, EINVAL,
+ N_("No anonymous pkinit support in RSA mode", ""));
+ return EINVAL;
+ }
+ }
+
+ return 0;
+#else
+ krb5_set_error_message(context, EINVAL,
+ N_("no support for PKINIT compiled in", ""));
+ return EINVAL;
+#endif
+}
+
+krb5_error_code KRB5_LIB_FUNCTION
+krb5_get_init_creds_opt_set_pkinit_user_certs(krb5_context context,
+ krb5_get_init_creds_opt *opt,
+ struct hx509_certs_data *certs)
+{
+#ifdef PKINIT
+ if (opt->opt_private == NULL) {
+ krb5_set_error_message(context, EINVAL,
+ N_("PKINIT: on non extendable opt", ""));
+ return EINVAL;
+ }
+ if (opt->opt_private->pk_init_ctx == NULL) {
+ krb5_set_error_message(context, EINVAL,
+ N_("PKINIT: on pkinit context", ""));
+ return EINVAL;
+ }
+
+ return _krb5_pk_set_user_id(context, NULL, opt->opt_private->pk_init_ctx, certs);
+#else
+ krb5_set_error_message(context, EINVAL,
+ N_("no support for PKINIT compiled in", ""));
+ return EINVAL;
+#endif
+}
+
+#ifdef PKINIT
+
+static int
+get_ms_san(hx509_context context, hx509_cert cert, char **upn)
+{
+ hx509_octet_string_list list;
+ int ret;
+
+ *upn = NULL;
+
+ ret = hx509_cert_find_subjectAltName_otherName(context,
+ cert,
+ &asn1_oid_id_pkinit_ms_san,
+ &list);
+ if (ret)
+ return 0;
+
+ if (list.len > 0 && list.val[0].length > 0)
+ ret = decode_MS_UPN_SAN(list.val[0].data, list.val[0].length,
+ upn, NULL);
+ else
+ ret = 1;
+ hx509_free_octet_string_list(&list);
+
+ return ret;
+}
+
+static int
+find_ms_san(hx509_context context, hx509_cert cert, void *ctx)
+{
+ char *upn;
+ int ret;
+
+ ret = get_ms_san(context, cert, &upn);
+ if (ret == 0)
+ free(upn);
+ return ret;
+}
+
+
+
+#endif
+
+/*
+ * Private since it need to be redesigned using krb5_get_init_creds()
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_pk_enterprise_cert(krb5_context context,
+ const char *user_id,
+ krb5_const_realm realm,
+ krb5_principal *principal,
+ struct hx509_certs_data **res)
+{
+#ifdef PKINIT
+ krb5_error_code ret;
+ hx509_certs certs, result;
+ hx509_cert cert = NULL;
+ hx509_query *q;
+ char *name;
+
+ *principal = NULL;
+ if (res)
+ *res = NULL;
+
+ if (user_id == NULL) {
+ krb5_set_error_message(context, ENOENT, "no user id");
+ return ENOENT;
+ }
+
+ ret = hx509_certs_init(context->hx509ctx, user_id, 0, NULL, &certs);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed to init cert certs");
+ goto out;
+ }
+
+ ret = hx509_query_alloc(context->hx509ctx, &q);
+ if (ret) {
+ krb5_set_error_message(context, ret, "out of memory");
+ hx509_certs_free(&certs);
+ goto out;
+ }
+
+ hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
+ hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
+ hx509_query_match_eku(q, &asn1_oid_id_pkinit_ms_eku);
+ hx509_query_match_cmp_func(q, find_ms_san, NULL);
+
+ ret = hx509_certs_filter(context->hx509ctx, certs, q, &result);
+ hx509_query_free(context->hx509ctx, q);
+ hx509_certs_free(&certs);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed to find PKINIT certificate");
+ return ret;
+ }
+
+ ret = hx509_get_one_cert(context->hx509ctx, result, &cert);
+ hx509_certs_free(&result);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed to get one cert");
+ goto out;
+ }
+
+ ret = get_ms_san(context->hx509ctx, cert, &name);
+ if (ret) {
+ pk_copy_error(context, context->hx509ctx, ret,
+ "Failed to get MS SAN");
+ goto out;
+ }
+
+ ret = krb5_make_principal(context, principal, realm, name, NULL);
+ free(name);
+ if (ret)
+ goto out;
+
+ krb5_principal_set_type(context, *principal, KRB5_NT_ENTERPRISE_PRINCIPAL);
+
+ if (res) {
+ ret = hx509_certs_init(context->hx509ctx, "MEMORY:", 0, NULL, res);
+ if (ret)
+ goto out;
+
+ ret = hx509_certs_add(context->hx509ctx, *res, cert);
+ if (ret) {
+ hx509_certs_free(res);
+ goto out;
+ }
+ }
+
+ out:
+ hx509_cert_free(cert);
+
+ return ret;
+#else
+ krb5_set_error_message(context, EINVAL,
+ N_("no support for PKINIT compiled in", ""));
+ return EINVAL;
+#endif
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+_krb5_pk_is_kdc_verified(krb5_context context,
+ krb5_get_init_creds_opt *opt)
+{
+ if (opt == NULL ||
+ opt->opt_private == NULL ||
+ opt->opt_private->pk_init_ctx == NULL)
+ return FALSE;
+
+ return opt->opt_private->pk_init_ctx->kdc_verified;
+}
diff --git a/third_party/heimdal/lib/krb5/plugin.c b/third_party/heimdal/lib/krb5/plugin.c
new file mode 100644
index 0000000..2dc22d1
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/plugin.c
@@ -0,0 +1,208 @@
+/*
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2018 AuriStor, Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include "common_plugin.h"
+
+/*
+ * Definitions:
+ *
+ * module - a category of plugin module, identified by subsystem
+ * (typically "krb5")
+ * dso - a library for a module containing a map of plugin
+ * types to plugins (e.g. "service_locator")
+ * plugin - a set of callbacks and state that follows the
+ * common plugin module definition (version, init, fini)
+ *
+ * Obviously it would have been clearer to use the term "module" rather than
+ * "DSO" given there is an internal "DSO", but "module" was already taken...
+ *
+ * modules := { module: dsos }
+ * dsos := { path, dsohandle, plugins-by-name }
+ * plugins-by-name := { plugin-name: [plug] }
+ * plug := { ftable, ctx }
+ *
+ * Some existing plugin consumers outside libkrb5 use the "krb5" module
+ * namespace, but going forward the module should match the consumer library
+ * name (e.g. libhdb should use the "hdb" module rather than "krb5").
+ */
+
+/**
+ * Register a plugin symbol name of specific type.
+ * @param context a Keberos context
+ * @param type type of plugin symbol
+ * @param name name of plugin symbol
+ * @param symbol a pointer to the named symbol
+ * @return In case of error a non zero error com_err error is returned
+ * and the Kerberos error string is set.
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_plugin_register(krb5_context context,
+ enum krb5_plugin_type type,
+ const char *name,
+ void *symbol)
+{
+ /*
+ * It's not clear that PLUGIN_TYPE_FUNC was ever used or supported. It likely
+ * would have caused _krb5_plugin_run_f() to crash as the previous implementation
+ * assumed PLUGIN_TYPE_DATA.
+ */
+ if (type != PLUGIN_TYPE_DATA) {
+ krb5_warnx(context, "krb5_plugin_register: PLUGIN_TYPE_DATA no longer supported");
+ return EINVAL;
+ }
+
+ return heim_plugin_register(context->hcontext, (heim_pcontext)context,
+ "krb5", name, symbol);
+}
+
+/**
+ * Load plugins (new system) for the given module @name (typically
+ * "krb5") from the given directory @paths.
+ *
+ * Inputs:
+ *
+ * @context A krb5_context
+ * @name Name of plugin module (typically "krb5")
+ * @paths Array of directory paths where to look
+ */
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_load_plugins(krb5_context context, const char *name, const char **paths)
+{
+ heim_load_plugins(context->hcontext, name, paths);
+}
+
+/**
+ * Unload plugins (new system)
+ */
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_unload_plugins(krb5_context context, const char *name)
+{
+ heim_unload_plugins(context->hcontext, name);
+}
+
+/**
+ * Run plugins for the given @module (e.g., "krb5") and @name (e.g.,
+ * "kuserok"). Specifically, the @func is invoked once per-plugin with
+ * four arguments: the @context, the plugin symbol value (a pointer to a
+ * struct whose first three fields are the same as common_plugin_ftable),
+ * a context value produced by the plugin's init method, and @userctx.
+ *
+ * @func should unpack arguments for a plugin function and invoke it
+ * with arguments taken from @userctx. @func should save plugin
+ * outputs, if any, in @userctx.
+ *
+ * All loaded and registered plugins are invoked via @func until @func
+ * returns something other than KRB5_PLUGIN_NO_HANDLE. Plugins that
+ * have nothing to do for the given arguments should return
+ * KRB5_PLUGIN_NO_HANDLE.
+ *
+ * Inputs:
+ *
+ * @context A krb5_context
+ * @module Name of module (typically "krb5")
+ * @name Name of pluggable interface (e.g., "kuserok")
+ * @min_version Lowest acceptable plugin minor version number
+ * @flags Flags (none defined at this time)
+ * @userctx Callback data for the callback function @func
+ * @func A callback function, invoked once per-plugin
+ *
+ * Outputs: None, other than the return value and such outputs as are
+ * gathered by @func.
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_plugin_run_f(krb5_context context,
+ struct heim_plugin_data *caller,
+ int flags,
+ void *userctx,
+ krb5_error_code (KRB5_LIB_CALL *func)(krb5_context, const void *, void *, void *))
+{
+ int32_t (HEIM_LIB_CALL *func2)(void *, const void *, void *, void *) = (void *)func;
+ return heim_plugin_run_f(context->hcontext, (heim_pcontext)context, caller,
+ flags, KRB5_PLUGIN_NO_HANDLE, userctx, func2);
+}
+
+/**
+ * Return a cookie identifying this instance of a library.
+ *
+ * Inputs:
+ *
+ * @context A krb5_context
+ * @module Our library name or a library we depend on
+ *
+ * Outputs: The instance cookie
+ *
+ * @ingroup krb5_support
+ */
+
+#ifdef WIN32
+static uintptr_t
+djb2(uintptr_t hash, unsigned char *str)
+{
+ int c;
+
+ while (c = *str++)
+ hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
+
+ return hash;
+}
+#endif
+
+KRB5_LIB_FUNCTION uintptr_t KRB5_LIB_CALL
+krb5_get_instance(const char *libname)
+{
+#ifdef WIN32
+ char *version;
+ char *name;
+ uintptr_t instance;
+
+ if (win32_getLibraryVersion("heimdal", &name, &version))
+ return 0;
+ instance = djb2(5381, name);
+ instance = djb2(instance, version);
+ free(name);
+ free(version);
+ return instance;
+#else
+ static const char *instance = "libkrb5";
+
+ if (strcmp(libname, "krb5") == 0)
+ return (uintptr_t)instance;
+ return 0;
+#endif
+}
diff --git a/third_party/heimdal/lib/krb5/principal.c b/third_party/heimdal/lib/krb5/principal.c
new file mode 100644
index 0000000..9174348
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/principal.c
@@ -0,0 +1,2205 @@
+/*
+ * Copyright (c) 1997-2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/**
+ * @page krb5_principal_intro The principal handing functions.
+ *
+ * A Kerberos principal is a email address looking string that
+ * contains two parts separated by @. The second part is the kerberos
+ * realm the principal belongs to and the first is a list of 0 or
+ * more components. For example
+ * @verbatim
+lha@SU.SE
+host/hummel.it.su.se@SU.SE
+host/admin@H5L.ORG
+@endverbatim
+ *
+ * See the library functions here: @ref krb5_principal
+ */
+
+#include "krb5_locl.h"
+#ifdef HAVE_RES_SEARCH
+#define USE_RESOLVER
+#endif
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+#include <fnmatch.h>
+#include "resolve.h"
+
+#define princ_num_comp(P) ((P)->name.name_string.len)
+#define princ_type(P) ((P)->name.name_type)
+#define princ_comp(P) ((P)->name.name_string.val)
+#define princ_ncomp(P, N) ((P)->name.name_string.val[(N)])
+#define princ_realm(P) ((P)->realm)
+
+static krb5_error_code
+set_default_princ_type(krb5_principal p, NAME_TYPE defnt)
+{
+ if (princ_num_comp(p) > 1 && strcmp(princ_ncomp(p, 0), KRB5_TGS_NAME) == 0)
+ princ_type(p) = KRB5_NT_SRV_INST;
+ else if (princ_num_comp(p) > 1 && strcmp(princ_ncomp(p, 0), "host") == 0)
+ princ_type(p) = KRB5_NT_SRV_HST;
+ else if (princ_num_comp(p) > 1 && strcmp(princ_ncomp(p, 0), "kca_service") == 0)
+ princ_type(p) = KRB5_NT_SRV_HST;
+ else if (princ_num_comp(p) == 2 &&
+ strcmp(princ_ncomp(p, 0), KRB5_WELLKNOWN_NAME) == 0)
+ princ_type(p) = KRB5_NT_WELLKNOWN;
+ else if (princ_num_comp(p) == 1 && strchr(princ_ncomp(p, 0), '@') != NULL)
+ princ_type(p) = KRB5_NT_SMTP_NAME;
+ else
+ princ_type(p) = defnt;
+ return 0;
+}
+
+static krb5_error_code append_component(krb5_context, krb5_principal,
+ const char *, size_t);
+
+/**
+ * Frees a Kerberos principal allocated by the library with
+ * krb5_parse_name(), krb5_make_principal() or any other related
+ * principal functions.
+ *
+ * @param context A Kerberos context.
+ * @param p a principal to free.
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_principal(krb5_context context,
+ krb5_principal p)
+{
+ if(p){
+ if (p->nameattrs && p->nameattrs->pac)
+ heim_release(p->nameattrs->pac);
+ free_Principal(p);
+ free(p);
+ }
+}
+
+/**
+ * Set the type of the principal
+ *
+ * @param context A Kerberos context.
+ * @param principal principal to set the type for
+ * @param type the new type
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_principal_set_type(krb5_context context,
+ krb5_principal principal,
+ int type)
+{
+ princ_type(principal) = type;
+}
+
+/**
+ * Get the type of the principal
+ *
+ * @param context A Kerberos context.
+ * @param principal principal to get the type for
+ *
+ * @return the type of principal
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_principal_get_type(krb5_context context,
+ krb5_const_principal principal)
+{
+ return princ_type(principal);
+}
+
+/**
+ * Get the realm of the principal
+ *
+ * @param context A Kerberos context.
+ * @param principal principal to get the realm for
+ *
+ * @return realm of the principal, don't free or use after krb5_principal is freed
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_principal_get_realm(krb5_context context,
+ krb5_const_principal principal)
+{
+ return princ_realm(principal);
+}
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_principal_get_comp_string(krb5_context context,
+ krb5_const_principal principal,
+ unsigned int component)
+{
+ if(component >= princ_num_comp(principal))
+ return NULL;
+ return princ_ncomp(principal, component);
+}
+
+/**
+ * Get number of component is principal.
+ *
+ * @param context Kerberos 5 context
+ * @param principal principal to query
+ *
+ * @return number of components in string
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION unsigned int KRB5_LIB_CALL
+krb5_principal_get_num_comp(krb5_context context,
+ krb5_const_principal principal)
+{
+ return princ_num_comp(principal);
+}
+
+/**
+ * Parse a name into a krb5_principal structure, flags controls the behavior.
+ *
+ * @param context Kerberos 5 context
+ * @param name name to parse into a Kerberos principal
+ * @param flags flags to control the behavior
+ * @param principal returned principal, free with krb5_free_principal().
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_parse_name_flags(krb5_context context,
+ const char *name,
+ int flags,
+ krb5_principal *principal)
+{
+ krb5_error_code ret;
+ heim_general_string *comp;
+ heim_general_string realm = NULL;
+ int ncomp;
+
+ const char *p;
+ char *q;
+ char *s;
+ char *start;
+
+ int n;
+ char c;
+ int got_realm = 0;
+ int first_at = 1;
+ int no_realm = flags & KRB5_PRINCIPAL_PARSE_NO_REALM;
+ int require_realm = flags & KRB5_PRINCIPAL_PARSE_REQUIRE_REALM;
+ int enterprise = flags & KRB5_PRINCIPAL_PARSE_ENTERPRISE;
+ int ignore_realm = flags & KRB5_PRINCIPAL_PARSE_IGNORE_REALM;
+ int no_def_realm = flags & KRB5_PRINCIPAL_PARSE_NO_DEF_REALM;
+
+ *principal = NULL;
+
+ if (no_realm && require_realm) {
+ krb5_set_error_message(context, EINVAL,
+ N_("Can't require both realm and "
+ "no realm at the same time", ""));
+ return EINVAL;
+ }
+
+ /* count number of component,
+ * enterprise names only have one component
+ */
+ ncomp = 1;
+ if (!enterprise) {
+ for (p = name; *p; p++) {
+ if (*p=='\\') {
+ if (!p[1]) {
+ krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
+ N_("trailing \\ in principal name", ""));
+ return KRB5_PARSE_MALFORMED;
+ }
+ p++;
+ } else if (*p == '/')
+ ncomp++;
+ else if (*p == '@')
+ break;
+ }
+ }
+ comp = calloc(ncomp, sizeof(*comp));
+ if (comp == NULL)
+ return krb5_enomem(context);
+
+ n = 0;
+ p = start = q = s = strdup(name);
+ if (start == NULL) {
+ free(comp);
+ return krb5_enomem(context);
+ }
+ while (*p) {
+ c = *p++;
+ if (c == '\\') {
+ c = *p++;
+ if (c == 'n')
+ c = '\n';
+ else if (c == 't')
+ c = '\t';
+ else if (c == 'b')
+ c = '\b';
+ else if (c == '0') {
+ /*
+ * We'll ignore trailing embedded NULs in components and
+ * realms, but can't support any other embedded NULs.
+ */
+ while (*p) {
+ if ((*p == '/' || *p == '@') && !got_realm)
+ break;
+ if (*(p++) != '\\' || *(p++) != '0') {
+ ret = KRB5_PARSE_MALFORMED;
+ krb5_set_error_message(context, ret,
+ N_("embedded NULs in principal "
+ "name not supported", ""));
+ goto exit;
+ }
+ }
+ continue;
+ } else if (c == '\0') {
+ ret = KRB5_PARSE_MALFORMED;
+ krb5_set_error_message(context, ret,
+ N_("trailing \\ in principal name", ""));
+ goto exit;
+ }
+ } else if (enterprise && first_at) {
+ if (c == '@')
+ first_at = 0;
+ } else if ((c == '/' && !enterprise) || c == '@') {
+ if (got_realm) {
+ ret = KRB5_PARSE_MALFORMED;
+ krb5_set_error_message(context, ret,
+ N_("part after realm in principal name", ""));
+ goto exit;
+ } else {
+ comp[n] = malloc(q - start + 1);
+ if (comp[n] == NULL) {
+ ret = krb5_enomem(context);
+ goto exit;
+ }
+ memcpy(comp[n], start, q - start);
+ comp[n][q - start] = 0;
+ n++;
+ }
+ if (c == '@')
+ got_realm = 1;
+ start = q;
+ continue;
+ }
+ if (got_realm && (c == '/' || c == '\0')) {
+ ret = KRB5_PARSE_MALFORMED;
+ krb5_set_error_message(context, ret,
+ N_("part after realm in principal name", ""));
+ goto exit;
+ }
+ *q++ = c;
+ }
+ if (got_realm) {
+ if (no_realm) {
+ ret = KRB5_PARSE_MALFORMED;
+ krb5_set_error_message(context, ret,
+ N_("realm found in 'short' principal "
+ "expected to be without one", ""));
+ goto exit;
+ }
+ if (!ignore_realm) {
+ realm = malloc(q - start + 1);
+ if (realm == NULL) {
+ ret = krb5_enomem(context);
+ goto exit;
+ }
+ memcpy(realm, start, q - start);
+ realm[q - start] = 0;
+ }
+ } else {
+ if (require_realm) {
+ ret = KRB5_PARSE_MALFORMED;
+ krb5_set_error_message(context, ret,
+ N_("realm NOT found in principal "
+ "expected to be with one", ""));
+ goto exit;
+ } else if (no_realm || no_def_realm) {
+ realm = NULL;
+ } else {
+ ret = krb5_get_default_realm(context, &realm);
+ if (ret)
+ goto exit;
+ }
+
+ comp[n] = malloc(q - start + 1);
+ if (comp[n] == NULL) {
+ ret = krb5_enomem(context);
+ goto exit;
+ }
+ memcpy(comp[n], start, q - start);
+ comp[n][q - start] = 0;
+ n++;
+ }
+ *principal = calloc(1, sizeof(**principal));
+ if (*principal == NULL) {
+ ret = krb5_enomem(context);
+ goto exit;
+ }
+ (*principal)->name.name_string.val = comp;
+ princ_num_comp(*principal) = n;
+ (*principal)->realm = realm;
+ if (enterprise)
+ princ_type(*principal) = KRB5_NT_ENTERPRISE_PRINCIPAL;
+ else
+ set_default_princ_type(*principal, KRB5_NT_PRINCIPAL);
+ free(s);
+ return 0;
+exit:
+ while (n>0) {
+ free(comp[--n]);
+ }
+ free(comp);
+ krb5_free_default_realm(context, realm);
+ free(s);
+ return ret;
+}
+
+/**
+ * Parse a name into a krb5_principal structure
+ *
+ * @param context Kerberos 5 context
+ * @param name name to parse into a Kerberos principal
+ * @param principal returned principal, free with krb5_free_principal().
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_parse_name(krb5_context context,
+ const char *name,
+ krb5_principal *principal)
+{
+ return krb5_parse_name_flags(context, name, 0, principal);
+}
+
+static const char quotable_chars[] = " \n\t\b\\/@";
+static const char replace_chars[] = " ntb\\/@";
+
+#define add_char(BASE, INDEX, LEN, C) do { if((INDEX) < (LEN)) (BASE)[(INDEX)++] = (C); }while(0);
+
+static size_t
+quote_string(const char *s, char *out, size_t idx, size_t len, int display)
+{
+ const char *p, *q;
+ for(p = s; *p && idx < len; p++){
+ q = strchr(quotable_chars, *p);
+ if (q && display) {
+ add_char(out, idx, len, replace_chars[q - quotable_chars]);
+ } else if (q) {
+ add_char(out, idx, len, '\\');
+ add_char(out, idx, len, replace_chars[q - quotable_chars]);
+ }else
+ add_char(out, idx, len, *p);
+ }
+ if(idx < len)
+ out[idx] = '\0';
+ return idx;
+}
+
+
+static krb5_error_code
+unparse_name_fixed(krb5_context context,
+ krb5_const_principal principal,
+ char *name,
+ size_t len,
+ int flags)
+{
+ size_t idx = 0;
+ size_t i;
+ int short_form = (flags & KRB5_PRINCIPAL_UNPARSE_SHORT) != 0;
+ int no_realm = (flags & KRB5_PRINCIPAL_UNPARSE_NO_REALM) != 0;
+ int display = (flags & KRB5_PRINCIPAL_UNPARSE_DISPLAY) != 0;
+
+ if (name == NULL) {
+ krb5_set_error_message(context, EINVAL,
+ N_("Invalid name buffer, "
+ "can't unparse", ""));
+ return EINVAL;
+ }
+
+ if (len == 0) {
+ krb5_set_error_message(context, ERANGE,
+ N_("Invalid name buffer length, "
+ "can't unparse", ""));
+ return ERANGE;
+ }
+
+ name[0] = '\0';
+
+ if (!no_realm && princ_realm(principal) == NULL) {
+ krb5_set_error_message(context, ERANGE,
+ N_("Realm missing from principal, "
+ "can't unparse", ""));
+ return ERANGE;
+ }
+
+ for(i = 0; i < princ_num_comp(principal); i++){
+ if(i)
+ add_char(name, idx, len, '/');
+ idx = quote_string(princ_ncomp(principal, i), name, idx, len, display);
+ if(idx == len) {
+ krb5_set_error_message(context, ERANGE,
+ N_("Out of space printing principal", ""));
+ return ERANGE;
+ }
+ }
+ /* add realm if different from default realm */
+ if(short_form && !no_realm) {
+ krb5_realm r;
+ krb5_error_code ret;
+ ret = krb5_get_default_realm(context, &r);
+ if(ret)
+ return ret;
+ if(strcmp(princ_realm(principal), r) != 0)
+ short_form = 0;
+ krb5_free_default_realm(context, r);
+ }
+ if(!short_form && !no_realm) {
+ add_char(name, idx, len, '@');
+ idx = quote_string(princ_realm(principal), name, idx, len, display);
+ if(idx == len) {
+ krb5_set_error_message(context, ERANGE,
+ N_("Out of space printing "
+ "realm of principal", ""));
+ return ERANGE;
+ }
+ }
+ return 0;
+}
+
+/**
+ * Unparse the principal name to a fixed buffer
+ *
+ * @param context A Kerberos context.
+ * @param principal principal to unparse
+ * @param name buffer to write name to
+ * @param len length of buffer
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_unparse_name_fixed(krb5_context context,
+ krb5_const_principal principal,
+ char *name,
+ size_t len)
+{
+ return unparse_name_fixed(context, principal, name, len, 0);
+}
+
+/**
+ * Unparse the principal name to a fixed buffer. The realm is skipped
+ * if its a default realm.
+ *
+ * @param context A Kerberos context.
+ * @param principal principal to unparse
+ * @param name buffer to write name to
+ * @param len length of buffer
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_unparse_name_fixed_short(krb5_context context,
+ krb5_const_principal principal,
+ char *name,
+ size_t len)
+{
+ return unparse_name_fixed(context, principal, name, len,
+ KRB5_PRINCIPAL_UNPARSE_SHORT);
+}
+
+/**
+ * Unparse the principal name with unparse flags to a fixed buffer.
+ *
+ * @param context A Kerberos context.
+ * @param principal principal to unparse
+ * @param flags unparse flags
+ * @param name buffer to write name to
+ * @param len length of buffer
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_unparse_name_fixed_flags(krb5_context context,
+ krb5_const_principal principal,
+ int flags,
+ char *name,
+ size_t len)
+{
+ return unparse_name_fixed(context, principal, name, len, flags);
+}
+
+static krb5_error_code
+unparse_name(krb5_context context,
+ krb5_const_principal principal,
+ char **name,
+ int flags)
+{
+ size_t len = 0, plen;
+ size_t i;
+ krb5_error_code ret;
+ /* count length */
+ if (princ_realm(principal)) {
+ plen = strlen(princ_realm(principal));
+
+ if(strcspn(princ_realm(principal), quotable_chars) == plen)
+ len += plen;
+ else
+ len += 2*plen;
+ len++; /* '@' */
+ }
+ for(i = 0; i < princ_num_comp(principal); i++){
+ plen = strlen(princ_ncomp(principal, i));
+ if(strcspn(princ_ncomp(principal, i), quotable_chars) == plen)
+ len += plen;
+ else
+ len += 2*plen;
+ len++;
+ }
+ len++; /* '\0' */
+ *name = malloc(len);
+ if(*name == NULL)
+ return krb5_enomem(context);
+ ret = unparse_name_fixed(context, principal, *name, len, flags);
+ if(ret) {
+ free(*name);
+ *name = NULL;
+ }
+ return ret;
+}
+
+/**
+ * Unparse the Kerberos name into a string
+ *
+ * @param context Kerberos 5 context
+ * @param principal principal to query
+ * @param name resulting string, free with krb5_xfree()
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_unparse_name(krb5_context context,
+ krb5_const_principal principal,
+ char **name)
+{
+ return unparse_name(context, principal, name, 0);
+}
+
+/**
+ * Unparse the Kerberos name into a string
+ *
+ * @param context Kerberos 5 context
+ * @param principal principal to query
+ * @param flags flag to determine the behavior
+ * @param name resulting string, free with krb5_xfree()
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_unparse_name_flags(krb5_context context,
+ krb5_const_principal principal,
+ int flags,
+ char **name)
+{
+ return unparse_name(context, principal, name, flags);
+}
+
+/**
+ * Unparse the principal name to a allocated buffer. The realm is
+ * skipped if its a default realm.
+ *
+ * @param context A Kerberos context.
+ * @param principal principal to unparse
+ * @param name returned buffer, free with krb5_xfree()
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_unparse_name_short(krb5_context context,
+ krb5_const_principal principal,
+ char **name)
+{
+ return unparse_name(context, principal, name, KRB5_PRINCIPAL_UNPARSE_SHORT);
+}
+
+/**
+ * Set a new realm for a principal, and as a side-effect free the
+ * previous realm.
+ *
+ * @param context A Kerberos context.
+ * @param principal principal set the realm for
+ * @param realm the new realm to set
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_principal_set_realm(krb5_context context,
+ krb5_principal principal,
+ krb5_const_realm realm)
+{
+ if (princ_realm(principal))
+ free(princ_realm(principal));
+
+ if (realm == NULL)
+ princ_realm(principal) = NULL;
+ else if ((princ_realm(principal) = strdup(realm)) == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_principal_set_comp_string(krb5_context context,
+ krb5_principal principal,
+ unsigned int k,
+ const char *component)
+{
+ char *s;
+ size_t i;
+
+ for (i = princ_num_comp(principal); i <= k; i++)
+ append_component(context, principal, "", 0);
+ s = strdup(component);
+ if (s == NULL)
+ return krb5_enomem(context);
+ free(princ_ncomp(principal, k));
+ princ_ncomp(principal, k) = s;
+ return 0;
+}
+
+#ifndef HEIMDAL_SMALLER
+/**
+ * Build a principal using vararg style building
+ *
+ * @param context A Kerberos context.
+ * @param principal returned principal
+ * @param rlen length of realm
+ * @param realm realm name
+ * @param ... a list of components ended with NULL.
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_build_principal(krb5_context context,
+ krb5_principal *principal,
+ int rlen,
+ krb5_const_realm realm,
+ ...)
+{
+ krb5_error_code ret;
+ va_list ap;
+ va_start(ap, realm);
+ ret = krb5_build_principal_va(context, principal, rlen, realm, ap);
+ va_end(ap);
+ return ret;
+}
+#endif
+
+/**
+ * Build a principal using vararg style building
+ *
+ * @param context A Kerberos context.
+ * @param principal returned principal
+ * @param realm realm name
+ * @param ... a list of components ended with NULL.
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+/* coverity[+alloc : arg-*1] */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_make_principal(krb5_context context,
+ krb5_principal *principal,
+ krb5_const_realm realm,
+ ...)
+{
+ krb5_error_code ret;
+ krb5_realm r = NULL;
+ va_list ap;
+
+ *principal = NULL;
+
+ if(realm == NULL) {
+ ret = krb5_get_default_realm(context, &r);
+ if(ret)
+ return ret;
+ realm = r;
+ }
+ va_start(ap, realm);
+ ret = krb5_build_principal_va(context, principal, strlen(realm), realm, ap);
+ va_end(ap);
+ if(r)
+ krb5_free_default_realm(context, r);
+ return ret;
+}
+
+static krb5_error_code
+append_component(krb5_context context, krb5_principal p,
+ const char *comp,
+ size_t comp_len)
+{
+ heim_general_string *tmp;
+ size_t len = princ_num_comp(p);
+
+ tmp = realloc(princ_comp(p), (len + 1) * sizeof(*tmp));
+ if(tmp == NULL)
+ return krb5_enomem(context);
+ princ_comp(p) = tmp;
+ princ_ncomp(p, len) = malloc(comp_len + 1);
+ if (princ_ncomp(p, len) == NULL)
+ return krb5_enomem(context);
+ memcpy (princ_ncomp(p, len), comp, comp_len);
+ princ_ncomp(p, len)[comp_len] = '\0';
+ princ_num_comp(p)++;
+ return 0;
+}
+
+static krb5_error_code
+va_ext_princ(krb5_context context, krb5_principal p, va_list ap)
+{
+ krb5_error_code ret = 0;
+
+ while (1){
+ const char *s;
+ int len;
+
+ if ((len = va_arg(ap, int)) == 0)
+ break;
+ s = va_arg(ap, const char*);
+ if ((ret = append_component(context, p, s, len)) != 0)
+ break;
+ }
+ return ret;
+}
+
+static krb5_error_code
+va_princ(krb5_context context, krb5_principal p, va_list ap)
+{
+ krb5_error_code ret = 0;
+
+ while (1){
+ const char *s;
+
+ if ((s = va_arg(ap, const char*)) == NULL)
+ break;
+ if ((ret = append_component(context, p, s, strlen(s))) != 0)
+ break;
+ }
+ return ret;
+}
+
+static krb5_error_code
+build_principal(krb5_context context,
+ krb5_principal *principal,
+ int rlen,
+ krb5_const_realm realm,
+ krb5_error_code (*func)(krb5_context, krb5_principal, va_list),
+ va_list ap)
+{
+ krb5_error_code ret;
+ krb5_principal p;
+
+ *principal = NULL;
+ p = calloc(1, sizeof(*p));
+ if (p == NULL)
+ return krb5_enomem(context);
+
+ princ_realm(p) = strdup(realm);
+ if (p->realm == NULL) {
+ free(p);
+ return krb5_enomem(context);
+ }
+
+ ret = func(context, p, ap);
+ if (ret == 0) {
+ *principal = p;
+ set_default_princ_type(p, KRB5_NT_PRINCIPAL);
+ } else
+ krb5_free_principal(context, p);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_build_principal_va(krb5_context context,
+ krb5_principal *principal,
+ int rlen,
+ krb5_const_realm realm,
+ va_list ap)
+{
+ return build_principal(context, principal, rlen, realm, va_princ, ap);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_build_principal_va_ext(krb5_context context,
+ krb5_principal *principal,
+ int rlen,
+ krb5_const_realm realm,
+ va_list ap)
+{
+ return build_principal(context, principal, rlen, realm, va_ext_princ, ap);
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_build_principal_ext(krb5_context context,
+ krb5_principal *principal,
+ int rlen,
+ krb5_const_realm realm,
+ ...)
+{
+ krb5_error_code ret;
+ va_list ap;
+ va_start(ap, realm);
+ ret = krb5_build_principal_va_ext(context, principal, rlen, realm, ap);
+ va_end(ap);
+ return ret;
+}
+
+/**
+ * Copy a principal
+ *
+ * @param context A Kerberos context.
+ * @param inprinc principal to copy
+ * @param outprinc copied principal, free with krb5_free_principal()
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_principal(krb5_context context,
+ krb5_const_principal inprinc,
+ krb5_principal *outprinc)
+{
+ krb5_principal p;
+
+ *outprinc = NULL;
+
+ p = malloc(sizeof(*p));
+ if (p == NULL)
+ return krb5_enomem(context);
+ if(copy_Principal(inprinc, p)) {
+ free(p);
+ return krb5_enomem(context);
+ }
+ if (inprinc->nameattrs && inprinc->nameattrs->pac)
+ p->nameattrs->pac = heim_retain(inprinc->nameattrs->pac);
+
+ *outprinc = p;
+ return 0;
+}
+
+/**
+ * Return TRUE iff princ1 == princ2 (without considering the realm)
+ *
+ * @param context Kerberos 5 context
+ * @param princ1 first principal to compare
+ * @param princ2 second principal to compare
+ *
+ * @return non zero if equal, 0 if not
+ *
+ * @ingroup krb5_principal
+ * @see krb5_principal_compare()
+ * @see krb5_realm_compare()
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_principal_compare_any_realm(krb5_context context,
+ krb5_const_principal princ1,
+ krb5_const_principal princ2)
+{
+ size_t i;
+ if(princ_num_comp(princ1) != princ_num_comp(princ2))
+ return FALSE;
+ for(i = 0; i < princ_num_comp(princ1); i++){
+ if(strcmp(princ_ncomp(princ1, i), princ_ncomp(princ2, i)) != 0)
+ return FALSE;
+ }
+ return TRUE;
+}
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+_krb5_principal_compare_PrincipalName(krb5_context context,
+ krb5_const_principal princ1,
+ PrincipalName *princ2)
+{
+ size_t i;
+ if (princ_num_comp(princ1) != princ2->name_string.len)
+ return FALSE;
+ for(i = 0; i < princ_num_comp(princ1); i++){
+ if(strcmp(princ_ncomp(princ1, i), princ2->name_string.val[i]) != 0)
+ return FALSE;
+ }
+ return TRUE;
+}
+
+
+/**
+ * Compares the two principals, including realm of the principals and returns
+ * TRUE if they are the same and FALSE if not.
+ *
+ * @param context Kerberos 5 context
+ * @param princ1 first principal to compare
+ * @param princ2 second principal to compare
+ *
+ * @ingroup krb5_principal
+ * @see krb5_principal_compare_any_realm()
+ * @see krb5_realm_compare()
+ */
+
+/*
+ * return TRUE iff princ1 == princ2
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_principal_compare(krb5_context context,
+ krb5_const_principal princ1,
+ krb5_const_principal princ2)
+{
+ if (!krb5_realm_compare(context, princ1, princ2))
+ return FALSE;
+ return krb5_principal_compare_any_realm(context, princ1, princ2);
+}
+
+/**
+ * return TRUE iff realm(princ1) == realm(princ2)
+ *
+ * @param context Kerberos 5 context
+ * @param princ1 first principal to compare
+ * @param princ2 second principal to compare
+ *
+ * @ingroup krb5_principal
+ * @see krb5_principal_compare_any_realm()
+ * @see krb5_principal_compare()
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_realm_compare(krb5_context context,
+ krb5_const_principal princ1,
+ krb5_const_principal princ2)
+{
+ return strcmp(princ_realm(princ1), princ_realm(princ2)) == 0;
+}
+
+/**
+ * return TRUE iff princ matches pattern
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_principal_match(krb5_context context,
+ krb5_const_principal princ,
+ krb5_const_principal pattern)
+{
+ size_t i;
+ if(princ_num_comp(princ) != princ_num_comp(pattern))
+ return FALSE;
+ if(fnmatch(princ_realm(pattern), princ_realm(princ), 0) != 0)
+ return FALSE;
+ for(i = 0; i < princ_num_comp(princ); i++){
+ if(fnmatch(princ_ncomp(pattern, i), princ_ncomp(princ, i), 0) != 0)
+ return FALSE;
+ }
+ return TRUE;
+}
+
+/*
+ * This is the original krb5_sname_to_principal(), renamed to be a
+ * helper of the new one.
+ */
+static krb5_error_code
+krb5_sname_to_principal_old(krb5_context context,
+ const char *realm,
+ const char *hostname,
+ const char *sname,
+ int32_t type,
+ krb5_principal *ret_princ)
+{
+ krb5_error_code ret;
+ char localhost[MAXHOSTNAMELEN];
+ char **realms = NULL, *host = NULL;
+
+ if(type != KRB5_NT_SRV_HST && type != KRB5_NT_UNKNOWN) {
+ krb5_set_error_message(context, KRB5_SNAME_UNSUPP_NAMETYPE,
+ N_("unsupported name type %d", ""),
+ (int)type);
+ return KRB5_SNAME_UNSUPP_NAMETYPE;
+ }
+ if(hostname == NULL) {
+ ret = gethostname(localhost, sizeof(localhost) - 1);
+ if (ret != 0) {
+ ret = errno;
+ krb5_set_error_message(context, ret,
+ N_("Failed to get local hostname", ""));
+ return ret;
+ }
+ localhost[sizeof(localhost) - 1] = '\0';
+ hostname = localhost;
+ }
+ if(sname == NULL)
+ sname = "host";
+ if(type == KRB5_NT_SRV_HST) {
+ if (realm)
+ ret = krb5_expand_hostname(context, hostname, &host);
+ else
+ ret = krb5_expand_hostname_realms(context, hostname,
+ &host, &realms);
+ if (ret)
+ return ret;
+ strlwr(host);
+ hostname = host;
+ if (!realm)
+ realm = realms[0];
+ } else if (!realm) {
+ ret = krb5_get_host_realm(context, hostname, &realms);
+ if(ret)
+ return ret;
+ realm = realms[0];
+ }
+
+ ret = krb5_make_principal(context, ret_princ, realm, sname,
+ hostname, NULL);
+ if(host)
+ free(host);
+ if (realms)
+ krb5_free_host_realm(context, realms);
+ return ret;
+}
+
+static const struct {
+ const char *type;
+ int32_t value;
+} nametypes[] = {
+ { "UNKNOWN", KRB5_NT_UNKNOWN },
+ { "PRINCIPAL", KRB5_NT_PRINCIPAL },
+ { "SRV_INST", KRB5_NT_SRV_INST },
+ { "SRV_HST", KRB5_NT_SRV_HST },
+ { "SRV_XHST", KRB5_NT_SRV_XHST },
+ { "UID", KRB5_NT_UID },
+ { "X500_PRINCIPAL", KRB5_NT_X500_PRINCIPAL },
+ { "SMTP_NAME", KRB5_NT_SMTP_NAME },
+ { "ENTERPRISE_PRINCIPAL", KRB5_NT_ENTERPRISE_PRINCIPAL },
+ { "WELLKNOWN", KRB5_NT_WELLKNOWN },
+ { "SRV_HST_DOMAIN", KRB5_NT_SRV_HST_DOMAIN },
+ { "ENT_PRINCIPAL_AND_ID", KRB5_NT_ENT_PRINCIPAL_AND_ID },
+ { "MS_PRINCIPAL", KRB5_NT_MS_PRINCIPAL },
+ { "MS_PRINCIPAL_AND_ID", KRB5_NT_MS_PRINCIPAL_AND_ID },
+ { "SRV_HST_NEEDS_CANON", KRB5_NT_SRV_HST_NEEDS_CANON },
+ { NULL, 0 }
+};
+
+/**
+ * Parse nametype string and return a nametype integer
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_parse_nametype(krb5_context context, const char *str, int32_t *nametype)
+{
+ size_t i;
+
+ for(i = 0; nametypes[i].type; i++) {
+ if (strcasecmp(nametypes[i].type, str) == 0) {
+ *nametype = nametypes[i].value;
+ return 0;
+ }
+ }
+ krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
+ N_("Failed to find name type %s", ""), str);
+ return KRB5_PARSE_MALFORMED;
+}
+
+/**
+ * Returns true if name is Kerberos NULL name
+ *
+ * @ingroup krb5_principal
+ */
+
+krb5_boolean KRB5_LIB_FUNCTION
+krb5_principal_is_null(krb5_context context, krb5_const_principal principal)
+{
+ if (principal->name.name_type == KRB5_NT_WELLKNOWN &&
+ principal->name.name_string.len == 2 &&
+ strcmp(principal->name.name_string.val[0], "WELLKNOWN") == 0 &&
+ strcmp(principal->name.name_string.val[1], "NULL") == 0)
+ return TRUE;
+ return FALSE;
+}
+
+const char _krb5_wellknown_lkdc[] = "WELLKNOWN:COM.APPLE.LKDC";
+static const char lkdc_prefix[] = "LKDC:";
+
+/**
+ * Returns true if name is Kerberos an LKDC realm
+ *
+ * @ingroup krb5_principal
+ */
+
+krb5_boolean KRB5_LIB_FUNCTION
+krb5_realm_is_lkdc(const char *realm)
+{
+
+ return strncmp(realm, lkdc_prefix, sizeof(lkdc_prefix)-1) == 0 ||
+ strncmp(realm, _krb5_wellknown_lkdc, sizeof(_krb5_wellknown_lkdc) - 1) == 0;
+}
+
+/**
+ * Returns true if name is Kerberos an LKDC realm
+ *
+ * @ingroup krb5_principal
+ */
+
+krb5_boolean KRB5_LIB_FUNCTION
+krb5_principal_is_lkdc(krb5_context context, krb5_const_principal principal)
+{
+ return krb5_realm_is_lkdc(principal->realm);
+}
+
+/**
+ * Returns true if name is Kerberos an LKDC realm
+ *
+ * @ingroup krb5_principal
+ */
+
+krb5_boolean KRB5_LIB_FUNCTION
+krb5_principal_is_pku2u(krb5_context context, krb5_const_principal principal)
+{
+ return strcmp(principal->realm, KRB5_PKU2U_REALM_NAME) == 0;
+}
+
+/**
+ * Check if the cname part of the principal is a krbtgt principal
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_principal_is_krbtgt(krb5_context context, krb5_const_principal p)
+{
+ return p->name.name_string.len == 2 &&
+ strcmp(p->name.name_string.val[0], KRB5_TGS_NAME) == 0;
+}
+
+/**
+ * Returns true iff name is an WELLKNOWN:ORG.H5L.HOSTBASED-SERVICE
+ *
+ * @ingroup krb5_principal
+ */
+
+krb5_boolean KRB5_LIB_FUNCTION
+krb5_principal_is_gss_hostbased_service(krb5_context context,
+ krb5_const_principal principal)
+{
+ if (principal == NULL)
+ return FALSE;
+ if (principal->name.name_string.len != 2)
+ return FALSE;
+ if (strcmp(principal->name.name_string.val[1], KRB5_GSS_HOSTBASED_SERVICE_NAME) != 0)
+ return FALSE;
+ return TRUE;
+}
+
+/**
+ * Check if the cname part of the principal is a initial or renewed krbtgt principal
+ *
+ * @ingroup krb5_principal
+ */
+
+krb5_boolean KRB5_LIB_FUNCTION
+krb5_principal_is_root_krbtgt(krb5_context context, krb5_const_principal p)
+{
+ return p->name.name_string.len == 2 &&
+ strcmp(p->name.name_string.val[0], KRB5_TGS_NAME) == 0 &&
+ strcmp(p->name.name_string.val[1], p->realm) == 0;
+}
+
+/**
+ * Returns true iff name is WELLKNOWN/ANONYMOUS
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_principal_is_anonymous(krb5_context context,
+ krb5_const_principal p,
+ unsigned int flags)
+{
+ /*
+ * Heimdal versions 7.5 and below left the name-type at KRB5_NT_PRINCIPAL
+ * even with anonymous pkinit responses. To retain interoperability with
+ * legacy KDCs, the name-type is not checked by the client after requesting
+ * a fully anonymous ticket.
+ */
+ if (!(flags & KRB5_ANON_IGNORE_NAME_TYPE) &&
+ p->name.name_type != KRB5_NT_WELLKNOWN &&
+ p->name.name_type != KRB5_NT_UNKNOWN)
+ return FALSE;
+
+ if (p->name.name_string.len != 2 ||
+ strcmp(p->name.name_string.val[0], KRB5_WELLKNOWN_NAME) != 0 ||
+ strcmp(p->name.name_string.val[1], KRB5_ANON_NAME) != 0)
+ return FALSE;
+
+ /*
+ * While unauthenticated clients SHOULD get "WELLKNOWN:ANONYMOUS" as their
+ * realm, Heimdal KDCs prior to 7.0 returned the requested realm. While
+ * such tickets might lead *servers* to unwittingly grant access to fully
+ * anonymous clients, trusting that the client was authenticated to the
+ * realm in question, doing it right is the KDC's job, the client should
+ * not refuse such a ticket.
+ *
+ * If we ever do decide to enforce WELLKNOWN:ANONYMOUS for unauthenticated
+ * clients, it is essential that calls that pass KRB5_ANON_MATCH_ANY still
+ * ignore the realm, as in that case either case matches one of the two
+ * possible conditions.
+ */
+ if (flags & KRB5_ANON_MATCH_UNAUTHENTICATED)
+ return TRUE;
+
+ /*
+ * Finally, authenticated clients that asked to be only anonymized do
+ * legitimately expect a non-anon realm.
+ */
+ return strcmp(p->realm, KRB5_ANON_REALM) != 0;
+}
+
+/**
+ * Returns true iff name is WELLKNOWN/FEDERATED
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_principal_is_federated(krb5_context context,
+ krb5_const_principal p)
+{
+ if (p->name.name_type != KRB5_NT_WELLKNOWN &&
+ p->name.name_type != KRB5_NT_UNKNOWN)
+ return FALSE;
+
+ if (p->name.name_string.len != 2 ||
+ strcmp(p->name.name_string.val[0], KRB5_WELLKNOWN_NAME) != 0 ||
+ strcmp(p->name.name_string.val[1], KRB5_FEDERATED_NAME) != 0)
+ return FALSE;
+
+ return TRUE;
+}
+
+static int
+tolower_ascii(int c)
+{
+ if (c >= 'A' && c <= 'Z')
+ return 'a' + (c - 'A');
+ return c;
+}
+
+typedef enum krb5_name_canon_rule_type {
+ KRB5_NCRT_BOGUS = 0,
+ KRB5_NCRT_AS_IS,
+ KRB5_NCRT_QUALIFY,
+ KRB5_NCRT_NSS
+} krb5_name_canon_rule_type;
+
+#ifdef UINT8_MAX
+#define MAXDOTS UINT8_MAX
+#else
+#define MAXDOTS (255U)
+#endif
+#ifdef UINT16_MAX
+#define MAXORDER UINT16_MAX
+#else
+#define MAXORDER (65535U)
+#endif
+
+struct krb5_name_canon_rule_data {
+ krb5_name_canon_rule_type type;
+ krb5_name_canon_rule_options options;
+ uint8_t mindots; /* match this many dots or more */
+ uint8_t maxdots; /* match no more than this many dots */
+ uint16_t explicit_order; /* given order */
+ uint16_t order; /* actual order */
+ char *match_domain; /* match this stem */
+ char *match_realm; /* match this realm */
+ char *domain; /* qualify with this domain */
+ char *realm; /* qualify with this realm */
+};
+
+/**
+ * Create a principal for the given service running on the given
+ * hostname. If KRB5_NT_SRV_HST is used, the hostname is canonicalized
+ * according the configured name canonicalization rules, with
+ * canonicalization delayed in some cases. One rule involves DNS, which
+ * is insecure unless DNSSEC is used, but we don't use DNSSEC-capable
+ * resolver APIs here, so that if DNSSEC is used we wouldn't know it.
+ *
+ * Canonicalization is immediate (not delayed) only when there is only
+ * one canonicalization rule and that rule indicates that we should do a
+ * host lookup by name (i.e., DNS).
+ *
+ * @param context A Kerberos context.
+ * @param hostname hostname to use
+ * @param sname Service name to use
+ * @param type name type of principal, use KRB5_NT_SRV_HST or KRB5_NT_UNKNOWN.
+ * @param ret_princ return principal, free with krb5_free_principal().
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+/* coverity[+alloc : arg-*4] */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_sname_to_principal(krb5_context context,
+ const char *hostname,
+ const char *sname,
+ int32_t type,
+ krb5_principal *ret_princ)
+{
+ char *realm, *remote_host;
+ krb5_error_code ret;
+ register char *cp;
+ char localname[MAXHOSTNAMELEN];
+
+ *ret_princ = NULL;
+
+ if ((type != KRB5_NT_UNKNOWN) &&
+ (type != KRB5_NT_SRV_HST))
+ return KRB5_SNAME_UNSUPP_NAMETYPE;
+
+ /* if hostname is NULL, use local hostname */
+ if (hostname == NULL) {
+ if (gethostname(localname, MAXHOSTNAMELEN))
+ return errno;
+ hostname = localname;
+ }
+
+ /* if sname is NULL, use "host" */
+ if (sname == NULL)
+ sname = "host";
+
+ remote_host = strdup(hostname);
+ if (remote_host == NULL)
+ return krb5_enomem(context);
+
+ if (type == KRB5_NT_SRV_HST) {
+ krb5_name_canon_rule rules;
+
+ /* Lower-case the hostname, because that's the convention */
+ for (cp = remote_host; *cp; cp++)
+ if (isupper((int) (*cp)))
+ *cp = tolower((int) (*cp));
+
+ /*
+ * If there is only one name canon rule and it says to
+ * canonicalize the old way, do that now, as we used to.
+ */
+ ret = _krb5_get_name_canon_rules(context, &rules);
+ if (ret) {
+ _krb5_debug(context, 5, "Failed to get name canon rules: ret = %d",
+ ret);
+ free(remote_host);
+ return ret;
+ }
+ if (rules[0].type == KRB5_NCRT_NSS &&
+ rules[1].type == KRB5_NCRT_BOGUS) {
+ _krb5_debug(context, 5, "Using nss for name canon immediately");
+ ret = krb5_sname_to_principal_old(context, rules[0].realm,
+ remote_host, sname,
+ KRB5_NT_SRV_HST, ret_princ);
+ free(remote_host);
+ return ret;
+ }
+ }
+
+ /* Remove trailing dots */
+ if (remote_host[0]) {
+ for (cp = remote_host + strlen(remote_host)-1;
+ *cp == '.' && cp > remote_host;
+ cp--) {
+ *cp = '\0';
+ }
+ }
+
+ realm = ""; /* "Referral realm" */
+
+ ret = krb5_build_principal(context, ret_princ, strlen(realm),
+ realm, sname, remote_host,
+ (char *)0);
+
+ if (ret == 0 && type == KRB5_NT_SRV_HST) {
+ /*
+ * Hostname canonicalization is done elsewhere (in
+ * krb5_get_credentials() and krb5_kt_get_entry()).
+ *
+ * We overload the name type to indicate to those functions that
+ * this principal name requires canonicalization.
+ *
+ * We can't use the empty realm to denote the need to
+ * canonicalize the hostname too: it would mean that users who
+ * want to assert knowledge of a service's realm must also know
+ * the canonical hostname, but in practice they don't.
+ */
+ (*ret_princ)->name.name_type = KRB5_NT_SRV_HST_NEEDS_CANON;
+
+ _krb5_debug(context, 5, "Building a delayed canon principal for %s/%s@",
+ sname, remote_host);
+ }
+
+ free(remote_host);
+ return ret;
+}
+
+static void
+tolower_str(char *s)
+{
+ for (; *s != '\0'; s++) {
+ if (isupper(*s))
+ *s = tolower_ascii(*s);
+ }
+}
+
+static krb5_error_code
+rule_parse_token(krb5_context context, krb5_name_canon_rule rule,
+ const char *tok)
+{
+ long int n;
+ int needs_type = rule->type == KRB5_NCRT_BOGUS;
+
+ /*
+ * Rules consist of a sequence of tokens, some of which indicate
+ * what type of rule the rule is, and some of which set rule options
+ * or ancilliary data. Last rule type token wins.
+ */
+
+ /* Rule type tokens: */
+ if (needs_type && strcmp(tok, "as-is") == 0) {
+ rule->type = KRB5_NCRT_AS_IS;
+ } else if (needs_type && strcmp(tok, "qualify") == 0) {
+ rule->type = KRB5_NCRT_QUALIFY;
+ } else if (needs_type && strcmp(tok, "nss") == 0) {
+ rule->type = KRB5_NCRT_NSS;
+ /* Rule options: */
+ } else if (strcmp(tok, "use_fast") == 0) {
+ rule->options |= KRB5_NCRO_USE_FAST;
+ } else if (strcmp(tok, "use_dnssec") == 0) {
+ rule->options |= KRB5_NCRO_USE_DNSSEC;
+ } else if (strcmp(tok, "ccache_only") == 0) {
+ rule->options |= KRB5_NCRO_GC_ONLY;
+ } else if (strcmp(tok, "no_referrals") == 0) {
+ rule->options |= KRB5_NCRO_NO_REFERRALS;
+ } else if (strcmp(tok, "use_referrals") == 0) {
+ rule->options &= ~KRB5_NCRO_NO_REFERRALS;
+ if (rule->realm == NULL) {
+ rule->realm = strdup("");
+ if (rule->realm == NULL)
+ return krb5_enomem(context);
+ }
+ } else if (strcmp(tok, "lookup_realm") == 0) {
+ rule->options |= KRB5_NCRO_LOOKUP_REALM;
+ free(rule->realm);
+ rule->realm = NULL;
+ /* Rule ancilliary data: */
+ } else if (strncmp(tok, "domain=", strlen("domain=")) == 0) {
+ free(rule->domain);
+ rule->domain = strdup(tok + strlen("domain="));
+ if (rule->domain == NULL)
+ return krb5_enomem(context);
+ tolower_str(rule->domain);
+ } else if (strncmp(tok, "realm=", strlen("realm=")) == 0) {
+ free(rule->realm);
+ rule->realm = strdup(tok + strlen("realm="));
+ if (rule->realm == NULL)
+ return krb5_enomem(context);
+ } else if (strncmp(tok, "match_domain=", strlen("match_domain=")) == 0) {
+ free(rule->match_domain);
+ rule->match_domain = strdup(tok + strlen("match_domain="));
+ if (rule->match_domain == NULL)
+ return krb5_enomem(context);
+ tolower_str(rule->match_domain);
+ } else if (strncmp(tok, "match_realm=", strlen("match_realm=")) == 0) {
+ free(rule->match_realm);
+ rule->match_realm = strdup(tok + strlen("match_realm="));
+ if (rule->match_realm == NULL)
+ return krb5_enomem(context);
+ } else if (strncmp(tok, "mindots=", strlen("mindots=")) == 0) {
+ errno = 0;
+ n = strtol(tok + strlen("mindots="), NULL, 10);
+ if (errno == 0 && n > 0 && n <= MAXDOTS)
+ rule->mindots = n;
+ } else if (strncmp(tok, "maxdots=", strlen("maxdots=")) == 0) {
+ errno = 0;
+ n = strtol(tok + strlen("maxdots="), NULL, 10);
+ if (errno == 0 && n > 0 && n <= MAXDOTS)
+ rule->maxdots = n;
+ } else if (strncmp(tok, "order=", strlen("order=")) == 0) {
+ errno = 0;
+ n = strtol(tok + strlen("order="), NULL, 10);
+ if (errno == 0 && n > 0 && n <= MAXORDER)
+ rule->explicit_order = n;
+ } else {
+ _krb5_debug(context, 5,
+ "Unrecognized name canonicalization rule token %s", tok);
+ return EINVAL;
+ }
+ return 0;
+}
+
+static int
+rule_cmp(const void *a, const void *b)
+{
+ krb5_const_name_canon_rule left = a;
+ krb5_const_name_canon_rule right = b;
+
+ if (left->type == KRB5_NCRT_BOGUS &&
+ right->type == KRB5_NCRT_BOGUS)
+ return 0;
+ if (left->type == KRB5_NCRT_BOGUS)
+ return 1;
+ if (right->type == KRB5_NCRT_BOGUS)
+ return -1;
+ if (left->explicit_order < right->explicit_order)
+ return -1;
+ if (left->explicit_order > right->explicit_order)
+ return 1;
+ return left->order - right->order;
+}
+
+static krb5_error_code
+parse_name_canon_rules(krb5_context context, char **rulestrs,
+ krb5_name_canon_rule *rules)
+{
+ krb5_error_code ret;
+ char *tok;
+ char *cp;
+ char **cpp;
+ size_t n;
+ size_t i, k;
+ int do_sort = 0;
+ krb5_name_canon_rule r;
+
+ *rules = NULL;
+
+ for (n =0, cpp = rulestrs; cpp != NULL && *cpp != NULL; cpp++)
+ n++;
+
+ n += 2; /* Always at least one rule; two for the default case */
+
+ if ((r = calloc(n, sizeof (*r))) == NULL)
+ return krb5_enomem(context);
+
+ for (k = 0; k < n; k++) {
+ r[k].type = KRB5_NCRT_BOGUS;
+ r[k].match_domain = NULL;
+ r[k].match_realm = NULL;
+ r[k].domain = NULL;
+ r[k].realm = NULL;
+ }
+
+ for (i = 0, k = 0; i < n && rulestrs != NULL && rulestrs[i] != NULL; i++) {
+ cp = rulestrs[i];
+ r[k].explicit_order = MAXORDER; /* mark order, see below */
+ r[k].maxdots = MAXDOTS;
+ r[k].order = k; /* default order */
+
+ /* Tokenize and parse value */
+ do {
+ tok = cp;
+ cp = strchr(cp, ':'); /* XXX use strtok_r() */
+ if (cp)
+ *cp++ = '\0'; /* delimit token */
+ ret = rule_parse_token(context, &r[k], tok);
+ if (ret == EINVAL) {
+ r[k].type = KRB5_NCRT_BOGUS;
+ break;
+ }
+ if (ret) {
+ _krb5_free_name_canon_rules(context, r);
+ return ret;
+ }
+ } while (cp && *cp);
+ if (r[k].explicit_order != MAXORDER)
+ do_sort = 1;
+
+ /* Validate parsed rule */
+ if (r[k].type == KRB5_NCRT_BOGUS ||
+ (r[k].type == KRB5_NCRT_QUALIFY && !r[k].domain) ||
+ (r[k].type == KRB5_NCRT_NSS && r[k].domain)) {
+ /* Invalid rule; mark it so and clean up */
+ r[k].type = KRB5_NCRT_BOGUS;
+ free(r[k].match_domain);
+ free(r[k].match_realm);
+ free(r[k].domain);
+ free(r[k].realm);
+ r[k].realm = NULL;
+ r[k].domain = NULL;
+ r[k].match_domain = NULL;
+ r[k].match_realm = NULL;
+ _krb5_debug(context, 5,
+ "Ignoring invalid name canonicalization rule %lu",
+ (unsigned long)i);
+ continue;
+ }
+ k++; /* good rule */
+ }
+
+ if (do_sort) {
+ /*
+ * Note that we make make this a stable sort by using appareance
+ * and explicit order.
+ */
+ qsort(r, n, sizeof(r[0]), rule_cmp);
+ }
+
+ if (r[0].type == KRB5_NCRT_BOGUS) {
+ /* No rules, or no valid rules */
+ if (context->flags & KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME) {
+ r[0].type = KRB5_NCRT_NSS;
+ } else {
+ r[0].type = KRB5_NCRT_AS_IS;
+ }
+ }
+
+ *rules = r;
+ return 0; /* We don't communicate bad rule errors here */
+}
+
+/*
+ * This exists only because the hostname canonicalization behavior in Heimdal
+ * (and other implementations of Kerberos) has been to use getaddrinfo(),
+ * unsafe though it is, for ages. We can't fix it in one day.
+ */
+static void
+make_rules_safe(krb5_context context, krb5_name_canon_rule rules)
+{
+ /*
+ * If the only rule were to use the name service (getaddrinfo()) then we're
+ * bound to fail. We could try to convert that rule to an as-is rule, but
+ * when we do get a validating resolver we'd be unhappy that we did such a
+ * conversion. Better let the user get failures and make them think about
+ * their naming rules.
+ */
+ if (rules == NULL)
+ return;
+ for (; rules[0].type != KRB5_NCRT_BOGUS; rules++) {
+ if (rules->type == KRB5_NCRT_NSS)
+ rules->options |= KRB5_NCRO_USE_DNSSEC;
+ else
+ rules->options |= KRB5_NCRO_USE_FAST;
+ }
+}
+
+/**
+ * This function returns an array of host-based service name
+ * canonicalization rules. The array of rules is organized as a list.
+ * See the definition of krb5_name_canon_rule.
+ *
+ * @param context A Kerberos context.
+ * @param rules Output location for array of rules.
+ */
+KRB5_LIB_FUNCTION krb5_error_code
+_krb5_get_name_canon_rules(krb5_context context, krb5_name_canon_rule *rules)
+{
+ krb5_error_code ret;
+ char **values = NULL;
+
+ *rules = context->name_canon_rules;
+ if (*rules != NULL)
+ return 0;
+
+ values = krb5_config_get_strings(context, NULL,
+ "libdefaults", "name_canon_rules", NULL);
+ ret = parse_name_canon_rules(context, values, rules);
+ krb5_config_free_strings(values);
+ if (ret)
+ return ret;
+
+ if (krb5_config_get_bool_default(context, NULL, FALSE,
+ "libdefaults", "safe_name_canon", NULL))
+ make_rules_safe(context, *rules);
+
+ heim_assert((*rules)[0].type != KRB5_NCRT_BOGUS,
+ "internal error in parsing principal name "
+ "canonicalization rules");
+
+ /* Memoize */
+ context->name_canon_rules = *rules;
+
+ return 0;
+}
+
+static krb5_error_code
+get_host_realm(krb5_context context, const char *hostname, char **realm)
+{
+ krb5_error_code ret;
+ char **hrealms = NULL;
+
+ *realm = NULL;
+ ret = krb5_get_host_realm(context, hostname, &hrealms);
+ if (ret)
+ return ret;
+ if (hrealms == NULL)
+ return KRB5_ERR_HOST_REALM_UNKNOWN; /* krb5_set_error() already done */
+ if (hrealms[0] == NULL) {
+ krb5_free_host_realm(context, hrealms);
+ return KRB5_ERR_HOST_REALM_UNKNOWN; /* krb5_set_error() already done */
+ }
+ *realm = strdup(hrealms[0]);
+ krb5_free_host_realm(context, hrealms);
+ if (*realm == NULL)
+ return krb5_enomem(context);
+ return 0;
+}
+
+static int
+is_domain_suffix(const char *domain, const char *suffix)
+{
+ size_t dlen = strlen(domain);
+ size_t slen = strlen(suffix);
+
+ if (dlen < slen + 2)
+ return 0;
+
+ if (strcasecmp(domain + (dlen - slen), suffix) != 0)
+ return 0;
+
+ if (domain[(dlen - slen) - 1] != '.')
+ return 0;
+ return 1;
+}
+
+/*
+ * Applies a name canonicalization rule to a principal.
+ *
+ * Returns zero and no out_princ if the rule does not match.
+ * Returns zero and an out_princ if the rule does match.
+ */
+static krb5_error_code
+apply_name_canon_rule(krb5_context context, krb5_name_canon_rule rules,
+ size_t rule_idx, krb5_const_principal in_princ,
+ krb5_principal *out_princ,
+ krb5_name_canon_rule_options *rule_opts)
+{
+ krb5_name_canon_rule rule = &rules[rule_idx];
+ krb5_error_code ret;
+ unsigned int ndots = 0;
+ krb5_principal nss = NULL;
+ const char *sname = NULL;
+ const char *orig_hostname = NULL;
+ const char *new_hostname = NULL;
+ const char *new_realm = NULL;
+ const char *port = "";
+ const char *cp;
+ char *hostname_sans_port = NULL;
+ char *hostname_with_port = NULL;
+ char *tmp_hostname = NULL;
+ char *tmp_realm = NULL;
+
+ *out_princ = NULL; /* Signal no match */
+
+ if (rule_opts != NULL)
+ *rule_opts = rule->options;
+
+ if (rule->type == KRB5_NCRT_BOGUS)
+ return 0; /* rule doesn't apply */
+
+ sname = krb5_principal_get_comp_string(context, in_princ, 0);
+ orig_hostname = krb5_principal_get_comp_string(context, in_princ, 1);
+
+ /*
+ * Some apps want to use the very non-standard svc/hostname:port@REALM
+ * form. We do our best to support that here :(
+ */
+ port = strchr(orig_hostname, ':');
+ if (port != NULL) {
+ hostname_sans_port = strndup(orig_hostname, port - orig_hostname);
+ if (hostname_sans_port == NULL)
+ return krb5_enomem(context);
+ orig_hostname = hostname_sans_port;
+ }
+
+ _krb5_debug(context, 5, N_("Applying a name rule (type %d) to %s", ""),
+ rule->type, orig_hostname);
+
+ if (rule->mindots > 0 || rule->maxdots > 0) {
+ for (cp = strchr(orig_hostname, '.'); cp && *cp; cp = strchr(cp + 1, '.'))
+ ndots++;
+ }
+ if (rule->mindots > 0 && ndots < rule->mindots)
+ return 0;
+ if (ndots > rule->maxdots)
+ return 0;
+
+ if (rule->match_domain != NULL &&
+ !is_domain_suffix(orig_hostname, rule->match_domain))
+ return 0;
+
+ if (rule->match_realm != NULL &&
+ strcmp(rule->match_realm, in_princ->realm) != 0)
+ return 0;
+
+ new_realm = rule->realm;
+ switch (rule->type) {
+ case KRB5_NCRT_AS_IS:
+ break;
+
+ case KRB5_NCRT_QUALIFY:
+ heim_assert(rule->domain != NULL,
+ "missing domain for qualify name canon rule");
+ if (asprintf(&tmp_hostname, "%s.%s", orig_hostname,
+ rule->domain) == -1 || tmp_hostname == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ new_hostname = tmp_hostname;
+ break;
+
+ case KRB5_NCRT_NSS:
+ if ((rule->options & KRB5_NCRO_USE_DNSSEC)) {
+ ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
+ krb5_set_error_message(context, ret,
+ "Secure hostname resolution not supported");
+ goto out;
+ }
+ _krb5_debug(context, 5, "Using name service lookups");
+ ret = krb5_sname_to_principal_old(context, rule->realm,
+ orig_hostname, sname,
+ KRB5_NT_SRV_HST,
+ &nss);
+ if (rules[rule_idx + 1].type != KRB5_NCRT_BOGUS &&
+ (ret == KRB5_ERR_BAD_HOSTNAME ||
+ ret == KRB5_ERR_HOST_REALM_UNKNOWN)) {
+ /*
+ * Bad hostname / realm unknown -> rule inapplicable if
+ * there's more rules. If it's the last rule then we want
+ * to return all errors from krb5_sname_to_principal_old()
+ * here.
+ */
+ ret = 0;
+ goto out;
+ }
+ if (ret)
+ goto out;
+
+ new_hostname = krb5_principal_get_comp_string(context, nss, 1);
+ new_realm = krb5_principal_get_realm(context, nss);
+ break;
+
+ default:
+ /* Can't happen */
+ ret = 0;
+ goto out;
+ }
+
+ /*
+ * This rule applies.
+ *
+ * Copy in_princ and mutate the copy per the matched rule.
+ *
+ * This way we apply to principals with two or more components, such as
+ * domain-based names.
+ */
+ ret = krb5_copy_principal(context, in_princ, out_princ);
+ if (ret)
+ goto out;
+
+ if (new_realm == NULL && (rule->options & KRB5_NCRO_LOOKUP_REALM) != 0) {
+ ret = get_host_realm(context, new_hostname, &tmp_realm);
+ if (ret)
+ goto out;
+ new_realm = tmp_realm;
+ }
+
+ /* If we stripped off a :port, add it back in */
+ if (port != NULL && new_hostname != NULL) {
+ if (asprintf(&hostname_with_port, "%s%s", new_hostname, port) == -1 ||
+ hostname_with_port == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ new_hostname = hostname_with_port;
+ }
+
+ if (new_realm != NULL &&
+ (ret = krb5_principal_set_realm(context, *out_princ, new_realm)))
+ goto out;
+ if (new_hostname != NULL &&
+ (ret = krb5_principal_set_comp_string(context, *out_princ, 1, new_hostname)))
+ goto out;
+ if (princ_type(*out_princ) == KRB5_NT_SRV_HST_NEEDS_CANON)
+ princ_type(*out_princ) = KRB5_NT_SRV_HST;
+
+ /* Trace rule application */
+ {
+ krb5_error_code ret2;
+ char *unparsed;
+
+ ret2 = krb5_unparse_name(context, *out_princ, &unparsed);
+ if (ret2) {
+ _krb5_debug(context, 5,
+ N_("Couldn't unparse canonicalized princicpal (%d)",
+ ""),
+ ret);
+ } else {
+ _krb5_debug(context, 5,
+ N_("Name canon rule application yields %s", ""),
+ unparsed);
+ free(unparsed);
+ }
+ }
+
+out:
+ free(hostname_sans_port);
+ free(hostname_with_port);
+ free(tmp_hostname);
+ free(tmp_realm);
+ krb5_free_principal(context, nss);
+ if (ret)
+ krb5_set_error_message(context, ret,
+ N_("Name canon rule application failed", ""));
+ return ret;
+}
+
+/**
+ * Free name canonicalization rules
+ */
+KRB5_LIB_FUNCTION void
+_krb5_free_name_canon_rules(krb5_context context, krb5_name_canon_rule rules)
+{
+ size_t k;
+
+ if (rules == NULL)
+ return;
+
+ for (k = 0; rules[k].type != KRB5_NCRT_BOGUS; k++) {
+ free(rules[k].match_domain);
+ free(rules[k].match_realm);
+ free(rules[k].domain);
+ free(rules[k].realm);
+ }
+ free(rules);
+}
+
+struct krb5_name_canon_iterator_data {
+ krb5_name_canon_rule rules;
+ krb5_const_principal in_princ; /* given princ */
+ krb5_const_principal out_princ; /* princ to be output */
+ krb5_principal tmp_princ; /* to be freed */
+ int is_trivial; /* no canon to be done */
+ int done; /* no more rules to be applied */
+ size_t cursor; /* current/next rule */
+};
+
+/**
+ * Initialize name canonicalization iterator.
+ *
+ * @param context Kerberos context
+ * @param in_princ principal name to be canonicalized OR
+ * @param iter output iterator object
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_name_canon_iterator_start(krb5_context context,
+ krb5_const_principal in_princ,
+ krb5_name_canon_iterator *iter)
+{
+ krb5_error_code ret;
+ krb5_name_canon_iterator state;
+
+ *iter = NULL;
+
+ state = calloc(1, sizeof (*state));
+ if (state == NULL)
+ return krb5_enomem(context);
+ state->in_princ = in_princ;
+
+ if (princ_type(state->in_princ) == KRB5_NT_SRV_HST_NEEDS_CANON) {
+ ret = _krb5_get_name_canon_rules(context, &state->rules);
+ if (ret)
+ goto out;
+ } else {
+ /* Name needs no canon -> trivial iterator: in_princ is canonical */
+ state->is_trivial = 1;
+ }
+
+ *iter = state;
+ return 0;
+
+out:
+ krb5_free_name_canon_iterator(context, state);
+ return krb5_enomem(context);
+}
+
+/*
+ * Helper for name canon iteration.
+ */
+static krb5_error_code
+name_canon_iterate(krb5_context context,
+ krb5_name_canon_iterator *iter,
+ krb5_name_canon_rule_options *rule_opts)
+{
+ krb5_error_code ret;
+ krb5_name_canon_iterator state = *iter;
+
+ if (rule_opts)
+ *rule_opts = 0;
+
+ if (state == NULL)
+ return 0;
+
+ if (state->done) {
+ krb5_free_name_canon_iterator(context, state);
+ *iter = NULL;
+ return 0;
+ }
+
+ if (state->is_trivial && !state->done) {
+ state->out_princ = state->in_princ;
+ state->done = 1;
+ return 0;
+ }
+
+ heim_assert(state->rules != NULL &&
+ state->rules[state->cursor].type != KRB5_NCRT_BOGUS,
+ "Internal error during name canonicalization");
+
+ do {
+ krb5_free_principal(context, state->tmp_princ);
+ ret = apply_name_canon_rule(context, state->rules, state->cursor,
+ state->in_princ, &state->tmp_princ, rule_opts);
+ if (ret) {
+ krb5_free_name_canon_iterator(context, state);
+ *iter = NULL;
+ return ret;
+ }
+ state->cursor++;
+ } while (state->tmp_princ == NULL &&
+ state->rules[state->cursor].type != KRB5_NCRT_BOGUS);
+
+ if (state->rules[state->cursor].type == KRB5_NCRT_BOGUS)
+ state->done = 1;
+
+ state->out_princ = state->tmp_princ;
+ if (state->tmp_princ == NULL) {
+ krb5_free_name_canon_iterator(context, state);
+ *iter = NULL;
+ return 0;
+ }
+ return 0;
+}
+
+/**
+ * Iteratively apply name canon rules, outputing a principal and rule
+ * options each time. Iteration completes when the @iter is NULL on
+ * return or when an error is returned. Callers must free the iterator
+ * if they abandon it mid-way.
+ *
+ * @param context Kerberos context
+ * @param iter name canon rule iterator (input/output)
+ * @param try_princ output principal name
+ * @param rule_opts output rule options
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_name_canon_iterate(krb5_context context,
+ krb5_name_canon_iterator *iter,
+ krb5_const_principal *try_princ,
+ krb5_name_canon_rule_options *rule_opts)
+{
+ krb5_error_code ret;
+
+ *try_princ = NULL;
+
+ ret = name_canon_iterate(context, iter, rule_opts);
+ if (*iter)
+ *try_princ = (*iter)->out_princ;
+ return ret;
+}
+
+/**
+ * Free a name canonicalization rule iterator.
+ */
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_name_canon_iterator(krb5_context context,
+ krb5_name_canon_iterator iter)
+{
+ if (iter == NULL)
+ return;
+ if (iter->tmp_princ)
+ krb5_free_principal(context, iter->tmp_princ);
+ free(iter);
+}
diff --git a/third_party/heimdal/lib/krb5/prog_setup.c b/third_party/heimdal/lib/krb5/prog_setup.c
new file mode 100644
index 0000000..21afbf8
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/prog_setup.c
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include <getarg.h>
+#include <err.h>
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_std_usage(int code, struct getargs *args, int num_args)
+{
+ arg_printusage(args, num_args, NULL, "");
+ exit(code);
+}
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_program_setup(krb5_context *context, int argc, char **argv,
+ struct getargs *args, int num_args,
+ void (KRB5_LIB_CALL *usage)(int, struct getargs*, int))
+{
+ krb5_error_code ret;
+ int optidx = 0;
+
+ if(usage == NULL)
+ usage = krb5_std_usage;
+
+ setprogname(argv[0]);
+ ret = krb5_init_context(context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ if(getarg(args, num_args, argc, argv, &optidx))
+ (*usage)(1, args, num_args);
+ return optidx;
+}
diff --git a/third_party/heimdal/lib/krb5/prompter_posix.c b/third_party/heimdal/lib/krb5/prompter_posix.c
new file mode 100644
index 0000000..1bf748c
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/prompter_posix.c
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION int KRB5_CALLCONV
+krb5_prompter_posix (krb5_context context,
+ void *data,
+ const char *name,
+ const char *banner,
+ int num_prompts,
+ krb5_prompt prompts[])
+{
+ int i;
+
+ if (name)
+ fprintf (stderr, "%s\n", name);
+ if (banner)
+ fprintf (stderr, "%s\n", banner);
+ if (name || banner)
+ fflush(stderr);
+ for (i = 0; i < num_prompts; ++i) {
+ if (prompts[i].hidden) {
+ if(UI_UTIL_read_pw_string(prompts[i].reply->data,
+ prompts[i].reply->length,
+ prompts[i].prompt,
+ 0))
+ return 1;
+ } else {
+ char *s = prompts[i].reply->data;
+
+ fputs (prompts[i].prompt, stdout);
+ fflush (stdout);
+ if(fgets(prompts[i].reply->data,
+ prompts[i].reply->length,
+ stdin) == NULL)
+ return 1;
+ s[strcspn(s, "\n")] = '\0';
+ }
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/pseudo-random-test.c b/third_party/heimdal/lib/krb5/pseudo-random-test.c
new file mode 100644
index 0000000..4acf808
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/pseudo-random-test.c
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+
+enum { MAXSIZE = 48 };
+
+static struct testcase {
+ krb5_enctype enctype;
+ unsigned char constant[MAXSIZE];
+ size_t constant_len;
+ unsigned char key[MAXSIZE];
+ unsigned char res[MAXSIZE];
+} tests[] = {
+ {ETYPE_AES128_CTS_HMAC_SHA256_128, "test", 4,
+ {0x37, 0x05, 0xD9, 0x60, 0x80, 0xC1, 0x77, 0x28, 0xA0, 0xE8, 0x00, 0xEA, 0xB6, 0xE0, 0xD2, 0x3C},
+ {0x9D, 0x18, 0x86, 0x16, 0xF6, 0x38, 0x52, 0xFE, 0x86, 0x91, 0x5B, 0xB8, 0x40, 0xB4, 0xA8, 0x86,
+ 0xFF, 0x3E, 0x6B, 0xB0, 0xF8, 0x19, 0xB4, 0x9B, 0x89, 0x33, 0x93, 0xD3, 0x93, 0x85, 0x42, 0x95}},
+ {ETYPE_AES256_CTS_HMAC_SHA384_192, "test", 4,
+ {0x6D, 0x40, 0x4D, 0x37, 0xFA, 0xF7, 0x9F, 0x9D, 0xF0, 0xD3, 0x35, 0x68, 0xD3, 0x20, 0x66, 0x98,
+ 0x00, 0xEB, 0x48, 0x36, 0x47, 0x2E, 0xA8, 0xA0, 0x26, 0xD1, 0x6B, 0x71, 0x82, 0x46, 0x0C, 0x52},
+ {0x98, 0x01, 0xF6, 0x9A, 0x36, 0x8C, 0x2B, 0xF6, 0x75, 0xE5, 0x95, 0x21, 0xE1, 0x77, 0xD9, 0xA0,
+ 0x7F, 0x67, 0xEF, 0xE1, 0xCF, 0xDE, 0x8D, 0x3C, 0x8D, 0x6F, 0x6A, 0x02, 0x56, 0xE3, 0xB1, 0x7D,
+ 0xB3, 0xC1, 0xB6, 0x2A, 0xD1, 0xB8, 0x55, 0x33, 0x60, 0xD1, 0x73, 0x67, 0xEB, 0x15, 0x14, 0xD2}},
+ {0, {0}, 0, {0}, {0}}
+};
+
+int
+main(int argc, char **argv)
+{
+ struct testcase *t;
+ krb5_context context;
+ krb5_error_code ret;
+ int val = 0;
+
+ ret = krb5_init_context (&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ for (t = tests; t->enctype != 0; ++t) {
+ krb5_keyblock key;
+ krb5_crypto crypto;
+ krb5_data constant, prf;
+
+ krb5_data_zero(&prf);
+
+ key.keytype = t->enctype;
+ krb5_enctype_keysize(context, t->enctype, &key.keyvalue.length);
+ key.keyvalue.data = t->key;
+
+ ret = krb5_crypto_init(context, &key, 0, &crypto);
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_crypto_init");
+
+ constant.data = t->constant;
+ constant.length = t->constant_len;
+
+ ret = krb5_crypto_prf(context, crypto, &constant, &prf);
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_crypto_prf");
+
+ if (memcmp(prf.data, t->res, prf.length) != 0) {
+ const unsigned char *p = prf.data;
+ int i;
+
+ printf ("PRF failed (enctype %d)\n", t->enctype);
+ printf ("should be: ");
+ for (i = 0; i < prf.length; ++i)
+ printf ("%02x", t->res[i]);
+ printf ("\nresult was: ");
+ for (i = 0; i < prf.length; ++i)
+ printf ("%02x", p[i]);
+ printf ("\n");
+ val = 1;
+ }
+ krb5_data_free(&prf);
+ krb5_crypto_destroy(context, crypto);
+ }
+ krb5_free_context(context);
+
+ return val;
+}
diff --git a/third_party/heimdal/lib/krb5/rd_cred.c b/third_party/heimdal/lib/krb5/rd_cred.c
new file mode 100644
index 0000000..f8d5736
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/rd_cred.c
@@ -0,0 +1,348 @@
+/*
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+static krb5_error_code
+compare_addrs(krb5_context context,
+ krb5_address *a,
+ krb5_address *b,
+ const char *message)
+{
+ char a_str[64], b_str[64];
+ size_t len;
+
+ if(krb5_address_compare (context, a, b))
+ return 0;
+
+ krb5_print_address (a, a_str, sizeof(a_str), &len);
+ krb5_print_address (b, b_str, sizeof(b_str), &len);
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_BADADDR,
+ "%s: %s != %s", message, b_str, a_str);
+ return KRB5KRB_AP_ERR_BADADDR;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_cred(krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_data *in_data,
+ krb5_creds ***ret_creds,
+ krb5_replay_data *outdata)
+{
+ krb5_error_code ret;
+ size_t len;
+ KRB_CRED cred;
+ EncKrbCredPart enc_krb_cred_part;
+ krb5_data enc_krb_cred_part_data;
+ krb5_crypto crypto;
+ size_t i;
+
+ memset(&enc_krb_cred_part, 0, sizeof(enc_krb_cred_part));
+ krb5_data_zero(&enc_krb_cred_part_data);
+
+ if ((auth_context->flags &
+ (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)) &&
+ outdata == NULL)
+ return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */
+
+ *ret_creds = NULL;
+
+ ret = decode_KRB_CRED(in_data->data, in_data->length,
+ &cred, &len);
+ if(ret) {
+ krb5_clear_error_message(context);
+ return ret;
+ }
+
+ if (cred.pvno != 5) {
+ ret = KRB5KRB_AP_ERR_BADVERSION;
+ krb5_clear_error_message (context);
+ goto out;
+ }
+
+ if (cred.msg_type != krb_cred) {
+ ret = KRB5KRB_AP_ERR_MSG_TYPE;
+ krb5_clear_error_message (context);
+ goto out;
+ }
+
+ if (cred.enc_part.etype == ETYPE_NULL) {
+ /* DK: MIT GSS-API Compatibility */
+ enc_krb_cred_part_data.length = cred.enc_part.cipher.length;
+ enc_krb_cred_part_data.data = cred.enc_part.cipher.data;
+ } else {
+ /* Try both subkey and session key.
+ *
+ * RFC4120 claims we should use the session key, but Heimdal
+ * before 0.8 used the remote subkey if it was send in the
+ * auth_context.
+ */
+
+ if (auth_context->remote_subkey) {
+ ret = krb5_crypto_init(context, auth_context->remote_subkey,
+ 0, &crypto);
+ if (ret)
+ goto out;
+
+ ret = krb5_decrypt_EncryptedData(context,
+ crypto,
+ KRB5_KU_KRB_CRED,
+ &cred.enc_part,
+ &enc_krb_cred_part_data);
+
+ krb5_crypto_destroy(context, crypto);
+ }
+
+ /*
+ * If there was not subkey, or we failed using subkey,
+ * retry using the session key
+ */
+ if (auth_context->remote_subkey == NULL || ret == KRB5KRB_AP_ERR_BAD_INTEGRITY)
+ {
+
+ ret = krb5_crypto_init(context, auth_context->keyblock,
+ 0, &crypto);
+
+ if (ret)
+ goto out;
+
+ ret = krb5_decrypt_EncryptedData(context,
+ crypto,
+ KRB5_KU_KRB_CRED,
+ &cred.enc_part,
+ &enc_krb_cred_part_data);
+
+ krb5_crypto_destroy(context, crypto);
+ }
+ if (ret)
+ goto out;
+ }
+
+ ret = decode_EncKrbCredPart(enc_krb_cred_part_data.data,
+ enc_krb_cred_part_data.length,
+ &enc_krb_cred_part,
+ &len);
+ if (enc_krb_cred_part_data.data != cred.enc_part.cipher.data)
+ krb5_data_free(&enc_krb_cred_part_data);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to decode "
+ "encrypte credential part", ""));
+ goto out;
+ }
+
+ /* check sender address */
+
+ if (enc_krb_cred_part.s_address
+ && auth_context->remote_address
+ && auth_context->remote_port) {
+ krb5_address *a;
+
+ ret = krb5_make_addrport (context, &a,
+ auth_context->remote_address,
+ auth_context->remote_port);
+ if (ret)
+ goto out;
+
+
+ ret = compare_addrs(context, a, enc_krb_cred_part.s_address,
+ N_("sender address is wrong "
+ "in received creds", ""));
+ krb5_free_address(context, a);
+ free(a);
+ if(ret)
+ goto out;
+ }
+
+ /* check receiver address */
+
+ if (enc_krb_cred_part.r_address
+ && auth_context->local_address) {
+ if(auth_context->local_port &&
+ enc_krb_cred_part.r_address->addr_type == KRB5_ADDRESS_ADDRPORT) {
+ krb5_address *a;
+ ret = krb5_make_addrport (context, &a,
+ auth_context->local_address,
+ auth_context->local_port);
+ if (ret)
+ goto out;
+
+ ret = compare_addrs(context, a, enc_krb_cred_part.r_address,
+ N_("receiver address is wrong "
+ "in received creds", ""));
+ krb5_free_address(context, a);
+ free(a);
+ if(ret)
+ goto out;
+ } else {
+ ret = compare_addrs(context, auth_context->local_address,
+ enc_krb_cred_part.r_address,
+ N_("receiver address is wrong "
+ "in received creds", ""));
+ if(ret)
+ goto out;
+ }
+ }
+
+ /* check timestamp */
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) {
+ krb5_timestamp sec;
+
+ krb5_timeofday (context, &sec);
+
+ if (enc_krb_cred_part.timestamp == NULL ||
+ enc_krb_cred_part.usec == NULL ||
+ krb5_time_abs(*enc_krb_cred_part.timestamp, sec)
+ > context->max_skew) {
+ krb5_clear_error_message (context);
+ ret = KRB5KRB_AP_ERR_SKEW;
+ goto out;
+ }
+ }
+
+ if ((auth_context->flags &
+ (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE))) {
+ /* if these fields are not present in the cred-part, silently
+ return zero */
+ memset(outdata, 0, sizeof(*outdata));
+ if(enc_krb_cred_part.timestamp)
+ outdata->timestamp = *enc_krb_cred_part.timestamp;
+ if(enc_krb_cred_part.usec)
+ outdata->usec = *enc_krb_cred_part.usec;
+ if(enc_krb_cred_part.nonce)
+ outdata->seq = *enc_krb_cred_part.nonce;
+ }
+
+ /* Convert to NULL terminated list of creds */
+
+ *ret_creds = calloc(enc_krb_cred_part.ticket_info.len + 1,
+ sizeof(**ret_creds));
+
+ if (*ret_creds == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ for (i = 0; i < enc_krb_cred_part.ticket_info.len; ++i) {
+ KrbCredInfo *kci = &enc_krb_cred_part.ticket_info.val[i];
+ krb5_creds *creds;
+
+ creds = calloc(1, sizeof(*creds));
+ if(creds == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ ASN1_MALLOC_ENCODE(Ticket, creds->ticket.data, creds->ticket.length,
+ &cred.tickets.val[i], &len, ret);
+ if (ret) {
+ free(creds);
+ goto out;
+ }
+ if(creds->ticket.length != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+ ret = copy_EncryptionKey (&kci->key, &creds->session);
+ if (ret) {
+ krb5_free_creds(context, creds);
+ goto out;
+ }
+ if (kci->prealm && kci->pname)
+ _krb5_principalname2krb5_principal (context,
+ &creds->client,
+ *kci->pname,
+ *kci->prealm);
+ if (kci->flags)
+ creds->flags.b = *kci->flags;
+ if (kci->authtime)
+ creds->times.authtime = *kci->authtime;
+ if (kci->starttime)
+ creds->times.starttime = *kci->starttime;
+ if (kci->endtime)
+ creds->times.endtime = *kci->endtime;
+ if (kci->renew_till)
+ creds->times.renew_till = *kci->renew_till;
+ if (kci->srealm && kci->sname)
+ _krb5_principalname2krb5_principal (context,
+ &creds->server,
+ *kci->sname,
+ *kci->srealm);
+ if (kci->caddr)
+ krb5_copy_addresses (context,
+ kci->caddr,
+ &creds->addresses);
+
+ (*ret_creds)[i] = creds;
+
+ }
+ (*ret_creds)[i] = NULL;
+
+ free_KRB_CRED (&cred);
+ free_EncKrbCredPart(&enc_krb_cred_part);
+
+ return 0;
+
+ out:
+ free_EncKrbCredPart(&enc_krb_cred_part);
+ free_KRB_CRED (&cred);
+ if(*ret_creds) {
+ for(i = 0; (*ret_creds)[i]; i++)
+ krb5_free_creds(context, (*ret_creds)[i]);
+ free(*ret_creds);
+ *ret_creds = NULL;
+ }
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_cred2 (krb5_context context,
+ krb5_auth_context auth_context,
+ krb5_ccache ccache,
+ krb5_data *in_data)
+{
+ krb5_error_code ret;
+ krb5_creds **creds;
+ int i;
+
+ ret = krb5_rd_cred(context, auth_context, in_data, &creds, NULL);
+ if(ret)
+ return ret;
+
+ /* Store the creds in the ccache */
+
+ for(i = 0; creds && creds[i]; i++) {
+ krb5_cc_store_cred(context, ccache, creds[i]);
+ krb5_free_creds(context, creds[i]);
+ }
+ free(creds);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/rd_error.c b/third_party/heimdal/lib/krb5/rd_error.c
new file mode 100644
index 0000000..d778c68
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/rd_error.c
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_error(krb5_context context,
+ const krb5_data *msg,
+ KRB_ERROR *result)
+{
+
+ size_t len;
+ krb5_error_code ret;
+
+ ret = decode_KRB_ERROR(msg->data, msg->length, result, &len);
+ if(ret) {
+ krb5_clear_error_message(context);
+ return ret;
+ }
+ result->error_code += KRB5KDC_ERR_NONE;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_error_contents (krb5_context context,
+ krb5_error *error)
+{
+ free_KRB_ERROR(error);
+ memset(error, 0, sizeof(*error));
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_error (krb5_context context,
+ krb5_error *error)
+{
+ krb5_free_error_contents (context, error);
+ free (error);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_error_from_rd_error(krb5_context context,
+ const krb5_error *error,
+ const krb5_creds *creds)
+{
+ krb5_error_code ret;
+
+ ret = error->error_code;
+ if (error->e_text != NULL) {
+ krb5_set_error_message(context, ret, "%s", *error->e_text);
+ } else {
+ char clientname[256], servername[256];
+
+ if (creds != NULL) {
+ krb5_unparse_name_fixed(context, creds->client,
+ clientname, sizeof(clientname));
+ krb5_unparse_name_fixed(context, creds->server,
+ servername, sizeof(servername));
+ }
+
+ switch (ret) {
+ case KRB5KDC_ERR_NAME_EXP :
+ krb5_set_error_message(context, ret,
+ N_("Client %s%s%s expired", ""),
+ creds ? "(" : "",
+ creds ? clientname : "",
+ creds ? ")" : "");
+ break;
+ case KRB5KDC_ERR_SERVICE_EXP :
+ krb5_set_error_message(context, ret,
+ N_("Server %s%s%s expired", ""),
+ creds ? "(" : "",
+ creds ? servername : "",
+ creds ? ")" : "");
+ break;
+ case KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN :
+ krb5_set_error_message(context, ret,
+ N_("Client %s%s%s unknown", ""),
+ creds ? "(" : "",
+ creds ? clientname : "",
+ creds ? ")" : "");
+ break;
+ case KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN :
+ krb5_set_error_message(context, ret,
+ N_("Server %s%s%s unknown", ""),
+ creds ? "(" : "",
+ creds ? servername : "",
+ creds ? ")" : "");
+ break;
+ default :
+ krb5_clear_error_message(context);
+ break;
+ }
+ }
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/rd_priv.c b/third_party/heimdal/lib/krb5/rd_priv.c
new file mode 100644
index 0000000..ab1a165
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/rd_priv.c
@@ -0,0 +1,184 @@
+/*
+ * Copyright (c) 1997-2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_priv(krb5_context context,
+ krb5_auth_context auth_context,
+ const krb5_data *inbuf,
+ krb5_data *outbuf,
+ krb5_replay_data *outdata)
+{
+ krb5_error_code ret;
+ KRB_PRIV priv;
+ EncKrbPrivPart part;
+ size_t len;
+ krb5_data plain;
+ krb5_keyblock *key;
+ krb5_crypto crypto;
+
+ krb5_data_zero(outbuf);
+
+ if ((auth_context->flags &
+ (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)))
+ {
+ if (outdata == NULL) {
+ krb5_clear_error_message (context);
+ return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */
+ }
+ /* if these fields are not present in the priv-part, silently
+ return zero */
+ memset(outdata, 0, sizeof(*outdata));
+ }
+
+ memset(&priv, 0, sizeof(priv));
+ ret = decode_KRB_PRIV (inbuf->data, inbuf->length, &priv, &len);
+ if (ret) {
+ krb5_clear_error_message (context);
+ goto failure;
+ }
+ if (priv.pvno != 5) {
+ krb5_clear_error_message (context);
+ ret = KRB5KRB_AP_ERR_BADVERSION;
+ goto failure;
+ }
+ if (priv.msg_type != krb_priv) {
+ krb5_clear_error_message (context);
+ ret = KRB5KRB_AP_ERR_MSG_TYPE;
+ goto failure;
+ }
+
+ if (auth_context->remote_subkey)
+ key = auth_context->remote_subkey;
+ else if (auth_context->local_subkey)
+ key = auth_context->local_subkey;
+ else
+ key = auth_context->keyblock;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ goto failure;
+ ret = krb5_decrypt_EncryptedData(context,
+ crypto,
+ KRB5_KU_KRB_PRIV,
+ &priv.enc_part,
+ &plain);
+ krb5_crypto_destroy(context, crypto);
+ if (ret)
+ goto failure;
+
+ ret = decode_EncKrbPrivPart (plain.data, plain.length, &part, &len);
+ krb5_data_free (&plain);
+ if (ret) {
+ krb5_clear_error_message (context);
+ goto failure;
+ }
+
+ /* check sender address */
+
+ if (part.s_address
+ && auth_context->remote_address
+ && !krb5_address_compare (context,
+ auth_context->remote_address,
+ part.s_address)) {
+ krb5_clear_error_message (context);
+ ret = KRB5KRB_AP_ERR_BADADDR;
+ goto failure_part;
+ }
+
+ /* check receiver address */
+
+ if (part.r_address
+ && auth_context->local_address
+ && !krb5_address_compare (context,
+ auth_context->local_address,
+ part.r_address)) {
+ krb5_clear_error_message (context);
+ ret = KRB5KRB_AP_ERR_BADADDR;
+ goto failure_part;
+ }
+
+ /* check timestamp */
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) {
+ krb5_timestamp sec;
+
+ krb5_timeofday (context, &sec);
+ if (part.timestamp == NULL ||
+ part.usec == NULL ||
+ krb5_time_abs(*part.timestamp, sec) > context->max_skew) {
+ krb5_clear_error_message (context);
+ ret = KRB5KRB_AP_ERR_SKEW;
+ goto failure_part;
+ }
+ }
+
+ /* XXX - check replay cache */
+
+ /* check sequence number. since MIT krb5 cannot generate a sequence
+ number of zero but instead generates no sequence number, we accept that
+ */
+
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) {
+ if ((part.seq_number == NULL
+ && auth_context->remote_seqnumber != 0)
+ || (part.seq_number != NULL
+ && *part.seq_number != auth_context->remote_seqnumber)) {
+ krb5_clear_error_message (context);
+ ret = KRB5KRB_AP_ERR_BADORDER;
+ goto failure_part;
+ }
+ auth_context->remote_seqnumber++;
+ }
+
+ ret = krb5_data_copy (outbuf, part.user_data.data, part.user_data.length);
+ if (ret)
+ goto failure_part;
+
+ if ((auth_context->flags &
+ (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE))) {
+ if(part.timestamp)
+ outdata->timestamp = *part.timestamp;
+ if(part.usec)
+ outdata->usec = *part.usec;
+ if(part.seq_number)
+ outdata->seq = *part.seq_number;
+ }
+
+ failure_part:
+ free_EncKrbPrivPart (&part);
+
+ failure:
+ free_KRB_PRIV (&priv);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/rd_rep.c b/third_party/heimdal/lib/krb5/rd_rep.c
new file mode 100644
index 0000000..9968db3
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/rd_rep.c
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_rep(krb5_context context,
+ krb5_auth_context auth_context,
+ const krb5_data *inbuf,
+ krb5_ap_rep_enc_part **repl)
+{
+ krb5_error_code ret;
+ AP_REP ap_rep;
+ size_t len;
+ krb5_data data;
+ krb5_crypto crypto;
+
+ *repl = NULL;
+ krb5_data_zero (&data);
+
+ ret = decode_AP_REP(inbuf->data, inbuf->length, &ap_rep, &len);
+ if (ret)
+ return ret;
+ if (ap_rep.pvno != 5) {
+ ret = KRB5KRB_AP_ERR_BADVERSION;
+ krb5_clear_error_message (context);
+ goto out;
+ }
+ if (ap_rep.msg_type != krb_ap_rep) {
+ ret = KRB5KRB_AP_ERR_MSG_TYPE;
+ krb5_clear_error_message (context);
+ goto out;
+ }
+
+ ret = krb5_crypto_init(context, auth_context->keyblock, 0, &crypto);
+ if (ret)
+ goto out;
+ ret = krb5_decrypt_EncryptedData(context,
+ crypto,
+ KRB5_KU_AP_REQ_ENC_PART,
+ &ap_rep.enc_part,
+ &data);
+ krb5_crypto_destroy(context, crypto);
+ if (ret)
+ goto out;
+
+ *repl = malloc(sizeof(**repl));
+ if (*repl == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ ret = decode_EncAPRepPart(data.data, data.length, *repl, &len);
+ if (ret) {
+ krb5_set_error_message(context, ret, N_("Failed to decode EncAPRepPart", ""));
+ goto out;
+ }
+
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) {
+ if ((*repl)->ctime != auth_context->authenticator->ctime ||
+ (*repl)->cusec != auth_context->authenticator->cusec)
+ {
+ ret = KRB5KRB_AP_ERR_MUT_FAIL;
+ krb5_clear_error_message(context);
+ goto out;
+ }
+ }
+ if ((*repl)->seq_number)
+ krb5_auth_con_setremoteseqnumber(context, auth_context,
+ *((*repl)->seq_number));
+ if ((*repl)->subkey)
+ krb5_auth_con_setremotesubkey(context, auth_context, (*repl)->subkey);
+
+ out:
+ if (ret) {
+ krb5_free_ap_rep_enc_part(context, *repl);
+ *repl = NULL;
+ }
+ krb5_data_free(&data);
+ free_AP_REP(&ap_rep);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_ap_rep_enc_part (krb5_context context,
+ krb5_ap_rep_enc_part *val)
+{
+ if (val) {
+ free_EncAPRepPart (val);
+ free (val);
+ }
+}
diff --git a/third_party/heimdal/lib/krb5/rd_req.c b/third_party/heimdal/lib/krb5/rd_req.c
new file mode 100644
index 0000000..371037c
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/rd_req.c
@@ -0,0 +1,1108 @@
+
+/*
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+static krb5_error_code
+decrypt_tkt_enc_part (krb5_context context,
+ krb5_keyblock *key,
+ EncryptedData *enc_part,
+ EncTicketPart *decr_part)
+{
+ krb5_error_code ret;
+ krb5_data plain;
+ size_t len;
+ krb5_crypto crypto;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ return ret;
+ ret = krb5_decrypt_EncryptedData (context,
+ crypto,
+ KRB5_KU_TICKET,
+ enc_part,
+ &plain);
+ krb5_crypto_destroy(context, crypto);
+ if (ret)
+ return ret;
+
+ ret = decode_EncTicketPart(plain.data, plain.length, decr_part, &len);
+ if (ret)
+ krb5_set_error_message(context, ret,
+ N_("Failed to decode encrypted "
+ "ticket part", ""));
+ krb5_data_free (&plain);
+ return ret;
+}
+
+static krb5_error_code
+decrypt_authenticator (krb5_context context,
+ EncryptionKey *key,
+ EncryptedData *enc_part,
+ Authenticator *authenticator,
+ krb5_key_usage usage)
+{
+ krb5_error_code ret;
+ krb5_data plain;
+ size_t len;
+ krb5_crypto crypto;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ return ret;
+ ret = krb5_decrypt_EncryptedData (context,
+ crypto,
+ usage /* KRB5_KU_AP_REQ_AUTH */,
+ enc_part,
+ &plain);
+ /* for backwards compatibility, also try the old usage */
+ if (ret && usage == KRB5_KU_TGS_REQ_AUTH)
+ ret = krb5_decrypt_EncryptedData (context,
+ crypto,
+ KRB5_KU_AP_REQ_AUTH,
+ enc_part,
+ &plain);
+ krb5_crypto_destroy(context, crypto);
+ if (ret)
+ return ret;
+
+ ret = decode_Authenticator(plain.data, plain.length,
+ authenticator, &len);
+ krb5_data_free (&plain);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decode_ap_req(krb5_context context,
+ const krb5_data *inbuf,
+ krb5_ap_req *ap_req)
+{
+ krb5_error_code ret;
+ size_t len;
+ ret = decode_AP_REQ(inbuf->data, inbuf->length, ap_req, &len);
+ if (ret)
+ return ret;
+ if (ap_req->pvno != 5){
+ free_AP_REQ(ap_req);
+ krb5_clear_error_message (context);
+ return KRB5KRB_AP_ERR_BADVERSION;
+ }
+ if (ap_req->msg_type != krb_ap_req){
+ free_AP_REQ(ap_req);
+ krb5_clear_error_message (context);
+ return KRB5KRB_AP_ERR_MSG_TYPE;
+ }
+ if (ap_req->ticket.tkt_vno != 5){
+ free_AP_REQ(ap_req);
+ krb5_clear_error_message (context);
+ return KRB5KRB_AP_ERR_BADVERSION;
+ }
+ return 0;
+}
+
+static krb5_error_code
+check_transited(krb5_context context, Ticket *ticket, EncTicketPart *enc)
+{
+ char **realms;
+ unsigned int num_realms, n;
+ krb5_error_code ret;
+
+ /*
+ * Windows 2000 and 2003 uses this inside their TGT so it's normaly
+ * not seen by others, however, samba4 joined with a Windows AD as
+ * a Domain Controller gets exposed to this.
+ */
+ if(enc->transited.tr_type == 0 && enc->transited.contents.length == 0)
+ return 0;
+
+ if(enc->transited.tr_type != domain_X500_Compress)
+ return KRB5KDC_ERR_TRTYPE_NOSUPP;
+
+ if(enc->transited.contents.length == 0)
+ return 0;
+
+ ret = krb5_domain_x500_decode(context, enc->transited.contents,
+ &realms, &num_realms,
+ enc->crealm,
+ ticket->realm);
+ if(ret)
+ return ret;
+ ret = krb5_check_transited(context, enc->crealm,
+ ticket->realm,
+ realms, num_realms, NULL);
+ for (n = 0; n < num_realms; n++)
+ free(realms[n]);
+ free(realms);
+ return ret;
+}
+
+static krb5_error_code
+find_etypelist(krb5_context context,
+ krb5_auth_context auth_context,
+ EtypeList *etypes)
+{
+ krb5_error_code ret;
+ krb5_data data;
+
+ ret = _krb5_get_ad(context, auth_context->authenticator->authorization_data, NULL, KRB5_AUTHDATA_GSS_API_ETYPE_NEGOTIATION, &data);
+ if (ret)
+ return 0;
+
+ ret = decode_EtypeList(data.data, data.length, etypes, NULL);
+ krb5_data_free(&data);
+ if (ret)
+ krb5_clear_error_message(context);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decrypt_ticket(krb5_context context,
+ Ticket *ticket,
+ krb5_keyblock *key,
+ EncTicketPart *out,
+ krb5_flags flags)
+{
+ EncTicketPart t;
+ krb5_error_code ret;
+ ret = decrypt_tkt_enc_part (context, key, &ticket->enc_part, &t);
+ if (ret)
+ return ret;
+
+ {
+ krb5_timestamp now;
+ time_t start = t.authtime;
+
+ krb5_timeofday (context, &now);
+ if(t.starttime)
+ start = *t.starttime;
+ if(start - now > context->max_skew
+ || (t.flags.invalid
+ && !(flags & KRB5_VERIFY_AP_REQ_IGNORE_INVALID))) {
+ free_EncTicketPart(&t);
+ krb5_clear_error_message (context);
+ return KRB5KRB_AP_ERR_TKT_NYV;
+ }
+ if(now - t.endtime > context->max_skew) {
+ free_EncTicketPart(&t);
+ krb5_clear_error_message (context);
+ return KRB5KRB_AP_ERR_TKT_EXPIRED;
+ }
+
+ if(!t.flags.transited_policy_checked) {
+ ret = check_transited(context, ticket, &t);
+ if(ret) {
+ free_EncTicketPart(&t);
+ return ret;
+ }
+ }
+ }
+
+ if(out)
+ *out = t;
+ else
+ free_EncTicketPart(&t);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verify_authenticator_checksum(krb5_context context,
+ krb5_auth_context ac,
+ void *data,
+ size_t len)
+{
+ krb5_error_code ret;
+ krb5_keyblock *key = NULL;
+ krb5_authenticator authenticator;
+ krb5_crypto crypto;
+
+ ret = krb5_auth_con_getauthenticator(context, ac, &authenticator);
+ if (ret)
+ return ret;
+ if (authenticator->cksum == NULL) {
+ ret = -17;
+ goto out;
+ }
+ ret = krb5_auth_con_getkey(context, ac, &key);
+ if (ret)
+ goto out;
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ goto out;
+
+ _krb5_crypto_set_flags(context, crypto, KRB5_CRYPTO_FLAG_ALLOW_UNKEYED_CHECKSUM);
+ ret = krb5_verify_checksum(context, crypto,
+ KRB5_KU_AP_REQ_AUTH_CKSUM,
+ data, len, authenticator->cksum);
+ krb5_crypto_destroy(context, crypto);
+out:
+ krb5_free_authenticator(context, &authenticator);
+ krb5_free_keyblock(context, key);
+ return ret;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verify_ap_req(krb5_context context,
+ krb5_auth_context *auth_context,
+ krb5_ap_req *ap_req,
+ krb5_const_principal server,
+ krb5_keyblock *keyblock,
+ krb5_flags flags,
+ krb5_flags *ap_req_options,
+ krb5_ticket **ticket)
+{
+ return krb5_verify_ap_req2 (context,
+ auth_context,
+ ap_req,
+ server,
+ keyblock,
+ flags,
+ ap_req_options,
+ ticket,
+ KRB5_KU_AP_REQ_AUTH);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verify_ap_req2(krb5_context context,
+ krb5_auth_context *auth_context,
+ krb5_ap_req *ap_req,
+ krb5_const_principal server,
+ krb5_keyblock *keyblock,
+ krb5_flags flags,
+ krb5_flags *ap_req_options,
+ krb5_ticket **ticket,
+ krb5_key_usage usage)
+{
+ krb5_ticket *t;
+ krb5_auth_context ac;
+ krb5_error_code ret;
+ EtypeList etypes;
+ int badaddr = 0;
+
+ memset(&etypes, 0, sizeof(etypes));
+
+ if (ticket)
+ *ticket = NULL;
+
+ if (auth_context && *auth_context) {
+ ac = *auth_context;
+ } else {
+ ret = krb5_auth_con_init (context, &ac);
+ if (ret)
+ return ret;
+ }
+
+ t = calloc(1, sizeof(*t));
+ if (t == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ if (ap_req->ap_options.use_session_key && ac->keyblock){
+ ret = krb5_decrypt_ticket(context, &ap_req->ticket,
+ ac->keyblock,
+ &t->ticket,
+ flags);
+ krb5_free_keyblock(context, ac->keyblock);
+ ac->keyblock = NULL;
+ }else
+ ret = krb5_decrypt_ticket(context, &ap_req->ticket,
+ keyblock,
+ &t->ticket,
+ flags);
+
+ if(ret)
+ goto out;
+
+ ret = _krb5_principalname2krb5_principal(context,
+ &t->server,
+ ap_req->ticket.sname,
+ ap_req->ticket.realm);
+ if (ret) goto out;
+
+ ret = decrypt_authenticator (context,
+ &t->ticket.key,
+ &ap_req->authenticator,
+ ac->authenticator,
+ usage);
+ if (ret)
+ goto out;
+
+ {
+ krb5_principal p1, p2;
+ krb5_boolean res;
+
+ _krb5_principalname2krb5_principal(context,
+ &p1,
+ ac->authenticator->cname,
+ ac->authenticator->crealm);
+ _krb5_principalname2krb5_principal(context,
+ &p2,
+ t->ticket.cname,
+ t->ticket.crealm);
+ res = krb5_principal_compare (context, p1, p2);
+ krb5_free_principal (context, p1);
+ krb5_free_principal (context, p2);
+ if (!res) {
+ ret = KRB5KRB_AP_ERR_BADMATCH;
+ krb5_clear_error_message (context);
+ goto out;
+ }
+ }
+
+ /*
+ * The ticket authenticates the client, and conveys naming attributes that
+ * we want to expose in GSS using RFC6680 APIs.
+ *
+ * So we same the ticket enc-part in the client's krb5_principal object
+ * (note though that the session key will be absent in that copy of the
+ * ticket enc-part).
+ */
+ ret = _krb5_ticket2krb5_principal(context, &t->client, &t->ticket,
+ ac->authenticator->authorization_data);
+ if (ret) goto out;
+
+ t->client->nameattrs->peer_realm =
+ calloc(1, sizeof(t->client->nameattrs->peer_realm[0]));
+ if (t->client->nameattrs->peer_realm == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ ret = copy_Realm(&ap_req->ticket.realm, t->client->nameattrs->peer_realm);
+ if (ret) goto out;
+
+ /* check addresses */
+
+ if (t->ticket.caddr
+ && ac->remote_address
+ && !krb5_address_search (context,
+ ac->remote_address,
+ t->ticket.caddr)) {
+ /*
+ * Hack alert. If KRB5_VERIFY_AP_REQ_IGNORE_ADDRS and the client's
+ * address didn't check out then we'll return KRB5KRB_AP_ERR_BADADDR
+ * even on success, and we'll let the caller figure it out because
+ * `*ticket != NULL' or `*auth_context != NULL'.
+ */
+ if ((flags & KRB5_VERIFY_AP_REQ_IGNORE_ADDRS)) {
+ badaddr = 1;
+ } else {
+ ret = KRB5KRB_AP_ERR_BADADDR;
+ krb5_clear_error_message(context);
+ goto out;
+ }
+ }
+
+ /* check timestamp in authenticator */
+ {
+ krb5_timestamp now;
+
+ krb5_timeofday (context, &now);
+
+ if (krb5_time_abs(ac->authenticator->ctime, now) > context->max_skew) {
+ ret = KRB5KRB_AP_ERR_SKEW;
+ krb5_clear_error_message (context);
+ goto out;
+ }
+ }
+
+ if (ac->authenticator->seq_number)
+ krb5_auth_con_setremoteseqnumber(context, ac,
+ *ac->authenticator->seq_number);
+
+ /* XXX - Xor sequence numbers */
+
+ if (ac->authenticator->subkey) {
+ ret = krb5_auth_con_setremotesubkey(context, ac,
+ ac->authenticator->subkey);
+ if (ret)
+ goto out;
+ }
+
+ ret = find_etypelist(context, ac, &etypes);
+ if (ret)
+ goto out;
+
+ ac->keytype = ETYPE_NULL;
+
+ if (etypes.val) {
+ size_t i;
+
+ for (i = 0; i < etypes.len; i++) {
+ if (krb5_enctype_valid(context, etypes.val[i]) == 0) {
+ ac->keytype = etypes.val[i];
+ break;
+ }
+ }
+ }
+
+ /* save key */
+ ret = krb5_copy_keyblock(context, &t->ticket.key, &ac->keyblock);
+ if (ret) goto out;
+
+ if (ap_req_options) {
+ *ap_req_options = 0;
+ if (ac->keytype != ETYPE_NULL)
+ *ap_req_options |= AP_OPTS_USE_SUBKEY;
+ if (ap_req->ap_options.use_session_key)
+ *ap_req_options |= AP_OPTS_USE_SESSION_KEY;
+ if (ap_req->ap_options.mutual_required)
+ *ap_req_options |= AP_OPTS_MUTUAL_REQUIRED;
+ }
+
+ if(ticket)
+ *ticket = t;
+ else
+ krb5_free_ticket (context, t);
+ if (auth_context) {
+ if (*auth_context == NULL)
+ *auth_context = ac;
+ } else
+ krb5_auth_con_free (context, ac);
+ free_EtypeList(&etypes);
+
+ if (badaddr) {
+ krb5_clear_error_message(context);
+ return KRB5KRB_AP_ERR_BADADDR;
+ }
+ return 0;
+ out:
+ free_EtypeList(&etypes);
+ if (t)
+ krb5_free_ticket (context, t);
+ if (auth_context == NULL || *auth_context == NULL)
+ krb5_auth_con_free (context, ac);
+ return ret;
+}
+
+/*
+ *
+ */
+
+struct krb5_rd_req_in_ctx_data {
+ krb5_keytab keytab;
+ krb5_keyblock *keyblock;
+ krb5_boolean check_pac;
+};
+
+struct krb5_rd_req_out_ctx_data {
+ krb5_keyblock *keyblock;
+ krb5_flags ap_req_options;
+ krb5_ticket *ticket;
+ krb5_principal server;
+};
+
+/**
+ * Allocate a krb5_rd_req_in_ctx as an input parameter to
+ * krb5_rd_req_ctx(). The caller should free the context with
+ * krb5_rd_req_in_ctx_free() when done with the context.
+ *
+ * @param context Keberos 5 context.
+ * @param ctx in ctx to krb5_rd_req_ctx().
+ *
+ * @return Kerberos 5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_auth
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_in_ctx_alloc(krb5_context context, krb5_rd_req_in_ctx *ctx)
+{
+ *ctx = calloc(1, sizeof(**ctx));
+ if (*ctx == NULL)
+ return krb5_enomem(context);
+ (*ctx)->check_pac = (context->flags & KRB5_CTX_F_CHECK_PAC) ? 1 : 0;
+ return 0;
+}
+
+/**
+ * Set the keytab that krb5_rd_req_ctx() will use.
+ *
+ * @param context Keberos 5 context.
+ * @param in in ctx to krb5_rd_req_ctx().
+ * @param keytab keytab that krb5_rd_req_ctx() will use, only copy the
+ * pointer, so the caller must free they keytab after
+ * krb5_rd_req_in_ctx_free() is called.
+ *
+ * @return Kerberos 5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_auth
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_in_set_keytab(krb5_context context,
+ krb5_rd_req_in_ctx in,
+ krb5_keytab keytab)
+{
+ in->keytab = keytab;
+ return 0;
+}
+
+/**
+ * Set if krb5_rq_red() is going to check the Windows PAC or not
+ *
+ * @param context Keberos 5 context.
+ * @param in krb5_rd_req_in_ctx to check the option on.
+ * @param flag flag to select if to check the pac (TRUE) or not (FALSE).
+ *
+ * @return Kerberos 5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_auth
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_in_set_pac_check(krb5_context context,
+ krb5_rd_req_in_ctx in,
+ krb5_boolean flag)
+{
+ in->check_pac = flag;
+ return 0;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_in_set_keyblock(krb5_context context,
+ krb5_rd_req_in_ctx in,
+ krb5_keyblock *keyblock)
+{
+ in->keyblock = keyblock; /* XXX should make copy */
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_out_get_ap_req_options(krb5_context context,
+ krb5_rd_req_out_ctx out,
+ krb5_flags *ap_req_options)
+{
+ *ap_req_options = out->ap_req_options;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_out_get_ticket(krb5_context context,
+ krb5_rd_req_out_ctx out,
+ krb5_ticket **ticket)
+{
+ return krb5_copy_ticket(context, out->ticket, ticket);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_out_get_keyblock(krb5_context context,
+ krb5_rd_req_out_ctx out,
+ krb5_keyblock **keyblock)
+{
+ return krb5_copy_keyblock(context, out->keyblock, keyblock);
+}
+
+/**
+ * Get the principal that was used in the request from the
+ * client. Might not match whats in the ticket if krb5_rd_req_ctx()
+ * searched in the keytab for a matching key.
+ *
+ * @param context a Kerberos 5 context.
+ * @param out a krb5_rd_req_out_ctx from krb5_rd_req_ctx().
+ * @param principal return principal, free with krb5_free_principal().
+ *
+ * @ingroup krb5_auth
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_out_get_server(krb5_context context,
+ krb5_rd_req_out_ctx out,
+ krb5_principal *principal)
+{
+ return krb5_copy_principal(context, out->server, principal);
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_rd_req_in_ctx_free(krb5_context context, krb5_rd_req_in_ctx ctx)
+{
+ free(ctx);
+}
+
+/**
+ * Free the krb5_rd_req_out_ctx.
+ *
+ * @param context Keberos 5 context.
+ * @param ctx krb5_rd_req_out_ctx context to free.
+ *
+ * @ingroup krb5_auth
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_rd_req_out_ctx_free(krb5_context context, krb5_rd_req_out_ctx ctx)
+{
+ if (ctx->ticket)
+ krb5_free_ticket(context, ctx->ticket);
+ if (ctx->keyblock)
+ krb5_free_keyblock(context, ctx->keyblock);
+ if (ctx->server)
+ krb5_free_principal(context, ctx->server);
+ free(ctx);
+}
+
+/**
+ * Process an AP_REQ message.
+ *
+ * @param context Kerberos 5 context.
+ * @param auth_context authentication context of the peer.
+ * @param inbuf the AP_REQ message, obtained for example with krb5_read_message().
+ * @param server server principal.
+ * @param keytab server keytab.
+ * @param ap_req_options set to the AP_REQ options. See the AP_OPTS_* defines.
+ * @param ticket on success, set to the authenticated client credentials.
+ * Must be deallocated with krb5_free_ticket(). If not
+ * interested, pass a NULL value.
+ *
+ * @return 0 to indicate success. Otherwise a Kerberos error code is
+ * returned, see krb5_get_error_message().
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req(krb5_context context,
+ krb5_auth_context *auth_context,
+ const krb5_data *inbuf,
+ krb5_const_principal server,
+ krb5_keytab keytab,
+ krb5_flags *ap_req_options,
+ krb5_ticket **ticket)
+{
+ krb5_error_code ret;
+ krb5_rd_req_in_ctx in;
+ krb5_rd_req_out_ctx out;
+
+ ret = krb5_rd_req_in_ctx_alloc(context, &in);
+ if (ret)
+ return ret;
+
+ ret = krb5_rd_req_in_set_keytab(context, in, keytab);
+ if (ret) {
+ krb5_rd_req_in_ctx_free(context, in);
+ return ret;
+ }
+
+ ret = krb5_rd_req_ctx(context, auth_context, inbuf, server, in, &out);
+ krb5_rd_req_in_ctx_free(context, in);
+ if (ret)
+ return ret;
+
+ if (ap_req_options)
+ *ap_req_options = out->ap_req_options;
+ if (ticket) {
+ ret = krb5_copy_ticket(context, out->ticket, ticket);
+ if (ret)
+ goto out;
+ }
+
+out:
+ krb5_rd_req_out_ctx_free(context, out);
+ return ret;
+}
+
+/*
+ *
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_with_keyblock(krb5_context context,
+ krb5_auth_context *auth_context,
+ const krb5_data *inbuf,
+ krb5_const_principal server,
+ krb5_keyblock *keyblock,
+ krb5_flags *ap_req_options,
+ krb5_ticket **ticket)
+{
+ krb5_error_code ret;
+ krb5_rd_req_in_ctx in;
+ krb5_rd_req_out_ctx out;
+
+ ret = krb5_rd_req_in_ctx_alloc(context, &in);
+ if (ret)
+ return ret;
+
+ ret = krb5_rd_req_in_set_keyblock(context, in, keyblock);
+ if (ret) {
+ krb5_rd_req_in_ctx_free(context, in);
+ return ret;
+ }
+
+ ret = krb5_rd_req_ctx(context, auth_context, inbuf, server, in, &out);
+ krb5_rd_req_in_ctx_free(context, in);
+ if (ret)
+ return ret;
+
+ if (ap_req_options)
+ *ap_req_options = out->ap_req_options;
+ if (ticket) {
+ ret = krb5_copy_ticket(context, out->ticket, ticket);
+ if (ret)
+ goto out;
+ }
+
+out:
+ krb5_rd_req_out_ctx_free(context, out);
+ return ret;
+}
+
+/*
+ *
+ */
+
+static krb5_error_code
+get_key_from_keytab(krb5_context context,
+ krb5_ap_req *ap_req,
+ krb5_const_principal server,
+ krb5_keytab keytab,
+ krb5_keyblock **out_key)
+{
+ krb5_keytab_entry entry;
+ krb5_error_code ret;
+ int kvno;
+ krb5_keytab real_keytab;
+
+ if(keytab == NULL)
+ krb5_kt_default(context, &real_keytab);
+ else
+ real_keytab = keytab;
+
+ if (ap_req->ticket.enc_part.kvno)
+ kvno = *ap_req->ticket.enc_part.kvno;
+ else
+ kvno = 0;
+
+ ret = krb5_kt_get_entry (context,
+ real_keytab,
+ server,
+ kvno,
+ ap_req->ticket.enc_part.etype,
+ &entry);
+ if(ret == 0) {
+ ret = krb5_copy_keyblock(context, &entry.keyblock, out_key);
+ krb5_kt_free_entry(context, &entry);
+ }
+ if(keytab == NULL)
+ krb5_kt_close(context, real_keytab);
+
+ return ret;
+}
+
+/**
+ * The core server function that verify application authentication
+ * requests from clients.
+ *
+ * @param context Keberos 5 context.
+ * @param auth_context the authentication context, can be NULL, then
+ * default values for the authentication context will used.
+ * @param inbuf the (AP-REQ) authentication buffer
+ *
+ * @param server the server to authenticate to. If NULL the function
+ * will try to find any available credential in the keytab
+ * that will verify the reply. The function will prefer the
+ * server specified in the AP-REQ, but if
+ * there is no mach, it will try all keytab entries for a
+ * match. This has serious performance issues for large keytabs.
+ *
+ * @param inctx control the behavior of the function, if NULL, the
+ * default behavior is used.
+ * @param outctx the return outctx, free with krb5_rd_req_out_ctx_free().
+ * @return Kerberos 5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_auth
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_ctx(krb5_context context,
+ krb5_auth_context *auth_context,
+ const krb5_data *inbuf,
+ krb5_const_principal server,
+ krb5_rd_req_in_ctx inctx,
+ krb5_rd_req_out_ctx *outctx)
+{
+ krb5_error_code ret;
+ krb5_ap_req ap_req;
+ krb5_rd_req_out_ctx o = NULL;
+ krb5_keytab id = NULL, keytab = NULL;
+ krb5_principal service = NULL;
+
+ if (outctx)
+ *outctx = NULL;
+
+ o = calloc(1, sizeof(*o));
+ if (o == NULL)
+ return krb5_enomem(context);
+
+ if (*auth_context == NULL) {
+ ret = krb5_auth_con_init(context, auth_context);
+ if (ret)
+ goto out;
+ }
+
+ ret = krb5_decode_ap_req(context, inbuf, &ap_req);
+ if(ret)
+ goto out;
+
+ /* Save the principal that was in the request */
+ ret = _krb5_principalname2krb5_principal(context,
+ &o->server,
+ ap_req.ticket.sname,
+ ap_req.ticket.realm);
+ if (ret)
+ goto out;
+
+ if (ap_req.ap_options.use_session_key &&
+ (*auth_context)->keyblock == NULL) {
+ ret = KRB5KRB_AP_ERR_NOKEY;
+ krb5_set_error_message(context, ret,
+ N_("krb5_rd_req: user to user auth "
+ "without session key given", ""));
+ goto out;
+ }
+
+ if (inctx && inctx->keytab)
+ id = inctx->keytab;
+
+ if((*auth_context)->keyblock){
+ ret = krb5_copy_keyblock(context,
+ (*auth_context)->keyblock,
+ &o->keyblock);
+ if (ret)
+ goto out;
+ } else if(inctx && inctx->keyblock){
+ ret = krb5_copy_keyblock(context,
+ inctx->keyblock,
+ &o->keyblock);
+ if (ret)
+ goto out;
+ } else {
+
+ if(id == NULL) {
+ krb5_kt_default(context, &keytab);
+ id = keytab;
+ }
+ if (id == NULL)
+ goto out;
+
+ if (server == NULL) {
+ ret = _krb5_principalname2krb5_principal(context,
+ &service,
+ ap_req.ticket.sname,
+ ap_req.ticket.realm);
+ if (ret)
+ goto out;
+ server = service;
+ }
+
+ ret = get_key_from_keytab(context,
+ &ap_req,
+ server,
+ id,
+ &o->keyblock);
+ if (ret) {
+ /* If caller specified a server, fail. */
+ if (service == NULL && (context->flags & KRB5_CTX_F_RD_REQ_IGNORE) == 0)
+ goto out;
+ /* Otherwise, fall back to iterating over the keytab. This
+ * have serious performace issues for larger keytab.
+ */
+ o->keyblock = NULL;
+ }
+ }
+
+ if (o->keyblock) {
+ /*
+ * We got an exact keymatch, use that.
+ */
+
+ ret = krb5_verify_ap_req2(context,
+ auth_context,
+ &ap_req,
+ server,
+ o->keyblock,
+ 0,
+ &o->ap_req_options,
+ &o->ticket,
+ KRB5_KU_AP_REQ_AUTH);
+
+ if (ret)
+ goto out;
+
+ } else {
+ /*
+ * Interate over keytab to find a key that can decrypt the request.
+ */
+
+ krb5_keytab_entry entry;
+ krb5_kt_cursor cursor;
+ int done = 0, kvno = 0;
+
+ memset(&cursor, 0, sizeof(cursor));
+
+ if (ap_req.ticket.enc_part.kvno)
+ kvno = *ap_req.ticket.enc_part.kvno;
+
+ ret = krb5_kt_start_seq_get(context, id, &cursor);
+ if (ret)
+ goto out;
+
+ done = 0;
+ while (!done) {
+ krb5_principal p;
+
+ ret = krb5_kt_next_entry(context, id, &entry, &cursor);
+ if (ret) {
+ _krb5_kt_principal_not_found(context, ret, id, o->server,
+ ap_req.ticket.enc_part.etype,
+ kvno);
+ break;
+ }
+
+ if (entry.keyblock.keytype != ap_req.ticket.enc_part.etype) {
+ krb5_kt_free_entry (context, &entry);
+ continue;
+ }
+
+ ret = krb5_verify_ap_req2(context,
+ auth_context,
+ &ap_req,
+ server,
+ &entry.keyblock,
+ 0,
+ &o->ap_req_options,
+ &o->ticket,
+ KRB5_KU_AP_REQ_AUTH);
+ if (ret) {
+ krb5_kt_free_entry (context, &entry);
+ continue;
+ }
+
+ /*
+ * Found a match, save the keyblock for PAC processing,
+ * and update the service principal in the ticket to match
+ * whatever is in the keytab.
+ */
+
+ ret = krb5_copy_keyblock(context,
+ &entry.keyblock,
+ &o->keyblock);
+ if (ret) {
+ krb5_kt_free_entry (context, &entry);
+ break;
+ }
+
+ ret = krb5_copy_principal(context, entry.principal, &p);
+ if (ret) {
+ krb5_kt_free_entry (context, &entry);
+ break;
+ }
+ krb5_free_principal(context, o->ticket->server);
+ o->ticket->server = p;
+
+ krb5_kt_free_entry (context, &entry);
+
+ done = 1;
+ }
+ krb5_kt_end_seq_get (context, id, &cursor);
+ if (ret)
+ goto out;
+ }
+
+ ret = krb5_ticket_get_authorization_data_type(context, o->ticket,
+ KRB5_AUTHDATA_KDC_ISSUED,
+ NULL);
+ if (ret == 0)
+ o->ticket->client->nameattrs->kdc_issued_verified = 1;
+
+ /* If there is a PAC, verify its server signature */
+ if (inctx == NULL || inctx->check_pac) {
+ krb5_pac pac;
+ krb5_data data;
+
+ ret = krb5_ticket_get_authorization_data_type(context,
+ o->ticket,
+ KRB5_AUTHDATA_WIN2K_PAC,
+ &data);
+ if (ret == 0) {
+ ret = krb5_pac_parse(context, data.data, data.length, &pac);
+ krb5_data_free(&data);
+ if (ret)
+ goto out;
+
+ ret = krb5_pac_verify(context,
+ pac,
+ o->ticket->ticket.authtime,
+ o->ticket->client,
+ o->keyblock,
+ NULL);
+ if (ret == 0)
+ o->ticket->client->nameattrs->pac_verified = 1;
+ if (ret == 0 && (context->flags & KRB5_CTX_F_REPORT_CANONICAL_CLIENT_NAME)) {
+ krb5_error_code ret2;
+ krb5_principal canon_name;
+
+ ret2 = _krb5_pac_get_canon_principal(context, pac, &canon_name);
+ if (ret2 == 0) {
+ free_Realm(&o->ticket->client->realm);
+ free_PrincipalName(&o->ticket->client->name);
+ ret = copy_Realm(&canon_name->realm, &o->ticket->client->realm);
+ if (ret == 0)
+ ret = copy_PrincipalName(&canon_name->name, &o->ticket->client->name);
+ krb5_free_principal(context, canon_name);
+ } else if (ret2 != ENOENT)
+ ret = ret2;
+ }
+ if (ret) {
+ krb5_pac_free(context, pac);
+ goto out;
+ }
+ o->ticket->client->nameattrs->pac = pac;
+ } else
+ ret = 0;
+ }
+out:
+
+ if (ret || outctx == NULL)
+ krb5_rd_req_out_ctx_free(context, o);
+ else
+ *outctx = o;
+
+ free_AP_REQ(&ap_req);
+
+ if (service)
+ krb5_free_principal(context, service);
+
+ if (keytab)
+ krb5_kt_close(context, keytab);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/rd_safe.c b/third_party/heimdal/lib/krb5/rd_safe.c
new file mode 100644
index 0000000..24ed636
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/rd_safe.c
@@ -0,0 +1,214 @@
+/*
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+static krb5_error_code
+verify_checksum(krb5_context context,
+ krb5_auth_context auth_context,
+ KRB_SAFE *safe)
+{
+ krb5_error_code ret;
+ u_char *buf;
+ size_t buf_size;
+ size_t len = 0;
+ Checksum c;
+ krb5_crypto crypto;
+ krb5_keyblock *key;
+
+ c = safe->cksum;
+ safe->cksum.cksumtype = 0;
+ safe->cksum.checksum.data = NULL;
+ safe->cksum.checksum.length = 0;
+
+ ASN1_MALLOC_ENCODE(KRB_SAFE, buf, buf_size, safe, &len, ret);
+ if(ret)
+ return ret;
+ if(buf_size != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ if (auth_context->remote_subkey)
+ key = auth_context->remote_subkey;
+ else if (auth_context->local_subkey)
+ key = auth_context->local_subkey;
+ else
+ key = auth_context->keyblock;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ goto out;
+ ret = krb5_verify_checksum (context,
+ crypto,
+ KRB5_KU_KRB_SAFE_CKSUM,
+ buf + buf_size - len,
+ len,
+ &c);
+ krb5_crypto_destroy(context, crypto);
+out:
+ safe->cksum = c;
+ free (buf);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_safe(krb5_context context,
+ krb5_auth_context auth_context,
+ const krb5_data *inbuf,
+ krb5_data *outbuf,
+ krb5_replay_data *outdata)
+{
+ krb5_error_code ret;
+ KRB_SAFE safe;
+ size_t len;
+
+ krb5_data_zero(outbuf);
+
+ if ((auth_context->flags &
+ (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)))
+ {
+ if (outdata == NULL) {
+ krb5_set_error_message(context, KRB5_RC_REQUIRED,
+ N_("rd_safe: need outdata "
+ "to return data", ""));
+ return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */
+ }
+ /* if these fields are not present in the safe-part, silently
+ return zero */
+ memset(outdata, 0, sizeof(*outdata));
+ }
+
+ ret = decode_KRB_SAFE (inbuf->data, inbuf->length, &safe, &len);
+ if (ret)
+ return ret;
+ if (safe.pvno != 5) {
+ ret = KRB5KRB_AP_ERR_BADVERSION;
+ krb5_clear_error_message (context);
+ goto failure;
+ }
+ if (safe.msg_type != krb_safe) {
+ ret = KRB5KRB_AP_ERR_MSG_TYPE;
+ krb5_clear_error_message (context);
+ goto failure;
+ }
+ if (!krb5_checksum_is_keyed(context, safe.cksum.cksumtype)
+ || !krb5_checksum_is_collision_proof(context, safe.cksum.cksumtype)) {
+ ret = KRB5KRB_AP_ERR_INAPP_CKSUM;
+ krb5_clear_error_message (context);
+ goto failure;
+ }
+
+ /* check sender address */
+
+ if (safe.safe_body.s_address
+ && auth_context->remote_address
+ && !krb5_address_compare (context,
+ auth_context->remote_address,
+ safe.safe_body.s_address)) {
+ ret = KRB5KRB_AP_ERR_BADADDR;
+ krb5_clear_error_message (context);
+ goto failure;
+ }
+
+ /* check receiver address */
+
+ if (safe.safe_body.r_address
+ && auth_context->local_address
+ && !krb5_address_compare (context,
+ auth_context->local_address,
+ safe.safe_body.r_address)) {
+ ret = KRB5KRB_AP_ERR_BADADDR;
+ krb5_clear_error_message (context);
+ goto failure;
+ }
+
+ /* check timestamp */
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) {
+ krb5_timestamp sec;
+
+ krb5_timeofday (context, &sec);
+
+ if (safe.safe_body.timestamp == NULL ||
+ safe.safe_body.usec == NULL ||
+ krb5_time_abs(*safe.safe_body.timestamp, sec) > context->max_skew) {
+ ret = KRB5KRB_AP_ERR_SKEW;
+ krb5_clear_error_message (context);
+ goto failure;
+ }
+ }
+ /* XXX - check replay cache */
+
+ /* check sequence number. since MIT krb5 cannot generate a sequence
+ number of zero but instead generates no sequence number, we accept that
+ */
+
+ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) {
+ if ((safe.safe_body.seq_number == NULL
+ && auth_context->remote_seqnumber != 0)
+ || (safe.safe_body.seq_number != NULL
+ && *safe.safe_body.seq_number !=
+ auth_context->remote_seqnumber)) {
+ ret = KRB5KRB_AP_ERR_BADORDER;
+ krb5_clear_error_message (context);
+ goto failure;
+ }
+ auth_context->remote_seqnumber++;
+ }
+
+ ret = verify_checksum (context, auth_context, &safe);
+ if (ret)
+ goto failure;
+
+ outbuf->length = safe.safe_body.user_data.length;
+ outbuf->data = malloc(outbuf->length);
+ if (outbuf->data == NULL && outbuf->length != 0) {
+ ret = krb5_enomem(context);
+ krb5_data_zero(outbuf);
+ goto failure;
+ }
+ memcpy (outbuf->data, safe.safe_body.user_data.data, outbuf->length);
+
+ if ((auth_context->flags &
+ (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE))) {
+
+ if(safe.safe_body.timestamp)
+ outdata->timestamp = *safe.safe_body.timestamp;
+ if(safe.safe_body.usec)
+ outdata->usec = *safe.safe_body.usec;
+ if(safe.safe_body.seq_number)
+ outdata->seq = *safe.safe_body.seq_number;
+ }
+
+ failure:
+ free_KRB_SAFE (&safe);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/read_message.c b/third_party/heimdal/lib/krb5/read_message.c
new file mode 100644
index 0000000..4e9bd01
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/read_message.c
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_read_message (krb5_context context,
+ krb5_pointer p_fd,
+ krb5_data *data)
+{
+ krb5_error_code ret;
+ uint32_t len;
+ uint8_t buf[4];
+
+ krb5_data_zero(data);
+
+ ret = krb5_net_read (context, p_fd, buf, 4);
+ if(ret == -1) {
+ ret = errno;
+ krb5_clear_error_message (context);
+ return ret;
+ }
+ if(ret < 4) {
+ krb5_clear_error_message(context);
+ return HEIM_ERR_EOF;
+ }
+ len = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
+ ret = krb5_data_alloc (data, len);
+ if (ret) {
+ krb5_clear_error_message(context);
+ return ret;
+ }
+ if (krb5_net_read (context, p_fd, data->data, len) != len) {
+ ret = errno;
+ krb5_data_free (data);
+ krb5_clear_error_message (context);
+ return ret;
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_read_priv_message(krb5_context context,
+ krb5_auth_context ac,
+ krb5_pointer p_fd,
+ krb5_data *data)
+{
+ krb5_error_code ret;
+ krb5_data packet;
+
+ ret = krb5_read_message(context, p_fd, &packet);
+ if(ret)
+ return ret;
+ ret = krb5_rd_priv (context, ac, &packet, data, NULL);
+ krb5_data_free(&packet);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_read_safe_message(krb5_context context,
+ krb5_auth_context ac,
+ krb5_pointer p_fd,
+ krb5_data *data)
+{
+ krb5_error_code ret;
+ krb5_data packet;
+
+ ret = krb5_read_message(context, p_fd, &packet);
+ if(ret)
+ return ret;
+ ret = krb5_rd_safe (context, ac, &packet, data, NULL);
+ krb5_data_free(&packet);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/recvauth.c b/third_party/heimdal/lib/krb5/recvauth.c
new file mode 100644
index 0000000..caf1451
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/recvauth.c
@@ -0,0 +1,264 @@
+/*
+ * Copyright (c) 1997-2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/*
+ * See `sendauth.c' for the format.
+ */
+
+static krb5_boolean
+match_exact(const void *data, const char *appl_version)
+{
+ return strcmp(data, appl_version) == 0;
+}
+
+/**
+ * Perform the server side of the sendauth protocol.
+ *
+ * @param context Kerberos 5 context.
+ * @param auth_context authentication context of the peer.
+ * @param p_fd socket associated to the connection.
+ * @param appl_version server-specific string.
+ * @param server server principal.
+ * @param flags if KRB5_RECVAUTH_IGNORE_VERSION is set, skip the sendauth version
+ * part of the protocol.
+ * @param keytab server keytab.
+ * @param ticket on success, set to the authenticated client credentials.
+ * Must be deallocated with krb5_free_ticket(). If not
+ * interested, pass a NULL value.
+ *
+ * @return 0 to indicate success. Otherwise a Kerberos error code is
+ * returned, see krb5_get_error_message().
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_recvauth(krb5_context context,
+ krb5_auth_context *auth_context,
+ krb5_pointer p_fd,
+ const char *appl_version,
+ krb5_principal server,
+ int32_t flags,
+ krb5_keytab keytab,
+ krb5_ticket **ticket)
+{
+ return krb5_recvauth_match_version(context, auth_context, p_fd,
+ match_exact, appl_version,
+ server, flags,
+ keytab, ticket);
+}
+
+/**
+ * Perform the server side of the sendauth protocol like krb5_recvauth(), but support
+ * a user-specified callback, \a match_appl_version, to perform the match of the application
+ * version \a match_data.
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_recvauth_match_version(krb5_context context,
+ krb5_auth_context *auth_context,
+ krb5_pointer p_fd,
+ krb5_boolean (*match_appl_version)(const void *,
+ const char*),
+ const void *match_data,
+ krb5_principal server,
+ int32_t flags,
+ krb5_keytab keytab,
+ krb5_ticket **ticket)
+{
+ krb5_error_code ret;
+ const char *version = KRB5_SENDAUTH_VERSION;
+ char her_version[sizeof(KRB5_SENDAUTH_VERSION)];
+ char *her_appl_version;
+ uint32_t len;
+ u_char repl;
+ krb5_data data;
+ krb5_flags ap_options;
+ ssize_t n;
+
+ /*
+ * If there are no addresses in auth_context, get them from `fd'.
+ */
+
+ if (*auth_context == NULL) {
+ ret = krb5_auth_con_init (context, auth_context);
+ if (ret)
+ return ret;
+ }
+
+ ret = krb5_auth_con_setaddrs_from_fd (context,
+ *auth_context,
+ p_fd);
+ if (ret)
+ return ret;
+
+ /*
+ * Expect SENDAUTH protocol version.
+ */
+ if(!(flags & KRB5_RECVAUTH_IGNORE_VERSION)) {
+ n = krb5_net_read (context, p_fd, &len, 4);
+ if (n < 0) {
+ ret = errno ? errno : EINVAL;
+ krb5_set_error_message(context, ret, "read: %s", strerror(ret));
+ return ret;
+ }
+ if (n == 0) {
+ krb5_set_error_message(context, KRB5_SENDAUTH_BADAUTHVERS,
+ N_("Failed to receive sendauth data", ""));
+ return KRB5_SENDAUTH_BADAUTHVERS;
+ }
+ len = ntohl(len);
+ if (len != sizeof(her_version)
+ || krb5_net_read (context, p_fd, her_version, len) != len
+ || strncmp (version, her_version, len) != 0) {
+ repl = 1;
+ krb5_net_write (context, p_fd, &repl, 1);
+ krb5_clear_error_message (context);
+ return KRB5_SENDAUTH_BADAUTHVERS;
+ }
+ }
+
+ /*
+ * Expect application protocol version.
+ */
+ n = krb5_net_read (context, p_fd, &len, 4);
+ if (n < 0) {
+ ret = errno ? errno : EINVAL;
+ krb5_set_error_message(context, ret, "read: %s", strerror(ret));
+ return ret;
+ }
+ if (n == 0) {
+ krb5_clear_error_message (context);
+ return KRB5_SENDAUTH_BADAPPLVERS;
+ }
+ len = ntohl(len);
+ her_appl_version = malloc (len);
+ if (her_appl_version == NULL) {
+ repl = 2;
+ krb5_net_write (context, p_fd, &repl, 1);
+ return krb5_enomem(context);
+ }
+ if (krb5_net_read (context, p_fd, her_appl_version, len) != len
+ || !(*match_appl_version)(match_data, her_appl_version)) {
+ repl = 2;
+ krb5_net_write (context, p_fd, &repl, 1);
+ krb5_set_error_message(context, KRB5_SENDAUTH_BADAPPLVERS,
+ N_("wrong sendauth application version (%s)", ""),
+ her_appl_version);
+ free (her_appl_version);
+ return KRB5_SENDAUTH_BADAPPLVERS;
+ }
+ free (her_appl_version);
+
+ /*
+ * Send OK.
+ */
+ repl = 0;
+ if (krb5_net_write (context, p_fd, &repl, 1) != 1) {
+ ret = errno ? errno : EINVAL;
+ krb5_set_error_message(context, ret, "write: %s", strerror(ret));
+ return ret;
+ }
+
+ /*
+ * Until here, the fields in the message were in cleartext and unauthenticated.
+ * From now on, Kerberos kicks in.
+ */
+
+ /*
+ * Expect AP_REQ.
+ */
+ krb5_data_zero (&data);
+ ret = krb5_read_message (context, p_fd, &data);
+ if (ret)
+ return ret;
+
+ ret = krb5_rd_req (context,
+ auth_context,
+ &data,
+ server,
+ keytab,
+ &ap_options,
+ ticket);
+ krb5_data_free (&data);
+ if (ret) {
+ krb5_data error_data;
+ krb5_error_code ret2;
+
+ ret2 = krb5_mk_error (context,
+ ret,
+ NULL,
+ NULL,
+ NULL,
+ server,
+ NULL,
+ NULL,
+ &error_data);
+ if (ret2 == 0) {
+ krb5_write_message (context, p_fd, &error_data);
+ krb5_data_free (&error_data);
+ }
+ return ret;
+ }
+
+ /*
+ * Send OK.
+ */
+ len = 0;
+ if (krb5_net_write (context, p_fd, &len, 4) != 4) {
+ ret = errno ? errno : EINVAL;
+ krb5_set_error_message(context, ret, "write: %s", strerror(ret));
+ krb5_free_ticket(context, *ticket);
+ *ticket = NULL;
+ return ret;
+ }
+
+ /*
+ * If client requires mutual authentication, send AP_REP.
+ */
+ if (ap_options & AP_OPTS_MUTUAL_REQUIRED) {
+ ret = krb5_mk_rep (context, *auth_context, &data);
+ if (ret) {
+ krb5_free_ticket(context, *ticket);
+ *ticket = NULL;
+ return ret;
+ }
+
+ ret = krb5_write_message (context, p_fd, &data);
+ if (ret) {
+ krb5_free_ticket(context, *ticket);
+ *ticket = NULL;
+ return ret;
+ }
+ krb5_data_free (&data);
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/replay.c b/third_party/heimdal/lib/krb5/replay.c
new file mode 100644
index 0000000..2fec8af
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/replay.c
@@ -0,0 +1,328 @@
+/*
+ * Copyright (c) 1997-2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include <vis.h>
+
+struct krb5_rcache_data {
+ char *name;
+};
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rc_resolve(krb5_context context,
+ krb5_rcache id,
+ const char *name)
+{
+ id->name = strdup(name);
+ if(id->name == NULL) {
+ krb5_set_error_message(context, KRB5_RC_MALLOC,
+ N_("malloc: out of memory", ""));
+ return KRB5_RC_MALLOC;
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rc_resolve_type(krb5_context context,
+ krb5_rcache *id,
+ const char *type)
+{
+ *id = NULL;
+ if (strcmp(type, "FILE") != 0) {
+ krb5_set_error_message (context, KRB5_RC_TYPE_NOTFOUND,
+ N_("replay cache type %s not supported", ""),
+ type);
+ return KRB5_RC_TYPE_NOTFOUND;
+ }
+ *id = calloc(1, sizeof(**id));
+ if(*id == NULL) {
+ krb5_set_error_message(context, KRB5_RC_MALLOC,
+ N_("malloc: out of memory", ""));
+ return KRB5_RC_MALLOC;
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rc_resolve_full(krb5_context context,
+ krb5_rcache *id,
+ const char *string_name)
+{
+ krb5_error_code ret;
+
+ *id = NULL;
+
+ if (strncmp(string_name, "FILE:", 5) != 0) {
+ krb5_set_error_message(context, KRB5_RC_TYPE_NOTFOUND,
+ N_("replay cache type %s not supported", ""),
+ string_name);
+ return KRB5_RC_TYPE_NOTFOUND;
+ }
+ ret = krb5_rc_resolve_type(context, id, "FILE");
+ if(ret)
+ return ret;
+ ret = krb5_rc_resolve(context, *id, string_name + 5);
+ if (ret) {
+ krb5_rc_close(context, *id);
+ *id = NULL;
+ }
+ return ret;
+}
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_rc_default_name(krb5_context context)
+{
+ return "FILE:/var/run/default_rcache";
+}
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_rc_default_type(krb5_context context)
+{
+ return "FILE";
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rc_default(krb5_context context,
+ krb5_rcache *id)
+{
+ return krb5_rc_resolve_full(context, id, krb5_rc_default_name(context));
+}
+
+struct rc_entry{
+ time_t stamp;
+ unsigned char data[16];
+};
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rc_initialize(krb5_context context,
+ krb5_rcache id,
+ krb5_deltat auth_lifespan)
+{
+ FILE *f = fopen(id->name, "w");
+ struct rc_entry tmp;
+ int ret;
+
+ if(f == NULL) {
+ char buf[128];
+ ret = errno;
+ rk_strerror_r(ret, buf, sizeof(buf));
+ krb5_set_error_message(context, ret, "open(%s): %s", id->name, buf);
+ return ret;
+ }
+ memset(&tmp, 0, sizeof(tmp));
+ tmp.stamp = auth_lifespan;
+ fwrite(&tmp, 1, sizeof(tmp), f);
+ fclose(f);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rc_recover(krb5_context context,
+ krb5_rcache id)
+{
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rc_destroy(krb5_context context,
+ krb5_rcache id)
+{
+ int ret;
+
+ if(remove(id->name) < 0) {
+ char buf[128];
+ ret = errno;
+ rk_strerror_r(ret, buf, sizeof(buf));
+ krb5_set_error_message(context, ret, "remove(%s): %s", id->name, buf);
+ return ret;
+ }
+ return krb5_rc_close(context, id);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rc_close(krb5_context context,
+ krb5_rcache id)
+{
+ free(id->name);
+ free(id);
+ return 0;
+}
+
+static void
+checksum_authenticator(Authenticator *auth, void *data)
+{
+ EVP_MD_CTX *m = EVP_MD_CTX_create();
+ unsigned i;
+
+ EVP_DigestInit_ex(m, EVP_md5(), NULL);
+
+ EVP_DigestUpdate(m, auth->crealm, strlen(auth->crealm));
+ for(i = 0; i < auth->cname.name_string.len; i++)
+ EVP_DigestUpdate(m, auth->cname.name_string.val[i],
+ strlen(auth->cname.name_string.val[i]));
+ EVP_DigestUpdate(m, &auth->ctime, sizeof(auth->ctime));
+ EVP_DigestUpdate(m, &auth->cusec, sizeof(auth->cusec));
+
+ EVP_DigestFinal_ex(m, data, NULL);
+ EVP_MD_CTX_destroy(m);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rc_store(krb5_context context,
+ krb5_rcache id,
+ krb5_donot_replay *rep)
+{
+ struct rc_entry ent, tmp;
+ time_t t;
+ FILE *f;
+ int ret;
+ size_t count;
+
+ ent.stamp = time(NULL);
+ checksum_authenticator(rep, ent.data);
+ f = fopen(id->name, "r");
+ if(f == NULL) {
+ char buf[128];
+ ret = errno;
+ rk_strerror_r(ret, buf, sizeof(buf));
+ krb5_set_error_message(context, ret, "open(%s): %s", id->name, buf);
+ return ret;
+ }
+ rk_cloexec_file(f);
+ count = fread(&tmp, sizeof(ent), 1, f);
+ if (count != 1) {
+ fclose(f);
+ return KRB5_RC_IO_UNKNOWN;
+ }
+ t = ent.stamp - tmp.stamp;
+ while(fread(&tmp, sizeof(ent), 1, f)){
+ if(tmp.stamp < t)
+ continue;
+ if(memcmp(tmp.data, ent.data, sizeof(ent.data)) == 0){
+ fclose(f);
+ krb5_clear_error_message (context);
+ return KRB5_RC_REPLAY;
+ }
+ }
+ if(ferror(f)){
+ char buf[128];
+ ret = errno;
+ fclose(f);
+ rk_strerror_r(ret, buf, sizeof(buf));
+ krb5_set_error_message(context, ret, "%s: %s",
+ id->name, buf);
+ return ret;
+ }
+ fclose(f);
+ f = fopen(id->name, "a");
+ if(f == NULL) {
+ char buf[128];
+ rk_strerror_r(errno, buf, sizeof(buf));
+ krb5_set_error_message(context, KRB5_RC_IO_UNKNOWN,
+ "open(%s): %s", id->name, buf);
+ return KRB5_RC_IO_UNKNOWN;
+ }
+ fwrite(&ent, 1, sizeof(ent), f);
+ fclose(f);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rc_expunge(krb5_context context,
+ krb5_rcache id)
+{
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rc_get_lifespan(krb5_context context,
+ krb5_rcache id,
+ krb5_deltat *auth_lifespan)
+{
+ FILE *f = fopen(id->name, "r");
+ int r;
+ struct rc_entry ent;
+ r = fread(&ent, sizeof(ent), 1, f);
+ fclose(f);
+ if(r){
+ *auth_lifespan = ent.stamp;
+ return 0;
+ }
+ krb5_clear_error_message (context);
+ return KRB5_RC_IO_UNKNOWN;
+}
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_rc_get_name(krb5_context context,
+ krb5_rcache id)
+{
+ return id->name;
+}
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_rc_get_type(krb5_context context,
+ krb5_rcache id)
+{
+ return "FILE";
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_server_rcache(krb5_context context,
+ const krb5_data *piece,
+ krb5_rcache *id)
+{
+ krb5_rcache rcache;
+ krb5_error_code ret;
+
+ char *tmp = malloc(4 * piece->length + 1);
+ char *name;
+
+ if (tmp == NULL)
+ return krb5_enomem(context);
+ strvisx(tmp, piece->data, piece->length, VIS_WHITE | VIS_OCTAL);
+#ifdef HAVE_GETEUID
+ ret = asprintf(&name, "FILE:rc_%s_%u", tmp, (unsigned)geteuid());
+#else
+ ret = asprintf(&name, "FILE:rc_%s", tmp);
+#endif
+ free(tmp);
+ if (ret < 0 || name == NULL)
+ return krb5_enomem(context);
+
+ ret = krb5_rc_resolve_full(context, &rcache, name);
+ free(name);
+ if(ret)
+ return ret;
+ *id = rcache;
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/salt-aes-sha1.c b/third_party/heimdal/lib/krb5/salt-aes-sha1.c
new file mode 100644
index 0000000..edd066d
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/salt-aes-sha1.c
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+int _krb5_AES_SHA1_string_to_default_iterator = 4096;
+
+static krb5_error_code
+AES_SHA1_string_to_key(krb5_context context,
+ krb5_enctype enctype,
+ krb5_data password,
+ krb5_salt salt,
+ krb5_data opaque,
+ krb5_keyblock *key)
+{
+ krb5_error_code ret;
+ uint32_t iter;
+ struct _krb5_encryption_type *et;
+ struct _krb5_key_data kd;
+
+ if (opaque.length == 0)
+ iter = _krb5_AES_SHA1_string_to_default_iterator;
+ else if (opaque.length == 4) {
+ unsigned long v;
+ _krb5_get_int(opaque.data, &v, 4);
+ iter = ((uint32_t)v);
+ } else
+ return KRB5_PROG_KEYTYPE_NOSUPP; /* XXX */
+
+ et = _krb5_find_enctype(enctype);
+ if (et == NULL)
+ return KRB5_PROG_KEYTYPE_NOSUPP;
+
+ kd.schedule = NULL;
+ ALLOC(kd.key, 1);
+ if (kd.key == NULL)
+ return krb5_enomem(context);
+ kd.key->keytype = enctype;
+ ret = krb5_data_alloc(&kd.key->keyvalue, et->keytype->size);
+ if (ret) {
+ krb5_set_error_message (context, ret, N_("malloc: out of memory", ""));
+ return ret;
+ }
+
+ ret = PKCS5_PBKDF2_HMAC(password.data, password.length,
+ salt.saltvalue.data, salt.saltvalue.length,
+ iter,
+ EVP_sha1(),
+ et->keytype->size, kd.key->keyvalue.data);
+ if (ret != 1) {
+ _krb5_free_key_data(context, &kd, et);
+ krb5_set_error_message(context, KRB5_PROG_KEYTYPE_NOSUPP,
+ "Error calculating s2k");
+ return KRB5_PROG_KEYTYPE_NOSUPP;
+ }
+
+ ret = _krb5_derive_key(context, et, &kd, "kerberos", strlen("kerberos"));
+ if (ret == 0)
+ ret = krb5_copy_keyblock_contents(context, kd.key, key);
+ _krb5_free_key_data(context, &kd, et);
+
+ return ret;
+}
+
+struct salt_type _krb5_AES_SHA1_salt[] = {
+ {
+ KRB5_PW_SALT,
+ "pw-salt",
+ AES_SHA1_string_to_key
+ },
+ { 0, NULL, NULL }
+};
diff --git a/third_party/heimdal/lib/krb5/salt-aes-sha2.c b/third_party/heimdal/lib/krb5/salt-aes-sha2.c
new file mode 100644
index 0000000..bfd726c
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/salt-aes-sha2.c
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+int _krb5_AES_SHA2_string_to_default_iterator = 32768;
+
+static krb5_error_code
+AES_SHA2_string_to_key(krb5_context context,
+ krb5_enctype enctype,
+ krb5_data password,
+ krb5_salt salt,
+ krb5_data opaque,
+ krb5_keyblock *key)
+{
+ krb5_error_code ret;
+ uint32_t iter;
+ struct _krb5_encryption_type *et = NULL;
+ struct _krb5_key_data kd;
+ krb5_data saltp;
+ size_t enctypesz;
+ const EVP_MD *md = NULL;
+
+ krb5_data_zero(&saltp);
+ kd.key = NULL;
+ kd.schedule = NULL;
+
+ if (opaque.length == 0) {
+ iter = _krb5_AES_SHA2_string_to_default_iterator;
+ } else if (opaque.length == 4) {
+ unsigned long v;
+ _krb5_get_int(opaque.data, &v, 4);
+ iter = ((uint32_t)v);
+ } else {
+ ret = KRB5_PROG_KEYTYPE_NOSUPP; /* XXX */
+ goto cleanup;
+ }
+
+ et = _krb5_find_enctype(enctype);
+ if (et == NULL) {
+ ret = KRB5_PROG_KEYTYPE_NOSUPP;
+ goto cleanup;
+ }
+
+ kd.schedule = NULL;
+ ALLOC(kd.key, 1);
+ if (kd.key == NULL) {
+ ret = krb5_enomem(context);
+ goto cleanup;
+ }
+ kd.key->keytype = enctype;
+ ret = krb5_data_alloc(&kd.key->keyvalue, et->keytype->size);
+ if (ret) {
+ ret = krb5_enomem(context);
+ goto cleanup;
+ }
+
+ enctypesz = strlen(et->name) + 1;
+ ret = krb5_data_alloc(&saltp, enctypesz + salt.saltvalue.length);
+ if (ret) {
+ ret = krb5_enomem(context);
+ goto cleanup;
+ }
+ memcpy(saltp.data, et->name, enctypesz);
+ memcpy((unsigned char *)saltp.data + enctypesz,
+ salt.saltvalue.data, salt.saltvalue.length);
+
+ ret = _krb5_aes_sha2_md_for_enctype(context, enctype, &md);
+ if (ret)
+ goto cleanup;
+
+ ret = PKCS5_PBKDF2_HMAC(password.data, password.length,
+ saltp.data, saltp.length,
+ iter, md,
+ et->keytype->size, kd.key->keyvalue.data);
+ if (ret != 1) {
+ krb5_set_error_message(context, KRB5_PROG_KEYTYPE_NOSUPP,
+ "Error calculating s2k");
+ ret = KRB5_PROG_KEYTYPE_NOSUPP;
+ goto cleanup;
+ }
+
+ ret = _krb5_derive_key(context, et, &kd, "kerberos", strlen("kerberos"));
+ if (ret)
+ goto cleanup;
+
+ ret = krb5_copy_keyblock_contents(context, kd.key, key);
+ if (ret)
+ goto cleanup;
+
+cleanup:
+ krb5_data_free(&saltp);
+ _krb5_free_key_data(context, &kd, et);
+
+ return ret;
+}
+
+struct salt_type _krb5_AES_SHA2_salt[] = {
+ {
+ KRB5_PW_SALT,
+ "pw-salt",
+ AES_SHA2_string_to_key
+ },
+ { 0, NULL, NULL }
+};
diff --git a/third_party/heimdal/lib/krb5/salt-arcfour.c b/third_party/heimdal/lib/krb5/salt-arcfour.c
new file mode 100644
index 0000000..033128e
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/salt-arcfour.c
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+static krb5_error_code
+ARCFOUR_string_to_key(krb5_context context,
+ krb5_enctype enctype,
+ krb5_data password,
+ krb5_salt salt,
+ krb5_data opaque,
+ krb5_keyblock *key)
+{
+ krb5_error_code ret;
+ uint16_t *s = NULL;
+ size_t len = 0, i;
+ EVP_MD_CTX *m;
+
+ m = EVP_MD_CTX_create();
+ if (m == NULL)
+ return krb5_enomem(context);
+
+ EVP_DigestInit_ex(m, EVP_md4(), NULL);
+
+ ret = wind_utf8ucs2_length(password.data, &len);
+ if (ret) {
+ krb5_set_error_message (context, ret,
+ N_("Password is not valid UTF-8", ""));
+ goto out;
+ }
+
+ s = malloc (len * sizeof(s[0]));
+ if (len != 0 && s == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ ret = wind_utf8ucs2(password.data, s, &len);
+ if (ret) {
+ krb5_set_error_message (context, ret,
+ N_("Password is not valid UTF-8", ""));
+ goto out;
+ }
+
+ /* LE encoding */
+ for (i = 0; i < len; i++) {
+ unsigned char p;
+ p = (s[i] & 0xff);
+ EVP_DigestUpdate (m, &p, 1);
+ p = (s[i] >> 8) & 0xff;
+ EVP_DigestUpdate (m, &p, 1);
+ }
+
+ key->keytype = enctype;
+ ret = krb5_data_alloc (&key->keyvalue, 16);
+ if (ret) {
+ krb5_enomem(context);
+ goto out;
+ }
+ EVP_DigestFinal_ex (m, key->keyvalue.data, NULL);
+
+ out:
+ EVP_MD_CTX_destroy(m);
+ if (s)
+ memset (s, 0, len);
+ free (s);
+ return ret;
+}
+
+struct salt_type _krb5_arcfour_salt[] = {
+ {
+ KRB5_PW_SALT,
+ "pw-salt",
+ ARCFOUR_string_to_key
+ },
+ { 0, NULL, NULL }
+};
diff --git a/third_party/heimdal/lib/krb5/salt-des.c b/third_party/heimdal/lib/krb5/salt-des.c
new file mode 100644
index 0000000..d898d6c
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/salt-des.c
@@ -0,0 +1,222 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#ifdef HEIM_WEAK_CRYPTO
+
+#ifdef ENABLE_AFS_STRING_TO_KEY
+
+/* This defines the Andrew string_to_key function. It accepts a password
+ * string as input and converts it via a one-way encryption algorithm to a DES
+ * encryption key. It is compatible with the original Andrew authentication
+ * service password database.
+ */
+
+/*
+ * Short passwords, i.e 8 characters or less.
+ */
+static void
+krb5_DES_AFS3_CMU_string_to_key (krb5_data pw,
+ krb5_data cell,
+ DES_cblock *key)
+{
+ char password[8+1]; /* crypt is limited to 8 chars anyway */
+ size_t i;
+
+ for(i = 0; i < 8; i++) {
+ char c = ((i < pw.length) ? ((char*)pw.data)[i] : 0) ^
+ ((i < cell.length) ?
+ tolower(((unsigned char*)cell.data)[i]) : 0);
+ password[i] = c ? c : 'X';
+ }
+ password[8] = '\0';
+
+ memcpy(key, crypt(password, "p1") + 2, sizeof(DES_cblock));
+
+ /* parity is inserted into the LSB so left shift each byte up one
+ bit. This allows ascii characters with a zero MSB to retain as
+ much significance as possible. */
+ for (i = 0; i < sizeof(DES_cblock); i++)
+ ((unsigned char*)key)[i] <<= 1;
+ DES_set_odd_parity (key);
+}
+
+/*
+ * Long passwords, i.e 9 characters or more.
+ */
+static void
+krb5_DES_AFS3_Transarc_string_to_key (krb5_data pw,
+ krb5_data cell,
+ DES_cblock *key)
+{
+ DES_key_schedule schedule;
+ DES_cblock temp_key;
+ DES_cblock ivec;
+ char password[512];
+ size_t passlen;
+
+ memcpy(password, pw.data, min(pw.length, sizeof(password)));
+ if(pw.length < sizeof(password)) {
+ int len = min(cell.length, sizeof(password) - pw.length);
+ size_t i;
+
+ memcpy(password + pw.length, cell.data, len);
+ for (i = pw.length; i < pw.length + len; ++i)
+ password[i] = tolower((unsigned char)password[i]);
+ }
+ passlen = min(sizeof(password), pw.length + cell.length);
+ memcpy(&ivec, "kerberos", 8);
+ memcpy(&temp_key, "kerberos", 8);
+ DES_set_odd_parity (&temp_key);
+ DES_set_key_unchecked (&temp_key, &schedule);
+ DES_cbc_cksum ((void*)password, &ivec, passlen, &schedule, &ivec);
+
+ memcpy(&temp_key, &ivec, 8);
+ DES_set_odd_parity (&temp_key);
+ DES_set_key_unchecked (&temp_key, &schedule);
+ DES_cbc_cksum ((void*)password, key, passlen, &schedule, &ivec);
+ memset(&schedule, 0, sizeof(schedule));
+ memset(&temp_key, 0, sizeof(temp_key));
+ memset(&ivec, 0, sizeof(ivec));
+ memset_s(password, sizeof(password), 0, sizeof(password));
+
+ DES_set_odd_parity (key);
+}
+
+static krb5_error_code
+DES_AFS3_string_to_key(krb5_context context,
+ krb5_enctype enctype,
+ krb5_data password,
+ krb5_salt salt,
+ krb5_data opaque,
+ krb5_keyblock *key)
+{
+ DES_cblock tmp;
+ if(password.length > 8)
+ krb5_DES_AFS3_Transarc_string_to_key(password, salt.saltvalue, &tmp);
+ else
+ krb5_DES_AFS3_CMU_string_to_key(password, salt.saltvalue, &tmp);
+ key->keytype = enctype;
+ krb5_data_copy(&key->keyvalue, tmp, sizeof(tmp));
+ memset(&key, 0, sizeof(key));
+ return 0;
+}
+#endif /* ENABLE_AFS_STRING_TO_KEY */
+
+static void
+DES_string_to_key_int(unsigned char *data, size_t length, DES_cblock *key)
+{
+ DES_key_schedule schedule;
+ size_t i;
+ int reverse = 0;
+ unsigned char *p;
+
+ unsigned char swap[] = { 0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe,
+ 0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf };
+ memset(key, 0, 8);
+
+ p = (unsigned char*)key;
+ for (i = 0; i < length; i++) {
+ unsigned char tmp = data[i];
+ if (!reverse)
+ *p++ ^= (tmp << 1);
+ else
+ *--p ^= (swap[tmp & 0xf] << 4) | swap[(tmp & 0xf0) >> 4];
+ if((i % 8) == 7)
+ reverse = !reverse;
+ }
+ DES_set_odd_parity(key);
+ if(DES_is_weak_key(key))
+ (*key)[7] ^= 0xF0;
+ DES_set_key_unchecked(key, &schedule);
+ DES_cbc_cksum((void*)data, key, length, &schedule, key);
+ memset(&schedule, 0, sizeof(schedule));
+ DES_set_odd_parity(key);
+ if(DES_is_weak_key(key))
+ (*key)[7] ^= 0xF0;
+}
+
+static krb5_error_code
+krb5_DES_string_to_key(krb5_context context,
+ krb5_enctype enctype,
+ krb5_data password,
+ krb5_salt salt,
+ krb5_data opaque,
+ krb5_keyblock *key)
+{
+ unsigned char *s;
+ size_t len;
+ DES_cblock tmp;
+
+#ifdef ENABLE_AFS_STRING_TO_KEY
+ if (opaque.length == 1) {
+ unsigned long v;
+ _krb5_get_int(opaque.data, &v, 1);
+ if (v == 1)
+ return DES_AFS3_string_to_key(context, enctype, password,
+ salt, opaque, key);
+ }
+#endif
+
+ len = password.length + salt.saltvalue.length;
+ s = malloc(len);
+ if (len > 0 && s == NULL)
+ return krb5_enomem(context);
+ memcpy(s, password.data, password.length);
+ memcpy(s + password.length, salt.saltvalue.data, salt.saltvalue.length);
+ DES_string_to_key_int(s, len, &tmp);
+ key->keytype = enctype;
+ krb5_data_copy(&key->keyvalue, tmp, sizeof(tmp));
+ memset(&tmp, 0, sizeof(tmp));
+ memset(s, 0, len);
+ free(s);
+ return 0;
+}
+
+struct salt_type _krb5_des_salt[] = {
+ {
+ KRB5_PW_SALT,
+ "pw-salt",
+ krb5_DES_string_to_key
+ },
+#ifdef ENABLE_AFS_STRING_TO_KEY
+ {
+ KRB5_AFS3_SALT,
+ "afs3-salt",
+ DES_AFS3_string_to_key
+ },
+#endif
+ { 0, NULL, NULL }
+};
+#endif
diff --git a/third_party/heimdal/lib/krb5/salt-des3.c b/third_party/heimdal/lib/krb5/salt-des3.c
new file mode 100644
index 0000000..8cb73cf
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/salt-des3.c
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#ifdef DES3_OLD_ENCTYPE
+static krb5_error_code
+DES3_string_to_key(krb5_context context,
+ krb5_enctype enctype,
+ krb5_data password,
+ krb5_salt salt,
+ krb5_data opaque,
+ krb5_keyblock *key)
+{
+ char *str;
+ size_t len;
+ unsigned char tmp[24];
+ DES_cblock keys[3];
+ krb5_error_code ret;
+
+ len = password.length + salt.saltvalue.length;
+ str = malloc(len);
+ if (len != 0 && str == NULL)
+ return krb5_enomem(context);
+ memcpy(str, password.data, password.length);
+ memcpy(str + password.length, salt.saltvalue.data, salt.saltvalue.length);
+ {
+ DES_cblock ivec;
+ DES_key_schedule s[3];
+ int i;
+
+ ret = _krb5_n_fold(str, len, tmp, 24);
+ if (ret) {
+ memset_s(str, len, 0, len);
+ free(str);
+ krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+ return ret;
+ }
+
+ for(i = 0; i < 3; i++){
+ memcpy(keys + i, tmp + i * 8, sizeof(keys[i]));
+ DES_set_odd_parity(keys + i);
+ if(DES_is_weak_key(keys + i))
+ _krb5_xor8(*(keys + i), (const unsigned char*)"\0\0\0\0\0\0\0\xf0");
+ DES_set_key_unchecked(keys + i, &s[i]);
+ }
+ memset_s(&ivec, sizeof(ivec), 0, sizeof(ivec));
+ DES_ede3_cbc_encrypt(tmp,
+ tmp, sizeof(tmp),
+ &s[0], &s[1], &s[2], &ivec, DES_ENCRYPT);
+ memset_s(s, sizeof(s), 0, sizeof(s));
+ memset_s(&ivec, sizeof(ivec), 0, sizeof(ivec));
+ for(i = 0; i < 3; i++){
+ memcpy(keys + i, tmp + i * 8, sizeof(keys[i]));
+ DES_set_odd_parity(keys + i);
+ if(DES_is_weak_key(keys + i))
+ _krb5_xor8(*(keys + i), (const unsigned char*)"\0\0\0\0\0\0\0\xf0");
+ }
+ memset_s(tmp, sizeof(tmp), 0, sizeof(tmp));
+ }
+ key->keytype = enctype;
+ krb5_data_copy(&key->keyvalue, keys, sizeof(keys));
+ memset_s(keys, sizeof(keys), 0, sizeof(keys));
+ memset_s(str, len, 0, len);
+ free(str);
+ return 0;
+}
+#endif
+
+static krb5_error_code
+DES3_string_to_key_derived(krb5_context context,
+ krb5_enctype enctype,
+ krb5_data password,
+ krb5_salt salt,
+ krb5_data opaque,
+ krb5_keyblock *key)
+{
+ krb5_error_code ret;
+ size_t len = password.length + salt.saltvalue.length;
+ char *s;
+
+ s = malloc(len);
+ if (len != 0 && s == NULL)
+ return krb5_enomem(context);
+ memcpy(s, password.data, password.length);
+ memcpy(s + password.length, salt.saltvalue.data, salt.saltvalue.length);
+ ret = krb5_string_to_key_derived(context,
+ s,
+ len,
+ enctype,
+ key);
+ memset_s(s, len, 0, len);
+ free(s);
+ return ret;
+}
+
+
+#ifdef DES3_OLD_ENCTYPE
+struct salt_type _krb5_des3_salt[] = {
+ {
+ KRB5_PW_SALT,
+ "pw-salt",
+ DES3_string_to_key
+ },
+ { 0, NULL, NULL }
+};
+#endif
+
+struct salt_type _krb5_des3_salt_derived[] = {
+ {
+ KRB5_PW_SALT,
+ "pw-salt",
+ DES3_string_to_key_derived
+ },
+ { 0, NULL, NULL }
+};
diff --git a/third_party/heimdal/lib/krb5/salt.c b/third_party/heimdal/lib/krb5/salt.c
new file mode 100644
index 0000000..fa926f3
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/salt.c
@@ -0,0 +1,362 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/* coverity[+alloc : arg-*3] */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_salttype_to_string (krb5_context context,
+ krb5_enctype etype,
+ krb5_salttype stype,
+ char **string)
+{
+ struct _krb5_encryption_type *e;
+ struct salt_type *st;
+
+ *string = NULL;
+ e = _krb5_find_enctype (etype);
+ if (e == NULL) {
+ krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+ "encryption type %d not supported",
+ etype);
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ for (st = e->keytype->string_to_key; st && st->type; st++) {
+ if (st->type == stype) {
+ *string = strdup (st->name);
+ if (*string == NULL)
+ return krb5_enomem(context);
+ return 0;
+ }
+ }
+ krb5_set_error_message (context, HEIM_ERR_SALTTYPE_NOSUPP,
+ "salttype %d not supported", stype);
+ return HEIM_ERR_SALTTYPE_NOSUPP;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_string_to_salttype (krb5_context context,
+ krb5_enctype etype,
+ const char *string,
+ krb5_salttype *salttype)
+{
+ struct _krb5_encryption_type *e;
+ struct salt_type *st;
+
+ e = _krb5_find_enctype (etype);
+ if (e == NULL) {
+ krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("encryption type %d not supported", ""),
+ etype);
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ for (st = e->keytype->string_to_key; st && st->type; st++) {
+ if (strcasecmp (st->name, string) == 0) {
+ *salttype = st->type;
+ return 0;
+ }
+ }
+ krb5_set_error_message(context, HEIM_ERR_SALTTYPE_NOSUPP,
+ N_("salttype %s not supported", ""), string);
+ return HEIM_ERR_SALTTYPE_NOSUPP;
+}
+
+/*
+ * Like MIT's krb5_string_to_keysalts(), but simpler and with a context
+ * argument.
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_string_to_keysalts2(krb5_context context, const char *string,
+ size_t *nksaltp, krb5_key_salt_tuple **ksaltp)
+{
+ /* deleted: tupleseps, ksaltseps, dups */
+ krb5_key_salt_tuple *tmp = NULL;
+ krb5_error_code ret = 0;
+ char *copy, *token, *stype_str;
+ char *lasts = NULL;
+ krb5_enctype etype;
+ krb5_salttype stype;
+ size_t i;
+
+ *ksaltp = NULL;
+ *nksaltp = 0;
+ if ((copy = strdup(string)) == NULL)
+ return krb5_enomem(context);
+ for (token = strtok_r(copy, ", \t", &lasts), ret = 0;
+ token != NULL;
+ token = strtok_r(NULL, ", \t", &lasts)) {
+ if ((stype_str = strchr(token, ':')) != NULL)
+ *(stype_str++) = '\0';
+ if ((ret = krb5_string_to_enctype(context, token, &etype)))
+ continue;
+ if (stype_str == NULL)
+ stype = KRB5_PW_SALT;
+ else if ((ret = krb5_string_to_salttype(context, etype, stype_str, &stype)))
+ continue;
+ for (i = 0; i < *nksaltp; i++) {
+ if ((*ksaltp)[i].ks_enctype == etype &&
+ (*ksaltp)[i].ks_salttype == stype)
+ goto skip;
+ }
+ tmp = realloc(*ksaltp, ((*nksaltp) + 1) * sizeof(**ksaltp));
+ if (tmp == NULL) {
+ ret = krb5_enomem(context);
+ break;
+ }
+ *ksaltp = tmp;
+ (*ksaltp)[*nksaltp].ks_enctype = etype;
+ (*ksaltp)[*nksaltp].ks_salttype = stype;
+ (*nksaltp)++;
+skip:
+ (void)1;
+ }
+ free(copy);
+ if (ret == ENOMEM) {
+ free(*ksaltp);
+ *nksaltp = 0;
+ *ksaltp = NULL;
+ } else if (*nksaltp) {
+ return 0;
+ } else if (ret == 0) {
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ return ret;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_pw_salt(krb5_context context,
+ krb5_const_principal principal,
+ krb5_salt *salt)
+{
+ size_t len;
+ size_t i;
+ krb5_error_code ret;
+ char *p;
+
+ salt->salttype = KRB5_PW_SALT;
+ len = strlen(principal->realm);
+ for (i = 0; i < principal->name.name_string.len; ++i)
+ len += strlen(principal->name.name_string.val[i]);
+ ret = krb5_data_alloc (&salt->saltvalue, len);
+ if (ret)
+ return ret;
+ p = salt->saltvalue.data;
+ memcpy (p, principal->realm, strlen(principal->realm));
+ p += strlen(principal->realm);
+ for (i = 0; i < principal->name.name_string.len; ++i) {
+ memcpy (p,
+ principal->name.name_string.val[i],
+ strlen(principal->name.name_string.val[i]));
+ p += strlen(principal->name.name_string.val[i]);
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_free_salt(krb5_context context,
+ krb5_salt salt)
+{
+ krb5_data_free(&salt.saltvalue);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_string_to_key_data (krb5_context context,
+ krb5_enctype enctype,
+ krb5_data password,
+ krb5_const_principal principal,
+ krb5_keyblock *key)
+{
+ krb5_error_code ret;
+ krb5_salt salt;
+
+ ret = krb5_get_pw_salt(context, principal, &salt);
+ if(ret)
+ return ret;
+ ret = krb5_string_to_key_data_salt(context, enctype, password, salt, key);
+ krb5_free_salt(context, salt);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_string_to_key (krb5_context context,
+ krb5_enctype enctype,
+ const char *password,
+ krb5_const_principal principal,
+ krb5_keyblock *key)
+{
+ krb5_data pw;
+ pw.data = rk_UNCONST(password);
+ pw.length = strlen(password);
+ return krb5_string_to_key_data(context, enctype, pw, principal, key);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_string_to_key_data_salt (krb5_context context,
+ krb5_enctype enctype,
+ krb5_data password,
+ krb5_salt salt,
+ krb5_keyblock *key)
+{
+ krb5_data opaque;
+ krb5_data_zero(&opaque);
+ return krb5_string_to_key_data_salt_opaque(context, enctype, password,
+ salt, opaque, key);
+}
+
+/*
+ * Do a string -> key for encryption type `enctype' operation on
+ * `password' (with salt `salt' and the enctype specific data string
+ * `opaque'), returning the resulting key in `key'
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_string_to_key_data_salt_opaque (krb5_context context,
+ krb5_enctype enctype,
+ krb5_data password,
+ krb5_salt salt,
+ krb5_data opaque,
+ krb5_keyblock *key)
+{
+ struct _krb5_encryption_type *et =_krb5_find_enctype(enctype);
+ struct salt_type *st;
+ if(et == NULL) {
+ krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("encryption type %d not supported", ""),
+ enctype);
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ for(st = et->keytype->string_to_key; st && st->type; st++)
+ if(st->type == salt.salttype)
+ return (*st->string_to_key)(context, enctype, password,
+ salt, opaque, key);
+ krb5_set_error_message(context, HEIM_ERR_SALTTYPE_NOSUPP,
+ N_("salt type %d not supported", ""),
+ salt.salttype);
+ return HEIM_ERR_SALTTYPE_NOSUPP;
+}
+
+/*
+ * Do a string -> key for encryption type `enctype' operation on the
+ * string `password' (with salt `salt'), returning the resulting key
+ * in `key'
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_string_to_key_salt (krb5_context context,
+ krb5_enctype enctype,
+ const char *password,
+ krb5_salt salt,
+ krb5_keyblock *key)
+{
+ krb5_data pw;
+ pw.data = rk_UNCONST(password);
+ pw.length = strlen(password);
+ return krb5_string_to_key_data_salt(context, enctype, pw, salt, key);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_string_to_key_salt_opaque (krb5_context context,
+ krb5_enctype enctype,
+ const char *password,
+ krb5_salt salt,
+ krb5_data opaque,
+ krb5_keyblock *key)
+{
+ krb5_data pw;
+ pw.data = rk_UNCONST(password);
+ pw.length = strlen(password);
+ return krb5_string_to_key_data_salt_opaque(context, enctype,
+ pw, salt, opaque, key);
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_string_to_key_derived(krb5_context context,
+ const void *str,
+ size_t len,
+ krb5_enctype etype,
+ krb5_keyblock *key)
+{
+ struct _krb5_encryption_type *et = _krb5_find_enctype(etype);
+ krb5_error_code ret;
+ struct _krb5_key_data kd;
+ size_t keylen;
+ u_char *tmp;
+
+ if(et == NULL) {
+ krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP,
+ N_("encryption type %d not supported", ""),
+ etype);
+ return KRB5_PROG_ETYPE_NOSUPP;
+ }
+ keylen = et->keytype->bits / 8;
+
+ ALLOC(kd.key, 1);
+ if (kd.key == NULL)
+ return krb5_enomem(context);
+ ret = krb5_data_alloc(&kd.key->keyvalue, et->keytype->size);
+ if(ret) {
+ free(kd.key);
+ return ret;
+ }
+ kd.key->keytype = etype;
+ tmp = malloc (keylen);
+ if(tmp == NULL) {
+ krb5_free_keyblock(context, kd.key);
+ return krb5_enomem(context);
+ }
+ ret = _krb5_n_fold(str, len, tmp, keylen);
+ if (ret) {
+ free(tmp);
+ krb5_enomem(context);
+ return ret;
+ }
+ kd.schedule = NULL;
+ _krb5_DES3_random_to_key(context, kd.key, tmp, keylen);
+ memset(tmp, 0, keylen);
+ free(tmp);
+ ret = _krb5_derive_key(context,
+ et,
+ &kd,
+ "kerberos", /* XXX well known constant */
+ strlen("kerberos"));
+ if (ret) {
+ _krb5_free_key_data(context, &kd, et);
+ return ret;
+ }
+ ret = krb5_copy_keyblock_contents(context, kd.key, key);
+ _krb5_free_key_data(context, &kd, et);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/scache.c b/third_party/heimdal/lib/krb5/scache.c
new file mode 100644
index 0000000..7a39664
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/scache.c
@@ -0,0 +1,1599 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#ifdef HAVE_SCC
+
+#include <sqlite3.h>
+
+typedef struct krb5_scache {
+ char *name;
+ char *file;
+ char *sub;
+ sqlite3 *db;
+
+ sqlite_uint64 cid;
+
+ sqlite3_stmt *icred;
+ sqlite3_stmt *dcred;
+ sqlite3_stmt *iprincipal;
+
+ sqlite3_stmt *icache;
+ sqlite3_stmt *ucachen;
+ sqlite3_stmt *ucachep;
+ sqlite3_stmt *dcache;
+ sqlite3_stmt *scache;
+ sqlite3_stmt *scache_name;
+ sqlite3_stmt *umaster;
+
+} krb5_scache;
+
+#define SCACHE(X) ((krb5_scache *)(X)->data.data)
+
+/*
+ * Because we can't control what permissions SQLite3 (if not in-tree) will use,
+ * and we're a library and can't set the umask. We can't even determine the
+ * current umask in a thread-safe way (not easily), and we can't tell if some
+ * other thread might change it. So what we'll do is put the SQLite3-based
+ * ccache file in its own directory so we can create that directory with
+ * mkdir(2) and the correct permissions.
+ */
+
+#define SCACHE_DEF_NAME "Default-cache"
+#define KRB5_SCACHE_DIR "%{TEMP}/krb5scc_%{uid}"
+#define KRB5_SCACHE_DB KRB5_SCACHE_DIR "scc"
+#define KRB5_SCACHE_NAME "SCC:" KRB5_SCACHE_DB ":" SCACHE_DEF_NAME
+
+#define SCACHE_INVALID_CID ((sqlite_uint64)-1)
+
+/*
+ *
+ */
+
+#define SQL_CMASTER "" \
+ "CREATE TABLE master (" \
+ "oid INTEGER PRIMARY KEY," \
+ "version INTEGER NOT NULL," \
+ "defaultcache TEXT NOT NULL" \
+ ")"
+
+#define SQL_SETUP_MASTER \
+ "INSERT INTO master (version,defaultcache) VALUES(2, \"" SCACHE_DEF_NAME "\")"
+#define SQL_UMASTER "UPDATE master SET defaultcache=? WHERE version=2"
+
+#define SQL_CCACHE "" \
+ "CREATE TABLE caches (" \
+ "oid INTEGER PRIMARY KEY," \
+ "principal TEXT," \
+ "name TEXT NOT NULL" \
+ ")"
+
+#define SQL_TCACHE "" \
+ "CREATE TRIGGER CacheDropCreds AFTER DELETE ON caches " \
+ "FOR EACH ROW BEGIN " \
+ "DELETE FROM credentials WHERE cid=old.oid;" \
+ "END"
+
+#define SQL_ICACHE "INSERT INTO caches (name) VALUES(?)"
+#define SQL_UCACHE_NAME "UPDATE caches SET name=? WHERE OID=?"
+#define SQL_UCACHE_PRINCIPAL "UPDATE caches SET principal=? WHERE OID=?"
+#define SQL_DCACHE "DELETE FROM caches WHERE OID=?"
+#define SQL_SCACHE "SELECT principal,name FROM caches WHERE OID=?"
+#define SQL_SCACHE_NAME "SELECT oid FROM caches WHERE NAME=? OR " \
+ "(PRINCIPAL IS NOT NULL AND PRINCIPAL=?)"
+
+#define SQL_CCREDS "" \
+ "CREATE TABLE credentials (" \
+ "oid INTEGER PRIMARY KEY," \
+ "cid INTEGER NOT NULL," \
+ "kvno INTEGER NOT NULL," \
+ "etype INTEGER NOT NULL," \
+ "created_at INTEGER NOT NULL," \
+ "cred BLOB NOT NULL" \
+ ")"
+
+#define SQL_TCRED "" \
+ "CREATE TRIGGER credDropPrincipal AFTER DELETE ON credentials " \
+ "FOR EACH ROW BEGIN " \
+ "DELETE FROM principals WHERE credential_id=old.oid;" \
+ "END"
+
+#define SQL_ICRED "INSERT INTO credentials (cid, kvno, etype, cred, created_at) VALUES (?,?,?,?,?)"
+#define SQL_DCRED "DELETE FROM credentials WHERE cid=?"
+
+#define SQL_CPRINCIPALS "" \
+ "CREATE TABLE principals (" \
+ "oid INTEGER PRIMARY KEY," \
+ "principal TEXT NOT NULL," \
+ "type INTEGER NOT NULL," \
+ "credential_id INTEGER NOT NULL" \
+ ")"
+
+#define SQL_IPRINCIPAL "INSERT INTO principals (principal, type, credential_id) VALUES (?,?,?)"
+
+/*
+ * sqlite destructors
+ */
+
+static void
+free_data(void *data)
+{
+ free(data);
+}
+
+static void
+free_krb5(void *str)
+{
+ krb5_xfree(str);
+}
+
+static void
+scc_free(krb5_scache *s)
+{
+ if (!s)
+ return;
+ if (s->file)
+ free(s->file);
+ if (s->sub)
+ free(s->sub);
+ if (s->name)
+ free(s->name);
+
+ if (s->icred)
+ sqlite3_finalize(s->icred);
+ if (s->dcred)
+ sqlite3_finalize(s->dcred);
+ if (s->iprincipal)
+ sqlite3_finalize(s->iprincipal);
+ if (s->icache)
+ sqlite3_finalize(s->icache);
+ if (s->ucachen)
+ sqlite3_finalize(s->ucachen);
+ if (s->ucachep)
+ sqlite3_finalize(s->ucachep);
+ if (s->dcache)
+ sqlite3_finalize(s->dcache);
+ if (s->scache)
+ sqlite3_finalize(s->scache);
+ if (s->scache_name)
+ sqlite3_finalize(s->scache_name);
+ if (s->umaster)
+ sqlite3_finalize(s->umaster);
+
+ if (s->db)
+ sqlite3_close(s->db);
+ free(s);
+}
+
+#ifdef TRACEME
+static void
+trace(void* ptr, const char * str)
+{
+ printf("SQL: %s\n", str);
+}
+#endif
+
+static krb5_error_code
+prepare_stmt(krb5_context context, sqlite3 *db,
+ sqlite3_stmt **stmt, const char *str)
+{
+ int ret;
+
+ ret = sqlite3_prepare_v2(db, str, -1, stmt, NULL);
+ if (ret != SQLITE_OK) {
+ krb5_set_error_message(context, ENOENT,
+ N_("Failed to prepare stmt %s: %s", ""),
+ str, sqlite3_errmsg(db));
+ return ENOENT;
+ }
+ return 0;
+}
+
+static krb5_error_code
+exec_stmt(krb5_context context, sqlite3 *db, const char *str,
+ krb5_error_code code)
+{
+ int ret;
+
+ ret = sqlite3_exec(db, str, NULL, NULL, NULL);
+ if (ret != SQLITE_OK && code) {
+ krb5_set_error_message(context, code,
+ N_("scache execute %s: %s", ""), str,
+ sqlite3_errmsg(db));
+ return code;
+ }
+ return 0;
+}
+
+/* See block comment at the top of this file */
+static krb5_error_code
+make_dir(krb5_context context, const char *name)
+{
+ krb5_error_code ret = 0;
+ char *s, *p;
+
+ /* We really need a dirname() in roken; lib/krb5/fcache.c has one */
+ if ((s = strdup(name)) == NULL)
+ return krb5_enomem(context);
+ for (p = s + strlen(s); p > s; p--) {
+#ifdef WIN32
+ if (*p != '/' && *p != '\\')
+ continue;
+#else
+ if (*p != '/')
+ continue;
+#endif
+ *p = '\0';
+ break;
+ }
+
+ /* If p == s then DB in current directory -- nothing we can do */
+ if (p > s && mkdir(s, 0700) == -1)
+ ret = errno;
+ free(s);
+
+ /* If we created it, we're good, else there's nothing we can do */
+ if (ret == EEXIST)
+ return 0;
+ if (ret)
+ krb5_set_error_message(context, ret,
+ N_("Error making directory for scache file %s", ""),
+ name);
+ return ret;
+}
+
+static krb5_error_code
+default_db(krb5_context context, const char *name, sqlite3 **db, char **file)
+{
+ krb5_error_code ret = 0;
+ char *s = NULL;
+ char *f = NULL;
+
+ if (file)
+ *file = NULL;
+
+ if (name == NULL) {
+ if ((name = krb5_cc_default_name(context))) {
+ if (strncmp(name, "SCC:", sizeof("SCC:") - 1) == 0)
+ name += sizeof("SCC:") - 1;
+ }
+ if (name == NULL) {
+ ret = _krb5_expand_default_cc_name(context, KRB5_SCACHE_DB, &s);
+ if (ret)
+ return ret;
+ name = s;
+ }
+ }
+
+ if (strncmp(name, "SCC:", sizeof("SCC:") - 1) == 0)
+ name += sizeof("SCC:") - 1;
+
+ if ((f = strdup(name)) == NULL) {
+ free(s);
+ return krb5_enomem(context);
+ }
+ free(s);
+
+ /* Strip off any residue from default name */
+#ifdef WIN32
+ if (f[0] && f[1] == ':' && (s = strrchr(f, ':')) != &f[1])
+ *s = '\0';
+#else
+ if ((s = strrchr(f, ':')))
+ *s = '\0';
+#endif
+
+ ret = make_dir(context, f);
+ if (ret == 0) {
+ int sret;
+
+ sret = sqlite3_open_v2(f, db, SQLITE_OPEN_READWRITE, NULL);
+ if (sret != SQLITE_OK) {
+ if (*db) {
+ krb5_set_error_message(context, ENOENT,
+ N_("Error opening scache file %s: %s (%d)", ""),
+ f, sqlite3_errmsg(*db), sret);
+ sqlite3_close(*db);
+ *db = NULL;
+ } else
+ krb5_set_error_message(context, ENOENT,
+ N_("Error opening scache file %s: %s (%d)", ""),
+ f, sqlite3_errstr(sret), sret);
+ free(f);
+ return ENOENT;
+ }
+ }
+
+#ifndef WIN32
+ /*
+ * Just in case we're using an out-of-tree SQLite3. See block comment at
+ * the top of this file, near KRB5_SCACHE_DIR's definition.
+ */
+ (void) chmod(f, 0600);
+#endif
+
+ if (file)
+ *file = f;
+ else
+ free(f);
+
+#ifdef TRACEME
+ sqlite3_trace(*db, trace, NULL);
+#endif
+
+ return ret;
+}
+
+static krb5_error_code
+get_def_name(krb5_context context, char *filein, char **str, char **file)
+{
+ krb5_error_code ret;
+ sqlite3_stmt *stmt;
+ const char *name;
+ sqlite3 *db;
+
+ ret = default_db(context, filein, &db, file);
+ if (ret)
+ return ret;
+
+ ret = prepare_stmt(context, db, &stmt, "SELECT defaultcache FROM master");
+ if (ret) {
+ sqlite3_close(db);
+ return ret;
+ }
+
+ ret = sqlite3_step(stmt);
+ if (ret != SQLITE_ROW)
+ goto out;
+
+ if (sqlite3_column_type(stmt, 0) != SQLITE_TEXT)
+ goto out;
+
+ name = (const char *)sqlite3_column_text(stmt, 0);
+ if (name == NULL)
+ goto out;
+
+ *str = strdup(name);
+ if (*str == NULL)
+ goto out;
+
+ sqlite3_finalize(stmt);
+ sqlite3_close(db);
+ return 0;
+out:
+ sqlite3_finalize(stmt);
+ sqlite3_close(db);
+ krb5_clear_error_message(context);
+ return ENOENT;
+}
+
+
+
+static krb5_scache * KRB5_CALLCONV
+scc_alloc(krb5_context context,
+ const char *name,
+ const char *sub,
+ int new_unique)
+{
+ krb5_error_code ret = 0;
+ krb5_scache *s;
+ char *freeme = NULL;
+ char *subsidiary;
+
+ ALLOC(s, 1);
+ if(s == NULL)
+ return NULL;
+
+ s->cid = SCACHE_INVALID_CID;
+
+ if (name && *name && sub && *sub) {
+ if ((s->sub = strdup(sub)) == NULL ||
+ (s->file = strdup(name)) == NULL) {
+ free(s->file);
+ free(s);
+ (void) krb5_enomem(context);
+ return NULL;
+ }
+ } else {
+ s->sub = NULL;
+ s->file = NULL;
+ s->name = NULL;
+
+ if (name == NULL)
+ name = krb5_cc_default_name(context);
+ if (name == NULL) {
+ ret = _krb5_expand_default_cc_name(context, KRB5_SCACHE_DB,
+ &freeme);
+ if (ret) {
+ free(s);
+ return NULL;
+ }
+ name = freeme;
+ }
+
+ if (strncmp(name, "SCC:", sizeof("SCC:") - 1) == 0)
+ name += sizeof("SCC:") - 1;
+
+ if ((s->file = strdup(name)) == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+
+ if ((subsidiary = strrchr(s->file, ':'))) {
+#ifdef WIN32
+ if (subsidiary == s->file + 1)
+ subsidiary = NULL;
+ else
+#endif
+ *(subsidiary++) = '\0';
+ }
+
+ if (new_unique) {
+ ret = asprintf(&s->sub, "unique-%p", s) < 0 || s->sub == NULL ?
+ krb5_enomem(context) : 0;
+ } else if (subsidiary == NULL || *subsidiary == '\0') {
+ ret = get_def_name(context, s->file, &s->sub, NULL);
+ if (ret) {
+ if ((s->sub = strdup(SCACHE_DEF_NAME)) == NULL)
+ ret = krb5_enomem(context);
+ else
+ ret = 0;
+ }
+ } else if ((s->sub = strdup(subsidiary)) == NULL) {
+ ret = krb5_enomem(context);
+ }
+ }
+
+ if (ret == 0 && s->file && s->sub &&
+ (asprintf(&s->name, "%s:%s", s->file, s->sub) < 0 || s->name == NULL))
+ ret = krb5_enomem(context);
+
+ out:
+ if (ret || s->file == NULL || s->sub == NULL || s->name == NULL) {
+ scc_free(s);
+ s = NULL;
+ }
+
+ free(freeme);
+ return s;
+}
+
+static krb5_error_code
+open_database(krb5_context context, krb5_scache *s, int flags)
+{
+ krb5_error_code ret;
+ struct stat st;
+ int sret;
+
+
+ if (!(flags & SQLITE_OPEN_CREATE) && stat(s->file, &st) == 0 &&
+ st.st_size == 0)
+ return ENOENT;
+
+ ret = make_dir(context, s->file);
+ if (ret)
+ return ret;
+ sret = sqlite3_open_v2(s->file, &s->db, SQLITE_OPEN_READWRITE|flags, NULL);
+ if (sret != SQLITE_OK) {
+ if (s->db) {
+ krb5_set_error_message(context, ENOENT,
+ N_("Error opening scache file %s: %s (%d)", ""),
+ s->file, sqlite3_errmsg(s->db), sret);
+ sqlite3_close(s->db);
+ s->db = NULL;
+ } else
+ krb5_set_error_message(context, ENOENT,
+ N_("Error opening scache file %s: %s (%d)", ""),
+ s->file, sqlite3_errstr(sret), sret);
+ return ENOENT;
+ }
+ return 0;
+}
+
+static krb5_error_code
+create_cache(krb5_context context, krb5_scache *s)
+{
+ int ret;
+
+ sqlite3_bind_text(s->icache, 1, s->sub, -1, NULL);
+ do {
+ ret = sqlite3_step(s->icache);
+ } while (ret == SQLITE_ROW);
+ if (ret != SQLITE_DONE) {
+ krb5_set_error_message(context, KRB5_CC_IO,
+ N_("Failed to add scache: %d", ""), ret);
+ return KRB5_CC_IO;
+ }
+ sqlite3_reset(s->icache);
+
+ s->cid = sqlite3_last_insert_rowid(s->db);
+
+ return 0;
+}
+
+static krb5_error_code
+make_database(krb5_context context, krb5_scache *s)
+{
+ int created_file = 0;
+ int ret;
+
+ if (s->db)
+ return 0;
+
+ ret = open_database(context, s, 0);
+ if (ret) {
+ ret = open_database(context, s, SQLITE_OPEN_CREATE);
+ if (ret) goto out;
+
+ created_file = 1;
+
+ ret = exec_stmt(context, s->db, SQL_CMASTER, KRB5_CC_IO);
+ if (ret) goto out;
+ ret = exec_stmt(context, s->db, SQL_CCACHE, KRB5_CC_IO);
+ if (ret) goto out;
+ ret = exec_stmt(context, s->db, SQL_CCREDS, KRB5_CC_IO);
+ if (ret) goto out;
+ ret = exec_stmt(context, s->db, SQL_CPRINCIPALS, KRB5_CC_IO);
+ if (ret) goto out;
+ ret = exec_stmt(context, s->db, SQL_SETUP_MASTER, KRB5_CC_IO);
+ if (ret) goto out;
+
+ ret = exec_stmt(context, s->db, SQL_TCACHE, KRB5_CC_IO);
+ if (ret) goto out;
+ ret = exec_stmt(context, s->db, SQL_TCRED, KRB5_CC_IO);
+ if (ret) goto out;
+ }
+
+#ifdef TRACEME
+ sqlite3_trace(s->db, trace, NULL);
+#endif
+
+ ret = prepare_stmt(context, s->db, &s->icred, SQL_ICRED);
+ if (ret) goto out;
+ ret = prepare_stmt(context, s->db, &s->dcred, SQL_DCRED);
+ if (ret) goto out;
+ ret = prepare_stmt(context, s->db, &s->iprincipal, SQL_IPRINCIPAL);
+ if (ret) goto out;
+ ret = prepare_stmt(context, s->db, &s->icache, SQL_ICACHE);
+ if (ret) goto out;
+ ret = prepare_stmt(context, s->db, &s->ucachen, SQL_UCACHE_NAME);
+ if (ret) goto out;
+ ret = prepare_stmt(context, s->db, &s->ucachep, SQL_UCACHE_PRINCIPAL);
+ if (ret) goto out;
+ ret = prepare_stmt(context, s->db, &s->dcache, SQL_DCACHE);
+ if (ret) goto out;
+ ret = prepare_stmt(context, s->db, &s->scache, SQL_SCACHE);
+ if (ret) goto out;
+ ret = prepare_stmt(context, s->db, &s->scache_name, SQL_SCACHE_NAME);
+ if (ret) goto out;
+ ret = prepare_stmt(context, s->db, &s->umaster, SQL_UMASTER);
+ if (ret) goto out;
+
+#ifndef WIN32
+ /*
+ * Just in case we're using an out-of-tree SQLite3. See block comment at
+ * the top of this file, near KRB5_SCACHE_DIR's definition.
+ */
+ (void) chmod(s->file, 0600);
+#endif
+
+ return 0;
+
+out:
+ if (s->db)
+ sqlite3_close(s->db);
+ if (created_file)
+ unlink(s->file);
+
+ return ret;
+}
+
+static krb5_error_code
+bind_principal(krb5_context context,
+ sqlite3 *db,
+ sqlite3_stmt *stmt,
+ int col,
+ krb5_const_principal principal)
+{
+ krb5_error_code ret;
+ char *str;
+
+ ret = krb5_unparse_name(context, principal, &str);
+ if (ret)
+ return ret;
+
+ ret = sqlite3_bind_text(stmt, col, str, -1, free_krb5);
+ if (ret != SQLITE_OK) {
+ krb5_xfree(str);
+ krb5_set_error_message(context, ENOMEM,
+ N_("scache bind principal: %s", ""),
+ sqlite3_errmsg(db));
+ return ENOMEM;
+ }
+ return 0;
+}
+
+/*
+ *
+ */
+
+static krb5_error_code KRB5_CALLCONV
+scc_get_name_2(krb5_context context,
+ krb5_ccache id,
+ const char **name,
+ const char **file,
+ const char **sub)
+{
+ if (name)
+ *name = SCACHE(id)->name;
+ if (file)
+ *file = SCACHE(id)->file;
+ if (sub)
+ *sub = SCACHE(id)->sub;
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_resolve_2(krb5_context context,
+ krb5_ccache *id,
+ const char *res,
+ const char *sub)
+{
+ krb5_error_code ret;
+ krb5_scache *s;
+
+ s = scc_alloc(context, res, sub, 0);
+ if (s == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOMEM,
+ N_("malloc: out of memory", ""));
+ return KRB5_CC_NOMEM;
+ }
+
+ ret = make_database(context, s);
+ if (ret) {
+ scc_free(s);
+ return ret;
+ }
+
+ ret = sqlite3_bind_text(s->scache_name, 1, s->sub, -1, NULL);
+ if (ret != SQLITE_OK) {
+ krb5_set_error_message(context, ENOMEM,
+ "bind principal: %s", sqlite3_errmsg(s->db));
+ scc_free(s);
+ return ENOMEM;
+ }
+
+ if (sqlite3_step(s->scache_name) == SQLITE_ROW) {
+
+ if (sqlite3_column_type(s->scache_name, 0) != SQLITE_INTEGER) {
+ sqlite3_reset(s->scache_name);
+ krb5_set_error_message(context, KRB5_CC_END,
+ N_("Cache name of wrong type "
+ "for scache %s", ""),
+ s->name);
+ scc_free(s);
+ return KRB5_CC_END;
+ }
+
+ s->cid = sqlite3_column_int(s->scache_name, 0);
+ } else {
+ s->cid = SCACHE_INVALID_CID;
+ }
+ sqlite3_reset(s->scache_name);
+
+ (*id)->data.data = s;
+ (*id)->data.length = sizeof(*s);
+
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_gen_new(krb5_context context, krb5_ccache *id)
+{
+ krb5_scache *s;
+
+ s = scc_alloc(context, NULL, NULL, 1);
+
+ if (s == NULL) {
+ krb5_set_error_message(context, KRB5_CC_NOMEM,
+ N_("malloc: out of memory", ""));
+ return KRB5_CC_NOMEM;
+ }
+
+ (*id)->data.data = s;
+ (*id)->data.length = sizeof(*s);
+
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_initialize(krb5_context context,
+ krb5_ccache id,
+ krb5_principal principal)
+{
+ krb5_scache *s = SCACHE(id);
+ krb5_error_code ret;
+
+ ret = make_database(context, s);
+ if (ret)
+ return ret;
+
+ ret = exec_stmt(context, s->db, "BEGIN IMMEDIATE TRANSACTION", KRB5_CC_IO);
+ if (ret) return ret;
+
+ if (s->cid == SCACHE_INVALID_CID) {
+ ret = create_cache(context, s);
+ if (ret)
+ goto rollback;
+ } else {
+ sqlite3_bind_int(s->dcred, 1, s->cid);
+ do {
+ ret = sqlite3_step(s->dcred);
+ } while (ret == SQLITE_ROW);
+ sqlite3_reset(s->dcred);
+ if (ret != SQLITE_DONE) {
+ ret = KRB5_CC_IO;
+ krb5_set_error_message(context, ret,
+ N_("Failed to delete old "
+ "credentials: %s", ""),
+ sqlite3_errmsg(s->db));
+ goto rollback;
+ }
+ }
+
+ ret = bind_principal(context, s->db, s->ucachep, 1, principal);
+ if (ret)
+ goto rollback;
+ sqlite3_bind_int(s->ucachep, 2, s->cid);
+
+ do {
+ ret = sqlite3_step(s->ucachep);
+ } while (ret == SQLITE_ROW);
+ sqlite3_reset(s->ucachep);
+ if (ret != SQLITE_DONE) {
+ ret = KRB5_CC_IO;
+ krb5_set_error_message(context, ret,
+ N_("Failed to bind principal to cache %s", ""),
+ sqlite3_errmsg(s->db));
+ goto rollback;
+ }
+
+ ret = exec_stmt(context, s->db, "COMMIT", KRB5_CC_IO);
+ if (ret) return ret;
+
+ return 0;
+
+rollback:
+ exec_stmt(context, s->db, "ROLLBACK", 0);
+
+ return ret;
+
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_close(krb5_context context,
+ krb5_ccache id)
+{
+ scc_free(SCACHE(id));
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_destroy(krb5_context context,
+ krb5_ccache id)
+{
+ krb5_scache *s = SCACHE(id);
+ int ret;
+
+ if (s->cid == SCACHE_INVALID_CID)
+ return 0;
+
+ sqlite3_bind_int(s->dcache, 1, s->cid);
+ do {
+ ret = sqlite3_step(s->dcache);
+ } while (ret == SQLITE_ROW);
+ sqlite3_reset(s->dcache);
+ if (ret != SQLITE_DONE) {
+ krb5_set_error_message(context, KRB5_CC_IO,
+ N_("Failed to destroy cache %s: %s", ""),
+ s->name, sqlite3_errmsg(s->db));
+ return KRB5_CC_IO;
+ }
+ return 0;
+}
+
+static krb5_error_code
+encode_creds(krb5_context context, krb5_creds *creds, krb5_data *data)
+{
+ krb5_error_code ret;
+ krb5_storage *sp;
+
+ krb5_data_zero(data);
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ return krb5_enomem(context);
+
+ ret = krb5_store_creds(sp, creds);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to store credential in scache", ""));
+ krb5_storage_free(sp);
+ return ret;
+ }
+
+ ret = krb5_storage_to_data(sp, data);
+ krb5_storage_free(sp);
+ if (ret)
+ krb5_set_error_message(context, ret,
+ N_("Failed to encode credential in scache", ""));
+ return ret;
+}
+
+static krb5_error_code
+decode_creds(krb5_context context, const void *data, size_t length,
+ krb5_creds *creds)
+{
+ krb5_error_code ret;
+ krb5_storage *sp;
+
+ sp = krb5_storage_from_readonly_mem(data, length);
+ if (sp == NULL)
+ return krb5_enomem(context);
+
+ ret = krb5_ret_creds(sp, creds);
+ krb5_storage_free(sp);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to read credential in scache", ""));
+ return ret;
+ }
+ return 0;
+}
+
+
+static krb5_error_code KRB5_CALLCONV
+scc_store_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_creds *creds)
+{
+ sqlite_uint64 credid;
+ krb5_scache *s = SCACHE(id);
+ krb5_error_code ret;
+ krb5_data data;
+
+ ret = make_database(context, s);
+ if (ret)
+ return ret;
+
+ ret = encode_creds(context, creds, &data);
+ if (ret)
+ return ret;
+
+ sqlite3_bind_int(s->icred, 1, s->cid);
+ {
+ krb5_enctype etype = 0;
+ int kvno = 0;
+ Ticket t;
+ size_t len;
+
+ ret = decode_Ticket(creds->ticket.data,
+ creds->ticket.length, &t, &len);
+ if (ret == 0) {
+ if(t.enc_part.kvno)
+ kvno = *t.enc_part.kvno;
+
+ etype = t.enc_part.etype;
+
+ free_Ticket(&t);
+ }
+
+ sqlite3_bind_int(s->icred, 2, kvno);
+ sqlite3_bind_int(s->icred, 3, etype);
+
+ }
+
+ sqlite3_bind_blob(s->icred, 4, data.data, data.length, free_data);
+ sqlite3_bind_int(s->icred, 5, time(NULL));
+
+ ret = exec_stmt(context, s->db, "BEGIN IMMEDIATE TRANSACTION", KRB5_CC_IO);
+ if (ret) return ret;
+
+ do {
+ ret = sqlite3_step(s->icred);
+ } while (ret == SQLITE_ROW);
+ sqlite3_reset(s->icred);
+ if (ret != SQLITE_DONE) {
+ ret = KRB5_CC_IO;
+ krb5_set_error_message(context, ret,
+ N_("Failed to add credential: %s", ""),
+ sqlite3_errmsg(s->db));
+ goto rollback;
+ }
+
+ credid = sqlite3_last_insert_rowid(s->db);
+
+ {
+ bind_principal(context, s->db, s->iprincipal, 1, creds->server);
+ sqlite3_bind_int(s->iprincipal, 2, 1);
+ sqlite3_bind_int(s->iprincipal, 3, credid);
+
+ do {
+ ret = sqlite3_step(s->iprincipal);
+ } while (ret == SQLITE_ROW);
+ sqlite3_reset(s->iprincipal);
+ if (ret != SQLITE_DONE) {
+ ret = KRB5_CC_IO;
+ krb5_set_error_message(context, ret,
+ N_("Failed to add principal: %s", ""),
+ sqlite3_errmsg(s->db));
+ goto rollback;
+ }
+ }
+
+ {
+ bind_principal(context, s->db, s->iprincipal, 1, creds->client);
+ sqlite3_bind_int(s->iprincipal, 2, 0);
+ sqlite3_bind_int(s->iprincipal, 3, credid);
+
+ do {
+ ret = sqlite3_step(s->iprincipal);
+ } while (ret == SQLITE_ROW);
+ sqlite3_reset(s->iprincipal);
+ if (ret != SQLITE_DONE) {
+ ret = KRB5_CC_IO;
+ krb5_set_error_message(context, ret,
+ N_("Failed to add principal: %s", ""),
+ sqlite3_errmsg(s->db));
+ goto rollback;
+ }
+ }
+
+ ret = exec_stmt(context, s->db, "COMMIT", KRB5_CC_IO);
+ if (ret) return ret;
+
+ return 0;
+
+rollback:
+ exec_stmt(context, s->db, "ROLLBACK", 0);
+
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_get_principal(krb5_context context,
+ krb5_ccache id,
+ krb5_principal *principal)
+{
+ krb5_scache *s = SCACHE(id);
+ krb5_error_code ret;
+ const char *str;
+
+ *principal = NULL;
+
+ ret = make_database(context, s);
+ if (ret)
+ return ret;
+
+ sqlite3_bind_int(s->scache, 1, s->cid);
+
+ if (sqlite3_step(s->scache) != SQLITE_ROW) {
+ sqlite3_reset(s->scache);
+ krb5_set_error_message(context, KRB5_CC_END,
+ N_("No principal for cache SCC:%s", ""),
+ s->name);
+ return KRB5_CC_END;
+ }
+
+ if (sqlite3_column_type(s->scache, 0) != SQLITE_TEXT) {
+ sqlite3_reset(s->scache);
+ krb5_set_error_message(context, KRB5_CC_END,
+ N_("Principal data of wrong type "
+ "for SCC:%s", ""),
+ s->name);
+ return KRB5_CC_END;
+ }
+
+ str = (const char *)sqlite3_column_text(s->scache, 0);
+ if (str == NULL) {
+ sqlite3_reset(s->scache);
+ krb5_set_error_message(context, KRB5_CC_END,
+ N_("Principal not set for SCC:%s", ""),
+ s->name);
+ return KRB5_CC_END;
+ }
+
+ ret = krb5_parse_name(context, str, principal);
+
+ sqlite3_reset(s->scache);
+
+ return ret;
+}
+
+struct cred_ctx {
+ char *drop;
+ sqlite3_stmt *stmt;
+ sqlite3_stmt *credstmt;
+};
+
+static krb5_error_code KRB5_CALLCONV
+scc_get_first (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+ krb5_scache *s = SCACHE(id);
+ krb5_error_code ret;
+ struct cred_ctx *ctx;
+ char *str = NULL, *name = NULL;
+
+ *cursor = NULL;
+
+ ctx = calloc(1, sizeof(*ctx));
+ if (ctx == NULL)
+ return krb5_enomem(context);
+
+ ret = make_database(context, s);
+ if (ret) {
+ free(ctx);
+ return ret;
+ }
+
+ if (s->cid == SCACHE_INVALID_CID) {
+ krb5_set_error_message(context, KRB5_CC_END,
+ N_("Iterating a invalid scache %s", ""),
+ s->name);
+ free(ctx);
+ return KRB5_CC_END;
+ }
+
+ ret = asprintf(&name, "credIteration%pPid%d",
+ ctx, (int)getpid());
+ if (ret < 0 || name == NULL) {
+ free(ctx);
+ return krb5_enomem(context);
+ }
+
+ ret = asprintf(&ctx->drop, "DROP TABLE %s", name);
+ if (ret < 0 || ctx->drop == NULL) {
+ free(name);
+ free(ctx);
+ return krb5_enomem(context);
+ }
+
+ ret = asprintf(&str, "CREATE TEMPORARY TABLE %s "
+ "AS SELECT oid,created_at FROM credentials WHERE cid = %lu",
+ name, (unsigned long)s->cid);
+ if (ret < 0 || str == NULL) {
+ free(ctx->drop);
+ free(name);
+ free(ctx);
+ return krb5_enomem(context);
+ }
+
+ ret = exec_stmt(context, s->db, str, KRB5_CC_IO);
+ free(str);
+ str = NULL;
+ if (ret) {
+ free(ctx->drop);
+ free(name);
+ free(ctx);
+ return ret;
+ }
+
+ ret = asprintf(&str, "SELECT oid FROM %s ORDER BY created_at", name);
+ if (ret < 0 || str == NULL) {
+ exec_stmt(context, s->db, ctx->drop, 0);
+ free(ctx->drop);
+ free(name);
+ free(ctx);
+ return ret;
+ }
+
+ ret = prepare_stmt(context, s->db, &ctx->stmt, str);
+ free(str);
+ str = NULL;
+ free(name);
+ if (ret) {
+ exec_stmt(context, s->db, ctx->drop, 0);
+ free(ctx->drop);
+ free(ctx);
+ return ret;
+ }
+
+ ret = prepare_stmt(context, s->db, &ctx->credstmt,
+ "SELECT cred FROM credentials WHERE oid = ?");
+ if (ret) {
+ sqlite3_finalize(ctx->stmt);
+ exec_stmt(context, s->db, ctx->drop, 0);
+ free(ctx->drop);
+ free(ctx);
+ return ret;
+ }
+
+ *cursor = ctx;
+
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_get_next (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor,
+ krb5_creds *creds)
+{
+ struct cred_ctx *ctx = *cursor;
+ krb5_scache *s = SCACHE(id);
+ krb5_error_code ret;
+ sqlite_uint64 oid;
+ const void *data = NULL;
+ size_t len = 0;
+
+next:
+ ret = sqlite3_step(ctx->stmt);
+ if (ret == SQLITE_DONE) {
+ krb5_clear_error_message(context);
+ return KRB5_CC_END;
+ } else if (ret != SQLITE_ROW) {
+ krb5_set_error_message(context, KRB5_CC_IO,
+ N_("scache Database failed: %s", ""),
+ sqlite3_errmsg(s->db));
+ return KRB5_CC_IO;
+ }
+
+ oid = sqlite3_column_int64(ctx->stmt, 0);
+
+ /* read cred from credentials table */
+
+ sqlite3_bind_int(ctx->credstmt, 1, oid);
+
+ ret = sqlite3_step(ctx->credstmt);
+ if (ret != SQLITE_ROW) {
+ sqlite3_reset(ctx->credstmt);
+ goto next;
+ }
+
+ if (sqlite3_column_type(ctx->credstmt, 0) != SQLITE_BLOB) {
+ krb5_set_error_message(context, KRB5_CC_END,
+ N_("credential of wrong type for SCC:%s", ""),
+ s->name);
+ sqlite3_reset(ctx->credstmt);
+ return KRB5_CC_END;
+ }
+
+ data = sqlite3_column_blob(ctx->credstmt, 0);
+ len = sqlite3_column_bytes(ctx->credstmt, 0);
+
+ ret = decode_creds(context, data, len, creds);
+ sqlite3_reset(ctx->credstmt);
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_end_get (krb5_context context,
+ krb5_ccache id,
+ krb5_cc_cursor *cursor)
+{
+ struct cred_ctx *ctx = *cursor;
+ krb5_scache *s = SCACHE(id);
+
+ sqlite3_finalize(ctx->stmt);
+ sqlite3_finalize(ctx->credstmt);
+
+ exec_stmt(context, s->db, ctx->drop, 0);
+
+ free(ctx->drop);
+ free(ctx);
+
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_remove_cred(krb5_context context,
+ krb5_ccache id,
+ krb5_flags which,
+ krb5_creds *mcreds)
+{
+ krb5_scache *s = SCACHE(id);
+ krb5_error_code ret;
+ sqlite3_stmt *stmt;
+ sqlite_uint64 credid = 0;
+ const void *data = NULL;
+ size_t len = 0;
+
+ ret = make_database(context, s);
+ if (ret)
+ return ret;
+
+ ret = prepare_stmt(context, s->db, &stmt,
+ "SELECT cred,oid FROM credentials "
+ "WHERE cid = ?");
+ if (ret)
+ return ret;
+
+ sqlite3_bind_int(stmt, 1, s->cid);
+
+ /* find credential... */
+ while (1) {
+ krb5_creds creds;
+
+ ret = sqlite3_step(stmt);
+ if (ret == SQLITE_DONE) {
+ ret = 0;
+ break;
+ } else if (ret != SQLITE_ROW) {
+ ret = KRB5_CC_IO;
+ krb5_set_error_message(context, ret,
+ N_("scache Database failed: %s", ""),
+ sqlite3_errmsg(s->db));
+ break;
+ }
+
+ if (sqlite3_column_type(stmt, 0) != SQLITE_BLOB) {
+ ret = KRB5_CC_END;
+ krb5_set_error_message(context, ret,
+ N_("Credential of wrong type "
+ "for SCC:%s", ""),
+ s->name);
+ break;
+ }
+
+ data = sqlite3_column_blob(stmt, 0);
+ len = sqlite3_column_bytes(stmt, 0);
+
+ ret = decode_creds(context, data, len, &creds);
+ if (ret)
+ break;
+
+ ret = krb5_compare_creds(context, which, mcreds, &creds);
+ krb5_free_cred_contents(context, &creds);
+ if (ret) {
+ credid = sqlite3_column_int64(stmt, 1);
+ ret = 0;
+ break;
+ }
+ }
+
+ sqlite3_finalize(stmt);
+
+ ret = prepare_stmt(context, s->db, &stmt,
+ "DELETE FROM credentials WHERE oid=?");
+ if (ret)
+ return ret;
+ sqlite3_bind_int(stmt, 1, credid);
+
+ do {
+ ret = sqlite3_step(stmt);
+ } while (ret == SQLITE_ROW);
+ sqlite3_finalize(stmt);
+ if (ret != SQLITE_DONE) {
+ ret = KRB5_CC_IO;
+ krb5_set_error_message(context, ret,
+ N_("failed to delete scache credental", ""));
+ } else
+ ret = 0;
+
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_set_flags(krb5_context context,
+ krb5_ccache id,
+ krb5_flags flags)
+{
+ return 0; /* XXX */
+}
+
+struct cache_iter {
+ char *drop;
+ char *file;
+ sqlite3 *db;
+ sqlite3_stmt *stmt;
+};
+
+static krb5_error_code KRB5_CALLCONV
+scc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor)
+{
+ struct cache_iter *ctx;
+ krb5_error_code ret;
+ char *name = NULL, *str = NULL;
+
+ *cursor = NULL;
+
+ ctx = calloc(1, sizeof(*ctx));
+ if (ctx == NULL)
+ return krb5_enomem(context);
+
+ ret = default_db(context, NULL, &ctx->db, &ctx->file);
+ if (ret) {
+ free(ctx);
+ return ret;
+ }
+
+ ret = asprintf(&name, "cacheIteration%pPid%d",
+ ctx, (int)getpid());
+ if (ret < 0 || name == NULL) {
+ sqlite3_close(ctx->db);
+ free(ctx);
+ return krb5_enomem(context);
+ }
+
+ ret = asprintf(&ctx->drop, "DROP TABLE %s", name);
+ if (ret < 0 || ctx->drop == NULL) {
+ sqlite3_close(ctx->db);
+ free(name);
+ free(ctx);
+ return krb5_enomem(context);
+ }
+
+ ret = asprintf(&str, "CREATE TEMPORARY TABLE %s AS SELECT name FROM caches",
+ name);
+ if (ret < 0 || str == NULL) {
+ sqlite3_close(ctx->db);
+ free(name);
+ free(ctx->drop);
+ free(ctx);
+ return krb5_enomem(context);
+ }
+
+ ret = exec_stmt(context, ctx->db, str, KRB5_CC_IO);
+ free(str);
+ str = NULL;
+ if (ret) {
+ sqlite3_close(ctx->db);
+ free(name);
+ free(ctx->drop);
+ free(ctx);
+ return ret;
+ }
+
+ ret = asprintf(&str, "SELECT name FROM %s", name);
+ if (ret < 0 || str == NULL) {
+ exec_stmt(context, ctx->db, ctx->drop, 0);
+ sqlite3_close(ctx->db);
+ free(name);
+ free(ctx->drop);
+ free(ctx);
+ return krb5_enomem(context);
+ }
+ free(name);
+
+ ret = prepare_stmt(context, ctx->db, &ctx->stmt, str);
+ free(str);
+ if (ret) {
+ exec_stmt(context, ctx->db, ctx->drop, 0);
+ sqlite3_close(ctx->db);
+ free(ctx->drop);
+ free(ctx);
+ return ret;
+ }
+
+ *cursor = ctx;
+
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_get_cache_next(krb5_context context,
+ krb5_cc_cursor cursor,
+ krb5_ccache *id)
+{
+ struct cache_iter *ctx = cursor;
+ krb5_error_code ret;
+ const char *name;
+
+again:
+ ret = sqlite3_step(ctx->stmt);
+ if (ret == SQLITE_DONE) {
+ krb5_clear_error_message(context);
+ return KRB5_CC_END;
+ } else if (ret != SQLITE_ROW) {
+ krb5_set_error_message(context, KRB5_CC_IO,
+ N_("Database failed: %s", ""),
+ sqlite3_errmsg(ctx->db));
+ return KRB5_CC_IO;
+ }
+
+ if (sqlite3_column_type(ctx->stmt, 0) != SQLITE_TEXT)
+ goto again;
+
+ name = (const char *)sqlite3_column_text(ctx->stmt, 0);
+ if (name == NULL)
+ goto again;
+
+ ret = _krb5_cc_allocate(context, &krb5_scc_ops, id);
+ if (ret == 0)
+ ret = scc_resolve_2(context, id, ctx->file, name);
+ if (ret) {
+ free(*id);
+ *id = NULL;
+ }
+ return ret;
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_end_cache_get(krb5_context context, krb5_cc_cursor cursor)
+{
+ struct cache_iter *ctx = cursor;
+
+ exec_stmt(context, ctx->db, ctx->drop, 0);
+ sqlite3_finalize(ctx->stmt);
+ sqlite3_close(ctx->db);
+ free(ctx->file);
+ free(ctx->drop);
+ free(ctx);
+ return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_move(krb5_context context, krb5_ccache from, krb5_ccache to)
+{
+ krb5_scache *sfrom = SCACHE(from);
+ krb5_scache *sto = SCACHE(to);
+ krb5_error_code ret;
+
+ if (strcmp(sfrom->file, sto->file) != 0) {
+ /* Let upstairs handle the move */
+ return EXDEV;
+ }
+
+ ret = make_database(context, sfrom);
+ if (ret)
+ return ret;
+
+ ret = exec_stmt(context, sfrom->db,
+ "BEGIN IMMEDIATE TRANSACTION", KRB5_CC_IO);
+ if (ret) return ret;
+
+ if (sto->cid != SCACHE_INVALID_CID) {
+ /* drop old cache entry */
+
+ sqlite3_bind_int(sfrom->dcache, 1, sto->cid);
+ do {
+ ret = sqlite3_step(sfrom->dcache);
+ } while (ret == SQLITE_ROW);
+ sqlite3_reset(sfrom->dcache);
+ if (ret != SQLITE_DONE) {
+ krb5_set_error_message(context, KRB5_CC_IO,
+ N_("Failed to delete old cache: %d", ""),
+ (int)ret);
+ goto rollback;
+ }
+ }
+
+ sqlite3_bind_text(sfrom->ucachen, 1, sto->sub, -1, NULL);
+ sqlite3_bind_int(sfrom->ucachen, 2, sfrom->cid);
+
+ do {
+ ret = sqlite3_step(sfrom->ucachen);
+ } while (ret == SQLITE_ROW);
+ sqlite3_reset(sfrom->ucachen);
+ if (ret != SQLITE_DONE) {
+ krb5_set_error_message(context, KRB5_CC_IO,
+ N_("Failed to update new cache: %d", ""),
+ (int)ret);
+ goto rollback;
+ }
+
+ sto->cid = sfrom->cid;
+
+ ret = exec_stmt(context, sfrom->db, "COMMIT", KRB5_CC_IO);
+ if (ret) return ret;
+
+ krb5_cc_close(context, from);
+ return 0;
+
+rollback:
+ exec_stmt(context, sfrom->db, "ROLLBACK", 0);
+ return KRB5_CC_IO;
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_get_default_name(krb5_context context, char **str)
+{
+ *str = NULL;
+ return _krb5_expand_default_cc_name(context, KRB5_SCACHE_NAME, str);
+}
+
+static krb5_error_code KRB5_CALLCONV
+scc_set_default(krb5_context context, krb5_ccache id)
+{
+ krb5_scache *s = SCACHE(id);
+ krb5_error_code ret;
+
+ if (s->cid == SCACHE_INVALID_CID) {
+ krb5_set_error_message(context, KRB5_CC_IO,
+ N_("Trying to set a invalid cache "
+ "as default %s", ""),
+ s->name);
+ return KRB5_CC_IO;
+ }
+
+ ret = sqlite3_bind_text(s->umaster, 1, s->sub, -1, NULL);
+ if (ret) {
+ sqlite3_reset(s->umaster);
+ krb5_set_error_message(context, KRB5_CC_IO,
+ N_("Failed to set name of default cache", ""));
+ return KRB5_CC_IO;
+ }
+
+ do {
+ ret = sqlite3_step(s->umaster);
+ } while (ret == SQLITE_ROW);
+ sqlite3_reset(s->umaster);
+ if (ret != SQLITE_DONE) {
+ krb5_set_error_message(context, KRB5_CC_IO,
+ N_("Failed to update default cache", ""));
+ return KRB5_CC_IO;
+ }
+
+ return 0;
+}
+
+/**
+ * Variable containing the SCC based credential cache implemention.
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_VARIABLE const krb5_cc_ops krb5_scc_ops = {
+ KRB5_CC_OPS_VERSION_5,
+ "SCC",
+ NULL,
+ NULL,
+ scc_gen_new,
+ scc_initialize,
+ scc_destroy,
+ scc_close,
+ scc_store_cred,
+ NULL, /* scc_retrieve */
+ scc_get_principal,
+ scc_get_first,
+ scc_get_next,
+ scc_end_get,
+ scc_remove_cred,
+ scc_set_flags,
+ NULL,
+ scc_get_cache_first,
+ scc_get_cache_next,
+ scc_end_cache_get,
+ scc_move,
+ scc_get_default_name,
+ scc_set_default,
+ NULL,
+ NULL,
+ NULL,
+ scc_get_name_2,
+ scc_resolve_2
+};
+
+#endif
diff --git a/third_party/heimdal/lib/krb5/send_to_kdc.c b/third_party/heimdal/lib/krb5/send_to_kdc.c
new file mode 100644
index 0000000..086f2ed
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/send_to_kdc.c
@@ -0,0 +1,1357 @@
+/*
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 - 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include "send_to_kdc_plugin.h"
+
+/**
+ * @section send_to_kdc Locating and sending packets to the KDC
+ *
+ * The send to kdc code is responsible to request the list of KDC from
+ * the locate-kdc subsystem and then send requests to each of them.
+ *
+ * - Each second a new hostname is tried.
+ * - If the hostname have several addresses, the first will be tried
+ * directly then in turn the other will be tried every 3 seconds
+ * (host_timeout).
+ * - UDP requests are tried 3 times, and it tried with a individual timeout of kdc_timeout / 3.
+ * - TCP and HTTP requests are tried 1 time.
+ *
+ * Total wait time shorter then (number of addresses * 3) + kdc_timeout seconds.
+ *
+ */
+
+static int
+init_port(const char *s, int fallback)
+{
+ int tmp;
+
+ if (s && sscanf(s, "%d", &tmp) == 1)
+ return htons(tmp);
+ return fallback;
+}
+
+struct send_via_plugin_s {
+ krb5_const_realm realm;
+ krb5_krbhst_info *hi;
+ time_t timeout;
+ const krb5_data *send_data;
+ krb5_data *receive;
+};
+
+
+static krb5_error_code KRB5_LIB_CALL
+kdccallback(krb5_context context, const void *plug, void *plugctx, void *userctx)
+{
+ const krb5plugin_send_to_kdc_ftable *service = (const krb5plugin_send_to_kdc_ftable *)plug;
+ struct send_via_plugin_s *ctx = userctx;
+
+ if (service->send_to_kdc == NULL)
+ return KRB5_PLUGIN_NO_HANDLE;
+ return service->send_to_kdc(context, plugctx, ctx->hi, ctx->timeout,
+ ctx->send_data, ctx->receive);
+}
+
+static krb5_error_code KRB5_LIB_CALL
+realmcallback(krb5_context context, const void *plug, void *plugctx, void *userctx)
+{
+ const krb5plugin_send_to_kdc_ftable *service = (const krb5plugin_send_to_kdc_ftable *)plug;
+ struct send_via_plugin_s *ctx = userctx;
+
+ if (service->send_to_realm == NULL)
+ return KRB5_PLUGIN_NO_HANDLE;
+ return service->send_to_realm(context, plugctx, ctx->realm, ctx->timeout,
+ ctx->send_data, ctx->receive);
+}
+
+static const char *send_to_kdc_plugin_deps[] = { "krb5", NULL };
+
+static struct heim_plugin_data
+send_to_kdc_plugin_data = {
+ "krb5",
+ KRB5_PLUGIN_SEND_TO_KDC,
+ KRB5_PLUGIN_SEND_TO_KDC_VERSION_0,
+ send_to_kdc_plugin_deps,
+ krb5_get_instance
+};
+
+static krb5_error_code
+kdc_via_plugin(krb5_context context,
+ krb5_krbhst_info *hi,
+ time_t timeout,
+ const krb5_data *send_data,
+ krb5_data *receive)
+{
+ struct send_via_plugin_s userctx;
+
+ userctx.realm = NULL;
+ userctx.hi = hi;
+ userctx.timeout = timeout;
+ userctx.send_data = send_data;
+ userctx.receive = receive;
+
+ return _krb5_plugin_run_f(context, &send_to_kdc_plugin_data, 0,
+ &userctx, kdccallback);
+}
+
+static krb5_error_code
+realm_via_plugin(krb5_context context,
+ krb5_const_realm realm,
+ time_t timeout,
+ const krb5_data *send_data,
+ krb5_data *receive)
+{
+ struct send_via_plugin_s userctx;
+
+ userctx.realm = realm;
+ userctx.hi = NULL;
+ userctx.timeout = timeout;
+ userctx.send_data = send_data;
+ userctx.receive = receive;
+
+ return _krb5_plugin_run_f(context, &send_to_kdc_plugin_data, 0,
+ &userctx, realmcallback);
+}
+
+struct krb5_sendto_ctx_data {
+ int flags;
+ int type;
+ krb5_sendto_ctx_func func;
+ void *data;
+ char *hostname;
+ char *sitename;
+ krb5_krbhst_handle krbhst;
+
+ /* context2 */
+ const krb5_data *send_data;
+ krb5_data response;
+ heim_array_t hosts;
+ int stateflags;
+#define KRBHST_COMPLETED 1
+
+ /* prexmit */
+ krb5_sendto_prexmit prexmit_func;
+ void *prexmit_ctx;
+
+ /* stats */
+ struct {
+ struct timeval start_time;
+ struct timeval name_resolution;
+ struct timeval krbhst;
+ unsigned long sent_packets;
+ unsigned long num_hosts;
+ } stats;
+ unsigned int stid;
+};
+
+static void KRB5_CALLCONV
+dealloc_sendto_ctx(void *ptr)
+{
+ krb5_sendto_ctx ctx = (krb5_sendto_ctx)ptr;
+ if (ctx->hostname)
+ free(ctx->hostname);
+ if (ctx->sitename)
+ free(ctx->sitename);
+ heim_release(ctx->hosts);
+ heim_release(ctx->krbhst);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_sendto_ctx_alloc(krb5_context context, krb5_sendto_ctx *ctx)
+{
+ *ctx = heim_alloc(sizeof(**ctx), "sendto-context", dealloc_sendto_ctx);
+ if (*ctx == NULL)
+ return krb5_enomem(context);
+ (*ctx)->hosts = heim_array_create();
+
+ return 0;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_sendto_ctx_add_flags(krb5_sendto_ctx ctx, int flags)
+{
+ ctx->flags |= flags;
+}
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_sendto_ctx_get_flags(krb5_sendto_ctx ctx)
+{
+ return ctx->flags;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_sendto_ctx_set_type(krb5_sendto_ctx ctx, int type)
+{
+ ctx->type = type;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_sendto_ctx_set_func(krb5_sendto_ctx ctx,
+ krb5_sendto_ctx_func func,
+ void *data)
+{
+ ctx->func = func;
+ ctx->data = data;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_sendto_ctx_set_prexmit(krb5_sendto_ctx ctx,
+ krb5_sendto_prexmit prexmit,
+ void *data)
+{
+ ctx->prexmit_func = prexmit;
+ ctx->prexmit_ctx = data;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_sendto_set_hostname(krb5_context context,
+ krb5_sendto_ctx ctx,
+ const char *hostname)
+{
+ char *newname;
+
+ /*
+ * Handle the case where hostname == ctx->hostname by copying it first, and
+ * disposing of any previous value after.
+ */
+ newname = strdup(hostname);
+ if (newname == NULL)
+ return krb5_enomem(context);
+ free(ctx->hostname);
+ ctx->hostname = newname;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_sendto_set_sitename(krb5_context context,
+ krb5_sendto_ctx ctx,
+ const char *sitename)
+{
+ char *newname;
+
+ newname = strdup(sitename);
+ if (newname == NULL)
+ return krb5_enomem(context);
+ free(ctx->sitename);
+ ctx->sitename = newname;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_sendto_ctx_set_krb5hst(krb5_context context,
+ krb5_sendto_ctx ctx,
+ krb5_krbhst_handle handle)
+{
+ heim_release(ctx->krbhst);
+ ctx->krbhst = heim_retain(handle);
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_sendto_ctx_free(krb5_context context, krb5_sendto_ctx ctx)
+{
+ heim_release(ctx);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_kdc_retry(krb5_context context, krb5_sendto_ctx ctx, void *data,
+ const krb5_data *reply, int *action)
+{
+ krb5_error_code ret;
+ KRB_ERROR error;
+
+ if(krb5_rd_error(context, reply, &error))
+ return 0;
+
+ ret = krb5_error_from_rd_error(context, &error, NULL);
+ krb5_free_error_contents(context, &error);
+
+ switch(ret) {
+ case KRB5KRB_ERR_RESPONSE_TOO_BIG: {
+ if (krb5_sendto_ctx_get_flags(ctx) & KRB5_KRBHST_FLAGS_LARGE_MSG)
+ break;
+ krb5_sendto_ctx_add_flags(ctx, KRB5_KRBHST_FLAGS_LARGE_MSG);
+ *action = KRB5_SENDTO_RESET;
+ break;
+ }
+ case KRB5KDC_ERR_SVC_UNAVAILABLE:
+ *action = KRB5_SENDTO_RESET;
+ break;
+ }
+ return 0;
+}
+
+/*
+ *
+ */
+
+struct host;
+
+struct host_fun {
+ krb5_error_code (*prepare)(krb5_context, struct host *, const krb5_data *);
+ krb5_error_code (*send_fn)(krb5_context, struct host *);
+ krb5_error_code (*recv_fn)(krb5_context, struct host *, krb5_data *);
+ int ntries;
+};
+
+struct host {
+ enum host_state { CONNECT, CONNECTING, CONNECTED, WAITING_REPLY, DEAD } state;
+ krb5_krbhst_info *hi;
+ struct addrinfo *ai;
+ rk_socket_t fd;
+ struct host_fun *fun;
+ unsigned int tries;
+ time_t timeout;
+ krb5_data data;
+ unsigned int tid;
+};
+
+static void
+debug_host(krb5_context context, int level, struct host *host, const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 4, 5)));
+
+static void
+debug_host(krb5_context context, int level, struct host *host, const char *fmt, ...)
+{
+ const char *proto = "unknown";
+ const char *state;
+ char name[NI_MAXHOST], port[NI_MAXSERV];
+ char *text = NULL;
+ va_list ap;
+ int ret;
+
+ if (!_krb5_have_debug(context, 5))
+ return;
+
+ va_start(ap, fmt);
+ ret = vasprintf(&text, fmt, ap);
+ va_end(ap);
+ if (ret == -1 || text == NULL)
+ return;
+
+ if (host->hi->proto == KRB5_KRBHST_HTTP)
+ proto = "http";
+ else if (host->hi->proto == KRB5_KRBHST_TCP)
+ proto = "tcp";
+ else if (host->hi->proto == KRB5_KRBHST_UDP)
+ proto = "udp";
+
+ if (getnameinfo(host->ai->ai_addr, host->ai->ai_addrlen,
+ name, sizeof(name), port, sizeof(port), NI_NUMERICHOST) != 0)
+ name[0] = '\0';
+
+ switch (host->state) {
+ case CONNECT: state = "CONNECT"; break;
+ case CONNECTING: state = "CONNECTING"; break;
+ case CONNECTED: state = "CONNECTED"; break;
+ case WAITING_REPLY: state = "WAITING_REPLY"; break;
+ case DEAD: state = "DEAD"; break;
+ default: state = "unknown"; break;
+ }
+
+ _krb5_debug(context, level, "%s: %s %s:%s (%s) state=%s tid: %08x", text,
+ proto, name, port, host->hi->hostname, state, host->tid);
+ free(text);
+}
+
+
+static void HEIM_CALLCONV
+deallocate_host(void *ptr)
+{
+ struct host *host = ptr;
+ if (!rk_IS_BAD_SOCKET(host->fd))
+ rk_closesocket(host->fd);
+ krb5_data_free(&host->data);
+ host->ai = NULL;
+}
+
+static void
+host_dead(krb5_context context, struct host *host, const char *msg)
+{
+ debug_host(context, 5, host, "%s", msg);
+ rk_closesocket(host->fd);
+ host->fd = rk_INVALID_SOCKET;
+ host->state = DEAD;
+}
+
+static krb5_error_code
+send_stream(krb5_context context, struct host *host)
+{
+ ssize_t len;
+
+ len = krb5_net_write(context, &host->fd, host->data.data, host->data.length);
+
+ if (len < 0)
+ return errno;
+ else if (len < host->data.length) {
+ host->data.length -= len;
+ memmove(host->data.data, ((uint8_t *)host->data.data) + len, host->data.length - len);
+ return -1;
+ } else {
+ krb5_data_free(&host->data);
+ return 0;
+ }
+}
+
+static krb5_error_code
+recv_stream(krb5_context context, struct host *host)
+{
+ krb5_error_code ret;
+ size_t oldlen;
+ ssize_t sret;
+ int nbytes;
+
+ if (rk_SOCK_IOCTL(host->fd, FIONREAD, &nbytes) != 0 || nbytes <= 0)
+ return HEIM_NET_CONN_REFUSED;
+
+ if (context->max_msg_size - host->data.length < nbytes) {
+ krb5_set_error_message(context, KRB5KRB_ERR_FIELD_TOOLONG,
+ N_("TCP message from KDC too large %d", ""),
+ (int)(host->data.length + nbytes));
+ return KRB5KRB_ERR_FIELD_TOOLONG;
+ }
+
+ oldlen = host->data.length;
+
+ ret = krb5_data_realloc(&host->data, oldlen + nbytes + 1 /* NUL */);
+ if (ret)
+ return ret;
+
+ sret = krb5_net_read(context, &host->fd, ((uint8_t *)host->data.data) + oldlen, nbytes);
+ if (sret <= 0) {
+ ret = errno;
+ return ret;
+ }
+ host->data.length = oldlen + sret;
+ /* zero terminate for http transport */
+ ((uint8_t *)host->data.data)[host->data.length] = '\0';
+
+ return 0;
+}
+
+/*
+ *
+ */
+
+static void
+host_next_timeout(krb5_context context, struct host *host)
+{
+ host->timeout = context->kdc_timeout / host->fun->ntries;
+ if (host->timeout == 0)
+ host->timeout = 1;
+
+ host->timeout += time(NULL);
+}
+
+/*
+ * connected host
+ */
+
+static void
+host_connected(krb5_context context, krb5_sendto_ctx ctx, struct host *host)
+{
+ krb5_error_code ret;
+
+ host->state = CONNECTED;
+ /*
+ * Now prepare data to send to host
+ */
+ if (ctx->prexmit_func) {
+ krb5_data data;
+
+ krb5_data_zero(&data);
+
+ ret = ctx->prexmit_func(context, host->hi->proto,
+ ctx->prexmit_ctx, host->fd, &data);
+ if (ret == 0) {
+ if (data.length == 0) {
+ host_dead(context, host, "prexmit function didn't send data");
+ return;
+ }
+ ret = host->fun->prepare(context, host, &data);
+ krb5_data_free(&data);
+ }
+
+ } else {
+ ret = host->fun->prepare(context, host, ctx->send_data);
+ }
+ if (ret)
+ debug_host(context, 5, host, "failed to prexmit/prepare");
+}
+
+/*
+ * connect host
+ */
+
+static void
+host_connect(krb5_context context, krb5_sendto_ctx ctx, struct host *host)
+{
+ krb5_krbhst_info *hi = host->hi;
+ struct addrinfo *ai = host->ai;
+
+ debug_host(context, 5, host, "connecting to host");
+
+ if (connect(host->fd, ai->ai_addr, ai->ai_addrlen) < 0) {
+#ifdef HAVE_WINSOCK
+ if (WSAGetLastError() == WSAEWOULDBLOCK)
+ errno = EINPROGRESS;
+#endif /* HAVE_WINSOCK */
+ if (errno == EINPROGRESS && (hi->proto == KRB5_KRBHST_HTTP || hi->proto == KRB5_KRBHST_TCP)) {
+ debug_host(context, 5, host, "connecting to %d", host->fd);
+ host->state = CONNECTING;
+ } else {
+ host_dead(context, host, "failed to connect");
+ }
+ } else {
+ host_connected(context, ctx, host);
+ }
+
+ host_next_timeout(context, host);
+}
+
+/*
+ * HTTP transport
+ */
+
+static krb5_error_code
+prepare_http(krb5_context context, struct host *host, const krb5_data *data)
+{
+ char *str = NULL, *request = NULL;
+ krb5_error_code ret;
+ int len;
+
+ heim_assert(host->data.length == 0, "prepare_http called twice");
+
+ len = rk_base64_encode(data->data, data->length, &str);
+ if(len < 0)
+ return ENOMEM;
+
+ if (context->http_proxy)
+ ret = asprintf(&request, "GET http://%s/%s HTTP/1.0\r\n\r\n", host->hi->hostname, str);
+ else
+ ret = asprintf(&request, "GET /%s HTTP/1.0\r\n\r\n", str);
+ free(str);
+ if(ret < 0 || request == NULL)
+ return ENOMEM;
+
+ host->data.data = request;
+ host->data.length = strlen(request);
+
+ return 0;
+}
+
+static krb5_error_code
+recv_http(krb5_context context, struct host *host, krb5_data *data)
+{
+ krb5_error_code ret;
+ unsigned long rep_len;
+ size_t len;
+ char *p;
+
+ /*
+ * recv_stream returns a NUL terminated stream
+ */
+
+ ret = recv_stream(context, host);
+ if (ret)
+ return ret;
+
+ p = strstr(host->data.data, "\r\n\r\n");
+ if (p == NULL)
+ return -1;
+ p += 4;
+
+ len = host->data.length - (p - (char *)host->data.data);
+ if (len < 4)
+ return -1;
+
+ _krb5_get_int(p, &rep_len, 4);
+ if (len < rep_len)
+ return -1;
+
+ p += 4;
+
+ memmove(host->data.data, p, rep_len);
+ host->data.length = rep_len;
+
+ *data = host->data;
+ krb5_data_zero(&host->data);
+
+ return 0;
+}
+
+/*
+ * TCP transport
+ */
+
+static krb5_error_code
+prepare_tcp(krb5_context context, struct host *host, const krb5_data *data)
+{
+ krb5_error_code ret;
+ krb5_storage *sp;
+
+ heim_assert(host->data.length == 0, "prepare_tcp called twice");
+
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ return ENOMEM;
+
+ ret = krb5_store_data(sp, *data);
+ if (ret) {
+ krb5_storage_free(sp);
+ return ret;
+ }
+ ret = krb5_storage_to_data(sp, &host->data);
+ krb5_storage_free(sp);
+
+ return ret;
+}
+
+static krb5_error_code
+recv_tcp(krb5_context context, struct host *host, krb5_data *data)
+{
+ krb5_error_code ret;
+ unsigned long pktlen;
+
+ ret = recv_stream(context, host);
+ if (ret)
+ return ret;
+
+ if (host->data.length < 4)
+ return -1;
+
+ _krb5_get_int(host->data.data, &pktlen, 4);
+
+ if (pktlen > host->data.length - 4)
+ return -1;
+
+ memmove(host->data.data, ((uint8_t *)host->data.data) + 4, host->data.length - 4);
+ host->data.length -= 4;
+
+ *data = host->data;
+ krb5_data_zero(&host->data);
+
+ return 0;
+}
+
+/*
+ * UDP transport
+ */
+
+static krb5_error_code
+prepare_udp(krb5_context context, struct host *host, const krb5_data *data)
+{
+ return krb5_data_copy(&host->data, data->data, data->length);
+}
+
+static krb5_error_code
+send_udp(krb5_context context, struct host *host)
+{
+ if (send(host->fd, host->data.data, host->data.length, 0) < 0)
+ return errno;
+ return 0;
+}
+
+static krb5_error_code
+recv_udp(krb5_context context, struct host *host, krb5_data *data)
+{
+ krb5_error_code ret;
+ int nbytes;
+
+
+ if (rk_SOCK_IOCTL(host->fd, FIONREAD, &nbytes) != 0 || nbytes <= 0)
+ return HEIM_NET_CONN_REFUSED;
+
+ if (context->max_msg_size < nbytes) {
+ krb5_set_error_message(context, KRB5KRB_ERR_FIELD_TOOLONG,
+ N_("UDP message from KDC too large %d", ""),
+ (int)nbytes);
+ return KRB5KRB_ERR_FIELD_TOOLONG;
+ }
+
+ ret = krb5_data_alloc(data, nbytes);
+ if (ret)
+ return ret;
+
+ ret = recv(host->fd, data->data, data->length, 0);
+ if (ret < 0) {
+ ret = errno;
+ krb5_data_free(data);
+ return ret;
+ }
+ data->length = ret;
+
+ return 0;
+}
+
+static struct host_fun http_fun = {
+ prepare_http,
+ send_stream,
+ recv_http,
+ 1
+};
+static struct host_fun tcp_fun = {
+ prepare_tcp,
+ send_stream,
+ recv_tcp,
+ 1
+};
+static struct host_fun udp_fun = {
+ prepare_udp,
+ send_udp,
+ recv_udp,
+ 3
+};
+
+
+/*
+ * Host state machine
+ */
+
+static int
+eval_host_state(krb5_context context,
+ krb5_sendto_ctx ctx,
+ struct host *host,
+ int readable, int writeable)
+{
+ krb5_error_code ret;
+
+ if (host->state == CONNECT) {
+ /* check if its this host time to connect */
+ if (host->timeout < time(NULL))
+ host_connect(context, ctx, host);
+ return 0;
+ }
+
+ if (host->state == CONNECTING && writeable)
+ host_connected(context, ctx, host);
+
+ if (readable) {
+
+ debug_host(context, 5, host, "reading packet");
+
+ ret = host->fun->recv_fn(context, host, &ctx->response);
+ if (ret == -1) {
+ /* not done yet */
+ } else if (ret == 0) {
+ /* if recv_foo function returns 0, we have a complete reply */
+ debug_host(context, 5, host, "host completed");
+ return 1;
+ } else {
+ host_dead(context, host, "host disconnected");
+ }
+ }
+
+ /* check if there is anything to send, state might DEAD after read */
+ if (writeable && host->state == CONNECTED) {
+
+ ctx->stats.sent_packets++;
+
+ debug_host(context, 5, host, "writing packet");
+
+ ret = host->fun->send_fn(context, host);
+ if (ret == -1) {
+ /* not done yet */
+ } else if (ret) {
+ host_dead(context, host, "host dead, write failed");
+ } else
+ host->state = WAITING_REPLY;
+ }
+
+ return 0;
+}
+
+/*
+ *
+ */
+
+static krb5_error_code
+submit_request(krb5_context context, krb5_sendto_ctx ctx, krb5_krbhst_info *hi)
+{
+ unsigned long submitted_host = 0;
+ krb5_boolean freeai = FALSE;
+ struct timeval nrstart, nrstop;
+ krb5_error_code ret;
+ struct addrinfo *ai = NULL, *a;
+ struct host *host;
+
+ ret = kdc_via_plugin(context, hi, context->kdc_timeout,
+ ctx->send_data, &ctx->response);
+ if (ret == 0) {
+ return 0;
+ } else if (ret != KRB5_PLUGIN_NO_HANDLE) {
+ _krb5_debug(context, 5, "send via plugin failed %s: %d",
+ hi->hostname, ret);
+ return ret;
+ }
+
+ /*
+ * If we have a proxy, let use the address of the proxy instead of
+ * the KDC and let the proxy deal with the resolving of the KDC.
+ */
+
+ gettimeofday(&nrstart, NULL);
+
+ if (hi->proto == KRB5_KRBHST_HTTP && context->http_proxy) {
+ char *proxy2 = strdup(context->http_proxy);
+ char *el, *proxy = proxy2;
+ struct addrinfo hints;
+ char portstr[NI_MAXSERV];
+ unsigned short nport;
+
+ if (proxy == NULL)
+ return ENOMEM;
+ if (strncmp(proxy, "http://", 7) == 0)
+ proxy += 7;
+
+ /* check for url terminating slash */
+ el = strchr(proxy, '/');
+ if (el != NULL)
+ *el = '\0';
+
+ /* check for port in hostname, used below as port */
+ el = strchr(proxy, ':');
+ if(el != NULL)
+ *el++ = '\0';
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+
+ /* On some systems ntohs(foo(..., htons(...))) causes shadowing */
+ nport = init_port(el, htons(80));
+ snprintf(portstr, sizeof(portstr), "%d", ntohs(nport));
+
+ ret = getaddrinfo(proxy, portstr, &hints, &ai);
+ free(proxy2);
+ if (ret)
+ return krb5_eai_to_heim_errno(ret, errno);
+
+ freeai = TRUE;
+
+ } else {
+ ret = krb5_krbhst_get_addrinfo(context, hi, &ai);
+ if (ret)
+ return ret;
+ }
+
+ /* add up times */
+ gettimeofday(&nrstop, NULL);
+ timevalsub(&nrstop, &nrstart);
+ timevaladd(&ctx->stats.name_resolution, &nrstop);
+
+ ctx->stats.num_hosts++;
+
+ for (a = ai; a != NULL; a = a->ai_next) {
+ rk_socket_t fd;
+
+ fd = socket(a->ai_family, a->ai_socktype | SOCK_CLOEXEC, a->ai_protocol);
+ if (rk_IS_BAD_SOCKET(fd))
+ continue;
+ rk_cloexec(fd);
+
+#ifndef NO_LIMIT_FD_SETSIZE
+ if (fd >= FD_SETSIZE) {
+ _krb5_debug(context, 0, "fd too large for select");
+ rk_closesocket(fd);
+ continue;
+ }
+#endif
+ socket_set_nonblocking(fd, 1);
+
+ host = heim_alloc(sizeof(*host), "sendto-host", deallocate_host);
+ if (host == NULL) {
+ if (freeai)
+ freeaddrinfo(ai);
+ rk_closesocket(fd);
+ return ENOMEM;
+ }
+ host->hi = hi;
+ host->fd = fd;
+ host->ai = a;
+ /* next version of stid */
+ host->tid = ctx->stid = (ctx->stid & 0xffff0000) | ((ctx->stid & 0xffff) + 1);
+
+ host->state = CONNECT;
+
+ switch (host->hi->proto) {
+ case KRB5_KRBHST_HTTP :
+ host->fun = &http_fun;
+ break;
+ case KRB5_KRBHST_TCP :
+ host->fun = &tcp_fun;
+ break;
+ case KRB5_KRBHST_UDP :
+ host->fun = &udp_fun;
+ break;
+ default:
+ heim_abort("undefined http transport protocol: %d", (int)host->hi->proto);
+ }
+
+ host->tries = host->fun->ntries;
+
+ /*
+ * Connect directly next host, wait a host_timeout for each next address.
+ * We try host_connect() here, checking the return code because as we do
+ * non-blocking connects, any error here indicates that the address is just
+ * offline. That is, it's something like "No route to host" which is not
+ * worth retrying. And so, we fail directly and immediately to the next
+ * address for this host without enqueueing the address for retries.
+ */
+ if (submitted_host == 0) {
+ host_connect(context, ctx, host);
+ if (host->state == DEAD)
+ continue;
+ } else {
+ debug_host(context, 5, host,
+ "Queuing host in future (in %ds), its the %lu address on the same name",
+ (int)(context->host_timeout * submitted_host), submitted_host + 1);
+ host->timeout = time(NULL) + (submitted_host * context->host_timeout);
+ }
+
+ heim_array_append_value(ctx->hosts, host);
+ heim_release(host);
+ submitted_host++;
+ }
+
+ if (freeai)
+ freeaddrinfo(ai);
+
+ if (submitted_host == 0)
+ return KRB5_KDC_UNREACH;
+
+ return 0;
+}
+
+struct wait_ctx {
+ krb5_context context;
+ krb5_sendto_ctx ctx;
+ fd_set rfds;
+ fd_set wfds;
+ rk_socket_t max_fd;
+ int got_reply;
+ time_t timenow;
+};
+
+static void
+wait_setup(heim_object_t obj, void *iter_ctx, int *stop)
+{
+ struct wait_ctx *wait_ctx = iter_ctx;
+ struct host *h = (struct host *)obj;
+
+ if (h->state == CONNECT) {
+ if (h->timeout >= wait_ctx->timenow)
+ return;
+ host_connect(wait_ctx->context, wait_ctx->ctx, h);
+ }
+
+ /* skip dead hosts */
+ if (h->state == DEAD)
+ return;
+
+ /* if host timed out, dec tries and (retry or kill host) */
+ if (h->timeout < wait_ctx->timenow) {
+ heim_assert(h->tries != 0, "tries should not reach 0");
+ h->tries--;
+ if (h->tries == 0) {
+ host_dead(wait_ctx->context, h, "host timed out");
+ return;
+ } else {
+ debug_host(wait_ctx->context, 5, h, "retrying sending to");
+ host_next_timeout(wait_ctx->context, h);
+ host_connected(wait_ctx->context, wait_ctx->ctx, h);
+ }
+ }
+
+#ifndef NO_LIMIT_FD_SETSIZE
+ heim_assert(h->fd < FD_SETSIZE, "fd too large");
+#endif
+ switch (h->state) {
+ case WAITING_REPLY:
+ FD_SET(h->fd, &wait_ctx->rfds);
+ break;
+ case CONNECTING:
+ case CONNECTED:
+ FD_SET(h->fd, &wait_ctx->rfds);
+ FD_SET(h->fd, &wait_ctx->wfds);
+ break;
+ default:
+ debug_host(wait_ctx->context, 5, h, "invalid sendto host state");
+ heim_abort("invalid sendto host state");
+ }
+ if (h->fd > wait_ctx->max_fd || wait_ctx->max_fd == rk_INVALID_SOCKET)
+ wait_ctx->max_fd = h->fd;
+}
+
+static int
+wait_filter_dead(heim_object_t obj, void *ctx)
+{
+ struct host *h = (struct host *)obj;
+ return (int)((h->state == DEAD) ? true : false);
+}
+
+static void
+wait_accelerate(heim_object_t obj, void *ctx, int *stop)
+{
+ struct host *h = (struct host *)obj;
+
+ if (h->state == CONNECT && h->timeout > 0)
+ h->timeout--;
+}
+
+static void
+wait_process(heim_object_t obj, void *ctx, int *stop)
+{
+ struct wait_ctx *wait_ctx = ctx;
+ struct host *h = (struct host *)obj;
+ int readable, writeable;
+ heim_assert(h->state != DEAD, "dead host resurected");
+
+#ifndef NO_LIMIT_FD_SETSIZE
+ heim_assert(h->fd < FD_SETSIZE, "fd too large");
+#endif
+ readable = FD_ISSET(h->fd, &wait_ctx->rfds);
+ writeable = FD_ISSET(h->fd, &wait_ctx->wfds);
+
+ if (readable || writeable || h->state == CONNECT)
+ wait_ctx->got_reply |= eval_host_state(wait_ctx->context, wait_ctx->ctx, h, readable, writeable);
+
+ /* if there is already a reply, just fall though the array */
+ if (wait_ctx->got_reply)
+ *stop = 1;
+}
+
+static krb5_error_code
+wait_response(krb5_context context, int *action, krb5_sendto_ctx ctx)
+{
+ struct wait_ctx wait_ctx;
+ struct timeval tv;
+ int ret;
+
+ wait_ctx.context = context;
+ wait_ctx.ctx = ctx;
+ FD_ZERO(&wait_ctx.rfds);
+ FD_ZERO(&wait_ctx.wfds);
+ wait_ctx.max_fd = rk_INVALID_SOCKET;
+
+ /* oh, we have a reply, it must be a plugin that got it for us */
+ if (ctx->response.length) {
+ *action = KRB5_SENDTO_FILTER;
+ return 0;
+ }
+
+ wait_ctx.timenow = time(NULL);
+
+ heim_array_iterate_f(ctx->hosts, &wait_ctx, wait_setup);
+ heim_array_filter_f(ctx->hosts, &wait_ctx, wait_filter_dead);
+
+ if (heim_array_get_length(ctx->hosts) == 0) {
+ if (ctx->stateflags & KRBHST_COMPLETED) {
+ _krb5_debug(context, 5, "no more hosts to send/recv packets to/from "
+ "trying to pulling more hosts");
+ *action = KRB5_SENDTO_FAILED;
+ } else {
+ _krb5_debug(context, 5, "no more hosts to send/recv packets to/from "
+ "and no more hosts -> failure");
+ *action = KRB5_SENDTO_TIMEOUT;
+ }
+ return 0;
+ }
+
+ if (wait_ctx.max_fd == rk_INVALID_SOCKET) {
+ /*
+ * If we don't find a host which can make progress, then
+ * we accelerate the process by moving all of the contestants
+ * up by 1s.
+ */
+ _krb5_debug(context, 5, "wait_response: moving the contestants forward");
+ heim_array_iterate_f(ctx->hosts, &wait_ctx, wait_accelerate);
+ return 0;
+ }
+
+ tv.tv_sec = 1;
+ tv.tv_usec = 0;
+
+ ret = select(wait_ctx.max_fd + 1, &wait_ctx.rfds, &wait_ctx.wfds, NULL, &tv);
+ if (ret < 0)
+ return errno;
+ if (ret == 0) {
+ *action = KRB5_SENDTO_TIMEOUT;
+ return 0;
+ }
+
+ wait_ctx.got_reply = 0;
+ heim_array_iterate_f(ctx->hosts, &wait_ctx, wait_process);
+ if (wait_ctx.got_reply)
+ *action = KRB5_SENDTO_FILTER;
+ else
+ *action = KRB5_SENDTO_CONTINUE;
+
+ return 0;
+}
+
+static void
+reset_context(krb5_context context, krb5_sendto_ctx ctx)
+{
+ krb5_data_free(&ctx->response);
+ heim_release(ctx->hosts);
+ ctx->hosts = heim_array_create();
+ ctx->stateflags = 0;
+}
+
+
+/*
+ *
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_sendto_context(krb5_context context,
+ krb5_sendto_ctx ctx,
+ const krb5_data *send_data,
+ krb5_const_realm realm,
+ krb5_data *receive)
+{
+ krb5_error_code ret = 0;
+ krb5_krbhst_handle handle = NULL;
+ struct timeval nrstart, nrstop, stop_time;
+ int type, freectx = 0;
+ int action;
+ int numreset = 0;
+
+ krb5_data_zero(receive);
+
+ if (ctx == NULL) {
+ ret = krb5_sendto_ctx_alloc(context, &ctx);
+ if (ret)
+ goto out;
+ freectx = 1;
+ }
+
+ ctx->stid = (context->num_kdc_requests++) << 16;
+
+ memset(&ctx->stats, 0, sizeof(ctx->stats));
+ gettimeofday(&ctx->stats.start_time, NULL);
+
+ type = ctx->type;
+ if (type == 0) {
+ if ((ctx->flags & KRB5_KRBHST_FLAGS_MASTER) || context->use_admin_kdc)
+ type = KRB5_KRBHST_ADMIN;
+ else
+ type = KRB5_KRBHST_KDC;
+ }
+
+ ctx->send_data = send_data;
+
+ if ((int)send_data->length > context->large_msg_size)
+ ctx->flags |= KRB5_KRBHST_FLAGS_LARGE_MSG;
+
+ /* loop until we get back a appropriate response */
+
+ action = KRB5_SENDTO_INITIAL;
+
+ while (1) {
+ krb5_krbhst_info *hi;
+
+ switch (action) {
+ case KRB5_SENDTO_INITIAL:
+ ret = realm_via_plugin(context, realm, context->kdc_timeout,
+ send_data, &ctx->response);
+ if (ret == 0 || ret != KRB5_PLUGIN_NO_HANDLE) {
+ action = KRB5_SENDTO_DONE;
+ break;
+ }
+ action = KRB5_SENDTO_KRBHST;
+ fallthrough;
+ case KRB5_SENDTO_KRBHST:
+ if (ctx->krbhst == NULL) {
+ ret = krb5_krbhst_init_flags(context, realm, type,
+ ctx->flags, &handle);
+ if (ret)
+ goto out;
+
+ if (ctx->hostname) {
+ ret = krb5_krbhst_set_hostname(context, handle, ctx->hostname);
+ if (ret)
+ goto out;
+ }
+ if (ctx->sitename) {
+ ret = krb5_krbhst_set_sitename(context, handle, ctx->sitename);
+ if (ret)
+ goto out;
+ }
+ } else {
+ handle = heim_retain(ctx->krbhst);
+ }
+ action = KRB5_SENDTO_TIMEOUT;
+ fallthrough;
+ case KRB5_SENDTO_TIMEOUT:
+
+ /*
+ * If we completed, just got to next step
+ */
+
+ if (ctx->stateflags & KRBHST_COMPLETED) {
+ action = KRB5_SENDTO_CONTINUE;
+ break;
+ }
+
+ /*
+ * Pull out next host, if there is no more, close the
+ * handle and mark as completed.
+ *
+ * Collect time spent in krbhst (dns, plugin, etc)
+ */
+
+
+ gettimeofday(&nrstart, NULL);
+
+ ret = krb5_krbhst_next(context, handle, &hi);
+
+ gettimeofday(&nrstop, NULL);
+ timevalsub(&nrstop, &nrstart);
+ timevaladd(&ctx->stats.krbhst, &nrstop);
+
+ action = KRB5_SENDTO_CONTINUE;
+ if (ret == 0) {
+ _krb5_debug(context, 5, "submitting new requests to new host");
+ if (submit_request(context, ctx, hi) != 0)
+ action = KRB5_SENDTO_TIMEOUT;
+ } else {
+ _krb5_debug(context, 5, "out of hosts, waiting for replies");
+ ctx->stateflags |= KRBHST_COMPLETED;
+ }
+
+ break;
+ case KRB5_SENDTO_CONTINUE:
+
+ ret = wait_response(context, &action, ctx);
+ if (ret)
+ goto out;
+
+ break;
+ case KRB5_SENDTO_RESET:
+ /* start over */
+ _krb5_debug(context, 5,
+ "krb5_sendto trying over again (reset): %d",
+ numreset);
+ reset_context(context, ctx);
+ if (handle) {
+ krb5_krbhst_free(context, handle);
+ handle = NULL;
+ }
+ numreset++;
+ if (numreset >= 3)
+ action = KRB5_SENDTO_FAILED;
+ else
+ action = KRB5_SENDTO_KRBHST;
+
+ break;
+ case KRB5_SENDTO_FILTER:
+ /* default to next state, the filter function might modify this */
+ action = KRB5_SENDTO_DONE;
+
+ if (ctx->func) {
+ ret = (*ctx->func)(context, ctx, ctx->data,
+ &ctx->response, &action);
+ if (ret)
+ goto out;
+
+ /*
+ * If we are not done, ask to continue/reset
+ */
+ switch (action) {
+ case KRB5_SENDTO_DONE:
+ break;
+ case KRB5_SENDTO_RESET:
+ case KRB5_SENDTO_CONTINUE:
+ /* free response to clear it out so we don't loop */
+ krb5_data_free(&ctx->response);
+ break;
+ default:
+ ret = KRB5_KDC_UNREACH;
+ krb5_set_error_message(context, ret,
+ "sendto filter funcation return unsupported state: %d", (int)action);
+ goto out;
+ }
+ }
+ break;
+ case KRB5_SENDTO_FAILED:
+ ret = KRB5_KDC_UNREACH;
+ goto out;
+ case KRB5_SENDTO_DONE:
+ ret = 0;
+ goto out;
+ default:
+ heim_abort("invalid krb5_sendto_context state");
+ }
+ }
+
+out:
+ gettimeofday(&stop_time, NULL);
+ timevalsub(&stop_time, &ctx->stats.start_time);
+ if (ret == 0 && ctx->response.length) {
+ *receive = ctx->response;
+ krb5_data_zero(&ctx->response);
+ } else {
+ krb5_data_free(&ctx->response);
+ krb5_clear_error_message (context);
+ ret = KRB5_KDC_UNREACH;
+ krb5_set_error_message(context, ret,
+ N_("unable to reach any KDC in realm %s", ""),
+ realm);
+ }
+
+ _krb5_debug(context, 1,
+ "%s %s done: %d hosts: %lu packets: %lu"
+ " wc: %lld.%06lu nr: %lld.%06lu kh: %lld.%06lu tid: %08x",
+ __func__, realm, ret,
+ ctx->stats.num_hosts, ctx->stats.sent_packets,
+ (long long)stop_time.tv_sec,
+ (unsigned long)stop_time.tv_usec,
+ (long long)ctx->stats.name_resolution.tv_sec,
+ (unsigned long)ctx->stats.name_resolution.tv_usec,
+ (long long)ctx->stats.krbhst.tv_sec,
+ (unsigned long)ctx->stats.krbhst.tv_usec, ctx->stid);
+
+
+ if (freectx)
+ krb5_sendto_ctx_free(context, ctx);
+ else
+ reset_context(context, ctx);
+
+ if (handle)
+ krb5_krbhst_free(context, handle);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/send_to_kdc_plugin.h b/third_party/heimdal/lib/krb5/send_to_kdc_plugin.h
new file mode 100644
index 0000000..30d6892
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/send_to_kdc_plugin.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIMDAL_KRB5_SEND_TO_KDC_PLUGIN_H
+#define HEIMDAL_KRB5_SEND_TO_KDC_PLUGIN_H 1
+
+#include <krb5.h>
+#include <heimbase-svc.h>
+
+#define KRB5_PLUGIN_SEND_TO_KDC "send_to_kdc"
+
+#define KRB5_PLUGIN_SEND_TO_KDC_VERSION_0 0
+#define KRB5_PLUGIN_SEND_TO_KDC_VERSION_2 2
+#define KRB5_PLUGIN_SEND_TO_KDC_VERSION KRB5_PLUGIN_SEND_TO_KDC_VERSION_2
+
+typedef krb5_error_code
+(KRB5_CALLCONV *krb5plugin_send_to_kdc_func)(krb5_context,
+ void *,
+ krb5_krbhst_info *,
+ time_t timeout,
+ const krb5_data *,
+ krb5_data *);
+typedef krb5_error_code
+(KRB5_CALLCONV *krb5plugin_send_to_realm_func)(krb5_context,
+ void *,
+ krb5_const_realm,
+ time_t timeout,
+ const krb5_data *,
+ krb5_data *);
+
+
+typedef struct krb5plugin_send_to_kdc_ftable {
+ HEIM_PLUGIN_FTABLE_COMMON_ELEMENTS(krb5_context);
+ krb5plugin_send_to_kdc_func send_to_kdc;
+ krb5plugin_send_to_realm_func send_to_realm; /* added in version 2 */
+} krb5plugin_send_to_kdc_ftable;
+
+#endif /* HEIMDAL_KRB5_SEND_TO_KDC_PLUGIN_H */
diff --git a/third_party/heimdal/lib/krb5/sendauth.c b/third_party/heimdal/lib/krb5/sendauth.c
new file mode 100644
index 0000000..5011c26
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/sendauth.c
@@ -0,0 +1,255 @@
+/*
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/*
+ * The format seems to be:
+ * client -> server
+ *
+ * 4 bytes - length
+ * KRB5_SENDAUTH_V1.0 (including zero)
+ * 4 bytes - length
+ * protocol string (with terminating zero)
+ *
+ * server -> client
+ * 1 byte - (0 = OK, else some kind of error)
+ *
+ * client -> server
+ * 4 bytes - length
+ * AP-REQ
+ *
+ * server -> client
+ * 4 bytes - length (0 = OK, else length of error)
+ * (error)
+ *
+ * if(mutual) {
+ * server -> client
+ * 4 bytes - length
+ * AP-REP
+ * }
+ */
+
+/**
+ * Perform the client side of the sendauth protocol.
+ *
+ * @param context Kerberos 5 context.
+ * @param auth_context Authentication context of the peer.
+ * @param p_fd Socket associated to the connection.
+ * @param appl_version Server-specific string.
+ * @param client Client principal. If NULL, use the credentials in \a ccache.
+ * @param server Server principal.
+ * @param ap_req_options Options for the AP_REQ message. See the AP_OPTS_* defines in krb5.h.
+ * @param in_data FIXME
+ * @param in_creds FIXME
+ * @param ccache Credentials cache. If NULL, use the default credentials cache.
+ * @param ret_error If not NULL, will be set to the error reported by server, if any.
+ * Must be deallocated with krb5_free_error_contents().
+ * @param rep_result If not NULL, will be set to the EncApRepPart of the AP_REP message.
+ * Must be deallocated with krb5_free_ap_rep_enc_part().
+ * @param out_creds FIXME If not NULL, will be set to FIXME. Must be deallocated with
+ * krb5_free_creds().
+ *
+ * @return 0 to indicate success. Otherwise a Kerberos error code is
+ * returned, see krb5_get_error_message().
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_sendauth(krb5_context context,
+ krb5_auth_context *auth_context,
+ krb5_pointer p_fd,
+ const char *appl_version,
+ krb5_principal client,
+ krb5_principal server,
+ krb5_flags ap_req_options,
+ krb5_data *in_data,
+ krb5_creds *in_creds,
+ krb5_ccache ccache,
+ krb5_error **ret_error,
+ krb5_ap_rep_enc_part **rep_result,
+ krb5_creds **out_creds)
+{
+ krb5_error_code ret;
+ uint32_t len, net_len;
+ const char *version = KRB5_SENDAUTH_VERSION;
+ u_char repl;
+ krb5_data ap_req, error_data;
+ krb5_creds this_cred;
+ krb5_principal this_client = NULL;
+ krb5_creds *creds;
+ ssize_t sret;
+ krb5_boolean my_ccache = FALSE;
+
+ len = strlen(version) + 1;
+ net_len = htonl(len);
+ if (krb5_net_write (context, p_fd, &net_len, 4) != 4
+ || krb5_net_write (context, p_fd, version, len) != len) {
+ ret = errno;
+ krb5_set_error_message (context, ret, "write: %s", strerror(ret));
+ return ret;
+ }
+
+ len = strlen(appl_version) + 1;
+ net_len = htonl(len);
+ if (krb5_net_write (context, p_fd, &net_len, 4) != 4
+ || krb5_net_write (context, p_fd, appl_version, len) != len) {
+ ret = errno;
+ krb5_set_error_message (context, ret, "write: %s", strerror(ret));
+ return ret;
+ }
+
+ sret = krb5_net_read (context, p_fd, &repl, sizeof(repl));
+ if (sret < 0) {
+ ret = errno;
+ krb5_set_error_message (context, ret, "read: %s", strerror(ret));
+ return ret;
+ } else if (sret != sizeof(repl)) {
+ krb5_clear_error_message (context);
+ return KRB5_SENDAUTH_BADRESPONSE;
+ }
+
+ if (repl != 0) {
+ krb5_clear_error_message (context);
+ return KRB5_SENDAUTH_REJECTED;
+ }
+
+ if (in_creds == NULL) {
+ if (ccache == NULL) {
+ ret = krb5_cc_default (context, &ccache);
+ if (ret)
+ return ret;
+ my_ccache = TRUE;
+ }
+
+ if (client == NULL) {
+ ret = krb5_cc_get_principal (context, ccache, &this_client);
+ if (ret) {
+ if(my_ccache)
+ krb5_cc_close(context, ccache);
+ return ret;
+ }
+ client = this_client;
+ }
+ memset(&this_cred, 0, sizeof(this_cred));
+ this_cred.client = client;
+ this_cred.server = server;
+ this_cred.times.endtime = 0;
+ this_cred.ticket.length = 0;
+ in_creds = &this_cred;
+ }
+ if (in_creds->ticket.length == 0) {
+ ret = krb5_get_credentials (context, 0, ccache, in_creds, &creds);
+ if (ret) {
+ if(my_ccache)
+ krb5_cc_close(context, ccache);
+ return ret;
+ }
+ } else {
+ creds = in_creds;
+ }
+ if(my_ccache)
+ krb5_cc_close(context, ccache);
+ ret = krb5_mk_req_extended (context,
+ auth_context,
+ ap_req_options,
+ in_data,
+ creds,
+ &ap_req);
+
+ if (out_creds)
+ *out_creds = creds;
+ else
+ krb5_free_creds(context, creds);
+ if(this_client)
+ krb5_free_principal(context, this_client);
+
+ if (ret)
+ return ret;
+
+ ret = krb5_write_message (context,
+ p_fd,
+ &ap_req);
+ if (ret)
+ return ret;
+
+ krb5_data_free (&ap_req);
+
+ ret = krb5_read_message (context, p_fd, &error_data);
+ if (ret)
+ return ret;
+
+ if (error_data.length != 0) {
+ KRB_ERROR error;
+
+ ret = krb5_rd_error (context, &error_data, &error);
+ krb5_data_free (&error_data);
+ if (ret == 0) {
+ ret = krb5_error_from_rd_error(context, &error, NULL);
+ if (ret_error != NULL) {
+ *ret_error = malloc (sizeof(krb5_error));
+ if (*ret_error == NULL) {
+ krb5_free_error_contents (context, &error);
+ } else {
+ **ret_error = error;
+ }
+ } else {
+ krb5_free_error_contents (context, &error);
+ }
+ return ret;
+ } else {
+ krb5_clear_error_message(context);
+ return ret;
+ }
+ } else
+ krb5_data_free (&error_data);
+
+ if (ap_req_options & AP_OPTS_MUTUAL_REQUIRED) {
+ krb5_data ap_rep;
+ krb5_ap_rep_enc_part *ignore = NULL;
+
+ krb5_data_zero (&ap_rep);
+ ret = krb5_read_message (context,
+ p_fd,
+ &ap_rep);
+ if (ret)
+ return ret;
+
+ ret = krb5_rd_rep (context, *auth_context, &ap_rep,
+ rep_result ? rep_result : &ignore);
+ krb5_data_free (&ap_rep);
+ if (ret)
+ return ret;
+ if (rep_result == NULL)
+ krb5_free_ap_rep_enc_part (context, ignore);
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/set_default_realm.c b/third_party/heimdal/lib/krb5/set_default_realm.c
new file mode 100644
index 0000000..b3450c4
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/set_default_realm.c
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/*
+ * Convert the simple string `s' into a NULL-terminated and freshly allocated
+ * list in `list'. Return an error code.
+ */
+
+static krb5_error_code
+string_to_list (krb5_context context, const char *s, krb5_realm **list)
+{
+
+ *list = malloc (2 * sizeof(**list));
+ if (*list == NULL)
+ return krb5_enomem(context);
+ (*list)[0] = strdup (s);
+ if ((*list)[0] == NULL) {
+ free (*list);
+ return krb5_enomem(context);
+ }
+ (*list)[1] = NULL;
+ return 0;
+}
+
+/*
+ * Set the knowledge of the default realm(s) in `context'.
+ * If realm != NULL, that's the new default realm.
+ * Otherwise, the realm(s) are figured out from configuration or DNS.
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_default_realm(krb5_context context,
+ const char *realm)
+{
+ krb5_error_code ret = 0;
+ krb5_realm *realms = NULL;
+
+ if (realm == NULL) {
+ realms = krb5_config_get_strings (context, NULL,
+ "libdefaults",
+ "default_realm",
+ NULL);
+ if (realms == NULL)
+ ret = krb5_get_host_realm(context, NULL, &realms);
+ } else {
+ ret = string_to_list (context, realm, &realms);
+ }
+ if (ret)
+ return ret;
+ krb5_free_host_realm (context, context->default_realms);
+ context->default_realms = realms;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/sock_principal.c b/third_party/heimdal/lib/krb5/sock_principal.c
new file mode 100644
index 0000000..a43546d
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/sock_principal.c
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_sock_to_principal (krb5_context context,
+ int sock,
+ const char *sname,
+ int32_t type,
+ krb5_principal *ret_princ)
+{
+ krb5_error_code ret;
+ struct sockaddr_storage __ss;
+ struct sockaddr *sa = (struct sockaddr *)&__ss;
+ socklen_t salen = sizeof(__ss);
+ char hostname[NI_MAXHOST];
+
+ if (getsockname (sock, sa, &salen) < 0) {
+ ret = errno;
+ krb5_set_error_message (context, ret, "getsockname: %s", strerror(ret));
+ return ret;
+ }
+ ret = getnameinfo (sa, salen, hostname, sizeof(hostname), NULL, 0, 0);
+ if (ret) {
+ int save_errno = errno;
+ krb5_error_code ret2 = krb5_eai_to_heim_errno(ret, save_errno);
+ krb5_set_error_message (context, ret2, "getnameinfo: %s", gai_strerror(ret));
+ return ret2;
+ }
+
+ ret = krb5_sname_to_principal (context,
+ hostname,
+ sname,
+ type,
+ ret_princ);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/sp800-108-kdf.c b/third_party/heimdal/lib/krb5/sp800-108-kdf.c
new file mode 100755
index 0000000..4a12067
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/sp800-108-kdf.c
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2015, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "krb5_locl.h"
+
+/*
+ * SP800-108 KDF
+ */
+
+/**
+ * As described in SP800-108 5.1 (for HMAC)
+ *
+ * @param context Kerberos 5 context
+ * @param kdf_K1 Base key material.
+ * @param kdf_label A string that identifies the purpose for the derived key.
+ * @param kdf_context A binary string containing parties, nonce, etc.
+ * @param md Message digest function to use for PRF.
+ * @param kdf_K0 Derived key data.
+ *
+ * @return Return an error code for an failure or 0 on success.
+ * @ingroup krb5_crypto
+ */
+krb5_error_code
+_krb5_SP800_108_HMAC_KDF(krb5_context context,
+ const krb5_data *kdf_K1,
+ const krb5_data *kdf_label,
+ const krb5_data *kdf_context,
+ const EVP_MD *md,
+ krb5_data *kdf_K0)
+{
+ HMAC_CTX c;
+ unsigned char *p = kdf_K0->data;
+ size_t i, n, left = kdf_K0->length;
+ unsigned char hmac[EVP_MAX_MD_SIZE];
+ unsigned int h = EVP_MD_size(md);
+ const size_t L = kdf_K0->length;
+
+ heim_assert(md != NULL, "SP800-108 KDF internal error");
+
+ HMAC_CTX_init(&c);
+
+ n = L / h;
+
+ for (i = 0; i <= n; i++) {
+ unsigned char tmp[4];
+ size_t len;
+
+ if (HMAC_Init_ex(&c, kdf_K1->data, kdf_K1->length, md, NULL) == 0) {
+ HMAC_CTX_cleanup(&c);
+ return krb5_enomem(context);
+ }
+
+ _krb5_put_int(tmp, i + 1, 4);
+ HMAC_Update(&c, tmp, 4);
+ HMAC_Update(&c, kdf_label->data, kdf_label->length);
+ HMAC_Update(&c, (unsigned char *)"", 1);
+ if (kdf_context)
+ HMAC_Update(&c, kdf_context->data, kdf_context->length);
+ _krb5_put_int(tmp, L * 8, 4);
+ HMAC_Update(&c, tmp, 4);
+
+ HMAC_Final(&c, hmac, &h);
+ len = h > left ? left : h;
+ memcpy(p, hmac, len);
+ p += len;
+ left -= len;
+ }
+
+ HMAC_CTX_cleanup(&c);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/store-int.c b/third_party/heimdal/lib/krb5/store-int.c
new file mode 100644
index 0000000..6fe7eb3
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/store-int.c
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 1997-2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
+_krb5_put_int(void *buffer, uint64_t value, size_t size)
+{
+ unsigned char *p = buffer;
+ int i;
+ for (i = size - 1; i >= 0; i--) {
+ p[i] = value & 0xff;
+ value >>= 8;
+ }
+ return size;
+}
+
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
+_krb5_get_int64(void *buffer, uint64_t *value, size_t size)
+{
+ unsigned char *p = buffer;
+ uint64_t v = 0;
+ size_t i;
+ for (i = 0; i < size; i++)
+ v = (v << 8) + p[i];
+ *value = v;
+ return size;
+}
+
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
+_krb5_get_int(void *buffer, unsigned long *value, size_t size)
+{
+ uint64_t v64;
+ krb5_ssize_t bytes = _krb5_get_int64(buffer, &v64, size);
+ *value = v64;
+ return bytes;
+}
diff --git a/third_party/heimdal/lib/krb5/store-int.h b/third_party/heimdal/lib/krb5/store-int.h
new file mode 100644
index 0000000..2762d96
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/store-int.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef __store_int_h__
+#define __store_int_h__
+
+struct krb5_storage_data {
+ void *data;
+ ssize_t (*fetch)(struct krb5_storage_data*, void*, size_t);
+ ssize_t (*store)(struct krb5_storage_data*, const void*, size_t);
+ off_t (*seek)(struct krb5_storage_data*, off_t, int);
+ int (*trunc)(struct krb5_storage_data*, off_t);
+ int (*fsync)(struct krb5_storage_data*);
+ void (*free)(struct krb5_storage_data*);
+ krb5_flags flags;
+ int eof_code;
+ size_t max_alloc;
+};
+
+#endif /* __store_int_h__ */
diff --git a/third_party/heimdal/lib/krb5/store-test.c b/third_party/heimdal/lib/krb5/store-test.c
new file mode 100644
index 0000000..3d0f9e0
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/store-test.c
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+
+static void
+print_data(unsigned char *data, size_t len)
+{
+ int i;
+ for(i = 0; i < len; i++) {
+ if(i > 0 && (i % 16) == 0)
+ printf("\n ");
+ printf("%02x ", data[i]);
+ }
+ printf("\n");
+}
+
+static int
+compare(const char *name, krb5_storage *sp, void *expected, size_t len)
+{
+ int ret = 0;
+ krb5_data data;
+ if (krb5_storage_to_data(sp, &data))
+ errx(1, "krb5_storage_to_data failed");
+ krb5_storage_free(sp);
+ if(data.length != len || memcmp(data.data, expected, len) != 0) {
+ printf("%s mismatch\n", name);
+ printf(" Expected: ");
+ print_data(expected, len);
+ printf(" Actual: ");
+ print_data(data.data, data.length);
+ ret++;
+ }
+ krb5_data_free(&data);
+ return ret;
+}
+
+int
+main(int argc, char **argv)
+{
+ int nerr = 0;
+ krb5_storage *sp;
+ krb5_context context;
+ krb5_principal principal;
+
+
+ krb5_init_context(&context);
+
+ sp = krb5_storage_emem();
+ krb5_store_int32(sp, 0x01020304);
+ nerr += compare("Integer", sp, "\x1\x2\x3\x4", 4);
+
+ sp = krb5_storage_emem();
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_LE);
+ krb5_store_int32(sp, 0x01020304);
+ nerr += compare("Integer (LE)", sp, "\x4\x3\x2\x1", 4);
+
+ sp = krb5_storage_emem();
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_BE);
+ krb5_store_int32(sp, 0x01020304);
+ nerr += compare("Integer (BE)", sp, "\x1\x2\x3\x4", 4);
+
+ sp = krb5_storage_emem();
+ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_HOST);
+ krb5_store_int32(sp, 0x01020304);
+ {
+ int test = 1;
+ void *data;
+ if(*(char*)&test)
+ data = "\x4\x3\x2\x1";
+ else
+ data = "\x1\x2\x3\x4";
+ nerr += compare("Integer (host)", sp, data, 4);
+ }
+
+ sp = krb5_storage_emem();
+ krb5_make_principal(context, &principal, "TEST", "foobar", NULL);
+ krb5_store_principal(sp, principal);
+ krb5_free_principal(context, principal);
+ nerr += compare("Principal", sp, "\x0\x0\x0\x1"
+ "\x0\x0\x0\x1"
+ "\x0\x0\x0\x4TEST"
+ "\x0\x0\x0\x6""foobar", 26);
+
+ krb5_free_context(context);
+
+ return nerr ? 1 : 0;
+}
diff --git a/third_party/heimdal/lib/krb5/store.c b/third_party/heimdal/lib/krb5/store.c
new file mode 100644
index 0000000..79f8e3a
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/store.c
@@ -0,0 +1,2041 @@
+/*
+ * Copyright (c) 1997-2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include "store-int.h"
+
+#define BYTEORDER_IS(SP, V) (((SP)->flags & KRB5_STORAGE_BYTEORDER_MASK) == (V))
+#define BYTEORDER_IS_LE(SP) BYTEORDER_IS((SP), KRB5_STORAGE_BYTEORDER_LE)
+#define BYTEORDER_IS_BE(SP) BYTEORDER_IS((SP), KRB5_STORAGE_BYTEORDER_BE)
+#define BYTEORDER_IS_HOST(SP) (BYTEORDER_IS((SP), KRB5_STORAGE_BYTEORDER_HOST) || \
+ krb5_storage_is_flags((SP), KRB5_STORAGE_HOST_BYTEORDER))
+#define BYTEORDER_IS_PACKED(SP) BYTEORDER_IS((SP), KRB5_STORAGE_BYTEORDER_PACKED)
+
+/**
+ * Add the flags on a storage buffer by or-ing in the flags to the buffer.
+ *
+ * @param sp the storage buffer to set the flags on
+ * @param flags the flags to set
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_storage_set_flags(krb5_storage *sp, krb5_flags flags)
+{
+ sp->flags |= flags;
+}
+
+/**
+ * Clear the flags on a storage buffer
+ *
+ * @param sp the storage buffer to clear the flags on
+ * @param flags the flags to clear
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_storage_clear_flags(krb5_storage *sp, krb5_flags flags)
+{
+ sp->flags &= ~flags;
+}
+
+/**
+ * Return true or false depending on if the storage flags is set or
+ * not. NB testing for the flag 0 always return true.
+ *
+ * @param sp the storage buffer to check flags on
+ * @param flags The flags to test for
+ *
+ * @return true if all the flags are set, false if not.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_storage_is_flags(krb5_storage *sp, krb5_flags flags)
+{
+ return (sp->flags & flags) == flags;
+}
+
+/**
+ * Set the new byte order of the storage buffer.
+ *
+ * @param sp the storage buffer to set the byte order for.
+ * @param byteorder the new byte order.
+ *
+ * The byte order are: KRB5_STORAGE_BYTEORDER_BE,
+ * KRB5_STORAGE_BYTEORDER_LE and KRB5_STORAGE_BYTEORDER_HOST.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_storage_set_byteorder(krb5_storage *sp, krb5_flags byteorder)
+{
+ sp->flags &= ~KRB5_STORAGE_BYTEORDER_MASK;
+ sp->flags |= byteorder;
+}
+
+/**
+ * Return the current byteorder for the buffer. See krb5_storage_set_byteorder() for the list or byte order contants.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_flags KRB5_LIB_CALL
+krb5_storage_get_byteorder(krb5_storage *sp)
+{
+ return sp->flags & KRB5_STORAGE_BYTEORDER_MASK;
+}
+
+/**
+ * Set the max alloc value
+ *
+ * @param sp the storage buffer set the max allow for
+ * @param size maximum size to allocate, use 0 to remove limit
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_storage_set_max_alloc(krb5_storage *sp, size_t size)
+{
+ sp->max_alloc = size;
+}
+
+/* don't allocate unresonable amount of memory */
+static krb5_error_code
+size_too_large(krb5_storage *sp, size_t size)
+{
+ if (sp->max_alloc && sp->max_alloc < size)
+ return HEIM_ERR_TOO_BIG;
+ return 0;
+}
+
+static krb5_error_code
+size_too_large_num(krb5_storage *sp, size_t count, size_t size)
+{
+ if (sp->max_alloc == 0 || size == 0)
+ return 0;
+ size = sp->max_alloc / size;
+ if (size < count)
+ return HEIM_ERR_TOO_BIG;
+ return 0;
+}
+
+/**
+ * Seek to a new offset.
+ *
+ * @param sp the storage buffer to seek in.
+ * @param offset the offset to seek
+ * @param whence relateive searching, SEEK_CUR from the current
+ * position, SEEK_END from the end, SEEK_SET absolute from the start.
+ *
+ * @return The new current offset
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION off_t KRB5_LIB_CALL
+krb5_storage_seek(krb5_storage *sp, off_t offset, int whence)
+{
+ return (*sp->seek)(sp, offset, whence);
+}
+
+/**
+ * Truncate the storage buffer in sp to offset.
+ *
+ * @param sp the storage buffer to truncate.
+ * @param offset the offset to truncate too.
+ *
+ * @return An Kerberos 5 error code.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_storage_truncate(krb5_storage *sp, off_t offset)
+{
+ return (*sp->trunc)(sp, offset);
+}
+
+/**
+ * Sync the storage buffer to its backing store. If there is no
+ * backing store this function will return success.
+ *
+ * @param sp the storage buffer to sync
+ *
+ * @return A Kerberos 5 error code
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_storage_fsync(krb5_storage *sp)
+{
+ if (sp->fsync != NULL)
+ return sp->fsync(sp);
+ return 0;
+}
+
+/**
+ * Read to the storage buffer.
+ *
+ * @param sp the storage buffer to read from
+ * @param buf the buffer to store the data in
+ * @param len the length to read
+ *
+ * @return The length of data read (can be shorter then len), or negative on error.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
+krb5_storage_read(krb5_storage *sp, void *buf, size_t len)
+{
+ return sp->fetch(sp, buf, len);
+}
+
+/**
+ * Write to the storage buffer.
+ *
+ * @param sp the storage buffer to write to
+ * @param buf the buffer to write to the storage buffer
+ * @param len the length to write
+ *
+ * @return The length of data written (can be shorter then len), or negative on error.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
+krb5_storage_write(krb5_storage *sp, const void *buf, size_t len)
+{
+ return sp->store(sp, buf, len);
+}
+
+/**
+ * Set the return code that will be used when end of storage is reached.
+ *
+ * @param sp the storage
+ * @param code the error code to return on end of storage
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_storage_set_eof_code(krb5_storage *sp, int code)
+{
+ sp->eof_code = code;
+}
+
+/**
+ * Get the return code that will be used when end of storage is reached.
+ *
+ * @param sp the storage
+ *
+ * @return storage error code
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_storage_get_eof_code(krb5_storage *sp)
+{
+ return sp->eof_code;
+}
+
+/**
+ * Free a krb5 storage.
+ *
+ * @param sp the storage to free.
+ *
+ * @return An Kerberos 5 error code.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_storage_free(krb5_storage *sp)
+{
+ if (sp == NULL)
+ return 0;
+ if(sp->free)
+ (*sp->free)(sp);
+ free(sp->data);
+ free(sp);
+ return 0;
+}
+
+/**
+ * Copy the contnent of storage
+ *
+ * @param sp the storage to copy to a data
+ * @param data the copied data, free with krb5_data_free()
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_storage_to_data(krb5_storage *sp, krb5_data *data)
+{
+ off_t pos, size;
+ krb5_error_code ret;
+
+ pos = sp->seek(sp, 0, SEEK_CUR);
+ if (pos < 0)
+ return HEIM_ERR_NOT_SEEKABLE;
+ size = sp->seek(sp, 0, SEEK_END);
+ ret = size_too_large(sp, size);
+ if (ret)
+ return ret;
+ ret = krb5_data_alloc(data, size);
+ if (ret) {
+ sp->seek(sp, pos, SEEK_SET);
+ return ret;
+ }
+ if (size) {
+ sp->seek(sp, 0, SEEK_SET);
+ sp->fetch(sp, data->data, data->length);
+ sp->seek(sp, pos, SEEK_SET);
+ }
+ return 0;
+}
+
+static size_t
+pack_int(uint8_t *p, uint64_t val)
+{
+ size_t l = 0;
+
+ if (val < 128) {
+ *p = val;
+ } else {
+ while (val > 0) {
+ *p-- = val % 256;
+ val /= 256;
+ l++;
+ }
+ *p = 0x80 | l;
+ }
+ return l + 1;
+}
+
+static size_t
+unpack_int_length(uint8_t *v)
+{
+ size_t size;
+
+ if (*v < 128)
+ size = 0;
+ else
+ size = *v & 0x7f;
+
+ return size + 1;
+}
+
+static int
+unpack_int(uint8_t *p, size_t len, uint64_t *val, size_t *size)
+{
+ size_t v;
+
+ if (len == 0)
+ return EINVAL;
+ --len;
+ v = *p++;
+ if (v < 128) {
+ *val = v;
+ *size = 1;
+ } else {
+ int e;
+ size_t l;
+ uint64_t tmp;
+
+ if (v == 0x80) {
+ *size = 1;
+ return EINVAL;
+ }
+ v &= 0x7F;
+ if (len < v)
+ return ERANGE;
+ e = der_get_unsigned64(p, v, &tmp, &l);
+ if (e)
+ return ERANGE;
+ *val = tmp;
+ *size = l + 1;
+ }
+ return 0;
+}
+
+static krb5_error_code
+krb5_store_int(krb5_storage *sp,
+ int64_t value,
+ size_t len)
+{
+ int ret;
+ uint8_t v[9], *p = v;
+
+ if (len > sizeof(value))
+ return EINVAL;
+
+ if (BYTEORDER_IS_PACKED(sp)) {
+ uint64_t mask = ~0ULL >> (64 - len * 8);
+ value &= mask;
+ p += sizeof(v) - 1;
+ len = pack_int(p, value);
+ p = v + sizeof(v) - len;
+ } else
+ _krb5_put_int(v, value, len);
+ ret = sp->store(sp, p, len);
+ if (ret < 0)
+ return errno;
+ if ((size_t)ret != len)
+ return sp->eof_code;
+ return 0;
+}
+
+/**
+ * Store a int32 to storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value to store
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_int32(krb5_storage *sp,
+ int32_t value)
+{
+ if(BYTEORDER_IS_HOST(sp))
+ value = htonl(value);
+ else if(BYTEORDER_IS_LE(sp))
+ value = bswap32(value);
+ return krb5_store_int(sp, value, 4);
+}
+
+/**
+ * Store a int64 to storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value to store
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_int64(krb5_storage *sp,
+ int64_t value)
+{
+ if (BYTEORDER_IS_HOST(sp))
+#ifdef WORDS_BIGENDIAN
+ ;
+#else
+ value = bswap64(value); /* There's no ntohll() */
+#endif
+ else if (BYTEORDER_IS_LE(sp))
+ value = bswap64(value);
+ return krb5_store_int(sp, value, 8);
+}
+
+/**
+ * Store a uint32 to storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value to store
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_uint32(krb5_storage *sp,
+ uint32_t value)
+{
+ return krb5_store_int32(sp, (int32_t)value);
+}
+
+/**
+ * Store a uint64 to storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value to store
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_uint64(krb5_storage *sp,
+ uint64_t value)
+{
+ return krb5_store_int64(sp, (int64_t)value);
+}
+
+static krb5_error_code
+krb5_ret_int(krb5_storage *sp,
+ int64_t *value,
+ size_t len)
+{
+ int ret;
+ unsigned char v[9];
+ uint64_t w = 0;
+ *value = 0; /* quiets warnings */
+ if (BYTEORDER_IS_PACKED(sp)) {
+ ret = sp->fetch(sp, v, 1);
+ if (ret < 0)
+ return errno;
+
+ len = unpack_int_length(v);
+ if (len < 1)
+ return ERANGE;
+ else if (len > 1) {
+ ret = sp->fetch(sp, v + 1, len - 1);
+ if (ret < 0)
+ return errno;
+ }
+ ret = unpack_int(v, len, &w, &len);
+ if (ret)
+ return ret;
+ *value = w;
+ return 0;
+ }
+ ret = sp->fetch(sp, v, len);
+ if (ret < 0)
+ return errno;
+ if ((size_t)ret != len)
+ return sp->eof_code;
+ _krb5_get_int64(v, &w, len);
+ *value = w;
+ return 0;
+}
+
+/**
+ * Read a int64 from storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value read from the buffer
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_int64(krb5_storage *sp,
+ int64_t *value)
+{
+ krb5_error_code ret = krb5_ret_int(sp, value, 8);
+ if(ret)
+ return ret;
+ if(BYTEORDER_IS_HOST(sp))
+#ifdef WORDS_BIGENDIAN
+ ;
+#else
+ *value = bswap64(*value); /* There's no ntohll() */
+#endif
+ else if(BYTEORDER_IS_LE(sp))
+ *value = bswap64(*value);
+ return 0;
+}
+
+/**
+ * Read a uint64 from storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value read from the buffer
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_uint64(krb5_storage *sp,
+ uint64_t *value)
+{
+ krb5_error_code ret;
+ int64_t v;
+
+ ret = krb5_ret_int64(sp, &v);
+ if (ret == 0)
+ *value = (uint64_t)v;
+
+ return ret;
+}
+
+/**
+ * Read a int32 from storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value read from the buffer
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_int32(krb5_storage *sp,
+ int32_t *value)
+{
+ int64_t v;
+
+ krb5_error_code ret = krb5_ret_int(sp, &v, 4);
+ if (ret)
+ return ret;
+ *value = v;
+ if (BYTEORDER_IS_HOST(sp))
+ *value = htonl(*value);
+ else if (BYTEORDER_IS_LE(sp))
+ *value = bswap32(*value);
+ return 0;
+}
+
+/**
+ * Read a uint32 from storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value read from the buffer
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_uint32(krb5_storage *sp, uint32_t *value)
+{
+ krb5_error_code ret;
+ int32_t v;
+
+ ret = krb5_ret_int32(sp, &v);
+ if (ret == 0)
+ *value = (uint32_t)v;
+
+ return ret;
+}
+
+/**
+ * Store a int16 to storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value to store
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_int16(krb5_storage *sp,
+ int16_t value)
+{
+ if(BYTEORDER_IS_HOST(sp))
+ value = htons(value);
+ else if(BYTEORDER_IS_LE(sp))
+ value = bswap16(value);
+ return krb5_store_int(sp, value, 2);
+}
+
+/**
+ * Store a uint16 to storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value to store
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_uint16(krb5_storage *sp,
+ uint16_t value)
+{
+ return krb5_store_int16(sp, (int16_t)value);
+}
+
+/**
+ * Read a int16 from storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value read from the buffer
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_int16(krb5_storage *sp,
+ int16_t *value)
+{
+ int64_t v;
+ int ret;
+ ret = krb5_ret_int(sp, &v, 2);
+ if(ret)
+ return ret;
+ *value = v;
+ if(BYTEORDER_IS_HOST(sp))
+ *value = htons(*value);
+ else if(BYTEORDER_IS_LE(sp))
+ *value = bswap16(*value);
+ return 0;
+}
+
+/**
+ * Read a int16 from storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value read from the buffer
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_uint16(krb5_storage *sp,
+ uint16_t *value)
+{
+ krb5_error_code ret;
+ int16_t v;
+
+ ret = krb5_ret_int16(sp, &v);
+ if (ret == 0)
+ *value = (uint16_t)v;
+
+ return ret;
+}
+
+/**
+ * Store a int8 to storage.
+ *
+ * @param sp the storage to write too
+ * @param value the value to store
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_int8(krb5_storage *sp,
+ int8_t value)
+{
+ int ret;
+
+ ret = sp->store(sp, &value, sizeof(value));
+ if (ret != sizeof(value))
+ return (ret<0)?errno:sp->eof_code;
+ return 0;
+}
+
+/**
+ * Store a uint8 to storage.
+ *
+ * @param sp the storage to write too
+ * @param value the value to store
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_uint8(krb5_storage *sp,
+ uint8_t value)
+{
+ return krb5_store_int8(sp, (int8_t)value);
+}
+
+/**
+ * Read a int8 from storage
+ *
+ * @param sp the storage to write too
+ * @param value the value read from the buffer
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_int8(krb5_storage *sp,
+ int8_t *value)
+{
+ int ret;
+
+ ret = sp->fetch(sp, value, sizeof(*value));
+ if (ret != sizeof(*value))
+ return (ret<0)?errno:sp->eof_code;
+ return 0;
+}
+
+/**
+ * Read a uint8 from storage
+ *
+ * @param sp the storage to write too
+ * @param value the value read from the buffer
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_uint8(krb5_storage *sp,
+ uint8_t *value)
+{
+ krb5_error_code ret;
+ int8_t v;
+
+ ret = krb5_ret_int8(sp, &v);
+ if (ret == 0)
+ *value = (uint8_t)v;
+
+ return ret;
+}
+
+/**
+ * Store a data to the storage. The data is stored with an int32 as
+ * lenght plus the data (not padded).
+ *
+ * @param sp the storage buffer to write to
+ * @param data the buffer to store.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_data(krb5_storage *sp,
+ krb5_data data)
+{
+ int ret;
+ ret = krb5_store_int32(sp, data.length);
+ if(ret < 0)
+ return ret;
+ ret = sp->store(sp, data.data, data.length);
+ if(ret < 0)
+ return errno;
+ if((size_t)ret != data.length)
+ return sp->eof_code;
+ return 0;
+}
+
+/**
+ * Store a data blob to the storage. The data is stored with an int32 as
+ * length plus the data (not padded). This function only differs from
+ * krb5_store_data() insofar as it takes a void * and a length as parameters.
+ *
+ * @param sp the storage buffer to write to
+ * @param s the string to store.
+ * @param len length of the string to be stored.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_datalen(krb5_storage *sp, const void *d, size_t len)
+{
+ krb5_data data;
+ data.length = len;
+ data.data = (void *)d;
+ return krb5_store_data(sp, data);
+}
+
+/**
+ * Store a data blob to the storage. The data is stored without a length.
+ *
+ * @param sp the storage buffer to write to
+ * @param s the string to store.
+ * @param len length of the string to be stored.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_bytes(krb5_storage *sp, const void *d, size_t len)
+{
+ ssize_t ssize;
+
+ ssize = krb5_storage_write(sp, d, len);
+ if (ssize != len)
+ return ENOMEM;
+
+ return 0;
+}
+
+/**
+ * Parse a data from the storage.
+ *
+ * @param sp the storage buffer to read from
+ * @param data the parsed data
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_data(krb5_storage *sp,
+ krb5_data *data)
+{
+ int ret;
+ int32_t size;
+
+ ret = krb5_ret_int32(sp, &size);
+ if(ret)
+ return ret;
+ ret = size_too_large(sp, size);
+ if (ret)
+ return ret;
+ ret = krb5_data_alloc (data, size);
+ if (ret)
+ return ret;
+ if (size) {
+ ret = sp->fetch(sp, data->data, size);
+ if(ret != size) {
+ krb5_data_free(data);
+ return (ret < 0)? errno : sp->eof_code;
+ }
+ }
+ return 0;
+}
+
+/**
+ * Store a string to the buffer. The data is formated as an len:uint32
+ * plus the string itself (not padded).
+ *
+ * @param sp the storage buffer to write to
+ * @param s the string to store.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_string(krb5_storage *sp, const char *s)
+{
+ krb5_data data;
+
+ if (s == NULL)
+ return EINVAL;
+
+ data.length = strlen(s);
+ data.data = rk_UNCONST(s);
+ return krb5_store_data(sp, data);
+}
+
+/**
+ * Parse a string from the storage.
+ *
+ * @param sp the storage buffer to read from
+ * @param string the parsed string
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_string(krb5_storage *sp,
+ char **string)
+{
+ int ret;
+ krb5_data data;
+ ret = krb5_ret_data(sp, &data);
+ if(ret)
+ return ret;
+ *string = realloc(data.data, data.length + 1);
+ if(*string == NULL){
+ free(data.data);
+ return ENOMEM;
+ }
+ (*string)[data.length] = 0;
+ return 0;
+}
+
+/**
+ * Store a zero terminated string to the buffer. The data is stored
+ * one character at a time until a NUL is stored.
+ *
+ * @param sp the storage buffer to write to
+ * @param s the string to store.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_stringz(krb5_storage *sp, const char *s)
+{
+ size_t len;
+ ssize_t ret;
+
+ if (s == NULL)
+ return EINVAL;
+
+ len = strlen(s) + 1;
+ ret = sp->store(sp, s, len);
+ if(ret < 0)
+ return ret;
+ if((size_t)ret != len)
+ return sp->eof_code;
+ return 0;
+}
+
+/**
+ * Parse zero terminated string from the storage.
+ *
+ * @param sp the storage buffer to read from
+ * @param string the parsed string
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_stringz(krb5_storage *sp,
+ char **string)
+{
+ char c;
+ char *s = NULL;
+ size_t len = 0;
+ ssize_t ret;
+
+ while((ret = sp->fetch(sp, &c, 1)) == 1){
+ krb5_error_code eret;
+ char *tmp;
+
+ len++;
+ eret = size_too_large(sp, len);
+ if (eret) {
+ free(s);
+ return eret;
+ }
+ tmp = realloc (s, len);
+ if (tmp == NULL) {
+ free (s);
+ return ENOMEM;
+ }
+ s = tmp;
+ s[len - 1] = c;
+ if(c == 0)
+ break;
+ }
+ if(ret != 1){
+ free(s);
+ if(ret == 0)
+ return sp->eof_code;
+ return ret;
+ }
+ *string = s;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_stringnl(krb5_storage *sp, const char *s)
+{
+ size_t len;
+ ssize_t ret;
+
+ if (s == NULL)
+ return EINVAL;
+
+ len = strlen(s);
+ ret = sp->store(sp, s, len);
+ if(ret < 0)
+ return ret;
+ if((size_t)ret != len)
+ return sp->eof_code;
+ ret = sp->store(sp, "\n", 1);
+ if(ret != 1) {
+ if(ret < 0)
+ return ret;
+ else
+ return sp->eof_code;
+ }
+
+ return 0;
+
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_stringnl(krb5_storage *sp,
+ char **string)
+{
+ int expect_nl = 0;
+ char c;
+ char *s = NULL;
+ size_t len = 0;
+ ssize_t ret;
+
+ while((ret = sp->fetch(sp, &c, 1)) == 1){
+ krb5_error_code eret;
+ char *tmp;
+
+ if (c == '\r') {
+ expect_nl = 1;
+ continue;
+ }
+ if (expect_nl && c != '\n') {
+ free(s);
+ return KRB5_BADMSGTYPE;
+ }
+
+ len++;
+ eret = size_too_large(sp, len);
+ if (eret) {
+ free(s);
+ return eret;
+ }
+ tmp = realloc (s, len);
+ if (tmp == NULL) {
+ free (s);
+ return ENOMEM;
+ }
+ s = tmp;
+ if(c == '\n') {
+ s[len - 1] = '\0';
+ break;
+ }
+ s[len - 1] = c;
+ }
+ if(ret != 1){
+ free(s);
+ if(ret == 0)
+ return sp->eof_code;
+ return ret;
+ }
+ *string = s;
+ return 0;
+}
+
+/**
+ * Write a principal block to storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param p the principal block to write.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_principal(krb5_storage *sp,
+ krb5_const_principal p)
+{
+ size_t i;
+ int ret;
+
+ if(!krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE)) {
+ ret = krb5_store_int32(sp, p->name.name_type);
+ if(ret) return ret;
+ }
+ if(krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONENTS))
+ ret = krb5_store_int32(sp, p->name.name_string.len + 1);
+ else
+ ret = krb5_store_int32(sp, p->name.name_string.len);
+
+ if(ret) return ret;
+ ret = krb5_store_string(sp, p->realm);
+ if(ret) return ret;
+ for(i = 0; i < p->name.name_string.len; i++){
+ ret = krb5_store_string(sp, p->name.name_string.val[i]);
+ if(ret) return ret;
+ }
+ return 0;
+}
+
+/**
+ * Parse principal from the storage.
+ *
+ * @param sp the storage buffer to read from
+ * @param princ the parsed principal
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_principal(krb5_storage *sp,
+ krb5_principal *princ)
+{
+ int i;
+ int ret;
+ krb5_principal p;
+ int32_t type;
+ int32_t ncomp;
+
+ p = calloc(1, sizeof(*p));
+ if(p == NULL)
+ return ENOMEM;
+
+ if(krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE))
+ type = KRB5_NT_UNKNOWN;
+ else if((ret = krb5_ret_int32(sp, &type))){
+ free(p);
+ return ret;
+ }
+ if((ret = krb5_ret_int32(sp, &ncomp))){
+ free(p);
+ return ret;
+ }
+ if(krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONENTS))
+ ncomp--;
+ if (ncomp < 0) {
+ free(p);
+ return EINVAL;
+ }
+ ret = size_too_large_num(sp, ncomp, sizeof(p->name.name_string.val[0]));
+ if (ret) {
+ free(p);
+ return ret;
+ }
+ p->name.name_type = type;
+ p->name.name_string.len = ncomp;
+ ret = krb5_ret_string(sp, &p->realm);
+ if(ret) {
+ free(p);
+ return ret;
+ }
+ p->name.name_string.val = calloc(ncomp, sizeof(p->name.name_string.val[0]));
+ if(p->name.name_string.val == NULL && ncomp != 0){
+ free(p->realm);
+ free(p);
+ return ENOMEM;
+ }
+ for(i = 0; i < ncomp; i++){
+ ret = krb5_ret_string(sp, &p->name.name_string.val[i]);
+ if(ret) {
+ while (i >= 0)
+ free(p->name.name_string.val[i--]);
+ free(p->realm);
+ free(p);
+ return ret;
+ }
+ }
+ *princ = p;
+ return 0;
+}
+
+/**
+ * Store a keyblock to the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param p the keyblock to write
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_keyblock(krb5_storage *sp, krb5_keyblock p)
+{
+ int ret;
+ ret = krb5_store_int16(sp, p.keytype);
+ if(ret) return ret;
+
+ if(krb5_storage_is_flags(sp, KRB5_STORAGE_KEYBLOCK_KEYTYPE_TWICE)){
+ /* this should really be enctype, but it is the same as
+ keytype nowadays */
+ ret = krb5_store_int16(sp, p.keytype);
+ if(ret) return ret;
+ }
+
+ ret = krb5_store_data(sp, p.keyvalue);
+ return ret;
+}
+
+/**
+ * Read a keyblock from the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param p the keyblock read from storage, free using krb5_free_keyblock()
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_keyblock(krb5_storage *sp, krb5_keyblock *p)
+{
+ int ret;
+ int16_t tmp;
+
+ ret = krb5_ret_int16(sp, &tmp);
+ if(ret) return ret;
+ p->keytype = tmp;
+
+ if(krb5_storage_is_flags(sp, KRB5_STORAGE_KEYBLOCK_KEYTYPE_TWICE)){
+ ret = krb5_ret_int16(sp, &tmp);
+ if(ret) return ret;
+ }
+
+ ret = krb5_ret_data(sp, &p->keyvalue);
+ return ret;
+}
+
+/**
+ * Write a times block to storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param times the times block to write.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_times(krb5_storage *sp, krb5_times times)
+{
+ int ret;
+ ret = krb5_store_int32(sp, times.authtime);
+ if(ret) return ret;
+ ret = krb5_store_int32(sp, times.starttime);
+ if(ret) return ret;
+ ret = krb5_store_int32(sp, times.endtime);
+ if(ret) return ret;
+ ret = krb5_store_int32(sp, times.renew_till);
+ return ret;
+}
+
+/**
+ * Read a times block from the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param times the times block read from storage
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_times(krb5_storage *sp, krb5_times *times)
+{
+ int ret;
+ int32_t tmp;
+
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret) return ret;
+ times->authtime = tmp;
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret) return ret;
+ times->starttime = tmp;
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret) return ret;
+ times->endtime = tmp;
+ ret = krb5_ret_int32(sp, &tmp);
+ if (ret) return ret;
+ times->renew_till = tmp;
+ return ret;
+}
+
+/**
+ * Write a address block to storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param p the address block to write.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_address(krb5_storage *sp, krb5_address p)
+{
+ int ret;
+ ret = krb5_store_int16(sp, p.addr_type);
+ if(ret) return ret;
+ ret = krb5_store_data(sp, p.address);
+ return ret;
+}
+
+/**
+ * Read a address block from the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param adr the address block read from storage
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_address(krb5_storage *sp, krb5_address *adr)
+{
+ int16_t t;
+ int ret;
+ ret = krb5_ret_int16(sp, &t);
+ if(ret) return ret;
+ adr->addr_type = t;
+ ret = krb5_ret_data(sp, &adr->address);
+ return ret;
+}
+
+/**
+ * Write a addresses block to storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param p the addresses block to write.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_addrs(krb5_storage *sp, krb5_addresses p)
+{
+ size_t i;
+ int ret;
+ ret = krb5_store_int32(sp, p.len);
+ if(ret) return ret;
+ for(i = 0; i<p.len; i++){
+ ret = krb5_store_address(sp, p.val[i]);
+ if(ret) break;
+ }
+ return ret;
+}
+
+/**
+ * Read a addresses block from the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param adr the addresses block read from storage
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_addrs(krb5_storage *sp, krb5_addresses *adr)
+{
+ size_t i;
+ int ret;
+ int32_t tmp;
+
+ ret = krb5_ret_int32(sp, &tmp);
+ if(ret) return ret;
+ ret = size_too_large_num(sp, tmp, sizeof(adr->val[0]));
+ if (ret) return ret;
+ adr->len = tmp;
+ ALLOC(adr->val, adr->len);
+ if (adr->val == NULL && adr->len != 0)
+ return ENOMEM;
+ for(i = 0; i < adr->len; i++){
+ ret = krb5_ret_address(sp, &adr->val[i]);
+ if(ret) break;
+ }
+ return ret;
+}
+
+/**
+ * Write a auth data block to storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param auth the auth data block to write.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_authdata(krb5_storage *sp, krb5_authdata auth)
+{
+ krb5_error_code ret;
+ size_t i;
+ ret = krb5_store_int32(sp, auth.len);
+ if(ret) return ret;
+ for(i = 0; i < auth.len; i++){
+ ret = krb5_store_int16(sp, auth.val[i].ad_type);
+ if(ret) break;
+ ret = krb5_store_data(sp, auth.val[i].ad_data);
+ if(ret) break;
+ }
+ return 0;
+}
+
+/**
+ * Read a auth data from the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param auth the auth data block read from storage
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_authdata(krb5_storage *sp, krb5_authdata *auth)
+{
+ krb5_error_code ret;
+ int32_t tmp;
+ int16_t tmp2;
+ int i;
+ ret = krb5_ret_int32(sp, &tmp);
+ if(ret) return ret;
+ ret = size_too_large_num(sp, tmp, sizeof(auth->val[0]));
+ if (ret) return ret;
+ ALLOC_SEQ(auth, tmp);
+ if (auth->val == NULL && tmp != 0)
+ return ENOMEM;
+ for(i = 0; i < tmp; i++){
+ ret = krb5_ret_int16(sp, &tmp2);
+ if(ret) break;
+ auth->val[i].ad_type = tmp2;
+ ret = krb5_ret_data(sp, &auth->val[i].ad_data);
+ if(ret) break;
+ }
+ return ret;
+}
+
+static int32_t
+bitswap32(int32_t b)
+{
+ int32_t r = 0;
+ int i;
+ for (i = 0; i < 32; i++) {
+ r = r << 1 | (b & 1);
+ b = b >> 1;
+ }
+ return r;
+}
+
+/**
+ * Write a credentials block to storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param creds the creds block to write.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_creds(krb5_storage *sp, krb5_creds *creds)
+{
+ int ret;
+
+ ret = krb5_store_principal(sp, creds->client);
+ if(ret)
+ return ret;
+ ret = krb5_store_principal(sp, creds->server);
+ if(ret)
+ return ret;
+ ret = krb5_store_keyblock(sp, creds->session);
+ if(ret)
+ return ret;
+ ret = krb5_store_times(sp, creds->times);
+ if(ret)
+ return ret;
+ ret = krb5_store_int8(sp, creds->second_ticket.length != 0); /* is_skey */
+ if(ret)
+ return ret;
+ ret = krb5_store_int32(sp, bitswap32(TicketFlags2int(creds->flags.b)));
+ if(ret)
+ return ret;
+ ret = krb5_store_addrs(sp, creds->addresses);
+ if(ret)
+ return ret;
+ ret = krb5_store_authdata(sp, creds->authdata);
+ if(ret)
+ return ret;
+ ret = krb5_store_data(sp, creds->ticket);
+ if(ret)
+ return ret;
+ ret = krb5_store_data(sp, creds->second_ticket);
+ return ret;
+}
+
+/**
+ * Read a credentials block from the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param creds the credentials block read from storage
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_creds(krb5_storage *sp, krb5_creds *creds)
+{
+ krb5_error_code ret;
+ int8_t dummy8;
+ int32_t dummy32;
+
+ memset(creds, 0, sizeof(*creds));
+ ret = krb5_ret_principal (sp, &creds->client);
+ if(ret) goto cleanup;
+ ret = krb5_ret_principal (sp, &creds->server);
+ if(ret) goto cleanup;
+ ret = krb5_ret_keyblock (sp, &creds->session);
+ if(ret) goto cleanup;
+ ret = krb5_ret_times (sp, &creds->times);
+ if(ret) goto cleanup;
+ ret = krb5_ret_int8 (sp, &dummy8);
+ if(ret) goto cleanup;
+ ret = krb5_ret_int32 (sp, &dummy32);
+ if(ret) goto cleanup;
+ creds->flags.b = int2TicketFlags(bitswap32(dummy32));
+ ret = krb5_ret_addrs (sp, &creds->addresses);
+ if(ret) goto cleanup;
+ ret = krb5_ret_authdata (sp, &creds->authdata);
+ if(ret) goto cleanup;
+ ret = krb5_ret_data (sp, &creds->ticket);
+ if(ret) goto cleanup;
+ ret = krb5_ret_data (sp, &creds->second_ticket);
+cleanup:
+ if(ret) {
+#if 0
+ krb5_free_cred_contents(context, creds); /* XXX */
+#endif
+ }
+ return ret;
+}
+
+#define SC_CLIENT_PRINCIPAL 0x0001
+#define SC_SERVER_PRINCIPAL 0x0002
+#define SC_SESSION_KEY 0x0004
+#define SC_TICKET 0x0008
+#define SC_SECOND_TICKET 0x0010
+#define SC_AUTHDATA 0x0020
+#define SC_ADDRESSES 0x0040
+
+/**
+ * Write a tagged credentials block to storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param creds the creds block to write.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_store_creds_tag(krb5_storage *sp, krb5_creds *creds)
+{
+ int ret;
+ int32_t header = 0;
+
+ if (creds->client)
+ header |= SC_CLIENT_PRINCIPAL;
+ if (creds->server)
+ header |= SC_SERVER_PRINCIPAL;
+ if (creds->session.keytype != ETYPE_NULL)
+ header |= SC_SESSION_KEY;
+ if (creds->ticket.data)
+ header |= SC_TICKET;
+ if (creds->second_ticket.length)
+ header |= SC_SECOND_TICKET;
+ if (creds->authdata.len)
+ header |= SC_AUTHDATA;
+ if (creds->addresses.len)
+ header |= SC_ADDRESSES;
+
+ ret = krb5_store_int32(sp, header);
+ if (ret)
+ return ret;
+
+ if (creds->client) {
+ ret = krb5_store_principal(sp, creds->client);
+ if(ret)
+ return ret;
+ }
+
+ if (creds->server) {
+ ret = krb5_store_principal(sp, creds->server);
+ if(ret)
+ return ret;
+ }
+
+ if (creds->session.keytype != ETYPE_NULL) {
+ ret = krb5_store_keyblock(sp, creds->session);
+ if(ret)
+ return ret;
+ }
+
+ ret = krb5_store_times(sp, creds->times);
+ if(ret)
+ return ret;
+ ret = krb5_store_int8(sp, creds->second_ticket.length != 0); /* is_skey */
+ if(ret)
+ return ret;
+
+ ret = krb5_store_int32(sp, bitswap32(TicketFlags2int(creds->flags.b)));
+ if(ret)
+ return ret;
+
+ if (creds->addresses.len) {
+ ret = krb5_store_addrs(sp, creds->addresses);
+ if(ret)
+ return ret;
+ }
+
+ if (creds->authdata.len) {
+ ret = krb5_store_authdata(sp, creds->authdata);
+ if(ret)
+ return ret;
+ }
+
+ if (creds->ticket.data) {
+ ret = krb5_store_data(sp, creds->ticket);
+ if(ret)
+ return ret;
+ }
+
+ if (creds->second_ticket.data) {
+ ret = krb5_store_data(sp, creds->second_ticket);
+ if (ret)
+ return ret;
+ }
+
+ return ret;
+}
+
+/**
+ * Read a tagged credentials block from the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param creds the credentials block read from storage
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ret_creds_tag(krb5_storage *sp,
+ krb5_creds *creds)
+{
+ krb5_error_code ret;
+ int8_t dummy8;
+ int32_t dummy32, header;
+
+ memset(creds, 0, sizeof(*creds));
+
+ ret = krb5_ret_int32 (sp, &header);
+ if (ret) goto cleanup;
+
+ if (header & SC_CLIENT_PRINCIPAL) {
+ ret = krb5_ret_principal (sp, &creds->client);
+ if(ret) goto cleanup;
+ }
+ if (header & SC_SERVER_PRINCIPAL) {
+ ret = krb5_ret_principal (sp, &creds->server);
+ if(ret) goto cleanup;
+ }
+ if (header & SC_SESSION_KEY) {
+ ret = krb5_ret_keyblock (sp, &creds->session);
+ if(ret) goto cleanup;
+ }
+ ret = krb5_ret_times (sp, &creds->times);
+ if(ret) goto cleanup;
+ ret = krb5_ret_int8 (sp, &dummy8);
+ if(ret) goto cleanup;
+ ret = krb5_ret_int32 (sp, &dummy32);
+ if(ret) goto cleanup;
+ creds->flags.b = int2TicketFlags(bitswap32(dummy32));
+ if (header & SC_ADDRESSES) {
+ ret = krb5_ret_addrs (sp, &creds->addresses);
+ if(ret) goto cleanup;
+ }
+ if (header & SC_AUTHDATA) {
+ ret = krb5_ret_authdata (sp, &creds->authdata);
+ if(ret) goto cleanup;
+ }
+ if (header & SC_TICKET) {
+ ret = krb5_ret_data (sp, &creds->ticket);
+ if(ret) goto cleanup;
+ }
+ if (header & SC_SECOND_TICKET) {
+ ret = krb5_ret_data (sp, &creds->second_ticket);
+ if(ret) goto cleanup;
+ }
+
+cleanup:
+ if(ret) {
+#if 0
+ krb5_free_cred_contents(context, creds); /* XXX */
+#endif
+ }
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_ret_data_at_offset(krb5_storage *sp,
+ size_t offset,
+ size_t length,
+ krb5_data *data)
+{
+ krb5_error_code ret;
+ off_t cur, size;
+
+ krb5_data_zero(data);
+
+ cur = sp->seek(sp, 0, SEEK_CUR);
+ if (cur < 0)
+ return HEIM_ERR_NOT_SEEKABLE;
+
+ size = sp->seek(sp, 0, SEEK_END);
+ if (offset + length > size) {
+ ret = ERANGE;
+ goto cleanup;
+ }
+
+ ret = krb5_data_alloc(data, length);
+ if (ret)
+ goto cleanup;
+
+ if (length) {
+ sp->seek(sp, offset, SEEK_SET);
+
+ size = sp->fetch(sp, data->data, length);
+ heim_assert(size == length, "incomplete buffer fetched");
+ }
+
+cleanup:
+ sp->seek(sp, cur, SEEK_SET);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_ret_utf8_from_ucs2le_at_offset(krb5_storage *sp,
+ off_t offset,
+ size_t length,
+ char **utf8)
+{
+ krb5_error_code ret;
+ krb5_data data;
+ size_t ucs2len = length / 2;
+ uint16_t *ucs2 = NULL;
+ size_t u8len;
+ unsigned int flags = WIND_RW_LE;
+
+ *utf8 = NULL;
+
+ krb5_data_zero(&data);
+
+ ret = _krb5_ret_data_at_offset(sp, offset, length, &data);
+ if (ret)
+ goto out;
+
+ ucs2 = malloc(sizeof(ucs2[0]) * ucs2len);
+ if (ucs2 == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ ret = wind_ucs2read(data.data, data.length, &flags, ucs2, &ucs2len);
+ if (ret)
+ goto out;
+
+ ret = wind_ucs2utf8_length(ucs2, ucs2len, &u8len);
+ if (ret)
+ goto out;
+
+ u8len += 1; /* Add space for NUL */
+
+ *utf8 = malloc(u8len);
+ if (*utf8 == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ ret = wind_ucs2utf8(ucs2, ucs2len, *utf8, &u8len);
+ if (ret)
+ goto out;
+
+out:
+ if (ret && *utf8) {
+ free(*utf8);
+ *utf8 = NULL;
+ }
+ free(ucs2);
+ krb5_data_free(&data);
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_store_data_at_offset(krb5_storage *sp,
+ size_t offset,
+ const krb5_data *data)
+{
+ krb5_error_code ret;
+ krb5_ssize_t nbytes;
+ off_t pos;
+
+ if (offset == (off_t)-1) {
+ if (data == NULL || data->data == NULL) {
+ offset = 0;
+ } else {
+ pos = sp->seek(sp, 0, SEEK_CUR);
+ offset = sp->seek(sp, 0, SEEK_END);
+ sp->seek(sp, pos, SEEK_SET);
+
+ if (offset == (off_t)-1)
+ return HEIM_ERR_NOT_SEEKABLE;
+ }
+ }
+
+ if (offset > 0xFFFF)
+ return ERANGE;
+ else if ((offset != 0) != (data && data->data))
+ return EINVAL;
+ else if (data && data->length > 0xFFFF)
+ return ERANGE;
+
+ ret = krb5_store_uint16(sp, data ? (uint16_t)data->length : 0);
+ if (ret == 0)
+ ret = krb5_store_uint16(sp, (uint16_t)offset);
+ if (ret == 0 && offset) {
+ pos = sp->seek(sp, 0, SEEK_CUR);
+ sp->seek(sp, offset, SEEK_SET);
+ nbytes = krb5_storage_write(sp, data->data, data->length);
+ if ((size_t)nbytes != data->length)
+ ret = sp->eof_code;
+ sp->seek(sp, pos, SEEK_SET);
+ }
+
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_store_utf8_as_ucs2le_at_offset(krb5_storage *sp,
+ off_t offset,
+ const char *utf8)
+{
+ krb5_error_code ret;
+ size_t ucs2_len, ucs2le_size;
+ uint16_t *ucs2, *ucs2le;
+ unsigned int flags;
+
+ if (utf8) {
+ ret = wind_utf8ucs2_length(utf8, &ucs2_len);
+ if (ret)
+ return ret;
+
+ ucs2 = malloc(sizeof(ucs2[0]) * ucs2_len);
+ if (ucs2 == NULL)
+ return ENOMEM;
+
+ ret = wind_utf8ucs2(utf8, ucs2, &ucs2_len);
+ if (ret) {
+ free(ucs2);
+ return ret;
+ }
+
+ ucs2le_size = (ucs2_len + 1) * 2;
+ ucs2le = malloc(ucs2le_size);
+ if (ucs2le == NULL) {
+ free(ucs2);
+ return ENOMEM;
+ }
+
+ flags = WIND_RW_LE;
+ ret = wind_ucs2write(ucs2, ucs2_len, &flags, ucs2le, &ucs2le_size);
+ free(ucs2);
+ if (ret) {
+ free(ucs2le);
+ return ret;
+ }
+
+ ucs2le_size = ucs2_len * 2;
+ } else {
+ ucs2le = NULL;
+ ucs2le_size = 0;
+ offset = 0;
+ ret = 0;
+ }
+
+ {
+ krb5_data data;
+
+ data.data = ucs2le;
+ data.length = ucs2le_size;
+
+ ret = _krb5_store_data_at_offset(sp, offset, &data);
+ }
+
+ free(ucs2le);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/store_emem.c b/third_party/heimdal/lib/krb5/store_emem.c
new file mode 100644
index 0000000..6a3908f
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/store_emem.c
@@ -0,0 +1,214 @@
+/*
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include "store-int.h"
+#include <assert.h>
+
+typedef struct emem_storage{
+ unsigned char *base;
+ size_t size;
+ size_t len;
+ unsigned char *ptr;
+}emem_storage;
+
+static ssize_t
+emem_fetch(krb5_storage *sp, void *data, size_t size)
+{
+ emem_storage *s = (emem_storage*)sp->data;
+
+ assert(data != NULL && s->ptr != NULL);
+
+ if((size_t)(s->base + s->len - s->ptr) < size)
+ size = s->base + s->len - s->ptr;
+ memmove(data, s->ptr, size);
+ sp->seek(sp, size, SEEK_CUR);
+ return size;
+}
+
+static ssize_t
+emem_store(krb5_storage *sp, const void *data, size_t size)
+{
+ emem_storage *s;
+
+ if (size == 0) {
+ sp->seek(sp, 0, SEEK_CUR);
+ return 0;
+ }
+
+ s = (emem_storage*)sp->data;
+
+ assert(data != NULL);
+
+ if(size > (size_t)(s->base + s->size - s->ptr)){
+ void *base;
+ size_t sz, off;
+ off = s->ptr - s->base;
+ sz = off + size;
+ if (sz < 4096)
+ sz *= 2;
+ base = realloc(s->base, sz);
+ if(base == NULL)
+ return -1;
+ s->size = sz;
+ s->base = base;
+ s->ptr = (unsigned char*)base + off;
+ }
+ memmove(s->ptr, data, size);
+ sp->seek(sp, size, SEEK_CUR);
+ return size;
+}
+
+static off_t
+emem_seek(krb5_storage *sp, off_t offset, int whence)
+{
+ emem_storage *s = (emem_storage*)sp->data;
+ switch(whence){
+ case SEEK_SET:
+ if((size_t)offset > s->size)
+ offset = s->size;
+ if(offset < 0)
+ offset = 0;
+ s->ptr = s->base + offset;
+ if((size_t)offset > s->len)
+ s->len = offset;
+ break;
+ case SEEK_CUR:
+ sp->seek(sp,s->ptr - s->base + offset, SEEK_SET);
+ break;
+ case SEEK_END:
+ sp->seek(sp, s->len + offset, SEEK_SET);
+ break;
+ default:
+ errno = EINVAL;
+ return -1;
+ }
+ return s->ptr - s->base;
+}
+
+static int
+emem_trunc(krb5_storage *sp, off_t offset)
+{
+ emem_storage *s = (emem_storage*)sp->data;
+ /*
+ * If offset is larget then current size, or current size is
+ * shrunk more then half of the current size, adjust buffer.
+ */
+ if (offset == 0) {
+ free(s->base);
+ s->size = 0;
+ s->base = NULL;
+ s->ptr = NULL;
+ } else if ((size_t)offset > s->size || (s->size / 2) > (size_t)offset) {
+ void *base;
+ size_t off;
+ off = s->ptr - s->base;
+ base = realloc(s->base, offset);
+ if(base == NULL)
+ return ENOMEM;
+ if ((size_t)offset > s->size)
+ memset((char *)base + s->size, 0, offset - s->size);
+ s->size = offset;
+ s->base = base;
+ s->ptr = (unsigned char *)base + off;
+ }
+ s->len = offset;
+ if ((s->ptr - s->base) > offset)
+ s->ptr = s->base + offset;
+ return 0;
+}
+
+
+static void
+emem_free(krb5_storage *sp)
+{
+ emem_storage *s = sp->data;
+
+ assert(s->base != NULL);
+
+ memset_s(s->base, s->len, 0, s->len);
+ free(s->base);
+}
+
+/**
+ * Create a elastic (allocating) memory storage backend. Memory is
+ * allocated on demand. Free returned krb5_storage with
+ * krb5_storage_free().
+ *
+ * @return A krb5_storage on success, or NULL on out of memory error.
+ *
+ * @ingroup krb5_storage
+ *
+ * @sa krb5_storage_from_mem()
+ * @sa krb5_storage_from_readonly_mem()
+ * @sa krb5_storage_from_fd()
+ * @sa krb5_storage_from_data()
+ * @sa krb5_storage_from_socket()
+ */
+
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
+krb5_storage_emem(void)
+{
+ krb5_storage *sp;
+ emem_storage *s;
+
+ sp = malloc(sizeof(krb5_storage));
+ if (sp == NULL)
+ return NULL;
+
+ s = malloc(sizeof(*s));
+ if (s == NULL) {
+ free(sp);
+ return NULL;
+ }
+ sp->data = s;
+ sp->flags = 0;
+ sp->eof_code = HEIM_ERR_EOF;
+ s->size = 1024;
+ s->base = calloc(1, s->size);
+ if (s->base == NULL) {
+ free(sp);
+ free(s);
+ return NULL;
+ }
+ s->len = 0;
+ s->ptr = s->base;
+ sp->fetch = emem_fetch;
+ sp->store = emem_store;
+ sp->seek = emem_seek;
+ sp->trunc = emem_trunc;
+ sp->fsync = NULL;
+ sp->free = emem_free;
+ sp->max_alloc = UINT_MAX/8;
+ return sp;
+}
diff --git a/third_party/heimdal/lib/krb5/store_fd.c b/third_party/heimdal/lib/krb5/store_fd.c
new file mode 100644
index 0000000..720ed66
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/store_fd.c
@@ -0,0 +1,200 @@
+/*
+ * Copyright (c) 1997 - 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include "store-int.h"
+
+typedef struct fd_storage {
+ int fd;
+} fd_storage;
+
+#define FD(S) (((fd_storage*)(S)->data)->fd)
+
+static ssize_t
+fd_fetch(krb5_storage * sp, void *data, size_t size)
+{
+ char *cbuf = (char *)data;
+ ssize_t count;
+ size_t rem = size;
+
+ /* similar pattern to net_read() to support pipes */
+ while (rem > 0) {
+ count = read (FD(sp), cbuf, rem);
+ if (count < 0) {
+ if (errno == EINTR)
+ continue;
+ else if (rem == size)
+ return count;
+ else
+ return size - rem;
+ } else if (count == 0) {
+ return count;
+ }
+ cbuf += count;
+ rem -= count;
+ }
+ return size;
+}
+
+static ssize_t
+fd_store(krb5_storage * sp, const void *data, size_t size)
+{
+ const char *cbuf = (const char *)data;
+ ssize_t count;
+ size_t rem = size;
+
+ /* similar pattern to net_write() to support pipes */
+ while (rem > 0) {
+ count = write(FD(sp), cbuf, rem);
+ if (count < 0) {
+ if (errno == EINTR)
+ continue;
+ else
+ return size - rem;
+ }
+ cbuf += count;
+ rem -= count;
+ }
+ return size;
+}
+
+static off_t
+fd_seek(krb5_storage * sp, off_t offset, int whence)
+{
+ return lseek(FD(sp), offset, whence);
+}
+
+static int
+fd_trunc(krb5_storage * sp, off_t offset)
+{
+ off_t tmpoff;
+
+ if (ftruncate(FD(sp), offset) == -1)
+ return errno;
+
+ tmpoff = lseek(FD(sp), 0, SEEK_CUR);
+ if (tmpoff == -1)
+ return errno;
+
+ if (tmpoff > offset) {
+ tmpoff = lseek(FD(sp), offset, SEEK_SET);
+ if (tmpoff == -1)
+ return errno;
+ }
+
+ return 0;
+}
+
+static int
+fd_sync(krb5_storage * sp)
+{
+ if (fsync(FD(sp)) == -1)
+ return errno;
+ return 0;
+}
+
+static void
+fd_free(krb5_storage * sp)
+{
+ int save_errno = errno;
+ if (close(FD(sp)) == 0)
+ errno = save_errno;
+}
+
+/**
+ *
+ *
+ * @return A krb5_storage on success, or NULL on out of memory error.
+ *
+ * @ingroup krb5_storage
+ *
+ * @sa krb5_storage_emem()
+ * @sa krb5_storage_from_mem()
+ * @sa krb5_storage_from_readonly_mem()
+ * @sa krb5_storage_from_data()
+ * @sa krb5_storage_from_socket()
+ */
+
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
+krb5_storage_from_fd(int fd_in)
+{
+ krb5_storage *sp;
+ int saved_errno;
+ int fd;
+
+#ifdef _MSC_VER
+ /*
+ * This function used to try to pass the input to
+ * _get_osfhandle() to test if the value is a HANDLE
+ * but this doesn't work because doing so throws an
+ * exception that will result in Watson being triggered
+ * to file a Windows Error Report.
+ */
+ fd = _dup(fd_in);
+#else
+ fd = dup(fd_in);
+#endif
+
+ if (fd < 0)
+ return NULL;
+
+ errno = ENOMEM;
+ sp = malloc(sizeof(krb5_storage));
+ if (sp == NULL) {
+ saved_errno = errno;
+ close(fd);
+ errno = saved_errno;
+ return NULL;
+ }
+
+ errno = ENOMEM;
+ sp->data = malloc(sizeof(fd_storage));
+ if (sp->data == NULL) {
+ saved_errno = errno;
+ close(fd);
+ free(sp);
+ errno = saved_errno;
+ return NULL;
+ }
+ sp->flags = 0;
+ sp->eof_code = HEIM_ERR_EOF;
+ FD(sp) = fd;
+ sp->fetch = fd_fetch;
+ sp->store = fd_store;
+ sp->seek = fd_seek;
+ sp->trunc = fd_trunc;
+ sp->fsync = fd_sync;
+ sp->free = fd_free;
+ sp->max_alloc = UINT_MAX/8;
+ return sp;
+}
diff --git a/third_party/heimdal/lib/krb5/store_mem.c b/third_party/heimdal/lib/krb5/store_mem.c
new file mode 100644
index 0000000..ff2a570
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/store_mem.c
@@ -0,0 +1,212 @@
+/*
+ * Copyright (c) 1997 - 2000, 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include "store-int.h"
+
+typedef struct mem_storage{
+ unsigned char *base;
+ size_t size;
+ unsigned char *ptr;
+}mem_storage;
+
+static ssize_t
+mem_fetch(krb5_storage *sp, void *data, size_t size)
+{
+ mem_storage *s = (mem_storage*)sp->data;
+ if(size > (size_t)(s->base + s->size - s->ptr))
+ size = s->base + s->size - s->ptr;
+ memmove(data, s->ptr, size);
+ sp->seek(sp, size, SEEK_CUR);
+ return size;
+}
+
+static ssize_t
+mem_store(krb5_storage *sp, const void *data, size_t size)
+{
+ mem_storage *s = (mem_storage*)sp->data;
+ if(size > (size_t)(s->base + s->size - s->ptr))
+ size = s->base + s->size - s->ptr;
+ memmove(s->ptr, data, size);
+ sp->seek(sp, size, SEEK_CUR);
+ return size;
+}
+
+static ssize_t
+mem_no_store(krb5_storage *sp, const void *data, size_t size)
+{
+ return -1;
+}
+
+static off_t
+mem_seek(krb5_storage *sp, off_t offset, int whence)
+{
+ mem_storage *s = (mem_storage*)sp->data;
+ switch(whence){
+ case SEEK_SET:
+ if((size_t)offset > s->size)
+ offset = s->size;
+ if(offset < 0)
+ offset = 0;
+ s->ptr = s->base + offset;
+ break;
+ case SEEK_CUR:
+ return sp->seek(sp, s->ptr - s->base + offset, SEEK_SET);
+ case SEEK_END:
+ return sp->seek(sp, s->size + offset, SEEK_SET);
+ default:
+ errno = EINVAL;
+ return -1;
+ }
+ return s->ptr - s->base;
+}
+
+static int
+mem_trunc(krb5_storage *sp, off_t offset)
+{
+ mem_storage *s = (mem_storage*)sp->data;
+ if((size_t)offset > s->size)
+ return ERANGE;
+ s->size = offset;
+ if ((s->ptr - s->base) > offset)
+ s->ptr = s->base + offset;
+ return 0;
+}
+
+static int
+mem_no_trunc(krb5_storage *sp, off_t offset)
+{
+ return EINVAL;
+}
+
+/**
+ * Create a fixed size memory storage block
+ *
+ * @return A krb5_storage on success, or NULL on out of memory error.
+ *
+ * @ingroup krb5_storage
+ *
+ * @sa krb5_storage_mem()
+ * @sa krb5_storage_from_readonly_mem()
+ * @sa krb5_storage_from_data()
+ * @sa krb5_storage_from_fd()
+ * @sa krb5_storage_from_socket()
+ */
+
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
+krb5_storage_from_mem(void *buf, size_t len)
+{
+ krb5_storage *sp = malloc(sizeof(krb5_storage));
+ mem_storage *s;
+ if(sp == NULL)
+ return NULL;
+ s = malloc(sizeof(*s));
+ if(s == NULL) {
+ free(sp);
+ return NULL;
+ }
+ sp->data = s;
+ sp->flags = 0;
+ sp->eof_code = HEIM_ERR_EOF;
+ s->base = buf;
+ s->size = len;
+ s->ptr = buf;
+ sp->fetch = mem_fetch;
+ sp->store = mem_store;
+ sp->seek = mem_seek;
+ sp->trunc = mem_trunc;
+ sp->fsync = NULL;
+ sp->free = NULL;
+ sp->max_alloc = UINT_MAX/8;
+ return sp;
+}
+
+/**
+ * Create a fixed size memory storage block
+ *
+ * @return A krb5_storage on success, or NULL on out of memory error.
+ *
+ * @ingroup krb5_storage
+ *
+ * @sa krb5_storage_mem()
+ * @sa krb5_storage_from_mem()
+ * @sa krb5_storage_from_readonly_mem()
+ * @sa krb5_storage_from_fd()
+ */
+
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
+krb5_storage_from_data(krb5_data *data)
+{
+ return krb5_storage_from_mem(data->data, data->length);
+}
+
+/**
+ * Create a fixed size memory storage block that is read only
+ *
+ * @return A krb5_storage on success, or NULL on out of memory error.
+ *
+ * @ingroup krb5_storage
+ *
+ * @sa krb5_storage_mem()
+ * @sa krb5_storage_from_mem()
+ * @sa krb5_storage_from_data()
+ * @sa krb5_storage_from_fd()
+ */
+
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
+krb5_storage_from_readonly_mem(const void *buf, size_t len)
+{
+ krb5_storage *sp = malloc(sizeof(krb5_storage));
+ mem_storage *s;
+ if(sp == NULL)
+ return NULL;
+ s = malloc(sizeof(*s));
+ if(s == NULL) {
+ free(sp);
+ return NULL;
+ }
+ sp->data = s;
+ sp->flags = 0;
+ sp->eof_code = HEIM_ERR_EOF;
+ s->base = rk_UNCONST(buf);
+ s->size = len;
+ s->ptr = rk_UNCONST(buf);
+ sp->fetch = mem_fetch;
+ sp->store = mem_no_store;
+ sp->seek = mem_seek;
+ sp->trunc = mem_no_trunc;
+ sp->fsync = NULL;
+ sp->free = NULL;
+ sp->max_alloc = UINT_MAX/8;
+ return sp;
+}
diff --git a/third_party/heimdal/lib/krb5/store_sock.c b/third_party/heimdal/lib/krb5/store_sock.c
new file mode 100644
index 0000000..fd6fe8f
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/store_sock.c
@@ -0,0 +1,160 @@
+/*
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include "store-int.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#endif
+
+typedef struct socket_storage {
+ krb5_socket_t sock;
+} socket_storage;
+
+#define SOCK(S) (((socket_storage*)(S)->data)->sock)
+
+static ssize_t
+socket_fetch(krb5_storage * sp, void *data, size_t size)
+{
+ return net_read(SOCK(sp), data, size);
+}
+
+static ssize_t
+socket_store(krb5_storage * sp, const void *data, size_t size)
+{
+ return net_write(SOCK(sp), data, size);
+}
+
+static off_t
+socket_seek(krb5_storage * sp, off_t offset, int whence)
+{
+ return lseek(SOCK(sp), offset, whence);
+}
+
+static int
+socket_trunc(krb5_storage * sp, off_t offset)
+{
+ if (ftruncate(SOCK(sp), offset) == -1)
+ return errno;
+ return 0;
+}
+
+static int
+socket_sync(krb5_storage * sp)
+{
+ if (fsync(SOCK(sp)) == -1)
+ return errno;
+ return 0;
+}
+
+static void
+socket_free(krb5_storage * sp)
+{
+ int save_errno = errno;
+ if (rk_IS_SOCKET_ERROR(rk_closesocket(SOCK(sp))))
+ errno = rk_SOCK_ERRNO;
+ else
+ errno = save_errno;
+}
+
+/**
+ *
+ *
+ * @return A krb5_storage on success, or NULL on out of memory error.
+ *
+ * @ingroup krb5_storage
+ *
+ * @sa krb5_storage_emem()
+ * @sa krb5_storage_from_mem()
+ * @sa krb5_storage_from_readonly_mem()
+ * @sa krb5_storage_from_data()
+ * @sa krb5_storage_from_fd()
+ */
+
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
+krb5_storage_from_socket(krb5_socket_t sock_in)
+{
+ krb5_storage *sp;
+ int saved_errno;
+ krb5_socket_t sock;
+
+#ifdef _WIN32
+ WSAPROTOCOL_INFO info;
+
+ sock = rk_INVALID_SOCKET;
+ if (WSADuplicateSocket(sock_in, GetCurrentProcessId(), &info) == 0)
+ {
+
+ sock = WSASocket( FROM_PROTOCOL_INFO,
+ FROM_PROTOCOL_INFO,
+ FROM_PROTOCOL_INFO,
+ &info, 0, 0);
+ }
+#else
+ sock = dup(sock_in);
+#endif
+
+ if (sock == rk_INVALID_SOCKET)
+ return NULL;
+
+ errno = ENOMEM;
+ sp = malloc(sizeof(krb5_storage));
+ if (sp == NULL) {
+ saved_errno = errno;
+ rk_closesocket(sock);
+ errno = saved_errno;
+ return NULL;
+ }
+
+ errno = ENOMEM;
+ sp->data = malloc(sizeof(socket_storage));
+ if (sp->data == NULL) {
+ saved_errno = errno;
+ rk_closesocket(sock);
+ free(sp);
+ errno = saved_errno;
+ return NULL;
+ }
+ sp->flags = 0;
+ sp->eof_code = HEIM_ERR_EOF;
+ SOCK(sp) = sock;
+ sp->fetch = socket_fetch;
+ sp->store = socket_store;
+ sp->seek = socket_seek;
+ sp->trunc = socket_trunc;
+ sp->fsync = socket_sync;
+ sp->free = socket_free;
+ sp->max_alloc = UINT_MAX/8;
+ return sp;
+}
diff --git a/third_party/heimdal/lib/krb5/store_stdio.c b/third_party/heimdal/lib/krb5/store_stdio.c
new file mode 100644
index 0000000..dddaa92
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/store_stdio.c
@@ -0,0 +1,264 @@
+/*
+ * Copyright (c) 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include "store-int.h"
+
+#ifndef HAVE_FSEEKO
+#define fseeko fseek
+#define ftello ftell
+#endif
+
+typedef struct stdio_storage {
+ FILE *f;
+ off_t pos;
+} stdio_storage;
+
+#define F(S) (((stdio_storage*)(S)->data)->f)
+#define POS(S) (((stdio_storage*)(S)->data)->pos)
+
+static ssize_t
+stdio_fetch(krb5_storage * sp, void *data, size_t size)
+{
+ char *cbuf = (char *)data;
+ ssize_t count;
+ size_t rem = size;
+
+ /* similar pattern to net_read() to support pipes */
+ while (rem > 0) {
+ count = fread(cbuf, 1, rem, F(sp));
+ if (count < 0) {
+ POS(sp) = -1;
+ if (errno == EINTR)
+ continue;
+ else
+ return count;
+ } else if (count == 0) {
+ if (POS(sp) >= 0)
+ POS(sp) += size - rem;
+ return size - rem;
+ }
+ cbuf += count;
+ rem -= count;
+ }
+ if (POS(sp) >= 0)
+ POS(sp) += size;
+ return size;
+}
+
+static ssize_t
+stdio_store(krb5_storage * sp, const void *data, size_t size)
+{
+ const char *cbuf = (const char *)data;
+ ssize_t count;
+ size_t rem = size;
+
+ /* similar pattern to net_write() to support pipes */
+ while (rem > 0) {
+ count = fwrite(cbuf, 1, rem, F(sp));
+ if (count < 0) {
+ if (errno == EINTR)
+ continue;
+ /*
+ * What does it mean to have a short write when using stdio?
+ *
+ * It can't mean much. After all stdio is buffering, so
+ * earlier writes that appeared complete may have failed,
+ * and so we don't know how much we really failed to write.
+ */
+ POS(sp) = -1;
+ return -1;
+ }
+ if (count == 0) {
+ POS(sp) = -1;
+ return -1;
+ }
+ cbuf += count;
+ rem -= count;
+ }
+ if (POS(sp) >= 0)
+ POS(sp) += size;
+ return size;
+}
+
+static off_t
+stdio_seek(krb5_storage * sp, off_t offset, int whence)
+{
+ int save_errno = errno;
+
+ if (whence == SEEK_SET && POS(sp) == offset)
+ return POS(sp);
+
+ if (whence == SEEK_CUR && POS(sp) >= 0 && offset == 0)
+ return POS(sp);
+
+ if (fseeko(F(sp), offset, whence) != 0)
+ return -1;
+ errno = save_errno;
+ return POS(sp) = ftello(F(sp));
+}
+
+static int
+stdio_trunc(krb5_storage * sp, off_t offset)
+{
+ off_t tmpoff;
+ int save_errno = errno;
+
+ if (fflush(F(sp)) == EOF)
+ return errno;
+ tmpoff = ftello(F(sp));
+ if (tmpoff < 0)
+ return errno;
+ if (tmpoff > offset)
+ tmpoff = offset;
+ if (ftruncate(fileno(F(sp)), offset) == -1)
+ return errno;
+ if (fseeko(F(sp), 0, SEEK_END) == -1)
+ return errno;
+ if (fseeko(F(sp), tmpoff, SEEK_SET) == -1)
+ return errno;
+ errno = save_errno;
+ POS(sp) = tmpoff;
+ return 0;
+}
+
+static int
+stdio_sync(krb5_storage * sp)
+{
+ if (fflush(F(sp)) == EOF)
+ return errno;
+ if (fsync(fileno(F(sp))) == -1)
+ return errno;
+ return 0;
+}
+
+static void
+stdio_free(krb5_storage * sp)
+{
+ int save_errno = errno;
+
+ if (F(sp) != NULL && fclose(F(sp)) == 0)
+ errno = save_errno;
+ F(sp) = NULL;
+}
+
+/**
+ * Open a krb5_storage using stdio for buffering.
+ *
+ * @return A krb5_storage on success, or NULL on out of memory error.
+ *
+ * @ingroup krb5_storage
+ *
+ * @sa krb5_storage_emem()
+ * @sa krb5_storage_from_fd()
+ * @sa krb5_storage_from_mem()
+ * @sa krb5_storage_from_readonly_mem()
+ * @sa krb5_storage_from_data()
+ * @sa krb5_storage_from_socket()
+ */
+
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
+krb5_storage_stdio_from_fd(int fd_in, const char *mode)
+{
+ krb5_storage *sp;
+ off_t off;
+ FILE *f;
+ int saved_errno = errno;
+ int fd;
+
+ off = lseek(fd_in, 0, SEEK_CUR);
+ if (off == -1)
+ return NULL;
+
+#ifdef _MSC_VER
+ /*
+ * This function used to try to pass the input to
+ * _get_osfhandle() to test if the value is a HANDLE
+ * but this doesn't work because doing so throws an
+ * exception that will result in Watson being triggered
+ * to file a Windows Error Report.
+ */
+ fd = _dup(fd_in);
+#else
+ fd = dup(fd_in);
+#endif
+
+ if (fd < 0)
+ return NULL;
+
+ f = fdopen(fd, mode);
+ if (f == NULL) {
+ (void) close(fd);
+ return NULL;
+ }
+
+ errno = saved_errno;
+
+ if (fseeko(f, off, SEEK_SET) == -1) {
+ saved_errno = errno;
+ (void) fclose(f);
+ errno = saved_errno;
+ return NULL;
+ }
+
+ errno = ENOMEM;
+ sp = malloc(sizeof(krb5_storage));
+ if (sp == NULL) {
+ saved_errno = errno;
+ (void) fclose(f);
+ errno = saved_errno;
+ return NULL;
+ }
+
+ errno = ENOMEM;
+ sp->data = malloc(sizeof(stdio_storage));
+ if (sp->data == NULL) {
+ saved_errno = errno;
+ (void) fclose(f);
+ free(sp);
+ errno = saved_errno;
+ return NULL;
+ }
+ sp->flags = 0;
+ sp->eof_code = HEIM_ERR_EOF;
+ F(sp) = f;
+ POS(sp) = off;
+ sp->fetch = stdio_fetch;
+ sp->store = stdio_store;
+ sp->seek = stdio_seek;
+ sp->trunc = stdio_trunc;
+ sp->fsync = stdio_sync;
+ sp->free = stdio_free;
+ sp->max_alloc = UINT_MAX/8;
+ return sp;
+}
diff --git a/third_party/heimdal/lib/krb5/string-to-key-test.c b/third_party/heimdal/lib/krb5/string-to-key-test.c
new file mode 100644
index 0000000..8988575
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/string-to-key-test.c
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+
+enum { MAXSIZE = 24 };
+
+static struct testcase {
+ const char *principal_name;
+ const char *password;
+ krb5_enctype enctype;
+ unsigned char res[MAXSIZE];
+} tests[] = {
+#ifdef HEIM_WEAK_CRYPTO
+ {"@", "", ETYPE_DES_CBC_MD5,
+ {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0xf1}},
+ {"nisse@FOO.SE", "hej", ETYPE_DES_CBC_MD5,
+ {0xfe, 0x67, 0xbf, 0x9e, 0x57, 0x6b, 0xfe, 0x52}},
+ {"assar/liten@FOO.SE", "hemligt", ETYPE_DES_CBC_MD5,
+ {0x5b, 0x9b, 0xcb, 0xf2, 0x97, 0x43, 0xc8, 0x40}},
+ {"raeburn@ATHENA.MIT.EDU", "password", ETYPE_DES_CBC_MD5,
+ {0xcb, 0xc2, 0x2f, 0xae, 0x23, 0x52, 0x98, 0xe3}},
+ {"danny@WHITEHOUSE.GOV", "potatoe", ETYPE_DES_CBC_MD5,
+ {0xdf, 0x3d, 0x32, 0xa7, 0x4f, 0xd9, 0x2a, 0x01}},
+ {"buckaroo@EXAMPLE.COM", "penny", ETYPE_DES_CBC_MD5,
+ {0x94, 0x43, 0xa2, 0xe5, 0x32, 0xfd, 0xc4, 0xf1}},
+ {"Juri\xc5\xa1i\xc4\x87@ATHENA.MIT.EDU", "\xc3\x9f", ETYPE_DES_CBC_MD5,
+ {0x62, 0xc8, 0x1a, 0x52, 0x32, 0xb5, 0xe6, 0x9d}},
+ {"AAAAAAAA", "11119999", ETYPE_DES_CBC_MD5,
+ {0x98, 0x40, 0x54, 0xd0, 0xf1, 0xa7, 0x3e, 0x31}},
+ {"FFFFAAAA", "NNNN6666", ETYPE_DES_CBC_MD5,
+ {0xc4, 0xbf, 0x6b, 0x25, 0xad, 0xf7, 0xa4, 0xf8}},
+#endif
+#if 0
+ {"@", "", ETYPE_DES3_CBC_SHA1,
+ {0xce, 0xa2, 0x2f, 0x9b, 0x52, 0x2c, 0xb0, 0x15, 0x6e, 0x6b, 0x64,
+ 0x73, 0x62, 0x64, 0x73, 0x4f, 0x6e, 0x73, 0xce, 0xa2, 0x2f, 0x9b,
+ 0x52, 0x57}},
+#endif
+ {"nisse@FOO.SE", "hej", ETYPE_DES3_CBC_SHA1,
+ {0x0e, 0xbc, 0x23, 0x9d, 0x68, 0x46, 0xf2, 0xd5, 0x51, 0x98, 0x5b,
+ 0x57, 0xc1, 0x57, 0x01, 0x79, 0x04, 0xc4, 0xe9, 0xfe, 0xc1, 0x0e,
+ 0x13, 0xd0}},
+ {"assar/liten@FOO.SE", "hemligt", ETYPE_DES3_CBC_SHA1,
+ {0x7f, 0x40, 0x67, 0xb9, 0xbc, 0xc4, 0x40, 0xfb, 0x43, 0x73, 0xd9,
+ 0xd3, 0xcd, 0x7c, 0xc7, 0x67, 0xe6, 0x79, 0x94, 0xd0, 0xa8, 0x34,
+ 0xdf, 0x62}},
+ {"does/not@MATTER", "foo", ETYPE_ARCFOUR_HMAC_MD5,
+ {0xac, 0x8e, 0x65, 0x7f, 0x83, 0xdf, 0x82, 0xbe,
+ 0xea, 0x5d, 0x43, 0xbd, 0xaf, 0x78, 0x00, 0xcc}},
+ {"raeburn@ATHENA.MIT.EDU", "password", ETYPE_DES3_CBC_SHA1,
+ {0x85, 0x0b, 0xb5, 0x13, 0x58, 0x54, 0x8c, 0xd0, 0x5e, 0x86, 0x76, 0x8c, 0x31, 0x3e, 0x3b, 0xfe, 0xf7, 0x51, 0x19, 0x37, 0xdc, 0xf7, 0x2c, 0x3e}},
+ {"danny@WHITEHOUSE.GOV", "potatoe", ETYPE_DES3_CBC_SHA1,
+ {0xdf, 0xcd, 0x23, 0x3d, 0xd0, 0xa4, 0x32, 0x04, 0xea, 0x6d, 0xc4, 0x37, 0xfb, 0x15, 0xe0, 0x61, 0xb0, 0x29, 0x79, 0xc1, 0xf7, 0x4f, 0x37, 0x7a}},
+ {"buckaroo@EXAMPLE.COM", "penny", ETYPE_DES3_CBC_SHA1,
+ {0x6d, 0x2f, 0xcd, 0xf2, 0xd6, 0xfb, 0xbc, 0x3d, 0xdc, 0xad, 0xb5, 0xda, 0x57, 0x10, 0xa2, 0x34, 0x89, 0xb0, 0xd3, 0xb6, 0x9d, 0x5d, 0x9d, 0x4a}},
+ {"Juri\xc5\xa1i\xc4\x87@ATHENA.MIT.EDU", "\xc3\x9f", ETYPE_DES3_CBC_SHA1,
+ {0x16, 0xd5, 0xa4, 0x0e, 0x1c, 0xe3, 0xba, 0xcb, 0x61, 0xb9, 0xdc, 0xe0, 0x04, 0x70, 0x32, 0x4c, 0x83, 0x19, 0x73, 0xa7, 0xb9, 0x52, 0xfe, 0xb0}},
+ {NULL, NULL, 0, {0}}
+};
+
+int
+main(int argc, char **argv)
+{
+ struct testcase *t;
+ krb5_context context;
+ krb5_error_code ret;
+ int val = 0;
+
+ ret = krb5_init_context (&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ /* to enable realm-less principal name above */
+
+ krb5_set_default_realm(context, "");
+
+ for (t = tests; t->principal_name; ++t) {
+ krb5_keyblock key;
+ krb5_principal principal;
+ int i;
+
+ ret = krb5_parse_name (context, t->principal_name, &principal);
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_parse_name %s",
+ t->principal_name);
+ ret = krb5_string_to_key (context, t->enctype, t->password,
+ principal, &key);
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_string_to_key");
+ krb5_free_principal (context, principal);
+ if (memcmp (key.keyvalue.data, t->res, key.keyvalue.length) != 0) {
+ const unsigned char *p = key.keyvalue.data;
+
+ printf ("string_to_key(%s, %s) failed\n",
+ t->principal_name, t->password);
+ printf ("should be: ");
+ for (i = 0; i < key.keyvalue.length; ++i)
+ printf ("%02x", t->res[i]);
+ printf ("\nresult was: ");
+ for (i = 0; i < key.keyvalue.length; ++i)
+ printf ("%02x", p[i]);
+ printf ("\n");
+ val = 1;
+ }
+ krb5_free_keyblock_contents(context, &key);
+ }
+ krb5_free_context(context);
+ return val;
+}
diff --git a/third_party/heimdal/lib/krb5/test_acl.c b/third_party/heimdal/lib/krb5/test_acl.c
new file mode 100644
index 0000000..a11ff3f
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_acl.c
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+
+#define RETVAL(c, r, e, s) \
+ do { if (r != e) krb5_errx(c, 1, "%s", s); } while (0)
+#define STRINGMATCH(c, s, _s1, _s2) \
+ do { \
+ if (_s1 == NULL) \
+ krb5_errx(c, 1, "s1 or s2 is NULL"); \
+ if (strcmp(_s1,_s2) != 0) \
+ krb5_errx(c, 1, "%s", s); \
+ } while (0)
+
+static void
+test_match_string(krb5_context context)
+{
+ krb5_error_code ret;
+ char *s1, *s2;
+
+ ret = krb5_acl_match_string(context, "foo", "s", "foo");
+ RETVAL(context, ret, 0, "single s");
+ ret = krb5_acl_match_string(context, "foo foo", "s", "foo");
+ RETVAL(context, ret, EACCES, "too many strings");
+ ret = krb5_acl_match_string(context, "foo bar", "ss", "foo", "bar");
+ RETVAL(context, ret, 0, "two strings");
+ ret = krb5_acl_match_string(context, "foo bar", "ss", "foo", "bar");
+ RETVAL(context, ret, 0, "two strings double space");
+ ret = krb5_acl_match_string(context, "foo \tbar", "ss", "foo", "bar");
+ RETVAL(context, ret, 0, "two strings space + tab");
+ ret = krb5_acl_match_string(context, "foo", "ss", "foo", "bar");
+ RETVAL(context, ret, EACCES, "one string, two format strings");
+ ret = krb5_acl_match_string(context, "foo", "ss", "foo", "foo");
+ RETVAL(context, ret, EACCES, "one string, two format strings (same)");
+ ret = krb5_acl_match_string(context, "foo \t", "s", "foo");
+ RETVAL(context, ret, 0, "ending space");
+
+ ret = krb5_acl_match_string(context, "foo/bar", "f", "foo/bar");
+ RETVAL(context, ret, 0, "liternal fnmatch");
+ ret = krb5_acl_match_string(context, "foo/bar", "f", "foo/*");
+ RETVAL(context, ret, 0, "foo/*");
+ ret = krb5_acl_match_string(context, "foo/bar.example.org", "f",
+ "foo/*.example.org");
+ RETVAL(context, ret, 0, "foo/*.example.org");
+ ret = krb5_acl_match_string(context, "foo/bar.example.com", "f",
+ "foo/*.example.org");
+ RETVAL(context, ret, EACCES, "foo/*.example.com");
+
+ ret = krb5_acl_match_string(context, "foo/bar/baz", "f", "foo/*/baz");
+ RETVAL(context, ret, 0, "foo/*/baz");
+
+ ret = krb5_acl_match_string(context, "foo", "r", &s1);
+ RETVAL(context, ret, 0, "ret 1");
+ STRINGMATCH(context, "ret 1 match", s1, "foo"); free(s1);
+
+ ret = krb5_acl_match_string(context, "foo bar", "rr", &s1, &s2);
+ RETVAL(context, ret, 0, "ret 2");
+ STRINGMATCH(context, "ret 2 match 1", s1, "foo"); free(s1);
+ STRINGMATCH(context, "ret 2 match 2", s2, "bar"); free(s2);
+
+ ret = krb5_acl_match_string(context, "foo bar", "sr", "bar", &s1);
+ RETVAL(context, ret, EACCES, "ret mismatch");
+ if (s1 != NULL) krb5_errx(context, 1, "s1 not NULL");
+
+ ret = krb5_acl_match_string(context, "foo", "l", "foo");
+ RETVAL(context, ret, EINVAL, "unknown letter");
+}
+
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+
+ setprogname(argv[0]);
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ test_match_string(context);
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_addr.c b/third_party/heimdal/lib/krb5/test_addr.c
new file mode 100644
index 0000000..79a55ff
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_addr.c
@@ -0,0 +1,239 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+
+static void
+print_addr(krb5_context context, const char *addr)
+{
+ krb5_addresses addresses;
+ krb5_error_code ret;
+ char buf[38];
+ char buf2[1000];
+ size_t len;
+ int i;
+
+ ret = krb5_parse_address(context, addr, &addresses);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_address");
+
+ if (addresses.len < 1)
+ krb5_err(context, 1, ret, "too few addresses");
+
+ for (i = 0; i < addresses.len; i++) {
+ krb5_print_address(&addresses.val[i], buf, sizeof(buf), &len);
+#if 0
+ printf("addr %d: %s (%d/%d)\n", i, buf, (int)len, (int)strlen(buf));
+#endif
+ if (strlen(buf) > sizeof(buf))
+ krb5_err(context, 1, ret, "len %d larger then buf %d",
+ (int)strlen(buf), (int)sizeof(buf));
+ krb5_print_address(&addresses.val[i], buf2, sizeof(buf2), &len);
+#if 0
+ printf("addr %d: %s (%d/%d)\n", i, buf2, (int)len, (int)strlen(buf2));
+#endif
+ if (strlen(buf2) > sizeof(buf2))
+ krb5_err(context, 1, ret, "len %d larger then buf %d",
+ (int)strlen(buf2), (int)sizeof(buf2));
+
+ }
+ krb5_free_addresses(context, &addresses);
+
+}
+
+static void
+truncated_addr(krb5_context context, const char *addr,
+ size_t truncate_len, size_t outlen)
+{
+ krb5_addresses addresses;
+ krb5_error_code ret;
+ char *buf;
+ size_t len;
+
+ buf = ecalloc(1, outlen + 1);
+
+ ret = krb5_parse_address(context, addr, &addresses);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_address");
+
+ if (addresses.len != 1)
+ krb5_err(context, 1, ret, "addresses should be one");
+
+ krb5_print_address(&addresses.val[0], buf, truncate_len, &len);
+
+#if 0
+ printf("addr %s (%d/%d) should be %d\n", buf, (int)len, (int)strlen(buf), (int)outlen);
+#endif
+
+ if (truncate_len > strlen(buf) + 1)
+ krb5_err(context, 1, ret, "%s truncate_len %d larger then strlen %d source %s",
+ buf, (int)truncate_len, (int)strlen(buf), addr);
+
+ if (outlen != len)
+ krb5_err(context, 1, ret, "%s: outlen %d != len %d",
+ buf, (int)outlen, (int)strlen(buf));
+
+ krb5_print_address(&addresses.val[0], buf, outlen + 1, &len);
+
+#if 0
+ printf("addr %s (%d/%d)\n", buf, (int)len, (int)strlen(buf));
+#endif
+
+ if (len != outlen)
+ abort();
+ if (strlen(buf) != len)
+ abort();
+
+ krb5_free_addresses(context, &addresses);
+ free(buf);
+}
+
+static void
+check_truncation(krb5_context context, const char *addr)
+{
+ int i, len = strlen(addr);
+
+ truncated_addr(context, addr, len, len);
+
+ for (i = 0; i < len; i++)
+ truncated_addr(context, addr, i, len);
+}
+
+static void
+match_addr(krb5_context context, const char *range_addr,
+ const char *one_addr, int match)
+{
+ krb5_addresses range, one;
+ krb5_error_code ret;
+
+ ret = krb5_parse_address(context, range_addr, &range);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_address");
+
+ if (range.len != 1)
+ krb5_err(context, 1, ret, "wrong num of addresses");
+
+ ret = krb5_parse_address(context, one_addr, &one);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_address");
+
+ if (one.len != 1)
+ krb5_err(context, 1, ret, "wrong num of addresses");
+
+ if (krb5_address_order(context, &range.val[0], &one.val[0]) == 0) {
+ if (!match)
+ krb5_errx(context, 1, "match when one shouldn't be");
+ } else {
+ if (match)
+ krb5_errx(context, 1, "no match when one should be");
+ }
+
+ krb5_free_addresses(context, &range);
+ krb5_free_addresses(context, &one);
+}
+
+#ifdef _MSC_VER
+
+/* For the truncation tests, calling strcpy_s() or strcat_s() with a
+ size of 0 results in the invalid parameter handler being invoked.
+ For the debug version, the runtime also throws an assert. */
+
+static void
+inv_param_handler(const wchar_t* expression,
+ const wchar_t* function,
+ const wchar_t* file,
+ unsigned int line,
+ uintptr_t pReserved)
+{
+ printf("Invalid parameter handler invoked for: %S in %S(%d) [%S]\n",
+ function, file, line, expression);
+}
+
+static _invalid_parameter_handler _inv_old = NULL;
+
+#define SET_INVALID_PARAM_HANDLER _inv_old = _set_invalid_parameter_handler(inv_param_handler)
+
+#else
+
+#define SET_INVALID_PARAM_HANDLER ((void) 0)
+
+#endif
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+
+ SET_INVALID_PARAM_HANDLER;
+
+ setprogname(argv[0]);
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ print_addr(context, "RANGE:127.0.0.0/8");
+ print_addr(context, "RANGE:127.0.0.0/24");
+ print_addr(context, "RANGE:IPv4:127.0.0.0-IPv4:127.0.0.255");
+ print_addr(context, "RANGE:130.237.237.4/29");
+#ifdef HAVE_IPV6
+ print_addr(context, "RANGE:2001:db8:1:2:3:4:1428:7ab/64");
+ print_addr(context, "RANGE:IPv6:fe80::209:6bff:fea0:e522/64");
+ print_addr(context, "RANGE:IPv6:fe80::-IPv6:fe80::ffff:ffff:ffff:ffff");
+ print_addr(context, "RANGE:fe80::-fe80::ffff:ffff:ffff:ffff");
+#endif
+
+ check_truncation(context, "IPv4:127.0.0.0");
+ check_truncation(context, "RANGE:IPv4:127.0.0.0-IPv4:127.0.0.255");
+#ifdef HAVE_IPV6
+ check_truncation(context, "IPv6:::");
+ check_truncation(context, "IPv6:::1");
+ check_truncation(context, "IPv6:2001:db8:1:2:3:4:1428:7ab");
+ check_truncation(context, "IPv6:fe80::209:0:0:0");
+ check_truncation(context, "IPv6:fe80::ffff:ffff:ffff:ffff");
+#endif
+
+ match_addr(context, "RANGE:127.0.0.0/8", "inet:127.0.0.0", 1);
+ match_addr(context, "RANGE:127.0.0.0/8", "inet:127.255.255.255", 1);
+ match_addr(context, "RANGE:127.0.0.0/8", "inet:128.0.0.0", 0);
+
+ match_addr(context, "RANGE:130.237.237.8/29", "inet:130.237.237.7", 0);
+ match_addr(context, "RANGE:130.237.237.8/29", "inet:130.237.237.8", 1);
+ match_addr(context, "RANGE:130.237.237.8/29", "inet:130.237.237.15", 1);
+ match_addr(context, "RANGE:130.237.237.8/29", "inet:130.237.237.16", 0);
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_alname.c b/third_party/heimdal/lib/krb5/test_alname.c
new file mode 100644
index 0000000..36775ad
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_alname.c
@@ -0,0 +1,219 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <getarg.h>
+#include <err.h>
+
+char localname[1024];
+static size_t lname_size = sizeof (localname);
+static int lname_size_arg = 0;
+static int simple_flag = 0;
+static int verbose_flag = 0;
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"lname-size", 0, arg_integer, &lname_size_arg,
+ "set localname size (0 means use default, must be 0..1023)", "integer" },
+ {"simple", 0, arg_flag, &simple_flag, /* Used for scripting */
+ "map the given principal and print the resulting localname", NULL },
+ {"verbose", 0, arg_flag, &verbose_flag,
+ "print the actual principal name as well as the localname", NULL },
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+test_alname(krb5_context context, krb5_const_realm realm,
+ const char *user, const char *inst,
+ const char *localuser, int ok)
+{
+ krb5_principal p;
+ krb5_error_code ret;
+ char *princ;
+
+ ret = krb5_make_principal(context, &p, realm, user, inst, NULL);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_build_principal");
+
+ ret = krb5_unparse_name(context, p, &princ);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_unparse_name");
+
+ ret = krb5_aname_to_localname(context, p, lname_size, localname);
+ krb5_free_principal(context, p);
+ if (ret) {
+ if (!ok) {
+ free(princ);
+ return;
+ }
+ krb5_err(context, 1, ret, "krb5_aname_to_localname: %s -> %s",
+ princ, localuser);
+ }
+ free(princ);
+
+ if (strcmp(localname, localuser) != 0) {
+ if (ok)
+ errx(1, "compared failed %s != %s (should have succeded)",
+ localname, localuser);
+ } else {
+ if (!ok)
+ errx(1, "compared failed %s == %s (should have failed)",
+ localname, localuser);
+ }
+
+}
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ krb5_realm realm;
+ int optidx = 0;
+ char *user;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ if (simple_flag) {
+ krb5_principal princ;
+ char *unparsed;
+ int status = 0;
+
+ /* Map then print the result and exit */
+ if (argc != 1)
+ errx(1, "One argument is required and it must be a principal name");
+
+ ret = krb5_parse_name(context, argv[0], &princ);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_build_principal");
+
+ ret = krb5_unparse_name(context, princ, &unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_unparse_name");
+
+ if (lname_size_arg > 0 && lname_size_arg < 1024)
+ lname_size = lname_size_arg;
+ else if (lname_size_arg != 0)
+ errx(1, "local name size must be between 0 and 1023 (inclusive)");
+
+ ret = krb5_aname_to_localname(context, princ, lname_size, localname);
+ if (ret == KRB5_NO_LOCALNAME) {
+ if (verbose_flag)
+ fprintf(stderr, "No mapping obtained for %s\n", unparsed);
+ exit(1);
+ }
+ switch (ret) {
+ case KRB5_PLUGIN_NO_HANDLE:
+ fprintf(stderr, "Error: KRB5_PLUGIN_NO_HANDLE leaked!\n");
+ status = 2;
+ break;
+ case KRB5_CONFIG_NOTENUFSPACE:
+ fprintf(stderr, "Error: lname-size (%lu) too small\n",
+ (long unsigned)lname_size);
+ status = 3;
+ break;
+ case 0:
+ if (verbose_flag)
+ printf("%s ", unparsed);
+ printf("%s\n", localname);
+ break;
+ default:
+ krb5_err(context, 4, ret, "krb5_aname_to_localname");
+ break;
+ }
+ free(unparsed);
+ krb5_free_principal(context, princ);
+ krb5_free_context(context);
+ exit(status);
+ }
+
+ if (argc != 1)
+ errx(1, "first argument should be a local user that is in root .k5login");
+
+ user = argv[0];
+
+ ret = krb5_get_default_realm(context, &realm);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_get_default_realm");
+
+ test_alname(context, realm, user, NULL, user, 1);
+ test_alname(context, realm, user, "root", "root", 1);
+
+ test_alname(context, "FOO.BAR.BAZ.KAKA", user, NULL, user, 0);
+ test_alname(context, "FOO.BAR.BAZ.KAKA", user, "root", "root", 0);
+
+ test_alname(context, realm, user, NULL,
+ "not-same-as-user", 0);
+ test_alname(context, realm, user, "root",
+ "not-same-as-user", 0);
+
+ test_alname(context, "FOO.BAR.BAZ.KAKA", user, NULL,
+ "not-same-as-user", 0);
+ test_alname(context, "FOO.BAR.BAZ.KAKA", user, "root",
+ "not-same-as-user", 0);
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_ap-req.c b/third_party/heimdal/lib/krb5/test_ap-req.c
new file mode 100644
index 0000000..0fd1078
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_ap-req.c
@@ -0,0 +1,228 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include <config.h>
+
+#include <sys/types.h>
+#include <stdio.h>
+#include <krb5.h>
+#include <err.h>
+#include <getarg.h>
+#include <roken.h>
+
+static int verify_pac = 1;
+static int server_any = 0;
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"verify-pac",0, arg_flag, &verify_pac,
+ "verify the PAC", NULL },
+ {"server-any",0, arg_flag, &server_any,
+ "let server pick the principal", NULL },
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "...");
+ exit (ret);
+}
+
+
+static void
+test_ap(krb5_context context,
+ krb5_principal target,
+ krb5_principal server,
+ krb5_keytab keytab,
+ krb5_ccache ccache,
+ const krb5_flags client_flags)
+{
+ krb5_error_code ret;
+ krb5_auth_context client_ac = NULL, server_ac = NULL;
+ krb5_data data;
+ krb5_flags server_flags;
+ krb5_ticket *ticket = NULL;
+ int32_t server_seq, client_seq;
+
+ ret = krb5_mk_req_exact(context,
+ &client_ac,
+ client_flags,
+ target,
+ NULL,
+ ccache,
+ &data);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_mk_req_exact");
+
+ ret = krb5_rd_req(context,
+ &server_ac,
+ &data,
+ server,
+ keytab,
+ &server_flags,
+ &ticket);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_rd_req");
+
+
+ if (server_flags & AP_OPTS_MUTUAL_REQUIRED) {
+ krb5_ap_rep_enc_part *repl;
+
+ krb5_data_free(&data);
+
+ if ((client_flags & AP_OPTS_MUTUAL_REQUIRED) == 0)
+ krb5_errx(context, 1, "client flag missing mutual req");
+
+ ret = krb5_mk_rep (context, server_ac, &data);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_mk_rep");
+
+ ret = krb5_rd_rep (context,
+ client_ac,
+ &data,
+ &repl);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_rd_rep");
+
+ krb5_free_ap_rep_enc_part (context, repl);
+ } else {
+ if (client_flags & AP_OPTS_MUTUAL_REQUIRED)
+ krb5_errx(context, 1, "server flag missing mutual req");
+ }
+
+ krb5_auth_con_getremoteseqnumber(context, server_ac, &server_seq);
+ krb5_auth_con_getremoteseqnumber(context, client_ac, &client_seq);
+ if (server_seq != client_seq)
+ krb5_errx(context, 1, "seq num differ");
+
+ krb5_auth_con_getlocalseqnumber(context, server_ac, &server_seq);
+ krb5_auth_con_getlocalseqnumber(context, client_ac, &client_seq);
+ if (server_seq != client_seq)
+ krb5_errx(context, 1, "seq num differ");
+
+ krb5_data_free(&data);
+ krb5_auth_con_free(context, client_ac);
+ krb5_auth_con_free(context, server_ac);
+
+ if (verify_pac) {
+ krb5_pac pac;
+
+ ret = krb5_ticket_get_authorization_data_type(context,
+ ticket,
+ KRB5_AUTHDATA_WIN2K_PAC,
+ &data);
+ if (ret)
+ krb5_err(context, 1, ret, "get pac");
+
+ ret = krb5_pac_parse(context, data.data, data.length, &pac);
+ if (ret)
+ krb5_err(context, 1, ret, "pac parse");
+
+ krb5_pac_free(context, pac);
+ krb5_data_free(&data);
+ }
+
+ krb5_free_ticket(context, ticket);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ int optidx = 0;
+ const char *principal, *keytab, *ccache;
+ krb5_ccache id;
+ krb5_keytab kt;
+ krb5_principal sprincipal, server;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (argc < 3)
+ usage(1);
+
+ principal = argv[0];
+ keytab = argv[1];
+ ccache = argv[2];
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ ret = krb5_cc_resolve(context, ccache, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_resolve");
+
+ ret = krb5_parse_name(context, principal, &sprincipal);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_kt_resolve(context, keytab, &kt);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_resolve");
+
+ if (server_any)
+ server = NULL;
+ else
+ server = sprincipal;
+
+ test_ap(context, sprincipal, server, kt, id, 0);
+ test_ap(context, sprincipal, server, kt, id, AP_OPTS_MUTUAL_REQUIRED);
+
+ krb5_cc_close(context, id);
+ krb5_kt_close(context, kt);
+ krb5_free_principal(context, sprincipal);
+
+ krb5_free_context(context);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/test_canon.c b/third_party/heimdal/lib/krb5/test_canon.c
new file mode 100755
index 0000000..8389c02
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_canon.c
@@ -0,0 +1,177 @@
+/*
+ * Copyright (c) 2011, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "krb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+#if 0
+#include <stdio.h>
+#include <string.h>
+#include <strings.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <krb5.h>
+#endif
+
+int
+main(int argc, char **argv)
+{
+ krb5_error_code retval;
+ krb5_context context;
+ krb5_principal princ = NULL;
+ krb5_principal me = NULL;
+ krb5_principal cmp_to_princ = NULL;
+ krb5_ccache cc = NULL;
+ krb5_creds *out_creds = NULL;
+ krb5_keytab kt = NULL;
+ krb5_keytab_entry ktent;
+ krb5_creds in_creds;
+ char *hostname = NULL;
+ char *unparsed = NULL;
+ char *unparsed_canon = NULL;
+ char *during;
+ char *cmp_to = NULL;;
+ int do_kt = 0;
+ int do_get_creds = 0;
+ int opt;
+ int ret = 1;
+
+ memset(&ktent, 0, sizeof(ktent));
+
+ while ((opt = getopt(argc, argv, "hgkc:")) != -1) {
+ switch (opt) {
+ case 'g':
+ do_get_creds++;
+ break;
+ case 'k':
+ do_kt++;
+ break;
+ case 'c':
+ cmp_to = optarg;
+ break;
+ case 'h':
+ default:
+ fprintf(stderr, "Usage: %s [-g] [-k] [-c compare-to-principal] "
+ "[principal]\n", argv[0]);
+ return 1;
+ }
+ }
+
+ if (!do_get_creds && !do_kt && !cmp_to)
+ do_get_creds++;
+
+ if (optind < argc)
+ hostname = argv[optind];
+
+ during = "init_context";
+ retval = krb5_init_context(&context);
+ if (retval) goto err;
+
+ during = "sn2p";
+ retval = krb5_sname_to_principal(context, hostname, "host", KRB5_NT_SRV_HST, &princ);
+ if (retval) goto err;
+
+ during = "unparse of sname2princ";
+ retval = krb5_unparse_name(context, princ, &unparsed);
+ if (retval) goto err;
+ printf("krb5_sname_to_principal() output: %s\n", unparsed);
+
+ if (cmp_to) {
+ krb5_boolean eq;
+
+ during = "parsing principal name for comparison compare";
+ retval = krb5_parse_name(context, cmp_to, &cmp_to_princ);
+ if (retval) goto err;
+
+ eq = krb5_principal_compare(context, princ, cmp_to_princ);
+ printf("%s %s %s\n", unparsed, eq ? "==" : "!=", cmp_to);
+ }
+
+ if (do_get_creds) {
+ during = "ccdefault";
+ retval = krb5_cc_default(context, &cc);
+ if (retval) goto err;
+
+ during = "ccprinc";
+ retval = krb5_cc_get_principal(context, cc, &me);
+ if (retval) goto err;
+
+ memset(&in_creds, 0, sizeof(in_creds));
+ in_creds.client = me;
+ in_creds.server = princ;
+
+ during = "getcreds";
+ retval = krb5_get_credentials(context, 0, cc, &in_creds, &out_creds);
+ if (retval) goto err;
+
+ during = "unparsing principal name canonicalized by krb5_get_credentials()";
+ retval = krb5_unparse_name(context, in_creds.server, &unparsed_canon);
+ if (retval) goto err;
+ printf("Principal name as canonicalized by krb5_get_credentials() is %s\n", unparsed_canon);
+ }
+
+ if (do_kt) {
+ during = "getting keytab";
+ retval = krb5_kt_default(context, &kt);
+ if (retval) goto err;
+
+ during = "getting keytab ktent";
+ retval = krb5_kt_get_entry(context, kt, princ, 0, 0, &ktent);
+ if (retval) goto err;
+
+ during = "unparsing principal name canonicalized by krb5_kt_get_entry()";
+ retval = krb5_unparse_name(context, ktent.principal, &unparsed_canon);
+ if (retval) goto err;
+ printf("Principal name as canonicalized by krb5_kt_get_entry() is %s\n", unparsed_canon);
+ }
+
+ ret = 0;
+
+err:
+ krb5_free_principal(context, princ);
+ krb5_free_principal(context, me);
+ krb5_free_principal(context, cmp_to_princ);
+ krb5_xfree(unparsed);
+ krb5_xfree(unparsed_canon);
+ if (do_get_creds) {
+ krb5_free_creds(context, out_creds);
+ (void) krb5_cc_close(context, cc);
+ }
+ krb5_kt_free_entry(context, &ktent);
+ if (kt)
+ krb5_kt_close(context, kt);
+ krb5_free_context(context);
+ if (ret)
+ fprintf(stderr, "Failed while doing %s (%d)\n", during, retval);
+ return (ret);
+}
+
diff --git a/third_party/heimdal/lib/krb5/test_cc.c b/third_party/heimdal/lib/krb5/test_cc.c
new file mode 100644
index 0000000..0ca582e
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_cc.c
@@ -0,0 +1,1218 @@
+/*
+ * Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/*
+ * If this test fails with
+ *
+ * krb5_cc_gen_new: KEYRING: Key has been revoked
+ *
+ * then run
+ *
+ * keyctl new_session
+ */
+
+#include "krb5_locl.h"
+#include <getarg.h>
+#include <err.h>
+
+#ifdef HAVE_KEYUTILS_H
+#include <keyutils.h>
+#endif
+
+static const char *unlink_this;
+static const char *unlink_this2;
+static char *tmpdir;
+static int debug_flag = 0;
+static int version_flag = 0;
+static int help_flag = 0;
+
+#define TEST_CC_TEMPLATE "%{TEMP}/krb5-cc-test-XXXXXX"
+
+static void
+cleanup(void)
+{
+ char *s = NULL;
+
+ if (asprintf(&s, "%s/cc", tmpdir) > -1 && s != NULL)
+ unlink(s);
+ free(s);
+
+ if (asprintf(&s, "%s/scc", tmpdir) > -1 && s != NULL)
+ unlink(s);
+ free(s);
+
+ if (asprintf(&s, "%s/cccol/foobar+lha@H5L.SE", tmpdir) > -1 && s != NULL)
+ unlink(s);
+ free(s);
+
+ if (asprintf(&s, "%s/cccol/foobar+lha@SU.SE", tmpdir) > -1 && s != NULL)
+ unlink(s);
+ free(s);
+
+ if (asprintf(&s, "%s/cccol/foobar", tmpdir) > -1 && s != NULL)
+ unlink(s);
+ free(s);
+
+ if (asprintf(&s, "%s/cccol", tmpdir) > -1 && s != NULL)
+ rmdir(s);
+ free(s);
+
+ if (asprintf(&s, "%s/dcc/tkt.lha@H5L.SE", tmpdir) > -1 && s != NULL)
+ unlink(s);
+ free(s);
+
+ if (asprintf(&s, "%s/dcc/tkt.lha@SU.SE", tmpdir) > -1 && s != NULL)
+ unlink(s);
+ free(s);
+
+ if (asprintf(&s, "%s/dcc/tkt", tmpdir) > -1 && s != NULL)
+ unlink(s);
+ free(s);
+
+ if (asprintf(&s, "%s/dcc/primary", tmpdir) > -1 && s != NULL)
+ unlink(s);
+ free(s);
+
+ if (asprintf(&s, "%s/dcc", tmpdir) > -1 && s != NULL)
+ rmdir(s);
+ free(s);
+
+ if (unlink_this)
+ unlink(unlink_this);
+ unlink_this = NULL;
+ if (unlink_this2)
+ unlink(unlink_this2);
+ unlink_this2 = NULL;
+
+ rmdir(tmpdir);
+}
+
+static void
+make_dir(krb5_context context)
+{
+ krb5_error_code ret;
+ char *template = NULL;
+ char *dcc = NULL;
+
+ ret = _krb5_expand_path_tokens(context, TEST_CC_TEMPLATE, 1, &template);
+ if (ret)
+ krb5_err(context, 1, ret, "_krb5_expand_path_tokens(%s) failed",
+ TEST_CC_TEMPLATE);
+ if ((tmpdir = mkdtemp(template)) == NULL)
+ krb5_err(context, 1, errno, "mkdtemp(%s) failed", template);
+ if (asprintf(&dcc, "%s/dcc", tmpdir) == -1 || dcc == NULL)
+ krb5_err(context, 1, errno, "asprintf failed");
+ free(dcc);
+ atexit(cleanup);
+}
+
+static void
+test_default_name(krb5_context context)
+{
+ krb5_error_code ret;
+ const char *p;
+ char *test_cc_name = NULL;
+ const char *p3;
+ char *p1, *p2;
+ char *exp_test_cc_name;
+
+ if (asprintf(&test_cc_name, "%s/cc", tmpdir) == -1 || test_cc_name == NULL)
+ krb5_err(context, 1, errno, "out of memory");
+
+ /* Convert slashes to backslashes */
+ ret = _krb5_expand_path_tokens(context, test_cc_name, 1,
+ &exp_test_cc_name);
+ if (ret)
+ krb5_err(context, 1, ret, "_krb5_expand_path_tokens(%s) failed",
+ test_cc_name);
+ free(test_cc_name);
+ test_cc_name = NULL;
+
+ p = krb5_cc_default_name(context);
+ if (p == NULL)
+ krb5_errx (context, 1, "krb5_cc_default_name 1 failed");
+ p1 = estrdup(p);
+
+ ret = krb5_cc_set_default_name(context, NULL);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_set_default_name(NULL) failed");
+
+ p = krb5_cc_default_name(context);
+ if (p == NULL)
+ krb5_errx (context, 1, "krb5_cc_default_name 2 failed");
+ p2 = estrdup(p);
+
+ if (strcmp(p1, p2) != 0)
+ krb5_errx (context, 1, "krb5_cc_default_name no longer same");
+
+ ret = krb5_cc_set_default_name(context, exp_test_cc_name);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_set_default_name(%s) failed",
+ exp_test_cc_name);
+
+ p = krb5_cc_default_name(context);
+ if (p == NULL)
+ krb5_errx (context, 1, "krb5_cc_default_name 2 failed");
+
+ if (strncmp(p, "FILE:", sizeof("FILE:") - 1) == 0)
+ p3 = p + sizeof("FILE:") - 1;
+ else
+ p3 = p;
+
+ if (strcmp(exp_test_cc_name, p3) != 0) {
+#ifdef WIN32
+ krb5_warnx(context, 1,
+ "krb5_cc_default_name() returned %s; expected %s",
+ p, exp_test_cc_name);
+#else
+ krb5_errx(context, 1,
+ "krb5_cc_default_name() returned %s; expected %s",
+ p, exp_test_cc_name);
+#endif
+ }
+
+ free(exp_test_cc_name);
+ free(p1);
+ free(p2);
+}
+
+/*
+ * Check that a closed cc still keeps it data and that it's no longer
+ * there when it's destroyed.
+ */
+
+static void
+test_mcache(krb5_context context)
+{
+ krb5_error_code ret;
+ krb5_ccache id, id2;
+ const char *nc, *tc;
+ char *c;
+ krb5_principal p, p2;
+
+ ret = krb5_parse_name(context, "lha@SU.SE", &p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_new_unique");
+
+ ret = krb5_cc_initialize(context, id, p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_initialize");
+
+ nc = krb5_cc_get_name(context, id);
+ if (nc == NULL)
+ krb5_errx(context, 1, "krb5_cc_get_name");
+
+ tc = krb5_cc_get_type(context, id);
+ if (tc == NULL)
+ krb5_errx(context, 1, "krb5_cc_get_name");
+
+ if (asprintf(&c, "%s:%s", tc, nc) < 0 || c == NULL)
+ errx(1, "malloc");
+
+ krb5_cc_close(context, id);
+
+ ret = krb5_cc_resolve(context, c, &id2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_resolve");
+
+ ret = krb5_cc_get_principal(context, id2, &p2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_get_principal");
+
+ if (krb5_principal_compare(context, p, p2) == FALSE)
+ krb5_errx(context, 1, "p != p2");
+
+ krb5_cc_destroy(context, id2);
+ krb5_free_principal(context, p);
+ krb5_free_principal(context, p2);
+
+ ret = krb5_cc_resolve(context, c, &id2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_resolve");
+
+ ret = krb5_cc_get_principal(context, id2, &p2);
+ if (ret == 0)
+ krb5_errx(context, 1, "krb5_cc_get_principal");
+
+ krb5_cc_destroy(context, id2);
+ free(c);
+}
+
+/*
+ * Test that init works on a destroyed cc.
+ */
+
+static void
+test_init_vs_destroy(krb5_context context, const char *type)
+{
+ krb5_error_code ret;
+ krb5_ccache id, id2;
+ krb5_principal p, p2;
+ char *n = NULL;
+
+ ret = krb5_parse_name(context, "lha@SU.SE", &p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_cc_new_unique(context, type, NULL, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_new_unique: %s", type);
+
+ if (asprintf(&n, "%s:%s",
+ krb5_cc_get_type(context, id),
+ krb5_cc_get_name(context, id)) < 0 || n == NULL)
+ errx(1, "malloc");
+
+ if (strcmp(krb5_cc_get_type(context, id), "FILE") == 0)
+ unlink_this = krb5_cc_get_name(context, id);
+
+ ret = krb5_cc_resolve(context, n, &id2);
+ free(n);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_resolve");
+
+ krb5_cc_destroy(context, id);
+
+ ret = krb5_cc_initialize(context, id2, p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_initialize");
+
+ ret = krb5_cc_get_principal(context, id2, &p2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_get_principal");
+
+ krb5_cc_destroy(context, id2);
+ unlink_this = NULL;
+ krb5_free_principal(context, p);
+ krb5_free_principal(context, p2);
+}
+
+static void
+test_cache_remove(krb5_context context, const char *type)
+{
+ krb5_error_code ret;
+ krb5_ccache id;
+ krb5_principal p;
+ krb5_creds cred, found;
+
+ ret = krb5_parse_name(context, "lha@SU.SE", &p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_cc_new_unique(context, type, NULL, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_gen_new: %s", type);
+
+ if (strcmp(krb5_cc_get_type(context, id), "FILE") == 0)
+ unlink_this = krb5_cc_get_name(context, id);
+
+ ret = krb5_cc_initialize(context, id, p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_initialize");
+
+ /* */
+ memset(&cred, 0, sizeof(cred));
+ ret = krb5_parse_name(context, "krbtgt/SU.SE@SU.SE", &cred.server);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+ ret = krb5_parse_name(context, "lha@SU.SE", &cred.client);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+ cred.times.endtime = time(NULL) + 300;
+
+ ret = krb5_cc_store_cred(context, id, &cred);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_store_cred");
+
+ ret = krb5_cc_remove_cred(context, id, 0, &cred);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_remove_cred");
+
+ memset(&found, 0, sizeof(found));
+ ret = krb5_cc_retrieve_cred(context, id, KRB5_TC_MATCH_TIMES,
+ &cred, &found);
+ if (ret == 0)
+ krb5_err(context, 1, ret, "krb5_cc_remove_cred didn't");
+
+ ret = krb5_cc_destroy(context, id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_destroy");
+ unlink_this = NULL;
+
+ krb5_free_principal(context, p);
+ krb5_free_principal(context, cred.server);
+ krb5_free_principal(context, cred.client);
+}
+
+static void
+test_mcc_default(void)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ krb5_ccache id, id2;
+ int i;
+
+ for (i = 0; i < 10; i++) {
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_init_context");
+
+ ret = krb5_cc_set_default_name(context, "MEMORY:foo");
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_set_default_name");
+
+ ret = krb5_cc_default(context, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_default");
+
+ ret = krb5_cc_default(context, &id2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_default");
+
+ ret = krb5_cc_close(context, id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_close");
+
+ ret = krb5_cc_close(context, id2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_close");
+
+ krb5_free_context(context);
+ }
+}
+
+struct {
+ char *str;
+ int fail;
+ char *res;
+} cc_names[] = {
+ { "foo", 0, "foo" },
+ { "foo%}", 0, "foo%}" },
+ { "%{uid}", 0, NULL },
+ { "%{euid}", 0, NULL },
+ { "%{username}", 0, NULL },
+ { "foo%{null}", 0, "foo" },
+ { "foo%{null}bar", 0, "foobar" },
+ { "%{", 1, NULL },
+ { "%{foo %{", 1, NULL },
+ { "%{{", 1, NULL },
+ { "%{{}", 1, NULL },
+ { "%{nulll}", 1, NULL },
+ { "%{does not exist}", 1, NULL },
+ { "%{}", 1, NULL },
+#ifdef WIN32
+ { "%{APPDATA}", 0, NULL },
+ { "%{COMMON_APPDATA}", 0, NULL},
+ { "%{LOCAL_APPDATA}", 0, NULL},
+ { "%{SYSTEM}", 0, NULL},
+ { "%{WINDOWS}", 0, NULL},
+ { "%{TEMP}", 0, NULL},
+ { "%{USERID}", 0, NULL},
+ { "%{uid}", 0, NULL},
+ { "%{USERCONFIG}", 0, NULL},
+ { "%{COMMONCONFIG}", 0, NULL},
+ { "%{LIBDIR}", 0, NULL},
+ { "%{BINDIR}", 0, NULL},
+ { "%{LIBEXEC}", 0, NULL},
+ { "%{SBINDIR}", 0, NULL},
+#endif
+};
+
+static void
+test_def_cc_name(krb5_context context)
+{
+ krb5_error_code ret;
+ char *str;
+ int i;
+
+ for (i = 0; i < sizeof(cc_names)/sizeof(cc_names[0]); i++) {
+ ret = _krb5_expand_default_cc_name(context, cc_names[i].str, &str);
+ if (ret) {
+ if (cc_names[i].fail == 0)
+ krb5_errx(context, 1, "test %d \"%s\" failed",
+ i, cc_names[i].str);
+ } else {
+ if (cc_names[i].fail)
+ krb5_errx(context, 1, "test %d \"%s\" was successful",
+ i, cc_names[i].str);
+ if (cc_names[i].res && strcmp(cc_names[i].res, str) != 0)
+ krb5_errx(context, 1, "test %d %s != %s",
+ i, cc_names[i].res, str);
+ if (debug_flag)
+ printf("%s => %s\n", cc_names[i].str, str);
+ free(str);
+ }
+ }
+}
+
+static void
+test_cache_find(krb5_context context, const char *principal, int find)
+{
+ krb5_principal client;
+ krb5_error_code ret;
+ krb5_ccache id = NULL;
+
+ ret = krb5_parse_name(context, principal, &client);
+ if (ret)
+ krb5_err(context, 1, ret, "parse_name for %s failed", principal);
+
+ ret = krb5_cc_cache_match(context, client, &id);
+ if (ret && find)
+ krb5_err(context, 1, ret, "cc_cache_match for %s failed", principal);
+ if (ret == 0 && !find)
+ krb5_err(context, 1, ret, "cc_cache_match for %s found", principal);
+
+ if (id)
+ krb5_cc_close(context, id);
+ krb5_free_principal(context, client);
+}
+
+
+static void
+test_cache_iter(krb5_context context, const char *type, int destroy)
+{
+ krb5_cc_cache_cursor cursor;
+ krb5_error_code ret;
+ krb5_ccache id;
+
+ ret = krb5_cc_cache_get_first (context, type, &cursor);
+ if (ret == KRB5_CC_NOSUPP)
+ return;
+ else if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_cache_get_first(%s)", type);
+
+
+ while ((ret = krb5_cc_cache_next (context, cursor, &id)) == 0) {
+ krb5_principal principal;
+ char *name;
+
+ heim_assert(id != NULL, "credentials cache is non-NULL");
+ if (debug_flag)
+ printf("name: %s\n", krb5_cc_get_name(context, id));
+ ret = krb5_cc_get_principal(context, id, &principal);
+ if (ret == 0) {
+ ret = krb5_unparse_name(context, principal, &name);
+ if (ret == 0) {
+ if (debug_flag)
+ printf("\tprincipal: %s\n", name);
+ free(name);
+ }
+ krb5_free_principal(context, principal);
+ }
+ if (destroy)
+ krb5_cc_destroy(context, id);
+ else
+ krb5_cc_close(context, id);
+ }
+
+ krb5_cc_cache_end_seq_get(context, cursor);
+}
+
+static void
+test_cache_iter_all(krb5_context context)
+{
+ krb5_cccol_cursor cursor;
+ krb5_error_code ret;
+ krb5_ccache id;
+
+ ret = krb5_cccol_cursor_new (context, &cursor);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cccol_cursor_new");
+
+
+ while ((ret = krb5_cccol_cursor_next (context, cursor, &id)) == 0 && id != NULL) {
+ krb5_principal principal;
+ char *name;
+
+ if (debug_flag)
+ printf("name: %s\n", krb5_cc_get_name(context, id));
+ ret = krb5_cc_get_principal(context, id, &principal);
+ if (ret == 0) {
+ ret = krb5_unparse_name(context, principal, &name);
+ if (ret == 0) {
+ if (debug_flag)
+ printf("\tprincipal: %s\n", name);
+ free(name);
+ }
+ krb5_free_principal(context, principal);
+ }
+ krb5_cc_close(context, id);
+ }
+
+ krb5_cccol_cursor_free(context, &cursor);
+}
+
+
+static void
+test_copy(krb5_context context, const char *from, const char *to)
+{
+ krb5_ccache fromid, toid;
+ krb5_error_code ret;
+ krb5_principal p, p2;
+
+ ret = krb5_parse_name(context, "lha@SU.SE", &p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_cc_new_unique(context, from, NULL, &fromid);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_new_unique: %s", from);
+
+ if (strcmp(krb5_cc_get_type(context, fromid), "FILE") == 0)
+ unlink_this = krb5_cc_get_name(context, fromid);
+
+ ret = krb5_cc_initialize(context, fromid, p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_initialize");
+
+ ret = krb5_cc_new_unique(context, to, NULL, &toid);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_gen_new: %s", to);
+
+ if (strcmp(krb5_cc_get_type(context, toid), "FILE") == 0)
+ unlink_this2 = krb5_cc_get_name(context, toid);
+
+ ret = krb5_cc_copy_cache(context, fromid, toid);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_copy_cache");
+
+ ret = krb5_cc_get_principal(context, toid, &p2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_get_principal");
+
+ if (krb5_principal_compare(context, p, p2) == FALSE)
+ krb5_errx(context, 1, "p != p2");
+
+ krb5_free_principal(context, p);
+ krb5_free_principal(context, p2);
+
+ krb5_cc_destroy(context, fromid);
+ krb5_cc_destroy(context, toid);
+ unlink_this = unlink_this2 = NULL;
+}
+
+static void
+test_move(krb5_context context, const char *type)
+{
+ const krb5_cc_ops *ops;
+ krb5_ccache fromid, toid;
+ krb5_error_code ret;
+ krb5_principal p, p2;
+ krb5_creds cred, tocred;
+
+ ops = krb5_cc_get_prefix_ops(context, type);
+ if (ops == NULL)
+ return;
+
+ ret = krb5_cc_new_unique(context, type, NULL, &fromid);
+ if (ret == KRB5_CC_NOSUPP)
+ return;
+ else if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_new_unique: %s", type);
+
+ ret = krb5_parse_name(context, "lha@SU.SE", &p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_cc_initialize(context, fromid, p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_initialize");
+
+ memset(&cred, 0, sizeof(cred));
+ ret = krb5_parse_name(context, "krbtgt/SU.SE@SU.SE", &cred.server);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+ ret = krb5_parse_name(context, "lha@SU.SE", &cred.client);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_cc_store_cred(context, fromid, &cred);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_store_cred");
+
+
+ ret = krb5_cc_new_unique(context, type, NULL, &toid);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_new_unique");
+
+ ret = krb5_cc_move(context, fromid, toid);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_move");
+
+ ret = krb5_cc_get_principal(context, toid, &p2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_get_principal");
+
+ if (krb5_principal_compare(context, p, p2) == FALSE)
+ krb5_errx(context, 1, "p != p2");
+
+ ret = krb5_cc_retrieve_cred(context, toid, 0, &cred, &tocred);
+ if (ret)
+ krb5_errx(context, 1, "move failed");
+ krb5_free_cred_contents(context, &cred);
+ krb5_free_cred_contents(context, &tocred);
+
+ krb5_free_principal(context, p);
+ krb5_free_principal(context, p2);
+ krb5_cc_destroy(context, toid);
+}
+
+
+static void
+test_prefix_ops(krb5_context context, const char *name, const krb5_cc_ops *ops)
+{
+ const krb5_cc_ops *o;
+
+ o = krb5_cc_get_prefix_ops(context, name);
+ if (o == NULL)
+ krb5_errx(context, 1, "found no match for prefix '%s'", name);
+ if (strcmp(o->prefix, ops->prefix) != 0)
+ krb5_errx(context, 1, "ops for prefix '%s' is not "
+ "the expected %s != %s", name, o->prefix, ops->prefix);
+}
+
+static void
+test_cc_config(krb5_context context, const char *cc_type,
+ const char *cc_name, size_t count)
+{
+ krb5_error_code ret;
+ krb5_principal p;
+ krb5_ccache id;
+ unsigned int i;
+
+ ret = krb5_cc_new_unique(context, cc_type, cc_name, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_new_unique");
+
+ ret = krb5_parse_name(context, "lha@SU.SE", &p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_cc_initialize(context, id, p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_initialize");
+
+ for (i = 0; i < count; i++) {
+ krb5_data data, data2;
+ const char *name = "foo";
+ krb5_principal p1 = NULL;
+
+ if (i & 1)
+ p1 = p;
+
+ data.data = rk_UNCONST(name);
+ data.length = strlen(name);
+
+ /*
+ * Because of how krb5_cc_set_config() this will also test
+ * krb5_cc_remove_cred().
+ */
+ ret = krb5_cc_set_config(context, id, p1, "FriendlyName", &data);
+ if (ret)
+ krb5_errx(context, 1, "krb5_cc_set_config: add");
+
+ ret = krb5_cc_get_config(context, id, p1, "FriendlyName", &data2);
+ if (ret)
+ krb5_errx(context, 1, "krb5_cc_get_config: first");
+
+ if (data.length != data2.length ||
+ memcmp(data.data, data2.data, data.length) != 0)
+ krb5_errx(context, 1, "krb5_cc_get_config: did not fetch what was set");
+
+ krb5_data_free(&data2);
+
+ data.data = rk_UNCONST("bar");
+ data.length = strlen("bar");
+
+ ret = krb5_cc_set_config(context, id, p1, "FriendlyName", &data);
+ if (ret)
+ krb5_errx(context, 1, "krb5_cc_set_config: add -second");
+
+ ret = krb5_cc_get_config(context, id, p1, "FriendlyName", &data2);
+ if (ret)
+ krb5_errx(context, 1, "krb5_cc_get_config: second");
+
+ if (data.length != data2.length ||
+ memcmp(data.data, data2.data, data.length) != 0)
+ krb5_errx(context, 1, "krb5_cc_get_config: replace failed");
+
+ krb5_data_free(&data2);
+
+ ret = krb5_cc_set_config(context, id, p1, "FriendlyName", NULL);
+ if (ret)
+ krb5_errx(context, 1, "krb5_cc_set_config: delete");
+
+ ret = krb5_cc_get_config(context, id, p1, "FriendlyName", &data2);
+ if (ret == 0)
+ krb5_errx(context, 1, "krb5_cc_get_config: non-existant");
+
+ if (data2.length)
+ krb5_errx(context, 1, "krb5_cc_get_config: delete failed");
+ }
+
+ krb5_cc_destroy(context, id);
+ krb5_free_principal(context, p);
+}
+
+static krb5_error_code
+test_cccol(krb5_context context, const char *def_cccol, const char **what)
+{
+ krb5_cc_cache_cursor cursor;
+ krb5_error_code ret;
+ krb5_principal p1, p2;
+ krb5_ccache id, id1, id2;
+ krb5_creds cred1, cred2;
+ size_t match1 = 0;
+ size_t match2 = 0;
+
+ memset(&cred1, 0, sizeof(cred1));
+ memset(&cred2, 0, sizeof(cred2));
+
+ *what = "krb5_parse_name";
+ ret = krb5_parse_name(context, "krbtgt/SU.SE@SU.SE", &cred1.server);
+ if (ret) return ret;
+ ret = krb5_parse_name(context, "lha@SU.SE", &cred1.client);
+ if (ret) return ret;
+ ret = krb5_parse_name(context, "krbtgt/H5L.SE@H5L.SE", &cred2.server);
+ if (ret) return ret;
+ ret = krb5_parse_name(context, "lha@H5L.SE", &cred2.client);
+ if (ret) return ret;
+ *what = "krb5_cc_set_default_name";
+ ret = krb5_cc_set_default_name(context, def_cccol);
+ if (ret) return ret;
+ *what = "krb5_cc_default";
+ ret = krb5_cc_default(context, &id1);
+ if (ret) return ret;
+ *what = "krb5_cc_initialize";
+ ret = krb5_cc_initialize(context, id1, cred1.client);
+ if (ret) return ret;
+ *what = "krb5_cc_store_cred";
+ ret = krb5_cc_store_cred(context, id1, &cred1);
+ if (ret) return ret;
+ *what = "krb5_cc_resolve";
+ ret = krb5_cc_resolve_for(context, NULL, def_cccol, cred2.client, &id2);
+ if (ret) return ret;
+ *what = "krb5_cc_initialize";
+ ret = krb5_cc_initialize(context, id2, cred2.client);
+ if (ret) return ret;
+ *what = "krb5_cc_store_cred";
+ ret = krb5_cc_store_cred(context, id2, &cred2);
+ if (ret) return ret;
+
+ krb5_cc_close(context, id1);
+ krb5_cc_close(context, id2);
+ id1 = id2 = NULL;
+
+ *what = "krb5_cc_default";
+ ret = krb5_cc_default(context, &id1);
+ if (ret) return ret;
+ *what = "krb5_cc_resolve";
+ ret = krb5_cc_resolve_for(context, NULL, def_cccol, cred2.client, &id2);
+ if (ret) return ret;
+
+ *what = "krb5_cc_get_principal";
+ ret = krb5_cc_get_principal(context, id1, &p1);
+ if (ret) return ret;
+ ret = krb5_cc_get_principal(context, id2, &p2);
+ if (ret) return ret;
+
+ if (!krb5_principal_compare(context, p1, cred1.client)) {
+ char *u1 = NULL;
+ char *u2 = NULL;
+
+ (void) krb5_unparse_name(context, p1, &u1);
+ (void) krb5_unparse_name(context, cred1.client, &u2);
+ warnx("Inconsistent principals for ccaches in %s: %s vs %s "
+ "(expected lha@SU.SE)", def_cccol, u1, u2);
+ return EINVAL;
+ }
+ if (!krb5_principal_compare(context, p2, cred2.client)) {
+ char *u1 = NULL;
+ char *u2 = NULL;
+
+ (void) krb5_unparse_name(context, p2, &u1);
+ (void) krb5_unparse_name(context, cred2.client, &u2);
+ warnx("Inconsistent principals for ccaches in %s: %s and %s "
+ "(expected lha@H5L.SE)", def_cccol, u1, u2);
+ return EINVAL;
+ }
+ krb5_free_principal(context, p1);
+ krb5_free_principal(context, p2);
+
+ *what = "krb5_cc_cache_get_first";
+ ret = krb5_cc_cache_get_first(context, NULL, &cursor);
+ if (ret) return ret;
+ *what = "krb5_cc_cache_next";
+ while (krb5_cc_cache_next(context, cursor, &id) == 0) {
+ krb5_principal p;
+
+ *what = "krb5_cc_get_principal";
+ ret = krb5_cc_get_principal(context, id, &p);
+ if (ret) return ret;
+ if (krb5_principal_compare(context, p, cred1.client))
+ match1++;
+ else if (krb5_principal_compare(context, p, cred2.client))
+ match2++;
+ krb5_free_principal(context, p);
+ krb5_cc_close(context, id);
+ }
+ (void) krb5_cc_cache_end_seq_get(context, cursor);
+
+ *what = "cccol iteration inconsistency";
+ if (match1 != 1 || match2 != 1)
+ return EINVAL;
+
+ krb5_cc_close(context, id1);
+ krb5_cc_close(context, id2);
+
+ krb5_free_cred_contents(context, &cred1);
+ krb5_free_cred_contents(context, &cred2);
+
+ return 0;
+}
+
+static void
+test_cccol_dcache(krb5_context context)
+{
+ krb5_error_code ret;
+ char *dcc = NULL;
+ const char *what;
+
+ if (asprintf(&dcc, "DIR:%s/dcc", tmpdir) == -1 || dcc == NULL)
+ krb5_err(context, 1, errno, "asprintf");
+
+ ret = test_cccol(context, dcc, &what);
+ free(dcc);
+ if (ret)
+ krb5_err(context, 1, ret, "%s", what);
+}
+
+static void
+test_cccol_scache(krb5_context context)
+{
+ krb5_error_code ret;
+ char *scache = NULL;
+ const char *what;
+ int fd;
+
+ if (asprintf(&scache, "SCC:%s/scache", tmpdir) == -1 || scache == NULL)
+ krb5_err(context, 1, errno, "asprintf");
+ if ((fd = open(scache + sizeof("SCC:") - 1, O_CREAT | O_RDWR, 0600)) == -1)
+ krb5_err(context, 1, errno, "open(%s)", scache + sizeof("SCC:") - 1);
+ (void) close(fd);
+
+ ret = test_cccol(context, scache, &what);
+ (void) unlink(scache + sizeof("SCC:") - 1);
+ free(scache);
+ if (ret)
+ krb5_err(context, 1, ret, "%s", what);
+}
+
+
+static struct getargs args[] = {
+ {"debug", 'd', arg_flag, &debug_flag,
+ "turn on debuggin", NULL },
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "hostname ...");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ int optidx = 0;
+ krb5_ccache id1, id2;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ make_dir(context);
+
+ test_cache_remove(context, krb5_cc_type_file);
+ test_cache_remove(context, krb5_cc_type_memory);
+#ifdef USE_SQLITE
+ test_cache_remove(context, krb5_cc_type_scc);
+#endif
+#ifdef HAVE_KEYUTILS_H
+ keyctl_join_session_keyring(NULL);
+ test_cache_remove(context, krb5_cc_type_keyring);
+#endif
+
+ test_default_name(context);
+ test_mcache(context);
+ /*
+ * XXX Make sure to set default ccache names for each cc type!
+ * Otherwise we clobber the user's ccaches.
+ */
+ test_init_vs_destroy(context, krb5_cc_type_memory);
+ test_init_vs_destroy(context, krb5_cc_type_file);
+#if 0
+ test_init_vs_destroy(context, krb5_cc_type_api);
+#endif
+ /*
+ * Cleanup so we can check that the permissions on the directory created by
+ * scc are correct.
+ */
+ cleanup();
+ test_init_vs_destroy(context, krb5_cc_type_scc);
+
+#if defined(S_IRWXG) && defined(S_IRWXO)
+ {
+ struct stat st;
+
+ if (stat(tmpdir, &st) == 0) {
+ if ((st.st_mode & S_IRWXG) ||
+ (st.st_mode & S_IRWXO))
+ krb5_errx(context, 1,
+ "SQLite3 ccache dir perms wrong: %d", st.st_mode);
+ }
+ }
+#endif
+ test_init_vs_destroy(context, krb5_cc_type_dcc);
+#ifdef HAVE_KEYUTILS_H
+ test_init_vs_destroy(context, krb5_cc_type_keyring);
+#endif
+ test_mcc_default();
+ test_def_cc_name(context);
+
+ test_cache_iter_all(context);
+
+ test_cache_iter(context, krb5_cc_type_memory, 0);
+ {
+ krb5_principal p;
+ krb5_cc_new_unique(context, krb5_cc_type_memory, "bar", &id1);
+ krb5_cc_new_unique(context, krb5_cc_type_memory, "baz", &id2);
+ krb5_parse_name(context, "lha@SU.SE", &p);
+ krb5_cc_initialize(context, id1, p);
+ krb5_free_principal(context, p);
+ }
+
+ test_cache_find(context, "lha@SU.SE", 1);
+ test_cache_find(context, "hulabundulahotentot@SU.SE", 0);
+
+ /*
+ * XXX We should compose and krb5_cc_set_default_name() a default ccache
+ * for each cc type that we test with test_cache_iter(), and we should do
+ * that inside test_cache_iter().
+ *
+ * Alternatively we should remove test_cache_iter() in favor of
+ * test_cccol(), which is a much more complete test.
+ */
+ test_cache_iter(context, krb5_cc_type_memory, 0);
+ test_cache_iter(context, krb5_cc_type_memory, 1);
+ test_cache_iter(context, krb5_cc_type_memory, 0);
+ test_cache_iter(context, krb5_cc_type_file, 0);
+ test_cache_iter(context, krb5_cc_type_api, 0);
+ test_cache_iter(context, krb5_cc_type_scc, 0);
+ test_cache_iter(context, krb5_cc_type_scc, 1);
+#if 0
+ test_cache_iter(context, krb5_cc_type_dcc, 0);
+ test_cache_iter(context, krb5_cc_type_dcc, 1);
+#endif
+#ifdef HAVE_KEYUTILS_H
+ test_cache_iter(context, krb5_cc_type_keyring, 0);
+ test_cache_iter(context, krb5_cc_type_keyring, 1);
+#endif
+
+ test_copy(context, krb5_cc_type_file, krb5_cc_type_file);
+ test_copy(context, krb5_cc_type_memory, krb5_cc_type_memory);
+ test_copy(context, krb5_cc_type_file, krb5_cc_type_memory);
+ test_copy(context, krb5_cc_type_memory, krb5_cc_type_file);
+ test_copy(context, krb5_cc_type_scc, krb5_cc_type_file);
+ test_copy(context, krb5_cc_type_file, krb5_cc_type_scc);
+ test_copy(context, krb5_cc_type_scc, krb5_cc_type_memory);
+ test_copy(context, krb5_cc_type_memory, krb5_cc_type_scc);
+#if 0
+ test_copy(context, krb5_cc_type_dcc, krb5_cc_type_memory);
+ test_copy(context, krb5_cc_type_dcc, krb5_cc_type_file);
+ test_copy(context, krb5_cc_type_dcc, krb5_cc_type_scc);
+#endif
+#ifdef HAVE_KEYUTILS_H
+ test_copy(context, krb5_cc_type_keyring, krb5_cc_type_file);
+ test_copy(context, krb5_cc_type_file, krb5_cc_type_file);
+ test_copy(context, "KEYRING:", "KEYRING:bar");
+ test_copy(context, "KEYRING:bar", "KEYRING:baz");
+# ifdef HAVE_KEYCTL_GET_PERSISTENT
+ test_copy(context, krb5_cc_type_file, "KEYRING:persistent");
+ test_copy(context, "KEYRING:persistent:", krb5_cc_type_file);
+ test_copy(context, krb5_cc_type_file, "KEYRING:persistent:foo");
+ test_copy(context, "KEYRING:persistent:foo", krb5_cc_type_file);
+# endif
+ test_copy(context, krb5_cc_type_memory, "KEYRING:process:");
+ test_copy(context, "KEYRING:process:", krb5_cc_type_memory);
+ test_copy(context, krb5_cc_type_memory, "KEYRING:process:foo");
+ test_copy(context, "KEYRING:process:foo", krb5_cc_type_memory);
+ test_copy(context, krb5_cc_type_memory, "KEYRING:thread:");
+ test_copy(context, "KEYRING:thread:", krb5_cc_type_memory);
+ test_copy(context, krb5_cc_type_memory, "KEYRING:thread:foo");
+ test_copy(context, "KEYRING:thread:foo", krb5_cc_type_memory);
+ test_copy(context, krb5_cc_type_memory, "KEYRING:session:");
+ test_copy(context, "KEYRING:session:", krb5_cc_type_memory);
+ test_copy(context, krb5_cc_type_memory, "KEYRING:session:foo");
+ test_copy(context, "KEYRING:session:foo", krb5_cc_type_memory);
+ test_copy(context, krb5_cc_type_file, "KEYRING:user:");
+ test_copy(context, "KEYRING:user:", krb5_cc_type_file);
+ test_copy(context, krb5_cc_type_file, "KEYRING:user:foo");
+ test_copy(context, "KEYRING:user:foo", krb5_cc_type_memory);
+#endif /* HAVE_KEYUTILS_H */
+
+ test_move(context, krb5_cc_type_file);
+ test_move(context, krb5_cc_type_memory);
+ test_move(context, krb5_cc_type_scc);
+#if 0
+ test_move(context, krb5_cc_type_dcc);
+#endif
+#ifdef HAVE_KEYUTILS_H
+ test_move(context, krb5_cc_type_keyring);
+# ifdef HAVE_KEYCTL_GET_PERSISTENT
+ test_move(context, "KEYRING:persistent:");
+ test_move(context, "KEYRING:persistent:foo");
+# endif
+ test_move(context, "KEYRING:process:");
+ test_move(context, "KEYRING:process:foo");
+ test_move(context, "KEYRING:thread:");
+ test_move(context, "KEYRING:thread:foo");
+ test_move(context, "KEYRING:session:");
+ test_move(context, "KEYRING:session:foo");
+ test_move(context, "KEYRING:user:");
+ test_move(context, "KEYRING:user:foo");
+#endif /* HAVE_KEYUTILS_H */
+
+ test_prefix_ops(context, "FILE:/tmp/foo", &krb5_fcc_ops);
+ test_prefix_ops(context, "FILE", &krb5_fcc_ops);
+ test_prefix_ops(context, "MEMORY", &krb5_mcc_ops);
+ test_prefix_ops(context, "MEMORY:foo", &krb5_mcc_ops);
+ test_prefix_ops(context, "/tmp/kaka", &krb5_fcc_ops);
+#ifdef HAVE_SCC
+ test_prefix_ops(context, "SCC:", &krb5_scc_ops);
+ test_prefix_ops(context, "SCC:foo", &krb5_scc_ops);
+#endif
+#if 0
+ test_prefix_ops(context, "DIR:", &krb5_dcc_ops);
+ test_prefix_ops(context, "DIR:tkt1", &krb5_dcc_ops);
+#endif
+#ifdef HAVE_KEYUTILS_H
+ test_prefix_ops(context, "KEYRING:", &krb5_krcc_ops);
+ test_prefix_ops(context, "KEYRING:foo", &krb5_krcc_ops);
+#endif /* HAVE_KEYUTILS_H */
+
+ krb5_cc_destroy(context, id1);
+ krb5_cc_destroy(context, id2);
+
+ test_cc_config(context, "MEMORY", "bar", 1000); /* 1000 because fast */
+ test_cc_config(context, "FILE", "/tmp/foocc", 30); /* 30 because slower */
+
+ test_cccol_dcache(context);
+ test_cccol_scache(context);
+#ifdef HAVE_KEYUTILS_H
+ {
+ const char *what;
+
+ ret = test_cccol(context, "KEYRING:legacy:fooccol", &what);
+ if (ret)
+ krb5_err(context, 1, ret, "%s", what);
+
+ ret = test_cccol(context, "MEMORY:fooccol", &what);
+ if (ret)
+ krb5_err(context, 1, ret, "%s", what);
+ }
+#endif /* HAVE_KEYUTILS_H */
+
+ {
+ const char *what;
+ char *config = NULL;
+ char *fname = NULL;
+ char *d = NULL;
+
+ if (asprintf(&d, "%s/cccol", tmpdir) == -1 || d == NULL)
+ krb5_err(context, 1, errno, "asprintf");
+ if (mkdir(d, 0700) == -1)
+ krb5_err(context, 1, errno, "mkdir(%s)", d);
+ if (asprintf(&fname, "%s/foobar", d) == -1 || fname == NULL ||
+ asprintf(&config,
+ "[libdefaults]\n"
+ "\tdefault_file_cache_collections = FILE:%1$s/cccol/foobar\n"
+ "\tenable_file_cache_iteration = true\n",
+ tmpdir) == -1 || config == NULL)
+ krb5_err(context, 1, errno, "asprintf");
+ ret = krb5_set_config(context, config);
+ if (ret)
+ krb5_err(context, 1, ret,
+ "Could not configure context from string:\n%s\n", config);
+ ret = test_cccol(context, fname, &what);
+ if (ret)
+ krb5_err(context, 1, ret, "%s", what);
+ free(config);
+ free(fname);
+ free(d);
+ }
+
+ krb5_free_context(context);
+
+#if 0
+ sleep(60);
+#endif
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_config.c b/third_party/heimdal/lib/krb5/test_config.c
new file mode 100644
index 0000000..a281633
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_config.c
@@ -0,0 +1,246 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include <err.h>
+
+static int
+check_config_file(krb5_context context, char *filelist, char **res, int def)
+{
+ krb5_error_code ret;
+ char **pp;
+ int i;
+
+ pp = NULL;
+
+ if (def)
+ ret = krb5_prepend_config_files_default(filelist, &pp);
+ else
+ ret = krb5_prepend_config_files(filelist, NULL, &pp);
+
+ if (ret)
+ krb5_err(context, 1, ret, "prepend_config_files");
+
+ for (i = 0; res[i] && pp[i]; i++)
+ if (strcmp(pp[i], res[i]) != 0)
+ krb5_errx(context, 1, "'%s' != '%s'", pp[i], res[i]);
+
+ if (res[i] != NULL)
+ krb5_errx(context, 1, "pp ended before res list");
+
+ if (def) {
+ char **deflist;
+ int j;
+
+ ret = krb5_get_default_config_files(&deflist);
+ if (ret)
+ krb5_err(context, 1, ret, "get_default_config_files");
+
+ for (j = 0 ; pp[i] && deflist[j]; i++, j++)
+ if (strcmp(pp[i], deflist[j]) != 0)
+ krb5_errx(context, 1, "'%s' != '%s'", pp[i], deflist[j]);
+
+ if (deflist[j] != NULL)
+ krb5_errx(context, 1, "pp ended before def list");
+ krb5_free_config_files(deflist);
+ }
+
+ if (pp[i] != NULL)
+ krb5_errx(context, 1, "pp ended after res (and def) list");
+
+ krb5_free_config_files(pp);
+
+ return 0;
+}
+
+char *list0[] = { "/tmp/foo", NULL };
+char *list1[] = { "/tmp/foo", "/tmp/foo/bar", NULL };
+char *list2[] = { "", NULL };
+
+struct {
+ char *fl;
+ char **res;
+} test[] = {
+ { "/tmp/foo", NULL },
+ { "/tmp/foo" PATH_SEP "/tmp/foo/bar", NULL },
+ { "", NULL }
+};
+
+static void
+check_config_files(void)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ int i;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_init_context %d", ret);
+
+ test[0].res = list0;
+ test[1].res = list1;
+ test[2].res = list2;
+
+ for (i = 0; i < sizeof(test)/sizeof(*test); i++) {
+ check_config_file(context, test[i].fl, test[i].res, 0);
+ check_config_file(context, test[i].fl, test[i].res, 1);
+ }
+
+ krb5_free_context(context);
+}
+
+const char *config_string_result0[] = {
+ "A", "B", "C", "D", NULL
+};
+
+const char *config_string_result1[] = {
+ "A", "B", "C D", NULL
+};
+
+const char *config_string_result2[] = {
+ "A", "B", "", NULL
+};
+
+const char *config_string_result3[] = {
+ "A B;C: D", NULL
+};
+
+const char *config_string_result4[] = {
+ "\"\"", "", "\"\"", NULL
+};
+
+const char *config_string_result5[] = {
+ "A\"BQd", NULL
+};
+
+const char *config_string_result6[] = {
+ "efgh\"", "ABC", NULL
+};
+
+const char *config_string_result7[] = {
+ "SnapeKills\\", "Dumbledore", NULL
+};
+
+const char *config_string_result8[] = {
+ "\"TownOf Sandwich: Massachusetts\"Oldest", "Town", "In", "Cape Cod", NULL
+};
+
+const char *config_string_result9[] = {
+ "\"Begins and\"ends", "In", "One", "String", NULL
+};
+
+const char *config_string_result10[] = {
+ "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:",
+ "1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.",
+ "2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.",
+ "3. Neither the name of the Institute nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.",
+ "THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
+ "Why do we test with such long strings? Because some people have config files",
+ "That", "look", "Like this.", NULL
+};
+
+const struct {
+ const char * name;
+ const char ** expected;
+} config_strings_tests[] = {
+ { "foo", config_string_result0 },
+ { "bar", config_string_result1 },
+ { "baz", config_string_result2 },
+ { "quux", config_string_result3 },
+ { "questionable", config_string_result4 },
+ { "mismatch1", config_string_result5 },
+ { "mismatch2", config_string_result6 },
+ { "internal1", config_string_result7 },
+ { "internal2", config_string_result8 },
+ { "internal3", config_string_result9 },
+ { "longer_strings", config_string_result10 }
+};
+
+static void
+check_escaped_strings(void)
+{
+ krb5_context context;
+ krb5_config_section *c = NULL;
+ krb5_error_code ret;
+ int i;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_init_context %d", ret);
+
+ ret = krb5_config_parse_file(context, "test_config_strings.out", &c);
+ if (ret)
+ krb5_errx(context, 1, "krb5_config_parse_file()");
+
+ for (i=0; i < sizeof(config_strings_tests)/sizeof(config_strings_tests[0]); i++) {
+ char **ps;
+ const char **s;
+ const char **e;
+
+ ps = krb5_config_get_strings(context, c, "escapes", config_strings_tests[i].name,
+ NULL);
+ if (ps == NULL)
+ errx(1, "Failed to read string value %s", config_strings_tests[i].name);
+
+ e = config_strings_tests[i].expected;
+
+ for (s = (const char **)ps; *s && *e; s++, e++) {
+ if (strcmp(*s, *e))
+ errx(1,
+ "Unexpected configuration string at value [%s].\n"
+ "Actual=[%s]\n"
+ "Expected=[%s]\n",
+ config_strings_tests[i].name, *s, *e);
+ }
+
+ if (*s || *e)
+ errx(1, "Configuation string list for value [%s] has incorrect length.",
+ config_strings_tests[i].name);
+
+ krb5_config_free_strings(ps);
+ }
+
+ ret = krb5_config_file_free(context, c);
+ if (ret)
+ krb5_errx(context, 1, "krb5_config_file_free()");
+
+ krb5_free_context(context);
+}
+
+int
+main(int argc, char **argv)
+{
+ check_config_files();
+ check_escaped_strings();
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_config_strings.cfg b/third_party/heimdal/lib/krb5/test_config_strings.cfg
new file mode 100644
index 0000000..c62201b
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_config_strings.cfg
@@ -0,0 +1,12 @@
+[escapes]
+ foo = A B C D
+ bar = A B "C D"
+ baz = A B ""
+ quux = "A B;C: D"
+ questionable="""" "" """"
+ mismatch1 = A"BQd
+ mismatch2 = efgh" ABC
+ internal1 = "SnapeKills\" "Dumbledore"
+ internal2 = "TownOf Sandwich: Massachusetts"Oldest Town In "Cape Cod"
+ internal3 = "Begins and"ends In One String
+ longer_strings = "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:" "1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer." "2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution." "3. Neither the name of the Institute nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission." "THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." "Why do we test with such long strings? Because some people have config files" That look "Like this."
diff --git a/third_party/heimdal/lib/krb5/test_crypto.c b/third_party/heimdal/lib/krb5/test_crypto.c
new file mode 100644
index 0000000..34a709a
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_crypto.c
@@ -0,0 +1,216 @@
+/*
+ * Copyright (c) 2003-2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+static void
+time_encryption(krb5_context context, size_t size,
+ krb5_enctype etype, int iterations)
+{
+ struct timeval tv1, tv2;
+ krb5_error_code ret;
+ krb5_keyblock key;
+ krb5_crypto crypto;
+ krb5_data data;
+ char *etype_name;
+ void *buf;
+ int i;
+
+ ret = krb5_generate_random_keyblock(context, etype, &key);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_generate_random_keyblock");
+
+ ret = krb5_enctype_to_string(context, etype, &etype_name);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_enctype_to_string");
+
+ buf = malloc(size);
+ if (buf == NULL)
+ krb5_errx(context, 1, "out of memory");
+ memset(buf, 0, size);
+
+ ret = krb5_crypto_init(context, &key, 0, &crypto);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_init");
+
+ gettimeofday(&tv1, NULL);
+
+ for (i = 0; i < iterations; i++) {
+ ret = krb5_encrypt(context, crypto, 0, buf, size, &data);
+ if (ret)
+ krb5_err(context, 1, ret, "encrypt: %d", i);
+ krb5_data_free(&data);
+ }
+
+ gettimeofday(&tv2, NULL);
+
+ timevalsub(&tv2, &tv1);
+
+ printf("%s size: %7lu iterations: %d time: %3ld.%06ld\n",
+ etype_name, (unsigned long)size, iterations,
+ (long)tv2.tv_sec, (long)tv2.tv_usec);
+
+ free(buf);
+ free(etype_name);
+ krb5_crypto_destroy(context, crypto);
+ krb5_free_keyblock_contents(context, &key);
+}
+
+static void
+time_s2k(krb5_context context,
+ krb5_enctype etype,
+ const char *password,
+ krb5_salt salt,
+ int iterations)
+{
+ struct timeval tv1, tv2;
+ krb5_error_code ret;
+ krb5_keyblock key;
+ krb5_data opaque;
+ char *etype_name;
+ int i;
+
+ ret = krb5_enctype_to_string(context, etype, &etype_name);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_enctype_to_string");
+
+ opaque.data = NULL;
+ opaque.length = 0;
+
+ gettimeofday(&tv1, NULL);
+
+ for (i = 0; i < iterations; i++) {
+ ret = krb5_string_to_key_salt_opaque(context, etype, password, salt,
+ opaque, &key);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_string_to_key_data_salt_opaque");
+ krb5_free_keyblock_contents(context, &key);
+ }
+
+ gettimeofday(&tv2, NULL);
+
+ timevalsub(&tv2, &tv1);
+
+ printf("%s string2key %d iterations time: %3ld.%06ld\n",
+ etype_name, iterations, (long)tv2.tv_sec, (long)tv2.tv_usec);
+ free(etype_name);
+
+}
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ int i, enciter, s2kiter;
+ int optidx = 0;
+ krb5_salt salt;
+
+ krb5_enctype enctypes[] = {
+#if 0
+ ETYPE_DES_CBC_CRC,
+ ETYPE_DES3_CBC_SHA1,
+ ETYPE_ARCFOUR_HMAC_MD5,
+#endif
+ ETYPE_AES128_CTS_HMAC_SHA1_96,
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ ETYPE_AES128_CTS_HMAC_SHA256_128,
+ ETYPE_AES256_CTS_HMAC_SHA384_192
+ };
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ salt.salttype = KRB5_PW_SALT;
+ salt.saltvalue.data = NULL;
+ salt.saltvalue.length = 0;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ enciter = 1000;
+ s2kiter = 100;
+
+ for (i = 0; i < sizeof(enctypes)/sizeof(enctypes[0]); i++) {
+
+ krb5_enctype_enable(context, enctypes[i]);
+
+ time_encryption(context, 16, enctypes[i], enciter);
+ time_encryption(context, 32, enctypes[i], enciter);
+ time_encryption(context, 512, enctypes[i], enciter);
+ time_encryption(context, 1024, enctypes[i], enciter);
+ time_encryption(context, 2048, enctypes[i], enciter);
+ time_encryption(context, 4096, enctypes[i], enciter);
+ time_encryption(context, 8192, enctypes[i], enciter);
+ time_encryption(context, 16384, enctypes[i], enciter);
+ time_encryption(context, 32768, enctypes[i], enciter);
+
+ time_s2k(context, enctypes[i], "mYsecreitPassword", salt, s2kiter);
+ }
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_crypto_wrapping.c b/third_party/heimdal/lib/krb5/test_crypto_wrapping.c
new file mode 100644
index 0000000..aff4e8d
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_crypto_wrapping.c
@@ -0,0 +1,168 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+static void
+test_wrapping(krb5_context context,
+ size_t min_size,
+ size_t max_size,
+ size_t step,
+ krb5_enctype etype)
+{
+ krb5_error_code ret;
+ krb5_keyblock key;
+ krb5_crypto crypto;
+ krb5_data data;
+ char *etype_name;
+ void *buf;
+ size_t size;
+
+ ret = krb5_generate_random_keyblock(context, etype, &key);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_generate_random_keyblock");
+
+ ret = krb5_enctype_to_string(context, etype, &etype_name);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_enctype_to_string");
+
+ buf = malloc(max_size);
+ if (buf == NULL)
+ krb5_errx(context, 1, "out of memory");
+ memset(buf, 0, max_size);
+
+ ret = krb5_crypto_init(context, &key, 0, &crypto);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_init");
+
+ for (size = min_size; size < max_size; size += step) {
+ size_t wrapped_size;
+
+ ret = krb5_encrypt(context, crypto, 0, buf, size, &data);
+ if (ret)
+ krb5_err(context, 1, ret, "encrypt size %lu using %s",
+ (unsigned long)size, etype_name);
+
+ wrapped_size = krb5_get_wrapped_length(context, crypto, size);
+
+ if (wrapped_size != data.length)
+ krb5_errx(context, 1, "calculated wrapped length %lu != "
+ "real wrapped length %lu for data length %lu using "
+ "enctype %s",
+ (unsigned long)wrapped_size,
+ (unsigned long)data.length,
+ (unsigned long)size,
+ etype_name);
+ krb5_data_free(&data);
+ }
+
+ free(etype_name);
+ free(buf);
+ krb5_crypto_destroy(context, crypto);
+ krb5_free_keyblock_contents(context, &key);
+}
+
+
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ int i, optidx = 0;
+
+ krb5_enctype enctypes[] = {
+#ifdef HEIM_WEAK_CRYPTO
+ ETYPE_DES_CBC_CRC,
+ ETYPE_DES_CBC_MD4,
+ ETYPE_DES_CBC_MD5,
+#endif
+ ETYPE_DES3_CBC_SHA1,
+ ETYPE_ARCFOUR_HMAC_MD5,
+ ETYPE_AES128_CTS_HMAC_SHA1_96,
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128,
+ KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192
+ };
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ for (i = 0; i < sizeof(enctypes)/sizeof(enctypes[0]); i++) {
+ krb5_enctype_enable(context, enctypes[i]);
+
+ test_wrapping(context, 0, 1024, 1, enctypes[i]);
+ test_wrapping(context, 1024, 1024 * 100, 1024, enctypes[i]);
+ }
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_expand_toks.c b/third_party/heimdal/lib/krb5/test_expand_toks.c
new file mode 100644
index 0000000..9b105fb
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_expand_toks.c
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <getarg.h>
+#include <err.h>
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ int optidx = 0;
+ char *expanded;
+
+ setprogname(argv[0]);
+
+ if (getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if (version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ ret = _krb5_expand_path_tokensv(context, "/tmp/%{foo}/%{bar}%{baz}/x", 0,
+ &expanded,
+ "foo", "abc",
+ "bar", "dce",
+ "baz", "fgh",
+ NULL);
+ if (ret)
+ krb5_err(context, ret, 1, "Token expansion failed");
+
+#ifdef _WIN32
+#define EXPANDED_SHOULD_BE "\\tmp\\abc\\dcefgh\\x"
+#else
+#define EXPANDED_SHOULD_BE "/tmp/abc/dcefgh/x"
+#endif
+
+ if (strcmp(expanded, EXPANDED_SHOULD_BE) != 0)
+ krb5_errx(context, 1, "Token expansion incorrect");
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_forward.c b/third_party/heimdal/lib/krb5/test_forward.c
new file mode 100644
index 0000000..3782e50
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_forward.c
@@ -0,0 +1,134 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "hostname");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ const char *hostname;
+ krb5_context context;
+ krb5_auth_context ac;
+ krb5_error_code ret;
+ krb5_creds cred;
+ krb5_ccache id;
+ krb5_data data;
+ int optidx = 0;
+
+ setprogname (argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (argc < 1)
+ usage(1);
+
+ hostname = argv[0];
+
+ memset(&cred, 0, sizeof(cred));
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ ret = krb5_cc_default(context, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_default failed");
+
+ ret = krb5_auth_con_init(context, &ac);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_auth_con_init failed");
+
+ krb5_auth_con_addflags(context, ac,
+ KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED, NULL);
+
+ ret = krb5_cc_get_principal(context, id, &cred.client);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_get_principal");
+
+ ret = krb5_make_principal(context,
+ &cred.server,
+ krb5_principal_get_realm(context, cred.client),
+ KRB5_TGS_NAME,
+ krb5_principal_get_realm(context, cred.client),
+ NULL);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_make_principal(server)");
+
+ ret = krb5_get_forwarded_creds (context,
+ ac,
+ id,
+ KDC_OPT_FORWARDABLE,
+ hostname,
+ &cred,
+ &data);
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_get_forwarded_creds");
+
+ krb5_data_free(&data);
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_fx.c b/third_party/heimdal/lib/krb5/test_fx.c
new file mode 100644
index 0000000..68f00dc
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_fx.c
@@ -0,0 +1,253 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+struct {
+ char *p1;
+ char *pepper1;
+ krb5_enctype e1;
+ char *p2;
+ char *pepper2;
+ krb5_enctype e2;
+ krb5_enctype e3;
+ char *key;
+ size_t len;
+} cf2[] = {
+ {
+ "key1", "a", ETYPE_AES128_CTS_HMAC_SHA1_96,
+ "key2", "b", ETYPE_AES128_CTS_HMAC_SHA1_96,
+ ETYPE_AES128_CTS_HMAC_SHA1_96,
+ "\x97\xdf\x97\xe4\xb7\x98\xb2\x9e\xb3\x1e\xd7\x28\x02\x87\xa9\x2a",
+ 16
+ },
+ {
+ "key1", "a", ETYPE_AES256_CTS_HMAC_SHA1_96,
+ "key2", "b", ETYPE_AES256_CTS_HMAC_SHA1_96,
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ "\x4d\x6c\xa4\xe6\x29\x78\x5c\x1f\x01\xba\xf5\x5e\x2e\x54\x85\x66"
+ "\xb9\x61\x7a\xe3\xa9\x68\x68\xc3\x37\xcb\x93\xb5\xe7\x2b\x1c\x7b",
+ 32
+ },
+ {
+ "key1", "a", ETYPE_AES128_CTS_HMAC_SHA1_96,
+ "key2", "b", ETYPE_AES128_CTS_HMAC_SHA1_96,
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ "\x97\xdf\x97\xe4\xb7\x98\xb2\x9e\xb3\x1e\xd7\x28\x2\x87\xa9\x2a"
+ "\x1\x96\xfa\xf2\x44\xf8\x11\x20\xc2\x1c\x51\x17\xb3\xe6\xeb\x98",
+ 32
+ },
+ {
+ "key1", "a", ETYPE_AES256_CTS_HMAC_SHA1_96,
+ "key2", "b", ETYPE_AES256_CTS_HMAC_SHA1_96,
+ ETYPE_AES128_CTS_HMAC_SHA1_96,
+ "\x4d\x6c\xa4\xe6\x29\x78\x5c\x1f\x01\xba\xf5\x5e\x2e\x54\x85\x66",
+ 16
+ },
+ {
+ "key1", "a", ETYPE_AES128_CTS_HMAC_SHA1_96,
+ "key2", "b", ETYPE_AES256_CTS_HMAC_SHA1_96,
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ "\x88\xbd\xb2\xa9\xf\x3e\x52\x5a\xb0\x5f\x68\xc5\x43\x9a\x4d\x5e"
+ "\x9c\x2b\xfd\x2b\x02\x24\xde\x39\xb5\x82\xf4\xbb\x05\xfe\x2\x2e",
+ 32
+ },
+ {
+ "key1", "a", ETYPE_ARCFOUR_HMAC_MD5,
+ "key2", "b", ETYPE_ARCFOUR_HMAC_MD5,
+ ETYPE_ARCFOUR_HMAC_MD5,
+ "\x24\xd7\xf6\xb6\xba\xe4\xe5\xc0\x0d\x20\x82\xc5\xeb\xab\x36\x72",
+ 16
+ },
+ /* We don't yet have a PRF for 1DES in Heimdal */
+ {
+ "key1", "a", ETYPE_DES_CBC_CRC,
+ "key2", "b", ETYPE_DES_CBC_CRC,
+ ETYPE_DES_CBC_CRC,
+ "\x43\xba\xe3\x73\x8c\x94\x67\xe6",
+ 8
+ },
+ {
+ "key1", "a", ETYPE_DES3_CBC_SHA1,
+ "key2", "b", ETYPE_DES3_CBC_SHA1,
+ ETYPE_DES3_CBC_SHA1,
+ "\xe5\x8f\x9e\xb6\x43\x86\x2c\x13\xad\x38\xe5\x29\x31\x34\x62\xa7"
+ "\xf7\x3e\x62\x83\x4f\xe5\x4a\x01",
+ 24
+ },
+};
+
+
+static void
+test_cf2(krb5_context context)
+{
+ krb5_error_code ret;
+ krb5_data pw, p1, p2;
+ krb5_salt salt;
+ krb5_keyblock k1, k2, k3;
+ krb5_crypto c1, c2;
+ unsigned int i;
+ unsigned int errors = 0;
+
+ ret = krb5_allow_weak_crypto(context, 1);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_allow_weak_crypto");
+
+ for (i = 0; i < sizeof(cf2)/sizeof(cf2[0]); i++) {
+ pw.data = cf2[i].p1;
+ pw.length = strlen(cf2[i].p1);
+ salt.salttype = (krb5_salttype)KRB5_PADATA_PW_SALT;
+ salt.saltvalue.data = cf2[i].p1;
+ salt.saltvalue.length = strlen(cf2[i].p1);
+
+ ret = krb5_string_to_key_data_salt(context,
+ cf2[i].e1,
+ pw,
+ salt,
+ &k1);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_string_to_key_data_salt");
+
+ ret = krb5_crypto_init(context, &k1, 0, &c1);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_init");
+
+ pw.data = cf2[i].p2;
+ pw.length = strlen(cf2[i].p2);
+ salt.saltvalue.data = cf2[i].p2;
+ salt.saltvalue.length = strlen(cf2[i].p2);
+
+ ret = krb5_string_to_key_data_salt(context,
+ cf2[i].e2,
+ pw,
+ salt,
+ &k2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_string_to_key_data_salt");
+
+ ret = krb5_crypto_init(context, &k2, 0, &c2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_init");
+
+
+ p1.data = cf2[i].pepper1;
+ p1.length = strlen(cf2[i].pepper1);
+
+ p2.data = cf2[i].pepper2;
+ p2.length = strlen(cf2[i].pepper2);
+
+ ret = krb5_crypto_fx_cf2(context, c1, c2, &p1, &p2, cf2[i].e3, &k3);
+ if (ret == KRB5_PROG_ETYPE_NOSUPP) {
+ krb5_warn(context, ret, "KRB-FX-CF2 not supported for enctype %d",
+ cf2[i].e1);
+ continue;
+ } else if (ret) {
+ krb5_err(context, 1, ret, "krb5_crypto_fx_cf2");
+ }
+
+ if (k3.keytype != cf2[i].e3) {
+ errors++;
+ krb5_warnx(context, "length not right for enctype %d", cf2[i].e3);
+ continue;
+ }
+ if (k3.keyvalue.length != cf2[i].len ||
+ memcmp(k3.keyvalue.data, cf2[i].key, cf2[i].len) != 0) {
+ errors++;
+ krb5_warnx(context, "key not same for enctypes %d %d %d",
+ cf2[i].e1, cf2[i].e2, cf2[i].e3);
+ continue;
+ }
+
+ krb5_crypto_destroy(context, c1);
+ krb5_crypto_destroy(context, c2);
+
+ krb5_free_keyblock_contents(context, &k1);
+ krb5_free_keyblock_contents(context, &k2);
+ krb5_free_keyblock_contents(context, &k3);
+ }
+
+ if (errors)
+ krb5_errx(context, 1, "%u KRB-FX-CF2 vectors failed", errors);
+}
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ int optidx = 0;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ test_cf2(context);
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_get_addrs.c b/third_party/heimdal/lib/krb5/test_get_addrs.c
new file mode 100644
index 0000000..33ca929
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_get_addrs.c
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2000 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+/* print all addresses that we find */
+
+static void
+print_addresses (krb5_context context, const krb5_addresses *addrs)
+{
+ int i;
+ char buf[256];
+ size_t len;
+
+ for (i = 0; i < addrs->len; ++i) {
+ krb5_print_address (&addrs->val[i], buf, sizeof(buf), &len);
+ printf ("%s\n", buf);
+ }
+}
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ krb5_addresses addrs;
+ int optidx = 0;
+
+ setprogname (argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ ret = krb5_get_all_client_addrs (context, &addrs);
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_get_all_client_addrs");
+ printf ("client addresses\n");
+ print_addresses (context, &addrs);
+ krb5_free_addresses (context, &addrs);
+
+ ret = krb5_get_all_server_addrs (context, &addrs);
+ if (ret)
+ krb5_err (context, 1, ret, "krb5_get_all_server_addrs");
+ printf ("server addresses\n");
+ print_addresses (context, &addrs);
+ krb5_free_addresses (context, &addrs);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_gic.c b/third_party/heimdal/lib/krb5/test_gic.c
new file mode 100644
index 0000000..f11777e
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_gic.c
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+static char *password_str;
+
+static krb5_error_code
+lr_proc(krb5_context context, krb5_last_req_entry **e, void *ctx)
+{
+ while (e && *e) {
+ printf("e type: %d value: %d\n", (*e)->lr_type, (int)(*e)->value);
+ e++;
+ }
+ return 0;
+}
+
+static void
+test_get_init_creds(krb5_context context,
+ krb5_principal client)
+{
+ krb5_error_code ret;
+ krb5_get_init_creds_opt *opt;
+ krb5_creds cred;
+
+ ret = krb5_get_init_creds_opt_alloc(context, &opt);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_get_init_creds_opt_alloc");
+
+
+ ret = krb5_get_init_creds_opt_set_process_last_req(context,
+ opt,
+ lr_proc,
+ NULL);
+ if (ret)
+ krb5_err(context, 1, ret,
+ "krb5_get_init_creds_opt_set_process_last_req");
+
+ ret = krb5_get_init_creds_password(context,
+ &cred,
+ client,
+ password_str,
+ krb5_prompter_posix,
+ NULL,
+ 0,
+ NULL,
+ opt);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_get_init_creds_password");
+
+ krb5_get_init_creds_opt_free(context, opt);
+}
+
+static char *client_str = NULL;
+static int debug_flag = 0;
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"client", 0, arg_string, &client_str,
+ "client principal to use", NULL },
+ {"password",0, arg_string, &password_str,
+ "password", NULL },
+ {"debug", 'd', arg_flag, &debug_flag,
+ "turn on debuggin", NULL },
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "hostname ...");
+ exit (ret);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ int optidx = 0, errors = 0;
+ krb5_principal client;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ if(client_str == NULL)
+ errx(1, "client is not set");
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ ret = krb5_parse_name(context, client_str, &client);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name: %d", ret);
+
+ test_get_init_creds(context, client);
+
+ krb5_free_context(context);
+
+ return errors;
+}
diff --git a/third_party/heimdal/lib/krb5/test_hostname.c b/third_party/heimdal/lib/krb5/test_hostname.c
new file mode 100644
index 0000000..f722353
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_hostname.c
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+static int debug_flag = 0;
+static int version_flag = 0;
+static int help_flag = 0;
+
+static int
+expand_hostname(krb5_context context, const char *host)
+{
+ krb5_error_code ret;
+ char *h, **r;
+
+ ret = krb5_expand_hostname(context, host, &h);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_expand_hostname(%s)", host);
+
+ if (debug_flag)
+ printf("hostname: %s -> %s\n", host, h);
+
+ free(h);
+
+ ret = krb5_expand_hostname_realms(context, host, &h, &r);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_expand_hostname_realms(%s)", host);
+
+ if (debug_flag) {
+ int j;
+
+ printf("hostname: %s -> %s\n", host, h);
+ for (j = 0; r[j]; j++) {
+ printf("\trealm: %s\n", r[j]);
+ }
+ }
+ free(h);
+ krb5_free_host_realm(context, r);
+
+ return 0;
+}
+
+static int
+test_expand_hostname(krb5_context context)
+{
+ int i, errors = 0;
+
+ struct t {
+ krb5_error_code ret;
+ const char *orig_hostname;
+ const char *new_hostname;
+ } tests[] = {
+ { 0, "pstn1.su.se", "pstn1.su.se" },
+ { 0, "pstnproxy.su.se", "pstnproxy.su.se" },
+ };
+
+ for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
+ errors += expand_hostname(context, tests[i].orig_hostname);
+ }
+
+ return errors;
+}
+
+static struct getargs args[] = {
+ {"debug", 'd', arg_flag, &debug_flag,
+ "turn on debuggin", NULL },
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "hostname ...");
+ exit (ret);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ int optidx = 0, errors = 0;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ if (argc > 0) {
+ while (argc-- > 0)
+ errors += expand_hostname(context, *argv++);
+ return errors;
+ }
+
+ errors += test_expand_hostname(context);
+
+ krb5_free_context(context);
+
+ return errors;
+}
diff --git a/third_party/heimdal/lib/krb5/test_keytab.c b/third_party/heimdal/lib/krb5/test_keytab.c
new file mode 100644
index 0000000..134b0f1
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_keytab.c
@@ -0,0 +1,291 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+/*
+ * Test that removal entry from of empty keytab doesn't corrupts
+ * memory.
+ */
+
+static void
+test_empty_keytab(krb5_context context, const char *keytab)
+{
+ krb5_error_code ret;
+ krb5_keytab id;
+ krb5_keytab_entry entry;
+
+ ret = krb5_kt_resolve(context, keytab, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_resolve");
+
+ memset(&entry, 0, sizeof(entry));
+
+ krb5_kt_remove_entry(context, id, &entry);
+
+ ret = krb5_kt_have_content(context, id);
+ if (ret == 0)
+ krb5_errx(context, 1, "supposed to be empty keytab isn't");
+
+ ret = krb5_kt_close(context, id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_close");
+}
+
+/*
+ * Test that memory keytab are refcounted.
+ */
+
+static void
+test_memory_keytab(krb5_context context, const char *keytab, const char *keytab2)
+{
+ krb5_error_code ret;
+ krb5_keytab id, id2, id3;
+ krb5_keytab_entry entry, entry2, entry3;
+
+ ret = krb5_kt_resolve(context, keytab, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_resolve");
+
+ memset(&entry, 0, sizeof(entry));
+ ret = krb5_parse_name(context, "lha@SU.SE", &entry.principal);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+ entry.vno = 1;
+ ret = krb5_generate_random_keyblock(context,
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ &entry.keyblock);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_generate_random_keyblock");
+
+ krb5_kt_add_entry(context, id, &entry);
+
+ ret = krb5_kt_resolve(context, keytab, &id2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_resolve");
+
+ ret = krb5_kt_get_entry(context, id,
+ entry.principal,
+ 0,
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ &entry2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_get_entry");
+ krb5_kt_free_entry(context, &entry2);
+
+ ret = krb5_kt_close(context, id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_close");
+
+ ret = krb5_kt_get_entry(context, id2,
+ entry.principal,
+ 0,
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ &entry2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_get_entry");
+ krb5_kt_free_entry(context, &entry2);
+
+ ret = krb5_kt_close(context, id2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_close");
+
+
+ ret = krb5_kt_resolve(context, keytab2, &id3);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_resolve");
+
+ memset(&entry3, 0, sizeof(entry3));
+ ret = krb5_parse_name(context, "lha3@SU.SE", &entry3.principal);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+ entry3.vno = 1;
+ ret = krb5_generate_random_keyblock(context,
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ &entry3.keyblock);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_generate_random_keyblock");
+
+ krb5_kt_add_entry(context, id3, &entry3);
+
+
+ ret = krb5_kt_resolve(context, keytab, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_resolve");
+
+ ret = krb5_kt_get_entry(context, id,
+ entry.principal,
+ 0,
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ &entry2);
+ if (ret == 0)
+ krb5_errx(context, 1, "krb5_kt_get_entry when if should fail");
+
+ krb5_kt_remove_entry(context, id, &entry);
+
+ ret = krb5_kt_close(context, id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_close");
+
+ krb5_kt_free_entry(context, &entry);
+
+ krb5_kt_remove_entry(context, id3, &entry3);
+
+ ret = krb5_kt_close(context, id3);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_close");
+
+ krb5_free_principal(context, entry3.principal);
+ krb5_free_keyblock_contents(context, &entry3.keyblock);
+}
+
+static void
+perf_add(krb5_context context, krb5_keytab id, int times)
+{
+}
+
+static void
+perf_find(krb5_context context, krb5_keytab id, int times)
+{
+}
+
+static void
+perf_delete(krb5_context context, krb5_keytab id, int forward, int times)
+{
+}
+
+
+static int version_flag = 0;
+static int help_flag = 0;
+static char *perf_str = NULL;
+static int times = 1000;
+
+static struct getargs args[] = {
+ {"performance", 0, arg_string, &perf_str,
+ "test performance for named keytab", "keytab" },
+ {"times", 0, arg_integer, &times,
+ "number of times to run the perforamce test", "number" },
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ int optidx = 0;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (argc != 0)
+ errx(1, "argc != 0");
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ if (perf_str) {
+ krb5_keytab id;
+
+ ret = krb5_kt_resolve(context, perf_str, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_resolve: %s", perf_str);
+
+ /* add, find, delete on keytab */
+ perf_add(context, id, times);
+ perf_find(context, id, times);
+ perf_delete(context, id, 0, times);
+
+ /* add and find again on used keytab */
+ perf_add(context, id, times);
+ perf_find(context, id, times);
+
+ ret = krb5_kt_destroy(context, id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_destroy: %s", perf_str);
+
+ ret = krb5_kt_resolve(context, perf_str, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_resolve: %s", perf_str);
+
+ /* try delete backwards */
+#if 0
+ perf_add(context, id, times);
+ perf_delete(context, id, 1, times);
+#endif
+
+ ret = krb5_kt_destroy(context, id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_kt_destroy");
+
+ } else {
+
+ test_empty_keytab(context, "MEMORY:foo");
+ test_empty_keytab(context, "FILE:foo");
+
+ test_memory_keytab(context, "MEMORY:foo", "MEMORY:foo2");
+
+ }
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_kuserok.c b/third_party/heimdal/lib/krb5/test_kuserok.c
new file mode 100644
index 0000000..7319ef7
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_kuserok.c
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <getarg.h>
+#include <err.h>
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "principal luser");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ krb5_principal principal;
+ char *p;
+ int o = 0;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &o))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= o;
+ argv += o;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ if (argc != 2)
+ usage(1);
+
+ ret = krb5_parse_name(context, argv[0], &principal);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_unparse_name(context, principal, &p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_unparse_name");
+
+ ret = krb5_kuserok(context, principal, argv[1]);
+
+ krb5_free_principal(context, principal);
+ krb5_free_context(context);
+
+ printf("%s is %sallowed to login as %s\n", p, ret ? "" : "NOT ", argv[1]);
+ free(p);
+
+ if (ret)
+ return 0;
+
+ return 1;
+}
diff --git a/third_party/heimdal/lib/krb5/test_mem.c b/third_party/heimdal/lib/krb5/test_mem.c
new file mode 100644
index 0000000..3333d0d
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_mem.c
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+
+/*
+ * Test run functions, to be used with valgrind to detect memoryleaks.
+ */
+
+static void
+check_log(void)
+{
+ int i;
+
+ for (i = 0; i < 10; i++) {
+ krb5_log_facility *logfacility;
+ krb5_context context;
+ krb5_error_code ret;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ krb5_initlog(context, "test-mem", &logfacility);
+ krb5_addlog_dest(context, logfacility, "0/STDERR:");
+ krb5_set_warn_dest(context, logfacility);
+
+ krb5_free_context(context);
+ }
+}
+
+
+int
+main(int argc, char **argv)
+{
+ setprogname(argv[0]);
+
+ check_log();
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_mkforwardable.c b/third_party/heimdal/lib/krb5/test_mkforwardable.c
new file mode 100644
index 0000000..3f25f13
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_mkforwardable.c
@@ -0,0 +1,191 @@
+/*
+ * Copyright (c) 1997-2021 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * Copyright (c) 2021 Isaac Boukris
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/*
+ * Usage: mkforwardable server out_ccache
+ *
+ * The default cache contains a ticket to server and the default keytab
+ * contains a key to decrypt it, the ticket is decrypted and the forwardable
+ * flag is added, the ticket is then re-encrypted and stored in out_cache.
+ *
+ */
+
+static krb5_context context;
+
+static void
+check(krb5_error_code code)
+{
+ const char *errmsg;
+
+ if (code == 0)
+ return;
+
+ errmsg = krb5_get_error_message(context, code);
+ fprintf(stderr, "%s\n", errmsg);
+ krb5_free_error_message(context, errmsg);
+
+ abort();
+}
+
+static void
+decrypt_ticket_enc_part(EncryptionKey *key,
+ krb5_enctype etype,
+ Ticket *ticket,
+ EncTicketPart *et)
+{
+ krb5_error_code ret;
+ krb5_data plain;
+ size_t len;
+ krb5_crypto crypto;
+
+ check(krb5_crypto_init(context, key, etype, &crypto));
+
+ ret = krb5_decrypt_EncryptedData (context,
+ crypto,
+ KRB5_KU_TICKET,
+ &ticket->enc_part,
+ &plain);
+ check(ret);
+
+ check(decode_EncTicketPart(plain.data, plain.length, et, &len));
+
+ krb5_data_free (&plain);
+ krb5_crypto_destroy(context, crypto);
+}
+
+static void
+encrypt_ticket_enc_part(EncryptionKey *key,
+ krb5_enctype etype,
+ krb5_kvno skvno,
+ EncTicketPart *et,
+ Ticket *ticket)
+{
+ size_t len, size;
+ char *buf;
+ krb5_error_code ret;
+ krb5_crypto crypto;
+
+ ASN1_MALLOC_ENCODE(EncTicketPart, buf, len, et, &size, ret);
+ check(ret);
+
+ check(krb5_crypto_init(context, key, etype, &crypto));
+ ret = krb5_encrypt_EncryptedData(context,
+ crypto,
+ KRB5_KU_TICKET,
+ buf,
+ len,
+ skvno,
+ &ticket->enc_part);
+ check(ret);
+
+ free(buf);
+ krb5_crypto_destroy(context, crypto);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ krb5_error_code ret;
+ krb5_keytab kt;
+ krb5_keytab_entry entry;
+ krb5_enctype etype;
+ krb5_creds mc, cred;
+ krb5_ccache ccache;
+ EncTicketPart et;
+ Ticket ticket;
+ size_t size;
+ krb5_kvno kvno = 0;
+
+ memset(&cred, 0, sizeof(cred));
+
+ if (argc != 3)
+ errx(1, "Usage: mkforwardable server out_ccache");
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_init_context failed: %u", ret);
+
+ check(krb5_cc_default(context, &ccache));
+
+ krb5_cc_clear_mcred(&mc);
+
+ check(krb5_parse_name(context, argv[1], &mc.server));
+
+ check(krb5_cc_retrieve_cred(context, ccache, 0, &mc, &cred));
+
+ check(decode_Ticket(cred.ticket.data, cred.ticket.length, &ticket, NULL));
+
+ etype = ticket.enc_part.etype;
+
+ if (ticket.enc_part.kvno != NULL)
+ kvno = *ticket.enc_part.kvno;
+
+ check(krb5_kt_default(context, &kt));
+
+ check(krb5_kt_get_entry(context, kt, mc.server, kvno, etype, &entry));
+
+ decrypt_ticket_enc_part(&entry.keyblock, etype, &ticket, &et);
+
+ et.flags.forwardable = 1;
+ cred.flags.b = et.flags;
+
+ free_EncryptedData(&ticket.enc_part);
+
+ encrypt_ticket_enc_part(&entry.keyblock, etype, kvno, &et, &ticket);
+
+ krb5_data_free(&cred.ticket);
+ ASN1_MALLOC_ENCODE(Ticket, cred.ticket.data, cred.ticket.length, &ticket,
+ &size, ret);
+ check(ret);
+
+ krb5_cc_close(context, ccache);
+
+ check(krb5_cc_resolve(context, argv[2], &ccache));
+ check(krb5_cc_initialize(context, ccache, cred.client));
+
+ check(krb5_cc_store_cred(context, ccache, &cred));
+
+ free_Ticket(&ticket);
+ free_EncTicketPart(&et);
+ krb5_cc_close(context, ccache);
+ krb5_free_principal(context, mc.server);
+ krb5_free_cred_contents(context, &cred);
+ krb5_kt_free_entry(context, &entry);
+ krb5_kt_close(context, kt);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_pac.c b/third_party/heimdal/lib/krb5/test_pac.c
new file mode 100644
index 0000000..70da1cb
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_pac.c
@@ -0,0 +1,1255 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/*
+ * This PAC and keys are copied (with permission) from Samba torture
+ * regression test suite, they where created by Andrew Bartlet.
+ */
+
+static const unsigned char saved_pac[] = {
+ 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xd8, 0x01, 0x00, 0x00,
+ 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
+ 0x20, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00,
+ 0x40, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00,
+ 0x58, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x10, 0x08, 0x00, 0xcc, 0xcc, 0xcc, 0xcc,
+ 0xc8, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x30, 0xdf, 0xa6, 0xcb,
+ 0x4f, 0x7d, 0xc5, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0x7f, 0xc0, 0x3c, 0x4e, 0x59, 0x62, 0x73, 0xc5, 0x01, 0xc0, 0x3c, 0x4e, 0x59,
+ 0x62, 0x73, 0xc5, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x16, 0x00, 0x16, 0x00,
+ 0x04, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x0c, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x14, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x02, 0x00, 0x65, 0x00, 0x00, 0x00,
+ 0xed, 0x03, 0x00, 0x00, 0x04, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x02, 0x00,
+ 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x16, 0x00, 0x20, 0x00, 0x02, 0x00, 0x16, 0x00, 0x18, 0x00,
+ 0x24, 0x00, 0x02, 0x00, 0x28, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x01, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
+ 0x57, 0x00, 0x32, 0x00, 0x30, 0x00, 0x30, 0x00, 0x33, 0x00, 0x46, 0x00, 0x49, 0x00, 0x4e, 0x00,
+ 0x41, 0x00, 0x4c, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x02, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
+ 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x57, 0x00, 0x32, 0x00,
+ 0x30, 0x00, 0x30, 0x00, 0x33, 0x00, 0x46, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x41, 0x00, 0x4c, 0x00,
+ 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x57, 0x00, 0x49, 0x00,
+ 0x4e, 0x00, 0x32, 0x00, 0x4b, 0x00, 0x33, 0x00, 0x54, 0x00, 0x48, 0x00, 0x49, 0x00, 0x4e, 0x00,
+ 0x4b, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05,
+ 0x15, 0x00, 0x00, 0x00, 0x11, 0x2f, 0xaf, 0xb5, 0x90, 0x04, 0x1b, 0xec, 0x50, 0x3b, 0xec, 0xdc,
+ 0x01, 0x00, 0x00, 0x00, 0x30, 0x00, 0x02, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
+ 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x80, 0x66, 0x28, 0xea, 0x37, 0x80, 0xc5, 0x01, 0x16, 0x00, 0x77, 0x00, 0x32, 0x00, 0x30, 0x00,
+ 0x30, 0x00, 0x33, 0x00, 0x66, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x61, 0x00, 0x6c, 0x00, 0x24, 0x00,
+ 0x76, 0xff, 0xff, 0xff, 0x37, 0xd5, 0xb0, 0xf7, 0x24, 0xf0, 0xd6, 0xd4, 0xec, 0x09, 0x86, 0x5a,
+ 0xa0, 0xe8, 0xc3, 0xa9, 0x00, 0x00, 0x00, 0x00, 0x76, 0xff, 0xff, 0xff, 0xb4, 0xd8, 0xb8, 0xfe,
+ 0x83, 0xb3, 0x13, 0x3f, 0xfc, 0x5c, 0x41, 0xad, 0xe2, 0x64, 0x83, 0xe0, 0x00, 0x00, 0x00, 0x00
+};
+
+static int type_1_length = 472;
+
+static const krb5_keyblock kdc_keyblock = {
+ ETYPE_ARCFOUR_HMAC_MD5,
+ { 16, "\xB2\x86\x75\x71\x48\xAF\x7F\xD2\x52\xC5\x36\x03\xA1\x50\xB7\xE7" }
+};
+
+static const krb5_keyblock member_keyblock = {
+ ETYPE_ARCFOUR_HMAC_MD5,
+ { 16, "\xD2\x17\xFA\xEA\xE5\xE6\xB5\xF9\x5C\xCC\x94\x07\x7A\xB8\xA5\xFC" }
+};
+
+static time_t authtime = 1120440609;
+static const char *user = "w2003final$";
+
+/*
+ * This pac from Christan Krause
+ */
+
+static const unsigned char saved_pac2[] =
+ "\x05\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\xc8\x01\x00\x00"
+ "\x58\x00\x00\x00\x00\x00\x00\x00\x0a\x00\x00\x00\x18\x00\x00\x00"
+ "\x20\x02\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x00\x70\x00\x00\x00"
+ "\x38\x02\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x14\x00\x00\x00"
+ "\xa8\x02\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00\x14\x00\x00\x00"
+ "\xc0\x02\x00\x00\x00\x00\x00\x00\x01\x10\x08\x00\xcc\xcc\xcc\xcc"
+ "\xb8\x01\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x7d\xee\x09\x76"
+ "\xf2\x39\xc9\x01\xff\xff\xff\xff\xff\xff\xff\x7f\xff\xff\xff\xff"
+ "\xff\xff\xff\x7f\x6d\x49\x38\x62\xf2\x39\xc9\x01\x6d\x09\xa2\x8c"
+ "\xbb\x3a\xc9\x01\xff\xff\xff\xff\xff\xff\xff\x7f\x0e\x00\x0e\x00"
+ "\x04\x00\x02\x00\x10\x00\x10\x00\x08\x00\x02\x00\x00\x00\x00\x00"
+ "\x0c\x00\x02\x00\x00\x00\x00\x00\x10\x00\x02\x00\x00\x00\x00\x00"
+ "\x14\x00\x02\x00\x00\x00\x00\x00\x18\x00\x02\x00\x02\x01\x00\x00"
+ "\x52\x04\x00\x00\x01\x02\x00\x00\x03\x00\x00\x00\x1c\x00\x02\x00"
+ "\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x10\x00\x12\x00\x20\x00\x02\x00\x0e\x00\x10\x00"
+ "\x24\x00\x02\x00\x28\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x10\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x07\x00\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00"
+ "\x6f\x00\x70\x00\x65\x00\x6e\x00\x6d\x00\x73\x00\x70\x00\x00\x00"
+ "\x08\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x6f\x00\x70\x00"
+ "\x65\x00\x6e\x00\x20\x00\x6d\x00\x73\x00\x70\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00"
+ "\x60\x04\x00\x00\x07\x00\x00\x00\x01\x02\x00\x00\x07\x00\x00\x00"
+ "\x5e\x04\x00\x00\x07\x00\x00\x00\x09\x00\x00\x00\x00\x00\x00\x00"
+ "\x08\x00\x00\x00\x43\x00\x48\x00\x4b\x00\x52\x00\x2d\x00\x41\x00"
+ "\x44\x00\x53\x00\x08\x00\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00"
+ "\x4d\x00\x53\x00\x50\x00\x2d\x00\x41\x00\x44\x00\x53\x00\x00\x00"
+ "\x04\x00\x00\x00\x01\x04\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00"
+ "\x91\xad\xdc\x4c\x63\xb8\xb5\x48\xd5\x53\xd2\xd1\x00\x00\x00\x00"
+ "\x00\x66\xeb\x75\xf2\x39\xc9\x01\x0e\x00\x6f\x00\x70\x00\x65\x00"
+ "\x6e\x00\x6d\x00\x73\x00\x70\x00\x38\x00\x10\x00\x28\x00\x48\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x6f\x00\x70\x00\x65\x00\x6e\x00"
+ "\x6d\x00\x73\x00\x70\x00\x40\x00\x6d\x00\x73\x00\x70\x00\x2d\x00"
+ "\x61\x00\x64\x00\x73\x00\x2e\x00\x70\x00\x65\x00\x70\x00\x70\x00"
+ "\x65\x00\x72\x00\x63\x00\x6f\x00\x6e\x00\x2e\x00\x64\x00\x65\x00"
+ "\x4d\x00\x53\x00\x50\x00\x2d\x00\x41\x00\x44\x00\x53\x00\x2e\x00"
+ "\x50\x00\x45\x00\x50\x00\x50\x00\x45\x00\x52\x00\x43\x00\x4f\x00"
+ "\x4e\x00\x2e\x00\x44\x00\x45\x00\x76\xff\xff\xff\xb3\x56\x15\x29"
+ "\x37\xc6\x5c\xf7\x97\x35\xfa\xec\x59\xe8\x96\xa0\x00\x00\x00\x00"
+ "\x76\xff\xff\xff\x50\x71\xa2\xb1\xa3\x64\x82\x5c\xfd\x23\xea\x3b"
+ "\xb0\x19\x12\xd4\x00\x00\x00\x00";
+
+
+static const krb5_keyblock member_keyblock2 = {
+ ETYPE_DES_CBC_MD5,
+ { 8, "\x9e\x37\x83\x25\x4a\x7f\xf2\xf8" }
+};
+
+static time_t authtime2 = 1225304188;
+static const char *user2 = "openmsp";
+
+
+/* PAC ticket-signature test data. */
+
+static const krb5_keyblock rwdc_tgt_key = {
+ ENCTYPE_AES256_CTS_HMAC_SHA1_96,
+ { 32, "\x27\x86\x34\x1d\xd3\x15\x06\x0d\x6f\xd6\x40\xfa\x03\xb1\x95\x32"
+ "\x91\x22\xe8\x6b\x0f\x47\xe0\xb5\xfe\xda\xef\x54\x98\xdc\x07\x5a" }
+};
+
+static const krb5_keyblock rwdc_tgt_pac_key = {
+ ENCTYPE_ARCFOUR_HMAC,
+ { 16, "\xb9\xf0\x39\x8d\xe9\x60\xb8\x40\x8c\x54\x0b\x61\xf9\xd2\xf1\x16" }
+};
+
+static const krb5_keyblock rodc_tgt_key = {
+ ENCTYPE_AES256_CTS_HMAC_SHA1_96,
+ { 32, "\x0c\x7e\x63\x47\xc8\x70\x7f\x58\x7c\x91\x59\xba\xc9\xbf\x50\xb4"
+ "\xe2\xd6\x49\xb6\x85\xd3\xd9\xf3\x80\xba\xe9\x02\x46\x51\xab\x23" }
+};
+
+static const krb5_keyblock rodc_tgt_pac_key = {
+ ENCTYPE_ARCFOUR_HMAC,
+ { 16, "\x80\x5d\x66\xb9\x5f\x66\xd6\x80\xc3\x5a\x07\x41\xe8\x97\xcc\x66" }
+};
+
+static const krb5_keyblock server_key = {
+ ENCTYPE_ARCFOUR_HMAC,
+ { 16, "\xed\x23\x11\x20\x7a\x21\x44\x20\xbf\xc0\x8d\x36\xf7\xf6\xb2\x3e" }
+};
+
+
+static const unsigned char tgt_ticket[] =
+ "\x61\x82\x03\xe1\x30\x82\x03\xdd\xa0\x03\x02\x01\x05\xa1\x0a\x1b"
+ "\x08\x41\x43\x4d\x45\x2e\x43\x4f\x4d\xa2\x1d\x30\x1b\xa0\x03\x02"
+ "\x01\x02\xa1\x14\x30\x12\x1b\x06\x6b\x72\x62\x74\x67\x74\x1b\x08"
+ "\x41\x43\x4d\x45\x2e\x43\x4f\x4d\xa3\x82\x03\xa9\x30\x82\x03\xa5"
+ "\xa0\x03\x02\x01\x12\xa1\x03\x02\x01\x02\xa2\x82\x03\x97\x04\x82"
+ "\x03\x93\xfb\x16\x6b\x43\xca\x54\x6a\xed\xc8\xa4\x1f\x9e\xde\x88"
+ "\xa0\xa2\xc8\x86\x50\x17\x67\xbc\x0b\x13\xb8\x00\x80\x48\x54\x77"
+ "\xb2\x4c\x5f\xff\x34\xb6\x05\xc4\xff\xdb\x68\x00\x7c\xf4\x4f\x65"
+ "\x56\x69\x1a\x2f\x32\x24\x19\xef\x0a\xf8\xcd\x22\x4a\xe9\xcc\x2b"
+ "\x65\xfb\x3a\xff\x3d\xb3\xdc\xea\x5a\x9b\xb0\x14\xd0\xa6\x1d\x7c"
+ "\x82\xa7\x18\x23\xad\xd3\x43\x6c\x23\x41\x6e\x7c\x84\x01\xc7\xd6"
+ "\x60\xdf\xbb\x19\xac\xf3\x5b\x52\xea\xd1\xdb\xa5\x49\xc6\xf1\x44"
+ "\x59\x41\x15\x78\x13\xbc\x85\x73\xba\xd7\xde\x55\xe9\x84\x30\x11"
+ "\x5e\x00\x47\xff\x01\x87\x46\xda\xe3\xb4\xe3\xef\xac\x67\xa8\x8d"
+ "\x06\xf4\x04\xa3\x15\x5f\x51\x59\xe9\xb4\x65\x00\x1f\x45\x7c\x2a"
+ "\xcf\x17\x78\x75\xad\xc8\x65\x92\xe7\x20\x89\x41\x43\x5e\x08\x1d"
+ "\xc9\x4b\xa1\x57\x26\x7f\x9a\x64\xc7\xe3\x90\xbf\xa8\x9f\x86\x89"
+ "\xbf\x37\xd0\x1a\x9c\xe7\x32\xbb\x9f\x8d\x38\xfd\xe8\xf4\x88\x54"
+ "\x3d\xe7\xd0\xfb\x73\x1a\x97\xee\xa5\x32\x67\x62\x4d\x1c\x28\x85"
+ "\x01\x4f\x76\x4c\xf6\xe5\x73\x93\x0e\xd8\x0a\xf1\x6f\xf0\x8c\xbf"
+ "\x65\x80\x87\xd1\xe8\xbc\xc5\x8f\x03\xb8\xfe\x7e\xd6\xde\x80\xa5"
+ "\x27\x8c\x26\x14\x66\xf3\xd2\x4d\x51\x51\xe7\x47\xac\xa5\x93\xd7"
+ "\x01\x5b\x6b\xca\x6c\xd5\x19\x7b\xad\x97\xf2\xa6\x18\x0e\xe3\xea"
+ "\x5e\x81\xe4\xd7\xf5\xb0\xca\x0f\x04\x13\xc4\xed\x5b\x0c\xb2\xc4"
+ "\x5e\xd3\xc2\xb6\x0f\x0a\x76\x8a\x7d\x1c\x79\x62\xb5\x68\x47\x33"
+ "\x5e\x28\x3a\xd6\x78\x89\xb3\xbd\x34\x72\x7f\xe1\x8e\x5e\xa9\x89"
+ "\xfe\xc5\xba\x5f\x76\x00\x27\x29\x88\x79\xb4\x42\x33\xe7\x4c\xce"
+ "\x47\x39\xac\xfa\x8e\x93\x7a\x92\x7f\xbd\x91\xc8\xff\xe4\x7b\x04"
+ "\xe8\xf7\x29\x3b\xb4\x41\xb9\xe0\x61\x14\x2a\xc9\x5b\x02\xc2\x01"
+ "\x6f\x61\xa8\x1a\x5e\x2d\x0b\x3f\xc3\x1d\x6a\xb0\x9e\xf1\x41\xaf"
+ "\xc6\xe0\x11\xb3\x47\xb2\x43\x42\xb4\x6e\xdb\x16\x41\x6a\x7b\x53"
+ "\x97\x01\x7f\x3e\x9d\x47\x27\x14\x29\x7d\xc7\xa5\x40\xaf\x77\xcb"
+ "\xc9\x3e\x2e\x1f\xa3\xc8\x69\x98\xf7\xb2\x18\xa7\xcf\x45\x87\xba"
+ "\x48\x0b\xb8\x03\x10\x46\x2d\x95\x59\x5b\x9e\xe3\xe4\x20\x08\x80"
+ "\x97\x39\x16\x0c\x34\x27\x35\xd3\xd9\x71\x7b\xc2\x7d\x16\x36\xad"
+ "\xa0\x95\x12\x49\x5a\x3b\xea\xcf\x85\x75\x9e\xa4\x96\x51\x6c\x34"
+ "\x60\xd5\x3a\x9d\x60\x80\x53\x71\xac\x21\xfe\xea\xb3\xc5\x74\x65"
+ "\x7b\x98\xb6\x63\x58\xb7\xc9\x0c\x80\xad\x54\x9b\x1c\xdf\x84\xf9"
+ "\x97\xac\x73\x72\x4f\xbe\x10\x72\x6a\xec\x36\xfc\x7c\x98\xc6\x98"
+ "\x81\xde\xab\x2b\x8a\x68\x17\xd6\xb0\xac\xfd\xed\x5d\x67\xd3\x5a"
+ "\xbe\x7e\x88\x63\x5f\xc3\x1f\xf7\x04\xd9\xcd\x0a\xc7\x70\x83\x93"
+ "\x60\x86\x0c\x08\x21\xbb\x2f\x29\x28\xaf\x3f\x93\x24\x5f\x3a\x1d"
+ "\xf3\x81\x95\xb4\xef\xd6\x8c\x79\xdf\xf7\x9d\x4a\x0a\x49\xa7\x46"
+ "\xcd\x05\x30\x6e\x92\xa2\x26\x23\x8e\xf3\xe1\x38\x41\x63\x2f\xe6"
+ "\xd1\x59\x99\x8d\x7a\x8c\x4d\x57\x19\x5c\xee\x75\x7a\xd8\x0a\x53"
+ "\x43\xb0\x92\x01\x4a\xf7\xc4\x54\x8e\xe8\xc6\x43\x0b\x43\x9a\xa3"
+ "\xfd\x5c\x0c\x47\x52\xdf\xc6\x47\xa0\x14\xef\x45\xcf\xdf\xb7\x04"
+ "\xca\x3e\x5d\x8b\x32\x9b\x81\xa3\x8b\x9d\x7c\x0f\x11\x13\xf1\x0d"
+ "\xc0\xd0\xe2\xc1\xf7\x65\x03\xe0\x50\x6c\xbb\x3c\xd2\xc1\xad\x15"
+ "\xa3\xcd\x24\x85\xc0\x94\x54\x12\x2d\x63\x01\x47\x8b\x51\xee\xd1"
+ "\x46\xc0\x47\xcf\xce\xa1\x81\x5a\x5c\xe6\x59\x99\xb1\xaf\x80\x05"
+ "\xc3\x22\x69\xb3\x19\xec\x0e\xdd\x72\x0a\xcb\xf5\x4e\x90\x65\x41"
+ "\x68\x46\x8e\xab\xb3\xcc\xb6\xe2\xbd\xbf\xc0\x04\x12\x35\x84\xe5"
+ "\xef\xa5\x7f\x98\x8e\x0d\xac\x92\xae\x8f\x9c\x41\xce\x41\xb5\xcc"
+ "\x59\x00\xa5\x2c\x71\xe3\xdd\x25\x29\xd2\xac\x0f\x9b\x23\xbd\x1e"
+ "\x25\xe5\x06\xbd\x43\x46\x46\x4f\x81\x08\x1f\x57\xa9\x93\x24\xe4"
+ "\x83\x42\x13\x00\xce\x95\xdb\xde\x95\xc5\x8c\xd8\x29\x4e\x43\xb2"
+ "\x64\xe6\x6c\x0e\x40\x86\x35\xef\xac\x5b\x15\x92\xfb\x3c\xf0\x94"
+ "\xd8\x1f\xf9\x90\x8a\xd2\xa8\x4a\x1d\x77\x57\x4c\x65\xb3\x4f\xe4"
+ "\x03\x13\x3d\x52\x8b\xe4\x9e\x98\x53\xf1\xad\xc1\x2a\x3c\xda\x4f"
+ "\x24\xbf\x24\xb2\xb7\x34\xc7\xde\xfb\xe6\xe9\x82\x05\x07\x25\xd9"
+ "\x8e\xea\xd8\xb7\x0d\x1d\x0d\xf1\x0c\x99\x1a\x6a\xa7\xe7\x27\x49"
+ "\x26\x2a\x75\xd5\x84";
+
+static const unsigned char service_ticket[] =
+ "\x61\x82\x03\xf3\x30\x82\x03\xef\xa0\x03\x02\x01\x05\xa1\x0a\x1b"
+ "\x08\x41\x43\x4d\x45\x2e\x43\x4f\x4d\xa2\x13\x30\x11\xa0\x03\x02"
+ "\x01\x01\xa1\x0a\x30\x08\x1b\x06\x61\x70\x61\x63\x68\x65\xa3\x82"
+ "\x03\xc5\x30\x82\x03\xc1\xa0\x03\x02\x01\x17\xa1\x03\x02\x01\x02"
+ "\xa2\x82\x03\xb3\x04\x82\x03\xaf\x7e\x88\x85\x77\x22\x5e\x30\x7a"
+ "\xaf\x63\xc4\x2b\xc1\xae\x88\x87\x27\x65\x0e\x1e\xa7\x94\x67\xf9"
+ "\x9d\x49\x5b\x6b\xba\xfb\x51\x04\xc4\xe8\x44\xc9\xdf\x8d\x8d\x58"
+ "\x61\xdb\x1e\x82\x98\xc7\x68\x9e\x81\xf0\xc4\x88\x87\xd6\xf5\x7b"
+ "\x44\x8e\x4a\x65\x4f\x37\x49\x8a\x81\x67\x00\x7e\xf3\x7e\x75\x9d"
+ "\x61\x18\x6d\x6f\x21\x73\xe3\xab\xe2\x86\xc0\xf1\x8b\x9f\x25\xc2"
+ "\xdc\xc4\x65\xeb\xba\x24\x3d\x2d\x5a\x9b\xbe\xc1\x24\x8c\xf1\x78"
+ "\xfc\xf9\xca\x14\x8e\xd4\xe3\xb3\x54\x87\xce\x97\x0c\x7b\x11\x2e"
+ "\x38\x30\xed\x8c\x41\x28\x90\x5b\xc6\x3d\xba\x29\x7b\x11\xfa\x85"
+ "\x54\x13\xab\x22\xe9\x52\xdd\xad\x5a\xdc\xa7\xca\x4f\x19\x49\x81"
+ "\x53\x09\x10\xca\x6b\x1a\x44\x13\xe6\x88\xec\x14\xd2\x15\x5a\x65"
+ "\x8a\xef\x55\x6a\xb1\xda\xc4\xe6\x0d\xc8\x2d\x8b\x0c\x00\x71\x6a"
+ "\x7b\x06\x34\xe0\x93\xa4\x5d\x5b\xa9\x43\x65\x42\xc5\x13\x64\xee"
+ "\x51\xd3\xd9\xc8\x3d\x52\xe2\xba\xb2\x81\xe6\x86\x25\x6f\xa6\x22"
+ "\x25\x97\xbb\xf1\xe4\x6e\xe1\x9a\xfa\xa4\xa0\x8b\xd6\x7b\x4a\x8a"
+ "\x62\x3d\x21\x1c\x08\x16\x8d\x29\x58\x7e\xfd\x43\x48\xba\xd7\x19"
+ "\x7c\xdd\x57\xe4\x8f\x94\x6e\x97\xed\x8d\xf2\x68\xe4\x89\xde\xc3"
+ "\xed\xa6\x7b\xcd\xff\x0c\xcf\xac\xad\xfa\x54\x89\xfc\xd0\x94\xd9"
+ "\x48\x25\x61\x71\x89\x32\xb8\xdb\xf9\xfb\xb9\xf4\x8b\x7e\x9c\x95"
+ "\x5d\xa3\x03\x13\xaa\x50\x28\xfa\x0b\x54\x5e\x0a\x3a\xb6\x4e\x58"
+ "\xee\x3f\xbc\xd2\x23\x81\x82\x82\xab\xef\x6a\xf8\x10\x56\x0e\x43"
+ "\xc2\x4a\x30\xa9\x17\x1a\x46\xb2\xdd\xcf\x7d\x20\x46\x0e\xc8\xff"
+ "\x54\xf5\xa1\xa1\x43\x8b\x02\x00\x0c\x31\xbb\x66\xcd\x17\xf0\x12"
+ "\x83\x39\x6c\xcf\x9c\xe9\x68\x26\x68\x86\xd4\xa4\xe6\x33\xa1\xdb"
+ "\x74\x1d\x56\x1c\x2b\xff\x5e\xdd\xe7\xdd\x3a\x3e\x3a\x13\xbf\x36"
+ "\x5a\x3f\x0d\x21\x9d\x9c\xd5\x20\x13\x1d\x86\xb4\xb2\xa5\x34\xa2"
+ "\x0b\x9a\x0c\xa0\xac\x92\x9b\x02\xf2\x68\x19\x9e\x1c\x66\x40\x29"
+ "\x81\x13\xf3\x06\x49\xa4\xf5\xd9\xe9\xd1\x2f\x89\xac\x1d\x20\x9e"
+ "\xb1\x2e\xf3\xde\x09\x7c\xf4\xe6\x2b\x61\x3f\x35\x0f\x83\xa9\x24"
+ "\xd3\xbd\x14\x0f\x48\xcb\xe4\x98\x02\x7c\x83\x1b\x61\x59\x34\x7d"
+ "\x32\x59\xbc\xb8\xe2\xb3\x99\x80\x75\x4b\x4b\xb5\x2b\x6d\x07\x66"
+ "\x3c\x8a\xbc\x6d\x61\x6e\xcb\x12\x53\xe2\x07\x38\x4e\x2f\xdb\xe0"
+ "\x15\x4c\x8b\xdb\x7e\xeb\x61\x96\xfb\x4f\x3d\x5f\xbe\xdb\x34\xb0"
+ "\x73\x7a\xe6\x10\x8a\xe7\x37\xa3\x15\x68\x44\x85\xc2\xc1\x4f\x3e"
+ "\x4c\xc8\x51\x54\x2c\x7d\x50\x86\xf2\xbd\x19\x63\x51\x4c\xb4\xd4"
+ "\x29\x6a\x03\xae\x38\x77\x25\xbc\x15\xba\xa8\x65\x29\x29\xdd\xb1"
+ "\xaa\xe8\x9a\xbf\x4c\x15\xcf\x13\x11\x0b\x86\x5c\x44\xca\x82\x49"
+ "\x8c\x1b\x77\x28\x36\x87\xf9\xad\x6d\xe0\x05\x0f\x93\x00\x1f\xaf"
+ "\xe4\xe9\x5a\x8f\x61\x41\x46\x2f\x52\x4d\x16\x4f\x9c\xca\x94\xff"
+ "\x19\x2e\xa5\x65\x09\x4f\x58\xfb\x4b\xbe\x89\xb3\x1a\x3b\x9b\xe4"
+ "\xb9\x7b\x58\xcd\xa3\x73\x41\xe0\xcb\xbd\xce\x97\x87\x1f\x60\xc8"
+ "\xbb\x8c\xe9\xd7\x4f\x9a\x2d\xb5\xd4\x73\x4e\x25\xf3\x36\xbc\x3f"
+ "\x81\x23\x82\x1e\xde\xbe\x9b\x35\x67\x99\x9f\x9c\x02\x9c\x75\x0c"
+ "\xed\xb1\xcb\x82\x7f\xf5\x31\x66\x76\x01\x5a\x61\x3c\xa4\xe9\xae"
+ "\x1a\xc1\x3f\x35\x7d\xd4\x41\xdb\x7f\xd2\xc5\x5f\xbe\x8c\x13\xa6"
+ "\x1a\xd3\x2e\xf6\x0f\x91\xd5\x20\xd5\x36\x57\xa8\x40\x17\x3b\x49"
+ "\xf6\xe5\x55\x04\xcf\xf3\x72\x3d\xa6\x99\x3a\x40\x49\xdf\x5a\x69"
+ "\xfb\x35\x43\x3a\x49\x8e\xb9\x6d\x1b\xd3\xb9\x6a\xcb\xcd\x6c\xda"
+ "\x68\x3f\xc1\xd4\x0e\xdb\x7a\xd5\x05\x77\xac\xc2\x95\xf4\x7c\x83"
+ "\x3c\xaf\x55\x9f\x29\x52\xee\xe4\x34\x2d\x4c\x5f\xfa\x76\x0a\xe2"
+ "\x8e\xe3\xb7\x12\x37\x79\x9e\xfb\xe2\xaf\x3f\xbc\x2a\x2e\x35\x79"
+ "\xd4\x65\x05\x88\xb7\x1d\xc6\xf8\x89\xe7\xe9\xa1\xe0\xf0\x18\x3a"
+ "\xd4\x06\x47\x22\xf2\xb7\xbf\x67\x41\x24\xaf\x19\x85\x32\xf5\x91"
+ "\x8a\x16\xd8\x99\xd5\x27\x0e\x08\xfd\x07\x42\xdd\xd9\x41\xd7\x1c"
+ "\x7e\x64\x09\x9b\xe7\x51\xff\x02\x37\x32\x12\x6d\x60\x3f\x36\x25"
+ "\xd0\x53\xd8\xbd\x22\x6f\x2c\xec\x7c\xe4\x65\x7b\xd4\xcc\xce\xc4"
+ "\x8d\xee\x53\x48\x26\x8c\x97\x18\x0a\x06\x62\xaf\x31\x0c\x85\xc8"
+ "\x27\x11\xb3\x18\x9b\x24\x57\x38\x20\xf6\xe5\x42\x72\x1c\x3c\xfb"
+ "\xce\xd4\x26\x65\x92\x21\x49\x0b\x5d\x62\x72\xeb\xb3\x53\x89\x55"
+ "\xb6\x81\xef\xfd\xd2\xb6\xed";
+
+static const unsigned char s4u2self_ticket[] =
+ "\x61\x82\x03\xf2\x30\x82\x03\xee\xa0\x03\x02\x01\x05\xa1\x0a\x1b"
+ "\x08\x41\x43\x4d\x45\x2e\x43\x4f\x4d\xa2\x13\x30\x11\xa0\x03\x02"
+ "\x01\x01\xa1\x0a\x30\x08\x1b\x06\x61\x70\x61\x63\x68\x65\xa3\x82"
+ "\x03\xc4\x30\x82\x03\xc0\xa0\x03\x02\x01\x17\xa1\x03\x02\x01\x02"
+ "\xa2\x82\x03\xb2\x04\x82\x03\xae\x41\x12\xbe\x9e\x19\x0b\x27\xfe"
+ "\x38\xd3\x9b\x98\x8d\xcf\xc4\xe5\x34\x43\x64\x4a\x96\x00\x12\x52"
+ "\x92\x24\xcc\x8a\xe2\x80\x2a\x9e\xc1\x67\x6d\xd2\x77\x41\xe3\xc3"
+ "\xb7\xde\xf9\xdf\x8f\xdb\xe8\xd6\x78\x84\x83\xa0\x99\x2a\xbb\x24"
+ "\x25\x9d\x3a\x4d\xb0\x89\xe8\xa7\x67\xbe\x4e\x7b\xd4\x20\xad\xa6"
+ "\xb5\xa2\xab\xf4\x07\xf9\x14\x2e\x08\xc5\xa8\x43\xc2\xaf\x24\x53"
+ "\xb3\xaf\x7b\x83\xb5\xd1\xca\x8a\x99\x83\x14\x08\x37\x1f\x20\x03"
+ "\xfc\xd4\xb4\xce\xb3\x9a\xc1\xbd\x31\x54\x21\xb6\xbe\x7c\x82\xbc"
+ "\x30\x61\x0d\x9a\x10\x90\x00\x69\xee\xd5\xd3\xf6\x7c\xfa\x70\xa7"
+ "\xd4\xa1\xe6\xbd\x0b\xb1\xe2\xcc\x4e\xc6\x53\xc7\x89\x39\x57\x63"
+ "\xca\xfb\x4f\x0d\x73\xf7\x2a\xda\x94\x40\xdd\x0a\xd6\x00\x14\xc2"
+ "\x7b\x5f\xda\x27\x7c\x95\x32\xab\xcf\xd1\xac\xd0\xfc\x4a\xb4\x82"
+ "\x80\x5f\x56\xa5\xac\xb9\xb4\xc8\xb9\x08\x0a\x52\x9b\x2e\x80\xf4"
+ "\x9d\x85\x73\x09\xb1\x9a\xd6\x50\x59\x47\x0f\x8f\x72\xd5\x91\x76"
+ "\x89\xba\x49\xe3\x5e\x76\x07\x84\x8b\xf2\xc0\x57\xd4\xd2\x31\xfe"
+ "\xfd\xa3\xcd\x96\x5a\xbe\x19\x18\x97\x8e\xbf\x18\x1b\xdf\xf9\x78"
+ "\x5b\xac\x3c\x1f\xff\x4c\x64\xef\x1d\x5e\x69\x04\xcf\x68\xf6\x97"
+ "\xc4\xff\x16\x8e\xb2\x22\xf3\xc5\x84\x67\x41\x04\xce\x72\xdd\x76"
+ "\x65\x2e\xee\x84\xfb\x85\x83\x4b\x41\xdf\x24\x1e\xc7\x31\xf0\xc4"
+ "\xf1\xf7\x83\xfe\x46\x6d\x6f\x45\xf6\xb4\x40\xbb\x2f\x09\xf7\xe2"
+ "\x6f\x19\xd3\x3e\xa6\x94\x76\x46\x6b\x78\x43\x08\x4c\xfc\x15\xc2"
+ "\x4d\xef\x12\xe0\x38\x6a\xdb\x49\x7a\x71\x6c\xeb\xe3\xdf\xe7\x57"
+ "\x25\x23\x09\x4d\x74\xac\x93\x95\x8a\x6c\x01\x70\x0a\xb7\x42\xee"
+ "\xf5\x5c\x65\x64\xc6\xd7\x3e\x57\x7e\x0f\x9b\xdd\xf0\xfb\xdb\x92"
+ "\xa6\x1c\x75\x18\x88\x29\x03\xf9\x58\xf0\xd0\xc2\x91\x9c\xf6\x58"
+ "\x4e\x15\xe1\xab\x46\x1e\x23\x7c\xdc\xa5\xdd\xaf\x59\xae\x22\xbb"
+ "\xc3\x6d\x02\x0f\x02\x9e\x4a\xc1\x6d\x55\x4b\x35\x69\xd5\xaa\x92"
+ "\x61\xef\x0d\x50\x42\x49\xc0\xb5\x9d\x57\x3f\x50\x4d\xc2\x17\xda"
+ "\xc4\x43\xd1\x1f\x8c\x77\x4c\xa1\x37\x5c\x39\xe7\x51\x7e\x52\x68"
+ "\x0f\x6d\x8e\x1e\xb7\x81\x14\xc1\x11\x17\xa9\x37\x75\x48\x72\x35"
+ "\xca\xeb\xcb\x0d\x84\xbb\xf1\x08\x79\xde\x31\x00\x7f\x54\xc8\xbc"
+ "\x38\x1f\x2c\x56\x3b\xfc\x9d\x8a\xbc\x2d\x72\x8b\x32\x29\xf7\x52"
+ "\x96\x60\x34\x70\x13\x6f\x5a\x98\x7f\x69\xdc\x00\x21\x4c\x9d\x21"
+ "\x52\xd9\x71\xa3\xc6\xea\xd9\xdb\xeb\xd5\x78\xe5\x8f\x5e\x1d\xa8"
+ "\xa6\x0a\x58\x9c\xc9\x45\xc0\xb6\xb1\xe5\xfb\x49\xd2\x71\x41\x52"
+ "\xae\x52\x84\xd6\x90\x1e\x9a\xc2\xdb\x5b\xf8\x18\xf8\x47\x25\x70"
+ "\x1b\x07\x64\x8c\x4a\x94\xb0\x52\x50\xf0\x99\x3b\x0d\x11\x33\xb9"
+ "\xd6\xdf\x43\xfe\x34\x92\x3f\xa9\x1c\x9e\xfc\x89\x11\xdb\xe5\x15"
+ "\xae\x74\xd2\x1b\xd0\x42\x5a\x19\x0c\x03\x8e\x09\x16\xd2\xcf\xe8"
+ "\xd5\x02\xa4\x58\xe3\xca\xef\xe3\xa5\x36\x4f\x79\x6e\xc2\x57\x7f"
+ "\x97\xcf\x87\xec\x10\x57\x35\x15\xd8\x67\x4c\xaf\x2c\x6b\x50\x04"
+ "\xd6\xf7\x5f\x83\x1a\x4d\xfe\x44\x67\x60\x3f\x98\xfe\xa5\xd0\x56"
+ "\xf1\x46\x1e\xa0\x38\x21\x62\x0e\xce\xd5\x9a\x41\x4b\xb1\x9a\x7d"
+ "\xfe\x7d\x2d\x88\x16\x82\x73\x27\x4d\x9f\xad\x06\x1e\x93\x0f\xe7"
+ "\xd0\x98\xc5\x2e\xd8\xfc\x97\x4c\xed\x3b\x89\x94\xf4\x71\x88\x9f"
+ "\xc6\x5a\x73\x6e\x00\x4a\xd4\x99\xe2\x87\x32\x62\x03\x20\x73\xe3"
+ "\xba\xcc\x5d\x35\xa8\x20\x10\xb8\x60\xff\xed\x8c\x44\x21\x31\x1a"
+ "\x41\xb1\x3b\xa3\x44\x15\x45\x99\xa2\x89\x47\xd1\x80\xfd\xee\xc7"
+ "\xe8\xa2\xaa\xb3\x90\x2b\x04\x3c\x78\xf9\xcd\x0a\x90\xd5\x46\x28"
+ "\x52\x62\xbb\x08\x46\x19\x82\xb6\xe6\x2d\x3e\x04\x95\xd5\x0e\x7e"
+ "\xb3\x5f\x0e\x30\xbe\xf0\xdb\x36\x15\x69\xd5\x2d\x38\x95\x17\x27"
+ "\x2b\xa3\xc8\x68\x00\x55\xde\x2e\xd6\x07\xb4\x7a\x89\x1c\xe7\xc2"
+ "\x3c\xc4\x57\x9f\x45\xea\x77\xaf\xd8\xf1\xbe\x2a\x05\x46\x04\x51"
+ "\x83\x21\xa7\x1a\xa8\x23\x2f\x62\xa9\x67\xe6\xf3\xab\x47\xb9\xa6"
+ "\xec\x98\x7c\x7b\xd3\x42\x5d\x73\x37\xab\x46\x75\x2b\x33\xda\xf8"
+ "\xad\x2c\x62\x36\x2a\x91\x8f\x2c\x12\x4d\x00\xd5\x02\x98\x58\xfe"
+ "\xd2\x3d\x38\xc1\xe0\x2d\xeb\x7f\x22\xe6\x12\x72\xcd\xc7\x4b\xac"
+ "\x6d\x70\xc1\xcc\xda\x6d\xf1\x21\x44\xb4\x92\xec\xce\xd7\x6a\xde"
+ "\xea\x62\x63\xa9\x15\xe8\xf3\xea\xc6\xc8\x26\x39\xef\xa0\x76\x66"
+ "\x54\x45\xb6\xdd\x4b\xff";
+
+static const unsigned char s4u2proxy_ticket[] =
+ "\x61\x82\x04\x9f\x30\x82\x04\x9b\xa0\x03\x02\x01\x05\xa1\x0a\x1b"
+ "\x08\x41\x43\x4d\x45\x2e\x43\x4f\x4d\xa2\x20\x30\x1e\xa0\x03\x02"
+ "\x01\x03\xa1\x17\x30\x15\x1b\x03\x73\x71\x6c\x1b\x0e\x6d\x79\x73"
+ "\x71\x6c\x2e\x61\x63\x6d\x65\x2e\x63\x6f\x6d\xa3\x82\x04\x64\x30"
+ "\x82\x04\x60\xa0\x03\x02\x01\x17\xa1\x03\x02\x01\x02\xa2\x82\x04"
+ "\x52\x04\x82\x04\x4e\xaa\x63\x2e\xe0\x3a\x24\xed\x98\x29\x42\xa4"
+ "\x17\x2b\x4a\x17\x1d\xea\x46\x2a\xc9\xeb\x10\xeb\x02\xe3\xa2\x40"
+ "\xf5\x79\xaa\x1c\x83\x20\xe0\x24\x9b\x6f\x06\xc4\x31\x82\xc8\x52"
+ "\xdb\x9a\x04\x36\xff\x5c\x7a\xa5\xfe\x5c\xf3\x40\xcf\x7c\x31\x0f"
+ "\xda\x2a\x20\xa1\x7e\xdb\xf4\x05\x54\xcb\x51\xa0\x54\x25\xc8\x9f"
+ "\x4d\x23\x0a\xef\x56\x4e\xa0\xdf\xf5\x0b\xce\x75\x93\x5b\xf9\xe5"
+ "\x3a\xdf\x08\x3f\xce\x1c\x75\x6b\x4f\x38\x1a\x90\x4c\x3e\x99\x49"
+ "\x6c\x7a\x55\xf5\xdd\x59\x64\xab\x43\xfd\x3f\x45\x5a\xd3\x0f\x4f"
+ "\x37\x44\x03\x42\x0e\x83\xac\xf9\x04\x83\x43\xfc\x60\xc3\x1b\xc4"
+ "\xc0\x2a\x6c\x6e\x65\xf4\x8f\x2d\x52\x1f\x18\xbe\x09\x17\x10\x1d"
+ "\xd4\xc7\xe6\xa9\x9f\x70\x90\x65\x8a\x30\x63\x26\xfd\xb4\x63\xd0"
+ "\xaa\x3d\x80\x03\x79\x74\xc7\x5d\xe8\x50\x9e\x1b\x0a\xa7\x69\x62"
+ "\x91\xda\xcb\x80\xe8\xa3\x0d\xd8\xef\x05\x46\x2a\xb8\x14\x6f\x45"
+ "\x4e\xa6\x76\x28\x1b\xbe\x50\x0b\x5b\xf9\xe1\x61\x66\x5b\xe8\xb7"
+ "\xa1\x9c\xea\x2a\x8b\x28\x63\x8e\x20\x41\xaa\xdc\xca\x61\xa9\x1f"
+ "\x1b\xf1\xf3\x39\x47\xdf\x1f\xc3\x0d\xdd\xe7\x40\xb1\x8d\xbf\x28"
+ "\x22\xd4\x5d\x82\x63\x80\xc6\x75\x45\xa3\xe2\x79\x71\xa9\x5d\x9a"
+ "\x29\xa4\xc5\x3d\x1a\x56\x99\x2a\x3f\x4c\x97\x02\x85\xd8\x21\x15"
+ "\xd7\xaa\x8c\x6e\xa9\x0f\xb8\xa7\x1b\x43\xa4\xb5\xf0\xab\x2f\x77"
+ "\xa0\xa9\x23\xb2\x81\xf4\x0d\x02\x0e\x17\xa5\xb7\xa6\x54\xc6\x3b"
+ "\x12\xd9\x2e\x30\xdc\xb7\x84\x46\x9b\x28\x89\x15\x48\xd0\xe4\x44"
+ "\xd5\x22\x67\x3e\x58\x96\xcf\xd1\x0f\x5e\xd1\x5c\xa5\xdd\x5a\x60"
+ "\xf2\xf9\x36\xad\xe0\x39\x2a\x56\x98\x71\x37\x67\xca\x3a\xc4\x7f"
+ "\xda\x43\x22\x7b\xe9\xf3\x8c\x0d\x31\x9e\xc3\x8d\xf8\x49\xf1\x81"
+ "\xe0\xb3\x4d\x47\xfa\x91\xdd\x46\xfb\x03\x84\x13\x37\x9c\x12\x0c"
+ "\x80\x4f\x01\xc6\x19\x62\x0e\xba\x94\x0d\x89\x24\x0c\x14\xbe\x0f"
+ "\x06\xc2\x8d\x54\xfb\x84\x64\xa2\x57\x9e\x85\x54\x98\xad\x25\x2c"
+ "\xa0\x73\x39\x14\x47\xf4\xa6\x1d\xf8\x1e\x94\x4c\x2e\x0f\xd6\x33"
+ "\xa6\x1b\x58\x7a\xc1\x29\x8d\xc8\x7e\x79\xb7\x44\x92\x8a\xf3\x69"
+ "\x37\x34\x74\xe6\x29\xf7\x38\xb1\xb5\xad\x4a\x2a\x56\x86\xa5\xc5"
+ "\x65\xcf\x0b\x9b\x2a\x54\x31\x1d\xad\xc0\xac\xd0\xf3\xaf\x41\x9a"
+ "\x4c\x5b\x42\x2c\x4c\x38\x72\xa4\x74\xcb\xfb\x77\xe1\xc7\x08\xba"
+ "\x72\xc1\x8e\xa7\x60\xeb\x6a\x63\xeb\x75\x0f\xe6\xd0\x82\x43\xa3"
+ "\x49\x7c\x74\xac\x50\xbb\x30\xf8\x59\x31\xa6\xcf\xaf\xc9\x08\x1c"
+ "\x21\x6d\x42\xa6\x84\x7a\xc9\x3e\x1d\x65\xc8\x8a\x6f\x28\xaa\x54"
+ "\x0a\x87\xed\x09\xa4\x90\xe1\x4a\xda\x71\x9c\x3d\x06\x82\x86\xf6"
+ "\xc9\x0d\xe6\xcd\xdc\xe7\xe8\x9f\x07\x4b\x6b\xf3\x50\x30\xee\xdb"
+ "\xd6\x7c\x97\xa5\x53\x09\x91\xa8\xc1\x06\xed\xc2\x30\xd5\x66\x07"
+ "\x5c\x1c\xb2\x04\x81\x09\x9f\x7c\xdf\x47\xc7\xfa\x04\x4d\x73\xbd"
+ "\x1a\x28\x8c\x83\x2a\x4b\xcd\xcc\x93\x41\xc9\x9f\x05\x7a\xb6\xff"
+ "\x98\x58\xa4\x11\xf1\x3d\xca\x94\x71\xb6\x0e\x6e\xeb\x30\x3c\xfc"
+ "\x5a\xf6\x0e\x0b\x1a\x0a\x3d\xd0\x9a\x08\xd4\x43\xaf\x06\xbe\x8f"
+ "\xc0\xf2\xfb\xe7\x94\xa0\x5d\x9c\x44\x7f\xca\xbd\x1e\x83\xf8\x22"
+ "\xe8\x6e\x7f\xd4\xc6\xaa\x8a\x45\x76\x37\xf7\x45\xdb\xcb\x20\xa9"
+ "\xcc\x74\x62\x52\xe2\x88\xbf\x95\x4d\xe8\x1e\xac\x30\xfa\x9c\x1e"
+ "\xe7\xe6\xeb\x18\x75\xe3\x0f\xb8\xfc\xbf\x6c\x6f\x59\x51\xd4\x38"
+ "\xb0\xab\x85\x73\x16\x51\x5d\x27\x94\x83\x03\xd2\x86\x28\x99\xa1"
+ "\x8c\x04\x4c\xfb\x21\x79\x7b\x95\x96\x21\x47\x81\xc9\xba\xef\x13"
+ "\x18\xd6\x8f\xa9\xf4\x89\x25\x5b\xa4\xae\xbc\x6a\x59\x1e\x7b\x15"
+ "\xc9\xa5\xc8\x8a\x8c\x35\xec\xee\xe2\x8a\x0e\x1b\x8e\xaf\x4b\x51"
+ "\x9e\x66\xe7\x94\x56\xf6\x37\x93\x22\x5d\xe3\x9e\x33\x5e\xb4\x74"
+ "\xf1\x69\xe3\x93\xc3\xe8\xc7\x61\x09\x6a\xc1\xb7\x42\xcc\x3b\x5b"
+ "\x24\x40\x28\xf7\x9b\xef\x5c\x98\xb9\xe7\x2c\x01\xed\x99\x66\xa7"
+ "\x06\xeb\x08\x89\xd6\x5e\xce\x85\x08\x1a\x90\xc4\x92\x40\x53\xc5"
+ "\x53\x8b\xcb\x1a\xe9\x30\x8c\x48\xdb\x66\xc3\x98\x24\x1d\x5f\xee"
+ "\x6c\x2c\xc1\x3e\xcd\xcd\xb9\x1a\x5d\x8d\xb9\x64\xd9\x4c\x33\x83"
+ "\xa4\xa5\x08\x0a\xe3\x73\x0c\xe9\xd9\x6f\xb8\x78\x9a\x46\xdf\x6f"
+ "\x7f\x9f\x38\x69\x4b\x44\x00\x7e\x5b\xee\xf6\x2b\xba\xdd\xf7\x8a"
+ "\x0e\xa3\xff\xfc\x09\x5a\xd0\x44\x7e\x58\x2f\xfa\xe9\x1d\x1d\xc8"
+ "\x39\xc7\x2c\x62\xff\xf5\x22\xca\x8d\xae\xfd\x86\xef\x3b\x8f\xac"
+ "\x1b\x11\xb8\x6a\x4e\xf9\x6a\x93\xb1\xda\x8d\x80\xb9\xfa\xca\x52"
+ "\x0d\x4a\x45\xf1\x43\x5b\xca\x74\x1f\x94\xe6\x2a\x83\x2f\x76\x8c"
+ "\x70\x00\xcf\xa5\x95\x3c\x31\x10\x75\xd2\x75\xf8\x83\x09\x58\x11"
+ "\xff\xf9\x82\x32\x26\xad\x72\x85\x13\x64\x6e\xf6\xc1\x71\x55\xe3"
+ "\x51\x98\xda\x03\x76\xf0\x5b\x5f\xbe\x5c\xf3\x12\xe5\x6f\x03\xc4"
+ "\x36\x84\x66\xb7\xf8\xd5\xb9\x99\xeb\x66\x84\xbc\xf2\x78\x23\x87"
+ "\xb2\xa5\x64\xc4\x4a\xa1\x30\x93\x7f\x3a\x48\xe1\xad\xc0\x14\xc2"
+ "\x28\x14\x77\x7f\x23\xc7\xa8\xa2\x6c\xab\xd4\x74\xdf\xb1\x42\x84"
+ "\xa7\x11\x73\xef\x2d\xf6\x7a\xfb\xe1\xe6\xdb\xac\x57\x3b\xc7\xba"
+ "\x8c\x83\x19";
+
+static const unsigned char tgt_rodc[] =
+ "\x61\x82\x03\xe4\x30\x82\x03\xe0\xa0\x03\x02\x01\x05\xa1\x0a\x1b"
+ "\x08\x41\x43\x4d\x45\x2e\x43\x4f\x4d\xa2\x1d\x30\x1b\xa0\x03\x02"
+ "\x01\x02\xa1\x14\x30\x12\x1b\x06\x6b\x72\x62\x74\x67\x74\x1b\x08"
+ "\x41\x43\x4d\x45\x2e\x43\x4f\x4d\xa3\x82\x03\xac\x30\x82\x03\xa8"
+ "\xa0\x03\x02\x01\x12\xa1\x06\x02\x04\xb6\x51\x00\x01\xa2\x82\x03"
+ "\x97\x04\x82\x03\x93\xe2\x97\x36\xa2\x9f\x18\x79\x44\x87\xbf\xc8"
+ "\x27\x59\x40\xd1\x9d\x3b\x3d\x1d\x8b\xc8\x86\xfb\xc5\x4a\xf8\x27"
+ "\x5b\xee\x59\xcc\x3a\xcd\x2f\x0d\xb3\x9f\xb7\x87\xe2\x83\xdb\x36"
+ "\xee\xa0\x1c\xdb\x91\x9b\xe1\x50\x3e\xaa\x3d\xea\xae\x93\x65\xdf"
+ "\xb3\x23\xfb\xa6\x00\xaf\x55\x49\xf5\x6e\xd9\x2c\xc1\x61\x97\x37"
+ "\x19\x83\xe6\x60\xd8\x46\x2d\xdb\x0c\xc4\x55\x2e\x0a\x52\x0d\x64"
+ "\xb4\x80\xa9\x3d\x37\xb6\xed\x06\xdc\x32\xfd\x6a\x40\x20\xc4\x69"
+ "\x59\xf5\x80\x9c\x7f\x7a\x68\x88\x1c\x67\x37\x52\x85\x1a\x2f\x01"
+ "\xf8\x46\xd7\x7a\x24\xfb\x14\x31\xa8\x23\xd0\xac\x13\x85\x1c\xef"
+ "\xb1\xe4\x26\x20\x4f\x0c\xbb\xcc\xbb\x86\x40\xb3\x2e\x76\x25\x26"
+ "\x2e\x0f\x33\xec\xca\xac\x32\xa2\x35\x98\x1a\x9d\x34\x30\xe8\xaa"
+ "\x85\x8c\xa0\x0a\xf6\xe9\x60\x4f\x59\x20\xed\x51\x9d\xcf\xb4\xc1"
+ "\xdf\x1e\x8f\x91\x3e\xe2\x32\x9f\x68\x14\x41\x22\x2e\x05\xa7\x6d"
+ "\x1d\xa5\x55\xd8\x3b\x1c\xa4\x0b\x80\xf1\x43\x5f\xf7\xc2\xef\xa6"
+ "\x28\xcf\xbb\x2a\xbc\x0f\xbc\x20\x11\xff\xc1\x1b\x75\x5b\x49\x6f"
+ "\xc5\xc4\xa8\x3c\x46\xb3\xfd\x41\x70\x2a\xd8\x8b\xa6\xc1\x54\xad"
+ "\x15\x3e\x96\xca\x28\x3e\xca\x06\xe6\x0d\xad\xc8\x74\x32\x9a\x0d"
+ "\x80\x65\xd6\x49\x35\xc0\xd8\x75\xed\xb7\x4b\x9d\xb5\xd5\x3b\x3b"
+ "\xd3\x2e\x9f\xed\xbe\xd3\x83\x68\xe1\x3a\x25\x2c\xb5\xfe\xbd\x89"
+ "\xf3\x0e\xe3\x5e\xb3\x15\x2e\x0e\xb5\x2b\x97\x47\x6c\x6d\x88\x82"
+ "\x42\x54\x0d\x97\x52\x17\x56\x16\x9b\x5e\xaa\x63\xb0\xcb\x6f\xe6"
+ "\x0f\x9c\x9e\x6f\x3f\x49\x31\x60\x88\x2f\x25\xae\xff\x1c\x90\x55"
+ "\x9d\x63\x50\x56\x4d\x6e\x55\x5c\x48\x84\x1d\xf1\x0a\x03\xa6\x99"
+ "\x90\x13\xd6\x9a\xf1\x43\x5d\x0d\x69\x74\x3d\x60\xf5\xa0\x58\x29"
+ "\x98\x74\x10\x35\x2f\x6b\x35\x0b\x9a\xed\x3d\x7c\x4f\x00\x55\xec"
+ "\x0e\x20\xd0\x77\x46\x45\x7c\x0f\xfa\xf6\x55\xd9\x9f\xf8\x4b\x81"
+ "\xfa\x7a\x36\x05\xb9\x8e\xaf\xd8\xd3\x40\x6c\x0f\x72\x0d\x06\xba"
+ "\x91\x65\xbe\x5a\xfd\xf4\xb4\x49\xfa\x41\x83\xcb\xcf\x8d\x8a\xb0"
+ "\xf6\x3b\xcc\x08\xf8\x26\x41\x0d\x7e\xc6\xb3\x29\x8c\x33\x32\xb3"
+ "\x44\x7c\xbd\x0a\xc7\x0a\x58\x75\xfb\x2d\xf0\x53\x6c\xba\x89\x77"
+ "\xfd\x71\x7f\xe2\x9d\x9d\x35\x1d\x6b\xb2\x6f\x72\x27\x9b\xe5\x9e"
+ "\xc0\x21\x6f\x4a\x5f\x15\xf3\x13\xa4\xd9\x76\x96\xc1\xb3\xcf\x95"
+ "\xad\x47\x39\xa7\x10\x39\x7b\xfd\x9d\x71\xe3\xb8\xc4\xdf\xea\x96"
+ "\x40\x5e\xbb\x91\xfe\x99\x78\xc7\x97\x89\xca\x38\xd5\xdc\x7f\xad"
+ "\x3c\xf8\x59\x46\x05\x54\xb0\xfd\x33\x00\xd8\xa8\xb2\xf6\x44\xad"
+ "\xd5\xfc\x2d\xce\x92\x59\x85\x61\x5c\x53\xba\xf9\xe6\xc8\x47\x2f"
+ "\x50\xa3\x4a\xa6\x69\x70\xc2\x03\x5a\x44\x84\x20\x4b\x0a\x37\xa1"
+ "\x3b\xa8\x46\x96\xa6\x95\xfa\x59\x01\x38\xb5\xc7\xdb\x7c\xa8\x24"
+ "\xf9\x75\x90\xa9\x3d\x56\x5f\x95\x14\x17\xc7\xa3\x6f\xe7\xed\x0f"
+ "\x6b\xc9\x24\xfa\x0e\x4b\x33\x32\x0f\xd4\xe8\x3d\xae\x03\x9d\xfd"
+ "\xbf\x68\xef\x1b\x5a\xfa\x4b\x2e\x7f\x70\xd8\x95\x69\x03\x58\x1b"
+ "\xae\xf2\xde\xdb\x1e\xbd\x8a\xb0\xe5\xb3\x1a\x19\xe6\x1c\xf3\xf1"
+ "\xa5\xea\x8e\x61\x47\xd6\x4a\x5c\xb1\x2d\x4c\xcb\x22\xb5\x5a\x41"
+ "\xac\xad\xdc\x94\x71\xd4\x53\xcf\x67\xc6\xfa\xd4\x6b\x60\xe7\xf6"
+ "\x8e\xaf\xae\x98\x1c\x55\xd8\xed\xff\x48\x05\x69\xf4\x63\x4b\x0b"
+ "\x1a\xa4\x50\x3e\xff\x61\x72\x23\x5d\x8a\x19\x9e\x7b\x32\x79\x81"
+ "\xab\x4e\x5b\x5d\x06\x89\x2a\x26\x13\x20\x6d\xeb\xb2\x69\xb0\xd9"
+ "\xa3\x17\x04\xfd\x85\xfb\x54\x12\x02\xa8\x1d\xc4\xd8\x17\x15\xe0"
+ "\x67\xc0\x17\x81\x91\xab\x8a\x4b\x72\xe0\x10\x17\xc2\xd3\xe2\x5e"
+ "\x08\x24\xfe\x6f\x9d\xc0\x57\x03\x19\x4b\x62\x0a\xee\x3c\xd3\xc6"
+ "\xa7\x70\xe6\xca\x02\xea\x91\xf6\x31\xcd\x02\x5b\x55\xd2\xf4\x76"
+ "\x2b\x24\xbd\x09\x45\xe8\x00\x63\xbd\x3b\xf8\xeb\xe7\x17\x20\x24"
+ "\xaf\x11\x65\xaa\x52\xd1\xf5\x74\xf5\xed\xd2\x5b\x60\x86\x9a\xfc"
+ "\xa4\x63\x10\x25\x50\xb4\x40\x14\x97\x20\xf0\x53\xbe\x0f\x2a\x28"
+ "\x09\xac\x4d\x9d\x45\x52\x77\xcd\x65\x9a\x2c\xf2\x49\xfe\x92\x1a"
+ "\x6d\xb9\xf3\x29\x6c\xcd\x5b\xee\x73\x28\x6b\x2c\x14\xec\x6a\x25"
+ "\x64\xac\xcb\xdf\x1a\xe0\xaf\x56\xf6\x49\xea\xad\x06\x9c\xa3\x60"
+ "\xb2\xcf\x2c\xad\x19\xeb\xc3\x0f";
+
+static const unsigned char service_rodc[] =
+ "\x61\x82\x03\xf3\x30\x82\x03\xef\xa0\x03\x02\x01\x05\xa1\x0a\x1b"
+ "\x08\x41\x43\x4d\x45\x2e\x43\x4f\x4d\xa2\x13\x30\x11\xa0\x03\x02"
+ "\x01\x01\xa1\x0a\x30\x08\x1b\x06\x61\x70\x61\x63\x68\x65\xa3\x82"
+ "\x03\xc5\x30\x82\x03\xc1\xa0\x03\x02\x01\x17\xa1\x03\x02\x01\x02"
+ "\xa2\x82\x03\xb3\x04\x82\x03\xaf\xaf\x34\x2b\xc2\xe0\x1a\x4d\x2d"
+ "\xb9\xda\x8c\x44\x52\xa3\xc1\xbf\xe2\xb3\xc9\x27\x29\xd2\x90\xa4"
+ "\xca\x87\xd7\xae\x3d\x10\x1a\xc4\x88\x6c\x22\x78\x9a\xb8\xd9\xb0"
+ "\x64\xa8\xfc\x49\x8b\xcd\x95\xf6\xc0\xeb\x32\xaa\x70\x06\xdf\xa8"
+ "\x98\x9f\xa5\x56\x42\xdf\x33\xd5\x6d\x15\x9d\xea\x6c\x04\x0d\xef"
+ "\x06\x13\x52\xe2\xa7\xc3\x76\xb9\xec\x95\x94\xc4\xad\xad\xb5\xa0"
+ "\xf5\x44\x69\x69\x96\xf3\xfb\x9e\x99\x48\xca\x5d\x85\x34\x10\xfb"
+ "\x51\xb1\x6f\x59\x70\x98\x06\x39\x55\xdc\xa3\x1f\xc8\x36\x63\x47"
+ "\xc8\xfc\xc7\x8e\x44\xaf\x5c\x20\x79\x3c\x8f\x54\xb5\x3b\x38\xb4"
+ "\xda\xcf\x6c\xea\xcd\x33\x0d\xc6\x86\x07\x08\xa7\x37\x3f\xed\xc4"
+ "\x3a\xa6\x98\xcd\x5e\xf8\x06\x3c\x47\xea\x04\xaf\x1e\xd3\x88\x1e"
+ "\x17\xf9\xac\xa7\x9e\xf2\x92\x70\xef\xd3\xb7\x39\x24\x65\x0c\x32"
+ "\x7e\x03\x2f\x36\x31\xa1\x9b\xe4\x58\x8f\x78\xde\xec\xa5\xba\x54"
+ "\x68\xb4\x4c\x17\x23\x0a\x62\xc6\xb0\x22\x3d\x21\x35\xfa\x4f\xf4"
+ "\x6d\x9e\x46\xb7\xf5\xcc\x28\xe4\x78\x3a\x36\x6a\x44\xc5\x34\xb7"
+ "\x34\x0d\xac\x4f\x02\x41\x8f\xfd\xcb\xd4\x4c\xb6\x4e\xf1\xd1\xe7"
+ "\x4a\x1b\xf1\x96\xa5\xd3\x15\x74\xd4\x52\xbe\x1b\xbd\xe1\x17\xe8"
+ "\x77\x79\xf6\x51\xc4\xc3\xd9\x6a\xe9\x4c\x70\x10\x33\xed\x59\xa5"
+ "\x7d\x05\x17\xde\x61\x65\x5f\xf5\xde\x06\xa4\xd6\x39\xe4\x3f\x83"
+ "\xdd\x95\xa3\xb3\x57\x60\x1c\xf3\x42\xdb\xdc\xd5\x39\x76\x68\xd3"
+ "\x6e\xc8\x06\xff\x6b\x5b\x1d\x72\x7d\xb4\x4d\xec\x3e\xb8\x6d\x09"
+ "\xff\xa5\x0e\x30\xe8\x12\x72\x31\xce\xf3\xdd\x78\xee\x43\x53\x75"
+ "\x26\x43\xc2\x29\x1f\x78\x2f\x03\x4f\x2d\x82\xe3\x7c\x82\xb0\x1d"
+ "\x64\xdc\x67\xb3\x53\xa6\x7f\x17\xd5\x11\xc1\x0d\xde\x79\x28\x07"
+ "\x40\x08\xe0\xfa\x41\x2b\xeb\x3e\xa9\xf0\x92\xdd\x4f\xfe\x13\x05"
+ "\x73\x1a\xc7\xfe\x14\x56\x86\x32\x27\x4d\xe5\x4e\x15\x35\x1e\xe5"
+ "\x54\x87\x8f\x75\x2a\xcb\x48\x5d\xc4\xce\xd3\x71\x25\x3b\xc6\x51"
+ "\xe2\x4f\x83\x87\x05\x97\xc9\x35\x4a\xce\xd7\x5a\x82\xcc\xe5\xc1"
+ "\xf6\xf6\x40\x8a\x91\xce\x05\x3a\x6a\xba\x9b\x43\xc6\x9f\x3b\x59"
+ "\xb4\xb7\x9b\x24\x6e\xad\x98\xdf\x3e\x12\x9f\x17\x31\x0c\xc7\x7d"
+ "\x31\x0b\x6c\xc0\x7b\x72\x1f\xb3\xcf\x24\x80\x64\x49\x95\x5d\xc0"
+ "\x0a\x84\xfc\x66\xf7\xcc\xc6\x82\x78\xf4\x23\x69\xfd\x34\x09\x94"
+ "\x9e\xd6\x26\xd3\xb6\x4f\x61\x50\xd0\x38\x72\x6d\x06\xef\xa1\x0f"
+ "\x3d\x3d\x46\xb0\x4b\xd9\xe8\xe9\x76\x73\xfe\x53\x82\x84\xbd\xea"
+ "\x4b\x1b\x97\x5e\x23\x55\x8d\xe6\x2d\x14\xe2\x9c\xbd\x07\xd2\xc2"
+ "\x98\x18\xbe\x02\xda\x19\x89\x95\x05\x06\xdb\x59\x4b\xd3\xfc\x18"
+ "\x9a\xf7\x39\x98\x9b\x79\x9c\xe1\xbe\x96\xf5\x55\xd7\x2c\x1b\xbb"
+ "\x84\x1b\xd3\xad\x8c\x26\x50\xbf\x86\x1b\x59\xfa\xab\xf5\xaf\x2b"
+ "\x04\x75\xf9\x33\xcf\xed\x01\x46\xbc\x5c\xd8\x9a\x3c\x1e\x11\x9e"
+ "\x03\x86\xf7\xed\x72\x93\xde\xf4\x5f\xb7\x63\x9c\x13\x0a\xa9\xba"
+ "\x51\x12\x3d\x13\xa5\xcf\x3e\x4b\x0d\x09\xfe\x97\x87\xde\xdf\x23"
+ "\x8d\x2a\x5a\x97\x7d\xfc\xe0\x40\x1a\x99\x75\x02\x7a\xb9\xae\xb4"
+ "\x51\x5d\x48\xcd\x98\xb1\xa7\x1e\x91\x06\xf5\xb7\x85\xb5\xd3\xe0"
+ "\x9e\xa2\x44\x08\xd7\xed\xbf\x3f\x6c\x39\x19\xfe\xd9\x80\x24\xe4"
+ "\x16\x7d\xd8\x66\x1f\xbb\x85\xc1\x38\x03\x1f\x36\xce\x77\x18\x11"
+ "\x99\x22\x7e\xb1\x7c\x47\x19\xd7\x8d\x79\x39\xef\xf5\xbd\xa0\xf7"
+ "\xca\x88\x79\x7e\xc9\x2b\xd7\x99\x2c\x87\x78\x7b\x4f\x4c\x38\xd8"
+ "\x02\xcd\x7c\xd4\x07\x33\x74\x89\x61\xa7\x11\x04\x98\xb2\x5f\x95"
+ "\x0c\xc3\x17\x35\xf6\xc3\x38\xee\xc3\xf6\xcf\x46\x68\xeb\x95\xb4"
+ "\xa3\x92\xbb\xe9\xd7\x7c\x92\x7f\xd0\x67\x64\x7d\x93\xc6\x37\xb3"
+ "\xb4\xe2\xf6\x31\x89\x22\x4b\xd7\xa6\x9d\xad\x14\x0c\x00\xc4\x7c"
+ "\x44\xfa\x2c\x89\x3a\x78\xc0\xe8\xb2\x6e\x4f\xde\x37\x07\xca\x5e"
+ "\x4a\x7f\x27\xbc\x2e\x96\x5b\xaf\xd0\x6b\xa4\x31\xad\x21\x2d\x0e"
+ "\x4c\x25\x97\xde\x42\x07\xc3\x97\xf0\xf5\x3b\x69\x8c\x89\x34\x8f"
+ "\xd4\xe7\x7c\xca\x45\x83\x7f\xf7\x7b\x4e\x75\x86\x39\x3b\x67\xbe"
+ "\x57\x76\xa1\x26\x65\x1d\x49\x8c\x33\x5c\xdf\x05\x9b\xcf\x4d\xce"
+ "\x06\xc9\xaa\xd5\xee\xf0\x3a\x42\x75\x02\x93\xf5\xeb\x00\xa7\xa4"
+ "\xfc\xe6\xff\x9e\xda\xb6\xbd\xc9\xe0\x67\xac\x99\x74\x99\xd8\x3e"
+ "\xf1\x13\xa8\x2f\xd7\x9c\x26\x95\x0e\xbe\x52\x79\x9b\xda\x8a\x78"
+ "\x7e\x2b\x9f\x22\xf3\xfb\x0f";
+
+static const unsigned char s4u2self_rodc[] =
+ "\x61\x82\x03\xf2\x30\x82\x03\xee\xa0\x03\x02\x01\x05\xa1\x0a\x1b"
+ "\x08\x41\x43\x4d\x45\x2e\x43\x4f\x4d\xa2\x13\x30\x11\xa0\x03\x02"
+ "\x01\x01\xa1\x0a\x30\x08\x1b\x06\x61\x70\x61\x63\x68\x65\xa3\x82"
+ "\x03\xc4\x30\x82\x03\xc0\xa0\x03\x02\x01\x17\xa1\x03\x02\x01\x02"
+ "\xa2\x82\x03\xb2\x04\x82\x03\xae\x4d\x90\xed\x46\x56\x94\x72\x5e"
+ "\x2a\x3d\x13\xad\xfa\xfa\x0e\xd6\x75\x91\x38\x57\xd4\x31\x6b\x07"
+ "\x75\x4b\x5c\x3c\x2c\x7a\xdc\x71\xd9\x36\x27\xf9\x27\xbf\xf0\xa9"
+ "\xb5\x16\xa0\x12\x3c\x36\x36\x16\x6e\xa5\x19\xcb\x28\xf9\xbb\xe3"
+ "\x66\xf7\x02\xad\xa8\xf9\xca\xe0\x84\x27\x7e\x9f\x81\x02\xea\xba"
+ "\x85\x6c\x57\x56\x39\x59\xfd\xce\x0f\xb6\x7d\x11\x1c\xc4\x9c\x92"
+ "\xb7\xbc\xe0\xc9\x51\xb8\x0f\xd4\x03\x84\xc4\x25\x0b\x9d\x44\x56"
+ "\x3f\xc2\xf3\x63\x7b\x8d\x2b\x61\xf2\x5f\x5b\x51\x46\x9f\x81\x1e"
+ "\xfc\xc6\x96\x71\x81\x63\xf9\xd8\x20\x57\x08\x6a\xf2\xce\xf7\x4b"
+ "\x7f\x92\x3b\x20\x21\xac\x1e\x30\x9e\x88\x71\x55\x00\x12\xef\xe4"
+ "\xfe\xf1\x6c\xe1\xab\x2f\x7c\xd9\xea\x53\xac\xd8\x74\x36\x04\xe7"
+ "\x40\x9e\x2d\x49\xc4\x9a\x6d\xdb\x95\xd1\xa1\x41\x27\xf9\x9d\xa7"
+ "\x16\x44\xd3\x58\x50\x95\x93\xdd\xba\xd0\x81\x17\xaf\x37\x19\x99"
+ "\x66\x3d\xc8\x3b\x75\xa0\xef\xd8\xa6\x8d\xa5\xe9\x94\xba\x53\x1c"
+ "\x0f\xc7\xcc\x34\x34\x23\x4f\xd5\x63\xda\x33\x49\x9c\x89\xd9\xb7"
+ "\xef\x3d\xf3\x9b\x44\x44\xcf\x84\x72\x0d\x54\xca\x40\x67\x42\x81"
+ "\xd9\xd8\xd4\x83\x6c\x52\x94\x1b\xdc\x36\x81\xee\x51\x9f\x82\x1c"
+ "\xda\x04\x84\x26\x0c\x83\xd2\xe0\x56\xbe\x53\x6b\x50\x43\xc2\x1e"
+ "\xaa\x08\xce\x37\x6b\xa8\xa8\xf8\xf2\x03\x69\xfb\xfa\xcb\xfc\xa4"
+ "\x89\x47\xbb\xd2\x68\xe5\x2d\x00\x3e\xb2\x06\x71\xda\x4c\x35\xe9"
+ "\x6d\xfc\x17\x2a\xdf\xc2\xd5\x96\x67\x03\x39\x75\xe9\xa7\x1f\x77"
+ "\xb2\xa8\x0d\xc1\x50\xc2\xe5\xed\x1a\x88\xc3\x73\x81\xa9\x86\xd2"
+ "\xc6\x34\xc7\xaa\x1c\x7f\xe6\x47\xbf\x47\xc9\x90\x39\xb3\x2c\x31"
+ "\xa0\x26\xee\x7d\xbc\x61\xe0\x26\xaa\xf6\xce\x73\x6f\xdc\xed\x27"
+ "\xdd\x13\x53\x0e\x21\x52\x1f\xd3\x75\xdb\x07\x62\x14\x00\xda\x85"
+ "\x76\x77\x16\x34\x30\x90\x7f\x94\xc5\x54\x9d\xc6\xce\xab\x11\x0b"
+ "\x98\xa9\xe6\x5f\x82\xb7\x1b\x13\xcd\xb0\xcc\xa6\xb8\x27\xb3\xd7"
+ "\x0f\x1f\xd8\x75\x56\x0e\xc5\x73\x95\x6f\x90\xda\x49\x12\xd8\x2d"
+ "\x23\x49\x13\x43\x49\x1e\xe3\xbf\x80\x4a\xde\xd6\x97\x1e\x33\x50"
+ "\x44\x6b\x7b\x00\x05\x90\xab\xfe\x94\xa8\x7c\x40\x86\x42\x4a\x6b"
+ "\xc7\x26\x21\x12\x19\x98\x01\xd5\x64\x7d\xdb\xf7\xe3\xf7\xea\xca"
+ "\x5d\xf8\xcb\x0a\x3f\x83\xf2\x6b\xe7\x2e\x3c\x71\x73\xc9\x3c\xc0"
+ "\x82\xc5\x2d\x7b\xd0\x03\xa2\xe2\xd9\x6d\xcd\x15\xd5\xd4\xbf\x90"
+ "\xc6\xf4\x19\x5b\x72\x0f\xaf\x42\xd4\x28\x58\x4f\xbe\xff\x63\x6a"
+ "\x0d\x42\x9f\x05\xfe\xbd\xdb\x81\x18\xaa\x73\x4b\x16\x96\x1b\x62"
+ "\xe8\x21\x88\xde\x9a\x57\x70\xcc\xab\x49\x4e\x0c\x31\xec\x8d\xce"
+ "\x82\x20\x3c\x44\x9b\xbc\x36\xb2\x8f\x7d\xe5\xea\x11\xf6\x71\x16"
+ "\x8e\x66\xcb\xfb\xc2\x92\xf5\xc1\x09\xac\x90\x68\xc6\xd7\x93\x21"
+ "\xcb\xb8\x57\x47\x56\x8c\x13\x7e\x78\x81\x08\x25\x3d\x4c\x1d\xeb"
+ "\x39\x2c\xf5\x9b\x67\x5d\xb4\xee\xb5\x71\xba\xcf\x29\x7a\x6b\xa5"
+ "\x30\x4a\xfd\x16\x33\x5d\x68\x95\x62\xe7\x76\xca\x06\xb8\x94\x51"
+ "\x1f\x9a\x71\x99\x78\xaa\xec\xcf\x27\xc9\x16\xcb\x91\xa0\xbe\xca"
+ "\xf9\x9c\xbe\x4d\xb0\xb9\x98\x21\x01\xb2\xa7\x7a\x8a\x0d\x1c\x62"
+ "\xeb\x7d\x52\x81\xf9\xf5\x94\x0b\x27\x6a\x1c\xfc\xb6\xb2\x3a\x52"
+ "\x39\xd2\x6c\xca\x23\x43\xd1\xbf\x44\x54\x85\xb6\xd5\xb9\x93\xb9"
+ "\x91\x86\x59\x7f\xd2\x23\x1c\xeb\x2c\x5d\xb0\xcd\x09\x2d\x83\x62"
+ "\x24\x94\x65\x64\x13\x00\xe0\x1d\xd0\xf5\x56\x79\xff\xcc\xa9\xb9"
+ "\xda\xd4\x6a\xab\xe9\x2a\x91\x40\x44\xed\x7b\x8c\xed\xb1\x39\x70"
+ "\xd0\x51\x51\x6c\x45\x5f\xd4\xed\x0d\x36\x17\xf0\x69\xf6\x92\x72"
+ "\xca\xc8\x90\x1e\xe0\x44\xf0\x19\x2e\x2c\x1f\x12\x42\xa3\x15\x9d"
+ "\x37\x86\xa3\xa3\x6e\x04\xfc\x84\x73\xf8\x1d\x13\x30\xe5\x0f\x32"
+ "\x58\xab\x51\x0e\xad\x0a\xcc\xb9\x32\x81\x44\x7c\x6e\xc1\xec\xcd"
+ "\x5d\x6a\x9a\xb7\x27\x53\x98\xcc\x2b\x8d\x3c\xac\xbe\x12\xcb\x01"
+ "\xeb\xe7\xbe\xb5\x10\x16\x22\xc1\x92\x86\xe7\xa6\x1f\x88\xfa\x6a"
+ "\x70\xec\xd8\x38\x31\x85\x6f\x08\x33\x3c\x1b\x49\x68\xd4\xa5\x4c"
+ "\x7e\xf1\xbc\x25\x4f\x2f\xef\x39\xad\x78\x19\x23\x31\x47\xa1\x96"
+ "\xae\x7b\x8d\x8b\xf1\xf4\xc4\x3b\x06\xc0\xf6\x6e\x0f\xd2\xe0\x18"
+ "\xca\xc4\x09\x1b\x34\xbe\x1f\x12\x21\x69\x79\x9c\xaf\xe2\x78\xb4"
+ "\x19\x85\x83\xb7\x9c\x2d\x1a\x14\x1d\x64\xc8\x36\x48\xf2\x3d\xf6"
+ "\x26\x8c\x5a\x4c\x03\xae";
+
+static const unsigned char s4u2proxy_rodc[] =
+ "\x61\x82\x04\x9f\x30\x82\x04\x9b\xa0\x03\x02\x01\x05\xa1\x0a\x1b"
+ "\x08\x41\x43\x4d\x45\x2e\x43\x4f\x4d\xa2\x20\x30\x1e\xa0\x03\x02"
+ "\x01\x03\xa1\x17\x30\x15\x1b\x03\x73\x71\x6c\x1b\x0e\x6d\x79\x73"
+ "\x71\x6c\x2e\x61\x63\x6d\x65\x2e\x63\x6f\x6d\xa3\x82\x04\x64\x30"
+ "\x82\x04\x60\xa0\x03\x02\x01\x17\xa1\x03\x02\x01\x02\xa2\x82\x04"
+ "\x52\x04\x82\x04\x4e\xd2\x92\xec\x00\xf9\xc9\x37\xde\x46\xf6\x35"
+ "\x62\xb7\xa1\x77\x0c\x9a\x4f\x6d\x17\x2e\xfd\x59\x24\xfe\x85\x32"
+ "\x3f\xf2\x40\x1e\xcd\xf1\xa6\xd2\xeb\xba\x26\xa1\x87\xee\x0b\xee"
+ "\xbf\x3e\xad\x73\x07\xf1\xc8\xb9\x2b\xc7\x16\x31\xf3\x63\x95\x56"
+ "\x5d\x5d\x00\x6a\xff\xa0\x20\x05\x14\x0b\x50\x0b\x1e\x1a\xf2\x61"
+ "\x29\x1b\x49\x54\xf9\xac\x6c\x08\x91\xdf\x44\x3e\x43\x42\xbe\x4a"
+ "\x5a\x7d\xaf\xd5\xb9\x26\xe4\x91\x5f\xf0\xcc\x55\x3d\xc7\xc4\xc0"
+ "\x46\x3b\x32\x1f\xca\xcf\x16\xec\x18\x1b\x29\xe9\xb1\x4c\xdd\x0f"
+ "\xb3\x53\x2b\x0a\x7a\x5a\xff\xa0\xf4\x62\xcf\xf1\x2c\xc9\x64\xfa"
+ "\x35\xad\xb7\x18\x9b\x53\xb2\xe4\xdc\x81\x59\x8b\x2a\xb7\x94\xe0"
+ "\xf5\x99\x7d\x04\xb6\x49\xa2\x9a\x6a\xcc\x17\x62\x63\x5d\x2e\xf2"
+ "\x24\x56\x58\x00\x68\x6a\x60\x37\xf9\xa7\x55\xac\xb8\x95\xcb\x22"
+ "\x6a\xd6\x6c\x91\x99\x22\xc4\x33\x38\xfa\xf4\x7f\xf0\xf1\xae\x2e"
+ "\x5c\xa5\x6c\x6b\x98\x3e\x82\x94\xee\x2e\x4c\xbd\x41\xb8\x4f\xeb"
+ "\x0a\xca\xb1\x0b\x88\xfb\x51\x76\x87\x69\x7c\x0b\x61\xc3\xe6\xe1"
+ "\xd8\x2a\xc3\xee\xde\x13\x70\xbf\x6a\x9f\x7d\x2a\x6f\x7b\x57\x28"
+ "\xd3\x9e\x39\xf8\xc7\x05\xd5\xc0\xe3\x11\x11\x05\xeb\x2f\x08\x14"
+ "\x1c\x98\xae\x7e\x56\x8a\xb7\xcc\x2b\x74\xda\x01\x69\xeb\x56\x3c"
+ "\x89\x4f\x5d\xf8\xf7\xdb\x73\xa4\x84\x29\x91\x79\x32\xcc\xa0\xc1"
+ "\x28\xad\x9d\x4e\xcf\x45\x00\x6e\x8a\xe7\xf8\xd5\xeb\x87\x51\x37"
+ "\xcb\xb9\x4f\xc7\x08\x27\x2a\xf3\xaa\x24\x26\x0b\xed\x40\xcf\x74"
+ "\xae\xa9\xa3\xed\x1e\x97\xd0\x05\xb5\xae\xdf\x37\xb5\x24\x52\xa1"
+ "\xac\xd7\x31\xa2\xef\xc8\xab\x8a\xc4\x8c\x3d\x7c\xf3\x00\xf0\xc3"
+ "\xe7\xa3\x6d\x93\x83\xe4\x08\x2e\xa1\xb5\xc4\xdc\x4b\x3f\x06\x23"
+ "\x40\xaa\x0a\x72\xe6\x5a\xad\x65\x53\x3d\x48\x6c\x6f\xe3\xc5\x8b"
+ "\xa3\xba\x54\x73\x78\x07\xf8\x88\xd5\xf4\x87\x04\x5d\x88\x1b\xba"
+ "\x4e\x67\x9f\x92\xe8\x9c\xf0\xc4\xba\xfb\xe3\x78\xe2\xd9\xa3\x38"
+ "\xdb\xd6\x41\x4c\xa4\x76\x92\x36\xc1\xd7\x30\x05\x3f\xf8\x9f\xd1"
+ "\xf8\x79\x13\xeb\x98\xc2\x7a\xa3\x25\xab\x32\x1e\x14\x10\x87\xc0"
+ "\x00\x68\x26\xf8\x8d\x4d\xb5\x96\xb7\x35\x81\xe5\x0c\x3f\x45\x2c"
+ "\xcf\x4e\xdd\xda\xe6\xd4\xb3\xcb\x50\xf1\xe5\x48\x4c\xec\xcc\x10"
+ "\x33\xa0\x11\x53\x0d\xf3\x2c\x98\xcb\x76\xbf\x6e\xd7\xe9\x20\xe7"
+ "\xdb\xbd\xae\xcf\x69\x0e\xd1\xce\x47\xae\x5a\xe1\x21\x0d\xe9\xd5"
+ "\x2f\x09\xc4\x36\x53\x24\x4a\x5c\xac\x07\xff\xd8\xac\xfe\xae\x91"
+ "\x93\x92\xbf\xc6\x3b\xa4\xdb\x28\x52\x23\x58\x7d\xcb\xbd\x39\x34"
+ "\x07\xeb\x56\x1a\xf9\x47\xf8\x70\xee\x60\x51\x2e\x80\x92\xd4\xcf"
+ "\xd8\x9d\x75\x16\x50\xf1\xb0\x02\x61\x99\x51\x7c\x46\x48\xf9\x6b"
+ "\x84\xdf\x5c\xef\xe1\x1f\x0c\x22\x9b\xdc\xbc\x76\x7f\x3f\x6d\xfe"
+ "\xb8\x2f\x93\xb9\x27\x58\xa9\x93\x42\xda\xf2\x67\xf7\x01\xbe\xd8"
+ "\xa2\x18\xec\x1e\x40\x3d\x3b\x6f\xfe\x50\xab\xb9\x35\xb7\xdd\x2a"
+ "\xe1\x51\xf9\xce\xea\xf5\x1d\xed\x6c\x2b\xbc\x86\xc9\x53\x41\x8b"
+ "\x2e\x06\xc8\xc0\x08\x48\x37\x40\x8c\xf8\xe9\x4b\xc7\xc0\x6f\x1b"
+ "\xe1\x0c\x8c\x0e\xf4\x73\x19\x7e\xc6\x36\x84\xa2\x8f\x72\x2e\x59"
+ "\x53\x25\x2c\x92\x95\x04\x9b\x13\x97\x7a\xc7\x53\xa4\xa6\x0f\xf3"
+ "\x06\x59\x25\xe7\xd5\x35\x0e\xe9\x10\x95\x60\x0f\x53\xd4\x24\x13"
+ "\x72\xf6\x6d\x17\xb8\x43\xb2\xac\x40\x15\x11\xb6\x1b\xbb\x13\xb3"
+ "\x90\x66\x85\x92\xcb\xb4\xf5\x9c\x15\x89\x41\xbc\x07\xb0\x37\x21"
+ "\xff\x13\x93\x55\xe9\xe0\x2d\x32\x64\x62\x40\x45\xb5\x41\x80\xdd"
+ "\xb8\xf2\xe9\x64\x3e\xfb\xe6\x69\x1c\xd0\xb4\xb1\xa2\x58\x95\xe5"
+ "\xf7\x48\x8e\x10\x4c\x8b\x05\x96\xfa\x6f\x36\x34\xe1\x29\x1c\x65"
+ "\x65\x8d\xb0\x39\x50\x27\x00\xac\xa6\x4f\x5b\xd2\xb0\xfe\x69\x17"
+ "\xa2\xa8\x19\x34\x78\x9b\xef\x8c\xc2\xb9\xf1\xb6\xee\x28\xf4\x74"
+ "\xd6\x18\xe0\x0f\x36\x91\xf4\x56\xbc\x5d\x16\x21\x0e\x14\xb2\x5e"
+ "\x42\x38\xe2\x10\x81\x31\x54\x4b\xf5\xfd\x62\x72\xb0\x05\x16\x19"
+ "\x88\xe0\xd4\x5d\x5f\x10\x5c\x0d\x1f\x6a\x9f\x27\x48\x58\x18\xd1"
+ "\x60\x46\x17\xf3\x5e\xbc\xf1\x3a\xcd\x4b\x01\x08\x2e\x34\x5e\xa6"
+ "\x91\xa3\x87\x0f\xe7\x34\x9c\xcb\x87\x95\x40\xee\x22\x1c\x41\x55"
+ "\xc1\x6b\x36\x22\xa2\xbb\xf2\x55\x04\xb7\x79\x0f\xe1\xb8\x95\xcf"
+ "\x7b\x8a\x37\x6d\x1e\x78\x09\x5c\x1a\x6c\xa3\x93\x13\x70\xfe\x37"
+ "\xcc\x4a\xe7\x58\xda\xaa\x14\xe1\x32\xac\x64\xdb\x52\xef\x33\x71"
+ "\xf3\x27\xa5\x2e\x2c\x69\xe3\xa6\xab\x15\xe5\xdc\x27\xf4\xe8\x6d"
+ "\x7a\x66\x9a\x1e\x69\x46\xa9\xfa\x02\xbb\x35\x6e\x16\xc0\x06\xdf"
+ "\xd7\xcf\x8b\xab\x3e\xfc\x62\x7d\x35\x95\xb8\x15\xe2\xee\x6d\x61"
+ "\x5b\x7b\xb5\x88\x03\x45\x1c\xa0\x79\xff\x81\x4f\x75\xa9\xe7\x0a"
+ "\xed\x81\xac\xe6\x2f\x86\xb2\x23\x9b\x5a\xfe\x5c\xee\x18\x5a\x4a"
+ "\x0f\x4a\xf4\x49\x8d\xbc\x7f\x3f\xc4\xbc\x7f\xbf\x41\x95\x62\x9e"
+ "\xc6\x73\x5f\x5a\x5d\x41\x53\xe2\xaa\x03\xc8\x00\x68\xad\x26\xf2"
+ "\x8f\x66\x78\x10\x3f\xa8\x56\x4b\x77\xb9\x0d\x94\x49\x54\x47\xd5"
+ "\x69\x9d\x4f\x44\xce\xc3\x6d\xae\x51\x20\x24\x61\xb6\x6f\xff\x27"
+ "\xc4\x36\xb1";
+
+static const unsigned char extra_logon_info[] =
+ "\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\xf0\x01\x00\x00"
+ "\x88\x00\x00\x00\x00\x00\x00\x00\x0a\x00\x00\x00\x1e\x00\x00\x00"
+ "\x78\x02\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x00\x98\x00\x00\x00"
+ "\x98\x02\x00\x00\x00\x00\x00\x00\x0d\x00\x00\x00\x00\x00\x00\x00"
+ "\x30\x03\x00\x00\x00\x00\x00\x00\x11\x00\x00\x00\x08\x00\x00\x00"
+ "\x30\x03\x00\x00\x00\x00\x00\x00\x12\x00\x00\x00\x1c\x00\x00\x00"
+ "\x38\x03\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x10\x00\x00\x00"
+ "\x58\x03\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00\x10\x00\x00\x00"
+ "\x68\x03\x00\x00\x00\x00\x00\x00\x01\x10\x08\x00\xcc\xcc\xcc\xcc"
+ "\xe0\x01\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\x7f\xff\xff\xff\xff"
+ "\xff\xff\xff\x7f\x59\xa1\x0f\x59\x77\xf5\xd7\x01\x59\xa1\x0f\x59"
+ "\x77\xf5\xd7\x01\x59\x21\x69\x4e\x78\x16\xd8\x01\x14\x00\x14\x00"
+ "\x04\x00\x02\x00\x00\x00\x00\x00\x08\x00\x02\x00\x00\x00\x00\x00"
+ "\x0c\x00\x02\x00\x00\x00\x00\x00\x10\x00\x02\x00\x00\x00\x00\x00"
+ "\x14\x00\x02\x00\x00\x00\x00\x00\x18\x00\x02\x00\x00\x00\x00\x00"
+ "\x4d\x04\x00\x00\x01\x02\x00\x00\x01\x00\x00\x00\x1c\x00\x02\x00"
+ "\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x0e\x00\x10\x00\x20\x00\x02\x00\x0e\x00\x10\x00"
+ "\x24\x00\x02\x00\x28\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x02\x00\x00\x00\x2c\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x0a\x00\x00\x00\x00\x00\x00\x00\x0a\x00\x00\x00"
+ "\x63\x00\x39\x00\x64\x00\x38\x00\x30\x00\x31\x00\x61\x00\x38\x00"
+ "\x5f\x00\x30\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x01\x00\x00\x00\x01\x02\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00"
+ "\x00\x00\x00\x00\x07\x00\x00\x00\x54\x00\x45\x00\x53\x00\x54\x00"
+ "\x2d\x00\x44\x00\x43\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00"
+ "\x07\x00\x00\x00\x45\x00\x58\x00\x41\x00\x4d\x00\x50\x00\x4c\x00"
+ "\x45\x00\x00\x00\x04\x00\x00\x00\x01\x04\x00\x00\x00\x00\x00\x05"
+ "\x15\x00\x00\x00\xa1\xa5\x92\x7f\x29\x19\xc5\x3b\xbb\x56\xb0\x05"
+ "\x02\x00\x00\x00\x30\x00\x02\x00\x07\x00\x00\x00\x34\x00\x02\x00"
+ "\x07\x00\x00\x00\x05\x00\x00\x00\x01\x05\x00\x00\x00\x00\x00\x05"
+ "\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\xf1\x01\x00\x00\x01\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x12"
+ "\x01\x00\x00\x00\x00\x00\x00\x00\x00\xb6\x8f\x5a\x77\xf5\xd7\x01"
+ "\x14\x00\x63\x00\x39\x00\x64\x00\x38\x00\x30\x00\x31\x00\x61\x00"
+ "\x38\x00\x5f\x00\x30\x00\x00\x00\x2c\x00\x18\x00\x16\x00\x48\x00"
+ "\x03\x00\x00\x00\x14\x00\x60\x00\x1c\x00\x78\x00\x00\x00\x00\x00"
+ "\x63\x00\x39\x00\x64\x00\x38\x00\x30\x00\x31\x00\x61\x00\x38\x00"
+ "\x5f\x00\x30\x00\x40\x00\x45\x00\x58\x00\x41\x00\x4d\x00\x50\x00"
+ "\x4c\x00\x45\x00\x2e\x00\x43\x00\x4f\x00\x4d\x00\x00\x00\x00\x00"
+ "\x45\x00\x58\x00\x41\x00\x4d\x00\x50\x00\x4c\x00\x45\x00\x2e\x00"
+ "\x43\x00\x4f\x00\x4d\x00\x00\x00\x63\x00\x39\x00\x64\x00\x38\x00"
+ "\x30\x00\x31\x00\x61\x00\x38\x00\x5f\x00\x30\x00\x00\x00\x00\x00"
+ "\x01\x05\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00\xa1\xa5\x92\x7f"
+ "\x29\x19\xc5\x3b\xbb\x56\xb0\x05\x4d\x04\x00\x00\x00\x00\x00\x00"
+ "\x02\x00\x00\x00\x01\x00\x00\x00\x01\x05\x00\x00\x00\x00\x00\x05"
+ "\x15\x00\x00\x00\xa1\xa5\x92\x7f\x29\x19\xc5\x3b\xbb\x56\xb0\x05"
+ "\x4d\x04\x00\x00\x00\x00\x00\x00\x10\x00\x00\x00\xfd\x39\xd8\x32"
+ "\x3b\x8c\xa5\xfe\x6b\x3d\x27\xff\x10\x00\x00\x00\x2f\x99\x7e\x57"
+ "\xca\xe4\xe1\xc7\x1b\xc0\xbd\xee";
+
+struct test_pac_ticket {
+ const char *name;
+ const unsigned char *ticket;
+ size_t ticket_len;
+ uint16_t rodc_id;
+ const krb5_keyblock *key;
+ const krb5_keyblock *kdc_key;
+};
+
+static const struct test_pac_ticket pac_tickets[] = {
+ { "tgt_ticket", tgt_ticket, sizeof(tgt_ticket), 0, &rwdc_tgt_key, &rwdc_tgt_pac_key },
+ { "service_ticket", service_ticket, sizeof(service_ticket), 0, &server_key, &rwdc_tgt_pac_key },
+ { "s4u2self_ticket", s4u2self_ticket, sizeof(s4u2self_ticket), 0, &server_key, &rwdc_tgt_pac_key },
+ { "s4u2proxy_ticket", s4u2proxy_ticket, sizeof(s4u2proxy_ticket), 0, &server_key, &rwdc_tgt_pac_key },
+ { "tgt_rodc", tgt_rodc, sizeof(tgt_rodc), 46673, &rodc_tgt_key, &rodc_tgt_pac_key },
+ { "service_rodc", service_rodc, sizeof(service_rodc), 46673, &server_key, &rodc_tgt_pac_key },
+ { "s4u2self_rodc", s4u2self_rodc, sizeof(s4u2self_rodc), 46673, &server_key, &rodc_tgt_pac_key },
+ { "s4u2proxy_rodc", s4u2proxy_rodc, sizeof(s4u2proxy_rodc), 46673, &server_key, &rodc_tgt_pac_key },
+ { NULL, NULL, 0, 0, NULL, NULL }
+};
+
+static void
+t_err(krb5_context context,
+ const char *test,
+ const char *func,
+ krb5_error_code error)
+{
+ krb5_err(context, 1, error, "test %s failed in %s", test, func);
+}
+
+static krb5_boolean
+is_krbtgt(const PrincipalName *p)
+{
+ return (p->name_string.len == 2 &&
+ strcmp(p->name_string.val[0], KRB5_TGS_NAME) == 0);
+}
+
+static void
+check_ticket_signature(krb5_context context,
+ const struct test_pac_ticket *tkt)
+{
+ krb5_error_code ret;
+ krb5_crypto crypto;
+ krb5_data data, orig_pac_ad;
+ Ticket ticket;
+ AuthorizationDataElement ad;
+ EncTicketPart et;
+ krb5_principal client;
+ krb5_pac pac;
+ krb5_boolean signedticket;
+ krb5_cksumtype cstype;
+ uint16_t rodc_id;
+
+ ret = decode_Ticket(tkt->ticket, tkt->ticket_len, &ticket, NULL);
+ if (ret)
+ t_err(context, tkt->name, "decode_Ticket", ret);
+
+ ret = krb5_crypto_init(context, tkt->key, tkt->key->keytype, &crypto);
+ if (ret)
+ t_err(context, tkt->name, "krb5_crypto_init", ret);
+
+ ret = krb5_decrypt_EncryptedData(context,
+ crypto,
+ KRB5_KU_TICKET,
+ &ticket.enc_part,
+ &data);
+ if (ret)
+ t_err(context, tkt->name, "krb5_decrypt_EncryptedData", ret);
+
+ ret = decode_EncTicketPart(data.data, data.length, &et, NULL);
+ if (ret)
+ t_err(context, tkt->name, "decode_EncTicketPart", ret);
+
+ ret = _krb5_principalname2krb5_principal(context, &client, et.cname,
+ et.crealm);
+ if (ret)
+ t_err(context, tkt->name, "_krb5_principalname2krb5_principal", ret);
+
+ ret = _krb5_kdc_pac_ticket_parse(context, &et, &signedticket, &pac);
+ if (ret)
+ t_err(context, tkt->name, "_krb5_kdc_pac_ticket_parse", ret);
+
+ heim_assert(!is_krbtgt(&ticket.sname) == !!signedticket, "ticket-signature");
+
+ ret = krb5_pac_verify(context, pac, et.authtime, client,
+ tkt->key, tkt->kdc_key);
+ if (ret)
+ t_err(context, tkt->name, "krb5_pac_verify ticket-sig", ret);
+
+ ret = krb5_pac_get_kdc_checksum_info(context, pac, &cstype, &rodc_id);
+ if (ret)
+ t_err(context, tkt->name, "krb5_pac_get_kdc_checksum_info", ret);
+
+ heim_assert(cstype == CKSUMTYPE_HMAC_MD5, "Wrong checksum type");
+ heim_assert(rodc_id == tkt->rodc_id, "Wrong RODCIdentifier");
+
+ /* Try to resign the PAC */
+ ret = copy_AuthorizationDataElement(&et.authorization_data->val[0], &ad);
+ if (ret)
+ t_err(context, tkt->name, "remove_AuthorizationData", ret);
+ orig_pac_ad = ad.ad_data;
+
+ ret = remove_AuthorizationData(et.authorization_data, 0);
+ if (ret)
+ t_err(context, tkt->name, "remove_AuthorizationData", ret);
+
+ ret = _krb5_kdc_pac_sign_ticket(context, pac, client, tkt->key,
+ tkt->kdc_key, tkt->rodc_id,
+ NULL, NULL, signedticket, &et, NULL);
+ if (ret)
+ t_err(context, tkt->name, "_krb5_kdc_pac_sign_ticket", ret);
+
+ heim_assert(krb5_data_cmp(&et.authorization_data->val[0].ad_data,
+ &orig_pac_ad) == 0, "PACs differ");
+
+ free_AuthorizationDataElement(&ad);
+
+ /* Sign and verify a clean PAC */
+ krb5_pac_free(context, pac);
+ ret = krb5_pac_init(context, &pac);
+ if (ret)
+ t_err(context, tkt->name, "krb5_pac_init", ret);
+
+ ret = remove_AuthorizationData(et.authorization_data, 0);
+ if (ret)
+ t_err(context, tkt->name, "remove_AuthorizationData 2", ret);
+
+ ret = _krb5_kdc_pac_sign_ticket(context, pac, client, tkt->key,
+ tkt->kdc_key, tkt->rodc_id,
+ NULL, NULL, signedticket, &et, NULL);
+ if (ret)
+ t_err(context, tkt->name, "_krb5_kdcsignedticketsign_ticket 2", ret);
+
+ krb5_pac_free(context, pac);
+
+ ret = _krb5_kdc_pac_ticket_parse(context, &et, &signedticket, &pac);
+ if (ret)
+ t_err(context, tkt->name, "_krb5_kdc_pac_ticket_parse 2", ret);
+
+ heim_assert(!is_krbtgt(&ticket.sname) == !!signedticket, "ticket-signature");
+
+ ret = krb5_pac_verify(context, pac, et.authtime, client, tkt->key,
+ tkt->kdc_key);
+ if (ret)
+ t_err(context, tkt->name, "krb5_pac_verify ticket-sig 2", ret);
+
+ ret = krb5_pac_get_kdc_checksum_info(context, pac, &cstype, &rodc_id);
+ if (ret)
+ t_err(context, tkt->name, "krb5_pac_get_kdc_checksum_info 2", ret);
+
+ heim_assert(cstype == CKSUMTYPE_HMAC_MD5, "Wrong checksum type 2");
+ heim_assert(rodc_id == tkt->rodc_id, "Wrong RODCIdentifier 2");
+
+ krb5_pac_free(context, pac);
+ krb5_free_principal(context, client);
+ krb5_crypto_destroy(context, crypto);
+ free_EncTicketPart(&et);
+ krb5_data_free(&data);
+ free_Ticket(&ticket);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ krb5_error_code ret;
+ krb5_context context;
+ krb5_pac pac;
+ krb5_data data;
+ krb5_principal p, p2;
+ unsigned char bad_pac[sizeof(saved_pac)];
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_init_context");
+
+ krb5_enctype_enable(context, ETYPE_DES_CBC_MD5);
+
+ ret = krb5_parse_name_flags(context, user,
+ KRB5_PRINCIPAL_PARSE_NO_REALM, &p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ /* Attempt to parse a truncated PAC */
+ ret = krb5_pac_parse(context, saved_pac, sizeof(saved_pac) >> 1, &pac);
+ if (ret == 0)
+ krb5_err(context, 1, ret, "krb5_pac_parse parsed a short PAC");
+
+ /* Attempt to parse a PAC with a buffer claiming too large a length */
+ memcpy(bad_pac, saved_pac, sizeof(saved_pac));
+ bad_pac[13] += 1;
+
+ ret = krb5_pac_parse(context, bad_pac, sizeof(saved_pac), &pac);
+ if (ret == 0)
+ krb5_err(context, 1, ret, "krb5_pac_parse parsed a malicious PAC");
+
+ /* Attempt to parse a PAC with a buffer offset too far in */
+ memcpy(bad_pac, saved_pac, sizeof(saved_pac));
+ bad_pac[16] += 1;
+
+ ret = krb5_pac_parse(context, bad_pac, sizeof(saved_pac), &pac);
+ if (ret == 0)
+ krb5_err(context, 1, ret, "krb5_pac_parse parsed a malicious PAC");
+
+ /* Attempt to parse a PAC with a buffer offset too far back */
+ memcpy(bad_pac, saved_pac, sizeof(saved_pac));
+ bad_pac[16] -= 1;
+
+ ret = krb5_pac_parse(context, bad_pac, sizeof(saved_pac), &pac);
+ if (ret == 0)
+ krb5_err(context, 1, ret, "krb5_pac_parse parsed a malicious PAC");
+
+ /* Attempt to parse a PAC with an incorrect buffer count */
+ memcpy(bad_pac, saved_pac, sizeof(saved_pac));
+ bad_pac[0] += 1;
+
+ ret = krb5_pac_parse(context, bad_pac, sizeof(saved_pac), &pac);
+ if (ret == 0)
+ krb5_err(context, 1, ret, "krb5_pac_parse parsed a malicious PAC");
+
+ /* Parse a well-formed PAC */
+ ret = krb5_pac_parse(context, saved_pac, sizeof(saved_pac), &pac);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_parse");
+
+ ret = krb5_pac_verify(context, pac, authtime, p,
+ &member_keyblock, &kdc_keyblock);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_verify");
+
+ ret = _krb5_pac_sign(context, pac, authtime, p,
+ &member_keyblock, &kdc_keyblock, 0, NULL, NULL,
+ NULL, &data);
+ if (ret)
+ krb5_err(context, 1, ret, "_krb5_pac_sign");
+
+ krb5_pac_free(context, pac);
+
+ ret = krb5_pac_parse(context, data.data, data.length, &pac);
+ krb5_data_free(&data);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_parse 2");
+
+ ret = krb5_pac_verify(context, pac, authtime, p,
+ &member_keyblock, &kdc_keyblock);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_verify 2");
+
+ /* make a copy and try to reproduce it */
+ {
+ uint32_t *list;
+ size_t len, i;
+ krb5_pac pac2;
+
+ ret = krb5_pac_init(context, &pac2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_init");
+
+ /* our two user buffer plus the three "system" buffers */
+ ret = krb5_pac_get_types(context, pac, &len, &list);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_get_types");
+
+ for (i = 0; i < len; i++) {
+ /* skip server_cksum, privsvr_cksum, and logon_name */
+ if (list[i] == 6 || list[i] == 7 || list[i] == 10)
+ continue;
+
+ ret = krb5_pac_get_buffer(context, pac, list[i], &data);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_get_buffer");
+
+ if (list[i] == 1) {
+ if (type_1_length != data.length)
+ krb5_errx(context, 1, "type 1 have wrong length: %lu",
+ (unsigned long)data.length);
+ } else
+ krb5_errx(context, 1, "unknown type %lu",
+ (unsigned long)list[i]);
+
+ ret = krb5_pac_add_buffer(context, pac2, list[i], &data);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_add_buffer");
+ krb5_data_free(&data);
+ }
+ free(list);
+
+ ret = _krb5_pac_sign(context, pac2, authtime, p,
+ &member_keyblock, &kdc_keyblock, 0,
+ NULL, NULL, NULL, &data);
+ if (ret)
+ krb5_err(context, 1, ret, "_krb5_pac_sign 4");
+
+ krb5_pac_free(context, pac2);
+
+ ret = krb5_pac_parse(context, data.data, data.length, &pac2);
+ krb5_data_free(&data);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_parse 4");
+
+ ret = krb5_pac_verify(context, pac2, authtime, p,
+ &member_keyblock, &kdc_keyblock);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_verify 4");
+
+ krb5_pac_free(context, pac2);
+ }
+
+ krb5_pac_free(context, pac);
+
+ /*
+ * check pac from Christian
+ */
+
+ ret = krb5_parse_name_flags(context, user2,
+ KRB5_PRINCIPAL_PARSE_NO_REALM, &p2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_pac_parse(context, saved_pac2, sizeof(saved_pac2) -1, &pac);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_parse");
+
+ ret = krb5_pac_verify(context, pac, authtime2, p2,
+ &member_keyblock2, NULL);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_verify c1");
+
+ krb5_pac_free(context, pac);
+ krb5_free_principal(context, p2);
+
+ /*
+ * Test empty free
+ */
+
+ ret = krb5_pac_init(context, &pac);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_init");
+ krb5_pac_free(context, pac);
+
+ /*
+ * Test add remove buffer
+ */
+
+ ret = krb5_pac_init(context, &pac);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_init");
+
+ {
+ const krb5_data cdata = { 2, "\x00\x01" } ;
+
+ ret = krb5_pac_add_buffer(context, pac, 1, &cdata);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_add_buffer");
+ }
+ {
+ ret = krb5_pac_get_buffer(context, pac, 1, &data);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_get_buffer");
+ if (data.length != 2 || memcmp(data.data, "\x00\x01", 2) != 0)
+ krb5_errx(context, 1, "krb5_pac_get_buffer data not the same");
+ krb5_data_free(&data);
+ }
+
+ {
+ const krb5_data cdata = { 2, "\x02\x00" } ;
+
+ ret = krb5_pac_add_buffer(context, pac, 2, &cdata);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_add_buffer");
+ }
+ {
+ ret = krb5_pac_get_buffer(context, pac, 1, &data);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_get_buffer");
+ if (data.length != 2 || memcmp(data.data, "\x00\x01", 2) != 0)
+ krb5_errx(context, 1, "krb5_pac_get_buffer data not the same");
+ krb5_data_free(&data);
+ /* */
+ ret = krb5_pac_get_buffer(context, pac, 2, &data);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_get_buffer");
+ if (data.length != 2 || memcmp(data.data, "\x02\x00", 2) != 0)
+ krb5_errx(context, 1, "krb5_pac_get_buffer data not the same");
+ krb5_data_free(&data);
+ }
+
+ ret = _krb5_pac_sign(context, pac, authtime, p,
+ &member_keyblock, &kdc_keyblock, 0,
+ NULL, NULL, NULL, &data);
+ if (ret)
+ krb5_err(context, 1, ret, "_krb5_pac_sign");
+
+ krb5_pac_free(context, pac);
+
+ ret = krb5_pac_parse(context, data.data, data.length, &pac);
+ krb5_data_free(&data);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_parse 3");
+
+ ret = krb5_pac_verify(context, pac, authtime, p,
+ &member_keyblock, &kdc_keyblock);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_verify 3");
+
+ {
+ uint32_t *list;
+ size_t len;
+
+ /* our two user buffer plus the three "system" buffers */
+ ret = krb5_pac_get_types(context, pac, &len, &list);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_get_types");
+ if (len != 5)
+ krb5_errx(context, 1, "list wrong length");
+ free(list);
+ }
+
+ krb5_pac_free(context, pac);
+ krb5_free_principal(context, p);
+
+ /*
+ * check extra logon info PAC
+ */
+ ret = krb5_pac_parse(context, extra_logon_info,
+ sizeof(extra_logon_info) - 1, &pac);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_parse");
+
+ ret = krb5_pac_verify(context, pac, 0, NULL, NULL, NULL);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_pac_verify");
+
+ ret = krb5_parse_name(context, "c9d801a8_0@EXAMPLE.COM", &p);
+ if (ret)
+ krb5_err(context, 1, ret, "_krb5_pac_get_canon_principal");
+
+ ret = _krb5_pac_get_canon_principal(context, pac, &p2);
+ if (ret)
+ krb5_err(context, 1, ret, "_krb5_pac_get_canon_principal");
+
+ if (!krb5_principal_compare(context, p, p2))
+ krb5_errx(context, 1, "canon principal doesn't match");
+
+ krb5_pac_free(context, pac);
+ krb5_free_principal(context, p);
+ krb5_free_principal(context, p2);
+
+ /* Test PAC ticket-signature */
+ {
+ const struct test_pac_ticket *tkt;
+
+ for (tkt = pac_tickets; tkt->name != NULL; tkt++)
+ check_ticket_signature(context, tkt);
+ }
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_pkinit_dh2key.c b/third_party/heimdal/lib/krb5/test_pkinit_dh2key.c
new file mode 100644
index 0000000..e18fd17
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_pkinit_dh2key.c
@@ -0,0 +1,216 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+static void
+test_dh2key(int i,
+ krb5_context context,
+ const heim_octet_string *dh,
+ const heim_octet_string *c_n,
+ const heim_octet_string *k_n,
+ krb5_enctype etype,
+ const heim_octet_string *result)
+{
+ krb5_error_code ret;
+ krb5_keyblock key;
+
+ ret = _krb5_pk_octetstring2key(context,
+ etype,
+ dh->data, dh->length,
+ c_n,
+ k_n,
+ &key);
+ if (ret != 0)
+ krb5_err(context, 1, ret, "_krb5_pk_octetstring2key: %d", i);
+
+ if (key.keyvalue.length != result->length ||
+ memcmp(key.keyvalue.data, result->data, result->length) != 0)
+ krb5_errx(context, 1, "resulting key wrong: %d", i);
+
+ krb5_free_keyblock_contents(context, &key);
+}
+
+
+struct {
+ krb5_enctype type;
+ krb5_data X;
+ krb5_data key;
+} tests[] = {
+ /* 0 */
+ {
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ {
+ 256,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ },
+ {
+ 32,
+ "\x5e\xe5\x0d\x67\x5c\x80\x9f\xe5\x9e\x4a\x77\x62\xc5\x4b\x65\x83"
+ "\x75\x47\xea\xfb\x15\x9b\xd8\xcd\xc7\x5f\xfc\xa5\x91\x1e\x4c\x41"
+ }
+ },
+ /* 1 */
+ {
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ {
+ 128,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ },
+ {
+ 32,
+ "\xac\xf7\x70\x7c\x08\x97\x3d\xdf\xdb\x27\xcd\x36\x14\x42\xcc\xfb"
+ "\xa3\x55\xc8\x88\x4c\xb4\x72\xf3\x7d\xa6\x36\xd0\x7d\x56\x78\x7e"
+ }
+ },
+ /* 2 */
+ {
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ {
+ 128,
+ "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
+ "\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e"
+ "\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d"
+ "\x0e\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c"
+ "\x0d\x0e\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b"
+ "\x0c\x0d\x0e\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a"
+ "\x0b\x0c\x0d\x0e\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09"
+ "\x0a\x0b\x0c\x0d\x0e\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08"
+ },
+ {
+ 32,
+ "\xc4\x42\xda\x58\x5f\xcb\x80\xe4\x3b\x47\x94\x6f\x25\x40\x93\xe3"
+ "\x73\x29\xd9\x90\x01\x38\x0d\xb7\x83\x71\xdb\x3a\xcf\x5c\x79\x7e"
+ }
+ },
+ /* 3 */
+ {
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ {
+ 77,
+ "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
+ "\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e"
+ "\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d"
+ "\x0e\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c"
+ "\x0d\x0e\x0f\x10\x00\x01\x02\x03"
+ "\x04\x05\x06\x07\x08"
+ },
+ {
+ 32,
+ "\x00\x53\x95\x3b\x84\xc8\x96\xf4\xeb\x38\x5c\x3f\x2e\x75\x1c\x4a"
+ "\x59\x0e\xd6\xff\xad\xca\x6f\xf6\x4f\x47\xeb\xeb\x8d\x78\x0f\xfc"
+ }
+ }
+};
+
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "");
+ exit (ret);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ int i, optidx = 0;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
+ test_dh2key(i, context, &tests[i].X, NULL, NULL,
+ tests[i].type, &tests[i].key);
+ }
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_pknistkdf.c b/third_party/heimdal/lib/krb5/test_pknistkdf.c
new file mode 100644
index 0000000..f97dddf
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_pknistkdf.c
@@ -0,0 +1,373 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <pkinit_asn1.h>
+#include <err.h>
+#include <getarg.h>
+#include <hex.h>
+
+static int verbose_flag = 0;
+
+struct testcase {
+ const heim_oid *oid;
+ krb5_data Z;
+ const char *client;
+ const char *server;
+ krb5_enctype enctype;
+ krb5_data as_req;
+ krb5_data pk_as_rep;
+ krb5_data ticket;
+
+ krb5_data key;
+} tests[] = {
+ /* 0 */
+ {
+ NULL, /* AlgorithmIdentifier */
+ { /* Z */
+ 256,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ },
+ "lha@SU.SE", /* client, partyUInfo */
+ "krbtgt/SU.SE@SU.SE", /* server, partyVInfo */
+ ETYPE_AES256_CTS_HMAC_SHA1_96, /* enctype */
+ { /* as_req */
+ 10,
+ "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA"
+ },
+ { /* pk_as_rep */
+ 9,
+ "\xBB\xBB\xBB\xBB\xBB\xBB\xBB\xBB\xBB"
+ },
+ { /* ticket */
+ 55,
+ "\x61\x35\x30\x33\xa0\x03\x02\x01\x05\xa1\x07\x1b\x05\x53\x55\x2e"
+ "\x53\x45\xa2\x10\x30\x0e\xa0\x03\x02\x01\x01\xa1\x07\x30\x05\x1b"
+ "\x03\x6c\x68\x61\xa3\x11\x30\x0f\xa0\x03\x02\x01\x12\xa2\x08\x04"
+ "\x06\x68\x65\x6a\x68\x65\x6a"
+ },
+ { /* key */
+ 32,
+ "\xc7\x62\x89\xec\x4b\x28\xa6\x91\xff\xce\x80\xbb\xb7\xec\x82\x41"
+ "\x52\x3f\x99\xb1\x90\xcf\x2d\x34\x8f\x54\xa8\x65\x81\x2c\x32\x73"
+ }
+ },
+ /* 1 */
+ {
+ NULL, /* AlgorithmIdentifier */
+ { /* Z */
+ 256,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ },
+ "lha@SU.SE", /* client, partyUInfo */
+ "krbtgt/SU.SE@SU.SE", /* server, partyVInfo */
+ ETYPE_AES256_CTS_HMAC_SHA1_96, /* enctype */
+ { /* as_req */
+ 10,
+ "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA"
+ },
+ { /* pk_as_rep */
+ 9,
+ "\xBB\xBB\xBB\xBB\xBB\xBB\xBB\xBB\xBB"
+ },
+ { /* ticket */
+ 55,
+ "\x61\x35\x30\x33\xa0\x03\x02\x01\x05\xa1\x07\x1b\x05\x53\x55\x2e"
+ "\x53\x45\xa2\x10\x30\x0e\xa0\x03\x02\x01\x01\xa1\x07\x30\x05\x1b"
+ "\x03\x6c\x68\x61\xa3\x11\x30\x0f\xa0\x03\x02\x01\x12\xa2\x08\x04"
+ "\x06\x68\x65\x6a\x68\x65\x6a"
+ },
+ { /* key */
+ 32,
+ "\x59\xf3\xca\x77\x5b\x20\x17\xe9\xad\x36\x3f\x47\xca\xbd\x43\xb8"
+ "\x8c\xb8\x90\x35\x8d\xc6\x0d\x52\x0d\x11\x9f\xb0\xdc\x24\x0b\x61"
+ }
+ },
+ /* 2 */
+ {
+ NULL, /* AlgorithmIdentifier */
+ { /* Z */
+ 256,
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ },
+ "lha@SU.SE", /* client, partyUInfo */
+ "krbtgt/SU.SE@SU.SE", /* server, partyVInfo */
+ ETYPE_AES256_CTS_HMAC_SHA1_96, /* enctype */
+ { /* as_req */
+ 10,
+ "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA"
+ },
+ { /* pk_as_rep */
+ 9,
+ "\xBB\xBB\xBB\xBB\xBB\xBB\xBB\xBB\xBB"
+ },
+ { /* ticket */
+ 55,
+ "\x61\x35\x30\x33\xa0\x03\x02\x01\x05\xa1\x07\x1b\x05\x53\x55\x2e"
+ "\x53\x45\xa2\x10\x30\x0e\xa0\x03\x02\x01\x01\xa1\x07\x30\x05\x1b"
+ "\x03\x6c\x68\x61\xa3\x11\x30\x0f\xa0\x03\x02\x01\x12\xa2\x08\x04"
+ "\x06\x68\x65\x6a\x68\x65\x6a"
+ },
+ { /* key */
+ 32,
+ "\x8a\x9a\xc5\x5f\x45\xda\x1a\x73\xd9\x1e\xe9\x88\x1f\xa9\x48\x81"
+ "\xce\xac\x66\x2d\xb1\xd3\xb9\x0a\x9d\x0e\x52\x83\xdf\xe1\x84\x3d"
+ }
+ }
+};
+
+#ifdef MAKETICKET
+static void
+fooTicket(void)
+{
+ krb5_error_code ret;
+ krb5_data data;
+ size_t size;
+ Ticket t;
+
+ t.tkt_vno = 5;
+ t.realm = "SU.SE";
+ t.sname.name_type = KRB5_NT_PRINCIPAL;
+ t.sname.name_string.len = 1;
+ t.sname.name_string.val = ecalloc(1, sizeof(t.sname.name_string.val[0]));
+ t.sname.name_string.val[0] = estrdup("lha");
+ t.enc_part.etype = ETYPE_AES256_CTS_HMAC_SHA1_96;
+ t.enc_part.kvno = NULL;
+ t.enc_part.cipher.length = 6;
+ t.enc_part.cipher.data = "hejhej";
+
+ ASN1_MALLOC_ENCODE(Ticket, data.data, data.length, &t, &size, ret);
+ if (ret)
+ errx(1, "ASN1_MALLOC_ENCODE(Ticket)");
+
+ rk_dumpdata("foo", data.data, data.length);
+ free(data.data);
+}
+#endif
+
+static void
+test_dh2key(krb5_context context, int i, struct testcase *c)
+{
+ krb5_error_code ret;
+ krb5_keyblock key;
+ krb5_principal client, server;
+ Ticket ticket;
+ AlgorithmIdentifier ai;
+ size_t size;
+
+ memset(&ticket, 0, sizeof(ticket));
+
+ ai.algorithm = *c->oid;
+ ai.parameters = NULL;
+
+ ret = decode_Ticket(c->ticket.data, c->ticket.length, &ticket, &size);
+ if (ret)
+ krb5_errx(context, 1, "decode ticket: %d", ret);
+
+ ret = krb5_parse_name(context, c->client, &client);
+ if (ret)
+ krb5_err(context, 1, ret, "parse_name: %s", c->client);
+ ret = krb5_parse_name(context, c->server, &server);
+ if (ret)
+ krb5_err(context, 1, ret, "parse_name: %s", c->server);
+ /*
+ * Making krb5_build_principal*() set a reasonable default principal
+ * name type broke the test vectors here. Rather than regenerate
+ * the vectors, and to prove that this was the issue, we coerce the
+ * name types back to their original.
+ */
+ krb5_principal_set_type(context, client, KRB5_NT_PRINCIPAL);
+ krb5_principal_set_type(context, server, KRB5_NT_PRINCIPAL);
+
+ if (verbose_flag) {
+ char *str;
+ hex_encode(c->Z.data, c->Z.length, &str);
+ printf("Z: %s\n", str);
+ free(str);
+ printf("client: %s\n", c->client);
+ printf("server: %s\n", c->server);
+ printf("enctype: %d\n", (int)c->enctype);
+ hex_encode(c->as_req.data, c->as_req.length, &str);
+ printf("as-req: %s\n", str);
+ free(str);
+ hex_encode(c->pk_as_rep.data, c->pk_as_rep.length, &str);
+ printf("pk-as-rep: %s\n", str);
+ free(str);
+ hex_encode(c->ticket.data, c->ticket.length, &str);
+ printf("ticket: %s\n", str);
+ free(str);
+ }
+
+ ret = _krb5_pk_kdf(context,
+ &ai,
+ c->Z.data,
+ c->Z.length,
+ client,
+ server,
+ c->enctype,
+ &c->as_req,
+ &c->pk_as_rep,
+ &ticket,
+ &key);
+ krb5_free_principal(context, client);
+ krb5_free_principal(context, server);
+ if (ret)
+ krb5_err(context, 1, ret, "_krb5_pk_kdf: %d", i);
+
+ if (verbose_flag) {
+ char *str;
+ hex_encode(key.keyvalue.data, key.keyvalue.length, &str);
+ printf("key: %s\n", str);
+ free(str);
+ }
+
+ if (key.keyvalue.length != c->key.length ||
+ memcmp(key.keyvalue.data, c->key.data, c->key.length) != 0)
+ krb5_errx(context, 1, "resulting key wrong: %d", i);
+
+ krb5_free_keyblock_contents(context, &key);
+ free_Ticket(&ticket);
+}
+
+
+
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"verbose", 0, arg_flag, &verbose_flag,
+ "verbose output", NULL },
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "");
+ exit (ret);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ int i, optidx = 0;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+#ifdef MAKETICKET
+ fooTicket();
+#endif
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ tests[0].oid = &asn1_oid_id_pkinit_kdf_ah_sha1;
+ tests[1].oid = &asn1_oid_id_pkinit_kdf_ah_sha256;
+ tests[2].oid = &asn1_oid_id_pkinit_kdf_ah_sha512;
+
+ for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
+ test_dh2key(context, i, &tests[i]);
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_plugin.c b/third_party/heimdal/lib/krb5/test_plugin.c
new file mode 100644
index 0000000..6aedfa2
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_plugin.c
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <krb5_locl.h>
+#include "locate_plugin.h"
+
+static krb5_error_code KRB5_CALLCONV
+resolve_init(krb5_context context, void **ctx)
+{
+ *ctx = NULL;
+ return 0;
+}
+
+static void KRB5_CALLCONV
+resolve_fini(void *ctx)
+{
+}
+
+static krb5_error_code KRB5_CALLCONV
+resolve_lookup(void *ctx,
+ enum locate_service_type service,
+ const char *realm,
+ int domain,
+ int type,
+ int (*add)(void *,int,struct sockaddr *),
+ void *addctx)
+{
+ struct sockaddr_in s;
+
+ memset(&s, 0, sizeof(s));
+
+#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
+ s.sin_len = sizeof(s);
+#endif
+ s.sin_family = AF_INET;
+ s.sin_port = htons(88);
+ s.sin_addr.s_addr = htonl(0x7f000002);
+
+ if (strcmp(realm, "NOTHERE.H5L.SE") == 0) {
+ (*add)(addctx, type, (struct sockaddr *)&s);
+ return 0;
+ }
+
+ return KRB5_PLUGIN_NO_HANDLE;
+}
+
+
+krb5plugin_service_locate_ftable resolve = {
+ 0,
+ resolve_init,
+ resolve_fini,
+ resolve_lookup,
+ NULL
+};
+
+
+int
+main(int argc, char **argv)
+{
+ krb5_error_code ret;
+ krb5_context context;
+ krb5_krbhst_handle handle;
+ char host[MAXHOSTNAMELEN];
+ int found = 0;
+
+ setprogname(argv[0]);
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_init_contex");
+
+ ret = krb5_plugin_register(context, PLUGIN_TYPE_DATA,
+ KRB5_PLUGIN_LOCATE, &resolve);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_plugin_register");
+
+
+ ret = krb5_krbhst_init_flags(context,
+ "NOTHERE.H5L.SE",
+ KRB5_KRBHST_KDC,
+ 0,
+ &handle);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_krbhst_init_flags");
+
+
+ while(krb5_krbhst_next_as_string(context, handle, host, sizeof(host)) == 0){
+ found++;
+ if (!found && strcmp(host, "127.0.0.2") != 0 && strcmp(host, "tcp/127.0.0.2") != 0)
+ krb5_errx(context, 1, "wrong address: %s", host);
+ }
+ if (!found)
+ krb5_errx(context, 1, "failed to find host");
+ if (found < 2)
+ krb5_errx(context, 1, "did not get the two expected results");
+
+ krb5_krbhst_free(context, handle);
+
+ krb5_free_context(context);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_prf.c b/third_party/heimdal/lib/krb5/test_prf.c
new file mode 100644
index 0000000..26ba2a6
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_prf.c
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+#include <hex.h>
+#include <err.h>
+
+/*
+ * key: string2key(aes256, "testkey", "testkey", default_params)
+ * input: unhex(1122334455667788)
+ * output: 58b594b8a61df6e9439b7baa991ff5c1
+ *
+ * key: string2key(aes128, "testkey", "testkey", default_params)
+ * input: unhex(1122334455667788)
+ * output: ffa2f823aa7f83a8ce3c5fb730587129
+ */
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ krb5_keyblock key;
+ krb5_crypto crypto;
+ size_t length;
+ krb5_data input, output, output2;
+ krb5_enctype etype = ETYPE_AES256_CTS_HMAC_SHA1_96;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_init_context %d", ret);
+
+ ret = krb5_generate_random_keyblock(context, etype, &key);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_generate_random_keyblock");
+
+ ret = krb5_crypto_prf_length(context, etype, &length);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_prf_length");
+
+ ret = krb5_crypto_init(context, &key, 0, &crypto);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_init");
+
+ input.data = rk_UNCONST("foo");
+ input.length = 3;
+
+ ret = krb5_crypto_prf(context, crypto, &input, &output);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_prf");
+
+ ret = krb5_crypto_prf(context, crypto, &input, &output2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_prf");
+
+ if (krb5_data_cmp(&output, &output2) != 0)
+ krb5_errx(context, 1, "krb5_data_cmp");
+
+ krb5_data_free(&output);
+ krb5_data_free(&output2);
+
+ krb5_crypto_destroy(context, crypto);
+
+ krb5_free_keyblock_contents(context, &key);
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_princ.c b/third_party/heimdal/lib/krb5/test_princ.c
new file mode 100644
index 0000000..e61a603
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_princ.c
@@ -0,0 +1,365 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+
+/*
+ * Check that a closed cc still keeps it data and that it's no longer
+ * there when it's destroyed.
+ */
+
+static void
+test_princ(krb5_context context)
+{
+ const char *princ = "lha@SU.SE";
+ const char *princ_short = "lha";
+ const char *noquote;
+ krb5_error_code ret;
+ char *princ_unparsed;
+ char *princ_reformed = NULL;
+ const char *realm;
+
+ krb5_principal p, p2;
+
+ ret = krb5_parse_name(context, princ, &p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_unparse_name(context, p, &princ_unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ if (strcmp(princ, princ_unparsed) != 0) {
+ krb5_errx(context, 1, "%s != %s", princ, princ_unparsed);
+ }
+
+ free(princ_unparsed);
+
+ ret = krb5_unparse_name_flags(context, p,
+ KRB5_PRINCIPAL_UNPARSE_NO_REALM,
+ &princ_unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ if (strcmp(princ_short, princ_unparsed) != 0)
+ krb5_errx(context, 1, "%s != %s", princ_short, princ_unparsed);
+ free(princ_unparsed);
+
+ realm = krb5_principal_get_realm(context, p);
+
+ if (asprintf(&princ_reformed, "%s@%s", princ_short, realm) < 0 || princ_reformed == NULL)
+ errx(1, "malloc");
+
+ ret = krb5_parse_name(context, princ_reformed, &p2);
+ free(princ_reformed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ if (!krb5_principal_compare(context, p, p2)) {
+ krb5_errx(context, 1, "p != p2");
+ }
+
+ krb5_free_principal(context, p2);
+
+ ret = krb5_set_default_realm(context, "SU.SE");
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_unparse_name_flags(context, p,
+ KRB5_PRINCIPAL_UNPARSE_SHORT,
+ &princ_unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ if (strcmp(princ_short, princ_unparsed) != 0)
+ krb5_errx(context, 1, "'%s' != '%s'", princ_short, princ_unparsed);
+ free(princ_unparsed);
+
+ ret = krb5_parse_name(context, princ_short, &p2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ if (!krb5_principal_compare(context, p, p2))
+ krb5_errx(context, 1, "p != p2");
+ krb5_free_principal(context, p2);
+
+ ret = krb5_unparse_name(context, p, &princ_unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ if (strcmp(princ, princ_unparsed) != 0)
+ krb5_errx(context, 1, "'%s' != '%s'", princ, princ_unparsed);
+ free(princ_unparsed);
+
+ ret = krb5_set_default_realm(context, "SAMBA.ORG");
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_parse_name(context, princ_short, &p2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ if (krb5_principal_compare(context, p, p2))
+ krb5_errx(context, 1, "p == p2");
+
+ if (!krb5_principal_compare_any_realm(context, p, p2))
+ krb5_errx(context, 1, "(ignoring realms) p != p2");
+
+ ret = krb5_unparse_name(context, p2, &princ_unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ if (strcmp(princ, princ_unparsed) == 0)
+ krb5_errx(context, 1, "%s == %s", princ, princ_unparsed);
+ free(princ_unparsed);
+
+ krb5_free_principal(context, p2);
+
+ ret = krb5_parse_name(context, princ, &p2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ if (!krb5_principal_compare(context, p, p2))
+ krb5_errx(context, 1, "p != p2");
+
+ ret = krb5_unparse_name(context, p2, &princ_unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ if (strcmp(princ, princ_unparsed) != 0)
+ krb5_errx(context, 1, "'%s' != '%s'", princ, princ_unparsed);
+ free(princ_unparsed);
+
+ krb5_free_principal(context, p2);
+
+ ret = krb5_unparse_name_flags(context, p,
+ KRB5_PRINCIPAL_UNPARSE_SHORT,
+ &princ_unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_unparse_name_short");
+
+ if (strcmp(princ, princ_unparsed) != 0)
+ krb5_errx(context, 1, "'%s' != '%s'", princ, princ_unparsed);
+ free(princ_unparsed);
+
+ ret = krb5_unparse_name(context, p, &princ_unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_unparse_name_short");
+
+ if (strcmp(princ, princ_unparsed) != 0)
+ krb5_errx(context, 1, "'%s' != '%s'", princ, princ_unparsed);
+ free(princ_unparsed);
+
+ ret = krb5_parse_name_flags(context, princ,
+ KRB5_PRINCIPAL_PARSE_NO_REALM,
+ &p2);
+ if (!ret)
+ krb5_err(context, 1, ret, "Should have failed to parse %s a "
+ "short name", princ);
+
+ ret = krb5_parse_name_flags(context, princ_short,
+ KRB5_PRINCIPAL_PARSE_NO_REALM,
+ &p2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_unparse_name_flags(context, p2,
+ KRB5_PRINCIPAL_UNPARSE_NO_REALM,
+ &princ_unparsed);
+ krb5_free_principal(context, p2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_unparse_name_norealm");
+
+ if (strcmp(princ_short, princ_unparsed) != 0)
+ krb5_errx(context, 1, "'%s' != '%s'", princ_short, princ_unparsed);
+ free(princ_unparsed);
+
+ ret = krb5_parse_name_flags(context, princ_short,
+ KRB5_PRINCIPAL_PARSE_REQUIRE_REALM,
+ &p2);
+ if (!ret)
+ krb5_err(context, 1, ret, "Should have failed to parse %s "
+ "because it lacked a realm", princ_short);
+
+ ret = krb5_parse_name_flags(context, princ,
+ KRB5_PRINCIPAL_PARSE_REQUIRE_REALM,
+ &p2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ if (!krb5_principal_compare(context, p, p2))
+ krb5_errx(context, 1, "p != p2");
+
+ ret = krb5_unparse_name_flags(context, p2,
+ KRB5_PRINCIPAL_UNPARSE_NO_REALM,
+ &princ_unparsed);
+ krb5_free_principal(context, p2);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_unparse_name_norealm");
+
+ if (strcmp(princ_short, princ_unparsed) != 0)
+ krb5_errx(context, 1, "'%s' != '%s'", princ_short, princ_unparsed);
+ free(princ_unparsed);
+
+ krb5_free_principal(context, p);
+
+ /* test quoting */
+
+ princ = "test\\ principal@SU.SE";
+ noquote = "test principal@SU.SE";
+
+ ret = krb5_parse_name_flags(context, princ, 0, &p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_unparse_name_flags(context, p, 0, &princ_unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_unparse_name_flags");
+
+ if (strcmp(princ, princ_unparsed) != 0)
+ krb5_errx(context, 1, "q '%s' != '%s'", princ, princ_unparsed);
+ free(princ_unparsed);
+
+ ret = krb5_unparse_name_flags(context, p, KRB5_PRINCIPAL_UNPARSE_DISPLAY,
+ &princ_unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_unparse_name_flags");
+
+ if (strcmp(noquote, princ_unparsed) != 0)
+ krb5_errx(context, 1, "nq '%s' != '%s'", noquote, princ_unparsed);
+ free(princ_unparsed);
+
+ krb5_free_principal(context, p);
+}
+
+static void
+test_enterprise(krb5_context context)
+{
+ krb5_error_code ret;
+ char *unparsed;
+ krb5_principal p;
+
+ ret = krb5_set_default_realm(context, "SAMBA.ORG");
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name");
+
+ ret = krb5_parse_name_flags(context, "lha@su.se@WIN.SU.SE",
+ KRB5_PRINCIPAL_PARSE_ENTERPRISE, &p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name_flags");
+
+ ret = krb5_unparse_name(context, p, &unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_unparse_name");
+
+ krb5_free_principal(context, p);
+
+ if (strcmp(unparsed, "lha\\@su.se@WIN.SU.SE") != 0)
+ krb5_errx(context, 1, "enterprise name failed 1");
+ free(unparsed);
+
+ /*
+ *
+ */
+
+ ret = krb5_parse_name_flags(context, "lha\\@su.se@WIN.SU.SE",
+ KRB5_PRINCIPAL_PARSE_ENTERPRISE, &p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name_flags");
+
+ ret = krb5_unparse_name(context, p, &unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_unparse_name");
+
+ krb5_free_principal(context, p);
+ if (strcmp(unparsed, "lha\\@su.se\\@WIN.SU.SE@SAMBA.ORG") != 0)
+ krb5_errx(context, 1, "enterprise name failed 2: %s", unparsed);
+ free(unparsed);
+
+ /*
+ *
+ */
+
+ ret = krb5_parse_name_flags(context, "lha\\@su.se@WIN.SU.SE", 0, &p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name_flags");
+
+ ret = krb5_unparse_name(context, p, &unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_unparse_name");
+
+ krb5_free_principal(context, p);
+ if (strcmp(unparsed, "lha\\@su.se@WIN.SU.SE") != 0)
+ krb5_errx(context, 1, "enterprise name failed 3");
+ free(unparsed);
+
+ /*
+ *
+ */
+
+ ret = krb5_parse_name_flags(context, "lha@su.se",
+ KRB5_PRINCIPAL_PARSE_ENTERPRISE, &p);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_parse_name_flags");
+
+ ret = krb5_unparse_name(context, p, &unparsed);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_unparse_name");
+
+ krb5_free_principal(context, p);
+ if (strcmp(unparsed, "lha\\@su.se@SAMBA.ORG") != 0)
+ krb5_errx(context, 1, "enterprise name failed 2: %s", unparsed);
+ free(unparsed);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+
+ setprogname(argv[0]);
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ test_princ(context);
+
+ test_enterprise(context);
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_renew.c b/third_party/heimdal/lib/krb5/test_renew.c
new file mode 100644
index 0000000..40d3739
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_renew.c
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "[principal]");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_principal client;
+ krb5_context context;
+ const char *in_tkt_service = NULL;
+ krb5_ccache id;
+ krb5_error_code ret;
+ krb5_creds out;
+ int optidx = 0;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (argc > 0)
+ in_tkt_service = argv[0];
+
+ memset(&out, 0, sizeof(out));
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_init_context");
+
+ ret = krb5_cc_default(context, &id);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_default");
+
+ ret = krb5_cc_get_principal(context, id, &client);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_cc_default");
+
+ ret = krb5_get_renewed_creds(context,
+ &out,
+ client,
+ id,
+ in_tkt_service);
+
+ if(ret)
+ krb5_err(context, 1, ret, "krb5_get_renewed_creds");
+
+ if (krb5_principal_compare(context, out.client, client) != TRUE)
+ krb5_errx(context, 1, "return principal is not as expected");
+
+ krb5_free_cred_contents(context, &out);
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_rfc3961.c b/third_party/heimdal/lib/krb5/test_rfc3961.c
new file mode 100644
index 0000000..ed8ee9b
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_rfc3961.c
@@ -0,0 +1,522 @@
+/*
+ * Copyright (c) 2003-2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+static void
+time_hmac(krb5_context context, size_t size, int iterations)
+{
+ struct timeval tv1, tv2;
+ krb5_error_code ret;
+ krb5_keyblock key;
+ char sha1_data[20];
+ Checksum result;
+ char *buf;
+ int i;
+
+ ret = krb5_generate_random_keyblock(context,
+ ETYPE_AES128_CTS_HMAC_SHA1_96,
+ &key);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_generate_random_keyblock");
+
+ buf = calloc(1, size);
+ if (buf == NULL)
+ krb5_errx(context, 1, "out of memory");
+
+ gettimeofday(&tv1, NULL);
+
+ result.checksum.data = &sha1_data;
+ result.checksum.length = sizeof(sha1_data);
+ for (i = 0; i < iterations; i++) {
+ ret = krb5_hmac(context, CKSUMTYPE_SHA1, buf, size, 0, &key, &result);
+ if (ret)
+ krb5_err(context, 1, ret, "hmac: %d", i);
+ }
+
+ gettimeofday(&tv2, NULL);
+
+ timevalsub(&tv2, &tv1);
+
+ printf("HMAC-SHA1 size: %7lu iterations: %d time: %3ld.%06ld\n",
+ (unsigned long)size, iterations,
+ (long)tv2.tv_sec, (long)tv2.tv_usec);
+
+ free(buf);
+ krb5_free_keyblock_contents(context, &key);
+}
+
+static void
+time_hmac_evp(krb5_context context, size_t size, int iterations)
+{
+ struct timeval tv1, tv2;
+ struct krb5_crypto_iov iov;
+ struct _krb5_key_data kd;
+ krb5_error_code ret;
+ krb5_keyblock key;
+ krb5_crypto crypto;
+ char sha1_data[20];
+ Checksum result;
+ char *buf;
+ int i;
+
+ ret = krb5_generate_random_keyblock(context,
+ ETYPE_AES128_CTS_HMAC_SHA1_96,
+ &key);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_generate_random_keyblock");
+
+ buf = calloc(1, size);
+ if (buf == NULL)
+ krb5_errx(context, 1, "out of memory");
+
+ gettimeofday(&tv1, NULL);
+
+ result.checksum.data = &sha1_data;
+ result.checksum.length = sizeof(sha1_data);
+ iov.data.data = buf;
+ iov.data.length = size;
+ iov.flags = KRB5_CRYPTO_TYPE_DATA;
+ kd.key = &key;
+ kd.schedule = NULL;
+
+ ret = krb5_crypto_init(context, &key, ETYPE_AES128_CTS_HMAC_SHA1_96,
+ &crypto);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_init");
+
+ for (i = 0; i < iterations; i++) {
+ ret = _krb5_SP_HMAC_SHA1_checksum(context, crypto, &kd, 0,
+ &iov, 1, &result);
+ if (ret)
+ krb5_err(context, 1, ret, "hmac: %d", i);
+ }
+
+ gettimeofday(&tv2, NULL);
+
+ timevalsub(&tv2, &tv1);
+
+ printf("HMAC-SHA1 (evp) size: %7lu iterations: %d time: %3ld.%06ld\n",
+ (unsigned long)size, iterations,
+ (long)tv2.tv_sec, (long)tv2.tv_usec);
+
+ free(buf);
+ krb5_free_keyblock_contents(context, &key);
+ krb5_crypto_destroy(context, crypto);
+}
+
+static void
+time_encryption(krb5_context context, size_t size,
+ krb5_enctype etype, int iterations)
+{
+ struct timeval tv1, tv2;
+ krb5_error_code ret;
+ krb5_keyblock key;
+ krb5_crypto crypto;
+ krb5_data data;
+ char *etype_name;
+ void *buf;
+ int i;
+
+ ret = krb5_generate_random_keyblock(context, etype, &key);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_generate_random_keyblock");
+
+ ret = krb5_enctype_to_string(context, etype, &etype_name);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_enctype_to_string");
+
+ buf = malloc(size);
+ if (buf == NULL)
+ krb5_errx(context, 1, "out of memory");
+ memset(buf, 0, size);
+
+ ret = krb5_crypto_init(context, &key, 0, &crypto);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_crypto_init");
+
+ gettimeofday(&tv1, NULL);
+
+ for (i = 0; i < iterations; i++) {
+ ret = krb5_encrypt(context, crypto, 0, buf, size, &data);
+ if (ret)
+ krb5_err(context, 1, ret, "encrypt: %d", i);
+ krb5_data_free(&data);
+ }
+
+ gettimeofday(&tv2, NULL);
+
+ timevalsub(&tv2, &tv1);
+
+ printf("%s size: %7lu iterations: %d time: %3ld.%06ld\n",
+ etype_name, (unsigned long)size, iterations,
+ (long)tv2.tv_sec, (long)tv2.tv_usec);
+
+ free(buf);
+ free(etype_name);
+ krb5_crypto_destroy(context, crypto);
+ krb5_free_keyblock_contents(context, &key);
+}
+
+static void
+time_s2k(krb5_context context,
+ krb5_enctype etype,
+ const char *password,
+ krb5_salt salt,
+ int iterations)
+{
+ struct timeval tv1, tv2;
+ krb5_error_code ret;
+ krb5_keyblock key;
+ krb5_data opaque;
+ char *etype_name;
+ int i;
+
+ ret = krb5_enctype_to_string(context, etype, &etype_name);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_enctype_to_string");
+
+ opaque.data = NULL;
+ opaque.length = 0;
+
+ gettimeofday(&tv1, NULL);
+
+ for (i = 0; i < iterations; i++) {
+ ret = krb5_string_to_key_salt_opaque(context, etype, password, salt,
+ opaque, &key);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_string_to_key_data_salt_opaque");
+ krb5_free_keyblock_contents(context, &key);
+ }
+
+ gettimeofday(&tv2, NULL);
+
+ timevalsub(&tv2, &tv1);
+
+ printf("%s string2key %d iterations time: %3ld.%06ld\n",
+ etype_name, iterations, (long)tv2.tv_sec, (long)tv2.tv_usec);
+ free(etype_name);
+
+}
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "");
+ exit (ret);
+}
+
+/* SHA1 test vectors from RFC2202 */
+
+struct rfc2202 {
+ char key[80];
+ int keylen;
+ char data[80];
+ int datalen;
+ char digest[20];
+ int digestlen;
+};
+
+static struct rfc2202 rfc2202_vectors[] =
+{
+ {
+ {0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ 0x0b, 0x0b, 0x0b, 0x0b},
+ 20,
+ "Hi There",
+ 8,
+ {0xb6, 0x17, 0x31, 0x86, 0x55, 0x05, 0x72, 0x64,
+ 0xe2, 0x8b, 0xc0, 0xb6, 0xfb, 0x37, 0x8c, 0x8e,
+ 0xf1, 0x46, 0xbe, 0x00},
+ 20
+ },
+ {
+ "Jefe",
+ 4,
+ "what do ya want for nothing?",
+ 28,
+ {0xef, 0xfc, 0xdf, 0x6a, 0xe5, 0xeb, 0x2f, 0xa2,
+ 0xd2, 0x74, 0x16, 0xd5, 0xf1, 0x84, 0xdf, 0x9c,
+ 0x25, 0x9a, 0x7c, 0x79},
+ 20
+ },
+ {
+ {0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa},
+ 20,
+ {0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd},
+ 50,
+ {0x12, 0x5d, 0x73, 0x42, 0xb9, 0xac, 0x11, 0xcd,
+ 0x91, 0xa3, 0x9a, 0xf4, 0x8a, 0xa1, 0x7b, 0x4f,
+ 0x63, 0xf1, 0x75, 0xd3},
+ 20
+ },
+ {
+ {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+ 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
+ 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
+ 0x19},
+ 25,
+ {0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd},
+ 50,
+ {0x4c, 0x90, 0x07, 0xf4, 0x02, 0x62, 0x50, 0xc6,
+ 0xbc, 0x84, 0x14, 0xf9, 0xbf, 0x50, 0xc8, 0x6c,
+ 0x2d, 0x72, 0x35, 0xda},
+ 20
+ },
+ {
+ {0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
+ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
+ 0x0c, 0x0c, 0x0c, 0x0c},
+ 20,
+ "Test With Truncation",
+ 20,
+ {0x4c, 0x1a, 0x03, 0x42, 0x4b, 0x55, 0xe0, 0x7f,
+ 0xe7, 0xf2, 0x7b, 0xe1, 0xd5, 0x8b, 0xb9, 0x32,
+ 0x4a, 0x9a, 0x5a, 0x04},
+ 20
+ },
+ {
+ {0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa},
+ 80,
+ "Test Using Larger Than Block-Size Key - Hash Key First",
+ 54,
+ {0xaa, 0x4a, 0xe5, 0xe1, 0x52, 0x72, 0xd0, 0x0e,
+ 0x95, 0x70, 0x56, 0x37, 0xce, 0x8a, 0x3b, 0x55,
+ 0xed, 0x40, 0x21, 0x12},
+ 20
+ },
+ {
+ {0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa},
+ 80,
+ "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data",
+ 73,
+ {0xe8, 0xe9, 0x9d, 0x0f, 0x45, 0x23, 0x7d, 0x78,
+ 0x6d, 0x6b, 0xba, 0xa7, 0x96, 0x5c, 0x78, 0x08,
+ 0xbb, 0xff, 0x1a, 0x91},
+ 20
+ }
+};
+
+/* RFC 2202 test vectors for HMAC-SHA1 */
+static void
+test_rfc2202(krb5_context context)
+{
+ int num_tests;
+ int i;
+
+ num_tests = sizeof(rfc2202_vectors) / sizeof(struct rfc2202);
+
+ printf("Running %d RFC2202 HMAC-SHA1 tests\n", num_tests);
+ for (i = 0; i < num_tests; i++) {
+ krb5_keyblock keyblock;
+ Checksum result;
+ struct krb5_crypto_iov iov;
+ struct _krb5_key_data kd;
+ char sha1_data[20];
+ int code;
+
+ memset(&keyblock, 0, sizeof(keyblock));
+ memset(&result, 0, sizeof(result));
+
+ keyblock.keyvalue.length = rfc2202_vectors[i].keylen;
+ keyblock.keyvalue.data = &rfc2202_vectors[i].key;
+
+ result.checksum.data = &sha1_data;
+ result.checksum.length = sizeof(sha1_data);
+
+ code = krb5_hmac(context, CKSUMTYPE_SHA1,
+ &rfc2202_vectors[i].data, rfc2202_vectors[i].datalen,
+ 0, &keyblock, &result);
+
+ if (code != 0)
+ errx(1, "HMAC-SHA1 failed with %d on test %d", code, i + 1);
+
+ if (memcmp(&sha1_data, rfc2202_vectors[i].digest, sizeof(sha1_data)) !=0)
+ errx(1, "Digests don't match on test %d", i);
+
+ printf("Test %d okay\n", (i * 2) + 1);
+
+ /* Now check the same using the internal HMAC function */
+
+ iov.data.data = rfc2202_vectors[i].data;
+ iov.data.length = rfc2202_vectors[i].datalen;
+ iov.flags = KRB5_CRYPTO_TYPE_DATA;
+ kd.key = &keyblock;
+ kd.schedule = NULL;
+ code = _krb5_SP_HMAC_SHA1_checksum(context, NULL, &kd, 0,
+ &iov, 1, &result);
+
+ if (code != 0)
+ errx(1, "HMAC-SHA1 failed with %d on test %d", code, i + 1);
+
+ if (memcmp(&sha1_data, rfc2202_vectors[i].digest, sizeof(sha1_data)) !=0)
+ errx(1, "Digests don't match on test %d", i);
+
+ printf("Test %d okay\n", (i * 2) + 2);
+ }
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ int i, enciter, s2kiter, hmaciter;
+ int optidx = 0;
+ krb5_salt salt;
+
+ krb5_enctype enctypes[] = {
+ ETYPE_DES_CBC_CRC,
+ ETYPE_DES3_CBC_SHA1,
+ ETYPE_ARCFOUR_HMAC_MD5,
+ ETYPE_AES128_CTS_HMAC_SHA1_96,
+ ETYPE_AES256_CTS_HMAC_SHA1_96,
+ ETYPE_AES128_CTS_HMAC_SHA256_128,
+ ETYPE_AES256_CTS_HMAC_SHA384_192
+ };
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ salt.salttype = KRB5_PW_SALT;
+ salt.saltvalue.data = NULL;
+ salt.saltvalue.length = 0;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ test_rfc2202(context);
+
+ enciter = 1000;
+ hmaciter = 10000;
+ s2kiter = 100;
+
+ time_hmac(context, 16, hmaciter);
+ time_hmac(context, 32, hmaciter);
+ time_hmac(context, 512, hmaciter);
+ time_hmac(context, 1024, hmaciter);
+ time_hmac(context, 2048, hmaciter);
+ time_hmac(context, 4096, hmaciter);
+ time_hmac(context, 8192, hmaciter);
+ time_hmac(context, 16384, hmaciter);
+ time_hmac(context, 32768, hmaciter);
+
+ time_hmac_evp(context, 16, hmaciter);
+ time_hmac_evp(context, 32, hmaciter);
+ time_hmac_evp(context, 512, hmaciter);
+ time_hmac_evp(context, 1024, hmaciter);
+ time_hmac_evp(context, 2048, hmaciter);
+ time_hmac_evp(context, 4096, hmaciter);
+ time_hmac_evp(context, 8192, hmaciter);
+ time_hmac_evp(context, 16384, hmaciter);
+ time_hmac_evp(context, 32768, hmaciter);
+
+ for (i = 0; i < sizeof(enctypes)/sizeof(enctypes[0]); i++) {
+
+ krb5_enctype_enable(context, enctypes[i]);
+
+ time_encryption(context, 16, enctypes[i], enciter);
+ time_encryption(context, 32, enctypes[i], enciter);
+ time_encryption(context, 512, enctypes[i], enciter);
+ time_encryption(context, 1024, enctypes[i], enciter);
+ time_encryption(context, 2048, enctypes[i], enciter);
+ time_encryption(context, 4096, enctypes[i], enciter);
+ time_encryption(context, 8192, enctypes[i], enciter);
+ time_encryption(context, 16384, enctypes[i], enciter);
+ time_encryption(context, 32768, enctypes[i], enciter);
+
+ time_s2k(context, enctypes[i], "mYsecreitPassword", salt, s2kiter);
+ }
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_set_kvno0.c b/third_party/heimdal/lib/krb5/test_set_kvno0.c
new file mode 100644
index 0000000..0c7e6b4
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_set_kvno0.c
@@ -0,0 +1,182 @@
+/*
+ * Copyright (c) 2011, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "krb5_locl.h"
+#include <err.h>
+#include <getarg.h>
+
+#if 0
+#include <stdio.h>
+#include <string.h>
+#include <strings.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <krb5.h>
+#endif
+
+int
+main(int argc, char **argv)
+{
+ krb5_error_code ret;
+ krb5_context context;
+ krb5_ccache src_cc = NULL;
+ krb5_ccache dst_cc = NULL;
+ krb5_cc_cursor cursor;
+ krb5_principal me = NULL;
+ krb5_creds cred;
+ const char *during;
+ Ticket t;
+ size_t len;
+ int make_kvno_absent = 0;
+ int opt;
+
+ memset(&cred, 0, sizeof (cred));
+ during = "init_context";
+ ret = krb5_init_context(&context);
+ if (ret) goto err;
+
+ while ((opt = getopt(argc, argv, "c:n")) != -1) {
+ switch (opt) {
+ case 'c':
+ during = "cc_resolve of source ccache";
+ ret = krb5_cc_resolve(context, optarg, &src_cc);
+ if (ret) goto err;
+ break;
+ case 'n':
+ make_kvno_absent++;
+ break;
+ case 'h':
+ default:
+ fprintf(stderr, "Usage: %s [-n] [-c ccache]\n"
+ "\tThis utility edits a ccache, setting all ticket\n"
+ "\tenc_part kvnos to zero or absent (if -n is set).\n",
+ argv[0]);
+ return 1;
+ }
+ }
+
+ if (!src_cc) {
+ during = "cc_default";
+ ret = krb5_cc_default(context, &src_cc);
+ if (ret) goto err;
+ }
+
+ during = "cc_get_principal";
+ ret = krb5_cc_get_principal(context, src_cc, &me);
+ if (ret) goto err;
+
+ if (optind != argc) {
+ fprintf(stderr, "Usage: %s [-n] [-c ccache]\n"
+ "\tThis utility edits a ccache, setting all ticket\n"
+ "\tenc_part kvnos to zero or absent (if -n is set).\n",
+ argv[0]);
+ return 1;
+ }
+
+ during = "cc_new_unique of temporary ccache";
+ ret = krb5_cc_new_unique(context, krb5_cc_get_type(context, src_cc),
+ NULL, &dst_cc);
+
+ during = "cc_initialize of temporary ccache";
+ ret = krb5_cc_initialize(context, dst_cc, me);
+ if (ret) goto err;
+
+ during = "cc_start_seq_get";
+ ret = krb5_cc_start_seq_get(context, src_cc, &cursor);
+ if (ret) goto err;
+
+ while ((ret = krb5_cc_next_cred(context, src_cc, &cursor, &cred)) == 0) {
+ krb5_data data;
+
+ during = "decode_Ticket";
+ memset(&t, 0, sizeof (t));
+ ret = decode_Ticket(cred.ticket.data, cred.ticket.length, &t, &len);
+ if (ret == ASN1_MISSING_FIELD) {
+ krb5_free_cred_contents(context, &cred);
+ memset(&cred, 0, sizeof (cred));
+ continue;
+ }
+ if (ret) goto err;
+ if (t.enc_part.kvno) {
+ *t.enc_part.kvno = 0;
+ if (make_kvno_absent) {
+ free(t.enc_part.kvno);
+ t.enc_part.kvno = NULL;
+ }
+ /*
+ * The new Ticket has to need less or same space as before, so
+ * we reuse cred->icket.data.
+ */
+ during = "encode_Ticket";
+ ASN1_MALLOC_ENCODE(Ticket, data.data, data.length, &t, &len, ret);
+ if (ret) {
+ free_Ticket(&t);
+ goto err;
+ }
+ krb5_data_free(&cred.ticket);
+ cred.ticket = data;
+ }
+ free_Ticket(&t);
+ during = "cc_store_cred";
+ ret = krb5_cc_store_cred(context, dst_cc, &cred);
+ if (ret) goto err;
+ krb5_free_cred_contents(context, &cred);
+ memset(&cred, 0, sizeof (cred));
+ }
+ during = "cc_next_cred";
+ if (ret != KRB5_CC_END) goto err;
+
+ during = "cc_end_seq_get";
+ ret = krb5_cc_end_seq_get(context, src_cc, &cursor);
+ if (ret) goto err;
+
+ during = "cc_move";
+ ret = krb5_cc_move(context, dst_cc, src_cc);
+ if (ret) goto err;
+ dst_cc = NULL;
+
+ during = "cc_switch";
+ ret = krb5_cc_switch(context, src_cc);
+ if (ret) goto err;
+
+err:
+ (void) krb5_free_principal(context, me);
+ if (src_cc)
+ (void) krb5_cc_close(context, src_cc);
+ if (dst_cc)
+ (void) krb5_cc_destroy(context, dst_cc);
+ if (ret) {
+ fprintf(stderr, "Failed while doing %s (%d)\n", during, ret);
+ ret = 1;
+ }
+ return (ret);
+}
+
diff --git a/third_party/heimdal/lib/krb5/test_store.c b/third_party/heimdal/lib/krb5/test_store.c
new file mode 100644
index 0000000..163022c
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_store.c
@@ -0,0 +1,364 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <getarg.h>
+
+static void
+test_int8(krb5_context context, krb5_storage *sp)
+{
+ krb5_error_code ret;
+ int i;
+ int8_t val[] = {
+ 0, 1, -1, 128, -127
+ }, v;
+
+ krb5_storage_truncate(sp, 0);
+
+ for (i = 0; i < sizeof(val)/sizeof(val[0]); i++) {
+
+ ret = krb5_store_int8(sp, val[i]);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_store_int8");
+ krb5_storage_seek(sp, i, SEEK_SET);
+ ret = krb5_ret_int8(sp, &v);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_ret_int8");
+ if (v != val[i])
+ krb5_errx(context, 1, "store and ret mismatch");
+ }
+}
+
+static void
+test_int16(krb5_context context, krb5_storage *sp)
+{
+ krb5_error_code ret;
+ int i;
+ int16_t val[] = {
+ 0, 1, -1, 32767, -32768
+ }, v;
+
+ krb5_storage_truncate(sp, 0);
+
+ for (i = 0; i < sizeof(val)/sizeof(val[0]); i++) {
+
+ ret = krb5_store_int16(sp, val[i]);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_store_int16");
+ krb5_storage_seek(sp, i * sizeof (v), SEEK_SET);
+ ret = krb5_ret_int16(sp, &v);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_ret_int16");
+ if (v != val[i])
+ krb5_errx(context, 1, "store and ret mismatch");
+ }
+}
+
+static void
+test_int32(krb5_context context, krb5_storage *sp)
+{
+ krb5_error_code ret;
+ int i;
+ int32_t val[] = {
+ 0, 1, -1, 2147483647, -2147483646
+ }, v;
+
+ krb5_storage_truncate(sp, 0);
+
+ for (i = 0; i < sizeof(val)/sizeof(val[0]); i++) {
+
+ ret = krb5_store_int32(sp, val[i]);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_store_int32");
+ krb5_storage_seek(sp, i * sizeof (v), SEEK_SET);
+ ret = krb5_ret_int32(sp, &v);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_ret_int32");
+ if (v != val[i])
+ krb5_errx(context, 1, "store and ret mismatch");
+ }
+}
+
+static void
+test_uint8(krb5_context context, krb5_storage *sp)
+{
+ krb5_error_code ret;
+ int i;
+ uint8_t val[] = {
+ 0, 1, 255
+ }, v;
+
+ krb5_storage_truncate(sp, 0);
+
+ for (i = 0; i < sizeof(val)/sizeof(val[0]); i++) {
+
+ ret = krb5_store_uint8(sp, val[i]);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_store_uint8");
+ krb5_storage_seek(sp, i * sizeof (v), SEEK_SET);
+ ret = krb5_ret_uint8(sp, &v);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_ret_uint8");
+ if (v != val[i])
+ krb5_errx(context, 1, "store and ret mismatch");
+ }
+}
+
+static void
+test_uint16(krb5_context context, krb5_storage *sp)
+{
+ krb5_error_code ret;
+ int i;
+ uint16_t val[] = {
+ 0, 1, 65535
+ }, v;
+
+ krb5_storage_truncate(sp, 0);
+
+ for (i = 0; i < sizeof(val)/sizeof(val[0]); i++) {
+
+ ret = krb5_store_uint16(sp, val[i]);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_store_uint16");
+ krb5_storage_seek(sp, i * sizeof (v), SEEK_SET);
+ ret = krb5_ret_uint16(sp, &v);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_ret_uint16");
+ if (v != val[i])
+ krb5_errx(context, 1, "store and ret mismatch");
+ }
+}
+
+static void
+test_uint32(krb5_context context, krb5_storage *sp)
+{
+ krb5_error_code ret;
+ int i;
+ uint32_t val[] = {
+ 0, 1, 4294967295UL
+ }, v;
+
+ krb5_storage_truncate(sp, 0);
+
+ for (i = 0; i < sizeof(val)/sizeof(val[0]); i++) {
+
+ ret = krb5_store_uint32(sp, val[i]);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_store_uint32");
+ krb5_storage_seek(sp, i * sizeof (v), SEEK_SET);
+ ret = krb5_ret_uint32(sp, &v);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_ret_uint32");
+ if (v != val[i])
+ krb5_errx(context, 1, "store and ret mismatch");
+ }
+}
+
+
+static void
+test_storage(krb5_context context, krb5_storage *sp)
+{
+ test_int8(context, sp);
+ test_int16(context, sp);
+ test_int32(context, sp);
+ test_uint8(context, sp);
+ test_uint16(context, sp);
+ test_uint32(context, sp);
+}
+
+
+static void
+test_truncate(krb5_context context, krb5_storage *sp, int fd)
+{
+ struct stat sb;
+
+ krb5_storage_truncate(sp, 0);
+ krb5_store_string(sp, "hej");
+ krb5_storage_truncate(sp, 2);
+
+ if (fstat(fd, &sb) != 0)
+ krb5_err(context, 1, errno, "fstat");
+ if (sb.st_size != 2)
+ krb5_errx(context, 1, "length not 2");
+
+ krb5_storage_truncate(sp, 1024);
+
+ if (fstat(fd, &sb) != 0)
+ krb5_err(context, 1, errno, "fstat");
+ if (sb.st_size != 1024)
+ krb5_errx(context, 1, "length not 1024");
+}
+
+static void
+test_buffer_issues(krb5_context context, krb5_storage *sp)
+{
+ krb5_error_code ret;
+ size_t i;
+ uint32_t v;
+
+ krb5_storage_set_eof_code(sp, -1);
+ krb5_storage_truncate(sp, 0);
+ for (i=0; i < 4096; i++) {
+ krb5_store_uint32(sp, i);
+ }
+
+ krb5_storage_truncate(sp, 1024);
+ ret = krb5_ret_uint32(sp, &v);
+ if (ret != -1)
+ krb5_errx(context, 1, "Should have received EOF");
+
+ krb5_storage_seek(sp, 8, SEEK_SET);
+ ret = krb5_ret_uint32(sp, &v);
+ if (ret == -1)
+ krb5_errx(context, 1, "Should not have received EOF");
+ if (v != 2)
+ krb5_errx(context, 1, "uint32 should have been 2");
+}
+
+static void
+check_too_large(krb5_context context, krb5_storage *sp)
+{
+ uint32_t too_big_sizes[] = { UINT_MAX, UINT_MAX / 2, UINT_MAX / 4, UINT_MAX / 8 + 1};
+ krb5_error_code ret;
+ krb5_data data;
+ size_t n;
+
+ for (n = 0; n < sizeof(too_big_sizes) / sizeof(too_big_sizes[0]); n++) {
+ krb5_storage_truncate(sp, 0);
+ krb5_store_uint32(sp, too_big_sizes[n]);
+ krb5_storage_seek(sp, 0, SEEK_SET);
+ ret = krb5_ret_data(sp, &data);
+ if (ret != HEIM_ERR_TOO_BIG)
+ errx(1, "not too big: %lu", (unsigned long)n);
+ }
+}
+
+/*
+ *
+ */
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ int fd, optidx = 0;
+ krb5_storage *sp;
+ const char *fn = "test-store-data";
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ ret = krb5_init_context (&context);
+ if (ret)
+ errx (1, "krb5_init_context failed: %d", ret);
+
+ /*
+ * Test encoding/decoding of primotive types on diffrent backends
+ */
+
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ krb5_errx(context, 1, "krb5_storage_emem: no mem");
+
+ test_storage(context, sp);
+ check_too_large(context, sp);
+ krb5_storage_free(sp);
+
+
+ fd = open(fn, O_RDWR|O_CREAT|O_TRUNC, 0600);
+ if (fd < 0)
+ krb5_err(context, 1, errno, "open(%s)", fn);
+
+ sp = krb5_storage_from_fd(fd);
+ if (sp == NULL)
+ krb5_errx(context, 1, "krb5_storage_from_fd: %s no mem", fn);
+
+ test_storage(context, sp);
+ test_truncate(context, sp, fd);
+ test_buffer_issues(context, sp);
+ krb5_storage_free(sp);
+ close(fd);
+ unlink(fn);
+
+ fd = open(fn, O_RDWR|O_CREAT|O_TRUNC, 0600);
+ if (fd < 0)
+ krb5_err(context, 1, errno, "open(%s)", fn);
+
+ sp = krb5_storage_stdio_from_fd(fd, "r+");
+ if (sp == NULL)
+ krb5_errx(context, 1, "krb5_storage_stdio_from_fd: %s no mem", fn);
+
+ test_storage(context, sp);
+ test_truncate(context, sp, fd);
+ test_buffer_issues(context, sp);
+ krb5_storage_free(sp);
+ close(fd);
+ unlink(fn);
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_time.c b/third_party/heimdal/lib/krb5/test_time.c
new file mode 100644
index 0000000..9c6d1cc
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_time.c
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include <err.h>
+
+static void
+check_set_time(krb5_context context)
+{
+ krb5_error_code ret;
+ krb5_timestamp sec;
+ int32_t usec;
+ struct timeval tv;
+ int diff = 10;
+ int diff2;
+
+ gettimeofday(&tv, NULL);
+
+ ret = krb5_set_real_time(context, tv.tv_sec + diff, tv.tv_usec);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_us_timeofday");
+
+ ret = krb5_us_timeofday(context, &sec, &usec);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_us_timeofday");
+
+ diff2 = krb5_time_abs(sec, tv.tv_sec);
+
+ if (diff2 < 9 || diff > 11)
+ krb5_errx(context, 1, "set time error: diff: %ld",
+ krb5_time_abs(sec, tv.tv_sec));
+}
+
+
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_init_context %d", ret);
+
+ check_set_time(context);
+ check_set_time(context);
+ check_set_time(context);
+ check_set_time(context);
+ check_set_time(context);
+
+ krb5_free_context(context);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/test_x500.c b/third_party/heimdal/lib/krb5/test_x500.c
new file mode 100644
index 0000000..ecad779
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/test_x500.c
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2011 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "krb5_locl.h"
+#include <err.h>
+
+/*
+ *
+ */
+
+static void
+check_linear(krb5_context context,
+ const char *client_realm,
+ const char *server_realm,
+ const char *realm,
+ ...)
+{
+ unsigned int num_inrealms = 0, num_realms = 0, n;
+ char **inrealms = NULL;
+ char **realms = NULL;
+ krb5_error_code ret;
+ krb5_data tr;
+ va_list va;
+
+ krb5_data_zero(&tr);
+
+ va_start(va, realm);
+
+ while (realm) {
+ inrealms = erealloc(inrealms, (num_inrealms + 2) * sizeof(inrealms[0]));
+ inrealms[num_inrealms] = rk_UNCONST(realm);
+ num_inrealms++;
+ realm = va_arg(va, const char *);
+ }
+ if (inrealms)
+ inrealms[num_inrealms] = NULL;
+
+ ret = krb5_domain_x500_encode(inrealms, num_inrealms, &tr);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_domain_x500_encode");
+
+ ret = krb5_domain_x500_decode(context, tr,
+ &realms, &num_realms,
+ client_realm, server_realm);
+ if (ret)
+ krb5_err(context, 1, ret, "krb5_domain_x500_decode");
+
+ krb5_data_free(&tr);
+
+ if (num_inrealms != num_realms)
+ errx(1, "num_inrealms != num_realms");
+
+ for(n = 0; n < num_realms; n++)
+ free(realms[n]);
+ free(realms);
+
+ free(inrealms);
+}
+
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+
+ setprogname(argv[0]);
+
+ ret = krb5_init_context(&context);
+ if (ret)
+ errx(1, "krb5_init_context");
+
+
+ check_linear(context, "KTH1.SE", "KTH1.SE", NULL);
+ check_linear(context, "KTH1.SE", "KTH2.SE", NULL);
+ check_linear(context, "KTH1.SE", "KTH3.SE", "KTH2.SE", NULL);
+ check_linear(context, "KTH1.SE", "KTH4.SE", "KTH3.SE", "KTH2.SE", NULL);
+ check_linear(context, "KTH1.SE", "KTH5.SE", "KTH4.SE", "KTH3.SE", "KTH2.SE", NULL);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/krb5/ticket.c b/third_party/heimdal/lib/krb5/ticket.c
new file mode 100644
index 0000000..d19fcc6
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/ticket.c
@@ -0,0 +1,967 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ * Free ticket and content
+ *
+ * @param context a Kerberos 5 context
+ * @param ticket ticket to free
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_free_ticket(krb5_context context,
+ krb5_ticket *ticket)
+{
+ free_EncTicketPart(&ticket->ticket);
+ krb5_free_principal(context, ticket->client);
+ krb5_free_principal(context, ticket->server);
+ free(ticket);
+ return 0;
+}
+
+/**
+ * Copy ticket and content
+ *
+ * @param context a Kerberos 5 context
+ * @param from ticket to copy
+ * @param to new copy of ticket, free with krb5_free_ticket()
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_ticket(krb5_context context,
+ const krb5_ticket *from,
+ krb5_ticket **to)
+{
+ krb5_error_code ret;
+ krb5_ticket *tmp;
+
+ *to = NULL;
+ tmp = malloc(sizeof(*tmp));
+ if (tmp == NULL)
+ return krb5_enomem(context);
+ if((ret = copy_EncTicketPart(&from->ticket, &tmp->ticket))){
+ free(tmp);
+ return ret;
+ }
+ ret = krb5_copy_principal(context, from->client, &tmp->client);
+ if(ret){
+ free_EncTicketPart(&tmp->ticket);
+ free(tmp);
+ return ret;
+ }
+ ret = krb5_copy_principal(context, from->server, &tmp->server);
+ if(ret){
+ krb5_free_principal(context, tmp->client);
+ free_EncTicketPart(&tmp->ticket);
+ free(tmp);
+ return ret;
+ }
+ *to = tmp;
+ return 0;
+}
+
+/**
+ * Return client principal in ticket
+ *
+ * @param context a Kerberos 5 context
+ * @param ticket ticket to copy
+ * @param client client principal, free with krb5_free_principal()
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ticket_get_client(krb5_context context,
+ const krb5_ticket *ticket,
+ krb5_principal *client)
+{
+ return krb5_copy_principal(context, ticket->client, client);
+}
+
+/**
+ * Return server principal in ticket
+ *
+ * @param context a Kerberos 5 context
+ * @param ticket ticket to copy
+ * @param server server principal, free with krb5_free_principal()
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ticket_get_server(krb5_context context,
+ const krb5_ticket *ticket,
+ krb5_principal *server)
+{
+ return krb5_copy_principal(context, ticket->server, server);
+}
+
+/**
+ * Return end time of a ticket
+ *
+ * @param context a Kerberos 5 context
+ * @param ticket ticket to copy
+ *
+ * @return end time of ticket
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION time_t KRB5_LIB_CALL
+krb5_ticket_get_endtime(krb5_context context,
+ const krb5_ticket *ticket)
+{
+ return ticket->ticket.endtime;
+}
+
+/**
+ * Return authentication, start, end, and renew limit times of a ticket
+ *
+ * @param context a Kerberos 5 context
+ * @param ticket ticket to copy
+ * @param t pointer to krb5_times structure
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_ticket_get_times(krb5_context context,
+ const krb5_ticket *ticket,
+ krb5_times *t)
+{
+ t->authtime = ticket->ticket.authtime;
+ t->starttime = ticket->ticket.starttime ? *ticket->ticket.starttime :
+ t->authtime;
+ t->endtime = ticket->ticket.endtime;
+ t->renew_till = ticket->ticket.renew_till ? *ticket->ticket.renew_till :
+ t->endtime;
+}
+
+/**
+ * Get the flags from the Kerberos ticket
+ *
+ * @param context Kerberos context
+ * @param ticket Kerberos ticket
+ *
+ * @return ticket flags
+ *
+ * @ingroup krb5_ticket
+ */
+KRB5_LIB_FUNCTION unsigned long KRB5_LIB_CALL
+krb5_ticket_get_flags(krb5_context context,
+ const krb5_ticket *ticket)
+{
+ return TicketFlags2int(ticket->ticket.flags);
+}
+
+/*
+ * Find an authz-data element in the given `ad'. If `failp', then validate any
+ * containing AD-KDC-ISSUED's keyed checksum with the `sessionkey' (if given).
+ *
+ * All AD-KDC-ISSUED will be validated (if requested) even when `type' is
+ * `KRB5_AUTHDATA_KDC_ISSUED'.
+ *
+ * Only the first matching element will be output (via `data').
+ *
+ * Note that all AD-KDC-ISSUEDs found while traversing the authz-data will be
+ * validated, though only the first one will be returned.
+ *
+ * XXX We really need a better interface though. First, forget AD-AND-OR --
+ * just remove it. Second, probably forget AD-KDC-ISSUED, but still, between
+ * that, the PAC, and the CAMMAC, we need an interface that can:
+ *
+ * a) take the derived keys instead of the service key or the session key,
+ * b) can indicate whether the element was marked critical,
+ * c) can indicate whether the element was authenticated to the KDC,
+ * d) can iterate over all the instances found (if more than one is found).
+ *
+ * Also, we need to know here if the authz-data is from a Ticket or from an
+ * Authenticator -- if the latter then we must refuse to find AD-KDC-ISSUED /
+ * PAC / CAMMAC or anything of the sort, ever.
+ */
+static int
+find_type_in_ad(krb5_context context,
+ int type,
+ krb5_data *data, /* optional */
+ krb5_boolean *found,
+ krb5_boolean failp, /* validate AD-KDC-ISSUED */
+ krb5_keyblock *sessionkey, /* ticket session key */
+ const AuthorizationData *ad,
+ int level)
+{
+ krb5_error_code ret = 0;
+ size_t i;
+
+ if (level > 9) {
+ ret = ENOENT; /* XXX */
+ krb5_set_error_message(context, ret,
+ N_("Authorization data nested deeper "
+ "then %d levels, stop searching", ""),
+ level);
+ goto out;
+ }
+
+ /*
+ * Only copy out the element the first time we get to it, we need
+ * to run over the whole authorization data fields to check if
+ * there are any container clases we need to care about.
+ */
+ for (i = 0; i < ad->len; i++) {
+ if (!*found && ad->val[i].ad_type == type) {
+ if (data) {
+ ret = der_copy_octet_string(&ad->val[i].ad_data, data);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("malloc: out of memory", ""));
+ goto out;
+ }
+ }
+ *found = TRUE;
+ if (type != KRB5_AUTHDATA_KDC_ISSUED ||
+ !failp || !sessionkey || !sessionkey->keyvalue.length)
+ continue;
+ /* else go on to validate the AD-KDC-ISSUED's keyed checksum */
+ }
+ switch (ad->val[i].ad_type) {
+ case KRB5_AUTHDATA_IF_RELEVANT: {
+ AuthorizationData child;
+ ret = decode_AuthorizationData(ad->val[i].ad_data.data,
+ ad->val[i].ad_data.length,
+ &child,
+ NULL);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to decode "
+ "IF_RELEVANT with %d", ""),
+ (int)ret);
+ goto out;
+ }
+ ret = find_type_in_ad(context, type, data, found, FALSE,
+ sessionkey, &child, level + 1);
+ free_AuthorizationData(&child);
+ if (ret)
+ goto out;
+ break;
+ }
+ case KRB5_AUTHDATA_KDC_ISSUED: {
+ AD_KDCIssued child;
+
+ ret = decode_AD_KDCIssued(ad->val[i].ad_data.data,
+ ad->val[i].ad_data.length,
+ &child,
+ NULL);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to decode "
+ "AD_KDCIssued with %d", ""),
+ ret);
+ goto out;
+ }
+ if (failp && sessionkey && sessionkey->keyvalue.length) {
+ krb5_boolean valid;
+ krb5_data buf;
+ size_t len;
+
+ ASN1_MALLOC_ENCODE(AuthorizationData, buf.data, buf.length,
+ &child.elements, &len, ret);
+ if (ret) {
+ free_AD_KDCIssued(&child);
+ krb5_clear_error_message(context);
+ goto out;
+ }
+ if(buf.length != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+
+ ret = krb5_c_verify_checksum(context, sessionkey, 19, &buf,
+ &child.ad_checksum, &valid);
+ krb5_data_free(&buf);
+ if (ret) {
+ free_AD_KDCIssued(&child);
+ goto out;
+ }
+ if (!valid) {
+ krb5_clear_error_message(context);
+ ret = ENOENT;
+ free_AD_KDCIssued(&child);
+ goto out;
+ }
+ } else if (failp) {
+ krb5_clear_error_message(context);
+ ret = ENOENT;
+ free_AD_KDCIssued(&child);
+ goto out;
+ }
+ ret = find_type_in_ad(context, type, data, found, failp, sessionkey,
+ &child.elements, level + 1);
+ free_AD_KDCIssued(&child);
+ if (ret)
+ goto out;
+ break;
+ }
+ case KRB5_AUTHDATA_AND_OR:
+ if (!failp)
+ break;
+ ret = ENOENT; /* XXX */
+ krb5_set_error_message(context, ret,
+ N_("Authorization data contains "
+ "AND-OR element that is unknown to the "
+ "application", ""));
+ goto out;
+ default:
+ if (!failp)
+ break;
+ ret = ENOENT; /* XXX */
+ krb5_set_error_message(context, ret,
+ N_("Authorization data contains "
+ "unknown type (%d) ", ""),
+ ad->val[i].ad_type);
+ goto out;
+ }
+ }
+out:
+ if (ret) {
+ if (*found) {
+ if (data)
+ krb5_data_free(data);
+ *found = 0;
+ }
+ }
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_get_ad(krb5_context context,
+ const AuthorizationData *ad,
+ krb5_keyblock *sessionkey,
+ int type,
+ krb5_data *data)
+{
+ krb5_boolean found = FALSE;
+ krb5_error_code ret;
+
+ if (data)
+ krb5_data_zero(data);
+
+ if (ad == NULL) {
+ krb5_set_error_message(context, ENOENT,
+ N_("No authorization data", ""));
+ return ENOENT; /* XXX */
+ }
+
+ ret = find_type_in_ad(context, type, data, &found, TRUE, sessionkey, ad, 0);
+ if (ret)
+ return ret;
+ if (!found) {
+ krb5_set_error_message(context, ENOENT,
+ N_("Have no authorization data of type %d", ""),
+ type);
+ return ENOENT; /* XXX */
+ }
+ return 0;
+}
+
+
+/**
+ * Extract the authorization data type of type from the ticket. Store
+ * the field in data. This function is to use for kerberos
+ * applications.
+ *
+ * @param context a Kerberos 5 context
+ * @param ticket Kerberos ticket
+ * @param type type to fetch
+ * @param data returned data, free with krb5_data_free()
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ticket_get_authorization_data_type(krb5_context context,
+ krb5_ticket *ticket,
+ int type,
+ krb5_data *data)
+{
+ AuthorizationData *ad;
+ krb5_error_code ret;
+ krb5_boolean found = FALSE;
+
+ if (data)
+ krb5_data_zero(data);
+
+ ad = ticket->ticket.authorization_data;
+ if (ticket->ticket.authorization_data == NULL) {
+ krb5_set_error_message(context, ENOENT,
+ N_("Ticket has no authorization data", ""));
+ return ENOENT; /* XXX */
+ }
+
+ ret = find_type_in_ad(context, type, data, &found, TRUE,
+ &ticket->ticket.key, ad, 0);
+ if (ret)
+ return ret;
+ if (!found) {
+ krb5_set_error_message(context, ENOENT,
+ N_("Ticket has no "
+ "authorization data of type %d", ""),
+ type);
+ return ENOENT; /* XXX */
+ }
+ return 0;
+}
+
+static krb5_error_code
+check_server_referral(krb5_context context,
+ krb5_kdc_rep *rep,
+ unsigned flags,
+ krb5_const_principal requested,
+ krb5_const_principal returned,
+ krb5_keyblock * key)
+{
+ krb5_error_code ret;
+ PA_ServerReferralData ref;
+ krb5_crypto session;
+ EncryptedData ed;
+ size_t len;
+ krb5_data data;
+ PA_DATA *pa;
+ int i = 0, cmp;
+
+ if (rep->kdc_rep.padata == NULL)
+ goto noreferral;
+
+ pa = krb5_find_padata(rep->kdc_rep.padata->val,
+ rep->kdc_rep.padata->len,
+ KRB5_PADATA_SERVER_REFERRAL, &i);
+ if (pa == NULL)
+ goto noreferral;
+
+ memset(&ed, 0, sizeof(ed));
+ memset(&ref, 0, sizeof(ref));
+
+ ret = decode_EncryptedData(pa->padata_value.data,
+ pa->padata_value.length,
+ &ed, &len);
+ if (ret)
+ return ret;
+ if (len != pa->padata_value.length) {
+ free_EncryptedData(&ed);
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+ N_("Referral EncryptedData wrong for realm %s",
+ "realm"), requested->realm);
+ return KRB5KRB_AP_ERR_MODIFIED;
+ }
+
+ ret = krb5_crypto_init(context, key, 0, &session);
+ if (ret) {
+ free_EncryptedData(&ed);
+ return ret;
+ }
+
+ ret = krb5_decrypt_EncryptedData(context, session,
+ KRB5_KU_PA_SERVER_REFERRAL,
+ &ed, &data);
+ free_EncryptedData(&ed);
+ krb5_crypto_destroy(context, session);
+ if (ret)
+ return ret;
+
+ ret = decode_PA_ServerReferralData(data.data, data.length, &ref, &len);
+ if (ret) {
+ krb5_data_free(&data);
+ return ret;
+ }
+ krb5_data_free(&data);
+
+ if (strcmp(requested->realm, returned->realm) != 0) {
+ free_PA_ServerReferralData(&ref);
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+ N_("server ref realm mismatch, "
+ "requested realm %s got back %s", ""),
+ requested->realm, returned->realm);
+ return KRB5KRB_AP_ERR_MODIFIED;
+ }
+
+ if (krb5_principal_is_krbtgt(context, returned)) {
+ const char *realm = returned->name.name_string.val[1];
+
+ if (ref.referred_realm == NULL
+ || strcmp(*ref.referred_realm, realm) != 0)
+ {
+ free_PA_ServerReferralData(&ref);
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+ N_("tgt returned with wrong ref", ""));
+ return KRB5KRB_AP_ERR_MODIFIED;
+ }
+ } else if (krb5_principal_compare(context, returned, requested) == 0) {
+ free_PA_ServerReferralData(&ref);
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+ N_("req princ no same as returned", ""));
+ return KRB5KRB_AP_ERR_MODIFIED;
+ }
+
+ if (ref.requested_principal_name) {
+ cmp = _krb5_principal_compare_PrincipalName(context,
+ requested,
+ ref.requested_principal_name);
+ if (!cmp) {
+ free_PA_ServerReferralData(&ref);
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+ N_("referred principal not same "
+ "as requested", ""));
+ return KRB5KRB_AP_ERR_MODIFIED;
+ }
+ } else if (flags & EXTRACT_TICKET_AS_REQ) {
+ free_PA_ServerReferralData(&ref);
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+ N_("Requested principal missing on AS-REQ", ""));
+ return KRB5KRB_AP_ERR_MODIFIED;
+ }
+
+ free_PA_ServerReferralData(&ref);
+
+ return ret;
+noreferral:
+ /*
+ * Expect excact match or that we got a krbtgt
+ */
+ if (krb5_principal_compare(context, requested, returned) != TRUE &&
+ (krb5_realm_compare(context, requested, returned) != TRUE &&
+ krb5_principal_is_krbtgt(context, returned) != TRUE))
+ {
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+ N_("Not same server principal returned "
+ "as requested", ""));
+ return KRB5KRB_AP_ERR_MODIFIED;
+ }
+ return 0;
+}
+
+/*
+ * Verify KDC supported anonymous if requested
+ */
+static krb5_error_code
+check_client_anonymous(krb5_context context,
+ krb5_kdc_rep *rep,
+ krb5_const_principal requested,
+ krb5_const_principal mapped,
+ krb5_boolean is_tgs_rep)
+{
+ int flags;
+
+ if (!rep->enc_part.flags.anonymous)
+ return KRB5KDC_ERR_BADOPTION;
+
+ /*
+ * Here we must validate that the AS returned a ticket of the expected type
+ * for either a fully anonymous request, or authenticated request for an
+ * anonymous ticket. If this is a TGS request, we're done. Then if the
+ * 'requested' principal was anonymous, we'll check the 'mapped' principal
+ * accordingly (without enforcing the name type and perhaps the realm).
+ * Finally, if the 'requested' principal was not anonymous, well check
+ * that the 'mapped' principal has an anonymous name and type, in a
+ * non-anonymous realm. (Should we also be checking for a realm match
+ * between the request and the mapped name in this case?)
+ */
+ if (is_tgs_rep)
+ flags = KRB5_ANON_MATCH_ANY_NONT;
+ else if (krb5_principal_is_anonymous(context, requested,
+ KRB5_ANON_MATCH_ANY_NONT))
+ flags = KRB5_ANON_MATCH_UNAUTHENTICATED | KRB5_ANON_IGNORE_NAME_TYPE;
+ else
+ flags = KRB5_ANON_MATCH_AUTHENTICATED;
+
+ if (!krb5_principal_is_anonymous(context, mapped, flags))
+ return KRB5KRB_AP_ERR_MODIFIED;
+
+ return 0;
+}
+
+/*
+ * Verify returned client principal name in anonymous/referral case
+ */
+
+static krb5_error_code
+check_client_mismatch(krb5_context context,
+ krb5_kdc_rep *rep,
+ krb5_const_principal requested,
+ krb5_const_principal mapped,
+ krb5_keyblock const * key)
+{
+ if (rep->enc_part.flags.anonymous) {
+ if (!krb5_principal_is_anonymous(context, mapped,
+ KRB5_ANON_MATCH_ANY_NONT)) {
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+ N_("Anonymous ticket does not contain anonymous "
+ "principal", ""));
+ return KRB5KRB_AP_ERR_MODIFIED;
+ }
+ } else {
+ if (krb5_principal_compare(context, requested, mapped) == FALSE &&
+ !rep->enc_part.flags.enc_pa_rep) {
+ krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+ N_("Not same client principal returned "
+ "as requested", ""));
+ return KRB5KRB_AP_ERR_MODIFIED;
+ }
+ }
+
+ return 0;
+}
+
+
+static krb5_error_code KRB5_CALLCONV
+decrypt_tkt (krb5_context context,
+ krb5_keyblock *key,
+ krb5_key_usage usage,
+ krb5_const_pointer decrypt_arg,
+ krb5_kdc_rep *dec_rep)
+{
+ krb5_error_code ret;
+ krb5_data data;
+ size_t size;
+ krb5_crypto crypto;
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ return ret;
+
+ ret = krb5_decrypt_EncryptedData (context,
+ crypto,
+ usage,
+ &dec_rep->kdc_rep.enc_part,
+ &data);
+ krb5_crypto_destroy(context, crypto);
+
+ if (ret)
+ return ret;
+
+ ret = decode_EncASRepPart(data.data,
+ data.length,
+ &dec_rep->enc_part,
+ &size);
+ if (ret)
+ ret = decode_EncTGSRepPart(data.data,
+ data.length,
+ &dec_rep->enc_part,
+ &size);
+ krb5_data_free (&data);
+ if (ret) {
+ krb5_set_error_message(context, ret,
+ N_("Failed to decode encpart in ticket", ""));
+ return ret;
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+_krb5_extract_ticket(krb5_context context,
+ krb5_kdc_rep *rep,
+ krb5_creds *creds,
+ krb5_keyblock *key,
+ krb5_const_pointer keyseed,
+ krb5_key_usage key_usage,
+ krb5_addresses *addrs,
+ unsigned nonce,
+ unsigned flags,
+ krb5_data *request,
+ krb5_decrypt_proc decrypt_proc,
+ krb5_const_pointer decryptarg)
+{
+ krb5_error_code ret;
+ krb5_principal tmp_principal;
+ size_t len = 0;
+ time_t tmp_time;
+ krb5_timestamp sec_now;
+
+ /* decrypt */
+
+ if (decrypt_proc == NULL)
+ decrypt_proc = decrypt_tkt;
+
+ ret = (*decrypt_proc)(context, key, key_usage, decryptarg, rep);
+ if (ret)
+ goto out;
+
+ if (rep->enc_part.flags.enc_pa_rep && request) {
+ krb5_crypto crypto = NULL;
+ Checksum cksum;
+ PA_DATA *pa = NULL;
+ int idx = 0;
+
+ _krb5_debug(context, 5, "processing enc-ap-rep");
+
+ if (rep->enc_part.encrypted_pa_data == NULL ||
+ (pa = krb5_find_padata(rep->enc_part.encrypted_pa_data->val,
+ rep->enc_part.encrypted_pa_data->len,
+ KRB5_PADATA_REQ_ENC_PA_REP,
+ &idx)) == NULL)
+ {
+ _krb5_debug(context, 5, "KRB5_PADATA_REQ_ENC_PA_REP missing");
+ ret = KRB5KRB_AP_ERR_MODIFIED;
+ goto out;
+ }
+
+ ret = krb5_crypto_init(context, key, 0, &crypto);
+ if (ret)
+ goto out;
+
+ ret = decode_Checksum(pa->padata_value.data,
+ pa->padata_value.length,
+ &cksum, NULL);
+ if (ret) {
+ krb5_crypto_destroy(context, crypto);
+ goto out;
+ }
+
+ ret = krb5_verify_checksum(context, crypto,
+ KRB5_KU_AS_REQ,
+ request->data, request->length,
+ &cksum);
+ krb5_crypto_destroy(context, crypto);
+ free_Checksum(&cksum);
+ _krb5_debug(context, 5, "enc-ap-rep: %svalid", (ret == 0) ? "" : "in");
+ if (ret)
+ goto out;
+ }
+
+ /* save session key */
+
+ creds->session.keyvalue.length = 0;
+ creds->session.keyvalue.data = NULL;
+ creds->session.keytype = rep->enc_part.key.keytype;
+ ret = krb5_data_copy (&creds->session.keyvalue,
+ rep->enc_part.key.keyvalue.data,
+ rep->enc_part.key.keyvalue.length);
+ if (ret) {
+ krb5_clear_error_message(context);
+ goto out;
+ }
+
+ /* compare client and save */
+ ret = _krb5_principalname2krb5_principal(context,
+ &tmp_principal,
+ rep->kdc_rep.cname,
+ rep->kdc_rep.crealm);
+ if (ret)
+ goto out;
+
+ /* check KDC supported anonymous if it was requested */
+ if (flags & EXTRACT_TICKET_MATCH_ANON) {
+ ret = check_client_anonymous(context,rep,
+ creds->client,
+ tmp_principal,
+ request == NULL); /* is TGS */
+ if (ret) {
+ krb5_free_principal(context, tmp_principal);
+ goto out;
+ }
+ }
+
+ /* check client referral and save principal */
+ if((flags & EXTRACT_TICKET_ALLOW_CNAME_MISMATCH) == 0) {
+ ret = check_client_mismatch(context, rep,
+ creds->client,
+ tmp_principal,
+ &creds->session);
+ if (ret) {
+ krb5_free_principal (context, tmp_principal);
+ goto out;
+ }
+ }
+ krb5_free_principal (context, creds->client);
+ creds->client = tmp_principal;
+
+ /* check server referral and save principal */
+ ret = _krb5_kdcrep2krb5_principal(context, &tmp_principal, &rep->enc_part);
+ if (ret)
+ goto out;
+
+ tmp_principal->nameattrs->peer_realm =
+ calloc(1, sizeof(tmp_principal->nameattrs->peer_realm[0]));
+ if (tmp_principal->nameattrs->peer_realm == NULL) {
+ ret = krb5_enomem(context);
+ goto out;
+ }
+ ret = copy_Realm(&creds->client->realm, tmp_principal->nameattrs->peer_realm);
+ if (ret) goto out;
+
+ if((flags & EXTRACT_TICKET_ALLOW_SERVER_MISMATCH) == 0){
+ ret = check_server_referral(context,
+ rep,
+ flags,
+ creds->server,
+ tmp_principal,
+ &creds->session);
+ if (ret) {
+ krb5_free_principal (context, tmp_principal);
+ goto out;
+ }
+ }
+ krb5_free_principal(context, creds->server);
+ creds->server = tmp_principal;
+
+ /* verify names */
+ if(flags & EXTRACT_TICKET_MATCH_REALM){
+ const char *srealm = krb5_principal_get_realm(context, creds->server);
+ const char *crealm = krb5_principal_get_realm(context, creds->client);
+
+ if (strcmp(rep->enc_part.srealm, srealm) != 0 ||
+ strcmp(rep->enc_part.srealm, crealm) != 0)
+ {
+ ret = KRB5KRB_AP_ERR_MODIFIED;
+ krb5_clear_error_message(context);
+ goto out;
+ }
+ }
+
+ /* compare nonces */
+
+ if (nonce != (unsigned)rep->enc_part.nonce) {
+ ret = KRB5KRB_AP_ERR_MODIFIED;
+ krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+ goto out;
+ }
+
+ /* set kdc-offset */
+
+ krb5_timeofday (context, &sec_now);
+ if (rep->enc_part.flags.initial
+ && (flags & EXTRACT_TICKET_TIMESYNC)
+ && context->kdc_sec_offset == 0
+ && krb5_config_get_bool (context, NULL,
+ "libdefaults",
+ "kdc_timesync",
+ NULL)) {
+ context->kdc_sec_offset = rep->enc_part.authtime - sec_now;
+ krb5_timeofday (context, &sec_now);
+ }
+
+ /* check all times */
+
+ if (rep->enc_part.starttime) {
+ tmp_time = *rep->enc_part.starttime;
+ } else
+ tmp_time = rep->enc_part.authtime;
+
+ if (creds->times.starttime == 0
+ && krb5_time_abs(tmp_time, sec_now) > context->max_skew) {
+ ret = KRB5KRB_AP_ERR_SKEW;
+ krb5_set_error_message (context, ret,
+ N_("time skew (%ld) larger than max (%ld)", ""),
+ (long)krb5_time_abs(tmp_time, sec_now),
+ (long)context->max_skew);
+ goto out;
+ }
+
+ if (creds->times.starttime != 0
+ && tmp_time != creds->times.starttime) {
+ krb5_clear_error_message (context);
+ ret = KRB5KRB_AP_ERR_MODIFIED;
+ goto out;
+ }
+
+ creds->times.starttime = tmp_time;
+
+ if (rep->enc_part.renew_till) {
+ tmp_time = *rep->enc_part.renew_till;
+ } else
+ tmp_time = 0;
+
+ if (creds->times.renew_till != 0
+ && tmp_time > creds->times.renew_till) {
+ krb5_clear_error_message (context);
+ ret = KRB5KRB_AP_ERR_MODIFIED;
+ goto out;
+ }
+
+ creds->times.renew_till = tmp_time;
+
+ creds->times.authtime = rep->enc_part.authtime;
+
+ if (creds->times.endtime != 0
+ && rep->enc_part.endtime > creds->times.endtime) {
+ krb5_clear_error_message (context);
+ ret = KRB5KRB_AP_ERR_MODIFIED;
+ goto out;
+ }
+
+ creds->times.endtime = rep->enc_part.endtime;
+
+ if(rep->enc_part.caddr)
+ krb5_copy_addresses (context, rep->enc_part.caddr, &creds->addresses);
+ else if(addrs)
+ krb5_copy_addresses (context, addrs, &creds->addresses);
+ else {
+ creds->addresses.len = 0;
+ creds->addresses.val = NULL;
+ }
+ creds->flags.b = rep->enc_part.flags;
+
+ creds->authdata.len = 0;
+ creds->authdata.val = NULL;
+
+ /* extract ticket */
+ ASN1_MALLOC_ENCODE(Ticket, creds->ticket.data, creds->ticket.length,
+ &rep->kdc_rep.ticket, &len, ret);
+ if(ret)
+ goto out;
+ if (creds->ticket.length != len)
+ krb5_abortx(context, "internal error in ASN.1 encoder");
+ creds->second_ticket.length = 0;
+ creds->second_ticket.data = NULL;
+
+
+out:
+ memset (rep->enc_part.key.keyvalue.data, 0,
+ rep->enc_part.key.keyvalue.length);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/time.c b/third_party/heimdal/lib/krb5/time.c
new file mode 100644
index 0000000..d0d4af1
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/time.c
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 1997-2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/**
+ * Set the absolute time that the caller knows the kdc has so the
+ * kerberos library can calculate the relative diffrence beteen the
+ * KDC time and local system time.
+ *
+ * @param context Keberos 5 context.
+ * @param sec The applications new of "now" in seconds
+ * @param usec The applications new of "now" in micro seconds
+
+ * @return Kerberos 5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_real_time (krb5_context context,
+ krb5_timestamp sec,
+ int32_t usec)
+{
+ struct timeval tv;
+
+ gettimeofday(&tv, NULL);
+
+ context->kdc_sec_offset = sec - tv.tv_sec;
+
+ /**
+ * If the caller passes in a negative usec, its assumed to be
+ * unknown and the function will use the current time usec.
+ */
+ if (usec >= 0) {
+ context->kdc_usec_offset = usec - tv.tv_usec;
+
+ if (context->kdc_usec_offset < 0) {
+ context->kdc_sec_offset--;
+ context->kdc_usec_offset += 1000000;
+ }
+ } else
+ context->kdc_usec_offset = tv.tv_usec;
+
+ return 0;
+}
+
+/*
+ * return ``corrected'' time in `timeret'.
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_timeofday (krb5_context context,
+ krb5_timestamp *timeret)
+{
+ *timeret = time(NULL) + context->kdc_sec_offset;
+ return 0;
+}
+
+/*
+ * like gettimeofday but with time correction to the KDC
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_us_timeofday (krb5_context context,
+ krb5_timestamp *sec,
+ int32_t *usec)
+{
+ struct timeval tv;
+
+ gettimeofday (&tv, NULL);
+
+ *sec = tv.tv_sec + context->kdc_sec_offset;
+ *usec = tv.tv_usec; /* XXX */
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_format_time(krb5_context context, time_t t,
+ char *s, size_t len, krb5_boolean include_time)
+{
+ struct tm *tm;
+ if(context->log_utc)
+ tm = gmtime (&t);
+ else
+ tm = localtime(&t);
+ if(tm == NULL ||
+ strftime(s, len, include_time ? context->time_fmt : context->date_fmt, tm) == 0)
+ snprintf(s, len, "%ld", (long)t);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_string_to_deltat(const char *string, krb5_deltat *deltat)
+{
+ if((*deltat = parse_time(string, "s")) == -1)
+ return KRB5_DELTAT_BADFORMAT;
+ return 0;
+}
+
+krb5_deltat
+krb5_time_abs(krb5_deltat t1, krb5_deltat t2)
+{
+ krb5_deltat t = t1 - t2;
+ if (t < 0)
+ return -t;
+ return t;
+}
diff --git a/third_party/heimdal/lib/krb5/transited.c b/third_party/heimdal/lib/krb5/transited.c
new file mode 100644
index 0000000..484fd39
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/transited.c
@@ -0,0 +1,699 @@
+/*
+ * Copyright (c) 1997 - 2001, 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/* this is an attempt at one of the most horrible `compression'
+ schemes that has ever been invented; it's so amazingly brain-dead
+ that words can not describe it, and all this just to save a few
+ silly bytes */
+
+struct tr_realm {
+ char *realm;
+ unsigned leading_space:1;
+ unsigned leading_slash:1;
+ unsigned trailing_dot:1;
+ struct tr_realm *next;
+};
+
+static void
+free_realms(struct tr_realm *r)
+{
+ struct tr_realm *p;
+ while(r){
+ p = r;
+ r = r->next;
+ free(p->realm);
+ free(p);
+ }
+}
+
+static int
+make_path(krb5_context context, struct tr_realm *r,
+ const char *from, const char *to)
+{
+ struct tr_realm *tmp;
+ const char *p;
+
+ if(strlen(from) < strlen(to)){
+ const char *str;
+ str = from;
+ from = to;
+ to = str;
+ }
+
+ if(strcmp(from + strlen(from) - strlen(to), to) == 0){
+ p = from;
+ while(1){
+ p = strchr(p, '.');
+ if(p == NULL) {
+ krb5_clear_error_message (context);
+ return KRB5KDC_ERR_POLICY;
+ }
+ p++;
+ if(strcmp(p, to) == 0)
+ break;
+ tmp = calloc(1, sizeof(*tmp));
+ if(tmp == NULL)
+ return krb5_enomem(context);
+ tmp->next = r->next;
+ r->next = tmp;
+ tmp->realm = strdup(p);
+ if(tmp->realm == NULL){
+ r->next = tmp->next;
+ free(tmp);
+ return krb5_enomem(context);
+ }
+ }
+ }else if(strncmp(from, to, strlen(to)) == 0){
+ p = from + strlen(from);
+ while(1){
+ while(p >= from && *p != '/') p--;
+ if(p == from)
+ return KRB5KDC_ERR_POLICY;
+
+ if(strncmp(to, from, p - from) == 0)
+ break;
+ tmp = calloc(1, sizeof(*tmp));
+ if(tmp == NULL)
+ return krb5_enomem(context);
+ tmp->next = r->next;
+ r->next = tmp;
+ tmp->realm = malloc(p - from + 1);
+ if(tmp->realm == NULL){
+ r->next = tmp->next;
+ free(tmp);
+ return krb5_enomem(context);
+ }
+ memcpy(tmp->realm, from, p - from);
+ tmp->realm[p - from] = '\0';
+ p--;
+ }
+ } else {
+ krb5_clear_error_message (context);
+ return KRB5KDC_ERR_POLICY;
+ }
+
+ return 0;
+}
+
+static int
+make_paths(krb5_context context,
+ struct tr_realm *realms, const char *client_realm,
+ const char *server_realm)
+{
+ struct tr_realm *r;
+ int ret;
+ const char *prev_realm = client_realm;
+ const char *next_realm = NULL;
+ for(r = realms; r; r = r->next){
+ /* it *might* be that you can have more than one empty
+ component in a row, at least that's how I interpret the
+ "," exception in 1510 */
+ if(r->realm[0] == '\0'){
+ while(r->next && r->next->realm[0] == '\0')
+ r = r->next;
+ if(r->next)
+ next_realm = r->next->realm;
+ else
+ next_realm = server_realm;
+ ret = make_path(context, r, prev_realm, next_realm);
+ if(ret){
+ free_realms(realms);
+ return ret;
+ }
+ }
+ prev_realm = r->realm;
+ }
+ return 0;
+}
+
+static int
+expand_realms(krb5_context context,
+ struct tr_realm *realms, const char *client_realm)
+{
+ struct tr_realm *r;
+ const char *prev_realm = NULL;
+ for(r = realms; r; r = r->next){
+ if(r->trailing_dot){
+ char *tmp;
+ size_t len;
+
+ if(prev_realm == NULL)
+ prev_realm = client_realm;
+
+ len = strlen(r->realm) + strlen(prev_realm) + 1;
+
+ tmp = realloc(r->realm, len);
+ if(tmp == NULL){
+ free_realms(realms);
+ return krb5_enomem(context);
+ }
+ r->realm = tmp;
+ strlcat(r->realm, prev_realm, len);
+ }else if(r->leading_slash && !r->leading_space && prev_realm){
+ /* yet another exception: if you use x500-names, the
+ leading realm doesn't have to be "quoted" with a space */
+ char *tmp;
+ size_t len = strlen(r->realm) + strlen(prev_realm) + 1;
+
+ tmp = malloc(len);
+ if(tmp == NULL){
+ free_realms(realms);
+ return krb5_enomem(context);
+ }
+ strlcpy(tmp, prev_realm, len);
+ strlcat(tmp, r->realm, len);
+ free(r->realm);
+ r->realm = tmp;
+ }
+ prev_realm = r->realm;
+ }
+ return 0;
+}
+
+static struct tr_realm *
+make_realm(char *realm)
+{
+ struct tr_realm *r;
+ char *p, *q;
+ int quote = 0;
+ r = calloc(1, sizeof(*r));
+ if(r == NULL){
+ free(realm);
+ return NULL;
+ }
+ r->realm = realm;
+ for(p = q = r->realm; *p; p++){
+ if(p == r->realm && *p == ' '){
+ r->leading_space = 1;
+ continue;
+ }
+ if(q == r->realm && *p == '/')
+ r->leading_slash = 1;
+ if(quote){
+ *q++ = *p;
+ quote = 0;
+ continue;
+ }
+ if(*p == '\\'){
+ quote = 1;
+ continue;
+ }
+ if(p[0] == '.' && p[1] == '\0')
+ r->trailing_dot = 1;
+ *q++ = *p;
+ }
+ *q = '\0';
+ return r;
+}
+
+static struct tr_realm*
+append_realm(struct tr_realm *head, struct tr_realm *r)
+{
+ struct tr_realm *p;
+ if(head == NULL){
+ r->next = NULL;
+ return r;
+ }
+ p = head;
+ while(p->next) p = p->next;
+ p->next = r;
+ return head;
+}
+
+static int
+decode_realms(krb5_context context,
+ const char *tr, int length, struct tr_realm **realms)
+{
+ struct tr_realm *r = NULL;
+
+ char *tmp;
+ int quote = 0;
+ const char *start = tr;
+ int i;
+
+ for(i = 0; i < length; i++){
+ if(quote){
+ quote = 0;
+ continue;
+ }
+ if(tr[i] == '\\'){
+ quote = 1;
+ continue;
+ }
+ if(tr[i] == ','){
+ tmp = malloc(tr + i - start + 1);
+ if(tmp == NULL) {
+ free_realms(*realms);
+ *realms = NULL;
+ return krb5_enomem(context);
+ }
+ memcpy(tmp, start, tr + i - start);
+ tmp[tr + i - start] = '\0';
+ r = make_realm(tmp);
+ if(r == NULL){
+ free_realms(*realms);
+ *realms = NULL;
+ return krb5_enomem(context);
+ }
+ *realms = append_realm(*realms, r);
+ start = tr + i + 1;
+ }
+ }
+ tmp = malloc(tr + i - start + 1);
+ if(tmp == NULL){
+ free_realms(*realms);
+ *realms = NULL;
+ return krb5_enomem(context);
+ }
+ memcpy(tmp, start, tr + i - start);
+ tmp[tr + i - start] = '\0';
+ r = make_realm(tmp);
+ if(r == NULL){
+ free_realms(*realms);
+ *realms = NULL;
+ return krb5_enomem(context);
+ }
+ *realms = append_realm(*realms, r);
+
+ return 0;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_domain_x500_decode(krb5_context context,
+ krb5_data tr, char ***realms, unsigned int *num_realms,
+ const char *client_realm, const char *server_realm)
+{
+ struct tr_realm *r = NULL;
+ struct tr_realm *p, **q;
+ int ret;
+
+ if(tr.length == 0) {
+ *realms = NULL;
+ *num_realms = 0;
+ return 0;
+ }
+
+ /* split string in components */
+ ret = decode_realms(context, tr.data, tr.length, &r);
+ if(ret)
+ return ret;
+
+ /* apply prefix rule */
+ ret = expand_realms(context, r, client_realm);
+ if(ret)
+ return ret;
+
+ ret = make_paths(context, r, client_realm, server_realm);
+ if(ret)
+ return ret;
+
+ /* remove empty components and count realms */
+ *num_realms = 0;
+ for(q = &r; *q; ){
+ if((*q)->realm[0] == '\0'){
+ p = *q;
+ *q = (*q)->next;
+ free(p->realm);
+ free(p);
+ }else{
+ q = &(*q)->next;
+ (*num_realms)++;
+ }
+ }
+ if (*num_realms + 1 > UINT_MAX/sizeof(**realms))
+ return ERANGE;
+
+ {
+ char **R;
+ R = malloc((*num_realms + 1) * sizeof(*R));
+ *realms = R;
+ while(r){
+ *R++ = r->realm;
+ p = r->next;
+ free(r);
+ r = p;
+ }
+ if (*realms == NULL)
+ return krb5_enomem(context);
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_domain_x500_encode(char **realms, unsigned int num_realms,
+ krb5_data *encoding)
+{
+ char *s = NULL;
+ int len = 0;
+ unsigned int i;
+ krb5_data_zero(encoding);
+ if (num_realms == 0)
+ return 0;
+ for(i = 0; i < num_realms; i++){
+ len += strlen(realms[i]);
+ if(realms[i][0] == '/')
+ len++;
+ }
+ len += num_realms - 1;
+ s = malloc(len + 1);
+ if (s == NULL)
+ return ENOMEM;
+ *s = '\0';
+ for(i = 0; i < num_realms; i++){
+ if(i)
+ strlcat(s, ",", len + 1);
+ if(realms[i][0] == '/')
+ strlcat(s, " ", len + 1);
+ strlcat(s, realms[i], len + 1);
+ }
+ encoding->data = s;
+ encoding->length = strlen(s);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+_krb5_free_capath(krb5_context context, char **capath)
+{
+ char **s;
+
+ for (s = capath; s && *s; ++s)
+ free(*s);
+ free(capath);
+}
+
+struct hier_iter {
+ const char *local_realm;
+ const char *server_realm;
+ const char *lr; /* Pointer into tail of local realm */
+ const char *sr; /* Pointer into tail of server realm */
+ size_t llen; /* Length of local_realm */
+ size_t slen; /* Length of server_realm */
+ size_t len; /* Length of common suffix */
+ size_t num; /* Path element count */
+};
+
+/*
+ * Step up from local_realm to common suffix, or else down to server_realm.
+ */
+static const char *
+hier_next(struct hier_iter *state)
+{
+ const char *lr = state->lr;
+ const char *sr = state->sr;
+ const char *lsuffix = state->local_realm + state->llen - state->len;
+ const char *server_realm = state->server_realm;
+
+ if (lr != NULL) {
+ while (lr < lsuffix)
+ if (*lr++ == '.')
+ return state->lr = lr;
+ state->lr = NULL;
+ }
+ if (sr != NULL) {
+ while (--sr >= server_realm)
+ if (sr == server_realm || sr[-1] == '.')
+ return state->sr = sr;
+ state->sr = NULL;
+ }
+ return NULL;
+}
+
+static void
+hier_init(struct hier_iter *state, const char *local_realm, const char *server_realm)
+{
+ size_t llen;
+ size_t slen;
+ size_t len = 0;
+ const char *lr;
+ const char *sr;
+
+ state->local_realm = local_realm;
+ state->server_realm = server_realm;
+ state->llen = llen = strlen(local_realm);
+ state->slen = slen = strlen(server_realm);
+ state->len = 0;
+ state->num = 0;
+
+ if (slen == 0 || llen == 0)
+ return;
+
+ /* Find first difference from the back */
+ for (lr = local_realm + llen, sr = server_realm + slen;
+ lr != local_realm && sr != server_realm;
+ --lr, --sr) {
+ if (lr[-1] != sr[-1])
+ break;
+ if (lr[-1] == '.')
+ len = llen - (lr - local_realm);
+ }
+
+ /* Nothing in common? */
+ if (*lr == '\0')
+ return;
+
+ /* Everything in common? */
+ if (llen == slen && lr == local_realm)
+ return;
+
+ /* Is one realm is a suffix of the other? */
+ if ((llen < slen && lr == local_realm && sr[-1] == '.') ||
+ (llen > slen && sr == server_realm && lr[-1] == '.'))
+ len = llen - (lr - local_realm);
+
+ state->len = len;
+ /* `lr` starts at local realm and walks up the tree to common suffix */
+ state->lr = local_realm;
+ /* `sr` starts at common suffix in server realm and walks down the tree */
+ state->sr = server_realm + slen - len;
+
+ /* Count elements and reset */
+ while (hier_next(state) != NULL)
+ ++state->num;
+ state->lr = local_realm;
+ state->sr = server_realm + slen - len;
+}
+
+/*
+ * Find a referral path from client_realm to server_realm via local_realm.
+ * Either via [capaths] or hierarchicaly.
+ */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_find_capath(krb5_context context,
+ const char *client_realm,
+ const char *local_realm,
+ const char *server_realm,
+ krb5_boolean use_hierarchical,
+ char ***rpath,
+ size_t *npath)
+{
+ char **confpath;
+ char **capath;
+ struct hier_iter hier_state;
+ char **rp;
+ const char *r;
+
+ *rpath = NULL;
+ *npath = 0;
+
+ confpath = krb5_config_get_strings(context, NULL, "capaths",
+ client_realm, server_realm, NULL);
+ if (confpath == NULL)
+ confpath = krb5_config_get_strings(context, NULL, "capaths",
+ local_realm, server_realm, NULL);
+ /*
+ * With a [capaths] setting from the client to the server we look for our
+ * own realm in the list. If our own realm is not present, we return the
+ * full list. Otherwise, we return our realm's successors, or possibly
+ * NULL. Ignoring a [capaths] settings risks loops plus would violate
+ * explicit policy and the principle of least surpise.
+ */
+ if (confpath != NULL) {
+ char **start = confpath;
+ size_t i;
+ size_t n;
+
+ for (rp = start; *rp; rp++)
+ if (strcmp(*rp, local_realm) == 0)
+ start = rp+1;
+ n = rp - start;
+
+ if (n == 0) {
+ krb5_config_free_strings(confpath);
+ return 0;
+ }
+
+ capath = calloc(n + 1, sizeof(*capath));
+ if (capath == NULL) {
+ krb5_config_free_strings(confpath);
+ return krb5_enomem(context);
+ }
+
+ for (i = 0, rp = start; *rp; rp++) {
+ if ((capath[i++] = strdup(*rp)) == NULL) {
+ _krb5_free_capath(context, capath);
+ krb5_config_free_strings(confpath);
+ return krb5_enomem(context);
+ }
+ }
+ krb5_config_free_strings(confpath);
+ capath[i] = NULL;
+ *rpath = capath;
+ *npath = n;
+ return 0;
+ }
+
+ /* The use_hierarchical flag makes hierarchical path lookup unconditional */
+ if (! use_hierarchical &&
+ ! krb5_config_get_bool_default(context, NULL, TRUE, "libdefaults",
+ "allow_hierarchical_capaths", NULL))
+ return 0;
+
+ /*
+ * When validating transit paths, local_realm == client_realm. Otherwise,
+ * with hierarchical referrals, they may differ, and we may be building a
+ * path forward from our own realm!
+ */
+ hier_init(&hier_state, local_realm, server_realm);
+ if (hier_state.num == 0)
+ return 0;
+
+ rp = capath = calloc(hier_state.num + 1, sizeof(*capath));
+ if (capath == NULL)
+ return krb5_enomem(context);
+ while ((r = hier_next(&hier_state)) != NULL) {
+ if ((*rp++ = strdup(r)) == NULL) {
+ _krb5_free_capath(context, capath);
+ return krb5_enomem(context);
+ }
+ }
+
+ *rp = NULL;
+ *rpath = capath;
+ *npath = hier_state.num;
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_check_transited(krb5_context context,
+ krb5_const_realm client_realm,
+ krb5_const_realm server_realm,
+ krb5_realm *realms,
+ unsigned int num_realms,
+ int *bad_realm)
+{
+ krb5_error_code ret = 0;
+ char **capath = NULL;
+ size_t num_capath = 0;
+ size_t i = 0;
+ size_t j = 0;
+
+ /* In transit checks hierarchical capaths are optional */
+ ret = _krb5_find_capath(context, client_realm, client_realm, server_realm,
+ FALSE, &capath, &num_capath);
+ if (ret)
+ return ret;
+
+ for (i = 0; i < num_realms; i++) {
+ for (j = 0; j < num_capath && capath[j]; ++j) {
+ /* `capath[j]' can't be NULL, but compilers be dumb */
+ if (strcmp(realms[i], capath[j]) == 0)
+ break;
+ }
+ if (j == num_capath || !capath[j]) {
+ _krb5_free_capath(context, capath);
+ krb5_set_error_message (context, KRB5KRB_AP_ERR_ILL_CR_TKT,
+ N_("no transit allowed "
+ "through realm %s from %s to %s", ""),
+ realms[i], client_realm, server_realm);
+ if (bad_realm)
+ *bad_realm = i;
+ return KRB5KRB_AP_ERR_ILL_CR_TKT;
+ }
+ }
+
+ _krb5_free_capath(context, capath);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_check_transited_realms(krb5_context context,
+ const char *const *realms,
+ unsigned int num_realms,
+ int *bad_realm)
+{
+ size_t i;
+ int ret = 0;
+ char **bad_realms = krb5_config_get_strings(context, NULL,
+ "libdefaults",
+ "transited_realms_reject",
+ NULL);
+ if(bad_realms == NULL)
+ return 0;
+
+ for(i = 0; i < num_realms; i++) {
+ char **p;
+ for(p = bad_realms; *p; p++)
+ if(strcmp(*p, realms[i]) == 0) {
+ ret = KRB5KRB_AP_ERR_ILL_CR_TKT;
+ krb5_set_error_message (context, ret,
+ N_("no transit allowed "
+ "through realm %s", ""),
+ *p);
+ if(bad_realm)
+ *bad_realm = i;
+ break;
+ }
+ }
+ krb5_config_free_strings(bad_realms);
+ return ret;
+}
+
+#if 0
+int
+main(int argc, char **argv)
+{
+ krb5_data x;
+ char **r;
+ int num, i;
+ x.data = argv[1];
+ x.length = strlen(x.data);
+ if(domain_expand(x, &r, &num, argv[2], argv[3]))
+ exit(1);
+ for(i = 0; i < num; i++)
+ printf("%s\n", r[i]);
+ return 0;
+}
+#endif
diff --git a/third_party/heimdal/lib/krb5/verify_init.c b/third_party/heimdal/lib/krb5/verify_init.c
new file mode 100644
index 0000000..128502f
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/verify_init.c
@@ -0,0 +1,246 @@
+/*
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_verify_init_creds_opt_init(krb5_verify_init_creds_opt *options)
+{
+ memset (options, 0, sizeof(*options));
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_verify_init_creds_opt_set_ap_req_nofail(krb5_verify_init_creds_opt *options,
+ int ap_req_nofail)
+{
+ options->flags |= KRB5_VERIFY_INIT_CREDS_OPT_AP_REQ_NOFAIL;
+ options->ap_req_nofail = ap_req_nofail;
+}
+
+/*
+ *
+ */
+
+static krb5_boolean
+fail_verify_is_ok (krb5_context context,
+ krb5_verify_init_creds_opt *options)
+{
+
+ if (options && (options->flags & KRB5_VERIFY_INIT_CREDS_OPT_AP_REQ_NOFAIL)
+ && options->ap_req_nofail != 0)
+ return FALSE;
+
+ if (krb5_config_get_bool(context,
+ NULL,
+ "libdefaults",
+ "verify_ap_req_nofail",
+ NULL))
+ return FALSE;
+
+ return TRUE;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verify_init_creds(krb5_context context,
+ krb5_creds *creds,
+ krb5_principal ap_req_server,
+ krb5_keytab ap_req_keytab,
+ krb5_ccache *ccache,
+ krb5_verify_init_creds_opt *options)
+{
+ krb5_error_code ret;
+ krb5_data req;
+ krb5_ccache local_ccache = NULL;
+ krb5_creds *new_creds = NULL;
+ krb5_auth_context auth_context = NULL;
+ krb5_principal server = NULL;
+ krb5_keytab keytab = NULL;
+
+ krb5_data_zero (&req);
+
+ if (ap_req_server == NULL) {
+ char local_hostname[MAXHOSTNAMELEN];
+
+ if (gethostname (local_hostname, sizeof(local_hostname)) < 0) {
+ ret = errno;
+ krb5_set_error_message (context, ret, "gethostname: %s",
+ strerror(ret));
+ return ret;
+ }
+
+ ret = krb5_sname_to_principal (context,
+ local_hostname,
+ "host",
+ KRB5_NT_SRV_HST,
+ &server);
+ if (ret)
+ goto cleanup;
+ } else
+ server = ap_req_server;
+
+ if (ap_req_keytab == NULL) {
+ ret = krb5_kt_default (context, &keytab);
+ if (ret)
+ goto cleanup;
+ } else
+ keytab = ap_req_keytab;
+
+ if (ccache && *ccache)
+ local_ccache = *ccache;
+ else {
+ ret = krb5_cc_new_unique(context, krb5_cc_type_memory,
+ NULL, &local_ccache);
+ if (ret)
+ goto cleanup;
+ ret = krb5_cc_initialize (context,
+ local_ccache,
+ creds->client);
+ if (ret)
+ goto cleanup;
+ ret = krb5_cc_store_cred (context,
+ local_ccache,
+ creds);
+ if (ret)
+ goto cleanup;
+ }
+
+ if (!krb5_principal_compare (context, server, creds->server)) {
+ krb5_creds match_cred;
+
+ memset (&match_cred, 0, sizeof(match_cred));
+
+ match_cred.client = creds->client;
+ match_cred.server = server;
+
+ ret = krb5_get_credentials (context,
+ 0,
+ local_ccache,
+ &match_cred,
+ &new_creds);
+ if (ret) {
+ if (fail_verify_is_ok (context, options))
+ ret = 0;
+ goto cleanup;
+ }
+ creds = new_creds;
+ }
+
+ ret = krb5_mk_req_extended (context,
+ &auth_context,
+ 0,
+ NULL,
+ creds,
+ &req);
+
+ krb5_auth_con_free (context, auth_context);
+ auth_context = NULL;
+
+ if (ret)
+ goto cleanup;
+
+ ret = krb5_rd_req (context,
+ &auth_context,
+ &req,
+ server,
+ keytab,
+ 0,
+ NULL);
+
+ if (ret == KRB5_KT_NOTFOUND && fail_verify_is_ok (context, options))
+ ret = 0;
+cleanup:
+ if (auth_context)
+ krb5_auth_con_free (context, auth_context);
+ krb5_data_free (&req);
+ if (new_creds != NULL)
+ krb5_free_creds (context, new_creds);
+ if (ap_req_server == NULL && server)
+ krb5_free_principal (context, server);
+ if (ap_req_keytab == NULL && keytab)
+ krb5_kt_close (context, keytab);
+ if (local_ccache != NULL
+ &&
+ (ccache == NULL
+ || (ret != 0 && *ccache == NULL)))
+ krb5_cc_destroy (context, local_ccache);
+
+ if (ret == 0 && ccache != NULL && *ccache == NULL)
+ *ccache = local_ccache;
+
+ return ret;
+}
+
+/**
+ * Validate the newly fetch credential, see also krb5_verify_init_creds().
+ *
+ * @param context a Kerberos 5 context
+ * @param creds the credentials to verify
+ * @param client the client name to match up
+ * @param ccache the credential cache to use
+ * @param service a service name to use, used with
+ * krb5_sname_to_principal() to build a hostname to use to
+ * verify.
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_validated_creds(krb5_context context,
+ krb5_creds *creds,
+ krb5_principal client,
+ krb5_ccache ccache,
+ char *service)
+{
+ krb5_verify_init_creds_opt vopt;
+ krb5_principal server;
+ krb5_error_code ret;
+
+ if (krb5_principal_compare(context, creds->client, client) != TRUE) {
+ krb5_set_error_message(context, KRB5_PRINC_NOMATCH,
+ N_("Validation credentials and client "
+ "doesn't match", ""));
+ return KRB5_PRINC_NOMATCH;
+ }
+
+ ret = krb5_sname_to_principal (context, NULL, service,
+ KRB5_NT_SRV_HST, &server);
+ if(ret)
+ return ret;
+
+ krb5_verify_init_creds_opt_init(&vopt);
+
+ ret = krb5_verify_init_creds(context, creds, server, NULL, NULL, &vopt);
+ krb5_free_principal(context, server);
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/krb5/verify_krb5_conf-version.rc b/third_party/heimdal/lib/krb5/verify_krb5_conf-version.rc
new file mode 100644
index 0000000..f7d90df
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/verify_krb5_conf-version.rc
@@ -0,0 +1,36 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#define RC_FILE_TYPE VFT_APP
+#define RC_FILE_DESC_0409 "Krb5.conf Verification Tool"
+#define RC_FILE_ORIG_0409 "verify_krb5_conf.exe"
+
+#include "../../windows/version.rc"
diff --git a/third_party/heimdal/lib/krb5/verify_krb5_conf.8 b/third_party/heimdal/lib/krb5/verify_krb5_conf.8
new file mode 100644
index 0000000..fc580fe
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/verify_krb5_conf.8
@@ -0,0 +1,95 @@
+.\" Copyright (c) 2000 - 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.Dd December 8, 2004
+.Dt VERIFY_KRB5_CONF 8
+.Os HEIMDAL
+.Sh NAME
+.Nm verify_krb5_conf
+.Nd checks krb5.conf for obvious errors
+.Sh SYNOPSIS
+.Nm
+.Ar [config-file]
+.Sh DESCRIPTION
+.Nm
+reads the configuration file
+.Pa krb5.conf ,
+or the file given on the command line,
+parses it, checking verifying that the syntax is not correctly wrong.
+.Pp
+If the file is syntactically correct,
+.Nm
+tries to verify that the contents of the file is of relevant nature.
+.Sh ENVIRONMENT
+.Ev KRB5_CONFIG
+points to the configuration file to read.
+.Sh FILES
+.Bl -tag -width /etc/krb5.conf -compact
+.It Pa /etc/krb5.conf
+Kerberos 5 configuration file
+.El
+.Sh DIAGNOSTICS
+Possible output from
+.Nm
+include:
+.Bl -tag -width "FpathF"
+.It "<path>: failed to parse <something> as size/time/number/boolean"
+Usually means that <something> is misspelled, or that it contains
+weird characters. The parsing done by
+.Nm
+is more strict than the one performed by libkrb5, so strings that
+work in real life might be reported as bad.
+.It "<path>: host not found (<hostname>)"
+Means that <path> is supposed to point to a host, but it can't be
+recognised as one.
+.It <path>: unknown or wrong type
+Means that <path> is either a string when it should be a list, vice
+versa, or just that
+.Nm
+is confused.
+.It <path>: unknown entry
+Means that <string> is not known by
+.Nm .
+.El
+.Sh SEE ALSO
+.Xr krb5.conf 5
+.Sh BUGS
+Since each application can put almost anything in the config file,
+it's hard to come up with a watertight verification process. Most of
+the default settings are sanity checked, but this does not mean that
+every problem is discovered, or that everything that is reported as a
+possible problem actually is one. This tool should thus be used with
+some care.
+.Pp
+It should warn about obsolete data, or bad practice, but currently
+doesn't.
diff --git a/third_party/heimdal/lib/krb5/verify_krb5_conf.c b/third_party/heimdal/lib/krb5/verify_krb5_conf.c
new file mode 100644
index 0000000..c258a2b
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/verify_krb5_conf.c
@@ -0,0 +1,795 @@
+/*
+ * Copyright (c) 1999 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+#include <getarg.h>
+#include <parse_bytes.h>
+#include <err.h>
+
+/* verify krb5.conf */
+static int dumpconfig_flag = 0;
+static int version_flag = 0;
+static int help_flag = 0;
+static int warn_mit_syntax_flag = 0;
+
+static struct getargs args[] = {
+ {"dumpconfig", 0, arg_flag, &dumpconfig_flag,
+ "show the parsed config files", NULL },
+ {"warn-mit-syntax", 0, arg_flag, &warn_mit_syntax_flag,
+ "show the parsed config files", NULL },
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "[config-file]");
+ exit (ret);
+}
+
+static int
+check_bytes(krb5_context context, const char *path, char *data)
+{
+ if(parse_bytes(data, NULL) == -1) {
+ krb5_warnx(context, "%s: failed to parse \"%s\" as size", path, data);
+ return 1;
+ }
+ return 0;
+}
+
+static int
+check_time(krb5_context context, const char *path, char *data)
+{
+ if(parse_time(data, NULL) == -1) {
+ krb5_warnx(context, "%s: failed to parse \"%s\" as time", path, data);
+ return 1;
+ }
+ return 0;
+}
+
+static int
+check_numeric(krb5_context context, const char *path, char *data)
+{
+ long v;
+ char *end;
+ v = strtol(data, &end, 0);
+
+ if ((v == LONG_MIN || v == LONG_MAX) && errno != 0) {
+ krb5_warnx(context, "%s: over/under flow for \"%s\"",
+ path, data);
+ return 1;
+ }
+ if(*end != '\0') {
+ krb5_warnx(context, "%s: failed to parse \"%s\" as a number",
+ path, data);
+ return 1;
+ }
+ return 0;
+}
+
+static int
+check_boolean(krb5_context context, const char *path, char *data)
+{
+ long int v;
+ char *end;
+ if(strcasecmp(data, "yes") == 0 ||
+ strcasecmp(data, "true") == 0 ||
+ strcasecmp(data, "no") == 0 ||
+ strcasecmp(data, "false") == 0)
+ return 0;
+ v = strtol(data, &end, 0);
+ if(*end != '\0') {
+ krb5_warnx(context, "%s: failed to parse \"%s\" as a boolean",
+ path, data);
+ return 1;
+ }
+ if(v != 0 && v != 1)
+ krb5_warnx(context, "%s: numeric value \"%s\" is treated as \"true\"",
+ path, data);
+ return 0;
+}
+
+static int
+check_524(krb5_context context, const char *path, char *data)
+{
+ if(strcasecmp(data, "yes") == 0 ||
+ strcasecmp(data, "no") == 0 ||
+ strcasecmp(data, "2b") == 0 ||
+ strcasecmp(data, "local") == 0)
+ return 0;
+
+ krb5_warnx(context, "%s: didn't contain a valid option `%s'",
+ path, data);
+ return 1;
+}
+
+static int
+check_host(krb5_context context, const char *path, char *data)
+{
+ int ret;
+ char hostname[128];
+ const char *p = data;
+ struct addrinfo hints;
+ char service[32];
+ int defport;
+ struct addrinfo *ai;
+
+ hints.ai_flags = 0;
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = 0;
+ hints.ai_protocol = 0;
+
+ hints.ai_addrlen = 0;
+ hints.ai_canonname = NULL;
+ hints.ai_addr = NULL;
+ hints.ai_next = NULL;
+
+ /* XXX data could be a list of hosts that this code can't handle */
+ /* XXX copied from krbhst.c */
+ if (strncmp(p, "http://", 7) == 0){
+ p += 7;
+ hints.ai_socktype = SOCK_STREAM;
+ strlcpy(service, "http", sizeof(service));
+ defport = 80;
+ } else if (strncmp(p, "http/", 5) == 0) {
+ p += 5;
+ hints.ai_socktype = SOCK_STREAM;
+ strlcpy(service, "http", sizeof(service));
+ defport = 80;
+ } else if (strncmp(p, "tcp/", 4) == 0){
+ p += 4;
+ hints.ai_socktype = SOCK_STREAM;
+ strlcpy(service, "kerberos", sizeof(service));
+ defport = 88;
+ } else if (strncmp(p, "udp/", 4) == 0) {
+ p += 4;
+ hints.ai_socktype = SOCK_DGRAM;
+ strlcpy(service, "kerberos", sizeof(service));
+ defport = 88;
+ } else {
+ hints.ai_socktype = SOCK_DGRAM;
+ strlcpy(service, "kerberos", sizeof(service));
+ defport = 88;
+ }
+ if (strsep_copy(&p, ":", hostname, sizeof(hostname)) < 0) {
+ return 1;
+ }
+ hostname[strcspn(hostname, "/")] = '\0';
+ if (p != NULL) {
+ char *end;
+ int tmp = strtol(p, &end, 0);
+ if (end == p) {
+ krb5_warnx(context, "%s: failed to parse port number in %s",
+ path, data);
+ return 1;
+ }
+ defport = tmp;
+ snprintf(service, sizeof(service), "%u", defport);
+ }
+ ret = getaddrinfo(hostname, service, &hints, &ai);
+ if (ret == EAI_SERVICE && !isdigit((unsigned char)service[0])) {
+ snprintf(service, sizeof(service), "%u", defport);
+ ret = getaddrinfo(hostname, service, &hints, &ai);
+ }
+ if (ret != 0) {
+ krb5_warnx(context, "%s: %s (%s)", path, gai_strerror(ret), hostname);
+ return 1;
+ }
+ freeaddrinfo(ai);
+ return 0;
+}
+
+static int
+check_directory(krb5_context context, const char *path, char *data)
+{
+ DIR *d = opendir(data);
+ if (d == NULL) {
+ krb5_warn(context, errno, "%s: could not open directory `%s'",
+ path, data);
+ return 1;
+ }
+
+ closedir(d);
+ return 0;
+}
+
+static int
+mit_entry(krb5_context context, const char *path, char *data)
+{
+ if (warn_mit_syntax_flag)
+ krb5_warnx(context, "%s is only used by MIT Kerberos", path);
+ return 0;
+}
+
+struct s2i {
+ const char *s;
+ int val;
+};
+
+#define L(X) { #X, LOG_ ## X }
+
+static struct s2i syslogvals[] = {
+ /* severity */
+ L(EMERG),
+ L(ALERT),
+ L(CRIT),
+ L(ERR),
+ L(WARNING),
+ L(NOTICE),
+ L(INFO),
+ L(DEBUG),
+ /* facility */
+ L(AUTH),
+#ifdef LOG_AUTHPRIV
+ L(AUTHPRIV),
+#endif
+#ifdef LOG_CRON
+ L(CRON),
+#endif
+ L(DAEMON),
+#ifdef LOG_FTP
+ L(FTP),
+#endif
+ L(KERN),
+ L(LPR),
+ L(MAIL),
+#ifdef LOG_NEWS
+ L(NEWS),
+#endif
+ L(SYSLOG),
+ L(USER),
+#ifdef LOG_UUCP
+ L(UUCP),
+#endif
+ L(LOCAL0),
+ L(LOCAL1),
+ L(LOCAL2),
+ L(LOCAL3),
+ L(LOCAL4),
+ L(LOCAL5),
+ L(LOCAL6),
+ L(LOCAL7),
+ { NULL, -1 }
+};
+
+static int
+find_value(const char *s, struct s2i *table)
+{
+ while (table->s && strcasecmp(table->s, s) != 0)
+ table++;
+ return table->val;
+}
+
+static int
+check_log(krb5_context context, const char *path, char *data)
+{
+ /* XXX sync with log.c */
+ int min = 0, max = -1, n;
+ char c;
+ const char *p = data;
+#ifdef _WIN32
+ const char *q;
+#endif
+
+ n = sscanf(p, "%d%c%d/", &min, &c, &max);
+ if(n == 2){
+ if(ISPATHSEP(c)) {
+ if(min < 0){
+ max = -min;
+ min = 0;
+ }else{
+ max = min;
+ }
+ }
+ }
+ if(n){
+#ifdef _WIN32
+ q = strrchr(p, '\\');
+ if (q != NULL)
+ p = q;
+ else
+#endif
+ p = strchr(p, '/');
+ if(p == NULL) {
+ krb5_warnx(context, "%s: failed to parse \"%s\"", path, data);
+ return 1;
+ }
+ p++;
+ }
+ if(strcmp(p, "STDERR") == 0 ||
+ strcmp(p, "CONSOLE") == 0 ||
+ (strncmp(p, "FILE", 4) == 0 && (p[4] == ':' || p[4] == '=')) ||
+ (strncmp(p, "DEVICE", 6) == 0 && p[6] == '='))
+ return 0;
+ if(strncmp(p, "SYSLOG", 6) == 0){
+ int ret = 0;
+ char severity[128] = "";
+ char facility[128] = "";
+ p += 6;
+ if(*p != '\0')
+ p++;
+ if(strsep_copy(&p, ":", severity, sizeof(severity)) != -1)
+ strsep_copy(&p, ":", facility, sizeof(facility));
+ if(*severity == '\0')
+ strlcpy(severity, "ERR", sizeof(severity));
+ if(*facility == '\0')
+ strlcpy(facility, "AUTH", sizeof(facility));
+ if(find_value(facility, syslogvals) == -1) {
+ krb5_warnx(context, "%s: unknown syslog facility \"%s\"",
+ path, facility);
+ ret++;
+ }
+ if(find_value(severity, syslogvals) == -1) {
+ krb5_warnx(context, "%s: unknown syslog severity \"%s\"",
+ path, severity);
+ ret++;
+ }
+ return ret;
+ }else{
+ krb5_warnx(context, "%s: unknown log type: \"%s\"", path, data);
+ return 1;
+ }
+}
+
+typedef int (*check_func_t)(krb5_context, const char*, char*);
+struct entry {
+ const char *name;
+ int type;
+ void *check_data;
+ int deprecated;
+};
+
+struct entry all_strings[] = {
+ { "", krb5_config_string, NULL, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+struct entry all_boolean[] = {
+ { "", krb5_config_string, check_boolean, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+
+struct entry v4_name_convert_entries[] = {
+ { "host", krb5_config_list, all_strings, 0 },
+ { "plain", krb5_config_list, all_strings, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+struct entry libdefaults_entries[] = {
+ { "accept_null_addresses", krb5_config_string, check_boolean, 0 },
+ { "allow_weak_crypto", krb5_config_string, check_boolean, 0 },
+ { "capath", krb5_config_list, all_strings, 1 },
+ { "ccapi_library", krb5_config_string, NULL, 0 },
+ { "check_pac", krb5_config_string, check_boolean, 0 },
+ { "check-rd-req-server", krb5_config_string, check_boolean, 0 },
+ { "clockskew", krb5_config_string, check_time, 0 },
+ { "date_format", krb5_config_string, NULL, 0 },
+ { "default_as_etypes", krb5_config_string, NULL, 0 },
+ { "default_ccache_name", krb5_config_string, NULL, 0 },
+ { "default_client_keytab_name", krb5_config_string, NULL, 0 },
+ { "default_cc_name", krb5_config_string, NULL, 0 },
+ { "default_cc_type", krb5_config_string, NULL, 0 },
+ { "default_cc_collection", krb5_config_string, NULL, 0 },
+ { "default_etypes", krb5_config_string, NULL, 0 },
+ { "default_etypes_des", krb5_config_string, NULL, 0 },
+ { "default_keytab_modify_name", krb5_config_string, NULL, 0 },
+ { "default_keytab_name", krb5_config_string, NULL, 0 },
+ { "default_keytab_modify_name", krb5_config_string, NULL, 0 },
+ { "default_realm", krb5_config_string, NULL, 0 },
+ { "default_tgs_etypes", krb5_config_string, NULL, 0 },
+ { "dns_canonicalize_hostname", krb5_config_string, check_boolean, 0 },
+ { "dns_proxy", krb5_config_string, NULL, 0 },
+ { "dns_lookup_kdc", krb5_config_string, check_boolean, 0 },
+ { "dns_lookup_realm", krb5_config_string, check_boolean, 0 },
+ { "dns_lookup_realm_labels", krb5_config_string, NULL, 0 },
+ { "egd_socket", krb5_config_string, NULL, 0 },
+ { "encrypt", krb5_config_string, check_boolean, 0 },
+ { "extra_addresses", krb5_config_string, NULL, 0 },
+ { "fcache_version", krb5_config_string, check_numeric, 0 },
+ { "fcache_strict_checking", krb5_config_string, check_boolean, 0 },
+ { "fcc-mit-ticketflags", krb5_config_string, check_boolean, 0 },
+ { "forward", krb5_config_string, check_boolean, 0 },
+ { "forwardable", krb5_config_string, check_boolean, 0 },
+ { "allow_hierarchical_capaths", krb5_config_string, check_boolean, 0 },
+ { "host_timeout", krb5_config_string, check_time, 0 },
+ { "http_proxy", krb5_config_string, check_host /* XXX */, 0 },
+ { "ignore_addresses", krb5_config_string, NULL, 0 },
+ { "k5login_authoritative", krb5_config_string, check_boolean, 0 },
+ { "k5login_directory", krb5_config_string, NULL, 0 },
+ { "kdc_timeout", krb5_config_string, check_time, 0 },
+ { "kdc_timesync", krb5_config_string, check_boolean, 0 },
+ { "kuserok", krb5_config_string, NULL, 0 },
+ { "large_message_size", krb5_config_string, check_numeric, 0 },
+ { "log_utc", krb5_config_string, check_boolean, 0 },
+ { "max_retries", krb5_config_string, check_numeric, 0 },
+ { "maximum_message_size", krb5_config_string, check_numeric, 0 },
+ { "moduli", krb5_config_string, NULL, 0 },
+ { "name_canon_rules", krb5_config_string, NULL, 0 },
+ { "no-addresses", krb5_config_string, check_boolean, 0 },
+ { "pkinit_dh_min_bits", krb5_config_string, NULL, 0 },
+ { "plugin_dir", krb5_config_string, check_directory, 0 },
+ { "proxiable", krb5_config_string, check_boolean, 0 },
+ { "renew_lifetime", krb5_config_string, check_time, 0 },
+ { "scan_interfaces", krb5_config_string, check_boolean, 0 },
+ { "srv_lookup", krb5_config_string, check_boolean, 0 },
+ { "srv_try_txt", krb5_config_string, check_boolean, 0 },
+ { "ticket_lifetime", krb5_config_string, check_time, 0 },
+ { "time_format", krb5_config_string, NULL, 0 },
+ { "transited_realms_reject", krb5_config_string, NULL, 0 },
+ { "use_fallback", krb5_config_string, check_boolean, 0 },
+ { "v4_instance_resolve", krb5_config_string, check_boolean, 0 },
+ { "v4_name_convert", krb5_config_list, v4_name_convert_entries, 0 },
+ { "verify_ap_req_nofail", krb5_config_string, check_boolean, 0 },
+ { "warn_pwexpire", krb5_config_string, check_time, 0 },
+
+ /* MIT stuff */
+ { "permitted_enctypes", krb5_config_string, mit_entry, 0 },
+ { "default_tgs_enctypes", krb5_config_string, mit_entry, 0 },
+ { "default_tkt_enctypes", krb5_config_string, mit_entry, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+struct entry appdefaults_entries[] = {
+ { "afslog", krb5_config_string, check_boolean, 0 },
+ { "afs-use-524", krb5_config_string, check_524, 0 },
+#if 0
+ { "anonymous", krb5_config_string, check_boolean, 0 },
+#endif
+ { "encrypt", krb5_config_string, check_boolean, 0 },
+ { "forward", krb5_config_string, check_boolean, 0 },
+ { "forwardable", krb5_config_string, check_boolean, 0 },
+ { "krb4_get_tickets", krb5_config_string, check_boolean, 0 },
+ { "proxiable", krb5_config_string, check_boolean, 0 },
+ { "renew_lifetime", krb5_config_string, check_time, 0 },
+ { "no-addresses", krb5_config_string, check_boolean, 0 },
+ { "pkinit_anchors", krb5_config_string, NULL, 0 },
+ { "pkinit_pool", krb5_config_string, NULL, 0 },
+ { "pkinit_require_eku", krb5_config_string, NULL, 0 },
+ { "pkinit_require_hostname_match", krb5_config_string, NULL, 0 },
+ { "pkinit_require_krbtgt_otherName", krb5_config_string, NULL, 0 },
+ { "pkinit_revoke", krb5_config_string, NULL, 0 },
+ { "pkinit_trustedCertifiers", krb5_config_string, check_boolean, 0 },
+ { "pkinit_win2k", krb5_config_string, NULL, 0 },
+ { "pkinit_win2k_require_binding", krb5_config_string, NULL, 0 },
+ { "ticket_lifetime", krb5_config_string, check_time, 0 },
+ { "", krb5_config_list, appdefaults_entries, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+struct entry realms_entries[] = {
+ { "admin_server", krb5_config_string, check_host, 0 },
+ { "auth_to_local", krb5_config_string, NULL, 0 },
+ { "auth_to_local_names", krb5_config_string, NULL, 0 },
+ { "default_domain", krb5_config_string, NULL, 0 },
+ { "forwardable", krb5_config_string, check_boolean, 0 },
+ { "allow_hierarchical_capaths", krb5_config_string, check_boolean, 0 },
+ { "kdc", krb5_config_string, check_host, 0 },
+ { "kpasswd_server", krb5_config_string, check_host, 0 },
+ { "krb524_server", krb5_config_string, check_host, 0 },
+ { "kx509_ca", krb5_config_string, NULL, 0 },
+ { "kx509_include_pkinit_san", krb5_config_string, check_boolean, 0 },
+ { "name_canon_rules", krb5_config_string, NULL, 0 },
+ { "no-addresses", krb5_config_string, check_boolean, 0 },
+ { "pkinit_anchors", krb5_config_string, NULL, 0 },
+ { "pkinit_require_eku", krb5_config_string, NULL, 0 },
+ { "pkinit_require_hostname_match", krb5_config_string, NULL, 0 },
+ { "pkinit_require_krbtgt_otherName", krb5_config_string, NULL, 0 },
+ { "pkinit_trustedCertifiers", krb5_config_string, check_boolean, 0 },
+ { "pkinit_win2k", krb5_config_string, NULL, 0 },
+ { "pkinit_win2k_require_binding", krb5_config_string, NULL, 0 },
+ { "proxiable", krb5_config_string, check_boolean, 0 },
+ { "renew_lifetime", krb5_config_string, check_time, 0 },
+ { "require_initial_kca_tickets", krb5_config_string, check_boolean, 0 },
+ { "ticket_lifetime", krb5_config_string, check_time, 0 },
+ { "v4_domains", krb5_config_string, NULL, 0 },
+ { "v4_instance_convert", krb5_config_list, all_strings, 0 },
+ { "v4_name_convert", krb5_config_list, v4_name_convert_entries, 0 },
+ { "warn_pwexpire", krb5_config_string, check_time, 0 },
+ { "win2k_pkinit", krb5_config_string, NULL, 0 },
+
+ /* MIT stuff */
+ { "admin_keytab", krb5_config_string, mit_entry, 0 },
+ { "acl_file", krb5_config_string, mit_entry, 0 },
+ { "database_name", krb5_config_string, mit_entry, 0 },
+ { "default_principal_expiration", krb5_config_string, mit_entry, 0 },
+ { "default_principal_flags", krb5_config_string, mit_entry, 0 },
+ { "dict_file", krb5_config_string, mit_entry, 0 },
+ { "kadmind_port", krb5_config_string, mit_entry, 0 },
+ { "kpasswd_port", krb5_config_string, mit_entry, 0 },
+ { "master_kdc", krb5_config_string, mit_entry, 0 },
+ { "master_key_name", krb5_config_string, mit_entry, 0 },
+ { "master_key_type", krb5_config_string, mit_entry, 0 },
+ { "key_stash_file", krb5_config_string, mit_entry, 0 },
+ { "max_life", krb5_config_string, mit_entry, 0 },
+ { "max_renewable_life", krb5_config_string, mit_entry, 0 },
+ { "supported_enctypes", krb5_config_string, mit_entry, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+struct entry realms_foobar[] = {
+ { "", krb5_config_list, realms_entries, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+
+struct entry kdc_database_entries[] = {
+ { "acl_file", krb5_config_string, NULL, 0 },
+ { "dbname", krb5_config_string, NULL, 0 },
+ { "log_file", krb5_config_string, NULL, 0 },
+ { "mkey_file", krb5_config_string, NULL, 0 },
+ { "realm", krb5_config_string, NULL, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+struct entry kdc_entries[] = {
+ { "addresses", krb5_config_string, NULL, 0 },
+ { "allow-anonymous", krb5_config_string, check_boolean, 0 },
+ { "allow-null-ticket-addresses", krb5_config_string, check_boolean, 0 },
+ { "check-ticket-addresses", krb5_config_string, check_boolean, 0 },
+ { "database", krb5_config_list, kdc_database_entries, 0 },
+ { "detach", krb5_config_string, check_boolean, 0 },
+ { "digests_allowed", krb5_config_string, NULL, 0 },
+ { "disable-des", krb5_config_string, check_boolean, 0 },
+ { "enable-524", krb5_config_string, check_boolean, 0 },
+ { "enable-digest", krb5_config_string, check_boolean, 0 },
+ { "enable-kaserver", krb5_config_string, check_boolean, 1 },
+ { "enable-kerberos4", krb5_config_string, check_boolean, 1 },
+ { "enable-kx509", krb5_config_string, check_boolean, 0 },
+ { "enable-http", krb5_config_string, check_boolean, 0 },
+ { "enable-pkinit", krb5_config_string, check_boolean, 0 },
+ { "encode_as_rep_as_tgs_rep", krb5_config_string, check_boolean, 0 },
+ { "enforce-transited-policy", krb5_config_string, NULL, 1 },
+ { "hdb-ldap-create-base", krb5_config_string, NULL, 0 },
+ { "iprop-acl", krb5_config_string, NULL, 0 },
+ { "iprop-stats", krb5_config_string, NULL, 0 },
+ { "kdc-request-log", krb5_config_string, NULL, 0 },
+ { "kdc_warn_pwexpire", krb5_config_string, check_time, 0 },
+ { "key-file", krb5_config_string, NULL, 0 },
+ { "kx509_ca", krb5_config_string, NULL, 0 },
+ { "kx509_include_pkinit_san", krb5_config_string, check_boolean, 0 },
+ { "kx509_template", krb5_config_string, NULL, 0 },
+ { "logging", krb5_config_string, check_log, 0 },
+ { "max-kdc-datagram-reply-length", krb5_config_string, check_bytes, 0 },
+ { "max-request", krb5_config_string, check_bytes, 0 },
+ { "num-kdc-processes", krb5_config_string, check_numeric, 0 },
+ { "pkinit_allow_proxy_certificate", krb5_config_string, check_boolean, 0 },
+ { "pkinit_anchors", krb5_config_string, NULL, 0 },
+ { "pkinit_dh_min_bits", krb5_config_string, check_numeric, 0 },
+ { "pkinit_identity", krb5_config_string, NULL, 0 },
+ { "pkinit_kdc_friendly_name", krb5_config_string, NULL, 0 },
+ { "pkinit_kdc_ocsp", krb5_config_string, NULL, 0 },
+ { "pkinit_mappings_file", krb5_config_string, NULL, 0 },
+ { "pkinit_pool", krb5_config_string, NULL, 0 },
+ { "pkinit_principal_in_certificate", krb5_config_string, check_boolean, 0 },
+ { "pkinit_revoke", krb5_config_string, NULL, 0 },
+ { "pkinit_win2k_require_binding", krb5_config_string, check_boolean, 0 },
+ { "ports", krb5_config_string, NULL, 0 },
+ { "preauth-use-strongest-session-key", krb5_config_string, check_boolean, 0 },
+ { "require_initial_kca_tickets", krb5_config_string, check_boolean, 0 },
+ { "require-preauth", krb5_config_string, check_boolean, 0 },
+ { "strict-nametypes", krb5_config_string, check_boolean, 0 },
+ { "svc-use-strongest-session-key", krb5_config_string, check_boolean, 0 },
+ { "tgt-use-strongest-session-key", krb5_config_string, check_boolean, 0 },
+ { "transited-policy", krb5_config_string, NULL, 0 },
+ { "use_2b", krb5_config_list, NULL, 0 },
+ { "use-strongest-server-key", krb5_config_string, check_boolean, 0 },
+ { "v4_realm", krb5_config_string, NULL, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+struct entry kadmin_entries[] = {
+ { "allow_self_change_password", krb5_config_string, check_boolean, 0 },
+ { "default_keys", krb5_config_string, NULL, 0 },
+ { "password_lifetime", krb5_config_string, check_time, 0 },
+ { "plugin_dir", krb5_config_string, check_directory, 0 },
+ { "require-preauth", krb5_config_string, check_boolean, 0 },
+ { "save-password", krb5_config_string, check_boolean, 0 },
+ { "use_v4_salt", krb5_config_string, NULL, 0 },
+ { NULL, 0, NULL, 0 }
+};
+struct entry log_strings[] = {
+ { "", krb5_config_string, check_log, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+
+/* MIT stuff */
+struct entry kdcdefaults_entries[] = {
+ { "kdc_ports", krb5_config_string, mit_entry, 0 },
+ { "v4_mode", krb5_config_string, mit_entry, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+struct entry capaths_entries[] = {
+ { "", krb5_config_list, all_strings, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+struct entry kcm_entries[] = {
+ { "detach", krb5_config_string, check_boolean, 0 },
+ { "disallow-getting-krbtgt", krb5_config_string, check_boolean, 0 },
+ { "logging", krb5_config_string, NULL, 0 },
+ { "max-request", krb5_config_string, NULL, 0 },
+ { "system_ccache", krb5_config_string, NULL, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+struct entry password_quality_entries[] = {
+ { "enforce_on_admin_set", krb5_config_string, check_boolean, 0 },
+ { "check_function", krb5_config_string, NULL, 0 },
+ { "check_library", krb5_config_string, NULL, 0 },
+ { "external_program", krb5_config_string, NULL, 0 },
+ { "min_classes", krb5_config_string, check_numeric, 0 },
+ { "min_length", krb5_config_string, check_numeric, 0 },
+ { "policies", krb5_config_string, NULL, 0 },
+ { "policy_libraries", krb5_config_string, NULL, 0 },
+ { "", krb5_config_list, all_strings, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+struct entry toplevel_sections[] = {
+ { "appdefaults", krb5_config_list, appdefaults_entries, 0 },
+ { "capaths", krb5_config_list, capaths_entries, 0 },
+ { "domain_realm", krb5_config_list, all_strings, 0 },
+ { "gssapi", krb5_config_list, NULL, 0 },
+ { "kadmin", krb5_config_list, kadmin_entries, 0 },
+ { "kcm", krb5_config_list, kcm_entries, 0 },
+ { "kdc", krb5_config_list, kdc_entries, 0 },
+ { "libdefaults" , krb5_config_list, libdefaults_entries, 0 },
+ { "logging", krb5_config_list, log_strings, 0 },
+ { "password_quality", krb5_config_list, password_quality_entries, 0 },
+ { "realms", krb5_config_list, realms_foobar, 0 },
+
+ /* MIT stuff */
+ { "kdcdefaults", krb5_config_list, kdcdefaults_entries, 0 },
+ { NULL, 0, NULL, 0 }
+};
+
+
+static int
+check_section(krb5_context context, const char *path, krb5_config_section *cf,
+ struct entry *entries)
+{
+ int error = 0;
+ krb5_config_section *p;
+ struct entry *e;
+
+ char *local;
+
+ for(p = cf; p != NULL; p = p->next) {
+ local = NULL;
+ if (asprintf(&local, "%s/%s", path, p->name) < 0 || local == NULL)
+ errx(1, "out of memory");
+ for(e = entries; e->name != NULL; e++) {
+ if(*e->name == '\0' || strcmp(e->name, p->name) == 0) {
+ if(e->type != p->type) {
+ krb5_warnx(context, "%s: unknown or wrong type", local);
+ error |= 1;
+ } else if(p->type == krb5_config_string && e->check_data != NULL) {
+ error |= (*(check_func_t)e->check_data)(context, local, p->u.string);
+ } else if(p->type == krb5_config_list && e->check_data != NULL) {
+ error |= check_section(context, local, p->u.list, e->check_data);
+ }
+ if(e->deprecated) {
+ krb5_warnx(context, "%s: is a deprecated entry", local);
+ error |= 1;
+ }
+ break;
+ }
+ }
+ if(e->name == NULL) {
+ krb5_warnx(context, "%s: unknown entry", local);
+ error |= 1;
+ }
+ free(local);
+ }
+ return error;
+}
+
+
+static void
+dumpconfig(int level, krb5_config_section *top)
+{
+ krb5_config_section *x;
+ for(x = top; x; x = x->next) {
+ switch(x->type) {
+ case krb5_config_list:
+ if(level == 0) {
+ printf("[%s]\n", x->name);
+ } else {
+ printf("%*s%s = {\n", 4 * level, " ", x->name);
+ }
+ dumpconfig(level + 1, x->u.list);
+ if(level > 0)
+ printf("%*s}\n", 4 * level, " ");
+ break;
+ case krb5_config_string:
+ printf("%*s%s = %s\n", 4 * level, " ", x->name, x->u.string);
+ break;
+ }
+ }
+}
+
+int
+main(int argc, char **argv)
+{
+ krb5_context context;
+ krb5_error_code ret;
+ krb5_config_section *tmp_cf;
+ int optidx = 0;
+
+ setprogname (argv[0]);
+
+ ret = krb5_init_context(&context);
+ if (ret == KRB5_CONFIG_BADFORMAT)
+ errx (1, "krb5_init_context failed to parse configuration file");
+ else if (ret)
+ errx (1, "krb5_init_context failed with %d", ret);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ tmp_cf = NULL;
+ if(argc == 0)
+ krb5_get_default_config_files(&argv);
+
+ while(*argv) {
+ ret = krb5_config_parse_file_multi(context, *argv, &tmp_cf);
+ if (ret != 0)
+ krb5_warn (context, ret, "krb5_config_parse_file");
+ argv++;
+ }
+
+ if(dumpconfig_flag)
+ dumpconfig(0, tmp_cf);
+
+ return check_section(context, "", tmp_cf, toplevel_sections);
+}
diff --git a/third_party/heimdal/lib/krb5/verify_user.c b/third_party/heimdal/lib/krb5/verify_user.c
new file mode 100644
index 0000000..c6ead8e
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/verify_user.c
@@ -0,0 +1,258 @@
+/*
+ * Copyright (c) 1997-2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+static krb5_error_code
+verify_common (krb5_context context,
+ krb5_principal principal,
+ krb5_ccache ccache,
+ krb5_keytab keytab,
+ krb5_boolean secure,
+ const char *service,
+ krb5_creds *cred)
+{
+ krb5_error_code ret;
+ krb5_principal server;
+ krb5_verify_init_creds_opt vopt;
+ krb5_ccache id;
+
+ ret = krb5_sname_to_principal (context, NULL, service, KRB5_NT_SRV_HST,
+ &server);
+ if(ret)
+ return ret;
+
+ krb5_verify_init_creds_opt_init(&vopt);
+ krb5_verify_init_creds_opt_set_ap_req_nofail(&vopt, secure);
+
+ ret = krb5_verify_init_creds(context,
+ cred,
+ server,
+ keytab,
+ NULL,
+ &vopt);
+ krb5_free_principal(context, server);
+ if(ret)
+ return ret;
+ if(ccache == NULL)
+ ret = krb5_cc_default (context, &id);
+ else
+ id = ccache;
+ if(ret == 0){
+ ret = krb5_cc_initialize(context, id, principal);
+ if(ret == 0){
+ ret = krb5_cc_store_cred(context, id, cred);
+ }
+ if(ccache == NULL)
+ krb5_cc_close(context, id);
+ }
+ return ret;
+}
+
+/*
+ * Verify user `principal' with `password'.
+ *
+ * If `secure', also verify against local service key for `service'.
+ *
+ * As a side effect, fresh tickets are obtained and stored in `ccache'.
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_verify_opt_init(krb5_verify_opt *opt)
+{
+ memset(opt, 0, sizeof(*opt));
+ opt->secure = TRUE;
+ opt->service = "host";
+}
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_verify_opt_alloc(krb5_context context, krb5_verify_opt **opt)
+{
+ *opt = calloc(1, sizeof(**opt));
+ if ((*opt) == NULL)
+ return krb5_enomem(context);
+ krb5_verify_opt_init(*opt);
+ return 0;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_verify_opt_free(krb5_verify_opt *opt)
+{
+ free(opt);
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_verify_opt_set_ccache(krb5_verify_opt *opt, krb5_ccache ccache)
+{
+ opt->ccache = ccache;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_verify_opt_set_keytab(krb5_verify_opt *opt, krb5_keytab keytab)
+{
+ opt->keytab = keytab;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_verify_opt_set_secure(krb5_verify_opt *opt, krb5_boolean secure)
+{
+ opt->secure = secure;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_verify_opt_set_service(krb5_verify_opt *opt, const char *service)
+{
+ opt->service = service;
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_verify_opt_set_flags(krb5_verify_opt *opt, unsigned int flags)
+{
+ opt->flags |= flags;
+}
+
+static krb5_error_code
+verify_user_opt_int(krb5_context context,
+ krb5_principal principal,
+ const char *password,
+ krb5_verify_opt *vopt)
+
+{
+ krb5_error_code ret;
+ krb5_get_init_creds_opt *opt;
+ krb5_creds cred;
+
+ ret = krb5_get_init_creds_opt_alloc (context, &opt);
+ if (ret)
+ return ret;
+ krb5_get_init_creds_opt_set_default_flags(context, NULL,
+ krb5_principal_get_realm(context, principal),
+ opt);
+ ret = krb5_get_init_creds_password (context,
+ &cred,
+ principal,
+ password,
+ krb5_prompter_posix,
+ NULL,
+ 0,
+ NULL,
+ opt);
+ krb5_get_init_creds_opt_free(context, opt);
+ if(ret)
+ return ret;
+#define OPT(V, D) ((vopt && (vopt->V)) ? (vopt->V) : (D))
+ ret = verify_common (context, principal, OPT(ccache, NULL),
+ OPT(keytab, NULL), vopt ? vopt->secure : TRUE,
+ OPT(service, "host"), &cred);
+#undef OPT
+ krb5_free_cred_contents(context, &cred);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verify_user_opt(krb5_context context,
+ krb5_principal principal,
+ const char *password,
+ krb5_verify_opt *opt)
+{
+ krb5_error_code ret;
+
+ if(opt && (opt->flags & KRB5_VERIFY_LREALMS)) {
+ krb5_realm *realms, *r;
+ ret = krb5_get_default_realms (context, &realms);
+ if (ret)
+ return ret;
+ ret = KRB5_CONFIG_NODEFREALM;
+
+ for (r = realms; *r != NULL && ret != 0; ++r) {
+ ret = krb5_principal_set_realm(context, principal, *r);
+ if (ret) {
+ krb5_free_host_realm (context, realms);
+ return ret;
+ }
+
+ ret = verify_user_opt_int(context, principal, password, opt);
+ }
+ krb5_free_host_realm (context, realms);
+ if(ret)
+ return ret;
+ } else
+ ret = verify_user_opt_int(context, principal, password, opt);
+ return ret;
+}
+
+/* compat function that calls above */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verify_user(krb5_context context,
+ krb5_principal principal,
+ krb5_ccache ccache,
+ const char *password,
+ krb5_boolean secure,
+ const char *service)
+{
+ krb5_verify_opt opt;
+
+ krb5_verify_opt_init(&opt);
+
+ krb5_verify_opt_set_ccache(&opt, ccache);
+ krb5_verify_opt_set_secure(&opt, secure);
+ krb5_verify_opt_set_service(&opt, service);
+
+ return krb5_verify_user_opt(context, principal, password, &opt);
+}
+
+/*
+ * A variant of `krb5_verify_user'. The realm of `principal' is
+ * ignored and all the local realms are tried.
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verify_user_lrealm(krb5_context context,
+ krb5_principal principal,
+ krb5_ccache ccache,
+ const char *password,
+ krb5_boolean secure,
+ const char *service)
+{
+ krb5_verify_opt opt;
+
+ krb5_verify_opt_init(&opt);
+
+ krb5_verify_opt_set_ccache(&opt, ccache);
+ krb5_verify_opt_set_secure(&opt, secure);
+ krb5_verify_opt_set_service(&opt, service);
+ krb5_verify_opt_set_flags(&opt, KRB5_VERIFY_LREALMS);
+
+ return krb5_verify_user_opt(context, principal, password, &opt);
+}
diff --git a/third_party/heimdal/lib/krb5/version-script.map b/third_party/heimdal/lib/krb5/version-script.map
new file mode 100644
index 0000000..f6278e9
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/version-script.map
@@ -0,0 +1,886 @@
+HEIMDAL_KRB5_2.0 {
+ global:
+ krb524_convert_creds_kdc;
+ krb524_convert_creds_kdc_ccache;
+ krb5_abort;
+ krb5_abortx;
+ krb5_acl_match_file;
+ krb5_acl_match_string;
+ krb5_add_et_list;
+ krb5_add_extra_addresses;
+ krb5_add_ignore_addresses;
+ krb5_addlog_dest;
+ krb5_addlog_func;
+ krb5_addr2sockaddr;
+ krb5_address_compare;
+ krb5_address_order;
+ krb5_address_prefixlen_boundary;
+ krb5_address_search;
+ krb5_allow_weak_crypto;
+ krb5_aname_to_localname;
+ krb5_anyaddr;
+ krb5_appdefault_boolean;
+ krb5_appdefault_string;
+ krb5_appdefault_time;
+ krb5_append_addresses;
+ krb5_auth_con_addflags;
+ krb5_auth_con_add_AuthorizationData;
+ krb5_auth_con_add_AuthorizationDataIfRelevant;
+ krb5_auth_con_free;
+ krb5_auth_con_genaddrs;
+ krb5_auth_con_generatelocalsubkey;
+ krb5_auth_con_getaddrs;
+ krb5_auth_con_getauthenticator;
+ krb5_auth_con_getcksumtype;
+ krb5_auth_con_getflags;
+ krb5_auth_con_getkey;
+ krb5_auth_con_getkeytype;
+ krb5_auth_con_getlocalseqnumber;
+ krb5_auth_con_getlocalsubkey;
+ krb5_auth_con_getrcache;
+ krb5_auth_con_getremoteseqnumber;
+ krb5_auth_con_getremotesubkey;
+ krb5_auth_con_getsendsubkey;
+ krb5_auth_con_init;
+ krb5_auth_con_removeflags;
+ krb5_auth_con_setaddrs;
+ krb5_auth_con_setaddrs_from_fd;
+ krb5_auth_con_setcksumtype;
+ krb5_auth_con_setflags;
+ krb5_auth_con_setkey;
+ krb5_auth_con_setkeytype;
+ krb5_auth_con_setlocalseqnumber;
+ krb5_auth_con_setlocalsubkey;
+ krb5_auth_con_setrcache;
+ krb5_auth_con_setremoteseqnumber;
+ krb5_auth_con_setremotesubkey;
+ krb5_auth_con_setuserkey;
+ krb5_auth_getremoteseqnumber;
+ krb5_build_ap_req;
+ krb5_build_principal;
+ krb5_build_principal_ext;
+ krb5_build_principal_va;
+ krb5_build_principal_va_ext;
+ krb5_c_block_size;
+ krb5_c_checksum_length;
+ krb5_c_decrypt;
+ krb5_c_encrypt;
+ krb5_c_encrypt_length;
+ krb5_c_enctype_compare;
+ krb5_c_get_checksum;
+ krb5_c_is_coll_proof_cksum;
+ krb5_c_is_keyed_cksum;
+ krb5_c_keylengths;
+ krb5_c_make_checksum;
+ krb5_c_make_random_key;
+ krb5_c_prf;
+ krb5_c_prf_length;
+ krb5_c_set_checksum;
+ krb5_c_valid_cksumtype;
+ krb5_c_valid_enctype;
+ krb5_c_verify_checksum;
+ krb5_cc_cache_end_seq_get;
+ krb5_cc_cache_get_first;
+ krb5_cc_cache_match;
+ krb5_cc_cache_next;
+ krb5_cc_clear_mcred;
+ krb5_cc_close;
+ krb5_cc_configured_default_name;
+ krb5_cc_copy_cache;
+ krb5_cc_copy_match_f;
+ krb5_cc_default;
+ krb5_cc_default_for;
+ krb5_cc_default_sub;
+ krb5_cc_default_name;
+ krb5_cc_destroy;
+ krb5_cc_end_seq_get;
+ krb5_cc_gen_new;
+ krb5_cc_get_config;
+ krb5_cc_get_friendly_name;
+ krb5_cc_get_full_name;
+ krb5_cc_get_kdc_offset;
+ krb5_cc_get_lifetime;
+ krb5_cc_get_name;
+ krb5_cc_get_ops;
+ krb5_cc_get_prefix_ops;
+ krb5_cc_get_principal;
+ krb5_cc_get_type;
+ krb5_cc_get_version;
+ krb5_cc_initialize;
+ krb5_cc_last_change_time;
+ krb5_cc_move;
+ krb5_cc_new_unique;
+ krb5_cc_next_cred;
+ krb5_cc_next_cred_match;
+ krb5_cc_register;
+ krb5_cc_remove_cred;
+ krb5_cc_resolve;
+ krb5_cc_resolve_for;
+ krb5_cc_resolve_sub;
+ krb5_cc_retrieve_cred;
+ krb5_cc_set_config;
+ krb5_cc_set_default_name;
+ krb5_cc_set_flags;
+ krb5_cc_set_kdc_offset;
+ krb5_cc_start_seq_get;
+ krb5_cc_store_cred;
+ krb5_cc_support_switch;
+ krb5_cc_switch;
+ krb5_cc_set_friendly_name;
+ krb5_change_password;
+ krb5_check_transited;
+ krb5_check_transited_realms;
+ krb5_checksum_disable;
+ krb5_checksum_free;
+ krb5_checksum_is_collision_proof;
+ krb5_checksum_is_keyed;
+ krb5_checksumsize;
+ krb5_cksumtype_to_enctype;
+ krb5_cksumtype_valid;
+ krb5_clear_error_string;
+ krb5_clear_error_message;
+ krb5_closelog;
+ krb5_compare_creds;
+ krb5_config_file_free;
+ krb5_config_free_strings;
+ krb5_config_get_bool;
+ krb5_config_get_bool_default;
+ krb5_config_get_int;
+ krb5_config_get_int_default;
+ krb5_config_get_list;
+ krb5_config_get_string;
+ krb5_config_get_string_default;
+ krb5_config_get_strings;
+ krb5_config_get_time;
+ krb5_config_get_time_default;
+ krb5_config_parse_file;
+ krb5_config_parse_file_multi;
+ krb5_config_parse_string_multi;
+ krb5_config_vget_bool;
+ krb5_config_vget_bool_default;
+ krb5_config_vget_int;
+ krb5_config_vget_int_default;
+ krb5_config_vget_list;
+ krb5_config_vget_string;
+ krb5_config_vget_string_default;
+ krb5_config_vget_strings;
+ krb5_config_vget_time;
+ krb5_config_vget_time_default;
+ krb5_copy_address;
+ krb5_copy_addresses;
+ krb5_copy_checksum;
+ krb5_copy_creds;
+ krb5_copy_creds_contents;
+ krb5_copy_context;
+ krb5_copy_data;
+ krb5_copy_host_realm;
+ krb5_copy_keyblock;
+ krb5_copy_keyblock_contents;
+ krb5_copy_principal;
+ krb5_copy_ticket;
+ krb5_create_checksum;
+ krb5_create_checksum_iov;
+ krb5_crypto_destroy;
+ krb5_crypto_fx_cf2;
+ krb5_crypto_get_checksum_type;
+ krb5_crypto_getblocksize;
+ krb5_crypto_getconfoundersize;
+ krb5_crypto_getenctype;
+ krb5_crypto_getpadsize;
+ krb5_crypto_init;
+ krb5_crypto_overhead;
+ krb5_crypto_prf;
+ krb5_crypto_prfplus;
+ krb5_crypto_prf_length;
+ krb5_crypto_length;
+ krb5_crypto_length_iov;
+ krb5_decrypt_iov_ivec;
+ krb5_encrypt_iov_ivec;
+ krb5_enomem;
+ krb5_data_alloc;
+ krb5_data_ct_cmp;
+ krb5_data_cmp;
+ krb5_data_copy;
+ krb5_data_free;
+ krb5_data_realloc;
+ krb5_data_zero;
+ krb5_debug;
+ krb5_decode_Authenticator;
+ krb5_decode_ETYPE_INFO2;
+ krb5_decode_ETYPE_INFO;
+ krb5_decode_EncAPRepPart;
+ krb5_decode_EncASRepPart;
+ krb5_decode_EncKrbCredPart;
+ krb5_decode_EncTGSRepPart;
+ krb5_decode_EncTicketPart;
+ krb5_decode_ap_req;
+ krb5_decrypt;
+ krb5_decrypt_EncryptedData;
+ krb5_decrypt_ivec;
+ krb5_decrypt_ticket;
+ krb5_derive_key;
+ krb5_digest_alloc;
+ krb5_digest_free;
+ krb5_digest_get_client_binding;
+ krb5_digest_get_identifier;
+ krb5_digest_get_opaque;
+ krb5_digest_get_rsp;
+ krb5_digest_get_server_nonce;
+ krb5_digest_get_session_key;
+ krb5_digest_get_tickets;
+ krb5_digest_init_request;
+ krb5_digest_probe;
+ krb5_digest_rep_get_status;
+ krb5_digest_request;
+ krb5_digest_set_authentication_user;
+ krb5_digest_set_authid;
+ krb5_digest_set_client_nonce;
+ krb5_digest_set_digest;
+ krb5_digest_set_hostname;
+ krb5_digest_set_identifier;
+ krb5_digest_set_method;
+ krb5_digest_set_nonceCount;
+ krb5_digest_set_opaque;
+ krb5_digest_set_qop;
+ krb5_digest_set_realm;
+ krb5_digest_set_responseData;
+ krb5_digest_set_server_cb;
+ krb5_digest_set_server_nonce;
+ krb5_digest_set_type;
+ krb5_digest_set_uri;
+ krb5_digest_set_username;
+ krb5_domain_x500_decode;
+ krb5_domain_x500_encode;
+ krb5_eai_to_heim_errno;
+ krb5_encode_Authenticator;
+ krb5_encode_ETYPE_INFO2;
+ krb5_encode_ETYPE_INFO;
+ krb5_encode_EncAPRepPart;
+ krb5_encode_EncASRepPart;
+ krb5_encode_EncKrbCredPart;
+ krb5_encode_EncTGSRepPart;
+ krb5_encode_EncTicketPart;
+ krb5_encrypt;
+ krb5_encrypt_EncryptedData;
+ krb5_encrypt_ivec;
+ krb5_enctype_enable;
+ krb5_enctype_disable;
+ krb5_enctype_keybits;
+ krb5_enctype_keysize;
+ krb5_enctype_to_keytype;
+ krb5_enctype_to_string;
+ krb5_enctype_valid;
+ krb5_enctypes_compatible_keys;
+ krb5_err;
+ krb5_error_from_rd_error;
+ krb5_errx;
+ krb5_expand_hostname;
+ krb5_expand_hostname_realms;
+ krb5_find_padata;
+ krb5_format_time;
+ krb5_free_address;
+ krb5_free_addresses;
+ krb5_free_ap_rep_enc_part;
+ krb5_free_authenticator;
+ krb5_free_checksum;
+ krb5_free_checksum_contents;
+ krb5_free_config_files;
+ krb5_free_context;
+ krb5_free_cred_contents;
+ krb5_free_creds;
+ krb5_free_creds_contents;
+ krb5_free_data;
+ krb5_free_data_contents;
+ krb5_free_default_realm;
+ krb5_free_error;
+ krb5_free_error_contents;
+ krb5_free_error_string;
+ krb5_free_error_message;
+ krb5_free_host_realm;
+ krb5_free_kdc_rep;
+ krb5_free_keyblock;
+ krb5_free_keyblock_contents;
+ krb5_free_krbhst;
+ krb5_free_principal;
+ krb5_free_salt;
+ krb5_free_ticket;
+ krb5_free_unparsed_name;
+ krb5_fwd_tgt_creds;
+ krb5_generate_random_block;
+ krb5_generate_random_keyblock;
+ krb5_generate_seq_number;
+ krb5_generate_subkey;
+ krb5_generate_subkey_extended;
+ krb5_get_all_client_addrs;
+ krb5_get_all_server_addrs;
+ krb5_get_cred_from_kdc;
+ krb5_get_cred_from_kdc_opt;
+ krb5_get_credentials;
+ krb5_get_credentials_with_flags;
+ krb5_get_creds;
+ krb5_get_creds_opt_add_options;
+ krb5_get_creds_opt_alloc;
+ krb5_get_creds_opt_free;
+ krb5_get_creds_opt_set_enctype;
+ krb5_get_creds_opt_set_impersonate;
+ krb5_get_creds_opt_set_options;
+ krb5_get_creds_opt_set_ticket;
+ krb5_get_default_config_files;
+ krb5_get_default_in_tkt_etypes;
+ krb5_get_default_principal;
+ krb5_get_default_realm;
+ krb5_get_default_realms;
+ krb5_get_dns_canonicalize_hostname;
+ krb5_get_err_text;
+ krb5_get_error_message;
+ krb5_get_error_string;
+ krb5_get_extra_addresses;
+ krb5_get_fcache_version;
+ krb5_get_forwarded_creds;
+ krb5_get_host_realm;
+ krb5_get_ignore_addresses;
+ krb5_get_in_cred;
+ krb5_cccol_last_change_time;
+ krb5_get_in_tkt;
+ krb5_get_in_tkt_with_keytab;
+ krb5_get_in_tkt_with_password;
+ krb5_get_in_tkt_with_skey;
+ krb5_get_init_creds;
+ krb5_get_init_creds_keyblock;
+ krb5_get_init_creds_keytab;
+ krb5_get_init_creds_opt_alloc;
+ krb5_get_init_creds_opt_free;
+ krb5_get_init_creds_opt_get_error;
+ krb5_get_init_creds_opt_init;
+ krb5_get_init_creds_opt_set_address_list;
+ krb5_get_init_creds_opt_set_addressless;
+ krb5_get_init_creds_opt_set_anonymous;
+ krb5_get_init_creds_opt_set_change_password_prompt;
+ krb5_get_init_creds_opt_set_canonicalize;
+ krb5_get_init_creds_opt_set_default_flags;
+ krb5_get_init_creds_opt_set_etype_list;
+ krb5_get_init_creds_opt_set_forwardable;
+ krb5_get_init_creds_opt_set_pa_password;
+ krb5_get_init_creds_opt_set_pac_request;
+ krb5_get_init_creds_opt_set_pkinit;
+ krb5_get_init_creds_opt_set_preauth_list;
+ krb5_get_init_creds_opt_set_process_last_req;
+ krb5_get_init_creds_opt_set_proxiable;
+ krb5_get_init_creds_opt_set_renew_life;
+ krb5_get_init_creds_opt_set_salt;
+ krb5_get_init_creds_opt_set_tkt_life;
+ krb5_get_init_creds_opt_set_win2k;
+ krb5_get_init_creds_password;
+ krb5_get_instance;
+ krb5_get_kdc_cred;
+ krb5_get_kdc_sec_offset;
+ krb5_get_krb524hst;
+ krb5_get_krb_admin_hst;
+ krb5_get_krb_changepw_hst;
+ krb5_get_krb_readonly_admin_hst;
+ krb5_get_krbhst;
+ krb5_get_max_time_skew;
+ krb5_get_pw_salt;
+ krb5_get_renewed_creds;
+ krb5_get_server_rcache;
+ krb5_get_use_admin_kdc;
+ krb5_get_warn_dest;
+ krb5_get_wrapped_length;
+ krb5_getportbyname;
+ krb5_h_addr2addr;
+ krb5_h_addr2sockaddr;
+ krb5_h_errno_to_heim_errno;
+ krb5_have_debug;
+ krb5_have_error_string;
+ krb5_hmac;
+ krb5_init_context;
+ krb5_init_ets;
+ krb5_initlog;
+ krb5_is_config_principal;
+ krb5_is_enctype_old;
+ krb5_is_enctype_weak;
+ krb5_is_thread_safe;
+ krb5_kcm_call;
+ krb5_kcm_storage_request;
+ krb5_kerberos_enctypes;
+ krb5_keyblock_get_enctype;
+ krb5_keyblock_init;
+ krb5_keyblock_key_proc;
+ krb5_keyblock_zero;
+ krb5_keytab_key_proc;
+ krb5_keytype_to_enctypes;
+ krb5_keytype_to_enctypes_default;
+ krb5_keytype_to_string;
+ krb5_krbhst_format_string;
+ krb5_krbhst_free;
+ krb5_krbhst_get_addrinfo;
+ krb5_krbhst_init;
+ krb5_krbhst_init_flags;
+ krb5_krbhst_next;
+ krb5_krbhst_next_as_string;
+ krb5_krbhst_reset;
+ krb5_kt_add_entry;
+ krb5_kt_close;
+ krb5_kt_compare;
+ krb5_kt_copy_entry_contents;
+ krb5_kt_default;
+ krb5_kt_default_modify_name;
+ krb5_kt_default_name;
+ krb5_kt_destroy;
+ krb5_kt_end_seq_get;
+ krb5_kt_free_entry;
+ krb5_kt_get_entry;
+ krb5_kt_get_full_name;
+ krb5_kt_get_name;
+ krb5_kt_get_type;
+ krb5_kt_have_content;
+ krb5_kt_next_entry;
+ krb5_kt_read_service_key;
+ krb5_kt_register;
+ krb5_kt_remove_entry;
+ krb5_kt_resolve;
+ krb5_kt_start_seq_get;
+ krb5_kuserok;
+ krb5_kx509;
+ krb5_kx509_ctx_add_eku;
+ krb5_kx509_ctx_add_san_dns_name;
+ krb5_kx509_ctx_add_san_ms_upn;
+ krb5_kx509_ctx_add_san_pkinit;
+ krb5_kx509_ctx_add_san_registeredID;
+ krb5_kx509_ctx_add_san_rfc822Name;
+ krb5_kx509_ctx_add_san_xmpp;
+ krb5_kx509_ctx_free;
+ krb5_kx509_ctx_init;
+ krb5_kx509_ctx_set_csr_der;
+ krb5_kx509_ctx_set_key;
+ krb5_kx509_ctx_set_realm;
+ krb5_kx509_ext;
+ krb5_log;
+ krb5_log_msg;
+ krb5_make_addrport;
+ krb5_make_principal;
+ krb5_max_sockaddr_size;
+ krb5_mk_1cred;
+ krb5_mk_error;
+ krb5_mk_error_ext;
+ krb5_mk_ncred;
+ krb5_mk_priv;
+ krb5_mk_rep;
+ krb5_mk_req;
+ krb5_mk_req_exact;
+ krb5_mk_req_extended;
+ krb5_mk_safe;
+ krb5_net_read;
+ krb5_net_write;
+ krb5_net_write_block;
+ krb5_ntlm_alloc;
+ krb5_ntlm_free;
+ krb5_ntlm_init_get_challenge;
+ krb5_ntlm_init_get_flags;
+ krb5_ntlm_init_get_opaque;
+ krb5_ntlm_init_get_targetinfo;
+ krb5_ntlm_init_get_targetname;
+ krb5_ntlm_init_request;
+ krb5_ntlm_rep_get_sessionkey;
+ krb5_ntlm_rep_get_status;
+ krb5_ntlm_req_set_flags;
+ krb5_ntlm_req_set_lm;
+ krb5_ntlm_req_set_ntlm;
+ krb5_ntlm_req_set_opaque;
+ krb5_ntlm_req_set_session;
+ krb5_ntlm_req_set_targetname;
+ krb5_ntlm_req_set_username;
+ krb5_ntlm_request;
+ krb5_openlog;
+ krb5_pac_add_buffer;
+ krb5_pac_free;
+ krb5_pac_get_buffer;
+ _krb5_pac_get_buffer_by_name;
+ krb5_pac_get_kdc_checksum_info;
+ krb5_pac_get_types;
+ krb5_pac_init;
+ krb5_pac_parse;
+ krb5_pac_verify;
+ krb5_padata_add;
+ _krb5_parse_address_no_lookup;
+ krb5_parse_address;
+ krb5_parse_name;
+ krb5_parse_name_flags;
+ krb5_parse_nametype;
+ krb5_passwd_result_to_string;
+ krb5_password_key_proc;
+ krb5_get_permitted_enctypes;
+ krb5_plugin_register;
+ krb5_prepend_config_files;
+ krb5_prepend_config_files_default;
+ krb5_prepend_error_message;
+ krb5_princ_realm;
+ krb5_princ_set_realm;
+ krb5_principal_compare;
+ krb5_principal_compare_any_realm;
+ krb5_principal_get_comp_string;
+ krb5_principal_get_num_comp;
+ krb5_principal_get_realm;
+ krb5_principal_get_type;
+ krb5_principal_match;
+ krb5_principal_set_comp_string;
+ krb5_principal_set_realm;
+ krb5_principal_set_type;
+ krb5_principal_is_anonymous;
+ krb5_principal_is_federated;
+ krb5_principal_is_krbtgt;
+ krb5_principal_is_root_krbtgt;
+ krb5_print_address;
+ krb5_program_setup;
+ krb5_prompter_posix;
+ krb5_random_to_key;
+ krb5_rc_close;
+ krb5_rc_default;
+ krb5_rc_default_name;
+ krb5_rc_default_type;
+ krb5_rc_destroy;
+ krb5_rc_expunge;
+ krb5_rc_get_lifespan;
+ krb5_rc_get_name;
+ krb5_rc_get_type;
+ krb5_rc_initialize;
+ krb5_rc_recover;
+ krb5_rc_resolve;
+ krb5_rc_resolve_full;
+ krb5_rc_resolve_type;
+ krb5_rc_store;
+ krb5_rd_cred2;
+ krb5_rd_cred;
+ krb5_rd_error;
+ krb5_rd_priv;
+ krb5_rd_rep;
+ krb5_rd_req;
+ krb5_rd_req_ctx;
+ krb5_rd_req_in_ctx_alloc;
+ krb5_rd_req_in_ctx_free;
+ krb5_rd_req_in_set_keyblock;
+ krb5_rd_req_in_set_keytab;
+ krb5_rd_req_in_set_pac_check;
+ krb5_rd_req_out_ctx_free;
+ krb5_rd_req_out_get_ap_req_options;
+ krb5_rd_req_out_get_keyblock;
+ krb5_rd_req_out_get_ticket;
+ krb5_rd_req_with_keyblock;
+ krb5_rd_safe;
+ krb5_read_message;
+ krb5_read_priv_message;
+ krb5_read_safe_message;
+ krb5_realm_compare;
+ krb5_recvauth;
+ krb5_recvauth_match_version;
+ krb5_ret_address;
+ krb5_ret_addrs;
+ krb5_ret_authdata;
+ krb5_ret_creds;
+ krb5_ret_creds_tag;
+ krb5_ret_data;
+ krb5_ret_int16;
+ krb5_ret_int32;
+ krb5_ret_int64;
+ krb5_ret_int8;
+ krb5_ret_keyblock;
+ krb5_ret_principal;
+ krb5_ret_string;
+ krb5_ret_stringnl;
+ krb5_ret_stringz;
+ krb5_ret_times;
+ krb5_ret_uint16;
+ krb5_ret_uint32;
+ krb5_ret_uint64;
+ krb5_ret_uint8;
+ krb5_salttype_to_string;
+ krb5_sendauth;
+ krb5_sendto;
+ krb5_sendto_context;
+ krb5_sendto_ctx_add_flags;
+ krb5_sendto_ctx_alloc;
+ krb5_sendto_ctx_free;
+ krb5_sendto_ctx_get_flags;
+ krb5_sendto_ctx_set_func;
+ krb5_sendto_ctx_set_type;
+ krb5_sendto_kdc;
+ krb5_sendto_kdc_flags;
+ krb5_sendto_set_hostname;
+ krb5_sendto_set_sitename;
+ krb5_set_config;
+ krb5_set_config_files;
+ krb5_set_debug_dest;
+ krb5_set_default_in_tkt_etypes;
+ krb5_set_default_realm;
+ krb5_set_dns_canonicalize_hostname;
+ krb5_set_error_message;
+ krb5_set_error_string;
+ krb5_set_extra_addresses;
+ krb5_set_fcache_version;
+ krb5_set_home_dir_access;
+ krb5_set_ignore_addresses;
+ krb5_set_kdc_sec_offset;
+ krb5_set_log_dest;
+ krb5_set_max_time_skew;
+ krb5_set_password;
+ krb5_set_password_using_ccache;
+ krb5_set_real_time;
+ krb5_set_send_to_kdc_func;
+ krb5_set_use_admin_kdc;
+ krb5_set_warn_dest;
+ krb5_sname_to_principal;
+ krb5_sock_to_principal;
+ krb5_sockaddr2address;
+ krb5_sockaddr2port;
+ krb5_sockaddr_uninteresting;
+ krb5_std_usage;
+ krb5_storage_clear_flags;
+ krb5_storage_emem;
+ krb5_storage_free;
+ krb5_storage_from_data;
+ krb5_storage_from_fd;
+ krb5_storage_from_mem;
+ krb5_storage_from_readonly_mem;
+ krb5_storage_from_socket;
+ krb5_storage_fsync;
+ krb5_storage_get_byteorder;
+ krb5_storage_get_eof_code;
+ krb5_storage_is_flags;
+ krb5_storage_read;
+ krb5_storage_stdio_from_fd;
+ krb5_storage_seek;
+ krb5_storage_set_byteorder;
+ krb5_storage_set_eof_code;
+ krb5_storage_set_flags;
+ krb5_storage_set_max_alloc;
+ krb5_storage_to_data;
+ krb5_storage_truncate;
+ krb5_storage_write;
+ krb5_store_address;
+ krb5_store_addrs;
+ krb5_store_authdata;
+ krb5_store_bytes;
+ krb5_store_creds;
+ krb5_store_creds_tag;
+ krb5_store_data;
+ krb5_store_datalen;
+ krb5_store_int16;
+ krb5_store_int32;
+ krb5_store_int64;
+ krb5_store_int8;
+ krb5_store_keyblock;
+ krb5_store_principal;
+ krb5_store_string;
+ krb5_store_stringnl;
+ krb5_store_stringz;
+ krb5_store_times;
+ krb5_store_uint16;
+ krb5_store_uint32;
+ krb5_store_uint64;
+ krb5_store_uint8;
+ krb5_string_to_deltat;
+ krb5_string_to_enctype;
+ krb5_string_to_key;
+ krb5_string_to_key_data;
+ krb5_string_to_key_data_salt;
+ krb5_string_to_key_data_salt_opaque;
+ krb5_string_to_key_derived;
+ krb5_string_to_key_salt;
+ krb5_string_to_key_salt_opaque;
+ krb5_string_to_keysalts2;
+ krb5_string_to_keytype;
+ krb5_string_to_salttype;
+ krb5_ticket_get_authorization_data_type;
+ krb5_ticket_get_client;
+ krb5_ticket_get_endtime;
+ krb5_ticket_get_times;
+ krb5_ticket_get_server;
+ krb5_timeofday;
+ krb5_unparse_name;
+ krb5_unparse_name_fixed;
+ krb5_unparse_name_fixed_flags;
+ krb5_unparse_name_fixed_short;
+ krb5_unparse_name_flags;
+ krb5_unparse_name_short;
+ krb5_us_timeofday;
+ krb5_vabort;
+ krb5_vabortx;
+ krb5_verify_ap_req2;
+ krb5_verify_ap_req;
+ krb5_verify_authenticator_checksum;
+ krb5_verify_checksum;
+ krb5_verify_checksum_iov;
+ krb5_verify_init_creds;
+ krb5_verify_init_creds_opt_init;
+ krb5_verify_init_creds_opt_set_ap_req_nofail;
+ krb5_verify_opt_alloc;
+ krb5_verify_opt_free;
+ krb5_verify_opt_init;
+ krb5_verify_opt_set_ccache;
+ krb5_verify_opt_set_flags;
+ krb5_verify_opt_set_keytab;
+ krb5_verify_opt_set_secure;
+ krb5_verify_opt_set_service;
+ krb5_verify_user;
+ krb5_verify_user_lrealm;
+ krb5_verify_user_opt;
+ krb5_verr;
+ krb5_verrx;
+ krb5_vlog;
+ krb5_vlog_msg;
+ krb5_vprepend_error_message;
+ krb5_vset_error_message;
+ krb5_vset_error_string;
+ krb5_vwarn;
+ krb5_vwarnx;
+ krb5_warn;
+ krb5_warnx;
+ krb5_write_message;
+ krb5_write_priv_message;
+ krb5_write_safe_message;
+ krb5_xfree;
+ krb5_cccol_cursor_new;
+ krb5_cccol_cursor_next;
+ krb5_cccol_cursor_free;
+ krb5_cccol_get_default_ccname;
+
+ # com_err error tables
+ initialize_krb5_error_table_r;
+ initialize_krb5_error_table;
+ initialize_krb_error_table_r;
+ initialize_krb_error_table;
+ initialize_heim_error_table_r;
+ initialize_heim_error_table;
+ initialize_k524_error_table_r;
+ initialize_k524_error_table;
+ initialize_k5e1_error_table_r;
+ initialize_k5e1_error_table;
+
+ # variables
+ krb5_dcc_ops;
+ krb5_mcc_ops;
+ krb5_acc_ops;
+ krb5_fcc_ops;
+ krb5_krcc_ops;
+ krb5_scc_ops;
+ krb5_kcm_ops;
+ krb5_wrfkt_ops;
+ krb5_mkt_ops;
+ krb5_akf_ops;
+ krb5_any_ops;
+ heimdal_version;
+ heimdal_long_version;
+ krb5_config_file;
+ krb5_defkeyname;
+ krb5_cc_type_api;
+ krb5_cc_type_dcc;
+ krb5_cc_type_file;
+ krb5_cc_type_memory;
+ krb5_cc_type_kcm;
+ krb5_cc_type_keyring;
+ krb5_cc_type_scc;
+
+ # shared with HDB
+ _krb5_plugin_run_f;
+ _krb5_enctype_requires_random_salt;
+
+ # Shared with GSSAPI krb5
+ _krb5_crc_init_table;
+ _krb5_crc_update;
+ _krb5_get_krbtgt;
+ _krb5_build_authenticator;
+ _krb5_kt_client_default_name;
+ _krb5_have_debug;
+ _krb5_SP800_108_HMAC_KDF;
+ _krb5_get_ad;
+
+ # Shared with GSSAPI preauth wrapper
+ _krb5_init_creds_set_gss_mechanism;
+ _krb5_init_creds_get_gss_mechanism;
+ _krb5_init_creds_set_gss_cred;
+ _krb5_init_creds_get_gss_cred;
+ _krb5_init_creds_init_gss;
+
+ # Private init_creds API
+ _krb5_init_creds_get_cred_starttime;
+ _krb5_init_creds_get_cred_endtime;
+ _krb5_init_creds_get_cred_client;
+
+ # Shared with libkadm5
+ _krb5_load_plugins;
+ _krb5_unload_plugins;
+
+ # Shared with libkdc
+ _krb5_AES_SHA1_string_to_default_iterator;
+ _krb5_AES_SHA2_string_to_default_iterator;
+ _krb5_dh_group_ok;
+ _krb5_get_host_realm_int;
+ _krb5_get_int;
+ _krb5_get_int64;
+ _krb5_pac_sign;
+ _krb5_pac_get_attributes_info;
+ _krb5_pac_get_canon_principal;
+ _krb5_kdc_pac_sign_ticket;
+ _krb5_kdc_pac_ticket_parse;
+ _kdc_tkt_insert_pac;
+ _kdc_tkt_add_if_relevant_ad;
+ _krb5_parse_moduli;
+ _krb5_pk_kdf;
+ _krb5_pk_load_id;
+ _krb5_pk_mk_ContentInfo;
+ _krb5_pk_octetstring2key;
+ _krb5_plugin_run_f;
+ _krb5_principal2principalname;
+ _krb5_principalname2krb5_principal;
+ _krb5_kdcrep2krb5_principal;
+ _krb5_ticket2krb5_principal;
+ _krb5_put_int;
+ _krb5_s4u2self_to_checksumdata;
+ _krb5_HMAC_MD5_checksum;
+ _krb5_crypto_set_flags;
+ _krb5_make_pa_enc_challenge;
+ _krb5_validate_pa_enc_challenge;
+
+ # kinit helper
+ krb5_get_init_creds_opt_set_pkinit_user_certs;
+ krb5_pk_enterprise_cert;
+ krb5_process_last_request;
+ krb5_init_creds_init;
+ krb5_init_creds_set_service;
+ krb5_init_creds_set_fast_anon_pkinit;
+ _krb5_init_creds_set_fast_anon_pkinit_optimistic;
+ krb5_init_creds_set_fast_ccache;
+ krb5_init_creds_set_keytab;
+ krb5_init_creds_set_kdc_hostname;
+ krb5_init_creds_get;
+ krb5_init_creds_get_as_reply_key;
+ krb5_init_creds_get_creds;
+ krb5_init_creds_get_error;
+ krb5_init_creds_set_password;
+ krb5_init_creds_set_sitename;
+ krb5_init_creds_step;
+ krb5_init_creds_store;
+ krb5_init_creds_store_config;
+ krb5_init_creds_free;
+ krb5_init_creds_warn_user;
+
+ # testing
+ krb5_time_abs;
+ _krb5_aes_cts_encrypt;
+ _krb5_n_fold;
+ _krb5_expand_default_cc_name;
+ _krb5_expand_path_tokensv;
+ _krb5_expand_path_tokens;
+
+ # FAST
+ _krb5_fast_cf2;
+ _krb5_fast_armor_key;
+ _krb5_fast_explicit_armor_key;
+
+ # TGS
+ _krb5_find_capath;
+ _krb5_free_capath;
+
+ local:
+ *;
+};
diff --git a/third_party/heimdal/lib/krb5/version.c b/third_party/heimdal/lib/krb5/version.c
new file mode 100644
index 0000000..302854d
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/version.c
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+/* this is just to get a version stamp in the library file */
+
+#include "version.h"
+
diff --git a/third_party/heimdal/lib/krb5/warn.c b/third_party/heimdal/lib/krb5/warn.c
new file mode 100644
index 0000000..65a7db6
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/warn.c
@@ -0,0 +1,330 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if defined(_MSC_VER)
+# pragma warning(disable: 4646)
+# pragma warning(disable: 4716)
+#endif
+
+#include "krb5_locl.h"
+#include <err.h>
+
+static krb5_error_code _warnerr(krb5_context context, int do_errtext,
+ krb5_error_code code, int level, const char *fmt, va_list ap)
+ __attribute__ ((__format__ (__printf__, 5, 0)));
+
+static krb5_error_code
+_warnerr(krb5_context context, int do_errtext,
+ krb5_error_code code, int level, const char *fmt, va_list ap)
+{
+ if (do_errtext)
+ return heim_vwarn(context ? context->hcontext : NULL, code, fmt, ap);
+ else
+ return heim_vwarnx(context ? context->hcontext : NULL, fmt, ap);
+}
+
+#define FUNC_NORET(ETEXT, CODE, LEVEL) \
+ va_list ap; \
+ va_start(ap, fmt); \
+ (void) _warnerr(context, ETEXT, CODE, LEVEL, fmt, ap); \
+ va_end(ap);
+
+#undef __attribute__
+#define __attribute__(X)
+
+/**
+ * Log a warning to the log, default stderr, include the error from
+ * the last failure.
+ *
+ * @param context A Kerberos 5 context.
+ * @param code error code of the last error
+ * @param fmt message to print
+ * @param ap arguments
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_vwarn(krb5_context context, krb5_error_code code,
+ const char *fmt, va_list ap)
+ __attribute__ ((__format__ (__printf__, 3, 0)))
+{
+ return heim_vwarn(context ? context->hcontext : NULL, code, fmt, ap);
+}
+
+/**
+ * Log a warning to the log, default stderr, include the error from
+ * the last failure.
+ *
+ * @param context A Kerberos 5 context.
+ * @param code error code of the last error
+ * @param fmt message to print
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_warn(krb5_context context, krb5_error_code code, const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 3, 4)))
+{
+ krb5_error_code ret;
+ va_list ap;
+
+ va_start(ap, fmt);
+ ret = krb5_vwarn(context, code, fmt, ap);
+ va_end(ap);
+ return ret;
+}
+
+/**
+ * Log a warning to the log, default stderr.
+ *
+ * @param context A Kerberos 5 context.
+ * @param fmt message to print
+ * @param ap arguments
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_vwarnx(krb5_context context, const char *fmt, va_list ap)
+ __attribute__ ((__format__ (__printf__, 2, 0)))
+{
+ return heim_vwarnx(context ? context->hcontext : NULL, fmt, ap);
+}
+
+/**
+ * Log a warning to the log, default stderr.
+ *
+ * @param context A Kerberos 5 context.
+ * @param fmt message to print
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_warnx(krb5_context context, const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 2, 3)))
+{
+ krb5_error_code ret;
+ va_list ap;
+
+ va_start(ap, fmt);
+ ret = krb5_vwarnx(context, fmt, ap);
+ va_end(ap);
+ return ret;
+}
+
+/**
+ * Log a warning to the log, default stderr, include bthe error from
+ * the last failure and then exit.
+ *
+ * @param context A Kerberos 5 context
+ * @param eval the exit code to exit with
+ * @param code error code of the last error
+ * @param fmt message to print
+ * @param ap arguments
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_NORETURN_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verr(krb5_context context, int eval, krb5_error_code code,
+ const char *fmt, va_list ap)
+ __attribute__ ((__noreturn__, __format__ (__printf__, 4, 0)))
+{
+ _warnerr(context, 1, code, 0, fmt, ap);
+ exit(eval);
+ UNREACHABLE(return 0);
+}
+
+/**
+ * Log a warning to the log, default stderr, include bthe error from
+ * the last failure and then exit.
+ *
+ * @param context A Kerberos 5 context
+ * @param eval the exit code to exit with
+ * @param code error code of the last error
+ * @param fmt message to print
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_NORETURN_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_err(krb5_context context, int eval, krb5_error_code code,
+ const char *fmt, ...)
+ __attribute__ ((__noreturn__, __format__ (__printf__, 4, 5)))
+{
+ FUNC_NORET(1, code, 0);
+ exit(eval);
+ UNREACHABLE(return 0);
+}
+
+/**
+ * Log a warning to the log, default stderr, and then exit.
+ *
+ * @param context A Kerberos 5 context
+ * @param eval the exit code to exit with
+ * @param fmt message to print
+ * @param ap arguments
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_NORETURN_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verrx(krb5_context context, int eval, const char *fmt, va_list ap)
+ __attribute__ ((__noreturn__, __format__ (__printf__, 3, 0)))
+{
+ _warnerr(context, 0, 0, 0, fmt, ap);
+ exit(eval);
+ UNREACHABLE(return 0);
+}
+
+/**
+ * Log a warning to the log, default stderr, and then exit.
+ *
+ * @param context A Kerberos 5 context
+ * @param eval the exit code to exit with
+ * @param fmt message to print
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_NORETURN_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_errx(krb5_context context, int eval, const char *fmt, ...)
+ __attribute__ ((__noreturn__, __format__ (__printf__, 3, 4)))
+{
+ FUNC_NORET(0, 0, 0);
+ exit(eval);
+ UNREACHABLE(return 0);
+}
+
+/**
+ * Log a warning to the log, default stderr, include bthe error from
+ * the last failure and then abort.
+ *
+ * @param context A Kerberos 5 context
+ * @param code error code of the last error
+ * @param fmt message to print
+ * @param ap arguments
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_NORETURN_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_vabort(krb5_context context, krb5_error_code code,
+ const char *fmt, va_list ap)
+ __attribute__ ((__noreturn__, __format__ (__printf__, 3, 0)))
+{
+ _warnerr(context, 1, code, 0, fmt, ap);
+ abort();
+ UNREACHABLE(return 0);
+}
+
+/**
+ * Log a warning to the log, default stderr, include the error from
+ * the last failure and then abort.
+ *
+ * @param context A Kerberos 5 context
+ * @param code error code of the last error
+ * @param fmt message to print
+ * @param ... arguments for format string
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_NORETURN_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_abort(krb5_context context, krb5_error_code code, const char *fmt, ...)
+ __attribute__ ((__noreturn__, __format__ (__printf__, 3, 4)))
+{
+ FUNC_NORET(1, code, 0);
+ abort();
+ UNREACHABLE(return 0);
+}
+
+KRB5_LIB_NORETURN_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_vabortx(krb5_context context, const char *fmt, va_list ap)
+ __attribute__ ((__noreturn__, __format__ (__printf__, 2, 0)))
+{
+ _warnerr(context, 0, 0, 0, fmt, ap);
+ abort();
+ UNREACHABLE(return 0);
+}
+
+/**
+ * Log a warning to the log, default stderr, and then abort.
+ *
+ * @param context A Kerberos 5 context
+ * @param fmt printf format string of message to print
+ * @param ... arguments for format string
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_NORETURN_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_abortx(krb5_context context, const char *fmt, ...)
+ __attribute__ ((__noreturn__, __format__ (__printf__, 2, 3)))
+{
+ FUNC_NORET(0, 0, 0);
+ abort();
+ UNREACHABLE(return 0);
+}
+
+/**
+ * Set the default logging facility.
+ *
+ * @param context A Kerberos 5 context
+ * @param fac Facility to use for logging.
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_warn_dest(krb5_context context, krb5_log_facility *fac)
+{
+ return heim_set_warn_dest(context->hcontext, fac);
+}
+
+/**
+ * Get the default logging facility.
+ *
+ * @param context A Kerberos 5 context
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_log_facility * KRB5_LIB_CALL
+krb5_get_warn_dest(krb5_context context)
+{
+ return heim_get_warn_dest(context->hcontext);
+}
diff --git a/third_party/heimdal/lib/krb5/write_message.c b/third_party/heimdal/lib/krb5/write_message.c
new file mode 100644
index 0000000..8410046
--- /dev/null
+++ b/third_party/heimdal/lib/krb5/write_message.c
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "krb5_locl.h"
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_write_message (krb5_context context,
+ krb5_pointer p_fd,
+ krb5_data *data)
+{
+ uint32_t len;
+ uint8_t buf[4];
+ int ret;
+
+ len = data->length;
+ _krb5_put_int(buf, len, 4);
+ if (krb5_net_write (context, p_fd, buf, 4) != 4
+ || krb5_net_write (context, p_fd, data->data, len) != len) {
+ ret = errno;
+ krb5_set_error_message (context, ret, "write: %s", strerror(ret));
+ return ret;
+ }
+ return 0;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_write_priv_message(krb5_context context,
+ krb5_auth_context ac,
+ krb5_pointer p_fd,
+ krb5_data *data)
+{
+ krb5_error_code ret;
+ krb5_data packet;
+
+ ret = krb5_mk_priv (context, ac, data, &packet, NULL);
+ if(ret)
+ return ret;
+ ret = krb5_write_message(context, p_fd, &packet);
+ krb5_data_free(&packet);
+ return ret;
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_write_safe_message(krb5_context context,
+ krb5_auth_context ac,
+ krb5_pointer p_fd,
+ krb5_data *data)
+{
+ krb5_error_code ret;
+ krb5_data packet;
+ ret = krb5_mk_safe (context, ac, data, &packet, NULL);
+ if(ret)
+ return ret;
+ ret = krb5_write_message(context, p_fd, &packet);
+ krb5_data_free(&packet);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/libedit/COPYING b/third_party/heimdal/lib/libedit/COPYING
new file mode 100644
index 0000000..742f005
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/COPYING
@@ -0,0 +1,30 @@
+Copyright (c) 1992, 1993
+ The Regents of the University of California. All rights reserved.
+
+This code is derived from software contributed to Berkeley by
+Christos Zoulas of Cornell University.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+3. Neither the name of the University nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
+
diff --git a/third_party/heimdal/lib/libedit/ChangeLog b/third_party/heimdal/lib/libedit/ChangeLog
new file mode 100644
index 0000000..bdcb1e2
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/ChangeLog
@@ -0,0 +1,300 @@
+ * See also NetBSD changelog:
+ http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libedit
+
+2011-02-27 Jess Thrysoee
+
+ * version-info: 0:36:0
+
+ * all: sync with upstream source.
+
+2010-04-24 Jess Thrysoee
+
+ * version-info: 0:35:0
+
+ * all: sync with upstream source.
+ Now with UTF-8 support. To enable this run 'configure --enable-widec'.
+ For now an UTF-32 encoded wchar_t is required.
+ This requirement is met on NetBSD, Solaris and OS X for any UTF-8 locale,
+ and any system that define __STDC_ISO_10646__ (e.g. GNU libc on Linux).
+
+2009-09-23 Jess Thrysoee
+ * version-info: 0:34:0
+
+ * all: apply Apple patches from:
+ http://opensource.apple.com/source/libedit/libedit-11/patches
+
+2009-09-05 Jess Thrysoee
+
+ * version-info: 0:33:0
+
+ * all: Use predefined macro __sun to identify Solaris
+
+ * src/el.c: Ignore comment lines in .editrc
+
+2009-07-23 Jess Thrysoee
+
+ * version-info: 0:32:0
+
+ * all: sync with upstream source.
+
+2009-06-10 Jess Thrysoee
+
+ * version-info: 0:31:0
+
+ * all: sync with upstream source.
+
+2009-05-03 Jess Thrysoee
+
+ * version-info: 0:30:0
+
+ * all: sync with upstream source.
+
+2009-04-05 Jess Thrysoee
+
+ * version-info: 0:29:0
+
+ * all: sync with upstream source.
+
+2009-01-11 Jess Thrysoee
+
+ * version-info: 0:28:0
+
+ * all: sync with upstream source. MAJOR.MINOR version is now 3.0.
+ This is due to NetBSD changing time_t and dev_t to 64 bits. It does
+ not really effect this package.
+
+ * configure.ac: Remove '--enable-debug' configure flag. The autoconf way
+ to control flags is by specifying them when running configure,
+ e.g. 'CFLAGS="-O0 -g" ./configure'
+
+2008-07-12 Jess Thrysoee
+
+ * version-info: 0:27:0
+
+ * configure.ac: Added '--enable-debug' configure flag, to produce debugging
+ information.
+
+ * examples/fileman.c: cast stat struct members, st_nlink and st_size,
+ appropriately (see also 'man 2 stat'). Patch by Alex Elder.
+
+ * all: sync with upstream source. MINOR version is now 11.
+
+2007-08-31 Jess Thrysoee
+
+ * version-info: 0:26:0
+
+ * libedit.pc.in,Makefile.am,configure.ac,patches/extra_dist_list.sh:
+ Added pkg-config support for libedit. Patch by Masatake YAMATO.
+
+2007-08-13 Jess Thrysoee
+
+ * version-info: 0:25:0
+
+ * all: sync with upstream source.
+
+2007-03-02 Jess Thrysoee
+
+ * version-info: 0:24:0
+
+ * all: sync with upstream source.
+
+2006-10-22 Jess Thrysoee
+
+ * version-info: 0:23:0
+
+ * src/shlib_version: Upstream bumped minor version from 9 to 10.
+
+ * all: sync with upstream source. More readline functions.
+
+2006-10-22 Jess Thrysoee
+
+ * version-info: 0:22:0
+
+ * all: sync with upstream source.
+
+2006-08-29 Jess Thrysoee
+
+ * version-info: 0:21:0
+
+ * all: License cleanup. All 4-clause advertising BSD licenses has been
+ changed to the 3-clause version by upstream.
+
+ * src/fgetln.c: use src/tools/compat/fgetln.c instead of
+ othersrc/libexec/tnftpd/libnetbsd/fgetln.c
+
+2006-08-16 Jess Thrysoee
+
+ * version-info: 0:20:0
+
+ * all: sync with upstream source.
+
+2006-06-03 Jess Thrysoee
+
+ * version-info: 0:19:0
+
+ * COPYING: added global license file
+
+ * all: sync with upstream source.
+
+2006-02-13 Jess Thrysoee
+
+ * version-info: 0:18:0
+
+ * src/readline.c: Partial rl_getc_function support, patch by Kjeld Borch
+ Egevang.
+
+ * src/readline.c: Make write_history and read_history returncode readline
+ compatible. Upstream patch.
+
+2006-01-03 Jess Thrysoee
+
+ * version-info: 0:17:0
+
+ * patches/cvs_export.sh: strlcat.c and strlcpy.c was moved to
+ src/common/lib/libc/string in the upstream cvs repository.
+
+ * all: sync with upstream source.
+
+2005-10-22 Jess Thrysoee
+
+ * version-info: 0:16:0
+
+ * patches/*.patch, configure.ac: define SCCSID, undef LIBC_SCCS. Remove
+ fourteen cosmetic patches.
+
+ * all: sync with upstream source.
+
+2005-09-11 Jess Thrysoee
+
+ * version-info: 0:15:0
+
+ * src/Makefile.am: fix typo that meant generated files were distributes,
+ and make generated file targets dependent on the the 'makelist' input
+ files.
+
+ * all: sync with upstream source. This is just a manpage update
+
+2005-08-28 Jess Thrysoee
+
+ * version-info: 0:14:0
+
+ * src/sys.h: include config.h to avoid "redefinition of
+ `u_int32_t'". Patch by Norihiko Murase.
+
+ * src/search.c: explicitly include sys/types.h, because regex.h on
+ FreeBSD needs it and does not include it itself. Patch by Norihiko Murase.
+
+ * acinclude.m4: added EL_GETPW_R_DRAFT test and use AC_TRY_LINK instead
+ of AC_TRY_COMPILE. Suggested by Norihiko Murase.
+
+ * all: sync with upstream source.
+
+2005-08-16 Jess Thrysoee
+
+ * version-info: 0:13:0
+
+ * all: sync with upstream source.
+
+2005-08-05 Jess Thrysoee
+
+ * version-info: 0:12:0
+
+ * all: sync with upstream source.
+
+2005-07-24 Jess Thrysoee
+
+ * version-info: 0:11:0
+
+ * histedit.h, histedit.c, readline.c, editline/readline.h: From
+ upstream; added remove_history().
+
+2005-07-07 Jess Thrysoee
+
+ * version-info: 0:10:0
+
+ * history.c, key.c: From upstream source; Fix memory leaks found by
+ valgrind.
+
+2005-06-28 Jess Thrysoee
+
+ * version-info: 0:9:0
+
+ * src/readline.c: getpwent_r is not POSIX, always use getpwent.
+ Reported by Gerrit P. Haase.
+
+ * src/Makefile.am: Added libtool -no-undefined. This is needed on Cygwin
+ to get a shared editline library. Should not affect other platforms.
+ Suggested by Gerrit P. Haase.
+
+2005-06-15 Jess Thrysoee
+
+ * version-info: 0:8:0
+
+ * all: sync with upstream source.
+
+2005-06-01 Jess Thrysoee
+
+ * version-info: 0:7:0
+
+ * all: sync with upstream source.
+
+ * src/readline.c, src/filecomplete.c: Solaris use POSIX draft versions
+ of getpwent_r, getpwnam_r and getpwuid_r which return 'struct passwd *'.
+ Define HAVE_GETPW_R_POSIX if these functions are (non draft) POSIX
+ compatible. Patch by Julien Torrès.
+
+2005-05-28 Jess Thrysoee
+
+ * version-info: 0:6:0
+
+ * all: sync with upstream source.
+
+2005-03-11 Jess Thrysoee
+
+ * version-info: 0:5:0
+
+ * all: sync with upstream source.
+
+2004-12-07 Jess Thrysoee
+
+ * version-info: 0:4:0
+
+ * src/readline.c: d_namlen (in struct dirent) is not portable, always
+ use strlen. Patch by Scott Rankin.
+
+2004-11-27 Jess Thrysoee
+
+ * version-info: 0:3:0
+
+ * src/history.c: bug #26785 fixed upstream, removed local patch.
+
+2004-11-06 Jess Thrysoee
+
+ * version-info: 0:2:0
+
+ * all: sync with upstream source.
+
+ * doc/Makefile.am: If mdoc2man fails, remove empty file. Patch by
+ Darren Tucker.
+
+2004-10-14 Jess Thrysoee
+
+ * version-info: 0:1:0
+
+ * doc/Makefile.am: 'make install' twice fails. Remove old links before
+ trying to link the man pages. Patch by Rick Richardson.
+
+2004-09-28 Jess Thrysoee
+
+ * version-info: 0:0:0
+
+ * acinclude.m4 configure.ac src/Makefile.am: Adhere to
+ LibTools library interface versions recommendation.
+ http://www.gnu.org/software/libtool/manual.html#SEC32
+
+ * doc/Makefile.am: name all manpage links as el_* (e.g. el_history.3)
+ to avoid conflicts.
+
+2004-09-08 Jess Thrysoee
+
+ * all: Initial package.
diff --git a/third_party/heimdal/lib/libedit/INSTALL b/third_party/heimdal/lib/libedit/INSTALL
new file mode 100644
index 0000000..54caf7c
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/INSTALL
@@ -0,0 +1,229 @@
+Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002 Free Software
+Foundation, Inc.
+
+ This file is free documentation; the Free Software Foundation gives
+unlimited permission to copy, distribute and modify it.
+
+Basic Installation
+==================
+
+ These are generic installation instructions.
+
+ The `configure' shell script attempts to guess correct values for
+various system-dependent variables used during compilation. It uses
+those values to create a `Makefile' in each directory of the package.
+It may also create one or more `.h' files containing system-dependent
+definitions. Finally, it creates a shell script `config.status' that
+you can run in the future to recreate the current configuration, and a
+file `config.log' containing compiler output (useful mainly for
+debugging `configure').
+
+ It can also use an optional file (typically called `config.cache'
+and enabled with `--cache-file=config.cache' or simply `-C') that saves
+the results of its tests to speed up reconfiguring. (Caching is
+disabled by default to prevent problems with accidental use of stale
+cache files.)
+
+ If you need to do unusual things to compile the package, please try
+to figure out how `configure' could check whether to do them, and mail
+diffs or instructions to the address given in the `README' so they can
+be considered for the next release. If you are using the cache, and at
+some point `config.cache' contains results you don't want to keep, you
+may remove or edit it.
+
+ The file `configure.ac' (or `configure.in') is used to create
+`configure' by a program called `autoconf'. You only need
+`configure.ac' if you want to change it or regenerate `configure' using
+a newer version of `autoconf'.
+
+The simplest way to compile this package is:
+
+ 1. `cd' to the directory containing the package's source code and type
+ `./configure' to configure the package for your system. If you're
+ using `csh' on an old version of System V, you might need to type
+ `sh ./configure' instead to prevent `csh' from trying to execute
+ `configure' itself.
+
+ Running `configure' takes awhile. While running, it prints some
+ messages telling which features it is checking for.
+
+ 2. Type `make' to compile the package.
+
+ 3. Optionally, type `make check' to run any self-tests that come with
+ the package.
+
+ 4. Type `make install' to install the programs and any data files and
+ documentation.
+
+ 5. You can remove the program binaries and object files from the
+ source code directory by typing `make clean'. To also remove the
+ files that `configure' created (so you can compile the package for
+ a different kind of computer), type `make distclean'. There is
+ also a `make maintainer-clean' target, but that is intended mainly
+ for the package's developers. If you use it, you may have to get
+ all sorts of other programs in order to regenerate files that came
+ with the distribution.
+
+Compilers and Options
+=====================
+
+ Some systems require unusual options for compilation or linking that
+the `configure' script does not know about. Run `./configure --help'
+for details on some of the pertinent environment variables.
+
+ You can give `configure' initial values for configuration parameters
+by setting variables in the command line or in the environment. Here
+is an example:
+
+ ./configure CC=c89 CFLAGS=-O2 LIBS=-lposix
+
+ *Note Defining Variables::, for more details.
+
+Compiling For Multiple Architectures
+====================================
+
+ You can compile the package for more than one kind of computer at the
+same time, by placing the object files for each architecture in their
+own directory. To do this, you must use a version of `make' that
+supports the `VPATH' variable, such as GNU `make'. `cd' to the
+directory where you want the object files and executables to go and run
+the `configure' script. `configure' automatically checks for the
+source code in the directory that `configure' is in and in `..'.
+
+ If you have to use a `make' that does not support the `VPATH'
+variable, you have to compile the package for one architecture at a
+time in the source code directory. After you have installed the
+package for one architecture, use `make distclean' before reconfiguring
+for another architecture.
+
+Installation Names
+==================
+
+ By default, `make install' will install the package's files in
+`/usr/local/bin', `/usr/local/man', etc. You can specify an
+installation prefix other than `/usr/local' by giving `configure' the
+option `--prefix=PATH'.
+
+ You can specify separate installation prefixes for
+architecture-specific files and architecture-independent files. If you
+give `configure' the option `--exec-prefix=PATH', the package will use
+PATH as the prefix for installing programs and libraries.
+Documentation and other data files will still use the regular prefix.
+
+ In addition, if you use an unusual directory layout you can give
+options like `--bindir=PATH' to specify different values for particular
+kinds of files. Run `configure --help' for a list of the directories
+you can set and what kinds of files go in them.
+
+ If the package supports it, you can cause programs to be installed
+with an extra prefix or suffix on their names by giving `configure' the
+option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'.
+
+Optional Features
+=================
+
+ Some packages pay attention to `--enable-FEATURE' options to
+`configure', where FEATURE indicates an optional part of the package.
+They may also pay attention to `--with-PACKAGE' options, where PACKAGE
+is something like `gnu-as' or `x' (for the X Window System). The
+`README' should mention any `--enable-' and `--with-' options that the
+package recognizes.
+
+ For packages that use the X Window System, `configure' can usually
+find the X include and library files automatically, but if it doesn't,
+you can use the `configure' options `--x-includes=DIR' and
+`--x-libraries=DIR' to specify their locations.
+
+Specifying the System Type
+==========================
+
+ There may be some features `configure' cannot figure out
+automatically, but needs to determine by the type of machine the package
+will run on. Usually, assuming the package is built to be run on the
+_same_ architectures, `configure' can figure that out, but if it prints
+a message saying it cannot guess the machine type, give it the
+`--build=TYPE' option. TYPE can either be a short name for the system
+type, such as `sun4', or a canonical name which has the form:
+
+ CPU-COMPANY-SYSTEM
+
+where SYSTEM can have one of these forms:
+
+ OS KERNEL-OS
+
+ See the file `config.sub' for the possible values of each field. If
+`config.sub' isn't included in this package, then this package doesn't
+need to know the machine type.
+
+ If you are _building_ compiler tools for cross-compiling, you should
+use the `--target=TYPE' option to select the type of system they will
+produce code for.
+
+ If you want to _use_ a cross compiler, that generates code for a
+platform different from the build platform, you should specify the
+"host" platform (i.e., that on which the generated programs will
+eventually be run) with `--host=TYPE'.
+
+Sharing Defaults
+================
+
+ If you want to set default values for `configure' scripts to share,
+you can create a site shell script called `config.site' that gives
+default values for variables like `CC', `cache_file', and `prefix'.
+`configure' looks for `PREFIX/share/config.site' if it exists, then
+`PREFIX/etc/config.site' if it exists. Or, you can set the
+`CONFIG_SITE' environment variable to the location of the site script.
+A warning: not all `configure' scripts look for a site script.
+
+Defining Variables
+==================
+
+ Variables not defined in a site shell script can be set in the
+environment passed to `configure'. However, some packages may run
+configure again during the build, and the customized values of these
+variables may be lost. In order to avoid this problem, you should set
+them in the `configure' command line, using `VAR=value'. For example:
+
+ ./configure CC=/usr/local2/bin/gcc
+
+will cause the specified gcc to be used as the C compiler (unless it is
+overridden in the site shell script).
+
+`configure' Invocation
+======================
+
+ `configure' recognizes the following options to control how it
+operates.
+
+`--help'
+`-h'
+ Print a summary of the options to `configure', and exit.
+
+`--version'
+`-V'
+ Print the version of Autoconf used to generate the `configure'
+ script, and exit.
+
+`--cache-file=FILE'
+ Enable the cache: use and save the results of the tests in FILE,
+ traditionally `config.cache'. FILE defaults to `/dev/null' to
+ disable caching.
+
+`--config-cache'
+`-C'
+ Alias for `--cache-file=config.cache'.
+
+`--quiet'
+`--silent'
+`-q'
+ Do not print messages saying which checks are being made. To
+ suppress all normal output, redirect it to `/dev/null' (any error
+ messages will still be shown).
+
+`--srcdir=DIR'
+ Look for the package's source code in directory DIR. Usually
+ `configure' can determine that directory automatically.
+
+`configure' also accepts some other, not widely useful, options. Run
+`configure --help' for more details.
+
diff --git a/third_party/heimdal/lib/libedit/Makefile.am b/third_party/heimdal/lib/libedit/Makefile.am
new file mode 100644
index 0000000..4018edc
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/Makefile.am
@@ -0,0 +1,9 @@
+
+AUTOMAKE_OPTIONS = foreign
+
+#SUBDIRS = src examples doc
+SUBDIRS = src
+
+#EXTRA_DIST = libedit.pc.in
+#pkgconfigdir = $(libdir)/pkgconfig
+#pkgconfig_DATA = libedit.pc
diff --git a/third_party/heimdal/lib/libedit/THANKS b/third_party/heimdal/lib/libedit/THANKS
new file mode 100644
index 0000000..98ad22b
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/THANKS
@@ -0,0 +1 @@
+Thanks to the NetBSD Project maintainers of libedit!
diff --git a/third_party/heimdal/lib/libedit/acinclude.m4 b/third_party/heimdal/lib/libedit/acinclude.m4
new file mode 100644
index 0000000..51b4ddb
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/acinclude.m4
@@ -0,0 +1,66 @@
+
+dnl
+dnl read lib version from file (and trim trailing newline)
+dnl
+define([EL_RELEASE], [patsubst(esyscmd([. src/shlib_version; echo $major.$minor]), [
+])])
+
+dnl
+dnl read cvsexport timestamp from file (and trim trailing newline)
+dnl
+define([EL_TIMESTAMP], [patsubst(esyscmd([date +"%Y%m%d"]), [
+])])
+
+
+dnl
+dnl NetBSD use the -mdoc macro package for manpages, but e.g.
+dnl AIX and Solaris only support the -man package.
+dnl
+AC_DEFUN([EL_MANTYPE],
+[
+ MANTYPE=
+ TestPath="/usr/bin${PATH_SEPARATOR}/usr/ucb"
+ AC_PATH_PROGS(NROFF, nroff awf, /bin/false, $TestPath)
+ if ${NROFF} -mdoc ${srcdir}/doc/editrc.5.roff >/dev/null 2>&1; then
+ MANTYPE=mdoc
+ fi
+ AC_SUBST(MANTYPE)
+])
+
+
+dnl
+dnl Check if getpwnam_r and getpwuid_r are POSIX.1 compatible
+dnl POSIX draft version returns 'struct passwd *' (used on Solaris)
+dnl NOTE: getpwent_r is not POSIX so we always use getpwent
+dnl
+AC_DEFUN([EL_GETPW_R_POSIX],
+[
+ AC_MSG_CHECKING([whether getpwnam_r and getpwuid_r are posix like])
+ # The prototype for the POSIX version is:
+ # int getpwnam_r(char *, struct passwd *, char *, size_t, struct passwd **)
+ # int getpwuid_r(uid_t, struct passwd *, char *, size_t, struct passwd **);
+ AC_TRY_LINK([#include <stdlib.h>
+ #include <sys/types.h>
+ #include <pwd.h>],
+ [getpwnam_r(NULL, NULL, NULL, (size_t)0, NULL);
+ getpwuid_r((uid_t)0, NULL, NULL, (size_t)0, NULL);],
+ [AC_DEFINE([HAVE_GETPW_R_POSIX], 1, [Define to 1 if you have getpwnam_r and getpwuid_r that are POSIX.1 compatible.])
+ AC_MSG_RESULT(yes)],
+ [AC_MSG_RESULT(no)])
+])
+
+AC_DEFUN([EL_GETPW_R_DRAFT],
+[
+ AC_MSG_CHECKING([whether getpwnam_r and getpwuid_r are posix _draft_ like])
+ # The prototype for the POSIX draft version is:
+ # struct passwd *getpwuid_r(uid_t, struct passwd *, char *, int);
+ # struct passwd *getpwnam_r(char *, struct passwd *, char *, int);
+ AC_TRY_LINK([#include <stdlib.h>
+ #include <sys/types.h>
+ #include <pwd.h>],
+ [getpwnam_r(NULL, NULL, NULL, (size_t)0);
+ getpwuid_r((uid_t)0, NULL, NULL, (size_t)0);],
+ [AC_DEFINE([HAVE_GETPW_R_DRAFT], 1, [Define to 1 if you have getpwnam_r and getpwuid_r that are draft POSIX.1 versions.])
+ AC_MSG_RESULT(yes)],
+ [AC_MSG_RESULT(no)])
+])
diff --git a/third_party/heimdal/lib/libedit/config.h.in b/third_party/heimdal/lib/libedit/config.h.in
new file mode 100644
index 0000000..059e5ab
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/config.h.in
@@ -0,0 +1,218 @@
+/* config.h.in. Generated from configure.ac by autoheader. */
+
+/* Define to 1 if you have the <curses.h> header file. */
+#undef HAVE_CURSES_H
+
+/* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
+ */
+#undef HAVE_DIRENT_H
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#undef HAVE_DLFCN_H
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#undef HAVE_FCNTL_H
+
+/* Define to 1 if you have the `fork' function. */
+#undef HAVE_FORK
+
+/* Define to 1 if you have the `getline' function. */
+#undef HAVE_GETLINE
+
+/* Define to 1 if you have getpwnam_r and getpwuid_r that are draft POSIX.1
+ versions. */
+#undef HAVE_GETPW_R_DRAFT
+
+/* Define to 1 if you have getpwnam_r and getpwuid_r that are POSIX.1
+ compatible. */
+#undef HAVE_GETPW_R_POSIX
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#undef HAVE_INTTYPES_H
+
+/* Define to 1 if you have the `isascii' function. */
+#undef HAVE_ISASCII
+
+/* Define to 1 if you have the `issetugid' function. */
+#undef HAVE_ISSETUGID
+
+/* Define to 1 if you have the `curses' library (-lcurses). */
+#undef HAVE_LIBCURSES
+
+/* Define to 1 if you have the `ncurses' library (-lncurses). */
+#undef HAVE_LIBNCURSES
+
+/* Define to 1 if you have the `tinfo' library (-ltinfo). */
+#undef HAVE_LIBTINFO
+
+/* Define to 1 if you have the <limits.h> header file. */
+#undef HAVE_LIMITS_H
+
+/* Define to 1 if you have the <memory.h> header file. */
+#undef HAVE_MEMORY_H
+
+/* Define to 1 if you have the <ncurses.h> header file. */
+#undef HAVE_NCURSES_H
+
+/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
+#undef HAVE_NDIR_H
+
+/* Define to 1 if if your system has SIZE_MAX */
+#undef HAVE_SIZE_MAX
+
+/* Define to 1 if `stat' has the bug that it succeeds when given the
+ zero-length file name argument. */
+#undef HAVE_STAT_EMPTY_STRING_BUG
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#undef HAVE_STDINT_H
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#undef HAVE_STDLIB_H
+
+/* Define to 1 if you have the <strings.h> header file. */
+#undef HAVE_STRINGS_H
+
+/* Define to 1 if you have the <string.h> header file. */
+#undef HAVE_STRING_H
+
+/* Define to 1 if struct dirent has member d_namlen */
+#undef HAVE_STRUCT_DIRENT_D_NAMLEN
+
+/* Define to 1 if you have the <sys/cdefs.h> header file. */
+#undef HAVE_SYS_CDEFS_H
+
+/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
+ */
+#undef HAVE_SYS_DIR_H
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#undef HAVE_SYS_IOCTL_H
+
+/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
+ */
+#undef HAVE_SYS_NDIR_H
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#undef HAVE_SYS_PARAM_H
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#undef HAVE_SYS_STAT_H
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#undef HAVE_SYS_TYPES_H
+
+/* Define to 1 if you have <sys/wait.h> that is POSIX.1 compatible. */
+#undef HAVE_SYS_WAIT_H
+
+/* Define to 1 if you have the <term.h> header file. */
+#undef HAVE_TERM_H
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#undef HAVE_UNISTD_H
+
+/* Define to 1 if the system has the type `u_int32_t'. */
+#undef HAVE_U_INT32_T
+
+/* Define to 1 if you have the `vfork' function. */
+#undef HAVE_VFORK
+
+/* Define to 1 if you have the <vfork.h> header file. */
+#undef HAVE_VFORK_H
+
+/* Define to 1 if you have the `wcsdup' function. */
+#undef HAVE_WCSDUP
+
+/* Define to 1 if `fork' works. */
+#undef HAVE_WORKING_FORK
+
+/* Define to 1 if `vfork' works. */
+#undef HAVE_WORKING_VFORK
+
+/* Define to 1 if `lstat' dereferences a symlink specified with a trailing
+ slash. */
+#undef LSTAT_FOLLOWS_SLASHED_SYMLINK
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#undef LT_OBJDIR
+
+/* Name of package */
+#undef PACKAGE
+
+/* Define to the address where bug reports for this package should be sent. */
+#undef PACKAGE_BUGREPORT
+
+/* Define to the full name of this package. */
+#undef PACKAGE_NAME
+
+/* Define to the full name and version of this package. */
+#undef PACKAGE_STRING
+
+/* Define to the one symbol short name of this package. */
+#undef PACKAGE_TARNAME
+
+/* Define to the home page for this package. */
+#undef PACKAGE_URL
+
+/* Define to the version of this package. */
+#undef PACKAGE_VERSION
+
+/* Define as the return type of signal handlers (`int' or `void'). */
+#undef RETSIGTYPE
+
+/* Define to 1 if you have the ANSI C header files. */
+#undef STDC_HEADERS
+
+/* Enable extensions on AIX 3, Interix. */
+#ifndef _ALL_SOURCE
+# undef _ALL_SOURCE
+#endif
+/* Enable GNU extensions on systems that have them. */
+#ifndef _GNU_SOURCE
+# undef _GNU_SOURCE
+#endif
+/* Enable threading extensions on Solaris. */
+#ifndef _POSIX_PTHREAD_SEMANTICS
+# undef _POSIX_PTHREAD_SEMANTICS
+#endif
+/* Enable extensions on HP NonStop. */
+#ifndef _TANDEM_SOURCE
+# undef _TANDEM_SOURCE
+#endif
+/* Enable general extensions on Solaris. */
+#ifndef __EXTENSIONS__
+# undef __EXTENSIONS__
+#endif
+
+
+/* Version number of package */
+#undef VERSION
+
+/* Define to 1 if on MINIX. */
+#undef _MINIX
+
+/* Define to 2 if the system does not provide POSIX.1 features except with
+ this defined. */
+#undef _POSIX_1_SOURCE
+
+/* Define to 1 if you need to in order for `stat' and other things to work. */
+#undef _POSIX_SOURCE
+
+/* Define to empty if `const' does not conform to ANSI C. */
+#undef const
+
+/* Define to `int' if <sys/types.h> does not define. */
+#undef pid_t
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+#undef size_t
+
+/* Define as `fork' if `vfork' does not work. */
+#undef vfork
+
+
+#include "sys.h"
+#define SCCSID
+#undef LIBC_SCCS
+#define lint
+
diff --git a/third_party/heimdal/lib/libedit/configure.ac b/third_party/heimdal/lib/libedit/configure.ac
new file mode 100644
index 0000000..b94bafc
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/configure.ac
@@ -0,0 +1,111 @@
+# -*- Autoconf -*-
+# Process this file with autoconf to produce a configure script.
+#
+# Compile with debug symbols:
+# CFLAGS="-ggdb -pedandic -O0" ./configure
+# CFLAGS="-ggdb -Wall -Wextra -pedantic -O0" ./configure
+#
+# Verbose output can be enabled with
+# "./configure --disable-silent-rules" or "make V=1"
+#
+
+AC_PREREQ(2.61)
+AC_INIT(libedit, [EL_RELEASE],, libedit-[EL_TIMESTAMP])
+AC_CONFIG_SRCDIR([src/el.c])
+AC_CONFIG_HEADER([config.h])
+
+# features of Posix that are extensions to C (define _GNU_SOURCE)
+AC_USE_SYSTEM_EXTENSIONS
+
+AM_INIT_AUTOMAKE
+AM_MAINTAINER_MODE
+AC_PROG_LIBTOOL
+
+# libtool -version-info
+AC_SUBST(LT_VERSION, [0:36:0])
+
+m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])
+
+# Checks for programs.
+AC_PROG_CC_C99
+#AC_PROG_CC
+AC_PROG_LN_S
+AC_PROG_AWK
+EL_MANTYPE
+
+
+AC_CHECK_LIB(curses, tgetent,,
+ [AC_CHECK_LIB(ncurses, tgetent,,
+ [AC_CHECK_LIB(tinfo, tgetent,,
+ [AC_MSG_ERROR([libcurses, libncurses, or tinfo are required!])] )] )] )
+
+
+# Checks for header files.
+AC_HEADER_DIRENT
+AC_HEADER_STDC
+AC_HEADER_SYS_WAIT
+AC_CHECK_HEADERS([fcntl.h limits.h stdint.h stdlib.h string.h sys/ioctl.h sys/param.h unistd.h curses.h ncurses.h sys/cdefs.h])
+
+AC_CHECK_HEADER([termios.h], [], [AC_MSG_ERROR([termios.h is required!])],[])
+
+## include curses.h to prevent "Present But Cannot Be Compiled"
+AC_CHECK_HEADERS([term.h],,,
+[[#if HAVE_CURSES_H
+# include <curses.h>
+#elif HAVE_NCURSES_H
+# include <ncurses.h>
+#endif
+]])
+
+# Checks for typedefs, structures, and compiler characteristics.
+AC_C_CONST
+AC_TYPE_PID_T
+AC_TYPE_SIZE_T
+AC_CHECK_TYPES([u_int32_t])
+
+AC_TRY_COMPILE([
+#include <limits.h>
+#include <stddef.h>
+#if HAVE_STDINT_H
+# include <stdint.h>
+#endif
+],
+[size_t x = SIZE_MAX;],
+[have_size_max=yes],
+[have_size_max=no])
+if test "$have_size_max" = yes; then
+ AC_DEFINE([HAVE_SIZE_MAX], [1],
+ [Define to 1 if if your system has SIZE_MAX])
+fi
+
+# Checks for library functions.
+AC_FUNC_FORK
+AC_PROG_GCC_TRADITIONAL
+## _AIX is offended by rpl_malloc and rpl_realloc
+#AC_FUNC_MALLOC
+#AC_FUNC_REALLOC
+AC_TYPE_SIGNAL
+AC_FUNC_STAT
+AC_CHECK_FUNCS([getline isascii issetugid wcsdup])
+EL_GETPW_R_POSIX
+EL_GETPW_R_DRAFT
+
+AC_CHECK_MEMBER(struct dirent.d_namlen,
+AC_DEFINE([HAVE_STRUCT_DIRENT_D_NAMLEN],[1],
+[Define to 1 if struct dirent has member d_namlen]),,
+[#if HAVE_DIRENT_H
+#include <dirent.h>
+#endif
+])
+
+AH_BOTTOM([
+#include "sys.h"
+#define SCCSID
+#undef LIBC_SCCS
+#define lint
+])
+
+AC_CONFIG_FILES([Makefile
+ src/Makefile
+])
+AC_OUTPUT
diff --git a/third_party/heimdal/lib/libedit/doc/Makefile.am b/third_party/heimdal/lib/libedit/doc/Makefile.am
new file mode 100644
index 0000000..dfdf841
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/doc/Makefile.am
@@ -0,0 +1,33 @@
+
+EL_MANS = editline.3 editrc.5
+
+man_MANS = $(EL_MANS)
+
+EL_MAN_LINKS = el_init.3 el_end.3 el_reset.3 el_gets.3 el_getc.3 \
+ el_push.3 el_parse.3 el_set.3 el_get.3 el_source.3 \
+ el_resize.3 el_line.3 el_insertstr.3 el_deletestr.3 \
+ el_history_init.3 el_history_end.3 el_history.3 el_tok_init.3 \
+ el_tok_end.3 el_tok_reset.3 el_tok_line.3 el_tok_str.3
+
+install-data-hook: $(EL_MAN_LINKS)
+
+$(EL_MAN_LINKS):
+ (cd $(DESTDIR)$(man3dir) && rm -f $@ && $(LN_S) editline.3 $@)
+
+$(EL_MANS):
+ @if test "$(MANTYPE)" = "mdoc"; then\
+ cp $(srcdir)/$@.roff $@;\
+ else\
+ $(AWK) -f $(srcdir)/mdoc2man.awk $(srcdir)/$@.roff > $@ || rm -f $@;\
+ fi;
+
+uninstall-local:
+ (cd $(DESTDIR)$(man3dir) && rm -f $(EL_MAN_LINKS))
+
+CLEANFILES = $(EL_MANS)
+EXTRA_DIST = editline.3.roff editrc.5.roff mdoc2man.awk
+
+changelog.txt: ../ChangeLog
+ @sed 's/@/ (at)/g; s/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g;' $(srcdir)/$< > $@;
+
+
diff --git a/third_party/heimdal/lib/libedit/doc/editline.3.roff b/third_party/heimdal/lib/libedit/doc/editline.3.roff
new file mode 100644
index 0000000..9fe455d
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/doc/editline.3.roff
@@ -0,0 +1,883 @@
+.\" $NetBSD: editline.3,v 1.74 2010/12/16 17:42:28 wiz Exp $
+.\"
+.\" Copyright (c) 1997-2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This file was contributed to The NetBSD Foundation by Luke Mewburn.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+.\" ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+.\" TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+.\" BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+.\" POSSIBILITY OF SUCH DAMAGE.
+.\"
+.Dd January 3, 2010
+.Dt EDITLINE 3
+.Os
+.Sh NAME
+.Nm editline ,
+.Nm el_init ,
+.Nm el_end ,
+.Nm el_reset ,
+.Nm el_gets ,
+.Nm el_wgets ,
+.Nm el_getc ,
+.Nm el_wgetc ,
+.Nm el_push ,
+.Nm el_wpush ,
+.Nm el_parse ,
+.Nm el_wparse ,
+.Nm el_set ,
+.Nm el_wset ,
+.Nm el_get ,
+.Nm el_wget ,
+.Nm el_source ,
+.Nm el_resize ,
+.Nm el_line ,
+.Nm el_wline ,
+.Nm el_insertstr ,
+.Nm el_winsertstr ,
+.Nm el_deletestr ,
+.Nm el_wdeletestr ,
+.Nm history_init ,
+.Nm history_winit ,
+.Nm history_end ,
+.Nm history_wend ,
+.Nm history ,
+.Nm history_w ,
+.Nm tok_init ,
+.Nm tok_winit ,
+.Nm tok_end ,
+.Nm tok_wend ,
+.Nm tok_reset ,
+.Nm tok_wreset ,
+.Nm tok_line ,
+.Nm tok_wline ,
+.Nm tok_str
+.Nm tok_wstr
+.Nd line editor, history and tokenization functions
+.Sh LIBRARY
+.Lb libedit
+.Sh SYNOPSIS
+.In histedit.h
+.Ft EditLine *
+.Fn el_init "const char *prog" "FILE *fin" "FILE *fout" "FILE *ferr"
+.Ft void
+.Fn el_end "EditLine *e"
+.Ft void
+.Fn el_reset "EditLine *e"
+.Ft const char *
+.Fn el_gets "EditLine *e" "int *count"
+.Ft const wchar_t *
+.Fn el_wgets "EditLine *e" "int *count"
+.Ft int
+.Fn el_getc "EditLine *e" "char *ch"
+.Ft int
+.Fn el_wgetc "EditLine *e" "wchar_t *ch"
+.Ft void
+.Fn el_push "EditLine *e" "const char *str"
+.Ft void
+.Fn el_wpush "EditLine *e" "const wchar_t *str"
+.Ft int
+.Fn el_parse "EditLine *e" "int argc" "const char *argv[]"
+.Ft int
+.Fn el_wparse "EditLine *e" "int argc" "const wchar_t *argv[]"
+.Ft int
+.Fn el_set "EditLine *e" "int op" "..."
+.Ft int
+.Fn el_wset "EditLine *e" "int op" "..."
+.Ft int
+.Fn el_get "EditLine *e" "int op" "..."
+.Ft int
+.Fn el_wget "EditLine *e" "int op" "..."
+.Ft int
+.Fn el_source "EditLine *e" "const char *file"
+.Ft void
+.Fn el_resize "EditLine *e"
+.Ft const LineInfo *
+.Fn el_line "EditLine *e"
+.Ft int
+.Fn el_insertstr "EditLine *e" "const char *str"
+.Ft int
+.Fn el_winsertstr "EditLine *e" "const wchar_t *str"
+.Ft void
+.Fn el_deletestr "EditLine *e" "int count"
+.Ft void
+.Fn el_wdeletestr "EditLine *e" "int count"
+.Ft History *
+.Fn history_init
+.Ft HistoryW *
+.Fn history_winit
+.Ft void
+.Fn history_end "History *h"
+.Ft void
+.Fn history_wend "HistoryW *h"
+.Ft int
+.Fn history "History *h" "HistEvent *ev" "int op" "..."
+.Ft int
+.Fn history_w "HistoryW *h" "HistEventW *ev" "int op" "..."
+.Ft Tokenizer *
+.Fn tok_init "const char *IFS"
+.Ft TokenizerW *
+.Fn tok_winit "const wchar_t *IFS"
+.Ft void
+.Fn tok_end "Tokenizer *t"
+.Ft void
+.Fn tok_wend "TokenizerW *t"
+.Ft void
+.Fn tok_reset "Tokenizer *t"
+.Ft void
+.Fn tok_wreset "TokenizerW *t"
+.Ft int
+.Fn tok_line "Tokenizer *t" "const LineInfo *li" "int *argc" "const char **argv[]" "int *cursorc" "int *cursoro"
+.Ft int
+.Fn tok_wline "TokenizerW *t" "const LineInfoW *li" "int *argc" "const wchar_t **argv[]" "int *cursorc" "int *cursoro"
+.Ft int
+.Fn tok_str "Tokenizer *t" "const char *str" "int *argc" "const char **argv[]"
+.Ft int
+.Fn tok_wstr "TokenizerW *t" "const wchar_t *str" "int *argc" "const wchar_t **argv[]"
+.Sh DESCRIPTION
+The
+.Nm
+library provides generic line editing, history and tokenization functions,
+similar to those found in
+.Xr sh 1 .
+.Pp
+These functions are available in the
+.Nm libedit
+library (which needs the
+.Nm libtermcap
+library).
+Programs should be linked with
+.Fl ledit ltermcap .
+.Sh LINE EDITING FUNCTIONS
+The line editing functions use a common data structure,
+.Fa EditLine ,
+which is created by
+.Fn el_init
+and freed by
+.Fn el_end .
+.Pp
+The wide-character functions behave the same way as their narrow
+counterparts.
+.Pp
+The following functions are available:
+.Bl -tag -width 4n
+.It Fn el_init
+Initialise the line editor, and return a data structure
+to be used by all other line editing functions.
+.Fa prog
+is the name of the invoking program, used when reading the
+.Xr editrc 5
+file to determine which settings to use.
+.Fa fin ,
+.Fa fout
+and
+.Fa ferr
+are the input, output, and error streams (respectively) to use.
+In this documentation, references to
+.Dq the tty
+are actually to this input/output stream combination.
+.It Fn el_end
+Clean up and finish with
+.Fa e ,
+assumed to have been created with
+.Fn el_init .
+.It Fn el_reset
+Reset the tty and the parser.
+This should be called after an error which may have upset the tty's
+state.
+.It Fn el_gets
+Read a line from the tty.
+.Fa count
+is modified to contain the number of characters read.
+Returns the line read if successful, or
+.Dv NULL
+if no characters were read or if an error occurred.
+If an error occurred,
+.Fa count
+is set to \-1 and
+.Dv errno
+contains the error code that caused it.
+The return value may not remain valid across calls to
+.Fn el_gets
+and must be copied if the data is to be retained.
+.It Fn el_getc
+Read a character from the tty.
+.Fa ch
+is modified to contain the character read.
+Returns the number of characters read if successful, \-1 otherwise.
+.It Fn el_push
+Pushes
+.Fa str
+back onto the input stream.
+This is used by the macro expansion mechanism.
+Refer to the description of
+.Ic bind
+.Fl s
+in
+.Xr editrc 5
+for more information.
+.It Fn el_parse
+Parses the
+.Fa argv
+array (which is
+.Fa argc
+elements in size)
+to execute builtin
+.Nm
+commands.
+If the command is prefixed with
+.Dq prog :
+then
+.Fn el_parse
+will only execute the command if
+.Dq prog
+matches the
+.Fa prog
+argument supplied to
+.Fn el_init .
+The return value is
+\-1 if the command is unknown,
+0 if there was no error or
+.Dq prog
+didn't match, or
+1 if the command returned an error.
+Refer to
+.Xr editrc 5
+for more information.
+.It Fn el_set
+Set
+.Nm
+parameters.
+.Fa op
+determines which parameter to set, and each operation has its
+own parameter list.
+.Pp
+The following values for
+.Fa op
+are supported, along with the required argument list:
+.Bl -tag -width 4n
+.It Dv EL_PROMPT , Fa "char *(*f)(EditLine *)"
+Define prompt printing function as
+.Fa f ,
+which is to return a string that contains the prompt.
+.It Dv EL_PROMPT_ESC , Fa "char *(*f)(EditLine *)" , Fa "char c"
+Same as
+.Dv EL_PROMPT ,
+but the
+.Fa c
+argument indicates the start/stop literal prompt character.
+.Pp
+If a start/stop literal character is found in the prompt, the
+character itself
+is not printed, but characters after it are printed directly to the
+terminal without affecting the state of the current line.
+A subsequent second start/stop literal character ends this behavior.
+This is typically used to embed literal escape sequences that change the
+color/style of the terminal in the prompt.
+.Dv 0
+unsets it.
+.It Dv EL_REFRESH
+Re-display the current line on the next terminal line.
+.It Dv EL_RPROMPT , Fa "char *(*f)(EditLine *)"
+Define right side prompt printing function as
+.Fa f ,
+which is to return a string that contains the prompt.
+.It Dv EL_RPROMPT_ESC , Fa "char *(*f)(EditLine *)" , Fa "char c"
+Define the right prompt printing function but with a literal escape character.
+.It Dv EL_TERMINAL , Fa "const char *type"
+Define terminal type of the tty to be
+.Fa type ,
+or to
+.Ev TERM
+if
+.Fa type
+is
+.Dv NULL .
+.It Dv EL_EDITOR , Fa "const char *mode"
+Set editing mode to
+.Fa mode ,
+which must be one of
+.Dq emacs
+or
+.Dq vi .
+.It Dv EL_SIGNAL , Fa "int flag"
+If
+.Fa flag
+is non-zero,
+.Nm
+will install its own signal handler for the following signals when
+reading command input:
+.Dv SIGCONT ,
+.Dv SIGHUP ,
+.Dv SIGINT ,
+.Dv SIGQUIT ,
+.Dv SIGSTOP ,
+.Dv SIGTERM ,
+.Dv SIGTSTP ,
+and
+.Dv SIGWINCH .
+Otherwise, the current signal handlers will be used.
+.It Dv EL_BIND , Fa "const char *" , Fa "..." , Dv NULL
+Perform the
+.Ic bind
+builtin command.
+Refer to
+.Xr editrc 5
+for more information.
+.It Dv EL_ECHOTC , Fa "const char *" , Fa "..." , Dv NULL
+Perform the
+.Ic echotc
+builtin command.
+Refer to
+.Xr editrc 5
+for more information.
+.It Dv EL_SETTC , Fa "const char *" , Fa "..." , Dv NULL
+Perform the
+.Ic settc
+builtin command.
+Refer to
+.Xr editrc 5
+for more information.
+.It Dv EL_SETTY , Fa "const char *" , Fa "..." , Dv NULL
+Perform the
+.Ic setty
+builtin command.
+Refer to
+.Xr editrc 5
+for more information.
+.It Dv EL_TELLTC , Fa "const char *" , Fa "..." , Dv NULL
+Perform the
+.Ic telltc
+builtin command.
+Refer to
+.Xr editrc 5
+for more information.
+.It Dv EL_ADDFN , Fa "const char *name" , Fa "const char *help" , \
+Fa "unsigned char (*func)(EditLine *e, int ch)"
+Add a user defined function,
+.Fn func ,
+referred to as
+.Fa name
+which is invoked when a key which is bound to
+.Fa name
+is entered.
+.Fa help
+is a description of
+.Fa name .
+At invocation time,
+.Fa ch
+is the key which caused the invocation.
+The return value of
+.Fn func
+should be one of:
+.Bl -tag -width "CC_REDISPLAY"
+.It Dv CC_NORM
+Add a normal character.
+.It Dv CC_NEWLINE
+End of line was entered.
+.It Dv CC_EOF
+EOF was entered.
+.It Dv CC_ARGHACK
+Expecting further command input as arguments, do nothing visually.
+.It Dv CC_REFRESH
+Refresh display.
+.It Dv CC_REFRESH_BEEP
+Refresh display, and beep.
+.It Dv CC_CURSOR
+Cursor moved, so update and perform
+.Dv CC_REFRESH .
+.It Dv CC_REDISPLAY
+Redisplay entire input line.
+This is useful if a key binding outputs extra information.
+.It Dv CC_ERROR
+An error occurred.
+Beep, and flush tty.
+.It Dv CC_FATAL
+Fatal error, reset tty to known state.
+.El
+.It Dv EL_HIST , Fa "History *(*func)(History *, int op, ...)" , \
+Fa "const char *ptr"
+Defines which history function to use, which is usually
+.Fn history .
+.Fa ptr
+should be the value returned by
+.Fn history_init .
+.It Dv EL_EDITMODE , Fa "int flag"
+If
+.Fa flag
+is non-zero,
+editing is enabled (the default).
+Note that this is only an indication, and does not
+affect the operation of
+.Nm .
+At this time, it is the caller's responsibility to
+check this
+(using
+.Fn el_get )
+to determine if editing should be enabled or not.
+.It Dv EL_GETCFN , Fa "int (*f)(EditLine *, char *c)"
+Define the character reading function as
+.Fa f ,
+which is to return the number of characters read and store them in
+.Fa c .
+This function is called internally by
+.Fn el_gets
+and
+.Fn el_getc .
+The builtin function can be set or restored with the special function
+name
+.Dq Dv EL_BUILTIN_GETCFN .
+.It Dv EL_CLIENTDATA , Fa "void *data"
+Register
+.Fa data
+to be associated with this EditLine structure.
+It can be retrieved with the corresponding
+.Fn el_get
+call.
+.It Dv EL_SETFP , Fa "int fd" , Fa "FILE *fp"
+Set the current
+.Nm editline
+file pointer for
+.Dq input
+.Fa fd
+=
+.Dv 0 ,
+.Dq output
+.Fa fd
+=
+.Dv 1 ,
+or
+.Dq error
+.Fa fd
+=
+.Dv 2
+from
+.Fa fp .
+.El
+.It Fn el_get
+Get
+.Nm
+parameters.
+.Fa op
+determines which parameter to retrieve into
+.Fa result .
+Returns 0 if successful, \-1 otherwise.
+.Pp
+The following values for
+.Fa op
+are supported, along with actual type of
+.Fa result :
+.Bl -tag -width 4n
+.It Dv EL_PROMPT , Fa "char *(*f)(EditLine *)" , Fa "char *c"
+Return a pointer to the function that displays the prompt in
+.Fa f .
+If
+.Fa c
+is not
+.Dv NULL ,
+return the start/stop literal prompt character in it.
+.It Dv EL_RPROMPT , Fa "char *(*f)(EditLine *)" , Fa "char *c"
+Return a pointer to the function that displays the prompt in
+.Fa f .
+If
+.Fa c
+is not
+.Dv NULL ,
+return the start/stop literal prompt character in it.
+.It Dv EL_EDITOR , Fa "const char **"
+Return the name of the editor, which will be one of
+.Dq emacs
+or
+.Dq vi .
+.It Dv EL_GETTC , Fa "const char *name" , Fa "void *value"
+Return non-zero if
+.Fa name
+is a valid
+.Xr termcap 5
+capability
+and set
+.Fa value
+to the current value of that capability.
+.It Dv EL_SIGNAL , Fa "int *"
+Return non-zero if
+.Nm
+has installed private signal handlers (see
+.Fn el_get
+above).
+.It Dv EL_EDITMODE , Fa "int *"
+Return non-zero if editing is enabled.
+.It Dv EL_GETCFN , Fa "int (**f)(EditLine *, char *)"
+Return a pointer to the function that read characters, which is equal to
+.Dq Dv EL_BUILTIN_GETCFN
+in the case of the default builtin function.
+.It Dv EL_CLIENTDATA , Fa "void **data"
+Retrieve
+.Fa data
+previously registered with the corresponding
+.Fn el_set
+call.
+.It Dv EL_UNBUFFERED , Fa "int"
+Sets or clears unbuffered mode.
+In this mode,
+.Fn el_gets
+will return immediately after processing a single character.
+.It Dv EL_PREP_TERM , Fa "int"
+Sets or clears terminal editing mode.
+.It Dv EL_GETFP , Fa "int fd", Fa "FILE **fp"
+Return in
+.Fa fp
+the current
+.Nm editline
+file pointer for
+.Dq input
+.Fa fd
+=
+.Dv 0 ,
+.Dq output
+.Fa fd
+=
+.Dv 1 ,
+or
+.Dq error
+.Fa fd
+=
+.Dv 2 .
+.El
+.It Fn el_source
+Initialise
+.Nm
+by reading the contents of
+.Fa file .
+.Fn el_parse
+is called for each line in
+.Fa file .
+If
+.Fa file
+is
+.Dv NULL ,
+try
+.Pa $PWD/.editrc
+then
+.Pa $HOME/.editrc .
+Refer to
+.Xr editrc 5
+for details on the format of
+.Fa file .
+.It Fn el_resize
+Must be called if the terminal size changes.
+If
+.Dv EL_SIGNAL
+has been set with
+.Fn el_set ,
+then this is done automatically.
+Otherwise, it's the responsibility of the application to call
+.Fn el_resize
+on the appropriate occasions.
+.It Fn el_line
+Return the editing information for the current line in a
+.Fa LineInfo
+structure, which is defined as follows:
+.Bd -literal
+typedef struct lineinfo {
+ const char *buffer; /* address of buffer */
+ const char *cursor; /* address of cursor */
+ const char *lastchar; /* address of last character */
+} LineInfo;
+.Ed
+.Pp
+.Fa buffer
+is not NUL terminated.
+This function may be called after
+.Fn el_gets
+to obtain the
+.Fa LineInfo
+structure pertaining to line returned by that function,
+and from within user defined functions added with
+.Dv EL_ADDFN .
+.It Fn el_insertstr
+Insert
+.Fa str
+into the line at the cursor.
+Returns \-1 if
+.Fa str
+is empty or won't fit, and 0 otherwise.
+.It Fn el_deletestr
+Delete
+.Fa count
+characters before the cursor.
+.El
+.Sh HISTORY LIST FUNCTIONS
+The history functions use a common data structure,
+.Fa History ,
+which is created by
+.Fn history_init
+and freed by
+.Fn history_end .
+.Pp
+The following functions are available:
+.Bl -tag -width 4n
+.It Fn history_init
+Initialise the history list, and return a data structure
+to be used by all other history list functions.
+.It Fn history_end
+Clean up and finish with
+.Fa h ,
+assumed to have been created with
+.Fn history_init .
+.It Fn history
+Perform operation
+.Fa op
+on the history list, with optional arguments as needed by the
+operation.
+.Fa ev
+is changed accordingly to operation.
+The following values for
+.Fa op
+are supported, along with the required argument list:
+.Bl -tag -width 4n
+.It Dv H_SETSIZE , Fa "int size"
+Set size of history to
+.Fa size
+elements.
+.It Dv H_GETSIZE
+Get number of events currently in history.
+.It Dv H_END
+Cleans up and finishes with
+.Fa h ,
+assumed to be created with
+.Fn history_init .
+.It Dv H_CLEAR
+Clear the history.
+.It Dv H_FUNC , Fa "void *ptr" , Fa "history_gfun_t first" , \
+Fa "history_gfun_t next" , Fa "history_gfun_t last" , \
+Fa "history_gfun_t prev" , Fa "history_gfun_t curr" , \
+Fa "history_sfun_t set" , Fa "history_vfun_t clear" , \
+Fa "history_efun_t enter" , Fa "history_efun_t add"
+Define functions to perform various history operations.
+.Fa ptr
+is the argument given to a function when it's invoked.
+.It Dv H_FIRST
+Return the first element in the history.
+.It Dv H_LAST
+Return the last element in the history.
+.It Dv H_PREV
+Return the previous element in the history.
+.It Dv H_NEXT
+Return the next element in the history.
+.It Dv H_CURR
+Return the current element in the history.
+.It Dv H_SET
+Set the cursor to point to the requested element.
+.It Dv H_ADD , Fa "const char *str"
+Append
+.Fa str
+to the current element of the history, or perform the
+.Dv H_ENTER
+operation with argument
+.Fa str
+if there is no current element.
+.It Dv H_APPEND , Fa "const char *str"
+Append
+.Fa str
+to the last new element of the history.
+.It Dv H_ENTER , Fa "const char *str"
+Add
+.Fa str
+as a new element to the history, and, if necessary,
+removing the oldest entry to keep the list to the created size.
+If
+.Dv H_SETUNIQUE
+was has been called with a non-zero arguments, the element
+will not be entered into the history if its contents match
+the ones of the current history element.
+If the element is entered
+.Fn history
+returns 1, if it is ignored as a duplicate returns 0.
+Finally
+.Fn history
+returns \-1 if an error occurred.
+.It Dv H_PREV_STR , Fa "const char *str"
+Return the closest previous event that starts with
+.Fa str .
+.It Dv H_NEXT_STR , Fa "const char *str"
+Return the closest next event that starts with
+.Fa str .
+.It Dv H_PREV_EVENT , Fa "int e"
+Return the previous event numbered
+.Fa e .
+.It Dv H_NEXT_EVENT , Fa "int e"
+Return the next event numbered
+.Fa e .
+.It Dv H_LOAD , Fa "const char *file"
+Load the history list stored in
+.Fa file .
+.It Dv H_SAVE , Fa "const char *file"
+Save the history list to
+.Fa file .
+.It Dv H_SETUNIQUE , Fa "int unique"
+Set flag that adjacent identical event strings should not be entered
+into the history.
+.It Dv H_GETUNIQUE
+Retrieve the current setting if adjacent identical elements should
+be entered into the history.
+.It Dv H_DEL , Fa "int e"
+Delete the event numbered
+.Fa e .
+This function is only provided for
+.Xr readline 3
+compatibility.
+The caller is responsible for free'ing the string in the returned
+.Fa HistEvent .
+.El
+.Pp
+.Fn history
+returns \*[Gt]= 0 if the operation
+.Fa op
+succeeds.
+Otherwise, \-1 is returned and
+.Fa ev
+is updated to contain more details about the error.
+.El
+.Sh TOKENIZATION FUNCTIONS
+The tokenization functions use a common data structure,
+.Fa Tokenizer ,
+which is created by
+.Fn tok_init
+and freed by
+.Fn tok_end .
+.Pp
+The following functions are available:
+.Bl -tag -width 4n
+.It Fn tok_init
+Initialise the tokenizer, and return a data structure
+to be used by all other tokenizer functions.
+.Fa IFS
+contains the Input Field Separators, which defaults to
+.Aq space ,
+.Aq tab ,
+and
+.Aq newline
+if
+.Dv NULL .
+.It Fn tok_end
+Clean up and finish with
+.Fa t ,
+assumed to have been created with
+.Fn tok_init .
+.It Fn tok_reset
+Reset the tokenizer state.
+Use after a line has been successfully tokenized
+by
+.Fn tok_line
+or
+.Fn tok_str
+and before a new line is to be tokenized.
+.It Fn tok_line
+Tokenize
+.Fa li ,
+If successful, modify:
+.Fa argv
+to contain the words,
+.Fa argc
+to contain the number of words,
+.Fa cursorc
+(if not
+.Dv NULL )
+to contain the index of the word containing the cursor,
+and
+.Fa cursoro
+(if not
+.Dv NULL )
+to contain the offset within
+.Fa argv[cursorc]
+of the cursor.
+.Pp
+Returns
+0 if successful,
+\-1 for an internal error,
+1 for an unmatched single quote,
+2 for an unmatched double quote,
+and
+3 for a backslash quoted
+.Aq newline .
+A positive exit code indicates that another line should be read
+and tokenization attempted again.
+.
+.It Fn tok_str
+A simpler form of
+.Fn tok_line ;
+.Fa str
+is a NUL terminated string to tokenize.
+.El
+.
+.\"XXX.Sh EXAMPLES
+.\"XXX: provide some examples
+.Sh SEE ALSO
+.Xr sh 1 ,
+.Xr signal 3 ,
+.Xr termcap 3 ,
+.Xr editrc 5 ,
+.Xr termcap 5
+.Sh HISTORY
+The
+.Nm
+library first appeared in
+.Bx 4.4 .
+.Dv CC_REDISPLAY
+appeared in
+.Nx 1.3 .
+.Dv CC_REFRESH_BEEP ,
+.Dv EL_EDITMODE
+and the readline emulation appeared in
+.Nx 1.4 .
+.Dv EL_RPROMPT
+appeared in
+.Nx 1.5 .
+.Sh AUTHORS
+The
+.Nm
+library was written by Christos Zoulas.
+Luke Mewburn wrote this manual and implemented
+.Dv CC_REDISPLAY ,
+.Dv CC_REFRESH_BEEP ,
+.Dv EL_EDITMODE ,
+and
+.Dv EL_RPROMPT .
+Jaromir Dolecek implemented the readline emulation.
+Johny Mattsson implemented wide-character support.
+.Sh BUGS
+At this time, it is the responsibility of the caller to
+check the result of the
+.Dv EL_EDITMODE
+operation of
+.Fn el_get
+(after an
+.Fn el_source
+or
+.Fn el_parse )
+to determine if
+.Nm
+should be used for further input.
+I.e.,
+.Dv EL_EDITMODE
+is purely an indication of the result of the most recent
+.Xr editrc 5
+.Ic edit
+command.
diff --git a/third_party/heimdal/lib/libedit/doc/editrc.5.roff b/third_party/heimdal/lib/libedit/doc/editrc.5.roff
new file mode 100644
index 0000000..44ab99d
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/doc/editrc.5.roff
@@ -0,0 +1,490 @@
+.\" $NetBSD: editrc.5,v 1.24 2009/04/11 22:17:52 wiz Exp $
+.\"
+.\" Copyright (c) 1997-2000 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This file was contributed to The NetBSD Foundation by Luke Mewburn.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+.\" ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+.\" TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+.\" BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+.\" POSSIBILITY OF SUCH DAMAGE.
+.\"
+.Dd October 18, 2003
+.Dt EDITRC 5
+.Os
+.Sh NAME
+.Nm editrc
+.Nd configuration file for editline library
+.Sh SYNOPSIS
+.Nm
+.Sh DESCRIPTION
+The
+.Nm
+file defines various settings to be used by the
+.Xr editline 3
+library.
+.Pp
+The format of each line is:
+.Dl [prog:]command [arg [...]]
+.Pp
+.Ar command
+is one of the
+.Xr editline 3
+builtin commands.
+Refer to
+.Sx BUILTIN COMMANDS
+for more information.
+.Pp
+.Ar prog
+is the program name string that a program defines when it calls
+.Xr el_init 3
+to set up
+.Xr editline 3 ,
+which is usually
+.Va argv[0] .
+.Ar command
+will be executed for any program which matches
+.Ar prog .
+.Pp
+.Ar prog
+may also be a
+.Xr regex 3
+style
+regular expression, in which case
+.Ar command
+will be executed for any program that matches the regular expression.
+.Pp
+If
+.Ar prog
+is absent,
+.Ar command
+is executed for all programs.
+.Sh BUILTIN COMMANDS
+The
+.Nm editline
+library has some builtin commands, which affect the way
+that the line editing and history functions operate.
+These are based on similar named builtins present in the
+.Xr tcsh 1
+shell.
+.Pp
+The following builtin commands are available:
+.Bl -tag -width 4n
+.It Ic bind Oo Fl a Oc Oo Fl e Oc Oo Fl k Oc Oo Fl l Oc Oo Fl r Oc \
+Oo Fl s Oc Oo Fl v Oc Oo Ar key Op Ar command Oc
+Without options, list all bound keys, and the editor command to which
+each is bound.
+If
+.Ar key
+is supplied, show the bindings for
+.Ar key .
+If
+.Ar key command
+is supplied, bind
+.Ar command
+to
+.Ar key .
+Options include:
+.Bl -tag -width 4n
+.It Fl e
+Bind all keys to the standard GNU Emacs-like bindings.
+.It Fl v
+Bind all keys to the standard
+.Xr vi 1 Ns -like
+bindings.
+.It Fl a
+List or change key bindings in the
+.Xr vi 1
+mode alternate (command mode) key map.
+.It Fl k
+.Ar key
+is interpreted as a symbolic arrow key name, which may be one of
+.Sq up ,
+.Sq down ,
+.Sq left
+or
+.Sq right .
+.It Fl l
+List all editor commands and a short description of each.
+.It Fl r
+Remove a key's binding.
+.It Fl s
+.Ar command
+is taken as a literal string and treated as terminal input when
+.Ar key
+is typed.
+Bound keys in
+.Ar command
+are themselves reinterpreted, and this continues for ten levels of
+interpretation.
+.El
+.Pp
+.Ar command
+may be one of the commands documented in
+.Sx "EDITOR COMMANDS"
+below, or another key.
+.Pp
+.Ar key
+and
+.Ar command
+can contain control characters of the form
+.Sm off
+.Sq No ^ Ar character
+.Sm on
+.Po
+e.g.
+.Sq ^A
+.Pc ,
+and the following backslashed escape sequences:
+.Pp
+.Bl -tag -compact -offset indent -width 4n
+.It Ic \ea
+Bell
+.It Ic \eb
+Backspace
+.It Ic \ee
+Escape
+.It Ic \ef
+Formfeed
+.It Ic \en
+Newline
+.It Ic \er
+Carriage return
+.It Ic \et
+Horizontal tab
+.It Ic \ev
+Vertical tab
+.Sm off
+.It Sy \e Ar nnn
+.Sm on
+The ASCII character corresponding to the octal number
+.Ar nnn .
+.El
+.Pp
+.Sq \e
+nullifies the special meaning of the following character,
+if it has any, notably
+.Sq \e
+and
+.Sq ^ .
+.It Ic echotc Oo Fl sv Oc Ar arg Ar ...
+Exercise terminal capabilities given in
+.Ar arg Ar ... .
+If
+.Ar arg
+is
+.Sq baud ,
+.Sq cols ,
+.Sq lines ,
+.Sq rows ,
+.Sq meta or
+.Sq tabs ,
+the value of that capability is printed, with
+.Dq yes
+or
+.Dq no
+indicating that the terminal does or does not have that capability.
+.Pp
+.Fl s
+returns an empty string for non-existent capabilities, rather than
+causing an error.
+.Fl v
+causes messages to be verbose.
+.It Ic edit Op Li on | Li off
+Enable or disable the
+.Nm editline
+functionality in a program.
+.It Ic history Ar list | Ar size Dv n | Ar unique Dv n
+The
+.Ar list
+command lists all entries in the history.
+The
+.Ar size
+command sets the history size to
+.Dv n
+entries.
+The
+.Ar unique
+command controls if history should keep duplicate entries.
+If
+.Dv n
+is non zero, only keep unique history entries.
+If
+.Dv n
+is zero, then keep all entries (the default).
+.It Ic telltc
+List the values of all the terminal capabilities (see
+.Xr termcap 5 ) .
+.It Ic settc Ar cap Ar val
+Set the terminal capability
+.Ar cap
+to
+.Ar val ,
+as defined in
+.Xr termcap 5 .
+No sanity checking is done.
+.It Ic setty Oo Fl a Oc Oo Fl d Oc Oo Fl q Oc Oo Fl x Oc Oo Ar +mode Oc \
+Oo Ar -mode Oc Oo Ar mode Oc Oo Ar char=c Oc
+Control which tty modes that
+.Nm
+won't allow the user to change.
+.Fl d ,
+.Fl q
+or
+.Fl x
+tells
+.Ic setty
+to act on the
+.Sq edit ,
+.Sq quote
+or
+.Sq execute
+set of tty modes respectively; defaulting to
+.Fl x .
+.Pp
+Without other arguments,
+.Ic setty
+lists the modes in the chosen set which are fixed on
+.Po
+.Sq +mode
+.Pc
+or off
+.Po
+.Sq -mode
+.Pc .
+.Fl a
+lists all tty modes in the chosen set regardless of the setting.
+With
+.Ar +mode ,
+.Ar -mode
+or
+.Ar mode ,
+fixes
+.Ar mode
+on or off or removes control of
+.Ar mode
+in the chosen set.
+.Pp
+.Ic Setty
+can also be used to set tty characters to particular values using
+.Ar char=value .
+If
+.Ar value
+is empty
+then the character is set to
+.Dv _POSIX_VDISABLE .
+.El
+.Sh EDITOR COMMANDS
+The following editor commands are available for use in key bindings:
+.\" Section automatically generated with makelist
+.Bl -tag -width 4n
+.It Ic vi-paste-next
+Vi paste previous deletion to the right of the cursor.
+.It Ic vi-paste-prev
+Vi paste previous deletion to the left of the cursor.
+.It Ic vi-prev-space-word
+Vi move to the previous space delimited word.
+.It Ic vi-prev-word
+Vi move to the previous word.
+.It Ic vi-next-space-word
+Vi move to the next space delimited word.
+.It Ic vi-next-word
+Vi move to the next word.
+.It Ic vi-change-case
+Vi change case of character under the cursor and advance one character.
+.It Ic vi-change-meta
+Vi change prefix command.
+.It Ic vi-insert-at-bol
+Vi enter insert mode at the beginning of line.
+.It Ic vi-replace-char
+Vi replace character under the cursor with the next character typed.
+.It Ic vi-replace-mode
+Vi enter replace mode.
+.It Ic vi-substitute-char
+Vi replace character under the cursor and enter insert mode.
+.It Ic vi-substitute-line
+Vi substitute entire line.
+.It Ic vi-change-to-eol
+Vi change to end of line.
+.It Ic vi-insert
+Vi enter insert mode.
+.It Ic vi-add
+Vi enter insert mode after the cursor.
+.It Ic vi-add-at-eol
+Vi enter insert mode at end of line.
+.It Ic vi-delete-meta
+Vi delete prefix command.
+.It Ic vi-end-word
+Vi move to the end of the current space delimited word.
+.It Ic vi-to-end-word
+Vi move to the end of the current word.
+.It Ic vi-undo
+Vi undo last change.
+.It Ic vi-command-mode
+Vi enter command mode (use alternative key bindings).
+.It Ic vi-zero
+Vi move to the beginning of line.
+.It Ic vi-delete-prev-char
+Vi move to previous character (backspace).
+.It Ic vi-list-or-eof
+Vi list choices for completion or indicate end of file if empty line.
+.It Ic vi-kill-line-prev
+Vi cut from beginning of line to cursor.
+.It Ic vi-search-prev
+Vi search history previous.
+.It Ic vi-search-next
+Vi search history next.
+.It Ic vi-repeat-search-next
+Vi repeat current search in the same search direction.
+.It Ic vi-repeat-search-prev
+Vi repeat current search in the opposite search direction.
+.It Ic vi-next-char
+Vi move to the character specified next.
+.It Ic vi-prev-char
+Vi move to the character specified previous.
+.It Ic vi-to-next-char
+Vi move up to the character specified next.
+.It Ic vi-to-prev-char
+Vi move up to the character specified previous.
+.It Ic vi-repeat-next-char
+Vi repeat current character search in the same search direction.
+.It Ic vi-repeat-prev-char
+Vi repeat current character search in the opposite search direction.
+.It Ic em-delete-or-list
+Delete character under cursor or list completions if at end of line.
+.It Ic em-delete-next-word
+Cut from cursor to end of current word.
+.It Ic em-yank
+Paste cut buffer at cursor position.
+.It Ic em-kill-line
+Cut the entire line and save in cut buffer.
+.It Ic em-kill-region
+Cut area between mark and cursor and save in cut buffer.
+.It Ic em-copy-region
+Copy area between mark and cursor to cut buffer.
+.It Ic em-gosmacs-transpose
+Exchange the two characters before the cursor.
+.It Ic em-next-word
+Move next to end of current word.
+.It Ic em-upper-case
+Uppercase the characters from cursor to end of current word.
+.It Ic em-capitol-case
+Capitalize the characters from cursor to end of current word.
+.It Ic em-lower-case
+Lowercase the characters from cursor to end of current word.
+.It Ic em-set-mark
+Set the mark at cursor.
+.It Ic em-exchange-mark
+Exchange the cursor and mark.
+.It Ic em-universal-argument
+Universal argument (argument times 4).
+.It Ic em-meta-next
+Add 8th bit to next character typed.
+.It Ic em-toggle-overwrite
+Switch from insert to overwrite mode or vice versa.
+.It Ic em-copy-prev-word
+Copy current word to cursor.
+.It Ic em-inc-search-next
+Emacs incremental next search.
+.It Ic em-inc-search-prev
+Emacs incremental reverse search.
+.It Ic ed-end-of-file
+Indicate end of file.
+.It Ic ed-insert
+Add character to the line.
+.It Ic ed-delete-prev-word
+Delete from beginning of current word to cursor.
+.It Ic ed-delete-next-char
+Delete character under cursor.
+.It Ic ed-kill-line
+Cut to the end of line.
+.It Ic ed-move-to-end
+Move cursor to the end of line.
+.It Ic ed-move-to-beg
+Move cursor to the beginning of line.
+.It Ic ed-transpose-chars
+Exchange the character to the left of the cursor with the one under it.
+.It Ic ed-next-char
+Move to the right one character.
+.It Ic ed-prev-word
+Move to the beginning of the current word.
+.It Ic ed-prev-char
+Move to the left one character.
+.It Ic ed-quoted-insert
+Add the next character typed verbatim.
+.It Ic ed-digit
+Adds to argument or enters a digit.
+.It Ic ed-argument-digit
+Digit that starts argument.
+.It Ic ed-unassigned
+Indicates unbound character.
+.It Ic ed-tty-sigint
+Tty interrupt character.
+.It Ic ed-tty-dsusp
+Tty delayed suspend character.
+.It Ic ed-tty-flush-output
+Tty flush output characters.
+.It Ic ed-tty-sigquit
+Tty quit character.
+.It Ic ed-tty-sigtstp
+Tty suspend character.
+.It Ic ed-tty-stop-output
+Tty disallow output characters.
+.It Ic ed-tty-start-output
+Tty allow output characters.
+.It Ic ed-newline
+Execute command.
+.It Ic ed-delete-prev-char
+Delete the character to the left of the cursor.
+.It Ic ed-clear-screen
+Clear screen leaving current line at the top.
+.It Ic ed-redisplay
+Redisplay everything.
+.It Ic ed-start-over
+Erase current line and start from scratch.
+.It Ic ed-sequence-lead-in
+First character in a bound sequence.
+.It Ic ed-prev-history
+Move to the previous history line.
+.It Ic ed-next-history
+Move to the next history line.
+.It Ic ed-search-prev-history
+Search previous in history for a line matching the current.
+.It Ic ed-search-next-history
+Search next in history for a line matching the current.
+.It Ic ed-prev-line
+Move up one line.
+.It Ic ed-next-line
+Move down one line.
+.It Ic ed-command
+Editline extended command.
+.El
+.\" End of section automatically generated with makelist
+.Sh SEE ALSO
+.Xr editline 3 ,
+.Xr regex 3 ,
+.Xr termcap 5
+.Sh AUTHORS
+The
+.Nm editline
+library was written by Christos Zoulas,
+and this manual was written by Luke Mewburn,
+with some sections inspired by
+.Xr tcsh 1 .
diff --git a/third_party/heimdal/lib/libedit/doc/mdoc2man.awk b/third_party/heimdal/lib/libedit/doc/mdoc2man.awk
new file mode 100644
index 0000000..e21753f
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/doc/mdoc2man.awk
@@ -0,0 +1,459 @@
+#!/usr/bin/awk
+#
+# Version history:
+# v3, I put the program under a proper license
+# Dan Nelson <dnelson@allantgroup.com> added .An, .Aq and fixed a typo
+# v2, fixed to work on GNU awk --posix and MacOS X
+# v1, first attempt, didn't work on MacOS X
+#
+# Copyright (c) 2003 Peter Stuge <stuge-mdoc2man@cdy.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.
+
+
+BEGIN {
+ optlist=0
+ oldoptlist=0
+ nospace=0
+ synopsis=0
+ reference=0
+ block=0
+ ext=0
+ extopt=0
+ literal=0
+ prenl=0
+ breakw=0
+ line=""
+ proto=0
+ bl_level=0
+}
+
+function wtail() {
+ retval=""
+ while(w<nwords) {
+ if(length(retval))
+ retval=retval OFS
+ retval=retval words[++w]
+ }
+ return retval
+}
+
+function add(str) {
+ for(;prenl;prenl--)
+ line=line "\n"
+ line=line str
+}
+
+! /^\./ {
+ for(;prenl;prenl--)
+ print ""
+ print
+ if(literal)
+ print ".br"
+ next
+}
+
+/^\.\\"/ { next }
+
+{
+ option=0
+ parens=0
+ angles=0
+ sub("^\\.","")
+ nwords=split($0,words)
+ for(w=1;w<=nwords;w++) {
+ skip=0
+ if(match(words[w],"^Li|Pf$")) {
+ skip=1
+ } else if(match(words[w],"^Xo$")) {
+ skip=1
+ ext=1
+ if(length(line)&&!(match(line," $")||prenl))
+ add(OFS)
+ } else if(match(words[w],"^Xc$")) {
+ skip=1
+ ext=0
+ if(!extopt)
+ prenl++
+ w=nwords
+ } else if(match(words[w],"^Bd$")) {
+ skip=1
+ if(match(words[w+1],"-literal")) {
+ literal=1
+ prenl++
+ w=nwords
+ }
+ } else if(match(words[w],"^Po$")) {
+ skip=1
+ add("(")
+ if(!nospace)
+ nospace=1
+ } else if(match(words[w],"^Pc$")) {
+ skip=1
+ add(")")
+ if(!nospace)
+ nospace=1
+ } else if(match(words[w],"^Ed$")) {
+ skip=1
+ literal=0
+ } else if(match(words[w],"^Ns$")) {
+ skip=1
+ if(!nospace)
+ nospace=1
+ sub(" $","",line)
+ } else if(match(words[w],"^No$")) {
+ skip=1
+ sub(" $","",line)
+ add(words[++w])
+ } else if(match(words[w],"^Dq$")) {
+ skip=1
+ add("``")
+ add(words[++w])
+ while(w<nwords&&!match(words[w+1],"^[\\.,]"))
+ add(OFS words[++w])
+ add("''")
+ if(!nospace&&match(words[w+1],"^[\\.,]"))
+ nospace=1
+ } else if(match(words[w],"^Va$")) {
+ skip=1
+ add("\\fI" words[++w])
+ while(w<nwords&&!match(words[w+1],"^[\\.,]"))
+ add(OFS words[++w])
+ add("\\fP")
+ if(!nospace&&match(words[w+1],"^[\\.,]"))
+ nospace=1
+ } else if(match(words[w],"^Sq|Ql$")) {
+ skip=1
+ add("`" words[++w] "'")
+ if(!nospace&&match(words[w+1],"^[\\.,]"))
+ nospace=1
+ } else if(match(words[w],"^Oo$")) {
+ skip=1
+ extopt=1
+ if(!nospace)
+ nospace=1
+ add("[")
+ } else if(match(words[w],"^Oc$")) {
+ skip=1
+ extopt=0
+ add("]")
+ }
+ if(!skip) {
+ if(!nospace&&length(line)&&!(match(line," $")||prenl))
+ add(OFS)
+ if(nospace==1)
+ nospace=0
+ }
+ if(match(words[w],"^Dd$")) {
+ date=wtail()
+ next
+ } else if(match(words[w],"^Dt$")) {
+ id=wtail()
+ next
+ } else if(match(words[w],"^Os$")) {
+ add(".TH " id " \"" date "\" \"" wtail() "\"")
+ } else if(match(words[w],"^Sh$")) {
+ add(".SH")
+ synopsis=match(words[w+1],"SYNOPSIS")
+ } else if(match(words[w],"^Xr$")) {
+ #add("\\fB" words[++w] "\\fP(" words[++w] ")" words[++w])
+ add("\\fB" words[++w] "\\fP(" words[++w] ")")
+ sub("^Ns$", "", words[w+1])
+ add(words[++w])
+ } else if(match(words[w],"^Rs$")) {
+ split("",refauthors)
+ nrefauthors=0
+ reftitle=""
+ refissue=""
+ refdate=""
+ refopt=""
+ reference=1
+ next
+ } else if(match(words[w],"^Re$")) {
+ prenl++
+ for(i=nrefauthors-1;i>0;i--) {
+ add(refauthors[i])
+ if(i>1)
+ add(", ")
+ }
+ if(nrefauthors>1)
+ add(" and ")
+ add(refauthors[0] ", \\fI" reftitle "\\fP")
+ if(length(refissue))
+ add(", " refissue)
+ if(length(refdate))
+ add(", " refdate)
+ if(length(refopt))
+ add(", " refopt)
+ add(".")
+ reference=0
+ } else if(reference) {
+ if(match(words[w],"^%A$")) { refauthors[nrefauthors++]=wtail() }
+ if(match(words[w],"^%T$")) {
+ reftitle=wtail()
+ sub("^\"","",reftitle)
+ sub("\"$","",reftitle)
+ }
+ if(match(words[w],"^%N$")) { refissue=wtail() }
+ if(match(words[w],"^%D$")) { refdate=wtail() }
+ if(match(words[w],"^%O$")) { refopt=wtail() }
+ } else if(match(words[w],"^Nm$")) {
+ if(synopsis) {
+ add(".br")
+ prenl++
+ }
+ n=words[++w]
+ if(!length(name))
+ name=n
+ if(!length(n))
+ n=name
+ add("\\fB" n "\\fP")
+ if(!nospace&&match(words[w+1],"^[\\.,]"))
+ nospace=1
+ } else if(match(words[w],"^Nd$")) {
+ add("\\- " wtail())
+ } else if(match(words[w],"^Fl$")) {
+ add("\\fB\\-" words[++w] "\\fP")
+ if(!nospace&&match(words[w+1],"^[\\.,]"))
+ nospace=1
+ } else if(match(words[w],"^Ar$")) {
+ add("\\fI")
+ if(w==nwords)
+ add("file ...\\fP")
+ else {
+ add(words[++w] "\\fP")
+ while(match(words[w+1],"^\\|$"))
+ add(OFS words[++w] " \\fI" words[++w] "\\fP")
+ }
+ if(!nospace&&match(words[w+1],"^[\\.,]"))
+ nospace=1
+ } else if(match(words[w],"^Cm$")) {
+ add("\\fB" words[++w] "\\fP")
+ while(w<nwords&&match(words[w+1],"^[\\.,:;)]"))
+ add(words[++w])
+ } else if(match(words[w],"^Op$")) {
+ option=1
+ if(!nospace)
+ nospace=1
+ add("[")
+ } else if(match(words[w],"^Pp$")) {
+ prenl++
+ } else if(match(words[w],"^An$")) {
+ prenl++
+ } else if(match(words[w],"^Ss$")) {
+ add(".SS")
+ } else if(match(words[w],"^Pa$")&&!option) {
+ add("\\fI")
+ w++
+ if(match(words[w],"^\\."))
+ add("\\&")
+ add(words[w] "\\fP")
+ while(w<nwords&&match(words[w+1],"^[\\.,:;)]"))
+ add(words[++w])
+ } else if(match(words[w],"^Dv$")) {
+ #add(".BR")
+ } else if(match(words[w],"^Em|Ev$")) {
+ add(".IR")
+ } else if(match(words[w],"^Pq$")) {
+ add("(")
+ nospace=1
+ parens=1
+ } else if(match(words[w],"^Aq$")) {
+ add("<")
+ nospace=1
+ angles=1
+ } else if(match(words[w],"^S[xy]$")) {
+ add(".B " wtail())
+ } else if(match(words[w],"^Ic$")) {
+ plain=1
+ add("\\fB")
+ while(w<nwords) {
+ w++
+ if(match(words[w],"^Op$")) {
+ w++
+ add("[")
+ words[nwords]=words[nwords] "]"
+ }
+ if(match(words[w],"^Ar$")) {
+ add("\\fI" words[++w] "\\fP")
+ } else if(match(words[w],"^[\\.,]")) {
+ sub(" $","",line)
+ if(plain) {
+ add("\\fP")
+ plain=0
+ }
+ add(words[w])
+ } else if(match(words[w],"^Xo$")) {
+ } else {
+ if(!plain) {
+ add("\\fB")
+ plain=1
+ }
+ add(words[w])
+ }
+ if(!nospace)
+ add(OFS)
+ }
+ sub(" $","",line)
+ if(plain)
+ add("\\fP")
+ } else if(match(words[w],"^Dl$")) {
+ ## remove is ok for editrc.5
+ } else if(match(words[w],"^Bl$")) {
+ ++bl_level
+ if (bl_level > 1)
+ add(".RS")
+ oldoptlist=optlist
+ if(match(words[w+1],"-bullet"))
+ optlist=1
+ else if(match(words[w+1],"-enum")) {
+ optlist=2
+ enum=0
+ } else if(match(words[w+1],"-tag"))
+ optlist=3
+ else if(match(words[w+1],"-item"))
+ optlist=4
+ else if(match(words[w+1],"-bullet"))
+ optlist=1
+ w=nwords
+ } else if(match(words[w],"^El$")) {
+ if (bl_level > 1)
+ add(".RE")
+ --bl_level
+ optlist=oldoptlist
+ } else if(match(words[w],"^Bk$")) {
+ if(match(words[w+1],"-words")) {
+ w++
+ breakw=1
+ }
+ } else if(match(words[w],"^Ek$")) {
+ breakw=0
+ } else if(match(words[w],"^It$")&&optlist) {
+ if(optlist==1)
+ add(".IP \\(bu")
+ else if(optlist==2)
+ add(".IP " ++enum ".")
+ else if(optlist==3) {
+ add(".TP")
+ prenl++
+ if(match(words[w+1],"^Pa$|^Ev$")) {
+ add(".B")
+ w++
+ }
+ } else if(optlist==4)
+ add(".IP")
+ } else if(match(words[w],"^Sm$")) {
+ if(match(words[w+1],"off"))
+ nospace=2
+ else if(match(words[w+1],"on"))
+ nospace=0
+ w++
+ } else if(match(words[w],"^Lb$")) {
+ wtail()
+ add("Command Line Editor Library (libedit, -ledit)")
+ } else if(match(words[w],"^In$")) {
+ add(".PP\n")
+ add("\\fB#include <" wtail() ">\\fP")
+ } else if(match(words[w],"^Ft$")) {
+ add(".PP\n")
+ add("\\fI" wtail() "\\fP\n")
+ add(".br")
+ proto=1
+ } else if(match(words[w],"^Fn$")) {
+ add("\\fB" words[++w] "\\fP(")
+ punct=0
+ while(++w<=nwords) {
+ if(match(words[w], "^\".*\"$")) {
+ sub("^\"", "", words[w])
+ sub("\"$", "", words[w])
+ add("\\fI" words[w] "\\fP")
+ if (w!=nwords) {
+ add(", ")
+ }
+ } else if(match(words[w], "^\"")) {
+ sub("^\"", "", words[w])
+ add("\\fI" words[w] " ")
+ } else if (match(words[w], "\"$")) {
+ sub("\"$", "", words[w])
+ add(words[w] "\\fP")
+ if (w!=nwords) {
+ add(", ")
+ }
+ } else {
+ if (w==nwords&&(match(words[w], "^[.,]$"))) {
+ punct=1
+ } else {
+ add(words[w] " ")
+ }
+
+ }
+ }
+ add(")")
+ if (punct==1) {
+ add(words[w-1])
+ } else {
+ if (proto==1) {
+ add(";")
+ proto=0
+ }
+ }
+ } else if(match(words[w],"^Fa$")) {
+ punct=0
+ add("\\fI")
+ while(++w<=nwords) {
+ if(match(words[w], "^\".*\"$")) {
+ sub("^\"", "", words[w])
+ sub("\"$", "", words[w])
+ add(words[w])
+ } else if(match(words[w], "^\"")) {
+ sub("^\"", "", words[w])
+ add(words[w] " ")
+ } else if (match(words[w], "\"$")) {
+ sub("\"$", "", words[w])
+ add(words[w])
+ } else {
+ if (w==nwords&&(match(words[w], "^[.,]$"))) {
+ punct=1
+ } else {
+ if (w+1==nwords&&(match(words[w+1], "^[.,]$"))) {
+ add(words[w])
+ } else {
+ add(words[w] " ")
+ }
+ }
+ }
+ }
+ add("\\fP")
+ if (punct==1) {
+ add(words[w-1])
+ }
+ } else if(!skip) {
+ add(words[w])
+ }
+ }
+ if(match(line,"^\\.[^a-zA-Z]"))
+ sub("^\\.","",line)
+ if(parens)
+ add(")")
+ if(angles)
+ add(">")
+ if(option)
+ add("]")
+ if(ext&&!extopt&&!match(line," $"))
+ add(OFS)
+ if(!ext&&!extopt&&length(line)) {
+ print line
+ prenl=0
+ line=""
+ }
+}
diff --git a/third_party/heimdal/lib/libedit/examples/Makefile.am b/third_party/heimdal/lib/libedit/examples/Makefile.am
new file mode 100644
index 0000000..a5c1950
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/examples/Makefile.am
@@ -0,0 +1,14 @@
+
+LDADD = $(top_builddir)/src/libedit.la
+AM_CFLAGS = -I$(top_srcdir)/src
+
+noinst_PROGRAMS = tc1 fileman
+
+tc1_SOURCES = tc1.c
+fileman_SOURCES = fileman.c
+
+if WIDECHAR
+noinst_PROGRAMS += wtc1
+wtc1_SOURCES = wtc1.c
+endif
+
diff --git a/third_party/heimdal/lib/libedit/examples/fileman.c b/third_party/heimdal/lib/libedit/examples/fileman.c
new file mode 100644
index 0000000..559f535
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/examples/fileman.c
@@ -0,0 +1,496 @@
+/* fileman.c -- A tiny application which demonstrates how to use the
+ GNU Readline library. This application interactively allows users
+ to manipulate files and their modes.
+
+ NOTE: this was taken from the GNU Readline documentation and ported
+ to libedit. A commad to output the history list was added.
+
+ */
+
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/file.h>
+#include <sys/stat.h>
+#include <sys/errno.h>
+#include <ctype.h>
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <locale.h>
+#include <time.h>
+
+/* GNU readline
+#include <readline/readline.h>
+#include <readline/history.h>
+*/
+#include <editline/readline.h>
+
+void * xmalloc (size_t size);
+void too_dangerous (char *caller);
+void initialize_readline ();
+int execute_line (char *line);
+int valid_argument (char *caller, char *arg);
+
+typedef int rl_icpfunc_t (char *);
+
+/* The names of functions that actually do the manipulation. */
+int com_list (char *);
+int com_view (char *);
+int com_history (char *);
+int com_rename(char *);
+int com_stat(char *);
+int com_pwd(char *);
+int com_delete(char *);
+int com_help(char *);
+int com_cd(char *);
+int com_quit(char *);
+
+/* A structure which contains information on the commands this program
+ can understand. */
+
+typedef struct {
+ char *name; /* User printable name of the function. */
+ rl_icpfunc_t *func; /* Function to call to do the job. */
+ char *doc; /* Documentation for this function. */
+} COMMAND;
+
+COMMAND commands[] = {
+ { "cd", com_cd, "Change to directory DIR" },
+ { "delete", com_delete, "Delete FILE" },
+ { "help", com_help, "Display this text" },
+ { "?", com_help, "Synonym for `help'" },
+ { "list", com_list, "List files in DIR" },
+ { "ls", com_list, "Synonym for `list'" },
+ { "pwd", com_pwd, "Print the current working directory" },
+ { "quit", com_quit, "Quit using Fileman" },
+ { "rename", com_rename, "Rename FILE to NEWNAME" },
+ { "stat", com_stat, "Print out statistics on FILE" },
+ { "view", com_view, "View the contents of FILE" },
+ { "history", com_history, "List editline history" },
+ { (char *)NULL, (rl_icpfunc_t *)NULL, (char *)NULL }
+};
+
+/* Forward declarations. */
+char *stripwhite ();
+COMMAND *find_command ();
+
+/* The name of this program, as taken from argv[0]. */
+char *progname;
+
+/* When non-zero, this means the user is done using this program. */
+int done;
+
+char *
+dupstr (char* s)
+{
+ char *r;
+
+ r = xmalloc (strlen (s) + 1);
+ strcpy (r, s);
+ return (r);
+}
+
+int
+main (int argc, char **argv)
+{
+ char *line, *s;
+
+ progname = argv[0];
+
+ setlocale(LC_CTYPE, "");
+
+ initialize_readline(); /* Bind our completer. */
+
+ stifle_history(7);
+
+ /* Loop reading and executing lines until the user quits. */
+ for ( ; done == 0; )
+ {
+ line = readline ("FileMan: ");
+
+ if (!line)
+ break;
+
+ /* Remove leading and trailing whitespace from the line.
+ Then, if there is anything left, add it to the history list
+ and execute it. */
+ s = stripwhite(line);
+
+ if (*s) {
+
+ char* expansion;
+ int result;
+
+ result = history_expand(s, &expansion);
+
+ if (result < 0 || result == 2) {
+ fprintf(stderr, "%s\n", expansion);
+ } else {
+ add_history(expansion);
+ execute_line(expansion);
+ }
+ free(expansion);
+ }
+
+ free(line);
+ }
+ exit (0);
+
+ return 0;
+}
+
+/* Execute a command line. */
+int
+execute_line (char *line)
+{
+ register int i;
+ COMMAND *command;
+ char *word;
+
+ /* Isolate the command word. */
+ i = 0;
+ while (line[i] && isspace (line[i]))
+ i++;
+ word = line + i;
+
+ while (line[i] && !isspace (line[i]))
+ i++;
+
+ if (line[i])
+ line[i++] = '\0';
+
+ command = find_command (word);
+
+ if (!command)
+ {
+ fprintf (stderr, "%s: No such command for FileMan.\n", word);
+ return (-1);
+ }
+
+ /* Get argument to command, if any. */
+ while (isspace (line[i]))
+ i++;
+
+ word = line + i;
+
+ /* Call the function. */
+ return ((*(command->func)) (word));
+}
+
+/* Look up NAME as the name of a command, and return a pointer to that
+ command. Return a NULL pointer if NAME isn't a command name. */
+COMMAND *
+find_command (char *name)
+{
+ register int i;
+
+ for (i = 0; commands[i].name; i++)
+ if (strcmp (name, commands[i].name) == 0)
+ return (&commands[i]);
+
+ return ((COMMAND *)NULL);
+}
+
+/* Strip whitespace from the start and end of STRING. Return a pointer
+ into STRING. */
+char *
+stripwhite (char *string)
+{
+ register char *s, *t;
+
+ for (s = string; isspace (*s); s++)
+ ;
+
+ if (*s == 0)
+ return (s);
+
+ t = s + strlen (s) - 1;
+ while (t > s && isspace (*t))
+ t--;
+ *++t = '\0';
+
+ return s;
+}
+
+/* **************************************************************** */
+/* */
+/* Interface to Readline Completion */
+/* */
+/* **************************************************************** */
+
+char *command_generator(const char *, int);
+char **fileman_completion(const char *, int, int);
+
+/* Tell the GNU Readline library how to complete. We want to try to
+ complete on command names if this is the first word in the line, or
+ on filenames if not. */
+void
+initialize_readline ()
+{
+ /* Allow conditional parsing of the ~/.inputrc file. */
+ rl_readline_name = "FileMan";
+
+ /* Tell the completer that we want a crack first. */
+ rl_attempted_completion_function = fileman_completion;
+}
+
+/* Attempt to complete on the contents of TEXT. START and END
+ bound the region of rl_line_buffer that contains the word to
+ complete. TEXT is the word to complete. We can use the entire
+ contents of rl_line_buffer in case we want to do some simple
+ parsing. Returnthe array of matches, or NULL if there aren't any. */
+char **
+fileman_completion (const char* text, int start, int end)
+{
+ char **matches;
+
+ matches = (char **)NULL;
+
+ /* If this word is at the start of the line, then it is a command
+ to complete. Otherwise it is the name of a file in the current
+ directory. */
+ if (start == 0)
+ /* TODO */
+ matches = completion_matches (text, command_generator);
+ /* matches = rl_completion_matches (text, command_generator); */
+
+ return (matches);
+}
+
+/* Generator function for command completion. STATE lets us
+ know whether to start from scratch; without any state
+ (i.e. STATE == 0), then we start at the top of the list. */
+char *
+command_generator (text, state)
+ const char *text;
+ int state;
+{
+ static int list_index, len;
+ char *name;
+
+ /* If this is a new word to complete, initialize now. This
+ includes saving the length of TEXT for efficiency, and
+ initializing the index variable to 0. */
+ if (!state)
+ {
+ list_index = 0;
+ len = strlen (text);
+ }
+
+ /* Return the next name which partially matches from the
+ command list. */
+ while (name = commands[list_index].name)
+ {
+ list_index++;
+
+ if (strncmp (name, text, len) == 0)
+ return (dupstr(name));
+ }
+
+ /* If no names matched, then return NULL. */
+ return ((char *)NULL);
+}
+
+/* **************************************************************** */
+/* */
+/* FileMan Commands */
+/* */
+/* **************************************************************** */
+
+/* String to pass to system (). This is for the LIST, VIEW and RENAME
+ commands. */
+static char syscom[1024];
+
+/* List the file(s) named in arg. */
+int
+com_list (char *arg)
+{
+ if (!arg)
+ arg = "";
+
+ sprintf (syscom, "ls -FClg %s", arg);
+ return (system (syscom));
+}
+
+int
+com_view (char *arg)
+{
+ if (!valid_argument ("view", arg))
+ return 1;
+
+ sprintf (syscom, "more %s", arg);
+ return (system (syscom));
+}
+
+int
+com_history(char* arg)
+{
+ HIST_ENTRY *he;
+
+ /* rewind history */
+ while (next_history())
+ ;
+
+ for (he = current_history(); he != NULL; he = previous_history()) {
+ //printf("%5d %s\n", *((int*)he->data) - 1, he->line);
+ printf("%s\n", he->line);
+ }
+
+ return 0;
+}
+
+int
+com_rename (char *arg)
+{
+ too_dangerous ("rename");
+ return (1);
+}
+
+int
+com_stat (char *arg)
+{
+ struct stat finfo;
+
+ if (!valid_argument ("stat", arg))
+ return (1);
+
+ if (stat (arg, &finfo) == -1)
+ {
+ perror (arg);
+ return (1);
+ }
+
+ printf ("Statistics for `%s':\n", arg);
+
+ printf ("%s has %ld link%s, and is %lld byte%s in length.\n", arg,
+ (long) finfo.st_nlink,
+ (finfo.st_nlink == 1) ? "" : "s",
+ (long long) finfo.st_size,
+ (finfo.st_size == 1) ? "" : "s");
+ printf ("Inode Last Change at: %s", ctime (&finfo.st_ctime));
+ printf (" Last access at: %s", ctime (&finfo.st_atime));
+ printf (" Last modified at: %s", ctime (&finfo.st_mtime));
+ return (0);
+}
+
+int
+com_delete (char *arg)
+{
+ too_dangerous ("delete");
+ return (1);
+}
+
+/* Print out help for ARG, or for all of the commands if ARG is
+ not present. */
+int
+com_help (char *arg)
+{
+ register int i;
+ int printed = 0;
+
+ for (i = 0; commands[i].name; i++)
+ {
+ if (!*arg || (strcmp (arg, commands[i].name) == 0))
+ {
+ printf ("%s\t\t%s.\n", commands[i].name, commands[i].doc);
+ printed++;
+ }
+ }
+
+ if (!printed)
+ {
+ printf ("No commands match `%s'. Possibilties are:\n", arg);
+
+ for (i = 0; commands[i].name; i++)
+ {
+ /* Print in six columns. */
+ if (printed == 6)
+ {
+ printed = 0;
+ printf ("\n");
+ }
+
+ printf ("%s\t", commands[i].name);
+ printed++;
+ }
+
+ if (printed)
+ printf ("\n");
+ }
+ return (0);
+}
+
+/* Change to the directory ARG. */
+int
+com_cd (char *arg)
+{
+ if (chdir (arg) == -1)
+ {
+ perror (arg);
+ return 1;
+ }
+
+ com_pwd ("");
+ return (0);
+}
+
+/* Print out the current working directory. */
+int
+com_pwd (char* ignore)
+{
+ char dir[1024], *s;
+
+ s = (char*)getcwd(dir, sizeof(dir) - 1);
+ if (s == 0)
+ {
+ printf ("Error getting pwd: %s\n", dir);
+ return 1;
+ }
+
+ printf ("Current directory is %s\n", dir);
+ return 0;
+}
+
+/* The user wishes to quit using this program. Just set DONE
+ non-zero. */
+int
+com_quit (char *arg)
+{
+ done = 1;
+ return (0);
+}
+
+/* Function which tells you that you can't do this. */
+void
+too_dangerous (char *caller)
+{
+ fprintf (stderr,
+ "%s: Too dangerous for me to distribute.\n",
+ caller);
+ fprintf (stderr, "Write it yourself.\n");
+}
+
+/* Return non-zero if ARG is a valid argument for CALLER,
+ else print an error message and return zero. */
+int
+valid_argument (char *caller, char *arg)
+{
+ if (!arg || !*arg)
+ {
+ fprintf (stderr, "%s: Argument required.\n", caller);
+ return (0);
+ }
+
+ return (1);
+}
+
+void *
+xmalloc (size_t size)
+{
+ register void *value = (void*)malloc(size);
+ if (value == 0)
+ fprintf(stderr, "virtual memory exhausted");
+ return value;
+}
+
+
diff --git a/third_party/heimdal/lib/libedit/examples/tc1.c b/third_party/heimdal/lib/libedit/examples/tc1.c
new file mode 100644
index 0000000..5ebe3f6
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/examples/tc1.c
@@ -0,0 +1,309 @@
+/* $NetBSD: tc1.c,v 1.5 2010/04/18 21:17:47 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#ifndef lint
+__COPYRIGHT("@(#) Copyright (c) 1992, 1993\n\
+ The Regents of the University of California. All rights reserved.\n");
+#endif /* not lint */
+
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)test.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: tc1.c,v 1.5 2010/04/18 21:17:47 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/* from src/sys/sys/cdefs.h */
+#ifndef __UNCONST
+# define __UNCONST(a) ((void *)(unsigned long)(const void *)(a))
+#endif
+
+/*
+ * test.c: A little test program
+ */
+#include <stdio.h>
+#include <string.h>
+#include <signal.h>
+#include <sys/wait.h>
+#include <ctype.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <dirent.h>
+#include <locale.h>
+
+#include "histedit.h"
+
+static int continuation = 0;
+volatile sig_atomic_t gotsig = 0;
+
+static unsigned char complete(EditLine *, int);
+ int main(int, char **);
+static char *prompt(EditLine *);
+static void sig(int);
+
+static char *
+prompt(EditLine *el)
+{
+ static char a[] = "\1\033[7m\1Edit$\1\033[0m\1 ";
+ static char b[] = "Edit> ";
+
+ return (continuation ? b : a);
+}
+
+static void
+sig(int i)
+{
+ gotsig = i;
+}
+
+static unsigned char
+complete(EditLine *el, int ch)
+{
+ DIR *dd = opendir(".");
+ struct dirent *dp;
+ const char* ptr;
+ const LineInfo *lf = el_line(el);
+ int len;
+ int res = CC_ERROR;
+
+ /*
+ * Find the last word
+ */
+ for (ptr = lf->cursor - 1;
+ !isspace((unsigned char)*ptr) && ptr > lf->buffer; ptr--)
+ continue;
+ len = lf->cursor - ++ptr;
+
+ for (dp = readdir(dd); dp != NULL; dp = readdir(dd)) {
+ if (len > strlen(dp->d_name))
+ continue;
+ if (strncmp(dp->d_name, ptr, len) == 0) {
+ if (el_insertstr(el, &dp->d_name[len]) == -1)
+ res = CC_ERROR;
+ else
+ res = CC_REFRESH;
+ break;
+ }
+ }
+
+ closedir(dd);
+ return res;
+}
+
+int
+main(int argc, char *argv[])
+{
+ EditLine *el = NULL;
+ int num;
+ const char *buf;
+ Tokenizer *tok;
+#if 0
+ int lastevent = 0;
+#endif
+ int ncontinuation;
+ History *hist;
+ HistEvent ev;
+
+ (void) setlocale(LC_CTYPE, "");
+ (void) signal(SIGINT, sig);
+ (void) signal(SIGQUIT, sig);
+ (void) signal(SIGHUP, sig);
+ (void) signal(SIGTERM, sig);
+
+ hist = history_init(); /* Init the builtin history */
+ /* Remember 100 events */
+ history(hist, &ev, H_SETSIZE, 100);
+
+ tok = tok_init(NULL); /* Initialize the tokenizer */
+
+ /* Initialize editline */
+ el = el_init(*argv, stdin, stdout, stderr);
+
+ el_set(el, EL_EDITOR, "vi"); /* Default editor is vi */
+ el_set(el, EL_SIGNAL, 1); /* Handle signals gracefully */
+ el_set(el, EL_PROMPT_ESC, prompt, '\1');/* Set the prompt function */
+
+ /* Tell editline to use this history interface */
+ el_set(el, EL_HIST, history, hist);
+
+ /* Add a user-defined function */
+ el_set(el, EL_ADDFN, "ed-complete", "Complete argument", complete);
+
+ /* Bind tab to it */
+ el_set(el, EL_BIND, "^I", "ed-complete", NULL);
+
+ /*
+ * Bind j, k in vi command mode to previous and next line, instead
+ * of previous and next history.
+ */
+ el_set(el, EL_BIND, "-a", "k", "ed-prev-line", NULL);
+ el_set(el, EL_BIND, "-a", "j", "ed-next-line", NULL);
+
+ /*
+ * Source the user's defaults file.
+ */
+ el_source(el, NULL);
+
+ while ((buf = el_gets(el, &num)) != NULL && num != 0) {
+ int ac, cc, co;
+#ifdef DEBUG
+ int i;
+#endif
+ const char **av;
+ const LineInfo *li;
+ li = el_line(el);
+#ifdef DEBUG
+ (void) fprintf(stderr, "==> got %d %s", num, buf);
+ (void) fprintf(stderr, " > li `%.*s_%.*s'\n",
+ (li->cursor - li->buffer), li->buffer,
+ (li->lastchar - 1 - li->cursor),
+ (li->cursor >= li->lastchar) ? "" : li->cursor);
+
+#endif
+ if (gotsig) {
+ (void) fprintf(stderr, "Got signal %d.\n", gotsig);
+ gotsig = 0;
+ el_reset(el);
+ }
+
+ if (!continuation && num == 1)
+ continue;
+
+ ac = cc = co = 0;
+ ncontinuation = tok_line(tok, li, &ac, &av, &cc, &co);
+ if (ncontinuation < 0) {
+ (void) fprintf(stderr, "Internal error\n");
+ continuation = 0;
+ continue;
+ }
+#ifdef DEBUG
+ (void) fprintf(stderr, " > nc %d ac %d cc %d co %d\n",
+ ncontinuation, ac, cc, co);
+#endif
+#if 0
+ if (continuation) {
+ /*
+ * Append to the right event in case the user
+ * moved around in history.
+ */
+ if (history(hist, &ev, H_SET, lastevent) == -1)
+ err(1, "%d: %s", lastevent, ev.str);
+ history(hist, &ev, H_ADD , buf);
+ } else {
+ history(hist, &ev, H_ENTER, buf);
+ lastevent = ev.num;
+ }
+#else
+ /* Simpler */
+ history(hist, &ev, continuation ? H_APPEND : H_ENTER, buf);
+#endif
+
+ continuation = ncontinuation;
+ ncontinuation = 0;
+ if (continuation)
+ continue;
+#ifdef DEBUG
+ for (i = 0; i < ac; i++) {
+ (void) fprintf(stderr, " > arg# %2d ", i);
+ if (i != cc)
+ (void) fprintf(stderr, "`%s'\n", av[i]);
+ else
+ (void) fprintf(stderr, "`%.*s_%s'\n",
+ co, av[i], av[i] + co);
+ }
+#endif
+
+ if (strcmp(av[0], "history") == 0) {
+ int rv;
+
+ switch (ac) {
+ case 1:
+ for (rv = history(hist, &ev, H_LAST); rv != -1;
+ rv = history(hist, &ev, H_PREV))
+ (void) fprintf(stdout, "%4d %s",
+ ev.num, ev.str);
+ break;
+
+ case 2:
+ if (strcmp(av[1], "clear") == 0)
+ history(hist, &ev, H_CLEAR);
+ else
+ goto badhist;
+ break;
+
+ case 3:
+ if (strcmp(av[1], "load") == 0)
+ history(hist, &ev, H_LOAD, av[2]);
+ else if (strcmp(av[1], "save") == 0)
+ history(hist, &ev, H_SAVE, av[2]);
+ break;
+
+ badhist:
+ default:
+ (void) fprintf(stderr,
+ "Bad history arguments\n");
+ break;
+ }
+ } else if (el_parse(el, ac, av) == -1) {
+ switch (fork()) {
+ case 0:
+ execvp(av[0], (char *const *)__UNCONST(av));
+ perror(av[0]);
+ _exit(1);
+ /*NOTREACHED*/
+ break;
+
+ case -1:
+ perror("fork");
+ break;
+
+ default:
+ if (wait(&num) == -1)
+ perror("wait");
+ (void) fprintf(stderr, "Exit %x\n", num);
+ break;
+ }
+ }
+
+ tok_reset(tok);
+ }
+
+ el_end(el);
+ tok_end(tok);
+ history_end(hist);
+
+ return (0);
+}
diff --git a/third_party/heimdal/lib/libedit/examples/wtc1.c b/third_party/heimdal/lib/libedit/examples/wtc1.c
new file mode 100644
index 0000000..76ee0b4
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/examples/wtc1.c
@@ -0,0 +1,269 @@
+#include <stdio.h>
+#include <string.h>
+#include <signal.h>
+#include <sys/wait.h>
+#include <ctype.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <dirent.h>
+#include <limits.h>
+#include <locale.h>
+
+#include <histedit.h>
+
+
+static int continuation;
+volatile sig_atomic_t gotsig;
+
+static wchar_t *
+prompt(EditLine *el)
+{
+ static wchar_t a[] = L"\1\033[7m\1Edit$\1\033[0m\1 ";
+ static wchar_t b[] = L"Edit> ";
+
+ return continuation ? b : a;
+}
+
+
+static void
+sig(int i)
+{
+ gotsig = i;
+}
+
+const char *
+my_wcstombs(const wchar_t *wstr)
+{
+ static struct {
+ char *str;
+ int len;
+ } buf;
+
+ int needed = wcstombs(0, wstr, 0) + 1;
+ if (needed > buf.len) {
+ buf.str = malloc(needed);
+ buf.len = needed;
+ }
+ wcstombs(buf.str, wstr, needed);
+ buf.str[needed - 1] = 0;
+
+ return buf.str;
+}
+
+
+static unsigned char
+complete(EditLine *el, int ch)
+{
+ DIR *dd = opendir(".");
+ struct dirent *dp;
+ const wchar_t *ptr;
+ char *buf, *bptr;
+ const LineInfoW *lf = el_wline(el);
+ int len, mblen, i;
+ unsigned char res;
+
+ /* Find the last word */
+ for (ptr = lf->cursor -1; !iswspace(*ptr) && ptr > lf->buffer; --ptr)
+ continue;
+ len = lf->cursor - ++ptr;
+
+ /* Convert last word to multibyte encoding, so we can compare to it */
+ wctomb(NULL, 0); /* Reset shift state */
+ mblen = MB_LEN_MAX * len + 1;
+ buf = bptr =(char *)malloc(mblen);
+ for (i = 0; i < len; ++i) {
+ /* Note: really should test for -1 return from wctomb */
+ bptr += wctomb(bptr, ptr[i]);
+ }
+ *bptr = 0; /* Terminate multibyte string */
+ mblen = bptr - buf;
+
+ /* Scan directory for matching name */
+ for (dp = readdir(dd); dp != NULL; dp = readdir(dd)) {
+ if (mblen > strlen(dp->d_name))
+ continue;
+ if (strncmp(dp->d_name, buf, mblen) == 0) {
+ if (el_insertstr(el, &dp->d_name[mblen]) == -1)
+ res = CC_ERROR;
+ else
+ res = CC_REFRESH;
+ break;
+ }
+ }
+
+ closedir(dd);
+ free(buf);
+ return res;
+}
+
+
+int
+main(int argc, char *argv[])
+{
+ EditLine *el = NULL;
+ int numc, ncontinuation;
+ const wchar_t *line;
+ TokenizerW *tok;
+ HistoryW *hist;
+ HistEventW ev;
+#ifdef DEBUG
+ int i;
+#endif
+
+ setlocale(LC_ALL, "");
+
+ (void)signal(SIGINT, sig);
+ (void)signal(SIGQUIT, sig);
+ (void)signal(SIGHUP, sig);
+ (void)signal(SIGTERM, sig);
+
+ hist = history_winit(); /* Init built-in history */
+ history_w(hist, &ev, H_SETSIZE, 100); /* Remember 100 events */
+
+ tok = tok_winit(NULL); /* Init the tokenizer */
+
+ el = el_init(argv[0], stdin, stdout, stderr);
+
+ el_wset(el, EL_EDITOR, L"vi"); /* Default editor is vi */
+ el_wset(el, EL_SIGNAL, 1); /* Handle signals gracefully */
+ el_wset(el, EL_PROMPT_ESC, prompt, '\1'); /* Set the prompt function */
+
+ el_wset(el, EL_HIST, history_w, hist); /* FIXME - history_w? */
+
+ /* Add a user-defined function */
+ el_wset(el, EL_ADDFN, L"ed-complete", L"Complete argument", complete);
+
+ /* Bind <tab> to it */
+ el_wset(el, EL_BIND, L"^I", L"ed-complete", NULL);
+
+ /*
+ * Bind j, k in vi command mode to previous and next line, instead
+ * of previous and next history.
+ */
+ el_wset(el, EL_BIND, L"-a", L"k", L"ed-prev-line", NULL);
+ el_wset(el, EL_BIND, L"-a", L"j", L"ed-next-line", NULL);
+
+ /* Source the user's defaults file. */
+ el_source(el, NULL);
+
+ while((line = el_wgets(el, &numc)) != NULL && numc != 0) {
+ int ac, cc, co, rc;
+ const wchar_t **av;
+
+ const LineInfoW *li;
+ li = el_wline(el);
+
+#ifdef DEBUG
+ (void)fwprintf(stderr, L"==> got %d %ls", numc, line);
+ (void)fwprintf(stderr, L" > li `%.*ls_%.*ls'\n",
+ (li->cursor - li->buffer), li->buffer,
+ (li->lastchar - 1 - li->cursor),
+ (li->cursor >= li->lastchar) ? L"" : li->cursor);
+#endif
+
+ if (gotsig) {
+ (void)fprintf(stderr, "Got signal %d.\n", gotsig);
+ gotsig = 0;
+ el_reset(el);
+ }
+
+ if(!continuation && numc == 1)
+ continue; /* Only got a linefeed */
+
+ ac = cc = co = 0;
+ ncontinuation = tok_wline(tok, li, &ac, &av, &cc, &co);
+ if (ncontinuation < 0) {
+ (void) fprintf(stderr, "Internal error\n");
+ continuation = 0;
+ continue;
+ }
+
+#ifdef DEBUG
+ (void)fprintf(stderr, " > nc %d ac %d cc %d co %d\n",
+ ncontinuation, ac, cc, co);
+#endif
+ history_w(hist, &ev, continuation ? H_APPEND : H_ENTER, line);
+
+ continuation = ncontinuation;
+ ncontinuation = 0;
+ if(continuation)
+ continue;
+
+#ifdef DEBUG
+ for (i = 0; i < ac; ++i) {
+ (void)fwprintf(stderr, L" > arg# %2d ", i);
+ if (i != cc)
+ (void)fwprintf(stderr, L"`%ls'\n", av[i]);
+ else
+ (void)fwprintf(stderr, L"`%.*ls_%ls'\n",
+ co, av[i], av[i] + co);
+ }
+#endif
+
+ if (wcscmp (av[0], L"history") == 0) {
+ switch(ac) {
+ case 1:
+ for(rc = history_w(hist, &ev, H_LAST);
+ rc != -1;
+ rc = history_w(hist, &ev, H_PREV))
+ (void)fwprintf(stdout, L"%4d %ls",
+ ev.num, ev.str);
+ break;
+ case 2:
+ if (wcscmp(av[1], L"clear") == 0)
+ history_w(hist, &ev, H_CLEAR);
+ else
+ goto badhist;
+ break;
+ case 3:
+ if (wcscmp(av[1], L"load") == 0)
+ history_w(hist, &ev, H_LOAD,
+ my_wcstombs(av[2]));
+ else if (wcscmp(av[1], L"save") == 0)
+ history_w(hist, &ev, H_SAVE,
+ my_wcstombs(av[2]));
+ else
+ goto badhist;
+ break;
+ badhist:
+ default:
+ (void)fprintf(stderr,
+ "Bad history arguments\n");
+ break;
+ }
+ } else if (el_wparse(el, ac, av) == -1) {
+ switch (fork()) {
+ case 0: {
+ Tokenizer *ntok = tok_init(NULL);
+ int nargc;
+ const char **nav;
+ tok_str(ntok, my_wcstombs(line), &nargc, &nav);
+ execvp(nav[0],(char **)nav);
+ perror(nav[0]);
+ _exit(1);
+ /* NOTREACHED */
+ break;
+ }
+ case -1:
+ perror("fork");
+ break;
+ default:
+ if (wait(&rc) == -1)
+ perror("wait");
+ (void)fprintf(stderr, "Exit %x\n", rc);
+ break;
+ }
+ }
+
+ tok_wreset(tok);
+ }
+
+ el_end(el);
+ tok_wend(tok);
+ history_wend(hist);
+
+ fprintf(stdout, "\n");
+ return 0;
+}
+
+
diff --git a/third_party/heimdal/lib/libedit/libedit.pc.in b/third_party/heimdal/lib/libedit/libedit.pc.in
new file mode 100644
index 0000000..deaaa39
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/libedit.pc.in
@@ -0,0 +1,12 @@
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: libedit
+Description: command line editor library provides generic line editing, history, and tokenization functions.
+Version: @VERSION@
+Requires:
+Libs: -L${libdir} -ledit @LIBS@
+Cflags: -I${includedir} -I${includedir}/editline
+
diff --git a/third_party/heimdal/lib/libedit/src/Makefile.am b/third_party/heimdal/lib/libedit/src/Makefile.am
new file mode 100644
index 0000000..565e56e
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/Makefile.am
@@ -0,0 +1,43 @@
+
+BUILT_SOURCES = vi.h emacs.h common.h fcns.h help.h func.h
+
+AHDR= vi.h emacs.h common.h
+ASRC= $(srcdir)/vi.c $(srcdir)/emacs.c $(srcdir)/common.c
+
+vi.h: Makefile $(srcdir)/makelist $(srcdir)/vi.c
+ AWK=$(AWK) sh $(srcdir)/makelist -h $(srcdir)/vi.c > $@
+
+emacs.h: Makefile $(srcdir)/makelist $(srcdir)/emacs.c
+ AWK=$(AWK) sh $(srcdir)/makelist -h $(srcdir)/emacs.c > $@
+
+common.h: Makefile $(srcdir)/makelist $(srcdir)/common.c
+ AWK=$(AWK) sh $(srcdir)/makelist -h $(srcdir)/common.c > $@
+
+fcns.h: Makefile $(srcdir)/makelist $(AHDR)
+ AWK=$(AWK) sh $(srcdir)/makelist -fh $(AHDR) > $@
+
+func.h: Makefile $(srcdir)/makelist $(AHDR)
+ AWK=$(AWK) sh $(srcdir)/makelist -fc $(AHDR) > $@
+
+help.h: Makefile $(srcdir)/makelist $(ASRC)
+ AWK=$(AWK) sh $(srcdir)/makelist -bh $(ASRC) > $@
+
+CLEANFILES = $(BUILT_SOURCES)
+
+lib_LTLIBRARIES = libheimedit.la
+libheimedit_la_SOURCES = \
+ chared.c chartype.c common.c el.c eln.c emacs.c filecomplete.c getline.c hist.c \
+ history.c historyn.c keymacro.c map.c parse.c prompt.c read.c readline.c \
+ refresh.c search.c sig.c terminal.c tokenizer.c tokenizern.c tty.c \
+ unvis.c vi.c vis.c wcsdup.c \
+ chared.h chartype.h readline/readline.h el.h filecomplete.h \
+ histedit.h hist.h keymacro.h map.h parse.h prompt.h read.h \
+ refresh.h search.h sig.h sys.h terminal.h tty.h vis.h
+
+EXTRA_DIST = makelist shlib_version
+EXTRA_DIST += histedit.h readline/readline.h
+
+nodist_libheimedit_la_SOURCES = $(BUILT_SOURCES)
+
+libheimedit_la_LDFLAGS = -no-undefined -version-info $(LT_VERSION)
+
diff --git a/third_party/heimdal/lib/libedit/src/chared.c b/third_party/heimdal/lib/libedit/src/chared.c
new file mode 100644
index 0000000..9d46ba6
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/chared.c
@@ -0,0 +1,753 @@
+/* $NetBSD: chared.c,v 1.56 2016/05/22 19:44:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)chared.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: chared.c,v 1.56 2016/05/22 19:44:26 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * chared.c: Character editor utilities
+ */
+#include <ctype.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "el.h"
+#include "common.h"
+#include "fcns.h"
+
+/* value to leave unused in line buffer */
+#define EL_LEAVE 2
+
+/* cv_undo():
+ * Handle state for the vi undo command
+ */
+libedit_private void
+cv_undo(EditLine *el)
+{
+ c_undo_t *vu = &el->el_chared.c_undo;
+ c_redo_t *r = &el->el_chared.c_redo;
+ size_t size;
+
+ /* Save entire line for undo */
+ size = (size_t)(el->el_line.lastchar - el->el_line.buffer);
+ vu->len = (ssize_t)size;
+ vu->cursor = (int)(el->el_line.cursor - el->el_line.buffer);
+ (void)memcpy(vu->buf, el->el_line.buffer, size * sizeof(*vu->buf));
+
+ /* save command info for redo */
+ r->count = el->el_state.doingarg ? el->el_state.argument : 0;
+ r->action = el->el_chared.c_vcmd.action;
+ r->pos = r->buf;
+ r->cmd = el->el_state.thiscmd;
+ r->ch = el->el_state.thisch;
+}
+
+/* cv_yank():
+ * Save yank/delete data for paste
+ */
+libedit_private void
+cv_yank(EditLine *el, const wchar_t *ptr, int size)
+{
+ c_kill_t *k = &el->el_chared.c_kill;
+
+ (void)memcpy(k->buf, ptr, (size_t)size * sizeof(*k->buf));
+ k->last = k->buf + size;
+}
+
+
+/* c_insert():
+ * Insert num characters
+ */
+libedit_private void
+c_insert(EditLine *el, int num)
+{
+ wchar_t *cp;
+
+ if (el->el_line.lastchar + num >= el->el_line.limit) {
+ if (!ch_enlargebufs(el, (size_t)num))
+ return; /* can't go past end of buffer */
+ }
+
+ if (el->el_line.cursor < el->el_line.lastchar) {
+ /* if I must move chars */
+ for (cp = el->el_line.lastchar; cp >= el->el_line.cursor; cp--)
+ cp[num] = *cp;
+ }
+ el->el_line.lastchar += num;
+}
+
+
+/* c_delafter():
+ * Delete num characters after the cursor
+ */
+libedit_private void
+c_delafter(EditLine *el, int num)
+{
+
+ if (el->el_line.cursor + num > el->el_line.lastchar)
+ num = (int)(el->el_line.lastchar - el->el_line.cursor);
+
+ if (el->el_map.current != el->el_map.emacs) {
+ cv_undo(el);
+ cv_yank(el, el->el_line.cursor, num);
+ }
+
+ if (num > 0) {
+ wchar_t *cp;
+
+ for (cp = el->el_line.cursor; cp <= el->el_line.lastchar; cp++)
+ *cp = cp[num];
+
+ el->el_line.lastchar -= num;
+ }
+}
+
+
+/* c_delafter1():
+ * Delete the character after the cursor, do not yank
+ */
+libedit_private void
+c_delafter1(EditLine *el)
+{
+ wchar_t *cp;
+
+ for (cp = el->el_line.cursor; cp <= el->el_line.lastchar; cp++)
+ *cp = cp[1];
+
+ el->el_line.lastchar--;
+}
+
+
+/* c_delbefore():
+ * Delete num characters before the cursor
+ */
+libedit_private void
+c_delbefore(EditLine *el, int num)
+{
+
+ if (el->el_line.cursor - num < el->el_line.buffer)
+ num = (int)(el->el_line.cursor - el->el_line.buffer);
+
+ if (el->el_map.current != el->el_map.emacs) {
+ cv_undo(el);
+ cv_yank(el, el->el_line.cursor - num, num);
+ }
+
+ if (num > 0) {
+ wchar_t *cp;
+
+ for (cp = el->el_line.cursor - num;
+ cp <= el->el_line.lastchar;
+ cp++)
+ *cp = cp[num];
+
+ el->el_line.lastchar -= num;
+ }
+}
+
+
+/* c_delbefore1():
+ * Delete the character before the cursor, do not yank
+ */
+libedit_private void
+c_delbefore1(EditLine *el)
+{
+ wchar_t *cp;
+
+ for (cp = el->el_line.cursor - 1; cp <= el->el_line.lastchar; cp++)
+ *cp = cp[1];
+
+ el->el_line.lastchar--;
+}
+
+
+/* ce__isword():
+ * Return if p is part of a word according to emacs
+ */
+libedit_private int
+ce__isword(wint_t p)
+{
+ return iswalnum(p) || wcschr(L"*?_-.[]~=", p) != NULL;
+}
+
+
+/* cv__isword():
+ * Return if p is part of a word according to vi
+ */
+libedit_private int
+cv__isword(wint_t p)
+{
+ if (iswalnum(p) || p == L'_')
+ return 1;
+ if (iswgraph(p))
+ return 2;
+ return 0;
+}
+
+
+/* cv__isWord():
+ * Return if p is part of a big word according to vi
+ */
+libedit_private int
+cv__isWord(wint_t p)
+{
+ return !iswspace(p);
+}
+
+
+/* c__prev_word():
+ * Find the previous word
+ */
+libedit_private wchar_t *
+c__prev_word(wchar_t *p, wchar_t *low, int n, int (*wtest)(wint_t))
+{
+ p--;
+
+ while (n--) {
+ while ((p >= low) && !(*wtest)(*p))
+ p--;
+ while ((p >= low) && (*wtest)(*p))
+ p--;
+ }
+
+ /* cp now points to one character before the word */
+ p++;
+ if (p < low)
+ p = low;
+ /* cp now points where we want it */
+ return p;
+}
+
+
+/* c__next_word():
+ * Find the next word
+ */
+libedit_private wchar_t *
+c__next_word(wchar_t *p, wchar_t *high, int n, int (*wtest)(wint_t))
+{
+ while (n--) {
+ while ((p < high) && !(*wtest)(*p))
+ p++;
+ while ((p < high) && (*wtest)(*p))
+ p++;
+ }
+ if (p > high)
+ p = high;
+ /* p now points where we want it */
+ return p;
+}
+
+/* cv_next_word():
+ * Find the next word vi style
+ */
+libedit_private wchar_t *
+cv_next_word(EditLine *el, wchar_t *p, wchar_t *high, int n,
+ int (*wtest)(wint_t))
+{
+ int test;
+
+ while (n--) {
+ test = (*wtest)(*p);
+ while ((p < high) && (*wtest)(*p) == test)
+ p++;
+ /*
+ * vi historically deletes with cw only the word preserving the
+ * trailing whitespace! This is not what 'w' does..
+ */
+ if (n || el->el_chared.c_vcmd.action != (DELETE|INSERT))
+ while ((p < high) && iswspace(*p))
+ p++;
+ }
+
+ /* p now points where we want it */
+ if (p > high)
+ return high;
+ else
+ return p;
+}
+
+
+/* cv_prev_word():
+ * Find the previous word vi style
+ */
+libedit_private wchar_t *
+cv_prev_word(wchar_t *p, wchar_t *low, int n, int (*wtest)(wint_t))
+{
+ int test;
+
+ p--;
+ while (n--) {
+ while ((p > low) && iswspace(*p))
+ p--;
+ test = (*wtest)(*p);
+ while ((p >= low) && (*wtest)(*p) == test)
+ p--;
+ }
+ p++;
+
+ /* p now points where we want it */
+ if (p < low)
+ return low;
+ else
+ return p;
+}
+
+
+/* cv_delfini():
+ * Finish vi delete action
+ */
+libedit_private void
+cv_delfini(EditLine *el)
+{
+ int size;
+ int action = el->el_chared.c_vcmd.action;
+
+ if (action & INSERT)
+ el->el_map.current = el->el_map.key;
+
+ if (el->el_chared.c_vcmd.pos == 0)
+ /* sanity */
+ return;
+
+ size = (int)(el->el_line.cursor - el->el_chared.c_vcmd.pos);
+ if (size == 0)
+ size = 1;
+ el->el_line.cursor = el->el_chared.c_vcmd.pos;
+ if (action & YANK) {
+ if (size > 0)
+ cv_yank(el, el->el_line.cursor, size);
+ else
+ cv_yank(el, el->el_line.cursor + size, -size);
+ } else {
+ if (size > 0) {
+ c_delafter(el, size);
+ re_refresh_cursor(el);
+ } else {
+ c_delbefore(el, -size);
+ el->el_line.cursor += size;
+ }
+ }
+ el->el_chared.c_vcmd.action = NOP;
+}
+
+
+/* cv__endword():
+ * Go to the end of this word according to vi
+ */
+libedit_private wchar_t *
+cv__endword(wchar_t *p, wchar_t *high, int n, int (*wtest)(wint_t))
+{
+ int test;
+
+ p++;
+
+ while (n--) {
+ while ((p < high) && iswspace(*p))
+ p++;
+
+ test = (*wtest)(*p);
+ while ((p < high) && (*wtest)(*p) == test)
+ p++;
+ }
+ p--;
+ return p;
+}
+
+/* ch_init():
+ * Initialize the character editor
+ */
+libedit_private int
+ch_init(EditLine *el)
+{
+ el->el_line.buffer = el_malloc(EL_BUFSIZ *
+ sizeof(*el->el_line.buffer));
+ if (el->el_line.buffer == NULL)
+ return -1;
+
+ (void) memset(el->el_line.buffer, 0, EL_BUFSIZ *
+ sizeof(*el->el_line.buffer));
+ el->el_line.cursor = el->el_line.buffer;
+ el->el_line.lastchar = el->el_line.buffer;
+ el->el_line.limit = &el->el_line.buffer[EL_BUFSIZ - EL_LEAVE];
+
+ el->el_chared.c_undo.buf = el_malloc(EL_BUFSIZ *
+ sizeof(*el->el_chared.c_undo.buf));
+ if (el->el_chared.c_undo.buf == NULL)
+ return -1;
+ (void) memset(el->el_chared.c_undo.buf, 0, EL_BUFSIZ *
+ sizeof(*el->el_chared.c_undo.buf));
+ el->el_chared.c_undo.len = -1;
+ el->el_chared.c_undo.cursor = 0;
+ el->el_chared.c_redo.buf = el_malloc(EL_BUFSIZ *
+ sizeof(*el->el_chared.c_redo.buf));
+ if (el->el_chared.c_redo.buf == NULL)
+ return -1;
+ el->el_chared.c_redo.pos = el->el_chared.c_redo.buf;
+ el->el_chared.c_redo.lim = el->el_chared.c_redo.buf + EL_BUFSIZ;
+ el->el_chared.c_redo.cmd = ED_UNASSIGNED;
+
+ el->el_chared.c_vcmd.action = NOP;
+ el->el_chared.c_vcmd.pos = el->el_line.buffer;
+
+ el->el_chared.c_kill.buf = el_malloc(EL_BUFSIZ *
+ sizeof(*el->el_chared.c_kill.buf));
+ if (el->el_chared.c_kill.buf == NULL)
+ return -1;
+ (void) memset(el->el_chared.c_kill.buf, 0, EL_BUFSIZ *
+ sizeof(*el->el_chared.c_kill.buf));
+ el->el_chared.c_kill.mark = el->el_line.buffer;
+ el->el_chared.c_kill.last = el->el_chared.c_kill.buf;
+ el->el_chared.c_resizefun = NULL;
+ el->el_chared.c_resizearg = NULL;
+ el->el_chared.c_aliasfun = NULL;
+ el->el_chared.c_aliasarg = NULL;
+
+ el->el_map.current = el->el_map.key;
+
+ el->el_state.inputmode = MODE_INSERT; /* XXX: save a default */
+ el->el_state.doingarg = 0;
+ el->el_state.metanext = 0;
+ el->el_state.argument = 1;
+ el->el_state.lastcmd = ED_UNASSIGNED;
+
+ return 0;
+}
+
+/* ch_reset():
+ * Reset the character editor
+ */
+libedit_private void
+ch_reset(EditLine *el)
+{
+ el->el_line.cursor = el->el_line.buffer;
+ el->el_line.lastchar = el->el_line.buffer;
+
+ el->el_chared.c_undo.len = -1;
+ el->el_chared.c_undo.cursor = 0;
+
+ el->el_chared.c_vcmd.action = NOP;
+ el->el_chared.c_vcmd.pos = el->el_line.buffer;
+
+ el->el_chared.c_kill.mark = el->el_line.buffer;
+
+ el->el_map.current = el->el_map.key;
+
+ el->el_state.inputmode = MODE_INSERT; /* XXX: save a default */
+ el->el_state.doingarg = 0;
+ el->el_state.metanext = 0;
+ el->el_state.argument = 1;
+ el->el_state.lastcmd = ED_UNASSIGNED;
+
+ el->el_history.eventno = 0;
+}
+
+/* ch_enlargebufs():
+ * Enlarge line buffer to be able to hold twice as much characters.
+ * Returns 1 if successful, 0 if not.
+ */
+libedit_private int
+ch_enlargebufs(EditLine *el, size_t addlen)
+{
+ size_t sz, newsz;
+ wchar_t *newbuffer, *oldbuf, *oldkbuf;
+
+ sz = (size_t)(el->el_line.limit - el->el_line.buffer + EL_LEAVE);
+ newsz = sz * 2;
+ /*
+ * If newly required length is longer than current buffer, we need
+ * to make the buffer big enough to hold both old and new stuff.
+ */
+ if (addlen > sz) {
+ while(newsz - sz < addlen)
+ newsz *= 2;
+ }
+
+ /*
+ * Reallocate line buffer.
+ */
+ newbuffer = el_realloc(el->el_line.buffer, newsz * sizeof(*newbuffer));
+ if (!newbuffer)
+ return 0;
+
+ /* zero the newly added memory, leave old data in */
+ (void) memset(&newbuffer[sz], 0, (newsz - sz) * sizeof(*newbuffer));
+
+ oldbuf = el->el_line.buffer;
+
+ el->el_line.buffer = newbuffer;
+ el->el_line.cursor = newbuffer + (el->el_line.cursor - oldbuf);
+ el->el_line.lastchar = newbuffer + (el->el_line.lastchar - oldbuf);
+ /* don't set new size until all buffers are enlarged */
+ el->el_line.limit = &newbuffer[sz - EL_LEAVE];
+
+ /*
+ * Reallocate kill buffer.
+ */
+ newbuffer = el_realloc(el->el_chared.c_kill.buf, newsz *
+ sizeof(*newbuffer));
+ if (!newbuffer)
+ return 0;
+
+ /* zero the newly added memory, leave old data in */
+ (void) memset(&newbuffer[sz], 0, (newsz - sz) * sizeof(*newbuffer));
+
+ oldkbuf = el->el_chared.c_kill.buf;
+
+ el->el_chared.c_kill.buf = newbuffer;
+ el->el_chared.c_kill.last = newbuffer +
+ (el->el_chared.c_kill.last - oldkbuf);
+ el->el_chared.c_kill.mark = el->el_line.buffer +
+ (el->el_chared.c_kill.mark - oldbuf);
+
+ /*
+ * Reallocate undo buffer.
+ */
+ newbuffer = el_realloc(el->el_chared.c_undo.buf,
+ newsz * sizeof(*newbuffer));
+ if (!newbuffer)
+ return 0;
+
+ /* zero the newly added memory, leave old data in */
+ (void) memset(&newbuffer[sz], 0, (newsz - sz) * sizeof(*newbuffer));
+ el->el_chared.c_undo.buf = newbuffer;
+
+ newbuffer = el_realloc(el->el_chared.c_redo.buf,
+ newsz * sizeof(*newbuffer));
+ if (!newbuffer)
+ return 0;
+ el->el_chared.c_redo.pos = newbuffer +
+ (el->el_chared.c_redo.pos - el->el_chared.c_redo.buf);
+ el->el_chared.c_redo.lim = newbuffer +
+ (el->el_chared.c_redo.lim - el->el_chared.c_redo.buf);
+ el->el_chared.c_redo.buf = newbuffer;
+
+ if (!hist_enlargebuf(el, sz, newsz))
+ return 0;
+
+ /* Safe to set enlarged buffer size */
+ el->el_line.limit = &el->el_line.buffer[newsz - EL_LEAVE];
+ if (el->el_chared.c_resizefun)
+ (*el->el_chared.c_resizefun)(el, el->el_chared.c_resizearg);
+ return 1;
+}
+
+/* ch_end():
+ * Free the data structures used by the editor
+ */
+libedit_private void
+ch_end(EditLine *el)
+{
+ el_free(el->el_line.buffer);
+ el->el_line.buffer = NULL;
+ el->el_line.limit = NULL;
+ el_free(el->el_chared.c_undo.buf);
+ el->el_chared.c_undo.buf = NULL;
+ el_free(el->el_chared.c_redo.buf);
+ el->el_chared.c_redo.buf = NULL;
+ el->el_chared.c_redo.pos = NULL;
+ el->el_chared.c_redo.lim = NULL;
+ el->el_chared.c_redo.cmd = ED_UNASSIGNED;
+ el_free(el->el_chared.c_kill.buf);
+ el->el_chared.c_kill.buf = NULL;
+ ch_reset(el);
+}
+
+
+/* el_insertstr():
+ * Insert string at cursorI
+ */
+int
+el_winsertstr(EditLine *el, const wchar_t *s)
+{
+ size_t len;
+
+ if (s == NULL || (len = wcslen(s)) == 0)
+ return -1;
+ if (el->el_line.lastchar + len >= el->el_line.limit) {
+ if (!ch_enlargebufs(el, len))
+ return -1;
+ }
+
+ c_insert(el, (int)len);
+ while (*s)
+ *el->el_line.cursor++ = *s++;
+ return 0;
+}
+
+
+/* el_deletestr():
+ * Delete num characters before the cursor
+ */
+void
+el_deletestr(EditLine *el, int n)
+{
+ if (n <= 0)
+ return;
+
+ if (el->el_line.cursor < &el->el_line.buffer[n])
+ return;
+
+ c_delbefore(el, n); /* delete before dot */
+ el->el_line.cursor -= n;
+ if (el->el_line.cursor < el->el_line.buffer)
+ el->el_line.cursor = el->el_line.buffer;
+}
+
+/* el_cursor():
+ * Move the cursor to the left or the right of the current position
+ */
+int
+el_cursor(EditLine *el, int n)
+{
+ if (n == 0)
+ goto out;
+
+ el->el_line.cursor += n;
+
+ if (el->el_line.cursor < el->el_line.buffer)
+ el->el_line.cursor = el->el_line.buffer;
+ if (el->el_line.cursor > el->el_line.lastchar)
+ el->el_line.cursor = el->el_line.lastchar;
+out:
+ return (int)(el->el_line.cursor - el->el_line.buffer);
+}
+
+/* c_gets():
+ * Get a string
+ */
+libedit_private int
+c_gets(EditLine *el, wchar_t *buf, const wchar_t *prompt)
+{
+ ssize_t len;
+ wchar_t *cp = el->el_line.buffer, ch;
+
+ if (prompt) {
+ len = (ssize_t)wcslen(prompt);
+ (void)memcpy(cp, prompt, (size_t)len * sizeof(*cp));
+ cp += len;
+ }
+ len = 0;
+
+ for (;;) {
+ el->el_line.cursor = cp;
+ *cp = ' ';
+ el->el_line.lastchar = cp + 1;
+ re_refresh(el);
+
+ if (el_wgetc(el, &ch) != 1) {
+ ed_end_of_file(el, 0);
+ len = -1;
+ break;
+ }
+
+ switch (ch) {
+
+ case L'\b': /* Delete and backspace */
+ case 0177:
+ if (len == 0) {
+ len = -1;
+ break;
+ }
+ len--;
+ cp--;
+ continue;
+
+ case 0033: /* ESC */
+ case L'\r': /* Newline */
+ case L'\n':
+ buf[len] = ch;
+ break;
+
+ default:
+ if (len >= (ssize_t)(EL_BUFSIZ - 16))
+ terminal_beep(el);
+ else {
+ buf[len++] = ch;
+ *cp++ = ch;
+ }
+ continue;
+ }
+ break;
+ }
+
+ el->el_line.buffer[0] = '\0';
+ el->el_line.lastchar = el->el_line.buffer;
+ el->el_line.cursor = el->el_line.buffer;
+ return (int)len;
+}
+
+
+/* c_hpos():
+ * Return the current horizontal position of the cursor
+ */
+libedit_private int
+c_hpos(EditLine *el)
+{
+ wchar_t *ptr;
+
+ /*
+ * Find how many characters till the beginning of this line.
+ */
+ if (el->el_line.cursor == el->el_line.buffer)
+ return 0;
+ else {
+ for (ptr = el->el_line.cursor - 1;
+ ptr >= el->el_line.buffer && *ptr != '\n';
+ ptr--)
+ continue;
+ return (int)(el->el_line.cursor - ptr - 1);
+ }
+}
+
+libedit_private int
+ch_resizefun(EditLine *el, el_zfunc_t f, void *a)
+{
+ el->el_chared.c_resizefun = f;
+ el->el_chared.c_resizearg = a;
+ return 0;
+}
+
+libedit_private int
+ch_aliasfun(EditLine *el, el_afunc_t f, void *a)
+{
+ el->el_chared.c_aliasfun = f;
+ el->el_chared.c_aliasarg = a;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/libedit/src/chared.h b/third_party/heimdal/lib/libedit/src/chared.h
new file mode 100644
index 0000000..39f7d51
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/chared.h
@@ -0,0 +1,155 @@
+/* $NetBSD: chared.h,v 1.30 2016/05/22 19:44:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)chared.h 8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * el.chared.h: Character editor interface
+ */
+#ifndef _h_el_chared
+#define _h_el_chared
+
+/*
+ * This is an issue of basic "vi" look-and-feel. Defining VI_MOVE works
+ * like real vi: i.e. the transition from command<->insert modes moves
+ * the cursor.
+ *
+ * On the other hand we really don't want to move the cursor, because
+ * all the editing commands don't include the character under the cursor.
+ * Probably the best fix is to make all the editing commands aware of
+ * this fact.
+ */
+#define VI_MOVE
+
+/*
+ * Undo information for vi - no undo in emacs (yet)
+ */
+typedef struct c_undo_t {
+ ssize_t len; /* length of saved line */
+ int cursor; /* position of saved cursor */
+ wchar_t *buf; /* full saved text */
+} c_undo_t;
+
+/* redo for vi */
+typedef struct c_redo_t {
+ wchar_t *buf; /* redo insert key sequence */
+ wchar_t *pos;
+ wchar_t *lim;
+ el_action_t cmd; /* command to redo */
+ wchar_t ch; /* char that invoked it */
+ int count;
+ int action; /* from cv_action() */
+} c_redo_t;
+
+/*
+ * Current action information for vi
+ */
+typedef struct c_vcmd_t {
+ int action;
+ wchar_t *pos;
+} c_vcmd_t;
+
+/*
+ * Kill buffer for emacs
+ */
+typedef struct c_kill_t {
+ wchar_t *buf;
+ wchar_t *last;
+ wchar_t *mark;
+} c_kill_t;
+
+typedef void (*el_zfunc_t)(EditLine *, void *);
+typedef const char *(*el_afunc_t)(void *, const char *);
+
+/*
+ * Note that we use both data structures because the user can bind
+ * commands from both editors!
+ */
+typedef struct el_chared_t {
+ c_undo_t c_undo;
+ c_kill_t c_kill;
+ c_redo_t c_redo;
+ c_vcmd_t c_vcmd;
+ el_zfunc_t c_resizefun;
+ el_afunc_t c_aliasfun;
+ void * c_resizearg;
+ void * c_aliasarg;
+} el_chared_t;
+
+
+#define STRQQ "\"\""
+
+#define isglob(a) (strchr("*[]?", (a)) != NULL)
+
+#define NOP 0x00
+#define DELETE 0x01
+#define INSERT 0x02
+#define YANK 0x04
+
+#define CHAR_FWD (+1)
+#define CHAR_BACK (-1)
+
+#define MODE_INSERT 0
+#define MODE_REPLACE 1
+#define MODE_REPLACE_1 2
+
+
+libedit_private int cv__isword(wint_t);
+libedit_private int cv__isWord(wint_t);
+libedit_private void cv_delfini(EditLine *);
+libedit_private wchar_t *cv__endword(wchar_t *, wchar_t *, int, int (*)(wint_t));
+libedit_private int ce__isword(wint_t);
+libedit_private void cv_undo(EditLine *);
+libedit_private void cv_yank(EditLine *, const wchar_t *, int);
+libedit_private wchar_t *cv_next_word(EditLine*, wchar_t *, wchar_t *, int,
+ int (*)(wint_t));
+libedit_private wchar_t *cv_prev_word(wchar_t *, wchar_t *, int, int (*)(wint_t));
+libedit_private wchar_t *c__next_word(wchar_t *, wchar_t *, int, int (*)(wint_t));
+libedit_private wchar_t *c__prev_word(wchar_t *, wchar_t *, int, int (*)(wint_t));
+libedit_private void c_insert(EditLine *, int);
+libedit_private void c_delbefore(EditLine *, int);
+libedit_private void c_delbefore1(EditLine *);
+libedit_private void c_delafter(EditLine *, int);
+libedit_private void c_delafter1(EditLine *);
+libedit_private int c_gets(EditLine *, wchar_t *, const wchar_t *);
+libedit_private int c_hpos(EditLine *);
+
+libedit_private int ch_init(EditLine *);
+libedit_private void ch_reset(EditLine *);
+libedit_private int ch_resizefun(EditLine *, el_zfunc_t, void *);
+libedit_private int ch_aliasfun(EditLine *, el_afunc_t, void *);
+libedit_private int ch_enlargebufs(EditLine *, size_t);
+libedit_private void ch_end(EditLine *);
+
+#endif /* _h_el_chared */
diff --git a/third_party/heimdal/lib/libedit/src/chartype.c b/third_party/heimdal/lib/libedit/src/chartype.c
new file mode 100644
index 0000000..f350dfd
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/chartype.c
@@ -0,0 +1,340 @@
+/* $NetBSD: chartype.c,v 1.30 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * chartype.c: character classification and meta information
+ */
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+__RCSID("$NetBSD: chartype.c,v 1.30 2016/05/09 21:46:56 christos Exp $");
+#endif /* not lint && not SCCSID */
+
+#include <ctype.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "el.h"
+
+#define CT_BUFSIZ ((size_t)1024)
+
+static int ct_conv_cbuff_resize(ct_buffer_t *, size_t);
+static int ct_conv_wbuff_resize(ct_buffer_t *, size_t);
+
+static int
+ct_conv_cbuff_resize(ct_buffer_t *conv, size_t csize)
+{
+ void *p;
+
+ if (csize <= conv->csize)
+ return 0;
+
+ conv->csize = csize;
+
+ p = el_realloc(conv->cbuff, conv->csize * sizeof(*conv->cbuff));
+ if (p == NULL) {
+ conv->csize = 0;
+ el_free(conv->cbuff);
+ conv->cbuff = NULL;
+ return -1;
+ }
+ conv->cbuff = p;
+ return 0;
+}
+
+static int
+ct_conv_wbuff_resize(ct_buffer_t *conv, size_t wsize)
+{
+ void *p;
+
+ if (wsize <= conv->wsize)
+ return 0;
+
+ conv->wsize = wsize;
+
+ p = el_realloc(conv->wbuff, conv->wsize * sizeof(*conv->wbuff));
+ if (p == NULL) {
+ conv->wsize = 0;
+ el_free(conv->wbuff);
+ conv->wbuff = NULL;
+ return -1;
+ }
+ conv->wbuff = p;
+ return 0;
+}
+
+
+char *
+ct_encode_string(const wchar_t *s, ct_buffer_t *conv)
+{
+ char *dst;
+ ssize_t used;
+
+ if (!s)
+ return NULL;
+
+ dst = conv->cbuff;
+ for (;;) {
+ used = (ssize_t)(dst - conv->cbuff);
+ if ((conv->csize - (size_t)used) < 5) {
+ if (ct_conv_cbuff_resize(conv,
+ conv->csize + CT_BUFSIZ) == -1)
+ return NULL;
+ dst = conv->cbuff + used;
+ }
+ if (!*s)
+ break;
+ used = ct_encode_char(dst, (size_t)5, *s);
+ if (used == -1) /* failed to encode, need more buffer space */
+ abort();
+ ++s;
+ dst += used;
+ }
+ *dst = '\0';
+ return conv->cbuff;
+}
+
+wchar_t *
+ct_decode_string(const char *s, ct_buffer_t *conv)
+{
+ size_t len;
+
+ if (!s)
+ return NULL;
+
+ len = mbstowcs(NULL, s, (size_t)0);
+ if (len == (size_t)-1)
+ return NULL;
+
+ if (conv->wsize < ++len)
+ if (ct_conv_wbuff_resize(conv, len + CT_BUFSIZ) == -1)
+ return NULL;
+
+ mbstowcs(conv->wbuff, s, conv->wsize);
+ return conv->wbuff;
+}
+
+
+libedit_private wchar_t **
+ct_decode_argv(int argc, const char *argv[], ct_buffer_t *conv)
+{
+ size_t bufspace;
+ int i;
+ wchar_t *p;
+ wchar_t **wargv;
+ ssize_t bytes;
+
+ /* Make sure we have enough space in the conversion buffer to store all
+ * the argv strings. */
+ for (i = 0, bufspace = 0; i < argc; ++i)
+ bufspace += argv[i] ? strlen(argv[i]) + 1 : 0;
+ if (conv->wsize < ++bufspace)
+ if (ct_conv_wbuff_resize(conv, bufspace + CT_BUFSIZ) == -1)
+ return NULL;
+
+ wargv = el_malloc((size_t)argc * sizeof(*wargv));
+
+ for (i = 0, p = conv->wbuff; i < argc; ++i) {
+ if (!argv[i]) { /* don't pass null pointers to mbstowcs */
+ wargv[i] = NULL;
+ continue;
+ } else {
+ wargv[i] = p;
+ bytes = (ssize_t)mbstowcs(p, argv[i], bufspace);
+ }
+ if (bytes == -1) {
+ el_free(wargv);
+ return NULL;
+ } else
+ bytes++; /* include '\0' in the count */
+ bufspace -= (size_t)bytes;
+ p += bytes;
+ }
+
+ return wargv;
+}
+
+
+libedit_private size_t
+ct_enc_width(wchar_t c)
+{
+ /* UTF-8 encoding specific values */
+ if (c < 0x80)
+ return 1;
+ else if (c < 0x0800)
+ return 2;
+ else if (c < 0x10000)
+ return 3;
+ else if (c < 0x110000)
+ return 4;
+ else
+ return 0; /* not a valid codepoint */
+}
+
+libedit_private ssize_t
+ct_encode_char(char *dst, size_t len, wchar_t c)
+{
+ ssize_t l = 0;
+ if (len < ct_enc_width(c))
+ return -1;
+ l = wctomb(dst, c);
+
+ if (l < 0) {
+ wctomb(NULL, L'\0');
+ l = 0;
+ }
+ return l;
+}
+
+libedit_private const wchar_t *
+ct_visual_string(const wchar_t *s, ct_buffer_t *conv)
+{
+ wchar_t *dst;
+ ssize_t used;
+
+ if (!s)
+ return NULL;
+
+ if (ct_conv_wbuff_resize(conv, CT_BUFSIZ) == -1)
+ return NULL;
+
+ used = 0;
+ dst = conv->wbuff;
+ while (*s) {
+ used = ct_visual_char(dst,
+ conv->wsize - (size_t)(dst - conv->wbuff), *s);
+ if (used != -1) {
+ ++s;
+ dst += used;
+ continue;
+ }
+
+ /* failed to encode, need more buffer space */
+ used = dst - conv->wbuff;
+ if (ct_conv_wbuff_resize(conv, conv->wsize + CT_BUFSIZ) == -1)
+ return NULL;
+ dst = conv->wbuff + used;
+ }
+
+ if (dst >= (conv->wbuff + conv->wsize)) { /* sigh */
+ used = dst - conv->wbuff;
+ if (ct_conv_wbuff_resize(conv, conv->wsize + CT_BUFSIZ) == -1)
+ return NULL;
+ dst = conv->wbuff + used;
+ }
+
+ *dst = L'\0';
+ return conv->wbuff;
+}
+
+
+
+libedit_private int
+ct_visual_width(wchar_t c)
+{
+ int t = ct_chr_class(c);
+ switch (t) {
+ case CHTYPE_ASCIICTL:
+ return 2; /* ^@ ^? etc. */
+ case CHTYPE_TAB:
+ return 1; /* Hmm, this really need to be handled outside! */
+ case CHTYPE_NL:
+ return 0; /* Should this be 1 instead? */
+ case CHTYPE_PRINT:
+ return wcwidth(c);
+ case CHTYPE_NONPRINT:
+ if (c > 0xffff) /* prefer standard 4-byte display over 5-byte */
+ return 8; /* \U+12345 */
+ else
+ return 7; /* \U+1234 */
+ default:
+ return 0; /* should not happen */
+ }
+}
+
+
+libedit_private ssize_t
+ct_visual_char(wchar_t *dst, size_t len, wchar_t c)
+{
+ int t = ct_chr_class(c);
+ switch (t) {
+ case CHTYPE_TAB:
+ case CHTYPE_NL:
+ case CHTYPE_ASCIICTL:
+ if (len < 2)
+ return -1; /* insufficient space */
+ *dst++ = '^';
+ if (c == '\177')
+ *dst = '?'; /* DEL -> ^? */
+ else
+ *dst = c | 0100; /* uncontrolify it */
+ return 2;
+ case CHTYPE_PRINT:
+ if (len < 1)
+ return -1; /* insufficient space */
+ *dst = c;
+ return 1;
+ case CHTYPE_NONPRINT:
+ /* we only use single-width glyphs for display,
+ * so this is right */
+ if ((ssize_t)len < ct_visual_width(c))
+ return -1; /* insufficient space */
+ *dst++ = '\\';
+ *dst++ = 'U';
+ *dst++ = '+';
+#define tohexdigit(v) "0123456789ABCDEF"[v]
+ if (c > 0xffff) /* prefer standard 4-byte display over 5-byte */
+ *dst++ = tohexdigit(((unsigned int) c >> 16) & 0xf);
+ *dst++ = tohexdigit(((unsigned int) c >> 12) & 0xf);
+ *dst++ = tohexdigit(((unsigned int) c >> 8) & 0xf);
+ *dst++ = tohexdigit(((unsigned int) c >> 4) & 0xf);
+ *dst = tohexdigit(((unsigned int) c ) & 0xf);
+ return c > 0xffff ? 8 : 7;
+ /*FALLTHROUGH*/
+ /* these two should be handled outside this function */
+ default: /* we should never hit the default */
+ return 0;
+ }
+}
+
+
+
+
+libedit_private int
+ct_chr_class(wchar_t c)
+{
+ if (c == '\t')
+ return CHTYPE_TAB;
+ else if (c == '\n')
+ return CHTYPE_NL;
+ else if (c < 0x100 && iswcntrl(c))
+ return CHTYPE_ASCIICTL;
+ else if (iswprint(c))
+ return CHTYPE_PRINT;
+ else
+ return CHTYPE_NONPRINT;
+}
diff --git a/third_party/heimdal/lib/libedit/src/chartype.h b/third_party/heimdal/lib/libedit/src/chartype.h
new file mode 100644
index 0000000..7f4b8d9
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/chartype.h
@@ -0,0 +1,114 @@
+/* $NetBSD: chartype.h,v 1.34 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _h_chartype_f
+#define _h_chartype_f
+
+/* Ideally we should also test the value of the define to see if it
+ * supports non-BMP code points without requiring UTF-16, but nothing
+ * seems to actually advertise this properly, despite Unicode 3.1 having
+ * been around since 2001... */
+#if !defined(__NetBSD__) && !defined(__sun) && !(defined(__APPLE__) && defined(__MACH__)) && !defined(__OpenBSD__) && !defined(__FreeBSD__)
+#ifndef __STDC_ISO_10646__
+/* In many places it is assumed that the first 127 code points are ASCII
+ * compatible, so ensure wchar_t indeed does ISO 10646 and not some other
+ * funky encoding that could break us in weird and wonderful ways. */
+ #error wchar_t must store ISO 10646 characters
+#endif
+#endif
+
+/* Oh for a <uchar.h> with char32_t and __STDC_UTF_32__ in it...
+ * ref: ISO/IEC DTR 19769
+ */
+#if WCHAR_MAX < INT32_MAX
+#warning Build environment does not support non-BMP characters
+#endif
+
+/*
+ * Conversion buffer
+ */
+typedef struct ct_buffer_t {
+ char *cbuff;
+ size_t csize;
+ wchar_t *wbuff;
+ size_t wsize;
+} ct_buffer_t;
+
+/* Encode a wide-character string and return the UTF-8 encoded result. */
+char *ct_encode_string(const wchar_t *, ct_buffer_t *);
+
+/* Decode a (multi)?byte string and return the wide-character string result. */
+wchar_t *ct_decode_string(const char *, ct_buffer_t *);
+
+/* Decode a (multi)?byte argv string array.
+ * The pointer returned must be free()d when done. */
+libedit_private wchar_t **ct_decode_argv(int, const char *[], ct_buffer_t *);
+
+/* Encode a character into the destination buffer, provided there is sufficient
+ * buffer space available. Returns the number of bytes used up (zero if the
+ * character cannot be encoded, -1 if there was not enough space available). */
+libedit_private ssize_t ct_encode_char(char *, size_t, wchar_t);
+libedit_private size_t ct_enc_width(wchar_t);
+
+/* The maximum buffer size to hold the most unwieldy visual representation,
+ * in this case \U+nnnnn. */
+#define VISUAL_WIDTH_MAX ((size_t)8)
+
+/* The terminal is thought of in terms of X columns by Y lines. In the cases
+ * where a wide character takes up more than one column, the adjacent
+ * occupied column entries will contain this faux character. */
+#define MB_FILL_CHAR ((wchar_t)-1)
+
+/* Visual width of character c, taking into account ^? , \0177 and \U+nnnnn
+ * style visual expansions. */
+libedit_private int ct_visual_width(wchar_t);
+
+/* Turn the given character into the appropriate visual format, matching
+ * the width given by ct_visual_width(). Returns the number of characters used
+ * up, or -1 if insufficient space. Buffer length is in count of wchar_t's. */
+libedit_private ssize_t ct_visual_char(wchar_t *, size_t, wchar_t);
+
+/* Convert the given string into visual format, using the ct_visual_char()
+ * function. Uses a static buffer, so not threadsafe. */
+libedit_private const wchar_t *ct_visual_string(const wchar_t *, ct_buffer_t *);
+
+
+/* printable character, use ct_visual_width() to find out display width */
+#define CHTYPE_PRINT ( 0)
+/* control character found inside the ASCII portion of the charset */
+#define CHTYPE_ASCIICTL (-1)
+/* a \t */
+#define CHTYPE_TAB (-2)
+/* a \n */
+#define CHTYPE_NL (-3)
+/* non-printable character */
+#define CHTYPE_NONPRINT (-4)
+/* classification of character c, as one of the above defines */
+libedit_private int ct_chr_class(wchar_t c);
+
+#endif /* _chartype_f */
diff --git a/third_party/heimdal/lib/libedit/src/common.c b/third_party/heimdal/lib/libedit/src/common.c
new file mode 100644
index 0000000..2708605
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/common.c
@@ -0,0 +1,835 @@
+/* $NetBSD: common.c,v 1.47 2016/05/22 19:44:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)common.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: common.c,v 1.47 2016/05/22 19:44:26 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * common.c: Common Editor functions
+ */
+#include <ctype.h>
+#include <string.h>
+
+#include "el.h"
+#include "common.h"
+#include "fcns.h"
+#include "parse.h"
+#include "vi.h"
+
+/* ed_end_of_file():
+ * Indicate end of file
+ * [^D]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_end_of_file(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ re_goto_bottom(el);
+ *el->el_line.lastchar = '\0';
+ return CC_EOF;
+}
+
+
+/* ed_insert():
+ * Add character to the line
+ * Insert a character [bound to all insert keys]
+ */
+libedit_private el_action_t
+ed_insert(EditLine *el, wint_t c)
+{
+ int count = el->el_state.argument;
+
+ if (c == '\0')
+ return CC_ERROR;
+
+ if (el->el_line.lastchar + el->el_state.argument >=
+ el->el_line.limit) {
+ /* end of buffer space, try to allocate more */
+ if (!ch_enlargebufs(el, (size_t) count))
+ return CC_ERROR; /* error allocating more */
+ }
+
+ if (count == 1) {
+ if (el->el_state.inputmode == MODE_INSERT
+ || el->el_line.cursor >= el->el_line.lastchar)
+ c_insert(el, 1);
+
+ *el->el_line.cursor++ = c;
+ re_fastaddc(el); /* fast refresh for one char. */
+ } else {
+ if (el->el_state.inputmode != MODE_REPLACE_1)
+ c_insert(el, el->el_state.argument);
+
+ while (count-- && el->el_line.cursor < el->el_line.lastchar)
+ *el->el_line.cursor++ = c;
+ re_refresh(el);
+ }
+
+ if (el->el_state.inputmode == MODE_REPLACE_1)
+ return vi_command_mode(el, 0);
+
+ return CC_NORM;
+}
+
+
+/* ed_delete_prev_word():
+ * Delete from beginning of current word to cursor
+ * [M-^?] [^W]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_delete_prev_word(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *cp, *p, *kp;
+
+ if (el->el_line.cursor == el->el_line.buffer)
+ return CC_ERROR;
+
+ cp = c__prev_word(el->el_line.cursor, el->el_line.buffer,
+ el->el_state.argument, ce__isword);
+
+ for (p = cp, kp = el->el_chared.c_kill.buf; p < el->el_line.cursor; p++)
+ *kp++ = *p;
+ el->el_chared.c_kill.last = kp;
+
+ c_delbefore(el, (int)(el->el_line.cursor - cp));/* delete before dot */
+ el->el_line.cursor = cp;
+ if (el->el_line.cursor < el->el_line.buffer)
+ el->el_line.cursor = el->el_line.buffer; /* bounds check */
+ return CC_REFRESH;
+}
+
+
+/* ed_delete_next_char():
+ * Delete character under cursor
+ * [^D] [x]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_delete_next_char(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+#ifdef DEBUG_EDIT
+#define EL el->el_line
+ (void) fprintf(el->el_errfile,
+ "\nD(b: %p(%ls) c: %p(%ls) last: %p(%ls) limit: %p(%ls)\n",
+ EL.buffer, EL.buffer, EL.cursor, EL.cursor, EL.lastchar,
+ EL.lastchar, EL.limit, EL.limit);
+#endif
+ if (el->el_line.cursor == el->el_line.lastchar) {
+ /* if I'm at the end */
+ if (el->el_map.type == MAP_VI) {
+ if (el->el_line.cursor == el->el_line.buffer) {
+ /* if I'm also at the beginning */
+#ifdef KSHVI
+ return CC_ERROR;
+#else
+ /* then do an EOF */
+ terminal_writec(el, c);
+ return CC_EOF;
+#endif
+ } else {
+#ifdef KSHVI
+ el->el_line.cursor--;
+#else
+ return CC_ERROR;
+#endif
+ }
+ } else
+ return CC_ERROR;
+ }
+ c_delafter(el, el->el_state.argument); /* delete after dot */
+ if (el->el_map.type == MAP_VI &&
+ el->el_line.cursor >= el->el_line.lastchar &&
+ el->el_line.cursor > el->el_line.buffer)
+ /* bounds check */
+ el->el_line.cursor = el->el_line.lastchar - 1;
+ return CC_REFRESH;
+}
+
+
+/* ed_kill_line():
+ * Cut to the end of line
+ * [^K] [^K]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_kill_line(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *kp, *cp;
+
+ cp = el->el_line.cursor;
+ kp = el->el_chared.c_kill.buf;
+ while (cp < el->el_line.lastchar)
+ *kp++ = *cp++; /* copy it */
+ el->el_chared.c_kill.last = kp;
+ /* zap! -- delete to end */
+ el->el_line.lastchar = el->el_line.cursor;
+ return CC_REFRESH;
+}
+
+
+/* ed_move_to_end():
+ * Move cursor to the end of line
+ * [^E] [^E]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_move_to_end(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ el->el_line.cursor = el->el_line.lastchar;
+ if (el->el_map.type == MAP_VI) {
+ if (el->el_chared.c_vcmd.action != NOP) {
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+#ifdef VI_MOVE
+ el->el_line.cursor--;
+#endif
+ }
+ return CC_CURSOR;
+}
+
+
+/* ed_move_to_beg():
+ * Move cursor to the beginning of line
+ * [^A] [^A]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_move_to_beg(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ el->el_line.cursor = el->el_line.buffer;
+
+ if (el->el_map.type == MAP_VI) {
+ /* We want FIRST non space character */
+ while (iswspace(*el->el_line.cursor))
+ el->el_line.cursor++;
+ if (el->el_chared.c_vcmd.action != NOP) {
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+ }
+ return CC_CURSOR;
+}
+
+
+/* ed_transpose_chars():
+ * Exchange the character to the left of the cursor with the one under it
+ * [^T] [^T]
+ */
+libedit_private el_action_t
+ed_transpose_chars(EditLine *el, wint_t c)
+{
+
+ if (el->el_line.cursor < el->el_line.lastchar) {
+ if (el->el_line.lastchar <= &el->el_line.buffer[1])
+ return CC_ERROR;
+ else
+ el->el_line.cursor++;
+ }
+ if (el->el_line.cursor > &el->el_line.buffer[1]) {
+ /* must have at least two chars entered */
+ c = el->el_line.cursor[-2];
+ el->el_line.cursor[-2] = el->el_line.cursor[-1];
+ el->el_line.cursor[-1] = c;
+ return CC_REFRESH;
+ } else
+ return CC_ERROR;
+}
+
+
+/* ed_next_char():
+ * Move to the right one character
+ * [^F] [^F]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_next_char(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *lim = el->el_line.lastchar;
+
+ if (el->el_line.cursor >= lim ||
+ (el->el_line.cursor == lim - 1 &&
+ el->el_map.type == MAP_VI &&
+ el->el_chared.c_vcmd.action == NOP))
+ return CC_ERROR;
+
+ el->el_line.cursor += el->el_state.argument;
+ if (el->el_line.cursor > lim)
+ el->el_line.cursor = lim;
+
+ if (el->el_map.type == MAP_VI)
+ if (el->el_chared.c_vcmd.action != NOP) {
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+ return CC_CURSOR;
+}
+
+
+/* ed_prev_word():
+ * Move to the beginning of the current word
+ * [M-b] [b]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_prev_word(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ if (el->el_line.cursor == el->el_line.buffer)
+ return CC_ERROR;
+
+ el->el_line.cursor = c__prev_word(el->el_line.cursor,
+ el->el_line.buffer,
+ el->el_state.argument,
+ ce__isword);
+
+ if (el->el_map.type == MAP_VI)
+ if (el->el_chared.c_vcmd.action != NOP) {
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+ return CC_CURSOR;
+}
+
+
+/* ed_prev_char():
+ * Move to the left one character
+ * [^B] [^B]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_prev_char(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ if (el->el_line.cursor > el->el_line.buffer) {
+ el->el_line.cursor -= el->el_state.argument;
+ if (el->el_line.cursor < el->el_line.buffer)
+ el->el_line.cursor = el->el_line.buffer;
+
+ if (el->el_map.type == MAP_VI)
+ if (el->el_chared.c_vcmd.action != NOP) {
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+ return CC_CURSOR;
+ } else
+ return CC_ERROR;
+}
+
+
+/* ed_quoted_insert():
+ * Add the next character typed verbatim
+ * [^V] [^V]
+ */
+libedit_private el_action_t
+ed_quoted_insert(EditLine *el, wint_t c)
+{
+ int num;
+
+ tty_quotemode(el);
+ num = el_wgetc(el, &c);
+ tty_noquotemode(el);
+ if (num == 1)
+ return ed_insert(el, c);
+ else
+ return ed_end_of_file(el, 0);
+}
+
+
+/* ed_digit():
+ * Adds to argument or enters a digit
+ */
+libedit_private el_action_t
+ed_digit(EditLine *el, wint_t c)
+{
+
+ if (!iswdigit(c))
+ return CC_ERROR;
+
+ if (el->el_state.doingarg) {
+ /* if doing an arg, add this in... */
+ if (el->el_state.lastcmd == EM_UNIVERSAL_ARGUMENT)
+ el->el_state.argument = c - '0';
+ else {
+ if (el->el_state.argument > 1000000)
+ return CC_ERROR;
+ el->el_state.argument =
+ (el->el_state.argument * 10) + (c - '0');
+ }
+ return CC_ARGHACK;
+ }
+
+ return ed_insert(el, c);
+}
+
+
+/* ed_argument_digit():
+ * Digit that starts argument
+ * For ESC-n
+ */
+libedit_private el_action_t
+ed_argument_digit(EditLine *el, wint_t c)
+{
+
+ if (!iswdigit(c))
+ return CC_ERROR;
+
+ if (el->el_state.doingarg) {
+ if (el->el_state.argument > 1000000)
+ return CC_ERROR;
+ el->el_state.argument = (el->el_state.argument * 10) +
+ (c - '0');
+ } else { /* else starting an argument */
+ el->el_state.argument = c - '0';
+ el->el_state.doingarg = 1;
+ }
+ return CC_ARGHACK;
+}
+
+
+/* ed_unassigned():
+ * Indicates unbound character
+ * Bound to keys that are not assigned
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_unassigned(EditLine *el __attribute__((__unused__)),
+ wint_t c __attribute__((__unused__)))
+{
+
+ return CC_ERROR;
+}
+
+
+/* ed_ignore():
+ * Input characters that have no effect
+ * [^C ^O ^Q ^S ^Z ^\ ^]] [^C ^O ^Q ^S ^\]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_ignore(EditLine *el __attribute__((__unused__)),
+ wint_t c __attribute__((__unused__)))
+{
+
+ return CC_NORM;
+}
+
+
+/* ed_newline():
+ * Execute command
+ * [^J]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_newline(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ re_goto_bottom(el);
+ *el->el_line.lastchar++ = '\n';
+ *el->el_line.lastchar = '\0';
+ return CC_NEWLINE;
+}
+
+
+/* ed_delete_prev_char():
+ * Delete the character to the left of the cursor
+ * [^?]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_delete_prev_char(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ if (el->el_line.cursor <= el->el_line.buffer)
+ return CC_ERROR;
+
+ c_delbefore(el, el->el_state.argument);
+ el->el_line.cursor -= el->el_state.argument;
+ if (el->el_line.cursor < el->el_line.buffer)
+ el->el_line.cursor = el->el_line.buffer;
+ return CC_REFRESH;
+}
+
+
+/* ed_clear_screen():
+ * Clear screen leaving current line at the top
+ * [^L]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_clear_screen(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ terminal_clear_screen(el); /* clear the whole real screen */
+ re_clear_display(el); /* reset everything */
+ return CC_REFRESH;
+}
+
+
+/* ed_redisplay():
+ * Redisplay everything
+ * ^R
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_redisplay(EditLine *el __attribute__((__unused__)),
+ wint_t c __attribute__((__unused__)))
+{
+
+ return CC_REDISPLAY;
+}
+
+
+/* ed_start_over():
+ * Erase current line and start from scratch
+ * [^G]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_start_over(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ ch_reset(el);
+ return CC_REFRESH;
+}
+
+
+/* ed_sequence_lead_in():
+ * First character in a bound sequence
+ * Placeholder for external keys
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_sequence_lead_in(EditLine *el __attribute__((__unused__)),
+ wint_t c __attribute__((__unused__)))
+{
+
+ return CC_NORM;
+}
+
+
+/* ed_prev_history():
+ * Move to the previous history line
+ * [^P] [k]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_prev_history(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ char beep = 0;
+ int sv_event = el->el_history.eventno;
+
+ el->el_chared.c_undo.len = -1;
+ *el->el_line.lastchar = '\0'; /* just in case */
+
+ if (el->el_history.eventno == 0) { /* save the current buffer
+ * away */
+ (void) wcsncpy(el->el_history.buf, el->el_line.buffer,
+ EL_BUFSIZ);
+ el->el_history.last = el->el_history.buf +
+ (el->el_line.lastchar - el->el_line.buffer);
+ }
+ el->el_history.eventno += el->el_state.argument;
+
+ if (hist_get(el) == CC_ERROR) {
+ if (el->el_map.type == MAP_VI) {
+ el->el_history.eventno = sv_event;
+ }
+ beep = 1;
+ /* el->el_history.eventno was fixed by first call */
+ (void) hist_get(el);
+ }
+ if (beep)
+ return CC_REFRESH_BEEP;
+ return CC_REFRESH;
+}
+
+
+/* ed_next_history():
+ * Move to the next history line
+ * [^N] [j]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_next_history(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ el_action_t beep = CC_REFRESH, rval;
+
+ el->el_chared.c_undo.len = -1;
+ *el->el_line.lastchar = '\0'; /* just in case */
+
+ el->el_history.eventno -= el->el_state.argument;
+
+ if (el->el_history.eventno < 0) {
+ el->el_history.eventno = 0;
+ beep = CC_REFRESH_BEEP;
+ }
+ rval = hist_get(el);
+ if (rval == CC_REFRESH)
+ return beep;
+ return rval;
+
+}
+
+
+/* ed_search_prev_history():
+ * Search previous in history for a line matching the current
+ * next search history [M-P] [K]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_search_prev_history(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ const wchar_t *hp;
+ int h;
+ int found = 0;
+
+ el->el_chared.c_vcmd.action = NOP;
+ el->el_chared.c_undo.len = -1;
+ *el->el_line.lastchar = '\0'; /* just in case */
+ if (el->el_history.eventno < 0) {
+#ifdef DEBUG_EDIT
+ (void) fprintf(el->el_errfile,
+ "e_prev_search_hist(): eventno < 0;\n");
+#endif
+ el->el_history.eventno = 0;
+ return CC_ERROR;
+ }
+ if (el->el_history.eventno == 0) {
+ (void) wcsncpy(el->el_history.buf, el->el_line.buffer,
+ EL_BUFSIZ);
+ el->el_history.last = el->el_history.buf +
+ (el->el_line.lastchar - el->el_line.buffer);
+ }
+ if (el->el_history.ref == NULL)
+ return CC_ERROR;
+
+ hp = HIST_FIRST(el);
+ if (hp == NULL)
+ return CC_ERROR;
+
+ c_setpat(el); /* Set search pattern !! */
+
+ for (h = 1; h <= el->el_history.eventno; h++)
+ hp = HIST_NEXT(el);
+
+ while (hp != NULL) {
+#ifdef SDEBUG
+ (void) fprintf(el->el_errfile, "Comparing with \"%s\"\n", hp);
+#endif
+ if ((wcsncmp(hp, el->el_line.buffer, (size_t)
+ (el->el_line.lastchar - el->el_line.buffer)) ||
+ hp[el->el_line.lastchar - el->el_line.buffer]) &&
+ c_hmatch(el, hp)) {
+ found = 1;
+ break;
+ }
+ h++;
+ hp = HIST_NEXT(el);
+ }
+
+ if (!found) {
+#ifdef SDEBUG
+ (void) fprintf(el->el_errfile, "not found\n");
+#endif
+ return CC_ERROR;
+ }
+ el->el_history.eventno = h;
+
+ return hist_get(el);
+}
+
+
+/* ed_search_next_history():
+ * Search next in history for a line matching the current
+ * [M-N] [J]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_search_next_history(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ const wchar_t *hp;
+ int h;
+ int found = 0;
+
+ el->el_chared.c_vcmd.action = NOP;
+ el->el_chared.c_undo.len = -1;
+ *el->el_line.lastchar = '\0'; /* just in case */
+
+ if (el->el_history.eventno == 0)
+ return CC_ERROR;
+
+ if (el->el_history.ref == NULL)
+ return CC_ERROR;
+
+ hp = HIST_FIRST(el);
+ if (hp == NULL)
+ return CC_ERROR;
+
+ c_setpat(el); /* Set search pattern !! */
+
+ for (h = 1; h < el->el_history.eventno && hp; h++) {
+#ifdef SDEBUG
+ (void) fprintf(el->el_errfile, "Comparing with \"%s\"\n", hp);
+#endif
+ if ((wcsncmp(hp, el->el_line.buffer, (size_t)
+ (el->el_line.lastchar - el->el_line.buffer)) ||
+ hp[el->el_line.lastchar - el->el_line.buffer]) &&
+ c_hmatch(el, hp))
+ found = h;
+ hp = HIST_NEXT(el);
+ }
+
+ if (!found) { /* is it the current history number? */
+ if (!c_hmatch(el, el->el_history.buf)) {
+#ifdef SDEBUG
+ (void) fprintf(el->el_errfile, "not found\n");
+#endif
+ return CC_ERROR;
+ }
+ }
+ el->el_history.eventno = found;
+
+ return hist_get(el);
+}
+
+
+/* ed_prev_line():
+ * Move up one line
+ * Could be [k] [^p]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_prev_line(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *ptr;
+ int nchars = c_hpos(el);
+
+ /*
+ * Move to the line requested
+ */
+ if (*(ptr = el->el_line.cursor) == '\n')
+ ptr--;
+
+ for (; ptr >= el->el_line.buffer; ptr--)
+ if (*ptr == '\n' && --el->el_state.argument <= 0)
+ break;
+
+ if (el->el_state.argument > 0)
+ return CC_ERROR;
+
+ /*
+ * Move to the beginning of the line
+ */
+ for (ptr--; ptr >= el->el_line.buffer && *ptr != '\n'; ptr--)
+ continue;
+
+ /*
+ * Move to the character requested
+ */
+ for (ptr++;
+ nchars-- > 0 && ptr < el->el_line.lastchar && *ptr != '\n';
+ ptr++)
+ continue;
+
+ el->el_line.cursor = ptr;
+ return CC_CURSOR;
+}
+
+
+/* ed_next_line():
+ * Move down one line
+ * Could be [j] [^n]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_next_line(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *ptr;
+ int nchars = c_hpos(el);
+
+ /*
+ * Move to the line requested
+ */
+ for (ptr = el->el_line.cursor; ptr < el->el_line.lastchar; ptr++)
+ if (*ptr == '\n' && --el->el_state.argument <= 0)
+ break;
+
+ if (el->el_state.argument > 0)
+ return CC_ERROR;
+
+ /*
+ * Move to the character requested
+ */
+ for (ptr++;
+ nchars-- > 0 && ptr < el->el_line.lastchar && *ptr != '\n';
+ ptr++)
+ continue;
+
+ el->el_line.cursor = ptr;
+ return CC_CURSOR;
+}
+
+
+/* ed_command():
+ * Editline extended command
+ * [M-X] [:]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+ed_command(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t tmpbuf[EL_BUFSIZ];
+ int tmplen;
+
+ tmplen = c_gets(el, tmpbuf, L"\n: ");
+ terminal__putc(el, '\n');
+
+ if (tmplen < 0 || (tmpbuf[tmplen] = 0, parse_line(el, tmpbuf)) == -1)
+ terminal_beep(el);
+
+ el->el_map.current = el->el_map.key;
+ re_clear_display(el);
+ return CC_REFRESH;
+}
diff --git a/third_party/heimdal/lib/libedit/src/editline.3 b/third_party/heimdal/lib/libedit/src/editline.3
new file mode 100644
index 0000000..bb57972
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/editline.3
@@ -0,0 +1,997 @@
+.\" $NetBSD: editline.3,v 1.92 2016/05/22 23:54:20 christos Exp $
+.\"
+.\" Copyright (c) 1997-2014 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This file was contributed to The NetBSD Foundation by Luke Mewburn.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+.\" ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+.\" TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+.\" BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+.\" POSSIBILITY OF SUCH DAMAGE.
+.\"
+.Dd May 22, 2016
+.Dt EDITLINE 3
+.Os
+.Sh NAME
+.Nm editline ,
+.Nm el_init ,
+.Nm el_init_fd ,
+.Nm el_end ,
+.Nm el_reset ,
+.Nm el_gets ,
+.Nm el_wgets ,
+.Nm el_getc ,
+.Nm el_wgetc ,
+.Nm el_push ,
+.Nm el_wpush ,
+.Nm el_parse ,
+.Nm el_wparse ,
+.Nm el_set ,
+.Nm el_wset ,
+.Nm el_get ,
+.Nm el_wget ,
+.Nm el_source ,
+.Nm el_resize ,
+.Nm el_cursor ,
+.Nm el_line ,
+.Nm el_wline ,
+.Nm el_insertstr ,
+.Nm el_winsertstr ,
+.Nm el_deletestr ,
+.Nm el_wdeletestr ,
+.Nm history_init ,
+.Nm history_winit ,
+.Nm history_end ,
+.Nm history_wend ,
+.Nm history ,
+.Nm history_w ,
+.Nm tok_init ,
+.Nm tok_winit ,
+.Nm tok_end ,
+.Nm tok_wend ,
+.Nm tok_reset ,
+.Nm tok_wreset ,
+.Nm tok_line ,
+.Nm tok_wline ,
+.Nm tok_str ,
+.Nm tok_wstr
+.Nd line editor, history and tokenization functions
+.Sh LIBRARY
+.Lb libedit
+.Sh SYNOPSIS
+.In histedit.h
+.Ft EditLine *
+.Fn el_init "const char *prog" "FILE *fin" "FILE *fout" "FILE *ferr"
+.Ft EditLine *
+.Fn el_init_fd "const char *prog" "FILE *fin" "FILE *fout" "FILE *ferr" "int fdin" "int fdout" "int fderr"
+.Ft void
+.Fn el_end "EditLine *e"
+.Ft void
+.Fn el_reset "EditLine *e"
+.Ft const char *
+.Fn el_gets "EditLine *e" "int *count"
+.Ft const wchar_t *
+.Fn el_wgets "EditLine *e" "int *count"
+.Ft int
+.Fn el_getc "EditLine *e" "char *ch"
+.Ft int
+.Fn el_wgetc "EditLine *e" "wchar_t *wc"
+.Ft void
+.Fn el_push "EditLine *e" "const char *mbs"
+.Ft void
+.Fn el_wpush "EditLine *e" "const wchar_t *wcs"
+.Ft int
+.Fn el_parse "EditLine *e" "int argc" "const char *argv[]"
+.Ft int
+.Fn el_wparse "EditLine *e" "int argc" "const wchar_t *argv[]"
+.Ft int
+.Fn el_set "EditLine *e" "int op" "..."
+.Ft int
+.Fn el_wset "EditLine *e" "int op" "..."
+.Ft int
+.Fn el_get "EditLine *e" "int op" "..."
+.Ft int
+.Fn el_wget "EditLine *e" "int op" "..."
+.Ft int
+.Fn el_source "EditLine *e" "const char *file"
+.Ft void
+.Fn el_resize "EditLine *e"
+.Ft int
+.Fn el_cursor "EditLine *e" "int count"
+.Ft const LineInfo *
+.Fn el_line "EditLine *e"
+.Ft const LineInfoW *
+.Fn el_wline "EditLine *e"
+.Ft int
+.Fn el_insertstr "EditLine *e" "const char *str"
+.Ft int
+.Fn el_winsertstr "EditLine *e" "const wchar_t *str"
+.Ft void
+.Fn el_deletestr "EditLine *e" "int count"
+.Ft void
+.Fn el_wdeletestr "EditLine *e" "int count"
+.Ft History *
+.Fn history_init void
+.Ft HistoryW *
+.Fn history_winit void
+.Ft void
+.Fn history_end "History *h"
+.Ft void
+.Fn history_wend "HistoryW *h"
+.Ft int
+.Fn history "History *h" "HistEvent *ev" "int op" "..."
+.Ft int
+.Fn history_w "HistoryW *h" "HistEventW *ev" "int op" "..."
+.Ft Tokenizer *
+.Fn tok_init "const char *IFS"
+.Ft TokenizerW *
+.Fn tok_winit "const wchar_t *IFS"
+.Ft void
+.Fn tok_end "Tokenizer *t"
+.Ft void
+.Fn tok_wend "TokenizerW *t"
+.Ft void
+.Fn tok_reset "Tokenizer *t"
+.Ft void
+.Fn tok_wreset "TokenizerW *t"
+.Ft int
+.Fn tok_line "Tokenizer *t" "const LineInfo *li" "int *argc" "const char **argv[]" "int *cursorc" "int *cursoro"
+.Ft int
+.Fn tok_wline "TokenizerW *t" "const LineInfoW *li" "int *argc" "const wchar_t **argv[]" "int *cursorc" "int *cursoro"
+.Ft int
+.Fn tok_str "Tokenizer *t" "const char *str" "int *argc" "const char **argv[]"
+.Ft int
+.Fn tok_wstr "TokenizerW *t" "const wchar_t *str" "int *argc" "const wchar_t **argv[]"
+.Sh DESCRIPTION
+The
+.Nm
+library provides generic line editing, history and tokenization functions,
+similar to those found in
+.Xr sh 1 .
+.Pp
+These functions are available in the
+.Nm libedit
+library (which needs the
+.Nm libtermcap
+library).
+Programs should be linked with
+.Fl ledit ltermcap .
+.Pp
+The
+.Nm
+library respects the
+.Ev LC_CTYPE
+locale set by the application program and never uses
+.Xr setlocale 3
+to change the locale.
+The only locales supported are UTF-8 and the default C or POSIX locale.
+If any other locale is set, behaviour is undefined.
+.Sh LINE EDITING FUNCTIONS
+The line editing functions use a common data structure,
+.Fa EditLine ,
+which is created by
+.Fn el_init
+or
+.Fn el_init_fd
+and freed by
+.Fn el_end .
+.Pp
+The wide-character functions behave the same way as their narrow
+counterparts.
+.Pp
+The following functions are available:
+.Bl -tag -width 4n
+.It Fn el_init
+Initialize the line editor, and return a data structure
+to be used by all other line editing functions, or
+.Dv NULL
+on failure.
+.Fa prog
+is the name of the invoking program, used when reading the
+.Xr editrc 5
+file to determine which settings to use.
+.Fa fin ,
+.Fa fout
+and
+.Fa ferr
+are the input, output, and error streams (respectively) to use.
+In this documentation, references to
+.Dq the tty
+are actually to this input/output stream combination.
+.It Fn el_init_fd
+Like
+.Fn el_init
+but allows specifying file descriptors for the
+.Xr stdio 3
+corresponding streams, in case those were created with
+.Xr funopen 3 .
+.It Fn el_end
+Clean up and finish with
+.Fa e ,
+assumed to have been created with
+.Fn el_init
+or
+.Fn el_init_fd .
+.It Fn el_reset
+Reset the tty and the parser.
+This should be called after an error which may have upset the tty's
+state.
+.It Fn el_gets
+Read a line from the tty.
+.Fa count
+is modified to contain the number of characters read.
+Returns the line read if successful, or
+.Dv NULL
+if no characters were read or if an error occurred.
+If an error occurred,
+.Fa count
+is set to \-1 and
+.Dv errno
+contains the error code that caused it.
+The return value may not remain valid across calls to
+.Fn el_gets
+and must be copied if the data is to be retained.
+.It Fn el_wgetc
+Read a wide character from the tty, respecting the current locale,
+or from the input queue described in
+.Xr editline 7
+if that is not empty, and store it in
+.Fa wc .
+If an invalid or incomplete character is found, it is discarded,
+.Va errno
+is set to
+.Er EILSEQ ,
+and the next character is read and stored in
+.Fa wc .
+Returns 1 if a valid character was read, 0 on end of file, or \-1 on
+.Xr read 2
+failure.
+In the latter case,
+.Va errno
+is set to indicate the error.
+.It Fn el_getc
+Read a wide character as described for
+.Fn el_wgetc
+and return 0 on end of file or \-1 on failure.
+If the wide character can be represented as a single-byte character,
+convert it with
+.Xr wctob 3 ,
+store the result in
+.Fa ch ,
+and return 1; otherwise, set
+.Va errno
+to
+.Er ERANGE
+and return \-1.
+In the C or POSIX locale, this simply reads a byte, but for any other
+locale, including UTF-8, this is rarely useful.
+.It Fn el_wpush
+Push the wide character string
+.Fa wcs
+back onto the input queue described in
+.Xr editline 7 .
+If the queue overflows, for example due to a recursive macro,
+or if an error occurs, for example because
+.Fa wcs
+is
+.Dv NULL
+or memory allocation fails, the function beeps at the user,
+but does not report the problem to the caller.
+.It Fn el_push
+Use the current locale to convert the multibyte string
+.Fa mbs
+to a wide character string, and pass the result to
+.Fn el_wpush .
+.It Fn el_parse
+Parses the
+.Fa argv
+array (which is
+.Fa argc
+elements in size)
+to execute builtin
+.Nm
+commands.
+If the command is prefixed with
+.Dq prog :
+then
+.Fn el_parse
+will only execute the command if
+.Dq prog
+matches the
+.Fa prog
+argument supplied to
+.Fn el_init .
+The return value is
+\-1 if the command is unknown,
+0 if there was no error or
+.Dq prog
+didn't match, or
+1 if the command returned an error.
+Refer to
+.Xr editrc 5
+for more information.
+.It Fn el_set
+Set
+.Nm
+parameters.
+.Fa op
+determines which parameter to set, and each operation has its
+own parameter list.
+Returns 0 on success, \-1 on failure.
+.Pp
+The following values for
+.Fa op
+are supported, along with the required argument list:
+.Bl -tag -width 4n
+.It Dv EL_PROMPT , Fa "char *(*f)(EditLine *)"
+Define prompt printing function as
+.Fa f ,
+which is to return a string that contains the prompt.
+.It Dv EL_PROMPT_ESC , Fa "char *(*f)(EditLine *)" , Fa "char c"
+Same as
+.Dv EL_PROMPT ,
+but the
+.Fa c
+argument indicates the start/stop literal prompt character.
+.Pp
+If a start/stop literal character is found in the prompt, the
+character itself
+is not printed, but characters after it are printed directly to the
+terminal without affecting the state of the current line.
+A subsequent second start/stop literal character ends this behavior.
+This is typically used to embed literal escape sequences that change the
+color/style of the terminal in the prompt.
+.Dv 0
+unsets it.
+.It Dv EL_REFRESH
+Re-display the current line on the next terminal line.
+.It Dv EL_RPROMPT , Fa "char *(*f)(EditLine *)"
+Define right side prompt printing function as
+.Fa f ,
+which is to return a string that contains the prompt.
+.It Dv EL_RPROMPT_ESC , Fa "char *(*f)(EditLine *)" , Fa "char c"
+Define the right prompt printing function but with a literal escape character.
+.It Dv EL_TERMINAL , Fa "const char *type"
+Define terminal type of the tty to be
+.Fa type ,
+or to
+.Ev TERM
+if
+.Fa type
+is
+.Dv NULL .
+.It Dv EL_EDITOR , Fa "const char *mode"
+Set editing mode to
+.Fa mode ,
+which must be one of
+.Dq emacs
+or
+.Dq vi .
+.It Dv EL_SIGNAL , Fa "int flag"
+If
+.Fa flag
+is non-zero,
+.Nm
+will install its own signal handler for the following signals when
+reading command input:
+.Dv SIGCONT ,
+.Dv SIGHUP ,
+.Dv SIGINT ,
+.Dv SIGQUIT ,
+.Dv SIGSTOP ,
+.Dv SIGTERM ,
+.Dv SIGTSTP ,
+and
+.Dv SIGWINCH .
+Otherwise, the current signal handlers will be used.
+.It Dv EL_BIND , Fa "const char *" , Fa "..." , Dv NULL
+Perform the
+.Ic bind
+builtin command.
+Refer to
+.Xr editrc 5
+for more information.
+.It Dv EL_ECHOTC , Fa "const char *" , Fa "..." , Dv NULL
+Perform the
+.Ic echotc
+builtin command.
+Refer to
+.Xr editrc 5
+for more information.
+.It Dv EL_SETTC , Fa "const char *" , Fa "..." , Dv NULL
+Perform the
+.Ic settc
+builtin command.
+Refer to
+.Xr editrc 5
+for more information.
+.It Dv EL_SETTY , Fa "const char *" , Fa "..." , Dv NULL
+Perform the
+.Ic setty
+builtin command.
+Refer to
+.Xr editrc 5
+for more information.
+.It Dv EL_TELLTC , Fa "const char *" , Fa "..." , Dv NULL
+Perform the
+.Ic telltc
+builtin command.
+Refer to
+.Xr editrc 5
+for more information.
+.It Dv EL_ADDFN , Fa "const char *name" , Fa "const char *help" , \
+Fa "unsigned char (*func)(EditLine *e, int ch)"
+Add a user defined function,
+.Fn func ,
+referred to as
+.Fa name
+which is invoked when a key which is bound to
+.Fa name
+is entered.
+.Fa help
+is a description of
+.Fa name .
+At invocation time,
+.Fa ch
+is the key which caused the invocation.
+The return value of
+.Fn func
+should be one of:
+.Bl -tag -width "CC_REDISPLAY"
+.It Dv CC_NORM
+Add a normal character.
+.It Dv CC_NEWLINE
+End of line was entered.
+.It Dv CC_EOF
+EOF was entered.
+.It Dv CC_ARGHACK
+Expecting further command input as arguments, do nothing visually.
+.It Dv CC_REFRESH
+Refresh display.
+.It Dv CC_REFRESH_BEEP
+Refresh display, and beep.
+.It Dv CC_CURSOR
+Cursor moved, so update and perform
+.Dv CC_REFRESH .
+.It Dv CC_REDISPLAY
+Redisplay entire input line.
+This is useful if a key binding outputs extra information.
+.It Dv CC_ERROR
+An error occurred.
+Beep, and flush tty.
+.It Dv CC_FATAL
+Fatal error, reset tty to known state.
+.El
+.It Dv EL_HIST , Fa "History *(*func)(History *, int op, ...)" , \
+Fa "const char *ptr"
+Defines which history function to use, which is usually
+.Fn history .
+.Fa ptr
+should be the value returned by
+.Fn history_init .
+.It Dv EL_EDITMODE , Fa "int flag"
+If
+.Fa flag
+is non-zero,
+editing is enabled (the default).
+Note that this is only an indication, and does not
+affect the operation of
+.Nm .
+At this time, it is the caller's responsibility to
+check this
+(using
+.Fn el_get )
+to determine if editing should be enabled or not.
+.It Dv EL_UNBUFFERED , Fa "int flag"
+If
+.Fa flag
+is zero,
+unbuffered mode is disabled (the default).
+In unbuffered mode,
+.Fn el_gets
+will return immediately after processing a single character.
+.It Dv EL_GETCFN , Fa "el_rfunc_t f"
+Whenever reading a character, use the function
+.Bd -ragged -offset indent -compact
+.Ft int
+.Fo f
+.Fa "EditLine *e"
+.Fa "wchar_t *wc"
+.Fc
+.Ed
+which stores the character in
+.Fa wc
+and returns 1 on success, 0 on end of file, or \-1 on I/O or encoding
+errors.
+Functions internally using it include
+.Fn el_wgets ,
+.Fn el_wgetc ,
+.Fn el_gets ,
+and
+.Fn el_getc .
+Initially, a builtin function is installed, and replacing it
+is discouraged because writing such a function is very error prone.
+The builtin function can be restored at any time by passing the
+special value
+.Dv EL_BUILTIN_GETCFN
+instead of a function pointer.
+.It Dv EL_CLIENTDATA , Fa "void *data"
+Register
+.Fa data
+to be associated with this EditLine structure.
+It can be retrieved with the corresponding
+.Fn el_get
+call.
+.It Dv EL_SETFP , Fa "int fd" , Fa "FILE *fp"
+Set the current
+.Nm editline
+file pointer for
+.Dq input
+.Fa fd
+=
+.Dv 0 ,
+.Dq output
+.Fa fd
+=
+.Dv 1 ,
+or
+.Dq error
+.Fa fd
+=
+.Dv 2
+from
+.Fa fp .
+.El
+.It Fn el_get
+Get
+.Nm
+parameters.
+.Fa op
+determines which parameter to retrieve into
+.Fa result .
+Returns 0 if successful, \-1 otherwise.
+.Pp
+The following values for
+.Fa op
+are supported, along with actual type of
+.Fa result :
+.Bl -tag -width 4n
+.It Dv EL_PROMPT , Fa "char *(*f)(EditLine *)" , Fa "char *c"
+Set
+.Fa f
+to a pointer to the function that displays the prompt.
+If
+.Fa c
+is not
+.Dv NULL ,
+set it to the start/stop literal prompt character.
+.It Dv EL_RPROMPT , Fa "char *(*f)(EditLine *)" , Fa "char *c"
+Set
+.Fa f
+to a pointer to the function that displays the prompt.
+If
+.Fa c
+is not
+.Dv NULL ,
+set it to the start/stop literal prompt character.
+.It Dv EL_EDITOR , Fa "const char **n"
+Set the name of the editor in
+.Fa n ,
+which will be one of
+.Dq emacs
+or
+.Dq vi .
+.It Dv EL_GETTC , Fa "const char *name" , Fa "void *value"
+If
+.Fa name
+is a valid
+.Xr termcap 5
+capability set
+.Fa value
+to the current value of that capability.
+.It Dv EL_SIGNAL , Fa "int *s"
+Set
+.Fa s
+to non-zero if
+.Nm
+has installed private signal handlers (see
+.Fn el_get
+above).
+.It Dv EL_EDITMODE , Fa "int *c"
+Set
+.Fa c
+to non-zero if editing is enabled.
+.It Dv EL_GETCFN , Fa "el_rfunc_t *f"
+Set
+.Fa f
+to a pointer to the function that reads characters, or to
+.Dv EL_BUILTIN_GETCFN
+if the builtin function is in use.
+.It Dv EL_CLIENTDATA , Fa "void **data"
+Set
+.Fa data
+to the previously registered client data set by an
+.Fn el_set
+call.
+.It Dv EL_UNBUFFERED , Fa "int *c"
+Set
+.Fa c
+to non-zero if unbuffered mode is enabled.
+.It Dv EL_GETFP , Fa "int fd", Fa "FILE **fp"
+Set
+.Fa fp
+to the current
+.Nm editline
+file pointer for
+.Dq input
+.Fa fd
+=
+.Dv 0 ,
+.Dq output
+.Fa fd
+=
+.Dv 1 ,
+or
+.Dq error
+.Fa fd
+=
+.Dv 2 .
+.El
+.It Fn el_source
+Initialize
+.Nm
+by reading the contents of
+.Fa file .
+.Fn el_parse
+is called for each line in
+.Fa file .
+If
+.Fa file
+is
+.Dv NULL ,
+try
+.Pa $HOME/.editrc .
+Refer to
+.Xr editrc 5
+for details on the format of
+.Fa file .
+.Fn el_source
+returns 0 on success and \-1 on error.
+.It Fn el_resize
+Must be called if the terminal size changes.
+If
+.Dv EL_SIGNAL
+has been set with
+.Fn el_set ,
+then this is done automatically.
+Otherwise, it's the responsibility of the application to call
+.Fn el_resize
+on the appropriate occasions.
+.It Fn el_cursor
+Move the cursor to the right (if positive) or to the left (if negative)
+.Fa count
+characters.
+Returns the resulting offset of the cursor from the beginning of the line.
+.It Fn el_line
+Return the editing information for the current line in a
+.Fa LineInfo
+structure, which is defined as follows:
+.Bd -literal
+typedef struct lineinfo {
+ const char *buffer; /* address of buffer */
+ const char *cursor; /* address of cursor */
+ const char *lastchar; /* address of last character */
+} LineInfo;
+.Ed
+.Pp
+.Fa buffer
+is not NUL terminated.
+This function may be called after
+.Fn el_gets
+to obtain the
+.Fa LineInfo
+structure pertaining to line returned by that function,
+and from within user defined functions added with
+.Dv EL_ADDFN .
+.It Fn el_insertstr
+Insert
+.Fa str
+into the line at the cursor.
+Returns \-1 if
+.Fa str
+is empty or won't fit, and 0 otherwise.
+.It Fn el_deletestr
+Delete
+.Fa count
+characters before the cursor.
+.El
+.Sh HISTORY LIST FUNCTIONS
+The history functions use a common data structure,
+.Fa History ,
+which is created by
+.Fn history_init
+and freed by
+.Fn history_end .
+.Pp
+The following functions are available:
+.Bl -tag -width 4n
+.It Fn history_init
+Initialize the history list, and return a data structure
+to be used by all other history list functions, or
+.Dv NULL
+on failure.
+.It Fn history_end
+Clean up and finish with
+.Fa h ,
+assumed to have been created with
+.Fn history_init .
+.It Fn history
+Perform operation
+.Fa op
+on the history list, with optional arguments as needed by the
+operation.
+.Fa ev
+is changed accordingly to operation.
+The following values for
+.Fa op
+are supported, along with the required argument list:
+.Bl -tag -width 4n
+.It Dv H_SETSIZE , Fa "int size"
+Set size of history to
+.Fa size
+elements.
+.It Dv H_GETSIZE
+Get number of events currently in history.
+.It Dv H_END
+Cleans up and finishes with
+.Fa h ,
+assumed to be created with
+.Fn history_init .
+.It Dv H_CLEAR
+Clear the history.
+.It Dv H_FUNC , Fa "void *ptr" , Fa "history_gfun_t first" , \
+Fa "history_gfun_t next" , Fa "history_gfun_t last" , \
+Fa "history_gfun_t prev" , Fa "history_gfun_t curr" , \
+Fa "history_sfun_t set" , Fa "history_vfun_t clear" , \
+Fa "history_efun_t enter" , Fa "history_efun_t add"
+Define functions to perform various history operations.
+.Fa ptr
+is the argument given to a function when it's invoked.
+.It Dv H_FIRST
+Return the first element in the history.
+.It Dv H_LAST
+Return the last element in the history.
+.It Dv H_PREV
+Return the previous element in the history.
+It is newer than the current one.
+.It Dv H_NEXT
+Return the next element in the history.
+It is older than the current one.
+.It Dv H_CURR
+Return the current element in the history.
+.It Dv H_SET
+Set the cursor to point to the requested element.
+.It Dv H_ADD , Fa "const char *str"
+Append
+.Fa str
+to the current element of the history, or perform the
+.Dv H_ENTER
+operation with argument
+.Fa str
+if there is no current element.
+.It Dv H_APPEND , Fa "const char *str"
+Append
+.Fa str
+to the last new element of the history.
+.It Dv H_ENTER , Fa "const char *str"
+Add
+.Fa str
+as a new element to the history and, if necessary,
+removing the oldest entry to keep the list to the created size.
+If
+.Dv H_SETUNIQUE
+has been called with a non-zero argument, the element
+will not be entered into the history if its contents match
+the ones of the current history element.
+If the element is entered
+.Fn history
+returns 1; if it is ignored as a duplicate returns 0.
+Finally
+.Fn history
+returns \-1 if an error occurred.
+.It Dv H_PREV_STR , Fa "const char *str"
+Return the closest previous event that starts with
+.Fa str .
+.It Dv H_NEXT_STR , Fa "const char *str"
+Return the closest next event that starts with
+.Fa str .
+.It Dv H_PREV_EVENT , Fa "int e"
+Return the previous event numbered
+.Fa e .
+.It Dv H_NEXT_EVENT , Fa "int e"
+Return the next event numbered
+.Fa e .
+.It Dv H_LOAD , Fa "const char *file"
+Load the history list stored in
+.Fa file .
+.It Dv H_SAVE , Fa "const char *file"
+Save the history list to
+.Fa file .
+.It Dv H_SAVE_FP , Fa "FILE *fp"
+Save the history list to the opened
+.Ft FILE
+pointer
+.Fa fp .
+.It Dv H_SETUNIQUE , Fa "int unique"
+Set flag that adjacent identical event strings should not be entered
+into the history.
+.It Dv H_GETUNIQUE
+Retrieve the current setting if adjacent identical elements should
+be entered into the history.
+.It Dv H_DEL , Fa "int e"
+Delete the event numbered
+.Fa e .
+This function is only provided for
+.Xr readline 3
+compatibility.
+The caller is responsible for free'ing the string in the returned
+.Fa HistEvent .
+.El
+.Pp
+.Fn history
+returns \*[Gt]= 0 if the operation
+.Fa op
+succeeds.
+Otherwise, \-1 is returned and
+.Fa ev
+is updated to contain more details about the error.
+.El
+.Sh TOKENIZATION FUNCTIONS
+The tokenization functions use a common data structure,
+.Fa Tokenizer ,
+which is created by
+.Fn tok_init
+and freed by
+.Fn tok_end .
+.Pp
+The following functions are available:
+.Bl -tag -width 4n
+.It Fn tok_init
+Initialize the tokenizer, and return a data structure
+to be used by all other tokenizer functions.
+.Fa IFS
+contains the Input Field Separators, which defaults to
+.Aq space ,
+.Aq tab ,
+and
+.Aq newline
+if
+.Dv NULL .
+.It Fn tok_end
+Clean up and finish with
+.Fa t ,
+assumed to have been created with
+.Fn tok_init .
+.It Fn tok_reset
+Reset the tokenizer state.
+Use after a line has been successfully tokenized
+by
+.Fn tok_line
+or
+.Fn tok_str
+and before a new line is to be tokenized.
+.It Fn tok_line
+Tokenize
+.Fa li ,
+If successful, modify:
+.Fa argv
+to contain the words,
+.Fa argc
+to contain the number of words,
+.Fa cursorc
+(if not
+.Dv NULL )
+to contain the index of the word containing the cursor,
+and
+.Fa cursoro
+(if not
+.Dv NULL )
+to contain the offset within
+.Fa argv[cursorc]
+of the cursor.
+.Pp
+Returns
+0 if successful,
+\-1 for an internal error,
+1 for an unmatched single quote,
+2 for an unmatched double quote,
+and
+3 for a backslash quoted
+.Aq newline .
+A positive exit code indicates that another line should be read
+and tokenization attempted again.
+.
+.It Fn tok_str
+A simpler form of
+.Fn tok_line ;
+.Fa str
+is a NUL terminated string to tokenize.
+.El
+.
+.\"XXX.Sh EXAMPLES
+.\"XXX: provide some examples
+.Sh SEE ALSO
+.Xr sh 1 ,
+.Xr signal 3 ,
+.Xr termcap 3 ,
+.Xr editrc 5 ,
+.Xr termcap 5 ,
+.Xr editline 7
+.Sh HISTORY
+The
+.Nm
+library first appeared in
+.Bx 4.4 .
+.Dv CC_REDISPLAY
+appeared in
+.Nx 1.3 .
+.Dv CC_REFRESH_BEEP ,
+.Dv EL_EDITMODE
+and the readline emulation appeared in
+.Nx 1.4 .
+.Dv EL_RPROMPT
+appeared in
+.Nx 1.5 .
+.Sh AUTHORS
+.An -nosplit
+The
+.Nm
+library was written by
+.An Christos Zoulas .
+.An Luke Mewburn
+wrote this manual and implemented
+.Dv CC_REDISPLAY ,
+.Dv CC_REFRESH_BEEP ,
+.Dv EL_EDITMODE ,
+and
+.Dv EL_RPROMPT .
+.An Jaromir Dolecek
+implemented the readline emulation.
+.An Johny Mattsson
+implemented wide-character support.
+.Sh BUGS
+At this time, it is the responsibility of the caller to
+check the result of the
+.Dv EL_EDITMODE
+operation of
+.Fn el_get
+(after an
+.Fn el_source
+or
+.Fn el_parse )
+to determine if
+.Nm
+should be used for further input.
+I.e.,
+.Dv EL_EDITMODE
+is purely an indication of the result of the most recent
+.Xr editrc 5
+.Ic edit
+command.
diff --git a/third_party/heimdal/lib/libedit/src/editline.7 b/third_party/heimdal/lib/libedit/src/editline.7
new file mode 100644
index 0000000..863bab9
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/editline.7
@@ -0,0 +1,935 @@
+.\" $NetBSD: editline.7,v 1.5 2016/05/09 21:27:55 christos Exp $
+.\" $OpenBSD: editline.7,v 1.1 2016/04/20 01:11:45 schwarze Exp $
+.\"
+.\" Copyright (c) 2016 Ingo Schwarze <schwarze@openbsd.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.
+.\"
+.Dd May 7, 2016
+.Dt EDITLINE 7
+.Os
+.Sh NAME
+.Nm editline
+.Nd line editing user interface
+.Sh DESCRIPTION
+When a program using the
+.Xr editline 3
+library prompts for an input string using the function
+.Xr el_wgets 3 ,
+it reads characters from the terminal.
+Invalid input bytes that do not form characters are silently
+discarded.
+For each character read, one editor command is executed.
+The mapping of input characters to editor commands depends on the
+editing mode.
+There are three editing modes: vi insert mode, vi command mode,
+and emacs mode.
+The default is vi insert mode.
+The program can switch the default to emacs mode by using the
+.Xr el_set 3
+or
+.Xr el_parse 3
+functions, and the user can switch to emacs mode either in the
+.Xr editrc 5
+configuration file or interactively with the
+.Ic ed-command
+editor command, in all three cases executing the
+.Ic bind Fl e
+builtin command.
+.Pp
+If trying to read from the terminal results in end of file or an
+error, the library signals end of file to the program and does not
+return a string.
+.Ss Input character bindings
+All default bindings described below can be overridden by individual
+programs and can be changed with the
+.Xr editrc 5
+.Ic bind
+builtin command.
+.Pp
+In the following tables,
+.Sq Ctrl-
+indicates a character with the bit 0x40 flipped, and
+.Sq Meta-
+indicates a character with the bit 0x80 set.
+In vi insert mode and in emacs mode, all Meta-characters considered
+printable by the current
+.Xr locale 1
+are bound to
+.Ic ed-insert
+instead of to the editor command listed below.
+Consequently, in UTF-8 mode, most of the Meta-characters are not
+directly accessible because their code points are occupied by
+printable Unicode characters, and Meta-characters are usually input
+using the
+.Ic em-meta-next
+editor command.
+For example, to enter
+.Sq Meta-B
+in order to call the
+.Ic ed-prev-word
+editor command in emacs mode, call
+.Ic em-meta-next
+by pressing and releasing the escape key (or equivalently, Ctrl-[),
+then press and release the
+.Sq B
+key.
+If you have configured a Meta-key on your keyboard, for example
+with
+.Ql setxkbmap -option altwin:left_meta_win ,
+the Ctrl-Meta-characters are directly accessible.
+For example, to enter
+.Sq Ctrl-Meta-H
+in order to call the
+.Ic ed-delete-prev-word
+editor command in emacs mode, hold down the keys
+.Sq Ctrl ,
+.Sq Meta ,
+and
+.Sq H
+at the same time.
+Alternatively, press and release the escape key, then press and
+release
+.Sq Ctrl-H .
+.Pp
+In vi input mode, input characters are bound to the following editor
+commands by default:
+.Bl -column -offset indent "Ctrl-Z, TSTP" "ed-search-next-history"
+.It Ctrl-D, EOF Ta Ic vi-list-or-eof
+.It Ctrl-H, BS Ta Ic vi-delete-prev-char
+.It Ctrl-J, LF Ta Ic ed-newline
+.It Ctrl-M, CR Ta Ic ed-newline
+.It Ctrl-Q Ta Ic ed-tty-start-output
+.It Ctrl-S Ta Ic ed-tty-stop-output
+.It Ctrl-U Ta Ic vi-kill-line-prev
+.It Ctrl-V Ta Ic ed-quoted-insert
+.It Ctrl-W Ta Ic ed-delete-prev-word
+.It Ctrl-[, ESC Ta Ic vi-command-mode
+.It Ctrl-\e, QUIT Ta Ic ed-tty-sigquit
+.It Ctrl-?, DEL Ta Ic vi-delete-prev-char
+.El
+.Pp
+All other input characters except the NUL character (Ctrl-@) are
+bound to
+.Ic ed-insert .
+.Pp
+In vi command mode, input characters are bound to the following
+editor commands by default:
+.Bl -column -offset indent "Ctrl-Z, TSTP" "ed-search-next-history"
+.It Ctrl-A Ta Ic ed-move-to-beg
+.It Ctrl-C, INT Ta Ic ed-tty-sigint
+.It Ctrl-E Ta Ic ed-move-to-end
+.It Ctrl-H, BS Ta Ic ed-delete-prev-char
+.It Ctrl-J, LF Ta Ic ed-newline
+.It Ctrl-K Ta Ic ed-kill-line
+.It Ctrl-L, FF Ta Ic ed-clear-screen
+.It Ctrl-M, CR Ta Ic ed-newline
+.It Ctrl-N Ta Ic ed-next-history
+.It Ctrl-O Ta Ic ed-tty-flush-output
+.It Ctrl-P Ta Ic ed-prev-history
+.It Ctrl-Q Ta Ic ed-tty-start-output
+.It Ctrl-R Ta Ic ed-redisplay
+.It Ctrl-S Ta Ic ed-tty-stop-output
+.It Ctrl-U Ta Ic vi-kill-line-prev
+.It Ctrl-W Ta Ic ed-delete-prev-word
+.It Ctrl-[, ESC Ta Ic em-meta-next
+.It Ctrl-\e, QUIT Ta Ic ed-tty-sigquit
+.It Space Ta Ic ed-next-char
+.It # Ta Ic vi-comment-out
+.It $ Ta Ic ed-move-to-end
+.It % Ta Ic vi-match
+.It + Ta Ic ed-next-history
+.It \&, Ta Ic vi-repeat-prev-char
+.It - Ta Ic ed-prev-history
+.It \&. Ta Ic vi-redo
+.It / Ta Ic vi-search-prev
+.It 0 Ta Ic vi-zero
+.It 1 to 9 Ta Ic ed-argument-digit
+.It \&: Ta Ic ed-command
+.It \&; Ta Ic vi-repeat-next-char
+.It \&? Ta Ic vi-search-next
+.It @ Ta Ic vi-alias
+.It A Ta Ic vi-add-at-eol
+.It B Ta Ic vi-prev-big-word
+.It C Ta Ic vi-change-to-eol
+.It D Ta Ic ed-kill-line
+.It E Ta Ic vi-end-big-word
+.It F Ta Ic vi-prev-char
+.It G Ta Ic vi-to-history-line
+.It I Ta Ic vi-insert-at-bol
+.It J Ta Ic ed-search-next-history
+.It K Ta Ic ed-search-prev-history
+.It N Ta Ic vi-repeat-search-prev
+.It O Ta Ic ed-sequence-lead-in
+.It P Ta Ic vi-paste-prev
+.It R Ta Ic vi-replace-mode
+.It S Ta Ic vi-substitute-line
+.It T Ta Ic vi-to-prev-char
+.It U Ta Ic vi-undo-line
+.It W Ta Ic vi-next-big-word
+.It X Ta Ic ed-delete-prev-char
+.It Y Ta Ic vi-yank-end
+.It \&[ Ta Ic ed-sequence-lead-in
+.It ^ Ta Ic ed-move-to-beg
+.It _ Ta Ic vi-history-word
+.It a Ta Ic vi-add
+.It b Ta Ic vi-prev-word
+.It c Ta Ic vi-change-meta
+.It d Ta Ic vi-delete-meta
+.It e Ta Ic vi-end-word
+.It f Ta Ic vi-next-char
+.It h Ta Ic ed-prev-char
+.It i Ta Ic vi-insert
+.It j Ta Ic ed-next-history
+.It k Ta Ic ed-prev-history
+.It l Ta Ic ed-next-char
+.It n Ta Ic vi-repeat-search-next
+.It p Ta Ic vi-paste-next
+.It r Ta Ic vi-replace-char
+.It s Ta Ic vi-substitute-char
+.It t Ta Ic vi-to-next-char
+.It u Ta Ic vi-undo
+.It v Ta Ic vi-histedit
+.It w Ta Ic vi-next-word
+.It x Ta Ic ed-delete-next-char
+.It y Ta Ic vi-yank
+.It \&| Ta Ic vi-to-column
+.It ~ Ta Ic vi-change-case
+.It Ctrl-?, DEL Ta Ic ed-delete-prev-char
+.It Meta-O Ta Ic ed-sequence-lead-in
+.It Meta-[ Ta Ic ed-sequence-lead-in
+.El
+.Pp
+In emacs mode, input characters are bound to the following editor
+commands by default:
+.Bl -column -offset indent "Ctrl-Z, TSTP" "ed-search-next-history"
+.It 0 to 9 Ta Ic ed-digit
+.It Ctrl-@, NUL Ta Ic em-set-mark
+.It Ctrl-A Ta Ic ed-move-to-beg
+.It Ctrl-B Ta Ic ed-prev-char
+.It Ctrl-C, INT Ta Ic ed-tty-sigint
+.It Ctrl-D, EOF Ta Ic em-delete-or-list
+.It Ctrl-E Ta Ic ed-move-to-end
+.It Ctrl-F Ta Ic ed-next-char
+.It Ctrl-H, BS Ta Ic em-delete-prev-char
+.It Ctrl-J, LF Ta Ic ed-newline
+.It Ctrl-K Ta Ic ed-kill-line
+.It Ctrl-L, FF Ta Ic ed-clear-screen
+.It Ctrl-M, CR Ta Ic ed-newline
+.It Ctrl-N Ta Ic ed-next-history
+.It Ctrl-O Ta Ic ed-tty-flush-output
+.It Ctrl-P Ta Ic ed-prev-history
+.It Ctrl-Q Ta Ic ed-tty-start-output
+.It Ctrl-R Ta Ic ed-redisplay
+.It Ctrl-S Ta Ic ed-tty-stop-output
+.It Ctrl-T Ta Ic ed-transpose-chars
+.It Ctrl-U Ta Ic ed-kill-line
+.It Ctrl-V Ta Ic ed-quoted-insert
+.It Ctrl-W Ta Ic em-kill-region
+.It Ctrl-X Ta Ic ed-sequence-lead-in
+.It Ctrl-Y Ta Ic em-yank
+.It Ctrl-Z, TSTP Ta Ic ed-tty-sigtstp
+.It Ctrl-[, ESC Ta Ic em-meta-next
+.It Ctrl-\e, QUIT Ta Ic ed-tty-sigquit
+.It Ctrl-] Ta Ic ed-tty-dsusp
+.It Ctrl-?, DEL Ta Ic em-delete-prev-char
+.It Ctrl-Meta-H Ta Ic ed-delete-prev-word
+.It Ctrl-Meta-L Ta Ic ed-clear-screen
+.It Ctrl-Meta-_ Ta Ic em-copy-prev-word
+.It Meta-0 to 9 Ta Ic ed-argument-digit
+.It Meta-B Ta Ic ed-prev-word
+.It Meta-C Ta Ic em-capitol-case
+.It Meta-D Ta Ic em-delete-next-word
+.It Meta-F Ta Ic em-next-word
+.It Meta-L Ta Ic em-lower-case
+.It Meta-N Ta Ic ed-search-next-history
+.It Meta-O Ta Ic ed-sequence-lead-in
+.It Meta-P Ta Ic ed-search-prev-history
+.It Meta-U Ta Ic em-upper-case
+.It Meta-W Ta Ic em-copy-region
+.It Meta-X Ta Ic ed-command
+.It Meta-[ Ta Ic ed-sequence-lead-in
+.It Meta-b Ta Ic ed-prev-word
+.It Meta-c Ta Ic em-capitol-case
+.It Meta-d Ta Ic em-delete-next-word
+.It Meta-f Ta Ic em-next-word
+.It Meta-l Ta Ic em-lower-case
+.It Meta-n Ta Ic ed-search-next-history
+.It Meta-p Ta Ic ed-search-prev-history
+.It Meta-u Ta Ic em-upper-case
+.It Meta-w Ta Ic em-copy-region
+.It Meta-x Ta Ic ed-command
+.It Ctrl-Meta-? Ta Ic ed-delete-prev-word
+.El
+.Pp
+The remaining
+.Xr ascii 7
+characters in the range 0x20 to 0x7e are bound to
+.Ic ed-insert .
+.Pp
+If standard output is not connected to a terminal device
+or
+.Xr el_set 3
+was used to set
+.Dv EL_EDITMODE
+to 0, all input character bindings are disabled and all characters
+typed are appended to the edit buffer.
+In that case, the edit buffer is returned to the program after a
+newline or carriage return character is typed, or after the first
+character typed if
+.Xr el_set 3
+was used to set
+.Dv EL_UNBUFFERED
+to non-zero.
+.Ss Editor commands
+Most editor commands accept an optional argument.
+The argument is entered by prefixing the editor command with one
+or more of the editor commands
+.Ic ed-argument-digit ,
+.Ic ed-digit ,
+.Ic em-universal-argument ,
+or
+.Ic vi-zero .
+When an argument is not provided, it defaults to 1.
+For most editor commands, the effect of an argument is to repeatedly
+execute the command that number of times.
+.Pp
+When talking about a character string from a left character to a
+right character, the left character is included in the string, while
+the right character is not included.
+.Pp
+If an editor command causes an error, the input character is discarded,
+no action occurs, and the terminal bell is rung.
+In case of a non-fatal error, the terminal bell is also rung,
+but the editor command takes effect anyway.
+.Pp
+In the following list, the default key bindings are listed after
+each editor command.
+.Bl -tag -width 4n
+.It Ic ed-argument-digit Pq vi command: 1 to 9; emacs: Meta-0 to Meta-9
+If in argument input mode, append the input digit to the argument
+being read.
+Otherwise, switch to argument input mode and use the input digit
+as the most significant digit of the argument.
+It is an error if the input character is not a digit or if the
+existing argument is already greater than a million.
+.It Ic ed-clear-screen Pq vi command: Ctrl-L; emacs: Ctrl-L, Ctrl-Meta-L
+Clear the screen and display the edit buffer at the top.
+Ignore any argument.
+.It Ic ed-command Pq vi command: So \&: Sc ; emacs: Meta-X, Meta-x
+Read a line from the terminal bypassing the normal line editing
+functionality and execute that line as an
+.Xr editrc 5
+builtin command.
+If in vi command mode, also switch back to vi insert mode.
+Ignore any argument.
+.It Ic ed-delete-next-char Pq vi command: x
+Delete the character at the cursor position.
+With an argument, delete that number of characters.
+In emacs mode, it is an error if the cursor is at the end of the
+edit buffer.
+In vi mode, the last character in the edit buffer is deleted in
+that case, and it is an error if the buffer is empty.
+.It Ic ed-delete-prev-char Pq vi command: X, Ctrl-H, BS, Ctrl-?, DEL
+Delete the character to the left of the cursor position.
+With an argument, delete that number of characters.
+It is an error if the cursor is at the beginning of the edit buffer.
+.It Ic ed-delete-prev-word Pq vi: Ctrl-W; emacs: Ctrl-Meta-H, Ctrl-Meta-?
+Move to the left to the closest beginning of a word, delete the
+string from that position to the cursor, and save it to the cut
+buffer.
+With an argument, delete that number of words.
+It is an error if the cursor is at the beginning of the edit buffer.
+.It Ic ed-digit Pq emacs: 0 to 9
+If in argument input mode, append the input digit to the argument
+being read.
+Otherwise, call
+.Ic ed-insert .
+It is an error if the input character is not a digit or if the
+existing argument is already greater than a million.
+.It Ic ed-end-of-file Pq not bound by default
+Discard the edit buffer and indicate end of file to the program.
+Ignore any argument.
+.It Ic ed-ignore Pq various
+Discard the input character and do nothing.
+.It Ic ed-insert Pq vi input: almost all; emacs: printable characters
+In insert mode, insert the input character left of the cursor
+position.
+In replace mode, overwrite the character at the cursor and move the
+cursor to the right by one character position.
+Accept an argument to do this repeatedly.
+It is an error if the input character is the NUL character (Ctrl-@).
+Failure to enlarge the edit buffer also results in an error.
+.It Ic ed-kill-line Pq vi command: D, Ctrl-K; emacs: Ctrl-K, Ctrl-U
+Delete the string from the cursor position to the end of the line
+and save it to the cut buffer.
+Ignore any argument.
+.It Ic ed-move-to-beg Pq vi command: ^, Ctrl-A; emacs: Ctrl-A
+In vi mode, move the cursor to the first non-space character in the
+edit buffer.
+In emacs mode, move the cursor to the beginning of the edit buffer.
+Ignore any argument.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+.It Ic ed-move-to-end Pq vi command: $, Ctrl-E; emacs: Ctrl-E
+Move the cursor to the end of the edit buffer.
+Ignore any argument.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+.It Ic ed-newline Pq all modes: Ctrl-J, LF, Ctrl-M, CR
+Append a newline character to the edit buffer and return the edit
+buffer to the program.
+Ignore any argument.
+.It Ic ed-next-char Pq vi command: Space, l; emacs: Ctrl-F
+Move the cursor one character position to the right.
+With an argument, move by that number of characters.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+It is an error if the cursor is already at the end of the edit
+buffer.
+.It Ic ed-next-history Pq vi command: j, +, Ctrl-N; emacs: Ctrl-N
+Replace the edit buffer with the next history line.
+That line is older than the current line.
+With an argument, go forward by that number of history lines.
+It is a non-fatal error to advance by more lines than are available.
+.It Ic ed-next-line Pq not bound by default
+Move the cursor down one line.
+With an argument, move down by that number of lines.
+It is an error if the edit buffer does not contain enough newline
+characters to the right of the cursor position.
+.It Ic ed-prev-char Pq vi command: h; emacs: Ctrl-B
+Move the cursor one character position to the left.
+With an argument, move by that number of characters.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+It is an error if the cursor is already at the beginning of the
+edit buffer.
+.It Ic ed-prev-history Pq vi command: k, -, Ctrl-P; emacs: Ctrl-P
+Replace the edit buffer with the previous history line.
+That line is newer than the current line.
+With an argument, go back by that number of lines.
+It is a non-fatal error to back up by more lines than are available.
+.It Ic ed-prev-line Pq not bound by default
+Move the cursor up one line.
+With an argument, move up by that number of lines.
+It is an error if the edit buffer does not contain enough newline
+characters to the left of the cursor position.
+.It Ic ed-prev-word Pq emacs: Meta-B, Meta-b
+Move the cursor to the left to the closest beginning of a word.
+With an argument, repeat that number of times.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+It is an error if the cursor is already at the beginning of the
+edit buffer.
+.It Ic ed-quoted-insert Pq vi insert, emacs: Ctrl-V
+Read one character from the terminal bypassing the normal line
+editing functionality and call
+.Ic ed-insert
+on it.
+If trying to read the character returns end of file or an error,
+call
+.Ic ed-end-of-file
+instead.
+.It Ic ed-redisplay Pq vi command, emacs: Ctrl-R
+Redisplay everything.
+Ignore any argument.
+.It Ic ed-search-next-history Pq vi command: J; emacs: Meta-N, Meta-n
+Replace the edit buffer with the next matching history entry.
+.It Ic ed-search-prev-history Pq vi command: K; emacs: Meta-P, Meta-p
+Replace the edit buffer with the previous matching history entry.
+.It Ic ed-sequence-lead-in Pq vi cmd: O, \&[; emacs: Ctrl-X;\
+ both: Meta-O, Meta-[
+Call a macro.
+See the section about
+.Sx Macros
+below for details.
+.It Ic ed-start-over Pq not bound by default
+Discard the contents of the edit buffer and start from scratch.
+Ignore any argument.
+.It Ic ed-transpose-chars Pq emacs: Ctrl-T
+Exchange the character at the cursor position with the one to the
+left of it and move the cursor to the character to the right of the
+two exchanged characters.
+Ignore any argument.
+It is an error if the cursor is at the beginning of the edit buffer
+or if the edit buffer contains less than two characters.
+.It Ic ed-unassigned Pq all characters not listed
+This editor command always results in an error.
+.It Ic em-capitol-case Pq emacs: Meta-C, Meta-c
+Capitalize the string from the cursor to the end of the current
+word.
+That is, if it contains at least one alphabetic character, convert
+the first alphabetic character to upper case, and convert all
+characters to the right of it to lower case.
+In any case, move the cursor to the next character after the end
+of the current word.
+.It Ic em-copy-prev-word Pq emacs: Ctrl-Meta-_
+Copy the string from the beginning of the current word to the cursor
+and insert it to the left of the cursor.
+Move the cursor to the character after the inserted string.
+It is an error if the cursor is at the beginning of the edit buffer.
+.It Ic em-copy-region Pq emacs: Meta-W, Meta-w
+Copy the string from the cursor to the mark to the cut buffer.
+It is an error if the mark is not set.
+.It Ic em-delete-next-word Pq emacs: Meta-D, Meta-d
+Delete the string from the cursor to the end of the current word
+and save it to the cut buffer.
+It is an error if the cursor is at the end of the edit buffer.
+.It Ic em-delete-or-list Pq emacs: Ctrl-D, EOF
+If the cursor is not at the end of the line, delete the character
+at the cursor.
+If the edit buffer is empty, indicate end of file to the program.
+It is an error if the cursor is at the end of the edit buffer and
+the edit buffer is not empty.
+.It Ic em-delete-prev-char Pq emacs: Ctrl-H, BS, Ctrl-?, DEL
+Delete the character to the left of the cursor.
+It is an error if the cursor is at the beginning of the edit buffer.
+.It Ic em-exchange-mark Pq not bound by default
+Exchange the cursor and the mark.
+.It Ic em-gosmacs-transpose Pq not bound by default
+Exchange the two characters to the left of the cursor.
+It is an error if the cursor is on the first or second character
+of the edit buffer.
+.It Ic em-inc-search-next Pq not bound by default
+Emacs incremental next search.
+.It Ic em-inc-search-prev Pq not bound by default
+Emacs incremental reverse search.
+.It Ic em-kill-line Pq not bound by default
+Delete the entire contents of the edit buffer and save it to the
+cut buffer.
+.It Ic em-kill-region Pq emacs: Ctrl-W
+Delete the string from the cursor to the mark and save it to the
+cut buffer.
+It is an error if the mark is not set.
+.It Ic em-lower-case Pq emacs: Meta-L, Meta-l
+Convert the characters from the cursor to the end of the current
+word to lower case.
+.It Ic em-meta-next Pq vi command, emacs: Ctrl-[, ESC
+Set the bit 0x80 on the next character typed.
+Unless the resulting code point is printable, holding down the
+.Sq Meta-
+key while typing that character is a simpler way to achieve the
+same effect.
+.It Ic em-next-word Pq Meta-F, Meta-f
+Move the cursor to the end of the current word.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+It is an error if the cursor is already at the end of the edit
+buffer.
+.It Ic em-set-mark Pq emacs: Ctrl-Q, NUL
+Set the mark at the current cursor position.
+.It Ic em-toggle-overwrite Pq not bound by default
+Switch from insert to overwrite mode or vice versa.
+.It Ic em-universal-argument Pq not bound by default
+If in argument input mode, multiply the argument by 4.
+Otherwise, switch to argument input mode and set the argument to 4.
+It is an error if the existing argument is already greater than a
+million.
+.It Ic em-upper-case Pq emacs: Meta-U, Meta-u
+Convert the characters from the cursor to the end of the current
+word to upper case.
+.It Ic em-yank Pq emacs: Ctrl-Y
+Paste the cut buffer to the left of the cursor.
+.It Ic vi-add Pq vi command: a
+Switch to vi insert mode.
+Unless the cursor is already at the end of the edit buffer, move
+it one character position to the right.
+.It Ic vi-add-at-eol Pq vi command: A
+Switch to vi insert mode and move the cursor to the end of the edit
+buffer.
+.It Ic vi-alias Pq vi command: @
+If an alias function was defined by calling the
+.Xr el_set 3
+or
+.Xr el_wset 3
+function with the argument
+.Dv EL_ALIAS_TEXT ,
+read one character from the terminal bypassing the normal line
+editing functionality, call the alias function passing the argument that was specified with
+.Dv EL_ALIAS_TEXT
+as the first argument and the character read, with an underscore
+prepended, as the second argument, and pass the string returned
+from the alias function to
+.Xr el_wpush 3 .
+It is an error if no alias function is defined or if trying to read
+the character results in end of file or an error.
+.It Ic vi-change-case Pq vi command: ~
+Change the case of the character at the cursor and move the cursor
+one character position to the right.
+It is an error if the cursor is already at the end of the edit
+buffer.
+.It Ic vi-change-meta Pq vi command: c
+Delete the string from the cursor to the position specified by the
+following movement command and save a copy of it to the cut buffer.
+When given twice in a row, instead delete the whole contents of the
+edit buffer and save a copy of it to the cut buffer.
+In either case, switch to vi insert mode after that.
+.It Ic vi-change-to-eol Pq vi command: C
+Delete the string from the cursor position to the end of the line
+and save it to the cut buffer, then switch to vi insert mode.
+.It Ic vi-command-mode Pq vi insert: Ctrl-[, ESC
+Discard pending actions and arguments and switch to vi command mode.
+Unless the cursor is already at the beginning of the edit buffer,
+move it to the left by one character position.
+.It Ic vi-comment-out Pq vi command: #
+Insert a
+.Sq #
+character at the beginning of the edit buffer and return the edit
+buffer to the program.
+.It Ic vi-delete-meta Pq vi command: d
+Delete the string from the cursor to the position specified by the
+following movement command and save a copy of it to the cut buffer.
+When given twice in a row, instead delete the whole contents of the
+edit buffer and save a copy of it to the cut buffer.
+.It Ic vi-delete-prev-char Pq vi insert: Ctrl-H, BS, Ctrl-?, DEL
+Delete the character to the left of the cursor.
+It is an error if the cursor is already at the beginning of the
+edit buffer.
+.It Ic vi-end-big-word Pq vi command: E
+Move the cursor to the end of the current space delimited word.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+It is an error if the cursor is already at the end of the edit
+buffer.
+.It Ic vi-end-word Pq vi command: e
+Move the cursor to the end of the current word.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+It is an error if the cursor is already at the end of the edit
+buffer.
+.It Ic vi-history-word Pq vi command: _
+Insert the first word from the most recent history entry after the
+cursor, move the cursor after to the character after the inserted
+word, and switch to vi insert mode.
+It is an error if there is no history entry or the most recent
+history entry is empty.
+.It Ic vi-insert Pq vi command: i
+Enter insert mode.
+.It Ic vi-insert-at-bol Pq vi command: I
+Move the cursor to the beginning of the edit buffer and switch to
+vi insert mode.
+.It Ic vi-kill-line-prev Pq vi: Ctrl-U
+Delete the string from the beginning of the edit buffer to the
+cursor and save it to the cut buffer.
+.It Ic vi-list-or-eof Pq vi insert: Ctrl-D, EOF
+If the edit buffer is empty, indicate end of file to the program.
+It is an error if the edit buffer is not empty.
+.It Ic vi-match Pq vi command: %
+Consider opening and closing parentheses, braces, and brackets as
+delimiters.
+If the cursor is not at a delimiter, move it to the right until it
+gets to one, then move it to the matching delimiter.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+It is an error if there is no delimiter at the cursor or in the
+string to the right of the cursor, or if the first such delimiter
+has no matching delimiter.
+.It Ic vi-next-big-word Pq vi command: W
+Move the cursor to the right to the beginning of the next space
+delimited word.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+It is an error if the cursor is already at the end of the edit
+buffer or on its last character.
+.It Ic vi-next-char Pq vi command: f
+Read one character from the terminal bypassing the normal line
+editing functionality and move the cursor to the right to the next
+instance of that character in the edit buffer.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+If trying to read the character results in end of file or an error,
+call
+.Ic ed-end-of-file
+instead.
+It is an error if the character is not found searching to the right
+in the edit buffer.
+.It Ic vi-next-word Pq vi command: w
+Move the cursor to the right to the beginning of the next word.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+It is an error if the cursor is already at the end of the edit
+buffer or on its last character.
+.It Ic vi-paste-next Pq vi command: p
+Insert a copy of the cut buffer to the right of the cursor.
+It is an error if the cut buffer is empty.
+.It Ic vi-paste-prev Pq vi command: P
+Insert a copy of the cut buffer to the left of the cursor.
+It is an error if the cut buffer is empty.
+.It Ic vi-prev-big-word Pq vi command: B
+Move the cursor to the left to the next beginning of a space delimited
+word.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+It is an error if the cursor is already at the beginning of the
+edit buffer.
+.It Ic vi-prev-char Pq vi command: F
+Read one character from the terminal bypassing the normal line
+editing functionality and move the cursor to the left to the next
+instance of that character in the edit buffer.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+If trying to read the character results in end of file or an error,
+call
+.Ic ed-end-of-file
+instead.
+It is an error if the character is not found searching to the left
+in the edit buffer.
+.It Ic vi-prev-word Pq vi command: b
+Move the cursor to the left to the next beginning of a word.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+It is an error if the cursor is already at the beginning of the
+edit buffer.
+.It Ic vi-redo Pq vi command: Sq \&.
+Redo the last non-motion command.
+.It Ic vi-repeat-next-char Pq vi command: Sq \&;
+Repeat the most recent character search in the same search direction.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+.It Ic vi-repeat-prev-char Pq vi command: Sq \&,
+Repeat the most recent character search in the opposite search
+direction.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+.It Ic vi-repeat-search-next Pq vi command: n
+Repeat the most recent history search in the same search direction.
+.It Ic vi-repeat-search-prev Pq vi command: N
+Repeat the most recent history search in the opposite search
+direction.
+.It Ic vi-replace-char Pq vi command: r
+Switch to vi replace mode, and automatically switch back to vi
+command mode after the next character typed.
+See
+.Ic ed-insert
+for a description of replace mode.
+It is an error if the cursor is at the end of the edit buffer.
+.It Ic vi-replace-mode Pq vi command: R
+Switch to vi replace mode.
+This is a variant of vi insert mode; see
+.Ic ed-insert
+for the difference.
+.It Ic vi-search-next Pq vi command: \&?
+Replace the edit buffer with the next matching history entry.
+.It Ic vi-search-prev Pq vi command: /
+Replace the edit buffer with the previous matching history entry.
+.It Ic vi-substitute-char Pq vi command: s
+Delete the character at the cursor and switch to vi insert mode.
+.It Ic vi-substitute-line Pq vi command: S
+Delete the entire contents of the edit buffer, save a copy of it
+in the cut buffer, and enter vi insert mode.
+.It Ic vi-to-column Pq vi command: \&|
+Move the cursor to the column specified as the argument.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+.It Ic vi-to-history-line Pq vi command: G
+Replace the edit buffer with the specified history entry.
+.It Ic vi-to-next-char Pq vi command: t
+Read one character from the terminal bypassing the normal line
+editing functionality and move the cursor to the right to the
+character before the next instance of that character in the edit
+buffer.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+If trying to read the character results in end of file or an error,
+call
+.Ic ed-end-of-file
+instead.
+It is an error if the character is not found searching to the right
+in the edit buffer.
+.It Ic vi-to-prev-char Pq vi command: T
+Read one character from the terminal bypassing the normal line
+editing functionality and move the cursor to the left to the character
+after the next instance of that character in the edit buffer.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+If trying to read the character results in end of file or an error,
+call
+.Ic ed-end-of-file
+instead.
+It is an error if the character is not found searching to the left
+in the edit buffer.
+.It Ic vi-undo Pq vi command: u
+Undo the last change.
+.It Ic vi-undo-line Pq vi command: U
+Undo all changes to the edit buffer.
+.It Ic vi-yank Pq vi command: y
+Copy the string from the cursor to the position specified by the
+following movement command to the cut buffer.
+When given twice in a row, instead copy the whole contents of the
+edit buffer to the cut buffer.
+.It Ic vi-yank-end Pq vi command: Y
+Copy the string from the cursor to the end of the edit buffer to
+the cut buffer.
+.It Ic vi-zero Pq vi command: 0
+If in argument input mode, multiply the argument by ten.
+Otherwise, move the cursor to the beginning of the edit buffer.
+Can be used as a movement command after
+.Ic vi_change_meta ,
+.Ic vi_delete_meta ,
+or
+.Ic vi_yank .
+.El
+.Ss Macros
+If an input character is bound to the editor command
+.Ic ed-sequence-lead-in ,
+.Nm
+attempts to call a macro.
+If the input character by itself forms the name of a macro, that
+macro is executed.
+Otherwise, additional input characters are read until the string
+read forms the name of a macro, in which case that macro is executed,
+or until the string read matches the beginning of none of the existing
+macro names, in which case the string including the final, mismatching
+character is discarded and the terminal bell is rung.
+.Pp
+There are two kinds of macros.
+Command macros execute a single editor command.
+Keyboard macros return a string of characters that is appended
+as a new line to the
+.Sx Input Queue .
+.Pp
+The following command macros are defined by default in vi command
+mode and in emacs mode:
+.Bl -column -offset indent "Esc O A, Esc O A" "em-exchange-mark"
+.It Esc \&[ A, Esc O A Ta Ic ed-prev-history
+.It Esc \&[ B, Esc O B Ta Ic ed-next-history
+.It Esc \&[ C, Esc O C Ta Ic ed-next-char
+.It Esc \&[ D, Esc O D Ta Ic ed-prev-char
+.It Esc \&[ F, Esc O F Ta Ic ed-move-to-end
+.It Esc \&[ H, Esc O H Ta Ic ed-move-to-beg
+.El
+.Pp
+In vi command mode, they are also defined by default without the
+initial escape character.
+.Pp
+In addition, the
+.Nm
+library tries to bind the strings generated by the arrow keys
+as reported by the
+.Xr terminfo 5
+database to these editor commands, unless that would clobber
+user settings.
+.Pp
+In emacs mode, the two-character string
+.Dq Ctrl-X Ctrl-X
+is bound to the
+.Ic em-exchange-mark
+editor command.
+.Ss Input Queue
+The
+.Nm
+library maintains an input queue operated in FIFO mode.
+Whenever it needs an input character, it takes the first character
+from the first line of the input queue.
+When the queue is empty, it reads from the terminal.
+.Pp
+A line can be appended to the end of the input queue in several ways:
+.Bl -dash -offset indent
+.It
+By calling one of the keyboard
+.Sx Macros .
+.It
+By calling the editor command
+.Ic vi-redo .
+.It
+By calling the editor command
+.Ic vi-alias .
+.It
+By pressing a key in emacs incremental search mode that doesn't
+have a special meaning in that mode but returns to normal emacs
+mode.
+.It
+If an application program directly calls the functions
+.Xr el_push 3
+or
+.Xr el_wpush 3 ,
+it can provide additional, program-specific ways
+of appending to the input queue.
+.El
+.Sh SEE ALSO
+.Xr mg 1 ,
+.Xr vi 1 ,
+.Xr editline 3 ,
+.Xr el_wgets 3 ,
+.Xr el_wpush 3 ,
+.Xr el_wset 3 ,
+.Xr editrc 5
+.Sh HISTORY
+This manual page first appeared in
+.Ox 6.0
+and
+.Nx 8 .
+.Sh AUTHORS
+.An -nosplit
+This manual page was written by
+.An Ingo Schwarze Aq Mt schwarze@openbsd.org .
diff --git a/third_party/heimdal/lib/libedit/src/editrc.5 b/third_party/heimdal/lib/libedit/src/editrc.5
new file mode 100644
index 0000000..723cb9e
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/editrc.5
@@ -0,0 +1,317 @@
+.\" $NetBSD: editrc.5,v 1.32 2016/05/22 23:54:20 christos Exp $
+.\"
+.\" Copyright (c) 1997-2000 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This file was contributed to The NetBSD Foundation by Luke Mewburn.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+.\" ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+.\" TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+.\" BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+.\" POSSIBILITY OF SUCH DAMAGE.
+.\"
+.Dd May 22, 2016
+.Dt EDITRC 5
+.Os
+.Sh NAME
+.Nm editrc
+.Nd configuration file for editline library
+.Sh SYNOPSIS
+.Nm
+.Sh DESCRIPTION
+The
+.Nm
+file defines various settings to be used by the
+.Xr editline 3
+library.
+.Pp
+The format of each line is:
+.Pp
+.Dl [prog:]command [arg ...]
+.Pp
+.Ar command
+is one of the
+.Xr editline 3
+builtin commands.
+Refer to
+.Sx BUILTIN COMMANDS
+for more information.
+.Pp
+.Ar prog
+is the program name string that a program defines when it calls
+.Xr el_init 3
+to set up
+.Xr editline 3 ,
+which is usually
+.Va argv[0] .
+.Ar command
+will be executed for any program which matches
+.Ar prog .
+.Pp
+.Ar prog
+may also be a
+.Xr regex 3
+style
+regular expression, in which case
+.Ar command
+will be executed for any program that matches the regular expression.
+.Pp
+If
+.Ar prog
+is absent,
+.Ar command
+is executed for all programs.
+.Sh BUILTIN COMMANDS
+The
+.Nm editline
+library has some builtin commands, which affect the way
+that the line editing and history functions operate.
+These are based on similar named builtins present in the
+.Xr tcsh 1
+shell.
+.Pp
+The following builtin commands are available:
+.Bl -tag -width 4n
+.It Ic bind Oo Fl aeklrsv Oc Op Ar key Op Ar command
+Without options and arguments, list all bound keys and macros, and
+the editor command or input string to which each one is bound.
+If only
+.Ar key
+is supplied, show the binding for that key or macro.
+If
+.Ar key command
+is supplied, bind the editor
+.Ar command
+to that key or macro.
+.Pp
+The options are as follows:
+.Bl -tag -width 4n
+.It Fl a
+List or change key bindings in the
+.Xr vi 1
+mode alternate (command mode) key map.
+.It Fl e
+Bind all keys to the standard GNU Emacs-like bindings.
+.It Fl k
+.Ar key
+is interpreted as a symbolic arrow key name, which may be one of
+.Sq up ,
+.Sq down ,
+.Sq left
+or
+.Sq right .
+.It Fl l
+List all editor commands and a short description of each.
+.It Fl r
+Remove the binding of the key or macro
+.Ar key .
+.It Fl s
+Define a keyboard macro rather than a key binding or command macro:
+.Ar command
+is taken as a literal string and appended to the input queue whenever
+.Ar key
+is typed.
+Bound keys and macros in
+.Ar command
+are themselves reinterpreted, and this continues for ten levels of
+interpretation.
+.It Fl v
+Bind all keys to the standard
+.Xr vi 1 Ns -like
+bindings.
+.El
+.Pp
+The
+.Xr editline 7
+manual documents all editor commands and contains more information
+about macros and the input queue.
+.Pp
+.Ar key
+and
+.Ar command
+can contain control characters of the form
+.Sm off
+.Sq No ^ Ar character
+.Sm on
+.Po
+e.g.\&
+.Sq ^A
+.Pc ,
+and the following backslashed escape sequences:
+.Pp
+.Bl -tag -compact -offset indent -width 4n
+.It Ic \ea
+Bell
+.It Ic \eb
+Backspace
+.It Ic \ee
+Escape
+.It Ic \ef
+Formfeed
+.It Ic \en
+Newline
+.It Ic \er
+Carriage return
+.It Ic \et
+Horizontal tab
+.It Ic \ev
+Vertical tab
+.Sm off
+.It Sy \e Ar nnn
+.Sm on
+The ASCII character corresponding to the octal number
+.Ar nnn .
+.El
+.Pp
+.Sq \e
+nullifies the special meaning of the following character,
+if it has any, notably
+.Sq \e
+and
+.Sq ^ .
+.It Ic echotc Oo Fl sv Oc Ar arg Ar ...
+Exercise terminal capabilities given in
+.Ar arg ... .
+If
+.Ar arg
+is
+.Sq baud ,
+.Sq cols ,
+.Sq lines ,
+.Sq rows ,
+.Sq meta ,
+or
+.Sq tabs ,
+the value of that capability is printed, with
+.Dq yes
+or
+.Dq no
+indicating that the terminal does or does not have that capability.
+.Pp
+.Fl s
+returns an empty string for non-existent capabilities, rather than
+causing an error.
+.Fl v
+causes messages to be verbose.
+.It Ic edit Op Li on | Li off
+Enable or disable the
+.Nm editline
+functionality in a program.
+.It Ic history Ar list | Ar size Dv n | Ar unique Dv n
+The
+.Ar list
+command lists all entries in the history.
+The
+.Ar size
+command sets the history size to
+.Dv n
+entries.
+The
+.Ar unique
+command controls if history should keep duplicate entries.
+If
+.Dv n
+is non zero, only keep unique history entries.
+If
+.Dv n
+is zero, then keep all entries (the default).
+.It Ic settc Ar cap Ar val
+Set the terminal capability
+.Ar cap
+to
+.Ar val ,
+as defined in
+.Xr termcap 5 .
+No sanity checking is done.
+.It Ic setty Oo Fl a Oc Oo Fl d Oc Oo Fl q Oc Oo Fl x Oc Oo Ar +mode Oc \
+Oo Ar -mode Oc Oo Ar mode Oc Oo Ar char=c Oc
+Control which tty modes that
+.Nm
+won't allow the user to change.
+.Fl d ,
+.Fl q
+or
+.Fl x
+tells
+.Ic setty
+to act on the
+.Sq edit ,
+.Sq quote
+or
+.Sq execute
+set of tty modes respectively; defaulting to
+.Fl x .
+.Pp
+Without other arguments,
+.Ic setty
+lists the modes in the chosen set which are fixed on
+.Po
+.Sq +mode
+.Pc
+or off
+.Po
+.Sq -mode
+.Pc .
+.Fl a
+lists all tty modes in the chosen set regardless of the setting.
+With
+.Ar +mode ,
+.Ar -mode
+or
+.Ar mode ,
+fixes
+.Ar mode
+on or off or removes control of
+.Ar mode
+in the chosen set.
+.Pp
+.Ic Setty
+can also be used to set tty characters to particular values using
+.Ar char=value .
+If
+.Ar value
+is empty
+then the character is set to
+.Dv _POSIX_VDISABLE .
+.It Ic telltc
+List the values of all the terminal capabilities (see
+.Xr termcap 5 ) .
+.El
+.Sh FILES
+.Bl -tag -width "~/.editrcXXX"
+.It Pa ~/.editrc
+User configuration file for the
+.Xr editline 3
+library.
+.El
+.Sh SEE ALSO
+.Xr editline 3 ,
+.Xr regex 3 ,
+.Xr termcap 5 ,
+.Xr editline 7
+.Sh AUTHORS
+.An -nosplit
+The
+.Nm editline
+library was written by
+.An Christos Zoulas ,
+and this manual was written by
+.An Luke Mewburn ,
+with some sections inspired by
+.Xr tcsh 1 .
diff --git a/third_party/heimdal/lib/libedit/src/el.c b/third_party/heimdal/lib/libedit/src/el.c
new file mode 100644
index 0000000..acde929
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/el.c
@@ -0,0 +1,640 @@
+/* $NetBSD: el.c,v 1.92 2016/05/22 19:44:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)el.c 8.2 (Berkeley) 1/3/94";
+#else
+__RCSID("$NetBSD: el.c,v 1.92 2016/05/22 19:44:26 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * el.c: EditLine interface functions
+ */
+#include <sys/types.h>
+#include <sys/param.h>
+#include <ctype.h>
+#include <langinfo.h>
+#include <locale.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "el.h"
+#include "parse.h"
+#include "read.h"
+
+/* el_init():
+ * Initialize editline and set default parameters.
+ */
+EditLine *
+el_init(const char *prog, FILE *fin, FILE *fout, FILE *ferr)
+{
+ return el_init_fd(prog, fin, fout, ferr, fileno(fin), fileno(fout),
+ fileno(ferr));
+}
+
+EditLine *
+el_init_fd(const char *prog, FILE *fin, FILE *fout, FILE *ferr,
+ int fdin, int fdout, int fderr)
+{
+ EditLine *el = el_malloc(sizeof(*el));
+
+ if (el == NULL)
+ return NULL;
+
+ memset(el, 0, sizeof(EditLine));
+
+ el->el_infile = fin;
+ el->el_outfile = fout;
+ el->el_errfile = ferr;
+
+ el->el_infd = fdin;
+ el->el_outfd = fdout;
+ el->el_errfd = fderr;
+
+ el->el_prog = wcsdup(ct_decode_string(prog, &el->el_scratch));
+ if (el->el_prog == NULL) {
+ el_free(el);
+ return NULL;
+ }
+
+ /*
+ * Initialize all the modules. Order is important!!!
+ */
+ el->el_flags = 0;
+ if (setlocale(LC_CTYPE, NULL) != NULL){
+ if (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)
+ el->el_flags |= CHARSET_IS_UTF8;
+ }
+
+ if (terminal_init(el) == -1) {
+ el_free(el->el_prog);
+ el_free(el);
+ return NULL;
+ }
+ (void) keymacro_init(el);
+ (void) map_init(el);
+ if (tty_init(el) == -1)
+ el->el_flags |= NO_TTY;
+ (void) ch_init(el);
+ (void) search_init(el);
+ (void) hist_init(el);
+ (void) prompt_init(el);
+ (void) sig_init(el);
+ if (read_init(el) == -1) {
+ el_end(el);
+ return NULL;
+ }
+ return el;
+}
+
+
+/* el_end():
+ * Clean up.
+ */
+void
+el_end(EditLine *el)
+{
+
+ if (el == NULL)
+ return;
+
+ el_reset(el);
+
+ terminal_end(el);
+ keymacro_end(el);
+ map_end(el);
+ if (!(el->el_flags & NO_TTY))
+ tty_end(el);
+ ch_end(el);
+ read_end(el->el_read);
+ search_end(el);
+ hist_end(el);
+ prompt_end(el);
+ sig_end(el);
+
+ el_free(el->el_prog);
+ el_free(el->el_visual.cbuff);
+ el_free(el->el_visual.wbuff);
+ el_free(el->el_scratch.cbuff);
+ el_free(el->el_scratch.wbuff);
+ el_free(el->el_lgcyconv.cbuff);
+ el_free(el->el_lgcyconv.wbuff);
+ el_free(el);
+}
+
+
+/* el_reset():
+ * Reset the tty and the parser
+ */
+void
+el_reset(EditLine *el)
+{
+
+ tty_cookedmode(el);
+ ch_reset(el); /* XXX: Do we want that? */
+}
+
+
+/* el_set():
+ * set the editline parameters
+ */
+int
+el_wset(EditLine *el, int op, ...)
+{
+ va_list ap;
+ int rv = 0;
+
+ if (el == NULL)
+ return -1;
+ va_start(ap, op);
+
+ switch (op) {
+ case EL_PROMPT:
+ case EL_RPROMPT: {
+ el_pfunc_t p = va_arg(ap, el_pfunc_t);
+
+ rv = prompt_set(el, p, 0, op, 1);
+ break;
+ }
+
+ case EL_RESIZE: {
+ el_zfunc_t p = va_arg(ap, el_zfunc_t);
+ void *arg = va_arg(ap, void *);
+ rv = ch_resizefun(el, p, arg);
+ break;
+ }
+
+ case EL_ALIAS_TEXT: {
+ el_afunc_t p = va_arg(ap, el_afunc_t);
+ void *arg = va_arg(ap, void *);
+ rv = ch_aliasfun(el, p, arg);
+ break;
+ }
+
+ case EL_PROMPT_ESC:
+ case EL_RPROMPT_ESC: {
+ el_pfunc_t p = va_arg(ap, el_pfunc_t);
+ int c = va_arg(ap, int);
+
+ rv = prompt_set(el, p, (wchar_t)c, op, 1);
+ break;
+ }
+
+ case EL_TERMINAL:
+ rv = terminal_set(el, va_arg(ap, char *));
+ break;
+
+ case EL_EDITOR:
+ rv = map_set_editor(el, va_arg(ap, wchar_t *));
+ break;
+
+ case EL_SIGNAL:
+ if (va_arg(ap, int))
+ el->el_flags |= HANDLE_SIGNALS;
+ else
+ el->el_flags &= ~HANDLE_SIGNALS;
+ break;
+
+ case EL_BIND:
+ case EL_TELLTC:
+ case EL_SETTC:
+ case EL_ECHOTC:
+ case EL_SETTY:
+ {
+ const wchar_t *argv[20];
+ int i;
+
+ for (i = 1; i < (int)__arraycount(argv); i++)
+ if ((argv[i] = va_arg(ap, wchar_t *)) == NULL)
+ break;
+
+ switch (op) {
+ case EL_BIND:
+ argv[0] = L"bind";
+ rv = map_bind(el, i, argv);
+ break;
+
+ case EL_TELLTC:
+ argv[0] = L"telltc";
+ rv = terminal_telltc(el, i, argv);
+ break;
+
+ case EL_SETTC:
+ argv[0] = L"settc";
+ rv = terminal_settc(el, i, argv);
+ break;
+
+ case EL_ECHOTC:
+ argv[0] = L"echotc";
+ rv = terminal_echotc(el, i, argv);
+ break;
+
+ case EL_SETTY:
+ argv[0] = L"setty";
+ rv = tty_stty(el, i, argv);
+ break;
+
+ default:
+ rv = -1;
+ EL_ABORT((el->el_errfile, "Bad op %d\n", op));
+ break;
+ }
+ break;
+ }
+
+ case EL_ADDFN:
+ {
+ wchar_t *name = va_arg(ap, wchar_t *);
+ wchar_t *help = va_arg(ap, wchar_t *);
+ el_func_t func = va_arg(ap, el_func_t);
+
+ rv = map_addfunc(el, name, help, func);
+ break;
+ }
+
+ case EL_HIST:
+ {
+ hist_fun_t func = va_arg(ap, hist_fun_t);
+ void *ptr = va_arg(ap, void *);
+
+ rv = hist_set(el, func, ptr);
+ if (!(el->el_flags & CHARSET_IS_UTF8))
+ el->el_flags &= ~NARROW_HISTORY;
+ break;
+ }
+
+ case EL_EDITMODE:
+ if (va_arg(ap, int))
+ el->el_flags &= ~EDIT_DISABLED;
+ else
+ el->el_flags |= EDIT_DISABLED;
+ rv = 0;
+ break;
+
+ case EL_GETCFN:
+ {
+ el_rfunc_t rc = va_arg(ap, el_rfunc_t);
+ rv = el_read_setfn(el->el_read, rc);
+ break;
+ }
+
+ case EL_CLIENTDATA:
+ el->el_data = va_arg(ap, void *);
+ break;
+
+ case EL_UNBUFFERED:
+ rv = va_arg(ap, int);
+ if (rv && !(el->el_flags & UNBUFFERED)) {
+ el->el_flags |= UNBUFFERED;
+ read_prepare(el);
+ } else if (!rv && (el->el_flags & UNBUFFERED)) {
+ el->el_flags &= ~UNBUFFERED;
+ read_finish(el);
+ }
+ rv = 0;
+ break;
+
+ case EL_PREP_TERM:
+ rv = va_arg(ap, int);
+ if (rv)
+ (void) tty_rawmode(el);
+ else
+ (void) tty_cookedmode(el);
+ rv = 0;
+ break;
+
+ case EL_SETFP:
+ {
+ FILE *fp;
+ int what;
+
+ what = va_arg(ap, int);
+ fp = va_arg(ap, FILE *);
+
+ rv = 0;
+ switch (what) {
+ case 0:
+ el->el_infile = fp;
+ el->el_infd = fileno(fp);
+ break;
+ case 1:
+ el->el_outfile = fp;
+ el->el_outfd = fileno(fp);
+ break;
+ case 2:
+ el->el_errfile = fp;
+ el->el_errfd = fileno(fp);
+ break;
+ default:
+ rv = -1;
+ break;
+ }
+ break;
+ }
+
+ case EL_REFRESH:
+ re_clear_display(el);
+ re_refresh(el);
+ terminal__flush(el);
+ break;
+
+ default:
+ rv = -1;
+ break;
+ }
+
+ va_end(ap);
+ return rv;
+}
+
+
+/* el_get():
+ * retrieve the editline parameters
+ */
+int
+el_wget(EditLine *el, int op, ...)
+{
+ va_list ap;
+ int rv;
+
+ if (el == NULL)
+ return -1;
+
+ va_start(ap, op);
+
+ switch (op) {
+ case EL_PROMPT:
+ case EL_RPROMPT: {
+ el_pfunc_t *p = va_arg(ap, el_pfunc_t *);
+ rv = prompt_get(el, p, 0, op);
+ break;
+ }
+ case EL_PROMPT_ESC:
+ case EL_RPROMPT_ESC: {
+ el_pfunc_t *p = va_arg(ap, el_pfunc_t *);
+ wchar_t *c = va_arg(ap, wchar_t *);
+
+ rv = prompt_get(el, p, c, op);
+ break;
+ }
+
+ case EL_EDITOR:
+ rv = map_get_editor(el, va_arg(ap, const wchar_t **));
+ break;
+
+ case EL_SIGNAL:
+ *va_arg(ap, int *) = (el->el_flags & HANDLE_SIGNALS);
+ rv = 0;
+ break;
+
+ case EL_EDITMODE:
+ *va_arg(ap, int *) = !(el->el_flags & EDIT_DISABLED);
+ rv = 0;
+ break;
+
+ case EL_TERMINAL:
+ terminal_get(el, va_arg(ap, const char **));
+ rv = 0;
+ break;
+
+ case EL_GETTC:
+ {
+ static char name[] = "gettc";
+ char *argv[20];
+ int i;
+
+ for (i = 1; i < (int)__arraycount(argv); i++)
+ if ((argv[i] = va_arg(ap, char *)) == NULL)
+ break;
+
+ argv[0] = name;
+ rv = terminal_gettc(el, i, argv);
+ break;
+ }
+
+ case EL_GETCFN:
+ *va_arg(ap, el_rfunc_t *) = el_read_getfn(el->el_read);
+ rv = 0;
+ break;
+
+ case EL_CLIENTDATA:
+ *va_arg(ap, void **) = el->el_data;
+ rv = 0;
+ break;
+
+ case EL_UNBUFFERED:
+ *va_arg(ap, int *) = (el->el_flags & UNBUFFERED) != 0;
+ rv = 0;
+ break;
+
+ case EL_GETFP:
+ {
+ int what;
+ FILE **fpp;
+
+ what = va_arg(ap, int);
+ fpp = va_arg(ap, FILE **);
+ rv = 0;
+ switch (what) {
+ case 0:
+ *fpp = el->el_infile;
+ break;
+ case 1:
+ *fpp = el->el_outfile;
+ break;
+ case 2:
+ *fpp = el->el_errfile;
+ break;
+ default:
+ rv = -1;
+ break;
+ }
+ break;
+ }
+ default:
+ rv = -1;
+ break;
+ }
+ va_end(ap);
+
+ return rv;
+}
+
+
+/* el_line():
+ * Return editing info
+ */
+const LineInfoW *
+el_wline(EditLine *el)
+{
+
+ return (const LineInfoW *)(void *)&el->el_line;
+}
+
+
+/* el_source():
+ * Source a file
+ */
+int
+el_source(EditLine *el, const char *fname)
+{
+ FILE *fp;
+ size_t len;
+ ssize_t slen;
+ char *ptr;
+ char *path = NULL;
+ const wchar_t *dptr;
+ int error = 0;
+
+ fp = NULL;
+ if (fname == NULL) {
+#ifdef HAVE_ISSETUGID
+ static const char elpath[] = "/.editrc";
+ size_t plen = sizeof(elpath);
+
+ if (issetugid())
+ return -1;
+ if ((ptr = getenv("HOME")) == NULL)
+ return -1;
+ plen += strlen(ptr);
+ if ((path = el_malloc(plen * sizeof(*path))) == NULL)
+ return -1;
+ (void)snprintf(path, plen, "%s%s", ptr, elpath);
+ fname = path;
+#else
+ /*
+ * If issetugid() is missing, always return an error, in order
+ * to keep from inadvertently opening up the user to a security
+ * hole.
+ */
+ return -1;
+#endif
+ }
+ if (fp == NULL)
+ fp = fopen(fname, "r");
+ if (fp == NULL) {
+ el_free(path);
+ return -1;
+ }
+
+ ptr = NULL;
+ len = 0;
+ while ((slen = getline(&ptr, &len, fp)) != -1) {
+ if (*ptr == '\n')
+ continue; /* Empty line. */
+ if (slen > 0 && ptr[--slen] == '\n')
+ ptr[slen] = '\0';
+
+ dptr = ct_decode_string(ptr, &el->el_scratch);
+ if (!dptr)
+ continue;
+ /* loop until first non-space char or EOL */
+ while (*dptr != '\0' && iswspace(*dptr))
+ dptr++;
+ if (*dptr == '#')
+ continue; /* ignore, this is a comment line */
+ if ((error = parse_line(el, dptr)) == -1)
+ break;
+ }
+ free(ptr);
+
+ el_free(path);
+ (void) fclose(fp);
+ return error;
+}
+
+
+/* el_resize():
+ * Called from program when terminal is resized
+ */
+void
+el_resize(EditLine *el)
+{
+ int lins, cols;
+ sigset_t oset, nset;
+
+ (void) sigemptyset(&nset);
+ (void) sigaddset(&nset, SIGWINCH);
+ (void) sigprocmask(SIG_BLOCK, &nset, &oset);
+
+ /* get the correct window size */
+ if (terminal_get_size(el, &lins, &cols))
+ terminal_change_size(el, lins, cols);
+
+ (void) sigprocmask(SIG_SETMASK, &oset, NULL);
+}
+
+
+/* el_beep():
+ * Called from the program to beep
+ */
+void
+el_beep(EditLine *el)
+{
+
+ terminal_beep(el);
+}
+
+
+/* el_editmode()
+ * Set the state of EDIT_DISABLED from the `edit' command.
+ */
+libedit_private int
+/*ARGSUSED*/
+el_editmode(EditLine *el, int argc, const wchar_t **argv)
+{
+ const wchar_t *how;
+
+ if (argv == NULL || argc != 2 || argv[1] == NULL)
+ return -1;
+
+ how = argv[1];
+ if (wcscmp(how, L"on") == 0) {
+ el->el_flags &= ~EDIT_DISABLED;
+ tty_rawmode(el);
+ } else if (wcscmp(how, L"off") == 0) {
+ tty_cookedmode(el);
+ el->el_flags |= EDIT_DISABLED;
+ }
+ else {
+ (void) fprintf(el->el_errfile, "edit: Bad value `%ls'.\n",
+ how);
+ return -1;
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/libedit/src/el.h b/third_party/heimdal/lib/libedit/src/el.h
new file mode 100644
index 0000000..c281bc0
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/el.h
@@ -0,0 +1,153 @@
+/* $NetBSD: el.h,v 1.41 2016/05/24 15:00:45 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)el.h 8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * el.h: Internal structures.
+ */
+#ifndef _h_el
+#define _h_el
+/*
+ * Local defaults
+ */
+#define KSHVI
+#define VIDEFAULT
+#define ANCHOR
+
+#include "histedit.h"
+#include "chartype.h"
+
+#define EL_BUFSIZ ((size_t)1024) /* Maximum line size */
+
+#define HANDLE_SIGNALS 0x01
+#define NO_TTY 0x02
+#define EDIT_DISABLED 0x04
+#define UNBUFFERED 0x08
+#define CHARSET_IS_UTF8 0x10
+#define NARROW_HISTORY 0x40
+
+typedef unsigned char el_action_t; /* Index to command array */
+
+typedef struct coord_t { /* Position on the screen */
+ int h;
+ int v;
+} coord_t;
+
+typedef struct el_line_t {
+ wchar_t *buffer; /* Input line */
+ wchar_t *cursor; /* Cursor position */
+ wchar_t *lastchar; /* Last character */
+ const wchar_t *limit; /* Max position */
+} el_line_t;
+
+/*
+ * Editor state
+ */
+typedef struct el_state_t {
+ int inputmode; /* What mode are we in? */
+ int doingarg; /* Are we getting an argument? */
+ int argument; /* Numeric argument */
+ int metanext; /* Is the next char a meta char */
+ el_action_t lastcmd; /* Previous command */
+ el_action_t thiscmd; /* this command */
+ wchar_t thisch; /* char that generated it */
+} el_state_t;
+
+/*
+ * Until we come up with something better...
+ */
+#define el_malloc(a) malloc(a)
+#define el_realloc(a,b) realloc(a, b)
+#define el_free(a) free(a)
+
+#include "tty.h"
+#include "prompt.h"
+#include "keymacro.h"
+#include "terminal.h"
+#include "refresh.h"
+#include "chared.h"
+#include "search.h"
+#include "hist.h"
+#include "map.h"
+#include "sig.h"
+
+struct el_read_t;
+
+struct editline {
+ wchar_t *el_prog; /* the program name */
+ FILE *el_infile; /* Stdio stuff */
+ FILE *el_outfile; /* Stdio stuff */
+ FILE *el_errfile; /* Stdio stuff */
+ int el_infd; /* Input file descriptor */
+ int el_outfd; /* Output file descriptor */
+ int el_errfd; /* Error file descriptor */
+ int el_flags; /* Various flags. */
+ coord_t el_cursor; /* Cursor location */
+ wchar_t **el_display; /* Real screen image = what is there */
+ wchar_t **el_vdisplay; /* Virtual screen image = what we see */
+ void *el_data; /* Client data */
+ el_line_t el_line; /* The current line information */
+ el_state_t el_state; /* Current editor state */
+ el_terminal_t el_terminal; /* Terminal dependent stuff */
+ el_tty_t el_tty; /* Tty dependent stuff */
+ el_refresh_t el_refresh; /* Refresh stuff */
+ el_prompt_t el_prompt; /* Prompt stuff */
+ el_prompt_t el_rprompt; /* Prompt stuff */
+ el_chared_t el_chared; /* Characted editor stuff */
+ el_map_t el_map; /* Key mapping stuff */
+ el_keymacro_t el_keymacro; /* Key binding stuff */
+ el_history_t el_history; /* History stuff */
+ el_search_t el_search; /* Search stuff */
+ el_signal_t el_signal; /* Signal handling stuff */
+ struct el_read_t *el_read; /* Character reading stuff */
+ ct_buffer_t el_visual; /* Buffer for displayable str */
+ ct_buffer_t el_scratch; /* Scratch conversion buffer */
+ ct_buffer_t el_lgcyconv; /* Buffer for legacy wrappers */
+ LineInfo el_lgcylinfo; /* Legacy LineInfo buffer */
+};
+
+libedit_private int el_editmode(EditLine *, int, const wchar_t **);
+
+#ifdef DEBUG
+#define EL_ABORT(a) do { \
+ fprintf(el->el_errfile, "%s, %d: ", \
+ __FILE__, __LINE__); \
+ fprintf a; \
+ abort(); \
+ } while( /*CONSTCOND*/0);
+#else
+#define EL_ABORT(a) abort()
+#endif
+#endif /* _h_el */
diff --git a/third_party/heimdal/lib/libedit/src/eln.c b/third_party/heimdal/lib/libedit/src/eln.c
new file mode 100644
index 0000000..aa0a5b5
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/eln.c
@@ -0,0 +1,388 @@
+/* $NetBSD: eln.c,v 1.34 2016/05/09 21:37:34 christos Exp $ */
+
+/*-
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+__RCSID("$NetBSD: eln.c,v 1.34 2016/05/09 21:37:34 christos Exp $");
+#endif /* not lint && not SCCSID */
+
+#include <errno.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "el.h"
+
+int
+el_getc(EditLine *el, char *cp)
+{
+ int num_read;
+ wchar_t wc = 0;
+
+ num_read = el_wgetc(el, &wc);
+ *cp = '\0';
+ if (num_read <= 0)
+ return num_read;
+ num_read = wctob(wc);
+ if (num_read == EOF) {
+ errno = ERANGE;
+ return -1;
+ } else {
+ *cp = (char)num_read;
+ return 1;
+ }
+}
+
+
+void
+el_push(EditLine *el, const char *str)
+{
+ /* Using multibyte->wide string decoding works fine under single-byte
+ * character sets too, and Does The Right Thing. */
+ el_wpush(el, ct_decode_string(str, &el->el_lgcyconv));
+}
+
+
+const char *
+el_gets(EditLine *el, int *nread)
+{
+ const wchar_t *tmp;
+
+ tmp = el_wgets(el, nread);
+ if (tmp != NULL) {
+ int i;
+ size_t nwread = 0;
+
+ for (i = 0; i < *nread; i++)
+ nwread += ct_enc_width(tmp[i]);
+ *nread = (int)nwread;
+ }
+ return ct_encode_string(tmp, &el->el_lgcyconv);
+}
+
+
+int
+el_parse(EditLine *el, int argc, const char *argv[])
+{
+ int ret;
+ const wchar_t **wargv;
+
+ wargv = (void *)ct_decode_argv(argc, argv, &el->el_lgcyconv);
+ if (!wargv)
+ return -1;
+ ret = el_wparse(el, argc, wargv);
+ el_free(wargv);
+
+ return ret;
+}
+
+
+int
+el_set(EditLine *el, int op, ...)
+{
+ va_list ap;
+ int ret;
+
+ if (!el)
+ return -1;
+ va_start(ap, op);
+
+ switch (op) {
+ case EL_PROMPT: /* el_pfunc_t */
+ case EL_RPROMPT: {
+ el_pfunc_t p = va_arg(ap, el_pfunc_t);
+ ret = prompt_set(el, p, 0, op, 0);
+ break;
+ }
+
+ case EL_RESIZE: {
+ el_zfunc_t p = va_arg(ap, el_zfunc_t);
+ void *arg = va_arg(ap, void *);
+ ret = ch_resizefun(el, p, arg);
+ break;
+ }
+
+ case EL_ALIAS_TEXT: {
+ el_afunc_t p = va_arg(ap, el_afunc_t);
+ void *arg = va_arg(ap, void *);
+ ret = ch_aliasfun(el, p, arg);
+ break;
+ }
+
+ case EL_PROMPT_ESC:
+ case EL_RPROMPT_ESC: {
+ el_pfunc_t p = va_arg(ap, el_pfunc_t);
+ int c = va_arg(ap, int);
+
+ ret = prompt_set(el, p, c, op, 0);
+ break;
+ }
+
+ case EL_TERMINAL: /* const char * */
+ ret = el_wset(el, op, va_arg(ap, char *));
+ break;
+
+ case EL_EDITOR: /* const wchar_t * */
+ ret = el_wset(el, op, ct_decode_string(va_arg(ap, char *),
+ &el->el_lgcyconv));
+ break;
+
+ case EL_SIGNAL: /* int */
+ case EL_EDITMODE:
+ case EL_UNBUFFERED:
+ case EL_PREP_TERM:
+ ret = el_wset(el, op, va_arg(ap, int));
+ break;
+
+ case EL_BIND: /* const char * list -> const wchar_t * list */
+ case EL_TELLTC:
+ case EL_SETTC:
+ case EL_ECHOTC:
+ case EL_SETTY: {
+ const char *argv[20];
+ int i;
+ const wchar_t **wargv;
+ for (i = 1; i < (int)__arraycount(argv) - 1; ++i)
+ if ((argv[i] = va_arg(ap, const char *)) == NULL)
+ break;
+ argv[0] = argv[i] = NULL;
+ wargv = (void *)ct_decode_argv(i + 1, argv, &el->el_lgcyconv);
+ if (!wargv) {
+ ret = -1;
+ goto out;
+ }
+ /*
+ * AFAIK we can't portably pass through our new wargv to
+ * el_wset(), so we have to reimplement the body of
+ * el_wset() for these ops.
+ */
+ switch (op) {
+ case EL_BIND:
+ wargv[0] = L"bind";
+ ret = map_bind(el, i, wargv);
+ break;
+ case EL_TELLTC:
+ wargv[0] = L"telltc";
+ ret = terminal_telltc(el, i, wargv);
+ break;
+ case EL_SETTC:
+ wargv[0] = L"settc";
+ ret = terminal_settc(el, i, wargv);
+ break;
+ case EL_ECHOTC:
+ wargv[0] = L"echotc";
+ ret = terminal_echotc(el, i, wargv);
+ break;
+ case EL_SETTY:
+ wargv[0] = L"setty";
+ ret = tty_stty(el, i, wargv);
+ break;
+ default:
+ ret = -1;
+ }
+ el_free(wargv);
+ break;
+ }
+
+ /* XXX: do we need to change el_func_t too? */
+ case EL_ADDFN: { /* const char *, const char *, el_func_t */
+ const char *args[2];
+ el_func_t func;
+ wchar_t **wargv;
+
+ args[0] = va_arg(ap, const char *);
+ args[1] = va_arg(ap, const char *);
+ func = va_arg(ap, el_func_t);
+
+ wargv = ct_decode_argv(2, args, &el->el_lgcyconv);
+ if (!wargv) {
+ ret = -1;
+ goto out;
+ }
+ /* XXX: The two strdup's leak */
+ ret = map_addfunc(el, wcsdup(wargv[0]), wcsdup(wargv[1]),
+ func);
+ el_free(wargv);
+ break;
+ }
+ case EL_HIST: { /* hist_fun_t, const char * */
+ hist_fun_t fun = va_arg(ap, hist_fun_t);
+ void *ptr = va_arg(ap, void *);
+ ret = hist_set(el, fun, ptr);
+ el->el_flags |= NARROW_HISTORY;
+ break;
+ }
+
+ case EL_GETCFN: /* el_rfunc_t */
+ ret = el_wset(el, op, va_arg(ap, el_rfunc_t));
+ break;
+
+ case EL_CLIENTDATA: /* void * */
+ ret = el_wset(el, op, va_arg(ap, void *));
+ break;
+
+ case EL_SETFP: { /* int, FILE * */
+ int what = va_arg(ap, int);
+ FILE *fp = va_arg(ap, FILE *);
+ ret = el_wset(el, op, what, fp);
+ break;
+ }
+
+ case EL_REFRESH:
+ re_clear_display(el);
+ re_refresh(el);
+ terminal__flush(el);
+ ret = 0;
+ break;
+
+ default:
+ ret = -1;
+ break;
+ }
+
+out:
+ va_end(ap);
+ return ret;
+}
+
+
+int
+el_get(EditLine *el, int op, ...)
+{
+ va_list ap;
+ int ret;
+
+ if (!el)
+ return -1;
+
+ va_start(ap, op);
+
+ switch (op) {
+ case EL_PROMPT: /* el_pfunc_t * */
+ case EL_RPROMPT: {
+ el_pfunc_t *p = va_arg(ap, el_pfunc_t *);
+ ret = prompt_get(el, p, 0, op);
+ break;
+ }
+
+ case EL_PROMPT_ESC: /* el_pfunc_t *, char **/
+ case EL_RPROMPT_ESC: {
+ el_pfunc_t *p = va_arg(ap, el_pfunc_t *);
+ char *c = va_arg(ap, char *);
+ wchar_t wc = 0;
+ ret = prompt_get(el, p, &wc, op);
+ *c = (char)wc;
+ break;
+ }
+
+ case EL_EDITOR: {
+ const char **p = va_arg(ap, const char **);
+ const wchar_t *pw;
+ ret = el_wget(el, op, &pw);
+ *p = ct_encode_string(pw, &el->el_lgcyconv);
+ if (!el->el_lgcyconv.csize)
+ ret = -1;
+ break;
+ }
+
+ case EL_TERMINAL: /* const char ** */
+ ret = el_wget(el, op, va_arg(ap, const char **));
+ break;
+
+ case EL_SIGNAL: /* int * */
+ case EL_EDITMODE:
+ case EL_UNBUFFERED:
+ case EL_PREP_TERM:
+ ret = el_wget(el, op, va_arg(ap, int *));
+ break;
+
+ case EL_GETTC: {
+ char *argv[20];
+ static char gettc[] = "gettc";
+ int i;
+ for (i = 1; i < (int)__arraycount(argv); ++i)
+ if ((argv[i] = va_arg(ap, char *)) == NULL)
+ break;
+ argv[0] = gettc;
+ ret = terminal_gettc(el, i, argv);
+ break;
+ }
+
+ case EL_GETCFN: /* el_rfunc_t */
+ ret = el_wget(el, op, va_arg(ap, el_rfunc_t *));
+ break;
+
+ case EL_CLIENTDATA: /* void ** */
+ ret = el_wget(el, op, va_arg(ap, void **));
+ break;
+
+ case EL_GETFP: { /* int, FILE ** */
+ int what = va_arg(ap, int);
+ FILE **fpp = va_arg(ap, FILE **);
+ ret = el_wget(el, op, what, fpp);
+ break;
+ }
+
+ default:
+ ret = -1;
+ break;
+ }
+
+ va_end(ap);
+ return ret;
+}
+
+
+const LineInfo *
+el_line(EditLine *el)
+{
+ const LineInfoW *winfo = el_wline(el);
+ LineInfo *info = &el->el_lgcylinfo;
+ size_t offset;
+ const wchar_t *p;
+
+ info->buffer = ct_encode_string(winfo->buffer, &el->el_lgcyconv);
+
+ offset = 0;
+ for (p = winfo->buffer; p < winfo->cursor; p++)
+ offset += ct_enc_width(*p);
+ info->cursor = info->buffer + offset;
+
+ offset = 0;
+ for (p = winfo->buffer; p < winfo->lastchar; p++)
+ offset += ct_enc_width(*p);
+ info->lastchar = info->buffer + offset;
+
+ return info;
+}
+
+
+int
+el_insertstr(EditLine *el, const char *str)
+{
+ return el_winsertstr(el, ct_decode_string(str, &el->el_lgcyconv));
+}
diff --git a/third_party/heimdal/lib/libedit/src/emacs.c b/third_party/heimdal/lib/libedit/src/emacs.c
new file mode 100644
index 0000000..0636c28
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/emacs.c
@@ -0,0 +1,512 @@
+/* $NetBSD: emacs.c,v 1.36 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)emacs.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: emacs.c,v 1.36 2016/05/09 21:46:56 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * emacs.c: Emacs functions
+ */
+#include <ctype.h>
+
+#include "el.h"
+#include "emacs.h"
+#include "fcns.h"
+
+/* em_delete_or_list():
+ * Delete character under cursor or list completions if at end of line
+ * [^D]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_delete_or_list(EditLine *el, wint_t c)
+{
+
+ if (el->el_line.cursor == el->el_line.lastchar) {
+ /* if I'm at the end */
+ if (el->el_line.cursor == el->el_line.buffer) {
+ /* and the beginning */
+ terminal_writec(el, c); /* then do an EOF */
+ return CC_EOF;
+ } else {
+ /*
+ * Here we could list completions, but it is an
+ * error right now
+ */
+ terminal_beep(el);
+ return CC_ERROR;
+ }
+ } else {
+ if (el->el_state.doingarg)
+ c_delafter(el, el->el_state.argument);
+ else
+ c_delafter1(el);
+ if (el->el_line.cursor > el->el_line.lastchar)
+ el->el_line.cursor = el->el_line.lastchar;
+ /* bounds check */
+ return CC_REFRESH;
+ }
+}
+
+
+/* em_delete_next_word():
+ * Cut from cursor to end of current word
+ * [M-d]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_delete_next_word(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *cp, *p, *kp;
+
+ if (el->el_line.cursor == el->el_line.lastchar)
+ return CC_ERROR;
+
+ cp = c__next_word(el->el_line.cursor, el->el_line.lastchar,
+ el->el_state.argument, ce__isword);
+
+ for (p = el->el_line.cursor, kp = el->el_chared.c_kill.buf; p < cp; p++)
+ /* save the text */
+ *kp++ = *p;
+ el->el_chared.c_kill.last = kp;
+
+ c_delafter(el, (int)(cp - el->el_line.cursor)); /* delete after dot */
+ if (el->el_line.cursor > el->el_line.lastchar)
+ el->el_line.cursor = el->el_line.lastchar;
+ /* bounds check */
+ return CC_REFRESH;
+}
+
+
+/* em_yank():
+ * Paste cut buffer at cursor position
+ * [^Y]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_yank(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *kp, *cp;
+
+ if (el->el_chared.c_kill.last == el->el_chared.c_kill.buf)
+ return CC_NORM;
+
+ if (el->el_line.lastchar +
+ (el->el_chared.c_kill.last - el->el_chared.c_kill.buf) >=
+ el->el_line.limit)
+ return CC_ERROR;
+
+ el->el_chared.c_kill.mark = el->el_line.cursor;
+ cp = el->el_line.cursor;
+
+ /* open the space, */
+ c_insert(el,
+ (int)(el->el_chared.c_kill.last - el->el_chared.c_kill.buf));
+ /* copy the chars */
+ for (kp = el->el_chared.c_kill.buf; kp < el->el_chared.c_kill.last; kp++)
+ *cp++ = *kp;
+
+ /* if an arg, cursor at beginning else cursor at end */
+ if (el->el_state.argument == 1)
+ el->el_line.cursor = cp;
+
+ return CC_REFRESH;
+}
+
+
+/* em_kill_line():
+ * Cut the entire line and save in cut buffer
+ * [^U]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_kill_line(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *kp, *cp;
+
+ cp = el->el_line.buffer;
+ kp = el->el_chared.c_kill.buf;
+ while (cp < el->el_line.lastchar)
+ *kp++ = *cp++; /* copy it */
+ el->el_chared.c_kill.last = kp;
+ /* zap! -- delete all of it */
+ el->el_line.lastchar = el->el_line.buffer;
+ el->el_line.cursor = el->el_line.buffer;
+ return CC_REFRESH;
+}
+
+
+/* em_kill_region():
+ * Cut area between mark and cursor and save in cut buffer
+ * [^W]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_kill_region(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *kp, *cp;
+
+ if (!el->el_chared.c_kill.mark)
+ return CC_ERROR;
+
+ if (el->el_chared.c_kill.mark > el->el_line.cursor) {
+ cp = el->el_line.cursor;
+ kp = el->el_chared.c_kill.buf;
+ while (cp < el->el_chared.c_kill.mark)
+ *kp++ = *cp++; /* copy it */
+ el->el_chared.c_kill.last = kp;
+ c_delafter(el, (int)(cp - el->el_line.cursor));
+ } else { /* mark is before cursor */
+ cp = el->el_chared.c_kill.mark;
+ kp = el->el_chared.c_kill.buf;
+ while (cp < el->el_line.cursor)
+ *kp++ = *cp++; /* copy it */
+ el->el_chared.c_kill.last = kp;
+ c_delbefore(el, (int)(cp - el->el_chared.c_kill.mark));
+ el->el_line.cursor = el->el_chared.c_kill.mark;
+ }
+ return CC_REFRESH;
+}
+
+
+/* em_copy_region():
+ * Copy area between mark and cursor to cut buffer
+ * [M-W]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_copy_region(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *kp, *cp;
+
+ if (!el->el_chared.c_kill.mark)
+ return CC_ERROR;
+
+ if (el->el_chared.c_kill.mark > el->el_line.cursor) {
+ cp = el->el_line.cursor;
+ kp = el->el_chared.c_kill.buf;
+ while (cp < el->el_chared.c_kill.mark)
+ *kp++ = *cp++; /* copy it */
+ el->el_chared.c_kill.last = kp;
+ } else {
+ cp = el->el_chared.c_kill.mark;
+ kp = el->el_chared.c_kill.buf;
+ while (cp < el->el_line.cursor)
+ *kp++ = *cp++; /* copy it */
+ el->el_chared.c_kill.last = kp;
+ }
+ return CC_NORM;
+}
+
+
+/* em_gosmacs_transpose():
+ * Exchange the two characters before the cursor
+ * Gosling emacs transpose chars [^T]
+ */
+libedit_private el_action_t
+em_gosmacs_transpose(EditLine *el, wint_t c)
+{
+
+ if (el->el_line.cursor > &el->el_line.buffer[1]) {
+ /* must have at least two chars entered */
+ c = el->el_line.cursor[-2];
+ el->el_line.cursor[-2] = el->el_line.cursor[-1];
+ el->el_line.cursor[-1] = c;
+ return CC_REFRESH;
+ } else
+ return CC_ERROR;
+}
+
+
+/* em_next_word():
+ * Move next to end of current word
+ * [M-f]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_next_word(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ if (el->el_line.cursor == el->el_line.lastchar)
+ return CC_ERROR;
+
+ el->el_line.cursor = c__next_word(el->el_line.cursor,
+ el->el_line.lastchar,
+ el->el_state.argument,
+ ce__isword);
+
+ if (el->el_map.type == MAP_VI)
+ if (el->el_chared.c_vcmd.action != NOP) {
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+ return CC_CURSOR;
+}
+
+
+/* em_upper_case():
+ * Uppercase the characters from cursor to end of current word
+ * [M-u]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_upper_case(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *cp, *ep;
+
+ ep = c__next_word(el->el_line.cursor, el->el_line.lastchar,
+ el->el_state.argument, ce__isword);
+
+ for (cp = el->el_line.cursor; cp < ep; cp++)
+ if (iswlower(*cp))
+ *cp = towupper(*cp);
+
+ el->el_line.cursor = ep;
+ if (el->el_line.cursor > el->el_line.lastchar)
+ el->el_line.cursor = el->el_line.lastchar;
+ return CC_REFRESH;
+}
+
+
+/* em_capitol_case():
+ * Capitalize the characters from cursor to end of current word
+ * [M-c]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_capitol_case(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *cp, *ep;
+
+ ep = c__next_word(el->el_line.cursor, el->el_line.lastchar,
+ el->el_state.argument, ce__isword);
+
+ for (cp = el->el_line.cursor; cp < ep; cp++) {
+ if (iswalpha(*cp)) {
+ if (iswlower(*cp))
+ *cp = towupper(*cp);
+ cp++;
+ break;
+ }
+ }
+ for (; cp < ep; cp++)
+ if (iswupper(*cp))
+ *cp = towlower(*cp);
+
+ el->el_line.cursor = ep;
+ if (el->el_line.cursor > el->el_line.lastchar)
+ el->el_line.cursor = el->el_line.lastchar;
+ return CC_REFRESH;
+}
+
+
+/* em_lower_case():
+ * Lowercase the characters from cursor to end of current word
+ * [M-l]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_lower_case(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *cp, *ep;
+
+ ep = c__next_word(el->el_line.cursor, el->el_line.lastchar,
+ el->el_state.argument, ce__isword);
+
+ for (cp = el->el_line.cursor; cp < ep; cp++)
+ if (iswupper(*cp))
+ *cp = towlower(*cp);
+
+ el->el_line.cursor = ep;
+ if (el->el_line.cursor > el->el_line.lastchar)
+ el->el_line.cursor = el->el_line.lastchar;
+ return CC_REFRESH;
+}
+
+
+/* em_set_mark():
+ * Set the mark at cursor
+ * [^@]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_set_mark(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ el->el_chared.c_kill.mark = el->el_line.cursor;
+ return CC_NORM;
+}
+
+
+/* em_exchange_mark():
+ * Exchange the cursor and mark
+ * [^X^X]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_exchange_mark(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *cp;
+
+ cp = el->el_line.cursor;
+ el->el_line.cursor = el->el_chared.c_kill.mark;
+ el->el_chared.c_kill.mark = cp;
+ return CC_CURSOR;
+}
+
+
+/* em_universal_argument():
+ * Universal argument (argument times 4)
+ * [^U]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_universal_argument(EditLine *el, wint_t c __attribute__((__unused__)))
+{ /* multiply current argument by 4 */
+
+ if (el->el_state.argument > 1000000)
+ return CC_ERROR;
+ el->el_state.doingarg = 1;
+ el->el_state.argument *= 4;
+ return CC_ARGHACK;
+}
+
+
+/* em_meta_next():
+ * Add 8th bit to next character typed
+ * [<ESC>]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_meta_next(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ el->el_state.metanext = 1;
+ return CC_ARGHACK;
+}
+
+
+/* em_toggle_overwrite():
+ * Switch from insert to overwrite mode or vice versa
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_toggle_overwrite(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ el->el_state.inputmode = (el->el_state.inputmode == MODE_INSERT) ?
+ MODE_REPLACE : MODE_INSERT;
+ return CC_NORM;
+}
+
+
+/* em_copy_prev_word():
+ * Copy current word to cursor
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_copy_prev_word(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *cp, *oldc, *dp;
+
+ if (el->el_line.cursor == el->el_line.buffer)
+ return CC_ERROR;
+
+ oldc = el->el_line.cursor;
+ /* does a bounds check */
+ cp = c__prev_word(el->el_line.cursor, el->el_line.buffer,
+ el->el_state.argument, ce__isword);
+
+ c_insert(el, (int)(oldc - cp));
+ for (dp = oldc; cp < oldc && dp < el->el_line.lastchar; cp++)
+ *dp++ = *cp;
+
+ el->el_line.cursor = dp;/* put cursor at end */
+
+ return CC_REFRESH;
+}
+
+
+/* em_inc_search_next():
+ * Emacs incremental next search
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_inc_search_next(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ el->el_search.patlen = 0;
+ return ce_inc_search(el, ED_SEARCH_NEXT_HISTORY);
+}
+
+
+/* em_inc_search_prev():
+ * Emacs incremental reverse search
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_inc_search_prev(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ el->el_search.patlen = 0;
+ return ce_inc_search(el, ED_SEARCH_PREV_HISTORY);
+}
+
+
+/* em_delete_prev_char():
+ * Delete the character to the left of the cursor
+ * [^?]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+em_delete_prev_char(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ if (el->el_line.cursor <= el->el_line.buffer)
+ return CC_ERROR;
+
+ if (el->el_state.doingarg)
+ c_delbefore(el, el->el_state.argument);
+ else
+ c_delbefore1(el);
+ el->el_line.cursor -= el->el_state.argument;
+ if (el->el_line.cursor < el->el_line.buffer)
+ el->el_line.cursor = el->el_line.buffer;
+ return CC_REFRESH;
+}
diff --git a/third_party/heimdal/lib/libedit/src/filecomplete.c b/third_party/heimdal/lib/libedit/src/filecomplete.c
new file mode 100644
index 0000000..d1051f0
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/filecomplete.c
@@ -0,0 +1,573 @@
+/* $NetBSD: filecomplete.c,v 1.44 2016/10/31 17:46:32 abhinav Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jaromir Dolecek.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+__RCSID("$NetBSD: filecomplete.c,v 1.44 2016/10/31 17:46:32 abhinav Exp $");
+#endif /* not lint && not SCCSID */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <pwd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "el.h"
+#include "filecomplete.h"
+
+static const wchar_t break_chars[] = L" \t\n\"\\'`@$><=;|&{(";
+
+/********************************/
+/* completion functions */
+
+/*
+ * does tilde expansion of strings of type ``~user/foo''
+ * if ``user'' isn't valid user name or ``txt'' doesn't start
+ * w/ '~', returns pointer to strdup()ed copy of ``txt''
+ *
+ * it's the caller's responsibility to free() the returned string
+ */
+char *
+fn_tilde_expand(const char *txt)
+{
+#if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
+ struct passwd pwres;
+ char pwbuf[1024];
+#endif
+ struct passwd *pass;
+ char *temp;
+ size_t len = 0;
+
+ if (txt[0] != '~')
+ return strdup(txt);
+
+ temp = strchr(txt + 1, '/');
+ if (temp == NULL) {
+ temp = strdup(txt + 1);
+ if (temp == NULL)
+ return NULL;
+ } else {
+ /* text until string after slash */
+ len = (size_t)(temp - txt + 1);
+ temp = el_malloc(len * sizeof(*temp));
+ if (temp == NULL)
+ return NULL;
+ (void)strncpy(temp, txt + 1, len - 2);
+ temp[len - 2] = '\0';
+ }
+ if (temp[0] == 0) {
+#ifdef HAVE_GETPW_R_POSIX
+ if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf),
+ &pass) != 0)
+ pass = NULL;
+#elif HAVE_GETPW_R_DRAFT
+ pass = getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf));
+#else
+ pass = getpwuid(getuid());
+#endif
+ } else {
+#ifdef HAVE_GETPW_R_POSIX
+ if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
+ pass = NULL;
+#elif HAVE_GETPW_R_DRAFT
+ pass = getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf));
+#else
+ pass = getpwnam(temp);
+#endif
+ }
+ el_free(temp); /* value no more needed */
+ if (pass == NULL)
+ return strdup(txt);
+
+ /* update pointer txt to point at string immedially following */
+ /* first slash */
+ txt += len;
+
+ len = strlen(pass->pw_dir) + 1 + strlen(txt) + 1;
+ temp = el_malloc(len * sizeof(*temp));
+ if (temp == NULL)
+ return NULL;
+ (void)snprintf(temp, len, "%s/%s", pass->pw_dir, txt);
+
+ return temp;
+}
+
+
+/*
+ * return first found file name starting by the ``text'' or NULL if no
+ * such file can be found
+ * value of ``state'' is ignored
+ *
+ * it's the caller's responsibility to free the returned string
+ */
+char *
+fn_filename_completion_function(const char *text, int state)
+{
+ static DIR *dir = NULL;
+ static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
+ static size_t filename_len = 0;
+ struct dirent *entry;
+ char *temp;
+ size_t len;
+
+ if (state == 0 || dir == NULL) {
+ temp = strrchr(text, '/');
+ if (temp) {
+ char *nptr;
+ temp++;
+ nptr = el_realloc(filename, (strlen(temp) + 1) *
+ sizeof(*nptr));
+ if (nptr == NULL) {
+ el_free(filename);
+ filename = NULL;
+ return NULL;
+ }
+ filename = nptr;
+ (void)strcpy(filename, temp);
+ len = (size_t)(temp - text); /* including last slash */
+
+ nptr = el_realloc(dirname, (len + 1) *
+ sizeof(*nptr));
+ if (nptr == NULL) {
+ el_free(dirname);
+ dirname = NULL;
+ return NULL;
+ }
+ dirname = nptr;
+ (void)strncpy(dirname, text, len);
+ dirname[len] = '\0';
+ } else {
+ el_free(filename);
+ if (*text == 0)
+ filename = NULL;
+ else {
+ filename = strdup(text);
+ if (filename == NULL)
+ return NULL;
+ }
+ el_free(dirname);
+ dirname = NULL;
+ }
+
+ if (dir != NULL) {
+ (void)closedir(dir);
+ dir = NULL;
+ }
+
+ /* support for ``~user'' syntax */
+
+ el_free(dirpath);
+ dirpath = NULL;
+ if (dirname == NULL) {
+ if ((dirname = strdup("")) == NULL)
+ return NULL;
+ dirpath = strdup("./");
+ } else if (*dirname == '~')
+ dirpath = fn_tilde_expand(dirname);
+ else
+ dirpath = strdup(dirname);
+
+ if (dirpath == NULL)
+ return NULL;
+
+ dir = opendir(dirpath);
+ if (!dir)
+ return NULL; /* cannot open the directory */
+
+ /* will be used in cycle */
+ filename_len = filename ? strlen(filename) : 0;
+ }
+
+ /* find the match */
+ while ((entry = readdir(dir)) != NULL) {
+ /* skip . and .. */
+ if (entry->d_name[0] == '.' && (!entry->d_name[1]
+ || (entry->d_name[1] == '.' && !entry->d_name[2])))
+ continue;
+ if (filename_len == 0)
+ break;
+ /* otherwise, get first entry where first */
+ /* filename_len characters are equal */
+ if (entry->d_name[0] == filename[0]
+#if HAVE_STRUCT_DIRENT_D_NAMLEN
+ && entry->d_namlen >= filename_len
+#else
+ && strlen(entry->d_name) >= filename_len
+#endif
+ && strncmp(entry->d_name, filename,
+ filename_len) == 0)
+ break;
+ }
+
+ if (entry) { /* match found */
+
+#if HAVE_STRUCT_DIRENT_D_NAMLEN
+ len = entry->d_namlen;
+#else
+ len = strlen(entry->d_name);
+#endif
+
+ len = strlen(dirname) + len + 1;
+ temp = el_malloc(len * sizeof(*temp));
+ if (temp == NULL)
+ return NULL;
+ (void)snprintf(temp, len, "%s%s", dirname, entry->d_name);
+ } else {
+ (void)closedir(dir);
+ dir = NULL;
+ temp = NULL;
+ }
+
+ return temp;
+}
+
+
+static const char *
+append_char_function(const char *name)
+{
+ struct stat stbuf;
+ char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
+ const char *rs = " ";
+
+ if (stat(expname ? expname : name, &stbuf) == -1)
+ goto out;
+ if (S_ISDIR(stbuf.st_mode))
+ rs = "/";
+out:
+ if (expname)
+ el_free(expname);
+ return rs;
+}
+/*
+ * returns list of completions for text given
+ * non-static for readline.
+ */
+char ** completion_matches(const char *, char *(*)(const char *, int));
+char **
+completion_matches(const char *text, char *(*genfunc)(const char *, int))
+{
+ char **match_list = NULL, *retstr, *prevstr;
+ size_t match_list_len, max_equal, which, i;
+ size_t matches;
+
+ matches = 0;
+ match_list_len = 1;
+ while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
+ /* allow for list terminator here */
+ if (matches + 3 >= match_list_len) {
+ char **nmatch_list;
+ while (matches + 3 >= match_list_len)
+ match_list_len <<= 1;
+ nmatch_list = el_realloc(match_list,
+ match_list_len * sizeof(*nmatch_list));
+ if (nmatch_list == NULL) {
+ el_free(match_list);
+ return NULL;
+ }
+ match_list = nmatch_list;
+
+ }
+ match_list[++matches] = retstr;
+ }
+
+ if (!match_list)
+ return NULL; /* nothing found */
+
+ /* find least denominator and insert it to match_list[0] */
+ which = 2;
+ prevstr = match_list[1];
+ max_equal = strlen(prevstr);
+ for (; which <= matches; which++) {
+ for (i = 0; i < max_equal &&
+ prevstr[i] == match_list[which][i]; i++)
+ continue;
+ max_equal = i;
+ }
+
+ retstr = el_malloc((max_equal + 1) * sizeof(*retstr));
+ if (retstr == NULL) {
+ el_free(match_list);
+ return NULL;
+ }
+ (void)strncpy(retstr, match_list[1], max_equal);
+ retstr[max_equal] = '\0';
+ match_list[0] = retstr;
+
+ /* add NULL as last pointer to the array */
+ match_list[matches + 1] = NULL;
+
+ return match_list;
+}
+
+/*
+ * Sort function for qsort(). Just wrapper around strcasecmp().
+ */
+static int
+_fn_qsort_string_compare(const void *i1, const void *i2)
+{
+ const char *s1 = ((const char * const *)i1)[0];
+ const char *s2 = ((const char * const *)i2)[0];
+
+ return strcasecmp(s1, s2);
+}
+
+/*
+ * Display list of strings in columnar format on readline's output stream.
+ * 'matches' is list of strings, 'num' is number of strings in 'matches',
+ * 'width' is maximum length of string in 'matches'.
+ *
+ * matches[0] is not one of the match strings, but it is counted in
+ * num, so the strings are matches[1] *through* matches[num-1].
+ */
+void
+fn_display_match_list (EditLine *el, char **matches, size_t num, size_t width)
+{
+ size_t line, lines, col, cols, thisguy;
+ int screenwidth = el->el_terminal.t_size.h;
+
+ /* Ignore matches[0]. Avoid 1-based array logic below. */
+ matches++;
+ num--;
+
+ /*
+ * Find out how many entries can be put on one line; count
+ * with one space between strings the same way it's printed.
+ */
+ cols = (size_t)screenwidth / (width + 1);
+ if (cols == 0)
+ cols = 1;
+
+ /* how many lines of output, rounded up */
+ lines = (num + cols - 1) / cols;
+
+ /* Sort the items. */
+ qsort(matches, num, sizeof(char *), _fn_qsort_string_compare);
+
+ /*
+ * On the ith line print elements i, i+lines, i+lines*2, etc.
+ */
+ for (line = 0; line < lines; line++) {
+ for (col = 0; col < cols; col++) {
+ thisguy = line + col * lines;
+ if (thisguy >= num)
+ break;
+ (void)fprintf(el->el_outfile, "%s%-*s",
+ col == 0 ? "" : " ", (int)width, matches[thisguy]);
+ }
+ (void)fprintf(el->el_outfile, "\n");
+ }
+}
+
+/*
+ * Complete the word at or before point,
+ * 'what_to_do' says what to do with the completion.
+ * \t means do standard completion.
+ * `?' means list the possible completions.
+ * `*' means insert all of the possible completions.
+ * `!' means to do standard completion, and list all possible completions if
+ * there is more than one.
+ *
+ * Note: '*' support is not implemented
+ * '!' could never be invoked
+ */
+int
+fn_complete(EditLine *el,
+ char *(*complet_func)(const char *, int),
+ char **(*attempted_completion_function)(const char *, int, int),
+ const wchar_t *word_break, const wchar_t *special_prefixes,
+ const char *(*app_func)(const char *), size_t query_items,
+ int *completion_type, int *over, int *point, int *end)
+{
+ const LineInfoW *li;
+ wchar_t *temp;
+ char **matches;
+ const wchar_t *ctemp;
+ size_t len;
+ int what_to_do = '\t';
+ int retval = CC_NORM;
+
+ if (el->el_state.lastcmd == el->el_state.thiscmd)
+ what_to_do = '?';
+
+ /* readline's rl_complete() has to be told what we did... */
+ if (completion_type != NULL)
+ *completion_type = what_to_do;
+
+ if (!complet_func)
+ complet_func = fn_filename_completion_function;
+ if (!app_func)
+ app_func = append_char_function;
+
+ /* We now look backwards for the start of a filename/variable word */
+ li = el_wline(el);
+ ctemp = li->cursor;
+ while (ctemp > li->buffer
+ && !wcschr(word_break, ctemp[-1])
+ && (!special_prefixes || !wcschr(special_prefixes, ctemp[-1]) ) )
+ ctemp--;
+
+ len = (size_t)(li->cursor - ctemp);
+ temp = el_malloc((len + 1) * sizeof(*temp));
+ (void)wcsncpy(temp, ctemp, len);
+ temp[len] = '\0';
+
+ /* these can be used by function called in completion_matches() */
+ /* or (*attempted_completion_function)() */
+ if (point != NULL)
+ *point = (int)(li->cursor - li->buffer);
+ if (end != NULL)
+ *end = (int)(li->lastchar - li->buffer);
+
+ if (attempted_completion_function) {
+ int cur_off = (int)(li->cursor - li->buffer);
+ matches = (*attempted_completion_function)(
+ ct_encode_string(temp, &el->el_scratch),
+ cur_off - (int)len, cur_off);
+ } else
+ matches = NULL;
+ if (!attempted_completion_function ||
+ (over != NULL && !*over && !matches))
+ matches = completion_matches(
+ ct_encode_string(temp, &el->el_scratch), complet_func);
+
+ if (over != NULL)
+ *over = 0;
+
+ if (matches) {
+ int i;
+ size_t matches_num, maxlen, match_len, match_display=1;
+
+ retval = CC_REFRESH;
+ /*
+ * Only replace the completed string with common part of
+ * possible matches if there is possible completion.
+ */
+ if (matches[0][0] != '\0') {
+ el_deletestr(el, (int) len);
+ el_winsertstr(el,
+ ct_decode_string(matches[0], &el->el_scratch));
+ }
+
+
+ if (matches[2] == NULL &&
+ (matches[1] == NULL || strcmp(matches[0], matches[1]) == 0)) {
+ /*
+ * We found exact match. Add a space after
+ * it, unless we do filename completion and the
+ * object is a directory.
+ */
+ el_winsertstr(el,
+ ct_decode_string((*app_func)(matches[0]),
+ &el->el_scratch));
+ } else if (what_to_do == '!' || what_to_do == '?') {
+ /*
+ * More than one match and requested to list possible
+ * matches.
+ */
+
+ for(i = 1, maxlen = 0; matches[i]; i++) {
+ match_len = strlen(matches[i]);
+ if (match_len > maxlen)
+ maxlen = match_len;
+ }
+ /* matches[1] through matches[i-1] are available */
+ matches_num = (size_t)(i - 1);
+
+ /* newline to get on next line from command line */
+ (void)fprintf(el->el_outfile, "\n");
+
+ /*
+ * If there are too many items, ask user for display
+ * confirmation.
+ */
+ if (matches_num > query_items) {
+ (void)fprintf(el->el_outfile,
+ "Display all %zu possibilities? (y or n) ",
+ matches_num);
+ (void)fflush(el->el_outfile);
+ if (getc(stdin) != 'y')
+ match_display = 0;
+ (void)fprintf(el->el_outfile, "\n");
+ }
+
+ if (match_display) {
+ /*
+ * Interface of this function requires the
+ * strings be matches[1..num-1] for compat.
+ * We have matches_num strings not counting
+ * the prefix in matches[0], so we need to
+ * add 1 to matches_num for the call.
+ */
+ fn_display_match_list(el, matches,
+ matches_num+1, maxlen);
+ }
+ retval = CC_REDISPLAY;
+ } else if (matches[0][0]) {
+ /*
+ * There was some common match, but the name was
+ * not complete enough. Next tab will print possible
+ * completions.
+ */
+ el_beep(el);
+ } else {
+ /* lcd is not a valid object - further specification */
+ /* is needed */
+ el_beep(el);
+ retval = CC_NORM;
+ }
+
+ /* free elements of array and the array itself */
+ for (i = 0; matches[i]; i++)
+ el_free(matches[i]);
+ el_free(matches);
+ matches = NULL;
+ }
+ el_free(temp);
+ return retval;
+}
+
+/*
+ * el-compatible wrapper around rl_complete; needed for key binding
+ */
+/* ARGSUSED */
+unsigned char
+_el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
+{
+ return (unsigned char)fn_complete(el, NULL, NULL,
+ break_chars, NULL, NULL, (size_t)100,
+ NULL, NULL, NULL, NULL);
+}
diff --git a/third_party/heimdal/lib/libedit/src/filecomplete.h b/third_party/heimdal/lib/libedit/src/filecomplete.h
new file mode 100644
index 0000000..7e93b9e
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/filecomplete.h
@@ -0,0 +1,44 @@
+/* $NetBSD: filecomplete.h,v 1.10 2016/04/11 00:50:13 christos Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jaromir Dolecek.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _FILECOMPLETE_H_
+#define _FILECOMPLETE_H_
+
+int fn_complete(EditLine *,
+ char *(*)(const char *, int),
+ char **(*)(const char *, int, int),
+ const wchar_t *, const wchar_t *, const char *(*)(const char *), size_t,
+ int *, int *, int *, int *);
+
+void fn_display_match_list(EditLine *, char **, size_t, size_t);
+char *fn_tilde_expand(const char *);
+char *fn_filename_completion_function(const char *, int);
+
+#endif
diff --git a/third_party/heimdal/lib/libedit/src/getline.c b/third_party/heimdal/lib/libedit/src/getline.c
new file mode 100644
index 0000000..379bcd9
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/getline.c
@@ -0,0 +1,128 @@
+/* Implementations of the getdelim() and getline() functions from POSIX 2008,
+ just in case your libc doesn't have them.
+
+ getdelim() reads from a stream until a specified delimiter is encountered.
+ getline() reads from a stream until a newline is encountered.
+
+ See: http://pubs.opengroup.org/onlinepubs/9699919799/functions/getdelim.html
+
+ NOTE: It is always the caller's responsibility to free the line buffer, even
+ when an error occurs.
+
+ Copyright (c) 2011 James E. Ingram
+
+ 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.
+*/
+
+#include <stddef.h>
+#include <stdio.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdlib.h>
+
+#ifndef HAVE_GETLINE
+ssize_t libedit_getline(char **lineptr, size_t *n, FILE *stream);
+#endif
+
+#ifndef SSIZE_MAX
+#define SSIZE_MAX 32767
+#endif
+
+#define _GETDELIM_GROWBY 4096 /* amount to grow line buffer by */
+#define _GETDELIM_MINLEN 4 /* minimum line buffer size */
+
+static ssize_t libedit_getdelim(char **restrict lineptr, size_t *restrict n, int delimiter,
+ FILE *restrict stream)
+{
+ char *buf, *pos;
+ int c;
+ ssize_t bytes;
+
+ if (lineptr == NULL || n == NULL)
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ if (stream == NULL)
+ {
+ errno = EBADF;
+ return -1;
+ }
+
+ /* resize (or allocate) the line buffer if necessary */
+ buf = *lineptr;
+ if (buf == NULL || *n < _GETDELIM_MINLEN)
+ {
+ buf = realloc(*lineptr, _GETDELIM_GROWBY);
+ if (buf == NULL)
+ {
+ /* ENOMEM */
+ return -1;
+ }
+ *n = _GETDELIM_GROWBY;
+ *lineptr = buf;
+ }
+
+ /* read characters until delimiter is found, end of file is reached, or an
+ error occurs. */
+ bytes = 0;
+ pos = buf;
+ while ((c = getc(stream)) != EOF)
+ {
+ if (bytes + 1 >= SSIZE_MAX)
+ {
+ errno = ERANGE;
+ return -1;
+ }
+ bytes++;
+ if (bytes >= *n - 1)
+ {
+ buf = realloc(*lineptr, *n + _GETDELIM_GROWBY);
+ if (buf == NULL)
+ {
+ /* ENOMEM */
+ return -1;
+ }
+ *n += _GETDELIM_GROWBY;
+ pos = buf + bytes - 1;
+ *lineptr = buf;
+ }
+
+ *pos++ = (char) c;
+ if (c == delimiter)
+ {
+ break;
+ }
+ }
+
+ if (ferror(stream) || (feof(stream) && (bytes == 0)))
+ {
+ /* EOF, or an error from getc(). */
+ return -1;
+ }
+
+ *pos = '\0';
+ return bytes;
+}
+
+ssize_t libedit_getline(char **restrict lineptr, size_t *restrict n,
+ FILE *restrict stream)
+{
+ return libedit_getdelim(lineptr, n, '\n', stream);
+}
diff --git a/third_party/heimdal/lib/libedit/src/hist.c b/third_party/heimdal/lib/libedit/src/hist.c
new file mode 100644
index 0000000..4f01ade
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/hist.c
@@ -0,0 +1,245 @@
+/* $NetBSD: hist.c,v 1.30 2016/11/07 15:30:18 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)hist.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: hist.c,v 1.30 2016/11/07 15:30:18 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * hist.c: History access functions
+ */
+#include <stdlib.h>
+#include <string.h>
+#include <vis.h>
+
+#include "el.h"
+
+/* hist_init():
+ * Initialization function.
+ */
+libedit_private int
+hist_init(EditLine *el)
+{
+
+ el->el_history.fun = NULL;
+ el->el_history.ref = NULL;
+ el->el_history.buf = el_malloc(EL_BUFSIZ * sizeof(*el->el_history.buf));
+ el->el_history.sz = EL_BUFSIZ;
+ if (el->el_history.buf == NULL)
+ return -1;
+ el->el_history.last = el->el_history.buf;
+ return 0;
+}
+
+
+/* hist_end():
+ * clean up history;
+ */
+libedit_private void
+hist_end(EditLine *el)
+{
+
+ el_free(el->el_history.buf);
+ el->el_history.buf = NULL;
+}
+
+
+/* hist_set():
+ * Set new history interface
+ */
+libedit_private int
+hist_set(EditLine *el, hist_fun_t fun, void *ptr)
+{
+
+ el->el_history.ref = ptr;
+ el->el_history.fun = fun;
+ return 0;
+}
+
+
+/* hist_get():
+ * Get a history line and update it in the buffer.
+ * eventno tells us the event to get.
+ */
+libedit_private el_action_t
+hist_get(EditLine *el)
+{
+ const wchar_t *hp;
+ int h;
+
+ if (el->el_history.eventno == 0) { /* if really the current line */
+ (void) wcsncpy(el->el_line.buffer, el->el_history.buf,
+ el->el_history.sz);
+ el->el_line.lastchar = el->el_line.buffer +
+ (el->el_history.last - el->el_history.buf);
+
+#ifdef KSHVI
+ if (el->el_map.type == MAP_VI)
+ el->el_line.cursor = el->el_line.buffer;
+ else
+#endif /* KSHVI */
+ el->el_line.cursor = el->el_line.lastchar;
+
+ return CC_REFRESH;
+ }
+ if (el->el_history.ref == NULL)
+ return CC_ERROR;
+
+ hp = HIST_FIRST(el);
+
+ if (hp == NULL)
+ return CC_ERROR;
+
+ for (h = 1; h < el->el_history.eventno; h++)
+ if ((hp = HIST_NEXT(el)) == NULL) {
+ el->el_history.eventno = h;
+ return CC_ERROR;
+ }
+ (void) wcsncpy(el->el_line.buffer, hp,
+ (size_t)(el->el_line.limit - el->el_line.buffer));
+ el->el_line.buffer[el->el_line.limit - el->el_line.buffer - 1] = '\0';
+ el->el_line.lastchar = el->el_line.buffer + wcslen(el->el_line.buffer);
+
+ if (el->el_line.lastchar > el->el_line.buffer
+ && el->el_line.lastchar[-1] == '\n')
+ el->el_line.lastchar--;
+ if (el->el_line.lastchar > el->el_line.buffer
+ && el->el_line.lastchar[-1] == ' ')
+ el->el_line.lastchar--;
+#ifdef KSHVI
+ if (el->el_map.type == MAP_VI)
+ el->el_line.cursor = el->el_line.buffer;
+ else
+#endif /* KSHVI */
+ el->el_line.cursor = el->el_line.lastchar;
+
+ return CC_REFRESH;
+}
+
+
+/* hist_command()
+ * process a history command
+ */
+libedit_private int
+hist_command(EditLine *el, int argc, const wchar_t **argv)
+{
+ const wchar_t *str;
+ int num;
+ HistEventW ev;
+
+ if (el->el_history.ref == NULL)
+ return -1;
+
+ if (argc == 1 || wcscmp(argv[1], L"list") == 0) {
+ size_t maxlen = 0;
+ char *buf = NULL;
+ int hno = 1;
+ /* List history entries */
+
+ for (str = HIST_LAST(el); str != NULL; str = HIST_PREV(el)) {
+ char *ptr =
+ ct_encode_string(str, &el->el_scratch);
+ size_t len = strlen(ptr);
+ if (len > 0 && ptr[len - 1] == '\n')
+ ptr[--len] = '\0';
+ len = len * 4 + 1;
+ if (len >= maxlen) {
+ maxlen = len + 1024;
+ char *nbuf = el_realloc(buf, maxlen);
+ if (nbuf == NULL) {
+ el_free(buf);
+ return -1;
+ }
+ buf = nbuf;
+ }
+ strvis(buf, ptr, VIS_NL);
+ (void) fprintf(el->el_outfile, "%d\t%s\n",
+ hno++, buf);
+ }
+ el_free(buf);
+ return 0;
+ }
+
+ if (argc != 3)
+ return -1;
+
+ num = (int)wcstol(argv[2], NULL, 0);
+
+ if (wcscmp(argv[1], L"size") == 0)
+ return history_w(el->el_history.ref, &ev, H_SETSIZE, num);
+
+ if (wcscmp(argv[1], L"unique") == 0)
+ return history_w(el->el_history.ref, &ev, H_SETUNIQUE, num);
+
+ return -1;
+}
+
+/* hist_enlargebuf()
+ * Enlarge history buffer to specified value. Called from el_enlargebufs().
+ * Return 0 for failure, 1 for success.
+ */
+libedit_private int
+/*ARGSUSED*/
+hist_enlargebuf(EditLine *el, size_t oldsz, size_t newsz)
+{
+ wchar_t *newbuf;
+
+ newbuf = el_realloc(el->el_history.buf, newsz * sizeof(*newbuf));
+ if (!newbuf)
+ return 0;
+
+ (void) memset(&newbuf[oldsz], '\0', (newsz - oldsz) * sizeof(*newbuf));
+
+ el->el_history.last = newbuf +
+ (el->el_history.last - el->el_history.buf);
+ el->el_history.buf = newbuf;
+ el->el_history.sz = newsz;
+
+ return 1;
+}
+
+libedit_private wchar_t *
+hist_convert(EditLine *el, int fn, void *arg)
+{
+ HistEventW ev;
+ if ((*(el)->el_history.fun)((el)->el_history.ref, &ev, fn, arg) == -1)
+ return NULL;
+ return ct_decode_string((const char *)(const void *)ev.str,
+ &el->el_scratch);
+}
diff --git a/third_party/heimdal/lib/libedit/src/hist.h b/third_party/heimdal/lib/libedit/src/hist.h
new file mode 100644
index 0000000..c58c5bf
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/hist.h
@@ -0,0 +1,79 @@
+/* $NetBSD: hist.h,v 1.22 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)hist.h 8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * el.hist.c: History functions
+ */
+#ifndef _h_el_hist
+#define _h_el_hist
+
+typedef int (*hist_fun_t)(void *, HistEventW *, int, ...);
+
+typedef struct el_history_t {
+ wchar_t *buf; /* The history buffer */
+ size_t sz; /* Size of history buffer */
+ wchar_t *last; /* The last character */
+ int eventno; /* Event we are looking for */
+ void *ref; /* Argument for history fcns */
+ hist_fun_t fun; /* Event access */
+ HistEventW ev; /* Event cookie */
+} el_history_t;
+
+#define HIST_FUN_INTERNAL(el, fn, arg) \
+ ((((*(el)->el_history.fun) ((el)->el_history.ref, &(el)->el_history.ev, \
+ fn, arg)) == -1) ? NULL : (el)->el_history.ev.str)
+#define HIST_FUN(el, fn, arg) \
+ (((el)->el_flags & NARROW_HISTORY) ? hist_convert(el, fn, arg) : \
+ HIST_FUN_INTERNAL(el, fn, arg))
+
+#define HIST_NEXT(el) HIST_FUN(el, H_NEXT, NULL)
+#define HIST_FIRST(el) HIST_FUN(el, H_FIRST, NULL)
+#define HIST_LAST(el) HIST_FUN(el, H_LAST, NULL)
+#define HIST_PREV(el) HIST_FUN(el, H_PREV, NULL)
+#define HIST_SET(el, num) HIST_FUN(el, H_SET, num)
+#define HIST_LOAD(el, fname) HIST_FUN(el, H_LOAD fname)
+#define HIST_SAVE(el, fname) HIST_FUN(el, H_SAVE fname)
+#define HIST_SAVE_FP(el, fp) HIST_FUN(el, H_SAVE_FP fp)
+
+libedit_private int hist_init(EditLine *);
+libedit_private void hist_end(EditLine *);
+libedit_private el_action_t hist_get(EditLine *);
+libedit_private int hist_set(EditLine *, hist_fun_t, void *);
+libedit_private int hist_command(EditLine *, int, const wchar_t **);
+libedit_private int hist_enlargebuf(EditLine *, size_t, size_t);
+libedit_private wchar_t *hist_convert(EditLine *, int, void *);
+
+#endif /* _h_el_hist */
diff --git a/third_party/heimdal/lib/libedit/src/histedit.h b/third_party/heimdal/lib/libedit/src/histedit.h
new file mode 100644
index 0000000..9ea7189
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/histedit.h
@@ -0,0 +1,313 @@
+/* $NetBSD: histedit.h,v 1.56 2016/04/19 19:50:53 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)histedit.h 8.2 (Berkeley) 1/3/94
+ */
+
+/*
+ * histedit.h: Line editor and history interface.
+ */
+#ifndef _HISTEDIT_H_
+#define _HISTEDIT_H_
+
+#define LIBEDIT_MAJOR 2
+#define LIBEDIT_MINOR 11
+
+#include <sys/types.h>
+#include <stdio.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * ==== Editing ====
+ */
+
+typedef struct editline EditLine;
+
+/*
+ * For user-defined function interface
+ */
+typedef struct lineinfo {
+ const char *buffer;
+ const char *cursor;
+ const char *lastchar;
+} LineInfo;
+
+/*
+ * EditLine editor function return codes.
+ * For user-defined function interface
+ */
+#define CC_NORM 0
+#define CC_NEWLINE 1
+#define CC_EOF 2
+#define CC_ARGHACK 3
+#define CC_REFRESH 4
+#define CC_CURSOR 5
+#define CC_ERROR 6
+#define CC_FATAL 7
+#define CC_REDISPLAY 8
+#define CC_REFRESH_BEEP 9
+
+/*
+ * Initialization, cleanup, and resetting
+ */
+EditLine *el_init(const char *, FILE *, FILE *, FILE *);
+EditLine *el_init_fd(const char *, FILE *, FILE *, FILE *,
+ int, int, int);
+void el_end(EditLine *);
+void el_reset(EditLine *);
+
+/*
+ * Get a line, a character or push a string back in the input queue
+ */
+const char *el_gets(EditLine *, int *);
+int el_getc(EditLine *, char *);
+void el_push(EditLine *, const char *);
+
+/*
+ * Beep!
+ */
+void el_beep(EditLine *);
+
+/*
+ * High level function internals control
+ * Parses argc, argv array and executes builtin editline commands
+ */
+int el_parse(EditLine *, int, const char **);
+
+/*
+ * Low level editline access functions
+ */
+int el_set(EditLine *, int, ...);
+int el_get(EditLine *, int, ...);
+unsigned char _el_fn_complete(EditLine *, int);
+
+/*
+ * el_set/el_get parameters
+ *
+ * When using el_wset/el_wget (as opposed to el_set/el_get):
+ * Char is wchar_t, otherwise it is char.
+ * prompt_func is el_wpfunc_t, otherwise it is el_pfunc_t .
+
+ * Prompt function prototypes are:
+ * typedef char *(*el_pfunct_t) (EditLine *);
+ * typedef wchar_t *(*el_wpfunct_t) (EditLine *);
+ *
+ * For operations that support set or set/get, the argument types listed are for
+ * the "set" operation. For "get", each listed type must be a pointer.
+ * E.g. EL_EDITMODE takes an int when set, but an int* when get.
+ *
+ * Operations that only support "get" have the correct argument types listed.
+ */
+#define EL_PROMPT 0 /* , prompt_func); set/get */
+#define EL_TERMINAL 1 /* , const char *); set/get */
+#define EL_EDITOR 2 /* , const Char *); set/get */
+#define EL_SIGNAL 3 /* , int); set/get */
+#define EL_BIND 4 /* , const Char *, ..., NULL); set */
+#define EL_TELLTC 5 /* , const Char *, ..., NULL); set */
+#define EL_SETTC 6 /* , const Char *, ..., NULL); set */
+#define EL_ECHOTC 7 /* , const Char *, ..., NULL); set */
+#define EL_SETTY 8 /* , const Char *, ..., NULL); set */
+#define EL_ADDFN 9 /* , const Char *, const Char, set */
+ /* el_func_t); */
+#define EL_HIST 10 /* , hist_fun_t, const void *); set */
+#define EL_EDITMODE 11 /* , int); set/get */
+#define EL_RPROMPT 12 /* , prompt_func); set/get */
+#define EL_GETCFN 13 /* , el_rfunc_t); set/get */
+#define EL_CLIENTDATA 14 /* , void *); set/get */
+#define EL_UNBUFFERED 15 /* , int); set/get */
+#define EL_PREP_TERM 16 /* , int); set */
+#define EL_GETTC 17 /* , const Char *, ..., NULL); get */
+#define EL_GETFP 18 /* , int, FILE **); get */
+#define EL_SETFP 19 /* , int, FILE *); set */
+#define EL_REFRESH 20 /* , void); set */
+#define EL_PROMPT_ESC 21 /* , prompt_func, Char); set/get */
+#define EL_RPROMPT_ESC 22 /* , prompt_func, Char); set/get */
+#define EL_RESIZE 23 /* , el_zfunc_t, void *); set */
+#define EL_ALIAS_TEXT 24 /* , el_afunc_t, void *); set */
+
+#define EL_BUILTIN_GETCFN (NULL)
+
+/*
+ * Source named file or $PWD/.editrc or $HOME/.editrc
+ */
+int el_source(EditLine *, const char *);
+
+/*
+ * Must be called when the terminal changes size; If EL_SIGNAL
+ * is set this is done automatically otherwise it is the responsibility
+ * of the application
+ */
+void el_resize(EditLine *);
+
+/*
+ * User-defined function interface.
+ */
+const LineInfo *el_line(EditLine *);
+int el_insertstr(EditLine *, const char *);
+void el_deletestr(EditLine *, int);
+
+
+/*
+ * ==== History ====
+ */
+
+typedef struct history History;
+
+typedef struct HistEvent {
+ int num;
+ const char *str;
+} HistEvent;
+
+/*
+ * History access functions.
+ */
+History * history_init(void);
+void history_end(History *);
+
+int history(History *, HistEvent *, int, ...);
+
+#define H_FUNC 0 /* , UTSL */
+#define H_SETSIZE 1 /* , const int); */
+#define H_GETSIZE 2 /* , void); */
+#define H_FIRST 3 /* , void); */
+#define H_LAST 4 /* , void); */
+#define H_PREV 5 /* , void); */
+#define H_NEXT 6 /* , void); */
+#define H_CURR 8 /* , const int); */
+#define H_SET 7 /* , int); */
+#define H_ADD 9 /* , const wchar_t *); */
+#define H_ENTER 10 /* , const wchar_t *); */
+#define H_APPEND 11 /* , const wchar_t *); */
+#define H_END 12 /* , void); */
+#define H_NEXT_STR 13 /* , const wchar_t *); */
+#define H_PREV_STR 14 /* , const wchar_t *); */
+#define H_NEXT_EVENT 15 /* , const int); */
+#define H_PREV_EVENT 16 /* , const int); */
+#define H_LOAD 17 /* , const char *); */
+#define H_SAVE 18 /* , const char *); */
+#define H_CLEAR 19 /* , void); */
+#define H_SETUNIQUE 20 /* , int); */
+#define H_GETUNIQUE 21 /* , void); */
+#define H_DEL 22 /* , int); */
+#define H_NEXT_EVDATA 23 /* , const int, histdata_t *); */
+#define H_DELDATA 24 /* , int, histdata_t *);*/
+#define H_REPLACE 25 /* , const char *, histdata_t); */
+#define H_SAVE_FP 26 /* , FILE *); */
+
+
+
+/*
+ * ==== Tokenization ====
+ */
+
+typedef struct tokenizer Tokenizer;
+
+/*
+ * String tokenization functions, using simplified sh(1) quoting rules
+ */
+Tokenizer *tok_init(const char *);
+void tok_end(Tokenizer *);
+void tok_reset(Tokenizer *);
+int tok_line(Tokenizer *, const LineInfo *,
+ int *, const char ***, int *, int *);
+int tok_str(Tokenizer *, const char *,
+ int *, const char ***);
+
+/*
+ * Begin Wide Character Support
+ */
+#include <wchar.h>
+#include <wctype.h>
+
+/*
+ * ==== Editing ====
+ */
+typedef struct lineinfow {
+ const wchar_t *buffer;
+ const wchar_t *cursor;
+ const wchar_t *lastchar;
+} LineInfoW;
+
+typedef int (*el_rfunc_t)(EditLine *, wchar_t *);
+
+const wchar_t *el_wgets(EditLine *, int *);
+int el_wgetc(EditLine *, wchar_t *);
+void el_wpush(EditLine *, const wchar_t *);
+
+int el_wparse(EditLine *, int, const wchar_t **);
+
+int el_wset(EditLine *, int, ...);
+int el_wget(EditLine *, int, ...);
+
+int el_cursor(EditLine *, int);
+const LineInfoW *el_wline(EditLine *);
+int el_winsertstr(EditLine *, const wchar_t *);
+#define el_wdeletestr el_deletestr
+
+/*
+ * ==== History ====
+ */
+typedef struct histeventW {
+ int num;
+ const wchar_t *str;
+} HistEventW;
+
+typedef struct historyW HistoryW;
+
+HistoryW * history_winit(void);
+void history_wend(HistoryW *);
+
+int history_w(HistoryW *, HistEventW *, int, ...);
+
+/*
+ * ==== Tokenization ====
+ */
+typedef struct tokenizerW TokenizerW;
+
+/* Wide character tokenizer support */
+TokenizerW *tok_winit(const wchar_t *);
+void tok_wend(TokenizerW *);
+void tok_wreset(TokenizerW *);
+int tok_wline(TokenizerW *, const LineInfoW *,
+ int *, const wchar_t ***, int *, int *);
+int tok_wstr(TokenizerW *, const wchar_t *,
+ int *, const wchar_t ***);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _HISTEDIT_H_ */
diff --git a/third_party/heimdal/lib/libedit/src/history.c b/third_party/heimdal/lib/libedit/src/history.c
new file mode 100644
index 0000000..41d1014
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/history.c
@@ -0,0 +1,1157 @@
+/* $NetBSD: history.c,v 1.57 2016/04/11 18:56:31 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)history.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: history.c,v 1.57 2016/04/11 18:56:31 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * hist.c: TYPE(History) access functions
+ */
+#include <sys/stat.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <vis.h>
+
+static const char hist_cookie[] = "_HiStOrY_V2_\n";
+
+#include "histedit.h"
+
+
+#ifdef NARROWCHAR
+
+#define Char char
+#define FUN(prefix, rest) prefix ## _ ## rest
+#define FUNW(type) type
+#define TYPE(type) type
+#define STR(x) x
+
+#define Strlen(s) strlen(s)
+#define Strdup(s) strdup(s)
+#define Strcmp(d, s) strcmp(d, s)
+#define Strncmp(d, s, n) strncmp(d, s, n)
+#define Strncpy(d, s, n) strncpy(d, s, n)
+#define Strncat(d, s, n) strncat(d, s, n)
+#define ct_decode_string(s, b) (s)
+#define ct_encode_string(s, b) (s)
+
+#else
+#include "chartype.h"
+
+#define Char wchar_t
+#define FUN(prefix, rest) prefix ## _w ## rest
+#define FUNW(type) type ## _w
+#define TYPE(type) type ## W
+#define STR(x) L ## x
+
+#define Strlen(s) wcslen(s)
+#define Strdup(s) wcsdup(s)
+#define Strcmp(d, s) wcscmp(d, s)
+#define Strncmp(d, s, n) wcsncmp(d, s, n)
+#define Strncpy(d, s, n) wcsncpy(d, s, n)
+#define Strncat(d, s, n) wcsncat(d, s, n)
+
+#endif
+
+
+typedef int (*history_gfun_t)(void *, TYPE(HistEvent) *);
+typedef int (*history_efun_t)(void *, TYPE(HistEvent) *, const Char *);
+typedef void (*history_vfun_t)(void *, TYPE(HistEvent) *);
+typedef int (*history_sfun_t)(void *, TYPE(HistEvent) *, const int);
+
+struct TYPE(history) {
+ void *h_ref; /* Argument for history fcns */
+ int h_ent; /* Last entry point for history */
+ history_gfun_t h_first; /* Get the first element */
+ history_gfun_t h_next; /* Get the next element */
+ history_gfun_t h_last; /* Get the last element */
+ history_gfun_t h_prev; /* Get the previous element */
+ history_gfun_t h_curr; /* Get the current element */
+ history_sfun_t h_set; /* Set the current element */
+ history_sfun_t h_del; /* Set the given element */
+ history_vfun_t h_clear; /* Clear the history list */
+ history_efun_t h_enter; /* Add an element */
+ history_efun_t h_add; /* Append to an element */
+};
+
+#define HNEXT(h, ev) (*(h)->h_next)((h)->h_ref, ev)
+#define HFIRST(h, ev) (*(h)->h_first)((h)->h_ref, ev)
+#define HPREV(h, ev) (*(h)->h_prev)((h)->h_ref, ev)
+#define HLAST(h, ev) (*(h)->h_last)((h)->h_ref, ev)
+#define HCURR(h, ev) (*(h)->h_curr)((h)->h_ref, ev)
+#define HSET(h, ev, n) (*(h)->h_set)((h)->h_ref, ev, n)
+#define HCLEAR(h, ev) (*(h)->h_clear)((h)->h_ref, ev)
+#define HENTER(h, ev, str) (*(h)->h_enter)((h)->h_ref, ev, str)
+#define HADD(h, ev, str) (*(h)->h_add)((h)->h_ref, ev, str)
+#define HDEL(h, ev, n) (*(h)->h_del)((h)->h_ref, ev, n)
+
+#define h_strdup(a) Strdup(a)
+#define h_malloc(a) malloc(a)
+#define h_realloc(a, b) realloc((a), (b))
+#define h_free(a) free(a)
+
+typedef struct {
+ int num;
+ Char *str;
+} HistEventPrivate;
+
+
+static int history_setsize(TYPE(History) *, TYPE(HistEvent) *, int);
+static int history_getsize(TYPE(History) *, TYPE(HistEvent) *);
+static int history_setunique(TYPE(History) *, TYPE(HistEvent) *, int);
+static int history_getunique(TYPE(History) *, TYPE(HistEvent) *);
+static int history_set_fun(TYPE(History) *, TYPE(History) *);
+static int history_load(TYPE(History) *, const char *);
+static int history_save(TYPE(History) *, const char *);
+static int history_save_fp(TYPE(History) *, FILE *);
+static int history_prev_event(TYPE(History) *, TYPE(HistEvent) *, int);
+static int history_next_event(TYPE(History) *, TYPE(HistEvent) *, int);
+static int history_next_string(TYPE(History) *, TYPE(HistEvent) *,
+ const Char *);
+static int history_prev_string(TYPE(History) *, TYPE(HistEvent) *,
+ const Char *);
+
+
+/***********************************************************************/
+
+/*
+ * Builtin- history implementation
+ */
+typedef struct hentry_t {
+ TYPE(HistEvent) ev; /* What we return */
+ void *data; /* data */
+ struct hentry_t *next; /* Next entry */
+ struct hentry_t *prev; /* Previous entry */
+} hentry_t;
+
+typedef struct history_t {
+ hentry_t list; /* Fake list header element */
+ hentry_t *cursor; /* Current element in the list */
+ int max; /* Maximum number of events */
+ int cur; /* Current number of events */
+ int eventid; /* For generation of unique event id */
+ int flags; /* TYPE(History) flags */
+#define H_UNIQUE 1 /* Store only unique elements */
+} history_t;
+
+static int history_def_next(void *, TYPE(HistEvent) *);
+static int history_def_first(void *, TYPE(HistEvent) *);
+static int history_def_prev(void *, TYPE(HistEvent) *);
+static int history_def_last(void *, TYPE(HistEvent) *);
+static int history_def_curr(void *, TYPE(HistEvent) *);
+static int history_def_set(void *, TYPE(HistEvent) *, const int);
+static void history_def_clear(void *, TYPE(HistEvent) *);
+static int history_def_enter(void *, TYPE(HistEvent) *, const Char *);
+static int history_def_add(void *, TYPE(HistEvent) *, const Char *);
+static int history_def_del(void *, TYPE(HistEvent) *, const int);
+
+static int history_def_init(void **, TYPE(HistEvent) *, int);
+static int history_def_insert(history_t *, TYPE(HistEvent) *, const Char *);
+static void history_def_delete(history_t *, TYPE(HistEvent) *, hentry_t *);
+
+static int history_deldata_nth(history_t *, TYPE(HistEvent) *, int, void **);
+static int history_set_nth(void *, TYPE(HistEvent) *, int);
+
+#define history_def_setsize(p, num)(void) (((history_t *)p)->max = (num))
+#define history_def_getsize(p) (((history_t *)p)->cur)
+#define history_def_getunique(p) (((((history_t *)p)->flags) & H_UNIQUE) != 0)
+#define history_def_setunique(p, uni) \
+ if (uni) \
+ (((history_t *)p)->flags) |= H_UNIQUE; \
+ else \
+ (((history_t *)p)->flags) &= ~H_UNIQUE
+
+#define he_strerror(code) he_errlist[code]
+#define he_seterrev(evp, code) {\
+ evp->num = code;\
+ evp->str = he_strerror(code);\
+ }
+
+/* error messages */
+static const Char *const he_errlist[] = {
+ STR("OK"),
+ STR("unknown error"),
+ STR("malloc() failed"),
+ STR("first event not found"),
+ STR("last event not found"),
+ STR("empty list"),
+ STR("no next event"),
+ STR("no previous event"),
+ STR("current event is invalid"),
+ STR("event not found"),
+ STR("can't read history from file"),
+ STR("can't write history"),
+ STR("required parameter(s) not supplied"),
+ STR("history size negative"),
+ STR("function not allowed with other history-functions-set the default"),
+ STR("bad parameters")
+};
+/* error codes */
+#define _HE_OK 0
+#define _HE_UNKNOWN 1
+#define _HE_MALLOC_FAILED 2
+#define _HE_FIRST_NOTFOUND 3
+#define _HE_LAST_NOTFOUND 4
+#define _HE_EMPTY_LIST 5
+#define _HE_END_REACHED 6
+#define _HE_START_REACHED 7
+#define _HE_CURR_INVALID 8
+#define _HE_NOT_FOUND 9
+#define _HE_HIST_READ 10
+#define _HE_HIST_WRITE 11
+#define _HE_PARAM_MISSING 12
+#define _HE_SIZE_NEGATIVE 13
+#define _HE_NOT_ALLOWED 14
+#define _HE_BAD_PARAM 15
+
+/* history_def_first():
+ * Default function to return the first event in the history.
+ */
+static int
+history_def_first(void *p, TYPE(HistEvent) *ev)
+{
+ history_t *h = (history_t *) p;
+
+ h->cursor = h->list.next;
+ if (h->cursor != &h->list)
+ *ev = h->cursor->ev;
+ else {
+ he_seterrev(ev, _HE_FIRST_NOTFOUND);
+ return -1;
+ }
+
+ return 0;
+}
+
+
+/* history_def_last():
+ * Default function to return the last event in the history.
+ */
+static int
+history_def_last(void *p, TYPE(HistEvent) *ev)
+{
+ history_t *h = (history_t *) p;
+
+ h->cursor = h->list.prev;
+ if (h->cursor != &h->list)
+ *ev = h->cursor->ev;
+ else {
+ he_seterrev(ev, _HE_LAST_NOTFOUND);
+ return -1;
+ }
+
+ return 0;
+}
+
+
+/* history_def_next():
+ * Default function to return the next event in the history.
+ */
+static int
+history_def_next(void *p, TYPE(HistEvent) *ev)
+{
+ history_t *h = (history_t *) p;
+
+ if (h->cursor == &h->list) {
+ he_seterrev(ev, _HE_EMPTY_LIST);
+ return -1;
+ }
+
+ if (h->cursor->next == &h->list) {
+ he_seterrev(ev, _HE_END_REACHED);
+ return -1;
+ }
+
+ h->cursor = h->cursor->next;
+ *ev = h->cursor->ev;
+
+ return 0;
+}
+
+
+/* history_def_prev():
+ * Default function to return the previous event in the history.
+ */
+static int
+history_def_prev(void *p, TYPE(HistEvent) *ev)
+{
+ history_t *h = (history_t *) p;
+
+ if (h->cursor == &h->list) {
+ he_seterrev(ev,
+ (h->cur > 0) ? _HE_END_REACHED : _HE_EMPTY_LIST);
+ return -1;
+ }
+
+ if (h->cursor->prev == &h->list) {
+ he_seterrev(ev, _HE_START_REACHED);
+ return -1;
+ }
+
+ h->cursor = h->cursor->prev;
+ *ev = h->cursor->ev;
+
+ return 0;
+}
+
+
+/* history_def_curr():
+ * Default function to return the current event in the history.
+ */
+static int
+history_def_curr(void *p, TYPE(HistEvent) *ev)
+{
+ history_t *h = (history_t *) p;
+
+ if (h->cursor != &h->list)
+ *ev = h->cursor->ev;
+ else {
+ he_seterrev(ev,
+ (h->cur > 0) ? _HE_CURR_INVALID : _HE_EMPTY_LIST);
+ return -1;
+ }
+
+ return 0;
+}
+
+
+/* history_def_set():
+ * Default function to set the current event in the history to the
+ * given one.
+ */
+static int
+history_def_set(void *p, TYPE(HistEvent) *ev, const int n)
+{
+ history_t *h = (history_t *) p;
+
+ if (h->cur == 0) {
+ he_seterrev(ev, _HE_EMPTY_LIST);
+ return -1;
+ }
+ if (h->cursor == &h->list || h->cursor->ev.num != n) {
+ for (h->cursor = h->list.next; h->cursor != &h->list;
+ h->cursor = h->cursor->next)
+ if (h->cursor->ev.num == n)
+ break;
+ }
+ if (h->cursor == &h->list) {
+ he_seterrev(ev, _HE_NOT_FOUND);
+ return -1;
+ }
+ return 0;
+}
+
+
+/* history_set_nth():
+ * Default function to set the current event in the history to the
+ * n-th one.
+ */
+static int
+history_set_nth(void *p, TYPE(HistEvent) *ev, int n)
+{
+ history_t *h = (history_t *) p;
+
+ if (h->cur == 0) {
+ he_seterrev(ev, _HE_EMPTY_LIST);
+ return -1;
+ }
+ for (h->cursor = h->list.prev; h->cursor != &h->list;
+ h->cursor = h->cursor->prev)
+ if (n-- <= 0)
+ break;
+ if (h->cursor == &h->list) {
+ he_seterrev(ev, _HE_NOT_FOUND);
+ return -1;
+ }
+ return 0;
+}
+
+
+/* history_def_add():
+ * Append string to element
+ */
+static int
+history_def_add(void *p, TYPE(HistEvent) *ev, const Char *str)
+{
+ history_t *h = (history_t *) p;
+ size_t len;
+ Char *s;
+ HistEventPrivate *evp = (void *)&h->cursor->ev;
+
+ if (h->cursor == &h->list)
+ return history_def_enter(p, ev, str);
+ len = Strlen(evp->str) + Strlen(str) + 1;
+ s = h_malloc(len * sizeof(*s));
+ if (s == NULL) {
+ he_seterrev(ev, _HE_MALLOC_FAILED);
+ return -1;
+ }
+ (void) Strncpy(s, h->cursor->ev.str, len);
+ s[len - 1] = '\0';
+ (void) Strncat(s, str, len - Strlen(s) - 1);
+ h_free(evp->str);
+ evp->str = s;
+ *ev = h->cursor->ev;
+ return 0;
+}
+
+
+static int
+history_deldata_nth(history_t *h, TYPE(HistEvent) *ev,
+ int num, void **data)
+{
+ if (history_set_nth(h, ev, num) != 0)
+ return -1;
+ /* magic value to skip delete (just set to n-th history) */
+ if (data == (void **)-1)
+ return 0;
+ ev->str = Strdup(h->cursor->ev.str);
+ ev->num = h->cursor->ev.num;
+ if (data)
+ *data = h->cursor->data;
+ history_def_delete(h, ev, h->cursor);
+ return 0;
+}
+
+
+/* history_def_del():
+ * Delete element hp of the h list
+ */
+/* ARGSUSED */
+static int
+history_def_del(void *p, TYPE(HistEvent) *ev __attribute__((__unused__)),
+ const int num)
+{
+ history_t *h = (history_t *) p;
+ if (history_def_set(h, ev, num) != 0)
+ return -1;
+ ev->str = Strdup(h->cursor->ev.str);
+ ev->num = h->cursor->ev.num;
+ history_def_delete(h, ev, h->cursor);
+ return 0;
+}
+
+
+/* history_def_delete():
+ * Delete element hp of the h list
+ */
+/* ARGSUSED */
+static void
+history_def_delete(history_t *h,
+ TYPE(HistEvent) *ev __attribute__((__unused__)), hentry_t *hp)
+{
+ HistEventPrivate *evp = (void *)&hp->ev;
+ if (hp == &h->list)
+ abort();
+ if (h->cursor == hp) {
+ h->cursor = hp->prev;
+ if (h->cursor == &h->list)
+ h->cursor = hp->next;
+ }
+ hp->prev->next = hp->next;
+ hp->next->prev = hp->prev;
+ h_free(evp->str);
+ h_free(hp);
+ h->cur--;
+}
+
+
+/* history_def_insert():
+ * Insert element with string str in the h list
+ */
+static int
+history_def_insert(history_t *h, TYPE(HistEvent) *ev, const Char *str)
+{
+ hentry_t *c;
+
+ c = h_malloc(sizeof(*c));
+ if (c == NULL)
+ goto oomem;
+ if ((c->ev.str = h_strdup(str)) == NULL) {
+ h_free(c);
+ goto oomem;
+ }
+ c->data = NULL;
+ c->ev.num = ++h->eventid;
+ c->next = h->list.next;
+ c->prev = &h->list;
+ h->list.next->prev = c;
+ h->list.next = c;
+ h->cur++;
+ h->cursor = c;
+
+ *ev = c->ev;
+ return 0;
+oomem:
+ he_seterrev(ev, _HE_MALLOC_FAILED);
+ return -1;
+}
+
+
+/* history_def_enter():
+ * Default function to enter an item in the history
+ */
+static int
+history_def_enter(void *p, TYPE(HistEvent) *ev, const Char *str)
+{
+ history_t *h = (history_t *) p;
+
+ if ((h->flags & H_UNIQUE) != 0 && h->list.next != &h->list &&
+ Strcmp(h->list.next->ev.str, str) == 0)
+ return 0;
+
+ if (history_def_insert(h, ev, str) == -1)
+ return -1; /* error, keep error message */
+
+ /*
+ * Always keep at least one entry.
+ * This way we don't have to check for the empty list.
+ */
+ while (h->cur > h->max && h->cur > 0)
+ history_def_delete(h, ev, h->list.prev);
+
+ return 1;
+}
+
+
+/* history_def_init():
+ * Default history initialization function
+ */
+/* ARGSUSED */
+static int
+history_def_init(void **p, TYPE(HistEvent) *ev __attribute__((__unused__)), int n)
+{
+ history_t *h = (history_t *) h_malloc(sizeof(*h));
+ if (h == NULL)
+ return -1;
+
+ if (n <= 0)
+ n = 0;
+ h->eventid = 0;
+ h->cur = 0;
+ h->max = n;
+ h->list.next = h->list.prev = &h->list;
+ h->list.ev.str = NULL;
+ h->list.ev.num = 0;
+ h->cursor = &h->list;
+ h->flags = 0;
+ *p = h;
+ return 0;
+}
+
+
+/* history_def_clear():
+ * Default history cleanup function
+ */
+static void
+history_def_clear(void *p, TYPE(HistEvent) *ev)
+{
+ history_t *h = (history_t *) p;
+
+ while (h->list.prev != &h->list)
+ history_def_delete(h, ev, h->list.prev);
+ h->cursor = &h->list;
+ h->eventid = 0;
+ h->cur = 0;
+}
+
+
+
+
+/************************************************************************/
+
+/* history_init():
+ * Initialization function.
+ */
+TYPE(History) *
+FUN(history,init)(void)
+{
+ TYPE(HistEvent) ev;
+ TYPE(History) *h = (TYPE(History) *) h_malloc(sizeof(*h));
+ if (h == NULL)
+ return NULL;
+
+ if (history_def_init(&h->h_ref, &ev, 0) == -1) {
+ h_free(h);
+ return NULL;
+ }
+ h->h_ent = -1;
+ h->h_next = history_def_next;
+ h->h_first = history_def_first;
+ h->h_last = history_def_last;
+ h->h_prev = history_def_prev;
+ h->h_curr = history_def_curr;
+ h->h_set = history_def_set;
+ h->h_clear = history_def_clear;
+ h->h_enter = history_def_enter;
+ h->h_add = history_def_add;
+ h->h_del = history_def_del;
+
+ return h;
+}
+
+
+/* history_end():
+ * clean up history;
+ */
+void
+FUN(history,end)(TYPE(History) *h)
+{
+ TYPE(HistEvent) ev;
+
+ if (h->h_next == history_def_next)
+ history_def_clear(h->h_ref, &ev);
+ h_free(h->h_ref);
+ h_free(h);
+}
+
+
+
+/* history_setsize():
+ * Set history number of events
+ */
+static int
+history_setsize(TYPE(History) *h, TYPE(HistEvent) *ev, int num)
+{
+
+ if (h->h_next != history_def_next) {
+ he_seterrev(ev, _HE_NOT_ALLOWED);
+ return -1;
+ }
+ if (num < 0) {
+ he_seterrev(ev, _HE_BAD_PARAM);
+ return -1;
+ }
+ history_def_setsize(h->h_ref, num);
+ return 0;
+}
+
+
+/* history_getsize():
+ * Get number of events currently in history
+ */
+static int
+history_getsize(TYPE(History) *h, TYPE(HistEvent) *ev)
+{
+ if (h->h_next != history_def_next) {
+ he_seterrev(ev, _HE_NOT_ALLOWED);
+ return -1;
+ }
+ ev->num = history_def_getsize(h->h_ref);
+ if (ev->num < -1) {
+ he_seterrev(ev, _HE_SIZE_NEGATIVE);
+ return -1;
+ }
+ return 0;
+}
+
+
+/* history_setunique():
+ * Set if adjacent equal events should not be entered in history.
+ */
+static int
+history_setunique(TYPE(History) *h, TYPE(HistEvent) *ev, int uni)
+{
+
+ if (h->h_next != history_def_next) {
+ he_seterrev(ev, _HE_NOT_ALLOWED);
+ return -1;
+ }
+ history_def_setunique(h->h_ref, uni);
+ return 0;
+}
+
+
+/* history_getunique():
+ * Get if adjacent equal events should not be entered in history.
+ */
+static int
+history_getunique(TYPE(History) *h, TYPE(HistEvent) *ev)
+{
+ if (h->h_next != history_def_next) {
+ he_seterrev(ev, _HE_NOT_ALLOWED);
+ return -1;
+ }
+ ev->num = history_def_getunique(h->h_ref);
+ return 0;
+}
+
+
+/* history_set_fun():
+ * Set history functions
+ */
+static int
+history_set_fun(TYPE(History) *h, TYPE(History) *nh)
+{
+ TYPE(HistEvent) ev;
+
+ if (nh->h_first == NULL || nh->h_next == NULL || nh->h_last == NULL ||
+ nh->h_prev == NULL || nh->h_curr == NULL || nh->h_set == NULL ||
+ nh->h_enter == NULL || nh->h_add == NULL || nh->h_clear == NULL ||
+ nh->h_del == NULL || nh->h_ref == NULL) {
+ if (h->h_next != history_def_next) {
+ if (history_def_init(&h->h_ref, &ev, 0) == -1)
+ return -1;
+ h->h_first = history_def_first;
+ h->h_next = history_def_next;
+ h->h_last = history_def_last;
+ h->h_prev = history_def_prev;
+ h->h_curr = history_def_curr;
+ h->h_set = history_def_set;
+ h->h_clear = history_def_clear;
+ h->h_enter = history_def_enter;
+ h->h_add = history_def_add;
+ h->h_del = history_def_del;
+ }
+ return -1;
+ }
+ if (h->h_next == history_def_next)
+ history_def_clear(h->h_ref, &ev);
+
+ h->h_ent = -1;
+ h->h_first = nh->h_first;
+ h->h_next = nh->h_next;
+ h->h_last = nh->h_last;
+ h->h_prev = nh->h_prev;
+ h->h_curr = nh->h_curr;
+ h->h_set = nh->h_set;
+ h->h_clear = nh->h_clear;
+ h->h_enter = nh->h_enter;
+ h->h_add = nh->h_add;
+ h->h_del = nh->h_del;
+
+ return 0;
+}
+
+
+/* history_load():
+ * TYPE(History) load function
+ */
+static int
+history_load(TYPE(History) *h, const char *fname)
+{
+ FILE *fp;
+ char *line;
+ size_t llen;
+ ssize_t sz;
+ size_t max_size;
+ char *ptr;
+ int i = -1;
+ TYPE(HistEvent) ev;
+#ifndef NARROWCHAR
+ static ct_buffer_t conv;
+#endif
+
+ if ((fp = fopen(fname, "r")) == NULL)
+ return i;
+
+ line = NULL;
+ llen = 0;
+ if ((sz = getline(&line, &llen, fp)) == -1)
+ goto done;
+
+ if (strncmp(line, hist_cookie, (size_t)sz) != 0)
+ goto done;
+
+ ptr = h_malloc((max_size = 1024) * sizeof(*ptr));
+ if (ptr == NULL)
+ goto done;
+ for (i = 0; (sz = getline(&line, &llen, fp)) != -1; i++) {
+ if (sz > 0 && line[sz - 1] == '\n')
+ line[--sz] = '\0';
+ if (max_size < (size_t)sz) {
+ char *nptr;
+ max_size = ((size_t)sz + 1024) & (size_t)~1023;
+ nptr = h_realloc(ptr, max_size * sizeof(*ptr));
+ if (nptr == NULL) {
+ i = -1;
+ goto oomem;
+ }
+ ptr = nptr;
+ }
+ (void) strunvis(ptr, line);
+ if (HENTER(h, &ev, ct_decode_string(ptr, &conv)) == -1) {
+ i = -1;
+ goto oomem;
+ }
+ }
+oomem:
+ h_free(ptr);
+done:
+ free(line);
+ (void) fclose(fp);
+ return i;
+}
+
+
+/* history_save_fp():
+ * TYPE(History) save function
+ */
+static int
+history_save_fp(TYPE(History) *h, FILE *fp)
+{
+ TYPE(HistEvent) ev;
+ int i = -1, retval;
+ size_t len, max_size;
+ char *ptr;
+ const char *str;
+#ifndef NARROWCHAR
+ static ct_buffer_t conv;
+#endif
+
+ if (fchmod(fileno(fp), S_IRUSR|S_IWUSR) == -1)
+ goto done;
+ if (fputs(hist_cookie, fp) == EOF)
+ goto done;
+ ptr = h_malloc((max_size = 1024) * sizeof(*ptr));
+ if (ptr == NULL)
+ goto done;
+ for (i = 0, retval = HLAST(h, &ev);
+ retval != -1;
+ retval = HPREV(h, &ev), i++) {
+ str = ct_encode_string(ev.str, &conv);
+ len = strlen(str) * 4 + 1;
+ if (len > max_size) {
+ char *nptr;
+ max_size = (len + 1024) & (size_t)~1023;
+ nptr = h_realloc(ptr, max_size * sizeof(*ptr));
+ if (nptr == NULL) {
+ i = -1;
+ goto oomem;
+ }
+ ptr = nptr;
+ }
+ (void) strvis(ptr, str, VIS_WHITE);
+ (void) fprintf(fp, "%s\n", ptr);
+ }
+oomem:
+ h_free(ptr);
+done:
+ return i;
+}
+
+
+/* history_save():
+ * History save function
+ */
+static int
+history_save(TYPE(History) *h, const char *fname)
+{
+ FILE *fp;
+ int i;
+
+ if ((fp = fopen(fname, "w")) == NULL)
+ return -1;
+
+ i = history_save_fp(h, fp);
+
+ (void) fclose(fp);
+ return i;
+}
+
+
+/* history_prev_event():
+ * Find the previous event, with number given
+ */
+static int
+history_prev_event(TYPE(History) *h, TYPE(HistEvent) *ev, int num)
+{
+ int retval;
+
+ for (retval = HCURR(h, ev); retval != -1; retval = HPREV(h, ev))
+ if (ev->num == num)
+ return 0;
+
+ he_seterrev(ev, _HE_NOT_FOUND);
+ return -1;
+}
+
+
+static int
+history_next_evdata(TYPE(History) *h, TYPE(HistEvent) *ev, int num, void **d)
+{
+ int retval;
+
+ for (retval = HCURR(h, ev); retval != -1; retval = HPREV(h, ev))
+ if (ev->num == num) {
+ if (d)
+ *d = ((history_t *)h->h_ref)->cursor->data;
+ return 0;
+ }
+
+ he_seterrev(ev, _HE_NOT_FOUND);
+ return -1;
+}
+
+
+/* history_next_event():
+ * Find the next event, with number given
+ */
+static int
+history_next_event(TYPE(History) *h, TYPE(HistEvent) *ev, int num)
+{
+ int retval;
+
+ for (retval = HCURR(h, ev); retval != -1; retval = HNEXT(h, ev))
+ if (ev->num == num)
+ return 0;
+
+ he_seterrev(ev, _HE_NOT_FOUND);
+ return -1;
+}
+
+
+/* history_prev_string():
+ * Find the previous event beginning with string
+ */
+static int
+history_prev_string(TYPE(History) *h, TYPE(HistEvent) *ev, const Char *str)
+{
+ size_t len = Strlen(str);
+ int retval;
+
+ for (retval = HCURR(h, ev); retval != -1; retval = HNEXT(h, ev))
+ if (Strncmp(str, ev->str, len) == 0)
+ return 0;
+
+ he_seterrev(ev, _HE_NOT_FOUND);
+ return -1;
+}
+
+
+/* history_next_string():
+ * Find the next event beginning with string
+ */
+static int
+history_next_string(TYPE(History) *h, TYPE(HistEvent) *ev, const Char *str)
+{
+ size_t len = Strlen(str);
+ int retval;
+
+ for (retval = HCURR(h, ev); retval != -1; retval = HPREV(h, ev))
+ if (Strncmp(str, ev->str, len) == 0)
+ return 0;
+
+ he_seterrev(ev, _HE_NOT_FOUND);
+ return -1;
+}
+
+
+/* history():
+ * User interface to history functions.
+ */
+int
+FUNW(history)(TYPE(History) *h, TYPE(HistEvent) *ev, int fun, ...)
+{
+ va_list va;
+ const Char *str;
+ int retval;
+
+ va_start(va, fun);
+
+ he_seterrev(ev, _HE_OK);
+
+ switch (fun) {
+ case H_GETSIZE:
+ retval = history_getsize(h, ev);
+ break;
+
+ case H_SETSIZE:
+ retval = history_setsize(h, ev, va_arg(va, int));
+ break;
+
+ case H_GETUNIQUE:
+ retval = history_getunique(h, ev);
+ break;
+
+ case H_SETUNIQUE:
+ retval = history_setunique(h, ev, va_arg(va, int));
+ break;
+
+ case H_ADD:
+ str = va_arg(va, const Char *);
+ retval = HADD(h, ev, str);
+ break;
+
+ case H_DEL:
+ retval = HDEL(h, ev, va_arg(va, const int));
+ break;
+
+ case H_ENTER:
+ str = va_arg(va, const Char *);
+ if ((retval = HENTER(h, ev, str)) != -1)
+ h->h_ent = ev->num;
+ break;
+
+ case H_APPEND:
+ str = va_arg(va, const Char *);
+ if ((retval = HSET(h, ev, h->h_ent)) != -1)
+ retval = HADD(h, ev, str);
+ break;
+
+ case H_FIRST:
+ retval = HFIRST(h, ev);
+ break;
+
+ case H_NEXT:
+ retval = HNEXT(h, ev);
+ break;
+
+ case H_LAST:
+ retval = HLAST(h, ev);
+ break;
+
+ case H_PREV:
+ retval = HPREV(h, ev);
+ break;
+
+ case H_CURR:
+ retval = HCURR(h, ev);
+ break;
+
+ case H_SET:
+ retval = HSET(h, ev, va_arg(va, const int));
+ break;
+
+ case H_CLEAR:
+ HCLEAR(h, ev);
+ retval = 0;
+ break;
+
+ case H_LOAD:
+ retval = history_load(h, va_arg(va, const char *));
+ if (retval == -1)
+ he_seterrev(ev, _HE_HIST_READ);
+ break;
+
+ case H_SAVE:
+ retval = history_save(h, va_arg(va, const char *));
+ if (retval == -1)
+ he_seterrev(ev, _HE_HIST_WRITE);
+ break;
+
+ case H_SAVE_FP:
+ retval = history_save_fp(h, va_arg(va, FILE *));
+ if (retval == -1)
+ he_seterrev(ev, _HE_HIST_WRITE);
+ break;
+
+ case H_PREV_EVENT:
+ retval = history_prev_event(h, ev, va_arg(va, int));
+ break;
+
+ case H_NEXT_EVENT:
+ retval = history_next_event(h, ev, va_arg(va, int));
+ break;
+
+ case H_PREV_STR:
+ retval = history_prev_string(h, ev, va_arg(va, const Char *));
+ break;
+
+ case H_NEXT_STR:
+ retval = history_next_string(h, ev, va_arg(va, const Char *));
+ break;
+
+ case H_FUNC:
+ {
+ TYPE(History) hf;
+
+ hf.h_ref = va_arg(va, void *);
+ h->h_ent = -1;
+ hf.h_first = va_arg(va, history_gfun_t);
+ hf.h_next = va_arg(va, history_gfun_t);
+ hf.h_last = va_arg(va, history_gfun_t);
+ hf.h_prev = va_arg(va, history_gfun_t);
+ hf.h_curr = va_arg(va, history_gfun_t);
+ hf.h_set = va_arg(va, history_sfun_t);
+ hf.h_clear = va_arg(va, history_vfun_t);
+ hf.h_enter = va_arg(va, history_efun_t);
+ hf.h_add = va_arg(va, history_efun_t);
+ hf.h_del = va_arg(va, history_sfun_t);
+
+ if ((retval = history_set_fun(h, &hf)) == -1)
+ he_seterrev(ev, _HE_PARAM_MISSING);
+ break;
+ }
+
+ case H_END:
+ FUN(history,end)(h);
+ retval = 0;
+ break;
+
+ case H_NEXT_EVDATA:
+ {
+ int num = va_arg(va, int);
+ void **d = va_arg(va, void **);
+ retval = history_next_evdata(h, ev, num, d);
+ break;
+ }
+
+ case H_DELDATA:
+ {
+ int num = va_arg(va, int);
+ void **d = va_arg(va, void **);
+ retval = history_deldata_nth((history_t *)h->h_ref, ev, num, d);
+ break;
+ }
+
+ case H_REPLACE: /* only use after H_NEXT_EVDATA */
+ {
+ const Char *line = va_arg(va, const Char *);
+ void *d = va_arg(va, void *);
+ const Char *s;
+ if(!line || !(s = Strdup(line))) {
+ retval = -1;
+ break;
+ }
+ ((history_t *)h->h_ref)->cursor->ev.str = s;
+ ((history_t *)h->h_ref)->cursor->data = d;
+ retval = 0;
+ break;
+ }
+
+ default:
+ retval = -1;
+ he_seterrev(ev, _HE_UNKNOWN);
+ break;
+ }
+ va_end(va);
+ return retval;
+}
diff --git a/third_party/heimdal/lib/libedit/src/historyn.c b/third_party/heimdal/lib/libedit/src/historyn.c
new file mode 100644
index 0000000..59130de
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/historyn.c
@@ -0,0 +1,3 @@
+#include "config.h"
+#define NARROWCHAR
+#include "history.c"
diff --git a/third_party/heimdal/lib/libedit/src/keymacro.c b/third_party/heimdal/lib/libedit/src/keymacro.c
new file mode 100644
index 0000000..13d2089
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/keymacro.c
@@ -0,0 +1,669 @@
+/* $NetBSD: keymacro.c,v 1.23 2016/05/24 15:00:45 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)key.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: keymacro.c,v 1.23 2016/05/24 15:00:45 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * keymacro.c: This module contains the procedures for maintaining
+ * the extended-key map.
+ *
+ * An extended-key (key) is a sequence of keystrokes introduced
+ * with a sequence introducer and consisting of an arbitrary
+ * number of characters. This module maintains a map (the
+ * el->el_keymacro.map)
+ * to convert these extended-key sequences into input strs
+ * (XK_STR) or editor functions (XK_CMD).
+ *
+ * Warning:
+ * If key is a substr of some other keys, then the longer
+ * keys are lost!! That is, if the keys "abcd" and "abcef"
+ * are in el->el_keymacro.map, adding the key "abc" will cause
+ * the first two definitions to be lost.
+ *
+ * Restrictions:
+ * -------------
+ * 1) It is not possible to have one key that is a
+ * substr of another.
+ */
+#include <stdlib.h>
+#include <string.h>
+
+#include "el.h"
+#include "fcns.h"
+
+/*
+ * The Nodes of the el->el_keymacro.map. The el->el_keymacro.map is a
+ * linked list of these node elements
+ */
+struct keymacro_node_t {
+ wchar_t ch; /* single character of key */
+ int type; /* node type */
+ keymacro_value_t val; /* command code or pointer to str, */
+ /* if this is a leaf */
+ struct keymacro_node_t *next; /* ptr to next char of this key */
+ struct keymacro_node_t *sibling;/* ptr to another key with same prefix*/
+};
+
+static int node_trav(EditLine *, keymacro_node_t *, wchar_t *,
+ keymacro_value_t *);
+static int node__try(EditLine *, keymacro_node_t *,
+ const wchar_t *, keymacro_value_t *, int);
+static keymacro_node_t *node__get(wint_t);
+static void node__free(keymacro_node_t *);
+static void node__put(EditLine *, keymacro_node_t *);
+static int node__delete(EditLine *, keymacro_node_t **,
+ const wchar_t *);
+static int node_lookup(EditLine *, const wchar_t *,
+ keymacro_node_t *, size_t);
+static int node_enum(EditLine *, keymacro_node_t *, size_t);
+
+#define KEY_BUFSIZ EL_BUFSIZ
+
+
+/* keymacro_init():
+ * Initialize the key maps
+ */
+libedit_private int
+keymacro_init(EditLine *el)
+{
+
+ el->el_keymacro.buf = el_malloc(KEY_BUFSIZ *
+ sizeof(*el->el_keymacro.buf));
+ if (el->el_keymacro.buf == NULL)
+ return -1;
+ el->el_keymacro.map = NULL;
+ keymacro_reset(el);
+ return 0;
+}
+
+/* keymacro_end():
+ * Free the key maps
+ */
+libedit_private void
+keymacro_end(EditLine *el)
+{
+
+ el_free(el->el_keymacro.buf);
+ el->el_keymacro.buf = NULL;
+ node__free(el->el_keymacro.map);
+}
+
+
+/* keymacro_map_cmd():
+ * Associate cmd with a key value
+ */
+libedit_private keymacro_value_t *
+keymacro_map_cmd(EditLine *el, int cmd)
+{
+
+ el->el_keymacro.val.cmd = (el_action_t) cmd;
+ return &el->el_keymacro.val;
+}
+
+
+/* keymacro_map_str():
+ * Associate str with a key value
+ */
+libedit_private keymacro_value_t *
+keymacro_map_str(EditLine *el, wchar_t *str)
+{
+
+ el->el_keymacro.val.str = str;
+ return &el->el_keymacro.val;
+}
+
+
+/* keymacro_reset():
+ * Takes all nodes on el->el_keymacro.map and puts them on free list.
+ * Then initializes el->el_keymacro.map with arrow keys
+ * [Always bind the ansi arrow keys?]
+ */
+libedit_private void
+keymacro_reset(EditLine *el)
+{
+
+ node__put(el, el->el_keymacro.map);
+ el->el_keymacro.map = NULL;
+ return;
+}
+
+
+/* keymacro_get():
+ * Calls the recursive function with entry point el->el_keymacro.map
+ * Looks up *ch in map and then reads characters until a
+ * complete match is found or a mismatch occurs. Returns the
+ * type of the match found (XK_STR or XK_CMD).
+ * Returns NULL in val.str and XK_STR for no match.
+ * Returns XK_NOD for end of file or read error.
+ * The last character read is returned in *ch.
+ */
+libedit_private int
+keymacro_get(EditLine *el, wchar_t *ch, keymacro_value_t *val)
+{
+
+ return node_trav(el, el->el_keymacro.map, ch, val);
+}
+
+
+/* keymacro_add():
+ * Adds key to the el->el_keymacro.map and associates the value in
+ * val with it. If key is already is in el->el_keymacro.map, the new
+ * code is applied to the existing key. Ntype specifies if code is a
+ * command, an out str or a unix command.
+ */
+libedit_private void
+keymacro_add(EditLine *el, const wchar_t *key, keymacro_value_t *val,
+ int ntype)
+{
+
+ if (key[0] == '\0') {
+ (void) fprintf(el->el_errfile,
+ "keymacro_add: Null extended-key not allowed.\n");
+ return;
+ }
+ if (ntype == XK_CMD && val->cmd == ED_SEQUENCE_LEAD_IN) {
+ (void) fprintf(el->el_errfile,
+ "keymacro_add: sequence-lead-in command not allowed\n");
+ return;
+ }
+ if (el->el_keymacro.map == NULL)
+ /* tree is initially empty. Set up new node to match key[0] */
+ el->el_keymacro.map = node__get(key[0]);
+ /* it is properly initialized */
+
+ /* Now recurse through el->el_keymacro.map */
+ (void) node__try(el, el->el_keymacro.map, key, val, ntype);
+ return;
+}
+
+
+/* keymacro_clear():
+ *
+ */
+libedit_private void
+keymacro_clear(EditLine *el, el_action_t *map, const wchar_t *in)
+{
+ if (*in > N_KEYS) /* can't be in the map */
+ return;
+ if ((map[(unsigned char)*in] == ED_SEQUENCE_LEAD_IN) &&
+ ((map == el->el_map.key &&
+ el->el_map.alt[(unsigned char)*in] != ED_SEQUENCE_LEAD_IN) ||
+ (map == el->el_map.alt &&
+ el->el_map.key[(unsigned char)*in] != ED_SEQUENCE_LEAD_IN)))
+ (void) keymacro_delete(el, in);
+}
+
+
+/* keymacro_delete():
+ * Delete the key and all longer keys staring with key, if
+ * they exists.
+ */
+libedit_private int
+keymacro_delete(EditLine *el, const wchar_t *key)
+{
+
+ if (key[0] == '\0') {
+ (void) fprintf(el->el_errfile,
+ "keymacro_delete: Null extended-key not allowed.\n");
+ return -1;
+ }
+ if (el->el_keymacro.map == NULL)
+ return 0;
+
+ (void) node__delete(el, &el->el_keymacro.map, key);
+ return 0;
+}
+
+
+/* keymacro_print():
+ * Print the binding associated with key key.
+ * Print entire el->el_keymacro.map if null
+ */
+libedit_private void
+keymacro_print(EditLine *el, const wchar_t *key)
+{
+
+ /* do nothing if el->el_keymacro.map is empty and null key specified */
+ if (el->el_keymacro.map == NULL && *key == 0)
+ return;
+
+ el->el_keymacro.buf[0] = '"';
+ if (node_lookup(el, key, el->el_keymacro.map, (size_t)1) <= -1)
+ /* key is not bound */
+ (void) fprintf(el->el_errfile, "Unbound extended key \"%ls"
+ "\"\n", key);
+ return;
+}
+
+
+/* node_trav():
+ * recursively traverses node in tree until match or mismatch is
+ * found. May read in more characters.
+ */
+static int
+node_trav(EditLine *el, keymacro_node_t *ptr, wchar_t *ch,
+ keymacro_value_t *val)
+{
+
+ if (ptr->ch == *ch) {
+ /* match found */
+ if (ptr->next) {
+ /* key not complete so get next char */
+ if (el_wgetc(el, ch) != 1)
+ return XK_NOD;
+ return node_trav(el, ptr->next, ch, val);
+ } else {
+ *val = ptr->val;
+ if (ptr->type != XK_CMD)
+ *ch = '\0';
+ return ptr->type;
+ }
+ } else {
+ /* no match found here */
+ if (ptr->sibling) {
+ /* try next sibling */
+ return node_trav(el, ptr->sibling, ch, val);
+ } else {
+ /* no next sibling -- mismatch */
+ val->str = NULL;
+ return XK_STR;
+ }
+ }
+}
+
+
+/* node__try():
+ * Find a node that matches *str or allocate a new one
+ */
+static int
+node__try(EditLine *el, keymacro_node_t *ptr, const wchar_t *str,
+ keymacro_value_t *val, int ntype)
+{
+
+ if (ptr->ch != *str) {
+ keymacro_node_t *xm;
+
+ for (xm = ptr; xm->sibling != NULL; xm = xm->sibling)
+ if (xm->sibling->ch == *str)
+ break;
+ if (xm->sibling == NULL)
+ xm->sibling = node__get(*str); /* setup new node */
+ ptr = xm->sibling;
+ }
+ if (*++str == '\0') {
+ /* we're there */
+ if (ptr->next != NULL) {
+ node__put(el, ptr->next);
+ /* lose longer keys with this prefix */
+ ptr->next = NULL;
+ }
+ switch (ptr->type) {
+ case XK_CMD:
+ case XK_NOD:
+ break;
+ case XK_STR:
+ if (ptr->val.str)
+ el_free(ptr->val.str);
+ break;
+ default:
+ EL_ABORT((el->el_errfile, "Bad XK_ type %d\n",
+ ptr->type));
+ break;
+ }
+
+ switch (ptr->type = ntype) {
+ case XK_CMD:
+ ptr->val = *val;
+ break;
+ case XK_STR:
+ if ((ptr->val.str = wcsdup(val->str)) == NULL)
+ return -1;
+ break;
+ default:
+ EL_ABORT((el->el_errfile, "Bad XK_ type %d\n", ntype));
+ break;
+ }
+ } else {
+ /* still more chars to go */
+ if (ptr->next == NULL)
+ ptr->next = node__get(*str); /* setup new node */
+ (void) node__try(el, ptr->next, str, val, ntype);
+ }
+ return 0;
+}
+
+
+/* node__delete():
+ * Delete node that matches str
+ */
+static int
+node__delete(EditLine *el, keymacro_node_t **inptr, const wchar_t *str)
+{
+ keymacro_node_t *ptr;
+ keymacro_node_t *prev_ptr = NULL;
+
+ ptr = *inptr;
+
+ if (ptr->ch != *str) {
+ keymacro_node_t *xm;
+
+ for (xm = ptr; xm->sibling != NULL; xm = xm->sibling)
+ if (xm->sibling->ch == *str)
+ break;
+ if (xm->sibling == NULL)
+ return 0;
+ prev_ptr = xm;
+ ptr = xm->sibling;
+ }
+ if (*++str == '\0') {
+ /* we're there */
+ if (prev_ptr == NULL)
+ *inptr = ptr->sibling;
+ else
+ prev_ptr->sibling = ptr->sibling;
+ ptr->sibling = NULL;
+ node__put(el, ptr);
+ return 1;
+ } else if (ptr->next != NULL &&
+ node__delete(el, &ptr->next, str) == 1) {
+ if (ptr->next != NULL)
+ return 0;
+ if (prev_ptr == NULL)
+ *inptr = ptr->sibling;
+ else
+ prev_ptr->sibling = ptr->sibling;
+ ptr->sibling = NULL;
+ node__put(el, ptr);
+ return 1;
+ } else {
+ return 0;
+ }
+}
+
+
+/* node__put():
+ * Puts a tree of nodes onto free list using free(3).
+ */
+static void
+node__put(EditLine *el, keymacro_node_t *ptr)
+{
+ if (ptr == NULL)
+ return;
+
+ if (ptr->next != NULL) {
+ node__put(el, ptr->next);
+ ptr->next = NULL;
+ }
+ node__put(el, ptr->sibling);
+
+ switch (ptr->type) {
+ case XK_CMD:
+ case XK_NOD:
+ break;
+ case XK_STR:
+ if (ptr->val.str != NULL)
+ el_free(ptr->val.str);
+ break;
+ default:
+ EL_ABORT((el->el_errfile, "Bad XK_ type %d\n", ptr->type));
+ break;
+ }
+ el_free(ptr);
+}
+
+
+/* node__get():
+ * Returns pointer to a keymacro_node_t for ch.
+ */
+static keymacro_node_t *
+node__get(wint_t ch)
+{
+ keymacro_node_t *ptr;
+
+ ptr = el_malloc(sizeof(*ptr));
+ if (ptr == NULL)
+ return NULL;
+ ptr->ch = ch;
+ ptr->type = XK_NOD;
+ ptr->val.str = NULL;
+ ptr->next = NULL;
+ ptr->sibling = NULL;
+ return ptr;
+}
+
+static void
+node__free(keymacro_node_t *k)
+{
+ if (k == NULL)
+ return;
+ node__free(k->sibling);
+ node__free(k->next);
+ el_free(k);
+}
+
+/* node_lookup():
+ * look for the str starting at node ptr.
+ * Print if last node
+ */
+static int
+node_lookup(EditLine *el, const wchar_t *str, keymacro_node_t *ptr,
+ size_t cnt)
+{
+ ssize_t used;
+
+ if (ptr == NULL)
+ return -1; /* cannot have null ptr */
+
+ if (!str || *str == 0) {
+ /* no more chars in str. node_enum from here. */
+ (void) node_enum(el, ptr, cnt);
+ return 0;
+ } else {
+ /* If match put this char into el->el_keymacro.buf. Recurse */
+ if (ptr->ch == *str) {
+ /* match found */
+ used = ct_visual_char(el->el_keymacro.buf + cnt,
+ KEY_BUFSIZ - cnt, ptr->ch);
+ if (used == -1)
+ return -1; /* ran out of buffer space */
+ if (ptr->next != NULL)
+ /* not yet at leaf */
+ return (node_lookup(el, str + 1, ptr->next,
+ (size_t)used + cnt));
+ else {
+ /* next node is null so key should be complete */
+ if (str[1] == 0) {
+ size_t px = cnt + (size_t)used;
+ el->el_keymacro.buf[px] = '"';
+ el->el_keymacro.buf[px + 1] = '\0';
+ keymacro_kprint(el, el->el_keymacro.buf,
+ &ptr->val, ptr->type);
+ return 0;
+ } else
+ return -1;
+ /* mismatch -- str still has chars */
+ }
+ } else {
+ /* no match found try sibling */
+ if (ptr->sibling)
+ return (node_lookup(el, str, ptr->sibling,
+ cnt));
+ else
+ return -1;
+ }
+ }
+}
+
+
+/* node_enum():
+ * Traverse the node printing the characters it is bound in buffer
+ */
+static int
+node_enum(EditLine *el, keymacro_node_t *ptr, size_t cnt)
+{
+ ssize_t used;
+
+ if (cnt >= KEY_BUFSIZ - 5) { /* buffer too small */
+ el->el_keymacro.buf[++cnt] = '"';
+ el->el_keymacro.buf[++cnt] = '\0';
+ (void) fprintf(el->el_errfile,
+ "Some extended keys too long for internal print buffer");
+ (void) fprintf(el->el_errfile, " \"%ls...\"\n",
+ el->el_keymacro.buf);
+ return 0;
+ }
+ if (ptr == NULL) {
+#ifdef DEBUG_EDIT
+ (void) fprintf(el->el_errfile,
+ "node_enum: BUG!! Null ptr passed\n!");
+#endif
+ return -1;
+ }
+ /* put this char at end of str */
+ used = ct_visual_char(el->el_keymacro.buf + cnt, KEY_BUFSIZ - cnt,
+ ptr->ch);
+ if (ptr->next == NULL) {
+ /* print this key and function */
+ el->el_keymacro.buf[cnt + (size_t)used ] = '"';
+ el->el_keymacro.buf[cnt + (size_t)used + 1] = '\0';
+ keymacro_kprint(el, el->el_keymacro.buf, &ptr->val, ptr->type);
+ } else
+ (void) node_enum(el, ptr->next, cnt + (size_t)used);
+
+ /* go to sibling if there is one */
+ if (ptr->sibling)
+ (void) node_enum(el, ptr->sibling, cnt);
+ return 0;
+}
+
+
+/* keymacro_kprint():
+ * Print the specified key and its associated
+ * function specified by val
+ */
+libedit_private void
+keymacro_kprint(EditLine *el, const wchar_t *key, keymacro_value_t *val,
+ int ntype)
+{
+ el_bindings_t *fp;
+ char unparsbuf[EL_BUFSIZ];
+ static const char fmt[] = "%-15s-> %s\n";
+
+ if (val != NULL)
+ switch (ntype) {
+ case XK_STR:
+ (void) keymacro__decode_str(val->str, unparsbuf,
+ sizeof(unparsbuf),
+ ntype == XK_STR ? "\"\"" : "[]");
+ (void) fprintf(el->el_outfile, fmt,
+ ct_encode_string(key, &el->el_scratch), unparsbuf);
+ break;
+ case XK_CMD:
+ for (fp = el->el_map.help; fp->name; fp++)
+ if (val->cmd == fp->func) {
+ wcstombs(unparsbuf, fp->name, sizeof(unparsbuf));
+ unparsbuf[sizeof(unparsbuf) -1] = '\0';
+ (void) fprintf(el->el_outfile, fmt,
+ ct_encode_string(key, &el->el_scratch), unparsbuf);
+ break;
+ }
+#ifdef DEBUG_KEY
+ if (fp->name == NULL)
+ (void) fprintf(el->el_outfile,
+ "BUG! Command not found.\n");
+#endif
+
+ break;
+ default:
+ EL_ABORT((el->el_errfile, "Bad XK_ type %d\n", ntype));
+ break;
+ }
+ else
+ (void) fprintf(el->el_outfile, fmt, ct_encode_string(key,
+ &el->el_scratch), "no input");
+}
+
+
+#define ADDC(c) \
+ if (b < eb) \
+ *b++ = c; \
+ else \
+ b++
+/* keymacro__decode_str():
+ * Make a printable version of the ey
+ */
+libedit_private size_t
+keymacro__decode_str(const wchar_t *str, char *buf, size_t len,
+ const char *sep)
+{
+ char *b = buf, *eb = b + len;
+ const wchar_t *p;
+
+ b = buf;
+ if (sep[0] != '\0') {
+ ADDC(sep[0]);
+ }
+ if (*str == '\0') {
+ ADDC('^');
+ ADDC('@');
+ goto add_endsep;
+ }
+ for (p = str; *p != 0; p++) {
+ wchar_t dbuf[VISUAL_WIDTH_MAX];
+ wchar_t *p2 = dbuf;
+ ssize_t l = ct_visual_char(dbuf, VISUAL_WIDTH_MAX, *p);
+ while (l-- > 0) {
+ ssize_t n = ct_encode_char(b, (size_t)(eb - b), *p2++);
+ if (n == -1) /* ran out of space */
+ goto add_endsep;
+ else
+ b += n;
+ }
+ }
+add_endsep:
+ if (sep[0] != '\0' && sep[1] != '\0') {
+ ADDC(sep[1]);
+ }
+ ADDC('\0');
+ if ((size_t)(b - buf) >= len)
+ buf[len - 1] = '\0';
+ return (size_t)(b - buf);
+}
diff --git a/third_party/heimdal/lib/libedit/src/keymacro.h b/third_party/heimdal/lib/libedit/src/keymacro.h
new file mode 100644
index 0000000..0653bbe
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/keymacro.h
@@ -0,0 +1,76 @@
+/* $NetBSD: keymacro.h,v 1.6 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)key.h 8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * el.keymacro.h: Key macro header
+ */
+#ifndef _h_el_keymacro
+#define _h_el_keymacro
+
+typedef union keymacro_value_t {
+ el_action_t cmd; /* If it is a command the # */
+ wchar_t *str; /* If it is a string... */
+} keymacro_value_t;
+
+typedef struct keymacro_node_t keymacro_node_t;
+
+typedef struct el_keymacro_t {
+ wchar_t *buf; /* Key print buffer */
+ keymacro_node_t *map; /* Key map */
+ keymacro_value_t val; /* Local conversion buffer */
+} el_keymacro_t;
+
+#define XK_CMD 0
+#define XK_STR 1
+#define XK_NOD 2
+
+libedit_private int keymacro_init(EditLine *);
+libedit_private void keymacro_end(EditLine *);
+libedit_private keymacro_value_t *keymacro_map_cmd(EditLine *, int);
+libedit_private keymacro_value_t *keymacro_map_str(EditLine *, wchar_t *);
+libedit_private void keymacro_reset(EditLine *);
+libedit_private int keymacro_get(EditLine *, wchar_t *, keymacro_value_t *);
+libedit_private void keymacro_add(EditLine *, const wchar_t *,
+ keymacro_value_t *, int);
+libedit_private void keymacro_clear(EditLine *, el_action_t *, const wchar_t *);
+libedit_private int keymacro_delete(EditLine *, const wchar_t *);
+libedit_private void keymacro_print(EditLine *, const wchar_t *);
+libedit_private void keymacro_kprint(EditLine *, const wchar_t *,
+ keymacro_value_t *, int);
+libedit_private size_t keymacro__decode_str(const wchar_t *, char *, size_t,
+ const char *);
+
+#endif /* _h_el_keymacro */
diff --git a/third_party/heimdal/lib/libedit/src/makelist b/third_party/heimdal/lib/libedit/src/makelist
new file mode 100644
index 0000000..c8db945
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/makelist
@@ -0,0 +1,177 @@
+#!/bin/sh -
+# $NetBSD: makelist,v 1.29 2016/05/09 21:46:56 christos Exp $
+#
+# Copyright (c) 1992, 1993
+# The Regents of the University of California. All rights reserved.
+#
+# This code is derived from software contributed to Berkeley by
+# Christos Zoulas of Cornell University.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+# 3. Neither the name of the University nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# @(#)makelist 5.3 (Berkeley) 6/4/93
+
+# makelist.sh: Automatically generate header files...
+
+if [ "x$AWK" = "x" ]
+then
+ AWK=awk
+fi
+USAGE="Usage: $0 -h|-fc|-fh|-bh <filenames>"
+
+if [ "x$1" = "x" ]
+then
+ echo $USAGE 1>&2
+ exit 1
+fi
+
+FLAG="$1"
+shift
+
+FILES="$@"
+
+case $FLAG in
+
+-h)
+ set - `echo $FILES | sed -e 's/\\./_/g'`
+ hdr="_h_`basename $1`"
+ cat $FILES | $AWK '
+ BEGIN {
+ printf("/* Automatically generated file, do not edit */\n");
+ printf("#ifndef %s\n#define %s\n", "'$hdr'", "'$hdr'");
+ }
+ /\(\):/ {
+ pr = substr($2, 1, 2);
+ if (pr == "vi" || pr == "em" || pr == "ed") {
+ name = substr($2, 1, length($2) - 3);
+#
+# XXX: need a space between name and prototype so that -fc and -fh
+# parsing is much easier
+#
+ printf("libedit_private el_action_t\t%s (EditLine *, wint_t);\n",
+ name);
+ }
+ }
+ END {
+ printf("#endif /* %s */\n", "'$hdr'");
+ }'
+ ;;
+
+# generate help.h from various .c files
+#
+-bh)
+ cat $FILES | $AWK '
+ BEGIN {
+ printf("/* Automatically generated file, do not edit */\n");
+ printf("static const struct el_bindings_t el_func_help[] = {\n");
+ low = "abcdefghijklmnopqrstuvwxyz_";
+ high = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_";
+ for (i = 1; i <= length(low); i++)
+ tr[substr(low, i, 1)] = substr(high, i, 1);
+ }
+ /\(\):/ {
+ pr = substr($2, 1, 2);
+ if (pr == "vi" || pr == "em" || pr == "ed") {
+ name = substr($2, 1, length($2) - 3);
+ uname = "";
+ fname = "";
+ for (i = 1; i <= length(name); i++) {
+ s = substr(name, i, 1);
+ uname = uname tr[s];
+ if (s == "_")
+ s = "-";
+ fname = fname s;
+ }
+
+ printf(" { %-30.30s %-30.30s\n","L\"" fname "\",", uname ",");
+ ok = 1;
+ }
+ }
+ /^ \*/ {
+ if (ok) {
+ printf(" L\"");
+ for (i = 2; i < NF; i++)
+ printf("%s ", $i);
+ printf("%s\" },\n", $i);
+ ok = 0;
+ }
+ }
+ END {
+ printf("};\n");
+ }'
+ ;;
+
+# generate fcns.h from various .h files
+#
+-fh)
+ cat $FILES | $AWK '/el_action_t/ { print $3 }' | \
+ sort | tr '[a-z]' '[A-Z]' | tr -d ' ' | $AWK '
+ BEGIN {
+ printf("/* Automatically generated file, do not edit */\n");
+ count = 0;
+ }
+ {
+ printf("#define\t%-30.30s\t%3d\n", $1, count++);
+ }
+ END {
+ printf("#define\t%-30.30s\t%3d\n", "EL_NUM_FCNS", count);
+ }'
+ ;;
+
+# generate func.h from various .h files
+#
+-fc)
+ cat $FILES | $AWK '/el_action_t/ { print $3 }' | sort | $AWK '
+ BEGIN {
+ printf("/* Automatically generated file, do not edit */\n");
+ printf("static const el_func_t el_func[] = {");
+ maxlen = 80;
+ needn = 1;
+ len = 0;
+ }
+ {
+ clen = 25 + 2;
+ len += clen;
+ if (len >= maxlen)
+ needn = 1;
+ if (needn) {
+ printf("\n ");
+ needn = 0;
+ len = 4 + clen;
+ }
+ s = $1 ",";
+ printf("%-26.26s ", s);
+ }
+ END {
+ printf("\n};\n");
+ }'
+ ;;
+
+*)
+ echo $USAGE 1>&2
+ exit 1
+ ;;
+
+esac
diff --git a/third_party/heimdal/lib/libedit/src/map.c b/third_party/heimdal/lib/libedit/src/map.c
new file mode 100644
index 0000000..f72d272
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/map.c
@@ -0,0 +1,1427 @@
+/* $NetBSD: map.c,v 1.51 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)map.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: map.c,v 1.51 2016/05/09 21:46:56 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * map.c: Editor function definitions
+ */
+#include <ctype.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "el.h"
+#include "common.h"
+#include "emacs.h"
+#include "vi.h"
+#include "fcns.h"
+#include "func.h"
+#include "help.h"
+#include "parse.h"
+
+static void map_print_key(EditLine *, el_action_t *, const wchar_t *);
+static void map_print_some_keys(EditLine *, el_action_t *, wint_t, wint_t);
+static void map_print_all_keys(EditLine *);
+static void map_init_nls(EditLine *);
+static void map_init_meta(EditLine *);
+
+/* keymap tables ; should be N_KEYS*sizeof(KEYCMD) bytes long */
+
+
+static const el_action_t el_map_emacs[] = {
+ /* 0 */ EM_SET_MARK, /* ^@ */
+ /* 1 */ ED_MOVE_TO_BEG, /* ^A */
+ /* 2 */ ED_PREV_CHAR, /* ^B */
+ /* 3 */ ED_IGNORE, /* ^C */
+ /* 4 */ EM_DELETE_OR_LIST, /* ^D */
+ /* 5 */ ED_MOVE_TO_END, /* ^E */
+ /* 6 */ ED_NEXT_CHAR, /* ^F */
+ /* 7 */ ED_UNASSIGNED, /* ^G */
+ /* 8 */ EM_DELETE_PREV_CHAR, /* ^H */
+ /* 9 */ ED_UNASSIGNED, /* ^I */
+ /* 10 */ ED_NEWLINE, /* ^J */
+ /* 11 */ ED_KILL_LINE, /* ^K */
+ /* 12 */ ED_CLEAR_SCREEN, /* ^L */
+ /* 13 */ ED_NEWLINE, /* ^M */
+ /* 14 */ ED_NEXT_HISTORY, /* ^N */
+ /* 15 */ ED_IGNORE, /* ^O */
+ /* 16 */ ED_PREV_HISTORY, /* ^P */
+ /* 17 */ ED_IGNORE, /* ^Q */
+ /* 18 */ ED_REDISPLAY, /* ^R */
+ /* 19 */ ED_IGNORE, /* ^S */
+ /* 20 */ ED_TRANSPOSE_CHARS, /* ^T */
+ /* 21 */ EM_KILL_LINE, /* ^U */
+ /* 22 */ ED_QUOTED_INSERT, /* ^V */
+ /* 23 */ EM_KILL_REGION, /* ^W */
+ /* 24 */ ED_SEQUENCE_LEAD_IN, /* ^X */
+ /* 25 */ EM_YANK, /* ^Y */
+ /* 26 */ ED_IGNORE, /* ^Z */
+ /* 27 */ EM_META_NEXT, /* ^[ */
+ /* 28 */ ED_IGNORE, /* ^\ */
+ /* 29 */ ED_IGNORE, /* ^] */
+ /* 30 */ ED_UNASSIGNED, /* ^^ */
+ /* 31 */ ED_UNASSIGNED, /* ^_ */
+ /* 32 */ ED_INSERT, /* SPACE */
+ /* 33 */ ED_INSERT, /* ! */
+ /* 34 */ ED_INSERT, /* " */
+ /* 35 */ ED_INSERT, /* # */
+ /* 36 */ ED_INSERT, /* $ */
+ /* 37 */ ED_INSERT, /* % */
+ /* 38 */ ED_INSERT, /* & */
+ /* 39 */ ED_INSERT, /* ' */
+ /* 40 */ ED_INSERT, /* ( */
+ /* 41 */ ED_INSERT, /* ) */
+ /* 42 */ ED_INSERT, /* * */
+ /* 43 */ ED_INSERT, /* + */
+ /* 44 */ ED_INSERT, /* , */
+ /* 45 */ ED_INSERT, /* - */
+ /* 46 */ ED_INSERT, /* . */
+ /* 47 */ ED_INSERT, /* / */
+ /* 48 */ ED_DIGIT, /* 0 */
+ /* 49 */ ED_DIGIT, /* 1 */
+ /* 50 */ ED_DIGIT, /* 2 */
+ /* 51 */ ED_DIGIT, /* 3 */
+ /* 52 */ ED_DIGIT, /* 4 */
+ /* 53 */ ED_DIGIT, /* 5 */
+ /* 54 */ ED_DIGIT, /* 6 */
+ /* 55 */ ED_DIGIT, /* 7 */
+ /* 56 */ ED_DIGIT, /* 8 */
+ /* 57 */ ED_DIGIT, /* 9 */
+ /* 58 */ ED_INSERT, /* : */
+ /* 59 */ ED_INSERT, /* ; */
+ /* 60 */ ED_INSERT, /* < */
+ /* 61 */ ED_INSERT, /* = */
+ /* 62 */ ED_INSERT, /* > */
+ /* 63 */ ED_INSERT, /* ? */
+ /* 64 */ ED_INSERT, /* @ */
+ /* 65 */ ED_INSERT, /* A */
+ /* 66 */ ED_INSERT, /* B */
+ /* 67 */ ED_INSERT, /* C */
+ /* 68 */ ED_INSERT, /* D */
+ /* 69 */ ED_INSERT, /* E */
+ /* 70 */ ED_INSERT, /* F */
+ /* 71 */ ED_INSERT, /* G */
+ /* 72 */ ED_INSERT, /* H */
+ /* 73 */ ED_INSERT, /* I */
+ /* 74 */ ED_INSERT, /* J */
+ /* 75 */ ED_INSERT, /* K */
+ /* 76 */ ED_INSERT, /* L */
+ /* 77 */ ED_INSERT, /* M */
+ /* 78 */ ED_INSERT, /* N */
+ /* 79 */ ED_INSERT, /* O */
+ /* 80 */ ED_INSERT, /* P */
+ /* 81 */ ED_INSERT, /* Q */
+ /* 82 */ ED_INSERT, /* R */
+ /* 83 */ ED_INSERT, /* S */
+ /* 84 */ ED_INSERT, /* T */
+ /* 85 */ ED_INSERT, /* U */
+ /* 86 */ ED_INSERT, /* V */
+ /* 87 */ ED_INSERT, /* W */
+ /* 88 */ ED_INSERT, /* X */
+ /* 89 */ ED_INSERT, /* Y */
+ /* 90 */ ED_INSERT, /* Z */
+ /* 91 */ ED_INSERT, /* [ */
+ /* 92 */ ED_INSERT, /* \ */
+ /* 93 */ ED_INSERT, /* ] */
+ /* 94 */ ED_INSERT, /* ^ */
+ /* 95 */ ED_INSERT, /* _ */
+ /* 96 */ ED_INSERT, /* ` */
+ /* 97 */ ED_INSERT, /* a */
+ /* 98 */ ED_INSERT, /* b */
+ /* 99 */ ED_INSERT, /* c */
+ /* 100 */ ED_INSERT, /* d */
+ /* 101 */ ED_INSERT, /* e */
+ /* 102 */ ED_INSERT, /* f */
+ /* 103 */ ED_INSERT, /* g */
+ /* 104 */ ED_INSERT, /* h */
+ /* 105 */ ED_INSERT, /* i */
+ /* 106 */ ED_INSERT, /* j */
+ /* 107 */ ED_INSERT, /* k */
+ /* 108 */ ED_INSERT, /* l */
+ /* 109 */ ED_INSERT, /* m */
+ /* 110 */ ED_INSERT, /* n */
+ /* 111 */ ED_INSERT, /* o */
+ /* 112 */ ED_INSERT, /* p */
+ /* 113 */ ED_INSERT, /* q */
+ /* 114 */ ED_INSERT, /* r */
+ /* 115 */ ED_INSERT, /* s */
+ /* 116 */ ED_INSERT, /* t */
+ /* 117 */ ED_INSERT, /* u */
+ /* 118 */ ED_INSERT, /* v */
+ /* 119 */ ED_INSERT, /* w */
+ /* 120 */ ED_INSERT, /* x */
+ /* 121 */ ED_INSERT, /* y */
+ /* 122 */ ED_INSERT, /* z */
+ /* 123 */ ED_INSERT, /* { */
+ /* 124 */ ED_INSERT, /* | */
+ /* 125 */ ED_INSERT, /* } */
+ /* 126 */ ED_INSERT, /* ~ */
+ /* 127 */ EM_DELETE_PREV_CHAR, /* ^? */
+ /* 128 */ ED_UNASSIGNED, /* M-^@ */
+ /* 129 */ ED_UNASSIGNED, /* M-^A */
+ /* 130 */ ED_UNASSIGNED, /* M-^B */
+ /* 131 */ ED_UNASSIGNED, /* M-^C */
+ /* 132 */ ED_UNASSIGNED, /* M-^D */
+ /* 133 */ ED_UNASSIGNED, /* M-^E */
+ /* 134 */ ED_UNASSIGNED, /* M-^F */
+ /* 135 */ ED_UNASSIGNED, /* M-^G */
+ /* 136 */ ED_DELETE_PREV_WORD, /* M-^H */
+ /* 137 */ ED_UNASSIGNED, /* M-^I */
+ /* 138 */ ED_UNASSIGNED, /* M-^J */
+ /* 139 */ ED_UNASSIGNED, /* M-^K */
+ /* 140 */ ED_CLEAR_SCREEN, /* M-^L */
+ /* 141 */ ED_UNASSIGNED, /* M-^M */
+ /* 142 */ ED_UNASSIGNED, /* M-^N */
+ /* 143 */ ED_UNASSIGNED, /* M-^O */
+ /* 144 */ ED_UNASSIGNED, /* M-^P */
+ /* 145 */ ED_UNASSIGNED, /* M-^Q */
+ /* 146 */ ED_UNASSIGNED, /* M-^R */
+ /* 147 */ ED_UNASSIGNED, /* M-^S */
+ /* 148 */ ED_UNASSIGNED, /* M-^T */
+ /* 149 */ ED_UNASSIGNED, /* M-^U */
+ /* 150 */ ED_UNASSIGNED, /* M-^V */
+ /* 151 */ ED_UNASSIGNED, /* M-^W */
+ /* 152 */ ED_UNASSIGNED, /* M-^X */
+ /* 153 */ ED_UNASSIGNED, /* M-^Y */
+ /* 154 */ ED_UNASSIGNED, /* M-^Z */
+ /* 155 */ ED_UNASSIGNED, /* M-^[ */
+ /* 156 */ ED_UNASSIGNED, /* M-^\ */
+ /* 157 */ ED_UNASSIGNED, /* M-^] */
+ /* 158 */ ED_UNASSIGNED, /* M-^^ */
+ /* 159 */ EM_COPY_PREV_WORD, /* M-^_ */
+ /* 160 */ ED_UNASSIGNED, /* M-SPACE */
+ /* 161 */ ED_UNASSIGNED, /* M-! */
+ /* 162 */ ED_UNASSIGNED, /* M-" */
+ /* 163 */ ED_UNASSIGNED, /* M-# */
+ /* 164 */ ED_UNASSIGNED, /* M-$ */
+ /* 165 */ ED_UNASSIGNED, /* M-% */
+ /* 166 */ ED_UNASSIGNED, /* M-& */
+ /* 167 */ ED_UNASSIGNED, /* M-' */
+ /* 168 */ ED_UNASSIGNED, /* M-( */
+ /* 169 */ ED_UNASSIGNED, /* M-) */
+ /* 170 */ ED_UNASSIGNED, /* M-* */
+ /* 171 */ ED_UNASSIGNED, /* M-+ */
+ /* 172 */ ED_UNASSIGNED, /* M-, */
+ /* 173 */ ED_UNASSIGNED, /* M-- */
+ /* 174 */ ED_UNASSIGNED, /* M-. */
+ /* 175 */ ED_UNASSIGNED, /* M-/ */
+ /* 176 */ ED_ARGUMENT_DIGIT, /* M-0 */
+ /* 177 */ ED_ARGUMENT_DIGIT, /* M-1 */
+ /* 178 */ ED_ARGUMENT_DIGIT, /* M-2 */
+ /* 179 */ ED_ARGUMENT_DIGIT, /* M-3 */
+ /* 180 */ ED_ARGUMENT_DIGIT, /* M-4 */
+ /* 181 */ ED_ARGUMENT_DIGIT, /* M-5 */
+ /* 182 */ ED_ARGUMENT_DIGIT, /* M-6 */
+ /* 183 */ ED_ARGUMENT_DIGIT, /* M-7 */
+ /* 184 */ ED_ARGUMENT_DIGIT, /* M-8 */
+ /* 185 */ ED_ARGUMENT_DIGIT, /* M-9 */
+ /* 186 */ ED_UNASSIGNED, /* M-: */
+ /* 187 */ ED_UNASSIGNED, /* M-; */
+ /* 188 */ ED_UNASSIGNED, /* M-< */
+ /* 189 */ ED_UNASSIGNED, /* M-= */
+ /* 190 */ ED_UNASSIGNED, /* M-> */
+ /* 191 */ ED_UNASSIGNED, /* M-? */
+ /* 192 */ ED_UNASSIGNED, /* M-@ */
+ /* 193 */ ED_UNASSIGNED, /* M-A */
+ /* 194 */ ED_PREV_WORD, /* M-B */
+ /* 195 */ EM_CAPITOL_CASE, /* M-C */
+ /* 196 */ EM_DELETE_NEXT_WORD, /* M-D */
+ /* 197 */ ED_UNASSIGNED, /* M-E */
+ /* 198 */ EM_NEXT_WORD, /* M-F */
+ /* 199 */ ED_UNASSIGNED, /* M-G */
+ /* 200 */ ED_UNASSIGNED, /* M-H */
+ /* 201 */ ED_UNASSIGNED, /* M-I */
+ /* 202 */ ED_UNASSIGNED, /* M-J */
+ /* 203 */ ED_UNASSIGNED, /* M-K */
+ /* 204 */ EM_LOWER_CASE, /* M-L */
+ /* 205 */ ED_UNASSIGNED, /* M-M */
+ /* 206 */ ED_SEARCH_NEXT_HISTORY, /* M-N */
+ /* 207 */ ED_SEQUENCE_LEAD_IN, /* M-O */
+ /* 208 */ ED_SEARCH_PREV_HISTORY, /* M-P */
+ /* 209 */ ED_UNASSIGNED, /* M-Q */
+ /* 210 */ ED_UNASSIGNED, /* M-R */
+ /* 211 */ ED_UNASSIGNED, /* M-S */
+ /* 212 */ ED_UNASSIGNED, /* M-T */
+ /* 213 */ EM_UPPER_CASE, /* M-U */
+ /* 214 */ ED_UNASSIGNED, /* M-V */
+ /* 215 */ EM_COPY_REGION, /* M-W */
+ /* 216 */ ED_COMMAND, /* M-X */
+ /* 217 */ ED_UNASSIGNED, /* M-Y */
+ /* 218 */ ED_UNASSIGNED, /* M-Z */
+ /* 219 */ ED_SEQUENCE_LEAD_IN, /* M-[ */
+ /* 220 */ ED_UNASSIGNED, /* M-\ */
+ /* 221 */ ED_UNASSIGNED, /* M-] */
+ /* 222 */ ED_UNASSIGNED, /* M-^ */
+ /* 223 */ ED_UNASSIGNED, /* M-_ */
+ /* 223 */ ED_UNASSIGNED, /* M-` */
+ /* 224 */ ED_UNASSIGNED, /* M-a */
+ /* 225 */ ED_PREV_WORD, /* M-b */
+ /* 226 */ EM_CAPITOL_CASE, /* M-c */
+ /* 227 */ EM_DELETE_NEXT_WORD, /* M-d */
+ /* 228 */ ED_UNASSIGNED, /* M-e */
+ /* 229 */ EM_NEXT_WORD, /* M-f */
+ /* 230 */ ED_UNASSIGNED, /* M-g */
+ /* 231 */ ED_UNASSIGNED, /* M-h */
+ /* 232 */ ED_UNASSIGNED, /* M-i */
+ /* 233 */ ED_UNASSIGNED, /* M-j */
+ /* 234 */ ED_UNASSIGNED, /* M-k */
+ /* 235 */ EM_LOWER_CASE, /* M-l */
+ /* 236 */ ED_UNASSIGNED, /* M-m */
+ /* 237 */ ED_SEARCH_NEXT_HISTORY, /* M-n */
+ /* 238 */ ED_UNASSIGNED, /* M-o */
+ /* 239 */ ED_SEARCH_PREV_HISTORY, /* M-p */
+ /* 240 */ ED_UNASSIGNED, /* M-q */
+ /* 241 */ ED_UNASSIGNED, /* M-r */
+ /* 242 */ ED_UNASSIGNED, /* M-s */
+ /* 243 */ ED_UNASSIGNED, /* M-t */
+ /* 244 */ EM_UPPER_CASE, /* M-u */
+ /* 245 */ ED_UNASSIGNED, /* M-v */
+ /* 246 */ EM_COPY_REGION, /* M-w */
+ /* 247 */ ED_COMMAND, /* M-x */
+ /* 248 */ ED_UNASSIGNED, /* M-y */
+ /* 249 */ ED_UNASSIGNED, /* M-z */
+ /* 250 */ ED_UNASSIGNED, /* M-{ */
+ /* 251 */ ED_UNASSIGNED, /* M-| */
+ /* 252 */ ED_UNASSIGNED, /* M-} */
+ /* 253 */ ED_UNASSIGNED, /* M-~ */
+ /* 254 */ ED_DELETE_PREV_WORD /* M-^? */
+ /* 255 */
+};
+
+
+/*
+ * keymap table for vi. Each index into above tbl; should be
+ * N_KEYS entries long. Vi mode uses a sticky-extend to do command mode:
+ * insert mode characters are in the normal keymap, and command mode
+ * in the extended keymap.
+ */
+static const el_action_t el_map_vi_insert[] = {
+#ifdef KSHVI
+ /* 0 */ ED_UNASSIGNED, /* ^@ */
+ /* 1 */ ED_INSERT, /* ^A */
+ /* 2 */ ED_INSERT, /* ^B */
+ /* 3 */ ED_INSERT, /* ^C */
+ /* 4 */ VI_LIST_OR_EOF, /* ^D */
+ /* 5 */ ED_INSERT, /* ^E */
+ /* 6 */ ED_INSERT, /* ^F */
+ /* 7 */ ED_INSERT, /* ^G */
+ /* 8 */ VI_DELETE_PREV_CHAR, /* ^H */ /* BackSpace key */
+ /* 9 */ ED_INSERT, /* ^I */ /* Tab Key */
+ /* 10 */ ED_NEWLINE, /* ^J */
+ /* 11 */ ED_INSERT, /* ^K */
+ /* 12 */ ED_INSERT, /* ^L */
+ /* 13 */ ED_NEWLINE, /* ^M */
+ /* 14 */ ED_INSERT, /* ^N */
+ /* 15 */ ED_INSERT, /* ^O */
+ /* 16 */ ED_INSERT, /* ^P */
+ /* 17 */ ED_IGNORE, /* ^Q */
+ /* 18 */ ED_INSERT, /* ^R */
+ /* 19 */ ED_IGNORE, /* ^S */
+ /* 20 */ ED_INSERT, /* ^T */
+ /* 21 */ VI_KILL_LINE_PREV, /* ^U */
+ /* 22 */ ED_QUOTED_INSERT, /* ^V */
+ /* 23 */ ED_DELETE_PREV_WORD, /* ^W */
+ /* ED_DELETE_PREV_WORD: Only until strt edit pos */
+ /* 24 */ ED_INSERT, /* ^X */
+ /* 25 */ ED_INSERT, /* ^Y */
+ /* 26 */ ED_INSERT, /* ^Z */
+ /* 27 */ VI_COMMAND_MODE, /* ^[ */ /* [ Esc ] key */
+ /* 28 */ ED_IGNORE, /* ^\ */
+ /* 29 */ ED_INSERT, /* ^] */
+ /* 30 */ ED_INSERT, /* ^^ */
+ /* 31 */ ED_INSERT, /* ^_ */
+#else /* !KSHVI */
+ /*
+ * NOTE: These mappings do NOT Correspond well
+ * to the KSH VI editing assignments.
+ * On the other and they are convenient and
+ * many people have have gotten used to them.
+ */
+ /* 0 */ ED_UNASSIGNED, /* ^@ */
+ /* 1 */ ED_MOVE_TO_BEG, /* ^A */
+ /* 2 */ ED_PREV_CHAR, /* ^B */
+ /* 3 */ ED_IGNORE, /* ^C */
+ /* 4 */ VI_LIST_OR_EOF, /* ^D */
+ /* 5 */ ED_MOVE_TO_END, /* ^E */
+ /* 6 */ ED_NEXT_CHAR, /* ^F */
+ /* 7 */ ED_UNASSIGNED, /* ^G */
+ /* 8 */ VI_DELETE_PREV_CHAR, /* ^H */ /* BackSpace key */
+ /* 9 */ ED_UNASSIGNED, /* ^I */ /* Tab Key */
+ /* 10 */ ED_NEWLINE, /* ^J */
+ /* 11 */ ED_KILL_LINE, /* ^K */
+ /* 12 */ ED_CLEAR_SCREEN, /* ^L */
+ /* 13 */ ED_NEWLINE, /* ^M */
+ /* 14 */ ED_NEXT_HISTORY, /* ^N */
+ /* 15 */ ED_IGNORE, /* ^O */
+ /* 16 */ ED_PREV_HISTORY, /* ^P */
+ /* 17 */ ED_IGNORE, /* ^Q */
+ /* 18 */ ED_REDISPLAY, /* ^R */
+ /* 19 */ ED_IGNORE, /* ^S */
+ /* 20 */ ED_TRANSPOSE_CHARS, /* ^T */
+ /* 21 */ VI_KILL_LINE_PREV, /* ^U */
+ /* 22 */ ED_QUOTED_INSERT, /* ^V */
+ /* 23 */ ED_DELETE_PREV_WORD, /* ^W */
+ /* 24 */ ED_UNASSIGNED, /* ^X */
+ /* 25 */ ED_IGNORE, /* ^Y */
+ /* 26 */ ED_IGNORE, /* ^Z */
+ /* 27 */ VI_COMMAND_MODE, /* ^[ */
+ /* 28 */ ED_IGNORE, /* ^\ */
+ /* 29 */ ED_UNASSIGNED, /* ^] */
+ /* 30 */ ED_UNASSIGNED, /* ^^ */
+ /* 31 */ ED_UNASSIGNED, /* ^_ */
+#endif /* KSHVI */
+ /* 32 */ ED_INSERT, /* SPACE */
+ /* 33 */ ED_INSERT, /* ! */
+ /* 34 */ ED_INSERT, /* " */
+ /* 35 */ ED_INSERT, /* # */
+ /* 36 */ ED_INSERT, /* $ */
+ /* 37 */ ED_INSERT, /* % */
+ /* 38 */ ED_INSERT, /* & */
+ /* 39 */ ED_INSERT, /* ' */
+ /* 40 */ ED_INSERT, /* ( */
+ /* 41 */ ED_INSERT, /* ) */
+ /* 42 */ ED_INSERT, /* * */
+ /* 43 */ ED_INSERT, /* + */
+ /* 44 */ ED_INSERT, /* , */
+ /* 45 */ ED_INSERT, /* - */
+ /* 46 */ ED_INSERT, /* . */
+ /* 47 */ ED_INSERT, /* / */
+ /* 48 */ ED_INSERT, /* 0 */
+ /* 49 */ ED_INSERT, /* 1 */
+ /* 50 */ ED_INSERT, /* 2 */
+ /* 51 */ ED_INSERT, /* 3 */
+ /* 52 */ ED_INSERT, /* 4 */
+ /* 53 */ ED_INSERT, /* 5 */
+ /* 54 */ ED_INSERT, /* 6 */
+ /* 55 */ ED_INSERT, /* 7 */
+ /* 56 */ ED_INSERT, /* 8 */
+ /* 57 */ ED_INSERT, /* 9 */
+ /* 58 */ ED_INSERT, /* : */
+ /* 59 */ ED_INSERT, /* ; */
+ /* 60 */ ED_INSERT, /* < */
+ /* 61 */ ED_INSERT, /* = */
+ /* 62 */ ED_INSERT, /* > */
+ /* 63 */ ED_INSERT, /* ? */
+ /* 64 */ ED_INSERT, /* @ */
+ /* 65 */ ED_INSERT, /* A */
+ /* 66 */ ED_INSERT, /* B */
+ /* 67 */ ED_INSERT, /* C */
+ /* 68 */ ED_INSERT, /* D */
+ /* 69 */ ED_INSERT, /* E */
+ /* 70 */ ED_INSERT, /* F */
+ /* 71 */ ED_INSERT, /* G */
+ /* 72 */ ED_INSERT, /* H */
+ /* 73 */ ED_INSERT, /* I */
+ /* 74 */ ED_INSERT, /* J */
+ /* 75 */ ED_INSERT, /* K */
+ /* 76 */ ED_INSERT, /* L */
+ /* 77 */ ED_INSERT, /* M */
+ /* 78 */ ED_INSERT, /* N */
+ /* 79 */ ED_INSERT, /* O */
+ /* 80 */ ED_INSERT, /* P */
+ /* 81 */ ED_INSERT, /* Q */
+ /* 82 */ ED_INSERT, /* R */
+ /* 83 */ ED_INSERT, /* S */
+ /* 84 */ ED_INSERT, /* T */
+ /* 85 */ ED_INSERT, /* U */
+ /* 86 */ ED_INSERT, /* V */
+ /* 87 */ ED_INSERT, /* W */
+ /* 88 */ ED_INSERT, /* X */
+ /* 89 */ ED_INSERT, /* Y */
+ /* 90 */ ED_INSERT, /* Z */
+ /* 91 */ ED_INSERT, /* [ */
+ /* 92 */ ED_INSERT, /* \ */
+ /* 93 */ ED_INSERT, /* ] */
+ /* 94 */ ED_INSERT, /* ^ */
+ /* 95 */ ED_INSERT, /* _ */
+ /* 96 */ ED_INSERT, /* ` */
+ /* 97 */ ED_INSERT, /* a */
+ /* 98 */ ED_INSERT, /* b */
+ /* 99 */ ED_INSERT, /* c */
+ /* 100 */ ED_INSERT, /* d */
+ /* 101 */ ED_INSERT, /* e */
+ /* 102 */ ED_INSERT, /* f */
+ /* 103 */ ED_INSERT, /* g */
+ /* 104 */ ED_INSERT, /* h */
+ /* 105 */ ED_INSERT, /* i */
+ /* 106 */ ED_INSERT, /* j */
+ /* 107 */ ED_INSERT, /* k */
+ /* 108 */ ED_INSERT, /* l */
+ /* 109 */ ED_INSERT, /* m */
+ /* 110 */ ED_INSERT, /* n */
+ /* 111 */ ED_INSERT, /* o */
+ /* 112 */ ED_INSERT, /* p */
+ /* 113 */ ED_INSERT, /* q */
+ /* 114 */ ED_INSERT, /* r */
+ /* 115 */ ED_INSERT, /* s */
+ /* 116 */ ED_INSERT, /* t */
+ /* 117 */ ED_INSERT, /* u */
+ /* 118 */ ED_INSERT, /* v */
+ /* 119 */ ED_INSERT, /* w */
+ /* 120 */ ED_INSERT, /* x */
+ /* 121 */ ED_INSERT, /* y */
+ /* 122 */ ED_INSERT, /* z */
+ /* 123 */ ED_INSERT, /* { */
+ /* 124 */ ED_INSERT, /* | */
+ /* 125 */ ED_INSERT, /* } */
+ /* 126 */ ED_INSERT, /* ~ */
+ /* 127 */ VI_DELETE_PREV_CHAR, /* ^? */
+ /* 128 */ ED_INSERT, /* M-^@ */
+ /* 129 */ ED_INSERT, /* M-^A */
+ /* 130 */ ED_INSERT, /* M-^B */
+ /* 131 */ ED_INSERT, /* M-^C */
+ /* 132 */ ED_INSERT, /* M-^D */
+ /* 133 */ ED_INSERT, /* M-^E */
+ /* 134 */ ED_INSERT, /* M-^F */
+ /* 135 */ ED_INSERT, /* M-^G */
+ /* 136 */ ED_INSERT, /* M-^H */
+ /* 137 */ ED_INSERT, /* M-^I */
+ /* 138 */ ED_INSERT, /* M-^J */
+ /* 139 */ ED_INSERT, /* M-^K */
+ /* 140 */ ED_INSERT, /* M-^L */
+ /* 141 */ ED_INSERT, /* M-^M */
+ /* 142 */ ED_INSERT, /* M-^N */
+ /* 143 */ ED_INSERT, /* M-^O */
+ /* 144 */ ED_INSERT, /* M-^P */
+ /* 145 */ ED_INSERT, /* M-^Q */
+ /* 146 */ ED_INSERT, /* M-^R */
+ /* 147 */ ED_INSERT, /* M-^S */
+ /* 148 */ ED_INSERT, /* M-^T */
+ /* 149 */ ED_INSERT, /* M-^U */
+ /* 150 */ ED_INSERT, /* M-^V */
+ /* 151 */ ED_INSERT, /* M-^W */
+ /* 152 */ ED_INSERT, /* M-^X */
+ /* 153 */ ED_INSERT, /* M-^Y */
+ /* 154 */ ED_INSERT, /* M-^Z */
+ /* 155 */ ED_INSERT, /* M-^[ */
+ /* 156 */ ED_INSERT, /* M-^\ */
+ /* 157 */ ED_INSERT, /* M-^] */
+ /* 158 */ ED_INSERT, /* M-^^ */
+ /* 159 */ ED_INSERT, /* M-^_ */
+ /* 160 */ ED_INSERT, /* M-SPACE */
+ /* 161 */ ED_INSERT, /* M-! */
+ /* 162 */ ED_INSERT, /* M-" */
+ /* 163 */ ED_INSERT, /* M-# */
+ /* 164 */ ED_INSERT, /* M-$ */
+ /* 165 */ ED_INSERT, /* M-% */
+ /* 166 */ ED_INSERT, /* M-& */
+ /* 167 */ ED_INSERT, /* M-' */
+ /* 168 */ ED_INSERT, /* M-( */
+ /* 169 */ ED_INSERT, /* M-) */
+ /* 170 */ ED_INSERT, /* M-* */
+ /* 171 */ ED_INSERT, /* M-+ */
+ /* 172 */ ED_INSERT, /* M-, */
+ /* 173 */ ED_INSERT, /* M-- */
+ /* 174 */ ED_INSERT, /* M-. */
+ /* 175 */ ED_INSERT, /* M-/ */
+ /* 176 */ ED_INSERT, /* M-0 */
+ /* 177 */ ED_INSERT, /* M-1 */
+ /* 178 */ ED_INSERT, /* M-2 */
+ /* 179 */ ED_INSERT, /* M-3 */
+ /* 180 */ ED_INSERT, /* M-4 */
+ /* 181 */ ED_INSERT, /* M-5 */
+ /* 182 */ ED_INSERT, /* M-6 */
+ /* 183 */ ED_INSERT, /* M-7 */
+ /* 184 */ ED_INSERT, /* M-8 */
+ /* 185 */ ED_INSERT, /* M-9 */
+ /* 186 */ ED_INSERT, /* M-: */
+ /* 187 */ ED_INSERT, /* M-; */
+ /* 188 */ ED_INSERT, /* M-< */
+ /* 189 */ ED_INSERT, /* M-= */
+ /* 190 */ ED_INSERT, /* M-> */
+ /* 191 */ ED_INSERT, /* M-? */
+ /* 192 */ ED_INSERT, /* M-@ */
+ /* 193 */ ED_INSERT, /* M-A */
+ /* 194 */ ED_INSERT, /* M-B */
+ /* 195 */ ED_INSERT, /* M-C */
+ /* 196 */ ED_INSERT, /* M-D */
+ /* 197 */ ED_INSERT, /* M-E */
+ /* 198 */ ED_INSERT, /* M-F */
+ /* 199 */ ED_INSERT, /* M-G */
+ /* 200 */ ED_INSERT, /* M-H */
+ /* 201 */ ED_INSERT, /* M-I */
+ /* 202 */ ED_INSERT, /* M-J */
+ /* 203 */ ED_INSERT, /* M-K */
+ /* 204 */ ED_INSERT, /* M-L */
+ /* 205 */ ED_INSERT, /* M-M */
+ /* 206 */ ED_INSERT, /* M-N */
+ /* 207 */ ED_INSERT, /* M-O */
+ /* 208 */ ED_INSERT, /* M-P */
+ /* 209 */ ED_INSERT, /* M-Q */
+ /* 210 */ ED_INSERT, /* M-R */
+ /* 211 */ ED_INSERT, /* M-S */
+ /* 212 */ ED_INSERT, /* M-T */
+ /* 213 */ ED_INSERT, /* M-U */
+ /* 214 */ ED_INSERT, /* M-V */
+ /* 215 */ ED_INSERT, /* M-W */
+ /* 216 */ ED_INSERT, /* M-X */
+ /* 217 */ ED_INSERT, /* M-Y */
+ /* 218 */ ED_INSERT, /* M-Z */
+ /* 219 */ ED_INSERT, /* M-[ */
+ /* 220 */ ED_INSERT, /* M-\ */
+ /* 221 */ ED_INSERT, /* M-] */
+ /* 222 */ ED_INSERT, /* M-^ */
+ /* 223 */ ED_INSERT, /* M-_ */
+ /* 224 */ ED_INSERT, /* M-` */
+ /* 225 */ ED_INSERT, /* M-a */
+ /* 226 */ ED_INSERT, /* M-b */
+ /* 227 */ ED_INSERT, /* M-c */
+ /* 228 */ ED_INSERT, /* M-d */
+ /* 229 */ ED_INSERT, /* M-e */
+ /* 230 */ ED_INSERT, /* M-f */
+ /* 231 */ ED_INSERT, /* M-g */
+ /* 232 */ ED_INSERT, /* M-h */
+ /* 233 */ ED_INSERT, /* M-i */
+ /* 234 */ ED_INSERT, /* M-j */
+ /* 235 */ ED_INSERT, /* M-k */
+ /* 236 */ ED_INSERT, /* M-l */
+ /* 237 */ ED_INSERT, /* M-m */
+ /* 238 */ ED_INSERT, /* M-n */
+ /* 239 */ ED_INSERT, /* M-o */
+ /* 240 */ ED_INSERT, /* M-p */
+ /* 241 */ ED_INSERT, /* M-q */
+ /* 242 */ ED_INSERT, /* M-r */
+ /* 243 */ ED_INSERT, /* M-s */
+ /* 244 */ ED_INSERT, /* M-t */
+ /* 245 */ ED_INSERT, /* M-u */
+ /* 246 */ ED_INSERT, /* M-v */
+ /* 247 */ ED_INSERT, /* M-w */
+ /* 248 */ ED_INSERT, /* M-x */
+ /* 249 */ ED_INSERT, /* M-y */
+ /* 250 */ ED_INSERT, /* M-z */
+ /* 251 */ ED_INSERT, /* M-{ */
+ /* 252 */ ED_INSERT, /* M-| */
+ /* 253 */ ED_INSERT, /* M-} */
+ /* 254 */ ED_INSERT, /* M-~ */
+ /* 255 */ ED_INSERT /* M-^? */
+};
+
+static const el_action_t el_map_vi_command[] = {
+ /* 0 */ ED_UNASSIGNED, /* ^@ */
+ /* 1 */ ED_MOVE_TO_BEG, /* ^A */
+ /* 2 */ ED_UNASSIGNED, /* ^B */
+ /* 3 */ ED_IGNORE, /* ^C */
+ /* 4 */ ED_UNASSIGNED, /* ^D */
+ /* 5 */ ED_MOVE_TO_END, /* ^E */
+ /* 6 */ ED_UNASSIGNED, /* ^F */
+ /* 7 */ ED_UNASSIGNED, /* ^G */
+ /* 8 */ ED_DELETE_PREV_CHAR, /* ^H */
+ /* 9 */ ED_UNASSIGNED, /* ^I */
+ /* 10 */ ED_NEWLINE, /* ^J */
+ /* 11 */ ED_KILL_LINE, /* ^K */
+ /* 12 */ ED_CLEAR_SCREEN, /* ^L */
+ /* 13 */ ED_NEWLINE, /* ^M */
+ /* 14 */ ED_NEXT_HISTORY, /* ^N */
+ /* 15 */ ED_IGNORE, /* ^O */
+ /* 16 */ ED_PREV_HISTORY, /* ^P */
+ /* 17 */ ED_IGNORE, /* ^Q */
+ /* 18 */ ED_REDISPLAY, /* ^R */
+ /* 19 */ ED_IGNORE, /* ^S */
+ /* 20 */ ED_UNASSIGNED, /* ^T */
+ /* 21 */ VI_KILL_LINE_PREV, /* ^U */
+ /* 22 */ ED_UNASSIGNED, /* ^V */
+ /* 23 */ ED_DELETE_PREV_WORD, /* ^W */
+ /* 24 */ ED_UNASSIGNED, /* ^X */
+ /* 25 */ ED_UNASSIGNED, /* ^Y */
+ /* 26 */ ED_UNASSIGNED, /* ^Z */
+ /* 27 */ EM_META_NEXT, /* ^[ */
+ /* 28 */ ED_IGNORE, /* ^\ */
+ /* 29 */ ED_UNASSIGNED, /* ^] */
+ /* 30 */ ED_UNASSIGNED, /* ^^ */
+ /* 31 */ ED_UNASSIGNED, /* ^_ */
+ /* 32 */ ED_NEXT_CHAR, /* SPACE */
+ /* 33 */ ED_UNASSIGNED, /* ! */
+ /* 34 */ ED_UNASSIGNED, /* " */
+ /* 35 */ VI_COMMENT_OUT, /* # */
+ /* 36 */ ED_MOVE_TO_END, /* $ */
+ /* 37 */ VI_MATCH, /* % */
+ /* 38 */ ED_UNASSIGNED, /* & */
+ /* 39 */ ED_UNASSIGNED, /* ' */
+ /* 40 */ ED_UNASSIGNED, /* ( */
+ /* 41 */ ED_UNASSIGNED, /* ) */
+ /* 42 */ ED_UNASSIGNED, /* * */
+ /* 43 */ ED_NEXT_HISTORY, /* + */
+ /* 44 */ VI_REPEAT_PREV_CHAR, /* , */
+ /* 45 */ ED_PREV_HISTORY, /* - */
+ /* 46 */ VI_REDO, /* . */
+ /* 47 */ VI_SEARCH_PREV, /* / */
+ /* 48 */ VI_ZERO, /* 0 */
+ /* 49 */ ED_ARGUMENT_DIGIT, /* 1 */
+ /* 50 */ ED_ARGUMENT_DIGIT, /* 2 */
+ /* 51 */ ED_ARGUMENT_DIGIT, /* 3 */
+ /* 52 */ ED_ARGUMENT_DIGIT, /* 4 */
+ /* 53 */ ED_ARGUMENT_DIGIT, /* 5 */
+ /* 54 */ ED_ARGUMENT_DIGIT, /* 6 */
+ /* 55 */ ED_ARGUMENT_DIGIT, /* 7 */
+ /* 56 */ ED_ARGUMENT_DIGIT, /* 8 */
+ /* 57 */ ED_ARGUMENT_DIGIT, /* 9 */
+ /* 58 */ ED_COMMAND, /* : */
+ /* 59 */ VI_REPEAT_NEXT_CHAR, /* ; */
+ /* 60 */ ED_UNASSIGNED, /* < */
+ /* 61 */ ED_UNASSIGNED, /* = */
+ /* 62 */ ED_UNASSIGNED, /* > */
+ /* 63 */ VI_SEARCH_NEXT, /* ? */
+ /* 64 */ VI_ALIAS, /* @ */
+ /* 65 */ VI_ADD_AT_EOL, /* A */
+ /* 66 */ VI_PREV_BIG_WORD, /* B */
+ /* 67 */ VI_CHANGE_TO_EOL, /* C */
+ /* 68 */ ED_KILL_LINE, /* D */
+ /* 69 */ VI_END_BIG_WORD, /* E */
+ /* 70 */ VI_PREV_CHAR, /* F */
+ /* 71 */ VI_TO_HISTORY_LINE, /* G */
+ /* 72 */ ED_UNASSIGNED, /* H */
+ /* 73 */ VI_INSERT_AT_BOL, /* I */
+ /* 74 */ ED_SEARCH_NEXT_HISTORY, /* J */
+ /* 75 */ ED_SEARCH_PREV_HISTORY, /* K */
+ /* 76 */ ED_UNASSIGNED, /* L */
+ /* 77 */ ED_UNASSIGNED, /* M */
+ /* 78 */ VI_REPEAT_SEARCH_PREV, /* N */
+ /* 79 */ ED_SEQUENCE_LEAD_IN, /* O */
+ /* 80 */ VI_PASTE_PREV, /* P */
+ /* 81 */ ED_UNASSIGNED, /* Q */
+ /* 82 */ VI_REPLACE_MODE, /* R */
+ /* 83 */ VI_SUBSTITUTE_LINE, /* S */
+ /* 84 */ VI_TO_PREV_CHAR, /* T */
+ /* 85 */ VI_UNDO_LINE, /* U */
+ /* 86 */ ED_UNASSIGNED, /* V */
+ /* 87 */ VI_NEXT_BIG_WORD, /* W */
+ /* 88 */ ED_DELETE_PREV_CHAR, /* X */
+ /* 89 */ VI_YANK_END, /* Y */
+ /* 90 */ ED_UNASSIGNED, /* Z */
+ /* 91 */ ED_SEQUENCE_LEAD_IN, /* [ */
+ /* 92 */ ED_UNASSIGNED, /* \ */
+ /* 93 */ ED_UNASSIGNED, /* ] */
+ /* 94 */ ED_MOVE_TO_BEG, /* ^ */
+ /* 95 */ VI_HISTORY_WORD, /* _ */
+ /* 96 */ ED_UNASSIGNED, /* ` */
+ /* 97 */ VI_ADD, /* a */
+ /* 98 */ VI_PREV_WORD, /* b */
+ /* 99 */ VI_CHANGE_META, /* c */
+ /* 100 */ VI_DELETE_META, /* d */
+ /* 101 */ VI_END_WORD, /* e */
+ /* 102 */ VI_NEXT_CHAR, /* f */
+ /* 103 */ ED_UNASSIGNED, /* g */
+ /* 104 */ ED_PREV_CHAR, /* h */
+ /* 105 */ VI_INSERT, /* i */
+ /* 106 */ ED_NEXT_HISTORY, /* j */
+ /* 107 */ ED_PREV_HISTORY, /* k */
+ /* 108 */ ED_NEXT_CHAR, /* l */
+ /* 109 */ ED_UNASSIGNED, /* m */
+ /* 110 */ VI_REPEAT_SEARCH_NEXT, /* n */
+ /* 111 */ ED_UNASSIGNED, /* o */
+ /* 112 */ VI_PASTE_NEXT, /* p */
+ /* 113 */ ED_UNASSIGNED, /* q */
+ /* 114 */ VI_REPLACE_CHAR, /* r */
+ /* 115 */ VI_SUBSTITUTE_CHAR, /* s */
+ /* 116 */ VI_TO_NEXT_CHAR, /* t */
+ /* 117 */ VI_UNDO, /* u */
+ /* 118 */ VI_HISTEDIT, /* v */
+ /* 119 */ VI_NEXT_WORD, /* w */
+ /* 120 */ ED_DELETE_NEXT_CHAR, /* x */
+ /* 121 */ VI_YANK, /* y */
+ /* 122 */ ED_UNASSIGNED, /* z */
+ /* 123 */ ED_UNASSIGNED, /* { */
+ /* 124 */ VI_TO_COLUMN, /* | */
+ /* 125 */ ED_UNASSIGNED, /* } */
+ /* 126 */ VI_CHANGE_CASE, /* ~ */
+ /* 127 */ ED_DELETE_PREV_CHAR, /* ^? */
+ /* 128 */ ED_UNASSIGNED, /* M-^@ */
+ /* 129 */ ED_UNASSIGNED, /* M-^A */
+ /* 130 */ ED_UNASSIGNED, /* M-^B */
+ /* 131 */ ED_UNASSIGNED, /* M-^C */
+ /* 132 */ ED_UNASSIGNED, /* M-^D */
+ /* 133 */ ED_UNASSIGNED, /* M-^E */
+ /* 134 */ ED_UNASSIGNED, /* M-^F */
+ /* 135 */ ED_UNASSIGNED, /* M-^G */
+ /* 136 */ ED_UNASSIGNED, /* M-^H */
+ /* 137 */ ED_UNASSIGNED, /* M-^I */
+ /* 138 */ ED_UNASSIGNED, /* M-^J */
+ /* 139 */ ED_UNASSIGNED, /* M-^K */
+ /* 140 */ ED_UNASSIGNED, /* M-^L */
+ /* 141 */ ED_UNASSIGNED, /* M-^M */
+ /* 142 */ ED_UNASSIGNED, /* M-^N */
+ /* 143 */ ED_UNASSIGNED, /* M-^O */
+ /* 144 */ ED_UNASSIGNED, /* M-^P */
+ /* 145 */ ED_UNASSIGNED, /* M-^Q */
+ /* 146 */ ED_UNASSIGNED, /* M-^R */
+ /* 147 */ ED_UNASSIGNED, /* M-^S */
+ /* 148 */ ED_UNASSIGNED, /* M-^T */
+ /* 149 */ ED_UNASSIGNED, /* M-^U */
+ /* 150 */ ED_UNASSIGNED, /* M-^V */
+ /* 151 */ ED_UNASSIGNED, /* M-^W */
+ /* 152 */ ED_UNASSIGNED, /* M-^X */
+ /* 153 */ ED_UNASSIGNED, /* M-^Y */
+ /* 154 */ ED_UNASSIGNED, /* M-^Z */
+ /* 155 */ ED_UNASSIGNED, /* M-^[ */
+ /* 156 */ ED_UNASSIGNED, /* M-^\ */
+ /* 157 */ ED_UNASSIGNED, /* M-^] */
+ /* 158 */ ED_UNASSIGNED, /* M-^^ */
+ /* 159 */ ED_UNASSIGNED, /* M-^_ */
+ /* 160 */ ED_UNASSIGNED, /* M-SPACE */
+ /* 161 */ ED_UNASSIGNED, /* M-! */
+ /* 162 */ ED_UNASSIGNED, /* M-" */
+ /* 163 */ ED_UNASSIGNED, /* M-# */
+ /* 164 */ ED_UNASSIGNED, /* M-$ */
+ /* 165 */ ED_UNASSIGNED, /* M-% */
+ /* 166 */ ED_UNASSIGNED, /* M-& */
+ /* 167 */ ED_UNASSIGNED, /* M-' */
+ /* 168 */ ED_UNASSIGNED, /* M-( */
+ /* 169 */ ED_UNASSIGNED, /* M-) */
+ /* 170 */ ED_UNASSIGNED, /* M-* */
+ /* 171 */ ED_UNASSIGNED, /* M-+ */
+ /* 172 */ ED_UNASSIGNED, /* M-, */
+ /* 173 */ ED_UNASSIGNED, /* M-- */
+ /* 174 */ ED_UNASSIGNED, /* M-. */
+ /* 175 */ ED_UNASSIGNED, /* M-/ */
+ /* 176 */ ED_UNASSIGNED, /* M-0 */
+ /* 177 */ ED_UNASSIGNED, /* M-1 */
+ /* 178 */ ED_UNASSIGNED, /* M-2 */
+ /* 179 */ ED_UNASSIGNED, /* M-3 */
+ /* 180 */ ED_UNASSIGNED, /* M-4 */
+ /* 181 */ ED_UNASSIGNED, /* M-5 */
+ /* 182 */ ED_UNASSIGNED, /* M-6 */
+ /* 183 */ ED_UNASSIGNED, /* M-7 */
+ /* 184 */ ED_UNASSIGNED, /* M-8 */
+ /* 185 */ ED_UNASSIGNED, /* M-9 */
+ /* 186 */ ED_UNASSIGNED, /* M-: */
+ /* 187 */ ED_UNASSIGNED, /* M-; */
+ /* 188 */ ED_UNASSIGNED, /* M-< */
+ /* 189 */ ED_UNASSIGNED, /* M-= */
+ /* 190 */ ED_UNASSIGNED, /* M-> */
+ /* 191 */ ED_UNASSIGNED, /* M-? */
+ /* 192 */ ED_UNASSIGNED, /* M-@ */
+ /* 193 */ ED_UNASSIGNED, /* M-A */
+ /* 194 */ ED_UNASSIGNED, /* M-B */
+ /* 195 */ ED_UNASSIGNED, /* M-C */
+ /* 196 */ ED_UNASSIGNED, /* M-D */
+ /* 197 */ ED_UNASSIGNED, /* M-E */
+ /* 198 */ ED_UNASSIGNED, /* M-F */
+ /* 199 */ ED_UNASSIGNED, /* M-G */
+ /* 200 */ ED_UNASSIGNED, /* M-H */
+ /* 201 */ ED_UNASSIGNED, /* M-I */
+ /* 202 */ ED_UNASSIGNED, /* M-J */
+ /* 203 */ ED_UNASSIGNED, /* M-K */
+ /* 204 */ ED_UNASSIGNED, /* M-L */
+ /* 205 */ ED_UNASSIGNED, /* M-M */
+ /* 206 */ ED_UNASSIGNED, /* M-N */
+ /* 207 */ ED_SEQUENCE_LEAD_IN, /* M-O */
+ /* 208 */ ED_UNASSIGNED, /* M-P */
+ /* 209 */ ED_UNASSIGNED, /* M-Q */
+ /* 210 */ ED_UNASSIGNED, /* M-R */
+ /* 211 */ ED_UNASSIGNED, /* M-S */
+ /* 212 */ ED_UNASSIGNED, /* M-T */
+ /* 213 */ ED_UNASSIGNED, /* M-U */
+ /* 214 */ ED_UNASSIGNED, /* M-V */
+ /* 215 */ ED_UNASSIGNED, /* M-W */
+ /* 216 */ ED_UNASSIGNED, /* M-X */
+ /* 217 */ ED_UNASSIGNED, /* M-Y */
+ /* 218 */ ED_UNASSIGNED, /* M-Z */
+ /* 219 */ ED_SEQUENCE_LEAD_IN, /* M-[ */
+ /* 220 */ ED_UNASSIGNED, /* M-\ */
+ /* 221 */ ED_UNASSIGNED, /* M-] */
+ /* 222 */ ED_UNASSIGNED, /* M-^ */
+ /* 223 */ ED_UNASSIGNED, /* M-_ */
+ /* 224 */ ED_UNASSIGNED, /* M-` */
+ /* 225 */ ED_UNASSIGNED, /* M-a */
+ /* 226 */ ED_UNASSIGNED, /* M-b */
+ /* 227 */ ED_UNASSIGNED, /* M-c */
+ /* 228 */ ED_UNASSIGNED, /* M-d */
+ /* 229 */ ED_UNASSIGNED, /* M-e */
+ /* 230 */ ED_UNASSIGNED, /* M-f */
+ /* 231 */ ED_UNASSIGNED, /* M-g */
+ /* 232 */ ED_UNASSIGNED, /* M-h */
+ /* 233 */ ED_UNASSIGNED, /* M-i */
+ /* 234 */ ED_UNASSIGNED, /* M-j */
+ /* 235 */ ED_UNASSIGNED, /* M-k */
+ /* 236 */ ED_UNASSIGNED, /* M-l */
+ /* 237 */ ED_UNASSIGNED, /* M-m */
+ /* 238 */ ED_UNASSIGNED, /* M-n */
+ /* 239 */ ED_UNASSIGNED, /* M-o */
+ /* 240 */ ED_UNASSIGNED, /* M-p */
+ /* 241 */ ED_UNASSIGNED, /* M-q */
+ /* 242 */ ED_UNASSIGNED, /* M-r */
+ /* 243 */ ED_UNASSIGNED, /* M-s */
+ /* 244 */ ED_UNASSIGNED, /* M-t */
+ /* 245 */ ED_UNASSIGNED, /* M-u */
+ /* 246 */ ED_UNASSIGNED, /* M-v */
+ /* 247 */ ED_UNASSIGNED, /* M-w */
+ /* 248 */ ED_UNASSIGNED, /* M-x */
+ /* 249 */ ED_UNASSIGNED, /* M-y */
+ /* 250 */ ED_UNASSIGNED, /* M-z */
+ /* 251 */ ED_UNASSIGNED, /* M-{ */
+ /* 252 */ ED_UNASSIGNED, /* M-| */
+ /* 253 */ ED_UNASSIGNED, /* M-} */
+ /* 254 */ ED_UNASSIGNED, /* M-~ */
+ /* 255 */ ED_UNASSIGNED /* M-^? */
+};
+
+
+/* map_init():
+ * Initialize and allocate the maps
+ */
+libedit_private int
+map_init(EditLine *el)
+{
+
+ /*
+ * Make sure those are correct before starting.
+ */
+#ifdef MAP_DEBUG
+ if (sizeof(el_map_emacs) != N_KEYS * sizeof(el_action_t))
+ EL_ABORT((el->errfile, "Emacs map incorrect\n"));
+ if (sizeof(el_map_vi_command) != N_KEYS * sizeof(el_action_t))
+ EL_ABORT((el->errfile, "Vi command map incorrect\n"));
+ if (sizeof(el_map_vi_insert) != N_KEYS * sizeof(el_action_t))
+ EL_ABORT((el->errfile, "Vi insert map incorrect\n"));
+#endif
+
+ el->el_map.alt = el_malloc(sizeof(*el->el_map.alt) * N_KEYS);
+ if (el->el_map.alt == NULL)
+ return -1;
+ el->el_map.key = el_malloc(sizeof(*el->el_map.key) * N_KEYS);
+ if (el->el_map.key == NULL)
+ return -1;
+ el->el_map.emacs = el_map_emacs;
+ el->el_map.vic = el_map_vi_command;
+ el->el_map.vii = el_map_vi_insert;
+ el->el_map.help = el_malloc(sizeof(*el->el_map.help) * EL_NUM_FCNS);
+ if (el->el_map.help == NULL)
+ return -1;
+ (void) memcpy(el->el_map.help, el_func_help,
+ sizeof(*el->el_map.help) * EL_NUM_FCNS);
+ el->el_map.func = el_malloc(sizeof(*el->el_map.func) * EL_NUM_FCNS);
+ if (el->el_map.func == NULL)
+ return -1;
+ memcpy(el->el_map.func, el_func, sizeof(*el->el_map.func)
+ * EL_NUM_FCNS);
+ el->el_map.nfunc = EL_NUM_FCNS;
+
+#ifdef VIDEFAULT
+ map_init_vi(el);
+#else
+ map_init_emacs(el);
+#endif /* VIDEFAULT */
+ return 0;
+}
+
+
+/* map_end():
+ * Free the space taken by the editor maps
+ */
+libedit_private void
+map_end(EditLine *el)
+{
+
+ el_free(el->el_map.alt);
+ el->el_map.alt = NULL;
+ el_free(el->el_map.key);
+ el->el_map.key = NULL;
+ el->el_map.emacs = NULL;
+ el->el_map.vic = NULL;
+ el->el_map.vii = NULL;
+ el_free(el->el_map.help);
+ el->el_map.help = NULL;
+ el_free(el->el_map.func);
+ el->el_map.func = NULL;
+}
+
+
+/* map_init_nls():
+ * Find all the printable keys and bind them to self insert
+ */
+static void
+map_init_nls(EditLine *el)
+{
+ int i;
+
+ el_action_t *map = el->el_map.key;
+
+ for (i = 0200; i <= 0377; i++)
+ if (iswprint(i))
+ map[i] = ED_INSERT;
+}
+
+
+/* map_init_meta():
+ * Bind all the meta keys to the appropriate ESC-<key> sequence
+ */
+static void
+map_init_meta(EditLine *el)
+{
+ wchar_t buf[3];
+ int i;
+ el_action_t *map = el->el_map.key;
+ el_action_t *alt = el->el_map.alt;
+
+ for (i = 0; i <= 0377 && map[i] != EM_META_NEXT; i++)
+ continue;
+
+ if (i > 0377) {
+ for (i = 0; i <= 0377 && alt[i] != EM_META_NEXT; i++)
+ continue;
+ if (i > 0377) {
+ i = 033;
+ if (el->el_map.type == MAP_VI)
+ map = alt;
+ } else
+ map = alt;
+ }
+ buf[0] = (wchar_t)i;
+ buf[2] = 0;
+ for (i = 0200; i <= 0377; i++)
+ switch (map[i]) {
+ case ED_INSERT:
+ case ED_UNASSIGNED:
+ case ED_SEQUENCE_LEAD_IN:
+ break;
+ default:
+ buf[1] = i & 0177;
+ keymacro_add(el, buf, keymacro_map_cmd(el, (int) map[i]), XK_CMD);
+ break;
+ }
+ map[(int) buf[0]] = ED_SEQUENCE_LEAD_IN;
+}
+
+
+/* map_init_vi():
+ * Initialize the vi bindings
+ */
+libedit_private void
+map_init_vi(EditLine *el)
+{
+ int i;
+ el_action_t *key = el->el_map.key;
+ el_action_t *alt = el->el_map.alt;
+ const el_action_t *vii = el->el_map.vii;
+ const el_action_t *vic = el->el_map.vic;
+
+ el->el_map.type = MAP_VI;
+ el->el_map.current = el->el_map.key;
+
+ keymacro_reset(el);
+
+ for (i = 0; i < N_KEYS; i++) {
+ key[i] = vii[i];
+ alt[i] = vic[i];
+ }
+
+ map_init_meta(el);
+ map_init_nls(el);
+
+ tty_bind_char(el, 1);
+ terminal_bind_arrow(el);
+}
+
+
+/* map_init_emacs():
+ * Initialize the emacs bindings
+ */
+libedit_private void
+map_init_emacs(EditLine *el)
+{
+ int i;
+ wchar_t buf[3];
+ el_action_t *key = el->el_map.key;
+ el_action_t *alt = el->el_map.alt;
+ const el_action_t *emacs = el->el_map.emacs;
+
+ el->el_map.type = MAP_EMACS;
+ el->el_map.current = el->el_map.key;
+ keymacro_reset(el);
+
+ for (i = 0; i < N_KEYS; i++) {
+ key[i] = emacs[i];
+ alt[i] = ED_UNASSIGNED;
+ }
+
+ map_init_meta(el);
+ map_init_nls(el);
+
+ buf[0] = CONTROL('X');
+ buf[1] = CONTROL('X');
+ buf[2] = 0;
+ keymacro_add(el, buf, keymacro_map_cmd(el, EM_EXCHANGE_MARK), XK_CMD);
+
+ tty_bind_char(el, 1);
+ terminal_bind_arrow(el);
+}
+
+
+/* map_set_editor():
+ * Set the editor
+ */
+libedit_private int
+map_set_editor(EditLine *el, wchar_t *editor)
+{
+
+ if (wcscmp(editor, L"emacs") == 0) {
+ map_init_emacs(el);
+ return 0;
+ }
+ if (wcscmp(editor, L"vi") == 0) {
+ map_init_vi(el);
+ return 0;
+ }
+ return -1;
+}
+
+
+/* map_get_editor():
+ * Retrieve the editor
+ */
+libedit_private int
+map_get_editor(EditLine *el, const wchar_t **editor)
+{
+
+ if (editor == NULL)
+ return -1;
+ switch (el->el_map.type) {
+ case MAP_EMACS:
+ *editor = L"emacs";
+ return 0;
+ case MAP_VI:
+ *editor = L"vi";
+ return 0;
+ }
+ return -1;
+}
+
+
+/* map_print_key():
+ * Print the function description for 1 key
+ */
+static void
+map_print_key(EditLine *el, el_action_t *map, const wchar_t *in)
+{
+ char outbuf[EL_BUFSIZ];
+ el_bindings_t *bp, *ep;
+
+ if (in[0] == '\0' || in[1] == '\0') {
+ (void) keymacro__decode_str(in, outbuf, sizeof(outbuf), "");
+ ep = &el->el_map.help[el->el_map.nfunc];
+ for (bp = el->el_map.help; bp < ep; bp++)
+ if (bp->func == map[(unsigned char) *in]) {
+ (void) fprintf(el->el_outfile,
+ "%s\t->\t%ls\n", outbuf, bp->name);
+ return;
+ }
+ } else
+ keymacro_print(el, in);
+}
+
+
+/* map_print_some_keys():
+ * Print keys from first to last
+ */
+static void
+map_print_some_keys(EditLine *el, el_action_t *map, wint_t first, wint_t last)
+{
+ el_bindings_t *bp, *ep;
+ wchar_t firstbuf[2], lastbuf[2];
+ char unparsbuf[EL_BUFSIZ], extrabuf[EL_BUFSIZ];
+
+ firstbuf[0] = first;
+ firstbuf[1] = 0;
+ lastbuf[0] = last;
+ lastbuf[1] = 0;
+ if (map[first] == ED_UNASSIGNED) {
+ if (first == last) {
+ (void) keymacro__decode_str(firstbuf, unparsbuf,
+ sizeof(unparsbuf), STRQQ);
+ (void) fprintf(el->el_outfile,
+ "%-15s-> is undefined\n", unparsbuf);
+ }
+ return;
+ }
+ ep = &el->el_map.help[el->el_map.nfunc];
+ for (bp = el->el_map.help; bp < ep; bp++) {
+ if (bp->func == map[first]) {
+ if (first == last) {
+ (void) keymacro__decode_str(firstbuf, unparsbuf,
+ sizeof(unparsbuf), STRQQ);
+ (void) fprintf(el->el_outfile, "%-15s-> %ls\n",
+ unparsbuf, bp->name);
+ } else {
+ (void) keymacro__decode_str(firstbuf, unparsbuf,
+ sizeof(unparsbuf), STRQQ);
+ (void) keymacro__decode_str(lastbuf, extrabuf,
+ sizeof(extrabuf), STRQQ);
+ (void) fprintf(el->el_outfile,
+ "%-4s to %-7s-> %ls\n",
+ unparsbuf, extrabuf, bp->name);
+ }
+ return;
+ }
+ }
+#ifdef MAP_DEBUG
+ if (map == el->el_map.key) {
+ (void) keymacro__decode_str(firstbuf, unparsbuf,
+ sizeof(unparsbuf), STRQQ);
+ (void) fprintf(el->el_outfile,
+ "BUG!!! %s isn't bound to anything.\n", unparsbuf);
+ (void) fprintf(el->el_outfile, "el->el_map.key[%d] == %d\n",
+ first, el->el_map.key[first]);
+ } else {
+ (void) keymacro__decode_str(firstbuf, unparsbuf,
+ sizeof(unparsbuf), STRQQ);
+ (void) fprintf(el->el_outfile,
+ "BUG!!! %s isn't bound to anything.\n", unparsbuf);
+ (void) fprintf(el->el_outfile, "el->el_map.alt[%d] == %d\n",
+ first, el->el_map.alt[first]);
+ }
+#endif
+ EL_ABORT((el->el_errfile, "Error printing keys\n"));
+}
+
+
+/* map_print_all_keys():
+ * Print the function description for all keys.
+ */
+static void
+map_print_all_keys(EditLine *el)
+{
+ int prev, i;
+
+ (void) fprintf(el->el_outfile, "Standard key bindings\n");
+ prev = 0;
+ for (i = 0; i < N_KEYS; i++) {
+ if (el->el_map.key[prev] == el->el_map.key[i])
+ continue;
+ map_print_some_keys(el, el->el_map.key, prev, i - 1);
+ prev = i;
+ }
+ map_print_some_keys(el, el->el_map.key, prev, i - 1);
+
+ (void) fprintf(el->el_outfile, "Alternative key bindings\n");
+ prev = 0;
+ for (i = 0; i < N_KEYS; i++) {
+ if (el->el_map.alt[prev] == el->el_map.alt[i])
+ continue;
+ map_print_some_keys(el, el->el_map.alt, prev, i - 1);
+ prev = i;
+ }
+ map_print_some_keys(el, el->el_map.alt, prev, i - 1);
+
+ (void) fprintf(el->el_outfile, "Multi-character bindings\n");
+ keymacro_print(el, L"");
+ (void) fprintf(el->el_outfile, "Arrow key bindings\n");
+ terminal_print_arrow(el, L"");
+}
+
+
+/* map_bind():
+ * Add/remove/change bindings
+ */
+libedit_private int
+map_bind(EditLine *el, int argc, const wchar_t **argv)
+{
+ el_action_t *map;
+ int ntype, rem;
+ const wchar_t *p;
+ wchar_t inbuf[EL_BUFSIZ];
+ wchar_t outbuf[EL_BUFSIZ];
+ const wchar_t *in = NULL;
+ wchar_t *out;
+ el_bindings_t *bp, *ep;
+ int cmd;
+ int key;
+
+ if (argv == NULL)
+ return -1;
+
+ map = el->el_map.key;
+ ntype = XK_CMD;
+ key = rem = 0;
+ for (argc = 1; (p = argv[argc]) != NULL; argc++)
+ if (p[0] == '-')
+ switch (p[1]) {
+ case 'a':
+ map = el->el_map.alt;
+ break;
+
+ case 's':
+ ntype = XK_STR;
+ break;
+ case 'k':
+ key = 1;
+ break;
+
+ case 'r':
+ rem = 1;
+ break;
+
+ case 'v':
+ map_init_vi(el);
+ return 0;
+
+ case 'e':
+ map_init_emacs(el);
+ return 0;
+
+ case 'l':
+ ep = &el->el_map.help[el->el_map.nfunc];
+ for (bp = el->el_map.help; bp < ep; bp++)
+ (void) fprintf(el->el_outfile,
+ "%ls\n\t%ls\n",
+ bp->name, bp->description);
+ return 0;
+ default:
+ (void) fprintf(el->el_errfile,
+ "%ls: Invalid switch `%lc'.\n",
+ argv[0], (wint_t)p[1]);
+ }
+ else
+ break;
+
+ if (argv[argc] == NULL) {
+ map_print_all_keys(el);
+ return 0;
+ }
+ if (key)
+ in = argv[argc++];
+ else if ((in = parse__string(inbuf, argv[argc++])) == NULL) {
+ (void) fprintf(el->el_errfile,
+ "%ls: Invalid \\ or ^ in instring.\n",
+ argv[0]);
+ return -1;
+ }
+ if (rem) {
+ if (key) {
+ (void) terminal_clear_arrow(el, in);
+ return -1;
+ }
+ if (in[1])
+ (void) keymacro_delete(el, in);
+ else if (map[(unsigned char) *in] == ED_SEQUENCE_LEAD_IN)
+ (void) keymacro_delete(el, in);
+ else
+ map[(unsigned char) *in] = ED_UNASSIGNED;
+ return 0;
+ }
+ if (argv[argc] == NULL) {
+ if (key)
+ terminal_print_arrow(el, in);
+ else
+ map_print_key(el, map, in);
+ return 0;
+ }
+#ifdef notyet
+ if (argv[argc + 1] != NULL) {
+ bindkeymacro_usage();
+ return -1;
+ }
+#endif
+
+ switch (ntype) {
+ case XK_STR:
+ if ((out = parse__string(outbuf, argv[argc])) == NULL) {
+ (void) fprintf(el->el_errfile,
+ "%ls: Invalid \\ or ^ in outstring.\n", argv[0]);
+ return -1;
+ }
+ if (key)
+ terminal_set_arrow(el, in, keymacro_map_str(el, out), ntype);
+ else
+ keymacro_add(el, in, keymacro_map_str(el, out), ntype);
+ map[(unsigned char) *in] = ED_SEQUENCE_LEAD_IN;
+ break;
+
+ case XK_CMD:
+ if ((cmd = parse_cmd(el, argv[argc])) == -1) {
+ (void) fprintf(el->el_errfile,
+ "%ls: Invalid command `%ls'.\n",
+ argv[0], argv[argc]);
+ return -1;
+ }
+ if (key)
+ terminal_set_arrow(el, in, keymacro_map_cmd(el, cmd), ntype);
+ else {
+ if (in[1]) {
+ keymacro_add(el, in, keymacro_map_cmd(el, cmd), ntype);
+ map[(unsigned char) *in] = ED_SEQUENCE_LEAD_IN;
+ } else {
+ keymacro_clear(el, map, in);
+ map[(unsigned char) *in] = (el_action_t)cmd;
+ }
+ }
+ break;
+
+ /* coverity[dead_error_begin] */
+ default:
+ EL_ABORT((el->el_errfile, "Bad XK_ type %d\n", ntype));
+ break;
+ }
+ return 0;
+}
+
+
+/* map_addfunc():
+ * add a user defined function
+ */
+libedit_private int
+map_addfunc(EditLine *el, const wchar_t *name, const wchar_t *help,
+ el_func_t func)
+{
+ void *p;
+ size_t nf = el->el_map.nfunc + 1;
+
+ if (name == NULL || help == NULL || func == NULL)
+ return -1;
+
+ if ((p = el_realloc(el->el_map.func, nf *
+ sizeof(*el->el_map.func))) == NULL)
+ return -1;
+ el->el_map.func = p;
+ if ((p = el_realloc(el->el_map.help, nf * sizeof(*el->el_map.help)))
+ == NULL)
+ return -1;
+ el->el_map.help = p;
+
+ nf = (size_t)el->el_map.nfunc;
+ el->el_map.func[nf] = func;
+
+ el->el_map.help[nf].name = name;
+ el->el_map.help[nf].func = (int)nf;
+ el->el_map.help[nf].description = help;
+ el->el_map.nfunc++;
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/libedit/src/map.h b/third_party/heimdal/lib/libedit/src/map.h
new file mode 100644
index 0000000..b4e4e28
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/map.h
@@ -0,0 +1,79 @@
+/* $NetBSD: map.h,v 1.13 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)map.h 8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * el.map.h: Editor maps
+ */
+#ifndef _h_el_map
+#define _h_el_map
+
+typedef el_action_t (*el_func_t)(EditLine *, wint_t);
+
+typedef struct el_bindings_t { /* for the "bind" shell command */
+ const wchar_t *name; /* function name for bind command */
+ int func; /* function numeric value */
+ const wchar_t *description; /* description of function */
+} el_bindings_t;
+
+typedef struct el_map_t {
+ el_action_t *alt; /* The current alternate key map */
+ el_action_t *key; /* The current normal key map */
+ el_action_t *current; /* The keymap we are using */
+ const el_action_t *emacs; /* The default emacs key map */
+ const el_action_t *vic; /* The vi command mode key map */
+ const el_action_t *vii; /* The vi insert mode key map */
+ int type; /* Emacs or vi */
+ el_bindings_t *help; /* The help for the editor functions */
+ el_func_t *func; /* List of available functions */
+ size_t nfunc; /* The number of functions/help items */
+} el_map_t;
+
+#define MAP_EMACS 0
+#define MAP_VI 1
+
+#define N_KEYS 256
+
+libedit_private int map_bind(EditLine *, int, const wchar_t **);
+libedit_private int map_init(EditLine *);
+libedit_private void map_end(EditLine *);
+libedit_private void map_init_vi(EditLine *);
+libedit_private void map_init_emacs(EditLine *);
+libedit_private int map_set_editor(EditLine *, wchar_t *);
+libedit_private int map_get_editor(EditLine *, const wchar_t **);
+libedit_private int map_addfunc(EditLine *, const wchar_t *, const wchar_t *,
+ el_func_t);
+
+#endif /* _h_el_map */
diff --git a/third_party/heimdal/lib/libedit/src/parse.c b/third_party/heimdal/lib/libedit/src/parse.c
new file mode 100644
index 0000000..fdd0d84
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/parse.c
@@ -0,0 +1,289 @@
+/* $NetBSD: parse.c,v 1.40 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)parse.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: parse.c,v 1.40 2016/05/09 21:46:56 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * parse.c: parse an editline extended command
+ *
+ * commands are:
+ *
+ * bind
+ * echotc
+ * edit
+ * gettc
+ * history
+ * settc
+ * setty
+ */
+#include <stdlib.h>
+#include <string.h>
+
+#include "el.h"
+#include "parse.h"
+
+static const struct {
+ const wchar_t *name;
+ int (*func)(EditLine *, int, const wchar_t **);
+} cmds[] = {
+ { L"bind", map_bind },
+ { L"echotc", terminal_echotc },
+ { L"edit", el_editmode },
+ { L"history", hist_command },
+ { L"telltc", terminal_telltc },
+ { L"settc", terminal_settc },
+ { L"setty", tty_stty },
+ { NULL, NULL }
+};
+
+
+/* parse_line():
+ * Parse a line and dispatch it
+ */
+libedit_private int
+parse_line(EditLine *el, const wchar_t *line)
+{
+ const wchar_t **argv;
+ int argc;
+ TokenizerW *tok;
+
+ tok = tok_winit(NULL);
+ tok_wstr(tok, line, &argc, &argv);
+ argc = el_wparse(el, argc, argv);
+ tok_wend(tok);
+ return argc;
+}
+
+
+/* el_parse():
+ * Command dispatcher
+ */
+int
+el_wparse(EditLine *el, int argc, const wchar_t *argv[])
+{
+ const wchar_t *ptr;
+ int i;
+
+ if (argc < 1)
+ return -1;
+ ptr = wcschr(argv[0], L':');
+ if (ptr != NULL) {
+ wchar_t *tprog;
+ size_t l;
+
+ if (ptr == argv[0])
+ return 0;
+ l = (size_t)(ptr - argv[0] - 1);
+ tprog = el_malloc((l + 1) * sizeof(*tprog));
+ if (tprog == NULL)
+ return 0;
+ (void) wcsncpy(tprog, argv[0], l);
+ tprog[l] = '\0';
+ ptr++;
+ l = (size_t)el_match(el->el_prog, tprog);
+ el_free(tprog);
+ if (!l)
+ return 0;
+ } else
+ ptr = argv[0];
+
+ for (i = 0; cmds[i].name != NULL; i++)
+ if (wcscmp(cmds[i].name, ptr) == 0) {
+ i = (*cmds[i].func) (el, argc, argv);
+ return -i;
+ }
+ return -1;
+}
+
+
+/* parse__escape():
+ * Parse a string of the form ^<char> \<odigit> \<char> \U+xxxx and return
+ * the appropriate character or -1 if the escape is not valid
+ */
+libedit_private int
+parse__escape(const wchar_t **ptr)
+{
+ const wchar_t *p;
+ wint_t c;
+
+ p = *ptr;
+
+ if (p[1] == 0)
+ return -1;
+
+ if (*p == '\\') {
+ p++;
+ switch (*p) {
+ case 'a':
+ c = '\007'; /* Bell */
+ break;
+ case 'b':
+ c = '\010'; /* Backspace */
+ break;
+ case 't':
+ c = '\011'; /* Horizontal Tab */
+ break;
+ case 'n':
+ c = '\012'; /* New Line */
+ break;
+ case 'v':
+ c = '\013'; /* Vertical Tab */
+ break;
+ case 'f':
+ c = '\014'; /* Form Feed */
+ break;
+ case 'r':
+ c = '\015'; /* Carriage Return */
+ break;
+ case 'e':
+ c = '\033'; /* Escape */
+ break;
+ case 'U': /* Unicode \U+xxxx or \U+xxxxx format */
+ {
+ int i;
+ const wchar_t hex[] = L"0123456789ABCDEF";
+ const wchar_t *h;
+ ++p;
+ if (*p++ != '+')
+ return -1;
+ c = 0;
+ for (i = 0; i < 5; ++i) {
+ h = wcschr(hex, *p++);
+ if (!h && i < 4)
+ return -1;
+ else if (h)
+ c = (c << 4) | ((int)(h - hex));
+ else
+ --p;
+ }
+ if (c > 0x10FFFF) /* outside valid character range */
+ return -1;
+ break;
+ }
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ {
+ int cnt, ch;
+
+ for (cnt = 0, c = 0; cnt < 3; cnt++) {
+ ch = *p++;
+ if (ch < '0' || ch > '7') {
+ p--;
+ break;
+ }
+ c = (c << 3) | (ch - '0');
+ }
+ if ((c & (wint_t)0xffffff00) != (wint_t)0)
+ return -1;
+ --p;
+ break;
+ }
+ default:
+ c = *p;
+ break;
+ }
+ } else if (*p == '^') {
+ p++;
+ c = (*p == '?') ? '\177' : (*p & 0237);
+ } else
+ c = *p;
+ *ptr = ++p;
+ return c;
+}
+
+/* parse__string():
+ * Parse the escapes from in and put the raw string out
+ */
+libedit_private wchar_t *
+parse__string(wchar_t *out, const wchar_t *in)
+{
+ wchar_t *rv = out;
+ int n;
+
+ for (;;)
+ switch (*in) {
+ case '\0':
+ *out = '\0';
+ return rv;
+
+ case '\\':
+ case '^':
+ if ((n = parse__escape(&in)) == -1)
+ return NULL;
+ *out++ = (wchar_t)n;
+ break;
+
+ case 'M':
+ if (in[1] == '-' && in[2] != '\0') {
+ *out++ = '\033';
+ in += 2;
+ break;
+ }
+ /*FALLTHROUGH*/
+
+ default:
+ *out++ = *in++;
+ break;
+ }
+}
+
+
+/* parse_cmd():
+ * Return the command number for the command string given
+ * or -1 if one is not found
+ */
+libedit_private int
+parse_cmd(EditLine *el, const wchar_t *cmd)
+{
+ el_bindings_t *b = el->el_map.help;
+ size_t i;
+
+ for (i = 0; i < el->el_map.nfunc; i++)
+ if (wcscmp(b[i].name, cmd) == 0)
+ return b[i].func;
+ return -1;
+}
diff --git a/third_party/heimdal/lib/libedit/src/parse.h b/third_party/heimdal/lib/libedit/src/parse.h
new file mode 100644
index 0000000..fe8eb47
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/parse.h
@@ -0,0 +1,48 @@
+/* $NetBSD: parse.h,v 1.9 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)parse.h 8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * el.parse.h: Parser functions
+ */
+#ifndef _h_el_parse
+#define _h_el_parse
+
+libedit_private int parse_line(EditLine *, const wchar_t *);
+libedit_private int parse__escape(const wchar_t **);
+libedit_private wchar_t *parse__string(wchar_t *, const wchar_t *);
+libedit_private int parse_cmd(EditLine *, const wchar_t *);
+
+#endif /* _h_el_parse */
diff --git a/third_party/heimdal/lib/libedit/src/prompt.c b/third_party/heimdal/lib/libedit/src/prompt.c
new file mode 100644
index 0000000..a3d9915
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/prompt.c
@@ -0,0 +1,199 @@
+/* $NetBSD: prompt.c,v 1.26 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)prompt.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: prompt.c,v 1.26 2016/05/09 21:46:56 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * prompt.c: Prompt printing functions
+ */
+#include <stdio.h>
+#include "el.h"
+
+static wchar_t *prompt_default(EditLine *);
+static wchar_t *prompt_default_r(EditLine *);
+
+/* prompt_default():
+ * Just a default prompt, in case the user did not provide one
+ */
+static wchar_t *
+/*ARGSUSED*/
+prompt_default(EditLine *el __attribute__((__unused__)))
+{
+ static wchar_t a[3] = L"? ";
+
+ return a;
+}
+
+
+/* prompt_default_r():
+ * Just a default rprompt, in case the user did not provide one
+ */
+static wchar_t *
+/*ARGSUSED*/
+prompt_default_r(EditLine *el __attribute__((__unused__)))
+{
+ static wchar_t a[1] = L"";
+
+ return a;
+}
+
+
+/* prompt_print():
+ * Print the prompt and update the prompt position.
+ */
+libedit_private void
+prompt_print(EditLine *el, int op)
+{
+ el_prompt_t *elp;
+ wchar_t *p;
+ int ignore = 0;
+
+ if (op == EL_PROMPT)
+ elp = &el->el_prompt;
+ else
+ elp = &el->el_rprompt;
+
+ if (elp->p_wide)
+ p = (*elp->p_func)(el);
+ else
+ p = ct_decode_string((char *)(void *)(*elp->p_func)(el),
+ &el->el_scratch);
+
+ for (; *p; p++) {
+ if (elp->p_ignore == *p) {
+ ignore = !ignore;
+ continue;
+ }
+ if (ignore)
+ terminal__putc(el, *p);
+ else
+ re_putc(el, *p, 1);
+ }
+
+ elp->p_pos.v = el->el_refresh.r_cursor.v;
+ elp->p_pos.h = el->el_refresh.r_cursor.h;
+}
+
+
+/* prompt_init():
+ * Initialize the prompt stuff
+ */
+libedit_private int
+prompt_init(EditLine *el)
+{
+
+ el->el_prompt.p_func = prompt_default;
+ el->el_prompt.p_pos.v = 0;
+ el->el_prompt.p_pos.h = 0;
+ el->el_prompt.p_ignore = '\0';
+ el->el_rprompt.p_func = prompt_default_r;
+ el->el_rprompt.p_pos.v = 0;
+ el->el_rprompt.p_pos.h = 0;
+ el->el_rprompt.p_ignore = '\0';
+ return 0;
+}
+
+
+/* prompt_end():
+ * Clean up the prompt stuff
+ */
+libedit_private void
+/*ARGSUSED*/
+prompt_end(EditLine *el __attribute__((__unused__)))
+{
+}
+
+
+/* prompt_set():
+ * Install a prompt printing function
+ */
+libedit_private int
+prompt_set(EditLine *el, el_pfunc_t prf, wchar_t c, int op, int wide)
+{
+ el_prompt_t *p;
+
+ if (op == EL_PROMPT || op == EL_PROMPT_ESC)
+ p = &el->el_prompt;
+ else
+ p = &el->el_rprompt;
+
+ if (prf == NULL) {
+ if (op == EL_PROMPT || op == EL_PROMPT_ESC)
+ p->p_func = prompt_default;
+ else
+ p->p_func = prompt_default_r;
+ } else {
+ p->p_func = prf;
+ }
+
+ p->p_ignore = c;
+
+ p->p_pos.v = 0;
+ p->p_pos.h = 0;
+ p->p_wide = wide;
+
+ return 0;
+}
+
+
+/* prompt_get():
+ * Retrieve the prompt printing function
+ */
+libedit_private int
+prompt_get(EditLine *el, el_pfunc_t *prf, wchar_t *c, int op)
+{
+ el_prompt_t *p;
+
+ if (prf == NULL)
+ return -1;
+
+ if (op == EL_PROMPT)
+ p = &el->el_prompt;
+ else
+ p = &el->el_rprompt;
+
+ if (prf)
+ *prf = p->p_func;
+ if (c)
+ *c = p->p_ignore;
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/libedit/src/prompt.h b/third_party/heimdal/lib/libedit/src/prompt.h
new file mode 100644
index 0000000..2931428
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/prompt.h
@@ -0,0 +1,58 @@
+/* $NetBSD: prompt.h,v 1.15 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)prompt.h 8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * el.prompt.h: Prompt printing stuff
+ */
+#ifndef _h_el_prompt
+#define _h_el_prompt
+
+typedef wchar_t *(*el_pfunc_t)(EditLine *);
+
+typedef struct el_prompt_t {
+ el_pfunc_t p_func; /* Function to return the prompt */
+ coord_t p_pos; /* position in the line after prompt */
+ wchar_t p_ignore; /* character to start/end literal */
+ int p_wide;
+} el_prompt_t;
+
+libedit_private void prompt_print(EditLine *, int);
+libedit_private int prompt_set(EditLine *, el_pfunc_t, wchar_t, int, int);
+libedit_private int prompt_get(EditLine *, el_pfunc_t *, wchar_t *, int);
+libedit_private int prompt_init(EditLine *);
+libedit_private void prompt_end(EditLine *);
+
+#endif /* _h_el_prompt */
diff --git a/third_party/heimdal/lib/libedit/src/read.c b/third_party/heimdal/lib/libedit/src/read.c
new file mode 100644
index 0000000..cfab820
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/read.c
@@ -0,0 +1,628 @@
+/* $NetBSD: read.c,v 1.101 2016/05/25 13:01:11 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)read.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: read.c,v 1.101 2016/05/25 13:01:11 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * read.c: Terminal read functions
+ */
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "el.h"
+#include "fcns.h"
+#include "read.h"
+
+#define EL_MAXMACRO 10
+
+struct macros {
+ wchar_t **macro;
+ int level;
+ int offset;
+};
+
+struct el_read_t {
+ struct macros macros;
+ el_rfunc_t read_char; /* Function to read a character. */
+ int read_errno;
+};
+
+static int read__fixio(int, int);
+static int read_char(EditLine *, wchar_t *);
+static int read_getcmd(EditLine *, el_action_t *, wchar_t *);
+static void read_clearmacros(struct macros *);
+static void read_pop(struct macros *);
+static const wchar_t *noedit_wgets(EditLine *, int *);
+
+/* read_init():
+ * Initialize the read stuff
+ */
+libedit_private int
+read_init(EditLine *el)
+{
+ struct macros *ma;
+
+ if ((el->el_read = el_malloc(sizeof(*el->el_read))) == NULL)
+ return -1;
+
+ ma = &el->el_read->macros;
+ if ((ma->macro = el_malloc(EL_MAXMACRO *
+ sizeof(*ma->macro))) == NULL) {
+ free(el->el_read);
+ return -1;
+ }
+ ma->level = -1;
+ ma->offset = 0;
+
+ /* builtin read_char */
+ el->el_read->read_char = read_char;
+ return 0;
+}
+
+/* el_read_end():
+ * Free the data structures used by the read stuff.
+ */
+libedit_private void
+read_end(struct el_read_t *el_read)
+{
+ read_clearmacros(&el_read->macros);
+ el_free(el_read->macros.macro);
+ el_read->macros.macro = NULL;
+}
+
+/* el_read_setfn():
+ * Set the read char function to the one provided.
+ * If it is set to EL_BUILTIN_GETCFN, then reset to the builtin one.
+ */
+libedit_private int
+el_read_setfn(struct el_read_t *el_read, el_rfunc_t rc)
+{
+ el_read->read_char = (rc == EL_BUILTIN_GETCFN) ? read_char : rc;
+ return 0;
+}
+
+
+/* el_read_getfn():
+ * return the current read char function, or EL_BUILTIN_GETCFN
+ * if it is the default one
+ */
+libedit_private el_rfunc_t
+el_read_getfn(struct el_read_t *el_read)
+{
+ return el_read->read_char == read_char ?
+ EL_BUILTIN_GETCFN : el_read->read_char;
+}
+
+
+/* read__fixio():
+ * Try to recover from a read error
+ */
+/* ARGSUSED */
+static int
+read__fixio(int fd __attribute__((__unused__)), int e)
+{
+
+ switch (e) {
+ case -1: /* Make sure that the code is reachable */
+
+#ifdef EWOULDBLOCK
+ case EWOULDBLOCK:
+#ifndef TRY_AGAIN
+#define TRY_AGAIN
+#endif
+#endif /* EWOULDBLOCK */
+
+#if defined(POSIX) && defined(EAGAIN)
+#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
+ case EAGAIN:
+#ifndef TRY_AGAIN
+#define TRY_AGAIN
+#endif
+#endif /* EWOULDBLOCK && EWOULDBLOCK != EAGAIN */
+#endif /* POSIX && EAGAIN */
+
+ e = 0;
+#ifdef TRY_AGAIN
+#if defined(F_SETFL) && defined(O_NDELAY)
+ if ((e = fcntl(fd, F_GETFL, 0)) == -1)
+ return -1;
+
+ if (fcntl(fd, F_SETFL, e & ~O_NDELAY) == -1)
+ return -1;
+ else
+ e = 1;
+#endif /* F_SETFL && O_NDELAY */
+
+#ifdef FIONBIO
+ {
+ int zero = 0;
+
+ if (ioctl(fd, FIONBIO, &zero) == -1)
+ return -1;
+ else
+ e = 1;
+ }
+#endif /* FIONBIO */
+
+#endif /* TRY_AGAIN */
+ return e ? 0 : -1;
+
+ case EINTR:
+ return 0;
+
+ default:
+ return -1;
+ }
+}
+
+
+/* el_push():
+ * Push a macro
+ */
+void
+el_wpush(EditLine *el, const wchar_t *str)
+{
+ struct macros *ma = &el->el_read->macros;
+
+ if (str != NULL && ma->level + 1 < EL_MAXMACRO) {
+ ma->level++;
+ if ((ma->macro[ma->level] = wcsdup(str)) != NULL)
+ return;
+ ma->level--;
+ }
+ terminal_beep(el);
+ terminal__flush(el);
+}
+
+
+/* read_getcmd():
+ * Get next command from the input stream,
+ * return 0 on success or -1 on EOF or error.
+ * Character values > 255 are not looked up in the map, but inserted.
+ */
+static int
+read_getcmd(EditLine *el, el_action_t *cmdnum, wchar_t *ch)
+{
+ static const wchar_t meta = (wchar_t)0x80;
+ el_action_t cmd;
+ int num;
+
+ do {
+ if ((num = el_wgetc(el, ch)) != 1)
+ return -1;
+
+#ifdef KANJI
+ if ((*ch & meta)) {
+ el->el_state.metanext = 0;
+ cmd = CcViMap[' '];
+ break;
+ } else
+#endif /* KANJI */
+
+ if (el->el_state.metanext) {
+ el->el_state.metanext = 0;
+ *ch |= meta;
+ }
+ if (*ch >= N_KEYS)
+ cmd = ED_INSERT;
+ else
+ cmd = el->el_map.current[(unsigned char) *ch];
+ if (cmd == ED_SEQUENCE_LEAD_IN) {
+ keymacro_value_t val;
+ switch (keymacro_get(el, ch, &val)) {
+ case XK_CMD:
+ cmd = val.cmd;
+ break;
+ case XK_STR:
+ el_wpush(el, val.str);
+ break;
+ case XK_NOD:
+ return -1;
+ default:
+ EL_ABORT((el->el_errfile, "Bad XK_ type \n"));
+ break;
+ }
+ }
+ } while (cmd == ED_SEQUENCE_LEAD_IN);
+ *cmdnum = cmd;
+ return 0;
+}
+
+/* read_char():
+ * Read a character from the tty.
+ */
+static int
+read_char(EditLine *el, wchar_t *cp)
+{
+ ssize_t num_read;
+ int tried = 0;
+ char cbuf[MB_LEN_MAX];
+ size_t cbp = 0;
+ int save_errno = errno;
+
+ again:
+ el->el_signal->sig_no = 0;
+ while ((num_read = read(el->el_infd, cbuf + cbp, (size_t)1)) == -1) {
+ int e = errno;
+ switch (el->el_signal->sig_no) {
+ case SIGCONT:
+ el_wset(el, EL_REFRESH);
+ /*FALLTHROUGH*/
+ case SIGWINCH:
+ sig_set(el);
+ goto again;
+ default:
+ break;
+ }
+ if (!tried && read__fixio(el->el_infd, e) == 0) {
+ errno = save_errno;
+ tried = 1;
+ } else {
+ errno = e;
+ *cp = L'\0';
+ return -1;
+ }
+ }
+
+ /* Test for EOF */
+ if (num_read == 0) {
+ *cp = L'\0';
+ return 0;
+ }
+
+ for (;;) {
+ mbstate_t mbs;
+
+ ++cbp;
+ /* This only works because UTF8 is stateless. */
+ memset(&mbs, 0, sizeof(mbs));
+ switch (mbrtowc(cp, cbuf, cbp, &mbs)) {
+ case (size_t)-1:
+ if (cbp > 1) {
+ /*
+ * Invalid sequence, discard all bytes
+ * except the last one.
+ */
+ cbuf[0] = cbuf[cbp - 1];
+ cbp = 0;
+ break;
+ } else {
+ /* Invalid byte, discard it. */
+ cbp = 0;
+ goto again;
+ }
+ case (size_t)-2:
+ /*
+ * We don't support other multibyte charsets.
+ * The second condition shouldn't happen
+ * and is here merely for additional safety.
+ */
+ if ((el->el_flags & CHARSET_IS_UTF8) == 0 ||
+ cbp >= MB_LEN_MAX) {
+ errno = EILSEQ;
+ *cp = L'\0';
+ return -1;
+ }
+ /* Incomplete sequence, read another byte. */
+ goto again;
+ default:
+ /* Valid character, process it. */
+ return 1;
+ }
+ }
+}
+
+/* read_pop():
+ * Pop a macro from the stack
+ */
+static void
+read_pop(struct macros *ma)
+{
+ int i;
+
+ el_free(ma->macro[0]);
+ for (i = 0; i < ma->level; i++)
+ ma->macro[i] = ma->macro[i + 1];
+ ma->level--;
+ ma->offset = 0;
+}
+
+static void
+read_clearmacros(struct macros *ma)
+{
+ while (ma->level >= 0)
+ el_free(ma->macro[ma->level--]);
+ ma->offset = 0;
+}
+
+/* el_wgetc():
+ * Read a wide character
+ */
+int
+el_wgetc(EditLine *el, wchar_t *cp)
+{
+ struct macros *ma = &el->el_read->macros;
+ int num_read;
+
+ terminal__flush(el);
+ for (;;) {
+ if (ma->level < 0)
+ break;
+
+ if (ma->macro[0][ma->offset] == '\0') {
+ read_pop(ma);
+ continue;
+ }
+
+ *cp = ma->macro[0][ma->offset++];
+
+ if (ma->macro[0][ma->offset] == '\0') {
+ /* Needed for QuoteMode On */
+ read_pop(ma);
+ }
+
+ return 1;
+ }
+
+ if (tty_rawmode(el) < 0)/* make sure the tty is set up correctly */
+ return 0;
+
+ num_read = (*el->el_read->read_char)(el, cp);
+
+ /*
+ * Remember the original reason of a read failure
+ * such that el_wgets() can restore it after doing
+ * various cleanup operation that might change errno.
+ */
+ if (num_read < 0)
+ el->el_read->read_errno = errno;
+
+ return num_read;
+}
+
+libedit_private void
+read_prepare(EditLine *el)
+{
+ if (el->el_flags & HANDLE_SIGNALS)
+ sig_set(el);
+ if (el->el_flags & NO_TTY)
+ return;
+ if ((el->el_flags & (UNBUFFERED|EDIT_DISABLED)) == UNBUFFERED)
+ tty_rawmode(el);
+
+ /* This is relatively cheap, and things go terribly wrong if
+ we have the wrong size. */
+ el_resize(el);
+ re_clear_display(el); /* reset the display stuff */
+ ch_reset(el);
+ re_refresh(el); /* print the prompt */
+
+ if (el->el_flags & UNBUFFERED)
+ terminal__flush(el);
+}
+
+libedit_private void
+read_finish(EditLine *el)
+{
+ if ((el->el_flags & UNBUFFERED) == 0)
+ (void) tty_cookedmode(el);
+ if (el->el_flags & HANDLE_SIGNALS)
+ sig_clr(el);
+}
+
+static const wchar_t *
+noedit_wgets(EditLine *el, int *nread)
+{
+ el_line_t *lp = &el->el_line;
+ int num;
+
+ while ((num = (*el->el_read->read_char)(el, lp->lastchar)) == 1) {
+ if (lp->lastchar + 1 >= lp->limit &&
+ !ch_enlargebufs(el, (size_t)2))
+ break;
+ lp->lastchar++;
+ if (el->el_flags & UNBUFFERED ||
+ lp->lastchar[-1] == '\r' ||
+ lp->lastchar[-1] == '\n')
+ break;
+ }
+ if (num == -1 && errno == EINTR)
+ lp->lastchar = lp->buffer;
+ lp->cursor = lp->lastchar;
+ *lp->lastchar = '\0';
+ *nread = (int)(lp->lastchar - lp->buffer);
+ return *nread ? lp->buffer : NULL;
+}
+
+const wchar_t *
+el_wgets(EditLine *el, int *nread)
+{
+ int retval;
+ el_action_t cmdnum = 0;
+ int num; /* how many chars we have read at NL */
+ wchar_t ch;
+ int nrb;
+
+ if (nread == NULL)
+ nread = &nrb;
+ *nread = 0;
+ el->el_read->read_errno = 0;
+
+ if (el->el_flags & NO_TTY) {
+ el->el_line.lastchar = el->el_line.buffer;
+ return noedit_wgets(el, nread);
+ }
+
+#ifdef FIONREAD
+ if (el->el_tty.t_mode == EX_IO && el->el_read->macros.level < 0) {
+ int chrs = 0;
+
+ (void) ioctl(el->el_infd, FIONREAD, &chrs);
+ if (chrs == 0) {
+ if (tty_rawmode(el) < 0) {
+ errno = 0;
+ *nread = 0;
+ return NULL;
+ }
+ }
+ }
+#endif /* FIONREAD */
+
+ if ((el->el_flags & UNBUFFERED) == 0)
+ read_prepare(el);
+
+ if (el->el_flags & EDIT_DISABLED) {
+ if ((el->el_flags & UNBUFFERED) == 0)
+ el->el_line.lastchar = el->el_line.buffer;
+ terminal__flush(el);
+ return noedit_wgets(el, nread);
+ }
+
+ for (num = -1; num == -1;) { /* while still editing this line */
+ /* if EOF or error */
+ if (read_getcmd(el, &cmdnum, &ch) == -1)
+ break;
+ if ((size_t)cmdnum >= el->el_map.nfunc) /* BUG CHECK command */
+ continue; /* try again */
+ /* now do the real command */
+ /* vi redo needs these way down the levels... */
+ el->el_state.thiscmd = cmdnum;
+ el->el_state.thisch = ch;
+ if (el->el_map.type == MAP_VI &&
+ el->el_map.current == el->el_map.key &&
+ el->el_chared.c_redo.pos < el->el_chared.c_redo.lim) {
+ if (cmdnum == VI_DELETE_PREV_CHAR &&
+ el->el_chared.c_redo.pos != el->el_chared.c_redo.buf
+ && iswprint(el->el_chared.c_redo.pos[-1]))
+ el->el_chared.c_redo.pos--;
+ else
+ *el->el_chared.c_redo.pos++ = ch;
+ }
+ retval = (*el->el_map.func[cmdnum]) (el, ch);
+
+ /* save the last command here */
+ el->el_state.lastcmd = cmdnum;
+
+ /* use any return value */
+ switch (retval) {
+ case CC_CURSOR:
+ re_refresh_cursor(el);
+ break;
+
+ case CC_REDISPLAY:
+ re_clear_lines(el);
+ re_clear_display(el);
+ /* FALLTHROUGH */
+
+ case CC_REFRESH:
+ re_refresh(el);
+ break;
+
+ case CC_REFRESH_BEEP:
+ re_refresh(el);
+ terminal_beep(el);
+ break;
+
+ case CC_NORM: /* normal char */
+ break;
+
+ case CC_ARGHACK: /* Suggested by Rich Salz */
+ /* <rsalz@pineapple.bbn.com> */
+ continue; /* keep going... */
+
+ case CC_EOF: /* end of file typed */
+ if ((el->el_flags & UNBUFFERED) == 0)
+ num = 0;
+ else if (num == -1) {
+ *el->el_line.lastchar++ = CONTROL('d');
+ el->el_line.cursor = el->el_line.lastchar;
+ num = 1;
+ }
+ break;
+
+ case CC_NEWLINE: /* normal end of line */
+ num = (int)(el->el_line.lastchar - el->el_line.buffer);
+ break;
+
+ case CC_FATAL: /* fatal error, reset to known state */
+ /* put (real) cursor in a known place */
+ re_clear_display(el); /* reset the display stuff */
+ ch_reset(el); /* reset the input pointers */
+ read_clearmacros(&el->el_read->macros);
+ re_refresh(el); /* print the prompt again */
+ break;
+
+ case CC_ERROR:
+ default: /* functions we don't know about */
+ terminal_beep(el);
+ terminal__flush(el);
+ break;
+ }
+ el->el_state.argument = 1;
+ el->el_state.doingarg = 0;
+ el->el_chared.c_vcmd.action = NOP;
+ if (el->el_flags & UNBUFFERED)
+ break;
+ }
+
+ terminal__flush(el); /* flush any buffered output */
+ /* make sure the tty is set up correctly */
+ if ((el->el_flags & UNBUFFERED) == 0) {
+ read_finish(el);
+ *nread = num != -1 ? num : 0;
+ } else
+ *nread = (int)(el->el_line.lastchar - el->el_line.buffer);
+
+ if (*nread == 0) {
+ if (num == -1) {
+ *nread = -1;
+ if (el->el_read->read_errno)
+ errno = el->el_read->read_errno;
+ }
+ return NULL;
+ } else
+ return el->el_line.buffer;
+}
diff --git a/third_party/heimdal/lib/libedit/src/read.h b/third_party/heimdal/lib/libedit/src/read.h
new file mode 100644
index 0000000..1acf5d6
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/read.h
@@ -0,0 +1,45 @@
+/* $NetBSD: read.h,v 1.12 2016/05/22 19:44:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Anthony Mallet.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * el.read.h: Character reading functions
+ */
+#ifndef _h_el_read
+#define _h_el_read
+
+libedit_private int read_init(EditLine *);
+libedit_private void read_end(struct el_read_t *);
+libedit_private void read_prepare(EditLine *);
+libedit_private void read_finish(EditLine *);
+libedit_private int el_read_setfn(struct el_read_t *, el_rfunc_t);
+libedit_private el_rfunc_t el_read_getfn(struct el_read_t *);
+
+#endif /* _h_el_read */
diff --git a/third_party/heimdal/lib/libedit/src/readline.c b/third_party/heimdal/lib/libedit/src/readline.c
new file mode 100644
index 0000000..f4e0a39
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/readline.c
@@ -0,0 +1,2367 @@
+/* $NetBSD: readline.c,v 1.139 2016/10/28 18:32:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jaromir Dolecek.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+__RCSID("$NetBSD: readline.c,v 1.139 2016/10/28 18:32:26 christos Exp $");
+#endif /* not lint && not SCCSID */
+
+#include "config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <pwd.h>
+#include <setjmp.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <vis.h>
+
+#include "readline/readline.h"
+#include "el.h"
+#include "fcns.h"
+#include "filecomplete.h"
+
+void rl_prep_terminal(int);
+void rl_deprep_terminal(void);
+
+/* for rl_complete() */
+#define TAB '\r'
+
+/* see comment at the #ifdef for sense of this */
+/* #define GDB_411_HACK */
+
+/* readline compatibility stuff - look at readline sources/documentation */
+/* to see what these variables mean */
+const char *rl_library_version = "EditLine wrapper";
+int rl_readline_version = RL_READLINE_VERSION;
+static char empty[] = { '\0' };
+static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
+static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
+ '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
+char *rl_readline_name = empty;
+FILE *rl_instream = NULL;
+FILE *rl_outstream = NULL;
+int rl_point = 0;
+int rl_end = 0;
+char *rl_line_buffer = NULL;
+rl_vcpfunc_t *rl_linefunc = NULL;
+int rl_done = 0;
+VFunction *rl_event_hook = NULL;
+KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
+ emacs_meta_keymap,
+ emacs_ctlx_keymap;
+/*
+ * The following is not implemented; we always catch signals in the
+ * libedit fashion: set handlers on entry to el_gets() and clear them
+ * on the way out. This simplistic approach works for most cases; if
+ * it does not work for your application, please let us know.
+ */
+int rl_catch_signals = 1;
+int rl_catch_sigwinch = 1;
+
+int history_base = 1; /* probably never subject to change */
+int history_length = 0;
+int history_offset = 0;
+int max_input_history = 0;
+char history_expansion_char = '!';
+char history_subst_char = '^';
+char *history_no_expand_chars = expand_chars;
+Function *history_inhibit_expansion_function = NULL;
+char *history_arg_extract(int start, int end, const char *str);
+
+int rl_inhibit_completion = 0;
+int rl_attempted_completion_over = 0;
+char *rl_basic_word_break_characters = break_chars;
+char *rl_completer_word_break_characters = NULL;
+char *rl_completer_quote_characters = NULL;
+rl_compentry_func_t *rl_completion_entry_function = NULL;
+char *(*rl_completion_word_break_hook)(void) = NULL;
+rl_completion_func_t *rl_attempted_completion_function = NULL;
+Function *rl_pre_input_hook = NULL;
+Function *rl_startup1_hook = NULL;
+int (*rl_getc_function)(FILE *) = NULL;
+char *rl_terminal_name = NULL;
+int rl_already_prompted = 0;
+int rl_filename_completion_desired = 0;
+int rl_ignore_completion_duplicates = 0;
+int readline_echoing_p = 1;
+int _rl_print_completions_horizontally = 0;
+VFunction *rl_redisplay_function = NULL;
+Function *rl_startup_hook = NULL;
+VFunction *rl_completion_display_matches_hook = NULL;
+VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
+VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
+KEYMAP_ENTRY_ARRAY emacs_meta_keymap;
+
+/*
+ * The current prompt string.
+ */
+char *rl_prompt = NULL;
+/*
+ * This is set to character indicating type of completion being done by
+ * rl_complete_internal(); this is available for application completion
+ * functions.
+ */
+int rl_completion_type = 0;
+
+/*
+ * If more than this number of items results from query for possible
+ * completions, we ask user if they are sure to really display the list.
+ */
+int rl_completion_query_items = 100;
+
+/*
+ * List of characters which are word break characters, but should be left
+ * in the parsed text when it is passed to the completion function.
+ * Shell uses this to help determine what kind of completing to do.
+ */
+char *rl_special_prefixes = NULL;
+
+/*
+ * This is the character appended to the completed words if at the end of
+ * the line. Default is ' ' (a space).
+ */
+int rl_completion_append_character = ' ';
+
+/* stuff below is used internally by libedit for readline emulation */
+
+static History *h = NULL;
+static EditLine *e = NULL;
+static rl_command_func_t *map[256];
+static jmp_buf topbuf;
+
+/* internal functions */
+static unsigned char _el_rl_complete(EditLine *, int);
+static unsigned char _el_rl_tstp(EditLine *, int);
+static char *_get_prompt(EditLine *);
+static int _getc_function(EditLine *, wchar_t *);
+static int _history_expand_command(const char *, size_t, size_t,
+ char **);
+static char *_rl_compat_sub(const char *, const char *,
+ const char *, int);
+static int _rl_event_read_char(EditLine *, wchar_t *);
+static void _rl_update_pos(void);
+
+static HIST_ENTRY rl_he;
+
+/* ARGSUSED */
+static char *
+_get_prompt(EditLine *el __attribute__((__unused__)))
+{
+ rl_already_prompted = 1;
+ return rl_prompt;
+}
+
+
+/*
+ * read one key from user defined input function
+ */
+static int
+/*ARGSUSED*/
+_getc_function(EditLine *el __attribute__((__unused__)), wchar_t *c)
+{
+ int i;
+
+ i = (*rl_getc_function)(rl_instream);
+ if (i == -1)
+ return 0;
+ *c = (wchar_t)i;
+ return 1;
+}
+
+static void
+_resize_fun(EditLine *el, void *a)
+{
+ const LineInfo *li;
+ char **ap = a;
+
+ li = el_line(el);
+ /* a cheesy way to get rid of const cast. */
+ *ap = memchr(li->buffer, *li->buffer, (size_t)1);
+}
+
+static const char *
+_default_history_file(void)
+{
+ struct passwd *p;
+ static char *path;
+ size_t len;
+
+ if (path)
+ return path;
+
+ if ((p = getpwuid(getuid())) == NULL)
+ return NULL;
+
+ len = strlen(p->pw_dir) + sizeof("/.history");
+ if ((path = malloc(len)) == NULL)
+ return NULL;
+
+ (void)snprintf(path, len, "%s/.history", p->pw_dir);
+ return path;
+}
+
+/*
+ * READLINE compatibility stuff
+ */
+
+/*
+ * Set the prompt
+ */
+int
+rl_set_prompt(const char *prompt)
+{
+ char *p;
+
+ if (!prompt)
+ prompt = "";
+ if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0)
+ return 0;
+ if (rl_prompt)
+ el_free(rl_prompt);
+ rl_prompt = strdup(prompt);
+ if (rl_prompt == NULL)
+ return -1;
+
+ while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL)
+ *p = RL_PROMPT_START_IGNORE;
+
+ return 0;
+}
+
+/*
+ * initialize rl compat stuff
+ */
+int
+rl_initialize(void)
+{
+ HistEvent ev;
+ int editmode = 1;
+ struct termios t;
+
+ if (e != NULL)
+ el_end(e);
+ if (h != NULL)
+ history_end(h);
+
+ if (!rl_instream)
+ rl_instream = stdin;
+ if (!rl_outstream)
+ rl_outstream = stdout;
+
+ /*
+ * See if we don't really want to run the editor
+ */
+ if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
+ editmode = 0;
+
+ e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
+
+ if (!editmode)
+ el_set(e, EL_EDITMODE, 0);
+
+ h = history_init();
+ if (!e || !h)
+ return -1;
+
+ history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
+ history_length = 0;
+ max_input_history = INT_MAX;
+ el_set(e, EL_HIST, history, h);
+
+ /* Setup resize function */
+ el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer);
+
+ /* setup getc function if valid */
+ if (rl_getc_function)
+ el_set(e, EL_GETCFN, _getc_function);
+
+ /* for proper prompt printing in readline() */
+ if (rl_set_prompt("") == -1) {
+ history_end(h);
+ el_end(e);
+ return -1;
+ }
+ el_set(e, EL_PROMPT, _get_prompt, RL_PROMPT_START_IGNORE);
+ el_set(e, EL_SIGNAL, rl_catch_signals);
+
+ /* set default mode to "emacs"-style and read setting afterwards */
+ /* so this can be overridden */
+ el_set(e, EL_EDITOR, "emacs");
+ if (rl_terminal_name != NULL)
+ el_set(e, EL_TERMINAL, rl_terminal_name);
+ else
+ el_get(e, EL_TERMINAL, &rl_terminal_name);
+
+ /*
+ * Word completion - this has to go AFTER rebinding keys
+ * to emacs-style.
+ */
+ el_set(e, EL_ADDFN, "rl_complete",
+ "ReadLine compatible completion function",
+ _el_rl_complete);
+ el_set(e, EL_BIND, "^I", "rl_complete", NULL);
+
+ /*
+ * Send TSTP when ^Z is pressed.
+ */
+ el_set(e, EL_ADDFN, "rl_tstp",
+ "ReadLine compatible suspend function",
+ _el_rl_tstp);
+ el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
+
+ /*
+ * Set some readline compatible key-bindings.
+ */
+ el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL);
+
+ /*
+ * Allow the use of Home/End keys.
+ */
+ el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
+ el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
+ el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL);
+ el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL);
+ el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL);
+ el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL);
+
+ /*
+ * Allow the use of the Delete/Insert keys.
+ */
+ el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
+ el_set(e, EL_BIND, "\\e[2~", "ed-quoted-insert", NULL);
+
+ /*
+ * Ctrl-left-arrow and Ctrl-right-arrow for word moving.
+ */
+ el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL);
+ el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL);
+ el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL);
+ el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL);
+ el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL);
+ el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL);
+
+ /* read settings from configuration file */
+ el_source(e, NULL);
+
+ /*
+ * Unfortunately, some applications really do use rl_point
+ * and rl_line_buffer directly.
+ */
+ _resize_fun(e, &rl_line_buffer);
+ _rl_update_pos();
+
+ if (rl_startup_hook)
+ (*rl_startup_hook)(NULL, 0);
+
+ return 0;
+}
+
+
+/*
+ * read one line from input stream and return it, chomping
+ * trailing newline (if there is any)
+ */
+char *
+readline(const char *p)
+{
+ HistEvent ev;
+ const char * volatile prompt = p;
+ int count;
+ const char *ret;
+ char *buf;
+ static int used_event_hook;
+
+ if (e == NULL || h == NULL)
+ rl_initialize();
+
+ rl_done = 0;
+
+ (void)setjmp(topbuf);
+
+ /* update prompt accordingly to what has been passed */
+ if (rl_set_prompt(prompt) == -1)
+ return NULL;
+
+ if (rl_pre_input_hook)
+ (*rl_pre_input_hook)(NULL, 0);
+
+ if (rl_event_hook && !(e->el_flags&NO_TTY)) {
+ el_set(e, EL_GETCFN, _rl_event_read_char);
+ used_event_hook = 1;
+ }
+
+ if (!rl_event_hook && used_event_hook) {
+ el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
+ used_event_hook = 0;
+ }
+
+ rl_already_prompted = 0;
+
+ /* get one line from input stream */
+ ret = el_gets(e, &count);
+
+ if (ret && count > 0) {
+ int lastidx;
+
+ buf = strdup(ret);
+ if (buf == NULL)
+ return NULL;
+ lastidx = count - 1;
+ if (buf[lastidx] == '\n')
+ buf[lastidx] = '\0';
+ } else
+ buf = NULL;
+
+ history(h, &ev, H_GETSIZE);
+ history_length = ev.num;
+
+ return buf;
+}
+
+/*
+ * history functions
+ */
+
+/*
+ * is normally called before application starts to use
+ * history expansion functions
+ */
+void
+using_history(void)
+{
+ if (h == NULL || e == NULL)
+ rl_initialize();
+ history_offset = history_length;
+}
+
+
+/*
+ * substitute ``what'' with ``with'', returning resulting string; if
+ * globally == 1, substitutes all occurrences of what, otherwise only the
+ * first one
+ */
+static char *
+_rl_compat_sub(const char *str, const char *what, const char *with,
+ int globally)
+{
+ const char *s;
+ char *r, *result;
+ size_t len, with_len, what_len;
+
+ len = strlen(str);
+ with_len = strlen(with);
+ what_len = strlen(what);
+
+ /* calculate length we need for result */
+ s = str;
+ while (*s) {
+ if (*s == *what && !strncmp(s, what, what_len)) {
+ len += with_len - what_len;
+ if (!globally)
+ break;
+ s += what_len;
+ } else
+ s++;
+ }
+ r = result = el_malloc((len + 1) * sizeof(*r));
+ if (result == NULL)
+ return NULL;
+ s = str;
+ while (*s) {
+ if (*s == *what && !strncmp(s, what, what_len)) {
+ (void)strncpy(r, with, with_len);
+ r += with_len;
+ s += what_len;
+ if (!globally) {
+ (void)strcpy(r, s);
+ return result;
+ }
+ } else
+ *r++ = *s++;
+ }
+ *r = '\0';
+ return result;
+}
+
+static char *last_search_pat; /* last !?pat[?] search pattern */
+static char *last_search_match; /* last !?pat[?] that matched */
+
+const char *
+get_history_event(const char *cmd, int *cindex, int qchar)
+{
+ int idx, sign, sub, num, begin, ret;
+ size_t len;
+ char *pat;
+ const char *rptr;
+ HistEvent ev;
+
+ idx = *cindex;
+ if (cmd[idx++] != history_expansion_char)
+ return NULL;
+
+ /* find out which event to take */
+ if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
+ if (history(h, &ev, H_FIRST) != 0)
+ return NULL;
+ *cindex = cmd[idx]? (idx + 1):idx;
+ return ev.str;
+ }
+ sign = 0;
+ if (cmd[idx] == '-') {
+ sign = 1;
+ idx++;
+ }
+
+ if ('0' <= cmd[idx] && cmd[idx] <= '9') {
+ HIST_ENTRY *he;
+
+ num = 0;
+ while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
+ num = num * 10 + cmd[idx] - '0';
+ idx++;
+ }
+ if (sign)
+ num = history_length - num + 1;
+
+ if (!(he = history_get(num)))
+ return NULL;
+
+ *cindex = idx;
+ return he->line;
+ }
+ sub = 0;
+ if (cmd[idx] == '?') {
+ sub = 1;
+ idx++;
+ }
+ begin = idx;
+ while (cmd[idx]) {
+ if (cmd[idx] == '\n')
+ break;
+ if (sub && cmd[idx] == '?')
+ break;
+ if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
+ || cmd[idx] == '\t' || cmd[idx] == qchar))
+ break;
+ idx++;
+ }
+ len = (size_t)idx - (size_t)begin;
+ if (sub && cmd[idx] == '?')
+ idx++;
+ if (sub && len == 0 && last_search_pat && *last_search_pat)
+ pat = last_search_pat;
+ else if (len == 0)
+ return NULL;
+ else {
+ if ((pat = el_malloc((len + 1) * sizeof(*pat))) == NULL)
+ return NULL;
+ (void)strncpy(pat, cmd + begin, len);
+ pat[len] = '\0';
+ }
+
+ if (history(h, &ev, H_CURR) != 0) {
+ if (pat != last_search_pat)
+ el_free(pat);
+ return NULL;
+ }
+ num = ev.num;
+
+ if (sub) {
+ if (pat != last_search_pat) {
+ if (last_search_pat)
+ el_free(last_search_pat);
+ last_search_pat = pat;
+ }
+ ret = history_search(pat, -1);
+ } else
+ ret = history_search_prefix(pat, -1);
+
+ if (ret == -1) {
+ /* restore to end of list on failed search */
+ history(h, &ev, H_FIRST);
+ (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
+ if (pat != last_search_pat)
+ el_free(pat);
+ return NULL;
+ }
+
+ if (sub && len) {
+ if (last_search_match && last_search_match != pat)
+ el_free(last_search_match);
+ last_search_match = pat;
+ }
+
+ if (pat != last_search_pat)
+ el_free(pat);
+
+ if (history(h, &ev, H_CURR) != 0)
+ return NULL;
+ *cindex = idx;
+ rptr = ev.str;
+
+ /* roll back to original position */
+ (void)history(h, &ev, H_SET, num);
+
+ return rptr;
+}
+
+/*
+ * the real function doing history expansion - takes as argument command
+ * to do and data upon which the command should be executed
+ * does expansion the way I've understood readline documentation
+ *
+ * returns 0 if data was not modified, 1 if it was and 2 if the string
+ * should be only printed and not executed; in case of error,
+ * returns -1 and *result points to NULL
+ * it's the caller's responsibility to free() the string returned in *result
+ */
+static int
+_history_expand_command(const char *command, size_t offs, size_t cmdlen,
+ char **result)
+{
+ char *tmp, *search = NULL, *aptr;
+ const char *ptr, *cmd;
+ static char *from = NULL, *to = NULL;
+ int start, end, idx, has_mods = 0;
+ int p_on = 0, g_on = 0;
+
+ *result = NULL;
+ aptr = NULL;
+ ptr = NULL;
+
+ /* First get event specifier */
+ idx = 0;
+
+ if (strchr(":^*$", command[offs + 1])) {
+ char str[4];
+ /*
+ * "!:" is shorthand for "!!:".
+ * "!^", "!*" and "!$" are shorthand for
+ * "!!:^", "!!:*" and "!!:$" respectively.
+ */
+ str[0] = str[1] = '!';
+ str[2] = '0';
+ ptr = get_history_event(str, &idx, 0);
+ idx = (command[offs + 1] == ':')? 1:0;
+ has_mods = 1;
+ } else {
+ if (command[offs + 1] == '#') {
+ /* use command so far */
+ if ((aptr = el_malloc((offs + 1) * sizeof(*aptr)))
+ == NULL)
+ return -1;
+ (void)strncpy(aptr, command, offs);
+ aptr[offs] = '\0';
+ idx = 1;
+ } else {
+ int qchar;
+
+ qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
+ ptr = get_history_event(command + offs, &idx, qchar);
+ }
+ has_mods = command[offs + (size_t)idx] == ':';
+ }
+
+ if (ptr == NULL && aptr == NULL)
+ return -1;
+
+ if (!has_mods) {
+ *result = strdup(aptr ? aptr : ptr);
+ if (aptr)
+ el_free(aptr);
+ if (*result == NULL)
+ return -1;
+ return 1;
+ }
+
+ cmd = command + offs + idx + 1;
+
+ /* Now parse any word designators */
+
+ if (*cmd == '%') /* last word matched by ?pat? */
+ tmp = strdup(last_search_match? last_search_match:"");
+ else if (strchr("^*$-0123456789", *cmd)) {
+ start = end = -1;
+ if (*cmd == '^')
+ start = end = 1, cmd++;
+ else if (*cmd == '$')
+ start = -1, cmd++;
+ else if (*cmd == '*')
+ start = 1, cmd++;
+ else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
+ start = 0;
+ while (*cmd && '0' <= *cmd && *cmd <= '9')
+ start = start * 10 + *cmd++ - '0';
+
+ if (*cmd == '-') {
+ if (isdigit((unsigned char) cmd[1])) {
+ cmd++;
+ end = 0;
+ while (*cmd && '0' <= *cmd && *cmd <= '9')
+ end = end * 10 + *cmd++ - '0';
+ } else if (cmd[1] == '$') {
+ cmd += 2;
+ end = -1;
+ } else {
+ cmd++;
+ end = -2;
+ }
+ } else if (*cmd == '*')
+ end = -1, cmd++;
+ else
+ end = start;
+ }
+ tmp = history_arg_extract(start, end, aptr? aptr:ptr);
+ if (tmp == NULL) {
+ (void)fprintf(rl_outstream, "%s: Bad word specifier",
+ command + offs + idx);
+ if (aptr)
+ el_free(aptr);
+ return -1;
+ }
+ } else
+ tmp = strdup(aptr? aptr:ptr);
+
+ if (aptr)
+ el_free(aptr);
+
+ if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
+ *result = tmp;
+ return 1;
+ }
+
+ for (; *cmd; cmd++) {
+ if (*cmd == ':')
+ continue;
+ else if (*cmd == 'h') { /* remove trailing path */
+ if ((aptr = strrchr(tmp, '/')) != NULL)
+ *aptr = '\0';
+ } else if (*cmd == 't') { /* remove leading path */
+ if ((aptr = strrchr(tmp, '/')) != NULL) {
+ aptr = strdup(aptr + 1);
+ el_free(tmp);
+ tmp = aptr;
+ }
+ } else if (*cmd == 'r') { /* remove trailing suffix */
+ if ((aptr = strrchr(tmp, '.')) != NULL)
+ *aptr = '\0';
+ } else if (*cmd == 'e') { /* remove all but suffix */
+ if ((aptr = strrchr(tmp, '.')) != NULL) {
+ aptr = strdup(aptr);
+ el_free(tmp);
+ tmp = aptr;
+ }
+ } else if (*cmd == 'p') /* print only */
+ p_on = 1;
+ else if (*cmd == 'g')
+ g_on = 2;
+ else if (*cmd == 's' || *cmd == '&') {
+ char *what, *with, delim;
+ size_t len, from_len;
+ size_t size;
+
+ if (*cmd == '&' && (from == NULL || to == NULL))
+ continue;
+ else if (*cmd == 's') {
+ delim = *(++cmd), cmd++;
+ size = 16;
+ what = el_realloc(from, size * sizeof(*what));
+ if (what == NULL) {
+ el_free(from);
+ el_free(tmp);
+ return 0;
+ }
+ len = 0;
+ for (; *cmd && *cmd != delim; cmd++) {
+ if (*cmd == '\\' && cmd[1] == delim)
+ cmd++;
+ if (len >= size) {
+ char *nwhat;
+ nwhat = el_realloc(what,
+ (size <<= 1) *
+ sizeof(*nwhat));
+ if (nwhat == NULL) {
+ el_free(what);
+ el_free(tmp);
+ return 0;
+ }
+ what = nwhat;
+ }
+ what[len++] = *cmd;
+ }
+ what[len] = '\0';
+ from = what;
+ if (*what == '\0') {
+ el_free(what);
+ if (search) {
+ from = strdup(search);
+ if (from == NULL) {
+ el_free(tmp);
+ return 0;
+ }
+ } else {
+ from = NULL;
+ el_free(tmp);
+ return -1;
+ }
+ }
+ cmd++; /* shift after delim */
+ if (!*cmd)
+ continue;
+
+ size = 16;
+ with = el_realloc(to, size * sizeof(*with));
+ if (with == NULL) {
+ el_free(to);
+ el_free(tmp);
+ return -1;
+ }
+ len = 0;
+ from_len = strlen(from);
+ for (; *cmd && *cmd != delim; cmd++) {
+ if (len + from_len + 1 >= size) {
+ char *nwith;
+ size += from_len + 1;
+ nwith = el_realloc(with,
+ size * sizeof(*nwith));
+ if (nwith == NULL) {
+ el_free(with);
+ el_free(tmp);
+ return -1;
+ }
+ with = nwith;
+ }
+ if (*cmd == '&') {
+ /* safe */
+ (void)strcpy(&with[len], from);
+ len += from_len;
+ continue;
+ }
+ if (*cmd == '\\'
+ && (*(cmd + 1) == delim
+ || *(cmd + 1) == '&'))
+ cmd++;
+ with[len++] = *cmd;
+ }
+ with[len] = '\0';
+ to = with;
+ }
+
+ aptr = _rl_compat_sub(tmp, from, to, g_on);
+ if (aptr) {
+ el_free(tmp);
+ tmp = aptr;
+ }
+ g_on = 0;
+ }
+ }
+ *result = tmp;
+ return p_on? 2:1;
+}
+
+
+/*
+ * csh-style history expansion
+ */
+int
+history_expand(char *str, char **output)
+{
+ int ret = 0;
+ size_t idx, i, size;
+ char *tmp, *result;
+
+ if (h == NULL || e == NULL)
+ rl_initialize();
+
+ if (history_expansion_char == 0) {
+ *output = strdup(str);
+ return 0;
+ }
+
+ *output = NULL;
+ if (str[0] == history_subst_char) {
+ /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
+ *output = el_malloc((strlen(str) + 4 + 1) * sizeof(**output));
+ if (*output == NULL)
+ return 0;
+ (*output)[0] = (*output)[1] = history_expansion_char;
+ (*output)[2] = ':';
+ (*output)[3] = 's';
+ (void)strcpy((*output) + 4, str);
+ str = *output;
+ } else {
+ *output = strdup(str);
+ if (*output == NULL)
+ return 0;
+ }
+
+#define ADD_STRING(what, len, fr) \
+ { \
+ if (idx + len + 1 > size) { \
+ char *nresult = el_realloc(result, \
+ (size += len + 1) * sizeof(*nresult)); \
+ if (nresult == NULL) { \
+ el_free(*output); \
+ if (/*CONSTCOND*/fr) \
+ el_free(tmp); \
+ return 0; \
+ } \
+ result = nresult; \
+ } \
+ (void)strncpy(&result[idx], what, len); \
+ idx += len; \
+ result[idx] = '\0'; \
+ }
+
+ result = NULL;
+ size = idx = 0;
+ tmp = NULL;
+ for (i = 0; str[i];) {
+ int qchar, loop_again;
+ size_t len, start, j;
+
+ qchar = 0;
+ loop_again = 1;
+ start = j = i;
+loop:
+ for (; str[j]; j++) {
+ if (str[j] == '\\' &&
+ str[j + 1] == history_expansion_char) {
+ len = strlen(&str[j + 1]) + 1;
+ memmove(&str[j], &str[j + 1], len);
+ continue;
+ }
+ if (!loop_again) {
+ if (isspace((unsigned char) str[j])
+ || str[j] == qchar)
+ break;
+ }
+ if (str[j] == history_expansion_char
+ && !strchr(history_no_expand_chars, str[j + 1])
+ && (!history_inhibit_expansion_function ||
+ (*history_inhibit_expansion_function)(str,
+ (int)j) == 0))
+ break;
+ }
+
+ if (str[j] && loop_again) {
+ i = j;
+ qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
+ j++;
+ if (str[j] == history_expansion_char)
+ j++;
+ loop_again = 0;
+ goto loop;
+ }
+ len = i - start;
+ ADD_STRING(&str[start], len, 0);
+
+ if (str[i] == '\0' || str[i] != history_expansion_char) {
+ len = j - i;
+ ADD_STRING(&str[i], len, 0);
+ if (start == 0)
+ ret = 0;
+ else
+ ret = 1;
+ break;
+ }
+ ret = _history_expand_command (str, i, (j - i), &tmp);
+ if (ret > 0 && tmp) {
+ len = strlen(tmp);
+ ADD_STRING(tmp, len, 1);
+ }
+ if (tmp) {
+ el_free(tmp);
+ tmp = NULL;
+ }
+ i = j;
+ }
+
+ /* ret is 2 for "print only" option */
+ if (ret == 2) {
+ add_history(result);
+#ifdef GDB_411_HACK
+ /* gdb 4.11 has been shipped with readline, where */
+ /* history_expand() returned -1 when the line */
+ /* should not be executed; in readline 2.1+ */
+ /* it should return 2 in such a case */
+ ret = -1;
+#endif
+ }
+ el_free(*output);
+ *output = result;
+
+ return ret;
+}
+
+/*
+* Return a string consisting of arguments of "str" from "start" to "end".
+*/
+char *
+history_arg_extract(int start, int end, const char *str)
+{
+ size_t i, len, max;
+ char **arr, *result = NULL;
+
+ arr = history_tokenize(str);
+ if (!arr)
+ return NULL;
+ if (arr && *arr == NULL)
+ goto out;
+
+ for (max = 0; arr[max]; max++)
+ continue;
+ max--;
+
+ if (start == '$')
+ start = (int)max;
+ if (end == '$')
+ end = (int)max;
+ if (end < 0)
+ end = (int)max + end + 1;
+ if (start < 0)
+ start = end;
+
+ if (start < 0 || end < 0 || (size_t)start > max ||
+ (size_t)end > max || start > end)
+ goto out;
+
+ for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
+ len += strlen(arr[i]) + 1;
+ len++;
+ result = el_malloc(len * sizeof(*result));
+ if (result == NULL)
+ goto out;
+
+ for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
+ (void)strcpy(result + len, arr[i]);
+ len += strlen(arr[i]);
+ if (i < (size_t)end)
+ result[len++] = ' ';
+ }
+ result[len] = '\0';
+
+out:
+ for (i = 0; arr[i]; i++)
+ el_free(arr[i]);
+ el_free(arr);
+
+ return result;
+}
+
+/*
+ * Parse the string into individual tokens,
+ * similar to how shell would do it.
+ */
+char **
+history_tokenize(const char *str)
+{
+ int size = 1, idx = 0, i, start;
+ size_t len;
+ char **result = NULL, *temp, delim = '\0';
+
+ for (i = 0; str[i];) {
+ while (isspace((unsigned char) str[i]))
+ i++;
+ start = i;
+ for (; str[i];) {
+ if (str[i] == '\\') {
+ if (str[i+1] != '\0')
+ i++;
+ } else if (str[i] == delim)
+ delim = '\0';
+ else if (!delim &&
+ (isspace((unsigned char) str[i]) ||
+ strchr("()<>;&|$", str[i])))
+ break;
+ else if (!delim && strchr("'`\"", str[i]))
+ delim = str[i];
+ if (str[i])
+ i++;
+ }
+
+ if (idx + 2 >= size) {
+ char **nresult;
+ size <<= 1;
+ nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
+ if (nresult == NULL) {
+ el_free(result);
+ return NULL;
+ }
+ result = nresult;
+ }
+ len = (size_t)i - (size_t)start;
+ temp = el_malloc((size_t)(len + 1) * sizeof(*temp));
+ if (temp == NULL) {
+ for (i = 0; i < idx; i++)
+ el_free(result[i]);
+ el_free(result);
+ return NULL;
+ }
+ (void)strncpy(temp, &str[start], len);
+ temp[len] = '\0';
+ result[idx++] = temp;
+ result[idx] = NULL;
+ if (str[i])
+ i++;
+ }
+ return result;
+}
+
+
+/*
+ * limit size of history record to ``max'' events
+ */
+void
+stifle_history(int max)
+{
+ HistEvent ev;
+ HIST_ENTRY *he;
+
+ if (h == NULL || e == NULL)
+ rl_initialize();
+
+ if (history(h, &ev, H_SETSIZE, max) == 0) {
+ max_input_history = max;
+ if (history_length > max)
+ history_base = history_length - max;
+ while (history_length > max) {
+ he = remove_history(0);
+ el_free(he->data);
+ el_free((void *)(unsigned long)he->line);
+ el_free(he);
+ }
+ }
+}
+
+
+/*
+ * "unlimit" size of history - set the limit to maximum allowed int value
+ */
+int
+unstifle_history(void)
+{
+ HistEvent ev;
+ int omax;
+
+ history(h, &ev, H_SETSIZE, INT_MAX);
+ omax = max_input_history;
+ max_input_history = INT_MAX;
+ return omax; /* some value _must_ be returned */
+}
+
+
+int
+history_is_stifled(void)
+{
+
+ /* cannot return true answer */
+ return max_input_history != INT_MAX;
+}
+
+static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
+
+int
+history_truncate_file (const char *filename, int nlines)
+{
+ int ret = 0;
+ FILE *fp, *tp;
+ char template[sizeof(_history_tmp_template)];
+ char buf[4096];
+ int fd;
+ char *cp;
+ off_t off;
+ int count = 0;
+ ssize_t left = 0;
+
+ if (filename == NULL && (filename = _default_history_file()) == NULL)
+ return errno;
+ if ((fp = fopen(filename, "r+")) == NULL)
+ return errno;
+ strcpy(template, _history_tmp_template);
+ if ((fd = mkstemp(template)) == -1) {
+ ret = errno;
+ goto out1;
+ }
+
+ if ((tp = fdopen(fd, "r+")) == NULL) {
+ close(fd);
+ ret = errno;
+ goto out2;
+ }
+
+ for(;;) {
+ if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
+ if (ferror(fp)) {
+ ret = errno;
+ break;
+ }
+ if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
+ (off_t)-1) {
+ ret = errno;
+ break;
+ }
+ left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
+ if (ferror(fp)) {
+ ret = errno;
+ break;
+ }
+ if (left == 0) {
+ count--;
+ left = sizeof(buf);
+ } else if (fwrite(buf, (size_t)left, (size_t)1, tp)
+ != 1) {
+ ret = errno;
+ break;
+ }
+ fflush(tp);
+ break;
+ }
+ if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
+ ret = errno;
+ break;
+ }
+ count++;
+ }
+ if (ret)
+ goto out3;
+ cp = buf + left - 1;
+ if(*cp != '\n')
+ cp++;
+ for(;;) {
+ while (--cp >= buf) {
+ if (*cp == '\n') {
+ if (--nlines == 0) {
+ if (++cp >= buf + sizeof(buf)) {
+ count++;
+ cp = buf;
+ }
+ break;
+ }
+ }
+ }
+ if (nlines <= 0 || count == 0)
+ break;
+ count--;
+ if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
+ ret = errno;
+ break;
+ }
+ if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
+ if (ferror(tp)) {
+ ret = errno;
+ break;
+ }
+ ret = EAGAIN;
+ break;
+ }
+ cp = buf + sizeof(buf);
+ }
+
+ if (ret || nlines > 0)
+ goto out3;
+
+ if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
+ ret = errno;
+ goto out3;
+ }
+
+ if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
+ (off_t)-1) {
+ ret = errno;
+ goto out3;
+ }
+
+ for(;;) {
+ if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
+ if (ferror(fp))
+ ret = errno;
+ break;
+ }
+ if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
+ ret = errno;
+ break;
+ }
+ }
+ fflush(fp);
+ if((off = ftello(fp)) > 0)
+ (void)ftruncate(fileno(fp), off);
+out3:
+ fclose(tp);
+out2:
+ unlink(template);
+out1:
+ fclose(fp);
+
+ return ret;
+}
+
+
+/*
+ * read history from a file given
+ */
+int
+read_history(const char *filename)
+{
+ HistEvent ev;
+
+ if (h == NULL || e == NULL)
+ rl_initialize();
+ if (filename == NULL && (filename = _default_history_file()) == NULL)
+ return errno;
+ return history(h, &ev, H_LOAD, filename) == -1 ?
+ (errno ? errno : EINVAL) : 0;
+}
+
+
+/*
+ * write history to a file given
+ */
+int
+write_history(const char *filename)
+{
+ HistEvent ev;
+
+ if (h == NULL || e == NULL)
+ rl_initialize();
+ if (filename == NULL && (filename = _default_history_file()) == NULL)
+ return errno;
+ return history(h, &ev, H_SAVE, filename) == -1 ?
+ (errno ? errno : EINVAL) : 0;
+}
+
+
+/*
+ * returns history ``num''th event
+ *
+ * returned pointer points to static variable
+ */
+HIST_ENTRY *
+history_get(int num)
+{
+ static HIST_ENTRY she;
+ HistEvent ev;
+ int curr_num;
+
+ if (h == NULL || e == NULL)
+ rl_initialize();
+
+ if (num < history_base)
+ return NULL;
+
+ /* save current position */
+ if (history(h, &ev, H_CURR) != 0)
+ return NULL;
+ curr_num = ev.num;
+
+ /*
+ * use H_DELDATA to set to nth history (without delete) by passing
+ * (void **)-1 -- as in history_set_pos
+ */
+ if (history(h, &ev, H_DELDATA, num - history_base, (void **)-1) != 0)
+ goto out;
+
+ /* get current entry */
+ if (history(h, &ev, H_CURR) != 0)
+ goto out;
+ if (history(h, &ev, H_NEXT_EVDATA, ev.num, &she.data) != 0)
+ goto out;
+ she.line = ev.str;
+
+ /* restore pointer to where it was */
+ (void)history(h, &ev, H_SET, curr_num);
+
+ return &she;
+
+out:
+ /* restore pointer to where it was */
+ (void)history(h, &ev, H_SET, curr_num);
+ return NULL;
+}
+
+
+/*
+ * add the line to history table
+ */
+int
+add_history(const char *line)
+{
+ HistEvent ev;
+
+ if (h == NULL || e == NULL)
+ rl_initialize();
+
+ if (history(h, &ev, H_ENTER, line) == -1)
+ return 0;
+
+ (void)history(h, &ev, H_GETSIZE);
+ if (ev.num == history_length)
+ history_base++;
+ else
+ history_length = ev.num;
+ return 0;
+}
+
+
+/*
+ * remove the specified entry from the history list and return it.
+ */
+HIST_ENTRY *
+remove_history(int num)
+{
+ HIST_ENTRY *he;
+ HistEvent ev;
+
+ if (h == NULL || e == NULL)
+ rl_initialize();
+
+ if ((he = el_malloc(sizeof(*he))) == NULL)
+ return NULL;
+
+ if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
+ el_free(he);
+ return NULL;
+ }
+
+ he->line = ev.str;
+ if (history(h, &ev, H_GETSIZE) == 0)
+ history_length = ev.num;
+
+ return he;
+}
+
+
+/*
+ * replace the line and data of the num-th entry
+ */
+HIST_ENTRY *
+replace_history_entry(int num, const char *line, histdata_t data)
+{
+ HIST_ENTRY *he;
+ HistEvent ev;
+ int curr_num;
+
+ if (h == NULL || e == NULL)
+ rl_initialize();
+
+ /* save current position */
+ if (history(h, &ev, H_CURR) != 0)
+ return NULL;
+ curr_num = ev.num;
+
+ /* start from the oldest */
+ if (history(h, &ev, H_LAST) != 0)
+ return NULL; /* error */
+
+ if ((he = el_malloc(sizeof(*he))) == NULL)
+ return NULL;
+
+ /* look forwards for event matching specified offset */
+ if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
+ goto out;
+
+ he->line = strdup(ev.str);
+ if (he->line == NULL)
+ goto out;
+
+ if (history(h, &ev, H_REPLACE, line, data))
+ goto out;
+
+ /* restore pointer to where it was */
+ if (history(h, &ev, H_SET, curr_num))
+ goto out;
+
+ return he;
+out:
+ el_free(he);
+ return NULL;
+}
+
+/*
+ * clear the history list - delete all entries
+ */
+void
+clear_history(void)
+{
+ HistEvent ev;
+
+ if (h == NULL || e == NULL)
+ rl_initialize();
+
+ (void)history(h, &ev, H_CLEAR);
+ history_offset = history_length = 0;
+}
+
+
+/*
+ * returns offset of the current history event
+ */
+int
+where_history(void)
+{
+ return history_offset;
+}
+
+static HIST_ENTRY **_history_listp;
+static HIST_ENTRY *_history_list;
+
+HIST_ENTRY **
+history_list(void)
+{
+ HistEvent ev;
+ HIST_ENTRY **nlp, *nl;
+ int i;
+
+ if (history(h, &ev, H_LAST) != 0)
+ return NULL;
+
+ if ((nlp = el_realloc(_history_listp,
+ (size_t)history_length * sizeof(*nlp))) == NULL)
+ return NULL;
+ _history_listp = nlp;
+
+ if ((nl = el_realloc(_history_list,
+ (size_t)history_length * sizeof(*nl))) == NULL)
+ return NULL;
+ _history_list = nl;
+
+ i = 0;
+ do {
+ _history_listp[i] = &_history_list[i];
+ _history_list[i].line = ev.str;
+ _history_list[i].data = NULL;
+ if (i++ == history_length)
+ abort();
+ } while (history(h, &ev, H_PREV) == 0);
+ return _history_listp;
+}
+
+/*
+ * returns current history event or NULL if there is no such event
+ */
+HIST_ENTRY *
+current_history(void)
+{
+ HistEvent ev;
+
+ if (history(h, &ev, H_PREV_EVENT, history_offset + 1) != 0)
+ return NULL;
+
+ rl_he.line = ev.str;
+ rl_he.data = NULL;
+ return &rl_he;
+}
+
+
+/*
+ * returns total number of bytes history events' data are using
+ */
+int
+history_total_bytes(void)
+{
+ HistEvent ev;
+ int curr_num;
+ size_t size;
+
+ if (history(h, &ev, H_CURR) != 0)
+ return -1;
+ curr_num = ev.num;
+
+ (void)history(h, &ev, H_FIRST);
+ size = 0;
+ do
+ size += strlen(ev.str) * sizeof(*ev.str);
+ while (history(h, &ev, H_NEXT) == 0);
+
+ /* get to the same position as before */
+ history(h, &ev, H_PREV_EVENT, curr_num);
+
+ return (int)size;
+}
+
+
+/*
+ * sets the position in the history list to ``pos''
+ */
+int
+history_set_pos(int pos)
+{
+ if (pos >= history_length || pos < 0)
+ return 0;
+
+ history_offset = pos;
+ return 1;
+}
+
+
+/*
+ * returns previous event in history and shifts pointer accordingly
+ * Note that readline and editline define directions in opposite ways.
+ */
+HIST_ENTRY *
+previous_history(void)
+{
+ HistEvent ev;
+
+ if (history_offset == 0)
+ return NULL;
+
+ if (history(h, &ev, H_LAST) != 0)
+ return NULL;
+
+ history_offset--;
+ return current_history();
+}
+
+
+/*
+ * returns next event in history and shifts pointer accordingly
+ */
+HIST_ENTRY *
+next_history(void)
+{
+ HistEvent ev;
+
+ if (history_offset >= history_length)
+ return NULL;
+
+ if (history(h, &ev, H_LAST) != 0)
+ return NULL;
+
+ history_offset++;
+ return current_history();
+}
+
+
+/*
+ * searches for first history event containing the str
+ */
+int
+history_search(const char *str, int direction)
+{
+ HistEvent ev;
+ const char *strp;
+ int curr_num;
+
+ if (history(h, &ev, H_CURR) != 0)
+ return -1;
+ curr_num = ev.num;
+
+ for (;;) {
+ if ((strp = strstr(ev.str, str)) != NULL)
+ return (int)(strp - ev.str);
+ if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
+ break;
+ }
+ (void)history(h, &ev, H_SET, curr_num);
+ return -1;
+}
+
+
+/*
+ * searches for first history event beginning with str
+ */
+int
+history_search_prefix(const char *str, int direction)
+{
+ HistEvent ev;
+
+ return (history(h, &ev, direction < 0 ?
+ H_PREV_STR : H_NEXT_STR, str));
+}
+
+
+/*
+ * search for event in history containing str, starting at offset
+ * abs(pos); continue backward, if pos<0, forward otherwise
+ */
+/* ARGSUSED */
+int
+history_search_pos(const char *str,
+ int direction __attribute__((__unused__)), int pos)
+{
+ HistEvent ev;
+ int curr_num, off;
+
+ off = (pos > 0) ? pos : -pos;
+ pos = (pos > 0) ? 1 : -1;
+
+ if (history(h, &ev, H_CURR) != 0)
+ return -1;
+ curr_num = ev.num;
+
+ if (!history_set_pos(off) || history(h, &ev, H_CURR) != 0)
+ return -1;
+
+ for (;;) {
+ if (strstr(ev.str, str))
+ return off;
+ if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
+ break;
+ }
+
+ /* set "current" pointer back to previous state */
+ (void)history(h, &ev,
+ pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
+
+ return -1;
+}
+
+
+/********************************/
+/* completion functions */
+
+char *
+tilde_expand(char *name)
+{
+ return fn_tilde_expand(name);
+}
+
+char *
+filename_completion_function(const char *name, int state)
+{
+ return fn_filename_completion_function(name, state);
+}
+
+/*
+ * a completion generator for usernames; returns _first_ username
+ * which starts with supplied text
+ * text contains a partial username preceded by random character
+ * (usually '~'); state resets search from start (??? should we do that anyway)
+ * it's the caller's responsibility to free the returned value
+ */
+char *
+username_completion_function(const char *text, int state)
+{
+#if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
+ struct passwd pwres;
+ char pwbuf[1024];
+#endif
+ struct passwd *pass = NULL;
+
+ if (text[0] == '\0')
+ return NULL;
+
+ if (*text == '~')
+ text++;
+
+ if (state == 0)
+ setpwent();
+
+ while (
+ (pass = getpwent()) != NULL
+ && text[0] == pass->pw_name[0]
+ && strcmp(text, pass->pw_name) == 0)
+ continue;
+
+ if (pass == NULL) {
+ endpwent();
+ return NULL;
+ }
+ return strdup(pass->pw_name);
+}
+
+
+/*
+ * el-compatible wrapper to send TSTP on ^Z
+ */
+/* ARGSUSED */
+static unsigned char
+_el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
+{
+ (void)kill(0, SIGTSTP);
+ return CC_NORM;
+}
+
+/*
+ * Display list of strings in columnar format on readline's output stream.
+ * 'matches' is list of strings, 'len' is number of strings in 'matches',
+ * 'max' is maximum length of string in 'matches'.
+ */
+void
+rl_display_match_list(char **matches, int len, int max)
+{
+
+ fn_display_match_list(e, matches, (size_t)len, (size_t)max);
+}
+
+static const char *
+/*ARGSUSED*/
+_rl_completion_append_character_function(const char *dummy
+ __attribute__((__unused__)))
+{
+ static char buf[2];
+ buf[0] = (char)rl_completion_append_character;
+ buf[1] = '\0';
+ return buf;
+}
+
+
+/*
+ * complete word at current point
+ */
+/* ARGSUSED */
+int
+rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
+{
+ static ct_buffer_t wbreak_conv, sprefix_conv;
+ char *breakchars;
+
+ if (h == NULL || e == NULL)
+ rl_initialize();
+
+ if (rl_inhibit_completion) {
+ char arr[2];
+ arr[0] = (char)invoking_key;
+ arr[1] = '\0';
+ el_insertstr(e, arr);
+ return CC_REFRESH;
+ }
+
+ if (rl_completion_word_break_hook != NULL)
+ breakchars = (*rl_completion_word_break_hook)();
+ else
+ breakchars = rl_basic_word_break_characters;
+
+ _rl_update_pos();
+
+ /* Just look at how many global variables modify this operation! */
+ return fn_complete(e,
+ (rl_compentry_func_t *)rl_completion_entry_function,
+ rl_attempted_completion_function,
+ ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
+ ct_decode_string(breakchars, &sprefix_conv),
+ _rl_completion_append_character_function,
+ (size_t)rl_completion_query_items,
+ &rl_completion_type, &rl_attempted_completion_over,
+ &rl_point, &rl_end);
+
+
+}
+
+
+/* ARGSUSED */
+static unsigned char
+_el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
+{
+ return (unsigned char)rl_complete(0, ch);
+}
+
+/*
+ * misc other functions
+ */
+
+/*
+ * bind key c to readline-type function func
+ */
+int
+rl_bind_key(int c, rl_command_func_t *func)
+{
+ int retval = -1;
+
+ if (h == NULL || e == NULL)
+ rl_initialize();
+
+ if (func == rl_insert) {
+ /* XXX notice there is no range checking of ``c'' */
+ e->el_map.key[c] = ED_INSERT;
+ retval = 0;
+ }
+ return retval;
+}
+
+
+/*
+ * read one key from input - handles chars pushed back
+ * to input stream also
+ */
+int
+rl_read_key(void)
+{
+ char fooarr[2 * sizeof(int)];
+
+ if (e == NULL || h == NULL)
+ rl_initialize();
+
+ return el_getc(e, fooarr);
+}
+
+
+/*
+ * reset the terminal
+ */
+/* ARGSUSED */
+void
+rl_reset_terminal(const char *p __attribute__((__unused__)))
+{
+
+ if (h == NULL || e == NULL)
+ rl_initialize();
+ el_reset(e);
+}
+
+
+/*
+ * insert character ``c'' back into input stream, ``count'' times
+ */
+int
+rl_insert(int count, int c)
+{
+ char arr[2];
+
+ if (h == NULL || e == NULL)
+ rl_initialize();
+
+ /* XXX - int -> char conversion can lose on multichars */
+ arr[0] = (char)c;
+ arr[1] = '\0';
+
+ for (; count > 0; count--)
+ el_push(e, arr);
+
+ return 0;
+}
+
+int
+rl_insert_text(const char *text)
+{
+ if (!text || *text == 0)
+ return 0;
+
+ if (h == NULL || e == NULL)
+ rl_initialize();
+
+ if (el_insertstr(e, text) < 0)
+ return 0;
+ return (int)strlen(text);
+}
+
+/*ARGSUSED*/
+int
+rl_newline(int count __attribute__((__unused__)),
+ int c __attribute__((__unused__)))
+{
+ /*
+ * Readline-4.0 appears to ignore the args.
+ */
+ return rl_insert(1, '\n');
+}
+
+/*ARGSUSED*/
+static unsigned char
+rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
+{
+ if (map[c] == NULL)
+ return CC_ERROR;
+
+ _rl_update_pos();
+
+ (*map[c])(1, c);
+
+ /* If rl_done was set by the above call, deal with it here */
+ if (rl_done)
+ return CC_EOF;
+
+ return CC_NORM;
+}
+
+int
+rl_add_defun(const char *name, rl_command_func_t *fun, int c)
+{
+ char dest[8];
+ if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
+ return -1;
+ map[(unsigned char)c] = fun;
+ el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
+ vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
+ el_set(e, EL_BIND, dest, name, NULL);
+ return 0;
+}
+
+void
+rl_callback_read_char(void)
+{
+ int count = 0, done = 0;
+ const char *buf = el_gets(e, &count);
+ char *wbuf;
+
+ if (buf == NULL || count-- <= 0)
+ return;
+ if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
+ done = 1;
+ if (buf[count] == '\n' || buf[count] == '\r')
+ done = 2;
+
+ if (done && rl_linefunc != NULL) {
+ el_set(e, EL_UNBUFFERED, 0);
+ if (done == 2) {
+ if ((wbuf = strdup(buf)) != NULL)
+ wbuf[count] = '\0';
+ } else
+ wbuf = NULL;
+ (*(void (*)(const char *))rl_linefunc)(wbuf);
+ el_set(e, EL_UNBUFFERED, 1);
+ }
+}
+
+void
+rl_callback_handler_install(const char *prompt, rl_vcpfunc_t *linefunc)
+{
+ if (e == NULL) {
+ rl_initialize();
+ }
+ (void)rl_set_prompt(prompt);
+ rl_linefunc = linefunc;
+ el_set(e, EL_UNBUFFERED, 1);
+}
+
+void
+rl_callback_handler_remove(void)
+{
+ el_set(e, EL_UNBUFFERED, 0);
+ rl_linefunc = NULL;
+}
+
+void
+rl_redisplay(void)
+{
+ char a[2];
+ a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
+ a[1] = '\0';
+ el_push(e, a);
+}
+
+int
+rl_get_previous_history(int count, int key)
+{
+ char a[2];
+ a[0] = (char)key;
+ a[1] = '\0';
+ while (count--)
+ el_push(e, a);
+ return 0;
+}
+
+void
+/*ARGSUSED*/
+rl_prep_terminal(int meta_flag __attribute__((__unused__)))
+{
+ el_set(e, EL_PREP_TERM, 1);
+}
+
+void
+rl_deprep_terminal(void)
+{
+ el_set(e, EL_PREP_TERM, 0);
+}
+
+int
+rl_read_init_file(const char *s)
+{
+ return el_source(e, s);
+}
+
+int
+rl_parse_and_bind(const char *line)
+{
+ const char **argv;
+ int argc;
+ Tokenizer *tok;
+
+ tok = tok_init(NULL);
+ tok_str(tok, line, &argc, &argv);
+ argc = el_parse(e, argc, argv);
+ tok_end(tok);
+ return argc ? 1 : 0;
+}
+
+int
+rl_variable_bind(const char *var, const char *value)
+{
+ /*
+ * The proper return value is undocument, but this is what the
+ * readline source seems to do.
+ */
+ return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0;
+}
+
+void
+rl_stuff_char(int c)
+{
+ char buf[2];
+
+ buf[0] = (char)c;
+ buf[1] = '\0';
+ el_insertstr(e, buf);
+}
+
+static int
+_rl_event_read_char(EditLine *el, wchar_t *wc)
+{
+ char ch;
+ int n;
+ ssize_t num_read = 0;
+
+ ch = '\0';
+ *wc = L'\0';
+ while (rl_event_hook) {
+
+ (*rl_event_hook)();
+
+#if defined(FIONREAD)
+ if (ioctl(el->el_infd, FIONREAD, &n) < 0)
+ return -1;
+ if (n)
+ num_read = read(el->el_infd, &ch, (size_t)1);
+ else
+ num_read = 0;
+#elif defined(F_SETFL) && defined(O_NDELAY)
+ if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
+ return -1;
+ if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
+ return -1;
+ num_read = read(el->el_infd, &ch, 1);
+ if (fcntl(el->el_infd, F_SETFL, n))
+ return -1;
+#else
+ /* not non-blocking, but what you gonna do? */
+ num_read = read(el->el_infd, &ch, 1);
+ return -1;
+#endif
+
+ if (num_read < 0 && errno == EAGAIN)
+ continue;
+ if (num_read == 0)
+ continue;
+ break;
+ }
+ if (!rl_event_hook)
+ el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
+ *wc = (wchar_t)ch;
+ return (int)num_read;
+}
+
+static void
+_rl_update_pos(void)
+{
+ const LineInfo *li = el_line(e);
+
+ rl_point = (int)(li->cursor - li->buffer);
+ rl_end = (int)(li->lastchar - li->buffer);
+}
+
+void
+rl_get_screen_size(int *rows, int *cols)
+{
+ if (rows)
+ el_get(e, EL_GETTC, "li", rows, (void *)0);
+ if (cols)
+ el_get(e, EL_GETTC, "co", cols, (void *)0);
+}
+
+void
+rl_set_screen_size(int rows, int cols)
+{
+ char buf[64];
+ (void)snprintf(buf, sizeof(buf), "%d", rows);
+ el_set(e, EL_SETTC, "li", buf, NULL);
+ (void)snprintf(buf, sizeof(buf), "%d", cols);
+ el_set(e, EL_SETTC, "co", buf, NULL);
+}
+
+char **
+rl_completion_matches(const char *str, rl_compentry_func_t *fun)
+{
+ size_t len, max, i, j, min;
+ char **list, *match, *a, *b;
+
+ len = 1;
+ max = 10;
+ if ((list = el_malloc(max * sizeof(*list))) == NULL)
+ return NULL;
+
+ while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
+ list[len++] = match;
+ if (len == max) {
+ char **nl;
+ max += 10;
+ if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
+ goto out;
+ list = nl;
+ }
+ }
+ if (len == 1)
+ goto out;
+ list[len] = NULL;
+ if (len == 2) {
+ if ((list[0] = strdup(list[1])) == NULL)
+ goto out;
+ return list;
+ }
+ qsort(&list[1], len - 1, sizeof(*list),
+ (int (*)(const void *, const void *)) strcmp);
+ min = SIZE_MAX;
+ for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
+ b = list[i + 1];
+ for (j = 0; a[j] && a[j] == b[j]; j++)
+ continue;
+ if (min > j)
+ min = j;
+ }
+ if (min == 0 && *str) {
+ if ((list[0] = strdup(str)) == NULL)
+ goto out;
+ } else {
+ if ((list[0] = el_malloc((min + 1) * sizeof(*list[0]))) == NULL)
+ goto out;
+ (void)memcpy(list[0], list[1], min);
+ list[0][min] = '\0';
+ }
+ return list;
+
+out:
+ el_free(list);
+ return NULL;
+}
+
+char *
+rl_filename_completion_function (const char *text, int state)
+{
+ return fn_filename_completion_function(text, state);
+}
+
+void
+rl_forced_update_display(void)
+{
+ el_set(e, EL_REFRESH);
+}
+
+int
+_rl_abort_internal(void)
+{
+ el_beep(e);
+ longjmp(topbuf, 1);
+ /*NOTREACHED*/
+}
+
+int
+_rl_qsort_string_compare(char **s1, char **s2)
+{
+ return strcoll(*s1, *s2);
+}
+
+HISTORY_STATE *
+history_get_history_state(void)
+{
+ HISTORY_STATE *hs;
+
+ if ((hs = el_malloc(sizeof(*hs))) == NULL)
+ return NULL;
+ hs->length = history_length;
+ return hs;
+}
+
+int
+/*ARGSUSED*/
+rl_kill_text(int from __attribute__((__unused__)),
+ int to __attribute__((__unused__)))
+{
+ return 0;
+}
+
+Keymap
+rl_make_bare_keymap(void)
+{
+ return NULL;
+}
+
+Keymap
+rl_get_keymap(void)
+{
+ return NULL;
+}
+
+void
+/*ARGSUSED*/
+rl_set_keymap(Keymap k __attribute__((__unused__)))
+{
+}
+
+int
+/*ARGSUSED*/
+rl_generic_bind(int type __attribute__((__unused__)),
+ const char * keyseq __attribute__((__unused__)),
+ const char * data __attribute__((__unused__)),
+ Keymap k __attribute__((__unused__)))
+{
+ return 0;
+}
+
+int
+/*ARGSUSED*/
+rl_bind_key_in_map(int key __attribute__((__unused__)),
+ rl_command_func_t *fun __attribute__((__unused__)),
+ Keymap k __attribute__((__unused__)))
+{
+ return 0;
+}
+
+/* unsupported, but needed by python */
+void
+rl_cleanup_after_signal(void)
+{
+}
+
+int
+rl_on_new_line(void)
+{
+ return 0;
+}
+
+void
+rl_free_line_state(void)
+{
+}
+
+int
+/*ARGSUSED*/
+rl_set_keyboard_input_timeout(int u __attribute__((__unused__)))
+{
+ return 0;
+}
diff --git a/third_party/heimdal/lib/libedit/src/readline/readline.h b/third_party/heimdal/lib/libedit/src/readline/readline.h
new file mode 100644
index 0000000..79ae115
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/readline/readline.h
@@ -0,0 +1,227 @@
+/* $NetBSD: readline.h,v 1.41 2016/10/28 18:32:35 christos Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jaromir Dolecek.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _READLINE_H_
+#define _READLINE_H_
+
+#include <sys/types.h>
+#include <stdio.h>
+
+/* list of readline stuff supported by editline library's readline wrapper */
+
+/* typedefs */
+typedef int Function(const char *, int);
+typedef void VFunction(void);
+typedef void rl_vcpfunc_t(char *);
+typedef char **rl_completion_func_t(const char *, int, int);
+typedef char *rl_compentry_func_t(const char *, int);
+typedef int rl_command_func_t(int, int);
+
+/* only supports length */
+typedef struct {
+ int length;
+} HISTORY_STATE;
+
+typedef void *histdata_t;
+
+typedef struct _hist_entry {
+ const char *line;
+ histdata_t data;
+} HIST_ENTRY;
+
+typedef struct _keymap_entry {
+ char type;
+#define ISFUNC 0
+#define ISKMAP 1
+#define ISMACR 2
+ Function *function;
+} KEYMAP_ENTRY;
+
+#define KEYMAP_SIZE 256
+
+typedef KEYMAP_ENTRY KEYMAP_ENTRY_ARRAY[KEYMAP_SIZE];
+typedef KEYMAP_ENTRY *Keymap;
+
+#define control_character_threshold 0x20
+#define control_character_bit 0x40
+
+#ifndef CTRL
+#include <sys/ioctl.h>
+#if !defined(__sun) && !defined(__hpux) && !defined(_AIX) && !defined(_CYGWIN_)
+#include <sys/ttydefaults.h>
+#endif
+#ifndef CTRL
+#define CTRL(c) ((c) & 037)
+#endif
+#endif
+#ifndef UNCTRL
+#define UNCTRL(c) (((c) - 'a' + 'A')|control_character_bit)
+#endif
+
+#define RUBOUT 0x7f
+#define ABORT_CHAR CTRL('G')
+#define RL_READLINE_VERSION 0x0402
+#define RL_PROMPT_START_IGNORE '\1'
+#define RL_PROMPT_END_IGNORE '\2'
+
+/* global variables used by readline enabled applications */
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern const char *rl_library_version;
+extern int rl_readline_version;
+extern char *rl_readline_name;
+extern FILE *rl_instream;
+extern FILE *rl_outstream;
+extern char *rl_line_buffer;
+extern int rl_point, rl_end;
+extern int history_base, history_length;
+extern int max_input_history;
+extern char *rl_basic_word_break_characters;
+extern char *rl_completer_word_break_characters;
+extern char *rl_completer_quote_characters;
+extern rl_compentry_func_t *rl_completion_entry_function;
+extern char *(*rl_completion_word_break_hook)(void);
+extern rl_completion_func_t *rl_attempted_completion_function;
+extern int rl_attempted_completion_over;
+extern int rl_completion_type;
+extern int rl_completion_query_items;
+extern char *rl_special_prefixes;
+extern int rl_completion_append_character;
+extern int rl_inhibit_completion;
+extern Function *rl_pre_input_hook;
+extern Function *rl_startup_hook;
+extern char *rl_terminal_name;
+extern int rl_already_prompted;
+extern char *rl_prompt;
+extern int rl_done;
+/*
+ * The following is not implemented
+ */
+extern int rl_catch_signals;
+extern int rl_catch_sigwinch;
+extern KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
+ emacs_meta_keymap,
+ emacs_ctlx_keymap;
+extern int rl_filename_completion_desired;
+extern int rl_ignore_completion_duplicates;
+extern int (*rl_getc_function)(FILE *);
+extern VFunction *rl_redisplay_function;
+extern VFunction *rl_completion_display_matches_hook;
+extern VFunction *rl_prep_term_function;
+extern VFunction *rl_deprep_term_function;
+extern int readline_echoing_p;
+extern int _rl_print_completions_horizontally;
+
+/* supported functions */
+char *readline(const char *);
+int rl_initialize(void);
+
+void using_history(void);
+int add_history(const char *);
+void clear_history(void);
+void stifle_history(int);
+int unstifle_history(void);
+int history_is_stifled(void);
+int where_history(void);
+HIST_ENTRY *current_history(void);
+HIST_ENTRY *history_get(int);
+HIST_ENTRY *remove_history(int);
+HIST_ENTRY *replace_history_entry(int, const char *, histdata_t);
+int history_total_bytes(void);
+int history_set_pos(int);
+HIST_ENTRY *previous_history(void);
+HIST_ENTRY *next_history(void);
+HIST_ENTRY **history_list(void);
+int history_search(const char *, int);
+int history_search_prefix(const char *, int);
+int history_search_pos(const char *, int, int);
+int read_history(const char *);
+int write_history(const char *);
+int history_truncate_file (const char *, int);
+int history_expand(char *, char **);
+char **history_tokenize(const char *);
+const char *get_history_event(const char *, int *, int);
+char *history_arg_extract(int, int, const char *);
+
+char *tilde_expand(char *);
+char *filename_completion_function(const char *, int);
+char *username_completion_function(const char *, int);
+int rl_complete(int, int);
+int rl_read_key(void);
+char **completion_matches(const char *, rl_compentry_func_t *);
+void rl_display_match_list(char **, int, int);
+
+int rl_insert(int, int);
+int rl_insert_text(const char *);
+void rl_reset_terminal(const char *);
+int rl_bind_key(int, rl_command_func_t *);
+int rl_newline(int, int);
+void rl_callback_read_char(void);
+void rl_callback_handler_install(const char *, rl_vcpfunc_t *);
+void rl_callback_handler_remove(void);
+void rl_redisplay(void);
+int rl_get_previous_history(int, int);
+void rl_prep_terminal(int);
+void rl_deprep_terminal(void);
+int rl_read_init_file(const char *);
+int rl_parse_and_bind(const char *);
+int rl_variable_bind(const char *, const char *);
+void rl_stuff_char(int);
+int rl_add_defun(const char *, rl_command_func_t *, int);
+HISTORY_STATE *history_get_history_state(void);
+void rl_get_screen_size(int *, int *);
+void rl_set_screen_size(int, int);
+char *rl_filename_completion_function (const char *, int);
+int _rl_abort_internal(void);
+int _rl_qsort_string_compare(char **, char **);
+char **rl_completion_matches(const char *, rl_compentry_func_t *);
+void rl_forced_update_display(void);
+int rl_set_prompt(const char *);
+int rl_on_new_line(void);
+
+/*
+ * The following are not implemented
+ */
+int rl_kill_text(int, int);
+Keymap rl_get_keymap(void);
+void rl_set_keymap(Keymap);
+Keymap rl_make_bare_keymap(void);
+int rl_generic_bind(int, const char *, const char *, Keymap);
+int rl_bind_key_in_map(int, rl_command_func_t *, Keymap);
+void rl_cleanup_after_signal(void);
+void rl_free_line_state(void);
+int rl_set_keyboard_input_timeout(int);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _READLINE_H_ */
diff --git a/third_party/heimdal/lib/libedit/src/refresh.c b/third_party/heimdal/lib/libedit/src/refresh.c
new file mode 100644
index 0000000..e7775b0
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/refresh.c
@@ -0,0 +1,1187 @@
+/* $NetBSD: refresh.c,v 1.51 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)refresh.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: refresh.c,v 1.51 2016/05/09 21:46:56 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * refresh.c: Lower level screen refreshing functions
+ */
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "el.h"
+
+static void re_nextline(EditLine *);
+static void re_addc(EditLine *, wint_t);
+static void re_update_line(EditLine *, wchar_t *, wchar_t *, int);
+static void re_insert (EditLine *, wchar_t *, int, int, wchar_t *, int);
+static void re_delete(EditLine *, wchar_t *, int, int, int);
+static void re_fastputc(EditLine *, wint_t);
+static void re_clear_eol(EditLine *, int, int, int);
+static void re__strncopy(wchar_t *, wchar_t *, size_t);
+static void re__copy_and_pad(wchar_t *, const wchar_t *, size_t);
+
+#ifdef DEBUG_REFRESH
+static void re_printstr(EditLine *, const char *, wchar_t *, wchar_t *);
+#define __F el->el_errfile
+#define ELRE_ASSERT(a, b, c) do \
+ if (/*CONSTCOND*/ a) { \
+ (void) fprintf b; \
+ c; \
+ } \
+ while (/*CONSTCOND*/0)
+#define ELRE_DEBUG(a, b) ELRE_ASSERT(a,b,;)
+
+/* re_printstr():
+ * Print a string on the debugging pty
+ */
+static void
+re_printstr(EditLine *el, const char *str, wchar_t *f, wchar_t *t)
+{
+
+ ELRE_DEBUG(1, (__F, "%s:\"", str));
+ while (f < t)
+ ELRE_DEBUG(1, (__F, "%c", *f++ & 0177));
+ ELRE_DEBUG(1, (__F, "\"\r\n"));
+}
+#else
+#define ELRE_ASSERT(a, b, c)
+#define ELRE_DEBUG(a, b)
+#endif
+
+/* re_nextline():
+ * Move to the next line or scroll
+ */
+static void
+re_nextline(EditLine *el)
+{
+ el->el_refresh.r_cursor.h = 0; /* reset it. */
+
+ /*
+ * If we would overflow (input is longer than terminal size),
+ * emulate scroll by dropping first line and shuffling the rest.
+ * We do this via pointer shuffling - it's safe in this case
+ * and we avoid memcpy().
+ */
+ if (el->el_refresh.r_cursor.v + 1 >= el->el_terminal.t_size.v) {
+ int i, lins = el->el_terminal.t_size.v;
+ wchar_t *firstline = el->el_vdisplay[0];
+
+ for(i = 1; i < lins; i++)
+ el->el_vdisplay[i - 1] = el->el_vdisplay[i];
+
+ firstline[0] = '\0'; /* empty the string */
+ el->el_vdisplay[i - 1] = firstline;
+ } else
+ el->el_refresh.r_cursor.v++;
+
+ ELRE_ASSERT(el->el_refresh.r_cursor.v >= el->el_terminal.t_size.v,
+ (__F, "\r\nre_putc: overflow! r_cursor.v == %d > %d\r\n",
+ el->el_refresh.r_cursor.v, el->el_terminal.t_size.v),
+ abort());
+}
+
+/* re_addc():
+ * Draw c, expanding tabs, control chars etc.
+ */
+static void
+re_addc(EditLine *el, wint_t c)
+{
+ switch (ct_chr_class(c)) {
+ case CHTYPE_TAB: /* expand the tab */
+ for (;;) {
+ re_putc(el, ' ', 1);
+ if ((el->el_refresh.r_cursor.h & 07) == 0)
+ break; /* go until tab stop */
+ }
+ break;
+ case CHTYPE_NL: {
+ int oldv = el->el_refresh.r_cursor.v;
+ re_putc(el, '\0', 0); /* assure end of line */
+ if (oldv == el->el_refresh.r_cursor.v) /* XXX */
+ re_nextline(el);
+ break;
+ }
+ case CHTYPE_PRINT:
+ re_putc(el, c, 1);
+ break;
+ default: {
+ wchar_t visbuf[VISUAL_WIDTH_MAX];
+ ssize_t i, n =
+ ct_visual_char(visbuf, VISUAL_WIDTH_MAX, c);
+ for (i = 0; n-- > 0; ++i)
+ re_putc(el, visbuf[i], 1);
+ break;
+ }
+ }
+}
+
+
+/* re_putc():
+ * Draw the character given
+ */
+libedit_private void
+re_putc(EditLine *el, wint_t c, int shift)
+{
+ int i, w = wcwidth(c);
+ ELRE_DEBUG(1, (__F, "printing %5x '%lc'\r\n", c, c));
+ if (w == -1)
+ w = 0;
+
+ while (shift && (el->el_refresh.r_cursor.h + w > el->el_terminal.t_size.h))
+ re_putc(el, ' ', 1);
+
+ el->el_vdisplay[el->el_refresh.r_cursor.v]
+ [el->el_refresh.r_cursor.h] = c;
+ /* assumes !shift is only used for single-column chars */
+ i = w;
+ while (--i > 0)
+ el->el_vdisplay[el->el_refresh.r_cursor.v]
+ [el->el_refresh.r_cursor.h + i] = MB_FILL_CHAR;
+
+ if (!shift)
+ return;
+
+ el->el_refresh.r_cursor.h += w; /* advance to next place */
+ if (el->el_refresh.r_cursor.h >= el->el_terminal.t_size.h) {
+ /* assure end of line */
+ el->el_vdisplay[el->el_refresh.r_cursor.v][el->el_terminal.t_size.h]
+ = '\0';
+ re_nextline(el);
+ }
+}
+
+
+/* re_refresh():
+ * draws the new virtual screen image from the current input
+ * line, then goes line-by-line changing the real image to the new
+ * virtual image. The routine to re-draw a line can be replaced
+ * easily in hopes of a smarter one being placed there.
+ */
+libedit_private void
+re_refresh(EditLine *el)
+{
+ int i, rhdiff;
+ wchar_t *cp, *st;
+ coord_t cur;
+#ifdef notyet
+ size_t termsz;
+#endif
+
+ ELRE_DEBUG(1, (__F, "el->el_line.buffer = :%ls:\r\n",
+ el->el_line.buffer));
+
+ /* reset the Drawing cursor */
+ el->el_refresh.r_cursor.h = 0;
+ el->el_refresh.r_cursor.v = 0;
+
+ /* temporarily draw rprompt to calculate its size */
+ prompt_print(el, EL_RPROMPT);
+
+ /* reset the Drawing cursor */
+ el->el_refresh.r_cursor.h = 0;
+ el->el_refresh.r_cursor.v = 0;
+
+ if (el->el_line.cursor >= el->el_line.lastchar) {
+ if (el->el_map.current == el->el_map.alt
+ && el->el_line.lastchar != el->el_line.buffer)
+ el->el_line.cursor = el->el_line.lastchar - 1;
+ else
+ el->el_line.cursor = el->el_line.lastchar;
+ }
+
+ cur.h = -1; /* set flag in case I'm not set */
+ cur.v = 0;
+
+ prompt_print(el, EL_PROMPT);
+
+ /* draw the current input buffer */
+#if notyet
+ termsz = el->el_terminal.t_size.h * el->el_terminal.t_size.v;
+ if (el->el_line.lastchar - el->el_line.buffer > termsz) {
+ /*
+ * If line is longer than terminal, process only part
+ * of line which would influence display.
+ */
+ size_t rem = (el->el_line.lastchar-el->el_line.buffer)%termsz;
+
+ st = el->el_line.lastchar - rem
+ - (termsz - (((rem / el->el_terminal.t_size.v) - 1)
+ * el->el_terminal.t_size.v));
+ } else
+#endif
+ st = el->el_line.buffer;
+
+ for (cp = st; cp < el->el_line.lastchar; cp++) {
+ if (cp == el->el_line.cursor) {
+ int w = wcwidth(*cp);
+ /* save for later */
+ cur.h = el->el_refresh.r_cursor.h;
+ cur.v = el->el_refresh.r_cursor.v;
+ /* handle being at a linebroken doublewidth char */
+ if (w > 1 && el->el_refresh.r_cursor.h + w >
+ el->el_terminal.t_size.h) {
+ cur.h = 0;
+ cur.v++;
+ }
+ }
+ re_addc(el, *cp);
+ }
+
+ if (cur.h == -1) { /* if I haven't been set yet, I'm at the end */
+ cur.h = el->el_refresh.r_cursor.h;
+ cur.v = el->el_refresh.r_cursor.v;
+ }
+ rhdiff = el->el_terminal.t_size.h - el->el_refresh.r_cursor.h -
+ el->el_rprompt.p_pos.h;
+ if (el->el_rprompt.p_pos.h && !el->el_rprompt.p_pos.v &&
+ !el->el_refresh.r_cursor.v && rhdiff > 1) {
+ /*
+ * have a right-hand side prompt that will fit
+ * on the end of the first line with at least
+ * one character gap to the input buffer.
+ */
+ while (--rhdiff > 0) /* pad out with spaces */
+ re_putc(el, ' ', 1);
+ prompt_print(el, EL_RPROMPT);
+ } else {
+ el->el_rprompt.p_pos.h = 0; /* flag "not using rprompt" */
+ el->el_rprompt.p_pos.v = 0;
+ }
+
+ re_putc(el, '\0', 0); /* make line ended with NUL, no cursor shift */
+
+ el->el_refresh.r_newcv = el->el_refresh.r_cursor.v;
+
+ ELRE_DEBUG(1, (__F,
+ "term.h=%d vcur.h=%d vcur.v=%d vdisplay[0]=\r\n:%80.80s:\r\n",
+ el->el_terminal.t_size.h, el->el_refresh.r_cursor.h,
+ el->el_refresh.r_cursor.v, ct_encode_string(el->el_vdisplay[0],
+ &el->el_scratch)));
+
+ ELRE_DEBUG(1, (__F, "updating %d lines.\r\n", el->el_refresh.r_newcv));
+ for (i = 0; i <= el->el_refresh.r_newcv; i++) {
+ /* NOTE THAT re_update_line MAY CHANGE el_display[i] */
+ re_update_line(el, el->el_display[i], el->el_vdisplay[i], i);
+
+ /*
+ * Copy the new line to be the current one, and pad out with
+ * spaces to the full width of the terminal so that if we try
+ * moving the cursor by writing the character that is at the
+ * end of the screen line, it won't be a NUL or some old
+ * leftover stuff.
+ */
+ re__copy_and_pad(el->el_display[i], el->el_vdisplay[i],
+ (size_t) el->el_terminal.t_size.h);
+ }
+ ELRE_DEBUG(1, (__F,
+ "\r\nel->el_refresh.r_cursor.v=%d,el->el_refresh.r_oldcv=%d i=%d\r\n",
+ el->el_refresh.r_cursor.v, el->el_refresh.r_oldcv, i));
+
+ if (el->el_refresh.r_oldcv > el->el_refresh.r_newcv)
+ for (; i <= el->el_refresh.r_oldcv; i++) {
+ terminal_move_to_line(el, i);
+ terminal_move_to_char(el, 0);
+ /* This wcslen should be safe even with MB_FILL_CHARs */
+ terminal_clear_EOL(el, (int) wcslen(el->el_display[i]));
+#ifdef DEBUG_REFRESH
+ terminal_overwrite(el, L"C\b", 2);
+#endif /* DEBUG_REFRESH */
+ el->el_display[i][0] = '\0';
+ }
+
+ el->el_refresh.r_oldcv = el->el_refresh.r_newcv; /* set for next time */
+ ELRE_DEBUG(1, (__F,
+ "\r\ncursor.h = %d, cursor.v = %d, cur.h = %d, cur.v = %d\r\n",
+ el->el_refresh.r_cursor.h, el->el_refresh.r_cursor.v,
+ cur.h, cur.v));
+ terminal_move_to_line(el, cur.v); /* go to where the cursor is */
+ terminal_move_to_char(el, cur.h);
+}
+
+
+/* re_goto_bottom():
+ * used to go to last used screen line
+ */
+libedit_private void
+re_goto_bottom(EditLine *el)
+{
+
+ terminal_move_to_line(el, el->el_refresh.r_oldcv);
+ terminal__putc(el, '\n');
+ re_clear_display(el);
+ terminal__flush(el);
+}
+
+
+/* re_insert():
+ * insert num characters of s into d (in front of the character)
+ * at dat, maximum length of d is dlen
+ */
+static void
+/*ARGSUSED*/
+re_insert(EditLine *el __attribute__((__unused__)),
+ wchar_t *d, int dat, int dlen, wchar_t *s, int num)
+{
+ wchar_t *a, *b;
+
+ if (num <= 0)
+ return;
+ if (num > dlen - dat)
+ num = dlen - dat;
+
+ ELRE_DEBUG(1,
+ (__F, "re_insert() starting: %d at %d max %d, d == \"%s\"\n",
+ num, dat, dlen, ct_encode_string(d, &el->el_scratch)));
+ ELRE_DEBUG(1, (__F, "s == \"%s\"\n", ct_encode_string(s,
+ &el->el_scratch)));
+
+ /* open up the space for num chars */
+ if (num > 0) {
+ b = d + dlen - 1;
+ a = b - num;
+ while (a >= &d[dat])
+ *b-- = *a--;
+ d[dlen] = '\0'; /* just in case */
+ }
+
+ ELRE_DEBUG(1, (__F,
+ "re_insert() after insert: %d at %d max %d, d == \"%s\"\n",
+ num, dat, dlen, ct_encode_string(d, &el->el_scratch)));
+ ELRE_DEBUG(1, (__F, "s == \"%s\"\n", ct_encode_string(s,
+ &el->el_scratch)));
+
+ /* copy the characters */
+ for (a = d + dat; (a < d + dlen) && (num > 0); num--)
+ *a++ = *s++;
+
+#ifdef notyet
+ /* ct_encode_string() uses a static buffer, so we can't conveniently
+ * encode both d & s here */
+ ELRE_DEBUG(1,
+ (__F, "re_insert() after copy: %d at %d max %d, %s == \"%s\"\n",
+ num, dat, dlen, d, s));
+ ELRE_DEBUG(1, (__F, "s == \"%s\"\n", s));
+#endif
+}
+
+
+/* re_delete():
+ * delete num characters d at dat, maximum length of d is dlen
+ */
+static void
+/*ARGSUSED*/
+re_delete(EditLine *el __attribute__((__unused__)),
+ wchar_t *d, int dat, int dlen, int num)
+{
+ wchar_t *a, *b;
+
+ if (num <= 0)
+ return;
+ if (dat + num >= dlen) {
+ d[dat] = '\0';
+ return;
+ }
+ ELRE_DEBUG(1,
+ (__F, "re_delete() starting: %d at %d max %d, d == \"%s\"\n",
+ num, dat, dlen, ct_encode_string(d, &el->el_scratch)));
+
+ /* open up the space for num chars */
+ if (num > 0) {
+ b = d + dat;
+ a = b + num;
+ while (a < &d[dlen])
+ *b++ = *a++;
+ d[dlen] = '\0'; /* just in case */
+ }
+ ELRE_DEBUG(1,
+ (__F, "re_delete() after delete: %d at %d max %d, d == \"%s\"\n",
+ num, dat, dlen, ct_encode_string(d, &el->el_scratch)));
+}
+
+
+/* re__strncopy():
+ * Like strncpy without padding.
+ */
+static void
+re__strncopy(wchar_t *a, wchar_t *b, size_t n)
+{
+
+ while (n-- && *b)
+ *a++ = *b++;
+}
+
+/* re_clear_eol():
+ * Find the number of characters we need to clear till the end of line
+ * in order to make sure that we have cleared the previous contents of
+ * the line. fx and sx is the number of characters inserted or deleted
+ * in the first or second diff, diff is the difference between the
+ * number of characters between the new and old line.
+ */
+static void
+re_clear_eol(EditLine *el, int fx, int sx, int diff)
+{
+
+ ELRE_DEBUG(1, (__F, "re_clear_eol sx %d, fx %d, diff %d\n",
+ sx, fx, diff));
+
+ if (fx < 0)
+ fx = -fx;
+ if (sx < 0)
+ sx = -sx;
+ if (fx > diff)
+ diff = fx;
+ if (sx > diff)
+ diff = sx;
+
+ ELRE_DEBUG(1, (__F, "re_clear_eol %d\n", diff));
+ terminal_clear_EOL(el, diff);
+}
+
+/*****************************************************************
+ re_update_line() is based on finding the middle difference of each line
+ on the screen; vis:
+
+ /old first difference
+ /beginning of line | /old last same /old EOL
+ v v v v
+old: eddie> Oh, my little gruntle-buggy is to me, as lurgid as
+new: eddie> Oh, my little buggy says to me, as lurgid as
+ ^ ^ ^ ^
+ \beginning of line | \new last same \new end of line
+ \new first difference
+
+ all are character pointers for the sake of speed. Special cases for
+ no differences, as well as for end of line additions must be handled.
+**************************************************************** */
+
+/* Minimum at which doing an insert it "worth it". This should be about
+ * half the "cost" of going into insert mode, inserting a character, and
+ * going back out. This should really be calculated from the termcap
+ * data... For the moment, a good number for ANSI terminals.
+ */
+#define MIN_END_KEEP 4
+
+static void
+re_update_line(EditLine *el, wchar_t *old, wchar_t *new, int i)
+{
+ wchar_t *o, *n, *p, c;
+ wchar_t *ofd, *ols, *oe, *nfd, *nls, *ne;
+ wchar_t *osb, *ose, *nsb, *nse;
+ int fx, sx;
+ size_t len;
+
+ /*
+ * find first diff
+ */
+ for (o = old, n = new; *o && (*o == *n); o++, n++)
+ continue;
+ ofd = o;
+ nfd = n;
+
+ /*
+ * Find the end of both old and new
+ */
+ while (*o)
+ o++;
+ /*
+ * Remove any trailing blanks off of the end, being careful not to
+ * back up past the beginning.
+ */
+ while (ofd < o) {
+ if (o[-1] != ' ')
+ break;
+ o--;
+ }
+ oe = o;
+ *oe = '\0';
+
+ while (*n)
+ n++;
+
+ /* remove blanks from end of new */
+ while (nfd < n) {
+ if (n[-1] != ' ')
+ break;
+ n--;
+ }
+ ne = n;
+ *ne = '\0';
+
+ /*
+ * if no diff, continue to next line of redraw
+ */
+ if (*ofd == '\0' && *nfd == '\0') {
+ ELRE_DEBUG(1, (__F, "no difference.\r\n"));
+ return;
+ }
+ /*
+ * find last same pointer
+ */
+ while ((o > ofd) && (n > nfd) && (*--o == *--n))
+ continue;
+ ols = ++o;
+ nls = ++n;
+
+ /*
+ * find same beginning and same end
+ */
+ osb = ols;
+ nsb = nls;
+ ose = ols;
+ nse = nls;
+
+ /*
+ * case 1: insert: scan from nfd to nls looking for *ofd
+ */
+ if (*ofd) {
+ for (c = *ofd, n = nfd; n < nls; n++) {
+ if (c == *n) {
+ for (o = ofd, p = n;
+ p < nls && o < ols && *o == *p;
+ o++, p++)
+ continue;
+ /*
+ * if the new match is longer and it's worth
+ * keeping, then we take it
+ */
+ if (((nse - nsb) < (p - n)) &&
+ (2 * (p - n) > n - nfd)) {
+ nsb = n;
+ nse = p;
+ osb = ofd;
+ ose = o;
+ }
+ }
+ }
+ }
+ /*
+ * case 2: delete: scan from ofd to ols looking for *nfd
+ */
+ if (*nfd) {
+ for (c = *nfd, o = ofd; o < ols; o++) {
+ if (c == *o) {
+ for (n = nfd, p = o;
+ p < ols && n < nls && *p == *n;
+ p++, n++)
+ continue;
+ /*
+ * if the new match is longer and it's worth
+ * keeping, then we take it
+ */
+ if (((ose - osb) < (p - o)) &&
+ (2 * (p - o) > o - ofd)) {
+ nsb = nfd;
+ nse = n;
+ osb = o;
+ ose = p;
+ }
+ }
+ }
+ }
+ /*
+ * Pragmatics I: If old trailing whitespace or not enough characters to
+ * save to be worth it, then don't save the last same info.
+ */
+ if ((oe - ols) < MIN_END_KEEP) {
+ ols = oe;
+ nls = ne;
+ }
+ /*
+ * Pragmatics II: if the terminal isn't smart enough, make the data
+ * dumber so the smart update doesn't try anything fancy
+ */
+
+ /*
+ * fx is the number of characters we need to insert/delete: in the
+ * beginning to bring the two same begins together
+ */
+ fx = (int)((nsb - nfd) - (osb - ofd));
+ /*
+ * sx is the number of characters we need to insert/delete: in the
+ * end to bring the two same last parts together
+ */
+ sx = (int)((nls - nse) - (ols - ose));
+
+ if (!EL_CAN_INSERT) {
+ if (fx > 0) {
+ osb = ols;
+ ose = ols;
+ nsb = nls;
+ nse = nls;
+ }
+ if (sx > 0) {
+ ols = oe;
+ nls = ne;
+ }
+ if ((ols - ofd) < (nls - nfd)) {
+ ols = oe;
+ nls = ne;
+ }
+ }
+ if (!EL_CAN_DELETE) {
+ if (fx < 0) {
+ osb = ols;
+ ose = ols;
+ nsb = nls;
+ nse = nls;
+ }
+ if (sx < 0) {
+ ols = oe;
+ nls = ne;
+ }
+ if ((ols - ofd) > (nls - nfd)) {
+ ols = oe;
+ nls = ne;
+ }
+ }
+ /*
+ * Pragmatics III: make sure the middle shifted pointers are correct if
+ * they don't point to anything (we may have moved ols or nls).
+ */
+ /* if the change isn't worth it, don't bother */
+ /* was: if (osb == ose) */
+ if ((ose - osb) < MIN_END_KEEP) {
+ osb = ols;
+ ose = ols;
+ nsb = nls;
+ nse = nls;
+ }
+ /*
+ * Now that we are done with pragmatics we recompute fx, sx
+ */
+ fx = (int)((nsb - nfd) - (osb - ofd));
+ sx = (int)((nls - nse) - (ols - ose));
+
+ ELRE_DEBUG(1, (__F, "fx %d, sx %d\n", fx, sx));
+ ELRE_DEBUG(1, (__F, "ofd %td, osb %td, ose %td, ols %td, oe %td\n",
+ ofd - old, osb - old, ose - old, ols - old, oe - old));
+ ELRE_DEBUG(1, (__F, "nfd %td, nsb %td, nse %td, nls %td, ne %td\n",
+ nfd - new, nsb - new, nse - new, nls - new, ne - new));
+ ELRE_DEBUG(1, (__F,
+ "xxx-xxx:\"00000000001111111111222222222233333333334\"\r\n"));
+ ELRE_DEBUG(1, (__F,
+ "xxx-xxx:\"01234567890123456789012345678901234567890\"\r\n"));
+#ifdef DEBUG_REFRESH
+ re_printstr(el, "old- oe", old, oe);
+ re_printstr(el, "new- ne", new, ne);
+ re_printstr(el, "old-ofd", old, ofd);
+ re_printstr(el, "new-nfd", new, nfd);
+ re_printstr(el, "ofd-osb", ofd, osb);
+ re_printstr(el, "nfd-nsb", nfd, nsb);
+ re_printstr(el, "osb-ose", osb, ose);
+ re_printstr(el, "nsb-nse", nsb, nse);
+ re_printstr(el, "ose-ols", ose, ols);
+ re_printstr(el, "nse-nls", nse, nls);
+ re_printstr(el, "ols- oe", ols, oe);
+ re_printstr(el, "nls- ne", nls, ne);
+#endif /* DEBUG_REFRESH */
+
+ /*
+ * el_cursor.v to this line i MUST be in this routine so that if we
+ * don't have to change the line, we don't move to it. el_cursor.h to
+ * first diff char
+ */
+ terminal_move_to_line(el, i);
+
+ /*
+ * at this point we have something like this:
+ *
+ * /old /ofd /osb /ose /ols /oe
+ * v.....................v v..................v v........v
+ * eddie> Oh, my fredded gruntle-buggy is to me, as foo var lurgid as
+ * eddie> Oh, my fredded quiux buggy is to me, as gruntle-lurgid as
+ * ^.....................^ ^..................^ ^........^
+ * \new \nfd \nsb \nse \nls \ne
+ *
+ * fx is the difference in length between the chars between nfd and
+ * nsb, and the chars between ofd and osb, and is thus the number of
+ * characters to delete if < 0 (new is shorter than old, as above),
+ * or insert (new is longer than short).
+ *
+ * sx is the same for the second differences.
+ */
+
+ /*
+ * if we have a net insert on the first difference, AND inserting the
+ * net amount ((nsb-nfd) - (osb-ofd)) won't push the last useful
+ * character (which is ne if nls != ne, otherwise is nse) off the edge
+ * of the screen (el->el_terminal.t_size.h) else we do the deletes first
+ * so that we keep everything we need to.
+ */
+
+ /*
+ * if the last same is the same like the end, there is no last same
+ * part, otherwise we want to keep the last same part set p to the
+ * last useful old character
+ */
+ p = (ols != oe) ? oe : ose;
+
+ /*
+ * if (There is a diffence in the beginning) && (we need to insert
+ * characters) && (the number of characters to insert is less than
+ * the term width)
+ * We need to do an insert!
+ * else if (we need to delete characters)
+ * We need to delete characters!
+ * else
+ * No insert or delete
+ */
+ if ((nsb != nfd) && fx > 0 &&
+ ((p - old) + fx <= el->el_terminal.t_size.h)) {
+ ELRE_DEBUG(1,
+ (__F, "first diff insert at %td...\r\n", nfd - new));
+ /*
+ * Move to the first char to insert, where the first diff is.
+ */
+ terminal_move_to_char(el, (int)(nfd - new));
+ /*
+ * Check if we have stuff to keep at end
+ */
+ if (nsb != ne) {
+ ELRE_DEBUG(1, (__F, "with stuff to keep at end\r\n"));
+ /*
+ * insert fx chars of new starting at nfd
+ */
+ if (fx > 0) {
+ ELRE_DEBUG(!EL_CAN_INSERT, (__F,
+ "ERROR: cannot insert in early first diff\n"));
+ terminal_insertwrite(el, nfd, fx);
+ re_insert(el, old, (int)(ofd - old),
+ el->el_terminal.t_size.h, nfd, fx);
+ }
+ /*
+ * write (nsb-nfd) - fx chars of new starting at
+ * (nfd + fx)
+ */
+ len = (size_t) ((nsb - nfd) - fx);
+ terminal_overwrite(el, (nfd + fx), len);
+ re__strncopy(ofd + fx, nfd + fx, len);
+ } else {
+ ELRE_DEBUG(1, (__F, "without anything to save\r\n"));
+ len = (size_t)(nsb - nfd);
+ terminal_overwrite(el, nfd, len);
+ re__strncopy(ofd, nfd, len);
+ /*
+ * Done
+ */
+ return;
+ }
+ } else if (fx < 0) {
+ ELRE_DEBUG(1,
+ (__F, "first diff delete at %td...\r\n", ofd - old));
+ /*
+ * move to the first char to delete where the first diff is
+ */
+ terminal_move_to_char(el, (int)(ofd - old));
+ /*
+ * Check if we have stuff to save
+ */
+ if (osb != oe) {
+ ELRE_DEBUG(1, (__F, "with stuff to save at end\r\n"));
+ /*
+ * fx is less than zero *always* here but we check
+ * for code symmetry
+ */
+ if (fx < 0) {
+ ELRE_DEBUG(!EL_CAN_DELETE, (__F,
+ "ERROR: cannot delete in first diff\n"));
+ terminal_deletechars(el, -fx);
+ re_delete(el, old, (int)(ofd - old),
+ el->el_terminal.t_size.h, -fx);
+ }
+ /*
+ * write (nsb-nfd) chars of new starting at nfd
+ */
+ len = (size_t) (nsb - nfd);
+ terminal_overwrite(el, nfd, len);
+ re__strncopy(ofd, nfd, len);
+
+ } else {
+ ELRE_DEBUG(1, (__F,
+ "but with nothing left to save\r\n"));
+ /*
+ * write (nsb-nfd) chars of new starting at nfd
+ */
+ terminal_overwrite(el, nfd, (size_t)(nsb - nfd));
+ re_clear_eol(el, fx, sx,
+ (int)((oe - old) - (ne - new)));
+ /*
+ * Done
+ */
+ return;
+ }
+ } else
+ fx = 0;
+
+ if (sx < 0 && (ose - old) + fx < el->el_terminal.t_size.h) {
+ ELRE_DEBUG(1, (__F,
+ "second diff delete at %td...\r\n", (ose - old) + fx));
+ /*
+ * Check if we have stuff to delete
+ */
+ /*
+ * fx is the number of characters inserted (+) or deleted (-)
+ */
+
+ terminal_move_to_char(el, (int)((ose - old) + fx));
+ /*
+ * Check if we have stuff to save
+ */
+ if (ols != oe) {
+ ELRE_DEBUG(1, (__F, "with stuff to save at end\r\n"));
+ /*
+ * Again a duplicate test.
+ */
+ if (sx < 0) {
+ ELRE_DEBUG(!EL_CAN_DELETE, (__F,
+ "ERROR: cannot delete in second diff\n"));
+ terminal_deletechars(el, -sx);
+ }
+ /*
+ * write (nls-nse) chars of new starting at nse
+ */
+ terminal_overwrite(el, nse, (size_t)(nls - nse));
+ } else {
+ ELRE_DEBUG(1, (__F,
+ "but with nothing left to save\r\n"));
+ terminal_overwrite(el, nse, (size_t)(nls - nse));
+ re_clear_eol(el, fx, sx,
+ (int)((oe - old) - (ne - new)));
+ }
+ }
+ /*
+ * if we have a first insert AND WE HAVEN'T ALREADY DONE IT...
+ */
+ if ((nsb != nfd) && (osb - ofd) <= (nsb - nfd) && (fx == 0)) {
+ ELRE_DEBUG(1, (__F, "late first diff insert at %td...\r\n",
+ nfd - new));
+
+ terminal_move_to_char(el, (int)(nfd - new));
+ /*
+ * Check if we have stuff to keep at the end
+ */
+ if (nsb != ne) {
+ ELRE_DEBUG(1, (__F, "with stuff to keep at end\r\n"));
+ /*
+ * We have to recalculate fx here because we set it
+ * to zero above as a flag saying that we hadn't done
+ * an early first insert.
+ */
+ fx = (int)((nsb - nfd) - (osb - ofd));
+ if (fx > 0) {
+ /*
+ * insert fx chars of new starting at nfd
+ */
+ ELRE_DEBUG(!EL_CAN_INSERT, (__F,
+ "ERROR: cannot insert in late first diff\n"));
+ terminal_insertwrite(el, nfd, fx);
+ re_insert(el, old, (int)(ofd - old),
+ el->el_terminal.t_size.h, nfd, fx);
+ }
+ /*
+ * write (nsb-nfd) - fx chars of new starting at
+ * (nfd + fx)
+ */
+ len = (size_t) ((nsb - nfd) - fx);
+ terminal_overwrite(el, (nfd + fx), len);
+ re__strncopy(ofd + fx, nfd + fx, len);
+ } else {
+ ELRE_DEBUG(1, (__F, "without anything to save\r\n"));
+ len = (size_t) (nsb - nfd);
+ terminal_overwrite(el, nfd, len);
+ re__strncopy(ofd, nfd, len);
+ }
+ }
+ /*
+ * line is now NEW up to nse
+ */
+ if (sx >= 0) {
+ ELRE_DEBUG(1, (__F,
+ "second diff insert at %d...\r\n", (int)(nse - new)));
+ terminal_move_to_char(el, (int)(nse - new));
+ if (ols != oe) {
+ ELRE_DEBUG(1, (__F, "with stuff to keep at end\r\n"));
+ if (sx > 0) {
+ /* insert sx chars of new starting at nse */
+ ELRE_DEBUG(!EL_CAN_INSERT, (__F,
+ "ERROR: cannot insert in second diff\n"));
+ terminal_insertwrite(el, nse, sx);
+ }
+ /*
+ * write (nls-nse) - sx chars of new starting at
+ * (nse + sx)
+ */
+ terminal_overwrite(el, (nse + sx),
+ (size_t)((nls - nse) - sx));
+ } else {
+ ELRE_DEBUG(1, (__F, "without anything to save\r\n"));
+ terminal_overwrite(el, nse, (size_t)(nls - nse));
+
+ /*
+ * No need to do a clear-to-end here because we were
+ * doing a second insert, so we will have over
+ * written all of the old string.
+ */
+ }
+ }
+ ELRE_DEBUG(1, (__F, "done.\r\n"));
+}
+
+
+/* re__copy_and_pad():
+ * Copy string and pad with spaces
+ */
+static void
+re__copy_and_pad(wchar_t *dst, const wchar_t *src, size_t width)
+{
+ size_t i;
+
+ for (i = 0; i < width; i++) {
+ if (*src == '\0')
+ break;
+ *dst++ = *src++;
+ }
+
+ for (; i < width; i++)
+ *dst++ = ' ';
+
+ *dst = '\0';
+}
+
+
+/* re_refresh_cursor():
+ * Move to the new cursor position
+ */
+libedit_private void
+re_refresh_cursor(EditLine *el)
+{
+ wchar_t *cp;
+ int h, v, th, w;
+
+ if (el->el_line.cursor >= el->el_line.lastchar) {
+ if (el->el_map.current == el->el_map.alt
+ && el->el_line.lastchar != el->el_line.buffer)
+ el->el_line.cursor = el->el_line.lastchar - 1;
+ else
+ el->el_line.cursor = el->el_line.lastchar;
+ }
+
+ /* first we must find where the cursor is... */
+ h = el->el_prompt.p_pos.h;
+ v = el->el_prompt.p_pos.v;
+ th = el->el_terminal.t_size.h; /* optimize for speed */
+
+ /* do input buffer to el->el_line.cursor */
+ for (cp = el->el_line.buffer; cp < el->el_line.cursor; cp++) {
+ switch (ct_chr_class(*cp)) {
+ case CHTYPE_NL: /* handle newline in data part too */
+ h = 0;
+ v++;
+ break;
+ case CHTYPE_TAB: /* if a tab, to next tab stop */
+ while (++h & 07)
+ continue;
+ break;
+ default:
+ w = wcwidth(*cp);
+ if (w > 1 && h + w > th) { /* won't fit on line */
+ h = 0;
+ v++;
+ }
+ h += ct_visual_width(*cp);
+ break;
+ }
+
+ if (h >= th) { /* check, extra long tabs picked up here also */
+ h -= th;
+ v++;
+ }
+ }
+ /* if we have a next character, and it's a doublewidth one, we need to
+ * check whether we need to linebreak for it to fit */
+ if (cp < el->el_line.lastchar && (w = wcwidth(*cp)) > 1)
+ if (h + w > th) {
+ h = 0;
+ v++;
+ }
+
+ /* now go there */
+ terminal_move_to_line(el, v);
+ terminal_move_to_char(el, h);
+ terminal__flush(el);
+}
+
+
+/* re_fastputc():
+ * Add a character fast.
+ */
+static void
+re_fastputc(EditLine *el, wint_t c)
+{
+ int w = wcwidth(c);
+ while (w > 1 && el->el_cursor.h + w > el->el_terminal.t_size.h)
+ re_fastputc(el, ' ');
+
+ terminal__putc(el, c);
+ el->el_display[el->el_cursor.v][el->el_cursor.h++] = c;
+ while (--w > 0)
+ el->el_display[el->el_cursor.v][el->el_cursor.h++]
+ = MB_FILL_CHAR;
+
+ if (el->el_cursor.h >= el->el_terminal.t_size.h) {
+ /* if we must overflow */
+ el->el_cursor.h = 0;
+
+ /*
+ * If we would overflow (input is longer than terminal size),
+ * emulate scroll by dropping first line and shuffling the rest.
+ * We do this via pointer shuffling - it's safe in this case
+ * and we avoid memcpy().
+ */
+ if (el->el_cursor.v + 1 >= el->el_terminal.t_size.v) {
+ int i, lins = el->el_terminal.t_size.v;
+ wchar_t *firstline = el->el_display[0];
+
+ for(i = 1; i < lins; i++)
+ el->el_display[i - 1] = el->el_display[i];
+
+ re__copy_and_pad(firstline, L"", (size_t)0);
+ el->el_display[i - 1] = firstline;
+ } else {
+ el->el_cursor.v++;
+ el->el_refresh.r_oldcv++;
+ }
+ if (EL_HAS_AUTO_MARGINS) {
+ if (EL_HAS_MAGIC_MARGINS) {
+ terminal__putc(el, ' ');
+ terminal__putc(el, '\b');
+ }
+ } else {
+ terminal__putc(el, '\r');
+ terminal__putc(el, '\n');
+ }
+ }
+}
+
+
+/* re_fastaddc():
+ * we added just one char, handle it fast.
+ * Assumes that screen cursor == real cursor
+ */
+libedit_private void
+re_fastaddc(EditLine *el)
+{
+ wchar_t c;
+ int rhdiff;
+
+ c = el->el_line.cursor[-1];
+
+ if (c == '\t' || el->el_line.cursor != el->el_line.lastchar) {
+ re_refresh(el); /* too hard to handle */
+ return;
+ }
+ rhdiff = el->el_terminal.t_size.h - el->el_cursor.h -
+ el->el_rprompt.p_pos.h;
+ if (el->el_rprompt.p_pos.h && rhdiff < 3) {
+ re_refresh(el); /* clear out rprompt if less than 1 char gap */
+ return;
+ } /* else (only do at end of line, no TAB) */
+ switch (ct_chr_class(c)) {
+ case CHTYPE_TAB: /* already handled, should never happen here */
+ break;
+ case CHTYPE_NL:
+ case CHTYPE_PRINT:
+ re_fastputc(el, c);
+ break;
+ case CHTYPE_ASCIICTL:
+ case CHTYPE_NONPRINT: {
+ wchar_t visbuf[VISUAL_WIDTH_MAX];
+ ssize_t i, n =
+ ct_visual_char(visbuf, VISUAL_WIDTH_MAX, c);
+ for (i = 0; n-- > 0; ++i)
+ re_fastputc(el, visbuf[i]);
+ break;
+ }
+ }
+ terminal__flush(el);
+}
+
+
+/* re_clear_display():
+ * clear the screen buffers so that new new prompt starts fresh.
+ */
+libedit_private void
+re_clear_display(EditLine *el)
+{
+ int i;
+
+ el->el_cursor.v = 0;
+ el->el_cursor.h = 0;
+ for (i = 0; i < el->el_terminal.t_size.v; i++)
+ el->el_display[i][0] = '\0';
+ el->el_refresh.r_oldcv = 0;
+}
+
+
+/* re_clear_lines():
+ * Make sure all lines are *really* blank
+ */
+libedit_private void
+re_clear_lines(EditLine *el)
+{
+
+ if (EL_CAN_CEOL) {
+ int i;
+ for (i = el->el_refresh.r_oldcv; i >= 0; i--) {
+ /* for each line on the screen */
+ terminal_move_to_line(el, i);
+ terminal_move_to_char(el, 0);
+ terminal_clear_EOL(el, el->el_terminal.t_size.h);
+ }
+ } else {
+ terminal_move_to_line(el, el->el_refresh.r_oldcv);
+ /* go to last line */
+ terminal__putc(el, '\r'); /* go to BOL */
+ terminal__putc(el, '\n'); /* go to new line */
+ }
+}
diff --git a/third_party/heimdal/lib/libedit/src/refresh.h b/third_party/heimdal/lib/libedit/src/refresh.h
new file mode 100644
index 0000000..621c569
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/refresh.h
@@ -0,0 +1,57 @@
+/* $NetBSD: refresh.h,v 1.10 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)refresh.h 8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * el.refresh.h: Screen refresh functions
+ */
+#ifndef _h_el_refresh
+#define _h_el_refresh
+
+typedef struct {
+ coord_t r_cursor; /* Refresh cursor position */
+ int r_oldcv; /* Vertical locations */
+ int r_newcv;
+} el_refresh_t;
+
+libedit_private void re_putc(EditLine *, wint_t, int);
+libedit_private void re_clear_lines(EditLine *);
+libedit_private void re_clear_display(EditLine *);
+libedit_private void re_refresh(EditLine *);
+libedit_private void re_refresh_cursor(EditLine *);
+libedit_private void re_fastaddc(EditLine *);
+libedit_private void re_goto_bottom(EditLine *);
+
+#endif /* _h_el_refresh */
diff --git a/third_party/heimdal/lib/libedit/src/search.c b/third_party/heimdal/lib/libedit/src/search.c
new file mode 100644
index 0000000..5226cf5
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/search.c
@@ -0,0 +1,641 @@
+/* $NetBSD: search.c,v 1.47 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)search.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: search.c,v 1.47 2016/05/09 21:46:56 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * search.c: History and character search functions
+ */
+#include <stdlib.h>
+#include <string.h>
+#if defined(REGEX)
+#include <regex.h>
+#elif defined(REGEXP)
+#include <regexp.h>
+#endif
+
+#include "el.h"
+#include "common.h"
+#include "fcns.h"
+
+/*
+ * Adjust cursor in vi mode to include the character under it
+ */
+#define EL_CURSOR(el) \
+ ((el)->el_line.cursor + (((el)->el_map.type == MAP_VI) && \
+ ((el)->el_map.current == (el)->el_map.alt)))
+
+/* search_init():
+ * Initialize the search stuff
+ */
+libedit_private int
+search_init(EditLine *el)
+{
+
+ el->el_search.patbuf = el_malloc(EL_BUFSIZ *
+ sizeof(*el->el_search.patbuf));
+ if (el->el_search.patbuf == NULL)
+ return -1;
+ el->el_search.patbuf[0] = L'\0';
+ el->el_search.patlen = 0;
+ el->el_search.patdir = -1;
+ el->el_search.chacha = L'\0';
+ el->el_search.chadir = CHAR_FWD;
+ el->el_search.chatflg = 0;
+ return 0;
+}
+
+
+/* search_end():
+ * Initialize the search stuff
+ */
+libedit_private void
+search_end(EditLine *el)
+{
+
+ el_free(el->el_search.patbuf);
+ el->el_search.patbuf = NULL;
+}
+
+
+#ifdef REGEXP
+/* regerror():
+ * Handle regular expression errors
+ */
+void
+/*ARGSUSED*/
+regerror(const char *msg)
+{
+}
+#endif
+
+
+/* el_match():
+ * Return if string matches pattern
+ */
+libedit_private int
+el_match(const wchar_t *str, const wchar_t *pat)
+{
+ static ct_buffer_t conv;
+#if defined (REGEX)
+ regex_t re;
+ int rv;
+#elif defined (REGEXP)
+ regexp *rp;
+ int rv;
+#else
+ extern char *re_comp(const char *);
+ extern int re_exec(const char *);
+#endif
+
+ if (wcsstr(str, pat) != 0)
+ return 1;
+
+#if defined(REGEX)
+ if (regcomp(&re, ct_encode_string(pat, &conv), 0) == 0) {
+ rv = regexec(&re, ct_encode_string(str, &conv), (size_t)0, NULL,
+ 0) == 0;
+ regfree(&re);
+ } else {
+ rv = 0;
+ }
+ return rv;
+#elif defined(REGEXP)
+ if ((re = regcomp(ct_encode_string(pat, &conv))) != NULL) {
+ rv = regexec(re, ct_encode_string(str, &conv));
+ el_free(re);
+ } else {
+ rv = 0;
+ }
+ return rv;
+#else
+ if (re_comp(ct_encode_string(pat, &conv)) != NULL)
+ return 0;
+ else
+ return re_exec(ct_encode_string(str, &conv)) == 1;
+#endif
+}
+
+
+/* c_hmatch():
+ * return True if the pattern matches the prefix
+ */
+libedit_private int
+c_hmatch(EditLine *el, const wchar_t *str)
+{
+#ifdef SDEBUG
+ (void) fprintf(el->el_errfile, "match `%s' with `%s'\n",
+ el->el_search.patbuf, str);
+#endif /* SDEBUG */
+
+ return el_match(str, el->el_search.patbuf);
+}
+
+
+/* c_setpat():
+ * Set the history seatch pattern
+ */
+libedit_private void
+c_setpat(EditLine *el)
+{
+ if (el->el_state.lastcmd != ED_SEARCH_PREV_HISTORY &&
+ el->el_state.lastcmd != ED_SEARCH_NEXT_HISTORY) {
+ el->el_search.patlen =
+ (size_t)(EL_CURSOR(el) - el->el_line.buffer);
+ if (el->el_search.patlen >= EL_BUFSIZ)
+ el->el_search.patlen = EL_BUFSIZ - 1;
+ if (el->el_search.patlen != 0) {
+ (void) wcsncpy(el->el_search.patbuf, el->el_line.buffer,
+ el->el_search.patlen);
+ el->el_search.patbuf[el->el_search.patlen] = '\0';
+ } else
+ el->el_search.patlen = wcslen(el->el_search.patbuf);
+ }
+#ifdef SDEBUG
+ (void) fprintf(el->el_errfile, "\neventno = %d\n",
+ el->el_history.eventno);
+ (void) fprintf(el->el_errfile, "patlen = %d\n", el->el_search.patlen);
+ (void) fprintf(el->el_errfile, "patbuf = \"%s\"\n",
+ el->el_search.patbuf);
+ (void) fprintf(el->el_errfile, "cursor %d lastchar %d\n",
+ EL_CURSOR(el) - el->el_line.buffer,
+ el->el_line.lastchar - el->el_line.buffer);
+#endif
+}
+
+
+/* ce_inc_search():
+ * Emacs incremental search
+ */
+libedit_private el_action_t
+ce_inc_search(EditLine *el, int dir)
+{
+ static const wchar_t STRfwd[] = L"fwd", STRbck[] = L"bck";
+ static wchar_t pchar = L':'; /* ':' = normal, '?' = failed */
+ static wchar_t endcmd[2] = {'\0', '\0'};
+ wchar_t *ocursor = el->el_line.cursor, oldpchar = pchar, ch;
+ const wchar_t *cp;
+
+ el_action_t ret = CC_NORM;
+
+ int ohisteventno = el->el_history.eventno;
+ size_t oldpatlen = el->el_search.patlen;
+ int newdir = dir;
+ int done, redo;
+
+ if (el->el_line.lastchar + sizeof(STRfwd) /
+ sizeof(*el->el_line.lastchar) + 2 +
+ el->el_search.patlen >= el->el_line.limit)
+ return CC_ERROR;
+
+ for (;;) {
+
+ if (el->el_search.patlen == 0) { /* first round */
+ pchar = ':';
+#ifdef ANCHOR
+#define LEN 2
+ el->el_search.patbuf[el->el_search.patlen++] = '.';
+ el->el_search.patbuf[el->el_search.patlen++] = '*';
+#else
+#define LEN 0
+#endif
+ }
+ done = redo = 0;
+ *el->el_line.lastchar++ = '\n';
+ for (cp = (newdir == ED_SEARCH_PREV_HISTORY) ? STRbck : STRfwd;
+ *cp; *el->el_line.lastchar++ = *cp++)
+ continue;
+ *el->el_line.lastchar++ = pchar;
+ for (cp = &el->el_search.patbuf[LEN];
+ cp < &el->el_search.patbuf[el->el_search.patlen];
+ *el->el_line.lastchar++ = *cp++)
+ continue;
+ *el->el_line.lastchar = '\0';
+ re_refresh(el);
+
+ if (el_wgetc(el, &ch) != 1)
+ return ed_end_of_file(el, 0);
+
+ switch (el->el_map.current[(unsigned char) ch]) {
+ case ED_INSERT:
+ case ED_DIGIT:
+ if (el->el_search.patlen >= EL_BUFSIZ - LEN)
+ terminal_beep(el);
+ else {
+ el->el_search.patbuf[el->el_search.patlen++] =
+ ch;
+ *el->el_line.lastchar++ = ch;
+ *el->el_line.lastchar = '\0';
+ re_refresh(el);
+ }
+ break;
+
+ case EM_INC_SEARCH_NEXT:
+ newdir = ED_SEARCH_NEXT_HISTORY;
+ redo++;
+ break;
+
+ case EM_INC_SEARCH_PREV:
+ newdir = ED_SEARCH_PREV_HISTORY;
+ redo++;
+ break;
+
+ case EM_DELETE_PREV_CHAR:
+ case ED_DELETE_PREV_CHAR:
+ if (el->el_search.patlen > LEN)
+ done++;
+ else
+ terminal_beep(el);
+ break;
+
+ default:
+ switch (ch) {
+ case 0007: /* ^G: Abort */
+ ret = CC_ERROR;
+ done++;
+ break;
+
+ case 0027: /* ^W: Append word */
+ /* No can do if globbing characters in pattern */
+ for (cp = &el->el_search.patbuf[LEN];; cp++)
+ if (cp >= &el->el_search.patbuf[
+ el->el_search.patlen]) {
+ el->el_line.cursor +=
+ el->el_search.patlen - LEN - 1;
+ cp = c__next_word(el->el_line.cursor,
+ el->el_line.lastchar, 1,
+ ce__isword);
+ while (el->el_line.cursor < cp &&
+ *el->el_line.cursor != '\n') {
+ if (el->el_search.patlen >=
+ EL_BUFSIZ - LEN) {
+ terminal_beep(el);
+ break;
+ }
+ el->el_search.patbuf[el->el_search.patlen++] =
+ *el->el_line.cursor;
+ *el->el_line.lastchar++ =
+ *el->el_line.cursor++;
+ }
+ el->el_line.cursor = ocursor;
+ *el->el_line.lastchar = '\0';
+ re_refresh(el);
+ break;
+ } else if (isglob(*cp)) {
+ terminal_beep(el);
+ break;
+ }
+ break;
+
+ default: /* Terminate and execute cmd */
+ endcmd[0] = ch;
+ el_wpush(el, endcmd);
+ /* FALLTHROUGH */
+
+ case 0033: /* ESC: Terminate */
+ ret = CC_REFRESH;
+ done++;
+ break;
+ }
+ break;
+ }
+
+ while (el->el_line.lastchar > el->el_line.buffer &&
+ *el->el_line.lastchar != '\n')
+ *el->el_line.lastchar-- = '\0';
+ *el->el_line.lastchar = '\0';
+
+ if (!done) {
+
+ /* Can't search if unmatched '[' */
+ for (cp = &el->el_search.patbuf[el->el_search.patlen-1],
+ ch = L']';
+ cp >= &el->el_search.patbuf[LEN];
+ cp--)
+ if (*cp == '[' || *cp == ']') {
+ ch = *cp;
+ break;
+ }
+ if (el->el_search.patlen > LEN && ch != L'[') {
+ if (redo && newdir == dir) {
+ if (pchar == '?') { /* wrap around */
+ el->el_history.eventno =
+ newdir == ED_SEARCH_PREV_HISTORY ? 0 : 0x7fffffff;
+ if (hist_get(el) == CC_ERROR)
+ /* el->el_history.event
+ * no was fixed by
+ * first call */
+ (void) hist_get(el);
+ el->el_line.cursor = newdir ==
+ ED_SEARCH_PREV_HISTORY ?
+ el->el_line.lastchar :
+ el->el_line.buffer;
+ } else
+ el->el_line.cursor +=
+ newdir ==
+ ED_SEARCH_PREV_HISTORY ?
+ -1 : 1;
+ }
+#ifdef ANCHOR
+ el->el_search.patbuf[el->el_search.patlen++] =
+ '.';
+ el->el_search.patbuf[el->el_search.patlen++] =
+ '*';
+#endif
+ el->el_search.patbuf[el->el_search.patlen] =
+ '\0';
+ if (el->el_line.cursor < el->el_line.buffer ||
+ el->el_line.cursor > el->el_line.lastchar ||
+ (ret = ce_search_line(el, newdir))
+ == CC_ERROR) {
+ /* avoid c_setpat */
+ el->el_state.lastcmd =
+ (el_action_t) newdir;
+ ret = (el_action_t)
+ (newdir == ED_SEARCH_PREV_HISTORY ?
+ ed_search_prev_history(el, 0) :
+ ed_search_next_history(el, 0));
+ if (ret != CC_ERROR) {
+ el->el_line.cursor = newdir ==
+ ED_SEARCH_PREV_HISTORY ?
+ el->el_line.lastchar :
+ el->el_line.buffer;
+ (void) ce_search_line(el,
+ newdir);
+ }
+ }
+ el->el_search.patlen -= LEN;
+ el->el_search.patbuf[el->el_search.patlen] =
+ '\0';
+ if (ret == CC_ERROR) {
+ terminal_beep(el);
+ if (el->el_history.eventno !=
+ ohisteventno) {
+ el->el_history.eventno =
+ ohisteventno;
+ if (hist_get(el) == CC_ERROR)
+ return CC_ERROR;
+ }
+ el->el_line.cursor = ocursor;
+ pchar = '?';
+ } else {
+ pchar = ':';
+ }
+ }
+ ret = ce_inc_search(el, newdir);
+
+ if (ret == CC_ERROR && pchar == '?' && oldpchar == ':')
+ /*
+ * break abort of failed search at last
+ * non-failed
+ */
+ ret = CC_NORM;
+
+ }
+ if (ret == CC_NORM || (ret == CC_ERROR && oldpatlen == 0)) {
+ /* restore on normal return or error exit */
+ pchar = oldpchar;
+ el->el_search.patlen = oldpatlen;
+ if (el->el_history.eventno != ohisteventno) {
+ el->el_history.eventno = ohisteventno;
+ if (hist_get(el) == CC_ERROR)
+ return CC_ERROR;
+ }
+ el->el_line.cursor = ocursor;
+ if (ret == CC_ERROR)
+ re_refresh(el);
+ }
+ if (done || ret != CC_NORM)
+ return ret;
+ }
+}
+
+
+/* cv_search():
+ * Vi search.
+ */
+libedit_private el_action_t
+cv_search(EditLine *el, int dir)
+{
+ wchar_t ch;
+ wchar_t tmpbuf[EL_BUFSIZ];
+ ssize_t tmplen;
+
+#ifdef ANCHOR
+ tmpbuf[0] = '.';
+ tmpbuf[1] = '*';
+#endif
+ tmplen = LEN;
+
+ el->el_search.patdir = dir;
+
+ tmplen = c_gets(el, &tmpbuf[LEN],
+ dir == ED_SEARCH_PREV_HISTORY ? L"\n/" : L"\n?" );
+ if (tmplen == -1)
+ return CC_REFRESH;
+
+ tmplen += LEN;
+ ch = tmpbuf[tmplen];
+ tmpbuf[tmplen] = '\0';
+
+ if (tmplen == LEN) {
+ /*
+ * Use the old pattern, but wild-card it.
+ */
+ if (el->el_search.patlen == 0) {
+ re_refresh(el);
+ return CC_ERROR;
+ }
+#ifdef ANCHOR
+ if (el->el_search.patbuf[0] != '.' &&
+ el->el_search.patbuf[0] != '*') {
+ (void) wcsncpy(tmpbuf, el->el_search.patbuf,
+ sizeof(tmpbuf) / sizeof(*tmpbuf) - 1);
+ el->el_search.patbuf[0] = '.';
+ el->el_search.patbuf[1] = '*';
+ (void) wcsncpy(&el->el_search.patbuf[2], tmpbuf,
+ EL_BUFSIZ - 3);
+ el->el_search.patlen++;
+ el->el_search.patbuf[el->el_search.patlen++] = '.';
+ el->el_search.patbuf[el->el_search.patlen++] = '*';
+ el->el_search.patbuf[el->el_search.patlen] = '\0';
+ }
+#endif
+ } else {
+#ifdef ANCHOR
+ tmpbuf[tmplen++] = '.';
+ tmpbuf[tmplen++] = '*';
+#endif
+ tmpbuf[tmplen] = '\0';
+ (void) wcsncpy(el->el_search.patbuf, tmpbuf, EL_BUFSIZ - 1);
+ el->el_search.patlen = (size_t)tmplen;
+ }
+ el->el_state.lastcmd = (el_action_t) dir; /* avoid c_setpat */
+ el->el_line.cursor = el->el_line.lastchar = el->el_line.buffer;
+ if ((dir == ED_SEARCH_PREV_HISTORY ? ed_search_prev_history(el, 0) :
+ ed_search_next_history(el, 0)) == CC_ERROR) {
+ re_refresh(el);
+ return CC_ERROR;
+ }
+ if (ch == 0033) {
+ re_refresh(el);
+ return ed_newline(el, 0);
+ }
+ return CC_REFRESH;
+}
+
+
+/* ce_search_line():
+ * Look for a pattern inside a line
+ */
+libedit_private el_action_t
+ce_search_line(EditLine *el, int dir)
+{
+ wchar_t *cp = el->el_line.cursor;
+ wchar_t *pattern = el->el_search.patbuf;
+ wchar_t oc, *ocp;
+#ifdef ANCHOR
+ ocp = &pattern[1];
+ oc = *ocp;
+ *ocp = '^';
+#else
+ ocp = pattern;
+ oc = *ocp;
+#endif
+
+ if (dir == ED_SEARCH_PREV_HISTORY) {
+ for (; cp >= el->el_line.buffer; cp--) {
+ if (el_match(cp, ocp)) {
+ *ocp = oc;
+ el->el_line.cursor = cp;
+ return CC_NORM;
+ }
+ }
+ *ocp = oc;
+ return CC_ERROR;
+ } else {
+ for (; *cp != '\0' && cp < el->el_line.limit; cp++) {
+ if (el_match(cp, ocp)) {
+ *ocp = oc;
+ el->el_line.cursor = cp;
+ return CC_NORM;
+ }
+ }
+ *ocp = oc;
+ return CC_ERROR;
+ }
+}
+
+
+/* cv_repeat_srch():
+ * Vi repeat search
+ */
+libedit_private el_action_t
+cv_repeat_srch(EditLine *el, wint_t c)
+{
+
+#ifdef SDEBUG
+ (void) fprintf(el->el_errfile, "dir %d patlen %d patbuf %s\n",
+ c, el->el_search.patlen, ct_encode_string(el->el_search.patbuf));
+#endif
+
+ el->el_state.lastcmd = (el_action_t) c; /* Hack to stop c_setpat */
+ el->el_line.lastchar = el->el_line.buffer;
+
+ switch (c) {
+ case ED_SEARCH_NEXT_HISTORY:
+ return ed_search_next_history(el, 0);
+ case ED_SEARCH_PREV_HISTORY:
+ return ed_search_prev_history(el, 0);
+ default:
+ return CC_ERROR;
+ }
+}
+
+
+/* cv_csearch():
+ * Vi character search
+ */
+libedit_private el_action_t
+cv_csearch(EditLine *el, int direction, wint_t ch, int count, int tflag)
+{
+ wchar_t *cp;
+
+ if (ch == 0)
+ return CC_ERROR;
+
+ if (ch == (wint_t)-1) {
+ if (el_wgetc(el, &ch) != 1)
+ return ed_end_of_file(el, 0);
+ }
+
+ /* Save for ';' and ',' commands */
+ el->el_search.chacha = ch;
+ el->el_search.chadir = direction;
+ el->el_search.chatflg = (char)tflag;
+
+ cp = el->el_line.cursor;
+ while (count--) {
+ if ((wint_t)*cp == ch)
+ cp += direction;
+ for (;;cp += direction) {
+ if (cp >= el->el_line.lastchar)
+ return CC_ERROR;
+ if (cp < el->el_line.buffer)
+ return CC_ERROR;
+ if ((wint_t)*cp == ch)
+ break;
+ }
+ }
+
+ if (tflag)
+ cp -= direction;
+
+ el->el_line.cursor = cp;
+
+ if (el->el_chared.c_vcmd.action != NOP) {
+ if (direction > 0)
+ el->el_line.cursor++;
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+ return CC_CURSOR;
+}
diff --git a/third_party/heimdal/lib/libedit/src/search.h b/third_party/heimdal/lib/libedit/src/search.h
new file mode 100644
index 0000000..4ca39c4
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/search.h
@@ -0,0 +1,64 @@
+/* $NetBSD: search.h,v 1.14 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)search.h 8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * el.search.h: Line and history searching utilities
+ */
+#ifndef _h_el_search
+#define _h_el_search
+
+typedef struct el_search_t {
+ wchar_t *patbuf; /* The pattern buffer */
+ size_t patlen; /* Length of the pattern buffer */
+ int patdir; /* Direction of the last search */
+ int chadir; /* Character search direction */
+ wchar_t chacha; /* Character we are looking for */
+ char chatflg; /* 0 if f, 1 if t */
+} el_search_t;
+
+
+libedit_private int el_match(const wchar_t *, const wchar_t *);
+libedit_private int search_init(EditLine *);
+libedit_private void search_end(EditLine *);
+libedit_private int c_hmatch(EditLine *, const wchar_t *);
+libedit_private void c_setpat(EditLine *);
+libedit_private el_action_t ce_inc_search(EditLine *, int);
+libedit_private el_action_t cv_search(EditLine *, int);
+libedit_private el_action_t ce_search_line(EditLine *, int);
+libedit_private el_action_t cv_repeat_srch(EditLine *, wint_t);
+libedit_private el_action_t cv_csearch(EditLine *, int, wint_t, int, int);
+
+#endif /* _h_el_search */
diff --git a/third_party/heimdal/lib/libedit/src/shlib_version b/third_party/heimdal/lib/libedit/src/shlib_version
new file mode 100644
index 0000000..303609d
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/shlib_version
@@ -0,0 +1,5 @@
+# $NetBSD: shlib_version,v 1.19 2013/01/22 20:23:21 christos Exp $
+# Remember to update distrib/sets/lists/base/shl.* when changing
+#
+major=3
+minor=1
diff --git a/third_party/heimdal/lib/libedit/src/sig.c b/third_party/heimdal/lib/libedit/src/sig.c
new file mode 100644
index 0000000..83742a3
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/sig.c
@@ -0,0 +1,205 @@
+/* $NetBSD: sig.c,v 1.26 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)sig.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: sig.c,v 1.26 2016/05/09 21:46:56 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * sig.c: Signal handling stuff.
+ * our policy is to trap all signals, set a good state
+ * and pass the ball to our caller.
+ */
+#include <errno.h>
+#include <stdlib.h>
+
+#include "el.h"
+#include "common.h"
+
+static EditLine *sel = NULL;
+
+static const int sighdl[] = {
+#define _DO(a) (a),
+ ALLSIGS
+#undef _DO
+ - 1
+};
+
+static void sig_handler(int);
+
+/* sig_handler():
+ * This is the handler called for all signals
+ * XXX: we cannot pass any data so we just store the old editline
+ * state in a private variable
+ */
+static void
+sig_handler(int signo)
+{
+ int i, save_errno;
+ sigset_t nset, oset;
+
+ save_errno = errno;
+ (void) sigemptyset(&nset);
+ (void) sigaddset(&nset, signo);
+ (void) sigprocmask(SIG_BLOCK, &nset, &oset);
+
+ sel->el_signal->sig_no = signo;
+
+ switch (signo) {
+ case SIGCONT:
+ tty_rawmode(sel);
+ if (ed_redisplay(sel, 0) == CC_REFRESH)
+ re_refresh(sel);
+ terminal__flush(sel);
+ break;
+
+ case SIGWINCH:
+ el_resize(sel);
+ break;
+
+ default:
+ tty_cookedmode(sel);
+ break;
+ }
+
+ for (i = 0; sighdl[i] != -1; i++)
+ if (signo == sighdl[i])
+ break;
+
+ (void) sigaction(signo, &sel->el_signal->sig_action[i], NULL);
+ sel->el_signal->sig_action[i].sa_handler = SIG_ERR;
+ sel->el_signal->sig_action[i].sa_flags = 0;
+ sigemptyset(&sel->el_signal->sig_action[i].sa_mask);
+ (void) sigprocmask(SIG_SETMASK, &oset, NULL);
+ (void) kill(0, signo);
+ errno = save_errno;
+}
+
+
+/* sig_init():
+ * Initialize all signal stuff
+ */
+libedit_private int
+sig_init(EditLine *el)
+{
+ size_t i;
+ sigset_t *nset, oset;
+
+ el->el_signal = el_malloc(sizeof(*el->el_signal));
+ if (el->el_signal == NULL)
+ return -1;
+
+ nset = &el->el_signal->sig_set;
+ (void) sigemptyset(nset);
+#define _DO(a) (void) sigaddset(nset, a);
+ ALLSIGS
+#undef _DO
+ (void) sigprocmask(SIG_BLOCK, nset, &oset);
+
+ for (i = 0; sighdl[i] != -1; i++) {
+ el->el_signal->sig_action[i].sa_handler = SIG_ERR;
+ el->el_signal->sig_action[i].sa_flags = 0;
+ sigemptyset(&el->el_signal->sig_action[i].sa_mask);
+ }
+
+ (void) sigprocmask(SIG_SETMASK, &oset, NULL);
+
+ return 0;
+}
+
+
+/* sig_end():
+ * Clear all signal stuff
+ */
+libedit_private void
+sig_end(EditLine *el)
+{
+
+ el_free(el->el_signal);
+ el->el_signal = NULL;
+}
+
+
+/* sig_set():
+ * set all the signal handlers
+ */
+libedit_private void
+sig_set(EditLine *el)
+{
+ size_t i;
+ sigset_t oset;
+ struct sigaction osa, nsa;
+
+ nsa.sa_handler = sig_handler;
+ nsa.sa_flags = 0;
+ sigemptyset(&nsa.sa_mask);
+
+ (void) sigprocmask(SIG_BLOCK, &el->el_signal->sig_set, &oset);
+
+ for (i = 0; sighdl[i] != -1; i++) {
+ /* This could happen if we get interrupted */
+ if (sigaction(sighdl[i], &nsa, &osa) != -1 &&
+ osa.sa_handler != sig_handler)
+ el->el_signal->sig_action[i] = osa;
+ }
+ sel = el;
+ (void) sigprocmask(SIG_SETMASK, &oset, NULL);
+}
+
+
+/* sig_clr():
+ * clear all the signal handlers
+ */
+libedit_private void
+sig_clr(EditLine *el)
+{
+ size_t i;
+ sigset_t oset;
+
+ (void) sigprocmask(SIG_BLOCK, &el->el_signal->sig_set, &oset);
+
+ for (i = 0; sighdl[i] != -1; i++)
+ if (el->el_signal->sig_action[i].sa_handler != SIG_ERR)
+ (void)sigaction(sighdl[i],
+ &el->el_signal->sig_action[i], NULL);
+
+ sel = NULL; /* we are going to die if the handler is
+ * called */
+ (void)sigprocmask(SIG_SETMASK, &oset, NULL);
+}
diff --git a/third_party/heimdal/lib/libedit/src/sig.h b/third_party/heimdal/lib/libedit/src/sig.h
new file mode 100644
index 0000000..5ee453f
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/sig.h
@@ -0,0 +1,70 @@
+/* $NetBSD: sig.h,v 1.11 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)sig.h 8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * el.sig.h: Signal handling functions
+ */
+#ifndef _h_el_sig
+#define _h_el_sig
+
+#include <signal.h>
+
+/*
+ * Define here all the signals we are going to handle
+ * The _DO macro is used to iterate in the source code
+ */
+#define ALLSIGS \
+ _DO(SIGINT) \
+ _DO(SIGTSTP) \
+ _DO(SIGQUIT) \
+ _DO(SIGHUP) \
+ _DO(SIGTERM) \
+ _DO(SIGCONT) \
+ _DO(SIGWINCH)
+#define ALLSIGSNO 7
+
+typedef struct {
+ struct sigaction sig_action[ALLSIGSNO];
+ sigset_t sig_set;
+ volatile sig_atomic_t sig_no;
+} *el_signal_t;
+
+libedit_private void sig_end(EditLine*);
+libedit_private int sig_init(EditLine*);
+libedit_private void sig_set(EditLine*);
+libedit_private void sig_clr(EditLine*);
+
+#endif /* _h_el_sig */
diff --git a/third_party/heimdal/lib/libedit/src/sys.h b/third_party/heimdal/lib/libedit/src/sys.h
new file mode 100644
index 0000000..4005781
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/sys.h
@@ -0,0 +1,112 @@
+/* $NetBSD: sys.h,v 1.27 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)sys.h 8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * sys.h: Put all the stupid compiler and system dependencies here...
+ */
+#ifndef _h_sys
+#define _h_sys
+
+#ifdef HAVE_SYS_CDEFS_H
+#include <sys/cdefs.h>
+#endif
+
+#ifdef HAVE_STDINT_H
+#include <stdint.h>
+#endif
+
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+#if !defined(__attribute__) && (defined(__cplusplus) || !defined(__GNUC__) || __GNUC__ == 2 && __GNUC_MINOR__ < 8)
+# define __attribute__(A)
+#endif
+
+#ifndef __BEGIN_DECLS
+# ifdef __cplusplus
+# define __BEGIN_DECLS extern "C" {
+# define __END_DECLS }
+# else
+# define __BEGIN_DECLS
+# define __END_DECLS
+# endif
+#endif
+
+/* If your compiler does not support this, define it to be empty. */
+#define libedit_private __attribute__((__visibility__("hidden")))
+
+#ifndef __arraycount
+# define __arraycount(a) (sizeof(a) / sizeof(*(a)))
+#endif
+
+#include <stdio.h>
+
+#ifndef HAVE_STRLCAT
+#define strlcat libedit_strlcat
+size_t strlcat(char *dst, const char *src, size_t size);
+#endif
+
+#ifndef HAVE_STRLCPY
+#define strlcpy libedit_strlcpy
+size_t strlcpy(char *dst, const char *src, size_t size);
+#endif
+
+#ifndef HAVE_GETLINE
+#define getline libedit_getline
+ssize_t getline(char **line, size_t *len, FILE *fp);
+#endif
+
+#ifndef _DIAGASSERT
+#define _DIAGASSERT(x)
+#endif
+
+#ifndef __RCSID
+#define __RCSID(x)
+#endif
+
+#ifndef HAVE_U_INT32_T
+typedef unsigned int u_int32_t;
+#endif
+
+#ifndef HAVE_SIZE_MAX
+#define SIZE_MAX ((size_t)-1)
+#endif
+
+#define REGEX /* Use POSIX.2 regular expression functions */
+#undef REGEXP /* Use UNIX V8 regular expression functions */
+
+#endif /* _h_sys */
diff --git a/third_party/heimdal/lib/libedit/src/terminal.c b/third_party/heimdal/lib/libedit/src/terminal.c
new file mode 100644
index 0000000..5d2271f
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/terminal.c
@@ -0,0 +1,1691 @@
+/* $NetBSD: terminal.c,v 1.32 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)term.c 8.2 (Berkeley) 4/30/95";
+#else
+__RCSID("$NetBSD: terminal.c,v 1.32 2016/05/09 21:46:56 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * terminal.c: Editor/termcap-curses interface
+ * We have to declare a static variable here, since the
+ * termcap putchar routine does not take an argument!
+ */
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <limits.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#ifdef HAVE_TERMCAP_H
+#include <termcap.h>
+#endif
+#ifdef HAVE_CURSES_H
+#include <curses.h>
+#elif HAVE_NCURSES_H
+#include <ncurses.h>
+#endif
+
+/* Solaris's term.h does horrid things. */
+#if defined(HAVE_TERM_H) && !defined(__sun) && !defined(HAVE_TERMCAP_H)
+#include <term.h>
+#endif
+
+#ifdef _REENTRANT
+#include <pthread.h>
+#endif
+
+#include "el.h"
+#include "fcns.h"
+
+/*
+ * IMPORTANT NOTE: these routines are allowed to look at the current screen
+ * and the current position assuming that it is correct. If this is not
+ * true, then the update will be WRONG! This is (should be) a valid
+ * assumption...
+ */
+
+#define TC_BUFSIZE ((size_t)2048)
+
+#define GoodStr(a) (el->el_terminal.t_str[a] != NULL && \
+ el->el_terminal.t_str[a][0] != '\0')
+#define Str(a) el->el_terminal.t_str[a]
+#define Val(a) el->el_terminal.t_val[a]
+
+static const struct termcapstr {
+ const char *name;
+ const char *long_name;
+} tstr[] = {
+#define T_al 0
+ { "al", "add new blank line" },
+#define T_bl 1
+ { "bl", "audible bell" },
+#define T_cd 2
+ { "cd", "clear to bottom" },
+#define T_ce 3
+ { "ce", "clear to end of line" },
+#define T_ch 4
+ { "ch", "cursor to horiz pos" },
+#define T_cl 5
+ { "cl", "clear screen" },
+#define T_dc 6
+ { "dc", "delete a character" },
+#define T_dl 7
+ { "dl", "delete a line" },
+#define T_dm 8
+ { "dm", "start delete mode" },
+#define T_ed 9
+ { "ed", "end delete mode" },
+#define T_ei 10
+ { "ei", "end insert mode" },
+#define T_fs 11
+ { "fs", "cursor from status line" },
+#define T_ho 12
+ { "ho", "home cursor" },
+#define T_ic 13
+ { "ic", "insert character" },
+#define T_im 14
+ { "im", "start insert mode" },
+#define T_ip 15
+ { "ip", "insert padding" },
+#define T_kd 16
+ { "kd", "sends cursor down" },
+#define T_kl 17
+ { "kl", "sends cursor left" },
+#define T_kr 18
+ { "kr", "sends cursor right" },
+#define T_ku 19
+ { "ku", "sends cursor up" },
+#define T_md 20
+ { "md", "begin bold" },
+#define T_me 21
+ { "me", "end attributes" },
+#define T_nd 22
+ { "nd", "non destructive space" },
+#define T_se 23
+ { "se", "end standout" },
+#define T_so 24
+ { "so", "begin standout" },
+#define T_ts 25
+ { "ts", "cursor to status line" },
+#define T_up 26
+ { "up", "cursor up one" },
+#define T_us 27
+ { "us", "begin underline" },
+#define T_ue 28
+ { "ue", "end underline" },
+#define T_vb 29
+ { "vb", "visible bell" },
+#define T_DC 30
+ { "DC", "delete multiple chars" },
+#define T_DO 31
+ { "DO", "cursor down multiple" },
+#define T_IC 32
+ { "IC", "insert multiple chars" },
+#define T_LE 33
+ { "LE", "cursor left multiple" },
+#define T_RI 34
+ { "RI", "cursor right multiple" },
+#define T_UP 35
+ { "UP", "cursor up multiple" },
+#define T_kh 36
+ { "kh", "send cursor home" },
+#define T_at7 37
+ { "@7", "send cursor end" },
+#define T_kD 38
+ { "kD", "send cursor delete" },
+#define T_str 39
+ { NULL, NULL }
+};
+
+static const struct termcapval {
+ const char *name;
+ const char *long_name;
+} tval[] = {
+#define T_am 0
+ { "am", "has automatic margins" },
+#define T_pt 1
+ { "pt", "has physical tabs" },
+#define T_li 2
+ { "li", "Number of lines" },
+#define T_co 3
+ { "co", "Number of columns" },
+#define T_km 4
+ { "km", "Has meta key" },
+#define T_xt 5
+ { "xt", "Tab chars destructive" },
+#define T_xn 6
+ { "xn", "newline ignored at right margin" },
+#define T_MT 7
+ { "MT", "Has meta key" }, /* XXX? */
+#define T_val 8
+ { NULL, NULL, }
+};
+/* do two or more of the attributes use me */
+
+static void terminal_setflags(EditLine *);
+static int terminal_rebuffer_display(EditLine *);
+static void terminal_free_display(EditLine *);
+static int terminal_alloc_display(EditLine *);
+static void terminal_alloc(EditLine *, const struct termcapstr *,
+ const char *);
+static void terminal_init_arrow(EditLine *);
+static void terminal_reset_arrow(EditLine *);
+static int terminal_putc(int);
+static void terminal_tputs(EditLine *, const char *, int);
+
+#ifdef _REENTRANT
+static pthread_mutex_t terminal_mutex = PTHREAD_MUTEX_INITIALIZER;
+#endif
+static FILE *terminal_outfile = NULL;
+
+#ifndef HAVE_TGETENT
+/* provide a stub curses which fails all calls if we have no tgetent et al */
+#define tgoto(x, y, z) (char *)0
+#define tgetstr(x, y) (char *)0
+#define tgetent(x, y) -1;
+#define tputs(x, y, z) -1
+#define tgetflag(x) -1
+#define tgetnum(x) -1
+#endif
+
+/* terminal_setflags():
+ * Set the terminal capability flags
+ */
+static void
+terminal_setflags(EditLine *el)
+{
+ EL_FLAGS = 0;
+ if (el->el_tty.t_tabs)
+ EL_FLAGS |= (Val(T_pt) && !Val(T_xt)) ? TERM_CAN_TAB : 0;
+
+ EL_FLAGS |= (Val(T_km) || Val(T_MT)) ? TERM_HAS_META : 0;
+ EL_FLAGS |= GoodStr(T_ce) ? TERM_CAN_CEOL : 0;
+ EL_FLAGS |= (GoodStr(T_dc) || GoodStr(T_DC)) ? TERM_CAN_DELETE : 0;
+ EL_FLAGS |= (GoodStr(T_im) || GoodStr(T_ic) || GoodStr(T_IC)) ?
+ TERM_CAN_INSERT : 0;
+ EL_FLAGS |= (GoodStr(T_up) || GoodStr(T_UP)) ? TERM_CAN_UP : 0;
+ EL_FLAGS |= Val(T_am) ? TERM_HAS_AUTO_MARGINS : 0;
+ EL_FLAGS |= Val(T_xn) ? TERM_HAS_MAGIC_MARGINS : 0;
+
+ if (GoodStr(T_me) && GoodStr(T_ue))
+ EL_FLAGS |= (strcmp(Str(T_me), Str(T_ue)) == 0) ?
+ TERM_CAN_ME : 0;
+ else
+ EL_FLAGS &= ~TERM_CAN_ME;
+ if (GoodStr(T_me) && GoodStr(T_se))
+ EL_FLAGS |= (strcmp(Str(T_me), Str(T_se)) == 0) ?
+ TERM_CAN_ME : 0;
+
+
+#ifdef DEBUG_SCREEN
+ if (!EL_CAN_UP) {
+ (void) fprintf(el->el_errfile,
+ "WARNING: Your terminal cannot move up.\n");
+ (void) fprintf(el->el_errfile,
+ "Editing may be odd for long lines.\n");
+ }
+ if (!EL_CAN_CEOL)
+ (void) fprintf(el->el_errfile, "no clear EOL capability.\n");
+ if (!EL_CAN_DELETE)
+ (void) fprintf(el->el_errfile, "no delete char capability.\n");
+ if (!EL_CAN_INSERT)
+ (void) fprintf(el->el_errfile, "no insert char capability.\n");
+#endif /* DEBUG_SCREEN */
+}
+
+/* terminal_init():
+ * Initialize the terminal stuff
+ */
+libedit_private int
+terminal_init(EditLine *el)
+{
+
+ el->el_terminal.t_buf = el_malloc(TC_BUFSIZE *
+ sizeof(*el->el_terminal.t_buf));
+ if (el->el_terminal.t_buf == NULL)
+ goto fail1;
+ el->el_terminal.t_cap = el_malloc(TC_BUFSIZE *
+ sizeof(*el->el_terminal.t_cap));
+ if (el->el_terminal.t_cap == NULL)
+ goto fail2;
+ el->el_terminal.t_fkey = el_malloc(A_K_NKEYS *
+ sizeof(*el->el_terminal.t_fkey));
+ if (el->el_terminal.t_fkey == NULL)
+ goto fail3;
+ el->el_terminal.t_loc = 0;
+ el->el_terminal.t_str = el_malloc(T_str *
+ sizeof(*el->el_terminal.t_str));
+ if (el->el_terminal.t_str == NULL)
+ goto fail4;
+ (void) memset(el->el_terminal.t_str, 0, T_str *
+ sizeof(*el->el_terminal.t_str));
+ el->el_terminal.t_val = el_malloc(T_val *
+ sizeof(*el->el_terminal.t_val));
+ if (el->el_terminal.t_val == NULL)
+ goto fail5;
+ (void) memset(el->el_terminal.t_val, 0, T_val *
+ sizeof(*el->el_terminal.t_val));
+ (void) terminal_set(el, NULL);
+ terminal_init_arrow(el);
+ return 0;
+fail5:
+ free(el->el_terminal.t_str);
+ el->el_terminal.t_str = NULL;
+fail4:
+ free(el->el_terminal.t_fkey);
+ el->el_terminal.t_fkey = NULL;
+fail3:
+ free(el->el_terminal.t_cap);
+ el->el_terminal.t_cap = NULL;
+fail2:
+ free(el->el_terminal.t_buf);
+ el->el_terminal.t_buf = NULL;
+fail1:
+ return -1;
+}
+
+/* terminal_end():
+ * Clean up the terminal stuff
+ */
+libedit_private void
+terminal_end(EditLine *el)
+{
+
+ el_free(el->el_terminal.t_buf);
+ el->el_terminal.t_buf = NULL;
+ el_free(el->el_terminal.t_cap);
+ el->el_terminal.t_cap = NULL;
+ el->el_terminal.t_loc = 0;
+ el_free(el->el_terminal.t_str);
+ el->el_terminal.t_str = NULL;
+ el_free(el->el_terminal.t_val);
+ el->el_terminal.t_val = NULL;
+ el_free(el->el_terminal.t_fkey);
+ el->el_terminal.t_fkey = NULL;
+ terminal_free_display(el);
+}
+
+
+/* terminal_alloc():
+ * Maintain a string pool for termcap strings
+ */
+static void
+terminal_alloc(EditLine *el, const struct termcapstr *t, const char *cap)
+{
+ char termbuf[TC_BUFSIZE];
+ size_t tlen, clen;
+ char **tlist = el->el_terminal.t_str;
+ char **tmp, **str = &tlist[t - tstr];
+
+ (void) memset(termbuf, 0, sizeof(termbuf));
+ if (cap == NULL || *cap == '\0') {
+ *str = NULL;
+ return;
+ } else
+ clen = strlen(cap);
+
+ tlen = *str == NULL ? 0 : strlen(*str);
+
+ /*
+ * New string is shorter; no need to allocate space
+ */
+ if (clen <= tlen) {
+ if (*str)
+ (void) strcpy(*str, cap); /* XXX strcpy is safe */
+ return;
+ }
+ /*
+ * New string is longer; see if we have enough space to append
+ */
+ if (el->el_terminal.t_loc + 3 < TC_BUFSIZE) {
+ /* XXX strcpy is safe */
+ (void) strcpy(*str = &el->el_terminal.t_buf[
+ el->el_terminal.t_loc], cap);
+ el->el_terminal.t_loc += clen + 1; /* one for \0 */
+ return;
+ }
+ /*
+ * Compact our buffer; no need to check compaction, cause we know it
+ * fits...
+ */
+ tlen = 0;
+ for (tmp = tlist; tmp < &tlist[T_str]; tmp++)
+ if (*tmp != NULL && **tmp != '\0' && *tmp != *str) {
+ char *ptr;
+
+ for (ptr = *tmp; *ptr != '\0'; termbuf[tlen++] = *ptr++)
+ continue;
+ termbuf[tlen++] = '\0';
+ }
+ memcpy(el->el_terminal.t_buf, termbuf, TC_BUFSIZE);
+ el->el_terminal.t_loc = tlen;
+ if (el->el_terminal.t_loc + 3 >= TC_BUFSIZE) {
+ (void) fprintf(el->el_errfile,
+ "Out of termcap string space.\n");
+ return;
+ }
+ /* XXX strcpy is safe */
+ (void) strcpy(*str = &el->el_terminal.t_buf[el->el_terminal.t_loc],
+ cap);
+ el->el_terminal.t_loc += (size_t)clen + 1; /* one for \0 */
+ return;
+}
+
+
+/* terminal_rebuffer_display():
+ * Rebuffer the display after the screen changed size
+ */
+static int
+terminal_rebuffer_display(EditLine *el)
+{
+ coord_t *c = &el->el_terminal.t_size;
+
+ terminal_free_display(el);
+
+ c->h = Val(T_co);
+ c->v = Val(T_li);
+
+ if (terminal_alloc_display(el) == -1)
+ return -1;
+ return 0;
+}
+
+
+/* terminal_alloc_display():
+ * Allocate a new display.
+ */
+static int
+terminal_alloc_display(EditLine *el)
+{
+ int i;
+ wchar_t **b;
+ coord_t *c = &el->el_terminal.t_size;
+
+ b = el_malloc(sizeof(*b) * (size_t)(c->v + 1));
+ if (b == NULL)
+ goto done;
+ for (i = 0; i < c->v; i++) {
+ b[i] = el_malloc(sizeof(**b) * (size_t)(c->h + 1));
+ if (b[i] == NULL) {
+ while (--i >= 0)
+ el_free(b[i]);
+ el_free(b);
+ goto done;
+ }
+ }
+ b[c->v] = NULL;
+ el->el_display = b;
+
+ b = el_malloc(sizeof(*b) * (size_t)(c->v + 1));
+ if (b == NULL)
+ goto done;
+ for (i = 0; i < c->v; i++) {
+ b[i] = el_malloc(sizeof(**b) * (size_t)(c->h + 1));
+ if (b[i] == NULL) {
+ while (--i >= 0)
+ el_free(b[i]);
+ el_free(b);
+ goto done;
+ }
+ }
+ b[c->v] = NULL;
+ el->el_vdisplay = b;
+ return 0;
+done:
+ terminal_free_display(el);
+ return -1;
+}
+
+
+/* terminal_free_display():
+ * Free the display buffers
+ */
+static void
+terminal_free_display(EditLine *el)
+{
+ wchar_t **b;
+ wchar_t **bufp;
+
+ b = el->el_display;
+ el->el_display = NULL;
+ if (b != NULL) {
+ for (bufp = b; *bufp != NULL; bufp++)
+ el_free(*bufp);
+ el_free(b);
+ }
+ b = el->el_vdisplay;
+ el->el_vdisplay = NULL;
+ if (b != NULL) {
+ for (bufp = b; *bufp != NULL; bufp++)
+ el_free(*bufp);
+ el_free(b);
+ }
+}
+
+
+/* terminal_move_to_line():
+ * move to line <where> (first line == 0)
+ * as efficiently as possible
+ */
+libedit_private void
+terminal_move_to_line(EditLine *el, int where)
+{
+ int del;
+
+ if (where == el->el_cursor.v)
+ return;
+
+ if (where > el->el_terminal.t_size.v) {
+#ifdef DEBUG_SCREEN
+ (void) fprintf(el->el_errfile,
+ "%s: where is ridiculous: %d\r\n", __func__, where);
+#endif /* DEBUG_SCREEN */
+ return;
+ }
+ if ((del = where - el->el_cursor.v) > 0) {
+ while (del > 0) {
+ if (EL_HAS_AUTO_MARGINS &&
+ el->el_display[el->el_cursor.v][0] != '\0') {
+ size_t h = (size_t)
+ (el->el_terminal.t_size.h - 1);
+ for (; h > 0 &&
+ el->el_display[el->el_cursor.v][h] ==
+ MB_FILL_CHAR;
+ h--)
+ continue;
+ /* move without newline */
+ terminal_move_to_char(el, (int)h);
+ terminal_overwrite(el, &el->el_display
+ [el->el_cursor.v][el->el_cursor.h],
+ (size_t)(el->el_terminal.t_size.h -
+ el->el_cursor.h));
+ /* updates Cursor */
+ del--;
+ } else {
+ if ((del > 1) && GoodStr(T_DO)) {
+ terminal_tputs(el, tgoto(Str(T_DO), del,
+ del), del);
+ del = 0;
+ } else {
+ for (; del > 0; del--)
+ terminal__putc(el, '\n');
+ /* because the \n will become \r\n */
+ el->el_cursor.h = 0;
+ }
+ }
+ }
+ } else { /* del < 0 */
+ if (GoodStr(T_UP) && (-del > 1 || !GoodStr(T_up)))
+ terminal_tputs(el, tgoto(Str(T_UP), -del, -del), -del);
+ else {
+ if (GoodStr(T_up))
+ for (; del < 0; del++)
+ terminal_tputs(el, Str(T_up), 1);
+ }
+ }
+ el->el_cursor.v = where;/* now where is here */
+}
+
+
+/* terminal_move_to_char():
+ * Move to the character position specified
+ */
+libedit_private void
+terminal_move_to_char(EditLine *el, int where)
+{
+ int del, i;
+
+mc_again:
+ if (where == el->el_cursor.h)
+ return;
+
+ if (where > el->el_terminal.t_size.h) {
+#ifdef DEBUG_SCREEN
+ (void) fprintf(el->el_errfile,
+ "%s: where is ridiculous: %d\r\n", __func__, where);
+#endif /* DEBUG_SCREEN */
+ return;
+ }
+ if (!where) { /* if where is first column */
+ terminal__putc(el, '\r'); /* do a CR */
+ el->el_cursor.h = 0;
+ return;
+ }
+ del = where - el->el_cursor.h;
+
+ if ((del < -4 || del > 4) && GoodStr(T_ch))
+ /* go there directly */
+ terminal_tputs(el, tgoto(Str(T_ch), where, where), where);
+ else {
+ if (del > 0) { /* moving forward */
+ if ((del > 4) && GoodStr(T_RI))
+ terminal_tputs(el, tgoto(Str(T_RI), del, del),
+ del);
+ else {
+ /* if I can do tabs, use them */
+ if (EL_CAN_TAB) {
+ if ((el->el_cursor.h & 0370) !=
+ (where & ~0x7)
+ && (el->el_display[
+ el->el_cursor.v][where & 0370] !=
+ MB_FILL_CHAR)
+ ) {
+ /* if not within tab stop */
+ for (i =
+ (el->el_cursor.h & 0370);
+ i < (where & ~0x7);
+ i += 8)
+ terminal__putc(el,
+ '\t');
+ /* then tab over */
+ el->el_cursor.h = where & ~0x7;
+ }
+ }
+ /*
+ * it's usually cheaper to just write the
+ * chars, so we do.
+ */
+ /*
+ * NOTE THAT terminal_overwrite() WILL CHANGE
+ * el->el_cursor.h!!!
+ */
+ terminal_overwrite(el, &el->el_display[
+ el->el_cursor.v][el->el_cursor.h],
+ (size_t)(where - el->el_cursor.h));
+
+ }
+ } else { /* del < 0 := moving backward */
+ if ((-del > 4) && GoodStr(T_LE))
+ terminal_tputs(el, tgoto(Str(T_LE), -del, -del),
+ -del);
+ else { /* can't go directly there */
+ /*
+ * if the "cost" is greater than the "cost"
+ * from col 0
+ */
+ if (EL_CAN_TAB ?
+ ((unsigned int)-del >
+ (((unsigned int) where >> 3) +
+ (where & 07)))
+ : (-del > where)) {
+ terminal__putc(el, '\r');/* do a CR */
+ el->el_cursor.h = 0;
+ goto mc_again; /* and try again */
+ }
+ for (i = 0; i < -del; i++)
+ terminal__putc(el, '\b');
+ }
+ }
+ }
+ el->el_cursor.h = where; /* now where is here */
+}
+
+
+/* terminal_overwrite():
+ * Overstrike num characters
+ * Assumes MB_FILL_CHARs are present to keep the column count correct
+ */
+libedit_private void
+terminal_overwrite(EditLine *el, const wchar_t *cp, size_t n)
+{
+ if (n == 0)
+ return;
+
+ if (n > (size_t)el->el_terminal.t_size.h) {
+#ifdef DEBUG_SCREEN
+ (void) fprintf(el->el_errfile,
+ "%s: n is ridiculous: %zu\r\n", __func__, n);
+#endif /* DEBUG_SCREEN */
+ return;
+ }
+
+ do {
+ /* terminal__putc() ignores any MB_FILL_CHARs */
+ terminal__putc(el, *cp++);
+ el->el_cursor.h++;
+ } while (--n);
+
+ if (el->el_cursor.h >= el->el_terminal.t_size.h) { /* wrap? */
+ if (EL_HAS_AUTO_MARGINS) { /* yes */
+ el->el_cursor.h = 0;
+ el->el_cursor.v++;
+ if (EL_HAS_MAGIC_MARGINS) {
+ /* force the wrap to avoid the "magic"
+ * situation */
+ wchar_t c;
+ if ((c = el->el_display[el->el_cursor.v]
+ [el->el_cursor.h]) != '\0') {
+ terminal_overwrite(el, &c, (size_t)1);
+ while (el->el_display[el->el_cursor.v]
+ [el->el_cursor.h] == MB_FILL_CHAR)
+ el->el_cursor.h++;
+ } else {
+ terminal__putc(el, ' ');
+ el->el_cursor.h = 1;
+ }
+ }
+ } else /* no wrap, but cursor stays on screen */
+ el->el_cursor.h = el->el_terminal.t_size.h - 1;
+ }
+}
+
+
+/* terminal_deletechars():
+ * Delete num characters
+ */
+libedit_private void
+terminal_deletechars(EditLine *el, int num)
+{
+ if (num <= 0)
+ return;
+
+ if (!EL_CAN_DELETE) {
+#ifdef DEBUG_EDIT
+ (void) fprintf(el->el_errfile, " ERROR: cannot delete \n");
+#endif /* DEBUG_EDIT */
+ return;
+ }
+ if (num > el->el_terminal.t_size.h) {
+#ifdef DEBUG_SCREEN
+ (void) fprintf(el->el_errfile,
+ "%s: num is ridiculous: %d\r\n", __func__, num);
+#endif /* DEBUG_SCREEN */
+ return;
+ }
+ if (GoodStr(T_DC)) /* if I have multiple delete */
+ if ((num > 1) || !GoodStr(T_dc)) { /* if dc would be more
+ * expen. */
+ terminal_tputs(el, tgoto(Str(T_DC), num, num), num);
+ return;
+ }
+ if (GoodStr(T_dm)) /* if I have delete mode */
+ terminal_tputs(el, Str(T_dm), 1);
+
+ if (GoodStr(T_dc)) /* else do one at a time */
+ while (num--)
+ terminal_tputs(el, Str(T_dc), 1);
+
+ if (GoodStr(T_ed)) /* if I have delete mode */
+ terminal_tputs(el, Str(T_ed), 1);
+}
+
+
+/* terminal_insertwrite():
+ * Puts terminal in insert character mode or inserts num
+ * characters in the line
+ * Assumes MB_FILL_CHARs are present to keep column count correct
+ */
+libedit_private void
+terminal_insertwrite(EditLine *el, wchar_t *cp, int num)
+{
+ if (num <= 0)
+ return;
+ if (!EL_CAN_INSERT) {
+#ifdef DEBUG_EDIT
+ (void) fprintf(el->el_errfile, " ERROR: cannot insert \n");
+#endif /* DEBUG_EDIT */
+ return;
+ }
+ if (num > el->el_terminal.t_size.h) {
+#ifdef DEBUG_SCREEN
+ (void) fprintf(el->el_errfile,
+ "%s: num is ridiculous: %d\r\n", __func__, num);
+#endif /* DEBUG_SCREEN */
+ return;
+ }
+ if (GoodStr(T_IC)) /* if I have multiple insert */
+ if ((num > 1) || !GoodStr(T_ic)) {
+ /* if ic would be more expensive */
+ terminal_tputs(el, tgoto(Str(T_IC), num, num), num);
+ terminal_overwrite(el, cp, (size_t)num);
+ /* this updates el_cursor.h */
+ return;
+ }
+ if (GoodStr(T_im) && GoodStr(T_ei)) { /* if I have insert mode */
+ terminal_tputs(el, Str(T_im), 1);
+
+ el->el_cursor.h += num;
+ do
+ terminal__putc(el, *cp++);
+ while (--num);
+
+ if (GoodStr(T_ip)) /* have to make num chars insert */
+ terminal_tputs(el, Str(T_ip), 1);
+
+ terminal_tputs(el, Str(T_ei), 1);
+ return;
+ }
+ do {
+ if (GoodStr(T_ic)) /* have to make num chars insert */
+ terminal_tputs(el, Str(T_ic), 1);
+
+ terminal__putc(el, *cp++);
+
+ el->el_cursor.h++;
+
+ if (GoodStr(T_ip)) /* have to make num chars insert */
+ terminal_tputs(el, Str(T_ip), 1);
+ /* pad the inserted char */
+
+ } while (--num);
+}
+
+
+/* terminal_clear_EOL():
+ * clear to end of line. There are num characters to clear
+ */
+libedit_private void
+terminal_clear_EOL(EditLine *el, int num)
+{
+ int i;
+
+ if (EL_CAN_CEOL && GoodStr(T_ce))
+ terminal_tputs(el, Str(T_ce), 1);
+ else {
+ for (i = 0; i < num; i++)
+ terminal__putc(el, ' ');
+ el->el_cursor.h += num; /* have written num spaces */
+ }
+}
+
+
+/* terminal_clear_screen():
+ * Clear the screen
+ */
+libedit_private void
+terminal_clear_screen(EditLine *el)
+{ /* clear the whole screen and home */
+
+ if (GoodStr(T_cl))
+ /* send the clear screen code */
+ terminal_tputs(el, Str(T_cl), Val(T_li));
+ else if (GoodStr(T_ho) && GoodStr(T_cd)) {
+ terminal_tputs(el, Str(T_ho), Val(T_li)); /* home */
+ /* clear to bottom of screen */
+ terminal_tputs(el, Str(T_cd), Val(T_li));
+ } else {
+ terminal__putc(el, '\r');
+ terminal__putc(el, '\n');
+ }
+}
+
+
+/* terminal_beep():
+ * Beep the way the terminal wants us
+ */
+libedit_private void
+terminal_beep(EditLine *el)
+{
+ if (GoodStr(T_bl))
+ /* what termcap says we should use */
+ terminal_tputs(el, Str(T_bl), 1);
+ else
+ terminal__putc(el, '\007'); /* an ASCII bell; ^G */
+}
+
+
+libedit_private void
+terminal_get(EditLine *el, const char **term)
+{
+ *term = el->el_terminal.t_name;
+}
+
+
+/* terminal_set():
+ * Read in the terminal capabilities from the requested terminal
+ */
+libedit_private int
+terminal_set(EditLine *el, const char *term)
+{
+ int i;
+ char buf[TC_BUFSIZE];
+ char *area;
+ const struct termcapstr *t;
+ sigset_t oset, nset;
+ int lins, cols;
+
+ (void) sigemptyset(&nset);
+ (void) sigaddset(&nset, SIGWINCH);
+ (void) sigprocmask(SIG_BLOCK, &nset, &oset);
+
+ area = buf;
+
+
+ if (term == NULL)
+ term = getenv("TERM");
+
+ if (!term || !term[0])
+ term = "dumb";
+
+ if (strcmp(term, "emacs") == 0)
+ el->el_flags |= EDIT_DISABLED;
+
+ (void) memset(el->el_terminal.t_cap, 0, TC_BUFSIZE);
+
+ i = tgetent(el->el_terminal.t_cap, term);
+
+ if (i <= 0) {
+ if (i == -1)
+ (void) fprintf(el->el_errfile,
+ "Cannot read termcap database;\n");
+ else if (i == 0)
+ (void) fprintf(el->el_errfile,
+ "No entry for terminal type \"%s\";\n", term);
+ (void) fprintf(el->el_errfile,
+ "using dumb terminal settings.\n");
+ Val(T_co) = 80; /* do a dumb terminal */
+ Val(T_pt) = Val(T_km) = Val(T_li) = 0;
+ Val(T_xt) = Val(T_MT);
+ for (t = tstr; t->name != NULL; t++)
+ terminal_alloc(el, t, NULL);
+ } else {
+ /* auto/magic margins */
+ Val(T_am) = tgetflag("am");
+ Val(T_xn) = tgetflag("xn");
+ /* Can we tab */
+ Val(T_pt) = tgetflag("pt");
+ Val(T_xt) = tgetflag("xt");
+ /* do we have a meta? */
+ Val(T_km) = tgetflag("km");
+ Val(T_MT) = tgetflag("MT");
+ /* Get the size */
+ Val(T_co) = tgetnum("co");
+ Val(T_li) = tgetnum("li");
+ for (t = tstr; t->name != NULL; t++) {
+ /* XXX: some systems' tgetstr needs non const */
+ terminal_alloc(el, t, tgetstr(strchr(t->name, *t->name),
+ &area));
+ }
+ }
+
+ if (Val(T_co) < 2)
+ Val(T_co) = 80; /* just in case */
+ if (Val(T_li) < 1)
+ Val(T_li) = 24;
+
+ el->el_terminal.t_size.v = Val(T_co);
+ el->el_terminal.t_size.h = Val(T_li);
+
+ terminal_setflags(el);
+
+ /* get the correct window size */
+ (void) terminal_get_size(el, &lins, &cols);
+ if (terminal_change_size(el, lins, cols) == -1)
+ return -1;
+ (void) sigprocmask(SIG_SETMASK, &oset, NULL);
+ terminal_bind_arrow(el);
+ el->el_terminal.t_name = term;
+ return i <= 0 ? -1 : 0;
+}
+
+
+/* terminal_get_size():
+ * Return the new window size in lines and cols, and
+ * true if the size was changed.
+ */
+libedit_private int
+terminal_get_size(EditLine *el, int *lins, int *cols)
+{
+
+ *cols = Val(T_co);
+ *lins = Val(T_li);
+
+#ifdef TIOCGWINSZ
+ {
+ struct winsize ws;
+ if (ioctl(el->el_infd, TIOCGWINSZ, &ws) != -1) {
+ if (ws.ws_col)
+ *cols = ws.ws_col;
+ if (ws.ws_row)
+ *lins = ws.ws_row;
+ }
+ }
+#endif
+#ifdef TIOCGSIZE
+ {
+ struct ttysize ts;
+ if (ioctl(el->el_infd, TIOCGSIZE, &ts) != -1) {
+ if (ts.ts_cols)
+ *cols = ts.ts_cols;
+ if (ts.ts_lines)
+ *lins = ts.ts_lines;
+ }
+ }
+#endif
+ return Val(T_co) != *cols || Val(T_li) != *lins;
+}
+
+
+/* terminal_change_size():
+ * Change the size of the terminal
+ */
+libedit_private int
+terminal_change_size(EditLine *el, int lins, int cols)
+{
+ /*
+ * Just in case
+ */
+ Val(T_co) = (cols < 2) ? 80 : cols;
+ Val(T_li) = (lins < 1) ? 24 : lins;
+
+ /* re-make display buffers */
+ if (terminal_rebuffer_display(el) == -1)
+ return -1;
+ re_clear_display(el);
+ return 0;
+}
+
+
+/* terminal_init_arrow():
+ * Initialize the arrow key bindings from termcap
+ */
+static void
+terminal_init_arrow(EditLine *el)
+{
+ funckey_t *arrow = el->el_terminal.t_fkey;
+
+ arrow[A_K_DN].name = L"down";
+ arrow[A_K_DN].key = T_kd;
+ arrow[A_K_DN].fun.cmd = ED_NEXT_HISTORY;
+ arrow[A_K_DN].type = XK_CMD;
+
+ arrow[A_K_UP].name = L"up";
+ arrow[A_K_UP].key = T_ku;
+ arrow[A_K_UP].fun.cmd = ED_PREV_HISTORY;
+ arrow[A_K_UP].type = XK_CMD;
+
+ arrow[A_K_LT].name = L"left";
+ arrow[A_K_LT].key = T_kl;
+ arrow[A_K_LT].fun.cmd = ED_PREV_CHAR;
+ arrow[A_K_LT].type = XK_CMD;
+
+ arrow[A_K_RT].name = L"right";
+ arrow[A_K_RT].key = T_kr;
+ arrow[A_K_RT].fun.cmd = ED_NEXT_CHAR;
+ arrow[A_K_RT].type = XK_CMD;
+
+ arrow[A_K_HO].name = L"home";
+ arrow[A_K_HO].key = T_kh;
+ arrow[A_K_HO].fun.cmd = ED_MOVE_TO_BEG;
+ arrow[A_K_HO].type = XK_CMD;
+
+ arrow[A_K_EN].name = L"end";
+ arrow[A_K_EN].key = T_at7;
+ arrow[A_K_EN].fun.cmd = ED_MOVE_TO_END;
+ arrow[A_K_EN].type = XK_CMD;
+
+ arrow[A_K_DE].name = L"delete";
+ arrow[A_K_DE].key = T_kD;
+ arrow[A_K_DE].fun.cmd = ED_DELETE_NEXT_CHAR;
+ arrow[A_K_DE].type = XK_CMD;
+}
+
+
+/* terminal_reset_arrow():
+ * Reset arrow key bindings
+ */
+static void
+terminal_reset_arrow(EditLine *el)
+{
+ funckey_t *arrow = el->el_terminal.t_fkey;
+ static const wchar_t strA[] = L"\033[A";
+ static const wchar_t strB[] = L"\033[B";
+ static const wchar_t strC[] = L"\033[C";
+ static const wchar_t strD[] = L"\033[D";
+ static const wchar_t strH[] = L"\033[H";
+ static const wchar_t strF[] = L"\033[F";
+ static const wchar_t stOA[] = L"\033OA";
+ static const wchar_t stOB[] = L"\033OB";
+ static const wchar_t stOC[] = L"\033OC";
+ static const wchar_t stOD[] = L"\033OD";
+ static const wchar_t stOH[] = L"\033OH";
+ static const wchar_t stOF[] = L"\033OF";
+
+ keymacro_add(el, strA, &arrow[A_K_UP].fun, arrow[A_K_UP].type);
+ keymacro_add(el, strB, &arrow[A_K_DN].fun, arrow[A_K_DN].type);
+ keymacro_add(el, strC, &arrow[A_K_RT].fun, arrow[A_K_RT].type);
+ keymacro_add(el, strD, &arrow[A_K_LT].fun, arrow[A_K_LT].type);
+ keymacro_add(el, strH, &arrow[A_K_HO].fun, arrow[A_K_HO].type);
+ keymacro_add(el, strF, &arrow[A_K_EN].fun, arrow[A_K_EN].type);
+ keymacro_add(el, stOA, &arrow[A_K_UP].fun, arrow[A_K_UP].type);
+ keymacro_add(el, stOB, &arrow[A_K_DN].fun, arrow[A_K_DN].type);
+ keymacro_add(el, stOC, &arrow[A_K_RT].fun, arrow[A_K_RT].type);
+ keymacro_add(el, stOD, &arrow[A_K_LT].fun, arrow[A_K_LT].type);
+ keymacro_add(el, stOH, &arrow[A_K_HO].fun, arrow[A_K_HO].type);
+ keymacro_add(el, stOF, &arrow[A_K_EN].fun, arrow[A_K_EN].type);
+
+ if (el->el_map.type != MAP_VI)
+ return;
+ keymacro_add(el, &strA[1], &arrow[A_K_UP].fun, arrow[A_K_UP].type);
+ keymacro_add(el, &strB[1], &arrow[A_K_DN].fun, arrow[A_K_DN].type);
+ keymacro_add(el, &strC[1], &arrow[A_K_RT].fun, arrow[A_K_RT].type);
+ keymacro_add(el, &strD[1], &arrow[A_K_LT].fun, arrow[A_K_LT].type);
+ keymacro_add(el, &strH[1], &arrow[A_K_HO].fun, arrow[A_K_HO].type);
+ keymacro_add(el, &strF[1], &arrow[A_K_EN].fun, arrow[A_K_EN].type);
+ keymacro_add(el, &stOA[1], &arrow[A_K_UP].fun, arrow[A_K_UP].type);
+ keymacro_add(el, &stOB[1], &arrow[A_K_DN].fun, arrow[A_K_DN].type);
+ keymacro_add(el, &stOC[1], &arrow[A_K_RT].fun, arrow[A_K_RT].type);
+ keymacro_add(el, &stOD[1], &arrow[A_K_LT].fun, arrow[A_K_LT].type);
+ keymacro_add(el, &stOH[1], &arrow[A_K_HO].fun, arrow[A_K_HO].type);
+ keymacro_add(el, &stOF[1], &arrow[A_K_EN].fun, arrow[A_K_EN].type);
+}
+
+
+/* terminal_set_arrow():
+ * Set an arrow key binding
+ */
+libedit_private int
+terminal_set_arrow(EditLine *el, const wchar_t *name, keymacro_value_t *fun,
+ int type)
+{
+ funckey_t *arrow = el->el_terminal.t_fkey;
+ int i;
+
+ for (i = 0; i < A_K_NKEYS; i++)
+ if (wcscmp(name, arrow[i].name) == 0) {
+ arrow[i].fun = *fun;
+ arrow[i].type = type;
+ return 0;
+ }
+ return -1;
+}
+
+
+/* terminal_clear_arrow():
+ * Clear an arrow key binding
+ */
+libedit_private int
+terminal_clear_arrow(EditLine *el, const wchar_t *name)
+{
+ funckey_t *arrow = el->el_terminal.t_fkey;
+ int i;
+
+ for (i = 0; i < A_K_NKEYS; i++)
+ if (wcscmp(name, arrow[i].name) == 0) {
+ arrow[i].type = XK_NOD;
+ return 0;
+ }
+ return -1;
+}
+
+
+/* terminal_print_arrow():
+ * Print the arrow key bindings
+ */
+libedit_private void
+terminal_print_arrow(EditLine *el, const wchar_t *name)
+{
+ int i;
+ funckey_t *arrow = el->el_terminal.t_fkey;
+
+ for (i = 0; i < A_K_NKEYS; i++)
+ if (*name == '\0' || wcscmp(name, arrow[i].name) == 0)
+ if (arrow[i].type != XK_NOD)
+ keymacro_kprint(el, arrow[i].name,
+ &arrow[i].fun, arrow[i].type);
+}
+
+
+/* terminal_bind_arrow():
+ * Bind the arrow keys
+ */
+libedit_private void
+terminal_bind_arrow(EditLine *el)
+{
+ el_action_t *map;
+ const el_action_t *dmap;
+ int i, j;
+ char *p;
+ funckey_t *arrow = el->el_terminal.t_fkey;
+
+ /* Check if the components needed are initialized */
+ if (el->el_terminal.t_buf == NULL || el->el_map.key == NULL)
+ return;
+
+ map = el->el_map.type == MAP_VI ? el->el_map.alt : el->el_map.key;
+ dmap = el->el_map.type == MAP_VI ? el->el_map.vic : el->el_map.emacs;
+
+ terminal_reset_arrow(el);
+
+ for (i = 0; i < A_K_NKEYS; i++) {
+ wchar_t wt_str[VISUAL_WIDTH_MAX];
+ wchar_t *px;
+ size_t n;
+
+ p = el->el_terminal.t_str[arrow[i].key];
+ if (!p || !*p)
+ continue;
+ for (n = 0; n < VISUAL_WIDTH_MAX && p[n]; ++n)
+ wt_str[n] = p[n];
+ while (n < VISUAL_WIDTH_MAX)
+ wt_str[n++] = '\0';
+ px = wt_str;
+ j = (unsigned char) *p;
+ /*
+ * Assign the arrow keys only if:
+ *
+ * 1. They are multi-character arrow keys and the user
+ * has not re-assigned the leading character, or
+ * has re-assigned the leading character to be
+ * ED_SEQUENCE_LEAD_IN
+ * 2. They are single arrow keys pointing to an
+ * unassigned key.
+ */
+ if (arrow[i].type == XK_NOD)
+ keymacro_clear(el, map, px);
+ else {
+ if (p[1] && (dmap[j] == map[j] ||
+ map[j] == ED_SEQUENCE_LEAD_IN)) {
+ keymacro_add(el, px, &arrow[i].fun,
+ arrow[i].type);
+ map[j] = ED_SEQUENCE_LEAD_IN;
+ } else if (map[j] == ED_UNASSIGNED) {
+ keymacro_clear(el, map, px);
+ if (arrow[i].type == XK_CMD)
+ map[j] = arrow[i].fun.cmd;
+ else
+ keymacro_add(el, px, &arrow[i].fun,
+ arrow[i].type);
+ }
+ }
+ }
+}
+
+/* terminal_putc():
+ * Add a character
+ */
+static int
+terminal_putc(int c)
+{
+ if (terminal_outfile == NULL)
+ return -1;
+ return fputc(c, terminal_outfile);
+}
+
+static void
+terminal_tputs(EditLine *el, const char *cap, int affcnt)
+{
+#ifdef _REENTRANT
+ pthread_mutex_lock(&terminal_mutex);
+#endif
+ terminal_outfile = el->el_outfile;
+ (void)tputs(cap, affcnt, terminal_putc);
+#ifdef _REENTRANT
+ pthread_mutex_unlock(&terminal_mutex);
+#endif
+}
+
+/* terminal__putc():
+ * Add a character
+ */
+libedit_private int
+terminal__putc(EditLine *el, wint_t c)
+{
+ char buf[MB_LEN_MAX +1];
+ ssize_t i;
+ if (c == (wint_t)MB_FILL_CHAR)
+ return 0;
+ i = ct_encode_char(buf, (size_t)MB_LEN_MAX, c);
+ if (i <= 0)
+ return (int)i;
+ buf[i] = '\0';
+ return fputs(buf, el->el_outfile);
+}
+
+/* terminal__flush():
+ * Flush output
+ */
+libedit_private void
+terminal__flush(EditLine *el)
+{
+
+ (void) fflush(el->el_outfile);
+}
+
+/* terminal_writec():
+ * Write the given character out, in a human readable form
+ */
+libedit_private void
+terminal_writec(EditLine *el, wint_t c)
+{
+ wchar_t visbuf[VISUAL_WIDTH_MAX +1];
+ ssize_t vcnt = ct_visual_char(visbuf, VISUAL_WIDTH_MAX, c);
+ if (vcnt < 0)
+ vcnt = 0;
+ visbuf[vcnt] = '\0';
+ terminal_overwrite(el, visbuf, (size_t)vcnt);
+ terminal__flush(el);
+}
+
+
+/* terminal_telltc():
+ * Print the current termcap characteristics
+ */
+libedit_private int
+/*ARGSUSED*/
+terminal_telltc(EditLine *el, int argc __attribute__((__unused__)),
+ const wchar_t **argv __attribute__((__unused__)))
+{
+ const struct termcapstr *t;
+ char **ts;
+
+ (void) fprintf(el->el_outfile, "\n\tYour terminal has the\n");
+ (void) fprintf(el->el_outfile, "\tfollowing characteristics:\n\n");
+ (void) fprintf(el->el_outfile, "\tIt has %d columns and %d lines\n",
+ Val(T_co), Val(T_li));
+ (void) fprintf(el->el_outfile,
+ "\tIt has %s meta key\n", EL_HAS_META ? "a" : "no");
+ (void) fprintf(el->el_outfile,
+ "\tIt can%suse tabs\n", EL_CAN_TAB ? " " : "not ");
+ (void) fprintf(el->el_outfile, "\tIt %s automatic margins\n",
+ EL_HAS_AUTO_MARGINS ? "has" : "does not have");
+ if (EL_HAS_AUTO_MARGINS)
+ (void) fprintf(el->el_outfile, "\tIt %s magic margins\n",
+ EL_HAS_MAGIC_MARGINS ? "has" : "does not have");
+
+ for (t = tstr, ts = el->el_terminal.t_str; t->name != NULL; t++, ts++) {
+ const char *ub;
+ if (*ts && **ts) {
+ ub = ct_encode_string(ct_visual_string(
+ ct_decode_string(*ts, &el->el_scratch),
+ &el->el_visual), &el->el_scratch);
+ } else {
+ ub = "(empty)";
+ }
+ (void) fprintf(el->el_outfile, "\t%25s (%s) == %s\n",
+ t->long_name, t->name, ub);
+ }
+ (void) fputc('\n', el->el_outfile);
+ return 0;
+}
+
+
+/* terminal_settc():
+ * Change the current terminal characteristics
+ */
+libedit_private int
+/*ARGSUSED*/
+terminal_settc(EditLine *el, int argc __attribute__((__unused__)),
+ const wchar_t **argv)
+{
+ const struct termcapstr *ts;
+ const struct termcapval *tv;
+ char what[8], how[8];
+
+ if (argv == NULL || argv[1] == NULL || argv[2] == NULL)
+ return -1;
+
+ strncpy(what, ct_encode_string(argv[1], &el->el_scratch), sizeof(what));
+ what[sizeof(what) - 1] = '\0';
+ strncpy(how, ct_encode_string(argv[2], &el->el_scratch), sizeof(how));
+ how[sizeof(how) - 1] = '\0';
+
+ /*
+ * Do the strings first
+ */
+ for (ts = tstr; ts->name != NULL; ts++)
+ if (strcmp(ts->name, what) == 0)
+ break;
+
+ if (ts->name != NULL) {
+ terminal_alloc(el, ts, how);
+ terminal_setflags(el);
+ return 0;
+ }
+ /*
+ * Do the numeric ones second
+ */
+ for (tv = tval; tv->name != NULL; tv++)
+ if (strcmp(tv->name, what) == 0)
+ break;
+
+ if (tv->name != NULL)
+ return -1;
+
+ if (tv == &tval[T_pt] || tv == &tval[T_km] ||
+ tv == &tval[T_am] || tv == &tval[T_xn]) {
+ if (strcmp(how, "yes") == 0)
+ el->el_terminal.t_val[tv - tval] = 1;
+ else if (strcmp(how, "no") == 0)
+ el->el_terminal.t_val[tv - tval] = 0;
+ else {
+ (void) fprintf(el->el_errfile,
+ "%ls: Bad value `%s'.\n", argv[0], how);
+ return -1;
+ }
+ terminal_setflags(el);
+ if (terminal_change_size(el, Val(T_li), Val(T_co)) == -1)
+ return -1;
+ return 0;
+ } else {
+ long i;
+ char *ep;
+
+ i = strtol(how, &ep, 10);
+ if (*ep != '\0') {
+ (void) fprintf(el->el_errfile,
+ "%ls: Bad value `%s'.\n", argv[0], how);
+ return -1;
+ }
+ el->el_terminal.t_val[tv - tval] = (int) i;
+ el->el_terminal.t_size.v = Val(T_co);
+ el->el_terminal.t_size.h = Val(T_li);
+ if (tv == &tval[T_co] || tv == &tval[T_li])
+ if (terminal_change_size(el, Val(T_li), Val(T_co))
+ == -1)
+ return -1;
+ return 0;
+ }
+}
+
+
+/* terminal_gettc():
+ * Get the current terminal characteristics
+ */
+libedit_private int
+/*ARGSUSED*/
+terminal_gettc(EditLine *el, int argc __attribute__((__unused__)), char **argv)
+{
+ const struct termcapstr *ts;
+ const struct termcapval *tv;
+ char *what;
+ void *how;
+
+ if (argv == NULL || argv[1] == NULL || argv[2] == NULL)
+ return -1;
+
+ what = argv[1];
+ how = argv[2];
+
+ /*
+ * Do the strings first
+ */
+ for (ts = tstr; ts->name != NULL; ts++)
+ if (strcmp(ts->name, what) == 0)
+ break;
+
+ if (ts->name != NULL) {
+ *(char **)how = el->el_terminal.t_str[ts - tstr];
+ return 0;
+ }
+ /*
+ * Do the numeric ones second
+ */
+ for (tv = tval; tv->name != NULL; tv++)
+ if (strcmp(tv->name, what) == 0)
+ break;
+
+ if (tv->name == NULL)
+ return -1;
+
+ if (tv == &tval[T_pt] || tv == &tval[T_km] ||
+ tv == &tval[T_am] || tv == &tval[T_xn]) {
+ static char yes[] = "yes";
+ static char no[] = "no";
+ if (el->el_terminal.t_val[tv - tval])
+ *(char **)how = yes;
+ else
+ *(char **)how = no;
+ return 0;
+ } else {
+ *(int *)how = el->el_terminal.t_val[tv - tval];
+ return 0;
+ }
+}
+
+/* terminal_echotc():
+ * Print the termcap string out with variable substitution
+ */
+libedit_private int
+/*ARGSUSED*/
+terminal_echotc(EditLine *el, int argc __attribute__((__unused__)),
+ const wchar_t **argv)
+{
+ char *cap, *scap;
+ wchar_t *ep;
+ int arg_need, arg_cols, arg_rows;
+ int verbose = 0, silent = 0;
+ char *area;
+ static const char fmts[] = "%s\n", fmtd[] = "%d\n";
+ const struct termcapstr *t;
+ char buf[TC_BUFSIZE];
+ long i;
+
+ area = buf;
+
+ if (argv == NULL || argv[1] == NULL)
+ return -1;
+ argv++;
+
+ if (argv[0][0] == '-') {
+ switch (argv[0][1]) {
+ case 'v':
+ verbose = 1;
+ break;
+ case 's':
+ silent = 1;
+ break;
+ default:
+ /* stderror(ERR_NAME | ERR_TCUSAGE); */
+ break;
+ }
+ argv++;
+ }
+ if (!*argv || *argv[0] == '\0')
+ return 0;
+ if (wcscmp(*argv, L"tabs") == 0) {
+ (void) fprintf(el->el_outfile, fmts, EL_CAN_TAB ? "yes" : "no");
+ return 0;
+ } else if (wcscmp(*argv, L"meta") == 0) {
+ (void) fprintf(el->el_outfile, fmts, Val(T_km) ? "yes" : "no");
+ return 0;
+ } else if (wcscmp(*argv, L"xn") == 0) {
+ (void) fprintf(el->el_outfile, fmts, EL_HAS_MAGIC_MARGINS ?
+ "yes" : "no");
+ return 0;
+ } else if (wcscmp(*argv, L"am") == 0) {
+ (void) fprintf(el->el_outfile, fmts, EL_HAS_AUTO_MARGINS ?
+ "yes" : "no");
+ return 0;
+ } else if (wcscmp(*argv, L"baud") == 0) {
+ (void) fprintf(el->el_outfile, fmtd, (int)el->el_tty.t_speed);
+ return 0;
+ } else if (wcscmp(*argv, L"rows") == 0 ||
+ wcscmp(*argv, L"lines") == 0) {
+ (void) fprintf(el->el_outfile, fmtd, Val(T_li));
+ return 0;
+ } else if (wcscmp(*argv, L"cols") == 0) {
+ (void) fprintf(el->el_outfile, fmtd, Val(T_co));
+ return 0;
+ }
+ /*
+ * Try to use our local definition first
+ */
+ scap = NULL;
+ for (t = tstr; t->name != NULL; t++)
+ if (strcmp(t->name,
+ ct_encode_string(*argv, &el->el_scratch)) == 0) {
+ scap = el->el_terminal.t_str[t - tstr];
+ break;
+ }
+ if (t->name == NULL) {
+ /* XXX: some systems' tgetstr needs non const */
+ scap = tgetstr(ct_encode_string(*argv, &el->el_scratch), &area);
+ }
+ if (!scap || scap[0] == '\0') {
+ if (!silent)
+ (void) fprintf(el->el_errfile,
+ "echotc: Termcap parameter `%ls' not found.\n",
+ *argv);
+ return -1;
+ }
+ /*
+ * Count home many values we need for this capability.
+ */
+ for (cap = scap, arg_need = 0; *cap; cap++)
+ if (*cap == '%')
+ switch (*++cap) {
+ case 'd':
+ case '2':
+ case '3':
+ case '.':
+ case '+':
+ arg_need++;
+ break;
+ case '%':
+ case '>':
+ case 'i':
+ case 'r':
+ case 'n':
+ case 'B':
+ case 'D':
+ break;
+ default:
+ /*
+ * hpux has lot's of them...
+ */
+ if (verbose)
+ (void) fprintf(el->el_errfile,
+ "echotc: Warning: unknown termcap %% `%c'.\n",
+ *cap);
+ /* This is bad, but I won't complain */
+ break;
+ }
+
+ switch (arg_need) {
+ case 0:
+ argv++;
+ if (*argv && *argv[0]) {
+ if (!silent)
+ (void) fprintf(el->el_errfile,
+ "echotc: Warning: Extra argument `%ls'.\n",
+ *argv);
+ return -1;
+ }
+ terminal_tputs(el, scap, 1);
+ break;
+ case 1:
+ argv++;
+ if (!*argv || *argv[0] == '\0') {
+ if (!silent)
+ (void) fprintf(el->el_errfile,
+ "echotc: Warning: Missing argument.\n");
+ return -1;
+ }
+ arg_cols = 0;
+ i = wcstol(*argv, &ep, 10);
+ if (*ep != '\0' || i < 0) {
+ if (!silent)
+ (void) fprintf(el->el_errfile,
+ "echotc: Bad value `%ls' for rows.\n",
+ *argv);
+ return -1;
+ }
+ arg_rows = (int) i;
+ argv++;
+ if (*argv && *argv[0]) {
+ if (!silent)
+ (void) fprintf(el->el_errfile,
+ "echotc: Warning: Extra argument `%ls"
+ "'.\n", *argv);
+ return -1;
+ }
+ terminal_tputs(el, tgoto(scap, arg_cols, arg_rows), 1);
+ break;
+ default:
+ /* This is wrong, but I will ignore it... */
+ if (verbose)
+ (void) fprintf(el->el_errfile,
+ "echotc: Warning: Too many required arguments (%d).\n",
+ arg_need);
+ /* FALLTHROUGH */
+ case 2:
+ argv++;
+ if (!*argv || *argv[0] == '\0') {
+ if (!silent)
+ (void) fprintf(el->el_errfile,
+ "echotc: Warning: Missing argument.\n");
+ return -1;
+ }
+ i = wcstol(*argv, &ep, 10);
+ if (*ep != '\0' || i < 0) {
+ if (!silent)
+ (void) fprintf(el->el_errfile,
+ "echotc: Bad value `%ls' for cols.\n",
+ *argv);
+ return -1;
+ }
+ arg_cols = (int) i;
+ argv++;
+ if (!*argv || *argv[0] == '\0') {
+ if (!silent)
+ (void) fprintf(el->el_errfile,
+ "echotc: Warning: Missing argument.\n");
+ return -1;
+ }
+ i = wcstol(*argv, &ep, 10);
+ if (*ep != '\0' || i < 0) {
+ if (!silent)
+ (void) fprintf(el->el_errfile,
+ "echotc: Bad value `%ls' for rows.\n",
+ *argv);
+ return -1;
+ }
+ arg_rows = (int) i;
+ if (*ep != '\0') {
+ if (!silent)
+ (void) fprintf(el->el_errfile,
+ "echotc: Bad value `%ls'.\n", *argv);
+ return -1;
+ }
+ argv++;
+ if (*argv && *argv[0]) {
+ if (!silent)
+ (void) fprintf(el->el_errfile,
+ "echotc: Warning: Extra argument `%ls"
+ "'.\n", *argv);
+ return -1;
+ }
+ terminal_tputs(el, tgoto(scap, arg_cols, arg_rows), arg_rows);
+ break;
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/libedit/src/terminal.h b/third_party/heimdal/lib/libedit/src/terminal.h
new file mode 100644
index 0000000..ae61beb
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/terminal.h
@@ -0,0 +1,125 @@
+/* $NetBSD: terminal.h,v 1.9 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)term.h 8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * el.term.h: Termcap header
+ */
+#ifndef _h_el_terminal
+#define _h_el_terminal
+
+typedef struct { /* Symbolic function key bindings */
+ const wchar_t *name; /* name of the key */
+ int key; /* Index in termcap table */
+ keymacro_value_t fun; /* Function bound to it */
+ int type; /* Type of function */
+} funckey_t;
+
+typedef struct {
+ const char *t_name; /* the terminal name */
+ coord_t t_size; /* # lines and cols */
+ int t_flags;
+#define TERM_CAN_INSERT 0x001 /* Has insert cap */
+#define TERM_CAN_DELETE 0x002 /* Has delete cap */
+#define TERM_CAN_CEOL 0x004 /* Has CEOL cap */
+#define TERM_CAN_TAB 0x008 /* Can use tabs */
+#define TERM_CAN_ME 0x010 /* Can turn all attrs. */
+#define TERM_CAN_UP 0x020 /* Can move up */
+#define TERM_HAS_META 0x040 /* Has a meta key */
+#define TERM_HAS_AUTO_MARGINS 0x080 /* Has auto margins */
+#define TERM_HAS_MAGIC_MARGINS 0x100 /* Has magic margins */
+ char *t_buf; /* Termcap buffer */
+ size_t t_loc; /* location used */
+ char **t_str; /* termcap strings */
+ int *t_val; /* termcap values */
+ char *t_cap; /* Termcap buffer */
+ funckey_t *t_fkey; /* Array of keys */
+} el_terminal_t;
+
+/*
+ * fKey indexes
+ */
+#define A_K_DN 0
+#define A_K_UP 1
+#define A_K_LT 2
+#define A_K_RT 3
+#define A_K_HO 4
+#define A_K_EN 5
+#define A_K_DE 6
+#define A_K_NKEYS 7
+
+libedit_private void terminal_move_to_line(EditLine *, int);
+libedit_private void terminal_move_to_char(EditLine *, int);
+libedit_private void terminal_clear_EOL(EditLine *, int);
+libedit_private void terminal_overwrite(EditLine *, const wchar_t *, size_t);
+libedit_private void terminal_insertwrite(EditLine *, wchar_t *, int);
+libedit_private void terminal_deletechars(EditLine *, int);
+libedit_private void terminal_clear_screen(EditLine *);
+libedit_private void terminal_beep(EditLine *);
+libedit_private int terminal_change_size(EditLine *, int, int);
+libedit_private int terminal_get_size(EditLine *, int *, int *);
+libedit_private int terminal_init(EditLine *);
+libedit_private void terminal_bind_arrow(EditLine *);
+libedit_private void terminal_print_arrow(EditLine *, const wchar_t *);
+libedit_private int terminal_clear_arrow(EditLine *, const wchar_t *);
+libedit_private int terminal_set_arrow(EditLine *, const wchar_t *,
+ keymacro_value_t *, int);
+libedit_private void terminal_end(EditLine *);
+libedit_private void terminal_get(EditLine *, const char **);
+libedit_private int terminal_set(EditLine *, const char *);
+libedit_private int terminal_settc(EditLine *, int, const wchar_t **);
+libedit_private int terminal_gettc(EditLine *, int, char **);
+libedit_private int terminal_telltc(EditLine *, int, const wchar_t **);
+libedit_private int terminal_echotc(EditLine *, int, const wchar_t **);
+libedit_private void terminal_writec(EditLine *, wint_t);
+libedit_private int terminal__putc(EditLine *, wint_t);
+libedit_private void terminal__flush(EditLine *);
+
+/*
+ * Easy access macros
+ */
+#define EL_FLAGS (el)->el_terminal.t_flags
+
+#define EL_CAN_INSERT (EL_FLAGS & TERM_CAN_INSERT)
+#define EL_CAN_DELETE (EL_FLAGS & TERM_CAN_DELETE)
+#define EL_CAN_CEOL (EL_FLAGS & TERM_CAN_CEOL)
+#define EL_CAN_TAB (EL_FLAGS & TERM_CAN_TAB)
+#define EL_CAN_ME (EL_FLAGS & TERM_CAN_ME)
+#define EL_CAN_UP (EL_FLAGS & TERM_CAN_UP)
+#define EL_HAS_META (EL_FLAGS & TERM_HAS_META)
+#define EL_HAS_AUTO_MARGINS (EL_FLAGS & TERM_HAS_AUTO_MARGINS)
+#define EL_HAS_MAGIC_MARGINS (EL_FLAGS & TERM_HAS_MAGIC_MARGINS)
+
+#endif /* _h_el_terminal */
diff --git a/third_party/heimdal/lib/libedit/src/tokenizer.c b/third_party/heimdal/lib/libedit/src/tokenizer.c
new file mode 100644
index 0000000..1853224
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/tokenizer.c
@@ -0,0 +1,466 @@
+/* $NetBSD: tokenizer.c,v 1.28 2016/04/11 18:56:31 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)tokenizer.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: tokenizer.c,v 1.28 2016/04/11 18:56:31 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/* We build this file twice, once as NARROW, once as WIDE. */
+/*
+ * tokenize.c: Bourne shell like tokenizer
+ */
+#include <stdlib.h>
+#include <string.h>
+
+#include "histedit.h"
+
+typedef enum {
+ Q_none, Q_single, Q_double, Q_one, Q_doubleone
+} quote_t;
+
+#define TOK_KEEP 1
+#define TOK_EAT 2
+
+#define WINCR 20
+#define AINCR 10
+
+#define IFS STR("\t \n")
+
+#define tok_malloc(a) malloc(a)
+#define tok_free(a) free(a)
+#define tok_realloc(a, b) realloc(a, b)
+
+#ifdef NARROWCHAR
+#define Char char
+#define FUN(prefix, rest) prefix ## _ ## rest
+#define TYPE(type) type
+#define STR(x) x
+#define Strchr(s, c) strchr(s, c)
+#define tok_strdup(s) strdup(s)
+#else
+#define Char wchar_t
+#define FUN(prefix, rest) prefix ## _w ## rest
+#define TYPE(type) type ## W
+#define STR(x) L ## x
+#define Strchr(s, c) wcschr(s, c)
+#define tok_strdup(s) wcsdup(s)
+#endif
+
+struct TYPE(tokenizer) {
+ Char *ifs; /* In field separator */
+ size_t argc, amax; /* Current and maximum number of args */
+ Char **argv; /* Argument list */
+ Char *wptr, *wmax; /* Space and limit on the word buffer */
+ Char *wstart; /* Beginning of next word */
+ Char *wspace; /* Space of word buffer */
+ quote_t quote; /* Quoting state */
+ int flags; /* flags; */
+};
+
+
+static void FUN(tok,finish)(TYPE(Tokenizer) *);
+
+
+/* FUN(tok,finish)():
+ * Finish a word in the tokenizer.
+ */
+static void
+FUN(tok,finish)(TYPE(Tokenizer) *tok)
+{
+
+ *tok->wptr = '\0';
+ if ((tok->flags & TOK_KEEP) || tok->wptr != tok->wstart) {
+ tok->argv[tok->argc++] = tok->wstart;
+ tok->argv[tok->argc] = NULL;
+ tok->wstart = ++tok->wptr;
+ }
+ tok->flags &= ~TOK_KEEP;
+}
+
+
+/* FUN(tok,init)():
+ * Initialize the tokenizer
+ */
+TYPE(Tokenizer) *
+FUN(tok,init)(const Char *ifs)
+{
+ TYPE(Tokenizer) *tok = tok_malloc(sizeof(*tok));
+
+ if (tok == NULL)
+ return NULL;
+ tok->ifs = tok_strdup(ifs ? ifs : IFS);
+ if (tok->ifs == NULL) {
+ tok_free(tok);
+ return NULL;
+ }
+ tok->argc = 0;
+ tok->amax = AINCR;
+ tok->argv = tok_malloc(sizeof(*tok->argv) * tok->amax);
+ if (tok->argv == NULL) {
+ tok_free(tok->ifs);
+ tok_free(tok);
+ return NULL;
+ }
+ tok->argv[0] = NULL;
+ tok->wspace = tok_malloc(WINCR * sizeof(*tok->wspace));
+ if (tok->wspace == NULL) {
+ tok_free(tok->argv);
+ tok_free(tok->ifs);
+ tok_free(tok);
+ return NULL;
+ }
+ tok->wmax = tok->wspace + WINCR;
+ tok->wstart = tok->wspace;
+ tok->wptr = tok->wspace;
+ tok->flags = 0;
+ tok->quote = Q_none;
+
+ return tok;
+}
+
+
+/* FUN(tok,reset)():
+ * Reset the tokenizer
+ */
+void
+FUN(tok,reset)(TYPE(Tokenizer) *tok)
+{
+
+ tok->argc = 0;
+ tok->wstart = tok->wspace;
+ tok->wptr = tok->wspace;
+ tok->flags = 0;
+ tok->quote = Q_none;
+}
+
+
+/* FUN(tok,end)():
+ * Clean up
+ */
+void
+FUN(tok,end)(TYPE(Tokenizer) *tok)
+{
+
+ tok_free(tok->ifs);
+ tok_free(tok->wspace);
+ tok_free(tok->argv);
+ tok_free(tok);
+}
+
+
+
+/* FUN(tok,line)():
+ * Bourne shell (sh(1)) like tokenizing
+ * Arguments:
+ * tok current tokenizer state (setup with FUN(tok,init)())
+ * line line to parse
+ * Returns:
+ * -1 Internal error
+ * 3 Quoted return
+ * 2 Unmatched double quote
+ * 1 Unmatched single quote
+ * 0 Ok
+ * Modifies (if return value is 0):
+ * argc number of arguments
+ * argv argument array
+ * cursorc if !NULL, argv element containing cursor
+ * cursorv if !NULL, offset in argv[cursorc] of cursor
+ */
+int
+FUN(tok,line)(TYPE(Tokenizer) *tok, const TYPE(LineInfo) *line,
+ int *argc, const Char ***argv, int *cursorc, int *cursoro)
+{
+ const Char *ptr;
+ int cc, co;
+
+ cc = co = -1;
+ ptr = line->buffer;
+ for (ptr = line->buffer; ;ptr++) {
+ if (ptr >= line->lastchar)
+ ptr = STR("");
+ if (ptr == line->cursor) {
+ cc = (int)tok->argc;
+ co = (int)(tok->wptr - tok->wstart);
+ }
+ switch (*ptr) {
+ case '\'':
+ tok->flags |= TOK_KEEP;
+ tok->flags &= ~TOK_EAT;
+ switch (tok->quote) {
+ case Q_none:
+ tok->quote = Q_single; /* Enter single quote
+ * mode */
+ break;
+
+ case Q_single: /* Exit single quote mode */
+ tok->quote = Q_none;
+ break;
+
+ case Q_one: /* Quote this ' */
+ tok->quote = Q_none;
+ *tok->wptr++ = *ptr;
+ break;
+
+ case Q_double: /* Stay in double quote mode */
+ *tok->wptr++ = *ptr;
+ break;
+
+ case Q_doubleone: /* Quote this ' */
+ tok->quote = Q_double;
+ *tok->wptr++ = *ptr;
+ break;
+
+ default:
+ return -1;
+ }
+ break;
+
+ case '"':
+ tok->flags &= ~TOK_EAT;
+ tok->flags |= TOK_KEEP;
+ switch (tok->quote) {
+ case Q_none: /* Enter double quote mode */
+ tok->quote = Q_double;
+ break;
+
+ case Q_double: /* Exit double quote mode */
+ tok->quote = Q_none;
+ break;
+
+ case Q_one: /* Quote this " */
+ tok->quote = Q_none;
+ *tok->wptr++ = *ptr;
+ break;
+
+ case Q_single: /* Stay in single quote mode */
+ *tok->wptr++ = *ptr;
+ break;
+
+ case Q_doubleone: /* Quote this " */
+ tok->quote = Q_double;
+ *tok->wptr++ = *ptr;
+ break;
+
+ default:
+ return -1;
+ }
+ break;
+
+ case '\\':
+ tok->flags |= TOK_KEEP;
+ tok->flags &= ~TOK_EAT;
+ switch (tok->quote) {
+ case Q_none: /* Quote next character */
+ tok->quote = Q_one;
+ break;
+
+ case Q_double: /* Quote next character */
+ tok->quote = Q_doubleone;
+ break;
+
+ case Q_one: /* Quote this, restore state */
+ *tok->wptr++ = *ptr;
+ tok->quote = Q_none;
+ break;
+
+ case Q_single: /* Stay in single quote mode */
+ *tok->wptr++ = *ptr;
+ break;
+
+ case Q_doubleone: /* Quote this \ */
+ tok->quote = Q_double;
+ *tok->wptr++ = *ptr;
+ break;
+
+ default:
+ return -1;
+ }
+ break;
+
+ case '\n':
+ tok->flags &= ~TOK_EAT;
+ switch (tok->quote) {
+ case Q_none:
+ goto tok_line_outok;
+
+ case Q_single:
+ case Q_double:
+ *tok->wptr++ = *ptr; /* Add the return */
+ break;
+
+ case Q_doubleone: /* Back to double, eat the '\n' */
+ tok->flags |= TOK_EAT;
+ tok->quote = Q_double;
+ break;
+
+ case Q_one: /* No quote, more eat the '\n' */
+ tok->flags |= TOK_EAT;
+ tok->quote = Q_none;
+ break;
+
+ default:
+ return 0;
+ }
+ break;
+
+ case '\0':
+ switch (tok->quote) {
+ case Q_none:
+ /* Finish word and return */
+ if (tok->flags & TOK_EAT) {
+ tok->flags &= ~TOK_EAT;
+ return 3;
+ }
+ goto tok_line_outok;
+
+ case Q_single:
+ return 1;
+
+ case Q_double:
+ return 2;
+
+ case Q_doubleone:
+ tok->quote = Q_double;
+ *tok->wptr++ = *ptr;
+ break;
+
+ case Q_one:
+ tok->quote = Q_none;
+ *tok->wptr++ = *ptr;
+ break;
+
+ default:
+ return -1;
+ }
+ break;
+
+ default:
+ tok->flags &= ~TOK_EAT;
+ switch (tok->quote) {
+ case Q_none:
+ if (Strchr(tok->ifs, *ptr) != NULL)
+ FUN(tok,finish)(tok);
+ else
+ *tok->wptr++ = *ptr;
+ break;
+
+ case Q_single:
+ case Q_double:
+ *tok->wptr++ = *ptr;
+ break;
+
+
+ case Q_doubleone:
+ *tok->wptr++ = '\\';
+ tok->quote = Q_double;
+ *tok->wptr++ = *ptr;
+ break;
+
+ case Q_one:
+ tok->quote = Q_none;
+ *tok->wptr++ = *ptr;
+ break;
+
+ default:
+ return -1;
+
+ }
+ break;
+ }
+
+ if (tok->wptr >= tok->wmax - 4) {
+ size_t size = (size_t)(tok->wmax - tok->wspace + WINCR);
+ Char *s = tok_realloc(tok->wspace,
+ size * sizeof(*s));
+ if (s == NULL)
+ return -1;
+
+ if (s != tok->wspace) {
+ size_t i;
+ for (i = 0; i < tok->argc; i++) {
+ tok->argv[i] =
+ (tok->argv[i] - tok->wspace) + s;
+ }
+ tok->wptr = (tok->wptr - tok->wspace) + s;
+ tok->wstart = (tok->wstart - tok->wspace) + s;
+ tok->wspace = s;
+ }
+ tok->wmax = s + size;
+ }
+ if (tok->argc >= tok->amax - 4) {
+ Char **p;
+ tok->amax += AINCR;
+ p = tok_realloc(tok->argv, tok->amax * sizeof(*p));
+ if (p == NULL) {
+ tok->amax -= AINCR;
+ return -1;
+ }
+ tok->argv = p;
+ }
+ }
+ tok_line_outok:
+ if (cc == -1 && co == -1) {
+ cc = (int)tok->argc;
+ co = (int)(tok->wptr - tok->wstart);
+ }
+ if (cursorc != NULL)
+ *cursorc = cc;
+ if (cursoro != NULL)
+ *cursoro = co;
+ FUN(tok,finish)(tok);
+ *argv = (const Char **)tok->argv;
+ *argc = (int)tok->argc;
+ return 0;
+}
+
+/* FUN(tok,str)():
+ * Simpler version of tok_line, taking a NUL terminated line
+ * and splitting into words, ignoring cursor state.
+ */
+int
+FUN(tok,str)(TYPE(Tokenizer) *tok, const Char *line, int *argc,
+ const Char ***argv)
+{
+ TYPE(LineInfo) li;
+
+ memset(&li, 0, sizeof(li));
+ li.buffer = line;
+ li.cursor = li.lastchar = Strchr(line, '\0');
+ return FUN(tok,line)(tok, &li, argc, argv, NULL, NULL);
+}
diff --git a/third_party/heimdal/lib/libedit/src/tokenizern.c b/third_party/heimdal/lib/libedit/src/tokenizern.c
new file mode 100644
index 0000000..5846b60
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/tokenizern.c
@@ -0,0 +1,3 @@
+#include "config.h"
+#define NARROWCHAR
+#include "tokenizer.c"
diff --git a/third_party/heimdal/lib/libedit/src/tty.c b/third_party/heimdal/lib/libedit/src/tty.c
new file mode 100644
index 0000000..f524da4
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/tty.c
@@ -0,0 +1,1342 @@
+/* $NetBSD: tty.c,v 1.65 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)tty.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: tty.c,v 1.65 2016/05/09 21:46:56 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * tty.c: tty interface stuff
+ */
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h> /* for abort */
+#include <string.h>
+#include <strings.h> /* for ffs */
+#include <unistd.h> /* for isatty */
+
+#include "el.h"
+#include "fcns.h"
+#include "parse.h"
+
+typedef struct ttymodes_t {
+ const char *m_name;
+ unsigned int m_value;
+ int m_type;
+} ttymodes_t;
+
+typedef struct ttymap_t {
+ wint_t nch, och; /* Internal and termio rep of chars */
+ el_action_t bind[3]; /* emacs, vi, and vi-cmd */
+} ttymap_t;
+
+
+static const ttyperm_t ttyperm = {
+ {
+ {"iflag:", ICRNL, (INLCR | IGNCR)},
+ {"oflag:", (OPOST | ONLCR), ONLRET},
+ {"cflag:", 0, 0},
+ {"lflag:", (ISIG | ICANON | ECHO | ECHOE | ECHOCTL | IEXTEN),
+ (NOFLSH | ECHONL | EXTPROC | FLUSHO)},
+ {"chars:", 0, 0},
+ },
+ {
+ {"iflag:", (INLCR | ICRNL), IGNCR},
+ {"oflag:", (OPOST | ONLCR), ONLRET},
+ {"cflag:", 0, 0},
+ {"lflag:", ISIG,
+ (NOFLSH | ICANON | ECHO | ECHOK | ECHONL | EXTPROC | IEXTEN | FLUSHO)},
+ {"chars:", (C_SH(C_MIN) | C_SH(C_TIME) | C_SH(C_SWTCH) | C_SH(C_DSWTCH) |
+ C_SH(C_SUSP) | C_SH(C_DSUSP) | C_SH(C_EOL) | C_SH(C_DISCARD) |
+ C_SH(C_PGOFF) | C_SH(C_PAGE) | C_SH(C_STATUS)), 0}
+ },
+ {
+ {"iflag:", 0, IXON | IXOFF | INLCR | ICRNL},
+ {"oflag:", 0, 0},
+ {"cflag:", 0, 0},
+ {"lflag:", 0, ISIG | IEXTEN},
+ {"chars:", 0, 0},
+ }
+};
+
+static const ttychar_t ttychar = {
+ {
+ CINTR, CQUIT, CERASE, CKILL,
+ CEOF, CEOL, CEOL2, CSWTCH,
+ CDSWTCH, CERASE2, CSTART, CSTOP,
+ CWERASE, CSUSP, CDSUSP, CREPRINT,
+ CDISCARD, CLNEXT, CSTATUS, CPAGE,
+ CPGOFF, CKILL2, CBRK, CMIN,
+ CTIME
+ },
+ {
+ CINTR, CQUIT, CERASE, CKILL,
+ _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE,
+ _POSIX_VDISABLE, CERASE2, CSTART, CSTOP,
+ _POSIX_VDISABLE, CSUSP, _POSIX_VDISABLE, _POSIX_VDISABLE,
+ CDISCARD, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE,
+ _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, 1,
+ 0
+ },
+ {
+ 0, 0, 0, 0,
+ 0, 0, 0, 0,
+ 0, 0, 0, 0,
+ 0, 0, 0, 0,
+ 0, 0, 0, 0,
+ 0, 0, 0, 0,
+ 0
+ }
+};
+
+static const ttymap_t tty_map[] = {
+#ifdef VERASE
+ {C_ERASE, VERASE,
+ {EM_DELETE_PREV_CHAR, VI_DELETE_PREV_CHAR, ED_PREV_CHAR}},
+#endif /* VERASE */
+#ifdef VERASE2
+ {C_ERASE2, VERASE2,
+ {EM_DELETE_PREV_CHAR, VI_DELETE_PREV_CHAR, ED_PREV_CHAR}},
+#endif /* VERASE2 */
+#ifdef VKILL
+ {C_KILL, VKILL,
+ {EM_KILL_LINE, VI_KILL_LINE_PREV, ED_UNASSIGNED}},
+#endif /* VKILL */
+#ifdef VKILL2
+ {C_KILL2, VKILL2,
+ {EM_KILL_LINE, VI_KILL_LINE_PREV, ED_UNASSIGNED}},
+#endif /* VKILL2 */
+#ifdef VEOF
+ {C_EOF, VEOF,
+ {EM_DELETE_OR_LIST, VI_LIST_OR_EOF, ED_UNASSIGNED}},
+#endif /* VEOF */
+#ifdef VWERASE
+ {C_WERASE, VWERASE,
+ {ED_DELETE_PREV_WORD, ED_DELETE_PREV_WORD, ED_PREV_WORD}},
+#endif /* VWERASE */
+#ifdef VREPRINT
+ {C_REPRINT, VREPRINT,
+ {ED_REDISPLAY, ED_INSERT, ED_REDISPLAY}},
+#endif /* VREPRINT */
+#ifdef VLNEXT
+ {C_LNEXT, VLNEXT,
+ {ED_QUOTED_INSERT, ED_QUOTED_INSERT, ED_UNASSIGNED}},
+#endif /* VLNEXT */
+ {(wint_t)-1, (wint_t)-1,
+ {ED_UNASSIGNED, ED_UNASSIGNED, ED_UNASSIGNED}}
+};
+
+static const ttymodes_t ttymodes[] = {
+#ifdef IGNBRK
+ {"ignbrk", IGNBRK, MD_INP},
+#endif /* IGNBRK */
+#ifdef BRKINT
+ {"brkint", BRKINT, MD_INP},
+#endif /* BRKINT */
+#ifdef IGNPAR
+ {"ignpar", IGNPAR, MD_INP},
+#endif /* IGNPAR */
+#ifdef PARMRK
+ {"parmrk", PARMRK, MD_INP},
+#endif /* PARMRK */
+#ifdef INPCK
+ {"inpck", INPCK, MD_INP},
+#endif /* INPCK */
+#ifdef ISTRIP
+ {"istrip", ISTRIP, MD_INP},
+#endif /* ISTRIP */
+#ifdef INLCR
+ {"inlcr", INLCR, MD_INP},
+#endif /* INLCR */
+#ifdef IGNCR
+ {"igncr", IGNCR, MD_INP},
+#endif /* IGNCR */
+#ifdef ICRNL
+ {"icrnl", ICRNL, MD_INP},
+#endif /* ICRNL */
+#ifdef IUCLC
+ {"iuclc", IUCLC, MD_INP},
+#endif /* IUCLC */
+#ifdef IXON
+ {"ixon", IXON, MD_INP},
+#endif /* IXON */
+#ifdef IXANY
+ {"ixany", IXANY, MD_INP},
+#endif /* IXANY */
+#ifdef IXOFF
+ {"ixoff", IXOFF, MD_INP},
+#endif /* IXOFF */
+#ifdef IMAXBEL
+ {"imaxbel", IMAXBEL, MD_INP},
+#endif /* IMAXBEL */
+
+#ifdef OPOST
+ {"opost", OPOST, MD_OUT},
+#endif /* OPOST */
+#ifdef OLCUC
+ {"olcuc", OLCUC, MD_OUT},
+#endif /* OLCUC */
+#ifdef ONLCR
+ {"onlcr", ONLCR, MD_OUT},
+#endif /* ONLCR */
+#ifdef OCRNL
+ {"ocrnl", OCRNL, MD_OUT},
+#endif /* OCRNL */
+#ifdef ONOCR
+ {"onocr", ONOCR, MD_OUT},
+#endif /* ONOCR */
+#ifdef ONOEOT
+ {"onoeot", ONOEOT, MD_OUT},
+#endif /* ONOEOT */
+#ifdef ONLRET
+ {"onlret", ONLRET, MD_OUT},
+#endif /* ONLRET */
+#ifdef OFILL
+ {"ofill", OFILL, MD_OUT},
+#endif /* OFILL */
+#ifdef OFDEL
+ {"ofdel", OFDEL, MD_OUT},
+#endif /* OFDEL */
+#ifdef NLDLY
+ {"nldly", NLDLY, MD_OUT},
+#endif /* NLDLY */
+#ifdef CRDLY
+ {"crdly", CRDLY, MD_OUT},
+#endif /* CRDLY */
+#ifdef TABDLY
+ {"tabdly", TABDLY, MD_OUT},
+#endif /* TABDLY */
+#ifdef XTABS
+ {"xtabs", XTABS, MD_OUT},
+#endif /* XTABS */
+#ifdef BSDLY
+ {"bsdly", BSDLY, MD_OUT},
+#endif /* BSDLY */
+#ifdef VTDLY
+ {"vtdly", VTDLY, MD_OUT},
+#endif /* VTDLY */
+#ifdef FFDLY
+ {"ffdly", FFDLY, MD_OUT},
+#endif /* FFDLY */
+#ifdef PAGEOUT
+ {"pageout", PAGEOUT, MD_OUT},
+#endif /* PAGEOUT */
+#ifdef WRAP
+ {"wrap", WRAP, MD_OUT},
+#endif /* WRAP */
+
+#ifdef CIGNORE
+ {"cignore", CIGNORE, MD_CTL},
+#endif /* CBAUD */
+#ifdef CBAUD
+ {"cbaud", CBAUD, MD_CTL},
+#endif /* CBAUD */
+#ifdef CSTOPB
+ {"cstopb", CSTOPB, MD_CTL},
+#endif /* CSTOPB */
+#ifdef CREAD
+ {"cread", CREAD, MD_CTL},
+#endif /* CREAD */
+#ifdef PARENB
+ {"parenb", PARENB, MD_CTL},
+#endif /* PARENB */
+#ifdef PARODD
+ {"parodd", PARODD, MD_CTL},
+#endif /* PARODD */
+#ifdef HUPCL
+ {"hupcl", HUPCL, MD_CTL},
+#endif /* HUPCL */
+#ifdef CLOCAL
+ {"clocal", CLOCAL, MD_CTL},
+#endif /* CLOCAL */
+#ifdef LOBLK
+ {"loblk", LOBLK, MD_CTL},
+#endif /* LOBLK */
+#ifdef CIBAUD
+ {"cibaud", CIBAUD, MD_CTL},
+#endif /* CIBAUD */
+#ifdef CRTSCTS
+#ifdef CCTS_OFLOW
+ {"ccts_oflow", CCTS_OFLOW, MD_CTL},
+#else
+ {"crtscts", CRTSCTS, MD_CTL},
+#endif /* CCTS_OFLOW */
+#endif /* CRTSCTS */
+#ifdef CRTS_IFLOW
+ {"crts_iflow", CRTS_IFLOW, MD_CTL},
+#endif /* CRTS_IFLOW */
+#ifdef CDTRCTS
+ {"cdtrcts", CDTRCTS, MD_CTL},
+#endif /* CDTRCTS */
+#ifdef MDMBUF
+ {"mdmbuf", MDMBUF, MD_CTL},
+#endif /* MDMBUF */
+#ifdef RCV1EN
+ {"rcv1en", RCV1EN, MD_CTL},
+#endif /* RCV1EN */
+#ifdef XMT1EN
+ {"xmt1en", XMT1EN, MD_CTL},
+#endif /* XMT1EN */
+
+#ifdef ISIG
+ {"isig", ISIG, MD_LIN},
+#endif /* ISIG */
+#ifdef ICANON
+ {"icanon", ICANON, MD_LIN},
+#endif /* ICANON */
+#ifdef XCASE
+ {"xcase", XCASE, MD_LIN},
+#endif /* XCASE */
+#ifdef ECHO
+ {"echo", ECHO, MD_LIN},
+#endif /* ECHO */
+#ifdef ECHOE
+ {"echoe", ECHOE, MD_LIN},
+#endif /* ECHOE */
+#ifdef ECHOK
+ {"echok", ECHOK, MD_LIN},
+#endif /* ECHOK */
+#ifdef ECHONL
+ {"echonl", ECHONL, MD_LIN},
+#endif /* ECHONL */
+#ifdef NOFLSH
+ {"noflsh", NOFLSH, MD_LIN},
+#endif /* NOFLSH */
+#ifdef TOSTOP
+ {"tostop", TOSTOP, MD_LIN},
+#endif /* TOSTOP */
+#ifdef ECHOCTL
+ {"echoctl", ECHOCTL, MD_LIN},
+#endif /* ECHOCTL */
+#ifdef ECHOPRT
+ {"echoprt", ECHOPRT, MD_LIN},
+#endif /* ECHOPRT */
+#ifdef ECHOKE
+ {"echoke", ECHOKE, MD_LIN},
+#endif /* ECHOKE */
+#ifdef DEFECHO
+ {"defecho", DEFECHO, MD_LIN},
+#endif /* DEFECHO */
+#ifdef FLUSHO
+ {"flusho", FLUSHO, MD_LIN},
+#endif /* FLUSHO */
+#ifdef PENDIN
+ {"pendin", PENDIN, MD_LIN},
+#endif /* PENDIN */
+#ifdef IEXTEN
+ {"iexten", IEXTEN, MD_LIN},
+#endif /* IEXTEN */
+#ifdef NOKERNINFO
+ {"nokerninfo", NOKERNINFO, MD_LIN},
+#endif /* NOKERNINFO */
+#ifdef ALTWERASE
+ {"altwerase", ALTWERASE, MD_LIN},
+#endif /* ALTWERASE */
+#ifdef EXTPROC
+ {"extproc", EXTPROC, MD_LIN},
+#endif /* EXTPROC */
+
+#if defined(VINTR)
+ {"intr", C_SH(C_INTR), MD_CHAR},
+#endif /* VINTR */
+#if defined(VQUIT)
+ {"quit", C_SH(C_QUIT), MD_CHAR},
+#endif /* VQUIT */
+#if defined(VERASE)
+ {"erase", C_SH(C_ERASE), MD_CHAR},
+#endif /* VERASE */
+#if defined(VKILL)
+ {"kill", C_SH(C_KILL), MD_CHAR},
+#endif /* VKILL */
+#if defined(VEOF)
+ {"eof", C_SH(C_EOF), MD_CHAR},
+#endif /* VEOF */
+#if defined(VEOL)
+ {"eol", C_SH(C_EOL), MD_CHAR},
+#endif /* VEOL */
+#if defined(VEOL2)
+ {"eol2", C_SH(C_EOL2), MD_CHAR},
+#endif /* VEOL2 */
+#if defined(VSWTCH)
+ {"swtch", C_SH(C_SWTCH), MD_CHAR},
+#endif /* VSWTCH */
+#if defined(VDSWTCH)
+ {"dswtch", C_SH(C_DSWTCH), MD_CHAR},
+#endif /* VDSWTCH */
+#if defined(VERASE2)
+ {"erase2", C_SH(C_ERASE2), MD_CHAR},
+#endif /* VERASE2 */
+#if defined(VSTART)
+ {"start", C_SH(C_START), MD_CHAR},
+#endif /* VSTART */
+#if defined(VSTOP)
+ {"stop", C_SH(C_STOP), MD_CHAR},
+#endif /* VSTOP */
+#if defined(VWERASE)
+ {"werase", C_SH(C_WERASE), MD_CHAR},
+#endif /* VWERASE */
+#if defined(VSUSP)
+ {"susp", C_SH(C_SUSP), MD_CHAR},
+#endif /* VSUSP */
+#if defined(VDSUSP)
+ {"dsusp", C_SH(C_DSUSP), MD_CHAR},
+#endif /* VDSUSP */
+#if defined(VREPRINT)
+ {"reprint", C_SH(C_REPRINT), MD_CHAR},
+#endif /* VREPRINT */
+#if defined(VDISCARD)
+ {"discard", C_SH(C_DISCARD), MD_CHAR},
+#endif /* VDISCARD */
+#if defined(VLNEXT)
+ {"lnext", C_SH(C_LNEXT), MD_CHAR},
+#endif /* VLNEXT */
+#if defined(VSTATUS)
+ {"status", C_SH(C_STATUS), MD_CHAR},
+#endif /* VSTATUS */
+#if defined(VPAGE)
+ {"page", C_SH(C_PAGE), MD_CHAR},
+#endif /* VPAGE */
+#if defined(VPGOFF)
+ {"pgoff", C_SH(C_PGOFF), MD_CHAR},
+#endif /* VPGOFF */
+#if defined(VKILL2)
+ {"kill2", C_SH(C_KILL2), MD_CHAR},
+#endif /* VKILL2 */
+#if defined(VBRK)
+ {"brk", C_SH(C_BRK), MD_CHAR},
+#endif /* VBRK */
+#if defined(VMIN)
+ {"min", C_SH(C_MIN), MD_CHAR},
+#endif /* VMIN */
+#if defined(VTIME)
+ {"time", C_SH(C_TIME), MD_CHAR},
+#endif /* VTIME */
+ {NULL, 0, -1},
+};
+
+
+
+#define tty__gettabs(td) ((((td)->c_oflag & TAB3) == TAB3) ? 0 : 1)
+#define tty__geteightbit(td) (((td)->c_cflag & CSIZE) == CS8)
+#define tty__cooked_mode(td) ((td)->c_lflag & ICANON)
+
+static int tty_getty(EditLine *, struct termios *);
+static int tty_setty(EditLine *, int, const struct termios *);
+static int tty__getcharindex(int);
+static void tty__getchar(struct termios *, unsigned char *);
+static void tty__setchar(struct termios *, unsigned char *);
+static speed_t tty__getspeed(struct termios *);
+static int tty_setup(EditLine *);
+static void tty_setup_flags(EditLine *, struct termios *, int);
+
+#define t_qu t_ts
+
+/* tty_getty():
+ * Wrapper for tcgetattr to handle EINTR
+ */
+static int
+tty_getty(EditLine *el, struct termios *t)
+{
+ int rv;
+ while ((rv = tcgetattr(el->el_infd, t)) == -1 && errno == EINTR)
+ continue;
+ return rv;
+}
+
+/* tty_setty():
+ * Wrapper for tcsetattr to handle EINTR
+ */
+static int
+tty_setty(EditLine *el, int action, const struct termios *t)
+{
+ int rv;
+ while ((rv = tcsetattr(el->el_infd, action, t)) == -1 && errno == EINTR)
+ continue;
+ return rv;
+}
+
+/* tty_setup():
+ * Get the tty parameters and initialize the editing state
+ */
+static int
+tty_setup(EditLine *el)
+{
+ int rst = 1;
+
+ if (el->el_flags & EDIT_DISABLED)
+ return 0;
+
+ if (el->el_tty.t_initialized)
+ return -1;
+
+ if (!isatty(el->el_outfd)) {
+#ifdef DEBUG_TTY
+ (void) fprintf(el->el_errfile, "%s: isatty: %s\n", __func__,
+ strerror(errno));
+#endif /* DEBUG_TTY */
+ return -1;
+ }
+ if (tty_getty(el, &el->el_tty.t_or) == -1) {
+#ifdef DEBUG_TTY
+ (void) fprintf(el->el_errfile, "%s: tty_getty: %s\n", __func__,
+ strerror(errno));
+#endif /* DEBUG_TTY */
+ return -1;
+ }
+ el->el_tty.t_ts = el->el_tty.t_ex = el->el_tty.t_ed = el->el_tty.t_or;
+
+ el->el_tty.t_speed = tty__getspeed(&el->el_tty.t_ex);
+ el->el_tty.t_tabs = tty__gettabs(&el->el_tty.t_ex);
+ el->el_tty.t_eight = tty__geteightbit(&el->el_tty.t_ex);
+
+ tty_setup_flags(el, &el->el_tty.t_ex, EX_IO);
+
+ /*
+ * Reset the tty chars to reasonable defaults
+ * If they are disabled, then enable them.
+ */
+ if (rst) {
+ if (tty__cooked_mode(&el->el_tty.t_ts)) {
+ tty__getchar(&el->el_tty.t_ts, el->el_tty.t_c[TS_IO]);
+ /*
+ * Don't affect CMIN and CTIME for the editor mode
+ */
+ for (rst = 0; rst < C_NCC - 2; rst++)
+ if (el->el_tty.t_c[TS_IO][rst] !=
+ el->el_tty.t_vdisable
+ && el->el_tty.t_c[ED_IO][rst] !=
+ el->el_tty.t_vdisable)
+ el->el_tty.t_c[ED_IO][rst] =
+ el->el_tty.t_c[TS_IO][rst];
+ for (rst = 0; rst < C_NCC; rst++)
+ if (el->el_tty.t_c[TS_IO][rst] !=
+ el->el_tty.t_vdisable)
+ el->el_tty.t_c[EX_IO][rst] =
+ el->el_tty.t_c[TS_IO][rst];
+ }
+ tty__setchar(&el->el_tty.t_ex, el->el_tty.t_c[EX_IO]);
+ if (tty_setty(el, TCSADRAIN, &el->el_tty.t_ex) == -1) {
+#ifdef DEBUG_TTY
+ (void) fprintf(el->el_errfile, "%s: tty_setty: %s\n",
+ __func__, strerror(errno));
+#endif /* DEBUG_TTY */
+ return -1;
+ }
+ }
+
+ tty_setup_flags(el, &el->el_tty.t_ed, ED_IO);
+
+ tty__setchar(&el->el_tty.t_ed, el->el_tty.t_c[ED_IO]);
+ tty_bind_char(el, 1);
+ el->el_tty.t_initialized = 1;
+ return 0;
+}
+
+libedit_private int
+tty_init(EditLine *el)
+{
+
+ el->el_tty.t_mode = EX_IO;
+ el->el_tty.t_vdisable = _POSIX_VDISABLE;
+ el->el_tty.t_initialized = 0;
+ (void) memcpy(el->el_tty.t_t, ttyperm, sizeof(ttyperm_t));
+ (void) memcpy(el->el_tty.t_c, ttychar, sizeof(ttychar_t));
+ return tty_setup(el);
+}
+
+
+/* tty_end():
+ * Restore the tty to its original settings
+ */
+libedit_private void
+/*ARGSUSED*/
+tty_end(EditLine *el)
+{
+ if (el->el_flags & EDIT_DISABLED)
+ return;
+
+ if (!el->el_tty.t_initialized)
+ return;
+
+ if (tty_setty(el, TCSAFLUSH, &el->el_tty.t_or) == -1) {
+#ifdef DEBUG_TTY
+ (void) fprintf(el->el_errfile,
+ "%s: tty_setty: %s\n", __func__, strerror(errno));
+#endif /* DEBUG_TTY */
+ }
+}
+
+
+/* tty__getspeed():
+ * Get the tty speed
+ */
+static speed_t
+tty__getspeed(struct termios *td)
+{
+ speed_t spd;
+
+ if ((spd = cfgetispeed(td)) == 0)
+ spd = cfgetospeed(td);
+ return spd;
+}
+
+/* tty__getspeed():
+ * Return the index of the asked char in the c_cc array
+ */
+static int
+tty__getcharindex(int i)
+{
+ switch (i) {
+#ifdef VINTR
+ case C_INTR:
+ return VINTR;
+#endif /* VINTR */
+#ifdef VQUIT
+ case C_QUIT:
+ return VQUIT;
+#endif /* VQUIT */
+#ifdef VERASE
+ case C_ERASE:
+ return VERASE;
+#endif /* VERASE */
+#ifdef VKILL
+ case C_KILL:
+ return VKILL;
+#endif /* VKILL */
+#ifdef VEOF
+ case C_EOF:
+ return VEOF;
+#endif /* VEOF */
+#ifdef VEOL
+ case C_EOL:
+ return VEOL;
+#endif /* VEOL */
+#ifdef VEOL2
+ case C_EOL2:
+ return VEOL2;
+#endif /* VEOL2 */
+#ifdef VSWTCH
+ case C_SWTCH:
+ return VSWTCH;
+#endif /* VSWTCH */
+#ifdef VDSWTCH
+ case C_DSWTCH:
+ return VDSWTCH;
+#endif /* VDSWTCH */
+#ifdef VERASE2
+ case C_ERASE2:
+ return VERASE2;
+#endif /* VERASE2 */
+#ifdef VSTART
+ case C_START:
+ return VSTART;
+#endif /* VSTART */
+#ifdef VSTOP
+ case C_STOP:
+ return VSTOP;
+#endif /* VSTOP */
+#ifdef VWERASE
+ case C_WERASE:
+ return VWERASE;
+#endif /* VWERASE */
+#ifdef VSUSP
+ case C_SUSP:
+ return VSUSP;
+#endif /* VSUSP */
+#ifdef VDSUSP
+ case C_DSUSP:
+ return VDSUSP;
+#endif /* VDSUSP */
+#ifdef VREPRINT
+ case C_REPRINT:
+ return VREPRINT;
+#endif /* VREPRINT */
+#ifdef VDISCARD
+ case C_DISCARD:
+ return VDISCARD;
+#endif /* VDISCARD */
+#ifdef VLNEXT
+ case C_LNEXT:
+ return VLNEXT;
+#endif /* VLNEXT */
+#ifdef VSTATUS
+ case C_STATUS:
+ return VSTATUS;
+#endif /* VSTATUS */
+#ifdef VPAGE
+ case C_PAGE:
+ return VPAGE;
+#endif /* VPAGE */
+#ifdef VPGOFF
+ case C_PGOFF:
+ return VPGOFF;
+#endif /* VPGOFF */
+#ifdef VKILL2
+ case C_KILL2:
+ return VKILL2;
+#endif /* KILL2 */
+#ifdef VMIN
+ case C_MIN:
+ return VMIN;
+#endif /* VMIN */
+#ifdef VTIME
+ case C_TIME:
+ return VTIME;
+#endif /* VTIME */
+ default:
+ return -1;
+ }
+}
+
+/* tty__getchar():
+ * Get the tty characters
+ */
+static void
+tty__getchar(struct termios *td, unsigned char *s)
+{
+
+#ifdef VINTR
+ s[C_INTR] = td->c_cc[VINTR];
+#endif /* VINTR */
+#ifdef VQUIT
+ s[C_QUIT] = td->c_cc[VQUIT];
+#endif /* VQUIT */
+#ifdef VERASE
+ s[C_ERASE] = td->c_cc[VERASE];
+#endif /* VERASE */
+#ifdef VKILL
+ s[C_KILL] = td->c_cc[VKILL];
+#endif /* VKILL */
+#ifdef VEOF
+ s[C_EOF] = td->c_cc[VEOF];
+#endif /* VEOF */
+#ifdef VEOL
+ s[C_EOL] = td->c_cc[VEOL];
+#endif /* VEOL */
+#ifdef VEOL2
+ s[C_EOL2] = td->c_cc[VEOL2];
+#endif /* VEOL2 */
+#ifdef VSWTCH
+ s[C_SWTCH] = td->c_cc[VSWTCH];
+#endif /* VSWTCH */
+#ifdef VDSWTCH
+ s[C_DSWTCH] = td->c_cc[VDSWTCH];
+#endif /* VDSWTCH */
+#ifdef VERASE2
+ s[C_ERASE2] = td->c_cc[VERASE2];
+#endif /* VERASE2 */
+#ifdef VSTART
+ s[C_START] = td->c_cc[VSTART];
+#endif /* VSTART */
+#ifdef VSTOP
+ s[C_STOP] = td->c_cc[VSTOP];
+#endif /* VSTOP */
+#ifdef VWERASE
+ s[C_WERASE] = td->c_cc[VWERASE];
+#endif /* VWERASE */
+#ifdef VSUSP
+ s[C_SUSP] = td->c_cc[VSUSP];
+#endif /* VSUSP */
+#ifdef VDSUSP
+ s[C_DSUSP] = td->c_cc[VDSUSP];
+#endif /* VDSUSP */
+#ifdef VREPRINT
+ s[C_REPRINT] = td->c_cc[VREPRINT];
+#endif /* VREPRINT */
+#ifdef VDISCARD
+ s[C_DISCARD] = td->c_cc[VDISCARD];
+#endif /* VDISCARD */
+#ifdef VLNEXT
+ s[C_LNEXT] = td->c_cc[VLNEXT];
+#endif /* VLNEXT */
+#ifdef VSTATUS
+ s[C_STATUS] = td->c_cc[VSTATUS];
+#endif /* VSTATUS */
+#ifdef VPAGE
+ s[C_PAGE] = td->c_cc[VPAGE];
+#endif /* VPAGE */
+#ifdef VPGOFF
+ s[C_PGOFF] = td->c_cc[VPGOFF];
+#endif /* VPGOFF */
+#ifdef VKILL2
+ s[C_KILL2] = td->c_cc[VKILL2];
+#endif /* KILL2 */
+#ifdef VMIN
+ s[C_MIN] = td->c_cc[VMIN];
+#endif /* VMIN */
+#ifdef VTIME
+ s[C_TIME] = td->c_cc[VTIME];
+#endif /* VTIME */
+} /* tty__getchar */
+
+
+/* tty__setchar():
+ * Set the tty characters
+ */
+static void
+tty__setchar(struct termios *td, unsigned char *s)
+{
+
+#ifdef VINTR
+ td->c_cc[VINTR] = s[C_INTR];
+#endif /* VINTR */
+#ifdef VQUIT
+ td->c_cc[VQUIT] = s[C_QUIT];
+#endif /* VQUIT */
+#ifdef VERASE
+ td->c_cc[VERASE] = s[C_ERASE];
+#endif /* VERASE */
+#ifdef VKILL
+ td->c_cc[VKILL] = s[C_KILL];
+#endif /* VKILL */
+#ifdef VEOF
+ td->c_cc[VEOF] = s[C_EOF];
+#endif /* VEOF */
+#ifdef VEOL
+ td->c_cc[VEOL] = s[C_EOL];
+#endif /* VEOL */
+#ifdef VEOL2
+ td->c_cc[VEOL2] = s[C_EOL2];
+#endif /* VEOL2 */
+#ifdef VSWTCH
+ td->c_cc[VSWTCH] = s[C_SWTCH];
+#endif /* VSWTCH */
+#ifdef VDSWTCH
+ td->c_cc[VDSWTCH] = s[C_DSWTCH];
+#endif /* VDSWTCH */
+#ifdef VERASE2
+ td->c_cc[VERASE2] = s[C_ERASE2];
+#endif /* VERASE2 */
+#ifdef VSTART
+ td->c_cc[VSTART] = s[C_START];
+#endif /* VSTART */
+#ifdef VSTOP
+ td->c_cc[VSTOP] = s[C_STOP];
+#endif /* VSTOP */
+#ifdef VWERASE
+ td->c_cc[VWERASE] = s[C_WERASE];
+#endif /* VWERASE */
+#ifdef VSUSP
+ td->c_cc[VSUSP] = s[C_SUSP];
+#endif /* VSUSP */
+#ifdef VDSUSP
+ td->c_cc[VDSUSP] = s[C_DSUSP];
+#endif /* VDSUSP */
+#ifdef VREPRINT
+ td->c_cc[VREPRINT] = s[C_REPRINT];
+#endif /* VREPRINT */
+#ifdef VDISCARD
+ td->c_cc[VDISCARD] = s[C_DISCARD];
+#endif /* VDISCARD */
+#ifdef VLNEXT
+ td->c_cc[VLNEXT] = s[C_LNEXT];
+#endif /* VLNEXT */
+#ifdef VSTATUS
+ td->c_cc[VSTATUS] = s[C_STATUS];
+#endif /* VSTATUS */
+#ifdef VPAGE
+ td->c_cc[VPAGE] = s[C_PAGE];
+#endif /* VPAGE */
+#ifdef VPGOFF
+ td->c_cc[VPGOFF] = s[C_PGOFF];
+#endif /* VPGOFF */
+#ifdef VKILL2
+ td->c_cc[VKILL2] = s[C_KILL2];
+#endif /* VKILL2 */
+#ifdef VMIN
+ td->c_cc[VMIN] = s[C_MIN];
+#endif /* VMIN */
+#ifdef VTIME
+ td->c_cc[VTIME] = s[C_TIME];
+#endif /* VTIME */
+} /* tty__setchar */
+
+
+/* tty_bind_char():
+ * Rebind the editline functions
+ */
+libedit_private void
+tty_bind_char(EditLine *el, int force)
+{
+
+ unsigned char *t_n = el->el_tty.t_c[ED_IO];
+ unsigned char *t_o = el->el_tty.t_ed.c_cc;
+ wchar_t new[2], old[2];
+ const ttymap_t *tp;
+ el_action_t *map, *alt;
+ const el_action_t *dmap, *dalt;
+ new[1] = old[1] = '\0';
+
+ map = el->el_map.key;
+ alt = el->el_map.alt;
+ if (el->el_map.type == MAP_VI) {
+ dmap = el->el_map.vii;
+ dalt = el->el_map.vic;
+ } else {
+ dmap = el->el_map.emacs;
+ dalt = NULL;
+ }
+
+ for (tp = tty_map; tp->nch != (wint_t)-1; tp++) {
+ new[0] = (wchar_t)t_n[tp->nch];
+ old[0] = (wchar_t)t_o[tp->och];
+ if (new[0] == old[0] && !force)
+ continue;
+ /* Put the old default binding back, and set the new binding */
+ keymacro_clear(el, map, old);
+ map[(unsigned char)old[0]] = dmap[(unsigned char)old[0]];
+ keymacro_clear(el, map, new);
+ /* MAP_VI == 1, MAP_EMACS == 0... */
+ map[(unsigned char)new[0]] = tp->bind[el->el_map.type];
+ if (dalt) {
+ keymacro_clear(el, alt, old);
+ alt[(unsigned char)old[0]] =
+ dalt[(unsigned char)old[0]];
+ keymacro_clear(el, alt, new);
+ alt[(unsigned char)new[0]] =
+ tp->bind[el->el_map.type + 1];
+ }
+ }
+}
+
+
+static tcflag_t *
+tty__get_flag(struct termios *t, int kind) {
+ switch (kind) {
+ case MD_INP:
+ return &t->c_iflag;
+ case MD_OUT:
+ return &t->c_oflag;
+ case MD_CTL:
+ return &t->c_cflag;
+ case MD_LIN:
+ return &t->c_lflag;
+ default:
+ abort();
+ /*NOTREACHED*/
+ }
+}
+
+
+static tcflag_t
+tty_update_flag(EditLine *el, tcflag_t f, int mode, int kind)
+{
+ f &= ~el->el_tty.t_t[mode][kind].t_clrmask;
+ f |= el->el_tty.t_t[mode][kind].t_setmask;
+ return f;
+}
+
+
+static void
+tty_update_flags(EditLine *el, int kind)
+{
+ tcflag_t *tt, *ed, *ex;
+ tt = tty__get_flag(&el->el_tty.t_ts, kind);
+ ed = tty__get_flag(&el->el_tty.t_ed, kind);
+ ex = tty__get_flag(&el->el_tty.t_ex, kind);
+
+ if (*tt != *ex && (kind != MD_CTL || *tt != *ed)) {
+ *ed = tty_update_flag(el, *tt, ED_IO, kind);
+ *ex = tty_update_flag(el, *tt, EX_IO, kind);
+ }
+}
+
+
+static void
+tty_update_char(EditLine *el, int mode, int c) {
+ if (!((el->el_tty.t_t[mode][MD_CHAR].t_setmask & C_SH(c)))
+ && (el->el_tty.t_c[TS_IO][c] != el->el_tty.t_c[EX_IO][c]))
+ el->el_tty.t_c[mode][c] = el->el_tty.t_c[TS_IO][c];
+ if (el->el_tty.t_t[mode][MD_CHAR].t_clrmask & C_SH(c))
+ el->el_tty.t_c[mode][c] = el->el_tty.t_vdisable;
+}
+
+
+/* tty_rawmode():
+ * Set terminal into 1 character at a time mode.
+ */
+libedit_private int
+tty_rawmode(EditLine *el)
+{
+
+ if (el->el_tty.t_mode == ED_IO || el->el_tty.t_mode == QU_IO)
+ return 0;
+
+ if (el->el_flags & EDIT_DISABLED)
+ return 0;
+
+ if (tty_getty(el, &el->el_tty.t_ts) == -1) {
+#ifdef DEBUG_TTY
+ (void) fprintf(el->el_errfile, "%s: tty_getty: %s\n", __func__,
+ strerror(errno));
+#endif /* DEBUG_TTY */
+ return -1;
+ }
+ /*
+ * We always keep up with the eight bit setting and the speed of the
+ * tty. But we only believe changes that are made to cooked mode!
+ */
+ el->el_tty.t_eight = tty__geteightbit(&el->el_tty.t_ts);
+ el->el_tty.t_speed = tty__getspeed(&el->el_tty.t_ts);
+
+ if (tty__getspeed(&el->el_tty.t_ex) != el->el_tty.t_speed ||
+ tty__getspeed(&el->el_tty.t_ed) != el->el_tty.t_speed) {
+ (void) cfsetispeed(&el->el_tty.t_ex, el->el_tty.t_speed);
+ (void) cfsetospeed(&el->el_tty.t_ex, el->el_tty.t_speed);
+ (void) cfsetispeed(&el->el_tty.t_ed, el->el_tty.t_speed);
+ (void) cfsetospeed(&el->el_tty.t_ed, el->el_tty.t_speed);
+ }
+ if (tty__cooked_mode(&el->el_tty.t_ts)) {
+ int i;
+
+ for (i = MD_INP; i <= MD_LIN; i++)
+ tty_update_flags(el, i);
+
+ if (tty__gettabs(&el->el_tty.t_ex) == 0)
+ el->el_tty.t_tabs = 0;
+ else
+ el->el_tty.t_tabs = EL_CAN_TAB ? 1 : 0;
+
+ tty__getchar(&el->el_tty.t_ts, el->el_tty.t_c[TS_IO]);
+ /*
+ * Check if the user made any changes.
+ * If he did, then propagate the changes to the
+ * edit and execute data structures.
+ */
+ for (i = 0; i < C_NCC; i++)
+ if (el->el_tty.t_c[TS_IO][i] !=
+ el->el_tty.t_c[EX_IO][i])
+ break;
+
+ if (i != C_NCC) {
+ /*
+ * Propagate changes only to the unlibedit_private
+ * chars that have been modified just now.
+ */
+ for (i = 0; i < C_NCC; i++)
+ tty_update_char(el, ED_IO, i);
+
+ tty_bind_char(el, 0);
+ tty__setchar(&el->el_tty.t_ed, el->el_tty.t_c[ED_IO]);
+
+ for (i = 0; i < C_NCC; i++)
+ tty_update_char(el, EX_IO, i);
+
+ tty__setchar(&el->el_tty.t_ex, el->el_tty.t_c[EX_IO]);
+ }
+ }
+ if (tty_setty(el, TCSADRAIN, &el->el_tty.t_ed) == -1) {
+#ifdef DEBUG_TTY
+ (void) fprintf(el->el_errfile, "%s: tty_setty: %s\n", __func__,
+ strerror(errno));
+#endif /* DEBUG_TTY */
+ return -1;
+ }
+ el->el_tty.t_mode = ED_IO;
+ return 0;
+}
+
+
+/* tty_cookedmode():
+ * Set the tty back to normal mode
+ */
+libedit_private int
+tty_cookedmode(EditLine *el)
+{ /* set tty in normal setup */
+
+ if (el->el_tty.t_mode == EX_IO)
+ return 0;
+
+ if (el->el_flags & EDIT_DISABLED)
+ return 0;
+
+ if (tty_setty(el, TCSADRAIN, &el->el_tty.t_ex) == -1) {
+#ifdef DEBUG_TTY
+ (void) fprintf(el->el_errfile, "%s: tty_setty: %s\n", __func__,
+ strerror(errno));
+#endif /* DEBUG_TTY */
+ return -1;
+ }
+ el->el_tty.t_mode = EX_IO;
+ return 0;
+}
+
+
+/* tty_quotemode():
+ * Turn on quote mode
+ */
+libedit_private int
+tty_quotemode(EditLine *el)
+{
+ if (el->el_tty.t_mode == QU_IO)
+ return 0;
+
+ el->el_tty.t_qu = el->el_tty.t_ed;
+
+ tty_setup_flags(el, &el->el_tty.t_qu, QU_IO);
+
+ if (tty_setty(el, TCSADRAIN, &el->el_tty.t_qu) == -1) {
+#ifdef DEBUG_TTY
+ (void) fprintf(el->el_errfile, "%s: tty_setty: %s\n", __func__,
+ strerror(errno));
+#endif /* DEBUG_TTY */
+ return -1;
+ }
+ el->el_tty.t_mode = QU_IO;
+ return 0;
+}
+
+
+/* tty_noquotemode():
+ * Turn off quote mode
+ */
+libedit_private int
+tty_noquotemode(EditLine *el)
+{
+
+ if (el->el_tty.t_mode != QU_IO)
+ return 0;
+ if (tty_setty(el, TCSADRAIN, &el->el_tty.t_ed) == -1) {
+#ifdef DEBUG_TTY
+ (void) fprintf(el->el_errfile, "%s: tty_setty: %s\n", __func__,
+ strerror(errno));
+#endif /* DEBUG_TTY */
+ return -1;
+ }
+ el->el_tty.t_mode = ED_IO;
+ return 0;
+}
+
+
+/* tty_stty():
+ * Stty builtin
+ */
+libedit_private int
+/*ARGSUSED*/
+tty_stty(EditLine *el, int argc __attribute__((__unused__)),
+ const wchar_t **argv)
+{
+ const ttymodes_t *m;
+ char x;
+ int aflag = 0;
+ const wchar_t *s, *d;
+ char name[EL_BUFSIZ];
+ struct termios *tios = &el->el_tty.t_ex;
+ int z = EX_IO;
+
+ if (argv == NULL)
+ return -1;
+ strncpy(name, ct_encode_string(*argv++, &el->el_scratch), sizeof(name));
+ name[sizeof(name) - 1] = '\0';
+
+ while (argv && *argv && argv[0][0] == '-' && argv[0][2] == '\0')
+ switch (argv[0][1]) {
+ case 'a':
+ aflag++;
+ argv++;
+ break;
+ case 'd':
+ argv++;
+ tios = &el->el_tty.t_ed;
+ z = ED_IO;
+ break;
+ case 'x':
+ argv++;
+ tios = &el->el_tty.t_ex;
+ z = EX_IO;
+ break;
+ case 'q':
+ argv++;
+ tios = &el->el_tty.t_ts;
+ z = QU_IO;
+ break;
+ default:
+ (void) fprintf(el->el_errfile,
+ "%s: Unknown switch `%lc'.\n",
+ name, (wint_t)argv[0][1]);
+ return -1;
+ }
+
+ if (!argv || !*argv) {
+ int i = -1;
+ size_t len = 0, st = 0, cu;
+ for (m = ttymodes; m->m_name; m++) {
+ if (m->m_type != i) {
+ (void) fprintf(el->el_outfile, "%s%s",
+ i != -1 ? "\n" : "",
+ el->el_tty.t_t[z][m->m_type].t_name);
+ i = m->m_type;
+ st = len =
+ strlen(el->el_tty.t_t[z][m->m_type].t_name);
+ }
+ if (i != -1) {
+ x = (el->el_tty.t_t[z][i].t_setmask & m->m_value)
+ ? '+' : '\0';
+
+ if (el->el_tty.t_t[z][i].t_clrmask & m->m_value)
+ x = '-';
+ } else {
+ x = '\0';
+ }
+
+ if (x != '\0' || aflag) {
+
+ cu = strlen(m->m_name) + (x != '\0') + 1;
+
+ if (len + cu >=
+ (size_t)el->el_terminal.t_size.h) {
+ (void) fprintf(el->el_outfile, "\n%*s",
+ (int)st, "");
+ len = st + cu;
+ } else
+ len += cu;
+
+ if (x != '\0')
+ (void) fprintf(el->el_outfile, "%c%s ",
+ x, m->m_name);
+ else
+ (void) fprintf(el->el_outfile, "%s ",
+ m->m_name);
+ }
+ }
+ (void) fprintf(el->el_outfile, "\n");
+ return 0;
+ }
+ while (argv && (s = *argv++)) {
+ const wchar_t *p;
+ switch (*s) {
+ case '+':
+ case '-':
+ x = (char)*s++;
+ break;
+ default:
+ x = '\0';
+ break;
+ }
+ d = s;
+ p = wcschr(s, L'=');
+ for (m = ttymodes; m->m_name; m++)
+ if ((p ? strncmp(m->m_name, ct_encode_string(d,
+ &el->el_scratch), (size_t)(p - d)) :
+ strcmp(m->m_name, ct_encode_string(d,
+ &el->el_scratch))) == 0 &&
+ (p == NULL || m->m_type == MD_CHAR))
+ break;
+
+ if (!m->m_name) {
+ (void) fprintf(el->el_errfile,
+ "%s: Invalid argument `%ls'.\n", name, d);
+ return -1;
+ }
+ if (p) {
+ int c = ffs((int)m->m_value);
+ int v = *++p ? parse__escape(&p) :
+ el->el_tty.t_vdisable;
+ assert(c != 0);
+ c--;
+ c = tty__getcharindex(c);
+ assert(c != -1);
+ tios->c_cc[c] = (cc_t)v;
+ continue;
+ }
+ switch (x) {
+ case '+':
+ el->el_tty.t_t[z][m->m_type].t_setmask |= m->m_value;
+ el->el_tty.t_t[z][m->m_type].t_clrmask &= ~m->m_value;
+ break;
+ case '-':
+ el->el_tty.t_t[z][m->m_type].t_setmask &= ~m->m_value;
+ el->el_tty.t_t[z][m->m_type].t_clrmask |= m->m_value;
+ break;
+ default:
+ el->el_tty.t_t[z][m->m_type].t_setmask &= ~m->m_value;
+ el->el_tty.t_t[z][m->m_type].t_clrmask &= ~m->m_value;
+ break;
+ }
+ }
+
+ tty_setup_flags(el, tios, z);
+ if (el->el_tty.t_mode == z) {
+ if (tty_setty(el, TCSADRAIN, tios) == -1) {
+#ifdef DEBUG_TTY
+ (void) fprintf(el->el_errfile, "%s: tty_setty: %s\n",
+ __func__, strerror(errno));
+#endif /* DEBUG_TTY */
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+
+#ifdef notyet
+/* tty_printchar():
+ * DEbugging routine to print the tty characters
+ */
+static void
+tty_printchar(EditLine *el, unsigned char *s)
+{
+ ttyperm_t *m;
+ int i;
+
+ for (i = 0; i < C_NCC; i++) {
+ for (m = el->el_tty.t_t; m->m_name; m++)
+ if (m->m_type == MD_CHAR && C_SH(i) == m->m_value)
+ break;
+ if (m->m_name)
+ (void) fprintf(el->el_errfile, "%s ^%c ",
+ m->m_name, s[i] + 'A' - 1);
+ if (i % 5 == 0)
+ (void) fprintf(el->el_errfile, "\n");
+ }
+ (void) fprintf(el->el_errfile, "\n");
+}
+#endif /* notyet */
+
+
+static void
+tty_setup_flags(EditLine *el, struct termios *tios, int mode)
+{
+ int kind;
+ for (kind = MD_INP; kind <= MD_LIN; kind++) {
+ tcflag_t *f = tty__get_flag(tios, kind);
+ *f = tty_update_flag(el, *f, mode, kind);
+ }
+}
diff --git a/third_party/heimdal/lib/libedit/src/tty.h b/third_party/heimdal/lib/libedit/src/tty.h
new file mode 100644
index 0000000..2603e1a
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/tty.h
@@ -0,0 +1,481 @@
+/* $NetBSD: tty.h,v 1.21 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)tty.h 8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * el.tty.h: Local terminal header
+ */
+#ifndef _h_el_tty
+#define _h_el_tty
+
+#include <termios.h>
+#include <unistd.h>
+
+/* Define our own since everyone gets it wrong! */
+#define CONTROL(A) ((A) & 037)
+
+/*
+ * Aix compatible names
+ */
+# if defined(VWERSE) && !defined(VWERASE)
+# define VWERASE VWERSE
+# endif /* VWERSE && !VWERASE */
+
+# if defined(VDISCRD) && !defined(VDISCARD)
+# define VDISCARD VDISCRD
+# endif /* VDISCRD && !VDISCARD */
+
+# if defined(VFLUSHO) && !defined(VDISCARD)
+# define VDISCARD VFLUSHO
+# endif /* VFLUSHO && VDISCARD */
+
+# if defined(VSTRT) && !defined(VSTART)
+# define VSTART VSTRT
+# endif /* VSTRT && ! VSTART */
+
+# if defined(VSTAT) && !defined(VSTATUS)
+# define VSTATUS VSTAT
+# endif /* VSTAT && ! VSTATUS */
+
+# ifndef ONLRET
+# define ONLRET 0
+# endif /* ONLRET */
+
+# ifndef TAB3
+# ifdef OXTABS
+# define TAB3 OXTABS
+# else
+# define TAB3 0
+# endif /* OXTABS */
+# endif /* !TAB3 */
+
+# if defined(OXTABS) && !defined(XTABS)
+# define XTABS OXTABS
+# endif /* OXTABS && !XTABS */
+
+# ifndef ONLCR
+# define ONLCR 0
+# endif /* ONLCR */
+
+# ifndef IEXTEN
+# define IEXTEN 0
+# endif /* IEXTEN */
+
+# ifndef ECHOCTL
+# define ECHOCTL 0
+# endif /* ECHOCTL */
+
+# ifndef PARENB
+# define PARENB 0
+# endif /* PARENB */
+
+# ifndef EXTPROC
+# define EXTPROC 0
+# endif /* EXTPROC */
+
+# ifndef FLUSHO
+# define FLUSHO 0
+# endif /* FLUSHO */
+
+
+# if defined(VDISABLE) && !defined(_POSIX_VDISABLE)
+# define _POSIX_VDISABLE VDISABLE
+# endif /* VDISABLE && ! _POSIX_VDISABLE */
+
+/*
+ * Work around ISC's definition of IEXTEN which is
+ * XCASE!
+ */
+# ifdef ISC
+# if defined(IEXTEN) && defined(XCASE)
+# if IEXTEN == XCASE
+# undef IEXTEN
+# define IEXTEN 0
+# endif /* IEXTEN == XCASE */
+# endif /* IEXTEN && XCASE */
+# if defined(IEXTEN) && !defined(XCASE)
+# define XCASE IEXTEN
+# undef IEXTEN
+# define IEXTEN 0
+# endif /* IEXTEN && !XCASE */
+# endif /* ISC */
+
+/*
+ * Work around convex weirdness where turning off IEXTEN makes us
+ * lose all postprocessing!
+ */
+#if defined(convex) || defined(__convex__)
+# if defined(IEXTEN) && IEXTEN != 0
+# undef IEXTEN
+# define IEXTEN 0
+# endif /* IEXTEN != 0 */
+#endif /* convex || __convex__ */
+
+/*
+ * So that we don't lose job control.
+ */
+#ifdef __SVR4
+# undef CSWTCH
+#endif
+
+#ifndef _POSIX_VDISABLE
+# define _POSIX_VDISABLE ((unsigned char) -1)
+#endif /* _POSIX_VDISABLE */
+
+#if !defined(CREPRINT) && defined(CRPRNT)
+# define CREPRINT CRPRNT
+#endif /* !CREPRINT && CRPRNT */
+#if !defined(CDISCARD) && defined(CFLUSH)
+# define CDISCARD CFLUSH
+#endif /* !CDISCARD && CFLUSH */
+
+#ifndef CINTR
+# define CINTR CONTROL('c')
+#endif /* CINTR */
+#ifndef CQUIT
+# define CQUIT 034 /* ^\ */
+#endif /* CQUIT */
+#ifndef CERASE
+# define CERASE 0177 /* ^? */
+#endif /* CERASE */
+#ifndef CKILL
+# define CKILL CONTROL('u')
+#endif /* CKILL */
+#ifndef CEOF
+# define CEOF CONTROL('d')
+#endif /* CEOF */
+#ifndef CEOL
+# define CEOL _POSIX_VDISABLE
+#endif /* CEOL */
+#ifndef CEOL2
+# define CEOL2 _POSIX_VDISABLE
+#endif /* CEOL2 */
+#ifndef CSWTCH
+# define CSWTCH _POSIX_VDISABLE
+#endif /* CSWTCH */
+#ifndef CDSWTCH
+# define CDSWTCH _POSIX_VDISABLE
+#endif /* CDSWTCH */
+#ifndef CERASE2
+# define CERASE2 _POSIX_VDISABLE
+#endif /* CERASE2 */
+#ifndef CSTART
+# define CSTART CONTROL('q')
+#endif /* CSTART */
+#ifndef CSTOP
+# define CSTOP CONTROL('s')
+#endif /* CSTOP */
+#ifndef CSUSP
+# define CSUSP CONTROL('z')
+#endif /* CSUSP */
+#ifndef CDSUSP
+# define CDSUSP CONTROL('y')
+#endif /* CDSUSP */
+
+#ifdef hpux
+
+# ifndef CREPRINT
+# define CREPRINT _POSIX_VDISABLE
+# endif /* CREPRINT */
+# ifndef CDISCARD
+# define CDISCARD _POSIX_VDISABLE
+# endif /* CDISCARD */
+# ifndef CLNEXT
+# define CLNEXT _POSIX_VDISABLE
+# endif /* CLNEXT */
+# ifndef CWERASE
+# define CWERASE _POSIX_VDISABLE
+# endif /* CWERASE */
+
+#else /* !hpux */
+
+# ifndef CREPRINT
+# define CREPRINT CONTROL('r')
+# endif /* CREPRINT */
+# ifndef CDISCARD
+# define CDISCARD CONTROL('o')
+# endif /* CDISCARD */
+# ifndef CLNEXT
+# define CLNEXT CONTROL('v')
+# endif /* CLNEXT */
+# ifndef CWERASE
+# define CWERASE CONTROL('w')
+# endif /* CWERASE */
+
+#endif /* hpux */
+
+#ifndef CSTATUS
+# define CSTATUS CONTROL('t')
+#endif /* CSTATUS */
+#ifndef CPAGE
+# define CPAGE ' '
+#endif /* CPAGE */
+#ifndef CPGOFF
+# define CPGOFF CONTROL('m')
+#endif /* CPGOFF */
+#ifndef CKILL2
+# define CKILL2 _POSIX_VDISABLE
+#endif /* CKILL2 */
+#ifndef CBRK
+# ifndef masscomp
+# define CBRK 0377
+# else
+# define CBRK '\0'
+# endif /* masscomp */
+#endif /* CBRK */
+#ifndef CMIN
+# define CMIN CEOF
+#endif /* CMIN */
+#ifndef CTIME
+# define CTIME CEOL
+#endif /* CTIME */
+
+/*
+ * Fix for sun inconsistency. On termio VSUSP and the rest of the
+ * ttychars > NCC are defined. So we undefine them.
+ */
+#if defined(TERMIO) || defined(POSIX)
+# if defined(POSIX) && defined(NCCS)
+# define NUMCC NCCS
+# else
+# ifdef NCC
+# define NUMCC NCC
+# endif /* NCC */
+# endif /* POSIX && NCCS */
+# ifdef NUMCC
+# ifdef VINTR
+# if NUMCC <= VINTR
+# undef VINTR
+# endif /* NUMCC <= VINTR */
+# endif /* VINTR */
+# ifdef VQUIT
+# if NUMCC <= VQUIT
+# undef VQUIT
+# endif /* NUMCC <= VQUIT */
+# endif /* VQUIT */
+# ifdef VERASE
+# if NUMCC <= VERASE
+# undef VERASE
+# endif /* NUMCC <= VERASE */
+# endif /* VERASE */
+# ifdef VKILL
+# if NUMCC <= VKILL
+# undef VKILL
+# endif /* NUMCC <= VKILL */
+# endif /* VKILL */
+# ifdef VEOF
+# if NUMCC <= VEOF
+# undef VEOF
+# endif /* NUMCC <= VEOF */
+# endif /* VEOF */
+# ifdef VEOL
+# if NUMCC <= VEOL
+# undef VEOL
+# endif /* NUMCC <= VEOL */
+# endif /* VEOL */
+# ifdef VEOL2
+# if NUMCC <= VEOL2
+# undef VEOL2
+# endif /* NUMCC <= VEOL2 */
+# endif /* VEOL2 */
+# ifdef VSWTCH
+# if NUMCC <= VSWTCH
+# undef VSWTCH
+# endif /* NUMCC <= VSWTCH */
+# endif /* VSWTCH */
+# ifdef VDSWTCH
+# if NUMCC <= VDSWTCH
+# undef VDSWTCH
+# endif /* NUMCC <= VDSWTCH */
+# endif /* VDSWTCH */
+# ifdef VERASE2
+# if NUMCC <= VERASE2
+# undef VERASE2
+# endif /* NUMCC <= VERASE2 */
+# endif /* VERASE2 */
+# ifdef VSTART
+# if NUMCC <= VSTART
+# undef VSTART
+# endif /* NUMCC <= VSTART */
+# endif /* VSTART */
+# ifdef VSTOP
+# if NUMCC <= VSTOP
+# undef VSTOP
+# endif /* NUMCC <= VSTOP */
+# endif /* VSTOP */
+# ifdef VWERASE
+# if NUMCC <= VWERASE
+# undef VWERASE
+# endif /* NUMCC <= VWERASE */
+# endif /* VWERASE */
+# ifdef VSUSP
+# if NUMCC <= VSUSP
+# undef VSUSP
+# endif /* NUMCC <= VSUSP */
+# endif /* VSUSP */
+# ifdef VDSUSP
+# if NUMCC <= VDSUSP
+# undef VDSUSP
+# endif /* NUMCC <= VDSUSP */
+# endif /* VDSUSP */
+# ifdef VREPRINT
+# if NUMCC <= VREPRINT
+# undef VREPRINT
+# endif /* NUMCC <= VREPRINT */
+# endif /* VREPRINT */
+# ifdef VDISCARD
+# if NUMCC <= VDISCARD
+# undef VDISCARD
+# endif /* NUMCC <= VDISCARD */
+# endif /* VDISCARD */
+# ifdef VLNEXT
+# if NUMCC <= VLNEXT
+# undef VLNEXT
+# endif /* NUMCC <= VLNEXT */
+# endif /* VLNEXT */
+# ifdef VSTATUS
+# if NUMCC <= VSTATUS
+# undef VSTATUS
+# endif /* NUMCC <= VSTATUS */
+# endif /* VSTATUS */
+# ifdef VPAGE
+# if NUMCC <= VPAGE
+# undef VPAGE
+# endif /* NUMCC <= VPAGE */
+# endif /* VPAGE */
+# ifdef VPGOFF
+# if NUMCC <= VPGOFF
+# undef VPGOFF
+# endif /* NUMCC <= VPGOFF */
+# endif /* VPGOFF */
+# ifdef VKILL2
+# if NUMCC <= VKILL2
+# undef VKILL2
+# endif /* NUMCC <= VKILL2 */
+# endif /* VKILL2 */
+# ifdef VBRK
+# if NUMCC <= VBRK
+# undef VBRK
+# endif /* NUMCC <= VBRK */
+# endif /* VBRK */
+# ifdef VMIN
+# if NUMCC <= VMIN
+# undef VMIN
+# endif /* NUMCC <= VMIN */
+# endif /* VMIN */
+# ifdef VTIME
+# if NUMCC <= VTIME
+# undef VTIME
+# endif /* NUMCC <= VTIME */
+# endif /* VTIME */
+# endif /* NUMCC */
+#endif /* !POSIX */
+
+#define C_INTR 0
+#define C_QUIT 1
+#define C_ERASE 2
+#define C_KILL 3
+#define C_EOF 4
+#define C_EOL 5
+#define C_EOL2 6
+#define C_SWTCH 7
+#define C_DSWTCH 8
+#define C_ERASE2 9
+#define C_START 10
+#define C_STOP 11
+#define C_WERASE 12
+#define C_SUSP 13
+#define C_DSUSP 14
+#define C_REPRINT 15
+#define C_DISCARD 16
+#define C_LNEXT 17
+#define C_STATUS 18
+#define C_PAGE 19
+#define C_PGOFF 20
+#define C_KILL2 21
+#define C_BRK 22
+#define C_MIN 23
+#define C_TIME 24
+#define C_NCC 25
+#define C_SH(A) ((unsigned int)(1 << (A)))
+
+/*
+ * Terminal dependend data structures
+ */
+#define EX_IO 0 /* while we are executing */
+#define ED_IO 1 /* while we are editing */
+#define TS_IO 2 /* new mode from terminal */
+#define QU_IO 2 /* used only for quoted chars */
+#define NN_IO 3 /* The number of entries */
+
+/* Don't re-order */
+#define MD_INP 0
+#define MD_OUT 1
+#define MD_CTL 2
+#define MD_LIN 3
+#define MD_CHAR 4
+#define MD_NN 5
+
+typedef struct {
+ const char *t_name;
+ unsigned int t_setmask;
+ unsigned int t_clrmask;
+} ttyperm_t[NN_IO][MD_NN];
+
+typedef unsigned char ttychar_t[NN_IO][C_NCC];
+
+libedit_private int tty_init(EditLine *);
+libedit_private void tty_end(EditLine *);
+libedit_private int tty_stty(EditLine *, int, const wchar_t **);
+libedit_private int tty_rawmode(EditLine *);
+libedit_private int tty_cookedmode(EditLine *);
+libedit_private int tty_quotemode(EditLine *);
+libedit_private int tty_noquotemode(EditLine *);
+libedit_private void tty_bind_char(EditLine *, int);
+
+typedef struct {
+ ttyperm_t t_t;
+ ttychar_t t_c;
+ struct termios t_or, t_ex, t_ed, t_ts;
+ int t_tabs;
+ int t_eight;
+ speed_t t_speed;
+ unsigned char t_mode;
+ unsigned char t_vdisable;
+ unsigned char t_initialized;
+} el_tty_t;
+
+
+#endif /* _h_el_tty */
diff --git a/third_party/heimdal/lib/libedit/src/unvis.c b/third_party/heimdal/lib/libedit/src/unvis.c
new file mode 100644
index 0000000..719f86a
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/unvis.c
@@ -0,0 +1,553 @@
+/* $NetBSD: unvis.c,v 1.44 2014/09/26 15:43:36 roy Exp $ */
+
+/*-
+ * Copyright (c) 1989, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)unvis.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: unvis.c,v 1.44 2014/09/26 15:43:36 roy Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <errno.h>
+#include <vis.h>
+
+#if !HAVE_VIS
+/*
+ * decode driven by state machine
+ */
+#define S_GROUND 0 /* haven't seen escape char */
+#define S_START 1 /* start decoding special sequence */
+#define S_META 2 /* metachar started (M) */
+#define S_META1 3 /* metachar more, regular char (-) */
+#define S_CTRL 4 /* control char started (^) */
+#define S_OCTAL2 5 /* octal digit 2 */
+#define S_OCTAL3 6 /* octal digit 3 */
+#define S_HEX 7 /* mandatory hex digit */
+#define S_HEX1 8 /* http hex digit */
+#define S_HEX2 9 /* http hex digit 2 */
+#define S_MIME1 10 /* mime hex digit 1 */
+#define S_MIME2 11 /* mime hex digit 2 */
+#define S_EATCRNL 12 /* mime eating CRNL */
+#define S_AMP 13 /* seen & */
+#define S_NUMBER 14 /* collecting number */
+#define S_STRING 15 /* collecting string */
+
+#define isoctal(c) (((u_char)(c)) >= '0' && ((u_char)(c)) <= '7')
+#define xtod(c) (isdigit(c) ? (c - '0') : ((tolower(c) - 'a') + 10))
+#define XTOD(c) (isdigit(c) ? (c - '0') : ((c - 'A') + 10))
+
+/*
+ * RFC 1866
+ */
+static const struct nv {
+ char name[7];
+ uint8_t value;
+} nv[] = {
+ { "AElig", 198 }, /* capital AE diphthong (ligature) */
+ { "Aacute", 193 }, /* capital A, acute accent */
+ { "Acirc", 194 }, /* capital A, circumflex accent */
+ { "Agrave", 192 }, /* capital A, grave accent */
+ { "Aring", 197 }, /* capital A, ring */
+ { "Atilde", 195 }, /* capital A, tilde */
+ { "Auml", 196 }, /* capital A, dieresis or umlaut mark */
+ { "Ccedil", 199 }, /* capital C, cedilla */
+ { "ETH", 208 }, /* capital Eth, Icelandic */
+ { "Eacute", 201 }, /* capital E, acute accent */
+ { "Ecirc", 202 }, /* capital E, circumflex accent */
+ { "Egrave", 200 }, /* capital E, grave accent */
+ { "Euml", 203 }, /* capital E, dieresis or umlaut mark */
+ { "Iacute", 205 }, /* capital I, acute accent */
+ { "Icirc", 206 }, /* capital I, circumflex accent */
+ { "Igrave", 204 }, /* capital I, grave accent */
+ { "Iuml", 207 }, /* capital I, dieresis or umlaut mark */
+ { "Ntilde", 209 }, /* capital N, tilde */
+ { "Oacute", 211 }, /* capital O, acute accent */
+ { "Ocirc", 212 }, /* capital O, circumflex accent */
+ { "Ograve", 210 }, /* capital O, grave accent */
+ { "Oslash", 216 }, /* capital O, slash */
+ { "Otilde", 213 }, /* capital O, tilde */
+ { "Ouml", 214 }, /* capital O, dieresis or umlaut mark */
+ { "THORN", 222 }, /* capital THORN, Icelandic */
+ { "Uacute", 218 }, /* capital U, acute accent */
+ { "Ucirc", 219 }, /* capital U, circumflex accent */
+ { "Ugrave", 217 }, /* capital U, grave accent */
+ { "Uuml", 220 }, /* capital U, dieresis or umlaut mark */
+ { "Yacute", 221 }, /* capital Y, acute accent */
+ { "aacute", 225 }, /* small a, acute accent */
+ { "acirc", 226 }, /* small a, circumflex accent */
+ { "acute", 180 }, /* acute accent */
+ { "aelig", 230 }, /* small ae diphthong (ligature) */
+ { "agrave", 224 }, /* small a, grave accent */
+ { "amp", 38 }, /* ampersand */
+ { "aring", 229 }, /* small a, ring */
+ { "atilde", 227 }, /* small a, tilde */
+ { "auml", 228 }, /* small a, dieresis or umlaut mark */
+ { "brvbar", 166 }, /* broken (vertical) bar */
+ { "ccedil", 231 }, /* small c, cedilla */
+ { "cedil", 184 }, /* cedilla */
+ { "cent", 162 }, /* cent sign */
+ { "copy", 169 }, /* copyright sign */
+ { "curren", 164 }, /* general currency sign */
+ { "deg", 176 }, /* degree sign */
+ { "divide", 247 }, /* divide sign */
+ { "eacute", 233 }, /* small e, acute accent */
+ { "ecirc", 234 }, /* small e, circumflex accent */
+ { "egrave", 232 }, /* small e, grave accent */
+ { "eth", 240 }, /* small eth, Icelandic */
+ { "euml", 235 }, /* small e, dieresis or umlaut mark */
+ { "frac12", 189 }, /* fraction one-half */
+ { "frac14", 188 }, /* fraction one-quarter */
+ { "frac34", 190 }, /* fraction three-quarters */
+ { "gt", 62 }, /* greater than */
+ { "iacute", 237 }, /* small i, acute accent */
+ { "icirc", 238 }, /* small i, circumflex accent */
+ { "iexcl", 161 }, /* inverted exclamation mark */
+ { "igrave", 236 }, /* small i, grave accent */
+ { "iquest", 191 }, /* inverted question mark */
+ { "iuml", 239 }, /* small i, dieresis or umlaut mark */
+ { "laquo", 171 }, /* angle quotation mark, left */
+ { "lt", 60 }, /* less than */
+ { "macr", 175 }, /* macron */
+ { "micro", 181 }, /* micro sign */
+ { "middot", 183 }, /* middle dot */
+ { "nbsp", 160 }, /* no-break space */
+ { "not", 172 }, /* not sign */
+ { "ntilde", 241 }, /* small n, tilde */
+ { "oacute", 243 }, /* small o, acute accent */
+ { "ocirc", 244 }, /* small o, circumflex accent */
+ { "ograve", 242 }, /* small o, grave accent */
+ { "ordf", 170 }, /* ordinal indicator, feminine */
+ { "ordm", 186 }, /* ordinal indicator, masculine */
+ { "oslash", 248 }, /* small o, slash */
+ { "otilde", 245 }, /* small o, tilde */
+ { "ouml", 246 }, /* small o, dieresis or umlaut mark */
+ { "para", 182 }, /* pilcrow (paragraph sign) */
+ { "plusmn", 177 }, /* plus-or-minus sign */
+ { "pound", 163 }, /* pound sterling sign */
+ { "quot", 34 }, /* double quote */
+ { "raquo", 187 }, /* angle quotation mark, right */
+ { "reg", 174 }, /* registered sign */
+ { "sect", 167 }, /* section sign */
+ { "shy", 173 }, /* soft hyphen */
+ { "sup1", 185 }, /* superscript one */
+ { "sup2", 178 }, /* superscript two */
+ { "sup3", 179 }, /* superscript three */
+ { "szlig", 223 }, /* small sharp s, German (sz ligature) */
+ { "thorn", 254 }, /* small thorn, Icelandic */
+ { "times", 215 }, /* multiply sign */
+ { "uacute", 250 }, /* small u, acute accent */
+ { "ucirc", 251 }, /* small u, circumflex accent */
+ { "ugrave", 249 }, /* small u, grave accent */
+ { "uml", 168 }, /* umlaut (dieresis) */
+ { "uuml", 252 }, /* small u, dieresis or umlaut mark */
+ { "yacute", 253 }, /* small y, acute accent */
+ { "yen", 165 }, /* yen sign */
+ { "yuml", 255 }, /* small y, dieresis or umlaut mark */
+};
+
+/*
+ * unvis - decode characters previously encoded by vis
+ */
+int
+unvis(char *cp, int c, int *astate, int flag)
+{
+ unsigned char uc = (unsigned char)c;
+ unsigned char st, ia, is, lc;
+
+/*
+ * Bottom 8 bits of astate hold the state machine state.
+ * Top 8 bits hold the current character in the http 1866 nv string decoding
+ */
+#define GS(a) ((a) & 0xff)
+#define SS(a, b) (((uint32_t)(a) << 24) | (b))
+#define GI(a) ((uint32_t)(a) >> 24)
+
+ _DIAGASSERT(cp != NULL);
+ _DIAGASSERT(astate != NULL);
+ st = GS(*astate);
+
+ if (flag & UNVIS_END) {
+ switch (st) {
+ case S_OCTAL2:
+ case S_OCTAL3:
+ case S_HEX2:
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+ case S_GROUND:
+ return UNVIS_NOCHAR;
+ default:
+ return UNVIS_SYNBAD;
+ }
+ }
+
+ switch (st) {
+
+ case S_GROUND:
+ *cp = 0;
+ if ((flag & VIS_NOESCAPE) == 0 && c == '\\') {
+ *astate = SS(0, S_START);
+ return UNVIS_NOCHAR;
+ }
+ if ((flag & VIS_HTTP1808) && c == '%') {
+ *astate = SS(0, S_HEX1);
+ return UNVIS_NOCHAR;
+ }
+ if ((flag & VIS_HTTP1866) && c == '&') {
+ *astate = SS(0, S_AMP);
+ return UNVIS_NOCHAR;
+ }
+ if ((flag & VIS_MIMESTYLE) && c == '=') {
+ *astate = SS(0, S_MIME1);
+ return UNVIS_NOCHAR;
+ }
+ *cp = c;
+ return UNVIS_VALID;
+
+ case S_START:
+ switch(c) {
+ case '\\':
+ *cp = c;
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+ case '0': case '1': case '2': case '3':
+ case '4': case '5': case '6': case '7':
+ *cp = (c - '0');
+ *astate = SS(0, S_OCTAL2);
+ return UNVIS_NOCHAR;
+ case 'M':
+ *cp = (char)0200;
+ *astate = SS(0, S_META);
+ return UNVIS_NOCHAR;
+ case '^':
+ *astate = SS(0, S_CTRL);
+ return UNVIS_NOCHAR;
+ case 'n':
+ *cp = '\n';
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+ case 'r':
+ *cp = '\r';
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+ case 'b':
+ *cp = '\b';
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+ case 'a':
+ *cp = '\007';
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+ case 'v':
+ *cp = '\v';
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+ case 't':
+ *cp = '\t';
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+ case 'f':
+ *cp = '\f';
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+ case 's':
+ *cp = ' ';
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+ case 'E':
+ *cp = '\033';
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+ case 'x':
+ *astate = SS(0, S_HEX);
+ return UNVIS_NOCHAR;
+ case '\n':
+ /*
+ * hidden newline
+ */
+ *astate = SS(0, S_GROUND);
+ return UNVIS_NOCHAR;
+ case '$':
+ /*
+ * hidden marker
+ */
+ *astate = SS(0, S_GROUND);
+ return UNVIS_NOCHAR;
+ default:
+ if (isgraph(c)) {
+ *cp = c;
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+ }
+ }
+ goto bad;
+
+ case S_META:
+ if (c == '-')
+ *astate = SS(0, S_META1);
+ else if (c == '^')
+ *astate = SS(0, S_CTRL);
+ else
+ goto bad;
+ return UNVIS_NOCHAR;
+
+ case S_META1:
+ *astate = SS(0, S_GROUND);
+ *cp |= c;
+ return UNVIS_VALID;
+
+ case S_CTRL:
+ if (c == '?')
+ *cp |= 0177;
+ else
+ *cp |= c & 037;
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+
+ case S_OCTAL2: /* second possible octal digit */
+ if (isoctal(uc)) {
+ /*
+ * yes - and maybe a third
+ */
+ *cp = (*cp << 3) + (c - '0');
+ *astate = SS(0, S_OCTAL3);
+ return UNVIS_NOCHAR;
+ }
+ /*
+ * no - done with current sequence, push back passed char
+ */
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALIDPUSH;
+
+ case S_OCTAL3: /* third possible octal digit */
+ *astate = SS(0, S_GROUND);
+ if (isoctal(uc)) {
+ *cp = (*cp << 3) + (c - '0');
+ return UNVIS_VALID;
+ }
+ /*
+ * we were done, push back passed char
+ */
+ return UNVIS_VALIDPUSH;
+
+ case S_HEX:
+ if (!isxdigit(uc))
+ goto bad;
+ /*FALLTHROUGH*/
+ case S_HEX1:
+ if (isxdigit(uc)) {
+ *cp = xtod(uc);
+ *astate = SS(0, S_HEX2);
+ return UNVIS_NOCHAR;
+ }
+ /*
+ * no - done with current sequence, push back passed char
+ */
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALIDPUSH;
+
+ case S_HEX2:
+ *astate = S_GROUND;
+ if (isxdigit(uc)) {
+ *cp = xtod(uc) | (*cp << 4);
+ return UNVIS_VALID;
+ }
+ return UNVIS_VALIDPUSH;
+
+ case S_MIME1:
+ if (uc == '\n' || uc == '\r') {
+ *astate = SS(0, S_EATCRNL);
+ return UNVIS_NOCHAR;
+ }
+ if (isxdigit(uc) && (isdigit(uc) || isupper(uc))) {
+ *cp = XTOD(uc);
+ *astate = SS(0, S_MIME2);
+ return UNVIS_NOCHAR;
+ }
+ goto bad;
+
+ case S_MIME2:
+ if (isxdigit(uc) && (isdigit(uc) || isupper(uc))) {
+ *astate = SS(0, S_GROUND);
+ *cp = XTOD(uc) | (*cp << 4);
+ return UNVIS_VALID;
+ }
+ goto bad;
+
+ case S_EATCRNL:
+ switch (uc) {
+ case '\r':
+ case '\n':
+ return UNVIS_NOCHAR;
+ case '=':
+ *astate = SS(0, S_MIME1);
+ return UNVIS_NOCHAR;
+ default:
+ *cp = uc;
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+ }
+
+ case S_AMP:
+ *cp = 0;
+ if (uc == '#') {
+ *astate = SS(0, S_NUMBER);
+ return UNVIS_NOCHAR;
+ }
+ *astate = SS(0, S_STRING);
+ /*FALLTHROUGH*/
+
+ case S_STRING:
+ ia = *cp; /* index in the array */
+ is = GI(*astate); /* index in the string */
+ lc = is == 0 ? 0 : nv[ia].name[is - 1]; /* last character */
+
+ if (uc == ';')
+ uc = '\0';
+
+ for (; ia < __arraycount(nv); ia++) {
+ if (is != 0 && nv[ia].name[is - 1] != lc)
+ goto bad;
+ if (nv[ia].name[is] == uc)
+ break;
+ }
+
+ if (ia == __arraycount(nv))
+ goto bad;
+
+ if (uc != 0) {
+ *cp = ia;
+ *astate = SS(is + 1, S_STRING);
+ return UNVIS_NOCHAR;
+ }
+
+ *cp = nv[ia].value;
+ *astate = SS(0, S_GROUND);
+ return UNVIS_VALID;
+
+ case S_NUMBER:
+ if (uc == ';')
+ return UNVIS_VALID;
+ if (!isdigit(uc))
+ goto bad;
+ *cp += (*cp * 10) + uc - '0';
+ return UNVIS_NOCHAR;
+
+ default:
+ bad:
+ /*
+ * decoder in unknown state - (probably uninitialized)
+ */
+ *astate = SS(0, S_GROUND);
+ return UNVIS_SYNBAD;
+ }
+}
+
+/*
+ * strnunvisx - decode src into dst
+ *
+ * Number of chars decoded into dst is returned, -1 on error.
+ * Dst is null terminated.
+ */
+
+int
+strnunvisx(char *dst, size_t dlen, const char *src, int flag)
+{
+ char c;
+ char t = '\0', *start = dst;
+ int state = 0;
+
+ _DIAGASSERT(src != NULL);
+ _DIAGASSERT(dst != NULL);
+#define CHECKSPACE() \
+ do { \
+ if (dlen-- == 0) { \
+ errno = ENOSPC; \
+ return -1; \
+ } \
+ } while (/*CONSTCOND*/0)
+
+ while ((c = *src++) != '\0') {
+ again:
+ switch (unvis(&t, c, &state, flag)) {
+ case UNVIS_VALID:
+ CHECKSPACE();
+ *dst++ = t;
+ break;
+ case UNVIS_VALIDPUSH:
+ CHECKSPACE();
+ *dst++ = t;
+ goto again;
+ case 0:
+ case UNVIS_NOCHAR:
+ break;
+ case UNVIS_SYNBAD:
+ errno = EINVAL;
+ return -1;
+ default:
+ _DIAGASSERT(/*CONSTCOND*/0);
+ errno = EINVAL;
+ return -1;
+ }
+ }
+ if (unvis(&t, c, &state, UNVIS_END) == UNVIS_VALID) {
+ CHECKSPACE();
+ *dst++ = t;
+ }
+ CHECKSPACE();
+ *dst = '\0';
+ return (int)(dst - start);
+}
+
+int
+strunvisx(char *dst, const char *src, int flag)
+{
+ return strnunvisx(dst, (size_t)~0, src, flag);
+}
+
+int
+strunvis(char *dst, const char *src)
+{
+ return strnunvisx(dst, (size_t)~0, src, 0);
+}
+
+int
+strnunvis(char *dst, size_t dlen, const char *src)
+{
+ return strnunvisx(dst, dlen, src, 0);
+}
+#endif
diff --git a/third_party/heimdal/lib/libedit/src/vi.c b/third_party/heimdal/lib/libedit/src/vi.c
new file mode 100644
index 0000000..0c37bfb
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/vi.c
@@ -0,0 +1,1157 @@
+/* $NetBSD: vi.c,v 1.62 2016/05/09 21:46:56 christos Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Christos Zoulas of Cornell University.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if !defined(lint) && !defined(SCCSID)
+#if 0
+static char sccsid[] = "@(#)vi.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: vi.c,v 1.62 2016/05/09 21:46:56 christos Exp $");
+#endif
+#endif /* not lint && not SCCSID */
+
+/*
+ * vi.c: Vi mode commands.
+ */
+#include <sys/wait.h>
+#include <ctype.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "el.h"
+#include "common.h"
+#include "emacs.h"
+#include "fcns.h"
+#include "vi.h"
+
+static el_action_t cv_action(EditLine *, wint_t);
+static el_action_t cv_paste(EditLine *, wint_t);
+
+/* cv_action():
+ * Handle vi actions.
+ */
+static el_action_t
+cv_action(EditLine *el, wint_t c)
+{
+
+ if (el->el_chared.c_vcmd.action != NOP) {
+ /* 'cc', 'dd' and (possibly) friends */
+ if (c != (wint_t)el->el_chared.c_vcmd.action)
+ return CC_ERROR;
+
+ if (!(c & YANK))
+ cv_undo(el);
+ cv_yank(el, el->el_line.buffer,
+ (int)(el->el_line.lastchar - el->el_line.buffer));
+ el->el_chared.c_vcmd.action = NOP;
+ el->el_chared.c_vcmd.pos = 0;
+ if (!(c & YANK)) {
+ el->el_line.lastchar = el->el_line.buffer;
+ el->el_line.cursor = el->el_line.buffer;
+ }
+ if (c & INSERT)
+ el->el_map.current = el->el_map.key;
+
+ return CC_REFRESH;
+ }
+ el->el_chared.c_vcmd.pos = el->el_line.cursor;
+ el->el_chared.c_vcmd.action = c;
+ return CC_ARGHACK;
+}
+
+/* cv_paste():
+ * Paste previous deletion before or after the cursor
+ */
+static el_action_t
+cv_paste(EditLine *el, wint_t c)
+{
+ c_kill_t *k = &el->el_chared.c_kill;
+ size_t len = (size_t)(k->last - k->buf);
+
+ if (k->buf == NULL || len == 0)
+ return CC_ERROR;
+#ifdef DEBUG_PASTE
+ (void) fprintf(el->el_errfile, "Paste: \"%.*ls\"\n", (int)len,
+ k->buf);
+#endif
+
+ cv_undo(el);
+
+ if (!c && el->el_line.cursor < el->el_line.lastchar)
+ el->el_line.cursor++;
+
+ c_insert(el, (int)len);
+ if (el->el_line.cursor + len > el->el_line.lastchar)
+ return CC_ERROR;
+ (void) memcpy(el->el_line.cursor, k->buf, len *
+ sizeof(*el->el_line.cursor));
+
+ return CC_REFRESH;
+}
+
+
+/* vi_paste_next():
+ * Vi paste previous deletion to the right of the cursor
+ * [p]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_paste_next(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ return cv_paste(el, 0);
+}
+
+
+/* vi_paste_prev():
+ * Vi paste previous deletion to the left of the cursor
+ * [P]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_paste_prev(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ return cv_paste(el, 1);
+}
+
+
+/* vi_prev_big_word():
+ * Vi move to the previous space delimited word
+ * [B]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_prev_big_word(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ if (el->el_line.cursor == el->el_line.buffer)
+ return CC_ERROR;
+
+ el->el_line.cursor = cv_prev_word(el->el_line.cursor,
+ el->el_line.buffer,
+ el->el_state.argument,
+ cv__isWord);
+
+ if (el->el_chared.c_vcmd.action != NOP) {
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+ return CC_CURSOR;
+}
+
+
+/* vi_prev_word():
+ * Vi move to the previous word
+ * [b]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_prev_word(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ if (el->el_line.cursor == el->el_line.buffer)
+ return CC_ERROR;
+
+ el->el_line.cursor = cv_prev_word(el->el_line.cursor,
+ el->el_line.buffer,
+ el->el_state.argument,
+ cv__isword);
+
+ if (el->el_chared.c_vcmd.action != NOP) {
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+ return CC_CURSOR;
+}
+
+
+/* vi_next_big_word():
+ * Vi move to the next space delimited word
+ * [W]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_next_big_word(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ if (el->el_line.cursor >= el->el_line.lastchar - 1)
+ return CC_ERROR;
+
+ el->el_line.cursor = cv_next_word(el, el->el_line.cursor,
+ el->el_line.lastchar, el->el_state.argument, cv__isWord);
+
+ if (el->el_map.type == MAP_VI)
+ if (el->el_chared.c_vcmd.action != NOP) {
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+ return CC_CURSOR;
+}
+
+
+/* vi_next_word():
+ * Vi move to the next word
+ * [w]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_next_word(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ if (el->el_line.cursor >= el->el_line.lastchar - 1)
+ return CC_ERROR;
+
+ el->el_line.cursor = cv_next_word(el, el->el_line.cursor,
+ el->el_line.lastchar, el->el_state.argument, cv__isword);
+
+ if (el->el_map.type == MAP_VI)
+ if (el->el_chared.c_vcmd.action != NOP) {
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+ return CC_CURSOR;
+}
+
+
+/* vi_change_case():
+ * Vi change case of character under the cursor and advance one character
+ * [~]
+ */
+libedit_private el_action_t
+vi_change_case(EditLine *el, wint_t c)
+{
+ int i;
+
+ if (el->el_line.cursor >= el->el_line.lastchar)
+ return CC_ERROR;
+ cv_undo(el);
+ for (i = 0; i < el->el_state.argument; i++) {
+
+ c = *el->el_line.cursor;
+ if (iswupper(c))
+ *el->el_line.cursor = towlower(c);
+ else if (iswlower(c))
+ *el->el_line.cursor = towupper(c);
+
+ if (++el->el_line.cursor >= el->el_line.lastchar) {
+ el->el_line.cursor--;
+ re_fastaddc(el);
+ break;
+ }
+ re_fastaddc(el);
+ }
+ return CC_NORM;
+}
+
+
+/* vi_change_meta():
+ * Vi change prefix command
+ * [c]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_change_meta(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ /*
+ * Delete with insert == change: first we delete and then we leave in
+ * insert mode.
+ */
+ return cv_action(el, DELETE | INSERT);
+}
+
+
+/* vi_insert_at_bol():
+ * Vi enter insert mode at the beginning of line
+ * [I]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_insert_at_bol(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ el->el_line.cursor = el->el_line.buffer;
+ cv_undo(el);
+ el->el_map.current = el->el_map.key;
+ return CC_CURSOR;
+}
+
+
+/* vi_replace_char():
+ * Vi replace character under the cursor with the next character typed
+ * [r]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_replace_char(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ if (el->el_line.cursor >= el->el_line.lastchar)
+ return CC_ERROR;
+
+ el->el_map.current = el->el_map.key;
+ el->el_state.inputmode = MODE_REPLACE_1;
+ cv_undo(el);
+ return CC_ARGHACK;
+}
+
+
+/* vi_replace_mode():
+ * Vi enter replace mode
+ * [R]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_replace_mode(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ el->el_map.current = el->el_map.key;
+ el->el_state.inputmode = MODE_REPLACE;
+ cv_undo(el);
+ return CC_NORM;
+}
+
+
+/* vi_substitute_char():
+ * Vi replace character under the cursor and enter insert mode
+ * [s]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_substitute_char(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ c_delafter(el, el->el_state.argument);
+ el->el_map.current = el->el_map.key;
+ return CC_REFRESH;
+}
+
+
+/* vi_substitute_line():
+ * Vi substitute entire line
+ * [S]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_substitute_line(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ cv_undo(el);
+ cv_yank(el, el->el_line.buffer,
+ (int)(el->el_line.lastchar - el->el_line.buffer));
+ (void) em_kill_line(el, 0);
+ el->el_map.current = el->el_map.key;
+ return CC_REFRESH;
+}
+
+
+/* vi_change_to_eol():
+ * Vi change to end of line
+ * [C]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_change_to_eol(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ cv_undo(el);
+ cv_yank(el, el->el_line.cursor,
+ (int)(el->el_line.lastchar - el->el_line.cursor));
+ (void) ed_kill_line(el, 0);
+ el->el_map.current = el->el_map.key;
+ return CC_REFRESH;
+}
+
+
+/* vi_insert():
+ * Vi enter insert mode
+ * [i]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_insert(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ el->el_map.current = el->el_map.key;
+ cv_undo(el);
+ return CC_NORM;
+}
+
+
+/* vi_add():
+ * Vi enter insert mode after the cursor
+ * [a]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_add(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ int ret;
+
+ el->el_map.current = el->el_map.key;
+ if (el->el_line.cursor < el->el_line.lastchar) {
+ el->el_line.cursor++;
+ if (el->el_line.cursor > el->el_line.lastchar)
+ el->el_line.cursor = el->el_line.lastchar;
+ ret = CC_CURSOR;
+ } else
+ ret = CC_NORM;
+
+ cv_undo(el);
+
+ return (el_action_t)ret;
+}
+
+
+/* vi_add_at_eol():
+ * Vi enter insert mode at end of line
+ * [A]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_add_at_eol(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ el->el_map.current = el->el_map.key;
+ el->el_line.cursor = el->el_line.lastchar;
+ cv_undo(el);
+ return CC_CURSOR;
+}
+
+
+/* vi_delete_meta():
+ * Vi delete prefix command
+ * [d]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_delete_meta(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ return cv_action(el, DELETE);
+}
+
+
+/* vi_end_big_word():
+ * Vi move to the end of the current space delimited word
+ * [E]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_end_big_word(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ if (el->el_line.cursor == el->el_line.lastchar)
+ return CC_ERROR;
+
+ el->el_line.cursor = cv__endword(el->el_line.cursor,
+ el->el_line.lastchar, el->el_state.argument, cv__isWord);
+
+ if (el->el_chared.c_vcmd.action != NOP) {
+ el->el_line.cursor++;
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+ return CC_CURSOR;
+}
+
+
+/* vi_end_word():
+ * Vi move to the end of the current word
+ * [e]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_end_word(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ if (el->el_line.cursor == el->el_line.lastchar)
+ return CC_ERROR;
+
+ el->el_line.cursor = cv__endword(el->el_line.cursor,
+ el->el_line.lastchar, el->el_state.argument, cv__isword);
+
+ if (el->el_chared.c_vcmd.action != NOP) {
+ el->el_line.cursor++;
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+ return CC_CURSOR;
+}
+
+
+/* vi_undo():
+ * Vi undo last change
+ * [u]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_undo(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ c_undo_t un = el->el_chared.c_undo;
+
+ if (un.len == -1)
+ return CC_ERROR;
+
+ /* switch line buffer and undo buffer */
+ el->el_chared.c_undo.buf = el->el_line.buffer;
+ el->el_chared.c_undo.len = el->el_line.lastchar - el->el_line.buffer;
+ el->el_chared.c_undo.cursor =
+ (int)(el->el_line.cursor - el->el_line.buffer);
+ el->el_line.limit = un.buf + (el->el_line.limit - el->el_line.buffer);
+ el->el_line.buffer = un.buf;
+ el->el_line.cursor = un.buf + un.cursor;
+ el->el_line.lastchar = un.buf + un.len;
+
+ return CC_REFRESH;
+}
+
+
+/* vi_command_mode():
+ * Vi enter command mode (use alternative key bindings)
+ * [<ESC>]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_command_mode(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ /* [Esc] cancels pending action */
+ el->el_chared.c_vcmd.action = NOP;
+ el->el_chared.c_vcmd.pos = 0;
+
+ el->el_state.doingarg = 0;
+
+ el->el_state.inputmode = MODE_INSERT;
+ el->el_map.current = el->el_map.alt;
+#ifdef VI_MOVE
+ if (el->el_line.cursor > el->el_line.buffer)
+ el->el_line.cursor--;
+#endif
+ return CC_CURSOR;
+}
+
+
+/* vi_zero():
+ * Vi move to the beginning of line
+ * [0]
+ */
+libedit_private el_action_t
+vi_zero(EditLine *el, wint_t c)
+{
+
+ if (el->el_state.doingarg)
+ return ed_argument_digit(el, c);
+
+ el->el_line.cursor = el->el_line.buffer;
+ if (el->el_chared.c_vcmd.action != NOP) {
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+ return CC_CURSOR;
+}
+
+
+/* vi_delete_prev_char():
+ * Vi move to previous character (backspace)
+ * [^H] in insert mode only
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_delete_prev_char(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ if (el->el_line.cursor <= el->el_line.buffer)
+ return CC_ERROR;
+
+ c_delbefore1(el);
+ el->el_line.cursor--;
+ return CC_REFRESH;
+}
+
+
+/* vi_list_or_eof():
+ * Vi list choices for completion or indicate end of file if empty line
+ * [^D]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_list_or_eof(EditLine *el, wint_t c)
+{
+
+ if (el->el_line.cursor == el->el_line.lastchar) {
+ if (el->el_line.cursor == el->el_line.buffer) {
+ terminal_writec(el, c); /* then do a EOF */
+ return CC_EOF;
+ } else {
+ /*
+ * Here we could list completions, but it is an
+ * error right now
+ */
+ terminal_beep(el);
+ return CC_ERROR;
+ }
+ } else {
+#ifdef notyet
+ re_goto_bottom(el);
+ *el->el_line.lastchar = '\0'; /* just in case */
+ return CC_LIST_CHOICES;
+#else
+ /*
+ * Just complain for now.
+ */
+ terminal_beep(el);
+ return CC_ERROR;
+#endif
+ }
+}
+
+
+/* vi_kill_line_prev():
+ * Vi cut from beginning of line to cursor
+ * [^U]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_kill_line_prev(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ wchar_t *kp, *cp;
+
+ cp = el->el_line.buffer;
+ kp = el->el_chared.c_kill.buf;
+ while (cp < el->el_line.cursor)
+ *kp++ = *cp++; /* copy it */
+ el->el_chared.c_kill.last = kp;
+ c_delbefore(el, (int)(el->el_line.cursor - el->el_line.buffer));
+ el->el_line.cursor = el->el_line.buffer; /* zap! */
+ return CC_REFRESH;
+}
+
+
+/* vi_search_prev():
+ * Vi search history previous
+ * [?]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_search_prev(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ return cv_search(el, ED_SEARCH_PREV_HISTORY);
+}
+
+
+/* vi_search_next():
+ * Vi search history next
+ * [/]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_search_next(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ return cv_search(el, ED_SEARCH_NEXT_HISTORY);
+}
+
+
+/* vi_repeat_search_next():
+ * Vi repeat current search in the same search direction
+ * [n]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_repeat_search_next(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ if (el->el_search.patlen == 0)
+ return CC_ERROR;
+ else
+ return cv_repeat_srch(el, el->el_search.patdir);
+}
+
+
+/* vi_repeat_search_prev():
+ * Vi repeat current search in the opposite search direction
+ * [N]
+ */
+/*ARGSUSED*/
+libedit_private el_action_t
+vi_repeat_search_prev(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ if (el->el_search.patlen == 0)
+ return CC_ERROR;
+ else
+ return (cv_repeat_srch(el,
+ el->el_search.patdir == ED_SEARCH_PREV_HISTORY ?
+ ED_SEARCH_NEXT_HISTORY : ED_SEARCH_PREV_HISTORY));
+}
+
+
+/* vi_next_char():
+ * Vi move to the character specified next
+ * [f]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_next_char(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ return cv_csearch(el, CHAR_FWD, -1, el->el_state.argument, 0);
+}
+
+
+/* vi_prev_char():
+ * Vi move to the character specified previous
+ * [F]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_prev_char(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ return cv_csearch(el, CHAR_BACK, -1, el->el_state.argument, 0);
+}
+
+
+/* vi_to_next_char():
+ * Vi move up to the character specified next
+ * [t]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_to_next_char(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ return cv_csearch(el, CHAR_FWD, -1, el->el_state.argument, 1);
+}
+
+
+/* vi_to_prev_char():
+ * Vi move up to the character specified previous
+ * [T]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_to_prev_char(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ return cv_csearch(el, CHAR_BACK, -1, el->el_state.argument, 1);
+}
+
+
+/* vi_repeat_next_char():
+ * Vi repeat current character search in the same search direction
+ * [;]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_repeat_next_char(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ return cv_csearch(el, el->el_search.chadir, el->el_search.chacha,
+ el->el_state.argument, el->el_search.chatflg);
+}
+
+
+/* vi_repeat_prev_char():
+ * Vi repeat current character search in the opposite search direction
+ * [,]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_repeat_prev_char(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ el_action_t r;
+ int dir = el->el_search.chadir;
+
+ r = cv_csearch(el, -dir, el->el_search.chacha,
+ el->el_state.argument, el->el_search.chatflg);
+ el->el_search.chadir = dir;
+ return r;
+}
+
+
+/* vi_match():
+ * Vi go to matching () {} or []
+ * [%]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_match(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ const wchar_t match_chars[] = L"()[]{}";
+ wchar_t *cp;
+ size_t delta, i, count;
+ wchar_t o_ch, c_ch;
+
+ *el->el_line.lastchar = '\0'; /* just in case */
+
+ i = wcscspn(el->el_line.cursor, match_chars);
+ o_ch = el->el_line.cursor[i];
+ if (o_ch == 0)
+ return CC_ERROR;
+ delta = (size_t)(wcschr(match_chars, o_ch) - match_chars);
+ c_ch = match_chars[delta ^ 1];
+ count = 1;
+ delta = 1 - (delta & 1) * 2;
+
+ for (cp = &el->el_line.cursor[i]; count; ) {
+ cp += delta;
+ if (cp < el->el_line.buffer || cp >= el->el_line.lastchar)
+ return CC_ERROR;
+ if (*cp == o_ch)
+ count++;
+ else if (*cp == c_ch)
+ count--;
+ }
+
+ el->el_line.cursor = cp;
+
+ if (el->el_chared.c_vcmd.action != NOP) {
+ /* NB posix says char under cursor should NOT be deleted
+ for -ve delta - this is different to netbsd vi. */
+ if (delta > 0)
+ el->el_line.cursor++;
+ cv_delfini(el);
+ return CC_REFRESH;
+ }
+ return CC_CURSOR;
+}
+
+/* vi_undo_line():
+ * Vi undo all changes to line
+ * [U]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_undo_line(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ cv_undo(el);
+ return hist_get(el);
+}
+
+/* vi_to_column():
+ * Vi go to specified column
+ * [|]
+ * NB netbsd vi goes to screen column 'n', posix says nth character
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_to_column(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ el->el_line.cursor = el->el_line.buffer;
+ el->el_state.argument--;
+ return ed_next_char(el, 0);
+}
+
+/* vi_yank_end():
+ * Vi yank to end of line
+ * [Y]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_yank_end(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ cv_yank(el, el->el_line.cursor,
+ (int)(el->el_line.lastchar - el->el_line.cursor));
+ return CC_REFRESH;
+}
+
+/* vi_yank():
+ * Vi yank
+ * [y]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_yank(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ return cv_action(el, YANK);
+}
+
+/* vi_comment_out():
+ * Vi comment out current command
+ * [#]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_comment_out(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+
+ el->el_line.cursor = el->el_line.buffer;
+ c_insert(el, 1);
+ *el->el_line.cursor = '#';
+ re_refresh(el);
+ return ed_newline(el, 0);
+}
+
+/* vi_alias():
+ * Vi include shell alias
+ * [@]
+ * NB: posix implies that we should enter insert mode, however
+ * this is against historical precedent...
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_alias(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ char alias_name[3];
+ const char *alias_text;
+
+ if (el->el_chared.c_aliasfun == NULL)
+ return CC_ERROR;
+
+ alias_name[0] = '_';
+ alias_name[2] = 0;
+ if (el_getc(el, &alias_name[1]) != 1)
+ return CC_ERROR;
+
+ alias_text = (*el->el_chared.c_aliasfun)(el->el_chared.c_aliasarg,
+ alias_name);
+ if (alias_text != NULL)
+ el_wpush(el, ct_decode_string(alias_text, &el->el_scratch));
+ return CC_NORM;
+}
+
+/* vi_to_history_line():
+ * Vi go to specified history file line.
+ * [G]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_to_history_line(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ int sv_event_no = el->el_history.eventno;
+ el_action_t rval;
+
+
+ if (el->el_history.eventno == 0) {
+ (void) wcsncpy(el->el_history.buf, el->el_line.buffer,
+ EL_BUFSIZ);
+ el->el_history.last = el->el_history.buf +
+ (el->el_line.lastchar - el->el_line.buffer);
+ }
+
+ /* Lack of a 'count' means oldest, not 1 */
+ if (!el->el_state.doingarg) {
+ el->el_history.eventno = 0x7fffffff;
+ hist_get(el);
+ } else {
+ /* This is brain dead, all the rest of this code counts
+ * upwards going into the past. Here we need count in the
+ * other direction (to match the output of fc -l).
+ * I could change the world, but this seems to suffice.
+ */
+ el->el_history.eventno = 1;
+ if (hist_get(el) == CC_ERROR)
+ return CC_ERROR;
+ el->el_history.eventno = 1 + el->el_history.ev.num
+ - el->el_state.argument;
+ if (el->el_history.eventno < 0) {
+ el->el_history.eventno = sv_event_no;
+ return CC_ERROR;
+ }
+ }
+ rval = hist_get(el);
+ if (rval == CC_ERROR)
+ el->el_history.eventno = sv_event_no;
+ return rval;
+}
+
+/* vi_histedit():
+ * Vi edit history line with vi
+ * [v]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_histedit(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ int fd;
+ pid_t pid;
+ ssize_t st;
+ int status;
+ char tempfile[] = "/tmp/histedit.XXXXXXXXXX";
+ char *cp = NULL;
+ size_t len;
+ wchar_t *line = NULL;
+
+ if (el->el_state.doingarg) {
+ if (vi_to_history_line(el, 0) == CC_ERROR)
+ return CC_ERROR;
+ }
+
+ fd = mkstemp(tempfile);
+ if (fd < 0)
+ return CC_ERROR;
+ len = (size_t)(el->el_line.lastchar - el->el_line.buffer);
+#define TMP_BUFSIZ (EL_BUFSIZ * MB_LEN_MAX)
+ cp = el_malloc(TMP_BUFSIZ * sizeof(*cp));
+ if (cp == NULL)
+ goto error;
+ line = el_malloc(len * sizeof(*line) + 1);
+ if (line == NULL)
+ goto error;
+ wcsncpy(line, el->el_line.buffer, len);
+ line[len] = '\0';
+ wcstombs(cp, line, TMP_BUFSIZ - 1);
+ cp[TMP_BUFSIZ - 1] = '\0';
+ len = strlen(cp);
+ write(fd, cp, len);
+ write(fd, "\n", (size_t)1);
+ pid = fork();
+ switch (pid) {
+ case -1:
+ goto error;
+ case 0:
+ close(fd);
+ execlp("vi", "vi", tempfile, (char *)NULL);
+ exit(0);
+ /*NOTREACHED*/
+ default:
+ while (waitpid(pid, &status, 0) != pid)
+ continue;
+ lseek(fd, (off_t)0, SEEK_SET);
+ st = read(fd, cp, TMP_BUFSIZ - 1);
+ if (st > 0) {
+ cp[st] = '\0';
+ len = (size_t)(el->el_line.limit - el->el_line.buffer);
+ len = mbstowcs(el->el_line.buffer, cp, len);
+ if (len > 0 && el->el_line.buffer[len - 1] == '\n')
+ --len;
+ }
+ else
+ len = 0;
+ el->el_line.cursor = el->el_line.buffer;
+ el->el_line.lastchar = el->el_line.buffer + len;
+ el_free(cp);
+ el_free(line);
+ break;
+ }
+
+ close(fd);
+ unlink(tempfile);
+ /* return CC_REFRESH; */
+ return ed_newline(el, 0);
+error:
+ el_free(line);
+ el_free(cp);
+ close(fd);
+ unlink(tempfile);
+ return CC_ERROR;
+}
+
+/* vi_history_word():
+ * Vi append word from previous input line
+ * [_]
+ * Who knows where this one came from!
+ * '_' in vi means 'entire current line', so 'cc' is a synonym for 'c_'
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_history_word(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ const wchar_t *wp = HIST_FIRST(el);
+ const wchar_t *wep, *wsp;
+ int len;
+ wchar_t *cp;
+ const wchar_t *lim;
+
+ if (wp == NULL)
+ return CC_ERROR;
+
+ wep = wsp = NULL;
+ do {
+ while (iswspace(*wp))
+ wp++;
+ if (*wp == 0)
+ break;
+ wsp = wp;
+ while (*wp && !iswspace(*wp))
+ wp++;
+ wep = wp;
+ } while ((!el->el_state.doingarg || --el->el_state.argument > 0)
+ && *wp != 0);
+
+ if (wsp == NULL || (el->el_state.doingarg && el->el_state.argument != 0))
+ return CC_ERROR;
+
+ cv_undo(el);
+ len = (int)(wep - wsp);
+ if (el->el_line.cursor < el->el_line.lastchar)
+ el->el_line.cursor++;
+ c_insert(el, len + 1);
+ cp = el->el_line.cursor;
+ lim = el->el_line.limit;
+ if (cp < lim)
+ *cp++ = ' ';
+ while (wsp < wep && cp < lim)
+ *cp++ = *wsp++;
+ el->el_line.cursor = cp;
+
+ el->el_map.current = el->el_map.key;
+ return CC_REFRESH;
+}
+
+/* vi_redo():
+ * Vi redo last non-motion command
+ * [.]
+ */
+libedit_private el_action_t
+/*ARGSUSED*/
+vi_redo(EditLine *el, wint_t c __attribute__((__unused__)))
+{
+ c_redo_t *r = &el->el_chared.c_redo;
+
+ if (!el->el_state.doingarg && r->count) {
+ el->el_state.doingarg = 1;
+ el->el_state.argument = r->count;
+ }
+
+ el->el_chared.c_vcmd.pos = el->el_line.cursor;
+ el->el_chared.c_vcmd.action = r->action;
+ if (r->pos != r->buf) {
+ if (r->pos + 1 > r->lim)
+ /* sanity */
+ r->pos = r->lim - 1;
+ r->pos[0] = 0;
+ el_wpush(el, r->buf);
+ }
+
+ el->el_state.thiscmd = r->cmd;
+ el->el_state.thisch = r->ch;
+ return (*el->el_map.func[r->cmd])(el, r->ch);
+}
diff --git a/third_party/heimdal/lib/libedit/src/vis.c b/third_party/heimdal/lib/libedit/src/vis.c
new file mode 100644
index 0000000..1071803
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/vis.c
@@ -0,0 +1,728 @@
+/* $NetBSD: vis.c,v 1.71 2016/01/14 20:41:23 christos Exp $ */
+
+/*-
+ * Copyright (c) 1989, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*-
+ * Copyright (c) 1999, 2005 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: vis.c,v 1.71 2016/01/14 20:41:23 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/param.h>
+
+#include <assert.h>
+#include <vis.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#if !HAVE_VIS || !HAVE_SVIS
+#include <ctype.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+
+/*
+ * The reason for going through the trouble to deal with character encodings
+ * in vis(3), is that we use this to safe encode output of commands. This
+ * safe encoding varies depending on the character set. For example if we
+ * display ps output in French, we don't want to display French characters
+ * as M-foo.
+ */
+
+static wchar_t *do_svis(wchar_t *, wint_t, int, wint_t, const wchar_t *);
+
+#undef BELL
+#define BELL L'\a'
+
+#if defined(LC_C_LOCALE)
+#define iscgraph(c) isgraph_l(c, LC_C_LOCALE)
+#else
+/* Keep it simple for now, no locale stuff */
+#define iscgraph(c) isgraph(c)
+#ifdef notyet
+#include <locale.h>
+static int
+iscgraph(int c) {
+ int rv;
+ char *ol;
+
+ ol = setlocale(LC_CTYPE, "C");
+ rv = isgraph(c);
+ if (ol)
+ setlocale(LC_CTYPE, ol);
+ return rv;
+}
+#endif
+#endif
+
+#define ISGRAPH(flags, c) \
+ (((flags) & VIS_NOLOCALE) ? iscgraph(c) : iswgraph(c))
+
+#define iswoctal(c) (((u_char)(c)) >= L'0' && ((u_char)(c)) <= L'7')
+#define iswwhite(c) (c == L' ' || c == L'\t' || c == L'\n')
+#define iswsafe(c) (c == L'\b' || c == BELL || c == L'\r')
+#define xtoa(c) L"0123456789abcdef"[c]
+#define XTOA(c) L"0123456789ABCDEF"[c]
+
+#define MAXEXTRAS 30
+
+static const wchar_t char_shell[] = L"'`\";&<>()|{}]\\$!^~";
+static const wchar_t char_glob[] = L"*?[#";
+
+/*
+ * This is do_hvis, for HTTP style (RFC 1808)
+ */
+static wchar_t *
+do_hvis(wchar_t *dst, wint_t c, int flags, wint_t nextc, const wchar_t *extra)
+{
+ if (iswalnum(c)
+ /* safe */
+ || c == L'$' || c == L'-' || c == L'_' || c == L'.' || c == L'+'
+ /* extra */
+ || c == L'!' || c == L'*' || c == L'\'' || c == L'(' || c == L')'
+ || c == L',')
+ dst = do_svis(dst, c, flags, nextc, extra);
+ else {
+ *dst++ = L'%';
+ *dst++ = xtoa(((unsigned int)c >> 4) & 0xf);
+ *dst++ = xtoa((unsigned int)c & 0xf);
+ }
+
+ return dst;
+}
+
+/*
+ * This is do_mvis, for Quoted-Printable MIME (RFC 2045)
+ * NB: No handling of long lines or CRLF.
+ */
+static wchar_t *
+do_mvis(wchar_t *dst, wint_t c, int flags, wint_t nextc, const wchar_t *extra)
+{
+ if ((c != L'\n') &&
+ /* Space at the end of the line */
+ ((iswspace(c) && (nextc == L'\r' || nextc == L'\n')) ||
+ /* Out of range */
+ (!iswspace(c) && (c < 33 || (c > 60 && c < 62) || c > 126)) ||
+ /* Specific char to be escaped */
+ wcschr(L"#$@[\\]^`{|}~", c) != NULL)) {
+ *dst++ = L'=';
+ *dst++ = XTOA(((unsigned int)c >> 4) & 0xf);
+ *dst++ = XTOA((unsigned int)c & 0xf);
+ } else
+ dst = do_svis(dst, c, flags, nextc, extra);
+ return dst;
+}
+
+/*
+ * Output single byte of multibyte character.
+ */
+static wchar_t *
+do_mbyte(wchar_t *dst, wint_t c, int flags, wint_t nextc, int iswextra)
+{
+ if (flags & VIS_CSTYLE) {
+ switch (c) {
+ case L'\n':
+ *dst++ = L'\\'; *dst++ = L'n';
+ return dst;
+ case L'\r':
+ *dst++ = L'\\'; *dst++ = L'r';
+ return dst;
+ case L'\b':
+ *dst++ = L'\\'; *dst++ = L'b';
+ return dst;
+ case BELL:
+ *dst++ = L'\\'; *dst++ = L'a';
+ return dst;
+ case L'\v':
+ *dst++ = L'\\'; *dst++ = L'v';
+ return dst;
+ case L'\t':
+ *dst++ = L'\\'; *dst++ = L't';
+ return dst;
+ case L'\f':
+ *dst++ = L'\\'; *dst++ = L'f';
+ return dst;
+ case L' ':
+ *dst++ = L'\\'; *dst++ = L's';
+ return dst;
+ case L'\0':
+ *dst++ = L'\\'; *dst++ = L'0';
+ if (iswoctal(nextc)) {
+ *dst++ = L'0';
+ *dst++ = L'0';
+ }
+ return dst;
+ /* We cannot encode these characters in VIS_CSTYLE
+ * because they special meaning */
+ case L'n':
+ case L'r':
+ case L'b':
+ case L'a':
+ case L'v':
+ case L't':
+ case L'f':
+ case L's':
+ case L'0':
+ case L'M':
+ case L'^':
+ case L'$': /* vis(1) -l */
+ break;
+ default:
+ if (ISGRAPH(flags, c) && !iswoctal(c)) {
+ *dst++ = L'\\';
+ *dst++ = c;
+ return dst;
+ }
+ }
+ }
+ if (iswextra || ((c & 0177) == L' ') || (flags & VIS_OCTAL)) {
+ *dst++ = L'\\';
+ *dst++ = (u_char)(((u_int32_t)(u_char)c >> 6) & 03) + L'0';
+ *dst++ = (u_char)(((u_int32_t)(u_char)c >> 3) & 07) + L'0';
+ *dst++ = (c & 07) + L'0';
+ } else {
+ if ((flags & VIS_NOSLASH) == 0)
+ *dst++ = L'\\';
+
+ if (c & 0200) {
+ c &= 0177;
+ *dst++ = L'M';
+ }
+
+ if (iswcntrl(c)) {
+ *dst++ = L'^';
+ if (c == 0177)
+ *dst++ = L'?';
+ else
+ *dst++ = c + L'@';
+ } else {
+ *dst++ = L'-';
+ *dst++ = c;
+ }
+ }
+
+ return dst;
+}
+
+/*
+ * This is do_vis, the central code of vis.
+ * dst: Pointer to the destination buffer
+ * c: Character to encode
+ * flags: Flags word
+ * nextc: The character following 'c'
+ * extra: Pointer to the list of extra characters to be
+ * backslash-protected.
+ */
+static wchar_t *
+do_svis(wchar_t *dst, wint_t c, int flags, wint_t nextc, const wchar_t *extra)
+{
+ int iswextra, i, shft;
+ uint64_t bmsk, wmsk;
+
+ iswextra = wcschr(extra, c) != NULL;
+ if (!iswextra && (ISGRAPH(flags, c) || iswwhite(c) ||
+ ((flags & VIS_SAFE) && iswsafe(c)))) {
+ *dst++ = c;
+ return dst;
+ }
+
+ /* See comment in istrsenvisx() output loop, below. */
+ wmsk = 0;
+ for (i = sizeof(wmsk) - 1; i >= 0; i--) {
+ shft = i * NBBY;
+ bmsk = (uint64_t)0xffLL << shft;
+ wmsk |= bmsk;
+ if ((c & wmsk) || i == 0)
+ dst = do_mbyte(dst, (wint_t)(
+ (uint64_t)(c & bmsk) >> shft),
+ flags, nextc, iswextra);
+ }
+
+ return dst;
+}
+
+typedef wchar_t *(*visfun_t)(wchar_t *, wint_t, int, wint_t, const wchar_t *);
+
+/*
+ * Return the appropriate encoding function depending on the flags given.
+ */
+static visfun_t
+getvisfun(int flags)
+{
+ if (flags & VIS_HTTPSTYLE)
+ return do_hvis;
+ if (flags & VIS_MIMESTYLE)
+ return do_mvis;
+ return do_svis;
+}
+
+/*
+ * Expand list of extra characters to not visually encode.
+ */
+static wchar_t *
+makeextralist(int flags, const char *src)
+{
+ wchar_t *dst, *d;
+ size_t len;
+ const wchar_t *s;
+
+ len = strlen(src);
+ if ((dst = calloc(len + MAXEXTRAS, sizeof(*dst))) == NULL)
+ return NULL;
+
+ if ((flags & VIS_NOLOCALE) || mbstowcs(dst, src, len) == (size_t)-1) {
+ size_t i;
+ for (i = 0; i < len; i++)
+ dst[i] = (wchar_t)(u_char)src[i];
+ d = dst + len;
+ } else
+ d = dst + wcslen(dst);
+
+ if (flags & VIS_GLOB)
+ for (s = char_glob; *s; *d++ = *s++)
+ continue;
+
+ if (flags & VIS_SHELL)
+ for (s = char_shell; *s; *d++ = *s++)
+ continue;
+
+ if (flags & VIS_SP) *d++ = L' ';
+ if (flags & VIS_TAB) *d++ = L'\t';
+ if (flags & VIS_NL) *d++ = L'\n';
+ if ((flags & VIS_NOSLASH) == 0) *d++ = L'\\';
+ *d = L'\0';
+
+ return dst;
+}
+
+/*
+ * istrsenvisx()
+ * The main internal function.
+ * All user-visible functions call this one.
+ */
+static int
+istrsenvisx(char **mbdstp, size_t *dlen, const char *mbsrc, size_t mblength,
+ int flags, const char *mbextra, int *cerr_ptr)
+{
+ wchar_t *dst, *src, *pdst, *psrc, *start, *extra;
+ size_t len, olen;
+ uint64_t bmsk, wmsk;
+ wint_t c;
+ visfun_t f;
+ int clen = 0, cerr, error = -1, i, shft;
+ char *mbdst, *mdst;
+ ssize_t mbslength, maxolen;
+
+ _DIAGASSERT(mbdstp != NULL);
+ _DIAGASSERT(mbsrc != NULL || mblength == 0);
+ _DIAGASSERT(mbextra != NULL);
+
+ /*
+ * Input (mbsrc) is a char string considered to be multibyte
+ * characters. The input loop will read this string pulling
+ * one character, possibly multiple bytes, from mbsrc and
+ * converting each to wchar_t in src.
+ *
+ * The vis conversion will be done using the wide char
+ * wchar_t string.
+ *
+ * This will then be converted back to a multibyte string to
+ * return to the caller.
+ */
+
+ /* Allocate space for the wide char strings */
+ psrc = pdst = extra = NULL;
+ mdst = NULL;
+ if ((psrc = calloc(mblength + 1, sizeof(*psrc))) == NULL)
+ return -1;
+ if ((pdst = calloc((4 * mblength) + 1, sizeof(*pdst))) == NULL)
+ goto out;
+ if (*mbdstp == NULL) {
+ if ((mdst = calloc((4 * mblength) + 1, sizeof(*mdst))) == NULL)
+ goto out;
+ *mbdstp = mdst;
+ }
+
+ mbdst = *mbdstp;
+ dst = pdst;
+ src = psrc;
+
+ if (flags & VIS_NOLOCALE) {
+ /* Do one byte at a time conversion */
+ cerr = 1;
+ } else {
+ /* Use caller's multibyte conversion error flag. */
+ cerr = cerr_ptr ? *cerr_ptr : 0;
+ }
+
+ /*
+ * Input loop.
+ * Handle up to mblength characters (not bytes). We do not
+ * stop at NULs because we may be processing a block of data
+ * that includes NULs.
+ */
+ mbslength = (ssize_t)mblength;
+ /*
+ * When inputing a single character, must also read in the
+ * next character for nextc, the look-ahead character.
+ */
+ if (mbslength == 1)
+ mbslength++;
+ while (mbslength > 0) {
+ /* Convert one multibyte character to wchar_t. */
+ if (!cerr)
+ clen = mbtowc(src, mbsrc, MB_LEN_MAX);
+ if (cerr || clen < 0) {
+ /* Conversion error, process as a byte instead. */
+ *src = (wint_t)(u_char)*mbsrc;
+ clen = 1;
+ cerr = 1;
+ }
+ if (clen == 0)
+ /*
+ * NUL in input gives 0 return value. process
+ * as single NUL byte and keep going.
+ */
+ clen = 1;
+ /* Advance buffer character pointer. */
+ src++;
+ /* Advance input pointer by number of bytes read. */
+ mbsrc += clen;
+ /* Decrement input byte count. */
+ mbslength -= clen;
+ }
+ len = src - psrc;
+ src = psrc;
+ /*
+ * In the single character input case, we will have actually
+ * processed two characters, c and nextc. Reset len back to
+ * just a single character.
+ */
+ if (mblength < len)
+ len = mblength;
+
+ /* Convert extra argument to list of characters for this mode. */
+ extra = makeextralist(flags, mbextra);
+ if (!extra) {
+ if (dlen && *dlen == 0) {
+ errno = ENOSPC;
+ goto out;
+ }
+ *mbdst = '\0'; /* can't create extra, return "" */
+ error = 0;
+ goto out;
+ }
+
+ /* Look up which processing function to call. */
+ f = getvisfun(flags);
+
+ /*
+ * Main processing loop.
+ * Call do_Xvis processing function one character at a time
+ * with next character available for look-ahead.
+ */
+ for (start = dst; len > 0; len--) {
+ c = *src++;
+ dst = (*f)(dst, c, flags, len >= 1 ? *src : L'\0', extra);
+ if (dst == NULL) {
+ errno = ENOSPC;
+ goto out;
+ }
+ }
+
+ /* Terminate the string in the buffer. */
+ *dst = L'\0';
+
+ /*
+ * Output loop.
+ * Convert wchar_t string back to multibyte output string.
+ * If we have hit a multi-byte conversion error on input,
+ * output byte-by-byte here. Else use wctomb().
+ */
+ len = wcslen(start);
+ maxolen = dlen ? *dlen : (wcslen(start) * MB_LEN_MAX + 1);
+ olen = 0;
+ for (dst = start; len > 0; len--) {
+ if (!cerr)
+ clen = wctomb(mbdst, *dst);
+ if (cerr || clen < 0) {
+ /*
+ * Conversion error, process as a byte(s) instead.
+ * Examine each byte and higher-order bytes for
+ * data. E.g.,
+ * 0x000000000000a264 -> a2 64
+ * 0x000000001f00a264 -> 1f 00 a2 64
+ */
+ clen = 0;
+ wmsk = 0;
+ for (i = sizeof(wmsk) - 1; i >= 0; i--) {
+ shft = i * NBBY;
+ bmsk = (uint64_t)0xffLL << shft;
+ wmsk |= bmsk;
+ if ((*dst & wmsk) || i == 0)
+ mbdst[clen++] = (char)(
+ (uint64_t)(*dst & bmsk) >>
+ shft);
+ }
+ cerr = 1;
+ }
+ /* If this character would exceed our output limit, stop. */
+ if (olen + clen > (size_t)maxolen)
+ break;
+ /* Advance output pointer by number of bytes written. */
+ mbdst += clen;
+ /* Advance buffer character pointer. */
+ dst++;
+ /* Incrment output character count. */
+ olen += clen;
+ }
+
+ /* Terminate the output string. */
+ *mbdst = '\0';
+
+ if (flags & VIS_NOLOCALE) {
+ /* Pass conversion error flag out. */
+ if (cerr_ptr)
+ *cerr_ptr = cerr;
+ }
+
+ free(extra);
+ free(pdst);
+ free(psrc);
+
+ return (int)olen;
+out:
+ free(extra);
+ free(pdst);
+ free(psrc);
+ free(mdst);
+ return error;
+}
+
+static int
+istrsenvisxl(char **mbdstp, size_t *dlen, const char *mbsrc,
+ int flags, const char *mbextra, int *cerr_ptr)
+{
+ return istrsenvisx(mbdstp, dlen, mbsrc,
+ mbsrc != NULL ? strlen(mbsrc) : 0, flags, mbextra, cerr_ptr);
+}
+
+#endif
+
+#if !HAVE_SVIS
+/*
+ * The "svis" variants all take an "extra" arg that is a pointer
+ * to a NUL-terminated list of characters to be encoded, too.
+ * These functions are useful e. g. to encode strings in such a
+ * way so that they are not interpreted by a shell.
+ */
+
+char *
+svis(char *mbdst, int c, int flags, int nextc, const char *mbextra)
+{
+ char cc[2];
+ int ret;
+
+ cc[0] = c;
+ cc[1] = nextc;
+
+ ret = istrsenvisx(&mbdst, NULL, cc, 1, flags, mbextra, NULL);
+ if (ret < 0)
+ return NULL;
+ return mbdst + ret;
+}
+
+char *
+snvis(char *mbdst, size_t dlen, int c, int flags, int nextc, const char *mbextra)
+{
+ char cc[2];
+ int ret;
+
+ cc[0] = c;
+ cc[1] = nextc;
+
+ ret = istrsenvisx(&mbdst, &dlen, cc, 1, flags, mbextra, NULL);
+ if (ret < 0)
+ return NULL;
+ return mbdst + ret;
+}
+
+int
+strsvis(char *mbdst, const char *mbsrc, int flags, const char *mbextra)
+{
+ return istrsenvisxl(&mbdst, NULL, mbsrc, flags, mbextra, NULL);
+}
+
+int
+strsnvis(char *mbdst, size_t dlen, const char *mbsrc, int flags, const char *mbextra)
+{
+ return istrsenvisxl(&mbdst, &dlen, mbsrc, flags, mbextra, NULL);
+}
+
+int
+strsvisx(char *mbdst, const char *mbsrc, size_t len, int flags, const char *mbextra)
+{
+ return istrsenvisx(&mbdst, NULL, mbsrc, len, flags, mbextra, NULL);
+}
+
+int
+strsnvisx(char *mbdst, size_t dlen, const char *mbsrc, size_t len, int flags,
+ const char *mbextra)
+{
+ return istrsenvisx(&mbdst, &dlen, mbsrc, len, flags, mbextra, NULL);
+}
+
+int
+strsenvisx(char *mbdst, size_t dlen, const char *mbsrc, size_t len, int flags,
+ const char *mbextra, int *cerr_ptr)
+{
+ return istrsenvisx(&mbdst, &dlen, mbsrc, len, flags, mbextra, cerr_ptr);
+}
+#endif
+
+#if !HAVE_VIS
+/*
+ * vis - visually encode characters
+ */
+char *
+vis(char *mbdst, int c, int flags, int nextc)
+{
+ char cc[2];
+ int ret;
+
+ cc[0] = c;
+ cc[1] = nextc;
+
+ ret = istrsenvisx(&mbdst, NULL, cc, 1, flags, "", NULL);
+ if (ret < 0)
+ return NULL;
+ return mbdst + ret;
+}
+
+char *
+nvis(char *mbdst, size_t dlen, int c, int flags, int nextc)
+{
+ char cc[2];
+ int ret;
+
+ cc[0] = c;
+ cc[1] = nextc;
+
+ ret = istrsenvisx(&mbdst, &dlen, cc, 1, flags, "", NULL);
+ if (ret < 0)
+ return NULL;
+ return mbdst + ret;
+}
+
+/*
+ * strvis - visually encode characters from src into dst
+ *
+ * Dst must be 4 times the size of src to account for possible
+ * expansion. The length of dst, not including the trailing NULL,
+ * is returned.
+ */
+
+int
+strvis(char *mbdst, const char *mbsrc, int flags)
+{
+ return istrsenvisxl(&mbdst, NULL, mbsrc, flags, "", NULL);
+}
+
+int
+strnvis(char *mbdst, size_t dlen, const char *mbsrc, int flags)
+{
+ return istrsenvisxl(&mbdst, &dlen, mbsrc, flags, "", NULL);
+}
+
+int
+stravis(char **mbdstp, const char *mbsrc, int flags)
+{
+ *mbdstp = NULL;
+ return istrsenvisxl(mbdstp, NULL, mbsrc, flags, "", NULL);
+}
+
+/*
+ * strvisx - visually encode characters from src into dst
+ *
+ * Dst must be 4 times the size of src to account for possible
+ * expansion. The length of dst, not including the trailing NULL,
+ * is returned.
+ *
+ * Strvisx encodes exactly len characters from src into dst.
+ * This is useful for encoding a block of data.
+ */
+
+int
+strvisx(char *mbdst, const char *mbsrc, size_t len, int flags)
+{
+ return istrsenvisx(&mbdst, NULL, mbsrc, len, flags, "", NULL);
+}
+
+int
+strnvisx(char *mbdst, size_t dlen, const char *mbsrc, size_t len, int flags)
+{
+ return istrsenvisx(&mbdst, &dlen, mbsrc, len, flags, "", NULL);
+}
+
+int
+strenvisx(char *mbdst, size_t dlen, const char *mbsrc, size_t len, int flags,
+ int *cerr_ptr)
+{
+ return istrsenvisx(&mbdst, &dlen, mbsrc, len, flags, "", cerr_ptr);
+}
+#endif
diff --git a/third_party/heimdal/lib/libedit/src/vis.h b/third_party/heimdal/lib/libedit/src/vis.h
new file mode 100644
index 0000000..ddd597b
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/vis.h
@@ -0,0 +1,120 @@
+/* $NetBSD: vis.h,v 1.24 2016/01/14 20:42:14 christos Exp $ */
+
+/*-
+ * Copyright (c) 1990, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)vis.h 8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _VIS_H_
+#define _VIS_H_
+
+#include <sys/types.h>
+
+/*
+ * to select alternate encoding format
+ */
+#define VIS_OCTAL 0x0001 /* use octal \ddd format */
+#define VIS_CSTYLE 0x0002 /* use \[nrft0..] where appropiate */
+
+/*
+ * to alter set of characters encoded (default is to encode all
+ * non-graphic except space, tab, and newline).
+ */
+#define VIS_SP 0x0004 /* also encode space */
+#define VIS_TAB 0x0008 /* also encode tab */
+#define VIS_NL 0x0010 /* also encode newline */
+#define VIS_WHITE (VIS_SP | VIS_TAB | VIS_NL)
+#define VIS_SAFE 0x0020 /* only encode "unsafe" characters */
+
+/*
+ * other
+ */
+#define VIS_NOSLASH 0x0040 /* inhibit printing '\' */
+#define VIS_HTTP1808 0x0080 /* http-style escape % hex hex */
+#define VIS_HTTPSTYLE 0x0080 /* http-style escape % hex hex */
+#define VIS_MIMESTYLE 0x0100 /* mime-style escape = HEX HEX */
+#define VIS_HTTP1866 0x0200 /* http-style &#num; or &string; */
+#define VIS_NOESCAPE 0x0400 /* don't decode `\' */
+#define _VIS_END 0x0800 /* for unvis */
+#define VIS_GLOB 0x1000 /* encode glob(3) magic characters */
+#define VIS_SHELL 0x2000 /* encode shell special characters [not glob] */
+#define VIS_META (VIS_WHITE | VIS_GLOB | VIS_SHELL)
+#define VIS_NOLOCALE 0x4000 /* encode using the C locale */
+
+/*
+ * unvis return codes
+ */
+#define UNVIS_VALID 1 /* character valid */
+#define UNVIS_VALIDPUSH 2 /* character valid, push back passed char */
+#define UNVIS_NOCHAR 3 /* valid sequence, no character produced */
+#define UNVIS_SYNBAD -1 /* unrecognized escape sequence */
+#define UNVIS_ERROR -2 /* decoder in unknown state (unrecoverable) */
+
+/*
+ * unvis flags
+ */
+#define UNVIS_END _VIS_END /* no more characters */
+
+#ifdef HAVE_SYS_CDEFS_H
+#include <sys/cdefs.h>
+#endif
+
+__BEGIN_DECLS
+char *vis(char *, int, int, int);
+char *nvis(char *, size_t, int, int, int);
+
+char *svis(char *, int, int, int, const char *);
+char *snvis(char *, size_t, int, int, int, const char *);
+
+int strvis(char *, const char *, int);
+int stravis(char **, const char *, int);
+int strnvis(char *, size_t, const char *, int);
+
+int strsvis(char *, const char *, int, const char *);
+int strsnvis(char *, size_t, const char *, int, const char *);
+
+int strvisx(char *, const char *, size_t, int);
+int strnvisx(char *, size_t, const char *, size_t, int);
+int strenvisx(char *, size_t, const char *, size_t, int, int *);
+
+int strsvisx(char *, const char *, size_t, int, const char *);
+int strsnvisx(char *, size_t, const char *, size_t, int, const char *);
+int strsenvisx(char *, size_t, const char *, size_t , int, const char *,
+ int *);
+
+int strunvis(char *, const char *);
+int strnunvis(char *, size_t, const char *);
+
+int strunvisx(char *, const char *, int);
+int strnunvisx(char *, size_t, const char *, int);
+
+int unvis(char *, int, int *, int);
+__END_DECLS
+
+#endif /* !_VIS_H_ */
diff --git a/third_party/heimdal/lib/libedit/src/wcsdup.c b/third_party/heimdal/lib/libedit/src/wcsdup.c
new file mode 100644
index 0000000..5cf7b59
--- /dev/null
+++ b/third_party/heimdal/lib/libedit/src/wcsdup.c
@@ -0,0 +1,43 @@
+/* $NetBSD: wcsdup.c,v 1.3 2008/05/26 13:17:48 haad Exp $ */
+
+/*
+ * Copyright (C) 2006 Aleksey Cheusov
+ *
+ * This material is provided "as is", with absolutely no warranty expressed
+ * or implied. Any use is at your own risk.
+ *
+ * Permission to use or copy this software for any purpose is hereby granted
+ * without fee. Permission to modify the code and to distribute modified
+ * code is also granted without any restrictions.
+ */
+
+#ifndef HAVE_WCSDUP
+
+#include "config.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcsdup.c,v 1.3 2008/05/26 13:17:48 haad Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdlib.h>
+#include <assert.h>
+#include <wchar.h>
+
+wchar_t *
+wcsdup(const wchar_t *str)
+{
+ wchar_t *copy;
+ size_t len;
+
+ _DIAGASSERT(str != NULL);
+
+ len = wcslen(str) + 1;
+ copy = malloc(len * sizeof (wchar_t));
+
+ if (!copy)
+ return NULL;
+
+ return wmemcpy(copy, str, len);
+}
+
+#endif
diff --git a/third_party/heimdal/lib/ntlm/ChangeLog b/third_party/heimdal/lib/ntlm/ChangeLog
new file mode 100644
index 0000000..b2e151a
--- /dev/null
+++ b/third_party/heimdal/lib/ntlm/ChangeLog
@@ -0,0 +1,120 @@
+2008-05-14 Love Hornquist Astrand <lha@kth.se>
+
+ * ntlm.c: replace hashes with keys.
+
+2008-04-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm.c: Use DES_set_key_unchecked().
+
+2007-12-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * heimntlm.h: Add NTLM_TARGET_*
+
+ * ntlm.c: Make heim_ntlm_decode_type3 more useful and provide a
+ username. From Ming Yang.
+
+2007-11-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * move doxygen into the main file
+
+ * write doxygen documentation
+
+ * export heim_ntlm_free_buf, start doxygen documentation
+
+2007-07-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm.c: Use unsigned char * as argument to HMAC_Update to please
+ OpenSSL and gcc.
+
+ * test_ntlm.c: more verbose what we are testing.
+
+2007-07-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: New library version.
+
+2007-06-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_ntlm.c: heim_ntlm_calculate_ntlm2_sess_resp
+
+ * ntlm.c: Change prototype to match other heim_ntlm_calculate
+ functions.
+
+ * test_ntlm.c: Its ok if infotarget2 length is longer.
+
+ * ntlm.c: Merge in changes from Puneet Mehra and make work again.
+
+ * ntlm.c (heim_ntlm_ntlmv2_key): target should be uppercase.
+ From Puneet Mehra.
+
+ * version-script.map: Add heim_ntlm_calculate_ntlm2_sess_resp from
+ Puneet Mehra.
+
+ * ntlm.c: Add heim_ntlm_calculate_ntlm2_sess_resp from Puneet
+ Mehra.
+
+ * test_ntlm.c: Test heim_ntlm_calculate_ntlm2_sess_resp from
+ Puneet Mehra.
+
+2007-06-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: EXTRA_DIST += version-script.map.
+
+2007-06-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_ntlm.c: Free memory diffrently.
+
+ * ntlm.c: Make free functions free memory.
+
+2007-04-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: symbol versioning.
+
+ * version-script.map: symbol versioning.
+
+2007-01-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_ntlm.c: No need to include <gssapi.h>.
+
+2007-01-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add LIB_roken for test_ntlm
+
+2006-12-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_ntlm.c: Verify infotarget.
+
+ * ntlm.c: Extract the infotarget from the answer.
+
+ * ntlm.c (heim_ntlm_verify_ntlm2): verify the ntlmv2 reply
+
+2006-12-22 Dave Love <fx@gnu.org>
+
+ * ntlm.c: Include <limits.h>.
+
+2006-12-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_ntlm.c: add some new tests.
+
+ * ntlm.c: Add ntlmv2 answer calculating functions.
+
+ * ntlm.c: sent lm hashes, needed for NTLM2 session
+
+ * heimntlm.h: Add NTLM_NEG_NTLM2_SESSION, NTLMv2 session security.
+
+2006-12-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm.c (heim_ntlm_build_ntlm1_master): return session master
+ key.
+
+2006-12-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ntlm.c (heim_ntlm_build_ntlm1_master): calculate the ntlm
+ version 1 "master" key.
+
+2006-12-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_ntlm.c: Add simple parser test app.
+
+ * inital version of a NTLM library, only handles ntml version 1 and
+ ascii strings for now
+
diff --git a/third_party/heimdal/lib/ntlm/Makefile.am b/third_party/heimdal/lib/ntlm/Makefile.am
new file mode 100644
index 0000000..d33efd2
--- /dev/null
+++ b/third_party/heimdal/lib/ntlm/Makefile.am
@@ -0,0 +1,49 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+lib_LTLIBRARIES = libheimntlm.la
+
+dist_include_HEADERS = heimntlm.h $(srcdir)/heimntlm-protos.h
+
+nodist_include_HEADERS = ntlm_err.h
+
+dist_libheimntlm_la_SOURCES = ntlm.c heimntlm.h
+
+nodist_libheimntlm_la_SOURCES = ntlm_err.c
+
+libheimntlm_la_LDFLAGS = -version-info 1:0:1
+
+if versionscript
+libheimntlm_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+endif
+$(libheimntlm_la_OBJECTS): $(srcdir)/version-script.map
+
+libheimntlm_la_LIBADD = \
+ ../krb5/libkrb5.la \
+ $(top_builddir)/lib/wind/libwind.la \
+ $(LIB_hcrypto) \
+ $(LIBADD_roken)
+
+$(srcdir)/heimntlm-protos.h: $(dist_libheimntlm_la_SOURCES)
+ cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -o heimntlm-protos.h $(dist_libheimntlm_la_SOURCES) || rm -f heimntlm-protos.h
+
+$(libheimntlm_la_OBJECTS): $(srcdir)/heimntlm-protos.h ntlm_err.h
+
+TESTS = test_ntlm
+
+check_PROGRAMS = test_ntlm
+
+LDADD = libheimntlm.la $(LIB_roken)
+
+EXTRA_DIST = \
+ NTMakefile \
+ libheimntlm-version.rc \
+ libheimntlm-exports.def \
+ version-script.map \
+ ntlm_err.et
+
+CLEANFILES = \
+ ntlm_err.c ntlm_err.h
+
+ntlm_err.h: ntlm_err.et
diff --git a/third_party/heimdal/lib/ntlm/NTMakefile b/third_party/heimdal/lib/ntlm/NTMakefile
new file mode 100644
index 0000000..527fc89
--- /dev/null
+++ b/third_party/heimdal/lib/ntlm/NTMakefile
@@ -0,0 +1,90 @@
+########################################################################
+#
+# Copyright (c) 2009, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\ntlm
+
+!include ../../windows/NTMakefile.w32
+
+INCFILES= \
+ $(INCDIR)\heimntlm.h \
+ $(INCDIR)\heimntlm-protos.h \
+ $(INCDIR)\ntlm_err.h
+
+libheimntlm_la_SOURCES = ntlm.c heimntlm.h
+
+$(OBJ)\heimntlm-protos.h: $(libheimntlm_la_SOURCES)
+ $(PERL) ../../cf/make-proto.pl -q -P remove -o $(OBJ)\heimntlm-protos.h $(libheimntlm_la_SOURCES)
+
+$(OBJ)\ntlm_err.c $(OBJ)\ntlm_err.h: ntlm_err.et
+ cd $(OBJ)
+ $(BINDIR)\compile_et.exe $(SRCDIR)\ntlm_err.et
+ cd $(SRCDIR)
+
+!ifndef STATICLIBS
+
+RES=$(OBJ)\libheimntlm-version.res
+
+$(LIBHEIMNTLM): $(BINDIR)\heimntlm.dll
+
+$(BINDIR)\heimntlm.dll: $(OBJ)\ntlm.obj $(OBJ)\ntlm_err.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBCOMERR) $(RES)
+ $(DLLGUILINK) -def:libheimntlm-exports.def -implib:$(LIBHEIMNTLM)
+ $(DLLPREP_NODIST)
+
+clean::
+ -$(RM) $(BINDIR)\heimntlm.*
+
+!else
+
+$(LIBHEIMNTLM): $(OBJ)\ntlm.obj $(OBJ)\ntlm_err.obj
+ $(LIBCON)
+
+!endif
+
+all:: $(INCFILES) $(LIBHEIMNTLM)
+
+
+test-binaries: $(OBJ)\test_ntlm.exe
+
+test-run:
+ cd $(OBJ)
+ -test_ntlm.exe
+ cd $(SRCDIR)
+
+$(OBJ)\test_ntlm.exe: $(OBJ)\test_ntlm.obj $(LIBHEIMNTLM) $(LIBHEIMDAL) $(LIBVERS) $(LIBROKEN)
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+test:: test-binaries test-run
+
+test-exports:
+ $(PERL) ..\..\cf\w32-check-exported-symbols.pl --vs version-script.map --def libheimntlm-exports.def
+
+test:: test-exports
diff --git a/third_party/heimdal/lib/ntlm/apop.c b/third_party/heimdal/lib/ntlm/apop.c
new file mode 100644
index 0000000..b363239
--- /dev/null
+++ b/third_party/heimdal/lib/ntlm/apop.c
@@ -0,0 +1,263 @@
+/*
+ * Copyright (c) 2010 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <sys/types.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <CommonCrypto/CommonDigest.h>
+#include <CommonCrypto/CommonHMAC.h>
+#include <roken.h>
+#include <hex.h>
+#include "heim-auth.h"
+#include "ntlm_err.h"
+
+char *
+heim_generate_challenge(const char *hostname)
+{
+ char host[MAXHOSTNAMELEN], *str = NULL;
+ uint32_t num, t;
+
+ if (hostname == NULL) {
+ if (gethostname(host, sizeof(host)))
+ return NULL;
+ hostname = host;
+ }
+
+ t = (uint32_t)time(NULL);
+ num = rk_random();
+
+ asprintf(&str, "<%lu%lu@%s>", (unsigned long)t,
+ (unsigned long)num, hostname);
+
+ return str;
+}
+
+char *
+heim_apop_create(const char *challenge, const char *password)
+{
+ char *str = NULL;
+ uint8_t hash[CC_MD5_DIGEST_LENGTH];
+ CC_MD5_CTX ctx;
+
+ CC_MD5_Init(&ctx);
+ CC_MD5_Update(&ctx, challenge, (CC_LONG)strlen(challenge));
+ CC_MD5_Update(&ctx, password, (CC_LONG)strlen(password));
+
+ CC_MD5_Final(hash, &ctx);
+
+ hex_encode(hash, sizeof(hash), &str);
+ if (str)
+ strlwr(str);
+
+ return str;
+}
+
+int
+heim_apop_verify(const char *challenge, const char *password, const char *response)
+{
+ char *str;
+ int res;
+
+ str = heim_apop_create(challenge, password);
+ if (str == NULL)
+ return ENOMEM;
+
+ res = (strcasecmp(str, response) != 0);
+ free(str);
+
+ if (res)
+ return HNTLM_ERR_INVALID_APOP;
+ return 0;
+}
+
+struct heim_cram_md5_data {
+ CC_MD5_CTX ipad;
+ CC_MD5_CTX opad;
+};
+
+
+void
+heim_cram_md5_export(const char *password, heim_CRAM_MD5_STATE *state)
+{
+ size_t keylen = strlen(password);
+ uint8_t key[CC_MD5_BLOCK_BYTES];
+ uint8_t pad[CC_MD5_BLOCK_BYTES];
+ struct heim_cram_md5_data ctx;
+ size_t n;
+
+ memset(&ctx, 0, sizeof(ctx));
+
+ if (keylen > CC_MD5_BLOCK_BYTES) {
+ CC_MD5(password, (CC_LONG)keylen, key);
+ keylen = sizeof(keylen);
+ } else {
+ memcpy(key, password, keylen);
+ }
+
+ memset(pad, 0x36, sizeof(pad));
+ for (n = 0; n < keylen; n++)
+ pad[n] ^= key[n];
+
+ CC_MD5_Init(&ctx.ipad);
+ CC_MD5_Init(&ctx.opad);
+
+ CC_MD5_Update(&ctx.ipad, pad, sizeof(pad));
+
+ memset(pad, 0x5c, sizeof(pad));
+ for (n = 0; n < keylen; n++)
+ pad[n] ^= key[n];
+
+ CC_MD5_Update(&ctx.opad, pad, sizeof(pad));
+
+ memset(pad, 0, sizeof(pad));
+ memset(key, 0, sizeof(key));
+
+ state->istate[0] = htonl(ctx.ipad.A);
+ state->istate[1] = htonl(ctx.ipad.B);
+ state->istate[2] = htonl(ctx.ipad.C);
+ state->istate[3] = htonl(ctx.ipad.D);
+
+ state->ostate[0] = htonl(ctx.opad.A);
+ state->ostate[1] = htonl(ctx.opad.B);
+ state->ostate[2] = htonl(ctx.opad.C);
+ state->ostate[3] = htonl(ctx.opad.D);
+
+ memset(&ctx, 0, sizeof(ctx));
+}
+
+
+heim_cram_md5
+heim_cram_md5_import(void *data, size_t len)
+{
+ heim_CRAM_MD5_STATE state;
+ heim_cram_md5 ctx;
+
+ if (len != sizeof(state))
+ return NULL;
+
+ ctx = calloc(1, sizeof(*ctx));
+ if (ctx == NULL)
+ return NULL;
+
+ memcpy(&state, data, sizeof(state));
+
+ ctx->ipad.A = ntohl(state.istate[0]);
+ ctx->ipad.B = ntohl(state.istate[1]);
+ ctx->ipad.C = ntohl(state.istate[2]);
+ ctx->ipad.D = ntohl(state.istate[3]);
+
+ ctx->opad.A = ntohl(state.ostate[0]);
+ ctx->opad.B = ntohl(state.ostate[1]);
+ ctx->opad.C = ntohl(state.ostate[2]);
+ ctx->opad.D = ntohl(state.ostate[3]);
+
+ ctx->ipad.Nl = ctx->opad.Nl = 512;
+ ctx->ipad.Nh = ctx->opad.Nh = 0;
+ ctx->ipad.num = ctx->opad.num = 0;
+
+ return ctx;
+}
+
+int
+heim_cram_md5_verify_ctx(heim_cram_md5 ctx, const char *challenge, const char *response)
+{
+ uint8_t hash[CC_MD5_DIGEST_LENGTH];
+ char *str = NULL;
+ int res;
+
+ CC_MD5_Update(&ctx->ipad, challenge, (CC_LONG)strlen(challenge));
+ CC_MD5_Final(hash, &ctx->ipad);
+
+ CC_MD5_Update(&ctx->opad, hash, sizeof(hash));
+ CC_MD5_Final(hash, &ctx->opad);
+
+ hex_encode(hash, sizeof(hash), &str);
+ if (str == NULL)
+ return ENOMEM;
+
+ res = (strcasecmp(str, response) != 0);
+ free(str);
+
+ if (res)
+ return HNTLM_ERR_INVALID_CRAM_MD5;
+ return 0;
+}
+
+void
+heim_cram_md5_free(heim_cram_md5 ctx)
+{
+ memset(ctx, 0, sizeof(*ctx));
+ free(ctx);
+}
+
+
+char *
+heim_cram_md5_create(const char *challenge, const char *password)
+{
+ CCHmacContext ctx;
+ uint8_t hash[CC_MD5_DIGEST_LENGTH];
+ char *str = NULL;
+
+ CCHmacInit(&ctx, kCCHmacAlgMD5, password, strlen(password));
+ CCHmacUpdate(&ctx, challenge, strlen(challenge));
+ CCHmacFinal(&ctx, hash);
+
+ memset(&ctx, 0, sizeof(ctx));
+
+ hex_encode(hash, sizeof(hash), &str);
+ if (str)
+ strlwr(str);
+
+ return str;
+}
+
+ int
+heim_cram_md5_verify(const char *challenge, const char *password, const char *response)
+{
+ char *str;
+ int res;
+
+ str = heim_cram_md5_create(challenge, password);
+ if (str == NULL)
+ return ENOMEM;
+
+ res = (strcasecmp(str, response) != 0);
+ free(str);
+
+ if (res)
+ return HNTLM_ERR_INVALID_CRAM_MD5;
+ return 0;
+}
+
diff --git a/third_party/heimdal/lib/ntlm/digest.c b/third_party/heimdal/lib/ntlm/digest.c
new file mode 100644
index 0000000..761e1f4
--- /dev/null
+++ b/third_party/heimdal/lib/ntlm/digest.c
@@ -0,0 +1,994 @@
+/*
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <sys/types.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <CommonCrypto/CommonDigest.h>
+#include <CommonCrypto/CommonHMAC.h>
+#include <assert.h>
+#include <roken.h>
+#include <hex.h>
+#include "heim-auth.h"
+#include "ntlm_err.h"
+
+struct heim_digest_desc {
+#define F_SERVER 1
+#define F_HAVE_HASH 2
+#define F_HAVE_HA1 4
+#define F_USE_PREFIX 8
+ int flags;
+ int type;
+ char *password;
+ uint8_t SecretHash[CC_MD5_DIGEST_LENGTH];
+ char *serverNonce;
+ char *serverRealm;
+ char *serverQOP;
+ char *serverMethod;
+ char *serverMaxbuf;
+ char *serverOpaque;
+ char *clientUsername;
+ char *clientResponse;
+ char *clientURI;
+ char *clientRealm;
+ char *clientNonce;
+ char *clientQOP;
+ char *clientNC;
+ char *serverAlgorithm;
+ char *auth_id;
+
+ /* internally allocated objects returned to caller */
+ char *serverChallenge;
+ char *clientReply;
+ char *serverReply;
+};
+
+#define FREE_AND_CLEAR(x) do { if ((x)) { free((x)); (x) = NULL; } } while(0)
+#define MEMSET_FREE_AND_CLEAR(x) do { if ((x)) { memset(x, 0, strlen(x)); free((x)); (x) = NULL; } } while(0)
+
+static const char digest_prefix[] = "Digest ";
+
+static void
+clear_context(heim_digest_t context)
+{
+ MEMSET_FREE_AND_CLEAR(context->password);
+ memset(context->SecretHash, 0, sizeof(context->SecretHash));
+ context->flags &= ~(F_HAVE_HASH);
+ FREE_AND_CLEAR(context->serverNonce);
+ FREE_AND_CLEAR(context->serverRealm);
+ FREE_AND_CLEAR(context->serverQOP);
+ FREE_AND_CLEAR(context->serverMethod);
+ FREE_AND_CLEAR(context->serverMaxbuf);
+ FREE_AND_CLEAR(context->serverOpaque);
+ FREE_AND_CLEAR(context->clientUsername);
+ FREE_AND_CLEAR(context->clientResponse);
+ FREE_AND_CLEAR(context->clientURI);
+ FREE_AND_CLEAR(context->clientRealm);
+ FREE_AND_CLEAR(context->clientNonce);
+ FREE_AND_CLEAR(context->clientQOP);
+ FREE_AND_CLEAR(context->clientNC);
+ FREE_AND_CLEAR(context->serverAlgorithm);
+ FREE_AND_CLEAR(context->auth_id);
+
+ FREE_AND_CLEAR(context->serverChallenge);
+ FREE_AND_CLEAR(context->clientReply);
+ FREE_AND_CLEAR(context->serverReply);
+}
+
+static void
+digest_userhash(const char *user, const char *realm, const char *password,
+ unsigned char md[CC_MD5_DIGEST_LENGTH])
+{
+ CC_MD5_CTX ctx;
+
+ CC_MD5_Init(&ctx);
+ CC_MD5_Update(&ctx, user, (CC_LONG)strlen(user));
+ CC_MD5_Update(&ctx, ":", 1);
+ CC_MD5_Update(&ctx, realm, (CC_LONG)strlen(realm));
+ CC_MD5_Update(&ctx, ":", 1);
+ CC_MD5_Update(&ctx, password, (CC_LONG)strlen(password));
+ CC_MD5_Final(md, &ctx);
+}
+
+static char *
+build_A1_hash(heim_digest_t context)
+{
+ unsigned char md[CC_MD5_DIGEST_LENGTH];
+ CC_MD5_CTX ctx;
+ char *A1;
+
+ if (context->flags & F_HAVE_HA1) {
+ memcpy(md, context->SecretHash, sizeof(md));
+ } else if (context->flags & F_HAVE_HASH) {
+ memcpy(md, context->SecretHash, sizeof(md));
+ } else if (context->password) {
+ if (context->clientUsername == NULL)
+ return NULL;
+ if (context->serverRealm == NULL)
+ return NULL;
+ digest_userhash(context->clientUsername,
+ context->serverRealm,
+ context->password,
+ md);
+ } else
+ return NULL;
+
+ if ((context->type == HEIM_DIGEST_TYPE_RFC2617_MD5_SESS || context->type == HEIM_DIGEST_TYPE_RFC2831) && (context->flags & F_HAVE_HA1) == 0) {
+ if (context->serverNonce == NULL)
+ return NULL;
+
+ CC_MD5_Init(&ctx);
+ CC_MD5_Update(&ctx, md, sizeof(md));
+ memset(md, 0, sizeof(md));
+ CC_MD5_Update(&ctx, ":", 1);
+ CC_MD5_Update(&ctx, context->serverNonce, (CC_LONG)strlen(context->serverNonce));
+ if (context->clientNonce) {
+ CC_MD5_Update(&ctx, ":", 1);
+ CC_MD5_Update(&ctx, context->clientNonce, (CC_LONG)strlen(context->clientNonce));
+ }
+ if (context->type == HEIM_DIGEST_TYPE_RFC2831 && context->auth_id) {
+ CC_MD5_Update(&ctx, ":", 1);
+ CC_MD5_Update(&ctx, context->auth_id, (CC_LONG)strlen(context->auth_id));
+ }
+ CC_MD5_Final(md, &ctx);
+ }
+ hex_encode(md, sizeof(md), &A1);
+ if (A1)
+ strlwr(A1);
+
+ return A1;
+}
+
+static char *
+build_A2_hash(heim_digest_t context, const char *method)
+{
+ unsigned char md[CC_MD5_DIGEST_LENGTH];
+ CC_MD5_CTX ctx;
+ char *A2;
+
+ CC_MD5_Init(&ctx);
+ if (method)
+ CC_MD5_Update(&ctx, method, (CC_LONG)strlen(method));
+ CC_MD5_Update(&ctx, ":", 1);
+ CC_MD5_Update(&ctx, context->clientURI, (CC_LONG)strlen(context->clientURI));
+
+ /* conf|int */
+ if (context->type == HEIM_DIGEST_TYPE_RFC2831) {
+ if (strcasecmp(context->clientQOP, "auth-int") == 0 || strcasecmp(context->clientQOP, "auth-conf") == 0) {
+ /* XXX if we have a body hash, use that */
+ static char conf_zeros[] = ":00000000000000000000000000000000";
+ CC_MD5_Update(&ctx, conf_zeros, sizeof(conf_zeros) - 1);
+ }
+ } else {
+ /* support auth-int ? */
+ if (context->clientQOP && strcasecmp(context->clientQOP, "auth") != 0)
+ return NULL;
+ }
+
+ CC_MD5_Final(md, &ctx);
+
+ hex_encode(md, sizeof(md), &A2);
+ if (A2)
+ strlwr(A2);
+
+ return A2;
+}
+
+/*
+ *
+ */
+
+struct md5_value {
+ char *mv_name;
+ char *mv_value;
+ struct md5_value *mv_next;
+};
+
+static void
+free_values(struct md5_value *val)
+{
+ struct md5_value *v;
+ while(val) {
+ v = val->mv_next;
+ if (val->mv_name)
+ free(val->mv_name);
+ if (val->mv_value)
+ free(val->mv_value);
+ free(val);
+ val = v;
+ }
+}
+
+/*
+ * Search for entry, if found, remove entry and return string to be freed.
+ */
+
+static char *
+values_find(struct md5_value **val, const char *v)
+{
+ struct md5_value *cur;
+ char *str;
+
+ while (*val != NULL) {
+ if (strcasecmp(v, (*val)->mv_name) == 0)
+ break;
+ val = &(*val)->mv_next;
+ }
+ if (*val == NULL)
+ return NULL;
+ cur = *val;
+ *val = (*val)->mv_next;
+
+ str = cur->mv_value;
+ free(cur->mv_name);
+ free(cur);
+
+ return str;
+}
+
+static int
+parse_values(const char *string, struct md5_value **val)
+{
+ struct md5_value *v;
+ size_t size;
+ char *str, *p1, *p2;
+ size_t sz;
+
+ *val = NULL;
+
+ if ((str = strdup(string)) == NULL)
+ return ENOMEM;
+
+ size = strlen(str);
+
+ p1 = str;
+
+ while (p1 - str < size) {
+ sz = strspn(p1, " \t\n\r,");
+ if (p1[sz] == '\0')
+ break;
+ p1 += sz;
+ sz = strcspn(p1, " \t\n\r=");
+ if (sz == 0 || p1[sz] == '\0')
+ goto error;
+ p2 = p1 + sz;
+
+ if ((v = malloc(sizeof(*v))) == NULL)
+ goto nomem;
+ v->mv_name = v->mv_value = NULL;
+ v->mv_next = *val;
+ *val = v;
+ if ((v->mv_name = malloc(p2 - p1 + 1)) == NULL)
+ goto nomem;
+ strncpy(v->mv_name, p1, p2 - p1);
+ v->mv_name[p2 - p1] = '\0';
+
+ sz = strspn(p2, " \t\n\r");
+ if (p2[sz] == '\0')
+ goto error;
+ p2 += sz;
+
+ if (*p2 != '=')
+ goto error;
+ p2++;
+
+ sz = strspn(p2, " \t\n\r");
+ if (p2[sz] == '\0')
+ goto error;
+ p2 += sz;
+ p1 = p2;
+
+ if (*p2 == '"') {
+ p1++;
+ while (*p2 == '"') {
+ p2++;
+ p2 = strchr(p2, '\"');
+ if (p2 == NULL)
+ goto error;
+ if (p2[0] == '\0')
+ goto error;
+ if (p2[-1] != '\\')
+ break;
+ }
+ } else {
+ sz = strcspn(p2, " \t\n\r=,");
+ p2 += sz;
+ }
+
+#if 0 /* allow empty values */
+ if (p1 == p2)
+ goto error;
+#endif
+
+ if ((v->mv_value = malloc(p2 - p1 + 1)) == NULL)
+ goto nomem;
+ strncpy(v->mv_value, p1, p2 - p1);
+ v->mv_value[p2 - p1] = '\0';
+
+ if (p2[0] == '\0')
+ break;
+ if (p2[0] == '"')
+ p2++;
+
+ sz = strspn(p2, " \t\n\r");
+ if (p2[sz] == '\0')
+ break;
+ p2 += sz;
+
+ if (p2[0] == '\0')
+ break;
+ if (p2[0] != ',')
+ goto error;
+ p1 = p2;
+ }
+
+ free(str);
+
+ return 0;
+ error:
+ free_values(*val);
+ *val = NULL;
+ free(str);
+ return EINVAL;
+ nomem:
+ free_values(*val);
+ *val = NULL;
+ free(str);
+ return ENOMEM;
+}
+
+/*
+ *
+ */
+
+static const char *
+check_prefix(heim_digest_t context, const char *challenge)
+{
+ if (strncasecmp(digest_prefix, challenge, sizeof(digest_prefix) - 1) == 0) {
+
+ challenge += sizeof(digest_prefix) - 1;
+ while (*challenge == 0x20) /* remove extra space */
+ challenge++;
+ context->flags |= F_USE_PREFIX;
+ }
+
+ return challenge;
+}
+
+/*
+ *
+ */
+
+heim_digest_t
+heim_digest_create(int server, int type)
+{
+ heim_digest_t context;
+
+ context = calloc(1, sizeof(*context));
+ if (context == NULL)
+ return NULL;
+ context->flags |= F_SERVER;
+ context->type = type;
+
+ return context;
+}
+
+static char *
+generate_nonce(void)
+{
+ uint8_t rand[8];
+ char *nonce;
+
+ if (CCRandomCopyBytes(kCCRandomDefault, rand, sizeof(rand)) != kCCSuccess)
+ return NULL;
+
+ if (rk_hex_encode(rand, sizeof(rand), &nonce) < 0)
+ return NULL;
+
+ return nonce;
+}
+
+/**
+ * Generate a challange, needs to set serverRealm before calling this function.
+ *
+ * If type is set to HEIM_DIGEST_TYPE_AUTO, the HEIM_DIGEST_TYPE_RFC2831 will be used instead.
+ *
+ * For RFC2617 and RFC2831 QOP is required, so if any qop other then "auth" is requested, it need to be set with heim_diest_set_key().
+ *
+ * @return returns the challenge or NULL on error or failure to build the string. the lifetime
+ * of the string is manage by heim_digest and last until the the context is
+ * freed or until next call to heim_digest_generate_challenge().
+ */
+
+const char *
+heim_digest_generate_challenge(heim_digest_t context)
+{
+ char *challenge = NULL;
+
+ if (context->serverRealm == NULL)
+ return NULL;
+
+ if (context->serverNonce == NULL) {
+ if ((context->serverNonce = generate_nonce()) == NULL)
+ return NULL;
+ }
+
+ if (context->serverQOP == NULL) {
+ if ((context->serverQOP = strdup("auth")) == NULL)
+ return NULL;
+ }
+
+ if (context->serverMaxbuf == NULL) {
+ if ((context->serverMaxbuf = strdup("65536")) == NULL)
+ return NULL;
+ }
+
+ switch(context->type) {
+ case HEIM_DIGEST_TYPE_RFC2617_MD5:
+ asprintf(&challenge, "realm=\"%s\",nonce=\"%s\",algorithm=md5,qop=\"%s\"",
+ context->serverRealm, context->serverNonce,
+ context->serverQOP);
+ break;
+ case HEIM_DIGEST_TYPE_RFC2617_MD5_SESS:
+ asprintf(&challenge, "realm=\"%s\",nonce=\"%s\",algorithm=md5-sess,qop=\"%s\"",
+ context->serverRealm, context->serverNonce, context->serverQOP);
+ break;
+ case HEIM_DIGEST_TYPE_RFC2069:
+ asprintf(&challenge, "realm=\"%s\",nonce=\"%s\"",
+ context->serverRealm, context->serverNonce);
+ break;
+ case HEIM_DIGEST_TYPE_AUTO:
+ context->type = HEIM_DIGEST_TYPE_RFC2831;
+ fallthrough;
+ case HEIM_DIGEST_TYPE_RFC2831:
+ asprintf(&challenge, "realm=\"%s\",nonce=\"%s\",qop=\"%s\",algorithm=md5-sess,charset=utf-8,maxbuf=%s",
+ context->serverRealm, context->serverNonce, context->serverQOP, context->serverMaxbuf);
+ break;
+ }
+
+ FREE_AND_CLEAR(context->serverChallenge);
+ context->serverChallenge = challenge;
+
+ return challenge;
+}
+
+int
+heim_digest_parse_challenge(heim_digest_t context, const char *challenge)
+{
+ struct md5_value *val = NULL;
+ int ret, type;
+
+ challenge = check_prefix(context, challenge);
+
+ ret = parse_values(challenge, &val);
+ if (ret)
+ goto out;
+
+ ret = 1;
+
+ context->serverNonce = values_find(&val, "nonce");
+ if (context->serverNonce == NULL) goto out;
+
+ context->serverRealm = values_find(&val, "realm");
+ if (context->serverRealm == NULL) goto out;
+
+ /* check alg */
+
+ context->serverAlgorithm = values_find(&val, "algorithm");
+ if (context->serverAlgorithm == NULL || strcasecmp(context->serverAlgorithm, "md5") == 0) {
+ type = HEIM_DIGEST_TYPE_RFC2617_MD5;
+ } else if (strcasecmp(context->serverAlgorithm, "md5-sess") == 0) {
+ type = HEIM_DIGEST_TYPE_RFC2617_OR_RFC2831;
+ } else {
+ goto out;
+ }
+
+ context->serverQOP = values_find(&val, "qop");
+ if (context->serverQOP == NULL)
+ type = HEIM_DIGEST_TYPE_RFC2069;
+
+ context->serverOpaque = values_find(&val, "opaque");
+
+ if (context->type != HEIM_DIGEST_TYPE_AUTO && (context->type & type) == 0)
+ goto out;
+ else if (context->type == HEIM_DIGEST_TYPE_AUTO)
+ context->type = type;
+
+ ret = 0;
+ out:
+ free_values(val);
+ if (ret)
+ clear_context(context);
+ return ret;
+}
+
+
+static void
+set_auth_method(heim_digest_t context)
+{
+
+ if (context->serverMethod == NULL) {
+ if (context->type == HEIM_DIGEST_TYPE_RFC2831)
+ context->serverMethod = strdup("AUTHENTICATE");
+ else
+ context->serverMethod = strdup("GET");
+ }
+}
+
+int
+heim_digest_parse_response(heim_digest_t context, const char *response)
+{
+ struct md5_value *val = NULL;
+ char *nonce;
+ int ret;
+
+ response = check_prefix(context, response);
+
+ ret = parse_values(response, &val);
+ if (ret)
+ goto out;
+
+ ret = 1;
+
+ if (context->type == HEIM_DIGEST_TYPE_AUTO) {
+ goto out;
+ } else if (context->type == HEIM_DIGEST_TYPE_RFC2617_OR_RFC2831) {
+ context->clientURI = values_find(&val, "uri");
+ if (context->clientURI) {
+ context->type = HEIM_DIGEST_TYPE_RFC2617_MD5_SESS;
+ } else {
+ context->clientURI = values_find(&val, "digest-uri");
+ context->type = HEIM_DIGEST_TYPE_RFC2831;
+ }
+ } else if (context->type == HEIM_DIGEST_TYPE_RFC2831) {
+ context->clientURI = values_find(&val, "digest-uri");
+ } else {
+ context->clientURI = values_find(&val, "uri");
+ }
+
+ if (context->clientURI == NULL)
+ goto out;
+
+ context->clientUsername = values_find(&val, "username");
+ if (context->clientUsername == NULL) goto out;
+
+ /* if client sent realm, make sure its the same of serverRealm if its set */
+ context->clientRealm = values_find(&val, "realm");
+ if (context->clientRealm && context->serverRealm && strcmp(context->clientRealm, context->serverRealm) != 0)
+ goto out;
+
+ context->clientResponse = values_find(&val, "response");
+ if (context->clientResponse == NULL) goto out;
+
+ nonce = values_find(&val, "nonce");
+ if (nonce == NULL) goto out;
+
+ if (strcmp(nonce, context->serverNonce) != 0) {
+ free(nonce);
+ goto out;
+ }
+ free(nonce);
+
+ if (context->type != HEIM_DIGEST_TYPE_RFC2069) {
+
+ context->clientQOP = values_find(&val, "qop");
+ if (context->clientQOP == NULL) goto out;
+
+ /*
+ * If we have serverQOP, lets check that clientQOP exists
+ * in the list of server entries.
+ */
+
+ if (context->serverQOP) {
+ Boolean found = false;
+ char *b, *e;
+ size_t len, clen = strlen(context->clientQOP);
+
+ b = context->serverQOP;
+ while (b && !found) {
+ e = strchr(b, ',');
+ if (e == NULL)
+ len = strlen(b);
+ else {
+ len = e - b;
+ e += 1;
+ }
+ if (clen == len && strncmp(b, context->clientQOP, len) == 0)
+ found = true;
+ b = e;
+ }
+ if (!found)
+ goto out;
+ }
+
+ context->clientNC = values_find(&val, "nc");
+ if (context->clientNC == NULL) goto out;
+
+ context->clientNonce = values_find(&val, "cnonce");
+ if (context->clientNonce == NULL) goto out;
+ }
+
+ set_auth_method(context);
+
+ ret = 0;
+ out:
+ free_values(val);
+ return ret;
+}
+
+char *
+heim_digest_userhash(const char *user, const char *realm, const char *password)
+{
+ unsigned char md[CC_MD5_DIGEST_LENGTH];
+ char *str = NULL;
+
+ digest_userhash(user, realm, password, md);
+
+ hex_encode(md, sizeof(md), &str);
+ if (str)
+ strlwr(str);
+ return str;
+}
+
+static char *
+build_digest(heim_digest_t context, const char *a1, const char *method)
+{
+ CC_MD5_CTX ctx;
+ uint8_t md[CC_MD5_DIGEST_LENGTH];
+ char *a2, *str = NULL;
+
+ a2 = build_A2_hash(context, method);
+ if (a2 == NULL)
+ return NULL;
+
+ CC_MD5_Init(&ctx);
+ CC_MD5_Update(&ctx, a1, (CC_LONG)strlen(a1));
+ CC_MD5_Update(&ctx, ":", 1);
+ CC_MD5_Update(&ctx, context->serverNonce, (CC_LONG)strlen(context->serverNonce));
+ if (context->type != HEIM_DIGEST_TYPE_RFC2069) {
+ CC_MD5_Update(&ctx, ":", 1);
+ CC_MD5_Update(&ctx, context->clientNC, (CC_LONG)strlen(context->clientNC));
+ CC_MD5_Update(&ctx, ":", 1);
+ CC_MD5_Update(&ctx, context->clientNonce, (CC_LONG)strlen(context->clientNonce));
+ CC_MD5_Update(&ctx, ":", 1);
+ CC_MD5_Update(&ctx, context->clientQOP, (CC_LONG)strlen(context->clientQOP));
+ }
+ CC_MD5_Update(&ctx, ":", 1);
+ CC_MD5_Update(&ctx, a2, (CC_LONG)strlen(a2));
+ CC_MD5_Final(md, &ctx);
+
+ free(a2);
+
+ hex_encode(md, sizeof(md), &str);
+ if (str)
+ strlwr(str);
+
+ return str;
+}
+
+static void
+build_server_response(heim_digest_t context, char *a1, char **response)
+{
+ char *str;
+
+ str = build_digest(context, a1, NULL);
+ if (str == NULL)
+ return;
+
+ FREE_AND_CLEAR(context->serverReply);
+ asprintf(&context->serverReply, "%srspauth=%s",
+ (context->flags & F_USE_PREFIX) ? digest_prefix : "",
+ str);
+ free(str);
+ if (response)
+ *response = context->serverReply;
+}
+
+
+/**
+ * Create response from server to client to server, server verification is in response.
+ * clientUsername and clientURI have to be given.
+ * If realm is not set, its used from server.
+ */
+
+const char *
+heim_digest_create_response(heim_digest_t context, char **response)
+{
+ char *a1, *str, *cnonce = NULL, *opaque = NULL, *uri = NULL, *nc = NULL;
+
+ if (response)
+ *response = NULL;
+
+ if (context->clientUsername == NULL || context->clientURI == NULL)
+ return NULL;
+
+ if (context->clientRealm == NULL) {
+ if (context->serverRealm == NULL)
+ return NULL;
+ if ((context->clientRealm = strdup(context->serverRealm)) == NULL)
+ return NULL;
+ }
+
+ if (context->type != HEIM_DIGEST_TYPE_RFC2069) {
+ if (context->clientNC == NULL) {
+ if ((context->clientNC = strdup("00000001")) == NULL)
+ return NULL;
+ }
+ if (context->clientNonce == NULL) {
+ if ((context->clientNonce = generate_nonce()) == NULL)
+ return NULL;
+ }
+
+ /**
+ * If using non RFC2069, appropriate QOP should be set.
+ *
+ * Pick QOP from server if not given, if its a list, pick the first entry
+ */
+ if (context->clientQOP == NULL) {
+ char *r;
+ if (context->serverQOP == NULL)
+ return NULL;
+ r = strchr(context->serverQOP, ',');
+ if (r == NULL) {
+ if ((context->clientQOP = strdup(context->serverQOP)) == NULL)
+ return NULL;
+ } else {
+ size_t len = (r - context->serverQOP) + 1;
+ if ((context->clientQOP = malloc(len)) == NULL)
+ return NULL;
+ strlcpy(context->clientQOP, context->serverQOP, len);
+ }
+ }
+ }
+
+ set_auth_method(context);
+
+ a1 = build_A1_hash(context);
+ if (a1 == NULL)
+ return NULL;
+
+ str = build_digest(context, a1, context->serverMethod);
+ if (str == NULL) {
+ MEMSET_FREE_AND_CLEAR(a1);
+ return NULL;
+ }
+
+ MEMSET_FREE_AND_CLEAR(context->clientResponse);
+ context->clientResponse = str;
+
+ if (context->clientURI) {
+ const char *name = "digest-uri";
+ if (context->type != HEIM_DIGEST_TYPE_RFC2831)
+ name = "uri";
+ asprintf(&uri, ",%s=\"%s\"", name, context->clientURI);
+ }
+
+ if (context->serverOpaque)
+ asprintf(&opaque, ",opaque=\"%s\"", context->serverOpaque);
+
+ if (context->clientNonce)
+ asprintf(&cnonce, ",cnonce=\"%s\"", context->clientNonce);
+
+ if (context->clientNC)
+ asprintf(&nc, ",nc=%s", context->clientNC);
+
+ asprintf(&context->clientReply,
+ "username=%s,realm=%s,nonce=\"%s\",qop=\"%s\"%s%s%s,response=\"%s\"%s",
+ context->clientUsername, context->clientRealm,
+ context->serverNonce,
+ context->clientQOP,
+ uri ? uri : "",
+ cnonce ? cnonce : "",
+ nc ? nc : "",
+ context->clientResponse,
+ opaque ? opaque : "");
+
+ build_server_response(context, a1, response);
+ MEMSET_FREE_AND_CLEAR(a1);
+ FREE_AND_CLEAR(uri);
+ FREE_AND_CLEAR(opaque);
+ FREE_AND_CLEAR(cnonce);
+ FREE_AND_CLEAR(nc);
+
+ return context->clientReply;
+}
+
+int
+heim_digest_verify(heim_digest_t context, char **response)
+{
+ char *a1;
+ char *str;
+ int res;
+
+ if (response)
+ *response = NULL;
+
+ set_auth_method(context);
+
+ a1 = build_A1_hash(context);
+ if (a1 == NULL)
+ return ENOMEM;
+
+ str = build_digest(context, a1, context->serverMethod);
+ if (str == NULL) {
+ MEMSET_FREE_AND_CLEAR(a1);
+ return ENOMEM;
+ }
+
+ res = (strcmp(str, context->clientResponse) == 0) ? 0 : EINVAL;
+ free(str);
+ if (res) {
+ MEMSET_FREE_AND_CLEAR(a1);
+ return res;
+ }
+
+ /* build server_response */
+ build_server_response(context, a1, response);
+ MEMSET_FREE_AND_CLEAR(a1);
+ /* XXX break ABI and return internally allocated string instead */
+ if (response)
+ *response = strdup(*response);
+
+ return 0;
+}
+
+/**
+ * Create a rspauth= response.
+ * Assumes that the A1hash/password serverNonce, clientNC, clientNonce, clientQOP is set.
+ *
+ * @return the rspauth string (including rspauth), return key are stored in serverReply and will be invalid after another call to heim_digest_*
+ */
+
+const char *
+heim_digest_server_response(heim_digest_t context)
+{
+ char *a1;
+
+ if (context->serverNonce == NULL)
+ return NULL;
+ if (context->clientURI == NULL)
+ return NULL;
+
+ a1 = build_A1_hash(context);
+ if (a1 == NULL)
+ return NULL;
+
+ build_server_response(context, a1, NULL);
+ MEMSET_FREE_AND_CLEAR(a1);
+
+ return context->serverReply;
+}
+
+void
+heim_digest_get_session_key(heim_digest_t context, void **key, size_t *keySize)
+{
+}
+
+void
+heim_digest_release(heim_digest_t context)
+{
+ clear_context(context);
+ free(context);
+}
+
+struct {
+ char *name;
+ size_t offset;
+} keys[] = {
+#define KVN(value) { #value, offsetof(struct heim_digest_desc, value) }
+ KVN(serverNonce),
+ KVN(serverRealm),
+ KVN(serverQOP),
+ KVN(serverMethod),
+ { "method", offsetof(struct heim_digest_desc, serverMethod) },
+ KVN(serverMaxbuf),
+ KVN(clientUsername),
+ { "username", offsetof(struct heim_digest_desc, clientUsername) },
+ KVN(clientResponse),
+ KVN(clientURI),
+ { "uri", offsetof(struct heim_digest_desc, clientURI) },
+ KVN(clientRealm),
+ { "realm", offsetof(struct heim_digest_desc, clientRealm) },
+ KVN(clientNonce),
+ KVN(clientQOP),
+ KVN(clientNC),
+ KVN(serverAlgorithm),
+ KVN(auth_id)
+#undef KVN
+};
+
+const char *
+heim_digest_get_key(heim_digest_t context, const char *key)
+{
+ size_t n;
+
+ for (n = 0; n < sizeof(keys) / sizeof(keys[0]); n++) {
+ if (strcasecmp(key, keys[n].name) == 0) {
+ char **ptr = (char **)((((char *)context) + keys[n].offset));
+ return *ptr;
+ }
+ }
+ return NULL;
+}
+
+int
+heim_digest_set_key(heim_digest_t context, const char *key, const char *value)
+{
+
+ if (strcmp(key, "password") == 0) {
+ FREE_AND_CLEAR(context->password);
+ if ((context->password = strdup(value)) == NULL)
+ return ENOMEM;
+ context->flags &= ~(F_HAVE_HASH|F_HAVE_HA1);
+ } else if (strcmp(key, "userhash") == 0) {
+ ssize_t ret;
+ FREE_AND_CLEAR(context->password);
+
+ ret = hex_decode(value, context->SecretHash, sizeof(context->SecretHash));
+ if (ret != sizeof(context->SecretHash))
+ return EINVAL;
+ context->flags &= ~F_HAVE_HA1;
+ context->flags |= F_HAVE_HASH;
+ } else if (strcmp(key, "H(A1)") == 0) {
+ ssize_t ret;
+ FREE_AND_CLEAR(context->password);
+
+ ret = hex_decode(value, context->SecretHash, sizeof(context->SecretHash));
+ if (ret != sizeof(context->SecretHash))
+ return EINVAL;
+ context->flags &= ~F_HAVE_HASH;
+ context->flags |= F_HAVE_HA1;
+ } else if (strcmp(key, "method") == 0) {
+ FREE_AND_CLEAR(context->serverMethod);
+ if ((context->serverMethod = strdup(value)) == NULL)
+ return ENOMEM;
+ } else {
+ size_t n;
+
+ for (n = 0; n < sizeof(keys) / sizeof(keys[0]); n++) {
+ if (strcasecmp(key, keys[n].name) == 0) {
+ char **ptr = (char **)((((char *)context) + keys[n].offset));
+ FREE_AND_CLEAR(*ptr);
+ if (((*ptr) = strdup(value)) == NULL)
+ return ENOMEM;
+ break;
+ }
+ }
+ if (n == sizeof(keys) / sizeof(keys[0]))
+ return ENOENT;
+ }
+ return 0;
+}
+
diff --git a/third_party/heimdal/lib/ntlm/heim-auth.h b/third_party/heimdal/lib/ntlm/heim-auth.h
new file mode 100644
index 0000000..a828de3
--- /dev/null
+++ b/third_party/heimdal/lib/ntlm/heim-auth.h
@@ -0,0 +1,135 @@
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/*
+ * Generate challange for APOP and CRAM-MD5
+ */
+
+char *
+heim_generate_challenge(const char *hostname); /* hostname can be NULL, the local hostname is used */
+
+/*
+ * APOP
+ */
+
+char *
+heim_apop_create(const char *challenge, const char *password);
+
+int
+heim_apop_verify(const char *challenge, const char *password, const char *response);
+
+/*
+ * CRAM-MD5
+ */
+
+typedef struct heim_HMAC_MD5_STATE_s {
+ uint32_t istate[4];
+ uint32_t ostate[4];
+} heim_CRAM_MD5_STATE;
+
+typedef struct heim_cram_md5_data *heim_cram_md5;
+
+char *
+heim_cram_md5_create(const char *challenge, const char *password);
+
+int
+heim_cram_md5_verify(const char *challenge, const char *password, const char *response);
+
+void
+heim_cram_md5_export(const char *password, heim_CRAM_MD5_STATE *state);
+
+heim_cram_md5
+heim_cram_md5_import(void *data, size_t len);
+
+int
+heim_cram_md5_verify_ctx(heim_cram_md5 ctx, const char *challenge, const char *response);
+
+void
+heim_cram_md5_free(heim_cram_md5 ctx);
+
+/*
+ * DIGEST-MD5
+ *
+ * heim_digest_t d;
+ *
+ * d = heim_digest_create(1, HEIM_DIGEST_TYPE_DIGEST_MD5_HTTP);
+ *
+ * if ((s = heim_digest_generate_challange(d)) != NULL) abort();
+ * send_to_client(s);
+ * response = read_from_client();
+ *
+ * heim_digest_parse_response(d, response);
+ * const char *user = heim_digest_get_key(d, "username");
+ * heim_digest_set_key(d, "password", "sommar17");
+ *
+ * if (heim_digest_verify(d, &response)) abort();
+ *
+ * send_to_client(response);
+ *
+ * heim_digest_release(d);
+ */
+
+typedef struct heim_digest_desc *heim_digest_t;
+
+heim_digest_t
+heim_digest_create(int server, int type);
+
+#define HEIM_DIGEST_TYPE_AUTO 0
+#define HEIM_DIGEST_TYPE_RFC2069 1
+#define HEIM_DIGEST_TYPE_RFC2617_MD5 2
+#define HEIM_DIGEST_TYPE_RFC2617_MD5_SESS 4
+#define HEIM_DIGEST_TYPE_RFC2831 8
+
+#define HEIM_DIGEST_TYPE_RFC2617_OR_RFC2831 12
+
+/* old deprecated names, use the two above instead */
+#define HEIM_DIGEST_TYPE_MD5 2
+#define HEIM_DIGEST_TYPE_MD5_SESS 4
+
+void
+heim_digest_init_set_key(heim_digest_t context, const char *key, const char *value);
+
+const char *
+heim_digest_generate_challenge(heim_digest_t context);
+
+int
+heim_digest_parse_challenge(heim_digest_t context, const char *challenge);
+
+int
+heim_digest_parse_response(heim_digest_t context, const char *response);
+
+const char *
+heim_digest_get_key(heim_digest_t context, const char *key);
+
+int
+heim_digest_set_key(heim_digest_t context, const char *key, const char *value);
+
+void
+heim_digest_set_user_password(heim_digest_t context, const char *password);
+
+void
+heim_digest_set_user_h1hash(heim_digest_t context, void *ptr, size_t size);
+
+int
+heim_digest_verify(heim_digest_t context, char **response);
+
+const char *
+heim_digest_create_response(heim_digest_t context, char **response);
+
+void
+heim_digest_get_session_key(heim_digest_t context, void **key, size_t *keySize);
+
+void
+heim_digest_release(heim_digest_t context);
+
+char *
+heim_digest_userhash(const char *user, const char *realm, const char *password);
+
+const char *
+heim_digest_server_response(heim_digest_t context);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/third_party/heimdal/lib/ntlm/heimntlm.h b/third_party/heimdal/lib/ntlm/heimntlm.h
new file mode 100644
index 0000000..6b24649
--- /dev/null
+++ b/third_party/heimdal/lib/ntlm/heimntlm.h
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef HEIM_NTLM_H
+#define HEIM_NTLM_H
+
+/**
+ * Buffer for storing data in the NTLM library. When filled in by the
+ * library it should be freed with heim_ntlm_free_buf().
+ */
+struct ntlm_buf {
+ size_t length; /**< length buffer data */
+ void *data; /**< pointer to the data itself */
+};
+
+#define NTLM_NEG_UNICODE 0x00000001
+#define NTLM_NEG_OEM 0x00000002
+#define NTLM_NEG_TARGET 0x00000004
+#define NTLM_MBZ9 0x00000008
+
+#define NTLM_NEG_SIGN 0x00000010
+#define NTLM_NEG_SEAL 0x00000020
+#define NTLM_NEG_DATAGRAM 0x00000040
+#define NTLM_NEG_LM_KEY 0x00000080
+#define NTLM_NEG_NTLM 0x00000200
+#define NTLM_NEG_ANONYMOUS 0x00000800
+
+#define NTLM_MBZ8 0x00000100
+#define NTLM_NEG_NTLM 0x00000200
+#define NTLM_NEG_NT_ONLY 0x00000400
+#define NTLM_MBZ7 0x00000800 /* anon ? */
+
+#define NTLM_OEM_SUPPLIED_DOMAIN 0x00001000
+#define NTLM_OEM_SUPPLIED_WORKSTATION 0x00002000
+#define NTLM_MBZ6 0x00004000 /* local call ? */
+#define NTLM_NEG_ALWAYS_SIGN 0x00008000
+
+#define NTLM_TARGET_DOMAIN 0x00010000
+#define NTLM_TARGET_SERVER 0x00020000
+
+#define NTLM_TARGET_SHARE 0x00040000 /* mbz */
+#define NTLM_NEG_NTLM2_SESSION 0x00080000 /* EXTENDED_SESSIONSECURITY */
+#define NTLM_NEG_NTLM2 0x00080000
+
+#define NTLM_NEG_IDENTIFY 0x00100000
+#define NTLM_MBZ5 0x00200000
+#define NTLM_NON_NT_SESSION_KEY 0x00400000
+#define NTLM_NEG_TARGET_INFO 0x00800000
+
+#define NTLM_MBZ4 0x01000000
+#define NTLM_NEG_VERSION 0x02000000
+#define NTLM_MBZ3 0x04000000
+#define NTLM_MBZ2 0x08000000
+
+#define NTLM_MBZ1 0x10000000
+#define NTLM_ENC_128 0x20000000
+#define NTLM_NEG_KEYEX 0x40000000
+#define NTLM_ENC_56 0x80000000
+
+/**
+ * Struct for the NTLM target info, the strings is assumed to be in
+ * UTF8. When filled in by the library it should be freed with
+ * heim_ntlm_free_targetinfo().
+ */
+
+/* avflags */
+#define NTLM_TI_AV_FLAG_GUEST 0x00000001
+#define NTLM_TI_AV_FLAG_MIC 0x00000002
+
+struct ntlm_targetinfo {
+ char *servername; /**< */
+ char *domainname; /**< */
+ char *dnsdomainname; /**< */
+ char *dnsservername; /**< */
+ char *dnstreename; /**< */
+ uint32_t avflags; /**< */
+ char *targetname;
+ struct ntlm_buf channel_bindings;
+ uint64_t timestamp;
+};
+
+/**
+ * Struct for the NTLM type1 message info, the strings is assumed to
+ * be in UTF8. When filled in by the library it should be freed with
+ * heim_ntlm_free_type1().
+ */
+
+struct ntlm_type1 {
+ uint32_t flags; /**< */
+ char *domain; /**< */
+ char *hostname; /**< */
+ uint32_t os[2]; /**< */
+};
+
+/**
+ * Struct for the NTLM type2 message info, the strings is assumed to
+ * be in UTF8. When filled in by the library it should be freed with
+ * heim_ntlm_free_type2().
+ */
+
+struct ntlm_type2 {
+ uint32_t flags; /**< */
+ char *targetname; /**< */
+ struct ntlm_buf targetinfo; /**< */
+ unsigned char challenge[8]; /**< */
+ uint32_t context[2]; /**< */
+ uint32_t os[2]; /**< */
+};
+
+/**
+ * Struct for the NTLM type3 message info, the strings is assumed to
+ * be in UTF8. When filled in by the library it should be freed with
+ * heim_ntlm_free_type3().
+ */
+
+struct ntlm_type3 {
+ uint32_t flags; /**< */
+ char *username; /**< */
+ char *targetname; /**< */
+ struct ntlm_buf lm; /**< */
+ struct ntlm_buf ntlm; /**< */
+ struct ntlm_buf sessionkey; /**< */
+ char *ws; /**< */
+ uint32_t os[2]; /**< */
+ size_t mic_offset;
+ uint8_t mic[16];
+};
+
+extern time_t heim_ntlm_time_skew;
+
+#include <ntlm_err.h>
+#include <heimntlm-protos.h>
+
+#endif /* NTLM_NTLM_H */
diff --git a/third_party/heimdal/lib/ntlm/libheimntlm-exports.def b/third_party/heimdal/lib/ntlm/libheimntlm-exports.def
new file mode 100644
index 0000000..33ac09e
--- /dev/null
+++ b/third_party/heimdal/lib/ntlm/libheimntlm-exports.def
@@ -0,0 +1,24 @@
+EXPORTS
+ heim_ntlm_build_ntlm1_master
+ heim_ntlm_calculate_lm2
+ heim_ntlm_calculate_ntlm1
+ heim_ntlm_calculate_ntlm2
+ heim_ntlm_calculate_ntlm2_sess
+ heim_ntlm_decode_targetinfo
+ heim_ntlm_decode_type1
+ heim_ntlm_decode_type2
+ heim_ntlm_decode_type3
+ heim_ntlm_encode_targetinfo
+ heim_ntlm_encode_type1
+ heim_ntlm_encode_type2
+ heim_ntlm_encode_type3
+ heim_ntlm_free_buf
+ heim_ntlm_free_targetinfo
+ heim_ntlm_free_type1
+ heim_ntlm_free_type2
+ heim_ntlm_free_type3
+ heim_ntlm_nt_key
+ heim_ntlm_ntlmv2_key
+ heim_ntlm_verify_ntlm2
+ heim_ntlm_unparse_flags
+ initialize_ntlm_error_table_r
diff --git a/third_party/heimdal/lib/ntlm/libheimntlm-version.rc b/third_party/heimdal/lib/ntlm/libheimntlm-version.rc
new file mode 100644
index 0000000..2055c9d
--- /dev/null
+++ b/third_party/heimdal/lib/ntlm/libheimntlm-version.rc
@@ -0,0 +1,36 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#define RC_FILE_TYPE VFT_DLL
+#define RC_FILE_DESC_0409 "Heimdal NTLM Support Library"
+#define RC_FILE_ORIG_0409 "libheimntlm.dll"
+
+#include "../../windows/version.rc"
diff --git a/third_party/heimdal/lib/ntlm/ntlm.c b/third_party/heimdal/lib/ntlm/ntlm.c
new file mode 100644
index 0000000..d75752e
--- /dev/null
+++ b/third_party/heimdal/lib/ntlm/ntlm.c
@@ -0,0 +1,2030 @@
+/*
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <string.h>
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
+
+#include <roken.h>
+
+#include <wind.h>
+#include <parse_units.h>
+#include <krb5.h>
+
+
+#define HC_DEPRECATED_CRYPTO
+
+#include "krb5-types.h"
+#include "crypto-headers.h"
+
+#include <heimntlm.h>
+
+/*! \mainpage Heimdal NTLM library
+ *
+ * \section intro Introduction
+ *
+ * Heimdal libheimntlm library is a implementation of the NTLM
+ * protocol, both version 1 and 2. The GSS-API mech that uses this
+ * library adds support for transport encryption and integrity
+ * checking.
+ *
+ * NTLM is a protocol for mutual authentication, its still used in
+ * many protocol where Kerberos is not support, one example is
+ * EAP/X802.1x mechanism LEAP from Microsoft and Cisco.
+ *
+ * This is a support library for the core protocol, its used in
+ * Heimdal to implement and GSS-API mechanism. There is also support
+ * in the KDC to do remote digest authenticiation, this to allow
+ * services to authenticate users w/o direct access to the users ntlm
+ * hashes (same as Kerberos arcfour enctype keys).
+ *
+ * More information about the NTLM protocol can found here
+ * http://davenport.sourceforge.net/ntlm.html .
+ *
+ * The Heimdal projects web page: http://www.h5l.org/
+ *
+ * @section ntlm_example NTLM Example
+ *
+ * Example to to use @ref test_ntlm.c .
+ *
+ * @example test_ntlm.c
+ *
+ * Example how to use the NTLM primitives.
+ *
+ */
+
+/** @defgroup ntlm_core Heimdal NTLM library
+ *
+ * The NTLM core functions implement the string2key generation
+ * function, message encode and decode function, and the hash function
+ * functions.
+ */
+
+struct sec_buffer {
+ uint16_t length;
+ uint16_t allocated;
+ uint32_t offset;
+};
+
+static const unsigned char ntlmsigature[8] = "NTLMSSP\x00";
+
+time_t heim_ntlm_time_skew = 300;
+
+/*
+ *
+ */
+
+#define CHECK(f, e) \
+ do { \
+ ret = f; \
+ if (ret != (ssize_t)(e)) { \
+ ret = HNTLM_ERR_DECODE; \
+ goto out; \
+ } \
+ } while(/*CONSTCOND*/0)
+
+#define CHECK_SIZE(f, e) \
+ do { \
+ ssize_t sret = f; \
+ if (sret != (ssize_t)(e)) { \
+ ret = HNTLM_ERR_DECODE; \
+ goto out; \
+ } \
+ } while(/*CONSTCOND*/0)
+
+#define CHECK_OFFSET(f, e) \
+ do { \
+ off_t sret = f; \
+ if (sret != (e)) { \
+ ret = HNTLM_ERR_DECODE; \
+ goto out; \
+ } \
+ } while(/*CONSTCOND*/0)
+
+
+static struct units ntlm_flag_units[] = {
+#define ntlm_flag(x) { #x, NTLM_##x }
+ ntlm_flag(ENC_56),
+ ntlm_flag(NEG_KEYEX),
+ ntlm_flag(ENC_128),
+ ntlm_flag(MBZ1),
+ ntlm_flag(MBZ2),
+ ntlm_flag(MBZ3),
+ ntlm_flag(NEG_VERSION),
+ ntlm_flag(MBZ4),
+ ntlm_flag(NEG_TARGET_INFO),
+ ntlm_flag(NON_NT_SESSION_KEY),
+ ntlm_flag(MBZ5),
+ ntlm_flag(NEG_IDENTIFY),
+ ntlm_flag(NEG_NTLM2),
+ ntlm_flag(TARGET_SHARE),
+ ntlm_flag(TARGET_SERVER),
+ ntlm_flag(TARGET_DOMAIN),
+ ntlm_flag(NEG_ALWAYS_SIGN),
+ ntlm_flag(MBZ6),
+ ntlm_flag(OEM_SUPPLIED_WORKSTATION),
+ ntlm_flag(OEM_SUPPLIED_DOMAIN),
+ ntlm_flag(NEG_ANONYMOUS),
+ ntlm_flag(NEG_NT_ONLY),
+ ntlm_flag(NEG_NTLM),
+ ntlm_flag(MBZ8),
+ ntlm_flag(NEG_LM_KEY),
+ ntlm_flag(NEG_DATAGRAM),
+ ntlm_flag(NEG_SEAL),
+ ntlm_flag(NEG_SIGN),
+ ntlm_flag(MBZ9),
+ ntlm_flag(NEG_TARGET),
+ ntlm_flag(NEG_OEM),
+ ntlm_flag(NEG_UNICODE),
+#undef ntlm_flag
+ {NULL, 0}
+};
+
+size_t
+heim_ntlm_unparse_flags(uint32_t flags, char *s, size_t len)
+{
+ return unparse_flags(flags, ntlm_flag_units, s, len);
+}
+
+
+/**
+ * heim_ntlm_free_buf frees the ntlm buffer
+ *
+ * @param p buffer to be freed
+ *
+ * @ingroup ntlm_core
+ */
+
+void
+heim_ntlm_free_buf(struct ntlm_buf *p)
+{
+ if (p->data)
+ free(p->data);
+ p->data = NULL;
+ p->length = 0;
+}
+
+
+static int
+ascii2ucs2le(const char *string, int up, struct ntlm_buf *buf)
+{
+ uint16_t *data;
+ size_t len, n;
+ uint8_t *p;
+ int ret;
+
+ ret = wind_utf8ucs2_length(string, &len);
+ if (ret)
+ return ret;
+ if (len > UINT_MAX / sizeof(data[0]))
+ return ERANGE;
+
+ data = malloc(len * sizeof(data[0]));
+ if (data == NULL)
+ return ENOMEM;
+
+ ret = wind_utf8ucs2(string, data, &len);
+ if (ret) {
+ free(data);
+ return ret;
+ }
+
+ if (len == 0) {
+ free(data);
+ buf->data = NULL;
+ buf->length = 0;
+ return 0;
+ }
+
+ /* uppercase string, only handle ascii right now */
+ if (up) {
+ for (n = 0; n < len ; n++) {
+ if (data[n] < 128)
+ data[n] = toupper((int)data[n]);
+ }
+ }
+
+ buf->length = len * 2;
+ p = buf->data = malloc(buf->length);
+ if (buf->data == NULL && len != 0) {
+ free(data);
+ heim_ntlm_free_buf(buf);
+ return ENOMEM;
+ }
+
+ for (n = 0; n < len ; n++) {
+ p[(n * 2) + 0] = (data[n] ) & 0xff;
+ p[(n * 2) + 1] = (data[n] >> 8) & 0xff;
+ }
+ memset(data, 0, sizeof(data[0]) * len);
+ free(data);
+
+ return 0;
+}
+
+/*
+ * Sizes in bytes
+ */
+
+#define SIZE_SEC_BUFFER (2+2+4)
+#define SIZE_OS_VERSION (8)
+
+/*
+ *
+ */
+
+static krb5_error_code
+ret_sec_buffer(krb5_storage *sp, struct sec_buffer *buf)
+{
+ krb5_error_code ret;
+ CHECK(krb5_ret_uint16(sp, &buf->length), 0);
+ CHECK(krb5_ret_uint16(sp, &buf->allocated), 0);
+ CHECK(krb5_ret_uint32(sp, &buf->offset), 0);
+out:
+ return ret;
+}
+
+static krb5_error_code
+store_sec_buffer(krb5_storage *sp, const struct sec_buffer *buf)
+{
+ krb5_error_code ret;
+ CHECK(krb5_store_uint16(sp, buf->length), 0);
+ CHECK(krb5_store_uint16(sp, buf->allocated), 0);
+ CHECK(krb5_store_uint32(sp, buf->offset), 0);
+out:
+ return ret;
+}
+
+/*
+ * Strings are either OEM or UNICODE. The later is encoded as ucs2 on
+ * wire, but using utf8 in memory.
+ */
+
+static size_t
+len_string(int ucs2, const char *s)
+{
+ if (ucs2) {
+ size_t len;
+ int ret;
+
+ ret = wind_utf8ucs2_length(s, &len);
+ if (ret == 0)
+ return len * 2;
+ return strlen(s) * 5 * 2;
+ } else {
+ return strlen(s);
+ }
+}
+
+/*
+ *
+ */
+
+static krb5_error_code
+ret_string(krb5_storage *sp, int ucs2, size_t len, char **s)
+{
+ krb5_error_code ret;
+ uint16_t *data = NULL;
+
+ *s = malloc(len + 1);
+ if (*s == NULL)
+ return ENOMEM;
+ CHECK_SIZE(krb5_storage_read(sp, *s, len), len);
+
+ (*s)[len] = '\0';
+
+ if (ucs2) {
+ unsigned int flags = WIND_RW_LE;
+ size_t utf16len = len / 2;
+ size_t utf8len;
+
+ data = malloc(utf16len * sizeof(data[0]));
+ if (data == NULL) {
+ free(*s); *s = NULL;
+ ret = ENOMEM;
+ goto out;
+ }
+
+ ret = wind_ucs2read(*s, len, &flags, data, &utf16len);
+ free(*s); *s = NULL;
+ if (ret) {
+ goto out;
+ }
+
+ CHECK(wind_ucs2utf8_length(data, utf16len, &utf8len), 0);
+
+ utf8len += 1;
+
+ *s = malloc(utf8len);
+ if (*s == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ CHECK(wind_ucs2utf8(data, utf16len, *s, &utf8len), 0);
+ }
+ ret = 0;
+ out:
+ if (data)
+ free(data);
+
+ return ret;
+}
+
+
+
+static krb5_error_code
+ret_sec_string(krb5_storage *sp, int ucs2, struct sec_buffer *desc, char **s)
+{
+ krb5_error_code ret = 0;
+ CHECK_OFFSET(krb5_storage_seek(sp, desc->offset, SEEK_SET), desc->offset);
+ CHECK(ret_string(sp, ucs2, desc->length, s), 0);
+ out:
+ return ret;
+}
+
+static krb5_error_code
+put_string(krb5_storage *sp, int ucs2, const char *s)
+{
+ krb5_error_code ret;
+ struct ntlm_buf buf;
+
+ if (ucs2) {
+ ret = ascii2ucs2le(s, 0, &buf);
+ if (ret)
+ return ret;
+ } else {
+ buf.data = rk_UNCONST(s);
+ buf.length = strlen(s);
+ }
+
+ CHECK_SIZE(krb5_storage_write(sp, buf.data, buf.length), buf.length);
+ if (ucs2)
+ heim_ntlm_free_buf(&buf);
+ ret = 0;
+out:
+ return ret;
+}
+
+/*
+ *
+ */
+
+static krb5_error_code
+ret_buf(krb5_storage *sp, struct sec_buffer *desc, struct ntlm_buf *buf)
+{
+ krb5_error_code ret;
+
+ buf->data = malloc(desc->length);
+ buf->length = desc->length;
+ CHECK_OFFSET(krb5_storage_seek(sp, desc->offset, SEEK_SET), desc->offset);
+ CHECK_SIZE(krb5_storage_read(sp, buf->data, buf->length), buf->length);
+ ret = 0;
+out:
+ return ret;
+}
+
+static krb5_error_code
+put_buf(krb5_storage *sp, const struct ntlm_buf *buf)
+{
+ krb5_error_code ret;
+ CHECK_SIZE(krb5_storage_write(sp, buf->data, buf->length), buf->length);
+ ret = 0;
+out:
+ return ret;
+}
+
+/**
+ * Frees the ntlm_targetinfo message
+ *
+ * @param ti targetinfo to be freed
+ *
+ * @ingroup ntlm_core
+ */
+
+void
+heim_ntlm_free_targetinfo(struct ntlm_targetinfo *ti)
+{
+ free(ti->servername);
+ free(ti->domainname);
+ free(ti->dnsdomainname);
+ free(ti->dnsservername);
+ free(ti->dnstreename);
+ free(ti->targetname);
+ heim_ntlm_free_buf(&ti->channel_bindings);
+ memset(ti, 0, sizeof(*ti));
+}
+
+static int
+encode_ti_string(krb5_storage *out, uint16_t type, int ucs2, char *s)
+{
+ krb5_error_code ret;
+ CHECK(krb5_store_uint16(out, type), 0);
+ CHECK(krb5_store_uint16(out, len_string(ucs2, s)), 0);
+ CHECK(put_string(out, ucs2, s), 0);
+out:
+ return ret;
+}
+
+/**
+ * Encodes a ntlm_targetinfo message.
+ *
+ * @param ti the ntlm_targetinfo message to encode.
+ * @param ucs2 ignored
+ * @param data is the return buffer with the encoded message, should be
+ * freed with heim_ntlm_free_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_encode_targetinfo(const struct ntlm_targetinfo *ti,
+ int ucs2,
+ struct ntlm_buf *data)
+{
+ krb5_error_code ret;
+ krb5_storage *out;
+
+ data->data = NULL;
+ data->length = 0;
+
+ out = krb5_storage_emem();
+ if (out == NULL)
+ return ENOMEM;
+
+ krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
+
+ if (ti->servername)
+ CHECK(encode_ti_string(out, 1, ucs2, ti->servername), 0);
+ if (ti->domainname)
+ CHECK(encode_ti_string(out, 2, ucs2, ti->domainname), 0);
+ if (ti->dnsservername)
+ CHECK(encode_ti_string(out, 3, ucs2, ti->dnsservername), 0);
+ if (ti->dnsdomainname)
+ CHECK(encode_ti_string(out, 4, ucs2, ti->dnsdomainname), 0);
+ if (ti->dnstreename)
+ CHECK(encode_ti_string(out, 5, ucs2, ti->dnstreename), 0);
+ if (ti->avflags) {
+ CHECK(krb5_store_uint16(out, 6), 0);
+ CHECK(krb5_store_uint16(out, 4), 0);
+ CHECK(krb5_store_uint32(out, ti->avflags), 0);
+ }
+ if (ti->timestamp) {
+ CHECK(krb5_store_uint16(out, 7), 0);
+ CHECK(krb5_store_uint16(out, 8), 0);
+ CHECK(krb5_store_uint32(out, ti->timestamp & 0xffffffff), 0);
+ CHECK(krb5_store_uint32(out, (ti->timestamp >> 32) & 0xffffffff), 0);
+ }
+ if (ti->targetname) {
+ CHECK(encode_ti_string(out, 9, ucs2, ti->targetname), 0);
+ }
+ if (ti->channel_bindings.length) {
+ CHECK(krb5_store_uint16(out, 10), 0);
+ CHECK(krb5_store_uint16(out, ti->channel_bindings.length), 0);
+ CHECK_SIZE(krb5_storage_write(out, ti->channel_bindings.data, ti->channel_bindings.length), ti->channel_bindings.length);
+ }
+
+ /* end tag */
+ CHECK(krb5_store_int16(out, 0), 0);
+ CHECK(krb5_store_int16(out, 0), 0);
+
+ {
+ krb5_data d;
+ ret = krb5_storage_to_data(out, &d);
+ data->data = d.data;
+ data->length = d.length;
+ }
+out:
+ krb5_storage_free(out);
+ return ret;
+}
+
+/**
+ * Decodes an NTLM targetinfo message
+ *
+ * @param data input data buffer with the encode NTLM targetinfo message
+ * @param ucs2 if the strings should be encoded with ucs2 (selected by flag in message).
+ * @param ti the decoded target info, should be freed with heim_ntlm_free_targetinfo().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_decode_targetinfo(const struct ntlm_buf *data,
+ int ucs2,
+ struct ntlm_targetinfo *ti)
+{
+ uint16_t type, len;
+ krb5_storage *in;
+ int ret = 0, done = 0;
+
+ memset(ti, 0, sizeof(*ti));
+
+ if (data->length == 0)
+ return 0;
+
+ in = krb5_storage_from_readonly_mem(data->data, data->length);
+ if (in == NULL)
+ return ENOMEM;
+ krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
+
+ while (!done) {
+ CHECK(krb5_ret_uint16(in, &type), 0);
+ CHECK(krb5_ret_uint16(in, &len), 0);
+
+ switch (type) {
+ case 0:
+ done = 1;
+ break;
+ case 1:
+ CHECK(ret_string(in, ucs2, len, &ti->servername), 0);
+ break;
+ case 2:
+ CHECK(ret_string(in, ucs2, len, &ti->domainname), 0);
+ break;
+ case 3:
+ CHECK(ret_string(in, ucs2, len, &ti->dnsservername), 0);
+ break;
+ case 4:
+ CHECK(ret_string(in, ucs2, len, &ti->dnsdomainname), 0);
+ break;
+ case 5:
+ CHECK(ret_string(in, ucs2, len, &ti->dnstreename), 0);
+ break;
+ case 6:
+ CHECK(krb5_ret_uint32(in, &ti->avflags), 0);
+ break;
+ case 7: {
+ uint32_t tmp;
+ CHECK(krb5_ret_uint32(in, &tmp), 0);
+ ti->timestamp = tmp;
+ CHECK(krb5_ret_uint32(in, &tmp), 0);
+ ti->timestamp |= ((uint64_t)tmp) << 32;
+ break;
+ }
+ case 9:
+ CHECK(ret_string(in, 1, len, &ti->targetname), 0);
+ break;
+ case 10:
+ ti->channel_bindings.data = malloc(len);
+ if (ti->channel_bindings.data == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ ti->channel_bindings.length = len;
+ CHECK_SIZE(krb5_storage_read(in, ti->channel_bindings.data, len), len);
+ break;
+ default:
+ krb5_storage_seek(in, len, SEEK_CUR);
+ break;
+ }
+ }
+ out:
+ if (in)
+ krb5_storage_free(in);
+ return ret;
+}
+
+static krb5_error_code
+encode_os_version(krb5_storage *out)
+{
+ krb5_error_code ret;
+ CHECK(krb5_store_uint8(out, 0x06), 0);
+ CHECK(krb5_store_uint8(out, 0x01), 0);
+ CHECK(krb5_store_uint16(out, 0x1db0), 0);
+ CHECK(krb5_store_uint8(out, 0x00), 0);
+ CHECK(krb5_store_uint8(out, 0x00), 0);
+ CHECK(krb5_store_uint8(out, 0x00), 0);
+ CHECK(krb5_store_uint8(out, 0x0f), 0); /* ntlm version 15 */
+ out:
+ return ret;
+}
+
+/**
+ * Frees the ntlm_type1 message
+ *
+ * @param data message to be freed
+ *
+ * @ingroup ntlm_core
+ */
+
+void
+heim_ntlm_free_type1(struct ntlm_type1 *data)
+{
+ if (data->domain)
+ free(data->domain);
+ if (data->hostname)
+ free(data->hostname);
+ memset(data, 0, sizeof(*data));
+}
+
+int
+heim_ntlm_decode_type1(const struct ntlm_buf *buf, struct ntlm_type1 *data)
+{
+ krb5_error_code ret;
+ unsigned char sig[8];
+ uint32_t type;
+ struct sec_buffer domain, hostname;
+ krb5_storage *in;
+ int ucs2;
+
+ memset(data, 0, sizeof(*data));
+
+ in = krb5_storage_from_readonly_mem(buf->data, buf->length);
+ if (in == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
+
+ CHECK_SIZE(krb5_storage_read(in, sig, sizeof(sig)), sizeof(sig));
+ CHECK(memcmp(ntlmsigature, sig, sizeof(ntlmsigature)), 0);
+ CHECK(krb5_ret_uint32(in, &type), 0);
+ CHECK(type, 1);
+ CHECK(krb5_ret_uint32(in, &data->flags), 0);
+
+ ucs2 = !!(data->flags & NTLM_NEG_UNICODE);
+
+ /*
+ * domain and hostname are unconditionally encoded regardless of
+ * NTLMSSP_NEGOTIATE_OEM_{HOSTNAME,WORKSTATION}_SUPPLIED flag
+ */
+ CHECK(ret_sec_buffer(in, &domain), 0);
+ CHECK(ret_sec_buffer(in, &hostname), 0);
+
+ if (data->flags & NTLM_NEG_VERSION) {
+ CHECK(krb5_ret_uint32(in, &data->os[0]), 0);
+ CHECK(krb5_ret_uint32(in, &data->os[1]), 0);
+ }
+
+ if (data->flags & NTLM_OEM_SUPPLIED_DOMAIN)
+ CHECK(ret_sec_string(in, ucs2, &domain, &data->domain), 0);
+ if (data->flags & NTLM_OEM_SUPPLIED_WORKSTATION)
+ CHECK(ret_sec_string(in, ucs2, &hostname, &data->hostname), 0);
+
+out:
+ if (in)
+ krb5_storage_free(in);
+ if (ret)
+ heim_ntlm_free_type1(data);
+
+ return ret;
+}
+
+/**
+ * Encodes an ntlm_type1 message.
+ *
+ * @param type1 the ntlm_type1 message to encode.
+ * @param data is the return buffer with the encoded message, should be
+ * freed with heim_ntlm_free_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_encode_type1(const struct ntlm_type1 *type1, struct ntlm_buf *data)
+{
+ krb5_error_code ret;
+ struct sec_buffer domain, hostname;
+ krb5_storage *out;
+ uint32_t base, flags;
+ int ucs2 = 0;
+
+ flags = type1->flags;
+ base = 16;
+
+ if (flags & NTLM_NEG_UNICODE)
+ ucs2 = 1;
+
+ if (type1->domain) {
+ base += SIZE_SEC_BUFFER;
+ flags |= NTLM_OEM_SUPPLIED_DOMAIN;
+ }
+ if (type1->hostname) {
+ base += SIZE_SEC_BUFFER;
+ flags |= NTLM_OEM_SUPPLIED_WORKSTATION;
+ }
+ if (flags & NTLM_NEG_VERSION)
+ base += SIZE_OS_VERSION; /* os */
+
+ if (type1->domain) {
+ domain.offset = base;
+ domain.length = len_string(ucs2, type1->domain);
+ domain.allocated = domain.length;
+ } else {
+ domain.offset = 0;
+ domain.length = 0;
+ domain.allocated = 0;
+ }
+
+ if (type1->hostname) {
+ hostname.offset = domain.allocated + domain.offset;
+ hostname.length = len_string(ucs2, type1->hostname);
+ hostname.allocated = hostname.length;
+ } else {
+ hostname.offset = 0;
+ hostname.length = 0;
+ hostname.allocated = 0;
+ }
+
+ out = krb5_storage_emem();
+ if (out == NULL)
+ return ENOMEM;
+
+ krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
+ CHECK_SIZE(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)),
+ sizeof(ntlmsigature));
+ CHECK(krb5_store_uint32(out, 1), 0);
+ CHECK(krb5_store_uint32(out, flags), 0);
+
+ CHECK(store_sec_buffer(out, &domain), 0);
+ CHECK(store_sec_buffer(out, &hostname), 0);
+
+ if (flags & NTLM_NEG_VERSION) {
+ CHECK(encode_os_version(out), 0);
+ }
+ if (type1->domain)
+ CHECK(put_string(out, ucs2, type1->domain), 0);
+ if (type1->hostname)
+ CHECK(put_string(out, ucs2, type1->hostname), 0);
+
+ {
+ krb5_data d;
+ ret = krb5_storage_to_data(out, &d);
+ data->data = d.data;
+ data->length = d.length;
+ }
+out:
+ krb5_storage_free(out);
+
+ return ret;
+}
+
+/**
+ * Frees the ntlm_type2 message
+ *
+ * @param data message to be freed
+ *
+ * @ingroup ntlm_core
+ */
+
+void
+heim_ntlm_free_type2(struct ntlm_type2 *data)
+{
+ if (data->targetname)
+ free(data->targetname);
+ heim_ntlm_free_buf(&data->targetinfo);
+ memset(data, 0, sizeof(*data));
+}
+
+int
+heim_ntlm_decode_type2(const struct ntlm_buf *buf, struct ntlm_type2 *type2)
+{
+ krb5_error_code ret;
+ unsigned char sig[8];
+ uint32_t type, ctx[2];
+ struct sec_buffer targetname, targetinfo;
+ krb5_storage *in;
+ int ucs2 = 0;
+
+ memset(type2, 0, sizeof(*type2));
+
+ in = krb5_storage_from_readonly_mem(buf->data, buf->length);
+ if (in == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
+
+ CHECK_SIZE(krb5_storage_read(in, sig, sizeof(sig)), sizeof(sig));
+ CHECK(memcmp(ntlmsigature, sig, sizeof(ntlmsigature)), 0);
+ CHECK(krb5_ret_uint32(in, &type), 0);
+ CHECK(type, 2);
+
+ CHECK(ret_sec_buffer(in, &targetname), 0);
+ CHECK(krb5_ret_uint32(in, &type2->flags), 0);
+ if (type2->flags & NTLM_NEG_UNICODE)
+ ucs2 = 1;
+ CHECK_SIZE(krb5_storage_read(in, type2->challenge, sizeof(type2->challenge)),
+ sizeof(type2->challenge));
+ CHECK(krb5_ret_uint32(in, &ctx[0]), 0); /* context */
+ CHECK(krb5_ret_uint32(in, &ctx[1]), 0);
+ CHECK(ret_sec_buffer(in, &targetinfo), 0);
+ /* os version */
+ if (type2->flags & NTLM_NEG_VERSION) {
+ CHECK(krb5_ret_uint32(in, &type2->os[0]), 0);
+ CHECK(krb5_ret_uint32(in, &type2->os[1]), 0);
+ }
+
+ CHECK(ret_sec_string(in, ucs2, &targetname, &type2->targetname), 0);
+ CHECK(ret_buf(in, &targetinfo, &type2->targetinfo), 0);
+ ret = 0;
+
+out:
+ if (in)
+ krb5_storage_free(in);
+ if (ret)
+ heim_ntlm_free_type2(type2);
+
+ return ret;
+}
+
+/**
+ * Encodes an ntlm_type2 message.
+ *
+ * @param type2 the ntlm_type2 message to encode.
+ * @param data is the return buffer with the encoded message, should be
+ * freed with heim_ntlm_free_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_encode_type2(const struct ntlm_type2 *type2, struct ntlm_buf *data)
+{
+ struct sec_buffer targetname, targetinfo;
+ krb5_error_code ret;
+ krb5_storage *out = NULL;
+ uint32_t base;
+ int ucs2 = 0;
+
+ base = 48;
+
+ if (type2->flags & NTLM_NEG_VERSION)
+ base += SIZE_OS_VERSION;
+
+ if (type2->flags & NTLM_NEG_UNICODE)
+ ucs2 = 1;
+
+ targetname.offset = base;
+ targetname.length = len_string(ucs2, type2->targetname);
+ targetname.allocated = targetname.length;
+
+ targetinfo.offset = targetname.allocated + targetname.offset;
+ targetinfo.length = type2->targetinfo.length;
+ targetinfo.allocated = type2->targetinfo.length;
+
+ out = krb5_storage_emem();
+ if (out == NULL)
+ return ENOMEM;
+
+ krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
+ CHECK_SIZE(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)),
+ sizeof(ntlmsigature));
+ CHECK(krb5_store_uint32(out, 2), 0);
+ CHECK(store_sec_buffer(out, &targetname), 0);
+ CHECK(krb5_store_uint32(out, type2->flags), 0);
+ CHECK_SIZE(krb5_storage_write(out, type2->challenge, sizeof(type2->challenge)),
+ sizeof(type2->challenge));
+ CHECK(krb5_store_uint32(out, 0), 0); /* context */
+ CHECK(krb5_store_uint32(out, 0), 0);
+ CHECK(store_sec_buffer(out, &targetinfo), 0);
+ /* os version */
+ if (type2->flags & NTLM_NEG_VERSION) {
+ CHECK(encode_os_version(out), 0);
+ }
+ CHECK(put_string(out, ucs2, type2->targetname), 0);
+ CHECK_SIZE(krb5_storage_write(out, type2->targetinfo.data,
+ type2->targetinfo.length),
+ type2->targetinfo.length);
+
+ {
+ krb5_data d;
+ ret = krb5_storage_to_data(out, &d);
+ data->data = d.data;
+ data->length = d.length;
+ }
+
+out:
+ krb5_storage_free(out);
+
+ return ret;
+}
+
+/**
+ * Frees the ntlm_type3 message
+ *
+ * @param data message to be freed
+ *
+ * @ingroup ntlm_core
+ */
+
+void
+heim_ntlm_free_type3(struct ntlm_type3 *data)
+{
+ heim_ntlm_free_buf(&data->lm);
+ heim_ntlm_free_buf(&data->ntlm);
+ if (data->targetname)
+ free(data->targetname);
+ if (data->username)
+ free(data->username);
+ if (data->ws)
+ free(data->ws);
+ heim_ntlm_free_buf(&data->sessionkey);
+ memset(data, 0, sizeof(*data));
+}
+
+/*
+ *
+ */
+
+int
+heim_ntlm_decode_type3(const struct ntlm_buf *buf,
+ int ucs2,
+ struct ntlm_type3 *type3)
+{
+ krb5_error_code ret;
+ unsigned char sig[8];
+ uint32_t type;
+ krb5_storage *in;
+ struct sec_buffer lm, ntlm, target, username, sessionkey, ws;
+ uint32_t min_offset = 0xffffffff;
+
+ memset(type3, 0, sizeof(*type3));
+ memset(&sessionkey, 0, sizeof(sessionkey));
+
+ in = krb5_storage_from_readonly_mem(buf->data, buf->length);
+ if (in == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
+
+ CHECK_SIZE(krb5_storage_read(in, sig, sizeof(sig)), sizeof(sig));
+ CHECK(memcmp(ntlmsigature, sig, sizeof(ntlmsigature)), 0);
+ CHECK(krb5_ret_uint32(in, &type), 0);
+ CHECK(type, 3);
+ CHECK(ret_sec_buffer(in, &lm), 0);
+ if (lm.allocated)
+ min_offset = min(min_offset, lm.offset);
+ CHECK(ret_sec_buffer(in, &ntlm), 0);
+ if (ntlm.allocated)
+ min_offset = min(min_offset, ntlm.offset);
+ CHECK(ret_sec_buffer(in, &target), 0);
+ min_offset = min(min_offset, target.offset);
+ CHECK(ret_sec_buffer(in, &username), 0);
+ min_offset = min(min_offset, username.offset);
+ CHECK(ret_sec_buffer(in, &ws), 0);
+ if (ws.allocated)
+ min_offset = min(min_offset, ws.offset);
+
+ if (min_offset >= 52) {
+ CHECK(ret_sec_buffer(in, &sessionkey), 0);
+ min_offset = min(min_offset, sessionkey.offset);
+ CHECK(krb5_ret_uint32(in, &type3->flags), 0);
+ }
+ if (min_offset >= 52 + SIZE_SEC_BUFFER + 4 + SIZE_OS_VERSION) {
+ CHECK(krb5_ret_uint32(in, &type3->os[0]), 0);
+ CHECK(krb5_ret_uint32(in, &type3->os[1]), 0);
+ }
+ if (min_offset >= 52 + SIZE_SEC_BUFFER + 4 + SIZE_OS_VERSION + 16) {
+ type3->mic_offset = 52 + SIZE_SEC_BUFFER + 4 + SIZE_OS_VERSION;
+ CHECK_SIZE(krb5_storage_read(in, type3->mic, sizeof(type3->mic)), sizeof(type3->mic));
+ } else
+ type3->mic_offset = 0;
+ CHECK(ret_buf(in, &lm, &type3->lm), 0);
+ CHECK(ret_buf(in, &ntlm, &type3->ntlm), 0);
+ CHECK(ret_sec_string(in, ucs2, &target, &type3->targetname), 0);
+ CHECK(ret_sec_string(in, ucs2, &username, &type3->username), 0);
+ CHECK(ret_sec_string(in, ucs2, &ws, &type3->ws), 0);
+ if (sessionkey.offset)
+ CHECK(ret_buf(in, &sessionkey, &type3->sessionkey), 0);
+
+out:
+ if (in)
+ krb5_storage_free(in);
+ if (ret)
+ heim_ntlm_free_type3(type3);
+
+ return ret;
+}
+
+/**
+ * Encodes an ntlm_type3 message.
+ *
+ * @param type3 the ntlm_type3 message to encode.
+ * @param data is the return buffer with the encoded message, should be
+ * @param[out] mic_offset offset of message integrity code
+ * freed with heim_ntlm_free_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_encode_type3(const struct ntlm_type3 *type3, struct ntlm_buf *data, size_t *mic_offset)
+{
+ struct sec_buffer lm, ntlm, target, username, sessionkey, ws;
+ krb5_error_code ret;
+ krb5_storage *out = NULL;
+ uint32_t base;
+ int ucs2 = 0;
+
+ memset(&lm, 0, sizeof(lm));
+ memset(&ntlm, 0, sizeof(ntlm));
+ memset(&target, 0, sizeof(target));
+ memset(&username, 0, sizeof(username));
+ memset(&ws, 0, sizeof(ws));
+ memset(&sessionkey, 0, sizeof(sessionkey));
+
+ base = 52;
+
+ base += 8; /* sessionkey sec buf */
+ base += 4; /* flags */
+ if (type3->flags & NTLM_NEG_VERSION)
+ base += SIZE_OS_VERSION; /* os flags */
+
+ if (mic_offset) {
+ *mic_offset = base;
+ base += 16;
+ }
+
+ if (type3->flags & NTLM_NEG_UNICODE)
+ ucs2 = 1;
+
+ target.offset = base;
+ target.length = len_string(ucs2, type3->targetname);
+ target.allocated = target.length;
+
+ username.offset = target.offset + target.allocated;
+ username.length = len_string(ucs2, type3->username);
+ username.allocated = username.length;
+
+ ws.offset = username.offset + username.allocated;
+ ws.length = len_string(ucs2, type3->ws);
+ ws.allocated = ws.length;
+
+ lm.offset = ws.offset + ws.allocated;
+ lm.length = type3->lm.length;
+ lm.allocated = type3->lm.length;
+
+ ntlm.offset = lm.offset + lm.allocated;
+ ntlm.length = type3->ntlm.length;
+ ntlm.allocated = ntlm.length;
+
+ sessionkey.offset = ntlm.offset + ntlm.allocated;
+ sessionkey.length = type3->sessionkey.length;
+ sessionkey.allocated = type3->sessionkey.length;
+
+ out = krb5_storage_emem();
+ if (out == NULL)
+ return ENOMEM;
+
+ krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
+ CHECK_SIZE(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)),
+ sizeof(ntlmsigature));
+ CHECK(krb5_store_uint32(out, 3), 0);
+
+ CHECK(store_sec_buffer(out, &lm), 0);
+ CHECK(store_sec_buffer(out, &ntlm), 0);
+ CHECK(store_sec_buffer(out, &target), 0);
+ CHECK(store_sec_buffer(out, &username), 0);
+ CHECK(store_sec_buffer(out, &ws), 0);
+ CHECK(store_sec_buffer(out, &sessionkey), 0);
+ CHECK(krb5_store_uint32(out, type3->flags), 0);
+
+ /* os version */
+ if (type3->flags & NTLM_NEG_VERSION) {
+ CHECK(encode_os_version(out), 0);
+ }
+
+ if (mic_offset) {
+ static const uint8_t buf[16] = { 0 };
+ CHECK_SIZE(krb5_storage_write(out, buf, sizeof(buf)), sizeof(buf));
+ }
+
+ CHECK(put_string(out, ucs2, type3->targetname), 0);
+ CHECK(put_string(out, ucs2, type3->username), 0);
+ CHECK(put_string(out, ucs2, type3->ws), 0);
+ CHECK(put_buf(out, &type3->lm), 0);
+ CHECK(put_buf(out, &type3->ntlm), 0);
+ CHECK(put_buf(out, &type3->sessionkey), 0);
+
+ {
+ krb5_data d;
+ ret = krb5_storage_to_data(out, &d);
+ data->data = d.data;
+ data->length = d.length;
+ }
+
+out:
+ krb5_storage_free(out);
+
+ return ret;
+}
+
+
+/*
+ *
+ */
+
+static void
+splitandenc(unsigned char *hash,
+ unsigned char *challenge,
+ unsigned char *answer)
+{
+ EVP_CIPHER_CTX ctx;
+ unsigned char key[8];
+
+ key[0] = hash[0];
+ key[1] = (hash[0] << 7) | (hash[1] >> 1);
+ key[2] = (hash[1] << 6) | (hash[2] >> 2);
+ key[3] = (hash[2] << 5) | (hash[3] >> 3);
+ key[4] = (hash[3] << 4) | (hash[4] >> 4);
+ key[5] = (hash[4] << 3) | (hash[5] >> 5);
+ key[6] = (hash[5] << 2) | (hash[6] >> 6);
+ key[7] = (hash[6] << 1);
+
+ EVP_CIPHER_CTX_init(&ctx);
+
+ EVP_CipherInit_ex(&ctx, EVP_des_cbc(), NULL, key, NULL, 1);
+ EVP_Cipher(&ctx, answer, challenge, 8);
+ EVP_CIPHER_CTX_cleanup(&ctx);
+ memset_s(key, sizeof(key), 0, sizeof(key));
+}
+
+/**
+ * Calculate the NTLM key, the password is assumed to be in UTF8.
+ *
+ * @param password password to calcute the key for.
+ * @param key calcuted key, should be freed with heim_ntlm_free_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_nt_key(const char *password, struct ntlm_buf *key)
+{
+ struct ntlm_buf buf;
+ EVP_MD_CTX *m;
+ int ret;
+
+ key->data = malloc(MD4_DIGEST_LENGTH);
+ if (key->data == NULL)
+ return ENOMEM;
+ key->length = MD4_DIGEST_LENGTH;
+
+ ret = ascii2ucs2le(password, 0, &buf);
+ if (ret) {
+ heim_ntlm_free_buf(key);
+ return ret;
+ }
+
+ m = EVP_MD_CTX_create();
+ if (m == NULL) {
+ heim_ntlm_free_buf(key);
+ heim_ntlm_free_buf(&buf);
+ return ENOMEM;
+ }
+
+ EVP_DigestInit_ex(m, EVP_md4(), NULL);
+ EVP_DigestUpdate(m, buf.data, buf.length);
+ EVP_DigestFinal_ex(m, key->data, NULL);
+ EVP_MD_CTX_destroy(m);
+
+ heim_ntlm_free_buf(&buf);
+ return 0;
+}
+
+/**
+ * Calculate NTLMv1 response hash
+ *
+ * @param key the ntlm v1 key
+ * @param len length of key
+ * @param challenge sent by the server
+ * @param answer calculated answer, should be freed with heim_ntlm_free_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_calculate_ntlm1(void *key, size_t len,
+ unsigned char challenge[8],
+ struct ntlm_buf *answer)
+{
+ unsigned char res[21];
+
+ if (len != MD4_DIGEST_LENGTH)
+ return HNTLM_ERR_INVALID_LENGTH;
+
+ memcpy(res, key, len);
+ memset(&res[MD4_DIGEST_LENGTH], 0, sizeof(res) - MD4_DIGEST_LENGTH);
+
+ answer->data = malloc(24);
+ if (answer->data == NULL)
+ return ENOMEM;
+ answer->length = 24;
+
+ splitandenc(&res[0], challenge, ((unsigned char *)answer->data) + 0);
+ splitandenc(&res[7], challenge, ((unsigned char *)answer->data) + 8);
+ splitandenc(&res[14], challenge, ((unsigned char *)answer->data) + 16);
+
+ return 0;
+}
+
+int
+heim_ntlm_v1_base_session(void *key, size_t len,
+ struct ntlm_buf *session)
+{
+ EVP_MD_CTX *m;
+
+ session->length = MD4_DIGEST_LENGTH;
+ session->data = malloc(session->length);
+ if (session->data == NULL) {
+ session->length = 0;
+ return ENOMEM;
+ }
+
+ m = EVP_MD_CTX_create();
+ if (m == NULL) {
+ heim_ntlm_free_buf(session);
+ return ENOMEM;
+ }
+ EVP_DigestInit_ex(m, EVP_md4(), NULL);
+ EVP_DigestUpdate(m, key, len);
+ EVP_DigestFinal_ex(m, session->data, NULL);
+ EVP_MD_CTX_destroy(m);
+
+ return 0;
+}
+
+int
+heim_ntlm_v2_base_session(void *key, size_t len,
+ struct ntlm_buf *ntlmResponse,
+ struct ntlm_buf *session)
+{
+ unsigned int hmaclen;
+ HMAC_CTX c;
+
+ if (ntlmResponse->length <= 16)
+ return HNTLM_ERR_INVALID_LENGTH;
+
+ session->data = malloc(16);
+ if (session->data == NULL)
+ return ENOMEM;
+ session->length = 16;
+
+ /* Note: key is the NTLMv2 key */
+ HMAC_CTX_init(&c);
+ if (HMAC_Init_ex(&c, key, len, EVP_md5(), NULL) == 0) {
+ HMAC_CTX_cleanup(&c);
+ return ENOMEM;
+ }
+ HMAC_Update(&c, ntlmResponse->data, 16);
+ HMAC_Final(&c, session->data, &hmaclen);
+ HMAC_CTX_cleanup(&c);
+
+ return 0;
+}
+
+
+int
+heim_ntlm_keyex_wrap(struct ntlm_buf *base_session,
+ struct ntlm_buf *session,
+ struct ntlm_buf *encryptedSession)
+{
+ EVP_CIPHER_CTX c;
+ int ret;
+
+ if (base_session->length != MD4_DIGEST_LENGTH)
+ return HNTLM_ERR_INVALID_LENGTH;
+
+ session->length = MD4_DIGEST_LENGTH;
+ session->data = malloc(session->length);
+ if (session->data == NULL) {
+ session->length = 0;
+ return ENOMEM;
+ }
+ encryptedSession->length = MD4_DIGEST_LENGTH;
+ encryptedSession->data = malloc(encryptedSession->length);
+ if (encryptedSession->data == NULL) {
+ heim_ntlm_free_buf(session);
+ encryptedSession->length = 0;
+ return ENOMEM;
+ }
+
+ EVP_CIPHER_CTX_init(&c);
+
+ ret = EVP_CipherInit_ex(&c, EVP_rc4(), NULL, base_session->data, NULL, 1);
+ if (ret != 1) {
+ EVP_CIPHER_CTX_cleanup(&c);
+ heim_ntlm_free_buf(encryptedSession);
+ heim_ntlm_free_buf(session);
+ return HNTLM_ERR_CRYPTO;
+ }
+
+ if (RAND_bytes(session->data, session->length) != 1) {
+ EVP_CIPHER_CTX_cleanup(&c);
+ heim_ntlm_free_buf(encryptedSession);
+ heim_ntlm_free_buf(session);
+ return HNTLM_ERR_RAND;
+ }
+
+ EVP_Cipher(&c, encryptedSession->data, session->data, encryptedSession->length);
+ EVP_CIPHER_CTX_cleanup(&c);
+
+ return 0;
+
+
+
+}
+
+/**
+ * Generates an NTLMv1 session random with assosited session master key.
+ *
+ * @param key the ntlm v1 key
+ * @param len length of key
+ * @param session generated session nonce, should be freed with heim_ntlm_free_buf().
+ * @param master calculated session master key, should be freed with heim_ntlm_free_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_build_ntlm1_master(void *key, size_t len,
+ struct ntlm_buf *session,
+ struct ntlm_buf *master)
+{
+ struct ntlm_buf sess;
+ int ret;
+
+ ret = heim_ntlm_v1_base_session(key, len, &sess);
+ if (ret)
+ return ret;
+
+ ret = heim_ntlm_keyex_wrap(&sess, session, master);
+ heim_ntlm_free_buf(&sess);
+
+ return ret;
+}
+
+/**
+ * Generates an NTLMv2 session random with associated session master key.
+ *
+ * @param key the NTLMv2 key
+ * @param len length of key
+ * @param blob the NTLMv2 "blob"
+ * @param session generated session nonce, should be freed with heim_ntlm_free_buf().
+ * @param master calculated session master key, should be freed with heim_ntlm_free_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+
+int
+heim_ntlm_build_ntlm2_master(void *key, size_t len,
+ struct ntlm_buf *blob,
+ struct ntlm_buf *session,
+ struct ntlm_buf *master)
+{
+ struct ntlm_buf sess;
+ int ret;
+
+ ret = heim_ntlm_v2_base_session(key, len, blob, &sess);
+ if (ret)
+ return ret;
+
+ ret = heim_ntlm_keyex_wrap(&sess, session, master);
+ heim_ntlm_free_buf(&sess);
+
+ return ret;
+}
+
+/**
+ * Given a key and encrypted session, unwrap the session key
+ *
+ * @param baseKey the sessionBaseKey
+ * @param encryptedSession encrypted session, type3.session field.
+ * @param session generated session nonce, should be freed with heim_ntlm_free_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_keyex_unwrap(struct ntlm_buf *baseKey,
+ struct ntlm_buf *encryptedSession,
+ struct ntlm_buf *session)
+{
+ EVP_CIPHER_CTX c;
+
+ memset(session, 0, sizeof(*session));
+
+ if (encryptedSession->length != MD4_DIGEST_LENGTH)
+ return HNTLM_ERR_INVALID_LENGTH;
+ if (baseKey->length != MD4_DIGEST_LENGTH)
+ return HNTLM_ERR_INVALID_LENGTH;
+
+ session->length = MD4_DIGEST_LENGTH;
+ session->data = malloc(session->length);
+ if (session->data == NULL) {
+ session->length = 0;
+ return ENOMEM;
+ }
+ EVP_CIPHER_CTX_init(&c);
+
+ if (EVP_CipherInit_ex(&c, EVP_rc4(), NULL, baseKey->data, NULL, 0) != 1) {
+ EVP_CIPHER_CTX_cleanup(&c);
+ heim_ntlm_free_buf(session);
+ return HNTLM_ERR_CRYPTO;
+ }
+
+ EVP_Cipher(&c, session->data, encryptedSession->data, session->length);
+ EVP_CIPHER_CTX_cleanup(&c);
+
+ return 0;
+}
+
+
+/**
+ * Generates an NTLMv2 session key.
+ *
+ * @param key the ntlm key
+ * @param len length of key
+ * @param username name of the user, as sent in the message, assumed to be in UTF8.
+ * @param target the name of the target, assumed to be in UTF8.
+ * @param upper_case_target upper case the target, should not be used only for legacy systems
+ * @param ntlmv2 the ntlmv2 session key
+ *
+ * @return 0 on success, or an error code on failure.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_ntlmv2_key(const void *key, size_t len,
+ const char *username,
+ const char *target,
+ int upper_case_target,
+ unsigned char ntlmv2[16])
+{
+ int ret;
+ unsigned int hmaclen;
+ struct ntlm_buf buf;
+ HMAC_CTX c;
+
+ HMAC_CTX_init(&c);
+ if (HMAC_Init_ex(&c, key, len, EVP_md5(), NULL) == 0) {
+ ret = ENOMEM;
+ goto out;
+ }
+ /* uppercase username and turn it into ucs2-le */
+ ret = ascii2ucs2le(username, 1, &buf);
+ if (ret)
+ goto out;
+ HMAC_Update(&c, buf.data, buf.length);
+ free(buf.data);
+ /* turn target into ucs2-le */
+ ret = ascii2ucs2le(target, upper_case_target, &buf);
+ if (ret)
+ goto out;
+ HMAC_Update(&c, buf.data, buf.length);
+ free(buf.data);
+ HMAC_Final(&c, ntlmv2, &hmaclen);
+ out:
+ HMAC_CTX_cleanup(&c);
+ memset(&c, 0, sizeof(c));
+
+ return ret;
+}
+
+/*
+ *
+ */
+
+#define NTTIME_EPOCH 0x019DB1DED53E8000LL
+
+uint64_t
+heim_ntlm_unix2ts_time(time_t unix_time)
+{
+ long long wt;
+ wt = unix_time * (uint64_t)10000000 + (uint64_t)NTTIME_EPOCH;
+ return wt;
+}
+
+time_t
+heim_ntlm_ts2unixtime(uint64_t t)
+{
+ t = ((t - (uint64_t)NTTIME_EPOCH) / (uint64_t)10000000);
+ if (t > (((uint64_t)(time_t)(~(uint64_t)0)) >> 1))
+ return 0;
+ return (time_t)t;
+}
+
+/**
+ * Calculate LMv2 response
+ *
+ * @param key the ntlm key
+ * @param len length of key
+ * @param username name of the user, as sent in the message, assumed to be in UTF8.
+ * @param target the name of the target, assumed to be in UTF8.
+ * @param serverchallenge challenge as sent by the server in the type2 message.
+ * @param ntlmv2 calculated session key
+ * @param answer ntlm response answer, should be freed with heim_ntlm_free_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_calculate_lm2(const void *key, size_t len,
+ const char *username,
+ const char *target,
+ const unsigned char serverchallenge[8],
+ unsigned char ntlmv2[16],
+ struct ntlm_buf *answer)
+{
+ unsigned char clientchallenge[8];
+ krb5_error_code ret;
+
+ if (RAND_bytes(clientchallenge, sizeof(clientchallenge)) != 1)
+ return HNTLM_ERR_RAND;
+
+ /* calculate ntlmv2 key */
+
+ heim_ntlm_ntlmv2_key(key, len, username, target, 0, ntlmv2);
+
+ answer->data = malloc(24);
+ if (answer->data == NULL)
+ return ENOMEM;
+ answer->length = 24;
+
+ ret = heim_ntlm_derive_ntlm2_sess(ntlmv2, clientchallenge, 8,
+ serverchallenge, answer->data);
+ if (ret == 0)
+ memcpy(((unsigned char *)answer->data) + 16, clientchallenge, 8);
+
+ return ret;
+}
+
+
+/**
+ * Calculate NTLMv2 response
+ *
+ * @param key the ntlm key
+ * @param len length of key
+ * @param username name of the user, as sent in the message, assumed to be in UTF8.
+ * @param target the name of the target, assumed to be in UTF8.
+ * @param serverchallenge challenge as sent by the server in the type2 message.
+ * @param infotarget infotarget as sent by the server in the type2 message.
+ * @param ntlmv2 calculated session key
+ * @param answer ntlm response answer, should be freed with heim_ntlm_free_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_calculate_ntlm2(const void *key, size_t len,
+ const char *username,
+ const char *target,
+ const unsigned char serverchallenge[8],
+ const struct ntlm_buf *infotarget,
+ unsigned char ntlmv2[16],
+ struct ntlm_buf *answer)
+{
+ krb5_error_code ret;
+ krb5_data data;
+ unsigned char ntlmv2answer[16];
+ krb5_storage *sp;
+ unsigned char clientchallenge[8];
+ uint64_t t;
+
+ t = heim_ntlm_unix2ts_time(time(NULL));
+
+ if (RAND_bytes(clientchallenge, sizeof(clientchallenge)) != 1)
+ return HNTLM_ERR_RAND;
+
+ /* calculate ntlmv2 key */
+
+ heim_ntlm_ntlmv2_key(key, len, username, target, 0, ntlmv2);
+
+ /* calculate and build ntlmv2 answer */
+
+ sp = krb5_storage_emem();
+ if (sp == NULL)
+ return ENOMEM;
+ krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
+
+ CHECK(krb5_store_uint32(sp, 0x00000101), 0);
+ CHECK(krb5_store_uint32(sp, 0), 0);
+ /* timestamp le 64 bit ts */
+ CHECK(krb5_store_uint32(sp, t & 0xffffffff), 0);
+ CHECK(krb5_store_uint32(sp, t >> 32), 0);
+
+ CHECK_SIZE(krb5_storage_write(sp, clientchallenge, 8), 8);
+
+ CHECK(krb5_store_uint32(sp, 0), 0); /* Z(4) */
+ CHECK_SIZE(krb5_storage_write(sp, infotarget->data, infotarget->length),
+ infotarget->length);
+
+ /*
+ * These last 4 bytes(Z(4)) are not documented by MicroSoft and
+ * SnowLeopard doesn't send them, Lion expected them to be there,
+ * so we have to continue to send them. That is ok, since everyone
+ * else (except Snow) seems to do that too.
+ */
+ CHECK(krb5_store_uint32(sp, 0), 0); /* Z(4) */
+
+ CHECK(krb5_storage_to_data(sp, &data), 0);
+ krb5_storage_free(sp);
+ sp = NULL;
+
+ ret = heim_ntlm_derive_ntlm2_sess(ntlmv2, data.data, data.length,
+ serverchallenge, ntlmv2answer);
+ if (ret)
+ return ret;
+
+ sp = krb5_storage_emem();
+ if (sp == NULL) {
+ krb5_data_free(&data);
+ return ENOMEM;
+ }
+
+ CHECK_SIZE(krb5_storage_write(sp, ntlmv2answer, 16), 16);
+ CHECK_SIZE(krb5_storage_write(sp, data.data, data.length), data.length);
+ krb5_data_free(&data);
+
+ CHECK(krb5_storage_to_data(sp, &data), 0);
+ krb5_storage_free(sp);
+ sp = NULL;
+
+ answer->data = data.data;
+ answer->length = data.length;
+
+ return 0;
+out:
+ if (sp)
+ krb5_storage_free(sp);
+ return ret;
+}
+
+static const int authtimediff = 3600 * 2; /* 2 hours */
+
+static int
+verify_ntlm2(const void *key, size_t len,
+ const char *username,
+ const char *target,
+ int upper_case_target,
+ time_t now,
+ const unsigned char serverchallenge[8],
+ const struct ntlm_buf *answer,
+ struct ntlm_buf *infotarget,
+ unsigned char ntlmv2[16])
+{
+ krb5_error_code ret;
+ unsigned char clientanswer[16];
+ unsigned char clientnonce[8];
+ unsigned char serveranswer[16];
+ krb5_storage *sp;
+ uint64_t t;
+ time_t authtime;
+ uint32_t temp;
+
+ infotarget->length = 0;
+ infotarget->data = NULL;
+
+ if (answer->length < 16)
+ return HNTLM_ERR_INVALID_LENGTH;
+
+ if (now == 0)
+ now = time(NULL);
+
+ /* calculate ntlmv2 key */
+
+ heim_ntlm_ntlmv2_key(key, len, username, target, upper_case_target, ntlmv2);
+
+ /* calculate and build ntlmv2 answer */
+
+ sp = krb5_storage_from_readonly_mem(answer->data, answer->length);
+ if (sp == NULL)
+ return ENOMEM;
+ krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
+
+ CHECK_SIZE(krb5_storage_read(sp, clientanswer, 16), 16);
+
+ CHECK(krb5_ret_uint32(sp, &temp), 0);
+ CHECK(temp, 0x00000101);
+ CHECK(krb5_ret_uint32(sp, &temp), 0);
+ CHECK(temp, 0);
+ /* timestamp le 64 bit ts */
+ CHECK(krb5_ret_uint32(sp, &temp), 0);
+ t = temp;
+ CHECK(krb5_ret_uint32(sp, &temp), 0);
+ t |= ((uint64_t)temp)<< 32;
+
+ authtime = heim_ntlm_ts2unixtime(t);
+
+ if (labs((int)(authtime - now)) > authtimediff) {
+ ret = HNTLM_ERR_TIME_SKEW;
+ goto out;
+ }
+
+ /* client challenge */
+ CHECK_SIZE(krb5_storage_read(sp, clientnonce, 8), 8);
+
+ CHECK(krb5_ret_uint32(sp, &temp), 0); /* Z(4) */
+
+ /* let pick up targetinfo */
+ infotarget->length = answer->length - (size_t)krb5_storage_seek(sp, 0, SEEK_CUR);
+ if (infotarget->length < 4) {
+ ret = HNTLM_ERR_INVALID_LENGTH;
+ goto out;
+ }
+ infotarget->data = malloc(infotarget->length);
+ if (infotarget->data == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ CHECK_SIZE(krb5_storage_read(sp, infotarget->data, infotarget->length),
+ infotarget->length);
+
+ krb5_storage_free(sp);
+ sp = NULL;
+
+ if (answer->length < 16) {
+ ret = HNTLM_ERR_INVALID_LENGTH;
+ goto out;
+ }
+
+ ret = heim_ntlm_derive_ntlm2_sess(ntlmv2,
+ ((unsigned char *)answer->data) + 16,
+ answer->length - 16,
+ serverchallenge,
+ serveranswer);
+ if (ret)
+ goto out;
+
+ if (memcmp(serveranswer, clientanswer, 16) != 0) {
+ heim_ntlm_free_buf(infotarget);
+ return HNTLM_ERR_AUTH;
+ }
+
+ return 0;
+out:
+ heim_ntlm_free_buf(infotarget);
+ if (sp)
+ krb5_storage_free(sp);
+ return ret;
+}
+
+/**
+ * Verify NTLMv2 response.
+ *
+ * @param key the ntlm key
+ * @param len length of key
+ * @param username name of the user, as sent in the message, assumed to be in UTF8.
+ * @param target the name of the target, assumed to be in UTF8.
+ * @param now the time now (0 if the library should pick it up itself)
+ * @param serverchallenge challenge as sent by the server in the type2 message.
+ * @param answer ntlm response answer, should be freed with heim_ntlm_free_buf().
+ * @param infotarget infotarget as sent by the server in the type2 message.
+ * @param ntlmv2 calculated session key
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_verify_ntlm2(const void *key, size_t len,
+ const char *username,
+ const char *target,
+ time_t now,
+ const unsigned char serverchallenge[8],
+ const struct ntlm_buf *answer,
+ struct ntlm_buf *infotarget,
+ unsigned char ntlmv2[16])
+{
+ int ret;
+
+ /**
+ * First check with the domain as the client passed it to the function.
+ */
+
+ ret = verify_ntlm2(key, len, username, target, 0, now,
+ serverchallenge, answer, infotarget, ntlmv2);
+
+ /**
+ * Second check with domain uppercased.
+ */
+
+ if (ret)
+ ret = verify_ntlm2(key, len, username, target, 1, now,
+ serverchallenge, answer, infotarget, ntlmv2);
+
+ /**
+ * Third check with empty domain.
+ */
+ if (ret)
+ ret = verify_ntlm2(key, len, username, "", 0, now,
+ serverchallenge, answer, infotarget, ntlmv2);
+ return ret;
+}
+
+/*
+ * Calculate the NTLM2 Session Response
+ *
+ * @param clnt_nonce client nonce
+ * @param svr_chal server challage
+ * @param ntlm2_hash ntlm hash
+ * @param lm The LM response, should be freed with heim_ntlm_free_buf().
+ * @param ntlm The NTLM response, should be freed with heim_ntlm_free_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_calculate_ntlm2_sess(const unsigned char clnt_nonce[8],
+ const unsigned char svr_chal[8],
+ const unsigned char ntlm_hash[16],
+ struct ntlm_buf *lm,
+ struct ntlm_buf *ntlm)
+{
+ unsigned char ntlm2_sess_hash[8];
+ unsigned char res[21], *resp;
+ int code;
+
+ code = heim_ntlm_calculate_ntlm2_sess_hash(clnt_nonce, svr_chal,
+ ntlm2_sess_hash);
+ if (code) {
+ return code;
+ }
+
+ lm->data = malloc(24);
+ if (lm->data == NULL) {
+ return ENOMEM;
+ }
+ lm->length = 24;
+
+ ntlm->data = malloc(24);
+ if (ntlm->data == NULL) {
+ free(lm->data);
+ lm->data = NULL;
+ return ENOMEM;
+ }
+ ntlm->length = 24;
+
+ /* first setup the lm resp */
+ memset(lm->data, 0, 24);
+ memcpy(lm->data, clnt_nonce, 8);
+
+ memset(res, 0, sizeof(res));
+ memcpy(res, ntlm_hash, 16);
+
+ resp = ntlm->data;
+ splitandenc(&res[0], ntlm2_sess_hash, resp + 0);
+ splitandenc(&res[7], ntlm2_sess_hash, resp + 8);
+ splitandenc(&res[14], ntlm2_sess_hash, resp + 16);
+
+ return 0;
+}
+
+
+/*
+ * Calculate the NTLM2 Session "Verifier"
+ *
+ * @param clnt_nonce client nonce
+ * @param svr_chal server challage
+ * @param hash The NTLM session verifier
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_calculate_ntlm2_sess_hash(const unsigned char clnt_nonce[8],
+ const unsigned char svr_chal[8],
+ unsigned char verifier[8])
+{
+ unsigned char ntlm2_sess_hash[MD5_DIGEST_LENGTH];
+ EVP_MD_CTX *m;
+
+ m = EVP_MD_CTX_create();
+ if (m == NULL)
+ return ENOMEM;
+
+ EVP_DigestInit_ex(m, EVP_md5(), NULL);
+ EVP_DigestUpdate(m, svr_chal, 8); /* session nonce part 1 */
+ EVP_DigestUpdate(m, clnt_nonce, 8); /* session nonce part 2 */
+ EVP_DigestFinal_ex(m, ntlm2_sess_hash, NULL); /* will only use first 8 bytes */
+ EVP_MD_CTX_destroy(m);
+
+ memcpy(verifier, ntlm2_sess_hash, 8);
+
+ return 0;
+}
+
+
+/*
+ * Derive a NTLM2 session key
+ *
+ * @param sessionkey session key from domain controller
+ * @param clnt_nonce client nonce
+ * @param svr_chal server challenge
+ * @param derivedkey salted session key
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_derive_ntlm2_sess(const unsigned char sessionkey[16],
+ const unsigned char *clnt_nonce, size_t clnt_nonce_length,
+ const unsigned char svr_chal[8],
+ unsigned char derivedkey[16])
+{
+ unsigned int hmaclen;
+ HMAC_CTX c;
+
+ /* HMAC(Ksession, serverchallenge || clientchallenge) */
+ HMAC_CTX_init(&c);
+ if (HMAC_Init_ex(&c, sessionkey, 16, EVP_md5(), NULL) == 0) {
+ HMAC_CTX_cleanup(&c);
+ return ENOMEM;
+ }
+ HMAC_Update(&c, svr_chal, 8);
+ HMAC_Update(&c, clnt_nonce, clnt_nonce_length);
+ HMAC_Final(&c, derivedkey, &hmaclen);
+ HMAC_CTX_cleanup(&c);
+ memset(&c, 0, sizeof(c));
+ return 0;
+}
diff --git a/third_party/heimdal/lib/ntlm/ntlm_err.et b/third_party/heimdal/lib/ntlm/ntlm_err.et
new file mode 100644
index 0000000..fd39aa3
--- /dev/null
+++ b/third_party/heimdal/lib/ntlm/ntlm_err.et
@@ -0,0 +1,60 @@
+#
+# Error messages for the ntlm library
+#
+# This might look like a com_err file, but is not
+#
+
+error_table ntlm
+
+prefix HNTLM_ERR
+error_code DECODE, "Failed to decode packet"
+error_code INVALID_LENGTH, "Input length invalid"
+error_code CRYPTO, "Failed crypto primitive"
+error_code RAND, "Random generator failed"
+error_code AUTH, "NTLM authentication failed"
+error_code TIME_SKEW, "Client time skewed to server"
+error_code OEM, "Client set OEM string"
+error_code MISSING_NAME_SEPARATOR, "missing @ or \\\\ in name"
+error_code MISSING_BUFFER, "missing expected buffer"
+error_code INVALID_APOP, "Invalid APOP response"
+error_code INVALID_CRAM_MD5, "Invalid CRAM-MD5 response"
+error_code INVALID_DIGEST_MD5, "Invalid DIGEST-MD5 response"
+error_code INVALID_DIGEST_MD5_RSPAUTH, "Invalid DIGEST-MD5 rspauth"
+error_code INVALID_CHANNEL_BINDINGS, "Invalid channel bindings"
+error_code INVALID_MIC, "Invalid MIC"
+error_code INVALID_SESSIONKEY, "Invalid session key"
+
+
+#
+# NTLM/GSS error codes
+#
+index 64
+error_code NOT_CONFIGURED, "NTLM not configured"
+
+error_code INVALID_CHALLANGE, "Invalid client challenge"
+error_code INVALID_LMv1_RESPONSE, "Invalid client LMv1 response"
+error_code INVALID_NT_RESPONSE, "Invalid client NT response"
+error_code INVALID_LMv2_RESPONSE, "Invalid client LMv2 response"
+error_code INVALID_NTv1_RESPONSE, "Invalid client NTv1 response"
+error_code INVALID_NTv2_RESPONSE, "Invalid client NTv2 response"
+error_code INVALID_NTv1_ANSWER, "Invalid client NTv1 answer"
+error_code INVALID_NTv2_ANSWER, "Invalid client NTv2 answer"
+error_code INVALID_SESSION_KEY, "Invalid session key"
+
+error_code INVALID_NO_GUEST, "Invalid guest login request"
+
+error_code NO_NETR_CONFIGURED, "No NETR configured"
+
+
+#
+# Scram errors
+#
+prefix HSCRAM_ERR
+index 128
+
+error_code INVALID_MESSAGE, "Invalid SCRAM message"
+error_code INVALID_PROOF, "Invalid SCRAM proof"
+error_code INVALID_ROLE, "Invalid SCRAM role"
+
+
+end
diff --git a/third_party/heimdal/lib/ntlm/test_commonauth.c b/third_party/heimdal/lib/ntlm/test_commonauth.c
new file mode 100644
index 0000000..89b8c7e
--- /dev/null
+++ b/third_party/heimdal/lib/ntlm/test_commonauth.c
@@ -0,0 +1,425 @@
+/*
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <roken.h>
+#include <err.h>
+#include "heim-auth.h"
+
+static int
+test_sasl_digest_md5(void)
+{
+ heim_digest_t ctx;
+ const char *user, *challenge, *resp;
+ char *r;
+
+ if ((ctx = heim_digest_create(1, HEIM_DIGEST_TYPE_AUTO)) == NULL)
+ abort();
+
+ if (heim_digest_parse_challenge(ctx, "realm=\"elwood.innosoft.com\",nonce=\"OA6MG9tEQGm2hh\",qop=\"auth\",algorithm=md5-sess,charset=utf-8"))
+ abort();
+
+ /* check that server detects changing QOP */
+ if (!heim_digest_parse_response(ctx, "charset=utf-8,username=\"chris\",realm=\"elwood.innosoft.com\",nonce=\"OA6MG9tEQGm2hh\",nc=00000001,cnonce=\"OA6MHXh6VqTrRk\",digest-uri=\"imap/elwood.innosoft.com\",response=d388dad90d4bbd760a152321f2143af7,qop=auth-int"))
+ errx(1, "don't detect changing qop");
+
+ /* should pass */
+ if (heim_digest_parse_response(ctx, "charset=utf-8,username=\"chris\",realm=\"elwood.innosoft.com\",nonce=\"OA6MG9tEQGm2hh\",nc=00000001,cnonce=\"OA6MHXh6VqTrRk\",digest-uri=\"imap/elwood.innosoft.com\",response=d388dad90d4bbd760a152321f2143af7,qop=auth"))
+ abort();
+
+ if ((user = heim_digest_get_key(ctx, "username")) == NULL)
+ abort();
+ if (strcmp(user, "chris") != 0)
+ abort();
+
+ /*
+ * check password
+ */
+
+ heim_digest_set_key(ctx, "password", "secret");
+
+ if (heim_digest_verify(ctx, &r))
+ abort();
+
+ if (strcmp(r, "rspauth=ea40f60335c427b5527b84dbabcdfffd") != 0)
+ abort();
+
+ free(r);
+
+ /*
+ * Also check userhash
+ */
+
+ r = heim_digest_userhash("chris", "elwood.innosoft.com", "secret");
+ if (strcmp(r, "eb5a750053e4d2c34aa84bbc9b0b6ee7") != 0)
+ abort();
+
+ heim_digest_set_key(ctx, "userhash", r);
+ free(r);
+
+ if (heim_digest_verify(ctx, &r))
+ abort();
+
+ if (strcmp(r, "rspauth=ea40f60335c427b5527b84dbabcdfffd") != 0)
+ abort();
+
+ free(r);
+
+ /* check that it failes */
+
+ heim_digest_set_key(ctx, "username", "notright");
+ heim_digest_set_key(ctx, "password", "secret");
+
+ if (heim_digest_verify(ctx, &r) == 0)
+ abort();
+
+ if ((user = heim_digest_get_key(ctx, "username")) == NULL)
+ abort();
+ if (strcmp(user, "notright") != 0)
+ abort();
+
+
+ /* Done */
+
+ heim_digest_release(ctx);
+
+
+ /*
+ * Check heim_digest_generate_challenge()
+ */
+
+ if ((ctx = heim_digest_create(1, HEIM_DIGEST_TYPE_RFC2831)) == NULL)
+ abort();
+
+ heim_digest_set_key(ctx, "serverRealm", "elwood.innosoft.com");
+ heim_digest_set_key(ctx, "serverNonce", "OA6MG9tEQGm2hh");
+ heim_digest_set_key(ctx, "serverQOP", "auth,auth-int");
+
+ challenge = heim_digest_generate_challenge(ctx);
+ if (challenge == NULL)
+ abort();
+
+ if (heim_digest_parse_challenge(ctx, challenge))
+ abort();
+
+ /* check that server detects changing QOP */
+ if (!heim_digest_parse_response(ctx, "charset=utf-8,username=\"chris\",realm=\"elwood.innosoft.com\",nonce=\"OA6MG9tEQGm2hh\",nc=00000001,cnonce=\"OA6MHXh6VqTrRk\",digest-uri=\"imap/elwood.innosoft.com\",response=d388dad90d4bbd760a152321f2143af7,qop=auth-conf"))
+ abort();
+
+ if (heim_digest_parse_response(ctx, "charset=utf-8,username=\"chris\",realm=\"elwood.innosoft.com\",nonce=\"OA6MG9tEQGm2hh\",nc=00000001,cnonce=\"OA6MHXh6VqTrRk\",digest-uri=\"imap/elwood.innosoft.com\",response=d388dad90d4bbd760a152321f2143af7,qop=auth"))
+ abort();
+
+ heim_digest_set_key(ctx, "password", "secret");
+
+ if (heim_digest_verify(ctx, &r))
+ abort();
+
+ if (strcmp(r, "rspauth=ea40f60335c427b5527b84dbabcdfffd") != 0)
+ abort();
+
+ free(r);
+
+ heim_digest_release(ctx);
+
+ /*
+ * Validate heim_digest_service_response()
+ */
+
+ if ((ctx = heim_digest_create(1, HEIM_DIGEST_TYPE_RFC2831)) == NULL)
+ abort();
+
+ heim_digest_set_key(ctx, "clientNonce", "OA6MHXh6VqTrRk");
+ heim_digest_set_key(ctx, "clientQOP", "auth");
+ heim_digest_set_key(ctx, "clientNC", "00000001");
+ heim_digest_set_key(ctx, "serverNonce", "OA6MG9tEQGm2hh");
+ heim_digest_set_key(ctx, "clientURI", "imap/elwood.innosoft.com");
+ heim_digest_set_key(ctx, "serverRealm", "elwood.innosoft.com");
+ heim_digest_set_key(ctx, "serverNonce", "OA6MG9tEQGm2hh");
+ heim_digest_set_key(ctx, "H(A1)", "a2549853149b0536f01f0b850c643c57");
+
+ resp = heim_digest_server_response(ctx);
+
+ if (resp == NULL || strcmp(resp, "rspauth=ea40f60335c427b5527b84dbabcdfffd") != 0)
+ abort();
+
+ heim_digest_release(ctx);
+
+ if ((ctx = heim_digest_create(1, HEIM_DIGEST_TYPE_RFC2831)) == NULL)
+ abort();
+
+ heim_digest_set_key(ctx, "clientNonce", "OA6MHXh6VqTrRk");
+ heim_digest_set_key(ctx, "clientQOP", "auth");
+ heim_digest_set_key(ctx, "clientNC", "00000001");
+ heim_digest_set_key(ctx, "serverNonce", "OA6MG9tEQGm2hh");
+ heim_digest_set_key(ctx, "clientURI", "imap/elwood.innosoft.com");
+ heim_digest_set_key(ctx, "serverRealm", "elwood.innosoft.com");
+ heim_digest_set_key(ctx, "serverNonce", "OA6MG9tEQGm2hh");
+ heim_digest_set_key(ctx, "password", "secret");
+ heim_digest_set_key(ctx, "username", "chris");
+
+ resp = heim_digest_server_response(ctx);
+
+ if (resp == NULL || strcmp(resp, "rspauth=ea40f60335c427b5527b84dbabcdfffd") != 0)
+ abort();
+
+ heim_digest_release(ctx);
+
+ return 0;
+}
+
+static int
+test_http_digest_md5(void)
+{
+ heim_digest_t ctx, ctx2;
+ const char *user, *chal, *resp;
+ char *serverresp, *serverresp2;
+
+ if ((ctx = heim_digest_create(1, HEIM_DIGEST_TYPE_AUTO)) == NULL)
+ abort();
+
+ if (heim_digest_parse_challenge(ctx, "realm=\"testrealm@host.com\","
+ "nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\","
+ "opaque=\"5ccc069c403ebaf9f0171e9517f40e41\""))
+ abort();
+
+ if (heim_digest_parse_response(ctx, "username=\"Mufasa\","
+ "realm=\"testrealm@host.com\","
+ "nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\","
+ "uri=\"/dir/index.html\","
+ "response=\"1949323746fe6a43ef61f9606e7febea\","
+ "opaque=\"5ccc069c403ebaf9f0171e9517f40e41\""))
+ abort();
+
+ if ((user = heim_digest_get_key(ctx, "username")) == NULL)
+ abort();
+ if (strcmp(user, "Mufasa") != 0)
+ abort();
+
+ if ((user = heim_digest_get_key(ctx, "clientUsername")) == NULL)
+ abort();
+ if (strcmp(user, "Mufasa") != 0)
+ abort();
+
+ heim_digest_set_key(ctx, "password", "CircleOfLife");
+
+ if (heim_digest_verify(ctx, NULL))
+ abort();
+
+ /* Verify failure */
+
+ heim_digest_set_key(ctx, "username", "Oskar");
+
+ if (heim_digest_verify(ctx, NULL) == 0)
+ abort();
+
+ heim_digest_release(ctx);
+
+ /*
+ * Check myself
+ */
+
+ /* server */
+ if ((ctx = heim_digest_create(1, HEIM_DIGEST_TYPE_RFC2831)) == NULL)
+ abort();
+
+ heim_digest_set_key(ctx, "serverRealm", "myrealmhahaha");
+ heim_digest_set_key(ctx, "serverQOP", "auth,auth-int");
+
+ chal = heim_digest_generate_challenge(ctx);
+ if (chal == NULL)
+ abort();
+
+ /* client */
+ if ((ctx2 = heim_digest_create(1, HEIM_DIGEST_TYPE_RFC2831)) == NULL)
+ abort();
+
+ if (heim_digest_parse_challenge(ctx2, chal))
+ abort();
+
+ heim_digest_set_key(ctx2, "username", "lha");
+ heim_digest_set_key(ctx2, "password", "passw0rd");
+ heim_digest_set_key(ctx2, "uri", "/uri");
+
+ resp = heim_digest_create_response(ctx2, &serverresp);
+ if (resp == NULL)
+ abort();
+
+ /* server */
+ if (heim_digest_parse_response(ctx, resp))
+ abort();
+
+ heim_digest_set_key(ctx, "password", "passw0rd");
+ heim_digest_verify(ctx, &serverresp2);
+
+
+ /* client */
+ if (strcmp(serverresp, serverresp2) != 0)
+ abort();
+
+ heim_digest_release(ctx);
+ heim_digest_release(ctx2);
+
+ /*
+ * check prefix
+ */
+
+ if ((ctx = heim_digest_create(1, HEIM_DIGEST_TYPE_AUTO)) == NULL)
+ abort();
+
+ if (heim_digest_parse_challenge(ctx, "Digest realm=\"testrealm@host.com\","
+ "nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\","
+ "opaque=\"5ccc069c403ebaf9f0171e9517f40e41\""))
+ abort();
+
+ heim_digest_release(ctx);
+
+ /*
+ * check prefix
+ */
+
+ if ((ctx = heim_digest_create(1, HEIM_DIGEST_TYPE_AUTO)) == NULL)
+ abort();
+
+ if (heim_digest_parse_challenge(ctx, "Digest realm=\"testrealm@host.com\","
+ "nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\","
+ "opaque=\"5ccc069c403ebaf9f0171e9517f40e41\""))
+ abort();
+
+ heim_digest_release(ctx);
+
+ return 0;
+}
+
+static int
+test_cram_md5(void)
+{
+ const char *chal = "<1896.697170952@postoffice.reston.mci.net>";
+ const char *secret = "tanstaaftanstaaf";
+ const char *resp = "b913a602c7eda7a495b4e6e7334d3890";
+ heim_CRAM_MD5_STATE state;
+ heim_cram_md5 ctx;
+ char *t;
+
+ const uint8_t *prestate = (uint8_t *)
+ "\x87\x1E\x24\x10\xB4\x0C\x72\x5D\xA3\x95\x2D\x5B\x8B\xFC\xDD\xE1"
+ "\x29\x90\xCB\xA7\x66\xF6\xB3\x40\xE8\xAC\x48\x2C\xE4\xE3\xA4\x40";
+
+ /*
+ * Test prebuild blobs
+ */
+
+ if (sizeof(state) != 32)
+ abort();
+
+ heim_cram_md5_export("foo", &state);
+
+ if (memcmp(prestate, &state, 32) != 0)
+ abort();
+
+ /*
+ * Check example
+ */
+
+
+ if (heim_cram_md5_verify(chal, secret, resp) != 0)
+ abort();
+
+
+ /*
+ * Do it ourself
+ */
+
+ t = heim_cram_md5_create(chal, secret);
+ if (t == NULL)
+ abort();
+
+ if (strcmp(resp, t) != 0)
+ abort();
+
+ heim_cram_md5_export(secret, &state);
+ /* here you can store the memcpy-ed version of state somewhere else */
+
+ ctx = heim_cram_md5_import(&state, sizeof(state));
+
+ memset(&state, 0, sizeof(state));
+
+ if (heim_cram_md5_verify_ctx(ctx, chal, resp) != 0)
+ abort();
+
+ heim_cram_md5_free(ctx);
+
+ free(t);
+
+ return 0;
+}
+
+static int
+test_apop(void)
+{
+ const char *chal = "<1896.697170952@dbc.mtview.ca.us>";
+ const char *secret = "tanstaaf";
+ const char *resp = "c4c9334bac560ecc979e58001b3e22fb";
+ char *t;
+
+ t = heim_apop_create(chal, secret);
+ if (t == NULL)
+ abort();
+
+ if (strcmp(resp, t) != 0)
+ abort();
+
+ if (heim_apop_verify(chal, secret, resp) != 0)
+ abort();
+
+ free(t);
+
+ return 0;
+}
+
+
+int
+main(int argc, char **argv)
+{
+ int ret = 0;
+
+ ret |= test_sasl_digest_md5();
+ ret |= test_http_digest_md5();
+ ret |= test_cram_md5();
+ ret |= test_apop();
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/ntlm/test_ntlm.c b/third_party/heimdal/lib/ntlm/test_ntlm.c
new file mode 100644
index 0000000..e7d7237
--- /dev/null
+++ b/third_party/heimdal/lib/ntlm/test_ntlm.c
@@ -0,0 +1,617 @@
+/*
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include <stdio.h>
+#include <err.h>
+#include <roken.h>
+#include <getarg.h>
+
+#include <krb5-types.h> /* or <inttypes.h> */
+#include <heimntlm.h>
+
+static int dumpdata_flag;
+
+static int
+test_parse(void)
+{
+ const char *user = "foo",
+ *domain = "mydomain",
+ *hostname = "myhostname",
+ *password = "digestpassword",
+ *target = "DOMAIN";
+ struct ntlm_type1 type1;
+ struct ntlm_type2 type2;
+ struct ntlm_type3 type3;
+ struct ntlm_buf data;
+ int ret, flags;
+
+ memset(&type1, 0, sizeof(type1));
+
+ type1.flags = NTLM_NEG_UNICODE|NTLM_NEG_TARGET|NTLM_NEG_NTLM|NTLM_NEG_VERSION;
+ type1.domain = rk_UNCONST(domain);
+ type1.hostname = rk_UNCONST(hostname);
+ type1.os[0] = 0;
+ type1.os[1] = 0;
+
+ ret = heim_ntlm_encode_type1(&type1, &data);
+ if (ret)
+ errx(1, "heim_ntlm_encode_type1");
+
+ memset(&type1, 0, sizeof(type1));
+
+ if (dumpdata_flag)
+ rk_dumpdata("ntlm-type1", data.data, data.length);
+
+ ret = heim_ntlm_decode_type1(&data, &type1);
+ free(data.data);
+ if (ret)
+ errx(1, "heim_ntlm_encode_type1");
+
+ if (strcmp(type1.domain, domain) != 0)
+ errx(1, "parser got domain wrong: %s", type1.domain);
+
+ if (strcmp(type1.hostname, hostname) != 0)
+ errx(1, "parser got hostname wrong: %s", type1.hostname);
+
+ heim_ntlm_free_type1(&type1);
+
+ /*
+ *
+ */
+
+ memset(&type2, 0, sizeof(type2));
+
+ flags = NTLM_NEG_UNICODE | NTLM_NEG_NTLM | NTLM_TARGET_DOMAIN;
+ type2.flags = flags;
+
+ memset(type2.challenge, 0x7f, sizeof(type2.challenge));
+ type2.targetname = rk_UNCONST(target);
+ type2.targetinfo.data = NULL;
+ type2.targetinfo.length = 0;
+
+ ret = heim_ntlm_encode_type2(&type2, &data);
+ if (ret)
+ errx(1, "heim_ntlm_encode_type2");
+
+ memset(&type2, 0, sizeof(type2));
+
+ if (dumpdata_flag)
+ rk_dumpdata("ntlm-type2", data.data, data.length);
+
+ ret = heim_ntlm_decode_type2(&data, &type2);
+ free(data.data);
+ if (ret)
+ errx(1, "heim_ntlm_decode_type2");
+
+ heim_ntlm_free_type2(&type2);
+
+ /*
+ *
+ */
+
+ memset(&type3, 0, sizeof(type3));
+
+ type3.flags = flags;
+ type3.username = rk_UNCONST(user);
+ type3.targetname = rk_UNCONST(target);
+ type3.ws = rk_UNCONST("workstation");
+
+ {
+ struct ntlm_buf key;
+ heim_ntlm_nt_key(password, &key);
+
+ heim_ntlm_calculate_ntlm1(key.data, key.length,
+ type2.challenge,
+ &type3.ntlm);
+ free(key.data);
+ }
+
+ ret = heim_ntlm_encode_type3(&type3, &data, NULL);
+ if (ret)
+ errx(1, "heim_ntlm_encode_type3");
+
+ free(type3.ntlm.data);
+
+ memset(&type3, 0, sizeof(type3));
+
+ if (dumpdata_flag)
+ rk_dumpdata("ntlm-type3", data.data, data.length);
+
+ ret = heim_ntlm_decode_type3(&data, 1, &type3);
+ free(data.data);
+ if (ret)
+ errx(1, "heim_ntlm_decode_type3");
+
+ if (strcmp("workstation", type3.ws) != 0)
+ errx(1, "type3 ws wrong");
+
+ if (strcmp(target, type3.targetname) != 0)
+ errx(1, "type3 targetname wrong");
+
+ if (strcmp(user, type3.username) != 0)
+ errx(1, "type3 username wrong");
+
+
+ heim_ntlm_free_type3(&type3);
+
+ /*
+ * NTLMv2
+ */
+
+ memset(&type2, 0, sizeof(type2));
+
+ flags = NTLM_NEG_UNICODE | NTLM_NEG_NTLM | NTLM_TARGET_DOMAIN;
+ type2.flags = flags;
+
+ memset(type2.challenge, 0x7f, sizeof(type2.challenge));
+ type2.targetname = rk_UNCONST(target);
+ type2.targetinfo.data = "\x00\x00";
+ type2.targetinfo.length = 2;
+
+ ret = heim_ntlm_encode_type2(&type2, &data);
+ if (ret)
+ errx(1, "heim_ntlm_encode_type2");
+
+ memset(&type2, 0, sizeof(type2));
+
+ ret = heim_ntlm_decode_type2(&data, &type2);
+ free(data.data);
+ if (ret)
+ errx(1, "heim_ntlm_decode_type2");
+
+ heim_ntlm_free_type2(&type2);
+
+ return 0;
+}
+
+static int
+test_keys(void)
+{
+ const char
+ *username = "test",
+ *password = "test1234",
+ *target = "TESTNT";
+ const unsigned char
+ serverchallenge[8] = "\x67\x7f\x1c\x55\x7a\x5e\xe9\x6c";
+ struct ntlm_buf infotarget, infotarget2, answer, key;
+ unsigned char ntlmv2[16], ntlmv2_1[16];
+ int ret;
+
+ infotarget.length = 70;
+ infotarget.data =
+ "\x02\x00\x0c\x00\x54\x00\x45\x00\x53\x00\x54\x00\x4e\x00\x54\x00"
+ "\x01\x00\x0c\x00\x4d\x00\x45\x00\x4d\x00\x42\x00\x45\x00\x52\x00"
+ "\x03\x00\x1e\x00\x6d\x00\x65\x00\x6d\x00\x62\x00\x65\x00\x72\x00"
+ "\x2e\x00\x74\x00\x65\x00\x73\x00\x74\x00\x2e\x00\x63\x00\x6f"
+ "\x00\x6d\x00"
+ "\x00\x00\x00\x00";
+
+ answer.length = 0;
+ answer.data = NULL;
+
+ heim_ntlm_nt_key(password, &key);
+
+ ret = heim_ntlm_calculate_ntlm2(key.data,
+ key.length,
+ username,
+ target,
+ serverchallenge,
+ &infotarget,
+ ntlmv2,
+ &answer);
+ if (ret)
+ errx(1, "heim_ntlm_calculate_ntlm2");
+
+ ret = heim_ntlm_verify_ntlm2(key.data,
+ key.length,
+ username,
+ target,
+ 0,
+ serverchallenge,
+ &answer,
+ &infotarget2,
+ ntlmv2_1);
+ if (ret)
+ errx(1, "heim_ntlm_verify_ntlm2");
+
+ if (memcmp(ntlmv2, ntlmv2_1, sizeof(ntlmv2)) != 0)
+ errx(1, "ntlm master key not same");
+
+ if (infotarget.length > infotarget2.length)
+ errx(1, "infotarget length");
+
+ if (memcmp(infotarget.data, infotarget2.data, infotarget.length) != 0)
+ errx(1, "infotarget not the same");
+
+ free(key.data);
+ free(answer.data);
+ free(infotarget2.data);
+
+ return 0;
+}
+
+static int
+test_ntlm2_session_resp(void)
+{
+ int ret;
+ struct ntlm_buf lm, ntlm;
+
+ const unsigned char lm_resp[24] =
+ "\xff\xff\xff\x00\x11\x22\x33\x44"
+ "\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00";
+ const unsigned char ntlm2_sess_resp[24] =
+ "\x10\xd5\x50\x83\x2d\x12\xb2\xcc"
+ "\xb7\x9d\x5a\xd1\xf4\xee\xd3\xdf"
+ "\x82\xac\xa4\xc3\x68\x1d\xd4\x55";
+
+ const unsigned char client_nonce[8] =
+ "\xff\xff\xff\x00\x11\x22\x33\x44";
+ const unsigned char server_challenge[8] =
+ "\x01\x23\x45\x67\x89\xab\xcd\xef";
+
+ const unsigned char ntlm_hash[16] =
+ "\xcd\x06\xca\x7c\x7e\x10\xc9\x9b"
+ "\x1d\x33\xb7\x48\x5a\x2e\xd8\x08";
+
+ ret = heim_ntlm_calculate_ntlm2_sess(client_nonce,
+ server_challenge,
+ ntlm_hash,
+ &lm,
+ &ntlm);
+ if (ret)
+ errx(1, "heim_ntlm_calculate_ntlm2_sess_resp");
+
+ if (lm.length != 24 || memcmp(lm.data, lm_resp, 24) != 0)
+ errx(1, "lm_resp wrong");
+ if (ntlm.length != 24 || memcmp(ntlm.data, ntlm2_sess_resp, 24) != 0)
+ errx(1, "ntlm2_sess_resp wrong");
+
+ free(lm.data);
+ free(ntlm.data);
+
+
+ return 0;
+}
+
+static int
+test_ntlmv2(void)
+{
+ unsigned char type3[413] =
+ "\x4e\x54\x4c\x4d\x53\x53\x50\x00\x03\x00\x00\x00\x18\x00\x18\x00"
+ "\x80\x00\x00\x00\x9e\x00\x9e\x00\x98\x00\x00\x00\x14\x00\x14\x00"
+ "\x48\x00\x00\x00\x10\x00\x10\x00\x5c\x00\x00\x00\x14\x00\x14\x00"
+ "\x6c\x00\x00\x00\x00\x00\x00\x00\x36\x01\x00\x00\x05\x82\x88\xa2"
+ "\x05\x01\x28\x0a\x00\x00\x00\x0f\x43\x00\x4f\x00\x4c\x00\x4c\x00"
+ "\x45\x00\x59\x00\x2d\x00\x58\x00\x50\x00\x34\x00\x54\x00\x45\x00"
+ "\x53\x00\x54\x00\x55\x00\x53\x00\x45\x00\x52\x00\x43\x00\x4f\x00"
+ "\x4c\x00\x4c\x00\x45\x00\x59\x00\x2d\x00\x58\x00\x50\x00\x34\x00"
+ "\x2f\x96\xec\x0a\xf7\x9f\x2e\x24\xba\x09\x48\x10\xa5\x22\xd4\xe1"
+ "\x16\x6a\xca\x58\x74\x9a\xc1\x4f\x54\x6f\xee\x40\x96\xce\x43\x6e"
+ "\xdf\x99\x20\x71\x6c\x9a\xda\x2a\x01\x01\x00\x00\x00\x00\x00\x00"
+ "\x8d\xc0\x57\xc9\x79\x5e\xcb\x01\x16\x6a\xca\x58\x74\x9a\xc1\x4f"
+ "\x00\x00\x00\x00\x02\x00\x14\x00\x4e\x00\x55\x00\x54\x00\x43\x00"
+ "\x52\x00\x41\x00\x43\x00\x4b\x00\x45\x00\x52\x00\x01\x00\x14\x00"
+ "\x4e\x00\x55\x00\x54\x00\x43\x00\x52\x00\x41\x00\x43\x00\x4b\x00"
+ "\x45\x00\x52\x00\x04\x00\x12\x00\x61\x00\x70\x00\x70\x00\x6c\x00"
+ "\x65\x00\x2e\x00\x63\x00\x6f\x00\x6d\x00\x03\x00\x20\x00\x68\x00"
+ "\x75\x00\x6d\x00\x6d\x00\x65\x00\x6c\x00\x2e\x00\x61\x00\x70\x00"
+ "\x70\x00\x6c\x00\x65\x00\x2e\x00\x63\x00\x6f\x00\x6d\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x57\x00\x69\x00\x6e\x00\x64\x00\x6f"
+ "\x00\x77\x00\x73\x00\x20\x00\x32\x00\x30\x00\x30\x00\x32\x00\x20"
+ "\x00\x53\x00\x65\x00\x72\x00\x76\x00\x69\x00\x63\x00\x65\x00\x20"
+ "\x00\x50\x00\x61\x00\x63\x00\x6b\x00\x20\x00\x33\x00\x20\x00\x32"
+ "\x00\x36\x00\x30\x00\x30\x00\x00\x00\x57\x00\x69\x00\x6e\x00\x64"
+ "\x00\x6f\x00\x77\x00\x73\x00\x20\x00\x32\x00\x30\x00\x30\x00\x32"
+ "\x00\x20\x00\x35\x00\x2e\x00\x31\x00\x00\x00\x00\x00";
+ const unsigned char challenge[8] =
+ "\xe4\x9c\x6a\x12\xe1\xbd\xde\x6a";
+ unsigned char sessionkey[16];
+
+ const char key[16] = "\xD1\x83\x98\x3E\xAE\xA7\xBE\x99\x59\xC8\xF4\xC1\x98\xED\x0E\x68";
+
+ struct ntlm_buf data;
+ struct ntlm_type3 t3;
+ int ret;
+
+ struct ntlm_targetinfo ti;
+
+ unsigned char timsg[114] =
+ "\002\000\024\000N\000U\000T\000C\000R\000A\000C\000K\000E\000R\000\001\000\024\000N\000U\000T\000C\000R\000A\000C\000K\000E\000R\000\004\000\022\000a\000p\000p\000l\000e\000.\000c\000o\000m\000\003\000 \000h\000u\000m\000m\000e\000l\000.\000a\000p\000p\000l\000e\000.\000c\000o\000m\000\000\000\000\000\000\000\000";
+
+
+ data.data = type3;
+ data.length = sizeof(type3);
+
+ ret = heim_ntlm_decode_type3(&data, 1, &t3);
+ if (ret)
+ errx(1, "heim_ntlm_decode_type3");
+
+ memset(&ti, 0, sizeof(ti));
+
+ data.data = timsg;
+ data.length = sizeof(timsg);
+
+ ret = heim_ntlm_decode_targetinfo(&data, 1, &ti);
+ if (ret)
+ return ret;
+
+ ret = heim_ntlm_verify_ntlm2(key, sizeof(key),
+ t3.username,
+ t3.targetname,
+ 1285615547,
+ challenge,
+ &t3.ntlm,
+ &data,
+ sessionkey);
+ if (ret)
+ errx(1, "verify_ntlmv2");
+
+ if (sizeof(timsg) != data.length || memcmp(timsg, data.data, sizeof(timsg)) != 0)
+ errx(1, "target info wrong: %d != %d",
+ (int)sizeof(timsg), (int)data.length);
+
+ heim_ntlm_free_type3(&t3);
+ heim_ntlm_free_targetinfo(&ti);
+
+ return 0;
+}
+
+static int
+test_targetinfo(void)
+{
+ struct ntlm_targetinfo ti;
+ struct ntlm_buf buf;
+ const char *dnsservername = "dnsservername";
+ const char *targetname = "targetname";
+ const char z16[16] = { 0 };
+ int ret;
+
+ memset(&ti, 0, sizeof(ti));
+
+ ti.dnsservername = rk_UNCONST(dnsservername);
+ ti.avflags = 1;
+ ti.targetname = rk_UNCONST(targetname);
+ ti.channel_bindings.data = rk_UNCONST(z16);
+ ti.channel_bindings.length = sizeof(z16);
+
+ ret = heim_ntlm_encode_targetinfo(&ti, 1, &buf);
+ if (ret)
+ return ret;
+
+ memset(&ti, 0, sizeof(ti));
+
+ ret = heim_ntlm_decode_targetinfo(&buf, 1, &ti);
+ if (ret)
+ return ret;
+
+ if (ti.dnsservername == NULL ||
+ strcmp(ti.dnsservername, dnsservername) != 0)
+ errx(1, "ti.dnshostname != %s", dnsservername);
+ if (ti.avflags != 1)
+ errx(1, "ti.avflags != 1");
+ if (ti.targetname == NULL ||
+ strcmp(ti.targetname, targetname) != 0)
+ errx(1, "ti.targetname != %s", targetname);
+
+ if (ti.channel_bindings.length != sizeof(z16) ||
+ memcmp(ti.channel_bindings.data, z16, sizeof(z16)) != 0)
+ errx(1, "ti.channel_bindings != Z(16)");
+
+ heim_ntlm_free_targetinfo(&ti);
+
+ return 0;
+}
+
+static int
+test_string2key(void)
+{
+ const char *pw = "山田";
+ struct ntlm_buf buf;
+
+ unsigned char key[16] = {
+ 0xc6, 0x5d, 0xc7, 0x61, 0xa1, 0x34, 0x17, 0xa1,
+ 0x17, 0x08, 0x9c, 0x1b, 0xb0, 0x0d, 0x0f, 0x19
+ };
+
+ if (heim_ntlm_nt_key(pw, &buf) != 0)
+ errx(1, "heim_ntlmv_nt_key(jp)");
+
+ if (buf.length != 16 || memcmp(buf.data, key, 16) != 0)
+ errx(1, "compare failed");
+
+ heim_ntlm_free_buf(&buf);
+
+ return 0;
+}
+
+static int
+test_jp(void)
+{
+ char buf2[220] =
+ "\x4e\x54\x4c\x4d\x53\x53\x50\x00\x02\x00\x00\x00\x06\x00\x06\x00"
+ "\x38\x00\x00\x00\x05\x02\x89\x62\x62\x94\xb1\xf3\x56\x80\xb0\xf9"
+ "\x00\x00\x00\x00\x00\x00\x00\x00\x9e\x00\x9e\x00\x3e\x00\x00\x00"
+ "\x06\x01\xb0\x1d\x00\x00\x00\x0f\x43\x00\x4f\x00\x53\x00\x02\x00"
+ "\x06\x00\x43\x00\x4f\x00\x53\x00\x01\x00\x12\x00\x43\x00\x4f\x00"
+ "\x53\x00\x57\x00\x49\x00\x4e\x00\x37\x00\x4a\x00\x50\x00\x04\x00"
+ "\x1a\x00\x63\x00\x6f\x00\x73\x00\x2e\x00\x61\x00\x70\x00\x70\x00"
+ "\x6c\x00\x65\x00\x2e\x00\x63\x00\x6f\x00\x6d\x00\x03\x00\x2e\x00"
+ "\x63\x00\x6f\x00\x73\x00\x77\x00\x69\x00\x6e\x00\x37\x00\x6a\x00"
+ "\x70\x00\x2e\x00\x63\x00\x6f\x00\x73\x00\x2e\x00\x61\x00\x70\x00"
+ "\x70\x00\x6c\x00\x65\x00\x2e\x00\x63\x00\x6f\x00\x6d\x00\x05\x00"
+ "\x1a\x00\x63\x00\x6f\x00\x73\x00\x2e\x00\x61\x00\x70\x00\x70\x00"
+ "\x6c\x00\x65\x00\x2e\x00\x63\x00\x6f\x00\x6d\x00\x07\x00\x08\x00"
+ "\x94\x51\xf0\xbd\xdc\x61\xcb\x01\x00\x00\x00\x00";
+
+ char buf3[362] =
+ "\x4e\x54\x4c\x4d\x53\x53\x50\x00\x03\x00\x00\x00\x18\x00\x18\x00"
+ "\x74\x00\x00\x00\xce\x00\xce\x00\x8c\x00\x00\x00\x1a\x00\x1a\x00"
+ "\x40\x00\x00\x00\x04\x00\x04\x00\x5a\x00\x00\x00\x16\x00\x16\x00"
+ "\x5e\x00\x00\x00\x10\x00\x10\x00\x5a\x01\x00\x00\x05\x02\x89\x62"
+ "\x31\x00\x37\x00\x2e\x00\x32\x00\x30\x00\x31\x00\x2e\x00\x35\x00"
+ "\x37\x00\x2e\x00\x31\x00\x32\x00\x31\x00\x71\x5c\x30\x75\x77\x00"
+ "\x6f\x00\x72\x00\x6b\x00\x73\x00\x74\x00\x61\x00\x74\x00\x69\x00"
+ "\x6f\x00\x6e\x00\xab\xad\xeb\x72\x01\xd4\x5f\xdf\x59\x07\x5f\xa9"
+ "\xfd\x54\x98\x2d\xfa\x17\xbb\xf1\x3c\x8f\xf5\x20\xe6\x8f\xd7\x0a"
+ "\xc9\x19\x3e\x94\x61\x31\xdb\x0f\x55\xe8\xe2\x53\x01\x01\x00\x00"
+ "\x00\x00\x00\x00\x00\x06\x3e\x30\xe4\x61\xcb\x01\x71\x98\x10\x6b"
+ "\x4c\x82\xec\xb3\x00\x00\x00\x00\x02\x00\x06\x00\x43\x00\x4f\x00"
+ "\x53\x00\x01\x00\x12\x00\x43\x00\x4f\x00\x53\x00\x57\x00\x49\x00"
+ "\x4e\x00\x37\x00\x4a\x00\x50\x00\x04\x00\x1a\x00\x63\x00\x6f\x00"
+ "\x73\x00\x2e\x00\x61\x00\x70\x00\x70\x00\x6c\x00\x65\x00\x2e\x00"
+ "\x63\x00\x6f\x00\x6d\x00\x03\x00\x2e\x00\x63\x00\x6f\x00\x73\x00"
+ "\x77\x00\x69\x00\x6e\x00\x37\x00\x6a\x00\x70\x00\x2e\x00\x63\x00"
+ "\x6f\x00\x73\x00\x2e\x00\x61\x00\x70\x00\x70\x00\x6c\x00\x65\x00"
+ "\x2e\x00\x63\x00\x6f\x00\x6d\x00\x05\x00\x1a\x00\x63\x00\x6f\x00"
+ "\x73\x00\x2e\x00\x61\x00\x70\x00\x70\x00\x6c\x00\x65\x00\x2e\x00"
+ "\x63\x00\x6f\x00\x6d\x00\x07\x00\x08\x00\xab\xec\xcc\x30\xe4\x61"
+ "\xcb\x01\x00\x00\x00\x00\x00\x00\x00\x00\xbc\x2e\xba\x3f\xd1\xb1"
+ "\xa7\x70\x00\x9d\x55\xa0\x59\x74\x2b\x78";
+
+
+ struct ntlm_type2 type2;
+ struct ntlm_type3 type3;
+ struct ntlm_buf data;
+ int ret;
+
+ data.length = sizeof(buf2);
+ data.data = buf2;
+
+ memset(&type2, 0, sizeof(type2));
+
+ ret = heim_ntlm_decode_type2(&data, &type2);
+ if (ret)
+ errx(1, "heim_ntlm_decode_type2(jp): %d", ret);
+
+ data.data = NULL;
+ data.length = 0;
+
+ ret = heim_ntlm_encode_type2(&type2, &data);
+ if (ret)
+ errx(1, "heim_ntlm_encode_type2(jp): %d", ret);
+
+ heim_ntlm_free_type2(&type2);
+ heim_ntlm_free_buf(&data);
+
+ data.length = sizeof(buf3);
+ data.data = buf3;
+
+ memset(&type3, 0, sizeof(type3));
+
+ ret = heim_ntlm_decode_type3(&data, 1, &type3);
+ if (ret)
+ errx(1, "heim_ntlm_decode_type2(jp): %d", ret);
+
+ data.data = NULL;
+ data.length = 0;
+
+ ret = heim_ntlm_encode_type3(&type3, &data, NULL);
+ if (ret)
+ errx(1, "heim_ntlm_decode_type2(jp): %d", ret);
+
+ heim_ntlm_free_type3(&type3);
+ heim_ntlm_free_buf(&data);
+
+ return 0;
+}
+
+
+static int verbose_flag = 0;
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"verbose", 0, arg_flag, &verbose_flag, "verbose printing", NULL },
+ {"version", 0, arg_flag, &version_flag, "print version", NULL },
+ {"help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args),
+ NULL, "");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ int ret = 0, optidx = 0;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ if (verbose_flag)
+ printf("test_parse\n");
+ ret |= test_parse();
+
+ if (verbose_flag)
+ printf("test_keys\n");
+ ret |= test_keys();
+
+ if (verbose_flag)
+ printf("test_ntlm2_session_resp\n");
+ ret |= test_ntlm2_session_resp();
+
+ if (verbose_flag)
+ printf("test_targetinfo\n");
+ ret |= test_targetinfo();
+
+ if (verbose_flag)
+ printf("test_ntlmv2\n");
+ ret |= test_ntlmv2();
+
+ if (verbose_flag)
+ printf("test_string2key\n");
+ ret |= test_string2key();
+
+ if (verbose_flag)
+ printf("test_jp\n");
+ ret |= test_jp();
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/ntlm/version-script.map b/third_party/heimdal/lib/ntlm/version-script.map
new file mode 100644
index 0000000..6fe67a6
--- /dev/null
+++ b/third_party/heimdal/lib/ntlm/version-script.map
@@ -0,0 +1,30 @@
+# $Id$
+
+HEIMDAL_NTLM_1.0 {
+ global:
+ heim_ntlm_build_ntlm1_master;
+ heim_ntlm_calculate_lm2;
+ heim_ntlm_calculate_ntlm1;
+ heim_ntlm_calculate_ntlm2;
+ heim_ntlm_calculate_ntlm2_sess;
+ heim_ntlm_decode_targetinfo;
+ heim_ntlm_decode_type1;
+ heim_ntlm_decode_type2;
+ heim_ntlm_decode_type3;
+ heim_ntlm_encode_targetinfo;
+ heim_ntlm_encode_type1;
+ heim_ntlm_encode_type2;
+ heim_ntlm_encode_type3;
+ heim_ntlm_free_buf;
+ heim_ntlm_free_targetinfo;
+ heim_ntlm_free_type1;
+ heim_ntlm_free_type2;
+ heim_ntlm_free_type3;
+ heim_ntlm_nt_key;
+ heim_ntlm_ntlmv2_key;
+ heim_ntlm_verify_ntlm2;
+ heim_ntlm_unparse_flags;
+ initialize_ntlm_error_table_r;
+ local:
+ *;
+};
diff --git a/third_party/heimdal/lib/otp/ChangeLog b/third_party/heimdal/lib/otp/ChangeLog
new file mode 100644
index 0000000..d4fda44
--- /dev/null
+++ b/third_party/heimdal/lib/otp/ChangeLog
@@ -0,0 +1,128 @@
+2007-07-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: split source files in dist and nodist.
+
+2007-07-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: New library version
+
+2007-06-07 Assar Westerlund <assar@kth.se>
+
+ * otp_parse.c: NIIL should be NIL
+
+2006-05-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * otp_parse.c: Less "pointer targets in passing argument differ in
+ signedness" warnings.
+
+2005-07-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * otp.h: remove parameter names to avoid shadow warnings
+
+2005-07-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * otp_parse.c (parse_words): avoid const warnings by making a
+ (shorter) copy of the string instead of truncating it
+
+2005-01-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * otp_parse.c: cast argument to tolower to unsigned char
+
+2003-04-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * roken_rename.h: rename strlcat, strlcpy
+ * Makefile.am: (ES): add strlcpy.c and strlcat.c
+ * otp_db.c: use strlcpy, from openbsd
+ * otp_md.c: use strlcat/strlcpy, from openbsd
+ * otp_challenge.c: do strdup again, we desupport ultrix
+
+2002-09-10 Johan Danielsson <joda@pdc.kth.se>
+
+ * otp_md.c: if we only have old hash names, we need to include
+ functions here that do the work
+
+2002-05-20 Johan Danielsson <joda@pdc.kth.se>
+
+ * otp_db.c: fix ndbm test
+
+2002-05-17 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: add hooks for ndbm_wrap
+
+ * otp_db.c: use ndbm_wrap
+
+2001-07-12 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: add required library dependencies
+
+2001-01-30 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libotp_la_LDFLAGS): bump version to 1:2:1
+
+2001-01-29 Assar Westerlund <assar@sics.se>
+
+ * otp_md.c: update to new md4/md5/sha API
+
+2000-12-11 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (INCLUDES): add krb4 includes here, which are
+ somewhat bogusly used when linking against libdes supplied by krb4
+
+2000-07-25 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: bump version to 1:1:1
+
+2000-07-01 Assar Westerlund <assar@sics.se>
+
+ * const-ify
+
+2000-02-07 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: update version to 1:0:1
+
+2000-01-26 Assar Westerlund <assar@sics.se>
+
+ * otp_md.c: update to pseudo-standard APIs for md4,md5,sha.
+ * otp_md.c: start using the pseudo-standard APIs for the hash
+ functions
+
+1999-10-20 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 0:1:0
+
+Fri Mar 19 14:52:48 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: add version-info
+
+Thu Mar 18 11:24:19 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: include Makefile.am.common
+
+Sat Mar 13 22:27:10 1999 Assar Westerlund <assar@sics.se>
+
+ * otp_parse.c: unsigned-ify
+
+Sun Nov 22 10:44:16 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (WFLAGS): set
+
+Mon May 25 05:27:07 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (clean): try to remove shared library debris
+
+Sat May 23 20:54:28 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: link with DBLIB
+
+Sun Apr 19 09:59:46 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in: add symlink magic for linux
+
+Sat Feb 7 07:27:18 1998 Assar Westerlund <assar@sics.se>
+
+ * otp_db.c (otp_put): make sure we don't overrun `buf'
+
+Sun Nov 9 07:14:59 1997 Assar Westerlund <assar@sics.se>
+
+ * otp_locl.h: use xdbm.h
+
diff --git a/third_party/heimdal/lib/otp/Makefile.am b/third_party/heimdal/lib/otp/Makefile.am
new file mode 100644
index 0000000..018e4ef
--- /dev/null
+++ b/third_party/heimdal/lib/otp/Makefile.am
@@ -0,0 +1,90 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+AM_CPPFLAGS += $(ROKEN_RENAME)
+if HAVE_DBHEADER
+AM_CPPFLAGS += -I$(DBHEADER)
+endif
+
+noinst_PROGRAMS = otptest
+
+check_PROGRAMS = otptest
+
+otptest_LDADD = libotp.la
+
+include_HEADERS = otp.h
+
+lib_LTLIBRARIES = libotp.la
+libotp_la_LDFLAGS = -version-info 1:5:1
+libotp_la_LIBADD = $(LIB_hcrypto) $(LIB_roken)
+
+if HAVE_DB3
+ndbm_wrap = ndbm_wrap.c ndbm_wrap.h
+libotp_la_LIBADD += $(DB3LIB)
+else
+if HAVE_DB1
+ndbm_wrap = ndbm_wrap.c ndbm_wrap.h
+libotp_la_LIBADD += $(DB1LIB)
+else
+ndbm_wrap =
+libotp_la_LIBADD += $(NDBMLIB)
+endif
+endif
+
+dist_libotp_la_SOURCES = \
+ otp.c \
+ otp_challenge.c \
+ otp_db.c \
+ otp_md.c \
+ otp_parse.c \
+ otp_print.c \
+ otp_verify.c \
+ otp_locl.h \
+ otp_md.h \
+ roken_rename.h
+
+nodist_libotp_la_SOURCES = $(ndbm_wrap) $(ROKEN_SRCS)
+
+libotp_la_DEPENDENCIES = version-script.map
+
+if do_roken_rename
+ROKEN_SRCS = snprintf.c strcasecmp.c strncasecmp.c strlwr.c strlcpy.c strlcat.c
+endif
+
+if versionscript
+libotp_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+endif
+
+$(libotp_la_OBJECTS): $(ndbm_wrap)
+
+ndbm_wrap.c:
+ $(LN_S) $(srcdir)/../roken/ndbm_wrap.c .
+ndbm_wrap.h:
+ (echo '#define dbm_rename(X) __otp_ ## X'; cat $(srcdir)/../roken/ndbm_wrap.h) > ndbm_wrap.h
+
+
+snprintf.c:
+ $(LN_S) $(srcdir)/../roken/snprintf.c .
+strcasecmp.c:
+ $(LN_S) $(srcdir)/../roken/strcasecmp.c .
+strncasecmp.c:
+ $(LN_S) $(srcdir)/../roken/strncasecmp.c .
+strlwr.c:
+ $(LN_S) $(srcdir)/../roken/strlwr.c .
+strlcpy.c:
+ $(LN_S) $(srcdir)/../roken/strlcpy.c .
+strlcat.c:
+ $(LN_S) $(srcdir)/../roken/strlcat.c .
+
+CLEANFILES = \
+ ndbm_wrap.c \
+ ndbm_wrap.h \
+ snprintf.c \
+ strcasecmp.c \
+ strlcat.c \
+ strlcpy.c \
+ strlwr.c \
+ strncasecmp.c
+
+EXTRA_DIST = NTMakefile version-script.map
diff --git a/third_party/heimdal/lib/otp/NTMakefile b/third_party/heimdal/lib/otp/NTMakefile
new file mode 100644
index 0000000..a531c8b
--- /dev/null
+++ b/third_party/heimdal/lib/otp/NTMakefile
@@ -0,0 +1,35 @@
+########################################################################
+#
+# Copyright (c) 2009, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\otp
+
+!include ../../windows/NTMakefile.w32
+
diff --git a/third_party/heimdal/lib/otp/otp.c b/third_party/heimdal/lib/otp/otp.c
new file mode 100644
index 0000000..906f72c
--- /dev/null
+++ b/third_party/heimdal/lib/otp/otp.c
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 1995 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+RCSID("$Id$");
+#endif
+
+#include "otp_locl.h"
+#include "otp_md.h"
+
+static OtpAlgorithm algorithms[] = {
+ {OTP_ALG_MD4, "md4", 16, otp_md4_hash, otp_md4_init, otp_md4_next},
+ {OTP_ALG_MD5, "md5", 16, otp_md5_hash, otp_md5_init, otp_md5_next},
+ {OTP_ALG_SHA, "sha", 20, otp_sha_hash, otp_sha_init, otp_sha_next}
+};
+
+OtpAlgorithm *
+otp_find_alg (char *name)
+{
+ int i;
+
+ for (i = 0; i < sizeof(algorithms)/sizeof(*algorithms); ++i)
+ if (strcmp (name, algorithms[i].name) == 0)
+ return &algorithms[i];
+ return NULL;
+}
+
+char *
+otp_error (OtpContext *o)
+{
+ return o->err;
+}
diff --git a/third_party/heimdal/lib/otp/otp.h b/third_party/heimdal/lib/otp/otp.h
new file mode 100644
index 0000000..3a4e549
--- /dev/null
+++ b/third_party/heimdal/lib/otp/otp.h
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 1995 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef _OTP_H
+#define _OTP_H
+
+#include <stdlib.h>
+#include <time.h>
+
+enum {OTPKEYSIZE = 8};
+
+typedef unsigned char OtpKey[OTPKEYSIZE];
+
+#define OTP_MIN_PASSPHRASE 10
+#define OTP_MAX_PASSPHRASE 63
+
+#define OTP_USER_TIMEOUT 120
+#define OTP_DB_TIMEOUT 60
+
+#define OTP_HEXPREFIX "hex:"
+#define OTP_WORDPREFIX "word:"
+
+typedef enum { OTP_ALG_MD4, OTP_ALG_MD5, OTP_ALG_SHA } OtpAlgID;
+
+#define OTP_ALG_DEFAULT "md5"
+
+typedef struct {
+ OtpAlgID id;
+ char *name;
+ int hashsize;
+ int (*hash)(const char *, size_t, unsigned char *);
+ int (*init)(OtpKey, const char *, const char *);
+ int (*next)(OtpKey);
+} OtpAlgorithm;
+
+typedef struct {
+ char *user;
+ OtpAlgorithm *alg;
+ unsigned n;
+ char seed[17];
+ OtpKey key;
+ int challengep;
+ time_t lock_time;
+ char *err;
+} OtpContext;
+
+OtpAlgorithm *otp_find_alg (char *);
+void otp_print_stddict (OtpKey, char *, size_t);
+void otp_print_hex (OtpKey, char *, size_t);
+void otp_print_stddict_extended (OtpKey, char *, size_t);
+void otp_print_hex_extended (OtpKey, char *, size_t);
+unsigned otp_checksum (OtpKey);
+int otp_parse_hex (OtpKey, const char *);
+int otp_parse_stddict (OtpKey, const char *);
+int otp_parse_altdict (OtpKey, const char *, OtpAlgorithm *);
+int otp_parse (OtpKey, const char *, OtpAlgorithm *);
+int otp_challenge (OtpContext *, char *, char *, size_t);
+int otp_verify_user (OtpContext *, const char *);
+int otp_verify_user_1 (OtpContext *, const char *);
+char *otp_error (OtpContext *);
+
+void *otp_db_open (void);
+void otp_db_close (void *);
+int otp_put (void *, OtpContext *);
+int otp_get (void *, OtpContext *);
+int otp_simple_get (void *, OtpContext *);
+int otp_delete (void *, OtpContext *);
+
+#endif /* _OTP_H */
diff --git a/third_party/heimdal/lib/otp/otp_challenge.c b/third_party/heimdal/lib/otp/otp_challenge.c
new file mode 100644
index 0000000..76b3768
--- /dev/null
+++ b/third_party/heimdal/lib/otp/otp_challenge.c
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+RCSID("$Id$");
+#endif
+
+#include "otp_locl.h"
+
+int
+otp_challenge (OtpContext *ctx, char *user, char *str, size_t len)
+{
+ void *dbm;
+ int ret;
+
+ ctx->challengep = 0;
+ ctx->err = NULL;
+ ctx->user = strdup(user);
+ if (ctx->user == NULL) {
+ ctx->err = "Out of memory";
+ return -1;
+ }
+ dbm = otp_db_open ();
+ if (dbm == NULL) {
+ ctx->err = "Cannot open database";
+ return -1;
+ }
+ ret = otp_get (dbm, ctx);
+ otp_db_close (dbm);
+ if (ret)
+ return ret;
+ snprintf (str, len,
+ "[ otp-%s %u %s ]",
+ ctx->alg->name, ctx->n-1, ctx->seed);
+ ctx->challengep = 1;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/otp/otp_db.c b/third_party/heimdal/lib/otp/otp_db.c
new file mode 100644
index 0000000..76daa87
--- /dev/null
+++ b/third_party/heimdal/lib/otp/otp_db.c
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+RCSID("$Id$");
+#endif
+
+#include "otp_locl.h"
+
+#if !defined(HAVE_NDBM) && !defined(HAVE_DB_NDBM)
+#include "ndbm_wrap.h"
+#endif
+
+#define RETRIES 5
+
+void *
+otp_db_open (void)
+{
+ int lock;
+ int i;
+ void *ret;
+
+ for(i = 0; i < RETRIES; ++i) {
+ struct stat statbuf;
+
+ lock = open (OTP_DB_LOCK, O_WRONLY | O_CREAT | O_EXCL, 0666);
+ if (lock >= 0) {
+ close(lock);
+ break;
+ }
+ if (stat (OTP_DB_LOCK, &statbuf) == 0) {
+ if (time(NULL) - statbuf.st_mtime > OTP_DB_TIMEOUT)
+ unlink (OTP_DB_LOCK);
+ else
+ sleep (1);
+ }
+ }
+ if (i == RETRIES)
+ return NULL;
+ ret = dbm_open (OTP_DB, O_RDWR | O_CREAT, 0600);
+ if (ret == NULL)
+ unlink (OTP_DB_LOCK);
+ return ret;
+}
+
+void
+otp_db_close (void *dbm)
+{
+ dbm_close ((DBM *)dbm);
+ unlink (OTP_DB_LOCK);
+}
+
+/*
+ * Remove this entry from the database.
+ * return 0 if ok.
+ */
+
+int
+otp_delete (void *v, OtpContext *ctx)
+{
+ DBM *dbm = (DBM *)v;
+ datum key;
+
+ key.dsize = strlen(ctx->user);
+ key.dptr = ctx->user;
+
+ return dbm_delete(dbm, key);
+}
+
+/*
+ * Read this entry from the database and lock it if lockp.
+ */
+
+static int
+otp_get_internal (void *v, OtpContext *ctx, int lockp)
+{
+ DBM *dbm = (DBM *)v;
+ datum dat, key;
+ char *p;
+ time_t now, then;
+
+ key.dsize = strlen(ctx->user);
+ key.dptr = ctx->user;
+
+ dat = dbm_fetch (dbm, key);
+ if (dat.dptr == NULL) {
+ ctx->err = "Entry not found";
+ return -1;
+ }
+ p = dat.dptr;
+
+ memcpy (&then, p, sizeof(then));
+ ctx->lock_time = then;
+ if (lockp) {
+ time(&now);
+ if (then && now - then < OTP_USER_TIMEOUT) {
+ ctx->err = "Entry locked";
+ return -1;
+ }
+ memcpy (p, &now, sizeof(now));
+ }
+ p += sizeof(now);
+ ctx->alg = otp_find_alg (p);
+ if (ctx->alg == NULL) {
+ ctx->err = "Bad algorithm";
+ return -1;
+ }
+ p += strlen(p) + 1;
+ {
+ unsigned char *up = (unsigned char *)p;
+ ctx->n = (up[0] << 24) | (up[1] << 16) | (up[2] << 8) | up[3];
+ }
+ p += 4;
+ memcpy (ctx->key, p, OTPKEYSIZE);
+ p += OTPKEYSIZE;
+ strlcpy (ctx->seed, p, sizeof(ctx->seed));
+ if (lockp)
+ return dbm_store (dbm, key, dat, DBM_REPLACE);
+ else
+ return 0;
+}
+
+/*
+ * Get and lock.
+ */
+
+int
+otp_get (void *v, OtpContext *ctx)
+{
+ return otp_get_internal (v, ctx, 1);
+}
+
+/*
+ * Get and don't lock.
+ */
+
+int
+otp_simple_get (void *v, OtpContext *ctx)
+{
+ return otp_get_internal (v, ctx, 0);
+}
+
+/*
+ * Write this entry to the database.
+ */
+
+int
+otp_put (void *v, OtpContext *ctx)
+{
+ DBM *dbm = (DBM *)v;
+ datum dat, key;
+ char buf[1024], *p;
+ time_t zero = 0;
+ size_t len, rem;
+
+ key.dsize = strlen(ctx->user);
+ key.dptr = ctx->user;
+
+ p = buf;
+ rem = sizeof(buf);
+
+ if (rem < sizeof(zero))
+ return -1;
+ memcpy (p, &zero, sizeof(zero));
+ p += sizeof(zero);
+ rem -= sizeof(zero);
+ len = strlen(ctx->alg->name) + 1;
+
+ if (rem < len)
+ return -1;
+ strlcpy (p, ctx->alg->name, rem);
+ p += len;
+ rem -= len;
+
+ if (rem < 4)
+ return -1;
+ {
+ unsigned char *up = (unsigned char *)p;
+ *up++ = (ctx->n >> 24) & 0xFF;
+ *up++ = (ctx->n >> 16) & 0xFF;
+ *up++ = (ctx->n >> 8) & 0xFF;
+ *up++ = (ctx->n >> 0) & 0xFF;
+ }
+ p += 4;
+ rem -= 4;
+
+ if (rem < OTPKEYSIZE)
+ return -1;
+ memcpy (p, ctx->key, OTPKEYSIZE);
+ p += OTPKEYSIZE;
+ rem -= OTPKEYSIZE;
+
+ len = strlen(ctx->seed) + 1;
+ if (rem < len)
+ return -1;
+ strlcpy (p, ctx->seed, rem);
+ p += len;
+ rem -= len;
+ dat.dptr = buf;
+ dat.dsize = p - buf;
+ return dbm_store (dbm, key, dat, DBM_REPLACE);
+}
diff --git a/third_party/heimdal/lib/otp/otp_locl.h b/third_party/heimdal/lib/otp/otp_locl.h
new file mode 100644
index 0000000..29b455e
--- /dev/null
+++ b/third_party/heimdal/lib/otp/otp_locl.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include <string.h>
+#include <time.h>
+#include <errno.h>
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#endif
+#ifdef HAVE_PWD_H
+#include <pwd.h>
+#endif
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_IO_H
+#include <io.h>
+#endif
+
+#include <roken.h>
+
+#include <otp.h>
+
+#include <xdbm.h>
+
+#define OTPKEYS "/.otpkeys"
+
+#define OTP_DB SYSCONFDIR "/otp"
+#define OTP_DB_LOCK SYSCONFDIR "/otp-lock"
diff --git a/third_party/heimdal/lib/otp/otp_md.c b/third_party/heimdal/lib/otp/otp_md.c
new file mode 100644
index 0000000..9338a20
--- /dev/null
+++ b/third_party/heimdal/lib/otp/otp_md.c
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) 1995 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#define HC_DEPRECATED_CRYPTO
+
+#include "config.h"
+
+#include "otp_locl.h"
+
+#include "otp_md.h"
+#include "crypto-headers.h"
+
+/*
+ * Compress len bytes from md into key
+ */
+
+static void
+compressmd (OtpKey key, unsigned char *md, size_t len)
+{
+ u_char *p = key;
+
+ memset (p, 0, OTPKEYSIZE);
+ while(len) {
+ *p++ ^= *md++;
+ *p++ ^= *md++;
+ *p++ ^= *md++;
+ *p++ ^= *md++;
+ len -= 4;
+ if (p == key + OTPKEYSIZE)
+ p = key;
+ }
+}
+
+/*
+ * For histerical reasons, in the OTP definition it's said that
+ * the result from SHA must be stored in little-endian order. See
+ * draft-ietf-otp-01.txt.
+ */
+
+static void
+little_endian(unsigned char *res, size_t len)
+{
+ unsigned char t;
+ size_t i;
+
+ for (i = 0; i < len; i += 4) {
+ t = res[i + 0]; res[i + 0] = res[i + 3]; res[i + 3] = t;
+ t = res[i + 1]; res[i + 1] = res[i + 2]; res[i + 2] = t;
+ }
+}
+
+static int
+otp_md_init (OtpKey key,
+ const char *pwd,
+ const char *seed,
+ const EVP_MD *md,
+ int le,
+ unsigned char *res,
+ size_t ressz)
+{
+ EVP_MD_CTX *ctx;
+ char *p;
+ int len;
+
+ len = strlen(pwd) + strlen(seed);
+ p = malloc (len + 1);
+ if (p == NULL)
+ return -1;
+ strlcpy (p, seed, len + 1);
+ strlwr (p);
+ strlcat (p, pwd, len + 1);
+
+ ctx = EVP_MD_CTX_create();
+
+ EVP_DigestInit_ex(ctx, md, NULL);
+ EVP_DigestUpdate(ctx, p, len);
+ EVP_DigestFinal_ex(ctx, res, NULL);
+
+ EVP_MD_CTX_destroy(ctx);
+
+ if (le)
+ little_endian(res, ressz);
+
+ free (p);
+ compressmd (key, res, ressz);
+ return 0;
+}
+
+static int
+otp_md_next (OtpKey key,
+ const EVP_MD *md,
+ int le,
+ unsigned char *res,
+ size_t ressz)
+{
+ EVP_MD_CTX *ctx;
+
+ ctx = EVP_MD_CTX_create();
+
+ EVP_DigestInit_ex(ctx, md, NULL);
+ EVP_DigestUpdate(ctx, key, OTPKEYSIZE);
+ EVP_DigestFinal_ex(ctx, res, NULL);
+
+ EVP_MD_CTX_destroy(ctx);
+
+ if (le)
+ little_endian(res, ressz);
+
+ compressmd (key, res, ressz);
+ return 0;
+}
+
+static int
+otp_md_hash (const char *data,
+ size_t len,
+ const EVP_MD *md,
+ int le,
+ unsigned char *res,
+ size_t ressz)
+{
+ EVP_MD_CTX *ctx;
+ ctx = EVP_MD_CTX_create();
+
+ EVP_DigestInit_ex(ctx, md, NULL);
+ EVP_DigestUpdate(ctx, data, len);
+ EVP_DigestFinal_ex(ctx, res, NULL);
+
+ EVP_MD_CTX_destroy(ctx);
+
+ if (le)
+ little_endian(res, ressz);
+
+ return 0;
+}
+
+int
+otp_md4_init (OtpKey key, const char *pwd, const char *seed)
+{
+ unsigned char res[16];
+ return otp_md_init (key, pwd, seed, EVP_md4(), 0, res, sizeof(res));
+}
+
+int
+otp_md4_hash (const char *data,
+ size_t len,
+ unsigned char *res)
+{
+ return otp_md_hash (data, len, EVP_md4(), 0, res, 16);
+}
+
+int
+otp_md4_next (OtpKey key)
+{
+ unsigned char res[16];
+ return otp_md_next (key, EVP_md4(), 0, res, sizeof(res));
+}
+
+
+int
+otp_md5_init (OtpKey key, const char *pwd, const char *seed)
+{
+ unsigned char res[16];
+ return otp_md_init (key, pwd, seed, EVP_md5(), 0, res, sizeof(res));
+}
+
+int
+otp_md5_hash (const char *data,
+ size_t len,
+ unsigned char *res)
+{
+ return otp_md_hash (data, len, EVP_md5(), 0, res, 16);
+}
+
+int
+otp_md5_next (OtpKey key)
+{
+ unsigned char res[16];
+ return otp_md_next (key, EVP_md5(), 0, res, sizeof(res));
+}
+
+int
+otp_sha_init (OtpKey key, const char *pwd, const char *seed)
+{
+ unsigned char res[20];
+ return otp_md_init (key, pwd, seed, EVP_sha1(), 1, res, sizeof(res));
+}
+
+int
+otp_sha_hash (const char *data,
+ size_t len,
+ unsigned char *res)
+{
+ return otp_md_hash (data, len, EVP_sha1(), 1, res, 20);
+}
+
+int
+otp_sha_next (OtpKey key)
+{
+ unsigned char res[20];
+ return otp_md_next (key, EVP_sha1(), 1, res, sizeof(res));
+}
diff --git a/third_party/heimdal/lib/otp/otp_md.h b/third_party/heimdal/lib/otp/otp_md.h
new file mode 100644
index 0000000..645ac1a
--- /dev/null
+++ b/third_party/heimdal/lib/otp/otp_md.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 1995 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+int otp_md4_init (OtpKey key, const char *pwd, const char *seed);
+int otp_md4_hash (const char *, size_t, unsigned char *res);
+int otp_md4_next (OtpKey key);
+
+int otp_md5_init (OtpKey key, const char *pwd, const char *seed);
+int otp_md5_hash (const char *, size_t, unsigned char *res);
+int otp_md5_next (OtpKey key);
+
+int otp_sha_init (OtpKey key, const char *pwd, const char *seed);
+int otp_sha_hash (const char *, size_t, unsigned char *res);
+int otp_sha_next (OtpKey key);
diff --git a/third_party/heimdal/lib/otp/otp_parse.c b/third_party/heimdal/lib/otp/otp_parse.c
new file mode 100644
index 0000000..385f043
--- /dev/null
+++ b/third_party/heimdal/lib/otp/otp_parse.c
@@ -0,0 +1,2522 @@
+/*
+ * Copyright (c) 1995-2000, 2005-2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+RCSID("$Id$");
+#endif
+
+#include "otp_locl.h"
+
+struct e {
+ const char *s;
+ unsigned n;
+};
+
+extern const struct e inv_std_dict[2048];
+
+static int
+cmp(const void *a, const void *b)
+{
+ const struct e *e1, *e2;
+
+ e1 = (const struct e *)a;
+ e2 = (const struct e *)b;
+ return strcasecmp (e1->s, e2->s);
+}
+
+static int
+get_stdword (const char *s, void *v)
+{
+ struct e e, *r;
+
+ e.s = s;
+ e.n = -1;
+ r = (struct e *) bsearch (&e, inv_std_dict,
+ sizeof(inv_std_dict)/sizeof(*inv_std_dict),
+ sizeof(*inv_std_dict), cmp);
+ if (r)
+ return r->n;
+ else
+ return -1;
+}
+
+static void
+compress (OtpKey key, unsigned wn[])
+{
+ key[0] = wn[0] >> 3;
+ key[1] = ((wn[0] & 0x07) << 5) | (wn[1] >> 6);
+ key[2] = ((wn[1] & 0x3F) << 2) | (wn[2] >> 9);
+ key[3] = ((wn[2] >> 1) & 0xFF);
+ key[4] = ((wn[2] & 0x01) << 7) | (wn[3] >> 4);
+ key[5] = ((wn[3] & 0x0F) << 4) | (wn[4] >> 7);
+ key[6] = ((wn[4] & 0x7F) << 1) | (wn[5] >> 10);
+ key[7] = ((wn[5] >> 2) & 0xFF);
+}
+
+static int
+get_altword (const char *s, void *a)
+{
+ OtpAlgorithm *alg = (OtpAlgorithm *)a;
+ int ret;
+ unsigned char *res = malloc(alg->hashsize);
+
+ if (res == NULL)
+ return -1;
+ alg->hash (s, strlen(s), res);
+ ret = (unsigned)(res[alg->hashsize - 1]) |
+ ((res[alg->hashsize - 2] & 0x03) << 8);
+ free (res);
+ return ret;
+}
+
+static int
+parse_words(unsigned wn[],
+ const char *str,
+ int (*convert)(const char *, void *),
+ void *arg)
+{
+ const unsigned char *w, *wend;
+ char *wcopy;
+ int i;
+ int tmp;
+
+ w = (const unsigned char *)str;
+ for (i = 0; i < 6; ++i) {
+ while (isspace(*w))
+ ++w;
+ wend = w;
+ while (isalpha (*wend))
+ ++wend;
+
+ tmp = wend - w;
+ wcopy = malloc(tmp + 1);
+ if (wcopy == NULL)
+ return -1;
+ memcpy(wcopy, w, tmp);
+ wcopy[tmp] = '\0';
+
+ tmp = (*convert)(wcopy, arg);
+ free(wcopy);
+ w = wend;
+ if (tmp < 0)
+ return -1;
+ wn[i] = tmp;
+ }
+ return 0;
+}
+
+static int
+otp_parse_internal (OtpKey key, const char *str,
+ OtpAlgorithm *alg,
+ int (*convert)(const char *, void *))
+{
+ unsigned wn[6];
+
+ if (parse_words (wn, str, convert, alg))
+ return -1;
+ compress (key, wn);
+ if (otp_checksum (key) != (wn[5] & 0x03))
+ return -1;
+ return 0;
+}
+
+int
+otp_parse_stddict (OtpKey key, const char *str)
+{
+ return otp_parse_internal (key, str, NULL, get_stdword);
+}
+
+int
+otp_parse_altdict (OtpKey key, const char *str, OtpAlgorithm *alg)
+{
+ return otp_parse_internal (key, str, alg, get_altword);
+}
+
+int
+otp_parse_hex (OtpKey key, const char *s)
+{
+ char buf[17], *b;
+ int is[8];
+ int i;
+
+ b = buf;
+ while (*s) {
+ if (strchr ("0123456789ABCDEFabcdef", *s)) {
+ if (b - buf >= 16)
+ return -1;
+ else
+ *b++ = tolower((unsigned char)*s);
+ }
+ s++;
+ }
+ *b = '\0';
+ if (sscanf (buf, "%2x%2x%2x%2x%2x%2x%2x%2x",
+ &is[0], &is[1], &is[2], &is[3], &is[4],
+ &is[5], &is[6], &is[7]) != 8)
+ return -1;
+ for (i = 0; i < OTPKEYSIZE; ++i)
+ key[i] = is[i];
+ return 0;
+}
+
+int
+otp_parse (OtpKey key, const char *s, OtpAlgorithm *alg)
+{
+ int ret;
+ int dohex = 1;
+
+ if (strncmp (s, OTP_HEXPREFIX, strlen(OTP_HEXPREFIX)) == 0)
+ return otp_parse_hex (key, s + strlen(OTP_HEXPREFIX));
+ if (strncmp (s, OTP_WORDPREFIX, strlen(OTP_WORDPREFIX)) == 0) {
+ s += strlen(OTP_WORDPREFIX);
+ dohex = 0;
+ }
+
+ ret = otp_parse_stddict (key, s);
+ if (ret)
+ ret = otp_parse_altdict (key, s, alg);
+ if (ret && dohex)
+ ret = otp_parse_hex (key, s);
+ return ret;
+}
+
+const char *const std_dict[2048] =
+{ "A", "ABE", "ACE", "ACT", "AD", "ADA", "ADD",
+"AGO", "AID", "AIM", "AIR", "ALL", "ALP", "AM", "AMY",
+"AN", "ANA", "AND", "ANN", "ANT", "ANY", "APE", "APS",
+"APT", "ARC", "ARE", "ARK", "ARM", "ART", "AS", "ASH",
+"ASK", "AT", "ATE", "AUG", "AUK", "AVE", "AWE", "AWK",
+"AWL", "AWN", "AX", "AYE", "BAD", "BAG", "BAH", "BAM",
+"BAN", "BAR", "BAT", "BAY", "BE", "BED", "BEE", "BEG",
+"BEN", "BET", "BEY", "BIB", "BID", "BIG", "BIN", "BIT",
+"BOB", "BOG", "BON", "BOO", "BOP", "BOW", "BOY", "BUB",
+"BUD", "BUG", "BUM", "BUN", "BUS", "BUT", "BUY", "BY",
+"BYE", "CAB", "CAL", "CAM", "CAN", "CAP", "CAR", "CAT",
+"CAW", "COD", "COG", "COL", "CON", "COO", "COP", "COT",
+"COW", "COY", "CRY", "CUB", "CUE", "CUP", "CUR", "CUT",
+"DAB", "DAD", "DAM", "DAN", "DAR", "DAY", "DEE", "DEL",
+"DEN", "DES", "DEW", "DID", "DIE", "DIG", "DIN", "DIP",
+"DO", "DOE", "DOG", "DON", "DOT", "DOW", "DRY", "DUB",
+"DUD", "DUE", "DUG", "DUN", "EAR", "EAT", "ED", "EEL",
+"EGG", "EGO", "ELI", "ELK", "ELM", "ELY", "EM", "END",
+"EST", "ETC", "EVA", "EVE", "EWE", "EYE", "FAD", "FAN",
+"FAR", "FAT", "FAY", "FED", "FEE", "FEW", "FIB", "FIG",
+"FIN", "FIR", "FIT", "FLO", "FLY", "FOE", "FOG", "FOR",
+"FRY", "FUM", "FUN", "FUR", "GAB", "GAD", "GAG", "GAL",
+"GAM", "GAP", "GAS", "GAY", "GEE", "GEL", "GEM", "GET",
+"GIG", "GIL", "GIN", "GO", "GOT", "GUM", "GUN", "GUS",
+"GUT", "GUY", "GYM", "GYP", "HA", "HAD", "HAL", "HAM",
+"HAN", "HAP", "HAS", "HAT", "HAW", "HAY", "HE", "HEM",
+"HEN", "HER", "HEW", "HEY", "HI", "HID", "HIM", "HIP",
+"HIS", "HIT", "HO", "HOB", "HOC", "HOE", "HOG", "HOP",
+"HOT", "HOW", "HUB", "HUE", "HUG", "HUH", "HUM", "HUT",
+"I", "ICY", "IDA", "IF", "IKE", "ILL", "INK", "INN",
+"IO", "ION", "IQ", "IRA", "IRE", "IRK", "IS", "IT",
+"ITS", "IVY", "JAB", "JAG", "JAM", "JAN", "JAR", "JAW",
+"JAY", "JET", "JIG", "JIM", "JO", "JOB", "JOE", "JOG",
+"JOT", "JOY", "JUG", "JUT", "KAY", "KEG", "KEN", "KEY",
+"KID", "KIM", "KIN", "KIT", "LA", "LAB", "LAC", "LAD",
+"LAG", "LAM", "LAP", "LAW", "LAY", "LEA", "LED", "LEE",
+"LEG", "LEN", "LEO", "LET", "LEW", "LID", "LIE", "LIN",
+"LIP", "LIT", "LO", "LOB", "LOG", "LOP", "LOS", "LOT",
+"LOU", "LOW", "LOY", "LUG", "LYE", "MA", "MAC", "MAD",
+"MAE", "MAN", "MAO", "MAP", "MAT", "MAW", "MAY", "ME",
+"MEG", "MEL", "MEN", "MET", "MEW", "MID", "MIN", "MIT",
+"MOB", "MOD", "MOE", "MOO", "MOP", "MOS", "MOT", "MOW",
+"MUD", "MUG", "MUM", "MY", "NAB", "NAG", "NAN", "NAP",
+"NAT", "NAY", "NE", "NED", "NEE", "NET", "NEW", "NIB",
+"NIL", "NIP", "NIT", "NO", "NOB", "NOD", "NON", "NOR",
+"NOT", "NOV", "NOW", "NU", "NUN", "NUT", "O", "OAF",
+"OAK", "OAR", "OAT", "ODD", "ODE", "OF", "OFF", "OFT",
+"OH", "OIL", "OK", "OLD", "ON", "ONE", "OR", "ORB",
+"ORE", "ORR", "OS", "OTT", "OUR", "OUT", "OVA", "OW",
+"OWE", "OWL", "OWN", "OX", "PA", "PAD", "PAL", "PAM",
+"PAN", "PAP", "PAR", "PAT", "PAW", "PAY", "PEA", "PEG",
+"PEN", "PEP", "PER", "PET", "PEW", "PHI", "PI", "PIE",
+"PIN", "PIT", "PLY", "PO", "POD", "POE", "POP", "POT",
+"POW", "PRO", "PRY", "PUB", "PUG", "PUN", "PUP", "PUT",
+"QUO", "RAG", "RAM", "RAN", "RAP", "RAT", "RAW", "RAY",
+"REB", "RED", "REP", "RET", "RIB", "RID", "RIG", "RIM",
+"RIO", "RIP", "ROB", "ROD", "ROE", "RON", "ROT", "ROW",
+"ROY", "RUB", "RUE", "RUG", "RUM", "RUN", "RYE", "SAC",
+"SAD", "SAG", "SAL", "SAM", "SAN", "SAP", "SAT", "SAW",
+"SAY", "SEA", "SEC", "SEE", "SEN", "SET", "SEW", "SHE",
+"SHY", "SIN", "SIP", "SIR", "SIS", "SIT", "SKI", "SKY",
+"SLY", "SO", "SOB", "SOD", "SON", "SOP", "SOW", "SOY",
+"SPA", "SPY", "SUB", "SUD", "SUE", "SUM", "SUN", "SUP",
+"TAB", "TAD", "TAG", "TAN", "TAP", "TAR", "TEA", "TED",
+"TEE", "TEN", "THE", "THY", "TIC", "TIE", "TIM", "TIN",
+"TIP", "TO", "TOE", "TOG", "TOM", "TON", "TOO", "TOP",
+"TOW", "TOY", "TRY", "TUB", "TUG", "TUM", "TUN", "TWO",
+"UN", "UP", "US", "USE", "VAN", "VAT", "VET", "VIE",
+"WAD", "WAG", "WAR", "WAS", "WAY", "WE", "WEB", "WED",
+"WEE", "WET", "WHO", "WHY", "WIN", "WIT", "WOK", "WON",
+"WOO", "WOW", "WRY", "WU", "YAM", "YAP", "YAW", "YE",
+"YEA", "YES", "YET", "YOU", "ABED", "ABEL", "ABET", "ABLE",
+"ABUT", "ACHE", "ACID", "ACME", "ACRE", "ACTA", "ACTS", "ADAM",
+"ADDS", "ADEN", "AFAR", "AFRO", "AGEE", "AHEM", "AHOY", "AIDA",
+"AIDE", "AIDS", "AIRY", "AJAR", "AKIN", "ALAN", "ALEC", "ALGA",
+"ALIA", "ALLY", "ALMA", "ALOE", "ALSO", "ALTO", "ALUM", "ALVA",
+"AMEN", "AMES", "AMID", "AMMO", "AMOK", "AMOS", "AMRA", "ANDY",
+"ANEW", "ANNA", "ANNE", "ANTE", "ANTI", "AQUA", "ARAB", "ARCH",
+"AREA", "ARGO", "ARID", "ARMY", "ARTS", "ARTY", "ASIA", "ASKS",
+"ATOM", "AUNT", "AURA", "AUTO", "AVER", "AVID", "AVIS", "AVON",
+"AVOW", "AWAY", "AWRY", "BABE", "BABY", "BACH", "BACK", "BADE",
+"BAIL", "BAIT", "BAKE", "BALD", "BALE", "BALI", "BALK", "BALL",
+"BALM", "BAND", "BANE", "BANG", "BANK", "BARB", "BARD", "BARE",
+"BARK", "BARN", "BARR", "BASE", "BASH", "BASK", "BASS", "BATE",
+"BATH", "BAWD", "BAWL", "BEAD", "BEAK", "BEAM", "BEAN", "BEAR",
+"BEAT", "BEAU", "BECK", "BEEF", "BEEN", "BEER", "BEET", "BELA",
+"BELL", "BELT", "BEND", "BENT", "BERG", "BERN", "BERT", "BESS",
+"BEST", "BETA", "BETH", "BHOY", "BIAS", "BIDE", "BIEN", "BILE",
+"BILK", "BILL", "BIND", "BING", "BIRD", "BITE", "BITS", "BLAB",
+"BLAT", "BLED", "BLEW", "BLOB", "BLOC", "BLOT", "BLOW", "BLUE",
+"BLUM", "BLUR", "BOAR", "BOAT", "BOCA", "BOCK", "BODE", "BODY",
+"BOGY", "BOHR", "BOIL", "BOLD", "BOLO", "BOLT", "BOMB", "BONA",
+"BOND", "BONE", "BONG", "BONN", "BONY", "BOOK", "BOOM", "BOON",
+"BOOT", "BORE", "BORG", "BORN", "BOSE", "BOSS", "BOTH", "BOUT",
+"BOWL", "BOYD", "BRAD", "BRAE", "BRAG", "BRAN", "BRAY", "BRED",
+"BREW", "BRIG", "BRIM", "BROW", "BUCK", "BUDD", "BUFF", "BULB",
+"BULK", "BULL", "BUNK", "BUNT", "BUOY", "BURG", "BURL", "BURN",
+"BURR", "BURT", "BURY", "BUSH", "BUSS", "BUST", "BUSY", "BYTE",
+"CADY", "CAFE", "CAGE", "CAIN", "CAKE", "CALF", "CALL", "CALM",
+"CAME", "CANE", "CANT", "CARD", "CARE", "CARL", "CARR", "CART",
+"CASE", "CASH", "CASK", "CAST", "CAVE", "CEIL", "CELL", "CENT",
+"CERN", "CHAD", "CHAR", "CHAT", "CHAW", "CHEF", "CHEN", "CHEW",
+"CHIC", "CHIN", "CHOU", "CHOW", "CHUB", "CHUG", "CHUM", "CITE",
+"CITY", "CLAD", "CLAM", "CLAN", "CLAW", "CLAY", "CLOD", "CLOG",
+"CLOT", "CLUB", "CLUE", "COAL", "COAT", "COCA", "COCK", "COCO",
+"CODA", "CODE", "CODY", "COED", "COIL", "COIN", "COKE", "COLA",
+"COLD", "COLT", "COMA", "COMB", "COME", "COOK", "COOL", "COON",
+"COOT", "CORD", "CORE", "CORK", "CORN", "COST", "COVE", "COWL",
+"CRAB", "CRAG", "CRAM", "CRAY", "CREW", "CRIB", "CROW", "CRUD",
+"CUBA", "CUBE", "CUFF", "CULL", "CULT", "CUNY", "CURB", "CURD",
+"CURE", "CURL", "CURT", "CUTS", "DADE", "DALE", "DAME", "DANA",
+"DANE", "DANG", "DANK", "DARE", "DARK", "DARN", "DART", "DASH",
+"DATA", "DATE", "DAVE", "DAVY", "DAWN", "DAYS", "DEAD", "DEAF",
+"DEAL", "DEAN", "DEAR", "DEBT", "DECK", "DEED", "DEEM", "DEER",
+"DEFT", "DEFY", "DELL", "DENT", "DENY", "DESK", "DIAL", "DICE",
+"DIED", "DIET", "DIME", "DINE", "DING", "DINT", "DIRE", "DIRT",
+"DISC", "DISH", "DISK", "DIVE", "DOCK", "DOES", "DOLE", "DOLL",
+"DOLT", "DOME", "DONE", "DOOM", "DOOR", "DORA", "DOSE", "DOTE",
+"DOUG", "DOUR", "DOVE", "DOWN", "DRAB", "DRAG", "DRAM", "DRAW",
+"DREW", "DRUB", "DRUG", "DRUM", "DUAL", "DUCK", "DUCT", "DUEL",
+"DUET", "DUKE", "DULL", "DUMB", "DUNE", "DUNK", "DUSK", "DUST",
+"DUTY", "EACH", "EARL", "EARN", "EASE", "EAST", "EASY", "EBEN",
+"ECHO", "EDDY", "EDEN", "EDGE", "EDGY", "EDIT", "EDNA", "EGAN",
+"ELAN", "ELBA", "ELLA", "ELSE", "EMIL", "EMIT", "EMMA", "ENDS",
+"ERIC", "EROS", "EVEN", "EVER", "EVIL", "EYED", "FACE", "FACT",
+"FADE", "FAIL", "FAIN", "FAIR", "FAKE", "FALL", "FAME", "FANG",
+"FARM", "FAST", "FATE", "FAWN", "FEAR", "FEAT", "FEED", "FEEL",
+"FEET", "FELL", "FELT", "FEND", "FERN", "FEST", "FEUD", "FIEF",
+"FIGS", "FILE", "FILL", "FILM", "FIND", "FINE", "FINK", "FIRE",
+"FIRM", "FISH", "FISK", "FIST", "FITS", "FIVE", "FLAG", "FLAK",
+"FLAM", "FLAT", "FLAW", "FLEA", "FLED", "FLEW", "FLIT", "FLOC",
+"FLOG", "FLOW", "FLUB", "FLUE", "FOAL", "FOAM", "FOGY", "FOIL",
+"FOLD", "FOLK", "FOND", "FONT", "FOOD", "FOOL", "FOOT", "FORD",
+"FORE", "FORK", "FORM", "FORT", "FOSS", "FOUL", "FOUR", "FOWL",
+"FRAU", "FRAY", "FRED", "FREE", "FRET", "FREY", "FROG", "FROM",
+"FUEL", "FULL", "FUME", "FUND", "FUNK", "FURY", "FUSE", "FUSS",
+"GAFF", "GAGE", "GAIL", "GAIN", "GAIT", "GALA", "GALE", "GALL",
+"GALT", "GAME", "GANG", "GARB", "GARY", "GASH", "GATE", "GAUL",
+"GAUR", "GAVE", "GAWK", "GEAR", "GELD", "GENE", "GENT", "GERM",
+"GETS", "GIBE", "GIFT", "GILD", "GILL", "GILT", "GINA", "GIRD",
+"GIRL", "GIST", "GIVE", "GLAD", "GLEE", "GLEN", "GLIB", "GLOB",
+"GLOM", "GLOW", "GLUE", "GLUM", "GLUT", "GOAD", "GOAL", "GOAT",
+"GOER", "GOES", "GOLD", "GOLF", "GONE", "GONG", "GOOD", "GOOF",
+"GORE", "GORY", "GOSH", "GOUT", "GOWN", "GRAB", "GRAD", "GRAY",
+"GREG", "GREW", "GREY", "GRID", "GRIM", "GRIN", "GRIT", "GROW",
+"GRUB", "GULF", "GULL", "GUNK", "GURU", "GUSH", "GUST", "GWEN",
+"GWYN", "HAAG", "HAAS", "HACK", "HAIL", "HAIR", "HALE", "HALF",
+"HALL", "HALO", "HALT", "HAND", "HANG", "HANK", "HANS", "HARD",
+"HARK", "HARM", "HART", "HASH", "HAST", "HATE", "HATH", "HAUL",
+"HAVE", "HAWK", "HAYS", "HEAD", "HEAL", "HEAR", "HEAT", "HEBE",
+"HECK", "HEED", "HEEL", "HEFT", "HELD", "HELL", "HELM", "HERB",
+"HERD", "HERE", "HERO", "HERS", "HESS", "HEWN", "HICK", "HIDE",
+"HIGH", "HIKE", "HILL", "HILT", "HIND", "HINT", "HIRE", "HISS",
+"HIVE", "HOBO", "HOCK", "HOFF", "HOLD", "HOLE", "HOLM", "HOLT",
+"HOME", "HONE", "HONK", "HOOD", "HOOF", "HOOK", "HOOT", "HORN",
+"HOSE", "HOST", "HOUR", "HOVE", "HOWE", "HOWL", "HOYT", "HUCK",
+"HUED", "HUFF", "HUGE", "HUGH", "HUGO", "HULK", "HULL", "HUNK",
+"HUNT", "HURD", "HURL", "HURT", "HUSH", "HYDE", "HYMN", "IBIS",
+"ICON", "IDEA", "IDLE", "IFFY", "INCA", "INCH", "INTO", "IONS",
+"IOTA", "IOWA", "IRIS", "IRMA", "IRON", "ISLE", "ITCH", "ITEM",
+"IVAN", "JACK", "JADE", "JAIL", "JAKE", "JANE", "JAVA", "JEAN",
+"JEFF", "JERK", "JESS", "JEST", "JIBE", "JILL", "JILT", "JIVE",
+"JOAN", "JOBS", "JOCK", "JOEL", "JOEY", "JOHN", "JOIN", "JOKE",
+"JOLT", "JOVE", "JUDD", "JUDE", "JUDO", "JUDY", "JUJU", "JUKE",
+"JULY", "JUNE", "JUNK", "JUNO", "JURY", "JUST", "JUTE", "KAHN",
+"KALE", "KANE", "KANT", "KARL", "KATE", "KEEL", "KEEN", "KENO",
+"KENT", "KERN", "KERR", "KEYS", "KICK", "KILL", "KIND", "KING",
+"KIRK", "KISS", "KITE", "KLAN", "KNEE", "KNEW", "KNIT", "KNOB",
+"KNOT", "KNOW", "KOCH", "KONG", "KUDO", "KURD", "KURT", "KYLE",
+"LACE", "LACK", "LACY", "LADY", "LAID", "LAIN", "LAIR", "LAKE",
+"LAMB", "LAME", "LAND", "LANE", "LANG", "LARD", "LARK", "LASS",
+"LAST", "LATE", "LAUD", "LAVA", "LAWN", "LAWS", "LAYS", "LEAD",
+"LEAF", "LEAK", "LEAN", "LEAR", "LEEK", "LEER", "LEFT", "LEND",
+"LENS", "LENT", "LEON", "LESK", "LESS", "LEST", "LETS", "LIAR",
+"LICE", "LICK", "LIED", "LIEN", "LIES", "LIEU", "LIFE", "LIFT",
+"LIKE", "LILA", "LILT", "LILY", "LIMA", "LIMB", "LIME", "LIND",
+"LINE", "LINK", "LINT", "LION", "LISA", "LIST", "LIVE", "LOAD",
+"LOAF", "LOAM", "LOAN", "LOCK", "LOFT", "LOGE", "LOIS", "LOLA",
+"LONE", "LONG", "LOOK", "LOON", "LOOT", "LORD", "LORE", "LOSE",
+"LOSS", "LOST", "LOUD", "LOVE", "LOWE", "LUCK", "LUCY", "LUGE",
+"LUKE", "LULU", "LUND", "LUNG", "LURA", "LURE", "LURK", "LUSH",
+"LUST", "LYLE", "LYNN", "LYON", "LYRA", "MACE", "MADE", "MAGI",
+"MAID", "MAIL", "MAIN", "MAKE", "MALE", "MALI", "MALL", "MALT",
+"MANA", "MANN", "MANY", "MARC", "MARE", "MARK", "MARS", "MART",
+"MARY", "MASH", "MASK", "MASS", "MAST", "MATE", "MATH", "MAUL",
+"MAYO", "MEAD", "MEAL", "MEAN", "MEAT", "MEEK", "MEET", "MELD",
+"MELT", "MEMO", "MEND", "MENU", "MERT", "MESH", "MESS", "MICE",
+"MIKE", "MILD", "MILE", "MILK", "MILL", "MILT", "MIMI", "MIND",
+"MINE", "MINI", "MINK", "MINT", "MIRE", "MISS", "MIST", "MITE",
+"MITT", "MOAN", "MOAT", "MOCK", "MODE", "MOLD", "MOLE", "MOLL",
+"MOLT", "MONA", "MONK", "MONT", "MOOD", "MOON", "MOOR", "MOOT",
+"MORE", "MORN", "MORT", "MOSS", "MOST", "MOTH", "MOVE", "MUCH",
+"MUCK", "MUDD", "MUFF", "MULE", "MULL", "MURK", "MUSH", "MUST",
+"MUTE", "MUTT", "MYRA", "MYTH", "NAGY", "NAIL", "NAIR", "NAME",
+"NARY", "NASH", "NAVE", "NAVY", "NEAL", "NEAR", "NEAT", "NECK",
+"NEED", "NEIL", "NELL", "NEON", "NERO", "NESS", "NEST", "NEWS",
+"NEWT", "NIBS", "NICE", "NICK", "NILE", "NINA", "NINE", "NOAH",
+"NODE", "NOEL", "NOLL", "NONE", "NOOK", "NOON", "NORM", "NOSE",
+"NOTE", "NOUN", "NOVA", "NUDE", "NULL", "NUMB", "OATH", "OBEY",
+"OBOE", "ODIN", "OHIO", "OILY", "OINT", "OKAY", "OLAF", "OLDY",
+"OLGA", "OLIN", "OMAN", "OMEN", "OMIT", "ONCE", "ONES", "ONLY",
+"ONTO", "ONUS", "ORAL", "ORGY", "OSLO", "OTIS", "OTTO", "OUCH",
+"OUST", "OUTS", "OVAL", "OVEN", "OVER", "OWLY", "OWNS", "QUAD",
+"QUIT", "QUOD", "RACE", "RACK", "RACY", "RAFT", "RAGE", "RAID",
+"RAIL", "RAIN", "RAKE", "RANK", "RANT", "RARE", "RASH", "RATE",
+"RAVE", "RAYS", "READ", "REAL", "REAM", "REAR", "RECK", "REED",
+"REEF", "REEK", "REEL", "REID", "REIN", "RENA", "REND", "RENT",
+"REST", "RICE", "RICH", "RICK", "RIDE", "RIFT", "RILL", "RIME",
+"RING", "RINK", "RISE", "RISK", "RITE", "ROAD", "ROAM", "ROAR",
+"ROBE", "ROCK", "RODE", "ROIL", "ROLL", "ROME", "ROOD", "ROOF",
+"ROOK", "ROOM", "ROOT", "ROSA", "ROSE", "ROSS", "ROSY", "ROTH",
+"ROUT", "ROVE", "ROWE", "ROWS", "RUBE", "RUBY", "RUDE", "RUDY",
+"RUIN", "RULE", "RUNG", "RUNS", "RUNT", "RUSE", "RUSH", "RUSK",
+"RUSS", "RUST", "RUTH", "SACK", "SAFE", "SAGE", "SAID", "SAIL",
+"SALE", "SALK", "SALT", "SAME", "SAND", "SANE", "SANG", "SANK",
+"SARA", "SAUL", "SAVE", "SAYS", "SCAN", "SCAR", "SCAT", "SCOT",
+"SEAL", "SEAM", "SEAR", "SEAT", "SEED", "SEEK", "SEEM", "SEEN",
+"SEES", "SELF", "SELL", "SEND", "SENT", "SETS", "SEWN", "SHAG",
+"SHAM", "SHAW", "SHAY", "SHED", "SHIM", "SHIN", "SHOD", "SHOE",
+"SHOT", "SHOW", "SHUN", "SHUT", "SICK", "SIDE", "SIFT", "SIGH",
+"SIGN", "SILK", "SILL", "SILO", "SILT", "SINE", "SING", "SINK",
+"SIRE", "SITE", "SITS", "SITU", "SKAT", "SKEW", "SKID", "SKIM",
+"SKIN", "SKIT", "SLAB", "SLAM", "SLAT", "SLAY", "SLED", "SLEW",
+"SLID", "SLIM", "SLIT", "SLOB", "SLOG", "SLOT", "SLOW", "SLUG",
+"SLUM", "SLUR", "SMOG", "SMUG", "SNAG", "SNOB", "SNOW", "SNUB",
+"SNUG", "SOAK", "SOAR", "SOCK", "SODA", "SOFA", "SOFT", "SOIL",
+"SOLD", "SOME", "SONG", "SOON", "SOOT", "SORE", "SORT", "SOUL",
+"SOUR", "SOWN", "STAB", "STAG", "STAN", "STAR", "STAY", "STEM",
+"STEW", "STIR", "STOW", "STUB", "STUN", "SUCH", "SUDS", "SUIT",
+"SULK", "SUMS", "SUNG", "SUNK", "SURE", "SURF", "SWAB", "SWAG",
+"SWAM", "SWAN", "SWAT", "SWAY", "SWIM", "SWUM", "TACK", "TACT",
+"TAIL", "TAKE", "TALE", "TALK", "TALL", "TANK", "TASK", "TATE",
+"TAUT", "TEAL", "TEAM", "TEAR", "TECH", "TEEM", "TEEN", "TEET",
+"TELL", "TEND", "TENT", "TERM", "TERN", "TESS", "TEST", "THAN",
+"THAT", "THEE", "THEM", "THEN", "THEY", "THIN", "THIS", "THUD",
+"THUG", "TICK", "TIDE", "TIDY", "TIED", "TIER", "TILE", "TILL",
+"TILT", "TIME", "TINA", "TINE", "TINT", "TINY", "TIRE", "TOAD",
+"TOGO", "TOIL", "TOLD", "TOLL", "TONE", "TONG", "TONY", "TOOK",
+"TOOL", "TOOT", "TORE", "TORN", "TOTE", "TOUR", "TOUT", "TOWN",
+"TRAG", "TRAM", "TRAY", "TREE", "TREK", "TRIG", "TRIM", "TRIO",
+"TROD", "TROT", "TROY", "TRUE", "TUBA", "TUBE", "TUCK", "TUFT",
+"TUNA", "TUNE", "TUNG", "TURF", "TURN", "TUSK", "TWIG", "TWIN",
+"TWIT", "ULAN", "UNIT", "URGE", "USED", "USER", "USES", "UTAH",
+"VAIL", "VAIN", "VALE", "VARY", "VASE", "VAST", "VEAL", "VEDA",
+"VEIL", "VEIN", "VEND", "VENT", "VERB", "VERY", "VETO", "VICE",
+"VIEW", "VINE", "VISE", "VOID", "VOLT", "VOTE", "WACK", "WADE",
+"WAGE", "WAIL", "WAIT", "WAKE", "WALE", "WALK", "WALL", "WALT",
+"WAND", "WANE", "WANG", "WANT", "WARD", "WARM", "WARN", "WART",
+"WASH", "WAST", "WATS", "WATT", "WAVE", "WAVY", "WAYS", "WEAK",
+"WEAL", "WEAN", "WEAR", "WEED", "WEEK", "WEIR", "WELD", "WELL",
+"WELT", "WENT", "WERE", "WERT", "WEST", "WHAM", "WHAT", "WHEE",
+"WHEN", "WHET", "WHOA", "WHOM", "WICK", "WIFE", "WILD", "WILL",
+"WIND", "WINE", "WING", "WINK", "WINO", "WIRE", "WISE", "WISH",
+"WITH", "WOLF", "WONT", "WOOD", "WOOL", "WORD", "WORE", "WORK",
+"WORM", "WORN", "WOVE", "WRIT", "WYNN", "YALE", "YANG", "YANK",
+"YARD", "YARN", "YAWL", "YAWN", "YEAH", "YEAR", "YELL", "YOGA",
+"YOKE" };
+
+const struct e inv_std_dict[2048] = {
+{"A", 0},
+{"ABE", 1},
+{"ABED", 571},
+{"ABEL", 572},
+{"ABET", 573},
+{"ABLE", 574},
+{"ABUT", 575},
+{"ACE", 2},
+{"ACHE", 576},
+{"ACID", 577},
+{"ACME", 578},
+{"ACRE", 579},
+{"ACT", 3},
+{"ACTA", 580},
+{"ACTS", 581},
+{"AD", 4},
+{"ADA", 5},
+{"ADAM", 582},
+{"ADD", 6},
+{"ADDS", 583},
+{"ADEN", 584},
+{"AFAR", 585},
+{"AFRO", 586},
+{"AGEE", 587},
+{"AGO", 7},
+{"AHEM", 588},
+{"AHOY", 589},
+{"AID", 8},
+{"AIDA", 590},
+{"AIDE", 591},
+{"AIDS", 592},
+{"AIM", 9},
+{"AIR", 10},
+{"AIRY", 593},
+{"AJAR", 594},
+{"AKIN", 595},
+{"ALAN", 596},
+{"ALEC", 597},
+{"ALGA", 598},
+{"ALIA", 599},
+{"ALL", 11},
+{"ALLY", 600},
+{"ALMA", 601},
+{"ALOE", 602},
+{"ALP", 12},
+{"ALSO", 603},
+{"ALTO", 604},
+{"ALUM", 605},
+{"ALVA", 606},
+{"AM", 13},
+{"AMEN", 607},
+{"AMES", 608},
+{"AMID", 609},
+{"AMMO", 610},
+{"AMOK", 611},
+{"AMOS", 612},
+{"AMRA", 613},
+{"AMY", 14},
+{"AN", 15},
+{"ANA", 16},
+{"AND", 17},
+{"ANDY", 614},
+{"ANEW", 615},
+{"ANN", 18},
+{"ANNA", 616},
+{"ANNE", 617},
+{"ANT", 19},
+{"ANTE", 618},
+{"ANTI", 619},
+{"ANY", 20},
+{"APE", 21},
+{"APS", 22},
+{"APT", 23},
+{"AQUA", 620},
+{"ARAB", 621},
+{"ARC", 24},
+{"ARCH", 622},
+{"ARE", 25},
+{"AREA", 623},
+{"ARGO", 624},
+{"ARID", 625},
+{"ARK", 26},
+{"ARM", 27},
+{"ARMY", 626},
+{"ART", 28},
+{"ARTS", 627},
+{"ARTY", 628},
+{"AS", 29},
+{"ASH", 30},
+{"ASIA", 629},
+{"ASK", 31},
+{"ASKS", 630},
+{"AT", 32},
+{"ATE", 33},
+{"ATOM", 631},
+{"AUG", 34},
+{"AUK", 35},
+{"AUNT", 632},
+{"AURA", 633},
+{"AUTO", 634},
+{"AVE", 36},
+{"AVER", 635},
+{"AVID", 636},
+{"AVIS", 637},
+{"AVON", 638},
+{"AVOW", 639},
+{"AWAY", 640},
+{"AWE", 37},
+{"AWK", 38},
+{"AWL", 39},
+{"AWN", 40},
+{"AWRY", 641},
+{"AX", 41},
+{"AYE", 42},
+{"BABE", 642},
+{"BABY", 643},
+{"BACH", 644},
+{"BACK", 645},
+{"BAD", 43},
+{"BADE", 646},
+{"BAG", 44},
+{"BAH", 45},
+{"BAIL", 647},
+{"BAIT", 648},
+{"BAKE", 649},
+{"BALD", 650},
+{"BALE", 651},
+{"BALI", 652},
+{"BALK", 653},
+{"BALL", 654},
+{"BALM", 655},
+{"BAM", 46},
+{"BAN", 47},
+{"BAND", 656},
+{"BANE", 657},
+{"BANG", 658},
+{"BANK", 659},
+{"BAR", 48},
+{"BARB", 660},
+{"BARD", 661},
+{"BARE", 662},
+{"BARK", 663},
+{"BARN", 664},
+{"BARR", 665},
+{"BASE", 666},
+{"BASH", 667},
+{"BASK", 668},
+{"BASS", 669},
+{"BAT", 49},
+{"BATE", 670},
+{"BATH", 671},
+{"BAWD", 672},
+{"BAWL", 673},
+{"BAY", 50},
+{"BE", 51},
+{"BEAD", 674},
+{"BEAK", 675},
+{"BEAM", 676},
+{"BEAN", 677},
+{"BEAR", 678},
+{"BEAT", 679},
+{"BEAU", 680},
+{"BECK", 681},
+{"BED", 52},
+{"BEE", 53},
+{"BEEF", 682},
+{"BEEN", 683},
+{"BEER", 684},
+{"BEET", 685},
+{"BEG", 54},
+{"BELA", 686},
+{"BELL", 687},
+{"BELT", 688},
+{"BEN", 55},
+{"BEND", 689},
+{"BENT", 690},
+{"BERG", 691},
+{"BERN", 692},
+{"BERT", 693},
+{"BESS", 694},
+{"BEST", 695},
+{"BET", 56},
+{"BETA", 696},
+{"BETH", 697},
+{"BEY", 57},
+{"BHOY", 698},
+{"BIAS", 699},
+{"BIB", 58},
+{"BID", 59},
+{"BIDE", 700},
+{"BIEN", 701},
+{"BIG", 60},
+{"BILE", 702},
+{"BILK", 703},
+{"BILL", 704},
+{"BIN", 61},
+{"BIND", 705},
+{"BING", 706},
+{"BIRD", 707},
+{"BIT", 62},
+{"BITE", 708},
+{"BITS", 709},
+{"BLAB", 710},
+{"BLAT", 711},
+{"BLED", 712},
+{"BLEW", 713},
+{"BLOB", 714},
+{"BLOC", 715},
+{"BLOT", 716},
+{"BLOW", 717},
+{"BLUE", 718},
+{"BLUM", 719},
+{"BLUR", 720},
+{"BOAR", 721},
+{"BOAT", 722},
+{"BOB", 63},
+{"BOCA", 723},
+{"BOCK", 724},
+{"BODE", 725},
+{"BODY", 726},
+{"BOG", 64},
+{"BOGY", 727},
+{"BOHR", 728},
+{"BOIL", 729},
+{"BOLD", 730},
+{"BOLO", 731},
+{"BOLT", 732},
+{"BOMB", 733},
+{"BON", 65},
+{"BONA", 734},
+{"BOND", 735},
+{"BONE", 736},
+{"BONG", 737},
+{"BONN", 738},
+{"BONY", 739},
+{"BOO", 66},
+{"BOOK", 740},
+{"BOOM", 741},
+{"BOON", 742},
+{"BOOT", 743},
+{"BOP", 67},
+{"BORE", 744},
+{"BORG", 745},
+{"BORN", 746},
+{"BOSE", 747},
+{"BOSS", 748},
+{"BOTH", 749},
+{"BOUT", 750},
+{"BOW", 68},
+{"BOWL", 751},
+{"BOY", 69},
+{"BOYD", 752},
+{"BRAD", 753},
+{"BRAE", 754},
+{"BRAG", 755},
+{"BRAN", 756},
+{"BRAY", 757},
+{"BRED", 758},
+{"BREW", 759},
+{"BRIG", 760},
+{"BRIM", 761},
+{"BROW", 762},
+{"BUB", 70},
+{"BUCK", 763},
+{"BUD", 71},
+{"BUDD", 764},
+{"BUFF", 765},
+{"BUG", 72},
+{"BULB", 766},
+{"BULK", 767},
+{"BULL", 768},
+{"BUM", 73},
+{"BUN", 74},
+{"BUNK", 769},
+{"BUNT", 770},
+{"BUOY", 771},
+{"BURG", 772},
+{"BURL", 773},
+{"BURN", 774},
+{"BURR", 775},
+{"BURT", 776},
+{"BURY", 777},
+{"BUS", 75},
+{"BUSH", 778},
+{"BUSS", 779},
+{"BUST", 780},
+{"BUSY", 781},
+{"BUT", 76},
+{"BUY", 77},
+{"BY", 78},
+{"BYE", 79},
+{"BYTE", 782},
+{"CAB", 80},
+{"CADY", 783},
+{"CAFE", 784},
+{"CAGE", 785},
+{"CAIN", 786},
+{"CAKE", 787},
+{"CAL", 81},
+{"CALF", 788},
+{"CALL", 789},
+{"CALM", 790},
+{"CAM", 82},
+{"CAME", 791},
+{"CAN", 83},
+{"CANE", 792},
+{"CANT", 793},
+{"CAP", 84},
+{"CAR", 85},
+{"CARD", 794},
+{"CARE", 795},
+{"CARL", 796},
+{"CARR", 797},
+{"CART", 798},
+{"CASE", 799},
+{"CASH", 800},
+{"CASK", 801},
+{"CAST", 802},
+{"CAT", 86},
+{"CAVE", 803},
+{"CAW", 87},
+{"CEIL", 804},
+{"CELL", 805},
+{"CENT", 806},
+{"CERN", 807},
+{"CHAD", 808},
+{"CHAR", 809},
+{"CHAT", 810},
+{"CHAW", 811},
+{"CHEF", 812},
+{"CHEN", 813},
+{"CHEW", 814},
+{"CHIC", 815},
+{"CHIN", 816},
+{"CHOU", 817},
+{"CHOW", 818},
+{"CHUB", 819},
+{"CHUG", 820},
+{"CHUM", 821},
+{"CITE", 822},
+{"CITY", 823},
+{"CLAD", 824},
+{"CLAM", 825},
+{"CLAN", 826},
+{"CLAW", 827},
+{"CLAY", 828},
+{"CLOD", 829},
+{"CLOG", 830},
+{"CLOT", 831},
+{"CLUB", 832},
+{"CLUE", 833},
+{"COAL", 834},
+{"COAT", 835},
+{"COCA", 836},
+{"COCK", 837},
+{"COCO", 838},
+{"COD", 88},
+{"CODA", 839},
+{"CODE", 840},
+{"CODY", 841},
+{"COED", 842},
+{"COG", 89},
+{"COIL", 843},
+{"COIN", 844},
+{"COKE", 845},
+{"COL", 90},
+{"COLA", 846},
+{"COLD", 847},
+{"COLT", 848},
+{"COMA", 849},
+{"COMB", 850},
+{"COME", 851},
+{"CON", 91},
+{"COO", 92},
+{"COOK", 852},
+{"COOL", 853},
+{"COON", 854},
+{"COOT", 855},
+{"COP", 93},
+{"CORD", 856},
+{"CORE", 857},
+{"CORK", 858},
+{"CORN", 859},
+{"COST", 860},
+{"COT", 94},
+{"COVE", 861},
+{"COW", 95},
+{"COWL", 862},
+{"COY", 96},
+{"CRAB", 863},
+{"CRAG", 864},
+{"CRAM", 865},
+{"CRAY", 866},
+{"CREW", 867},
+{"CRIB", 868},
+{"CROW", 869},
+{"CRUD", 870},
+{"CRY", 97},
+{"CUB", 98},
+{"CUBA", 871},
+{"CUBE", 872},
+{"CUE", 99},
+{"CUFF", 873},
+{"CULL", 874},
+{"CULT", 875},
+{"CUNY", 876},
+{"CUP", 100},
+{"CUR", 101},
+{"CURB", 877},
+{"CURD", 878},
+{"CURE", 879},
+{"CURL", 880},
+{"CURT", 881},
+{"CUT", 102},
+{"CUTS", 882},
+{"DAB", 103},
+{"DAD", 104},
+{"DADE", 883},
+{"DALE", 884},
+{"DAM", 105},
+{"DAME", 885},
+{"DAN", 106},
+{"DANA", 886},
+{"DANE", 887},
+{"DANG", 888},
+{"DANK", 889},
+{"DAR", 107},
+{"DARE", 890},
+{"DARK", 891},
+{"DARN", 892},
+{"DART", 893},
+{"DASH", 894},
+{"DATA", 895},
+{"DATE", 896},
+{"DAVE", 897},
+{"DAVY", 898},
+{"DAWN", 899},
+{"DAY", 108},
+{"DAYS", 900},
+{"DEAD", 901},
+{"DEAF", 902},
+{"DEAL", 903},
+{"DEAN", 904},
+{"DEAR", 905},
+{"DEBT", 906},
+{"DECK", 907},
+{"DEE", 109},
+{"DEED", 908},
+{"DEEM", 909},
+{"DEER", 910},
+{"DEFT", 911},
+{"DEFY", 912},
+{"DEL", 110},
+{"DELL", 913},
+{"DEN", 111},
+{"DENT", 914},
+{"DENY", 915},
+{"DES", 112},
+{"DESK", 916},
+{"DEW", 113},
+{"DIAL", 917},
+{"DICE", 918},
+{"DID", 114},
+{"DIE", 115},
+{"DIED", 919},
+{"DIET", 920},
+{"DIG", 116},
+{"DIME", 921},
+{"DIN", 117},
+{"DINE", 922},
+{"DING", 923},
+{"DINT", 924},
+{"DIP", 118},
+{"DIRE", 925},
+{"DIRT", 926},
+{"DISC", 927},
+{"DISH", 928},
+{"DISK", 929},
+{"DIVE", 930},
+{"DO", 119},
+{"DOCK", 931},
+{"DOE", 120},
+{"DOES", 932},
+{"DOG", 121},
+{"DOLE", 933},
+{"DOLL", 934},
+{"DOLT", 935},
+{"DOME", 936},
+{"DON", 122},
+{"DONE", 937},
+{"DOOM", 938},
+{"DOOR", 939},
+{"DORA", 940},
+{"DOSE", 941},
+{"DOT", 123},
+{"DOTE", 942},
+{"DOUG", 943},
+{"DOUR", 944},
+{"DOVE", 945},
+{"DOW", 124},
+{"DOWN", 946},
+{"DRAB", 947},
+{"DRAG", 948},
+{"DRAM", 949},
+{"DRAW", 950},
+{"DREW", 951},
+{"DRUB", 952},
+{"DRUG", 953},
+{"DRUM", 954},
+{"DRY", 125},
+{"DUAL", 955},
+{"DUB", 126},
+{"DUCK", 956},
+{"DUCT", 957},
+{"DUD", 127},
+{"DUE", 128},
+{"DUEL", 958},
+{"DUET", 959},
+{"DUG", 129},
+{"DUKE", 960},
+{"DULL", 961},
+{"DUMB", 962},
+{"DUN", 130},
+{"DUNE", 963},
+{"DUNK", 964},
+{"DUSK", 965},
+{"DUST", 966},
+{"DUTY", 967},
+{"EACH", 968},
+{"EAR", 131},
+{"EARL", 969},
+{"EARN", 970},
+{"EASE", 971},
+{"EAST", 972},
+{"EASY", 973},
+{"EAT", 132},
+{"EBEN", 974},
+{"ECHO", 975},
+{"ED", 133},
+{"EDDY", 976},
+{"EDEN", 977},
+{"EDGE", 978},
+{"EDGY", 979},
+{"EDIT", 980},
+{"EDNA", 981},
+{"EEL", 134},
+{"EGAN", 982},
+{"EGG", 135},
+{"EGO", 136},
+{"ELAN", 983},
+{"ELBA", 984},
+{"ELI", 137},
+{"ELK", 138},
+{"ELLA", 985},
+{"ELM", 139},
+{"ELSE", 986},
+{"ELY", 140},
+{"EM", 141},
+{"EMIL", 987},
+{"EMIT", 988},
+{"EMMA", 989},
+{"END", 142},
+{"ENDS", 990},
+{"ERIC", 991},
+{"EROS", 992},
+{"EST", 143},
+{"ETC", 144},
+{"EVA", 145},
+{"EVE", 146},
+{"EVEN", 993},
+{"EVER", 994},
+{"EVIL", 995},
+{"EWE", 147},
+{"EYE", 148},
+{"EYED", 996},
+{"FACE", 997},
+{"FACT", 998},
+{"FAD", 149},
+{"FADE", 999},
+{"FAIL", 1000},
+{"FAIN", 1001},
+{"FAIR", 1002},
+{"FAKE", 1003},
+{"FALL", 1004},
+{"FAME", 1005},
+{"FAN", 150},
+{"FANG", 1006},
+{"FAR", 151},
+{"FARM", 1007},
+{"FAST", 1008},
+{"FAT", 152},
+{"FATE", 1009},
+{"FAWN", 1010},
+{"FAY", 153},
+{"FEAR", 1011},
+{"FEAT", 1012},
+{"FED", 154},
+{"FEE", 155},
+{"FEED", 1013},
+{"FEEL", 1014},
+{"FEET", 1015},
+{"FELL", 1016},
+{"FELT", 1017},
+{"FEND", 1018},
+{"FERN", 1019},
+{"FEST", 1020},
+{"FEUD", 1021},
+{"FEW", 156},
+{"FIB", 157},
+{"FIEF", 1022},
+{"FIG", 158},
+{"FIGS", 1023},
+{"FILE", 1024},
+{"FILL", 1025},
+{"FILM", 1026},
+{"FIN", 159},
+{"FIND", 1027},
+{"FINE", 1028},
+{"FINK", 1029},
+{"FIR", 160},
+{"FIRE", 1030},
+{"FIRM", 1031},
+{"FISH", 1032},
+{"FISK", 1033},
+{"FIST", 1034},
+{"FIT", 161},
+{"FITS", 1035},
+{"FIVE", 1036},
+{"FLAG", 1037},
+{"FLAK", 1038},
+{"FLAM", 1039},
+{"FLAT", 1040},
+{"FLAW", 1041},
+{"FLEA", 1042},
+{"FLED", 1043},
+{"FLEW", 1044},
+{"FLIT", 1045},
+{"FLO", 162},
+{"FLOC", 1046},
+{"FLOG", 1047},
+{"FLOW", 1048},
+{"FLUB", 1049},
+{"FLUE", 1050},
+{"FLY", 163},
+{"FOAL", 1051},
+{"FOAM", 1052},
+{"FOE", 164},
+{"FOG", 165},
+{"FOGY", 1053},
+{"FOIL", 1054},
+{"FOLD", 1055},
+{"FOLK", 1056},
+{"FOND", 1057},
+{"FONT", 1058},
+{"FOOD", 1059},
+{"FOOL", 1060},
+{"FOOT", 1061},
+{"FOR", 166},
+{"FORD", 1062},
+{"FORE", 1063},
+{"FORK", 1064},
+{"FORM", 1065},
+{"FORT", 1066},
+{"FOSS", 1067},
+{"FOUL", 1068},
+{"FOUR", 1069},
+{"FOWL", 1070},
+{"FRAU", 1071},
+{"FRAY", 1072},
+{"FRED", 1073},
+{"FREE", 1074},
+{"FRET", 1075},
+{"FREY", 1076},
+{"FROG", 1077},
+{"FROM", 1078},
+{"FRY", 167},
+{"FUEL", 1079},
+{"FULL", 1080},
+{"FUM", 168},
+{"FUME", 1081},
+{"FUN", 169},
+{"FUND", 1082},
+{"FUNK", 1083},
+{"FUR", 170},
+{"FURY", 1084},
+{"FUSE", 1085},
+{"FUSS", 1086},
+{"GAB", 171},
+{"GAD", 172},
+{"GAFF", 1087},
+{"GAG", 173},
+{"GAGE", 1088},
+{"GAIL", 1089},
+{"GAIN", 1090},
+{"GAIT", 1091},
+{"GAL", 174},
+{"GALA", 1092},
+{"GALE", 1093},
+{"GALL", 1094},
+{"GALT", 1095},
+{"GAM", 175},
+{"GAME", 1096},
+{"GANG", 1097},
+{"GAP", 176},
+{"GARB", 1098},
+{"GARY", 1099},
+{"GAS", 177},
+{"GASH", 1100},
+{"GATE", 1101},
+{"GAUL", 1102},
+{"GAUR", 1103},
+{"GAVE", 1104},
+{"GAWK", 1105},
+{"GAY", 178},
+{"GEAR", 1106},
+{"GEE", 179},
+{"GEL", 180},
+{"GELD", 1107},
+{"GEM", 181},
+{"GENE", 1108},
+{"GENT", 1109},
+{"GERM", 1110},
+{"GET", 182},
+{"GETS", 1111},
+{"GIBE", 1112},
+{"GIFT", 1113},
+{"GIG", 183},
+{"GIL", 184},
+{"GILD", 1114},
+{"GILL", 1115},
+{"GILT", 1116},
+{"GIN", 185},
+{"GINA", 1117},
+{"GIRD", 1118},
+{"GIRL", 1119},
+{"GIST", 1120},
+{"GIVE", 1121},
+{"GLAD", 1122},
+{"GLEE", 1123},
+{"GLEN", 1124},
+{"GLIB", 1125},
+{"GLOB", 1126},
+{"GLOM", 1127},
+{"GLOW", 1128},
+{"GLUE", 1129},
+{"GLUM", 1130},
+{"GLUT", 1131},
+{"GO", 186},
+{"GOAD", 1132},
+{"GOAL", 1133},
+{"GOAT", 1134},
+{"GOER", 1135},
+{"GOES", 1136},
+{"GOLD", 1137},
+{"GOLF", 1138},
+{"GONE", 1139},
+{"GONG", 1140},
+{"GOOD", 1141},
+{"GOOF", 1142},
+{"GORE", 1143},
+{"GORY", 1144},
+{"GOSH", 1145},
+{"GOT", 187},
+{"GOUT", 1146},
+{"GOWN", 1147},
+{"GRAB", 1148},
+{"GRAD", 1149},
+{"GRAY", 1150},
+{"GREG", 1151},
+{"GREW", 1152},
+{"GREY", 1153},
+{"GRID", 1154},
+{"GRIM", 1155},
+{"GRIN", 1156},
+{"GRIT", 1157},
+{"GROW", 1158},
+{"GRUB", 1159},
+{"GULF", 1160},
+{"GULL", 1161},
+{"GUM", 188},
+{"GUN", 189},
+{"GUNK", 1162},
+{"GURU", 1163},
+{"GUS", 190},
+{"GUSH", 1164},
+{"GUST", 1165},
+{"GUT", 191},
+{"GUY", 192},
+{"GWEN", 1166},
+{"GWYN", 1167},
+{"GYM", 193},
+{"GYP", 194},
+{"HA", 195},
+{"HAAG", 1168},
+{"HAAS", 1169},
+{"HACK", 1170},
+{"HAD", 196},
+{"HAIL", 1171},
+{"HAIR", 1172},
+{"HAL", 197},
+{"HALE", 1173},
+{"HALF", 1174},
+{"HALL", 1175},
+{"HALO", 1176},
+{"HALT", 1177},
+{"HAM", 198},
+{"HAN", 199},
+{"HAND", 1178},
+{"HANG", 1179},
+{"HANK", 1180},
+{"HANS", 1181},
+{"HAP", 200},
+{"HARD", 1182},
+{"HARK", 1183},
+{"HARM", 1184},
+{"HART", 1185},
+{"HAS", 201},
+{"HASH", 1186},
+{"HAST", 1187},
+{"HAT", 202},
+{"HATE", 1188},
+{"HATH", 1189},
+{"HAUL", 1190},
+{"HAVE", 1191},
+{"HAW", 203},
+{"HAWK", 1192},
+{"HAY", 204},
+{"HAYS", 1193},
+{"HE", 205},
+{"HEAD", 1194},
+{"HEAL", 1195},
+{"HEAR", 1196},
+{"HEAT", 1197},
+{"HEBE", 1198},
+{"HECK", 1199},
+{"HEED", 1200},
+{"HEEL", 1201},
+{"HEFT", 1202},
+{"HELD", 1203},
+{"HELL", 1204},
+{"HELM", 1205},
+{"HEM", 206},
+{"HEN", 207},
+{"HER", 208},
+{"HERB", 1206},
+{"HERD", 1207},
+{"HERE", 1208},
+{"HERO", 1209},
+{"HERS", 1210},
+{"HESS", 1211},
+{"HEW", 209},
+{"HEWN", 1212},
+{"HEY", 210},
+{"HI", 211},
+{"HICK", 1213},
+{"HID", 212},
+{"HIDE", 1214},
+{"HIGH", 1215},
+{"HIKE", 1216},
+{"HILL", 1217},
+{"HILT", 1218},
+{"HIM", 213},
+{"HIND", 1219},
+{"HINT", 1220},
+{"HIP", 214},
+{"HIRE", 1221},
+{"HIS", 215},
+{"HISS", 1222},
+{"HIT", 216},
+{"HIVE", 1223},
+{"HO", 217},
+{"HOB", 218},
+{"HOBO", 1224},
+{"HOC", 219},
+{"HOCK", 1225},
+{"HOE", 220},
+{"HOFF", 1226},
+{"HOG", 221},
+{"HOLD", 1227},
+{"HOLE", 1228},
+{"HOLM", 1229},
+{"HOLT", 1230},
+{"HOME", 1231},
+{"HONE", 1232},
+{"HONK", 1233},
+{"HOOD", 1234},
+{"HOOF", 1235},
+{"HOOK", 1236},
+{"HOOT", 1237},
+{"HOP", 222},
+{"HORN", 1238},
+{"HOSE", 1239},
+{"HOST", 1240},
+{"HOT", 223},
+{"HOUR", 1241},
+{"HOVE", 1242},
+{"HOW", 224},
+{"HOWE", 1243},
+{"HOWL", 1244},
+{"HOYT", 1245},
+{"HUB", 225},
+{"HUCK", 1246},
+{"HUE", 226},
+{"HUED", 1247},
+{"HUFF", 1248},
+{"HUG", 227},
+{"HUGE", 1249},
+{"HUGH", 1250},
+{"HUGO", 1251},
+{"HUH", 228},
+{"HULK", 1252},
+{"HULL", 1253},
+{"HUM", 229},
+{"HUNK", 1254},
+{"HUNT", 1255},
+{"HURD", 1256},
+{"HURL", 1257},
+{"HURT", 1258},
+{"HUSH", 1259},
+{"HUT", 230},
+{"HYDE", 1260},
+{"HYMN", 1261},
+{"I", 231},
+{"IBIS", 1262},
+{"ICON", 1263},
+{"ICY", 232},
+{"IDA", 233},
+{"IDEA", 1264},
+{"IDLE", 1265},
+{"IF", 234},
+{"IFFY", 1266},
+{"IKE", 235},
+{"ILL", 236},
+{"INCA", 1267},
+{"INCH", 1268},
+{"INK", 237},
+{"INN", 238},
+{"INTO", 1269},
+{"IO", 239},
+{"ION", 240},
+{"IONS", 1270},
+{"IOTA", 1271},
+{"IOWA", 1272},
+{"IQ", 241},
+{"IRA", 242},
+{"IRE", 243},
+{"IRIS", 1273},
+{"IRK", 244},
+{"IRMA", 1274},
+{"IRON", 1275},
+{"IS", 245},
+{"ISLE", 1276},
+{"IT", 246},
+{"ITCH", 1277},
+{"ITEM", 1278},
+{"ITS", 247},
+{"IVAN", 1279},
+{"IVY", 248},
+{"JAB", 249},
+{"JACK", 1280},
+{"JADE", 1281},
+{"JAG", 250},
+{"JAIL", 1282},
+{"JAKE", 1283},
+{"JAM", 251},
+{"JAN", 252},
+{"JANE", 1284},
+{"JAR", 253},
+{"JAVA", 1285},
+{"JAW", 254},
+{"JAY", 255},
+{"JEAN", 1286},
+{"JEFF", 1287},
+{"JERK", 1288},
+{"JESS", 1289},
+{"JEST", 1290},
+{"JET", 256},
+{"JIBE", 1291},
+{"JIG", 257},
+{"JILL", 1292},
+{"JILT", 1293},
+{"JIM", 258},
+{"JIVE", 1294},
+{"JO", 259},
+{"JOAN", 1295},
+{"JOB", 260},
+{"JOBS", 1296},
+{"JOCK", 1297},
+{"JOE", 261},
+{"JOEL", 1298},
+{"JOEY", 1299},
+{"JOG", 262},
+{"JOHN", 1300},
+{"JOIN", 1301},
+{"JOKE", 1302},
+{"JOLT", 1303},
+{"JOT", 263},
+{"JOVE", 1304},
+{"JOY", 264},
+{"JUDD", 1305},
+{"JUDE", 1306},
+{"JUDO", 1307},
+{"JUDY", 1308},
+{"JUG", 265},
+{"JUJU", 1309},
+{"JUKE", 1310},
+{"JULY", 1311},
+{"JUNE", 1312},
+{"JUNK", 1313},
+{"JUNO", 1314},
+{"JURY", 1315},
+{"JUST", 1316},
+{"JUT", 266},
+{"JUTE", 1317},
+{"KAHN", 1318},
+{"KALE", 1319},
+{"KANE", 1320},
+{"KANT", 1321},
+{"KARL", 1322},
+{"KATE", 1323},
+{"KAY", 267},
+{"KEEL", 1324},
+{"KEEN", 1325},
+{"KEG", 268},
+{"KEN", 269},
+{"KENO", 1326},
+{"KENT", 1327},
+{"KERN", 1328},
+{"KERR", 1329},
+{"KEY", 270},
+{"KEYS", 1330},
+{"KICK", 1331},
+{"KID", 271},
+{"KILL", 1332},
+{"KIM", 272},
+{"KIN", 273},
+{"KIND", 1333},
+{"KING", 1334},
+{"KIRK", 1335},
+{"KISS", 1336},
+{"KIT", 274},
+{"KITE", 1337},
+{"KLAN", 1338},
+{"KNEE", 1339},
+{"KNEW", 1340},
+{"KNIT", 1341},
+{"KNOB", 1342},
+{"KNOT", 1343},
+{"KNOW", 1344},
+{"KOCH", 1345},
+{"KONG", 1346},
+{"KUDO", 1347},
+{"KURD", 1348},
+{"KURT", 1349},
+{"KYLE", 1350},
+{"LA", 275},
+{"LAB", 276},
+{"LAC", 277},
+{"LACE", 1351},
+{"LACK", 1352},
+{"LACY", 1353},
+{"LAD", 278},
+{"LADY", 1354},
+{"LAG", 279},
+{"LAID", 1355},
+{"LAIN", 1356},
+{"LAIR", 1357},
+{"LAKE", 1358},
+{"LAM", 280},
+{"LAMB", 1359},
+{"LAME", 1360},
+{"LAND", 1361},
+{"LANE", 1362},
+{"LANG", 1363},
+{"LAP", 281},
+{"LARD", 1364},
+{"LARK", 1365},
+{"LASS", 1366},
+{"LAST", 1367},
+{"LATE", 1368},
+{"LAUD", 1369},
+{"LAVA", 1370},
+{"LAW", 282},
+{"LAWN", 1371},
+{"LAWS", 1372},
+{"LAY", 283},
+{"LAYS", 1373},
+{"LEA", 284},
+{"LEAD", 1374},
+{"LEAF", 1375},
+{"LEAK", 1376},
+{"LEAN", 1377},
+{"LEAR", 1378},
+{"LED", 285},
+{"LEE", 286},
+{"LEEK", 1379},
+{"LEER", 1380},
+{"LEFT", 1381},
+{"LEG", 287},
+{"LEN", 288},
+{"LEND", 1382},
+{"LENS", 1383},
+{"LENT", 1384},
+{"LEO", 289},
+{"LEON", 1385},
+{"LESK", 1386},
+{"LESS", 1387},
+{"LEST", 1388},
+{"LET", 290},
+{"LETS", 1389},
+{"LEW", 291},
+{"LIAR", 1390},
+{"LICE", 1391},
+{"LICK", 1392},
+{"LID", 292},
+{"LIE", 293},
+{"LIED", 1393},
+{"LIEN", 1394},
+{"LIES", 1395},
+{"LIEU", 1396},
+{"LIFE", 1397},
+{"LIFT", 1398},
+{"LIKE", 1399},
+{"LILA", 1400},
+{"LILT", 1401},
+{"LILY", 1402},
+{"LIMA", 1403},
+{"LIMB", 1404},
+{"LIME", 1405},
+{"LIN", 294},
+{"LIND", 1406},
+{"LINE", 1407},
+{"LINK", 1408},
+{"LINT", 1409},
+{"LION", 1410},
+{"LIP", 295},
+{"LISA", 1411},
+{"LIST", 1412},
+{"LIT", 296},
+{"LIVE", 1413},
+{"LO", 297},
+{"LOAD", 1414},
+{"LOAF", 1415},
+{"LOAM", 1416},
+{"LOAN", 1417},
+{"LOB", 298},
+{"LOCK", 1418},
+{"LOFT", 1419},
+{"LOG", 299},
+{"LOGE", 1420},
+{"LOIS", 1421},
+{"LOLA", 1422},
+{"LONE", 1423},
+{"LONG", 1424},
+{"LOOK", 1425},
+{"LOON", 1426},
+{"LOOT", 1427},
+{"LOP", 300},
+{"LORD", 1428},
+{"LORE", 1429},
+{"LOS", 301},
+{"LOSE", 1430},
+{"LOSS", 1431},
+{"LOST", 1432},
+{"LOT", 302},
+{"LOU", 303},
+{"LOUD", 1433},
+{"LOVE", 1434},
+{"LOW", 304},
+{"LOWE", 1435},
+{"LOY", 305},
+{"LUCK", 1436},
+{"LUCY", 1437},
+{"LUG", 306},
+{"LUGE", 1438},
+{"LUKE", 1439},
+{"LULU", 1440},
+{"LUND", 1441},
+{"LUNG", 1442},
+{"LURA", 1443},
+{"LURE", 1444},
+{"LURK", 1445},
+{"LUSH", 1446},
+{"LUST", 1447},
+{"LYE", 307},
+{"LYLE", 1448},
+{"LYNN", 1449},
+{"LYON", 1450},
+{"LYRA", 1451},
+{"MA", 308},
+{"MAC", 309},
+{"MACE", 1452},
+{"MAD", 310},
+{"MADE", 1453},
+{"MAE", 311},
+{"MAGI", 1454},
+{"MAID", 1455},
+{"MAIL", 1456},
+{"MAIN", 1457},
+{"MAKE", 1458},
+{"MALE", 1459},
+{"MALI", 1460},
+{"MALL", 1461},
+{"MALT", 1462},
+{"MAN", 312},
+{"MANA", 1463},
+{"MANN", 1464},
+{"MANY", 1465},
+{"MAO", 313},
+{"MAP", 314},
+{"MARC", 1466},
+{"MARE", 1467},
+{"MARK", 1468},
+{"MARS", 1469},
+{"MART", 1470},
+{"MARY", 1471},
+{"MASH", 1472},
+{"MASK", 1473},
+{"MASS", 1474},
+{"MAST", 1475},
+{"MAT", 315},
+{"MATE", 1476},
+{"MATH", 1477},
+{"MAUL", 1478},
+{"MAW", 316},
+{"MAY", 317},
+{"MAYO", 1479},
+{"ME", 318},
+{"MEAD", 1480},
+{"MEAL", 1481},
+{"MEAN", 1482},
+{"MEAT", 1483},
+{"MEEK", 1484},
+{"MEET", 1485},
+{"MEG", 319},
+{"MEL", 320},
+{"MELD", 1486},
+{"MELT", 1487},
+{"MEMO", 1488},
+{"MEN", 321},
+{"MEND", 1489},
+{"MENU", 1490},
+{"MERT", 1491},
+{"MESH", 1492},
+{"MESS", 1493},
+{"MET", 322},
+{"MEW", 323},
+{"MICE", 1494},
+{"MID", 324},
+{"MIKE", 1495},
+{"MILD", 1496},
+{"MILE", 1497},
+{"MILK", 1498},
+{"MILL", 1499},
+{"MILT", 1500},
+{"MIMI", 1501},
+{"MIN", 325},
+{"MIND", 1502},
+{"MINE", 1503},
+{"MINI", 1504},
+{"MINK", 1505},
+{"MINT", 1506},
+{"MIRE", 1507},
+{"MISS", 1508},
+{"MIST", 1509},
+{"MIT", 326},
+{"MITE", 1510},
+{"MITT", 1511},
+{"MOAN", 1512},
+{"MOAT", 1513},
+{"MOB", 327},
+{"MOCK", 1514},
+{"MOD", 328},
+{"MODE", 1515},
+{"MOE", 329},
+{"MOLD", 1516},
+{"MOLE", 1517},
+{"MOLL", 1518},
+{"MOLT", 1519},
+{"MONA", 1520},
+{"MONK", 1521},
+{"MONT", 1522},
+{"MOO", 330},
+{"MOOD", 1523},
+{"MOON", 1524},
+{"MOOR", 1525},
+{"MOOT", 1526},
+{"MOP", 331},
+{"MORE", 1527},
+{"MORN", 1528},
+{"MORT", 1529},
+{"MOS", 332},
+{"MOSS", 1530},
+{"MOST", 1531},
+{"MOT", 333},
+{"MOTH", 1532},
+{"MOVE", 1533},
+{"MOW", 334},
+{"MUCH", 1534},
+{"MUCK", 1535},
+{"MUD", 335},
+{"MUDD", 1536},
+{"MUFF", 1537},
+{"MUG", 336},
+{"MULE", 1538},
+{"MULL", 1539},
+{"MUM", 337},
+{"MURK", 1540},
+{"MUSH", 1541},
+{"MUST", 1542},
+{"MUTE", 1543},
+{"MUTT", 1544},
+{"MY", 338},
+{"MYRA", 1545},
+{"MYTH", 1546},
+{"NAB", 339},
+{"NAG", 340},
+{"NAGY", 1547},
+{"NAIL", 1548},
+{"NAIR", 1549},
+{"NAME", 1550},
+{"NAN", 341},
+{"NAP", 342},
+{"NARY", 1551},
+{"NASH", 1552},
+{"NAT", 343},
+{"NAVE", 1553},
+{"NAVY", 1554},
+{"NAY", 344},
+{"NE", 345},
+{"NEAL", 1555},
+{"NEAR", 1556},
+{"NEAT", 1557},
+{"NECK", 1558},
+{"NED", 346},
+{"NEE", 347},
+{"NEED", 1559},
+{"NEIL", 1560},
+{"NELL", 1561},
+{"NEON", 1562},
+{"NERO", 1563},
+{"NESS", 1564},
+{"NEST", 1565},
+{"NET", 348},
+{"NEW", 349},
+{"NEWS", 1566},
+{"NEWT", 1567},
+{"NIB", 350},
+{"NIBS", 1568},
+{"NICE", 1569},
+{"NICK", 1570},
+{"NIL", 351},
+{"NILE", 1571},
+{"NINA", 1572},
+{"NINE", 1573},
+{"NIP", 352},
+{"NIT", 353},
+{"NO", 354},
+{"NOAH", 1574},
+{"NOB", 355},
+{"NOD", 356},
+{"NODE", 1575},
+{"NOEL", 1576},
+{"NOLL", 1577},
+{"NON", 357},
+{"NONE", 1578},
+{"NOOK", 1579},
+{"NOON", 1580},
+{"NOR", 358},
+{"NORM", 1581},
+{"NOSE", 1582},
+{"NOT", 359},
+{"NOTE", 1583},
+{"NOUN", 1584},
+{"NOV", 360},
+{"NOVA", 1585},
+{"NOW", 361},
+{"NU", 362},
+{"NUDE", 1586},
+{"NULL", 1587},
+{"NUMB", 1588},
+{"NUN", 363},
+{"NUT", 364},
+{"O", 365},
+{"OAF", 366},
+{"OAK", 367},
+{"OAR", 368},
+{"OAT", 369},
+{"OATH", 1589},
+{"OBEY", 1590},
+{"OBOE", 1591},
+{"ODD", 370},
+{"ODE", 371},
+{"ODIN", 1592},
+{"OF", 372},
+{"OFF", 373},
+{"OFT", 374},
+{"OH", 375},
+{"OHIO", 1593},
+{"OIL", 376},
+{"OILY", 1594},
+{"OINT", 1595},
+{"OK", 377},
+{"OKAY", 1596},
+{"OLAF", 1597},
+{"OLD", 378},
+{"OLDY", 1598},
+{"OLGA", 1599},
+{"OLIN", 1600},
+{"OMAN", 1601},
+{"OMEN", 1602},
+{"OMIT", 1603},
+{"ON", 379},
+{"ONCE", 1604},
+{"ONE", 380},
+{"ONES", 1605},
+{"ONLY", 1606},
+{"ONTO", 1607},
+{"ONUS", 1608},
+{"OR", 381},
+{"ORAL", 1609},
+{"ORB", 382},
+{"ORE", 383},
+{"ORGY", 1610},
+{"ORR", 384},
+{"OS", 385},
+{"OSLO", 1611},
+{"OTIS", 1612},
+{"OTT", 386},
+{"OTTO", 1613},
+{"OUCH", 1614},
+{"OUR", 387},
+{"OUST", 1615},
+{"OUT", 388},
+{"OUTS", 1616},
+{"OVA", 389},
+{"OVAL", 1617},
+{"OVEN", 1618},
+{"OVER", 1619},
+{"OW", 390},
+{"OWE", 391},
+{"OWL", 392},
+{"OWLY", 1620},
+{"OWN", 393},
+{"OWNS", 1621},
+{"OX", 394},
+{"PA", 395},
+{"PAD", 396},
+{"PAL", 397},
+{"PAM", 398},
+{"PAN", 399},
+{"PAP", 400},
+{"PAR", 401},
+{"PAT", 402},
+{"PAW", 403},
+{"PAY", 404},
+{"PEA", 405},
+{"PEG", 406},
+{"PEN", 407},
+{"PEP", 408},
+{"PER", 409},
+{"PET", 410},
+{"PEW", 411},
+{"PHI", 412},
+{"PI", 413},
+{"PIE", 414},
+{"PIN", 415},
+{"PIT", 416},
+{"PLY", 417},
+{"PO", 418},
+{"POD", 419},
+{"POE", 420},
+{"POP", 421},
+{"POT", 422},
+{"POW", 423},
+{"PRO", 424},
+{"PRY", 425},
+{"PUB", 426},
+{"PUG", 427},
+{"PUN", 428},
+{"PUP", 429},
+{"PUT", 430},
+{"QUAD", 1622},
+{"QUIT", 1623},
+{"QUO", 431},
+{"QUOD", 1624},
+{"RACE", 1625},
+{"RACK", 1626},
+{"RACY", 1627},
+{"RAFT", 1628},
+{"RAG", 432},
+{"RAGE", 1629},
+{"RAID", 1630},
+{"RAIL", 1631},
+{"RAIN", 1632},
+{"RAKE", 1633},
+{"RAM", 433},
+{"RAN", 434},
+{"RANK", 1634},
+{"RANT", 1635},
+{"RAP", 435},
+{"RARE", 1636},
+{"RASH", 1637},
+{"RAT", 436},
+{"RATE", 1638},
+{"RAVE", 1639},
+{"RAW", 437},
+{"RAY", 438},
+{"RAYS", 1640},
+{"READ", 1641},
+{"REAL", 1642},
+{"REAM", 1643},
+{"REAR", 1644},
+{"REB", 439},
+{"RECK", 1645},
+{"RED", 440},
+{"REED", 1646},
+{"REEF", 1647},
+{"REEK", 1648},
+{"REEL", 1649},
+{"REID", 1650},
+{"REIN", 1651},
+{"RENA", 1652},
+{"REND", 1653},
+{"RENT", 1654},
+{"REP", 441},
+{"REST", 1655},
+{"RET", 442},
+{"RIB", 443},
+{"RICE", 1656},
+{"RICH", 1657},
+{"RICK", 1658},
+{"RID", 444},
+{"RIDE", 1659},
+{"RIFT", 1660},
+{"RIG", 445},
+{"RILL", 1661},
+{"RIM", 446},
+{"RIME", 1662},
+{"RING", 1663},
+{"RINK", 1664},
+{"RIO", 447},
+{"RIP", 448},
+{"RISE", 1665},
+{"RISK", 1666},
+{"RITE", 1667},
+{"ROAD", 1668},
+{"ROAM", 1669},
+{"ROAR", 1670},
+{"ROB", 449},
+{"ROBE", 1671},
+{"ROCK", 1672},
+{"ROD", 450},
+{"RODE", 1673},
+{"ROE", 451},
+{"ROIL", 1674},
+{"ROLL", 1675},
+{"ROME", 1676},
+{"RON", 452},
+{"ROOD", 1677},
+{"ROOF", 1678},
+{"ROOK", 1679},
+{"ROOM", 1680},
+{"ROOT", 1681},
+{"ROSA", 1682},
+{"ROSE", 1683},
+{"ROSS", 1684},
+{"ROSY", 1685},
+{"ROT", 453},
+{"ROTH", 1686},
+{"ROUT", 1687},
+{"ROVE", 1688},
+{"ROW", 454},
+{"ROWE", 1689},
+{"ROWS", 1690},
+{"ROY", 455},
+{"RUB", 456},
+{"RUBE", 1691},
+{"RUBY", 1692},
+{"RUDE", 1693},
+{"RUDY", 1694},
+{"RUE", 457},
+{"RUG", 458},
+{"RUIN", 1695},
+{"RULE", 1696},
+{"RUM", 459},
+{"RUN", 460},
+{"RUNG", 1697},
+{"RUNS", 1698},
+{"RUNT", 1699},
+{"RUSE", 1700},
+{"RUSH", 1701},
+{"RUSK", 1702},
+{"RUSS", 1703},
+{"RUST", 1704},
+{"RUTH", 1705},
+{"RYE", 461},
+{"SAC", 462},
+{"SACK", 1706},
+{"SAD", 463},
+{"SAFE", 1707},
+{"SAG", 464},
+{"SAGE", 1708},
+{"SAID", 1709},
+{"SAIL", 1710},
+{"SAL", 465},
+{"SALE", 1711},
+{"SALK", 1712},
+{"SALT", 1713},
+{"SAM", 466},
+{"SAME", 1714},
+{"SAN", 467},
+{"SAND", 1715},
+{"SANE", 1716},
+{"SANG", 1717},
+{"SANK", 1718},
+{"SAP", 468},
+{"SARA", 1719},
+{"SAT", 469},
+{"SAUL", 1720},
+{"SAVE", 1721},
+{"SAW", 470},
+{"SAY", 471},
+{"SAYS", 1722},
+{"SCAN", 1723},
+{"SCAR", 1724},
+{"SCAT", 1725},
+{"SCOT", 1726},
+{"SEA", 472},
+{"SEAL", 1727},
+{"SEAM", 1728},
+{"SEAR", 1729},
+{"SEAT", 1730},
+{"SEC", 473},
+{"SEE", 474},
+{"SEED", 1731},
+{"SEEK", 1732},
+{"SEEM", 1733},
+{"SEEN", 1734},
+{"SEES", 1735},
+{"SELF", 1736},
+{"SELL", 1737},
+{"SEN", 475},
+{"SEND", 1738},
+{"SENT", 1739},
+{"SET", 476},
+{"SETS", 1740},
+{"SEW", 477},
+{"SEWN", 1741},
+{"SHAG", 1742},
+{"SHAM", 1743},
+{"SHAW", 1744},
+{"SHAY", 1745},
+{"SHE", 478},
+{"SHED", 1746},
+{"SHIM", 1747},
+{"SHIN", 1748},
+{"SHOD", 1749},
+{"SHOE", 1750},
+{"SHOT", 1751},
+{"SHOW", 1752},
+{"SHUN", 1753},
+{"SHUT", 1754},
+{"SHY", 479},
+{"SICK", 1755},
+{"SIDE", 1756},
+{"SIFT", 1757},
+{"SIGH", 1758},
+{"SIGN", 1759},
+{"SILK", 1760},
+{"SILL", 1761},
+{"SILO", 1762},
+{"SILT", 1763},
+{"SIN", 480},
+{"SINE", 1764},
+{"SING", 1765},
+{"SINK", 1766},
+{"SIP", 481},
+{"SIR", 482},
+{"SIRE", 1767},
+{"SIS", 483},
+{"SIT", 484},
+{"SITE", 1768},
+{"SITS", 1769},
+{"SITU", 1770},
+{"SKAT", 1771},
+{"SKEW", 1772},
+{"SKI", 485},
+{"SKID", 1773},
+{"SKIM", 1774},
+{"SKIN", 1775},
+{"SKIT", 1776},
+{"SKY", 486},
+{"SLAB", 1777},
+{"SLAM", 1778},
+{"SLAT", 1779},
+{"SLAY", 1780},
+{"SLED", 1781},
+{"SLEW", 1782},
+{"SLID", 1783},
+{"SLIM", 1784},
+{"SLIT", 1785},
+{"SLOB", 1786},
+{"SLOG", 1787},
+{"SLOT", 1788},
+{"SLOW", 1789},
+{"SLUG", 1790},
+{"SLUM", 1791},
+{"SLUR", 1792},
+{"SLY", 487},
+{"SMOG", 1793},
+{"SMUG", 1794},
+{"SNAG", 1795},
+{"SNOB", 1796},
+{"SNOW", 1797},
+{"SNUB", 1798},
+{"SNUG", 1799},
+{"SO", 488},
+{"SOAK", 1800},
+{"SOAR", 1801},
+{"SOB", 489},
+{"SOCK", 1802},
+{"SOD", 490},
+{"SODA", 1803},
+{"SOFA", 1804},
+{"SOFT", 1805},
+{"SOIL", 1806},
+{"SOLD", 1807},
+{"SOME", 1808},
+{"SON", 491},
+{"SONG", 1809},
+{"SOON", 1810},
+{"SOOT", 1811},
+{"SOP", 492},
+{"SORE", 1812},
+{"SORT", 1813},
+{"SOUL", 1814},
+{"SOUR", 1815},
+{"SOW", 493},
+{"SOWN", 1816},
+{"SOY", 494},
+{"SPA", 495},
+{"SPY", 496},
+{"STAB", 1817},
+{"STAG", 1818},
+{"STAN", 1819},
+{"STAR", 1820},
+{"STAY", 1821},
+{"STEM", 1822},
+{"STEW", 1823},
+{"STIR", 1824},
+{"STOW", 1825},
+{"STUB", 1826},
+{"STUN", 1827},
+{"SUB", 497},
+{"SUCH", 1828},
+{"SUD", 498},
+{"SUDS", 1829},
+{"SUE", 499},
+{"SUIT", 1830},
+{"SULK", 1831},
+{"SUM", 500},
+{"SUMS", 1832},
+{"SUN", 501},
+{"SUNG", 1833},
+{"SUNK", 1834},
+{"SUP", 502},
+{"SURE", 1835},
+{"SURF", 1836},
+{"SWAB", 1837},
+{"SWAG", 1838},
+{"SWAM", 1839},
+{"SWAN", 1840},
+{"SWAT", 1841},
+{"SWAY", 1842},
+{"SWIM", 1843},
+{"SWUM", 1844},
+{"TAB", 503},
+{"TACK", 1845},
+{"TACT", 1846},
+{"TAD", 504},
+{"TAG", 505},
+{"TAIL", 1847},
+{"TAKE", 1848},
+{"TALE", 1849},
+{"TALK", 1850},
+{"TALL", 1851},
+{"TAN", 506},
+{"TANK", 1852},
+{"TAP", 507},
+{"TAR", 508},
+{"TASK", 1853},
+{"TATE", 1854},
+{"TAUT", 1855},
+{"TEA", 509},
+{"TEAL", 1856},
+{"TEAM", 1857},
+{"TEAR", 1858},
+{"TECH", 1859},
+{"TED", 510},
+{"TEE", 511},
+{"TEEM", 1860},
+{"TEEN", 1861},
+{"TEET", 1862},
+{"TELL", 1863},
+{"TEN", 512},
+{"TEND", 1864},
+{"TENT", 1865},
+{"TERM", 1866},
+{"TERN", 1867},
+{"TESS", 1868},
+{"TEST", 1869},
+{"THAN", 1870},
+{"THAT", 1871},
+{"THE", 513},
+{"THEE", 1872},
+{"THEM", 1873},
+{"THEN", 1874},
+{"THEY", 1875},
+{"THIN", 1876},
+{"THIS", 1877},
+{"THUD", 1878},
+{"THUG", 1879},
+{"THY", 514},
+{"TIC", 515},
+{"TICK", 1880},
+{"TIDE", 1881},
+{"TIDY", 1882},
+{"TIE", 516},
+{"TIED", 1883},
+{"TIER", 1884},
+{"TILE", 1885},
+{"TILL", 1886},
+{"TILT", 1887},
+{"TIM", 517},
+{"TIME", 1888},
+{"TIN", 518},
+{"TINA", 1889},
+{"TINE", 1890},
+{"TINT", 1891},
+{"TINY", 1892},
+{"TIP", 519},
+{"TIRE", 1893},
+{"TO", 520},
+{"TOAD", 1894},
+{"TOE", 521},
+{"TOG", 522},
+{"TOGO", 1895},
+{"TOIL", 1896},
+{"TOLD", 1897},
+{"TOLL", 1898},
+{"TOM", 523},
+{"TON", 524},
+{"TONE", 1899},
+{"TONG", 1900},
+{"TONY", 1901},
+{"TOO", 525},
+{"TOOK", 1902},
+{"TOOL", 1903},
+{"TOOT", 1904},
+{"TOP", 526},
+{"TORE", 1905},
+{"TORN", 1906},
+{"TOTE", 1907},
+{"TOUR", 1908},
+{"TOUT", 1909},
+{"TOW", 527},
+{"TOWN", 1910},
+{"TOY", 528},
+{"TRAG", 1911},
+{"TRAM", 1912},
+{"TRAY", 1913},
+{"TREE", 1914},
+{"TREK", 1915},
+{"TRIG", 1916},
+{"TRIM", 1917},
+{"TRIO", 1918},
+{"TROD", 1919},
+{"TROT", 1920},
+{"TROY", 1921},
+{"TRUE", 1922},
+{"TRY", 529},
+{"TUB", 530},
+{"TUBA", 1923},
+{"TUBE", 1924},
+{"TUCK", 1925},
+{"TUFT", 1926},
+{"TUG", 531},
+{"TUM", 532},
+{"TUN", 533},
+{"TUNA", 1927},
+{"TUNE", 1928},
+{"TUNG", 1929},
+{"TURF", 1930},
+{"TURN", 1931},
+{"TUSK", 1932},
+{"TWIG", 1933},
+{"TWIN", 1934},
+{"TWIT", 1935},
+{"TWO", 534},
+{"ULAN", 1936},
+{"UN", 535},
+{"UNIT", 1937},
+{"UP", 536},
+{"URGE", 1938},
+{"US", 537},
+{"USE", 538},
+{"USED", 1939},
+{"USER", 1940},
+{"USES", 1941},
+{"UTAH", 1942},
+{"VAIL", 1943},
+{"VAIN", 1944},
+{"VALE", 1945},
+{"VAN", 539},
+{"VARY", 1946},
+{"VASE", 1947},
+{"VAST", 1948},
+{"VAT", 540},
+{"VEAL", 1949},
+{"VEDA", 1950},
+{"VEIL", 1951},
+{"VEIN", 1952},
+{"VEND", 1953},
+{"VENT", 1954},
+{"VERB", 1955},
+{"VERY", 1956},
+{"VET", 541},
+{"VETO", 1957},
+{"VICE", 1958},
+{"VIE", 542},
+{"VIEW", 1959},
+{"VINE", 1960},
+{"VISE", 1961},
+{"VOID", 1962},
+{"VOLT", 1963},
+{"VOTE", 1964},
+{"WACK", 1965},
+{"WAD", 543},
+{"WADE", 1966},
+{"WAG", 544},
+{"WAGE", 1967},
+{"WAIL", 1968},
+{"WAIT", 1969},
+{"WAKE", 1970},
+{"WALE", 1971},
+{"WALK", 1972},
+{"WALL", 1973},
+{"WALT", 1974},
+{"WAND", 1975},
+{"WANE", 1976},
+{"WANG", 1977},
+{"WANT", 1978},
+{"WAR", 545},
+{"WARD", 1979},
+{"WARM", 1980},
+{"WARN", 1981},
+{"WART", 1982},
+{"WAS", 546},
+{"WASH", 1983},
+{"WAST", 1984},
+{"WATS", 1985},
+{"WATT", 1986},
+{"WAVE", 1987},
+{"WAVY", 1988},
+{"WAY", 547},
+{"WAYS", 1989},
+{"WE", 548},
+{"WEAK", 1990},
+{"WEAL", 1991},
+{"WEAN", 1992},
+{"WEAR", 1993},
+{"WEB", 549},
+{"WED", 550},
+{"WEE", 551},
+{"WEED", 1994},
+{"WEEK", 1995},
+{"WEIR", 1996},
+{"WELD", 1997},
+{"WELL", 1998},
+{"WELT", 1999},
+{"WENT", 2000},
+{"WERE", 2001},
+{"WERT", 2002},
+{"WEST", 2003},
+{"WET", 552},
+{"WHAM", 2004},
+{"WHAT", 2005},
+{"WHEE", 2006},
+{"WHEN", 2007},
+{"WHET", 2008},
+{"WHO", 553},
+{"WHOA", 2009},
+{"WHOM", 2010},
+{"WHY", 554},
+{"WICK", 2011},
+{"WIFE", 2012},
+{"WILD", 2013},
+{"WILL", 2014},
+{"WIN", 555},
+{"WIND", 2015},
+{"WINE", 2016},
+{"WING", 2017},
+{"WINK", 2018},
+{"WINO", 2019},
+{"WIRE", 2020},
+{"WISE", 2021},
+{"WISH", 2022},
+{"WIT", 556},
+{"WITH", 2023},
+{"WOK", 557},
+{"WOLF", 2024},
+{"WON", 558},
+{"WONT", 2025},
+{"WOO", 559},
+{"WOOD", 2026},
+{"WOOL", 2027},
+{"WORD", 2028},
+{"WORE", 2029},
+{"WORK", 2030},
+{"WORM", 2031},
+{"WORN", 2032},
+{"WOVE", 2033},
+{"WOW", 560},
+{"WRIT", 2034},
+{"WRY", 561},
+{"WU", 562},
+{"WYNN", 2035},
+{"YALE", 2036},
+{"YAM", 563},
+{"YANG", 2037},
+{"YANK", 2038},
+{"YAP", 564},
+{"YARD", 2039},
+{"YARN", 2040},
+{"YAW", 565},
+{"YAWL", 2041},
+{"YAWN", 2042},
+{"YE", 566},
+{"YEA", 567},
+{"YEAH", 2043},
+{"YEAR", 2044},
+{"YELL", 2045},
+{"YES", 568},
+{"YET", 569},
+{"YOGA", 2046},
+{"YOKE", 2047},
+{"YOU", 570}
+};
diff --git a/third_party/heimdal/lib/otp/otp_print.c b/third_party/heimdal/lib/otp/otp_print.c
new file mode 100644
index 0000000..372ddcf
--- /dev/null
+++ b/third_party/heimdal/lib/otp/otp_print.c
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+RCSID("$Id$");
+#endif
+
+#include "otp_locl.h"
+
+extern const char *const std_dict[];
+
+unsigned
+otp_checksum (OtpKey key)
+{
+ int i;
+ unsigned sum = 0;
+
+ for (i = 0; i < OTPKEYSIZE; ++i)
+ sum += ((key[i] >> 0) & 0x03)
+ + ((key[i] >> 2) & 0x03)
+ + ((key[i] >> 4) & 0x03)
+ + ((key[i] >> 6) & 0x03);
+ sum &= 0x03;
+ return sum;
+}
+
+void
+otp_print_stddict (OtpKey key, char *str, size_t sz)
+{
+ unsigned sum;
+
+ sum = otp_checksum (key);
+ snprintf (str, sz,
+ "%s %s %s %s %s %s",
+ std_dict[(key[0] << 3) | (key[1] >> 5)],
+ std_dict[((key[1] & 0x1F) << 6) | (key[2] >> 2)],
+ std_dict[((key[2] & 0x03) << 9) | (key[3] << 1) | (key[4] >> 7)],
+ std_dict[((key[4] & 0x7F) << 4) | (key[5] >> 4)],
+ std_dict[((key[5] & 0x0F) << 7) | (key[6] >> 1)],
+ std_dict[((key[6] & 0x01) << 10) | (key[7] << 2) | sum]);
+}
+
+void
+otp_print_hex (OtpKey key, char *str, size_t sz)
+{
+ snprintf (str, sz,
+ "%02x%02x%02x%02x%02x%02x%02x%02x",
+ key[0], key[1], key[2], key[3],
+ key[4], key[5], key[6], key[7]);
+}
+
+void
+otp_print_hex_extended (OtpKey key, char *str, size_t sz)
+{
+ strlcpy (str, OTP_HEXPREFIX, sz);
+ otp_print_hex (key,
+ str + strlen(OTP_HEXPREFIX),
+ sz - strlen(OTP_HEXPREFIX));
+}
+
+void
+otp_print_stddict_extended (OtpKey key, char *str, size_t sz)
+{
+ strlcpy (str, OTP_WORDPREFIX, sz);
+ otp_print_stddict (key,
+ str + strlen(OTP_WORDPREFIX),
+ sz - strlen(OTP_WORDPREFIX));
+}
diff --git a/third_party/heimdal/lib/otp/otp_verify.c b/third_party/heimdal/lib/otp/otp_verify.c
new file mode 100644
index 0000000..8a1c743
--- /dev/null
+++ b/third_party/heimdal/lib/otp/otp_verify.c
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 1995 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+RCSID("$Id$");
+#endif
+
+#include "otp_locl.h"
+
+int
+otp_verify_user_1 (OtpContext *ctx, const char *passwd)
+{
+ OtpKey key1, key2;
+
+ if (otp_parse (key1, passwd, ctx->alg)) {
+ ctx->err = "Syntax error in reply";
+ return -1;
+ }
+ memcpy (key2, key1, sizeof(key1));
+ ctx->alg->next (key2);
+ if (memcmp (ctx->key, key2, sizeof(key2)) == 0) {
+ --ctx->n;
+ memcpy (ctx->key, key1, sizeof(key1));
+ return 0;
+ } else
+ return -1;
+}
+
+int
+otp_verify_user (OtpContext *ctx, const char *passwd)
+{
+ void *dbm;
+ int ret;
+
+ if (!ctx->challengep)
+ return -1;
+ ret = otp_verify_user_1 (ctx, passwd);
+ dbm = otp_db_open ();
+ if (dbm == NULL) {
+ free(ctx->user);
+ return -1;
+ }
+ otp_put (dbm, ctx);
+ free(ctx->user);
+ otp_db_close (dbm);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/otp/otptest.c b/third_party/heimdal/lib/otp/otptest.c
new file mode 100644
index 0000000..dbf2131
--- /dev/null
+++ b/third_party/heimdal/lib/otp/otptest.c
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include <stdio.h>
+#include <string.h>
+#include <otp.h>
+
+static int
+test_one(OtpKey key1, char *name, char *val,
+ void (*print)(OtpKey,char*, size_t),
+ OtpAlgorithm *alg)
+{
+ char buf[256];
+ OtpKey key2;
+
+ (*print)(key1, buf, sizeof(buf));
+ printf ("%s: %s, ", name, buf);
+ if (strcmp (buf, val) != 0) {
+ printf ("failed(*%s* != *%s*)\n", buf, val);
+ return 1;
+ }
+ if (otp_parse (key2, buf, alg)) {
+ printf ("parse of %s failed\n", name);
+ return 1;
+ }
+ if (memcmp (key1, key2, OTPKEYSIZE) != 0) {
+ printf ("key1 != key2, ");
+ }
+ printf ("success\n");
+ return 0;
+}
+
+static int
+test (void)
+{
+ struct test {
+ char *alg;
+ char *passphrase;
+ char *seed;
+ int count;
+ char *hex;
+ char *word;
+ } tests[] = {
+
+ /* md4 */
+ {"md4", "This is a test.", "TeSt", 0, "d1854218ebbb0b51", "ROME MUG FRED SCAN LIVE LACE"},
+ {"md4", "This is a test.", "TeSt", 1, "63473ef01cd0b444", "CARD SAD MINI RYE COL KIN"},
+ {"md4", "This is a test.", "TeSt", 99, "c5e612776e6c237a", "NOTE OUT IBIS SINK NAVE MODE"},
+ {"md4", "AbCdEfGhIjK", "alpha1", 0, "50076f47eb1ade4e", "AWAY SEN ROOK SALT LICE MAP"},
+ {"md4", "AbCdEfGhIjK", "alpha1", 1, "65d20d1949b5f7ab", "CHEW GRIM WU HANG BUCK SAID"},
+ {"md4", "AbCdEfGhIjK", "alpha1", 99, "d150c82cce6f62d1", "ROIL FREE COG HUNK WAIT COCA"},
+ {"md4", "OTP's are good", "correct", 0, "849c79d4f6f55388", "FOOL STEM DONE TOOL BECK NILE"},
+ {"md4", "OTP's are good", "correct", 1, "8c0992fb250847b1", "GIST AMOS MOOT AIDS FOOD SEEM"},
+ {"md4", "OTP's are good", "correct",99, "3f3bf4b4145fd74b", "TAG SLOW NOV MIN WOOL KENO"},
+
+
+ /* md5 */
+ {"md5", "This is a test.", "TeSt", 0, "9e876134d90499dd", "INCH SEA ANNE LONG AHEM TOUR"},
+ {"md5", "This is a test.", "TeSt", 1, "7965e05436f5029f", "EASE OIL FUM CURE AWRY AVIS"},
+ {"md5", "This is a test.", "TeSt", 99, "50fe1962c4965880", "BAIL TUFT BITS GANG CHEF THY"},
+ {"md5", "AbCdEfGhIjK", "alpha1", 0, "87066dd9644bf206", "FULL PEW DOWN ONCE MORT ARC"},
+ {"md5", "AbCdEfGhIjK", "alpha1", 1, "7cd34c1040add14b", "FACT HOOF AT FIST SITE KENT"},
+ {"md5", "AbCdEfGhIjK", "alpha1", 99, "5aa37a81f212146c", "BODE HOP JAKE STOW JUT RAP"},
+ {"md5", "OTP's are good", "correct", 0, "f205753943de4cf9", "ULAN NEW ARMY FUSE SUIT EYED"},
+ {"md5", "OTP's are good", "correct", 1, "ddcdac956f234937", "SKIM CULT LOB SLAM POE HOWL"},
+ {"md5", "OTP's are good", "correct",99, "b203e28fa525be47", "LONG IVY JULY AJAR BOND LEE"},
+
+ /* sha */
+ {"sha", "This is a test.", "TeSt", 0, "bb9e6ae1979d8ff4", "MILT VARY MAST OK SEES WENT"},
+ {"sha", "This is a test.", "TeSt", 1, "63d936639734385b", "CART OTTO HIVE ODE VAT NUT"},
+ {"sha", "This is a test.", "TeSt", 99, "87fec7768b73ccf9", "GAFF WAIT SKID GIG SKY EYED"},
+ {"sha", "AbCdEfGhIjK", "alpha1", 0, "ad85f658ebe383c9", "LEST OR HEEL SCOT ROB SUIT"},
+ {"sha", "AbCdEfGhIjK", "alpha1", 1, "d07ce229b5cf119b", "RITE TAKE GELD COST TUNE RECK"},
+ {"sha", "AbCdEfGhIjK", "alpha1", 99, "27bc71035aaf3dc6", "MAY STAR TIN LYON VEDA STAN"},
+ {"sha", "OTP's are good", "correct", 0, "d51f3e99bf8e6f0b", "RUST WELT KICK FELL TAIL FRAU"},
+ {"sha", "OTP's are good", "correct", 1, "82aeb52d943774e4", "FLIT DOSE ALSO MEW DRUM DEFY"},
+ {"sha", "OTP's are good", "correct", 99, "4f296a74fe1567ec", "AURA ALOE HURL WING BERG WAIT"},
+ {NULL, NULL, NULL, 0, NULL, NULL}
+ };
+
+ struct test *t;
+ int sum = 0;
+
+ for(t = tests; t->alg; ++t) {
+ int i;
+ OtpAlgorithm *alg = otp_find_alg (t->alg);
+ OtpKey key;
+
+ if (alg == NULL) {
+ printf ("Could not find alg %s\n", t->alg);
+ return 1;
+ }
+ if(alg->init (key, t->passphrase, t->seed))
+ return 1;
+ for (i = 0; i < t->count; ++i) {
+ if (alg->next (key))
+ return 1;
+ }
+ sum += test_one (key, "hexadecimal", t->hex, otp_print_hex,
+ alg) +
+ test_one (key, "standard_word", t->word, otp_print_stddict, alg);
+ }
+ return sum;
+}
+
+int
+main (void)
+{
+ return test ();
+}
diff --git a/third_party/heimdal/lib/otp/roken_rename.h b/third_party/heimdal/lib/otp/roken_rename.h
new file mode 100644
index 0000000..07c3249
--- /dev/null
+++ b/third_party/heimdal/lib/otp/roken_rename.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __roken_rename_h__
+#define __roken_rename_h__
+
+#ifndef HAVE_SNPRINTF
+#define rk_snprintf _otp_snprintf
+#endif
+#ifndef HAVE_ASPRINTF
+#define rk_asprintf _otp_asprintf
+#endif
+#ifndef HAVE_ASNPRINTF
+#define rk_asnprintf _otp_asnprintf
+#endif
+#ifndef HAVE_VASPRINTF
+#define rk_vasprintf _otp_vasprintf
+#endif
+#ifndef HAVE_VASNPRINTF
+#define rk_vasnprintf _otp_vasnprintf
+#endif
+#ifndef HAVE_VSNPRINTF
+#define rk_vsnprintf _otp_vsnprintf
+#endif
+#ifndef HAVE_STRCASECMP
+#define rk_strcasecmp _otp_strcasecmp
+#endif
+#ifndef HAVE_STRNCASECMP
+#define rk_strncasecmp _otp_strncasecmp
+#endif
+#ifndef HAVE_STRLWR
+#define rk_strlwr _otp_strlwr
+#endif
+#ifndef HAVE_STRLCAT
+#define rk_strlcat _otp_strlcat
+#endif
+#ifndef HAVE_STRLCPY
+#define rk_strlcpy _otp_strlcpy
+#endif
+
+#endif /* __roken_rename_h__ */
diff --git a/third_party/heimdal/lib/otp/version-script.map b/third_party/heimdal/lib/otp/version-script.map
new file mode 100644
index 0000000..499943f
--- /dev/null
+++ b/third_party/heimdal/lib/otp/version-script.map
@@ -0,0 +1,25 @@
+HEIMDAL_OTP_1.0 {
+ global:
+ otp_challenge;
+ otp_checksum;
+ otp_db_close;
+ otp_db_open;
+ otp_delete;
+ otp_error;
+ otp_find_alg;
+ otp_get;
+ otp_parse;
+ otp_parse_altdict;
+ otp_parse_hex;
+ otp_parse_stddict;
+ otp_print_hex;
+ otp_print_hex_extended;
+ otp_print_stddict;
+ otp_print_stddict_extended;
+ otp_put;
+ otp_simple_get;
+ otp_verify_user;
+ otp_verify_user_1;
+ local:
+ *;
+};
diff --git a/third_party/heimdal/lib/roken/ChangeLog b/third_party/heimdal/lib/roken/ChangeLog
new file mode 100644
index 0000000..518987b
--- /dev/null
+++ b/third_party/heimdal/lib/roken/ChangeLog
@@ -0,0 +1,2229 @@
+2008-07-12 Love Hörnquist Åstrand <lha@kth.se>
+
+ * rkpty.c: Always print output for status.
+
+2008-04-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * getaddrinfo-test.c: drop )
+
+ * Makefile.am: Add rkpty.
+
+ * rkpty.c: More includes.
+
+ * rkpty.c: Add timeout, add password command, add diffrent
+ verbosity levels.
+
+2008-04-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rkpty.c: pty testing application
+
+2008-04-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolve.c: Use unsigned where appropriate.
+
+2008-02-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: make AM_CPPFLAGS +=
+
+2008-02-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Use AM_CPPFLAGS instead, not really right, but
+ definatly better then CPPFLAGS. Thanks to Mike Whitton for
+ pointing this out.
+
+2008-01-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add missing files.
+
+2007-08-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * strftime.c: rewrite str[pf]time for testing.
+
+ * strptime.c: rewrite str[pf]time for testing.
+
+ * Makefile.am: add TEST_STRPFTIME
+
+2007-07-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ndbm_wrap.c (dbm_get): set dsize to 0 on failure.
+
+ * Makefile.am: add ndbm_wrap.[ch] to EXTRA_DIST
+
+ * ndbm_wrap.c (dbm_fetch): set dsize to 0 on failure.
+
+2007-07-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * socket_wrapper.c: Implement swrap_dup too.
+
+ * socket_wrapper.c: Add dup(dummy stub) and dup2(real).
+
+ * socket_wrapper.h: Add dup(dummy stub) and dup2(real).
+
+2007-07-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: New library version.
+
+2007-06-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * roken_gethostby.c: set proxy_port to 0 to pacify BEAM.
+
+2007-06-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * use "roken.h" consitantly
+
+2007-06-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test-readenv.c: Free environment.
+
+ * environment.c (free_environment): free result of
+ read_environment().
+
+ * roken-common.h (free_environment): free result of
+ read_environment().
+
+2007-05-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * fnmatch.c: Do recursive call to rk_fnmatch
+
+2007-01-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolve.c: Try harder to call res_ndestroy().
+
+2006-12-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: make sure built headers are copied to the
+ ${build_topdir}/include
+
+2006-12-15 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * unvis.c: Use internal version of rk_unvis
+
+ * unvis.c: Always include rk_versions.
+
+ * vis.c: Always include rk_versions.
+
+ * vis.hin: Fix argument for unvis and strsvisx.
+
+ * unvis.c: prefix unvis functions with rk_, and prototypes.
+
+2006-12-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * vis.c: Provide some prototypes for the rk_vis functions.
+
+2006-12-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ifaddrs.hin: Prefix getifaddrs functions with rk_ and do symbol
+ renaming.
+
+ * fnmatch.c: Prefix fnmatch functions with rk_ and do symbol
+ renaming.
+
+ * vis.hin: Prefix strvis functions with rk_ and do symbol
+ renaming.
+
+ * vis.c: prefix strvis functions with rk_
+
+ * Makefile.am: Install extra posix headers in <roken/...> to avoid
+ dup headers.
+
+2006-11-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * socket_wrapper.c (swrap_sendto): fail on to unknown si->type
+
+2006-11-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * socket_wrapper.c: A few fixes to have Heimdal pass the make
+ check under socket_wrapper. The first is a missing 'break' before
+ the (heimdal specific) IPv6 support. The second works around the
+ fact that sendto() *may* object to a destination being specified.
+ It appears to be that on Linux, this objects (with EISCONN) for
+ unix stream sockets, but not for TCP sockets. The alternate fix
+ would be to have the KDC use 'send()' in this case. Andrew Bartlett.
+
+2006-10-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: split dist and nondist HEADERS
+
+2006-10-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * roken.h.in: Add timegm glue.
+
+ * timegm.c: add timegm()
+
+ * socket_wrapper.c: Include <roken.h>, gives os socklen_t on IRIX
+ 6.4.
+
+ * socket_wrapper.c: Maybe include <sys/time.h> and/or maybe
+ include <time.h>.
+
+2006-10-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * roken.h.in: Revert prevois for now, the problem is that we have
+ to include symbols unconditionally, even for those that just needs
+ protos.
+
+ * roken.h.in: Provide symbol renaming, let see what breaks.
+
+ * socket_wrapper.c: Maybe include <sys/filio.h>.
+
+2006-10-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * socket_wrapper.c: more consitity check, remove dead code, add
+ socket length code, add missing break, make diffrent chars of type
+ type files for case-insensitiv filesystems
+
+ * socket_wrapper.c: try even hard to not use socket wrapper for
+ socket_wrapper itself.
+
+ * socket_wrapper.c: Force no socket wrapper for socket_wrapper
+ itself.
+
+2006-10-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * socket_wrapper.c: Maybe include <config.h>.
+
+ * socket_wrapper.c: Protect AF_INET6 with #ifdef HAVE_IPV6.
+
+ * socket_wrapper.c: Use a symbol for the v6 address.
+
+ * socket_wrapper.c: Add IPv6 suppport.
+
+ * socket_wrapper.[ch]: Include socket wrapper from samba4 (rev
+ 19179).
+
+2006-10-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add build_HEADERZ to EXTRA_DIST
+
+ * Makefile.am: Add man_MANS to EXTRA_DIST
+
+ * Makefile.am: Add to all objects BUILD_ROKEN_LIB.
+
+2006-09-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * roken.h.in: Add samba socket wrapper fragment.
+
+ * Makefile.am: Add samba socket wrapper fragment.
+
+2006-09-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * snprintf.c: reapply patch that went away in last commit
+
+ * snprintf-test.c: unbreak from previous commit
+
+ * snprintf.c: Add size_t formater (z modifer).
+
+ * snprintf-test.c: add tests for size_t printf formater
+
+2006-06-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rtbl.h: Add extern "C" for C++.
+
+ * rtbl.c: Add rtbl_add_column_entryv functions, printf like
+
+ * rtbl.h: Add rtbl_add_column_entryv functions, printf like
+
+2006-06-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * glob.hin: Add extern "C" for C++. From joerg at britannica dot
+ bec dot de
+
+ * fnmatch.hin: Add extern "C" for C++. From joerg at britannica
+ dot bec dot de
+
+2006-04-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * fnmatch.hin (fnmatch): CPP rename to rk_fnmatch
+
+2006-04-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolve.c (dns_srv_order): change a if (ptr == NULL) continue
+ into a assert(ptr != NULL) since it could never happen, found by
+ the IBM code checker (beam). Thanks to Florian Krohm for
+ explaining it.
+
+2006-04-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * roken_gethostby.c (roken_gethostby): make addr_list one larger
+ to avoid a off-by-one error. Found by IBM checker.
+
+ * resolve.c: Plug memory leak found by IBM checker (and try to
+ please it).
+
+2006-02-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolve.c: Spelling, from Alexey Dobriyan, via Jason McIntyre
+
+2006-01-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * getcap.c: Don't use db support unless its build into libc but we
+ dont check for that now, so just disable the code. This removes
+ the dependency on libdb for roken, and that is a good thing since
+ it causes problem with nss plugins that uses DB3 that also
+ provides the same symbol, but with a diffrent ABI. so when the
+ application calls getpwnamn() and it linked to roken, it craches
+ in the nss functions.
+
+2006-01-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hex.c (hex_decode): support decoding odd number of characters,
+ in the odd len case, the first character ends up in the first byte
+ in the lower nibble.
+
+ * hex-test.c: Check that we can decode single character hex chars.
+
+2005-12-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * getifaddrs.c: Try handle HP/UX 11.nn, its diffrent from Solaris
+ large SIOCGIFCONF.
+
+2005-09-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * roken-common.h: Move rk_UNCONST to roken.h.in since it might use
+ uintptr_t depending on avaibility.
+
+ * roken.h.in: Include <stdint.h> if it exists. If avaiable, use
+ uintptr_t to define rk_UNCONST.
+
+2005-09-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * roken-common.h: Add rk_dumpdata.
+
+ * dumpdata.c: Add rk_dumpdata() that write a chunk of data into a
+ file for later processing by some other tool (like asn1_print).
+
+2005-09-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * strptime.c: cast to unsigned char to make sure its not negative
+ when passing it to is* functions
+
+2005-09-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * socket.c: Add socket_set_ipv6only.
+
+ * roken-common.h: Add socket_set_ipv6only, remove some argument
+ names.
+
+2005-08-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * strpool.c (rk_strpoolprintf): remove debug printf, plug memory
+ leak
+
+2005-08-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * setprogname.c (setprogname): const poision
+
+ * print_version.c: Removed, moved to libvers.
+
+2005-08-22 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolve.c (dns_lookup_int): if we have res_ndestroy, prefeer
+ that before res_nclose
+
+2005-08-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * getaddrinfo-test.c: Rename optind to optidx to avoid shadowing.
+
+2005-08-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gai_strerror.c: sprinkel more const
+
+ * gai_strerror.c, roken.h.in: Make return value of gai_strerror
+ const to match SUSv3. Prompted by Stefan Metzmacher change to
+ Samba.
+
+2005-07-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * roken.h.in: Remove parameter names to avoid shadow warnings.
+
+2005-07-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * getifaddrs.c (nl_getlist): poll to get messages from kernel, and
+ retry if the message was lost
+ (free_nlmsglist): free all linked elements, not just the first one
+
+2005-07-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * snprintf-test.c: Check a very simple format string
+
+2005-07-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * roken.h.in: If we have <strings.h> include it, its needed for
+ strcasecmp() on those platforms that are SUS3/iso c99 strict (like
+ AIX)
+
+ * roken-common.h: remove duplicate ;
+
+2005-07-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * roken-common.h: rk_strpoolprintf first variable identifier is 3
+
+2005-06-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * base64.h: remove variable names
+
+2005-06-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * roken-common.h: fix format attribute
+
+ * Makefile.am (libroken_la_SOURCES): += strpool.c
+
+ * roken-common.h: add strpool, a printf collector to make it
+ eaiser to collect strings into one string
+
+ * strpool.c: add strpool, a printf collector to make it eaiser to
+ collect strings into one string
+
+2005-06-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * base64.c: Add const, from Andrew Abartlet <abartlet@samba.org>
+
+2005-06-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * strpftime-test.c: test for "%Y%m"
+
+ * esetenv.c: unconst
+
+ * strptime.c: Write a new parse_number function that is possible
+ to limit that amount of numbers used, with this strptime can
+ handle strptime("200505", "%Y%m", &tm);
+
+2005-06-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * getaddrinfo.c: avoid shadowing sin
+
+ * resolve-test.c: rename optind to optidx to avoid shadowing
+
+ * strptime.c: UNCONST return value from strptime
+
+ * strftime.c: rk_UNCONST argument mktime
+
+ * getnameinfo.c: avoid shadowing sin
+
+ * socket.c: avoid shadowing sin
+
+ * resolve.c (parse_record): fix casting to avoid losing const
+
+ * roken.awk: since we got no feedback regarding people running
+ heimdal on the crays, remove the quoted # version
+
+ * environment.c: rename index to idx to avoid shadowing
+
+2005-05-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * parse_reply-test.c: avoid signedness warnings
+
+ * test-mem.c: avoid signedness warnings
+
+2005-05-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hex.c: include "roken.h" to avoid undefined size_t/ssize_t
+
+2005-05-24 Dave Love <fx@gnu.org>
+
+ * Makefile.am (snprintf_test_SOURCES): Add snprintf-test.h.
+
+2005-05-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * environment.c (rk_read_env_file): move assignment to later to
+ make pre c99 compiler happy
+
+2005-05-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * strptime.c: use english spelling of March
+
+2005-05-17 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: only link with dblib if we need it
+
+ * Makefile.am: add test_readenv
+
+ * test-readenv.c: test for read_environment()
+
+ * environment.c: eliminate duplicates
+
+2005-05-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * issuid.c (issuid): change the #ifdef order to avoid unreachable
+ code warning.
+
+2005-05-10 Dave Love <fx@gnu.org>
+
+ * roken.h.in: Get daemon declared on Solaris (it's in unistd.h but
+ masked by a feature test), just to avoid a warning, since it has
+ int args. Include err.h unconditionally, since it's always
+ supplied.
+
+2005-05-04 Dave Love <fx@gnu.org>
+
+ * snprintf-test.c: Include snprintf-test.h earlier.
+
+2005-05-03 Dave Love <fx@gnu.org>
+
+ * snprintf.c: Include snprintf-test.h earlier.
+
+ * test-mem.c: Add member fd to map.
+ (rk_test_mem_alloc, rk_test_mem_free): Use it.
+
+2005-04-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * getifaddrs.c: add break on default: statements, from Douglas
+ E. Engert
+
+ * snprintf.c (vsnprintf): don't write the NUL into the string if
+ the length was 0
+
+ * snprintf-test.c: add check that snprintf doesn't write the NUL
+ into the last byte when its a zero length input string
+
+ * parse_time-test.c: Include <err.h>.
+
+2005-04-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * parse_time-test.c: improve testing
+
+ * roken-common.h: add rk_realloc
+
+ * Makefile.am: add realloc
+
+ * realloc.c: add rk_realloc, unbroken version of realloc
+
+2005-04-26 Dave Love <fx@gnu.org>
+
+ * getusershell.c: Include roken.h
+
+2005-04-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * unvis.c: cast to unsigned char to make sure its not negative
+ when passing it to is* functions
+
+ * strptime.c: cast to unsigned char to make sure its not negative
+ when passing it to to* functions
+
+2005-04-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * simple_exec.c: don't close stderr, close all fd that is num 3
+ and larger
+
+ * simple_exec.c (pipe_execv): use closefrom
+
+ * add closefrom
+
+2005-04-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * add ROKEN_LIB_FUNCTION to all exported functions
+
+2005-04-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolve-test.c: print DS
+
+2005-04-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * parse_time-test.c: remove unused variable
+
+2005-04-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * strpftime-test.c: print size_t by casting to unsigned long
+
+ * base64-test.c: print size_t by casting to unsigned long
+
+ * hex-test.c: print size_t by casting to unsigned long
+
+ * resolve-test.c: print size_t by casting to unsigned long
+
+2005-04-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * snprintf-test.c (try): reset va_list argument between reuse,
+ from Peter Kruty <xkruty@fi.muni.cz>
+
+2005-03-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * roken_gethostby.c (roken_gethostby): s/sin/addr/ to avoid
+ shadowing
+
+ * resolve.c (dns_lookup_int): s/stat/state/ to avoid shadowing
+
+ * parse_units.c: avoid shadowing div
+
+2005-03-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * snprintf.c: use defined(TEST_SNPRINTF) like on all other places
+ in the same file
+
+2005-03-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * hex.c: check for overflows
+
+2005-03-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * vis.c: use RCSID instead of __RCSID
+
+2005-03-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: check_PROGRAMS += hex-test
+
+ * hex-test.c: hex encoding/decoding test
+
+ * hex.c: fix decodeing, it processed to much data and thus
+ returned the wrong length
+
+2005-03-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: add hex.[ch]
+
+ * hex.c: add hex encoder/decoder
+
+2005-03-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * daemon.c fnmatch.c fnmatch.hin getcap.c getopt.c getusershell.c
+ glob.c glob.hin iruserok.c unvis.c vis.hin:
+
+ In 1997, the University of California, Berkeley issued a statement
+ retroactively relicensing all code held under their copyright from
+ a 4-clause 'traditional' BSD license to a new 3-clause 'revised'
+ BSD license, which removed the advertising clause.
+
+ From NetBSD, via Joel Baker, and Alistair G. Crooks
+
+ * getaddrinfo-test.c: remove stray ( in output
+
+ * vis.c: Update new revision from NetBSD (copyright update)
+
+2005-02-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: bump version to 17:0:1
+
+2005-01-19 Dave Love <d.love@dl.ac.uk>
+
+ * getusershell.c: Include ctype.h, cast argument to isspace to
+ unsigned char.
+
+2004-10-31 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * parse_time.3, parse_units.c: Change the behavior of the
+ parse_unit code to return the number of bytes needed to print the
+ whole string (minus the trailing '\0'), just like snprintf. Idea
+ from bugreport from Gabriel Kihlman <gk@stacken.kth.se>.
+
+ * parse_time-test.c Makefile.am test-mem.c test-mem.h: test parse_time
+
+2004-10-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolve.c: put dns_type_to_string and dns_string_to_type in the
+ abi
+
+ * resolve.c: add ds_record
+
+ * resolve.h: add ds_record
+
+2004-10-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ndbm_wrap.c: undefine open so this works on solaris with large
+ file support From netbsd's pkgsrc via Gavan Fantom
+
+2004-09-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolve-test.c: add --version/--help
+
+2004-09-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: make resolve-test a noinst program
+
+2004-09-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolve-test.c: test program for libroken resolve from resolve.c
+
+ * Makefile.am: add resolve-test
+
+ * resolve.h: add constant for max DNS protocol packet size
+
+ * resolve.c (dns_lookup_int): grow the answer buffer to the size
+ the server send to us if the answer buffer was too small (limited
+ to the dns protocol max packet size)
+
+2004-08-26 Johan Danielsson <joda@pdc.kth.se>
+
+ * err.hin: no need to declare __progname here
+
+ * Makefile.am: always clean generated headers
+
+2004-06-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rtbl.3: use .In for header, remove trailing space
+
+2004-06-23 Johan Danielsson <joda@pdc.kth.se>
+
+ * rtbl.h: add protos and macros
+
+ * rtbl.c: implement a bunch of stuff:
+ - column separator (instead of global column prefix)
+ - per column suffix
+ - indexing columns by id-number instead of column header
+ - optional header supression (via settable flags)
+ - ability to end a row
+ - don't extend last column to full width
+
+2004-06-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolve.[ch]: add and use and bind9 version of rr type
+ (rk_ns_t_XXX) instead of the old bind4 version (T_XXX)
+
+2004-05-25 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolve.c (stot): add AAAA
+
+2004-02-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * getarg.c (add_string): catch error from realloc
+
+2004-02-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * roken-common.h: add simple_execve_timed
+
+ * roken-common.h: add timed simple_exec
+
+ * simple_exec.c: add timed simple_exec
+
+2004-01-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gai_strerror.c: correct ifdef for EAI_ADDRFAMILY
+
+2003-12-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolve.c: parse dns header, add support for SSHFP
+
+ * resolve.h: add cpp rewrite for sshfp_record
+
+ * resolve.h: add SSHFP, clean up the the dns_header
+
+2003-12-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolve.h: remove HEADER (only used for crays)
+
+ * resolve.c: number-of fields no longer stored in network order
+
+2003-12-13 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolve.c: remove depency on c99 types in resolv.h
+
+ * resolve.h: remove depency on c99 types
+
+2003-12-06 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * resolv.h: add more T_ types and inline the dns headers, all this
+ for bind9 resolvers
+
+2003-12-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * gai_strerror.c: EAI_ADDRFAMILY and EAI_NODATA is deprecated
+
+ * roken-common.h: use EAI_NONAME instead of EAI_ADDRFAMILY to
+ check for if we need EAI_ macros
+
+2003-10-04 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * strptime.c: let t and n match zero or more whitespaces
+
+2003-08-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * ndbm_wrap.c: patch for working with DB4 on heimdal-discuss
+ From: Luke Howard <lukeh@PADL.COM>
+
+2003-08-27 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: don't include discovered files in EXTRA_SOURCES;
+ don't depend on all header files, just the built ones
+
+2003-08-15 Johan Danielsson <joda@pdc.kth.se>
+
+ * emalloc.3: manpage
+
+2003-07-11 Love <lha@stacken.kth.se>
+
+ * resolve.c: AIX have broken res_nsearch() in 5.1 (5.0 also ?) so
+ just don't use res_nsearch on AIX
+
+2003-06-29 Johan Danielsson <joda@pdc.kth.se>
+
+ * snprintf.c: * don't ever print sign for unsigned conversions *
+ don't break when right justifying a number past the end of the
+ buffer * handle zero precision and the value zero more correctly
+
+2003-06-14 Love <lha@stacken.kth.se>
+
+ * glob.hin: prefix glob symbols with rk_
+
+2003-04-22 Love <lha@stacken.kth.se>
+
+ * resolve.c: copy NUL too, from janj@wenf.org via openbsd
+
+2003-04-16 Love <lha@stacken.kth.se>
+
+ * parse_units.h: remove typedef for units to avoid problems with
+ shadowing
+
+ * resolve.c: use strlcpy, from openbsd
+
+ * getcap.c: use strlcpy, from openbsd
+
+ * getarg.3: Change .Fd #include <header.h> to .In header.h
+ from Thomas Klausner <wiz@netbsd.org>
+
+2003-04-15 Love <lha@stacken.kth.se>
+
+ * socket.c (socket_set_tos): if setsockopt failed with EINVAL
+ failed, just ignore it, sock was probably a just a non AF_INET
+ socket
+
+2003-04-14 Love <lha@stacken.kth.se>
+
+ * strncasecmp.c: cast argument to toupper to unsigned char, from
+ Christian Biere <christianbiere@gmx.de> via NetBSD
+
+ * strlwr.c: cast argument to tolower to unsigned char, from
+ Christian Biere <christianbiere@gmx.de> via NetBSD
+
+ * strcasecmp.c: cast argument to toupper to unsigned char, from
+ Christian Biere <christianbiere@gmx.de> via NetBSD
+
+2003-03-19 Love <lha@stacken.kth.se>
+
+ * getarg.3: spelling, from <jmc@prioris.mini.pw.edu.pl>
+
+2003-03-07 Love <lha@stacken.kth.se>
+
+ * parse_bytes.c: use struct units instead of units
+
+ * parse_time.c: use struct units instead of units
+
+2003-03-04 Love <lha@stacken.kth.se>
+
+ * roken.awk: use full prototype for main
+
+2002-10-15 Johan Danielsson <joda@pdc.kth.se>
+
+ * resolve.c: check length of txt records
+
+2002-09-10 Johan Danielsson <joda@pdc.kth.se>
+
+ * roken.awk: include config.h before stdio.h (breaks with
+ _FILE_OFFSET_BITS on solaris otherwise)
+
+2002-09-09 Johan Danielsson <joda@pdc.kth.se>
+
+ * resolve.c: fix res_nsearch call, but don't use it for now, AIX5
+ has a broken version that trashes memory
+
+ * roken-common.h: fix typo in previous
+
+ * roken-common.h: change IRIX == 4 to IRIX4
+
+2002-09-04 Assar Westerlund <assar@kth.se>
+
+ * getifaddrs.c: remove some warnings from the linux-portion
+
+ * getnameinfo_verified.c (getnameinfo_verified): handle the case
+ of forward but no backward DNS information, and also describe the
+ desired behaviour. from Love <lha@stacken.kth.se>
+
+2002-09-04 Johan Danielsson <joda@pdc.kth.se>
+
+ * rtbl.c (rtbl_destroy): free whole table
+
+ * resolve.c: use res_nsearch if we have it (from Larry Greenfield)
+
+2002-09-03 Assar Westerlund <assar@kth.se>
+
+ * getifaddrs.c: add Linux AF_NETLINK getifaddrs from Hideaki
+ YOSHIFUJI of the Usagi project
+
+ * parse_reply-test.c: make this build and return 77 if there is no
+ mmap
+
+ * Makefile.am (parse_reply-test): add
+ * parse_reply-test.c: add a test case for parse_reply reading past
+ the given buffer
+ * resolve.c (parse_reply): update the arguments to more reasonable
+ types. allow parse_reply-test to call it
+
+2002-08-28 Johan Danielsson <joda@pdc.kth.se>
+
+ * resolve.c (dns_srv_order): do alignment tricks with the random()
+ state (from NetBSD)
+
+2002-08-27 Assar Westerlund <assar@kth.se>
+
+ * resolve.c (parse_reply): verify the lengths (both external and
+ internal) are consistent and not too long
+ (dns_lookup_int): be conservative in the length sent in to to
+ parse_reply
+
+2002-08-26 Assar Westerlund <assar@kth.se>
+
+ * roken.h.in: add prototypes for str, unvis functions
+ * resolve.h: add fallback definition for T_AAAA
+
+2002-08-22 Johan Danielsson <joda@pdc.kth.se>
+
+ * roken.h.in: we may need a prototype for strndup
+
+2002-08-20 Johan Danielsson <joda@pdc.kth.se>
+
+ * roken.h.in: typedef ssize_t here
+
+ * getarg.c: don't put Ns before comma
+
+ * resolve.c: _res might not be available
+
+ * localtime_r.c: include stdio.h and roken.h
+
+ * strftime.c: only use altzone if we have it
+
+ * roken-common.h: AI_NUMERICHOST needs special handling
+
+ * strlcat.c: add some consistency checks
+
+ * strlcpy.c: make the logic simpler, and handle dst_sz == 0
+
+2002-08-19 Johan Danielsson <joda@pdc.kth.se>
+
+ * resolve.h: prefix these functions to avoid conflicts with other
+ packages
+
+2002-08-14 Johan Danielsson <joda@pdc.kth.se>
+
+ * strsep_copy.c: don't write to buf if len == 0
+
+2002-05-31 Assar Westerlund <assar@pdc.kth.se>
+
+ * Makefile.am: *_LDADD: add LDADD, so that libroken is used
+
+2002-05-17 Johan Danielsson <joda@pdc.kth.se>
+
+ * xdbm.h: remove old dbm part
+
+2002-04-30 Johan Danielsson <joda@pdc.kth.se>
+
+ * ndbm_wrap.{c,h}: ndbm wrapper for newer db libraries
+
+2002-04-18 Johan Danielsson <joda@pdc.kth.se>
+
+ * roken.h.in: move mini_inetd protos to after addrinfo definition
+
+ * snprintf.c (append_number): make rep const
+
+ * getarg.h: rename optind and optarg to avoid some gcc warnings
+
+ * getarg.c: rename optind and optarg to avoid some gcc warnings
+
+2002-02-18 Johan Danielsson <joda@pdc.kth.se>
+
+ * mini_inetd.c: mini_inetd_addrinfo that takes an addrinfo instead
+ of a port number
+
+2001-11-30 Assar Westerlund <assar@sics.se>
+
+ * getifaddrs.c: support SIOCGLIFCONF and SIOCGLIFFLAGS which are
+ used on Solaris 8 to retrieve addresses larger than `struct
+ sockaddr'. From Magnus Ahltorp <ahltorp@nada.kth.se> (with some
+ modifications by me)
+
+2001-10-27 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libroken_la_LDFLAGS): set version to 15:0:6
+
+2001-10-22 Assar Westerlund <assar@sics.se>
+
+ * localtime_r.c: add
+
+2001-10-02 Johan Danielsson <joda@pdc.kth.se>
+
+ * resolve.c (dns_srv_order): don't try to return a value
+
+2001-09-24 Johan Danielsson <joda@pdc.kth.se>
+
+ * snprintf.c: va_{start,end} fixes; from Thomas Klausner
+
+2001-09-20 Assar Westerlund <assar@sics.se>
+
+ * resolve.c (dns_srv_order): make sure of not reading after the
+ array
+
+2001-09-17 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libroken_la_LDFLAGS): bump to 14:4:5
+ * snprintf.c: rename 'struct state' -> 'struct snprintf_test' to
+ avoid collision with resolv.h on aix
+
+2001-09-04 Assar Westerlund <assar@sics.se>
+
+ * parse_bytes-test.c, parse_bytes.c, parse_bytes.h, parse_units.c,
+ parse_units.h: use int instead of size_t as return values to be
+ compatible with snprintf
+
+ * strftime.c (strftime): check for return values from snprintf() <
+ 0
+
+2001-09-03 Johan Danielsson <joda@pdc.kth.se>
+
+ * socket.c: restrict is a keyword
+
+2001-09-03 Assar Westerlund <assar@sics.se>
+
+ * write_pid.c: handle atexit or on_exit
+
+ * Makefile.am (EXTRA_libroken_la_SOURCES): add vis.hin to help
+ solaris make
+
+2001-08-30 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: use LDADD directly
+
+2001-08-28 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libroken_la_LDFLAGS): set to 14:3:5
+
+ * issuid.c (issuid): call issetugid if it exists
+
+2001-08-24 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: make it play better with recent automake
+
+2001-08-21 Assar Westerlund <assar@sics.se>
+
+ * glob.c: provide a fallback for ARG_MAX. from <tol@stacken.kth.se>
+
+ * roken.h.in: remove all winsock.h
+ for now, it does more harm than good under cygwin and if it should be
+ used, the correct conditional needs to be found
+ from <tol@stacken.kth.se>
+
+2001-08-17 Johan Danielsson <joda@pdc.kth.se>
+
+ * getaddrinfo.c: include a definition of in6addr_loopback if it
+ doesn't exist
+
+2001-08-10 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libroken_la_LDFLAGS): update to 14:2:5
+
+2001-08-08 Assar Westerlund <assar@sics.se>
+
+ * hstrerror.c: move h_errno to its own file (h_errno.c)
+
+2001-08-04 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: add getarg.3
+
+2001-08-01 Assar Westerlund <assar@sics.se>
+
+ * mini_inetd.c (mini_inetd): explicitly use PF_UNSPEC. be more
+ resilient to bind/listen failing.
+
+2001-07-31 Assar Westerlund <assar@sics.se>
+
+ * getifaddrs.c (getifaddrs2): remove unused variables
+
+2001-07-31 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libroken_la_LDFLAGS): update version to 14:1:5
+
+2001-07-23 Assar Westerlund <assar@sics.se>
+
+ * getarg.c (arg_match_long): fix parsing of arg_counter optional
+ argument
+
+2001-07-19 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libroken_la_LDFLAGS): bump version to 14:0:5
+
+2001-07-17 Assar Westerlund <assar@sics.se>
+
+ * snprintf-test.h: add a file with renaming of the snprintf
+ functions, to be used for running the tests
+
+2001-07-11 Assar Westerlund <assar@sics.se>
+
+ * snprintf-test.c: add more %X tests, and long and conditional
+ long long tests
+ * snprintf.c: add support for printing long long (if available)
+
+2001-07-10 Assar Westerlund <assar@sics.se>
+
+ * getaddrinfo.c (add_hostent): adapt to const hostent_find_fqdn
+ * hostent_find_fqdn.c (hostent_find_fqdn): const-ize
+
+2001-07-09 Assar Westerlund <assar@sics.se>
+
+ * roken-common.h (hostent_find_fqdn): add
+ * hostent_find_fqdn.c: separate out hostent_find_fqdn
+
+ * warnerr.c: move out getprogname, setprogname
+
+2001-07-03 Assar Westerlund <assar@sics.se>
+
+ * warnerr.c (setprogname): add const cast
+ * vis.c (SVIS): add some (unsigned char) before calling isfoo*
+ * Makefile.am (libroken_la_LDFLAGS:) set version to 13:0:4
+
+ * Makefile.am: add snprintf_test
+ * snprintf.c: rewrite so that it does not stop as soon as there
+ are no more characters to print, we need to figure out how long
+ the string would have to be. this also fixes snprintf(NULL, 0
+
+2001-06-21 Assar Westerlund <assar@sics.se>
+
+ * simple_exec.c (pipe_execv): remove unused variable
+
+2001-06-20 Johan Danielsson <joda@pdc.kth.se>
+
+ * getdtablesize.c: fix typo in obviously never used sysctl case
+
+ * simple_exec.c: rename check_status to wait_for_process, and
+ export it; function pipe_execv similar to popen, but with more
+ control over input and output
+
+ * roken-common.h: prototypes for wait_for_process and pipe_execv
+
+2001-06-17 Assar Westerlund <assar@sics.se>
+
+ * roken-common.h: move emalloc et al to roken.h.in
+ * Makefile.am: make emalloc,ecalloc,erealloc,estrdup conditional
+ * emalloc.c, erealloc.c, estrup.c: use errx, since errno might not
+ be set reliably
+ * ecalloc.c: add for symmetry
+
+2001-06-09 Johan Danielsson <joda@pdc.kth.se>
+
+ * resolve.c: dns_srv_order to order srv records
+
+2001-06-08 Johan Danielsson <joda@pdc.kth.se>
+
+ * getarg.c: Grog tries to figure out if to use mdoc.old instead of
+ mdoc by looking at some macros that were only present in the old
+ version, and by looking at the number of .Oo's present. In
+ mdoc.old .Oo was a toggle, but in mdoc it's closed by .Oc, so if
+ the number of .Oo's is bigger than the number of .Oc's, it figures
+ it must be mdoc.old. This doesn't however account for called Oc's,
+ and thus grog thinks that valid pages are mdoc.old when they
+ infact are mdoc. So let's make sure that Oc's are not called by
+ other macros.
+
+2001-05-29 Assar Westerlund <assar@sics.se>
+
+ * base64-test.c (main): initialize numerr
+
+2001-05-28 Johan Danielsson <joda@pdc.kth.se>
+
+ * base64.c: clean up the decode mess somewhat
+
+ * base64-test.c: base64 tests
+
+2001-05-18 Johan Danielsson <joda@pdc.kth.se>
+
+ * roken.h.in: just use standard C types with bswap*
+
+ * bswap.c: just use standard C types
+
+2001-05-17 Assar Westerlund <assar@sics.se>
+
+ * roken.h.in: include all the headers that AC_GROK_TYPES tries for
+ finding u_int17_t et al
+
+ * Makefile.am: bump version to 12:0:3
+ * roken.h.in: re-add set_progname and get_progname for backwards
+ compatability
+ * warnerr.c: re-add set_progname and get_progname for backwards
+ compatability
+
+2001-05-12 Assar Westerlund <assar@sics.se>
+
+ * glob.c: add limits.h, from <shadow@dementia.org>
+
+2001-05-11 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: bswap.c
+
+ * bswap.c: bswap{16,32}
+
+2001-05-08 Assar Westerlund <assar@sics.se>
+
+ * freeaddrinfo.c (freeaddrinfo): also free every `struct
+ addrinfo'. from <tmartin@mirapoint.com>
+
+2001-04-25 Assar Westerlund <assar@sics.se>
+
+ * getarg.h (free_getarg_strings): add prototype
+ * getarg.c (free_getarg_strings): add function
+
+2001-04-21 Johan Danielsson <joda@pdc.kth.se>
+
+ * getarg.c: pack short flag options togther, to shorten the usage
+ string
+
+2001-04-17 Johan Danielsson <joda@pdc.kth.se>
+
+ * getifaddrs.c (getifaddrs2): close socket when done
+
+2001-03-26 Johan Danielsson <joda@pdc.kth.se>
+
+ * roken.awk: END has to be last with Sun's awk
+
+2001-03-26 Assar Westerlund <assar@sics.se>
+
+ * parse_units.c (parse_something): do not check the return value
+ from strtod, it might return != 0.0 when the string has no digits.
+ just testing if it consumed any characters is enough and more
+ resilient
+ * glob.c: add GLOB_LIMIT (from NetBSD)
+
+2001-02-20 Assar Westerlund <assar@sics.se>
+
+ * warnerr.c (warnerr): do not use __progname
+ * roken.h.in (setprogname, getprogname): add prototypes
+ * warnerr.c (setprogname, getprogname): rename to. change all
+ callers
+
+2001-02-12 Assar Westerlund <assar@sics.se>
+
+ * getnameinfo_verified.c (getnameinfo_verified): do the first
+ getnameinfo with NI_NUMERICSERV to avoid the error that bind 8.2.3
+ reports on not finding the service
+ (ENI_NOSERVNAME). reported by Ake Sandgren <ake@cs.umu.se>
+
+2001-02-09 Assar Westerlund <assar@sics.se>
+
+ * getnameinfo.c (doit): call inet_ntop with correct af, noted by
+ Ake Sandgren <ake@cs.umu.se>
+
+2001-02-08 Assar Westerlund <assar@sics.se>
+
+ * getnameinfo_verified.c (getnameinfo_verified): always capture
+ the service from getnameinfo so it can be sent back to getaddrinfo
+ and set socktype to avoid getaddrinfo not returning any addresses
+
+2001-01-30 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libroken_la_LDFLAGS): bump version to 11:1:2
+ * print_version.c (print_version): add 2001
+
+2001-01-29 Assar Westerlund <assar@sics.se>
+
+ * getifaddrs.c (getifaddrs2): copy the entire sockaddr
+
+ * roken-common.h (_PATH_BSHELL): add
+
+2001-01-27 Assar Westerlund <assar@sics.se>
+
+ * roken.h.in: move __attribute__ to roken-common.h
+
+ * esetenv.c (esetenv): cast to handle a setenv that takes a `char
+ * which is the case on Unicos
+
+2000-12-29 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (EXTRA_libroken_la_SOURCES): ifaddrs.h ->
+ ifaddrs.hin
+
+2000-12-25 Assar Westerlund <assar@sics.se>
+
+ * getarg.c (print_arg): add a case for arg_strings
+
+2000-12-15 Johan Danielsson <joda@pdc.kth.se>
+
+ * snprintf.c (append_string): handle NULL strings by printing
+ `(null)'
+
+2000-12-12 Johan Danielsson <joda@pdc.kth.se>
+
+ * roken-common.h: add c++ externs
+
+ * roken.h.in: fix last commit differently
+
+2000-12-11 Assar Westerlund <assar@sics.se>
+
+ * err.hin (warnerr): remove, it's not part of the err.h interface
+ * roken-common.h (warnerr): moved here from err.hin
+ * Makefile.am (libroken_la_LDFLAGS): set version to 11:0:2
+ * vis.c: s/u_int32_t/unsigned/ for systems that do not define
+ u_int32_t
+
+2000-12-10 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: rename some headers to avoid conflict with possible
+ system headers
+
+2000-12-06 Johan Danielsson <joda@pdc.kth.se>
+
+ * vis.c: make sure _DIAGASSERT is defined
+
+ * unvis.c: make sure _DIAGASSERT is defined
+
+ * Makefile.am: unvis.c, and vis.h
+
+ * vis.h: vis.h from NetBSD
+
+ * unvis.c: unvis from NetBSD
+
+ * roken.h.in: cleanup previous
+
+ * roken-common.h: make `extern "C"' into a macro, this make emacs
+ much happier
+
+ * vis.c: strvis implementation from NetBSD
+
+ * roken.h.in: add prototypes for strvis*
+
+2000-12-05 Johan Danielsson <joda@pdc.kth.se>
+
+ * ifaddrs.h: fix freeifaddrs prototype, and add ifa_broadaddr
+ macro
+
+ * getifaddrs.c: free some memory
+
+2000-12-04 Johan Danielsson <joda@pdc.kth.se>
+
+ * ifaddrs.h: getifaddrs implementation using SIOCGIFCONFIG etc
+
+ * getifaddrs.c: getifaddrs implementation using SIOCGIFCONFIG etc
+
+2000-10-08 Assar Westerlund <assar@sics.se>
+
+ * mini_inetd.c (mini_inetd): check that fds are not too large to
+ select on
+
+2000-09-24 Assar Westerlund <assar@sics.se>
+
+ * esetenv.c: new file/function
+
+2000-08-16 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 10:0:1
+
+2000-08-10 Assar Westerlund <assar@sics.se>
+
+ * mini_inetd.c (accept_it): type-correctness on parameters to
+ accept
+
+2000-08-07 Johan Danielsson <joda@pdc.kth.se>
+
+ * roken.h.in: add proto compat for getsockname
+
+2000-08-04 Johan Danielsson <joda@pdc.kth.se>
+
+ * write_pid.c: conditionalise pidfile
+
+ * write_pid.c: add pidfile function
+
+2000-07-25 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: bump version to 9:0:0
+
+ * warnerr.c: add get_progname
+
+2000-07-24 Assar Westerlund <assar@sics.se>
+
+ * getaddrinfo.c (add_hostent): if there's no fqdn in `he' try
+ reverse resolving to see if there's a fuller name there. don't
+ use just-freed memory
+
+2000-07-22 Assar Westerlund <assar@sics.se>
+
+ * xdbm.h: do not define ndbm functions in terms of dbm functions
+ if we're using db
+
+2000-07-20 Assar Westerlund <assar@sics.se>
+
+ * rtbl.c (rtbl_format): avoid printing an empty row at the end
+
+2000-07-19 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: make this compatible with `make dist'
+
+ * Makefile.am: revert version number for now
+
+2000-07-18 Johan Danielsson <joda@pdc.kth.se>
+
+ * configure.in: AM_PROG_LIBTOOL -> AC_PROG_LIBTOOL
+
+2000-07-17 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: set ACLOCAL_AMFLAGS
+
+2000-07-15 Johan Danielsson <joda@pdc.kth.se>
+
+ * getaddrinfo_hostspec.c: add new function that takes socktype
+ hint as parameter
+
+2000-07-09 Assar Westerlund <assar@sics.se>
+
+ * rtbl.c (rtbl_add_column): initialize `col' completely
+
+ * configure.in: bring headers and functions more in-line with
+ what's actually being used
+
+2000-07-08 Johan Danielsson <joda@pdc.kth.se>
+
+ * roken.h.in: declare ether_addr and sockaddr_dl for AIX
+
+ * rtbl.{c,h}: simple table functions
+
+2000-07-08 Assar Westerlund <assar@sics.se>
+
+ * configure.in (AM_INIT_AUTOMAKE): bump version to 10
+ * configure.in (AC_BROKEN): add strsep_copy
+ * Makefile.am (ACLOCAL): fetch files from cf
+
+2000-07-01 Assar Westerlund <assar@sics.se>
+
+ * roken-common.h (pid_file_*): fix protos
+
+2000-06-28 Assar Westerlund <assar@sics.se>
+
+ * getnameinfo_verified.c (getnameinfo_verified): free memory
+ returned from getaddrinfo
+
+2000-06-27 Assar Westerlund <assar@sics.se>
+
+ * resolve.c: export string_to_type and type_to_string
+ * resolve.c: add key,sig,cert update test-program
+ * resolve.h: add key,sig,cert
+
+2000-06-21 Assar Westerlund <assar@sics.se>
+
+ * resolve.h: add T_SIG, T_KEY
+ * resolve.c: add SIG and KEY
+ * Makefile.am (libroken_la_SOURCES): add environment.c and
+ write_pid.c
+
+ * write_pid.c: new file for writing a pid file.
+
+ * environment.c: new file with functionality for reading
+ /etc/environment. From Ake Sandgren <ake@cs.umu.se>
+
+2000-06-12 Johan Danielsson <joda@pdc.kth.se>
+
+ * strsep_copy.c: strsep, but with const stringp so returns string
+ in separate buffer
+
+2000-05-23 Assar Westerlund <assar@sics.se>
+
+ * vsyslog.c (vsyslog): calculate length of new format string
+ correctly
+
+2000-05-22 Johan Danielsson <joda@pdc.kth.se>
+
+ * getusershell.c: implment the AIX version use
+ /etc/security/login.cfg
+
+2000-05-21 Assar Westerlund <assar@sics.se>
+
+ * vsyslog.c (vsyslog): actually handle `%m'
+
+2000-05-15 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libroken_la_LDFLAGS): set version to 8:1:3
+
+ * roken-common.h: moved __attribute__ to roken.h.in
+
+2000-04-14 Assar Westerlund <assar@sics.se>
+
+ * getaddrinfo_hostspec.c (roken_getaddrinfo_hostspec): copy the
+ correct length from `hostspec'. based on a patch from Love
+ <lha@s3.kth.se>
+
+2000-04-09 Assar Westerlund <assar@sics.se>
+
+ * xdbm.h: only include one of db.h and the dbm-series
+
+2000-04-05 Assar Westerlund <assar@sics.se>
+
+ * resolve.c (_resolve_debug): explicitly set to zero. this moves
+ the variable from bss to data and the dynamic linker on MacOS
+ X/Darwin seems unhappy with stuff in the bss segment.
+
+2000-04-03 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 8:0:3
+
+2000-03-11 Assar Westerlund <assar@sics.se>
+
+ * roken.h.in (_SS_PAD1SIZE): try to write an inpenetrable
+ expression that also works on Crays
+
+2000-03-09 Assar Westerlund <assar@sics.se>
+
+ * getarg.c (arg_match_short): backup optind when there's a missing
+ argument so that the error can point at the flag and not the
+ non-existant argument
+
+2000-03-03 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (SOURCES): add timeval.c
+ * Makefile.am (libroken_la_SOURCES): add timeval.c
+ * timeval.c: new file
+
+2000-02-19 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 7:1:2
+
+2000-02-16 Assar Westerlund <assar@sics.se>
+
+ * snprintf.c (PARSE_INT_FORMAT): note that shorts are actually
+ transmitted as ints
+ (according to the integer protomotion rules) in variable arguments
+ lists. Therefore, we should not call va_arg with short but rather
+ with int. See <http://www.debian.org/Bugs/db/57/57919.html> for
+ original bug report
+
+2000-02-13 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 7:0:2
+
+ * getarg.c (mandoc_template): also fix no- prefix in .Sh OPTIONS
+ * getarg.c (mandoc_template): better man-stuff for negative
+ options
+
+2000-02-07 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 6:0:1
+
+2000-02-06 Assar Westerlund <assar@sics.se>
+
+ * xdbm.h: hopefully catch a few more declarations by including
+ <ndbm.h> even if <db.h> was found
+
+2000-01-26 Assar Westerlund <assar@sics.se>
+
+ * mini_inetd.c (mini_inetd): separate number of allocated sockets
+ and number of actual ones
+ * mini_inetd.c (mini_inetd): count sockets properly. and fail if
+ we cannot bind any
+ * mini_inetd.c (mini_inetd): make failing to create a socket
+ non-fatal
+
+2000-01-09 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am(libroken_la_SOURCES): add strcollect.c
+ * Makefile.in: add strcollect.[co]
+ * simple_exec.c: use vstrcollect
+ * roken-common.h (_PATH_DEV): add
+ (strcollect, vstrcollect): add prototypes
+ * strcollect.c: new file. functions for collapsing an `va_list'
+ into an `char **'
+
+2000-01-06 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 5:0:0
+
+1999-12-30 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (strpftime_test_SOURCES): correct source file name
+
+ * roken.h.in (sockaddr_storage): change padding so that we have
+ one char[] of pad and then an unsigned long[] (for alignment and
+ padding). this works much better in practice.
+
+1999-12-22 Assar Westerlund <assar@sics.se>
+
+ * roken.h.in (sockaddr_storage): drop leading underscore on
+ `public' fields. this was the consensus on the ipng mailing list
+
+1999-12-21 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (strpftime-test): define sources to avoid having
+ '.o'
+ * Makefile.am (print_version.h): use $(EXEEXT)
+ * Makefile.am (roken.h): add $(EXEEXT) to make this work on cygwin
+ et al
+
+1999-12-20 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libroken_la_LDFLAGS): bump version to 4:3:0
+
+ * getaddrinfo.c (get_nodes): use getipnodebyname instead of
+ gethostbyname(2)
+
+1999-12-16 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libroken_la_LDFLAGS): bump version to 4:2:0
+
+ * roken.h.in (struct sockaddr_storage): redefine with the example
+ code from rfc2553
+
+ * getaddrinfo.c (get_null): set loopback with correct endianess
+ for v4. dunno about v6.
+
+1999-12-13 Assar Westerlund <assar@sics.se>
+
+ * roken.h.in: add prototypes for str[pf]time
+
+ * signal.c: macosx = rhapsody ~= nextstep also can't handle
+ various definitions of the same symbol.
+
+1999-12-12 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 4:1:0
+
+1999-12-06 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 4:0:0
+
+1999-12-05 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in: replace inaddr2str with getnameinfo_verified
+
+ * roken-common.h (INADDR_LOOPBACK): add fallback definition
+
+ * roken-common.h: move getnameinfo_verified to roken.h.in
+ * roken.h.in (inaddr2str): remove
+ * Makefile.am (libroken_la_SOURCES); removed inaddr2str
+ * roken-common.h (getnameinfo_verified): add prototype
+ * getnameinfo_verified.c: new file
+
+1999-12-04 Assar Westerlund <assar@sics.se>
+
+ * roken-common.h: add constants for getaddrinfo, getnameinfo
+ * roken.h.in (socklen_t): make independent of sockaddr_storage
+ (AI_*, NI_*, EAI_*): move to roken-common.h
+
+1999-12-03 Assar Westerlund <assar@sics.se>
+
+ * mini_inetd.c (mini_inted): rewrite to use `getaddrinfo'
+ * getaddrinfo.c (const_v*): no sizeof(sizeof())
+ * getaddrinfo.c (add_hostent): search for the canonical name among
+ all aliases
+ (getaddrinfo): handle AI_NUMERICHOST correctly
+ * Makefile.am (EXTRA_libroken_la_SOURCES): add freeaddinfo,
+ getaddrinfo, getnameinfo, gai_strerror
+ (getaddrinfo_test): add
+ * Makefile.in (SOURCES): add freeaddinfo, getaddrinfo,
+ getnameinfo, gai_strerror
+ (getaddrinfo_test): add
+ * roken.h.in: arpa/inet.h: include
+ (socklen_t): add
+ (struct addrinfo): add
+ (EAI_*): add
+ (NI_*): add
+ (AI_*): add
+ (getaddrinfo, getnameinfo, freeaddrinfo, gai_strerror): add
+ * getnameinfo.c: new file
+ * getaddrinfo-test.c: new file
+ * gai_strerror.c: new file
+ * getaddrinfo.c: new file
+ * freeaddrinfo.c: new file
+
+1999-11-25 Assar Westerlund <assar@sics.se>
+
+ * getopt.c (getopt): return -1 instead of EOF. From
+ <art@stacken.kth.se>
+
+1999-11-13 Assar Westerlund <assar@sics.se>
+
+ * strftime.c (strftime): handle `%z' and `%Z' in a tm_gmtoff-less
+ world
+
+ * getcap.c: make sure to use db only if we have both the library
+ and the header file
+
+1999-11-12 Assar Westerlund <assar@sics.se>
+
+ * getarg.h: add arg_counter
+ * getarg.c: add a new type of argument: `arg_counter' re-organize
+ the code somewhat
+
+ * Makefile.am: add strptime and strpftime-test
+
+ * snprintf.c (xyzprintf): try to do the right thing with an % at
+ the end of the format string
+
+ * strptime.c (strptime): implement '%U', '%V', '%W'
+ * strftime.c (strftime): implement '%U', '%V', '%W', '%z'
+
+ * strftime.c (strftime): correct %E and %O handling. do something
+ reasonable with "...%"
+
+ * strftime.c: replace the BSD implementation by one of our own
+ coding
+
+ * strptime.c : new file
+ * strpftime-test.c: new file
+
+1999-11-07 Assar Westerlund <assar@sics.se>
+
+ * parse_bytes-test.c: new file
+
+ * Makefile.am: add parse_bytes-test
+
+ * parse_units.c (parse_something): try to handle the case of no
+ value specified a little bit better
+
+1999-11-04 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 3:2:0
+
+1999-10-30 Assar Westerlund <assar@sics.se>
+
+ * snprintf.c (PARSE_INT_FORMAT): add redundant casts to work
+ around a gcc-bug that manifests itself on Linux-PPC. From Tom
+ Rini <trini@kernel.crashing.org>
+
+1999-10-28 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump version to 3:1:0
+
+ * roken.h.in: use `unsigned char' instead of `u_int8_t' to avoid
+ having to have that definition. this is the easy way out instead
+ of getting the definition here where it's needed. flame me.
+
+Fri Oct 22 15:39:31 1999 Bjoern Groenvall <bg@sics.se>
+
+ * k_getpwuid.c (k_getpwuid): getspuid() does not exist (even
+ though it should), use getspnam().
+
+1999-10-20 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 3:0:0
+
+1999-10-18 Johan Danielsson <joda@pdc.kth.se>
+
+ * getarg.3: document arg_collect
+
+ * getarg.c: change the way arg_collect works; it's still quite
+ horrible though
+
+ * getarg.h: change type of the collect function
+
+1999-10-17 Assar Westerlund <assar@sics.se>
+
+ * xdbm.h: undo last commit
+
+ * xdbm.h: reorder db includes
+
+1999-10-10 Assar Westerlund <assar@sics.se>
+
+ * socket.c: const-ize and comment
+
+ * net_write.c: const-ize
+
+ * base64.c: const-ize
+
+1999-10-06 Assar Westerlund <assar@sics.se>
+
+ * getarg.c (getarg): also set optind when returning error
+
+1999-09-26 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: add parse_bytes.[ch]
+
+1999-09-24 Johan Danielsson <joda@pdc.kth.se>
+
+ * getarg.3: getarg manpage
+
+ * getarg.{c,h}: add a callback type to do more complicated processing
+
+ * getarg.{c,h}: add floating point support
+
+1999-09-16 Assar Westerlund <assar@sics.se>
+
+ * strlcat.c (strlcat): call strlcpy
+
+ * strlcpy.c: update name and prototype
+
+ * strlcat.c: update name and prototype
+
+ * roken.h.in: rename strc{py,at}_truncate to strlc{py,at}
+
+ * Makefile.am: rename strc{py,at}_truncate -> strlc{py,at}
+
+ * Makefile.in: rename strc{py,at}_truncate -> strlc{py,at}
+
+ * strcpy_truncate.c (strcpy_truncate): change return value to be
+ the length of `src'
+
+1999-08-16 Assar Westerlund <assar@sics.se>
+
+ * getcap.c: try to make this work on systems with DB
+
+1999-08-16 Johan Danielsson <joda@pdc.kth.se>
+
+ * getcap.c: protect from db-less systems
+
+1999-08-09 Johan Danielsson <joda@pdc.kth.se>
+
+ * simple_exec.c: add simple_exec{ve,le}
+
+ * getcap.c: getcap from NetBSD
+
+1999-08-06 Assar Westerlund <assar@sics.se>
+
+ * roken.h.in (sockaddr_storage): cater for those that have
+ v6-support also
+
+1999-08-05 Assar Westerlund <assar@sics.se>
+
+ * inet_ntop.c (inet_ntop_v4): remember to call ntohl
+
+1999-08-04 Assar Westerlund <assar@sics.se>
+
+ * roken-common.h: add shutdown constants
+
+ * mini_inetd.c (listen_v4, listen_v6): handle the case of the
+ protocol not being supported
+
+1999-08-01 Assar Westerlund <assar@sics.se>
+
+ * mini_inetd.c (socket_set_reuseaddr): remove duplicate
+
+1999-07-29 Assar Westerlund <assar@sics.se>
+
+ * mini_inetd.c (mini_inetd): fix my stupid bugs
+
+1999-07-28 Assar Westerlund <assar@sics.se>
+
+ * roken-common.h: add socket* functions
+
+ * Makefile.am (libroken_la_SOURCES): add socket.c
+
+ * socket.c: new file, originally from appl/ftp/common
+
+ * Makefile.am: set version to 2:0:2
+
+ * roken.h.in (inet_pton): add prototype
+
+ * Makefile.am (EXTRA_libroken_la_SOURCES): add inet_pton
+
+ * inet_pton.c: new file
+
+ * getipnodebyname.c (getipnodebyname): try gethostbyname2 if we
+ have it
+
+1999-07-27 Assar Westerlund <assar@sics.se>
+
+ * mini_inetd.c: support IPv6
+
+1999-07-26 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 1:0:1
+
+ * roken.h.in (inet_ntop): add prototype
+
+ * roken-common.h: (INET{,6}_ADDRSTRLEN): add
+
+ * inet_ntop.c: new file
+
+ * Makefile.am (EXTRA_libroken_la_SOURCES): add inet_ntop.c
+
+ * Makefile.am: move some files from libroken_la_SOURCES to
+ EXTRA_libroken_la_SOURCES
+
+ * snprintf.c: some signed vs unsigned casts
+
+1999-07-24 Assar Westerlund <assar@sics.se>
+
+ * roken.h.in (struct sockaddr_storage): define it needed
+
+1999-07-19 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libroken_la_SOURCES): add copyhostent.c,
+ freehostent.c, getipnodebyname.c, getipnodebyaddr.c
+
+ * roken.h.in: <netdb.h>: include
+ (copyhostent, freehostent, getipnodebyname, getipnodebyaddr): add
+ prototypes
+
+ * roken-common.h: new constants for getipnodeby*
+
+ * Makefile.in (SOURCES): add freehostent, copyhostent,
+ getipnodebyname, getipnodebyaddr
+
+ * freehostent.c: new file
+
+ * copyhostent.c: new file
+
+ * getipnodebyaddr.c: new file
+
+ * getipnodebyname.c: new file
+
+1999-07-13 Assar Westerlund <assar@sics.se>
+
+ * roken.h.in (k_getpwnam): update prototype
+
+ * k_getpwnam.c (k_getpwnam): const-ize
+
+ * get_default_username.c (get_default_username): a better way of
+ guessing when the user has su:ed
+
+1999-07-08 Johan Danielsson <joda@pdc.kth.se>
+
+ * roken.awk: use puts, as suggested by Jeffrey Hutzelman
+ <jhutz+@cmu.edu>
+
+1999-07-06 Assar Westerlund <assar@sics.se>
+
+ * readv.c (readv): typo
+
+1999-07-03 Assar Westerlund <assar@sics.se>
+
+ * writev.c (writev): error check malloc properly
+
+ * sendmsg.c (sendmsg): error check malloc properly
+
+ * resolve.c (parse_reply): error check malloc properly
+
+ * recvmsg.c (recvmsg): error check malloc properly
+
+ * readv.c (readv): error check malloc properly
+
+1999-06-23 Assar Westerlund <assar@sics.se>
+
+ * parse_units.c (acc_units): move the special case of 0 -> 1 to
+ parse_something to avoid having it happen at the end of the string
+
+1999-06-15 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in: add get_default_username
+
+ * get_default_username.c: new file
+
+ * roken.h.in (get_default_username): add prototype
+
+ * Makefile.am: add get_default_username
+
+1999-05-08 Assar Westerlund <assar@sics.se>
+
+ * xdbm.h: also try <db.h> with DB_DBM_HSEARCH == 1
+
+ * strnlen.c (strnlen): update prototype
+
+ * Makefile.am: strndup.c: add
+
+ * Makefile.in: strndup.c: add
+
+ * roken.h.in (strndup): add
+ (strnlen): update prototype
+
+ * strndup.c: new file
+
+Fri Apr 16 17:59:30 1999 Assar Westerlund <assar@sics.se>
+
+ * roken.h.in: include strsep prototype if needed
+
+Thu Apr 15 14:04:03 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: make make-print-version.o depend on version.h
+
+Wed Apr 7 14:11:00 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: make it compile w/o krb4
+
+Sat Mar 27 17:33:03 1999 Johan Danielsson <joda@blubb.pdc.kth.se>
+
+ * snprintf.c (vasnprintf): correct check if realloc returns NULL
+
+Sat Mar 27 12:37:55 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: link print_version with -ldes to avoid unresolved
+ references if -lkrb is shared
+
+Sat Mar 20 03:42:30 1999 Assar Westerlund <assar@sics.se>
+
+ * roken-common.h (eread, ewrite): add
+
+ * simple_exec.c: add <roken.h>
+
+Fri Mar 19 21:29:58 1999 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in: add eread, ewrite
+
+ * eread.c, ewrite.c: new files
+
+ * Makefile.am (libroken_la_SOURCES): add eread and ewrite
+
+Fri Mar 19 14:52:57 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: add version-info
+
+Thu Mar 18 12:53:32 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: remove include_dir hack
+
+ * Makefile.am: parse_units.h
+
+ * Makefile.am: include Makefile.am.common
+
+Sat Mar 13 23:31:35 1999 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (SOURCES): add glob.c
+
+Thu Mar 11 15:02:21 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * iruserok.c: move innetgr() to separate file
+
+ * innetgr.c: move innetgr() to separate file
+
+ * hstrerror.c (hstrerror): add const to return type
+
+ * erealloc.c: fix types in format string
+
+ * emalloc.c: fix types in format string
+
+Wed Mar 10 16:36:55 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * resolve.c: ugly fix for crays
+
+Mon Mar 8 11:52:20 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * roken.h.in: protos for {un,}setenv
+
+1999-02-16 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (SOURCES): add fnmatch
+
+ * roken-common.h (abs): add
+
+Sat Feb 13 17:12:53 1999 Assar Westerlund <assar@sics.se>
+
+ * emalloc.c, erealloc.c, estrup.c: new files
+
+ * roken.h.in (mkstemp, gethostname): also includes prototypes if
+ they are needed.
+
+1998-12-23 Assar Westerlund <assar@sics.se>
+
+ * roken.h.in: mkstemp: add prototype
+
+1998-12-20 Assar Westerlund <assar@sics.se>
+
+ * snprintf.c, iruserok.c, parse-units.c: unsigned char-correctness
+
+ * roken.h.in (inet_aton): also chedk NEED_INET_ATON_PROTO
+
+ * roken-common.h: __attribute__: check for autoconf'd
+ HAVE___ATTRIBUTE__ instead of GNUC
+
+Sun Dec 6 19:53:21 1998 Assar Westerlund <assar@sics.se>
+
+ * parse_units.c (parse_something): func is called with val == 0 if
+ no unit was given
+ (acc_flags, acc_units): update to new standard
+
+Fri Nov 27 03:09:42 1998 Assar Westerlund <assar@sics.se>
+
+ * resolve.c (stot): constify
+ (type_to_string): always declare
+ (dns_lookup_int): correct debug output
+
+Thu Nov 26 23:43:55 1998 Assar Westerlund <assar@sics.se>
+
+ * resolve.c (dns_lookup_int): send rr_class to res_search
+
+Thu Nov 26 17:09:47 1998 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * resolve.c: some cleanup
+
+ * resolve.h: add T_NAPTR
+
+Sun Nov 22 10:23:07 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (WFLAGS): set
+
+ * k_getpwnam.c (k_getpwnam): check for `struct spwd'
+
+ * k_getpwuid.c (k_getpwuid): check for `struct spwd'
+
+Tue Sep 8 05:18:31 1998 Assar Westerlund <assar@sics.se>
+
+ * recvmsg.c (recvmsg): patch from bpreece@unity.ncsu.edu
+
+Fri Sep 4 16:29:27 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * vsyslog.c: asprintf -> vasprintf
+
+Tue Aug 18 22:25:52 1998 Assar Westerlund <assar@sics.se>
+
+ * getarg.h (arg_printusage): new signature
+
+ * getarg.c (arg_printusage): new parameter `progname'. NULL means
+ __progname.
+
+Sun Aug 9 14:53:44 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * Makefile.am: net_{read,write}.c
+
+Fri Jul 24 21:56:02 1998 Assar Westerlund <assar@sics.se>
+
+ * simple_exec.c (simple_execvp): loop around waitpid when errno ==
+ EINTR
+
+Thu Jul 23 20:24:35 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * Makefile.am: net_{read,write}.c
+
+Wed Jul 22 21:38:35 1998 Assar Westerlund <assar@sics.se>
+
+ * simple_exec.c (simple_execlp): initialize `argv'
+
+Mon Jul 13 23:01:22 1998 Assar Westerlund <assar@sics.se>
+
+ * inaddr2str.c (inaddr2str): don't advance hostent->h_addr_list,
+ use a copy instead
+
+Fri Jul 10 01:20:08 1998 Assar Westerlund <assar@sics.se>
+
+ * roken.h.in (net_write, net_read): add prototypes
+
+ * Makefile.in: net_{read,write}.c: add
+
+ * net_{read,write}.c: new files
+
+Tue Jun 30 17:29:09 1998 Assar Westerlund <assar@sics.se>
+
+ * roken.h.in (issuid): add
+
+ * get_window_size.c: fix misspelling of TIOCGWINSZ and bad use of
+ fields
+
+Sun May 31 03:24:34 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * getarg.c (mandoc_template): Put short and long options in
+ SYNOPSIS within the same [ ] pair.
+
+Sat May 30 00:13:01 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * getarg.c (arg_printusage): try to keep options shorter than
+ column width
+
+ * get_window_size.c (get_window_size): check COLUMNS and LINES
+
+Fri May 29 00:05:04 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * getarg.c (mandoc_template): Put short and long options in
+ DESCRIPTION on the same line.
+
+ * getarg.c (arg_match_long): make sure you only get an exact match
+ if the strings are the same length
+
+Thu May 14 02:23:40 1998 Assar Westerlund <assar@sics.se>
+
+ * roken.awk: stupid cray awk wants \#
+
+Fri May 1 01:29:36 1998 Assar Westerlund <assar@sics.se>
+
+ * print_version.c (print_version): according to ISO/ANSI C the
+ elements of `arg' are not constant and therefore not settable at
+ compile-time. Set the at run-time instead.
+
+Sun Apr 19 10:00:06 1998 Assar Westerlund <assar@sics.se>
+
+ * roken.h.in: include paths.h
+
+Sun Apr 5 12:30:49 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (SOURCES): add roken_gethostby.c to make solaris
+ make happy
+
+Thu Mar 19 20:41:25 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * simple_exec.c: Simple fork+exec system() replacement.
+
+Fri Mar 6 00:21:53 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * roken_gethostby.c: Make `roken_gethostby_setup' take URL-like
+ specification instead of split up versions. Makes it easier for
+ calling applications.
+
+ * roken_gethostby.c: Another miracle of the 20th century:
+ gethostby* over HTTP.
+
+Sat Feb 21 15:18:36 1998 assar westerlund <assar@sics.se>
+
+ * parse_time.c (unparse_time_approx): new function that calls
+ `unparse_units_approx'
+
+ * parse_units.c (unparse_units_approx): new function that will
+ only print the first unit.
+
+ * Makefile.in: include parse_{time,units}
+
+Thu Feb 12 03:30:08 1998 Assar Westerlund <assar@sics.se>
+
+ * parse_time.c (print_time_table): don't return a void value.
+
+Tue Feb 3 11:06:24 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * getarg.c (mandoc_template): Change date format to full month
+ name, and day of month without leading zero.
+
+Thu Jan 22 21:23:23 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * getarg.c: Fix long form of negative flags.
+
+Mon Dec 29 23:31:10 1997 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * roken.h.in: Include <err.h>, to get linux __progname.
+
+Sun Dec 21 09:45:18 1997 Assar Westerlund <assar@sics.se>
+
+ * parse_time.c (print_time_table): new function
+
+ * parse_units.c (print_flags_table, print_units_table): new
+ functions.
+
+Thu Dec 4 02:51:46 1997 Assar Westerlund <assar@sics.se>
+
+ * iruserok.c: moved here.
+
+ * snprintf.c (sn_append_char): don't write any terminating zero.
+ (as_reserve): don't loop. better heuristic for how much space to
+ realloc.
+ (vasnprintf): simplify initializing to one.
+
+Sun Nov 30 14:56:59 1997 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * getarg.c: Add mandoc help back-end to getarg.
+
+Wed Nov 12 01:09:17 1997 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * verr.c, verrx.c: Fix warnings by moving exit from.
+
+Tue Nov 11 21:12:09 1997 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * parse_units.c: Change the list of separating characters (between
+ units) to comma, space, and tab, removing digits. Having digits in
+ this list makes a flag like `T42 generate a parse error. This
+ change makes `17m3s' an invalid time-spec (you need a space).
+
+Tue Nov 11 02:38:44 1997 Assar Westerlund <assar@sics.se>
+
+ * roken.h: add <sys/socket.h>
+
+Sun Nov 9 04:48:46 1997 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * fnmatch.c: Add fnmatch from NetBSD
+
+Sun Nov 9 02:00:08 1997 Assar Westerlund <assar@sics.se>
+
+ * parse_units.c (parse_something): ignore white-space and ','
+
+Mon Nov 3 22:38:32 1997 Assar Westerlund <assar@sics.se>
+
+ * roken.h: fclose prototype
+
+ * roken.h: add prototype for vsyslog
+
+ * Makefile.in: add some more source files to make soriasis make
+ happy
+
+Sat Nov 1 00:19:21 1997 Assar Westerlund <assar@sics.se>
+
+ * roken.h: include <sys/uio.h> and <errno.h>.
+ prototypes for readv and writev
+
+ * readv.c, writev.c: new files
+
+Wed Oct 29 02:21:38 1997 Assar Westerlund <assar@sics.se>
+
+ * roken.h: Add ugly macros for openlog, gethostbyname,
+ gethostbyaddr, and getservbyname for the benefit of Crays. Add
+ default definition of MAXPATHLEN
diff --git a/third_party/heimdal/lib/roken/Makefile.am b/third_party/heimdal/lib/roken/Makefile.am
new file mode 100644
index 0000000..35d7532
--- /dev/null
+++ b/third_party/heimdal/lib/roken/Makefile.am
@@ -0,0 +1,290 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+ACLOCAL_AMFLAGS = -I ../../cf
+
+CLEANFILES = roken.h make-roken.c $(XHEADERS)
+
+lib_LTLIBRARIES = libroken.la
+
+libroken_la_LDFLAGS = -version-info 20:0:1
+libroken_la_CPPFLAGS = -DBUILD_ROKEN_LIB
+
+if versionscript
+libroken_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+endif
+
+AM_CPPFLAGS += $(libroken_la_CPPFLAGS)
+if HAVE_DBHEADER
+AM_CPPFLAGS += -I$(DBHEADER)
+endif
+
+bin_PROGRAMS = rkvis rkbase32 rkbase64
+noinst_PROGRAMS = snprintf-test resolve-test rkpty test-detach test-auxval rtbl timeval
+
+CHECK_LOCAL = snprintf-test resolve-test rkpty make-roken
+
+check_PROGRAMS = \
+ base32-test \
+ base64-test \
+ getaddrinfo-test \
+ getifaddrs-test \
+ hex-test \
+ test-auxval \
+ test-getuserinfo \
+ test-readenv \
+ resolve-test \
+ parse_bytes-test \
+ parse_reply-test \
+ parse_time-test \
+ snprintf-test \
+ strpftime-test \
+ timeval \
+ tsearch-test
+
+TESTS = $(check_PROGRAMS)
+
+LDADD = libroken.la
+make_roken_LDADD =
+
+noinst_LTLIBRARIES = libtest.la
+libtest_la_SOURCES = strftime.c strptime.c snprintf.c tsearch.c
+libtest_la_CFLAGS = -DTEST_SNPRINTF -DTEST_STRPFTIME
+
+parse_reply_test_SOURCES = parse_reply-test.c resolve.c
+parse_reply_test_CFLAGS = -DTEST_RESOLVE
+
+test_readenv_SOURCES = test-readenv.c test-mem.c
+test_auxval_SOURCES = test-auxval.c
+test_getuserinfo_SOURCES = test-getuserinfo.c
+test_getuserinfo_LDADD = libtest.la $(LDADD)
+
+if have_err_h
+err_h =
+else
+err_h = err.h
+endif
+
+if have_fnmatch_h
+fnmatch_h =
+else
+fnmatch_h = fnmatch.h
+endif
+
+if have_ifaddrs_h
+ifaddrs_h =
+else
+ifaddrs_h = ifaddrs.h
+endif
+
+if have_search_h
+search_h =
+else
+search_h = search.h
+endif
+
+if have_vis_h
+vis_h =
+else
+vis_h = vis.h
+endif
+
+timeval_SOURCES = timeval.c
+timeval_CPPFLAGS = -DTEST
+
+rkvis_SOURCES = vis.c $(vis_h) vis-extras.h
+rkvis_CPPFLAGS = -DTEST
+
+rkbase32_SOURCES = base32.c
+rkbase32_CPPFLAGS = -DTEST
+
+rkbase64_SOURCES = base64.c
+rkbase64_CPPFLAGS = -DTEST
+
+rtbl_SOURCES = rtbl.c
+rtbl_CPPFLAGS = -DTEST
+
+test_detach_SOURCES = test-detach.c
+
+rkpty_LDADD = $(LIB_openpty) $(LDADD)
+
+parse_time_test_SOURCES = parse_time-test.c test-mem.c
+
+strpftime_test_SOURCES = strpftime-test.c strpftime-test.h
+strpftime_test_LDADD = libtest.la $(LDADD)
+strpftime_test_CFLAGS = -DTEST_STRPFTIME
+snprintf_test_SOURCES = snprintf-test.c
+snprintf_test_LDADD = libtest.la $(LDADD)
+snprintf_test_CFLAGS = -DTEST_SNPRINTF
+tsearch_test_SOURCES = tsearch-test.c
+tsearch_test_LDADD = libtest.la $(LDADD)
+tsearch_test_CFLAGS = -DTEST_TSEARCH
+
+resolve_test_SOURCES = resolve-test.c
+
+libroken_la_SOURCES = \
+ base32.c \
+ base64.c \
+ bswap.c \
+ concat.c \
+ cloexec.c \
+ clz.c \
+ ct.c \
+ detach.c \
+ doxygen.c \
+ dumpdata.c \
+ environment.c \
+ eread.c \
+ esetenv.c \
+ ewrite.c \
+ fseeko.c \
+ ftello.c \
+ getaddrinfo_hostspec.c \
+ get_window_size.c \
+ getarg.c \
+ getauxval.c \
+ getauxval.h \
+ getnameinfo_verified.c \
+ getprogname.c \
+ getuserinfo.c \
+ h_errno.c \
+ hex.c \
+ hostent_find_fqdn.c \
+ issuid.c \
+ memmem.c \
+ mini_inetd.c \
+ mkdir.c \
+ mkdtemp.c \
+ mkostemp.c \
+ net_read.c \
+ net_write.c \
+ parse_bytes.c \
+ parse_time.c \
+ parse_units.c \
+ qsort.c \
+ rand.c \
+ realloc.c \
+ resolve.c \
+ roken_gethostby.c \
+ rtbl.c \
+ rtbl.h \
+ secure_getenv.c \
+ secure_getenv.h \
+ setprogname.c \
+ signal.c \
+ simple_exec.c \
+ snprintf.c \
+ socket.c \
+ strcollect.c \
+ strerror_r.c \
+ strpool.c \
+ timeval.c \
+ tm2time.c \
+ unvis.c \
+ vis.c \
+ $(vis_h) \
+ vis-extras.h \
+ warnerr.c \
+ write_pid.c \
+ xfree.c \
+ xdbm.h
+
+EXTRA_libroken_la_SOURCES = \
+ err.hin \
+ fnmatch.hin \
+ ifaddrs.hin \
+ search.hin \
+ vis.hin
+
+libroken_la_LIBADD = @LTLIBOBJS@ $(LIB_crypt) $(LIB_pidfile)
+
+$(LTLIBOBJS) $(libroken_la_OBJECTS): roken.h $(XHEADERS)
+
+BUILT_SOURCES = roken.h $(err_h) $(fnmatch_h) $(ifadds_h) $(search_h) $(vis_h)
+
+## these are controlled by configure
+XHEADERS = $(err_h) $(fnmatch_h) $(ifaddrs_h) $(search_h) $(vis_h)
+CLEANFILES += err.h fnmatch.h ifaddrs.h search.h vis.h
+
+dist_include_HEADERS = \
+ base32.h \
+ base64.h \
+ getarg.h \
+ hex.h \
+ parse_bytes.h \
+ parse_time.h \
+ parse_units.h \
+ resolve.h \
+ roken-common.h \
+ rtbl.h \
+ xdbm.h
+
+if have_socket_wrapper
+libroken_la_SOURCES += socket_wrapper.c socket_wrapper.h
+dist_include_HEADERS += socket_wrapper.h
+endif
+
+build_HEADERZ = test-mem.h $(XHEADERS)
+
+nodist_include_HEADERS = roken.h
+rokenincludedir = $(includedir)/roken
+nodist_rokeninclude_HEADERS = $(XHEADERS)
+
+man_MANS = getarg.3 parse_time.3 rtbl.3 ecalloc.3
+
+SUFFIXES += .hin
+.hin.h:
+ cp $< $@
+
+# Make make-roken deprecated in 1.4 when we know that roken-h-process.pl works
+if !CROSS_COMPILE
+
+noinst_PROGRAMS += make-roken
+BUILT_SOURCES += make-roken.c
+
+nodist_make_roken_SOURCES = make-roken.c
+
+roken.h: make-roken$(EXEEXT)
+ @./make-roken$(EXEEXT) > tmp.h ;\
+ if [ -f roken.h ] && cmp -s tmp.h roken.h ; then rm -f tmp.h ; \
+ else rm -f roken.h; mv tmp.h roken.h; fi
+
+make-roken.c: roken.h.in roken.awk
+ $(AWK) -f $(srcdir)/roken.awk $(srcdir)/roken.h.in > make-roken.c
+
+else
+
+roken.h: $(top_srcdir)/cf/roken-h-process.pl roken.h.in
+ perl $(top_srcdir)/cf/roken-h-process.pl \
+ -c $(top_builddir)/include/config.h \
+ -p $(srcdir)/roken.h.in -o roken.h
+
+endif
+
+
+EXTRA_DIST = \
+ NTMakefile \
+ roken.awk roken.h.in \
+ $(man_MANS) \
+ dirent.c \
+ dirent.hin \
+ dirent-test.c \
+ dlfcn.hin \
+ dlfcn_w32.c \
+ getifaddrs_w32.c \
+ ndbm_wrap.c \
+ ndbm_wrap.h \
+ rename.c \
+ simple_exec_w32.c \
+ sleep.c \
+ sockstartup_w32.c \
+ stdbool.hin \
+ stdint.hin \
+ syslogc.c \
+ syslog.hin \
+ test-auxval.c \
+ test-mem.h \
+ test-mini_inetd.c \
+ win32_alloc.c \
+ version-script.map
diff --git a/third_party/heimdal/lib/roken/NTMakefile b/third_party/heimdal/lib/roken/NTMakefile
new file mode 100644
index 0000000..5749efd
--- /dev/null
+++ b/third_party/heimdal/lib/roken/NTMakefile
@@ -0,0 +1,312 @@
+########################################################################
+#
+# Copyright (c) 2009 - 2017, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\roken
+
+!include ../../windows/NTMakefile.w32
+
+libroken_la_OBJS = \
+ $(OBJ)\base32.obj \
+ $(OBJ)\base64.obj \
+ $(OBJ)\bswap.obj \
+ $(OBJ)\concat.obj \
+ $(OBJ)\cloexec.obj \
+ $(OBJ)\clz.obj \
+ $(OBJ)\ct.obj \
+ $(OBJ)\detach.obj \
+ $(OBJ)\dirent.obj \
+ $(OBJ)\dlfcn_w32.obj \
+ $(OBJ)\dumpdata.obj \
+ $(OBJ)\ecalloc.obj \
+ $(OBJ)\emalloc.obj \
+ $(OBJ)\environment.obj \
+ $(OBJ)\eread.obj \
+ $(OBJ)\erealloc.obj \
+ $(OBJ)\err.obj \
+ $(OBJ)\errx.obj \
+ $(OBJ)\esetenv.obj \
+ $(OBJ)\estrdup.obj \
+ $(OBJ)\ewrite.obj \
+ $(OBJ)\flock.obj \
+ $(OBJ)\fnmatch.obj \
+ $(OBJ)\fseeko.obj \
+ $(OBJ)\ftello.obj \
+ $(OBJ)\getauxval.obj \
+ $(OBJ)\getaddrinfo_hostspec.obj \
+ $(OBJ)\get_window_size.obj \
+ $(OBJ)\getarg.obj \
+ $(OBJ)\getifaddrs_w32.obj \
+ $(OBJ)\getnameinfo_verified.obj \
+ $(OBJ)\getopt.obj \
+ $(OBJ)\getprogname.obj \
+ $(OBJ)\gettimeofday.obj \
+ $(OBJ)\getuserinfo.obj \
+ $(OBJ)\hex.obj \
+ $(OBJ)\hostent_find_fqdn.obj \
+ $(OBJ)\inet_aton.obj \
+ $(OBJ)\issuid.obj \
+ $(OBJ)\localtime_r.obj \
+ $(OBJ)\lstat.obj \
+ $(OBJ)\memmem.obj \
+ $(OBJ)\memset_s.obj \
+ $(OBJ)\mergesort_r.obj \
+ $(OBJ)\mkdir.obj \
+ $(OBJ)\mini_inetd.obj \
+ $(OBJ)\mkdtemp.obj \
+ $(OBJ)\mkstemp.obj \
+ $(OBJ)\mkostemp.obj \
+ $(OBJ)\net_read.obj \
+ $(OBJ)\net_write.obj \
+ $(OBJ)\parse_bytes.obj \
+ $(OBJ)\parse_time.obj \
+ $(OBJ)\parse_units.obj \
+ $(OBJ)\realloc.obj \
+ $(OBJ)\rename.obj \
+ $(OBJ)\resolve.obj \
+ $(OBJ)\rand.obj \
+ $(OBJ)\roken_gethostby.obj \
+ $(OBJ)\rtbl.obj \
+ $(OBJ)\secure_getenv.obj \
+ $(OBJ)\sendmsg.obj \
+ $(OBJ)\setenv.obj \
+ $(OBJ)\setprogname.obj \
+ $(OBJ)\simple_exec_w32.obj \
+ $(OBJ)\sleep.obj \
+ $(OBJ)\snprintf.obj \
+ $(OBJ)\socket.obj \
+ $(OBJ)\sockstartup_w32.obj \
+ $(OBJ)\strcollect.obj \
+ $(OBJ)\strerror_r.obj \
+ $(OBJ)\strftime.obj \
+ $(OBJ)\strlcat.obj \
+ $(OBJ)\strlcpy.obj \
+ $(OBJ)\strndup.obj \
+ $(OBJ)\strpool.obj \
+ $(OBJ)\strptime.obj \
+ $(OBJ)\strsep.obj \
+ $(OBJ)\strsep_copy.obj \
+ $(OBJ)\strtok_r.obj \
+ $(OBJ)\strtoll.obj \
+ $(OBJ)\strtoull.obj \
+ $(OBJ)\syslogc.obj \
+ $(OBJ)\timegm.obj \
+ $(OBJ)\timeval.obj \
+ $(OBJ)\tm2time.obj \
+ $(OBJ)\tsearch.obj \
+ $(OBJ)\unvis.obj \
+ $(OBJ)\verr.obj \
+ $(OBJ)\verrx.obj \
+ $(OBJ)\vis.obj \
+ $(OBJ)\vwarn.obj \
+ $(OBJ)\vwarnx.obj \
+ $(OBJ)\warn.obj \
+ $(OBJ)\warnerr.obj \
+ $(OBJ)\warnx.obj \
+ $(OBJ)\win32_alloc.obj \
+ $(OBJ)\win32_version.obj \
+ $(OBJ)\writev.obj \
+ $(OBJ)\xfree.obj
+
+!if $(NMAKE_WINVER) < 0x0600
+libroken_la_OBJS=$(libroken_la_OBJS) \
+ $(OBJ)\inet_ntop.obj \
+ $(OBJ)\inet_pton.obj
+!endif
+
+{}.c{$(OBJ)}.obj::
+ $(C2OBJ_P) -DBUILD_ROKEN_LIB
+
+$(LIBROKEN): $(libroken_la_OBJS)
+ $(LIBCON_C) -out:$@ @<<
+$(**: =
+)
+<<
+
+$(OBJ)\make-roken.exe: $(OBJ)\make-roken.obj
+ $(EXECONLINK)
+
+$(OBJ)\make-roken.c: roken.h.in roken.awk $(INCDIR)\config.h
+ $(AWK) -f roken.awk roken.h.in > $(OBJ)\make-roken.c || $(RM) $(OBJ)\make-roken.c
+
+$(INCDIR)\roken.h: $(OBJ)\make-roken.exe
+ $(OBJ)\make-roken.exe > $@ || $(RM) $@
+
+INCFILES = \
+ $(INCDIR)\base32.h \
+ $(INCDIR)\base64.h \
+ $(INCDIR)\dirent.h \
+ $(INCDIR)\dlfcn.h \
+ $(INCDIR)\err.h \
+ $(INCDIR)\fnmatch.h \
+ $(INCDIR)\getarg.h \
+ $(INCDIR)\hex.h \
+ $(INCDIR)\ifaddrs.h \
+ $(INCDIR)\parse_bytes.h \
+ $(INCDIR)\parse_time.h \
+ $(INCDIR)\parse_units.h \
+ $(INCDIR)\resolve.h \
+ $(INCDIR)\roken.h \
+ $(INCDIR)\roken-common.h \
+ $(INCDIR)\rtbl.h \
+ $(INCDIR)\search.h \
+ $(INCDIR)\stdbool.h \
+ $(INCDIR)\syslog.h \
+ $(INCDIR)\vis.h \
+ $(INCDIR)\vis-extras.h \
+!ifndef HAVE_STDINT_H
+ $(INCDIR)\stdint.h \
+!endif
+ $(INCDIR)\versionsupport.h \
+ $(INCDIR)\xdbm.h
+
+clean::
+ -$(RM) $(XHEADERS)
+
+all:: $(INCFILES) $(LIBROKEN)
+
+clean::
+ -$(RM) $(LIBROKEN)
+
+TMP_PROGS = $(OBJ)\snprintf-test.exe $(OBJ)\resolve-test.exe $(OBJ)\test-getuserinfo.exe
+
+# Tests
+
+TEST_PROGS = \
+ $(OBJ)\base32-test.exe \
+ $(OBJ)\base64-test.exe \
+ $(OBJ)\getaddrinfo-test.exe \
+ $(OBJ)\getifaddrs-test.exe \
+ $(OBJ)\hex-test.exe \
+ $(OBJ)\test-detach.exe \
+ $(OBJ)\test-getuserinfo.exe \
+ $(OBJ)\test-readenv.exe \
+ $(OBJ)\parse_bytes-test.exe \
+ $(OBJ)\parse_reply-test.exe \
+ $(OBJ)\parse_time-test.exe \
+ $(OBJ)\snprintf-test.exe \
+ $(OBJ)\strpftime-test.exe \
+ $(OBJ)\dirent-test.exe \
+ $(OBJ)\test-mini_inetd.exe
+
+$(OBJ)\strftime_test.obj: strftime.c
+ $(C2OBJ) -DTEST_SNPRINTF -DTEST_STRPFTIME -DBUILD_ROKEN_LIB
+
+$(OBJ)\strptime_test.obj: strptime.c
+ $(C2OBJ) -DTEST_SNPRINTF -DTEST_STRPFTIME -DBUILD_ROKEN_LIB
+
+$(OBJ)\snprintf_test.obj: snprintf.c
+ $(C2OBJ) -DTEST_SNPRINTF -DTEST_STRPFTIME -DBUILD_ROKEN_LIB
+
+$(OBJ)\libtest.lib: $(OBJ)\strftime_test.obj $(OBJ)\strptime_test.obj $(OBJ)\snprintf_test.obj
+ $(LIBCON)
+
+$(OBJ)\parse_reply-test.obj: parse_reply-test.c
+ $(C2OBJ) -DTEST_RESOLVE -DBUILD_ROKEN_LIB
+
+$(OBJ)\resolve_test.obj: resolve.c
+ $(C2OBJ) -DTEST_RESOLVE -DBUILD_ROKEN_LIB
+
+$(OBJ)\parse_reply-test.exe: $(OBJ)\parse_reply-test.obj $(OBJ)\resolve_test.obj $(LIBROKEN)
+ $(EXECONLINK) DnsAPI.lib
+
+$(OBJ)\test-readenv.exe: $(OBJ)\test-readenv.obj $(OBJ)\test-mem.obj $(LIBROKEN)
+ $(EXECONLINK)
+
+$(OBJ)\parse_time-test.exe: $(OBJ)\parse_time-test.obj $(OBJ)\test-mem.obj $(LIBROKEN)
+ $(EXECONLINK)
+
+$(OBJ)\strpftime-test.obj: strpftime-test.c
+ $(C2OBJ) -DTEST_STRPFTIME -DBUILD_ROKEN_LIB
+
+$(OBJ)\strpftime-test.exe: $(OBJ)\strpftime-test.obj $(OBJ)\libtest.lib $(LIBROKEN)
+ $(EXECONLINK)
+
+$(OBJ)\snprintf-test.obj: snprintf-test.c
+ $(C2OBJ) -DTEST_SNPRINTF -DBUILD_ROKEN_LIB
+
+$(OBJ)\snprintf-test.exe: $(OBJ)\snprintf-test.obj $(OBJ)\libtest.lib $(LIBROKEN)
+ $(EXECONLINK)
+
+$(OBJ)\resolve-test.exe: $(OBJ)\resolve-test.obj $(LIBROKEN)
+ $(EXECONLINK) DnsAPI.lib
+
+$(OBJ)\base32-test.exe: $(OBJ)\base32-test.obj $(OBJ)\base32.obj $(LIBROKEN)
+ $(EXECONLINK)
+
+$(OBJ)\base64-test.exe: $(OBJ)\base64-test.obj $(OBJ)\base64.obj $(LIBROKEN)
+ $(EXECONLINK)
+
+$(OBJ)\getaddrinfo-test.exe: $(OBJ)\getaddrinfo-test.obj $(LIBROKEN)
+ $(EXECONLINK)
+
+$(OBJ)\hex-test.exe: $(OBJ)\hex-test.obj $(LIBROKEN)
+ $(EXECONLINK)
+
+$(OBJ)\parse_bytes-test.exe: $(OBJ)\parse_bytes-test.obj $(LIBROKEN)
+ $(EXECONLINK)
+
+$(OBJ)\test-detach.exe: $(OBJ)\test-detach.obj $(OBJ)\detach.obj $(LIBROKEN)
+ $(EXECONLINK)
+
+$(OBJ)\test-getuserinfo.exe: $(OBJ)\test-getuserinfo.obj $(OBJ)\getuserinfo.obj $(LIBROKEN)
+ $(EXECONLINK) Secur32.lib Shell32.lib
+
+$(OBJ)\dirent-test.exe: $(OBJ)\dirent-test.obj $(LIBROKEN)
+ $(EXECONLINK)
+
+$(OBJ)\getifaddrs-test.exe: $(OBJ)\getifaddrs-test.obj $(LIBROKEN)
+ $(EXECONLINK)
+
+$(OBJ)\test-mini_inetd.exe: $(OBJ)\test-mini_inetd.obj $(LIBROKEN)
+ $(EXECONLINK)
+
+test-binaries: $(TEST_PROGS) $(TMP_PROGS)
+
+test-run:
+ cd $(OBJ)
+ -test-mini_inetd.exe
+ -dirent-test.exe
+ -base32-test.exe
+ -base64-test.exe
+ -getaddrinfo-test.exe www.h5l.org http
+ -getifaddrs-test.exe
+ -hex-test.exe
+ -test-readenv.exe
+ -parse_bytes-test.exe
+# Need to rewrite this test:
+# -parse_reply-test.exe
+ -parse_time-test.exe
+ -snprintf-test.exe
+ -strpftime-test.exe
+ cd $(SRCDIR)
+
+test:: test-binaries test-run
+
diff --git a/third_party/heimdal/lib/roken/base32-test.c b/third_party/heimdal/lib/roken/base32-test.c
new file mode 100644
index 0000000..e30c193
--- /dev/null
+++ b/third_party/heimdal/lib/roken/base32-test.c
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include <base32.h>
+
+int
+main(int argc, char **argv)
+{
+ int numerr = 0;
+ int numtest = 1;
+ struct test {
+ int preserve_order;
+ void *data;
+ size_t len;
+ const char *result;
+ } *t, tests[] = {
+ { 0, "", 0 , "" },
+ { 0, "f", 1, "MY======" },
+ { 0, "fo", 2, "MZXQ====" },
+ { 0, "foo", 3, "MZXW6===" },
+ { 0, "foob", 4, "MZXW6YQ=" },
+ { 0, "fooba", 5, "MZXW6YTB" },
+ { 0, "foobar", 6, "MZXW6YTBOI======" },
+ { 1, "", 0 , "" },
+ { 1, "f", 1, "CO======" },
+ { 1, "fo", 2, "CPNG====" },
+ { 1, "foo", 3, "CPNMU===" },
+ { 1, "foob", 4, "CPNMUOG=" },
+ { 1, "fooba", 5, "CPNMUOJ1" },
+ { 1, "foobar", 6, "CPNMUOJ1E8======" },
+ { 0, NULL, 0, NULL }
+ };
+ for(t = tests; t->data; t++) {
+ char *str;
+ int len;
+
+ (void) rk_base32_encode(t->data, t->len, &str, t->preserve_order);
+ if (strcmp(str, t->result) != 0) {
+ fprintf(stderr, "failed test %d: %s != %s\n", numtest,
+ str, t->result);
+ numerr++;
+ }
+ free(str);
+ str = strdup(t->result);
+ len = rk_base32_decode(t->result, str, t->preserve_order);
+ if (len != t->len) {
+ fprintf(stderr, "failed test %d: len %lu != %lu\n", numtest,
+ (unsigned long)len, (unsigned long)t->len);
+ numerr++;
+ } else if(memcmp(str, t->data, t->len) != 0) {
+ fprintf(stderr, "failed test %d: data\n", numtest);
+ numerr++;
+ }
+ free(str);
+ numtest++;
+ }
+
+ {
+ char str[32];
+
+ if (rk_base32_decode("M=M=", str, 1) != -1) {
+ fprintf(stderr, "failed test %d: successful decode of `M=M='\n",
+ numtest++);
+ numerr++;
+ }
+ if (rk_base32_decode("MQ===", str, 1) != -1) {
+ fprintf(stderr, "failed test %d: successful decode of `MQ==='\n",
+ numtest++);
+ numerr++;
+ }
+ }
+ return numerr;
+}
diff --git a/third_party/heimdal/lib/roken/base32.c b/third_party/heimdal/lib/roken/base32.c
new file mode 100644
index 0000000..ef74336
--- /dev/null
+++ b/third_party/heimdal/lib/roken/base32.c
@@ -0,0 +1,315 @@
+/*
+ * Copyright (c) 2020 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#ifdef TEST
+#include <stdio.h>
+#include <getarg.h>
+#include <err.h>
+#endif
+#include "base32.h"
+#include "roken.h"
+
+static const unsigned char base32_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
+static const unsigned char base32op_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_base32_encode(const void *data, int size, char **str, enum rk_base32_flags flags)
+{
+ const unsigned char *chars =
+ (flags & RK_BASE32_FLAG_PRESERVE_ORDER) ? base32op_chars :
+ base32_chars;
+ uint64_t c;
+ char *s, *p;
+ int i;
+ const unsigned char *q;
+
+ if (size > INT_MAX/8 || size < 0) {
+ *str = NULL;
+ errno = ERANGE;
+ return -1;
+ }
+
+ p = s = malloc(((size + 5 - 1) / 5) * 8 + 1);
+ if (p == NULL) {
+ *str = NULL;
+ return -1;
+ }
+ q = (const unsigned char *) data;
+
+ for (i = 0; i < size;) {
+ /* 5 bytes of input will give us 8 output bytes' worth of bits */
+ c = q[i++];
+ c <<= 8;
+ if (i < size)
+ c += q[i];
+ i++;
+ c <<= 8;
+ if (i < size)
+ c += q[i];
+ i++;
+ c <<= 8;
+ if (i < size)
+ c += q[i];
+ i++;
+ c <<= 8;
+ if (i < size)
+ c += q[i];
+ i++;
+ p[0] = chars[(c & 0x00000000f800000000ULL) >> 35];
+ p[1] = chars[(c & 0x0000000007c0000000ULL) >> 30];
+ p[2] = chars[(c & 0x00000000003e000000ULL) >> 25];
+ p[3] = chars[(c & 0x000000000001f00000ULL) >> 20];
+ p[4] = chars[(c & 0x0000000000000f8000ULL) >> 15];
+ p[5] = chars[(c & 0x000000000000007c00ULL) >> 10];
+ p[6] = chars[(c & 0x0000000000000003e0ULL) >> 5];
+ p[7] = chars[(c & 0x00000000000000001fULL) >> 0];
+ switch (i - size) {
+ case 4: p[2] = p[3] = '='; fallthrough;
+ case 3: p[4] = '='; fallthrough;
+ case 2: p[5] = p[6] = '='; fallthrough;
+ case 1: p[7] = '='; fallthrough;
+ default: break;
+ }
+ p += 8;
+ }
+ *p = 0;
+ *str = s;
+ return (int) strlen(s);
+}
+
+#define DECODE_ERROR ((uint64_t)-1)
+
+static int
+pos(char c, int preserve_order)
+{
+ /* EBCDIC need not apply */
+ if (preserve_order) {
+ if (c >= '0' && c <= '9')
+ return c - '0';
+ if (c >= 'A' && c <= 'V')
+ return c - 'A' + ('9' - '0') + 1;
+ } else {
+ if (c >= 'A' && c <= 'Z')
+ return c - 'A';
+ if (c >= '2' && c <= '7')
+ return c - '2' + ('Z' - 'A') + 1;
+ }
+ return -1;
+}
+
+static uint64_t
+token_decode(const char *token, enum rk_base32_flags flags)
+{
+ uint64_t marker = 0;
+ uint64_t val = 0;
+ int preserve_order = !!(flags & RK_BASE32_FLAG_PRESERVE_ORDER);
+ int i, c;
+
+ if (strlen(token) < 8)
+ return DECODE_ERROR;
+ for (i = 0; i < 8; i++) {
+ val <<= 5;
+ if (token[i] == '=')
+ marker++;
+ else if (marker)
+ return DECODE_ERROR;
+ else if ((c = pos(token[i], preserve_order)) == -1 &&
+ (flags & RK_BASE32_FLAG_STOP_ON_GARBAGE))
+ break;
+ else if (c == -1)
+ return DECODE_ERROR;
+ else
+ val |= c;
+ }
+ if (marker > 6)
+ return DECODE_ERROR;
+ return (marker << 40) | val;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_base32_decode(const char *str, void *data, enum rk_base32_flags flags)
+{
+ const char *p;
+ unsigned char *q;
+ int preserve_order = !!(flags & RK_BASE32_FLAG_PRESERVE_ORDER);
+
+ q = data;
+ for (p = str; *p && (*p == '=' || pos(*p, preserve_order) != -1); p += 8) {
+ uint64_t val = token_decode(p, flags);
+ uint64_t marker = (val >> 40) & 0xffULL;
+
+ if (val == DECODE_ERROR) {
+ errno = EINVAL;
+ return -1;
+ }
+ *q++ = (val >> 32) & 0xffULL;
+ if (marker < 6)
+ *q++ = (val >> 24) & 0xffULL;
+ if (marker < 4)
+ *q++ = (val >> 16) & 0xffULL;
+ if (marker < 3)
+ *q++ = (val >> 8) & 0xffULL;
+ if (marker < 1)
+ *q++ = val & 0xffULL;
+ if (marker && !(flags & RK_BASE32_FLAG_INTERIOR_PADDING_OK))
+ break;
+ }
+ if (q - (unsigned char *) data > INT_MAX) {
+ errno = EOVERFLOW;
+ return -1;
+ }
+ return q - (unsigned char *) data;
+}
+
+#ifdef TEST
+static int interior_padding_ok;
+static int preserve_order_flag;
+static int stop_on_garbage;
+static int decode_flag;
+static int help_flag;
+
+/*
+ * The short options are compatible with a subset of the FreeBSD contrib
+ * vis(1). Heimdal additions have long option names only.
+ */
+static struct getargs args[] = {
+ { "preserve-order", 'P', arg_flag, &preserve_order_flag,
+ "Use order-preserving alphabet", NULL },
+ { "interior-padding-ok", 'O', arg_flag, &interior_padding_ok,
+ "Decode concatenated padded base32 strings as one", NULL },
+ { "stop-on-garbage", 'G', arg_flag, &stop_on_garbage,
+ "Do not error on garbage", NULL },
+ { "decode", 'd', arg_flag, &decode_flag, "Decode", NULL },
+ { "help", 'h', arg_flag, &help_flag, "Print help message", NULL },
+};
+static size_t num_args = sizeof(args)/sizeof(args[0]);
+
+int
+main(int argc, char **argv)
+{
+ enum rk_base32_flags flags = 0;
+ unsigned char *buf = NULL;
+ size_t buflen = 0;
+ size_t bufsz = 0;
+ int goptind = 0;
+ int ret;
+
+ setprogname("rkbase32");
+ if (getarg(args, num_args, argc, argv, &goptind) || help_flag) {
+ arg_printusage(args, num_args, NULL, "FILE | -");
+ return help_flag ? 0 : 1;
+ }
+
+ argc -= goptind;
+ argv += goptind;
+
+ flags |= preserve_order_flag ? RK_BASE32_FLAG_PRESERVE_ORDER : 0;
+ flags |= interior_padding_ok ? RK_BASE32_FLAG_INTERIOR_PADDING_OK : 0;
+ flags |= stop_on_garbage ? RK_BASE32_FLAG_STOP_ON_GARBAGE : 0;
+
+ if (help_flag)
+ return arg_printusage(args, num_args, NULL, "FILE | -- -"), 0;
+ if (argc != 1)
+ return arg_printusage(args, num_args, NULL, "FILE | -- -"), 1;
+
+ if (strcmp(argv[0], "-") == 0) {
+ unsigned char *tmp;
+ unsigned char d[4096];
+ size_t bytes;
+
+ while (!feof(stdin) && !ferror(stdin)) {
+ bytes = fread(d, 1, sizeof(d), stdin);
+ if (bytes == 0)
+ continue;
+ if (buflen + bytes > bufsz) {
+ if ((tmp = realloc(buf, bufsz + (bufsz >> 2) + sizeof(d))) == NULL)
+ err(1, "Could not read stdin");
+ buf = tmp;
+ bufsz = bufsz + (bufsz >> 2) + sizeof(d);
+ }
+ memcpy(buf + buflen, d, bytes);
+ buflen += bytes;
+ }
+ if (ferror(stdin))
+ err(1, "Could not read stdin");
+ } else {
+ void *d;
+
+ if ((errno = rk_undumpdata(argv[0], &d, &bufsz)))
+ err(1, "Could not read %s", argv[0]);
+ buflen = bufsz;
+ buf = d;
+ }
+
+ if (decode_flag) {
+ unsigned char *d;
+
+ if (buflen == bufsz) {
+ unsigned char *tmp;
+
+ if ((tmp = realloc(buf, bufsz + 1)) == NULL)
+ err(1, "Could not decode data");
+ buf = tmp;
+ bufsz++;
+ }
+ buf[buflen] = '\0';
+
+ if ((d = malloc(buflen * 5 / 8 + 4)) == NULL)
+ err(1, "Could not decode data");
+
+ if ((ret = rk_base32_decode((const char *)buf, d, flags)) < 0)
+ err(1, "Could not decode data");
+ if (fwrite(d, ret, 1, stdout) != 1)
+ err(1, "Could not write decoded data");
+ free(d);
+ } else if (buf) { /* buf can be NULL if we read from an empty file */
+ char *e;
+
+ if ((ret = rk_base32_encode(buf, buflen, &e, flags)) < 0)
+ err(1, "Could not encode data");
+ if (fwrite(e, ret, 1, stdout) != 1)
+ err(1, "Could not write decoded data");
+ free(e);
+ if (fwrite("\n", 1, 1, stdout) != 1)
+ err(1, "Could not write decoded data");
+ }
+ free(buf);
+ return 0;
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/base32.h b/third_party/heimdal/lib/roken/base32.h
new file mode 100644
index 0000000..1dc0dd0
--- /dev/null
+++ b/third_party/heimdal/lib/roken/base32.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef _BASE32_H_
+#define _BASE32_H_
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __cdecl
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+enum rk_base32_flags {
+ RK_BASE32_FLAG_PRESERVE_ORDER = 1,
+ RK_BASE32_FLAG_STOP_ON_GARBAGE = 2,
+ RK_BASE32_FLAG_INTERIOR_PADDING_OK = 4,
+};
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_base32_encode(const void *, int, char **, enum rk_base32_flags);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_base32_decode(const char *, void *, enum rk_base32_flags);
+
+#endif
diff --git a/third_party/heimdal/lib/roken/base64-test.c b/third_party/heimdal/lib/roken/base64-test.c
new file mode 100644
index 0000000..8fb3f52
--- /dev/null
+++ b/third_party/heimdal/lib/roken/base64-test.c
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include <base64.h>
+
+int
+main(int argc, char **argv)
+{
+ int numerr = 0;
+ int numtest = 1;
+ struct test {
+ void *data;
+ size_t len;
+ const char *result;
+ } *t, tests[] = {
+ { "", 0 , "" },
+ { "1", 1, "MQ==" },
+ { "22", 2, "MjI=" },
+ { "333", 3, "MzMz" },
+ { "4444", 4, "NDQ0NA==" },
+ { "55555", 5, "NTU1NTU=" },
+ { "abc:def", 7, "YWJjOmRlZg==" },
+ { NULL, 0, NULL }
+ };
+ for(t = tests; t->data; t++) {
+ char *str;
+ int len;
+
+ (void) rk_base64_encode(t->data, t->len, &str);
+ if(strcmp(str, t->result) != 0) {
+ fprintf(stderr, "failed test %d: %s != %s\n", numtest,
+ str, t->result);
+ numerr++;
+ }
+ free(str);
+ str = strdup(t->result);
+ len = rk_base64_decode(t->result, str);
+ if(len != t->len) {
+ fprintf(stderr, "failed test %d: len %lu != %lu\n", numtest,
+ (unsigned long)len, (unsigned long)t->len);
+ numerr++;
+ } else if(memcmp(str, t->data, t->len) != 0) {
+ fprintf(stderr, "failed test %d: data\n", numtest);
+ numerr++;
+ }
+ free(str);
+ numtest++;
+ }
+
+ {
+ char str[32];
+ if(rk_base64_decode("M=M=", str) != -1) {
+ fprintf(stderr, "failed test %d: successful decode of `M=M='\n",
+ numtest++);
+ numerr++;
+ }
+ if(rk_base64_decode("MQ===", str) != -1) {
+ fprintf(stderr, "failed test %d: successful decode of `MQ==='\n",
+ numtest++);
+ numerr++;
+ }
+ }
+ return numerr;
+}
diff --git a/third_party/heimdal/lib/roken/base64.c b/third_party/heimdal/lib/roken/base64.c
new file mode 100644
index 0000000..582d183
--- /dev/null
+++ b/third_party/heimdal/lib/roken/base64.c
@@ -0,0 +1,258 @@
+/*
+ * Copyright (c) 1995-2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#ifdef TEST
+#include <stdio.h>
+#include <getarg.h>
+#include <err.h>
+#endif
+#include "base64.h"
+#include "roken.h"
+
+static const char base64_chars[] =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+static int
+pos(char c)
+{
+ const char *p;
+ for (p = base64_chars; *p; p++)
+ if (*p == c)
+ return p - base64_chars;
+ return -1;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_base64_encode(const void *data, int size, char **str)
+{
+ char *s, *p;
+ int i;
+ int c;
+ const unsigned char *q;
+
+ if (size > INT_MAX/4 || size < 0) {
+ *str = NULL;
+ errno = ERANGE;
+ return -1;
+ }
+
+ p = s = (char *) malloc(size * 4 / 3 + 4);
+ if (p == NULL) {
+ *str = NULL;
+ return -1;
+ }
+ q = (const unsigned char *) data;
+
+ for (i = 0; i < size;) {
+ c = q[i++];
+ c *= 256;
+ if (i < size)
+ c += q[i];
+ i++;
+ c *= 256;
+ if (i < size)
+ c += q[i];
+ i++;
+ p[0] = base64_chars[(c & 0x00fc0000) >> 18];
+ p[1] = base64_chars[(c & 0x0003f000) >> 12];
+ p[2] = base64_chars[(c & 0x00000fc0) >> 6];
+ p[3] = base64_chars[(c & 0x0000003f) >> 0];
+ if (i > size)
+ p[3] = '=';
+ if (i > size + 1)
+ p[2] = '=';
+ p += 4;
+ }
+ *p = 0;
+ *str = s;
+ return (int) strlen(s);
+}
+
+#define DECODE_ERROR 0xffffffff
+
+static unsigned int
+token_decode(const char *token)
+{
+ int i;
+ unsigned int val = 0;
+ int marker = 0;
+ if (strlen(token) < 4)
+ return DECODE_ERROR;
+ for (i = 0; i < 4; i++) {
+ val *= 64;
+ if (token[i] == '=')
+ marker++;
+ else if (marker > 0)
+ return DECODE_ERROR;
+ else
+ val += pos(token[i]);
+ }
+ if (marker > 2)
+ return DECODE_ERROR;
+ return (marker << 24) | val;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_base64_decode(const char *str, void *data)
+{
+ const char *p;
+ unsigned char *q;
+
+ q = data;
+ for (p = str; *p && (*p == '=' || strchr(base64_chars, *p)); p += 4) {
+ unsigned int val = token_decode(p);
+ unsigned int marker = (val >> 24) & 0xff;
+ if (val == DECODE_ERROR) {
+ errno = EINVAL;
+ return -1;
+ }
+ *q++ = (val >> 16) & 0xff;
+ if (marker < 2)
+ *q++ = (val >> 8) & 0xff;
+ if (marker < 1)
+ *q++ = val & 0xff;
+ }
+ if (q - (unsigned char *) data > INT_MAX) {
+ errno = EOVERFLOW;
+ return -1;
+ }
+ return q - (unsigned char *) data;
+}
+
+#ifdef TEST
+static int decode_flag;
+static int help_flag;
+
+/*
+ * The short options are compatible with a subset of the FreeBSD contrib
+ * vis(1). Heimdal additions have long option names only.
+ */
+static struct getargs args[] = {
+ { "decode", 'd', arg_flag, &decode_flag, "Decode", NULL },
+ { "help", 'h', arg_flag, &help_flag, "Print help message", NULL },
+};
+static size_t num_args = sizeof(args)/sizeof(args[0]);
+
+int
+main(int argc, char **argv)
+{
+ unsigned char *buf = NULL;
+ size_t buflen = 0;
+ size_t bufsz = 0;
+ int goptind = 0;
+ int ret;
+
+ setprogname("rkbase64");
+ if (getarg(args, num_args, argc, argv, &goptind) || help_flag) {
+ arg_printusage(args, num_args, NULL, "FILE | -");
+ return help_flag ? 0 : 1;
+ }
+
+ argc -= goptind;
+ argv += goptind;
+
+ if (help_flag)
+ return arg_printusage(args, num_args, NULL, "FILE | -- -"), 0;
+ if (argc != 1)
+ return arg_printusage(args, num_args, NULL, "FILE | -- -"), 1;
+
+ if (strcmp(argv[0], "-") == 0) {
+ unsigned char *tmp;
+ unsigned char d[4096];
+ size_t bytes;
+
+ while (!feof(stdin) && !ferror(stdin)) {
+ bytes = fread(d, 1, sizeof(d), stdin);
+ if (bytes == 0)
+ continue;
+ if (buflen + bytes > bufsz) {
+ if ((tmp = realloc(buf, bufsz + (bufsz >> 2) + sizeof(d))) == NULL)
+ err(1, "Could not read stdin");
+ buf = tmp;
+ bufsz = bufsz + (bufsz >> 2) + sizeof(d);
+ }
+ memcpy(buf + buflen, d, bytes);
+ buflen += bytes;
+ }
+ if (ferror(stdin))
+ err(1, "Could not read stdin");
+ } else {
+ void *d;
+ if ((errno = rk_undumpdata(argv[0], &d, &bufsz)))
+ err(1, "Could not read %s", argv[0]);
+ buflen = bufsz;
+ buf = d;
+ }
+
+ if (decode_flag) {
+ unsigned char *d;
+
+ if (buflen == bufsz) {
+ unsigned char *tmp;
+
+ if ((tmp = realloc(buf, bufsz + 1)) == NULL)
+ err(1, "Could not decode data");
+ buf = tmp;
+ bufsz++;
+ }
+ buf[buflen] = '\0';
+
+ if ((d = malloc(buflen * 3 / 4 + 4)) == NULL)
+ err(1, "Could not decode data");
+
+ if ((ret = rk_base64_decode((const char *)buf, d)) < 0)
+ err(1, "Could not decode data");
+ if (fwrite(d, ret, 1, stdout) != 1)
+ err(1, "Could not write decoded data");
+ free(d);
+ } else if (buf) { /* buf can be NULL if we read from an empty file */
+ char *e;
+
+ if ((ret = rk_base64_encode(buf, buflen, &e)) < 0)
+ err(1, "Could not encode data");
+ if (fwrite(e, ret, 1, stdout) != 1)
+ err(1, "Could not write decoded data");
+ free(e);
+ if (fwrite("\n", 1, 1, stdout) != 1)
+ err(1, "Could not write decoded data");
+ }
+ free(buf);
+ return 0;
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/base64.h b/third_party/heimdal/lib/roken/base64.h
new file mode 100644
index 0000000..734a6b5
--- /dev/null
+++ b/third_party/heimdal/lib/roken/base64.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef _BASE64_H_
+#define _BASE64_H_
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __cdecl
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_base64_encode(const void *, int, char **);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_base64_decode(const char *, void *);
+
+#endif
diff --git a/third_party/heimdal/lib/roken/bswap.c b/third_party/heimdal/lib/roken/bswap.c
new file mode 100644
index 0000000..b0c4248
--- /dev/null
+++ b/third_party/heimdal/lib/roken/bswap.c
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include "roken.h"
+
+#ifndef HAVE_BSWAP64
+
+ROKEN_LIB_FUNCTION uint64_t ROKEN_LIB_CALL
+bswap64 (uint64_t val)
+{
+ return
+ (val & 0xffULL) << 56 |
+ (val & 0xff00ULL) << 40 |
+ (val & 0xff0000ULL) << 24 |
+ (val & 0xff000000ULL) << 8 |
+ (val & 0xff00000000ULL) >> 8 |
+ (val & 0xff0000000000ULL) >> 24 |
+ (val & 0xff000000000000ULL) >> 40 |
+ (val & 0xff00000000000000ULL) >> 56 ;
+}
+#endif
+
+#ifndef HAVE_BSWAP32
+
+ROKEN_LIB_FUNCTION unsigned int ROKEN_LIB_CALL
+bswap32 (unsigned int val)
+{
+ return (val & 0xff) << 24 |
+ (val & 0xff00) << 8 |
+ (val & 0xff0000) >> 8 |
+ (val & 0xff000000) >> 24;
+}
+#endif
+
+#ifndef HAVE_BSWAP16
+
+ROKEN_LIB_FUNCTION unsigned short ROKEN_LIB_CALL
+bswap16 (unsigned short val)
+{
+ return (val & 0xff) << 8 |
+ (val & 0xff00) >> 8;
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/chown.c b/third_party/heimdal/lib/roken/chown.c
new file mode 100644
index 0000000..90a82d9
--- /dev/null
+++ b/third_party/heimdal/lib/roken/chown.c
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+chown(const char *path, uid_t owner, gid_t group)
+{
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/cloexec.c b/third_party/heimdal/lib/roken/cloexec.c
new file mode 100644
index 0000000..59ffa50
--- /dev/null
+++ b/third_party/heimdal/lib/roken/cloexec.c
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+void ROKEN_LIB_FUNCTION
+rk_cloexec(int fd)
+{
+#ifdef HAVE_FCNTL
+ int ret;
+
+ ret = fcntl(fd, F_GETFD);
+ if (ret == -1)
+ return;
+ if (fcntl(fd, F_SETFD, ret | FD_CLOEXEC) == -1)
+ return;
+#endif
+}
+
+void ROKEN_LIB_FUNCTION
+rk_cloexec_file(FILE *f)
+{
+#ifdef HAVE_FCNTL
+ rk_cloexec(fileno(f));
+#endif
+}
+
+void ROKEN_LIB_FUNCTION
+rk_cloexec_dir(DIR * d)
+{
+#ifndef _WIN32
+ rk_cloexec(dirfd(d));
+#endif
+}
+
+void ROKEN_LIB_FUNCTION
+rk_cloexec_socket(rk_socket_t s)
+{
+#ifndef _WIN32
+ rk_cloexec((int)s);
+#endif
+}
+
diff --git a/third_party/heimdal/lib/roken/closefrom.c b/third_party/heimdal/lib/roken/closefrom.c
new file mode 100644
index 0000000..770eb2c
--- /dev/null
+++ b/third_party/heimdal/lib/roken/closefrom.c
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+closefrom(int fd)
+{
+ int num = getdtablesize();
+
+ if (num < 0)
+ num = 1024; /* XXX */
+
+ for (; fd <= num; fd++)
+ close(fd);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/clz.c b/third_party/heimdal/lib/roken/clz.c
new file mode 100644
index 0000000..1a36234
--- /dev/null
+++ b/third_party/heimdal/lib/roken/clz.c
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip.
+ * All rights reserved.
+ *
+ * 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.
+ */
+
+#include <config.h>
+#include <assert.h>
+
+#include "roken.h"
+
+#if defined(_MSC_VER)
+#include <intrin.h>
+#if defined(_WIN64)
+#pragma intrinsic(_BitScanReverse64)
+#else
+#pragma intrinsic(_BitScanReverse)
+#endif
+#endif
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_clzll(uint64_t x)
+{
+#if defined(_MSC_VER)
+ unsigned long r = 0;
+#elif !(defined(__GNUC__) && __GNUC__ >= 4)
+ int r = 0;
+#endif
+
+ assert(x != 0);
+
+#if defined(_MSC_VER)
+# if defined(_WIN64)
+ _BitScanReverse64(&r, x);
+# else
+ if (_BitScanReverse(&r, (uint32_t)(x >> 32)))
+ return 63 - (r + 32);
+ _BitScanReverse(&r, (uint32_t)(x & 0xFFFFFFFF));
+# endif
+
+ return 63 - r;
+#elif (defined(__GNUC__) && __GNUC__ >= 4)
+ return __builtin_clzll(x);
+#else
+ while (!(x & ((uint64_t)1 << 63))) {
+ x <<= 1;
+ ++r;
+ }
+
+ return r;
+#endif /* _MSC_VER || __GNUC__ */
+}
diff --git a/third_party/heimdal/lib/roken/concat.c b/third_party/heimdal/lib/roken/concat.c
new file mode 100644
index 0000000..0b4ac46
--- /dev/null
+++ b/third_party/heimdal/lib/roken/concat.c
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+roken_concat (char *s, size_t len, ...)
+{
+ int ret;
+ va_list args;
+
+ va_start(args, len);
+ ret = roken_vconcat (s, len, args);
+ va_end(args);
+ return ret;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+roken_vconcat (char *s, size_t len, va_list args)
+{
+ const char *a;
+
+ while ((a = va_arg(args, const char*))) {
+ size_t n = strlen (a);
+
+ if (n >= len)
+ return -1;
+ memcpy (s, a, n);
+ s += n;
+ len -= n;
+ }
+ *s = '\0';
+ return 0;
+}
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+roken_vmconcat (char **s, size_t max_len, va_list args)
+{
+ const char *a;
+ char *p, *q;
+ size_t len = 0;
+ *s = NULL;
+ p = malloc(1);
+ if(p == NULL)
+ return 0;
+ len = 1;
+ while ((a = va_arg(args, const char*))) {
+ size_t n = strlen (a);
+
+ if(max_len && len + n > max_len){
+ free(p);
+ return 0;
+ }
+ q = realloc(p, len + n);
+ if(q == NULL){
+ free(p);
+ return 0;
+ }
+ p = q;
+ memcpy (p + len - 1, a, n);
+ len += n;
+ }
+ p[len - 1] = '\0';
+ *s = p;
+ return len;
+}
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+roken_mconcat (char **s, size_t max_len, ...)
+{
+ size_t ret;
+ va_list args;
+
+ va_start(args, max_len);
+ ret = roken_vmconcat (s, max_len, args);
+ va_end(args);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/copyhostent.c b/third_party/heimdal/lib/roken/copyhostent.c
new file mode 100644
index 0000000..9b9dba2
--- /dev/null
+++ b/third_party/heimdal/lib/roken/copyhostent.c
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/*
+ * return a malloced copy of `h'
+ */
+
+ROKEN_LIB_FUNCTION struct hostent * ROKEN_LIB_CALL
+rk_copyhostent(const struct hostent *h)
+{
+ struct hostent *res;
+ char **p;
+ int i, n;
+
+ res = malloc (sizeof (*res));
+ if (res == NULL)
+ return NULL;
+ res->h_name = NULL;
+ res->h_aliases = NULL;
+ res->h_addrtype = h->h_addrtype;
+ res->h_length = h->h_length;
+ res->h_addr_list = NULL;
+ res->h_name = strdup (h->h_name);
+ if (res->h_name == NULL) {
+ freehostent (res);
+ return NULL;
+ }
+ for (n = 0, p = h->h_aliases; *p != NULL; ++p)
+ ++n;
+ res->h_aliases = malloc ((n + 1) * sizeof(*res->h_aliases));
+ if (res->h_aliases == NULL) {
+ freehostent (res);
+ return NULL;
+ }
+ for (i = 0; i < n + 1; ++i)
+ res->h_aliases[i] = NULL;
+ for (i = 0; i < n; ++i) {
+ res->h_aliases[i] = strdup (h->h_aliases[i]);
+ if (res->h_aliases[i] == NULL) {
+ freehostent (res);
+ return NULL;
+ }
+ }
+
+ for (n = 0, p = h->h_addr_list; *p != NULL; ++p)
+ ++n;
+ res->h_addr_list = malloc ((n + 1) * sizeof(*res->h_addr_list));
+ if (res->h_addr_list == NULL) {
+ freehostent (res);
+ return NULL;
+ }
+ for (i = 0; i < n + 1; ++i) {
+ res->h_addr_list[i] = NULL;
+ }
+ for (i = 0; i < n; ++i) {
+ res->h_addr_list[i] = malloc (h->h_length);
+ if (res->h_addr_list[i] == NULL) {
+ freehostent (res);
+ return NULL;
+ }
+ memcpy (res->h_addr_list[i], h->h_addr_list[i], h->h_length);
+ }
+ return res;
+}
diff --git a/third_party/heimdal/lib/roken/ct.c b/third_party/heimdal/lib/roken/ct.c
new file mode 100644
index 0000000..79f312d
--- /dev/null
+++ b/third_party/heimdal/lib/roken/ct.c
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include "roken.h"
+
+/**
+ * Constant time compare to memory regions. The reason for making it
+ * constant time is to make sure that timeing information leak from
+ * where in the function the diffrence is.
+ *
+ * ct_memcmp() can't be used to order memory regions like memcmp(),
+ * for example, use ct_memcmp() with qsort().
+ *
+ * We use volatile to avoid optimizations where the compiler and/or
+ * linker turn this ct_memcmp() into a plain memcmp(). The pointers
+ * themselves are also marked volatile (not just the memory pointed at)
+ * because in some GCC versions there is a bug which can be worked
+ * around by doing this.
+ *
+ * @param p1 memory region 1 to compare
+ * @param p2 memory region 2 to compare
+ * @param len length of memory
+ *
+ * @return 0 when the memory regions are equal, non zero if not
+ *
+ * @ingroup roken
+ */
+
+int
+ct_memcmp(const volatile void * volatile p1,
+ const volatile void * volatile p2,
+ size_t len)
+{
+ /*
+ * There's no need for s1 and s2 to be volatile; only p1 and p2 have
+ * to be in order to work around GCC bugs.
+ *
+ * However, s1 and s2 do have to point to volatile, as we don't know
+ * if the object was originally defined as volatile, and if it was
+ * then we'd get undefined behavior here if s1/s2 were declared to
+ * point to non-volatile memory.
+ */
+ const volatile unsigned char *s1 = p1;
+ const volatile unsigned char *s2 = p2;
+ size_t i;
+ int r = 0;
+
+ for (i = 0; i < len; i++)
+ r |= (s1[i] ^ s2[i]);
+ return !!r;
+}
diff --git a/third_party/heimdal/lib/roken/daemon.c b/third_party/heimdal/lib/roken/daemon.c
new file mode 100644
index 0000000..6128beb
--- /dev/null
+++ b/third_party/heimdal/lib/roken/daemon.c
@@ -0,0 +1,80 @@
+/*-
+ * Copyright (c) 1990, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+static char sccsid[] = "@(#)daemon.c 8.1 (Berkeley) 6/4/93";
+#endif /* LIBC_SCCS and not lint */
+
+#include <config.h>
+
+#ifndef HAVE_DAEMON
+
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef HAVE_PATHS_H
+#include <paths.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+daemon(int nochdir, int noclose)
+{
+ int fd;
+
+ switch (fork()) {
+ case -1:
+ return (-1);
+ case 0:
+ break;
+ default:
+ _exit(0);
+ }
+
+ if (setsid() == -1)
+ return (-1);
+
+ if (!nochdir)
+ chdir("/");
+
+ if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
+ dup2(fd, STDIN_FILENO);
+ dup2(fd, STDOUT_FILENO);
+ dup2(fd, STDERR_FILENO);
+ if (fd > 2)
+ (void) close(fd);
+ }
+ return (0);
+}
+
+#endif /* HAVE_DAEMON */
diff --git a/third_party/heimdal/lib/roken/detach.c b/third_party/heimdal/lib/roken/detach.c
new file mode 100644
index 0000000..4a00682
--- /dev/null
+++ b/third_party/heimdal/lib/roken/detach.c
@@ -0,0 +1,226 @@
+/*-
+ * Copyright (c) 2015
+ * Cryptonector LLC. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Cryptonector LLC may not be used to endorse or promote products
+ * derived from this software without specific prior written
+ * permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <errno.h>
+#include <fcntl.h>
+#ifdef WIN32
+#include <io.h>
+#include <stdlib.h>
+#else
+#include <unistd.h>
+#endif
+#include "roken.h"
+
+#ifdef WIN32
+#define dup2 _dup2
+#endif
+
+static int pipefds[2] = {-1, -1};
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+roken_detach_prep(int argc, char **argv, char *special_arg)
+{
+ ssize_t bytes;
+ size_t i;
+ pid_t child;
+ char **new_argv;
+ char buf[1];
+ char fildes[21];
+ int status;
+
+ pipefds[0] = -1;
+ pipefds[1] = -1;
+
+#ifdef WIN32
+ if (_pipe(pipefds, 4, _O_NOINHERIT | O_BINARY) == -1)
+ err(1, "failed to setup to detach daemon (_pipe failed)");
+#else
+ if (pipe(pipefds) == -1)
+ err(1, "failed to setup to detach daemon (pipe failed)");
+#endif
+
+ new_argv = calloc(argc + 3, sizeof(*new_argv));
+ if (new_argv == NULL)
+ err(1, "Out of memory");
+
+#ifdef WIN32
+ pipefds[1] = _dup(pipefds[1]); /* The new fd will be inherited */
+ if (pipefds[1] == -1)
+ err(1, "Out of memory");
+#else
+ (void) fcntl(pipefds[1], F_SETFD,
+ fcntl(pipefds[1], F_GETFD & ~(O_CLOEXEC)));
+#endif
+
+ if (snprintf(fildes, sizeof(fildes), "%d", pipefds[1]) >= sizeof(fildes))
+ err(1, "failed to setup to detach daemon (fd number %d too large)",
+ pipefds[1]);
+
+ new_argv[0] = argv[0];
+ new_argv[1] = special_arg;
+ new_argv[2] = fildes;
+ for (i = 1; argv[i] != NULL; i++)
+ new_argv[i + 2] = argv[i];
+ new_argv[argc + 2] = NULL;
+
+#ifndef WIN32
+ fflush(stdout);
+ child = fork();
+#else
+ {
+ intptr_t child_handle;
+
+ _flushall();
+ child_handle = spawnvp(_P_NOWAIT, argv[0], new_argv);
+ if (child_handle == -1)
+ child = (pid_t)-1;
+ else
+ child = GetProcessId((HANDLE)child_handle);
+ }
+#endif
+ if (child == (pid_t)-1)
+ err(1, "failed to setup to fork daemon (fork failed)");
+
+#ifndef WIN32
+ if (child == 0) {
+ int fd;
+
+ (void) close(pipefds[0]);
+ pipefds[0] = -1;
+ /*
+ * Keep stdout/stderr for now so output and errors prior to
+ * detach_finish() can be seen by the user.
+ */
+ fd = open(_PATH_DEVNULL, O_RDWR, 0);
+ if (fd == -1)
+ err(1, "failed to open /dev/null");
+ (void) dup2(fd, STDIN_FILENO);
+ if (fd > STDERR_FILENO)
+ (void) close(fd);
+ if (getenv("ROKEN_DETACH_USE_EXEC")) {
+ (void) execvp(argv[0], new_argv);
+ err(1, "failed to self-re-exec");
+ }
+ free(new_argv);
+ return pipefds[1];
+ }
+#endif
+
+ /* Parent */
+ free(new_argv);
+ (void) close(pipefds[1]);
+ pipefds[1] = -1;
+ do {
+ bytes = read(pipefds[0], buf, sizeof(buf));
+ } while (bytes == -1 && errno == EINTR);
+ (void) close(pipefds[0]);
+ pipefds[0] = -1;
+ if (bytes == -1) {
+ /*
+ * No need to wait for the process. We've killed it. If it
+ * doesn't want to exit, we'd have to wait potentially forever,
+ * but we want to indicate failure to the user as soon as
+ * possible. A wait with timeout would end the same way
+ * (attempting to kill the process).
+ */
+ err(1, "failed to setup daemon child (read from child pipe)");
+ }
+ if (bytes == 0) {
+ warnx("daemon child preparation failed, waiting for child");
+ status = wait_for_process(child);
+ if (SE_IS_ERROR(status) || SE_PROCSTATUS(status) != 0)
+ errx(SE_PROCSTATUS(status),
+ "daemon child preparation failed (child exited)");
+ }
+ _exit(0);
+ /* NOTREACHED */
+ return -1;
+}
+
+#ifdef WIN32
+#ifdef dup2
+#undef dup2
+#endif
+#define dup2 _dup2
+#endif
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+roken_detach_finish(const char *dir, int daemon_child_fd)
+{
+ char buf[1] = "";
+ ssize_t bytes;
+ int fd;
+
+ rk_pidfile(NULL);
+ if (pipefds[1] == -1 && daemon_child_fd != -1)
+ pipefds[1] = daemon_child_fd;
+ if (pipefds[0] != -1)
+ (void) close(pipefds[0]);
+ if (pipefds[1] == -1)
+ return;
+
+#ifdef HAVE_SETSID
+ if (setsid() == -1)
+ err(1, "failed to detach from tty");
+#endif
+
+#ifndef WIN32
+ /*
+ * Hopefully we've written any pidfiles by now, if they had to be in
+ * the current directory...
+ *
+ * The daemons do re-open logs and so on, therefore this chdir()
+ * call needs to be optional for testing.
+ */
+ if (dir != NULL && chdir(dir) == -1)
+ err(1, "failed to chdir to /");
+#endif
+
+ do {
+ bytes = write(pipefds[1], buf, sizeof(buf));
+ } while (bytes == -1 && errno == EINTR);
+ if (bytes == -1)
+ err(1, "failed to signal parent while detaching");
+ (void) close(pipefds[1]);
+ if (bytes != sizeof(buf))
+ errx(1, "failed to signal parent while detaching");
+
+ fd = open(_PATH_DEVNULL, O_RDWR, 0);
+ if (fd == -1)
+ err(1, "failed to open /dev/null");
+ /*
+ * Maybe we should check that our output got written, if redirected
+ * to a file. File utils normally do this.
+ */
+ (void) dup2(fd, STDOUT_FILENO);
+ (void) dup2(fd, STDERR_FILENO);
+ if (fd > 2)
+ (void) close(fd);
+}
diff --git a/third_party/heimdal/lib/roken/dirent-test.c b/third_party/heimdal/lib/roken/dirent-test.c
new file mode 100644
index 0000000..dc4518a
--- /dev/null
+++ b/third_party/heimdal/lib/roken/dirent-test.c
@@ -0,0 +1,278 @@
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+#include <config.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <direct.h>
+#include <errno.h>
+#include <io.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <string.h>
+#include "dirent.h"
+
+/* Note that we create a known directory structure in a subdirectory
+ of the current directory to run our tests. */
+
+#define TESTDIR "dirent-test-dir"
+
+const char * dir_entries[] = {
+ "A",
+ "B",
+ "C",
+ "CAA",
+ "CAAA",
+ "CABBBB",
+ "CAABBB.txt",
+ "A filename with spaces"
+};
+
+const char * entries_begin_with_C[] = {
+ "C",
+ "CAA",
+ "CAAA",
+ "CABBBB",
+ "CAABBB.txt"
+};
+
+const char * entries_end_with_A[] = {
+ "A",
+ "CAA",
+ "CAAA"
+};
+
+const int n_dir_entries = sizeof(dir_entries)/sizeof(dir_entries[0]);
+
+int teardown_test(void);
+
+void fail_test(const char * reason, ...)
+{
+ va_list args;
+
+ va_start(args, reason);
+ vfprintf(stderr, reason, args);
+ va_end(args);
+
+ fprintf(stderr, " : errno = %d (%s)\n", errno, strerror(errno));
+ teardown_test();
+ abort();
+}
+
+void fail_test_nf(const char * format, ...)
+{
+ va_list args;
+
+ fprintf(stderr, "FAIL:");
+
+ va_start(args, format);
+ vfprintf(stderr, format, args);
+ va_end(args);
+
+ fprintf(stderr, " : errno = %d (%s)\n", errno, strerror(errno));
+}
+
+int touch(const char * filename)
+{
+ int fd;
+
+ fd = _open(filename, _O_CREAT, _S_IREAD| _S_IWRITE);
+
+ if (fd == -1)
+ return -1;
+
+ return _close(fd);
+}
+
+int setup_test(void)
+{
+ int i;
+
+ fprintf(stderr, "Creating test directory %s ...\n", TESTDIR);
+
+ if (_mkdir(TESTDIR))
+ fail_test("Can't create test directory \"" TESTDIR "\"");
+
+ if (_chdir(TESTDIR))
+ fail_test("Can't change to test directory");
+
+ for (i=0; i < n_dir_entries; i++) {
+ if (touch(dir_entries[i]))
+ fail_test("Can't create test file '%s'", dir_entries[i]);
+ }
+
+ fprintf(stderr, "Done with test setup.\n");
+
+ return 0;
+}
+
+int teardown_test(void)
+{
+ char dirname[_MAX_PATH];
+ size_t len;
+ int i;
+
+ printf ("Begin cleanup...\n");
+
+ if (_getcwd(dirname, sizeof(dirname)/sizeof(char)) != NULL &&
+
+ (len = strlen(dirname)) > sizeof(TESTDIR)/sizeof(char) &&
+
+ strcmp(dirname + len + 1 - sizeof(TESTDIR)/sizeof(char), TESTDIR) == 0) {
+
+ fallthrough;
+
+ } else {
+ /* did we create the directory? */
+
+ if (!_rmdir( TESTDIR )) {
+ fprintf(stderr, "Removed test directory\n");
+ return 0;
+ } else {
+ if (errno == ENOTEMPTY) {
+ if (_chdir(TESTDIR)) {
+ fprintf(stderr, "Can't change to test directory. Aborting cleanup.\n");
+ return -1;
+ } else {
+ fallthrough;
+ }
+ } else {
+ return -1;
+ }
+ }
+ }
+
+ fprintf(stderr, "Cleaning up test directory %s ...\n", TESTDIR);
+
+ for (i=0; i < n_dir_entries; i++) {
+ if (_unlink(dir_entries[i])) {
+ /* if the test setup failed, we expect this to happen for
+ at least some files */
+ }
+ }
+
+ if (_chdir("..")) {
+ fprintf(stderr, "Can't escape test directory. Giving in.\n");
+ return -1;
+ }
+
+ if (_rmdir( TESTDIR )) {
+ fprintf(stderr, "Can't remove test directory.\n");
+ return -1;
+ }
+
+ printf("Cleaned up test directory\n");
+ return 0;
+}
+
+int check_list(const char * filespec, const char ** list, int n, int expect_dot_and_dotdot)
+{
+ DIR * d;
+ struct dirent * e;
+ int n_found = 0;
+ int i;
+ int rv = 0;
+ int retry = 1;
+
+ d = opendir(filespec);
+ if (d == NULL) {
+ fail_test_nf("opendir failed for [%s]", filespec);
+ return -1;
+ }
+
+ printf("Checking filespec [%s]... ", filespec);
+
+ retry:
+ while ((e = readdir(d)) != NULL) {
+ n_found ++;
+
+ if (expect_dot_and_dotdot &&
+ (strcmp(e->d_name, ".") == 0 ||
+ strcmp(e->d_name, "..") == 0))
+ continue;
+
+ for (i=0; i < n; i++) {
+ if (strcmp(list[i], e->d_name) == 0)
+ break;
+ }
+
+ if (i == n) {
+ fail_test_nf("Found unexpected entry [%s]", e->d_name);
+ rv = -1;
+ }
+ }
+
+ if (n_found != n) {
+ fail_test_nf("Unexpected number of entries [%d]. Expected %d", n_found, n);
+ rv = -1;
+ }
+
+ if (retry) {
+ retry = 0;
+ n_found = 0;
+
+ rewinddir(d);
+ goto retry;
+ }
+
+ if (closedir(d)) {
+ fail_test_nf("closedir() failed");
+ }
+
+ printf("done\n");
+
+ return rv;
+}
+
+int run_tests()
+{
+ /* assumes that the test directory has been set up and we have
+ changed into the test directory. */
+
+ check_list("*", dir_entries, n_dir_entries + 2, 1);
+ check_list("*.*", dir_entries, n_dir_entries + 2, 1);
+ check_list("C*", entries_begin_with_C, sizeof(entries_begin_with_C)/sizeof(entries_begin_with_C[0]), 0);
+ check_list("*A", entries_end_with_A, sizeof(entries_end_with_A)/sizeof(entries_end_with_A[0]), 0);
+
+ return 0;
+}
+
+int main(int argc, char ** argv)
+{
+ if (setup_test())
+ return 1;
+
+ run_tests();
+
+ teardown_test();
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/dirent.c b/third_party/heimdal/lib/roken/dirent.c
new file mode 100644
index 0000000..36f1bc9
--- /dev/null
+++ b/third_party/heimdal/lib/roken/dirent.c
@@ -0,0 +1,235 @@
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include<config.h>
+
+#include <stdlib.h>
+#include <io.h>
+#include <string.h>
+#include <errno.h>
+#include "dirent.h"
+
+#ifndef _WIN32
+#error Only implemented for Win32
+#endif
+
+struct _dirent_dirinfo {
+ int magic;
+ long n_entries;
+ long nc_entries;
+ long cursor;
+ struct dirent **entries;
+};
+#define DIRINFO_MAGIC 0xf8c0639d
+#define IS_DP(p) ((p) && ((DIR *)(p))->magic == DIRINFO_MAGIC)
+
+#define INITIAL_ENTRIES 16
+
+/**
+ * Create a filespec for use with _findfirst() using a path spec
+ *
+ * If the last component of the path spec contains wildcards, we let
+ * it be. If the last component doesn't end with a slash, we add one.
+ */
+static const char *
+filespec_from_dir_path(const char * path, char * buffer, size_t cch_buffer)
+{
+ char *comp, *t;
+ size_t pos;
+ int found_sep = 0;
+
+ if (strcpy_s(buffer, cch_buffer, path) != 0)
+ return NULL;
+
+ comp = strrchr(buffer, '\\');
+ if (comp == NULL)
+ comp = buffer;
+ else
+ found_sep = 1;
+
+ t = strrchr(comp, '/');
+ if (t != NULL) {
+ comp = t;
+ found_sep = 1;
+ }
+
+ if (found_sep)
+ comp++;
+
+ pos = strcspn(comp, "*?");
+ if (comp[pos] != '\0')
+ return buffer;
+
+ /* We don't append a slash if pos == 0 because that changes the
+ * meaning:
+ *
+ * "*.*" is all files in the current directory.
+ * "\*.*" is all files in the root directory of the current drive.
+ */
+ if (pos > 0 && comp[pos - 1] != '\\' &&
+ comp[pos - 1] != '/') {
+ strcat_s(comp, cch_buffer - (comp - buffer), "\\");
+ }
+
+ strcat_s(comp, cch_buffer - (comp - buffer), "*.*");
+
+ return buffer;
+}
+
+ROKEN_LIB_FUNCTION DIR * ROKEN_LIB_CALL
+opendir(const char * path)
+{
+ DIR * dp;
+ struct _finddata_t fd;
+ intptr_t fd_handle;
+ const char *filespec;
+ char path_buffer[1024]="";
+
+ memset(&fd, 0, sizeof(fd));
+
+ filespec = filespec_from_dir_path(path, path_buffer, sizeof(path_buffer)/sizeof(char));
+ if (filespec == NULL)
+ return NULL;
+
+ fd_handle = _findfirst(filespec, &fd);
+
+ if (fd_handle == -1)
+ return NULL;
+
+ dp = malloc(sizeof(*dp));
+ if (dp == NULL)
+ goto done;
+
+ memset(dp, 0, sizeof(*dp));
+ dp->magic = DIRINFO_MAGIC;
+ dp->cursor = 0;
+ dp->n_entries = 0;
+ dp->nc_entries = INITIAL_ENTRIES;
+ dp->entries = calloc(dp->nc_entries, sizeof(dp->entries[0]));
+
+ if (dp->entries == NULL) {
+ closedir(dp);
+ dp = NULL;
+ goto done;
+ }
+
+ do {
+ size_t len = strlen(fd.name);
+ struct dirent * e;
+
+ if (dp->n_entries == dp->nc_entries) {
+ struct dirent ** ne;
+
+ dp->nc_entries *= 2;
+ ne = realloc(dp->entries, sizeof(dp->entries[0]) * dp->nc_entries);
+
+ if (ne == NULL) {
+ closedir(dp);
+ dp = NULL;
+ goto done;
+ }
+
+ dp->entries = ne;
+ }
+
+ e = malloc(sizeof(*e) + len * sizeof(char));
+ if (e == NULL) {
+ closedir(dp);
+ dp = NULL;
+ goto done;
+ }
+
+ e->d_ino = 0; /* no inodes :( */
+ strcpy_s(e->d_name, len + 1, fd.name);
+
+ dp->entries[dp->n_entries++] = e;
+
+ } while (_findnext(fd_handle, &fd) == 0);
+
+ done:
+ if (fd_handle != -1)
+ _findclose(fd_handle);
+
+ return dp;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+closedir(DIR * dp)
+{
+ if (!IS_DP(dp))
+ return EINVAL;
+
+ if (dp->entries) {
+ long i;
+
+ for (i=0; i < dp->n_entries; i++) {
+ free(dp->entries[i]);
+ }
+
+ free(dp->entries);
+ }
+
+ free(dp);
+
+ return 0;
+}
+
+ROKEN_LIB_FUNCTION struct dirent * ROKEN_LIB_CALL
+readdir(DIR * dp)
+{
+ if (!IS_DP(dp) ||
+ dp->cursor < 0 ||
+ dp->cursor >= dp->n_entries)
+
+ return NULL;
+
+ return dp->entries[dp->cursor++];
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rewinddir(DIR * dp)
+{
+ if (IS_DP(dp))
+ dp->cursor = 0;
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+seekdir(DIR * dp, long offset)
+{
+ if (IS_DP(dp) && offset >= 0 && offset < dp->n_entries)
+ dp->cursor = offset;
+}
+
+ROKEN_LIB_FUNCTION long ROKEN_LIB_CALL
+telldir(DIR * dp)
+{
+ return dp->cursor;
+}
diff --git a/third_party/heimdal/lib/roken/dirent.hin b/third_party/heimdal/lib/roken/dirent.hin
new file mode 100644
index 0000000..c9a86c6
--- /dev/null
+++ b/third_party/heimdal/lib/roken/dirent.hin
@@ -0,0 +1,66 @@
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#ifndef __DIRENT_H__
+#define __DIRENT_H__
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __cdecl
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+#include<sys/types.h>
+
+struct dirent {
+ ino_t d_ino;
+ char d_name[1];
+};
+
+typedef struct _dirent_dirinfo DIR;
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL closedir(DIR *);
+
+ROKEN_LIB_FUNCTION DIR * ROKEN_LIB_CALL opendir(const char *);
+
+ROKEN_LIB_FUNCTION struct dirent * ROKEN_LIB_CALL readdir(DIR *);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL rewinddir(DIR *);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL seekdir(DIR *, long);
+
+ROKEN_LIB_FUNCTION long ROKEN_LIB_CALL telldir(DIR *);
+
+#endif
diff --git a/third_party/heimdal/lib/roken/dlfcn.hin b/third_party/heimdal/lib/roken/dlfcn.hin
new file mode 100644
index 0000000..4f2341b
--- /dev/null
+++ b/third_party/heimdal/lib/roken/dlfcn.hin
@@ -0,0 +1,109 @@
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#ifndef __dlfcn_h__
+#define __dlfcn_h__
+
+#include <windows.h>
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __cdecl
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+#ifdef _WIN32
+typedef int (__stdcall *DLSYM_RET_TYPE)();
+#else
+#define DLSYM_RET_TYPE void *
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Relocations are performed when the object is loaded. */
+#define RTLD_NOW 0
+
+/* Relocations are performed at an implementation-defined time.
+ * Windows API does not support lazy symbol resolving (when first reference
+ * to a given symbol occurs). So RTLD_LAZY implementation is same as RTLD_NOW.
+ */
+#define RTLD_LAZY RTLD_NOW
+
+/* All symbols are available for relocation processing of other modules. */
+#define RTLD_GLOBAL (1 << 1)
+
+/* All symbols are not made available for relocation processing by other modules. */
+#define RTLD_LOCAL (1 << 2)
+
+/* These two were added in The Open Group Base Specifications Issue 6.
+ * Note: All other RTLD_* flags in any dlfcn.h are not standard compliant.
+ */
+
+/* The symbol lookup happens in the normal global scope. */
+#define RTLD_DEFAULT ((void *)0LL)
+
+/* Specifies the next object after this one that defines name. */
+#define RTLD_NEXT ((void *)-1LL)
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+dlclose(void *);
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+dlerror(void);
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+dlopen(const char *, int);
+
+ROKEN_LIB_FUNCTION DLSYM_RET_TYPE ROKEN_LIB_CALL
+dlsym(void *, const char *);
+
+typedef struct Dl_info
+{
+ const char *dli_fname; /* Filename of defining object (thread unsafe and reused on every call to dladdr) */
+ void *dli_fbase; /* Load address of that object */
+ const char *dli_sname; /* Name of nearest lower symbol */
+ void *dli_saddr; /* Exact value of nearest symbol */
+} Dl_info, Dl_info_t;
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+dladdr(void *addr, Dl_info *dli);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* __dlfcn_h__ */
diff --git a/third_party/heimdal/lib/roken/dlfcn_w32.c b/third_party/heimdal/lib/roken/dlfcn_w32.c
new file mode 100644
index 0000000..9da3f6f
--- /dev/null
+++ b/third_party/heimdal/lib/roken/dlfcn_w32.c
@@ -0,0 +1,700 @@
+/*
+ * dlfcn-win32
+ * Copyright (c) 2007 Ramiro Polla
+ * Copyright (c) 2015 Tiancheng "Timothy" Gu
+ * Copyright (c) 2019 Pali Rohár <pali.rohar@gmail.com>
+ * Copyright (c) 2020 Ralf Habacker <ralf.habacker@freenet.de>
+ *
+ * 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.
+ */
+
+/*
+ * Copied from https://github.com/dlfcn-win32/dlfcn-win32 and modified only to
+ * fit Heimdal's lib/roken.
+ */
+
+#ifndef _WIN32_WINNT
+#define _WIN32_WINNT 0x0501
+#endif
+#ifdef _DEBUG
+#define _CRTDBG_MAP_ALLOC
+#include <stdlib.h>
+#include <crtdbg.h>
+#endif
+#include <windows.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#ifdef _MSC_VER
+/* https://docs.microsoft.com/en-us/cpp/intrinsics/returnaddress */
+#pragma intrinsic(_ReturnAddress)
+#else
+/* https://gcc.gnu.org/onlinedocs/gcc/Return-Address.html */
+#ifndef _ReturnAddress
+#define _ReturnAddress() (__builtin_extract_return_addr(__builtin_return_address(0)))
+#endif
+#endif
+
+#ifdef DLFCN_WIN32_SHARED
+#define DLFCN_WIN32_EXPORTS
+#endif
+#include "dlfcn.h"
+
+/* Note:
+ * MSDN says these functions are not thread-safe. We make no efforts to have
+ * any kind of thread safety.
+ */
+
+typedef struct local_object {
+ HMODULE hModule;
+ struct local_object *previous;
+ struct local_object *next;
+} local_object;
+
+static local_object first_object;
+
+/* These functions implement a double linked list for the local objects. */
+static local_object *local_search( HMODULE hModule )
+{
+ local_object *pobject;
+
+ if( hModule == NULL )
+ return NULL;
+
+ for( pobject = &first_object; pobject; pobject = pobject->next )
+ if( pobject->hModule == hModule )
+ return pobject;
+
+ return NULL;
+}
+
+static BOOL local_add( HMODULE hModule )
+{
+ local_object *pobject;
+ local_object *nobject;
+
+ if( hModule == NULL )
+ return TRUE;
+
+ pobject = local_search( hModule );
+
+ /* Do not add object again if it's already on the list */
+ if( pobject )
+ return TRUE;
+
+ for( pobject = &first_object; pobject->next; pobject = pobject->next );
+
+ nobject = (local_object*) malloc( sizeof( local_object ) );
+
+ if( !nobject )
+ {
+ SetLastError( ERROR_NOT_ENOUGH_MEMORY );
+ return FALSE;
+ }
+
+ pobject->next = nobject;
+ nobject->next = NULL;
+ nobject->previous = pobject;
+ nobject->hModule = hModule;
+
+ return TRUE;
+}
+
+static void local_rem( HMODULE hModule )
+{
+ local_object *pobject;
+
+ if( hModule == NULL )
+ return;
+
+ pobject = local_search( hModule );
+
+ if( !pobject )
+ return;
+
+ if( pobject->next )
+ pobject->next->previous = pobject->previous;
+ if( pobject->previous )
+ pobject->previous->next = pobject->next;
+
+ free( pobject );
+}
+
+/* POSIX says dlerror( ) doesn't have to be thread-safe, so we use one
+ * static buffer.
+ * MSDN says the buffer cannot be larger than 64K bytes, so we set it to
+ * the limit.
+ */
+static char error_buffer[65535];
+static BOOL error_occurred;
+
+static void save_err_str( const char *str )
+{
+ DWORD dwMessageId;
+ DWORD ret;
+ size_t pos, len;
+
+ dwMessageId = GetLastError( );
+
+ if( dwMessageId == 0 )
+ return;
+
+ len = strlen( str );
+ if( len > sizeof( error_buffer ) - 5 )
+ len = sizeof( error_buffer ) - 5;
+
+ /* Format error message to:
+ * "<argument to function that failed>": <Windows localized error message>
+ */
+ pos = 0;
+ error_buffer[pos++] = '"';
+ memcpy( error_buffer+pos, str, len );
+ pos += len;
+ error_buffer[pos++] = '"';
+ error_buffer[pos++] = ':';
+ error_buffer[pos++] = ' ';
+
+ ret = FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwMessageId,
+ MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),
+ error_buffer+pos, (DWORD) (sizeof(error_buffer)-pos), NULL );
+ pos += ret;
+
+ /* When FormatMessageA() fails it returns zero and does not touch buffer
+ * so add trailing null byte */
+ if( ret == 0 )
+ error_buffer[pos] = '\0';
+
+ if( pos > 1 )
+ {
+ /* POSIX says the string must not have trailing <newline> */
+ if( error_buffer[pos-2] == '\r' && error_buffer[pos-1] == '\n' )
+ error_buffer[pos-2] = '\0';
+ }
+
+ error_occurred = TRUE;
+}
+
+static void save_err_ptr_str( const void *ptr )
+{
+ char ptr_buf[2 + 2 * sizeof( ptr ) + 1];
+ char num;
+ size_t i;
+
+ ptr_buf[0] = '0';
+ ptr_buf[1] = 'x';
+
+ for( i = 0; i < 2 * sizeof( ptr ); i++ )
+ {
+ num = ( ( (ULONG_PTR) ptr ) >> ( 8 * sizeof( ptr ) - 4 * ( i + 1 ) ) ) & 0xF;
+ ptr_buf[2+i] = num + ( ( num < 0xA ) ? '0' : ( 'A' - 0xA ) );
+ }
+
+ ptr_buf[2 + 2 * sizeof( ptr )] = 0;
+
+ save_err_str( ptr_buf );
+}
+
+/* Load Psapi.dll at runtime, this avoids linking caveat */
+static BOOL MyEnumProcessModules( HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded )
+{
+ static BOOL (WINAPI *EnumProcessModulesPtr)(HANDLE, HMODULE *, DWORD, LPDWORD);
+ HMODULE psapi;
+
+ if( !EnumProcessModulesPtr )
+ {
+ psapi = LoadLibraryA( "Psapi.dll" );
+ if( psapi )
+ EnumProcessModulesPtr = (BOOL (WINAPI *)(HANDLE, HMODULE *, DWORD, LPDWORD)) GetProcAddress( psapi, "EnumProcessModules" );
+ if( !EnumProcessModulesPtr )
+ return 0;
+ }
+
+ return EnumProcessModulesPtr( hProcess, lphModule, cb, lpcbNeeded );
+}
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+dlopen( const char *file, int mode )
+{
+ HMODULE hModule;
+ UINT uMode;
+
+ error_occurred = FALSE;
+
+ /* Do not let Windows display the critical-error-handler message box */
+ uMode = SetErrorMode( SEM_FAILCRITICALERRORS );
+
+ if( file == 0 )
+ {
+ /* POSIX says that if the value of file is 0, a handle on a global
+ * symbol object must be provided. That object must be able to access
+ * all symbols from the original program file, and any objects loaded
+ * with the RTLD_GLOBAL flag.
+ * The return value from GetModuleHandle( ) allows us to retrieve
+ * symbols only from the original program file. EnumProcessModules() is
+ * used to access symbols from other libraries. For objects loaded
+ * with the RTLD_LOCAL flag, we create our own list later on. They are
+ * excluded from EnumProcessModules() iteration.
+ */
+ hModule = GetModuleHandle( NULL );
+
+ if( !hModule )
+ save_err_str( "(null)" );
+ }
+ else
+ {
+ HANDLE hCurrentProc;
+ DWORD dwProcModsBefore, dwProcModsAfter;
+ char lpFileName[MAX_PATH];
+ size_t i, len;
+
+ len = strlen( file );
+
+ if( len >= sizeof( lpFileName ) )
+ {
+ SetLastError( ERROR_FILENAME_EXCED_RANGE );
+ save_err_str( file );
+ hModule = NULL;
+ }
+ else
+ {
+ /* MSDN says backslashes *must* be used instead of forward slashes. */
+ for( i = 0; i < len; i++ )
+ {
+ if( file[i] == '/' )
+ lpFileName[i] = '\\';
+ else
+ lpFileName[i] = file[i];
+ }
+ lpFileName[len] = '\0';
+
+ hCurrentProc = GetCurrentProcess( );
+
+ if( MyEnumProcessModules( hCurrentProc, NULL, 0, &dwProcModsBefore ) == 0 )
+ dwProcModsBefore = 0;
+
+ /* POSIX says the search path is implementation-defined.
+ * LOAD_WITH_ALTERED_SEARCH_PATH is used to make it behave more closely
+ * to UNIX's search paths (start with system folders instead of current
+ * folder).
+ */
+ hModule = LoadLibraryExA( lpFileName, NULL, LOAD_WITH_ALTERED_SEARCH_PATH );
+
+ if( !hModule )
+ {
+ save_err_str( lpFileName );
+ }
+ else
+ {
+ if( MyEnumProcessModules( hCurrentProc, NULL, 0, &dwProcModsAfter ) == 0 )
+ dwProcModsAfter = 0;
+
+ /* If the object was loaded with RTLD_LOCAL, add it to list of local
+ * objects, so that its symbols cannot be retrieved even if the handle for
+ * the original program file is passed. POSIX says that if the same
+ * file is specified in multiple invocations, and any of them are
+ * RTLD_GLOBAL, even if any further invocations use RTLD_LOCAL, the
+ * symbols will remain global. If number of loaded modules was not
+ * changed after calling LoadLibraryEx(), it means that library was
+ * already loaded.
+ */
+ if( (mode & RTLD_LOCAL) && dwProcModsBefore != dwProcModsAfter )
+ {
+ if( !local_add( hModule ) )
+ {
+ save_err_str( lpFileName );
+ FreeLibrary( hModule );
+ hModule = NULL;
+ }
+ }
+ else if( !(mode & RTLD_LOCAL) && dwProcModsBefore == dwProcModsAfter )
+ {
+ local_rem( hModule );
+ }
+ }
+ }
+ }
+
+ /* Return to previous state of the error-mode bit flags. */
+ SetErrorMode( uMode );
+
+ return (void *) hModule;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+dlclose( void *handle )
+{
+ HMODULE hModule = (HMODULE) handle;
+ BOOL ret;
+
+ error_occurred = FALSE;
+
+ ret = FreeLibrary( hModule );
+
+ /* If the object was loaded with RTLD_LOCAL, remove it from list of local
+ * objects.
+ */
+ if( ret )
+ local_rem( hModule );
+ else
+ save_err_ptr_str( handle );
+
+ /* dlclose's return value in inverted in relation to FreeLibrary's. */
+ ret = !ret;
+
+ return (int) ret;
+}
+
+__declspec(noinline) /* Needed for _ReturnAddress() */
+ROKEN_LIB_FUNCTION DLSYM_RET_TYPE ROKEN_LIB_CALL
+dlsym( void *handle, const char *name )
+{
+ FARPROC symbol;
+ HMODULE hCaller;
+ HMODULE hModule;
+ HANDLE hCurrentProc;
+
+ error_occurred = FALSE;
+
+ symbol = NULL;
+ hCaller = NULL;
+ hModule = GetModuleHandle( NULL );
+ hCurrentProc = GetCurrentProcess( );
+
+ if( handle == RTLD_DEFAULT )
+ {
+ /* The symbol lookup happens in the normal global scope; that is,
+ * a search for a symbol using this handle would find the same
+ * definition as a direct use of this symbol in the program code.
+ * So use same lookup procedure as when filename is NULL.
+ */
+ handle = hModule;
+ }
+ else if( handle == RTLD_NEXT )
+ {
+ /* Specifies the next object after this one that defines name.
+ * This one refers to the object containing the invocation of dlsym().
+ * The next object is the one found upon the application of a load
+ * order symbol resolution algorithm. To get caller function of dlsym()
+ * use _ReturnAddress() intrinsic. To get HMODULE of caller function
+ * use standard GetModuleHandleExA() function.
+ */
+ if( !GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR) _ReturnAddress( ), &hCaller ) )
+ goto end;
+ }
+
+ if( handle != RTLD_NEXT )
+ {
+ symbol = GetProcAddress( (HMODULE) handle, name );
+
+ if( symbol != NULL )
+ goto end;
+ }
+
+ /* If the handle for the original program file is passed, also search
+ * in all globally loaded objects.
+ */
+
+ if( hModule == handle || handle == RTLD_NEXT )
+ {
+ HMODULE *modules;
+ DWORD cbNeeded;
+ DWORD dwSize;
+ size_t i;
+
+ /* GetModuleHandle( NULL ) only returns the current program file. So
+ * if we want to get ALL loaded module including those in linked DLLs,
+ * we have to use EnumProcessModules( ).
+ */
+ if( MyEnumProcessModules( hCurrentProc, NULL, 0, &dwSize ) != 0 )
+ {
+ modules = malloc( dwSize );
+ if( modules )
+ {
+ if( MyEnumProcessModules( hCurrentProc, modules, dwSize, &cbNeeded ) != 0 && dwSize == cbNeeded )
+ {
+ for( i = 0; i < dwSize / sizeof( HMODULE ); i++ )
+ {
+ if( handle == RTLD_NEXT && hCaller )
+ {
+ /* Next modules can be used for RTLD_NEXT */
+ if( hCaller == modules[i] )
+ hCaller = NULL;
+ continue;
+ }
+ if( local_search( modules[i] ) )
+ continue;
+ symbol = GetProcAddress( modules[i], name );
+ if( symbol != NULL )
+ {
+ free( modules );
+ goto end;
+ }
+ }
+
+ }
+ free( modules );
+ }
+ else
+ {
+ SetLastError( ERROR_NOT_ENOUGH_MEMORY );
+ goto end;
+ }
+ }
+ }
+
+end:
+ if( symbol == NULL )
+ {
+ if( GetLastError() == 0 )
+ SetLastError( ERROR_PROC_NOT_FOUND );
+ save_err_str( name );
+ }
+
+ return *(void **) (&symbol);
+}
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+dlerror( void )
+{
+ /* If this is the second consecutive call to dlerror, return NULL */
+ if( !error_occurred )
+ return NULL;
+
+ /* POSIX says that invoking dlerror( ) a second time, immediately following
+ * a prior invocation, shall result in NULL being returned.
+ */
+ error_occurred = FALSE;
+
+ return error_buffer;
+}
+
+/* See https://docs.microsoft.com/en-us/archive/msdn-magazine/2002/march/inside-windows-an-in-depth-look-into-the-win32-portable-executable-file-format-part-2
+ * for details */
+
+/* Get specific image section */
+static BOOL get_image_section( HMODULE module, int index, void **ptr, DWORD *size )
+{
+ IMAGE_DOS_HEADER *dosHeader;
+ IMAGE_OPTIONAL_HEADER *optionalHeader;
+
+ dosHeader = (IMAGE_DOS_HEADER *) module;
+
+ if( dosHeader->e_magic != 0x5A4D )
+ return FALSE;
+
+ optionalHeader = (IMAGE_OPTIONAL_HEADER *) ( (BYTE *) module + dosHeader->e_lfanew + 24 );
+
+ if( optionalHeader->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC )
+ return FALSE;
+
+ if( index < 0 || index > IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR )
+ return FALSE;
+
+ if( optionalHeader->DataDirectory[index].Size == 0 || optionalHeader->DataDirectory[index].VirtualAddress == 0 )
+ return FALSE;
+
+ if( size != NULL )
+ *size = optionalHeader->DataDirectory[index].Size;
+
+ *ptr = (void *)( (BYTE *) module + optionalHeader->DataDirectory[index].VirtualAddress );
+
+ return TRUE;
+}
+
+/* Return symbol name for a given address */
+static const char *get_symbol_name( HMODULE module, IMAGE_IMPORT_DESCRIPTOR *iid, void *addr, void **func_address )
+{
+ int i;
+ void *candidateAddr = NULL;
+ const char *candidateName = NULL;
+ BYTE *base = (BYTE *) module; /* Required to have correct calculations */
+
+ for( i = 0; iid[i].Characteristics != 0 && iid[i].FirstThunk != 0; i++ )
+ {
+ IMAGE_THUNK_DATA *thunkILT = (IMAGE_THUNK_DATA *)( base + iid[i].Characteristics );
+ IMAGE_THUNK_DATA *thunkIAT = (IMAGE_THUNK_DATA *)( base + iid[i].FirstThunk );
+
+ for( ; thunkILT->u1.AddressOfData != 0; thunkILT++, thunkIAT++ )
+ {
+ IMAGE_IMPORT_BY_NAME *nameData;
+
+ if( IMAGE_SNAP_BY_ORDINAL( thunkILT->u1.Ordinal ) )
+ continue;
+
+ if( (void *) thunkIAT->u1.Function > addr || candidateAddr >= (void *) thunkIAT->u1.Function )
+ continue;
+
+ candidateAddr = (void *) thunkIAT->u1.Function;
+ nameData = (IMAGE_IMPORT_BY_NAME *)( base + (ULONG_PTR) thunkILT->u1.AddressOfData );
+ candidateName = (const char *) nameData->Name;
+ }
+ }
+
+ *func_address = candidateAddr;
+ return candidateName;
+}
+
+static BOOL is_valid_address( void *addr )
+{
+ MEMORY_BASIC_INFORMATION info;
+ SIZE_T result;
+
+ if( addr == NULL )
+ return FALSE;
+
+ /* check valid pointer */
+ result = VirtualQuery( addr, &info, sizeof( info ) );
+
+ if( result == 0 || info.AllocationBase == NULL || info.AllocationProtect == 0 || info.AllocationProtect == PAGE_NOACCESS )
+ return FALSE;
+
+ return TRUE;
+}
+
+/* Return state if address points to an import thunk
+ *
+ * An import thunk is setup with a 'jmp' instruction followed by an
+ * absolute address (32bit) or relative offset (64bit) pointing into
+ * the import address table (iat), which is partially maintained by
+ * the runtime linker.
+ */
+static BOOL is_import_thunk( void *addr )
+{
+ return *(short *) addr == 0x25ff ? TRUE : FALSE;
+}
+
+/* Return adress from the import address table (iat),
+ * if the original address points to a thunk table entry.
+ */
+static void *get_address_from_import_address_table( void *iat, DWORD iat_size, void *addr )
+{
+ BYTE *thkp = (BYTE *) addr;
+ /* Get offset from thunk table (after instruction 0xff 0x25)
+ * 4018c8 <_VirtualQuery>: ff 25 4a 8a 00 00
+ */
+ ULONG offset = *(ULONG *)( thkp + 2 );
+#ifdef _WIN64
+ /* On 64 bit the offset is relative
+ * 4018c8: ff 25 4a 8a 00 00 jmpq *0x8a4a(%rip) # 40a318 <__imp_VirtualQuery>
+ * And can be also negative (MSVC in WDK)
+ * 100002f20: ff 25 3a e1 ff ff jmpq *-0x1ec6(%rip) # 0x100001060
+ * So cast to signed LONG type
+ */
+ BYTE *ptr = (BYTE *)( thkp + 6 + (LONG) offset );
+#else
+ /* On 32 bit the offset is absolute
+ * 4019b4: ff 25 90 71 40 00 jmp *0x40719
+ */
+ BYTE *ptr = (BYTE *) offset;
+#endif
+
+ if( !is_valid_address( ptr ) || ptr < (BYTE *) iat || ptr > (BYTE *) iat + iat_size )
+ return NULL;
+
+ return *(void **) ptr;
+}
+
+/* Holds module filename */
+static char module_filename[2*MAX_PATH];
+
+static BOOL fill_module_info( void *addr, Dl_info *info )
+{
+ HMODULE hModule;
+ DWORD dwSize;
+
+ if( !GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, addr, &hModule ) || hModule == NULL )
+ return FALSE;
+
+ dwSize = GetModuleFileNameA( hModule, module_filename, sizeof( module_filename ) );
+
+ if( dwSize == 0 || dwSize == sizeof( module_filename ) )
+ return FALSE;
+
+ info->dli_fbase = (void *) hModule;
+ info->dli_fname = module_filename;
+
+ return TRUE;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+dladdr( void *addr, Dl_info *info )
+{
+ void *realAddr, *funcAddress = NULL;
+ HMODULE hModule;
+ IMAGE_IMPORT_DESCRIPTOR *iid;
+ DWORD iidSize = 0;
+
+ if( addr == NULL || info == NULL )
+ return 0;
+
+ hModule = GetModuleHandleA( NULL );
+ if( hModule == NULL )
+ return 0;
+
+ if( !is_valid_address( addr ) )
+ return 0;
+
+ realAddr = addr;
+
+ if( !get_image_section( hModule, IMAGE_DIRECTORY_ENTRY_IMPORT, (void **) &iid, &iidSize ) )
+ return 0;
+
+ if( is_import_thunk( addr ) )
+ {
+ void *iat;
+ void *iatAddr = NULL;
+ DWORD iatSize = 0;
+
+ if( !get_image_section( hModule, IMAGE_DIRECTORY_ENTRY_IAT, &iat, &iatSize ) )
+ {
+ /* Fallback for cases where the iat is not defined,
+ * for example i586-mingw32msvc-gcc */
+ if( iid == NULL || iid->Characteristics == 0 || iid->FirstThunk == 0 )
+ return 0;
+
+ iat = (void *)( (BYTE *) hModule + iid->FirstThunk );
+ /* We assume that in this case iid and iat's are in linear order */
+ iatSize = iidSize - (DWORD) ( (BYTE *) iat - (BYTE *) iid );
+ }
+
+ iatAddr = get_address_from_import_address_table( iat, iatSize, addr );
+ if( iatAddr == NULL )
+ return 0;
+
+ realAddr = iatAddr;
+ }
+
+ if( !fill_module_info( realAddr, info ) )
+ return 0;
+
+ info->dli_sname = get_symbol_name( hModule, iid, realAddr, &funcAddress );
+
+ info->dli_saddr = !info->dli_sname ? NULL : funcAddress ? funcAddress : realAddr;
+ return 1;
+}
+
+#ifdef DLFCN_WIN32_SHARED
+BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
+{
+ (void) hinstDLL;
+ (void) fdwReason;
+ (void) lpvReserved;
+ return TRUE;
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/doxygen.c b/third_party/heimdal/lib/roken/doxygen.c
new file mode 100644
index 0000000..0d30a47
--- /dev/null
+++ b/third_party/heimdal/lib/roken/doxygen.c
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*! @mainpage Heimdal Roken support library
+ *
+ * @section intro Introduction
+ *
+ * Heimdal's roken implememnts missing functions and make it easier to
+ * work with almost unixies like cygwin and AIX.
+ *
+ * The project web page: http://www.h5l.org/
+ */
+
+/** @defgroup roken Heimdal roken library */
diff --git a/third_party/heimdal/lib/roken/dumpdata.c b/third_party/heimdal/lib/roken/dumpdata.c
new file mode 100644
index 0000000..252744e
--- /dev/null
+++ b/third_party/heimdal/lib/roken/dumpdata.c
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/*
+ * Write datablob to a filename, don't care about errors.
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_dumpdata (const char *filename, const void *buf, size_t size)
+{
+ int fd;
+
+ fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0640);
+ if (fd < 0)
+ return;
+ net_write(fd, buf, size);
+ close(fd);
+}
+
+/*
+ * Read all data from a filename, care about errors.
+ */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_undumpdata(const char *filename, void **buf, size_t *size)
+{
+ struct stat sb;
+ int fd, ret;
+ ssize_t sret;
+
+ *buf = NULL;
+
+ fd = open(filename, O_RDONLY, 0);
+ if (fd < 0)
+ return errno;
+ if (fstat(fd, &sb) != 0){
+ ret = errno;
+ goto out;
+ }
+ *buf = malloc(sb.st_size);
+ if (*buf == NULL) {
+ ret = ENOMEM;
+ goto out;
+ }
+ *size = sb.st_size;
+
+ sret = net_read(fd, *buf, *size);
+ if (sret < 0)
+ ret = errno;
+ else if (sret != (ssize_t)*size)
+ ret = EINVAL;
+ else
+ ret = 0;
+
+ out:
+ if (ret) {
+ free(*buf);
+ *buf = NULL;
+ }
+ close(fd);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/ecalloc.3 b/third_party/heimdal/lib/roken/ecalloc.3
new file mode 100644
index 0000000..a2863df
--- /dev/null
+++ b/third_party/heimdal/lib/roken/ecalloc.3
@@ -0,0 +1,84 @@
+.\" Copyright (c) 2001, 2003 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\" $Id$
+.\"
+.Dd August 14, 2003
+.Dt ECALLOC 3
+.Os HEIMDAL
+.Sh NAME
+.Nm ecalloc ,
+.Nm emalloc ,
+.Nm eread ,
+.Nm erealloc ,
+.Nm esetenv ,
+.Nm estrdup ,
+.Nm ewrite
+.Nd exit-on-failure wrapper functions
+.Sh LIBRARY
+The roken library (libroken, -lroken)
+.Sh SYNOPSIS
+.Fd #include <roken.h>
+.Ft "void *"
+.Fn ecalloc "size_t number" "size_t size"
+.Ft "void *"
+.Fn emalloc "size_t sz"
+.Ft ssize_t
+.Fn eread "int fd" "void *buf" "size_t nbytes"
+.Ft "void *"
+.Fn erealloc "void *ptr" "size_t sz"
+.Ft void
+.Fn esetenv "const char *var" "const char *val" "int rewrite"
+.Ft "char *"
+.Fn estrdup "const char *str"
+.Ft ssize_t
+.Fn ewrite "int fd" "const void *buf" "size_t nbytes"
+.Sh DESCRIPTION
+These functions do the same as the ones without the
+.Dq e
+prefix, but if there is an error they will print a message with
+.Xr errx 3 ,
+and exit. For
+.Nm eread
+and
+.Nm ewrite
+this is also true for partial data.
+.Pp
+This is useful in applications when there is no need for a more
+advanced failure mode.
+.Sh SEE ALSO
+.Xr read 2 ,
+.Xr write 2 ,
+.Xr calloc 3 ,
+.Xr errx 3 ,
+.Xr malloc 3 ,
+.Xr realloc 3 ,
+.Xr setenv 3 ,
+.Xr strdup 3
diff --git a/third_party/heimdal/lib/roken/ecalloc.c b/third_party/heimdal/lib/roken/ecalloc.c
new file mode 100644
index 0000000..04b3733
--- /dev/null
+++ b/third_party/heimdal/lib/roken/ecalloc.c
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdlib.h>
+#include <err.h>
+
+#include "roken.h"
+
+/*
+ * Like calloc but never fails.
+ */
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+ecalloc (size_t number, size_t size)
+{
+ void *tmp = calloc (number, size);
+
+ if (tmp == NULL && number * size != 0)
+ errx (1, "calloc %lu failed", (unsigned long)number * size);
+ return tmp;
+}
diff --git a/third_party/heimdal/lib/roken/emalloc.c b/third_party/heimdal/lib/roken/emalloc.c
new file mode 100644
index 0000000..2520230
--- /dev/null
+++ b/third_party/heimdal/lib/roken/emalloc.c
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdlib.h>
+#include <err.h>
+
+#include "roken.h"
+
+/*
+ * Like malloc but never fails.
+ */
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+emalloc (size_t sz)
+{
+ void *tmp = malloc (sz);
+
+ if (tmp == NULL && sz != 0)
+ errx (1, "malloc %lu failed", (unsigned long)sz);
+ return tmp;
+}
diff --git a/third_party/heimdal/lib/roken/environment.c b/third_party/heimdal/lib/roken/environment.c
new file mode 100644
index 0000000..a14f27b
--- /dev/null
+++ b/third_party/heimdal/lib/roken/environment.c
@@ -0,0 +1,162 @@
+/*
+ * Copyright (c) 2000, 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+
+#include <config.h>
+
+#include <stdio.h>
+#include <string.h>
+#include <ctype.h>
+#include "roken.h"
+
+/* find assignment in env list; len is length of variable including
+ * equal
+ */
+
+static int
+find_var(char **env, char *assignment, size_t len)
+{
+ int i;
+ for(i = 0; env != NULL && env[i] != NULL; i++)
+ if(strncmp(env[i], assignment, len) == 0)
+ return i;
+ return -1;
+}
+
+/*
+ * return count of environment assignments from open file F in
+ * assigned and list of malloced strings in env, return 0 or errno
+ * number
+ */
+
+static int
+read_env_file(FILE *F, char ***env, int *assigned)
+{
+ size_t alloced = 0;
+ size_t idx = 0;
+ int i;
+ char **l;
+ char buf[BUFSIZ], *p, *r;
+ char **tmp;
+ int ret = 0;
+
+ *assigned = 0;
+
+ l = *env;
+ for (idx = 0; l != NULL && l[idx] != NULL; idx++)
+ ;
+ if (l)
+ alloced = idx + 1;
+
+ /* This is somewhat more relaxed on what it accepts then
+ * Wietses sysv_environ from K4 was...
+ */
+ while (fgets(buf, BUFSIZ, F) != NULL) {
+ buf[strcspn(buf, "#\n")] = '\0';
+
+ for(p = buf; isspace((unsigned char)*p); p++);
+ if (*p == '\0')
+ continue;
+
+ /* Here one should check that it's a 'valid' env string... */
+ r = strchr(p, '=');
+ if (r == NULL)
+ continue;
+
+ if((i = find_var(l, p, r - p + 1)) >= 0) {
+ char *val;
+
+ if ((size_t)i >= alloced)
+ continue; /* Doesn't happen (fix scan-build noise) */
+ val = strdup(p);
+ if(val == NULL) {
+ ret = ENOMEM;
+ break;
+ }
+ free(l[i]);
+ l[i] = val;
+ (*assigned)++;
+ continue;
+ }
+
+ tmp = realloc(l, (idx+2) * sizeof (char *));
+ if(tmp == NULL) {
+ ret = ENOMEM;
+ break;
+ }
+
+ l = tmp;
+ l[idx] = strdup(p);
+ if(l[idx] == NULL) {
+ ret = ENOMEM;
+ break;
+ }
+ l[++idx] = NULL;
+ alloced = idx + 1;
+ (*assigned)++;
+ }
+ if(ferror(F))
+ ret = errno;
+ *env = l;
+ return ret;
+}
+
+/*
+ * return count of environment assignments from file and
+ * list of malloced strings in `env'
+ */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+read_environment(const char *file, char ***env)
+{
+ int assigned;
+ FILE *F;
+
+ if ((F = fopen(file, "r")) == NULL)
+ return 0;
+
+ read_env_file(F, env, &assigned);
+ fclose(F);
+ return assigned;
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+free_environment(char **env)
+{
+ int i;
+ if (env == NULL)
+ return;
+ for (i = 0; env[i]; i++)
+ free(env[i]);
+ free(env);
+}
diff --git a/third_party/heimdal/lib/roken/eread.c b/third_party/heimdal/lib/roken/eread.c
new file mode 100644
index 0000000..ba30f02
--- /dev/null
+++ b/third_party/heimdal/lib/roken/eread.c
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/*
+ * Like read but never fails (and never returns partial data).
+ */
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+eread (int fd, void *buf, size_t nbytes)
+{
+ ssize_t ret;
+
+ ret = net_read (fd, buf, nbytes);
+ if (ret < 0)
+ err (1, "read");
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/erealloc.c b/third_party/heimdal/lib/roken/erealloc.c
new file mode 100644
index 0000000..1c30ecc
--- /dev/null
+++ b/third_party/heimdal/lib/roken/erealloc.c
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdlib.h>
+#include <err.h>
+
+#include "roken.h"
+
+/*
+ * Like realloc but never fails.
+ */
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+erealloc (void *ptr, size_t sz)
+{
+ void *tmp = realloc (ptr, sz);
+
+ if (tmp == NULL && sz != 0)
+ errx (1, "realloc %lu failed", (unsigned long)sz);
+ return tmp;
+}
diff --git a/third_party/heimdal/lib/roken/err.c b/third_party/heimdal/lib/roken/err.c
new file mode 100644
index 0000000..592ed69
--- /dev/null
+++ b/third_party/heimdal/lib/roken/err.c
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include "err.h"
+
+ROKEN_LIB_NORETURN_FUNCTION void ROKEN_LIB_CALL
+err(int eval, const char *fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ verr(eval, fmt, ap);
+ va_end(ap);
+}
diff --git a/third_party/heimdal/lib/roken/err.hin b/third_party/heimdal/lib/roken/err.hin
new file mode 100644
index 0000000..905b1eb
--- /dev/null
+++ b/third_party/heimdal/lib/roken/err.hin
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 1995 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __ERR_H__
+#define __ERR_H__
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+
+#if !defined(__GNUC__) && !defined(__attribute__)
+#define __attribute__(x)
+#endif
+
+#ifndef ROKEN_LIB_FUNCTION
+ #define ROKEN_LIB_FUNCTION
+#endif
+#ifndef ROKEN_LIB_NORETURN_FUNCTION
+ #ifdef _WIN32
+ #define ROKEN_LIB_NORETURN_FUNCTION __declspec(noreturn)
+ #else
+ #define ROKEN_LIB_NORETURN_FUNCTION
+ #endif
+#endif
+#ifndef ROKEN_LIB_CALL
+ #ifdef _WIN32
+ #define ROKEN_LIB_CALL __cdecl
+ #else
+ #define ROKEN_LIB_CALL
+ #endif
+#endif
+
+ROKEN_LIB_NORETURN_FUNCTION void ROKEN_LIB_CALL
+verr(int eval, const char *fmt, va_list ap)
+ __attribute__ ((__noreturn__, __format__ (__printf__, 2, 0)));
+
+ROKEN_LIB_NORETURN_FUNCTION void ROKEN_LIB_CALL
+err(int eval, const char *fmt, ...)
+ __attribute__ ((__noreturn__, __format__ (__printf__, 2, 3)));
+
+ROKEN_LIB_NORETURN_FUNCTION void ROKEN_LIB_CALL
+verrx(int eval, const char *fmt, va_list ap)
+ __attribute__ ((__noreturn__, __format__ (__printf__, 2, 0)));
+
+ROKEN_LIB_NORETURN_FUNCTION void ROKEN_LIB_CALL
+errx(int eval, const char *fmt, ...)
+ __attribute__ ((__noreturn__, __format__ (__printf__, 2, 3)));
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+vwarn(const char *fmt, va_list ap)
+ __attribute__ ((__format__ (__printf__, 1, 0)));
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+warn(const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 1, 2)));
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+vwarnx(const char *fmt, va_list ap)
+ __attribute__ ((__format__ (__printf__, 1, 0)));
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+warnx(const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 1, 2)));
+
+#endif /* __ERR_H__ */
diff --git a/third_party/heimdal/lib/roken/errx.c b/third_party/heimdal/lib/roken/errx.c
new file mode 100644
index 0000000..121c707
--- /dev/null
+++ b/third_party/heimdal/lib/roken/errx.c
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "err.h"
+
+ROKEN_LIB_NORETURN_FUNCTION void ROKEN_LIB_CALL
+errx(int eval, const char *fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ verrx(eval, fmt, ap);
+ va_end(ap);
+}
diff --git a/third_party/heimdal/lib/roken/esetenv.c b/third_party/heimdal/lib/roken/esetenv.c
new file mode 100644
index 0000000..3cbf5ed
--- /dev/null
+++ b/third_party/heimdal/lib/roken/esetenv.c
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2000, 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+#include <err.h>
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+esetenv(const char *var, const char *val, int rewrite)
+{
+ if (setenv (rk_UNCONST(var), rk_UNCONST(val), rewrite))
+ errx (1, "failed setting environment variable %s", var);
+}
diff --git a/third_party/heimdal/lib/roken/estrdup.c b/third_party/heimdal/lib/roken/estrdup.c
new file mode 100644
index 0000000..d275a28
--- /dev/null
+++ b/third_party/heimdal/lib/roken/estrdup.c
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdlib.h>
+#include <err.h>
+
+#include "roken.h"
+
+/*
+ * Like strdup but never fails.
+ */
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+estrdup (const char *str)
+{
+ char *tmp = strdup (str);
+
+ if (tmp == NULL)
+ errx (1, "strdup failed");
+ return tmp;
+}
diff --git a/third_party/heimdal/lib/roken/ewrite.c b/third_party/heimdal/lib/roken/ewrite.c
new file mode 100644
index 0000000..fce5705
--- /dev/null
+++ b/third_party/heimdal/lib/roken/ewrite.c
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/*
+ * Like write but never fails (and never returns partial data).
+ */
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+ewrite (int fd, const void *buf, size_t nbytes)
+{
+ ssize_t ret;
+
+ ret = net_write (fd, buf, nbytes);
+ if (ret < 0)
+ err (1, "write");
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/fchown.c b/third_party/heimdal/lib/roken/fchown.c
new file mode 100644
index 0000000..050c2dd
--- /dev/null
+++ b/third_party/heimdal/lib/roken/fchown.c
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+fchown(int fd, uid_t owner, gid_t group)
+{
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/flock.c b/third_party/heimdal/lib/roken/flock.c
new file mode 100644
index 0000000..068d099
--- /dev/null
+++ b/third_party/heimdal/lib/roken/flock.c
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifndef HAVE_FLOCK
+
+#include "roken.h"
+
+#define OP_MASK (LOCK_SH | LOCK_EX | LOCK_UN)
+
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_flock(int fd, int operation)
+{
+#if defined(HAVE_FCNTL) && defined(F_SETLK)
+ struct flock arg;
+ int code, cmd;
+
+ arg.l_whence = SEEK_SET;
+ arg.l_start = 0;
+ arg.l_len = 0; /* means to EOF */
+
+ if (operation & LOCK_NB)
+ cmd = F_SETLK;
+ else
+ cmd = F_SETLKW; /* Blocking */
+
+ switch (operation & OP_MASK) {
+ case LOCK_UN:
+ arg.l_type = F_UNLCK;
+ code = fcntl(fd, F_SETLK, &arg);
+ break;
+ case LOCK_SH:
+ arg.l_type = F_RDLCK;
+ code = fcntl(fd, cmd, &arg);
+ break;
+ case LOCK_EX:
+ arg.l_type = F_WRLCK;
+ code = fcntl(fd, cmd, &arg);
+ break;
+ default:
+ errno = EINVAL;
+ code = -1;
+ break;
+ }
+ return code;
+
+#elif defined(_WIN32)
+ /* Windows */
+
+#define FLOCK_OFFSET_LOW 0
+#define FLOCK_OFFSET_HIGH 0
+#define FLOCK_LENGTH_LOW 0x00000000
+#define FLOCK_LENGTH_HIGH 0x80000000
+
+ HANDLE hFile;
+ OVERLAPPED ov;
+ BOOL rv = FALSE;
+ DWORD f = 0;
+
+ hFile = (HANDLE) _get_osfhandle(fd);
+ if (hFile == NULL || hFile == INVALID_HANDLE_VALUE) {
+ _set_errno(EBADF);
+ return -1;
+ }
+
+ ZeroMemory(&ov, sizeof(ov));
+ ov.hEvent = NULL;
+ ov.Offset = FLOCK_OFFSET_LOW;
+ ov.OffsetHigh = FLOCK_OFFSET_HIGH;
+
+ if (operation & LOCK_NB)
+ f = LOCKFILE_FAIL_IMMEDIATELY;
+
+ switch (operation & OP_MASK) {
+ case LOCK_UN: /* Unlock */
+ rv = UnlockFileEx(hFile, 0,
+ FLOCK_LENGTH_LOW, FLOCK_LENGTH_HIGH, &ov);
+ break;
+
+ case LOCK_SH: /* Shared lock */
+ rv = LockFileEx(hFile, f, 0,
+ FLOCK_LENGTH_LOW, FLOCK_LENGTH_HIGH, &ov);
+ break;
+
+ case LOCK_EX: /* Exclusive lock */
+ rv = LockFileEx(hFile, f|LOCKFILE_EXCLUSIVE_LOCK, 0,
+ FLOCK_LENGTH_LOW, FLOCK_LENGTH_HIGH,
+ &ov);
+ break;
+
+ default:
+ _set_errno(EINVAL);
+ return -1;
+ }
+
+ if (!rv) {
+ switch (GetLastError()) {
+ case ERROR_SHARING_VIOLATION:
+ case ERROR_LOCK_VIOLATION:
+ case ERROR_IO_PENDING:
+ _set_errno(EWOULDBLOCK);
+ break;
+
+ case ERROR_ACCESS_DENIED:
+ _set_errno(EACCES);
+ break;
+
+ default:
+ _set_errno(ENOLCK);
+ }
+ return -1;
+ }
+
+ return 0;
+
+#else
+ return -1;
+#endif
+}
+
+#endif
+
diff --git a/third_party/heimdal/lib/roken/fnmatch.c b/third_party/heimdal/lib/roken/fnmatch.c
new file mode 100644
index 0000000..74f3528
--- /dev/null
+++ b/third_party/heimdal/lib/roken/fnmatch.c
@@ -0,0 +1,175 @@
+/* $NetBSD: fnmatch.c,v 1.11 1995/02/27 03:43:06 cgd Exp $ */
+
+/*
+ * Copyright (c) 1989, 1993, 1994
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Guido van Rossum.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fnmatch.c 8.2 (Berkeley) 4/16/94";
+#else
+static char rcsid[] = "$NetBSD: fnmatch.c,v 1.11 1995/02/27 03:43:06 cgd Exp $";
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Function fnmatch() as specified in POSIX 1003.2-1992, section B.6.
+ * Compares a filename or pathname to a pattern.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <roken.h>
+
+#include <fnmatch.h>
+#include <string.h>
+
+#define EOS '\0'
+
+static const char *rangematch (const char *, int, int);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_fnmatch(const char *pattern, const char *string, int flags)
+{
+ const char *stringstart;
+ char c, test;
+
+ for (stringstart = string;;)
+ switch (c = *pattern++) {
+ case EOS:
+ return (*string == EOS ? 0 : FNM_NOMATCH);
+ case '?':
+ if (*string == EOS)
+ return (FNM_NOMATCH);
+ if (*string == '/' && (flags & FNM_PATHNAME))
+ return (FNM_NOMATCH);
+ if (*string == '.' && (flags & FNM_PERIOD) &&
+ (string == stringstart ||
+ ((flags & FNM_PATHNAME) && *(string - 1) == '/')))
+ return (FNM_NOMATCH);
+ ++string;
+ break;
+ case '*':
+ c = *pattern;
+ /* Collapse multiple stars. */
+ while (c == '*')
+ c = *++pattern;
+
+ if (*string == '.' && (flags & FNM_PERIOD) &&
+ (string == stringstart ||
+ ((flags & FNM_PATHNAME) && *(string - 1) == '/')))
+ return (FNM_NOMATCH);
+
+ /* Optimize for pattern with * at end or before /. */
+ if (c == EOS)
+ if (flags & FNM_PATHNAME)
+ return (strchr(string, '/') == NULL ?
+ 0 : FNM_NOMATCH);
+ else
+ return (0);
+ else if (c == '/' && flags & FNM_PATHNAME) {
+ if ((string = strchr(string, '/')) == NULL)
+ return (FNM_NOMATCH);
+ break;
+ }
+
+ /* General case, use recursion. */
+ while ((test = *string) != EOS) {
+ if (!rk_fnmatch(pattern, string, flags & ~FNM_PERIOD))
+ return (0);
+ if (test == '/' && flags & FNM_PATHNAME)
+ break;
+ ++string;
+ }
+ return (FNM_NOMATCH);
+ case '[':
+ if (*string == EOS)
+ return (FNM_NOMATCH);
+ if (*string == '/' && flags & FNM_PATHNAME)
+ return (FNM_NOMATCH);
+ if ((pattern =
+ rangematch(pattern, *string, flags)) == NULL)
+ return (FNM_NOMATCH);
+ ++string;
+ break;
+ case '\\':
+ if (!(flags & FNM_NOESCAPE)) {
+ if ((c = *pattern++) == EOS) {
+ c = '\\';
+ --pattern;
+ }
+ }
+ fallthrough;
+ default:
+ if (c != *string++)
+ return (FNM_NOMATCH);
+ break;
+ }
+ /* NOTREACHED */
+}
+
+static const char *
+rangematch(const char *pattern, int test, int flags)
+{
+ int negate, ok;
+ char c, c2;
+
+ /*
+ * A bracket expression starting with an unquoted circumflex
+ * character produces unspecified results (IEEE 1003.2-1992,
+ * 3.13.2). This implementation treats it like '!', for
+ * consistency with the regular expression syntax.
+ * J.T. Conklin (conklin@ngai.kaleida.com)
+ */
+ if (negate = (*pattern == '!' || *pattern == '^'))
+ ++pattern;
+
+ for (ok = 0; (c = *pattern++) != ']';) {
+ if (c == '\\' && !(flags & FNM_NOESCAPE))
+ c = *pattern++;
+ if (c == EOS)
+ return (NULL);
+ if (*pattern == '-'
+ && (c2 = *(pattern+1)) != EOS && c2 != ']') {
+ pattern += 2;
+ if (c2 == '\\' && !(flags & FNM_NOESCAPE))
+ c2 = *pattern++;
+ if (c2 == EOS)
+ return (NULL);
+ if (c <= test && test <= c2)
+ ok = 1;
+ } else if (c == test)
+ ok = 1;
+ }
+ return (ok == negate ? NULL : pattern);
+}
diff --git a/third_party/heimdal/lib/roken/fnmatch.hin b/third_party/heimdal/lib/roken/fnmatch.hin
new file mode 100644
index 0000000..fd96656
--- /dev/null
+++ b/third_party/heimdal/lib/roken/fnmatch.hin
@@ -0,0 +1,66 @@
+/* $NetBSD: fnmatch.h,v 1.5 1994/10/26 00:55:53 cgd Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)fnmatch.h 8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _FNMATCH_H_
+#define _FNMATCH_H_
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __stdcall
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define FNM_NOMATCH 1 /* Match failed. */
+
+#define FNM_NOESCAPE 0x01 /* Disable backslash escaping. */
+#define FNM_PATHNAME 0x02 /* Slash must be matched by slash. */
+#define FNM_PERIOD 0x04 /* Period must be matched by period. */
+
+int ROKEN_LIB_FUNCTION
+rk_fnmatch (const char *, const char *, int);
+
+#define fnmatch(a,b,c) rk_fnmatch(a,b,c)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !_FNMATCH_H_ */
diff --git a/third_party/heimdal/lib/roken/freeaddrinfo.c b/third_party/heimdal/lib/roken/freeaddrinfo.c
new file mode 100644
index 0000000..80a7487
--- /dev/null
+++ b/third_party/heimdal/lib/roken/freeaddrinfo.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/*
+ * free the list of `struct addrinfo' starting at `ai'
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_freeaddrinfo(struct addrinfo *ai)
+{
+ struct addrinfo *tofree;
+
+ while(ai != NULL) {
+ free (ai->ai_canonname);
+ free (ai->ai_addr);
+ tofree = ai;
+ ai = ai->ai_next;
+ free (tofree);
+ }
+}
diff --git a/third_party/heimdal/lib/roken/freehostent.c b/third_party/heimdal/lib/roken/freehostent.c
new file mode 100644
index 0000000..05dd0fe
--- /dev/null
+++ b/third_party/heimdal/lib/roken/freehostent.c
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/*
+ * free a malloced hostent
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_freehostent(struct hostent *h)
+{
+ char **p;
+
+ free (h->h_name);
+ if (h->h_aliases != NULL) {
+ for (p = h->h_aliases; *p != NULL; ++p)
+ free (*p);
+ free (h->h_aliases);
+ }
+ if (h->h_addr_list != NULL) {
+ for (p = h->h_addr_list; *p != NULL; ++p)
+ free (*p);
+ free (h->h_addr_list);
+ }
+ free (h);
+}
diff --git a/third_party/heimdal/lib/roken/fseeko.c b/third_party/heimdal/lib/roken/fseeko.c
new file mode 100644
index 0000000..b6ffaa2
--- /dev/null
+++ b/third_party/heimdal/lib/roken/fseeko.c
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+#ifndef HAVE_FSEEKO
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+fseeko(FILE *f, off_t o, int w)
+{
+#ifdef HAVE__FSEEKI64
+ return _fseeki64(f, o, w);
+#else
+ return fseek(f, o, w);
+#endif
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/ftello.c b/third_party/heimdal/lib/roken/ftello.c
new file mode 100644
index 0000000..cd3b84b
--- /dev/null
+++ b/third_party/heimdal/lib/roken/ftello.c
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+#ifndef HAVE_FTELLO
+ROKEN_LIB_FUNCTION off_t ROKEN_LIB_CALL
+ftello(FILE *f)
+{
+#ifdef HAVE__FTELLI64
+ return _ftelli64(f);
+#else
+ return ftell(f);
+#endif
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/gai_strerror.c b/third_party/heimdal/lib/roken/gai_strerror.c
new file mode 100644
index 0000000..1e326be
--- /dev/null
+++ b/third_party/heimdal/lib/roken/gai_strerror.c
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+static struct gai_error {
+ int code;
+ const char *str;
+} errors[] = {
+{EAI_NOERROR, "no error"},
+#ifdef EAI_ADDRFAMILY
+{EAI_ADDRFAMILY, "address family for nodename not supported"},
+#endif
+{EAI_AGAIN, "temporary failure in name resolution"},
+{EAI_BADFLAGS, "invalid value for ai_flags"},
+{EAI_FAIL, "non-recoverable failure in name resolution"},
+{EAI_FAMILY, "ai_family not supported"},
+{EAI_MEMORY, "memory allocation failure"},
+#ifdef EAI_NODATA
+{EAI_NODATA, "no address associated with nodename"},
+#endif
+{EAI_NONAME, "nodename nor servname provided, or not known"},
+{EAI_SERVICE, "servname not supported for ai_socktype"},
+{EAI_SOCKTYPE, "ai_socktype not supported"},
+{EAI_SYSTEM, "system error returned in errno"},
+{0, NULL},
+};
+
+/*
+ *
+ */
+
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
+gai_strerror(int ecode)
+{
+ struct gai_error *g;
+
+ for (g = errors; g->str != NULL; ++g)
+ if (g->code == ecode)
+ return g->str;
+ return "unknown error code in gai_strerror";
+}
diff --git a/third_party/heimdal/lib/roken/get_window_size.c b/third_party/heimdal/lib/roken/get_window_size.c
new file mode 100644
index 0000000..5a4a175
--- /dev/null
+++ b/third_party/heimdal/lib/roken/get_window_size.c
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+#if 0 /* Where were those needed? /confused */
+#ifdef HAVE_SYS_PROC_H
+#include <sys/proc.h>
+#endif
+
+#ifdef HAVE_SYS_TTY_H
+#include <sys/tty.h>
+#endif
+#endif
+
+#ifdef HAVE_TERMIOS_H
+#include <termios.h>
+#endif
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+get_window_size(int fd, int *lines, int *columns)
+{
+ char *s;
+
+#if defined(TIOCGWINSZ)
+ {
+ struct winsize ws;
+ int ret;
+ ret = ioctl(fd, TIOCGWINSZ, &ws);
+ if (ret != -1) {
+ if (lines)
+ *lines = ws.ws_row;
+ if (columns)
+ *columns = ws.ws_col;
+ return 0;
+ }
+ }
+#elif defined(TIOCGSIZE)
+ {
+ struct ttysize ts;
+ int ret;
+ ret = ioctl(fd, TIOCGSIZE, &ts);
+ if (ret != -1) {
+ if (lines)
+ *lines = ts.ws_lines;
+ if (columns)
+ *columns = ts.ts_cols;
+ return 0;
+ }
+ }
+#elif defined(HAVE__SCRSIZE)
+ {
+ int dst[2];
+
+ _scrsize(dst);
+ if (lines)
+ *lines = dst[1];
+ if (columns)
+ *columns = dst[0];
+ return 0;
+ }
+#elif defined(_WIN32)
+ {
+ intptr_t fh = 0;
+ CONSOLE_SCREEN_BUFFER_INFO sb_info;
+
+ fh = _get_osfhandle(fd);
+ if (fh != (intptr_t) INVALID_HANDLE_VALUE &&
+ GetConsoleScreenBufferInfo((HANDLE) fh, &sb_info)) {
+ if (lines)
+ *lines = 1 + sb_info.srWindow.Bottom - sb_info.srWindow.Top;
+ if (columns)
+ *columns = 1 + sb_info.srWindow.Right - sb_info.srWindow.Left;
+
+ return 0;
+ }
+ }
+#endif
+ if (columns) {
+ if ((s = getenv("COLUMNS")))
+ *columns = atoi(s);
+ else
+ return -1;
+ }
+ if (lines) {
+ if ((s = getenv("LINES")))
+ *lines = atoi(s);
+ else
+ return -1;
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/getaddrinfo-test.c b/third_party/heimdal/lib/roken/getaddrinfo-test.c
new file mode 100644
index 0000000..6bdc603
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getaddrinfo-test.c
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 1999 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include "getarg.h"
+
+static int flags;
+static int family;
+static int socktype;
+
+static int verbose_counter;
+static int version_flag;
+static int help_flag;
+
+static struct getargs args[] = {
+ {"verbose", 0, arg_counter, &verbose_counter,"verbose", NULL},
+ {"flags", 0, arg_integer, &flags, "flags", NULL},
+ {"family", 0, arg_integer, &family, "family", NULL},
+ {"socktype",0, arg_integer, &socktype, "socktype", NULL},
+ {"version", 0, arg_flag, &version_flag, "print version",NULL},
+ {"help", 0, arg_flag, &help_flag, NULL, NULL}
+};
+
+static void
+usage(int ret)
+{
+ arg_printusage (args,
+ sizeof(args) / sizeof(args[0]),
+ NULL,
+ "[nodename servname...]");
+ exit (ret);
+}
+
+static void
+doit (const char *nodename, const char *servname)
+{
+ struct addrinfo hints;
+ struct addrinfo *res, *r;
+ int ret;
+
+ if (verbose_counter)
+ printf ("(%s,%s)... ", nodename ? nodename : "null", servname);
+
+ memset (&hints, 0, sizeof(hints));
+ hints.ai_flags = flags;
+ hints.ai_family = family;
+ hints.ai_socktype = socktype;
+
+ ret = getaddrinfo (nodename, servname, &hints, &res);
+ if (ret)
+ errx(1, "error: %s\n", gai_strerror(ret));
+
+ if (verbose_counter)
+ printf ("\n");
+
+ for (r = res; r != NULL; r = r->ai_next) {
+ char addrstr[256];
+
+ if (inet_ntop (r->ai_family,
+ socket_get_address (r->ai_addr),
+ addrstr, sizeof(addrstr)) == NULL) {
+ if (verbose_counter)
+ printf ("\tbad address?\n");
+ continue;
+ }
+ if (verbose_counter) {
+ printf ("\tfamily = %d, socktype = %d, protocol = %d, "
+ "address = \"%s\", port = %d",
+ r->ai_family, r->ai_socktype, r->ai_protocol,
+ addrstr,
+ ntohs(socket_get_port (r->ai_addr)));
+ if (r->ai_canonname)
+ printf (", canonname = \"%s\"", r->ai_canonname);
+ printf ("\n");
+ }
+ }
+ freeaddrinfo (res);
+}
+
+int
+main(int argc, char **argv)
+{
+ int optidx = 0;
+ int i;
+
+ setprogname (argv[0]);
+
+ if (getarg (args, sizeof(args) / sizeof(args[0]), argc, argv,
+ &optidx))
+ usage (1);
+
+ if (help_flag)
+ usage (0);
+
+ if (version_flag) {
+ fprintf (stderr, "%s from %s-%s\n", getprogname(), PACKAGE, VERSION);
+ return 0;
+ }
+
+ if (rk_SOCK_INIT())
+ errx(1, "Failed to initialize sockets (%s)", strerror(rk_SOCK_ERRNO));
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (argc % 2 != 0)
+ usage (1);
+
+ for (i = 0; i < argc; i += 2) {
+ const char *nodename = argv[i];
+
+ if (strcmp (nodename, "null") == 0)
+ nodename = NULL;
+
+ doit (nodename, argv[i+1]);
+ }
+ rk_SOCK_EXIT();
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/getaddrinfo.c b/third_party/heimdal/lib/roken/getaddrinfo.c
new file mode 100644
index 0000000..12a26a7
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getaddrinfo.c
@@ -0,0 +1,414 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/*
+ * uses hints->ai_socktype and hints->ai_protocol
+ */
+
+static int
+get_port_protocol_socktype (const char *servname,
+ const struct addrinfo *hints,
+ int *port,
+ int *protocol,
+ int *socktype)
+{
+ struct servent *se;
+ const char *proto_str = NULL;
+
+ *socktype = 0;
+
+ if (hints != NULL && hints->ai_protocol != 0) {
+ struct protoent *protoent = getprotobynumber (hints->ai_protocol);
+
+ if (protoent == NULL)
+ return EAI_SOCKTYPE; /* XXX */
+
+ proto_str = protoent->p_name;
+ *protocol = protoent->p_proto;
+ }
+
+ if (hints != NULL)
+ *socktype = hints->ai_socktype;
+
+ if (*socktype == SOCK_STREAM) {
+ se = getservbyname (servname, proto_str ? proto_str : "tcp");
+ if (proto_str == NULL)
+ *protocol = IPPROTO_TCP;
+ } else if (*socktype == SOCK_DGRAM) {
+ se = getservbyname (servname, proto_str ? proto_str : "udp");
+ if (proto_str == NULL)
+ *protocol = IPPROTO_UDP;
+ } else if (*socktype == 0) {
+ if (proto_str != NULL) {
+ se = getservbyname (servname, proto_str);
+ } else {
+ se = getservbyname (servname, "tcp");
+ *protocol = IPPROTO_TCP;
+ *socktype = SOCK_STREAM;
+ if (se == NULL) {
+ se = getservbyname (servname, "udp");
+ *protocol = IPPROTO_UDP;
+ *socktype = SOCK_DGRAM;
+ }
+ }
+ } else
+ return EAI_SOCKTYPE;
+
+ if (se == NULL) {
+ char *endstr;
+
+ *port = htons(strtol (servname, &endstr, 10));
+ if (servname == endstr)
+ return EAI_NONAME;
+ } else {
+ *port = se->s_port;
+ }
+ return 0;
+}
+
+static int
+add_one (int port, int protocol, int socktype,
+ struct addrinfo ***ptr,
+ int (*func)(struct addrinfo *, void *data, int port),
+ void *data,
+ char *canonname)
+{
+ struct addrinfo *a;
+ int ret;
+
+ a = malloc (sizeof (*a));
+ if (a == NULL)
+ return EAI_MEMORY;
+ memset (a, 0, sizeof(*a));
+ a->ai_flags = 0;
+ a->ai_next = NULL;
+ a->ai_protocol = protocol;
+ a->ai_socktype = socktype;
+ a->ai_canonname = canonname;
+ ret = (*func)(a, data, port);
+ if (ret) {
+ free (a);
+ return ret;
+ }
+ **ptr = a;
+ *ptr = &a->ai_next;
+ return 0;
+}
+
+static int
+const_v4 (struct addrinfo *a, void *data, int port)
+{
+ struct sockaddr_in *sin4;
+ struct in_addr *addr = (struct in_addr *)data;
+
+ a->ai_family = PF_INET;
+ a->ai_addrlen = sizeof(*sin4);
+ a->ai_addr = malloc (sizeof(*sin4));
+ if (a->ai_addr == NULL)
+ return EAI_MEMORY;
+ sin4 = (struct sockaddr_in *)a->ai_addr;
+ memset (sin4, 0, sizeof(*sin4));
+ sin4->sin_family = AF_INET;
+ sin4->sin_port = port;
+ sin4->sin_addr = *addr;
+ return 0;
+}
+
+#ifdef HAVE_IPV6
+static int
+const_v6 (struct addrinfo *a, void *data, int port)
+{
+ struct sockaddr_in6 *sin6;
+ struct in6_addr *addr = (struct in6_addr *)data;
+
+ a->ai_family = PF_INET6;
+ a->ai_addrlen = sizeof(*sin6);
+ a->ai_addr = malloc (sizeof(*sin6));
+ if (a->ai_addr == NULL)
+ return EAI_MEMORY;
+ sin6 = (struct sockaddr_in6 *)a->ai_addr;
+ memset (sin6, 0, sizeof(*sin6));
+ sin6->sin6_family = AF_INET6;
+ sin6->sin6_port = port;
+ sin6->sin6_addr = *addr;
+ return 0;
+}
+#endif
+
+/* this is mostly a hack for some versions of AIX that has a prototype
+ for in6addr_loopback but no actual symbol in libc */
+#if defined(HAVE_IPV6) && !defined(HAVE_IN6ADDR_LOOPBACK) && defined(IN6ADDR_LOOPBACK_INIT)
+#define in6addr_loopback _roken_in6addr_loopback
+struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
+#endif
+
+static int
+get_null (const struct addrinfo *hints,
+ int port, int protocol, int socktype,
+ struct addrinfo **res)
+{
+ struct in_addr v4_addr;
+#ifdef HAVE_IPV6
+ struct in6_addr v6_addr;
+#endif
+ struct addrinfo *first = NULL;
+ struct addrinfo **current = &first;
+ int family = PF_UNSPEC;
+ int ret;
+
+ if (hints != NULL)
+ family = hints->ai_family;
+
+ if (hints && hints->ai_flags & AI_PASSIVE) {
+ v4_addr.s_addr = INADDR_ANY;
+#ifdef HAVE_IPV6
+ v6_addr = in6addr_any;
+#endif
+ } else {
+ v4_addr.s_addr = htonl(INADDR_LOOPBACK);
+#ifdef HAVE_IPV6
+ v6_addr = in6addr_loopback;
+#endif
+ }
+
+#ifdef HAVE_IPV6
+ if (family == PF_INET6 || family == PF_UNSPEC) {
+ ret = add_one (port, protocol, socktype,
+ &current, const_v6, &v6_addr, NULL);
+ }
+#endif
+ if (family == PF_INET || family == PF_UNSPEC) {
+ ret = add_one (port, protocol, socktype,
+ &current, const_v4, &v4_addr, NULL);
+ }
+ *res = first;
+ return 0;
+}
+
+static int
+add_hostent (int port, int protocol, int socktype,
+ struct addrinfo ***current,
+ int (*func)(struct addrinfo *, void *data, int port),
+ struct hostent *he, int *flags)
+{
+ int ret;
+ char *canonname = NULL;
+ char **h;
+
+ if (*flags & AI_CANONNAME) {
+ struct hostent *he2 = NULL;
+ const char *tmp_canon;
+
+ tmp_canon = hostent_find_fqdn (he);
+ if (strchr (tmp_canon, '.') == NULL) {
+ int error;
+
+ he2 = getipnodebyaddr (he->h_addr_list[0], he->h_length,
+ he->h_addrtype, &error);
+ if (he2 != NULL) {
+ const char *tmp = hostent_find_fqdn (he2);
+
+ if (strchr (tmp, '.') != NULL)
+ tmp_canon = tmp;
+ }
+ }
+
+ canonname = strdup (tmp_canon);
+ if (he2 != NULL)
+ freehostent (he2);
+ if (canonname == NULL)
+ return EAI_MEMORY;
+ }
+
+ for (h = he->h_addr_list; *h != NULL; ++h) {
+ ret = add_one (port, protocol, socktype,
+ current, func, *h, canonname);
+ if (ret)
+ return ret;
+ if (*flags & AI_CANONNAME) {
+ *flags &= ~AI_CANONNAME;
+ canonname = NULL;
+ }
+ }
+ return 0;
+}
+
+static int
+get_number (const char *nodename,
+ const struct addrinfo *hints,
+ int port, int protocol, int socktype,
+ struct addrinfo **res)
+{
+ struct addrinfo *first = NULL;
+ struct addrinfo **current = &first;
+ int family = PF_UNSPEC;
+ int ret;
+
+ if (hints != NULL) {
+ family = hints->ai_family;
+ }
+
+#ifdef HAVE_IPV6
+ if (family == PF_INET6 || family == PF_UNSPEC) {
+ struct in6_addr v6_addr;
+
+ if (inet_pton (PF_INET6, nodename, &v6_addr) == 1) {
+ ret = add_one (port, protocol, socktype,
+ &current, const_v6, &v6_addr, NULL);
+ *res = first;
+ return ret;
+ }
+ }
+#endif
+ if (family == PF_INET || family == PF_UNSPEC) {
+ struct in_addr v4_addr;
+
+ if (inet_pton (PF_INET, nodename, &v4_addr) == 1) {
+ ret = add_one (port, protocol, socktype,
+ &current, const_v4, &v4_addr, NULL);
+ *res = first;
+ return ret;
+ }
+ }
+ return EAI_NONAME;
+}
+
+static int
+get_nodes (const char *nodename,
+ const struct addrinfo *hints,
+ int port, int protocol, int socktype,
+ struct addrinfo **res)
+{
+ struct addrinfo *first = NULL;
+ struct addrinfo **current = &first;
+ int family = PF_UNSPEC;
+ int flags = 0;
+ int ret = EAI_NONAME;
+ int error;
+
+ if (hints != NULL) {
+ family = hints->ai_family;
+ flags = hints->ai_flags;
+ }
+
+#ifdef HAVE_IPV6
+ if (family == PF_INET6 || family == PF_UNSPEC) {
+ struct hostent *he;
+
+ he = getipnodebyname (nodename, PF_INET6, 0, &error);
+
+ if (he != NULL) {
+ ret = add_hostent (port, protocol, socktype,
+ &current, const_v6, he, &flags);
+ freehostent (he);
+ }
+ }
+#endif
+ if (family == PF_INET || family == PF_UNSPEC) {
+ struct hostent *he;
+
+ he = getipnodebyname (nodename, PF_INET, 0, &error);
+
+ if (he != NULL) {
+ ret = add_hostent (port, protocol, socktype,
+ &current, const_v4, he, &flags);
+ freehostent (he);
+ }
+ }
+ *res = first;
+ return ret;
+}
+
+/*
+ * hints:
+ *
+ * struct addrinfo {
+ * int ai_flags;
+ * int ai_family;
+ * int ai_socktype;
+ * int ai_protocol;
+ * ...
+ * };
+ */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_getaddrinfo(const char *nodename,
+ const char *servname,
+ const struct addrinfo *hints,
+ struct addrinfo **res)
+{
+ int ret;
+ int port = 0;
+ int protocol = 0;
+ int socktype = 0;
+
+ *res = NULL;
+
+ if (servname == NULL && nodename == NULL)
+ return EAI_NONAME;
+
+ if (hints != NULL
+ && hints->ai_family != PF_UNSPEC
+ && hints->ai_family != PF_INET
+#ifdef HAVE_IPV6
+ && hints->ai_family != PF_INET6
+#endif
+ )
+ return EAI_FAMILY;
+
+ if (servname != NULL) {
+ ret = get_port_protocol_socktype (servname, hints,
+ &port, &protocol, &socktype);
+ if (ret)
+ return ret;
+ }
+ if (nodename != NULL) {
+ ret = get_number (nodename, hints, port, protocol, socktype, res);
+ if (ret) {
+ if(hints && hints->ai_flags & AI_NUMERICHOST)
+ ret = EAI_NONAME;
+ else
+ ret = get_nodes (nodename, hints, port, protocol, socktype,
+ res);
+ }
+ } else {
+ ret = get_null (hints, port, protocol, socktype, res);
+ }
+ if (ret)
+ rk_freeaddrinfo(*res);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/getaddrinfo_hostspec.c b/third_party/heimdal/lib/roken/getaddrinfo_hostspec.c
new file mode 100644
index 0000000..4541219
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getaddrinfo_hostspec.c
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/* getaddrinfo via string specifying host and port */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+roken_getaddrinfo_hostspec2(const char *hostspec,
+ int socktype,
+ int port,
+ struct addrinfo **ai)
+{
+ const char *p;
+ char portstr[NI_MAXSERV];
+ char host[MAXHOSTNAMELEN];
+ struct addrinfo hints;
+ int hostspec_len;
+
+ struct hst {
+ const char *prefix;
+ int socktype;
+ int protocol;
+ int port;
+ } *hstp, hst[] = {
+ { "http://", SOCK_STREAM, IPPROTO_TCP, 80 },
+ { "http/", SOCK_STREAM, IPPROTO_TCP, 80 },
+ { "tcp/", SOCK_STREAM, IPPROTO_TCP, 0 },
+ { "udp/", SOCK_DGRAM, IPPROTO_UDP, 0 },
+ { NULL, 0, 0, 0 }
+ };
+
+ memset(&hints, 0, sizeof(hints));
+
+ hints.ai_socktype = socktype;
+
+ for(hstp = hst; hstp->prefix; hstp++) {
+ if(strncmp(hostspec, hstp->prefix, strlen(hstp->prefix)) == 0) {
+ hints.ai_socktype = hstp->socktype;
+ hints.ai_protocol = hstp->protocol;
+ if(port == 0)
+ port = hstp->port;
+ hostspec += strlen(hstp->prefix);
+ break;
+ }
+ }
+
+ p = strchr (hostspec, ':');
+ if (p != NULL) {
+ char *end;
+
+ port = strtol (p + 1, &end, 0);
+ hostspec_len = p - hostspec;
+ } else {
+ hostspec_len = strlen(hostspec);
+ }
+ snprintf (portstr, sizeof(portstr), "%u", port);
+
+ snprintf (host, sizeof(host), "%.*s", hostspec_len, hostspec);
+ return getaddrinfo (host, portstr, &hints, ai);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+roken_getaddrinfo_hostspec(const char *hostspec,
+ int port,
+ struct addrinfo **ai)
+{
+ return roken_getaddrinfo_hostspec2(hostspec, 0, port, ai);
+}
diff --git a/third_party/heimdal/lib/roken/getarg.3 b/third_party/heimdal/lib/roken/getarg.3
new file mode 100644
index 0000000..0d01d8f
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getarg.3
@@ -0,0 +1,341 @@
+.\" Copyright (c) 1999 - 2002 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.Dd September 24, 1999
+.Dt GETARG 3
+.Os ROKEN
+.Sh NAME
+.Nm getarg ,
+.Nm arg_printusage
+.Nd collect command line options
+.Sh SYNOPSIS
+.In getarg.h
+.Ft int
+.Fn getarg "struct getargs *args" "size_t num_args" "int argc" "char **argv" "int *optind"
+.Ft void
+.Fn arg_printusage "struct getargs *args" "size_t num_args" "const char *progname" "const char *extra_string"
+.Sh DESCRIPTION
+.Fn getarg
+collects any command line options given to a program in an easily used way.
+.Fn arg_printusage
+pretty-prints the available options, with a short help text.
+.Pp
+.Fa args
+is the option specification to use, and it's an array of
+.Fa struct getargs
+elements.
+.Fa num_args
+is the size of
+.Fa args
+(in elements).
+.Fa argc
+and
+.Fa argv
+are the argument count and argument vector to extract option from.
+.Fa optind
+is a pointer to an integer where the index to the last processed
+argument is stored, it must be initialised to the first index (minus
+one) to process (normally 0) before the first call.
+.Pp
+.Fa arg_printusage
+take the same
+.Fa args
+and
+.Fa num_args
+as getarg;
+.Fa progname
+is the name of the program (to be used in the help text), and
+.Fa extra_string
+is a string to print after the actual options to indicate more
+arguments. The usefulness of this function is realised only be people
+who has used programs that has help strings that doesn't match what
+the code does.
+.Pp
+The
+.Fa getargs
+struct has the following elements.
+.Bd -literal
+struct getargs{
+ const char *long_name;
+ char short_name;
+ enum { arg_integer,
+ arg_string,
+ arg_flag,
+ arg_negative_flag,
+ arg_strings,
+ arg_double,
+ arg_collect
+ } type;
+ void *value;
+ const char *help;
+ const char *arg_help;
+};
+.Ed
+.Pp
+.Fa long_name
+is the long name of the option, it can be
+.Dv NULL ,
+if you don't want a long name.
+.Fa short_name
+is the characted to use as short option, it can be zero. If the option
+has a value the
+.Fa value
+field gets filled in with that value interpreted as specified by the
+.Fa type
+field.
+.Fa help
+is a longer help string for the option as a whole, if it's
+.Dv NULL
+the help text for the option is omitted (but it's still displayed in
+the synopsis).
+.Fa arg_help
+is a description of the argument, if
+.Dv NULL
+a default value will be used, depending on the type of the option:
+.Pp
+.Bl -hang -width arg_negative_flag
+.It arg_integer
+the argument is a signed integer, and
+.Fa value
+should point to an
+.Fa int .
+.It Fa arg_string
+the argument is a string, and
+.Fa value
+should point to a
+.Fa char* .
+.It Fa arg_flag
+the argument is a flag, and
+.Fa value
+should point to a
+.Fa int .
+It gets filled in with either zero or one, depending on how the option
+is given, the normal case being one. Note that if the option isn't
+given, the value isn't altered, so it should be initialised to some
+useful default.
+.It Fa arg_negative_flag
+this is the same as
+.Fa arg_flag
+but it reverses the meaning of the flag (a given short option clears
+the flag), and the synopsis of a long option is negated.
+.It Fa arg_strings
+the argument can be given multiple times, and the values are collected
+in an array;
+.Fa value
+should be a pointer to a
+.Fa struct getarg_strings
+structure, which holds a length and a string pointer.
+.It Fa arg_double
+argument is a double precision floating point value, and
+.Fa value
+should point to a
+.Fa double .
+.It Fa arg_collect
+allows more fine-grained control of the option parsing process.
+.Fa value
+should be a pointer to a
+.Fa getarg_collect_info
+structure:
+.Bd -literal
+typedef int (*getarg_collect_func)(int short_opt,
+ int argc,
+ char **argv,
+ int *optind,
+ int *optarg,
+ void *data);
+
+typedef struct getarg_collect_info {
+ getarg_collect_func func;
+ void *data;
+} getarg_collect_info;
+.Ed
+.Pp
+With the
+.Fa func
+member set to a function to call, and
+.Fa data
+to some application specific data. The parameters to the collect function are:
+.Bl -inset
+.It Fa short_flag
+non-zero if this call is via a short option flag, zero otherwise
+.It Fa argc , argv
+the whole argument list
+.It Fa optind
+pointer to the index in argv where the flag is
+.It Fa optarg
+pointer to the index in argv[*optind] where the flag name starts
+.It Fa data
+application specific data
+.El
+.Pp
+You can modify
+.Fa *optind ,
+and
+.Fa *optarg ,
+but to do this correct you (more or less) have to know about the inner
+workings of getarg.
+.Pp
+You can skip parts of arguments by increasing
+.Fa *optarg
+(you could
+implement the
+.Fl z Ns Ar 3
+set of flags from
+.Nm gzip
+with this), or whole argument strings by increasing
+.Fa *optind
+(let's say you want a flag
+.Fl c Ar x y z
+to specify a coordinate); if you also have to set
+.Fa *optarg
+to a sane value.
+.Pp
+The collect function should return one of
+.Dv ARG_ERR_NO_MATCH , ARG_ERR_BAD_ARG , ARG_ERR_NO_ARG, ENOMEM
+on error, zero otherwise.
+.Pp
+For your convenience there is a function,
+.Fn getarg_optarg ,
+that returns the traditional argument string, and you pass it all
+arguments, sans data, that where given to the collection function.
+.Pp
+Don't use this more this unless you absolutely have to.
+.El
+.Pp
+Option parsing is similar to what
+.Xr getopt
+uses. Short options without arguments can be compressed
+.Pf ( Fl xyz
+is the same as
+.Fl x y z ) ,
+and short
+options with arguments take these as either the rest of the
+argv-string or as the next option
+.Pf ( Fl o Ns Ar foo ,
+or
+.Fl o Ar foo ) .
+.Pp
+Long option names are prefixed with -- (double dash), and the value
+with a = (equal),
+.Fl Fl foo= Ns Ar bar .
+Long option flags can either be specified as they are
+.Pf ( Fl Fl help ) ,
+or with an (boolean parsable) option
+.Pf ( Fl Fl help= Ns Ar yes ,
+.Fl Fl help= Ns Ar true ,
+or similar), or they can also be negated
+.Pf ( Fl Fl no-help
+is the same as
+.Fl Fl help= Ns no ) ,
+and if you're really confused you can do it multiple times
+.Pf ( Fl Fl no-no-help= Ns Ar false ,
+or even
+.Fl Fl no-no-help= Ns Ar maybe ) .
+.Sh EXAMPLE
+.Bd -literal
+#include <stdio.h>
+#include <string.h>
+#include <getarg.h>
+
+char *source = "Ouagadougou";
+char *destination;
+int weight;
+int include_catalog = 1;
+int help_flag;
+
+struct getargs args[] = {
+ { "source", 's', arg_string, &source,
+ "source of shippment", "city" },
+ { "destination", 'd', arg_string, &destination,
+ "destination of shippment", "city" },
+ { "weight", 'w', arg_integer, &weight,
+ "weight of shippment", "tons" },
+ { "catalog", 'c', arg_negative_flag, &include_catalog,
+ "include product catalog" },
+ { "help", 'h', arg_flag, &help_flag }
+};
+
+int num_args = sizeof(args) / sizeof(args[0]); /* number of elements in args */
+
+const char *progname = "ship++";
+
+int
+main(int argc, char **argv)
+{
+ int optind = 0;
+ if (getarg(args, num_args, argc, argv, &optind)) {
+ arg_printusage(args, num_args, progname, "stuff...");
+ exit (1);
+ }
+ if (help_flag) {
+ arg_printusage(args, num_args, progname, "stuff...");
+ exit (0);
+ }
+ if (destination == NULL) {
+ fprintf(stderr, "%s: must specify destination\en", progname);
+ exit(1);
+ }
+ if (strcmp(source, destination) == 0) {
+ fprintf(stderr, "%s: destination must be different from source\en");
+ exit(1);
+ }
+ /* include more stuff here ... */
+ exit(2);
+}
+.Ed
+.Pp
+The output help output from this program looks like this:
+.Bd -literal
+$ ship++ --help
+Usage: ship++ [--source=city] [-s city] [--destination=city] [-d city]
+ [--weight=tons] [-w tons] [--no-catalog] [-c] [--help] [-h] stuff...
+-s city, --source=city source of shippment
+-d city, --destination=city destination of shippment
+-w tons, --weight=tons weight of shippment
+-c, --no-catalog include product catalog
+.Ed
+.Sh BUGS
+It should be more flexible, so it would be possible to use other more
+complicated option syntaxes, such as what
+.Xr ps 1 ,
+and
+.Xr tar 1 ,
+uses, or the AFS model where you can skip the flag names as long as
+the options come in the correct order.
+.Pp
+Options with multiple arguments should be handled better.
+.Pp
+Should be integrated with SL.
+.Pp
+It's very confusing that the struct you pass in is called getargS.
+.Sh SEE ALSO
+.Xr getopt 3
diff --git a/third_party/heimdal/lib/roken/getarg.c b/third_party/heimdal/lib/roken/getarg.c
new file mode 100644
index 0000000..76f3c80
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getarg.c
@@ -0,0 +1,607 @@
+/*
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "roken.h"
+#include "getarg.h"
+
+#define ISFLAG(X) ((X).type == arg_flag || (X).type == arg_negative_flag)
+
+static size_t
+print_arg (char *string,
+ size_t len,
+ int mdoc,
+ int longp,
+ struct getargs *arg,
+ char *(i18n)(const char *))
+{
+ const char *s;
+
+ *string = '\0';
+
+ if (ISFLAG(*arg) || (!longp && arg->type == arg_counter))
+ return 0;
+
+ if(mdoc){
+ if(longp)
+ strlcat(string, "= Ns", len);
+ strlcat(string, " Ar ", len);
+ } else {
+ if (longp)
+ strlcat (string, "=", len);
+ else
+ strlcat (string, " ", len);
+ }
+
+ if (arg->arg_help)
+ s = (*i18n)(arg->arg_help);
+ else if (arg->type == arg_integer || arg->type == arg_counter)
+ s = "integer";
+ else if (arg->type == arg_string)
+ s = "string";
+ else if (arg->type == arg_strings)
+ s = "strings";
+ else if (arg->type == arg_double)
+ s = "float";
+ else
+ s = "<undefined>";
+
+ strlcat(string, s, len);
+ return 1 + strlen(s);
+}
+
+static void
+mandoc_template(struct getargs *args,
+ size_t num_args,
+ const char *progname,
+ const char *extra_string,
+ char *(i18n)(const char *))
+{
+ size_t i;
+ char timestr[64], cmd[64];
+ char buf[128];
+ const char *p;
+ time_t t;
+
+ printf(".\\\" Things to fix:\n");
+ printf(".\\\" * correct section, and operating system\n");
+ printf(".\\\" * remove Op from mandatory flags\n");
+ printf(".\\\" * use better macros for arguments (like .Pa for files)\n");
+ printf(".\\\"\n");
+ t = time(NULL);
+ strftime(timestr, sizeof(timestr), "%B %e, %Y", localtime(&t));
+ printf(".Dd %s\n", timestr);
+ p = strrchr(progname, '/');
+ if(p) p++; else p = progname;
+ strlcpy(cmd, p, sizeof(cmd));
+ strupr(cmd);
+
+ printf(".Dt %s SECTION\n", cmd);
+ printf(".Os OPERATING_SYSTEM\n");
+ printf(".Sh NAME\n");
+ printf(".Nm %s\n", p);
+ printf(".Nd in search of a description\n");
+ printf(".Sh SYNOPSIS\n");
+ printf(".Nm\n");
+ for(i = 0; i < num_args; i++){
+ /* we seem to hit a limit on number of arguments if doing
+ short and long flags with arguments -- split on two lines */
+ if(ISFLAG(args[i]) ||
+ args[i].short_name == 0 || args[i].long_name == NULL) {
+ printf(".Op ");
+
+ if(args[i].short_name) {
+ print_arg(buf, sizeof(buf), 1, 0, args + i, i18n);
+ printf("Fl %c%s", args[i].short_name, buf);
+ if(args[i].long_name)
+ printf(" | ");
+ }
+ if(args[i].long_name) {
+ print_arg(buf, sizeof(buf), 1, 1, args + i, i18n);
+ printf("Fl Fl %s%s%s",
+ args[i].type == arg_negative_flag ? "no-" : "",
+ args[i].long_name, buf);
+ }
+ printf("\n");
+ } else {
+ print_arg(buf, sizeof(buf), 1, 0, args + i, i18n);
+ printf(".Oo Fl %c%s \\*(Ba Xo\n", args[i].short_name, buf);
+ print_arg(buf, sizeof(buf), 1, 1, args + i, i18n);
+ printf(".Fl Fl %s%s\n.Xc\n.Oc\n", args[i].long_name, buf);
+ }
+ /*
+ if(args[i].type == arg_strings)
+ fprintf (stderr, "...");
+ */
+ }
+ if (extra_string && *extra_string)
+ printf (".Ar %s\n", extra_string);
+ printf(".Sh DESCRIPTION\n");
+ printf("Supported options:\n");
+ printf(".Bl -tag -width Ds\n");
+ for(i = 0; i < num_args; i++){
+ printf(".It Xo\n");
+ if(args[i].short_name){
+ printf(".Fl %c", args[i].short_name);
+ print_arg(buf, sizeof(buf), 1, 0, args + i, i18n);
+ printf("%s", buf);
+ if(args[i].long_name)
+ printf(" ,");
+ printf("\n");
+ }
+ if(args[i].long_name){
+ printf(".Fl Fl %s%s",
+ args[i].type == arg_negative_flag ? "no-" : "",
+ args[i].long_name);
+ print_arg(buf, sizeof(buf), 1, 1, args + i, i18n);
+ printf("%s\n", buf);
+ }
+ printf(".Xc\n");
+ if(args[i].help)
+ printf("%s\n", args[i].help);
+ /*
+ if(args[i].type == arg_strings)
+ fprintf (stderr, "...");
+ */
+ }
+ printf(".El\n");
+ printf(".\\\".Sh ENVIRONMENT\n");
+ printf(".\\\".Sh FILES\n");
+ printf(".\\\".Sh EXAMPLES\n");
+ printf(".\\\".Sh DIAGNOSTICS\n");
+ printf(".\\\".Sh SEE ALSO\n");
+ printf(".\\\".Sh STANDARDS\n");
+ printf(".\\\".Sh HISTORY\n");
+ printf(".\\\".Sh AUTHORS\n");
+ printf(".\\\".Sh BUGS\n");
+}
+
+static int
+check_column(FILE *f, int col, int len, int columns)
+{
+ if(col + len > columns) {
+ fprintf(f, "\n");
+ col = fprintf(f, " ");
+ }
+ return col;
+}
+
+static char *
+builtin_i18n(const char *str)
+{
+ return rk_UNCONST(str);
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+arg_printusage (struct getargs *args,
+ size_t num_args,
+ const char *progname,
+ const char *extra_string)
+{
+ arg_printusage_i18n(args, num_args, "Usage",
+ progname, extra_string, builtin_i18n);
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+arg_printusage_i18n (struct getargs *args,
+ size_t num_args,
+ const char *usage,
+ const char *progname,
+ const char *extra_string,
+ char *(*i18n)(const char *))
+{
+ size_t i, max_len = 0;
+ char buf[128];
+ int col = 0, columns;
+
+ if (progname == NULL)
+ progname = getprogname();
+
+ if (i18n == NULL)
+ i18n = builtin_i18n;
+
+ if(getenv("GETARGMANDOC")){
+ mandoc_template(args, num_args, progname, extra_string, i18n);
+ return;
+ }
+ if(get_window_size(2, NULL, &columns) == -1)
+ columns = 80;
+ col = 0;
+ col += fprintf (stderr, "%s: %s", usage, progname);
+ buf[0] = '\0';
+ for (i = 0; i < num_args; ++i) {
+ if(args[i].short_name && ISFLAG(args[i])) {
+ char s[2];
+ if(buf[0] == '\0')
+ strlcpy(buf, "[-", sizeof(buf));
+ s[0] = args[i].short_name;
+ s[1] = '\0';
+ strlcat(buf, s, sizeof(buf));
+ }
+ }
+ if(buf[0] != '\0') {
+ strlcat(buf, "]", sizeof(buf));
+ col = check_column(stderr, col, strlen(buf) + 1, columns);
+ col += fprintf(stderr, " %s", buf);
+ }
+
+ for (i = 0; i < num_args; ++i) {
+ size_t len = 0;
+
+ if (args[i].long_name) {
+ buf[0] = '\0';
+ strlcat(buf, "[--", sizeof(buf));
+ len += 2;
+ if(args[i].type == arg_negative_flag) {
+ strlcat(buf, "no-", sizeof(buf));
+ len += 3;
+ }
+ strlcat(buf, args[i].long_name, sizeof(buf));
+ len += strlen(args[i].long_name);
+ len += print_arg(buf + strlen(buf), sizeof(buf) - strlen(buf),
+ 0, 1, &args[i], i18n);
+ strlcat(buf, "]", sizeof(buf));
+ if(args[i].type == arg_strings)
+ strlcat(buf, "...", sizeof(buf));
+ col = check_column(stderr, col, strlen(buf) + 1, columns);
+ col += fprintf(stderr, " %s", buf);
+ }
+ if (args[i].short_name && !ISFLAG(args[i])) {
+ snprintf(buf, sizeof(buf), "[-%c", args[i].short_name);
+ len += 2;
+ len += print_arg(buf + strlen(buf), sizeof(buf) - strlen(buf),
+ 0, 0, &args[i], i18n);
+ strlcat(buf, "]", sizeof(buf));
+ if(args[i].type == arg_strings)
+ strlcat(buf, "...", sizeof(buf));
+ col = check_column(stderr, col, strlen(buf) + 1, columns);
+ col += fprintf(stderr, " %s", buf);
+ }
+ if (args[i].long_name && args[i].short_name)
+ len += 2; /* ", " */
+ max_len = max(max_len, len);
+ }
+ if (extra_string) {
+ check_column(stderr, col, strlen(extra_string) + 1, columns);
+ fprintf (stderr, " %s\n", extra_string);
+ } else
+ fprintf (stderr, "\n");
+ for (i = 0; i < num_args; ++i) {
+ if (args[i].help) {
+ size_t count = 0;
+
+ if (args[i].short_name) {
+ count += fprintf (stderr, "-%c", args[i].short_name);
+ print_arg (buf, sizeof(buf), 0, 0, &args[i], i18n);
+ count += fprintf(stderr, "%s", buf);
+ }
+ if (args[i].short_name && args[i].long_name)
+ count += fprintf (stderr, ", ");
+ if (args[i].long_name) {
+ count += fprintf (stderr, "--");
+ if (args[i].type == arg_negative_flag)
+ count += fprintf (stderr, "no-");
+ count += fprintf (stderr, "%s", args[i].long_name);
+ print_arg (buf, sizeof(buf), 0, 1, &args[i], i18n);
+ count += fprintf(stderr, "%s", buf);
+ }
+ while(count++ <= max_len)
+ putc (' ', stderr);
+ fprintf (stderr, "%s\n", (*i18n)(args[i].help));
+ }
+ }
+}
+
+static int
+add_string(getarg_strings *s, char *value)
+{
+ char **strings;
+
+ strings = realloc(s->strings, (s->num_strings + 1) * sizeof(*s->strings));
+ if (strings == NULL) {
+ free(s->strings);
+ s->strings = NULL;
+ s->num_strings = 0;
+ return ENOMEM;
+ }
+ s->strings = strings;
+ s->strings[s->num_strings] = value;
+ s->num_strings++;
+ return 0;
+}
+
+static int
+arg_match_long(struct getargs *args, size_t num_args,
+ char *argv, int argc, char **rargv, int *goptind)
+{
+ size_t i;
+ char *goptarg = NULL;
+ int negate = 0;
+ int partial_match = 0;
+ struct getargs *partial = NULL;
+ struct getargs *current = NULL;
+ int argv_len;
+ char *p;
+ int p_len;
+
+ argv_len = strlen(argv);
+ p = strchr (argv, '=');
+ if (p != NULL)
+ argv_len = p - argv;
+
+ for (i = 0; i < num_args; ++i) {
+ if(args[i].long_name) {
+ int len = strlen(args[i].long_name);
+ p = argv;
+ p_len = argv_len;
+ negate = 0;
+
+ for (;;) {
+ if (strncmp (args[i].long_name, p, p_len) == 0) {
+ if(p_len == len)
+ current = &args[i];
+ else {
+ ++partial_match;
+ partial = &args[i];
+ }
+ goptarg = p + p_len;
+ } else if (ISFLAG(args[i]) && strncmp (p, "no-", 3) == 0) {
+ negate = !negate;
+ p += 3;
+ p_len -= 3;
+ continue;
+ }
+ break;
+ }
+ if (current)
+ break;
+ }
+ }
+ if (current == NULL) {
+ if (partial_match == 1)
+ current = partial;
+ else
+ return ARG_ERR_NO_MATCH;
+ }
+
+ if(*goptarg == '\0'
+ && !ISFLAG(*current)
+ && current->type != arg_collect
+ && current->type != arg_counter)
+ return ARG_ERR_NO_MATCH;
+ switch(current->type){
+ case arg_integer:
+ {
+ int tmp;
+ if(sscanf(goptarg + 1, "%d", &tmp) != 1)
+ return ARG_ERR_BAD_ARG;
+ *(int*)current->value = tmp;
+ return 0;
+ }
+ case arg_string:
+ {
+ *(char**)current->value = goptarg + 1;
+ return 0;
+ }
+ case arg_strings:
+ {
+ return add_string((getarg_strings*)current->value, goptarg + 1);
+ }
+ case arg_flag:
+ case arg_negative_flag:
+ {
+ int *flag = current->value;
+ if(*goptarg == '\0' ||
+ strcmp(goptarg + 1, "yes") == 0 ||
+ strcmp(goptarg + 1, "true") == 0){
+ *flag = !negate;
+ return 0;
+ } else if (*goptarg && strcmp(goptarg + 1, "maybe") == 0) {
+ *flag = rk_random() & 1;
+ } else {
+ *flag = negate;
+ return 0;
+ }
+ return ARG_ERR_BAD_ARG;
+ }
+ case arg_counter :
+ {
+ int val;
+
+ if (*goptarg == '\0')
+ val = 1;
+ else if(sscanf(goptarg + 1, "%d", &val) != 1)
+ return ARG_ERR_BAD_ARG;
+ *(int *)current->value += val;
+ return 0;
+ }
+ case arg_double:
+ {
+ double tmp;
+ if(sscanf(goptarg + 1, "%lf", &tmp) != 1)
+ return ARG_ERR_BAD_ARG;
+ *(double*)current->value = tmp;
+ return 0;
+ }
+ case arg_collect:{
+ struct getarg_collect_info *c = current->value;
+ int o = argv - rargv[*goptind];
+ return (*c->func)(FALSE, argc, rargv, goptind, &o, c->data);
+ }
+
+ default:
+ abort ();
+ UNREACHABLE(return 0);
+ }
+}
+
+static int
+arg_match_short (struct getargs *args, size_t num_args,
+ char *argv, int argc, char **rargv, int *goptind)
+{
+ size_t j, k;
+
+ for(j = 1; j > 0 && j < strlen(rargv[*goptind]); j++) {
+ for(k = 0; k < num_args; k++) {
+ char *goptarg;
+
+ if(args[k].short_name == 0)
+ continue;
+ if(argv[j] == args[k].short_name) {
+ if(args[k].type == arg_flag) {
+ *(int*)args[k].value = 1;
+ break;
+ }
+ if(args[k].type == arg_negative_flag) {
+ *(int*)args[k].value = 0;
+ break;
+ }
+ if(args[k].type == arg_counter) {
+ ++*(int *)args[k].value;
+ break;
+ }
+ if(args[k].type == arg_collect) {
+ struct getarg_collect_info *c = args[k].value;
+ int a = (int)j;
+
+ if((*c->func)(TRUE, argc, rargv, goptind, &a, c->data))
+ return ARG_ERR_BAD_ARG;
+ j = a;
+ break;
+ }
+
+ if(argv[j + 1])
+ goptarg = &argv[j + 1];
+ else {
+ ++*goptind;
+ goptarg = rargv[*goptind];
+ }
+ if(goptarg == NULL) {
+ --*goptind;
+ return ARG_ERR_NO_ARG;
+ }
+ if(args[k].type == arg_integer) {
+ int tmp;
+ if(sscanf(goptarg, "%d", &tmp) != 1)
+ return ARG_ERR_BAD_ARG;
+ *(int*)args[k].value = tmp;
+ return 0;
+ } else if(args[k].type == arg_string) {
+ *(char**)args[k].value = goptarg;
+ return 0;
+ } else if(args[k].type == arg_strings) {
+ return add_string((getarg_strings*)args[k].value, goptarg);
+ } else if(args[k].type == arg_double) {
+ double tmp;
+ if(sscanf(goptarg, "%lf", &tmp) != 1)
+ return ARG_ERR_BAD_ARG;
+ *(double*)args[k].value = tmp;
+ return 0;
+ }
+ return ARG_ERR_BAD_ARG;
+ }
+ }
+ if (k == num_args)
+ return ARG_ERR_NO_MATCH;
+ }
+ return 0;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+getarg(struct getargs *args, size_t num_args,
+ int argc, char **argv, int *goptind)
+{
+ int i;
+ int ret = 0;
+
+ rk_random_init();
+ (*goptind)++;
+ for(i = *goptind; i < argc; i++) {
+ if(argv[i][0] != '-')
+ break;
+ if(argv[i][1] == '-'){
+ if(argv[i][2] == 0){
+ i++;
+ break;
+ }
+ ret = arg_match_long (args, num_args, argv[i] + 2,
+ argc, argv, &i);
+ } else {
+ ret = arg_match_short (args, num_args, argv[i],
+ argc, argv, &i);
+ }
+ if(ret)
+ break;
+ }
+ *goptind = i;
+ return ret;
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+free_getarg_strings (getarg_strings *s)
+{
+ free (s->strings);
+}
+
+#if TEST
+int foo_flag = 2;
+int flag1 = 0;
+int flag2 = 0;
+int bar_int;
+char *baz_string;
+
+struct getargs args[] = {
+ { NULL, '1', arg_flag, &flag1, "one", NULL },
+ { NULL, '2', arg_flag, &flag2, "two", NULL },
+ { "foo", 'f', arg_negative_flag, &foo_flag, "foo", NULL },
+ { "bar", 'b', arg_integer, &bar_int, "bar", "seconds"},
+ { "baz", 'x', arg_string, &baz_string, "baz", "name" },
+};
+
+int main(int argc, char **argv)
+{
+ int goptind = 0;
+ while (getarg(args, 5, argc, argv, &goptind))
+ printf("Bad arg: %s\n", argv[goptind]);
+ printf("flag1 = %d\n", flag1);
+ printf("flag2 = %d\n", flag2);
+ printf("foo_flag = %d\n", foo_flag);
+ printf("bar_int = %d\n", bar_int);
+ printf("baz_flag = %s\n", baz_string);
+ arg_printusage (args, 5, argv[0], "nothing here");
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/getarg.h b/third_party/heimdal/lib/roken/getarg.h
new file mode 100644
index 0000000..1065c7c
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getarg.h
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __GETARG_H__
+#define __GETARG_H__
+
+#include <stddef.h>
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __cdecl
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+struct getargs{
+ const char *long_name;
+ char short_name;
+ enum { arg_integer,
+ arg_string,
+ arg_flag,
+ arg_negative_flag,
+ arg_strings,
+ arg_double,
+ arg_collect,
+ arg_counter
+ } type;
+ void *value;
+ const char *help;
+ const char *arg_help;
+};
+
+enum {
+ ARG_ERR_NO_MATCH = 1,
+ ARG_ERR_BAD_ARG,
+ ARG_ERR_NO_ARG
+};
+
+typedef struct getarg_strings {
+ int num_strings;
+ char **strings;
+} getarg_strings;
+
+typedef int (*getarg_collect_func)(int short_opt,
+ int argc,
+ char **argv,
+ int *goptind,
+ int *goptarg,
+ void *data);
+
+typedef struct getarg_collect_info {
+ getarg_collect_func func;
+ void *data;
+} getarg_collect_info;
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+getarg(struct getargs *args, size_t num_args,
+ int argc, char **argv, int *goptind);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+arg_printusage (struct getargs *args,
+ size_t num_args,
+ const char *progname,
+ const char *extra_string);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+arg_printusage_i18n (struct getargs *args,
+ size_t num_args,
+ const char *usage,
+ const char *progname,
+ const char *extra_string,
+ char *(*i18n)(const char *));
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+free_getarg_strings (getarg_strings *);
+
+#endif /* __GETARG_H__ */
diff --git a/third_party/heimdal/lib/roken/getauxval.c b/third_party/heimdal/lib/roken/getauxval.c
new file mode 100644
index 0000000..f12bc93
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getauxval.c
@@ -0,0 +1,255 @@
+/*
+ * Copyright (c) 2016 - 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifdef HAVE_SYS_AUXV_H
+#include <sys/auxv.h>
+#endif
+
+#if defined(ENABLE_PTHREAD_SUPPORT) && defined(HAVE_PTHREAD_H)
+#include <pthread.h>
+#endif
+
+#include <errno.h>
+
+#include "roken.h"
+#include "getauxval.h"
+
+int rk_injected_auxv = 0; /* shared with issuid() for testing */
+static int has_proc_auxv = 1;
+static int proc_auxv_ret = 0;
+
+#if defined(ENABLE_PTHREAD_SUPPORT) && defined(HAVE_PTHREAD_H)
+pthread_once_t readprocauxv_once = PTHREAD_ONCE_INIT;
+#endif
+
+/*
+ * There's no standard maximum.
+ *
+ * At the time of this writing we observe some 20 or so auxv entries.
+ * If eventually that grows much larger then rk_getprocaux*() will see a
+ * truncated auxv.
+ */
+#define MAX_AUXV_COUNT 128
+static auxv_t auxv[MAX_AUXV_COUNT];
+
+static void
+do_readprocauxv(void)
+{
+ char *p = (void *)auxv;
+ ssize_t bytes = 0;
+ size_t sz = sizeof(auxv) - sizeof(auxv[0]); /* leave terminator */
+ int save_errno = errno;
+ int fd;
+
+ errno = 0;
+ memset(auxv, 0, sizeof(auxv)); /* terminates our copy */
+ if ((fd = open("/proc/self/auxv", O_RDONLY)) == -1) {
+ if (errno == ENOENT)
+ has_proc_auxv = 0;
+ goto out;
+ }
+
+ do {
+ if ((bytes = read(fd, p, sz)) > 0) {
+ sz -= bytes;
+ p += bytes;
+ }
+ } while (sz && ((bytes == -1 && errno == EINTR) || bytes > 0));
+
+out:
+ proc_auxv_ret = errno;
+ if (fd != -1)
+ (void) close(fd);
+ if (sz == 0 && bytes > 0)
+ warnx("/proc/self/auxv has more entries than expected");
+ errno = save_errno;
+ return;
+}
+
+static int
+readprocauxv(void)
+{
+#if defined(ENABLE_PTHREAD_SUPPORT) && defined(HAVE_PTHREAD_H)
+ pthread_once(&readprocauxv_once, do_readprocauxv);
+#else
+ do_readprocauxv();
+#endif
+ return proc_auxv_ret;
+}
+
+/**
+ * Looks up an auxv entry in /proc/self/auxv. Preserves errno.
+ *
+ * @return a pointer to an auxv_t if found, else NULL.
+ */
+ROKEN_LIB_FUNCTION const auxv_t * ROKEN_LIB_CALL
+rk_getauxv(unsigned long type)
+{
+ auxv_t *a;
+
+ if (!has_proc_auxv || type > INT_MAX)
+ return NULL;
+
+ if (readprocauxv() != 0)
+ return NULL;
+
+ for (a = auxv; a - auxv < MAX_AUXV_COUNT; a++) {
+ if ((int)a->a_type == (int)type)
+ return a;
+ if (a->a_type == 0 && a->a_un.a_val == 0)
+ break;
+ }
+ return NULL;
+}
+
+#ifdef HAVE_GETAUXVAL
+static unsigned long
+rk_getprocauxval(unsigned long type)
+{
+ const auxv_t *a = rk_getauxv(type);
+
+ if (a == NULL) {
+ errno = ENOENT;
+ return 0;
+ }
+ return a->a_un.a_val;
+}
+#endif
+
+/**
+ * Like the nearly-standard getauxval(). If the auxval is not found
+ * returns zero and always sets errno to ENOENT. Otherwise if auxval is
+ * found it leaves errno as it was, even if the value is zero.
+ *
+ * @return The value of the ELF auxiliary value for the given type, or
+ * zero and sets errno to ENOENT.
+ */
+ROKEN_LIB_FUNCTION unsigned long ROKEN_LIB_CALL
+rk_getauxval(unsigned long type)
+{
+ const auxv_t *a;
+#ifdef HAVE_GETAUXVAL
+#ifdef GETAUXVAL_SETS_ERRNO
+ if (rk_injected_auxv)
+ return rk_getprocauxval(type);
+ return getauxval(type);
+#else
+ unsigned long ret;
+ unsigned long ret2;
+ static int getauxval_sets_errno = -1;
+ int save_errno = errno;
+
+ if (rk_injected_auxv)
+ return rk_getprocauxval(type);
+
+ errno = 0;
+ ret = getauxval(type);
+ if (ret != 0 || errno == ENOENT || getauxval_sets_errno == 1) {
+ if (ret != 0)
+ errno = save_errno;
+ else if (getauxval_sets_errno > 0 && errno == 0)
+ errno = save_errno;
+ return ret;
+ }
+
+ if (getauxval_sets_errno == 0) {
+ errno = save_errno;
+ a = rk_getauxv(type);
+ if (a == NULL) {
+ errno = ENOENT;
+ return 0;
+ }
+ return a->a_un.a_val;
+ }
+
+ /*
+ * We've called getauxval() and it returned 0, but we don't know if
+ * getauxval() sets errno = ENOENT when entries are not found.
+ *
+ * Attempt to detect whether getauxval() sets errno = ENOENT by
+ * calling it with what should be a bogus type.
+ */
+
+ errno = 0;
+ ret2 = getauxval(~type);
+ if (ret2 == 0 && errno == ENOENT) {
+ getauxval_sets_errno = 1;
+ errno = save_errno;
+ return ret;
+ }
+
+ getauxval_sets_errno = 0;
+ errno = save_errno;
+#endif
+#endif
+ if ((a = rk_getauxv(type)) == NULL) {
+ errno = ENOENT;
+ return 0;
+ }
+ return a->a_un.a_val;
+}
+
+/**
+ * *Internal* function for testing by injecting or overwriting an ELF
+ * auxiliary vector entry.
+ *
+ * @return zero on success or ENOSPC if there are too many ELF auxiliary
+ * entries.
+ */
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_injectauxv(auxv_t *e)
+{
+ size_t i;
+ int ret;
+
+ /*
+ * This function is racy, but as an internal function never meant to
+ * be called in a threaded program, we don't care.
+ */
+
+ if ((ret = readprocauxv()) != 0)
+ return ret;
+
+ rk_injected_auxv = 1;
+ for (i = 0; i < MAX_AUXV_COUNT - 1 && auxv[i].a_type != 0; i++) {
+ /* e->a_type == 0 -> truncate auxv, delete all entries */
+ if (auxv[i].a_type == e->a_type || e->a_type == 0)
+ break;
+ }
+ if (i == MAX_AUXV_COUNT - 1)
+ return ENOSPC;
+ auxv[i] = e[0];
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/getauxval.h b/third_party/heimdal/lib/roken/getauxval.h
new file mode 100644
index 0000000..3088f0c
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getauxval.h
@@ -0,0 +1,176 @@
+/*
+ * Copyright (c) 2016 - 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef RK_GETAUXVAL_H
+#define RK_GETAUXVAL_H
+
+#include <config.h>
+
+#ifdef HAVE_SYS_AUXV_H
+#include <sys/auxv.h>
+#endif
+
+#ifdef HAVE_SYS_EXEC_ELF_H
+#include <sys/exec_elf.h>
+#endif
+
+#ifndef HAVE_AUXV_T
+/*
+ * Illumos defines auxv_t per the ABI standards, but all other OSes seem
+ * to use { long; long; } instead, depends on sizeof(long) ==
+ * sizeof(void *), and they do not define an auxv_t.
+ *
+ * sizeof(long) != sizeof(void *) on WIN64, but Windows doesn't have
+ * /proc/self/auxv anyways. Just in case we use uintptr_t.
+ */
+typedef struct rk_auxv {
+ uintptr_t a_type;
+ union {
+ uintptr_t a_val;
+ uintptr_t a_ptr; /* This would be void * */
+ uintptr_t a_fnc; /* This would be void (*)(void) */
+ } a_un;
+} auxv_t;
+#endif
+
+#ifdef __linux__
+/*
+ * Older glibcs have no <sys/auxv.h>, but do nonetheless have an ELF
+ * auxiliary vector, and with the values for these types that appear in
+ * <sys/auxv.h> in later versions.
+ *
+ * Note that Travis-CI still uses Ubuntu 14 for its Linux build
+ * environment, which has such an older glibc version.
+ */
+#ifndef AT_UID
+#define AT_UID 11
+#endif
+#ifndef AT_EUID
+#define AT_EUID 12
+#endif
+#ifndef AT_GID
+#define AT_GID 13
+#endif
+#ifndef AT_EGID
+#define AT_EGID 14
+#endif
+#ifndef AT_SECURE
+#define AT_SECURE 23
+#endif
+#endif
+
+#if __sun
+#if !defined(AT_UID) && defined(AT_SUN_RUID)
+#define AT_UID AT_SUN_RUID
+#endif
+#if !defined(AT_EUID) && defined(AT_SUN_UID)
+#define AT_EUID AT_SUN_UID
+#endif
+#if !defined(AT_GID) && defined(AT_SUN_RGID)
+#define AT_GID AT_SUN_RGID
+#endif
+#if !defined(AT_EGID) && defined(AT_SUN_GID)
+#define AT_EGID AT_SUN_GID
+#endif
+#endif /* __sun */
+
+/* NetBSD calls AT_UID AT_RUID. Everyone else calls it AT_UID. */
+#if defined(AT_EUID) && defined(AT_RUID) && !defined(AT_UID)
+#define AT_UID AT_RUID
+#endif
+#if defined(AT_EGID) && defined(AT_RGID) && !defined(AT_GID)
+#define AT_GID AT_RGID
+#endif
+
+#if defined(AT_EUID) && defined(AT_UID) && !defined(AT_RUID)
+#define AT_RUID AT_UID
+#endif
+#if defined(AT_EGID) && defined(AT_GID) && !defined(AT_RGID)
+#define AT_RGID AT_GID
+#endif
+
+
+/*
+ * There are three different names for the type whose value is the path
+ * to the executable being run by the process.
+ */
+#if defined(AT_EXECFN) && !defined(AT_EXECPATH)
+#define AT_EXECPATH AT_EXECFN
+#endif
+#if defined(AT_EXECFN) && !defined(AT_SUN_EXECNAME)
+#define AT_SUN_EXECNAME AT_EXECFN
+#endif
+#if defined(AT_EXECPATH) && !defined(AT_EXECFN)
+#define AT_EXECFN AT_EXECPATH
+#endif
+#if defined(AT_EXECPATH) && !defined(AT_SUN_EXECNAME)
+#define AT_SUN_EXECNAME AT_EXECPATH
+#endif
+#if defined(AT_SUN_EXECNAME) && !defined(AT_EXECFN)
+#define AT_EXECFN AT_SUN_EXECNAME
+#endif
+#if defined(AT_SUN_EXECNAME) && !defined(AT_EXECPATH)
+#define AT_EXECPATH AT_SUN_EXECNAME
+#endif
+
+/* We need this for part of the getauxval() brokenness detection below */
+#ifdef __GLIBC__
+#ifdef __GLIBC_PREREQ
+#define HAVE_GLIBC_API_VERSION_SUPPORT(maj, min) __GLIBC_PREREQ(maj, min)
+#else
+#define HAVE_GLIBC_API_VERSION_SUPPORT(maj, min) \
+ ((__GLIBC << 16) + GLIBC_MINOR >= ((maj) << 16) + (min))
+#endif
+
+/*
+ * Detect whether getauxval() is broken.
+ *
+ * Do change this check in order to manually test rk_getauxval() for
+ * older glibcs.
+ */
+#if HAVE_GLIBC_API_VERSION_SUPPORT(2, 19)
+#define GETAUXVAL_SETS_ERRNO
+/* #else it's broken */
+#endif
+#endif
+
+ROKEN_LIB_FUNCTION const auxv_t * ROKEN_LIB_CALL
+ rk_getauxv(unsigned long type);
+
+ROKEN_LIB_FUNCTION unsigned long ROKEN_LIB_CALL
+ rk_getauxval(unsigned long);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_injectauxv(auxv_t *e);
+
+#endif /* RK_GETAUXVAL_H */
diff --git a/third_party/heimdal/lib/roken/getcwd.c b/third_party/heimdal/lib/roken/getcwd.c
new file mode 100644
index 0000000..f8917b2
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getcwd.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION char* ROKEN_LIB_CALL
+getcwd(char *path, size_t size)
+{
+ char xxx[MaxPathLen];
+ char *ret;
+ ret = getwd(xxx);
+ if(ret)
+ strlcpy(path, xxx, size);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/getdtablesize.c b/third_party/heimdal/lib/roken/getdtablesize.c
new file mode 100644
index 0000000..08c0661
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getdtablesize.c
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 1995-2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef TIME_WITH_SYS_TIME
+#include <sys/time.h>
+#include <time.h>
+#elif defined(HAVE_SYS_TIME_H)
+#include <sys/time.h>
+#else
+#include <time.h>
+#endif
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#ifdef HAVE_SYS_RESOURCE_H
+#include <sys/resource.h>
+#endif
+
+#ifdef HAVE_SYS_SYSCTL_H
+#include <sys/sysctl.h>
+#endif
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+getdtablesize(void)
+{
+ int files = -1;
+#if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
+ files = sysconf(_SC_OPEN_MAX);
+#else /* !defined(HAVE_SYSCONF) */
+#if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
+ struct rlimit res;
+ if (getrlimit(RLIMIT_NOFILE, &res) == 0)
+ files = res.rlim_cur;
+#else /* !definded(HAVE_GETRLIMIT) */
+#if defined(HAVE_SYSCTL) && defined(CTL_KERN) && defined(KERN_MAXFILES)
+ int mib[2];
+ size_t len;
+
+ mib[0] = CTL_KERN;
+ mib[1] = KERN_MAXFILES;
+ len = sizeof(files);
+ sysctl(&mib, 2, &files, sizeof(files), NULL, 0);
+#endif /* defined(HAVE_SYSCTL) */
+#endif /* !definded(HAVE_GETRLIMIT) */
+#endif /* !defined(HAVE_SYSCONF) */
+
+#ifdef OPEN_MAX
+ if (files < 0)
+ files = OPEN_MAX;
+#endif
+
+#ifdef NOFILE
+ if (files < 0)
+ files = NOFILE;
+#endif
+
+ return files;
+}
diff --git a/third_party/heimdal/lib/roken/getegid.c b/third_party/heimdal/lib/roken/getegid.c
new file mode 100644
index 0000000..663fb1d
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getegid.c
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+#ifndef HAVE_GETEGID
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+getegid(void)
+{
+ return getgid();
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/geteuid.c b/third_party/heimdal/lib/roken/geteuid.c
new file mode 100644
index 0000000..598a739
--- /dev/null
+++ b/third_party/heimdal/lib/roken/geteuid.c
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+#ifndef HAVE_GETEUID
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+geteuid(void)
+{
+ return getuid();
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/getgid.c b/third_party/heimdal/lib/roken/getgid.c
new file mode 100644
index 0000000..b24ceeb
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getgid.c
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include "roken.h"
+
+#ifndef HAVE_GETGID
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+getgid(void)
+{
+ return 17;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/gethostname.c b/third_party/heimdal/lib/roken/gethostname.c
new file mode 100644
index 0000000..8389091
--- /dev/null
+++ b/third_party/heimdal/lib/roken/gethostname.c
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include "roken.h"
+
+#ifndef HAVE_GETHOSTNAME
+
+#ifdef HAVE_SYS_UTSNAME_H
+#include <sys/utsname.h>
+#endif
+
+/*
+ * Return the local host's name in "name", up to "namelen" characters.
+ * "name" will be null-terminated if "namelen" is big enough.
+ * The return code is 0 on success, -1 on failure. (The calling
+ * interface is identical to gethostname(2).)
+ */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+gethostname(char *name, int namelen)
+{
+#if defined(HAVE_UNAME)
+ {
+ struct utsname utsname;
+ int ret;
+
+ ret = uname (&utsname);
+ if (ret < 0)
+ return ret;
+ strlcpy (name, utsname.nodename, namelen);
+ return 0;
+ }
+#else
+ strlcpy (name, "some.random.host", namelen);
+ return 0;
+#endif
+}
+
+#endif /* GETHOSTNAME */
diff --git a/third_party/heimdal/lib/roken/getifaddrs-test.c b/third_party/heimdal/lib/roken/getifaddrs-test.c
new file mode 100644
index 0000000..252763d
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getifaddrs-test.c
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2009 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Portions Copyright (c) 2009, Secure Endpoints Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <err.h>
+#include "getarg.h"
+
+#include "roken.h"
+
+#include <ifaddrs.h>
+
+static int verbose_counter;
+static int version_flag;
+static int help_flag;
+
+static struct getargs args[] = {
+ {"verbose", 0, arg_counter, &verbose_counter,"verbose", NULL},
+ {"version", 0, arg_flag, &version_flag, "print version",NULL},
+ {"help", 0, arg_flag, &help_flag, NULL, NULL}
+};
+
+static void
+usage(int ret)
+{
+ arg_printusage (args,
+ sizeof(args) / sizeof(args[0]),
+ NULL, "");
+ exit (ret);
+}
+
+
+static void
+print_addr(const char *s, struct sockaddr *sa)
+{
+ int i;
+ printf(" %s=%d/", s, sa->sa_family);
+#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
+ for(i = 0; i < sa->sa_len - ((long)sa->sa_data - (long)&sa->sa_family); i++)
+ printf("%02x", ((unsigned char*)sa->sa_data)[i]);
+#else
+ for(i = 0; i < sizeof(sa->sa_data); i++)
+ printf("%02x", ((unsigned char*)sa->sa_data)[i]);
+#endif
+ printf("\n");
+}
+
+static void
+print_ifaddrs(struct ifaddrs *x)
+{
+ struct ifaddrs *p;
+
+ for(p = x; p; p = p->ifa_next) {
+ if (verbose_counter) {
+ printf("%s\n", p->ifa_name);
+ printf(" flags=%x\n", p->ifa_flags);
+ if(p->ifa_addr)
+ print_addr("addr", p->ifa_addr);
+ if(p->ifa_dstaddr)
+ print_addr("dstaddr", p->ifa_dstaddr);
+ if(p->ifa_netmask)
+ print_addr("netmask", p->ifa_netmask);
+ printf(" %p\n", p->ifa_data);
+ }
+ }
+}
+
+int
+main(int argc, char **argv)
+{
+ struct ifaddrs *addrs = NULL;
+ int ret, optidx = 0;
+
+ setprogname (argv[0]);
+
+ if (getarg (args, sizeof(args) / sizeof(args[0]), argc, argv,
+ &optidx))
+ usage (1);
+
+ if (help_flag)
+ usage (0);
+
+ if (version_flag) {
+ fprintf (stderr, "%s from %s-%s\n", getprogname(), PACKAGE, VERSION);
+ return 0;
+ }
+
+ if (rk_SOCK_INIT())
+ errx(1, "Failed to initialize sockets (%s)", strerror(rk_SOCK_ERRNO));
+
+ ret = getifaddrs(&addrs);
+ if (ret != 0)
+ err(1, "getifaddrs");
+
+ if (addrs == NULL)
+ errx(1, "address == NULL");
+
+ print_ifaddrs(addrs);
+
+ /* Check that freeifaddrs doesn't crash */
+ freeifaddrs(addrs);
+
+ rk_SOCK_EXIT();
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/getifaddrs.c b/third_party/heimdal/lib/roken/getifaddrs.c
new file mode 100644
index 0000000..72eb5aa
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getifaddrs.c
@@ -0,0 +1,1309 @@
+/*
+ * Copyright (c) 2000 - 2002, 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include "roken.h"
+
+#ifdef __osf__
+/* hate */
+struct rtentry;
+struct mbuf;
+#endif
+#ifdef HAVE_NET_IF_H
+#include <net/if.h>
+#endif
+
+#ifdef HAVE_SYS_SOCKIO_H
+#include <sys/sockio.h>
+#endif /* HAVE_SYS_SOCKIO_H */
+
+#ifdef HAVE_NETINET_IN6_VAR_H
+#include <netinet/in6_var.h>
+#endif /* HAVE_NETINET_IN6_VAR_H */
+
+#include <ifaddrs.h>
+
+#ifdef __hpux
+#define lifconf if_laddrconf
+#define lifc_len iflc_len
+#define lifc_buf iflc_buf
+#define lifc_req iflc_req
+
+#define lifreq if_laddrreq
+#define lifr_addr iflr_addr
+#define lifr_name iflr_name
+#define lifr_dstaddr iflr_dstaddr
+#define lifr_broadaddr iflr_broadaddr
+#define lifr_flags iflr_flags
+#define lifr_index iflr_index
+#endif
+
+#ifdef AF_NETLINK
+
+/*
+ * The linux - AF_NETLINK version of getifaddrs - from Usagi.
+ * Linux does not return v6 addresses from SIOCGIFCONF.
+ */
+
+/* $USAGI: ifaddrs.c,v 1.18 2002/03/06 01:50:46 yoshfuji Exp $ */
+
+/**************************************************************************
+ * ifaddrs.c
+ * Copyright (C)2000 Hideaki YOSHIFUJI, All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the author nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include <string.h>
+#include <time.h>
+#include <malloc.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include <sys/socket.h>
+#include <asm/types.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/poll.h>
+#include <netpacket/packet.h>
+#include <net/ethernet.h> /* the L2 protocols */
+#include <sys/uio.h>
+#include <net/if.h>
+#include <net/if_arp.h>
+#include <ifaddrs.h>
+#include <netinet/in.h>
+
+#define __set_errno(e) (errno = (e))
+#define __close(fd) (close(fd))
+#undef ifa_broadaddr
+#define ifa_broadaddr ifa_dstaddr
+#define IFA_NETMASK
+
+/* ====================================================================== */
+struct nlmsg_list{
+ struct nlmsg_list *nlm_next;
+ struct nlmsghdr *nlh;
+ int size;
+ time_t seq;
+};
+
+struct rtmaddr_ifamap {
+ void *address;
+ void *local;
+#ifdef IFA_NETMASK
+ void *netmask;
+#endif
+ void *broadcast;
+#ifdef HAVE_IFADDRS_IFA_ANYCAST
+ void *anycast;
+#endif
+ int address_len;
+ int local_len;
+#ifdef IFA_NETMASK
+ int netmask_len;
+#endif
+ int broadcast_len;
+#ifdef HAVE_IFADDRS_IFA_ANYCAST
+ int anycast_len;
+#endif
+};
+
+/* ====================================================================== */
+static size_t
+ifa_sa_len(sa_family_t family, int len)
+{
+ size_t size;
+ switch(family){
+ case AF_INET:
+ size = sizeof(struct sockaddr_in);
+ break;
+ case AF_INET6:
+ size = sizeof(struct sockaddr_in6);
+ break;
+ case AF_PACKET:
+ size = (size_t)(((struct sockaddr_ll *)NULL)->sll_addr) + len;
+ if (size < sizeof(struct sockaddr_ll))
+ size = sizeof(struct sockaddr_ll);
+ break;
+ default:
+ size = (size_t)(((struct sockaddr *)NULL)->sa_data) + len;
+ if (size < sizeof(struct sockaddr))
+ size = sizeof(struct sockaddr);
+ break;
+ }
+ return size;
+}
+
+static void
+ifa_make_sockaddr(sa_family_t family,
+ struct sockaddr *sa,
+ void *p, size_t len,
+ uint32_t scope, uint32_t scopeid)
+{
+ if (sa == NULL) return;
+ switch(family){
+ case AF_INET:
+ memcpy(&((struct sockaddr_in*)sa)->sin_addr, (char *)p, len);
+ break;
+ case AF_INET6:
+ memcpy(&((struct sockaddr_in6*)sa)->sin6_addr, (char *)p, len);
+ if (IN6_IS_ADDR_LINKLOCAL(p) ||
+ IN6_IS_ADDR_MC_LINKLOCAL(p)){
+ ((struct sockaddr_in6*)sa)->sin6_scope_id = scopeid;
+ }
+ break;
+ case AF_PACKET:
+ memcpy(((struct sockaddr_ll*)sa)->sll_addr, (char *)p, len);
+ ((struct sockaddr_ll*)sa)->sll_halen = len;
+ break;
+ default:
+ memcpy(sa->sa_data, p, len); /*XXX*/
+ break;
+ }
+ sa->sa_family = family;
+#ifdef HAVE_SOCKADDR_SA_LEN
+ sa->sa_len = ifa_sa_len(family, len);
+#endif
+}
+
+#ifndef IFA_NETMASK
+static struct sockaddr *
+ifa_make_sockaddr_mask(sa_family_t family,
+ struct sockaddr *sa,
+ uint32_t prefixlen)
+{
+ int i;
+ char *p = NULL, c;
+ uint32_t max_prefixlen = 0;
+
+ if (sa == NULL) return NULL;
+ switch(family){
+ case AF_INET:
+ memset(&((struct sockaddr_in*)sa)->sin_addr, 0, sizeof(((struct sockaddr_in*)sa)->sin_addr));
+ p = (char *)&((struct sockaddr_in*)sa)->sin_addr;
+ max_prefixlen = 32;
+ break;
+ case AF_INET6:
+ memset(&((struct sockaddr_in6*)sa)->sin6_addr, 0, sizeof(((struct sockaddr_in6*)sa)->sin6_addr));
+ p = (char *)&((struct sockaddr_in6*)sa)->sin6_addr;
+#if 0 /* XXX: fill scope-id? */
+ if (IN6_IS_ADDR_LINKLOCAL(p) ||
+ IN6_IS_ADDR_MC_LINKLOCAL(p)){
+ ((struct sockaddr_in6*)sa)->sin6_scope_id = scopeid;
+ }
+#endif
+ max_prefixlen = 128;
+ break;
+ default:
+ return NULL;
+ }
+ sa->sa_family = family;
+#ifdef HAVE_SOCKADDR_SA_LEN
+ sa->sa_len = ifa_sa_len(family, len);
+#endif
+ if (p){
+ if (prefixlen > max_prefixlen)
+ prefixlen = max_prefixlen;
+ for (i=0; i<(prefixlen / 8); i++)
+ *p++ = 0xff;
+ c = 0xff;
+ c <<= (8 - (prefixlen % 8));
+ *p = c;
+ }
+ return sa;
+}
+#endif
+
+/* ====================================================================== */
+static int
+nl_sendreq(int sd, int request, int flags, int *seq)
+{
+ char reqbuf[NLMSG_ALIGN(sizeof(struct nlmsghdr)) +
+ NLMSG_ALIGN(sizeof(struct rtgenmsg))];
+ struct sockaddr_nl nladdr;
+ struct nlmsghdr *req_hdr;
+ struct rtgenmsg *req_msg;
+ time_t t = time(NULL);
+
+ if (seq) *seq = t;
+ memset(&reqbuf, 0, sizeof(reqbuf));
+ req_hdr = (struct nlmsghdr *)reqbuf;
+ req_msg = (struct rtgenmsg *)NLMSG_DATA(req_hdr);
+ req_hdr->nlmsg_len = NLMSG_LENGTH(sizeof(*req_msg));
+ req_hdr->nlmsg_type = request;
+ req_hdr->nlmsg_flags = flags | NLM_F_REQUEST;
+ req_hdr->nlmsg_pid = 0;
+ req_hdr->nlmsg_seq = t;
+ req_msg->rtgen_family = AF_UNSPEC;
+ memset(&nladdr, 0, sizeof(nladdr));
+ nladdr.nl_family = AF_NETLINK;
+ return (sendto(sd, (void *)req_hdr, req_hdr->nlmsg_len, 0,
+ (struct sockaddr *)&nladdr, sizeof(nladdr)));
+}
+
+static int
+nl_recvmsg(int sd, int request, int seq,
+ void *buf, size_t buflen,
+ int *flags)
+{
+ struct msghdr msg;
+ struct iovec iov = { buf, buflen };
+ struct sockaddr_nl nladdr;
+ int read_len;
+
+ for (;;){
+ msg.msg_name = (void *)&nladdr;
+ msg.msg_namelen = sizeof(nladdr);
+ msg.msg_iov = &iov;
+ msg.msg_iovlen = 1;
+ msg.msg_control = NULL;
+ msg.msg_controllen = 0;
+ msg.msg_flags = 0;
+ read_len = recvmsg(sd, &msg, 0);
+ if ((read_len < 0 && errno == EINTR) || (msg.msg_flags & MSG_TRUNC))
+ continue;
+ if (flags) *flags = msg.msg_flags;
+ break;
+ }
+ return read_len;
+}
+
+static int
+nl_getmsg(int sd, int request, int seq,
+ struct nlmsghdr **nlhp,
+ int *done)
+{
+ struct nlmsghdr *nh;
+ size_t bufsize = 65536, lastbufsize = 0;
+ void *buff = NULL;
+ int result = 0, read_size;
+ int msg_flags;
+ pid_t pid = getpid();
+ for (;;){
+ void *newbuff = realloc(buff, bufsize);
+ if (newbuff == NULL || bufsize < lastbufsize) {
+ result = -1;
+ break;
+ }
+ buff = newbuff;
+ result = read_size = nl_recvmsg(sd, request, seq, buff, bufsize, &msg_flags);
+ if (read_size < 0 || (msg_flags & MSG_TRUNC)){
+ lastbufsize = bufsize;
+ bufsize *= 2;
+ continue;
+ }
+ if (read_size == 0) break;
+ nh = (struct nlmsghdr *)buff;
+ for (nh = (struct nlmsghdr *)buff;
+ NLMSG_OK(nh, read_size);
+ nh = (struct nlmsghdr *)NLMSG_NEXT(nh, read_size)){
+ if (nh->nlmsg_pid != pid ||
+ nh->nlmsg_seq != seq)
+ continue;
+ if (nh->nlmsg_type == NLMSG_DONE){
+ (*done)++;
+ break; /* ok */
+ }
+ if (nh->nlmsg_type == NLMSG_ERROR){
+ struct nlmsgerr *nlerr = (struct nlmsgerr *)NLMSG_DATA(nh);
+ result = -1;
+ if (nh->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr)))
+ __set_errno(EIO);
+ else
+ __set_errno(-nlerr->error);
+ break;
+ }
+ }
+ break;
+ }
+ if (result < 0)
+ if (buff){
+ int saved_errno = errno;
+ free(buff);
+ __set_errno(saved_errno);
+ }
+ *nlhp = (struct nlmsghdr *)buff;
+ return result;
+}
+
+static int
+nl_getlist(int sd, int seq,
+ int request,
+ struct nlmsg_list **nlm_list,
+ struct nlmsg_list **nlm_end)
+{
+ struct nlmsghdr *nlh = NULL;
+ int status;
+ int done = 0;
+ int tries = 3;
+
+ try_again:
+ status = nl_sendreq(sd, request, NLM_F_ROOT|NLM_F_MATCH, &seq);
+ if (status < 0)
+ return status;
+ if (seq == 0)
+ seq = (int)time(NULL);
+ while(!done){
+ struct pollfd pfd;
+
+ pfd.fd = sd;
+ pfd.events = POLLIN | POLLPRI;
+ pfd.revents = 0;
+ status = poll(&pfd, 1, 1000);
+ if (status < 0)
+ return status;
+ else if (status == 0) {
+ seq++;
+ if (tries-- > 0)
+ goto try_again;
+ return -1;
+ }
+
+ status = nl_getmsg(sd, request, seq, &nlh, &done);
+ if (status < 0)
+ return status;
+ if (nlh){
+ struct nlmsg_list *nlm_next = (struct nlmsg_list *)malloc(sizeof(struct nlmsg_list));
+ if (nlm_next == NULL){
+ int saved_errno = errno;
+ free(nlh);
+ __set_errno(saved_errno);
+ status = -1;
+ } else {
+ nlm_next->nlm_next = NULL;
+ nlm_next->nlh = (struct nlmsghdr *)nlh;
+ nlm_next->size = status;
+ nlm_next->seq = seq;
+ if (*nlm_list == NULL){
+ *nlm_list = nlm_next;
+ *nlm_end = nlm_next;
+ } else {
+ (*nlm_end)->nlm_next = nlm_next;
+ *nlm_end = nlm_next;
+ }
+ }
+ }
+ }
+ return status >= 0 ? seq : status;
+}
+
+/* ---------------------------------------------------------------------- */
+static void
+free_nlmsglist(struct nlmsg_list *nlm0)
+{
+ struct nlmsg_list *nlm, *nlm_next;
+ int saved_errno;
+ if (!nlm0)
+ return;
+ saved_errno = errno;
+ for (nlm=nlm0; nlm; nlm=nlm_next){
+ if (nlm->nlh)
+ free(nlm->nlh);
+ nlm_next=nlm->nlm_next;
+ free(nlm);
+ }
+ __set_errno(saved_errno);
+}
+
+static void
+free_data(void *data, void *ifdata)
+{
+ int saved_errno = errno;
+ if (data != NULL) free(data);
+ if (ifdata != NULL) free(ifdata);
+ __set_errno(saved_errno);
+}
+
+/* ---------------------------------------------------------------------- */
+static void
+nl_close(int sd)
+{
+ int saved_errno = errno;
+ if (sd >= 0) __close(sd);
+ __set_errno(saved_errno);
+}
+
+/* ---------------------------------------------------------------------- */
+static int
+nl_open(void)
+{
+ struct sockaddr_nl nladdr;
+ int sd;
+
+ sd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
+ if (sd < 0) return -1;
+ memset(&nladdr, 0, sizeof(nladdr));
+ nladdr.nl_family = AF_NETLINK;
+ if (bind(sd, (struct sockaddr*)&nladdr, sizeof(nladdr)) < 0){
+ nl_close(sd);
+ return -1;
+ }
+ return sd;
+}
+
+/* ====================================================================== */
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_getifaddrs(struct ifaddrs **ifap)
+{
+ int sd;
+ struct nlmsg_list *nlmsg_list, *nlmsg_end, *nlm;
+ /* - - - - - - - - - - - - - - - */
+ int icnt;
+ size_t dlen, xlen, nlen;
+ uint32_t max_ifindex = 0;
+
+ pid_t pid = getpid();
+ int seq;
+ int result;
+ int build ; /* 0 or 1 */
+
+/* ---------------------------------- */
+ /* initialize */
+ icnt = dlen = xlen = nlen = 0;
+ nlmsg_list = nlmsg_end = NULL;
+
+ if (ifap)
+ *ifap = NULL;
+
+/* ---------------------------------- */
+ /* open socket and bind */
+ sd = nl_open();
+ if (sd < 0)
+ return -1;
+
+/* ---------------------------------- */
+ /* gather info */
+ if ((seq = nl_getlist(sd, 0, RTM_GETLINK,
+ &nlmsg_list, &nlmsg_end)) < 0){
+ free_nlmsglist(nlmsg_list);
+ nl_close(sd);
+ return -1;
+ }
+ if ((seq = nl_getlist(sd, seq+1, RTM_GETADDR,
+ &nlmsg_list, &nlmsg_end)) < 0){
+ free_nlmsglist(nlmsg_list);
+ nl_close(sd);
+ return -1;
+ }
+
+/* ---------------------------------- */
+ /* Estimate size of result buffer and fill it */
+ for (build=0; build<=1; build++){
+ struct ifaddrs *ifl = NULL, *ifa = NULL;
+ struct nlmsghdr *nlh, *nlh0;
+ char *data = NULL, *xdata = NULL;
+ void *ifdata = NULL;
+ char *ifname = NULL, **iflist = NULL;
+ uint16_t *ifflist = NULL;
+ struct rtmaddr_ifamap ifamap;
+
+ if (build){
+ data = calloc(1,
+ NLMSG_ALIGN(sizeof(struct ifaddrs[icnt]))
+ + dlen + xlen + nlen);
+ ifa = (struct ifaddrs *)data;
+ ifdata = calloc(1,
+ NLMSG_ALIGN(sizeof(char *[max_ifindex+1]))
+ + NLMSG_ALIGN(sizeof(uint16_t [max_ifindex+1])));
+ if (ifap != NULL)
+ *ifap = (ifdata != NULL) ? ifa : NULL;
+ else{
+ free_data(data, ifdata);
+ result = 0;
+ break;
+ }
+ if (data == NULL || ifdata == NULL){
+ free_data(data, ifdata);
+ result = -1;
+ break;
+ }
+ ifl = NULL;
+ data += NLMSG_ALIGN(sizeof(struct ifaddrs)) * icnt;
+ xdata = data + dlen;
+ ifname = xdata + xlen;
+ iflist = ifdata;
+ ifflist = (uint16_t *)(((char *)iflist) + NLMSG_ALIGN(sizeof(char *[max_ifindex+1])));
+ }
+
+ for (nlm=nlmsg_list; nlm; nlm=nlm->nlm_next){
+ int nlmlen = nlm->size;
+ if (!(nlh0 = nlm->nlh))
+ continue;
+ for (nlh = nlh0;
+ NLMSG_OK(nlh, nlmlen);
+ nlh=NLMSG_NEXT(nlh,nlmlen)){
+ struct ifinfomsg *ifim = NULL;
+ struct ifaddrmsg *ifam = NULL;
+ struct rtattr *rta;
+
+ size_t nlm_struct_size = 0;
+ sa_family_t nlm_family = 0;
+ uint32_t nlm_scope = 0, nlm_index = 0;
+ size_t sockaddr_size = 0;
+ uint32_t nlm_prefixlen = 0;
+ size_t rtasize;
+
+ memset(&ifamap, 0, sizeof(ifamap));
+
+ /* check if the message is what we want */
+ if (nlh->nlmsg_pid != pid ||
+ nlh->nlmsg_seq != nlm->seq)
+ continue;
+ if (nlh->nlmsg_type == NLMSG_DONE){
+ break; /* ok */
+ }
+ switch (nlh->nlmsg_type){
+ case RTM_NEWLINK:
+ ifim = (struct ifinfomsg *)NLMSG_DATA(nlh);
+ nlm_struct_size = sizeof(*ifim);
+ nlm_family = ifim->ifi_family;
+ nlm_scope = 0;
+ nlm_index = ifim->ifi_index;
+ nlm_prefixlen = 0;
+ if (build)
+ ifflist[nlm_index] = ifa->ifa_flags = ifim->ifi_flags;
+ break;
+ case RTM_NEWADDR:
+ ifam = (struct ifaddrmsg *)NLMSG_DATA(nlh);
+ nlm_struct_size = sizeof(*ifam);
+ nlm_family = ifam->ifa_family;
+ nlm_scope = ifam->ifa_scope;
+ nlm_index = ifam->ifa_index;
+ nlm_prefixlen = ifam->ifa_prefixlen;
+ if (build)
+ ifa->ifa_flags = ifflist[nlm_index];
+ break;
+ default:
+ continue;
+ }
+
+ if (!build){
+ if (max_ifindex < nlm_index)
+ max_ifindex = nlm_index;
+ } else {
+ if (ifl != NULL)
+ ifl->ifa_next = ifa;
+ }
+
+ rtasize = NLMSG_PAYLOAD(nlh, nlmlen) - NLMSG_ALIGN(nlm_struct_size);
+ for (rta = (struct rtattr *)(((char *)NLMSG_DATA(nlh)) + NLMSG_ALIGN(nlm_struct_size));
+ RTA_OK(rta, rtasize);
+ rta = RTA_NEXT(rta, rtasize)){
+ struct sockaddr **sap = NULL;
+ void *rtadata = RTA_DATA(rta);
+ size_t rtapayload = RTA_PAYLOAD(rta);
+ socklen_t sa_len;
+
+ switch(nlh->nlmsg_type){
+ case RTM_NEWLINK:
+ switch(rta->rta_type){
+ case IFLA_ADDRESS:
+ case IFLA_BROADCAST:
+ if (build){
+ sap = (rta->rta_type == IFLA_ADDRESS) ? &ifa->ifa_addr : &ifa->ifa_broadaddr;
+ *sap = (struct sockaddr *)data;
+ }
+ sa_len = ifa_sa_len(AF_PACKET, rtapayload);
+ if (rta->rta_type == IFLA_ADDRESS)
+ sockaddr_size = NLMSG_ALIGN(sa_len);
+ if (!build){
+ dlen += NLMSG_ALIGN(sa_len);
+ } else {
+ memset(*sap, 0, sa_len);
+ ifa_make_sockaddr(AF_PACKET, *sap, rtadata,rtapayload, 0,0);
+ ((struct sockaddr_ll *)*sap)->sll_ifindex = nlm_index;
+ ((struct sockaddr_ll *)*sap)->sll_hatype = ifim->ifi_type;
+ data += NLMSG_ALIGN(sa_len);
+ }
+ break;
+ case IFLA_IFNAME:/* Name of Interface */
+ if (!build)
+ nlen += NLMSG_ALIGN(rtapayload + 1);
+ else{
+ ifa->ifa_name = ifname;
+ if (iflist[nlm_index] == NULL)
+ iflist[nlm_index] = ifa->ifa_name;
+ strncpy(ifa->ifa_name, rtadata, rtapayload);
+ ifa->ifa_name[rtapayload] = '\0';
+ ifname += NLMSG_ALIGN(rtapayload + 1);
+ }
+ break;
+ case IFLA_STATS:/* Statistics of Interface */
+ if (!build)
+ xlen += NLMSG_ALIGN(rtapayload);
+ else{
+ ifa->ifa_data = xdata;
+ memcpy(ifa->ifa_data, rtadata, rtapayload);
+ xdata += NLMSG_ALIGN(rtapayload);
+ }
+ break;
+ case IFLA_UNSPEC:
+ break;
+ case IFLA_MTU:
+ break;
+ case IFLA_LINK:
+ break;
+ case IFLA_QDISC:
+ break;
+ default:
+ break;
+ }
+ break;
+ case RTM_NEWADDR:
+ if (nlm_family == AF_PACKET) break;
+ switch(rta->rta_type){
+ case IFA_ADDRESS:
+ ifamap.address = rtadata;
+ ifamap.address_len = rtapayload;
+ break;
+ case IFA_LOCAL:
+ ifamap.local = rtadata;
+ ifamap.local_len = rtapayload;
+ break;
+ case IFA_BROADCAST:
+ ifamap.broadcast = rtadata;
+ ifamap.broadcast_len = rtapayload;
+ break;
+#ifdef HAVE_IFADDRS_IFA_ANYCAST
+ case IFA_ANYCAST:
+ ifamap.anycast = rtadata;
+ ifamap.anycast_len = rtapayload;
+ break;
+#endif
+ case IFA_LABEL:
+ if (!build)
+ nlen += NLMSG_ALIGN(rtapayload + 1);
+ else{
+ ifa->ifa_name = ifname;
+ if (iflist[nlm_index] == NULL)
+ iflist[nlm_index] = ifname;
+ strncpy(ifa->ifa_name, rtadata, rtapayload);
+ ifa->ifa_name[rtapayload] = '\0';
+ ifname += NLMSG_ALIGN(rtapayload + 1);
+ }
+ break;
+ case IFA_UNSPEC:
+ break;
+ case IFA_CACHEINFO:
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ if (nlh->nlmsg_type == RTM_NEWADDR &&
+ nlm_family != AF_PACKET) {
+ if (!ifamap.local) {
+ ifamap.local = ifamap.address;
+ ifamap.local_len = ifamap.address_len;
+ }
+ if (!ifamap.address) {
+ ifamap.address = ifamap.local;
+ ifamap.address_len = ifamap.local_len;
+ }
+ if (ifamap.address_len != ifamap.local_len ||
+ (ifamap.address != NULL &&
+ memcmp(ifamap.address, ifamap.local, ifamap.address_len) != 0)) {
+ /* p2p; address is peer and local is ours */
+ ifamap.broadcast = ifamap.address;
+ ifamap.broadcast_len = ifamap.address_len;
+ ifamap.address = ifamap.local;
+ ifamap.address_len = ifamap.local_len;
+ }
+ if (ifamap.address) {
+#ifndef IFA_NETMASK
+ sockaddr_size = NLMSG_ALIGN(ifa_sa_len(nlm_family,ifamap.address_len));
+#endif
+ if (!build)
+ dlen += NLMSG_ALIGN(ifa_sa_len(nlm_family,ifamap.address_len));
+ else {
+ ifa->ifa_addr = (struct sockaddr *)data;
+ ifa_make_sockaddr(nlm_family, ifa->ifa_addr, ifamap.address, ifamap.address_len,
+ nlm_scope, nlm_index);
+ data += NLMSG_ALIGN(ifa_sa_len(nlm_family, ifamap.address_len));
+ }
+ }
+#ifdef IFA_NETMASK
+ if (ifamap.netmask) {
+ if (!build)
+ dlen += NLMSG_ALIGN(ifa_sa_len(nlm_family,ifamap.netmask_len));
+ else {
+ ifa->ifa_netmask = (struct sockaddr *)data;
+ ifa_make_sockaddr(nlm_family, ifa->ifa_netmask, ifamap.netmask, ifamap.netmask_len,
+ nlm_scope, nlm_index);
+ data += NLMSG_ALIGN(ifa_sa_len(nlm_family, ifamap.netmask_len));
+ }
+ }
+#endif
+ if (ifamap.broadcast) {
+ if (!build)
+ dlen += NLMSG_ALIGN(ifa_sa_len(nlm_family,ifamap.broadcast_len));
+ else {
+ ifa->ifa_broadaddr = (struct sockaddr *)data;
+ ifa_make_sockaddr(nlm_family, ifa->ifa_broadaddr, ifamap.broadcast, ifamap.broadcast_len,
+ nlm_scope, nlm_index);
+ data += NLMSG_ALIGN(ifa_sa_len(nlm_family, ifamap.broadcast_len));
+ }
+ }
+#ifdef HAVE_IFADDRS_IFA_ANYCAST
+ if (ifamap.anycast) {
+ if (!build)
+ dlen += NLMSG_ALIGN(ifa_sa_len(nlm_family,ifamap.anycast_len));
+ else {
+ ifa->ifa_anycast = (struct sockaddr *)data;
+ ifa_make_sockaddr(nlm_family, ifa->ifa_anyaddr, ifamap.anycast, ifamap.anycast_len,
+ nlm_scope, nlm_index);
+ data += NLMSG_ALIGN(ifa_sa_len(nlm_family, ifamap.anycast_len));
+ }
+ }
+#endif
+ }
+ if (!build){
+#ifndef IFA_NETMASK
+ dlen += sockaddr_size;
+#endif
+ icnt++;
+ } else {
+ if (ifa->ifa_name == NULL)
+ ifa->ifa_name = iflist[nlm_index];
+#ifndef IFA_NETMASK
+ if (ifa->ifa_addr &&
+ ifa->ifa_addr->sa_family != AF_UNSPEC &&
+ ifa->ifa_addr->sa_family != AF_PACKET){
+ ifa->ifa_netmask = (struct sockaddr *)data;
+ ifa_make_sockaddr_mask(ifa->ifa_addr->sa_family, ifa->ifa_netmask, nlm_prefixlen);
+ }
+ data += sockaddr_size;
+#endif
+ ifl = ifa++;
+ }
+ }
+ }
+ if (!build){
+ if (icnt == 0 && (dlen + nlen + xlen == 0)){
+ if (ifap != NULL)
+ *ifap = NULL;
+ break; /* cannot found any addresses */
+ }
+ }
+ else
+ free_data(NULL, ifdata);
+ }
+
+/* ---------------------------------- */
+ /* Finalize */
+ free_nlmsglist(nlmsg_list);
+ nl_close(sd);
+ return 0;
+}
+
+void ROKEN_LIB_FUNCTION
+rk_freeifaddrs(struct ifaddrs *ifp)
+{
+ /* AF_NETLINK method uses a single allocation for all interfaces */
+ free(ifp);
+}
+
+#else /* !AF_NETLINK */
+
+/*
+ * The generic SIOCGIFCONF version.
+ */
+
+static int
+getifaddrs2(struct ifaddrs **ifap,
+ int af, int siocgifconf, int siocgifflags,
+ size_t ifreq_sz)
+{
+ int ret;
+ int fd;
+ size_t buf_size;
+ char *buf;
+ struct ifconf ifconf;
+ char *p;
+ size_t sz;
+ struct sockaddr sa_zero;
+ struct ifreq *ifr;
+ struct ifaddrs *start = NULL, **end = &start;
+
+ buf = NULL;
+
+ memset (&sa_zero, 0, sizeof(sa_zero));
+ fd = socket(af, SOCK_DGRAM, 0);
+ if (fd < 0)
+ return -1;
+
+ buf_size = 8192;
+ for (;;) {
+ buf = calloc(1, buf_size);
+ if (buf == NULL) {
+ ret = ENOMEM;
+ goto error_out;
+ }
+ ifconf.ifc_len = buf_size;
+ ifconf.ifc_buf = buf;
+
+ /*
+ * Solaris returns EINVAL when the buffer is too small.
+ */
+ if (ioctl (fd, siocgifconf, &ifconf) < 0 && errno != EINVAL) {
+ ret = errno;
+ goto error_out;
+ }
+ /*
+ * Can the difference between a full and a overfull buf
+ * be determined?
+ */
+
+ if (ifconf.ifc_len < buf_size)
+ break;
+ free (buf);
+ buf_size *= 2;
+ }
+
+ for (p = ifconf.ifc_buf;
+ p < ifconf.ifc_buf + ifconf.ifc_len;
+ p += sz) {
+ struct ifreq ifreq;
+ struct sockaddr *sa;
+ size_t salen;
+
+ ifr = (struct ifreq *)p;
+ sa = &ifr->ifr_addr;
+
+ sz = ifreq_sz;
+ salen = sizeof(struct sockaddr);
+#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
+ salen = sa->sa_len;
+ sz = max(sz, sizeof(ifr->ifr_name) + sa->sa_len);
+#endif
+#ifdef SA_LEN
+ salen = SA_LEN(sa);
+ sz = max(sz, sizeof(ifr->ifr_name) + SA_LEN(sa));
+#endif
+ memset (&ifreq, 0, sizeof(ifreq));
+ memcpy (ifreq.ifr_name, ifr->ifr_name, sizeof(ifr->ifr_name));
+
+ if (ioctl(fd, siocgifflags, &ifreq) < 0) {
+ ret = errno;
+ goto error_out;
+ }
+
+ *end = malloc(sizeof(**end));
+ if (*end == NULL) {
+ ret = ENOMEM;
+ goto error_out;
+ }
+
+ (*end)->ifa_next = NULL;
+ (*end)->ifa_name = strdup(ifr->ifr_name);
+ if ((*end)->ifa_name == NULL) {
+ ret = ENOMEM;
+ goto error_out;
+ }
+ (*end)->ifa_flags = ifreq.ifr_flags;
+ (*end)->ifa_addr = malloc(salen);
+ if ((*end)->ifa_addr == NULL) {
+ ret = ENOMEM;
+ goto error_out;
+ }
+ memcpy((*end)->ifa_addr, sa, salen);
+ (*end)->ifa_netmask = NULL;
+
+#if 0
+ /* fix these when we actually need them */
+ if(ifreq.ifr_flags & IFF_BROADCAST) {
+ (*end)->ifa_broadaddr = malloc(sizeof(ifr->ifr_broadaddr));
+ if ((*end)->ifa_broadaddr == NULL) {
+ ret = ENOMEM;
+ goto error_out;
+ }
+ memcpy((*end)->ifa_broadaddr, &ifr->ifr_broadaddr,
+ sizeof(ifr->ifr_broadaddr));
+ } else if(ifreq.ifr_flags & IFF_POINTOPOINT) {
+ (*end)->ifa_dstaddr = malloc(sizeof(ifr->ifr_dstaddr));
+ if ((*end)->ifa_dstaddr == NULL) {
+ ret = ENOMEM;
+ goto error_out;
+ }
+ memcpy((*end)->ifa_dstaddr, &ifr->ifr_dstaddr,
+ sizeof(ifr->ifr_dstaddr));
+ } else
+ (*end)->ifa_dstaddr = NULL;
+#else
+ (*end)->ifa_dstaddr = NULL;
+#endif
+
+ (*end)->ifa_data = NULL;
+
+ end = &(*end)->ifa_next;
+
+ }
+ *ifap = start;
+ close(fd);
+ free(buf);
+ return 0;
+ error_out:
+ rk_freeifaddrs(start);
+ close(fd);
+ free(buf);
+ errno = ret;
+ return -1;
+}
+
+#if defined(HAVE_IPV6) && defined(SIOCGLIFCONF) && defined(SIOCGLIFFLAGS)
+static int
+getlifaddrs2(struct ifaddrs **ifap,
+ int af, int siocgifconf, int siocgifflags,
+ size_t ifreq_sz)
+{
+ int ret;
+ int fd;
+ size_t buf_size;
+ char *buf;
+ struct lifconf ifconf;
+ char *p;
+ size_t sz;
+ struct sockaddr sa_zero;
+ struct lifreq *ifr;
+ struct ifaddrs *start = NULL, **end = &start;
+
+ buf = NULL;
+
+ memset (&sa_zero, 0, sizeof(sa_zero));
+ fd = socket(af, SOCK_DGRAM, 0);
+ if (fd < 0)
+ return -1;
+
+ buf_size = 8192;
+ for (;;) {
+ buf = calloc(1, buf_size);
+ if (buf == NULL) {
+ ret = ENOMEM;
+ goto error_out;
+ }
+#ifndef __hpux
+ ifconf.lifc_family = af;
+ ifconf.lifc_flags = 0;
+#endif
+ ifconf.lifc_len = buf_size;
+ ifconf.lifc_buf = buf;
+
+ /*
+ * Solaris returns EINVAL when the buffer is too small.
+ */
+ if (ioctl (fd, siocgifconf, &ifconf) < 0 && errno != EINVAL) {
+ ret = errno;
+ goto error_out;
+ }
+ /*
+ * Can the difference between a full and a overfull buf
+ * be determined?
+ */
+
+ if (ifconf.lifc_len < buf_size)
+ break;
+ free (buf);
+ buf_size *= 2;
+ }
+
+ for (p = ifconf.lifc_buf;
+ p < ifconf.lifc_buf + ifconf.lifc_len;
+ p += sz) {
+ struct lifreq ifreq;
+ struct sockaddr_storage *sa;
+ size_t salen;
+
+ ifr = (struct lifreq *)p;
+ sa = &ifr->lifr_addr;
+
+ sz = ifreq_sz;
+ salen = sizeof(struct sockaddr_storage);
+#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
+ salen = sa->sa_len;
+ sz = max(sz, sizeof(ifr->ifr_name) + sa->sa_len);
+#endif
+#ifdef SA_LEN
+ salen = SA_LEN(sa);
+ sz = max(sz, sizeof(ifr->ifr_name) + SA_LEN(sa));
+#endif
+ memset (&ifreq, 0, sizeof(ifreq));
+ memcpy (ifreq.lifr_name, ifr->lifr_name, sizeof(ifr->lifr_name));
+
+ if (ioctl(fd, siocgifflags, &ifreq) < 0) {
+ ret = errno;
+ goto error_out;
+ }
+
+ *end = malloc(sizeof(**end));
+ if (*end == NULL) {
+ ret = ENOMEM;
+ goto error_out;
+ }
+
+ (*end)->ifa_next = NULL;
+ (*end)->ifa_name = strdup(ifr->lifr_name);
+ if ((*end)->ifa_name == NULL) {
+ ret = ENOMEM;
+ goto error_out;
+ }
+ (*end)->ifa_flags = ifreq.lifr_flags;
+ (*end)->ifa_addr = malloc(salen);
+ if ((*end)->ifa_addr == NULL) {
+ ret = ENOMEM;
+ goto error_out;
+ }
+ memcpy((*end)->ifa_addr, sa, salen);
+ (*end)->ifa_netmask = NULL;
+
+#if 0
+ /* fix these when we actually need them */
+ if(ifreq.ifr_flags & IFF_BROADCAST) {
+ (*end)->ifa_broadaddr = malloc(sizeof(ifr->ifr_broadaddr));
+ if ((*end)->ifa_broadaddr == NULL) {
+ ret = ENOMEM;
+ goto error_out;
+ }
+ memcpy((*end)->ifa_broadaddr, &ifr->ifr_broadaddr,
+ sizeof(ifr->ifr_broadaddr));
+ } else if(ifreq.ifr_flags & IFF_POINTOPOINT) {
+ (*end)->ifa_dstaddr = malloc(sizeof(ifr->ifr_dstaddr));
+ if ((*end)->ifa_dstaddr == NULL) {
+ ret = ENOMEM;
+ goto error_out;
+ }
+ memcpy((*end)->ifa_dstaddr, &ifr->ifr_dstaddr,
+ sizeof(ifr->ifr_dstaddr));
+ } else
+ (*end)->ifa_dstaddr = NULL;
+#else
+ (*end)->ifa_dstaddr = NULL;
+#endif
+
+ (*end)->ifa_data = NULL;
+
+ end = &(*end)->ifa_next;
+
+ }
+ *ifap = start;
+ close(fd);
+ free(buf);
+ return 0;
+ error_out:
+ rk_freeifaddrs(start);
+ close(fd);
+ free(buf);
+ errno = ret;
+ return -1;
+}
+#endif /* defined(HAVE_IPV6) && defined(SIOCGLIFCONF) && defined(SIOCGLIFFLAGS) */
+
+/**
+ * Join two struct ifaddrs lists by appending supp to base.
+ * Either may be NULL. The new list head (usually base) will be
+ * returned.
+ */
+static struct ifaddrs *
+append_ifaddrs(struct ifaddrs *base, struct ifaddrs *supp) {
+ if (!base)
+ return supp;
+
+ if (!supp)
+ return base;
+
+ while (base->ifa_next)
+ base = base->ifa_next;
+
+ base->ifa_next = supp;
+
+ return base;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_getifaddrs(struct ifaddrs **ifap)
+{
+ int ret = -1;
+ errno = ENXIO;
+#if defined(AF_INET6) && defined(SIOCGIF6CONF) && defined(SIOCGIF6FLAGS)
+ if (ret)
+ ret = getifaddrs2 (ifap, AF_INET6, SIOCGIF6CONF, SIOCGIF6FLAGS,
+ sizeof(struct in6_ifreq));
+#endif
+#if defined(HAVE_IPV6) && defined(SIOCGLIFCONF) && defined(SIOCGLIFFLAGS)
+ /* Do IPv6 and IPv4 queries separately then join the result.
+ *
+ * HP-UX only returns IPv6 addresses using SIOCGLIFCONF,
+ * SIOCGIFCONF has to be used for IPv4 addresses. The result is then
+ * merged.
+ *
+ * Solaris needs particular care, because a SIOCGLIFCONF lookup using
+ * AF_UNSPEC can fail in a Zone requiring an AF_INET lookup, so we just
+ * do them separately the same as for HP-UX. See
+ * http://repo.or.cz/w/heimdal.git/commitdiff/76afc31e9ba2f37e64c70adc006ade9e37e9ef73
+ */
+ if (ret) {
+ int v6err, v4err;
+ struct ifaddrs *v6addrs, *v4addrs;
+
+ v6err = getlifaddrs2 (&v6addrs, AF_INET6, SIOCGLIFCONF, SIOCGLIFFLAGS,
+ sizeof(struct lifreq));
+ v4err = getifaddrs2 (&v4addrs, AF_INET, SIOCGIFCONF, SIOCGIFFLAGS,
+ sizeof(struct ifreq));
+ if (v6err)
+ v6addrs = NULL;
+ if (v4err)
+ v4addrs = NULL;
+
+ if (v6addrs) {
+ if (v4addrs)
+ *ifap = append_ifaddrs(v6addrs, v4addrs);
+ else
+ *ifap = v6addrs;
+ } else if (v4addrs) {
+ *ifap = v4addrs;
+ } else {
+ *ifap = NULL;
+ }
+
+ ret = (v6err || v4err) ? -1 : 0;
+ }
+#endif
+#if defined(HAVE_IPV6) && defined(SIOCGIFCONF)
+ if (ret)
+ ret = getifaddrs2 (ifap, AF_INET6, SIOCGIFCONF, SIOCGIFFLAGS,
+ sizeof(struct ifreq));
+#endif
+#if defined(AF_INET) && defined(SIOCGIFCONF) && defined(SIOCGIFFLAGS)
+ if (ret)
+ ret = getifaddrs2 (ifap, AF_INET, SIOCGIFCONF, SIOCGIFFLAGS,
+ sizeof(struct ifreq));
+#endif
+ return ret;
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_freeifaddrs(struct ifaddrs *ifp)
+{
+ struct ifaddrs *p, *q;
+
+ for(p = ifp; p; ) {
+ free(p->ifa_name);
+ if(p->ifa_addr)
+ free(p->ifa_addr);
+ if(p->ifa_dstaddr)
+ free(p->ifa_dstaddr);
+ if(p->ifa_netmask)
+ free(p->ifa_netmask);
+ if(p->ifa_data)
+ free(p->ifa_data);
+ q = p;
+ p = p->ifa_next;
+ free(q);
+ }
+}
+
+#endif /* !AF_NETLINK */
+
+#ifdef TEST
+
+void
+print_addr(const char *s, struct sockaddr *sa)
+{
+ int i;
+ printf(" %s=%d/", s, sa->sa_family);
+#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
+ for(i = 0; i < sa->sa_len - ((long)sa->sa_data - (long)&sa->sa_family); i++)
+ printf("%02x", ((unsigned char*)sa->sa_data)[i]);
+#else
+ for(i = 0; i < sizeof(sa->sa_data); i++)
+ printf("%02x", ((unsigned char*)sa->sa_data)[i]);
+#endif
+ printf("\n");
+}
+
+void
+print_ifaddrs(struct ifaddrs *x)
+{
+ struct ifaddrs *p;
+
+ for(p = x; p; p = p->ifa_next) {
+ printf("%s\n", p->ifa_name);
+ printf(" flags=%x\n", p->ifa_flags);
+ if(p->ifa_addr)
+ print_addr("addr", p->ifa_addr);
+ if(p->ifa_dstaddr)
+ print_addr("dstaddr", p->ifa_dstaddr);
+ if(p->ifa_netmask)
+ print_addr("netmask", p->ifa_netmask);
+ printf(" %p\n", p->ifa_data);
+ }
+}
+
+int
+main()
+{
+ struct ifaddrs *a = NULL, *b;
+ getifaddrs2(&a, AF_INET, SIOCGIFCONF, SIOCGIFFLAGS, sizeof(struct ifreq));
+ print_ifaddrs(a);
+ printf("---\n");
+ getifaddrs(&b);
+ print_ifaddrs(b);
+ return 0;
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/getifaddrs_w32.c b/third_party/heimdal/lib/roken/getifaddrs_w32.c
new file mode 100644
index 0000000..beb29b3
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getifaddrs_w32.c
@@ -0,0 +1,161 @@
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include<config.h>
+
+#include <roken.h>
+
+#include <ifaddrs.h>
+
+#ifndef _WIN32
+#error This is a Windows specific implementation.
+#endif
+
+static struct sockaddr *
+dupaddr(const sockaddr_gen * src)
+{
+ sockaddr_gen * d = malloc(sizeof(*d));
+
+ if (d) {
+ memcpy(d, src, sizeof(*d));
+ }
+
+ return (struct sockaddr *) d;
+}
+
+int ROKEN_LIB_FUNCTION
+rk_getifaddrs(struct ifaddrs **ifpp)
+{
+ SOCKET s = INVALID_SOCKET;
+ size_t il_len = 8192;
+ int ret = -1;
+ INTERFACE_INFO *il = NULL;
+
+ *ifpp = NULL;
+
+ s = socket(AF_INET, SOCK_DGRAM, 0);
+ if (s == INVALID_SOCKET)
+ return -1;
+
+ for (;;) {
+ DWORD cbret = 0;
+
+ il = malloc(il_len);
+ if (!il)
+ break;
+
+ ZeroMemory(il, il_len);
+
+ if (WSAIoctl(s, SIO_GET_INTERFACE_LIST, NULL, 0,
+ (LPVOID) il, (DWORD) il_len, &cbret,
+ NULL, NULL) == 0) {
+ il_len = cbret;
+ break;
+ }
+
+ free (il);
+ il = NULL;
+
+ if (WSAGetLastError() == WSAEFAULT && cbret > il_len) {
+ il_len = cbret;
+ } else {
+ break;
+ }
+ }
+
+ if (!il)
+ goto _exit;
+
+ /* il is an array of INTERFACE_INFO structures. il_len has the
+ actual size of the buffer. The number of elements is
+ il_len/sizeof(INTERFACE_INFO) */
+
+ {
+ size_t n = il_len / sizeof(INTERFACE_INFO);
+ size_t i;
+
+ for (i = 0; i < n; i++ ) {
+ struct ifaddrs *ifp;
+
+ ifp = malloc(sizeof(*ifp));
+ if (ifp == NULL)
+ break;
+
+ ZeroMemory(ifp, sizeof(*ifp));
+
+ ifp->ifa_next = NULL;
+ ifp->ifa_name = NULL;
+ ifp->ifa_flags = il[i].iiFlags;
+ ifp->ifa_addr = dupaddr(&il[i].iiAddress);
+ ifp->ifa_netmask = dupaddr(&il[i].iiNetmask);
+ ifp->ifa_broadaddr = dupaddr(&il[i].iiBroadcastAddress);
+ ifp->ifa_data = NULL;
+
+ *ifpp = ifp;
+ ifpp = &ifp->ifa_next;
+ }
+
+ if (i == n)
+ ret = 0;
+ }
+
+ _exit:
+
+ if (s != INVALID_SOCKET)
+ closesocket(s);
+
+ if (il)
+ free (il);
+
+ return ret;
+}
+
+void ROKEN_LIB_FUNCTION
+rk_freeifaddrs(struct ifaddrs *ifp)
+{
+ struct ifaddrs *p, *q;
+
+ for(p = ifp; p; ) {
+ if (p->ifa_name)
+ free(p->ifa_name);
+ if(p->ifa_addr)
+ free(p->ifa_addr);
+ if(p->ifa_dstaddr)
+ free(p->ifa_dstaddr);
+ if(p->ifa_netmask)
+ free(p->ifa_netmask);
+ if(p->ifa_data)
+ free(p->ifa_data);
+ q = p;
+ p = p->ifa_next;
+ free(q);
+ }
+}
diff --git a/third_party/heimdal/lib/roken/getipnodebyaddr.c b/third_party/heimdal/lib/roken/getipnodebyaddr.c
new file mode 100644
index 0000000..afebe91
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getipnodebyaddr.c
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/*
+ * lookup `src, len' (address family `af') in DNS and return a pointer
+ * to a malloced struct hostent or NULL.
+ */
+
+ROKEN_LIB_FUNCTION struct hostent * ROKEN_LIB_CALL
+rk_getipnodebyaddr(const void *src, size_t len, int af, int *error_num)
+{
+ struct hostent *tmp;
+
+ tmp = gethostbyaddr (src, len, af);
+ if (tmp == NULL) {
+ switch (h_errno) {
+ case HOST_NOT_FOUND :
+ case TRY_AGAIN :
+ case NO_RECOVERY :
+ *error_num = h_errno;
+ break;
+ case NO_DATA :
+ *error_num = NO_ADDRESS;
+ break;
+ default :
+ *error_num = NO_RECOVERY;
+ break;
+ }
+ return NULL;
+ }
+ tmp = copyhostent (tmp);
+ if (tmp == NULL) {
+ *error_num = TRY_AGAIN;
+ return NULL;
+ }
+ return tmp;
+}
diff --git a/third_party/heimdal/lib/roken/getipnodebyname.c b/third_party/heimdal/lib/roken/getipnodebyname.c
new file mode 100644
index 0000000..ee430c7
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getipnodebyname.c
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+#ifndef HAVE_H_ERRNO
+static int h_errno = NO_RECOVERY;
+#endif
+
+/*
+ * lookup `name' (address family `af') in DNS and return a pointer
+ * to a malloced struct hostent or NULL.
+ */
+
+ROKEN_LIB_FUNCTION struct hostent * ROKEN_LIB_CALL
+rk_getipnodebyname(const char *name, int af, int flags, int *error_num)
+{
+ struct hostent *tmp;
+
+#ifdef HAVE_GETHOSTBYNAME2
+ tmp = gethostbyname2 (name, af);
+#else
+ if (af != AF_INET) {
+ *error_num = NO_ADDRESS;
+ return NULL;
+ }
+ tmp = gethostbyname (name);
+#endif
+ if (tmp == NULL) {
+ switch (h_errno) {
+ case HOST_NOT_FOUND :
+ case TRY_AGAIN :
+ case NO_RECOVERY :
+ *error_num = h_errno;
+ break;
+ case NO_DATA :
+ *error_num = NO_ADDRESS;
+ break;
+ default :
+ *error_num = NO_RECOVERY;
+ break;
+ }
+ return NULL;
+ }
+ tmp = copyhostent (tmp);
+ if (tmp == NULL) {
+ *error_num = TRY_AGAIN;
+ return NULL;
+ }
+ return tmp;
+}
diff --git a/third_party/heimdal/lib/roken/getnameinfo.c b/third_party/heimdal/lib/roken/getnameinfo.c
new file mode 100644
index 0000000..9d11860
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getnameinfo.c
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+static int
+doit (int af,
+ const void *addr,
+ size_t addrlen,
+ int port,
+ char *host, size_t hostlen,
+ char *serv, size_t servlen,
+ int flags)
+{
+ if (host != NULL) {
+ if (flags & NI_NUMERICHOST) {
+ if (inet_ntop (af, addr, host, hostlen) == NULL)
+ return EAI_SYSTEM;
+ } else {
+ struct hostent *he = gethostbyaddr (addr,
+ addrlen,
+ af);
+ if (he != NULL) {
+ strlcpy (host, hostent_find_fqdn(he), hostlen);
+ if (flags & NI_NOFQDN) {
+ char *dot = strchr (host, '.');
+ if (dot != NULL)
+ *dot = '\0';
+ }
+ } else if (flags & NI_NAMEREQD) {
+ return EAI_NONAME;
+ } else if (inet_ntop (af, addr, host, hostlen) == NULL)
+ return EAI_SYSTEM;
+ }
+ }
+
+ if (serv != NULL) {
+ if (flags & NI_NUMERICSERV) {
+ snprintf (serv, servlen, "%u", ntohs(port));
+ } else {
+ const char *proto = "tcp";
+ struct servent *se;
+
+ if (flags & NI_DGRAM)
+ proto = "udp";
+
+ se = getservbyport (port, proto);
+ if (se == NULL) {
+ snprintf (serv, servlen, "%u", ntohs(port));
+ } else {
+ strlcpy (serv, se->s_name, servlen);
+ }
+ }
+ }
+ return 0;
+}
+
+/*
+ *
+ */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_getnameinfo(const struct sockaddr *sa, socklen_t salen,
+ char *host, size_t hostlen,
+ char *serv, size_t servlen,
+ int flags)
+{
+ switch (sa->sa_family) {
+#ifdef HAVE_IPV6
+ case AF_INET6 : {
+ const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)sa;
+
+ return doit (AF_INET6, &sin6->sin6_addr, sizeof(sin6->sin6_addr),
+ sin6->sin6_port,
+ host, hostlen,
+ serv, servlen,
+ flags);
+ }
+#endif
+ case AF_INET : {
+ const struct sockaddr_in *sin4 = (const struct sockaddr_in *)sa;
+
+ return doit (AF_INET, &sin4->sin_addr, sizeof(sin4->sin_addr),
+ sin4->sin_port,
+ host, hostlen,
+ serv, servlen,
+ flags);
+ }
+ default :
+ return EAI_FAMILY;
+ }
+}
diff --git a/third_party/heimdal/lib/roken/getnameinfo_verified.c b/third_party/heimdal/lib/roken/getnameinfo_verified.c
new file mode 100644
index 0000000..6175291
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getnameinfo_verified.c
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 1999 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/*
+ * Try to obtain a verified name for the address in `sa, salen' (much
+ * similar to getnameinfo).
+ * Verified in this context means that forwards and backwards lookups
+ * in DNS are consistent. If that fails, return an error if the
+ * NI_NAMEREQD flag is set or return the numeric address as a string.
+ */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+getnameinfo_verified(const struct sockaddr *sa, socklen_t salen,
+ char *host, size_t hostlen,
+ char *serv, size_t servlen,
+ int flags)
+{
+ int ret;
+ struct addrinfo *ai, *a;
+ char servbuf[NI_MAXSERV];
+ struct addrinfo hints;
+ void *saaddr;
+ size_t sasize;
+
+ if (host == NULL)
+ return EAI_NONAME;
+
+ if (serv == NULL) {
+ serv = servbuf;
+ servlen = sizeof(servbuf);
+ }
+
+ ret = getnameinfo (sa, salen, host, hostlen, serv, servlen,
+ flags | NI_NUMERICSERV);
+ if (ret)
+ goto fail;
+
+ memset (&hints, 0, sizeof(hints));
+ hints.ai_socktype = SOCK_STREAM;
+ ret = getaddrinfo (host, serv, &hints, &ai);
+ if (ret)
+ goto fail;
+
+ saaddr = socket_get_address(sa);
+ sasize = socket_addr_size(sa);
+ for (a = ai; a != NULL; a = a->ai_next) {
+ if (sasize == socket_addr_size(a->ai_addr) &&
+ memcmp(saaddr, socket_get_address(a->ai_addr), sasize) == 0) {
+ freeaddrinfo (ai);
+ return 0;
+ }
+ }
+ freeaddrinfo (ai);
+ fail:
+ if (flags & NI_NAMEREQD)
+ return EAI_NONAME;
+ ret = getnameinfo (sa, salen, host, hostlen, serv, servlen,
+ flags | NI_NUMERICSERV | NI_NUMERICHOST);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/getopt.c b/third_party/heimdal/lib/roken/getopt.c
new file mode 100644
index 0000000..f035f74
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getopt.c
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 1987, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+static char sccsid[] = "@(#)getopt.c 8.1 (Berkeley) 6/4/93";
+#endif /* LIBC_SCCS and not lint */
+
+#ifndef __STDC__
+#define const
+#endif
+#include <config.h>
+#include "roken.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+/*
+ * get option letter from argument vector
+ */
+ROKEN_LIB_VARIABLE int opterr = 1; /* if error message should be printed */
+ROKEN_LIB_VARIABLE int optind = 1; /* index into parent argv vector */
+ROKEN_LIB_VARIABLE int optopt; /* character checked for validity */
+int optreset; /* reset getopt */
+ROKEN_LIB_VARIABLE char *optarg; /* argument associated with option */
+
+#define BADCH (int)'?'
+#define BADARG (int)':'
+#define EMSG ""
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+getopt(int nargc, char * const *nargv, const char *ostr)
+{
+ static char *place = EMSG; /* option letter processing */
+ char *oli; /* option letter list index */
+ char *p;
+
+ if (optreset || !*place) { /* update scanning pointer */
+ optreset = 0;
+ if (optind >= nargc || *(place = nargv[optind]) != '-') {
+ place = EMSG;
+ return(-1);
+ }
+ if (place[1] && *++place == '-') { /* found "--" */
+ ++optind;
+ place = EMSG;
+ return(-1);
+ }
+ } /* option letter okay? */
+ if ((optopt = (int)*place++) == (int)':' ||
+ !(oli = strchr(ostr, optopt))) {
+ /*
+ * if the user didn't specify '-' as an option,
+ * assume it means -1 (EOF).
+ */
+ if (optopt == (int)'-')
+ return(-1);
+ if (!*place)
+ ++optind;
+ if (opterr && *ostr != ':') {
+ if (!(p = strrchr(*nargv, '/')))
+ p = *nargv;
+ else
+ ++p;
+ fprintf(stderr, "%s: illegal option -- %c\n",
+ p, optopt);
+ }
+ return(BADCH);
+ }
+ if (*++oli != ':') { /* don't need argument */
+ optarg = NULL;
+ if (!*place)
+ ++optind;
+ }
+ else { /* need an argument */
+ if (*place) /* no white space */
+ optarg = place;
+ else if (nargc <= ++optind) { /* no arg */
+ place = EMSG;
+ if (!(p = strrchr(*nargv, '/')))
+ p = *nargv;
+ else
+ ++p;
+ if (*ostr == ':')
+ return(BADARG);
+ if (opterr)
+ fprintf(stderr,
+ "%s: option requires an argument -- %c\n",
+ p, optopt);
+ return(BADCH);
+ }
+ else /* white space */
+ optarg = nargv[optind];
+ place = EMSG;
+ ++optind;
+ }
+ return(optopt); /* dump back option letter */
+}
diff --git a/third_party/heimdal/lib/roken/getprogname.c b/third_party/heimdal/lib/roken/getprogname.c
new file mode 100644
index 0000000..a310208
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getprogname.c
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 1995-2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+#ifndef HAVE___PROGNAME
+const char *__progname;
+#endif
+
+#ifndef HAVE_GETPROGNAME
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
+getprogname(void)
+{
+ return __progname;
+}
+#endif /* HAVE_GETPROGNAME */
diff --git a/third_party/heimdal/lib/roken/gettimeofday.c b/third_party/heimdal/lib/roken/gettimeofday.c
new file mode 100644
index 0000000..918b6f6
--- /dev/null
+++ b/third_party/heimdal/lib/roken/gettimeofday.c
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include "roken.h"
+#ifndef HAVE_GETTIMEOFDAY
+
+#ifdef _WIN32
+
+typedef BOOL (WINAPI *LPFN_GETSYSTEMTIME) (LPFILETIME);
+
+static LPFN_GETSYSTEMTIME lpGetSystemTime = NULL;
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+gettimeofday (struct timeval *tp, void *ignore)
+{
+ FILETIME ft;
+ ULARGE_INTEGER li;
+ ULONGLONG ull;
+
+ if (lpGetSystemTime == NULL) {
+ HANDLE h1;
+ LPFN_GETSYSTEMTIME fn;
+
+ h1 = GetModuleHandle(TEXT("kernel32.dll")); /* no refcount increase */
+ fn = (LPFN_GETSYSTEMTIME)GetProcAddress(h1,
+ "GetSystemTimePreciseAsFileTime");
+ if (fn == NULL)
+ fn = (LPFN_GETSYSTEMTIME)GetProcAddress(h1,
+ "GetSystemTimeAsFileTime");
+ lpGetSystemTime = fn;
+ }
+
+ lpGetSystemTime(&ft);
+ li.LowPart = ft.dwLowDateTime;
+ li.HighPart = ft.dwHighDateTime;
+ ull = li.QuadPart;
+
+ ull -= 116444736000000000i64;
+ ull /= 10i64; /* ull is now in microseconds */
+
+ tp->tv_usec = (ull % 1000000i64);
+ tp->tv_sec = (ull / 1000000i64);
+
+ return 0;
+}
+#else
+
+/*
+ * Simple gettimeofday that only returns seconds.
+ */
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+gettimeofday (struct timeval *tp, void *ignore)
+{
+ time_t t;
+
+ t = time(NULL);
+ tp->tv_sec = (long) t;
+ tp->tv_usec = 0;
+ return 0;
+}
+
+#endif /* !_WIN32 */
+#endif
diff --git a/third_party/heimdal/lib/roken/getuid.c b/third_party/heimdal/lib/roken/getuid.c
new file mode 100644
index 0000000..63fdec1
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getuid.c
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include "roken.h"
+
+#ifndef HAVE_GETUID
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+getuid(void)
+{
+ return 17;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/getuserinfo.c b/third_party/heimdal/lib/roken/getuserinfo.c
new file mode 100644
index 0000000..7fd2ca9
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getuserinfo.c
@@ -0,0 +1,334 @@
+/*
+ * Copyright (c) 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include "roken.h"
+
+#ifdef WIN32
+#include <Shlobj.h> // need to include definitions of constants
+#define SECURITY_WIN32
+#include <security.h>
+#else
+#include <sys/types.h>
+#include <pwd.h>
+#include <unistd.h>
+#endif
+
+/**
+ * Returns the user's SHELL.
+ */
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+roken_get_shell(char *shell, size_t shellsz)
+{
+ char *p;
+
+#ifndef WIN32
+#ifdef HAVE_GETPWNAM_R
+ size_t buflen = 2048;
+
+ if (sysconf(_SC_GETPW_R_SIZE_MAX) > 0)
+ buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
+#endif
+
+ if (issuid())
+ return "/bin/sh";
+
+ p = secure_getenv("SHELL");
+ if (p != NULL && p[0] != '\0') {
+ if (strlcpy(shell, p, shellsz) < shellsz)
+ return shell;
+ errno = ERANGE;
+ return NULL;
+ }
+
+#ifdef HAVE_GETPWNAM_R
+ {
+ struct passwd pwd;
+ struct passwd *pwdp;
+ char buf[buflen];
+ char user[128];
+ const char *username = roken_get_username(user, sizeof(user));
+
+ if (username &&
+ getpwnam_r(username, &pwd, buf, buflen, &pwdp) == 0 &&
+ pwdp != NULL && pwdp->pw_shell != NULL) {
+ if (strlcpy(shell, pwdp->pw_shell, shellsz) < shellsz)
+ return shell;
+ errno = ERANGE;
+ return NULL;
+ }
+ }
+#endif
+ errno = 0;
+ return "/bin/sh";
+#else
+ /* Windows */
+ p = getenv("SHELL");
+ if (p != NULL && p[0] != '\0') {
+ if (strlcpy(shell, p, shellsz) < shellsz)
+ return shell;
+ errno = ERANGE;
+ return NULL;
+ }
+ errno = 0;
+ return NULL;
+#endif
+}
+
+/**
+ * Returns the home directory.
+ */
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+roken_get_homedir(char *home, size_t homesz)
+{
+ char *p;
+
+#ifdef WIN32
+ if (homesz < MAX_PATH) {
+ errno = ERANGE;
+ return NULL;
+ }
+
+ if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL,
+ SHGFP_TYPE_CURRENT, home)))
+ return home;
+
+ if ((p = getenv("HOMEDRIVE")) != NULL && p[0] != '\0') {
+ if (strlcpy(home, p, homesz) >= homesz) {
+ errno = ERANGE;
+ return NULL;
+ }
+ if ((p = getenv("HOMEPATH")) != NULL) {
+ if (strlcat(home, p, homesz) < homesz)
+ return home;
+ errno = ERANGE;
+ return NULL;
+ }
+ return home;
+ }
+ fallthrough;
+#else
+#ifdef HAVE_GETPWNAM_R
+ size_t buflen = 2048;
+
+ if (sysconf(_SC_GETPW_R_SIZE_MAX) > 0)
+ buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
+#endif
+
+ if (issuid()) {
+ errno = 0;
+ return NULL;
+ }
+
+ p = secure_getenv("HOME");
+ if (p != NULL && p[0] != '\0') {
+ if (strlcpy(home, p, homesz) < homesz)
+ return home;
+ errno = ERANGE;
+ return NULL;
+ }
+
+#ifdef HAVE_GETPWNAM_R
+ {
+ char user[128];
+ const char *username = roken_get_username(user, sizeof(user));
+ struct passwd pwd;
+ struct passwd *pwdp;
+ char buf[buflen];
+
+ if (username &&
+ getpwnam_r(username, &pwd, buf, buflen, &pwdp) == 0 &&
+ pwdp != NULL && pwdp->pw_dir != NULL) {
+ if (strlcpy(home, pwdp->pw_dir, homesz) < homesz)
+ return home;
+ errno = ERANGE;
+ return NULL;
+ }
+ }
+#endif
+#endif
+ errno = 0;
+ return NULL;
+}
+
+/**
+ * Returns the home directory on Unix, or the AppData directory on
+ * Windows.
+ */
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+roken_get_appdatadir(char *appdata, size_t appdatasz)
+{
+#ifdef WIN32
+ char *p;
+#endif
+
+#ifndef WIN32
+ return roken_get_homedir(appdata, appdatasz);
+#else
+ if (appdatasz < MAX_PATH) {
+ errno = ERANGE;
+ return NULL;
+ }
+
+ if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL,
+ SHGFP_TYPE_CURRENT, appdata)))
+ return appdata;
+
+ if ((p = getenv("APPDATA")) != NULL && p[0] != '\0') {
+ if (strlcpy(appdata, p, appdatasz) < appdatasz)
+ return appdata;
+ errno = ERANGE;
+ return NULL;
+ }
+
+ errno = 0;
+ return NULL;
+#endif
+}
+
+/**
+ * Return a bare username. This is used for, e.g., constructing default
+ * principal names.
+ *
+ * On POSIX systems, if the caller is not set-uid-like, then this will return
+ * the value of the USER or LOGNAME environment variables (in that order of
+ * preference), else the username found by looking up the effective UID.
+ */
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+roken_get_username(char *user, size_t usersz)
+{
+ char *p;
+
+#ifdef WIN32
+ ULONG sz = usersz;
+
+ if (GetUserNameEx(NameSamCompatible, user, &sz)) {
+ /*
+ * There's no EXTENDED_NAME_FORMAT for "bare username". We we
+ * have to parse one.
+ */
+ p = strchr(user, '\\');
+ if (p != NULL) {
+ p++;
+ memmove(user, p, strlen(p) + 1);
+ }
+ return user;
+ } else {
+ DWORD err = GetLastError();
+ if (err == ERROR_MORE_DATA) {
+ errno = ERANGE;
+ return NULL;
+ }
+ /* %USERNAME% is generally bare */
+ p = getenv("USERNAME");
+ if (p != NULL && p[0] != '\0') {
+ if (strchr(p, '\\') != NULL)
+ p = strchr(p, '\\') + 1;
+ if (strlcpy(user, p, usersz) < usersz)
+ return user;
+ errno = ERANGE;
+ return NULL;
+ }
+ }
+#else
+#ifdef HAVE_GETPWUID_R
+ size_t buflen = 2048;
+
+ if (sysconf(_SC_GETPW_R_SIZE_MAX) > 0)
+ buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
+#endif
+
+ p = secure_getenv("USER");
+ if (p == NULL || p[0] == '\0')
+ p = secure_getenv("LOGNAME");
+ if (p != NULL && p[0] != '\0') {
+ if (strlcpy(user, p, usersz) < usersz)
+ return user;
+ errno = ERANGE;
+ return NULL;
+ }
+
+#ifdef HAVE_GETPWUID_R
+ {
+ struct passwd pwd;
+ struct passwd *pwdp;
+ char buf[buflen];
+
+ if (getpwuid_r(getuid(), &pwd, buf, buflen, &pwdp) == 0 &&
+ pwdp != NULL && pwdp->pw_name != NULL) {
+ if (strlcpy(user, pwdp->pw_name, usersz) < usersz)
+ return user;
+ errno = ERANGE;
+ return NULL;
+ }
+ }
+#endif
+#endif
+ errno = 0;
+ return NULL;
+}
+
+/**
+ * Return a bare username. This is used for, e.g., constructing default
+ * principal names.
+ *
+ * On POSIX systems this returns the name recorded in the system as currently
+ * logged in on the current terminal.
+ */
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+roken_get_loginname(char *user, size_t usersz)
+{
+#ifdef WIN32
+ return roken_get_username(user, usersz);
+#else
+#ifdef HAVE_GETLOGIN_R
+ if ((errno = getlogin_r(user, usersz)) == 0)
+ return user;
+ if (errno != ENOENT)
+ return NULL;
+#else
+#ifdef HAVE_GETLOGIN
+ if ((p = getlogin()) != NULL && p[0] != '\0') {
+ if (strlcpy(user, p, usersz) < usersz)
+ return user;
+ errno = ERANGE;
+ return NULL;
+ }
+ if (errno != ENOENT)
+ return NULL;
+#endif
+#endif
+ errno = 0;
+ return NULL;
+#endif
+}
diff --git a/third_party/heimdal/lib/roken/getusershell.c b/third_party/heimdal/lib/roken/getusershell.c
new file mode 100644
index 0000000..6f7145d
--- /dev/null
+++ b/third_party/heimdal/lib/roken/getusershell.c
@@ -0,0 +1,185 @@
+/*
+ * Copyright (c) 1985, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifndef HAVE_GETUSERSHELL
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#ifdef HAVE_PATHS_H
+#include <paths.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#endif
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#ifdef HAVE_USERSEC_H
+struct aud_rec;
+#include <usersec.h>
+#endif
+#ifdef HAVE_USERCONF_H
+#include <userconf.h>
+#endif
+#include "roken.h"
+
+#ifndef _PATH_SHELLS
+#define _PATH_SHELLS "/etc/shells"
+#endif
+
+#ifndef _PATH_BSHELL
+#define _PATH_BSHELL "/bin/sh"
+#endif
+
+#ifndef _PATH_CSHELL
+#define _PATH_CSHELL "/bin/csh"
+#endif
+
+/*
+ * Local shells should NOT be added here. They should be added in
+ * /etc/shells.
+ */
+
+static char *okshells[] = { _PATH_BSHELL, _PATH_CSHELL, NULL };
+static char **curshell, **shells, *strings;
+static char **initshells (void);
+
+/*
+ * Get a list of shells from _PATH_SHELLS, if it exists.
+ */
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+getusershell()
+{
+ char *ret;
+
+ if (curshell == NULL)
+ curshell = initshells();
+ ret = *curshell;
+ if (ret != NULL)
+ curshell++;
+ return (ret);
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+endusershell()
+{
+ if (shells != NULL)
+ free(shells);
+ shells = NULL;
+ if (strings != NULL)
+ free(strings);
+ strings = NULL;
+ curshell = NULL;
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+setusershell()
+{
+ curshell = initshells();
+}
+
+static char **
+initshells()
+{
+ char **sp, *cp;
+#ifdef HAVE_GETCONFATTR
+ char *tmp;
+ int nsh;
+#else
+ FILE *fp;
+#endif
+ struct stat statb;
+
+ free(shells);
+ shells = NULL;
+ free(strings);
+ strings = NULL;
+#ifdef HAVE_GETCONFATTR
+ if(getconfattr(SC_SYS_LOGIN, SC_SHELLS, &tmp, SEC_LIST) != 0)
+ return okshells;
+
+ for(cp = tmp, nsh = 0; *cp; cp += strlen(cp) + 1, nsh++);
+
+ shells = calloc(nsh + 1, sizeof(*shells));
+ if(shells == NULL)
+ return okshells;
+
+ strings = malloc(cp - tmp);
+ if(strings == NULL) {
+ free(shells);
+ shells = NULL;
+ return okshells;
+ }
+ memcpy(strings, tmp, cp - tmp);
+ for(sp = shells, cp = strings; *cp; cp += strlen(cp) + 1, sp++)
+ *sp = cp;
+#else
+ if ((fp = fopen(_PATH_SHELLS, "r")) == NULL)
+ return (okshells);
+ if (fstat(fileno(fp), &statb) == -1) {
+ fclose(fp);
+ return (okshells);
+ }
+ if ((strings = malloc((u_int)statb.st_size)) == NULL) {
+ fclose(fp);
+ return (okshells);
+ }
+ shells = calloc((unsigned)statb.st_size / 3, sizeof (char *));
+ if (shells == NULL) {
+ fclose(fp);
+ free(strings);
+ strings = NULL;
+ return (okshells);
+ }
+ sp = shells;
+ cp = strings;
+ while (fgets(cp, MaxPathLen + 1, fp) != NULL) {
+ while (*cp != '#' && *cp != '/' && *cp != '\0')
+ cp++;
+ if (*cp == '#' || *cp == '\0')
+ continue;
+ *sp++ = cp;
+ while (!isspace((unsigned char)*cp) && *cp != '#' && *cp != '\0')
+ cp++;
+ *cp++ = '\0';
+ }
+ fclose(fp);
+#endif
+ *sp = NULL;
+ return (shells);
+}
+#endif /* HAVE_GETUSERSHELL */
diff --git a/third_party/heimdal/lib/roken/h_errno.c b/third_party/heimdal/lib/roken/h_errno.c
new file mode 100644
index 0000000..7e49f80
--- /dev/null
+++ b/third_party/heimdal/lib/roken/h_errno.c
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifndef HAVE_H_ERRNO
+int h_errno = -17; /* Some magic number */
+#endif
diff --git a/third_party/heimdal/lib/roken/hex-test.c b/third_party/heimdal/lib/roken/hex-test.c
new file mode 100644
index 0000000..01f21c8
--- /dev/null
+++ b/third_party/heimdal/lib/roken/hex-test.c
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 1999 - 2001, 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include <hex.h>
+
+int
+main(int argc, char **argv)
+{
+ int numerr = 0;
+ int numtest = 1;
+ struct test {
+ void *data;
+ ssize_t len;
+ const char *result;
+ } *t, tests[] = {
+ { "", 0 , "" },
+ { "a", 1, "61" },
+ { "ab", 2, "6162" },
+ { "abc", 3, "616263" },
+ { "abcd", 4, "61626364" },
+ { "abcde", 5, "6162636465" },
+ { "abcdef", 6, "616263646566" },
+ { "abcdefg", 7, "61626364656667" },
+ { "=", 1, "3D" },
+ /* Embedded NUL, non-ASCII / binary */
+ { "\0\x01\x1a\xad\xf1\xff", 6, "00011AADF1FF" },
+ /* Invalid encodings */
+ { "", -1, "00.11AADF1FF" },
+ { "", -1, "000x1AADF1FF" },
+ { "", -1, "00011?ADF1FF" },
+ { NULL, 0, NULL }
+ };
+ for(t = tests; t->data; t++) {
+ ssize_t len;
+ char *str;
+
+ if (t->len > -1) {
+ (void) hex_encode(t->data, t->len, &str);
+ if (strcmp(str, t->result) != 0) {
+ fprintf(stderr, "failed test %d: %s != %s\n", numtest,
+ str, t->result);
+ numerr++;
+ }
+ free(str);
+ }
+ str = strdup(t->result);
+ len = strlen(str);
+ len = hex_decode(t->result, str, len);
+ if (len != t->len) {
+ fprintf(stderr, "failed test %d: len %lu != %ld\n", numtest,
+ (long)len, (long)t->len);
+ numerr++;
+ } else if (t->len > -1 && memcmp(str, t->data, t->len) != 0) {
+ fprintf(stderr, "failed test %d: data\n", numtest);
+ numerr++;
+ }
+ free(str);
+ numtest++;
+ }
+
+ {
+ unsigned char buf[2] = { 0, 0xff } ;
+ int len;
+
+ len = hex_decode("A", buf, 1);
+ if (len != 1) {
+ fprintf(stderr, "len != 1");
+ numerr++;
+ }
+ if (buf[0] != 10) {
+ fprintf(stderr, "buf != 10");
+ numerr++;
+ }
+ if (buf[1] != 0xff) {
+ fprintf(stderr, "buf != 0xff");
+ numerr++;
+ }
+
+ }
+
+ return numerr;
+}
diff --git a/third_party/heimdal/lib/roken/hex.c b/third_party/heimdal/lib/roken/hex.c
new file mode 100644
index 0000000..cc47fa4
--- /dev/null
+++ b/third_party/heimdal/lib/roken/hex.c
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2004-2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+
+#include <config.h>
+#include "roken.h"
+#include <ctype.h>
+#include "hex.h"
+
+static const char hexchar[16] = "0123456789ABCDEF";
+
+static inline int
+pos(char c)
+{
+ if (c >= '0' && c <= '9')
+ return c - '0';
+ if (c >= 'A' && c <= 'F')
+ return 10 + c - 'A';
+ if (c >= 'a' && c <= 'f')
+ return 10 + c - 'a';
+ return -1;
+}
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+hex_encode(const void *data, size_t size, char **str)
+{
+ const unsigned char *q = data;
+ size_t i;
+ char *p;
+
+ /* check for overflow */
+ if (size * 2 < size) {
+ *str = NULL;
+ return -1;
+ }
+
+ p = malloc(size * 2 + 1);
+ if (p == NULL) {
+ *str = NULL;
+ return -1;
+ }
+
+ for (i = 0; i < size; i++) {
+ p[i * 2] = hexchar[(*q >> 4) & 0xf];
+ p[i * 2 + 1] = hexchar[*q & 0xf];
+ q++;
+ }
+ p[i * 2] = '\0';
+ *str = p;
+
+ return i * 2;
+}
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+hex_decode(const char *str, void *data, size_t len)
+{
+ size_t l;
+ unsigned char *p = data;
+ size_t i;
+ int d;
+
+ l = strlen(str);
+
+ /* check for overflow, same as (l+1)/2 but overflow safe */
+ if ((l/2) + (l&1) > len)
+ return -1;
+
+ if (l & 1) {
+ if ((d = pos(str[0])) == -1)
+ return -1;
+ p[0] = d;
+ str++;
+ p++;
+ }
+ for (i = 0; i < l / 2; i++) {
+ if ((d = pos(str[i * 2])) == -1)
+ return -1;
+ p[i] = d << 4;
+ if ((d = pos(str[(i * 2) + 1])) == -1)
+ return -1;
+ p[i] |= d;
+ }
+ return i + (l & 1);
+}
diff --git a/third_party/heimdal/lib/roken/hex.h b/third_party/heimdal/lib/roken/hex.h
new file mode 100644
index 0000000..c266268
--- /dev/null
+++ b/third_party/heimdal/lib/roken/hex.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef _rk_HEX_H_
+#define _rk_HEX_H_ 1
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __cdecl
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+#define hex_encode rk_hex_encode
+#define hex_decode rk_hex_decode
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+ hex_encode(const void *, size_t, char **);
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+ hex_decode(const char *, void *, size_t);
+
+#endif /* _rk_HEX_H_ */
diff --git a/third_party/heimdal/lib/roken/hostent_find_fqdn.c b/third_party/heimdal/lib/roken/hostent_find_fqdn.c
new file mode 100644
index 0000000..dc3c17f
--- /dev/null
+++ b/third_party/heimdal/lib/roken/hostent_find_fqdn.c
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/*
+ * Try to find a fqdn (with `.') in he if possible, else return h_name
+ */
+
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
+hostent_find_fqdn (const struct hostent *he)
+{
+ const char *ret = he->h_name;
+ const char **h;
+
+ if (strchr (ret, '.') == NULL)
+ for (h = (const char **)he->h_aliases; *h != NULL; ++h) {
+ if (strchr (*h, '.') != NULL) {
+ ret = *h;
+ break;
+ }
+ }
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/hstrerror.c b/third_party/heimdal/lib/roken/hstrerror.c
new file mode 100644
index 0000000..70b6301
--- /dev/null
+++ b/third_party/heimdal/lib/roken/hstrerror.c
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 1995 - 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifndef HAVE_HSTRERROR
+
+#if (defined(SunOS) && (SunOS >= 50))
+#define hstrerror broken_proto
+#endif
+#include "roken.h"
+#if (defined(SunOS) && (SunOS >= 50))
+#undef hstrerror
+#endif
+
+#if !(defined(HAVE_H_ERRLIST) && defined(HAVE_H_NERR))
+static const char *const h_errlist[] = {
+ "Resolver Error 0 (no error)",
+ "Unknown host", /* 1 HOST_NOT_FOUND */
+ "Host name lookup failure", /* 2 TRY_AGAIN */
+ "Unknown server error", /* 3 NO_RECOVERY */
+ "No address associated with name", /* 4 NO_ADDRESS */
+};
+
+static
+const
+int h_nerr = { sizeof h_errlist / sizeof h_errlist[0] };
+#else
+
+#if !HAVE_DECL_H_ERRLIST
+extern const char *h_errlist[];
+extern int h_nerr;
+#endif
+
+#endif
+
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
+hstrerror(int herr)
+{
+ if (0 <= herr && herr < h_nerr)
+ return h_errlist[herr];
+ else if(herr == -17)
+ return "unknown error";
+ else
+ return "Error number out of range (hstrerror)";
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/ifaddrs.hin b/third_party/heimdal/lib/roken/ifaddrs.hin
new file mode 100644
index 0000000..ef00b63
--- /dev/null
+++ b/third_party/heimdal/lib/roken/ifaddrs.hin
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __ifaddrs_h__
+#define __ifaddrs_h__
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL _stdcall
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+/*
+ * the interface is defined in terms of the fields below, and this is
+ * sometimes #define'd, so there seems to be no simple way of solving
+ * this and this seemed the best. */
+
+#undef ifa_dstaddr
+
+struct ifaddrs {
+ struct ifaddrs *ifa_next;
+ char *ifa_name;
+ unsigned int ifa_flags;
+ struct sockaddr *ifa_addr;
+ struct sockaddr *ifa_netmask;
+ struct sockaddr *ifa_dstaddr;
+ void *ifa_data;
+};
+
+#ifndef ifa_broadaddr
+#define ifa_broadaddr ifa_dstaddr
+#endif
+
+int ROKEN_LIB_FUNCTION
+rk_getifaddrs(struct ifaddrs**);
+
+void ROKEN_LIB_FUNCTION
+rk_freeifaddrs(struct ifaddrs*);
+
+#define getifaddrs(a) rk_getifaddrs(a)
+#define freeifaddrs(a) rk_freeifaddrs(a)
+
+#endif /* __ifaddrs_h__ */
diff --git a/third_party/heimdal/lib/roken/inet_aton.c b/third_party/heimdal/lib/roken/inet_aton.c
new file mode 100644
index 0000000..31644a0
--- /dev/null
+++ b/third_party/heimdal/lib/roken/inet_aton.c
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/* Minimal implementation of inet_aton.
+ * Cannot distinguish between failure and a local broadcast address. */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+inet_aton(const char *cp, struct in_addr *addr)
+{
+ addr->s_addr = inet_addr(cp);
+ return (addr->s_addr == INADDR_NONE) ? 0 : 1;
+}
diff --git a/third_party/heimdal/lib/roken/inet_ntop.c b/third_party/heimdal/lib/roken/inet_ntop.c
new file mode 100644
index 0000000..b3c327c
--- /dev/null
+++ b/third_party/heimdal/lib/roken/inet_ntop.c
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/*
+ *
+ */
+
+static const char *
+inet_ntop_v4 (const void *src, char *dst, size_t size)
+{
+ const char digits[] = "0123456789";
+ int i;
+ struct in_addr *addr = (struct in_addr *)src;
+ u_long a = ntohl(addr->s_addr);
+ const char *orig_dst = dst;
+
+ if (size < INET_ADDRSTRLEN) {
+ errno = ENOSPC;
+ return NULL;
+ }
+ for (i = 0; i < 4; ++i) {
+ int n = (a >> (24 - i * 8)) & 0xFF;
+ int non_zerop = 0;
+
+ if (non_zerop || n / 100 > 0) {
+ *dst++ = digits[n / 100];
+ n %= 100;
+ non_zerop = 1;
+ }
+ if (non_zerop || n / 10 > 0) {
+ *dst++ = digits[n / 10];
+ n %= 10;
+ non_zerop = 1;
+ }
+ *dst++ = digits[n];
+ if (i != 3)
+ *dst++ = '.';
+ }
+ *dst++ = '\0';
+ return orig_dst;
+}
+
+#ifdef HAVE_IPV6
+static const char *
+inet_ntop_v6 (const void *src, char *dst, size_t size)
+{
+ const char xdigits[] = "0123456789abcdef";
+ int i;
+ const struct in6_addr *addr = (struct in6_addr *)src;
+ const u_char *ptr = addr->s6_addr;
+ const char *orig_dst = dst;
+ int compressed = 0;
+
+ if (size < INET6_ADDRSTRLEN) {
+ errno = ENOSPC;
+ return NULL;
+ }
+ for (i = 0; i < 8; ++i) {
+ int non_zerop = 0;
+
+ if (compressed == 0 &&
+ ptr[0] == 0 && ptr[1] == 0 &&
+ i <= 5 &&
+ ptr[2] == 0 && ptr[3] == 0 &&
+ ptr[4] == 0 && ptr[5] == 0) {
+
+ compressed = 1;
+
+ if (i == 0)
+ *dst++ = ':';
+ *dst++ = ':';
+
+ for (ptr += 6, i += 3;
+ i < 8 && ptr[0] == 0 && ptr[1] == 0;
+ ++i, ptr += 2);
+
+ if (i >= 8)
+ break;
+ }
+
+ if (non_zerop || (ptr[0] >> 4)) {
+ *dst++ = xdigits[ptr[0] >> 4];
+ non_zerop = 1;
+ }
+ if (non_zerop || (ptr[0] & 0x0F)) {
+ *dst++ = xdigits[ptr[0] & 0x0F];
+ non_zerop = 1;
+ }
+ if (non_zerop || (ptr[1] >> 4)) {
+ *dst++ = xdigits[ptr[1] >> 4];
+ non_zerop = 1;
+ }
+ *dst++ = xdigits[ptr[1] & 0x0F];
+ if (i != 7)
+ *dst++ = ':';
+ ptr += 2;
+ }
+ *dst++ = '\0';
+ return orig_dst;
+}
+#endif /* HAVE_IPV6 */
+
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
+inet_ntop(int af, const void *src, char *dst, size_t size)
+{
+ switch (af) {
+ case AF_INET :
+ return inet_ntop_v4 (src, dst, size);
+#ifdef HAVE_IPV6
+ case AF_INET6 :
+ return inet_ntop_v6 (src, dst, size);
+#endif
+ default :
+ errno = EAFNOSUPPORT;
+ return NULL;
+ }
+}
diff --git a/third_party/heimdal/lib/roken/inet_pton.c b/third_party/heimdal/lib/roken/inet_pton.c
new file mode 100644
index 0000000..e44fb19
--- /dev/null
+++ b/third_party/heimdal/lib/roken/inet_pton.c
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 1999 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+#ifdef HAVE_WINSOCK
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+inet_pton(int af, const char *csrc, void *dst)
+{
+ char * src;
+
+ if (csrc == NULL || (src = strdup(csrc)) == NULL) {
+ _set_errno( ENOMEM );
+ return 0;
+ }
+
+ switch (af) {
+ case AF_INET:
+ {
+ struct sockaddr_in si4;
+ INT r;
+ INT s = sizeof(si4);
+
+ si4.sin_family = AF_INET;
+ r = WSAStringToAddress(src, AF_INET, NULL, (LPSOCKADDR) &si4, &s);
+ free(src);
+ src = NULL;
+
+ if (r == 0) {
+ memcpy(dst, &si4.sin_addr, sizeof(si4.sin_addr));
+ return 1;
+ }
+ }
+ break;
+
+ case AF_INET6:
+ {
+ struct sockaddr_in6 si6;
+ INT r;
+ INT s = sizeof(si6);
+
+ si6.sin6_family = AF_INET6;
+ r = WSAStringToAddress(src, AF_INET6, NULL, (LPSOCKADDR) &si6, &s);
+ free(src);
+ src = NULL;
+
+ if (r == 0) {
+ memcpy(dst, &si6.sin6_addr, sizeof(si6.sin6_addr));
+ return 1;
+ }
+ }
+ break;
+
+ default:
+ _set_errno( EAFNOSUPPORT );
+ return -1;
+ }
+
+ /* the call failed */
+ {
+ int le = WSAGetLastError();
+
+ if (le == WSAEINVAL)
+ return 0;
+
+ _set_errno(le);
+ return -1;
+ }
+}
+
+#else /* !HAVE_WINSOCK */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+inet_pton(int af, const char *src, void *dst)
+{
+ if (af != AF_INET) {
+ errno = EAFNOSUPPORT;
+ return -1;
+ }
+ return inet_aton (src, dst);
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/initgroups.c b/third_party/heimdal/lib/roken/initgroups.c
new file mode 100644
index 0000000..2ba944c
--- /dev/null
+++ b/third_party/heimdal/lib/roken/initgroups.c
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+initgroups(const char *name, gid_t basegid)
+{
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/innetgr.c b/third_party/heimdal/lib/roken/innetgr.c
new file mode 100644
index 0000000..e1783bb
--- /dev/null
+++ b/third_party/heimdal/lib/roken/innetgr.c
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include <config.h>
+#include "roken.h"
+
+#ifndef HAVE_INNETGR
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+innetgr(const char *netgroup, const char *machine,
+ const char *user, const char *domain)
+{
+ return 0;
+}
+#endif
+
diff --git a/third_party/heimdal/lib/roken/install-sh b/third_party/heimdal/lib/roken/install-sh
new file mode 100644
index 0000000..e9de238
--- /dev/null
+++ b/third_party/heimdal/lib/roken/install-sh
@@ -0,0 +1,251 @@
+#!/bin/sh
+#
+# install - install a program, script, or datafile
+# This comes from X11R5 (mit/util/scripts/install.sh).
+#
+# Copyright 1991 by the Massachusetts Institute of Technology
+#
+# Permission to use, copy, modify, distribute, and sell this software and its
+# documentation for any purpose is hereby granted without fee, provided that
+# the above copyright notice appear in all copies and that both that
+# copyright notice and this permission notice appear in supporting
+# documentation, and that the name of M.I.T. not be used in advertising or
+# publicity pertaining to distribution of the software without specific,
+# written prior permission. M.I.T. makes no representations about the
+# suitability of this software for any purpose. It is provided "as is"
+# without express or implied warranty.
+#
+# Calling this script install-sh is preferred over install.sh, to prevent
+# `make' implicit rules from creating a file called install from it
+# when there is no Makefile.
+#
+# This script is compatible with the BSD install script, but was written
+# from scratch. It can only install one file at a time, a restriction
+# shared with many OS's install programs.
+
+
+# set DOITPROG to echo to test this script
+
+# Don't use :- since 4.3BSD and earlier shells don't like it.
+doit="${DOITPROG-}"
+
+
+# put in absolute paths if you don't have them in your path; or use env. vars.
+
+mvprog="${MVPROG-mv}"
+cpprog="${CPPROG-cp}"
+chmodprog="${CHMODPROG-chmod}"
+chownprog="${CHOWNPROG-chown}"
+chgrpprog="${CHGRPPROG-chgrp}"
+stripprog="${STRIPPROG-strip}"
+rmprog="${RMPROG-rm}"
+mkdirprog="${MKDIRPROG-mkdir}"
+
+transformbasename=""
+transform_arg=""
+instcmd="$mvprog"
+chmodcmd="$chmodprog 0755"
+chowncmd=""
+chgrpcmd=""
+stripcmd=""
+rmcmd="$rmprog -f"
+mvcmd="$mvprog"
+src=""
+dst=""
+dir_arg=""
+
+while [ x"$1" != x ]; do
+ case $1 in
+ -c) instcmd="$cpprog"
+ shift
+ continue;;
+
+ -d) dir_arg=true
+ shift
+ continue;;
+
+ -m) chmodcmd="$chmodprog $2"
+ shift
+ shift
+ continue;;
+
+ -o) chowncmd="$chownprog $2"
+ shift
+ shift
+ continue;;
+
+ -g) chgrpcmd="$chgrpprog $2"
+ shift
+ shift
+ continue;;
+
+ -s) stripcmd="$stripprog"
+ shift
+ continue;;
+
+ -t=*) transformarg=`echo $1 | sed 's/-t=//'`
+ shift
+ continue;;
+
+ -b=*) transformbasename=`echo $1 | sed 's/-b=//'`
+ shift
+ continue;;
+
+ *) if [ x"$src" = x ]
+ then
+ src=$1
+ else
+ # this colon is to work around a 386BSD /bin/sh bug
+ :
+ dst=$1
+ fi
+ shift
+ continue;;
+ esac
+done
+
+if [ x"$src" = x ]
+then
+ echo "install: no input file specified"
+ exit 1
+else
+ true
+fi
+
+if [ x"$dir_arg" != x ]; then
+ dst=$src
+ src=""
+
+ if [ -d $dst ]; then
+ instcmd=:
+ chmodcmd=""
+ else
+ instcmd=mkdir
+ fi
+else
+
+# Waiting for this to be detected by the "$instcmd $src $dsttmp" command
+# might cause directories to be created, which would be especially bad
+# if $src (and thus $dsttmp) contains '*'.
+
+ if [ -f $src -o -d $src ]
+ then
+ true
+ else
+ echo "install: $src does not exist"
+ exit 1
+ fi
+
+ if [ x"$dst" = x ]
+ then
+ echo "install: no destination specified"
+ exit 1
+ else
+ true
+ fi
+
+# If destination is a directory, append the input filename; if your system
+# does not like double slashes in filenames, you may need to add some logic
+
+ if [ -d $dst ]
+ then
+ dst="$dst"/`basename $src`
+ else
+ true
+ fi
+fi
+
+## this sed command emulates the dirname command
+dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
+
+# Make sure that the destination directory exists.
+# this part is taken from Noah Friedman's mkinstalldirs script
+
+# Skip lots of stat calls in the usual case.
+if [ ! -d "$dstdir" ]; then
+defaultIFS='
+'
+IFS="${IFS-${defaultIFS}}"
+
+oIFS="${IFS}"
+# Some sh's can't handle IFS=/ for some reason.
+IFS='%'
+set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'`
+IFS="${oIFS}"
+
+pathcomp=''
+
+while [ $# -ne 0 ] ; do
+ pathcomp="${pathcomp}${1}"
+ shift
+
+ if [ ! -d "${pathcomp}" ] ;
+ then
+ $mkdirprog "${pathcomp}"
+ else
+ true
+ fi
+
+ pathcomp="${pathcomp}/"
+done
+fi
+
+if [ x"$dir_arg" != x ]
+then
+ $doit $instcmd $dst &&
+
+ if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi &&
+ if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi &&
+ if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi &&
+ if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi
+else
+
+# If we're going to rename the final executable, determine the name now.
+
+ if [ x"$transformarg" = x ]
+ then
+ dstfile=`basename $dst`
+ else
+ dstfile=`basename $dst $transformbasename |
+ sed $transformarg`$transformbasename
+ fi
+
+# don't allow the sed command to completely eliminate the filename
+
+ if [ x"$dstfile" = x ]
+ then
+ dstfile=`basename $dst`
+ else
+ true
+ fi
+
+# Make a temp file name in the proper directory.
+
+ dsttmp=$dstdir/#inst.$$#
+
+# Move or copy the file name to the temp name
+
+ $doit $instcmd $src $dsttmp &&
+
+ trap "rm -f ${dsttmp}" 0 &&
+
+# and set any options; do chmod last to preserve setuid bits
+
+# If any of these fail, we abort the whole thing. If we want to
+# ignore errors from any of these, just make sure not to ignore
+# errors from the above "$doit $instcmd $src $dsttmp" command.
+
+ if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi &&
+ if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi &&
+ if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi &&
+ if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi &&
+
+# Now rename the file to the real destination.
+
+ $doit $rmcmd -f $dstdir/$dstfile &&
+ $doit $mvcmd $dsttmp $dstdir/$dstfile
+
+fi &&
+
+
+exit 0
diff --git a/third_party/heimdal/lib/roken/issuid.c b/third_party/heimdal/lib/roken/issuid.c
new file mode 100644
index 0000000..0c503a0
--- /dev/null
+++ b/third_party/heimdal/lib/roken/issuid.c
@@ -0,0 +1,276 @@
+/*
+ * Copyright (c) 1998 - 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifdef HAVE_SYS_AUXV_H
+#include <sys/auxv.h>
+#endif
+
+#include <errno.h>
+
+#include "roken.h"
+#include "getauxval.h"
+
+extern int rk_injected_auxv;
+
+/**
+ * Returns non-zero if the caller's process started as set-uid or
+ * set-gid (and therefore the environment cannot be trusted).
+ *
+ * As much as possible this implements the same functionality and
+ * semantics as OpenBSD's issetugid() (as opposed to FreeBSD's).
+ *
+ * Preserves errno.
+ *
+ * @return Non-zero if the environment is not trusted.
+ */
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+issuid(void)
+{
+#ifdef WIN32
+ return 0; /* No set-id programs or anything like it on Windows */
+#else
+ /*
+ * We want to use issetugid(), but issetugid() is not the same on
+ * all OSes.
+ *
+ * On OpenBSD (where issetugid() originated), Illumos derivatives,
+ * and Solaris, issetugid() returns true IFF the program exec()ed
+ * was set-uid or set-gid.
+ *
+ * FreeBSD departed from OpenBSD's issetugid() semantics, and other
+ * BSDs (NetBSD, DragonFly) and OS X adopted FreeBSD's.
+ *
+ * FreeBSDs' issetugid() returns true if the program exec()ed was
+ * set-uid or set-gid, or if the process has switched UIDs/GIDs or
+ * otherwise changed privileges or is a descendant of such a process
+ * and has not exec()ed since.
+ *
+ * The FreeBSD/NetBSD issetugid() does us no good because we _want_
+ * to trust the environment when the process started life as
+ * non-set-uid root (or otherwise privileged). There's nothing
+ * about _dropping_ privileges (without having gained them first)
+ * that taints the environment. It's not like calling system(),
+ * say, might change the environment of the caller.
+ *
+ * We want OpenBSD's issetugid() semantics.
+ *
+ * Linux, meanwhile, has no issetugid() (at least glibc doesn't
+ * anyways) but has an equivalent: getauxval(AT_SECURE).
+ *
+ * To be really specific: we want getauxval(AT_SECURE) semantics
+ * because there may be ways in which a process might gain privilege
+ * at exec time other than by exec'ing a set-id program.
+ *
+ * Where we use getauxval(), we really use our getauxval(), the one
+ * that isn't broken the way glibc's used to be. Our getauxval()
+ * also works on more systems than actually provide one.
+ *
+ * In order to avoid FreeBSD issetugid() semantics, where available,
+ * we use the ELF auxilliary vector to implement OpenBSD semantics
+ * before finally falling back on issetugid().
+ *
+ * All of this is as of April 2017, and might become stale in the
+ * future.
+ */
+ static int we_are_suid = -1; /* Memoize; -1 == dunno */
+ int save_errno = errno;
+#if defined(AT_EUID) && defined(AT_UID) && defined(AT_EGID) && defined(AT_GID)
+ int seen = 0;
+#endif
+
+ if (we_are_suid >= 0 && !rk_injected_auxv)
+ return we_are_suid;
+
+#ifdef AT_SECURE
+ errno = 0;
+ if (rk_getauxval(AT_SECURE) != 0) {
+ errno = save_errno;
+ return we_are_suid = 1;
+ } else if (errno == 0) {
+ errno = save_errno;
+ return we_are_suid = 0;
+ }
+ /* errno == ENOENT; AT_SECURE not found; fall through */
+#endif
+
+#if defined(AT_EUID) && defined(AT_UID) && defined(AT_EGID) && defined(AT_GID)
+ {
+ unsigned long euid;
+ unsigned long uid;
+
+ errno = 0;
+ euid = rk_getauxval(AT_EUID);
+ if (errno == 0)
+ seen |= 1;
+ errno = 0;
+ uid = rk_getauxval(AT_UID);
+ if (errno == 0)
+ seen |= 2;
+ if (euid != uid) {
+ errno = save_errno;
+ return we_are_suid = 1;
+ }
+ }
+ /* Check GIDs */
+ {
+ unsigned long egid;
+ unsigned long gid;
+
+ errno = 0;
+ egid = rk_getauxval(AT_EGID);
+ if (errno == 0)
+ seen |= 4;
+ errno = 0;
+ gid = rk_getauxval(AT_GID);
+ if (errno == 0)
+ seen |= 8;
+ if (egid != gid) {
+ errno = save_errno;
+ return we_are_suid = 1;
+ }
+ }
+ errno = save_errno;
+ if (seen == 15)
+ return we_are_suid = 0;
+#endif
+
+#if defined(HAVE_ISSETUGID)
+ /* If issetugid() == 0 then we're definitely OK then */
+ if (issetugid() == 0)
+ return we_are_suid = 0;
+ /* issetugid() == 1 might have been a false positive; fall through */
+#endif /* USE_RK_GETAUXVAL */
+
+#ifdef AT_EXECFN
+ /*
+ * There's an auxval by which to find the path of the program this
+ * process exec'ed.
+ *
+ * We can stat() it. If the program did a chroot() and the chroot
+ * has a program with the same path but not set-uid/set-gid, of
+ * course, we lose here. But a) that's a bit of a stretch, b)
+ * there's not much more we can do here.
+ *
+ * Also, this is technically a TOCTOU race, though for set-id
+ * programs this is exceedingly unlikely to be an actual TOCTOU
+ * race.
+ */
+ {
+ unsigned long p = rk_getauxval(AT_EXECPATH);
+ struct stat st;
+
+ if (p != 0 && *(const char *)p == '/' &&
+ stat((const char *)p, &st) == 0) {
+ if ((st.st_mode & S_ISUID) || (st.st_mode & S_ISGID)) {
+ errno = save_errno;
+ return we_are_suid = 1;
+ }
+ errno = save_errno;
+ return we_are_suid = 0;
+ }
+ }
+ /* Fall through */
+#endif
+
+#if defined(HAVE_ISSETUGID)
+ errno = save_errno;
+ return we_are_suid = 1;
+#else
+ /*
+ * Paranoia: for extra safety we ought to default to returning 1.
+ *
+ * But who knows what that might break where users link statically
+ * (so no auxv), say.
+ *
+ * We'll check the actual real and effective IDs (as opposed to the
+ * ones at main() start time.
+ *
+ * For now we stick to returning zero by default. We've been rather
+ * heroic above trying to find out if we're suid, and we're running
+ * on a rather old or uncool OS if we've gotten here.
+ */
+
+#if defined(HAVE_GETRESUID)
+ /*
+ * If r/e/suid are all the same then chances are very good we did
+ * not start as set-uid. Though this could be a login program that
+ * started out as privileged and is calling Heimdal "as the user".
+ *
+ * Again, such a program would have to be statically linked to get
+ * here.
+ */
+ {
+ uid_t r, e, s;
+ if (getresuid(&r, &e, &s) == 0) {
+ if (r != e || r != s) {
+ errno = save_errno;
+ return we_are_suid = 1;
+ }
+ }
+ }
+#endif
+#if defined(HAVE_GETRESGID)
+ {
+ gid_t r, e, s;
+ if (getresgid(&r, &e, &s) == 0) {
+ if (r != e || r != s) {
+ errno = save_errno;
+ return we_are_suid = 1;
+ }
+ }
+ }
+#endif
+#if defined(HAVE_GETRESUID) && defined(HAVE_GETRESGID)
+ errno = save_errno;
+ return we_are_suid = 0;
+
+#else /* avoid compiler warnings about dead code */
+
+#if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
+ if (getuid() != geteuid())
+ return we_are_suid = 1;
+#endif
+#if defined(HAVE_GETGID) && defined(HAVE_GETEGID)
+ if (getgid() != getegid())
+ return we_are_suid = 1;
+#endif
+
+#endif /* !defined(HAVE_GETRESUID) || !defined(HAVE_GETRESGID) */
+
+ errno = save_errno;
+ return we_are_suid = 0;
+#endif /* !defined(HAVE_ISSETUGID) */
+#endif /* WIN32 */
+}
diff --git a/third_party/heimdal/lib/roken/localtime_r.c b/third_party/heimdal/lib/roken/localtime_r.c
new file mode 100644
index 0000000..fa3d126
--- /dev/null
+++ b/third_party/heimdal/lib/roken/localtime_r.c
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdio.h>
+#include <time.h>
+#include "roken.h"
+
+#ifndef HAVE_LOCALTIME_R
+
+ROKEN_LIB_FUNCTION struct tm * ROKEN_LIB_CALL
+localtime_r(const time_t *timer, struct tm *result)
+{
+#ifdef _MSC_VER
+
+ return (localtime_s(result, timer) == 0)? result : NULL;
+
+#else
+ struct tm *tm;
+
+ tm = localtime((time_t *)timer);
+ if (tm == NULL)
+ return NULL;
+ *result = *tm;
+ return result;
+#endif
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/lstat.c b/third_party/heimdal/lib/roken/lstat.c
new file mode 100644
index 0000000..4692588
--- /dev/null
+++ b/third_party/heimdal/lib/roken/lstat.c
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+lstat(const char *path, struct stat *buf)
+{
+ return stat(path, buf);
+}
diff --git a/third_party/heimdal/lib/roken/memmem.c b/third_party/heimdal/lib/roken/memmem.c
new file mode 100644
index 0000000..3f9c6bc
--- /dev/null
+++ b/third_party/heimdal/lib/roken/memmem.c
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifndef HAVE_MEMMEM
+#include "roken.h"
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+memmem(const void *haystack,
+ size_t haystacklen,
+ const void *needle,
+ size_t needlelen)
+{
+ const unsigned char *hs = haystack;
+ const unsigned char *n = needle;
+ size_t hsi, ni;
+
+ if (haystacklen < needlelen || haystacklen == 0)
+ return NULL;
+ /*
+ * Imagine a haystack of length 5 and needle of length 2, then the largest
+ * index in the haystack at which we can bother looking for the needle is:
+ *
+ * 0 1 2 3 4
+ * +---------+
+ * |?|?|?|?|?|
+ * +---------+
+ * ^
+ * \
+ * here, at index 3, which is 5 - 2, and less than (5 - 2 + 1).
+ */
+ for (hsi = 0, ni = 0; hsi < (haystacklen - needlelen + 1); hsi++, ni = 0) {
+ while (ni < needlelen && n[ni] == hs[hsi + ni])
+ ni++;
+ if (ni == needlelen)
+ return rk_UNCONST(&hs[hsi]);
+ }
+ return NULL;
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/memmove.c b/third_party/heimdal/lib/roken/memmove.c
new file mode 100644
index 0000000..1825d7e
--- /dev/null
+++ b/third_party/heimdal/lib/roken/memmove.c
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+/*
+ * memmove for systems that doesn't have it
+ */
+
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+ROKEN_LIB_FUNCTION void* ROKEN_LIB_CALL
+memmove(void *s1, const void *s2, size_t n)
+{
+ char *s=(char*)s2, *d=(char*)s1;
+
+ if(d > s){
+ s+=n-1;
+ d+=n-1;
+ while(n){
+ *d--=*s--;
+ n--;
+ }
+ }else if(d < s)
+ while(n){
+ *d++=*s++;
+ n--;
+ }
+ return s1;
+}
diff --git a/third_party/heimdal/lib/roken/memset_s.c b/third_party/heimdal/lib/roken/memset_s.c
new file mode 100644
index 0000000..207fe19
--- /dev/null
+++ b/third_party/heimdal/lib/roken/memset_s.c
@@ -0,0 +1,51 @@
+/***********************************************************************
+ * Copyright (c) 2015, Your File System Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include <config.h>
+#include "roken.h"
+
+int ROKEN_LIB_FUNCTION
+memset_s(void *s, size_t smax, int c, size_t n)
+{
+ volatile unsigned char *p = s;
+
+#ifdef _WIN32
+ if (c == 0) {
+ SecureZeroMemory(s, n);
+ return 0;
+ }
+#endif
+
+ while (n--)
+ *p++ = c;
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/mergesort.c b/third_party/heimdal/lib/roken/mergesort.c
new file mode 100644
index 0000000..ba51889
--- /dev/null
+++ b/third_party/heimdal/lib/roken/mergesort.c
@@ -0,0 +1,50 @@
+/***********************************************************************
+ * Copyright (c) 2020, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include <config.h>
+#include "roken.h"
+
+static int
+mergesort_compar_thunk(const void *a, const void *b, void *thunk)
+{
+ int (*compar)(const void *, const void *) = thunk;
+
+ return compar(a, b);
+}
+
+int ROKEN_LIB_FUNCTION
+mergesort(void *base, size_t nel, size_t width,
+ int (*compar)(const void *, const void *))
+{
+ return rk_mergesort_r(base, nel, width,
+ mergesort_compar_thunk, compar);
+}
+
diff --git a/third_party/heimdal/lib/roken/mergesort_r.c b/third_party/heimdal/lib/roken/mergesort_r.c
new file mode 100644
index 0000000..39b0301
--- /dev/null
+++ b/third_party/heimdal/lib/roken/mergesort_r.c
@@ -0,0 +1,339 @@
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Peter McIlroy.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include "roken.h"
+
+/*
+ * Hybrid exponential search/linear search merge sort with hybrid
+ * natural/pairwise first pass. Requires about .3% more comparisons
+ * for random data than LSMS with pairwise first pass alone.
+ * It works for objects as small as two bytes.
+ */
+
+#define NATURAL
+#define THRESHOLD 16 /* Best choice for natural merge cut-off. */
+
+/* #define NATURAL to get hybrid natural merge.
+ * (The default is pairwise merging.)
+ */
+
+#include <sys/types.h>
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+typedef int (*cmp_t)(const void *, const void *, void *);
+
+static void setup(u_char *, u_char *, size_t, size_t, cmp_t, void *);
+static void insertionsort(u_char *, size_t, size_t, cmp_t, void *);
+
+#define ISIZE sizeof(int)
+#define PSIZE sizeof(u_char *)
+#define ICOPY_LIST(src, dst, last) \
+ do \
+ *(int*)dst = *(int*)src, src += ISIZE, dst += ISIZE; \
+ while(src < last)
+#define ICOPY_ELT(src, dst, i) \
+ do \
+ *(int*) dst = *(int*) src, src += ISIZE, dst += ISIZE; \
+ while (i -= ISIZE)
+
+#define CCOPY_LIST(src, dst, last) \
+ do \
+ *dst++ = *src++; \
+ while (src < last)
+#define CCOPY_ELT(src, dst, i) \
+ do \
+ *dst++ = *src++; \
+ while (i -= 1)
+
+/*
+ * Find the next possible pointer head. (Trickery for forcing an array
+ * to do double duty as a linked list when objects do not align with word
+ * boundaries.
+ */
+/* Assumption: PSIZE is a power of 2. */
+#define EVAL(p) (u_char **) \
+ ((((uintptr_t)p + PSIZE - 1) & ~(PSIZE - 1)))
+
+/*
+ * Arguments are as for qsort_r, except thunk is moved to the last
+ * parameter for glibc compatibility. See:
+ * https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=214248
+ */
+int
+mergesort_r(void *base, size_t nmemb, size_t size, cmp_t cmp, void *thunk)
+{
+ size_t i;
+ int sense;
+ int big, iflag;
+ u_char *f1, *f2, *t, *b, *tp2, *q, *l1, *l2;
+ u_char *list2, *list1, *p2, *p, *last, **p1;
+
+ if (size < PSIZE / 2) { /* Pointers must fit into 2 * size. */
+ errno = EINVAL;
+ return (-1);
+ }
+
+ if (nmemb == 0)
+ return (0);
+
+ /*
+ * XXX
+ * Stupid subtraction for the Cray.
+ */
+ iflag = 0;
+ if (!(size % ISIZE) && !(((uintptr_t)base) % ISIZE))
+ iflag = 1;
+
+ if ((list2 = malloc(nmemb * size + PSIZE)) == NULL)
+ return (-1);
+
+ list1 = base;
+ setup(list1, list2, nmemb, size, cmp, thunk);
+ last = list2 + nmemb * size;
+ i = big = 0;
+ while (*EVAL(list2) != last) {
+ l2 = list1;
+ p1 = EVAL(list1);
+ for (tp2 = p2 = list2; p2 != last; p1 = EVAL(l2)) {
+ p2 = *EVAL(p2);
+ f1 = l2;
+ f2 = l1 = list1 + (p2 - list2);
+ if (p2 != last)
+ p2 = *EVAL(p2);
+ l2 = list1 + (p2 - list2);
+ while (f1 < l1 && f2 < l2) {
+ if (cmp(f1, f2, thunk) <= 0) {
+ q = f2;
+ b = f1, t = l1;
+ sense = -1;
+ } else {
+ q = f1;
+ b = f2, t = l2;
+ sense = 0;
+ }
+ if (!big) { /* here i = 0 */
+ while ((b += size) < t && cmp(q, b, thunk) >sense)
+ if (++i == 6) {
+ big = 1;
+ goto EXPONENTIAL;
+ }
+ } else {
+EXPONENTIAL: for (i = size; ; i <<= 1)
+ if ((p = (b + i)) >= t) {
+ if ((p = t - size) > b &&
+ cmp(q, p, thunk) <= sense)
+ t = p;
+ else
+ b = p;
+ break;
+ } else if (cmp(q, p, thunk) <= sense) {
+ t = p;
+ if (i == size)
+ big = 0;
+ goto FASTCASE;
+ } else
+ b = p;
+ while (t > b+size) {
+ i = (((t - b) / size) >> 1) * size;
+ if (cmp(q, p = b + i, thunk) <= sense)
+ t = p;
+ else
+ b = p;
+ }
+ goto COPY;
+FASTCASE: while (i > size)
+ if (cmp(q,
+ p = b + (i >>= 1), thunk) <= sense)
+ t = p;
+ else
+ b = p;
+COPY: b = t;
+ }
+ i = size;
+ if (q == f1) {
+ if (iflag) {
+ ICOPY_LIST(f2, tp2, b);
+ ICOPY_ELT(f1, tp2, i);
+ } else {
+ CCOPY_LIST(f2, tp2, b);
+ CCOPY_ELT(f1, tp2, i);
+ }
+ } else {
+ if (iflag) {
+ ICOPY_LIST(f1, tp2, b);
+ ICOPY_ELT(f2, tp2, i);
+ } else {
+ CCOPY_LIST(f1, tp2, b);
+ CCOPY_ELT(f2, tp2, i);
+ }
+ }
+ }
+ if (f2 < l2) {
+ if (iflag)
+ ICOPY_LIST(f2, tp2, l2);
+ else
+ CCOPY_LIST(f2, tp2, l2);
+ } else if (f1 < l1) {
+ if (iflag)
+ ICOPY_LIST(f1, tp2, l1);
+ else
+ CCOPY_LIST(f1, tp2, l1);
+ }
+ *p1 = l2;
+ }
+ tp2 = list1; /* swap list1, list2 */
+ list1 = list2;
+ list2 = tp2;
+ last = list2 + nmemb*size;
+ }
+ if (base == list2) {
+ memmove(list2, list1, nmemb*size);
+ list2 = list1;
+ }
+ free(list2);
+ return (0);
+}
+
+#define swap(a, b) { \
+ s = b; \
+ i = size; \
+ do { \
+ tmp = *a; *a++ = *s; *s++ = tmp; \
+ } while (--i); \
+ a -= size; \
+ }
+#define reverse(bot, top) { \
+ s = top; \
+ do { \
+ i = size; \
+ do { \
+ tmp = *bot; *bot++ = *s; *s++ = tmp; \
+ } while (--i); \
+ s -= size2; \
+ } while(bot < s); \
+}
+
+/*
+ * Optional hybrid natural/pairwise first pass. Eats up list1 in runs of
+ * increasing order, list2 in a corresponding linked list. Checks for runs
+ * when THRESHOLD/2 pairs compare with same sense. (Only used when NATURAL
+ * is defined. Otherwise simple pairwise merging is used.)
+ */
+void
+setup(u_char *list1, u_char *list2, size_t n, size_t size, cmp_t cmp, void *thunk)
+{
+ int i, length, size2, tmp, sense;
+ u_char *f1, *f2, *s, *l2, *last, *p2;
+
+ size2 = size*2;
+ if (n <= 5) {
+ insertionsort(list1, n, size, cmp, thunk);
+ *EVAL(list2) = (u_char*) list2 + n*size;
+ return;
+ }
+ /*
+ * Avoid running pointers out of bounds; limit n to evens
+ * for simplicity.
+ */
+ i = 4 + (n & 1);
+ insertionsort(list1 + (n - i) * size, i, size, cmp, thunk);
+ last = list1 + size * (n - i);
+ *EVAL(list2 + (last - list1)) = list2 + n * size;
+
+#ifdef NATURAL
+ p2 = list2;
+ f1 = list1;
+ sense = (cmp(f1, f1 + size, thunk) > 0);
+ for (; f1 < last; sense = !sense) {
+ length = 2;
+ /* Find pairs with same sense. */
+ for (f2 = f1 + size2; f2 < last; f2 += size2) {
+ if ((cmp(f2, f2+ size, thunk) > 0) != sense)
+ break;
+ length += 2;
+ }
+ if (length < THRESHOLD) { /* Pairwise merge */
+ do {
+ p2 = *EVAL(p2) = f1 + size2 - list1 + list2;
+ if (sense > 0)
+ swap (f1, f1 + size);
+ } while ((f1 += size2) < f2);
+ } else { /* Natural merge */
+ l2 = f2;
+ for (f2 = f1 + size2; f2 < l2; f2 += size2) {
+ if ((cmp(f2-size, f2, thunk) > 0) != sense) {
+ p2 = *EVAL(p2) = f2 - list1 + list2;
+ if (sense > 0)
+ reverse(f1, f2-size);
+ f1 = f2;
+ }
+ }
+ if (sense > 0)
+ reverse (f1, f2-size);
+ f1 = f2;
+ if (f2 < last || cmp(f2 - size, f2, thunk) > 0)
+ p2 = *EVAL(p2) = f2 - list1 + list2;
+ else
+ p2 = *EVAL(p2) = list2 + n*size;
+ }
+ }
+#else /* pairwise merge only. */
+ for (f1 = list1, p2 = list2; f1 < last; f1 += size2) {
+ p2 = *EVAL(p2) = p2 + size2;
+ if (cmp (f1, f1 + size) > 0)
+ swap(f1, f1 + size);
+ }
+#endif /* NATURAL */
+}
+
+/*
+ * This is to avoid out-of-bounds addresses in sorting the
+ * last 4 elements.
+ */
+static void
+insertionsort(u_char *a, size_t n, size_t size, cmp_t cmp, void *thunk)
+{
+ u_char *ai, *s, *t, *u, tmp;
+ int i;
+
+ for (ai = a+size; --n >= 1; ai += size)
+ for (t = ai; t > a; t -= size) {
+ u = t - size;
+ if (cmp(u, t, thunk) <= 0)
+ break;
+ swap(u, t);
+ }
+}
diff --git a/third_party/heimdal/lib/roken/mini_inetd.c b/third_party/heimdal/lib/roken/mini_inetd.c
new file mode 100644
index 0000000..a9398f4
--- /dev/null
+++ b/third_party/heimdal/lib/roken/mini_inetd.c
@@ -0,0 +1,197 @@
+/*
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <err.h>
+#include "roken.h"
+
+/*
+ * accept a connection on `s' and pretend it's served by inetd.
+ */
+
+static void
+accept_it (rk_socket_t s, rk_socket_t *ret_socket)
+{
+ rk_socket_t as;
+
+ as = accept(s, NULL, NULL);
+ if(rk_IS_BAD_SOCKET(as))
+ err (1, "accept");
+
+ if (ret_socket) {
+
+ *ret_socket = as;
+
+ } else {
+ int fd = socket_to_fd(as, 0);
+
+ /* We would use _O_RDONLY for the socket_to_fd() call for
+ STDIN, but there are instances where we assume that STDIN
+ is a r/w socket. */
+
+ dup2(fd, STDIN_FILENO);
+ dup2(fd, STDOUT_FILENO);
+
+ rk_closesocket(as);
+ }
+}
+
+/**
+ * Listen on a specified addresses
+ *
+ * Listens on the specified addresses for incoming connections. If
+ * the \a ret_socket parameter is \a NULL, on return STDIN and STDOUT
+ * will be connected to an accepted socket. If the \a ret_socket
+ * parameter is non-NULL, the accepted socket will be returned in
+ * *ret_socket. In the latter case, STDIN and STDOUT will be left
+ * unmodified.
+ *
+ * This function does not return if there is an error or if no
+ * connection is established.
+ *
+ * @param[in] ai Addresses to listen on
+ * @param[out] ret_socket If non-NULL receives the accepted socket.
+ *
+ * @see mini_inetd()
+ */
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+mini_inetd_addrinfo (struct addrinfo *ai, rk_socket_t *ret_socket)
+{
+ int ret;
+ struct addrinfo *a;
+ int n, nalloc, i;
+ rk_socket_t *fds;
+ fd_set orig_read_set, read_set;
+ rk_socket_t max_fd = (rk_socket_t)-1;
+
+ for (nalloc = 0, a = ai; a != NULL; a = a->ai_next)
+ ++nalloc;
+
+ fds = malloc (nalloc * sizeof(*fds));
+ if (fds == NULL) {
+ errx (1, "mini_inetd: out of memory");
+ UNREACHABLE(return);
+ }
+
+ FD_ZERO(&orig_read_set);
+
+ for (i = 0, a = ai; a != NULL; a = a->ai_next) {
+ fds[i] = socket (a->ai_family, a->ai_socktype, a->ai_protocol);
+ if (rk_IS_BAD_SOCKET(fds[i]))
+ continue;
+ socket_set_reuseaddr (fds[i], 1);
+ socket_set_ipv6only(fds[i], 1);
+ if (rk_IS_SOCKET_ERROR(bind (fds[i], a->ai_addr, a->ai_addrlen))) {
+ warn ("bind af = %d", a->ai_family);
+ rk_closesocket(fds[i]);
+ fds[i] = rk_INVALID_SOCKET;
+ continue;
+ }
+ if (rk_IS_SOCKET_ERROR(listen (fds[i], SOMAXCONN))) {
+ warn ("listen af = %d", a->ai_family);
+ rk_closesocket(fds[i]);
+ fds[i] = rk_INVALID_SOCKET;
+ continue;
+ }
+#ifndef NO_LIMIT_FD_SETSIZE
+ if (fds[i] >= FD_SETSIZE)
+ errx (1, "fd too large");
+#endif
+ FD_SET(fds[i], &orig_read_set);
+ max_fd = max(max_fd, fds[i]);
+ ++i;
+ }
+ if (i == 0)
+ errx (1, "no sockets");
+ n = i;
+
+ do {
+ read_set = orig_read_set;
+
+ ret = select (max_fd + 1, &read_set, NULL, NULL, NULL);
+ if (rk_IS_SOCKET_ERROR(ret) && rk_SOCK_ERRNO != EINTR)
+ err (1, "select");
+ } while (ret <= 0);
+
+ for (i = 0; i < n; ++i)
+ if (FD_ISSET (fds[i], &read_set)) {
+ accept_it (fds[i], ret_socket);
+ for (i = 0; i < n; ++i)
+ rk_closesocket(fds[i]);
+ free(fds);
+ return;
+ }
+ abort ();
+}
+
+/**
+ * Listen on a specified port
+ *
+ * Listens on the specified port for incoming connections. If the \a
+ * ret_socket parameter is \a NULL, on return STDIN and STDOUT will be
+ * connected to an accepted socket. If the \a ret_socket parameter is
+ * non-NULL, the accepted socket will be returned in *ret_socket. In
+ * the latter case, STDIN and STDOUT will be left unmodified.
+ *
+ * This function does not return if there is an error or if no
+ * connection is established.
+ *
+ * @param[in] port Port to listen on
+ * @param[out] ret_socket If non-NULL receives the accepted socket.
+ *
+ * @see mini_inetd_addrinfo()
+ */
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+mini_inetd(int port, rk_socket_t * ret_socket)
+{
+ int error;
+ struct addrinfo *ai, hints;
+ char portstr[NI_MAXSERV];
+
+ memset (&hints, 0, sizeof(hints));
+ hints.ai_flags = AI_PASSIVE;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_family = PF_UNSPEC;
+
+ snprintf (portstr, sizeof(portstr), "%d", ntohs(port));
+
+ error = getaddrinfo (NULL, portstr, &hints, &ai);
+ if (error)
+ errx (1, "getaddrinfo: %s", gai_strerror (error));
+
+ mini_inetd_addrinfo(ai, ret_socket);
+
+ freeaddrinfo(ai);
+}
+
diff --git a/third_party/heimdal/lib/roken/missing b/third_party/heimdal/lib/roken/missing
new file mode 100644
index 0000000..7789652
--- /dev/null
+++ b/third_party/heimdal/lib/roken/missing
@@ -0,0 +1,190 @@
+#! /bin/sh
+# Common stub for a few missing GNU programs while installing.
+# Copyright (C) 1996, 1997 Free Software Foundation, Inc.
+# Franc,ois Pinard <pinard@iro.umontreal.ca>, 1996.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2, or (at your option)
+# any later version.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+# 02111-1307, USA.
+
+if test $# -eq 0; then
+ echo 1>&2 "Try \`$0 --help' for more information"
+ exit 1
+fi
+
+case "$1" in
+
+ -h|--h|--he|--hel|--help)
+ echo "\
+$0 [OPTION]... PROGRAM [ARGUMENT]...
+
+Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an
+error status if there is no known handling for PROGRAM.
+
+Options:
+ -h, --help display this help and exit
+ -v, --version output version information and exit
+
+Supported PROGRAM values:
+ aclocal touch file \`aclocal.m4'
+ autoconf touch file \`configure'
+ autoheader touch file \`config.h.in'
+ automake touch all \`Makefile.in' files
+ bison create \`y.tab.[ch]', if possible, from existing .[ch]
+ flex create \`lex.yy.c', if possible, from existing .c
+ lex create \`lex.yy.c', if possible, from existing .c
+ makeinfo touch the output file
+ yacc create \`y.tab.[ch]', if possible, from existing .[ch]"
+ ;;
+
+ -v|--v|--ve|--ver|--vers|--versi|--versio|--version)
+ echo "missing - GNU libit 0.0"
+ ;;
+
+ -*)
+ echo 1>&2 "$0: Unknown \`$1' option"
+ echo 1>&2 "Try \`$0 --help' for more information"
+ exit 1
+ ;;
+
+ aclocal)
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified \`acinclude.m4' or \`configure.in'. You might want
+ to install the \`Automake' and \`Perl' packages. Grab them from
+ any GNU archive site."
+ touch aclocal.m4
+ ;;
+
+ autoconf)
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified \`configure.in'. You might want to install the
+ \`Autoconf' and \`GNU m4' packages. Grab them from any GNU
+ archive site."
+ touch configure
+ ;;
+
+ autoheader)
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified \`acconfig.h' or \`configure.in'. You might want
+ to install the \`Autoconf' and \`GNU m4' packages. Grab them
+ from any GNU archive site."
+ files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' configure.in`
+ test -z "$files" && files="config.h"
+ touch_files=
+ for f in $files; do
+ case "$f" in
+ *:*) touch_files="$touch_files "`echo "$f" |
+ sed -e 's/^[^:]*://' -e 's/:.*//'`;;
+ *) touch_files="$touch_files $f.in";;
+ esac
+ done
+ touch $touch_files
+ ;;
+
+ automake)
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified \`Makefile.am', \`acinclude.m4' or \`configure.in'.
+ You might want to install the \`Automake' and \`Perl' packages.
+ Grab them from any GNU archive site."
+ find . -type f -name Makefile.am -print |
+ sed 's/\.am$/.in/' |
+ while read f; do touch "$f"; done
+ ;;
+
+ bison|yacc)
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified a \`.y' file. You may need the \`Bison' package
+ in order for those modifications to take effect. You can get
+ \`Bison' from any GNU archive site."
+ rm -f y.tab.c y.tab.h
+ if [ $# -ne 1 ]; then
+ eval LASTARG="\${$#}"
+ case "$LASTARG" in
+ *.y)
+ SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'`
+ if [ -f "$SRCFILE" ]; then
+ cp "$SRCFILE" y.tab.c
+ fi
+ SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'`
+ if [ -f "$SRCFILE" ]; then
+ cp "$SRCFILE" y.tab.h
+ fi
+ ;;
+ esac
+ fi
+ if [ ! -f y.tab.h ]; then
+ echo >y.tab.h
+ fi
+ if [ ! -f y.tab.c ]; then
+ echo 'main() { return 0; }' >y.tab.c
+ fi
+ ;;
+
+ lex|flex)
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified a \`.l' file. You may need the \`Flex' package
+ in order for those modifications to take effect. You can get
+ \`Flex' from any GNU archive site."
+ rm -f lex.yy.c
+ if [ $# -ne 1 ]; then
+ eval LASTARG="\${$#}"
+ case "$LASTARG" in
+ *.l)
+ SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'`
+ if [ -f "$SRCFILE" ]; then
+ cp "$SRCFILE" lex.yy.c
+ fi
+ ;;
+ esac
+ fi
+ if [ ! -f lex.yy.c ]; then
+ echo 'main() { return 0; }' >lex.yy.c
+ fi
+ ;;
+
+ makeinfo)
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified a \`.texi' or \`.texinfo' file, or any other file
+ indirectly affecting the aspect of the manual. The spurious
+ call might also be the consequence of using a buggy \`make' (AIX,
+ DU, IRIX). You might want to install the \`Texinfo' package or
+ the \`GNU make' package. Grab either from any GNU archive site."
+ file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'`
+ if test -z "$file"; then
+ file=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'`
+ file=`sed -n '/^@setfilename/ { s/.* \([^ ]*\) *$/\1/; p; q; }' $file`
+ fi
+ touch $file
+ ;;
+
+ *)
+ echo 1>&2 "\
+WARNING: \`$1' is needed, and you do not seem to have it handy on your
+ system. You might have modified some files without having the
+ proper tools for further handling them. Check the \`README' file,
+ it often tells you about the needed prerequirements for installing
+ this package. You may also peek at any GNU archive site, in case
+ some other package would contain this missing \`$1' program."
+ exit 1
+ ;;
+esac
+
+exit 0
diff --git a/third_party/heimdal/lib/roken/mkdir.c b/third_party/heimdal/lib/roken/mkdir.c
new file mode 100644
index 0000000..5ed4c0d
--- /dev/null
+++ b/third_party/heimdal/lib/roken/mkdir.c
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2013 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifdef WIN32
+#include <direct.h>
+#endif
+
+#include "roken.h"
+#ifndef WIN32
+ #undef rk_mkdir
+#endif
+
+int ROKEN_LIB_FUNCTION
+rk_mkdir(const char *pathname, mode_t mode)
+{
+#ifdef WIN32
+ return _mkdir(pathname);
+#else
+ return mkdir(pathname, mode);
+#endif
+}
diff --git a/third_party/heimdal/lib/roken/mkdtemp.c b/third_party/heimdal/lib/roken/mkdtemp.c
new file mode 100644
index 0000000..b106add
--- /dev/null
+++ b/third_party/heimdal/lib/roken/mkdtemp.c
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2020 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <string.h>
+#include <errno.h>
+
+#include <roken.h>
+
+#ifndef O_APPEND
+#define O_APPEND 0
+#endif
+#ifndef O_CLOEXEC
+#define O_CLOEXEC 0
+#endif
+#ifndef O_SYNC
+#define O_SYNC 0
+#endif
+
+#ifndef HAVE_MKDTEMP
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+mkdtemp(char *template)
+{
+ size_t len = strlen(template) - 1;
+ size_t start, i;
+ pid_t val = getpid();
+
+ for (i = 0; i < len && i < 7 && template[len - i] == 'X'; i++) {
+ template[len] = '0' + val % 10;
+ val /= 10;
+ len--;
+ if (!val)
+ val = getpid();
+ }
+
+ if (i < 6) {
+ errno = EINVAL;
+ return NULL;
+ }
+
+ start = len - i;
+ do {
+ if (mkdir(template, 0700) == 0)
+ return template;
+ for (i = start + 1; i < len; i++) {
+ if (++(template[i]) == '9' + 1)
+ template[i] = 'a';
+ if (template[i] <= 'z')
+ break;
+ template[i] = 'a';
+ }
+ } while(1);
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/mkinstalldirs b/third_party/heimdal/lib/roken/mkinstalldirs
new file mode 100644
index 0000000..6b3b5fc
--- /dev/null
+++ b/third_party/heimdal/lib/roken/mkinstalldirs
@@ -0,0 +1,40 @@
+#! /bin/sh
+# mkinstalldirs --- make directory hierarchy
+# Author: Noah Friedman <friedman@prep.ai.mit.edu>
+# Created: 1993-05-16
+# Public domain
+
+# $Id$
+
+errstatus=0
+
+for file
+do
+ set fnord `echo ":$file" | sed -ne 's/^:\//#/;s/^://;s/\// /g;s/^#/\//;p'`
+ shift
+
+ pathcomp=
+ for d
+ do
+ pathcomp="$pathcomp$d"
+ case "$pathcomp" in
+ -* ) pathcomp=./$pathcomp ;;
+ esac
+
+ if test ! -d "$pathcomp"; then
+ echo "mkdir $pathcomp"
+
+ mkdir "$pathcomp" || lasterr=$?
+
+ if test ! -d "$pathcomp"; then
+ errstatus=$lasterr
+ fi
+ fi
+
+ pathcomp="$pathcomp/"
+ done
+done
+
+exit $errstatus
+
+# mkinstalldirs ends here
diff --git a/third_party/heimdal/lib/roken/mkostemp.c b/third_party/heimdal/lib/roken/mkostemp.c
new file mode 100644
index 0000000..8d739d8
--- /dev/null
+++ b/third_party/heimdal/lib/roken/mkostemp.c
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2019 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <string.h>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#include <errno.h>
+
+#include <roken.h>
+
+#ifndef O_APPEND
+#define O_APPEND 0
+#endif
+#ifndef O_CLOEXEC
+#define O_CLOEXEC 0
+#endif
+#ifndef O_SYNC
+#define O_SYNC 0
+#endif
+
+#ifndef HAVE_MKOSTEMP
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+mkostemp(char *template, int flags)
+{
+ int fd = mkstemp(template);
+
+ if (flags == 0)
+ return fd;
+
+ if ((flags & O_CLOEXEC))
+ rk_cloexec(fd);
+
+ /* fcntl F_SETFL O_APPEND and O_SYNC. */
+#ifdef HAVE_FCNTL
+ if ((flags & (O_APPEND | O_SYNC))) {
+ int fl;
+
+ if ((fl = fcntl(fd, F_GETFL)) == -1 ||
+ fcntl(fd, F_SETFD, fl | (flags & (O_APPEND | O_SYNC))) == -1) {
+ int save_errno = errno;
+
+ (void) unlink(template);
+ (void) close(fd);
+ errno = save_errno;
+ return -1;
+ }
+ }
+#endif
+ return fd;
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/mkstemp.c b/third_party/heimdal/lib/roken/mkstemp.c
new file mode 100644
index 0000000..a3ca6c7
--- /dev/null
+++ b/third_party/heimdal/lib/roken/mkstemp.c
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <string.h>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#include <errno.h>
+
+#include <roken.h>
+
+#ifndef HAVE_MKSTEMP
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+mkstemp(char *template)
+{
+ int start, i;
+ pid_t val;
+ val = getpid();
+ start = strlen(template) - 1;
+ while(template[start] == 'X') {
+ template[start] = '0' + val % 10;
+ val /= 10;
+ start--;
+ }
+
+ do{
+ int fd;
+ fd = open(template, O_RDWR | O_CREAT | O_EXCL, 0600);
+ if(fd >= 0 || errno != EEXIST)
+ return fd;
+ i = start + 1;
+ do{
+ if(template[i] == 0)
+ return -1;
+ template[i]++;
+ if(template[i] == '9' + 1)
+ template[i] = 'a';
+ if(template[i] <= 'z')
+ break;
+ template[i] = 'a';
+ i++;
+ }while(1);
+ }while(1);
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/ndbm_wrap.c b/third_party/heimdal/lib/roken/ndbm_wrap.c
new file mode 100644
index 0000000..f8403da
--- /dev/null
+++ b/third_party/heimdal/lib/roken/ndbm_wrap.c
@@ -0,0 +1,227 @@
+/*
+ * Copyright (c) 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "ndbm_wrap.h"
+#if defined(HAVE_DBHEADER)
+#include <db.h>
+#elif defined(HAVE_DB6_DB_H)
+#include <db6/db.h>
+#elif defined(HAVE_DB5_DB_H)
+#include <db5/db.h>
+#elif defined(HAVE_DB4_DB_H)
+#include <db4/db.h>
+#elif defined(HAVE_DB3_DB_H)
+#include <db3/db.h>
+#else
+#include <db.h>
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+
+/* XXX undefine open so this works on Solaris with large file support */
+#undef open
+
+#define DBT2DATUM(DBT, DATUM) do { (DATUM)->dptr = (DBT)->data; (DATUM)->dsize = (DBT)->size; } while(0)
+#define DATUM2DBT(DATUM, DBT) do { (DBT)->data = (DATUM)->dptr; (DBT)->size = (DATUM)->dsize; } while(0)
+#define RETURN(X) return ((X) == 0) ? 0 : -1
+
+#ifdef HAVE_DB3
+static DBC *cursor;
+#endif
+
+#define D(X) ((DB*)(X))
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+dbm_close (DBM *db)
+{
+#ifdef HAVE_DB3
+ D(db)->close(D(db), 0);
+ cursor = NULL;
+#else
+ D(db)->close(D(db));
+#endif
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+dbm_delete (DBM *db, datum dkey)
+{
+ DBT key;
+ DATUM2DBT(&dkey, &key);
+#ifdef HAVE_DB3
+ RETURN(D(db)->del(D(db), NULL, &key, 0));
+#else
+ RETURN(D(db)->del(D(db), &key, 0));
+#endif
+}
+
+datum
+dbm_fetch (DBM *db, datum dkey)
+{
+ datum dvalue;
+ DBT key, value;
+ DATUM2DBT(&dkey, &key);
+ if(D(db)->get(D(db),
+#ifdef HAVE_DB3
+ NULL,
+#endif
+ &key, &value, 0) != 0) {
+ dvalue.dptr = NULL;
+ dvalue.dsize = 0;
+ }
+ else
+ DBT2DATUM(&value, &dvalue);
+
+ return dvalue;
+}
+
+static datum
+dbm_get (DB *db, int flags)
+{
+ DBT key, value;
+ datum d;
+#ifdef HAVE_DB3
+ if(cursor == NULL)
+ db->cursor(db, NULL, &cursor, 0);
+ if(cursor->c_get(cursor, &key, &value, flags) != 0) {
+ d.dptr = NULL;
+ d.dsize = 0;
+ } else
+ DBT2DATUM(&value, &d);
+#else
+ db->seq(db, &key, &value, flags);
+ DBT2DATUM(&value, &d);
+#endif
+ return d;
+}
+
+#ifndef DB_FIRST
+#define DB_FIRST R_FIRST
+#define DB_NEXT R_NEXT
+#define DB_NOOVERWRITE R_NOOVERWRITE
+#define DB_KEYEXIST 1
+#endif
+
+ROKEN_LIB_FUNCTION datum ROKEN_LIB_CALL
+dbm_firstkey (DBM *db)
+{
+ return dbm_get(D(db), DB_FIRST);
+}
+
+ROKEN_LIB_FUNCTION datum ROKEN_LIB_CALL
+dbm_nextkey (DBM *db)
+{
+ return dbm_get(D(db), DB_NEXT);
+}
+
+ROKEN_LIB_FUNCTION DBM* ROKEN_LIB_CALL
+dbm_open (const char *file, int flags, mode_t mode)
+{
+#ifdef HAVE_DB3
+ int myflags = 0;
+#endif
+ DB *db;
+ char *fn = malloc(strlen(file) + 4);
+ if(fn == NULL)
+ return NULL;
+ strcpy(fn, file);
+ strcat(fn, ".db");
+#ifdef HAVE_DB3
+ if (flags & O_CREAT)
+ myflags |= DB_CREATE;
+
+ if (flags & O_EXCL)
+ myflags |= DB_EXCL;
+
+ if (flags & O_RDONLY)
+ myflags |= DB_RDONLY;
+
+ if (flags & O_TRUNC)
+ myflags |= DB_TRUNCATE;
+ if(db_create(&db, NULL, 0) != 0) {
+ free(fn);
+ return NULL;
+ }
+
+#if (DB_VERSION_MAJOR > 3) && (DB_VERSION_MINOR > 0)
+ if(db->open(db, NULL, fn, NULL, DB_BTREE, myflags, mode) != 0) {
+#else
+ if(db->open(db, fn, NULL, DB_BTREE, myflags, mode) != 0) {
+#endif
+ free(fn);
+ db->close(db, 0);
+ return NULL;
+ }
+#else
+ db = dbopen(fn, flags, mode, DB_BTREE, NULL);
+#endif
+ free(fn);
+ return (DBM*)db;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+dbm_store (DBM *db, datum dkey, datum dvalue, int flags)
+{
+ int ret;
+ DBT key, value;
+ int myflags = 0;
+ if((flags & DBM_REPLACE) == 0)
+ myflags |= DB_NOOVERWRITE;
+ DATUM2DBT(&dkey, &key);
+ DATUM2DBT(&dvalue, &value);
+ ret = D(db)->put(D(db),
+#ifdef HAVE_DB3
+ NULL,
+#endif
+&key, &value, myflags);
+ if(ret == DB_KEYEXIST)
+ return 1;
+ RETURN(ret);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+dbm_error (DBM *db)
+{
+ return 0;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+dbm_clearerr (DBM *db)
+{
+ return 0;
+}
+
diff --git a/third_party/heimdal/lib/roken/ndbm_wrap.h b/third_party/heimdal/lib/roken/ndbm_wrap.h
new file mode 100644
index 0000000..a2ec4f2
--- /dev/null
+++ b/third_party/heimdal/lib/roken/ndbm_wrap.h
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __ndbm_wrap_h__
+#define __ndbm_wrap_h__
+
+#include <stdio.h>
+#include <sys/types.h>
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __cdecl
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+#ifndef dbm_rename
+#define dbm_rename(X) __roken_ ## X
+#endif
+
+#define dbm_open dbm_rename(dbm_open)
+#define dbm_close dbm_rename(dbm_close)
+#define dbm_delete dbm_rename(dbm_delete)
+#define dbm_fetch dbm_rename(dbm_fetch)
+#define dbm_get dbm_rename(dbm_get)
+#define dbm_firstkey dbm_rename(dbm_firstkey)
+#define dbm_nextkey dbm_rename(dbm_nextkey)
+#define dbm_store dbm_rename(dbm_store)
+#define dbm_error dbm_rename(dbm_error)
+#define dbm_clearerr dbm_rename(dbm_clearerr)
+
+#define datum dbm_rename(datum)
+
+typedef struct {
+ void *dptr;
+ size_t dsize;
+} datum;
+
+#define DBM_REPLACE 1
+typedef struct DBM DBM;
+
+#if 0
+typedef struct {
+ int dummy;
+} DBM;
+#endif
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL dbm_clearerr (DBM*);
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL dbm_close (DBM*);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL dbm_delete (DBM*, datum);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL dbm_error (DBM*);
+ROKEN_LIB_FUNCTION datum ROKEN_LIB_CALL dbm_fetch (DBM*, datum);
+ROKEN_LIB_FUNCTION datum ROKEN_LIB_CALL dbm_firstkey (DBM*);
+ROKEN_LIB_FUNCTION datum ROKEN_LIB_CALL dbm_nextkey (DBM*);
+ROKEN_LIB_FUNCTION DBM* ROKEN_LIB_CALL dbm_open (const char*, int, mode_t);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL dbm_store (DBM*, datum, datum, int);
+
+#endif /* __ndbm_wrap_h__ */
diff --git a/third_party/heimdal/lib/roken/net_read.c b/third_party/heimdal/lib/roken/net_read.c
new file mode 100644
index 0000000..df1ac53
--- /dev/null
+++ b/third_party/heimdal/lib/roken/net_read.c
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/*
+ * Like read but never return partial data.
+ */
+
+#ifndef _WIN32
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+net_read (rk_socket_t fd, void *buf, size_t nbytes)
+{
+ char *cbuf = (char *)buf;
+ ssize_t count;
+ size_t rem = nbytes;
+
+ while (rem > 0) {
+ count = read (fd, cbuf, rem);
+ if (count < 0) {
+ if (errno == EINTR)
+ continue;
+ else
+ return count;
+ } else if (count == 0) {
+ return count;
+ }
+ cbuf += count;
+ rem -= count;
+ }
+ return nbytes;
+}
+
+#else
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+net_read(rk_socket_t sock, void *buf, size_t nbytes)
+{
+ char *cbuf = (char *)buf;
+ ssize_t count;
+ size_t rem = nbytes;
+
+#ifdef SOCKET_IS_NOT_AN_FD
+ int use_read = 0;
+#endif
+
+ while (rem > 0) {
+#ifdef SOCKET_IS_NOT_AN_FD
+ if (use_read)
+ count = _read (sock, cbuf, rem);
+ else
+ count = recv (sock, cbuf, rem, 0);
+
+ if (use_read == 0 &&
+ rk_IS_SOCKET_ERROR(count) &&
+ (rk_SOCK_ERRNO == WSANOTINITIALISED ||
+ rk_SOCK_ERRNO == WSAENOTSOCK)) {
+ use_read = 1;
+
+ count = _read (sock, cbuf, rem);
+ }
+#else
+ count = recv (sock, cbuf, rem, 0);
+#endif
+ if (count < 0) {
+
+ /* With WinSock, the error EINTR (WSAEINTR), is used to
+ indicate that a blocking call was cancelled using
+ WSACancelBlockingCall(). */
+
+#ifndef HAVE_WINSOCK
+ if (rk_SOCK_ERRNO == EINTR)
+ continue;
+#endif
+ return count;
+ } else if (count == 0) {
+ return count;
+ }
+ cbuf += count;
+ rem -= count;
+ }
+ return nbytes;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/net_write.c b/third_party/heimdal/lib/roken/net_write.c
new file mode 100644
index 0000000..e66f56b
--- /dev/null
+++ b/third_party/heimdal/lib/roken/net_write.c
@@ -0,0 +1,134 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+/*
+ * Like write but blocking sockets never return partial data, i.e. we retry on
+ * EINTR. With non-blocking sockets (EWOULDBLOCK or EAGAIN) we return the
+ * number of bytes written.
+ */
+
+#ifndef _WIN32
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+net_write (rk_socket_t fd, const void *buf, size_t nbytes)
+{
+ const char *cbuf = (const char *)buf;
+ ssize_t count;
+ size_t rem = nbytes;
+
+ while (rem > 0) {
+ count = write (fd, cbuf, rem);
+ if (count < 0) {
+ switch (errno) {
+ case EINTR:
+ continue;
+#if defined(EAGAIN) && EAGAIN != EWOULDBLOCK
+ case EAGAIN:
+#endif
+ case EWOULDBLOCK:
+ return nbytes - rem;
+ default:
+ return count;
+ }
+ }
+ cbuf += count;
+ rem -= count;
+ }
+ return nbytes;
+}
+
+#else /* defined(_WIN32) */
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+net_write(rk_socket_t sock, const void *buf, size_t nbytes)
+{
+ const char *cbuf = (const char *)buf;
+ ssize_t count;
+ size_t rem = nbytes;
+#ifdef SOCKET_IS_NOT_AN_FD
+ int use_write = 0;
+#endif
+
+ while (rem > 0) {
+#ifdef SOCKET_IS_NOT_AN_FD
+ if (use_write)
+ count = _write (sock, cbuf, rem);
+ else
+ count = send (sock, cbuf, rem, 0);
+
+ if (use_write == 0 &&
+ rk_IS_SOCKET_ERROR(count) &&
+ (rk_SOCK_ERRNO == WSANOTINITIALISED ||
+ rk_SOCK_ERRNO == WSAENOTSOCK)) {
+ use_write = 1;
+
+ count = _write (sock, cbuf, rem);
+ }
+#else
+ count = send (sock, cbuf, rem, 0);
+#endif
+ if (count < 0) {
+#ifdef SOCKET_IS_NOT_AN_FD
+ if (!use_write) {
+ switch (rk_SOCK_ERRNO) {
+ case WSAEINTR:
+ continue;
+ case WSAEWOULDBLOCK:
+ return nbytes - rem;
+ default:
+ return count;
+ }
+ } else
+#endif
+ {
+ switch (errno) {
+ case EINTR:
+ continue;
+ case EWOULDBLOCK:
+ return nbytes - rem;
+ default:
+ return count;
+ }
+ }
+ }
+ cbuf += count;
+ rem -= count;
+ }
+ return nbytes;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/parse_bytes-test.c b/third_party/heimdal/lib/roken/parse_bytes-test.c
new file mode 100644
index 0000000..f7697e6
--- /dev/null
+++ b/third_party/heimdal/lib/roken/parse_bytes-test.c
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include "parse_bytes.h"
+
+static struct testcase {
+ int canonicalp;
+ ssize_t val;
+ const char *def_unit;
+ const char *str;
+} tests[] = {
+ {0, 0, NULL, "0 bytes"},
+ {1, 0, NULL, "0"},
+ {0, 1, NULL, "1"},
+ {1, 1, NULL, "1 byte"},
+ {0, 0, "kilobyte", "0"},
+ {0, 1024, "kilobyte", "1"},
+ {1, 1024, "kilobyte", "1 kilobyte"},
+ {1, 1024 * 1024, NULL, "1 megabyte"},
+ {0, 1025, NULL, "1 kilobyte 1"},
+ {1, 1025, NULL, "1 kilobyte 1 byte"},
+ {1, 1024UL * 1024 * 1024 * 1024, NULL, "1 terabyte"},
+};
+
+int
+main(int argc, char **argv)
+{
+ int i;
+ int ret = 0;
+
+ for (i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i) {
+ char buf[256];
+ ssize_t val = parse_bytes (tests[i].str, tests[i].def_unit);
+
+ if (val != tests[i].val) {
+ printf ("parse_bytes (%s, %s) = %lld != %lld\n",
+ tests[i].str,
+ tests[i].def_unit ? tests[i].def_unit : "none",
+ (long long)val, (long long)tests[i].val);
+ ++ret;
+ }
+ if (tests[i].canonicalp) {
+ (void) unparse_bytes (tests[i].val, buf, sizeof(buf));
+ if (strcmp (tests[i].str, buf) != 0) {
+ printf ("unparse_bytes (%lld) = \"%s\" != \"%s\"\n",
+ (long long)tests[i].val, buf, tests[i].str);
+ ++ret;
+ }
+ }
+ }
+ if (ret) {
+ printf ("%d errors\n", ret);
+ return 1;
+ } else
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/parse_bytes.c b/third_party/heimdal/lib/roken/parse_bytes.c
new file mode 100644
index 0000000..006a352
--- /dev/null
+++ b/third_party/heimdal/lib/roken/parse_bytes.c
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <parse_units.h>
+#include "parse_bytes.h"
+
+static struct units bytes_units[] = {
+ { "petabyte", 1024UL * 1024 * 1024 * 1024 * 1024 },
+ { "PB", 1024UL * 1024 * 1024 * 1024 * 1024 },
+ { "terabyte", 1024UL * 1024 * 1024 * 1024 },
+ { "TB", 1024UL * 1024 * 1024 * 1024 },
+ { "gigabyte", 1024 * 1024 * 1024 },
+ { "gbyte", 1024 * 1024 * 1024 },
+ { "GB", 1024 * 1024 * 1024 },
+ { "megabyte", 1024 * 1024 },
+ { "mbyte", 1024 * 1024 },
+ { "MB", 1024 * 1024 },
+ { "kilobyte", 1024 },
+ { "KB", 1024 },
+ { "byte", 1 },
+ { NULL, 0 }
+};
+
+static struct units bytes_short_units[] = {
+ { "PB", 1024UL * 1024 * 1024 * 1024 * 1024 },
+ { "TB", 1024UL * 1024 * 1024 * 1024 },
+ { "GB", 1024 * 1024 * 1024 },
+ { "MB", 1024 * 1024 },
+ { "KB", 1024 },
+ { NULL, 0 }
+};
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+parse_bytes(const char *s, const char *def_unit)
+{
+ return parse_units (s, bytes_units, def_unit);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_bytes(ssize_t t, char *s, size_t len)
+{
+ return unparse_units (t, bytes_units, s, len);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_bytes_short (ssize_t t, char *s, size_t len)
+{
+ return unparse_units_approx (t, bytes_short_units, s, len);
+}
diff --git a/third_party/heimdal/lib/roken/parse_bytes.h b/third_party/heimdal/lib/roken/parse_bytes.h
new file mode 100644
index 0000000..b7eea2b
--- /dev/null
+++ b/third_party/heimdal/lib/roken/parse_bytes.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __PARSE_BYTES_H__
+#define __PARSE_BYTES_H__
+
+#include <roken.h>
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+parse_bytes(const char *s, const char *def_unit);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_bytes(ssize_t t, char *s, size_t len);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_bytes_short(ssize_t t, char *s, size_t len);
+
+#endif /* __PARSE_BYTES_H__ */
diff --git a/third_party/heimdal/lib/roken/parse_reply-test.c b/third_party/heimdal/lib/roken/parse_reply-test.c
new file mode 100644
index 0000000..5e40b81
--- /dev/null
+++ b/third_party/heimdal/lib/roken/parse_reply-test.c
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <sys/types.h>
+#ifdef HAVE_SYS_MMAN_H
+#include <sys/mman.h>
+#endif
+#include <fcntl.h>
+
+#include "roken.h"
+#include "resolve.h"
+
+struct dns_reply*
+parse_reply(const unsigned char *, size_t);
+
+enum { MAX_BUF = 36};
+
+static struct testcase {
+ unsigned char buf[MAX_BUF];
+ size_t buf_len;
+} tests[] = {
+ {{0x12, 0x67, 0x84, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
+ 0x03, 'f', 'o', 'o', 0x00,
+ 0x00, 0x10, 0x00, 0x01,
+ 0x03, 'f', 'o', 'o', 0x00,
+ 0x00, 0x10, 0x00, 0x01,
+ 0x00, 0x00, 0x12, 0x67, 0xff, 0xff}, 36}
+};
+
+#ifndef MAP_FAILED
+#define MAP_FAILED (-1)
+#endif
+
+static sig_atomic_t val = 0;
+
+static RETSIGTYPE
+segv_handler(int sig)
+{
+ val = 1;
+}
+
+int
+main(int argc, char **argv)
+{
+#ifndef HAVE_MMAP
+ return 77; /* signal to automake that this test
+ cannot be run */
+#else /* HAVE_MMAP */
+ int ret;
+ int i;
+ struct sigaction sa;
+
+ sigemptyset (&sa.sa_mask);
+ sa.sa_flags = 0;
+ sa.sa_handler = segv_handler;
+ sigaction (SIGSEGV, &sa, NULL);
+
+ for (i = 0; val == 0 && i < sizeof(tests)/sizeof(tests[0]); ++i) {
+ const struct testcase *t = &tests[i];
+ unsigned char *p1, *p2;
+ int flags;
+ int fd;
+ size_t pagesize = getpagesize();
+ unsigned char *buf;
+
+#ifdef MAP_ANON
+ flags = MAP_ANON;
+ fd = -1;
+#else
+ flags = 0;
+ fd = open ("/dev/zero", O_RDONLY);
+ if(fd < 0)
+ err (1, "open /dev/zero");
+#endif
+ flags |= MAP_PRIVATE;
+
+ p1 = (unsigned char *)mmap(0, 2 * pagesize, PROT_READ | PROT_WRITE,
+ flags, fd, 0);
+ if (p1 == (unsigned char *)MAP_FAILED)
+ err (1, "mmap");
+ p2 = p1 + pagesize;
+ ret = mprotect ((void *)p2, pagesize, 0);
+ if (ret < 0)
+ err (1, "mprotect");
+ buf = p2 - t->buf_len;
+ memcpy (buf, t->buf, t->buf_len);
+ parse_reply (buf, t->buf_len);
+ ret = munmap ((void *)p1, 2 * pagesize);
+ if (ret < 0)
+ err (1, "munmap");
+ }
+ return val;
+#endif /* HAVE_MMAP */
+}
diff --git a/third_party/heimdal/lib/roken/parse_time-test.c b/third_party/heimdal/lib/roken/parse_time-test.c
new file mode 100644
index 0000000..a2dfb22
--- /dev/null
+++ b/third_party/heimdal/lib/roken/parse_time-test.c
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include "parse_time.h"
+#include "test-mem.h"
+#include "err.h"
+
+static struct testcase {
+ size_t size;
+ int val;
+ char *str;
+} tests[] = {
+ { 8, 1, "1 second" },
+ { 17, 61, "1 minute 1 second" },
+ { 18, 62, "1 minute 2 seconds" },
+ { 8, 60, "1 minute" },
+ { 6, 3600, "1 hour" },
+ { 15, 3601, "1 hour 1 second" },
+ { 16, 3602, "1 hour 2 seconds" },
+ { 9, 300, "5 minutes" },
+};
+
+int
+main(int argc, char **argv)
+{
+ size_t sz;
+ size_t buf_sz;
+ int i, j;
+
+ for (i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i) {
+ char *buf;
+
+ sz = unparse_time(tests[i].val, NULL, 0);
+ if (sz != tests[i].size)
+ errx(1, "sz (%lu) != tests[%d].size (%lu)",
+ (unsigned long)sz, i, (unsigned long)tests[i].size);
+
+ for (buf_sz = 0; buf_sz < tests[i].size + 2; buf_sz++) {
+
+ buf = rk_test_mem_alloc(RK_TM_OVERRUN, "overrun",
+ NULL, buf_sz);
+ sz = unparse_time(tests[i].val, buf, buf_sz);
+ if (sz != tests[i].size)
+ errx(1, "sz (%lu) != tests[%d].size (%lu) with in size %lu",
+ (unsigned long)sz, i,
+ (unsigned long)tests[i].size,
+ (unsigned long)buf_sz);
+ if (buf_sz > 0 && memcmp(buf, tests[i].str, buf_sz - 1) != 0)
+ errx(1, "test %i wrong result %s vs %s", i, buf, tests[i].str);
+ if (buf_sz > 0 && buf[buf_sz - 1] != '\0')
+ errx(1, "test %i not zero terminated", i);
+ rk_test_mem_free("overrun");
+
+ buf = rk_test_mem_alloc(RK_TM_UNDERRUN, "underrun",
+ NULL, tests[i].size);
+ sz = unparse_time(tests[i].val, buf, min(buf_sz, tests[i].size));
+ if (sz != tests[i].size)
+ errx(1, "sz (%lu) != tests[%d].size (%lu) with insize %lu",
+ (unsigned long)sz, i,
+ (unsigned long)tests[i].size,
+ (unsigned long)buf_sz);
+ if (buf_sz > 0 && strncmp(buf, tests[i].str, min(buf_sz, tests[i].size) - 1) != 0)
+ errx(1, "test %i wrong result %s vs %s", i, buf, tests[i].str);
+ if (buf_sz > 0 && buf[min(buf_sz, tests[i].size) - 1] != '\0')
+ errx(1, "test %i not zero terminated", i);
+ rk_test_mem_free("underrun");
+ }
+
+ buf = rk_test_mem_alloc(RK_TM_OVERRUN, "overrun",
+ tests[i].str, tests[i].size + 1);
+ j = parse_time(buf, "s");
+ if (j != tests[i].val)
+ errx(1, "parse_time failed for test %d", i);
+ rk_test_mem_free("overrun");
+
+ buf = rk_test_mem_alloc(RK_TM_UNDERRUN, "underrun",
+ tests[i].str, tests[i].size + 1);
+ j = parse_time(buf, "s");
+ if (j != tests[i].val)
+ errx(1, "parse_time failed for test %d", i);
+ rk_test_mem_free("underrun");
+
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/parse_time.3 b/third_party/heimdal/lib/roken/parse_time.3
new file mode 100644
index 0000000..7881eab
--- /dev/null
+++ b/third_party/heimdal/lib/roken/parse_time.3
@@ -0,0 +1,173 @@
+.\" Copyright (c) 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\" $Id: parse_time.3,v 1.3 2013/06/17 18:57:45 robert Exp $
+.\"
+.Dd November 17, 2013
+.Dt PARSE_TIME 3
+.Os HEIMDAL
+.Sh NAME
+.Nm parse_time ,
+.Nm print_time_table ,
+.Nm unparse_time ,
+.Nm unparse_time_approx ,
+.Nd parse and unparse time intervals
+.Sh LIBRARY
+The roken library (libroken, -lroken)
+.Sh SYNOPSIS
+.Fd #include <parse_time.h>
+.Ft int
+.Fn parse_time "const char *timespec" "const char *def_unit"
+.Ft void
+.Fn print_time_table "FILE *f"
+.Ft size_t
+.Fn unparse_time "int seconds" "char *buf" "size_t len"
+.Ft size_t
+.Fn unparse_time_approx "int seconds" "char *buf" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn parse_time
+function converts the period of time specified
+into a number of seconds.
+The
+.Fa timespec
+can be any number of
+.Aq number unit
+pairs separated by comma and whitespace. The number can be
+negative. Numbers without explicit units are taken as being
+.Fa def_unit .
+.Pp
+The
+.Fn unparse_time
+and
+.Fn unparse_time_approx
+do the opposite of
+.Fn parse_time ,
+that is they take a number of seconds and express that as human
+readable strings.
+.Fa unparse_time
+produces an exact time, while
+.Fa unparse_time_approx
+restricts the result to include only one unit.
+.Pp
+.Fn print_time_table
+prints a descriptive list of available units on the passed file
+descriptor.
+.Pp
+The possible units include:
+.Bl -tag -width "month" -compact -offset indent
+.It Li second , s
+.It Li minute , m
+.It Li hour , h
+.It day
+.It week
+seven days
+.It month
+30 days
+.It year
+365 days
+.El
+.Pp
+Units names can be arbitrarily abbreviated (as long as they are
+unique).
+.Sh RETURN VALUES
+.Fn parse_time
+returns the number of seconds that represents the expression in
+.Fa timespec
+or -1 on error.
+.Fn unparse_time
+and
+.Fn unparse_time_approx
+return the number of characters written to
+.Fa buf .
+if the return value is greater than or equal to the
+.Fa len
+argument, the string was too short and some of the printed characters
+were discarded.
+.Sh EXAMPLES
+.Bd -literal
+#include <stdio.h>
+#include <parse_time.h>
+
+int
+main(int argc, char **argv)
+{
+ int i;
+ int result;
+ char buf[128];
+ print_time_table(stdout);
+ for (i = 1; i < argc; i++) {
+ result = parse_time(argv[i], "second");
+ if(result == -1) {
+ fprintf(stderr, "%s: parse error\\n", argv[i]);
+ continue;
+ }
+ printf("--\\n");
+ printf("parse_time = %d\\n", result);
+ unparse_time(result, buf, sizeof(buf));
+ printf("unparse_time = %s\\n", buf);
+ unparse_time_approx(result, buf, sizeof(buf));
+ printf("unparse_time_approx = %s\\n", buf);
+ }
+ return 0;
+}
+.Ed
+.Bd -literal
+$ ./a.out "1 minute 30 seconds" "90 s" "1 y -1 s"
+1 year = 365 days
+1 month = 30 days
+1 week = 7 days
+1 day = 24 hours
+1 hour = 60 minutes
+1 minute = 60 seconds
+1 second
+--
+parse_time = 90
+unparse_time = 1 minute 30 seconds
+unparse_time_approx = 1 minute
+--
+parse_time = 90
+unparse_time = 1 minute 30 seconds
+unparse_time_approx = 1 minute
+--
+parse_time = 31535999
+unparse_time = 12 months 4 days 23 hours 59 minutes 59 seconds
+unparse_time_approx = 12 months
+.Ed
+.Sh BUGS
+Since
+.Fn parse_time
+returns -1 on error there is no way to parse "minus one second".
+Currently "s" at the end of units is ignored. This is a hack for
+English plural forms. If these functions are ever localised, this
+scheme will have to change.
+.\".Sh SEE ALSO
+.\".Xr parse_bytes 3
+.\".Xr parse_units 3
diff --git a/third_party/heimdal/lib/roken/parse_time.c b/third_party/heimdal/lib/roken/parse_time.c
new file mode 100644
index 0000000..f5a99e3
--- /dev/null
+++ b/third_party/heimdal/lib/roken/parse_time.c
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 1997, 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <parse_units.h>
+#include "parse_time.h"
+
+static struct units time_units[] = {
+ {"year", 365 * 24 * 60 * 60},
+ {"month", 30 * 24 * 60 * 60},
+ {"week", 7 * 24 * 60 * 60},
+ {"day", 24 * 60 * 60},
+ {"hour", 60 * 60},
+ {"h", 60 * 60},
+ {"minute", 60},
+ {"m", 60},
+ {"second", 1},
+ {"s", 1},
+ {NULL, 0},
+};
+
+ROKEN_LIB_FUNCTION int64_t ROKEN_LIB_CALL
+parse_time (const char *s, const char *def_unit)
+{
+ return parse_units (s, time_units, def_unit);
+}
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+unparse_time(int64_t t, char *s, size_t len)
+{
+ return unparse_units (t, time_units, s, len);
+}
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+unparse_time_approx(int64_t t, char *s, size_t len)
+{
+ return unparse_units_approx (t, time_units, s, len);
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+print_time_table (FILE *f)
+{
+ print_units_table (time_units, f);
+}
+
+#undef parse_time
+#undef unparse_time
+#undef unparse_time_approx
+#undef print_time_table
+
+ROKEN_LIB_FUNCTION int64_t ROKEN_LIB_CALL
+parse_time(const char *s, const char *def_unit)
+{
+ return rk_parse_units(s, time_units, def_unit);
+}
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+unparse_time(int64_t t, char *s, size_t len)
+{
+ return rk_unparse_units(t, time_units, s, len);
+}
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+unparse_time_approx(int64_t t, char *s, size_t len)
+{
+ return rk_unparse_units_approx(t, time_units, s, len);
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+print_time_table(FILE *f)
+{
+ rk_print_units_table(time_units, f);
+}
diff --git a/third_party/heimdal/lib/roken/parse_time.h b/third_party/heimdal/lib/roken/parse_time.h
new file mode 100644
index 0000000..c0f08f9
--- /dev/null
+++ b/third_party/heimdal/lib/roken/parse_time.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __PARSE_TIME_H__
+#define __PARSE_TIME_H__
+
+#include <roken.h>
+
+ROKEN_LIB_FUNCTION int64_t ROKEN_LIB_CALL
+parse_time (const char *s, const char *def_unit);
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+unparse_time(int64_t t, char *s, size_t len);
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+unparse_time_approx(int64_t t, char *s, size_t len);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+print_time_table (FILE *f);
+
+/* And again, but renamed */
+
+#define parse_time rk_parse_time
+#define unparse_time rk_unparse_time
+#define unparse_time_approx rk_unparse_time_approx
+#define print_time_table rk_print_time_table
+
+ROKEN_LIB_FUNCTION int64_t ROKEN_LIB_CALL
+parse_time (const char *s, const char *def_unit);
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+unparse_time(int64_t t, char *s, size_t len);
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+unparse_time_approx(int64_t t, char *s, size_t len);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+print_time_table (FILE *f);
+
+#endif /* __PARSE_TIME_H__ */
diff --git a/third_party/heimdal/lib/roken/parse_units.c b/third_party/heimdal/lib/roken/parse_units.c
new file mode 100644
index 0000000..d76578a
--- /dev/null
+++ b/third_party/heimdal/lib/roken/parse_units.c
@@ -0,0 +1,525 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdio.h>
+#include <ctype.h>
+#include <string.h>
+#include "roken.h"
+#include "parse_units.h"
+
+/*
+ * Parse string in `s' according to `units' and return value.
+ * def_unit defines the default unit.
+ */
+
+static int64_t
+parse_something_signed(const char *s, const struct units *units,
+ const char *def_unit,
+ int64_t (*func)(int64_t res, int64_t val, uint64_t mult),
+ int64_t init,
+ int accept_no_val_p)
+{
+ const char *p;
+ int64_t res = init;
+ unsigned def_mult = 1;
+
+ if (def_unit != NULL) {
+ const struct units *u;
+
+ for (u = units; u->name; ++u) {
+ if (strcasecmp (u->name, def_unit) == 0) {
+ def_mult = u->mult;
+ break;
+ }
+ }
+ if (u->name == NULL)
+ return -1;
+ }
+
+ p = s;
+ while (*p) {
+ int64_t val;
+ char *next;
+ const struct units *u, *partial_unit;
+ size_t u_len;
+ unsigned partial;
+ int no_val_p = 0;
+
+ while (isspace((unsigned char)*p) || *p == ',')
+ ++p;
+
+ val = strtoll(p, &next, 0);
+ if (p == next) {
+ val = 0;
+ if(!accept_no_val_p)
+ return -1;
+ no_val_p = 1;
+ }
+ p = next;
+ while (isspace((unsigned char)*p))
+ ++p;
+ if (*p == '\0') {
+ res = (*func)(res, val, def_mult);
+ if (res < 0)
+ return res;
+ break;
+ } else if (*p == '+') {
+ ++p;
+ val = 1;
+ } else if (*p == '-') {
+ ++p;
+ val = -1;
+ }
+ if (no_val_p && val == 0)
+ val = 1;
+ u_len = strcspn (p, ", \t");
+ partial = 0;
+ partial_unit = NULL;
+ if (u_len > 1 && p[u_len - 1] == 's')
+ --u_len;
+ for (u = units; u->name; ++u) {
+ if (strncasecmp (p, u->name, u_len) == 0) {
+ if (u_len == strlen (u->name)) {
+ p += u_len;
+ res = (*func)(res, val, u->mult);
+ if (res < 0)
+ return res;
+ break;
+ } else {
+ ++partial;
+ partial_unit = u;
+ }
+ }
+ }
+ if (u->name == NULL) {
+ if (partial == 1) {
+ p += u_len;
+ res = (*func)(res, val, partial_unit->mult);
+ if (res < 0)
+ return res;
+ } else {
+ return -1;
+ }
+ }
+ if (*p == 's')
+ ++p;
+ while (isspace((unsigned char)*p))
+ ++p;
+ }
+ return res;
+}
+
+static uint64_t
+parse_something_unsigned(const char *s, const struct units *units,
+ const char *def_unit,
+ uint64_t (*func)(uint64_t res, int64_t val, uint64_t mult),
+ uint64_t init,
+ int accept_no_val_p)
+{
+ const char *p;
+ int64_t res = init;
+ unsigned def_mult = 1;
+
+ if (def_unit != NULL) {
+ const struct units *u;
+
+ for (u = units; u->name; ++u) {
+ if (strcasecmp (u->name, def_unit) == 0) {
+ def_mult = u->mult;
+ break;
+ }
+ }
+ if (u->name == NULL)
+ return -1;
+ }
+
+ p = s;
+ while (*p) {
+ int64_t val;
+ char *next;
+ const struct units *u, *partial_unit;
+ size_t u_len;
+ unsigned partial;
+ int no_val_p = 0;
+
+ while (isspace((unsigned char)*p) || *p == ',')
+ ++p;
+
+ val = strtoll(p, &next, 0);
+ if (p == next) {
+ val = 0;
+ if(!accept_no_val_p)
+ return -1;
+ no_val_p = 1;
+ }
+ p = next;
+ while (isspace((unsigned char)*p))
+ ++p;
+ if (*p == '\0') {
+ res = (*func)(res, val, def_mult);
+ if (res < 0)
+ return res;
+ break;
+ } else if (*p == '+') {
+ ++p;
+ val = 1;
+ } else if (*p == '-') {
+ ++p;
+ val = -1;
+ }
+ if (no_val_p && val == 0)
+ val = 1;
+ u_len = strcspn (p, ", \t");
+ partial = 0;
+ partial_unit = NULL;
+ if (u_len > 1 && p[u_len - 1] == 's')
+ --u_len;
+ for (u = units; u->name; ++u) {
+ if (strncasecmp (p, u->name, u_len) == 0) {
+ if (u_len == strlen (u->name)) {
+ p += u_len;
+ res = (*func)(res, val, u->mult);
+ if (res < 0)
+ return res;
+ break;
+ } else {
+ ++partial;
+ partial_unit = u;
+ }
+ }
+ }
+ if (u->name == NULL) {
+ if (partial == 1) {
+ p += u_len;
+ res = (*func)(res, val, partial_unit->mult);
+ if (res < 0)
+ return res;
+ } else {
+ return -1;
+ }
+ }
+ if (*p == 's')
+ ++p;
+ while (isspace((unsigned char)*p))
+ ++p;
+ }
+ return res;
+}
+
+/*
+ * The string consists of a sequence of `n unit'
+ */
+
+static int64_t
+acc_units(int64_t res, int64_t val, uint64_t mult)
+{
+ return res + val * mult;
+}
+
+ROKEN_LIB_FUNCTION int64_t ROKEN_LIB_CALL
+parse_units (const char *s, const struct units *units,
+ const char *def_unit)
+{
+ return parse_something_signed(s, units, def_unit, acc_units, 0, 0);
+}
+
+/*
+ * The string consists of a sequence of `[+-]flag'. `orig' consists
+ * the original set of flags, those are then modified and returned as
+ * the function value.
+ */
+
+static uint64_t
+acc_flags(uint64_t res, int64_t val, uint64_t mult)
+{
+ if(val == 1)
+ return res | mult;
+ else if(val == -1)
+ return res & ~mult;
+ else if (val == 0)
+ return mult;
+ else
+ return -1;
+}
+
+ROKEN_LIB_FUNCTION uint64_t ROKEN_LIB_CALL
+parse_flags (const char *s, const struct units *units,
+ int orig)
+{
+ return parse_something_unsigned (s, units, NULL, acc_flags, orig, 1);
+}
+
+/*
+ * Return a string representation according to `units' of `num' in `s'
+ * with maximum length `len'. The actual length is the function value.
+ */
+
+static int
+unparse_something_signed(int64_t num, const struct units *units, char *s,
+ size_t len,
+ int64_t (*get_divisor)(int64_t, uint64_t),
+ int (*print)(char *, size_t, int64_t, const char *, int64_t),
+ int64_t (*update)(int64_t, uint64_t),
+ const char *zero_string)
+{
+ const struct units *u;
+ int ret = 0, tmp;
+
+ if (num == 0)
+ return snprintf (s, len, "%s", zero_string);
+ if (len)
+ s[0] = '\0';
+ if (num < 0)
+ return -1;
+
+ for (u = units; num > 0 && u->name; ++u) {
+ long long divisor = get_divisor(num, u->mult);
+
+ if (divisor) {
+ num = (*update)(num, u->mult);
+ tmp = (*print)(s, len, divisor, u->name, num);
+ if (tmp < 0)
+ return tmp;
+ if ((size_t)tmp > len) {
+ len = 0;
+ s = NULL;
+ } else {
+ len -= tmp;
+ s += tmp;
+ }
+ ret += tmp;
+ }
+ }
+ return ret;
+}
+
+static int
+unparse_something_unsigned(uint64_t num, const struct units *units, char *s,
+ size_t len,
+ uint64_t (*get_divisor)(uint64_t, uint64_t),
+ int (*print)(char *, size_t, uint64_t, const char *, uint64_t),
+ uint64_t (*update)(uint64_t, uint64_t),
+ const char *zero_string)
+{
+ const struct units *u;
+ int64_t tmp;
+ int ret = 0;
+
+ if (num == 0)
+ return snprintf (s, len, "%s", zero_string);
+ if (len)
+ s[0] = '\0';
+
+ for (u = units; num > 0 && u->name; ++u) {
+ long long divisor = get_divisor(num, u->mult);
+
+ if (divisor) {
+ num = (*update) (num, u->mult);
+ tmp = (*print) (s, len, divisor, u->name, num);
+ if (tmp < 0)
+ return tmp;
+ if ((size_t)tmp > len) {
+ len = 0;
+ s = NULL;
+ } else {
+ len -= tmp;
+ s += tmp;
+ }
+ ret += tmp;
+ }
+ }
+ return ret;
+}
+
+static int
+print_unit(char *s, size_t len, int64_t divisor, const char *name, int64_t rem)
+{
+ return snprintf(s, len, "%lld %s%s%s", (long long)divisor, name,
+ divisor == 1 ? "" : "s", rem > 0 ? " " : "");
+}
+
+static int64_t
+get_divisor_unit(int64_t in, uint64_t mult)
+{
+ return in / mult;
+}
+
+static int64_t
+update_unit(int64_t in, uint64_t mult)
+{
+ return in % mult;
+}
+
+static int64_t
+update_unit_approx(int64_t in, uint64_t mult)
+{
+ if (in / mult > 0)
+ return 0;
+ else
+ return update_unit (in, mult);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_units(int64_t num, const struct units *units, char *s, size_t len)
+{
+ return unparse_something_signed(num, units, s, len,
+ get_divisor_unit, print_unit, update_unit,
+ "0");
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_units_approx(int64_t num, const struct units *units, char *s, size_t len)
+{
+ return unparse_something_signed(num, units, s, len, get_divisor_unit,
+ print_unit, update_unit_approx, "0");
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+print_units_table (const struct units *units, FILE *f)
+{
+ const struct units *u, *u2;
+ size_t max_sz = 0;
+
+ for (u = units; u->name; ++u) {
+ max_sz = max(max_sz, strlen(u->name));
+ }
+
+ for (u = units; u->name;) {
+ char buf[1024];
+ const struct units *next;
+
+ for (next = u + 1; next->name && next->mult == u->mult; ++next)
+ ;
+
+ if (next->name) {
+ for (u2 = next;
+ u2->name && u->mult % u2->mult != 0;
+ ++u2)
+ ;
+ if (u2->name == NULL)
+ --u2;
+ unparse_units (u->mult, u2, buf, sizeof(buf));
+ fprintf (f, "1 %*s = %s\n", (int)max_sz, u->name, buf);
+ } else {
+ fprintf (f, "1 %s\n", u->name);
+ }
+ u = next;
+ }
+}
+
+static uint64_t
+get_divisor_flag(uint64_t in, uint64_t mult)
+{
+ return in & mult;
+}
+
+static int
+print_flag(char *s, size_t len, uint64_t divisor, const char *name, uint64_t rem)
+{
+ return snprintf (s, len, "%s%s", name, rem > 0 ? ", " : "");
+}
+
+static uint64_t
+update_flag(uint64_t in, uint64_t mult)
+{
+ return in & ~mult;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_flags (uint64_t num, const struct units *units, char *s, size_t len)
+{
+ return unparse_something_unsigned(num, units, s, len, get_divisor_flag,
+ print_flag, update_flag, "");
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+print_flags_table (const struct units *units, FILE *f)
+{
+ const struct units *u;
+
+ for(u = units; u->name; ++u)
+ fprintf(f, "%s%s", u->name, (u+1)->name ? ", " : "\n");
+}
+
+#undef parse_units
+#undef unparse_units
+#undef unparse_units_approx
+#undef print_units_table
+#undef parse_flags
+#undef unparse_flags
+#undef print_flags_table
+
+ROKEN_LIB_FUNCTION int64_t ROKEN_LIB_CALL
+parse_units(const char *s, const struct units *units,
+ const char *def_unit)
+{
+ return rk_parse_units(s, units, def_unit);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_units(int64_t num, const struct units *units, char *s, size_t len)
+{
+ return rk_unparse_units(num, units, s, len);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_units_approx(int64_t num, const struct units *units, char *s, size_t len)
+{
+ return rk_unparse_units_approx(num, units, s, len);
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+print_units_table(const struct units *units, FILE *f)
+{
+ rk_print_units_table(units, f);
+}
+
+ROKEN_LIB_FUNCTION uint64_t ROKEN_LIB_CALL
+parse_flags(const char *s, const struct units *units, int orig)
+{
+ return rk_parse_flags(s, units, orig);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_flags(uint64_t num, const struct units *units, char *s, size_t len)
+{
+ return rk_unparse_flags(num, units, s, len);
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+print_flags_table (const struct units *units, FILE *f)
+{
+ rk_print_flags_table(units, f);
+}
diff --git a/third_party/heimdal/lib/roken/parse_units.h b/third_party/heimdal/lib/roken/parse_units.h
new file mode 100644
index 0000000..c5b6f20
--- /dev/null
+++ b/third_party/heimdal/lib/roken/parse_units.h
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __PARSE_UNITS_H__
+#define __PARSE_UNITS_H__
+
+#include <stdio.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __cdecl
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+struct units {
+ const char *name;
+ uint64_t mult;
+};
+
+ROKEN_LIB_FUNCTION int64_t ROKEN_LIB_CALL
+parse_units (const char *s, const struct units *units,
+ const char *def_unit);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+print_units_table (const struct units *units, FILE *f);
+
+ROKEN_LIB_FUNCTION uint64_t ROKEN_LIB_CALL
+parse_flags (const char *s, const struct units *units,
+ int orig);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_units(int64_t num, const struct units *units, char *s, size_t len);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_units_approx(int64_t num, const struct units *units, char *s,
+ size_t len);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_flags(uint64_t num, const struct units *units, char *s, size_t len);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+print_flags_table (const struct units *units, FILE *f);
+
+/* And again, but renamed */
+
+#define parse_units rk_parse_units
+#define unparse_units rk_unparse_units
+#define unparse_units_approx rk_unparse_units_approx
+#define print_units_table rk_print_units_table
+#define parse_flags rk_parse_flags
+#define unparse_flags rk_unparse_flags
+#define print_flags_table rk_print_flags_table
+
+ROKEN_LIB_FUNCTION int64_t ROKEN_LIB_CALL
+parse_units (const char *s, const struct units *units,
+ const char *def_unit);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+print_units_table (const struct units *units, FILE *f);
+
+ROKEN_LIB_FUNCTION uint64_t ROKEN_LIB_CALL
+parse_flags (const char *s, const struct units *units,
+ int orig);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_units(int64_t num, const struct units *units, char *s, size_t len);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_units_approx(int64_t num, const struct units *units, char *s,
+ size_t len);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unparse_flags(uint64_t num, const struct units *units, char *s, size_t len);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+print_flags_table (const struct units *units, FILE *f);
+
+#endif /* __PARSE_UNITS_H__ */
diff --git a/third_party/heimdal/lib/roken/putenv.c b/third_party/heimdal/lib/roken/putenv.c
new file mode 100644
index 0000000..647eb7a
--- /dev/null
+++ b/third_party/heimdal/lib/roken/putenv.c
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdlib.h>
+
+#if !HAVE_DECL_ENVIRON
+extern char **environ;
+#endif
+
+/*
+ * putenv --
+ * String points to a string of the form name=value.
+ *
+ * Makes the value of the environment variable name equal to
+ * value by altering an existing variable or creating a new one.
+ */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+putenv(const char *string)
+{
+ int i;
+ const char *eq = (const char *)strchr(string, '=');
+ int len;
+
+ if (eq == NULL)
+ return 1;
+ len = eq - string;
+
+ if(environ == NULL) {
+ environ = malloc(sizeof(char*));
+ if(environ == NULL)
+ return 1;
+ environ[0] = NULL;
+ }
+
+ for(i = 0; environ[i] != NULL; i++)
+ if(strncmp(string, environ[i], len) == 0) {
+ environ[i] = string;
+ return 0;
+ }
+ environ = realloc(environ, sizeof(char*) * (i + 2));
+ if(environ == NULL)
+ return 1;
+ environ[i] = string;
+ environ[i+1] = NULL;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/qsort.c b/third_party/heimdal/lib/roken/qsort.c
new file mode 100644
index 0000000..7689813
--- /dev/null
+++ b/third_party/heimdal/lib/roken/qsort.c
@@ -0,0 +1,203 @@
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 4. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if 0
+#if defined(LIBC_SCCS) && !defined(lint)
+static char sccsid[] = "@(#)qsort.c 8.1 (Berkeley) 6/4/93";
+#endif /* LIBC_SCCS and not lint */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+#endif
+
+#include <config.h>
+
+#ifdef NEED_QSORT
+
+#include "roken.h"
+
+#include <stdlib.h>
+
+#ifdef I_AM_QSORT_R
+typedef int cmp_t(void *, const void *, const void *);
+#else
+typedef int cmp_t(const void *, const void *);
+#endif
+static inline char *med3(char *, char *, char *, cmp_t *, void *);
+static inline void swapfunc(char *, char *, int, int);
+
+/*
+ * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
+ */
+#define swapcode(TYPE, parmi, parmj, n) { \
+ long i = (n) / sizeof (TYPE); \
+ TYPE *pi = (TYPE *) (parmi); \
+ TYPE *pj = (TYPE *) (parmj); \
+ do { \
+ TYPE t = *pi; \
+ *pi++ = *pj; \
+ *pj++ = t; \
+ } while (--i > 0); \
+}
+
+#define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \
+ es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1;
+
+static inline void
+swapfunc(a, b, n, swaptype)
+ char *a, *b;
+ int n, swaptype;
+{
+ if(swaptype <= 1)
+ swapcode(long, a, b, n)
+ else
+ swapcode(char, a, b, n)
+}
+
+#define swap(a, b) \
+ if (swaptype == 0) { \
+ long t = *(long *)(a); \
+ *(long *)(a) = *(long *)(b); \
+ *(long *)(b) = t; \
+ } else \
+ swapfunc(a, b, es, swaptype)
+
+#define vecswap(a, b, n) if ((n) > 0) swapfunc(a, b, n, swaptype)
+
+#ifdef I_AM_QSORT_R
+#define CMP(t, x, y) (cmp((t), (x), (y)))
+#else
+#define CMP(t, x, y) (cmp((x), (y)))
+#endif
+
+static inline char *
+med3(char *a, char *b, char *c, cmp_t *cmp, void *thunk
+#ifndef I_AM_QSORT_R
+/* __unused */
+#endif
+)
+{
+ return CMP(thunk, a, b) < 0 ?
+ (CMP(thunk, b, c) < 0 ? b : (CMP(thunk, a, c) < 0 ? c : a ))
+ :(CMP(thunk, b, c) > 0 ? b : (CMP(thunk, a, c) < 0 ? a : c ));
+}
+
+#ifdef I_AM_QSORT_R
+void
+rk_qsort_r(void *a, size_t n, size_t es, void *thunk, cmp_t *cmp)
+#else
+#define thunk NULL
+void
+rk_qsort(void *a, size_t n, size_t es, cmp_t *cmp)
+#endif
+{
+ char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
+ size_t d, r;
+ int cmp_result;
+ int swaptype, swap_cnt;
+
+loop: SWAPINIT(a, es);
+ swap_cnt = 0;
+ if (n < 7) {
+ for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
+ for (pl = pm;
+ pl > (char *)a && CMP(thunk, pl - es, pl) > 0;
+ pl -= es)
+ swap(pl, pl - es);
+ return;
+ }
+ pm = (char *)a + (n / 2) * es;
+ if (n > 7) {
+ pl = a;
+ pn = (char *)a + (n - 1) * es;
+ if (n > 40) {
+ d = (n / 8) * es;
+ pl = med3(pl, pl + d, pl + 2 * d, cmp, thunk);
+ pm = med3(pm - d, pm, pm + d, cmp, thunk);
+ pn = med3(pn - 2 * d, pn - d, pn, cmp, thunk);
+ }
+ pm = med3(pl, pm, pn, cmp, thunk);
+ }
+ swap(a, pm);
+ pa = pb = (char *)a + es;
+
+ pc = pd = (char *)a + (n - 1) * es;
+ for (;;) {
+ while (pb <= pc && (cmp_result = CMP(thunk, pb, a)) <= 0) {
+ if (cmp_result == 0) {
+ swap_cnt = 1;
+ swap(pa, pb);
+ pa += es;
+ }
+ pb += es;
+ }
+ while (pb <= pc && (cmp_result = CMP(thunk, pc, a)) >= 0) {
+ if (cmp_result == 0) {
+ swap_cnt = 1;
+ swap(pc, pd);
+ pd -= es;
+ }
+ pc -= es;
+ }
+ if (pb > pc)
+ break;
+ swap(pb, pc);
+ swap_cnt = 1;
+ pb += es;
+ pc -= es;
+ }
+ if (swap_cnt == 0) { /* Switch to insertion sort */
+ for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
+ for (pl = pm;
+ pl > (char *)a && CMP(thunk, pl - es, pl) > 0;
+ pl -= es)
+ swap(pl, pl - es);
+ return;
+ }
+
+ pn = (char *)a + n * es;
+ r = min(pa - (char *)a, pb - pa);
+ vecswap(a, pb - r, r);
+ r = min(pd - pc, pn - pd - es);
+ vecswap(pb, pn - r, r);
+ if ((r = pb - pa) > es)
+#ifdef I_AM_QSORT_R
+ rk_qsort_r(a, r / es, es, thunk, cmp);
+#else
+ rk_qsort(a, r / es, es, cmp);
+#endif
+ if ((r = pd - pc) > es) {
+ /* Iterate rather than recurse to save stack space */
+ a = pn - r;
+ n = r / es;
+ goto loop;
+ }
+/* rk_qsort(pn - r, r / es, es, cmp);*/
+}
+
+#endif /* NEED_QSORT */
diff --git a/third_party/heimdal/lib/roken/rand.c b/third_party/heimdal/lib/roken/rand.c
new file mode 100644
index 0000000..59ff47a
--- /dev/null
+++ b/third_party/heimdal/lib/roken/rand.c
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+#include <config.h>
+
+#include "roken.h"
+
+#ifdef HAVE_WIN32_RAND_S
+static int hasRand_s = 1;
+#include "versionsupport.h"
+#endif
+
+void ROKEN_LIB_FUNCTION
+rk_random_init(void)
+{
+#if defined(HAVE_ARC4RANDOM)
+ /* nothing to do */;
+#elif defined(HAVE_SRANDOMDEV)
+ srandomdev();
+#elif defined(HAVE_RANDOM)
+ srandom(time(NULL));
+#else
+# ifdef HAVE_WIN32_RAND_S
+ hasRand_s = IsWindowsXPOrGreater();
+# endif
+ srand (time(NULL));
+#endif
+}
+
+#ifdef HAVE_WIN32_RAND_S
+unsigned int ROKEN_LIB_FUNCTION
+rk_random(void)
+{
+ if (hasRand_s) {
+ unsigned int n;
+ int code;
+
+ code = rand_s(&n);
+ if (code == 0)
+ return n;
+ }
+
+ return rand();
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/rcmd.c b/third_party/heimdal/lib/roken/rcmd.c
new file mode 100644
index 0000000..7fa85a3
--- /dev/null
+++ b/third_party/heimdal/lib/roken/rcmd.c
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include <stdio.h>
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rcmd(char **ahost,
+ unsigned short inport,
+ const char *locuser,
+ const char *remuser,
+ const char *cmd,
+ int *fd2p)
+{
+ fprintf(stderr, "Only kerberized services are implemented\n");
+ return -1;
+}
diff --git a/third_party/heimdal/lib/roken/readv.c b/third_party/heimdal/lib/roken/readv.c
new file mode 100644
index 0000000..a156015
--- /dev/null
+++ b/third_party/heimdal/lib/roken/readv.c
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+readv(int d, const struct iovec *iov, int iovcnt)
+{
+ ssize_t ret, nb;
+ size_t tot = 0;
+ int i;
+ char *buf, *p;
+
+ for(i = 0; i < iovcnt; ++i)
+ tot += iov[i].iov_len;
+ buf = malloc(tot);
+ if (tot != 0 && buf == NULL) {
+ errno = ENOMEM;
+ return -1;
+ }
+ nb = ret = read (d, buf, tot);
+ p = buf;
+ while (nb > 0) {
+ ssize_t cnt = min(nb, iov->iov_len);
+
+ memcpy (iov->iov_base, p, cnt);
+ p += cnt;
+ nb -= cnt;
+ }
+ free(buf);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/realloc.c b/third_party/heimdal/lib/roken/realloc.c
new file mode 100644
index 0000000..fefa90d
--- /dev/null
+++ b/third_party/heimdal/lib/roken/realloc.c
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#undef realloc
+
+#include <stdlib.h>
+#include "roken.h"
+#undef realloc
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+rk_realloc(void *ptr, size_t size)
+{
+ if (ptr == NULL)
+ return malloc(size);
+ return realloc(ptr, size);
+}
diff --git a/third_party/heimdal/lib/roken/recvmsg.c b/third_party/heimdal/lib/roken/recvmsg.c
new file mode 100644
index 0000000..aba298b
--- /dev/null
+++ b/third_party/heimdal/lib/roken/recvmsg.c
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+recvmsg(int s, struct msghdr *msg, int flags)
+{
+ ssize_t ret, nb;
+ size_t tot = 0;
+ int i;
+ char *buf, *p;
+ struct iovec *iov = msg->msg_iov;
+
+ for(i = 0; i < msg->msg_iovlen; ++i)
+ tot += iov[i].iov_len;
+ buf = malloc(tot);
+ if (tot != 0 && buf == NULL) {
+ errno = ENOMEM;
+ return -1;
+ }
+ nb = ret = recvfrom (s, buf, tot, flags, msg->msg_name, &msg->msg_namelen);
+ p = buf;
+ while (nb > 0) {
+ ssize_t cnt = min(nb, iov->iov_len);
+
+ memcpy (iov->iov_base, p, cnt);
+ p += cnt;
+ nb -= cnt;
+ ++iov;
+ }
+ free(buf);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/rename.c b/third_party/heimdal/lib/roken/rename.c
new file mode 100644
index 0000000..d7348d3
--- /dev/null
+++ b/third_party/heimdal/lib/roken/rename.c
@@ -0,0 +1,49 @@
+/***********************************************************************
+ * Copyright (c) 2010, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include <config.h>
+#include "roken.h"
+
+/* rename() for platforms where the native implementation doesn't
+ * unlink newname. */
+int rk_rename(const char * oldname, const char * newname)
+{
+ int ret;
+
+ ret = rename(oldname, newname);
+ if (ret != 0 && (errno == EEXIST || errno == EACCES)) {
+ ret = unlink(newname);
+ if (ret == 0)
+ ret = rename(oldname, newname);
+ }
+
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/resolve-test.c b/third_party/heimdal/lib/roken/resolve-test.c
new file mode 100644
index 0000000..581600a
--- /dev/null
+++ b/third_party/heimdal/lib/roken/resolve-test.c
@@ -0,0 +1,309 @@
+/*
+ * Copyright (c) 1995 - 2016 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+
+#include <config.h>
+
+#include "roken.h"
+#include "getarg.h"
+#include <assert.h>
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+#ifdef HAVE_RESOLV_H
+#include <resolv.h>
+#endif
+#include "resolve.h"
+
+static int srv_rr_order = 1;
+static int loop_integer = 1;
+static int version_flag = 0;
+static int help_flag = 0;
+
+static struct getargs args[] = {
+ {"srv-rr-order", 0,
+ arg_negative_flag, &srv_rr_order,
+ "do not test SRV RR ordering", NULL },
+ {"loop", 0, arg_integer, &loop_integer,
+ "loop resolving", NULL },
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage (args,
+ sizeof(args)/sizeof(*args),
+ NULL,
+ "dns-record resource-record-type");
+ exit (ret);
+}
+
+#define NUMRRS 16
+
+static
+int
+test_rk_dns_srv_order(size_t run)
+{
+ struct rk_dns_reply reply;
+ struct rk_resource_record rrs[NUMRRS];
+ struct rk_resource_record *rr;
+ struct rk_srv_record srvs[NUMRRS];
+ size_t i, prio0;
+ int fail = 0;
+
+ (void) memset(&reply, 0, sizeof(reply));
+ (void) memset(srvs, 0, sizeof(srvs));
+ (void) memset(rrs, 0, sizeof(rrs));
+
+ /* Test with two equal weight zero SRV records */
+ rrs[0].type = rk_ns_t_srv;
+ rrs[0].u.srv = &srvs[0];
+ rrs[0].next = &rrs[1];
+ srvs[0].priority = 10;
+ srvs[0].weight = 0;
+
+ rrs[1].type = rk_ns_t_srv;
+ rrs[1].u.srv = &srvs[1];
+ rrs[1].next = NULL;
+ srvs[1].priority = 10;
+ srvs[1].weight = 0;
+ reply.head = &rrs[0];
+
+ rk_dns_srv_order(&reply);
+ assert(reply.head != NULL);
+ printf("%p %p\n", &rrs[0], rrs[0].next);
+
+ /*
+ * Test four priority groups with priority 1--5 and weigths 0--3 in the
+ * first two groups, and 1--4 in the last two groups. Test multiple zero
+ * weights, by further coercing the weight to zero if <= run/2.
+ */
+ for (i = 0; i < NUMRRS; i++) {
+ rrs[i].type = rk_ns_t_srv;
+ rrs[i].u.srv = &srvs[i];
+ srvs[i].priority = 1 + i / 4;
+ srvs[i].weight = i % 4 + i / 8;
+ if (srvs[i].weight <= run/2)
+ srvs[i].weight = 0;
+ }
+ /* Shuffle the RRs */
+ for (i = 0; i < NUMRRS - 1; i++) {
+ struct rk_resource_record tmp;
+ size_t j = rk_random() % (NUMRRS - i);
+
+ if (j > 0) {
+ tmp = rrs[i+j];
+ rrs[i+j] = rrs[i];
+ rrs[i] = tmp;
+ }
+ }
+ for (i = 0; i < NUMRRS; i++)
+ rrs[i].next = &rrs[i + 1];
+ rrs[i - 1].next = NULL;
+ reply.head = &rrs[0];
+
+ for (i = 0, rr = reply.head; i < NUMRRS; i++) {
+ if (rr == NULL)
+ break;
+ printf("SRV RR order run %lu input: prio %lu weight %lu\n",
+ (unsigned long)run, (unsigned long)rr->u.srv->priority,
+ (unsigned long)rr->u.srv->weight);
+ rr = rr->next;
+ }
+
+ rk_dns_srv_order(&reply);
+ assert(reply.head != NULL);
+
+ /*
+ * After sorting, ensure monotone priority ordering with jumps by 1 at
+ * group boundaries.
+ */
+ prio0 = 0;
+ for (i = 0, rr = reply.head; i < NUMRRS; i++) {
+ if (rr == NULL)
+ break;
+ if (rr->u.srv->priority < prio0 ||
+ (rr->u.srv->priority != prio0 &&
+ (i % 4 != 0 || rr->u.srv->priority > prio0 + 1))) {
+ printf("SRV RR order run %zu failed\n", run);
+ fail = 1;
+ }
+ prio0 = rr->u.srv->priority;
+ printf("SRV RR order run %lu output: prio %lu weight %lu\n",
+ (unsigned long)run, (unsigned long)rr->u.srv->priority,
+ (unsigned long)rr->u.srv->weight);
+ rr = rr->next;
+ }
+ assert(i == NUMRRS);
+
+ return fail;
+}
+
+int
+main(int argc, char **argv)
+{
+ struct rk_dns_reply *r;
+ struct rk_resource_record *rr;
+ int optidx = 0, i, exit_code = 0;
+
+ setprogname (argv[0]);
+ rk_random_init();
+
+ if (getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if (version_flag) {
+ printf("some version\n");
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (argc != 2 && argc != 0 && !srv_rr_order)
+ usage(1);
+
+ if (srv_rr_order) {
+ exit_code += test_rk_dns_srv_order(0);
+ exit_code += test_rk_dns_srv_order(1);
+ exit_code += test_rk_dns_srv_order(2);
+ exit_code += test_rk_dns_srv_order(3);
+ exit_code += test_rk_dns_srv_order(4);
+ exit_code += test_rk_dns_srv_order(5);
+ }
+
+ if (srv_rr_order && argc == 0)
+ exit(exit_code ? 1 : 0);
+
+ if (argc != 2)
+ usage(1);
+
+ for (i = 0; i < loop_integer; i++) {
+
+ r = rk_dns_lookup(argv[0], argv[1]);
+ if (r == NULL) {
+ printf("No reply.\n");
+ exit_code = 1;
+ break;
+ }
+ if (r->q.type == rk_ns_t_srv)
+ rk_dns_srv_order(r);
+
+ for (rr = r->head; rr;rr=rr->next) {
+ printf("%-30s %-5s %-6d ", rr->domain, rk_dns_type_to_string(rr->type), rr->ttl);
+ switch (rr->type) {
+ case rk_ns_t_ns:
+ case rk_ns_t_cname:
+ case rk_ns_t_ptr:
+ printf("%s\n", (char*)rr->u.data);
+ break;
+ case rk_ns_t_a:
+ printf("%s\n", inet_ntoa(*rr->u.a));
+ break;
+ case rk_ns_t_mx:
+ case rk_ns_t_afsdb: {
+ printf("%d %s\n", rr->u.mx->preference, rr->u.mx->domain);
+ break;
+ }
+ case rk_ns_t_srv: {
+ struct rk_srv_record *srv = rr->u.srv;
+ printf("%d %d %d %s\n", srv->priority, srv->weight,
+ srv->port, srv->target);
+ break;
+ }
+ case rk_ns_t_txt: {
+ printf("%s\n", rr->u.txt);
+ break;
+ }
+ case rk_ns_t_sig: {
+ struct rk_sig_record *sig = rr->u.sig;
+ const char *type_string = rk_dns_type_to_string (sig->type);
+
+ printf("type %u (%s), algorithm %u, labels %u, orig_ttl %u, "
+ "sig_expiration %u, sig_inception %u, key_tag %u, "
+ "signer %s\n",
+ sig->type, type_string ? type_string : "",
+ sig->algorithm, sig->labels, sig->orig_ttl,
+ sig->sig_expiration, sig->sig_inception, sig->key_tag,
+ sig->signer);
+ break;
+ }
+ case rk_ns_t_key: {
+ struct rk_key_record *key = rr->u.key;
+
+ printf("flags %u, protocol %u, algorithm %u\n",
+ key->flags, key->protocol, key->algorithm);
+ break;
+ }
+ case rk_ns_t_sshfp: {
+ struct rk_sshfp_record *sshfp = rr->u.sshfp;
+ size_t j;
+
+ printf ("alg %u type %u length %lu data ", sshfp->algorithm,
+ sshfp->type, (unsigned long)sshfp->sshfp_len);
+ for (j = 0; j < sshfp->sshfp_len; j++)
+ printf("%02X", sshfp->sshfp_data[j]);
+ printf("\n");
+
+ break;
+ }
+ case rk_ns_t_ds: {
+ struct rk_ds_record *ds = rr->u.ds;
+ size_t j;
+
+ printf("key tag %u alg %u type %u length %lu data ",
+ ds->key_tag, ds->algorithm, ds->digest_type,
+ (unsigned long)ds->digest_len);
+ for (j = 0; j < ds->digest_len; j++)
+ printf("%02X", ds->digest_data[j]);
+ printf("\n");
+
+ break;
+ }
+ default:
+ printf("\n");
+ break;
+ }
+ }
+ rk_dns_free_data(r);
+ }
+
+ return exit_code ? 1 : 0;
+}
diff --git a/third_party/heimdal/lib/roken/resolve.c b/third_party/heimdal/lib/roken/resolve.c
new file mode 100644
index 0000000..31da413
--- /dev/null
+++ b/third_party/heimdal/lib/roken/resolve.c
@@ -0,0 +1,956 @@
+/*
+ * Copyright (c) 1995 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+
+#include <config.h>
+
+#include "roken.h"
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+#ifdef HAVE_RESOLV_H
+#include <resolv.h>
+#endif
+#ifdef HAVE_DNS_H
+#include <dns.h>
+#endif
+#include "resolve.h"
+
+#include <assert.h>
+
+#ifdef _AIX /* AIX have broken res_nsearch() in 5.1 (5.0 also ?) */
+#undef HAVE_RES_NSEARCH
+#endif
+
+#define DECL(X) {#X, rk_ns_t_##X}
+
+static struct stot{
+ const char *name;
+ int type;
+}stot[] = {
+ DECL(a),
+ DECL(aaaa),
+ DECL(ns),
+ DECL(cname),
+ DECL(soa),
+ DECL(ptr),
+ DECL(mx),
+ DECL(txt),
+ DECL(afsdb),
+ DECL(sig),
+ DECL(key),
+ DECL(srv),
+ DECL(naptr),
+ DECL(sshfp),
+ DECL(ds),
+ {NULL, 0}
+};
+
+int _resolve_debug = 0;
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_dns_string_to_type(const char *name)
+{
+ struct stot *p = stot;
+ for(p = stot; p->name; p++)
+ if(strcasecmp(name, p->name) == 0)
+ return p->type;
+ return -1;
+}
+
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
+rk_dns_type_to_string(int type)
+{
+ struct stot *p = stot;
+ for(p = stot; p->name; p++)
+ if(type == p->type)
+ return p->name;
+ return NULL;
+}
+
+#if ((defined(HAVE_RES_SEARCH) || defined(HAVE_RES_NSEARCH)) && defined(HAVE_DN_EXPAND)) || defined(HAVE_WINDNS)
+
+static void
+dns_free_rr(struct rk_resource_record *rr)
+{
+ if(rr->domain)
+ free(rr->domain);
+ if(rr->u.data)
+ free(rr->u.data);
+ free(rr);
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_dns_free_data(struct rk_dns_reply *r)
+{
+ struct rk_resource_record *rr;
+ if(r->q.domain)
+ free(r->q.domain);
+ for(rr = r->head; rr;){
+ struct rk_resource_record *tmp = rr;
+ rr = rr->next;
+ dns_free_rr(tmp);
+ }
+ free (r);
+}
+
+#ifndef HAVE_WINDNS
+
+static int
+parse_record(const unsigned char *data, const unsigned char *end_data,
+ const unsigned char **pp, struct rk_resource_record **ret_rr)
+{
+ struct rk_resource_record *rr;
+ int type, class, ttl;
+ unsigned size;
+ int status;
+ char host[MAXDNAME];
+ const unsigned char *p = *pp;
+
+ *ret_rr = NULL;
+
+ status = dn_expand(data, end_data, p, host, sizeof(host));
+ if(status < 0)
+ return -1;
+ if (p + status + 10 > end_data)
+ return -1;
+
+ p += status;
+ type = (p[0] << 8) | p[1];
+ p += 2;
+ class = (p[0] << 8) | p[1];
+ p += 2;
+ ttl = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
+ p += 4;
+ size = (p[0] << 8) | p[1];
+ p += 2;
+
+ if (p + size > end_data)
+ return -1;
+
+ rr = calloc(1, sizeof(*rr));
+ if(rr == NULL)
+ return -1;
+ rr->domain = strdup(host);
+ if(rr->domain == NULL) {
+ dns_free_rr(rr);
+ return -1;
+ }
+ rr->type = type;
+ rr->class = class;
+ rr->ttl = ttl;
+ rr->size = size;
+ switch(type){
+ case rk_ns_t_ns:
+ case rk_ns_t_cname:
+ case rk_ns_t_ptr:
+ status = dn_expand(data, end_data, p, host, sizeof(host));
+ if(status < 0) {
+ dns_free_rr(rr);
+ return -1;
+ }
+ rr->u.txt = strdup(host);
+ if(rr->u.txt == NULL) {
+ dns_free_rr(rr);
+ return -1;
+ }
+ break;
+ case rk_ns_t_mx:
+ case rk_ns_t_afsdb:{
+ size_t hostlen;
+
+ status = dn_expand(data, end_data, p + 2, host, sizeof(host));
+ if(status < 0){
+ dns_free_rr(rr);
+ return -1;
+ }
+ if ((size_t)status + 2 > size) {
+ dns_free_rr(rr);
+ return -1;
+ }
+
+ hostlen = strlen(host);
+ rr->u.mx = (struct mx_record*)malloc(sizeof(struct mx_record) +
+ hostlen);
+ if(rr->u.mx == NULL) {
+ dns_free_rr(rr);
+ return -1;
+ }
+ rr->u.mx->preference = (p[0] << 8) | p[1];
+ strlcpy(rr->u.mx->domain, host, hostlen + 1);
+ break;
+ }
+ case rk_ns_t_srv:{
+ size_t hostlen;
+ status = dn_expand(data, end_data, p + 6, host, sizeof(host));
+ if(status < 0){
+ dns_free_rr(rr);
+ return -1;
+ }
+ if ((size_t)status + 6 > size) {
+ dns_free_rr(rr);
+ return -1;
+ }
+
+ hostlen = strlen(host);
+ rr->u.srv =
+ (struct srv_record*)malloc(sizeof(struct srv_record) +
+ hostlen);
+ if(rr->u.srv == NULL) {
+ dns_free_rr(rr);
+ return -1;
+ }
+ rr->u.srv->priority = (p[0] << 8) | p[1];
+ rr->u.srv->weight = (p[2] << 8) | p[3];
+ rr->u.srv->port = (p[4] << 8) | p[5];
+ strlcpy(rr->u.srv->target, host, hostlen + 1);
+ break;
+ }
+ case rk_ns_t_txt:{
+ if(size == 0 || size < (unsigned)(*p + 1)) {
+ dns_free_rr(rr);
+ return -1;
+ }
+ rr->u.txt = (char*)malloc(*p + 1);
+ if(rr->u.txt == NULL) {
+ dns_free_rr(rr);
+ return -1;
+ }
+ strncpy(rr->u.txt, (const char*)(p + 1), *p);
+ rr->u.txt[*p] = '\0';
+ break;
+ }
+ case rk_ns_t_key : {
+ size_t key_len;
+
+ if (size < 4) {
+ dns_free_rr(rr);
+ return -1;
+ }
+
+ key_len = size - 4;
+ rr->u.key = malloc (sizeof(*rr->u.key) + key_len - 1);
+ if (rr->u.key == NULL) {
+ dns_free_rr(rr);
+ return -1;
+ }
+
+ rr->u.key->flags = (p[0] << 8) | p[1];
+ rr->u.key->protocol = p[2];
+ rr->u.key->algorithm = p[3];
+ rr->u.key->key_len = key_len;
+ memcpy (rr->u.key->key_data, p + 4, key_len);
+ break;
+ }
+ case rk_ns_t_sig : {
+ size_t sig_len, hostlen;
+
+ if(size <= 18) {
+ dns_free_rr(rr);
+ return -1;
+ }
+ status = dn_expand (data, end_data, p + 18, host, sizeof(host));
+ if (status < 0) {
+ dns_free_rr(rr);
+ return -1;
+ }
+ if ((size_t)status + 18 > size) {
+ dns_free_rr(rr);
+ return -1;
+ }
+
+ /* the signer name is placed after the sig_data, to make it
+ easy to free this structure; the size calculation below
+ includes the zero-termination if the structure itself.
+ don't you just love C?
+ */
+ sig_len = size - 18 - status;
+ hostlen = strlen(host);
+ rr->u.sig = malloc(sizeof(*rr->u.sig)
+ + hostlen + sig_len);
+ if (rr->u.sig == NULL) {
+ dns_free_rr(rr);
+ return -1;
+ }
+ rr->u.sig->type = (p[0] << 8) | p[1];
+ rr->u.sig->algorithm = p[2];
+ rr->u.sig->labels = p[3];
+ rr->u.sig->orig_ttl = (p[4] << 24) | (p[5] << 16)
+ | (p[6] << 8) | p[7];
+ rr->u.sig->sig_expiration = (p[8] << 24) | (p[9] << 16)
+ | (p[10] << 8) | p[11];
+ rr->u.sig->sig_inception = (p[12] << 24) | (p[13] << 16)
+ | (p[14] << 8) | p[15];
+ rr->u.sig->key_tag = (p[16] << 8) | p[17];
+ rr->u.sig->sig_len = sig_len;
+ memcpy (rr->u.sig->sig_data, p + 18 + status, sig_len);
+ rr->u.sig->signer = &rr->u.sig->sig_data[sig_len];
+ strlcpy(rr->u.sig->signer, host, hostlen + 1);
+ break;
+ }
+
+ case rk_ns_t_cert : {
+ size_t cert_len;
+
+ if (size < 5) {
+ dns_free_rr(rr);
+ return -1;
+ }
+
+ cert_len = size - 5;
+ rr->u.cert = malloc (sizeof(*rr->u.cert) + cert_len - 1);
+ if (rr->u.cert == NULL) {
+ dns_free_rr(rr);
+ return -1;
+ }
+
+ rr->u.cert->type = (p[0] << 8) | p[1];
+ rr->u.cert->tag = (p[2] << 8) | p[3];
+ rr->u.cert->algorithm = p[4];
+ rr->u.cert->cert_len = cert_len;
+ memcpy (rr->u.cert->cert_data, p + 5, cert_len);
+ break;
+ }
+ case rk_ns_t_sshfp : {
+ size_t sshfp_len;
+
+ if (size < 2) {
+ dns_free_rr(rr);
+ return -1;
+ }
+
+ sshfp_len = size - 2;
+
+ rr->u.sshfp = malloc (sizeof(*rr->u.sshfp) + sshfp_len - 1);
+ if (rr->u.sshfp == NULL) {
+ dns_free_rr(rr);
+ return -1;
+ }
+
+ rr->u.sshfp->algorithm = p[0];
+ rr->u.sshfp->type = p[1];
+ rr->u.sshfp->sshfp_len = sshfp_len;
+ memcpy (rr->u.sshfp->sshfp_data, p + 2, sshfp_len);
+ break;
+ }
+ case rk_ns_t_ds: {
+ size_t digest_len;
+
+ if (size < 4) {
+ dns_free_rr(rr);
+ return -1;
+ }
+
+ digest_len = size - 4;
+
+ rr->u.ds = malloc (sizeof(*rr->u.ds) + digest_len - 1);
+ if (rr->u.ds == NULL) {
+ dns_free_rr(rr);
+ return -1;
+ }
+
+ rr->u.ds->key_tag = (p[0] << 8) | p[1];
+ rr->u.ds->algorithm = p[2];
+ rr->u.ds->digest_type = p[3];
+ rr->u.ds->digest_len = digest_len;
+ memcpy (rr->u.ds->digest_data, p + 4, digest_len);
+ break;
+ }
+ default:
+ rr->u.data = (unsigned char*)malloc(size);
+ if(size != 0 && rr->u.data == NULL) {
+ dns_free_rr(rr);
+ return -1;
+ }
+ if (size)
+ memcpy(rr->u.data, p, size);
+ }
+ *pp = p + size;
+ *ret_rr = rr;
+
+ return 0;
+}
+
+#ifndef TEST_RESOLVE
+static
+#endif
+struct rk_dns_reply*
+parse_reply(const unsigned char *data, size_t len)
+{
+ const unsigned char *p;
+ int status;
+ size_t i;
+ char host[MAXDNAME];
+ const unsigned char *end_data = data + len;
+ struct rk_dns_reply *r;
+ struct rk_resource_record **rr;
+
+ r = calloc(1, sizeof(*r));
+ if (r == NULL)
+ return NULL;
+
+ p = data;
+
+ r->h.id = (p[0] << 8) | p[1];
+ r->h.flags = 0;
+ if (p[2] & 0x01)
+ r->h.flags |= rk_DNS_HEADER_RESPONSE_FLAG;
+ r->h.opcode = (p[2] >> 1) & 0xf;
+ if (p[2] & 0x20)
+ r->h.flags |= rk_DNS_HEADER_AUTHORITIVE_ANSWER;
+ if (p[2] & 0x40)
+ r->h.flags |= rk_DNS_HEADER_TRUNCATED_MESSAGE;
+ if (p[2] & 0x80)
+ r->h.flags |= rk_DNS_HEADER_RECURSION_DESIRED;
+ if (p[3] & 0x01)
+ r->h.flags |= rk_DNS_HEADER_RECURSION_AVAILABLE;
+ if (p[3] & 0x04)
+ r->h.flags |= rk_DNS_HEADER_AUTHORITIVE_ANSWER;
+ if (p[3] & 0x08)
+ r->h.flags |= rk_DNS_HEADER_CHECKING_DISABLED;
+ r->h.response_code = (p[3] >> 4) & 0xf;
+ r->h.qdcount = (p[4] << 8) | p[5];
+ r->h.ancount = (p[6] << 8) | p[7];
+ r->h.nscount = (p[8] << 8) | p[9];
+ r->h.arcount = (p[10] << 8) | p[11];
+
+ p += 12;
+
+ if(r->h.qdcount != 1) {
+ free(r);
+ return NULL;
+ }
+ status = dn_expand(data, end_data, p, host, sizeof(host));
+ if(status < 0){
+ rk_dns_free_data(r);
+ return NULL;
+ }
+ r->q.domain = strdup(host);
+ if(r->q.domain == NULL) {
+ rk_dns_free_data(r);
+ return NULL;
+ }
+ if (p + status + 4 > end_data) {
+ rk_dns_free_data(r);
+ return NULL;
+ }
+ p += status;
+ r->q.type = (p[0] << 8 | p[1]);
+ p += 2;
+ r->q.class = (p[0] << 8 | p[1]);
+ p += 2;
+
+ rr = &r->head;
+ for(i = 0; i < r->h.ancount; i++) {
+ if(parse_record(data, end_data, &p, rr) != 0) {
+ rk_dns_free_data(r);
+ return NULL;
+ }
+ rr = &(*rr)->next;
+ }
+ for(i = 0; i < r->h.nscount; i++) {
+ if(parse_record(data, end_data, &p, rr) != 0) {
+ rk_dns_free_data(r);
+ return NULL;
+ }
+ rr = &(*rr)->next;
+ }
+ for(i = 0; i < r->h.arcount; i++) {
+ if(parse_record(data, end_data, &p, rr) != 0) {
+ rk_dns_free_data(r);
+ return NULL;
+ }
+ rr = &(*rr)->next;
+ }
+ *rr = NULL;
+ return r;
+}
+
+#ifdef HAVE_RES_NSEARCH
+#ifdef HAVE_RES_NDESTROY
+#define rk_res_free(x) res_ndestroy(x)
+#else
+#define rk_res_free(x) res_nclose(x)
+#endif
+#endif
+
+#if defined(HAVE_DNS_SEARCH)
+#define resolve_search(h,n,c,t,r,l) \
+ ((int)dns_search(h,n,c,t,r,l,(struct sockaddr *)&from,&fromsize))
+#define resolve_free_handle(h) dns_free(h)
+#elif defined(HAVE_RES_NSEARCH)
+#define resolve_search(h,n,c,t,r,l) res_nsearch(h,n,c,t,r,l)
+#define resolve_free_handle(h) rk_res_free(h);
+#else
+#define resolve_search(h,n,c,t,r,l) res_search(n,c,t,r,l)
+#define handle 0
+#define resolve_free_handle(h)
+#endif
+
+
+static struct rk_dns_reply *
+dns_lookup_int(const char *domain, int rr_class, int rr_type)
+{
+ struct rk_dns_reply *r;
+ void *reply = NULL;
+ int size, len;
+#if defined(HAVE_DNS_SEARCH)
+ struct sockaddr_storage from;
+ uint32_t fromsize = sizeof(from);
+ dns_handle_t handle;
+
+ handle = dns_open(NULL);
+ if (handle == NULL)
+ return NULL;
+#elif defined(HAVE_RES_NSEARCH)
+ struct __res_state state;
+ struct __res_state *handle = &state;
+
+ memset(&state, 0, sizeof(state));
+ if(res_ninit(handle))
+ return NULL; /* is this the best we can do? */
+#endif
+
+ len = 1500;
+ while(1) {
+ if (reply) {
+ free(reply);
+ reply = NULL;
+ }
+ if (_resolve_debug) {
+#if defined(HAVE_DNS_SEARCH)
+ dns_set_debug(handle, 1);
+#elif defined(HAVE_RES_NSEARCH)
+ state.options |= RES_DEBUG;
+#endif
+ fprintf(stderr, "dns_lookup(%s, %d, %s), buffer size %d\n", domain,
+ rr_class, rk_dns_type_to_string(rr_type), len);
+ }
+ reply = malloc(len);
+ if (reply == NULL) {
+ resolve_free_handle(handle);
+ return NULL;
+ }
+
+ size = resolve_search(handle, domain, rr_class, rr_type, reply, len);
+
+ if (_resolve_debug) {
+ fprintf(stderr, "dns_lookup(%s, %d, %s) --> %d\n",
+ domain, rr_class, rk_dns_type_to_string(rr_type), size);
+ }
+ if (size > len) {
+ /* resolver thinks it know better, go for it */
+ len = size;
+ } else if (size > 0) {
+ /* got a good reply */
+ break;
+ } else if (size <= 0 && len < rk_DNS_MAX_PACKET_SIZE) {
+ len *= 2;
+ if (len > rk_DNS_MAX_PACKET_SIZE)
+ len = rk_DNS_MAX_PACKET_SIZE;
+ } else {
+ /* the end, leave */
+ resolve_free_handle(handle);
+ free(reply);
+ return NULL;
+ }
+ }
+
+ len = min(len, size);
+ r = parse_reply(reply, len);
+ free(reply);
+
+ resolve_free_handle(handle);
+
+ return r;
+}
+
+ROKEN_LIB_FUNCTION struct rk_dns_reply * ROKEN_LIB_CALL
+rk_dns_lookup(const char *domain, const char *type_name)
+{
+ int type;
+
+ type = rk_dns_string_to_type(type_name);
+ if(type == -1) {
+ if(_resolve_debug)
+ fprintf(stderr, "dns_lookup: unknown resource type: `%s'\n",
+ type_name);
+ return NULL;
+ }
+ return dns_lookup_int(domain, rk_ns_c_in, type);
+}
+
+#endif /* !HAVE_WINDNS */
+
+static int
+compare_srv(const void *a, const void *b)
+{
+ const struct rk_resource_record *const* aa = a, *const* bb = b;
+
+ if((*aa)->u.srv->priority == (*bb)->u.srv->priority)
+ return ((*aa)->u.srv->weight - (*bb)->u.srv->weight);
+ return ((*aa)->u.srv->priority - (*bb)->u.srv->priority);
+}
+
+/* try to rearrange the srv-records by the algorithm in RFC2782 */
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_dns_srv_order(struct rk_dns_reply *r)
+{
+ struct rk_resource_record **srvs, **ss, **headp;
+ struct rk_resource_record *rr;
+ int num_srv = 0;
+ unsigned int srv_found = FALSE;
+
+ rk_random_init();
+
+ for(rr = r->head; rr; rr = rr->next)
+ if(rr->type == rk_ns_t_srv) {
+ num_srv++;
+ srv_found = TRUE;
+ }
+
+ if(srv_found == FALSE)
+ return;
+
+ srvs = malloc(num_srv * sizeof(*srvs));
+ if(srvs == NULL)
+ return; /* XXX not much to do here */
+
+ /* unlink all srv-records from the linked list and put them in
+ a vector */
+ for(ss = srvs, headp = &r->head; *headp; )
+ if((*headp)->type == rk_ns_t_srv) {
+ *ss = *headp;
+ *headp = (*headp)->next;
+ (*ss)->next = NULL;
+ ss++;
+ } else
+ headp = &(*headp)->next;
+
+ /* sort them by priority and weight */
+ qsort(srvs, num_srv, sizeof(*srvs), compare_srv);
+
+ headp = &r->head;
+
+ for (ss = srvs; ss < srvs + num_srv; ) {
+ int sum, zeros, rnd, count; /* zeros -> weight scaling */
+ struct rk_resource_record **ee, **tt;
+
+ /*
+ * find the last record with the same priority and count the sum of all
+ * weights
+ */
+ for (sum = 0, zeros = 0, tt = ss; tt < srvs + num_srv; tt++) {
+ assert(*tt != NULL);
+ if((*tt)->u.srv->priority != (*ss)->u.srv->priority)
+ break;
+ sum += (*tt)->u.srv->weight;
+ if ((*tt)->u.srv->weight == 0)
+ zeros++;
+ }
+ /* make sure scale (`zeros') is > 0 then scale out */
+ sum += zeros ? 1 : zeros++;
+ sum *= zeros;
+ ee = tt;
+
+ /*
+ * ss is now the first record of this priority and ee is the first of
+ * the next or the first past the end of srvs
+ */
+ while (ss < ee) {
+ rnd = rk_random() % sum + 1;
+ for (count = 0, tt = ss; tt < ee; tt++) {
+ if (*tt == NULL)
+ continue; /* this one's already been picked */
+ if ((*tt)->u.srv->weight == 0)
+ count++;
+ else
+ count += (*tt)->u.srv->weight * zeros;
+ if (count >= rnd)
+ break;
+ }
+ assert(tt < ee);
+
+ /* push the selected record */
+ (*tt)->next = *headp;
+ *headp = *tt;
+ headp = &(*tt)->next;
+ /*
+ * reduce the sum so the next iteration is sure to reach the random
+ * total after examining all the remaining records.
+ */
+ if ((*tt)->u.srv->weight == 0)
+ sum--;
+ else
+ sum -= (*tt)->u.srv->weight * zeros;
+ *tt = NULL;
+ while (ss < ee && *ss == NULL)
+ ss++;
+ }
+ }
+
+ free(srvs);
+ return;
+}
+
+#ifdef HAVE_WINDNS
+
+#include <WinDNS.h>
+
+static struct rk_resource_record *
+parse_dns_record(PDNS_RECORD pRec)
+{
+ struct rk_resource_record * rr;
+
+ if (pRec == NULL)
+ return NULL;
+
+ rr = calloc(1, sizeof(*rr));
+
+ rr->domain = strdup(pRec->pName);
+ rr->type = pRec->wType;
+ rr->class = 0;
+ rr->ttl = pRec->dwTtl;
+ rr->size = 0;
+
+ switch (rr->type) {
+ case rk_ns_t_ns:
+ case rk_ns_t_cname:
+ case rk_ns_t_ptr:
+ rr->u.txt = strdup(pRec->Data.NS.pNameHost);
+ if(rr->u.txt == NULL) {
+ dns_free_rr(rr);
+ return NULL;
+ }
+ break;
+
+ case rk_ns_t_mx:
+ case rk_ns_t_afsdb:{
+ size_t hostlen = strnlen(pRec->Data.MX.pNameExchange, DNS_MAX_NAME_LENGTH);
+
+ rr->u.mx = (struct mx_record *)malloc(sizeof(struct mx_record) +
+ hostlen);
+ if (rr->u.mx == NULL) {
+ dns_free_rr(rr);
+ return NULL;
+ }
+
+ strcpy_s(rr->u.mx->domain, hostlen + 1, pRec->Data.MX.pNameExchange);
+ rr->u.mx->preference = pRec->Data.MX.wPreference;
+ break;
+ }
+
+ case rk_ns_t_srv:{
+ size_t hostlen = strnlen(pRec->Data.SRV.pNameTarget, DNS_MAX_NAME_LENGTH);
+
+ rr->u.srv =
+ (struct srv_record*)malloc(sizeof(struct srv_record) +
+ hostlen);
+ if(rr->u.srv == NULL) {
+ dns_free_rr(rr);
+ return NULL;
+ }
+
+ rr->u.srv->priority = pRec->Data.SRV.wPriority;
+ rr->u.srv->weight = pRec->Data.SRV.wWeight;
+ rr->u.srv->port = pRec->Data.SRV.wPort;
+ strcpy_s(rr->u.srv->target, hostlen + 1, pRec->Data.SRV.pNameTarget);
+
+ break;
+ }
+
+ case rk_ns_t_txt:{
+ size_t len;
+
+ if (pRec->Data.TXT.dwStringCount == 0) {
+ rr->u.txt = strdup("");
+ break;
+ }
+
+ len = strnlen(pRec->Data.TXT.pStringArray[0], DNS_MAX_TEXT_STRING_LENGTH);
+
+ rr->u.txt = (char *)malloc(len + 1);
+ strcpy_s(rr->u.txt, len + 1, pRec->Data.TXT.pStringArray[0]);
+
+ break;
+ }
+
+ case rk_ns_t_key : {
+ size_t key_len;
+
+ if (pRec->wDataLength < 4) {
+ dns_free_rr(rr);
+ return NULL;
+ }
+
+ key_len = pRec->wDataLength - 4;
+ rr->u.key = malloc (sizeof(*rr->u.key) + key_len - 1);
+ if (rr->u.key == NULL) {
+ dns_free_rr(rr);
+ return NULL;
+ }
+
+ rr->u.key->flags = pRec->Data.KEY.wFlags;
+ rr->u.key->protocol = pRec->Data.KEY.chProtocol;
+ rr->u.key->algorithm = pRec->Data.KEY.chAlgorithm;
+ rr->u.key->key_len = key_len;
+ memcpy_s (rr->u.key->key_data, key_len,
+ pRec->Data.KEY.Key, key_len);
+ break;
+ }
+
+ case rk_ns_t_sig : {
+ size_t sig_len, hostlen;
+
+ if(pRec->wDataLength <= 18) {
+ dns_free_rr(rr);
+ return NULL;
+ }
+
+ sig_len = pRec->wDataLength;
+
+ hostlen = strnlen(pRec->Data.SIG.pNameSigner, DNS_MAX_NAME_LENGTH);
+
+ rr->u.sig = malloc(sizeof(*rr->u.sig)
+ + hostlen + sig_len);
+ if (rr->u.sig == NULL) {
+ dns_free_rr(rr);
+ return NULL;
+ }
+ rr->u.sig->type = pRec->Data.SIG.wTypeCovered;
+ rr->u.sig->algorithm = pRec->Data.SIG.chAlgorithm;
+ rr->u.sig->labels = pRec->Data.SIG.chLabelCount;
+ rr->u.sig->orig_ttl = pRec->Data.SIG.dwOriginalTtl;
+ rr->u.sig->sig_expiration = pRec->Data.SIG.dwExpiration;
+ rr->u.sig->sig_inception = pRec->Data.SIG.dwTimeSigned;
+ rr->u.sig->key_tag = pRec->Data.SIG.wKeyTag;
+ rr->u.sig->sig_len = sig_len;
+ memcpy_s (rr->u.sig->sig_data, sig_len,
+ pRec->Data.SIG.Signature, sig_len);
+ rr->u.sig->signer = &rr->u.sig->sig_data[sig_len];
+ strcpy_s(rr->u.sig->signer, hostlen + 1, pRec->Data.SIG.pNameSigner);
+ break;
+ }
+
+#ifdef DNS_TYPE_DS
+ case rk_ns_t_ds: {
+ rr->u.ds = malloc (sizeof(*rr->u.ds) + pRec->Data.DS.wDigestLength - 1);
+ if (rr->u.ds == NULL) {
+ dns_free_rr(rr);
+ return NULL;
+ }
+
+ rr->u.ds->key_tag = pRec->Data.DS.wKeyTag;
+ rr->u.ds->algorithm = pRec->Data.DS.chAlgorithm;
+ rr->u.ds->digest_type = pRec->Data.DS.chDigestType;
+ rr->u.ds->digest_len = pRec->Data.DS.wDigestLength;
+ memcpy_s (rr->u.ds->digest_data, pRec->Data.DS.wDigestLength,
+ pRec->Data.DS.Digest, pRec->Data.DS.wDigestLength);
+ break;
+ }
+#endif
+
+ default:
+ dns_free_rr(rr);
+ return NULL;
+ }
+
+ rr->next = parse_dns_record(pRec->pNext);
+ return rr;
+}
+
+ROKEN_LIB_FUNCTION struct rk_dns_reply * ROKEN_LIB_CALL
+rk_dns_lookup(const char *domain, const char *type_name)
+{
+ DNS_STATUS status;
+ int type;
+ PDNS_RECORD pRec = NULL;
+ struct rk_dns_reply * r = NULL;
+
+ __try {
+
+ type = rk_dns_string_to_type(type_name);
+ if(type == -1) {
+ if(_resolve_debug)
+ fprintf(stderr, "dns_lookup: unknown resource type: `%s'\n",
+ type_name);
+ return NULL;
+ }
+
+ status = DnsQuery_UTF8(domain, type, DNS_QUERY_STANDARD, NULL,
+ &pRec, NULL);
+ if (status != ERROR_SUCCESS)
+ return NULL;
+
+ r = calloc(1, sizeof(*r));
+ r->q.domain = strdup(domain);
+ r->q.type = type;
+ r->q.class = 0;
+
+ r->head = parse_dns_record(pRec);
+
+ if (r->head == NULL) {
+ rk_dns_free_data(r);
+ return NULL;
+ } else {
+ return r;
+ }
+
+ } __finally {
+
+ if (pRec)
+ DnsRecordListFree(pRec, DnsFreeRecordList);
+
+ }
+}
+#endif /* HAVE_WINDNS */
+
+#else /* NOT defined(HAVE_RES_SEARCH) && defined(HAVE_DN_EXPAND) */
+
+ROKEN_LIB_FUNCTION struct rk_dns_reply * ROKEN_LIB_CALL
+rk_dns_lookup(const char *domain, const char *type_name)
+{
+ return NULL;
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_dns_free_data(struct rk_dns_reply *r)
+{
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_dns_srv_order(struct rk_dns_reply *r)
+{
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/resolve.h b/third_party/heimdal/lib/roken/resolve.h
new file mode 100644
index 0000000..fc1e97f
--- /dev/null
+++ b/third_party/heimdal/lib/roken/resolve.h
@@ -0,0 +1,251 @@
+/*
+ * Copyright (c) 1995 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __RESOLVE_H__
+#define __RESOLVE_H__
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __cdecl
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+enum {
+ rk_ns_c_in = 1
+};
+
+enum {
+ rk_ns_t_invalid = 0, /* Cookie. */
+ rk_ns_t_a = 1, /* Host address. */
+ rk_ns_t_ns = 2, /* Authoritative server. */
+ rk_ns_t_md = 3, /* Mail destination. */
+ rk_ns_t_mf = 4, /* Mail forwarder. */
+ rk_ns_t_cname = 5, /* Canonical name. */
+ rk_ns_t_soa = 6, /* Start of authority zone. */
+ rk_ns_t_mb = 7, /* Mailbox domain name. */
+ rk_ns_t_mg = 8, /* Mail group member. */
+ rk_ns_t_mr = 9, /* Mail rename name. */
+ rk_ns_t_null = 10, /* Null resource record. */
+ rk_ns_t_wks = 11, /* Well known service. */
+ rk_ns_t_ptr = 12, /* Domain name pointer. */
+ rk_ns_t_hinfo = 13, /* Host information. */
+ rk_ns_t_minfo = 14, /* Mailbox information. */
+ rk_ns_t_mx = 15, /* Mail routing information. */
+ rk_ns_t_txt = 16, /* Text strings. */
+ rk_ns_t_rp = 17, /* Responsible person. */
+ rk_ns_t_afsdb = 18, /* AFS cell database. */
+ rk_ns_t_x25 = 19, /* X_25 calling address. */
+ rk_ns_t_isdn = 20, /* ISDN calling address. */
+ rk_ns_t_rt = 21, /* Router. */
+ rk_ns_t_nsap = 22, /* NSAP address. */
+ rk_ns_t_nsap_ptr = 23, /* Reverse NSAP lookup (deprecated). */
+ rk_ns_t_sig = 24, /* Security signature. */
+ rk_ns_t_key = 25, /* Security key. */
+ rk_ns_t_px = 26, /* X.400 mail mapping. */
+ rk_ns_t_gpos = 27, /* Geographical position (withdrawn). */
+ rk_ns_t_aaaa = 28, /* Ip6 Address. */
+ rk_ns_t_loc = 29, /* Location Information. */
+ rk_ns_t_nxt = 30, /* Next domain (security). */
+ rk_ns_t_eid = 31, /* Endpoint identifier. */
+ rk_ns_t_nimloc = 32, /* Nimrod Locator. */
+ rk_ns_t_srv = 33, /* Server Selection. */
+ rk_ns_t_atma = 34, /* ATM Address */
+ rk_ns_t_naptr = 35, /* Naming Authority PoinTeR */
+ rk_ns_t_kx = 36, /* Key Exchange */
+ rk_ns_t_cert = 37, /* Certification record */
+ rk_ns_t_a6 = 38, /* IPv6 address (deprecates AAAA) */
+ rk_ns_t_dname = 39, /* Non-terminal DNAME (for IPv6) */
+ rk_ns_t_sink = 40, /* Kitchen sink (experimentatl) */
+ rk_ns_t_opt = 41, /* EDNS0 option (meta-RR) */
+ rk_ns_t_apl = 42, /* Address prefix list (RFC 3123) */
+ rk_ns_t_ds = 43, /* Delegation Signer (RFC 3658) */
+ rk_ns_t_sshfp = 44, /* SSH fingerprint */
+ rk_ns_t_tkey = 249, /* Transaction key */
+ rk_ns_t_tsig = 250, /* Transaction signature. */
+ rk_ns_t_ixfr = 251, /* Incremental zone transfer. */
+ rk_ns_t_axfr = 252, /* Transfer zone of authority. */
+ rk_ns_t_mailb = 253, /* Transfer mailbox records. */
+ rk_ns_t_maila = 254, /* Transfer mail agent records. */
+ rk_ns_t_any = 255, /* Wildcard match. */
+ rk_ns_t_zxfr = 256, /* BIND-specific, nonstandard. */
+ rk_ns_t_max = 65536
+};
+
+#ifndef MAXDNAME
+#define MAXDNAME 1025
+#endif
+
+#define mx_record rk_mx_record
+#define srv_record rk_srv_record
+#define key_record rk_key_record
+#define sig_record rk_sig_record
+#define cert_record rk_cert_record
+#define sshfp_record rk_sshfp_record
+
+struct rk_dns_query{
+ char *domain;
+ unsigned type;
+ unsigned class;
+};
+
+struct rk_mx_record{
+ unsigned preference;
+ char domain[1];
+};
+
+struct rk_srv_record{
+ unsigned priority;
+ unsigned weight;
+ unsigned port;
+ char target[1];
+};
+
+struct rk_key_record {
+ unsigned flags;
+ unsigned protocol;
+ unsigned algorithm;
+ size_t key_len;
+ u_char key_data[1];
+};
+
+struct rk_sig_record {
+ unsigned type;
+ unsigned algorithm;
+ unsigned labels;
+ unsigned orig_ttl;
+ unsigned sig_expiration;
+ unsigned sig_inception;
+ unsigned key_tag;
+ char *signer;
+ size_t sig_len;
+ char sig_data[1]; /* also includes signer */
+};
+
+struct rk_cert_record {
+ unsigned type;
+ unsigned tag;
+ unsigned algorithm;
+ size_t cert_len;
+ u_char cert_data[1];
+};
+
+struct rk_sshfp_record {
+ unsigned algorithm;
+ unsigned type;
+ size_t sshfp_len;
+ u_char sshfp_data[1];
+};
+
+struct rk_ds_record {
+ unsigned key_tag;
+ unsigned algorithm;
+ unsigned digest_type;
+ size_t digest_len;
+ u_char digest_data[1];
+};
+
+struct rk_resource_record{
+ char *domain;
+ unsigned type;
+ unsigned class;
+ unsigned ttl;
+ unsigned size;
+ union {
+ void *data;
+ struct rk_mx_record *mx;
+ struct rk_mx_record *afsdb; /* mx and afsdb are identical */
+ struct rk_srv_record *srv;
+ struct in_addr *a;
+ char *txt;
+ struct rk_key_record *key;
+ struct rk_cert_record *cert;
+ struct rk_sig_record *sig;
+ struct rk_sshfp_record *sshfp;
+ struct rk_ds_record *ds;
+ }u;
+ struct rk_resource_record *next;
+};
+
+#define rk_DNS_MAX_PACKET_SIZE 0xffff
+
+struct rk_dns_header {
+ unsigned id;
+ unsigned flags;
+#define rk_DNS_HEADER_RESPONSE_FLAG 1
+#define rk_DNS_HEADER_AUTHORITIVE_ANSWER 2
+#define rk_DNS_HEADER_TRUNCATED_MESSAGE 4
+#define rk_DNS_HEADER_RECURSION_DESIRED 8
+#define rk_DNS_HEADER_RECURSION_AVAILABLE 16
+#define rk_DNS_HEADER_AUTHENTIC_DATA 32
+#define rk_DNS_HEADER_CHECKING_DISABLED 64
+ unsigned opcode;
+ unsigned response_code;
+ unsigned qdcount;
+ unsigned ancount;
+ unsigned nscount;
+ unsigned arcount;
+};
+
+struct rk_dns_reply{
+ struct rk_dns_header h;
+ struct rk_dns_query q;
+ struct rk_resource_record *head;
+};
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ROKEN_LIB_FUNCTION struct rk_dns_reply* ROKEN_LIB_CALL
+ rk_dns_lookup(const char *, const char *);
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+ rk_dns_free_data(struct rk_dns_reply *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_dns_string_to_type(const char *name);
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
+ rk_dns_type_to_string(int type);
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+ rk_dns_srv_order(struct rk_dns_reply*);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __RESOLVE_H__ */
diff --git a/third_party/heimdal/lib/roken/rkpty.c b/third_party/heimdal/lib/roken/rkpty.c
new file mode 100644
index 0000000..f7bfaca
--- /dev/null
+++ b/third_party/heimdal/lib/roken/rkpty.c
@@ -0,0 +1,392 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#ifndef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_WAIT_H
+#include <sys/wait.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_PTY_H
+#include <pty.h>
+#endif
+#ifdef HAVE_UTIL_H
+#include <util.h>
+#endif
+#ifdef HAVE_LIBUTIL_H
+#include <libutil.h>
+#endif
+
+#ifdef STREAMSPTY
+#include <stropts.h>
+#endif /* STREAMPTY */
+
+#include "roken.h"
+#include <getarg.h>
+
+struct command {
+ enum { CMD_EXPECT = 0, CMD_SEND, CMD_PASSWORD } type;
+ unsigned int lineno;
+ char *str;
+ struct command *next;
+};
+
+/*
+ *
+ */
+
+static struct command *commands, **next = &commands;
+
+static sig_atomic_t alarmset = 0;
+
+static int timeout = 10;
+static int verbose;
+static int help_flag;
+static int version_flag;
+
+static int master;
+static int slave;
+static char line[256] = { 0 };
+
+static void
+caught_signal(int signo)
+{
+ alarmset = signo;
+}
+
+
+static void
+open_pty(void)
+{
+#ifdef _AIX
+ printf("implement open_pty\n");
+ exit(77);
+#endif
+#if defined(HAVE_OPENPTY) || defined(__osf__) /* XXX */
+ if(openpty(&master, &slave, line, 0, 0) == 0)
+ return;
+#endif /* HAVE_OPENPTY .... */
+#ifdef STREAMSPTY
+ {
+ char *clone[] = {
+ "/dev/ptc",
+ "/dev/ptmx",
+ "/dev/ptm",
+ "/dev/ptym/clone",
+ NULL
+ };
+ char **q;
+
+ for(q = clone; *q; q++){
+ master = open(*q, O_RDWR);
+ if(master >= 0){
+#ifdef HAVE_GRANTPT
+ grantpt(master);
+#endif
+#ifdef HAVE_UNLOCKPT
+ unlockpt(master);
+#endif
+#ifdef HAVE_PTSNAME_R
+ if (ptsname_r(master, line, sizeof(line)) == -1)
+ err("Failed to open the pty master %s", *q);
+#else
+ {
+ char *s = ptsname(master);
+
+ if (s == NULL)
+ err("Failed to open the pty master %s", *q);
+ strlcpy(line, s, sizeof(line));
+ }
+#endif
+ slave = open(line, O_RDWR);
+ if (slave < 0)
+ errx(1, "failed to open slave when using %s", *q);
+ ioctl(slave, I_PUSH, "ptem");
+ ioctl(slave, I_PUSH, "ldterm");
+
+ return;
+ }
+ }
+ }
+#endif /* STREAMSPTY */
+
+ /* more cases, like open /dev/ptmx, etc */
+
+ exit(77);
+}
+
+/*
+ *
+ */
+
+static char *
+iscmd(const char *buf, const char *s)
+{
+ size_t len = strlen(s);
+ if (strncmp(buf, s, len) != 0)
+ return NULL;
+ return estrdup(buf + len);
+}
+
+static void
+parse_configuration(const char *fn)
+{
+ struct command *c;
+ char s[1024];
+ char *str;
+ unsigned int lineno = 0;
+ FILE *cmd;
+
+ cmd = fopen(fn, "r");
+ if (cmd == NULL)
+ err(1, "open: %s", fn);
+
+ while (fgets(s, sizeof(s), cmd) != NULL) {
+
+ s[strcspn(s, "#\n")] = '\0';
+ lineno++;
+
+ c = calloc(1, sizeof(*c));
+ if (c == NULL)
+ errx(1, "malloc");
+
+ c->lineno = lineno;
+ (*next) = c;
+ next = &(c->next);
+
+ if ((str = iscmd(s, "expect ")) != NULL) {
+ c->type = CMD_EXPECT;
+ c->str = str;
+ } else if ((str = iscmd(s, "send ")) != NULL) {
+ c->type = CMD_SEND;
+ c->str = str;
+ } else if ((str = iscmd(s, "password ")) != NULL) {
+ c->type = CMD_PASSWORD;
+ c->str = str;
+ } else
+ errx(1, "Invalid command on line %d: %s", lineno, s);
+ }
+
+ fclose(cmd);
+}
+
+
+/*
+ *
+ */
+
+static int
+eval_parent(pid_t pid)
+{
+ struct command *c;
+ char in;
+ size_t len = 0;
+ ssize_t sret;
+
+ for (c = commands; c != NULL; c = c->next) {
+ switch(c->type) {
+ case CMD_EXPECT:
+ if (verbose)
+ printf("[expecting %s]", c->str);
+ len = 0;
+ alarm(timeout);
+ while((sret = read(master, &in, sizeof(in))) > 0) {
+ alarm(timeout);
+ printf("%c", in);
+ if (c->str[len] != in) {
+ len = 0;
+ continue;
+ }
+ len++;
+ if (c->str[len] == '\0')
+ break;
+ }
+ alarm(0);
+ if (alarmset == SIGALRM)
+ errx(1, "timeout waiting for %s (line %u)",
+ c->str, c->lineno);
+ else if (alarmset)
+ errx(1, "got a signal %d waiting for %s (line %u)",
+ (int)alarmset, c->str, c->lineno);
+ if (sret <= 0)
+ errx(1, "end command while waiting for %s (line %u)",
+ c->str, c->lineno);
+ break;
+ case CMD_SEND:
+ case CMD_PASSWORD: {
+ size_t i = 0;
+ const char *msg = (c->type == CMD_PASSWORD) ? "****" : c->str;
+
+ if (verbose)
+ printf("[send %s]", msg);
+
+ len = strlen(c->str);
+
+ while (i < len) {
+ if (c->str[i] == '\\' && i < len - 1) {
+ char ctrl;
+ i++;
+ switch(c->str[i]) {
+ case 'n': ctrl = '\n'; break;
+ case 'r': ctrl = '\r'; break;
+ case 't': ctrl = '\t'; break;
+ default:
+ errx(1, "unknown control char %c (line %u)",
+ c->str[i], c->lineno);
+ }
+ if (net_write(master, &ctrl, 1) != 1)
+ errx(1, "command refused input (line %u)", c->lineno);
+ } else {
+ if (net_write(master, &c->str[i], 1) != 1)
+ errx(1, "command refused input (line %u)", c->lineno);
+ }
+ i++;
+ }
+ break;
+ }
+ default:
+ abort();
+ }
+ }
+ while(read(master, &in, sizeof(in)) > 0)
+ printf("%c", in);
+
+ if (verbose)
+ printf("[end of program]\n");
+
+ /*
+ * Fetch status from child
+ */
+ {
+ int ret, status;
+
+ ret = waitpid(pid, &status, 0);
+ if (ret == -1)
+ err(1, "waitpid");
+ if (WIFEXITED(status) && WEXITSTATUS(status))
+ return WEXITSTATUS(status);
+ else if (WIFSIGNALED(status)) {
+ printf("killed by signal: %d\n", WTERMSIG(status));
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/*
+ *
+ */
+
+static struct getargs args[] = {
+ { "timeout", 't', arg_integer, &timeout, "timout", "seconds" },
+ { "verbose", 'v', arg_counter, &verbose, "verbose debugging", NULL },
+ { "version", 0, arg_flag, &version_flag, "print version", NULL },
+ { "help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+
+static void
+usage(int ret)
+{
+ arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "infile command..");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ int optidx = 0;
+ pid_t pid;
+
+ setprogname(argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if (version_flag) {
+ fprintf (stderr, "%s from %s-%s\n", getprogname(), PACKAGE, VERSION);
+ return 0;
+ }
+
+ argv += optidx;
+ argc -= optidx;
+
+ if (argc < 2)
+ usage(1);
+
+ parse_configuration(argv[0]);
+
+ argv += 1;
+
+ open_pty();
+
+ pid = fork();
+ switch (pid) {
+ case -1:
+ err(1, "Failed to fork");
+ case 0:
+
+ if(setsid()<0)
+ err(1, "setsid");
+
+ dup2(slave, STDIN_FILENO);
+ dup2(slave, STDOUT_FILENO);
+ dup2(slave, STDERR_FILENO);
+ closefrom(STDERR_FILENO + 1);
+
+ execvp(argv[0], argv); /* add NULL to end of array ? */
+ err(1, "Failed to exec: %s", argv[0]);
+ default:
+ close(slave);
+ {
+ struct sigaction sa;
+
+ sa.sa_handler = caught_signal;
+ sa.sa_flags = 0;
+ sigemptyset (&sa.sa_mask);
+
+ sigaction(SIGALRM, &sa, NULL);
+ }
+
+ return eval_parent(pid);
+ }
+}
diff --git a/third_party/heimdal/lib/roken/roken-common.h b/third_party/heimdal/lib/roken/roken-common.h
new file mode 100644
index 0000000..035b99b
--- /dev/null
+++ b/third_party/heimdal/lib/roken/roken-common.h
@@ -0,0 +1,566 @@
+/*
+ * Copyright (c) 1995 - 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __ROKEN_COMMON_H__
+#define __ROKEN_COMMON_H__
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __cdecl
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+#ifdef __cplusplus
+#define ROKEN_CPP_START extern "C" {
+#define ROKEN_CPP_END }
+#else
+#define ROKEN_CPP_START
+#define ROKEN_CPP_END
+#endif
+
+#ifndef INADDR_NONE
+#define INADDR_NONE 0xffffffff
+#endif
+
+#ifndef INADDR_LOOPBACK
+#define INADDR_LOOPBACK 0x7f000001
+#endif
+
+#ifndef SOMAXCONN
+#define SOMAXCONN 5
+#endif
+
+#ifndef STDIN_FILENO
+#define STDIN_FILENO 0
+#endif
+
+#ifndef STDOUT_FILENO
+#define STDOUT_FILENO 1
+#endif
+
+#ifndef STDERR_FILENO
+#define STDERR_FILENO 2
+#endif
+
+#ifndef max
+#define max(a,b) (((a)>(b))?(a):(b))
+#endif
+
+#ifndef min
+#define min(a,b) (((a)<(b))?(a):(b))
+#endif
+
+#ifndef TRUE
+#define TRUE 1
+#endif
+
+#ifndef FALSE
+#define FALSE 0
+#endif
+
+#ifndef LOG_DAEMON
+#define openlog(id,option,facility) openlog((id),(option))
+#define LOG_DAEMON 0
+#endif
+#ifndef LOG_ODELAY
+#define LOG_ODELAY 0
+#endif
+#ifndef LOG_NDELAY
+#define LOG_NDELAY 0x08
+#endif
+#ifndef LOG_CONS
+#define LOG_CONS 0
+#endif
+#ifndef LOG_AUTH
+#define LOG_AUTH 0
+#endif
+#ifndef LOG_AUTHPRIV
+#define LOG_AUTHPRIV LOG_AUTH
+#endif
+
+#ifndef F_OK
+#define F_OK 0
+#endif
+
+#ifndef O_ACCMODE
+#define O_ACCMODE 003
+#endif
+
+#ifndef O_NOFOLLOW
+#define O_NOFOLLOW 0
+#endif
+
+#ifdef _WIN32
+
+#define _PATH_DEVNULL "\\\\.\\NUL"
+
+#else
+
+#ifndef _PATH_DEV
+#define _PATH_DEV "/dev/"
+#endif
+
+#ifndef _PATH_DEVNULL
+#define _PATH_DEVNULL "/dev/null"
+#endif
+
+#ifndef _PATH_HEQUIV
+#define _PATH_HEQUIV "/etc/hosts.equiv"
+#endif
+
+#ifndef _PATH_VARRUN
+#define _PATH_VARRUN "/var/run/"
+#endif
+
+#ifndef _PATH_BSHELL
+#define _PATH_BSHELL "/bin/sh"
+#endif
+
+#ifndef MAXPATHLEN
+#define MAXPATHLEN (1024+4)
+#endif
+
+#endif /* !_WIN32 */
+
+#ifndef PATH_MAX
+#ifdef MAX_PATH
+#define PATH_MAX MAX_PATH
+#else
+#define PATH_MAX 4096
+#endif
+#endif
+
+#ifndef MAX_PATH
+#define MAX_PATH PATH_MAX
+#endif
+
+#ifndef RETSIGTYPE
+#define RETSIGTYPE void
+#endif
+
+#ifndef SIG_ERR
+#define SIG_ERR ((RETSIGTYPE (*)(int))-1)
+#endif
+
+/*
+ * error code for getipnodeby{name,addr}
+ */
+
+#ifndef HOST_NOT_FOUND
+#define HOST_NOT_FOUND 1
+#endif
+
+#ifndef TRY_AGAIN
+#define TRY_AGAIN 2
+#endif
+
+#ifndef NO_RECOVERY
+#define NO_RECOVERY 3
+#endif
+
+#ifndef NO_DATA
+#define NO_DATA 4
+#endif
+
+#ifndef NO_ADDRESS
+#define NO_ADDRESS NO_DATA
+#endif
+
+/*
+ * error code for getaddrinfo
+ */
+
+#ifndef EAI_NOERROR
+#define EAI_NOERROR 0 /* no error */
+#endif
+
+#ifndef EAI_NONAME
+
+#define EAI_ADDRFAMILY 1 /* address family for nodename not supported */
+#define EAI_AGAIN 2 /* temporary failure in name resolution */
+#define EAI_BADFLAGS 3 /* invalid value for ai_flags */
+#define EAI_FAIL 4 /* non-recoverable failure in name resolution */
+#define EAI_FAMILY 5 /* ai_family not supported */
+#define EAI_MEMORY 6 /* memory allocation failure */
+#define EAI_NODATA 7 /* no address associated with nodename */
+#define EAI_NONAME 8 /* nodename nor servname provided, or not known */
+#define EAI_SERVICE 9 /* servname not supported for ai_socktype */
+#define EAI_SOCKTYPE 10 /* ai_socktype not supported */
+#define EAI_SYSTEM 11 /* system error returned in errno */
+
+#endif /* EAI_NONAME */
+
+/* flags for getaddrinfo() */
+
+#ifndef AI_PASSIVE
+#define AI_PASSIVE 0x01
+#define AI_CANONNAME 0x02
+#endif /* AI_PASSIVE */
+
+#ifndef AI_NUMERICHOST
+#define AI_NUMERICHOST 0x04
+#endif
+
+#ifndef AI_NUMERICSERV
+#define AI_NUMERICSERV 0x08
+#endif
+
+/* flags for getnameinfo() */
+
+#ifndef NI_DGRAM
+#define NI_DGRAM 0x01
+#define NI_NAMEREQD 0x02
+#define NI_NOFQDN 0x04
+#define NI_NUMERICHOST 0x08
+#define NI_NUMERICSERV 0x10
+#endif
+
+/*
+ * constants for getnameinfo
+ */
+
+#ifndef NI_MAXHOST
+#define NI_MAXHOST 1025
+#define NI_MAXSERV 32
+#endif
+
+/*
+ * constants for inet_ntop
+ */
+
+#ifndef INET_ADDRSTRLEN
+#define INET_ADDRSTRLEN 16
+#endif
+
+#ifndef INET6_ADDRSTRLEN
+#define INET6_ADDRSTRLEN 46
+#endif
+
+/*
+ * for shutdown(2)
+ */
+
+#ifndef SHUT_RD
+#define SHUT_RD 0
+#endif
+
+#ifndef SHUT_WR
+#define SHUT_WR 1
+#endif
+
+#ifndef SHUT_RDWR
+#define SHUT_RDWR 2
+#endif
+
+#ifndef HAVE___ATTRIBUTE__
+#define __attribute__(x)
+#endif
+
+/*
+ * for dlopen(3)
+ */
+#ifndef RTLD_LAZY
+#define RTLD_LAZY 0
+#endif
+
+#ifndef RTLD_NOW
+#define RTLD_NOW 0
+#endif
+
+#ifndef RTLD_GLOBAL
+#define RTLD_GLOBAL 0
+#endif
+
+#ifndef RTLD_LOCAL
+#define RTLD_LOCAL 0
+#endif
+
+#ifndef RTLD_GROUP
+#define RTLD_GROUP 0
+#endif
+
+#ifndef RTLD_NODELETE
+#define RTLD_NODELETE 0
+#endif
+
+ROKEN_CPP_START
+
+#ifndef IRIX4 /* fix for compiler bug */
+#ifndef _WIN32
+#ifdef RETSIGTYPE
+typedef RETSIGTYPE (*SigAction)(int);
+SigAction signal(int iSig, SigAction pAction); /* BSD compatible */
+#endif
+#endif
+#endif
+
+#define SE_E_UNSPECIFIED (-1)
+#define SE_E_FORKFAILED (-2)
+#define SE_E_WAITPIDFAILED (-3)
+#define SE_E_EXECTIMEOUT (-4)
+#define SE_E_NOEXEC 126
+#define SE_E_NOTFOUND 127
+
+#define SE_PROCSTATUS(st) (((st) >= 0 && (st) < 126)? st: -1)
+#define SE_PROCSIGNAL(st) (((st) >= 128)? (st) - 128: -1)
+#define SE_IS_ERROR(st) ((st) < 0 || (st) >= 126)
+
+
+#define simple_execve rk_simple_execve
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execve(const char*, char*const[], char*const[]);
+
+#define simple_execve_timed rk_simple_execve_timed
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execve_timed(const char *, char *const[],
+ char *const [], time_t (*)(void *),
+ void *, time_t);
+
+#define simple_execvp rk_simple_execvp
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execvp(const char*, char *const[]);
+
+#define simple_execvp_timed rk_simple_execvp_timed
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execvp_timed(const char *, char *const[],
+ time_t (*)(void *), void *, time_t);
+
+#define simple_execlp rk_simple_execlp
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execlp(const char*, ...);
+
+#define simple_execle rk_simple_execle
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execle(const char*, ...);
+
+#define wait_for_process rk_wait_for_process
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+wait_for_process(pid_t);
+
+#define wait_for_process_timed rk_wait_for_process_timed
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+wait_for_process_timed(pid_t, time_t (*)(void *),
+ void *, time_t);
+
+#define pipe_execv rk_pipe_execv
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+pipe_execv(FILE**, FILE**, FILE**, const char*, ...);
+
+#define print_version rk_print_version
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+print_version(const char *);
+
+#define eread rk_eread
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+eread (int fd, void *buf, size_t nbytes);
+
+#define ewrite rk_ewrite
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+ewrite (int fd, const void *buf, size_t nbytes);
+
+struct hostent;
+
+#define hostent_find_fqdn rk_hostent_find_fqdn
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
+hostent_find_fqdn (const struct hostent *);
+
+#define esetenv rk_esetenv
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+esetenv(const char *, const char *, int);
+
+#define socket_set_address_and_port rk_socket_set_address_and_port
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_address_and_port (struct sockaddr *, const void *, int);
+
+#define socket_addr_size rk_socket_addr_size
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+socket_addr_size (const struct sockaddr *);
+
+#define socket_set_any rk_socket_set_any
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_any (struct sockaddr *, int);
+
+#define socket_sockaddr_size rk_socket_sockaddr_size
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+socket_sockaddr_size (const struct sockaddr *);
+
+#define socket_get_address rk_socket_get_address
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+socket_get_address (const struct sockaddr *);
+
+#define socket_get_port rk_socket_get_port
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+socket_get_port (const struct sockaddr *);
+
+#define socket_set_port rk_socket_set_port
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_port (struct sockaddr *, int);
+
+#define socket_set_portrange rk_socket_set_portrange
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_portrange (rk_socket_t, int, int);
+
+#define socket_set_debug rk_socket_set_debug
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_debug (rk_socket_t);
+
+#define socket_set_tos rk_socket_set_tos
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_tos (rk_socket_t, int);
+
+#define socket_set_nonblocking rk_socket_set_nonblocking
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_nonblocking(rk_socket_t, int);
+
+#define socket_set_reuseaddr rk_socket_set_reuseaddr
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_reuseaddr (rk_socket_t, int);
+
+#define socket_set_ipv6only rk_socket_set_ipv6only
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_ipv6only (rk_socket_t, int);
+
+#define socket_set_keepalive rk_socket_set_keepalive
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_keepalive (rk_socket_t, int);
+
+#define socket_to_fd rk_socket_to_fd
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+socket_to_fd(rk_socket_t, int);
+
+#define vstrcollect rk_vstrcollect
+ROKEN_LIB_FUNCTION char ** ROKEN_LIB_CALL
+vstrcollect(va_list *ap);
+
+#define strcollect rk_strcollect
+ROKEN_LIB_FUNCTION char ** ROKEN_LIB_CALL
+strcollect(char *first, ...);
+
+ROKEN_LIB_FUNCTION time_t ROKEN_LIB_CALL
+rk_time_add(time_t, time_t);
+
+ROKEN_LIB_FUNCTION time_t ROKEN_LIB_CALL
+rk_time_sub(time_t, time_t);
+
+#define timevalfix rk_timevalfix
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+timevalfix(struct timeval *t1);
+
+#define timevaladd rk_timevaladd
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+timevaladd(struct timeval *t1, const struct timeval *t2);
+
+#define timevalsub rk_timevalsub
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+timevalsub(struct timeval *t1, const struct timeval *t2);
+
+#define pid_file_write rk_pid_file_write
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+pid_file_write (const char *progname);
+
+#define pid_file_delete rk_pid_file_delete
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+pid_file_delete (char **);
+
+#define read_environment rk_read_environment
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+read_environment(const char *file, char ***env);
+
+#define free_environment rk_free_environment
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+free_environment(char **);
+
+#define warnerr rk_warnerr
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_warnerr(int doerrno, const char *fmt, va_list ap)
+ __attribute__ ((__format__ (__printf__, 2, 0)));
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+rk_realloc(void *, size_t);
+
+struct rk_strpool;
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+rk_strpoolcollect(struct rk_strpool *);
+
+ROKEN_LIB_FUNCTION struct rk_strpool * ROKEN_LIB_CALL
+rk_strpoolprintf(struct rk_strpool *, const char *, ...)
+ __attribute__ ((__format__ (__printf__, 2, 3)));
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_strpoolfree(struct rk_strpool *);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_dumpdata (const char *, const void *, size_t);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_undumpdata (const char *, void **, size_t *);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_xfree (void *);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_cloexec(int);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_cloexec_file(FILE *);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_cloexec_dir(DIR *);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_cloexec_socket(rk_socket_t);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ct_memcmp(const volatile void * volatile,
+ const volatile void * volatile,
+ size_t);
+
+void ROKEN_LIB_FUNCTION
+rk_random_init(void);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_mkdir(const char *, mode_t);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_clzll(uint64_t);
+
+ROKEN_CPP_END
+
+#endif /* __ROKEN_COMMON_H__ */
diff --git a/third_party/heimdal/lib/roken/roken.awk b/third_party/heimdal/lib/roken/roken.awk
new file mode 100644
index 0000000..47313c8
--- /dev/null
+++ b/third_party/heimdal/lib/roken/roken.awk
@@ -0,0 +1,46 @@
+# $Id$
+
+BEGIN {
+ print "#include <config.h>"
+ print "#include <stdio.h>"
+ print "#ifdef HAVE_SYS_TYPES_H"
+ print "#include <sys/types.h>"
+ print "#endif"
+ print "#ifdef HAVE_SYS_SOCKET_H"
+ print "#include <sys/socket.h>"
+ print "#endif"
+ print "#ifdef HAVE_ERRNO_H"
+ print "#include <errno.h>"
+ print "#endif"
+ print ""
+ print "int main(int argc, char **argv)"
+ print "{"
+ print "puts(\"/* This is an OS dependent, generated file */\");"
+ print "puts(\"\\n\");"
+ print "puts(\"#ifndef __ROKEN_H__\");"
+ print "puts(\"#define __ROKEN_H__\");"
+ print "puts(\"\");"
+}
+
+$1 == "#ifdef" || $1 == "#ifndef" || $1 == "#if" || $1 == "#else" || $1 == "#elif" || $1 == "#endif" {
+ print $0;
+ next
+}
+
+{
+ s = ""
+ for(i = 1; i <= length; i++){
+ x = substr($0, i, 1)
+ if(x == "\"" || x == "\\")
+ s = s "\\";
+ s = s x;
+ }
+ print "puts(\"" s "\");"
+}
+
+END {
+ print "puts(\"\");"
+ print "puts(\"#endif /* __ROKEN_H__ */\");"
+ print "return 0;"
+ print "}"
+}
diff --git a/third_party/heimdal/lib/roken/roken.h.in b/third_party/heimdal/lib/roken/roken.h.in
new file mode 100644
index 0000000..e1902f5
--- /dev/null
+++ b/third_party/heimdal/lib/roken/roken.h.in
@@ -0,0 +1,1330 @@
+/* -*- C -*- */
+/*
+ * Copyright (c) 1995-2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+# if defined(_WIN32) && _MSC_VER >= 1400
+/* _CRT_RAND_S must be defined before including stdlib.h */
+# define _CRT_RAND_S
+# define HAVE_WIN32_RAND_S 1
+# endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#ifdef HAVE_STDINT_H
+#include <stdint.h>
+#endif
+#include <string.h>
+#include <limits.h>
+#include <signal.h>
+
+#ifdef HAVE_UTIL_H
+#include <util.h>
+#endif
+
+# ifndef ROKEN_LIB_FUNCTION
+# ifdef _WIN32
+# ifdef ROKEN_LIB_DYNAMIC
+# define ROKEN_LIB_FUNCTION __declspec(dllimport)
+# else
+# define ROKEN_LIB_FUNCTION
+# endif
+# else
+# define ROKEN_LIB_FUNCTION
+# endif
+# endif
+
+# ifndef ROKEN_LIB_NORETURN_FUNCTION
+# ifdef _WIN32
+# ifdef ROKEN_LIB_DYNAMIC
+# define ROKEN_LIB_NORETURN_FUNCTION __declspec(dllimport noreturn)
+# else
+# define ROKEN_LIB_NORETURN_FUNCTION __declspec(noreturn)
+# endif
+# else
+# define ROKEN_LIB_NORETURN_FUNCTION
+# endif
+# endif
+
+# ifndef ROKEN_LIB_CALL
+# ifdef _WIN32
+# define ROKEN_LIB_CALL __cdecl
+# else
+# define ROKEN_LIB_CALL
+# endif
+# endif
+
+# ifndef ROKEN_LIB_VARIABLE
+# ifdef _WIN32
+# ifdef ROKEN_LIB_DYNAMIC
+# define ROKEN_LIB_VARIABLE __declspec(dllimport)
+# else
+# define ROKEN_LIB_VARIABLE
+# endif
+# else
+# define ROKEN_LIB_VARIABLE
+# endif
+# endif
+
+#ifdef HAVE_WINSOCK
+/* Declarations for Microsoft Windows */
+
+#include <winsock2.h>
+#include <ws2tcpip.h>
+
+/*
+ * error codes for inet_ntop/inet_pton
+ */
+typedef SOCKET rk_socket_t;
+
+#define rk_closesocket(x) closesocket(x)
+#define rk_INVALID_SOCKET INVALID_SOCKET
+#define rk_IS_BAD_SOCKET(s) ((s) == INVALID_SOCKET)
+#define rk_IS_SOCKET_ERROR(rv) ((rv) == SOCKET_ERROR)
+#define rk_SOCK_ERRNO WSAGetLastError()
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL rk_SOCK_IOCTL(SOCKET s, long cmd, int * argp);
+
+#define rk_SOCK_INIT() rk_WSAStartup()
+#define rk_SOCK_EXIT() rk_WSACleanup()
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL rk_WSAStartup(void);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL rk_WSACleanup(void);
+
+#else /* not WinSock */
+
+typedef int rk_socket_t;
+
+#define rk_closesocket(x) close(x)
+#define rk_SOCK_IOCTL(s,c,a) ioctl((s),(c),(a))
+#define rk_IS_BAD_SOCKET(s) ((s) < 0)
+#define rk_IS_SOCKET_ERROR(rv) ((rv) < 0)
+#define rk_SOCK_ERRNO errno
+#define rk_INVALID_SOCKET (-1)
+
+static inline ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL rk_SOCK_INIT(void) {
+ return 0;
+}
+
+#define rk_SOCK_EXIT() do { } while(0)
+
+#endif /* WinSock */
+
+#ifndef IN_LOOPBACKNET
+#define IN_LOOPBACKNET 127
+#endif
+
+#ifdef _MSC_VER
+#ifndef HAVE_STDINT_H
+#include <intsafe.h>
+#endif
+
+/* Declarations for Microsoft Visual C runtime on Windows */
+
+#include<process.h>
+
+#include<io.h>
+
+#ifndef __BIT_TYPES_DEFINED__
+#define __BIT_TYPES_DEFINED__
+
+typedef __int8 int8_t;
+typedef __int16 int16_t;
+typedef __int32 int32_t;
+typedef __int64 int64_t;
+typedef unsigned __int8 uint8_t;
+typedef unsigned __int16 uint16_t;
+typedef unsigned __int32 uint32_t;
+typedef unsigned __int64 uint64_t;
+typedef uint8_t u_int8_t;
+typedef uint16_t u_int16_t;
+typedef uint32_t u_int32_t;
+typedef uint64_t u_int64_t;
+
+#endif /* __BIT_TYPES_DEFINED__ */
+
+#define UNREACHABLE(x) x
+#define UNUSED_ARGUMENT(x) ((void) x)
+
+#define RETSIGTYPE void
+
+#define VOID_RETSIGTYPE 1
+
+#ifdef VOID_RETSIGTYPE
+#define SIGRETURN(x) return
+#else
+#define SIGRETURN(x) return (RETSIGTYPE)(x)
+#endif
+
+#ifndef CPP_ONLY
+
+typedef int pid_t;
+
+typedef unsigned int gid_t;
+
+typedef unsigned int uid_t;
+
+typedef unsigned short mode_t;
+
+#endif
+
+#ifndef __cplusplus
+#define inline __inline
+#endif
+
+#else
+
+#define UNREACHABLE(x)
+#define UNUSED_ARGUMENT(x)
+
+#endif
+
+#ifdef _AIX
+struct ether_addr;
+struct sockaddr_dl;
+#endif
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+#ifdef HAVE_INTTYPES_H
+#include <inttypes.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_ERRNO_H
+#include <sys/errno.h>
+#endif
+#ifdef HAVE_SYS_BITYPES_H
+#include <sys/bitypes.h>
+#endif
+#ifdef HAVE_BIND_BITYPES_H
+#include <bind/bitypes.h>
+#endif
+#ifdef HAVE_NETINET_IN6_MACHTYPES_H
+#include <netinet/in6_machtypes.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef HAVE_SYS_UIO_H
+#include <sys/uio.h>
+#endif
+#ifdef HAVE_GRP_H
+#include <grp.h>
+#endif
+#ifdef HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+#ifdef HAVE_NETINET6_IN6_H
+#include <netinet6/in6.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+#ifdef HAVE_RESOLV_H
+#include <resolv.h>
+#endif
+#ifdef HAVE_SYSLOG_H
+#include <syslog.h>
+#endif
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef HAVE_ERRNO_H
+#include <errno.h>
+#endif
+#include <err.h>
+#ifdef HAVE_TERMIOS_H
+#include <termios.h>
+#endif
+#ifdef HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+#ifdef TIME_WITH_SYS_TIME
+#include <sys/time.h>
+#include <time.h>
+#elif defined(HAVE_SYS_TIME_H)
+#include <sys/time.h>
+#else
+#include <time.h>
+#endif
+
+#ifdef HAVE_PATHS_H
+#include <paths.h>
+#endif
+
+#ifdef HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+#ifdef HAVE_DIRENT_H
+#include <dirent.h>
+#endif
+
+#ifdef WIN32
+#include <direct.h>
+#endif
+
+#ifdef BACKSLASH_PATH_DELIM
+#define rk_PATH_DELIM '\\'
+#endif
+
+#ifndef HAVE_SSIZE_T
+#ifndef SSIZE_T_DEFINED
+#ifdef ssize_t
+#undef ssize_t
+#endif
+#ifdef _WIN64
+typedef __int64 ssize_t;
+#else
+typedef int ssize_t;
+#endif
+#define SSIZE_T_DEFINED
+#endif /* SSIZE_T_DEFINED */
+#endif /* HAVE_SSIZE_T */
+
+#include <roken-common.h>
+
+ROKEN_CPP_START
+
+#ifdef HAVE_UINTPTR_T
+#define rk_UNCONST(x) ((void *)(uintptr_t)(const void *)(x))
+#else
+#define rk_UNCONST(x) ((void *)(unsigned long)(const void *)(x))
+#endif
+
+#if !defined(HAVE_SETSID) && defined(HAVE__SETSID)
+#define setsid _setsid
+#endif
+
+#ifdef _MSC_VER
+/* Additional macros for Visual C/C++ runtime */
+
+#define close _close
+
+#define getpid _getpid
+
+#define open _open
+
+#define chdir _chdir
+
+#define fsync _commit
+
+#define _PIPE_BUFFER_SZ 8192
+#define pipe(fds) _pipe((fds), _PIPE_BUFFER_SZ, O_BINARY);
+
+#define ftruncate(fd, sz) _chsize((fd), (sz))
+
+#if !defined(HAVE_UCRT)
+#define snprintf rk_snprintf
+#define vsnprintf rk_vsnprintf
+#define vasnprintf rk_vasnprintf
+#define vasprintf rk_vasprintf
+#define asnprintf rk_asnprintf
+#define asprintf rk_asprintf
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_snprintf (char *str, size_t sz, const char *format, ...);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_asprintf (char **ret, const char *format, ...);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_asnprintf (char **ret, size_t max_sz, const char *format, ...);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_vasprintf (char **ret, const char *format, va_list args);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_vasnprintf (char **ret, size_t max_sz, const char *format, va_list args);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_vsnprintf (char *str, size_t sz, const char *format, va_list args);
+#endif /* !defined(HAVE_UCRT) */
+
+/* missing stat.h predicates */
+
+#define S_ISREG(m) (((m) & _S_IFREG) == _S_IFREG)
+
+#define S_ISDIR(m) (((m) & _S_IFDIR) == _S_IFDIR)
+
+#define S_ISCHR(m) (((m) & _S_IFCHR) == _S_IFCHR)
+
+#define S_ISFIFO(m) (((m) & _S_IFIFO) == _S_IFIFO)
+
+/* The following are not implemented:
+
+ S_ISLNK(m)
+ S_ISSOCK(m)
+ S_ISBLK(m)
+*/
+
+/* The following symbolic constants are provided for rk_mkdir mode */
+
+#define S_IRWXU 00700 /* user (file owner) has read, write and execute permission */
+#define S_IRUSR 00400 /* user has read permission */
+#define S_IWUSR 00200 /* user has write permission */
+#define S_IXUSR 00100 /* user has execute permission */
+#define S_IRWXG 00070 /* group has read, write and execute permission */
+#define S_IRGRP 00040 /* group has read permission */
+#define S_IWGRP 00020 /* group has write permission */
+#define S_IXGRP 00010 /* group has execute permission */
+#define S_IRWXO 00007 /* others have read, write and execute permission */
+#define S_IROTH 00004 /* others have read permission */
+#define S_IWOTH 00002 /* others have write permission */
+#define S_IXOTH 00001 /* others have execute permission */
+
+#if !defined(ROKEN_NO_DEFINE_ALLOCATORS)
+/* Ensure that a common memory allocator is used by all */
+#define calloc rk_calloc
+#define free rk_free
+#define malloc rk_malloc
+#define realloc rk_realloc
+#define strdup rk_strdup
+#define wcsdup rk_wcsdup
+#endif
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+rk_calloc(size_t, size_t);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_free(void *);
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+rk_malloc(size_t);
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+rk_realloc(void *, size_t);
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+rk_strdup(const char *);
+
+ROKEN_LIB_FUNCTION unsigned short * ROKEN_LIB_CALL
+rk_wcsdup(const unsigned short *);
+
+#endif /* _MSC_VER */
+
+#ifndef HAVE_MEMMEM
+#define memmem rk_smemmem
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL memmem(const void *, size_t, const void *, size_t);
+#endif
+
+#ifdef HAVE_WINSOCK
+
+/* While we are at it, define WinSock specific scatter gather socket
+ I/O. */
+
+#define iovec _WSABUF
+#define iov_base buf
+#define iov_len len
+
+struct msghdr {
+ void *msg_name;
+ socklen_t msg_namelen;
+ struct iovec *msg_iov;
+ size_t msg_iovlen;
+ void *msg_control;
+ socklen_t msg_controllen;
+ int msg_flags;
+};
+
+#define sendmsg sendmsg_w32
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+sendmsg_w32(rk_socket_t s, const struct msghdr * msg, int flags);
+
+#endif /* HAVE_WINSOCK */
+
+#ifndef HAVE_PUTENV
+#define putenv rk_putenv
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL putenv(const char *);
+#endif
+
+#if !defined(HAVE_SETENV) || defined(NEED_SETENV_PROTO)
+#ifndef HAVE_SETENV
+#define setenv rk_setenv
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL setenv(const char *, const char *, int);
+#endif
+
+#if !defined(HAVE_UNSETENV) || defined(NEED_UNSETENV_PROTO)
+#ifndef HAVE_UNSETENV
+#define unsetenv rk_unsetenv
+#endif
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL unsetenv(const char *);
+#endif
+
+#if !defined(HAVE_GETUSERSHELL) || defined(NEED_GETUSERSHELL_PROTO)
+#ifndef HAVE_GETUSERSHELL
+#define getusershell rk_getusershell
+#define endusershell rk_endusershell
+#endif
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL getusershell(void);
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL endusershell(void);
+#endif
+
+#if !defined(HAVE_SNPRINTF) || defined(NEED_SNPRINTF_PROTO)
+#ifndef HAVE_SNPRINTF
+#define snprintf rk_snprintf
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_snprintf (char *, size_t, const char *, ...)
+ __attribute__ ((__format__ (__printf__, 3, 4)));
+#endif
+
+#if !defined(HAVE_VSNPRINTF) || defined(NEED_VSNPRINTF_PROTO)
+#ifndef HAVE_VSNPRINTF
+#define vsnprintf rk_vsnprintf
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_vsnprintf (char *, size_t, const char *, va_list)
+ __attribute__ ((__format__ (__printf__, 3, 0)));
+#endif
+
+#if !defined(HAVE_ASPRINTF) || defined(NEED_ASPRINTF_PROTO)
+#ifndef HAVE_ASPRINTF
+#define asprintf rk_asprintf
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_asprintf (char **, const char *, ...)
+ __attribute__ ((__format__ (__printf__, 2, 3)));
+#endif
+
+#if !defined(HAVE_VASPRINTF) || defined(NEED_VASPRINTF_PROTO)
+#ifndef HAVE_VASPRINTF
+#define vasprintf rk_vasprintf
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_vasprintf (char **, const char *, va_list)
+ __attribute__ ((__format__ (__printf__, 2, 0)));
+#endif
+
+#if !defined(HAVE_ASNPRINTF) || defined(NEED_ASNPRINTF_PROTO)
+#ifndef HAVE_ASNPRINTF
+#define asnprintf rk_asnprintf
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_asnprintf (char **, size_t, const char *, ...)
+ __attribute__ ((__format__ (__printf__, 3, 4)));
+#endif
+
+#if !defined(HAVE_VASNPRINTF) || defined(NEED_VASNPRINTF_PROTO)
+#ifndef HAVE_VASNPRINTF
+#define vasnprintf rk_vasnprintf
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ vasnprintf (char **, size_t, const char *, va_list)
+ __attribute__ ((__format__ (__printf__, 3, 0)));
+#endif
+
+#ifndef HAVE_STRDUP
+#define strdup rk_strdup
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL strdup(const char *);
+#endif
+
+#if !defined(HAVE_STRNDUP) || defined(NEED_STRNDUP_PROTO)
+#ifndef HAVE_STRNDUP
+#define strndup rk_strndup
+#endif
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL strndup(const char *, size_t);
+#endif
+
+#ifndef HAVE_STRLWR
+#define strlwr rk_strlwr
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL strlwr(char *);
+#endif
+
+#ifndef HAVE_STRNLEN
+#define strnlen rk_strnlen
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL strnlen(const char*, size_t);
+#endif
+
+#if !defined(HAVE_STRSEP) || defined(NEED_STRSEP_PROTO)
+#ifndef HAVE_STRSEP
+#define strsep rk_strsep
+#endif
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL strsep(char**, const char*);
+#endif
+
+#if !defined(HAVE_STRSEP_COPY) || defined(NEED_STRSEP_COPY_PROTO)
+#ifndef HAVE_STRSEP_COPY
+#define strsep_copy rk_strsep_copy
+#endif
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL strsep_copy(const char**, const char*, char*, size_t);
+#endif
+
+#ifndef HAVE_STRCASECMP
+#define strcasecmp rk_strcasecmp
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL strcasecmp(const char *, const char *);
+#endif
+
+#ifdef NEED_FCLOSE_PROTO
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL fclose(FILE *);
+#endif
+
+#ifdef NEED_STRTOK_R_PROTO
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL strtok_r(char *, const char *, char **);
+#endif
+
+#ifndef HAVE_STRUPR
+#define strupr rk_strupr
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL strupr(char *);
+#endif
+
+#ifndef HAVE_STRLCPY
+#define strlcpy rk_strlcpy
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL strlcpy (char *, const char *, size_t);
+#endif
+
+#ifndef HAVE_STRLCAT
+#define strlcat rk_strlcat
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL strlcat (char *, const char *, size_t);
+#endif
+
+#ifndef HAVE_GETDTABLESIZE
+#define getdtablesize rk_getdtablesize
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL getdtablesize(void);
+#endif
+
+#if !defined(HAVE_STRERROR) && !defined(strerror)
+#define strerror rk_strerror
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL strerror(int);
+#endif
+
+#if (!defined(HAVE_STRERROR_R) && !defined(strerror_r)) || (!defined(STRERROR_R_PROTO_COMPATIBLE) && defined(HAVE_STRERROR_R))
+int ROKEN_LIB_FUNCTION rk_strerror_r(int, char *, size_t);
+#else
+#define rk_strerror_r strerror_r
+#endif
+
+#if !defined(HAVE_HSTRERROR) || defined(NEED_HSTRERROR_PROTO)
+#ifndef HAVE_HSTRERROR
+#define hstrerror rk_hstrerror
+#endif
+/* This causes a fatal error under Psoriasis */
+#ifndef SunOS
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL hstrerror(int);
+#endif
+#endif
+
+#if !HAVE_DECL_H_ERRNO
+extern int h_errno;
+#endif
+
+#if !defined(HAVE_INET_ATON) || defined(NEED_INET_ATON_PROTO)
+#ifndef HAVE_INET_ATON
+#define inet_aton rk_inet_aton
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL inet_aton(const char *, struct in_addr *);
+#endif
+
+#ifndef HAVE_INET_NTOP
+#define inet_ntop rk_inet_ntop
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
+inet_ntop(int af, const void *src, char *dst, size_t size);
+#endif
+
+#ifndef HAVE_INET_PTON
+#define inet_pton rk_inet_pton
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+inet_pton(int, const char *, void *);
+#endif
+
+#ifndef HAVE_GETCWD
+#define getcwd rk_getcwd
+ROKEN_LIB_FUNCTION char* ROKEN_LIB_CALL getcwd(char *, size_t);
+#endif
+
+#ifdef HAVE_PWD_H
+#include <pwd.h>
+#endif
+
+#ifndef HAVE_SETEUID
+#define seteuid rk_seteuid
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL seteuid(uid_t);
+#endif
+
+#ifndef HAVE_SETEGID
+#define setegid rk_setegid
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL setegid(gid_t);
+#endif
+
+#ifndef HAVE_LSTAT
+#define lstat rk_lstat
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL lstat(const char *, struct stat *);
+#endif
+
+#if !defined(HAVE_MKSTEMP) || defined(NEED_MKSTEMP_PROTO)
+#ifndef HAVE_MKSTEMP
+#define mkstemp rk_mkstemp
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL mkstemp(char *);
+#endif
+
+#ifndef HAVE_MKOSTEMP
+#define mkostemp rk_mkostemp
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL mkostemp(char *, int);
+#endif
+
+#ifndef HAVE_MKDTEMP
+#define mkdtemp rk_mkdtemp
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL mkdtemp(char *);
+#endif
+
+#ifndef HAVE_INITGROUPS
+#define initgroups rk_initgroups
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL initgroups(const char *, gid_t);
+#endif
+
+#ifndef HAVE_FCHOWN
+#define fchown rk_fchown
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL fchown(int, uid_t, gid_t);
+#endif
+
+#ifdef RENAME_DOES_NOT_UNLINK
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL rk_rename(const char *, const char *);
+#else
+#define rk_rename(__rk_rn_from,__rk_rn_to) rename(__rk_rn_from,__rk_rn_to)
+#endif
+
+#ifdef WIN32
+#define mkdir rk_mkdir
+#else
+#define rk_mkdir(__rk_rn_name, __rk_rn_mode) mkdir(__rk_rn_name,__rk_rn_mode)
+#endif
+
+
+#if !defined(HAVE_DAEMON) || defined(NEED_DAEMON_PROTO)
+#ifndef HAVE_DAEMON
+#define daemon rk_daemon
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL daemon(int, int);
+#endif
+
+#ifndef HAVE_CHOWN
+#define chown rk_chown
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL chown(const char *, uid_t, gid_t);
+#endif
+
+#ifndef HAVE_RCMD
+#define rcmd rk_rcmd
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rcmd(char **, unsigned short, const char *,
+ const char *, const char *, int *);
+#endif
+
+#if !defined(HAVE_INNETGR) || defined(NEED_INNETGR_PROTO)
+#ifndef HAVE_INNETGR
+#define innetgr rk_innetgr
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL innetgr(const char*, const char*,
+ const char*, const char*);
+#endif
+
+#if !defined(HAVE_GETHOSTNAME) || defined(NEED_GETHOSTNAME_PROTO)
+#ifndef HAVE_GETHOSTNAME
+#define gethostname rk_gethostname
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL gethostname(char *, int);
+#endif
+
+#ifndef HAVE_WRITEV
+#define writev rk_writev
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+writev(int, const struct iovec *, int);
+#endif
+
+#ifndef HAVE_READV
+#define readv rk_readv
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+readv(int, const struct iovec *, int);
+#endif
+
+#ifdef NO_PIDFILES
+#define rk_pidfile(x) ((void) 0)
+#else
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL rk_pidfile (const char*);
+#endif
+
+#ifndef HAVE_BSWAP64
+#define bswap64 rk_bswap64
+ROKEN_LIB_FUNCTION uint64_t ROKEN_LIB_CALL bswap64(uint64_t);
+#endif
+
+#ifndef HAVE_BSWAP32
+#define bswap32 rk_bswap32
+ROKEN_LIB_FUNCTION unsigned int ROKEN_LIB_CALL bswap32(unsigned int);
+#endif
+
+#ifndef HAVE_BSWAP16
+#define bswap16 rk_bswap16
+ROKEN_LIB_FUNCTION unsigned short ROKEN_LIB_CALL bswap16(unsigned short);
+#endif
+
+#ifndef HAVE_FLOCK
+#ifndef LOCK_SH
+#define LOCK_SH 1 /* Shared lock */
+#endif
+#ifndef LOCK_EX
+#define LOCK_EX 2 /* Exclusive lock */
+#endif
+#ifndef LOCK_NB
+#define LOCK_NB 4 /* Don't block when locking */
+#endif
+#ifndef LOCK_UN
+#define LOCK_UN 8 /* Unlock */
+#endif
+
+#define flock(_x,_y) rk_flock(_x,_y)
+int rk_flock(int fd, int operation);
+#endif /* HAVE_FLOCK */
+
+#ifndef HAVE_DIRFD
+#ifdef HAVE_DIR_DD_FD
+#define dirfd(x) ((x)->dd_fd)
+#elif defined(HAVE_DIR_D_FD)
+#define dirfd(x) ((x)->d_fd)
+#else
+#ifndef _WIN32 /* Windows code never calls dirfd */
+#error Missing dirfd() and ->dd_fd and ->d_fd
+#endif
+#endif
+#endif
+
+ROKEN_LIB_FUNCTION time_t ROKEN_LIB_CALL tm2time (struct tm, int);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL roken_concat (char *, size_t, ...);
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL roken_mconcat (char **, size_t, ...);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL roken_vconcat (char *, size_t, va_list);
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+ roken_vmconcat (char **, size_t, va_list);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL roken_detach_prep(int, char **, char *);
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL roken_detach_finish(const char *, int);
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+ net_write (rk_socket_t, const void *, size_t);
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+ net_read (rk_socket_t, void *, size_t);
+
+ROKEN_LIB_FUNCTION unsigned long ROKEN_LIB_CALL
+ rk_getauxval(unsigned long);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ issuid(void);
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+ rk_secure_getenv(const char *);
+
+#ifndef HAVE_SECURE_GETENV
+#undef secure_getenv
+#define secure_getenv(e) rk_secure_getenv(e)
+#endif
+
+#ifndef HAVE_STRUCT_WINSIZE
+struct winsize {
+ unsigned short ws_row, ws_col;
+ unsigned short ws_xpixel, ws_ypixel;
+};
+#endif
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL get_window_size(int fd, int *, int *);
+
+#ifndef HAVE_VSYSLOG
+#define vsyslog rk_vsyslog
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL vsyslog(int, const char *, va_list);
+#endif
+
+#ifndef HAVE_GETOPT
+#define getopt rk_getopt
+#define optarg rk_optarg
+#define optind rk_optind
+#define opterr rk_opterr
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+getopt(int nargc, char * const *nargv, const char *ostr);
+#endif
+
+#if !HAVE_DECL_OPTARG
+ROKEN_LIB_VARIABLE extern char *optarg;
+#endif
+#if !HAVE_DECL_OPTIND
+ROKEN_LIB_VARIABLE extern int optind;
+#endif
+#if !HAVE_DECL_OPTERR
+ROKEN_LIB_VARIABLE extern int opterr;
+#endif
+
+#ifndef HAVE_GETIPNODEBYNAME
+#define getipnodebyname rk_getipnodebyname
+#endif
+ROKEN_LIB_FUNCTION struct hostent * ROKEN_LIB_CALL
+rk_getipnodebyname(const char *, int, int, int *);
+
+#ifndef HAVE_GETIPNODEBYADDR
+#define getipnodebyaddr rk_getipnodebyaddr
+#endif
+ROKEN_LIB_FUNCTION struct hostent * ROKEN_LIB_CALL
+rk_getipnodebyaddr(const void *, size_t, int, int *);
+
+#ifndef HAVE_FREEHOSTENT
+#define freehostent rk_freehostent
+#endif
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_freehostent(struct hostent *);
+
+#ifndef HAVE_COPYHOSTENT
+#define copyhostent rk_copyhostent
+#endif
+ROKEN_LIB_FUNCTION struct hostent * ROKEN_LIB_CALL
+rk_copyhostent(const struct hostent *);
+
+#ifndef HAVE_SOCKLEN_T
+typedef int socklen_t;
+#endif
+
+#ifndef HAVE_STRUCT_SOCKADDR_STORAGE
+
+#ifndef HAVE_SA_FAMILY_T
+typedef unsigned short sa_family_t;
+#endif
+
+#ifdef HAVE_IPV6
+#define _SS_MAXSIZE sizeof(struct sockaddr_in6)
+#else
+#define _SS_MAXSIZE sizeof(struct sockaddr_in)
+#endif
+
+#define _SS_ALIGNSIZE sizeof(unsigned long)
+
+#if HAVE_STRUCT_SOCKADDR_SA_LEN
+
+typedef unsigned char roken_sa_family_t;
+
+#define _SS_PAD1SIZE ((2 * _SS_ALIGNSIZE - sizeof (roken_sa_family_t) - sizeof(unsigned char)) % _SS_ALIGNSIZE)
+#define _SS_PAD2SIZE (_SS_MAXSIZE - (sizeof (roken_sa_family_t) + sizeof(unsigned char) + _SS_PAD1SIZE + _SS_ALIGNSIZE))
+
+struct sockaddr_storage {
+ unsigned char ss_len;
+ roken_sa_family_t ss_family;
+ char __ss_pad1[_SS_PAD1SIZE];
+ unsigned long __ss_align[_SS_PAD2SIZE / sizeof(unsigned long) + 1];
+};
+
+#else /* !HAVE_STRUCT_SOCKADDR_SA_LEN */
+
+typedef unsigned short roken_sa_family_t;
+
+#define _SS_PAD1SIZE ((2 * _SS_ALIGNSIZE - sizeof (roken_sa_family_t)) % _SS_ALIGNSIZE)
+#define _SS_PAD2SIZE (_SS_MAXSIZE - (sizeof (roken_sa_family_t) + _SS_PAD1SIZE + _SS_ALIGNSIZE))
+
+struct sockaddr_storage {
+ roken_sa_family_t ss_family;
+ char __ss_pad1[_SS_PAD1SIZE];
+ unsigned long __ss_align[_SS_PAD2SIZE / sizeof(unsigned long) + 1];
+};
+
+#endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */
+
+#endif /* HAVE_STRUCT_SOCKADDR_STORAGE */
+
+#ifndef HAVE_STRUCT_ADDRINFO
+struct addrinfo {
+ int ai_flags;
+ int ai_family;
+ int ai_socktype;
+ int ai_protocol;
+ size_t ai_addrlen;
+ char *ai_canonname;
+ struct sockaddr *ai_addr;
+ struct addrinfo *ai_next;
+};
+#endif
+
+#ifndef HAVE_GETADDRINFO
+#define getaddrinfo rk_getaddrinfo
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_getaddrinfo(const char *,
+ const char *,
+ const struct addrinfo *,
+ struct addrinfo **);
+
+#ifndef HAVE_GETNAMEINFO
+#define getnameinfo rk_getnameinfo
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_getnameinfo(const struct sockaddr *, socklen_t,
+ char *, size_t,
+ char *, size_t,
+ int);
+
+#ifndef HAVE_FREEADDRINFO
+#define freeaddrinfo rk_freeaddrinfo
+#endif
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_freeaddrinfo(struct addrinfo *);
+
+#ifndef HAVE_GAI_STRERROR
+#define gai_strerror rk_gai_strerror
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
+gai_strerror(int);
+#endif
+
+#ifdef NO_SLEEP
+
+ROKEN_LIB_FUNCTION unsigned int ROKEN_LIB_CALL
+sleep(unsigned int seconds);
+
+ROKEN_LIB_FUNCTION unsigned int ROKEN_LIB_CALL
+usleep(unsigned int useconds);
+
+#endif
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+getnameinfo_verified(const struct sockaddr *, socklen_t,
+ char *, size_t,
+ char *, size_t,
+ int);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+roken_getaddrinfo_hostspec(const char *, int, struct addrinfo **);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+roken_getaddrinfo_hostspec2(const char *, int, int, struct addrinfo **);
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+roken_get_homedir(char *, size_t);
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+roken_get_appdatadir(char *, size_t);
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+roken_get_username(char *, size_t);
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+roken_get_loginname(char *, size_t);
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+roken_get_shell(char *, size_t);
+
+#ifndef HAVE_STRFTIME
+#define strftime rk_strftime
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+strftime (char *, size_t, const char *, const struct tm *);
+#endif
+
+#ifndef HAVE_STRPTIME
+#define strptime rk_strptime
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+strptime (const char *, const char *, struct tm *);
+#endif
+
+#ifndef HAVE_GETTIMEOFDAY
+#define gettimeofday rk_gettimeofday
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+gettimeofday (struct timeval *, void *);
+#endif
+
+#ifndef HAVE_EMALLOC
+#define emalloc rk_emalloc
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL emalloc (size_t);
+#endif
+#ifndef HAVE_ECALLOC
+#define ecalloc rk_ecalloc
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL ecalloc(size_t, size_t);
+#endif
+#ifndef HAVE_EREALLOC
+#define erealloc rk_erealloc
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL erealloc (void *, size_t);
+#endif
+#ifndef HAVE_ESTRDUP
+#define estrdup rk_estrdup
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL estrdup (const char *);
+#endif
+
+/*
+ * kludges and such
+ */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+roken_gethostby_setup(const char*, const char*);
+ROKEN_LIB_FUNCTION struct hostent* ROKEN_LIB_CALL
+roken_gethostbyname(const char*);
+ROKEN_LIB_FUNCTION struct hostent* ROKEN_LIB_CALL
+roken_gethostbyaddr(const void*, size_t, int);
+
+#ifdef GETSERVBYNAME_PROTO_COMPATIBLE
+#define roken_getservbyname(x,y) getservbyname(x,y)
+#else
+#define roken_getservbyname(x,y) getservbyname((char *)x, (char *)y)
+#endif
+
+#ifdef OPENLOG_PROTO_COMPATIBLE
+#define roken_openlog(a,b,c) openlog(a,b,c)
+#else
+#define roken_openlog(a,b,c) openlog((char *)a,b,c)
+#endif
+
+#ifdef GETSOCKNAME_PROTO_COMPATIBLE
+#define roken_getsockname(a,b,c) getsockname(a,b,c)
+#else
+#define roken_getsockname(a,b,c) getsockname(a, b, (void*)c)
+#endif
+
+#ifndef HAVE_SETPROGNAME
+#define setprogname rk_setprogname
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL setprogname(const char *);
+#endif
+
+#ifndef HAVE_GETPROGNAME
+#define getprogname rk_getprogname
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL getprogname(void);
+#endif
+
+#if !defined(HAVE_SETPROGNAME) && !defined(HAVE_GETPROGNAME) && !HAVE_DECL___PROGNAME
+extern const char *__progname;
+#endif
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+mini_inetd_addrinfo (struct addrinfo*, rk_socket_t *);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+mini_inetd (int, rk_socket_t *);
+
+#ifndef HAVE_LOCALTIME_R
+#define localtime_r rk_localtime_r
+ROKEN_LIB_FUNCTION struct tm * ROKEN_LIB_CALL
+localtime_r(const time_t *, struct tm *);
+#endif
+
+#if !defined(HAVE_STRTOLL) || defined(NEED_STRTOLL_PROTO)
+#ifndef HAVE_STRTOLL
+#define strtoll rk_strtoll
+#endif
+ROKEN_LIB_FUNCTION long long ROKEN_LIB_CALL
+strtoll(const char * nptr, char ** endptr, int base);
+#endif
+
+#if !defined(HAVE_STRTOULL) || defined(NEED_STRTOULL_PROTO)
+#ifndef HAVE_STRTOULL
+#define strtoull rk_strtoull
+#endif
+ROKEN_LIB_FUNCTION unsigned long long ROKEN_LIB_CALL
+strtoull(const char * nptr, char ** endptr, int base);
+#endif
+
+#if !defined(HAVE_STRSVIS) || defined(NEED_STRSVIS_PROTO)
+#ifndef HAVE_STRSVIS
+#define strsvis rk_strsvis
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+strsvis(char *, const char *, int, const char *);
+#endif
+
+#if !defined(HAVE_STRSVISX) || defined(NEED_STRSVISX_PROTO)
+#ifndef HAVE_STRSVISX
+#define strsvisx rk_strsvisx
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+strsvisx(char *, const char *, size_t, int, const char *);
+#endif
+
+#if !defined(HAVE_STRUNVIS) || defined(NEED_STRUNVIS_PROTO)
+#ifndef HAVE_STRUNVIS
+#define strunvis rk_strunvis
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+strunvis(char *, const char *);
+#endif
+
+#if !defined(HAVE_STRVIS) || defined(NEED_STRVIS_PROTO)
+#ifndef HAVE_STRVIS
+#define strvis rk_strvis
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+strvis(char *, const char *, int);
+#endif
+
+#if !defined(HAVE_STRVISX) || defined(NEED_STRVISX_PROTO)
+#ifndef HAVE_STRVISX
+#define strvisx rk_strvisx
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+strvisx(char *, const char *, size_t, int);
+#endif
+
+#if !defined(HAVE_SVIS) || defined(NEED_SVIS_PROTO)
+#ifndef HAVE_SVIS
+#define svis rk_svis
+#endif
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+svis(char *, int, int, int, const char *);
+#endif
+
+#if !defined(HAVE_UNVIS) || defined(NEED_UNVIS_PROTO)
+#ifndef HAVE_UNVIS
+#define unvis rk_unvis
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+unvis(char *, int, int *, int);
+#endif
+
+#if !defined(HAVE_VIS) || defined(NEED_VIS_PROTO)
+#ifndef HAVE_VIS
+#define vis rk_vis
+#endif
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+vis(char *, int, int, int);
+#endif
+
+#if !defined(HAVE_CLOSEFROM)
+#define closefrom rk_closefrom
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+closefrom(int);
+#endif
+
+#if !defined(HAVE_TIMEGM)
+#define timegm rk_timegm
+ROKEN_LIB_FUNCTION time_t ROKEN_LIB_CALL
+rk_timegm(struct tm *tm);
+#endif
+
+#ifdef NEED_QSORT
+#define qsort rk_qsort
+void
+rk_qsort(void *, size_t, size_t, int (*)(const void *, const void *));
+#endif
+
+#if !defined(HAVE_MERGESORT)
+#define mergesort rk_mergesort
+int
+mergesort(void *base, size_t nel, size_t width,
+ int (*compar)(const void *, const void *));
+#endif
+
+#if !defined(HAVE_MERGESORT_R)
+#define mergesort_r rk_mergesort_r
+int
+mergesort_r(void *base, size_t nel, size_t width,
+ int (*compar)(const void *, const void *, void *), void *thunk);
+#endif
+
+#ifndef HAVE_MEMSET_S
+#define memset_s rk_memset_s
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL memset_s(void *s, size_t smax,
+ int c, size_t n);
+#endif
+
+#if defined(HAVE_ARC4RANDOM)
+# define rk_random() arc4random()
+#elif defined(HAVE_RANDOM)
+# define rk_random() random()
+#else
+# ifdef HAVE_WIN32_RAND_S
+ROKEN_LIB_FUNCTION unsigned int ROKEN_LIB_CALL
+rk_random(void);
+# else
+# define rk_random() rand()
+# endif
+#endif
+
+#ifndef HAVE_TDELETE
+#define tdelete(a,b,c) rk_tdelete(a,b,c)
+#endif
+#ifndef HAVE_TFIND
+#define tfind(a,b,c) rk_tfind(a,b,c)
+#endif
+#ifndef HAVE_TSEARCH
+#define tsearch(a,b,c) rk_tsearch(a,b,c)
+#endif
+#ifndef HAVE_TWALK
+#define twalk(a,b) rk_twalk(a,b)
+#endif
+
+#if defined(__linux__) && defined(SOCK_CLOEXEC) && !defined(SOCKET_WRAPPER_REPLACE) && !defined(__SOCKET_WRAPPER_H__)
+#undef socket
+#define socket(_fam,_type,_prot) rk_socket(_fam,_type,_prot)
+int ROKEN_LIB_FUNCTION rk_socket(int, int, int);
+#endif
+
+/* Microsoft VC 2010 POSIX definitions */
+#ifndef EAFNOSUPPORT
+#define EAFNOSUPPORT 102
+#endif
+#ifndef EINPROGRESS
+#define EINPROGRESS 112
+#endif
+#ifndef ELOOP
+#define ELOOP 114
+#endif
+#ifndef ENOTSOCK
+#define ENOTSOCK 128
+#endif
+#ifndef ENOTSUP
+#define ENOTSUP 129
+#endif
+#ifndef EOVERFLOW
+#define EOVERFLOW 132
+#endif
+#ifndef ETIMEDOUT
+#define ETIMEDOUT 138
+#endif
+#ifndef EWOULDBLOCK
+#define EWOULDBLOCK 140
+#endif
+
+#ifdef WIN32
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+win32_getLibraryVersion(const char *libname, char **outname, char **outversion);
+#endif
+
+#ifdef SOCKET_WRAPPER_REPLACE
+#include <socket_wrapper.h>
+#endif
+
+ROKEN_CPP_END
diff --git a/third_party/heimdal/lib/roken/roken_gethostby.c b/third_party/heimdal/lib/roken/roken_gethostby.c
new file mode 100644
index 0000000..a2febd0
--- /dev/null
+++ b/third_party/heimdal/lib/roken/roken_gethostby.c
@@ -0,0 +1,292 @@
+/*
+ * Copyright (c) 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+#undef roken_gethostbyname
+#undef roken_gethostbyaddr
+
+static struct sockaddr_in dns_addr;
+static char *dns_req;
+
+static int
+make_address(const char *address, struct in_addr *ip)
+{
+ if(inet_aton(address, ip) == 0){
+ /* try to resolve as hostname, it might work if the address we
+ are trying to lookup is local, for instance a web proxy */
+ struct hostent *he = gethostbyname(address);
+ if(he) {
+ unsigned char *p = (unsigned char*)he->h_addr;
+ ip->s_addr = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
+ } else {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static int
+setup_int(const char *proxy_host, short proxy_port,
+ const char *dns_host, short dns_port,
+ const char *dns_path)
+{
+ memset(&dns_addr, 0, sizeof(dns_addr));
+ if(dns_req)
+ free(dns_req);
+ dns_req = NULL;
+ if(proxy_host) {
+ if(make_address(proxy_host, &dns_addr.sin_addr) != 0)
+ return -1;
+ dns_addr.sin_port = htons(proxy_port);
+ if (asprintf(&dns_req, "http://%s:%d%s", dns_host, dns_port, dns_path) < 0)
+ return -1;
+ } else {
+ if(make_address(dns_host, &dns_addr.sin_addr) != 0)
+ return -1;
+ dns_addr.sin_port = htons(dns_port);
+ if (asprintf(&dns_req, "%s", dns_path) < 0)
+ return -1;
+ }
+ dns_addr.sin_family = AF_INET;
+ return 0;
+}
+
+static int
+split_spec(const char *spec, char **host, int *port, char **path, int def_port)
+{
+ char *p;
+ *host = strdup(spec);
+ if (*host == NULL)
+ return -1;
+ p = strchr(*host, ':');
+ if(p) {
+ *p++ = '\0';
+ if(sscanf(p, "%d", port) != 1)
+ *port = def_port;
+ } else
+ *port = def_port;
+ p = strchr(p ? p : *host, '/');
+ if(p) {
+ if(path) {
+ *path = strdup(p);
+ if (*path == NULL) {
+ free(*host);
+ *host = NULL;
+ return -1;
+ }
+ }
+ *p = '\0';
+ }else
+ if(path)
+ *path = NULL;
+ return 0;
+}
+
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+roken_gethostby_setup(const char *proxy_spec, const char *dns_spec)
+{
+ char *proxy_host = NULL;
+ int proxy_port = 0;
+ char *dns_host = NULL, *dns_path = NULL;
+ int dns_port;
+ int ret;
+
+ ret = split_spec(dns_spec, &dns_host, &dns_port, &dns_path, 80);
+ if(ret)
+ goto out;
+ if(proxy_spec) {
+ ret = split_spec(proxy_spec, &proxy_host, &proxy_port, NULL, 80);
+ if (ret)
+ goto out;
+ }
+ ret = setup_int(proxy_host, proxy_port, dns_host, dns_port, dns_path);
+ if (ret)
+ goto out;
+
+out:
+ free(proxy_host);
+ free(dns_host);
+ free(dns_path);
+ return ret;
+}
+
+
+/* Try to lookup a name or an ip-address using http as transport
+ mechanism. See the end of this file for an example program. */
+static struct hostent*
+roken_gethostby(const char *hostname)
+{
+ int s;
+ struct sockaddr_in addr;
+ char *request = NULL;
+ char buf[1024];
+ int offset = 0;
+ int n;
+ char *p, *foo;
+ size_t len;
+
+ if(dns_addr.sin_family == 0)
+ return NULL; /* no configured host */
+ addr = dns_addr;
+ if (asprintf(&request, "GET %s?%s HTTP/1.0\r\n\r\n", dns_req, hostname) < 0)
+ return NULL;
+ if(request == NULL)
+ return NULL;
+ s = socket(AF_INET, SOCK_STREAM, 0);
+ if(s < 0) {
+ free(request);
+ return NULL;
+ }
+ if(connect(s, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
+ close(s);
+ free(request);
+ return NULL;
+ }
+
+ len = strlen(request);
+ if(write(s, request, len) != (ssize_t)len) {
+ close(s);
+ free(request);
+ return NULL;
+ }
+ free(request);
+ while(1) {
+ n = read(s, buf + offset, sizeof(buf) - offset);
+ if(n <= 0)
+ break;
+ offset += n;
+ }
+ buf[offset] = '\0';
+ close(s);
+ p = strstr(buf, "\r\n\r\n"); /* find end of header */
+ if(p) p += 4;
+ else return NULL;
+ foo = NULL;
+ p = strtok_r(p, " \t\r\n", &foo);
+ if(p == NULL)
+ return NULL;
+ {
+ /* make a hostent to return */
+#define MAX_ADDRS 16
+ static struct hostent he;
+ static char addrs[4 * MAX_ADDRS];
+ static char *addr_list[MAX_ADDRS + 1];
+ int num_addrs = 0;
+
+ he.h_name = p;
+ he.h_aliases = NULL;
+ he.h_addrtype = AF_INET;
+ he.h_length = 4;
+
+ while((p = strtok_r(NULL, " \t\r\n", &foo)) && num_addrs < MAX_ADDRS) {
+ struct in_addr ip;
+ inet_aton(p, &ip);
+ ip.s_addr = ntohl(ip.s_addr);
+ addr_list[num_addrs] = &addrs[num_addrs * 4];
+ addrs[num_addrs * 4 + 0] = (ip.s_addr >> 24) & 0xff;
+ addrs[num_addrs * 4 + 1] = (ip.s_addr >> 16) & 0xff;
+ addrs[num_addrs * 4 + 2] = (ip.s_addr >> 8) & 0xff;
+ addrs[num_addrs * 4 + 3] = (ip.s_addr >> 0) & 0xff;
+ addr_list[++num_addrs] = NULL;
+ }
+ he.h_addr_list = addr_list;
+ return &he;
+ }
+}
+
+ROKEN_LIB_FUNCTION struct hostent* ROKEN_LIB_CALL
+roken_gethostbyname(const char *hostname)
+{
+ struct hostent *he;
+ he = gethostbyname(hostname);
+ if(he)
+ return he;
+ return roken_gethostby(hostname);
+}
+
+ROKEN_LIB_FUNCTION struct hostent* ROKEN_LIB_CALL
+roken_gethostbyaddr(const void *addr, size_t len, int type)
+{
+ struct in_addr a;
+ const char *p;
+ struct hostent *he;
+ he = gethostbyaddr(addr, len, type);
+ if(he)
+ return he;
+ if(type != AF_INET || len != 4)
+ return NULL;
+ p = addr;
+ a.s_addr = htonl((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]);
+ return roken_gethostby(inet_ntoa(a));
+}
+
+#if 0
+
+/* this program can be used as a cgi `script' to lookup names and
+ ip-addresses */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <netdb.h>
+#include <sys/param.h>
+
+int
+main(int argc, char **argv)
+{
+ char *query = getenv("QUERY_STRING");
+ char host[MAXHOSTNAMELEN];
+ int i;
+ struct hostent *he;
+
+ printf("Content-type: text/plain\n\n");
+ if(query == NULL)
+ exit(0);
+ he = gethostbyname(query);
+ strncpy(host, he->h_name, sizeof(host));
+ host[sizeof(host) - 1] = '\0';
+ he = gethostbyaddr(he->h_addr, he->h_length, AF_INET);
+ printf("%s\n", he->h_name);
+ for(i = 0; he->h_addr_list[i]; i++) {
+ struct in_addr ip;
+ unsigned char *p = (unsigned char*)he->h_addr_list[i];
+ ip.s_addr = htonl((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]);
+ printf("%s\n", inet_ntoa(ip));
+ }
+ exit(0);
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/rtbl.3 b/third_party/heimdal/lib/roken/rtbl.3
new file mode 100644
index 0000000..0d70918
--- /dev/null
+++ b/third_party/heimdal/lib/roken/rtbl.3
@@ -0,0 +1,201 @@
+.\" Copyright (c) 2004 Kungliga Tekniska Högskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\" $Id$
+.\"
+.Dd June 26, 2004
+.Dt RTBL 3
+.Os HEIMDAL
+.Sh NAME
+.Nm rtbl_create ,
+.Nm rtbl_destroy ,
+.Nm rtbl_set_flags ,
+.Nm rtbl_get_flags ,
+.Nm rtbl_set_prefix ,
+.Nm rtbl_set_separator ,
+.Nm rtbl_set_column_prefix ,
+.Nm rtbl_set_column_affix_by_id ,
+.Nm rtbl_add_column ,
+.Nm rtbl_add_column_by_id ,
+.Nm rtbl_add_column_entry ,
+.Nm rtbl_add_column_entry_by_id ,
+.Nm rtbl_new_row ,
+.Nm rtbl_format
+.Nd format data in simple tables
+.Sh LIBRARY
+The roken library (libroken, -lroken)
+.Sh SYNOPSIS
+.In rtbl.h
+.Ft int
+.Fn rtbl_add_column "rtbl_t table" "const char *column_name" "unsigned int flags"
+.Ft int
+.Fn rtbl_add_column_by_id "rtbl_t table" "unsigned int column_id" "const char *column_header" "unsigned int flags"
+.Ft int
+.Fn rtbl_add_column_entry "rtbl_t table" "const char *column_name" "const char *cell_entry"
+.Ft int
+.Fn rtbl_add_column_entry_by_id "rtbl_t table" "unsigned int column_id" "const char *cell_entry"
+.Ft rtbl_t
+.Fn rtbl_create "void"
+.Ft void
+.Fn rtbl_destroy "rtbl_t table"
+.Ft int
+.Fn rtbl_new_row "rtbl_t table"
+.Ft int
+.Fn rtbl_set_column_affix_by_id "rtbl_t table" "unsigned int column_id "const char *prefix" "const char *suffix"
+.Ft int
+.Fn rtbl_set_column_prefix "rtbl_t table" "const char *column_name" "const char *prefix"
+.Ft "unsigned int"
+.Fn rtbl_get_flags "rtbl_t table"
+.Ft void
+.Fn rtbl_set_flags "rtbl_t table" "unsigned int flags"
+.Ft int
+.Fn rtbl_set_prefix "rtbl_t table" "const char *prefix"
+.Ft int
+.Fn rtbl_set_separator "rtbl_t table" "const char *separator"
+.Ft int
+.Fn rtbl_format "rtbl_t table "FILE *file"
+.Sh DESCRIPTION
+This set of functions assemble a simple table consisting of rows and
+columns, allowing it to be printed with certain options. Typical use
+would be output from tools such as
+.Xr ls 1
+or
+.Xr netstat 1 ,
+where you have a fixed number of columns, but don't know the column
+widths before hand.
+.Pp
+A table is created with
+.Fn rtbl_create
+and destroyed with
+.Fn rtbl_destroy .
+.Pp
+Global flags on the table are set with
+.Fa rtbl_set_flags
+and retrieved with
+.Fa rtbl_get_flags .
+At present the only defined flag is
+.Dv RTBL_HEADER_STYLE_NONE
+which suppresses printing the header.
+.Pp
+Before adding data to the table, one or more columns need to be
+created. This would normally be done with
+.Fn rtbl_add_column_by_id ,
+.Fa column_id
+is any number of your choice (it's used only to identify columns),
+.Fa column_header
+is the header to print at the top of the column, and
+.Fa flags
+are flags specific to this column. Currently the only defined flag is
+.Dv RTBL_ALIGN_RIGHT ,
+aligning column entries to the right. Columns are printed in the order
+they are added.
+.Pp
+There's also a way to add columns by column name with
+.Fn rtbl_add_column ,
+but this is less flexible (you need unique header names), and is
+considered deprecated.
+.Pp
+To add data to a column you use
+.Fn rtbl_add_column_entry_by_id ,
+where the
+.Fa column_id
+is the same as when the column was added (adding data to a
+non-existent column is undefined), and
+.Fa cell_entry
+is whatever string you wish to include in that cell. It should not
+include newlines.
+For columns added with
+.Fn rtbl_add_column
+you must use
+.Fn rtbl_add_column_entry
+instead.
+.Pp
+.Fn rtbl_new_row
+fills all columns with blank entries until they all have the same
+number of rows.
+.Pp
+Each column can have a separate prefix and suffix, set with
+.Fa rtbl_set_column_affix_by_id ;
+.Fa rtbl_set_column_prefix
+allows setting the prefix only by column name. In addition to this,
+columns may be separated by a string set with
+.Fa rtbl_set_separator ( Ns
+by default columns are not seprated by anything).
+.Pp
+The finished table is printed to
+.Fa file
+with
+.Fa rtbl_format .
+.Sh EXAMPLES
+This program:
+.Bd -literal -offset xxxx
+#include <stdio.h>
+#include <rtbl.h>
+int
+main(int argc, char **argv)
+{
+ rtbl_t table;
+ table = rtbl_create();
+ rtbl_set_separator(table, " ");
+ rtbl_add_column_by_id(table, 0, "Column A", 0);
+ rtbl_add_column_by_id(table, 1, "Column B", RTBL_ALIGN_RIGHT);
+ rtbl_add_column_by_id(table, 2, "Column C", 0);
+ rtbl_add_column_entry_by_id(table, 0, "A-1");
+ rtbl_add_column_entry_by_id(table, 0, "A-2");
+ rtbl_add_column_entry_by_id(table, 0, "A-3");
+ rtbl_add_column_entry_by_id(table, 1, "B-1");
+ rtbl_add_column_entry_by_id(table, 2, "C-1");
+ rtbl_add_column_entry_by_id(table, 2, "C-2");
+ rtbl_add_column_entry_by_id(table, 1, "B-2");
+ rtbl_add_column_entry_by_id(table, 1, "B-3");
+ rtbl_add_column_entry_by_id(table, 2, "C-3");
+ rtbl_add_column_entry_by_id(table, 0, "A-4");
+ rtbl_new_row(table);
+ rtbl_add_column_entry_by_id(table, 1, "B-4");
+ rtbl_new_row(table);
+ rtbl_add_column_entry_by_id(table, 2, "C-4");
+ rtbl_new_row(table);
+ rtbl_format(table, stdout);
+ rtbl_destroy(table);
+ return 0;
+}
+.Ed
+.Pp
+will output the following:
+.Bd -literal -offset xxxx
+Column A Column B Column C
+A-1 B-1 C-1
+A-2 B-2 C-2
+A-3 B-3 C-3
+A-4
+ B-4
+ C-4
+.Ed
+.\" .Sh SEE ALSO
diff --git a/third_party/heimdal/lib/roken/rtbl.c b/third_party/heimdal/lib/roken/rtbl.c
new file mode 100644
index 0000000..efcf55e
--- /dev/null
+++ b/third_party/heimdal/lib/roken/rtbl.c
@@ -0,0 +1,558 @@
+/*
+ * Copyright (c) 2000, 2002, 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include <ctype.h>
+#include "rtbl.h"
+
+struct column_entry {
+ char *data;
+};
+
+struct column_data {
+ char *header;
+ char *prefix;
+ int width;
+ unsigned flags;
+ size_t num_rows;
+ struct column_entry *rows;
+ unsigned int column_id;
+ char *suffix;
+};
+
+struct rtbl_data {
+ char *column_prefix;
+ size_t num_columns;
+ struct column_data **columns;
+ unsigned int flags;
+ char *column_separator;
+};
+
+ROKEN_LIB_FUNCTION rtbl_t ROKEN_LIB_CALL
+rtbl_create (void)
+{
+ return calloc (1, sizeof (struct rtbl_data));
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rtbl_set_flags (rtbl_t table, unsigned int flags)
+{
+ table->flags = flags;
+}
+
+ROKEN_LIB_FUNCTION unsigned int ROKEN_LIB_CALL
+rtbl_get_flags (rtbl_t table)
+{
+ return table->flags;
+}
+
+static struct column_data *
+rtbl_get_column_by_id (rtbl_t table, unsigned int id)
+{
+ size_t i;
+ for(i = 0; i < table->num_columns; i++)
+ if(table->columns[i]->column_id == id)
+ return table->columns[i];
+ return NULL;
+}
+
+static struct column_data *
+rtbl_get_column (rtbl_t table, const char *column)
+{
+ size_t i;
+ for(i = 0; i < table->num_columns; i++)
+ if(strcmp(table->columns[i]->header, column) == 0)
+ return table->columns[i];
+ return NULL;
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rtbl_destroy (rtbl_t table)
+{
+ size_t i, j;
+
+ for (i = 0; i < table->num_columns; i++) {
+ struct column_data *c = table->columns[i];
+
+ for (j = 0; j < c->num_rows; j++)
+ free (c->rows[j].data);
+ free (c->rows);
+ free (c->header);
+ free (c->prefix);
+ free (c->suffix);
+ free (c);
+ }
+ free (table->column_prefix);
+ free (table->column_separator);
+ free (table->columns);
+ free (table);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_add_column_by_id (rtbl_t table, unsigned int id,
+ const char *header, unsigned int flags)
+{
+ struct column_data *col, **tmp;
+
+ tmp = realloc (table->columns, (table->num_columns + 1) * sizeof (*tmp));
+ if (tmp == NULL)
+ return ENOMEM;
+ table->columns = tmp;
+ col = malloc (sizeof (*col));
+ if (col == NULL)
+ return ENOMEM;
+ col->header = strdup (header);
+ if (col->header == NULL) {
+ free (col);
+ return ENOMEM;
+ }
+ col->prefix = NULL;
+ col->width = 0;
+ col->flags = flags;
+ col->num_rows = 0;
+ col->rows = NULL;
+ col->column_id = id;
+ col->suffix = NULL;
+ table->columns[table->num_columns++] = col;
+ return 0;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_add_column (rtbl_t table, const char *header, unsigned int flags)
+{
+ return rtbl_add_column_by_id(table, 0, header, flags);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_new_row(rtbl_t table)
+{
+ size_t max_rows = 0;
+ size_t c;
+ for (c = 0; c < table->num_columns; c++)
+ if(table->columns[c]->num_rows > max_rows)
+ max_rows = table->columns[c]->num_rows;
+ for (c = 0; c < table->num_columns; c++) {
+ struct column_entry *tmp;
+
+ if(table->columns[c]->num_rows == max_rows)
+ continue;
+ tmp = realloc(table->columns[c]->rows,
+ max_rows * sizeof(table->columns[c]->rows[0]));
+ if(tmp == NULL)
+ return ENOMEM;
+ table->columns[c]->rows = tmp;
+ while(table->columns[c]->num_rows < max_rows) {
+ if((tmp[table->columns[c]->num_rows++].data = strdup("")) == NULL)
+ return ENOMEM;
+ }
+ }
+ return 0;
+}
+
+static void
+column_compute_width (rtbl_t table, struct column_data *column)
+{
+ size_t i;
+
+ if(table->flags & RTBL_HEADER_STYLE_NONE)
+ column->width = 0;
+ else
+ column->width = (int)strlen (column->header);
+ for (i = 0; i < column->num_rows; i++)
+ column->width = max (column->width, (int) strlen (column->rows[i].data));
+}
+
+/* DEPRECATED */
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_set_prefix (rtbl_t table, const char *prefix)
+{
+ if (table->column_prefix)
+ free (table->column_prefix);
+ table->column_prefix = strdup (prefix);
+ if (table->column_prefix == NULL)
+ return ENOMEM;
+ return 0;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_set_separator (rtbl_t table, const char *separator)
+{
+ if (table->column_separator)
+ free (table->column_separator);
+ table->column_separator = strdup (separator);
+ if (table->column_separator == NULL)
+ return ENOMEM;
+ return 0;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_set_column_prefix (rtbl_t table, const char *column,
+ const char *prefix)
+{
+ struct column_data *c = rtbl_get_column (table, column);
+
+ if (c == NULL)
+ return -1;
+ if (c->prefix)
+ free (c->prefix);
+ c->prefix = strdup (prefix);
+ if (c->prefix == NULL)
+ return ENOMEM;
+ return 0;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_set_column_affix_by_id(rtbl_t table, unsigned int id,
+ const char *prefix, const char *suffix)
+{
+ struct column_data *c = rtbl_get_column_by_id (table, id);
+
+ if (c == NULL)
+ return -1;
+ if (c->prefix)
+ free (c->prefix);
+ if(prefix == NULL)
+ c->prefix = NULL;
+ else {
+ c->prefix = strdup (prefix);
+ if (c->prefix == NULL)
+ return ENOMEM;
+ }
+
+ if (c->suffix)
+ free (c->suffix);
+ if(suffix == NULL)
+ c->suffix = NULL;
+ else {
+ c->suffix = strdup (suffix);
+ if (c->suffix == NULL)
+ return ENOMEM;
+ }
+ return 0;
+}
+
+
+static const char *
+get_column_prefix (rtbl_t table, struct column_data *c)
+{
+ if (c == NULL)
+ return "";
+ if (c->prefix)
+ return c->prefix;
+ if (table->column_prefix)
+ return table->column_prefix;
+ return "";
+}
+
+static const char *
+get_column_suffix (rtbl_t table, struct column_data *c)
+{
+ if (c && c->suffix)
+ return c->suffix;
+ return "";
+}
+
+static int
+add_column_entry (struct column_data *c, const char *data)
+{
+ struct column_entry row, *tmp;
+
+ row.data = strdup (data);
+ if (row.data == NULL)
+ return ENOMEM;
+ tmp = realloc (c->rows, (c->num_rows + 1) * sizeof (*tmp));
+ if (tmp == NULL) {
+ free (row.data);
+ return ENOMEM;
+ }
+ c->rows = tmp;
+ c->rows[c->num_rows++] = row;
+ return 0;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_add_column_entry_by_id (rtbl_t table, unsigned int id, const char *data)
+{
+ struct column_data *c = rtbl_get_column_by_id (table, id);
+
+ if (c == NULL)
+ return -1;
+
+ return add_column_entry(c, data);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_add_column_entryv_by_id (rtbl_t table, unsigned int id,
+ const char *fmt, ...)
+{
+ va_list ap;
+ char *str;
+ int ret;
+
+ va_start(ap, fmt);
+ ret = vasprintf(&str, fmt, ap);
+ va_end(ap);
+ if (ret == -1)
+ return -1;
+ ret = rtbl_add_column_entry_by_id(table, id, str);
+ free(str);
+ return ret;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_add_column_entry (rtbl_t table, const char *column, const char *data)
+{
+ struct column_data *c = rtbl_get_column (table, column);
+
+ if (c == NULL)
+ return -1;
+
+ return add_column_entry(c, data);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_add_column_entryv (rtbl_t table, const char *column, const char *fmt, ...)
+{
+ va_list ap;
+ char *str;
+ int ret;
+
+ va_start(ap, fmt);
+ ret = vasprintf(&str, fmt, ap);
+ va_end(ap);
+ if (ret == -1)
+ return -1;
+ ret = rtbl_add_column_entry(table, column, str);
+ free(str);
+ return ret;
+}
+
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_format (rtbl_t table, FILE * f)
+{
+ char *str = rtbl_format_str(table);
+ if (str == NULL)
+ return ENOMEM;
+ fprintf(f, "%s", str);
+ free(str);
+ return 0;
+}
+
+static char *
+rtbl_format_pretty(rtbl_t table)
+{
+ struct rk_strpool *p = NULL;
+ size_t i, j;
+
+ for (i = 0; i < table->num_columns; i++)
+ column_compute_width (table, table->columns[i]);
+ if((table->flags & RTBL_HEADER_STYLE_NONE) == 0) {
+ for (i = 0; i < table->num_columns; i++) {
+ struct column_data *c = table->columns[i];
+
+ if(table->column_separator != NULL && i > 0)
+ p = rk_strpoolprintf(p, "%s", table->column_separator);
+ p = rk_strpoolprintf(p, "%s", get_column_prefix (table, c));
+ if (c == NULL) {
+ /* do nothing if no column */
+ } else if(i == table->num_columns - 1 && c->suffix == NULL)
+ /* last column, so no need to pad with spaces */
+ p = rk_strpoolprintf(p, "%-*s", 0, c->header);
+ else
+ p = rk_strpoolprintf(p, "%-*s", (int)c->width, c->header);
+ p = rk_strpoolprintf(p, "%s", get_column_suffix (table, c));
+ }
+ p = rk_strpoolprintf(p, "\n");
+ }
+
+ for (j = 0;; j++) {
+ int flag = 0;
+
+ /* are there any more rows left? */
+ for (i = 0; flag == 0 && i < table->num_columns; ++i) {
+ struct column_data *c = table->columns[i];
+
+ if (c->num_rows > j) {
+ ++flag;
+ break;
+ }
+ }
+ if (flag == 0)
+ break;
+
+ for (i = 0; i < table->num_columns; i++) {
+ int w;
+ struct column_data *c = table->columns[i];
+
+ if(table->column_separator != NULL && i > 0)
+ p = rk_strpoolprintf(p, "%s", table->column_separator);
+
+ w = c->width;
+
+ if ((c->flags & RTBL_ALIGN_RIGHT) == 0) {
+ if(i == table->num_columns - 1 && c->suffix == NULL)
+ /* last column, so no need to pad with spaces */
+ w = 0;
+ else
+ w = -w;
+ }
+ p = rk_strpoolprintf(p, "%s", get_column_prefix (table, c));
+ if (c->num_rows <= j)
+ p = rk_strpoolprintf(p, "%*s", w, "");
+ else
+ p = rk_strpoolprintf(p, "%*s", w, c->rows[j].data);
+ p = rk_strpoolprintf(p, "%s", get_column_suffix (table, c));
+ }
+ p = rk_strpoolprintf(p, "\n");
+ }
+
+ return rk_strpoolcollect(p);
+}
+
+static char *
+rtbl_format_json(rtbl_t table)
+{
+ struct rk_strpool *p = NULL;
+ size_t i, j;
+ int comma;
+
+ p = rk_strpoolprintf(p, "[");
+ for (j = 0;; j++) {
+ int flag = 0;
+
+ /* are there any more rows left? */
+ for (i = 0; flag == 0 && i < table->num_columns; ++i) {
+ struct column_data *c = table->columns[i];
+
+ if (c->num_rows > j) {
+ ++flag;
+ break;
+ }
+ }
+ if (flag == 0)
+ break;
+
+ p = rk_strpoolprintf(p, "%s{", j > 0 ? "," : "");
+
+ comma = 0;
+ for (i = 0; i < table->num_columns; i++) {
+ struct column_data *c = table->columns[i];
+
+ if (c->num_rows > j) {
+ char *header = c->header;
+ while (isspace((int)header[0])) /* trim off prefixed whitespace */
+ header++;
+ p = rk_strpoolprintf(p, "%s\"%s\" : \"%s\"",
+ comma ? "," : "", header,
+ c->rows[j].data);
+ comma = 1;
+ }
+ }
+ p = rk_strpoolprintf(p, "}");
+ }
+ p = rk_strpoolprintf(p, "]");
+
+ return rk_strpoolcollect(p);
+}
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+rtbl_format_str (rtbl_t table)
+{
+ if (table->flags & RTBL_JSON)
+ return rtbl_format_json(table);
+
+ return rtbl_format_pretty(table);
+}
+
+#ifdef TEST
+int
+main (int argc, char **argv)
+{
+ rtbl_t table;
+
+ table = rtbl_create ();
+ rtbl_add_column_by_id (table, 0, "Issued", 0);
+ rtbl_add_column_by_id (table, 1, "Expires", 0);
+ rtbl_add_column_by_id (table, 2, "Foo", RTBL_ALIGN_RIGHT);
+ rtbl_add_column_by_id (table, 3, "Principal", 0);
+
+ rtbl_add_column_entry_by_id (table, 0, "Jul 7 21:19:29");
+ rtbl_add_column_entry_by_id (table, 1, "Jul 8 07:19:29");
+ rtbl_add_column_entry_by_id (table, 2, "73");
+ rtbl_add_column_entry_by_id (table, 2, "0");
+ rtbl_add_column_entry_by_id (table, 2, "-2000");
+ rtbl_add_column_entry_by_id (table, 3, "krbtgt/NADA.KTH.SE@NADA.KTH.SE");
+
+ rtbl_add_column_entry_by_id (table, 0, "Jul 7 21:19:29");
+ rtbl_add_column_entry_by_id (table, 1, "Jul 8 07:19:29");
+ rtbl_add_column_entry_by_id (table, 3, "afs/pdc.kth.se@NADA.KTH.SE");
+
+ rtbl_add_column_entry_by_id (table, 0, "Jul 7 21:19:29");
+ rtbl_add_column_entry_by_id (table, 1, "Jul 8 07:19:29");
+ rtbl_add_column_entry_by_id (table, 3, "afs@NADA.KTH.SE");
+
+ rtbl_set_separator (table, " ");
+
+ rtbl_format (table, stdout);
+
+ rtbl_destroy (table);
+
+ printf("\n");
+
+ table = rtbl_create ();
+ rtbl_add_column_by_id (table, 0, "Column A", 0);
+ rtbl_set_column_affix_by_id (table, 0, "<", ">");
+ rtbl_add_column_by_id (table, 1, "Column B", 0);
+ rtbl_set_column_affix_by_id (table, 1, "[", "]");
+ rtbl_add_column_by_id (table, 2, "Column C", 0);
+ rtbl_set_column_affix_by_id (table, 2, "(", ")");
+
+ rtbl_add_column_entry_by_id (table, 0, "1");
+ rtbl_new_row(table);
+ rtbl_add_column_entry_by_id (table, 1, "2");
+ rtbl_new_row(table);
+ rtbl_add_column_entry_by_id (table, 2, "3");
+ rtbl_new_row(table);
+
+ rtbl_set_separator (table, " ");
+ rtbl_format (table, stdout);
+
+ rtbl_destroy (table);
+
+ return 0;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/rtbl.h b/third_party/heimdal/lib/roken/rtbl.h
new file mode 100644
index 0000000..274f75c
--- /dev/null
+++ b/third_party/heimdal/lib/roken/rtbl.h
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2000,2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+/* $Id$ */
+
+#ifndef __rtbl_h__
+#define __rtbl_h__
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __cdecl
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+#if !defined(__GNUC__) && !defined(__attribute__)
+#define __attribute__(x)
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct rtbl_data;
+typedef struct rtbl_data *rtbl_t;
+
+#define RTBL_ALIGN_LEFT 0
+#define RTBL_ALIGN_RIGHT 1
+
+/* flags */
+#define RTBL_HEADER_STYLE_NONE 1
+#define RTBL_JSON 2
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_add_column (rtbl_t, const char*, unsigned int);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_add_column_by_id (rtbl_t, unsigned int, const char*, unsigned int);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_add_column_entryv_by_id (rtbl_t table, unsigned int id,
+ const char *fmt, ...)
+ __attribute__ ((__format__ (__printf__, 3, 0)));
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_add_column_entry (rtbl_t, const char*, const char*);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_add_column_entryv (rtbl_t, const char*, const char*, ...)
+ __attribute__ ((__format__ (__printf__, 3, 0)));
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_add_column_entry_by_id (rtbl_t, unsigned int, const char*);
+
+ROKEN_LIB_FUNCTION rtbl_t ROKEN_LIB_CALL
+rtbl_create (void);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rtbl_destroy (rtbl_t);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_format (rtbl_t, FILE*);
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+rtbl_format_str (rtbl_t);
+
+ROKEN_LIB_FUNCTION unsigned int ROKEN_LIB_CALL
+rtbl_get_flags (rtbl_t);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_new_row (rtbl_t);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_set_column_affix_by_id (rtbl_t, unsigned int, const char*, const char*);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_set_column_prefix (rtbl_t, const char*, const char*);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rtbl_set_flags (rtbl_t, unsigned int);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_set_prefix (rtbl_t, const char*);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_set_separator (rtbl_t, const char*);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __rtbl_h__ */
diff --git a/third_party/heimdal/lib/roken/search.hin b/third_party/heimdal/lib/roken/search.hin
new file mode 100644
index 0000000..f8592c4
--- /dev/null
+++ b/third_party/heimdal/lib/roken/search.hin
@@ -0,0 +1,44 @@
+/*-
+ * Written by J.T. Conklin <jtc@netbsd.org>
+ * Public domain.
+ *
+ * $NetBSD: search.h,v 1.12 1999/02/22 10:34:28 christos Exp $
+ */
+
+#ifndef _rk_SEARCH_H_
+#define _rk_SEARCH_H_ 1
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __cdecl
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+#ifndef _WIN32
+#include <sys/cdefs.h>
+#endif
+#include <sys/types.h>
+
+typedef enum {
+ preorder,
+ postorder,
+ endorder,
+ leaf
+} VISIT;
+
+ROKEN_CPP_START
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL rk_tdelete(const void *, void **,
+ int (*)(const void *, const void *));
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL rk_tfind(const void *, void * const *,
+ int (*)(const void *, const void *));
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL rk_tsearch(const void *, void **, int (*)(const void *, const void *));
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL rk_twalk(const void *, void (*)(const void *, VISIT, int));
+
+ROKEN_CPP_END
+
+#endif /* !_rk_SEARCH_H_ */
diff --git a/third_party/heimdal/lib/roken/secure_getenv.c b/third_party/heimdal/lib/roken/secure_getenv.c
new file mode 100644
index 0000000..d97d03d
--- /dev/null
+++ b/third_party/heimdal/lib/roken/secure_getenv.c
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <errno.h>
+
+#include "roken.h"
+#include "secure_getenv.h"
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+rk_secure_getenv(const char *name)
+{
+ if (issuid())
+ return NULL;
+ return getenv(name);
+}
diff --git a/third_party/heimdal/lib/roken/secure_getenv.h b/third_party/heimdal/lib/roken/secure_getenv.h
new file mode 100644
index 0000000..a3f5363
--- /dev/null
+++ b/third_party/heimdal/lib/roken/secure_getenv.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+ rk_secure_getenv(const char *);
+
+#ifndef HAVE_SECURE_GETENV
+#undef secure_getenv
+#define secure_getenv(e) rk_secure_getenv(e)
+#endif
diff --git a/third_party/heimdal/lib/roken/sendmsg.c b/third_party/heimdal/lib/roken/sendmsg.c
new file mode 100644
index 0000000..c685377
--- /dev/null
+++ b/third_party/heimdal/lib/roken/sendmsg.c
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+#ifndef _WIN32
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+sendmsg(rk_socket_t s, const struct msghdr *msg, int flags)
+{
+ ssize_t ret;
+ size_t tot = 0;
+ int i;
+ char *buf, *p;
+ struct iovec *iov = msg->msg_iov;
+
+ for(i = 0; i < msg->msg_iovlen; ++i)
+ tot += iov[i].iov_len;
+ buf = malloc(tot);
+ if (tot != 0 && buf == NULL) {
+ errno = ENOMEM;
+ return -1;
+ }
+ p = buf;
+ for (i = 0; i < msg->msg_iovlen; ++i) {
+ memcpy (p, iov[i].iov_base, iov[i].iov_len);
+ p += iov[i].iov_len;
+ }
+ ret = sendto (s, buf, tot, flags, msg->msg_name, msg->msg_namelen);
+ free (buf);
+ return ret;
+}
+
+#else /* _WIN32 */
+
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * - Neither the name of Secure Endpoints Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+/**
+ * Implementation of sendmsg() for WIN32
+ *
+ * We are using a contrived definition of msghdr which actually uses
+ * an array of ::_WSABUF structures instead of ::iovec . This allows
+ * us to call WSASend directly using the given ::msghdr instead of
+ * having to allocate another array of ::_WSABUF and copying data for
+ * each call.
+ *
+ * Limitations:
+ *
+ * - msg->msg_name is ignored. So is msg->control.
+ * - WSASend() only supports ::MSG_DONTROUTE, ::MSG_OOB and
+ * ::MSG_PARTIAL.
+ *
+ * @param[in] s The socket to use.
+ * @param[in] msg The message
+ * @param[in] flags Flags. A combination of ::MSG_DONTROUTE,
+ * ::MSG_OOB and ::MSG_PARTIAL
+ *
+ * @return The number of bytes sent, on success. Or -1 on error.
+ */
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+sendmsg_w32(rk_socket_t s, const struct msghdr * msg, int flags)
+{
+ int srv;
+ DWORD num_bytes_sent = 0;
+
+ /* TODO: For _WIN32_WINNT >= 0x0600 we can use WSASendMsg using
+ WSAMSG which is a much more direct analogue to sendmsg(). */
+
+ srv = WSASend(s, msg->msg_iov, msg->msg_iovlen,
+ &num_bytes_sent, flags, NULL, NULL);
+
+ if (srv == 0)
+ return (int) num_bytes_sent;
+
+ /* srv == SOCKET_ERROR and WSAGetLastError() == WSA_IO_PENDING
+ indicates that a non-blocking transfer has been scheduled.
+ We'll have to check for that if we ever support non-blocking
+ I/O. */
+
+ return -1;
+}
+
+#endif /* !_WIN32 */
diff --git a/third_party/heimdal/lib/roken/setegid.c b/third_party/heimdal/lib/roken/setegid.c
new file mode 100644
index 0000000..d9aef12
--- /dev/null
+++ b/third_party/heimdal/lib/roken/setegid.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+setegid(gid_t egid)
+{
+#ifdef HAVE_SETREGID
+ return setregid(-1, egid);
+#endif
+
+#ifdef HAVE_SETRESGID
+ return setresgid(-1, egid, -1);
+#endif
+
+ return -1;
+}
diff --git a/third_party/heimdal/lib/roken/setenv.c b/third_party/heimdal/lib/roken/setenv.c
new file mode 100644
index 0000000..b4dbefe
--- /dev/null
+++ b/third_party/heimdal/lib/roken/setenv.c
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+/*
+ * This is the easy way out, use putenv to implement setenv. We might
+ * leak some memory but that is ok since we are usally about to exec
+ * anyway.
+ */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+setenv(const char *var, const char *val, int rewrite)
+{
+#ifndef _WIN32
+ char *t = NULL;
+
+ if (!rewrite && getenv(var) != 0)
+ return 0;
+
+ if (asprintf (&t, "%s=%s", var, val) < 0 || t == NULL)
+ return -1;
+
+ if (putenv(t) == 0)
+ return 0;
+ else
+ return -1;
+#else /* Win32 */
+ char dummy[8];
+
+ if (!rewrite && GetEnvironmentVariable(var, dummy, sizeof(dummy)/sizeof(char)) != 0)
+ return 0;
+
+ if (SetEnvironmentVariable(var, val) == 0)
+ return -1;
+ else
+ return 0;
+#endif
+}
diff --git a/third_party/heimdal/lib/roken/seteuid.c b/third_party/heimdal/lib/roken/seteuid.c
new file mode 100644
index 0000000..2d8c148
--- /dev/null
+++ b/third_party/heimdal/lib/roken/seteuid.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+seteuid(uid_t euid)
+{
+#ifdef HAVE_SETREUID
+ return setreuid(-1, euid);
+#endif
+
+#ifdef HAVE_SETRESUID
+ return setresuid(-1, euid, -1);
+#endif
+
+ return -1;
+}
diff --git a/third_party/heimdal/lib/roken/setprogname.c b/third_party/heimdal/lib/roken/setprogname.c
new file mode 100644
index 0000000..d24106a
--- /dev/null
+++ b/third_party/heimdal/lib/roken/setprogname.c
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 1995-2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+#ifndef HAVE___PROGNAME
+extern const char *__progname;
+#endif
+
+#ifndef HAVE_SETPROGNAME
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+setprogname(const char *argv0)
+{
+
+#ifndef HAVE___PROGNAME
+
+ const char *p;
+ if(argv0 == NULL)
+ return;
+ p = strrchr(argv0, '/');
+
+#ifdef BACKSLASH_PATH_DELIM
+ {
+ const char * pb;
+
+ pb = strrchr((p != NULL)? p : argv0, '\\');
+ if (pb != NULL)
+ p = pb;
+ }
+#endif
+
+ if(p == NULL)
+ p = argv0;
+ else
+ p++;
+
+#ifdef _WIN32
+ {
+ char * fn = strdup(p);
+ char * ext;
+
+ strlwr(fn);
+ ext = strrchr(fn, '.');
+ if (ext != NULL && strcmp(ext, ".exe") == 0)
+ *ext = '\0';
+
+ __progname = fn;
+ }
+#else
+
+ __progname = p;
+
+#endif
+
+#endif /* HAVE___PROGNAME */
+}
+
+#endif /* HAVE_SETPROGNAME */
diff --git a/third_party/heimdal/lib/roken/signal.c b/third_party/heimdal/lib/roken/signal.c
new file mode 100644
index 0000000..284f1e7
--- /dev/null
+++ b/third_party/heimdal/lib/roken/signal.c
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 1995 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <signal.h>
+#include "roken.h"
+
+/*
+ * We would like to always use this signal but there is a link error
+ * on NEXTSTEP
+ */
+#if !defined(NeXT) && !defined(__APPLE__)
+/*
+ * Bugs:
+ *
+ * Do we need any extra hacks for SIGCLD and/or SIGCHLD?
+ */
+
+ROKEN_LIB_FUNCTION SigAction ROKEN_LIB_CALL
+signal(int iSig, SigAction pAction)
+{
+ struct sigaction saNew, saOld;
+
+ saNew.sa_handler = pAction;
+ sigemptyset(&saNew.sa_mask);
+ saNew.sa_flags = 0;
+
+ if (iSig == SIGALRM)
+ {
+#ifdef SA_INTERRUPT
+ saNew.sa_flags |= SA_INTERRUPT;
+#endif
+ }
+ else
+ {
+#ifdef SA_RESTART
+ saNew.sa_flags |= SA_RESTART;
+#endif
+ }
+
+ if (sigaction(iSig, &saNew, &saOld) < 0)
+ return(SIG_ERR);
+
+ return(saOld.sa_handler);
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/simple_exec.c b/third_party/heimdal/lib/roken/simple_exec.c
new file mode 100644
index 0000000..552e121
--- /dev/null
+++ b/third_party/heimdal/lib/roken/simple_exec.c
@@ -0,0 +1,325 @@
+/*
+ * Copyright (c) 1998 - 2001, 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdarg.h>
+#include <stdlib.h>
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_WAIT_H
+#include <sys/wait.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <errno.h>
+
+#include "roken.h"
+
+#define EX_NOEXEC 126
+#define EX_NOTFOUND 127
+
+/* return values:
+ SE_E_UNSPECIFIED on `unspecified' system errors
+ SE_E_FORKFAILED on fork failures
+ SE_E_WAITPIDFAILED on waitpid errors
+ SE_E_EXECTIMEOUT exec timeout
+ 0- is return value from subprocess
+ SE_E_NOEXEC if the program couldn't be executed
+ SE_E_NOTFOUND if the program couldn't be found
+ 128- is 128 + signal that killed subprocess
+
+ possible values `func' can return:
+ ((time_t)-2) exit loop w/o killing child and return
+ `exec timeout'/-4 from simple_exec
+ ((time_t)-1) kill child with SIGTERM and wait for child to exit
+ 0 don't timeout again
+ n seconds to next timeout
+ */
+
+static int sig_alarm;
+
+static RETSIGTYPE
+sigtimeout(int sig)
+{
+ sig_alarm = 1;
+ SIGRETURN(0);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+wait_for_process_timed(pid_t pid, time_t (*func)(void *),
+ void *ptr, time_t timeout)
+{
+ RETSIGTYPE (*old_func)(int sig) = NULL;
+ unsigned int oldtime = 0;
+ int ret;
+
+ sig_alarm = 0;
+
+ if (func) {
+ old_func = signal(SIGALRM, sigtimeout);
+ oldtime = alarm(timeout);
+ }
+
+ while(1) {
+ int status;
+
+ while(waitpid(pid, &status, 0) < 0) {
+ if (errno != EINTR) {
+ ret = SE_E_WAITPIDFAILED;
+ goto out;
+ }
+ if (func == NULL)
+ continue;
+ if (sig_alarm == 0)
+ continue;
+ timeout = (*func)(ptr);
+ if (timeout == (time_t)-1) {
+ kill(pid, SIGTERM);
+ continue;
+ } else if (timeout == (time_t)-2) {
+ ret = SE_E_EXECTIMEOUT;
+ goto out;
+ }
+ alarm(timeout);
+ }
+ if(WIFSTOPPED(status))
+ continue;
+ if(WIFEXITED(status)) {
+ ret = WEXITSTATUS(status);
+ break;
+ }
+ if(WIFSIGNALED(status)) {
+ ret = WTERMSIG(status) + 128;
+ break;
+ }
+ }
+ out:
+ if (func) {
+ signal(SIGALRM, old_func);
+ alarm(oldtime);
+ }
+ return ret;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+wait_for_process(pid_t pid)
+{
+ return wait_for_process_timed(pid, NULL, NULL, 0);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+pipe_execv(FILE **stdin_fd, FILE **stdout_fd, FILE **stderr_fd,
+ const char *file, ...)
+{
+ int in_fd[2] = {-1, -1};
+ int out_fd[2] = {-1, -1};
+ int err_fd[2] = {-1, -1};
+ pid_t pid;
+ va_list ap;
+ char **argv;
+ int ret = 0;
+
+ if(stdin_fd != NULL)
+ ret = pipe(in_fd);
+ if(ret != -1 && stdout_fd != NULL)
+ ret = pipe(out_fd);
+ if(ret != -1 && stderr_fd != NULL)
+ ret = pipe(err_fd);
+
+ if (ret == -1) {
+ close(in_fd[0]);
+ close(in_fd[1]);
+ close(out_fd[0]);
+ close(out_fd[1]);
+ close(err_fd[0]);
+ close(err_fd[1]);
+ return SE_E_UNSPECIFIED;
+ }
+
+ pid = fork();
+ switch(pid) {
+ case 0:
+ va_start(ap, file);
+ argv = vstrcollect(&ap);
+ va_end(ap);
+ if(argv == NULL)
+ exit(-1);
+
+ /* close pipes we're not interested in */
+ if(stdin_fd != NULL)
+ close(in_fd[1]);
+ if(stdout_fd != NULL)
+ close(out_fd[0]);
+ if(stderr_fd != NULL)
+ close(err_fd[0]);
+
+ /* pipe everything caller doesn't care about to /dev/null */
+ if(stdin_fd == NULL)
+ in_fd[0] = open(_PATH_DEVNULL, O_RDONLY);
+ if(stdout_fd == NULL)
+ out_fd[1] = open(_PATH_DEVNULL, O_WRONLY);
+ if(stderr_fd == NULL)
+ err_fd[1] = open(_PATH_DEVNULL, O_WRONLY);
+
+ /* move to proper descriptors */
+ if(in_fd[0] != STDIN_FILENO) {
+ dup2(in_fd[0], STDIN_FILENO);
+ close(in_fd[0]);
+ }
+ if(out_fd[1] != STDOUT_FILENO) {
+ dup2(out_fd[1], STDOUT_FILENO);
+ close(out_fd[1]);
+ }
+ if(err_fd[1] != STDERR_FILENO) {
+ dup2(err_fd[1], STDERR_FILENO);
+ close(err_fd[1]);
+ }
+
+ closefrom(3);
+
+ execv(file, argv);
+ exit((errno == ENOENT) ? EX_NOTFOUND : EX_NOEXEC);
+ case -1:
+ if(stdin_fd != NULL) {
+ close(in_fd[0]);
+ close(in_fd[1]);
+ }
+ if(stdout_fd != NULL) {
+ close(out_fd[0]);
+ close(out_fd[1]);
+ }
+ if(stderr_fd != NULL) {
+ close(err_fd[0]);
+ close(err_fd[1]);
+ }
+ return SE_E_FORKFAILED;
+ default:
+ if(stdin_fd != NULL) {
+ close(in_fd[0]);
+ *stdin_fd = fdopen(in_fd[1], "w");
+ }
+ if(stdout_fd != NULL) {
+ close(out_fd[1]);
+ *stdout_fd = fdopen(out_fd[0], "r");
+ }
+ if(stderr_fd != NULL) {
+ close(err_fd[1]);
+ *stderr_fd = fdopen(err_fd[0], "r");
+ }
+ }
+ return pid;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execvp_timed(const char *file, char *const args[],
+ time_t (*func)(void *), void *ptr, time_t timeout)
+{
+ pid_t pid = fork();
+ switch(pid){
+ case -1:
+ return SE_E_FORKFAILED;
+ case 0:
+ execvp(file, args);
+ exit((errno == ENOENT) ? EX_NOTFOUND : EX_NOEXEC);
+ default:
+ return wait_for_process_timed(pid, func, ptr, timeout);
+ }
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execvp(const char *file, char *const args[])
+{
+ return simple_execvp_timed(file, args, NULL, NULL, 0);
+}
+
+/* gee, I'd like a execvpe */
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execve_timed(const char *file, char *const args[], char *const envp[],
+ time_t (*func)(void *), void *ptr, time_t timeout)
+{
+ pid_t pid = fork();
+ switch(pid){
+ case -1:
+ return SE_E_FORKFAILED;
+ case 0:
+ execve(file, args, envp);
+ exit((errno == ENOENT) ? EX_NOTFOUND : EX_NOEXEC);
+ default:
+ return wait_for_process_timed(pid, func, ptr, timeout);
+ }
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execve(const char *file, char *const args[], char *const envp[])
+{
+ return simple_execve_timed(file, args, envp, NULL, NULL, 0);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execlp(const char *file, ...)
+{
+ va_list ap;
+ char **argv;
+ int ret;
+
+ va_start(ap, file);
+ argv = vstrcollect(&ap);
+ va_end(ap);
+ if(argv == NULL)
+ return SE_E_UNSPECIFIED;
+ ret = simple_execvp(file, argv);
+ free(argv);
+ return ret;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execle(const char *file, ... /* ,char *const envp[] */)
+{
+ va_list ap;
+ char **argv;
+ char *const* envp;
+ int ret;
+
+ va_start(ap, file);
+ argv = vstrcollect(&ap);
+ envp = va_arg(ap, char **);
+ va_end(ap);
+ if(argv == NULL)
+ return SE_E_UNSPECIFIED;
+ ret = simple_execve(file, argv, envp);
+ free(argv);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/simple_exec_w32.c b/third_party/heimdal/lib/roken/simple_exec_w32.c
new file mode 100644
index 0000000..264cdb2
--- /dev/null
+++ b/third_party/heimdal/lib/roken/simple_exec_w32.c
@@ -0,0 +1,431 @@
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include <config.h>
+
+#include <roken.h>
+#include <strsafe.h>
+
+#ifndef _WIN32
+#error This implementation is Windows specific.
+#endif
+
+/**
+ * wait_for_process_timed waits for a process to terminate or until a
+ * specified timeout occurs.
+ *
+ * @param[in] pid Process id for the monitored process
+
+ * @param[in] func Timeout callback function. When the wait times out,
+ * the callback function is called. The possible return values
+ * from the callback function are:
+ *
+ * - ((time_t) -2) Exit loop without killing child and return SE_E_EXECTIMEOUT.
+ * - ((time_t) -1) Kill child with SIGTERM and wait for child to exit.
+ * - 0 Don't timeout again
+ * - n Seconds to next timeout
+ *
+ * @param[in] ptr Optional parameter for func()
+ *
+ * @param[in] timeout Seconds to first timeout.
+ *
+ * @retval SE_E_UNSPECIFIED Unspecified system error
+ * @retval SE_E_FORKFAILED Fork failure (not applicable for _WIN32 targets)
+ * @retval SE_E_WAITPIDFAILED waitpid errors
+ * @retval SE_E_EXECTIMEOUT exec timeout
+ * @retval 0 <= Return value from subprocess
+ * @retval SE_E_NOTFOUND The program coudln't be found
+ * @retval 128- The signal that killed the subprocess +128.
+ */
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+wait_for_process_timed(pid_t pid, time_t (*func)(void *),
+ void *ptr, time_t timeout)
+{
+ HANDLE hProcess;
+ DWORD wrv = 0;
+ DWORD dtimeout;
+ int rv = 0;
+
+ hProcess = OpenProcess(SYNCHRONIZE, FALSE, pid);
+
+ if (hProcess == NULL) {
+ return SE_E_WAITPIDFAILED;
+ }
+
+ dtimeout = (DWORD) ((timeout == 0)? INFINITE: timeout * 1000);
+
+ do {
+ wrv = WaitForSingleObject(hProcess, dtimeout);
+
+ if (wrv == WAIT_OBJECT_0) {
+
+ DWORD prv = 0;
+
+ GetExitCodeProcess(hProcess, &prv);
+ rv = (int) prv;
+ break;
+
+ } else if (wrv == WAIT_TIMEOUT) {
+
+ if (func == NULL)
+ continue;
+
+ timeout = (*func)(ptr);
+
+ if (timeout == (time_t)-1) {
+
+ if (TerminateProcess(hProcess, 128 + 9)) {
+ dtimeout = INFINITE;
+ continue;
+ }
+ rv = SE_E_UNSPECIFIED;
+ break;
+
+ } else if (timeout == (time_t) -2) {
+
+ rv = SE_E_EXECTIMEOUT;
+ break;
+
+ } else {
+
+ dtimeout = (DWORD) ((timeout == 0)? INFINITE: timeout * 1000);
+ continue;
+
+ }
+
+ } else {
+
+ rv = SE_E_UNSPECIFIED;
+ break;
+
+ }
+
+ } while(TRUE);
+
+ CloseHandle(hProcess);
+
+ return rv;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+wait_for_process(pid_t pid)
+{
+ return wait_for_process_timed(pid, NULL, NULL, 0);
+}
+
+static char *
+collect_commandline(const char * fn, va_list * ap)
+{
+ size_t len = 0;
+ size_t alloc_len = 0;
+ const char * s;
+ char * cmd = NULL;
+
+ for (s = fn; s; s = (char *) va_arg(*ap, char *)) {
+ size_t cmp_len;
+ int need_quote = FALSE;
+
+ if (FAILED(StringCchLength(s, MAX_PATH, &cmp_len))) {
+ if (cmd)
+ free(cmd);
+ return NULL;
+ }
+
+ if (cmp_len == 0)
+ continue;
+
+ if (strchr(s, ' ') && /* need to quote any component that
+ has embedded spaces, but not if
+ they are already quoted. */
+ s[0] != '"' &&
+ s[cmp_len - 1] != '"') {
+ need_quote = TRUE;
+ cmp_len += 2 * sizeof(char);
+ }
+
+ if (s != fn)
+ cmp_len += 1 * sizeof(char);
+
+ if (alloc_len < len + cmp_len + 1) {
+ char * nc;
+
+ alloc_len += ((len + cmp_len - alloc_len) / MAX_PATH + 1) * MAX_PATH;
+ nc = (char *) realloc(cmd, alloc_len * sizeof(char));
+ if (nc == NULL) {
+ if (cmd)
+ free(cmd);
+ return NULL;
+ }
+ cmd = nc;
+ }
+
+ if (cmd == NULL)
+ return NULL;
+
+ if (s != fn)
+ cmd[len++] = ' ';
+
+ if (need_quote) {
+ StringCchPrintf(cmd + len, alloc_len - len, "\"%s\"", s);
+ } else {
+ StringCchCopy(cmd + len, alloc_len - len, s);
+ }
+
+ len += cmp_len;
+ }
+
+ return cmd;
+}
+
+ROKEN_LIB_FUNCTION pid_t ROKEN_LIB_CALL
+pipe_execv(FILE **stdin_fd, FILE **stdout_fd, FILE **stderr_fd,
+ const char *file, ...)
+{
+ HANDLE hOut_r = NULL;
+ HANDLE hOut_w = NULL;
+ HANDLE hIn_r = NULL;
+ HANDLE hIn_w = NULL;
+ HANDLE hErr_r = NULL;
+ HANDLE hErr_w = NULL;
+
+ SECURITY_ATTRIBUTES sa;
+ STARTUPINFO si;
+ PROCESS_INFORMATION pi;
+
+ char * commandline = NULL;
+
+ pid_t rv = (pid_t) -1;
+
+ {
+ va_list ap;
+
+ va_start(ap, file);
+ commandline = collect_commandline(file, &ap);
+
+ if (commandline == NULL)
+ return rv;
+ }
+
+ ZeroMemory(&si, sizeof(si));
+ ZeroMemory(&pi, sizeof(pi));
+ ZeroMemory(&sa, sizeof(sa));
+
+ pi.hProcess = NULL;
+ pi.hThread = NULL;
+
+ sa.nLength = sizeof(sa);
+ sa.bInheritHandle = TRUE;
+ sa.lpSecurityDescriptor = NULL;
+
+ if ((stdout_fd && !CreatePipe(&hOut_r, &hOut_w, &sa, 0 /* Use default */)) ||
+
+ (stdin_fd && !CreatePipe(&hIn_r, &hIn_w, &sa, 0)) ||
+
+ (stderr_fd && !CreatePipe(&hErr_r, &hErr_w, &sa, 0)) ||
+
+ (!stdout_fd && (hOut_w = CreateFile("CON", GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
+ &sa, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE) ||
+
+ (!stdin_fd && (hIn_r = CreateFile("CON",GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE,
+ &sa, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE) ||
+
+ (!stderr_fd && (hErr_w = CreateFile("CON", GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
+ &sa, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE))
+
+ goto _exit;
+
+ /* We don't want the child processes inheriting these */
+ if (hOut_r)
+ SetHandleInformation(hOut_r, HANDLE_FLAG_INHERIT, FALSE);
+
+ if (hIn_w)
+ SetHandleInformation(hIn_w, HANDLE_FLAG_INHERIT, FALSE);
+
+ if (hErr_r)
+ SetHandleInformation(hErr_r, HANDLE_FLAG_INHERIT, FALSE);
+
+ si.cb = sizeof(si);
+ si.lpReserved = NULL;
+ si.lpDesktop = NULL;
+ si.lpTitle = NULL;
+ si.dwFlags = STARTF_USESTDHANDLES;
+ si.hStdInput = hIn_r;
+ si.hStdOutput = hOut_w;
+ si.hStdError = hErr_w;
+
+ if (!CreateProcess(file, commandline, NULL, NULL,
+ TRUE, /* bInheritHandles */
+ CREATE_NO_WINDOW, /* dwCreationFlags */
+ NULL, /* lpEnvironment */
+ NULL, /* lpCurrentDirectory */
+ &si,
+ &pi)) {
+
+ rv = (pid_t) (GetLastError() == ERROR_FILE_NOT_FOUND)? 127 : -1;
+ goto _exit;
+ }
+
+ if (stdin_fd) {
+ *stdin_fd = _fdopen(_open_osfhandle((intptr_t) hIn_w, 0), "wb");
+ if (*stdin_fd)
+ hIn_w = NULL;
+ }
+
+ if (stdout_fd) {
+ *stdout_fd = _fdopen(_open_osfhandle((intptr_t) hOut_r, _O_RDONLY), "rb");
+ if (*stdout_fd)
+ hOut_r = NULL;
+ }
+
+ if (stderr_fd) {
+ *stderr_fd = _fdopen(_open_osfhandle((intptr_t) hErr_r, _O_RDONLY), "rb");
+ if (*stderr_fd)
+ hErr_r = NULL;
+ }
+
+ rv = (pid_t) pi.dwProcessId;
+
+ _exit:
+
+ if (pi.hProcess) CloseHandle(pi.hProcess);
+
+ if (pi.hThread) CloseHandle(pi.hThread);
+
+ if (hIn_r) CloseHandle(hIn_r);
+
+ if (hIn_w) CloseHandle(hIn_w);
+
+ if (hOut_r) CloseHandle(hOut_r);
+
+ if (hOut_w) CloseHandle(hOut_w);
+
+ if (hErr_r) CloseHandle(hErr_r);
+
+ if (hErr_w) CloseHandle(hErr_w);
+
+ return rv;
+}
+
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execvp_timed(const char *file, char *const args[],
+ time_t (*func)(void *), void *ptr, time_t timeout)
+{
+ intptr_t hp;
+ int rv;
+
+ hp = spawnvp(_P_NOWAIT, file, args);
+
+ if (hp == -1)
+ return (errno == ENOENT)? 127: 126;
+ else if (hp == 0)
+ return 0;
+
+ rv = wait_for_process_timed(GetProcessId((HANDLE) hp), func, ptr, timeout);
+
+ CloseHandle((HANDLE) hp);
+
+ return rv;
+}
+
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execvp(const char *file, char *const args[])
+{
+ return simple_execvp_timed(file, args, NULL, NULL, 0);
+}
+
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execve_timed(const char *file, char *const args[], char *const envp[],
+ time_t (*func)(void *), void *ptr, time_t timeout)
+{
+ intptr_t hp;
+ int rv;
+
+ hp = spawnve(_P_NOWAIT, file, args, envp);
+
+ if (hp == -1)
+ return (errno == ENOENT)? 127: 126;
+ else if (hp == 0)
+ return 0;
+
+ rv = wait_for_process_timed(GetProcessId((HANDLE) hp), func, ptr, timeout);
+
+ CloseHandle((HANDLE) hp);
+
+ return rv;
+}
+
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execve(const char *file, char *const args[], char *const envp[])
+{
+ return simple_execve_timed(file, args, envp, NULL, NULL, 0);
+}
+
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execlp(const char *file, ...)
+{
+ va_list ap;
+ char **argv;
+ int ret;
+
+ va_start(ap, file);
+ argv = vstrcollect(&ap);
+ va_end(ap);
+ if(argv == NULL)
+ return SE_E_UNSPECIFIED;
+ ret = simple_execvp(file, argv);
+ free(argv);
+ return ret;
+}
+
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execle(const char *file, ... /* ,char *const envp[] */)
+{
+ va_list ap;
+ char **argv;
+ char *const* envp;
+ int ret;
+
+ va_start(ap, file);
+ argv = vstrcollect(&ap);
+ envp = va_arg(ap, char **);
+ va_end(ap);
+ if(argv == NULL)
+ return SE_E_UNSPECIFIED;
+ ret = simple_execve(file, argv, envp);
+ free(argv);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/sleep.c b/third_party/heimdal/lib/roken/sleep.c
new file mode 100644
index 0000000..53f416e
--- /dev/null
+++ b/third_party/heimdal/lib/roken/sleep.c
@@ -0,0 +1,55 @@
+/***********************************************************************
+ * Copyright (c) 2009, 2014, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include <config.h>
+
+#include <roken.h>
+
+#ifndef _WIN32
+#error Only implemented on Windows
+#endif
+
+ROKEN_LIB_FUNCTION unsigned int ROKEN_LIB_CALL
+sleep(unsigned int seconds)
+{
+ if (SleepEx(1000 * (DWORD) seconds, FALSE) != 0)
+ return 1; /* XXX Should get time before and after */
+ return 0;
+}
+
+/* We can only sleep in millisecond increments */
+ROKEN_LIB_FUNCTION unsigned int ROKEN_LIB_CALL
+usleep(unsigned int useconds)
+{
+ if (SleepEx((DWORD)(useconds / 1000), FALSE) != 0)
+ return 1000; /* XXX Should get time before and after */
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/snprintf-test.c b/third_party/heimdal/lib/roken/snprintf-test.c
new file mode 100644
index 0000000..e51402d
--- /dev/null
+++ b/third_party/heimdal/lib/roken/snprintf-test.c
@@ -0,0 +1,268 @@
+/*
+ * Copyright (c) 2000 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include <config.h>
+#include "roken.h"
+#include <limits.h>
+
+extern int rk_snprintf(char *, size_t, const char *, ...);
+extern int rk_vsnprintf(char *, size_t, const char *, va_list);
+
+static int
+try (const char *format, ...)
+{
+ int ret;
+ va_list ap;
+ char buf1[256], buf2[256];
+
+ va_start (ap, format);
+ ret = rk_vsnprintf (buf1, sizeof(buf1), format, ap);
+ if (ret >= sizeof(buf1))
+ errx (1, "increase buf and try again");
+ va_end (ap);
+ va_start (ap, format);
+ vsprintf (buf2, format, ap);
+ ret = strcmp (buf1, buf2);
+ if (ret)
+ printf ("failed: format = \"%s\", \"%s\" != \"%s\"\n",
+ format, buf1, buf2);
+ va_end (ap);
+ return ret;
+}
+
+static int
+cmp_with_sprintf_int (void)
+{
+ int tot = 0;
+ int int_values[] = {INT_MIN, -17, -1, 0, 1, 17, 4711, 65535, INT_MAX};
+ int i;
+
+ for (i = 0; i < sizeof(int_values) / sizeof(int_values[0]); ++i) {
+ tot += try ("%d", int_values[i]);
+ tot += try ("%x", int_values[i]);
+ tot += try ("%X", int_values[i]);
+ tot += try ("%o", int_values[i]);
+ tot += try ("%#x", int_values[i]);
+ tot += try ("%#X", int_values[i]);
+ tot += try ("%#o", int_values[i]);
+ tot += try ("%10d", int_values[i]);
+ tot += try ("%10x", int_values[i]);
+ tot += try ("%10X", int_values[i]);
+ tot += try ("%10o", int_values[i]);
+ tot += try ("%#10x", int_values[i]);
+ tot += try ("%#10X", int_values[i]);
+ tot += try ("%#10o", int_values[i]);
+ tot += try ("%-10d", int_values[i]);
+ tot += try ("%-10x", int_values[i]);
+ tot += try ("%-10X", int_values[i]);
+ tot += try ("%-10o", int_values[i]);
+ tot += try ("%-#10x", int_values[i]);
+ tot += try ("%-#10X", int_values[i]);
+ tot += try ("%-#10o", int_values[i]);
+ }
+ return tot;
+}
+
+static int
+cmp_with_sprintf_long (void)
+{
+ int tot = 0;
+ long long_values[] = {LONG_MIN, -17, -1, 0, 1, 17, 4711, 65535, LONG_MAX};
+ int i;
+
+ for (i = 0; i < sizeof(long_values) / sizeof(long_values[0]); ++i) {
+ tot += try ("%ld", long_values[i]);
+ tot += try ("%lx", long_values[i]);
+ tot += try ("%lX", long_values[i]);
+ tot += try ("%lo", long_values[i]);
+ tot += try ("%#lx", long_values[i]);
+ tot += try ("%#lX", long_values[i]);
+ tot += try ("%#lo", long_values[i]);
+ tot += try ("%10ld", long_values[i]);
+ tot += try ("%10lx", long_values[i]);
+ tot += try ("%10lX", long_values[i]);
+ tot += try ("%10lo", long_values[i]);
+ tot += try ("%#10lx", long_values[i]);
+ tot += try ("%#10lX", long_values[i]);
+ tot += try ("%#10lo", long_values[i]);
+ tot += try ("%-10ld", long_values[i]);
+ tot += try ("%-10lx", long_values[i]);
+ tot += try ("%-10lX", long_values[i]);
+ tot += try ("%-10lo", long_values[i]);
+ tot += try ("%-#10lx", long_values[i]);
+ tot += try ("%-#10lX", long_values[i]);
+ tot += try ("%-#10lo", long_values[i]);
+ }
+ return tot;
+}
+
+#ifdef HAVE_LONG_LONG
+
+/* XXX doesn't work as expected on lp64 platforms with sizeof(long
+ * long) == sizeof(long) */
+
+static int
+cmp_with_sprintf_long_long (void)
+{
+ int tot = 0;
+ long long long_long_values[] = {
+ ((long long)LONG_MIN) - (sizeof(long long) > sizeof(long)),
+ LONG_MIN, -17, -1, 0, 1, 17, 4711, 65535, LONG_MAX,
+ ((long long)LONG_MAX) + (sizeof(long long) > sizeof(long))
+ };
+ int i;
+
+ for (i = 0; i < sizeof(long_long_values) / sizeof(long_long_values[0]); ++i) {
+ tot += try ("%lld", long_long_values[i]);
+ tot += try ("%llx", long_long_values[i]);
+ tot += try ("%llX", long_long_values[i]);
+ tot += try ("%llo", long_long_values[i]);
+ tot += try ("%#llx", long_long_values[i]);
+ tot += try ("%#llX", long_long_values[i]);
+ tot += try ("%#llo", long_long_values[i]);
+ tot += try ("%10lld", long_long_values[i]);
+ tot += try ("%10llx", long_long_values[i]);
+ tot += try ("%10llX", long_long_values[i]);
+ tot += try ("%10llo", long_long_values[i]);
+ tot += try ("%#10llx", long_long_values[i]);
+ tot += try ("%#10llX", long_long_values[i]);
+ tot += try ("%#10llo", long_long_values[i]);
+ tot += try ("%-10lld", long_long_values[i]);
+ tot += try ("%-10llx", long_long_values[i]);
+ tot += try ("%-10llX", long_long_values[i]);
+ tot += try ("%-10llo", long_long_values[i]);
+ tot += try ("%-#10llx", long_long_values[i]);
+ tot += try ("%-#10llX", long_long_values[i]);
+ tot += try ("%-#10llo", long_long_values[i]);
+ }
+ return tot;
+}
+
+#endif
+
+#if 0
+static int
+cmp_with_sprintf_float (void)
+{
+ int tot = 0;
+ double double_values[] = {-99999, -999, -17.4, -4.3, -3.0, -1.5, -1,
+ 0, 0.1, 0.2342374852, 0.2340007,
+ 3.1415926, 14.7845, 34.24758, 9999, 9999999};
+ int i;
+
+ for (i = 0; i < sizeof(double_values) / sizeof(double_values[0]); ++i) {
+ tot += try ("%f", double_values[i]);
+ tot += try ("%10f", double_values[i]);
+ tot += try ("%.2f", double_values[i]);
+ tot += try ("%7.0f", double_values[i]);
+ tot += try ("%5.2f", double_values[i]);
+ tot += try ("%0f", double_values[i]);
+ tot += try ("%#f", double_values[i]);
+ tot += try ("%e", double_values[i]);
+ tot += try ("%10e", double_values[i]);
+ tot += try ("%.2e", double_values[i]);
+ tot += try ("%7.0e", double_values[i]);
+ tot += try ("%5.2e", double_values[i]);
+ tot += try ("%0e", double_values[i]);
+ tot += try ("%#e", double_values[i]);
+ tot += try ("%E", double_values[i]);
+ tot += try ("%10E", double_values[i]);
+ tot += try ("%.2E", double_values[i]);
+ tot += try ("%7.0E", double_values[i]);
+ tot += try ("%5.2E", double_values[i]);
+ tot += try ("%0E", double_values[i]);
+ tot += try ("%#E", double_values[i]);
+ tot += try ("%g", double_values[i]);
+ tot += try ("%10g", double_values[i]);
+ tot += try ("%.2g", double_values[i]);
+ tot += try ("%7.0g", double_values[i]);
+ tot += try ("%5.2g", double_values[i]);
+ tot += try ("%0g", double_values[i]);
+ tot += try ("%#g", double_values[i]);
+ tot += try ("%G", double_values[i]);
+ tot += try ("%10G", double_values[i]);
+ tot += try ("%.2G", double_values[i]);
+ tot += try ("%7.0G", double_values[i]);
+ tot += try ("%5.2G", double_values[i]);
+ tot += try ("%0G", double_values[i]);
+ tot += try ("%#G", double_values[i]);
+ }
+ return tot;
+}
+#endif
+
+static int
+test_null (void)
+{
+ return rk_snprintf (NULL, 0, "foo") != 3;
+}
+
+static int
+test_sizet (void)
+{
+ int tot = 0;
+ size_t sizet_values[] = { 0, 1, 2, 200, 4294967295u }; /* SIZE_MAX */
+ char *result[] = { "0", "1", "2", "200", "4294967295" };
+ int i;
+
+ for (i = 0; i < sizeof(sizet_values) / sizeof(sizet_values[0]); ++i) {
+#if 0
+ tot += try("%zu", sizet_values[i]);
+ tot += try("%zx", sizet_values[i]);
+ tot += try("%zX", sizet_values[i]);
+#else
+ char buf[256];
+ rk_snprintf(buf, sizeof(buf), "%zu", sizet_values[i]);
+ if (strcmp(buf, result[i]) != 0) {
+ printf("%s != %s", buf, result[i]);
+ tot++;
+ }
+#endif
+ }
+ return tot;
+}
+
+
+int
+main (int argc, char **argv)
+{
+ int ret = 0;
+
+ ret += cmp_with_sprintf_int ();
+ ret += cmp_with_sprintf_long ();
+#ifdef HAVE_LONG_LONG
+ ret += cmp_with_sprintf_long_long ();
+#endif
+ ret += test_null ();
+ ret += test_sizet ();
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/snprintf.c b/third_party/heimdal/lib/roken/snprintf.c
new file mode 100644
index 0000000..3da4896
--- /dev/null
+++ b/third_party/heimdal/lib/roken/snprintf.c
@@ -0,0 +1,700 @@
+/*
+ * Copyright (c) 1995-2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include "roken.h"
+#include <assert.h>
+
+enum format_flags {
+ minus_flag = 1,
+ plus_flag = 2,
+ space_flag = 4,
+ alternate_flag = 8,
+ zero_flag = 16
+};
+
+/*
+ * Common state
+ */
+
+struct snprintf_state {
+ unsigned char *str;
+ unsigned char *s;
+ unsigned char *theend;
+ size_t sz;
+ size_t max_sz;
+ void (*append_char)(struct snprintf_state *, unsigned char);
+ /* XXX - methods */
+};
+
+#if !defined(HAVE_VSNPRINTF) || defined(TEST_SNPRINTF)
+static int
+sn_reserve (struct snprintf_state *state, size_t n)
+{
+ return state->s + n > state->theend;
+}
+
+static void
+sn_append_char (struct snprintf_state *state, unsigned char c)
+{
+ if (!sn_reserve (state, 1))
+ *state->s++ = c;
+}
+#endif
+
+static int
+as_reserve (struct snprintf_state *state, size_t n)
+{
+ if (state->s + n > state->theend) {
+ int off = state->s - state->str;
+ unsigned char *tmp;
+
+ if (state->max_sz && state->sz >= state->max_sz)
+ return 1;
+
+ state->sz = max(state->sz * 2, state->sz + n);
+ if (state->max_sz)
+ state->sz = min(state->sz, state->max_sz);
+ tmp = realloc (state->str, state->sz);
+ if (tmp == NULL)
+ return 1;
+ state->str = tmp;
+ state->s = state->str + off;
+ state->theend = state->str + state->sz - 1;
+ }
+ return 0;
+}
+
+static void
+as_append_char (struct snprintf_state *state, unsigned char c)
+{
+ if(!as_reserve (state, 1))
+ *state->s++ = c;
+}
+
+/* longest integer types */
+
+#ifdef HAVE_LONG_LONG
+typedef unsigned long long u_longest;
+typedef long long longest;
+#else
+typedef unsigned long u_longest;
+typedef long longest;
+#endif
+
+#ifndef HAVE_UINTPTR_T
+typedef u_longest uintptr_t;
+#endif
+
+
+
+static size_t
+pad(struct snprintf_state *state, int width, char c)
+{
+ size_t len = 0;
+ while(width-- > 0){
+ (*state->append_char)(state, c);
+ ++len;
+ }
+ return len;
+}
+
+/* return true if we should use alternatve hex form */
+static int
+use_alternative (int flags, u_longest num, unsigned base)
+{
+ return (flags & alternate_flag) && base == 16 && num != 0;
+}
+
+static int
+append_number(struct snprintf_state *state,
+ u_longest num, unsigned base, const char *rep,
+ int width, int prec, int flags, int minusp)
+{
+ int len = 0;
+ u_longest n = num;
+ char nstr[64]; /* enough for <192 bit octal integers */
+ int nstart, nlen;
+ char signchar;
+
+ /* given precision, ignore zero flag */
+ if(prec != -1)
+ flags &= ~zero_flag;
+ else
+ prec = 1;
+
+ /* format number as string */
+ nstart = sizeof(nstr);
+ nlen = 0;
+ nstr[--nstart] = '\0';
+ do {
+ assert(nstart > 0);
+ nstr[--nstart] = rep[n % base];
+ ++nlen;
+ n /= base;
+ } while(n);
+
+ /* zero value with zero precision should produce no digits */
+ if(prec == 0 && num == 0) {
+ nlen--;
+ nstart++;
+ }
+
+ /* figure out what char to use for sign */
+ if(minusp)
+ signchar = '-';
+ else if((flags & plus_flag))
+ signchar = '+';
+ else if((flags & space_flag))
+ signchar = ' ';
+ else
+ signchar = '\0';
+
+ if((flags & alternate_flag) && base == 8) {
+ /* if necessary, increase the precision to
+ make first digit a zero */
+
+ /* XXX C99 claims (regarding # and %o) that "if the value and
+ precision are both 0, a single 0 is printed", but there is
+ no such wording for %x. This would mean that %#.o would
+ output "0", but %#.x "". This does not make sense, and is
+ also not what other printf implementations are doing. */
+
+ if(prec <= nlen && nstr[nstart] != '0' && nstr[nstart] != '\0')
+ prec = nlen + 1;
+ }
+
+ /* possible formats:
+ pad | sign | alt | zero | digits
+ sign | alt | zero | digits | pad minus_flag
+ sign | alt | zero | digits zero_flag */
+
+ /* if not right justifying or padding with zeros, we need to
+ compute the length of the rest of the string, and then pad with
+ spaces */
+ if(!(flags & (minus_flag | zero_flag))) {
+ if(prec > nlen)
+ width -= prec;
+ else
+ width -= nlen;
+
+ if(use_alternative(flags, num, base))
+ width -= 2;
+
+ if(signchar != '\0')
+ width--;
+
+ /* pad to width */
+ len += pad(state, width, ' ');
+ }
+ if(signchar != '\0') {
+ (*state->append_char)(state, signchar);
+ ++len;
+ }
+ if(use_alternative(flags, num, base)) {
+ (*state->append_char)(state, '0');
+ (*state->append_char)(state, rep[10] + 23); /* XXX */
+ len += 2;
+ }
+ if(flags & zero_flag) {
+ /* pad to width with zeros */
+ if(prec - nlen > width - len - nlen)
+ len += pad(state, prec - nlen, '0');
+ else
+ len += pad(state, width - len - nlen, '0');
+ } else
+ /* pad to prec with zeros */
+ len += pad(state, prec - nlen, '0');
+
+ while(nstr[nstart] != '\0') {
+ (*state->append_char)(state, nstr[nstart++]);
+ ++len;
+ }
+
+ if(flags & minus_flag)
+ len += pad(state, width - len, ' ');
+
+ return len;
+}
+
+/*
+ * return length
+ */
+
+static size_t
+append_string (struct snprintf_state *state,
+ const unsigned char *arg,
+ int width,
+ int prec,
+ int flags)
+{
+ size_t len = 0;
+
+ if(arg == NULL)
+ arg = (const unsigned char*)"(null)";
+
+ if(prec != -1)
+ width -= prec;
+ else
+ width -= strlen((const char *)arg);
+ if(!(flags & minus_flag))
+ len += pad(state, width, ' ');
+
+ if (prec != -1) {
+ while (prec-- && *arg) {
+ (*state->append_char) (state, *arg++);
+ ++len;
+ }
+ } else {
+ while (*arg) {
+ (*state->append_char) (state, *arg++);
+ ++len;
+ }
+ }
+ if(flags & minus_flag)
+ len += pad(state, width, ' ');
+ return len;
+}
+
+static int
+append_char(struct snprintf_state *state,
+ unsigned char arg,
+ int width,
+ int flags)
+{
+ int len = 0;
+
+ while(!(flags & minus_flag) && --width > 0) {
+ (*state->append_char) (state, ' ') ;
+ ++len;
+ }
+ (*state->append_char) (state, arg);
+ ++len;
+ while((flags & minus_flag) && --width > 0) {
+ (*state->append_char) (state, ' ');
+ ++len;
+ }
+ return 0;
+}
+
+/*
+ * This can't be made into a function...
+ */
+
+#ifdef HAVE_LONG_LONG
+
+#define PARSE_INT_FORMAT(res, arg, unsig) \
+if (long_long_flag) \
+ res = (unsig long long)va_arg(arg, unsig long long); \
+else if (long_flag) \
+ res = (unsig long)va_arg(arg, unsig long); \
+else if (size_t_flag) \
+ res = (unsig long)va_arg(arg, size_t); \
+else if (short_flag) \
+ res = (unsig short)va_arg(arg, unsig int); \
+else \
+ res = (unsig int)va_arg(arg, unsig int)
+
+#else
+
+#define PARSE_INT_FORMAT(res, arg, unsig) \
+if (long_flag) \
+ res = (unsig long)va_arg(arg, unsig long); \
+else if (size_t_flag) \
+ res = (unsig long)va_arg(arg, size_t); \
+else if (short_flag) \
+ res = (unsig short)va_arg(arg, unsig int); \
+else \
+ res = (unsig int)va_arg(arg, unsig int)
+
+#endif
+
+/*
+ * zyxprintf - return length, as snprintf
+ */
+
+static size_t
+xyzprintf (struct snprintf_state *state, const char *char_format, va_list ap)
+{
+ const unsigned char *format = (const unsigned char *)char_format;
+ unsigned char c;
+ size_t len = 0;
+
+ while((c = *format++)) {
+ if (c == '%') {
+ int flags = 0;
+ int width = 0;
+ int prec = -1;
+ int size_t_flag = 0;
+ int long_long_flag = 0;
+ int long_flag = 0;
+ int short_flag = 0;
+
+ /* flags */
+ while((c = *format++)){
+ if(c == '-')
+ flags |= minus_flag;
+ else if(c == '+')
+ flags |= plus_flag;
+ else if(c == ' ')
+ flags |= space_flag;
+ else if(c == '#')
+ flags |= alternate_flag;
+ else if(c == '0')
+ flags |= zero_flag;
+ else if(c == '\'')
+ ; /* just ignore */
+ else
+ break;
+ }
+
+ if((flags & space_flag) && (flags & plus_flag))
+ flags ^= space_flag;
+
+ if((flags & minus_flag) && (flags & zero_flag))
+ flags ^= zero_flag;
+
+ /* width */
+ if (isdigit(c))
+ do {
+ width = width * 10 + c - '0';
+ c = *format++;
+ } while(isdigit(c));
+ else if(c == '*') {
+ width = va_arg(ap, int);
+ c = *format++;
+ }
+
+ /* precision */
+ if (c == '.') {
+ prec = 0;
+ c = *format++;
+ if (isdigit(c))
+ do {
+ prec = prec * 10 + c - '0';
+ c = *format++;
+ } while(isdigit(c));
+ else if (c == '*') {
+ prec = va_arg(ap, int);
+ c = *format++;
+ }
+ }
+
+ /* size */
+
+ if (c == 'h') {
+ short_flag = 1;
+ c = *format++;
+ } else if (c == 'z') {
+ size_t_flag = 1;
+ c = *format++;
+ } else if (c == 'l') {
+ long_flag = 1;
+ c = *format++;
+ if (c == 'l') {
+ long_long_flag = 1;
+ c = *format++;
+ }
+ }
+
+ if(c != 'd' && c != 'i')
+ flags &= ~(plus_flag | space_flag);
+
+ switch (c) {
+ case 'c' :
+ append_char(state, va_arg(ap, int), width, flags);
+ ++len;
+ break;
+ case 's' :
+ len += append_string(state,
+ va_arg(ap, unsigned char*),
+ width,
+ prec,
+ flags);
+ break;
+ case 'd' :
+ case 'i' : {
+ longest arg;
+ u_longest num;
+ int minusp = 0;
+
+ PARSE_INT_FORMAT(arg, ap, signed);
+
+ if (arg < 0) {
+ minusp = 1;
+ num = -arg;
+ } else
+ num = arg;
+
+ len += append_number (state, num, 10, "0123456789",
+ width, prec, flags, minusp);
+ break;
+ }
+ case 'u' : {
+ u_longest arg;
+
+ PARSE_INT_FORMAT(arg, ap, unsigned);
+
+ len += append_number (state, arg, 10, "0123456789",
+ width, prec, flags, 0);
+ break;
+ }
+ case 'o' : {
+ u_longest arg;
+
+ PARSE_INT_FORMAT(arg, ap, unsigned);
+
+ len += append_number (state, arg, 010, "01234567",
+ width, prec, flags, 0);
+ break;
+ }
+ case 'x' : {
+ u_longest arg;
+
+ PARSE_INT_FORMAT(arg, ap, unsigned);
+
+ len += append_number (state, arg, 0x10, "0123456789abcdef",
+ width, prec, flags, 0);
+ break;
+ }
+ case 'X' :{
+ u_longest arg;
+
+ PARSE_INT_FORMAT(arg, ap, unsigned);
+
+ len += append_number (state, arg, 0x10, "0123456789ABCDEF",
+ width, prec, flags, 0);
+ break;
+ }
+ case 'p' : {
+ uintptr_t arg = (uintptr_t)va_arg(ap, void*);
+
+ len += append_number (state, arg, 0x10, "0123456789ABCDEF",
+ width, prec, flags, 0);
+ break;
+ }
+ case 'n' : {
+ int *arg = va_arg(ap, int*);
+ *arg = state->s - state->str;
+ break;
+ }
+ case '\0' :
+ --format;
+ fallthrough;
+ case '%' :
+ (*state->append_char)(state, c);
+ ++len;
+ break;
+ default :
+ (*state->append_char)(state, '%');
+ (*state->append_char)(state, c);
+ len += 2;
+ break;
+ }
+ } else {
+ (*state->append_char) (state, c);
+ ++len;
+ }
+ }
+ return len;
+}
+
+#if !defined(HAVE_SNPRINTF) || defined(TEST_SNPRINTF)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_snprintf (char *str, size_t sz, const char *format, ...)
+{
+ va_list args;
+ int ret;
+
+ va_start(args, format);
+ ret = vsnprintf (str, sz, format, args);
+ va_end(args);
+
+#ifdef PARANOIA
+ {
+ int ret2;
+ char *tmp;
+
+ tmp = malloc (sz);
+ if (tmp == NULL)
+ abort ();
+
+ va_start(args, format);
+ ret2 = vsprintf (tmp, format, args);
+ va_end(args);
+ if (ret != ret2 || strcmp(str, tmp) != 0)
+ abort ();
+ free (tmp);
+ }
+#endif
+
+ return ret;
+}
+#endif
+
+#if !defined(HAVE_ASPRINTF) || defined(TEST_SNPRINTF)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_asprintf (char **ret, const char *format, ...)
+{
+ va_list args;
+ int val;
+
+ va_start(args, format);
+ val = vasprintf (ret, format, args);
+ va_end(args);
+
+#ifdef PARANOIA
+ {
+ int ret2;
+ char *tmp;
+ tmp = malloc (val + 1);
+ if (tmp == NULL)
+ abort ();
+
+ va_start(args, format);
+ ret2 = vsprintf (tmp, format, args);
+ va_end(args);
+ if (val != ret2 || strcmp(*ret, tmp) != 0)
+ abort ();
+ free (tmp);
+ }
+#endif
+
+ return val;
+}
+#endif
+
+#if !defined(HAVE_ASNPRINTF) || defined(TEST_SNPRINTF)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_asnprintf (char **ret, size_t max_sz, const char *format, ...)
+{
+ va_list args;
+ int val;
+
+ va_start(args, format);
+ val = vasnprintf (ret, max_sz, format, args);
+
+#ifdef PARANOIA
+ {
+ int ret2;
+ char *tmp;
+ tmp = malloc (val + 1);
+ if (tmp == NULL)
+ abort ();
+
+ ret2 = vsprintf (tmp, format, args);
+ if (val != ret2 || strcmp(*ret, tmp) != 0)
+ abort ();
+ free (tmp);
+ }
+#endif
+
+ va_end(args);
+ return val;
+}
+#endif
+
+#if !defined(HAVE_VASPRINTF) || defined(TEST_SNPRINTF)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_vasprintf (char **ret, const char *format, va_list args)
+{
+ return vasnprintf (ret, 0, format, args);
+}
+#endif
+
+
+#if !defined(HAVE_VASNPRINTF) || defined(TEST_SNPRINTF)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_vasnprintf (char **ret, size_t max_sz, const char *format, va_list args)
+{
+ size_t st;
+ struct snprintf_state state;
+
+ state.max_sz = max_sz;
+ state.sz = 1;
+ state.str = malloc(state.sz);
+ if (state.str == NULL) {
+ *ret = NULL;
+ return -1;
+ }
+ state.s = state.str;
+ state.theend = state.s + state.sz - 1;
+ state.append_char = as_append_char;
+
+ st = xyzprintf (&state, format, args);
+ if (st > state.sz) {
+ free (state.str);
+ *ret = NULL;
+ return -1;
+ } else {
+ char *tmp;
+
+ *state.s = '\0';
+ tmp = realloc (state.str, st+1);
+ if (tmp == NULL) {
+ free (state.str);
+ *ret = NULL;
+ return -1;
+ }
+ *ret = tmp;
+ return st;
+ }
+}
+#endif
+
+#if !defined(HAVE_VSNPRINTF) || defined(TEST_SNPRINTF)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_vsnprintf (char *str, size_t sz, const char *format, va_list args)
+{
+ struct snprintf_state state;
+ int ret;
+ unsigned char *ustr = (unsigned char *)str;
+
+ state.max_sz = 0;
+ state.sz = sz;
+ state.str = ustr;
+ state.s = ustr;
+ state.theend = ustr + sz - (sz > 0);
+ state.append_char = sn_append_char;
+
+ ret = xyzprintf (&state, format, args);
+ if (state.s != NULL && sz != 0)
+ *state.s = '\0';
+ return ret;
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/socket.c b/third_party/heimdal/lib/roken/socket.c
new file mode 100644
index 0000000..a790e08
--- /dev/null
+++ b/third_party/heimdal/lib/roken/socket.c
@@ -0,0 +1,371 @@
+/*
+ * Copyright (c) 1999 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include <err.h>
+
+/*
+ * Set `sa' to the unitialized address of address family `af'
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_any (struct sockaddr *sa, int af)
+{
+ switch (af) {
+ case AF_INET : {
+ struct sockaddr_in *sin4 = (struct sockaddr_in *)sa;
+
+ memset (sin4, 0, sizeof(*sin4));
+ sin4->sin_family = AF_INET;
+ sin4->sin_port = 0;
+ sin4->sin_addr.s_addr = INADDR_ANY;
+ break;
+ }
+#ifdef HAVE_IPV6
+ case AF_INET6 : {
+ struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
+
+ memset (sin6, 0, sizeof(*sin6));
+ sin6->sin6_family = AF_INET6;
+ sin6->sin6_port = 0;
+ sin6->sin6_addr = in6addr_any;
+ break;
+ }
+#endif
+ default :
+ errx (1, "unknown address family %d", sa->sa_family);
+ break;
+ }
+}
+
+/*
+ * set `sa' to (`ptr', `port')
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_address_and_port (struct sockaddr *sa, const void *ptr, int port)
+{
+ switch (sa->sa_family) {
+ case AF_INET : {
+ struct sockaddr_in *sin4 = (struct sockaddr_in *)sa;
+
+ memset (sin4, 0, sizeof(*sin4));
+ sin4->sin_family = AF_INET;
+ sin4->sin_port = port;
+ memcpy (&sin4->sin_addr, ptr, sizeof(struct in_addr));
+ break;
+ }
+#ifdef HAVE_IPV6
+ case AF_INET6 : {
+ struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
+
+ memset (sin6, 0, sizeof(*sin6));
+ sin6->sin6_family = AF_INET6;
+ sin6->sin6_port = port;
+ memcpy (&sin6->sin6_addr, ptr, sizeof(struct in6_addr));
+ break;
+ }
+#endif
+ default :
+ errx (1, "unknown address family %d", sa->sa_family);
+ break;
+ }
+}
+
+/*
+ * Return the size of an address of the type in `sa'
+ */
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+socket_addr_size (const struct sockaddr *sa)
+{
+ switch (sa->sa_family) {
+ case AF_INET :
+ return sizeof(struct in_addr);
+#ifdef HAVE_IPV6
+ case AF_INET6 :
+ return sizeof(struct in6_addr);
+#endif
+ default :
+ return 0;
+ }
+}
+
+/*
+ * Return the size of a `struct sockaddr' in `sa'.
+ */
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+socket_sockaddr_size (const struct sockaddr *sa)
+{
+ switch (sa->sa_family) {
+ case AF_INET :
+ return sizeof(struct sockaddr_in);
+#ifdef HAVE_IPV6
+ case AF_INET6 :
+ return sizeof(struct sockaddr_in6);
+#endif
+ default:
+ return 0;
+ }
+}
+
+/*
+ * Return the binary address of `sa'.
+ */
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+socket_get_address (const struct sockaddr *sa)
+{
+ switch (sa->sa_family) {
+ case AF_INET : {
+ const struct sockaddr_in *sin4 = (const struct sockaddr_in *)sa;
+ return rk_UNCONST(&sin4->sin_addr);
+ }
+#ifdef HAVE_IPV6
+ case AF_INET6 : {
+ const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)sa;
+ return rk_UNCONST(&sin6->sin6_addr);
+ }
+#endif
+ default:
+ return NULL;
+ }
+}
+
+/*
+ * Return the port number from `sa'.
+ */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+socket_get_port (const struct sockaddr *sa)
+{
+ switch (sa->sa_family) {
+ case AF_INET : {
+ const struct sockaddr_in *sin4 = (const struct sockaddr_in *)sa;
+ return sin4->sin_port;
+ }
+#ifdef HAVE_IPV6
+ case AF_INET6 : {
+ const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)sa;
+ return sin6->sin6_port;
+ }
+#endif
+ default :
+ return 0;
+ }
+}
+
+/*
+ * Set the port in `sa' to `port'.
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_port (struct sockaddr *sa, int port)
+{
+ switch (sa->sa_family) {
+ case AF_INET : {
+ struct sockaddr_in *sin4 = (struct sockaddr_in *)sa;
+ sin4->sin_port = port;
+ break;
+ }
+#ifdef HAVE_IPV6
+ case AF_INET6 : {
+ struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
+ sin6->sin6_port = port;
+ break;
+ }
+#endif
+ default :
+ errx (1, "unknown address family %d", sa->sa_family);
+ break;
+ }
+}
+
+/*
+ * Set the range of ports to use when binding with port = 0.
+ */
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_portrange (rk_socket_t sock, int restr, int af)
+{
+#if defined(IP_PORTRANGE)
+ if (af == AF_INET) {
+ int on = restr ? IP_PORTRANGE_HIGH : IP_PORTRANGE_DEFAULT;
+ (void) setsockopt(sock, IPPROTO_IP, IP_PORTRANGE, &on, sizeof(on));
+ }
+#endif
+#if defined(IPV6_PORTRANGE)
+ if (af == AF_INET6) {
+ int on = restr ? IPV6_PORTRANGE_HIGH : IPV6_PORTRANGE_DEFAULT;
+ (void) setsockopt(sock, IPPROTO_IPV6, IPV6_PORTRANGE, &on, sizeof(on));
+ }
+#endif
+}
+
+/*
+ * Enable debug on `sock'.
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_debug (rk_socket_t sock)
+{
+#if defined(SO_DEBUG) && defined(HAVE_SETSOCKOPT)
+ int on = 1;
+ (void) setsockopt(sock, SOL_SOCKET, SO_DEBUG, (void *) &on, sizeof (on));
+#endif
+}
+
+/*
+ * Set the type-of-service of `sock' to `tos'.
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_tos (rk_socket_t sock, int tos)
+{
+#if defined(IP_TOS) && defined(HAVE_SETSOCKOPT)
+ (void) setsockopt (sock, IPPROTO_IP, IP_TOS, (void *) &tos, sizeof(int));
+#endif
+}
+
+/*
+ * Set the non-blocking-ness of the socket.
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_nonblocking(rk_socket_t sock, int nonblock)
+{
+#if defined(O_NONBLOCK)
+ int flags = fcntl(sock, F_GETFL, 0);
+ if (flags == -1)
+ return;
+ if (nonblock)
+ flags |= O_NONBLOCK;
+ else
+ flags &= ~O_NONBLOCK;
+ fcntl(sock, F_SETFL, flags);
+#elif defined(FIOBIO)
+ int flags = !!nonblock;
+ return ioctl(sock, FIOBIO, &flags);
+#endif
+}
+
+/*
+ * set the reuse of addresses on `sock' to `val'.
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_reuseaddr (rk_socket_t sock, int val)
+{
+#if defined(SO_REUSEADDR) && defined(HAVE_SETSOCKOPT)
+ (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&val,
+ sizeof(val));
+#endif
+}
+
+/*
+ * Set the that the `sock' should bind to only IPv6 addresses.
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_ipv6only (rk_socket_t sock, int val)
+{
+#if defined(IPV6_V6ONLY) && defined(HAVE_SETSOCKOPT)
+ (void) setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&val,
+ sizeof(val));
+#endif
+}
+
+/*
+ * Set the that the `sock' keepalive setting.
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_keepalive(rk_socket_t sock, int val)
+{
+ (void) setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&val,
+ sizeof(val));
+}
+
+/**
+ * Create a file descriptor from a socket
+ *
+ * While the socket handle in \a sock can be used with WinSock
+ * functions after calling socket_to_fd(), it should not be closed
+ * with rk_closesocket(). The socket will be closed when the associated
+ * file descriptor is closed.
+ */
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+socket_to_fd(rk_socket_t sock, int flags)
+{
+#ifndef _WIN32
+ return sock;
+#else
+ return _open_osfhandle((intptr_t) sock, flags);
+#endif
+}
+
+#ifdef HAVE_WINSOCK
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_SOCK_IOCTL(SOCKET s, long cmd, int * argp) {
+ u_long ul = (argp)? *argp : 0;
+ int rv;
+
+ rv = ioctlsocket(s, cmd, &ul);
+ if (argp)
+ *argp = (int) ul;
+ return rv;
+}
+#endif
+
+#ifndef HEIMDAL_SMALLER
+#undef socket
+
+int rk_socket(int, int, int);
+
+int
+rk_socket(int domain, int type, int protocol)
+{
+ int s;
+ s = socket (domain, type, protocol);
+#ifdef SOCK_CLOEXEC
+ if ((SOCK_CLOEXEC & type) && s < 0 && errno == EINVAL) {
+ type &= ~SOCK_CLOEXEC;
+ s = socket (domain, type, protocol);
+ }
+#endif
+ return s;
+}
+
+#endif /* HEIMDAL_SMALLER */
diff --git a/third_party/heimdal/lib/roken/socket_wrapper.c b/third_party/heimdal/lib/roken/socket_wrapper.c
new file mode 100644
index 0000000..9438949
--- /dev/null
+++ b/third_party/heimdal/lib/roken/socket_wrapper.c
@@ -0,0 +1,1911 @@
+/*
+ * Copyright (C) Jelmer Vernooij 2005 <jelmer@samba.org>
+ * Copyright (C) Stefan Metzmacher 2006 <metze@samba.org>
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the author nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+
+/*
+ Socket wrapper library. Passes all socket communication over
+ unix domain sockets if the environment variable SOCKET_WRAPPER_DIR
+ is set.
+*/
+
+#define SOCKET_WRAPPER_NOT_REPLACE
+
+#ifdef _SAMBA_BUILD_
+
+#include "includes.h"
+#include "system/network.h"
+#include "system/filesys.h"
+
+#ifdef malloc
+#undef malloc
+#endif
+#ifdef calloc
+#undef calloc
+#endif
+#ifdef strdup
+#undef strdup
+#endif
+
+#else /* _SAMBA_BUILD_ */
+
+#include <config.h>
+#undef SOCKET_WRAPPER_REPLACE
+
+#include <sys/types.h>
+#ifdef TIME_WITH_SYS_TIME
+#include <sys/time.h>
+#include <time.h>
+#elif defined(HAVE_SYS_TIME_H)
+#include <sys/time.h>
+#else
+#include <time.h>
+#endif
+#include <sys/stat.h>
+#include <sys/socket.h>
+#include <sys/ioctl.h>
+#ifdef HAVE_SYS_FILIO_H
+#include <sys/filio.h>
+#endif
+#include <errno.h>
+#include <sys/un.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include <stdio.h>
+#include "roken.h"
+
+#include "socket_wrapper.h"
+
+#define HAVE_GETTIMEOFDAY_TZ 1
+
+#define _PUBLIC_
+
+#endif
+
+#define SWRAP_DLIST_ADD(list,item) do { \
+ if (!(list)) { \
+ (item)->prev = NULL; \
+ (item)->next = NULL; \
+ (list) = (item); \
+ } else { \
+ (item)->prev = NULL; \
+ (item)->next = (list); \
+ (list)->prev = (item); \
+ (list) = (item); \
+ } \
+} while (0)
+
+#define SWRAP_DLIST_REMOVE(list,item) do { \
+ if ((list) == (item)) { \
+ (list) = (item)->next; \
+ if (list) { \
+ (list)->prev = NULL; \
+ } \
+ } else { \
+ if ((item)->prev) { \
+ (item)->prev->next = (item)->next; \
+ } \
+ if ((item)->next) { \
+ (item)->next->prev = (item)->prev; \
+ } \
+ } \
+ (item)->prev = NULL; \
+ (item)->next = NULL; \
+} while (0)
+
+/* LD_PRELOAD doesn't work yet, so REWRITE_CALLS is all we support
+ * for now */
+#define REWRITE_CALLS
+
+#ifdef REWRITE_CALLS
+#define real_accept accept
+#define real_connect connect
+#define real_bind bind
+#define real_listen listen
+#define real_getpeername getpeername
+#define real_getsockname getsockname
+#define real_getsockopt getsockopt
+#define real_setsockopt setsockopt
+#define real_recvfrom recvfrom
+#define real_sendto sendto
+#define real_ioctl ioctl
+#define real_recv recv
+#define real_send send
+#define real_socket socket
+#define real_close close
+#define real_dup dup
+#define real_dup2 dup2
+#endif
+
+#ifdef HAVE_GETTIMEOFDAY_TZ
+#define swrapGetTimeOfDay(tval) gettimeofday(tval,NULL)
+#else
+#define swrapGetTimeOfDay(tval) gettimeofday(tval)
+#endif
+
+/* we need to use a very terse format here as IRIX 6.4 silently
+ truncates names to 16 chars, so if we use a longer name then we
+ can't tell which port a packet came from with recvfrom()
+
+ with this format we have 8 chars left for the directory name
+*/
+#define SOCKET_FORMAT "%c%02X%04X"
+#define SOCKET_TYPE_CHAR_TCP 'T'
+#define SOCKET_TYPE_CHAR_UDP 'U'
+#define SOCKET_TYPE_CHAR_TCP_V6 'X'
+#define SOCKET_TYPE_CHAR_UDP_V6 'Y'
+
+#define MAX_WRAPPED_INTERFACES 16
+
+#define SW_IPV6_ADDRESS 1
+
+static struct sockaddr *sockaddr_dup(const void *data, socklen_t len)
+{
+ struct sockaddr *ret = (struct sockaddr *)malloc(len);
+ memcpy(ret, data, len);
+ return ret;
+}
+
+static void set_port(int family, int prt, struct sockaddr *addr)
+{
+ switch (family) {
+ case AF_INET:
+ ((struct sockaddr_in *)addr)->sin_port = htons(prt);
+ break;
+#ifdef HAVE_IPV6
+ case AF_INET6:
+ ((struct sockaddr_in6 *)addr)->sin6_port = htons(prt);
+ break;
+#endif
+ }
+}
+
+static int socket_length(int family)
+{
+ switch (family) {
+ case AF_INET:
+ return sizeof(struct sockaddr_in);
+#ifdef HAVE_IPV6
+ case AF_INET6:
+ return sizeof(struct sockaddr_in6);
+#endif
+ }
+ return -1;
+}
+
+
+
+struct socket_info
+{
+ int fd;
+
+ int family;
+ int type;
+ int protocol;
+ int bound;
+ int bcast;
+ int is_server;
+
+ char *path;
+ char *tmp_path;
+
+ struct sockaddr *myname;
+ socklen_t myname_len;
+
+ struct sockaddr *peername;
+ socklen_t peername_len;
+
+ struct {
+ unsigned long pck_snd;
+ unsigned long pck_rcv;
+ } io;
+
+ struct socket_info *prev, *next;
+};
+
+static struct socket_info *sockets;
+
+
+static const char *socket_wrapper_dir(void)
+{
+ const char *s = getenv("SOCKET_WRAPPER_DIR");
+ if (s == NULL) {
+ return NULL;
+ }
+ if (strncmp(s, "./", 2) == 0) {
+ s += 2;
+ }
+ return s;
+}
+
+static unsigned int socket_wrapper_default_iface(void)
+{
+ const char *s = getenv("SOCKET_WRAPPER_DEFAULT_IFACE");
+ if (s) {
+ unsigned int iface;
+ if (sscanf(s, "%u", &iface) == 1) {
+ if (iface >= 1 && iface <= MAX_WRAPPED_INTERFACES) {
+ return iface;
+ }
+ }
+ }
+
+ return 1;/* 127.0.0.1 */
+}
+
+static int convert_un_in(const struct sockaddr_un *un, struct sockaddr *in, socklen_t *len)
+{
+ unsigned int iface;
+ unsigned int prt;
+ const char *p;
+ char type;
+
+ p = strrchr(un->sun_path, '/');
+ if (p) p++; else p = un->sun_path;
+
+ if (sscanf(p, SOCKET_FORMAT, &type, &iface, &prt) != 3) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if (iface == 0 || iface > MAX_WRAPPED_INTERFACES) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if (prt > 0xFFFF) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ switch(type) {
+ case SOCKET_TYPE_CHAR_TCP:
+ case SOCKET_TYPE_CHAR_UDP: {
+ struct sockaddr_in *in2 = (struct sockaddr_in *)in;
+
+ if ((*len) < sizeof(*in2)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ memset(in2, 0, sizeof(*in2));
+ in2->sin_family = AF_INET;
+ in2->sin_addr.s_addr = htonl((127<<24) | iface);
+ in2->sin_port = htons(prt);
+
+ *len = sizeof(*in2);
+ break;
+ }
+#ifdef HAVE_IPV6
+ case SOCKET_TYPE_CHAR_TCP_V6:
+ case SOCKET_TYPE_CHAR_UDP_V6: {
+ struct sockaddr_in6 *in2 = (struct sockaddr_in6 *)in;
+
+ if ((*len) < sizeof(*in2)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ memset(in2, 0, sizeof(*in2));
+ in2->sin6_family = AF_INET6;
+ in2->sin6_addr.s6_addr[0] = SW_IPV6_ADDRESS;
+ in2->sin6_port = htons(prt);
+
+ *len = sizeof(*in2);
+ break;
+ }
+#endif
+ default:
+ errno = EINVAL;
+ return -1;
+ }
+
+ return 0;
+}
+
+static int convert_in_un_remote(struct socket_info *si, const struct sockaddr *inaddr, struct sockaddr_un *un,
+ int *bcast)
+{
+ char type = '\0';
+ unsigned int prt;
+ unsigned int iface;
+ int is_bcast = 0;
+
+ if (bcast) *bcast = 0;
+
+ switch (si->family) {
+ case AF_INET: {
+ const struct sockaddr_in *in =
+ (const struct sockaddr_in *)inaddr;
+ unsigned int addr = ntohl(in->sin_addr.s_addr);
+ char u_type = '\0';
+ char b_type = '\0';
+ char a_type = '\0';
+
+ switch (si->type) {
+ case SOCK_STREAM:
+ u_type = SOCKET_TYPE_CHAR_TCP;
+ break;
+ case SOCK_DGRAM:
+ u_type = SOCKET_TYPE_CHAR_UDP;
+ a_type = SOCKET_TYPE_CHAR_UDP;
+ b_type = SOCKET_TYPE_CHAR_UDP;
+ break;
+ }
+
+ prt = ntohs(in->sin_port);
+ if (a_type && addr == 0xFFFFFFFF) {
+ /* 255.255.255.255 only udp */
+ is_bcast = 2;
+ type = a_type;
+ iface = socket_wrapper_default_iface();
+ } else if (b_type && addr == 0x7FFFFFFF) {
+ /* 127.255.255.255 only udp */
+ is_bcast = 1;
+ type = b_type;
+ iface = socket_wrapper_default_iface();
+ } else if ((addr & 0xFFFFFF00) == 0x7F000000) {
+ /* 127.0.0.X */
+ is_bcast = 0;
+ type = u_type;
+ iface = (addr & 0x000000FF);
+ } else {
+ errno = ENETUNREACH;
+ return -1;
+ }
+ if (bcast) *bcast = is_bcast;
+ break;
+ }
+#ifdef HAVE_IPV6
+ case AF_INET6: {
+ const struct sockaddr_in6 *in =
+ (const struct sockaddr_in6 *)inaddr;
+
+ switch (si->type) {
+ case SOCK_STREAM:
+ type = SOCKET_TYPE_CHAR_TCP_V6;
+ break;
+ case SOCK_DGRAM:
+ type = SOCKET_TYPE_CHAR_UDP_V6;
+ break;
+ }
+
+ /* XXX no multicast/broadcast */
+
+ prt = ntohs(in->sin6_port);
+ iface = SW_IPV6_ADDRESS;
+
+ break;
+ }
+#endif
+ default:
+ errno = ENETUNREACH;
+ return -1;
+ }
+
+ if (prt == 0) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if (is_bcast) {
+ snprintf(un->sun_path, sizeof(un->sun_path), "%s/EINVAL",
+ socket_wrapper_dir());
+ /* the caller need to do more processing */
+ return 0;
+ }
+
+ snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT,
+ socket_wrapper_dir(), type, iface, prt);
+
+ return 0;
+}
+
+static int convert_in_un_alloc(struct socket_info *si, const struct sockaddr *inaddr, struct sockaddr_un *un,
+ int *bcast)
+{
+ char type = '\0';
+ unsigned int prt;
+ unsigned int iface;
+ struct stat st;
+ int is_bcast = 0;
+
+ if (bcast) *bcast = 0;
+
+ switch (si->family) {
+ case AF_INET: {
+ const struct sockaddr_in *in =
+ (const struct sockaddr_in *)inaddr;
+ unsigned int addr = ntohl(in->sin_addr.s_addr);
+ char u_type = '\0';
+ char d_type = '\0';
+ char b_type = '\0';
+ char a_type = '\0';
+
+ prt = ntohs(in->sin_port);
+
+ switch (si->type) {
+ case SOCK_STREAM:
+ u_type = SOCKET_TYPE_CHAR_TCP;
+ d_type = SOCKET_TYPE_CHAR_TCP;
+ break;
+ case SOCK_DGRAM:
+ u_type = SOCKET_TYPE_CHAR_UDP;
+ d_type = SOCKET_TYPE_CHAR_UDP;
+ a_type = SOCKET_TYPE_CHAR_UDP;
+ b_type = SOCKET_TYPE_CHAR_UDP;
+ break;
+ }
+
+ if (addr == 0) {
+ /* 0.0.0.0 */
+ is_bcast = 0;
+ type = d_type;
+ iface = socket_wrapper_default_iface();
+ } else if (a_type && addr == 0xFFFFFFFF) {
+ /* 255.255.255.255 only udp */
+ is_bcast = 2;
+ type = a_type;
+ iface = socket_wrapper_default_iface();
+ } else if (b_type && addr == 0x7FFFFFFF) {
+ /* 127.255.255.255 only udp */
+ is_bcast = 1;
+ type = b_type;
+ iface = socket_wrapper_default_iface();
+ } else if ((addr & 0xFFFFFF00) == 0x7F000000) {
+ /* 127.0.0.X */
+ is_bcast = 0;
+ type = u_type;
+ iface = (addr & 0x000000FF);
+ } else {
+ errno = EADDRNOTAVAIL;
+ return -1;
+ }
+ break;
+ }
+#ifdef HAVE_IPV6
+ case AF_INET6: {
+ const struct sockaddr_in6 *in =
+ (const struct sockaddr_in6 *)inaddr;
+
+ switch (si->type) {
+ case SOCK_STREAM:
+ type = SOCKET_TYPE_CHAR_TCP_V6;
+ break;
+ case SOCK_DGRAM:
+ type = SOCKET_TYPE_CHAR_UDP_V6;
+ break;
+ }
+
+ /* XXX no multicast/broadcast */
+
+ prt = ntohs(in->sin6_port);
+ iface = SW_IPV6_ADDRESS;
+
+ break;
+ }
+#endif
+ default:
+ errno = ENETUNREACH;
+ return -1;
+ }
+
+
+ if (bcast) *bcast = is_bcast;
+
+ if (prt == 0) {
+ /* handle auto-allocation of ephemeral ports */
+ for (prt = 5001; prt < 10000; prt++) {
+ snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT,
+ socket_wrapper_dir(), type, iface, prt);
+ if (stat(un->sun_path, &st) == 0) continue;
+
+ set_port(si->family, prt, si->myname);
+ }
+ }
+
+ snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT,
+ socket_wrapper_dir(), type, iface, prt);
+ return 0;
+}
+
+static struct socket_info *find_socket_info(int fd)
+{
+ struct socket_info *i;
+ for (i = sockets; i; i = i->next) {
+ if (i->fd == fd)
+ return i;
+ }
+
+ return NULL;
+}
+
+static int sockaddr_convert_to_un(struct socket_info *si, const struct sockaddr *in_addr, socklen_t in_len,
+ struct sockaddr_un *out_addr, int alloc_sock, int *bcast)
+{
+ if (!out_addr)
+ return 0;
+
+ out_addr->sun_family = AF_UNIX;
+
+ switch (in_addr->sa_family) {
+ case AF_INET:
+#ifdef HAVE_IPV6
+ case AF_INET6:
+#endif
+ switch (si->type) {
+ case SOCK_STREAM:
+ case SOCK_DGRAM:
+ break;
+ default:
+ errno = ESOCKTNOSUPPORT;
+ return -1;
+ }
+ if (alloc_sock) {
+ return convert_in_un_alloc(si, in_addr, out_addr, bcast);
+ } else {
+ return convert_in_un_remote(si, in_addr, out_addr, bcast);
+ }
+ default:
+ break;
+ }
+
+ errno = EAFNOSUPPORT;
+ return -1;
+}
+
+static int sockaddr_convert_from_un(const struct socket_info *si,
+ const struct sockaddr_un *in_addr,
+ socklen_t un_addrlen,
+ int family,
+ struct sockaddr *out_addr,
+ socklen_t *out_addrlen)
+{
+ if (out_addr == NULL || out_addrlen == NULL)
+ return 0;
+
+ if (un_addrlen == 0) {
+ *out_addrlen = 0;
+ return 0;
+ }
+
+ switch (family) {
+ case AF_INET:
+#ifdef HAVE_IPV6
+ case AF_INET6:
+#endif
+ switch (si->type) {
+ case SOCK_STREAM:
+ case SOCK_DGRAM:
+ break;
+ default:
+ errno = ESOCKTNOSUPPORT;
+ return -1;
+ }
+ return convert_un_in(in_addr, out_addr, out_addrlen);
+ default:
+ break;
+ }
+
+ errno = EAFNOSUPPORT;
+ return -1;
+}
+
+enum swrap_packet_type {
+ SWRAP_CONNECT_SEND,
+ SWRAP_CONNECT_UNREACH,
+ SWRAP_CONNECT_RECV,
+ SWRAP_CONNECT_ACK,
+ SWRAP_ACCEPT_SEND,
+ SWRAP_ACCEPT_RECV,
+ SWRAP_ACCEPT_ACK,
+ SWRAP_RECVFROM,
+ SWRAP_SENDTO,
+ SWRAP_SENDTO_UNREACH,
+ SWRAP_PENDING_RST,
+ SWRAP_RECV,
+ SWRAP_RECV_RST,
+ SWRAP_SEND,
+ SWRAP_SEND_RST,
+ SWRAP_CLOSE_SEND,
+ SWRAP_CLOSE_RECV,
+ SWRAP_CLOSE_ACK
+};
+
+struct swrap_file_hdr {
+ unsigned long magic;
+ unsigned short version_major;
+ unsigned short version_minor;
+ long timezone;
+ unsigned long sigfigs;
+ unsigned long frame_max_len;
+#define SWRAP_FRAME_LENGTH_MAX 0xFFFF
+ unsigned long link_type;
+};
+#define SWRAP_FILE_HDR_SIZE 24
+
+struct swrap_packet {
+ struct {
+ unsigned long seconds;
+ unsigned long micro_seconds;
+ unsigned long recorded_length;
+ unsigned long full_length;
+ } frame;
+#define SWRAP_PACKET__FRAME_SIZE 16
+
+ struct {
+ struct {
+ unsigned char ver_hdrlen;
+ unsigned char tos;
+ unsigned short packet_length;
+ unsigned short identification;
+ unsigned char flags;
+ unsigned char fragment;
+ unsigned char ttl;
+ unsigned char protocol;
+ unsigned short hdr_checksum;
+ unsigned long src_addr;
+ unsigned long dest_addr;
+ } hdr;
+#define SWRAP_PACKET__IP_HDR_SIZE 20
+
+ union {
+ struct {
+ unsigned short source_port;
+ unsigned short dest_port;
+ unsigned long seq_num;
+ unsigned long ack_num;
+ unsigned char hdr_length;
+ unsigned char control;
+ unsigned short window;
+ unsigned short checksum;
+ unsigned short urg;
+ } tcp;
+#define SWRAP_PACKET__IP_P_TCP_SIZE 20
+ struct {
+ unsigned short source_port;
+ unsigned short dest_port;
+ unsigned short length;
+ unsigned short checksum;
+ } udp;
+#define SWRAP_PACKET__IP_P_UDP_SIZE 8
+ struct {
+ unsigned char type;
+ unsigned char code;
+ unsigned short checksum;
+ unsigned long unused;
+ } icmp;
+#define SWRAP_PACKET__IP_P_ICMP_SIZE 8
+ } p;
+ } ip;
+};
+#define SWRAP_PACKET_SIZE 56
+
+static const char *socket_wrapper_pcap_file(void)
+{
+ static int initialized = 0;
+ static const char *s = NULL;
+ static const struct swrap_file_hdr h;
+ static const struct swrap_packet p;
+
+ if (initialized == 1) {
+ return s;
+ }
+ initialized = 1;
+
+ /*
+ * TODO: don't use the structs use plain buffer offsets
+ * and PUSH_U8(), PUSH_U16() and PUSH_U32()
+ *
+ * for now make sure we disable PCAP support
+ * if the struct has alignment!
+ */
+ if (sizeof(h) != SWRAP_FILE_HDR_SIZE) {
+ return NULL;
+ }
+ if (sizeof(p) != SWRAP_PACKET_SIZE) {
+ return NULL;
+ }
+ if (sizeof(p.frame) != SWRAP_PACKET__FRAME_SIZE) {
+ return NULL;
+ }
+ if (sizeof(p.ip.hdr) != SWRAP_PACKET__IP_HDR_SIZE) {
+ return NULL;
+ }
+ if (sizeof(p.ip.p.tcp) != SWRAP_PACKET__IP_P_TCP_SIZE) {
+ return NULL;
+ }
+ if (sizeof(p.ip.p.udp) != SWRAP_PACKET__IP_P_UDP_SIZE) {
+ return NULL;
+ }
+ if (sizeof(p.ip.p.icmp) != SWRAP_PACKET__IP_P_ICMP_SIZE) {
+ return NULL;
+ }
+
+ s = getenv("SOCKET_WRAPPER_PCAP_FILE");
+ if (s == NULL) {
+ return NULL;
+ }
+ if (strncmp(s, "./", 2) == 0) {
+ s += 2;
+ }
+ return s;
+}
+
+static struct swrap_packet *swrap_packet_init(struct timeval *tval,
+ const struct sockaddr_in *src_addr,
+ const struct sockaddr_in *dest_addr,
+ int socket_type,
+ const unsigned char *payload,
+ size_t payload_len,
+ unsigned long tcp_seq,
+ unsigned long tcp_ack,
+ unsigned char tcp_ctl,
+ int unreachable,
+ size_t *_packet_len)
+{
+ struct swrap_packet *ret;
+ struct swrap_packet *packet;
+ size_t packet_len;
+ size_t alloc_len;
+ size_t nonwire_len = sizeof(packet->frame);
+ size_t wire_hdr_len = 0;
+ size_t wire_len = 0;
+ size_t icmp_hdr_len = 0;
+ size_t icmp_truncate_len = 0;
+ unsigned char protocol = 0, icmp_protocol = 0;
+ unsigned short src_port = src_addr->sin_port;
+ unsigned short dest_port = dest_addr->sin_port;
+
+ switch (socket_type) {
+ case SOCK_STREAM:
+ protocol = 0x06; /* TCP */
+ wire_hdr_len = sizeof(packet->ip.hdr) + sizeof(packet->ip.p.tcp);
+ wire_len = wire_hdr_len + payload_len;
+ break;
+
+ case SOCK_DGRAM:
+ protocol = 0x11; /* UDP */
+ wire_hdr_len = sizeof(packet->ip.hdr) + sizeof(packet->ip.p.udp);
+ wire_len = wire_hdr_len + payload_len;
+ break;
+ }
+
+ if (unreachable) {
+ icmp_protocol = protocol;
+ protocol = 0x01; /* ICMP */
+ if (wire_len > 64 ) {
+ icmp_truncate_len = wire_len - 64;
+ }
+ icmp_hdr_len = sizeof(packet->ip.hdr) + sizeof(packet->ip.p.icmp);
+ wire_hdr_len += icmp_hdr_len;
+ wire_len += icmp_hdr_len;
+ }
+
+ packet_len = nonwire_len + wire_len;
+ alloc_len = packet_len;
+ if (alloc_len < sizeof(struct swrap_packet)) {
+ alloc_len = sizeof(struct swrap_packet);
+ }
+ ret = (struct swrap_packet *)malloc(alloc_len);
+ if (!ret) return NULL;
+
+ packet = ret;
+
+ packet->frame.seconds = tval->tv_sec;
+ packet->frame.micro_seconds = tval->tv_usec;
+ packet->frame.recorded_length = wire_len - icmp_truncate_len;
+ packet->frame.full_length = wire_len - icmp_truncate_len;
+
+ packet->ip.hdr.ver_hdrlen = 0x45; /* version 4 and 5 * 32 bit words */
+ packet->ip.hdr.tos = 0x00;
+ packet->ip.hdr.packet_length = htons(wire_len - icmp_truncate_len);
+ packet->ip.hdr.identification = htons(0xFFFF);
+ packet->ip.hdr.flags = 0x40; /* BIT 1 set - means don't fraqment */
+ packet->ip.hdr.fragment = htons(0x0000);
+ packet->ip.hdr.ttl = 0xFF;
+ packet->ip.hdr.protocol = protocol;
+ packet->ip.hdr.hdr_checksum = htons(0x0000);
+ packet->ip.hdr.src_addr = src_addr->sin_addr.s_addr;
+ packet->ip.hdr.dest_addr = dest_addr->sin_addr.s_addr;
+
+ if (unreachable) {
+ packet->ip.p.icmp.type = 0x03; /* destination unreachable */
+ packet->ip.p.icmp.code = 0x01; /* host unreachable */
+ packet->ip.p.icmp.checksum = htons(0x0000);
+ packet->ip.p.icmp.unused = htonl(0x00000000);
+
+ /* set the ip header in the ICMP payload */
+ packet = (struct swrap_packet *)(((unsigned char *)ret) + icmp_hdr_len);
+ packet->ip.hdr.ver_hdrlen = 0x45; /* version 4 and 5 * 32 bit words */
+ packet->ip.hdr.tos = 0x00;
+ packet->ip.hdr.packet_length = htons(wire_len - icmp_hdr_len);
+ packet->ip.hdr.identification = htons(0xFFFF);
+ packet->ip.hdr.flags = 0x40; /* BIT 1 set - means don't fraqment */
+ packet->ip.hdr.fragment = htons(0x0000);
+ packet->ip.hdr.ttl = 0xFF;
+ packet->ip.hdr.protocol = icmp_protocol;
+ packet->ip.hdr.hdr_checksum = htons(0x0000);
+ packet->ip.hdr.src_addr = dest_addr->sin_addr.s_addr;
+ packet->ip.hdr.dest_addr = src_addr->sin_addr.s_addr;
+
+ src_port = dest_addr->sin_port;
+ dest_port = src_addr->sin_port;
+ }
+
+ switch (socket_type) {
+ case SOCK_STREAM:
+ packet->ip.p.tcp.source_port = src_port;
+ packet->ip.p.tcp.dest_port = dest_port;
+ packet->ip.p.tcp.seq_num = htonl(tcp_seq);
+ packet->ip.p.tcp.ack_num = htonl(tcp_ack);
+ packet->ip.p.tcp.hdr_length = 0x50; /* 5 * 32 bit words */
+ packet->ip.p.tcp.control = tcp_ctl;
+ packet->ip.p.tcp.window = htons(0x7FFF);
+ packet->ip.p.tcp.checksum = htons(0x0000);
+ packet->ip.p.tcp.urg = htons(0x0000);
+
+ break;
+
+ case SOCK_DGRAM:
+ packet->ip.p.udp.source_port = src_addr->sin_port;
+ packet->ip.p.udp.dest_port = dest_addr->sin_port;
+ packet->ip.p.udp.length = htons(8 + payload_len);
+ packet->ip.p.udp.checksum = htons(0x0000);
+
+ break;
+ }
+
+ if (payload && payload_len > 0) {
+ unsigned char *p = (unsigned char *)ret;
+ p += nonwire_len;
+ p += wire_hdr_len;
+ memcpy(p, payload, payload_len);
+ }
+
+ *_packet_len = packet_len - icmp_truncate_len;
+ return ret;
+}
+
+static int swrap_get_pcap_fd(const char *fname)
+{
+ static int fd = -1;
+
+ if (fd != -1) return fd;
+
+ fd = open(fname, O_WRONLY|O_CREAT|O_EXCL|O_APPEND, 0644);
+ if (fd != -1) {
+ struct swrap_file_hdr file_hdr;
+ file_hdr.magic = 0xA1B2C3D4;
+ file_hdr.version_major = 0x0002;
+ file_hdr.version_minor = 0x0004;
+ file_hdr.timezone = 0x00000000;
+ file_hdr.sigfigs = 0x00000000;
+ file_hdr.frame_max_len = SWRAP_FRAME_LENGTH_MAX;
+ file_hdr.link_type = 0x0065; /* 101 RAW IP */
+
+ write(fd, &file_hdr, sizeof(file_hdr));
+ return fd;
+ }
+
+ fd = open(fname, O_WRONLY|O_APPEND, 0644);
+
+ return fd;
+}
+
+static void swrap_dump_packet(struct socket_info *si, const struct sockaddr *addr,
+ enum swrap_packet_type type,
+ const void *buf, size_t len)
+{
+ const struct sockaddr_in *src_addr;
+ const struct sockaddr_in *dest_addr;
+ const char *file_name;
+ unsigned long tcp_seq = 0;
+ unsigned long tcp_ack = 0;
+ unsigned char tcp_ctl = 0;
+ int unreachable = 0;
+ struct timeval tv;
+ struct swrap_packet *packet;
+ size_t packet_len = 0;
+ int fd;
+
+ file_name = socket_wrapper_pcap_file();
+ if (!file_name) {
+ return;
+ }
+
+ switch (si->family) {
+ case AF_INET:
+#ifdef HAVE_IPV6
+ case AF_INET6:
+#endif
+ break;
+ default:
+ return;
+ }
+
+ switch (type) {
+ case SWRAP_CONNECT_SEND:
+ if (si->type != SOCK_STREAM) return;
+
+ src_addr = (const struct sockaddr_in *)si->myname;
+ dest_addr = (const struct sockaddr_in *)addr;
+
+ tcp_seq = si->io.pck_snd;
+ tcp_ack = si->io.pck_rcv;
+ tcp_ctl = 0x02; /* SYN */
+
+ si->io.pck_snd += 1;
+
+ break;
+
+ case SWRAP_CONNECT_RECV:
+ if (si->type != SOCK_STREAM) return;
+
+ dest_addr = (const struct sockaddr_in *)si->myname;
+ src_addr = (const struct sockaddr_in *)addr;
+
+ tcp_seq = si->io.pck_rcv;
+ tcp_ack = si->io.pck_snd;
+ tcp_ctl = 0x12; /** SYN,ACK */
+
+ si->io.pck_rcv += 1;
+
+ break;
+
+ case SWRAP_CONNECT_UNREACH:
+ if (si->type != SOCK_STREAM) return;
+
+ dest_addr = (const struct sockaddr_in *)si->myname;
+ src_addr = (const struct sockaddr_in *)addr;
+
+ /* Unreachable: resend the data of SWRAP_CONNECT_SEND */
+ tcp_seq = si->io.pck_snd - 1;
+ tcp_ack = si->io.pck_rcv;
+ tcp_ctl = 0x02; /* SYN */
+ unreachable = 1;
+
+ break;
+
+ case SWRAP_CONNECT_ACK:
+ if (si->type != SOCK_STREAM) return;
+
+ src_addr = (const struct sockaddr_in *)si->myname;
+ dest_addr = (const struct sockaddr_in *)addr;
+
+ tcp_seq = si->io.pck_snd;
+ tcp_ack = si->io.pck_rcv;
+ tcp_ctl = 0x10; /* ACK */
+
+ break;
+
+ case SWRAP_ACCEPT_SEND:
+ if (si->type != SOCK_STREAM) return;
+
+ dest_addr = (const struct sockaddr_in *)si->myname;
+ src_addr = (const struct sockaddr_in *)addr;
+
+ tcp_seq = si->io.pck_rcv;
+ tcp_ack = si->io.pck_snd;
+ tcp_ctl = 0x02; /* SYN */
+
+ si->io.pck_rcv += 1;
+
+ break;
+
+ case SWRAP_ACCEPT_RECV:
+ if (si->type != SOCK_STREAM) return;
+
+ src_addr = (const struct sockaddr_in *)si->myname;
+ dest_addr = (const struct sockaddr_in *)addr;
+
+ tcp_seq = si->io.pck_snd;
+ tcp_ack = si->io.pck_rcv;
+ tcp_ctl = 0x12; /* SYN,ACK */
+
+ si->io.pck_snd += 1;
+
+ break;
+
+ case SWRAP_ACCEPT_ACK:
+ if (si->type != SOCK_STREAM) return;
+
+ dest_addr = (const struct sockaddr_in *)si->myname;
+ src_addr = (const struct sockaddr_in *)addr;
+
+ tcp_seq = si->io.pck_rcv;
+ tcp_ack = si->io.pck_snd;
+ tcp_ctl = 0x10; /* ACK */
+
+ break;
+
+ case SWRAP_SEND:
+ src_addr = (const struct sockaddr_in *)si->myname;
+ dest_addr = (const struct sockaddr_in *)si->peername;
+
+ tcp_seq = si->io.pck_snd;
+ tcp_ack = si->io.pck_rcv;
+ tcp_ctl = 0x18; /* PSH,ACK */
+
+ si->io.pck_snd += len;
+
+ break;
+
+ case SWRAP_SEND_RST:
+ dest_addr = (const struct sockaddr_in *)si->myname;
+ src_addr = (const struct sockaddr_in *)si->peername;
+
+ if (si->type == SOCK_DGRAM) {
+ swrap_dump_packet(si, si->peername,
+ SWRAP_SENDTO_UNREACH,
+ buf, len);
+ return;
+ }
+
+ tcp_seq = si->io.pck_rcv;
+ tcp_ack = si->io.pck_snd;
+ tcp_ctl = 0x14; /** RST,ACK */
+
+ break;
+
+ case SWRAP_PENDING_RST:
+ dest_addr = (const struct sockaddr_in *)si->myname;
+ src_addr = (const struct sockaddr_in *)si->peername;
+
+ if (si->type == SOCK_DGRAM) {
+ return;
+ }
+
+ tcp_seq = si->io.pck_rcv;
+ tcp_ack = si->io.pck_snd;
+ tcp_ctl = 0x14; /* RST,ACK */
+
+ break;
+
+ case SWRAP_RECV:
+ dest_addr = (const struct sockaddr_in *)si->myname;
+ src_addr = (const struct sockaddr_in *)si->peername;
+
+ tcp_seq = si->io.pck_rcv;
+ tcp_ack = si->io.pck_snd;
+ tcp_ctl = 0x18; /* PSH,ACK */
+
+ si->io.pck_rcv += len;
+
+ break;
+
+ case SWRAP_RECV_RST:
+ dest_addr = (const struct sockaddr_in *)si->myname;
+ src_addr = (const struct sockaddr_in *)si->peername;
+
+ if (si->type == SOCK_DGRAM) {
+ return;
+ }
+
+ tcp_seq = si->io.pck_rcv;
+ tcp_ack = si->io.pck_snd;
+ tcp_ctl = 0x14; /* RST,ACK */
+
+ break;
+
+ case SWRAP_SENDTO:
+ src_addr = (const struct sockaddr_in *)si->myname;
+ dest_addr = (const struct sockaddr_in *)addr;
+
+ si->io.pck_snd += len;
+
+ break;
+
+ case SWRAP_SENDTO_UNREACH:
+ dest_addr = (const struct sockaddr_in *)si->myname;
+ src_addr = (const struct sockaddr_in *)addr;
+
+ unreachable = 1;
+
+ break;
+
+ case SWRAP_RECVFROM:
+ dest_addr = (const struct sockaddr_in *)si->myname;
+ src_addr = (const struct sockaddr_in *)addr;
+
+ si->io.pck_rcv += len;
+
+ break;
+
+ case SWRAP_CLOSE_SEND:
+ if (si->type != SOCK_STREAM) return;
+
+ src_addr = (const struct sockaddr_in *)si->myname;
+ dest_addr = (const struct sockaddr_in *)si->peername;
+
+ tcp_seq = si->io.pck_snd;
+ tcp_ack = si->io.pck_rcv;
+ tcp_ctl = 0x11; /* FIN, ACK */
+
+ si->io.pck_snd += 1;
+
+ break;
+
+ case SWRAP_CLOSE_RECV:
+ if (si->type != SOCK_STREAM) return;
+
+ dest_addr = (const struct sockaddr_in *)si->myname;
+ src_addr = (const struct sockaddr_in *)si->peername;
+
+ tcp_seq = si->io.pck_rcv;
+ tcp_ack = si->io.pck_snd;
+ tcp_ctl = 0x11; /* FIN,ACK */
+
+ si->io.pck_rcv += 1;
+
+ break;
+
+ case SWRAP_CLOSE_ACK:
+ if (si->type != SOCK_STREAM) return;
+
+ src_addr = (const struct sockaddr_in *)si->myname;
+ dest_addr = (const struct sockaddr_in *)si->peername;
+
+ tcp_seq = si->io.pck_snd;
+ tcp_ack = si->io.pck_rcv;
+ tcp_ctl = 0x10; /* ACK */
+
+ break;
+ default:
+ return;
+ }
+
+ swrapGetTimeOfDay(&tv);
+
+ packet = swrap_packet_init(&tv, src_addr, dest_addr, si->type,
+ (const unsigned char *)buf, len,
+ tcp_seq, tcp_ack, tcp_ctl, unreachable,
+ &packet_len);
+ if (!packet) {
+ return;
+ }
+
+ fd = swrap_get_pcap_fd(file_name);
+ if (fd != -1) {
+ write(fd, packet, packet_len);
+ }
+
+ free(packet);
+}
+
+_PUBLIC_ int swrap_socket(int family, int type, int protocol)
+{
+ struct socket_info *si;
+ int fd;
+
+ if (!socket_wrapper_dir()) {
+ return real_socket(family, type, protocol);
+ }
+
+ switch (family) {
+ case AF_INET:
+#ifdef HAVE_IPV6
+ case AF_INET6:
+#endif
+ break;
+ case AF_UNIX:
+ return real_socket(family, type, protocol);
+ default:
+ errno = EAFNOSUPPORT;
+ return -1;
+ }
+
+ switch (type) {
+ case SOCK_STREAM:
+ break;
+ case SOCK_DGRAM:
+ break;
+ default:
+ errno = EPROTONOSUPPORT;
+ return -1;
+ }
+
+#if 0
+ switch (protocol) {
+ case 0:
+ break;
+ default:
+ errno = EPROTONOSUPPORT;
+ return -1;
+ }
+#endif
+
+ fd = real_socket(AF_UNIX, type, 0);
+
+ if (fd == -1) return -1;
+
+ si = (struct socket_info *)calloc(1, sizeof(struct socket_info));
+
+ si->family = family;
+ si->type = type;
+ si->protocol = protocol;
+ si->fd = fd;
+
+ SWRAP_DLIST_ADD(sockets, si);
+
+ return si->fd;
+}
+
+_PUBLIC_ int swrap_accept(int s, struct sockaddr *addr, socklen_t *addrlen)
+{
+ struct socket_info *parent_si, *child_si;
+ int fd;
+ struct sockaddr_un un_addr;
+ socklen_t un_addrlen = sizeof(un_addr);
+ struct sockaddr_un un_my_addr;
+ socklen_t un_my_addrlen = sizeof(un_my_addr);
+ struct sockaddr *my_addr;
+ socklen_t my_addrlen, len;
+ int ret;
+
+ parent_si = find_socket_info(s);
+ if (!parent_si) {
+ return real_accept(s, addr, addrlen);
+ }
+
+ /*
+ * assume out sockaddr have the same size as the in parent
+ * socket family
+ */
+ my_addrlen = socket_length(parent_si->family);
+ if (my_addrlen < 0) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ my_addr = malloc(my_addrlen);
+ if (my_addr == NULL) {
+ return -1;
+ }
+
+ memset(&un_addr, 0, sizeof(un_addr));
+ memset(&un_my_addr, 0, sizeof(un_my_addr));
+
+ ret = real_accept(s, (struct sockaddr *)&un_addr, &un_addrlen);
+ if (ret == -1) {
+ free(my_addr);
+ return ret;
+ }
+
+ fd = ret;
+
+ len = my_addrlen;
+ ret = sockaddr_convert_from_un(parent_si, &un_addr, un_addrlen,
+ parent_si->family, my_addr, &len);
+ if (ret == -1) {
+ free(my_addr);
+ close(fd);
+ return ret;
+ }
+
+ child_si = (struct socket_info *)malloc(sizeof(struct socket_info));
+ memset(child_si, 0, sizeof(*child_si));
+
+ child_si->fd = fd;
+ child_si->family = parent_si->family;
+ child_si->type = parent_si->type;
+ child_si->protocol = parent_si->protocol;
+ child_si->bound = 1;
+ child_si->is_server = 1;
+
+ child_si->peername_len = len;
+ child_si->peername = sockaddr_dup(my_addr, len);
+
+ if (addr != NULL && addrlen != NULL) {
+ *addrlen = len;
+ if (*addrlen >= len)
+ memcpy(addr, my_addr, len);
+ *addrlen = 0;
+ }
+
+ ret = real_getsockname(fd, (struct sockaddr *)&un_my_addr, &un_my_addrlen);
+ if (ret == -1) {
+ free(child_si);
+ close(fd);
+ return ret;
+ }
+
+ len = my_addrlen;
+ ret = sockaddr_convert_from_un(child_si, &un_my_addr, un_my_addrlen,
+ child_si->family, my_addr, &len);
+ if (ret == -1) {
+ free(child_si);
+ free(my_addr);
+ close(fd);
+ return ret;
+ }
+
+ child_si->myname_len = len;
+ child_si->myname = sockaddr_dup(my_addr, len);
+ free(my_addr);
+
+ SWRAP_DLIST_ADD(sockets, child_si);
+
+ swrap_dump_packet(child_si, addr, SWRAP_ACCEPT_SEND, NULL, 0);
+ swrap_dump_packet(child_si, addr, SWRAP_ACCEPT_RECV, NULL, 0);
+ swrap_dump_packet(child_si, addr, SWRAP_ACCEPT_ACK, NULL, 0);
+
+ return fd;
+}
+
+static int autobind_start_init;
+static int autobind_start;
+
+/* using sendto() or connect() on an unbound socket would give the
+ recipient no way to reply, as unlike UDP and TCP, a unix domain
+ socket can't auto-assign emphemeral port numbers, so we need to
+ assign it here */
+static int swrap_auto_bind(struct socket_info *si)
+{
+ struct sockaddr_un un_addr;
+ int i;
+ char type;
+ int ret;
+ int port;
+ struct stat st;
+
+ if (autobind_start_init != 1) {
+ autobind_start_init = 1;
+ autobind_start = getpid();
+ autobind_start %= 50000;
+ autobind_start += 10000;
+ }
+
+ un_addr.sun_family = AF_UNIX;
+
+ switch (si->family) {
+ case AF_INET: {
+ struct sockaddr_in in;
+
+ switch (si->type) {
+ case SOCK_STREAM:
+ type = SOCKET_TYPE_CHAR_TCP;
+ break;
+ case SOCK_DGRAM:
+ type = SOCKET_TYPE_CHAR_UDP;
+ break;
+ default:
+ errno = ESOCKTNOSUPPORT;
+ return -1;
+ }
+
+ memset(&in, 0, sizeof(in));
+ in.sin_family = AF_INET;
+ in.sin_addr.s_addr = htonl(127<<24 |
+ socket_wrapper_default_iface());
+
+ si->myname_len = sizeof(in);
+ si->myname = sockaddr_dup(&in, si->myname_len);
+ break;
+ }
+#ifdef HAVE_IPV6
+ case AF_INET6: {
+ struct sockaddr_in6 in6;
+
+ switch (si->type) {
+ case SOCK_STREAM:
+ type = SOCKET_TYPE_CHAR_TCP_V6;
+ break;
+ case SOCK_DGRAM:
+ type = SOCKET_TYPE_CHAR_UDP_V6;
+ break;
+ default:
+ errno = ESOCKTNOSUPPORT;
+ return -1;
+ }
+
+ memset(&in6, 0, sizeof(in6));
+ in6.sin6_family = AF_INET6;
+ in6.sin6_addr.s6_addr[0] = SW_IPV6_ADDRESS;
+ si->myname_len = sizeof(in6);
+ si->myname = sockaddr_dup(&in6, si->myname_len);
+ break;
+ }
+#endif
+ default:
+ errno = ESOCKTNOSUPPORT;
+ return -1;
+ }
+
+ if (autobind_start > 60000) {
+ autobind_start = 10000;
+ }
+
+ for (i=0;i<1000;i++) {
+ port = autobind_start + i;
+ snprintf(un_addr.sun_path, sizeof(un_addr.sun_path),
+ "%s/"SOCKET_FORMAT, socket_wrapper_dir(),
+ type, socket_wrapper_default_iface(), port);
+ if (stat(un_addr.sun_path, &st) == 0) continue;
+
+ ret = real_bind(si->fd, (struct sockaddr *)&un_addr, sizeof(un_addr));
+ if (ret == -1) return ret;
+
+ si->tmp_path = strdup(un_addr.sun_path);
+ si->bound = 1;
+ autobind_start = port + 1;
+ break;
+ }
+ if (i == 1000) {
+ errno = ENFILE;
+ return -1;
+ }
+
+ set_port(si->family, port, si->myname);
+
+ return 0;
+}
+
+
+_PUBLIC_ int swrap_connect(int s, const struct sockaddr *serv_addr, socklen_t addrlen)
+{
+ int ret;
+ struct sockaddr_un un_addr;
+ struct socket_info *si = find_socket_info(s);
+
+ if (!si) {
+ return real_connect(s, serv_addr, addrlen);
+ }
+
+ if (si->bound == 0) {
+ ret = swrap_auto_bind(si);
+ if (ret == -1) return -1;
+ }
+
+ if (si->family != serv_addr->sa_family) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ ret = sockaddr_convert_to_un(si, (const struct sockaddr *)serv_addr, addrlen, &un_addr, 0, NULL);
+ if (ret == -1) return -1;
+
+ swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_SEND, NULL, 0);
+
+ ret = real_connect(s, (struct sockaddr *)&un_addr,
+ sizeof(struct sockaddr_un));
+
+ /* to give better errors */
+ if (ret == -1 && errno == ENOENT) {
+ errno = EHOSTUNREACH;
+ }
+
+ if (ret == 0) {
+ si->peername_len = addrlen;
+ si->peername = sockaddr_dup(serv_addr, addrlen);
+
+ swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_RECV, NULL, 0);
+ swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_ACK, NULL, 0);
+ } else {
+ swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_UNREACH, NULL, 0);
+ }
+
+ return ret;
+}
+
+_PUBLIC_ int swrap_bind(int s, const struct sockaddr *myaddr, socklen_t addrlen)
+{
+ int ret;
+ struct sockaddr_un un_addr;
+ struct socket_info *si = find_socket_info(s);
+
+ if (!si) {
+ return real_bind(s, myaddr, addrlen);
+ }
+
+ si->myname_len = addrlen;
+ si->myname = sockaddr_dup(myaddr, addrlen);
+
+ ret = sockaddr_convert_to_un(si, (const struct sockaddr *)myaddr, addrlen, &un_addr, 1, &si->bcast);
+ if (ret == -1) return -1;
+
+ unlink(un_addr.sun_path);
+
+ ret = real_bind(s, (struct sockaddr *)&un_addr,
+ sizeof(struct sockaddr_un));
+
+ if (ret == 0) {
+ si->bound = 1;
+ }
+
+ return ret;
+}
+
+_PUBLIC_ int swrap_listen(int s, int backlog)
+{
+ int ret;
+ struct socket_info *si = find_socket_info(s);
+
+ if (!si) {
+ return real_listen(s, backlog);
+ }
+
+ ret = real_listen(s, backlog);
+
+ return ret;
+}
+
+_PUBLIC_ int swrap_getpeername(int s, struct sockaddr *name, socklen_t *addrlen)
+{
+ struct socket_info *si = find_socket_info(s);
+
+ if (!si) {
+ return real_getpeername(s, name, addrlen);
+ }
+
+ if (!si->peername)
+ {
+ errno = ENOTCONN;
+ return -1;
+ }
+
+ memcpy(name, si->peername, si->peername_len);
+ *addrlen = si->peername_len;
+
+ return 0;
+}
+
+_PUBLIC_ int swrap_getsockname(int s, struct sockaddr *name, socklen_t *addrlen)
+{
+ struct socket_info *si = find_socket_info(s);
+
+ if (!si) {
+ return real_getsockname(s, name, addrlen);
+ }
+
+ memcpy(name, si->myname, si->myname_len);
+ *addrlen = si->myname_len;
+
+ return 0;
+}
+
+_PUBLIC_ int swrap_getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen)
+{
+ struct socket_info *si = find_socket_info(s);
+
+ if (!si) {
+ return real_getsockopt(s, level, optname, optval, optlen);
+ }
+
+ if (level == SOL_SOCKET) {
+ return real_getsockopt(s, level, optname, optval, optlen);
+ }
+
+ errno = ENOPROTOOPT;
+ return -1;
+}
+
+_PUBLIC_ int swrap_setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen)
+{
+ struct socket_info *si = find_socket_info(s);
+
+ if (!si) {
+ return real_setsockopt(s, level, optname, optval, optlen);
+ }
+
+ if (level == SOL_SOCKET) {
+ return real_setsockopt(s, level, optname, optval, optlen);
+ }
+
+ switch (si->family) {
+ case AF_INET:
+ return 0;
+ default:
+ errno = ENOPROTOOPT;
+ return -1;
+ }
+}
+
+_PUBLIC_ ssize_t swrap_recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen)
+{
+ struct sockaddr_un un_addr;
+ socklen_t un_addrlen = sizeof(un_addr);
+ int ret;
+ struct socket_info *si = find_socket_info(s);
+
+ if (!si) {
+ return real_recvfrom(s, buf, len, flags, from, fromlen);
+ }
+
+ /* irix 6.4 forgets to null terminate the sun_path string :-( */
+ memset(&un_addr, 0, sizeof(un_addr));
+ ret = real_recvfrom(s, buf, len, flags, (struct sockaddr *)&un_addr, &un_addrlen);
+ if (ret == -1)
+ return ret;
+
+ if (sockaddr_convert_from_un(si, &un_addr, un_addrlen,
+ si->family, from, fromlen) == -1) {
+ return -1;
+ }
+
+ swrap_dump_packet(si, from, SWRAP_RECVFROM, buf, ret);
+
+ return ret;
+}
+
+
+_PUBLIC_ ssize_t swrap_sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen)
+{
+ struct sockaddr_un un_addr;
+ int ret;
+ struct socket_info *si = find_socket_info(s);
+ int bcast = 0;
+
+ if (!si) {
+ return real_sendto(s, buf, len, flags, to, tolen);
+ }
+
+ switch (si->type) {
+ case SOCK_STREAM:
+ ret = real_send(s, buf, len, flags);
+ break;
+ case SOCK_DGRAM:
+ if (si->bound == 0) {
+ ret = swrap_auto_bind(si);
+ if (ret == -1) return -1;
+ }
+
+ ret = sockaddr_convert_to_un(si, to, tolen, &un_addr, 0, &bcast);
+ if (ret == -1) return -1;
+
+ if (bcast) {
+ struct stat st;
+ unsigned int iface;
+ unsigned int prt = ntohs(((const struct sockaddr_in *)to)->sin_port);
+ char type;
+
+ type = SOCKET_TYPE_CHAR_UDP;
+
+ for(iface=0; iface <= MAX_WRAPPED_INTERFACES; iface++) {
+ snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s/"SOCKET_FORMAT,
+ socket_wrapper_dir(), type, iface, prt);
+ if (stat(un_addr.sun_path, &st) != 0) continue;
+
+ /* ignore the any errors in broadcast sends */
+ real_sendto(s, buf, len, flags, (struct sockaddr *)&un_addr, sizeof(un_addr));
+ }
+
+ swrap_dump_packet(si, to, SWRAP_SENDTO, buf, len);
+
+ return len;
+ }
+
+ ret = real_sendto(s, buf, len, flags, (struct sockaddr *)&un_addr, sizeof(un_addr));
+ break;
+ default:
+ ret = -1;
+ errno = EHOSTUNREACH;
+ break;
+ }
+
+ /* to give better errors */
+ if (ret == -1 && errno == ENOENT) {
+ errno = EHOSTUNREACH;
+ }
+
+ if (ret == -1) {
+ swrap_dump_packet(si, to, SWRAP_SENDTO, buf, len);
+ swrap_dump_packet(si, to, SWRAP_SENDTO_UNREACH, buf, len);
+ } else {
+ swrap_dump_packet(si, to, SWRAP_SENDTO, buf, ret);
+ }
+
+ return ret;
+}
+
+_PUBLIC_ int swrap_ioctl(int s, int r, void *p)
+{
+ int ret;
+ struct socket_info *si = find_socket_info(s);
+ int value;
+
+ if (!si) {
+ return real_ioctl(s, r, p);
+ }
+
+ ret = real_ioctl(s, r, p);
+
+ switch (r) {
+ case FIONREAD:
+ value = *((int *)p);
+ if (ret == -1 && errno != EAGAIN && errno != ENOBUFS) {
+ swrap_dump_packet(si, NULL, SWRAP_PENDING_RST, NULL, 0);
+ } else if (value == 0) { /* END OF FILE */
+ swrap_dump_packet(si, NULL, SWRAP_PENDING_RST, NULL, 0);
+ }
+ break;
+ }
+
+ return ret;
+}
+
+_PUBLIC_ ssize_t swrap_recv(int s, void *buf, size_t len, int flags)
+{
+ int ret;
+ struct socket_info *si = find_socket_info(s);
+
+ if (!si) {
+ return real_recv(s, buf, len, flags);
+ }
+
+ ret = real_recv(s, buf, len, flags);
+ if (ret == -1 && errno != EAGAIN && errno != ENOBUFS) {
+ swrap_dump_packet(si, NULL, SWRAP_RECV_RST, NULL, 0);
+ } else if (ret == 0) { /* END OF FILE */
+ swrap_dump_packet(si, NULL, SWRAP_RECV_RST, NULL, 0);
+ } else {
+ swrap_dump_packet(si, NULL, SWRAP_RECV, buf, ret);
+ }
+
+ return ret;
+}
+
+
+_PUBLIC_ ssize_t swrap_send(int s, const void *buf, size_t len, int flags)
+{
+ int ret;
+ struct socket_info *si = find_socket_info(s);
+
+ if (!si) {
+ return real_send(s, buf, len, flags);
+ }
+
+ ret = real_send(s, buf, len, flags);
+
+ if (ret == -1) {
+ swrap_dump_packet(si, NULL, SWRAP_SEND, buf, len);
+ swrap_dump_packet(si, NULL, SWRAP_SEND_RST, NULL, 0);
+ } else {
+ swrap_dump_packet(si, NULL, SWRAP_SEND, buf, ret);
+ }
+
+ return ret;
+}
+
+_PUBLIC_ int swrap_close(int fd)
+{
+ struct socket_info *si = find_socket_info(fd);
+ int ret;
+
+ if (!si) {
+ return real_close(fd);
+ }
+
+ SWRAP_DLIST_REMOVE(sockets, si);
+
+ if (si->myname && si->peername) {
+ swrap_dump_packet(si, NULL, SWRAP_CLOSE_SEND, NULL, 0);
+ }
+
+ ret = real_close(fd);
+
+ if (si->myname && si->peername) {
+ swrap_dump_packet(si, NULL, SWRAP_CLOSE_RECV, NULL, 0);
+ swrap_dump_packet(si, NULL, SWRAP_CLOSE_ACK, NULL, 0);
+ }
+
+ if (si->path) free(si->path);
+ if (si->myname) free(si->myname);
+ if (si->peername) free(si->peername);
+ if (si->tmp_path) {
+ unlink(si->tmp_path);
+ free(si->tmp_path);
+ }
+ free(si);
+
+ return ret;
+}
+
+static int
+dup_internal(const struct socket_info *si_oldd, int fd)
+{
+ struct socket_info *si_newd;
+
+ si_newd = (struct socket_info *)calloc(1, sizeof(struct socket_info));
+
+ si_newd->fd = fd;
+
+ si_newd->family = si_oldd->family;
+ si_newd->type = si_oldd->type;
+ si_newd->protocol = si_oldd->protocol;
+ si_newd->bound = si_oldd->bound;
+ si_newd->bcast = si_oldd->bcast;
+ if (si_oldd->path)
+ si_newd->path = strdup(si_oldd->path);
+ if (si_oldd->tmp_path)
+ si_newd->tmp_path = strdup(si_oldd->tmp_path);
+ si_newd->myname =
+ sockaddr_dup(si_oldd->myname, si_oldd->myname_len);
+ si_newd->myname_len = si_oldd->myname_len;
+ si_newd->peername =
+ sockaddr_dup(si_oldd->peername, si_oldd->peername_len);
+ si_newd->peername_len = si_oldd->peername_len;
+
+ si_newd->io = si_oldd->io;
+
+ SWRAP_DLIST_ADD(sockets, si_newd);
+
+ return fd;
+}
+
+
+_PUBLIC_ int swrap_dup(int oldd)
+{
+ struct socket_info *si;
+ int fd;
+
+ si = find_socket_info(oldd);
+ if (si == NULL)
+ return real_dup(oldd);
+
+ fd = real_dup(si->fd);
+ if (fd < 0)
+ return fd;
+
+ return dup_internal(si, fd);
+}
+
+
+_PUBLIC_ int swrap_dup2(int oldd, int newd)
+{
+ struct socket_info *si_newd, *si_oldd;
+ int fd;
+
+ if (newd == oldd)
+ return newd;
+
+ si_oldd = find_socket_info(oldd);
+ si_newd = find_socket_info(newd);
+
+ if (si_oldd == NULL && si_newd == NULL)
+ return real_dup2(oldd, newd);
+
+ fd = real_dup2(si_oldd->fd, newd);
+ if (fd < 0)
+ return fd;
+
+ /* close new socket first */
+ if (si_newd)
+ swrap_close(newd);
+
+ return dup_internal(si_oldd, fd);
+}
diff --git a/third_party/heimdal/lib/roken/socket_wrapper.h b/third_party/heimdal/lib/roken/socket_wrapper.h
new file mode 100644
index 0000000..06fd633
--- /dev/null
+++ b/third_party/heimdal/lib/roken/socket_wrapper.h
@@ -0,0 +1,146 @@
+/*
+ * Copyright (C) Jelmer Vernooij 2005 <jelmer@samba.org>
+ * Copyright (C) Stefan Metzmacher 2006 <metze@samba.org>
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the author nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+
+#ifndef __SOCKET_WRAPPER_H__
+#define __SOCKET_WRAPPER_H__
+
+int swrap_socket(int family, int type, int protocol);
+int swrap_accept(int s, struct sockaddr *addr, socklen_t *addrlen);
+int swrap_connect(int s, const struct sockaddr *serv_addr, socklen_t addrlen);
+int swrap_bind(int s, const struct sockaddr *myaddr, socklen_t addrlen);
+int swrap_listen(int s, int backlog);
+int swrap_getpeername(int s, struct sockaddr *name, socklen_t *addrlen);
+int swrap_getsockname(int s, struct sockaddr *name, socklen_t *addrlen);
+int swrap_getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen);
+int swrap_setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen);
+ssize_t swrap_recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen);
+ssize_t swrap_sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen);
+int swrap_ioctl(int s, int req, void *ptr);
+ssize_t swrap_recv(int s, void *buf, size_t len, int flags);
+ssize_t swrap_send(int s, const void *buf, size_t len, int flags);
+int swrap_close(int);
+int swrap_dup(int);
+int swrap_dup2(int, int);
+
+#ifdef SOCKET_WRAPPER_REPLACE
+
+#ifdef accept
+#undef accept
+#endif
+#define accept(s,addr,addrlen) swrap_accept(s,addr,addrlen)
+
+#ifdef connect
+#undef connect
+#endif
+#define connect(s,serv_addr,addrlen) swrap_connect(s,serv_addr,addrlen)
+
+#ifdef bind
+#undef bind
+#endif
+#define bind(s,myaddr,addrlen) swrap_bind(s,myaddr,addrlen)
+
+#ifdef listen
+#undef listen
+#endif
+#define listen(s,blog) swrap_listen(s,blog)
+
+#ifdef getpeername
+#undef getpeername
+#endif
+#define getpeername(s,name,addrlen) swrap_getpeername(s,name,addrlen)
+
+#ifdef getsockname
+#undef getsockname
+#endif
+#define getsockname(s,name,addrlen) swrap_getsockname(s,name,addrlen)
+
+#ifdef getsockopt
+#undef getsockopt
+#endif
+#define getsockopt(s,level,optname,optval,optlen) swrap_getsockopt(s,level,optname,optval,optlen)
+
+#ifdef setsockopt
+#undef setsockopt
+#endif
+#define setsockopt(s,level,optname,optval,optlen) swrap_setsockopt(s,level,optname,optval,optlen)
+
+#ifdef recvfrom
+#undef recvfrom
+#endif
+#define recvfrom(s,buf,len,flags,from,fromlen) swrap_recvfrom(s,buf,len,flags,from,fromlen)
+
+#ifdef sendto
+#undef sendto
+#endif
+#define sendto(s,buf,len,flags,to,tolen) swrap_sendto(s,buf,len,flags,to,tolen)
+
+#ifdef ioctl
+#undef ioctl
+#endif
+#define ioctl(s,req,ptr) swrap_ioctl(s,req,ptr)
+
+#ifdef recv
+#undef recv
+#endif
+#define recv(s,buf,len,flags) swrap_recv(s,buf,len,flags)
+
+#ifdef send
+#undef send
+#endif
+#define send(s,buf,len,flags) swrap_send(s,buf,len,flags)
+
+#ifdef socket
+#undef socket
+#endif
+#define socket(domain,type,protocol) swrap_socket(domain,type,protocol)
+
+#ifdef close
+#undef close
+#endif
+#define close(s) swrap_close(s)
+
+#ifdef dup
+#undef dup
+#endif
+#define dup(oldd) swrap_dup(oldd)
+
+#ifdef dup2
+#undef dup2
+#endif
+#define dup2(oldd, newd) swrap_dup2(oldd, newd)
+
+#endif
+
+#endif /* __SOCKET_WRAPPER_H__ */
diff --git a/third_party/heimdal/lib/roken/sockstartup_w32.c b/third_party/heimdal/lib/roken/sockstartup_w32.c
new file mode 100644
index 0000000..35eb3ae
--- /dev/null
+++ b/third_party/heimdal/lib/roken/sockstartup_w32.c
@@ -0,0 +1,75 @@
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include<config.h>
+
+#include <roken.h>
+
+#ifndef _WIN32
+#error Only implemented for Windows
+#endif
+
+volatile LONG _startup_count = 0;
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_WSAStartup(void)
+{
+ WSADATA wsad;
+
+ if (!WSAStartup( MAKEWORD(2, 2), &wsad )) {
+ if (wsad.wVersion != MAKEWORD(2, 2)) {
+ /* huh? We can't use 2.2? */
+ WSACleanup();
+ return -1;
+ }
+
+ InterlockedIncrement(&_startup_count);
+ return 0;
+ }
+
+ return -1;
+}
+
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_WSACleanup(void)
+{
+ LONG l;
+
+ if ((l = InterlockedDecrement(&_startup_count)) < 0) {
+ l = InterlockedIncrement(&_startup_count) - 1;
+ }
+
+ if (l >= 0) {
+ return WSACleanup();
+ }
+ return -1;
+}
diff --git a/third_party/heimdal/lib/roken/stdbool.hin b/third_party/heimdal/lib/roken/stdbool.hin
new file mode 100644
index 0000000..cdaee5b
--- /dev/null
+++ b/third_party/heimdal/lib/roken/stdbool.hin
@@ -0,0 +1,13 @@
+#ifndef _STDBOOL_H
+#define _STDBOOL_H
+
+#ifndef __GNUC__
+typedef int _Bool;
+#endif
+
+#define bool _Bool
+#define true 1
+#define false 0
+#define __bool_true_false_are_defined 1
+
+#endif /* _STDBOOL_H */
diff --git a/third_party/heimdal/lib/roken/stdint.hin b/third_party/heimdal/lib/roken/stdint.hin
new file mode 100644
index 0000000..e552d9d
--- /dev/null
+++ b/third_party/heimdal/lib/roken/stdint.hin
@@ -0,0 +1,43 @@
+#ifndef _STDINT_H
+#define _STDINT_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef signed char int8_t;
+typedef unsigned char uint8_t;
+typedef short int int16_t;
+typedef unsigned short int uint16_t;
+typedef int int32_t;
+typedef unsigned int uint32_t;
+#ifdef _MSC_VER
+typedef __int64 int64_t;
+typedef unsigned __int64 uint64_t;
+#else
+typedef long long int64_t;
+typedef unsigned long long uint64_t;
+#endif
+
+#ifdef _MSC_VER
+#include <intsafe.h>
+#else
+#define INT8_MAX 0x7F
+#define INT8_MIN (-INT8_MAX - 1)
+#define UINT8_MAX 0xFF
+#define INT16_MAX 0x7FFF
+#define INT16_MIN (-INT16_MAX - 1)
+#define UINT16_MAX 0xFFFF
+#define INT32_MAX 0x7FFFFFFF
+#define INT32_MIN (-INT32_MIN - 1)
+#define UINT32_MAX 0xFFFFFFFF
+#define INT64_MAX 0x7FFFFFFFFFFFFFFFLL
+#define INT64_MIN (-INT64_MAX - 1)
+#define UINT64_MAX 0xFFFFFFFFFFFFFFFFLL
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _STDINT_H */
diff --git a/third_party/heimdal/lib/roken/strcasecmp.c b/third_party/heimdal/lib/roken/strcasecmp.c
new file mode 100644
index 0000000..00a0a8e
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strcasecmp.c
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <string.h>
+#include <ctype.h>
+#include <stddef.h>
+#include "roken.h"
+
+#ifndef HAVE_STRCASECMP
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+strcasecmp(const char *s1, const char *s2)
+{
+ while(toupper((unsigned char)*s1) == toupper((unsigned char)*s2)) {
+ if(*s1 == '\0')
+ return 0;
+ s1++;
+ s2++;
+ }
+ return toupper((unsigned char)*s1) - toupper((unsigned char)*s2);
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/strcollect.c b/third_party/heimdal/lib/roken/strcollect.c
new file mode 100644
index 0000000..0afc3f0
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strcollect.c
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 1998, 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include "roken.h"
+
+enum { initial = 10, increment = 5 };
+
+static char **
+sub (char **argv, int i, int argc, va_list *ap)
+{
+ do {
+ if(i == argc) {
+ /* realloc argv */
+ char **tmp = realloc(argv, (argc + increment) * sizeof(*argv));
+ if(tmp == NULL) {
+ free(argv);
+ errno = ENOMEM;
+ return NULL;
+ }
+ argv = tmp;
+ argc += increment;
+ }
+ argv[i++] = va_arg(*ap, char*);
+ } while(argv[i - 1] != NULL);
+ return argv;
+}
+
+/*
+ * return a malloced vector of pointers to the strings in `ap'
+ * terminated by NULL.
+ */
+
+ROKEN_LIB_FUNCTION char ** ROKEN_LIB_CALL
+vstrcollect(va_list *ap)
+{
+ return sub (NULL, 0, 0, ap);
+}
+
+/*
+ *
+ */
+
+ROKEN_LIB_FUNCTION char ** ROKEN_LIB_CALL
+strcollect(char *first, ...)
+{
+ va_list ap;
+ char **ret = malloc (initial * sizeof(char *));
+
+ if (ret == NULL)
+ return ret;
+
+ ret[0] = first;
+ va_start(ap, first);
+ ret = sub (ret, 1, initial, &ap);
+ va_end(ap);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/strdup.c b/third_party/heimdal/lib/roken/strdup.c
new file mode 100644
index 0000000..ce00456
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strdup.c
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifndef HAVE_STRDUP
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+strdup(const char *old)
+{
+ char *t = malloc(strlen(old)+1);
+ if (t != 0)
+ strcpy(t, old);
+ return t;
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/strerror.c b/third_party/heimdal/lib/roken/strerror.c
new file mode 100644
index 0000000..b5ec691
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strerror.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+extern int sys_nerr;
+extern char *sys_errlist[];
+
+ROKEN_LIB_FUNCTION char* ROKEN_LIB_CALL
+strerror(int eno)
+{
+ static char emsg[1024];
+
+ if(eno < 0 || eno >= sys_nerr)
+ snprintf(emsg, sizeof(emsg), "Error %d occurred.", eno);
+ else
+ snprintf(emsg, sizeof(emsg), "%s", sys_errlist[eno]);
+
+ return emsg;
+}
diff --git a/third_party/heimdal/lib/roken/strerror_r.c b/third_party/heimdal/lib/roken/strerror_r.c
new file mode 100644
index 0000000..85271ec
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strerror_r.c
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#if (!defined(HAVE_STRERROR_R) && !defined(strerror_r)) || (!defined(STRERROR_R_PROTO_COMPATIBLE) && defined(HAVE_STRERROR_R))
+
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include "roken.h"
+
+#ifdef _MSC_VER
+
+int ROKEN_LIB_FUNCTION
+rk_strerror_r(int eno, char * strerrbuf, size_t buflen)
+{
+ errno_t err;
+
+ err = strerror_s(strerrbuf, buflen, eno);
+ if (err != 0) {
+ int code;
+ code = sprintf_s(strerrbuf, buflen, "Error % occurred.", eno);
+ err = ((code != 0)? errno : 0);
+ }
+
+ return err;
+}
+
+#else /* _MSC_VER */
+
+int ROKEN_LIB_FUNCTION
+rk_strerror_r(int eno, char *strerrbuf, size_t buflen)
+{
+ /* Assume is the linux broken strerror_r (returns the a buffer (char *) if the input buffer wasn't use */
+#ifdef HAVE_STRERROR_R
+ const char *str;
+ str = strerror_r(eno, strerrbuf, buflen);
+ if (str != strerrbuf)
+ if (strlcpy(strerrbuf, str, buflen) >= buflen)
+ return ERANGE;
+ return 0;
+#else
+ int ret;
+ ret = strlcpy(strerrbuf, strerror(eno), buflen);
+ if (ret > buflen)
+ return ERANGE;
+ return 0;
+#endif
+}
+
+#endif /* !_MSC_VER */
+
+#endif
diff --git a/third_party/heimdal/lib/roken/strftime.c b/third_party/heimdal/lib/roken/strftime.c
new file mode 100644
index 0000000..9a951dd
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strftime.c
@@ -0,0 +1,402 @@
+/*
+ * Copyright (c) 1999 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include <config.h>
+#include "roken.h"
+#ifdef TEST_STRPFTIME
+#include "strpftime-test.h"
+#endif
+
+#if defined(_WIN32)
+# define timezone _timezone
+# define tzname _tzname
+#endif
+
+static const char *abb_weekdays[] = {
+ "Sun",
+ "Mon",
+ "Tue",
+ "Wed",
+ "Thu",
+ "Fri",
+ "Sat",
+};
+
+static const char *full_weekdays[] = {
+ "Sunday",
+ "Monday",
+ "Tuesday",
+ "Wednesday",
+ "Thursday",
+ "Friday",
+ "Saturday",
+};
+
+static const char *abb_month[] = {
+ "Jan",
+ "Feb",
+ "Mar",
+ "Apr",
+ "May",
+ "Jun",
+ "Jul",
+ "Aug",
+ "Sep",
+ "Oct",
+ "Nov",
+ "Dec"
+};
+
+static const char *full_month[] = {
+ "January",
+ "February",
+ "Mars",
+ "April",
+ "May",
+ "June",
+ "July",
+ "August",
+ "September",
+ "October",
+ "November",
+ "December"
+};
+
+static const char *ampm[] = {
+ "AM",
+ "PM"
+};
+
+/*
+ * Convert hour in [0, 24] to [12 1 - 11 12 1 - 11 12]
+ */
+
+static int
+hour_24to12 (int hour)
+{
+ int ret = hour % 12;
+
+ if (ret == 0)
+ ret = 12;
+ return ret;
+}
+
+/*
+ * Return AM or PM for `hour'
+ */
+
+static const char *
+hour_to_ampm (int hour)
+{
+ return ampm[hour / 12];
+}
+
+/*
+ * Return the week number of `tm' (Sunday being the first day of the week)
+ * as [0, 53]
+ */
+
+static int
+week_number_sun (const struct tm *tm)
+{
+ return (tm->tm_yday + 7 - (tm->tm_yday % 7 - tm->tm_wday + 7) % 7) / 7;
+}
+
+/*
+ * Return the week number of `tm' (Monday being the first day of the week)
+ * as [0, 53]
+ */
+
+static int
+week_number_mon (const struct tm *tm)
+{
+ int wday = (tm->tm_wday + 6) % 7;
+
+ return (tm->tm_yday + 7 - (tm->tm_yday % 7 - wday + 7) % 7) / 7;
+}
+
+/*
+ * Return the week number of `tm' (Monday being the first day of the
+ * week) as [01, 53]. Week number one is the one that has four or more
+ * days in that year.
+ */
+
+static int
+week_number_mon4 (const struct tm *tm)
+{
+ int wday = (tm->tm_wday + 6) % 7;
+ int w1day = (wday - tm->tm_yday % 7 + 7) % 7;
+ int ret;
+
+ ret = (tm->tm_yday + w1day) / 7;
+ if (w1day >= 4)
+ --ret;
+ if (ret == -1)
+ ret = 53;
+ else
+ ++ret;
+ return ret;
+}
+
+/*
+ *
+ */
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+strftime (char *buf, size_t maxsize, const char *format,
+ const struct tm *tm)
+{
+ size_t n = 0;
+ int ret;
+
+ while (*format != '\0' && n < maxsize) {
+ if (*format == '%') {
+ ++format;
+ if(*format == 'E' || *format == 'O')
+ ++format;
+ switch (*format) {
+ case 'a' :
+ ret = snprintf (buf, maxsize - n,
+ "%s", abb_weekdays[tm->tm_wday]);
+ break;
+ case 'A' :
+ ret = snprintf (buf, maxsize - n,
+ "%s", full_weekdays[tm->tm_wday]);
+ break;
+ case 'h' :
+ case 'b' :
+ ret = snprintf (buf, maxsize - n,
+ "%s", abb_month[tm->tm_mon]);
+ break;
+ case 'B' :
+ ret = snprintf (buf, maxsize - n,
+ "%s", full_month[tm->tm_mon]);
+ break;
+ case 'c' :
+ ret = snprintf (buf, maxsize - n,
+ "%d:%02d:%02d %02d:%02d:%02d",
+ tm->tm_year,
+ tm->tm_mon + 1,
+ tm->tm_mday,
+ tm->tm_hour,
+ tm->tm_min,
+ tm->tm_sec);
+ break;
+ case 'C' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d", (tm->tm_year + 1900) / 100);
+ break;
+ case 'd' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d", tm->tm_mday);
+ break;
+ case 'D' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d/%02d/%02d",
+ tm->tm_mon + 1,
+ tm->tm_mday,
+ (tm->tm_year + 1900) % 100);
+ break;
+ case 'e' :
+ ret = snprintf (buf, maxsize - n,
+ "%2d", tm->tm_mday);
+ break;
+ case 'F':
+ ret = snprintf (buf, maxsize - n,
+ "%04d-%02d-%02d", tm->tm_year + 1900,
+ tm->tm_mon + 1, tm->tm_mday);
+ break;
+ case 'g':
+ /* last two digits of week-based year */
+ abort();
+ case 'G':
+ /* week-based year */
+ abort();
+ case 'H' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d", tm->tm_hour);
+ break;
+ case 'I' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d",
+ hour_24to12 (tm->tm_hour));
+ break;
+ case 'j' :
+ ret = snprintf (buf, maxsize - n,
+ "%03d", tm->tm_yday + 1);
+ break;
+ case 'k' :
+ ret = snprintf (buf, maxsize - n,
+ "%2d", tm->tm_hour);
+ break;
+ case 'l' :
+ ret = snprintf (buf, maxsize - n,
+ "%2d",
+ hour_24to12 (tm->tm_hour));
+ break;
+ case 'm' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d", tm->tm_mon + 1);
+ break;
+ case 'M' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d", tm->tm_min);
+ break;
+ case 'n' :
+ ret = snprintf (buf, maxsize - n, "\n");
+ break;
+ case 'p' :
+ ret = snprintf (buf, maxsize - n, "%s",
+ hour_to_ampm (tm->tm_hour));
+ break;
+ case 'r' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d:%02d:%02d %s",
+ hour_24to12 (tm->tm_hour),
+ tm->tm_min,
+ tm->tm_sec,
+ hour_to_ampm (tm->tm_hour));
+ break;
+ case 'R' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d:%02d",
+ tm->tm_hour,
+ tm->tm_min);
+ break;
+ case 's' :
+ ret = snprintf (buf, maxsize - n,
+ "%d", (int)mktime(rk_UNCONST(tm)));
+ break;
+ case 'S' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d", tm->tm_sec);
+ break;
+ case 't' :
+ ret = snprintf (buf, maxsize - n, "\t");
+ break;
+ case 'T' :
+ case 'X' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d:%02d:%02d",
+ tm->tm_hour,
+ tm->tm_min,
+ tm->tm_sec);
+ break;
+ case 'u' :
+ ret = snprintf (buf, maxsize - n,
+ "%d", (tm->tm_wday == 0) ? 7 : tm->tm_wday);
+ break;
+ case 'U' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d", week_number_sun (tm));
+ break;
+ case 'V' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d", week_number_mon4 (tm));
+ break;
+ case 'w' :
+ ret = snprintf (buf, maxsize - n,
+ "%d", tm->tm_wday);
+ break;
+ case 'W' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d", week_number_mon (tm));
+ break;
+ case 'x' :
+ ret = snprintf (buf, maxsize - n,
+ "%d:%02d:%02d",
+ tm->tm_year,
+ tm->tm_mon + 1,
+ tm->tm_mday);
+ break;
+ case 'y' :
+ ret = snprintf (buf, maxsize - n,
+ "%02d", (tm->tm_year + 1900) % 100);
+ break;
+ case 'Y' :
+ ret = snprintf (buf, maxsize - n,
+ "%d", tm->tm_year + 1900);
+ break;
+ case 'z':
+ ret = snprintf (buf, maxsize - n,
+ "%ld",
+#if defined(HAVE_STRUCT_TM_TM_GMTOFF)
+ (long)tm->tm_gmtoff
+#elif defined(HAVE_TIMEZONE)
+#ifdef HAVE_ALTZONE
+ tm->tm_isdst ?
+ (long)altzone :
+#endif
+ (long)timezone
+#else
+#error Where in timezone chaos are you?
+#endif
+ );
+ break;
+ case 'Z' :
+ ret = snprintf (buf, maxsize - n,
+ "%s",
+
+#if defined(HAVE_STRUCT_TM_TM_ZONE)
+ tm->tm_zone
+#elif defined(HAVE_TIMEZONE)
+ tzname[tm->tm_isdst]
+#else
+#error what?
+#endif
+ );
+ break;
+ case '\0' :
+ --format;
+ fallthrough;
+ case '%' :
+ ret = snprintf (buf, maxsize - n,
+ "%%");
+ break;
+ default :
+ ret = snprintf (buf, maxsize - n,
+ "%%%c", *format);
+ break;
+ }
+ if (ret < 0 || ret >= (int)(maxsize - n))
+ return 0;
+ n += ret;
+ buf += ret;
+ ++format;
+ } else {
+ *buf++ = *format++;
+ ++n;
+ }
+ }
+ *buf = '\0';
+ return n;
+}
diff --git a/third_party/heimdal/lib/roken/strlcat.c b/third_party/heimdal/lib/roken/strlcat.c
new file mode 100644
index 0000000..e8fe1b7
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strlcat.c
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 1995-2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include "roken.h"
+
+#ifndef HAVE_STRLCAT
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+strlcat (char *dst, const char *src, size_t dst_sz)
+{
+ size_t len;
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+ len = strnlen_s(dst, dst_sz);
+#elif defined(HAVE_STRNLEN)
+ len = strnlen(dst, dst_sz);
+#else
+ len = strlen(dst);
+#endif
+
+ if (dst_sz <= len)
+ /* the total size of dst is less than the string it contains;
+ this could be considered bad input, but we might as well
+ handle it */
+ return len + strlen(src);
+
+ return len + strlcpy (dst + len, src, dst_sz - len);
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/strlcpy.c b/third_party/heimdal/lib/roken/strlcpy.c
new file mode 100644
index 0000000..0fe2b97
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strlcpy.c
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 1995-2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include "roken.h"
+
+#ifndef HAVE_STRLCPY
+
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+strlcpy (char *dst, const char *src, size_t dst_cch)
+{
+ errno_t e;
+
+ if (dst_cch > 0)
+ e = strncpy_s(dst, dst_cch, src, _TRUNCATE);
+
+ return strlen (src);
+}
+
+#else
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+strlcpy (char *dst, const char *src, size_t dst_sz)
+{
+ size_t n;
+
+ for (n = 0; n < dst_sz; n++) {
+ if ((*dst++ = *src++) == '\0')
+ break;
+ }
+
+ if (n < dst_sz)
+ return n;
+ if (n > 0)
+ *(dst - 1) = '\0';
+ return n + strlen (src);
+}
+
+#endif
+
+#endif
diff --git a/third_party/heimdal/lib/roken/strlwr.c b/third_party/heimdal/lib/roken/strlwr.c
new file mode 100644
index 0000000..68bd4ed
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strlwr.c
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <string.h>
+#include <ctype.h>
+
+#include "roken.h"
+
+#ifndef HAVE_STRLWR
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+strlwr(char *str)
+{
+ char *s;
+
+ for(s = str; *s; s++)
+ *s = tolower((unsigned char)*s);
+ return str;
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/strncasecmp.c b/third_party/heimdal/lib/roken/strncasecmp.c
new file mode 100644
index 0000000..f244fb5
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strncasecmp.c
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <string.h>
+#include <ctype.h>
+#include <stddef.h>
+
+#ifndef HAVE_STRNCASECMP
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+strncasecmp(const char *s1, const char *s2, size_t n)
+{
+ while(n > 0
+ && toupper((unsigned char)*s1) == toupper((unsigned char)*s2))
+ {
+ if(*s1 == '\0')
+ return 0;
+ s1++;
+ s2++;
+ n--;
+ }
+ if(n == 0)
+ return 0;
+ return toupper((unsigned char)*s1) - toupper((unsigned char)*s2);
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/strndup.c b/third_party/heimdal/lib/roken/strndup.c
new file mode 100644
index 0000000..e67c998
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strndup.c
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 1995 - 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "roken.h"
+
+#ifndef HAVE_STRNDUP
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+strndup(const char *old, size_t sz)
+{
+ size_t len = strnlen (old, sz);
+ char *t = malloc(len + 1);
+
+ if (t != NULL) {
+ memcpy (t, old, len);
+ t[len] = '\0';
+ }
+ return t;
+}
+#endif /* HAVE_STRNDUP */
diff --git a/third_party/heimdal/lib/roken/strnlen.c b/third_party/heimdal/lib/roken/strnlen.c
new file mode 100644
index 0000000..f26cd84
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strnlen.c
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 1995 - 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+strnlen(const char *s, size_t len)
+{
+ size_t i;
+
+ for(i = 0; i < len && s[i]; i++)
+ ;
+ return i;
+}
diff --git a/third_party/heimdal/lib/roken/strpftime-test.c b/third_party/heimdal/lib/roken/strpftime-test.c
new file mode 100644
index 0000000..8524ff5
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strpftime-test.c
@@ -0,0 +1,295 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include <config.h>
+#include <roken.h>
+#ifdef TEST_STRPFTIME
+#include "strpftime-test.h"
+#endif
+
+enum { MAXSIZE = 26 };
+
+static struct testcase {
+ time_t t;
+ struct {
+ const char *format;
+ const char *result;
+ } vals[MAXSIZE];
+} tests[] = {
+ {0,
+ {
+ {"%A", "Thursday"},
+ {"%a", "Thu"},
+ {"%B", "January"},
+ {"%b", "Jan"},
+ {"%C", "19"},
+ {"%d", "01"},
+ {"%e", " 1"},
+ {"%H", "00"},
+ {"%I", "12"},
+ {"%j", "001"},
+ {"%k", " 0"},
+ {"%l", "12"},
+ {"%M", "00"},
+ {"%m", "01"},
+ {"%n", "\n"},
+ {"%p", "AM"},
+ {"%S", "00"},
+ {"%t", "\t"},
+ {"%w", "4"},
+ {"%Y", "1970"},
+ {"%y", "70"},
+ {"%U", "00"},
+ {"%W", "00"},
+ {"%V", "01"},
+ {"%%", "%"},
+ {NULL, NULL}}
+ },
+ {90000,
+ {
+ {"%A", "Friday"},
+ {"%a", "Fri"},
+ {"%B", "January"},
+ {"%b", "Jan"},
+ {"%C", "19"},
+ {"%d", "02"},
+ {"%e", " 2"},
+ {"%H", "01"},
+ {"%I", "01"},
+ {"%j", "002"},
+ {"%k", " 1"},
+ {"%l", " 1"},
+ {"%M", "00"},
+ {"%m", "01"},
+ {"%n", "\n"},
+ {"%p", "AM"},
+ {"%S", "00"},
+ {"%t", "\t"},
+ {"%w", "5"},
+ {"%Y", "1970"},
+ {"%y", "70"},
+ {"%U", "00"},
+ {"%W", "00"},
+ {"%V", "01"},
+ {"%%", "%"},
+ {NULL, NULL}
+ }
+ },
+ {216306,
+ {
+ {"%A", "Saturday"},
+ {"%a", "Sat"},
+ {"%B", "January"},
+ {"%b", "Jan"},
+ {"%C", "19"},
+ {"%d", "03"},
+ {"%e", " 3"},
+ {"%H", "12"},
+ {"%I", "12"},
+ {"%j", "003"},
+ {"%k", "12"},
+ {"%l", "12"},
+ {"%M", "05"},
+ {"%m", "01"},
+ {"%n", "\n"},
+ {"%p", "PM"},
+ {"%S", "06"},
+ {"%t", "\t"},
+ {"%w", "6"},
+ {"%Y", "1970"},
+ {"%y", "70"},
+ {"%U", "00"},
+ {"%W", "00"},
+ {"%V", "01"},
+ {"%%", "%"},
+ {NULL, NULL}
+ }
+ },
+ {259200,
+ {
+ {"%A", "Sunday"},
+ {"%a", "Sun"},
+ {"%B", "January"},
+ {"%b", "Jan"},
+ {"%C", "19"},
+ {"%d", "04"},
+ {"%e", " 4"},
+ {"%H", "00"},
+ {"%I", "12"},
+ {"%j", "004"},
+ {"%k", " 0"},
+ {"%l", "12"},
+ {"%M", "00"},
+ {"%m", "01"},
+ {"%n", "\n"},
+ {"%p", "AM"},
+ {"%S", "00"},
+ {"%t", "\t"},
+ {"%w", "0"},
+ {"%Y", "1970"},
+ {"%y", "70"},
+ {"%U", "01"},
+ {"%W", "00"},
+ {"%V", "01"},
+ {"%%", "%"},
+ {NULL, NULL}
+ }
+ },
+ {915148800,
+ {
+ {"%A", "Friday"},
+ {"%a", "Fri"},
+ {"%B", "January"},
+ {"%b", "Jan"},
+ {"%C", "19"},
+ {"%d", "01"},
+ {"%e", " 1"},
+ {"%H", "00"},
+ {"%I", "12"},
+ {"%j", "001"},
+ {"%k", " 0"},
+ {"%l", "12"},
+ {"%M", "00"},
+ {"%m", "01"},
+ {"%n", "\n"},
+ {"%p", "AM"},
+ {"%S", "00"},
+ {"%t", "\t"},
+ {"%w", "5"},
+ {"%Y", "1999"},
+ {"%y", "99"},
+ {"%U", "00"},
+ {"%W", "00"},
+ {"%V", "53"},
+ {"%%", "%"},
+ {NULL, NULL}}
+ },
+ {942161105,
+ {
+
+ {"%A", "Tuesday"},
+ {"%a", "Tue"},
+ {"%B", "November"},
+ {"%b", "Nov"},
+ {"%C", "19"},
+ {"%d", "09"},
+ {"%e", " 9"},
+ {"%H", "15"},
+ {"%I", "03"},
+ {"%j", "313"},
+ {"%k", "15"},
+ {"%l", " 3"},
+ {"%M", "25"},
+ {"%m", "11"},
+ {"%n", "\n"},
+ {"%p", "PM"},
+ {"%S", "05"},
+ {"%t", "\t"},
+ {"%w", "2"},
+ {"%Y", "1999"},
+ {"%y", "99"},
+ {"%U", "45"},
+ {"%W", "45"},
+ {"%V", "45"},
+ {"%%", "%"},
+ {NULL, NULL}
+ }
+ }
+};
+
+int
+main(int argc, char **argv)
+{
+ int i, j;
+ int ret = 0;
+
+ for (i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i) {
+ struct tm *tm;
+
+ tm = gmtime (&tests[i].t);
+
+ for (j = 0; tests[i].vals[j].format != NULL; ++j) {
+ char buf[128];
+ size_t len;
+ struct tm tm2;
+ char *ptr;
+
+ len = strftime (buf, sizeof(buf), tests[i].vals[j].format, tm);
+ if (len != strlen (buf)) {
+ printf ("length of strftime(\"%s\") = %lu (\"%s\")\n",
+ tests[i].vals[j].format, (unsigned long)len,
+ buf);
+ ++ret;
+ continue;
+ }
+ if (strcmp (buf, tests[i].vals[j].result) != 0) {
+ printf ("result of strftime(\"%s\") = \"%s\" != \"%s\"\n",
+ tests[i].vals[j].format, buf,
+ tests[i].vals[j].result);
+ ++ret;
+ continue;
+ }
+ memset (&tm2, 0, sizeof(tm2));
+ ptr = strptime (tests[i].vals[j].result,
+ tests[i].vals[j].format,
+ &tm2);
+ if (ptr == NULL || *ptr != '\0') {
+ printf ("bad return value from strptime("
+ "\"%s\", \"%s\")\n",
+ tests[i].vals[j].result,
+ tests[i].vals[j].format);
+ ++ret;
+ }
+ strftime (buf, sizeof(buf), tests[i].vals[j].format, &tm2);
+ if (strcmp (buf, tests[i].vals[j].result) != 0) {
+ printf ("reverse of \"%s\" failed: \"%s\" vs \"%s\"\n",
+ tests[i].vals[j].format,
+ buf, tests[i].vals[j].result);
+ ++ret;
+ }
+ }
+ }
+ {
+ struct tm tm;
+ memset(&tm, 0, sizeof(tm));
+ strptime ("200505", "%Y%m", &tm);
+ if (tm.tm_year != 105)
+ ++ret;
+ if (tm.tm_mon != 4)
+ ++ret;
+ }
+ if (ret) {
+ printf ("%d errors\n", ret);
+ return 1;
+ } else
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/strpftime-test.h b/third_party/heimdal/lib/roken/strpftime-test.h
new file mode 100644
index 0000000..157c776
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strpftime-test.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* $Id: snprintf-test.h 10377 2001-07-19 18:39:14Z assar $ */
+
+#ifndef __STRFTIME_TEST_H__
+#define __STRFTIME_TEST_H__
+
+/*
+ * we cannot use the real names of the functions when testing, since
+ * they might have different prototypes as the system functions, hence
+ * these evil hacks
+ */
+
+#ifdef strftime
+#undef strftime
+#endif
+#define strftime test_strftime
+#ifdef strptime
+#undef strptime
+#endif
+#define strptime test_strptime
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+strftime (char *buf, size_t maxsize, const char *format,
+ const struct tm *tm);
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+strptime (const char *buf, const char *format, struct tm *timeptr);
+
+#endif /* __STRFTIME_TEST_H__ */
diff --git a/third_party/heimdal/lib/roken/strpool.c b/third_party/heimdal/lib/roken/strpool.c
new file mode 100644
index 0000000..032bae1
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strpool.c
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdarg.h>
+#include <stdlib.h>
+#include "roken.h"
+
+struct rk_strpool {
+ char *str;
+ size_t len; /* strlen() of str */
+ size_t sz; /* Allocated size */
+};
+
+/*
+ *
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_strpoolfree(struct rk_strpool *p)
+{
+ if (p && p->str) {
+ free(p->str);
+ p->str = NULL;
+ }
+ free(p);
+}
+
+/*
+ *
+ */
+
+ROKEN_LIB_FUNCTION struct rk_strpool * ROKEN_LIB_CALL
+rk_strpoolprintf(struct rk_strpool *p, const char *fmt, ...)
+{
+ va_list ap;
+ char *str;
+ int len;
+
+ va_start(ap, fmt);
+ len = vasprintf(&str, fmt, ap);
+ va_end(ap);
+ if (str == NULL)
+ return rk_strpoolfree(p), NULL;
+
+ if (p == NULL) {
+ if ((p = malloc(sizeof(*p))) == NULL)
+ return free(str), NULL;
+ p->str = str;
+ p->len = p->sz = len;
+ return p;
+ } /* else grow the buffer and append `str', but don't grow too fast */
+
+ if (len + p->len + 1 > p->sz) {
+ size_t sz = p->len + len + 9 + (p->sz >> 2);
+ char *str2;
+
+ if ((str2 = realloc(p->str, sz)) == NULL)
+ return rk_strpoolfree(p), NULL;
+ p->str = str2;
+ p->sz = sz;
+ }
+ memcpy(p->str + p->len, str, len + 1);
+ p->len += len;
+ free(str);
+ return p;
+}
+
+/*
+ *
+ */
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+rk_strpoolcollect(struct rk_strpool *p)
+{
+ char *str;
+ if (p == NULL)
+ return strdup("");
+ str = p->str;
+ p->str = NULL;
+ free(p);
+ return str;
+}
diff --git a/third_party/heimdal/lib/roken/strptime.c b/third_party/heimdal/lib/roken/strptime.c
new file mode 100644
index 0000000..86216d2
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strptime.c
@@ -0,0 +1,449 @@
+/*
+ * Copyright (c) 1999, 2003, 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include <config.h>
+#include "roken.h"
+#ifdef TEST_STRPFTIME
+#include "strpftime-test.h"
+#endif
+#include <ctype.h>
+
+static const char *abb_weekdays[] = {
+ "Sun",
+ "Mon",
+ "Tue",
+ "Wed",
+ "Thu",
+ "Fri",
+ "Sat",
+ NULL
+};
+
+static const char *full_weekdays[] = {
+ "Sunday",
+ "Monday",
+ "Tuesday",
+ "Wednesday",
+ "Thursday",
+ "Friday",
+ "Saturday",
+ NULL
+};
+
+static const char *abb_month[] = {
+ "Jan",
+ "Feb",
+ "Mar",
+ "Apr",
+ "May",
+ "Jun",
+ "Jul",
+ "Aug",
+ "Sep",
+ "Oct",
+ "Nov",
+ "Dec",
+ NULL
+};
+
+static const char *full_month[] = {
+ "January",
+ "February",
+ "March",
+ "April",
+ "May",
+ "June",
+ "July",
+ "August",
+ "September",
+ "October",
+ "November",
+ "December",
+ NULL,
+};
+
+static const char *ampm[] = {
+ "am",
+ "pm",
+ NULL
+};
+
+/*
+ * Try to match `*buf' to one of the strings in `strs'. Return the
+ * index of the matching string (or -1 if none). Also advance buf.
+ */
+
+static int
+match_string (const char **buf, const char **strs)
+{
+ int i = 0;
+
+ for (i = 0; strs[i] != NULL; ++i) {
+ int len = strlen (strs[i]);
+
+ if (strncasecmp (*buf, strs[i], len) == 0) {
+ *buf += len;
+ return i;
+ }
+ }
+ return -1;
+}
+
+/*
+ * Try to match `*buf' to at the most `n' characters and return the
+ * resulting number in `num'. Returns 0 or an error. Also advance
+ * buf.
+ */
+
+static int
+parse_number (const char **buf, int n, int *num)
+{
+ char *s, *str;
+ int i;
+
+ str = malloc(n + 1);
+ if (str == NULL)
+ return -1;
+
+ /* skip whitespace */
+ for (; **buf != '\0' && isspace((unsigned char)(**buf)); (*buf)++)
+ ;
+
+ /* parse at least n characters */
+ for (i = 0; **buf != '\0' && i < n && isdigit((unsigned char)(**buf)); i++, (*buf)++)
+ str[i] = **buf;
+ str[i] = '\0';
+
+ *num = strtol (str, &s, 10);
+ free(str);
+ if (s == str)
+ return -1;
+
+ return 0;
+}
+
+/*
+ * tm_year is relative this year
+ */
+
+const int tm_year_base = 1900;
+
+/*
+ * Return TRUE iff `year' was a leap year.
+ */
+
+static int
+is_leap_year (int year)
+{
+ return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0);
+}
+
+/*
+ * Return the weekday [0,6] (0 = Sunday) of the first day of `year'
+ */
+
+static int
+first_day (int year)
+{
+ int ret = 4;
+
+ for (; year > 1970; --year)
+ ret = (ret + (is_leap_year (year) ? 366 : 365)) % 7;
+ return ret;
+}
+
+/*
+ * Set `timeptr' given `wnum' (week number [0, 53])
+ */
+
+static void
+set_week_number_sun (struct tm *timeptr, int wnum)
+{
+ int fday = first_day (timeptr->tm_year + tm_year_base);
+
+ timeptr->tm_yday = wnum * 7 + timeptr->tm_wday - fday;
+ if (timeptr->tm_yday < 0) {
+ timeptr->tm_wday = fday;
+ timeptr->tm_yday = 0;
+ }
+}
+
+/*
+ * Set `timeptr' given `wnum' (week number [0, 53])
+ */
+
+static void
+set_week_number_mon (struct tm *timeptr, int wnum)
+{
+ int fday = (first_day (timeptr->tm_year + tm_year_base) + 6) % 7;
+
+ timeptr->tm_yday = wnum * 7 + (timeptr->tm_wday + 6) % 7 - fday;
+ if (timeptr->tm_yday < 0) {
+ timeptr->tm_wday = (fday + 1) % 7;
+ timeptr->tm_yday = 0;
+ }
+}
+
+/*
+ * Set `timeptr' given `wnum' (week number [0, 53])
+ */
+
+static void
+set_week_number_mon4 (struct tm *timeptr, int wnum)
+{
+ int fday = (first_day (timeptr->tm_year + tm_year_base) + 6) % 7;
+ int offset = 0;
+
+ if (fday < 4)
+ offset += 7;
+
+ timeptr->tm_yday = offset + (wnum - 1) * 7 + timeptr->tm_wday - fday;
+ if (timeptr->tm_yday < 0) {
+ timeptr->tm_wday = fday;
+ timeptr->tm_yday = 0;
+ }
+}
+
+/*
+ *
+ */
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+strptime (const char *buf, const char *format, struct tm *timeptr)
+{
+ char c;
+
+ for (; (c = *format) != '\0'; ++format) {
+ char *s;
+ int ret;
+
+ if (isspace ((unsigned char)c)) {
+ while (isspace ((unsigned char)*buf))
+ ++buf;
+ } else if (c == '%' && format[1] != '\0') {
+ c = *++format;
+ if (c == 'E' || c == 'O')
+ c = *++format;
+ switch (c) {
+ case 'A' :
+ ret = match_string (&buf, full_weekdays);
+ if (ret < 0)
+ return NULL;
+ timeptr->tm_wday = ret;
+ break;
+ case 'a' :
+ ret = match_string (&buf, abb_weekdays);
+ if (ret < 0)
+ return NULL;
+ timeptr->tm_wday = ret;
+ break;
+ case 'B' :
+ ret = match_string (&buf, full_month);
+ if (ret < 0)
+ return NULL;
+ timeptr->tm_mon = ret;
+ break;
+ case 'b' :
+ case 'h' :
+ ret = match_string (&buf, abb_month);
+ if (ret < 0)
+ return NULL;
+ timeptr->tm_mon = ret;
+ break;
+ case 'C' :
+ if (parse_number(&buf, 2, &ret))
+ return NULL;
+ timeptr->tm_year = (ret * 100) - tm_year_base;
+ break;
+ case 'c' :
+ abort ();
+ case 'D' : /* %m/%d/%y */
+ s = strptime (buf, "%m/%d/%y", timeptr);
+ if (s == NULL)
+ return NULL;
+ buf = s;
+ break;
+ case 'd' :
+ case 'e' :
+ if (parse_number(&buf, 2, &ret))
+ return NULL;
+ timeptr->tm_mday = ret;
+ break;
+ case 'H' :
+ case 'k' :
+ if (parse_number(&buf, 2, &ret))
+ return NULL;
+ timeptr->tm_hour = ret;
+ break;
+ case 'I' :
+ case 'l' :
+ if (parse_number(&buf, 2, &ret))
+ return NULL;
+ if (ret == 12)
+ timeptr->tm_hour = 0;
+ else
+ timeptr->tm_hour = ret;
+ break;
+ case 'j' :
+ if (parse_number(&buf, 3, &ret))
+ return NULL;
+ if (ret == 0)
+ return NULL;
+ timeptr->tm_yday = ret - 1;
+ break;
+ case 'm' :
+ if (parse_number(&buf, 2, &ret))
+ return NULL;
+ if (ret == 0)
+ return NULL;
+ timeptr->tm_mon = ret - 1;
+ break;
+ case 'M' :
+ if (parse_number(&buf, 2, &ret))
+ return NULL;
+ timeptr->tm_min = ret;
+ break;
+ case 'n' :
+ while (isspace ((unsigned char)*buf))
+ buf++;
+ break;
+ case 'p' :
+ ret = match_string (&buf, ampm);
+ if (ret < 0)
+ return NULL;
+ if (timeptr->tm_hour == 0) {
+ if (ret == 1)
+ timeptr->tm_hour = 12;
+ } else
+ timeptr->tm_hour += 12;
+ break;
+ case 'r' : /* %I:%M:%S %p */
+ s = strptime (buf, "%I:%M:%S %p", timeptr);
+ if (s == NULL)
+ return NULL;
+ buf = s;
+ break;
+ case 'R' : /* %H:%M */
+ s = strptime (buf, "%H:%M", timeptr);
+ if (s == NULL)
+ return NULL;
+ buf = s;
+ break;
+ case 'S' :
+ if (parse_number(&buf, 2, &ret))
+ return NULL;
+ timeptr->tm_sec = ret;
+ break;
+ case 't' :
+ while (isspace ((unsigned char)*buf))
+ buf++;
+ break;
+ case 'T' : /* %H:%M:%S */
+ case 'X' :
+ s = strptime (buf, "%H:%M:%S", timeptr);
+ if (s == NULL)
+ return NULL;
+ buf = s;
+ break;
+ case 'u' :
+ if (parse_number(&buf, 1, &ret))
+ return NULL;
+ if (ret <= 0)
+ return NULL;
+ timeptr->tm_wday = ret - 1;
+ break;
+ case 'w' :
+ if (parse_number(&buf, 1, &ret))
+ return NULL;
+ timeptr->tm_wday = ret;
+ break;
+ case 'U' :
+ if (parse_number(&buf, 2, &ret))
+ return NULL;
+ set_week_number_sun (timeptr, ret);
+ break;
+ case 'V' :
+ if (parse_number(&buf, 2, &ret))
+ return NULL;
+ set_week_number_mon4 (timeptr, ret);
+ break;
+ case 'W' :
+ if (parse_number(&buf, 2, &ret))
+ return NULL;
+ set_week_number_mon (timeptr, ret);
+ break;
+ case 'x' :
+ s = strptime (buf, "%Y:%m:%d", timeptr);
+ if (s == NULL)
+ return NULL;
+ buf = s;
+ break;
+ case 'y' :
+ if (parse_number(&buf, 2, &ret))
+ return NULL;
+ if (ret < 70)
+ timeptr->tm_year = 100 + ret;
+ else
+ timeptr->tm_year = ret;
+ break;
+ case 'Y' :
+ if (parse_number(&buf, 4, &ret))
+ return NULL;
+ timeptr->tm_year = ret - tm_year_base;
+ break;
+ case 'Z' :
+ abort ();
+ case '\0' :
+ --format;
+ fallthrough;
+ case '%' :
+ if (*buf == '%')
+ ++buf;
+ else
+ return NULL;
+ break;
+ default :
+ if (*buf == '%' || *++buf == c)
+ ++buf;
+ else
+ return NULL;
+ break;
+ }
+ } else {
+ if (*buf == c)
+ ++buf;
+ else
+ return NULL;
+ }
+ }
+ return rk_UNCONST(buf);
+}
diff --git a/third_party/heimdal/lib/roken/strsep.c b/third_party/heimdal/lib/roken/strsep.c
new file mode 100644
index 0000000..76b447c
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strsep.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <string.h>
+
+#include "roken.h"
+
+#ifndef HAVE_STRSEP
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+strsep(char **str, const char *delim)
+{
+ char *save = *str;
+ if(*str == NULL)
+ return NULL;
+ *str = *str + strcspn(*str, delim);
+ if(**str == 0)
+ *str = NULL;
+ else{
+ **str = 0;
+ (*str)++;
+ }
+ return save;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/strsep_copy.c b/third_party/heimdal/lib/roken/strsep_copy.c
new file mode 100644
index 0000000..1228f1a
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strsep_copy.c
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2000, 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <string.h>
+
+#include "roken.h"
+
+#ifndef HAVE_STRSEP_COPY
+
+/* strsep, but with const stringp, so return string in buf */
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+strsep_copy(const char **stringp, const char *delim, char *buf, size_t len)
+{
+ const char *save = *stringp;
+ size_t l;
+ if(save == NULL)
+ return -1;
+ *stringp = *stringp + strcspn(*stringp, delim);
+ l = min(len, (size_t)(*stringp - save));
+ if(len > 0) {
+ memcpy(buf, save, l);
+ buf[l] = '\0';
+ }
+
+ l = *stringp - save;
+ if(**stringp == '\0')
+ *stringp = NULL;
+ else
+ (*stringp)++;
+ return l;
+}
+
+#endif
diff --git a/third_party/heimdal/lib/roken/strtok_r.c b/third_party/heimdal/lib/roken/strtok_r.c
new file mode 100644
index 0000000..16a9daf
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strtok_r.c
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <string.h>
+
+#include "roken.h"
+
+#ifndef HAVE_STRTOK_R
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+strtok_r(char *s1, const char *s2, char **lasts)
+{
+ char *ret;
+
+ if (s1 == NULL)
+ s1 = *lasts;
+ while(*s1 && strchr(s2, *s1))
+ ++s1;
+ if(*s1 == '\0')
+ return NULL;
+ ret = s1;
+ while(*s1 && !strchr(s2, *s1))
+ ++s1;
+ if(*s1)
+ *s1++ = '\0';
+ *lasts = s1;
+ return ret;
+}
+
+#endif /* HAVE_STRTOK_R */
diff --git a/third_party/heimdal/lib/roken/strtoll.c b/third_party/heimdal/lib/roken/strtoll.c
new file mode 100644
index 0000000..96c1b25
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strtoll.c
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Copyright (c) 2011 The FreeBSD Foundation
+ * All rights reserved.
+ * Portions of this software were developed by David Chisnall
+ * under sponsorship from the FreeBSD Foundation.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 4. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <string.h>
+
+#include "roken.h"
+
+#ifndef HAVE_STRTOLL
+
+/* #include <sys/cdefs.h> */
+
+#include <limits.h>
+#include <errno.h>
+#include <ctype.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+/*
+ * Convert a string to a long long integer.
+ *
+ * Assumes that the upper and lower case
+ * alphabets and digits are each contiguous.
+ */
+ROKEN_LIB_FUNCTION long long ROKEN_LIB_CALL
+strtoll(const char * nptr, char ** endptr, int base)
+{
+ const char *s;
+ unsigned long long acc;
+ long long ret = 0;
+ char c;
+ unsigned long long cutoff;
+ int neg, any, cutlim;
+
+ /*
+ * Skip white space and pick up leading +/- sign if any.
+ * If base is 0, allow 0x for hex and 0 for octal, else
+ * assume decimal; if base is already 16, allow 0x.
+ */
+ s = nptr;
+ do {
+ c = *s++;
+ } while (isspace((unsigned char)c));
+ if (c == '-') {
+ neg = 1;
+ c = *s++;
+ } else {
+ neg = 0;
+ if (c == '+')
+ c = *s++;
+ }
+ if ((base == 0 || base == 16) &&
+ c == '0' && (*s == 'x' || *s == 'X') &&
+ ((s[1] >= '0' && s[1] <= '9') ||
+ (s[1] >= 'A' && s[1] <= 'F') ||
+ (s[1] >= 'a' && s[1] <= 'f'))) {
+ c = s[1];
+ s += 2;
+ base = 16;
+ }
+ if (base == 0)
+ base = c == '0' ? 8 : 10;
+ acc = any = 0;
+ if (base < 2 || base > 36)
+ goto noconv;
+
+ /*
+ * Compute the cutoff value between legal numbers and illegal
+ * numbers. That is the largest legal value, divided by the
+ * base. An input number that is greater than this value, if
+ * followed by a legal input character, is too big. One that
+ * is equal to this value may be valid or not; the limit
+ * between valid and invalid numbers is then based on the last
+ * digit. For instance, if the range for quads is
+ * [-9223372036854775808..9223372036854775807] and the input base
+ * is 10, cutoff will be set to 922337203685477580 and cutlim to
+ * either 7 (neg==0) or 8 (neg==1), meaning that if we have
+ * accumulated a value > 922337203685477580, or equal but the
+ * next digit is > 7 (or 8), the number is too big, and we will
+ * return a range error.
+ *
+ * Set 'any' if any `digits' consumed; make it negative to indicate
+ * overflow.
+ */
+ cutoff = neg ? (unsigned long long)-(LLONG_MIN + LLONG_MAX) + LLONG_MAX
+ : LLONG_MAX;
+ cutlim = cutoff % base;
+ cutoff /= base;
+ for ( ; ; c = *s++) {
+ if (c >= '0' && c <= '9')
+ c -= '0';
+ else if (c >= 'A' && c <= 'Z')
+ c -= 'A' - 10;
+ else if (c >= 'a' && c <= 'z')
+ c -= 'a' - 10;
+ else
+ break;
+ if (c >= base)
+ break;
+ if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
+ any = -1;
+ else {
+ any = 1;
+ acc *= base;
+ acc += c;
+ }
+ }
+ if (any < 0) {
+ ret = neg ? LLONG_MIN : LLONG_MAX;
+ errno = ERANGE;
+ } else if (!any) {
+noconv:
+ errno = EINVAL;
+ } else if (neg) {
+ ret = -(long long)acc;
+ } else {
+ ret = acc;
+ }
+ if (endptr != NULL)
+ *endptr = (char *)(any ? s - 1 : nptr);
+ return ret;
+}
+#endif /* !HAVE_STRTOLL */
diff --git a/third_party/heimdal/lib/roken/strtoull.c b/third_party/heimdal/lib/roken/strtoull.c
new file mode 100644
index 0000000..0516e18
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strtoull.c
@@ -0,0 +1,129 @@
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Copyright (c) 2011 The FreeBSD Foundation
+ * All rights reserved.
+ * Portions of this software were developed by David Chisnall
+ * under sponsorship from the FreeBSD Foundation.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 4. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <string.h>
+
+#include "roken.h"
+
+#ifndef HAVE_STRTOULL
+
+/* #include <sys/cdefs.h> */
+
+#include <limits.h>
+#include <errno.h>
+#include <ctype.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+/*
+ * Convert a string to an unsigned long long integer.
+ *
+ * Assumes that the upper and lower case
+ * alphabets and digits are each contiguous.
+ */
+ROKEN_LIB_FUNCTION unsigned long long ROKEN_LIB_CALL
+strtoull(const char * nptr, char ** endptr, int base)
+{
+ const char *s;
+ unsigned long long acc;
+ char c;
+ unsigned long long cutoff;
+ int neg, any, cutlim;
+
+ /*
+ * See strtoq for comments as to the logic used.
+ */
+ s = nptr;
+ do {
+ c = *s++;
+ } while (isspace((unsigned char)c));
+ if (c == '-') {
+ neg = 1;
+ c = *s++;
+ } else {
+ neg = 0;
+ if (c == '+')
+ c = *s++;
+ }
+ if ((base == 0 || base == 16) &&
+ c == '0' && (*s == 'x' || *s == 'X') &&
+ ((s[1] >= '0' && s[1] <= '9') ||
+ (s[1] >= 'A' && s[1] <= 'F') ||
+ (s[1] >= 'a' && s[1] <= 'f'))) {
+ c = s[1];
+ s += 2;
+ base = 16;
+ }
+ if (base == 0)
+ base = c == '0' ? 8 : 10;
+ acc = any = 0;
+ if (base < 2 || base > 36)
+ goto noconv;
+
+ cutoff = ULLONG_MAX / base;
+ cutlim = ULLONG_MAX % base;
+ for ( ; ; c = *s++) {
+ if (c >= '0' && c <= '9')
+ c -= '0';
+ else if (c >= 'A' && c <= 'Z')
+ c -= 'A' - 10;
+ else if (c >= 'a' && c <= 'z')
+ c -= 'a' - 10;
+ else
+ break;
+ if (c >= base)
+ break;
+ if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
+ any = -1;
+ else {
+ any = 1;
+ acc *= base;
+ acc += c;
+ }
+ }
+ if (any < 0) {
+ acc = ULLONG_MAX;
+ errno = ERANGE;
+ } else if (!any) {
+noconv:
+ errno = EINVAL;
+ } else if (neg)
+ acc = -(long long)acc;
+ if (endptr != NULL)
+ *endptr = (char *)(any ? s - 1 : nptr);
+ return (acc);
+}
+#endif /* !HAVE_STRTOULL */
diff --git a/third_party/heimdal/lib/roken/strupr.c b/third_party/heimdal/lib/roken/strupr.c
new file mode 100644
index 0000000..fdff7f4
--- /dev/null
+++ b/third_party/heimdal/lib/roken/strupr.c
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include <string.h>
+#include <ctype.h>
+
+#include "roken.h"
+
+#ifndef HAVE_STRUPR
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+strupr(char *str)
+{
+ char *s;
+
+ for(s = str; *s; s++)
+ *s = toupper((unsigned char)*s);
+ return str;
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/swab.c b/third_party/heimdal/lib/roken/swab.c
new file mode 100644
index 0000000..9b8d1d1
--- /dev/null
+++ b/third_party/heimdal/lib/roken/swab.c
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include "roken.h"
+
+#ifndef HAVE_SWAB
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+swab (char *from, char *to, int nbytes)
+{
+ while(nbytes >= 2) {
+ *(to + 1) = *from;
+ *to = *(from + 1);
+ to += 2;
+ from += 2;
+ nbytes -= 2;
+ }
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/syslog.hin b/third_party/heimdal/lib/roken/syslog.hin
new file mode 100644
index 0000000..f68dd11
--- /dev/null
+++ b/third_party/heimdal/lib/roken/syslog.hin
@@ -0,0 +1,248 @@
+/*
+ * Copyright (c) 1982, 1986, 1988, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 4. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)syslog.h 8.1 (Berkeley) 6/2/93
+ */
+
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#ifndef _SYS_SYSLOG_H
+#define _SYS_SYSLOG_H 1
+
+#include <stdarg.h>
+
+/*
+ * priorities/facilities are encoded into a single 32-bit quantity, where the
+ * bottom 3 bits are the priority (0-7) and the top 28 bits are the facility
+ * (0-big number). Both the priorities and the facilities map roughly
+ * one-to-one to strings in the syslogd(8) source code. This mapping is
+ * included in this file.
+ *
+ * priorities (these are ordered)
+ */
+#define LOG_EMERG 0 /* system is unusable */
+#define LOG_ALERT 1 /* action must be taken immediately */
+#define LOG_CRIT 2 /* critical conditions */
+#define LOG_ERR 3 /* error conditions */
+#define LOG_WARNING 4 /* warning conditions */
+#define LOG_NOTICE 5 /* normal but significant condition */
+#define LOG_INFO 6 /* informational */
+#define LOG_DEBUG 7 /* debug-level messages */
+
+#define LOG_PRIMASK 0x07 /* mask to extract priority part (internal) */
+ /* extract priority */
+#define LOG_PRI(p) ((p) & LOG_PRIMASK)
+#define LOG_MAKEPRI(fac, pri) (((fac) << 3) | (pri))
+
+#ifdef SYSLOG_NAMES
+#define INTERNAL_NOPRI 0x10 /* the "no priority" priority */
+ /* mark "facility" */
+#define INTERNAL_MARK LOG_MAKEPRI(LOG_NFACILITIES, 0)
+typedef struct _code {
+ char *c_name;
+ int c_val;
+} CODE;
+
+CODE prioritynames[] =
+ {
+ { "alert", LOG_ALERT },
+ { "crit", LOG_CRIT },
+ { "debug", LOG_DEBUG },
+ { "emerg", LOG_EMERG },
+ { "err", LOG_ERR },
+ { "error", LOG_ERR }, /* DEPRECATED */
+ { "info", LOG_INFO },
+ { "none", INTERNAL_NOPRI }, /* INTERNAL */
+ { "notice", LOG_NOTICE },
+ { "panic", LOG_EMERG }, /* DEPRECATED */
+ { "warn", LOG_WARNING }, /* DEPRECATED */
+ { "warning", LOG_WARNING },
+ { NULL, -1 }
+ };
+#endif
+
+/* facility codes */
+#define LOG_KERN (0<<3) /* kernel messages */
+#define LOG_USER (1<<3) /* random user-level messages */
+#define LOG_MAIL (2<<3) /* mail system */
+#define LOG_DAEMON (3<<3) /* system daemons */
+#define LOG_AUTH (4<<3) /* security/authorization messages */
+#define LOG_SYSLOG (5<<3) /* messages generated internally by syslogd */
+#define LOG_LPR (6<<3) /* line printer subsystem */
+#define LOG_NEWS (7<<3) /* network news subsystem */
+#define LOG_UUCP (8<<3) /* UUCP subsystem */
+#define LOG_CRON (9<<3) /* clock daemon */
+#define LOG_AUTHPRIV (10<<3) /* security/authorization messages (private) */
+#define LOG_FTP (11<<3) /* ftp daemon */
+
+ /* other codes through 15 reserved for system use */
+#define LOG_LOCAL0 (16<<3) /* reserved for local use */
+#define LOG_LOCAL1 (17<<3) /* reserved for local use */
+#define LOG_LOCAL2 (18<<3) /* reserved for local use */
+#define LOG_LOCAL3 (19<<3) /* reserved for local use */
+#define LOG_LOCAL4 (20<<3) /* reserved for local use */
+#define LOG_LOCAL5 (21<<3) /* reserved for local use */
+#define LOG_LOCAL6 (22<<3) /* reserved for local use */
+#define LOG_LOCAL7 (23<<3) /* reserved for local use */
+
+#define LOG_NFACILITIES 24 /* current number of facilities */
+#define LOG_FACMASK 0x03f8 /* mask to extract facility part */
+ /* facility of pri */
+#define LOG_FAC(p) (((p) & LOG_FACMASK) >> 3)
+
+#ifdef SYSLOG_NAMES
+CODE facilitynames[] =
+ {
+ { "auth", LOG_AUTH },
+ { "authpriv", LOG_AUTHPRIV },
+ { "cron", LOG_CRON },
+ { "daemon", LOG_DAEMON },
+ { "ftp", LOG_FTP },
+ { "kern", LOG_KERN },
+ { "lpr", LOG_LPR },
+ { "mail", LOG_MAIL },
+ { "mark", INTERNAL_MARK }, /* INTERNAL */
+ { "news", LOG_NEWS },
+ { "security", LOG_AUTH }, /* DEPRECATED */
+ { "syslog", LOG_SYSLOG },
+ { "user", LOG_USER },
+ { "uucp", LOG_UUCP },
+ { "local0", LOG_LOCAL0 },
+ { "local1", LOG_LOCAL1 },
+ { "local2", LOG_LOCAL2 },
+ { "local3", LOG_LOCAL3 },
+ { "local4", LOG_LOCAL4 },
+ { "local5", LOG_LOCAL5 },
+ { "local6", LOG_LOCAL6 },
+ { "local7", LOG_LOCAL7 },
+ { NULL, -1 }
+ };
+#endif
+
+/*
+ * arguments to setlogmask.
+ */
+#define LOG_MASK(pri) (1 << (pri)) /* mask for one priority */
+#define LOG_UPTO(pri) ((1 << ((pri)+1)) - 1) /* all priorities through pri */
+
+/*
+ * Option flags for openlog.
+ *
+ * LOG_ODELAY no longer does anything.
+ * LOG_NDELAY is the inverse of what it used to be.
+ */
+#define LOG_PID 0x01 /* log the pid with each message */
+#define LOG_CONS 0x02 /* log on the console if errors in sending */
+#define LOG_ODELAY 0x04 /* delay open until first syslog() (default) */
+#define LOG_NDELAY 0x08 /* don't delay open */
+#define LOG_NOWAIT 0x10 /* don't wait for console forks: DEPRECATED */
+#define LOG_PERROR 0x20 /* log to stderr as well */
+
+#define SYSLOG_PORT 514
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Close desriptor used to write to system logger. */
+extern void closelog (void);
+
+/* Open connection to system logger. */
+extern void openlog (char *__ident, int __option, int __facility);
+
+/* Set the log mask level. */
+extern int setlogmask (int __mask);
+
+/* Generate a log message using FMT string and option arguments. */
+extern void syslog (int __pri, char *__fmt, ...);
+
+/* Generate a log message using FMT and using arguments pointed to by AP. */
+extern void vsyslog (int __pri, char *__fmt, va_list __ap);
+
+#ifdef _WIN32
+ /* Windows specific.
+
+ init_syslog() *must* be called before calling any of the above
+ functions. exit_syslog() will be scheduled using atexit().
+ However, it is not an error and encouraged to call
+ exit_syslog() before the application exits.
+
+ During operation, the application is free to call exit_syslog()
+ followed by init_syslog() to re-initialize the library. i.e. if
+ a different syslog host is to be used.
+
+ */
+
+ /* Initializes the syslog library and sets the syslog host. The
+ hostname parameter is of the form "<hostname>[:<port>]". The
+ <port> may be a numeric port or it may be a name of a service.
+ If the <port> is specified using a service name, it will be
+ looked up using getservbyname().
+
+ On failure, the hostname and port will be set to "localhost"
+ and SYSLOG_PORT respectively.
+ */
+ extern void init_syslog(const char * hostname);
+
+ extern void exit_syslog(void);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* syslog.h */
diff --git a/third_party/heimdal/lib/roken/syslogc.c b/third_party/heimdal/lib/roken/syslogc.c
new file mode 100644
index 0000000..f4fb539
--- /dev/null
+++ b/third_party/heimdal/lib/roken/syslogc.c
@@ -0,0 +1,339 @@
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+/*
+ * Based on code by Alexander Yaworsky
+ */
+
+#include <config.h>
+
+#include <roken.h>
+
+#define SYSLOG_DGRAM_SIZE 1024
+
+static BOOL syslog_opened = FALSE;
+
+static int syslog_mask = 0xFF;
+static char syslog_ident[ 128 ] = "";
+static int syslog_facility = LOG_USER;
+static char syslog_procid_str[ 20 ];
+
+static SOCKADDR_IN syslog_hostaddr;
+static SOCKET syslog_socket = INVALID_SOCKET;
+static char local_hostname[ MAX_COMPUTERNAME_LENGTH + 1 ];
+
+static char syslog_hostname[ MAX_COMPUTERNAME_LENGTH + 1 ] = "localhost";
+static unsigned short syslog_port = SYSLOG_PORT;
+
+static int datagramm_size;
+
+volatile BOOL initialized = FALSE;
+BOOL wsa_initialized = FALSE;
+CRITICAL_SECTION cs_syslog;
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+init_syslog(const char * hostname)
+{
+ WSADATA wsd;
+ char * service;
+
+ if ( initialized )
+ return;
+
+ if( WSAStartup( MAKEWORD( 2, 2 ), &wsd ) ) {
+ fprintf(stderr, "Can't initialize WinSock\n");
+ /* we let the rest of the initialization code go through,
+ although none of the syslog calls would succeed. */
+ } else {
+ wsa_initialized = TRUE;
+ }
+
+ if (hostname)
+ strcpy_s(syslog_hostname, sizeof(syslog_hostname), hostname);
+ else
+ strcpy_s(syslog_hostname, sizeof(syslog_hostname), "");
+
+ service = strchr(syslog_hostname, ':');
+
+ if (service) {
+ int tp;
+
+ *service++ = '\0';
+
+ if ((tp = atoi(service)) <= 0) {
+ struct servent * se;
+
+ se = getservbyname(service, "udp");
+
+ syslog_port = (se == NULL)? SYSLOG_PORT: se->s_port;
+ } else {
+ syslog_port = (unsigned short) tp;
+ }
+ } else {
+ syslog_port = SYSLOG_PORT;
+ }
+
+ InitializeCriticalSection(&cs_syslog);
+ initialized = TRUE;
+
+ atexit(exit_syslog);
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+exit_syslog(void)
+{
+ if ( !initialized )
+ return;
+
+ closelog();
+
+ if ( wsa_initialized )
+ WSACleanup();
+
+ DeleteCriticalSection(&cs_syslog);
+ initialized = FALSE;
+}
+
+static void init_logger_addr()
+{
+ struct hostent * phe = NULL;
+
+ memset( &syslog_hostaddr, 0, sizeof(SOCKADDR_IN) );
+ syslog_hostaddr.sin_family = AF_INET;
+
+ if (syslog_hostname[0] == '\0')
+ goto use_default;
+
+ phe = gethostbyname( syslog_hostname );
+ if( !phe )
+ goto use_default;
+
+ memcpy( &syslog_hostaddr.sin_addr.s_addr, phe->h_addr, phe->h_length );
+
+ syslog_hostaddr.sin_port = htons( syslog_port );
+ return;
+
+use_default:
+ syslog_hostaddr.sin_addr.S_un.S_addr = htonl( 0x7F000001 );
+ syslog_hostaddr.sin_port = htons( SYSLOG_PORT );
+}
+
+/******************************************************************************
+ * closelog
+ *
+ * Close desriptor used to write to system logger.
+ */
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+closelog()
+{
+ if ( !initialized )
+ return;
+
+ EnterCriticalSection(&cs_syslog);
+ if( syslog_opened ) {
+ closesocket( syslog_socket );
+ syslog_socket = INVALID_SOCKET;
+ syslog_opened = FALSE;
+ }
+ LeaveCriticalSection(&cs_syslog);
+}
+
+/******************************************************************************
+ * openlog
+ *
+ * Open connection to system logger.
+ */
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+openlog( char* ident, int option, int facility )
+{
+ BOOL failed = FALSE;
+ SOCKADDR_IN sa_local;
+ DWORD n;
+ int size;
+
+ if ( !initialized )
+ return;
+
+ EnterCriticalSection(&cs_syslog);
+
+ if( syslog_opened )
+ goto done;
+
+ failed = TRUE;
+
+ syslog_facility = facility? facility : LOG_USER;
+
+ if( option & LOG_PID )
+ sprintf_s( syslog_procid_str, sizeof(syslog_procid_str), "[%lu]", GetCurrentProcessId() );
+ else
+ syslog_procid_str[0] = '\0';
+
+ /* FIXME: handle other options */
+
+ n = sizeof(local_hostname);
+ if( !GetComputerName( local_hostname, &n ) )
+ goto done;
+
+ syslog_socket = INVALID_SOCKET;
+
+ init_logger_addr();
+
+ for( n = 0;; n++ )
+ {
+ syslog_socket = socket( AF_INET, SOCK_DGRAM, 0 );
+ if( INVALID_SOCKET == syslog_socket )
+ goto done;
+
+ memset( &sa_local, 0, sizeof(SOCKADDR_IN) );
+ sa_local.sin_family = AF_INET;
+ if( bind( syslog_socket, (SOCKADDR*) &sa_local, sizeof(SOCKADDR_IN) ) == 0 )
+ break;
+ rk_closesocket( syslog_socket );
+ syslog_socket = INVALID_SOCKET;
+ if( n == 100 )
+ goto done;
+ Sleep(0);
+ }
+
+ /* get size of datagramm */
+ size = sizeof(datagramm_size);
+ if( getsockopt( syslog_socket, SOL_SOCKET, SO_MAX_MSG_SIZE, (char*) &datagramm_size, &size ) )
+ goto done;
+ if( datagramm_size - strlen(local_hostname) - (ident? strlen(ident) : 0) < 64 )
+ goto done;
+ if( datagramm_size > SYSLOG_DGRAM_SIZE )
+ datagramm_size = SYSLOG_DGRAM_SIZE;
+
+ if (ident)
+ strcpy_s(syslog_ident, sizeof(syslog_ident), ident);
+
+ syslog_facility = (facility ? facility : LOG_USER);
+ failed = FALSE;
+
+ done:
+ if( failed ) {
+ if( syslog_socket != INVALID_SOCKET )
+ rk_closesocket( syslog_socket );
+ }
+ syslog_opened = !failed;
+
+ LeaveCriticalSection(&cs_syslog);
+}
+
+/******************************************************************************
+ * setlogmask
+ *
+ * Set the log mask level.
+ */
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+setlogmask( int mask )
+{
+ int ret;
+
+ if ( !initialized )
+ return 0;
+
+ EnterCriticalSection(&cs_syslog);
+
+ ret = syslog_mask;
+ if( mask )
+ syslog_mask = mask;
+
+ LeaveCriticalSection(&cs_syslog);
+
+ return ret;
+}
+
+/******************************************************************************
+ * syslog
+ *
+ * Generate a log message using FMT string and option arguments.
+ */
+ROKEN_LIB_FUNCTION void
+syslog( int pri, char* fmt, ... )
+{
+ va_list ap;
+
+ va_start( ap, fmt );
+ vsyslog( pri, fmt, ap );
+ va_end( ap );
+}
+
+/******************************************************************************
+ * vsyslog
+ *
+ * Generate a log message using FMT and using arguments pointed to by AP.
+ */
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+vsyslog( int pri, char* fmt, va_list ap )
+{
+ static char *month[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
+ char datagramm[ SYSLOG_DGRAM_SIZE ];
+ SYSTEMTIME stm;
+ int len;
+ char *p;
+
+ if ( !initialized )
+ return;
+
+ EnterCriticalSection(&cs_syslog);
+
+ if( !(LOG_MASK( LOG_PRI( pri )) & syslog_mask) )
+ goto done;
+
+ openlog( NULL, 0, pri & LOG_FACMASK );
+ if( !syslog_opened )
+ goto done;
+
+ if( !(pri & LOG_FACMASK) )
+ pri |= syslog_facility;
+
+ GetLocalTime( &stm );
+ len = sprintf_s( datagramm, sizeof(datagramm),
+ "<%d>%s %2d %02d:%02d:%02d %s %s%s: ",
+ pri,
+ month[ stm.wMonth - 1 ], stm.wDay, stm.wHour, stm.wMinute, stm.wSecond,
+ local_hostname, syslog_ident, syslog_procid_str );
+ vsprintf_s( datagramm + len, datagramm_size - len, fmt, ap );
+ p = strchr( datagramm, '\n' );
+ if( p )
+ *p = 0;
+ p = strchr( datagramm, '\r' );
+ if( p )
+ *p = 0;
+
+ sendto( syslog_socket, datagramm, strlen(datagramm), 0, (SOCKADDR*) &syslog_hostaddr, sizeof(SOCKADDR_IN) );
+
+ done:
+ LeaveCriticalSection(&cs_syslog);
+}
+
diff --git a/third_party/heimdal/lib/roken/test-auxval.c b/third_party/heimdal/lib/roken/test-auxval.c
new file mode 100644
index 0000000..69ab359
--- /dev/null
+++ b/third_party/heimdal/lib/roken/test-auxval.c
@@ -0,0 +1,236 @@
+/*
+ * Copyright (c) 1999 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <err.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include "roken.h"
+#include "getauxval.h"
+
+static void
+check_secure_getenv(char **env)
+{
+ size_t i;
+ char *v;
+
+ for (i = 0; env[i] != NULL; i++) {
+ if (strchr(env[i], '=') == NULL)
+ continue;
+ if ((v = strdup(env[i])) == NULL)
+ err(1, "could not allocate copy of %s", env[i]);
+ *strchr(v, '=') = '\0';
+ if (issuid() && rk_secure_getenv(v) != NULL)
+ err(1, "rk_secure_getenv() returned non-NULL when issuid()!");
+ if (!issuid() && rk_secure_getenv(v) == NULL)
+ err(1, "rk_secure_getenv() returned NULL when !issuid()");
+ free(v);
+ return;
+ }
+}
+
+static void
+inject_suid(int suid)
+{
+#if defined(AT_SECURE) || (defined(AT_EUID) && defined(AT_RUID) && defined(AT_EGID) && defined(AT_RGID))
+ auxv_t e;
+#ifdef AT_SECURE
+ unsigned long secure = suid ? 1 : 0;
+#endif
+#if defined(AT_EUID) && defined(AT_RUID) && defined(AT_EGID) && defined(AT_RGID)
+ unsigned long eid = suid ? 0 : 1000;
+
+ /* Inject real UID and GID */
+ e.a_un.a_val = 1000;
+ e.a_type = AT_UID;
+ if ((errno = rk_injectauxv(&e)) != 0)
+ err(1, "rk_injectauxv(AT_RUID) failed");
+ e.a_type = AT_GID;
+ if ((errno = rk_injectauxv(&e)) != 0)
+ err(1, "rk_injectauxv(AT_RGID) failed");
+
+ /* Inject effective UID and GID */
+ e.a_un.a_val = eid;
+ e.a_type = AT_EUID;
+ if ((errno = rk_injectauxv(&e)) != 0)
+ err(1, "rk_injectauxv(AT_EUID) failed");
+ e.a_type = AT_EGID;
+ if ((errno = rk_injectauxv(&e)) != 0)
+ err(1, "rk_injectauxv(AT_RGID) failed");
+#endif
+
+#ifdef AT_SECURE
+ e.a_un.a_val = secure;
+ e.a_type = AT_SECURE;
+ if ((errno = rk_injectauxv(&e)) != 0)
+ err(1, "rk_injectauxv(AT_SECURE) failed");
+#endif
+
+ return;
+#else
+ warnx("No ELF auxv types to inject");
+#endif
+}
+
+static
+unsigned long
+getprocauxval(unsigned long type)
+{
+ const auxv_t *e;
+
+ if ((e = rk_getauxv(type)) == NULL) {
+ errno = ENOENT;
+ return 0;
+ }
+ return e->a_un.a_val;
+}
+
+/* returns 1 if auxval type is handled specially by libc */
+static int
+is_special_auxv_p(long type)
+{
+#ifdef AT_HWCAP
+ if (type == AT_HWCAP)
+ return 1;
+#endif
+#ifdef AT_HWCAP2
+ if (type == AT_HWCAP2)
+ return 1;
+#endif
+
+ return 0;
+}
+
+int
+main(int argc, char **argv, char **env)
+{
+ unsigned long max_t = 0;
+ unsigned long a[2];
+ unsigned long v;
+ ssize_t bytes;
+ int am_suid = issuid();
+ int fd;
+
+ (void) argc;
+ (void) argv;
+
+ if (getuid() == geteuid() && getgid() == getegid()) {
+ if (issuid())
+ errx(1, "issuid() false positive? Check AT_SECURE?");
+ } else {
+ if (!issuid())
+ errx(1, "issuid() did not detect set-uid-ness!");
+ }
+
+ if ((fd = open("/proc/self/auxv", O_RDONLY)) == -1)
+ return 0;
+
+ /*
+ * Check that for every ELF auxv entry in /proc/self/auxv we
+ * find the correct answer from the rk_get*auxval() functions.
+ */
+ do {
+ bytes = read(fd, a, sizeof(a));
+ if (bytes != sizeof(a)) {
+ if (bytes == -1)
+ err(1, "Error reading from /proc/self/auxv");
+ if (bytes == 0)
+ warnx("Did not see terminator in /proc/self/auxv");
+ else
+ warnx("Partial entry in /proc/self/auxv or test interrupted");
+ (void) close(fd);
+ return 1;
+ }
+ if (a[0] > max_t)
+ max_t = a[0];
+ if (a[0] == 0) {
+ if (a[1] != 0)
+ warnx("AT_NULL with non-zero value %lu?!", a[1]);
+ continue;
+ } else if (is_special_auxv_p(a[0]))
+ continue;
+
+ errno = EACCES;
+
+ if ((v = rk_getauxval(a[0])) != a[1])
+ errx(1, "rk_getauxval(%lu) should have been %lu, was %lu",
+ a[0], a[1], v);
+ if (errno != EACCES)
+ errx(1, "rk_getauxval(%lu) did not preserve errno", a[0]);
+
+ if ((v = getprocauxval(a[0])) != a[1])
+ errx(1, "rk_getauxval(%lu) should have been %lu, was %lu",
+ a[0], a[1], v);
+ if (errno != EACCES)
+ errx(1, "rk_getauxv(%lu) did not preserve errno", a[0]);
+
+ printf("auxv type %lu -> %lu\n", a[0], a[1]);
+ } while (a[0] != 0 || a[1] != 0);
+
+ (void) close(fd);
+ if (max_t == 0) {
+ warnx("No entries in /proc/self/auxv or it is not available on this "
+ "system or this program is linked statically; cannot test "
+ "rk_getauxval()");
+ return 0;
+ }
+
+ errno = EACCES;
+ if ((v = rk_getauxval(max_t + 1)) != 0)
+ errx(1, "rk_getauxval((max_type_seen = %lu) + 1) should have been "
+ "0, was %lu", max_t, v);
+ if (errno != ENOENT)
+ errx(1, "rk_getauxval((max_type_seen = %lu) + 1) did not set "
+ "errno = ENOENT!", max_t);
+
+ errno = EACCES;
+ if ((v = getprocauxval(max_t + 1)) != 0)
+ errx(1, "rk_getauxv((max_type_seen = %lu) + 1) should have been "
+ "0, was %lu", max_t, v);
+ if (errno != ENOENT)
+ errx(1, "rk_getauxv((max_type_seen = %lu) + 1) did not set "
+ "errno = ENOENT!", max_t);
+
+ check_secure_getenv(env);
+ inject_suid(!am_suid);
+ if ((am_suid && issuid()) || (!am_suid && !issuid()))
+ errx(1, "rk_injectprocauxv() failed");
+ check_secure_getenv(env);
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/test-detach.c b/third_party/heimdal/lib/roken/test-detach.c
new file mode 100644
index 0000000..0f4636e
--- /dev/null
+++ b/third_party/heimdal/lib/roken/test-detach.c
@@ -0,0 +1,100 @@
+/***********************************************************************
+ * Copyright (c) 2015, Cryptonector LLC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include <config.h>
+
+#include <sys/types.h>
+#include <err.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <string.h>
+#ifdef WIN32
+#include <process.h>
+#ifdef getpid
+#undef getpid
+#endif
+#define getpid _getpid
+#else
+#include <unistd.h>
+#endif
+#include "roken.h"
+
+int main(int argc, char **argv)
+{
+/*
+ * XXXrcd: let's see how much further the tests get when we disable this
+ * on Windows.
+ */
+#ifndef WIN32
+ char *ends;
+ long n;
+ int fd = -1;
+ pid_t parent = getpid();
+ pid_t child;
+
+ if (argc == 2 && strcmp(argv[1], "--reexec") != 0)
+ errx(1, "Usage: test-detach [--reexec] [--daemon-child FD]");
+ if (argc == 3 || argc == 4) {
+ parent = getppid();
+ errno = 0;
+ n = strtol(argv[2], &ends, 10);
+ fd = n;
+ if (errno != 0)
+ err(1, "Usage: test-detach [--daemon-child fd]");
+ if (n < 0 || ends == NULL || *ends != '\0' || n != fd)
+ errx(1, "Usage: test-detach [--daemon-child fd]");
+ } else {
+ if (argc == 2)
+ /* Make sure we re-exec on the child-side of fork() (not WIN32) */
+ putenv("ROKEN_DETACH_USE_EXEC=1");
+ fd = roken_detach_prep(argc, argv, "--daemon-child");
+ if (fd == -1)
+ errx(1, "bad");
+ }
+ if (parent == getpid())
+ errx(1, "detach prep failed");
+ child = getpid();
+ roken_detach_finish(NULL, fd);
+ if (child != getpid())
+ errx(1, "detach finish failed");
+ /*
+ * These printfs will not appear: stderr will have been replaced
+ * with /dev/null.
+ */
+ fprintf(stderr, "Now should be the child: %ld, wrote to parent\n", (long)getpid());
+ sleep(5);
+ fprintf(stderr, "Daemon child done\n");
+ return 0;
+#else
+ return 0;
+#endif
+}
diff --git a/third_party/heimdal/lib/roken/test-getuserinfo.c b/third_party/heimdal/lib/roken/test-getuserinfo.c
new file mode 100644
index 0000000..4feae17
--- /dev/null
+++ b/third_party/heimdal/lib/roken/test-getuserinfo.c
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2017 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef WIN32
+#include <err.h>
+#endif
+#include "roken.h"
+
+static void
+print1(const char *name, const char *tabs, const char *s2)
+{
+ (void) printf("%s:%s%s\n", name, tabs, s2 ? s2 : "<NULL>");
+}
+
+int
+main(void)
+{
+ char buf[MAX_PATH * 2];
+#ifndef WIN32
+ char buf2[MAX_PATH * 2];
+ int ret = 0;
+ if (!issuid() && getuid() != 0) {
+ const char *s = NULL;
+ const char *s2 = NULL;
+
+ if (getenv("USER") != NULL && strlen(getenv("USER")) != 0 &&
+ (s = roken_get_username(buf, sizeof(buf))) == NULL) {
+ warnx("roken_get_username() returned NULL but $USER is set");
+ ret++;
+ }
+ if (getenv("USER") != NULL && strlen(getenv("USER")) != 0 && s &&
+ strcmp(getenv("USER"), s) != 0) {
+ warnx("roken_get_username() != getenv(\"USER\")");
+ ret++;
+ }
+
+ if (getenv("HOME") != NULL && strlen(getenv("HOME")) != 0 &&
+ (s = roken_get_homedir(buf, sizeof(buf))) == NULL) {
+ warnx("roken_get_homedir() returned NULL but $HOME is set");
+ ret++;
+ }
+ if (getenv("HOME") != NULL && strlen(getenv("HOME")) != 0 && s &&
+ strcmp(getenv("HOME"), s) != 0) {
+ warnx("roken_get_homedir() != getenv(\"HOME\")");
+ ret++;
+ }
+
+ if (getenv("HOME") != NULL && strlen(getenv("HOME")) != 0 && s &&
+ (s2 = roken_get_appdatadir(buf, sizeof(buf))) == NULL) {
+ warnx("roken_get_appdatadir() returned NULL but $HOME is set "
+ "and roken_get_homedir() returned not-NULL");
+ ret++;
+ }
+ if (getenv("HOME") != NULL && strlen(getenv("HOME")) != 0 &&
+ s && s2 && strcmp(s, s2) != 0) {
+ warnx("roken_get_homedir() != roken_get_appdatadir()");
+ ret++;
+ }
+ if (getenv("SHELL") != NULL && strlen(getenv("SHELL")) != 0 &&
+ strcmp(getenv("SHELL"), roken_get_shell(buf, sizeof(buf))) != 0) {
+ warnx("roken_get_shell() != getenv(\"SHELL\")");
+ ret++;
+ }
+ }
+#endif
+
+ print1("Username", "\t", roken_get_username(buf, sizeof(buf)));
+ print1("Loginname", "\t", roken_get_loginname(buf, sizeof(buf)));
+ print1("Home", "\t\t", roken_get_homedir(buf, sizeof(buf)));
+ print1("Appdatadir", "\t", roken_get_appdatadir(buf, sizeof(buf)));
+ print1("Shell", "\t\t", roken_get_shell(buf, sizeof(buf)));
+
+#ifndef WIN32
+ if (!issuid() && getuid() != 0) {
+ const char *s, *s2;
+
+ putenv("USER=h5lfoouser");
+ putenv("HOME=/no/such/dir/h5lfoouser");
+ putenv("SHELL=/no/such/shell");
+ if ((s = roken_get_username(buf, sizeof(buf))) == NULL ||
+ strcmp("h5lfoouser", s) != 0) {
+ warnx("roken_get_username() (%s) did not honor $USER", s);
+ ret++;
+ }
+ if ((s = roken_get_homedir(buf, sizeof(buf))) == NULL ||
+ strcmp("/no/such/dir/h5lfoouser", s) != 0) {
+ warnx("roken_get_homedir() (%s) did not honor $HOME", s);
+ ret++;
+ }
+ s = roken_get_homedir(buf, sizeof(buf));
+ s2 = roken_get_appdatadir(buf2, sizeof(buf2));
+ if (strcmp(s, s2) != 0) {
+ warnx("roken_get_homedir() != roken_get_appdatadir() (%s)",
+ roken_get_appdatadir(buf, sizeof(buf)));
+ ret++;
+ }
+ if ((s = roken_get_shell(buf, sizeof(buf))) == NULL ||
+ strcmp("/no/such/shell", s) != 0) {
+ warnx("roken_get_shell() (%s) did not honor $SHELL", s);
+ ret++;
+ }
+ }
+ return ret;
+#endif
+ return 0;
+}
diff --git a/third_party/heimdal/lib/roken/test-mem.c b/third_party/heimdal/lib/roken/test-mem.c
new file mode 100644
index 0000000..5ae1017
--- /dev/null
+++ b/third_party/heimdal/lib/roken/test-mem.c
@@ -0,0 +1,215 @@
+/*
+ * Copyright (c) 1999 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifdef HAVE_SYS_MMAN_H
+#include <sys/mman.h>
+#endif
+#include <stdio.h>
+#include <string.h>
+#include <err.h>
+#include "roken.h"
+
+#include "test-mem.h"
+
+/* #undef HAVE_MMAP */
+
+struct {
+ void *start;
+ size_t size;
+ void *data_start;
+ size_t data_size;
+ enum rk_test_mem_type type;
+ int fd;
+} map;
+
+#ifdef HAVE_SIGACTION
+
+struct sigaction sa, osa;
+
+#else
+
+void (* osigh)(int);
+
+#endif
+
+char *testname;
+
+static RETSIGTYPE
+segv_handler(int sig)
+{
+ int fd;
+ ssize_t ret;
+ char msg[] = "SIGSEGV i current test: ";
+
+ fd = open("/dev/stdout", O_WRONLY, 0600);
+ if (fd >= 0) {
+ ret = write(fd, msg, sizeof(msg) - 1);
+ if (ret != -1)
+ ret = write(fd, testname, strlen(testname));
+ if (ret != -1)
+ ret = write(fd, "\n", 1);
+ close(fd);
+ }
+ _exit(1);
+}
+
+#define TESTREC() \
+ if (testname) \
+ errx(1, "test %s run recursively on %s", name, testname); \
+ testname = strdup(name); \
+ if (testname == NULL) \
+ errx(1, "malloc");
+
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+rk_test_mem_alloc(enum rk_test_mem_type type, const char *name,
+ void *buf, size_t size)
+{
+#ifndef HAVE_MMAP
+ unsigned char *p;
+
+ TESTREC();
+
+ p = malloc(size + 2);
+ if (p == NULL)
+ errx(1, "malloc");
+ map.type = type;
+ map.start = p;
+ map.size = size + 2;
+ p[0] = 0xff;
+ p[map.size-1] = 0xff;
+ map.data_start = p + 1;
+#else
+ unsigned char *p;
+ int flags, ret, fd;
+ size_t pagesize = getpagesize();
+
+ TESTREC();
+
+ map.type = type;
+
+#ifdef MAP_ANON
+ flags = MAP_ANON;
+ fd = -1;
+#else
+ flags = 0;
+ fd = open ("/dev/zero", O_RDONLY);
+ if(fd < 0)
+ err (1, "open /dev/zero");
+#endif
+ map.fd = fd;
+ flags |= MAP_PRIVATE;
+
+ map.size = size + pagesize - (size % pagesize) + pagesize * 2;
+
+ p = (unsigned char *)mmap(0, map.size, PROT_READ | PROT_WRITE,
+ flags, fd, 0);
+ if (p == (unsigned char *)MAP_FAILED)
+ err (1, "mmap");
+
+ map.start = p;
+
+ ret = mprotect ((void *)p, pagesize, 0);
+ if (ret < 0)
+ err (1, "mprotect");
+
+ ret = mprotect (p + map.size - pagesize, pagesize, 0);
+ if (ret < 0)
+ err (1, "mprotect");
+
+ switch (type) {
+ case RK_TM_OVERRUN:
+ map.data_start = p + map.size - pagesize - size;
+ break;
+ case RK_TM_UNDERRUN:
+ map.data_start = p + pagesize;
+ break;
+ default:
+ abort();
+ }
+#endif
+#ifdef HAVE_SIGACTION
+ sigemptyset (&sa.sa_mask);
+ sa.sa_flags = 0;
+#ifdef SA_RESETHAND
+ sa.sa_flags |= SA_RESETHAND;
+#endif
+ sa.sa_handler = segv_handler;
+ sigaction (SIGSEGV, &sa, &osa);
+#else
+ osigh = signal(SIGSEGV, segv_handler);
+#endif
+
+ map.data_size = size;
+ if (buf)
+ memcpy(map.data_start, buf, size);
+ return map.data_start;
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_test_mem_free(const char *map_name)
+{
+#ifndef HAVE_MMAP
+ unsigned char *p = map.start;
+
+ if (testname == NULL)
+ errx(1, "test_mem_free call on no free");
+
+ if (p[0] != 0xff)
+ errx(1, "%s: %s underrun %x\n", testname, map_name, p[0]);
+ if (p[map.size-1] != 0xff)
+ errx(1, "%s: %s overrun %x\n", testname, map_name, p[map.size - 1]);
+ free(map.start);
+#else
+ int ret;
+
+ if (testname == NULL)
+ errx(1, "test_mem_free call on no free");
+
+ ret = munmap (map.start, map.size);
+ if (ret < 0)
+ err (1, "munmap");
+ if (map.fd > 0)
+ close(map.fd);
+#endif
+ free(testname);
+ testname = NULL;
+
+#ifdef HAVE_SIGACTION
+ sigaction (SIGSEGV, &osa, NULL);
+#else
+ signal (SIGSEGV, osigh);
+#endif
+}
diff --git a/third_party/heimdal/lib/roken/test-mem.h b/third_party/heimdal/lib/roken/test-mem.h
new file mode 100644
index 0000000..4d900b4
--- /dev/null
+++ b/third_party/heimdal/lib/roken/test-mem.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 1999 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+enum rk_test_mem_type { RK_TM_OVERRUN, RK_TM_UNDERRUN };
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+ rk_test_mem_alloc(enum rk_test_mem_type, const char *, void *, size_t);
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+ rk_test_mem_free(const char *);
diff --git a/third_party/heimdal/lib/roken/test-mini_inetd.c b/third_party/heimdal/lib/roken/test-mini_inetd.c
new file mode 100644
index 0000000..7ab996a
--- /dev/null
+++ b/third_party/heimdal/lib/roken/test-mini_inetd.c
@@ -0,0 +1,371 @@
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+#include <config.h>
+#include <roken.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#define PORT 8013
+#define PORT_S "8013"
+
+char * prog = "Master";
+int is_client = 0;
+
+static int
+get_address(int flags, struct addrinfo ** ret)
+{
+ struct addrinfo ai;
+ int rv;
+
+ memset(&ai, 0, sizeof(ai));
+
+ ai.ai_flags = flags | AI_NUMERICHOST;
+ ai.ai_family = AF_INET;
+ ai.ai_socktype = SOCK_STREAM;
+ ai.ai_protocol = PF_UNSPEC;
+
+ rv = getaddrinfo("127.0.0.1", PORT_S, &ai, ret);
+ if (rv)
+ warnx("getaddrinfo: %s", gai_strerror(rv));
+ return rv;
+}
+
+static int
+get_connected_socket(rk_socket_t * s_ret)
+{
+ struct addrinfo * ai = NULL;
+ int rv = 0;
+ rk_socket_t s = rk_INVALID_SOCKET;
+
+ rv = get_address(0, &ai);
+ if (rv)
+ return rv;
+
+ s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
+ if (rk_IS_BAD_SOCKET(s)) {
+ rv = 1;
+ goto done;
+ }
+
+ rv = connect(s, ai->ai_addr, ai->ai_addrlen);
+ if (rk_IS_SOCKET_ERROR(rv))
+ goto done;
+
+ *s_ret = s;
+ s = rk_INVALID_SOCKET;
+ rv = 0;
+
+ done:
+ if (!rk_IS_BAD_SOCKET(s))
+ rk_closesocket(s);
+
+ if (ai)
+ freeaddrinfo(ai);
+
+ return (rv) ? rk_SOCK_ERRNO : 0;
+}
+
+const char * test_strings[] = {
+ "Hello",
+ "01234566789012345689012345678901234567890123456789",
+ "Another test",
+ "exit"
+};
+
+static int
+test_simple_echo_client(void)
+{
+ rk_socket_t s = rk_INVALID_SOCKET;
+ int rv;
+ char buf[81];
+ int i;
+
+ fprintf(stderr, "[%s] Getting connected socket...", getprogname());
+ rv = get_connected_socket(&s);
+ if (rv) {
+ fprintf(stderr, "\n[%s] get_connected_socket() failed (%s)\n",
+ getprogname(), strerror(rk_SOCK_ERRNO));
+ return 1;
+ }
+
+ fprintf(stderr, "[%s] done\n", getprogname());
+
+ for (i=0; i < sizeof(test_strings)/sizeof(test_strings[0]); i++) {
+ rv = send(s, test_strings[i], strlen(test_strings[i]), 0);
+ if (rk_IS_SOCKET_ERROR(rv)) {
+ fprintf(stderr, "[%s] send() failure (%s)\n",
+ getprogname(), strerror(rk_SOCK_ERRNO));
+ rk_closesocket(s);
+ return 1;
+ }
+
+ rv = recv(s, buf, sizeof(buf), 0);
+ if (rk_IS_SOCKET_ERROR(rv)) {
+ fprintf (stderr, "[%s] recv() failure (%s)\n",
+ getprogname(), strerror(rk_SOCK_ERRNO));
+ rk_closesocket(s);
+ return 1;
+ }
+
+ if (rv == 0) {
+ fprintf (stderr, "[%s] No data received\n", prog);
+ rk_closesocket(s);
+ return 1;
+ }
+
+ if (rv != strlen(test_strings[i])) {
+ fprintf (stderr, "[%s] Data length mismatch %d != %zu\n", prog, rv, strlen(test_strings[i]));
+ rk_closesocket(s);
+ return 1;
+ }
+ }
+
+ fprintf (stderr, "[%s] Done\n", prog);
+ rk_closesocket(s);
+ return 0;
+}
+
+static int
+test_simple_echo_socket(void)
+{
+ fprintf (stderr, "[%s] Process ID %d\n", prog, GetCurrentProcessId());
+ fprintf (stderr, "[%s] Starting echo test with sockets\n", prog);
+
+ if (is_client) {
+ return test_simple_echo_client();
+ } else {
+
+ rk_socket_t s = rk_INVALID_SOCKET;
+
+ fprintf (stderr, "[%s] Listening for connections...\n", prog);
+ mini_inetd(htons(PORT), &s);
+ if (rk_IS_BAD_SOCKET(s)) {
+ fprintf (stderr, "[%s] Connect failed (%s)\n",
+ getprogname(), strerror(rk_SOCK_ERRNO));
+ } else {
+ fprintf (stderr, "[%s] Connected\n", prog);
+ }
+
+ {
+ char buf[81];
+ int rv, srv;
+
+ while ((rv = recv(s, buf, sizeof(buf), 0)) != 0 && !rk_IS_SOCKET_ERROR(rv)) {
+ buf[rv] = 0;
+ fprintf(stderr, "[%s] Received [%s]\n", prog, buf);
+
+ /* simple echo */
+ srv = send(s, buf, rv, 0);
+ if (srv != rv) {
+ if (rk_IS_SOCKET_ERROR(srv))
+ fprintf(stderr, "[%s] send() error [%s]\n",
+ getprogname(), strerror(rk_SOCK_ERRNO));
+ else
+ fprintf(stderr, "[%s] send() size mismatch %d != %d",
+ getprogname(), srv, rv);
+ }
+
+ if (strcmp(buf, "exit") == 0) {
+ fprintf(stderr, "[%s] Exiting...\n", prog);
+ shutdown(s, SD_SEND);
+ rk_closesocket(s);
+ return 0;
+ }
+ }
+
+ fprintf(stderr, "[%s] recv() failed (%s)\n",
+ getprogname(),
+ strerror(rk_SOCK_ERRNO));
+ }
+
+ rk_closesocket(s);
+ }
+
+ return 1;
+}
+
+static int
+test_simple_echo(void)
+{
+ fprintf (stderr, "[%s] Starting echo test\n", prog);
+
+ if (is_client) {
+
+ return test_simple_echo_client();
+
+ } else {
+
+ fprintf (stderr, "[%s] Listening for connections...\n", prog);
+ mini_inetd(htons(PORT), NULL);
+ fprintf (stderr, "[%s] Connected\n", prog);
+
+ {
+ char buf[81];
+ while (gets(buf)) {
+ fprintf(stderr, "[%s] Received [%s]\n", prog, buf);
+
+ if (strcmp(buf, "exit") == 0)
+ return 0;
+
+ /* simple echo */
+ puts(buf);
+ }
+
+ fprintf(stderr, "[%s] gets() failed (%s)\n", prog, _strerror("gets"));
+ }
+ }
+
+ return 1;
+}
+
+static int
+do_client(void)
+{
+ int rv = 0;
+
+ if (rk_SOCK_INIT())
+ errx(1, "Failed to initialize sockets (%s)", strerror(rk_SOCK_ERRNO));
+
+ prog = "Client";
+ is_client = 1;
+
+ fprintf(stderr, "Starting client...\n");
+
+ rv = test_simple_echo_socket();
+
+ rk_SOCK_EXIT();
+
+ return rv;
+}
+
+static int
+do_server(void)
+{
+ int rv = 0;
+
+ if (rk_SOCK_INIT())
+ errx(1, "Failed to initialize sockets (%s)", strerror(rk_SOCK_ERRNO));
+
+ prog = "Server";
+
+ fprintf(stderr, "Starting server...\n");
+
+ rv = test_simple_echo_socket();
+
+ rk_SOCK_EXIT();
+
+ return rv;
+}
+
+static time_t
+wait_callback(void *p)
+{
+ return (time_t)-1;
+}
+
+static int
+do_test(char * path)
+{
+ intptr_t p_server;
+ intptr_t p_client;
+ int client_rv;
+ int server_rv;
+
+ p_server = _spawnl(_P_NOWAIT, path, path, "--server", NULL);
+ if (p_server <= 0) {
+ fprintf(stderr, "%s: %s", path, _strerror("Can't start server process"));
+ return 1;
+ }
+#ifdef _WIN32
+ /* On Windows, the _spawn*() functions return a process handle on
+ success. We need a process ID for use with
+ wait_for_process_timed(). */
+
+ p_server = GetProcessId((HANDLE) p_server);
+#endif
+ fprintf(stderr, "Created server process ID %d\n", p_server);
+
+ p_client = _spawnl(_P_NOWAIT, path, path, "--client", NULL);
+ if (p_client <= 0) {
+ fprintf(stderr, "%s: %s", path, _strerror("Can't start client process"));
+ fprintf(stderr, "Waiting for server process to terminate ...");
+ wait_for_process_timed(p_server, wait_callback, NULL, 5);
+ fprintf(stderr, "DONE\n");
+ return 1;
+ }
+#ifdef _WIN32
+ p_client = GetProcessId((HANDLE) p_client);
+#endif
+ fprintf(stderr, "Created client process ID %d\n", p_client);
+
+ fprintf(stderr, "Waiting for client process to terminate ...");
+ client_rv = wait_for_process_timed(p_client, wait_callback, NULL, 5);
+ if (SE_IS_ERROR(client_rv)) {
+ fprintf(stderr, "\nwait_for_process_timed() failed for client. rv=%d\n", client_rv);
+ } else {
+ fprintf(stderr, "DONE\n");
+ }
+
+ fprintf(stderr, "Waiting for server process to terminate ...");
+ server_rv = wait_for_process_timed(p_server, wait_callback, NULL, 5);
+ if (SE_IS_ERROR(server_rv)) {
+ fprintf(stderr, "\nwait_for_process_timed() failed for server. rv=%d\n", server_rv);
+ } else {
+ fprintf(stderr, "DONE\n");
+ }
+
+ if (client_rv == 0 && server_rv == 0) {
+ fprintf(stderr, "PASS\n");
+ return 0;
+ } else {
+ fprintf(stderr, "FAIL: Client rv=%d, Server rv=%d\n", client_rv, server_rv);
+ return 1;
+ }
+}
+
+int main(int argc, char ** argv)
+{
+ setprogname(argv[0]);
+
+ if (argc == 2 && strcmp(argv[1], "--client") == 0)
+ return do_client();
+ else if (argc == 2 && strcmp(argv[1], "--server") == 0)
+ return do_server();
+ else if (argc == 1)
+ return do_test(argv[0]);
+ else {
+ printf ("%s: Test mini_inetd() function. Run with no arguments to start test\n",
+ argv[0]);
+ return 1;
+ }
+}
diff --git a/third_party/heimdal/lib/roken/test-readenv.c b/third_party/heimdal/lib/roken/test-readenv.c
new file mode 100644
index 0000000..24a6661
--- /dev/null
+++ b/third_party/heimdal/lib/roken/test-readenv.c
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include "test-mem.h"
+
+char *s1 = "VAR1=VAL1#comment\n\
+VAR2=VAL2 VAL2 #comment\n\
+#this another comment\n\
+\n\
+VAR3=FOO";
+
+char *s2 = "VAR1=ENV2\n\
+";
+
+static void
+make_file(char *tmpl, size_t l)
+{
+ int fd;
+ strlcpy(tmpl, "env.XXXXXX", l);
+ fd = mkstemp(tmpl);
+ if(fd < 0)
+ err(1, "mkstemp");
+ close(fd);
+}
+
+static void
+write_file(const char *fn, const char *s)
+{
+ FILE *f;
+ f = fopen(fn, "w");
+ if(f == NULL) {
+ unlink(fn);
+ err(1, "fopen");
+ }
+ if(fwrite(s, 1, strlen(s), f) != strlen(s))
+ err(1, "short write");
+ if(fclose(f) != 0) {
+ unlink(fn);
+ err(1, "fclose");
+ }
+}
+
+int
+main(int argc, char **argv)
+{
+ char **env = NULL;
+ int count = 0;
+ char fn[MAXPATHLEN];
+ int error = 0;
+
+ make_file(fn, sizeof(fn));
+
+ write_file(fn, s1);
+ count = read_environment(fn, &env);
+ if(count != 3) {
+ warnx("test 1: variable count %d != 3", count);
+ error++;
+ }
+
+ write_file(fn, s2);
+ count = read_environment(fn, &env);
+ if(count != 1) {
+ warnx("test 2: variable count %d != 1", count);
+ error++;
+ }
+
+ unlink(fn);
+ count = read_environment(fn, &env);
+ if(count != 0) {
+ warnx("test 3: variable count %d != 0", count);
+ error++;
+ }
+ for(count = 0; env && env[count]; count++);
+ if(count != 3) {
+ warnx("total variable count %d != 3", count);
+ error++;
+ }
+ free_environment(env);
+
+
+ return error;
+}
diff --git a/third_party/heimdal/lib/roken/timegm.c b/third_party/heimdal/lib/roken/timegm.c
new file mode 100644
index 0000000..e6c8992
--- /dev/null
+++ b/third_party/heimdal/lib/roken/timegm.c
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 1997, 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+static int
+is_leap(unsigned y)
+{
+ y += 1900;
+ return (y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0);
+}
+
+/*
+ * XXX This is a simplifed version of timegm, it needs to support out of
+ * bounds values.
+ */
+
+time_t
+rk_timegm (struct tm *tm)
+{
+ static const unsigned ndays[2][12] ={
+ {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
+ {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
+ time_t res = 0;
+ unsigned i;
+
+ if (tm->tm_year < 0)
+ return -1;
+ if (tm->tm_mon < 0 || tm->tm_mon > 11)
+ return -1;
+ if (tm->tm_mday < 1 || tm->tm_mday > ndays[is_leap(tm->tm_year)][tm->tm_mon])
+ return -1;
+ if (tm->tm_hour < 0 || tm->tm_hour > 23)
+ return -1;
+ if (tm->tm_min < 0 || tm->tm_min > 59)
+ return -1;
+ if (tm->tm_sec < 0 || tm->tm_sec > 59)
+ return -1;
+
+ for (i = 70; i < tm->tm_year; ++i)
+ res += is_leap(i) ? 366 : 365;
+
+ for (i = 0; i < tm->tm_mon; ++i)
+ res += ndays[is_leap(tm->tm_year)][i];
+ res += tm->tm_mday - 1;
+ res *= 24;
+ res += tm->tm_hour;
+ res *= 60;
+ res += tm->tm_min;
+ res *= 60;
+ res += tm->tm_sec;
+ return res;
+}
diff --git a/third_party/heimdal/lib/roken/timeval.c b/third_party/heimdal/lib/roken/timeval.c
new file mode 100644
index 0000000..3012513
--- /dev/null
+++ b/third_party/heimdal/lib/roken/timeval.c
@@ -0,0 +1,286 @@
+/*
+ * Copyright (c) 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * Timeval stuff
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION time_t ROKEN_LIB_CALL
+rk_time_add(time_t t, time_t delta)
+{
+ if (delta == 0)
+ return t;
+
+#ifdef TIME_T_SIGNED
+ /* Signed overflow is UB in C */
+#if SIZEOF_TIME_T == 4
+ if (t >= 0 && delta > 0 && INT32_MAX - t < delta)
+ /* Time left to hit INT32_MAX is less than what we want to add */
+ return INT32_MAX;
+ else if (t == INT32_MIN && delta < 0)
+ /* Avoid computing -t when t == INT32_MIN! */
+ return INT32_MIN;
+ else if (t < 0 && delta < 0 && INT32_MIN + (-t) > delta)
+ /* Time left to hit INT32_MIN is less than what we want to subtract */
+ return INT32_MIN;
+ else
+ return t + delta;
+#elif SIZEOF_TIME_T == 8
+ if (t >= 0 && delta > 0 && INT64_MAX - t < delta)
+ return INT64_MAX;
+ else if (t == INT64_MIN && delta < 0)
+ /* Avoid computing -t when t == INT64_MIN! */
+ return INT64_MIN;
+ else if (t < 0 && delta < 0 && INT64_MIN + (-t) > delta)
+ return INT64_MIN;
+ else
+ return t + delta;
+#else
+#error "Unexpected sizeof(time_t)"
+#endif
+#else
+
+ /* Unsigned overflow is defined in C */
+#if SIZEOF_TIME_T == 4
+ if (t + delta < t)
+ return UINT32_MAX;
+#elif SIZEOF_TIME_T == 8
+ if (t + delta < t)
+ return UINT64_MAX;
+#else
+#error "Unexpected sizeof(time_t)"
+#endif
+#endif
+ return t + delta;
+}
+
+ROKEN_LIB_FUNCTION time_t ROKEN_LIB_CALL
+rk_time_sub(time_t t, time_t delta)
+{
+ if (delta == 0)
+ return t;
+#ifdef TIME_T_SIGNED
+ if (delta > 0)
+ return rk_time_add(t, -delta);
+#if SIZEOF_TIME_T == 4
+ if (delta == INT32_MIN) {
+ if (t < 0) {
+ t = t + INT32_MAX;
+ return t + 1;
+ }
+ return INT32_MAX;
+ }
+ /* Safe to compute -delta, so use rk_time_add() to add -delta */
+ return rk_time_add(t, -delta);
+#elif SIZEOF_TIME_T == 8
+ if (delta == INT64_MIN) {
+ if (t < 0) {
+ t = t + INT64_MAX;
+ return t + 1;
+ }
+ return INT64_MAX;
+ }
+ return rk_time_add(t, -delta);
+#else
+#error "Unexpected sizeof(time_t)"
+#endif
+#else
+ /* Both t and delta are non-negative. */
+ if (delta > t)
+ return 0;
+#endif
+ return t - delta;
+}
+
+/*
+ * Make `t1' consistent.
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+timevalfix(struct timeval *t1)
+{
+ if (t1->tv_usec < 0) {
+ t1->tv_sec = rk_time_sub(t1->tv_sec, 1);
+ t1->tv_usec = 1000000;
+ }
+ if (t1->tv_usec >= 1000000) {
+ t1->tv_sec = rk_time_add(t1->tv_sec, 1);
+ t1->tv_usec -= 1000000;
+ }
+}
+
+/*
+ * t1 += t2
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+timevaladd(struct timeval *t1, const struct timeval *t2)
+{
+ t1->tv_sec = rk_time_add(t1->tv_sec, t2->tv_sec);
+ t1->tv_usec += t2->tv_usec;
+ timevalfix(t1);
+}
+
+/*
+ * t1 -= t2
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+timevalsub(struct timeval *t1, const struct timeval *t2)
+{
+ t1->tv_sec = rk_time_sub(t1->tv_sec, t2->tv_sec);
+ t1->tv_usec -= t2->tv_usec;
+ timevalfix(t1);
+}
+
+#ifdef TEST
+int
+main(int argc, char **argv)
+{
+ time_t t, delta, r;
+ int e = 0;
+
+ if (argc == 0)
+ return 0; /* Apparently POSIX and Linux allow this case */
+
+ argc--;
+ argv++;
+
+ while (argc > 0) {
+ int64_t n;
+ time_t a;
+ char *ends;
+
+ if (argc < 3)
+ errx(1, "Usage: [TIME +|- DELTA [== TIME]]");
+
+ errno = 0;
+ n = strtoll(argv[0], &ends, 0);
+ if (errno)
+ err(1, "Time value is invalid");
+ if (*ends != '\0')
+ errx(1, "Time value is invalid");
+ t = n;
+
+ n = strtoll(argv[2], &ends, 0);
+ if (errno)
+ err(1, "Delta value is invalid");
+ if (*ends != '\0')
+ errx(1, "Delta value is invalid");
+ delta = n;
+
+ if (argv[1][0] == '+' && argv[1][1] == '\0')
+ r = rk_time_add(t, delta);
+ else if (argv[1][0] == '-' && argv[1][1] == '\0')
+ r = rk_time_sub(t, delta);
+ else
+ errx(1, "Operator must be a + or a - arithmetic operator");
+
+ if (delta == 0 && r != t) {
+ warnx("%s %s %s != %s!", argv[0], argv[1], argv[2], argv[0]);
+ e = 1;
+ }
+ if (t == 0 && r != delta) {
+ warnx("%s %s %s != %s!", argv[0], argv[1], argv[2], argv[2]);
+ e = 1;
+ }
+
+ if (argc > 4 && strcmp(argv[3], "==") == 0) {
+ n = strtoll(argv[4], &ends, 0);
+ if (errno)
+ err(1, "Time value is invalid");
+ if (*ends != '\0')
+ errx(1, "Time value is invalid");
+ a = n;
+ if (a != r) {
+ warnx("%s %s %s != %s!", argv[0], argv[1], argv[2], argv[4]);
+ e = 1;
+ }
+ argc -= 5;
+ argv += 5;
+ } else {
+#ifdef TIME_T_SIGNED
+ printf("%s %s %s == %lld\n", argv[0], argv[1], argv[2],
+ (long long)r);
+#else
+ printf("%s %s %s == %llu\n", argv[0], argv[1], argv[2],
+ (unsigned long long)r);
+#endif
+ argc -= 3;
+ argv += 3;
+ }
+ }
+
+#define CHECK(e) do { if (!(e)) errx(1, "Expression not true: " #e "!"); } while (0)
+#ifdef TIME_T_SIGNED
+#if SIZEOF_TIME_T == 4
+ CHECK(rk_time_add(INT32_MIN, -1) == INT32_MIN);
+ CHECK(rk_time_sub(INT32_MIN, 1) == INT32_MIN);
+ CHECK(rk_time_sub(-1, INT32_MAX) == INT32_MIN);
+ CHECK(rk_time_add(INT32_MAX, 0) == INT32_MAX);
+ CHECK(rk_time_add(INT32_MAX, 1) == INT32_MAX);
+ CHECK(rk_time_add(1, INT32_MAX) == INT32_MAX);
+ CHECK(rk_time_add(0, INT32_MAX) == INT32_MAX);
+#elif SIZEOF_TIME_T == 8
+ CHECK(rk_time_add(INT64_MIN, -1) == INT64_MIN);
+ CHECK(rk_time_sub(INT64_MIN, 1) == INT64_MIN);
+ CHECK(rk_time_sub(-1, INT64_MAX) == INT64_MIN);
+ CHECK(rk_time_add(INT64_MAX, 0) == INT64_MAX);
+ CHECK(rk_time_add(INT64_MAX, 1) == INT64_MAX);
+ CHECK(rk_time_add(1, INT64_MAX) == INT64_MAX);
+ CHECK(rk_time_add(0, INT64_MAX) == INT64_MAX);
+#endif
+ CHECK(rk_time_add(0, -1) == -1);
+ CHECK(rk_time_sub(0, 1) == -1);
+#else
+#if SIZEOF_TIME_T == 4
+ CHECK(rk_time_add(UINT32_MAX, 0) == UINT32_MAX);
+ CHECK(rk_time_add(UINT32_MAX, 1) == UINT32_MAX);
+ CHECK(rk_time_add(1, UINT32_MAX) == UINT32_MAX);
+ CHECK(rk_time_add(0, UINT32_MAX) == UINT32_MAX);
+#elif SIZEOF_TIME_T == 8
+ CHECK(rk_time_add(UINT64_MAX, 0) == UINT64_MAX);
+ CHECK(rk_time_add(UINT64_MAX, 1) == UINT64_MAX);
+ CHECK(rk_time_add(1, UINT64_MAX) == UINT64_MAX);
+ CHECK(rk_time_add(0, UINT64_MAX) == UINT64_MAX);
+#endif
+#endif
+ CHECK(rk_time_add(0, 1) == 1);
+ CHECK(rk_time_add(1, 0) == 1);
+ return e;
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/tm2time.c b/third_party/heimdal/lib/roken/tm2time.c
new file mode 100644
index 0000000..ba69a04
--- /dev/null
+++ b/third_party/heimdal/lib/roken/tm2time.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifdef TIME_WITH_SYS_TIME
+#include <sys/time.h>
+#include <time.h>
+#elif defined(HAVE_SYS_TIME_H)
+#include <sys/time.h>
+#else
+#include <time.h>
+#endif
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION time_t ROKEN_LIB_CALL
+tm2time (struct tm tm, int local)
+{
+ time_t t;
+
+ tm.tm_isdst = local ? -1 : 0;
+
+ t = mktime (&tm);
+
+ if (!local)
+ t += t - mktime (gmtime (&t));
+ return t;
+}
diff --git a/third_party/heimdal/lib/roken/tsearch-test.c b/third_party/heimdal/lib/roken/tsearch-test.c
new file mode 100644
index 0000000..b9d9963
--- /dev/null
+++ b/third_party/heimdal/lib/roken/tsearch-test.c
@@ -0,0 +1,125 @@
+/*
+ * Tree search generalized from Knuth (6.2.2) Algorithm T just like
+ * the AT&T man page says.
+ *
+ * The node_t structure is for internal use only, lint doesn't grok it.
+ *
+ * Written by reading the System V Interface Definition, not the code.
+ *
+ * Totally public domain.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include "search.h"
+
+struct node {
+ char *string;
+ int order;
+};
+
+extern void *rk_tdelete(const void *, void **,
+ int (*)(const void *, const void *));
+extern void *rk_tfind(const void *, void * const *,
+ int (*)(const void *, const void *));
+extern void *rk_tsearch(const void *, void **, int (*)(const void *, const void *));
+extern void rk_twalk(const void *, void (*)(const void *, VISIT, int));
+
+void *rootnode = NULL;
+int numerr = 0;
+
+/*
+ * This routine compares two nodes, based on an
+ * alphabetical ordering of the string field.
+ */
+int
+node_compare(const void *node1, const void *node2)
+{
+ return strcmp(((const struct node *) node1)->string,
+ ((const struct node *) node2)->string);
+}
+
+static int walkorder = -1;
+
+void
+list_node(const void *ptr, VISIT order, int level)
+{
+ const struct node *p = *(const struct node **) ptr;
+
+ if (order == postorder || order == leaf) {
+ walkorder++;
+ if (p->order != walkorder) {
+ warnx("sort failed: expected %d next, got %d\n", walkorder,
+ p->order);
+ numerr++;
+ }
+ }
+}
+
+int
+main(int argc, char **argv)
+{
+ int numtest = 1;
+ struct node *t, *p, tests[] = {
+ { "", 0 },
+ { "ab", 3 },
+ { "abc", 4 },
+ { "abcdefg", 8 },
+ { "abcd", 5 },
+ { "a", 2 },
+ { "abcdef", 7 },
+ { "abcde", 6 },
+ { "=", 1 },
+ { NULL }
+ };
+
+ for(t = tests; t->string; t++) {
+ /* Better not be there */
+ p = (struct node *)rk_tfind((void *)t, (void **)&rootnode,
+ node_compare);
+
+ if (p) {
+ warnx("erroneous list: found %d\n", p->order);
+ numerr++;
+ }
+
+ /* Put node into the tree. */
+ p = (struct node *) rk_tsearch((void *)t, (void **)&rootnode,
+ node_compare);
+
+ if (!p) {
+ warnx("erroneous list: missing %d\n", t->order);
+ numerr++;
+ }
+ }
+
+ rk_twalk(rootnode, list_node);
+
+ for(t = tests; t->string; t++) {
+ /* Better be there */
+ p = (struct node *) rk_tfind((void *)t, (void **)&rootnode,
+ node_compare);
+
+ if (!p) {
+ warnx("erroneous list: missing %d\n", t->order);
+ numerr++;
+ }
+
+ /* pull out node */
+ (void) rk_tdelete((void *)t, (void **)&rootnode,
+ node_compare);
+
+ /* Better not be there */
+ p = (struct node *) rk_tfind((void *)t, (void **)&rootnode,
+ node_compare);
+
+ if (p) {
+ warnx("erroneous list: found %d\n", p->order);
+ numerr++;
+ }
+
+ }
+
+ return numerr;
+}
diff --git a/third_party/heimdal/lib/roken/tsearch.c b/third_party/heimdal/lib/roken/tsearch.c
new file mode 100644
index 0000000..e5df846
--- /dev/null
+++ b/third_party/heimdal/lib/roken/tsearch.c
@@ -0,0 +1,175 @@
+/*
+ * Tree search generalized from Knuth (6.2.2) Algorithm T just like
+ * the AT&T man page says.
+ *
+ * The node_t structure is for internal use only, lint doesn't grok it.
+ *
+ * Written by reading the System V Interface Definition, not the code.
+ *
+ * Totally public domain.
+ *
+ * $NetBSD: tsearch.c,v 1.3 1999/09/16 11:45:37 lukem Exp $
+ * $NetBSD: twalk.c,v 1.1 1999/02/22 10:33:16 christos Exp $
+ * $NetBSD: tdelete.c,v 1.2 1999/09/16 11:45:37 lukem Exp $
+ * $NetBSD: tfind.c,v 1.2 1999/09/16 11:45:37 lukem Exp $
+ */
+
+#include <config.h>
+#include "roken.h"
+#include "search.h"
+#include <stdlib.h>
+
+typedef struct node {
+ char *key;
+ struct node *llink, *rlink;
+} node_t;
+
+/*
+ * find or insert datum into search tree
+ *
+ * Parameters:
+ * vkey: key to be located
+ * vrootp: address of tree root
+ */
+
+ROKEN_LIB_FUNCTION void *
+rk_tsearch(const void *vkey, void **vrootp,
+ int (*compar)(const void *, const void *))
+{
+ node_t *q;
+ node_t **rootp = (node_t **)vrootp;
+
+ if (rootp == NULL)
+ return NULL;
+
+ while (*rootp != NULL) { /* Knuth's T1: */
+ int r;
+
+ if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */
+ return *rootp; /* we found it! */
+
+ rootp = (r < 0) ?
+ &(*rootp)->llink : /* T3: follow left branch */
+ &(*rootp)->rlink; /* T4: follow right branch */
+ }
+
+ q = malloc(sizeof(node_t)); /* T5: key not found */
+ if (q != 0) { /* make new node */
+ *rootp = q; /* link new node to old */
+ /* LINTED const castaway ok */
+ q->key = rk_UNCONST(vkey); /* initialize new node */
+ q->llink = q->rlink = NULL;
+ }
+ return q;
+}
+
+/*
+ * Walk the nodes of a tree
+ *
+ * Parameters:
+ * root: Root of the tree to be walked
+ */
+static void
+trecurse(const node_t *root, void (*action)(const void *, VISIT, int),
+ int level)
+{
+
+ if (root->llink == NULL && root->rlink == NULL)
+ (*action)(root, leaf, level);
+ else {
+ (*action)(root, preorder, level);
+ if (root->llink != NULL)
+ trecurse(root->llink, action, level + 1);
+ (*action)(root, postorder, level);
+ if (root->rlink != NULL)
+ trecurse(root->rlink, action, level + 1);
+ (*action)(root, endorder, level);
+ }
+}
+
+/*
+ * Walk the nodes of a tree
+ *
+ * Parameters:
+ * vroot: Root of the tree to be walked
+ */
+ROKEN_LIB_FUNCTION void
+rk_twalk(const void *vroot,
+ void (*action)(const void *, VISIT, int))
+{
+ if (vroot != NULL && action != NULL)
+ trecurse(vroot, action, 0);
+}
+
+/*
+ * delete node with given key
+ *
+ * vkey: key to be deleted
+ * vrootp: address of the root of the tree
+ * compar: function to carry out node comparisons
+ */
+ROKEN_LIB_FUNCTION void *
+rk_tdelete(const void * vkey, void ** vrootp,
+ int (*compar)(const void *, const void *))
+{
+ node_t **rootp = (node_t **)vrootp;
+ node_t *q, *r;
+ int cmp;
+
+ if (rootp == NULL || *rootp == NULL)
+ return NULL;
+
+ while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0) {
+ rootp = (cmp < 0) ?
+ &(*rootp)->llink : /* follow llink branch */
+ &(*rootp)->rlink; /* follow rlink branch */
+ if (*rootp == NULL)
+ return NULL; /* key not found */
+ }
+ r = (*rootp)->rlink; /* D1: */
+ if ((q = (*rootp)->llink) == NULL) /* Left NULL? */
+ q = r;
+ else if (r != NULL) { /* Right link is NULL? */
+ if (r->llink == NULL) { /* D2: Find successor */
+ r->llink = q;
+ q = r;
+ } else { /* D3: Find NULL link */
+ for (q = r->llink; q->llink != NULL; q = r->llink)
+ r = q;
+ r->llink = q->rlink;
+ q->llink = (*rootp)->llink;
+ q->rlink = (*rootp)->rlink;
+ }
+ }
+ free(*rootp); /* D4: Free node */
+ *rootp = q; /* link parent to new node */
+ return *rootp;
+}
+
+/*
+ * find a node, or return 0
+ *
+ * Parameters:
+ * vkey: key to be found
+ * vrootp: address of the tree root
+ */
+ROKEN_LIB_FUNCTION void *
+rk_tfind(const void *vkey, void * const *vrootp,
+ int (*compar)(const void *, const void *))
+{
+ node_t **rootp = (node_t **)vrootp;
+
+ if (rootp == NULL)
+ return NULL;
+
+ while (*rootp != NULL) { /* T1: */
+ int r;
+
+ if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */
+ return *rootp; /* key found */
+ rootp = (r < 0) ?
+ &(*rootp)->llink : /* T3: follow left branch */
+ &(*rootp)->rlink; /* T4: follow right branch */
+ }
+ return NULL;
+}
diff --git a/third_party/heimdal/lib/roken/unsetenv.c b/third_party/heimdal/lib/roken/unsetenv.c
new file mode 100644
index 0000000..55ba5e3
--- /dev/null
+++ b/third_party/heimdal/lib/roken/unsetenv.c
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "roken.h"
+
+#if !HAVE_DECL_ENVIRON
+extern char **environ;
+#endif
+
+/*
+ * unsetenv --
+ */
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+unsetenv(const char *name)
+{
+ int len;
+ const char *np;
+ char **p;
+
+ if (name == 0 || environ == 0)
+ return;
+
+ for (np = name; *np && *np != '='; np++)
+ /* nop */;
+ len = np - name;
+
+ for (p = environ; *p != 0; p++)
+ if (strncmp(*p, name, len) == 0 && (*p)[len] == '=')
+ break;
+
+ for (; *p != 0; p++)
+ *p = *(p + 1);
+}
+
diff --git a/third_party/heimdal/lib/roken/unvis.c b/third_party/heimdal/lib/roken/unvis.c
new file mode 100644
index 0000000..6ceda4a
--- /dev/null
+++ b/third_party/heimdal/lib/roken/unvis.c
@@ -0,0 +1,283 @@
+/* $NetBSD: unvis.c,v 1.19 2000/01/22 22:19:13 mycroft Exp $ */
+
+/*-
+ * Copyright (c) 1989, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if 1
+#include <config.h>
+#include "roken.h"
+#ifndef _DIAGASSERT
+#define _DIAGASSERT(X)
+#endif
+#else
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)unvis.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: unvis.c,v 1.19 2000/01/22 22:19:13 mycroft Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#endif
+#include <sys/types.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <vis.h>
+
+#if 0
+#ifdef __weak_alias
+__weak_alias(strunvis,_strunvis)
+__weak_alias(unvis,_unvis)
+#endif
+
+__warn_references(unvis,
+ "warning: reference to compatibility unvis(); include <vis.h> for correct reference")
+#endif
+
+/*
+ * decode driven by state machine
+ */
+#define S_GROUND 0 /* haven't seen escape char */
+#define S_START 1 /* start decoding special sequence */
+#define S_META 2 /* metachar started (M) */
+#define S_META1 3 /* metachar more, regular char (-) */
+#define S_CTRL 4 /* control char started (^) */
+#define S_OCTAL2 5 /* octal digit 2 */
+#define S_OCTAL3 6 /* octal digit 3 */
+
+#define isoctal(c) (((u_char)(c)) >= '0' && ((u_char)(c)) <= '7')
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strunvis (char *, const char *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_unvis (char *, int, int *, int);
+
+/*
+ * unvis - decode characters previously encoded by vis
+ */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_unvis(char *cp, int c, int *astate, int flag)
+{
+
+ _DIAGASSERT(cp != NULL);
+ _DIAGASSERT(astate != NULL);
+
+ if (flag & UNVIS_END) {
+ if (*astate == S_OCTAL2 || *astate == S_OCTAL3) {
+ *astate = S_GROUND;
+ return (UNVIS_VALID);
+ }
+ return (*astate == S_GROUND ? UNVIS_NOCHAR : UNVIS_SYNBAD);
+ }
+
+ switch (*astate) {
+
+ case S_GROUND:
+ *cp = 0;
+ if (c == '\\') {
+ *astate = S_START;
+ return (0);
+ }
+ *cp = c;
+ return (UNVIS_VALID);
+
+ case S_START:
+ switch(c) {
+ case '\\':
+ *cp = c;
+ *astate = S_GROUND;
+ return (UNVIS_VALID);
+ case '0': case '1': case '2': case '3':
+ case '4': case '5': case '6': case '7':
+ *cp = (c - '0');
+ *astate = S_OCTAL2;
+ return (0);
+ case 'M':
+ *cp = (u_char)0200;
+ *astate = S_META;
+ return (0);
+ case '^':
+ *astate = S_CTRL;
+ return (0);
+ case 'n':
+ *cp = '\n';
+ *astate = S_GROUND;
+ return (UNVIS_VALID);
+ case 'r':
+ *cp = '\r';
+ *astate = S_GROUND;
+ return (UNVIS_VALID);
+ case 'b':
+ *cp = '\b';
+ *astate = S_GROUND;
+ return (UNVIS_VALID);
+ case 'a':
+ *cp = '\007';
+ *astate = S_GROUND;
+ return (UNVIS_VALID);
+ case 'v':
+ *cp = '\v';
+ *astate = S_GROUND;
+ return (UNVIS_VALID);
+ case 't':
+ *cp = '\t';
+ *astate = S_GROUND;
+ return (UNVIS_VALID);
+ case 'f':
+ *cp = '\f';
+ *astate = S_GROUND;
+ return (UNVIS_VALID);
+ case 's':
+ *cp = ' ';
+ *astate = S_GROUND;
+ return (UNVIS_VALID);
+ case 'E':
+ *cp = '\033';
+ *astate = S_GROUND;
+ return (UNVIS_VALID);
+ case '\n':
+ /*
+ * hidden newline
+ */
+ *astate = S_GROUND;
+ return (UNVIS_NOCHAR);
+ case '$':
+ /*
+ * hidden marker
+ */
+ *astate = S_GROUND;
+ return (UNVIS_NOCHAR);
+ }
+ *astate = S_GROUND;
+ return (UNVIS_SYNBAD);
+
+ case S_META:
+ if (c == '-')
+ *astate = S_META1;
+ else if (c == '^')
+ *astate = S_CTRL;
+ else {
+ *astate = S_GROUND;
+ return (UNVIS_SYNBAD);
+ }
+ return (0);
+
+ case S_META1:
+ *astate = S_GROUND;
+ *cp |= c;
+ return (UNVIS_VALID);
+
+ case S_CTRL:
+ if (c == '?')
+ *cp |= 0177;
+ else
+ *cp |= c & 037;
+ *astate = S_GROUND;
+ return (UNVIS_VALID);
+
+ case S_OCTAL2: /* second possible octal digit */
+ if (isoctal(c)) {
+ /*
+ * yes - and maybe a third
+ */
+ *cp = (*cp << 3) + (c - '0');
+ *astate = S_OCTAL3;
+ return (0);
+ }
+ /*
+ * no - done with current sequence, push back passed char
+ */
+ *astate = S_GROUND;
+ return (UNVIS_VALIDPUSH);
+
+ case S_OCTAL3: /* third possible octal digit */
+ *astate = S_GROUND;
+ if (isoctal(c)) {
+ *cp = (*cp << 3) + (c - '0');
+ return (UNVIS_VALID);
+ }
+ /*
+ * we were done, push back passed char
+ */
+ return (UNVIS_VALIDPUSH);
+
+ default:
+ /*
+ * decoder in unknown state - (probably uninitialized)
+ */
+ *astate = S_GROUND;
+ return (UNVIS_SYNBAD);
+ }
+}
+
+/*
+ * strunvis - decode src into dst
+ *
+ * Number of chars decoded into dst is returned, -1 on error.
+ * Dst is null terminated.
+ */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_strunvis(char *dst, const char *src)
+{
+ char c;
+ char *start = dst;
+ int state = 0;
+
+ _DIAGASSERT(src != NULL);
+ _DIAGASSERT(dst != NULL);
+
+ while ((c = *src++) != '\0') {
+ again:
+ switch (rk_unvis(dst, (unsigned char)c, &state, 0)) {
+ case UNVIS_VALID:
+ dst++;
+ break;
+ case UNVIS_VALIDPUSH:
+ dst++;
+ goto again;
+ case 0:
+ case UNVIS_NOCHAR:
+ break;
+ default:
+ return (-1);
+ }
+ }
+ if (unvis(dst, (unsigned char)c, &state, UNVIS_END) == UNVIS_VALID)
+ dst++;
+ *dst = '\0';
+ return (dst - start);
+}
diff --git a/third_party/heimdal/lib/roken/verr.c b/third_party/heimdal/lib/roken/verr.c
new file mode 100644
index 0000000..9201e6d
--- /dev/null
+++ b/third_party/heimdal/lib/roken/verr.c
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include <err.h>
+
+ROKEN_LIB_NORETURN_FUNCTION void ROKEN_LIB_CALL
+verr(int eval, const char *fmt, va_list ap)
+{
+ rk_warnerr(1, fmt, ap);
+ exit(eval);
+}
diff --git a/third_party/heimdal/lib/roken/verrx.c b/third_party/heimdal/lib/roken/verrx.c
new file mode 100644
index 0000000..7b148a4
--- /dev/null
+++ b/third_party/heimdal/lib/roken/verrx.c
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include <err.h>
+
+ROKEN_LIB_NORETURN_FUNCTION void ROKEN_LIB_CALL
+verrx(int eval, const char *fmt, va_list ap)
+{
+ rk_warnerr(0, fmt, ap);
+ exit(eval);
+}
diff --git a/third_party/heimdal/lib/roken/version-script.map b/third_party/heimdal/lib/roken/version-script.map
new file mode 100644
index 0000000..be1713e
--- /dev/null
+++ b/third_party/heimdal/lib/roken/version-script.map
@@ -0,0 +1,238 @@
+HEIMDAL_ROKEN_2.0 {
+ global:
+ arg_printusage;
+ arg_printusage_i18n;
+ cgetclose;
+ cgetmatch;
+ cgetnum;
+ cgetset;
+ cgetustr;
+ ct_memcmp;
+ err;
+ errx;
+ free_getarg_strings;
+ fseeko;
+ ftello;
+ get_window_size;
+ getarg;
+ getnameinfo_verified;
+ hex_decode;
+ hex_encode;
+ issuid;
+ mini_inetd;
+ mini_inetd_addrinfo;
+ net_read;
+ net_write;
+ parse_bytes;
+ parse_flags;
+ parse_time;
+ parse_units;
+ print_flags_table;
+ print_time_table;
+ print_units_table;
+ rk_asnprintf;
+ rk_asprintf;
+ rk_base32_decode;
+ rk_base32_encode;
+ rk_base64_decode;
+ rk_base64_encode;
+ rk_bswap16;
+ rk_bswap32;
+ rk_bswap64;
+ rk_cloexec;
+ rk_cloexec_dir;
+ rk_cloexec_file;
+ rk_cloexec_socket;
+ rk_closefrom;
+ rk_clzll;
+ rk_copyhostent;
+ rk_dns_free_data;
+ rk_dns_lookup;
+ rk_dns_srv_order;
+ rk_dns_string_to_type;
+ rk_dns_type_to_string;
+ rk_dumpdata;
+ rk_ecalloc;
+ rk_emalloc;
+ rk_eread;
+ rk_erealloc;
+ rk_esetenv;
+ rk_estrdup;
+ rk_ewrite;
+ rk_flock;
+ rk_fnmatch;
+ rk_free_environment;
+ rk_freeaddrinfo;
+ rk_freehostent;
+ rk_freeifaddrs;
+ rk_gai_strerror;
+ rk_getaddrinfo;
+ rk_getauxv;
+ rk_getauxval;
+ rk_getifaddrs;
+ rk_getipnodebyaddr;
+ rk_getipnodebyname;
+ rk_getnameinfo;
+ rk_getprogname;
+ rk_glob;
+ rk_globfree;
+ rk_hex_decode;
+ rk_hex_encode;
+ rk_hostent_find_fqdn;
+ rk_inet_ntop;
+ rk_inet_pton;
+ rk_injectauxv;
+ rk_localtime_r;
+ rk_memmem;
+ rk_memset_s;
+ rk_mergesort;
+ rk_mergesort_r;
+ rk_mkdir;
+ rk_mkdtemp;
+ rk_mkostemp;
+ rk_mkstemp;
+ rk_parse_flags;
+ rk_parse_time;
+ rk_parse_units;
+ rk_pid_file_delete;
+ rk_pid_file_write;
+ rk_pidfile;
+ rk_pipe_execv;
+ rk_print_flags_table;
+ rk_print_time_table;
+ rk_print_units_table;
+ rk_random_init;
+ rk_read_environment;
+ rk_readv;
+ rk_realloc;
+ rk_secure_getenv;
+ rk_setprogname;
+ rk_simple_execle;
+ rk_simple_execlp;
+ rk_simple_execve;
+ rk_simple_execve_timed;
+ rk_simple_execvp;
+ rk_simple_execvp_timed;
+ rk_socket;
+ rk_socket_addr_size;
+ rk_socket_get_address;
+ rk_socket_get_port;
+ rk_socket_set_address_and_port;
+ rk_socket_set_any;
+ rk_socket_set_debug;
+ rk_socket_set_ipv6only;
+ rk_socket_set_keepalive;
+ rk_socket_set_nonblocking;
+ rk_socket_set_port;
+ rk_socket_set_portrange;
+ rk_socket_set_reuseaddr;
+ rk_socket_set_tos;
+ rk_socket_sockaddr_size;
+ rk_strasvis;
+ rk_strasvisx;
+ rk_stravis;
+ rk_stravisx;
+ rk_strcollect;
+ rk_strerror;
+ rk_strerror_r;
+ rk_strftime;
+ rk_strlcat;
+ rk_strlcpy;
+ rk_strlwr;
+ rk_strndup;
+ rk_strnlen;
+ rk_strpoolcollect;
+ rk_strpoolfree;
+ rk_strpoolprintf;
+ rk_strptime;
+ rk_strrasvis;
+ rk_strrasvisx;
+ rk_strsep_copy;
+ rk_strsvis;
+ rk_strsvisx;
+ rk_strtoll;
+ rk_strtoull;
+ rk_strunvis;
+ rk_strunvisx;
+ rk_strupr;
+ rk_strvis;
+ rk_strvisx;
+ rk_svis;
+ rk_tdelete;
+ rk_tfind;
+ rk_timegm;
+ rk_time_add;
+ rk_time_sub;
+ rk_timevaladd;
+ rk_timevalfix;
+ rk_timevalsub;
+ rk_tsearch;
+ rk_twalk;
+ rk_undumpdata;
+ rk_unparse_flags;
+ rk_unparse_time;
+ rk_unparse_time_approx;
+ rk_unparse_units;
+ rk_unparse_units_approx;
+ rk_unvis;
+ rk_vasnprintf;
+ rk_vasprintf;
+ rk_vis;
+ rk_vsnprintf;
+ rk_vstrcollect;
+ rk_wait_for_process;
+ rk_wait_for_process_timed;
+ rk_warnerr;
+ rk_xfree;
+ roken_concat;
+ roken_detach_finish;
+ roken_detach_prep;
+ roken_getaddrinfo_hostspec2;
+ roken_getaddrinfo_hostspec;
+ roken_gethostby_setup;
+ roken_gethostbyaddr;
+ roken_gethostbyname;
+ roken_get_appdatadir;
+ roken_get_homedir;
+ roken_get_shell;
+ roken_get_username;
+ roken_get_loginname;
+ roken_mconcat;
+ roken_vconcat;
+ roken_vmconcat;
+ rtbl_add_column;
+ rtbl_add_column_by_id;
+ rtbl_add_column_entry;
+ rtbl_add_column_entry_by_id;
+ rtbl_add_column_entryv;
+ rtbl_add_column_entryv_by_id;
+ rtbl_create;
+ rtbl_destroy;
+ rtbl_format;
+ rtbl_get_flags;
+ rtbl_new_row;
+ rtbl_set_column_affix_by_id;
+ rtbl_set_column_prefix;
+ rtbl_set_flags;
+ rtbl_set_prefix;
+ rtbl_set_separator;
+ signal;
+ simple_execl;
+ tm2time;
+ unparse_bytes;
+ unparse_bytes_short;
+ unparse_flags;
+ unparse_time;
+ unparse_time_approx;
+ unparse_units;
+ unparse_units_approx;
+ verr;
+ verrx;
+ vwarn;
+ vwarnx;
+ warn;
+ warnx;
+ writev;
+ local:
+ *;
+};
diff --git a/third_party/heimdal/lib/roken/versionsupport.h b/third_party/heimdal/lib/roken/versionsupport.h
new file mode 100644
index 0000000..09adce3
--- /dev/null
+++ b/third_party/heimdal/lib/roken/versionsupport.h
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2018-2019, AuriStor, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef _VERSIONSUPPORT_H_
+#define _VERSIONSUPPORT_H_ 1
+
+/*
+ * IsWindowsVersionOrGreater() is provided by Windows SDK 8.1 or greater.
+ * As AuriStorFS supports building with SDK 7.0 and greater we must
+ * provide our own. VerifyVersionInfoW() is present on Windows XP and
+ * later.
+ */
+
+#ifndef _WIN32_WINNT_WIN7
+#define _WIN32_WINNT_WIN7 0x0601
+#endif
+
+#ifndef _WIN32_WINNT_WIN8
+#define _WIN32_WINNT_WIN8 0x0602
+#endif
+
+#ifndef _WIN32_WINNT_WINBLUE
+#define _WIN32_WINNT_WINBLUE 0x0603
+#endif
+
+/* Based upon VersionHelpers.h */
+FORCEINLINE BOOL
+IsWindowsVersionOrGreater(WORD wMajorVersion,
+ WORD wMinorVersion,
+ WORD wServicePackMajor)
+{
+ OSVERSIONINFOEXW osvi;
+ DWORDLONG dwlConditionMask = 0;
+
+ dwlConditionMask = VerSetConditionMask(dwlConditionMask,
+ VER_MAJORVERSION,
+ VER_GREATER_EQUAL);
+ dwlConditionMask = VerSetConditionMask(dwlConditionMask,
+ VER_MINORVERSION,
+ VER_GREATER_EQUAL);
+ dwlConditionMask = VerSetConditionMask(dwlConditionMask,
+ VER_SERVICEPACKMAJOR,
+ VER_GREATER_EQUAL);
+
+ memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
+ osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
+ osvi.dwMajorVersion = wMajorVersion;
+ osvi.dwMinorVersion = wMinorVersion;
+ osvi.wServicePackMajor = wServicePackMajor;
+
+ return VerifyVersionInfoW(&osvi,
+ (VER_MAJORVERSION |
+ VER_MINORVERSION |
+ VER_SERVICEPACKMAJOR),
+ dwlConditionMask);
+}
+
+FORCEINLINE BOOL
+IsWindowsXPOrGreater(VOID)
+{
+ return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP),
+ LOBYTE(_WIN32_WINNT_WINXP),
+ 0);
+}
+
+FORCEINLINE BOOL
+IsWindows7OrGreater(VOID)
+{
+ return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN7),
+ LOBYTE(_WIN32_WINNT_WIN7),
+ 0);
+}
+
+FORCEINLINE BOOL
+IsWindows8OrGreater(VOID)
+{
+ return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN8),
+ LOBYTE(_WIN32_WINNT_WIN8),
+ 0);
+}
+
+FORCEINLINE BOOL
+IsWindows8Point1OrGreater(VOID)
+{
+ return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINBLUE),
+ LOBYTE(_WIN32_WINNT_WINBLUE),
+ 0);
+}
+
+#define IS_WINDOWS_VERSION_OR_GREATER_CACHED(fn) \
+ \
+FORCEINLINE BOOL \
+fn##Cached(VOID) \
+{ \
+ static LONG lIsVersionOrGreater = -1; \
+ \
+ if (lIsVersionOrGreater == -1) { \
+ LONG lResult = fn(); \
+ InterlockedCompareExchangeRelease(&lIsVersionOrGreater, \
+ lResult, -1); \
+ } \
+ \
+ return lIsVersionOrGreater == 1; \
+}
+
+IS_WINDOWS_VERSION_OR_GREATER_CACHED(IsWindowsXPOrGreater)
+IS_WINDOWS_VERSION_OR_GREATER_CACHED(IsWindows7OrGreater)
+IS_WINDOWS_VERSION_OR_GREATER_CACHED(IsWindows8OrGreater)
+IS_WINDOWS_VERSION_OR_GREATER_CACHED(IsWindows8Point1OrGreater)
+
+#endif /* _VERSIONSUPPORT_H_ */
diff --git a/third_party/heimdal/lib/roken/vis-extras.h b/third_party/heimdal/lib/roken/vis-extras.h
new file mode 100644
index 0000000..693edf8
--- /dev/null
+++ b/third_party/heimdal/lib/roken/vis-extras.h
@@ -0,0 +1,27 @@
+#ifndef _VIS_EXTRAS_H_
+#define _VIS_EXTRAS_H_
+
+#include <roken.h>
+
+ROKEN_CPP_START
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strasvis(char **, const char *, int, const char *);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strasvisx(char **, const char *, size_t, int, const char *);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strrasvis(char **, size_t *, const char *, int, const char *);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strrasvisx(char **, size_t *, const char *, size_t, int, const char *);
+
+ROKEN_CPP_END
+
+#define strasvis(a, b, c, d) rk_strasvis(a, b, c, d)
+#define strasvisx(a, b, c, d) rk_strasvisx(a, b, c, d)
+#define strrasvis(a, b, c, d) rk_strrasvis(a, b, c, d)
+#define strrasvisx(a, b, c, d) rk_strrasvisx(a, b, c, d)
+
+#endif /* !_VIS_EXTRAS_H_ */
diff --git a/third_party/heimdal/lib/roken/vis.c b/third_party/heimdal/lib/roken/vis.c
new file mode 100644
index 0000000..0fe44ae
--- /dev/null
+++ b/third_party/heimdal/lib/roken/vis.c
@@ -0,0 +1,649 @@
+/* $NetBSD: vis.c,v 1.37 2008/07/25 22:29:23 dsl Exp $ */
+
+/*-
+ * Copyright (c) 1989, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*-
+ * Copyright (c) 1999, 2005 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#define _DEFAULT_SOURCE
+#include <config.h>
+#include "roken.h"
+#ifdef TEST
+#include "getarg.h"
+#endif
+#ifndef _DIAGASSERT
+#define _DIAGASSERT(X)
+#endif
+
+#include <sys/types.h>
+#include <assert.h>
+#include <ctype.h>
+#ifdef TEST
+#include <err.h>
+#endif
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <vis.h>
+
+#if !HAVE_VIS || !HAVE_SVIS
+#include <ctype.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+#endif
+
+#if !HAVE_VIS || !HAVE_SVIS || TEST
+/*
+ * We use makextralist() in main(), so we need it even if we have all the VIS
+ * routines in the host's C libraries.
+ */
+
+/* 5 is for VIS_SP, VIS_TAB, VIS_NL, VIS_DQ, and VIS_NOSLASH */
+#define MAXEXTRAS (sizeof(char_glob) - 1 + sizeof(char_shell) - 1 + 5)
+
+#ifndef VIS_SHELL
+#define VIS_SHELL 0x2000
+#endif
+#ifndef VIS_GLOB
+#define VIS_GLOB 0x0100
+#endif
+
+#ifndef VIS_SP
+#define VIS_SP 0x0004 /* also encode space */
+#endif
+#ifndef VIS_TAB
+#define VIS_TAB 0x0008 /* also encode tab */
+#endif
+#ifndef VIS_NL
+#define VIS_NL 0x0010 /* also encode newline */
+#endif
+#ifndef VIS_WHITE
+#define VIS_WHITE (VIS_SP | VIS_TAB | VIS_NL)
+#endif
+#ifndef VIS_SAFE
+#define VIS_SAFE 0x0020 /* only encode "unsafe" characters */
+#endif
+#ifndef VIS_DQ
+#define VIS_DQ 0x8000 /* also encode double quotes */
+#endif
+
+
+/*
+ * Expand list of extra characters to not visually encode.
+ */
+static char *
+makeextralist(int flags, const char *src)
+{
+ static const char char_glob[] = "*?[#";
+ static const char char_shell[] = "'`\";&<>()|{}]\\$!^~";
+ char *dst, *d;
+ size_t len;
+
+ len = strlen(src);
+ if ((dst = d = calloc(1, len + MAXEXTRAS + 1)) == NULL)
+ return NULL;
+
+ memcpy(dst, src, len);
+ d += len;
+
+ if (flags & VIS_GLOB) {
+ memcpy(d, char_glob, sizeof(char_glob) - 1);
+ d += sizeof(char_glob) - 1;
+ }
+ if (flags & VIS_SHELL) {
+ memcpy(d, char_shell, sizeof(char_shell) - 1);
+ d += sizeof(char_shell) - 1;
+ }
+
+ if (flags & VIS_SP) *d++ = ' ';
+ if (flags & VIS_TAB) *d++ = '\t';
+ if (flags & VIS_NL) *d++ = '\n';
+ if (flags & VIS_DQ) *d++ = '"';
+ if ((flags & VIS_NOSLASH) == 0) *d++ = '\\';
+
+ return dst;
+}
+#endif
+
+#if !HAVE_VIS || !HAVE_SVIS
+static char *do_svis(char *, int, int, int, const char *);
+
+#undef BELL
+#if defined(__STDC__)
+#define BELL '\a'
+#else
+#define BELL '\007'
+#endif
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+ rk_vis (char *, int, int, int);
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+ rk_svis (char *, int, int, int, const char *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strvis (char *, const char *, int);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strsvis (char *, const char *, int, const char *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strvisx (char *, const char *, size_t, int);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strsvisx (char *, const char *, size_t, int, const char *);
+
+#define isoctal(c) (((u_char)(c)) >= '0' && ((u_char)(c)) <= '7')
+#define iswhite(c) (c == ' ' || c == '\t' || c == '\n')
+#define issafe(c) (c == '\b' || c == BELL || c == '\r')
+#define xtoa(c) "0123456789abcdef"[c]
+
+/*
+ * This is do_hvis, for HTTP style (RFC 1808)
+ */
+static char *
+do_hvis(char *dst, int c, int flag, int nextc, const char *extra)
+{
+ if (!isascii(c) || !isalnum(c) || strchr("$-_.+!*'(),", c) != NULL ||
+ strchr(extra, c)) {
+ *dst++ = '%';
+ *dst++ = xtoa(((unsigned int)c >> 4) & 0xf);
+ *dst++ = xtoa((unsigned int)c & 0xf);
+ } else {
+ dst = do_svis(dst, c, flag, nextc, extra);
+ }
+ return dst;
+}
+
+/*
+ * This is do_vis, the central code of vis.
+ * dst: Pointer to the destination buffer
+ * c: Character to encode
+ * flag: Flag word
+ * nextc: The character following 'c'
+ * extra: Pointer to the list of extra characters to be
+ * backslash-protected.
+ */
+static char *
+do_svis(char *dst, int c, int flag, int nextc, const char *extra)
+{
+ int isextra;
+ isextra = strchr(extra, c) != NULL;
+ if (!isextra && isascii(c) && (isgraph(c) || iswhite(c) ||
+ ((flag & VIS_SAFE) && issafe(c)))) {
+ *dst++ = c;
+ return dst;
+ }
+ if (flag & VIS_CSTYLE) {
+ switch (c) {
+ case '\n':
+ *dst++ = '\\'; *dst++ = 'n';
+ return dst;
+ case '\r':
+ *dst++ = '\\'; *dst++ = 'r';
+ return dst;
+ case '\b':
+ *dst++ = '\\'; *dst++ = 'b';
+ return dst;
+ case BELL:
+ *dst++ = '\\'; *dst++ = 'a';
+ return dst;
+ case '\v':
+ *dst++ = '\\'; *dst++ = 'v';
+ return dst;
+ case '\t':
+ *dst++ = '\\'; *dst++ = 't';
+ return dst;
+ case '\f':
+ *dst++ = '\\'; *dst++ = 'f';
+ return dst;
+ case ' ':
+ *dst++ = '\\'; *dst++ = 's';
+ return dst;
+ case '\0':
+ *dst++ = '\\'; *dst++ = '0';
+ if (isoctal(nextc)) {
+ *dst++ = '0';
+ *dst++ = '0';
+ }
+ return dst;
+ default:
+ if (isgraph(c)) {
+ *dst++ = '\\'; *dst++ = c;
+ return dst;
+ }
+ }
+ }
+ if (isextra || ((c & 0177) == ' ') || (flag & VIS_OCTAL)) {
+ *dst++ = '\\';
+ *dst++ = (u_char)(((unsigned int)(u_char)c >> 6) & 03) + '0';
+ *dst++ = (u_char)(((unsigned int)(u_char)c >> 3) & 07) + '0';
+ *dst++ = (u_char)( c & 07) + '0';
+ } else {
+ if ((flag & VIS_NOSLASH) == 0) *dst++ = '\\';
+ if (c & 0200) {
+ c &= 0177; *dst++ = 'M';
+ }
+ if (iscntrl(c)) {
+ *dst++ = '^';
+ if (c == 0177)
+ *dst++ = '?';
+ else
+ *dst++ = c + '@';
+ } else {
+ *dst++ = '-'; *dst++ = c;
+ }
+ }
+ return dst;
+}
+
+
+/*
+ * svis - visually encode characters, also encoding the characters
+ * pointed to by `extra'
+ */
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+rk_svis(char *dst, int c, int flag, int nextc, const char *extra)
+{
+ char *nextra = NULL;
+
+ _DIAGASSERT(dst != NULL);
+ _DIAGASSERT(extra != NULL);
+ nextra = makeextralist(flag, extra);
+ if (!nextra) {
+ *dst = '\0'; /* can't create nextra, return "" */
+ return dst;
+ }
+ if (flag & VIS_HTTPSTYLE)
+ dst = do_hvis(dst, c, flag, nextc, nextra);
+ else
+ dst = do_svis(dst, c, flag, nextc, nextra);
+ free(nextra);
+ *dst = '\0';
+ return dst;
+}
+
+
+/*
+ * strsvis, strsvisx - visually encode characters from src into dst
+ *
+ * Extra is a pointer to a \0-terminated list of characters to
+ * be encoded, too. These functions are useful e. g. to
+ * encode strings in such a way so that they are not interpreted
+ * by a shell.
+ *
+ * Dst must be 4 times the size of src to account for possible
+ * expansion. The length of dst, not including the trailing NULL,
+ * is returned.
+ *
+ * Strsvisx encodes exactly len bytes from src into dst.
+ * This is useful for encoding a block of data.
+ */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_strsvis(char *dst, const char *csrc, int flag, const char *extra)
+{
+ int c;
+ char *start;
+ char *nextra = NULL;
+ const unsigned char *src = (const unsigned char *)csrc;
+
+ _DIAGASSERT(dst != NULL);
+ _DIAGASSERT(src != NULL);
+ _DIAGASSERT(extra != NULL);
+ nextra = makeextralist(flag, extra);
+ if (!nextra) {
+ *dst = '\0'; /* can't create nextra, return "" */
+ return 0;
+ }
+ if (flag & VIS_HTTPSTYLE) {
+ for (start = dst; (c = *src++) != '\0'; /* empty */)
+ dst = do_hvis(dst, c, flag, *src, nextra);
+ } else {
+ for (start = dst; (c = *src++) != '\0'; /* empty */)
+ dst = do_svis(dst, c, flag, *src, nextra);
+ }
+ free(nextra);
+ *dst = '\0';
+ return (dst - start);
+}
+
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_strsvisx(char *dst, const char *csrc, size_t len, int flag, const char *extra)
+{
+ unsigned char c;
+ char *start;
+ char *nextra = NULL;
+ const unsigned char *src = (const unsigned char *)csrc;
+
+ _DIAGASSERT(dst != NULL);
+ _DIAGASSERT(src != NULL);
+ _DIAGASSERT(extra != NULL);
+ nextra = makeextralist(flag, extra);
+ if (! nextra) {
+ *dst = '\0'; /* can't create nextra, return "" */
+ return 0;
+ }
+
+ if (flag & VIS_HTTPSTYLE) {
+ for (start = dst; len > 0; len--) {
+ c = *src++;
+ dst = do_hvis(dst, c, flag, *src, nextra);
+ }
+ } else {
+ for (start = dst; len > 0; len--) {
+ c = *src++;
+ dst = do_svis(dst, c, flag, *src, nextra);
+ }
+ }
+ free(nextra);
+ *dst = '\0';
+ return (dst - start);
+}
+#endif
+
+/*
+ * Heimdal innovations: functions that allocate or reallocate a destination
+ * buffer as needed. Based on OpenBSD's stravis().
+ */
+
+#include <vis-extras.h>
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_strasvis(char **out, const char *csrc, int flag, const char *extra)
+{
+ return rk_strasvisx(out, csrc, strlen(csrc), flag, extra);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_strrasvis(char **out, size_t *outsz, const char *csrc, int flag, const char *extra)
+{
+ return rk_strrasvisx(out, outsz, csrc, strlen(csrc), flag, extra);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_strasvisx(char **out, const char *csrc, size_t len, int flag, const char *extra)
+{
+ size_t sz = 0;
+
+ *out = NULL;
+ return rk_strrasvisx(out, &sz, csrc, strlen(csrc), flag, extra);
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_strrasvisx(char **out,
+ size_t *outsz,
+ const char *csrc,
+ size_t len,
+ int flag,
+ const char *extra)
+{
+ size_t want = 4 * len + 4;
+ size_t have = *outsz;
+ char *s = *out;
+ int r;
+
+ _DIAGASSERT(dst != NULL);
+ _DIAGASSERT(src != NULL);
+ _DIAGASSERT(extra != NULL);
+ if (want < len || want > INT_MAX) {
+ errno = EOVERFLOW;
+ return -1;
+ }
+ if (have < want) {
+ if ((s = realloc(s, want)) == NULL)
+ return -1;
+ *outsz = want;
+ *out = s;
+ }
+ if (*out == NULL) {
+ errno = EINVAL;
+ return -1;
+ }
+ **out = '\0'; /* Makes source debugging nicer, that's all */
+ r = strsvisx(*out, csrc, len, flag, extra);
+ return r;
+}
+
+#if !HAVE_VIS
+/*
+ * vis - visually encode characters
+ */
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+rk_vis(char *dst, int c, int flag, int nextc)
+{
+ char *extra = NULL;
+ unsigned char uc = (unsigned char)c;
+
+ _DIAGASSERT(dst != NULL);
+
+ extra = makeextralist(flag, "");
+ if (! extra) {
+ *dst = '\0'; /* can't create extra, return "" */
+ return dst;
+ }
+ if (flag & VIS_HTTPSTYLE)
+ dst = do_hvis(dst, uc, flag, nextc, extra);
+ else
+ dst = do_svis(dst, uc, flag, nextc, extra);
+ free(extra);
+ *dst = '\0';
+ return dst;
+}
+
+
+/*
+ * strvis, strvisx - visually encode characters from src into dst
+ *
+ * Dst must be 4 times the size of src to account for possible
+ * expansion. The length of dst, not including the trailing NULL,
+ * is returned.
+ *
+ * Strvisx encodes exactly len bytes from src into dst.
+ * This is useful for encoding a block of data.
+ */
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_strvis(char *dst, const char *src, int flag)
+{
+ char *extra = NULL;
+ int rv;
+
+ extra = makeextralist(flag, "");
+ if (!extra) {
+ *dst = '\0'; /* can't create extra, return "" */
+ return 0;
+ }
+ rv = strsvis(dst, src, flag, extra);
+ free(extra);
+ return rv;
+}
+
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_strvisx(char *dst, const char *src, size_t len, int flag)
+{
+ char *extra = NULL;
+ int rv;
+
+ extra = makeextralist(flag, "");
+ if (!extra) {
+ *dst = '\0'; /* can't create extra, return "" */
+ return 0;
+ }
+ rv = strsvisx(dst, src, len, flag, extra);
+ free(extra);
+ return rv;
+}
+#endif
+
+#ifdef TEST
+static const char *extra_arg = "";
+static int cstyle_flag;
+static int glob_flag;
+static int help_flag;
+static int http_flag;
+static int httponly_flag;
+static int line_flag;
+static int octal_flag;
+static int safe_flag;
+static int shell_flag;
+static int stdin_flag;
+static int tab_flag;
+static int whitespace_flag;
+
+/*
+ * The short options are compatible with a subset of the FreeBSD contrib
+ * vis(1). Heimdal additions have long option names only.
+ */
+static struct getargs args[] = {
+ { "c", 'C', arg_flag, &cstyle_flag, "C style", "C style" },
+ { "extra", 'e', arg_string, &extra_arg, "also encode extra", "also encode extra"},
+ { "glob", 'g', arg_flag, &glob_flag, "escape glob specials", "escape glob specials" },
+ { "help", 0, arg_flag, &help_flag, "help", "help"},
+ { "line", 0, arg_flag, &line_flag, "read and escape stdin without escaping newlines", NULL },
+ { "octal", 'o', arg_flag, &octal_flag, "octal escape", "octal escape" },
+ { "safe", 's', arg_flag, &safe_flag, "only encode \"unsafe\" characters", "only encode \"unsafe\" characters" },
+ { "shell", 'S', arg_flag, &shell_flag, "encode shell meta-characters", "encode shell meta-characters" },
+ { "stdin", 0, arg_flag, &stdin_flag, "read and escape stdin", NULL },
+ { "tab", 't', arg_flag, &tab_flag, "encode tabs", "encode tabs" },
+ { "url", 'h', arg_flag, &http_flag, "url escape", "url escape" },
+ { "url-only", 0, arg_flag, &httponly_flag, "url escape", "url escape" },
+ { "whitespace", 'w', arg_flag, &whitespace_flag, "encode whitespace", "encode whitespace" },
+ { 0, 0, 0, 0, 0, 0}
+};
+static size_t num_args = sizeof(args)/sizeof(args[0]);
+
+int
+main(int argc, char **argv)
+{
+ size_t sz = 0;
+ char *nextra = NULL;
+ char *s = NULL;
+ int goptind = 0;
+ int flags = 0;
+
+ setprogname("vis");
+ if (getarg(args, num_args, argc, argv, &goptind) || help_flag) {
+ arg_printusage(args, num_args, NULL, "strings...");
+ return help_flag ? 0 : 1;
+ }
+
+ argc -= goptind;
+ argv += goptind;
+
+ if (argc == 0 && !stdin_flag && !line_flag) {
+ arg_printusage(args, num_args, NULL, "strings...");
+ return 1;
+ }
+
+ if (http_flag && cstyle_flag)
+ errx(1, "--http and --cstyle are mutually exclusive");
+
+ flags |= cstyle_flag ? VIS_CSTYLE : 0;
+ flags |= http_flag ? VIS_HTTPSTYLE : 0;
+ flags |= httponly_flag ? VIS_HTTPSTYLE | VIS_NOESCAPE : 0;
+ flags |= octal_flag ? VIS_OCTAL : 0;
+ flags |= safe_flag ? VIS_SAFE : 0;
+ flags |= tab_flag ? VIS_TAB : 0;
+ flags |= whitespace_flag ? VIS_WHITE : 0;
+
+ if ((nextra = makeextralist(flags, extra_arg)) == NULL)
+ err(1, "Out of memory");
+
+ while (argc) {
+ if (rk_strrasvis(&s, &sz, argv[0], flags, nextra) < 0)
+ err(2, "Out of memory");
+ printf("%s\n", s);
+ argc--;
+ }
+ if (line_flag) {
+ ssize_t nbytes;
+ size_t linesz = 0;
+ char *line = NULL;
+
+ while (!feof(stdin) &&
+ (nbytes = getline(&line, &linesz, stdin)) > 0) {
+ const char *nl = "";
+
+ if (line[nbytes - 1] == '\n') {
+ line[--nbytes] = '\0';
+ nl = "\n";
+ }
+
+ if (rk_strrasvisx(&s, &sz, line, nbytes, flags, nextra) < 0)
+ err(2, "Out of memory");
+ printf("%s%s", s, nl);
+ }
+ fflush(stdout);
+ if (ferror(stdin))
+ errx(2, "I/O error");
+ } else if (stdin_flag) {
+ size_t nbytes;
+ char buf[2048 + 1];
+ char vbuf[4 * (sizeof(buf) - 1) + 1];
+
+ while (!feof(stdin) &&
+ (nbytes = fread(buf, 1, sizeof(buf) - 1, stdin))) {
+ buf[nbytes] = '\0';
+ strsvis(vbuf, buf, flags, nextra);
+ printf("%s", vbuf);
+ }
+ fflush(stdout);
+ if (ferror(stdin))
+ errx(2, "I/O error");
+ }
+
+ free(nextra);
+ free(s);
+ return 0;
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/vis.hin b/third_party/heimdal/lib/roken/vis.hin
new file mode 100644
index 0000000..f1027f5
--- /dev/null
+++ b/third_party/heimdal/lib/roken/vis.hin
@@ -0,0 +1,170 @@
+/* $NetBSD: vis.h,v 1.16 2005/09/13 01:44:32 christos Exp $ */
+
+/*-
+ * Copyright (c) 1990, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)vis.h 8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _VIS_H_
+#define _VIS_H_
+
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __cdecl
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#endif
+#endif
+
+#include <sys/types.h>
+
+#include <roken.h>
+
+/*
+ * to select alternate encoding format
+ */
+#define VIS_OCTAL 0x0001 /* use octal \ddd format */
+#define VIS_CSTYLE 0x0002 /* use \[nrft0..] where appropiate */
+
+/*
+ * to alter set of characters encoded (default is to encode all
+ * non-graphic except space, tab, and newline).
+ */
+#define VIS_SP 0x0004 /* also encode space */
+#define VIS_TAB 0x0008 /* also encode tab */
+#define VIS_NL 0x0010 /* also encode newline */
+#define VIS_WHITE (VIS_SP | VIS_TAB | VIS_NL)
+#define VIS_SAFE 0x0020 /* only encode "unsafe" characters */
+#define VIS_DQ 0x8000 /* also encode double quotes */
+
+/*
+ * other
+ */
+#define VIS_NOSLASH 0x0040 /* inhibit printing '\' */
+#define VIS_HTTPSTYLE 0x0080 /* http-style escape % HEX HEX */
+#define VIS_HTTP1808 0x0080 /* http-style escape % hex hex */
+#define VIS_GLOB 0x0100 /* encode glob(3) magic characters */
+#if 0
+/*
+ * Not yet. FreeBSD calls 0x0400 VIS_HTTP1866, but if that means RFC1866,
+ * that's HTML 2.0, not HTTP. Argh.
+ */
+#define VIS_MIMESTYLE 0x0200 /* mime-style escape = HEX HEX */
+#define VIS_HTML1866 0x0400 /* HTML-style &#num; or &string; */
+#endif
+#define VIS_NOESCAPE 0x0800 /* don't decode `\'; URL-encode only when given
+ * with VIS_HTTPSTYLE */
+#if 0
+#define _VIS_END 0x1000 /* for unvis */
+#endif
+#define VIS_SHELL 0x2000 /* encode shell special characters [not glob] */
+#define VIS_META (VIS_WHITE | VIS_GLOB | VIS_SHELL)
+#define VIS_NOLOCALE 0x4000 /* encode using the C locale */
+
+/*
+ * unvis return codes
+ */
+#define UNVIS_VALID 1 /* character valid */
+#define UNVIS_VALIDPUSH 2 /* character valid, push back passed char */
+#define UNVIS_NOCHAR 3 /* valid sequence, no character produced */
+#define UNVIS_SYNBAD -1 /* unrecognized escape sequence */
+#define UNVIS_ERROR -2 /* decoder in unknown state (unrecoverable) */
+
+/*
+ * unvis flags
+ */
+#define UNVIS_END 1 /* no more characters */
+
+ROKEN_CPP_START
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+ rk_vis(char *, int, int, int);
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+ rk_svis(char *, int, int, int, const char *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strvis(char *, const char *, int);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strsvis(char *, const char *, int, const char *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strvisx(char *, const char *, size_t, int);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strsvisx(char *, const char *, size_t, int, const char *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strunvis(char *, const char *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_strunvisx(char *, const char *, int);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ rk_unvis(char *, int, int *, int);
+
+ROKEN_CPP_END
+
+#ifndef HAVE_VIS
+#undef vis
+#define vis(a,b,c,d) rk_vis(a,b,c,d)
+#endif
+
+#ifndef HAVE_SVIS
+#undef svis
+#define svis(a,b,c,d,e) rk_svis(a,b,c,d,e)
+#endif
+
+#ifndef HAVE_STRVIS
+#undef strvis
+#define strvis(a,b,c) rk_strvis(a,b,c)
+#endif
+
+#ifndef HAVE_STRSVIS
+#undef strsvis
+#define strsvis(a,b,c,d) rk_strsvis(a,b,c,d)
+#endif
+
+#ifndef HAVE_STRVISX
+#undef strvisx
+#define strvisx(a,b,c,d) rk_strvisx(a,b,c,d)
+#endif
+
+#ifndef HAVE_STRSVISX
+#undef strsvisx
+#define strsvisx(a,b,c,d,e) rk_strsvisx(a,b,c,d,e)
+#endif
+
+#ifndef HAVE_STRUNVIS
+#undef strunvis
+#define strunvis(a,b) rk_strunvis(a,b)
+#endif
+
+
+#ifndef HAVE_UNVIS
+#undef unvis
+#define unvis(a,b,c,d) rk_unvis(a,b,c,d)
+#endif
+
+#endif /* !_VIS_H_ */
diff --git a/third_party/heimdal/lib/roken/vsyslog.c b/third_party/heimdal/lib/roken/vsyslog.c
new file mode 100644
index 0000000..aea7086
--- /dev/null
+++ b/third_party/heimdal/lib/roken/vsyslog.c
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 1995 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#ifndef HAVE_VSYSLOG
+
+#include <stdio.h>
+#include <syslog.h>
+#include <stdarg.h>
+
+#include "roken.h"
+
+/*
+ * the theory behind this is that we might be trying to call vsyslog
+ * when there's no memory left, and we should try to be as useful as
+ * possible. And the format string should say something about what's
+ * failing.
+ */
+
+static void
+simple_vsyslog(int pri, const char *fmt, va_list ap)
+{
+ syslog (pri, "%s", fmt);
+}
+
+/*
+ * do like syslog but with a `va_list'
+ */
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+vsyslog(int pri, const char *fmt, va_list ap)
+{
+ char *fmt2;
+ const char *p;
+ char *p2;
+ int ret;
+ int saved_errno = errno;
+ int fmt_len = strlen (fmt);
+ int fmt2_len = fmt_len;
+ char *buf;
+
+ fmt2 = malloc (fmt_len + 1);
+ if (fmt2 == NULL) {
+ simple_vsyslog (pri, fmt, ap);
+ return;
+ }
+
+ for (p = fmt, p2 = fmt2; *p != '\0'; ++p) {
+ if (p[0] == '%' && p[1] == 'm') {
+ const char *e = strerror (saved_errno);
+ int e_len = strlen (e);
+ char *tmp;
+ int pos;
+
+ pos = p2 - fmt2;
+ fmt2_len += e_len - 2;
+ tmp = realloc (fmt2, fmt2_len + 1);
+ if (tmp == NULL) {
+ free (fmt2);
+ simple_vsyslog (pri, fmt, ap);
+ return;
+ }
+ fmt2 = tmp;
+ p2 = fmt2 + pos;
+ memmove (p2, e, e_len);
+ p2 += e_len;
+ ++p;
+ } else
+ *p2++ = *p;
+ }
+ *p2 = '\0';
+
+ ret = vasprintf (&buf, fmt2, ap);
+ free (fmt2);
+ if (ret < 0 || buf == NULL) {
+ simple_vsyslog (pri, fmt, ap);
+ return;
+ }
+ syslog (pri, "%s", buf);
+ free (buf);
+}
+#endif
diff --git a/third_party/heimdal/lib/roken/vwarn.c b/third_party/heimdal/lib/roken/vwarn.c
new file mode 100644
index 0000000..8f1706d
--- /dev/null
+++ b/third_party/heimdal/lib/roken/vwarn.c
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include <err.h>
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+vwarn(const char *fmt, va_list ap)
+{
+ rk_warnerr(1, fmt, ap);
+}
diff --git a/third_party/heimdal/lib/roken/vwarnx.c b/third_party/heimdal/lib/roken/vwarnx.c
new file mode 100644
index 0000000..6fb1d8c
--- /dev/null
+++ b/third_party/heimdal/lib/roken/vwarnx.c
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include <err.h>
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+vwarnx(const char *fmt, va_list ap)
+{
+ rk_warnerr(0, fmt, ap);
+}
+
diff --git a/third_party/heimdal/lib/roken/warn.c b/third_party/heimdal/lib/roken/warn.c
new file mode 100644
index 0000000..e149c56
--- /dev/null
+++ b/third_party/heimdal/lib/roken/warn.c
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include "err.h"
+
+void
+warn(const char *fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ vwarn(fmt, ap);
+ va_end(ap);
+}
diff --git a/third_party/heimdal/lib/roken/warnerr.c b/third_party/heimdal/lib/roken/warnerr.c
new file mode 100644
index 0000000..9e67023
--- /dev/null
+++ b/third_party/heimdal/lib/roken/warnerr.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+#include "err.h"
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_warnerr(int doerrno, const char *fmt, va_list ap)
+{
+ int sverrno = errno;
+ const char *progname = getprogname();
+
+ if(progname != NULL){
+ fprintf(stderr, "%s", progname);
+ if(fmt != NULL || doerrno)
+ fprintf(stderr, ": ");
+ }
+ if (fmt != NULL){
+ vfprintf(stderr, fmt, ap);
+ if(doerrno)
+ fprintf(stderr, ": ");
+ }
+ if(doerrno)
+ fprintf(stderr, "%s", strerror(sverrno));
+ fprintf(stderr, "\n");
+}
diff --git a/third_party/heimdal/lib/roken/warnx.c b/third_party/heimdal/lib/roken/warnx.c
new file mode 100644
index 0000000..cf33939
--- /dev/null
+++ b/third_party/heimdal/lib/roken/warnx.c
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "err.h"
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+warnx(const char *fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ vwarnx(fmt, ap);
+ va_end(ap);
+}
diff --git a/third_party/heimdal/lib/roken/win32_alloc.c b/third_party/heimdal/lib/roken/win32_alloc.c
new file mode 100644
index 0000000..40fe0f4
--- /dev/null
+++ b/third_party/heimdal/lib/roken/win32_alloc.c
@@ -0,0 +1,76 @@
+/***********************************************************************
+ * Copyright (c) 2012, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+#include <config.h>
+#include "roken.h"
+#undef calloc
+#undef malloc
+#undef free
+#undef strdup
+#undef wcsdup
+
+/*
+ * Windows executables and dlls suffer when memory is
+ * allocated with one allocator and deallocated with
+ * another because each allocator is backed by a separate
+ * heap. Reduce the exposure by ensuring that all
+ * binaries that are built using roken will build against
+ * same allocator.
+ */
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+rk_calloc(size_t elements, size_t size)
+{
+ return calloc( elements, size);
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_free(void * ptr)
+{
+ free( ptr);
+}
+
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+rk_malloc(size_t size)
+{
+ return malloc( size);
+}
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+rk_strdup(const char *str)
+{
+ return strdup( str);
+}
+
+ROKEN_LIB_FUNCTION unsigned short * ROKEN_LIB_CALL
+rk_wcsdup(const unsigned short *str)
+{
+ return wcsdup( str);
+}
diff --git a/third_party/heimdal/lib/roken/win32_version.c b/third_party/heimdal/lib/roken/win32_version.c
new file mode 100644
index 0000000..faf05b8
--- /dev/null
+++ b/third_party/heimdal/lib/roken/win32_version.c
@@ -0,0 +1,128 @@
+#include <config.h>
+#include "roken.h"
+#include <psapi.h>
+
+static DWORD
+GetVersionInfo(CHAR *filename, CHAR *szOutput, DWORD dwOutput)
+{
+ DWORD dwVersionHandle;
+ LPVOID pVersionInfo = 0;
+ DWORD retval = 0;
+ LPDWORD pLangInfo = 0;
+ LPTSTR szVersion = 0;
+ UINT len = 0;
+ TCHAR szVerQ[] = TEXT("\\StringFileInfo\\12345678\\FileVersion");
+ DWORD size = GetFileVersionInfoSize(filename, &dwVersionHandle);
+
+ if (!size)
+ return GetLastError();
+
+ pVersionInfo = malloc(size);
+ if (!pVersionInfo)
+ return ERROR_NOT_ENOUGH_MEMORY;
+
+ GetFileVersionInfo(filename, dwVersionHandle, size, pVersionInfo);
+ if (retval = GetLastError())
+ goto cleanup;
+
+ VerQueryValue(pVersionInfo, TEXT("\\VarFileInfo\\Translation"),
+ (LPVOID*)&pLangInfo, &len);
+ if (retval = GetLastError())
+ goto cleanup;
+
+ wsprintf(szVerQ,
+ TEXT("\\StringFileInfo\\%04x%04x\\FileVersion"),
+ LOWORD(*pLangInfo), HIWORD(*pLangInfo));
+
+ VerQueryValue(pVersionInfo, szVerQ, (LPVOID*)&szVersion, &len);
+ if (retval = GetLastError()) {
+ /* try again with language 409 since the old binaries were tagged wrong */
+ wsprintf(szVerQ,
+ TEXT("\\StringFileInfo\\0409%04x\\FileVersion"),
+ HIWORD(*pLangInfo));
+
+ VerQueryValue(pVersionInfo, szVerQ, (LPVOID*)&szVersion, &len);
+ if (retval = GetLastError())
+ goto cleanup;
+ }
+ snprintf(szOutput, dwOutput, TEXT("%s"), szVersion);
+ szOutput[dwOutput - 1] = 0;
+
+ cleanup:
+ free(pVersionInfo);
+
+ return retval;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+win32_getLibraryVersion(const char *libname, char **outname, char **outversion)
+{
+ CHAR modVersion[128];
+ HMODULE hMods[1024];
+ HANDLE hProcess;
+ DWORD cbNeeded;
+ unsigned int i;
+ int success = -1;
+ HINSTANCE hPSAPI;
+ DWORD (WINAPI *pGetModuleFileNameExA)(HANDLE hProcess, HMODULE hModule, LPTSTR lpFilename, DWORD nSize);
+ BOOL (WINAPI *pEnumProcessModules)(HANDLE hProcess, HMODULE* lphModule, DWORD cb, LPDWORD lpcbNeeded);
+
+ if (outversion)
+ *outversion = NULL;
+ if (outname)
+ *outname = NULL;
+
+ hPSAPI = LoadLibrary("psapi");
+ if ( hPSAPI == NULL )
+ return -1;
+
+ if (((FARPROC) pGetModuleFileNameExA =
+ GetProcAddress( hPSAPI, "GetModuleFileNameExA" )) == NULL ||
+ ((FARPROC) pEnumProcessModules =
+ GetProcAddress( hPSAPI, "EnumProcessModules" )) == NULL)
+ {
+ goto out;
+ }
+
+ // Get a list of all the modules in this process.
+ hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
+ FALSE, GetCurrentProcessId());
+
+ if (pEnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
+ {
+ for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
+ {
+ char szModName[2048];
+
+ // Get the full path to the module's file.
+ if (pGetModuleFileNameExA(hProcess, hMods[i], szModName, sizeof(szModName)))
+ {
+ CHAR checkName[1024];
+ lstrcpy(checkName, szModName);
+ strlwr(checkName);
+
+ if (strstr(checkName, libname)) {
+ if (GetVersionInfo(szModName, modVersion, sizeof(modVersion)) == 0) {
+ success = 0;
+ if (outversion) {
+ *outversion = strdup(modVersion);
+ if (*outversion == NULL)
+ success = -1;
+ }
+ if (outname) {
+ *outname = strdup(szModName);
+ if (*outname == NULL)
+ success = -1;
+ }
+ }
+ break;
+ }
+ }
+ }
+ }
+ CloseHandle(hProcess);
+
+ out:
+ FreeLibrary(hPSAPI);
+ return success;
+}
diff --git a/third_party/heimdal/lib/roken/write_pid.c b/third_party/heimdal/lib/roken/write_pid.c
new file mode 100644
index 0000000..cf5299b
--- /dev/null
+++ b/third_party/heimdal/lib/roken/write_pid.c
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+#ifdef HAVE_UTIL_H
+#include <util.h>
+#endif
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+pid_file_write(const char *progname)
+{
+ const char *pidfile_dir = NULL;
+ char *ret = NULL;
+ FILE *fp;
+
+ /*
+ * Maybe we could have a version of this function (and pidfile())
+ * where we get a directory from the caller. That would allow us to
+ * have command-line options for the daemons for this.
+ *
+ * For now we use an environment variable.
+ */
+ pidfile_dir = secure_getenv("HEIM_PIDFILE_DIR");
+ if (pidfile_dir == NULL)
+ pidfile_dir = _PATH_VARRUN;
+
+ if (asprintf(&ret, "%s%s.pid", pidfile_dir, progname) < 0 || ret == NULL)
+ return NULL;
+ fp = fopen(ret, "w");
+ if (fp == NULL) {
+ free(ret);
+ return NULL;
+ }
+ fprintf(fp, "%lu\n", (unsigned long)getpid());
+ fclose(fp);
+ return ret;
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+pid_file_delete(char **filename)
+{
+ if (*filename != NULL) {
+ unlink(*filename);
+ free(*filename);
+ *filename = NULL;
+ }
+}
+
+static char *pidfile_path;
+static pid_t pidfile_pid;
+
+static void
+pidfile_cleanup(void)
+{
+ if (pidfile_path != NULL && pidfile_pid == getpid())
+ pid_file_delete(&pidfile_path);
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_pidfile(const char *bname)
+{
+ /*
+ * If the OS has a pidfile(), call that, but still call
+ * pid_file_write(). Even if both want to write the same file,
+ * writing it twice will still work.
+ */
+#ifdef HAVE_PIDFILE
+ pidfile(bname);
+#endif
+
+ if (pidfile_path != NULL)
+ return;
+ if (bname == NULL)
+ bname = getprogname();
+ pidfile_path = pid_file_write(bname);
+ pidfile_pid = getpid();
+#if defined(HAVE_ATEXIT)
+ if (pidfile_path != NULL)
+ atexit(pidfile_cleanup);
+#elif defined(HAVE_ON_EXIT)
+ if (pidfile_path != NULL)
+ on_exit(pidfile_cleanup);
+#endif
+}
diff --git a/third_party/heimdal/lib/roken/writev.c b/third_party/heimdal/lib/roken/writev.c
new file mode 100644
index 0000000..80945e9
--- /dev/null
+++ b/third_party/heimdal/lib/roken/writev.c
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+writev(int d, const struct iovec *iov, int iovcnt)
+{
+ ssize_t ret;
+ size_t tot = 0;
+ int i;
+ char *buf, *p;
+
+ for(i = 0; i < iovcnt; ++i)
+ tot += iov[i].iov_len;
+ buf = malloc(tot);
+ if (tot != 0 && buf == NULL) {
+ errno = ENOMEM;
+ return -1;
+ }
+ p = buf;
+ for (i = 0; i < iovcnt; ++i) {
+ memcpy (p, iov[i].iov_base, iov[i].iov_len);
+ p += iov[i].iov_len;
+ }
+ ret = write (d, buf, tot);
+ free (buf);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/roken/xdbm.h b/third_party/heimdal/lib/roken/xdbm.h
new file mode 100644
index 0000000..c2c6c28
--- /dev/null
+++ b/third_party/heimdal/lib/roken/xdbm.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 1995 - 2002 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+/* Generic *dbm include file */
+
+#ifndef __XDBM_H__
+#define __XDBM_H__
+
+#if HAVE_DB_NDBM
+#define DB_DBM_HSEARCH 1
+#include <db.h>
+#elif HAVE_NDBM
+#if defined(HAVE_GDBM_NDBM_H)
+#include <gdbm/ndbm.h>
+#elif defined(HAVE_NDBM_H)
+#include <ndbm.h>
+#endif
+#endif /* HAVE_NDBM */
+
+#endif /* __XDBM_H__ */
diff --git a/third_party/heimdal/lib/roken/xfree.c b/third_party/heimdal/lib/roken/xfree.c
new file mode 100644
index 0000000..c7e30da
--- /dev/null
+++ b/third_party/heimdal/lib/roken/xfree.c
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "roken.h"
+
+void ROKEN_LIB_FUNCTION
+rk_xfree (void *buf)
+{
+ free(buf);
+}
diff --git a/third_party/heimdal/lib/sl/ChangeLog b/third_party/heimdal/lib/sl/ChangeLog
new file mode 100644
index 0000000..485e1dc
--- /dev/null
+++ b/third_party/heimdal/lib/sl/ChangeLog
@@ -0,0 +1,329 @@
+2008-05-05 Love Hörnquist Åstrand <lha@vit.local>
+
+ * drop libss and make_cmds
+
+2007-07-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: roken_rename.h is a dist_ source k
+
+ * Makefile.am: split source files in dist and nodist.
+
+2007-07-10 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: New library version.
+
+2007-06-18 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * sl.c: make compile.
+
+ * sl.c: Pass in pointer to strlen().
+
+ * sl.c (sl_make_argv): use memmove since we are dealing with
+ overlapping strings.
+
+2007-06-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: don't clean yacc/lex files in CLEANFILES,
+ maintainers clean will do that for us.
+
+2007-06-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * slc-gram.y (main): also fclose yyin.
+
+2007-04-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add dependency on slc-gram.h for slc-lex.c, breaks
+ in disttree with make -j
+
+2006-12-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_sl.c: Fix caseing for case-sensitive filesystems
+
+2006-12-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test_sl.c: catch test that should fail but didn't
+
+ * test_sl.c: Test more quoting variants.
+
+ * sl_locl.h: Include <ctype.h>.
+
+ * test_sl.c: test sl_make_argv
+
+ * sl.c (sl_make_argv): Add quoting support (both "" and \ style).
+
+2006-12-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * sl.c: Use strcspn to remove \n from fgets result. Prompted by
+ change by Ray Lai of OpenBSD via Björn Sandell.
+
+2006-10-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am (ES): add roken_rename.h
+
+2006-08-30 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * sl.c (sl_slc_help): remove return
+
+2006-08-28 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * sl.h: Add sl_slc_help.
+
+ * sl.c: Add sl_slc_help.
+
+2005-07-27 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * slc-gram.y (gen_wrapper): use the generated version of name for
+ function, if no function is is used, also use the generated name
+ for the structure name.
+
+2005-06-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * slc-gram.y: fix a merge error
+
+ * slc-gram.y: rename optind to optidx, rename variables to avoid
+ shadowing
+
+ * make_cmds.c: rename optind to optidx, move variable define to
+ avoid shadowing
+
+ * ss.c: rename index to idx
+
+ * sl.c: use rk_UNCONST to un-constify
+
+2005-05-10 Dave Love <fx@gnu.org>
+
+ * slc-lex.l: Include <stdlib.h>.
+
+2005-05-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * sl.c (sl_command_loop): new return code -2 for EOF
+ (sl_loop): treat all return value from sl_command_loop >= 0 as ok, and
+ continue.
+
+2005-04-29 Dave Love <fx@gnu.org>
+
+ * Makefile.am (LDADD): Add libsl.la.
+
+2005-04-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * slc-gram.y: include <config.h> since defines _GNU_SOURCE if
+ needed, avoid asprintf warning
+
+2005-01-21 Dave Love <d.love@dl.ac.uk>
+
+ * slc-gram.y: include <roken.h>
+
+2005-01-09 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * slc-gram.y: cast argument to isalnum to unsigned char
+
+2004-09-22 Johan Danielsson <joda@pdc.kth.se>
+
+ * slc-gram.y: add support for "strings" and "negative-flag" types,
+ plus some usability tweaks and bug fixes
+
+2004-07-05 Johan Danielsson <joda@pdc.kth.se>
+
+ * slc-gram.y: add min_args/max_args checking
+
+2004-06-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * slc-gram.y: pull in <stdlib.h> and <vers.h> to avoid warnings
+
+2004-03-02 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * sl.h: make it possible to use libsl from c++
+ From: Mattias Amnefelt <mattiasa@kth.se>
+
+2002-05-19 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: just link mk_cmds against libsl; avoids libtool
+ problem
+
+2001-07-09 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: add getprogname.c libss.la:add libcom_err.la noted
+ by Leif Johansson <leifj@it.su.se>
+
+2001-05-17 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump versions to 1:2:1 and 1:4:1
+
+2001-05-06 Assar Westerlund <assar@sics.se>
+
+ * roken_rename.h (strdup): add
+
+2001-03-06 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: re do the roken-renaming properly
+
+2001-02-13 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: add more functions to rename
+
+2001-01-26 Johan Danielsson <joda@pdc.kth.se>
+
+ * sl.h: proto
+
+ * sl.c (sl_command_loop): try to handle user pressing C-c
+
+2000-12-11 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (libss_la_LDFLAGS): bump version to 1:2:1
+
+2000-08-19 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: add dependencies for libss/libsl shared libraries
+
+2000-07-25 Johan Danielsson <joda@pdc.kth.se>
+
+ * Makefile.am: bump ss version to 1:1:1
+
+2000-06-27 Assar Westerlund <assar@sics.se>
+
+ * parse.y (yyerror): static-ize
+ * make_cmds.h (error_message, yylex): add prototypes
+ * lex.l: fix prototypes and kill warnings
+
+2000-05-24 Assar Westerlund <assar@sics.se>
+
+ * ss.h (SS_ET_COMMAND_NOT_FOUND): add
+ * ss.c: check allocation and return some other error codes too
+
+2000-04-29 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in: add LIB_tgetent. From Derrick J Brashear
+ <shadow@dementia.org>
+
+2000-04-03 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: set version to 1:0:1
+
+2000-03-07 Assar Westerlund <assar@sics.se>
+
+ * sl.h (SL_BADCOMMAND): define
+ (sl_apropos): add prototype
+
+ * sl.c: mandoc-generation
+ (sl_apropos): stolen from arla
+
+2000-01-06 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: bump both versions to 0:1:0
+
+1999-12-16 Assar Westerlund <assar@sics.se>
+
+ * parse.y (name2number): not used here. remove.
+
+Thu Apr 1 17:03:59 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * make_cmds.c: use getarg
+
+Tue Mar 23 14:36:21 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: don't rename
+
+Sun Mar 21 14:13:29 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: don't roken-rename
+
+Sat Mar 20 03:43:30 1999 Assar Westerlund <assar@sics.se>
+
+ * parse.y: replace return with YYACCEPT
+
+Fri Mar 19 14:53:20 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: add libss; add version-info
+
+Thu Mar 18 15:07:06 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.am: clean lex.c parse.c parse.h
+
+ * Makefile.am: install ss.h
+
+ * Makefile.am: include Makefile.am.common
+
+Thu Mar 11 15:01:01 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * parse.y: prototype for error_message
+
+Tue Feb 9 23:45:37 1999 Johan Danielsson <joda@hella.pdc.kth.se>
+
+ * Makefile.in: add snprintf.o to make_cmds
+
+Sun Nov 22 10:46:23 1998 Assar Westerlund <assar@sics.se>
+
+ * sl.c (sl_command_loop): remove unused variable
+
+ * ss.c (ss_error): remove unused variable
+
+ * make_cmds.c: include err.h
+ (main): remove unused variable
+
+ * Makefile.in (WFLAGS): set
+
+Sun Sep 27 01:28:21 1998 Assar Westerlund <assar@sics.se>
+
+ * make_cmds.c: clean-up and simplification
+
+Mon May 25 02:54:13 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in (clean): try to remove shared library debris
+
+ * Makefile.in: make symlink magic work
+
+Sun Apr 19 10:00:26 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.in: add symlink magic for linux
+
+Sun Apr 5 09:21:43 1998 Assar Westerlund <assar@sics.se>
+
+ * parse.y: define alloca to malloc in case we're using bison but
+ don't have alloca
+
+Sat Mar 28 11:39:00 1998 Assar Westerlund <assar@sics.se>
+
+ * sl.c (sl_loop): s/2/1
+
+Sat Mar 21 00:46:51 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * sl.c (sl_loop): check that there is at least one argument before
+ calling sl_command
+
+Sun Mar 1 05:14:37 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * sl.c (sl_loop): Fix general broken-ness.
+
+ * sl.c: Cleanup printing of help strings.
+
+Thu Feb 26 02:22:02 1998 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: @LEXLIB@
+
+Sat Feb 21 15:18:21 1998 assar westerlund <assar@sics.se>
+
+ * Makefile.in: set YACC and LEX
+
+Mon Feb 16 16:08:25 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * Makefile.am: Some fixes for ss/mk_cmds.
+
+Sun Feb 15 05:12:11 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * Makefile.in: Install libsl under the `libss' name too. Install
+ mk_cmds, and ss.h.
+
+ * make_cmds.c: A mk_cmds clone that creates SL structures.
+
+ * ss.c: SS compatibility functions.
+
+ * sl.c: Move command line split to function `sl_make_argv'.
+
+Tue Feb 3 16:45:44 1998 Johan Danielsson <joda@emma.pdc.kth.se>
+
+ * sl.c: Add sl_command_loop, that is the loop body of sl_loop.
+
+Mon Oct 20 01:13:21 1997 Assar Westerlund <assar@sics.se>
+
+ * sl.c (sl_help): actually use the `help' field of `SL_cmd'
+
diff --git a/third_party/heimdal/lib/sl/Makefile.am b/third_party/heimdal/lib/sl/Makefile.am
new file mode 100644
index 0000000..1213d8c
--- /dev/null
+++ b/third_party/heimdal/lib/sl/Makefile.am
@@ -0,0 +1,50 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+if do_roken_rename
+ES = strtok_r.c snprintf.c strdup.c strupr.c
+endif
+
+AM_CPPFLAGS += $(ROKEN_RENAME)
+
+YFLAGS = -d -o slc-gram.c
+LFLAGS = @FLEXNOUNPUTARGS@
+
+include_HEADERS = sl.h
+
+lib_LTLIBRARIES = libsl.la
+libsl_la_LDFLAGS = -version-info 2:1:2
+
+libsl_la_LIBADD = @LIB_readline@
+
+dist_libsl_la_SOURCES = sl_locl.h sl.c roken_rename.h
+nodist_libsl_la_SOURCES = $(ES)
+
+TESTS = test_sl
+check_PROGRAMS = $(TESTS)
+
+# install these?
+
+libexec_heimdal_PROGRAMS = slc
+
+slc_SOURCES = slc-gram.y slc-lex.l slc.h
+
+CLEANFILES = snprintf.c strtok_r.c strdup.c strupr.c slc-lex.c
+
+LDADD = libsl.la $(LIB_roken)
+
+slc_LDADD = $(LEXLIB) $(LDADD)
+
+strtok_r.c:
+ $(LN_S) $(srcdir)/../roken/strtok_r.c .
+snprintf.c:
+ $(LN_S) $(srcdir)/../roken/snprintf.c .
+strdup.c:
+ $(LN_S) $(srcdir)/../roken/strdup.c .
+strupr.c:
+ $(LN_S) $(srcdir)/../roken/strupr.c .
+
+slc-lex.c: slc-gram.h
+
+EXTRA_DIST = NTMakefile
diff --git a/third_party/heimdal/lib/sl/NTMakefile b/third_party/heimdal/lib/sl/NTMakefile
new file mode 100644
index 0000000..ac398c7
--- /dev/null
+++ b/third_party/heimdal/lib/sl/NTMakefile
@@ -0,0 +1,74 @@
+########################################################################
+#
+# Copyright (c) 2009, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\sl
+
+!include ../../windows/NTMakefile.w32
+
+INCFILES=$(INCDIR)\sl.h
+
+$(LIBSL): $(OBJ)\sl.obj
+ $(LIBCON)
+
+$(BINDIR)\slc.exe: $(OBJ)\slc-gram.obj $(OBJ)\slc-lex.obj
+ $(EXECONLINK) $(LIBROKEN) $(LIBVERS)
+ $(EXEPREP_NOHEIM)
+
+$(OBJ)\slc-gram.c: slc-gram.y
+ $(YACC) -o $@ --defines=$(@R).h slc-gram.y
+
+$(OBJ)\slc-gram.obj: $(OBJ)\slc-gram.c
+ $(C2OBJ) -I$(SRC)\$(RELDIR)
+
+$(OBJ)\slc-lex.c: slc-lex.l
+ $(LEX) -o$@ slc-lex.l
+
+$(OBJ)\slc-lex.obj: $(OBJ)\slc-lex.c
+ $(C2OBJ) -I$(SRC)\$(RELDIR) -DYY_NO_UNISTD_H
+
+$(OBJ)\test_sl.exe: $(OBJ)\test_sl.obj
+ $(EXECONLINK) $(LIBSL) $(LIBVERS) $(LIBROKEN)
+ $(EXEPREP_NODIST)
+
+all:: $(INCFILES) $(LIBSL) $(BINDIR)\slc.exe
+
+clean::
+ -$(RM) $(LIBSL)
+ -$(RM) $(BINDIR)\slc.*
+
+test-binaries: $(OBJ)\test_sl.exe
+
+test-run:
+ cd $(OBJ)
+ -test_sl.exe
+ cd $(SRC)\$(RELDIR)
+
+test:: test-binaries test-run
diff --git a/third_party/heimdal/lib/sl/roken_rename.h b/third_party/heimdal/lib/sl/roken_rename.h
new file mode 100644
index 0000000..a198efc
--- /dev/null
+++ b/third_party/heimdal/lib/sl/roken_rename.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 1998 - 2001 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __roken_rename_h__
+#define __roken_rename_h__
+
+#ifndef HAVE_STRTOK_R
+#define rk_strtok_r _sl_strtok_r
+#endif
+#ifndef HAVE_SNPRINTF
+#define rk_snprintf _sl_snprintf
+#endif
+#ifndef HAVE_ASPRINTF
+#define rk_asprintf _sl_asprintf
+#endif
+#ifndef HAVE_ASNPRINTF
+#define rk_asnprintf _sl_asnprintf
+#endif
+#ifndef HAVE_VASPRINTF
+#define rk_vasprintf _sl_vasprintf
+#endif
+#ifndef HAVE_VASNPRINTF
+#define rk_vasnprintf _sl_vasnprintf
+#endif
+#ifndef HAVE_VSNPRINTF
+#define rk_vsnprintf _sl_vsnprintf
+#endif
+#ifndef HAVE_STRUPR
+#define rk_strupr _sl_strupr
+#endif
+#ifndef HAVE_STRDUP
+#define rk_strdup _sl_strdup
+#endif
+
+#endif /* __roken_rename_h__ */
diff --git a/third_party/heimdal/lib/sl/sl.c b/third_party/heimdal/lib/sl/sl.c
new file mode 100644
index 0000000..b78f9f6
--- /dev/null
+++ b/third_party/heimdal/lib/sl/sl.c
@@ -0,0 +1,499 @@
+/*
+ * Copyright (c) 1995 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include "sl_locl.h"
+#include <setjmp.h>
+
+static void
+mandoc_template(SL_cmd *cmds,
+ const char *extra_string)
+{
+ SL_cmd *c, *prev;
+ char timestr[64], cmd[64];
+ const char *p;
+ time_t t;
+
+ printf(".\\\" Things to fix:\n");
+ printf(".\\\" * correct section, and operating system\n");
+ printf(".\\\" * remove Op from mandatory flags\n");
+ printf(".\\\" * use better macros for arguments (like .Pa for files)\n");
+ printf(".\\\"\n");
+ t = time(NULL);
+ strftime(timestr, sizeof(timestr), "%b %d, %Y", localtime(&t));
+ printf(".Dd %s\n", timestr);
+#ifdef HAVE_GETPROGNAME
+ p = getprogname();
+#else
+ p = "unknown-application";
+#endif
+ strncpy(cmd, p, sizeof(cmd));
+ cmd[sizeof(cmd)-1] = '\0';
+ strupr(cmd);
+
+ printf(".Dt %s SECTION\n", cmd);
+ printf(".Os OPERATING_SYSTEM\n");
+ printf(".Sh NAME\n");
+ printf(".Nm %s\n", p);
+ printf(".Nd\n");
+ printf("in search of a description\n");
+ printf(".Sh SYNOPSIS\n");
+ printf(".Nm\n");
+ for(c = cmds; c->name; ++c) {
+/* if (c->func == NULL)
+ continue; */
+ printf(".Op Fl %s", c->name);
+ printf("\n");
+
+ }
+ if (extra_string && *extra_string)
+ printf (".Ar %s\n", extra_string);
+ printf(".Sh DESCRIPTION\n");
+ printf("Supported options:\n");
+ printf(".Bl -tag -width Ds\n");
+ prev = NULL;
+ for(c = cmds; c->name; ++c) {
+ if (c->func) {
+ if (prev)
+ printf ("\n%s\n", prev->usage);
+
+ printf (".It Fl %s", c->name);
+ prev = c;
+ } else
+ printf (", %s\n", c->name);
+ }
+ if (prev)
+ printf ("\n%s\n", prev->usage);
+
+ printf(".El\n");
+ printf(".\\\".Sh ENVIRONMENT\n");
+ printf(".\\\".Sh FILES\n");
+ printf(".\\\".Sh EXAMPLES\n");
+ printf(".\\\".Sh DIAGNOSTICS\n");
+ printf(".\\\".Sh SEE ALSO\n");
+ printf(".\\\".Sh STANDARDS\n");
+ printf(".\\\".Sh HISTORY\n");
+ printf(".\\\".Sh AUTHORS\n");
+ printf(".\\\".Sh BUGS\n");
+}
+
+SL_cmd *
+sl_match (SL_cmd *cmds, char *cmd, int exactp)
+{
+ SL_cmd *c, *current = NULL, *partial_cmd = NULL;
+ int partial_match = 0;
+
+ for (c = cmds; c->name; ++c) {
+ if (c->func)
+ current = c;
+ if (strcmp (cmd, c->name) == 0)
+ return current;
+ else if (strncmp (cmd, c->name, strlen(cmd)) == 0 &&
+ partial_cmd != current) {
+ ++partial_match;
+ partial_cmd = current;
+ }
+ }
+ if (partial_match == 1 && !exactp)
+ return partial_cmd;
+ else
+ return NULL;
+}
+
+void
+sl_help (SL_cmd *cmds, int argc, char **argv)
+{
+ SL_cmd *c, *prev_c;
+
+ if (getenv("SLMANDOC")) {
+ mandoc_template(cmds, NULL);
+ return;
+ }
+
+ if (argc == 1) {
+ prev_c = NULL;
+ for (c = cmds; c->name; ++c) {
+ if (c->func) {
+ if(prev_c)
+ printf ("\n\t%s%s", prev_c->usage ? prev_c->usage : "",
+ prev_c->usage ? "\n" : "");
+ prev_c = c;
+ printf ("%s", c->name);
+ } else
+ printf (", %s", c->name);
+ }
+ if(prev_c)
+ printf ("\n\t%s%s", prev_c->usage ? prev_c->usage : "",
+ prev_c->usage ? "\n" : "");
+ } else {
+ c = sl_match (cmds, argv[1], 0);
+ if (c == NULL)
+ printf ("No such command: %s. "
+ "Try \"help\" for a list of all commands\n",
+ argv[1]);
+ else {
+ printf ("%s\t%s\n", c->name, c->usage);
+ if(c->help && *c->help)
+ printf ("%s\n", c->help);
+ if((++c)->name && c->func == NULL) {
+ printf ("Synonyms:");
+ while (c->name && c->func == NULL)
+ printf ("\t%s", (c++)->name);
+ printf ("\n");
+ }
+ }
+ }
+}
+
+#ifdef HAVE_READLINE
+
+char *readline(char *prompt);
+void add_history(char *p);
+
+#else
+
+static char *
+readline(char *prompt)
+{
+ char buf[BUFSIZ];
+ printf ("%s", prompt);
+ fflush (stdout);
+ if(fgets(buf, sizeof(buf), stdin) == NULL)
+ return NULL;
+ buf[strcspn(buf, "\r\n")] = '\0';
+ return strdup(buf);
+}
+
+static void
+add_history(char *p)
+{
+}
+
+#endif
+
+int
+sl_command(SL_cmd *cmds, int argc, char **argv)
+{
+ SL_cmd *c;
+ c = sl_match (cmds, argv[0], 0);
+ if (c == NULL)
+ return -1;
+ return (*c->func)(argc, argv);
+}
+
+struct sl_data {
+ int max_count;
+ char **ptr;
+};
+
+int
+sl_make_argv(char *line, int *ret_argc, char ***ret_argv)
+{
+ char *p, *begining;
+ int argc, nargv;
+ char **argv;
+ int quote = 0;
+
+ nargv = 10;
+ argv = malloc(nargv * sizeof(*argv));
+ if(argv == NULL)
+ return ENOMEM;
+ argc = 0;
+
+ p = line;
+
+ while(isspace((unsigned char)*p))
+ p++;
+ begining = p;
+
+ while (1) {
+ if (*p == '\0') {
+ ;
+ } else if (*p == '"') {
+ quote = !quote;
+ memmove(&p[0], &p[1], strlen(&p[1]) + 1);
+ continue;
+ } else if (*p == '\\') {
+ if (p[1] == '\0')
+ goto failed;
+ memmove(&p[0], &p[1], strlen(&p[1]) + 1);
+ p += 1;
+ continue;
+ } else if (quote || !isspace((unsigned char)*p)) {
+ p++;
+ continue;
+ } else
+ *p++ = '\0';
+ if (quote)
+ goto failed;
+ if(argc == nargv - 1) {
+ char **tmp;
+ nargv *= 2;
+ tmp = realloc (argv, nargv * sizeof(*argv));
+ if (tmp == NULL) {
+ free(argv);
+ return ENOMEM;
+ }
+ argv = tmp;
+ }
+ argv[argc++] = begining;
+ while(isspace((unsigned char)*p))
+ p++;
+ if (*p == '\0')
+ break;
+ begining = p;
+ }
+ argv[argc] = NULL;
+ *ret_argc = argc;
+ *ret_argv = argv;
+ return 0;
+failed:
+ free(argv);
+ return ERANGE;
+}
+
+static jmp_buf sl_jmp;
+
+static void sl_sigint(int sig)
+{
+ longjmp(sl_jmp, 1);
+}
+
+static char *sl_readline(const char *prompt)
+{
+ char *s;
+ void (*old)(int);
+ old = signal(SIGINT, sl_sigint);
+ if(setjmp(sl_jmp))
+ printf("\n");
+ s = readline(rk_UNCONST(prompt));
+ signal(SIGINT, old);
+ return s;
+}
+
+/* return values:
+ * 0 on success,
+ * -1 on fatal error,
+ * -2 if EOF, or
+ * return value of command */
+int
+sl_command_loop(SL_cmd *cmds, const char *prompt, void **data)
+{
+ int ret = 0;
+ char *buf;
+ int argc;
+ char **argv;
+
+ buf = sl_readline(prompt);
+ if(buf == NULL)
+ return -2;
+
+ if(*buf)
+ add_history(buf);
+ ret = sl_make_argv(buf, &argc, &argv);
+ if(ret) {
+ fprintf(stderr, "sl_loop: out of memory\n");
+ free(buf);
+ return -1;
+ }
+ if (argc >= 1) {
+ ret = sl_command(cmds, argc, argv);
+ if(ret == -1) {
+ sl_did_you_mean(cmds, argv[0]);
+ ret = 0;
+ }
+ }
+ free(buf);
+ free(argv);
+ return ret;
+}
+
+int
+sl_loop(SL_cmd *cmds, const char *prompt)
+{
+ void *data = NULL;
+ int ret;
+ while((ret = sl_command_loop(cmds, prompt, &data)) >= 0)
+ ;
+ return ret;
+}
+
+void
+sl_apropos (SL_cmd *cmd, const char *topic)
+{
+ for (; cmd->name != NULL; ++cmd)
+ if (cmd->usage != NULL && strstr(cmd->usage, topic) != NULL)
+ printf ("%-20s%s\n", cmd->name, cmd->usage);
+}
+
+/*
+ * Help to be used with slc.
+ */
+
+void
+sl_slc_help (SL_cmd *cmds, int argc, char **argv)
+{
+ if(argc == 0) {
+ sl_help(cmds, 1, argv - 1 /* XXX */);
+ } else {
+ SL_cmd *c = sl_match (cmds, argv[0], 0);
+ if(c == NULL) {
+ fprintf (stderr, "No such command: %s. "
+ "Try \"help\" for a list of commands\n",
+ argv[0]);
+ } else {
+ if(c->func) {
+ static char help[] = "--help";
+ char *fake[3];
+ fake[0] = argv[0];
+ fake[1] = help;
+ fake[2] = NULL;
+ (*c->func)(2, fake);
+ fprintf(stderr, "\n");
+ }
+ if(c->help && *c->help)
+ fprintf (stderr, "%s\n", c->help);
+ if((++c)->name && c->func == NULL) {
+ int f = 0;
+ fprintf (stderr, "Synonyms:");
+ while (c->name && c->func == NULL) {
+ fprintf (stderr, "%s%s", f ? ", " : " ", (c++)->name);
+ f = 1;
+ }
+ fprintf (stderr, "\n");
+ }
+ }
+ }
+}
+
+/* OptimalStringAlignmentDistance */
+
+static int
+osad(const char *s1, const char *s2)
+{
+ size_t l1 = strlen(s1), l2 = strlen(s2), i, j;
+ int *row0, *row1, *row2, *tmp, cost;
+
+ row0 = calloc(sizeof(int), l2 + 1);
+ row1 = calloc(sizeof(int), l2 + 1);
+ row2 = calloc(sizeof(int), l2 + 1);
+
+ for (j = 0; j < l2 + 1; j++)
+ row1[j] = j;
+
+ for (i = 0; i < l1; i++) {
+
+ row2[0] = i + 1;
+
+ for (j = 0; j < l2; j++) {
+
+ row2[j + 1] = row1[j] + (s1[i] != s2[j]); /* substitute */
+
+ if (row2[j + 1] > row1[j + 1] + 1) /* delete */
+ row2[j + 1] = row1[j + 1] + 1;
+ if (row2[j + 1] > row2[j] + 1) /* insert */
+ row2[j + 1] = row2[j] + 1;
+ if (j > 0 && i > 0 && s1[i - 1] != s2[j - 1] && s1[i - 1] == s2[j] && s1[i] == s2[j - 1] && row2[j + 1] < row0[j - 1]) /* transposition */
+ row2[j + 1] = row0[j - 1] + 1;
+ }
+
+ tmp = row0;
+ row0 = row1;
+ row1 = row2;
+ row2 = tmp;
+ }
+
+ cost = row1[l2];
+
+ free(row0);
+ free(row1);
+ free(row2);
+
+ return cost;
+}
+
+/**
+ * Will propose a list of command that are almost matching the command
+ * used, if there is no matching, will ask the user to use "help".
+ *
+ * @param cmds command array to use for matching
+ * @param match the command that didn't exists
+ */
+
+void
+sl_did_you_mean(SL_cmd *cmds, const char *match)
+{
+ int *metrics, best_match = INT_MAX;
+ SL_cmd *c;
+ size_t n;
+
+ for (n = 0, c = cmds; c->name; c++, n++)
+ ;
+ if (n == 0)
+ return;
+ metrics = calloc(n, sizeof(metrics[0]));
+ if (metrics == NULL)
+ return;
+
+ for (n = 0; cmds[n].name; n++) {
+ metrics[n] = osad(match, cmds[n].name);
+ if (metrics[n] < best_match)
+ best_match = metrics[n];
+ }
+ if (best_match == INT_MAX) {
+ free(metrics);
+ fprintf(stderr, "What kind of command is %s", match);
+ return;
+ }
+
+ /* if match distance is low, propose that for the user */
+ if (best_match < 7) {
+
+ fprintf(stderr, "error: %s is not a known command, did you mean ?\n", match);
+ for (n = 0; cmds[n].name; n++) {
+ if (metrics[n] == best_match) {
+ fprintf(stderr, "\t%s\n", cmds[n].name);
+ }
+ }
+ fprintf(stderr, "\n");
+
+ } else {
+
+ fprintf(stderr, "error: %s is not a command, use \"help\" for more list of commands.\n", match);
+ }
+
+ free(metrics);
+
+ return;
+}
diff --git a/third_party/heimdal/lib/sl/sl.h b/third_party/heimdal/lib/sl/sl.h
new file mode 100644
index 0000000..affdb6e
--- /dev/null
+++ b/third_party/heimdal/lib/sl/sl.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 1995 - 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef _SL_H
+#define _SL_H
+
+#define SL_BADCOMMAND -1
+
+typedef int (*cmd_func)(int, char **);
+
+struct sl_cmd {
+ const char *name;
+ cmd_func func;
+ const char *usage;
+ const char *help;
+};
+
+typedef struct sl_cmd SL_cmd;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void sl_help (SL_cmd *, int argc, char **argv);
+int sl_loop (SL_cmd *, const char *prompt);
+int sl_command_loop (SL_cmd *cmds, const char *prompt, void **data);
+int sl_command (SL_cmd *cmds, int argc, char **argv);
+int sl_make_argv(char*, int*, char***);
+void sl_apropos (SL_cmd *cmd, const char *topic);
+SL_cmd *sl_match (SL_cmd *cmds, char *cmd, int exactp);
+void sl_slc_help (SL_cmd *cmds, int argc, char **argv);
+void sl_did_you_mean(SL_cmd *cmds, const char *match);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _SL_H */
diff --git a/third_party/heimdal/lib/sl/sl_locl.h b/third_party/heimdal/lib/sl/sl_locl.h
new file mode 100644
index 0000000..50eeade
--- /dev/null
+++ b/third_party/heimdal/lib/sl/sl_locl.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#include <config.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <ctype.h>
+
+#include <roken.h>
+
+#include <sl.h>
diff --git a/third_party/heimdal/lib/sl/slc-gram.y b/third_party/heimdal/lib/sl/slc-gram.y
new file mode 100644
index 0000000..38045c1
--- /dev/null
+++ b/third_party/heimdal/lib/sl/slc-gram.y
@@ -0,0 +1,791 @@
+%{
+/*
+ * Copyright (c) 2004-2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <err.h>
+#include <ctype.h>
+#include <limits.h>
+#include <getarg.h>
+#include <vers.h>
+#include <roken.h>
+
+#include "slc.h"
+extern FILE *yyin;
+extern struct assignment *assignment;
+
+/* Declarations for Bison:
+ */
+#define YYMALLOC malloc
+#define YYFREE free
+
+%}
+
+%union {
+ char *string;
+ struct assignment *assignment;
+}
+
+%token <string> LITERAL
+%token <string> STRING
+%type <assignment> assignment assignments
+
+%start start
+
+%%
+
+start : assignments
+ {
+ assignment = $1;
+ }
+ ;
+
+assignments : assignment assignments
+ {
+ $1->next = $2;
+ $$ = $1;
+ }
+ | assignment
+ ;
+
+assignment : LITERAL '=' STRING
+ {
+ $$ = malloc(sizeof(*$$));
+ $$->name = $1;
+ $$->type = a_value;
+ $$->lineno = lineno;
+ $$->u.value = $3;
+ $$->next = NULL;
+ }
+ | LITERAL '=' '{' assignments '}'
+ {
+ $$ = malloc(sizeof(*$$));
+ $$->name = $1;
+ $$->type = a_assignment;
+ $$->lineno = lineno;
+ $$->u.assignment = $4;
+ $$->next = NULL;
+ }
+ ;
+
+%%
+char *filename;
+FILE *cfile, *hfile;
+int error_flag;
+struct assignment *assignment;
+
+
+static void
+ex(struct assignment *a, const char *fmt, ...)
+{
+ va_list ap;
+ fprintf(stderr, "%s:%d: ", a->name, a->lineno);
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+ fprintf(stderr, "\n");
+}
+
+
+
+static int
+check_option(struct assignment *as)
+{
+ struct assignment *a;
+ int seen_long = 0;
+ int seen_name = 0;
+ int seen_short = 0;
+ int seen_type = 0;
+ int seen_argument = 0;
+ int seen_help = 0;
+ int seen_default = 0;
+ int ret = 0;
+
+ for(a = as; a != NULL; a = a->next) {
+ if(strcmp(a->name, "long") == 0)
+ seen_long++;
+ else if(strcmp(a->name, "short") == 0)
+ seen_short++;
+ else if(strcmp(a->name, "name") == 0)
+ seen_name++;
+ else if(strcmp(a->name, "type") == 0)
+ seen_type++;
+ else if(strcmp(a->name, "argument") == 0)
+ seen_argument++;
+ else if(strcmp(a->name, "help") == 0)
+ seen_help++;
+ else if(strcmp(a->name, "default") == 0)
+ seen_default++;
+ else {
+ ex(a, "unknown name %s", a->name);
+ ret++;
+ }
+ }
+ if(seen_long == 0 && seen_short == 0) {
+ ex(as, "neither long nor short option");
+ ret++;
+ }
+ if (seen_long == 0 && seen_name == 0) {
+ ex(as, "either of long or name option must be used");
+ ret++;
+ }
+ if(seen_long > 1) {
+ ex(as, "multiple long options");
+ ret++;
+ }
+ if(seen_short > 1) {
+ ex(as, "multiple short options");
+ ret++;
+ }
+ if(seen_type > 1) {
+ ex(as, "multiple types");
+ ret++;
+ }
+ if(seen_argument > 1) {
+ ex(as, "multiple arguments");
+ ret++;
+ }
+ if(seen_help > 1) {
+ ex(as, "multiple help strings");
+ ret++;
+ }
+ if(seen_default > 1) {
+ ex(as, "multiple default values");
+ ret++;
+ }
+ return ret;
+}
+
+static int
+check_command(struct assignment *as)
+{
+ struct assignment *a;
+ int seen_name = 0;
+ int seen_function = 0;
+ int seen_help = 0;
+ int seen_argument = 0;
+ int seen_minargs = 0;
+ int seen_maxargs = 0;
+ int ret = 0;
+ for(a = as; a != NULL; a = a->next) {
+ if(strcmp(a->name, "name") == 0)
+ seen_name++;
+ else if(strcmp(a->name, "function") == 0) {
+ seen_function++;
+ } else if(strcmp(a->name, "option") == 0)
+ ret += check_option(a->u.assignment);
+ else if(strcmp(a->name, "help") == 0) {
+ seen_help++;
+ } else if(strcmp(a->name, "argument") == 0) {
+ seen_argument++;
+ } else if(strcmp(a->name, "min_args") == 0) {
+ seen_minargs++;
+ } else if(strcmp(a->name, "max_args") == 0) {
+ seen_maxargs++;
+ } else {
+ ex(a, "unknown name: %s", a->name);
+ ret++;
+ }
+ }
+ if(seen_name == 0) {
+ ex(as, "no command name");
+ ret++;
+ }
+ if(seen_function > 1) {
+ ex(as, "multiple function names");
+ ret++;
+ }
+ if(seen_help > 1) {
+ ex(as, "multiple help strings");
+ ret++;
+ }
+ if(seen_argument > 1) {
+ ex(as, "multiple argument strings");
+ ret++;
+ }
+ if(seen_minargs > 1) {
+ ex(as, "multiple min_args strings");
+ ret++;
+ }
+ if(seen_maxargs > 1) {
+ ex(as, "multiple max_args strings");
+ ret++;
+ }
+
+ return ret;
+}
+
+static int
+check(struct assignment *as)
+{
+ struct assignment *a;
+ int ret = 0;
+ for(a = as; a != NULL; a = a->next) {
+ if (strcmp(a->name, "command") != 0) {
+ fprintf(stderr, "unknown type %s line %d\n", a->name, a->lineno);
+ ret++;
+ continue;
+ }
+ if(a->type != a_assignment) {
+ fprintf(stderr, "bad command definition %s line %d\n", a->name, a->lineno);
+ ret++;
+ continue;
+ }
+ ret += check_command(a->u.assignment);
+ }
+ return ret;
+}
+
+static struct assignment *
+find_next(struct assignment *as, const char *name)
+{
+ for(as = as->next; as != NULL; as = as->next) {
+ if(strcmp(as->name, name) == 0)
+ return as;
+ }
+ return NULL;
+}
+
+static struct assignment *
+find(struct assignment *as, const char *name)
+{
+ for(; as != NULL; as = as->next) {
+ if(strcmp(as->name, name) == 0)
+ return as;
+ }
+ return NULL;
+}
+
+static void
+space(FILE *f, int level)
+{
+ fprintf(f, "%*.*s", level * 4, level * 4, " ");
+}
+
+static void
+cprint(int level, const char *fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ space(cfile, level);
+ vfprintf(cfile, fmt, ap);
+ va_end(ap);
+}
+
+static void
+hprint(int level, const char *fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ space(hfile, level);
+ vfprintf(hfile, fmt, ap);
+ va_end(ap);
+}
+
+static void gen_name(char *str);
+
+static void
+gen_command(struct assignment *as)
+{
+ struct assignment *a, *b;
+ char *f;
+ a = find(as, "name");
+ f = strdup(a->u.value);
+ gen_name(f);
+ cprint(1, " { ");
+ fprintf(cfile, "\"%s\", ", a->u.value);
+ fprintf(cfile, "%s_wrap, ", f);
+ free(f);
+ b = find(as, "argument");
+ if(b)
+ fprintf(cfile, "\"%s %s\", ", a->u.value, b->u.value);
+ else
+ fprintf(cfile, "\"%s\", ", a->u.value);
+ b = find(as, "help");
+ if(b)
+ fprintf(cfile, "\"%s\"", b->u.value);
+ else
+ fprintf(cfile, "NULL");
+ fprintf(cfile, " },\n");
+ for(a = a->next; a != NULL; a = a->next)
+ if(strcmp(a->name, "name") == 0)
+ cprint(1, " { \"%s\", NULL, NULL, NULL },\n", a->u.value);
+ cprint(0, "\n");
+}
+
+static void
+gen_name(char *str)
+{
+ char *p;
+ for(p = str; *p != '\0'; p++)
+ if(!isalnum((unsigned char)*p))
+ *p = '_';
+}
+
+static char *
+make_name(struct assignment *as)
+{
+ struct assignment *lopt;
+ struct assignment *type;
+ char *s;
+ int ret;
+
+ lopt = find(as, "long");
+ if(lopt == NULL)
+ lopt = find(as, "name");
+ if(lopt == NULL)
+ return NULL;
+
+ type = find(as, "type");
+ if(strcmp(type->u.value, "-flag") == 0)
+ ret = asprintf(&s, "%s_flag", lopt->u.value);
+ else
+ ret = asprintf(&s, "%s_%s", lopt->u.value, type->u.value);
+ if (ret == -1)
+ return NULL;
+ gen_name(s);
+ return s;
+}
+
+
+static void defval_int(const char *name, struct assignment *defval)
+{
+ if(defval != NULL)
+ cprint(1, "opt.%s = %s;\n", name, defval->u.value);
+ else
+ cprint(1, "opt.%s = 0;\n", name);
+}
+static void defval_neg_flag(const char *name, struct assignment *defval)
+{
+ if(defval != NULL)
+ cprint(1, "opt.%s = %s;\n", name, defval->u.value);
+ else
+ cprint(1, "opt.%s = 1;\n", name);
+}
+static void defval_string(const char *name, struct assignment *defval)
+{
+ if(defval != NULL)
+ cprint(1, "opt.%s = (char *)(uintptr_t)\"%s\";\n", name, defval->u.value);
+ else
+ cprint(1, "opt.%s = NULL;\n", name);
+}
+static void defval_strings(const char *name, struct assignment *defval)
+{
+ cprint(1, "opt.%s.num_strings = 0;\n", name);
+ cprint(1, "opt.%s.strings = NULL;\n", name);
+}
+
+static void free_strings(const char *name)
+{
+ cprint(1, "free_getarg_strings (&opt.%s);\n", name);
+}
+
+struct type_handler {
+ const char *typename;
+ const char *c_type;
+ const char *getarg_type;
+ void (*defval)(const char*, struct assignment*);
+ void (*free)(const char*);
+} type_handlers[] = {
+ { "integer",
+ "int",
+ "arg_integer",
+ defval_int,
+ NULL
+ },
+ { "string",
+ "char*",
+ "arg_string",
+ defval_string,
+ NULL
+ },
+ { "strings",
+ "struct getarg_strings",
+ "arg_strings",
+ defval_strings,
+ free_strings
+ },
+ { "flag",
+ "int",
+ "arg_flag",
+ defval_int,
+ NULL
+ },
+ { "-flag",
+ "int",
+ "arg_negative_flag",
+ defval_neg_flag,
+ NULL
+ },
+ { NULL, NULL, NULL, NULL, NULL }
+};
+
+static struct type_handler *find_handler(struct assignment *type)
+{
+ struct type_handler *th;
+ for(th = type_handlers; th->typename != NULL; th++)
+ if(strcmp(type->u.value, th->typename) == 0)
+ return th;
+ ex(type, "unknown type \"%s\"", type->u.value);
+ exit(1);
+}
+
+static void
+gen_options(struct assignment *opt1, const char *name)
+{
+ struct assignment *tmp;
+
+ hprint(0, "struct %s_options {\n", name);
+
+ for(tmp = opt1;
+ tmp != NULL;
+ tmp = find_next(tmp, "option")) {
+ struct assignment *type;
+ struct type_handler *th;
+ char *s;
+
+ s = make_name(tmp->u.assignment);
+ type = find(tmp->u.assignment, "type");
+ th = find_handler(type);
+ hprint(1, "%s %s;\n", th->c_type, s);
+ free(s);
+ }
+ hprint(0, "};\n");
+}
+
+static void
+gen_wrapper(struct assignment *as)
+{
+ struct assignment *name;
+ struct assignment *arg;
+ struct assignment *opt1;
+ struct assignment *function;
+ struct assignment *tmp;
+ char *n, *f;
+ int nargs = 0;
+ int narguments = 0;
+
+ name = find(as, "name");
+ n = strdup(name->u.value);
+ gen_name(n);
+ arg = find(as, "argument");
+ if (arg)
+ narguments++;
+ opt1 = find(as, "option");
+ function = find(as, "function");
+ if(function)
+ f = function->u.value;
+ else
+ f = n;
+
+
+ if(opt1 != NULL) {
+ gen_options(opt1, n);
+ hprint(0, "int %s(struct %s_options*, int, char **);\n", f, n);
+ } else {
+ hprint(0, "int %s(void*, int, char **);\n", f);
+ }
+
+ fprintf(cfile, "static int\n");
+ fprintf(cfile, "%s_wrap(int argc, char **argv)\n", n);
+ fprintf(cfile, "{\n");
+ if(opt1 != NULL)
+ cprint(1, "struct %s_options opt;\n", n);
+ cprint(1, "int ret;\n");
+ cprint(1, "int optidx = 0;\n");
+ cprint(1, "struct getargs args[] = {\n");
+ for(tmp = find(as, "option");
+ tmp != NULL;
+ tmp = find_next(tmp, "option")) {
+ struct assignment *type = find(tmp->u.assignment, "type");
+ struct assignment *lopt = find(tmp->u.assignment, "long");
+ struct assignment *sopt = find(tmp->u.assignment, "short");
+ struct assignment *aarg = find(tmp->u.assignment, "argument");
+ struct assignment *help = find(tmp->u.assignment, "help");
+
+ struct type_handler *th;
+
+ cprint(2, "{ ");
+ if(lopt)
+ fprintf(cfile, "\"%s\", ", lopt->u.value);
+ else
+ fprintf(cfile, "NULL, ");
+ if(sopt)
+ fprintf(cfile, "'%c', ", *sopt->u.value);
+ else
+ fprintf(cfile, "0, ");
+ th = find_handler(type);
+ fprintf(cfile, "%s, ", th->getarg_type);
+ fprintf(cfile, "NULL, ");
+ if(help)
+ fprintf(cfile, "\"%s\", ", help->u.value);
+ else
+ fprintf(cfile, "NULL, ");
+ if(aarg) {
+ fprintf(cfile, "\"%s\"", aarg->u.value);
+ narguments++;
+ } else
+ fprintf(cfile, "NULL");
+ fprintf(cfile, " },\n");
+ }
+ cprint(2, "{ \"help\", 'h', arg_flag, NULL, NULL, NULL }\n");
+ cprint(1, "};\n");
+ cprint(1, "int help_flag = 0;\n");
+
+ for(tmp = find(as, "option");
+ tmp != NULL;
+ tmp = find_next(tmp, "option")) {
+ char *s;
+ struct assignment *type = find(tmp->u.assignment, "type");
+
+ struct assignment *defval = find(tmp->u.assignment, "default");
+
+ struct type_handler *th;
+
+ s = make_name(tmp->u.assignment);
+ th = find_handler(type);
+ (*th->defval)(s, defval);
+ free(s);
+ }
+
+ for(tmp = find(as, "option");
+ tmp != NULL;
+ tmp = find_next(tmp, "option")) {
+ char *s;
+ s = make_name(tmp->u.assignment);
+ cprint(1, "args[%d].value = &opt.%s;\n", nargs++, s);
+ free(s);
+ }
+ cprint(1, "args[%d].value = &help_flag;\n", nargs++);
+ cprint(1, "if(getarg(args, %d, argc, argv, &optidx))\n", nargs);
+ cprint(2, "goto usage;\n");
+
+ {
+ int min_args = -1;
+ int max_args = -1;
+ char *end;
+ if(narguments == 0) {
+ max_args = 0;
+ } else {
+ if((tmp = find(as, "min_args")) != NULL) {
+ min_args = strtol(tmp->u.value, &end, 0);
+ if(*end != '\0') {
+ ex(tmp, "min_args is not numeric");
+ exit(1);
+ }
+ if(min_args < 0) {
+ ex(tmp, "min_args must be non-negative");
+ exit(1);
+ }
+ }
+ if((tmp = find(as, "max_args")) != NULL) {
+ max_args = strtol(tmp->u.value, &end, 0);
+ if(*end != '\0') {
+ ex(tmp, "max_args is not numeric");
+ exit(1);
+ }
+ if(max_args < 0) {
+ ex(tmp, "max_args must be non-negative");
+ exit(1);
+ }
+ }
+ }
+ if(min_args != -1 || max_args != -1) {
+ if(min_args == max_args) {
+ cprint(1, "if(argc - optidx != %d) {\n",
+ min_args);
+ cprint(2, "fprintf(stderr, \"Need exactly %u parameters (%%u given).\\n\\n\", argc - optidx);\n", min_args);
+ cprint(2, "goto usage;\n");
+ cprint(1, "}\n");
+ } else {
+ if(max_args != -1) {
+ cprint(1, "if(argc - optidx > %d) {\n", max_args);
+ cprint(2, "fprintf(stderr, \"Arguments given (%%u) are more than expected (%u).\\n\\n\", argc - optidx);\n", max_args);
+ cprint(2, "goto usage;\n");
+ cprint(1, "}\n");
+ }
+ if(min_args != -1) {
+ cprint(1, "if(argc - optidx < %d) {\n", min_args);
+ cprint(2, "fprintf(stderr, \"Arguments given (%%u) are less than expected (%u).\\n\\n\", argc - optidx);\n", min_args);
+ cprint(2, "goto usage;\n");
+ cprint(1, "}\n");
+ }
+ }
+ }
+ }
+
+ cprint(1, "if(help_flag)\n");
+ cprint(2, "goto usage;\n");
+
+ cprint(1, "ret = %s(%s, argc - optidx, argv + optidx);\n",
+ f, opt1 ? "&opt": "NULL");
+
+ /* free allocated data */
+ for(tmp = find(as, "option");
+ tmp != NULL;
+ tmp = find_next(tmp, "option")) {
+ char *s;
+ struct assignment *type = find(tmp->u.assignment, "type");
+ struct type_handler *th;
+ th = find_handler(type);
+ if(th->free == NULL)
+ continue;
+ s = make_name(tmp->u.assignment);
+ (*th->free)(s);
+ free(s);
+ }
+ cprint(1, "return ret;\n");
+
+ cprint(0, "usage:\n");
+ cprint(1, "arg_printusage (args, %d, \"%s\", \"%s\");\n", nargs,
+ name->u.value, arg ? arg->u.value : "");
+ /* free allocated data */
+ for(tmp = find(as, "option");
+ tmp != NULL;
+ tmp = find_next(tmp, "option")) {
+ char *s;
+ struct assignment *type = find(tmp->u.assignment, "type");
+ struct type_handler *th;
+ th = find_handler(type);
+ if(th->free == NULL)
+ continue;
+ s = make_name(tmp->u.assignment);
+ (*th->free)(s);
+ free(s);
+ }
+ cprint(1, "return 0;\n");
+ cprint(0, "}\n");
+ cprint(0, "\n");
+ free(n);
+}
+
+char cname[PATH_MAX];
+char hname[PATH_MAX];
+
+static void
+gen(struct assignment *as)
+{
+ struct assignment *a;
+ cprint(0, "#include <stdio.h>\n");
+ cprint(0, "#include <stdint.h>\n");
+ cprint(0, "#include <getarg.h>\n");
+ cprint(0, "#include <sl.h>\n");
+ cprint(0, "#include \"%s\"\n\n", hname);
+
+ hprint(0, "#include <stdio.h>\n");
+ hprint(0, "#include <sl.h>\n");
+ hprint(0, "\n");
+
+
+ for(a = as; a != NULL; a = a->next)
+ gen_wrapper(a->u.assignment);
+
+ cprint(0, "SL_cmd commands[] = {\n");
+ for(a = as; a != NULL; a = a->next)
+ gen_command(a->u.assignment);
+ cprint(1, "{ NULL, NULL, NULL, NULL }\n");
+ cprint(0, "};\n");
+
+ hprint(0, "extern SL_cmd commands[];\n");
+}
+
+int version_flag;
+int help_flag;
+struct getargs args[] = {
+ { "version", 0, arg_flag, &version_flag, NULL, NULL },
+ { "help", 0, arg_flag, &help_flag, NULL, NULL }
+};
+int num_args = sizeof(args) / sizeof(args[0]);
+
+static void
+usage(int code)
+{
+ arg_printusage(args, num_args, NULL, "command-table");
+ exit(code);
+}
+
+int
+main(int argc, char **argv)
+{
+ char *p;
+
+ int optidx = 0;
+
+ setprogname(argv[0]);
+ if(getarg(args, num_args, argc, argv, &optidx))
+ usage(1);
+ if(help_flag)
+ usage(0);
+ if(version_flag) {
+ print_version(NULL);
+ exit(0);
+ }
+
+ if(argc == optidx)
+ usage(1);
+
+ filename = argv[optidx];
+ yyin = fopen(filename, "r");
+ if(yyin == NULL)
+ err(1, "%s", filename);
+ p = strrchr(filename, '/');
+ if(p)
+ strlcpy(cname, p + 1, sizeof(cname));
+ else
+ strlcpy(cname, filename, sizeof(cname));
+ p = strrchr(cname, '.');
+ if(p)
+ *p = '\0';
+ strlcpy(hname, cname, sizeof(hname));
+ strlcat(cname, ".c", sizeof(cname));
+ strlcat(hname, ".h", sizeof(hname));
+ yyparse();
+ if(error_flag)
+ exit(1);
+ if(check(assignment) == 0) {
+ cfile = fopen(cname, "w");
+ if(cfile == NULL)
+ err(1, "%s", cname);
+ hfile = fopen(hname, "w");
+ if(hfile == NULL)
+ err(1, "%s", hname);
+ gen(assignment);
+ fclose(cfile);
+ fclose(hfile);
+ }
+ fclose(yyin);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/sl/slc-lex.l b/third_party/heimdal/lib/sl/slc-lex.l
new file mode 100644
index 0000000..3a37302
--- /dev/null
+++ b/third_party/heimdal/lib/sl/slc-lex.l
@@ -0,0 +1,158 @@
+%{
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#undef ECHO
+
+#include <stdio.h>
+#include <string.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include "slc.h"
+#include "slc-gram.h"
+unsigned lineno = 1;
+
+static void handle_comment(void);
+static char * handle_string(void);
+
+#define YY_NO_UNPUT
+
+#undef ECHO
+
+%}
+
+%%
+[A-Za-z][-A-Za-z0-9_]* {
+ yylval.string = strdup ((const char *)yytext);
+ return LITERAL;
+ }
+"\"" { yylval.string = handle_string(); return STRING; }
+\n { ++lineno; }
+\/\* { handle_comment(); }
+[={}] { return *yytext; }
+[ \t] ;
+%%
+
+void
+error_message (const char *format, ...)
+{
+ va_list args;
+
+ va_start (args, format);
+ fprintf (stderr, "%s:%d: ", filename, lineno);
+ vfprintf (stderr, format, args);
+ va_end (args);
+ error_flag++;
+}
+
+void
+yyerror (const char *s)
+{
+ error_message("%s\n", s);
+}
+
+static void
+handle_comment(void)
+{
+ int c;
+ int start_lineno = lineno;
+ int level = 1;
+ int seen_star = 0;
+ int seen_slash = 0;
+ while((c = input()) != EOF) {
+ if(c == '/') {
+ if(seen_star) {
+ if(--level == 0)
+ return;
+ seen_star = 0;
+ continue;
+ }
+ seen_slash = 1;
+ continue;
+ } else if(c == '*') {
+ if(seen_slash) {
+ level++;
+ seen_star = seen_slash = 0;
+ continue;
+ }
+ seen_star = 1;
+ continue;
+ }
+ seen_star = seen_slash = 0;
+ if(c == '\n') {
+ lineno++;
+ continue;
+ }
+ }
+ if(c == EOF)
+ error_message("unterminated comment, possibly started on line %d\n", start_lineno);
+}
+
+static char *
+handle_string(void)
+{
+ char x[1024];
+ int i = 0;
+ int c;
+ int quote = 0;
+ while((c = input()) != EOF){
+ if(quote) {
+ x[i++] = '\\';
+ x[i++] = c;
+ quote = 0;
+ continue;
+ }
+ if(c == '\n'){
+ error_message("unterminated string");
+ lineno++;
+ break;
+ }
+ if(c == '\\'){
+ quote++;
+ continue;
+ }
+ if(c == '\"')
+ break;
+ x[i++] = c;
+ }
+ x[i] = '\0';
+ return strdup(x);
+}
+
+int
+yywrap ()
+{
+ return 1;
+}
diff --git a/third_party/heimdal/lib/sl/slc.h b/third_party/heimdal/lib/sl/slc.h
new file mode 100644
index 0000000..e4dc2cb
--- /dev/null
+++ b/third_party/heimdal/lib/sl/slc.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+#include <stdio.h>
+#include <string.h>
+#include <stdarg.h>
+
+struct assignment {
+ char *name;
+ enum { a_value, a_assignment } type;
+ union {
+ char *value;
+ struct assignment *assignment;
+ } u;
+ unsigned int lineno;
+ struct assignment *next;
+};
+
+extern char *filename;
+extern int error_flag;
+void error_message (const char *format, ...);
+int yylex(void);
+void yyerror (const char *s);
+#define yyerror yyerror
+extern unsigned lineno;
diff --git a/third_party/heimdal/lib/sl/test_sl.c b/third_party/heimdal/lib/sl/test_sl.c
new file mode 100644
index 0000000..9b9c1f7
--- /dev/null
+++ b/third_party/heimdal/lib/sl/test_sl.c
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of KTH nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+#include "sl_locl.h"
+
+struct {
+ int ok;
+ const char *line;
+ int argc;
+ const char *argv[4];
+} lines[] = {
+ { 1, "", 1, { "" } },
+ { 1, "foo", 1, { "foo" } },
+ { 1, "foo bar", 2, { "foo", "bar" }},
+ { 1, "foo bar baz", 3, { "foo", "bar", "baz" }},
+ { 1, "foobar baz", 2, { "foobar", "baz" }},
+ { 1, " foo", 1, { "foo" } },
+ { 1, "foo ", 1, { "foo" } },
+ { 1, " foo ", 1, { "foo" } },
+ { 1, " foo bar", 2, { "foo", "bar" } },
+ { 1, "foo\\ bar", 1, { "foo bar" } },
+ { 1, "\"foo bar\"", 1, { "foo bar" } },
+ { 1, "\"foo\\ bar\"", 1, { "foo bar" } },
+ { 1, "\"foo\\\" bar\"", 1, { "foo\" bar" } },
+ { 1, "\"\"f\"\"oo\"\"", 1, { "foo" } },
+ { 1, "\"foobar\"baz", 1, { "foobarbaz" }},
+ { 1, "foo\tbar baz", 3, { "foo", "bar", "baz" }},
+ { 1, "\"foo bar\" baz", 2, { "foo bar", "baz" }},
+ { 1, "\"foo bar baz\"", 1, { "foo bar baz" }},
+ { 1, "\\\"foo bar baz", 3, { "\"foo", "bar", "baz" }},
+ { 1, "\\ foo bar baz", 3, { " foo", "bar", "baz" }},
+ { 1, "foo\\\\\\\"barbaz", 1, { "foo\\\"barbaz" }},
+ { 1, "foobar\\\" baz", 2, { "foobar\"", "baz" }},
+ { 1, "foobar\\ \\ baz", 1, { "foobar baz" }},
+ { 0, "\\", 0, { "" }},
+ { 0, "\"", 0, { "" }}
+};
+
+int
+main(int argc, char **argv)
+{
+ int ret, i;
+
+ for (i = 0; i < sizeof(lines)/sizeof(lines[0]); i++) {
+ int j, rargc = 0;
+ char **rargv = NULL;
+ char *buf = strdup(lines[i].line);
+
+ ret = sl_make_argv(buf, &rargc, &rargv);
+ if (ret) {
+ if (!lines[i].ok)
+ goto next;
+ errx(1, "sl_make_argv test %d failed", i);
+ } else if (!lines[i].ok)
+ errx(1, "sl_make_argv passed test %d when it shouldn't", i);
+ if (rargc != lines[i].argc)
+ errx(1, "result argc (%d) != should be argc (%d) for test %d",
+ rargc, lines[i].argc, i);
+ for (j = 0; j < rargc; j++)
+ if (strcmp(rargv[j], lines[i].argv[j]) != 0)
+ errx(1, "result argv (%s) != should be argv (%s) for test %d",
+ rargv[j], lines[i].argv[j], i);
+ next:
+ free(buf);
+ free(rargv);
+ }
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/sqlite/Makefile.am b/third_party/heimdal/lib/sqlite/Makefile.am
new file mode 100644
index 0000000..90c1ad9
--- /dev/null
+++ b/third_party/heimdal/lib/sqlite/Makefile.am
@@ -0,0 +1,20 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+if ENABLE_PTHREAD_SUPPORT
+AM_CPPFLAGS += -DSQLITE_THREADSAFE=1 -DSQLITE_DEFAULT_FILE_PERMISSIONS=0600
+endif
+
+AM_CPPFLAGS += -DSQLITE_WITHOUT_ZONEMALLOC=1
+WFLAGS =
+
+lib_LTLIBRARIES = libheimsqlite.la
+
+noinst_HEADERS = sqlite3.h sqlite3ext.h
+
+libheimsqlite_la_SOURCES = sqlite3.c
+
+libheimsqlite_la_LIBADD = $(PTHREAD_LIBADD)
+
+EXTRA_DIST = NTMakefile
diff --git a/third_party/heimdal/lib/sqlite/NTMakefile b/third_party/heimdal/lib/sqlite/NTMakefile
new file mode 100644
index 0000000..3a6a4c2
--- /dev/null
+++ b/third_party/heimdal/lib/sqlite/NTMakefile
@@ -0,0 +1,52 @@
+########################################################################
+#
+# Copyright (c) 2009, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\sqlite
+
+!include ../../windows/NTMakefile.w32
+
+INCFILES= \
+ $(INCDIR)\sqlite3.h \
+ $(INCDIR)\sqlite3ext.h
+
+# pmode 0600 = _S_IREAD | _S_IWRITE
+cdefines = $(cdefines) \
+ -DSQLITE_DEFAULT_FILE_PERMISSIONS=0600 \
+ -DSQLITE_THREADSAFE=1
+
+$(LIBSQLITE): $(OBJ)\sqlite3.obj
+ $(LIBCON)
+
+all:: $(INCFILES) $(LIBSQLITE)
+
+clean::
+ -$(RM) $(LIBSQLITE)
+ -$(RM) $(INCFILES)
diff --git a/third_party/heimdal/lib/sqlite/README b/third_party/heimdal/lib/sqlite/README
new file mode 100644
index 0000000..f147d8a
--- /dev/null
+++ b/third_party/heimdal/lib/sqlite/README
@@ -0,0 +1,25 @@
+
+This directory contains a copy of the SQLite3 amalgamation.
+
+In order to help update this copy to newer versions of SQLite3, please
+make NO changes to it that are not absolutely necessary:
+
+ - add no features that can't be added as loadable extensions or avoided
+ altogether
+ - fix no bugs that can't be worked around
+ - define macros via the Makefile as much as possible (-D...) rather
+ than via changes to the source
+ - fix absolutely no whitespace, formatting, or spelling errors
+ - fix no compiler warnings (the upstream community mostly doesn't care
+ to fix them) unless you're absolutely convinced that the warning(s)
+ represent a serious bug(s) that is relevant to Heimdal
+
+If you must make changes to this copy, DO:
+
+ - have a commit just for those changes and no other changes outside
+ this part of the tree
+
+ - provide enough information in the commit message that someone else
+ (or even yourself) can figure out whether and how to re-apply your
+ change years later when updating to a newer version of SQLite3
+
diff --git a/third_party/heimdal/lib/sqlite/sqlite3.c b/third_party/heimdal/lib/sqlite/sqlite3.c
new file mode 100644
index 0000000..de55858
--- /dev/null
+++ b/third_party/heimdal/lib/sqlite/sqlite3.c
@@ -0,0 +1,231382 @@
+/******************************************************************************
+** This file is an amalgamation of many separate C source files from SQLite
+** version 3.34.0. By combining all the individual C code files into this
+** single large file, the entire code can be compiled as a single translation
+** unit. This allows many compilers to do optimizations that would not be
+** possible if the files were compiled separately. Performance improvements
+** of 5% or more are commonly seen when SQLite is compiled as a single
+** translation unit.
+**
+** This file is all you need to compile SQLite. To use SQLite in other
+** programs, you need this file and the "sqlite3.h" header file that defines
+** the programming interface to the SQLite library. (If you do not have
+** the "sqlite3.h" header file at hand, you will find a copy embedded within
+** the text of this file. Search for "Begin file sqlite3.h" to find the start
+** of the embedded sqlite3.h header file.) Additional code files may be needed
+** if you want a wrapper to interface SQLite with your choice of programming
+** language. The code for the "sqlite3" command-line shell is also in a
+** separate file. This file contains only code for the core SQLite library.
+*/
+#define SQLITE_CORE 1
+#define SQLITE_AMALGAMATION 1
+#ifndef SQLITE_PRIVATE
+# define SQLITE_PRIVATE static
+#endif
+/************** Begin file ctime.c *******************************************/
+/*
+** 2010 February 23
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file implements routines used to report what compile-time options
+** SQLite was built with.
+*/
+
+#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */
+
+/*
+** Include the configuration header output by 'configure' if we're using the
+** autoconf-based build
+*/
+#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
+#include "config.h"
+#define SQLITECONFIG_H 1
+#endif
+
+/* These macros are provided to "stringify" the value of the define
+** for those options in which the value is meaningful. */
+#define CTIMEOPT_VAL_(opt) #opt
+#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
+
+/* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This
+** option requires a separate macro because legal values contain a single
+** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */
+#define CTIMEOPT_VAL2_(opt1,opt2) #opt1 "," #opt2
+#define CTIMEOPT_VAL2(opt) CTIMEOPT_VAL2_(opt)
+
+/*
+** An array of names of all compile-time options. This array should
+** be sorted A-Z.
+**
+** This array looks large, but in a typical installation actually uses
+** only a handful of compile-time options, so most times this array is usually
+** rather short and uses little memory space.
+*/
+static const char * const sqlite3azCompileOpt[] = {
+
+/*
+** BEGIN CODE GENERATED BY tool/mkctime.tcl
+*/
+#if SQLITE_32BIT_ROWID
+ "32BIT_ROWID",
+#endif
+#if SQLITE_4_BYTE_ALIGNED_MALLOC
+ "4_BYTE_ALIGNED_MALLOC",
+#endif
+#if SQLITE_64BIT_STATS
+ "64BIT_STATS",
+#endif
+#if SQLITE_ALLOW_COVERING_INDEX_SCAN
+ "ALLOW_COVERING_INDEX_SCAN",
+#endif
+#if SQLITE_ALLOW_URI_AUTHORITY
+ "ALLOW_URI_AUTHORITY",
+#endif
+#ifdef SQLITE_BITMASK_TYPE
+ "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
+#endif
+#if SQLITE_BUG_COMPATIBLE_20160819
+ "BUG_COMPATIBLE_20160819",
+#endif
+#if SQLITE_CASE_SENSITIVE_LIKE
+ "CASE_SENSITIVE_LIKE",
+#endif
+#if SQLITE_CHECK_PAGES
+ "CHECK_PAGES",
+#endif
+#if defined(__clang__) && defined(__clang_major__)
+ "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
+ CTIMEOPT_VAL(__clang_minor__) "."
+ CTIMEOPT_VAL(__clang_patchlevel__),
+#elif defined(_MSC_VER)
+ "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
+#elif defined(__GNUC__) && defined(__VERSION__)
+ "COMPILER=gcc-" __VERSION__,
+#endif
+#if SQLITE_COVERAGE_TEST
+ "COVERAGE_TEST",
+#endif
+#if SQLITE_DEBUG
+ "DEBUG",
+#endif
+#if SQLITE_DEFAULT_AUTOMATIC_INDEX
+ "DEFAULT_AUTOMATIC_INDEX",
+#endif
+#if SQLITE_DEFAULT_AUTOVACUUM
+ "DEFAULT_AUTOVACUUM",
+#endif
+#ifdef SQLITE_DEFAULT_CACHE_SIZE
+ "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
+#endif
+#if SQLITE_DEFAULT_CKPTFULLFSYNC
+ "DEFAULT_CKPTFULLFSYNC",
+#endif
+#ifdef SQLITE_DEFAULT_FILE_FORMAT
+ "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
+#endif
+#ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
+ "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
+#endif
+#if SQLITE_DEFAULT_FOREIGN_KEYS
+ "DEFAULT_FOREIGN_KEYS",
+#endif
+#ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
+ "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
+#endif
+#ifdef SQLITE_DEFAULT_LOCKING_MODE
+ "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
+#endif
+#ifdef SQLITE_DEFAULT_LOOKASIDE
+ "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE),
+#endif
+#if SQLITE_DEFAULT_MEMSTATUS
+ "DEFAULT_MEMSTATUS",
+#endif
+#ifdef SQLITE_DEFAULT_MMAP_SIZE
+ "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
+#endif
+#ifdef SQLITE_DEFAULT_PAGE_SIZE
+ "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
+#endif
+#ifdef SQLITE_DEFAULT_PCACHE_INITSZ
+ "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
+#endif
+#ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
+ "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
+#endif
+#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
+ "DEFAULT_RECURSIVE_TRIGGERS",
+#endif
+#ifdef SQLITE_DEFAULT_ROWEST
+ "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
+#endif
+#ifdef SQLITE_DEFAULT_SECTOR_SIZE
+ "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
+#endif
+#ifdef SQLITE_DEFAULT_SYNCHRONOUS
+ "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
+#endif
+#ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
+ "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
+#endif
+#ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
+ "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
+#endif
+#ifdef SQLITE_DEFAULT_WORKER_THREADS
+ "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
+#endif
+#if SQLITE_DIRECT_OVERFLOW_READ
+ "DIRECT_OVERFLOW_READ",
+#endif
+#if SQLITE_DISABLE_DIRSYNC
+ "DISABLE_DIRSYNC",
+#endif
+#if SQLITE_DISABLE_FTS3_UNICODE
+ "DISABLE_FTS3_UNICODE",
+#endif
+#if SQLITE_DISABLE_FTS4_DEFERRED
+ "DISABLE_FTS4_DEFERRED",
+#endif
+#if SQLITE_DISABLE_INTRINSIC
+ "DISABLE_INTRINSIC",
+#endif
+#if SQLITE_DISABLE_LFS
+ "DISABLE_LFS",
+#endif
+#if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
+ "DISABLE_PAGECACHE_OVERFLOW_STATS",
+#endif
+#if SQLITE_DISABLE_SKIPAHEAD_DISTINCT
+ "DISABLE_SKIPAHEAD_DISTINCT",
+#endif
+#ifdef SQLITE_ENABLE_8_3_NAMES
+ "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
+#endif
+#if SQLITE_ENABLE_API_ARMOR
+ "ENABLE_API_ARMOR",
+#endif
+#if SQLITE_ENABLE_ATOMIC_WRITE
+ "ENABLE_ATOMIC_WRITE",
+#endif
+#if SQLITE_ENABLE_BATCH_ATOMIC_WRITE
+ "ENABLE_BATCH_ATOMIC_WRITE",
+#endif
+#if SQLITE_ENABLE_BYTECODE_VTAB
+ "ENABLE_BYTECODE_VTAB",
+#endif
+#if SQLITE_ENABLE_CEROD
+ "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),
+#endif
+#if SQLITE_ENABLE_COLUMN_METADATA
+ "ENABLE_COLUMN_METADATA",
+#endif
+#if SQLITE_ENABLE_COLUMN_USED_MASK
+ "ENABLE_COLUMN_USED_MASK",
+#endif
+#if SQLITE_ENABLE_COSTMULT
+ "ENABLE_COSTMULT",
+#endif
+#if SQLITE_ENABLE_CURSOR_HINTS
+ "ENABLE_CURSOR_HINTS",
+#endif
+#if SQLITE_ENABLE_DBSTAT_VTAB
+ "ENABLE_DBSTAT_VTAB",
+#endif
+#if SQLITE_ENABLE_EXPENSIVE_ASSERT
+ "ENABLE_EXPENSIVE_ASSERT",
+#endif
+#if SQLITE_ENABLE_FTS1
+ "ENABLE_FTS1",
+#endif
+#if SQLITE_ENABLE_FTS2
+ "ENABLE_FTS2",
+#endif
+#if SQLITE_ENABLE_FTS3
+ "ENABLE_FTS3",
+#endif
+#if SQLITE_ENABLE_FTS3_PARENTHESIS
+ "ENABLE_FTS3_PARENTHESIS",
+#endif
+#if SQLITE_ENABLE_FTS3_TOKENIZER
+ "ENABLE_FTS3_TOKENIZER",
+#endif
+#if SQLITE_ENABLE_FTS4
+ "ENABLE_FTS4",
+#endif
+#if SQLITE_ENABLE_FTS5
+ "ENABLE_FTS5",
+#endif
+#if SQLITE_ENABLE_GEOPOLY
+ "ENABLE_GEOPOLY",
+#endif
+#if SQLITE_ENABLE_HIDDEN_COLUMNS
+ "ENABLE_HIDDEN_COLUMNS",
+#endif
+#if SQLITE_ENABLE_ICU
+ "ENABLE_ICU",
+#endif
+#if SQLITE_ENABLE_IOTRACE
+ "ENABLE_IOTRACE",
+#endif
+#if SQLITE_ENABLE_JSON1
+ "ENABLE_JSON1",
+#endif
+#if SQLITE_ENABLE_LOAD_EXTENSION
+ "ENABLE_LOAD_EXTENSION",
+#endif
+#ifdef SQLITE_ENABLE_LOCKING_STYLE
+ "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
+#endif
+#if SQLITE_ENABLE_MEMORY_MANAGEMENT
+ "ENABLE_MEMORY_MANAGEMENT",
+#endif
+#if SQLITE_ENABLE_MEMSYS3
+ "ENABLE_MEMSYS3",
+#endif
+#if SQLITE_ENABLE_MEMSYS5
+ "ENABLE_MEMSYS5",
+#endif
+#if SQLITE_ENABLE_MULTIPLEX
+ "ENABLE_MULTIPLEX",
+#endif
+#if SQLITE_ENABLE_NORMALIZE
+ "ENABLE_NORMALIZE",
+#endif
+#if SQLITE_ENABLE_NULL_TRIM
+ "ENABLE_NULL_TRIM",
+#endif
+#if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
+ "ENABLE_OVERSIZE_CELL_CHECK",
+#endif
+#if SQLITE_ENABLE_PREUPDATE_HOOK
+ "ENABLE_PREUPDATE_HOOK",
+#endif
+#if SQLITE_ENABLE_QPSG
+ "ENABLE_QPSG",
+#endif
+#if SQLITE_ENABLE_RBU
+ "ENABLE_RBU",
+#endif
+#if SQLITE_ENABLE_RTREE
+ "ENABLE_RTREE",
+#endif
+#if SQLITE_ENABLE_SELECTTRACE
+ "ENABLE_SELECTTRACE",
+#endif
+#if SQLITE_ENABLE_SESSION
+ "ENABLE_SESSION",
+#endif
+#if SQLITE_ENABLE_SNAPSHOT
+ "ENABLE_SNAPSHOT",
+#endif
+#if SQLITE_ENABLE_SORTER_REFERENCES
+ "ENABLE_SORTER_REFERENCES",
+#endif
+#if SQLITE_ENABLE_SQLLOG
+ "ENABLE_SQLLOG",
+#endif
+#if defined(SQLITE_ENABLE_STAT4)
+ "ENABLE_STAT4",
+#endif
+#if SQLITE_ENABLE_STMTVTAB
+ "ENABLE_STMTVTAB",
+#endif
+#if SQLITE_ENABLE_STMT_SCANSTATUS
+ "ENABLE_STMT_SCANSTATUS",
+#endif
+#if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
+ "ENABLE_UNKNOWN_SQL_FUNCTION",
+#endif
+#if SQLITE_ENABLE_UNLOCK_NOTIFY
+ "ENABLE_UNLOCK_NOTIFY",
+#endif
+#if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
+ "ENABLE_UPDATE_DELETE_LIMIT",
+#endif
+#if SQLITE_ENABLE_URI_00_ERROR
+ "ENABLE_URI_00_ERROR",
+#endif
+#if SQLITE_ENABLE_VFSTRACE
+ "ENABLE_VFSTRACE",
+#endif
+#if SQLITE_ENABLE_WHERETRACE
+ "ENABLE_WHERETRACE",
+#endif
+#if SQLITE_ENABLE_ZIPVFS
+ "ENABLE_ZIPVFS",
+#endif
+#if SQLITE_EXPLAIN_ESTIMATED_ROWS
+ "EXPLAIN_ESTIMATED_ROWS",
+#endif
+#if SQLITE_EXTRA_IFNULLROW
+ "EXTRA_IFNULLROW",
+#endif
+#ifdef SQLITE_EXTRA_INIT
+ "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
+#endif
+#ifdef SQLITE_EXTRA_SHUTDOWN
+ "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
+#endif
+#ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
+ "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
+#endif
+#if SQLITE_FTS5_ENABLE_TEST_MI
+ "FTS5_ENABLE_TEST_MI",
+#endif
+#if SQLITE_FTS5_NO_WITHOUT_ROWID
+ "FTS5_NO_WITHOUT_ROWID",
+#endif
+#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
+ "HAVE_ISNAN",
+#endif
+#if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
+ "HOMEGROWN_RECURSIVE_MUTEX",
+#endif
+#if SQLITE_IGNORE_AFP_LOCK_ERRORS
+ "IGNORE_AFP_LOCK_ERRORS",
+#endif
+#if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
+ "IGNORE_FLOCK_LOCK_ERRORS",
+#endif
+#if SQLITE_INLINE_MEMCPY
+ "INLINE_MEMCPY",
+#endif
+#if SQLITE_INT64_TYPE
+ "INT64_TYPE",
+#endif
+#ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
+ "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
+#endif
+#if SQLITE_LIKE_DOESNT_MATCH_BLOBS
+ "LIKE_DOESNT_MATCH_BLOBS",
+#endif
+#if SQLITE_LOCK_TRACE
+ "LOCK_TRACE",
+#endif
+#if SQLITE_LOG_CACHE_SPILL
+ "LOG_CACHE_SPILL",
+#endif
+#ifdef SQLITE_MALLOC_SOFT_LIMIT
+ "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
+#endif
+#ifdef SQLITE_MAX_ATTACHED
+ "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
+#endif
+#ifdef SQLITE_MAX_COLUMN
+ "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
+#endif
+#ifdef SQLITE_MAX_COMPOUND_SELECT
+ "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
+#endif
+#ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
+ "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
+#endif
+#ifdef SQLITE_MAX_EXPR_DEPTH
+ "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
+#endif
+#ifdef SQLITE_MAX_FUNCTION_ARG
+ "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
+#endif
+#ifdef SQLITE_MAX_LENGTH
+ "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
+#endif
+#ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
+ "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
+#endif
+#ifdef SQLITE_MAX_MEMORY
+ "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
+#endif
+#ifdef SQLITE_MAX_MMAP_SIZE
+ "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
+#endif
+#ifdef SQLITE_MAX_MMAP_SIZE_
+ "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
+#endif
+#ifdef SQLITE_MAX_PAGE_COUNT
+ "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
+#endif
+#ifdef SQLITE_MAX_PAGE_SIZE
+ "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
+#endif
+#ifdef SQLITE_MAX_SCHEMA_RETRY
+ "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
+#endif
+#ifdef SQLITE_MAX_SQL_LENGTH
+ "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
+#endif
+#ifdef SQLITE_MAX_TRIGGER_DEPTH
+ "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
+#endif
+#ifdef SQLITE_MAX_VARIABLE_NUMBER
+ "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
+#endif
+#ifdef SQLITE_MAX_VDBE_OP
+ "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
+#endif
+#ifdef SQLITE_MAX_WORKER_THREADS
+ "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
+#endif
+#if SQLITE_MEMDEBUG
+ "MEMDEBUG",
+#endif
+#if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
+ "MIXED_ENDIAN_64BIT_FLOAT",
+#endif
+#if SQLITE_MMAP_READWRITE
+ "MMAP_READWRITE",
+#endif
+#if SQLITE_MUTEX_NOOP
+ "MUTEX_NOOP",
+#endif
+#if SQLITE_MUTEX_NREF
+ "MUTEX_NREF",
+#endif
+#if SQLITE_MUTEX_OMIT
+ "MUTEX_OMIT",
+#endif
+#if SQLITE_MUTEX_PTHREADS
+ "MUTEX_PTHREADS",
+#endif
+#if SQLITE_MUTEX_W32
+ "MUTEX_W32",
+#endif
+#if SQLITE_NEED_ERR_NAME
+ "NEED_ERR_NAME",
+#endif
+#if SQLITE_NOINLINE
+ "NOINLINE",
+#endif
+#if SQLITE_NO_SYNC
+ "NO_SYNC",
+#endif
+#if SQLITE_OMIT_ALTERTABLE
+ "OMIT_ALTERTABLE",
+#endif
+#if SQLITE_OMIT_ANALYZE
+ "OMIT_ANALYZE",
+#endif
+#if SQLITE_OMIT_ATTACH
+ "OMIT_ATTACH",
+#endif
+#if SQLITE_OMIT_AUTHORIZATION
+ "OMIT_AUTHORIZATION",
+#endif
+#if SQLITE_OMIT_AUTOINCREMENT
+ "OMIT_AUTOINCREMENT",
+#endif
+#if SQLITE_OMIT_AUTOINIT
+ "OMIT_AUTOINIT",
+#endif
+#if SQLITE_OMIT_AUTOMATIC_INDEX
+ "OMIT_AUTOMATIC_INDEX",
+#endif
+#if SQLITE_OMIT_AUTORESET
+ "OMIT_AUTORESET",
+#endif
+#if SQLITE_OMIT_AUTOVACUUM
+ "OMIT_AUTOVACUUM",
+#endif
+#if SQLITE_OMIT_BETWEEN_OPTIMIZATION
+ "OMIT_BETWEEN_OPTIMIZATION",
+#endif
+#if SQLITE_OMIT_BLOB_LITERAL
+ "OMIT_BLOB_LITERAL",
+#endif
+#if SQLITE_OMIT_CAST
+ "OMIT_CAST",
+#endif
+#if SQLITE_OMIT_CHECK
+ "OMIT_CHECK",
+#endif
+#if SQLITE_OMIT_COMPLETE
+ "OMIT_COMPLETE",
+#endif
+#if SQLITE_OMIT_COMPOUND_SELECT
+ "OMIT_COMPOUND_SELECT",
+#endif
+#if SQLITE_OMIT_CONFLICT_CLAUSE
+ "OMIT_CONFLICT_CLAUSE",
+#endif
+#if SQLITE_OMIT_CTE
+ "OMIT_CTE",
+#endif
+#if SQLITE_OMIT_DATETIME_FUNCS
+ "OMIT_DATETIME_FUNCS",
+#endif
+#if SQLITE_OMIT_DECLTYPE
+ "OMIT_DECLTYPE",
+#endif
+#if SQLITE_OMIT_DEPRECATED
+ "OMIT_DEPRECATED",
+#endif
+#if SQLITE_OMIT_DISKIO
+ "OMIT_DISKIO",
+#endif
+#if SQLITE_OMIT_EXPLAIN
+ "OMIT_EXPLAIN",
+#endif
+#if SQLITE_OMIT_FLAG_PRAGMAS
+ "OMIT_FLAG_PRAGMAS",
+#endif
+#if SQLITE_OMIT_FLOATING_POINT
+ "OMIT_FLOATING_POINT",
+#endif
+#if SQLITE_OMIT_FOREIGN_KEY
+ "OMIT_FOREIGN_KEY",
+#endif
+#if SQLITE_OMIT_GET_TABLE
+ "OMIT_GET_TABLE",
+#endif
+#if SQLITE_OMIT_HEX_INTEGER
+ "OMIT_HEX_INTEGER",
+#endif
+#if SQLITE_OMIT_INCRBLOB
+ "OMIT_INCRBLOB",
+#endif
+#if SQLITE_OMIT_INTEGRITY_CHECK
+ "OMIT_INTEGRITY_CHECK",
+#endif
+#if SQLITE_OMIT_LIKE_OPTIMIZATION
+ "OMIT_LIKE_OPTIMIZATION",
+#endif
+#if SQLITE_OMIT_LOAD_EXTENSION
+ "OMIT_LOAD_EXTENSION",
+#endif
+#if SQLITE_OMIT_LOCALTIME
+ "OMIT_LOCALTIME",
+#endif
+#if SQLITE_OMIT_LOOKASIDE
+ "OMIT_LOOKASIDE",
+#endif
+#if SQLITE_OMIT_MEMORYDB
+ "OMIT_MEMORYDB",
+#endif
+#if SQLITE_OMIT_OR_OPTIMIZATION
+ "OMIT_OR_OPTIMIZATION",
+#endif
+#if SQLITE_OMIT_PAGER_PRAGMAS
+ "OMIT_PAGER_PRAGMAS",
+#endif
+#if SQLITE_OMIT_PARSER_TRACE
+ "OMIT_PARSER_TRACE",
+#endif
+#if SQLITE_OMIT_POPEN
+ "OMIT_POPEN",
+#endif
+#if SQLITE_OMIT_PRAGMA
+ "OMIT_PRAGMA",
+#endif
+#if SQLITE_OMIT_PROGRESS_CALLBACK
+ "OMIT_PROGRESS_CALLBACK",
+#endif
+#if SQLITE_OMIT_QUICKBALANCE
+ "OMIT_QUICKBALANCE",
+#endif
+#if SQLITE_OMIT_REINDEX
+ "OMIT_REINDEX",
+#endif
+#if SQLITE_OMIT_SCHEMA_PRAGMAS
+ "OMIT_SCHEMA_PRAGMAS",
+#endif
+#if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
+ "OMIT_SCHEMA_VERSION_PRAGMAS",
+#endif
+#if SQLITE_OMIT_SHARED_CACHE
+ "OMIT_SHARED_CACHE",
+#endif
+#if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
+ "OMIT_SHUTDOWN_DIRECTORIES",
+#endif
+#if SQLITE_OMIT_SUBQUERY
+ "OMIT_SUBQUERY",
+#endif
+#if SQLITE_OMIT_TCL_VARIABLE
+ "OMIT_TCL_VARIABLE",
+#endif
+#if SQLITE_OMIT_TEMPDB
+ "OMIT_TEMPDB",
+#endif
+#if SQLITE_OMIT_TEST_CONTROL
+ "OMIT_TEST_CONTROL",
+#endif
+#if SQLITE_OMIT_TRACE
+ "OMIT_TRACE",
+#endif
+#if SQLITE_OMIT_TRIGGER
+ "OMIT_TRIGGER",
+#endif
+#if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
+ "OMIT_TRUNCATE_OPTIMIZATION",
+#endif
+#if SQLITE_OMIT_UTF16
+ "OMIT_UTF16",
+#endif
+#if SQLITE_OMIT_VACUUM
+ "OMIT_VACUUM",
+#endif
+#if SQLITE_OMIT_VIEW
+ "OMIT_VIEW",
+#endif
+#if SQLITE_OMIT_VIRTUALTABLE
+ "OMIT_VIRTUALTABLE",
+#endif
+#if SQLITE_OMIT_WAL
+ "OMIT_WAL",
+#endif
+#if SQLITE_OMIT_WSD
+ "OMIT_WSD",
+#endif
+#if SQLITE_OMIT_XFER_OPT
+ "OMIT_XFER_OPT",
+#endif
+#if SQLITE_PCACHE_SEPARATE_HEADER
+ "PCACHE_SEPARATE_HEADER",
+#endif
+#if SQLITE_PERFORMANCE_TRACE
+ "PERFORMANCE_TRACE",
+#endif
+#if SQLITE_POWERSAFE_OVERWRITE
+ "POWERSAFE_OVERWRITE",
+#endif
+#if SQLITE_PREFER_PROXY_LOCKING
+ "PREFER_PROXY_LOCKING",
+#endif
+#if SQLITE_PROXY_DEBUG
+ "PROXY_DEBUG",
+#endif
+#if SQLITE_REVERSE_UNORDERED_SELECTS
+ "REVERSE_UNORDERED_SELECTS",
+#endif
+#if SQLITE_RTREE_INT_ONLY
+ "RTREE_INT_ONLY",
+#endif
+#if SQLITE_SECURE_DELETE
+ "SECURE_DELETE",
+#endif
+#if SQLITE_SMALL_STACK
+ "SMALL_STACK",
+#endif
+#ifdef SQLITE_SORTER_PMASZ
+ "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
+#endif
+#if SQLITE_SOUNDEX
+ "SOUNDEX",
+#endif
+#ifdef SQLITE_STAT4_SAMPLES
+ "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
+#endif
+#ifdef SQLITE_STMTJRNL_SPILL
+ "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
+#endif
+#if SQLITE_SUBSTR_COMPATIBILITY
+ "SUBSTR_COMPATIBILITY",
+#endif
+#if SQLITE_SYSTEM_MALLOC
+ "SYSTEM_MALLOC",
+#endif
+#if SQLITE_TCL
+ "TCL",
+#endif
+#ifdef SQLITE_TEMP_STORE
+ "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
+#endif
+#if SQLITE_TEST
+ "TEST",
+#endif
+#if defined(SQLITE_THREADSAFE)
+ "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
+#elif defined(THREADSAFE)
+ "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
+#else
+ "THREADSAFE=1",
+#endif
+#if SQLITE_UNLINK_AFTER_CLOSE
+ "UNLINK_AFTER_CLOSE",
+#endif
+#if SQLITE_UNTESTABLE
+ "UNTESTABLE",
+#endif
+#if SQLITE_USER_AUTHENTICATION
+ "USER_AUTHENTICATION",
+#endif
+#if SQLITE_USE_ALLOCA
+ "USE_ALLOCA",
+#endif
+#if SQLITE_USE_FCNTL_TRACE
+ "USE_FCNTL_TRACE",
+#endif
+#if SQLITE_USE_URI
+ "USE_URI",
+#endif
+#if SQLITE_VDBE_COVERAGE
+ "VDBE_COVERAGE",
+#endif
+#if SQLITE_WIN32_MALLOC
+ "WIN32_MALLOC",
+#endif
+#if SQLITE_ZERO_MALLOC
+ "ZERO_MALLOC",
+#endif
+/*
+** END CODE GENERATED BY tool/mkctime.tcl
+*/
+};
+
+SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
+ *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
+ return (const char**)sqlite3azCompileOpt;
+}
+
+#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
+
+/************** End of ctime.c ***********************************************/
+/************** Begin file sqliteInt.h ***************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** Internal interface definitions for SQLite.
+**
+*/
+#ifndef SQLITEINT_H
+#define SQLITEINT_H
+
+/* Special Comments:
+**
+** Some comments have special meaning to the tools that measure test
+** coverage:
+**
+** NO_TEST - The branches on this line are not
+** measured by branch coverage. This is
+** used on lines of code that actually
+** implement parts of coverage testing.
+**
+** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
+** and the correct answer is still obtained,
+** though perhaps more slowly.
+**
+** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
+** and the correct answer is still obtained,
+** though perhaps more slowly.
+**
+** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
+** that would be harmless and undetectable
+** if it did occur.
+**
+** In all cases, the special comment must be enclosed in the usual
+** slash-asterisk...asterisk-slash comment marks, with no spaces between the
+** asterisks and the comment text.
+*/
+
+/*
+** Make sure the Tcl calling convention macro is defined. This macro is
+** only used by test code and Tcl integration code.
+*/
+#ifndef SQLITE_TCLAPI
+# define SQLITE_TCLAPI
+#endif
+
+/*
+** Include the header file used to customize the compiler options for MSVC.
+** This should be done first so that it can successfully prevent spurious
+** compiler warnings due to subsequent content in this file and other files
+** that are included by this file.
+*/
+/************** Include msvc.h in the middle of sqliteInt.h ******************/
+/************** Begin file msvc.h ********************************************/
+/*
+** 2015 January 12
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains code that is specific to MSVC.
+*/
+#ifndef SQLITE_MSVC_H
+#define SQLITE_MSVC_H
+
+#if defined(_MSC_VER)
+#pragma warning(disable : 4054)
+#pragma warning(disable : 4055)
+#pragma warning(disable : 4100)
+#pragma warning(disable : 4127)
+#pragma warning(disable : 4130)
+#pragma warning(disable : 4152)
+#pragma warning(disable : 4189)
+#pragma warning(disable : 4206)
+#pragma warning(disable : 4210)
+#pragma warning(disable : 4232)
+#pragma warning(disable : 4244)
+#pragma warning(disable : 4305)
+#pragma warning(disable : 4306)
+#pragma warning(disable : 4702)
+#pragma warning(disable : 4706)
+#endif /* defined(_MSC_VER) */
+
+#if defined(_MSC_VER) && !defined(_WIN64)
+#undef SQLITE_4_BYTE_ALIGNED_MALLOC
+#define SQLITE_4_BYTE_ALIGNED_MALLOC
+#endif /* defined(_MSC_VER) && !defined(_WIN64) */
+
+#endif /* SQLITE_MSVC_H */
+
+/************** End of msvc.h ************************************************/
+/************** Continuing where we left off in sqliteInt.h ******************/
+
+/*
+** Special setup for VxWorks
+*/
+/************** Include vxworks.h in the middle of sqliteInt.h ***************/
+/************** Begin file vxworks.h *****************************************/
+/*
+** 2015-03-02
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains code that is specific to Wind River's VxWorks
+*/
+#if defined(__RTP__) || defined(_WRS_KERNEL)
+/* This is VxWorks. Set up things specially for that OS
+*/
+#include <vxWorks.h>
+#include <pthread.h> /* amalgamator: dontcache */
+#define OS_VXWORKS 1
+#define SQLITE_OS_OTHER 0
+#define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
+#define SQLITE_OMIT_LOAD_EXTENSION 1
+#define SQLITE_ENABLE_LOCKING_STYLE 0
+#define HAVE_UTIME 1
+#else
+/* This is not VxWorks. */
+#define OS_VXWORKS 0
+#define HAVE_FCHOWN 1
+#define HAVE_READLINK 1
+#define HAVE_LSTAT 1
+#endif /* defined(_WRS_KERNEL) */
+
+/************** End of vxworks.h *********************************************/
+/************** Continuing where we left off in sqliteInt.h ******************/
+
+/*
+** These #defines should enable >2GB file support on POSIX if the
+** underlying operating system supports it. If the OS lacks
+** large file support, or if the OS is windows, these should be no-ops.
+**
+** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
+** system #includes. Hence, this block of code must be the very first
+** code in all source files.
+**
+** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
+** on the compiler command line. This is necessary if you are compiling
+** on a recent machine (ex: Red Hat 7.2) but you want your code to work
+** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
+** without this option, LFS is enable. But LFS does not exist in the kernel
+** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
+** portability you should omit LFS.
+**
+** The previous paragraph was written in 2005. (This paragraph is written
+** on 2008-11-28.) These days, all Linux kernels support large files, so
+** you should probably leave LFS enabled. But some embedded platforms might
+** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
+**
+** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
+*/
+#ifndef SQLITE_DISABLE_LFS
+# define _LARGE_FILE 1
+# ifndef _FILE_OFFSET_BITS
+# define _FILE_OFFSET_BITS 64
+# endif
+# define _LARGEFILE_SOURCE 1
+#endif
+
+/* The GCC_VERSION and MSVC_VERSION macros are used to
+** conditionally include optimizations for each of these compilers. A
+** value of 0 means that compiler is not being used. The
+** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
+** optimizations, and hence set all compiler macros to 0
+**
+** There was once also a CLANG_VERSION macro. However, we learn that the
+** version numbers in clang are for "marketing" only and are inconsistent
+** and unreliable. Fortunately, all versions of clang also recognize the
+** gcc version numbers and have reasonable settings for gcc version numbers,
+** so the GCC_VERSION macro will be set to a correct non-zero value even
+** when compiling with clang.
+*/
+#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
+# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
+#else
+# define GCC_VERSION 0
+#endif
+#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
+# define MSVC_VERSION _MSC_VER
+#else
+# define MSVC_VERSION 0
+#endif
+
+/* Needed for various definitions... */
+#if defined(__GNUC__) && !defined(_GNU_SOURCE)
+# define _GNU_SOURCE
+#endif
+
+#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
+# define _BSD_SOURCE
+#endif
+
+/*
+** Macro to disable warnings about missing "break" at the end of a "case".
+*/
+#if GCC_VERSION>=7000000
+# define deliberate_fall_through __attribute__((fallthrough));
+#else
+# define deliberate_fall_through
+#endif
+
+/*
+** For MinGW, check to see if we can include the header file containing its
+** version information, among other things. Normally, this internal MinGW
+** header file would [only] be included automatically by other MinGW header
+** files; however, the contained version information is now required by this
+** header file to work around binary compatibility issues (see below) and
+** this is the only known way to reliably obtain it. This entire #if block
+** would be completely unnecessary if there was any other way of detecting
+** MinGW via their preprocessor (e.g. if they customized their GCC to define
+** some MinGW-specific macros). When compiling for MinGW, either the
+** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
+** defined; otherwise, detection of conditions specific to MinGW will be
+** disabled.
+*/
+#if defined(_HAVE_MINGW_H)
+# include "mingw.h"
+#elif defined(_HAVE__MINGW_H)
+# include "_mingw.h"
+#endif
+
+/*
+** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
+** define is required to maintain binary compatibility with the MSVC runtime
+** library in use (e.g. for Windows XP).
+*/
+#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
+ defined(_WIN32) && !defined(_WIN64) && \
+ defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
+ defined(__MSVCRT__)
+# define _USE_32BIT_TIME_T
+#endif
+
+/* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
+** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
+** MinGW.
+*/
+/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
+/************** Begin file sqlite3.h *****************************************/
+/*
+** 2001-09-15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This header file defines the interface that the SQLite library
+** presents to client programs. If a C-function, structure, datatype,
+** or constant definition does not appear in this file, then it is
+** not a published API of SQLite, is subject to change without
+** notice, and should not be referenced by programs that use SQLite.
+**
+** Some of the definitions that are in this file are marked as
+** "experimental". Experimental interfaces are normally new
+** features recently added to SQLite. We do not anticipate changes
+** to experimental interfaces but reserve the right to make minor changes
+** if experience from use "in the wild" suggest such changes are prudent.
+**
+** The official C-language API documentation for SQLite is derived
+** from comments in this file. This file is the authoritative source
+** on how SQLite interfaces are supposed to operate.
+**
+** The name of this file under configuration management is "sqlite.h.in".
+** The makefile makes some minor changes to this file (such as inserting
+** the version number) and changes its name to "sqlite3.h" as
+** part of the build process.
+*/
+#ifndef SQLITE3_H
+#define SQLITE3_H
+#include <stdarg.h> /* Needed for the definition of va_list */
+
+/*
+** Make sure we can call this stuff from C++.
+*/
+#if 0
+extern "C" {
+#endif
+
+
+/*
+** Provide the ability to override linkage features of the interface.
+*/
+#ifndef SQLITE_EXTERN
+# define SQLITE_EXTERN extern
+#endif
+#ifndef SQLITE_API
+# define SQLITE_API
+#endif
+#ifndef SQLITE_CDECL
+# define SQLITE_CDECL
+#endif
+#ifndef SQLITE_APICALL
+# define SQLITE_APICALL
+#endif
+#ifndef SQLITE_STDCALL
+# define SQLITE_STDCALL SQLITE_APICALL
+#endif
+#ifndef SQLITE_CALLBACK
+# define SQLITE_CALLBACK
+#endif
+#ifndef SQLITE_SYSAPI
+# define SQLITE_SYSAPI
+#endif
+
+/*
+** These no-op macros are used in front of interfaces to mark those
+** interfaces as either deprecated or experimental. New applications
+** should not use deprecated interfaces - they are supported for backwards
+** compatibility only. Application writers should be aware that
+** experimental interfaces are subject to change in point releases.
+**
+** These macros used to resolve to various kinds of compiler magic that
+** would generate warning messages when they were used. But that
+** compiler magic ended up generating such a flurry of bug reports
+** that we have taken it all out and gone back to using simple
+** noop macros.
+*/
+#define SQLITE_DEPRECATED
+#define SQLITE_EXPERIMENTAL
+
+/*
+** Ensure these symbols were not defined by some previous header file.
+*/
+#ifdef SQLITE_VERSION
+# undef SQLITE_VERSION
+#endif
+#ifdef SQLITE_VERSION_NUMBER
+# undef SQLITE_VERSION_NUMBER
+#endif
+
+/*
+** CAPI3REF: Compile-Time Library Version Numbers
+**
+** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
+** evaluates to a string literal that is the SQLite version in the
+** format "X.Y.Z" where X is the major version number (always 3 for
+** SQLite3) and Y is the minor version number and Z is the release number.)^
+** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
+** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
+** numbers used in [SQLITE_VERSION].)^
+** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
+** be larger than the release from which it is derived. Either Y will
+** be held constant and Z will be incremented or else Y will be incremented
+** and Z will be reset to zero.
+**
+** Since [version 3.6.18] ([dateof:3.6.18]),
+** SQLite source code has been stored in the
+** <a href="http://www.fossil-scm.org/">Fossil configuration management
+** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
+** a string which identifies a particular check-in of SQLite
+** within its configuration management system. ^The SQLITE_SOURCE_ID
+** string contains the date and time of the check-in (UTC) and a SHA1
+** or SHA3-256 hash of the entire source tree. If the source code has
+** been edited in any way since it was last checked in, then the last
+** four hexadecimal digits of the hash may be modified.
+**
+** See also: [sqlite3_libversion()],
+** [sqlite3_libversion_number()], [sqlite3_sourceid()],
+** [sqlite_version()] and [sqlite_source_id()].
+*/
+#define SQLITE_VERSION "3.34.0"
+#define SQLITE_VERSION_NUMBER 3034000
+#define SQLITE_SOURCE_ID "2020-10-02 15:15:18 dd009cd7aec3598e930806907601f4f0f9b0021ea99fa6c5e29e88f1246066ed"
+
+/*
+** CAPI3REF: Run-Time Library Version Numbers
+** KEYWORDS: sqlite3_version sqlite3_sourceid
+**
+** These interfaces provide the same information as the [SQLITE_VERSION],
+** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
+** but are associated with the library instead of the header file. ^(Cautious
+** programmers might include assert() statements in their application to
+** verify that values returned by these interfaces match the macros in
+** the header, and thus ensure that the application is
+** compiled with matching library and header files.
+**
+** <blockquote><pre>
+** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
+** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
+** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
+** </pre></blockquote>)^
+**
+** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
+** macro. ^The sqlite3_libversion() function returns a pointer to the
+** to the sqlite3_version[] string constant. The sqlite3_libversion()
+** function is provided for use in DLLs since DLL users usually do not have
+** direct access to string constants within the DLL. ^The
+** sqlite3_libversion_number() function returns an integer equal to
+** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns
+** a pointer to a string constant whose value is the same as the
+** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built
+** using an edited copy of [the amalgamation], then the last four characters
+** of the hash might be different from [SQLITE_SOURCE_ID].)^
+**
+** See also: [sqlite_version()] and [sqlite_source_id()].
+*/
+SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
+SQLITE_API const char *sqlite3_libversion(void);
+SQLITE_API const char *sqlite3_sourceid(void);
+SQLITE_API int sqlite3_libversion_number(void);
+
+/*
+** CAPI3REF: Run-Time Library Compilation Options Diagnostics
+**
+** ^The sqlite3_compileoption_used() function returns 0 or 1
+** indicating whether the specified option was defined at
+** compile time. ^The SQLITE_ prefix may be omitted from the
+** option name passed to sqlite3_compileoption_used().
+**
+** ^The sqlite3_compileoption_get() function allows iterating
+** over the list of options that were defined at compile time by
+** returning the N-th compile time option string. ^If N is out of range,
+** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
+** prefix is omitted from any strings returned by
+** sqlite3_compileoption_get().
+**
+** ^Support for the diagnostic functions sqlite3_compileoption_used()
+** and sqlite3_compileoption_get() may be omitted by specifying the
+** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
+**
+** See also: SQL functions [sqlite_compileoption_used()] and
+** [sqlite_compileoption_get()] and the [compile_options pragma].
+*/
+#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
+SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
+SQLITE_API const char *sqlite3_compileoption_get(int N);
+#else
+# define sqlite3_compileoption_used(X) 0
+# define sqlite3_compileoption_get(X) ((void*)0)
+#endif
+
+/*
+** CAPI3REF: Test To See If The Library Is Threadsafe
+**
+** ^The sqlite3_threadsafe() function returns zero if and only if
+** SQLite was compiled with mutexing code omitted due to the
+** [SQLITE_THREADSAFE] compile-time option being set to 0.
+**
+** SQLite can be compiled with or without mutexes. When
+** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
+** are enabled and SQLite is threadsafe. When the
+** [SQLITE_THREADSAFE] macro is 0,
+** the mutexes are omitted. Without the mutexes, it is not safe
+** to use SQLite concurrently from more than one thread.
+**
+** Enabling mutexes incurs a measurable performance penalty.
+** So if speed is of utmost importance, it makes sense to disable
+** the mutexes. But for maximum safety, mutexes should be enabled.
+** ^The default behavior is for mutexes to be enabled.
+**
+** This interface can be used by an application to make sure that the
+** version of SQLite that it is linking against was compiled with
+** the desired setting of the [SQLITE_THREADSAFE] macro.
+**
+** This interface only reports on the compile-time mutex setting
+** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
+** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
+** can be fully or partially disabled using a call to [sqlite3_config()]
+** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
+** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
+** sqlite3_threadsafe() function shows only the compile-time setting of
+** thread safety, not any run-time changes to that setting made by
+** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
+** is unchanged by calls to sqlite3_config().)^
+**
+** See the [threading mode] documentation for additional information.
+*/
+SQLITE_API int sqlite3_threadsafe(void);
+
+/*
+** CAPI3REF: Database Connection Handle
+** KEYWORDS: {database connection} {database connections}
+**
+** Each open SQLite database is represented by a pointer to an instance of
+** the opaque structure named "sqlite3". It is useful to think of an sqlite3
+** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
+** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
+** and [sqlite3_close_v2()] are its destructors. There are many other
+** interfaces (such as
+** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
+** [sqlite3_busy_timeout()] to name but three) that are methods on an
+** sqlite3 object.
+*/
+typedef struct sqlite3 sqlite3;
+
+/*
+** CAPI3REF: 64-Bit Integer Types
+** KEYWORDS: sqlite_int64 sqlite_uint64
+**
+** Because there is no cross-platform way to specify 64-bit integer types
+** SQLite includes typedefs for 64-bit signed and unsigned integers.
+**
+** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
+** The sqlite_int64 and sqlite_uint64 types are supported for backwards
+** compatibility only.
+**
+** ^The sqlite3_int64 and sqlite_int64 types can store integer values
+** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
+** sqlite3_uint64 and sqlite_uint64 types can store integer values
+** between 0 and +18446744073709551615 inclusive.
+*/
+#ifdef SQLITE_INT64_TYPE
+ typedef SQLITE_INT64_TYPE sqlite_int64;
+# ifdef SQLITE_UINT64_TYPE
+ typedef SQLITE_UINT64_TYPE sqlite_uint64;
+# else
+ typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
+# endif
+#elif defined(_MSC_VER) || defined(__BORLANDC__)
+ typedef __int64 sqlite_int64;
+ typedef unsigned __int64 sqlite_uint64;
+#else
+ typedef long long int sqlite_int64;
+ typedef unsigned long long int sqlite_uint64;
+#endif
+typedef sqlite_int64 sqlite3_int64;
+typedef sqlite_uint64 sqlite3_uint64;
+
+/*
+** If compiling for a processor that lacks floating point support,
+** substitute integer for floating-point.
+*/
+#ifdef SQLITE_OMIT_FLOATING_POINT
+# define double sqlite3_int64
+#endif
+
+/*
+** CAPI3REF: Closing A Database Connection
+** DESTRUCTOR: sqlite3
+**
+** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
+** for the [sqlite3] object.
+** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
+** the [sqlite3] object is successfully destroyed and all associated
+** resources are deallocated.
+**
+** Ideally, applications should [sqlite3_finalize | finalize] all
+** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and
+** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
+** with the [sqlite3] object prior to attempting to close the object.
+** ^If the database connection is associated with unfinalized prepared
+** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then
+** sqlite3_close() will leave the database connection open and return
+** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared
+** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups,
+** it returns [SQLITE_OK] regardless, but instead of deallocating the database
+** connection immediately, it marks the database connection as an unusable
+** "zombie" and makes arrangements to automatically deallocate the database
+** connection after all prepared statements are finalized, all BLOB handles
+** are closed, and all backups have finished. The sqlite3_close_v2() interface
+** is intended for use with host languages that are garbage collected, and
+** where the order in which destructors are called is arbitrary.
+**
+** ^If an [sqlite3] object is destroyed while a transaction is open,
+** the transaction is automatically rolled back.
+**
+** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
+** must be either a NULL
+** pointer or an [sqlite3] object pointer obtained
+** from [sqlite3_open()], [sqlite3_open16()], or
+** [sqlite3_open_v2()], and not previously closed.
+** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
+** argument is a harmless no-op.
+*/
+SQLITE_API int sqlite3_close(sqlite3*);
+SQLITE_API int sqlite3_close_v2(sqlite3*);
+
+/*
+** The type for a callback function.
+** This is legacy and deprecated. It is included for historical
+** compatibility and is not documented.
+*/
+typedef int (*sqlite3_callback)(void*,int,char**, char**);
+
+/*
+** CAPI3REF: One-Step Query Execution Interface
+** METHOD: sqlite3
+**
+** The sqlite3_exec() interface is a convenience wrapper around
+** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
+** that allows an application to run multiple statements of SQL
+** without having to use a lot of C code.
+**
+** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
+** semicolon-separate SQL statements passed into its 2nd argument,
+** in the context of the [database connection] passed in as its 1st
+** argument. ^If the callback function of the 3rd argument to
+** sqlite3_exec() is not NULL, then it is invoked for each result row
+** coming out of the evaluated SQL statements. ^The 4th argument to
+** sqlite3_exec() is relayed through to the 1st argument of each
+** callback invocation. ^If the callback pointer to sqlite3_exec()
+** is NULL, then no callback is ever invoked and result rows are
+** ignored.
+**
+** ^If an error occurs while evaluating the SQL statements passed into
+** sqlite3_exec(), then execution of the current statement stops and
+** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
+** is not NULL then any error message is written into memory obtained
+** from [sqlite3_malloc()] and passed back through the 5th parameter.
+** To avoid memory leaks, the application should invoke [sqlite3_free()]
+** on error message strings returned through the 5th parameter of
+** sqlite3_exec() after the error message string is no longer needed.
+** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
+** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
+** NULL before returning.
+**
+** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
+** routine returns SQLITE_ABORT without invoking the callback again and
+** without running any subsequent SQL statements.
+**
+** ^The 2nd argument to the sqlite3_exec() callback function is the
+** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
+** callback is an array of pointers to strings obtained as if from
+** [sqlite3_column_text()], one for each column. ^If an element of a
+** result row is NULL then the corresponding string pointer for the
+** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
+** sqlite3_exec() callback is an array of pointers to strings where each
+** entry represents the name of corresponding result column as obtained
+** from [sqlite3_column_name()].
+**
+** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
+** to an empty string, or a pointer that contains only whitespace and/or
+** SQL comments, then no SQL statements are evaluated and the database
+** is not changed.
+**
+** Restrictions:
+**
+** <ul>
+** <li> The application must ensure that the 1st parameter to sqlite3_exec()
+** is a valid and open [database connection].
+** <li> The application must not close the [database connection] specified by
+** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
+** <li> The application must not modify the SQL statement text passed into
+** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
+** </ul>
+*/
+SQLITE_API int sqlite3_exec(
+ sqlite3*, /* An open database */
+ const char *sql, /* SQL to be evaluated */
+ int (*callback)(void*,int,char**,char**), /* Callback function */
+ void *, /* 1st argument to callback */
+ char **errmsg /* Error msg written here */
+);
+
+/*
+** CAPI3REF: Result Codes
+** KEYWORDS: {result code definitions}
+**
+** Many SQLite functions return an integer result code from the set shown
+** here in order to indicate success or failure.
+**
+** New error codes may be added in future versions of SQLite.
+**
+** See also: [extended result code definitions]
+*/
+#define SQLITE_OK 0 /* Successful result */
+/* beginning-of-error-codes */
+#define SQLITE_ERROR 1 /* Generic error */
+#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
+#define SQLITE_PERM 3 /* Access permission denied */
+#define SQLITE_ABORT 4 /* Callback routine requested an abort */
+#define SQLITE_BUSY 5 /* The database file is locked */
+#define SQLITE_LOCKED 6 /* A table in the database is locked */
+#define SQLITE_NOMEM 7 /* A malloc() failed */
+#define SQLITE_READONLY 8 /* Attempt to write a readonly database */
+#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
+#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
+#define SQLITE_CORRUPT 11 /* The database disk image is malformed */
+#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
+#define SQLITE_FULL 13 /* Insertion failed because database is full */
+#define SQLITE_CANTOPEN 14 /* Unable to open the database file */
+#define SQLITE_PROTOCOL 15 /* Database lock protocol error */
+#define SQLITE_EMPTY 16 /* Internal use only */
+#define SQLITE_SCHEMA 17 /* The database schema changed */
+#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
+#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
+#define SQLITE_MISMATCH 20 /* Data type mismatch */
+#define SQLITE_MISUSE 21 /* Library used incorrectly */
+#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
+#define SQLITE_AUTH 23 /* Authorization denied */
+#define SQLITE_FORMAT 24 /* Not used */
+#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
+#define SQLITE_NOTADB 26 /* File opened that is not a database file */
+#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
+#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
+#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
+#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
+/* end-of-error-codes */
+
+/*
+** CAPI3REF: Extended Result Codes
+** KEYWORDS: {extended result code definitions}
+**
+** In its default configuration, SQLite API routines return one of 30 integer
+** [result codes]. However, experience has shown that many of
+** these result codes are too coarse-grained. They do not provide as
+** much information about problems as programmers might like. In an effort to
+** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
+** and later) include
+** support for additional result codes that provide more detailed information
+** about errors. These [extended result codes] are enabled or disabled
+** on a per database connection basis using the
+** [sqlite3_extended_result_codes()] API. Or, the extended code for
+** the most recent error can be obtained using
+** [sqlite3_extended_errcode()].
+*/
+#define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8))
+#define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8))
+#define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8))
+#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
+#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
+#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
+#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
+#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
+#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
+#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
+#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
+#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
+#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
+#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
+#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
+#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
+#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
+#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
+#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
+#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
+#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
+#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
+#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
+#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
+#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
+#define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
+#define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
+#define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
+#define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
+#define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
+#define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
+#define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
+#define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
+#define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
+#define SQLITE_IOERR_DATA (SQLITE_IOERR | (32<<8))
+#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
+#define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8))
+#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
+#define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
+#define SQLITE_BUSY_TIMEOUT (SQLITE_BUSY | (3<<8))
+#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
+#define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
+#define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
+#define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
+#define SQLITE_CANTOPEN_DIRTYWAL (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
+#define SQLITE_CANTOPEN_SYMLINK (SQLITE_CANTOPEN | (6<<8))
+#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
+#define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8))
+#define SQLITE_CORRUPT_INDEX (SQLITE_CORRUPT | (3<<8))
+#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
+#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
+#define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
+#define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
+#define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8))
+#define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8))
+#define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
+#define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
+#define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
+#define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
+#define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
+#define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
+#define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
+#define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
+#define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
+#define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
+#define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
+#define SQLITE_CONSTRAINT_PINNED (SQLITE_CONSTRAINT |(11<<8))
+#define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
+#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
+#define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
+#define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
+#define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
+#define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8))
+
+/*
+** CAPI3REF: Flags For File Open Operations
+**
+** These bit values are intended for use in the
+** 3rd parameter to the [sqlite3_open_v2()] interface and
+** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
+*/
+#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
+#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
+#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
+#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
+#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
+#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
+#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
+#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
+#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
+#define SQLITE_OPEN_SUPER_JOURNAL 0x00004000 /* VFS only */
+#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
+#define SQLITE_OPEN_NOFOLLOW 0x01000000 /* Ok for sqlite3_open_v2() */
+
+/* Reserved: 0x00F00000 */
+/* Legacy compatibility: */
+#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
+
+
+/*
+** CAPI3REF: Device Characteristics
+**
+** The xDeviceCharacteristics method of the [sqlite3_io_methods]
+** object returns an integer which is a vector of these
+** bit values expressing I/O characteristics of the mass storage
+** device that holds the file that the [sqlite3_io_methods]
+** refers to.
+**
+** The SQLITE_IOCAP_ATOMIC property means that all writes of
+** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
+** mean that writes of blocks that are nnn bytes in size and
+** are aligned to an address which is an integer multiple of
+** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
+** that when data is appended to a file, the data is appended
+** first then the size of the file is extended, never the other
+** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
+** information is written to disk in the same order as calls
+** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
+** after reboot following a crash or power loss, the only bytes in a
+** file that were written at the application level might have changed
+** and that adjacent bytes, even bytes within the same sector are
+** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
+** flag indicates that a file cannot be deleted when open. The
+** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
+** read-only media and cannot be changed even by processes with
+** elevated privileges.
+**
+** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
+** filesystem supports doing multiple write operations atomically when those
+** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
+** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
+*/
+#define SQLITE_IOCAP_ATOMIC 0x00000001
+#define SQLITE_IOCAP_ATOMIC512 0x00000002
+#define SQLITE_IOCAP_ATOMIC1K 0x00000004
+#define SQLITE_IOCAP_ATOMIC2K 0x00000008
+#define SQLITE_IOCAP_ATOMIC4K 0x00000010
+#define SQLITE_IOCAP_ATOMIC8K 0x00000020
+#define SQLITE_IOCAP_ATOMIC16K 0x00000040
+#define SQLITE_IOCAP_ATOMIC32K 0x00000080
+#define SQLITE_IOCAP_ATOMIC64K 0x00000100
+#define SQLITE_IOCAP_SAFE_APPEND 0x00000200
+#define SQLITE_IOCAP_SEQUENTIAL 0x00000400
+#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
+#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
+#define SQLITE_IOCAP_IMMUTABLE 0x00002000
+#define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
+
+/*
+** CAPI3REF: File Locking Levels
+**
+** SQLite uses one of these integer values as the second
+** argument to calls it makes to the xLock() and xUnlock() methods
+** of an [sqlite3_io_methods] object.
+*/
+#define SQLITE_LOCK_NONE 0
+#define SQLITE_LOCK_SHARED 1
+#define SQLITE_LOCK_RESERVED 2
+#define SQLITE_LOCK_PENDING 3
+#define SQLITE_LOCK_EXCLUSIVE 4
+
+/*
+** CAPI3REF: Synchronization Type Flags
+**
+** When SQLite invokes the xSync() method of an
+** [sqlite3_io_methods] object it uses a combination of
+** these integer values as the second argument.
+**
+** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
+** sync operation only needs to flush data to mass storage. Inode
+** information need not be flushed. If the lower four bits of the flag
+** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
+** If the lower four bits equal SQLITE_SYNC_FULL, that means
+** to use Mac OS X style fullsync instead of fsync().
+**
+** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
+** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
+** settings. The [synchronous pragma] determines when calls to the
+** xSync VFS method occur and applies uniformly across all platforms.
+** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
+** energetic or rigorous or forceful the sync operations are and
+** only make a difference on Mac OSX for the default SQLite code.
+** (Third-party VFS implementations might also make the distinction
+** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
+** operating systems natively supported by SQLite, only Mac OSX
+** cares about the difference.)
+*/
+#define SQLITE_SYNC_NORMAL 0x00002
+#define SQLITE_SYNC_FULL 0x00003
+#define SQLITE_SYNC_DATAONLY 0x00010
+
+/*
+** CAPI3REF: OS Interface Open File Handle
+**
+** An [sqlite3_file] object represents an open file in the
+** [sqlite3_vfs | OS interface layer]. Individual OS interface
+** implementations will
+** want to subclass this object by appending additional fields
+** for their own use. The pMethods entry is a pointer to an
+** [sqlite3_io_methods] object that defines methods for performing
+** I/O operations on the open file.
+*/
+typedef struct sqlite3_file sqlite3_file;
+struct sqlite3_file {
+ const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
+};
+
+/*
+** CAPI3REF: OS Interface File Virtual Methods Object
+**
+** Every file opened by the [sqlite3_vfs.xOpen] method populates an
+** [sqlite3_file] object (or, more commonly, a subclass of the
+** [sqlite3_file] object) with a pointer to an instance of this object.
+** This object defines the methods used to perform various operations
+** against the open file represented by the [sqlite3_file] object.
+**
+** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
+** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
+** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
+** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
+** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
+** to NULL.
+**
+** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
+** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
+** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
+** flag may be ORed in to indicate that only the data of the file
+** and not its inode needs to be synced.
+**
+** The integer values to xLock() and xUnlock() are one of
+** <ul>
+** <li> [SQLITE_LOCK_NONE],
+** <li> [SQLITE_LOCK_SHARED],
+** <li> [SQLITE_LOCK_RESERVED],
+** <li> [SQLITE_LOCK_PENDING], or
+** <li> [SQLITE_LOCK_EXCLUSIVE].
+** </ul>
+** xLock() increases the lock. xUnlock() decreases the lock.
+** The xCheckReservedLock() method checks whether any database connection,
+** either in this process or in some other process, is holding a RESERVED,
+** PENDING, or EXCLUSIVE lock on the file. It returns true
+** if such a lock exists and false otherwise.
+**
+** The xFileControl() method is a generic interface that allows custom
+** VFS implementations to directly control an open file using the
+** [sqlite3_file_control()] interface. The second "op" argument is an
+** integer opcode. The third argument is a generic pointer intended to
+** point to a structure that may contain arguments or space in which to
+** write return values. Potential uses for xFileControl() might be
+** functions to enable blocking locks with timeouts, to change the
+** locking strategy (for example to use dot-file locks), to inquire
+** about the status of a lock, or to break stale locks. The SQLite
+** core reserves all opcodes less than 100 for its own use.
+** A [file control opcodes | list of opcodes] less than 100 is available.
+** Applications that define a custom xFileControl method should use opcodes
+** greater than 100 to avoid conflicts. VFS implementations should
+** return [SQLITE_NOTFOUND] for file control opcodes that they do not
+** recognize.
+**
+** The xSectorSize() method returns the sector size of the
+** device that underlies the file. The sector size is the
+** minimum write that can be performed without disturbing
+** other bytes in the file. The xDeviceCharacteristics()
+** method returns a bit vector describing behaviors of the
+** underlying device:
+**
+** <ul>
+** <li> [SQLITE_IOCAP_ATOMIC]
+** <li> [SQLITE_IOCAP_ATOMIC512]
+** <li> [SQLITE_IOCAP_ATOMIC1K]
+** <li> [SQLITE_IOCAP_ATOMIC2K]
+** <li> [SQLITE_IOCAP_ATOMIC4K]
+** <li> [SQLITE_IOCAP_ATOMIC8K]
+** <li> [SQLITE_IOCAP_ATOMIC16K]
+** <li> [SQLITE_IOCAP_ATOMIC32K]
+** <li> [SQLITE_IOCAP_ATOMIC64K]
+** <li> [SQLITE_IOCAP_SAFE_APPEND]
+** <li> [SQLITE_IOCAP_SEQUENTIAL]
+** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
+** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
+** <li> [SQLITE_IOCAP_IMMUTABLE]
+** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
+** </ul>
+**
+** The SQLITE_IOCAP_ATOMIC property means that all writes of
+** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
+** mean that writes of blocks that are nnn bytes in size and
+** are aligned to an address which is an integer multiple of
+** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
+** that when data is appended to a file, the data is appended
+** first then the size of the file is extended, never the other
+** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
+** information is written to disk in the same order as calls
+** to xWrite().
+**
+** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
+** in the unread portions of the buffer with zeros. A VFS that
+** fails to zero-fill short reads might seem to work. However,
+** failure to zero-fill short reads will eventually lead to
+** database corruption.
+*/
+typedef struct sqlite3_io_methods sqlite3_io_methods;
+struct sqlite3_io_methods {
+ int iVersion;
+ int (*xClose)(sqlite3_file*);
+ int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
+ int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
+ int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
+ int (*xSync)(sqlite3_file*, int flags);
+ int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
+ int (*xLock)(sqlite3_file*, int);
+ int (*xUnlock)(sqlite3_file*, int);
+ int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
+ int (*xFileControl)(sqlite3_file*, int op, void *pArg);
+ int (*xSectorSize)(sqlite3_file*);
+ int (*xDeviceCharacteristics)(sqlite3_file*);
+ /* Methods above are valid for version 1 */
+ int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
+ int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
+ void (*xShmBarrier)(sqlite3_file*);
+ int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
+ /* Methods above are valid for version 2 */
+ int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
+ int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
+ /* Methods above are valid for version 3 */
+ /* Additional methods may be added in future releases */
+};
+
+/*
+** CAPI3REF: Standard File Control Opcodes
+** KEYWORDS: {file control opcodes} {file control opcode}
+**
+** These integer constants are opcodes for the xFileControl method
+** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
+** interface.
+**
+** <ul>
+** <li>[[SQLITE_FCNTL_LOCKSTATE]]
+** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
+** opcode causes the xFileControl method to write the current state of
+** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
+** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
+** into an integer that the pArg argument points to. This capability
+** is used during testing and is only available when the SQLITE_TEST
+** compile-time option is used.
+**
+** <li>[[SQLITE_FCNTL_SIZE_HINT]]
+** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
+** layer a hint of how large the database file will grow to be during the
+** current transaction. This hint is not guaranteed to be accurate but it
+** is often close. The underlying VFS might choose to preallocate database
+** file space based on this hint in order to help writes to the database
+** file run faster.
+**
+** <li>[[SQLITE_FCNTL_SIZE_LIMIT]]
+** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that
+** implements [sqlite3_deserialize()] to set an upper bound on the size
+** of the in-memory database. The argument is a pointer to a [sqlite3_int64].
+** If the integer pointed to is negative, then it is filled in with the
+** current limit. Otherwise the limit is set to the larger of the value
+** of the integer pointed to and the current database size. The integer
+** pointed to is set to the new limit.
+**
+** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
+** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
+** extends and truncates the database file in chunks of a size specified
+** by the user. The fourth argument to [sqlite3_file_control()] should
+** point to an integer (type int) containing the new chunk-size to use
+** for the nominated database. Allocating database file space in large
+** chunks (say 1MB at a time), may reduce file-system fragmentation and
+** improve performance on some systems.
+**
+** <li>[[SQLITE_FCNTL_FILE_POINTER]]
+** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
+** to the [sqlite3_file] object associated with a particular database
+** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
+**
+** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
+** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
+** to the [sqlite3_file] object associated with the journal file (either
+** the [rollback journal] or the [write-ahead log]) for a particular database
+** connection. See also [SQLITE_FCNTL_FILE_POINTER].
+**
+** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
+** No longer in use.
+**
+** <li>[[SQLITE_FCNTL_SYNC]]
+** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
+** sent to the VFS immediately before the xSync method is invoked on a
+** database file descriptor. Or, if the xSync method is not invoked
+** because the user has configured SQLite with
+** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
+** of the xSync method. In most cases, the pointer argument passed with
+** this file-control is NULL. However, if the database file is being synced
+** as part of a multi-database commit, the argument points to a nul-terminated
+** string containing the transactions super-journal file name. VFSes that
+** do not need this signal should silently ignore this opcode. Applications
+** should not call [sqlite3_file_control()] with this opcode as doing so may
+** disrupt the operation of the specialized VFSes that do require it.
+**
+** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
+** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
+** and sent to the VFS after a transaction has been committed immediately
+** but before the database is unlocked. VFSes that do not need this signal
+** should silently ignore this opcode. Applications should not call
+** [sqlite3_file_control()] with this opcode as doing so may disrupt the
+** operation of the specialized VFSes that do require it.
+**
+** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
+** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
+** retry counts and intervals for certain disk I/O operations for the
+** windows [VFS] in order to provide robustness in the presence of
+** anti-virus programs. By default, the windows VFS will retry file read,
+** file write, and file delete operations up to 10 times, with a delay
+** of 25 milliseconds before the first retry and with the delay increasing
+** by an additional 25 milliseconds with each subsequent retry. This
+** opcode allows these two values (10 retries and 25 milliseconds of delay)
+** to be adjusted. The values are changed for all database connections
+** within the same process. The argument is a pointer to an array of two
+** integers where the first integer is the new retry count and the second
+** integer is the delay. If either integer is negative, then the setting
+** is not changed but instead the prior value of that setting is written
+** into the array entry, allowing the current retry settings to be
+** interrogated. The zDbName parameter is ignored.
+**
+** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
+** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
+** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
+** write ahead log ([WAL file]) and shared memory
+** files used for transaction control
+** are automatically deleted when the latest connection to the database
+** closes. Setting persistent WAL mode causes those files to persist after
+** close. Persisting the files is useful when other processes that do not
+** have write permission on the directory containing the database file want
+** to read the database file, as the WAL and shared memory files must exist
+** in order for the database to be readable. The fourth parameter to
+** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
+** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
+** WAL mode. If the integer is -1, then it is overwritten with the current
+** WAL persistence setting.
+**
+** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
+** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
+** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
+** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
+** xDeviceCharacteristics methods. The fourth parameter to
+** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
+** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
+** mode. If the integer is -1, then it is overwritten with the current
+** zero-damage mode setting.
+**
+** <li>[[SQLITE_FCNTL_OVERWRITE]]
+** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
+** a write transaction to indicate that, unless it is rolled back for some
+** reason, the entire database file will be overwritten by the current
+** transaction. This is used by VACUUM operations.
+**
+** <li>[[SQLITE_FCNTL_VFSNAME]]
+** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
+** all [VFSes] in the VFS stack. The names are of all VFS shims and the
+** final bottom-level VFS are written into memory obtained from
+** [sqlite3_malloc()] and the result is stored in the char* variable
+** that the fourth parameter of [sqlite3_file_control()] points to.
+** The caller is responsible for freeing the memory when done. As with
+** all file-control actions, there is no guarantee that this will actually
+** do anything. Callers should initialize the char* variable to a NULL
+** pointer in case this file-control is not implemented. This file-control
+** is intended for diagnostic use only.
+**
+** <li>[[SQLITE_FCNTL_VFS_POINTER]]
+** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
+** [VFSes] currently in use. ^(The argument X in
+** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
+** of type "[sqlite3_vfs] **". This opcodes will set *X
+** to a pointer to the top-level VFS.)^
+** ^When there are multiple VFS shims in the stack, this opcode finds the
+** upper-most shim only.
+**
+** <li>[[SQLITE_FCNTL_PRAGMA]]
+** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
+** file control is sent to the open [sqlite3_file] object corresponding
+** to the database file to which the pragma statement refers. ^The argument
+** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
+** pointers to strings (char**) in which the second element of the array
+** is the name of the pragma and the third element is the argument to the
+** pragma or NULL if the pragma has no argument. ^The handler for an
+** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
+** of the char** argument point to a string obtained from [sqlite3_mprintf()]
+** or the equivalent and that string will become the result of the pragma or
+** the error message if the pragma fails. ^If the
+** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
+** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
+** file control returns [SQLITE_OK], then the parser assumes that the
+** VFS has handled the PRAGMA itself and the parser generates a no-op
+** prepared statement if result string is NULL, or that returns a copy
+** of the result string if the string is non-NULL.
+** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
+** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
+** that the VFS encountered an error while handling the [PRAGMA] and the
+** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
+** file control occurs at the beginning of pragma statement analysis and so
+** it is able to override built-in [PRAGMA] statements.
+**
+** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
+** ^The [SQLITE_FCNTL_BUSYHANDLER]
+** file-control may be invoked by SQLite on the database file handle
+** shortly after it is opened in order to provide a custom VFS with access
+** to the connection's busy-handler callback. The argument is of type (void**)
+** - an array of two (void *) values. The first (void *) actually points
+** to a function of type (int (*)(void *)). In order to invoke the connection's
+** busy-handler, this function should be invoked with the second (void *) in
+** the array as the only argument. If it returns non-zero, then the operation
+** should be retried. If it returns zero, the custom VFS should abandon the
+** current operation.
+**
+** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
+** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
+** to have SQLite generate a
+** temporary filename using the same algorithm that is followed to generate
+** temporary filenames for TEMP tables and other internal uses. The
+** argument should be a char** which will be filled with the filename
+** written into memory obtained from [sqlite3_malloc()]. The caller should
+** invoke [sqlite3_free()] on the result to avoid a memory leak.
+**
+** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
+** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
+** maximum number of bytes that will be used for memory-mapped I/O.
+** The argument is a pointer to a value of type sqlite3_int64 that
+** is an advisory maximum number of bytes in the file to memory map. The
+** pointer is overwritten with the old value. The limit is not changed if
+** the value originally pointed to is negative, and so the current limit
+** can be queried by passing in a pointer to a negative number. This
+** file-control is used internally to implement [PRAGMA mmap_size].
+**
+** <li>[[SQLITE_FCNTL_TRACE]]
+** The [SQLITE_FCNTL_TRACE] file control provides advisory information
+** to the VFS about what the higher layers of the SQLite stack are doing.
+** This file control is used by some VFS activity tracing [shims].
+** The argument is a zero-terminated string. Higher layers in the
+** SQLite stack may generate instances of this file control if
+** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
+**
+** <li>[[SQLITE_FCNTL_HAS_MOVED]]
+** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
+** pointer to an integer and it writes a boolean into that integer depending
+** on whether or not the file has been renamed, moved, or deleted since it
+** was first opened.
+**
+** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
+** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
+** underlying native file handle associated with a file handle. This file
+** control interprets its argument as a pointer to a native file handle and
+** writes the resulting value there.
+**
+** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
+** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
+** opcode causes the xFileControl method to swap the file handle with the one
+** pointed to by the pArg argument. This capability is used during testing
+** and only needs to be supported when SQLITE_TEST is defined.
+**
+** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
+** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
+** be advantageous to block on the next WAL lock if the lock is not immediately
+** available. The WAL subsystem issues this signal during rare
+** circumstances in order to fix a problem with priority inversion.
+** Applications should <em>not</em> use this file-control.
+**
+** <li>[[SQLITE_FCNTL_ZIPVFS]]
+** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
+** VFS should return SQLITE_NOTFOUND for this opcode.
+**
+** <li>[[SQLITE_FCNTL_RBU]]
+** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
+** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
+** this opcode.
+**
+** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
+** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
+** the file descriptor is placed in "batch write mode", which
+** means all subsequent write operations will be deferred and done
+** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
+** that do not support batch atomic writes will return SQLITE_NOTFOUND.
+** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
+** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
+** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
+** no VFS interface calls on the same [sqlite3_file] file descriptor
+** except for calls to the xWrite method and the xFileControl method
+** with [SQLITE_FCNTL_SIZE_HINT].
+**
+** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
+** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
+** operations since the previous successful call to
+** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
+** This file control returns [SQLITE_OK] if and only if the writes were
+** all performed successfully and have been committed to persistent storage.
+** ^Regardless of whether or not it is successful, this file control takes
+** the file descriptor out of batch write mode so that all subsequent
+** write operations are independent.
+** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
+** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
+**
+** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
+** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
+** operations since the previous successful call to
+** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
+** ^This file control takes the file descriptor out of batch write mode
+** so that all subsequent write operations are independent.
+** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
+** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
+**
+** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
+** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS
+** to block for up to M milliseconds before failing when attempting to
+** obtain a file lock using the xLock or xShmLock methods of the VFS.
+** The parameter is a pointer to a 32-bit signed integer that contains
+** the value that M is to be set to. Before returning, the 32-bit signed
+** integer is overwritten with the previous value of M.
+**
+** <li>[[SQLITE_FCNTL_DATA_VERSION]]
+** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
+** a database file. The argument is a pointer to a 32-bit unsigned integer.
+** The "data version" for the pager is written into the pointer. The
+** "data version" changes whenever any change occurs to the corresponding
+** database file, either through SQL statements on the same database
+** connection or through transactions committed by separate database
+** connections possibly in other processes. The [sqlite3_total_changes()]
+** interface can be used to find if any database on the connection has changed,
+** but that interface responds to changes on TEMP as well as MAIN and does
+** not provide a mechanism to detect changes to MAIN only. Also, the
+** [sqlite3_total_changes()] interface responds to internal changes only and
+** omits changes made by other database connections. The
+** [PRAGMA data_version] command provides a mechanism to detect changes to
+** a single attached database that occur due to other database connections,
+** but omits changes implemented by the database connection on which it is
+** called. This file control is the only mechanism to detect changes that
+** happen either internally or externally and that are associated with
+** a particular attached database.
+**
+** <li>[[SQLITE_FCNTL_CKPT_START]]
+** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint
+** in wal mode before the client starts to copy pages from the wal
+** file to the database file.
+**
+** <li>[[SQLITE_FCNTL_CKPT_DONE]]
+** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint
+** in wal mode after the client has finished copying pages from the wal
+** file to the database file, but before the *-shm file is updated to
+** record the fact that the pages have been checkpointed.
+** </ul>
+*/
+#define SQLITE_FCNTL_LOCKSTATE 1
+#define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
+#define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
+#define SQLITE_FCNTL_LAST_ERRNO 4
+#define SQLITE_FCNTL_SIZE_HINT 5
+#define SQLITE_FCNTL_CHUNK_SIZE 6
+#define SQLITE_FCNTL_FILE_POINTER 7
+#define SQLITE_FCNTL_SYNC_OMITTED 8
+#define SQLITE_FCNTL_WIN32_AV_RETRY 9
+#define SQLITE_FCNTL_PERSIST_WAL 10
+#define SQLITE_FCNTL_OVERWRITE 11
+#define SQLITE_FCNTL_VFSNAME 12
+#define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
+#define SQLITE_FCNTL_PRAGMA 14
+#define SQLITE_FCNTL_BUSYHANDLER 15
+#define SQLITE_FCNTL_TEMPFILENAME 16
+#define SQLITE_FCNTL_MMAP_SIZE 18
+#define SQLITE_FCNTL_TRACE 19
+#define SQLITE_FCNTL_HAS_MOVED 20
+#define SQLITE_FCNTL_SYNC 21
+#define SQLITE_FCNTL_COMMIT_PHASETWO 22
+#define SQLITE_FCNTL_WIN32_SET_HANDLE 23
+#define SQLITE_FCNTL_WAL_BLOCK 24
+#define SQLITE_FCNTL_ZIPVFS 25
+#define SQLITE_FCNTL_RBU 26
+#define SQLITE_FCNTL_VFS_POINTER 27
+#define SQLITE_FCNTL_JOURNAL_POINTER 28
+#define SQLITE_FCNTL_WIN32_GET_HANDLE 29
+#define SQLITE_FCNTL_PDB 30
+#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
+#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
+#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
+#define SQLITE_FCNTL_LOCK_TIMEOUT 34
+#define SQLITE_FCNTL_DATA_VERSION 35
+#define SQLITE_FCNTL_SIZE_LIMIT 36
+#define SQLITE_FCNTL_CKPT_DONE 37
+#define SQLITE_FCNTL_RESERVE_BYTES 38
+#define SQLITE_FCNTL_CKPT_START 39
+
+/* deprecated names */
+#define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
+#define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
+#define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
+
+
+/*
+** CAPI3REF: Mutex Handle
+**
+** The mutex module within SQLite defines [sqlite3_mutex] to be an
+** abstract type for a mutex object. The SQLite core never looks
+** at the internal representation of an [sqlite3_mutex]. It only
+** deals with pointers to the [sqlite3_mutex] object.
+**
+** Mutexes are created using [sqlite3_mutex_alloc()].
+*/
+typedef struct sqlite3_mutex sqlite3_mutex;
+
+/*
+** CAPI3REF: Loadable Extension Thunk
+**
+** A pointer to the opaque sqlite3_api_routines structure is passed as
+** the third parameter to entry points of [loadable extensions]. This
+** structure must be typedefed in order to work around compiler warnings
+** on some platforms.
+*/
+typedef struct sqlite3_api_routines sqlite3_api_routines;
+
+/*
+** CAPI3REF: OS Interface Object
+**
+** An instance of the sqlite3_vfs object defines the interface between
+** the SQLite core and the underlying operating system. The "vfs"
+** in the name of the object stands for "virtual file system". See
+** the [VFS | VFS documentation] for further information.
+**
+** The VFS interface is sometimes extended by adding new methods onto
+** the end. Each time such an extension occurs, the iVersion field
+** is incremented. The iVersion value started out as 1 in
+** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2
+** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased
+** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields
+** may be appended to the sqlite3_vfs object and the iVersion value
+** may increase again in future versions of SQLite.
+** Note that due to an oversight, the structure
+** of the sqlite3_vfs object changed in the transition from
+** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
+** and yet the iVersion field was not increased.
+**
+** The szOsFile field is the size of the subclassed [sqlite3_file]
+** structure used by this VFS. mxPathname is the maximum length of
+** a pathname in this VFS.
+**
+** Registered sqlite3_vfs objects are kept on a linked list formed by
+** the pNext pointer. The [sqlite3_vfs_register()]
+** and [sqlite3_vfs_unregister()] interfaces manage this list
+** in a thread-safe way. The [sqlite3_vfs_find()] interface
+** searches the list. Neither the application code nor the VFS
+** implementation should use the pNext pointer.
+**
+** The pNext field is the only field in the sqlite3_vfs
+** structure that SQLite will ever modify. SQLite will only access
+** or modify this field while holding a particular static mutex.
+** The application should never modify anything within the sqlite3_vfs
+** object once the object has been registered.
+**
+** The zName field holds the name of the VFS module. The name must
+** be unique across all VFS modules.
+**
+** [[sqlite3_vfs.xOpen]]
+** ^SQLite guarantees that the zFilename parameter to xOpen
+** is either a NULL pointer or string obtained
+** from xFullPathname() with an optional suffix added.
+** ^If a suffix is added to the zFilename parameter, it will
+** consist of a single "-" character followed by no more than
+** 11 alphanumeric and/or "-" characters.
+** ^SQLite further guarantees that
+** the string will be valid and unchanged until xClose() is
+** called. Because of the previous sentence,
+** the [sqlite3_file] can safely store a pointer to the
+** filename if it needs to remember the filename for some reason.
+** If the zFilename parameter to xOpen is a NULL pointer then xOpen
+** must invent its own temporary name for the file. ^Whenever the
+** xFilename parameter is NULL it will also be the case that the
+** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
+**
+** The flags argument to xOpen() includes all bits set in
+** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
+** or [sqlite3_open16()] is used, then flags includes at least
+** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
+** If xOpen() opens a file read-only then it sets *pOutFlags to
+** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
+**
+** ^(SQLite will also add one of the following flags to the xOpen()
+** call, depending on the object being opened:
+**
+** <ul>
+** <li> [SQLITE_OPEN_MAIN_DB]
+** <li> [SQLITE_OPEN_MAIN_JOURNAL]
+** <li> [SQLITE_OPEN_TEMP_DB]
+** <li> [SQLITE_OPEN_TEMP_JOURNAL]
+** <li> [SQLITE_OPEN_TRANSIENT_DB]
+** <li> [SQLITE_OPEN_SUBJOURNAL]
+** <li> [SQLITE_OPEN_SUPER_JOURNAL]
+** <li> [SQLITE_OPEN_WAL]
+** </ul>)^
+**
+** The file I/O implementation can use the object type flags to
+** change the way it deals with files. For example, an application
+** that does not care about crash recovery or rollback might make
+** the open of a journal file a no-op. Writes to this journal would
+** also be no-ops, and any attempt to read the journal would return
+** SQLITE_IOERR. Or the implementation might recognize that a database
+** file will be doing page-aligned sector reads and writes in a random
+** order and set up its I/O subsystem accordingly.
+**
+** SQLite might also add one of the following flags to the xOpen method:
+**
+** <ul>
+** <li> [SQLITE_OPEN_DELETEONCLOSE]
+** <li> [SQLITE_OPEN_EXCLUSIVE]
+** </ul>
+**
+** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
+** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
+** will be set for TEMP databases and their journals, transient
+** databases, and subjournals.
+**
+** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
+** with the [SQLITE_OPEN_CREATE] flag, which are both directly
+** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
+** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
+** SQLITE_OPEN_CREATE, is used to indicate that file should always
+** be created, and that it is an error if it already exists.
+** It is <i>not</i> used to indicate the file should be opened
+** for exclusive access.
+**
+** ^At least szOsFile bytes of memory are allocated by SQLite
+** to hold the [sqlite3_file] structure passed as the third
+** argument to xOpen. The xOpen method does not have to
+** allocate the structure; it should just fill it in. Note that
+** the xOpen method must set the sqlite3_file.pMethods to either
+** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
+** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
+** element will be valid after xOpen returns regardless of the success
+** or failure of the xOpen call.
+**
+** [[sqlite3_vfs.xAccess]]
+** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
+** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
+** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
+** to test whether a file is at least readable. The SQLITE_ACCESS_READ
+** flag is never actually used and is not implemented in the built-in
+** VFSes of SQLite. The file is named by the second argument and can be a
+** directory. The xAccess method returns [SQLITE_OK] on success or some
+** non-zero error code if there is an I/O error or if the name of
+** the file given in the second argument is illegal. If SQLITE_OK
+** is returned, then non-zero or zero is written into *pResOut to indicate
+** whether or not the file is accessible.
+**
+** ^SQLite will always allocate at least mxPathname+1 bytes for the
+** output buffer xFullPathname. The exact size of the output buffer
+** is also passed as a parameter to both methods. If the output buffer
+** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
+** handled as a fatal error by SQLite, vfs implementations should endeavor
+** to prevent this by setting mxPathname to a sufficiently large value.
+**
+** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
+** interfaces are not strictly a part of the filesystem, but they are
+** included in the VFS structure for completeness.
+** The xRandomness() function attempts to return nBytes bytes
+** of good-quality randomness into zOut. The return value is
+** the actual number of bytes of randomness obtained.
+** The xSleep() method causes the calling thread to sleep for at
+** least the number of microseconds given. ^The xCurrentTime()
+** method returns a Julian Day Number for the current date and time as
+** a floating point value.
+** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
+** Day Number multiplied by 86400000 (the number of milliseconds in
+** a 24-hour day).
+** ^SQLite will use the xCurrentTimeInt64() method to get the current
+** date and time if that method is available (if iVersion is 2 or
+** greater and the function pointer is not NULL) and will fall back
+** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
+**
+** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
+** are not used by the SQLite core. These optional interfaces are provided
+** by some VFSes to facilitate testing of the VFS code. By overriding
+** system calls with functions under its control, a test program can
+** simulate faults and error conditions that would otherwise be difficult
+** or impossible to induce. The set of system calls that can be overridden
+** varies from one VFS to another, and from one version of the same VFS to the
+** next. Applications that use these interfaces must be prepared for any
+** or all of these interfaces to be NULL or for their behavior to change
+** from one release to the next. Applications must not attempt to access
+** any of these methods if the iVersion of the VFS is less than 3.
+*/
+typedef struct sqlite3_vfs sqlite3_vfs;
+typedef void (*sqlite3_syscall_ptr)(void);
+struct sqlite3_vfs {
+ int iVersion; /* Structure version number (currently 3) */
+ int szOsFile; /* Size of subclassed sqlite3_file */
+ int mxPathname; /* Maximum file pathname length */
+ sqlite3_vfs *pNext; /* Next registered VFS */
+ const char *zName; /* Name of this virtual file system */
+ void *pAppData; /* Pointer to application-specific data */
+ int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
+ int flags, int *pOutFlags);
+ int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
+ int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
+ int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
+ void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
+ void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
+ void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
+ void (*xDlClose)(sqlite3_vfs*, void*);
+ int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
+ int (*xSleep)(sqlite3_vfs*, int microseconds);
+ int (*xCurrentTime)(sqlite3_vfs*, double*);
+ int (*xGetLastError)(sqlite3_vfs*, int, char *);
+ /*
+ ** The methods above are in version 1 of the sqlite_vfs object
+ ** definition. Those that follow are added in version 2 or later
+ */
+ int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
+ /*
+ ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
+ ** Those below are for version 3 and greater.
+ */
+ int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
+ sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
+ const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
+ /*
+ ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
+ ** New fields may be appended in future versions. The iVersion
+ ** value will increment whenever this happens.
+ */
+};
+
+/*
+** CAPI3REF: Flags for the xAccess VFS method
+**
+** These integer constants can be used as the third parameter to
+** the xAccess method of an [sqlite3_vfs] object. They determine
+** what kind of permissions the xAccess method is looking for.
+** With SQLITE_ACCESS_EXISTS, the xAccess method
+** simply checks whether the file exists.
+** With SQLITE_ACCESS_READWRITE, the xAccess method
+** checks whether the named directory is both readable and writable
+** (in other words, if files can be added, removed, and renamed within
+** the directory).
+** The SQLITE_ACCESS_READWRITE constant is currently used only by the
+** [temp_store_directory pragma], though this could change in a future
+** release of SQLite.
+** With SQLITE_ACCESS_READ, the xAccess method
+** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
+** currently unused, though it might be used in a future release of
+** SQLite.
+*/
+#define SQLITE_ACCESS_EXISTS 0
+#define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
+#define SQLITE_ACCESS_READ 2 /* Unused */
+
+/*
+** CAPI3REF: Flags for the xShmLock VFS method
+**
+** These integer constants define the various locking operations
+** allowed by the xShmLock method of [sqlite3_io_methods]. The
+** following are the only legal combinations of flags to the
+** xShmLock method:
+**
+** <ul>
+** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
+** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
+** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
+** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
+** </ul>
+**
+** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
+** was given on the corresponding lock.
+**
+** The xShmLock method can transition between unlocked and SHARED or
+** between unlocked and EXCLUSIVE. It cannot transition between SHARED
+** and EXCLUSIVE.
+*/
+#define SQLITE_SHM_UNLOCK 1
+#define SQLITE_SHM_LOCK 2
+#define SQLITE_SHM_SHARED 4
+#define SQLITE_SHM_EXCLUSIVE 8
+
+/*
+** CAPI3REF: Maximum xShmLock index
+**
+** The xShmLock method on [sqlite3_io_methods] may use values
+** between 0 and this upper bound as its "offset" argument.
+** The SQLite core will never attempt to acquire or release a
+** lock outside of this range
+*/
+#define SQLITE_SHM_NLOCK 8
+
+
+/*
+** CAPI3REF: Initialize The SQLite Library
+**
+** ^The sqlite3_initialize() routine initializes the
+** SQLite library. ^The sqlite3_shutdown() routine
+** deallocates any resources that were allocated by sqlite3_initialize().
+** These routines are designed to aid in process initialization and
+** shutdown on embedded systems. Workstation applications using
+** SQLite normally do not need to invoke either of these routines.
+**
+** A call to sqlite3_initialize() is an "effective" call if it is
+** the first time sqlite3_initialize() is invoked during the lifetime of
+** the process, or if it is the first time sqlite3_initialize() is invoked
+** following a call to sqlite3_shutdown(). ^(Only an effective call
+** of sqlite3_initialize() does any initialization. All other calls
+** are harmless no-ops.)^
+**
+** A call to sqlite3_shutdown() is an "effective" call if it is the first
+** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
+** an effective call to sqlite3_shutdown() does any deinitialization.
+** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
+**
+** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
+** is not. The sqlite3_shutdown() interface must only be called from a
+** single thread. All open [database connections] must be closed and all
+** other SQLite resources must be deallocated prior to invoking
+** sqlite3_shutdown().
+**
+** Among other things, ^sqlite3_initialize() will invoke
+** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
+** will invoke sqlite3_os_end().
+**
+** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
+** ^If for some reason, sqlite3_initialize() is unable to initialize
+** the library (perhaps it is unable to allocate a needed resource such
+** as a mutex) it returns an [error code] other than [SQLITE_OK].
+**
+** ^The sqlite3_initialize() routine is called internally by many other
+** SQLite interfaces so that an application usually does not need to
+** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
+** calls sqlite3_initialize() so the SQLite library will be automatically
+** initialized when [sqlite3_open()] is called if it has not be initialized
+** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
+** compile-time option, then the automatic calls to sqlite3_initialize()
+** are omitted and the application must call sqlite3_initialize() directly
+** prior to using any other SQLite interface. For maximum portability,
+** it is recommended that applications always invoke sqlite3_initialize()
+** directly prior to using any other SQLite interface. Future releases
+** of SQLite may require this. In other words, the behavior exhibited
+** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
+** default behavior in some future release of SQLite.
+**
+** The sqlite3_os_init() routine does operating-system specific
+** initialization of the SQLite library. The sqlite3_os_end()
+** routine undoes the effect of sqlite3_os_init(). Typical tasks
+** performed by these routines include allocation or deallocation
+** of static resources, initialization of global variables,
+** setting up a default [sqlite3_vfs] module, or setting up
+** a default configuration using [sqlite3_config()].
+**
+** The application should never invoke either sqlite3_os_init()
+** or sqlite3_os_end() directly. The application should only invoke
+** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
+** interface is called automatically by sqlite3_initialize() and
+** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
+** implementations for sqlite3_os_init() and sqlite3_os_end()
+** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
+** When [custom builds | built for other platforms]
+** (using the [SQLITE_OS_OTHER=1] compile-time
+** option) the application must supply a suitable implementation for
+** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
+** implementation of sqlite3_os_init() or sqlite3_os_end()
+** must return [SQLITE_OK] on success and some other [error code] upon
+** failure.
+*/
+SQLITE_API int sqlite3_initialize(void);
+SQLITE_API int sqlite3_shutdown(void);
+SQLITE_API int sqlite3_os_init(void);
+SQLITE_API int sqlite3_os_end(void);
+
+/*
+** CAPI3REF: Configuring The SQLite Library
+**
+** The sqlite3_config() interface is used to make global configuration
+** changes to SQLite in order to tune SQLite to the specific needs of
+** the application. The default configuration is recommended for most
+** applications and so this routine is usually not necessary. It is
+** provided to support rare applications with unusual needs.
+**
+** <b>The sqlite3_config() interface is not threadsafe. The application
+** must ensure that no other SQLite interfaces are invoked by other
+** threads while sqlite3_config() is running.</b>
+**
+** The sqlite3_config() interface
+** may only be invoked prior to library initialization using
+** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
+** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
+** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
+** Note, however, that ^sqlite3_config() can be called as part of the
+** implementation of an application-defined [sqlite3_os_init()].
+**
+** The first argument to sqlite3_config() is an integer
+** [configuration option] that determines
+** what property of SQLite is to be configured. Subsequent arguments
+** vary depending on the [configuration option]
+** in the first argument.
+**
+** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
+** ^If the option is unknown or SQLite is unable to set the option
+** then this routine returns a non-zero [error code].
+*/
+SQLITE_API int sqlite3_config(int, ...);
+
+/*
+** CAPI3REF: Configure database connections
+** METHOD: sqlite3
+**
+** The sqlite3_db_config() interface is used to make configuration
+** changes to a [database connection]. The interface is similar to
+** [sqlite3_config()] except that the changes apply to a single
+** [database connection] (specified in the first argument).
+**
+** The second argument to sqlite3_db_config(D,V,...) is the
+** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
+** that indicates what aspect of the [database connection] is being configured.
+** Subsequent arguments vary depending on the configuration verb.
+**
+** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
+** the call is considered successful.
+*/
+SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
+
+/*
+** CAPI3REF: Memory Allocation Routines
+**
+** An instance of this object defines the interface between SQLite
+** and low-level memory allocation routines.
+**
+** This object is used in only one place in the SQLite interface.
+** A pointer to an instance of this object is the argument to
+** [sqlite3_config()] when the configuration option is
+** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
+** By creating an instance of this object
+** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
+** during configuration, an application can specify an alternative
+** memory allocation subsystem for SQLite to use for all of its
+** dynamic memory needs.
+**
+** Note that SQLite comes with several [built-in memory allocators]
+** that are perfectly adequate for the overwhelming majority of applications
+** and that this object is only useful to a tiny minority of applications
+** with specialized memory allocation requirements. This object is
+** also used during testing of SQLite in order to specify an alternative
+** memory allocator that simulates memory out-of-memory conditions in
+** order to verify that SQLite recovers gracefully from such
+** conditions.
+**
+** The xMalloc, xRealloc, and xFree methods must work like the
+** malloc(), realloc() and free() functions from the standard C library.
+** ^SQLite guarantees that the second argument to
+** xRealloc is always a value returned by a prior call to xRoundup.
+**
+** xSize should return the allocated size of a memory allocation
+** previously obtained from xMalloc or xRealloc. The allocated size
+** is always at least as big as the requested size but may be larger.
+**
+** The xRoundup method returns what would be the allocated size of
+** a memory allocation given a particular requested size. Most memory
+** allocators round up memory allocations at least to the next multiple
+** of 8. Some allocators round up to a larger multiple or to a power of 2.
+** Every memory allocation request coming in through [sqlite3_malloc()]
+** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
+** that causes the corresponding memory allocation to fail.
+**
+** The xInit method initializes the memory allocator. For example,
+** it might allocate any required mutexes or initialize internal data
+** structures. The xShutdown method is invoked (indirectly) by
+** [sqlite3_shutdown()] and should deallocate any resources acquired
+** by xInit. The pAppData pointer is used as the only parameter to
+** xInit and xShutdown.
+**
+** SQLite holds the [SQLITE_MUTEX_STATIC_MAIN] mutex when it invokes
+** the xInit method, so the xInit method need not be threadsafe. The
+** xShutdown method is only called from [sqlite3_shutdown()] so it does
+** not need to be threadsafe either. For all other methods, SQLite
+** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
+** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
+** it is by default) and so the methods are automatically serialized.
+** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
+** methods must be threadsafe or else make their own arrangements for
+** serialization.
+**
+** SQLite will never invoke xInit() more than once without an intervening
+** call to xShutdown().
+*/
+typedef struct sqlite3_mem_methods sqlite3_mem_methods;
+struct sqlite3_mem_methods {
+ void *(*xMalloc)(int); /* Memory allocation function */
+ void (*xFree)(void*); /* Free a prior allocation */
+ void *(*xRealloc)(void*,int); /* Resize an allocation */
+ int (*xSize)(void*); /* Return the size of an allocation */
+ int (*xRoundup)(int); /* Round up request size to allocation size */
+ int (*xInit)(void*); /* Initialize the memory allocator */
+ void (*xShutdown)(void*); /* Deinitialize the memory allocator */
+ void *pAppData; /* Argument to xInit() and xShutdown() */
+};
+
+/*
+** CAPI3REF: Configuration Options
+** KEYWORDS: {configuration option}
+**
+** These constants are the available integer configuration options that
+** can be passed as the first argument to the [sqlite3_config()] interface.
+**
+** New configuration options may be added in future releases of SQLite.
+** Existing configuration options might be discontinued. Applications
+** should check the return code from [sqlite3_config()] to make sure that
+** the call worked. The [sqlite3_config()] interface will return a
+** non-zero [error code] if a discontinued or unsupported configuration option
+** is invoked.
+**
+** <dl>
+** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
+** <dd>There are no arguments to this option. ^This option sets the
+** [threading mode] to Single-thread. In other words, it disables
+** all mutexing and puts SQLite into a mode where it can only be used
+** by a single thread. ^If SQLite is compiled with
+** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
+** it is not possible to change the [threading mode] from its default
+** value of Single-thread and so [sqlite3_config()] will return
+** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
+** configuration option.</dd>
+**
+** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
+** <dd>There are no arguments to this option. ^This option sets the
+** [threading mode] to Multi-thread. In other words, it disables
+** mutexing on [database connection] and [prepared statement] objects.
+** The application is responsible for serializing access to
+** [database connections] and [prepared statements]. But other mutexes
+** are enabled so that SQLite will be safe to use in a multi-threaded
+** environment as long as no two threads attempt to use the same
+** [database connection] at the same time. ^If SQLite is compiled with
+** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
+** it is not possible to set the Multi-thread [threading mode] and
+** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
+** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
+**
+** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
+** <dd>There are no arguments to this option. ^This option sets the
+** [threading mode] to Serialized. In other words, this option enables
+** all mutexes including the recursive
+** mutexes on [database connection] and [prepared statement] objects.
+** In this mode (which is the default when SQLite is compiled with
+** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
+** to [database connections] and [prepared statements] so that the
+** application is free to use the same [database connection] or the
+** same [prepared statement] in different threads at the same time.
+** ^If SQLite is compiled with
+** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
+** it is not possible to set the Serialized [threading mode] and
+** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
+** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
+**
+** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
+** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
+** a pointer to an instance of the [sqlite3_mem_methods] structure.
+** The argument specifies
+** alternative low-level memory allocation routines to be used in place of
+** the memory allocation routines built into SQLite.)^ ^SQLite makes
+** its own private copy of the content of the [sqlite3_mem_methods] structure
+** before the [sqlite3_config()] call returns.</dd>
+**
+** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
+** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
+** is a pointer to an instance of the [sqlite3_mem_methods] structure.
+** The [sqlite3_mem_methods]
+** structure is filled with the currently defined memory allocation routines.)^
+** This option can be used to overload the default memory allocation
+** routines with a wrapper that simulations memory allocation failure or
+** tracks memory usage, for example. </dd>
+**
+** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
+** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
+** type int, interpreted as a boolean, which if true provides a hint to
+** SQLite that it should avoid large memory allocations if possible.
+** SQLite will run faster if it is free to make large memory allocations,
+** but some application might prefer to run slower in exchange for
+** guarantees about memory fragmentation that are possible if large
+** allocations are avoided. This hint is normally off.
+** </dd>
+**
+** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
+** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
+** interpreted as a boolean, which enables or disables the collection of
+** memory allocation statistics. ^(When memory allocation statistics are
+** disabled, the following SQLite interfaces become non-operational:
+** <ul>
+** <li> [sqlite3_hard_heap_limit64()]
+** <li> [sqlite3_memory_used()]
+** <li> [sqlite3_memory_highwater()]
+** <li> [sqlite3_soft_heap_limit64()]
+** <li> [sqlite3_status64()]
+** </ul>)^
+** ^Memory allocation statistics are enabled by default unless SQLite is
+** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
+** allocation statistics are disabled by default.
+** </dd>
+**
+** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
+** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
+** </dd>
+**
+** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
+** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
+** that SQLite can use for the database page cache with the default page
+** cache implementation.
+** This configuration option is a no-op if an application-defined page
+** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
+** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
+** 8-byte aligned memory (pMem), the size of each page cache line (sz),
+** and the number of cache lines (N).
+** The sz argument should be the size of the largest database page
+** (a power of two between 512 and 65536) plus some extra bytes for each
+** page header. ^The number of extra bytes needed by the page header
+** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
+** ^It is harmless, apart from the wasted memory,
+** for the sz parameter to be larger than necessary. The pMem
+** argument must be either a NULL pointer or a pointer to an 8-byte
+** aligned block of memory of at least sz*N bytes, otherwise
+** subsequent behavior is undefined.
+** ^When pMem is not NULL, SQLite will strive to use the memory provided
+** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
+** a page cache line is larger than sz bytes or if all of the pMem buffer
+** is exhausted.
+** ^If pMem is NULL and N is non-zero, then each database connection
+** does an initial bulk allocation for page cache memory
+** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
+** of -1024*N bytes if N is negative, . ^If additional
+** page cache memory is needed beyond what is provided by the initial
+** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
+** additional cache line. </dd>
+**
+** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
+** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
+** that SQLite will use for all of its dynamic memory allocation needs
+** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
+** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
+** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
+** [SQLITE_ERROR] if invoked otherwise.
+** ^There are three arguments to SQLITE_CONFIG_HEAP:
+** An 8-byte aligned pointer to the memory,
+** the number of bytes in the memory buffer, and the minimum allocation size.
+** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
+** to using its default memory allocator (the system malloc() implementation),
+** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
+** memory pointer is not NULL then the alternative memory
+** allocator is engaged to handle all of SQLites memory allocation needs.
+** The first pointer (the memory pointer) must be aligned to an 8-byte
+** boundary or subsequent behavior of SQLite will be undefined.
+** The minimum allocation size is capped at 2**12. Reasonable values
+** for the minimum allocation size are 2**5 through 2**8.</dd>
+**
+** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
+** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
+** pointer to an instance of the [sqlite3_mutex_methods] structure.
+** The argument specifies alternative low-level mutex routines to be used
+** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
+** the content of the [sqlite3_mutex_methods] structure before the call to
+** [sqlite3_config()] returns. ^If SQLite is compiled with
+** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
+** the entire mutexing subsystem is omitted from the build and hence calls to
+** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
+** return [SQLITE_ERROR].</dd>
+**
+** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
+** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
+** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
+** [sqlite3_mutex_methods]
+** structure is filled with the currently defined mutex routines.)^
+** This option can be used to overload the default mutex allocation
+** routines with a wrapper used to track mutex usage for performance
+** profiling or testing, for example. ^If SQLite is compiled with
+** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
+** the entire mutexing subsystem is omitted from the build and hence calls to
+** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
+** return [SQLITE_ERROR].</dd>
+**
+** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
+** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
+** the default size of lookaside memory on each [database connection].
+** The first argument is the
+** size of each lookaside buffer slot and the second is the number of
+** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
+** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
+** option to [sqlite3_db_config()] can be used to change the lookaside
+** configuration on individual connections.)^ </dd>
+**
+** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
+** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
+** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
+** the interface to a custom page cache implementation.)^
+** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
+**
+** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
+** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
+** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
+** the current page cache implementation into that object.)^ </dd>
+**
+** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
+** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
+** global [error log].
+** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
+** function with a call signature of void(*)(void*,int,const char*),
+** and a pointer to void. ^If the function pointer is not NULL, it is
+** invoked by [sqlite3_log()] to process each logging event. ^If the
+** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
+** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
+** passed through as the first parameter to the application-defined logger
+** function whenever that function is invoked. ^The second parameter to
+** the logger function is a copy of the first parameter to the corresponding
+** [sqlite3_log()] call and is intended to be a [result code] or an
+** [extended result code]. ^The third parameter passed to the logger is
+** log message after formatting via [sqlite3_snprintf()].
+** The SQLite logging interface is not reentrant; the logger function
+** supplied by the application must not invoke any SQLite interface.
+** In a multi-threaded application, the application-defined logger
+** function must be threadsafe. </dd>
+**
+** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
+** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
+** If non-zero, then URI handling is globally enabled. If the parameter is zero,
+** then URI handling is globally disabled.)^ ^If URI handling is globally
+** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
+** [sqlite3_open16()] or
+** specified as part of [ATTACH] commands are interpreted as URIs, regardless
+** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
+** connection is opened. ^If it is globally disabled, filenames are
+** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
+** database connection is opened. ^(By default, URI handling is globally
+** disabled. The default value may be changed by compiling with the
+** [SQLITE_USE_URI] symbol defined.)^
+**
+** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
+** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
+** argument which is interpreted as a boolean in order to enable or disable
+** the use of covering indices for full table scans in the query optimizer.
+** ^The default setting is determined
+** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
+** if that compile-time option is omitted.
+** The ability to disable the use of covering indices for full table scans
+** is because some incorrectly coded legacy applications might malfunction
+** when the optimization is enabled. Providing the ability to
+** disable the optimization allows the older, buggy application code to work
+** without change even with newer versions of SQLite.
+**
+** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
+** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
+** <dd> These options are obsolete and should not be used by new code.
+** They are retained for backwards compatibility but are now no-ops.
+** </dd>
+**
+** [[SQLITE_CONFIG_SQLLOG]]
+** <dt>SQLITE_CONFIG_SQLLOG
+** <dd>This option is only available if sqlite is compiled with the
+** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
+** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
+** The second should be of type (void*). The callback is invoked by the library
+** in three separate circumstances, identified by the value passed as the
+** fourth parameter. If the fourth parameter is 0, then the database connection
+** passed as the second argument has just been opened. The third argument
+** points to a buffer containing the name of the main database file. If the
+** fourth parameter is 1, then the SQL statement that the third parameter
+** points to has just been executed. Or, if the fourth parameter is 2, then
+** the connection being passed as the second parameter is being closed. The
+** third parameter is passed NULL In this case. An example of using this
+** configuration option can be seen in the "test_sqllog.c" source file in
+** the canonical SQLite source tree.</dd>
+**
+** [[SQLITE_CONFIG_MMAP_SIZE]]
+** <dt>SQLITE_CONFIG_MMAP_SIZE
+** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
+** that are the default mmap size limit (the default setting for
+** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
+** ^The default setting can be overridden by each database connection using
+** either the [PRAGMA mmap_size] command, or by using the
+** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
+** will be silently truncated if necessary so that it does not exceed the
+** compile-time maximum mmap size set by the
+** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
+** ^If either argument to this option is negative, then that argument is
+** changed to its compile-time default.
+**
+** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
+** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
+** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
+** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
+** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
+** that specifies the maximum size of the created heap.
+**
+** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
+** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
+** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
+** is a pointer to an integer and writes into that integer the number of extra
+** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
+** The amount of extra space required can change depending on the compiler,
+** target platform, and SQLite version.
+**
+** [[SQLITE_CONFIG_PMASZ]]
+** <dt>SQLITE_CONFIG_PMASZ
+** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
+** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
+** sorter to that integer. The default minimum PMA Size is set by the
+** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
+** to help with sort operations when multithreaded sorting
+** is enabled (using the [PRAGMA threads] command) and the amount of content
+** to be sorted exceeds the page size times the minimum of the
+** [PRAGMA cache_size] setting and this value.
+**
+** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
+** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
+** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
+** becomes the [statement journal] spill-to-disk threshold.
+** [Statement journals] are held in memory until their size (in bytes)
+** exceeds this threshold, at which point they are written to disk.
+** Or if the threshold is -1, statement journals are always held
+** exclusively in memory.
+** Since many statement journals never become large, setting the spill
+** threshold to a value such as 64KiB can greatly reduce the amount of
+** I/O required to support statement rollback.
+** The default value for this setting is controlled by the
+** [SQLITE_STMTJRNL_SPILL] compile-time option.
+**
+** [[SQLITE_CONFIG_SORTERREF_SIZE]]
+** <dt>SQLITE_CONFIG_SORTERREF_SIZE
+** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter
+** of type (int) - the new value of the sorter-reference size threshold.
+** Usually, when SQLite uses an external sort to order records according
+** to an ORDER BY clause, all fields required by the caller are present in the
+** sorted records. However, if SQLite determines based on the declared type
+** of a table column that its values are likely to be very large - larger
+** than the configured sorter-reference size threshold - then a reference
+** is stored in each sorted record and the required column values loaded
+** from the database as records are returned in sorted order. The default
+** value for this option is to never use this optimization. Specifying a
+** negative value for this option restores the default behaviour.
+** This option is only available if SQLite is compiled with the
+** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
+**
+** [[SQLITE_CONFIG_MEMDB_MAXSIZE]]
+** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE
+** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter
+** [sqlite3_int64] parameter which is the default maximum size for an in-memory
+** database created using [sqlite3_deserialize()]. This default maximum
+** size can be adjusted up or down for individual databases using the
+** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control]. If this
+** configuration setting is never used, then the default maximum is determined
+** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option. If that
+** compile-time option is not set, then the default maximum is 1073741824.
+** </dl>
+*/
+#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
+#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
+#define SQLITE_CONFIG_SERIALIZED 3 /* nil */
+#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
+#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
+#define SQLITE_CONFIG_SCRATCH 6 /* No longer used */
+#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
+#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
+#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
+#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
+#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
+/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
+#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
+#define SQLITE_CONFIG_PCACHE 14 /* no-op */
+#define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
+#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
+#define SQLITE_CONFIG_URI 17 /* int */
+#define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
+#define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
+#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
+#define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
+#define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
+#define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
+#define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
+#define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
+#define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
+#define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */
+#define SQLITE_CONFIG_SORTERREF_SIZE 28 /* int nByte */
+#define SQLITE_CONFIG_MEMDB_MAXSIZE 29 /* sqlite3_int64 */
+
+/*
+** CAPI3REF: Database Connection Configuration Options
+**
+** These constants are the available integer configuration options that
+** can be passed as the second argument to the [sqlite3_db_config()] interface.
+**
+** New configuration options may be added in future releases of SQLite.
+** Existing configuration options might be discontinued. Applications
+** should check the return code from [sqlite3_db_config()] to make sure that
+** the call worked. ^The [sqlite3_db_config()] interface will return a
+** non-zero [error code] if a discontinued or unsupported configuration option
+** is invoked.
+**
+** <dl>
+** [[SQLITE_DBCONFIG_LOOKASIDE]]
+** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
+** <dd> ^This option takes three additional arguments that determine the
+** [lookaside memory allocator] configuration for the [database connection].
+** ^The first argument (the third parameter to [sqlite3_db_config()] is a
+** pointer to a memory buffer to use for lookaside memory.
+** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
+** may be NULL in which case SQLite will allocate the
+** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
+** size of each lookaside buffer slot. ^The third argument is the number of
+** slots. The size of the buffer in the first argument must be greater than
+** or equal to the product of the second and third arguments. The buffer
+** must be aligned to an 8-byte boundary. ^If the second argument to
+** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
+** rounded down to the next smaller multiple of 8. ^(The lookaside memory
+** configuration for a database connection can only be changed when that
+** connection is not currently using lookaside memory, or in other words
+** when the "current value" returned by
+** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
+** Any attempt to change the lookaside memory configuration when lookaside
+** memory is in use leaves the configuration unchanged and returns
+** [SQLITE_BUSY].)^</dd>
+**
+** [[SQLITE_DBCONFIG_ENABLE_FKEY]]
+** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
+** <dd> ^This option is used to enable or disable the enforcement of
+** [foreign key constraints]. There should be two additional arguments.
+** The first argument is an integer which is 0 to disable FK enforcement,
+** positive to enable FK enforcement or negative to leave FK enforcement
+** unchanged. The second parameter is a pointer to an integer into which
+** is written 0 or 1 to indicate whether FK enforcement is off or on
+** following this call. The second parameter may be a NULL pointer, in
+** which case the FK enforcement setting is not reported back. </dd>
+**
+** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]]
+** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
+** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
+** There should be two additional arguments.
+** The first argument is an integer which is 0 to disable triggers,
+** positive to enable triggers or negative to leave the setting unchanged.
+** The second parameter is a pointer to an integer into which
+** is written 0 or 1 to indicate whether triggers are disabled or enabled
+** following this call. The second parameter may be a NULL pointer, in
+** which case the trigger setting is not reported back. </dd>
+**
+** [[SQLITE_DBCONFIG_ENABLE_VIEW]]
+** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt>
+** <dd> ^This option is used to enable or disable [CREATE VIEW | views].
+** There should be two additional arguments.
+** The first argument is an integer which is 0 to disable views,
+** positive to enable views or negative to leave the setting unchanged.
+** The second parameter is a pointer to an integer into which
+** is written 0 or 1 to indicate whether views are disabled or enabled
+** following this call. The second parameter may be a NULL pointer, in
+** which case the view setting is not reported back. </dd>
+**
+** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]
+** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
+** <dd> ^This option is used to enable or disable the
+** [fts3_tokenizer()] function which is part of the
+** [FTS3] full-text search engine extension.
+** There should be two additional arguments.
+** The first argument is an integer which is 0 to disable fts3_tokenizer() or
+** positive to enable fts3_tokenizer() or negative to leave the setting
+** unchanged.
+** The second parameter is a pointer to an integer into which
+** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
+** following this call. The second parameter may be a NULL pointer, in
+** which case the new setting is not reported back. </dd>
+**
+** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]
+** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
+** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
+** interface independently of the [load_extension()] SQL function.
+** The [sqlite3_enable_load_extension()] API enables or disables both the
+** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
+** There should be two additional arguments.
+** When the first argument to this interface is 1, then only the C-API is
+** enabled and the SQL function remains disabled. If the first argument to
+** this interface is 0, then both the C-API and the SQL function are disabled.
+** If the first argument is -1, then no changes are made to state of either the
+** C-API or the SQL function.
+** The second parameter is a pointer to an integer into which
+** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
+** is disabled or enabled following this call. The second parameter may
+** be a NULL pointer, in which case the new setting is not reported back.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
+** <dd> ^This option is used to change the name of the "main" database
+** schema. ^The sole argument is a pointer to a constant UTF8 string
+** which will become the new schema name in place of "main". ^SQLite
+** does not make a copy of the new main schema name string, so the application
+** must ensure that the argument passed into this DBCONFIG option is unchanged
+** until after the database connection closes.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]]
+** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
+** <dd> Usually, when a database in wal mode is closed or detached from a
+** database handle, SQLite checks if this will mean that there are now no
+** connections at all to the database. If so, it performs a checkpoint
+** operation before closing the connection. This option may be used to
+** override this behaviour. The first parameter passed to this operation
+** is an integer - positive to disable checkpoints-on-close, or zero (the
+** default) to enable them, and negative to leave the setting unchanged.
+** The second parameter is a pointer to an integer
+** into which is written 0 or 1 to indicate whether checkpoints-on-close
+** have been disabled - 0 if they are not disabled, 1 if they are.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
+** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
+** the [query planner stability guarantee] (QPSG). When the QPSG is active,
+** a single SQL query statement will always use the same algorithm regardless
+** of values of [bound parameters].)^ The QPSG disables some query optimizations
+** that look at the values of bound parameters, which can make some queries
+** slower. But the QPSG has the advantage of more predictable behavior. With
+** the QPSG active, SQLite will always use the same query plan in the field as
+** was used during testing in the lab.
+** The first argument to this setting is an integer which is 0 to disable
+** the QPSG, positive to enable QPSG, or negative to leave the setting
+** unchanged. The second parameter is a pointer to an integer into which
+** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
+** following this call.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
+** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not
+** include output for any operations performed by trigger programs. This
+** option is used to set or clear (the default) a flag that governs this
+** behavior. The first parameter passed to this operation is an integer -
+** positive to enable output for trigger programs, or zero to disable it,
+** or negative to leave the setting unchanged.
+** The second parameter is a pointer to an integer into which is written
+** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
+** it is not disabled, 1 if it is.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
+** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
+** [VACUUM] in order to reset a database back to an empty database
+** with no schema and no content. The following process works even for
+** a badly corrupted database file:
+** <ol>
+** <li> If the database connection is newly opened, make sure it has read the
+** database schema by preparing then discarding some query against the
+** database, or calling sqlite3_table_column_metadata(), ignoring any
+** errors. This step is only necessary if the application desires to keep
+** the database in WAL mode after the reset if it was in WAL mode before
+** the reset.
+** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
+** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
+** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
+** </ol>
+** Because resetting a database is destructive and irreversible, the
+** process requires the use of this obscure API and multiple steps to help
+** ensure that it does not happen by accident.
+**
+** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>
+** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
+** "defensive" flag for a database connection. When the defensive
+** flag is enabled, language features that allow ordinary SQL to
+** deliberately corrupt the database file are disabled. The disabled
+** features include but are not limited to the following:
+** <ul>
+** <li> The [PRAGMA writable_schema=ON] statement.
+** <li> The [PRAGMA journal_mode=OFF] statement.
+** <li> Writes to the [sqlite_dbpage] virtual table.
+** <li> Direct writes to [shadow tables].
+** </ul>
+** </dd>
+**
+** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] <dt>SQLITE_DBCONFIG_WRITABLE_SCHEMA</dt>
+** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the
+** "writable_schema" flag. This has the same effect and is logically equivalent
+** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF].
+** The first argument to this setting is an integer which is 0 to disable
+** the writable_schema, positive to enable writable_schema, or negative to
+** leave the setting unchanged. The second parameter is a pointer to an
+** integer into which is written 0 or 1 to indicate whether the writable_schema
+** is enabled or disabled following this call.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]]
+** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt>
+** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates
+** the legacy behavior of the [ALTER TABLE RENAME] command such it
+** behaves as it did prior to [version 3.24.0] (2018-06-04). See the
+** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for
+** additional information. This feature can also be turned on and off
+** using the [PRAGMA legacy_alter_table] statement.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_DQS_DML]]
+** <dt>SQLITE_DBCONFIG_DQS_DML</td>
+** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
+** the legacy [double-quoted string literal] misfeature for DML statements
+** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
+** default value of this setting is determined by the [-DSQLITE_DQS]
+** compile-time option.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_DQS_DDL]]
+** <dt>SQLITE_DBCONFIG_DQS_DDL</td>
+** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates
+** the legacy [double-quoted string literal] misfeature for DDL statements,
+** such as CREATE TABLE and CREATE INDEX. The
+** default value of this setting is determined by the [-DSQLITE_DQS]
+** compile-time option.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]
+** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</td>
+** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to
+** assume that database schemas are untainted by malicious content.
+** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite
+** takes additional defensive steps to protect the application from harm
+** including:
+** <ul>
+** <li> Prohibit the use of SQL functions inside triggers, views,
+** CHECK constraints, DEFAULT clauses, expression indexes,
+** partial indexes, or generated columns
+** unless those functions are tagged with [SQLITE_INNOCUOUS].
+** <li> Prohibit the use of virtual tables inside of triggers or views
+** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].
+** </ul>
+** This setting defaults to "on" for legacy compatibility, however
+** all applications are advised to turn it off if possible. This setting
+** can also be controlled using the [PRAGMA trusted_schema] statement.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]
+** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</td>
+** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates
+** the legacy file format flag. When activated, this flag causes all newly
+** created database file to have a schema format version number (the 4-byte
+** integer found at offset 44 into the database header) of 1. This in turn
+** means that the resulting database file will be readable and writable by
+** any SQLite version back to 3.0.0 ([dateof:3.0.0]). Without this setting,
+** newly created databases are generally not understandable by SQLite versions
+** prior to 3.3.0 ([dateof:3.3.0]). As these words are written, there
+** is now scarcely any need to generated database files that are compatible
+** all the way back to version 3.0.0, and so this setting is of little
+** practical use, but is provided so that SQLite can continue to claim the
+** ability to generate new database files that are compatible with version
+** 3.0.0.
+** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,
+** the [VACUUM] command will fail with an obscure error when attempting to
+** process a table with generated columns and a descending index. This is
+** not considered a bug since SQLite versions 3.3.0 and earlier do not support
+** either generated columns or decending indexes.
+** </dd>
+** </dl>
+*/
+#define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
+#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
+#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
+#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
+#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
+#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
+#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */
+#define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */
+#define SQLITE_DBCONFIG_TRIGGER_EQP 1008 /* int int* */
+#define SQLITE_DBCONFIG_RESET_DATABASE 1009 /* int int* */
+#define SQLITE_DBCONFIG_DEFENSIVE 1010 /* int int* */
+#define SQLITE_DBCONFIG_WRITABLE_SCHEMA 1011 /* int int* */
+#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE 1012 /* int int* */
+#define SQLITE_DBCONFIG_DQS_DML 1013 /* int int* */
+#define SQLITE_DBCONFIG_DQS_DDL 1014 /* int int* */
+#define SQLITE_DBCONFIG_ENABLE_VIEW 1015 /* int int* */
+#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT 1016 /* int int* */
+#define SQLITE_DBCONFIG_TRUSTED_SCHEMA 1017 /* int int* */
+#define SQLITE_DBCONFIG_MAX 1017 /* Largest DBCONFIG */
+
+/*
+** CAPI3REF: Enable Or Disable Extended Result Codes
+** METHOD: sqlite3
+**
+** ^The sqlite3_extended_result_codes() routine enables or disables the
+** [extended result codes] feature of SQLite. ^The extended result
+** codes are disabled by default for historical compatibility.
+*/
+SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
+
+/*
+** CAPI3REF: Last Insert Rowid
+** METHOD: sqlite3
+**
+** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
+** has a unique 64-bit signed
+** integer key called the [ROWID | "rowid"]. ^The rowid is always available
+** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
+** names are not also used by explicitly declared columns. ^If
+** the table has a column of type [INTEGER PRIMARY KEY] then that column
+** is another alias for the rowid.
+**
+** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
+** the most recent successful [INSERT] into a rowid table or [virtual table]
+** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
+** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
+** on the database connection D, then sqlite3_last_insert_rowid(D) returns
+** zero.
+**
+** As well as being set automatically as rows are inserted into database
+** tables, the value returned by this function may be set explicitly by
+** [sqlite3_set_last_insert_rowid()]
+**
+** Some virtual table implementations may INSERT rows into rowid tables as
+** part of committing a transaction (e.g. to flush data accumulated in memory
+** to disk). In this case subsequent calls to this function return the rowid
+** associated with these internal INSERT operations, which leads to
+** unintuitive results. Virtual table implementations that do write to rowid
+** tables in this way can avoid this problem by restoring the original
+** rowid value using [sqlite3_set_last_insert_rowid()] before returning
+** control to the user.
+**
+** ^(If an [INSERT] occurs within a trigger then this routine will
+** return the [rowid] of the inserted row as long as the trigger is
+** running. Once the trigger program ends, the value returned
+** by this routine reverts to what it was before the trigger was fired.)^
+**
+** ^An [INSERT] that fails due to a constraint violation is not a
+** successful [INSERT] and does not change the value returned by this
+** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
+** and INSERT OR ABORT make no changes to the return value of this
+** routine when their insertion fails. ^(When INSERT OR REPLACE
+** encounters a constraint violation, it does not fail. The
+** INSERT continues to completion after deleting rows that caused
+** the constraint problem so INSERT OR REPLACE will always change
+** the return value of this interface.)^
+**
+** ^For the purposes of this routine, an [INSERT] is considered to
+** be successful even if it is subsequently rolled back.
+**
+** This function is accessible to SQL statements via the
+** [last_insert_rowid() SQL function].
+**
+** If a separate thread performs a new [INSERT] on the same
+** database connection while the [sqlite3_last_insert_rowid()]
+** function is running and thus changes the last insert [rowid],
+** then the value returned by [sqlite3_last_insert_rowid()] is
+** unpredictable and might not equal either the old or the new
+** last insert [rowid].
+*/
+SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
+
+/*
+** CAPI3REF: Set the Last Insert Rowid value.
+** METHOD: sqlite3
+**
+** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
+** set the value returned by calling sqlite3_last_insert_rowid(D) to R
+** without inserting a row into the database.
+*/
+SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
+
+/*
+** CAPI3REF: Count The Number Of Rows Modified
+** METHOD: sqlite3
+**
+** ^This function returns the number of rows modified, inserted or
+** deleted by the most recently completed INSERT, UPDATE or DELETE
+** statement on the database connection specified by the only parameter.
+** ^Executing any other type of SQL statement does not modify the value
+** returned by this function.
+**
+** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
+** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
+** [foreign key actions] or [REPLACE] constraint resolution are not counted.
+**
+** Changes to a view that are intercepted by
+** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
+** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
+** DELETE statement run on a view is always zero. Only changes made to real
+** tables are counted.
+**
+** Things are more complicated if the sqlite3_changes() function is
+** executed while a trigger program is running. This may happen if the
+** program uses the [changes() SQL function], or if some other callback
+** function invokes sqlite3_changes() directly. Essentially:
+**
+** <ul>
+** <li> ^(Before entering a trigger program the value returned by
+** sqlite3_changes() function is saved. After the trigger program
+** has finished, the original value is restored.)^
+**
+** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
+** statement sets the value returned by sqlite3_changes()
+** upon completion as normal. Of course, this value will not include
+** any changes performed by sub-triggers, as the sqlite3_changes()
+** value will be saved and restored after each sub-trigger has run.)^
+** </ul>
+**
+** ^This means that if the changes() SQL function (or similar) is used
+** by the first INSERT, UPDATE or DELETE statement within a trigger, it
+** returns the value as set when the calling statement began executing.
+** ^If it is used by the second or subsequent such statement within a trigger
+** program, the value returned reflects the number of rows modified by the
+** previous INSERT, UPDATE or DELETE statement within the same trigger.
+**
+** If a separate thread makes changes on the same database connection
+** while [sqlite3_changes()] is running then the value returned
+** is unpredictable and not meaningful.
+**
+** See also:
+** <ul>
+** <li> the [sqlite3_total_changes()] interface
+** <li> the [count_changes pragma]
+** <li> the [changes() SQL function]
+** <li> the [data_version pragma]
+** </ul>
+*/
+SQLITE_API int sqlite3_changes(sqlite3*);
+
+/*
+** CAPI3REF: Total Number Of Rows Modified
+** METHOD: sqlite3
+**
+** ^This function returns the total number of rows inserted, modified or
+** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
+** since the database connection was opened, including those executed as
+** part of trigger programs. ^Executing any other type of SQL statement
+** does not affect the value returned by sqlite3_total_changes().
+**
+** ^Changes made as part of [foreign key actions] are included in the
+** count, but those made as part of REPLACE constraint resolution are
+** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
+** are not counted.
+**
+** The [sqlite3_total_changes(D)] interface only reports the number
+** of rows that changed due to SQL statement run against database
+** connection D. Any changes by other database connections are ignored.
+** To detect changes against a database file from other database
+** connections use the [PRAGMA data_version] command or the
+** [SQLITE_FCNTL_DATA_VERSION] [file control].
+**
+** If a separate thread makes changes on the same database connection
+** while [sqlite3_total_changes()] is running then the value
+** returned is unpredictable and not meaningful.
+**
+** See also:
+** <ul>
+** <li> the [sqlite3_changes()] interface
+** <li> the [count_changes pragma]
+** <li> the [changes() SQL function]
+** <li> the [data_version pragma]
+** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control]
+** </ul>
+*/
+SQLITE_API int sqlite3_total_changes(sqlite3*);
+
+/*
+** CAPI3REF: Interrupt A Long-Running Query
+** METHOD: sqlite3
+**
+** ^This function causes any pending database operation to abort and
+** return at its earliest opportunity. This routine is typically
+** called in response to a user action such as pressing "Cancel"
+** or Ctrl-C where the user wants a long query operation to halt
+** immediately.
+**
+** ^It is safe to call this routine from a thread different from the
+** thread that is currently running the database operation. But it
+** is not safe to call this routine with a [database connection] that
+** is closed or might close before sqlite3_interrupt() returns.
+**
+** ^If an SQL operation is very nearly finished at the time when
+** sqlite3_interrupt() is called, then it might not have an opportunity
+** to be interrupted and might continue to completion.
+**
+** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
+** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
+** that is inside an explicit transaction, then the entire transaction
+** will be rolled back automatically.
+**
+** ^The sqlite3_interrupt(D) call is in effect until all currently running
+** SQL statements on [database connection] D complete. ^Any new SQL statements
+** that are started after the sqlite3_interrupt() call and before the
+** running statement count reaches zero are interrupted as if they had been
+** running prior to the sqlite3_interrupt() call. ^New SQL statements
+** that are started after the running statement count reaches zero are
+** not effected by the sqlite3_interrupt().
+** ^A call to sqlite3_interrupt(D) that occurs when there are no running
+** SQL statements is a no-op and has no effect on SQL statements
+** that are started after the sqlite3_interrupt() call returns.
+*/
+SQLITE_API void sqlite3_interrupt(sqlite3*);
+
+/*
+** CAPI3REF: Determine If An SQL Statement Is Complete
+**
+** These routines are useful during command-line input to determine if the
+** currently entered text seems to form a complete SQL statement or
+** if additional input is needed before sending the text into
+** SQLite for parsing. ^These routines return 1 if the input string
+** appears to be a complete SQL statement. ^A statement is judged to be
+** complete if it ends with a semicolon token and is not a prefix of a
+** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
+** string literals or quoted identifier names or comments are not
+** independent tokens (they are part of the token in which they are
+** embedded) and thus do not count as a statement terminator. ^Whitespace
+** and comments that follow the final semicolon are ignored.
+**
+** ^These routines return 0 if the statement is incomplete. ^If a
+** memory allocation fails, then SQLITE_NOMEM is returned.
+**
+** ^These routines do not parse the SQL statements thus
+** will not detect syntactically incorrect SQL.
+**
+** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
+** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
+** automatically by sqlite3_complete16(). If that initialization fails,
+** then the return value from sqlite3_complete16() will be non-zero
+** regardless of whether or not the input SQL is complete.)^
+**
+** The input to [sqlite3_complete()] must be a zero-terminated
+** UTF-8 string.
+**
+** The input to [sqlite3_complete16()] must be a zero-terminated
+** UTF-16 string in native byte order.
+*/
+SQLITE_API int sqlite3_complete(const char *sql);
+SQLITE_API int sqlite3_complete16(const void *sql);
+
+/*
+** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
+** KEYWORDS: {busy-handler callback} {busy handler}
+** METHOD: sqlite3
+**
+** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
+** that might be invoked with argument P whenever
+** an attempt is made to access a database table associated with
+** [database connection] D when another thread
+** or process has the table locked.
+** The sqlite3_busy_handler() interface is used to implement
+** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
+**
+** ^If the busy callback is NULL, then [SQLITE_BUSY]
+** is returned immediately upon encountering the lock. ^If the busy callback
+** is not NULL, then the callback might be invoked with two arguments.
+**
+** ^The first argument to the busy handler is a copy of the void* pointer which
+** is the third argument to sqlite3_busy_handler(). ^The second argument to
+** the busy handler callback is the number of times that the busy handler has
+** been invoked previously for the same locking event. ^If the
+** busy callback returns 0, then no additional attempts are made to
+** access the database and [SQLITE_BUSY] is returned
+** to the application.
+** ^If the callback returns non-zero, then another attempt
+** is made to access the database and the cycle repeats.
+**
+** The presence of a busy handler does not guarantee that it will be invoked
+** when there is lock contention. ^If SQLite determines that invoking the busy
+** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
+** to the application instead of invoking the
+** busy handler.
+** Consider a scenario where one process is holding a read lock that
+** it is trying to promote to a reserved lock and
+** a second process is holding a reserved lock that it is trying
+** to promote to an exclusive lock. The first process cannot proceed
+** because it is blocked by the second and the second process cannot
+** proceed because it is blocked by the first. If both processes
+** invoke the busy handlers, neither will make any progress. Therefore,
+** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
+** will induce the first process to release its read lock and allow
+** the second process to proceed.
+**
+** ^The default busy callback is NULL.
+**
+** ^(There can only be a single busy handler defined for each
+** [database connection]. Setting a new busy handler clears any
+** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
+** or evaluating [PRAGMA busy_timeout=N] will change the
+** busy handler and thus clear any previously set busy handler.
+**
+** The busy callback should not take any actions which modify the
+** database connection that invoked the busy handler. In other words,
+** the busy handler is not reentrant. Any such actions
+** result in undefined behavior.
+**
+** A busy handler must not close the database connection
+** or [prepared statement] that invoked the busy handler.
+*/
+SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
+
+/*
+** CAPI3REF: Set A Busy Timeout
+** METHOD: sqlite3
+**
+** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
+** for a specified amount of time when a table is locked. ^The handler
+** will sleep multiple times until at least "ms" milliseconds of sleeping
+** have accumulated. ^After at least "ms" milliseconds of sleeping,
+** the handler returns 0 which causes [sqlite3_step()] to return
+** [SQLITE_BUSY].
+**
+** ^Calling this routine with an argument less than or equal to zero
+** turns off all busy handlers.
+**
+** ^(There can only be a single busy handler for a particular
+** [database connection] at any given moment. If another busy handler
+** was defined (using [sqlite3_busy_handler()]) prior to calling
+** this routine, that other busy handler is cleared.)^
+**
+** See also: [PRAGMA busy_timeout]
+*/
+SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
+
+/*
+** CAPI3REF: Convenience Routines For Running Queries
+** METHOD: sqlite3
+**
+** This is a legacy interface that is preserved for backwards compatibility.
+** Use of this interface is not recommended.
+**
+** Definition: A <b>result table</b> is memory data structure created by the
+** [sqlite3_get_table()] interface. A result table records the
+** complete query results from one or more queries.
+**
+** The table conceptually has a number of rows and columns. But
+** these numbers are not part of the result table itself. These
+** numbers are obtained separately. Let N be the number of rows
+** and M be the number of columns.
+**
+** A result table is an array of pointers to zero-terminated UTF-8 strings.
+** There are (N+1)*M elements in the array. The first M pointers point
+** to zero-terminated strings that contain the names of the columns.
+** The remaining entries all point to query results. NULL values result
+** in NULL pointers. All other values are in their UTF-8 zero-terminated
+** string representation as returned by [sqlite3_column_text()].
+**
+** A result table might consist of one or more memory allocations.
+** It is not safe to pass a result table directly to [sqlite3_free()].
+** A result table should be deallocated using [sqlite3_free_table()].
+**
+** ^(As an example of the result table format, suppose a query result
+** is as follows:
+**
+** <blockquote><pre>
+** Name | Age
+** -----------------------
+** Alice | 43
+** Bob | 28
+** Cindy | 21
+** </pre></blockquote>
+**
+** There are two columns (M==2) and three rows (N==3). Thus the
+** result table has 8 entries. Suppose the result table is stored
+** in an array named azResult. Then azResult holds this content:
+**
+** <blockquote><pre>
+** azResult&#91;0] = "Name";
+** azResult&#91;1] = "Age";
+** azResult&#91;2] = "Alice";
+** azResult&#91;3] = "43";
+** azResult&#91;4] = "Bob";
+** azResult&#91;5] = "28";
+** azResult&#91;6] = "Cindy";
+** azResult&#91;7] = "21";
+** </pre></blockquote>)^
+**
+** ^The sqlite3_get_table() function evaluates one or more
+** semicolon-separated SQL statements in the zero-terminated UTF-8
+** string of its 2nd parameter and returns a result table to the
+** pointer given in its 3rd parameter.
+**
+** After the application has finished with the result from sqlite3_get_table(),
+** it must pass the result table pointer to sqlite3_free_table() in order to
+** release the memory that was malloced. Because of the way the
+** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
+** function must not try to call [sqlite3_free()] directly. Only
+** [sqlite3_free_table()] is able to release the memory properly and safely.
+**
+** The sqlite3_get_table() interface is implemented as a wrapper around
+** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
+** to any internal data structures of SQLite. It uses only the public
+** interface defined here. As a consequence, errors that occur in the
+** wrapper layer outside of the internal [sqlite3_exec()] call are not
+** reflected in subsequent calls to [sqlite3_errcode()] or
+** [sqlite3_errmsg()].
+*/
+SQLITE_API int sqlite3_get_table(
+ sqlite3 *db, /* An open database */
+ const char *zSql, /* SQL to be evaluated */
+ char ***pazResult, /* Results of the query */
+ int *pnRow, /* Number of result rows written here */
+ int *pnColumn, /* Number of result columns written here */
+ char **pzErrmsg /* Error msg written here */
+);
+SQLITE_API void sqlite3_free_table(char **result);
+
+/*
+** CAPI3REF: Formatted String Printing Functions
+**
+** These routines are work-alikes of the "printf()" family of functions
+** from the standard C library.
+** These routines understand most of the common formatting options from
+** the standard library printf()
+** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
+** See the [built-in printf()] documentation for details.
+**
+** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
+** results into memory obtained from [sqlite3_malloc64()].
+** The strings returned by these two routines should be
+** released by [sqlite3_free()]. ^Both routines return a
+** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough
+** memory to hold the resulting string.
+**
+** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
+** the standard C library. The result is written into the
+** buffer supplied as the second parameter whose size is given by
+** the first parameter. Note that the order of the
+** first two parameters is reversed from snprintf().)^ This is an
+** historical accident that cannot be fixed without breaking
+** backwards compatibility. ^(Note also that sqlite3_snprintf()
+** returns a pointer to its buffer instead of the number of
+** characters actually written into the buffer.)^ We admit that
+** the number of characters written would be a more useful return
+** value but we cannot change the implementation of sqlite3_snprintf()
+** now without breaking compatibility.
+**
+** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
+** guarantees that the buffer is always zero-terminated. ^The first
+** parameter "n" is the total size of the buffer, including space for
+** the zero terminator. So the longest string that can be completely
+** written will be n-1 characters.
+**
+** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
+**
+** See also: [built-in printf()], [printf() SQL function]
+*/
+SQLITE_API char *sqlite3_mprintf(const char*,...);
+SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
+SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
+SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
+
+/*
+** CAPI3REF: Memory Allocation Subsystem
+**
+** The SQLite core uses these three routines for all of its own
+** internal memory allocation needs. "Core" in the previous sentence
+** does not include operating-system specific [VFS] implementation. The
+** Windows VFS uses native malloc() and free() for some operations.
+**
+** ^The sqlite3_malloc() routine returns a pointer to a block
+** of memory at least N bytes in length, where N is the parameter.
+** ^If sqlite3_malloc() is unable to obtain sufficient free
+** memory, it returns a NULL pointer. ^If the parameter N to
+** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
+** a NULL pointer.
+**
+** ^The sqlite3_malloc64(N) routine works just like
+** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
+** of a signed 32-bit integer.
+**
+** ^Calling sqlite3_free() with a pointer previously returned
+** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
+** that it might be reused. ^The sqlite3_free() routine is
+** a no-op if is called with a NULL pointer. Passing a NULL pointer
+** to sqlite3_free() is harmless. After being freed, memory
+** should neither be read nor written. Even reading previously freed
+** memory might result in a segmentation fault or other severe error.
+** Memory corruption, a segmentation fault, or other severe error
+** might result if sqlite3_free() is called with a non-NULL pointer that
+** was not obtained from sqlite3_malloc() or sqlite3_realloc().
+**
+** ^The sqlite3_realloc(X,N) interface attempts to resize a
+** prior memory allocation X to be at least N bytes.
+** ^If the X parameter to sqlite3_realloc(X,N)
+** is a NULL pointer then its behavior is identical to calling
+** sqlite3_malloc(N).
+** ^If the N parameter to sqlite3_realloc(X,N) is zero or
+** negative then the behavior is exactly the same as calling
+** sqlite3_free(X).
+** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
+** of at least N bytes in size or NULL if insufficient memory is available.
+** ^If M is the size of the prior allocation, then min(N,M) bytes
+** of the prior allocation are copied into the beginning of buffer returned
+** by sqlite3_realloc(X,N) and the prior allocation is freed.
+** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
+** prior allocation is not freed.
+**
+** ^The sqlite3_realloc64(X,N) interfaces works the same as
+** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
+** of a 32-bit signed integer.
+**
+** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
+** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
+** sqlite3_msize(X) returns the size of that memory allocation in bytes.
+** ^The value returned by sqlite3_msize(X) might be larger than the number
+** of bytes requested when X was allocated. ^If X is a NULL pointer then
+** sqlite3_msize(X) returns zero. If X points to something that is not
+** the beginning of memory allocation, or if it points to a formerly
+** valid memory allocation that has now been freed, then the behavior
+** of sqlite3_msize(X) is undefined and possibly harmful.
+**
+** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
+** sqlite3_malloc64(), and sqlite3_realloc64()
+** is always aligned to at least an 8 byte boundary, or to a
+** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
+** option is used.
+**
+** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
+** must be either NULL or else pointers obtained from a prior
+** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
+** not yet been released.
+**
+** The application must not read or write any part of
+** a block of memory after it has been released using
+** [sqlite3_free()] or [sqlite3_realloc()].
+*/
+SQLITE_API void *sqlite3_malloc(int);
+SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
+SQLITE_API void *sqlite3_realloc(void*, int);
+SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
+SQLITE_API void sqlite3_free(void*);
+SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
+
+/*
+** CAPI3REF: Memory Allocator Statistics
+**
+** SQLite provides these two interfaces for reporting on the status
+** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
+** routines, which form the built-in memory allocation subsystem.
+**
+** ^The [sqlite3_memory_used()] routine returns the number of bytes
+** of memory currently outstanding (malloced but not freed).
+** ^The [sqlite3_memory_highwater()] routine returns the maximum
+** value of [sqlite3_memory_used()] since the high-water mark
+** was last reset. ^The values returned by [sqlite3_memory_used()] and
+** [sqlite3_memory_highwater()] include any overhead
+** added by SQLite in its implementation of [sqlite3_malloc()],
+** but not overhead added by the any underlying system library
+** routines that [sqlite3_malloc()] may call.
+**
+** ^The memory high-water mark is reset to the current value of
+** [sqlite3_memory_used()] if and only if the parameter to
+** [sqlite3_memory_highwater()] is true. ^The value returned
+** by [sqlite3_memory_highwater(1)] is the high-water mark
+** prior to the reset.
+*/
+SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
+SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
+
+/*
+** CAPI3REF: Pseudo-Random Number Generator
+**
+** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
+** select random [ROWID | ROWIDs] when inserting new records into a table that
+** already uses the largest possible [ROWID]. The PRNG is also used for
+** the built-in random() and randomblob() SQL functions. This interface allows
+** applications to access the same PRNG for other purposes.
+**
+** ^A call to this routine stores N bytes of randomness into buffer P.
+** ^The P parameter can be a NULL pointer.
+**
+** ^If this routine has not been previously called or if the previous
+** call had N less than one or a NULL pointer for P, then the PRNG is
+** seeded using randomness obtained from the xRandomness method of
+** the default [sqlite3_vfs] object.
+** ^If the previous call to this routine had an N of 1 or more and a
+** non-NULL P then the pseudo-randomness is generated
+** internally and without recourse to the [sqlite3_vfs] xRandomness
+** method.
+*/
+SQLITE_API void sqlite3_randomness(int N, void *P);
+
+/*
+** CAPI3REF: Compile-Time Authorization Callbacks
+** METHOD: sqlite3
+** KEYWORDS: {authorizer callback}
+**
+** ^This routine registers an authorizer callback with a particular
+** [database connection], supplied in the first argument.
+** ^The authorizer callback is invoked as SQL statements are being compiled
+** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
+** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
+** and [sqlite3_prepare16_v3()]. ^At various
+** points during the compilation process, as logic is being created
+** to perform various actions, the authorizer callback is invoked to
+** see if those actions are allowed. ^The authorizer callback should
+** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
+** specific action but allow the SQL statement to continue to be
+** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
+** rejected with an error. ^If the authorizer callback returns
+** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
+** then the [sqlite3_prepare_v2()] or equivalent call that triggered
+** the authorizer will fail with an error message.
+**
+** When the callback returns [SQLITE_OK], that means the operation
+** requested is ok. ^When the callback returns [SQLITE_DENY], the
+** [sqlite3_prepare_v2()] or equivalent call that triggered the
+** authorizer will fail with an error message explaining that
+** access is denied.
+**
+** ^The first parameter to the authorizer callback is a copy of the third
+** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
+** to the callback is an integer [SQLITE_COPY | action code] that specifies
+** the particular action to be authorized. ^The third through sixth parameters
+** to the callback are either NULL pointers or zero-terminated strings
+** that contain additional details about the action to be authorized.
+** Applications must always be prepared to encounter a NULL pointer in any
+** of the third through the sixth parameters of the authorization callback.
+**
+** ^If the action code is [SQLITE_READ]
+** and the callback returns [SQLITE_IGNORE] then the
+** [prepared statement] statement is constructed to substitute
+** a NULL value in place of the table column that would have
+** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
+** return can be used to deny an untrusted user access to individual
+** columns of a table.
+** ^When a table is referenced by a [SELECT] but no column values are
+** extracted from that table (for example in a query like
+** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
+** is invoked once for that table with a column name that is an empty string.
+** ^If the action code is [SQLITE_DELETE] and the callback returns
+** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
+** [truncate optimization] is disabled and all rows are deleted individually.
+**
+** An authorizer is used when [sqlite3_prepare | preparing]
+** SQL statements from an untrusted source, to ensure that the SQL statements
+** do not try to access data they are not allowed to see, or that they do not
+** try to execute malicious statements that damage the database. For
+** example, an application may allow a user to enter arbitrary
+** SQL queries for evaluation by a database. But the application does
+** not want the user to be able to make arbitrary changes to the
+** database. An authorizer could then be put in place while the
+** user-entered SQL is being [sqlite3_prepare | prepared] that
+** disallows everything except [SELECT] statements.
+**
+** Applications that need to process SQL from untrusted sources
+** might also consider lowering resource limits using [sqlite3_limit()]
+** and limiting database size using the [max_page_count] [PRAGMA]
+** in addition to using an authorizer.
+**
+** ^(Only a single authorizer can be in place on a database connection
+** at a time. Each call to sqlite3_set_authorizer overrides the
+** previous call.)^ ^Disable the authorizer by installing a NULL callback.
+** The authorizer is disabled by default.
+**
+** The authorizer callback must not do anything that will modify
+** the database connection that invoked the authorizer callback.
+** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
+** database connections for the meaning of "modify" in this paragraph.
+**
+** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
+** statement might be re-prepared during [sqlite3_step()] due to a
+** schema change. Hence, the application should ensure that the
+** correct authorizer callback remains in place during the [sqlite3_step()].
+**
+** ^Note that the authorizer callback is invoked only during
+** [sqlite3_prepare()] or its variants. Authorization is not
+** performed during statement evaluation in [sqlite3_step()], unless
+** as stated in the previous paragraph, sqlite3_step() invokes
+** sqlite3_prepare_v2() to reprepare a statement after a schema change.
+*/
+SQLITE_API int sqlite3_set_authorizer(
+ sqlite3*,
+ int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
+ void *pUserData
+);
+
+/*
+** CAPI3REF: Authorizer Return Codes
+**
+** The [sqlite3_set_authorizer | authorizer callback function] must
+** return either [SQLITE_OK] or one of these two constants in order
+** to signal SQLite whether or not the action is permitted. See the
+** [sqlite3_set_authorizer | authorizer documentation] for additional
+** information.
+**
+** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
+** returned from the [sqlite3_vtab_on_conflict()] interface.
+*/
+#define SQLITE_DENY 1 /* Abort the SQL statement with an error */
+#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
+
+/*
+** CAPI3REF: Authorizer Action Codes
+**
+** The [sqlite3_set_authorizer()] interface registers a callback function
+** that is invoked to authorize certain SQL statement actions. The
+** second parameter to the callback is an integer code that specifies
+** what action is being authorized. These are the integer action codes that
+** the authorizer callback may be passed.
+**
+** These action code values signify what kind of operation is to be
+** authorized. The 3rd and 4th parameters to the authorization
+** callback function will be parameters or NULL depending on which of these
+** codes is used as the second parameter. ^(The 5th parameter to the
+** authorizer callback is the name of the database ("main", "temp",
+** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
+** is the name of the inner-most trigger or view that is responsible for
+** the access attempt or NULL if this access attempt is directly from
+** top-level SQL code.
+*/
+/******************************************* 3rd ************ 4th ***********/
+#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
+#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
+#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
+#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
+#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
+#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
+#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
+#define SQLITE_CREATE_VIEW 8 /* View Name NULL */
+#define SQLITE_DELETE 9 /* Table Name NULL */
+#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
+#define SQLITE_DROP_TABLE 11 /* Table Name NULL */
+#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
+#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
+#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
+#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
+#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
+#define SQLITE_DROP_VIEW 17 /* View Name NULL */
+#define SQLITE_INSERT 18 /* Table Name NULL */
+#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
+#define SQLITE_READ 20 /* Table Name Column Name */
+#define SQLITE_SELECT 21 /* NULL NULL */
+#define SQLITE_TRANSACTION 22 /* Operation NULL */
+#define SQLITE_UPDATE 23 /* Table Name Column Name */
+#define SQLITE_ATTACH 24 /* Filename NULL */
+#define SQLITE_DETACH 25 /* Database Name NULL */
+#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
+#define SQLITE_REINDEX 27 /* Index Name NULL */
+#define SQLITE_ANALYZE 28 /* Table Name NULL */
+#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
+#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
+#define SQLITE_FUNCTION 31 /* NULL Function Name */
+#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
+#define SQLITE_COPY 0 /* No longer used */
+#define SQLITE_RECURSIVE 33 /* NULL NULL */
+
+/*
+** CAPI3REF: Tracing And Profiling Functions
+** METHOD: sqlite3
+**
+** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
+** instead of the routines described here.
+**
+** These routines register callback functions that can be used for
+** tracing and profiling the execution of SQL statements.
+**
+** ^The callback function registered by sqlite3_trace() is invoked at
+** various times when an SQL statement is being run by [sqlite3_step()].
+** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
+** SQL statement text as the statement first begins executing.
+** ^(Additional sqlite3_trace() callbacks might occur
+** as each triggered subprogram is entered. The callbacks for triggers
+** contain a UTF-8 SQL comment that identifies the trigger.)^
+**
+** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
+** the length of [bound parameter] expansion in the output of sqlite3_trace().
+**
+** ^The callback function registered by sqlite3_profile() is invoked
+** as each SQL statement finishes. ^The profile callback contains
+** the original statement text and an estimate of wall-clock time
+** of how long that statement took to run. ^The profile callback
+** time is in units of nanoseconds, however the current implementation
+** is only capable of millisecond resolution so the six least significant
+** digits in the time are meaningless. Future versions of SQLite
+** might provide greater resolution on the profiler callback. Invoking
+** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the
+** profile callback.
+*/
+SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
+ void(*xTrace)(void*,const char*), void*);
+SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
+ void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
+
+/*
+** CAPI3REF: SQL Trace Event Codes
+** KEYWORDS: SQLITE_TRACE
+**
+** These constants identify classes of events that can be monitored
+** using the [sqlite3_trace_v2()] tracing logic. The M argument
+** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
+** the following constants. ^The first argument to the trace callback
+** is one of the following constants.
+**
+** New tracing constants may be added in future releases.
+**
+** ^A trace callback has four arguments: xCallback(T,C,P,X).
+** ^The T argument is one of the integer type codes above.
+** ^The C argument is a copy of the context pointer passed in as the
+** fourth argument to [sqlite3_trace_v2()].
+** The P and X arguments are pointers whose meanings depend on T.
+**
+** <dl>
+** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
+** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
+** first begins running and possibly at other times during the
+** execution of the prepared statement, such as at the start of each
+** trigger subprogram. ^The P argument is a pointer to the
+** [prepared statement]. ^The X argument is a pointer to a string which
+** is the unexpanded SQL text of the prepared statement or an SQL comment
+** that indicates the invocation of a trigger. ^The callback can compute
+** the same text that would have been returned by the legacy [sqlite3_trace()]
+** interface by using the X argument when X begins with "--" and invoking
+** [sqlite3_expanded_sql(P)] otherwise.
+**
+** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
+** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
+** information as is provided by the [sqlite3_profile()] callback.
+** ^The P argument is a pointer to the [prepared statement] and the
+** X argument points to a 64-bit integer which is the estimated of
+** the number of nanosecond that the prepared statement took to run.
+** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
+**
+** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
+** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
+** statement generates a single row of result.
+** ^The P argument is a pointer to the [prepared statement] and the
+** X argument is unused.
+**
+** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
+** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
+** connection closes.
+** ^The P argument is a pointer to the [database connection] object
+** and the X argument is unused.
+** </dl>
+*/
+#define SQLITE_TRACE_STMT 0x01
+#define SQLITE_TRACE_PROFILE 0x02
+#define SQLITE_TRACE_ROW 0x04
+#define SQLITE_TRACE_CLOSE 0x08
+
+/*
+** CAPI3REF: SQL Trace Hook
+** METHOD: sqlite3
+**
+** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
+** function X against [database connection] D, using property mask M
+** and context pointer P. ^If the X callback is
+** NULL or if the M mask is zero, then tracing is disabled. The
+** M argument should be the bitwise OR-ed combination of
+** zero or more [SQLITE_TRACE] constants.
+**
+** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
+** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
+**
+** ^The X callback is invoked whenever any of the events identified by
+** mask M occur. ^The integer return value from the callback is currently
+** ignored, though this may change in future releases. Callback
+** implementations should return zero to ensure future compatibility.
+**
+** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
+** ^The T argument is one of the [SQLITE_TRACE]
+** constants to indicate why the callback was invoked.
+** ^The C argument is a copy of the context pointer.
+** The P and X arguments are pointers whose meanings depend on T.
+**
+** The sqlite3_trace_v2() interface is intended to replace the legacy
+** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
+** are deprecated.
+*/
+SQLITE_API int sqlite3_trace_v2(
+ sqlite3*,
+ unsigned uMask,
+ int(*xCallback)(unsigned,void*,void*,void*),
+ void *pCtx
+);
+
+/*
+** CAPI3REF: Query Progress Callbacks
+** METHOD: sqlite3
+**
+** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
+** function X to be invoked periodically during long running calls to
+** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
+** database connection D. An example use for this
+** interface is to keep a GUI updated during a large query.
+**
+** ^The parameter P is passed through as the only parameter to the
+** callback function X. ^The parameter N is the approximate number of
+** [virtual machine instructions] that are evaluated between successive
+** invocations of the callback X. ^If N is less than one then the progress
+** handler is disabled.
+**
+** ^Only a single progress handler may be defined at one time per
+** [database connection]; setting a new progress handler cancels the
+** old one. ^Setting parameter X to NULL disables the progress handler.
+** ^The progress handler is also disabled by setting N to a value less
+** than 1.
+**
+** ^If the progress callback returns non-zero, the operation is
+** interrupted. This feature can be used to implement a
+** "Cancel" button on a GUI progress dialog box.
+**
+** The progress handler callback must not do anything that will modify
+** the database connection that invoked the progress handler.
+** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
+** database connections for the meaning of "modify" in this paragraph.
+**
+*/
+SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
+
+/*
+** CAPI3REF: Opening A New Database Connection
+** CONSTRUCTOR: sqlite3
+**
+** ^These routines open an SQLite database file as specified by the
+** filename argument. ^The filename argument is interpreted as UTF-8 for
+** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
+** order for sqlite3_open16(). ^(A [database connection] handle is usually
+** returned in *ppDb, even if an error occurs. The only exception is that
+** if SQLite is unable to allocate memory to hold the [sqlite3] object,
+** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
+** object.)^ ^(If the database is opened (and/or created) successfully, then
+** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
+** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
+** an English language description of the error following a failure of any
+** of the sqlite3_open() routines.
+**
+** ^The default encoding will be UTF-8 for databases created using
+** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
+** created using sqlite3_open16() will be UTF-16 in the native byte order.
+**
+** Whether or not an error occurs when it is opened, resources
+** associated with the [database connection] handle should be released by
+** passing it to [sqlite3_close()] when it is no longer required.
+**
+** The sqlite3_open_v2() interface works like sqlite3_open()
+** except that it accepts two additional parameters for additional control
+** over the new database connection. ^(The flags parameter to
+** sqlite3_open_v2() must include, at a minimum, one of the following
+** three flag combinations:)^
+**
+** <dl>
+** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
+** <dd>The database is opened in read-only mode. If the database does not
+** already exist, an error is returned.</dd>)^
+**
+** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
+** <dd>The database is opened for reading and writing if possible, or reading
+** only if the file is write protected by the operating system. In either
+** case the database must already exist, otherwise an error is returned.</dd>)^
+**
+** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
+** <dd>The database is opened for reading and writing, and is created if
+** it does not already exist. This is the behavior that is always used for
+** sqlite3_open() and sqlite3_open16().</dd>)^
+** </dl>
+**
+** In addition to the required flags, the following optional flags are
+** also supported:
+**
+** <dl>
+** ^(<dt>[SQLITE_OPEN_URI]</dt>
+** <dd>The filename can be interpreted as a URI if this flag is set.</dd>)^
+**
+** ^(<dt>[SQLITE_OPEN_MEMORY]</dt>
+** <dd>The database will be opened as an in-memory database. The database
+** is named by the "filename" argument for the purposes of cache-sharing,
+** if shared cache mode is enabled, but the "filename" is otherwise ignored.
+** </dd>)^
+**
+** ^(<dt>[SQLITE_OPEN_NOMUTEX]</dt>
+** <dd>The new database connection will use the "multi-thread"
+** [threading mode].)^ This means that separate threads are allowed
+** to use SQLite at the same time, as long as each thread is using
+** a different [database connection].
+**
+** ^(<dt>[SQLITE_OPEN_FULLMUTEX]</dt>
+** <dd>The new database connection will use the "serialized"
+** [threading mode].)^ This means the multiple threads can safely
+** attempt to use the same database connection at the same time.
+** (Mutexes will block any actual concurrency, but in this mode
+** there is no harm in trying.)
+**
+** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt>
+** <dd>The database is opened [shared cache] enabled, overriding
+** the default shared cache setting provided by
+** [sqlite3_enable_shared_cache()].)^
+**
+** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>
+** <dd>The database is opened [shared cache] disabled, overriding
+** the default shared cache setting provided by
+** [sqlite3_enable_shared_cache()].)^
+**
+** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
+** <dd>The database filename is not allowed to be a symbolic link</dd>
+** </dl>)^
+**
+** If the 3rd parameter to sqlite3_open_v2() is not one of the
+** required combinations shown above optionally combined with other
+** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
+** then the behavior is undefined.
+**
+** ^The fourth parameter to sqlite3_open_v2() is the name of the
+** [sqlite3_vfs] object that defines the operating system interface that
+** the new database connection should use. ^If the fourth parameter is
+** a NULL pointer then the default [sqlite3_vfs] object is used.
+**
+** ^If the filename is ":memory:", then a private, temporary in-memory database
+** is created for the connection. ^This in-memory database will vanish when
+** the database connection is closed. Future versions of SQLite might
+** make use of additional special filenames that begin with the ":" character.
+** It is recommended that when a database filename actually does begin with
+** a ":" character you should prefix the filename with a pathname such as
+** "./" to avoid ambiguity.
+**
+** ^If the filename is an empty string, then a private, temporary
+** on-disk database will be created. ^This private database will be
+** automatically deleted as soon as the database connection is closed.
+**
+** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
+**
+** ^If [URI filename] interpretation is enabled, and the filename argument
+** begins with "file:", then the filename is interpreted as a URI. ^URI
+** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
+** set in the third argument to sqlite3_open_v2(), or if it has
+** been enabled globally using the [SQLITE_CONFIG_URI] option with the
+** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
+** URI filename interpretation is turned off
+** by default, but future releases of SQLite might enable URI filename
+** interpretation by default. See "[URI filenames]" for additional
+** information.
+**
+** URI filenames are parsed according to RFC 3986. ^If the URI contains an
+** authority, then it must be either an empty string or the string
+** "localhost". ^If the authority is not an empty string or "localhost", an
+** error is returned to the caller. ^The fragment component of a URI, if
+** present, is ignored.
+**
+** ^SQLite uses the path component of the URI as the name of the disk file
+** which contains the database. ^If the path begins with a '/' character,
+** then it is interpreted as an absolute path. ^If the path does not begin
+** with a '/' (meaning that the authority section is omitted from the URI)
+** then the path is interpreted as a relative path.
+** ^(On windows, the first component of an absolute path
+** is a drive specification (e.g. "C:").)^
+**
+** [[core URI query parameters]]
+** The query component of a URI may contain parameters that are interpreted
+** either by SQLite itself, or by a [VFS | custom VFS implementation].
+** SQLite and its built-in [VFSes] interpret the
+** following query parameters:
+**
+** <ul>
+** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
+** a VFS object that provides the operating system interface that should
+** be used to access the database file on disk. ^If this option is set to
+** an empty string the default VFS object is used. ^Specifying an unknown
+** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
+** present, then the VFS specified by the option takes precedence over
+** the value passed as the fourth parameter to sqlite3_open_v2().
+**
+** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
+** "rwc", or "memory". Attempting to set it to any other value is
+** an error)^.
+** ^If "ro" is specified, then the database is opened for read-only
+** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
+** third argument to sqlite3_open_v2(). ^If the mode option is set to
+** "rw", then the database is opened for read-write (but not create)
+** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
+** been set. ^Value "rwc" is equivalent to setting both
+** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
+** set to "memory" then a pure [in-memory database] that never reads
+** or writes from disk is used. ^It is an error to specify a value for
+** the mode parameter that is less restrictive than that specified by
+** the flags passed in the third parameter to sqlite3_open_v2().
+**
+** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
+** "private". ^Setting it to "shared" is equivalent to setting the
+** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
+** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
+** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
+** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
+** a URI filename, its value overrides any behavior requested by setting
+** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
+**
+** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
+** [powersafe overwrite] property does or does not apply to the
+** storage media on which the database file resides.
+**
+** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
+** which if set disables file locking in rollback journal modes. This
+** is useful for accessing a database on a filesystem that does not
+** support locking. Caution: Database corruption might result if two
+** or more processes write to the same database and any one of those
+** processes uses nolock=1.
+**
+** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
+** parameter that indicates that the database file is stored on
+** read-only media. ^When immutable is set, SQLite assumes that the
+** database file cannot be changed, even by a process with higher
+** privilege, and so the database is opened read-only and all locking
+** and change detection is disabled. Caution: Setting the immutable
+** property on a database file that does in fact change can result
+** in incorrect query results and/or [SQLITE_CORRUPT] errors.
+** See also: [SQLITE_IOCAP_IMMUTABLE].
+**
+** </ul>
+**
+** ^Specifying an unknown parameter in the query component of a URI is not an
+** error. Future versions of SQLite might understand additional query
+** parameters. See "[query parameters with special meaning to SQLite]" for
+** additional information.
+**
+** [[URI filename examples]] <h3>URI filename examples</h3>
+**
+** <table border="1" align=center cellpadding=5>
+** <tr><th> URI filenames <th> Results
+** <tr><td> file:data.db <td>
+** Open the file "data.db" in the current directory.
+** <tr><td> file:/home/fred/data.db<br>
+** file:///home/fred/data.db <br>
+** file://localhost/home/fred/data.db <br> <td>
+** Open the database file "/home/fred/data.db".
+** <tr><td> file://darkstar/home/fred/data.db <td>
+** An error. "darkstar" is not a recognized authority.
+** <tr><td style="white-space:nowrap">
+** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
+** <td> Windows only: Open the file "data.db" on fred's desktop on drive
+** C:. Note that the %20 escaping in this example is not strictly
+** necessary - space characters can be used literally
+** in URI filenames.
+** <tr><td> file:data.db?mode=ro&cache=private <td>
+** Open file "data.db" in the current directory for read-only access.
+** Regardless of whether or not shared-cache mode is enabled by
+** default, use a private cache.
+** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
+** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
+** that uses dot-files in place of posix advisory locking.
+** <tr><td> file:data.db?mode=readonly <td>
+** An error. "readonly" is not a valid option for the "mode" parameter.
+** </table>
+**
+** ^URI hexadecimal escape sequences (%HH) are supported within the path and
+** query components of a URI. A hexadecimal escape sequence consists of a
+** percent sign - "%" - followed by exactly two hexadecimal digits
+** specifying an octet value. ^Before the path or query components of a
+** URI filename are interpreted, they are encoded using UTF-8 and all
+** hexadecimal escape sequences replaced by a single byte containing the
+** corresponding octet. If this process generates an invalid UTF-8 encoding,
+** the results are undefined.
+**
+** <b>Note to Windows users:</b> The encoding used for the filename argument
+** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
+** codepage is currently defined. Filenames containing international
+** characters must be converted to UTF-8 prior to passing them into
+** sqlite3_open() or sqlite3_open_v2().
+**
+** <b>Note to Windows Runtime users:</b> The temporary directory must be set
+** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
+** features that require the use of temporary files may fail.
+**
+** See also: [sqlite3_temp_directory]
+*/
+SQLITE_API int sqlite3_open(
+ const char *filename, /* Database filename (UTF-8) */
+ sqlite3 **ppDb /* OUT: SQLite db handle */
+);
+SQLITE_API int sqlite3_open16(
+ const void *filename, /* Database filename (UTF-16) */
+ sqlite3 **ppDb /* OUT: SQLite db handle */
+);
+SQLITE_API int sqlite3_open_v2(
+ const char *filename, /* Database filename (UTF-8) */
+ sqlite3 **ppDb, /* OUT: SQLite db handle */
+ int flags, /* Flags */
+ const char *zVfs /* Name of VFS module to use */
+);
+
+/*
+** CAPI3REF: Obtain Values For URI Parameters
+**
+** These are utility routines, useful to [VFS|custom VFS implementations],
+** that check if a database file was a URI that contained a specific query
+** parameter, and if so obtains the value of that query parameter.
+**
+** The first parameter to these interfaces (hereafter referred to
+** as F) must be one of:
+** <ul>
+** <li> A database filename pointer created by the SQLite core and
+** passed into the xOpen() method of a VFS implemention, or
+** <li> A filename obtained from [sqlite3_db_filename()], or
+** <li> A new filename constructed using [sqlite3_create_filename()].
+** </ul>
+** If the F parameter is not one of the above, then the behavior is
+** undefined and probably undesirable. Older versions of SQLite were
+** more tolerant of invalid F parameters than newer versions.
+**
+** If F is a suitable filename (as described in the previous paragraph)
+** and if P is the name of the query parameter, then
+** sqlite3_uri_parameter(F,P) returns the value of the P
+** parameter if it exists or a NULL pointer if P does not appear as a
+** query parameter on F. If P is a query parameter of F and it
+** has no explicit value, then sqlite3_uri_parameter(F,P) returns
+** a pointer to an empty string.
+**
+** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
+** parameter and returns true (1) or false (0) according to the value
+** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
+** value of query parameter P is one of "yes", "true", or "on" in any
+** case or if the value begins with a non-zero number. The
+** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
+** query parameter P is one of "no", "false", or "off" in any case or
+** if the value begins with a numeric zero. If P is not a query
+** parameter on F or if the value of P does not match any of the
+** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
+**
+** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
+** 64-bit signed integer and returns that integer, or D if P does not
+** exist. If the value of P is something other than an integer, then
+** zero is returned.
+**
+** The sqlite3_uri_key(F,N) returns a pointer to the name (not
+** the value) of the N-th query parameter for filename F, or a NULL
+** pointer if N is less than zero or greater than the number of query
+** parameters minus 1. The N value is zero-based so N should be 0 to obtain
+** the name of the first query parameter, 1 for the second parameter, and
+** so forth.
+**
+** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
+** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
+** is not a database file pathname pointer that the SQLite core passed
+** into the xOpen VFS method, then the behavior of this routine is undefined
+** and probably undesirable.
+**
+** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F
+** parameter can also be the name of a rollback journal file or WAL file
+** in addition to the main database file. Prior to version 3.31.0, these
+** routines would only work if F was the name of the main database file.
+** When the F parameter is the name of the rollback journal or WAL file,
+** it has access to all the same query parameters as were found on the
+** main database file.
+**
+** See the [URI filename] documentation for additional information.
+*/
+SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
+SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
+SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
+SQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N);
+
+/*
+** CAPI3REF: Translate filenames
+**
+** These routines are available to [VFS|custom VFS implementations] for
+** translating filenames between the main database file, the journal file,
+** and the WAL file.
+**
+** If F is the name of an sqlite database file, journal file, or WAL file
+** passed by the SQLite core into the VFS, then sqlite3_filename_database(F)
+** returns the name of the corresponding database file.
+**
+** If F is the name of an sqlite database file, journal file, or WAL file
+** passed by the SQLite core into the VFS, or if F is a database filename
+** obtained from [sqlite3_db_filename()], then sqlite3_filename_journal(F)
+** returns the name of the corresponding rollback journal file.
+**
+** If F is the name of an sqlite database file, journal file, or WAL file
+** that was passed by the SQLite core into the VFS, or if F is a database
+** filename obtained from [sqlite3_db_filename()], then
+** sqlite3_filename_wal(F) returns the name of the corresponding
+** WAL file.
+**
+** In all of the above, if F is not the name of a database, journal or WAL
+** filename passed into the VFS from the SQLite core and F is not the
+** return value from [sqlite3_db_filename()], then the result is
+** undefined and is likely a memory access violation.
+*/
+SQLITE_API const char *sqlite3_filename_database(const char*);
+SQLITE_API const char *sqlite3_filename_journal(const char*);
+SQLITE_API const char *sqlite3_filename_wal(const char*);
+
+/*
+** CAPI3REF: Database File Corresponding To A Journal
+**
+** ^If X is the name of a rollback or WAL-mode journal file that is
+** passed into the xOpen method of [sqlite3_vfs], then
+** sqlite3_database_file_object(X) returns a pointer to the [sqlite3_file]
+** object that represents the main database file.
+**
+** This routine is intended for use in custom [VFS] implementations
+** only. It is not a general-purpose interface.
+** The argument sqlite3_file_object(X) must be a filename pointer that
+** has been passed into [sqlite3_vfs].xOpen method where the
+** flags parameter to xOpen contains one of the bits
+** [SQLITE_OPEN_MAIN_JOURNAL] or [SQLITE_OPEN_WAL]. Any other use
+** of this routine results in undefined and probably undesirable
+** behavior.
+*/
+SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*);
+
+/*
+** CAPI3REF: Create and Destroy VFS Filenames
+**
+** These interfces are provided for use by [VFS shim] implementations and
+** are not useful outside of that context.
+**
+** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of
+** database filename D with corresponding journal file J and WAL file W and
+** with N URI parameters key/values pairs in the array P. The result from
+** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that
+** is safe to pass to routines like:
+** <ul>
+** <li> [sqlite3_uri_parameter()],
+** <li> [sqlite3_uri_boolean()],
+** <li> [sqlite3_uri_int64()],
+** <li> [sqlite3_uri_key()],
+** <li> [sqlite3_filename_database()],
+** <li> [sqlite3_filename_journal()], or
+** <li> [sqlite3_filename_wal()].
+** </ul>
+** If a memory allocation error occurs, sqlite3_create_filename() might
+** return a NULL pointer. The memory obtained from sqlite3_create_filename(X)
+** must be released by a corresponding call to sqlite3_free_filename(Y).
+**
+** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array
+** of 2*N pointers to strings. Each pair of pointers in this array corresponds
+** to a key and value for a query parameter. The P parameter may be a NULL
+** pointer if N is zero. None of the 2*N pointers in the P array may be
+** NULL pointers and key pointers should not be empty strings.
+** None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may
+** be NULL pointers, though they can be empty strings.
+**
+** The sqlite3_free_filename(Y) routine releases a memory allocation
+** previously obtained from sqlite3_create_filename(). Invoking
+** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op.
+**
+** If the Y parameter to sqlite3_free_filename(Y) is anything other
+** than a NULL pointer or a pointer previously acquired from
+** sqlite3_create_filename(), then bad things such as heap
+** corruption or segfaults may occur. The value Y should be
+** used again after sqlite3_free_filename(Y) has been called. This means
+** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y,
+** then the corresponding [sqlite3_module.xClose() method should also be
+** invoked prior to calling sqlite3_free_filename(Y).
+*/
+SQLITE_API char *sqlite3_create_filename(
+ const char *zDatabase,
+ const char *zJournal,
+ const char *zWal,
+ int nParam,
+ const char **azParam
+);
+SQLITE_API void sqlite3_free_filename(char*);
+
+/*
+** CAPI3REF: Error Codes And Messages
+** METHOD: sqlite3
+**
+** ^If the most recent sqlite3_* API call associated with
+** [database connection] D failed, then the sqlite3_errcode(D) interface
+** returns the numeric [result code] or [extended result code] for that
+** API call.
+** ^The sqlite3_extended_errcode()
+** interface is the same except that it always returns the
+** [extended result code] even when extended result codes are
+** disabled.
+**
+** The values returned by sqlite3_errcode() and/or
+** sqlite3_extended_errcode() might change with each API call.
+** Except, there are some interfaces that are guaranteed to never
+** change the value of the error code. The error-code preserving
+** interfaces are:
+**
+** <ul>
+** <li> sqlite3_errcode()
+** <li> sqlite3_extended_errcode()
+** <li> sqlite3_errmsg()
+** <li> sqlite3_errmsg16()
+** </ul>
+**
+** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
+** text that describes the error, as either UTF-8 or UTF-16 respectively.
+** ^(Memory to hold the error message string is managed internally.
+** The application does not need to worry about freeing the result.
+** However, the error string might be overwritten or deallocated by
+** subsequent calls to other SQLite interface functions.)^
+**
+** ^The sqlite3_errstr() interface returns the English-language text
+** that describes the [result code], as UTF-8.
+** ^(Memory to hold the error message string is managed internally
+** and must not be freed by the application)^.
+**
+** When the serialized [threading mode] is in use, it might be the
+** case that a second error occurs on a separate thread in between
+** the time of the first error and the call to these interfaces.
+** When that happens, the second error will be reported since these
+** interfaces always report the most recent result. To avoid
+** this, each thread can obtain exclusive use of the [database connection] D
+** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
+** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
+** all calls to the interfaces listed here are completed.
+**
+** If an interface fails with SQLITE_MISUSE, that means the interface
+** was invoked incorrectly by the application. In that case, the
+** error code and message may or may not be set.
+*/
+SQLITE_API int sqlite3_errcode(sqlite3 *db);
+SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
+SQLITE_API const char *sqlite3_errmsg(sqlite3*);
+SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
+SQLITE_API const char *sqlite3_errstr(int);
+
+/*
+** CAPI3REF: Prepared Statement Object
+** KEYWORDS: {prepared statement} {prepared statements}
+**
+** An instance of this object represents a single SQL statement that
+** has been compiled into binary form and is ready to be evaluated.
+**
+** Think of each SQL statement as a separate computer program. The
+** original SQL text is source code. A prepared statement object
+** is the compiled object code. All SQL must be converted into a
+** prepared statement before it can be run.
+**
+** The life-cycle of a prepared statement object usually goes like this:
+**
+** <ol>
+** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
+** <li> Bind values to [parameters] using the sqlite3_bind_*()
+** interfaces.
+** <li> Run the SQL by calling [sqlite3_step()] one or more times.
+** <li> Reset the prepared statement using [sqlite3_reset()] then go back
+** to step 2. Do this zero or more times.
+** <li> Destroy the object using [sqlite3_finalize()].
+** </ol>
+*/
+typedef struct sqlite3_stmt sqlite3_stmt;
+
+/*
+** CAPI3REF: Run-time Limits
+** METHOD: sqlite3
+**
+** ^(This interface allows the size of various constructs to be limited
+** on a connection by connection basis. The first parameter is the
+** [database connection] whose limit is to be set or queried. The
+** second parameter is one of the [limit categories] that define a
+** class of constructs to be size limited. The third parameter is the
+** new limit for that construct.)^
+**
+** ^If the new limit is a negative number, the limit is unchanged.
+** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
+** [limits | hard upper bound]
+** set at compile-time by a C preprocessor macro called
+** [limits | SQLITE_MAX_<i>NAME</i>].
+** (The "_LIMIT_" in the name is changed to "_MAX_".))^
+** ^Attempts to increase a limit above its hard upper bound are
+** silently truncated to the hard upper bound.
+**
+** ^Regardless of whether or not the limit was changed, the
+** [sqlite3_limit()] interface returns the prior value of the limit.
+** ^Hence, to find the current value of a limit without changing it,
+** simply invoke this interface with the third parameter set to -1.
+**
+** Run-time limits are intended for use in applications that manage
+** both their own internal database and also databases that are controlled
+** by untrusted external sources. An example application might be a
+** web browser that has its own databases for storing history and
+** separate databases controlled by JavaScript applications downloaded
+** off the Internet. The internal databases can be given the
+** large, default limits. Databases managed by external sources can
+** be given much smaller limits designed to prevent a denial of service
+** attack. Developers might also want to use the [sqlite3_set_authorizer()]
+** interface to further control untrusted SQL. The size of the database
+** created by an untrusted script can be contained using the
+** [max_page_count] [PRAGMA].
+**
+** New run-time limit categories may be added in future releases.
+*/
+SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
+
+/*
+** CAPI3REF: Run-Time Limit Categories
+** KEYWORDS: {limit category} {*limit categories}
+**
+** These constants define various performance limits
+** that can be lowered at run-time using [sqlite3_limit()].
+** The synopsis of the meanings of the various limits is shown below.
+** Additional information is available at [limits | Limits in SQLite].
+**
+** <dl>
+** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
+** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
+**
+** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
+** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
+**
+** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
+** <dd>The maximum number of columns in a table definition or in the
+** result set of a [SELECT] or the maximum number of columns in an index
+** or in an ORDER BY or GROUP BY clause.</dd>)^
+**
+** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
+** <dd>The maximum depth of the parse tree on any expression.</dd>)^
+**
+** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
+** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
+**
+** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
+** <dd>The maximum number of instructions in a virtual machine program
+** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
+** the equivalent tries to allocate space for more than this many opcodes
+** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
+**
+** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
+** <dd>The maximum number of arguments on a function.</dd>)^
+**
+** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
+** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
+**
+** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
+** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
+** <dd>The maximum length of the pattern argument to the [LIKE] or
+** [GLOB] operators.</dd>)^
+**
+** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
+** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
+** <dd>The maximum index number of any [parameter] in an SQL statement.)^
+**
+** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
+** <dd>The maximum depth of recursion for triggers.</dd>)^
+**
+** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
+** <dd>The maximum number of auxiliary worker threads that a single
+** [prepared statement] may start.</dd>)^
+** </dl>
+*/
+#define SQLITE_LIMIT_LENGTH 0
+#define SQLITE_LIMIT_SQL_LENGTH 1
+#define SQLITE_LIMIT_COLUMN 2
+#define SQLITE_LIMIT_EXPR_DEPTH 3
+#define SQLITE_LIMIT_COMPOUND_SELECT 4
+#define SQLITE_LIMIT_VDBE_OP 5
+#define SQLITE_LIMIT_FUNCTION_ARG 6
+#define SQLITE_LIMIT_ATTACHED 7
+#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
+#define SQLITE_LIMIT_VARIABLE_NUMBER 9
+#define SQLITE_LIMIT_TRIGGER_DEPTH 10
+#define SQLITE_LIMIT_WORKER_THREADS 11
+
+/*
+** CAPI3REF: Prepare Flags
+**
+** These constants define various flags that can be passed into
+** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
+** [sqlite3_prepare16_v3()] interfaces.
+**
+** New flags may be added in future releases of SQLite.
+**
+** <dl>
+** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
+** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
+** that the prepared statement will be retained for a long time and
+** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
+** and [sqlite3_prepare16_v3()] assume that the prepared statement will
+** be used just once or at most a few times and then destroyed using
+** [sqlite3_finalize()] relatively soon. The current implementation acts
+** on this hint by avoiding the use of [lookaside memory] so as not to
+** deplete the limited store of lookaside memory. Future versions of
+** SQLite may act on this hint differently.
+**
+** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt>
+** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used
+** to be required for any prepared statement that wanted to use the
+** [sqlite3_normalized_sql()] interface. However, the
+** [sqlite3_normalized_sql()] interface is now available to all
+** prepared statements, regardless of whether or not they use this
+** flag.
+**
+** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt>
+** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler
+** to return an error (error code SQLITE_ERROR) if the statement uses
+** any virtual tables.
+** </dl>
+*/
+#define SQLITE_PREPARE_PERSISTENT 0x01
+#define SQLITE_PREPARE_NORMALIZE 0x02
+#define SQLITE_PREPARE_NO_VTAB 0x04
+
+/*
+** CAPI3REF: Compiling An SQL Statement
+** KEYWORDS: {SQL statement compiler}
+** METHOD: sqlite3
+** CONSTRUCTOR: sqlite3_stmt
+**
+** To execute an SQL statement, it must first be compiled into a byte-code
+** program using one of these routines. Or, in other words, these routines
+** are constructors for the [prepared statement] object.
+**
+** The preferred routine to use is [sqlite3_prepare_v2()]. The
+** [sqlite3_prepare()] interface is legacy and should be avoided.
+** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
+** for special purposes.
+**
+** The use of the UTF-8 interfaces is preferred, as SQLite currently
+** does all parsing using UTF-8. The UTF-16 interfaces are provided
+** as a convenience. The UTF-16 interfaces work by converting the
+** input text into UTF-8, then invoking the corresponding UTF-8 interface.
+**
+** The first argument, "db", is a [database connection] obtained from a
+** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
+** [sqlite3_open16()]. The database connection must not have been closed.
+**
+** The second argument, "zSql", is the statement to be compiled, encoded
+** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(),
+** and sqlite3_prepare_v3()
+** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
+** and sqlite3_prepare16_v3() use UTF-16.
+**
+** ^If the nByte argument is negative, then zSql is read up to the
+** first zero terminator. ^If nByte is positive, then it is the
+** number of bytes read from zSql. ^If nByte is zero, then no prepared
+** statement is generated.
+** If the caller knows that the supplied string is nul-terminated, then
+** there is a small performance advantage to passing an nByte parameter that
+** is the number of bytes in the input string <i>including</i>
+** the nul-terminator.
+**
+** ^If pzTail is not NULL then *pzTail is made to point to the first byte
+** past the end of the first SQL statement in zSql. These routines only
+** compile the first statement in zSql, so *pzTail is left pointing to
+** what remains uncompiled.
+**
+** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
+** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
+** to NULL. ^If the input text contains no SQL (if the input is an empty
+** string or a comment) then *ppStmt is set to NULL.
+** The calling procedure is responsible for deleting the compiled
+** SQL statement using [sqlite3_finalize()] after it has finished with it.
+** ppStmt may not be NULL.
+**
+** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
+** otherwise an [error code] is returned.
+**
+** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
+** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
+** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
+** are retained for backwards compatibility, but their use is discouraged.
+** ^In the "vX" interfaces, the prepared statement
+** that is returned (the [sqlite3_stmt] object) contains a copy of the
+** original SQL text. This causes the [sqlite3_step()] interface to
+** behave differently in three ways:
+**
+** <ol>
+** <li>
+** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
+** always used to do, [sqlite3_step()] will automatically recompile the SQL
+** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
+** retries will occur before sqlite3_step() gives up and returns an error.
+** </li>
+**
+** <li>
+** ^When an error occurs, [sqlite3_step()] will return one of the detailed
+** [error codes] or [extended error codes]. ^The legacy behavior was that
+** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
+** and the application would have to make a second call to [sqlite3_reset()]
+** in order to find the underlying cause of the problem. With the "v2" prepare
+** interfaces, the underlying reason for the error is returned immediately.
+** </li>
+**
+** <li>
+** ^If the specific value bound to a [parameter | host parameter] in the
+** WHERE clause might influence the choice of query plan for a statement,
+** then the statement will be automatically recompiled, as if there had been
+** a schema change, on the first [sqlite3_step()] call following any change
+** to the [sqlite3_bind_text | bindings] of that [parameter].
+** ^The specific value of a WHERE-clause [parameter] might influence the
+** choice of query plan if the parameter is the left-hand side of a [LIKE]
+** or [GLOB] operator or if the parameter is compared to an indexed column
+** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled.
+** </li>
+** </ol>
+**
+** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
+** the extra prepFlags parameter, which is a bit array consisting of zero or
+** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The
+** sqlite3_prepare_v2() interface works exactly the same as
+** sqlite3_prepare_v3() with a zero prepFlags parameter.
+*/
+SQLITE_API int sqlite3_prepare(
+ sqlite3 *db, /* Database handle */
+ const char *zSql, /* SQL statement, UTF-8 encoded */
+ int nByte, /* Maximum length of zSql in bytes. */
+ sqlite3_stmt **ppStmt, /* OUT: Statement handle */
+ const char **pzTail /* OUT: Pointer to unused portion of zSql */
+);
+SQLITE_API int sqlite3_prepare_v2(
+ sqlite3 *db, /* Database handle */
+ const char *zSql, /* SQL statement, UTF-8 encoded */
+ int nByte, /* Maximum length of zSql in bytes. */
+ sqlite3_stmt **ppStmt, /* OUT: Statement handle */
+ const char **pzTail /* OUT: Pointer to unused portion of zSql */
+);
+SQLITE_API int sqlite3_prepare_v3(
+ sqlite3 *db, /* Database handle */
+ const char *zSql, /* SQL statement, UTF-8 encoded */
+ int nByte, /* Maximum length of zSql in bytes. */
+ unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
+ sqlite3_stmt **ppStmt, /* OUT: Statement handle */
+ const char **pzTail /* OUT: Pointer to unused portion of zSql */
+);
+SQLITE_API int sqlite3_prepare16(
+ sqlite3 *db, /* Database handle */
+ const void *zSql, /* SQL statement, UTF-16 encoded */
+ int nByte, /* Maximum length of zSql in bytes. */
+ sqlite3_stmt **ppStmt, /* OUT: Statement handle */
+ const void **pzTail /* OUT: Pointer to unused portion of zSql */
+);
+SQLITE_API int sqlite3_prepare16_v2(
+ sqlite3 *db, /* Database handle */
+ const void *zSql, /* SQL statement, UTF-16 encoded */
+ int nByte, /* Maximum length of zSql in bytes. */
+ sqlite3_stmt **ppStmt, /* OUT: Statement handle */
+ const void **pzTail /* OUT: Pointer to unused portion of zSql */
+);
+SQLITE_API int sqlite3_prepare16_v3(
+ sqlite3 *db, /* Database handle */
+ const void *zSql, /* SQL statement, UTF-16 encoded */
+ int nByte, /* Maximum length of zSql in bytes. */
+ unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
+ sqlite3_stmt **ppStmt, /* OUT: Statement handle */
+ const void **pzTail /* OUT: Pointer to unused portion of zSql */
+);
+
+/*
+** CAPI3REF: Retrieving Statement SQL
+** METHOD: sqlite3_stmt
+**
+** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
+** SQL text used to create [prepared statement] P if P was
+** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
+** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
+** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
+** string containing the SQL text of prepared statement P with
+** [bound parameters] expanded.
+** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8
+** string containing the normalized SQL text of prepared statement P. The
+** semantics used to normalize a SQL statement are unspecified and subject
+** to change. At a minimum, literal values will be replaced with suitable
+** placeholders.
+**
+** ^(For example, if a prepared statement is created using the SQL
+** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
+** and parameter :xyz is unbound, then sqlite3_sql() will return
+** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
+** will return "SELECT 2345,NULL".)^
+**
+** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
+** is available to hold the result, or if the result would exceed the
+** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
+**
+** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
+** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
+** option causes sqlite3_expanded_sql() to always return NULL.
+**
+** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)
+** are managed by SQLite and are automatically freed when the prepared
+** statement is finalized.
+** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
+** is obtained from [sqlite3_malloc()] and must be free by the application
+** by passing it to [sqlite3_free()].
+*/
+SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
+SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
+SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Determine If An SQL Statement Writes The Database
+** METHOD: sqlite3_stmt
+**
+** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
+** and only if the [prepared statement] X makes no direct changes to
+** the content of the database file.
+**
+** Note that [application-defined SQL functions] or
+** [virtual tables] might change the database indirectly as a side effect.
+** ^(For example, if an application defines a function "eval()" that
+** calls [sqlite3_exec()], then the following SQL statement would
+** change the database file through side-effects:
+**
+** <blockquote><pre>
+** SELECT eval('DELETE FROM t1') FROM t2;
+** </pre></blockquote>
+**
+** But because the [SELECT] statement does not change the database file
+** directly, sqlite3_stmt_readonly() would still return true.)^
+**
+** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
+** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
+** since the statements themselves do not actually modify the database but
+** rather they control the timing of when other statements modify the
+** database. ^The [ATTACH] and [DETACH] statements also cause
+** sqlite3_stmt_readonly() to return true since, while those statements
+** change the configuration of a database connection, they do not make
+** changes to the content of the database files on disk.
+** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
+** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
+** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
+** sqlite3_stmt_readonly() returns false for those commands.
+*/
+SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement
+** METHOD: sqlite3_stmt
+**
+** ^The sqlite3_stmt_isexplain(S) interface returns 1 if the
+** prepared statement S is an EXPLAIN statement, or 2 if the
+** statement S is an EXPLAIN QUERY PLAN.
+** ^The sqlite3_stmt_isexplain(S) interface returns 0 if S is
+** an ordinary statement or a NULL pointer.
+*/
+SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Determine If A Prepared Statement Has Been Reset
+** METHOD: sqlite3_stmt
+**
+** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
+** [prepared statement] S has been stepped at least once using
+** [sqlite3_step(S)] but has neither run to completion (returned
+** [SQLITE_DONE] from [sqlite3_step(S)]) nor
+** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
+** interface returns false if S is a NULL pointer. If S is not a
+** NULL pointer and is not a pointer to a valid [prepared statement]
+** object, then the behavior is undefined and probably undesirable.
+**
+** This interface can be used in combination [sqlite3_next_stmt()]
+** to locate all prepared statements associated with a database
+** connection that are in need of being reset. This can be used,
+** for example, in diagnostic routines to search for prepared
+** statements that are holding a transaction open.
+*/
+SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
+
+/*
+** CAPI3REF: Dynamically Typed Value Object
+** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
+**
+** SQLite uses the sqlite3_value object to represent all values
+** that can be stored in a database table. SQLite uses dynamic typing
+** for the values it stores. ^Values stored in sqlite3_value objects
+** can be integers, floating point values, strings, BLOBs, or NULL.
+**
+** An sqlite3_value object may be either "protected" or "unprotected".
+** Some interfaces require a protected sqlite3_value. Other interfaces
+** will accept either a protected or an unprotected sqlite3_value.
+** Every interface that accepts sqlite3_value arguments specifies
+** whether or not it requires a protected sqlite3_value. The
+** [sqlite3_value_dup()] interface can be used to construct a new
+** protected sqlite3_value from an unprotected sqlite3_value.
+**
+** The terms "protected" and "unprotected" refer to whether or not
+** a mutex is held. An internal mutex is held for a protected
+** sqlite3_value object but no mutex is held for an unprotected
+** sqlite3_value object. If SQLite is compiled to be single-threaded
+** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
+** or if SQLite is run in one of reduced mutex modes
+** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
+** then there is no distinction between protected and unprotected
+** sqlite3_value objects and they can be used interchangeably. However,
+** for maximum code portability it is recommended that applications
+** still make the distinction between protected and unprotected
+** sqlite3_value objects even when not strictly required.
+**
+** ^The sqlite3_value objects that are passed as parameters into the
+** implementation of [application-defined SQL functions] are protected.
+** ^The sqlite3_value object returned by
+** [sqlite3_column_value()] is unprotected.
+** Unprotected sqlite3_value objects may only be used as arguments
+** to [sqlite3_result_value()], [sqlite3_bind_value()], and
+** [sqlite3_value_dup()].
+** The [sqlite3_value_blob | sqlite3_value_type()] family of
+** interfaces require protected sqlite3_value objects.
+*/
+typedef struct sqlite3_value sqlite3_value;
+
+/*
+** CAPI3REF: SQL Function Context Object
+**
+** The context in which an SQL function executes is stored in an
+** sqlite3_context object. ^A pointer to an sqlite3_context object
+** is always first parameter to [application-defined SQL functions].
+** The application-defined SQL function implementation will pass this
+** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
+** [sqlite3_aggregate_context()], [sqlite3_user_data()],
+** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
+** and/or [sqlite3_set_auxdata()].
+*/
+typedef struct sqlite3_context sqlite3_context;
+
+/*
+** CAPI3REF: Binding Values To Prepared Statements
+** KEYWORDS: {host parameter} {host parameters} {host parameter name}
+** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
+** METHOD: sqlite3_stmt
+**
+** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
+** literals may be replaced by a [parameter] that matches one of following
+** templates:
+**
+** <ul>
+** <li> ?
+** <li> ?NNN
+** <li> :VVV
+** <li> @VVV
+** <li> $VVV
+** </ul>
+**
+** In the templates above, NNN represents an integer literal,
+** and VVV represents an alphanumeric identifier.)^ ^The values of these
+** parameters (also called "host parameter names" or "SQL parameters")
+** can be set using the sqlite3_bind_*() routines defined here.
+**
+** ^The first argument to the sqlite3_bind_*() routines is always
+** a pointer to the [sqlite3_stmt] object returned from
+** [sqlite3_prepare_v2()] or its variants.
+**
+** ^The second argument is the index of the SQL parameter to be set.
+** ^The leftmost SQL parameter has an index of 1. ^When the same named
+** SQL parameter is used more than once, second and subsequent
+** occurrences have the same index as the first occurrence.
+** ^The index for named parameters can be looked up using the
+** [sqlite3_bind_parameter_index()] API if desired. ^The index
+** for "?NNN" parameters is the value of NNN.
+** ^The NNN value must be between 1 and the [sqlite3_limit()]
+** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 32766).
+**
+** ^The third argument is the value to bind to the parameter.
+** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
+** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
+** is ignored and the end result is the same as sqlite3_bind_null().
+** ^If the third parameter to sqlite3_bind_text() is not NULL, then
+** it should be a pointer to well-formed UTF8 text.
+** ^If the third parameter to sqlite3_bind_text16() is not NULL, then
+** it should be a pointer to well-formed UTF16 text.
+** ^If the third parameter to sqlite3_bind_text64() is not NULL, then
+** it should be a pointer to a well-formed unicode string that is
+** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16
+** otherwise.
+**
+** [[byte-order determination rules]] ^The byte-order of
+** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)
+** found in first character, which is removed, or in the absence of a BOM
+** the byte order is the native byte order of the host
+** machine for sqlite3_bind_text16() or the byte order specified in
+** the 6th parameter for sqlite3_bind_text64().)^
+** ^If UTF16 input text contains invalid unicode
+** characters, then SQLite might change those invalid characters
+** into the unicode replacement character: U+FFFD.
+**
+** ^(In those routines that have a fourth argument, its value is the
+** number of bytes in the parameter. To be clear: the value is the
+** number of <u>bytes</u> in the value, not the number of characters.)^
+** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
+** is negative, then the length of the string is
+** the number of bytes up to the first zero terminator.
+** If the fourth parameter to sqlite3_bind_blob() is negative, then
+** the behavior is undefined.
+** If a non-negative fourth parameter is provided to sqlite3_bind_text()
+** or sqlite3_bind_text16() or sqlite3_bind_text64() then
+** that parameter must be the byte offset
+** where the NUL terminator would occur assuming the string were NUL
+** terminated. If any NUL characters occurs at byte offsets less than
+** the value of the fourth parameter then the resulting string value will
+** contain embedded NULs. The result of expressions involving strings
+** with embedded NULs is undefined.
+**
+** ^The fifth argument to the BLOB and string binding interfaces
+** is a destructor used to dispose of the BLOB or
+** string after SQLite has finished with it. ^The destructor is called
+** to dispose of the BLOB or string even if the call to the bind API fails,
+** except the destructor is not called if the third parameter is a NULL
+** pointer or the fourth parameter is negative.
+** ^If the fifth argument is
+** the special value [SQLITE_STATIC], then SQLite assumes that the
+** information is in static, unmanaged space and does not need to be freed.
+** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
+** SQLite makes its own private copy of the data immediately, before
+** the sqlite3_bind_*() routine returns.
+**
+** ^The sixth argument to sqlite3_bind_text64() must be one of
+** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
+** to specify the encoding of the text in the third parameter. If
+** the sixth argument to sqlite3_bind_text64() is not one of the
+** allowed values shown above, or if the text encoding is different
+** from the encoding specified by the sixth parameter, then the behavior
+** is undefined.
+**
+** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
+** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
+** (just an integer to hold its size) while it is being processed.
+** Zeroblobs are intended to serve as placeholders for BLOBs whose
+** content is later written using
+** [sqlite3_blob_open | incremental BLOB I/O] routines.
+** ^A negative value for the zeroblob results in a zero-length BLOB.
+**
+** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
+** [prepared statement] S to have an SQL value of NULL, but to also be
+** associated with the pointer P of type T. ^D is either a NULL pointer or
+** a pointer to a destructor function for P. ^SQLite will invoke the
+** destructor D with a single argument of P when it is finished using
+** P. The T parameter should be a static string, preferably a string
+** literal. The sqlite3_bind_pointer() routine is part of the
+** [pointer passing interface] added for SQLite 3.20.0.
+**
+** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
+** for the [prepared statement] or with a prepared statement for which
+** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
+** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
+** routine is passed a [prepared statement] that has been finalized, the
+** result is undefined and probably harmful.
+**
+** ^Bindings are not cleared by the [sqlite3_reset()] routine.
+** ^Unbound parameters are interpreted as NULL.
+**
+** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
+** [error code] if anything goes wrong.
+** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
+** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
+** [SQLITE_MAX_LENGTH].
+** ^[SQLITE_RANGE] is returned if the parameter
+** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
+**
+** See also: [sqlite3_bind_parameter_count()],
+** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
+*/
+SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
+SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
+ void(*)(void*));
+SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
+SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
+SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
+SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
+SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
+SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
+SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
+ void(*)(void*), unsigned char encoding);
+SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
+SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
+SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
+SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
+
+/*
+** CAPI3REF: Number Of SQL Parameters
+** METHOD: sqlite3_stmt
+**
+** ^This routine can be used to find the number of [SQL parameters]
+** in a [prepared statement]. SQL parameters are tokens of the
+** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
+** placeholders for values that are [sqlite3_bind_blob | bound]
+** to the parameters at a later time.
+**
+** ^(This routine actually returns the index of the largest (rightmost)
+** parameter. For all forms except ?NNN, this will correspond to the
+** number of unique parameters. If parameters of the ?NNN form are used,
+** there may be gaps in the list.)^
+**
+** See also: [sqlite3_bind_blob|sqlite3_bind()],
+** [sqlite3_bind_parameter_name()], and
+** [sqlite3_bind_parameter_index()].
+*/
+SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
+
+/*
+** CAPI3REF: Name Of A Host Parameter
+** METHOD: sqlite3_stmt
+**
+** ^The sqlite3_bind_parameter_name(P,N) interface returns
+** the name of the N-th [SQL parameter] in the [prepared statement] P.
+** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
+** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
+** respectively.
+** In other words, the initial ":" or "$" or "@" or "?"
+** is included as part of the name.)^
+** ^Parameters of the form "?" without a following integer have no name
+** and are referred to as "nameless" or "anonymous parameters".
+**
+** ^The first host parameter has an index of 1, not 0.
+**
+** ^If the value N is out of range or if the N-th parameter is
+** nameless, then NULL is returned. ^The returned string is
+** always in UTF-8 encoding even if the named parameter was
+** originally specified as UTF-16 in [sqlite3_prepare16()],
+** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
+**
+** See also: [sqlite3_bind_blob|sqlite3_bind()],
+** [sqlite3_bind_parameter_count()], and
+** [sqlite3_bind_parameter_index()].
+*/
+SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
+
+/*
+** CAPI3REF: Index Of A Parameter With A Given Name
+** METHOD: sqlite3_stmt
+**
+** ^Return the index of an SQL parameter given its name. ^The
+** index value returned is suitable for use as the second
+** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
+** is returned if no matching parameter is found. ^The parameter
+** name must be given in UTF-8 even if the original statement
+** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
+** [sqlite3_prepare16_v3()].
+**
+** See also: [sqlite3_bind_blob|sqlite3_bind()],
+** [sqlite3_bind_parameter_count()], and
+** [sqlite3_bind_parameter_name()].
+*/
+SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
+
+/*
+** CAPI3REF: Reset All Bindings On A Prepared Statement
+** METHOD: sqlite3_stmt
+**
+** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
+** the [sqlite3_bind_blob | bindings] on a [prepared statement].
+** ^Use this routine to reset all host parameters to NULL.
+*/
+SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
+
+/*
+** CAPI3REF: Number Of Columns In A Result Set
+** METHOD: sqlite3_stmt
+**
+** ^Return the number of columns in the result set returned by the
+** [prepared statement]. ^If this routine returns 0, that means the
+** [prepared statement] returns no data (for example an [UPDATE]).
+** ^However, just because this routine returns a positive number does not
+** mean that one or more rows of data will be returned. ^A SELECT statement
+** will always have a positive sqlite3_column_count() but depending on the
+** WHERE clause constraints and the table content, it might return no rows.
+**
+** See also: [sqlite3_data_count()]
+*/
+SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Column Names In A Result Set
+** METHOD: sqlite3_stmt
+**
+** ^These routines return the name assigned to a particular column
+** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
+** interface returns a pointer to a zero-terminated UTF-8 string
+** and sqlite3_column_name16() returns a pointer to a zero-terminated
+** UTF-16 string. ^The first parameter is the [prepared statement]
+** that implements the [SELECT] statement. ^The second parameter is the
+** column number. ^The leftmost column is number 0.
+**
+** ^The returned string pointer is valid until either the [prepared statement]
+** is destroyed by [sqlite3_finalize()] or until the statement is automatically
+** reprepared by the first call to [sqlite3_step()] for a particular run
+** or until the next call to
+** sqlite3_column_name() or sqlite3_column_name16() on the same column.
+**
+** ^If sqlite3_malloc() fails during the processing of either routine
+** (for example during a conversion from UTF-8 to UTF-16) then a
+** NULL pointer is returned.
+**
+** ^The name of a result column is the value of the "AS" clause for
+** that column, if there is an AS clause. If there is no AS clause
+** then the name of the column is unspecified and may change from
+** one release of SQLite to the next.
+*/
+SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
+SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
+
+/*
+** CAPI3REF: Source Of Data In A Query Result
+** METHOD: sqlite3_stmt
+**
+** ^These routines provide a means to determine the database, table, and
+** table column that is the origin of a particular result column in
+** [SELECT] statement.
+** ^The name of the database or table or column can be returned as
+** either a UTF-8 or UTF-16 string. ^The _database_ routines return
+** the database name, the _table_ routines return the table name, and
+** the origin_ routines return the column name.
+** ^The returned string is valid until the [prepared statement] is destroyed
+** using [sqlite3_finalize()] or until the statement is automatically
+** reprepared by the first call to [sqlite3_step()] for a particular run
+** or until the same information is requested
+** again in a different encoding.
+**
+** ^The names returned are the original un-aliased names of the
+** database, table, and column.
+**
+** ^The first argument to these interfaces is a [prepared statement].
+** ^These functions return information about the Nth result column returned by
+** the statement, where N is the second function argument.
+** ^The left-most column is column 0 for these routines.
+**
+** ^If the Nth column returned by the statement is an expression or
+** subquery and is not a column value, then all of these functions return
+** NULL. ^These routines might also return NULL if a memory allocation error
+** occurs. ^Otherwise, they return the name of the attached database, table,
+** or column that query result column was extracted from.
+**
+** ^As with all other SQLite APIs, those whose names end with "16" return
+** UTF-16 encoded strings and the other functions return UTF-8.
+**
+** ^These APIs are only available if the library was compiled with the
+** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
+**
+** If two or more threads call one or more
+** [sqlite3_column_database_name | column metadata interfaces]
+** for the same [prepared statement] and result column
+** at the same time then the results are undefined.
+*/
+SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
+SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
+SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
+SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
+SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
+SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
+
+/*
+** CAPI3REF: Declared Datatype Of A Query Result
+** METHOD: sqlite3_stmt
+**
+** ^(The first parameter is a [prepared statement].
+** If this statement is a [SELECT] statement and the Nth column of the
+** returned result set of that [SELECT] is a table column (not an
+** expression or subquery) then the declared type of the table
+** column is returned.)^ ^If the Nth column of the result set is an
+** expression or subquery, then a NULL pointer is returned.
+** ^The returned string is always UTF-8 encoded.
+**
+** ^(For example, given the database schema:
+**
+** CREATE TABLE t1(c1 VARIANT);
+**
+** and the following statement to be compiled:
+**
+** SELECT c1 + 1, c1 FROM t1;
+**
+** this routine would return the string "VARIANT" for the second result
+** column (i==1), and a NULL pointer for the first result column (i==0).)^
+**
+** ^SQLite uses dynamic run-time typing. ^So just because a column
+** is declared to contain a particular type does not mean that the
+** data stored in that column is of the declared type. SQLite is
+** strongly typed, but the typing is dynamic not static. ^Type
+** is associated with individual values, not with the containers
+** used to hold those values.
+*/
+SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
+SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
+
+/*
+** CAPI3REF: Evaluate An SQL Statement
+** METHOD: sqlite3_stmt
+**
+** After a [prepared statement] has been prepared using any of
+** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
+** or [sqlite3_prepare16_v3()] or one of the legacy
+** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
+** must be called one or more times to evaluate the statement.
+**
+** The details of the behavior of the sqlite3_step() interface depend
+** on whether the statement was prepared using the newer "vX" interfaces
+** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
+** [sqlite3_prepare16_v2()] or the older legacy
+** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
+** new "vX" interface is recommended for new applications but the legacy
+** interface will continue to be supported.
+**
+** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
+** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
+** ^With the "v2" interface, any of the other [result codes] or
+** [extended result codes] might be returned as well.
+**
+** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
+** database locks it needs to do its job. ^If the statement is a [COMMIT]
+** or occurs outside of an explicit transaction, then you can retry the
+** statement. If the statement is not a [COMMIT] and occurs within an
+** explicit transaction then you should rollback the transaction before
+** continuing.
+**
+** ^[SQLITE_DONE] means that the statement has finished executing
+** successfully. sqlite3_step() should not be called again on this virtual
+** machine without first calling [sqlite3_reset()] to reset the virtual
+** machine back to its initial state.
+**
+** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
+** is returned each time a new row of data is ready for processing by the
+** caller. The values may be accessed using the [column access functions].
+** sqlite3_step() is called again to retrieve the next row of data.
+**
+** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
+** violation) has occurred. sqlite3_step() should not be called again on
+** the VM. More information may be found by calling [sqlite3_errmsg()].
+** ^With the legacy interface, a more specific error code (for example,
+** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
+** can be obtained by calling [sqlite3_reset()] on the
+** [prepared statement]. ^In the "v2" interface,
+** the more specific error code is returned directly by sqlite3_step().
+**
+** [SQLITE_MISUSE] means that the this routine was called inappropriately.
+** Perhaps it was called on a [prepared statement] that has
+** already been [sqlite3_finalize | finalized] or on one that had
+** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
+** be the case that the same database connection is being used by two or
+** more threads at the same moment in time.
+**
+** For all versions of SQLite up to and including 3.6.23.1, a call to
+** [sqlite3_reset()] was required after sqlite3_step() returned anything
+** other than [SQLITE_ROW] before any subsequent invocation of
+** sqlite3_step(). Failure to reset the prepared statement using
+** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
+** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
+** sqlite3_step() began
+** calling [sqlite3_reset()] automatically in this circumstance rather
+** than returning [SQLITE_MISUSE]. This is not considered a compatibility
+** break because any application that ever receives an SQLITE_MISUSE error
+** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
+** can be used to restore the legacy behavior.
+**
+** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
+** API always returns a generic error code, [SQLITE_ERROR], following any
+** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
+** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
+** specific [error codes] that better describes the error.
+** We admit that this is a goofy design. The problem has been fixed
+** with the "v2" interface. If you prepare all of your SQL statements
+** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
+** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
+** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
+** then the more specific [error codes] are returned directly
+** by sqlite3_step(). The use of the "vX" interfaces is recommended.
+*/
+SQLITE_API int sqlite3_step(sqlite3_stmt*);
+
+/*
+** CAPI3REF: Number of columns in a result set
+** METHOD: sqlite3_stmt
+**
+** ^The sqlite3_data_count(P) interface returns the number of columns in the
+** current row of the result set of [prepared statement] P.
+** ^If prepared statement P does not have results ready to return
+** (via calls to the [sqlite3_column_int | sqlite3_column()] family of
+** interfaces) then sqlite3_data_count(P) returns 0.
+** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
+** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
+** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
+** will return non-zero if previous call to [sqlite3_step](P) returned
+** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
+** where it always returns zero since each step of that multi-step
+** pragma returns 0 columns of data.
+**
+** See also: [sqlite3_column_count()]
+*/
+SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Fundamental Datatypes
+** KEYWORDS: SQLITE_TEXT
+**
+** ^(Every value in SQLite has one of five fundamental datatypes:
+**
+** <ul>
+** <li> 64-bit signed integer
+** <li> 64-bit IEEE floating point number
+** <li> string
+** <li> BLOB
+** <li> NULL
+** </ul>)^
+**
+** These constants are codes for each of those types.
+**
+** Note that the SQLITE_TEXT constant was also used in SQLite version 2
+** for a completely different meaning. Software that links against both
+** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
+** SQLITE_TEXT.
+*/
+#define SQLITE_INTEGER 1
+#define SQLITE_FLOAT 2
+#define SQLITE_BLOB 4
+#define SQLITE_NULL 5
+#ifdef SQLITE_TEXT
+# undef SQLITE_TEXT
+#else
+# define SQLITE_TEXT 3
+#endif
+#define SQLITE3_TEXT 3
+
+/*
+** CAPI3REF: Result Values From A Query
+** KEYWORDS: {column access functions}
+** METHOD: sqlite3_stmt
+**
+** <b>Summary:</b>
+** <blockquote><table border=0 cellpadding=0 cellspacing=0>
+** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
+** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
+** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
+** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
+** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
+** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
+** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
+** [sqlite3_value|unprotected sqlite3_value] object.
+** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
+** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
+** or a UTF-8 TEXT result in bytes
+** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
+** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
+** TEXT in bytes
+** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
+** datatype of the result
+** </table></blockquote>
+**
+** <b>Details:</b>
+**
+** ^These routines return information about a single column of the current
+** result row of a query. ^In every case the first argument is a pointer
+** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
+** that was returned from [sqlite3_prepare_v2()] or one of its variants)
+** and the second argument is the index of the column for which information
+** should be returned. ^The leftmost column of the result set has the index 0.
+** ^The number of columns in the result can be determined using
+** [sqlite3_column_count()].
+**
+** If the SQL statement does not currently point to a valid row, or if the
+** column index is out of range, the result is undefined.
+** These routines may only be called when the most recent call to
+** [sqlite3_step()] has returned [SQLITE_ROW] and neither
+** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
+** If any of these routines are called after [sqlite3_reset()] or
+** [sqlite3_finalize()] or after [sqlite3_step()] has returned
+** something other than [SQLITE_ROW], the results are undefined.
+** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
+** are called from a different thread while any of these routines
+** are pending, then the results are undefined.
+**
+** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
+** each return the value of a result column in a specific data format. If
+** the result column is not initially in the requested format (for example,
+** if the query returns an integer but the sqlite3_column_text() interface
+** is used to extract the value) then an automatic type conversion is performed.
+**
+** ^The sqlite3_column_type() routine returns the
+** [SQLITE_INTEGER | datatype code] for the initial data type
+** of the result column. ^The returned value is one of [SQLITE_INTEGER],
+** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
+** The return value of sqlite3_column_type() can be used to decide which
+** of the first six interface should be used to extract the column value.
+** The value returned by sqlite3_column_type() is only meaningful if no
+** automatic type conversions have occurred for the value in question.
+** After a type conversion, the result of calling sqlite3_column_type()
+** is undefined, though harmless. Future
+** versions of SQLite may change the behavior of sqlite3_column_type()
+** following a type conversion.
+**
+** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
+** or sqlite3_column_bytes16() interfaces can be used to determine the size
+** of that BLOB or string.
+**
+** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
+** routine returns the number of bytes in that BLOB or string.
+** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
+** the string to UTF-8 and then returns the number of bytes.
+** ^If the result is a numeric value then sqlite3_column_bytes() uses
+** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
+** the number of bytes in that string.
+** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
+**
+** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
+** routine returns the number of bytes in that BLOB or string.
+** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
+** the string to UTF-16 and then returns the number of bytes.
+** ^If the result is a numeric value then sqlite3_column_bytes16() uses
+** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
+** the number of bytes in that string.
+** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
+**
+** ^The values returned by [sqlite3_column_bytes()] and
+** [sqlite3_column_bytes16()] do not include the zero terminators at the end
+** of the string. ^For clarity: the values returned by
+** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
+** bytes in the string, not the number of characters.
+**
+** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
+** even empty strings, are always zero-terminated. ^The return
+** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
+**
+** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
+** [unprotected sqlite3_value] object. In a multithreaded environment,
+** an unprotected sqlite3_value object may only be used safely with
+** [sqlite3_bind_value()] and [sqlite3_result_value()].
+** If the [unprotected sqlite3_value] object returned by
+** [sqlite3_column_value()] is used in any other way, including calls
+** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
+** or [sqlite3_value_bytes()], the behavior is not threadsafe.
+** Hence, the sqlite3_column_value() interface
+** is normally only useful within the implementation of
+** [application-defined SQL functions] or [virtual tables], not within
+** top-level application code.
+**
+** The these routines may attempt to convert the datatype of the result.
+** ^For example, if the internal representation is FLOAT and a text result
+** is requested, [sqlite3_snprintf()] is used internally to perform the
+** conversion automatically. ^(The following table details the conversions
+** that are applied:
+**
+** <blockquote>
+** <table border="1">
+** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
+**
+** <tr><td> NULL <td> INTEGER <td> Result is 0
+** <tr><td> NULL <td> FLOAT <td> Result is 0.0
+** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
+** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
+** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
+** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
+** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
+** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
+** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
+** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
+** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
+** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
+** <tr><td> TEXT <td> BLOB <td> No change
+** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
+** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
+** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
+** </table>
+** </blockquote>)^
+**
+** Note that when type conversions occur, pointers returned by prior
+** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
+** sqlite3_column_text16() may be invalidated.
+** Type conversions and pointer invalidations might occur
+** in the following cases:
+**
+** <ul>
+** <li> The initial content is a BLOB and sqlite3_column_text() or
+** sqlite3_column_text16() is called. A zero-terminator might
+** need to be added to the string.</li>
+** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
+** sqlite3_column_text16() is called. The content must be converted
+** to UTF-16.</li>
+** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
+** sqlite3_column_text() is called. The content must be converted
+** to UTF-8.</li>
+** </ul>
+**
+** ^Conversions between UTF-16be and UTF-16le are always done in place and do
+** not invalidate a prior pointer, though of course the content of the buffer
+** that the prior pointer references will have been modified. Other kinds
+** of conversion are done in place when it is possible, but sometimes they
+** are not possible and in those cases prior pointers are invalidated.
+**
+** The safest policy is to invoke these routines
+** in one of the following ways:
+**
+** <ul>
+** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
+** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
+** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
+** </ul>
+**
+** In other words, you should call sqlite3_column_text(),
+** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
+** into the desired format, then invoke sqlite3_column_bytes() or
+** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
+** to sqlite3_column_text() or sqlite3_column_blob() with calls to
+** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
+** with calls to sqlite3_column_bytes().
+**
+** ^The pointers returned are valid until a type conversion occurs as
+** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
+** [sqlite3_finalize()] is called. ^The memory space used to hold strings
+** and BLOBs is freed automatically. Do not pass the pointers returned
+** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
+** [sqlite3_free()].
+**
+** As long as the input parameters are correct, these routines will only
+** fail if an out-of-memory error occurs during a format conversion.
+** Only the following subset of interfaces are subject to out-of-memory
+** errors:
+**
+** <ul>
+** <li> sqlite3_column_blob()
+** <li> sqlite3_column_text()
+** <li> sqlite3_column_text16()
+** <li> sqlite3_column_bytes()
+** <li> sqlite3_column_bytes16()
+** </ul>
+**
+** If an out-of-memory error occurs, then the return value from these
+** routines is the same as if the column had contained an SQL NULL value.
+** Valid SQL NULL returns can be distinguished from out-of-memory errors
+** by invoking the [sqlite3_errcode()] immediately after the suspect
+** return value is obtained and before any
+** other SQLite interface is called on the same [database connection].
+*/
+SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
+SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
+SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
+SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
+SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
+SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
+SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
+SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
+SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
+SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
+
+/*
+** CAPI3REF: Destroy A Prepared Statement Object
+** DESTRUCTOR: sqlite3_stmt
+**
+** ^The sqlite3_finalize() function is called to delete a [prepared statement].
+** ^If the most recent evaluation of the statement encountered no errors
+** or if the statement is never been evaluated, then sqlite3_finalize() returns
+** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
+** sqlite3_finalize(S) returns the appropriate [error code] or
+** [extended error code].
+**
+** ^The sqlite3_finalize(S) routine can be called at any point during
+** the life cycle of [prepared statement] S:
+** before statement S is ever evaluated, after
+** one or more calls to [sqlite3_reset()], or after any call
+** to [sqlite3_step()] regardless of whether or not the statement has
+** completed execution.
+**
+** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
+**
+** The application must finalize every [prepared statement] in order to avoid
+** resource leaks. It is a grievous error for the application to try to use
+** a prepared statement after it has been finalized. Any use of a prepared
+** statement after it has been finalized can result in undefined and
+** undesirable behavior such as segfaults and heap corruption.
+*/
+SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Reset A Prepared Statement Object
+** METHOD: sqlite3_stmt
+**
+** The sqlite3_reset() function is called to reset a [prepared statement]
+** object back to its initial state, ready to be re-executed.
+** ^Any SQL statement variables that had values bound to them using
+** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
+** Use [sqlite3_clear_bindings()] to reset the bindings.
+**
+** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
+** back to the beginning of its program.
+**
+** ^If the most recent call to [sqlite3_step(S)] for the
+** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
+** or if [sqlite3_step(S)] has never before been called on S,
+** then [sqlite3_reset(S)] returns [SQLITE_OK].
+**
+** ^If the most recent call to [sqlite3_step(S)] for the
+** [prepared statement] S indicated an error, then
+** [sqlite3_reset(S)] returns an appropriate [error code].
+**
+** ^The [sqlite3_reset(S)] interface does not change the values
+** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
+*/
+SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Create Or Redefine SQL Functions
+** KEYWORDS: {function creation routines}
+** METHOD: sqlite3
+**
+** ^These functions (collectively known as "function creation routines")
+** are used to add SQL functions or aggregates or to redefine the behavior
+** of existing SQL functions or aggregates. The only differences between
+** the three "sqlite3_create_function*" routines are the text encoding
+** expected for the second parameter (the name of the function being
+** created) and the presence or absence of a destructor callback for
+** the application data pointer. Function sqlite3_create_window_function()
+** is similar, but allows the user to supply the extra callback functions
+** needed by [aggregate window functions].
+**
+** ^The first parameter is the [database connection] to which the SQL
+** function is to be added. ^If an application uses more than one database
+** connection then application-defined SQL functions must be added
+** to each database connection separately.
+**
+** ^The second parameter is the name of the SQL function to be created or
+** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
+** representation, exclusive of the zero-terminator. ^Note that the name
+** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
+** ^Any attempt to create a function with a longer name
+** will result in [SQLITE_MISUSE] being returned.
+**
+** ^The third parameter (nArg)
+** is the number of arguments that the SQL function or
+** aggregate takes. ^If this parameter is -1, then the SQL function or
+** aggregate may take any number of arguments between 0 and the limit
+** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
+** parameter is less than -1 or greater than 127 then the behavior is
+** undefined.
+**
+** ^The fourth parameter, eTextRep, specifies what
+** [SQLITE_UTF8 | text encoding] this SQL function prefers for
+** its parameters. The application should set this parameter to
+** [SQLITE_UTF16LE] if the function implementation invokes
+** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
+** implementation invokes [sqlite3_value_text16be()] on an input, or
+** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
+** otherwise. ^The same SQL function may be registered multiple times using
+** different preferred text encodings, with different implementations for
+** each encoding.
+** ^When multiple implementations of the same function are available, SQLite
+** will pick the one that involves the least amount of data conversion.
+**
+** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
+** to signal that the function will always return the same result given
+** the same inputs within a single SQL statement. Most SQL functions are
+** deterministic. The built-in [random()] SQL function is an example of a
+** function that is not deterministic. The SQLite query planner is able to
+** perform additional optimizations on deterministic functions, so use
+** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
+**
+** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY]
+** flag, which if present prevents the function from being invoked from
+** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,
+** index expressions, or the WHERE clause of partial indexes.
+**
+** <span style="background-color:#ffff90;">
+** For best security, the [SQLITE_DIRECTONLY] flag is recommended for
+** all application-defined SQL functions that do not need to be
+** used inside of triggers, view, CHECK constraints, or other elements of
+** the database schema. This flags is especially recommended for SQL
+** functions that have side effects or reveal internal application state.
+** Without this flag, an attacker might be able to modify the schema of
+** a database file to include invocations of the function with parameters
+** chosen by the attacker, which the application will then execute when
+** the database file is opened and read.
+** </span>
+**
+** ^(The fifth parameter is an arbitrary pointer. The implementation of the
+** function can gain access to this pointer using [sqlite3_user_data()].)^
+**
+** ^The sixth, seventh and eighth parameters passed to the three
+** "sqlite3_create_function*" functions, xFunc, xStep and xFinal, are
+** pointers to C-language functions that implement the SQL function or
+** aggregate. ^A scalar SQL function requires an implementation of the xFunc
+** callback only; NULL pointers must be passed as the xStep and xFinal
+** parameters. ^An aggregate SQL function requires an implementation of xStep
+** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
+** SQL function or aggregate, pass NULL pointers for all three function
+** callbacks.
+**
+** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue
+** and xInverse) passed to sqlite3_create_window_function are pointers to
+** C-language callbacks that implement the new function. xStep and xFinal
+** must both be non-NULL. xValue and xInverse may either both be NULL, in
+** which case a regular aggregate function is created, or must both be
+** non-NULL, in which case the new function may be used as either an aggregate
+** or aggregate window function. More details regarding the implementation
+** of aggregate window functions are
+** [user-defined window functions|available here].
+**
+** ^(If the final parameter to sqlite3_create_function_v2() or
+** sqlite3_create_window_function() is not NULL, then it is destructor for
+** the application data pointer. The destructor is invoked when the function
+** is deleted, either by being overloaded or when the database connection
+** closes.)^ ^The destructor is also invoked if the call to
+** sqlite3_create_function_v2() fails. ^When the destructor callback is
+** invoked, it is passed a single argument which is a copy of the application
+** data pointer which was the fifth parameter to sqlite3_create_function_v2().
+**
+** ^It is permitted to register multiple implementations of the same
+** functions with the same name but with either differing numbers of
+** arguments or differing preferred text encodings. ^SQLite will use
+** the implementation that most closely matches the way in which the
+** SQL function is used. ^A function implementation with a non-negative
+** nArg parameter is a better match than a function implementation with
+** a negative nArg. ^A function where the preferred text encoding
+** matches the database encoding is a better
+** match than a function where the encoding is different.
+** ^A function where the encoding difference is between UTF16le and UTF16be
+** is a closer match than a function where the encoding difference is
+** between UTF8 and UTF16.
+**
+** ^Built-in functions may be overloaded by new application-defined functions.
+**
+** ^An application-defined function is permitted to call other
+** SQLite interfaces. However, such calls must not
+** close the database connection nor finalize or reset the prepared
+** statement in which the function is running.
+*/
+SQLITE_API int sqlite3_create_function(
+ sqlite3 *db,
+ const char *zFunctionName,
+ int nArg,
+ int eTextRep,
+ void *pApp,
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*)
+);
+SQLITE_API int sqlite3_create_function16(
+ sqlite3 *db,
+ const void *zFunctionName,
+ int nArg,
+ int eTextRep,
+ void *pApp,
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*)
+);
+SQLITE_API int sqlite3_create_function_v2(
+ sqlite3 *db,
+ const char *zFunctionName,
+ int nArg,
+ int eTextRep,
+ void *pApp,
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*),
+ void(*xDestroy)(void*)
+);
+SQLITE_API int sqlite3_create_window_function(
+ sqlite3 *db,
+ const char *zFunctionName,
+ int nArg,
+ int eTextRep,
+ void *pApp,
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*),
+ void (*xValue)(sqlite3_context*),
+ void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
+ void(*xDestroy)(void*)
+);
+
+/*
+** CAPI3REF: Text Encodings
+**
+** These constant define integer codes that represent the various
+** text encodings supported by SQLite.
+*/
+#define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
+#define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
+#define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
+#define SQLITE_UTF16 4 /* Use native byte order */
+#define SQLITE_ANY 5 /* Deprecated */
+#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
+
+/*
+** CAPI3REF: Function Flags
+**
+** These constants may be ORed together with the
+** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
+** to [sqlite3_create_function()], [sqlite3_create_function16()], or
+** [sqlite3_create_function_v2()].
+**
+** <dl>
+** [[SQLITE_DETERMINISTIC]] <dt>SQLITE_DETERMINISTIC</dt><dd>
+** The SQLITE_DETERMINISTIC flag means that the new function always gives
+** the same output when the input parameters are the same.
+** The [abs|abs() function] is deterministic, for example, but
+** [randomblob|randomblob()] is not. Functions must
+** be deterministic in order to be used in certain contexts such as
+** with the WHERE clause of [partial indexes] or in [generated columns].
+** SQLite might also optimize deterministic functions by factoring them
+** out of inner loops.
+** </dd>
+**
+** [[SQLITE_DIRECTONLY]] <dt>SQLITE_DIRECTONLY</dt><dd>
+** The SQLITE_DIRECTONLY flag means that the function may only be invoked
+** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in
+** schema structures such as [CHECK constraints], [DEFAULT clauses],
+** [expression indexes], [partial indexes], or [generated columns].
+** The SQLITE_DIRECTONLY flags is a security feature which is recommended
+** for all [application-defined SQL functions], and especially for functions
+** that have side-effects or that could potentially leak sensitive
+** information.
+** </dd>
+**
+** [[SQLITE_INNOCUOUS]] <dt>SQLITE_INNOCUOUS</dt><dd>
+** The SQLITE_INNOCUOUS flag means that the function is unlikely
+** to cause problems even if misused. An innocuous function should have
+** no side effects and should not depend on any values other than its
+** input parameters. The [abs|abs() function] is an example of an
+** innocuous function.
+** The [load_extension() SQL function] is not innocuous because of its
+** side effects.
+** <p> SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not
+** exactly the same. The [random|random() function] is an example of a
+** function that is innocuous but not deterministic.
+** <p>Some heightened security settings
+** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF])
+** disable the use of SQL functions inside views and triggers and in
+** schema structures such as [CHECK constraints], [DEFAULT clauses],
+** [expression indexes], [partial indexes], and [generated columns] unless
+** the function is tagged with SQLITE_INNOCUOUS. Most built-in functions
+** are innocuous. Developers are advised to avoid using the
+** SQLITE_INNOCUOUS flag for application-defined functions unless the
+** function has been carefully audited and found to be free of potentially
+** security-adverse side-effects and information-leaks.
+** </dd>
+**
+** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>
+** The SQLITE_SUBTYPE flag indicates to SQLite that a function may call
+** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.
+** Specifying this flag makes no difference for scalar or aggregate user
+** functions. However, if it is not specified for a user-defined window
+** function, then any sub-types belonging to arguments passed to the window
+** function may be discarded before the window function is called (i.e.
+** sqlite3_value_subtype() will always return 0).
+** </dd>
+** </dl>
+*/
+#define SQLITE_DETERMINISTIC 0x000000800
+#define SQLITE_DIRECTONLY 0x000080000
+#define SQLITE_SUBTYPE 0x000100000
+#define SQLITE_INNOCUOUS 0x000200000
+
+/*
+** CAPI3REF: Deprecated Functions
+** DEPRECATED
+**
+** These functions are [deprecated]. In order to maintain
+** backwards compatibility with older code, these functions continue
+** to be supported. However, new applications should avoid
+** the use of these functions. To encourage programmers to avoid
+** these functions, we will not explain what they do.
+*/
+#ifndef SQLITE_OMIT_DEPRECATED
+SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
+SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
+SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
+SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
+SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
+SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
+ void*,sqlite3_int64);
+#endif
+
+/*
+** CAPI3REF: Obtaining SQL Values
+** METHOD: sqlite3_value
+**
+** <b>Summary:</b>
+** <blockquote><table border=0 cellpadding=0 cellspacing=0>
+** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
+** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
+** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
+** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
+** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
+** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
+** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
+** the native byteorder
+** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
+** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
+** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
+** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
+** or a UTF-8 TEXT in bytes
+** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
+** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
+** TEXT in bytes
+** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
+** datatype of the value
+** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
+** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
+** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>
+** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE
+** against a virtual table.
+** <tr><td><b>sqlite3_value_frombind&nbsp;&nbsp;</b>
+** <td>&rarr;&nbsp;&nbsp;<td>True if value originated from a [bound parameter]
+** </table></blockquote>
+**
+** <b>Details:</b>
+**
+** These routines extract type, size, and content information from
+** [protected sqlite3_value] objects. Protected sqlite3_value objects
+** are used to pass parameter information into the functions that
+** implement [application-defined SQL functions] and [virtual tables].
+**
+** These routines work only with [protected sqlite3_value] objects.
+** Any attempt to use these routines on an [unprotected sqlite3_value]
+** is not threadsafe.
+**
+** ^These routines work just like the corresponding [column access functions]
+** except that these routines take a single [protected sqlite3_value] object
+** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
+**
+** ^The sqlite3_value_text16() interface extracts a UTF-16 string
+** in the native byte-order of the host machine. ^The
+** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
+** extract UTF-16 strings as big-endian and little-endian respectively.
+**
+** ^If [sqlite3_value] object V was initialized
+** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
+** and if X and Y are strings that compare equal according to strcmp(X,Y),
+** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise,
+** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
+** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
+**
+** ^(The sqlite3_value_type(V) interface returns the
+** [SQLITE_INTEGER | datatype code] for the initial datatype of the
+** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
+** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
+** Other interfaces might change the datatype for an sqlite3_value object.
+** For example, if the datatype is initially SQLITE_INTEGER and
+** sqlite3_value_text(V) is called to extract a text value for that
+** integer, then subsequent calls to sqlite3_value_type(V) might return
+** SQLITE_TEXT. Whether or not a persistent internal datatype conversion
+** occurs is undefined and may change from one release of SQLite to the next.
+**
+** ^(The sqlite3_value_numeric_type() interface attempts to apply
+** numeric affinity to the value. This means that an attempt is
+** made to convert the value to an integer or floating point. If
+** such a conversion is possible without loss of information (in other
+** words, if the value is a string that looks like a number)
+** then the conversion is performed. Otherwise no conversion occurs.
+** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
+**
+** ^Within the [xUpdate] method of a [virtual table], the
+** sqlite3_value_nochange(X) interface returns true if and only if
+** the column corresponding to X is unchanged by the UPDATE operation
+** that the xUpdate method call was invoked to implement and if
+** and the prior [xColumn] method call that was invoked to extracted
+** the value for that column returned without setting a result (probably
+** because it queried [sqlite3_vtab_nochange()] and found that the column
+** was unchanging). ^Within an [xUpdate] method, any value for which
+** sqlite3_value_nochange(X) is true will in all other respects appear
+** to be a NULL value. If sqlite3_value_nochange(X) is invoked anywhere other
+** than within an [xUpdate] method call for an UPDATE statement, then
+** the return value is arbitrary and meaningless.
+**
+** ^The sqlite3_value_frombind(X) interface returns non-zero if the
+** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()]
+** interfaces. ^If X comes from an SQL literal value, or a table column,
+** or an expression, then sqlite3_value_frombind(X) returns zero.
+**
+** Please pay particular attention to the fact that the pointer returned
+** from [sqlite3_value_blob()], [sqlite3_value_text()], or
+** [sqlite3_value_text16()] can be invalidated by a subsequent call to
+** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
+** or [sqlite3_value_text16()].
+**
+** These routines must be called from the same thread as
+** the SQL function that supplied the [sqlite3_value*] parameters.
+**
+** As long as the input parameter is correct, these routines can only
+** fail if an out-of-memory error occurs during a format conversion.
+** Only the following subset of interfaces are subject to out-of-memory
+** errors:
+**
+** <ul>
+** <li> sqlite3_value_blob()
+** <li> sqlite3_value_text()
+** <li> sqlite3_value_text16()
+** <li> sqlite3_value_text16le()
+** <li> sqlite3_value_text16be()
+** <li> sqlite3_value_bytes()
+** <li> sqlite3_value_bytes16()
+** </ul>
+**
+** If an out-of-memory error occurs, then the return value from these
+** routines is the same as if the column had contained an SQL NULL value.
+** Valid SQL NULL returns can be distinguished from out-of-memory errors
+** by invoking the [sqlite3_errcode()] immediately after the suspect
+** return value is obtained and before any
+** other SQLite interface is called on the same [database connection].
+*/
+SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
+SQLITE_API double sqlite3_value_double(sqlite3_value*);
+SQLITE_API int sqlite3_value_int(sqlite3_value*);
+SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
+SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
+SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
+SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
+SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
+SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
+SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
+SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
+SQLITE_API int sqlite3_value_type(sqlite3_value*);
+SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
+SQLITE_API int sqlite3_value_nochange(sqlite3_value*);
+SQLITE_API int sqlite3_value_frombind(sqlite3_value*);
+
+/*
+** CAPI3REF: Finding The Subtype Of SQL Values
+** METHOD: sqlite3_value
+**
+** The sqlite3_value_subtype(V) function returns the subtype for
+** an [application-defined SQL function] argument V. The subtype
+** information can be used to pass a limited amount of context from
+** one SQL function to another. Use the [sqlite3_result_subtype()]
+** routine to set the subtype for the return value of an SQL function.
+*/
+SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
+
+/*
+** CAPI3REF: Copy And Free SQL Values
+** METHOD: sqlite3_value
+**
+** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
+** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
+** is a [protected sqlite3_value] object even if the input is not.
+** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
+** memory allocation fails.
+**
+** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
+** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
+** then sqlite3_value_free(V) is a harmless no-op.
+*/
+SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
+SQLITE_API void sqlite3_value_free(sqlite3_value*);
+
+/*
+** CAPI3REF: Obtain Aggregate Function Context
+** METHOD: sqlite3_context
+**
+** Implementations of aggregate SQL functions use this
+** routine to allocate memory for storing their state.
+**
+** ^The first time the sqlite3_aggregate_context(C,N) routine is called
+** for a particular aggregate function, SQLite allocates
+** N bytes of memory, zeroes out that memory, and returns a pointer
+** to the new memory. ^On second and subsequent calls to
+** sqlite3_aggregate_context() for the same aggregate function instance,
+** the same buffer is returned. Sqlite3_aggregate_context() is normally
+** called once for each invocation of the xStep callback and then one
+** last time when the xFinal callback is invoked. ^(When no rows match
+** an aggregate query, the xStep() callback of the aggregate function
+** implementation is never called and xFinal() is called exactly once.
+** In those cases, sqlite3_aggregate_context() might be called for the
+** first time from within xFinal().)^
+**
+** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
+** when first called if N is less than or equal to zero or if a memory
+** allocate error occurs.
+**
+** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
+** determined by the N parameter on first successful call. Changing the
+** value of N in any subsequent call to sqlite3_aggregate_context() within
+** the same aggregate function instance will not resize the memory
+** allocation.)^ Within the xFinal callback, it is customary to set
+** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
+** pointless memory allocations occur.
+**
+** ^SQLite automatically frees the memory allocated by
+** sqlite3_aggregate_context() when the aggregate query concludes.
+**
+** The first parameter must be a copy of the
+** [sqlite3_context | SQL function context] that is the first parameter
+** to the xStep or xFinal callback routine that implements the aggregate
+** function.
+**
+** This routine must be called from the same thread in which
+** the aggregate SQL function is running.
+*/
+SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
+
+/*
+** CAPI3REF: User Data For Functions
+** METHOD: sqlite3_context
+**
+** ^The sqlite3_user_data() interface returns a copy of
+** the pointer that was the pUserData parameter (the 5th parameter)
+** of the [sqlite3_create_function()]
+** and [sqlite3_create_function16()] routines that originally
+** registered the application defined function.
+**
+** This routine must be called from the same thread in which
+** the application-defined function is running.
+*/
+SQLITE_API void *sqlite3_user_data(sqlite3_context*);
+
+/*
+** CAPI3REF: Database Connection For Functions
+** METHOD: sqlite3_context
+**
+** ^The sqlite3_context_db_handle() interface returns a copy of
+** the pointer to the [database connection] (the 1st parameter)
+** of the [sqlite3_create_function()]
+** and [sqlite3_create_function16()] routines that originally
+** registered the application defined function.
+*/
+SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
+
+/*
+** CAPI3REF: Function Auxiliary Data
+** METHOD: sqlite3_context
+**
+** These functions may be used by (non-aggregate) SQL functions to
+** associate metadata with argument values. If the same value is passed to
+** multiple invocations of the same SQL function during query execution, under
+** some circumstances the associated metadata may be preserved. An example
+** of where this might be useful is in a regular-expression matching
+** function. The compiled version of the regular expression can be stored as
+** metadata associated with the pattern string.
+** Then as long as the pattern string remains the same,
+** the compiled regular expression can be reused on multiple
+** invocations of the same function.
+**
+** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
+** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
+** value to the application-defined function. ^N is zero for the left-most
+** function argument. ^If there is no metadata
+** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
+** returns a NULL pointer.
+**
+** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
+** argument of the application-defined function. ^Subsequent
+** calls to sqlite3_get_auxdata(C,N) return P from the most recent
+** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
+** NULL if the metadata has been discarded.
+** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
+** SQLite will invoke the destructor function X with parameter P exactly
+** once, when the metadata is discarded.
+** SQLite is free to discard the metadata at any time, including: <ul>
+** <li> ^(when the corresponding function parameter changes)^, or
+** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
+** SQL statement)^, or
+** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
+** parameter)^, or
+** <li> ^(during the original sqlite3_set_auxdata() call when a memory
+** allocation error occurs.)^ </ul>
+**
+** Note the last bullet in particular. The destructor X in
+** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
+** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
+** should be called near the end of the function implementation and the
+** function implementation should not make any use of P after
+** sqlite3_set_auxdata() has been called.
+**
+** ^(In practice, metadata is preserved between function calls for
+** function parameters that are compile-time constants, including literal
+** values and [parameters] and expressions composed from the same.)^
+**
+** The value of the N parameter to these interfaces should be non-negative.
+** Future enhancements may make use of negative N values to define new
+** kinds of function caching behavior.
+**
+** These routines must be called from the same thread in which
+** the SQL function is running.
+*/
+SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
+SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
+
+
+/*
+** CAPI3REF: Constants Defining Special Destructor Behavior
+**
+** These are special values for the destructor that is passed in as the
+** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
+** argument is SQLITE_STATIC, it means that the content pointer is constant
+** and will never change. It does not need to be destroyed. ^The
+** SQLITE_TRANSIENT value means that the content will likely change in
+** the near future and that SQLite should make its own private copy of
+** the content before returning.
+**
+** The typedef is necessary to work around problems in certain
+** C++ compilers.
+*/
+typedef void (*sqlite3_destructor_type)(void*);
+#define SQLITE_STATIC ((sqlite3_destructor_type)0)
+#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
+
+/*
+** CAPI3REF: Setting The Result Of An SQL Function
+** METHOD: sqlite3_context
+**
+** These routines are used by the xFunc or xFinal callbacks that
+** implement SQL functions and aggregates. See
+** [sqlite3_create_function()] and [sqlite3_create_function16()]
+** for additional information.
+**
+** These functions work very much like the [parameter binding] family of
+** functions used to bind values to host parameters in prepared statements.
+** Refer to the [SQL parameter] documentation for additional information.
+**
+** ^The sqlite3_result_blob() interface sets the result from
+** an application-defined function to be the BLOB whose content is pointed
+** to by the second parameter and which is N bytes long where N is the
+** third parameter.
+**
+** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
+** interfaces set the result of the application-defined function to be
+** a BLOB containing all zero bytes and N bytes in size.
+**
+** ^The sqlite3_result_double() interface sets the result from
+** an application-defined function to be a floating point value specified
+** by its 2nd argument.
+**
+** ^The sqlite3_result_error() and sqlite3_result_error16() functions
+** cause the implemented SQL function to throw an exception.
+** ^SQLite uses the string pointed to by the
+** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
+** as the text of an error message. ^SQLite interprets the error
+** message string from sqlite3_result_error() as UTF-8. ^SQLite
+** interprets the string from sqlite3_result_error16() as UTF-16 using
+** the same [byte-order determination rules] as [sqlite3_bind_text16()].
+** ^If the third parameter to sqlite3_result_error()
+** or sqlite3_result_error16() is negative then SQLite takes as the error
+** message all text up through the first zero character.
+** ^If the third parameter to sqlite3_result_error() or
+** sqlite3_result_error16() is non-negative then SQLite takes that many
+** bytes (not characters) from the 2nd parameter as the error message.
+** ^The sqlite3_result_error() and sqlite3_result_error16()
+** routines make a private copy of the error message text before
+** they return. Hence, the calling function can deallocate or
+** modify the text after they return without harm.
+** ^The sqlite3_result_error_code() function changes the error code
+** returned by SQLite as a result of an error in a function. ^By default,
+** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
+** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
+**
+** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
+** error indicating that a string or BLOB is too long to represent.
+**
+** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
+** error indicating that a memory allocation failed.
+**
+** ^The sqlite3_result_int() interface sets the return value
+** of the application-defined function to be the 32-bit signed integer
+** value given in the 2nd argument.
+** ^The sqlite3_result_int64() interface sets the return value
+** of the application-defined function to be the 64-bit signed integer
+** value given in the 2nd argument.
+**
+** ^The sqlite3_result_null() interface sets the return value
+** of the application-defined function to be NULL.
+**
+** ^The sqlite3_result_text(), sqlite3_result_text16(),
+** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
+** set the return value of the application-defined function to be
+** a text string which is represented as UTF-8, UTF-16 native byte order,
+** UTF-16 little endian, or UTF-16 big endian, respectively.
+** ^The sqlite3_result_text64() interface sets the return value of an
+** application-defined function to be a text string in an encoding
+** specified by the fifth (and last) parameter, which must be one
+** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
+** ^SQLite takes the text result from the application from
+** the 2nd parameter of the sqlite3_result_text* interfaces.
+** ^If the 3rd parameter to the sqlite3_result_text* interfaces
+** is negative, then SQLite takes result text from the 2nd parameter
+** through the first zero character.
+** ^If the 3rd parameter to the sqlite3_result_text* interfaces
+** is non-negative, then as many bytes (not characters) of the text
+** pointed to by the 2nd parameter are taken as the application-defined
+** function result. If the 3rd parameter is non-negative, then it
+** must be the byte offset into the string where the NUL terminator would
+** appear if the string where NUL terminated. If any NUL characters occur
+** in the string at a byte offset that is less than the value of the 3rd
+** parameter, then the resulting string will contain embedded NULs and the
+** result of expressions operating on strings with embedded NULs is undefined.
+** ^If the 4th parameter to the sqlite3_result_text* interfaces
+** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
+** function as the destructor on the text or BLOB result when it has
+** finished using that result.
+** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
+** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
+** assumes that the text or BLOB result is in constant space and does not
+** copy the content of the parameter nor call a destructor on the content
+** when it has finished using that result.
+** ^If the 4th parameter to the sqlite3_result_text* interfaces
+** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
+** then SQLite makes a copy of the result into space obtained
+** from [sqlite3_malloc()] before it returns.
+**
+** ^For the sqlite3_result_text16(), sqlite3_result_text16le(), and
+** sqlite3_result_text16be() routines, and for sqlite3_result_text64()
+** when the encoding is not UTF8, if the input UTF16 begins with a
+** byte-order mark (BOM, U+FEFF) then the BOM is removed from the
+** string and the rest of the string is interpreted according to the
+** byte-order specified by the BOM. ^The byte-order specified by
+** the BOM at the beginning of the text overrides the byte-order
+** specified by the interface procedure. ^So, for example, if
+** sqlite3_result_text16le() is invoked with text that begins
+** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the
+** first two bytes of input are skipped and the remaining input
+** is interpreted as UTF16BE text.
+**
+** ^For UTF16 input text to the sqlite3_result_text16(),
+** sqlite3_result_text16be(), sqlite3_result_text16le(), and
+** sqlite3_result_text64() routines, if the text contains invalid
+** UTF16 characters, the invalid characters might be converted
+** into the unicode replacement character, U+FFFD.
+**
+** ^The sqlite3_result_value() interface sets the result of
+** the application-defined function to be a copy of the
+** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
+** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
+** so that the [sqlite3_value] specified in the parameter may change or
+** be deallocated after sqlite3_result_value() returns without harm.
+** ^A [protected sqlite3_value] object may always be used where an
+** [unprotected sqlite3_value] object is required, so either
+** kind of [sqlite3_value] object can be used with this interface.
+**
+** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
+** SQL NULL value, just like [sqlite3_result_null(C)], except that it
+** also associates the host-language pointer P or type T with that
+** NULL value such that the pointer can be retrieved within an
+** [application-defined SQL function] using [sqlite3_value_pointer()].
+** ^If the D parameter is not NULL, then it is a pointer to a destructor
+** for the P parameter. ^SQLite invokes D with P as its only argument
+** when SQLite is finished with P. The T parameter should be a static
+** string and preferably a string literal. The sqlite3_result_pointer()
+** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
+**
+** If these routines are called from within the different thread
+** than the one containing the application-defined function that received
+** the [sqlite3_context] pointer, the results are undefined.
+*/
+SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
+SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
+ sqlite3_uint64,void(*)(void*));
+SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
+SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
+SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
+SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
+SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
+SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
+SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
+SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
+SQLITE_API void sqlite3_result_null(sqlite3_context*);
+SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
+SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
+ void(*)(void*), unsigned char encoding);
+SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
+SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
+SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
+SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
+SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
+SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
+SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
+
+
+/*
+** CAPI3REF: Setting The Subtype Of An SQL Function
+** METHOD: sqlite3_context
+**
+** The sqlite3_result_subtype(C,T) function causes the subtype of
+** the result from the [application-defined SQL function] with
+** [sqlite3_context] C to be the value T. Only the lower 8 bits
+** of the subtype T are preserved in current versions of SQLite;
+** higher order bits are discarded.
+** The number of subtype bytes preserved by SQLite might increase
+** in future releases of SQLite.
+*/
+SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
+
+/*
+** CAPI3REF: Define New Collating Sequences
+** METHOD: sqlite3
+**
+** ^These functions add, remove, or modify a [collation] associated
+** with the [database connection] specified as the first argument.
+**
+** ^The name of the collation is a UTF-8 string
+** for sqlite3_create_collation() and sqlite3_create_collation_v2()
+** and a UTF-16 string in native byte order for sqlite3_create_collation16().
+** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
+** considered to be the same name.
+**
+** ^(The third argument (eTextRep) must be one of the constants:
+** <ul>
+** <li> [SQLITE_UTF8],
+** <li> [SQLITE_UTF16LE],
+** <li> [SQLITE_UTF16BE],
+** <li> [SQLITE_UTF16], or
+** <li> [SQLITE_UTF16_ALIGNED].
+** </ul>)^
+** ^The eTextRep argument determines the encoding of strings passed
+** to the collating function callback, xCompare.
+** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
+** force strings to be UTF16 with native byte order.
+** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
+** on an even byte address.
+**
+** ^The fourth argument, pArg, is an application data pointer that is passed
+** through as the first argument to the collating function callback.
+**
+** ^The fifth argument, xCompare, is a pointer to the collating function.
+** ^Multiple collating functions can be registered using the same name but
+** with different eTextRep parameters and SQLite will use whichever
+** function requires the least amount of data transformation.
+** ^If the xCompare argument is NULL then the collating function is
+** deleted. ^When all collating functions having the same name are deleted,
+** that collation is no longer usable.
+**
+** ^The collating function callback is invoked with a copy of the pArg
+** application data pointer and with two strings in the encoding specified
+** by the eTextRep argument. The two integer parameters to the collating
+** function callback are the length of the two strings, in bytes. The collating
+** function must return an integer that is negative, zero, or positive
+** if the first string is less than, equal to, or greater than the second,
+** respectively. A collating function must always return the same answer
+** given the same inputs. If two or more collating functions are registered
+** to the same collation name (using different eTextRep values) then all
+** must give an equivalent answer when invoked with equivalent strings.
+** The collating function must obey the following properties for all
+** strings A, B, and C:
+**
+** <ol>
+** <li> If A==B then B==A.
+** <li> If A==B and B==C then A==C.
+** <li> If A&lt;B THEN B&gt;A.
+** <li> If A&lt;B and B&lt;C then A&lt;C.
+** </ol>
+**
+** If a collating function fails any of the above constraints and that
+** collating function is registered and used, then the behavior of SQLite
+** is undefined.
+**
+** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
+** with the addition that the xDestroy callback is invoked on pArg when
+** the collating function is deleted.
+** ^Collating functions are deleted when they are overridden by later
+** calls to the collation creation functions or when the
+** [database connection] is closed using [sqlite3_close()].
+**
+** ^The xDestroy callback is <u>not</u> called if the
+** sqlite3_create_collation_v2() function fails. Applications that invoke
+** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
+** check the return code and dispose of the application data pointer
+** themselves rather than expecting SQLite to deal with it for them.
+** This is different from every other SQLite interface. The inconsistency
+** is unfortunate but cannot be changed without breaking backwards
+** compatibility.
+**
+** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
+*/
+SQLITE_API int sqlite3_create_collation(
+ sqlite3*,
+ const char *zName,
+ int eTextRep,
+ void *pArg,
+ int(*xCompare)(void*,int,const void*,int,const void*)
+);
+SQLITE_API int sqlite3_create_collation_v2(
+ sqlite3*,
+ const char *zName,
+ int eTextRep,
+ void *pArg,
+ int(*xCompare)(void*,int,const void*,int,const void*),
+ void(*xDestroy)(void*)
+);
+SQLITE_API int sqlite3_create_collation16(
+ sqlite3*,
+ const void *zName,
+ int eTextRep,
+ void *pArg,
+ int(*xCompare)(void*,int,const void*,int,const void*)
+);
+
+/*
+** CAPI3REF: Collation Needed Callbacks
+** METHOD: sqlite3
+**
+** ^To avoid having to register all collation sequences before a database
+** can be used, a single callback function may be registered with the
+** [database connection] to be invoked whenever an undefined collation
+** sequence is required.
+**
+** ^If the function is registered using the sqlite3_collation_needed() API,
+** then it is passed the names of undefined collation sequences as strings
+** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
+** the names are passed as UTF-16 in machine native byte order.
+** ^A call to either function replaces the existing collation-needed callback.
+**
+** ^(When the callback is invoked, the first argument passed is a copy
+** of the second argument to sqlite3_collation_needed() or
+** sqlite3_collation_needed16(). The second argument is the database
+** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
+** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
+** sequence function required. The fourth parameter is the name of the
+** required collation sequence.)^
+**
+** The callback function should register the desired collation using
+** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
+** [sqlite3_create_collation_v2()].
+*/
+SQLITE_API int sqlite3_collation_needed(
+ sqlite3*,
+ void*,
+ void(*)(void*,sqlite3*,int eTextRep,const char*)
+);
+SQLITE_API int sqlite3_collation_needed16(
+ sqlite3*,
+ void*,
+ void(*)(void*,sqlite3*,int eTextRep,const void*)
+);
+
+#ifdef SQLITE_ENABLE_CEROD
+/*
+** Specify the activation key for a CEROD database. Unless
+** activated, none of the CEROD routines will work.
+*/
+SQLITE_API void sqlite3_activate_cerod(
+ const char *zPassPhrase /* Activation phrase */
+);
+#endif
+
+/*
+** CAPI3REF: Suspend Execution For A Short Time
+**
+** The sqlite3_sleep() function causes the current thread to suspend execution
+** for at least a number of milliseconds specified in its parameter.
+**
+** If the operating system does not support sleep requests with
+** millisecond time resolution, then the time will be rounded up to
+** the nearest second. The number of milliseconds of sleep actually
+** requested from the operating system is returned.
+**
+** ^SQLite implements this interface by calling the xSleep()
+** method of the default [sqlite3_vfs] object. If the xSleep() method
+** of the default VFS is not implemented correctly, or not implemented at
+** all, then the behavior of sqlite3_sleep() may deviate from the description
+** in the previous paragraphs.
+*/
+SQLITE_API int sqlite3_sleep(int);
+
+/*
+** CAPI3REF: Name Of The Folder Holding Temporary Files
+**
+** ^(If this global variable is made to point to a string which is
+** the name of a folder (a.k.a. directory), then all temporary files
+** created by SQLite when using a built-in [sqlite3_vfs | VFS]
+** will be placed in that directory.)^ ^If this variable
+** is a NULL pointer, then SQLite performs a search for an appropriate
+** temporary file directory.
+**
+** Applications are strongly discouraged from using this global variable.
+** It is required to set a temporary folder on Windows Runtime (WinRT).
+** But for all other platforms, it is highly recommended that applications
+** neither read nor write this variable. This global variable is a relic
+** that exists for backwards compatibility of legacy applications and should
+** be avoided in new projects.
+**
+** It is not safe to read or modify this variable in more than one
+** thread at a time. It is not safe to read or modify this variable
+** if a [database connection] is being used at the same time in a separate
+** thread.
+** It is intended that this variable be set once
+** as part of process initialization and before any SQLite interface
+** routines have been called and that this variable remain unchanged
+** thereafter.
+**
+** ^The [temp_store_directory pragma] may modify this variable and cause
+** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
+** the [temp_store_directory pragma] always assumes that any string
+** that this variable points to is held in memory obtained from
+** [sqlite3_malloc] and the pragma may attempt to free that memory
+** using [sqlite3_free].
+** Hence, if this variable is modified directly, either it should be
+** made NULL or made to point to memory obtained from [sqlite3_malloc]
+** or else the use of the [temp_store_directory pragma] should be avoided.
+** Except when requested by the [temp_store_directory pragma], SQLite
+** does not free the memory that sqlite3_temp_directory points to. If
+** the application wants that memory to be freed, it must do
+** so itself, taking care to only do so after all [database connection]
+** objects have been destroyed.
+**
+** <b>Note to Windows Runtime users:</b> The temporary directory must be set
+** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
+** features that require the use of temporary files may fail. Here is an
+** example of how to do this using C++ with the Windows Runtime:
+**
+** <blockquote><pre>
+** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
+** &nbsp; TemporaryFolder->Path->Data();
+** char zPathBuf&#91;MAX_PATH + 1&#93;;
+** memset(zPathBuf, 0, sizeof(zPathBuf));
+** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
+** &nbsp; NULL, NULL);
+** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
+** </pre></blockquote>
+*/
+SQLITE_API char *sqlite3_temp_directory;
+
+/*
+** CAPI3REF: Name Of The Folder Holding Database Files
+**
+** ^(If this global variable is made to point to a string which is
+** the name of a folder (a.k.a. directory), then all database files
+** specified with a relative pathname and created or accessed by
+** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
+** to be relative to that directory.)^ ^If this variable is a NULL
+** pointer, then SQLite assumes that all database files specified
+** with a relative pathname are relative to the current directory
+** for the process. Only the windows VFS makes use of this global
+** variable; it is ignored by the unix VFS.
+**
+** Changing the value of this variable while a database connection is
+** open can result in a corrupt database.
+**
+** It is not safe to read or modify this variable in more than one
+** thread at a time. It is not safe to read or modify this variable
+** if a [database connection] is being used at the same time in a separate
+** thread.
+** It is intended that this variable be set once
+** as part of process initialization and before any SQLite interface
+** routines have been called and that this variable remain unchanged
+** thereafter.
+**
+** ^The [data_store_directory pragma] may modify this variable and cause
+** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
+** the [data_store_directory pragma] always assumes that any string
+** that this variable points to is held in memory obtained from
+** [sqlite3_malloc] and the pragma may attempt to free that memory
+** using [sqlite3_free].
+** Hence, if this variable is modified directly, either it should be
+** made NULL or made to point to memory obtained from [sqlite3_malloc]
+** or else the use of the [data_store_directory pragma] should be avoided.
+*/
+SQLITE_API char *sqlite3_data_directory;
+
+/*
+** CAPI3REF: Win32 Specific Interface
+**
+** These interfaces are available only on Windows. The
+** [sqlite3_win32_set_directory] interface is used to set the value associated
+** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to
+** zValue, depending on the value of the type parameter. The zValue parameter
+** should be NULL to cause the previous value to be freed via [sqlite3_free];
+** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
+** prior to being used. The [sqlite3_win32_set_directory] interface returns
+** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,
+** or [SQLITE_NOMEM] if memory could not be allocated. The value of the
+** [sqlite3_data_directory] variable is intended to act as a replacement for
+** the current directory on the sub-platforms of Win32 where that concept is
+** not present, e.g. WinRT and UWP. The [sqlite3_win32_set_directory8] and
+** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the
+** sqlite3_win32_set_directory interface except the string parameter must be
+** UTF-8 or UTF-16, respectively.
+*/
+SQLITE_API int sqlite3_win32_set_directory(
+ unsigned long type, /* Identifier for directory being set or reset */
+ void *zValue /* New value for directory being set or reset */
+);
+SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);
+SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);
+
+/*
+** CAPI3REF: Win32 Directory Types
+**
+** These macros are only available on Windows. They define the allowed values
+** for the type argument to the [sqlite3_win32_set_directory] interface.
+*/
+#define SQLITE_WIN32_DATA_DIRECTORY_TYPE 1
+#define SQLITE_WIN32_TEMP_DIRECTORY_TYPE 2
+
+/*
+** CAPI3REF: Test For Auto-Commit Mode
+** KEYWORDS: {autocommit mode}
+** METHOD: sqlite3
+**
+** ^The sqlite3_get_autocommit() interface returns non-zero or
+** zero if the given database connection is or is not in autocommit mode,
+** respectively. ^Autocommit mode is on by default.
+** ^Autocommit mode is disabled by a [BEGIN] statement.
+** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
+**
+** If certain kinds of errors occur on a statement within a multi-statement
+** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
+** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
+** transaction might be rolled back automatically. The only way to
+** find out whether SQLite automatically rolled back the transaction after
+** an error is to use this function.
+**
+** If another thread changes the autocommit status of the database
+** connection while this routine is running, then the return value
+** is undefined.
+*/
+SQLITE_API int sqlite3_get_autocommit(sqlite3*);
+
+/*
+** CAPI3REF: Find The Database Handle Of A Prepared Statement
+** METHOD: sqlite3_stmt
+**
+** ^The sqlite3_db_handle interface returns the [database connection] handle
+** to which a [prepared statement] belongs. ^The [database connection]
+** returned by sqlite3_db_handle is the same [database connection]
+** that was the first argument
+** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
+** create the statement in the first place.
+*/
+SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
+
+/*
+** CAPI3REF: Return The Filename For A Database Connection
+** METHOD: sqlite3
+**
+** ^The sqlite3_db_filename(D,N) interface returns a pointer to the filename
+** associated with database N of connection D.
+** ^If there is no attached database N on the database
+** connection D, or if database N is a temporary or in-memory database, then
+** this function will return either a NULL pointer or an empty string.
+**
+** ^The string value returned by this routine is owned and managed by
+** the database connection. ^The value will be valid until the database N
+** is [DETACH]-ed or until the database connection closes.
+**
+** ^The filename returned by this function is the output of the
+** xFullPathname method of the [VFS]. ^In other words, the filename
+** will be an absolute pathname, even if the filename used
+** to open the database originally was a URI or relative pathname.
+**
+** If the filename pointer returned by this routine is not NULL, then it
+** can be used as the filename input parameter to these routines:
+** <ul>
+** <li> [sqlite3_uri_parameter()]
+** <li> [sqlite3_uri_boolean()]
+** <li> [sqlite3_uri_int64()]
+** <li> [sqlite3_filename_database()]
+** <li> [sqlite3_filename_journal()]
+** <li> [sqlite3_filename_wal()]
+** </ul>
+*/
+SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
+
+/*
+** CAPI3REF: Determine if a database is read-only
+** METHOD: sqlite3
+**
+** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
+** of connection D is read-only, 0 if it is read/write, or -1 if N is not
+** the name of a database on connection D.
+*/
+SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
+
+/*
+** CAPI3REF: Determine the transaction state of a database
+** METHOD: sqlite3
+**
+** ^The sqlite3_txn_state(D,S) interface returns the current
+** [transaction state] of schema S in database connection D. ^If S is NULL,
+** then the highest transaction state of any schema on databse connection D
+** is returned. Transaction states are (in order of lowest to highest):
+** <ol>
+** <li value="0"> SQLITE_TXN_NONE
+** <li value="1"> SQLITE_TXN_READ
+** <li value="2"> SQLITE_TXN_WRITE
+** </ol>
+** ^If the S argument to sqlite3_txn_state(D,S) is not the name of
+** a valid schema, then -1 is returned.
+*/
+SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema);
+
+/*
+** CAPI3REF: Allowed return values from [sqlite3_txn_state()]
+** KEYWORDS: {transaction state}
+**
+** These constants define the current transaction state of a database file.
+** ^The [sqlite3_txn_state(D,S)] interface returns one of these
+** constants in order to describe the transaction state of schema S
+** in [database connection] D.
+**
+** <dl>
+** [[SQLITE_TXN_NONE]] <dt>SQLITE_TXN_NONE</dt>
+** <dd>The SQLITE_TXN_NONE state means that no transaction is currently
+** pending.</dd>
+**
+** [[SQLITE_TXN_READ]] <dt>SQLITE_TXN_READ</dt>
+** <dd>The SQLITE_TXN_READ state means that the database is currently
+** in a read transaction. Content has been read from the database file
+** but nothing in the database file has changed. The transaction state
+** will advanced to SQLITE_TXN_WRITE if any changes occur and there are
+** no other conflicting concurrent write transactions. The transaction
+** state will revert to SQLITE_TXN_NONE following a [ROLLBACK] or
+** [COMMIT].</dd>
+**
+** [[SQLITE_TXN_WRITE]] <dt>SQLITE_TXN_WRITE</dt>
+** <dd>The SQLITE_TXN_WRITE state means that the database is currently
+** in a write transaction. Content has been written to the database file
+** but has not yet committed. The transaction state will change to
+** to SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd>
+*/
+#define SQLITE_TXN_NONE 0
+#define SQLITE_TXN_READ 1
+#define SQLITE_TXN_WRITE 2
+
+/*
+** CAPI3REF: Find the next prepared statement
+** METHOD: sqlite3
+**
+** ^This interface returns a pointer to the next [prepared statement] after
+** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
+** then this interface returns a pointer to the first prepared statement
+** associated with the database connection pDb. ^If no prepared statement
+** satisfies the conditions of this routine, it returns NULL.
+**
+** The [database connection] pointer D in a call to
+** [sqlite3_next_stmt(D,S)] must refer to an open database
+** connection and in particular must not be a NULL pointer.
+*/
+SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Commit And Rollback Notification Callbacks
+** METHOD: sqlite3
+**
+** ^The sqlite3_commit_hook() interface registers a callback
+** function to be invoked whenever a transaction is [COMMIT | committed].
+** ^Any callback set by a previous call to sqlite3_commit_hook()
+** for the same database connection is overridden.
+** ^The sqlite3_rollback_hook() interface registers a callback
+** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
+** ^Any callback set by a previous call to sqlite3_rollback_hook()
+** for the same database connection is overridden.
+** ^The pArg argument is passed through to the callback.
+** ^If the callback on a commit hook function returns non-zero,
+** then the commit is converted into a rollback.
+**
+** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
+** return the P argument from the previous call of the same function
+** on the same [database connection] D, or NULL for
+** the first call for each function on D.
+**
+** The commit and rollback hook callbacks are not reentrant.
+** The callback implementation must not do anything that will modify
+** the database connection that invoked the callback. Any actions
+** to modify the database connection must be deferred until after the
+** completion of the [sqlite3_step()] call that triggered the commit
+** or rollback hook in the first place.
+** Note that running any other SQL statements, including SELECT statements,
+** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
+** the database connections for the meaning of "modify" in this paragraph.
+**
+** ^Registering a NULL function disables the callback.
+**
+** ^When the commit hook callback routine returns zero, the [COMMIT]
+** operation is allowed to continue normally. ^If the commit hook
+** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
+** ^The rollback hook is invoked on a rollback that results from a commit
+** hook returning non-zero, just as it would be with any other rollback.
+**
+** ^For the purposes of this API, a transaction is said to have been
+** rolled back if an explicit "ROLLBACK" statement is executed, or
+** an error or constraint causes an implicit rollback to occur.
+** ^The rollback callback is not invoked if a transaction is
+** automatically rolled back because the database connection is closed.
+**
+** See also the [sqlite3_update_hook()] interface.
+*/
+SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
+SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
+
+/*
+** CAPI3REF: Data Change Notification Callbacks
+** METHOD: sqlite3
+**
+** ^The sqlite3_update_hook() interface registers a callback function
+** with the [database connection] identified by the first argument
+** to be invoked whenever a row is updated, inserted or deleted in
+** a [rowid table].
+** ^Any callback set by a previous call to this function
+** for the same database connection is overridden.
+**
+** ^The second argument is a pointer to the function to invoke when a
+** row is updated, inserted or deleted in a rowid table.
+** ^The first argument to the callback is a copy of the third argument
+** to sqlite3_update_hook().
+** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
+** or [SQLITE_UPDATE], depending on the operation that caused the callback
+** to be invoked.
+** ^The third and fourth arguments to the callback contain pointers to the
+** database and table name containing the affected row.
+** ^The final callback parameter is the [rowid] of the row.
+** ^In the case of an update, this is the [rowid] after the update takes place.
+**
+** ^(The update hook is not invoked when internal system tables are
+** modified (i.e. sqlite_sequence).)^
+** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
+**
+** ^In the current implementation, the update hook
+** is not invoked when conflicting rows are deleted because of an
+** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
+** invoked when rows are deleted using the [truncate optimization].
+** The exceptions defined in this paragraph might change in a future
+** release of SQLite.
+**
+** The update hook implementation must not do anything that will modify
+** the database connection that invoked the update hook. Any actions
+** to modify the database connection must be deferred until after the
+** completion of the [sqlite3_step()] call that triggered the update hook.
+** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
+** database connections for the meaning of "modify" in this paragraph.
+**
+** ^The sqlite3_update_hook(D,C,P) function
+** returns the P argument from the previous call
+** on the same [database connection] D, or NULL for
+** the first call on D.
+**
+** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
+** and [sqlite3_preupdate_hook()] interfaces.
+*/
+SQLITE_API void *sqlite3_update_hook(
+ sqlite3*,
+ void(*)(void *,int ,char const *,char const *,sqlite3_int64),
+ void*
+);
+
+/*
+** CAPI3REF: Enable Or Disable Shared Pager Cache
+**
+** ^(This routine enables or disables the sharing of the database cache
+** and schema data structures between [database connection | connections]
+** to the same database. Sharing is enabled if the argument is true
+** and disabled if the argument is false.)^
+**
+** ^Cache sharing is enabled and disabled for an entire process.
+** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
+** In prior versions of SQLite,
+** sharing was enabled or disabled for each thread separately.
+**
+** ^(The cache sharing mode set by this interface effects all subsequent
+** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
+** Existing database connections continue to use the sharing mode
+** that was in effect at the time they were opened.)^
+**
+** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
+** successfully. An [error code] is returned otherwise.)^
+**
+** ^Shared cache is disabled by default. It is recommended that it stay
+** that way. In other words, do not use this routine. This interface
+** continues to be provided for historical compatibility, but its use is
+** discouraged. Any use of shared cache is discouraged. If shared cache
+** must be used, it is recommended that shared cache only be enabled for
+** individual database connections using the [sqlite3_open_v2()] interface
+** with the [SQLITE_OPEN_SHAREDCACHE] flag.
+**
+** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
+** and will always return SQLITE_MISUSE. On those systems,
+** shared cache mode should be enabled per-database connection via
+** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
+**
+** This interface is threadsafe on processors where writing a
+** 32-bit integer is atomic.
+**
+** See Also: [SQLite Shared-Cache Mode]
+*/
+SQLITE_API int sqlite3_enable_shared_cache(int);
+
+/*
+** CAPI3REF: Attempt To Free Heap Memory
+**
+** ^The sqlite3_release_memory() interface attempts to free N bytes
+** of heap memory by deallocating non-essential memory allocations
+** held by the database library. Memory used to cache database
+** pages to improve performance is an example of non-essential memory.
+** ^sqlite3_release_memory() returns the number of bytes actually freed,
+** which might be more or less than the amount requested.
+** ^The sqlite3_release_memory() routine is a no-op returning zero
+** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
+**
+** See also: [sqlite3_db_release_memory()]
+*/
+SQLITE_API int sqlite3_release_memory(int);
+
+/*
+** CAPI3REF: Free Memory Used By A Database Connection
+** METHOD: sqlite3
+**
+** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
+** memory as possible from database connection D. Unlike the
+** [sqlite3_release_memory()] interface, this interface is in effect even
+** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
+** omitted.
+**
+** See also: [sqlite3_release_memory()]
+*/
+SQLITE_API int sqlite3_db_release_memory(sqlite3*);
+
+/*
+** CAPI3REF: Impose A Limit On Heap Size
+**
+** These interfaces impose limits on the amount of heap memory that will be
+** by all database connections within a single process.
+**
+** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
+** soft limit on the amount of heap memory that may be allocated by SQLite.
+** ^SQLite strives to keep heap memory utilization below the soft heap
+** limit by reducing the number of pages held in the page cache
+** as heap memory usages approaches the limit.
+** ^The soft heap limit is "soft" because even though SQLite strives to stay
+** below the limit, it will exceed the limit rather than generate
+** an [SQLITE_NOMEM] error. In other words, the soft heap limit
+** is advisory only.
+**
+** ^The sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of
+** N bytes on the amount of memory that will be allocated. ^The
+** sqlite3_hard_heap_limit64(N) interface is similar to
+** sqlite3_soft_heap_limit64(N) except that memory allocations will fail
+** when the hard heap limit is reached.
+**
+** ^The return value from both sqlite3_soft_heap_limit64() and
+** sqlite3_hard_heap_limit64() is the size of
+** the heap limit prior to the call, or negative in the case of an
+** error. ^If the argument N is negative
+** then no change is made to the heap limit. Hence, the current
+** size of heap limits can be determined by invoking
+** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1).
+**
+** ^Setting the heap limits to zero disables the heap limiter mechanism.
+**
+** ^The soft heap limit may not be greater than the hard heap limit.
+** ^If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N)
+** is invoked with a value of N that is greater than the hard heap limit,
+** the the soft heap limit is set to the value of the hard heap limit.
+** ^The soft heap limit is automatically enabled whenever the hard heap
+** limit is enabled. ^When sqlite3_hard_heap_limit64(N) is invoked and
+** the soft heap limit is outside the range of 1..N, then the soft heap
+** limit is set to N. ^Invoking sqlite3_soft_heap_limit64(0) when the
+** hard heap limit is enabled makes the soft heap limit equal to the
+** hard heap limit.
+**
+** The memory allocation limits can also be adjusted using
+** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit].
+**
+** ^(The heap limits are not enforced in the current implementation
+** if one or more of following conditions are true:
+**
+** <ul>
+** <li> The limit value is set to zero.
+** <li> Memory accounting is disabled using a combination of the
+** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
+** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
+** <li> An alternative page cache implementation is specified using
+** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
+** <li> The page cache allocates from its own memory pool supplied
+** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
+** from the heap.
+** </ul>)^
+**
+** The circumstances under which SQLite will enforce the heap limits may
+** changes in future releases of SQLite.
+*/
+SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
+SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N);
+
+/*
+** CAPI3REF: Deprecated Soft Heap Limit Interface
+** DEPRECATED
+**
+** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
+** interface. This routine is provided for historical compatibility
+** only. All new applications should use the
+** [sqlite3_soft_heap_limit64()] interface rather than this one.
+*/
+SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
+
+
+/*
+** CAPI3REF: Extract Metadata About A Column Of A Table
+** METHOD: sqlite3
+**
+** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
+** information about column C of table T in database D
+** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
+** interface returns SQLITE_OK and fills in the non-NULL pointers in
+** the final five arguments with appropriate values if the specified
+** column exists. ^The sqlite3_table_column_metadata() interface returns
+** SQLITE_ERROR if the specified column does not exist.
+** ^If the column-name parameter to sqlite3_table_column_metadata() is a
+** NULL pointer, then this routine simply checks for the existence of the
+** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
+** does not. If the table name parameter T in a call to
+** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
+** undefined behavior.
+**
+** ^The column is identified by the second, third and fourth parameters to
+** this function. ^(The second parameter is either the name of the database
+** (i.e. "main", "temp", or an attached database) containing the specified
+** table or NULL.)^ ^If it is NULL, then all attached databases are searched
+** for the table using the same algorithm used by the database engine to
+** resolve unqualified table references.
+**
+** ^The third and fourth parameters to this function are the table and column
+** name of the desired column, respectively.
+**
+** ^Metadata is returned by writing to the memory locations passed as the 5th
+** and subsequent parameters to this function. ^Any of these arguments may be
+** NULL, in which case the corresponding element of metadata is omitted.
+**
+** ^(<blockquote>
+** <table border="1">
+** <tr><th> Parameter <th> Output<br>Type <th> Description
+**
+** <tr><td> 5th <td> const char* <td> Data type
+** <tr><td> 6th <td> const char* <td> Name of default collation sequence
+** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
+** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
+** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
+** </table>
+** </blockquote>)^
+**
+** ^The memory pointed to by the character pointers returned for the
+** declaration type and collation sequence is valid until the next
+** call to any SQLite API function.
+**
+** ^If the specified table is actually a view, an [error code] is returned.
+**
+** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
+** is not a [WITHOUT ROWID] table and an
+** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
+** parameters are set for the explicitly declared column. ^(If there is no
+** [INTEGER PRIMARY KEY] column, then the outputs
+** for the [rowid] are set as follows:
+**
+** <pre>
+** data type: "INTEGER"
+** collation sequence: "BINARY"
+** not null: 0
+** primary key: 1
+** auto increment: 0
+** </pre>)^
+**
+** ^This function causes all database schemas to be read from disk and
+** parsed, if that has not already been done, and returns an error if
+** any errors are encountered while loading the schema.
+*/
+SQLITE_API int sqlite3_table_column_metadata(
+ sqlite3 *db, /* Connection handle */
+ const char *zDbName, /* Database name or NULL */
+ const char *zTableName, /* Table name */
+ const char *zColumnName, /* Column name */
+ char const **pzDataType, /* OUTPUT: Declared data type */
+ char const **pzCollSeq, /* OUTPUT: Collation sequence name */
+ int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
+ int *pPrimaryKey, /* OUTPUT: True if column part of PK */
+ int *pAutoinc /* OUTPUT: True if column is auto-increment */
+);
+
+/*
+** CAPI3REF: Load An Extension
+** METHOD: sqlite3
+**
+** ^This interface loads an SQLite extension library from the named file.
+**
+** ^The sqlite3_load_extension() interface attempts to load an
+** [SQLite extension] library contained in the file zFile. If
+** the file cannot be loaded directly, attempts are made to load
+** with various operating-system specific extensions added.
+** So for example, if "samplelib" cannot be loaded, then names like
+** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
+** be tried also.
+**
+** ^The entry point is zProc.
+** ^(zProc may be 0, in which case SQLite will try to come up with an
+** entry point name on its own. It first tries "sqlite3_extension_init".
+** If that does not work, it constructs a name "sqlite3_X_init" where the
+** X is consists of the lower-case equivalent of all ASCII alphabetic
+** characters in the filename from the last "/" to the first following
+** "." and omitting any initial "lib".)^
+** ^The sqlite3_load_extension() interface returns
+** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
+** ^If an error occurs and pzErrMsg is not 0, then the
+** [sqlite3_load_extension()] interface shall attempt to
+** fill *pzErrMsg with error message text stored in memory
+** obtained from [sqlite3_malloc()]. The calling function
+** should free this memory by calling [sqlite3_free()].
+**
+** ^Extension loading must be enabled using
+** [sqlite3_enable_load_extension()] or
+** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
+** prior to calling this API,
+** otherwise an error will be returned.
+**
+** <b>Security warning:</b> It is recommended that the
+** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
+** interface. The use of the [sqlite3_enable_load_extension()] interface
+** should be avoided. This will keep the SQL function [load_extension()]
+** disabled and prevent SQL injections from giving attackers
+** access to extension loading capabilities.
+**
+** See also the [load_extension() SQL function].
+*/
+SQLITE_API int sqlite3_load_extension(
+ sqlite3 *db, /* Load the extension into this database connection */
+ const char *zFile, /* Name of the shared library containing extension */
+ const char *zProc, /* Entry point. Derived from zFile if 0 */
+ char **pzErrMsg /* Put error message here if not 0 */
+);
+
+/*
+** CAPI3REF: Enable Or Disable Extension Loading
+** METHOD: sqlite3
+**
+** ^So as not to open security holes in older applications that are
+** unprepared to deal with [extension loading], and as a means of disabling
+** [extension loading] while evaluating user-entered SQL, the following API
+** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
+**
+** ^Extension loading is off by default.
+** ^Call the sqlite3_enable_load_extension() routine with onoff==1
+** to turn extension loading on and call it with onoff==0 to turn
+** it back off again.
+**
+** ^This interface enables or disables both the C-API
+** [sqlite3_load_extension()] and the SQL function [load_extension()].
+** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
+** to enable or disable only the C-API.)^
+**
+** <b>Security warning:</b> It is recommended that extension loading
+** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
+** rather than this interface, so the [load_extension()] SQL function
+** remains disabled. This will prevent SQL injections from giving attackers
+** access to extension loading capabilities.
+*/
+SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
+
+/*
+** CAPI3REF: Automatically Load Statically Linked Extensions
+**
+** ^This interface causes the xEntryPoint() function to be invoked for
+** each new [database connection] that is created. The idea here is that
+** xEntryPoint() is the entry point for a statically linked [SQLite extension]
+** that is to be automatically loaded into all new database connections.
+**
+** ^(Even though the function prototype shows that xEntryPoint() takes
+** no arguments and returns void, SQLite invokes xEntryPoint() with three
+** arguments and expects an integer result as if the signature of the
+** entry point where as follows:
+**
+** <blockquote><pre>
+** &nbsp; int xEntryPoint(
+** &nbsp; sqlite3 *db,
+** &nbsp; const char **pzErrMsg,
+** &nbsp; const struct sqlite3_api_routines *pThunk
+** &nbsp; );
+** </pre></blockquote>)^
+**
+** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
+** point to an appropriate error message (obtained from [sqlite3_mprintf()])
+** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
+** is NULL before calling the xEntryPoint(). ^SQLite will invoke
+** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
+** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
+** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
+**
+** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
+** on the list of automatic extensions is a harmless no-op. ^No entry point
+** will be called more than once for each database connection that is opened.
+**
+** See also: [sqlite3_reset_auto_extension()]
+** and [sqlite3_cancel_auto_extension()]
+*/
+SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
+
+/*
+** CAPI3REF: Cancel Automatic Extension Loading
+**
+** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
+** initialization routine X that was registered using a prior call to
+** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
+** routine returns 1 if initialization routine X was successfully
+** unregistered and it returns 0 if X was not on the list of initialization
+** routines.
+*/
+SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
+
+/*
+** CAPI3REF: Reset Automatic Extension Loading
+**
+** ^This interface disables all automatic extensions previously
+** registered using [sqlite3_auto_extension()].
+*/
+SQLITE_API void sqlite3_reset_auto_extension(void);
+
+/*
+** The interface to the virtual-table mechanism is currently considered
+** to be experimental. The interface might change in incompatible ways.
+** If this is a problem for you, do not use the interface at this time.
+**
+** When the virtual-table mechanism stabilizes, we will declare the
+** interface fixed, support it indefinitely, and remove this comment.
+*/
+
+/*
+** Structures used by the virtual table interface
+*/
+typedef struct sqlite3_vtab sqlite3_vtab;
+typedef struct sqlite3_index_info sqlite3_index_info;
+typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
+typedef struct sqlite3_module sqlite3_module;
+
+/*
+** CAPI3REF: Virtual Table Object
+** KEYWORDS: sqlite3_module {virtual table module}
+**
+** This structure, sometimes called a "virtual table module",
+** defines the implementation of a [virtual table].
+** This structure consists mostly of methods for the module.
+**
+** ^A virtual table module is created by filling in a persistent
+** instance of this structure and passing a pointer to that instance
+** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
+** ^The registration remains valid until it is replaced by a different
+** module or until the [database connection] closes. The content
+** of this structure must not change while it is registered with
+** any database connection.
+*/
+struct sqlite3_module {
+ int iVersion;
+ int (*xCreate)(sqlite3*, void *pAux,
+ int argc, const char *const*argv,
+ sqlite3_vtab **ppVTab, char**);
+ int (*xConnect)(sqlite3*, void *pAux,
+ int argc, const char *const*argv,
+ sqlite3_vtab **ppVTab, char**);
+ int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
+ int (*xDisconnect)(sqlite3_vtab *pVTab);
+ int (*xDestroy)(sqlite3_vtab *pVTab);
+ int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
+ int (*xClose)(sqlite3_vtab_cursor*);
+ int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
+ int argc, sqlite3_value **argv);
+ int (*xNext)(sqlite3_vtab_cursor*);
+ int (*xEof)(sqlite3_vtab_cursor*);
+ int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
+ int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
+ int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
+ int (*xBegin)(sqlite3_vtab *pVTab);
+ int (*xSync)(sqlite3_vtab *pVTab);
+ int (*xCommit)(sqlite3_vtab *pVTab);
+ int (*xRollback)(sqlite3_vtab *pVTab);
+ int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
+ void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
+ void **ppArg);
+ int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
+ /* The methods above are in version 1 of the sqlite_module object. Those
+ ** below are for version 2 and greater. */
+ int (*xSavepoint)(sqlite3_vtab *pVTab, int);
+ int (*xRelease)(sqlite3_vtab *pVTab, int);
+ int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
+ /* The methods above are in versions 1 and 2 of the sqlite_module object.
+ ** Those below are for version 3 and greater. */
+ int (*xShadowName)(const char*);
+};
+
+/*
+** CAPI3REF: Virtual Table Indexing Information
+** KEYWORDS: sqlite3_index_info
+**
+** The sqlite3_index_info structure and its substructures is used as part
+** of the [virtual table] interface to
+** pass information into and receive the reply from the [xBestIndex]
+** method of a [virtual table module]. The fields under **Inputs** are the
+** inputs to xBestIndex and are read-only. xBestIndex inserts its
+** results into the **Outputs** fields.
+**
+** ^(The aConstraint[] array records WHERE clause constraints of the form:
+**
+** <blockquote>column OP expr</blockquote>
+**
+** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
+** stored in aConstraint[].op using one of the
+** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
+** ^(The index of the column is stored in
+** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
+** expr on the right-hand side can be evaluated (and thus the constraint
+** is usable) and false if it cannot.)^
+**
+** ^The optimizer automatically inverts terms of the form "expr OP column"
+** and makes other simplifications to the WHERE clause in an attempt to
+** get as many WHERE clause terms into the form shown above as possible.
+** ^The aConstraint[] array only reports WHERE clause terms that are
+** relevant to the particular virtual table being queried.
+**
+** ^Information about the ORDER BY clause is stored in aOrderBy[].
+** ^Each term of aOrderBy records a column of the ORDER BY clause.
+**
+** The colUsed field indicates which columns of the virtual table may be
+** required by the current scan. Virtual table columns are numbered from
+** zero in the order in which they appear within the CREATE TABLE statement
+** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
+** the corresponding bit is set within the colUsed mask if the column may be
+** required by SQLite. If the table has at least 64 columns and any column
+** to the right of the first 63 is required, then bit 63 of colUsed is also
+** set. In other words, column iCol may be required if the expression
+** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
+** non-zero.
+**
+** The [xBestIndex] method must fill aConstraintUsage[] with information
+** about what parameters to pass to xFilter. ^If argvIndex>0 then
+** the right-hand side of the corresponding aConstraint[] is evaluated
+** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
+** is true, then the constraint is assumed to be fully handled by the
+** virtual table and might not be checked again by the byte code.)^ ^(The
+** aConstraintUsage[].omit flag is an optimization hint. When the omit flag
+** is left in its default setting of false, the constraint will always be
+** checked separately in byte code. If the omit flag is change to true, then
+** the constraint may or may not be checked in byte code. In other words,
+** when the omit flag is true there is no guarantee that the constraint will
+** not be checked again using byte code.)^
+**
+** ^The idxNum and idxPtr values are recorded and passed into the
+** [xFilter] method.
+** ^[sqlite3_free()] is used to free idxPtr if and only if
+** needToFreeIdxPtr is true.
+**
+** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
+** the correct order to satisfy the ORDER BY clause so that no separate
+** sorting step is required.
+**
+** ^The estimatedCost value is an estimate of the cost of a particular
+** strategy. A cost of N indicates that the cost of the strategy is similar
+** to a linear scan of an SQLite table with N rows. A cost of log(N)
+** indicates that the expense of the operation is similar to that of a
+** binary search on a unique indexed field of an SQLite table with N rows.
+**
+** ^The estimatedRows value is an estimate of the number of rows that
+** will be returned by the strategy.
+**
+** The xBestIndex method may optionally populate the idxFlags field with a
+** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
+** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
+** assumes that the strategy may visit at most one row.
+**
+** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
+** SQLite also assumes that if a call to the xUpdate() method is made as
+** part of the same statement to delete or update a virtual table row and the
+** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
+** any database changes. In other words, if the xUpdate() returns
+** SQLITE_CONSTRAINT, the database contents must be exactly as they were
+** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
+** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
+** the xUpdate method are automatically rolled back by SQLite.
+**
+** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
+** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
+** If a virtual table extension is
+** used with an SQLite version earlier than 3.8.2, the results of attempting
+** to read or write the estimatedRows field are undefined (but are likely
+** to include crashing the application). The estimatedRows field should
+** therefore only be used if [sqlite3_libversion_number()] returns a
+** value greater than or equal to 3008002. Similarly, the idxFlags field
+** was added for [version 3.9.0] ([dateof:3.9.0]).
+** It may therefore only be used if
+** sqlite3_libversion_number() returns a value greater than or equal to
+** 3009000.
+*/
+struct sqlite3_index_info {
+ /* Inputs */
+ int nConstraint; /* Number of entries in aConstraint */
+ struct sqlite3_index_constraint {
+ int iColumn; /* Column constrained. -1 for ROWID */
+ unsigned char op; /* Constraint operator */
+ unsigned char usable; /* True if this constraint is usable */
+ int iTermOffset; /* Used internally - xBestIndex should ignore */
+ } *aConstraint; /* Table of WHERE clause constraints */
+ int nOrderBy; /* Number of terms in the ORDER BY clause */
+ struct sqlite3_index_orderby {
+ int iColumn; /* Column number */
+ unsigned char desc; /* True for DESC. False for ASC. */
+ } *aOrderBy; /* The ORDER BY clause */
+ /* Outputs */
+ struct sqlite3_index_constraint_usage {
+ int argvIndex; /* if >0, constraint is part of argv to xFilter */
+ unsigned char omit; /* Do not code a test for this constraint */
+ } *aConstraintUsage;
+ int idxNum; /* Number used to identify the index */
+ char *idxStr; /* String, possibly obtained from sqlite3_malloc */
+ int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
+ int orderByConsumed; /* True if output is already ordered */
+ double estimatedCost; /* Estimated cost of using this index */
+ /* Fields below are only available in SQLite 3.8.2 and later */
+ sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
+ /* Fields below are only available in SQLite 3.9.0 and later */
+ int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
+ /* Fields below are only available in SQLite 3.10.0 and later */
+ sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
+};
+
+/*
+** CAPI3REF: Virtual Table Scan Flags
+**
+** Virtual table implementations are allowed to set the
+** [sqlite3_index_info].idxFlags field to some combination of
+** these bits.
+*/
+#define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
+
+/*
+** CAPI3REF: Virtual Table Constraint Operator Codes
+**
+** These macros define the allowed values for the
+** [sqlite3_index_info].aConstraint[].op field. Each value represents
+** an operator that is part of a constraint term in the wHERE clause of
+** a query that uses a [virtual table].
+*/
+#define SQLITE_INDEX_CONSTRAINT_EQ 2
+#define SQLITE_INDEX_CONSTRAINT_GT 4
+#define SQLITE_INDEX_CONSTRAINT_LE 8
+#define SQLITE_INDEX_CONSTRAINT_LT 16
+#define SQLITE_INDEX_CONSTRAINT_GE 32
+#define SQLITE_INDEX_CONSTRAINT_MATCH 64
+#define SQLITE_INDEX_CONSTRAINT_LIKE 65
+#define SQLITE_INDEX_CONSTRAINT_GLOB 66
+#define SQLITE_INDEX_CONSTRAINT_REGEXP 67
+#define SQLITE_INDEX_CONSTRAINT_NE 68
+#define SQLITE_INDEX_CONSTRAINT_ISNOT 69
+#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
+#define SQLITE_INDEX_CONSTRAINT_ISNULL 71
+#define SQLITE_INDEX_CONSTRAINT_IS 72
+#define SQLITE_INDEX_CONSTRAINT_FUNCTION 150
+
+/*
+** CAPI3REF: Register A Virtual Table Implementation
+** METHOD: sqlite3
+**
+** ^These routines are used to register a new [virtual table module] name.
+** ^Module names must be registered before
+** creating a new [virtual table] using the module and before using a
+** preexisting [virtual table] for the module.
+**
+** ^The module name is registered on the [database connection] specified
+** by the first parameter. ^The name of the module is given by the
+** second parameter. ^The third parameter is a pointer to
+** the implementation of the [virtual table module]. ^The fourth
+** parameter is an arbitrary client data pointer that is passed through
+** into the [xCreate] and [xConnect] methods of the virtual table module
+** when a new virtual table is be being created or reinitialized.
+**
+** ^The sqlite3_create_module_v2() interface has a fifth parameter which
+** is a pointer to a destructor for the pClientData. ^SQLite will
+** invoke the destructor function (if it is not NULL) when SQLite
+** no longer needs the pClientData pointer. ^The destructor will also
+** be invoked if the call to sqlite3_create_module_v2() fails.
+** ^The sqlite3_create_module()
+** interface is equivalent to sqlite3_create_module_v2() with a NULL
+** destructor.
+**
+** ^If the third parameter (the pointer to the sqlite3_module object) is
+** NULL then no new module is create and any existing modules with the
+** same name are dropped.
+**
+** See also: [sqlite3_drop_modules()]
+*/
+SQLITE_API int sqlite3_create_module(
+ sqlite3 *db, /* SQLite connection to register module with */
+ const char *zName, /* Name of the module */
+ const sqlite3_module *p, /* Methods for the module */
+ void *pClientData /* Client data for xCreate/xConnect */
+);
+SQLITE_API int sqlite3_create_module_v2(
+ sqlite3 *db, /* SQLite connection to register module with */
+ const char *zName, /* Name of the module */
+ const sqlite3_module *p, /* Methods for the module */
+ void *pClientData, /* Client data for xCreate/xConnect */
+ void(*xDestroy)(void*) /* Module destructor function */
+);
+
+/*
+** CAPI3REF: Remove Unnecessary Virtual Table Implementations
+** METHOD: sqlite3
+**
+** ^The sqlite3_drop_modules(D,L) interface removes all virtual
+** table modules from database connection D except those named on list L.
+** The L parameter must be either NULL or a pointer to an array of pointers
+** to strings where the array is terminated by a single NULL pointer.
+** ^If the L parameter is NULL, then all virtual table modules are removed.
+**
+** See also: [sqlite3_create_module()]
+*/
+SQLITE_API int sqlite3_drop_modules(
+ sqlite3 *db, /* Remove modules from this connection */
+ const char **azKeep /* Except, do not remove the ones named here */
+);
+
+/*
+** CAPI3REF: Virtual Table Instance Object
+** KEYWORDS: sqlite3_vtab
+**
+** Every [virtual table module] implementation uses a subclass
+** of this object to describe a particular instance
+** of the [virtual table]. Each subclass will
+** be tailored to the specific needs of the module implementation.
+** The purpose of this superclass is to define certain fields that are
+** common to all module implementations.
+**
+** ^Virtual tables methods can set an error message by assigning a
+** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
+** take care that any prior string is freed by a call to [sqlite3_free()]
+** prior to assigning a new string to zErrMsg. ^After the error message
+** is delivered up to the client application, the string will be automatically
+** freed by sqlite3_free() and the zErrMsg field will be zeroed.
+*/
+struct sqlite3_vtab {
+ const sqlite3_module *pModule; /* The module for this virtual table */
+ int nRef; /* Number of open cursors */
+ char *zErrMsg; /* Error message from sqlite3_mprintf() */
+ /* Virtual table implementations will typically add additional fields */
+};
+
+/*
+** CAPI3REF: Virtual Table Cursor Object
+** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
+**
+** Every [virtual table module] implementation uses a subclass of the
+** following structure to describe cursors that point into the
+** [virtual table] and are used
+** to loop through the virtual table. Cursors are created using the
+** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
+** by the [sqlite3_module.xClose | xClose] method. Cursors are used
+** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
+** of the module. Each module implementation will define
+** the content of a cursor structure to suit its own needs.
+**
+** This superclass exists in order to define fields of the cursor that
+** are common to all implementations.
+*/
+struct sqlite3_vtab_cursor {
+ sqlite3_vtab *pVtab; /* Virtual table of this cursor */
+ /* Virtual table implementations will typically add additional fields */
+};
+
+/*
+** CAPI3REF: Declare The Schema Of A Virtual Table
+**
+** ^The [xCreate] and [xConnect] methods of a
+** [virtual table module] call this interface
+** to declare the format (the names and datatypes of the columns) of
+** the virtual tables they implement.
+*/
+SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
+
+/*
+** CAPI3REF: Overload A Function For A Virtual Table
+** METHOD: sqlite3
+**
+** ^(Virtual tables can provide alternative implementations of functions
+** using the [xFindFunction] method of the [virtual table module].
+** But global versions of those functions
+** must exist in order to be overloaded.)^
+**
+** ^(This API makes sure a global version of a function with a particular
+** name and number of parameters exists. If no such function exists
+** before this API is called, a new function is created.)^ ^The implementation
+** of the new function always causes an exception to be thrown. So
+** the new function is not good for anything by itself. Its only
+** purpose is to be a placeholder function that can be overloaded
+** by a [virtual table].
+*/
+SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
+
+/*
+** The interface to the virtual-table mechanism defined above (back up
+** to a comment remarkably similar to this one) is currently considered
+** to be experimental. The interface might change in incompatible ways.
+** If this is a problem for you, do not use the interface at this time.
+**
+** When the virtual-table mechanism stabilizes, we will declare the
+** interface fixed, support it indefinitely, and remove this comment.
+*/
+
+/*
+** CAPI3REF: A Handle To An Open BLOB
+** KEYWORDS: {BLOB handle} {BLOB handles}
+**
+** An instance of this object represents an open BLOB on which
+** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
+** ^Objects of this type are created by [sqlite3_blob_open()]
+** and destroyed by [sqlite3_blob_close()].
+** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
+** can be used to read or write small subsections of the BLOB.
+** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
+*/
+typedef struct sqlite3_blob sqlite3_blob;
+
+/*
+** CAPI3REF: Open A BLOB For Incremental I/O
+** METHOD: sqlite3
+** CONSTRUCTOR: sqlite3_blob
+**
+** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
+** in row iRow, column zColumn, table zTable in database zDb;
+** in other words, the same BLOB that would be selected by:
+**
+** <pre>
+** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
+** </pre>)^
+**
+** ^(Parameter zDb is not the filename that contains the database, but
+** rather the symbolic name of the database. For attached databases, this is
+** the name that appears after the AS keyword in the [ATTACH] statement.
+** For the main database file, the database name is "main". For TEMP
+** tables, the database name is "temp".)^
+**
+** ^If the flags parameter is non-zero, then the BLOB is opened for read
+** and write access. ^If the flags parameter is zero, the BLOB is opened for
+** read-only access.
+**
+** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
+** in *ppBlob. Otherwise an [error code] is returned and, unless the error
+** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
+** the API is not misused, it is always safe to call [sqlite3_blob_close()]
+** on *ppBlob after this function it returns.
+**
+** This function fails with SQLITE_ERROR if any of the following are true:
+** <ul>
+** <li> ^(Database zDb does not exist)^,
+** <li> ^(Table zTable does not exist within database zDb)^,
+** <li> ^(Table zTable is a WITHOUT ROWID table)^,
+** <li> ^(Column zColumn does not exist)^,
+** <li> ^(Row iRow is not present in the table)^,
+** <li> ^(The specified column of row iRow contains a value that is not
+** a TEXT or BLOB value)^,
+** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
+** constraint and the blob is being opened for read/write access)^,
+** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
+** column zColumn is part of a [child key] definition and the blob is
+** being opened for read/write access)^.
+** </ul>
+**
+** ^Unless it returns SQLITE_MISUSE, this function sets the
+** [database connection] error code and message accessible via
+** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
+**
+** A BLOB referenced by sqlite3_blob_open() may be read using the
+** [sqlite3_blob_read()] interface and modified by using
+** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
+** different row of the same table using the [sqlite3_blob_reopen()]
+** interface. However, the column, table, or database of a [BLOB handle]
+** cannot be changed after the [BLOB handle] is opened.
+**
+** ^(If the row that a BLOB handle points to is modified by an
+** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
+** then the BLOB handle is marked as "expired".
+** This is true if any column of the row is changed, even a column
+** other than the one the BLOB handle is open on.)^
+** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
+** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
+** ^(Changes written into a BLOB prior to the BLOB expiring are not
+** rolled back by the expiration of the BLOB. Such changes will eventually
+** commit if the transaction continues to completion.)^
+**
+** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
+** the opened blob. ^The size of a blob may not be changed by this
+** interface. Use the [UPDATE] SQL command to change the size of a
+** blob.
+**
+** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
+** and the built-in [zeroblob] SQL function may be used to create a
+** zero-filled blob to read or write using the incremental-blob interface.
+**
+** To avoid a resource leak, every open [BLOB handle] should eventually
+** be released by a call to [sqlite3_blob_close()].
+**
+** See also: [sqlite3_blob_close()],
+** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
+** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
+*/
+SQLITE_API int sqlite3_blob_open(
+ sqlite3*,
+ const char *zDb,
+ const char *zTable,
+ const char *zColumn,
+ sqlite3_int64 iRow,
+ int flags,
+ sqlite3_blob **ppBlob
+);
+
+/*
+** CAPI3REF: Move a BLOB Handle to a New Row
+** METHOD: sqlite3_blob
+**
+** ^This function is used to move an existing [BLOB handle] so that it points
+** to a different row of the same database table. ^The new row is identified
+** by the rowid value passed as the second argument. Only the row can be
+** changed. ^The database, table and column on which the blob handle is open
+** remain the same. Moving an existing [BLOB handle] to a new row is
+** faster than closing the existing handle and opening a new one.
+**
+** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
+** it must exist and there must be either a blob or text value stored in
+** the nominated column.)^ ^If the new row is not present in the table, or if
+** it does not contain a blob or text value, or if another error occurs, an
+** SQLite error code is returned and the blob handle is considered aborted.
+** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
+** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
+** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
+** always returns zero.
+**
+** ^This function sets the database handle error code and message.
+*/
+SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
+
+/*
+** CAPI3REF: Close A BLOB Handle
+** DESTRUCTOR: sqlite3_blob
+**
+** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
+** unconditionally. Even if this routine returns an error code, the
+** handle is still closed.)^
+**
+** ^If the blob handle being closed was opened for read-write access, and if
+** the database is in auto-commit mode and there are no other open read-write
+** blob handles or active write statements, the current transaction is
+** committed. ^If an error occurs while committing the transaction, an error
+** code is returned and the transaction rolled back.
+**
+** Calling this function with an argument that is not a NULL pointer or an
+** open blob handle results in undefined behaviour. ^Calling this routine
+** with a null pointer (such as would be returned by a failed call to
+** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
+** is passed a valid open blob handle, the values returned by the
+** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
+*/
+SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
+
+/*
+** CAPI3REF: Return The Size Of An Open BLOB
+** METHOD: sqlite3_blob
+**
+** ^Returns the size in bytes of the BLOB accessible via the
+** successfully opened [BLOB handle] in its only argument. ^The
+** incremental blob I/O routines can only read or overwriting existing
+** blob content; they cannot change the size of a blob.
+**
+** This routine only works on a [BLOB handle] which has been created
+** by a prior successful call to [sqlite3_blob_open()] and which has not
+** been closed by [sqlite3_blob_close()]. Passing any other pointer in
+** to this routine results in undefined and probably undesirable behavior.
+*/
+SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
+
+/*
+** CAPI3REF: Read Data From A BLOB Incrementally
+** METHOD: sqlite3_blob
+**
+** ^(This function is used to read data from an open [BLOB handle] into a
+** caller-supplied buffer. N bytes of data are copied into buffer Z
+** from the open BLOB, starting at offset iOffset.)^
+**
+** ^If offset iOffset is less than N bytes from the end of the BLOB,
+** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
+** less than zero, [SQLITE_ERROR] is returned and no data is read.
+** ^The size of the blob (and hence the maximum value of N+iOffset)
+** can be determined using the [sqlite3_blob_bytes()] interface.
+**
+** ^An attempt to read from an expired [BLOB handle] fails with an
+** error code of [SQLITE_ABORT].
+**
+** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
+** Otherwise, an [error code] or an [extended error code] is returned.)^
+**
+** This routine only works on a [BLOB handle] which has been created
+** by a prior successful call to [sqlite3_blob_open()] and which has not
+** been closed by [sqlite3_blob_close()]. Passing any other pointer in
+** to this routine results in undefined and probably undesirable behavior.
+**
+** See also: [sqlite3_blob_write()].
+*/
+SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
+
+/*
+** CAPI3REF: Write Data Into A BLOB Incrementally
+** METHOD: sqlite3_blob
+**
+** ^(This function is used to write data into an open [BLOB handle] from a
+** caller-supplied buffer. N bytes of data are copied from the buffer Z
+** into the open BLOB, starting at offset iOffset.)^
+**
+** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
+** Otherwise, an [error code] or an [extended error code] is returned.)^
+** ^Unless SQLITE_MISUSE is returned, this function sets the
+** [database connection] error code and message accessible via
+** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
+**
+** ^If the [BLOB handle] passed as the first argument was not opened for
+** writing (the flags parameter to [sqlite3_blob_open()] was zero),
+** this function returns [SQLITE_READONLY].
+**
+** This function may only modify the contents of the BLOB; it is
+** not possible to increase the size of a BLOB using this API.
+** ^If offset iOffset is less than N bytes from the end of the BLOB,
+** [SQLITE_ERROR] is returned and no data is written. The size of the
+** BLOB (and hence the maximum value of N+iOffset) can be determined
+** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
+** than zero [SQLITE_ERROR] is returned and no data is written.
+**
+** ^An attempt to write to an expired [BLOB handle] fails with an
+** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
+** before the [BLOB handle] expired are not rolled back by the
+** expiration of the handle, though of course those changes might
+** have been overwritten by the statement that expired the BLOB handle
+** or by other independent statements.
+**
+** This routine only works on a [BLOB handle] which has been created
+** by a prior successful call to [sqlite3_blob_open()] and which has not
+** been closed by [sqlite3_blob_close()]. Passing any other pointer in
+** to this routine results in undefined and probably undesirable behavior.
+**
+** See also: [sqlite3_blob_read()].
+*/
+SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
+
+/*
+** CAPI3REF: Virtual File System Objects
+**
+** A virtual filesystem (VFS) is an [sqlite3_vfs] object
+** that SQLite uses to interact
+** with the underlying operating system. Most SQLite builds come with a
+** single default VFS that is appropriate for the host computer.
+** New VFSes can be registered and existing VFSes can be unregistered.
+** The following interfaces are provided.
+**
+** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
+** ^Names are case sensitive.
+** ^Names are zero-terminated UTF-8 strings.
+** ^If there is no match, a NULL pointer is returned.
+** ^If zVfsName is NULL then the default VFS is returned.
+**
+** ^New VFSes are registered with sqlite3_vfs_register().
+** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
+** ^The same VFS can be registered multiple times without injury.
+** ^To make an existing VFS into the default VFS, register it again
+** with the makeDflt flag set. If two different VFSes with the
+** same name are registered, the behavior is undefined. If a
+** VFS is registered with a name that is NULL or an empty string,
+** then the behavior is undefined.
+**
+** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
+** ^(If the default VFS is unregistered, another VFS is chosen as
+** the default. The choice for the new VFS is arbitrary.)^
+*/
+SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
+SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
+SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
+
+/*
+** CAPI3REF: Mutexes
+**
+** The SQLite core uses these routines for thread
+** synchronization. Though they are intended for internal
+** use by SQLite, code that links against SQLite is
+** permitted to use any of these routines.
+**
+** The SQLite source code contains multiple implementations
+** of these mutex routines. An appropriate implementation
+** is selected automatically at compile-time. The following
+** implementations are available in the SQLite core:
+**
+** <ul>
+** <li> SQLITE_MUTEX_PTHREADS
+** <li> SQLITE_MUTEX_W32
+** <li> SQLITE_MUTEX_NOOP
+** </ul>
+**
+** The SQLITE_MUTEX_NOOP implementation is a set of routines
+** that does no real locking and is appropriate for use in
+** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
+** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
+** and Windows.
+**
+** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
+** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
+** implementation is included with the library. In this case the
+** application must supply a custom mutex implementation using the
+** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
+** before calling sqlite3_initialize() or any other public sqlite3_
+** function that calls sqlite3_initialize().
+**
+** ^The sqlite3_mutex_alloc() routine allocates a new
+** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
+** routine returns NULL if it is unable to allocate the requested
+** mutex. The argument to sqlite3_mutex_alloc() must one of these
+** integer constants:
+**
+** <ul>
+** <li> SQLITE_MUTEX_FAST
+** <li> SQLITE_MUTEX_RECURSIVE
+** <li> SQLITE_MUTEX_STATIC_MAIN
+** <li> SQLITE_MUTEX_STATIC_MEM
+** <li> SQLITE_MUTEX_STATIC_OPEN
+** <li> SQLITE_MUTEX_STATIC_PRNG
+** <li> SQLITE_MUTEX_STATIC_LRU
+** <li> SQLITE_MUTEX_STATIC_PMEM
+** <li> SQLITE_MUTEX_STATIC_APP1
+** <li> SQLITE_MUTEX_STATIC_APP2
+** <li> SQLITE_MUTEX_STATIC_APP3
+** <li> SQLITE_MUTEX_STATIC_VFS1
+** <li> SQLITE_MUTEX_STATIC_VFS2
+** <li> SQLITE_MUTEX_STATIC_VFS3
+** </ul>
+**
+** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
+** cause sqlite3_mutex_alloc() to create
+** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
+** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
+** The mutex implementation does not need to make a distinction
+** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
+** not want to. SQLite will only request a recursive mutex in
+** cases where it really needs one. If a faster non-recursive mutex
+** implementation is available on the host platform, the mutex subsystem
+** might return such a mutex in response to SQLITE_MUTEX_FAST.
+**
+** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
+** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
+** a pointer to a static preexisting mutex. ^Nine static mutexes are
+** used by the current version of SQLite. Future versions of SQLite
+** may add additional static mutexes. Static mutexes are for internal
+** use by SQLite only. Applications that use SQLite mutexes should
+** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
+** SQLITE_MUTEX_RECURSIVE.
+**
+** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
+** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
+** returns a different mutex on every call. ^For the static
+** mutex types, the same mutex is returned on every call that has
+** the same type number.
+**
+** ^The sqlite3_mutex_free() routine deallocates a previously
+** allocated dynamic mutex. Attempting to deallocate a static
+** mutex results in undefined behavior.
+**
+** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
+** to enter a mutex. ^If another thread is already within the mutex,
+** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
+** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
+** upon successful entry. ^(Mutexes created using
+** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
+** In such cases, the
+** mutex must be exited an equal number of times before another thread
+** can enter.)^ If the same thread tries to enter any mutex other
+** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
+**
+** ^(Some systems (for example, Windows 95) do not support the operation
+** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
+** will always return SQLITE_BUSY. The SQLite core only ever uses
+** sqlite3_mutex_try() as an optimization so this is acceptable
+** behavior.)^
+**
+** ^The sqlite3_mutex_leave() routine exits a mutex that was
+** previously entered by the same thread. The behavior
+** is undefined if the mutex is not currently entered by the
+** calling thread or is not currently allocated.
+**
+** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
+** sqlite3_mutex_leave() is a NULL pointer, then all three routines
+** behave as no-ops.
+**
+** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
+*/
+SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
+SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
+SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
+SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
+SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
+
+/*
+** CAPI3REF: Mutex Methods Object
+**
+** An instance of this structure defines the low-level routines
+** used to allocate and use mutexes.
+**
+** Usually, the default mutex implementations provided by SQLite are
+** sufficient, however the application has the option of substituting a custom
+** implementation for specialized deployments or systems for which SQLite
+** does not provide a suitable implementation. In this case, the application
+** creates and populates an instance of this structure to pass
+** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
+** Additionally, an instance of this structure can be used as an
+** output variable when querying the system for the current mutex
+** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
+**
+** ^The xMutexInit method defined by this structure is invoked as
+** part of system initialization by the sqlite3_initialize() function.
+** ^The xMutexInit routine is called by SQLite exactly once for each
+** effective call to [sqlite3_initialize()].
+**
+** ^The xMutexEnd method defined by this structure is invoked as
+** part of system shutdown by the sqlite3_shutdown() function. The
+** implementation of this method is expected to release all outstanding
+** resources obtained by the mutex methods implementation, especially
+** those obtained by the xMutexInit method. ^The xMutexEnd()
+** interface is invoked exactly once for each call to [sqlite3_shutdown()].
+**
+** ^(The remaining seven methods defined by this structure (xMutexAlloc,
+** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
+** xMutexNotheld) implement the following interfaces (respectively):
+**
+** <ul>
+** <li> [sqlite3_mutex_alloc()] </li>
+** <li> [sqlite3_mutex_free()] </li>
+** <li> [sqlite3_mutex_enter()] </li>
+** <li> [sqlite3_mutex_try()] </li>
+** <li> [sqlite3_mutex_leave()] </li>
+** <li> [sqlite3_mutex_held()] </li>
+** <li> [sqlite3_mutex_notheld()] </li>
+** </ul>)^
+**
+** The only difference is that the public sqlite3_XXX functions enumerated
+** above silently ignore any invocations that pass a NULL pointer instead
+** of a valid mutex handle. The implementations of the methods defined
+** by this structure are not required to handle this case. The results
+** of passing a NULL pointer instead of a valid mutex handle are undefined
+** (i.e. it is acceptable to provide an implementation that segfaults if
+** it is passed a NULL pointer).
+**
+** The xMutexInit() method must be threadsafe. It must be harmless to
+** invoke xMutexInit() multiple times within the same process and without
+** intervening calls to xMutexEnd(). Second and subsequent calls to
+** xMutexInit() must be no-ops.
+**
+** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
+** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
+** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
+** memory allocation for a fast or recursive mutex.
+**
+** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
+** called, but only if the prior call to xMutexInit returned SQLITE_OK.
+** If xMutexInit fails in any way, it is expected to clean up after itself
+** prior to returning.
+*/
+typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
+struct sqlite3_mutex_methods {
+ int (*xMutexInit)(void);
+ int (*xMutexEnd)(void);
+ sqlite3_mutex *(*xMutexAlloc)(int);
+ void (*xMutexFree)(sqlite3_mutex *);
+ void (*xMutexEnter)(sqlite3_mutex *);
+ int (*xMutexTry)(sqlite3_mutex *);
+ void (*xMutexLeave)(sqlite3_mutex *);
+ int (*xMutexHeld)(sqlite3_mutex *);
+ int (*xMutexNotheld)(sqlite3_mutex *);
+};
+
+/*
+** CAPI3REF: Mutex Verification Routines
+**
+** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
+** are intended for use inside assert() statements. The SQLite core
+** never uses these routines except inside an assert() and applications
+** are advised to follow the lead of the core. The SQLite core only
+** provides implementations for these routines when it is compiled
+** with the SQLITE_DEBUG flag. External mutex implementations
+** are only required to provide these routines if SQLITE_DEBUG is
+** defined and if NDEBUG is not defined.
+**
+** These routines should return true if the mutex in their argument
+** is held or not held, respectively, by the calling thread.
+**
+** The implementation is not required to provide versions of these
+** routines that actually work. If the implementation does not provide working
+** versions of these routines, it should at least provide stubs that always
+** return true so that one does not get spurious assertion failures.
+**
+** If the argument to sqlite3_mutex_held() is a NULL pointer then
+** the routine should return 1. This seems counter-intuitive since
+** clearly the mutex cannot be held if it does not exist. But
+** the reason the mutex does not exist is because the build is not
+** using mutexes. And we do not want the assert() containing the
+** call to sqlite3_mutex_held() to fail, so a non-zero return is
+** the appropriate thing to do. The sqlite3_mutex_notheld()
+** interface should also return 1 when given a NULL pointer.
+*/
+#ifndef NDEBUG
+SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
+SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
+#endif
+
+/*
+** CAPI3REF: Mutex Types
+**
+** The [sqlite3_mutex_alloc()] interface takes a single argument
+** which is one of these integer constants.
+**
+** The set of static mutexes may change from one SQLite release to the
+** next. Applications that override the built-in mutex logic must be
+** prepared to accommodate additional static mutexes.
+*/
+#define SQLITE_MUTEX_FAST 0
+#define SQLITE_MUTEX_RECURSIVE 1
+#define SQLITE_MUTEX_STATIC_MAIN 2
+#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
+#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
+#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
+#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
+#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
+#define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
+#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
+#define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
+#define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
+#define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
+#define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
+#define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
+#define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
+
+/* Legacy compatibility: */
+#define SQLITE_MUTEX_STATIC_MASTER 2
+
+
+/*
+** CAPI3REF: Retrieve the mutex for a database connection
+** METHOD: sqlite3
+**
+** ^This interface returns a pointer the [sqlite3_mutex] object that
+** serializes access to the [database connection] given in the argument
+** when the [threading mode] is Serialized.
+** ^If the [threading mode] is Single-thread or Multi-thread then this
+** routine returns a NULL pointer.
+*/
+SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
+
+/*
+** CAPI3REF: Low-Level Control Of Database Files
+** METHOD: sqlite3
+** KEYWORDS: {file control}
+**
+** ^The [sqlite3_file_control()] interface makes a direct call to the
+** xFileControl method for the [sqlite3_io_methods] object associated
+** with a particular database identified by the second argument. ^The
+** name of the database is "main" for the main database or "temp" for the
+** TEMP database, or the name that appears after the AS keyword for
+** databases that are added using the [ATTACH] SQL command.
+** ^A NULL pointer can be used in place of "main" to refer to the
+** main database file.
+** ^The third and fourth parameters to this routine
+** are passed directly through to the second and third parameters of
+** the xFileControl method. ^The return value of the xFileControl
+** method becomes the return value of this routine.
+**
+** A few opcodes for [sqlite3_file_control()] are handled directly
+** by the SQLite core and never invoke the
+** sqlite3_io_methods.xFileControl method.
+** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
+** a pointer to the underlying [sqlite3_file] object to be written into
+** the space pointed to by the 4th parameter. The
+** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns
+** the [sqlite3_file] object associated with the journal file instead of
+** the main database. The [SQLITE_FCNTL_VFS_POINTER] opcode returns
+** a pointer to the underlying [sqlite3_vfs] object for the file.
+** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter
+** from the pager.
+**
+** ^If the second parameter (zDbName) does not match the name of any
+** open database file, then SQLITE_ERROR is returned. ^This error
+** code is not remembered and will not be recalled by [sqlite3_errcode()]
+** or [sqlite3_errmsg()]. The underlying xFileControl method might
+** also return SQLITE_ERROR. There is no way to distinguish between
+** an incorrect zDbName and an SQLITE_ERROR return from the underlying
+** xFileControl method.
+**
+** See also: [file control opcodes]
+*/
+SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
+
+/*
+** CAPI3REF: Testing Interface
+**
+** ^The sqlite3_test_control() interface is used to read out internal
+** state of SQLite and to inject faults into SQLite for testing
+** purposes. ^The first parameter is an operation code that determines
+** the number, meaning, and operation of all subsequent parameters.
+**
+** This interface is not for use by applications. It exists solely
+** for verifying the correct operation of the SQLite library. Depending
+** on how the SQLite library is compiled, this interface might not exist.
+**
+** The details of the operation codes, their meanings, the parameters
+** they take, and what they do are all subject to change without notice.
+** Unlike most of the SQLite API, this function is not guaranteed to
+** operate consistently from one release to the next.
+*/
+SQLITE_API int sqlite3_test_control(int op, ...);
+
+/*
+** CAPI3REF: Testing Interface Operation Codes
+**
+** These constants are the valid operation code parameters used
+** as the first argument to [sqlite3_test_control()].
+**
+** These parameters and their meanings are subject to change
+** without notice. These values are for testing purposes only.
+** Applications should not use any of these parameters or the
+** [sqlite3_test_control()] interface.
+*/
+#define SQLITE_TESTCTRL_FIRST 5
+#define SQLITE_TESTCTRL_PRNG_SAVE 5
+#define SQLITE_TESTCTRL_PRNG_RESTORE 6
+#define SQLITE_TESTCTRL_PRNG_RESET 7 /* NOT USED */
+#define SQLITE_TESTCTRL_SEEK_COUNT 7
+#define SQLITE_TESTCTRL_BITVEC_TEST 8
+#define SQLITE_TESTCTRL_FAULT_INSTALL 9
+#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
+#define SQLITE_TESTCTRL_PENDING_BYTE 11
+#define SQLITE_TESTCTRL_ASSERT 12
+#define SQLITE_TESTCTRL_ALWAYS 13
+#define SQLITE_TESTCTRL_RESERVE 14 /* NOT USED */
+#define SQLITE_TESTCTRL_OPTIMIZATIONS 15
+#define SQLITE_TESTCTRL_ISKEYWORD 16 /* NOT USED */
+#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */
+#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 17
+#define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
+#define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
+#define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
+#define SQLITE_TESTCTRL_NEVER_CORRUPT 20
+#define SQLITE_TESTCTRL_VDBE_COVERAGE 21
+#define SQLITE_TESTCTRL_BYTEORDER 22
+#define SQLITE_TESTCTRL_ISINIT 23
+#define SQLITE_TESTCTRL_SORTER_MMAP 24
+#define SQLITE_TESTCTRL_IMPOSTER 25
+#define SQLITE_TESTCTRL_PARSER_COVERAGE 26
+#define SQLITE_TESTCTRL_RESULT_INTREAL 27
+#define SQLITE_TESTCTRL_PRNG_SEED 28
+#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS 29
+#define SQLITE_TESTCTRL_LAST 29 /* Largest TESTCTRL */
+
+/*
+** CAPI3REF: SQL Keyword Checking
+**
+** These routines provide access to the set of SQL language keywords
+** recognized by SQLite. Applications can uses these routines to determine
+** whether or not a specific identifier needs to be escaped (for example,
+** by enclosing in double-quotes) so as not to confuse the parser.
+**
+** The sqlite3_keyword_count() interface returns the number of distinct
+** keywords understood by SQLite.
+**
+** The sqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and
+** makes *Z point to that keyword expressed as UTF8 and writes the number
+** of bytes in the keyword into *L. The string that *Z points to is not
+** zero-terminated. The sqlite3_keyword_name(N,Z,L) routine returns
+** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z
+** or L are NULL or invalid pointers then calls to
+** sqlite3_keyword_name(N,Z,L) result in undefined behavior.
+**
+** The sqlite3_keyword_check(Z,L) interface checks to see whether or not
+** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
+** if it is and zero if not.
+**
+** The parser used by SQLite is forgiving. It is often possible to use
+** a keyword as an identifier as long as such use does not result in a
+** parsing ambiguity. For example, the statement
+** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
+** creates a new table named "BEGIN" with three columns named
+** "REPLACE", "PRAGMA", and "END". Nevertheless, best practice is to avoid
+** using keywords as identifiers. Common techniques used to avoid keyword
+** name collisions include:
+** <ul>
+** <li> Put all identifier names inside double-quotes. This is the official
+** SQL way to escape identifier names.
+** <li> Put identifier names inside &#91;...&#93;. This is not standard SQL,
+** but it is what SQL Server does and so lots of programmers use this
+** technique.
+** <li> Begin every identifier with the letter "Z" as no SQL keywords start
+** with "Z".
+** <li> Include a digit somewhere in every identifier name.
+** </ul>
+**
+** Note that the number of keywords understood by SQLite can depend on
+** compile-time options. For example, "VACUUM" is not a keyword if
+** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also,
+** new keywords may be added to future releases of SQLite.
+*/
+SQLITE_API int sqlite3_keyword_count(void);
+SQLITE_API int sqlite3_keyword_name(int,const char**,int*);
+SQLITE_API int sqlite3_keyword_check(const char*,int);
+
+/*
+** CAPI3REF: Dynamic String Object
+** KEYWORDS: {dynamic string}
+**
+** An instance of the sqlite3_str object contains a dynamically-sized
+** string under construction.
+**
+** The lifecycle of an sqlite3_str object is as follows:
+** <ol>
+** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
+** <li> ^Text is appended to the sqlite3_str object using various
+** methods, such as [sqlite3_str_appendf()].
+** <li> ^The sqlite3_str object is destroyed and the string it created
+** is returned using the [sqlite3_str_finish()] interface.
+** </ol>
+*/
+typedef struct sqlite3_str sqlite3_str;
+
+/*
+** CAPI3REF: Create A New Dynamic String Object
+** CONSTRUCTOR: sqlite3_str
+**
+** ^The [sqlite3_str_new(D)] interface allocates and initializes
+** a new [sqlite3_str] object. To avoid memory leaks, the object returned by
+** [sqlite3_str_new()] must be freed by a subsequent call to
+** [sqlite3_str_finish(X)].
+**
+** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
+** valid [sqlite3_str] object, though in the event of an out-of-memory
+** error the returned object might be a special singleton that will
+** silently reject new text, always return SQLITE_NOMEM from
+** [sqlite3_str_errcode()], always return 0 for
+** [sqlite3_str_length()], and always return NULL from
+** [sqlite3_str_finish(X)]. It is always safe to use the value
+** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
+** to any of the other [sqlite3_str] methods.
+**
+** The D parameter to [sqlite3_str_new(D)] may be NULL. If the
+** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum
+** length of the string contained in the [sqlite3_str] object will be
+** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead
+** of [SQLITE_MAX_LENGTH].
+*/
+SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);
+
+/*
+** CAPI3REF: Finalize A Dynamic String
+** DESTRUCTOR: sqlite3_str
+**
+** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X
+** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]
+** that contains the constructed string. The calling application should
+** pass the returned value to [sqlite3_free()] to avoid a memory leak.
+** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any
+** errors were encountered during construction of the string. ^The
+** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the
+** string in [sqlite3_str] object X is zero bytes long.
+*/
+SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
+
+/*
+** CAPI3REF: Add Content To A Dynamic String
+** METHOD: sqlite3_str
+**
+** These interfaces add content to an sqlite3_str object previously obtained
+** from [sqlite3_str_new()].
+**
+** ^The [sqlite3_str_appendf(X,F,...)] and
+** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
+** functionality of SQLite to append formatted text onto the end of
+** [sqlite3_str] object X.
+**
+** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
+** onto the end of the [sqlite3_str] object X. N must be non-negative.
+** S must contain at least N non-zero bytes of content. To append a
+** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
+** method instead.
+**
+** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of
+** zero-terminated string S onto the end of [sqlite3_str] object X.
+**
+** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the
+** single-byte character C onto the end of [sqlite3_str] object X.
+** ^This method can be used, for example, to add whitespace indentation.
+**
+** ^The [sqlite3_str_reset(X)] method resets the string under construction
+** inside [sqlite3_str] object X back to zero bytes in length.
+**
+** These methods do not return a result code. ^If an error occurs, that fact
+** is recorded in the [sqlite3_str] object and can be recovered by a
+** subsequent call to [sqlite3_str_errcode(X)].
+*/
+SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);
+SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);
+SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);
+SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);
+SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);
+SQLITE_API void sqlite3_str_reset(sqlite3_str*);
+
+/*
+** CAPI3REF: Status Of A Dynamic String
+** METHOD: sqlite3_str
+**
+** These interfaces return the current status of an [sqlite3_str] object.
+**
+** ^If any prior errors have occurred while constructing the dynamic string
+** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return
+** an appropriate error code. ^The [sqlite3_str_errcode(X)] method returns
+** [SQLITE_NOMEM] following any out-of-memory error, or
+** [SQLITE_TOOBIG] if the size of the dynamic string exceeds
+** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.
+**
+** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,
+** of the dynamic string under construction in [sqlite3_str] object X.
+** ^The length returned by [sqlite3_str_length(X)] does not include the
+** zero-termination byte.
+**
+** ^The [sqlite3_str_value(X)] method returns a pointer to the current
+** content of the dynamic string under construction in X. The value
+** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X
+** and might be freed or altered by any subsequent method on the same
+** [sqlite3_str] object. Applications must not used the pointer returned
+** [sqlite3_str_value(X)] after any subsequent method call on the same
+** object. ^Applications may change the content of the string returned
+** by [sqlite3_str_value(X)] as long as they do not write into any bytes
+** outside the range of 0 to [sqlite3_str_length(X)] and do not read or
+** write any byte after any subsequent sqlite3_str method call.
+*/
+SQLITE_API int sqlite3_str_errcode(sqlite3_str*);
+SQLITE_API int sqlite3_str_length(sqlite3_str*);
+SQLITE_API char *sqlite3_str_value(sqlite3_str*);
+
+/*
+** CAPI3REF: SQLite Runtime Status
+**
+** ^These interfaces are used to retrieve runtime status information
+** about the performance of SQLite, and optionally to reset various
+** highwater marks. ^The first argument is an integer code for
+** the specific parameter to measure. ^(Recognized integer codes
+** are of the form [status parameters | SQLITE_STATUS_...].)^
+** ^The current value of the parameter is returned into *pCurrent.
+** ^The highest recorded value is returned in *pHighwater. ^If the
+** resetFlag is true, then the highest record value is reset after
+** *pHighwater is written. ^(Some parameters do not record the highest
+** value. For those parameters
+** nothing is written into *pHighwater and the resetFlag is ignored.)^
+** ^(Other parameters record only the highwater mark and not the current
+** value. For these latter parameters nothing is written into *pCurrent.)^
+**
+** ^The sqlite3_status() and sqlite3_status64() routines return
+** SQLITE_OK on success and a non-zero [error code] on failure.
+**
+** If either the current value or the highwater mark is too large to
+** be represented by a 32-bit integer, then the values returned by
+** sqlite3_status() are undefined.
+**
+** See also: [sqlite3_db_status()]
+*/
+SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
+SQLITE_API int sqlite3_status64(
+ int op,
+ sqlite3_int64 *pCurrent,
+ sqlite3_int64 *pHighwater,
+ int resetFlag
+);
+
+
+/*
+** CAPI3REF: Status Parameters
+** KEYWORDS: {status parameters}
+**
+** These integer constants designate various run-time status parameters
+** that can be returned by [sqlite3_status()].
+**
+** <dl>
+** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
+** <dd>This parameter is the current amount of memory checked out
+** using [sqlite3_malloc()], either directly or indirectly. The
+** figure includes calls made to [sqlite3_malloc()] by the application
+** and internal memory usage by the SQLite library. Auxiliary page-cache
+** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
+** this parameter. The amount returned is the sum of the allocation
+** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
+**
+** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
+** <dd>This parameter records the largest memory allocation request
+** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
+** internal equivalents). Only the value returned in the
+** *pHighwater parameter to [sqlite3_status()] is of interest.
+** The value written into the *pCurrent parameter is undefined.</dd>)^
+**
+** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
+** <dd>This parameter records the number of separate memory allocations
+** currently checked out.</dd>)^
+**
+** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
+** <dd>This parameter returns the number of pages used out of the
+** [pagecache memory allocator] that was configured using
+** [SQLITE_CONFIG_PAGECACHE]. The
+** value returned is in pages, not in bytes.</dd>)^
+**
+** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
+** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
+** <dd>This parameter returns the number of bytes of page cache
+** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
+** buffer and where forced to overflow to [sqlite3_malloc()]. The
+** returned value includes allocations that overflowed because they
+** where too large (they were larger than the "sz" parameter to
+** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
+** no space was left in the page cache.</dd>)^
+**
+** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
+** <dd>This parameter records the largest memory allocation request
+** handed to the [pagecache memory allocator]. Only the value returned in the
+** *pHighwater parameter to [sqlite3_status()] is of interest.
+** The value written into the *pCurrent parameter is undefined.</dd>)^
+**
+** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
+** <dd>No longer used.</dd>
+**
+** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
+** <dd>No longer used.</dd>
+**
+** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
+** <dd>No longer used.</dd>
+**
+** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
+** <dd>The *pHighwater parameter records the deepest parser stack.
+** The *pCurrent value is undefined. The *pHighwater value is only
+** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
+** </dl>
+**
+** New status parameters may be added from time to time.
+*/
+#define SQLITE_STATUS_MEMORY_USED 0
+#define SQLITE_STATUS_PAGECACHE_USED 1
+#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
+#define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */
+#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */
+#define SQLITE_STATUS_MALLOC_SIZE 5
+#define SQLITE_STATUS_PARSER_STACK 6
+#define SQLITE_STATUS_PAGECACHE_SIZE 7
+#define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */
+#define SQLITE_STATUS_MALLOC_COUNT 9
+
+/*
+** CAPI3REF: Database Connection Status
+** METHOD: sqlite3
+**
+** ^This interface is used to retrieve runtime status information
+** about a single [database connection]. ^The first argument is the
+** database connection object to be interrogated. ^The second argument
+** is an integer constant, taken from the set of
+** [SQLITE_DBSTATUS options], that
+** determines the parameter to interrogate. The set of
+** [SQLITE_DBSTATUS options] is likely
+** to grow in future releases of SQLite.
+**
+** ^The current value of the requested parameter is written into *pCur
+** and the highest instantaneous value is written into *pHiwtr. ^If
+** the resetFlg is true, then the highest instantaneous value is
+** reset back down to the current value.
+**
+** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
+** non-zero [error code] on failure.
+**
+** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
+*/
+SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
+
+/*
+** CAPI3REF: Status Parameters for database connections
+** KEYWORDS: {SQLITE_DBSTATUS options}
+**
+** These constants are the available integer "verbs" that can be passed as
+** the second argument to the [sqlite3_db_status()] interface.
+**
+** New verbs may be added in future releases of SQLite. Existing verbs
+** might be discontinued. Applications should check the return code from
+** [sqlite3_db_status()] to make sure that the call worked.
+** The [sqlite3_db_status()] interface will return a non-zero error code
+** if a discontinued or unsupported verb is invoked.
+**
+** <dl>
+** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
+** <dd>This parameter returns the number of lookaside memory slots currently
+** checked out.</dd>)^
+**
+** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
+** <dd>This parameter returns the number of malloc attempts that were
+** satisfied using lookaside memory. Only the high-water value is meaningful;
+** the current value is always zero.)^
+**
+** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
+** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
+** <dd>This parameter returns the number malloc attempts that might have
+** been satisfied using lookaside memory but failed due to the amount of
+** memory requested being larger than the lookaside slot size.
+** Only the high-water value is meaningful;
+** the current value is always zero.)^
+**
+** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
+** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
+** <dd>This parameter returns the number malloc attempts that might have
+** been satisfied using lookaside memory but failed due to all lookaside
+** memory already being in use.
+** Only the high-water value is meaningful;
+** the current value is always zero.)^
+**
+** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
+** <dd>This parameter returns the approximate number of bytes of heap
+** memory used by all pager caches associated with the database connection.)^
+** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
+**
+** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
+** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
+** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
+** pager cache is shared between two or more connections the bytes of heap
+** memory used by that pager cache is divided evenly between the attached
+** connections.)^ In other words, if none of the pager caches associated
+** with the database connection are shared, this request returns the same
+** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
+** shared, the value returned by this call will be smaller than that returned
+** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
+** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
+**
+** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
+** <dd>This parameter returns the approximate number of bytes of heap
+** memory used to store the schema for all databases associated
+** with the connection - main, temp, and any [ATTACH]-ed databases.)^
+** ^The full amount of memory used by the schemas is reported, even if the
+** schema memory is shared with other database connections due to
+** [shared cache mode] being enabled.
+** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
+**
+** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
+** <dd>This parameter returns the approximate number of bytes of heap
+** and lookaside memory used by all prepared statements associated with
+** the database connection.)^
+** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
+** </dd>
+**
+** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
+** <dd>This parameter returns the number of pager cache hits that have
+** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
+** is always 0.
+** </dd>
+**
+** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
+** <dd>This parameter returns the number of pager cache misses that have
+** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
+** is always 0.
+** </dd>
+**
+** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
+** <dd>This parameter returns the number of dirty cache entries that have
+** been written to disk. Specifically, the number of pages written to the
+** wal file in wal mode databases, or the number of pages written to the
+** database file in rollback mode databases. Any pages written as part of
+** transaction rollback or database recovery operations are not included.
+** If an IO or other error occurs while writing a page to disk, the effect
+** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
+** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
+** </dd>
+**
+** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>
+** <dd>This parameter returns the number of dirty cache entries that have
+** been written to disk in the middle of a transaction due to the page
+** cache overflowing. Transactions are more efficient if they are written
+** to disk all at once. When pages spill mid-transaction, that introduces
+** additional overhead. This parameter can be used help identify
+** inefficiencies that can be resolved by increasing the cache size.
+** </dd>
+**
+** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
+** <dd>This parameter returns zero for the current value if and only if
+** all foreign key constraints (deferred or immediate) have been
+** resolved.)^ ^The highwater mark is always 0.
+** </dd>
+** </dl>
+*/
+#define SQLITE_DBSTATUS_LOOKASIDE_USED 0
+#define SQLITE_DBSTATUS_CACHE_USED 1
+#define SQLITE_DBSTATUS_SCHEMA_USED 2
+#define SQLITE_DBSTATUS_STMT_USED 3
+#define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
+#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
+#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
+#define SQLITE_DBSTATUS_CACHE_HIT 7
+#define SQLITE_DBSTATUS_CACHE_MISS 8
+#define SQLITE_DBSTATUS_CACHE_WRITE 9
+#define SQLITE_DBSTATUS_DEFERRED_FKS 10
+#define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
+#define SQLITE_DBSTATUS_CACHE_SPILL 12
+#define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */
+
+
+/*
+** CAPI3REF: Prepared Statement Status
+** METHOD: sqlite3_stmt
+**
+** ^(Each prepared statement maintains various
+** [SQLITE_STMTSTATUS counters] that measure the number
+** of times it has performed specific operations.)^ These counters can
+** be used to monitor the performance characteristics of the prepared
+** statements. For example, if the number of table steps greatly exceeds
+** the number of table searches or result rows, that would tend to indicate
+** that the prepared statement is using a full table scan rather than
+** an index.
+**
+** ^(This interface is used to retrieve and reset counter values from
+** a [prepared statement]. The first argument is the prepared statement
+** object to be interrogated. The second argument
+** is an integer code for a specific [SQLITE_STMTSTATUS counter]
+** to be interrogated.)^
+** ^The current value of the requested counter is returned.
+** ^If the resetFlg is true, then the counter is reset to zero after this
+** interface call returns.
+**
+** See also: [sqlite3_status()] and [sqlite3_db_status()].
+*/
+SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
+
+/*
+** CAPI3REF: Status Parameters for prepared statements
+** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
+**
+** These preprocessor macros define integer codes that name counter
+** values associated with the [sqlite3_stmt_status()] interface.
+** The meanings of the various counters are as follows:
+**
+** <dl>
+** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
+** <dd>^This is the number of times that SQLite has stepped forward in
+** a table as part of a full table scan. Large numbers for this counter
+** may indicate opportunities for performance improvement through
+** careful use of indices.</dd>
+**
+** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
+** <dd>^This is the number of sort operations that have occurred.
+** A non-zero value in this counter may indicate an opportunity to
+** improvement performance through careful use of indices.</dd>
+**
+** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
+** <dd>^This is the number of rows inserted into transient indices that
+** were created automatically in order to help joins run faster.
+** A non-zero value in this counter may indicate an opportunity to
+** improvement performance by adding permanent indices that do not
+** need to be reinitialized each time the statement is run.</dd>
+**
+** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
+** <dd>^This is the number of virtual machine operations executed
+** by the prepared statement if that number is less than or equal
+** to 2147483647. The number of virtual machine operations can be
+** used as a proxy for the total work done by the prepared statement.
+** If the number of virtual machine operations exceeds 2147483647
+** then the value returned by this statement status code is undefined.
+**
+** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
+** <dd>^This is the number of times that the prepare statement has been
+** automatically regenerated due to schema changes or changes to
+** [bound parameters] that might affect the query plan.
+**
+** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
+** <dd>^This is the number of times that the prepared statement has
+** been run. A single "run" for the purposes of this counter is one
+** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
+** The counter is incremented on the first [sqlite3_step()] call of each
+** cycle.
+**
+** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
+** <dd>^This is the approximate number of bytes of heap memory
+** used to store the prepared statement. ^This value is not actually
+** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
+** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
+** </dd>
+** </dl>
+*/
+#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
+#define SQLITE_STMTSTATUS_SORT 2
+#define SQLITE_STMTSTATUS_AUTOINDEX 3
+#define SQLITE_STMTSTATUS_VM_STEP 4
+#define SQLITE_STMTSTATUS_REPREPARE 5
+#define SQLITE_STMTSTATUS_RUN 6
+#define SQLITE_STMTSTATUS_MEMUSED 99
+
+/*
+** CAPI3REF: Custom Page Cache Object
+**
+** The sqlite3_pcache type is opaque. It is implemented by
+** the pluggable module. The SQLite core has no knowledge of
+** its size or internal structure and never deals with the
+** sqlite3_pcache object except by holding and passing pointers
+** to the object.
+**
+** See [sqlite3_pcache_methods2] for additional information.
+*/
+typedef struct sqlite3_pcache sqlite3_pcache;
+
+/*
+** CAPI3REF: Custom Page Cache Object
+**
+** The sqlite3_pcache_page object represents a single page in the
+** page cache. The page cache will allocate instances of this
+** object. Various methods of the page cache use pointers to instances
+** of this object as parameters or as their return value.
+**
+** See [sqlite3_pcache_methods2] for additional information.
+*/
+typedef struct sqlite3_pcache_page sqlite3_pcache_page;
+struct sqlite3_pcache_page {
+ void *pBuf; /* The content of the page */
+ void *pExtra; /* Extra information associated with the page */
+};
+
+/*
+** CAPI3REF: Application Defined Page Cache.
+** KEYWORDS: {page cache}
+**
+** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
+** register an alternative page cache implementation by passing in an
+** instance of the sqlite3_pcache_methods2 structure.)^
+** In many applications, most of the heap memory allocated by
+** SQLite is used for the page cache.
+** By implementing a
+** custom page cache using this API, an application can better control
+** the amount of memory consumed by SQLite, the way in which
+** that memory is allocated and released, and the policies used to
+** determine exactly which parts of a database file are cached and for
+** how long.
+**
+** The alternative page cache mechanism is an
+** extreme measure that is only needed by the most demanding applications.
+** The built-in page cache is recommended for most uses.
+**
+** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
+** internal buffer by SQLite within the call to [sqlite3_config]. Hence
+** the application may discard the parameter after the call to
+** [sqlite3_config()] returns.)^
+**
+** [[the xInit() page cache method]]
+** ^(The xInit() method is called once for each effective
+** call to [sqlite3_initialize()])^
+** (usually only once during the lifetime of the process). ^(The xInit()
+** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
+** The intent of the xInit() method is to set up global data structures
+** required by the custom page cache implementation.
+** ^(If the xInit() method is NULL, then the
+** built-in default page cache is used instead of the application defined
+** page cache.)^
+**
+** [[the xShutdown() page cache method]]
+** ^The xShutdown() method is called by [sqlite3_shutdown()].
+** It can be used to clean up
+** any outstanding resources before process shutdown, if required.
+** ^The xShutdown() method may be NULL.
+**
+** ^SQLite automatically serializes calls to the xInit method,
+** so the xInit method need not be threadsafe. ^The
+** xShutdown method is only called from [sqlite3_shutdown()] so it does
+** not need to be threadsafe either. All other methods must be threadsafe
+** in multithreaded applications.
+**
+** ^SQLite will never invoke xInit() more than once without an intervening
+** call to xShutdown().
+**
+** [[the xCreate() page cache methods]]
+** ^SQLite invokes the xCreate() method to construct a new cache instance.
+** SQLite will typically create one cache instance for each open database file,
+** though this is not guaranteed. ^The
+** first parameter, szPage, is the size in bytes of the pages that must
+** be allocated by the cache. ^szPage will always a power of two. ^The
+** second parameter szExtra is a number of bytes of extra storage
+** associated with each page cache entry. ^The szExtra parameter will
+** a number less than 250. SQLite will use the
+** extra szExtra bytes on each page to store metadata about the underlying
+** database page on disk. The value passed into szExtra depends
+** on the SQLite version, the target platform, and how SQLite was compiled.
+** ^The third argument to xCreate(), bPurgeable, is true if the cache being
+** created will be used to cache database pages of a file stored on disk, or
+** false if it is used for an in-memory database. The cache implementation
+** does not have to do anything special based with the value of bPurgeable;
+** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
+** never invoke xUnpin() except to deliberately delete a page.
+** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
+** false will always have the "discard" flag set to true.
+** ^Hence, a cache created with bPurgeable false will
+** never contain any unpinned pages.
+**
+** [[the xCachesize() page cache method]]
+** ^(The xCachesize() method may be called at any time by SQLite to set the
+** suggested maximum cache-size (number of pages stored by) the cache
+** instance passed as the first argument. This is the value configured using
+** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
+** parameter, the implementation is not required to do anything with this
+** value; it is advisory only.
+**
+** [[the xPagecount() page cache methods]]
+** The xPagecount() method must return the number of pages currently
+** stored in the cache, both pinned and unpinned.
+**
+** [[the xFetch() page cache methods]]
+** The xFetch() method locates a page in the cache and returns a pointer to
+** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
+** The pBuf element of the returned sqlite3_pcache_page object will be a
+** pointer to a buffer of szPage bytes used to store the content of a
+** single database page. The pExtra element of sqlite3_pcache_page will be
+** a pointer to the szExtra bytes of extra storage that SQLite has requested
+** for each entry in the page cache.
+**
+** The page to be fetched is determined by the key. ^The minimum key value
+** is 1. After it has been retrieved using xFetch, the page is considered
+** to be "pinned".
+**
+** If the requested page is already in the page cache, then the page cache
+** implementation must return a pointer to the page buffer with its content
+** intact. If the requested page is not already in the cache, then the
+** cache implementation should use the value of the createFlag
+** parameter to help it determined what action to take:
+**
+** <table border=1 width=85% align=center>
+** <tr><th> createFlag <th> Behavior when page is not already in cache
+** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
+** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
+** Otherwise return NULL.
+** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
+** NULL if allocating a new page is effectively impossible.
+** </table>
+**
+** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
+** will only use a createFlag of 2 after a prior call with a createFlag of 1
+** failed.)^ In between the xFetch() calls, SQLite may
+** attempt to unpin one or more cache pages by spilling the content of
+** pinned pages to disk and synching the operating system disk cache.
+**
+** [[the xUnpin() page cache method]]
+** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
+** as its second argument. If the third parameter, discard, is non-zero,
+** then the page must be evicted from the cache.
+** ^If the discard parameter is
+** zero, then the page may be discarded or retained at the discretion of
+** page cache implementation. ^The page cache implementation
+** may choose to evict unpinned pages at any time.
+**
+** The cache must not perform any reference counting. A single
+** call to xUnpin() unpins the page regardless of the number of prior calls
+** to xFetch().
+**
+** [[the xRekey() page cache methods]]
+** The xRekey() method is used to change the key value associated with the
+** page passed as the second argument. If the cache
+** previously contains an entry associated with newKey, it must be
+** discarded. ^Any prior cache entry associated with newKey is guaranteed not
+** to be pinned.
+**
+** When SQLite calls the xTruncate() method, the cache must discard all
+** existing cache entries with page numbers (keys) greater than or equal
+** to the value of the iLimit parameter passed to xTruncate(). If any
+** of these pages are pinned, they are implicitly unpinned, meaning that
+** they can be safely discarded.
+**
+** [[the xDestroy() page cache method]]
+** ^The xDestroy() method is used to delete a cache allocated by xCreate().
+** All resources associated with the specified cache should be freed. ^After
+** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
+** handle invalid, and will not use it with any other sqlite3_pcache_methods2
+** functions.
+**
+** [[the xShrink() page cache method]]
+** ^SQLite invokes the xShrink() method when it wants the page cache to
+** free up as much of heap memory as possible. The page cache implementation
+** is not obligated to free any memory, but well-behaved implementations should
+** do their best.
+*/
+typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
+struct sqlite3_pcache_methods2 {
+ int iVersion;
+ void *pArg;
+ int (*xInit)(void*);
+ void (*xShutdown)(void*);
+ sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
+ void (*xCachesize)(sqlite3_pcache*, int nCachesize);
+ int (*xPagecount)(sqlite3_pcache*);
+ sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
+ void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
+ void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
+ unsigned oldKey, unsigned newKey);
+ void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
+ void (*xDestroy)(sqlite3_pcache*);
+ void (*xShrink)(sqlite3_pcache*);
+};
+
+/*
+** This is the obsolete pcache_methods object that has now been replaced
+** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
+** retained in the header file for backwards compatibility only.
+*/
+typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
+struct sqlite3_pcache_methods {
+ void *pArg;
+ int (*xInit)(void*);
+ void (*xShutdown)(void*);
+ sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
+ void (*xCachesize)(sqlite3_pcache*, int nCachesize);
+ int (*xPagecount)(sqlite3_pcache*);
+ void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
+ void (*xUnpin)(sqlite3_pcache*, void*, int discard);
+ void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
+ void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
+ void (*xDestroy)(sqlite3_pcache*);
+};
+
+
+/*
+** CAPI3REF: Online Backup Object
+**
+** The sqlite3_backup object records state information about an ongoing
+** online backup operation. ^The sqlite3_backup object is created by
+** a call to [sqlite3_backup_init()] and is destroyed by a call to
+** [sqlite3_backup_finish()].
+**
+** See Also: [Using the SQLite Online Backup API]
+*/
+typedef struct sqlite3_backup sqlite3_backup;
+
+/*
+** CAPI3REF: Online Backup API.
+**
+** The backup API copies the content of one database into another.
+** It is useful either for creating backups of databases or
+** for copying in-memory databases to or from persistent files.
+**
+** See Also: [Using the SQLite Online Backup API]
+**
+** ^SQLite holds a write transaction open on the destination database file
+** for the duration of the backup operation.
+** ^The source database is read-locked only while it is being read;
+** it is not locked continuously for the entire backup operation.
+** ^Thus, the backup may be performed on a live source database without
+** preventing other database connections from
+** reading or writing to the source database while the backup is underway.
+**
+** ^(To perform a backup operation:
+** <ol>
+** <li><b>sqlite3_backup_init()</b> is called once to initialize the
+** backup,
+** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
+** the data between the two databases, and finally
+** <li><b>sqlite3_backup_finish()</b> is called to release all resources
+** associated with the backup operation.
+** </ol>)^
+** There should be exactly one call to sqlite3_backup_finish() for each
+** successful call to sqlite3_backup_init().
+**
+** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
+**
+** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
+** [database connection] associated with the destination database
+** and the database name, respectively.
+** ^The database name is "main" for the main database, "temp" for the
+** temporary database, or the name specified after the AS keyword in
+** an [ATTACH] statement for an attached database.
+** ^The S and M arguments passed to
+** sqlite3_backup_init(D,N,S,M) identify the [database connection]
+** and database name of the source database, respectively.
+** ^The source and destination [database connections] (parameters S and D)
+** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
+** an error.
+**
+** ^A call to sqlite3_backup_init() will fail, returning NULL, if
+** there is already a read or read-write transaction open on the
+** destination database.
+**
+** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
+** returned and an error code and error message are stored in the
+** destination [database connection] D.
+** ^The error code and message for the failed call to sqlite3_backup_init()
+** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
+** [sqlite3_errmsg16()] functions.
+** ^A successful call to sqlite3_backup_init() returns a pointer to an
+** [sqlite3_backup] object.
+** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
+** sqlite3_backup_finish() functions to perform the specified backup
+** operation.
+**
+** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
+**
+** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
+** the source and destination databases specified by [sqlite3_backup] object B.
+** ^If N is negative, all remaining source pages are copied.
+** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
+** are still more pages to be copied, then the function returns [SQLITE_OK].
+** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
+** from source to destination, then it returns [SQLITE_DONE].
+** ^If an error occurs while running sqlite3_backup_step(B,N),
+** then an [error code] is returned. ^As well as [SQLITE_OK] and
+** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
+** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
+** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
+**
+** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
+** <ol>
+** <li> the destination database was opened read-only, or
+** <li> the destination database is using write-ahead-log journaling
+** and the destination and source page sizes differ, or
+** <li> the destination database is an in-memory database and the
+** destination and source page sizes differ.
+** </ol>)^
+**
+** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
+** the [sqlite3_busy_handler | busy-handler function]
+** is invoked (if one is specified). ^If the
+** busy-handler returns non-zero before the lock is available, then
+** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
+** sqlite3_backup_step() can be retried later. ^If the source
+** [database connection]
+** is being used to write to the source database when sqlite3_backup_step()
+** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
+** case the call to sqlite3_backup_step() can be retried later on. ^(If
+** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
+** [SQLITE_READONLY] is returned, then
+** there is no point in retrying the call to sqlite3_backup_step(). These
+** errors are considered fatal.)^ The application must accept
+** that the backup operation has failed and pass the backup operation handle
+** to the sqlite3_backup_finish() to release associated resources.
+**
+** ^The first call to sqlite3_backup_step() obtains an exclusive lock
+** on the destination file. ^The exclusive lock is not released until either
+** sqlite3_backup_finish() is called or the backup operation is complete
+** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
+** sqlite3_backup_step() obtains a [shared lock] on the source database that
+** lasts for the duration of the sqlite3_backup_step() call.
+** ^Because the source database is not locked between calls to
+** sqlite3_backup_step(), the source database may be modified mid-way
+** through the backup process. ^If the source database is modified by an
+** external process or via a database connection other than the one being
+** used by the backup operation, then the backup will be automatically
+** restarted by the next call to sqlite3_backup_step(). ^If the source
+** database is modified by the using the same database connection as is used
+** by the backup operation, then the backup database is automatically
+** updated at the same time.
+**
+** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
+**
+** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
+** application wishes to abandon the backup operation, the application
+** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
+** ^The sqlite3_backup_finish() interfaces releases all
+** resources associated with the [sqlite3_backup] object.
+** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
+** active write-transaction on the destination database is rolled back.
+** The [sqlite3_backup] object is invalid
+** and may not be used following a call to sqlite3_backup_finish().
+**
+** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
+** sqlite3_backup_step() errors occurred, regardless or whether or not
+** sqlite3_backup_step() completed.
+** ^If an out-of-memory condition or IO error occurred during any prior
+** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
+** sqlite3_backup_finish() returns the corresponding [error code].
+**
+** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
+** is not a permanent error and does not affect the return value of
+** sqlite3_backup_finish().
+**
+** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
+** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
+**
+** ^The sqlite3_backup_remaining() routine returns the number of pages still
+** to be backed up at the conclusion of the most recent sqlite3_backup_step().
+** ^The sqlite3_backup_pagecount() routine returns the total number of pages
+** in the source database at the conclusion of the most recent
+** sqlite3_backup_step().
+** ^(The values returned by these functions are only updated by
+** sqlite3_backup_step(). If the source database is modified in a way that
+** changes the size of the source database or the number of pages remaining,
+** those changes are not reflected in the output of sqlite3_backup_pagecount()
+** and sqlite3_backup_remaining() until after the next
+** sqlite3_backup_step().)^
+**
+** <b>Concurrent Usage of Database Handles</b>
+**
+** ^The source [database connection] may be used by the application for other
+** purposes while a backup operation is underway or being initialized.
+** ^If SQLite is compiled and configured to support threadsafe database
+** connections, then the source database connection may be used concurrently
+** from within other threads.
+**
+** However, the application must guarantee that the destination
+** [database connection] is not passed to any other API (by any thread) after
+** sqlite3_backup_init() is called and before the corresponding call to
+** sqlite3_backup_finish(). SQLite does not currently check to see
+** if the application incorrectly accesses the destination [database connection]
+** and so no error code is reported, but the operations may malfunction
+** nevertheless. Use of the destination database connection while a
+** backup is in progress might also also cause a mutex deadlock.
+**
+** If running in [shared cache mode], the application must
+** guarantee that the shared cache used by the destination database
+** is not accessed while the backup is running. In practice this means
+** that the application must guarantee that the disk file being
+** backed up to is not accessed by any connection within the process,
+** not just the specific connection that was passed to sqlite3_backup_init().
+**
+** The [sqlite3_backup] object itself is partially threadsafe. Multiple
+** threads may safely make multiple concurrent calls to sqlite3_backup_step().
+** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
+** APIs are not strictly speaking threadsafe. If they are invoked at the
+** same time as another thread is invoking sqlite3_backup_step() it is
+** possible that they return invalid values.
+*/
+SQLITE_API sqlite3_backup *sqlite3_backup_init(
+ sqlite3 *pDest, /* Destination database handle */
+ const char *zDestName, /* Destination database name */
+ sqlite3 *pSource, /* Source database handle */
+ const char *zSourceName /* Source database name */
+);
+SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
+SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
+SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
+SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
+
+/*
+** CAPI3REF: Unlock Notification
+** METHOD: sqlite3
+**
+** ^When running in shared-cache mode, a database operation may fail with
+** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
+** individual tables within the shared-cache cannot be obtained. See
+** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
+** ^This API may be used to register a callback that SQLite will invoke
+** when the connection currently holding the required lock relinquishes it.
+** ^This API is only available if the library was compiled with the
+** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
+**
+** See Also: [Using the SQLite Unlock Notification Feature].
+**
+** ^Shared-cache locks are released when a database connection concludes
+** its current transaction, either by committing it or rolling it back.
+**
+** ^When a connection (known as the blocked connection) fails to obtain a
+** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
+** identity of the database connection (the blocking connection) that
+** has locked the required resource is stored internally. ^After an
+** application receives an SQLITE_LOCKED error, it may call the
+** sqlite3_unlock_notify() method with the blocked connection handle as
+** the first argument to register for a callback that will be invoked
+** when the blocking connections current transaction is concluded. ^The
+** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
+** call that concludes the blocking connection's transaction.
+**
+** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
+** there is a chance that the blocking connection will have already
+** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
+** If this happens, then the specified callback is invoked immediately,
+** from within the call to sqlite3_unlock_notify().)^
+**
+** ^If the blocked connection is attempting to obtain a write-lock on a
+** shared-cache table, and more than one other connection currently holds
+** a read-lock on the same table, then SQLite arbitrarily selects one of
+** the other connections to use as the blocking connection.
+**
+** ^(There may be at most one unlock-notify callback registered by a
+** blocked connection. If sqlite3_unlock_notify() is called when the
+** blocked connection already has a registered unlock-notify callback,
+** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
+** called with a NULL pointer as its second argument, then any existing
+** unlock-notify callback is canceled. ^The blocked connections
+** unlock-notify callback may also be canceled by closing the blocked
+** connection using [sqlite3_close()].
+**
+** The unlock-notify callback is not reentrant. If an application invokes
+** any sqlite3_xxx API functions from within an unlock-notify callback, a
+** crash or deadlock may be the result.
+**
+** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
+** returns SQLITE_OK.
+**
+** <b>Callback Invocation Details</b>
+**
+** When an unlock-notify callback is registered, the application provides a
+** single void* pointer that is passed to the callback when it is invoked.
+** However, the signature of the callback function allows SQLite to pass
+** it an array of void* context pointers. The first argument passed to
+** an unlock-notify callback is a pointer to an array of void* pointers,
+** and the second is the number of entries in the array.
+**
+** When a blocking connection's transaction is concluded, there may be
+** more than one blocked connection that has registered for an unlock-notify
+** callback. ^If two or more such blocked connections have specified the
+** same callback function, then instead of invoking the callback function
+** multiple times, it is invoked once with the set of void* context pointers
+** specified by the blocked connections bundled together into an array.
+** This gives the application an opportunity to prioritize any actions
+** related to the set of unblocked database connections.
+**
+** <b>Deadlock Detection</b>
+**
+** Assuming that after registering for an unlock-notify callback a
+** database waits for the callback to be issued before taking any further
+** action (a reasonable assumption), then using this API may cause the
+** application to deadlock. For example, if connection X is waiting for
+** connection Y's transaction to be concluded, and similarly connection
+** Y is waiting on connection X's transaction, then neither connection
+** will proceed and the system may remain deadlocked indefinitely.
+**
+** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
+** detection. ^If a given call to sqlite3_unlock_notify() would put the
+** system in a deadlocked state, then SQLITE_LOCKED is returned and no
+** unlock-notify callback is registered. The system is said to be in
+** a deadlocked state if connection A has registered for an unlock-notify
+** callback on the conclusion of connection B's transaction, and connection
+** B has itself registered for an unlock-notify callback when connection
+** A's transaction is concluded. ^Indirect deadlock is also detected, so
+** the system is also considered to be deadlocked if connection B has
+** registered for an unlock-notify callback on the conclusion of connection
+** C's transaction, where connection C is waiting on connection A. ^Any
+** number of levels of indirection are allowed.
+**
+** <b>The "DROP TABLE" Exception</b>
+**
+** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
+** always appropriate to call sqlite3_unlock_notify(). There is however,
+** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
+** SQLite checks if there are any currently executing SELECT statements
+** that belong to the same connection. If there are, SQLITE_LOCKED is
+** returned. In this case there is no "blocking connection", so invoking
+** sqlite3_unlock_notify() results in the unlock-notify callback being
+** invoked immediately. If the application then re-attempts the "DROP TABLE"
+** or "DROP INDEX" query, an infinite loop might be the result.
+**
+** One way around this problem is to check the extended error code returned
+** by an sqlite3_step() call. ^(If there is a blocking connection, then the
+** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
+** the special "DROP TABLE/INDEX" case, the extended error code is just
+** SQLITE_LOCKED.)^
+*/
+SQLITE_API int sqlite3_unlock_notify(
+ sqlite3 *pBlocked, /* Waiting connection */
+ void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
+ void *pNotifyArg /* Argument to pass to xNotify */
+);
+
+
+/*
+** CAPI3REF: String Comparison
+**
+** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
+** and extensions to compare the contents of two buffers containing UTF-8
+** strings in a case-independent fashion, using the same definition of "case
+** independence" that SQLite uses internally when comparing identifiers.
+*/
+SQLITE_API int sqlite3_stricmp(const char *, const char *);
+SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
+
+/*
+** CAPI3REF: String Globbing
+*
+** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
+** string X matches the [GLOB] pattern P.
+** ^The definition of [GLOB] pattern matching used in
+** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
+** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
+** is case sensitive.
+**
+** Note that this routine returns zero on a match and non-zero if the strings
+** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
+**
+** See also: [sqlite3_strlike()].
+*/
+SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
+
+/*
+** CAPI3REF: String LIKE Matching
+*
+** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
+** string X matches the [LIKE] pattern P with escape character E.
+** ^The definition of [LIKE] pattern matching used in
+** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
+** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
+** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
+** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
+** insensitive - equivalent upper and lower case ASCII characters match
+** one another.
+**
+** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
+** only ASCII characters are case folded.
+**
+** Note that this routine returns zero on a match and non-zero if the strings
+** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
+**
+** See also: [sqlite3_strglob()].
+*/
+SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
+
+/*
+** CAPI3REF: Error Logging Interface
+**
+** ^The [sqlite3_log()] interface writes a message into the [error log]
+** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
+** ^If logging is enabled, the zFormat string and subsequent arguments are
+** used with [sqlite3_snprintf()] to generate the final output string.
+**
+** The sqlite3_log() interface is intended for use by extensions such as
+** virtual tables, collating functions, and SQL functions. While there is
+** nothing to prevent an application from calling sqlite3_log(), doing so
+** is considered bad form.
+**
+** The zFormat string must not be NULL.
+**
+** To avoid deadlocks and other threading problems, the sqlite3_log() routine
+** will not use dynamically allocated memory. The log message is stored in
+** a fixed-length buffer on the stack. If the log message is longer than
+** a few hundred characters, it will be truncated to the length of the
+** buffer.
+*/
+SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
+
+/*
+** CAPI3REF: Write-Ahead Log Commit Hook
+** METHOD: sqlite3
+**
+** ^The [sqlite3_wal_hook()] function is used to register a callback that
+** is invoked each time data is committed to a database in wal mode.
+**
+** ^(The callback is invoked by SQLite after the commit has taken place and
+** the associated write-lock on the database released)^, so the implementation
+** may read, write or [checkpoint] the database as required.
+**
+** ^The first parameter passed to the callback function when it is invoked
+** is a copy of the third parameter passed to sqlite3_wal_hook() when
+** registering the callback. ^The second is a copy of the database handle.
+** ^The third parameter is the name of the database that was written to -
+** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
+** is the number of pages currently in the write-ahead log file,
+** including those that were just committed.
+**
+** The callback function should normally return [SQLITE_OK]. ^If an error
+** code is returned, that error will propagate back up through the
+** SQLite code base to cause the statement that provoked the callback
+** to report an error, though the commit will have still occurred. If the
+** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
+** that does not correspond to any valid SQLite error code, the results
+** are undefined.
+**
+** A single database handle may have at most a single write-ahead log callback
+** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
+** previously registered write-ahead log callback. ^Note that the
+** [sqlite3_wal_autocheckpoint()] interface and the
+** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
+** overwrite any prior [sqlite3_wal_hook()] settings.
+*/
+SQLITE_API void *sqlite3_wal_hook(
+ sqlite3*,
+ int(*)(void *,sqlite3*,const char*,int),
+ void*
+);
+
+/*
+** CAPI3REF: Configure an auto-checkpoint
+** METHOD: sqlite3
+**
+** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
+** [sqlite3_wal_hook()] that causes any database on [database connection] D
+** to automatically [checkpoint]
+** after committing a transaction if there are N or
+** more frames in the [write-ahead log] file. ^Passing zero or
+** a negative value as the nFrame parameter disables automatic
+** checkpoints entirely.
+**
+** ^The callback registered by this function replaces any existing callback
+** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
+** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
+** configured by this function.
+**
+** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
+** from SQL.
+**
+** ^Checkpoints initiated by this mechanism are
+** [sqlite3_wal_checkpoint_v2|PASSIVE].
+**
+** ^Every new [database connection] defaults to having the auto-checkpoint
+** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
+** pages. The use of this interface
+** is only necessary if the default setting is found to be suboptimal
+** for a particular application.
+*/
+SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
+
+/*
+** CAPI3REF: Checkpoint a database
+** METHOD: sqlite3
+**
+** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
+** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
+**
+** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
+** [write-ahead log] for database X on [database connection] D to be
+** transferred into the database file and for the write-ahead log to
+** be reset. See the [checkpointing] documentation for addition
+** information.
+**
+** This interface used to be the only way to cause a checkpoint to
+** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
+** interface was added. This interface is retained for backwards
+** compatibility and as a convenience for applications that need to manually
+** start a callback but which do not need the full power (and corresponding
+** complication) of [sqlite3_wal_checkpoint_v2()].
+*/
+SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
+
+/*
+** CAPI3REF: Checkpoint a database
+** METHOD: sqlite3
+**
+** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
+** operation on database X of [database connection] D in mode M. Status
+** information is written back into integers pointed to by L and C.)^
+** ^(The M parameter must be a valid [checkpoint mode]:)^
+**
+** <dl>
+** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
+** ^Checkpoint as many frames as possible without waiting for any database
+** readers or writers to finish, then sync the database file if all frames
+** in the log were checkpointed. ^The [busy-handler callback]
+** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
+** ^On the other hand, passive mode might leave the checkpoint unfinished
+** if there are concurrent readers or writers.
+**
+** <dt>SQLITE_CHECKPOINT_FULL<dd>
+** ^This mode blocks (it invokes the
+** [sqlite3_busy_handler|busy-handler callback]) until there is no
+** database writer and all readers are reading from the most recent database
+** snapshot. ^It then checkpoints all frames in the log file and syncs the
+** database file. ^This mode blocks new database writers while it is pending,
+** but new database readers are allowed to continue unimpeded.
+**
+** <dt>SQLITE_CHECKPOINT_RESTART<dd>
+** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
+** that after checkpointing the log file it blocks (calls the
+** [busy-handler callback])
+** until all readers are reading from the database file only. ^This ensures
+** that the next writer will restart the log file from the beginning.
+** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
+** database writer attempts while it is pending, but does not impede readers.
+**
+** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
+** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
+** addition that it also truncates the log file to zero bytes just prior
+** to a successful return.
+** </dl>
+**
+** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
+** the log file or to -1 if the checkpoint could not run because
+** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
+** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
+** log file (including any that were already checkpointed before the function
+** was called) or to -1 if the checkpoint could not run due to an error or
+** because the database is not in WAL mode. ^Note that upon successful
+** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
+** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
+**
+** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
+** any other process is running a checkpoint operation at the same time, the
+** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
+** busy-handler configured, it will not be invoked in this case.
+**
+** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
+** exclusive "writer" lock on the database file. ^If the writer lock cannot be
+** obtained immediately, and a busy-handler is configured, it is invoked and
+** the writer lock retried until either the busy-handler returns 0 or the lock
+** is successfully obtained. ^The busy-handler is also invoked while waiting for
+** database readers as described above. ^If the busy-handler returns 0 before
+** the writer lock is obtained or while waiting for database readers, the
+** checkpoint operation proceeds from that point in the same way as
+** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
+** without blocking any further. ^SQLITE_BUSY is returned in this case.
+**
+** ^If parameter zDb is NULL or points to a zero length string, then the
+** specified operation is attempted on all WAL databases [attached] to
+** [database connection] db. In this case the
+** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
+** an SQLITE_BUSY error is encountered when processing one or more of the
+** attached WAL databases, the operation is still attempted on any remaining
+** attached databases and SQLITE_BUSY is returned at the end. ^If any other
+** error occurs while processing an attached database, processing is abandoned
+** and the error code is returned to the caller immediately. ^If no error
+** (SQLITE_BUSY or otherwise) is encountered while processing the attached
+** databases, SQLITE_OK is returned.
+**
+** ^If database zDb is the name of an attached database that is not in WAL
+** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
+** zDb is not NULL (or a zero length string) and is not the name of any
+** attached database, SQLITE_ERROR is returned to the caller.
+**
+** ^Unless it returns SQLITE_MISUSE,
+** the sqlite3_wal_checkpoint_v2() interface
+** sets the error information that is queried by
+** [sqlite3_errcode()] and [sqlite3_errmsg()].
+**
+** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
+** from SQL.
+*/
+SQLITE_API int sqlite3_wal_checkpoint_v2(
+ sqlite3 *db, /* Database handle */
+ const char *zDb, /* Name of attached database (or NULL) */
+ int eMode, /* SQLITE_CHECKPOINT_* value */
+ int *pnLog, /* OUT: Size of WAL log in frames */
+ int *pnCkpt /* OUT: Total number of frames checkpointed */
+);
+
+/*
+** CAPI3REF: Checkpoint Mode Values
+** KEYWORDS: {checkpoint mode}
+**
+** These constants define all valid values for the "checkpoint mode" passed
+** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
+** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
+** meaning of each of these checkpoint modes.
+*/
+#define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
+#define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
+#define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
+#define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
+
+/*
+** CAPI3REF: Virtual Table Interface Configuration
+**
+** This function may be called by either the [xConnect] or [xCreate] method
+** of a [virtual table] implementation to configure
+** various facets of the virtual table interface.
+**
+** If this interface is invoked outside the context of an xConnect or
+** xCreate virtual table method then the behavior is undefined.
+**
+** In the call sqlite3_vtab_config(D,C,...) the D parameter is the
+** [database connection] in which the virtual table is being created and
+** which is passed in as the first argument to the [xConnect] or [xCreate]
+** method that is invoking sqlite3_vtab_config(). The C parameter is one
+** of the [virtual table configuration options]. The presence and meaning
+** of parameters after C depend on which [virtual table configuration option]
+** is used.
+*/
+SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
+
+/*
+** CAPI3REF: Virtual Table Configuration Options
+** KEYWORDS: {virtual table configuration options}
+** KEYWORDS: {virtual table configuration option}
+**
+** These macros define the various options to the
+** [sqlite3_vtab_config()] interface that [virtual table] implementations
+** can use to customize and optimize their behavior.
+**
+** <dl>
+** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]
+** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT</dt>
+** <dd>Calls of the form
+** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
+** where X is an integer. If X is zero, then the [virtual table] whose
+** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
+** support constraints. In this configuration (which is the default) if
+** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
+** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
+** specified as part of the users SQL statement, regardless of the actual
+** ON CONFLICT mode specified.
+**
+** If X is non-zero, then the virtual table implementation guarantees
+** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
+** any modifications to internal or persistent data structures have been made.
+** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
+** is able to roll back a statement or database transaction, and abandon
+** or continue processing the current SQL statement as appropriate.
+** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
+** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
+** had been ABORT.
+**
+** Virtual table implementations that are required to handle OR REPLACE
+** must do so within the [xUpdate] method. If a call to the
+** [sqlite3_vtab_on_conflict()] function indicates that the current ON
+** CONFLICT policy is REPLACE, the virtual table implementation should
+** silently replace the appropriate rows within the xUpdate callback and
+** return SQLITE_OK. Or, if this is not possible, it may return
+** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
+** constraint handling.
+** </dd>
+**
+** [[SQLITE_VTAB_DIRECTONLY]]<dt>SQLITE_VTAB_DIRECTONLY</dt>
+** <dd>Calls of the form
+** [sqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the
+** the [xConnect] or [xCreate] methods of a [virtual table] implmentation
+** prohibits that virtual table from being used from within triggers and
+** views.
+** </dd>
+**
+** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>
+** <dd>Calls of the form
+** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the
+** the [xConnect] or [xCreate] methods of a [virtual table] implmentation
+** identify that virtual table as being safe to use from within triggers
+** and views. Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the
+** virtual table can do no serious harm even if it is controlled by a
+** malicious hacker. Developers should avoid setting the SQLITE_VTAB_INNOCUOUS
+** flag unless absolutely necessary.
+** </dd>
+** </dl>
+*/
+#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
+#define SQLITE_VTAB_INNOCUOUS 2
+#define SQLITE_VTAB_DIRECTONLY 3
+
+/*
+** CAPI3REF: Determine The Virtual Table Conflict Policy
+**
+** This function may only be called from within a call to the [xUpdate] method
+** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
+** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
+** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
+** of the SQL statement that triggered the call to the [xUpdate] method of the
+** [virtual table].
+*/
+SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
+
+/*
+** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
+**
+** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
+** method of a [virtual table], then it returns true if and only if the
+** column is being fetched as part of an UPDATE operation during which the
+** column value will not change. Applications might use this to substitute
+** a return value that is less expensive to compute and that the corresponding
+** [xUpdate] method understands as a "no-change" value.
+**
+** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
+** the column is not changed by the UPDATE statement, then the xColumn
+** method can optionally return without setting a result, without calling
+** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
+** In that case, [sqlite3_value_nochange(X)] will return true for the
+** same column in the [xUpdate] method.
+*/
+SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
+
+/*
+** CAPI3REF: Determine The Collation For a Virtual Table Constraint
+**
+** This function may only be called from within a call to the [xBestIndex]
+** method of a [virtual table].
+**
+** The first argument must be the sqlite3_index_info object that is the
+** first parameter to the xBestIndex() method. The second argument must be
+** an index into the aConstraint[] array belonging to the sqlite3_index_info
+** structure passed to xBestIndex. This function returns a pointer to a buffer
+** containing the name of the collation sequence for the corresponding
+** constraint.
+*/
+SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
+
+/*
+** CAPI3REF: Conflict resolution modes
+** KEYWORDS: {conflict resolution mode}
+**
+** These constants are returned by [sqlite3_vtab_on_conflict()] to
+** inform a [virtual table] implementation what the [ON CONFLICT] mode
+** is for the SQL statement being evaluated.
+**
+** Note that the [SQLITE_IGNORE] constant is also used as a potential
+** return value from the [sqlite3_set_authorizer()] callback and that
+** [SQLITE_ABORT] is also a [result code].
+*/
+#define SQLITE_ROLLBACK 1
+/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
+#define SQLITE_FAIL 3
+/* #define SQLITE_ABORT 4 // Also an error code */
+#define SQLITE_REPLACE 5
+
+/*
+** CAPI3REF: Prepared Statement Scan Status Opcodes
+** KEYWORDS: {scanstatus options}
+**
+** The following constants can be used for the T parameter to the
+** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
+** different metric for sqlite3_stmt_scanstatus() to return.
+**
+** When the value returned to V is a string, space to hold that string is
+** managed by the prepared statement S and will be automatically freed when
+** S is finalized.
+**
+** <dl>
+** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
+** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be
+** set to the total number of times that the X-th loop has run.</dd>
+**
+** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
+** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be set
+** to the total number of rows examined by all iterations of the X-th loop.</dd>
+**
+** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
+** <dd>^The "double" variable pointed to by the V parameter will be set to the
+** query planner's estimate for the average number of rows output from each
+** iteration of the X-th loop. If the query planner's estimates was accurate,
+** then this value will approximate the quotient NVISIT/NLOOP and the
+** product of this value for all prior loops with the same SELECTID will
+** be the NLOOP value for the current loop.
+**
+** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
+** <dd>^The "const char *" variable pointed to by the V parameter will be set
+** to a zero-terminated UTF-8 string containing the name of the index or table
+** used for the X-th loop.
+**
+** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
+** <dd>^The "const char *" variable pointed to by the V parameter will be set
+** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
+** description for the X-th loop.
+**
+** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
+** <dd>^The "int" variable pointed to by the V parameter will be set to the
+** "select-id" for the X-th loop. The select-id identifies which query or
+** subquery the loop is part of. The main query has a select-id of zero.
+** The select-id is the same value as is output in the first column
+** of an [EXPLAIN QUERY PLAN] query.
+** </dl>
+*/
+#define SQLITE_SCANSTAT_NLOOP 0
+#define SQLITE_SCANSTAT_NVISIT 1
+#define SQLITE_SCANSTAT_EST 2
+#define SQLITE_SCANSTAT_NAME 3
+#define SQLITE_SCANSTAT_EXPLAIN 4
+#define SQLITE_SCANSTAT_SELECTID 5
+
+/*
+** CAPI3REF: Prepared Statement Scan Status
+** METHOD: sqlite3_stmt
+**
+** This interface returns information about the predicted and measured
+** performance for pStmt. Advanced applications can use this
+** interface to compare the predicted and the measured performance and
+** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
+**
+** Since this interface is expected to be rarely used, it is only
+** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
+** compile-time option.
+**
+** The "iScanStatusOp" parameter determines which status information to return.
+** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
+** of this interface is undefined.
+** ^The requested measurement is written into a variable pointed to by
+** the "pOut" parameter.
+** Parameter "idx" identifies the specific loop to retrieve statistics for.
+** Loops are numbered starting from zero. ^If idx is out of range - less than
+** zero or greater than or equal to the total number of loops used to implement
+** the statement - a non-zero value is returned and the variable that pOut
+** points to is unchanged.
+**
+** ^Statistics might not be available for all loops in all statements. ^In cases
+** where there exist loops with no available statistics, this function behaves
+** as if the loop did not exist - it returns non-zero and leave the variable
+** that pOut points to unchanged.
+**
+** See also: [sqlite3_stmt_scanstatus_reset()]
+*/
+SQLITE_API int sqlite3_stmt_scanstatus(
+ sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
+ int idx, /* Index of loop to report on */
+ int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
+ void *pOut /* Result written here */
+);
+
+/*
+** CAPI3REF: Zero Scan-Status Counters
+** METHOD: sqlite3_stmt
+**
+** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
+**
+** This API is only available if the library is built with pre-processor
+** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
+*/
+SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
+
+/*
+** CAPI3REF: Flush caches to disk mid-transaction
+** METHOD: sqlite3
+**
+** ^If a write-transaction is open on [database connection] D when the
+** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
+** pages in the pager-cache that are not currently in use are written out
+** to disk. A dirty page may be in use if a database cursor created by an
+** active SQL statement is reading from it, or if it is page 1 of a database
+** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
+** interface flushes caches for all schemas - "main", "temp", and
+** any [attached] databases.
+**
+** ^If this function needs to obtain extra database locks before dirty pages
+** can be flushed to disk, it does so. ^If those locks cannot be obtained
+** immediately and there is a busy-handler callback configured, it is invoked
+** in the usual manner. ^If the required lock still cannot be obtained, then
+** the database is skipped and an attempt made to flush any dirty pages
+** belonging to the next (if any) database. ^If any databases are skipped
+** because locks cannot be obtained, but no other error occurs, this
+** function returns SQLITE_BUSY.
+**
+** ^If any other error occurs while flushing dirty pages to disk (for
+** example an IO error or out-of-memory condition), then processing is
+** abandoned and an SQLite [error code] is returned to the caller immediately.
+**
+** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
+**
+** ^This function does not set the database handle error code or message
+** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
+*/
+SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
+
+/*
+** CAPI3REF: The pre-update hook.
+** METHOD: sqlite3
+**
+** ^These interfaces are only available if SQLite is compiled using the
+** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
+**
+** ^The [sqlite3_preupdate_hook()] interface registers a callback function
+** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
+** on a database table.
+** ^At most one preupdate hook may be registered at a time on a single
+** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
+** the previous setting.
+** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
+** with a NULL pointer as the second parameter.
+** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
+** the first parameter to callbacks.
+**
+** ^The preupdate hook only fires for changes to real database tables; the
+** preupdate hook is not invoked for changes to [virtual tables] or to
+** system tables like sqlite_sequence or sqlite_stat1.
+**
+** ^The second parameter to the preupdate callback is a pointer to
+** the [database connection] that registered the preupdate hook.
+** ^The third parameter to the preupdate callback is one of the constants
+** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
+** kind of update operation that is about to occur.
+** ^(The fourth parameter to the preupdate callback is the name of the
+** database within the database connection that is being modified. This
+** will be "main" for the main database or "temp" for TEMP tables or
+** the name given after the AS keyword in the [ATTACH] statement for attached
+** databases.)^
+** ^The fifth parameter to the preupdate callback is the name of the
+** table that is being modified.
+**
+** For an UPDATE or DELETE operation on a [rowid table], the sixth
+** parameter passed to the preupdate callback is the initial [rowid] of the
+** row being modified or deleted. For an INSERT operation on a rowid table,
+** or any operation on a WITHOUT ROWID table, the value of the sixth
+** parameter is undefined. For an INSERT or UPDATE on a rowid table the
+** seventh parameter is the final rowid value of the row being inserted
+** or updated. The value of the seventh parameter passed to the callback
+** function is not defined for operations on WITHOUT ROWID tables, or for
+** DELETE operations on rowid tables.
+**
+** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
+** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
+** provide additional information about a preupdate event. These routines
+** may only be called from within a preupdate callback. Invoking any of
+** these routines from outside of a preupdate callback or with a
+** [database connection] pointer that is different from the one supplied
+** to the preupdate callback results in undefined and probably undesirable
+** behavior.
+**
+** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
+** in the row that is being inserted, updated, or deleted.
+**
+** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
+** a [protected sqlite3_value] that contains the value of the Nth column of
+** the table row before it is updated. The N parameter must be between 0
+** and one less than the number of columns or the behavior will be
+** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
+** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
+** behavior is undefined. The [sqlite3_value] that P points to
+** will be destroyed when the preupdate callback returns.
+**
+** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
+** a [protected sqlite3_value] that contains the value of the Nth column of
+** the table row after it is updated. The N parameter must be between 0
+** and one less than the number of columns or the behavior will be
+** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
+** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
+** behavior is undefined. The [sqlite3_value] that P points to
+** will be destroyed when the preupdate callback returns.
+**
+** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
+** callback was invoked as a result of a direct insert, update, or delete
+** operation; or 1 for inserts, updates, or deletes invoked by top-level
+** triggers; or 2 for changes resulting from triggers called by top-level
+** triggers; and so forth.
+**
+** See also: [sqlite3_update_hook()]
+*/
+#if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
+SQLITE_API void *sqlite3_preupdate_hook(
+ sqlite3 *db,
+ void(*xPreUpdate)(
+ void *pCtx, /* Copy of third arg to preupdate_hook() */
+ sqlite3 *db, /* Database handle */
+ int op, /* SQLITE_UPDATE, DELETE or INSERT */
+ char const *zDb, /* Database name */
+ char const *zName, /* Table name */
+ sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
+ sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
+ ),
+ void*
+);
+SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
+SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
+SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
+SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
+#endif
+
+/*
+** CAPI3REF: Low-level system error code
+** METHOD: sqlite3
+**
+** ^Attempt to return the underlying operating system error code or error
+** number that caused the most recent I/O error or failure to open a file.
+** The return value is OS-dependent. For example, on unix systems, after
+** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
+** called to get back the underlying "errno" that caused the problem, such
+** as ENOSPC, EAUTH, EISDIR, and so forth.
+*/
+SQLITE_API int sqlite3_system_errno(sqlite3*);
+
+/*
+** CAPI3REF: Database Snapshot
+** KEYWORDS: {snapshot} {sqlite3_snapshot}
+**
+** An instance of the snapshot object records the state of a [WAL mode]
+** database for some specific point in history.
+**
+** In [WAL mode], multiple [database connections] that are open on the
+** same database file can each be reading a different historical version
+** of the database file. When a [database connection] begins a read
+** transaction, that connection sees an unchanging copy of the database
+** as it existed for the point in time when the transaction first started.
+** Subsequent changes to the database from other connections are not seen
+** by the reader until a new read transaction is started.
+**
+** The sqlite3_snapshot object records state information about an historical
+** version of the database file so that it is possible to later open a new read
+** transaction that sees that historical version of the database rather than
+** the most recent version.
+*/
+typedef struct sqlite3_snapshot {
+ unsigned char hidden[48];
+} sqlite3_snapshot;
+
+/*
+** CAPI3REF: Record A Database Snapshot
+** CONSTRUCTOR: sqlite3_snapshot
+**
+** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
+** new [sqlite3_snapshot] object that records the current state of
+** schema S in database connection D. ^On success, the
+** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
+** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
+** If there is not already a read-transaction open on schema S when
+** this function is called, one is opened automatically.
+**
+** The following must be true for this function to succeed. If any of
+** the following statements are false when sqlite3_snapshot_get() is
+** called, SQLITE_ERROR is returned. The final value of *P is undefined
+** in this case.
+**
+** <ul>
+** <li> The database handle must not be in [autocommit mode].
+**
+** <li> Schema S of [database connection] D must be a [WAL mode] database.
+**
+** <li> There must not be a write transaction open on schema S of database
+** connection D.
+**
+** <li> One or more transactions must have been written to the current wal
+** file since it was created on disk (by any connection). This means
+** that a snapshot cannot be taken on a wal mode database with no wal
+** file immediately after it is first opened. At least one transaction
+** must be written to it first.
+** </ul>
+**
+** This function may also return SQLITE_NOMEM. If it is called with the
+** database handle in autocommit mode but fails for some other reason,
+** whether or not a read transaction is opened on schema S is undefined.
+**
+** The [sqlite3_snapshot] object returned from a successful call to
+** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
+** to avoid a memory leak.
+**
+** The [sqlite3_snapshot_get()] interface is only available when the
+** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
+*/
+SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
+ sqlite3 *db,
+ const char *zSchema,
+ sqlite3_snapshot **ppSnapshot
+);
+
+/*
+** CAPI3REF: Start a read transaction on an historical snapshot
+** METHOD: sqlite3_snapshot
+**
+** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read
+** transaction or upgrades an existing one for schema S of
+** [database connection] D such that the read transaction refers to
+** historical [snapshot] P, rather than the most recent change to the
+** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK
+** on success or an appropriate [error code] if it fails.
+**
+** ^In order to succeed, the database connection must not be in
+** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there
+** is already a read transaction open on schema S, then the database handle
+** must have no active statements (SELECT statements that have been passed
+** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()).
+** SQLITE_ERROR is returned if either of these conditions is violated, or
+** if schema S does not exist, or if the snapshot object is invalid.
+**
+** ^A call to sqlite3_snapshot_open() will fail to open if the specified
+** snapshot has been overwritten by a [checkpoint]. In this case
+** SQLITE_ERROR_SNAPSHOT is returned.
+**
+** If there is already a read transaction open when this function is
+** invoked, then the same read transaction remains open (on the same
+** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT
+** is returned. If another error code - for example SQLITE_PROTOCOL or an
+** SQLITE_IOERR error code - is returned, then the final state of the
+** read transaction is undefined. If SQLITE_OK is returned, then the
+** read transaction is now open on database snapshot P.
+**
+** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
+** database connection D does not know that the database file for
+** schema S is in [WAL mode]. A database connection might not know
+** that the database file is in [WAL mode] if there has been no prior
+** I/O on that database connection, or if the database entered [WAL mode]
+** after the most recent I/O on the database connection.)^
+** (Hint: Run "[PRAGMA application_id]" against a newly opened
+** database connection in order to make it ready to use snapshots.)
+**
+** The [sqlite3_snapshot_open()] interface is only available when the
+** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
+*/
+SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
+ sqlite3 *db,
+ const char *zSchema,
+ sqlite3_snapshot *pSnapshot
+);
+
+/*
+** CAPI3REF: Destroy a snapshot
+** DESTRUCTOR: sqlite3_snapshot
+**
+** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
+** The application must eventually free every [sqlite3_snapshot] object
+** using this routine to avoid a memory leak.
+**
+** The [sqlite3_snapshot_free()] interface is only available when the
+** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
+*/
+SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
+
+/*
+** CAPI3REF: Compare the ages of two snapshot handles.
+** METHOD: sqlite3_snapshot
+**
+** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
+** of two valid snapshot handles.
+**
+** If the two snapshot handles are not associated with the same database
+** file, the result of the comparison is undefined.
+**
+** Additionally, the result of the comparison is only valid if both of the
+** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
+** last time the wal file was deleted. The wal file is deleted when the
+** database is changed back to rollback mode or when the number of database
+** clients drops to zero. If either snapshot handle was obtained before the
+** wal file was last deleted, the value returned by this function
+** is undefined.
+**
+** Otherwise, this API returns a negative value if P1 refers to an older
+** snapshot than P2, zero if the two handles refer to the same database
+** snapshot, and a positive value if P1 is a newer snapshot than P2.
+**
+** This interface is only available if SQLite is compiled with the
+** [SQLITE_ENABLE_SNAPSHOT] option.
+*/
+SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
+ sqlite3_snapshot *p1,
+ sqlite3_snapshot *p2
+);
+
+/*
+** CAPI3REF: Recover snapshots from a wal file
+** METHOD: sqlite3_snapshot
+**
+** If a [WAL file] remains on disk after all database connections close
+** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control]
+** or because the last process to have the database opened exited without
+** calling [sqlite3_close()]) and a new connection is subsequently opened
+** on that database and [WAL file], the [sqlite3_snapshot_open()] interface
+** will only be able to open the last transaction added to the WAL file
+** even though the WAL file contains other valid transactions.
+**
+** This function attempts to scan the WAL file associated with database zDb
+** of database handle db and make all valid snapshots available to
+** sqlite3_snapshot_open(). It is an error if there is already a read
+** transaction open on the database, or if the database is not a WAL mode
+** database.
+**
+** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
+**
+** This interface is only available if SQLite is compiled with the
+** [SQLITE_ENABLE_SNAPSHOT] option.
+*/
+SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
+
+/*
+** CAPI3REF: Serialize a database
+**
+** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory
+** that is a serialization of the S database on [database connection] D.
+** If P is not a NULL pointer, then the size of the database in bytes
+** is written into *P.
+**
+** For an ordinary on-disk database file, the serialization is just a
+** copy of the disk file. For an in-memory database or a "TEMP" database,
+** the serialization is the same sequence of bytes which would be written
+** to disk if that database where backed up to disk.
+**
+** The usual case is that sqlite3_serialize() copies the serialization of
+** the database into memory obtained from [sqlite3_malloc64()] and returns
+** a pointer to that memory. The caller is responsible for freeing the
+** returned value to avoid a memory leak. However, if the F argument
+** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations
+** are made, and the sqlite3_serialize() function will return a pointer
+** to the contiguous memory representation of the database that SQLite
+** is currently using for that database, or NULL if the no such contiguous
+** memory representation of the database exists. A contiguous memory
+** representation of the database will usually only exist if there has
+** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
+** values of D and S.
+** The size of the database is written into *P even if the
+** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
+** of the database exists.
+**
+** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
+** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
+** allocation error occurs.
+**
+** This interface is only available if SQLite is compiled with the
+** [SQLITE_ENABLE_DESERIALIZE] option.
+*/
+SQLITE_API unsigned char *sqlite3_serialize(
+ sqlite3 *db, /* The database connection */
+ const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */
+ sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */
+ unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */
+);
+
+/*
+** CAPI3REF: Flags for sqlite3_serialize
+**
+** Zero or more of the following constants can be OR-ed together for
+** the F argument to [sqlite3_serialize(D,S,P,F)].
+**
+** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return
+** a pointer to contiguous in-memory database that it is currently using,
+** without making a copy of the database. If SQLite is not currently using
+** a contiguous in-memory database, then this option causes
+** [sqlite3_serialize()] to return a NULL pointer. SQLite will only be
+** using a contiguous in-memory database if it has been initialized by a
+** prior call to [sqlite3_deserialize()].
+*/
+#define SQLITE_SERIALIZE_NOCOPY 0x001 /* Do no memory allocations */
+
+/*
+** CAPI3REF: Deserialize a database
+**
+** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
+** [database connection] D to disconnect from database S and then
+** reopen S as an in-memory database based on the serialization contained
+** in P. The serialized database P is N bytes in size. M is the size of
+** the buffer P, which might be larger than N. If M is larger than N, and
+** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is
+** permitted to add content to the in-memory database as long as the total
+** size does not exceed M bytes.
+**
+** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
+** invoke sqlite3_free() on the serialization buffer when the database
+** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
+** SQLite will try to increase the buffer size using sqlite3_realloc64()
+** if writes on the database cause it to grow larger than M bytes.
+**
+** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
+** database is currently in a read transaction or is involved in a backup
+** operation.
+**
+** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
+** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
+** [sqlite3_free()] is invoked on argument P prior to returning.
+**
+** This interface is only available if SQLite is compiled with the
+** [SQLITE_ENABLE_DESERIALIZE] option.
+*/
+SQLITE_API int sqlite3_deserialize(
+ sqlite3 *db, /* The database connection */
+ const char *zSchema, /* Which DB to reopen with the deserialization */
+ unsigned char *pData, /* The serialized database content */
+ sqlite3_int64 szDb, /* Number bytes in the deserialization */
+ sqlite3_int64 szBuf, /* Total size of buffer pData[] */
+ unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
+);
+
+/*
+** CAPI3REF: Flags for sqlite3_deserialize()
+**
+** The following are allowed values for 6th argument (the F argument) to
+** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.
+**
+** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization
+** in the P argument is held in memory obtained from [sqlite3_malloc64()]
+** and that SQLite should take ownership of this memory and automatically
+** free it when it has finished using it. Without this flag, the caller
+** is responsible for freeing any dynamically allocated memory.
+**
+** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to
+** grow the size of the database using calls to [sqlite3_realloc64()]. This
+** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.
+** Without this flag, the deserialized database cannot increase in size beyond
+** the number of bytes specified by the M parameter.
+**
+** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database
+** should be treated as read-only.
+*/
+#define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */
+#define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */
+#define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */
+
+/*
+** Undo the hack that converts floating point types to integer for
+** builds on processors without floating point support.
+*/
+#ifdef SQLITE_OMIT_FLOATING_POINT
+# undef double
+#endif
+
+#if 0
+} /* End of the 'extern "C"' block */
+#endif
+#endif /* SQLITE3_H */
+
+/******** Begin file sqlite3rtree.h *********/
+/*
+** 2010 August 30
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+*/
+
+#ifndef _SQLITE3RTREE_H_
+#define _SQLITE3RTREE_H_
+
+
+#if 0
+extern "C" {
+#endif
+
+typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
+typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
+
+/* The double-precision datatype used by RTree depends on the
+** SQLITE_RTREE_INT_ONLY compile-time option.
+*/
+#ifdef SQLITE_RTREE_INT_ONLY
+ typedef sqlite3_int64 sqlite3_rtree_dbl;
+#else
+ typedef double sqlite3_rtree_dbl;
+#endif
+
+/*
+** Register a geometry callback named zGeom that can be used as part of an
+** R-Tree geometry query as follows:
+**
+** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
+*/
+SQLITE_API int sqlite3_rtree_geometry_callback(
+ sqlite3 *db,
+ const char *zGeom,
+ int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
+ void *pContext
+);
+
+
+/*
+** A pointer to a structure of the following type is passed as the first
+** argument to callbacks registered using rtree_geometry_callback().
+*/
+struct sqlite3_rtree_geometry {
+ void *pContext; /* Copy of pContext passed to s_r_g_c() */
+ int nParam; /* Size of array aParam[] */
+ sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
+ void *pUser; /* Callback implementation user data */
+ void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
+};
+
+/*
+** Register a 2nd-generation geometry callback named zScore that can be
+** used as part of an R-Tree geometry query as follows:
+**
+** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
+*/
+SQLITE_API int sqlite3_rtree_query_callback(
+ sqlite3 *db,
+ const char *zQueryFunc,
+ int (*xQueryFunc)(sqlite3_rtree_query_info*),
+ void *pContext,
+ void (*xDestructor)(void*)
+);
+
+
+/*
+** A pointer to a structure of the following type is passed as the
+** argument to scored geometry callback registered using
+** sqlite3_rtree_query_callback().
+**
+** Note that the first 5 fields of this structure are identical to
+** sqlite3_rtree_geometry. This structure is a subclass of
+** sqlite3_rtree_geometry.
+*/
+struct sqlite3_rtree_query_info {
+ void *pContext; /* pContext from when function registered */
+ int nParam; /* Number of function parameters */
+ sqlite3_rtree_dbl *aParam; /* value of function parameters */
+ void *pUser; /* callback can use this, if desired */
+ void (*xDelUser)(void*); /* function to free pUser */
+ sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
+ unsigned int *anQueue; /* Number of pending entries in the queue */
+ int nCoord; /* Number of coordinates */
+ int iLevel; /* Level of current node or entry */
+ int mxLevel; /* The largest iLevel value in the tree */
+ sqlite3_int64 iRowid; /* Rowid for current entry */
+ sqlite3_rtree_dbl rParentScore; /* Score of parent node */
+ int eParentWithin; /* Visibility of parent node */
+ int eWithin; /* OUT: Visibility */
+ sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
+ /* The following fields are only available in 3.8.11 and later */
+ sqlite3_value **apSqlParam; /* Original SQL values of parameters */
+};
+
+/*
+** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
+*/
+#define NOT_WITHIN 0 /* Object completely outside of query region */
+#define PARTLY_WITHIN 1 /* Object partially overlaps query region */
+#define FULLY_WITHIN 2 /* Object fully contained within query region */
+
+
+#if 0
+} /* end of the 'extern "C"' block */
+#endif
+
+#endif /* ifndef _SQLITE3RTREE_H_ */
+
+/******** End of sqlite3rtree.h *********/
+/******** Begin file sqlite3session.h *********/
+
+#if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
+#define __SQLITESESSION_H_ 1
+
+/*
+** Make sure we can call this stuff from C++.
+*/
+#if 0
+extern "C" {
+#endif
+
+
+/*
+** CAPI3REF: Session Object Handle
+**
+** An instance of this object is a [session] that can be used to
+** record changes to a database.
+*/
+typedef struct sqlite3_session sqlite3_session;
+
+/*
+** CAPI3REF: Changeset Iterator Handle
+**
+** An instance of this object acts as a cursor for iterating
+** over the elements of a [changeset] or [patchset].
+*/
+typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
+
+/*
+** CAPI3REF: Create A New Session Object
+** CONSTRUCTOR: sqlite3_session
+**
+** Create a new session object attached to database handle db. If successful,
+** a pointer to the new object is written to *ppSession and SQLITE_OK is
+** returned. If an error occurs, *ppSession is set to NULL and an SQLite
+** error code (e.g. SQLITE_NOMEM) is returned.
+**
+** It is possible to create multiple session objects attached to a single
+** database handle.
+**
+** Session objects created using this function should be deleted using the
+** [sqlite3session_delete()] function before the database handle that they
+** are attached to is itself closed. If the database handle is closed before
+** the session object is deleted, then the results of calling any session
+** module function, including [sqlite3session_delete()] on the session object
+** are undefined.
+**
+** Because the session module uses the [sqlite3_preupdate_hook()] API, it
+** is not possible for an application to register a pre-update hook on a
+** database handle that has one or more session objects attached. Nor is
+** it possible to create a session object attached to a database handle for
+** which a pre-update hook is already defined. The results of attempting
+** either of these things are undefined.
+**
+** The session object will be used to create changesets for tables in
+** database zDb, where zDb is either "main", or "temp", or the name of an
+** attached database. It is not an error if database zDb is not attached
+** to the database when the session object is created.
+*/
+SQLITE_API int sqlite3session_create(
+ sqlite3 *db, /* Database handle */
+ const char *zDb, /* Name of db (e.g. "main") */
+ sqlite3_session **ppSession /* OUT: New session object */
+);
+
+/*
+** CAPI3REF: Delete A Session Object
+** DESTRUCTOR: sqlite3_session
+**
+** Delete a session object previously allocated using
+** [sqlite3session_create()]. Once a session object has been deleted, the
+** results of attempting to use pSession with any other session module
+** function are undefined.
+**
+** Session objects must be deleted before the database handle to which they
+** are attached is closed. Refer to the documentation for
+** [sqlite3session_create()] for details.
+*/
+SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
+
+
+/*
+** CAPI3REF: Enable Or Disable A Session Object
+** METHOD: sqlite3_session
+**
+** Enable or disable the recording of changes by a session object. When
+** enabled, a session object records changes made to the database. When
+** disabled - it does not. A newly created session object is enabled.
+** Refer to the documentation for [sqlite3session_changeset()] for further
+** details regarding how enabling and disabling a session object affects
+** the eventual changesets.
+**
+** Passing zero to this function disables the session. Passing a value
+** greater than zero enables it. Passing a value less than zero is a
+** no-op, and may be used to query the current state of the session.
+**
+** The return value indicates the final state of the session object: 0 if
+** the session is disabled, or 1 if it is enabled.
+*/
+SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
+
+/*
+** CAPI3REF: Set Or Clear the Indirect Change Flag
+** METHOD: sqlite3_session
+**
+** Each change recorded by a session object is marked as either direct or
+** indirect. A change is marked as indirect if either:
+**
+** <ul>
+** <li> The session object "indirect" flag is set when the change is
+** made, or
+** <li> The change is made by an SQL trigger or foreign key action
+** instead of directly as a result of a users SQL statement.
+** </ul>
+**
+** If a single row is affected by more than one operation within a session,
+** then the change is considered indirect if all operations meet the criteria
+** for an indirect change above, or direct otherwise.
+**
+** This function is used to set, clear or query the session object indirect
+** flag. If the second argument passed to this function is zero, then the
+** indirect flag is cleared. If it is greater than zero, the indirect flag
+** is set. Passing a value less than zero does not modify the current value
+** of the indirect flag, and may be used to query the current state of the
+** indirect flag for the specified session object.
+**
+** The return value indicates the final state of the indirect flag: 0 if
+** it is clear, or 1 if it is set.
+*/
+SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
+
+/*
+** CAPI3REF: Attach A Table To A Session Object
+** METHOD: sqlite3_session
+**
+** If argument zTab is not NULL, then it is the name of a table to attach
+** to the session object passed as the first argument. All subsequent changes
+** made to the table while the session object is enabled will be recorded. See
+** documentation for [sqlite3session_changeset()] for further details.
+**
+** Or, if argument zTab is NULL, then changes are recorded for all tables
+** in the database. If additional tables are added to the database (by
+** executing "CREATE TABLE" statements) after this call is made, changes for
+** the new tables are also recorded.
+**
+** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
+** defined as part of their CREATE TABLE statement. It does not matter if the
+** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
+** KEY may consist of a single column, or may be a composite key.
+**
+** It is not an error if the named table does not exist in the database. Nor
+** is it an error if the named table does not have a PRIMARY KEY. However,
+** no changes will be recorded in either of these scenarios.
+**
+** Changes are not recorded for individual rows that have NULL values stored
+** in one or more of their PRIMARY KEY columns.
+**
+** SQLITE_OK is returned if the call completes without error. Or, if an error
+** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
+**
+** <h3>Special sqlite_stat1 Handling</h3>
+**
+** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
+** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
+** <pre>
+** &nbsp; CREATE TABLE sqlite_stat1(tbl,idx,stat)
+** </pre>
+**
+** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
+** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
+** are recorded for rows for which (idx IS NULL) is true. However, for such
+** rows a zero-length blob (SQL value X'') is stored in the changeset or
+** patchset instead of a NULL value. This allows such changesets to be
+** manipulated by legacy implementations of sqlite3changeset_invert(),
+** concat() and similar.
+**
+** The sqlite3changeset_apply() function automatically converts the
+** zero-length blob back to a NULL value when updating the sqlite_stat1
+** table. However, if the application calls sqlite3changeset_new(),
+** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
+** iterator directly (including on a changeset iterator passed to a
+** conflict-handler callback) then the X'' value is returned. The application
+** must translate X'' to NULL itself if required.
+**
+** Legacy (older than 3.22.0) versions of the sessions module cannot capture
+** changes made to the sqlite_stat1 table. Legacy versions of the
+** sqlite3changeset_apply() function silently ignore any modifications to the
+** sqlite_stat1 table that are part of a changeset or patchset.
+*/
+SQLITE_API int sqlite3session_attach(
+ sqlite3_session *pSession, /* Session object */
+ const char *zTab /* Table name */
+);
+
+/*
+** CAPI3REF: Set a table filter on a Session Object.
+** METHOD: sqlite3_session
+**
+** The second argument (xFilter) is the "filter callback". For changes to rows
+** in tables that are not attached to the Session object, the filter is called
+** to determine whether changes to the table's rows should be tracked or not.
+** If xFilter returns 0, changes are not tracked. Note that once a table is
+** attached, xFilter will not be called again.
+*/
+SQLITE_API void sqlite3session_table_filter(
+ sqlite3_session *pSession, /* Session object */
+ int(*xFilter)(
+ void *pCtx, /* Copy of third arg to _filter_table() */
+ const char *zTab /* Table name */
+ ),
+ void *pCtx /* First argument passed to xFilter */
+);
+
+/*
+** CAPI3REF: Generate A Changeset From A Session Object
+** METHOD: sqlite3_session
+**
+** Obtain a changeset containing changes to the tables attached to the
+** session object passed as the first argument. If successful,
+** set *ppChangeset to point to a buffer containing the changeset
+** and *pnChangeset to the size of the changeset in bytes before returning
+** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
+** zero and return an SQLite error code.
+**
+** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
+** each representing a change to a single row of an attached table. An INSERT
+** change contains the values of each field of a new database row. A DELETE
+** contains the original values of each field of a deleted database row. An
+** UPDATE change contains the original values of each field of an updated
+** database row along with the updated values for each updated non-primary-key
+** column. It is not possible for an UPDATE change to represent a change that
+** modifies the values of primary key columns. If such a change is made, it
+** is represented in a changeset as a DELETE followed by an INSERT.
+**
+** Changes are not recorded for rows that have NULL values stored in one or
+** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
+** no corresponding change is present in the changesets returned by this
+** function. If an existing row with one or more NULL values stored in
+** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
+** only an INSERT is appears in the changeset. Similarly, if an existing row
+** with non-NULL PRIMARY KEY values is updated so that one or more of its
+** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
+** DELETE change only.
+**
+** The contents of a changeset may be traversed using an iterator created
+** using the [sqlite3changeset_start()] API. A changeset may be applied to
+** a database with a compatible schema using the [sqlite3changeset_apply()]
+** API.
+**
+** Within a changeset generated by this function, all changes related to a
+** single table are grouped together. In other words, when iterating through
+** a changeset or when applying a changeset to a database, all changes related
+** to a single table are processed before moving on to the next table. Tables
+** are sorted in the same order in which they were attached (or auto-attached)
+** to the sqlite3_session object. The order in which the changes related to
+** a single table are stored is undefined.
+**
+** Following a successful call to this function, it is the responsibility of
+** the caller to eventually free the buffer that *ppChangeset points to using
+** [sqlite3_free()].
+**
+** <h3>Changeset Generation</h3>
+**
+** Once a table has been attached to a session object, the session object
+** records the primary key values of all new rows inserted into the table.
+** It also records the original primary key and other column values of any
+** deleted or updated rows. For each unique primary key value, data is only
+** recorded once - the first time a row with said primary key is inserted,
+** updated or deleted in the lifetime of the session.
+**
+** There is one exception to the previous paragraph: when a row is inserted,
+** updated or deleted, if one or more of its primary key columns contain a
+** NULL value, no record of the change is made.
+**
+** The session object therefore accumulates two types of records - those
+** that consist of primary key values only (created when the user inserts
+** a new record) and those that consist of the primary key values and the
+** original values of other table columns (created when the users deletes
+** or updates a record).
+**
+** When this function is called, the requested changeset is created using
+** both the accumulated records and the current contents of the database
+** file. Specifically:
+**
+** <ul>
+** <li> For each record generated by an insert, the database is queried
+** for a row with a matching primary key. If one is found, an INSERT
+** change is added to the changeset. If no such row is found, no change
+** is added to the changeset.
+**
+** <li> For each record generated by an update or delete, the database is
+** queried for a row with a matching primary key. If such a row is
+** found and one or more of the non-primary key fields have been
+** modified from their original values, an UPDATE change is added to
+** the changeset. Or, if no such row is found in the table, a DELETE
+** change is added to the changeset. If there is a row with a matching
+** primary key in the database, but all fields contain their original
+** values, no change is added to the changeset.
+** </ul>
+**
+** This means, amongst other things, that if a row is inserted and then later
+** deleted while a session object is active, neither the insert nor the delete
+** will be present in the changeset. Or if a row is deleted and then later a
+** row with the same primary key values inserted while a session object is
+** active, the resulting changeset will contain an UPDATE change instead of
+** a DELETE and an INSERT.
+**
+** When a session object is disabled (see the [sqlite3session_enable()] API),
+** it does not accumulate records when rows are inserted, updated or deleted.
+** This may appear to have some counter-intuitive effects if a single row
+** is written to more than once during a session. For example, if a row
+** is inserted while a session object is enabled, then later deleted while
+** the same session object is disabled, no INSERT record will appear in the
+** changeset, even though the delete took place while the session was disabled.
+** Or, if one field of a row is updated while a session is disabled, and
+** another field of the same row is updated while the session is enabled, the
+** resulting changeset will contain an UPDATE change that updates both fields.
+*/
+SQLITE_API int sqlite3session_changeset(
+ sqlite3_session *pSession, /* Session object */
+ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
+ void **ppChangeset /* OUT: Buffer containing changeset */
+);
+
+/*
+** CAPI3REF: Load The Difference Between Tables Into A Session
+** METHOD: sqlite3_session
+**
+** If it is not already attached to the session object passed as the first
+** argument, this function attaches table zTbl in the same manner as the
+** [sqlite3session_attach()] function. If zTbl does not exist, or if it
+** does not have a primary key, this function is a no-op (but does not return
+** an error).
+**
+** Argument zFromDb must be the name of a database ("main", "temp" etc.)
+** attached to the same database handle as the session object that contains
+** a table compatible with the table attached to the session by this function.
+** A table is considered compatible if it:
+**
+** <ul>
+** <li> Has the same name,
+** <li> Has the same set of columns declared in the same order, and
+** <li> Has the same PRIMARY KEY definition.
+** </ul>
+**
+** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
+** are compatible but do not have any PRIMARY KEY columns, it is not an error
+** but no changes are added to the session object. As with other session
+** APIs, tables without PRIMARY KEYs are simply ignored.
+**
+** This function adds a set of changes to the session object that could be
+** used to update the table in database zFrom (call this the "from-table")
+** so that its content is the same as the table attached to the session
+** object (call this the "to-table"). Specifically:
+**
+** <ul>
+** <li> For each row (primary key) that exists in the to-table but not in
+** the from-table, an INSERT record is added to the session object.
+**
+** <li> For each row (primary key) that exists in the to-table but not in
+** the from-table, a DELETE record is added to the session object.
+**
+** <li> For each row (primary key) that exists in both tables, but features
+** different non-PK values in each, an UPDATE record is added to the
+** session.
+** </ul>
+**
+** To clarify, if this function is called and then a changeset constructed
+** using [sqlite3session_changeset()], then after applying that changeset to
+** database zFrom the contents of the two compatible tables would be
+** identical.
+**
+** It an error if database zFrom does not exist or does not contain the
+** required compatible table.
+**
+** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite
+** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
+** may be set to point to a buffer containing an English language error
+** message. It is the responsibility of the caller to free this buffer using
+** sqlite3_free().
+*/
+SQLITE_API int sqlite3session_diff(
+ sqlite3_session *pSession,
+ const char *zFromDb,
+ const char *zTbl,
+ char **pzErrMsg
+);
+
+
+/*
+** CAPI3REF: Generate A Patchset From A Session Object
+** METHOD: sqlite3_session
+**
+** The differences between a patchset and a changeset are that:
+**
+** <ul>
+** <li> DELETE records consist of the primary key fields only. The
+** original values of other fields are omitted.
+** <li> The original values of any modified fields are omitted from
+** UPDATE records.
+** </ul>
+**
+** A patchset blob may be used with up to date versions of all
+** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
+** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
+** attempting to use a patchset blob with old versions of the
+** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
+**
+** Because the non-primary key "old.*" fields are omitted, no
+** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
+** is passed to the sqlite3changeset_apply() API. Other conflict types work
+** in the same way as for changesets.
+**
+** Changes within a patchset are ordered in the same way as for changesets
+** generated by the sqlite3session_changeset() function (i.e. all changes for
+** a single table are grouped together, tables appear in the order in which
+** they were attached to the session object).
+*/
+SQLITE_API int sqlite3session_patchset(
+ sqlite3_session *pSession, /* Session object */
+ int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */
+ void **ppPatchset /* OUT: Buffer containing patchset */
+);
+
+/*
+** CAPI3REF: Test if a changeset has recorded any changes.
+**
+** Return non-zero if no changes to attached tables have been recorded by
+** the session object passed as the first argument. Otherwise, if one or
+** more changes have been recorded, return zero.
+**
+** Even if this function returns zero, it is possible that calling
+** [sqlite3session_changeset()] on the session handle may still return a
+** changeset that contains no changes. This can happen when a row in
+** an attached table is modified and then later on the original values
+** are restored. However, if this function returns non-zero, then it is
+** guaranteed that a call to sqlite3session_changeset() will return a
+** changeset containing zero changes.
+*/
+SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
+
+/*
+** CAPI3REF: Create An Iterator To Traverse A Changeset
+** CONSTRUCTOR: sqlite3_changeset_iter
+**
+** Create an iterator used to iterate through the contents of a changeset.
+** If successful, *pp is set to point to the iterator handle and SQLITE_OK
+** is returned. Otherwise, if an error occurs, *pp is set to zero and an
+** SQLite error code is returned.
+**
+** The following functions can be used to advance and query a changeset
+** iterator created by this function:
+**
+** <ul>
+** <li> [sqlite3changeset_next()]
+** <li> [sqlite3changeset_op()]
+** <li> [sqlite3changeset_new()]
+** <li> [sqlite3changeset_old()]
+** </ul>
+**
+** It is the responsibility of the caller to eventually destroy the iterator
+** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
+** changeset (pChangeset) must remain valid until after the iterator is
+** destroyed.
+**
+** Assuming the changeset blob was created by one of the
+** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
+** [sqlite3changeset_invert()] functions, all changes within the changeset
+** that apply to a single table are grouped together. This means that when
+** an application iterates through a changeset using an iterator created by
+** this function, all changes that relate to a single table are visited
+** consecutively. There is no chance that the iterator will visit a change
+** the applies to table X, then one for table Y, and then later on visit
+** another change for table X.
+**
+** The behavior of sqlite3changeset_start_v2() and its streaming equivalent
+** may be modified by passing a combination of
+** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.
+**
+** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b>
+** and therefore subject to change.
+*/
+SQLITE_API int sqlite3changeset_start(
+ sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
+ int nChangeset, /* Size of changeset blob in bytes */
+ void *pChangeset /* Pointer to blob containing changeset */
+);
+SQLITE_API int sqlite3changeset_start_v2(
+ sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
+ int nChangeset, /* Size of changeset blob in bytes */
+ void *pChangeset, /* Pointer to blob containing changeset */
+ int flags /* SESSION_CHANGESETSTART_* flags */
+);
+
+/*
+** CAPI3REF: Flags for sqlite3changeset_start_v2
+**
+** The following flags may passed via the 4th parameter to
+** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:
+**
+** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
+** Invert the changeset while iterating through it. This is equivalent to
+** inverting a changeset using sqlite3changeset_invert() before applying it.
+** It is an error to specify this flag with a patchset.
+*/
+#define SQLITE_CHANGESETSTART_INVERT 0x0002
+
+
+/*
+** CAPI3REF: Advance A Changeset Iterator
+** METHOD: sqlite3_changeset_iter
+**
+** This function may only be used with iterators created by the function
+** [sqlite3changeset_start()]. If it is called on an iterator passed to
+** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
+** is returned and the call has no effect.
+**
+** Immediately after an iterator is created by sqlite3changeset_start(), it
+** does not point to any change in the changeset. Assuming the changeset
+** is not empty, the first call to this function advances the iterator to
+** point to the first change in the changeset. Each subsequent call advances
+** the iterator to point to the next change in the changeset (if any). If
+** no error occurs and the iterator points to a valid change after a call
+** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
+** Otherwise, if all changes in the changeset have already been visited,
+** SQLITE_DONE is returned.
+**
+** If an error occurs, an SQLite error code is returned. Possible error
+** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
+** SQLITE_NOMEM.
+*/
+SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
+
+/*
+** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
+** METHOD: sqlite3_changeset_iter
+**
+** The pIter argument passed to this function may either be an iterator
+** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
+** created by [sqlite3changeset_start()]. In the latter case, the most recent
+** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
+** is not the case, this function returns [SQLITE_MISUSE].
+**
+** If argument pzTab is not NULL, then *pzTab is set to point to a
+** nul-terminated utf-8 encoded string containing the name of the table
+** affected by the current change. The buffer remains valid until either
+** sqlite3changeset_next() is called on the iterator or until the
+** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
+** set to the number of columns in the table affected by the change. If
+** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
+** is an indirect change, or false (0) otherwise. See the documentation for
+** [sqlite3session_indirect()] for a description of direct and indirect
+** changes. Finally, if pOp is not NULL, then *pOp is set to one of
+** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
+** type of change that the iterator currently points to.
+**
+** If no error occurs, SQLITE_OK is returned. If an error does occur, an
+** SQLite error code is returned. The values of the output variables may not
+** be trusted in this case.
+*/
+SQLITE_API int sqlite3changeset_op(
+ sqlite3_changeset_iter *pIter, /* Iterator object */
+ const char **pzTab, /* OUT: Pointer to table name */
+ int *pnCol, /* OUT: Number of columns in table */
+ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
+ int *pbIndirect /* OUT: True for an 'indirect' change */
+);
+
+/*
+** CAPI3REF: Obtain The Primary Key Definition Of A Table
+** METHOD: sqlite3_changeset_iter
+**
+** For each modified table, a changeset includes the following:
+**
+** <ul>
+** <li> The number of columns in the table, and
+** <li> Which of those columns make up the tables PRIMARY KEY.
+** </ul>
+**
+** This function is used to find which columns comprise the PRIMARY KEY of
+** the table modified by the change that iterator pIter currently points to.
+** If successful, *pabPK is set to point to an array of nCol entries, where
+** nCol is the number of columns in the table. Elements of *pabPK are set to
+** 0x01 if the corresponding column is part of the tables primary key, or
+** 0x00 if it is not.
+**
+** If argument pnCol is not NULL, then *pnCol is set to the number of columns
+** in the table.
+**
+** If this function is called when the iterator does not point to a valid
+** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
+** SQLITE_OK is returned and the output variables populated as described
+** above.
+*/
+SQLITE_API int sqlite3changeset_pk(
+ sqlite3_changeset_iter *pIter, /* Iterator object */
+ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
+ int *pnCol /* OUT: Number of entries in output array */
+);
+
+/*
+** CAPI3REF: Obtain old.* Values From A Changeset Iterator
+** METHOD: sqlite3_changeset_iter
+**
+** The pIter argument passed to this function may either be an iterator
+** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
+** created by [sqlite3changeset_start()]. In the latter case, the most recent
+** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
+** Furthermore, it may only be called if the type of change that the iterator
+** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
+** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
+**
+** Argument iVal must be greater than or equal to 0, and less than the number
+** of columns in the table affected by the current change. Otherwise,
+** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
+**
+** If successful, this function sets *ppValue to point to a protected
+** sqlite3_value object containing the iVal'th value from the vector of
+** original row values stored as part of the UPDATE or DELETE change and
+** returns SQLITE_OK. The name of the function comes from the fact that this
+** is similar to the "old.*" columns available to update or delete triggers.
+**
+** If some other error occurs (e.g. an OOM condition), an SQLite error code
+** is returned and *ppValue is set to NULL.
+*/
+SQLITE_API int sqlite3changeset_old(
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ int iVal, /* Column number */
+ sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
+);
+
+/*
+** CAPI3REF: Obtain new.* Values From A Changeset Iterator
+** METHOD: sqlite3_changeset_iter
+**
+** The pIter argument passed to this function may either be an iterator
+** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
+** created by [sqlite3changeset_start()]. In the latter case, the most recent
+** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
+** Furthermore, it may only be called if the type of change that the iterator
+** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
+** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
+**
+** Argument iVal must be greater than or equal to 0, and less than the number
+** of columns in the table affected by the current change. Otherwise,
+** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
+**
+** If successful, this function sets *ppValue to point to a protected
+** sqlite3_value object containing the iVal'th value from the vector of
+** new row values stored as part of the UPDATE or INSERT change and
+** returns SQLITE_OK. If the change is an UPDATE and does not include
+** a new value for the requested column, *ppValue is set to NULL and
+** SQLITE_OK returned. The name of the function comes from the fact that
+** this is similar to the "new.*" columns available to update or delete
+** triggers.
+**
+** If some other error occurs (e.g. an OOM condition), an SQLite error code
+** is returned and *ppValue is set to NULL.
+*/
+SQLITE_API int sqlite3changeset_new(
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ int iVal, /* Column number */
+ sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
+);
+
+/*
+** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
+** METHOD: sqlite3_changeset_iter
+**
+** This function should only be used with iterator objects passed to a
+** conflict-handler callback by [sqlite3changeset_apply()] with either
+** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
+** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
+** is set to NULL.
+**
+** Argument iVal must be greater than or equal to 0, and less than the number
+** of columns in the table affected by the current change. Otherwise,
+** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
+**
+** If successful, this function sets *ppValue to point to a protected
+** sqlite3_value object containing the iVal'th value from the
+** "conflicting row" associated with the current conflict-handler callback
+** and returns SQLITE_OK.
+**
+** If some other error occurs (e.g. an OOM condition), an SQLite error code
+** is returned and *ppValue is set to NULL.
+*/
+SQLITE_API int sqlite3changeset_conflict(
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ int iVal, /* Column number */
+ sqlite3_value **ppValue /* OUT: Value from conflicting row */
+);
+
+/*
+** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
+** METHOD: sqlite3_changeset_iter
+**
+** This function may only be called with an iterator passed to an
+** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
+** it sets the output variable to the total number of known foreign key
+** violations in the destination database and returns SQLITE_OK.
+**
+** In all other cases this function returns SQLITE_MISUSE.
+*/
+SQLITE_API int sqlite3changeset_fk_conflicts(
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ int *pnOut /* OUT: Number of FK violations */
+);
+
+
+/*
+** CAPI3REF: Finalize A Changeset Iterator
+** METHOD: sqlite3_changeset_iter
+**
+** This function is used to finalize an iterator allocated with
+** [sqlite3changeset_start()].
+**
+** This function should only be called on iterators created using the
+** [sqlite3changeset_start()] function. If an application calls this
+** function with an iterator passed to a conflict-handler by
+** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
+** call has no effect.
+**
+** If an error was encountered within a call to an sqlite3changeset_xxx()
+** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
+** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
+** to that error is returned by this function. Otherwise, SQLITE_OK is
+** returned. This is to allow the following pattern (pseudo-code):
+**
+** <pre>
+** sqlite3changeset_start();
+** while( SQLITE_ROW==sqlite3changeset_next() ){
+** // Do something with change.
+** }
+** rc = sqlite3changeset_finalize();
+** if( rc!=SQLITE_OK ){
+** // An error has occurred
+** }
+** </pre>
+*/
+SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
+
+/*
+** CAPI3REF: Invert A Changeset
+**
+** This function is used to "invert" a changeset object. Applying an inverted
+** changeset to a database reverses the effects of applying the uninverted
+** changeset. Specifically:
+**
+** <ul>
+** <li> Each DELETE change is changed to an INSERT, and
+** <li> Each INSERT change is changed to a DELETE, and
+** <li> For each UPDATE change, the old.* and new.* values are exchanged.
+** </ul>
+**
+** This function does not change the order in which changes appear within
+** the changeset. It merely reverses the sense of each individual change.
+**
+** If successful, a pointer to a buffer containing the inverted changeset
+** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
+** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
+** zeroed and an SQLite error code returned.
+**
+** It is the responsibility of the caller to eventually call sqlite3_free()
+** on the *ppOut pointer to free the buffer allocation following a successful
+** call to this function.
+**
+** WARNING/TODO: This function currently assumes that the input is a valid
+** changeset. If it is not, the results are undefined.
+*/
+SQLITE_API int sqlite3changeset_invert(
+ int nIn, const void *pIn, /* Input changeset */
+ int *pnOut, void **ppOut /* OUT: Inverse of input */
+);
+
+/*
+** CAPI3REF: Concatenate Two Changeset Objects
+**
+** This function is used to concatenate two changesets, A and B, into a
+** single changeset. The result is a changeset equivalent to applying
+** changeset A followed by changeset B.
+**
+** This function combines the two input changesets using an
+** sqlite3_changegroup object. Calling it produces similar results as the
+** following code fragment:
+**
+** <pre>
+** sqlite3_changegroup *pGrp;
+** rc = sqlite3_changegroup_new(&pGrp);
+** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
+** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
+** if( rc==SQLITE_OK ){
+** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
+** }else{
+** *ppOut = 0;
+** *pnOut = 0;
+** }
+** </pre>
+**
+** Refer to the sqlite3_changegroup documentation below for details.
+*/
+SQLITE_API int sqlite3changeset_concat(
+ int nA, /* Number of bytes in buffer pA */
+ void *pA, /* Pointer to buffer containing changeset A */
+ int nB, /* Number of bytes in buffer pB */
+ void *pB, /* Pointer to buffer containing changeset B */
+ int *pnOut, /* OUT: Number of bytes in output changeset */
+ void **ppOut /* OUT: Buffer containing output changeset */
+);
+
+
+/*
+** CAPI3REF: Changegroup Handle
+**
+** A changegroup is an object used to combine two or more
+** [changesets] or [patchsets]
+*/
+typedef struct sqlite3_changegroup sqlite3_changegroup;
+
+/*
+** CAPI3REF: Create A New Changegroup Object
+** CONSTRUCTOR: sqlite3_changegroup
+**
+** An sqlite3_changegroup object is used to combine two or more changesets
+** (or patchsets) into a single changeset (or patchset). A single changegroup
+** object may combine changesets or patchsets, but not both. The output is
+** always in the same format as the input.
+**
+** If successful, this function returns SQLITE_OK and populates (*pp) with
+** a pointer to a new sqlite3_changegroup object before returning. The caller
+** should eventually free the returned object using a call to
+** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
+** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
+**
+** The usual usage pattern for an sqlite3_changegroup object is as follows:
+**
+** <ul>
+** <li> It is created using a call to sqlite3changegroup_new().
+**
+** <li> Zero or more changesets (or patchsets) are added to the object
+** by calling sqlite3changegroup_add().
+**
+** <li> The result of combining all input changesets together is obtained
+** by the application via a call to sqlite3changegroup_output().
+**
+** <li> The object is deleted using a call to sqlite3changegroup_delete().
+** </ul>
+**
+** Any number of calls to add() and output() may be made between the calls to
+** new() and delete(), and in any order.
+**
+** As well as the regular sqlite3changegroup_add() and
+** sqlite3changegroup_output() functions, also available are the streaming
+** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
+*/
+SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
+
+/*
+** CAPI3REF: Add A Changeset To A Changegroup
+** METHOD: sqlite3_changegroup
+**
+** Add all changes within the changeset (or patchset) in buffer pData (size
+** nData bytes) to the changegroup.
+**
+** If the buffer contains a patchset, then all prior calls to this function
+** on the same changegroup object must also have specified patchsets. Or, if
+** the buffer contains a changeset, so must have the earlier calls to this
+** function. Otherwise, SQLITE_ERROR is returned and no changes are added
+** to the changegroup.
+**
+** Rows within the changeset and changegroup are identified by the values in
+** their PRIMARY KEY columns. A change in the changeset is considered to
+** apply to the same row as a change already present in the changegroup if
+** the two rows have the same primary key.
+**
+** Changes to rows that do not already appear in the changegroup are
+** simply copied into it. Or, if both the new changeset and the changegroup
+** contain changes that apply to a single row, the final contents of the
+** changegroup depends on the type of each change, as follows:
+**
+** <table border=1 style="margin-left:8ex;margin-right:8ex">
+** <tr><th style="white-space:pre">Existing Change </th>
+** <th style="white-space:pre">New Change </th>
+** <th>Output Change
+** <tr><td>INSERT <td>INSERT <td>
+** The new change is ignored. This case does not occur if the new
+** changeset was recorded immediately after the changesets already
+** added to the changegroup.
+** <tr><td>INSERT <td>UPDATE <td>
+** The INSERT change remains in the changegroup. The values in the
+** INSERT change are modified as if the row was inserted by the
+** existing change and then updated according to the new change.
+** <tr><td>INSERT <td>DELETE <td>
+** The existing INSERT is removed from the changegroup. The DELETE is
+** not added.
+** <tr><td>UPDATE <td>INSERT <td>
+** The new change is ignored. This case does not occur if the new
+** changeset was recorded immediately after the changesets already
+** added to the changegroup.
+** <tr><td>UPDATE <td>UPDATE <td>
+** The existing UPDATE remains within the changegroup. It is amended
+** so that the accompanying values are as if the row was updated once
+** by the existing change and then again by the new change.
+** <tr><td>UPDATE <td>DELETE <td>
+** The existing UPDATE is replaced by the new DELETE within the
+** changegroup.
+** <tr><td>DELETE <td>INSERT <td>
+** If one or more of the column values in the row inserted by the
+** new change differ from those in the row deleted by the existing
+** change, the existing DELETE is replaced by an UPDATE within the
+** changegroup. Otherwise, if the inserted row is exactly the same
+** as the deleted row, the existing DELETE is simply discarded.
+** <tr><td>DELETE <td>UPDATE <td>
+** The new change is ignored. This case does not occur if the new
+** changeset was recorded immediately after the changesets already
+** added to the changegroup.
+** <tr><td>DELETE <td>DELETE <td>
+** The new change is ignored. This case does not occur if the new
+** changeset was recorded immediately after the changesets already
+** added to the changegroup.
+** </table>
+**
+** If the new changeset contains changes to a table that is already present
+** in the changegroup, then the number of columns and the position of the
+** primary key columns for the table must be consistent. If this is not the
+** case, this function fails with SQLITE_SCHEMA. If the input changeset
+** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
+** returned. Or, if an out-of-memory condition occurs during processing, this
+** function returns SQLITE_NOMEM. In all cases, if an error occurs the state
+** of the final contents of the changegroup is undefined.
+**
+** If no error occurs, SQLITE_OK is returned.
+*/
+SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
+
+/*
+** CAPI3REF: Obtain A Composite Changeset From A Changegroup
+** METHOD: sqlite3_changegroup
+**
+** Obtain a buffer containing a changeset (or patchset) representing the
+** current contents of the changegroup. If the inputs to the changegroup
+** were themselves changesets, the output is a changeset. Or, if the
+** inputs were patchsets, the output is also a patchset.
+**
+** As with the output of the sqlite3session_changeset() and
+** sqlite3session_patchset() functions, all changes related to a single
+** table are grouped together in the output of this function. Tables appear
+** in the same order as for the very first changeset added to the changegroup.
+** If the second or subsequent changesets added to the changegroup contain
+** changes for tables that do not appear in the first changeset, they are
+** appended onto the end of the output changeset, again in the order in
+** which they are first encountered.
+**
+** If an error occurs, an SQLite error code is returned and the output
+** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
+** is returned and the output variables are set to the size of and a
+** pointer to the output buffer, respectively. In this case it is the
+** responsibility of the caller to eventually free the buffer using a
+** call to sqlite3_free().
+*/
+SQLITE_API int sqlite3changegroup_output(
+ sqlite3_changegroup*,
+ int *pnData, /* OUT: Size of output buffer in bytes */
+ void **ppData /* OUT: Pointer to output buffer */
+);
+
+/*
+** CAPI3REF: Delete A Changegroup Object
+** DESTRUCTOR: sqlite3_changegroup
+*/
+SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
+
+/*
+** CAPI3REF: Apply A Changeset To A Database
+**
+** Apply a changeset or patchset to a database. These functions attempt to
+** update the "main" database attached to handle db with the changes found in
+** the changeset passed via the second and third arguments.
+**
+** The fourth argument (xFilter) passed to these functions is the "filter
+** callback". If it is not NULL, then for each table affected by at least one
+** change in the changeset, the filter callback is invoked with
+** the table name as the second argument, and a copy of the context pointer
+** passed as the sixth argument as the first. If the "filter callback"
+** returns zero, then no attempt is made to apply any changes to the table.
+** Otherwise, if the return value is non-zero or the xFilter argument to
+** is NULL, all changes related to the table are attempted.
+**
+** For each table that is not excluded by the filter callback, this function
+** tests that the target database contains a compatible table. A table is
+** considered compatible if all of the following are true:
+**
+** <ul>
+** <li> The table has the same name as the name recorded in the
+** changeset, and
+** <li> The table has at least as many columns as recorded in the
+** changeset, and
+** <li> The table has primary key columns in the same position as
+** recorded in the changeset.
+** </ul>
+**
+** If there is no compatible table, it is not an error, but none of the
+** changes associated with the table are applied. A warning message is issued
+** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
+** one such warning is issued for each table in the changeset.
+**
+** For each change for which there is a compatible table, an attempt is made
+** to modify the table contents according to the UPDATE, INSERT or DELETE
+** change. If a change cannot be applied cleanly, the conflict handler
+** function passed as the fifth argument to sqlite3changeset_apply() may be
+** invoked. A description of exactly when the conflict handler is invoked for
+** each type of change is below.
+**
+** Unlike the xFilter argument, xConflict may not be passed NULL. The results
+** of passing anything other than a valid function pointer as the xConflict
+** argument are undefined.
+**
+** Each time the conflict handler function is invoked, it must return one
+** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
+** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
+** if the second argument passed to the conflict handler is either
+** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
+** returns an illegal value, any changes already made are rolled back and
+** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
+** actions are taken by sqlite3changeset_apply() depending on the value
+** returned by each invocation of the conflict-handler function. Refer to
+** the documentation for the three
+** [SQLITE_CHANGESET_OMIT|available return values] for details.
+**
+** <dl>
+** <dt>DELETE Changes<dd>
+** For each DELETE change, the function checks if the target database
+** contains a row with the same primary key value (or values) as the
+** original row values stored in the changeset. If it does, and the values
+** stored in all non-primary key columns also match the values stored in
+** the changeset the row is deleted from the target database.
+**
+** If a row with matching primary key values is found, but one or more of
+** the non-primary key fields contains a value different from the original
+** row value stored in the changeset, the conflict-handler function is
+** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
+** database table has more columns than are recorded in the changeset,
+** only the values of those non-primary key fields are compared against
+** the current database contents - any trailing database table columns
+** are ignored.
+**
+** If no row with matching primary key values is found in the database,
+** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
+** passed as the second argument.
+**
+** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
+** (which can only happen if a foreign key constraint is violated), the
+** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
+** passed as the second argument. This includes the case where the DELETE
+** operation is attempted because an earlier call to the conflict handler
+** function returned [SQLITE_CHANGESET_REPLACE].
+**
+** <dt>INSERT Changes<dd>
+** For each INSERT change, an attempt is made to insert the new row into
+** the database. If the changeset row contains fewer fields than the
+** database table, the trailing fields are populated with their default
+** values.
+**
+** If the attempt to insert the row fails because the database already
+** contains a row with the same primary key values, the conflict handler
+** function is invoked with the second argument set to
+** [SQLITE_CHANGESET_CONFLICT].
+**
+** If the attempt to insert the row fails because of some other constraint
+** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
+** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
+** This includes the case where the INSERT operation is re-attempted because
+** an earlier call to the conflict handler function returned
+** [SQLITE_CHANGESET_REPLACE].
+**
+** <dt>UPDATE Changes<dd>
+** For each UPDATE change, the function checks if the target database
+** contains a row with the same primary key value (or values) as the
+** original row values stored in the changeset. If it does, and the values
+** stored in all modified non-primary key columns also match the values
+** stored in the changeset the row is updated within the target database.
+**
+** If a row with matching primary key values is found, but one or more of
+** the modified non-primary key fields contains a value different from an
+** original row value stored in the changeset, the conflict-handler function
+** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
+** UPDATE changes only contain values for non-primary key fields that are
+** to be modified, only those fields need to match the original values to
+** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
+**
+** If no row with matching primary key values is found in the database,
+** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
+** passed as the second argument.
+**
+** If the UPDATE operation is attempted, but SQLite returns
+** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
+** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
+** This includes the case where the UPDATE operation is attempted after
+** an earlier call to the conflict handler function returned
+** [SQLITE_CHANGESET_REPLACE].
+** </dl>
+**
+** It is safe to execute SQL statements, including those that write to the
+** table that the callback related to, from within the xConflict callback.
+** This can be used to further customize the application's conflict
+** resolution strategy.
+**
+** All changes made by these functions are enclosed in a savepoint transaction.
+** If any other error (aside from a constraint failure when attempting to
+** write to the target database) occurs, then the savepoint transaction is
+** rolled back, restoring the target database to its original state, and an
+** SQLite error code returned.
+**
+** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
+** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
+** may set (*ppRebase) to point to a "rebase" that may be used with the
+** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
+** is set to the size of the buffer in bytes. It is the responsibility of the
+** caller to eventually free any such buffer using sqlite3_free(). The buffer
+** is only allocated and populated if one or more conflicts were encountered
+** while applying the patchset. See comments surrounding the sqlite3_rebaser
+** APIs for further details.
+**
+** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent
+** may be modified by passing a combination of
+** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.
+**
+** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>
+** and therefore subject to change.
+*/
+SQLITE_API int sqlite3changeset_apply(
+ sqlite3 *db, /* Apply change to "main" db of this handle */
+ int nChangeset, /* Size of changeset in bytes */
+ void *pChangeset, /* Changeset blob */
+ int(*xFilter)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ const char *zTab /* Table name */
+ ),
+ int(*xConflict)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
+ ),
+ void *pCtx /* First argument passed to xConflict */
+);
+SQLITE_API int sqlite3changeset_apply_v2(
+ sqlite3 *db, /* Apply change to "main" db of this handle */
+ int nChangeset, /* Size of changeset in bytes */
+ void *pChangeset, /* Changeset blob */
+ int(*xFilter)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ const char *zTab /* Table name */
+ ),
+ int(*xConflict)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
+ ),
+ void *pCtx, /* First argument passed to xConflict */
+ void **ppRebase, int *pnRebase, /* OUT: Rebase data */
+ int flags /* SESSION_CHANGESETAPPLY_* flags */
+);
+
+/*
+** CAPI3REF: Flags for sqlite3changeset_apply_v2
+**
+** The following flags may passed via the 9th parameter to
+** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:
+**
+** <dl>
+** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>
+** Usually, the sessions module encloses all operations performed by
+** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The
+** SAVEPOINT is committed if the changeset or patchset is successfully
+** applied, or rolled back if an error occurs. Specifying this flag
+** causes the sessions module to omit this savepoint. In this case, if the
+** caller has an open transaction or savepoint when apply_v2() is called,
+** it may revert the partially applied changeset by rolling it back.
+**
+** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
+** Invert the changeset before applying it. This is equivalent to inverting
+** a changeset using sqlite3changeset_invert() before applying it. It is
+** an error to specify this flag with a patchset.
+*/
+#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001
+#define SQLITE_CHANGESETAPPLY_INVERT 0x0002
+
+/*
+** CAPI3REF: Constants Passed To The Conflict Handler
+**
+** Values that may be passed as the second argument to a conflict-handler.
+**
+** <dl>
+** <dt>SQLITE_CHANGESET_DATA<dd>
+** The conflict handler is invoked with CHANGESET_DATA as the second argument
+** when processing a DELETE or UPDATE change if a row with the required
+** PRIMARY KEY fields is present in the database, but one or more other
+** (non primary-key) fields modified by the update do not contain the
+** expected "before" values.
+**
+** The conflicting row, in this case, is the database row with the matching
+** primary key.
+**
+** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
+** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
+** argument when processing a DELETE or UPDATE change if a row with the
+** required PRIMARY KEY fields is not present in the database.
+**
+** There is no conflicting row in this case. The results of invoking the
+** sqlite3changeset_conflict() API are undefined.
+**
+** <dt>SQLITE_CHANGESET_CONFLICT<dd>
+** CHANGESET_CONFLICT is passed as the second argument to the conflict
+** handler while processing an INSERT change if the operation would result
+** in duplicate primary key values.
+**
+** The conflicting row in this case is the database row with the matching
+** primary key.
+**
+** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
+** If foreign key handling is enabled, and applying a changeset leaves the
+** database in a state containing foreign key violations, the conflict
+** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
+** exactly once before the changeset is committed. If the conflict handler
+** returns CHANGESET_OMIT, the changes, including those that caused the
+** foreign key constraint violation, are committed. Or, if it returns
+** CHANGESET_ABORT, the changeset is rolled back.
+**
+** No current or conflicting row information is provided. The only function
+** it is possible to call on the supplied sqlite3_changeset_iter handle
+** is sqlite3changeset_fk_conflicts().
+**
+** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
+** If any other constraint violation occurs while applying a change (i.e.
+** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
+** invoked with CHANGESET_CONSTRAINT as the second argument.
+**
+** There is no conflicting row in this case. The results of invoking the
+** sqlite3changeset_conflict() API are undefined.
+**
+** </dl>
+*/
+#define SQLITE_CHANGESET_DATA 1
+#define SQLITE_CHANGESET_NOTFOUND 2
+#define SQLITE_CHANGESET_CONFLICT 3
+#define SQLITE_CHANGESET_CONSTRAINT 4
+#define SQLITE_CHANGESET_FOREIGN_KEY 5
+
+/*
+** CAPI3REF: Constants Returned By The Conflict Handler
+**
+** A conflict handler callback must return one of the following three values.
+**
+** <dl>
+** <dt>SQLITE_CHANGESET_OMIT<dd>
+** If a conflict handler returns this value no special action is taken. The
+** change that caused the conflict is not applied. The session module
+** continues to the next change in the changeset.
+**
+** <dt>SQLITE_CHANGESET_REPLACE<dd>
+** This value may only be returned if the second argument to the conflict
+** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
+** is not the case, any changes applied so far are rolled back and the
+** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
+**
+** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
+** handler, then the conflicting row is either updated or deleted, depending
+** on the type of change.
+**
+** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
+** handler, then the conflicting row is removed from the database and a
+** second attempt to apply the change is made. If this second attempt fails,
+** the original row is restored to the database before continuing.
+**
+** <dt>SQLITE_CHANGESET_ABORT<dd>
+** If this value is returned, any changes applied so far are rolled back
+** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
+** </dl>
+*/
+#define SQLITE_CHANGESET_OMIT 0
+#define SQLITE_CHANGESET_REPLACE 1
+#define SQLITE_CHANGESET_ABORT 2
+
+/*
+** CAPI3REF: Rebasing changesets
+** EXPERIMENTAL
+**
+** Suppose there is a site hosting a database in state S0. And that
+** modifications are made that move that database to state S1 and a
+** changeset recorded (the "local" changeset). Then, a changeset based
+** on S0 is received from another site (the "remote" changeset) and
+** applied to the database. The database is then in state
+** (S1+"remote"), where the exact state depends on any conflict
+** resolution decisions (OMIT or REPLACE) made while applying "remote".
+** Rebasing a changeset is to update it to take those conflict
+** resolution decisions into account, so that the same conflicts
+** do not have to be resolved elsewhere in the network.
+**
+** For example, if both the local and remote changesets contain an
+** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
+**
+** local: INSERT INTO t1 VALUES(1, 'v1');
+** remote: INSERT INTO t1 VALUES(1, 'v2');
+**
+** and the conflict resolution is REPLACE, then the INSERT change is
+** removed from the local changeset (it was overridden). Or, if the
+** conflict resolution was "OMIT", then the local changeset is modified
+** to instead contain:
+**
+** UPDATE t1 SET b = 'v2' WHERE a=1;
+**
+** Changes within the local changeset are rebased as follows:
+**
+** <dl>
+** <dt>Local INSERT<dd>
+** This may only conflict with a remote INSERT. If the conflict
+** resolution was OMIT, then add an UPDATE change to the rebased
+** changeset. Or, if the conflict resolution was REPLACE, add
+** nothing to the rebased changeset.
+**
+** <dt>Local DELETE<dd>
+** This may conflict with a remote UPDATE or DELETE. In both cases the
+** only possible resolution is OMIT. If the remote operation was a
+** DELETE, then add no change to the rebased changeset. If the remote
+** operation was an UPDATE, then the old.* fields of change are updated
+** to reflect the new.* values in the UPDATE.
+**
+** <dt>Local UPDATE<dd>
+** This may conflict with a remote UPDATE or DELETE. If it conflicts
+** with a DELETE, and the conflict resolution was OMIT, then the update
+** is changed into an INSERT. Any undefined values in the new.* record
+** from the update change are filled in using the old.* values from
+** the conflicting DELETE. Or, if the conflict resolution was REPLACE,
+** the UPDATE change is simply omitted from the rebased changeset.
+**
+** If conflict is with a remote UPDATE and the resolution is OMIT, then
+** the old.* values are rebased using the new.* values in the remote
+** change. Or, if the resolution is REPLACE, then the change is copied
+** into the rebased changeset with updates to columns also updated by
+** the conflicting remote UPDATE removed. If this means no columns would
+** be updated, the change is omitted.
+** </dl>
+**
+** A local change may be rebased against multiple remote changes
+** simultaneously. If a single key is modified by multiple remote
+** changesets, they are combined as follows before the local changeset
+** is rebased:
+**
+** <ul>
+** <li> If there has been one or more REPLACE resolutions on a
+** key, it is rebased according to a REPLACE.
+**
+** <li> If there have been no REPLACE resolutions on a key, then
+** the local changeset is rebased according to the most recent
+** of the OMIT resolutions.
+** </ul>
+**
+** Note that conflict resolutions from multiple remote changesets are
+** combined on a per-field basis, not per-row. This means that in the
+** case of multiple remote UPDATE operations, some fields of a single
+** local change may be rebased for REPLACE while others are rebased for
+** OMIT.
+**
+** In order to rebase a local changeset, the remote changeset must first
+** be applied to the local database using sqlite3changeset_apply_v2() and
+** the buffer of rebase information captured. Then:
+**
+** <ol>
+** <li> An sqlite3_rebaser object is created by calling
+** sqlite3rebaser_create().
+** <li> The new object is configured with the rebase buffer obtained from
+** sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
+** If the local changeset is to be rebased against multiple remote
+** changesets, then sqlite3rebaser_configure() should be called
+** multiple times, in the same order that the multiple
+** sqlite3changeset_apply_v2() calls were made.
+** <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().
+** <li> The sqlite3_rebaser object is deleted by calling
+** sqlite3rebaser_delete().
+** </ol>
+*/
+typedef struct sqlite3_rebaser sqlite3_rebaser;
+
+/*
+** CAPI3REF: Create a changeset rebaser object.
+** EXPERIMENTAL
+**
+** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
+** point to the new object and return SQLITE_OK. Otherwise, if an error
+** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
+** to NULL.
+*/
+SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
+
+/*
+** CAPI3REF: Configure a changeset rebaser object.
+** EXPERIMENTAL
+**
+** Configure the changeset rebaser object to rebase changesets according
+** to the conflict resolutions described by buffer pRebase (size nRebase
+** bytes), which must have been obtained from a previous call to
+** sqlite3changeset_apply_v2().
+*/
+SQLITE_API int sqlite3rebaser_configure(
+ sqlite3_rebaser*,
+ int nRebase, const void *pRebase
+);
+
+/*
+** CAPI3REF: Rebase a changeset
+** EXPERIMENTAL
+**
+** Argument pIn must point to a buffer containing a changeset nIn bytes
+** in size. This function allocates and populates a buffer with a copy
+** of the changeset rebased according to the configuration of the
+** rebaser object passed as the first argument. If successful, (*ppOut)
+** is set to point to the new buffer containing the rebased changeset and
+** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
+** responsibility of the caller to eventually free the new buffer using
+** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
+** are set to zero and an SQLite error code returned.
+*/
+SQLITE_API int sqlite3rebaser_rebase(
+ sqlite3_rebaser*,
+ int nIn, const void *pIn,
+ int *pnOut, void **ppOut
+);
+
+/*
+** CAPI3REF: Delete a changeset rebaser object.
+** EXPERIMENTAL
+**
+** Delete the changeset rebaser object and all associated resources. There
+** should be one call to this function for each successful invocation
+** of sqlite3rebaser_create().
+*/
+SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
+
+/*
+** CAPI3REF: Streaming Versions of API functions.
+**
+** The six streaming API xxx_strm() functions serve similar purposes to the
+** corresponding non-streaming API functions:
+**
+** <table border=1 style="margin-left:8ex;margin-right:8ex">
+** <tr><th>Streaming function<th>Non-streaming equivalent</th>
+** <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
+** <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2]
+** <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
+** <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
+** <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
+** <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
+** <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
+** </table>
+**
+** Non-streaming functions that accept changesets (or patchsets) as input
+** require that the entire changeset be stored in a single buffer in memory.
+** Similarly, those that return a changeset or patchset do so by returning
+** a pointer to a single large buffer allocated using sqlite3_malloc().
+** Normally this is convenient. However, if an application running in a
+** low-memory environment is required to handle very large changesets, the
+** large contiguous memory allocations required can become onerous.
+**
+** In order to avoid this problem, instead of a single large buffer, input
+** is passed to a streaming API functions by way of a callback function that
+** the sessions module invokes to incrementally request input data as it is
+** required. In all cases, a pair of API function parameters such as
+**
+** <pre>
+** &nbsp; int nChangeset,
+** &nbsp; void *pChangeset,
+** </pre>
+**
+** Is replaced by:
+**
+** <pre>
+** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
+** &nbsp; void *pIn,
+** </pre>
+**
+** Each time the xInput callback is invoked by the sessions module, the first
+** argument passed is a copy of the supplied pIn context pointer. The second
+** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
+** error occurs the xInput method should copy up to (*pnData) bytes of data
+** into the buffer and set (*pnData) to the actual number of bytes copied
+** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
+** should be set to zero to indicate this. Or, if an error occurs, an SQLite
+** error code should be returned. In all cases, if an xInput callback returns
+** an error, all processing is abandoned and the streaming API function
+** returns a copy of the error code to the caller.
+**
+** In the case of sqlite3changeset_start_strm(), the xInput callback may be
+** invoked by the sessions module at any point during the lifetime of the
+** iterator. If such an xInput callback returns an error, the iterator enters
+** an error state, whereby all subsequent calls to iterator functions
+** immediately fail with the same error code as returned by xInput.
+**
+** Similarly, streaming API functions that return changesets (or patchsets)
+** return them in chunks by way of a callback function instead of via a
+** pointer to a single large buffer. In this case, a pair of parameters such
+** as:
+**
+** <pre>
+** &nbsp; int *pnChangeset,
+** &nbsp; void **ppChangeset,
+** </pre>
+**
+** Is replaced by:
+**
+** <pre>
+** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
+** &nbsp; void *pOut
+** </pre>
+**
+** The xOutput callback is invoked zero or more times to return data to
+** the application. The first parameter passed to each call is a copy of the
+** pOut pointer supplied by the application. The second parameter, pData,
+** points to a buffer nData bytes in size containing the chunk of output
+** data being returned. If the xOutput callback successfully processes the
+** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
+** it should return some other SQLite error code. In this case processing
+** is immediately abandoned and the streaming API function returns a copy
+** of the xOutput error code to the application.
+**
+** The sessions module never invokes an xOutput callback with the third
+** parameter set to a value less than or equal to zero. Other than this,
+** no guarantees are made as to the size of the chunks of data returned.
+*/
+SQLITE_API int sqlite3changeset_apply_strm(
+ sqlite3 *db, /* Apply change to "main" db of this handle */
+ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
+ void *pIn, /* First arg for xInput */
+ int(*xFilter)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ const char *zTab /* Table name */
+ ),
+ int(*xConflict)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
+ ),
+ void *pCtx /* First argument passed to xConflict */
+);
+SQLITE_API int sqlite3changeset_apply_v2_strm(
+ sqlite3 *db, /* Apply change to "main" db of this handle */
+ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
+ void *pIn, /* First arg for xInput */
+ int(*xFilter)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ const char *zTab /* Table name */
+ ),
+ int(*xConflict)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
+ ),
+ void *pCtx, /* First argument passed to xConflict */
+ void **ppRebase, int *pnRebase,
+ int flags
+);
+SQLITE_API int sqlite3changeset_concat_strm(
+ int (*xInputA)(void *pIn, void *pData, int *pnData),
+ void *pInA,
+ int (*xInputB)(void *pIn, void *pData, int *pnData),
+ void *pInB,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+);
+SQLITE_API int sqlite3changeset_invert_strm(
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+);
+SQLITE_API int sqlite3changeset_start_strm(
+ sqlite3_changeset_iter **pp,
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn
+);
+SQLITE_API int sqlite3changeset_start_v2_strm(
+ sqlite3_changeset_iter **pp,
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn,
+ int flags
+);
+SQLITE_API int sqlite3session_changeset_strm(
+ sqlite3_session *pSession,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+);
+SQLITE_API int sqlite3session_patchset_strm(
+ sqlite3_session *pSession,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+);
+SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn
+);
+SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+);
+SQLITE_API int sqlite3rebaser_rebase_strm(
+ sqlite3_rebaser *pRebaser,
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+);
+
+/*
+** CAPI3REF: Configure global parameters
+**
+** The sqlite3session_config() interface is used to make global configuration
+** changes to the sessions module in order to tune it to the specific needs
+** of the application.
+**
+** The sqlite3session_config() interface is not threadsafe. If it is invoked
+** while any other thread is inside any other sessions method then the
+** results are undefined. Furthermore, if it is invoked after any sessions
+** related objects have been created, the results are also undefined.
+**
+** The first argument to the sqlite3session_config() function must be one
+** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The
+** interpretation of the (void*) value passed as the second parameter and
+** the effect of calling this function depends on the value of the first
+** parameter.
+**
+** <dl>
+** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd>
+** By default, the sessions module streaming interfaces attempt to input
+** and output data in approximately 1 KiB chunks. This operand may be used
+** to set and query the value of this configuration setting. The pointer
+** passed as the second argument must point to a value of type (int).
+** If this value is greater than 0, it is used as the new streaming data
+** chunk size for both input and output. Before returning, the (int) value
+** pointed to by pArg is set to the final value of the streaming interface
+** chunk size.
+** </dl>
+**
+** This function returns SQLITE_OK if successful, or an SQLite error code
+** otherwise.
+*/
+SQLITE_API int sqlite3session_config(int op, void *pArg);
+
+/*
+** CAPI3REF: Values for sqlite3session_config().
+*/
+#define SQLITE_SESSION_CONFIG_STRMSIZE 1
+
+/*
+** Make sure we can call this stuff from C++.
+*/
+#if 0
+}
+#endif
+
+#endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
+
+/******** End of sqlite3session.h *********/
+/******** Begin file fts5.h *********/
+/*
+** 2014 May 31
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** Interfaces to extend FTS5. Using the interfaces defined in this file,
+** FTS5 may be extended with:
+**
+** * custom tokenizers, and
+** * custom auxiliary functions.
+*/
+
+
+#ifndef _FTS5_H
+#define _FTS5_H
+
+
+#if 0
+extern "C" {
+#endif
+
+/*************************************************************************
+** CUSTOM AUXILIARY FUNCTIONS
+**
+** Virtual table implementations may overload SQL functions by implementing
+** the sqlite3_module.xFindFunction() method.
+*/
+
+typedef struct Fts5ExtensionApi Fts5ExtensionApi;
+typedef struct Fts5Context Fts5Context;
+typedef struct Fts5PhraseIter Fts5PhraseIter;
+
+typedef void (*fts5_extension_function)(
+ const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
+ Fts5Context *pFts, /* First arg to pass to pApi functions */
+ sqlite3_context *pCtx, /* Context for returning result/error */
+ int nVal, /* Number of values in apVal[] array */
+ sqlite3_value **apVal /* Array of trailing arguments */
+);
+
+struct Fts5PhraseIter {
+ const unsigned char *a;
+ const unsigned char *b;
+};
+
+/*
+** EXTENSION API FUNCTIONS
+**
+** xUserData(pFts):
+** Return a copy of the context pointer the extension function was
+** registered with.
+**
+** xColumnTotalSize(pFts, iCol, pnToken):
+** If parameter iCol is less than zero, set output variable *pnToken
+** to the total number of tokens in the FTS5 table. Or, if iCol is
+** non-negative but less than the number of columns in the table, return
+** the total number of tokens in column iCol, considering all rows in
+** the FTS5 table.
+**
+** If parameter iCol is greater than or equal to the number of columns
+** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
+** an OOM condition or IO error), an appropriate SQLite error code is
+** returned.
+**
+** xColumnCount(pFts):
+** Return the number of columns in the table.
+**
+** xColumnSize(pFts, iCol, pnToken):
+** If parameter iCol is less than zero, set output variable *pnToken
+** to the total number of tokens in the current row. Or, if iCol is
+** non-negative but less than the number of columns in the table, set
+** *pnToken to the number of tokens in column iCol of the current row.
+**
+** If parameter iCol is greater than or equal to the number of columns
+** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
+** an OOM condition or IO error), an appropriate SQLite error code is
+** returned.
+**
+** This function may be quite inefficient if used with an FTS5 table
+** created with the "columnsize=0" option.
+**
+** xColumnText:
+** This function attempts to retrieve the text of column iCol of the
+** current document. If successful, (*pz) is set to point to a buffer
+** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
+** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
+** if an error occurs, an SQLite error code is returned and the final values
+** of (*pz) and (*pn) are undefined.
+**
+** xPhraseCount:
+** Returns the number of phrases in the current query expression.
+**
+** xPhraseSize:
+** Returns the number of tokens in phrase iPhrase of the query. Phrases
+** are numbered starting from zero.
+**
+** xInstCount:
+** Set *pnInst to the total number of occurrences of all phrases within
+** the query within the current row. Return SQLITE_OK if successful, or
+** an error code (i.e. SQLITE_NOMEM) if an error occurs.
+**
+** This API can be quite slow if used with an FTS5 table created with the
+** "detail=none" or "detail=column" option. If the FTS5 table is created
+** with either "detail=none" or "detail=column" and "content=" option
+** (i.e. if it is a contentless table), then this API always returns 0.
+**
+** xInst:
+** Query for the details of phrase match iIdx within the current row.
+** Phrase matches are numbered starting from zero, so the iIdx argument
+** should be greater than or equal to zero and smaller than the value
+** output by xInstCount().
+**
+** Usually, output parameter *piPhrase is set to the phrase number, *piCol
+** to the column in which it occurs and *piOff the token offset of the
+** first token of the phrase. Returns SQLITE_OK if successful, or an error
+** code (i.e. SQLITE_NOMEM) if an error occurs.
+**
+** This API can be quite slow if used with an FTS5 table created with the
+** "detail=none" or "detail=column" option.
+**
+** xRowid:
+** Returns the rowid of the current row.
+**
+** xTokenize:
+** Tokenize text using the tokenizer belonging to the FTS5 table.
+**
+** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
+** This API function is used to query the FTS table for phrase iPhrase
+** of the current query. Specifically, a query equivalent to:
+**
+** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
+**
+** with $p set to a phrase equivalent to the phrase iPhrase of the
+** current query is executed. Any column filter that applies to
+** phrase iPhrase of the current query is included in $p. For each
+** row visited, the callback function passed as the fourth argument
+** is invoked. The context and API objects passed to the callback
+** function may be used to access the properties of each matched row.
+** Invoking Api.xUserData() returns a copy of the pointer passed as
+** the third argument to pUserData.
+**
+** If the callback function returns any value other than SQLITE_OK, the
+** query is abandoned and the xQueryPhrase function returns immediately.
+** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
+** Otherwise, the error code is propagated upwards.
+**
+** If the query runs to completion without incident, SQLITE_OK is returned.
+** Or, if some error occurs before the query completes or is aborted by
+** the callback, an SQLite error code is returned.
+**
+**
+** xSetAuxdata(pFts5, pAux, xDelete)
+**
+** Save the pointer passed as the second argument as the extension function's
+** "auxiliary data". The pointer may then be retrieved by the current or any
+** future invocation of the same fts5 extension function made as part of
+** the same MATCH query using the xGetAuxdata() API.
+**
+** Each extension function is allocated a single auxiliary data slot for
+** each FTS query (MATCH expression). If the extension function is invoked
+** more than once for a single FTS query, then all invocations share a
+** single auxiliary data context.
+**
+** If there is already an auxiliary data pointer when this function is
+** invoked, then it is replaced by the new pointer. If an xDelete callback
+** was specified along with the original pointer, it is invoked at this
+** point.
+**
+** The xDelete callback, if one is specified, is also invoked on the
+** auxiliary data pointer after the FTS5 query has finished.
+**
+** If an error (e.g. an OOM condition) occurs within this function,
+** the auxiliary data is set to NULL and an error code returned. If the
+** xDelete parameter was not NULL, it is invoked on the auxiliary data
+** pointer before returning.
+**
+**
+** xGetAuxdata(pFts5, bClear)
+**
+** Returns the current auxiliary data pointer for the fts5 extension
+** function. See the xSetAuxdata() method for details.
+**
+** If the bClear argument is non-zero, then the auxiliary data is cleared
+** (set to NULL) before this function returns. In this case the xDelete,
+** if any, is not invoked.
+**
+**
+** xRowCount(pFts5, pnRow)
+**
+** This function is used to retrieve the total number of rows in the table.
+** In other words, the same value that would be returned by:
+**
+** SELECT count(*) FROM ftstable;
+**
+** xPhraseFirst()
+** This function is used, along with type Fts5PhraseIter and the xPhraseNext
+** method, to iterate through all instances of a single query phrase within
+** the current row. This is the same information as is accessible via the
+** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
+** to use, this API may be faster under some circumstances. To iterate
+** through instances of phrase iPhrase, use the following code:
+**
+** Fts5PhraseIter iter;
+** int iCol, iOff;
+** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
+** iCol>=0;
+** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
+** ){
+** // An instance of phrase iPhrase at offset iOff of column iCol
+** }
+**
+** The Fts5PhraseIter structure is defined above. Applications should not
+** modify this structure directly - it should only be used as shown above
+** with the xPhraseFirst() and xPhraseNext() API methods (and by
+** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
+**
+** This API can be quite slow if used with an FTS5 table created with the
+** "detail=none" or "detail=column" option. If the FTS5 table is created
+** with either "detail=none" or "detail=column" and "content=" option
+** (i.e. if it is a contentless table), then this API always iterates
+** through an empty set (all calls to xPhraseFirst() set iCol to -1).
+**
+** xPhraseNext()
+** See xPhraseFirst above.
+**
+** xPhraseFirstColumn()
+** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
+** and xPhraseNext() APIs described above. The difference is that instead
+** of iterating through all instances of a phrase in the current row, these
+** APIs are used to iterate through the set of columns in the current row
+** that contain one or more instances of a specified phrase. For example:
+**
+** Fts5PhraseIter iter;
+** int iCol;
+** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
+** iCol>=0;
+** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
+** ){
+** // Column iCol contains at least one instance of phrase iPhrase
+** }
+**
+** This API can be quite slow if used with an FTS5 table created with the
+** "detail=none" option. If the FTS5 table is created with either
+** "detail=none" "content=" option (i.e. if it is a contentless table),
+** then this API always iterates through an empty set (all calls to
+** xPhraseFirstColumn() set iCol to -1).
+**
+** The information accessed using this API and its companion
+** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
+** (or xInst/xInstCount). The chief advantage of this API is that it is
+** significantly more efficient than those alternatives when used with
+** "detail=column" tables.
+**
+** xPhraseNextColumn()
+** See xPhraseFirstColumn above.
+*/
+struct Fts5ExtensionApi {
+ int iVersion; /* Currently always set to 3 */
+
+ void *(*xUserData)(Fts5Context*);
+
+ int (*xColumnCount)(Fts5Context*);
+ int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
+ int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
+
+ int (*xTokenize)(Fts5Context*,
+ const char *pText, int nText, /* Text to tokenize */
+ void *pCtx, /* Context passed to xToken() */
+ int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
+ );
+
+ int (*xPhraseCount)(Fts5Context*);
+ int (*xPhraseSize)(Fts5Context*, int iPhrase);
+
+ int (*xInstCount)(Fts5Context*, int *pnInst);
+ int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
+
+ sqlite3_int64 (*xRowid)(Fts5Context*);
+ int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
+ int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
+
+ int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
+ int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
+ );
+ int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
+ void *(*xGetAuxdata)(Fts5Context*, int bClear);
+
+ int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
+ void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
+
+ int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
+ void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
+};
+
+/*
+** CUSTOM AUXILIARY FUNCTIONS
+*************************************************************************/
+
+/*************************************************************************
+** CUSTOM TOKENIZERS
+**
+** Applications may also register custom tokenizer types. A tokenizer
+** is registered by providing fts5 with a populated instance of the
+** following structure. All structure methods must be defined, setting
+** any member of the fts5_tokenizer struct to NULL leads to undefined
+** behaviour. The structure methods are expected to function as follows:
+**
+** xCreate:
+** This function is used to allocate and initialize a tokenizer instance.
+** A tokenizer instance is required to actually tokenize text.
+**
+** The first argument passed to this function is a copy of the (void*)
+** pointer provided by the application when the fts5_tokenizer object
+** was registered with FTS5 (the third argument to xCreateTokenizer()).
+** The second and third arguments are an array of nul-terminated strings
+** containing the tokenizer arguments, if any, specified following the
+** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
+** to create the FTS5 table.
+**
+** The final argument is an output variable. If successful, (*ppOut)
+** should be set to point to the new tokenizer handle and SQLITE_OK
+** returned. If an error occurs, some value other than SQLITE_OK should
+** be returned. In this case, fts5 assumes that the final value of *ppOut
+** is undefined.
+**
+** xDelete:
+** This function is invoked to delete a tokenizer handle previously
+** allocated using xCreate(). Fts5 guarantees that this function will
+** be invoked exactly once for each successful call to xCreate().
+**
+** xTokenize:
+** This function is expected to tokenize the nText byte string indicated
+** by argument pText. pText may or may not be nul-terminated. The first
+** argument passed to this function is a pointer to an Fts5Tokenizer object
+** returned by an earlier call to xCreate().
+**
+** The second argument indicates the reason that FTS5 is requesting
+** tokenization of the supplied text. This is always one of the following
+** four values:
+**
+** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
+** or removed from the FTS table. The tokenizer is being invoked to
+** determine the set of tokens to add to (or delete from) the
+** FTS index.
+**
+** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
+** against the FTS index. The tokenizer is being called to tokenize
+** a bareword or quoted string specified as part of the query.
+**
+** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
+** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
+** followed by a "*" character, indicating that the last token
+** returned by the tokenizer will be treated as a token prefix.
+**
+** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
+** satisfy an fts5_api.xTokenize() request made by an auxiliary
+** function. Or an fts5_api.xColumnSize() request made by the same
+** on a columnsize=0 database.
+** </ul>
+**
+** For each token in the input string, the supplied callback xToken() must
+** be invoked. The first argument to it should be a copy of the pointer
+** passed as the second argument to xTokenize(). The third and fourth
+** arguments are a pointer to a buffer containing the token text, and the
+** size of the token in bytes. The 4th and 5th arguments are the byte offsets
+** of the first byte of and first byte immediately following the text from
+** which the token is derived within the input.
+**
+** The second argument passed to the xToken() callback ("tflags") should
+** normally be set to 0. The exception is if the tokenizer supports
+** synonyms. In this case see the discussion below for details.
+**
+** FTS5 assumes the xToken() callback is invoked for each token in the
+** order that they occur within the input text.
+**
+** If an xToken() callback returns any value other than SQLITE_OK, then
+** the tokenization should be abandoned and the xTokenize() method should
+** immediately return a copy of the xToken() return value. Or, if the
+** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
+** if an error occurs with the xTokenize() implementation itself, it
+** may abandon the tokenization and return any error code other than
+** SQLITE_OK or SQLITE_DONE.
+**
+** SYNONYM SUPPORT
+**
+** Custom tokenizers may also support synonyms. Consider a case in which a
+** user wishes to query for a phrase such as "first place". Using the
+** built-in tokenizers, the FTS5 query 'first + place' will match instances
+** of "first place" within the document set, but not alternative forms
+** such as "1st place". In some applications, it would be better to match
+** all instances of "first place" or "1st place" regardless of which form
+** the user specified in the MATCH query text.
+**
+** There are several ways to approach this in FTS5:
+**
+** <ol><li> By mapping all synonyms to a single token. In this case, using
+** the above example, this means that the tokenizer returns the
+** same token for inputs "first" and "1st". Say that token is in
+** fact "first", so that when the user inserts the document "I won
+** 1st place" entries are added to the index for tokens "i", "won",
+** "first" and "place". If the user then queries for '1st + place',
+** the tokenizer substitutes "first" for "1st" and the query works
+** as expected.
+**
+** <li> By querying the index for all synonyms of each query term
+** separately. In this case, when tokenizing query text, the
+** tokenizer may provide multiple synonyms for a single term
+** within the document. FTS5 then queries the index for each
+** synonym individually. For example, faced with the query:
+**
+** <codeblock>
+** ... MATCH 'first place'</codeblock>
+**
+** the tokenizer offers both "1st" and "first" as synonyms for the
+** first token in the MATCH query and FTS5 effectively runs a query
+** similar to:
+**
+** <codeblock>
+** ... MATCH '(first OR 1st) place'</codeblock>
+**
+** except that, for the purposes of auxiliary functions, the query
+** still appears to contain just two phrases - "(first OR 1st)"
+** being treated as a single phrase.
+**
+** <li> By adding multiple synonyms for a single term to the FTS index.
+** Using this method, when tokenizing document text, the tokenizer
+** provides multiple synonyms for each token. So that when a
+** document such as "I won first place" is tokenized, entries are
+** added to the FTS index for "i", "won", "first", "1st" and
+** "place".
+**
+** This way, even if the tokenizer does not provide synonyms
+** when tokenizing query text (it should not - to do so would be
+** inefficient), it doesn't matter if the user queries for
+** 'first + place' or '1st + place', as there are entries in the
+** FTS index corresponding to both forms of the first token.
+** </ol>
+**
+** Whether it is parsing document or query text, any call to xToken that
+** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
+** is considered to supply a synonym for the previous token. For example,
+** when parsing the document "I won first place", a tokenizer that supports
+** synonyms would call xToken() 5 times, as follows:
+**
+** <codeblock>
+** xToken(pCtx, 0, "i", 1, 0, 1);
+** xToken(pCtx, 0, "won", 3, 2, 5);
+** xToken(pCtx, 0, "first", 5, 6, 11);
+** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
+** xToken(pCtx, 0, "place", 5, 12, 17);
+**</codeblock>
+**
+** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
+** xToken() is called. Multiple synonyms may be specified for a single token
+** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
+** There is no limit to the number of synonyms that may be provided for a
+** single token.
+**
+** In many cases, method (1) above is the best approach. It does not add
+** extra data to the FTS index or require FTS5 to query for multiple terms,
+** so it is efficient in terms of disk space and query speed. However, it
+** does not support prefix queries very well. If, as suggested above, the
+** token "first" is substituted for "1st" by the tokenizer, then the query:
+**
+** <codeblock>
+** ... MATCH '1s*'</codeblock>
+**
+** will not match documents that contain the token "1st" (as the tokenizer
+** will probably not map "1s" to any prefix of "first").
+**
+** For full prefix support, method (3) may be preferred. In this case,
+** because the index contains entries for both "first" and "1st", prefix
+** queries such as 'fi*' or '1s*' will match correctly. However, because
+** extra entries are added to the FTS index, this method uses more space
+** within the database.
+**
+** Method (2) offers a midpoint between (1) and (3). Using this method,
+** a query such as '1s*' will match documents that contain the literal
+** token "1st", but not "first" (assuming the tokenizer is not able to
+** provide synonyms for prefixes). However, a non-prefix query like '1st'
+** will match against "1st" and "first". This method does not require
+** extra disk space, as no extra entries are added to the FTS index.
+** On the other hand, it may require more CPU cycles to run MATCH queries,
+** as separate queries of the FTS index are required for each synonym.
+**
+** When using methods (2) or (3), it is important that the tokenizer only
+** provide synonyms when tokenizing document text (method (2)) or query
+** text (method (3)), not both. Doing so will not cause any errors, but is
+** inefficient.
+*/
+typedef struct Fts5Tokenizer Fts5Tokenizer;
+typedef struct fts5_tokenizer fts5_tokenizer;
+struct fts5_tokenizer {
+ int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
+ void (*xDelete)(Fts5Tokenizer*);
+ int (*xTokenize)(Fts5Tokenizer*,
+ void *pCtx,
+ int flags, /* Mask of FTS5_TOKENIZE_* flags */
+ const char *pText, int nText,
+ int (*xToken)(
+ void *pCtx, /* Copy of 2nd argument to xTokenize() */
+ int tflags, /* Mask of FTS5_TOKEN_* flags */
+ const char *pToken, /* Pointer to buffer containing token */
+ int nToken, /* Size of token in bytes */
+ int iStart, /* Byte offset of token within input text */
+ int iEnd /* Byte offset of end of token within input text */
+ )
+ );
+};
+
+/* Flags that may be passed as the third argument to xTokenize() */
+#define FTS5_TOKENIZE_QUERY 0x0001
+#define FTS5_TOKENIZE_PREFIX 0x0002
+#define FTS5_TOKENIZE_DOCUMENT 0x0004
+#define FTS5_TOKENIZE_AUX 0x0008
+
+/* Flags that may be passed by the tokenizer implementation back to FTS5
+** as the third argument to the supplied xToken callback. */
+#define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
+
+/*
+** END OF CUSTOM TOKENIZERS
+*************************************************************************/
+
+/*************************************************************************
+** FTS5 EXTENSION REGISTRATION API
+*/
+typedef struct fts5_api fts5_api;
+struct fts5_api {
+ int iVersion; /* Currently always set to 2 */
+
+ /* Create a new tokenizer */
+ int (*xCreateTokenizer)(
+ fts5_api *pApi,
+ const char *zName,
+ void *pContext,
+ fts5_tokenizer *pTokenizer,
+ void (*xDestroy)(void*)
+ );
+
+ /* Find an existing tokenizer */
+ int (*xFindTokenizer)(
+ fts5_api *pApi,
+ const char *zName,
+ void **ppContext,
+ fts5_tokenizer *pTokenizer
+ );
+
+ /* Create a new auxiliary function */
+ int (*xCreateFunction)(
+ fts5_api *pApi,
+ const char *zName,
+ void *pContext,
+ fts5_extension_function xFunction,
+ void (*xDestroy)(void*)
+ );
+};
+
+/*
+** END OF REGISTRATION API
+*************************************************************************/
+
+#if 0
+} /* end of the 'extern "C"' block */
+#endif
+
+#endif /* _FTS5_H */
+
+/******** End of fts5.h *********/
+
+/************** End of sqlite3.h *********************************************/
+/************** Continuing where we left off in sqliteInt.h ******************/
+
+/*
+** Include the configuration header output by 'configure' if we're using the
+** autoconf-based build
+*/
+#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
+/* #include "config.h" */
+#define SQLITECONFIG_H 1
+#endif
+
+/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
+/************** Begin file sqliteLimit.h *************************************/
+/*
+** 2007 May 7
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file defines various limits of what SQLite can process.
+*/
+
+/*
+** The maximum length of a TEXT or BLOB in bytes. This also
+** limits the size of a row in a table or index.
+**
+** The hard limit is the ability of a 32-bit signed integer
+** to count the size: 2^31-1 or 2147483647.
+*/
+#ifndef SQLITE_MAX_LENGTH
+# define SQLITE_MAX_LENGTH 1000000000
+#endif
+
+/*
+** This is the maximum number of
+**
+** * Columns in a table
+** * Columns in an index
+** * Columns in a view
+** * Terms in the SET clause of an UPDATE statement
+** * Terms in the result set of a SELECT statement
+** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
+** * Terms in the VALUES clause of an INSERT statement
+**
+** The hard upper limit here is 32676. Most database people will
+** tell you that in a well-normalized database, you usually should
+** not have more than a dozen or so columns in any table. And if
+** that is the case, there is no point in having more than a few
+** dozen values in any of the other situations described above.
+*/
+#ifndef SQLITE_MAX_COLUMN
+# define SQLITE_MAX_COLUMN 2000
+#endif
+
+/*
+** The maximum length of a single SQL statement in bytes.
+**
+** It used to be the case that setting this value to zero would
+** turn the limit off. That is no longer true. It is not possible
+** to turn this limit off.
+*/
+#ifndef SQLITE_MAX_SQL_LENGTH
+# define SQLITE_MAX_SQL_LENGTH 1000000000
+#endif
+
+/*
+** The maximum depth of an expression tree. This is limited to
+** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
+** want to place more severe limits on the complexity of an
+** expression. A value of 0 means that there is no limit.
+*/
+#ifndef SQLITE_MAX_EXPR_DEPTH
+# define SQLITE_MAX_EXPR_DEPTH 1000
+#endif
+
+/*
+** The maximum number of terms in a compound SELECT statement.
+** The code generator for compound SELECT statements does one
+** level of recursion for each term. A stack overflow can result
+** if the number of terms is too large. In practice, most SQL
+** never has more than 3 or 4 terms. Use a value of 0 to disable
+** any limit on the number of terms in a compount SELECT.
+*/
+#ifndef SQLITE_MAX_COMPOUND_SELECT
+# define SQLITE_MAX_COMPOUND_SELECT 500
+#endif
+
+/*
+** The maximum number of opcodes in a VDBE program.
+** Not currently enforced.
+*/
+#ifndef SQLITE_MAX_VDBE_OP
+# define SQLITE_MAX_VDBE_OP 250000000
+#endif
+
+/*
+** The maximum number of arguments to an SQL function.
+*/
+#ifndef SQLITE_MAX_FUNCTION_ARG
+# define SQLITE_MAX_FUNCTION_ARG 127
+#endif
+
+/*
+** The suggested maximum number of in-memory pages to use for
+** the main database table and for temporary tables.
+**
+** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
+** which means the cache size is limited to 2048000 bytes of memory.
+** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
+** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
+*/
+#ifndef SQLITE_DEFAULT_CACHE_SIZE
+# define SQLITE_DEFAULT_CACHE_SIZE -2000
+#endif
+
+/*
+** The default number of frames to accumulate in the log file before
+** checkpointing the database in WAL mode.
+*/
+#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
+# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
+#endif
+
+/*
+** The maximum number of attached databases. This must be between 0
+** and 125. The upper bound of 125 is because the attached databases are
+** counted using a signed 8-bit integer which has a maximum value of 127
+** and we have to allow 2 extra counts for the "main" and "temp" databases.
+*/
+#ifndef SQLITE_MAX_ATTACHED
+# define SQLITE_MAX_ATTACHED 10
+#endif
+
+
+/*
+** The maximum value of a ?nnn wildcard that the parser will accept.
+** If the value exceeds 32767 then extra space is required for the Expr
+** structure. But otherwise, we believe that the number can be as large
+** as a signed 32-bit integer can hold.
+*/
+#ifndef SQLITE_MAX_VARIABLE_NUMBER
+# define SQLITE_MAX_VARIABLE_NUMBER 32766
+#endif
+
+/* Maximum page size. The upper bound on this value is 65536. This a limit
+** imposed by the use of 16-bit offsets within each page.
+**
+** Earlier versions of SQLite allowed the user to change this value at
+** compile time. This is no longer permitted, on the grounds that it creates
+** a library that is technically incompatible with an SQLite library
+** compiled with a different limit. If a process operating on a database
+** with a page-size of 65536 bytes crashes, then an instance of SQLite
+** compiled with the default page-size limit will not be able to rollback
+** the aborted transaction. This could lead to database corruption.
+*/
+#ifdef SQLITE_MAX_PAGE_SIZE
+# undef SQLITE_MAX_PAGE_SIZE
+#endif
+#define SQLITE_MAX_PAGE_SIZE 65536
+
+
+/*
+** The default size of a database page.
+*/
+#ifndef SQLITE_DEFAULT_PAGE_SIZE
+# define SQLITE_DEFAULT_PAGE_SIZE 4096
+#endif
+#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
+# undef SQLITE_DEFAULT_PAGE_SIZE
+# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
+#endif
+
+/*
+** Ordinarily, if no value is explicitly provided, SQLite creates databases
+** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
+** device characteristics (sector-size and atomic write() support),
+** SQLite may choose a larger value. This constant is the maximum value
+** SQLite will choose on its own.
+*/
+#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
+# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
+#endif
+#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
+# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
+# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
+#endif
+
+
+/*
+** Maximum number of pages in one database file.
+**
+** This is really just the default value for the max_page_count pragma.
+** This value can be lowered (or raised) at run-time using that the
+** max_page_count macro.
+*/
+#ifndef SQLITE_MAX_PAGE_COUNT
+# define SQLITE_MAX_PAGE_COUNT 1073741823
+#endif
+
+/*
+** Maximum length (in bytes) of the pattern in a LIKE or GLOB
+** operator.
+*/
+#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
+# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
+#endif
+
+/*
+** Maximum depth of recursion for triggers.
+**
+** A value of 1 means that a trigger program will not be able to itself
+** fire any triggers. A value of 0 means that no trigger programs at all
+** may be executed.
+*/
+#ifndef SQLITE_MAX_TRIGGER_DEPTH
+# define SQLITE_MAX_TRIGGER_DEPTH 1000
+#endif
+
+/************** End of sqliteLimit.h *****************************************/
+/************** Continuing where we left off in sqliteInt.h ******************/
+
+/* Disable nuisance warnings on Borland compilers */
+#if defined(__BORLANDC__)
+#pragma warn -rch /* unreachable code */
+#pragma warn -ccc /* Condition is always true or false */
+#pragma warn -aus /* Assigned value is never used */
+#pragma warn -csu /* Comparing signed and unsigned */
+#pragma warn -spa /* Suspicious pointer arithmetic */
+#endif
+
+/*
+** WAL mode depends on atomic aligned 32-bit loads and stores in a few
+** places. The following macros try to make this explicit.
+*/
+#ifndef __has_extension
+# define __has_extension(x) 0 /* compatibility with non-clang compilers */
+#endif
+#if GCC_VERSION>=4007000 || __has_extension(c_atomic)
+# define AtomicLoad(PTR) __atomic_load_n((PTR),__ATOMIC_RELAXED)
+# define AtomicStore(PTR,VAL) __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
+#else
+# define AtomicLoad(PTR) (*(PTR))
+# define AtomicStore(PTR,VAL) (*(PTR) = (VAL))
+#endif
+
+/*
+** Include standard header files as necessary
+*/
+#ifdef HAVE_STDINT_H
+#include <stdint.h>
+#endif
+#ifdef HAVE_INTTYPES_H
+#include <inttypes.h>
+#endif
+
+/*
+** The following macros are used to cast pointers to integers and
+** integers to pointers. The way you do this varies from one compiler
+** to the next, so we have developed the following set of #if statements
+** to generate appropriate macros for a wide range of compilers.
+**
+** The correct "ANSI" way to do this is to use the intptr_t type.
+** Unfortunately, that typedef is not available on all compilers, or
+** if it is available, it requires an #include of specific headers
+** that vary from one machine to the next.
+**
+** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
+** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
+** So we have to define the macros in different ways depending on the
+** compiler.
+*/
+#if defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
+# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
+# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
+#elif defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
+# define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
+# define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
+#elif !defined(__GNUC__) /* Works for compilers other than LLVM */
+# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
+# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
+#else /* Generates a warning - but it always works */
+# define SQLITE_INT_TO_PTR(X) ((void*)(X))
+# define SQLITE_PTR_TO_INT(X) ((int)(X))
+#endif
+
+/*
+** A macro to hint to the compiler that a function should not be
+** inlined.
+*/
+#if defined(__GNUC__)
+# define SQLITE_NOINLINE __attribute__((noinline))
+#elif defined(_MSC_VER) && _MSC_VER>=1310
+# define SQLITE_NOINLINE __declspec(noinline)
+#else
+# define SQLITE_NOINLINE
+#endif
+
+/*
+** Make sure that the compiler intrinsics we desire are enabled when
+** compiling with an appropriate version of MSVC unless prevented by
+** the SQLITE_DISABLE_INTRINSIC define.
+*/
+#if !defined(SQLITE_DISABLE_INTRINSIC)
+# if defined(_MSC_VER) && _MSC_VER>=1400
+# if !defined(_WIN32_WCE)
+# include <intrin.h>
+# pragma intrinsic(_byteswap_ushort)
+# pragma intrinsic(_byteswap_ulong)
+# pragma intrinsic(_byteswap_uint64)
+# pragma intrinsic(_ReadWriteBarrier)
+# else
+# include <cmnintrin.h>
+# endif
+# endif
+#endif
+
+/*
+** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
+** 0 means mutexes are permanently disable and the library is never
+** threadsafe. 1 means the library is serialized which is the highest
+** level of threadsafety. 2 means the library is multithreaded - multiple
+** threads can use SQLite as long as no two threads try to use the same
+** database connection at the same time.
+**
+** Older versions of SQLite used an optional THREADSAFE macro.
+** We support that for legacy.
+**
+** To ensure that the correct value of "THREADSAFE" is reported when querying
+** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
+** logic is partially replicated in ctime.c. If it is updated here, it should
+** also be updated there.
+*/
+#if !defined(SQLITE_THREADSAFE)
+# if defined(THREADSAFE)
+# define SQLITE_THREADSAFE THREADSAFE
+# else
+# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
+# endif
+#endif
+
+/*
+** Powersafe overwrite is on by default. But can be turned off using
+** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
+*/
+#ifndef SQLITE_POWERSAFE_OVERWRITE
+# define SQLITE_POWERSAFE_OVERWRITE 1
+#endif
+
+/*
+** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
+** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
+** which case memory allocation statistics are disabled by default.
+*/
+#if !defined(SQLITE_DEFAULT_MEMSTATUS)
+# define SQLITE_DEFAULT_MEMSTATUS 1
+#endif
+
+/*
+** Exactly one of the following macros must be defined in order to
+** specify which memory allocation subsystem to use.
+**
+** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
+** SQLITE_WIN32_MALLOC // Use Win32 native heap API
+** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
+** SQLITE_MEMDEBUG // Debugging version of system malloc()
+**
+** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
+** assert() macro is enabled, each call into the Win32 native heap subsystem
+** will cause HeapValidate to be called. If heap validation should fail, an
+** assertion will be triggered.
+**
+** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
+** the default.
+*/
+#if defined(SQLITE_SYSTEM_MALLOC) \
+ + defined(SQLITE_WIN32_MALLOC) \
+ + defined(SQLITE_ZERO_MALLOC) \
+ + defined(SQLITE_MEMDEBUG)>1
+# error "Two or more of the following compile-time configuration options\
+ are defined but at most one is allowed:\
+ SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
+ SQLITE_ZERO_MALLOC"
+#endif
+#if defined(SQLITE_SYSTEM_MALLOC) \
+ + defined(SQLITE_WIN32_MALLOC) \
+ + defined(SQLITE_ZERO_MALLOC) \
+ + defined(SQLITE_MEMDEBUG)==0
+# define SQLITE_SYSTEM_MALLOC 1
+#endif
+
+/*
+** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
+** sizes of memory allocations below this value where possible.
+*/
+#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
+# define SQLITE_MALLOC_SOFT_LIMIT 1024
+#endif
+
+/*
+** We need to define _XOPEN_SOURCE as follows in order to enable
+** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
+** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
+** it.
+*/
+#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
+# define _XOPEN_SOURCE 600
+#endif
+
+/*
+** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
+** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
+** make it true by defining or undefining NDEBUG.
+**
+** Setting NDEBUG makes the code smaller and faster by disabling the
+** assert() statements in the code. So we want the default action
+** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
+** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
+** feature.
+*/
+#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
+# define NDEBUG 1
+#endif
+#if defined(NDEBUG) && defined(SQLITE_DEBUG)
+# undef NDEBUG
+#endif
+
+/*
+** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
+*/
+#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
+# define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
+#endif
+
+/*
+** The testcase() macro is used to aid in coverage testing. When
+** doing coverage testing, the condition inside the argument to
+** testcase() must be evaluated both true and false in order to
+** get full branch coverage. The testcase() macro is inserted
+** to help ensure adequate test coverage in places where simple
+** condition/decision coverage is inadequate. For example, testcase()
+** can be used to make sure boundary values are tested. For
+** bitmask tests, testcase() can be used to make sure each bit
+** is significant and used at least once. On switch statements
+** where multiple cases go to the same block of code, testcase()
+** can insure that all cases are evaluated.
+**
+*/
+#ifdef SQLITE_COVERAGE_TEST
+SQLITE_PRIVATE void sqlite3Coverage(int);
+# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
+#else
+# define testcase(X)
+#endif
+
+/*
+** The TESTONLY macro is used to enclose variable declarations or
+** other bits of code that are needed to support the arguments
+** within testcase() and assert() macros.
+*/
+#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
+# define TESTONLY(X) X
+#else
+# define TESTONLY(X)
+#endif
+
+/*
+** Sometimes we need a small amount of code such as a variable initialization
+** to setup for a later assert() statement. We do not want this code to
+** appear when assert() is disabled. The following macro is therefore
+** used to contain that setup code. The "VVA" acronym stands for
+** "Verification, Validation, and Accreditation". In other words, the
+** code within VVA_ONLY() will only run during verification processes.
+*/
+#ifndef NDEBUG
+# define VVA_ONLY(X) X
+#else
+# define VVA_ONLY(X)
+#endif
+
+/*
+** The ALWAYS and NEVER macros surround boolean expressions which
+** are intended to always be true or false, respectively. Such
+** expressions could be omitted from the code completely. But they
+** are included in a few cases in order to enhance the resilience
+** of SQLite to unexpected behavior - to make the code "self-healing"
+** or "ductile" rather than being "brittle" and crashing at the first
+** hint of unplanned behavior.
+**
+** In other words, ALWAYS and NEVER are added for defensive code.
+**
+** When doing coverage testing ALWAYS and NEVER are hard-coded to
+** be true and false so that the unreachable code they specify will
+** not be counted as untested code.
+*/
+#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
+# define ALWAYS(X) (1)
+# define NEVER(X) (0)
+#elif !defined(NDEBUG)
+# define ALWAYS(X) ((X)?1:(assert(0),0))
+# define NEVER(X) ((X)?(assert(0),1):0)
+#else
+# define ALWAYS(X) (X)
+# define NEVER(X) (X)
+#endif
+
+/*
+** The harmless(X) macro indicates that expression X is usually false
+** but can be true without causing any problems, but we don't know of
+** any way to cause X to be true.
+**
+** In debugging and testing builds, this macro will abort if X is ever
+** true. In this way, developers are alerted to a possible test case
+** that causes X to be true. If a harmless macro ever fails, that is
+** an opportunity to change the macro into a testcase() and add a new
+** test case to the test suite.
+**
+** For normal production builds, harmless(X) is a no-op, since it does
+** not matter whether expression X is true or false.
+*/
+#ifdef SQLITE_DEBUG
+# define harmless(X) assert(!(X));
+#else
+# define harmless(X)
+#endif
+
+/*
+** Some conditionals are optimizations only. In other words, if the
+** conditionals are replaced with a constant 1 (true) or 0 (false) then
+** the correct answer is still obtained, though perhaps not as quickly.
+**
+** The following macros mark these optimizations conditionals.
+*/
+#if defined(SQLITE_MUTATION_TEST)
+# define OK_IF_ALWAYS_TRUE(X) (1)
+# define OK_IF_ALWAYS_FALSE(X) (0)
+#else
+# define OK_IF_ALWAYS_TRUE(X) (X)
+# define OK_IF_ALWAYS_FALSE(X) (X)
+#endif
+
+/*
+** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
+** defined. We need to defend against those failures when testing with
+** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
+** during a normal build. The following macro can be used to disable tests
+** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
+*/
+#if defined(SQLITE_TEST_REALLOC_STRESS)
+# define ONLY_IF_REALLOC_STRESS(X) (X)
+#elif !defined(NDEBUG)
+# define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
+#else
+# define ONLY_IF_REALLOC_STRESS(X) (0)
+#endif
+
+/*
+** Declarations used for tracing the operating system interfaces.
+*/
+#if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
+ (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
+ extern int sqlite3OSTrace;
+# define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
+# define SQLITE_HAVE_OS_TRACE
+#else
+# define OSTRACE(X)
+# undef SQLITE_HAVE_OS_TRACE
+#endif
+
+/*
+** Is the sqlite3ErrName() function needed in the build? Currently,
+** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
+** OSTRACE is enabled), and by several "test*.c" files (which are
+** compiled using SQLITE_TEST).
+*/
+#if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
+ (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
+# define SQLITE_NEED_ERR_NAME
+#else
+# undef SQLITE_NEED_ERR_NAME
+#endif
+
+/*
+** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
+*/
+#ifdef SQLITE_OMIT_EXPLAIN
+# undef SQLITE_ENABLE_EXPLAIN_COMMENTS
+#endif
+
+/*
+** Return true (non-zero) if the input is an integer that is too large
+** to fit in 32-bits. This macro is used inside of various testcase()
+** macros to verify that we have tested SQLite for large-file support.
+*/
+#define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
+
+/*
+** The macro unlikely() is a hint that surrounds a boolean
+** expression that is usually false. Macro likely() surrounds
+** a boolean expression that is usually true. These hints could,
+** in theory, be used by the compiler to generate better code, but
+** currently they are just comments for human readers.
+*/
+#define likely(X) (X)
+#define unlikely(X) (X)
+
+/************** Include hash.h in the middle of sqliteInt.h ******************/
+/************** Begin file hash.h ********************************************/
+/*
+** 2001 September 22
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This is the header file for the generic hash-table implementation
+** used in SQLite.
+*/
+#ifndef SQLITE_HASH_H
+#define SQLITE_HASH_H
+
+/* Forward declarations of structures. */
+typedef struct Hash Hash;
+typedef struct HashElem HashElem;
+
+/* A complete hash table is an instance of the following structure.
+** The internals of this structure are intended to be opaque -- client
+** code should not attempt to access or modify the fields of this structure
+** directly. Change this structure only by using the routines below.
+** However, some of the "procedures" and "functions" for modifying and
+** accessing this structure are really macros, so we can't really make
+** this structure opaque.
+**
+** All elements of the hash table are on a single doubly-linked list.
+** Hash.first points to the head of this list.
+**
+** There are Hash.htsize buckets. Each bucket points to a spot in
+** the global doubly-linked list. The contents of the bucket are the
+** element pointed to plus the next _ht.count-1 elements in the list.
+**
+** Hash.htsize and Hash.ht may be zero. In that case lookup is done
+** by a linear search of the global list. For small tables, the
+** Hash.ht table is never allocated because if there are few elements
+** in the table, it is faster to do a linear search than to manage
+** the hash table.
+*/
+struct Hash {
+ unsigned int htsize; /* Number of buckets in the hash table */
+ unsigned int count; /* Number of entries in this table */
+ HashElem *first; /* The first element of the array */
+ struct _ht { /* the hash table */
+ unsigned int count; /* Number of entries with this hash */
+ HashElem *chain; /* Pointer to first entry with this hash */
+ } *ht;
+};
+
+/* Each element in the hash table is an instance of the following
+** structure. All elements are stored on a single doubly-linked list.
+**
+** Again, this structure is intended to be opaque, but it can't really
+** be opaque because it is used by macros.
+*/
+struct HashElem {
+ HashElem *next, *prev; /* Next and previous elements in the table */
+ void *data; /* Data associated with this element */
+ const char *pKey; /* Key associated with this element */
+};
+
+/*
+** Access routines. To delete, insert a NULL pointer.
+*/
+SQLITE_PRIVATE void sqlite3HashInit(Hash*);
+SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
+SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
+SQLITE_PRIVATE void sqlite3HashClear(Hash*);
+
+/*
+** Macros for looping over all elements of a hash table. The idiom is
+** like this:
+**
+** Hash h;
+** HashElem *p;
+** ...
+** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
+** SomeStructure *pData = sqliteHashData(p);
+** // do something with pData
+** }
+*/
+#define sqliteHashFirst(H) ((H)->first)
+#define sqliteHashNext(E) ((E)->next)
+#define sqliteHashData(E) ((E)->data)
+/* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
+/* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
+
+/*
+** Number of entries in a hash table
+*/
+/* #define sqliteHashCount(H) ((H)->count) // NOT USED */
+
+#endif /* SQLITE_HASH_H */
+
+/************** End of hash.h ************************************************/
+/************** Continuing where we left off in sqliteInt.h ******************/
+/************** Include parse.h in the middle of sqliteInt.h *****************/
+/************** Begin file parse.h *******************************************/
+#define TK_SEMI 1
+#define TK_EXPLAIN 2
+#define TK_QUERY 3
+#define TK_PLAN 4
+#define TK_BEGIN 5
+#define TK_TRANSACTION 6
+#define TK_DEFERRED 7
+#define TK_IMMEDIATE 8
+#define TK_EXCLUSIVE 9
+#define TK_COMMIT 10
+#define TK_END 11
+#define TK_ROLLBACK 12
+#define TK_SAVEPOINT 13
+#define TK_RELEASE 14
+#define TK_TO 15
+#define TK_TABLE 16
+#define TK_CREATE 17
+#define TK_IF 18
+#define TK_NOT 19
+#define TK_EXISTS 20
+#define TK_TEMP 21
+#define TK_LP 22
+#define TK_RP 23
+#define TK_AS 24
+#define TK_WITHOUT 25
+#define TK_COMMA 26
+#define TK_ABORT 27
+#define TK_ACTION 28
+#define TK_AFTER 29
+#define TK_ANALYZE 30
+#define TK_ASC 31
+#define TK_ATTACH 32
+#define TK_BEFORE 33
+#define TK_BY 34
+#define TK_CASCADE 35
+#define TK_CAST 36
+#define TK_CONFLICT 37
+#define TK_DATABASE 38
+#define TK_DESC 39
+#define TK_DETACH 40
+#define TK_EACH 41
+#define TK_FAIL 42
+#define TK_OR 43
+#define TK_AND 44
+#define TK_IS 45
+#define TK_MATCH 46
+#define TK_LIKE_KW 47
+#define TK_BETWEEN 48
+#define TK_IN 49
+#define TK_ISNULL 50
+#define TK_NOTNULL 51
+#define TK_NE 52
+#define TK_EQ 53
+#define TK_GT 54
+#define TK_LE 55
+#define TK_LT 56
+#define TK_GE 57
+#define TK_ESCAPE 58
+#define TK_ID 59
+#define TK_COLUMNKW 60
+#define TK_DO 61
+#define TK_FOR 62
+#define TK_IGNORE 63
+#define TK_INITIALLY 64
+#define TK_INSTEAD 65
+#define TK_NO 66
+#define TK_KEY 67
+#define TK_OF 68
+#define TK_OFFSET 69
+#define TK_PRAGMA 70
+#define TK_RAISE 71
+#define TK_RECURSIVE 72
+#define TK_REPLACE 73
+#define TK_RESTRICT 74
+#define TK_ROW 75
+#define TK_ROWS 76
+#define TK_TRIGGER 77
+#define TK_VACUUM 78
+#define TK_VIEW 79
+#define TK_VIRTUAL 80
+#define TK_WITH 81
+#define TK_NULLS 82
+#define TK_FIRST 83
+#define TK_LAST 84
+#define TK_CURRENT 85
+#define TK_FOLLOWING 86
+#define TK_PARTITION 87
+#define TK_PRECEDING 88
+#define TK_RANGE 89
+#define TK_UNBOUNDED 90
+#define TK_EXCLUDE 91
+#define TK_GROUPS 92
+#define TK_OTHERS 93
+#define TK_TIES 94
+#define TK_GENERATED 95
+#define TK_ALWAYS 96
+#define TK_REINDEX 97
+#define TK_RENAME 98
+#define TK_CTIME_KW 99
+#define TK_ANY 100
+#define TK_BITAND 101
+#define TK_BITOR 102
+#define TK_LSHIFT 103
+#define TK_RSHIFT 104
+#define TK_PLUS 105
+#define TK_MINUS 106
+#define TK_STAR 107
+#define TK_SLASH 108
+#define TK_REM 109
+#define TK_CONCAT 110
+#define TK_COLLATE 111
+#define TK_BITNOT 112
+#define TK_ON 113
+#define TK_INDEXED 114
+#define TK_STRING 115
+#define TK_JOIN_KW 116
+#define TK_CONSTRAINT 117
+#define TK_DEFAULT 118
+#define TK_NULL 119
+#define TK_PRIMARY 120
+#define TK_UNIQUE 121
+#define TK_CHECK 122
+#define TK_REFERENCES 123
+#define TK_AUTOINCR 124
+#define TK_INSERT 125
+#define TK_DELETE 126
+#define TK_UPDATE 127
+#define TK_SET 128
+#define TK_DEFERRABLE 129
+#define TK_FOREIGN 130
+#define TK_DROP 131
+#define TK_UNION 132
+#define TK_ALL 133
+#define TK_EXCEPT 134
+#define TK_INTERSECT 135
+#define TK_SELECT 136
+#define TK_VALUES 137
+#define TK_DISTINCT 138
+#define TK_DOT 139
+#define TK_FROM 140
+#define TK_JOIN 141
+#define TK_USING 142
+#define TK_ORDER 143
+#define TK_GROUP 144
+#define TK_HAVING 145
+#define TK_LIMIT 146
+#define TK_WHERE 147
+#define TK_INTO 148
+#define TK_NOTHING 149
+#define TK_FLOAT 150
+#define TK_BLOB 151
+#define TK_INTEGER 152
+#define TK_VARIABLE 153
+#define TK_CASE 154
+#define TK_WHEN 155
+#define TK_THEN 156
+#define TK_ELSE 157
+#define TK_INDEX 158
+#define TK_ALTER 159
+#define TK_ADD 160
+#define TK_WINDOW 161
+#define TK_OVER 162
+#define TK_FILTER 163
+#define TK_COLUMN 164
+#define TK_AGG_FUNCTION 165
+#define TK_AGG_COLUMN 166
+#define TK_TRUEFALSE 167
+#define TK_ISNOT 168
+#define TK_FUNCTION 169
+#define TK_UMINUS 170
+#define TK_UPLUS 171
+#define TK_TRUTH 172
+#define TK_REGISTER 173
+#define TK_VECTOR 174
+#define TK_SELECT_COLUMN 175
+#define TK_IF_NULL_ROW 176
+#define TK_ASTERISK 177
+#define TK_SPAN 178
+#define TK_SPACE 179
+#define TK_ILLEGAL 180
+
+/************** End of parse.h ***********************************************/
+/************** Continuing where we left off in sqliteInt.h ******************/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <stddef.h>
+
+/*
+** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
+** This allows better measurements of where memcpy() is used when running
+** cachegrind. But this macro version of memcpy() is very slow so it
+** should not be used in production. This is a performance measurement
+** hack only.
+*/
+#ifdef SQLITE_INLINE_MEMCPY
+# define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
+ int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
+#endif
+
+/*
+** If compiling for a processor that lacks floating point support,
+** substitute integer for floating-point
+*/
+#ifdef SQLITE_OMIT_FLOATING_POINT
+# define double sqlite_int64
+# define float sqlite_int64
+# define LONGDOUBLE_TYPE sqlite_int64
+# ifndef SQLITE_BIG_DBL
+# define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
+# endif
+# define SQLITE_OMIT_DATETIME_FUNCS 1
+# define SQLITE_OMIT_TRACE 1
+# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
+# undef SQLITE_HAVE_ISNAN
+#endif
+#ifndef SQLITE_BIG_DBL
+# define SQLITE_BIG_DBL (1e99)
+#endif
+
+/*
+** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
+** afterward. Having this macro allows us to cause the C compiler
+** to omit code used by TEMP tables without messy #ifndef statements.
+*/
+#ifdef SQLITE_OMIT_TEMPDB
+#define OMIT_TEMPDB 1
+#else
+#define OMIT_TEMPDB 0
+#endif
+
+/*
+** The "file format" number is an integer that is incremented whenever
+** the VDBE-level file format changes. The following macros define the
+** the default file format for new databases and the maximum file format
+** that the library can read.
+*/
+#define SQLITE_MAX_FILE_FORMAT 4
+#ifndef SQLITE_DEFAULT_FILE_FORMAT
+# define SQLITE_DEFAULT_FILE_FORMAT 4
+#endif
+
+/*
+** Determine whether triggers are recursive by default. This can be
+** changed at run-time using a pragma.
+*/
+#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
+# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
+#endif
+
+/*
+** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
+** on the command-line
+*/
+#ifndef SQLITE_TEMP_STORE
+# define SQLITE_TEMP_STORE 1
+#endif
+
+/*
+** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
+** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
+** to zero.
+*/
+#if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
+# undef SQLITE_MAX_WORKER_THREADS
+# define SQLITE_MAX_WORKER_THREADS 0
+#endif
+#ifndef SQLITE_MAX_WORKER_THREADS
+# define SQLITE_MAX_WORKER_THREADS 8
+#endif
+#ifndef SQLITE_DEFAULT_WORKER_THREADS
+# define SQLITE_DEFAULT_WORKER_THREADS 0
+#endif
+#if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
+# undef SQLITE_MAX_WORKER_THREADS
+# define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
+#endif
+
+/*
+** The default initial allocation for the pagecache when using separate
+** pagecaches for each database connection. A positive number is the
+** number of pages. A negative number N translations means that a buffer
+** of -1024*N bytes is allocated and used for as many pages as it will hold.
+**
+** The default value of "20" was choosen to minimize the run-time of the
+** speedtest1 test program with options: --shrink-memory --reprepare
+*/
+#ifndef SQLITE_DEFAULT_PCACHE_INITSZ
+# define SQLITE_DEFAULT_PCACHE_INITSZ 20
+#endif
+
+/*
+** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.
+*/
+#ifndef SQLITE_DEFAULT_SORTERREF_SIZE
+# define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff
+#endif
+
+/*
+** The compile-time options SQLITE_MMAP_READWRITE and
+** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
+** You must choose one or the other (or neither) but not both.
+*/
+#if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
+#error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
+#endif
+
+/*
+** GCC does not define the offsetof() macro so we'll have to do it
+** ourselves.
+*/
+#ifndef offsetof
+#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
+#endif
+
+/*
+** Macros to compute minimum and maximum of two numbers.
+*/
+#ifndef MIN
+# define MIN(A,B) ((A)<(B)?(A):(B))
+#endif
+#ifndef MAX
+# define MAX(A,B) ((A)>(B)?(A):(B))
+#endif
+
+/*
+** Swap two objects of type TYPE.
+*/
+#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
+
+/*
+** Check to see if this machine uses EBCDIC. (Yes, believe it or
+** not, there are still machines out there that use EBCDIC.)
+*/
+#if 'A' == '\301'
+# define SQLITE_EBCDIC 1
+#else
+# define SQLITE_ASCII 1
+#endif
+
+/*
+** Integers of known sizes. These typedefs might change for architectures
+** where the sizes very. Preprocessor macros are available so that the
+** types can be conveniently redefined at compile-type. Like this:
+**
+** cc '-DUINTPTR_TYPE=long long int' ...
+*/
+#ifndef UINT32_TYPE
+# ifdef HAVE_UINT32_T
+# define UINT32_TYPE uint32_t
+# else
+# define UINT32_TYPE unsigned int
+# endif
+#endif
+#ifndef UINT16_TYPE
+# ifdef HAVE_UINT16_T
+# define UINT16_TYPE uint16_t
+# else
+# define UINT16_TYPE unsigned short int
+# endif
+#endif
+#ifndef INT16_TYPE
+# ifdef HAVE_INT16_T
+# define INT16_TYPE int16_t
+# else
+# define INT16_TYPE short int
+# endif
+#endif
+#ifndef UINT8_TYPE
+# ifdef HAVE_UINT8_T
+# define UINT8_TYPE uint8_t
+# else
+# define UINT8_TYPE unsigned char
+# endif
+#endif
+#ifndef INT8_TYPE
+# ifdef HAVE_INT8_T
+# define INT8_TYPE int8_t
+# else
+# define INT8_TYPE signed char
+# endif
+#endif
+#ifndef LONGDOUBLE_TYPE
+# define LONGDOUBLE_TYPE long double
+#endif
+typedef sqlite_int64 i64; /* 8-byte signed integer */
+typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
+typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
+typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
+typedef INT16_TYPE i16; /* 2-byte signed integer */
+typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
+typedef INT8_TYPE i8; /* 1-byte signed integer */
+
+/*
+** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
+** that can be stored in a u32 without loss of data. The value
+** is 0x00000000ffffffff. But because of quirks of some compilers, we
+** have to specify the value in the less intuitive manner shown:
+*/
+#define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
+
+/*
+** The datatype used to store estimates of the number of rows in a
+** table or index. This is an unsigned integer type. For 99.9% of
+** the world, a 32-bit integer is sufficient. But a 64-bit integer
+** can be used at compile-time if desired.
+*/
+#ifdef SQLITE_64BIT_STATS
+ typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
+#else
+ typedef u32 tRowcnt; /* 32-bit is the default */
+#endif
+
+/*
+** Estimated quantities used for query planning are stored as 16-bit
+** logarithms. For quantity X, the value stored is 10*log2(X). This
+** gives a possible range of values of approximately 1.0e986 to 1e-986.
+** But the allowed values are "grainy". Not every value is representable.
+** For example, quantities 16 and 17 are both represented by a LogEst
+** of 40. However, since LogEst quantities are suppose to be estimates,
+** not exact values, this imprecision is not a problem.
+**
+** "LogEst" is short for "Logarithmic Estimate".
+**
+** Examples:
+** 1 -> 0 20 -> 43 10000 -> 132
+** 2 -> 10 25 -> 46 25000 -> 146
+** 3 -> 16 100 -> 66 1000000 -> 199
+** 4 -> 20 1000 -> 99 1048576 -> 200
+** 10 -> 33 1024 -> 100 4294967296 -> 320
+**
+** The LogEst can be negative to indicate fractional values.
+** Examples:
+**
+** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
+*/
+typedef INT16_TYPE LogEst;
+
+/*
+** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
+*/
+#ifndef SQLITE_PTRSIZE
+# if defined(__SIZEOF_POINTER__)
+# define SQLITE_PTRSIZE __SIZEOF_POINTER__
+# elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
+ defined(_M_ARM) || defined(__arm__) || defined(__x86) || \
+ (defined(__TOS_AIX__) && !defined(__64BIT__))
+# define SQLITE_PTRSIZE 4
+# else
+# define SQLITE_PTRSIZE 8
+# endif
+#endif
+
+/* The uptr type is an unsigned integer large enough to hold a pointer
+*/
+#if defined(HAVE_STDINT_H)
+ typedef uintptr_t uptr;
+#elif SQLITE_PTRSIZE==4
+ typedef u32 uptr;
+#else
+ typedef u64 uptr;
+#endif
+
+/*
+** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
+** something between S (inclusive) and E (exclusive).
+**
+** In other words, S is a buffer and E is a pointer to the first byte after
+** the end of buffer S. This macro returns true if P points to something
+** contained within the buffer S.
+*/
+#define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
+
+
+/*
+** Macros to determine whether the machine is big or little endian,
+** and whether or not that determination is run-time or compile-time.
+**
+** For best performance, an attempt is made to guess at the byte-order
+** using C-preprocessor macros. If that is unsuccessful, or if
+** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
+** at run-time.
+*/
+#ifndef SQLITE_BYTEORDER
+# if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
+ defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
+ defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
+ defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
+# define SQLITE_BYTEORDER 1234
+# elif defined(sparc) || defined(__ppc__) || \
+ defined(__ARMEB__) || defined(__AARCH64EB__)
+# define SQLITE_BYTEORDER 4321
+# else
+# define SQLITE_BYTEORDER 0
+# endif
+#endif
+#if SQLITE_BYTEORDER==4321
+# define SQLITE_BIGENDIAN 1
+# define SQLITE_LITTLEENDIAN 0
+# define SQLITE_UTF16NATIVE SQLITE_UTF16BE
+#elif SQLITE_BYTEORDER==1234
+# define SQLITE_BIGENDIAN 0
+# define SQLITE_LITTLEENDIAN 1
+# define SQLITE_UTF16NATIVE SQLITE_UTF16LE
+#else
+# ifdef SQLITE_AMALGAMATION
+ const int sqlite3one = 1;
+# else
+ extern const int sqlite3one;
+# endif
+# define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
+# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
+# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
+#endif
+
+/*
+** Constants for the largest and smallest possible 64-bit signed integers.
+** These macros are designed to work correctly on both 32-bit and 64-bit
+** compilers.
+*/
+#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
+#define LARGEST_UINT64 (0xffffffff|(((u64)0xffffffff)<<32))
+#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
+
+/*
+** Round up a number to the next larger multiple of 8. This is used
+** to force 8-byte alignment on 64-bit architectures.
+*/
+#define ROUND8(x) (((x)+7)&~7)
+
+/*
+** Round down to the nearest multiple of 8
+*/
+#define ROUNDDOWN8(x) ((x)&~7)
+
+/*
+** Assert that the pointer X is aligned to an 8-byte boundary. This
+** macro is used only within assert() to verify that the code gets
+** all alignment restrictions correct.
+**
+** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
+** underlying malloc() implementation might return us 4-byte aligned
+** pointers. In that case, only verify 4-byte alignment.
+*/
+#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
+# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
+#else
+# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
+#endif
+
+/*
+** Disable MMAP on platforms where it is known to not work
+*/
+#if defined(__OpenBSD__) || defined(__QNXNTO__)
+# undef SQLITE_MAX_MMAP_SIZE
+# define SQLITE_MAX_MMAP_SIZE 0
+#endif
+
+/*
+** Default maximum size of memory used by memory-mapped I/O in the VFS
+*/
+#ifdef __APPLE__
+# include <TargetConditionals.h>
+#endif
+#ifndef SQLITE_MAX_MMAP_SIZE
+# if defined(__linux__) \
+ || defined(_WIN32) \
+ || (defined(__APPLE__) && defined(__MACH__)) \
+ || defined(__sun) \
+ || defined(__FreeBSD__) \
+ || defined(__DragonFly__)
+# define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
+# else
+# define SQLITE_MAX_MMAP_SIZE 0
+# endif
+#endif
+
+/*
+** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
+** default MMAP_SIZE is specified at compile-time, make sure that it does
+** not exceed the maximum mmap size.
+*/
+#ifndef SQLITE_DEFAULT_MMAP_SIZE
+# define SQLITE_DEFAULT_MMAP_SIZE 0
+#endif
+#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
+# undef SQLITE_DEFAULT_MMAP_SIZE
+# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
+#endif
+
+/*
+** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
+** the Select query generator tracing logic is turned on.
+*/
+#if defined(SQLITE_ENABLE_SELECTTRACE)
+# define SELECTTRACE_ENABLED 1
+#else
+# define SELECTTRACE_ENABLED 0
+#endif
+#if defined(SQLITE_ENABLE_SELECTTRACE)
+# define SELECTTRACE_ENABLED 1
+# define SELECTTRACE(K,P,S,X) \
+ if(sqlite3_unsupported_selecttrace&(K)) \
+ sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
+ sqlite3DebugPrintf X
+#else
+# define SELECTTRACE(K,P,S,X)
+# define SELECTTRACE_ENABLED 0
+#endif
+
+/*
+** An instance of the following structure is used to store the busy-handler
+** callback for a given sqlite handle.
+**
+** The sqlite.busyHandler member of the sqlite struct contains the busy
+** callback for the database handle. Each pager opened via the sqlite
+** handle is passed a pointer to sqlite.busyHandler. The busy-handler
+** callback is currently invoked only from within pager.c.
+*/
+typedef struct BusyHandler BusyHandler;
+struct BusyHandler {
+ int (*xBusyHandler)(void *,int); /* The busy callback */
+ void *pBusyArg; /* First arg to busy callback */
+ int nBusy; /* Incremented with each busy call */
+};
+
+/*
+** Name of table that holds the database schema.
+*/
+#define DFLT_SCHEMA_TABLE "sqlite_master"
+#define DFLT_TEMP_SCHEMA_TABLE "sqlite_temp_master"
+#define ALT_SCHEMA_TABLE "sqlite_schema"
+#define ALT_TEMP_SCHEMA_TABLE "sqlite_temp_schema"
+
+
+/*
+** The root-page of the schema table.
+*/
+#define SCHEMA_ROOT 1
+
+/*
+** The name of the schema table. The name is different for TEMP.
+*/
+#define SCHEMA_TABLE(x) \
+ ((!OMIT_TEMPDB)&&(x==1)?DFLT_TEMP_SCHEMA_TABLE:DFLT_SCHEMA_TABLE)
+
+/*
+** A convenience macro that returns the number of elements in
+** an array.
+*/
+#define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
+
+/*
+** Determine if the argument is a power of two
+*/
+#define IsPowerOfTwo(X) (((X)&((X)-1))==0)
+
+/*
+** The following value as a destructor means to use sqlite3DbFree().
+** The sqlite3DbFree() routine requires two parameters instead of the
+** one parameter that destructors normally want. So we have to introduce
+** this magic value that the code knows to handle differently. Any
+** pointer will work here as long as it is distinct from SQLITE_STATIC
+** and SQLITE_TRANSIENT.
+*/
+#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3OomFault)
+
+/*
+** When SQLITE_OMIT_WSD is defined, it means that the target platform does
+** not support Writable Static Data (WSD) such as global and static variables.
+** All variables must either be on the stack or dynamically allocated from
+** the heap. When WSD is unsupported, the variable declarations scattered
+** throughout the SQLite code must become constants instead. The SQLITE_WSD
+** macro is used for this purpose. And instead of referencing the variable
+** directly, we use its constant as a key to lookup the run-time allocated
+** buffer that holds real variable. The constant is also the initializer
+** for the run-time allocated buffer.
+**
+** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
+** macros become no-ops and have zero performance impact.
+*/
+#ifdef SQLITE_OMIT_WSD
+ #define SQLITE_WSD const
+ #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
+ #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
+SQLITE_API int sqlite3_wsd_init(int N, int J);
+SQLITE_API void *sqlite3_wsd_find(void *K, int L);
+#else
+ #define SQLITE_WSD
+ #define GLOBAL(t,v) v
+ #define sqlite3GlobalConfig sqlite3Config
+#endif
+
+/*
+** The following macros are used to suppress compiler warnings and to
+** make it clear to human readers when a function parameter is deliberately
+** left unused within the body of a function. This usually happens when
+** a function is called via a function pointer. For example the
+** implementation of an SQL aggregate step callback may not use the
+** parameter indicating the number of arguments passed to the aggregate,
+** if it knows that this is enforced elsewhere.
+**
+** When a function parameter is not used at all within the body of a function,
+** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
+** However, these macros may also be used to suppress warnings related to
+** parameters that may or may not be used depending on compilation options.
+** For example those parameters only used in assert() statements. In these
+** cases the parameters are named as per the usual conventions.
+*/
+#define UNUSED_PARAMETER(x) (void)(x)
+#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
+
+/*
+** Forward references to structures
+*/
+typedef struct AggInfo AggInfo;
+typedef struct AuthContext AuthContext;
+typedef struct AutoincInfo AutoincInfo;
+typedef struct Bitvec Bitvec;
+typedef struct CollSeq CollSeq;
+typedef struct Column Column;
+typedef struct Db Db;
+typedef struct Schema Schema;
+typedef struct Expr Expr;
+typedef struct ExprList ExprList;
+typedef struct FKey FKey;
+typedef struct FuncDestructor FuncDestructor;
+typedef struct FuncDef FuncDef;
+typedef struct FuncDefHash FuncDefHash;
+typedef struct IdList IdList;
+typedef struct Index Index;
+typedef struct IndexSample IndexSample;
+typedef struct KeyClass KeyClass;
+typedef struct KeyInfo KeyInfo;
+typedef struct Lookaside Lookaside;
+typedef struct LookasideSlot LookasideSlot;
+typedef struct Module Module;
+typedef struct NameContext NameContext;
+typedef struct Parse Parse;
+typedef struct PreUpdate PreUpdate;
+typedef struct PrintfArguments PrintfArguments;
+typedef struct RenameToken RenameToken;
+typedef struct RowSet RowSet;
+typedef struct Savepoint Savepoint;
+typedef struct Select Select;
+typedef struct SQLiteThread SQLiteThread;
+typedef struct SelectDest SelectDest;
+typedef struct SrcList SrcList;
+typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
+typedef struct Table Table;
+typedef struct TableLock TableLock;
+typedef struct Token Token;
+typedef struct TreeView TreeView;
+typedef struct Trigger Trigger;
+typedef struct TriggerPrg TriggerPrg;
+typedef struct TriggerStep TriggerStep;
+typedef struct UnpackedRecord UnpackedRecord;
+typedef struct Upsert Upsert;
+typedef struct VTable VTable;
+typedef struct VtabCtx VtabCtx;
+typedef struct Walker Walker;
+typedef struct WhereInfo WhereInfo;
+typedef struct Window Window;
+typedef struct With With;
+
+
+/*
+** The bitmask datatype defined below is used for various optimizations.
+**
+** Changing this from a 64-bit to a 32-bit type limits the number of
+** tables in a join to 32 instead of 64. But it also reduces the size
+** of the library by 738 bytes on ix86.
+*/
+#ifdef SQLITE_BITMASK_TYPE
+ typedef SQLITE_BITMASK_TYPE Bitmask;
+#else
+ typedef u64 Bitmask;
+#endif
+
+/*
+** The number of bits in a Bitmask. "BMS" means "BitMask Size".
+*/
+#define BMS ((int)(sizeof(Bitmask)*8))
+
+/*
+** A bit in a Bitmask
+*/
+#define MASKBIT(n) (((Bitmask)1)<<(n))
+#define MASKBIT64(n) (((u64)1)<<(n))
+#define MASKBIT32(n) (((unsigned int)1)<<(n))
+#define ALLBITS ((Bitmask)-1)
+
+/* A VList object records a mapping between parameters/variables/wildcards
+** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
+** variable number associated with that parameter. See the format description
+** on the sqlite3VListAdd() routine for more information. A VList is really
+** just an array of integers.
+*/
+typedef int VList;
+
+/*
+** Defer sourcing vdbe.h and btree.h until after the "u8" and
+** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
+** pointer types (i.e. FuncDef) defined above.
+*/
+/************** Include pager.h in the middle of sqliteInt.h *****************/
+/************** Begin file pager.h *******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This header file defines the interface that the sqlite page cache
+** subsystem. The page cache subsystem reads and writes a file a page
+** at a time and provides a journal for rollback.
+*/
+
+#ifndef SQLITE_PAGER_H
+#define SQLITE_PAGER_H
+
+/*
+** Default maximum size for persistent journal files. A negative
+** value means no limit. This value may be overridden using the
+** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
+*/
+#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
+ #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
+#endif
+
+/*
+** The type used to represent a page number. The first page in a file
+** is called page 1. 0 is used to represent "not a page".
+*/
+typedef u32 Pgno;
+
+/*
+** Each open file is managed by a separate instance of the "Pager" structure.
+*/
+typedef struct Pager Pager;
+
+/*
+** Handle type for pages.
+*/
+typedef struct PgHdr DbPage;
+
+/*
+** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
+** reserved for working around a windows/posix incompatibility). It is
+** used in the journal to signify that the remainder of the journal file
+** is devoted to storing a super-journal name - there are no more pages to
+** roll back. See comments for function writeSuperJournal() in pager.c
+** for details.
+*/
+#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
+
+/*
+** Allowed values for the flags parameter to sqlite3PagerOpen().
+**
+** NOTE: These values must match the corresponding BTREE_ values in btree.h.
+*/
+#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
+#define PAGER_MEMORY 0x0002 /* In-memory database */
+
+/*
+** Valid values for the second argument to sqlite3PagerLockingMode().
+*/
+#define PAGER_LOCKINGMODE_QUERY -1
+#define PAGER_LOCKINGMODE_NORMAL 0
+#define PAGER_LOCKINGMODE_EXCLUSIVE 1
+
+/*
+** Numeric constants that encode the journalmode.
+**
+** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
+** are exposed in the API via the "PRAGMA journal_mode" command and
+** therefore cannot be changed without a compatibility break.
+*/
+#define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
+#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
+#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
+#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
+#define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
+#define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
+#define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
+
+/*
+** Flags that make up the mask passed to sqlite3PagerGet().
+*/
+#define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
+#define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
+
+/*
+** Flags for sqlite3PagerSetFlags()
+**
+** Value constraints (enforced via assert()):
+** PAGER_FULLFSYNC == SQLITE_FullFSync
+** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
+** PAGER_CACHE_SPILL == SQLITE_CacheSpill
+*/
+#define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
+#define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
+#define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
+#define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
+#define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
+#define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
+#define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
+#define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
+#define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
+
+/*
+** The remainder of this file contains the declarations of the functions
+** that make up the Pager sub-system API. See source code comments for
+** a detailed description of each routine.
+*/
+
+/* Open and close a Pager connection. */
+SQLITE_PRIVATE int sqlite3PagerOpen(
+ sqlite3_vfs*,
+ Pager **ppPager,
+ const char*,
+ int,
+ int,
+ int,
+ void(*)(DbPage*)
+);
+SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
+SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
+
+/* Functions used to configure a Pager object. */
+SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);
+SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
+SQLITE_PRIVATE Pgno sqlite3PagerMaxPageCount(Pager*, Pgno);
+SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
+SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
+SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
+SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
+SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
+SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
+SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
+SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
+SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
+SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
+SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
+SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
+
+/* Functions used to obtain and release page references. */
+SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
+SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
+SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
+SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
+SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
+SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
+
+/* Operations on page references. */
+SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
+SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
+SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
+SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
+SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
+SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
+
+/* Functions used to manage pager transactions and savepoints. */
+SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
+SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
+SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zSuper, int);
+SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
+SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zSuper);
+SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
+SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
+SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
+SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
+SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
+
+#ifndef SQLITE_OMIT_WAL
+SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
+SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
+SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
+SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
+SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
+# ifdef SQLITE_ENABLE_SNAPSHOT
+SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager*, sqlite3_snapshot **ppSnapshot);
+SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager*, sqlite3_snapshot *pSnapshot);
+SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager);
+SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);
+SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager);
+# endif
+#endif
+
+#if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_ENABLE_SETLK_TIMEOUT)
+SQLITE_PRIVATE int sqlite3PagerWalWriteLock(Pager*, int);
+SQLITE_PRIVATE void sqlite3PagerWalDb(Pager*, sqlite3*);
+#else
+# define sqlite3PagerWalWriteLock(y,z) SQLITE_OK
+# define sqlite3PagerWalDb(x,y)
+#endif
+
+#ifdef SQLITE_DIRECT_OVERFLOW_READ
+SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);
+#endif
+
+#ifdef SQLITE_ENABLE_ZIPVFS
+SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
+#endif
+
+/* Functions used to query pager state and configuration. */
+SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
+SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
+#endif
+SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
+SQLITE_PRIVATE const char *sqlite3PagerFilename(const Pager*, int);
+SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
+SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
+SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
+SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
+SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
+SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
+SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
+SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
+SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
+
+/* Functions used to truncate the database file. */
+SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
+
+SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
+
+/* Functions to support testing and debugging. */
+#if !defined(NDEBUG) || defined(SQLITE_TEST)
+SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
+SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
+#endif
+#ifdef SQLITE_TEST
+SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
+SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
+ void disable_simulated_io_errors(void);
+ void enable_simulated_io_errors(void);
+#else
+# define disable_simulated_io_errors()
+# define enable_simulated_io_errors()
+#endif
+
+#endif /* SQLITE_PAGER_H */
+
+/************** End of pager.h ***********************************************/
+/************** Continuing where we left off in sqliteInt.h ******************/
+/************** Include btree.h in the middle of sqliteInt.h *****************/
+/************** Begin file btree.h *******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This header file defines the interface that the sqlite B-Tree file
+** subsystem. See comments in the source code for a detailed description
+** of what each interface routine does.
+*/
+#ifndef SQLITE_BTREE_H
+#define SQLITE_BTREE_H
+
+/* TODO: This definition is just included so other modules compile. It
+** needs to be revisited.
+*/
+#define SQLITE_N_BTREE_META 16
+
+/*
+** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
+** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
+*/
+#ifndef SQLITE_DEFAULT_AUTOVACUUM
+ #define SQLITE_DEFAULT_AUTOVACUUM 0
+#endif
+
+#define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
+#define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
+#define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
+
+/*
+** Forward declarations of structure
+*/
+typedef struct Btree Btree;
+typedef struct BtCursor BtCursor;
+typedef struct BtShared BtShared;
+typedef struct BtreePayload BtreePayload;
+
+
+SQLITE_PRIVATE int sqlite3BtreeOpen(
+ sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
+ const char *zFilename, /* Name of database file to open */
+ sqlite3 *db, /* Associated database connection */
+ Btree **ppBtree, /* Return open Btree* here */
+ int flags, /* Flags */
+ int vfsFlags /* Flags passed through to VFS open */
+);
+
+/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
+** following values.
+**
+** NOTE: These values must match the corresponding PAGER_ values in
+** pager.h.
+*/
+#define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
+#define BTREE_MEMORY 2 /* This is an in-memory DB */
+#define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
+#define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
+
+SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
+SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
+SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
+#if SQLITE_MAX_MMAP_SIZE>0
+SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
+#endif
+SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
+SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
+SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
+SQLITE_PRIVATE Pgno sqlite3BtreeMaxPageCount(Btree*,Pgno);
+SQLITE_PRIVATE Pgno sqlite3BtreeLastPage(Btree*);
+SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
+SQLITE_PRIVATE int sqlite3BtreeGetRequestedReserve(Btree*);
+SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
+SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
+SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
+SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int,int*);
+SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char*);
+SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
+SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
+SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
+SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
+SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, Pgno*, int flags);
+SQLITE_PRIVATE int sqlite3BtreeTxnState(Btree*);
+SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
+
+SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
+SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
+#ifndef SQLITE_OMIT_SHARED_CACHE
+SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
+#endif
+
+/* Savepoints are named, nestable SQL transactions mostly implemented */
+/* in vdbe.c and pager.c See https://sqlite.org/lang_savepoint.html */
+SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
+
+/* "Checkpoint" only refers to WAL. See https://sqlite.org/wal.html#ckpt */
+#ifndef SQLITE_OMIT_WAL
+SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
+#endif
+
+SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
+SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
+SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
+
+SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
+
+/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
+** of the flags shown below.
+**
+** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
+** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
+** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
+** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
+** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
+** indices.)
+*/
+#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
+#define BTREE_BLOBKEY 2 /* Table has keys only - no data */
+
+SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
+SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
+SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
+SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
+
+SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
+SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
+
+SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
+
+/*
+** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
+** should be one of the following values. The integer values are assigned
+** to constants so that the offset of the corresponding field in an
+** SQLite database header may be found using the following formula:
+**
+** offset = 36 + (idx * 4)
+**
+** For example, the free-page-count field is located at byte offset 36 of
+** the database file header. The incr-vacuum-flag field is located at
+** byte offset 64 (== 36+4*7).
+**
+** The BTREE_DATA_VERSION value is not really a value stored in the header.
+** It is a read-only number computed by the pager. But we merge it with
+** the header value access routines since its access pattern is the same.
+** Call it a "virtual meta value".
+*/
+#define BTREE_FREE_PAGE_COUNT 0
+#define BTREE_SCHEMA_VERSION 1
+#define BTREE_FILE_FORMAT 2
+#define BTREE_DEFAULT_CACHE_SIZE 3
+#define BTREE_LARGEST_ROOT_PAGE 4
+#define BTREE_TEXT_ENCODING 5
+#define BTREE_USER_VERSION 6
+#define BTREE_INCR_VACUUM 7
+#define BTREE_APPLICATION_ID 8
+#define BTREE_DATA_VERSION 15 /* A virtual meta-value */
+
+/*
+** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
+** interface.
+**
+** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
+**
+** The first argument is an Expr* (which is guaranteed to be constant for
+** the lifetime of the cursor) that defines constraints on which rows
+** might be fetched with this cursor. The Expr* tree may contain
+** TK_REGISTER nodes that refer to values stored in the array of registers
+** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
+** then the value of the node is the value in Mem[pExpr.iTable]. Any
+** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
+** column of the b-tree of the cursor. The Expr tree will not contain
+** any function calls nor subqueries nor references to b-trees other than
+** the cursor being hinted.
+**
+** The design of the _RANGE hint is aid b-tree implementations that try
+** to prefetch content from remote machines - to provide those
+** implementations with limits on what needs to be prefetched and thereby
+** reduce network bandwidth.
+**
+** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
+** standard SQLite. The other hints are provided for extentions that use
+** the SQLite parser and code generator but substitute their own storage
+** engine.
+*/
+#define BTREE_HINT_RANGE 0 /* Range constraints on queries */
+
+/*
+** Values that may be OR'd together to form the argument to the
+** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
+**
+** The BTREE_BULKLOAD flag is set on index cursors when the index is going
+** to be filled with content that is already in sorted order.
+**
+** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
+** OP_SeekLE opcodes for a range search, but where the range of entries
+** selected will all have the same key. In other words, the cursor will
+** be used only for equality key searches.
+**
+*/
+#define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
+#define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
+
+/*
+** Flags passed as the third argument to sqlite3BtreeCursor().
+**
+** For read-only cursors the wrFlag argument is always zero. For read-write
+** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
+** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
+** only be used by SQLite for the following:
+**
+** * to seek to and then delete specific entries, and/or
+**
+** * to read values that will be used to create keys that other
+** BTREE_FORDELETE cursors will seek to and delete.
+**
+** The BTREE_FORDELETE flag is an optimization hint. It is not used by
+** by this, the native b-tree engine of SQLite, but it is available to
+** alternative storage engines that might be substituted in place of this
+** b-tree system. For alternative storage engines in which a delete of
+** the main table row automatically deletes corresponding index rows,
+** the FORDELETE flag hint allows those alternative storage engines to
+** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
+** and DELETE operations as no-ops, and any READ operation against a
+** FORDELETE cursor may return a null row: 0x01 0x00.
+*/
+#define BTREE_WRCSR 0x00000004 /* read-write cursor */
+#define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
+
+SQLITE_PRIVATE int sqlite3BtreeCursor(
+ Btree*, /* BTree containing table to open */
+ Pgno iTable, /* Index of root page */
+ int wrFlag, /* 1 for writing. 0 for read-only */
+ struct KeyInfo*, /* First argument to compare function */
+ BtCursor *pCursor /* Space to write cursor structure */
+);
+SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
+SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
+SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
+SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
+#ifdef SQLITE_ENABLE_CURSOR_HINTS
+SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
+#endif
+
+SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
+SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
+ BtCursor*,
+ UnpackedRecord *pUnKey,
+ i64 intKey,
+ int bias,
+ int *pRes
+);
+SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
+SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
+SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
+
+/* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
+#define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
+#define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
+#define BTREE_APPEND 0x08 /* Insert is likely an append */
+
+/* An instance of the BtreePayload object describes the content of a single
+** entry in either an index or table btree.
+**
+** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
+** an arbitrary key and no data. These btrees have pKey,nKey set to the
+** key and the pData,nData,nZero fields are uninitialized. The aMem,nMem
+** fields give an array of Mem objects that are a decomposition of the key.
+** The nMem field might be zero, indicating that no decomposition is available.
+**
+** Table btrees (used for rowid tables) contain an integer rowid used as
+** the key and passed in the nKey field. The pKey field is zero.
+** pData,nData hold the content of the new entry. nZero extra zero bytes
+** are appended to the end of the content when constructing the entry.
+** The aMem,nMem fields are uninitialized for table btrees.
+**
+** Field usage summary:
+**
+** Table BTrees Index Btrees
+**
+** pKey always NULL encoded key
+** nKey the ROWID length of pKey
+** pData data not used
+** aMem not used decomposed key value
+** nMem not used entries in aMem
+** nData length of pData not used
+** nZero extra zeros after pData not used
+**
+** This object is used to pass information into sqlite3BtreeInsert(). The
+** same information used to be passed as five separate parameters. But placing
+** the information into this object helps to keep the interface more
+** organized and understandable, and it also helps the resulting code to
+** run a little faster by using fewer registers for parameter passing.
+*/
+struct BtreePayload {
+ const void *pKey; /* Key content for indexes. NULL for tables */
+ sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
+ const void *pData; /* Data for tables. */
+ sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */
+ u16 nMem; /* Number of aMem[] value. Might be zero */
+ int nData; /* Size of pData. 0 if none. */
+ int nZero; /* Extra zero data appended after pData,nData */
+};
+
+SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
+ int flags, int seekResult);
+SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
+SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
+SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
+SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
+SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
+SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
+SQLITE_PRIVATE void sqlite3BtreeCursorPin(BtCursor*);
+SQLITE_PRIVATE void sqlite3BtreeCursorUnpin(BtCursor*);
+#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
+SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);
+#endif
+SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
+SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
+SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
+SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor*);
+
+SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(sqlite3*,Btree*,Pgno*aRoot,int nRoot,int,int*);
+SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
+SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
+
+#ifndef SQLITE_OMIT_INCRBLOB
+SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
+SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
+SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
+#endif
+SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
+SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
+SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
+SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
+SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
+
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE sqlite3_uint64 sqlite3BtreeSeekCount(Btree*);
+#else
+# define sqlite3BtreeSeekCount(X) 0
+#endif
+
+#ifndef NDEBUG
+SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
+#endif
+SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
+
+SQLITE_PRIVATE int sqlite3BtreeCount(sqlite3*, BtCursor*, i64*);
+
+#ifdef SQLITE_TEST
+SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
+SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
+#endif
+
+#ifndef SQLITE_OMIT_WAL
+SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
+#endif
+
+/*
+** If we are not using shared cache, then there is no need to
+** use mutexes to access the BtShared structures. So make the
+** Enter and Leave procedures no-ops.
+*/
+#ifndef SQLITE_OMIT_SHARED_CACHE
+SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
+SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
+SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
+SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
+SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
+#else
+# define sqlite3BtreeEnter(X)
+# define sqlite3BtreeEnterAll(X)
+# define sqlite3BtreeSharable(X) 0
+# define sqlite3BtreeEnterCursor(X)
+# define sqlite3BtreeConnectionCount(X) 1
+#endif
+
+#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
+SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
+SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
+SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
+#ifndef NDEBUG
+ /* These routines are used inside assert() statements only. */
+SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
+SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
+SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
+#endif
+#else
+
+# define sqlite3BtreeLeave(X)
+# define sqlite3BtreeLeaveCursor(X)
+# define sqlite3BtreeLeaveAll(X)
+
+# define sqlite3BtreeHoldsMutex(X) 1
+# define sqlite3BtreeHoldsAllMutexes(X) 1
+# define sqlite3SchemaMutexHeld(X,Y,Z) 1
+#endif
+
+
+#endif /* SQLITE_BTREE_H */
+
+/************** End of btree.h ***********************************************/
+/************** Continuing where we left off in sqliteInt.h ******************/
+/************** Include vdbe.h in the middle of sqliteInt.h ******************/
+/************** Begin file vdbe.h ********************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** Header file for the Virtual DataBase Engine (VDBE)
+**
+** This header defines the interface to the virtual database engine
+** or VDBE. The VDBE implements an abstract machine that runs a
+** simple program to access and modify the underlying database.
+*/
+#ifndef SQLITE_VDBE_H
+#define SQLITE_VDBE_H
+/* #include <stdio.h> */
+
+/*
+** A single VDBE is an opaque structure named "Vdbe". Only routines
+** in the source file sqliteVdbe.c are allowed to see the insides
+** of this structure.
+*/
+typedef struct Vdbe Vdbe;
+
+/*
+** The names of the following types declared in vdbeInt.h are required
+** for the VdbeOp definition.
+*/
+typedef struct sqlite3_value Mem;
+typedef struct SubProgram SubProgram;
+
+/*
+** A single instruction of the virtual machine has an opcode
+** and as many as three operands. The instruction is recorded
+** as an instance of the following structure:
+*/
+struct VdbeOp {
+ u8 opcode; /* What operation to perform */
+ signed char p4type; /* One of the P4_xxx constants for p4 */
+ u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
+ int p1; /* First operand */
+ int p2; /* Second parameter (often the jump destination) */
+ int p3; /* The third parameter */
+ union p4union { /* fourth parameter */
+ int i; /* Integer value if p4type==P4_INT32 */
+ void *p; /* Generic pointer */
+ char *z; /* Pointer to data for string (char array) types */
+ i64 *pI64; /* Used when p4type is P4_INT64 */
+ double *pReal; /* Used when p4type is P4_REAL */
+ FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
+ sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
+ CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
+ Mem *pMem; /* Used when p4type is P4_MEM */
+ VTable *pVtab; /* Used when p4type is P4_VTAB */
+ KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
+ u32 *ai; /* Used when p4type is P4_INTARRAY */
+ SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
+ Table *pTab; /* Used when p4type is P4_TABLE */
+#ifdef SQLITE_ENABLE_CURSOR_HINTS
+ Expr *pExpr; /* Used when p4type is P4_EXPR */
+#endif
+ int (*xAdvance)(BtCursor *, int);
+ } p4;
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+ char *zComment; /* Comment to improve readability */
+#endif
+#ifdef VDBE_PROFILE
+ u32 cnt; /* Number of times this instruction was executed */
+ u64 cycles; /* Total time spent executing this instruction */
+#endif
+#ifdef SQLITE_VDBE_COVERAGE
+ u32 iSrcLine; /* Source-code line that generated this opcode
+ ** with flags in the upper 8 bits */
+#endif
+};
+typedef struct VdbeOp VdbeOp;
+
+
+/*
+** A sub-routine used to implement a trigger program.
+*/
+struct SubProgram {
+ VdbeOp *aOp; /* Array of opcodes for sub-program */
+ int nOp; /* Elements in aOp[] */
+ int nMem; /* Number of memory cells required */
+ int nCsr; /* Number of cursors required */
+ u8 *aOnce; /* Array of OP_Once flags */
+ void *token; /* id that may be used to recursive triggers */
+ SubProgram *pNext; /* Next sub-program already visited */
+};
+
+/*
+** A smaller version of VdbeOp used for the VdbeAddOpList() function because
+** it takes up less space.
+*/
+struct VdbeOpList {
+ u8 opcode; /* What operation to perform */
+ signed char p1; /* First operand */
+ signed char p2; /* Second parameter (often the jump destination) */
+ signed char p3; /* Third parameter */
+};
+typedef struct VdbeOpList VdbeOpList;
+
+/*
+** Allowed values of VdbeOp.p4type
+*/
+#define P4_NOTUSED 0 /* The P4 parameter is not used */
+#define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
+#define P4_STATIC (-1) /* Pointer to a static string */
+#define P4_COLLSEQ (-2) /* P4 is a pointer to a CollSeq structure */
+#define P4_INT32 (-3) /* P4 is a 32-bit signed integer */
+#define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */
+#define P4_ADVANCE (-5) /* P4 is a pointer to BtreeNext() or BtreePrev() */
+#define P4_TABLE (-6) /* P4 is a pointer to a Table structure */
+/* Above do not own any resources. Must free those below */
+#define P4_FREE_IF_LE (-7)
+#define P4_DYNAMIC (-7) /* Pointer to memory from sqliteMalloc() */
+#define P4_FUNCDEF (-8) /* P4 is a pointer to a FuncDef structure */
+#define P4_KEYINFO (-9) /* P4 is a pointer to a KeyInfo structure */
+#define P4_EXPR (-10) /* P4 is a pointer to an Expr tree */
+#define P4_MEM (-11) /* P4 is a pointer to a Mem* structure */
+#define P4_VTAB (-12) /* P4 is a pointer to an sqlite3_vtab structure */
+#define P4_REAL (-13) /* P4 is a 64-bit floating point value */
+#define P4_INT64 (-14) /* P4 is a 64-bit signed integer */
+#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
+#define P4_FUNCCTX (-16) /* P4 is a pointer to an sqlite3_context object */
+#define P4_DYNBLOB (-17) /* Pointer to memory from sqliteMalloc() */
+
+/* Error message codes for OP_Halt */
+#define P5_ConstraintNotNull 1
+#define P5_ConstraintUnique 2
+#define P5_ConstraintCheck 3
+#define P5_ConstraintFK 4
+
+/*
+** The Vdbe.aColName array contains 5n Mem structures, where n is the
+** number of columns of data returned by the statement.
+*/
+#define COLNAME_NAME 0
+#define COLNAME_DECLTYPE 1
+#define COLNAME_DATABASE 2
+#define COLNAME_TABLE 3
+#define COLNAME_COLUMN 4
+#ifdef SQLITE_ENABLE_COLUMN_METADATA
+# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
+#else
+# ifdef SQLITE_OMIT_DECLTYPE
+# define COLNAME_N 1 /* Store only the name */
+# else
+# define COLNAME_N 2 /* Store the name and decltype */
+# endif
+#endif
+
+/*
+** The following macro converts a label returned by sqlite3VdbeMakeLabel()
+** into an index into the Parse.aLabel[] array that contains the resolved
+** address of that label.
+*/
+#define ADDR(X) (~(X))
+
+/*
+** The makefile scans the vdbe.c source file and creates the "opcodes.h"
+** header file that defines a number for each opcode used by the VDBE.
+*/
+/************** Include opcodes.h in the middle of vdbe.h ********************/
+/************** Begin file opcodes.h *****************************************/
+/* Automatically generated. Do not edit */
+/* See the tool/mkopcodeh.tcl script for details */
+#define OP_Savepoint 0
+#define OP_AutoCommit 1
+#define OP_Transaction 2
+#define OP_SorterNext 3 /* jump */
+#define OP_Prev 4 /* jump */
+#define OP_Next 5 /* jump */
+#define OP_Checkpoint 6
+#define OP_JournalMode 7
+#define OP_Vacuum 8
+#define OP_VFilter 9 /* jump, synopsis: iplan=r[P3] zplan='P4' */
+#define OP_VUpdate 10 /* synopsis: data=r[P3@P2] */
+#define OP_Goto 11 /* jump */
+#define OP_Gosub 12 /* jump */
+#define OP_InitCoroutine 13 /* jump */
+#define OP_Yield 14 /* jump */
+#define OP_MustBeInt 15 /* jump */
+#define OP_Jump 16 /* jump */
+#define OP_Once 17 /* jump */
+#define OP_If 18 /* jump */
+#define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
+#define OP_IfNot 20 /* jump */
+#define OP_IfNullRow 21 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
+#define OP_SeekLT 22 /* jump, synopsis: key=r[P3@P4] */
+#define OP_SeekLE 23 /* jump, synopsis: key=r[P3@P4] */
+#define OP_SeekGE 24 /* jump, synopsis: key=r[P3@P4] */
+#define OP_SeekGT 25 /* jump, synopsis: key=r[P3@P4] */
+#define OP_IfNotOpen 26 /* jump, synopsis: if( !csr[P1] ) goto P2 */
+#define OP_IfNoHope 27 /* jump, synopsis: key=r[P3@P4] */
+#define OP_NoConflict 28 /* jump, synopsis: key=r[P3@P4] */
+#define OP_NotFound 29 /* jump, synopsis: key=r[P3@P4] */
+#define OP_Found 30 /* jump, synopsis: key=r[P3@P4] */
+#define OP_SeekRowid 31 /* jump, synopsis: intkey=r[P3] */
+#define OP_NotExists 32 /* jump, synopsis: intkey=r[P3] */
+#define OP_Last 33 /* jump */
+#define OP_IfSmaller 34 /* jump */
+#define OP_SorterSort 35 /* jump */
+#define OP_Sort 36 /* jump */
+#define OP_Rewind 37 /* jump */
+#define OP_IdxLE 38 /* jump, synopsis: key=r[P3@P4] */
+#define OP_IdxGT 39 /* jump, synopsis: key=r[P3@P4] */
+#define OP_IdxLT 40 /* jump, synopsis: key=r[P3@P4] */
+#define OP_IdxGE 41 /* jump, synopsis: key=r[P3@P4] */
+#define OP_RowSetRead 42 /* jump, synopsis: r[P3]=rowset(P1) */
+#define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
+#define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
+#define OP_RowSetTest 45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
+#define OP_Program 46 /* jump */
+#define OP_FkIfZero 47 /* jump, synopsis: if fkctr[P1]==0 goto P2 */
+#define OP_IfPos 48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
+#define OP_IfNotZero 49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
+#define OP_IsNull 50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
+#define OP_NotNull 51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
+#define OP_Ne 52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
+#define OP_Eq 53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
+#define OP_Gt 54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
+#define OP_Le 55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
+#define OP_Lt 56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
+#define OP_Ge 57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
+#define OP_ElseNotEq 58 /* jump, same as TK_ESCAPE */
+#define OP_DecrJumpZero 59 /* jump, synopsis: if (--r[P1])==0 goto P2 */
+#define OP_IncrVacuum 60 /* jump */
+#define OP_VNext 61 /* jump */
+#define OP_Init 62 /* jump, synopsis: Start at P2 */
+#define OP_PureFunc 63 /* synopsis: r[P3]=func(r[P2@NP]) */
+#define OP_Function 64 /* synopsis: r[P3]=func(r[P2@NP]) */
+#define OP_Return 65
+#define OP_EndCoroutine 66
+#define OP_HaltIfNull 67 /* synopsis: if r[P3]=null halt */
+#define OP_Halt 68
+#define OP_Integer 69 /* synopsis: r[P2]=P1 */
+#define OP_Int64 70 /* synopsis: r[P2]=P4 */
+#define OP_String 71 /* synopsis: r[P2]='P4' (len=P1) */
+#define OP_Null 72 /* synopsis: r[P2..P3]=NULL */
+#define OP_SoftNull 73 /* synopsis: r[P1]=NULL */
+#define OP_Blob 74 /* synopsis: r[P2]=P4 (len=P1) */
+#define OP_Variable 75 /* synopsis: r[P2]=parameter(P1,P4) */
+#define OP_Move 76 /* synopsis: r[P2@P3]=r[P1@P3] */
+#define OP_Copy 77 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
+#define OP_SCopy 78 /* synopsis: r[P2]=r[P1] */
+#define OP_IntCopy 79 /* synopsis: r[P2]=r[P1] */
+#define OP_ResultRow 80 /* synopsis: output=r[P1@P2] */
+#define OP_CollSeq 81
+#define OP_AddImm 82 /* synopsis: r[P1]=r[P1]+P2 */
+#define OP_RealAffinity 83
+#define OP_Cast 84 /* synopsis: affinity(r[P1]) */
+#define OP_Permutation 85
+#define OP_Compare 86 /* synopsis: r[P1@P3] <-> r[P2@P3] */
+#define OP_IsTrue 87 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
+#define OP_Offset 88 /* synopsis: r[P3] = sqlite_offset(P1) */
+#define OP_Column 89 /* synopsis: r[P3]=PX */
+#define OP_Affinity 90 /* synopsis: affinity(r[P1@P2]) */
+#define OP_MakeRecord 91 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
+#define OP_Count 92 /* synopsis: r[P2]=count() */
+#define OP_ReadCookie 93
+#define OP_SetCookie 94
+#define OP_ReopenIdx 95 /* synopsis: root=P2 iDb=P3 */
+#define OP_OpenRead 96 /* synopsis: root=P2 iDb=P3 */
+#define OP_OpenWrite 97 /* synopsis: root=P2 iDb=P3 */
+#define OP_OpenDup 98
+#define OP_OpenAutoindex 99 /* synopsis: nColumn=P2 */
+#define OP_OpenEphemeral 100 /* synopsis: nColumn=P2 */
+#define OP_BitAnd 101 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
+#define OP_BitOr 102 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
+#define OP_ShiftLeft 103 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
+#define OP_ShiftRight 104 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
+#define OP_Add 105 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
+#define OP_Subtract 106 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
+#define OP_Multiply 107 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
+#define OP_Divide 108 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
+#define OP_Remainder 109 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
+#define OP_Concat 110 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
+#define OP_SorterOpen 111
+#define OP_BitNot 112 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
+#define OP_SequenceTest 113 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
+#define OP_OpenPseudo 114 /* synopsis: P3 columns in r[P2] */
+#define OP_String8 115 /* same as TK_STRING, synopsis: r[P2]='P4' */
+#define OP_Close 116
+#define OP_ColumnsUsed 117
+#define OP_SeekScan 118 /* synopsis: Scan-ahead up to P1 rows */
+#define OP_SeekHit 119 /* synopsis: set P2<=seekHit<=P3 */
+#define OP_Sequence 120 /* synopsis: r[P2]=cursor[P1].ctr++ */
+#define OP_NewRowid 121 /* synopsis: r[P2]=rowid */
+#define OP_Insert 122 /* synopsis: intkey=r[P3] data=r[P2] */
+#define OP_Delete 123
+#define OP_ResetCount 124
+#define OP_SorterCompare 125 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
+#define OP_SorterData 126 /* synopsis: r[P2]=data */
+#define OP_RowData 127 /* synopsis: r[P2]=data */
+#define OP_Rowid 128 /* synopsis: r[P2]=rowid */
+#define OP_NullRow 129
+#define OP_SeekEnd 130
+#define OP_IdxInsert 131 /* synopsis: key=r[P2] */
+#define OP_SorterInsert 132 /* synopsis: key=r[P2] */
+#define OP_IdxDelete 133 /* synopsis: key=r[P2@P3] */
+#define OP_DeferredSeek 134 /* synopsis: Move P3 to P1.rowid if needed */
+#define OP_IdxRowid 135 /* synopsis: r[P2]=rowid */
+#define OP_FinishSeek 136
+#define OP_Destroy 137
+#define OP_Clear 138
+#define OP_ResetSorter 139
+#define OP_CreateBtree 140 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
+#define OP_SqlExec 141
+#define OP_ParseSchema 142
+#define OP_LoadAnalysis 143
+#define OP_DropTable 144
+#define OP_DropIndex 145
+#define OP_DropTrigger 146
+#define OP_IntegrityCk 147
+#define OP_RowSetAdd 148 /* synopsis: rowset(P1)=r[P2] */
+#define OP_Param 149
+#define OP_Real 150 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
+#define OP_FkCounter 151 /* synopsis: fkctr[P1]+=P2 */
+#define OP_MemMax 152 /* synopsis: r[P1]=max(r[P1],r[P2]) */
+#define OP_OffsetLimit 153 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
+#define OP_AggInverse 154 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */
+#define OP_AggStep 155 /* synopsis: accum=r[P3] step(r[P2@P5]) */
+#define OP_AggStep1 156 /* synopsis: accum=r[P3] step(r[P2@P5]) */
+#define OP_AggValue 157 /* synopsis: r[P3]=value N=P2 */
+#define OP_AggFinal 158 /* synopsis: accum=r[P1] N=P2 */
+#define OP_Expire 159
+#define OP_CursorLock 160
+#define OP_CursorUnlock 161
+#define OP_TableLock 162 /* synopsis: iDb=P1 root=P2 write=P3 */
+#define OP_VBegin 163
+#define OP_VCreate 164
+#define OP_VDestroy 165
+#define OP_VOpen 166
+#define OP_VColumn 167 /* synopsis: r[P3]=vcolumn(P2) */
+#define OP_VRename 168
+#define OP_Pagecount 169
+#define OP_MaxPgcnt 170
+#define OP_Trace 171
+#define OP_CursorHint 172
+#define OP_ReleaseReg 173 /* synopsis: release r[P1@P2] mask P3 */
+#define OP_Noop 174
+#define OP_Explain 175
+#define OP_Abortable 176
+
+/* Properties such as "out2" or "jump" that are specified in
+** comments following the "case" for each opcode in the vdbe.c
+** are encoded into bitvectors as follows:
+*/
+#define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
+#define OPFLG_IN1 0x02 /* in1: P1 is an input */
+#define OPFLG_IN2 0x04 /* in2: P2 is an input */
+#define OPFLG_IN3 0x08 /* in3: P3 is an input */
+#define OPFLG_OUT2 0x10 /* out2: P2 is an output */
+#define OPFLG_OUT3 0x20 /* out3: P3 is an output */
+#define OPFLG_INITIALIZER {\
+/* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x10,\
+/* 8 */ 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x03, 0x03,\
+/* 16 */ 0x01, 0x01, 0x03, 0x12, 0x03, 0x01, 0x09, 0x09,\
+/* 24 */ 0x09, 0x09, 0x01, 0x09, 0x09, 0x09, 0x09, 0x09,\
+/* 32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
+/* 40 */ 0x01, 0x01, 0x23, 0x26, 0x26, 0x0b, 0x01, 0x01,\
+/* 48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
+/* 56 */ 0x0b, 0x0b, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00,\
+/* 64 */ 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10,\
+/* 72 */ 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10,\
+/* 80 */ 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x12,\
+/* 88 */ 0x20, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
+/* 96 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x26, 0x26,\
+/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\
+/* 112 */ 0x12, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\
+/* 120 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
+/* 128 */ 0x10, 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x10,\
+/* 136 */ 0x00, 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,\
+/* 144 */ 0x00, 0x00, 0x00, 0x00, 0x06, 0x10, 0x10, 0x00,\
+/* 152 */ 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
+/* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
+/* 168 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
+/* 176 */ 0x00,}
+
+/* The sqlite3P2Values() routine is able to run faster if it knows
+** the value of the largest JUMP opcode. The smaller the maximum
+** JUMP opcode the better, so the mkopcodeh.tcl script that
+** generated this include file strives to group all JUMP opcodes
+** together near the beginning of the list.
+*/
+#define SQLITE_MX_JUMP_OPCODE 62 /* Maximum JUMP opcode */
+
+/************** End of opcodes.h *********************************************/
+/************** Continuing where we left off in vdbe.h ***********************/
+
+/*
+** Additional non-public SQLITE_PREPARE_* flags
+*/
+#define SQLITE_PREPARE_SAVESQL 0x80 /* Preserve SQL text */
+#define SQLITE_PREPARE_MASK 0x0f /* Mask of public flags */
+
+/*
+** Prototypes for the VDBE interface. See comments on the implementation
+** for a description of what each of these routines does.
+*/
+SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
+SQLITE_PRIVATE Parse *sqlite3VdbeParser(Vdbe*);
+SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
+SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
+SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
+SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
+SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
+SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
+SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
+SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
+SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
+SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
+SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall(Parse*,int,int,int,int,const FuncDef*,int);
+SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
+#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
+SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
+SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
+#else
+# define sqlite3VdbeVerifyNoMallocRequired(A,B)
+# define sqlite3VdbeVerifyNoResultRow(A)
+#endif
+#if defined(SQLITE_DEBUG)
+SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int);
+#else
+# define sqlite3VdbeVerifyAbortable(A,B)
+#endif
+SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno);
+#ifndef SQLITE_OMIT_EXPLAIN
+SQLITE_PRIVATE void sqlite3VdbeExplain(Parse*,u8,const char*,...);
+SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse*);
+SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse*);
+# define ExplainQueryPlan(P) sqlite3VdbeExplain P
+# define ExplainQueryPlanPop(P) sqlite3VdbeExplainPop(P)
+# define ExplainQueryPlanParent(P) sqlite3VdbeExplainParent(P)
+#else
+# define ExplainQueryPlan(P)
+# define ExplainQueryPlanPop(P)
+# define ExplainQueryPlanParent(P) 0
+# define sqlite3ExplainBreakpoint(A,B) /*no-op*/
+#endif
+#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN)
+SQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char*,const char*);
+#else
+# define sqlite3ExplainBreakpoint(A,B) /*no-op*/
+#endif
+SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
+SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, int addr, u8);
+SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
+SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
+SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
+SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
+SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
+SQLITE_PRIVATE void sqlite3VdbeJumpHereOrPopInst(Vdbe*, int addr);
+SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
+SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE void sqlite3VdbeReleaseRegisters(Parse*,int addr, int n, u32 mask, int);
+#else
+# define sqlite3VdbeReleaseRegisters(P,A,N,M,F)
+#endif
+SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
+SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
+SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
+SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
+SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
+SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse*);
+SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
+SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
+SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
+SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
+SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
+SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
+SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
+SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
+#endif
+SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
+SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
+SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
+SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
+SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
+SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
+SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
+SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
+SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
+#ifdef SQLITE_ENABLE_NORMALIZE
+SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3*,Vdbe*,const char*);
+SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(Vdbe*,const char*);
+#endif
+SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
+SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
+SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
+SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
+#ifndef SQLITE_OMIT_TRACE
+SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
+#endif
+SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
+SQLITE_PRIVATE int sqlite3BlobCompare(const Mem*, const Mem*);
+
+SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
+SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
+SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
+SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
+
+typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
+SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
+
+SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
+SQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe*);
+
+SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
+#ifdef SQLITE_ENABLE_BYTECODE_VTAB
+SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3*);
+#endif
+
+/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
+** each VDBE opcode.
+**
+** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
+** comments in VDBE programs that show key decision points in the code
+** generator.
+*/
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
+# define VdbeComment(X) sqlite3VdbeComment X
+SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
+# define VdbeNoopComment(X) sqlite3VdbeNoopComment X
+# ifdef SQLITE_ENABLE_MODULE_COMMENTS
+# define VdbeModuleComment(X) sqlite3VdbeNoopComment X
+# else
+# define VdbeModuleComment(X)
+# endif
+#else
+# define VdbeComment(X)
+# define VdbeNoopComment(X)
+# define VdbeModuleComment(X)
+#endif
+
+/*
+** The VdbeCoverage macros are used to set a coverage testing point
+** for VDBE branch instructions. The coverage testing points are line
+** numbers in the sqlite3.c source file. VDBE branch coverage testing
+** only works with an amalagmation build. That's ok since a VDBE branch
+** coverage build designed for testing the test suite only. No application
+** should ever ship with VDBE branch coverage measuring turned on.
+**
+** VdbeCoverage(v) // Mark the previously coded instruction
+** // as a branch
+**
+** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
+**
+** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
+**
+** VdbeCoverageNeverTaken(v) // Previous branch is never taken
+**
+** VdbeCoverageNeverNull(v) // Previous three-way branch is only
+** // taken on the first two ways. The
+** // NULL option is not possible
+**
+** VdbeCoverageEqNe(v) // Previous OP_Jump is only interested
+** // in distingishing equal and not-equal.
+**
+** Every VDBE branch operation must be tagged with one of the macros above.
+** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
+** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
+** routine in vdbe.c, alerting the developer to the missed tag.
+**
+** During testing, the test application will invoke
+** sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE,...) to set a callback
+** routine that is invoked as each bytecode branch is taken. The callback
+** contains the sqlite3.c source line number ov the VdbeCoverage macro and
+** flags to indicate whether or not the branch was taken. The test application
+** is responsible for keeping track of this and reporting byte-code branches
+** that are never taken.
+**
+** See the VdbeBranchTaken() macro and vdbeTakeBranch() function in the
+** vdbe.c source file for additional information.
+*/
+#ifdef SQLITE_VDBE_COVERAGE
+SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
+# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
+# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
+# define VdbeCoverageAlwaysTaken(v) \
+ sqlite3VdbeSetLineNumber(v,__LINE__|0x5000000);
+# define VdbeCoverageNeverTaken(v) \
+ sqlite3VdbeSetLineNumber(v,__LINE__|0x6000000);
+# define VdbeCoverageNeverNull(v) \
+ sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
+# define VdbeCoverageNeverNullIf(v,x) \
+ if(x)sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
+# define VdbeCoverageEqNe(v) \
+ sqlite3VdbeSetLineNumber(v,__LINE__|0x8000000);
+# define VDBE_OFFSET_LINENO(x) (__LINE__+x)
+#else
+# define VdbeCoverage(v)
+# define VdbeCoverageIf(v,x)
+# define VdbeCoverageAlwaysTaken(v)
+# define VdbeCoverageNeverTaken(v)
+# define VdbeCoverageNeverNull(v)
+# define VdbeCoverageNeverNullIf(v,x)
+# define VdbeCoverageEqNe(v)
+# define VDBE_OFFSET_LINENO(x) 0
+#endif
+
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
+#else
+# define sqlite3VdbeScanStatus(a,b,c,d,e)
+#endif
+
+#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
+SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);
+#endif
+
+#endif /* SQLITE_VDBE_H */
+
+/************** End of vdbe.h ************************************************/
+/************** Continuing where we left off in sqliteInt.h ******************/
+/************** Include pcache.h in the middle of sqliteInt.h ****************/
+/************** Begin file pcache.h ******************************************/
+/*
+** 2008 August 05
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This header file defines the interface that the sqlite page cache
+** subsystem.
+*/
+
+#ifndef _PCACHE_H_
+
+typedef struct PgHdr PgHdr;
+typedef struct PCache PCache;
+
+/*
+** Every page in the cache is controlled by an instance of the following
+** structure.
+*/
+struct PgHdr {
+ sqlite3_pcache_page *pPage; /* Pcache object page handle */
+ void *pData; /* Page data */
+ void *pExtra; /* Extra content */
+ PCache *pCache; /* PRIVATE: Cache that owns this page */
+ PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
+ Pager *pPager; /* The pager this page is part of */
+ Pgno pgno; /* Page number for this page */
+#ifdef SQLITE_CHECK_PAGES
+ u32 pageHash; /* Hash of page content */
+#endif
+ u16 flags; /* PGHDR flags defined below */
+
+ /**********************************************************************
+ ** Elements above, except pCache, are public. All that follow are
+ ** private to pcache.c and should not be accessed by other modules.
+ ** pCache is grouped with the public elements for efficiency.
+ */
+ i16 nRef; /* Number of users of this page */
+ PgHdr *pDirtyNext; /* Next element in list of dirty pages */
+ PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
+ /* NB: pDirtyNext and pDirtyPrev are undefined if the
+ ** PgHdr object is not dirty */
+};
+
+/* Bit values for PgHdr.flags */
+#define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
+#define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
+#define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
+#define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
+ ** writing this page to the database */
+#define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
+#define PGHDR_MMAP 0x020 /* This is an mmap page object */
+
+#define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
+
+/* Initialize and shutdown the page cache subsystem */
+SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
+SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
+
+/* Page cache buffer management:
+** These routines implement SQLITE_CONFIG_PAGECACHE.
+*/
+SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
+
+/* Create a new pager cache.
+** Under memory stress, invoke xStress to try to make pages clean.
+** Only clean and unpinned pages can be reclaimed.
+*/
+SQLITE_PRIVATE int sqlite3PcacheOpen(
+ int szPage, /* Size of every page */
+ int szExtra, /* Extra space associated with each page */
+ int bPurgeable, /* True if pages are on backing store */
+ int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
+ void *pStress, /* Argument to xStress */
+ PCache *pToInit /* Preallocated space for the PCache */
+);
+
+/* Modify the page-size after the cache has been created. */
+SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
+
+/* Return the size in bytes of a PCache object. Used to preallocate
+** storage space.
+*/
+SQLITE_PRIVATE int sqlite3PcacheSize(void);
+
+/* One release per successful fetch. Page is pinned until released.
+** Reference counted.
+*/
+SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
+SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
+SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
+SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
+
+SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
+SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
+SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
+SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
+SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
+
+/* Change a page number. Used by incr-vacuum. */
+SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
+
+/* Remove all pages with pgno>x. Reset the cache if x==0 */
+SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
+
+/* Get a list of all dirty pages in the cache, sorted by page number */
+SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
+
+/* Reset and close the cache object */
+SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
+
+/* Clear flags from pages of the page cache */
+SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
+
+/* Discard the contents of the cache */
+SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
+
+/* Return the total number of outstanding page references */
+SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
+
+/* Increment the reference count of an existing page */
+SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
+
+SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
+
+/* Return the total number of pages stored in the cache */
+SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
+
+#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
+/* Iterate through all dirty pages currently stored in the cache. This
+** interface is only available if SQLITE_CHECK_PAGES is defined when the
+** library is built.
+*/
+SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
+#endif
+
+#if defined(SQLITE_DEBUG)
+/* Check invariants on a PgHdr object */
+SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
+#endif
+
+/* Set and get the suggested cache-size for the specified pager-cache.
+**
+** If no global maximum is configured, then the system attempts to limit
+** the total number of pages cached by purgeable pager-caches to the sum
+** of the suggested cache-sizes.
+*/
+SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
+#ifdef SQLITE_TEST
+SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
+#endif
+
+/* Set or get the suggested spill-size for the specified pager-cache.
+**
+** The spill-size is the minimum number of pages in cache before the cache
+** will attempt to spill dirty pages by calling xStress.
+*/
+SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
+
+/* Free up as much memory as possible from the page cache */
+SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
+
+#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
+/* Try to return memory used by the pcache module to the main memory heap */
+SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
+#endif
+
+#ifdef SQLITE_TEST
+SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
+#endif
+
+SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
+
+/* Return the header size */
+SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
+SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
+
+/* Number of dirty pages as a percentage of the configured cache size */
+SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
+
+#ifdef SQLITE_DIRECT_OVERFLOW_READ
+SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
+#endif
+
+#endif /* _PCACHE_H_ */
+
+/************** End of pcache.h **********************************************/
+/************** Continuing where we left off in sqliteInt.h ******************/
+/************** Include os.h in the middle of sqliteInt.h ********************/
+/************** Begin file os.h **********************************************/
+/*
+** 2001 September 16
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This header file (together with is companion C source-code file
+** "os.c") attempt to abstract the underlying operating system so that
+** the SQLite library will work on both POSIX and windows systems.
+**
+** This header file is #include-ed by sqliteInt.h and thus ends up
+** being included by every source file.
+*/
+#ifndef _SQLITE_OS_H_
+#define _SQLITE_OS_H_
+
+/*
+** Attempt to automatically detect the operating system and setup the
+** necessary pre-processor macros for it.
+*/
+/************** Include os_setup.h in the middle of os.h *********************/
+/************** Begin file os_setup.h ****************************************/
+/*
+** 2013 November 25
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains pre-processor directives related to operating system
+** detection and/or setup.
+*/
+#ifndef SQLITE_OS_SETUP_H
+#define SQLITE_OS_SETUP_H
+
+/*
+** Figure out if we are dealing with Unix, Windows, or some other operating
+** system.
+**
+** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
+** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
+** the three will be 1. The other two will be 0.
+*/
+#if defined(SQLITE_OS_OTHER)
+# if SQLITE_OS_OTHER==1
+# undef SQLITE_OS_UNIX
+# define SQLITE_OS_UNIX 0
+# undef SQLITE_OS_WIN
+# define SQLITE_OS_WIN 0
+# else
+# undef SQLITE_OS_OTHER
+# endif
+#endif
+#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
+# define SQLITE_OS_OTHER 0
+# ifndef SQLITE_OS_WIN
+# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
+ defined(__MINGW32__) || defined(__BORLANDC__)
+# define SQLITE_OS_WIN 1
+# define SQLITE_OS_UNIX 0
+# else
+# define SQLITE_OS_WIN 0
+# define SQLITE_OS_UNIX 1
+# endif
+# else
+# define SQLITE_OS_UNIX 0
+# endif
+#else
+# ifndef SQLITE_OS_WIN
+# define SQLITE_OS_WIN 0
+# endif
+#endif
+
+#endif /* SQLITE_OS_SETUP_H */
+
+/************** End of os_setup.h ********************************************/
+/************** Continuing where we left off in os.h *************************/
+
+/* If the SET_FULLSYNC macro is not defined above, then make it
+** a no-op
+*/
+#ifndef SET_FULLSYNC
+# define SET_FULLSYNC(x,y)
+#endif
+
+/*
+** The default size of a disk sector
+*/
+#ifndef SQLITE_DEFAULT_SECTOR_SIZE
+# define SQLITE_DEFAULT_SECTOR_SIZE 4096
+#endif
+
+/*
+** Temporary files are named starting with this prefix followed by 16 random
+** alphanumeric characters, and no file extension. They are stored in the
+** OS's standard temporary file directory, and are deleted prior to exit.
+** If sqlite is being embedded in another program, you may wish to change the
+** prefix to reflect your program's name, so that if your program exits
+** prematurely, old temporary files can be easily identified. This can be done
+** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
+**
+** 2006-10-31: The default prefix used to be "sqlite_". But then
+** Mcafee started using SQLite in their anti-virus product and it
+** started putting files with the "sqlite" name in the c:/temp folder.
+** This annoyed many windows users. Those users would then do a
+** Google search for "sqlite", find the telephone numbers of the
+** developers and call to wake them up at night and complain.
+** For this reason, the default name prefix is changed to be "sqlite"
+** spelled backwards. So the temp files are still identified, but
+** anybody smart enough to figure out the code is also likely smart
+** enough to know that calling the developer will not help get rid
+** of the file.
+*/
+#ifndef SQLITE_TEMP_FILE_PREFIX
+# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
+#endif
+
+/*
+** The following values may be passed as the second argument to
+** sqlite3OsLock(). The various locks exhibit the following semantics:
+**
+** SHARED: Any number of processes may hold a SHARED lock simultaneously.
+** RESERVED: A single process may hold a RESERVED lock on a file at
+** any time. Other processes may hold and obtain new SHARED locks.
+** PENDING: A single process may hold a PENDING lock on a file at
+** any one time. Existing SHARED locks may persist, but no new
+** SHARED locks may be obtained by other processes.
+** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
+**
+** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
+** process that requests an EXCLUSIVE lock may actually obtain a PENDING
+** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
+** sqlite3OsLock().
+*/
+#define NO_LOCK 0
+#define SHARED_LOCK 1
+#define RESERVED_LOCK 2
+#define PENDING_LOCK 3
+#define EXCLUSIVE_LOCK 4
+
+/*
+** File Locking Notes: (Mostly about windows but also some info for Unix)
+**
+** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
+** those functions are not available. So we use only LockFile() and
+** UnlockFile().
+**
+** LockFile() prevents not just writing but also reading by other processes.
+** A SHARED_LOCK is obtained by locking a single randomly-chosen
+** byte out of a specific range of bytes. The lock byte is obtained at
+** random so two separate readers can probably access the file at the
+** same time, unless they are unlucky and choose the same lock byte.
+** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
+** There can only be one writer. A RESERVED_LOCK is obtained by locking
+** a single byte of the file that is designated as the reserved lock byte.
+** A PENDING_LOCK is obtained by locking a designated byte different from
+** the RESERVED_LOCK byte.
+**
+** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
+** which means we can use reader/writer locks. When reader/writer locks
+** are used, the lock is placed on the same range of bytes that is used
+** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
+** will support two or more Win95 readers or two or more WinNT readers.
+** But a single Win95 reader will lock out all WinNT readers and a single
+** WinNT reader will lock out all other Win95 readers.
+**
+** The following #defines specify the range of bytes used for locking.
+** SHARED_SIZE is the number of bytes available in the pool from which
+** a random byte is selected for a shared lock. The pool of bytes for
+** shared locks begins at SHARED_FIRST.
+**
+** The same locking strategy and
+** byte ranges are used for Unix. This leaves open the possibility of having
+** clients on win95, winNT, and unix all talking to the same shared file
+** and all locking correctly. To do so would require that samba (or whatever
+** tool is being used for file sharing) implements locks correctly between
+** windows and unix. I'm guessing that isn't likely to happen, but by
+** using the same locking range we are at least open to the possibility.
+**
+** Locking in windows is manditory. For this reason, we cannot store
+** actual data in the bytes used for locking. The pager never allocates
+** the pages involved in locking therefore. SHARED_SIZE is selected so
+** that all locks will fit on a single page even at the minimum page size.
+** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
+** is set high so that we don't have to allocate an unused page except
+** for very large databases. But one should test the page skipping logic
+** by setting PENDING_BYTE low and running the entire regression suite.
+**
+** Changing the value of PENDING_BYTE results in a subtly incompatible
+** file format. Depending on how it is changed, you might not notice
+** the incompatibility right away, even running a full regression test.
+** The default location of PENDING_BYTE is the first byte past the
+** 1GB boundary.
+**
+*/
+#ifdef SQLITE_OMIT_WSD
+# define PENDING_BYTE (0x40000000)
+#else
+# define PENDING_BYTE sqlite3PendingByte
+#endif
+#define RESERVED_BYTE (PENDING_BYTE+1)
+#define SHARED_FIRST (PENDING_BYTE+2)
+#define SHARED_SIZE 510
+
+/*
+** Wrapper around OS specific sqlite3_os_init() function.
+*/
+SQLITE_PRIVATE int sqlite3OsInit(void);
+
+/*
+** Functions for accessing sqlite3_file methods
+*/
+SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
+SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
+SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
+SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
+SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
+SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
+SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
+SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
+SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
+SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
+SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
+#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
+SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
+SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
+#ifndef SQLITE_OMIT_WAL
+SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
+SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
+SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
+SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
+#endif /* SQLITE_OMIT_WAL */
+SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
+SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
+
+
+/*
+** Functions for accessing sqlite3_vfs methods
+*/
+SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
+SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
+SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
+SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
+#ifndef SQLITE_OMIT_LOAD_EXTENSION
+SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
+SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
+SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
+SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
+#endif /* SQLITE_OMIT_LOAD_EXTENSION */
+SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
+SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
+SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
+SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
+
+/*
+** Convenience functions for opening and closing files using
+** sqlite3_malloc() to obtain space for the file-handle structure.
+*/
+SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
+SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
+
+#endif /* _SQLITE_OS_H_ */
+
+/************** End of os.h **************************************************/
+/************** Continuing where we left off in sqliteInt.h ******************/
+/************** Include mutex.h in the middle of sqliteInt.h *****************/
+/************** Begin file mutex.h *******************************************/
+/*
+** 2007 August 28
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains the common header for all mutex implementations.
+** The sqliteInt.h header #includes this file so that it is available
+** to all source files. We break it out in an effort to keep the code
+** better organized.
+**
+** NOTE: source files should *not* #include this header file directly.
+** Source files should #include the sqliteInt.h file and let that file
+** include this one indirectly.
+*/
+
+
+/*
+** Figure out what version of the code to use. The choices are
+**
+** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
+** mutexes implementation cannot be overridden
+** at start-time.
+**
+** SQLITE_MUTEX_NOOP For single-threaded applications. No
+** mutual exclusion is provided. But this
+** implementation can be overridden at
+** start-time.
+**
+** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
+**
+** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
+*/
+#if !SQLITE_THREADSAFE
+# define SQLITE_MUTEX_OMIT
+#endif
+#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
+# if SQLITE_OS_UNIX
+# define SQLITE_MUTEX_PTHREADS
+# elif SQLITE_OS_WIN
+# define SQLITE_MUTEX_W32
+# else
+# define SQLITE_MUTEX_NOOP
+# endif
+#endif
+
+#ifdef SQLITE_MUTEX_OMIT
+/*
+** If this is a no-op implementation, implement everything as macros.
+*/
+#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
+#define sqlite3_mutex_free(X)
+#define sqlite3_mutex_enter(X)
+#define sqlite3_mutex_try(X) SQLITE_OK
+#define sqlite3_mutex_leave(X)
+#define sqlite3_mutex_held(X) ((void)(X),1)
+#define sqlite3_mutex_notheld(X) ((void)(X),1)
+#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
+#define sqlite3MutexInit() SQLITE_OK
+#define sqlite3MutexEnd()
+#define MUTEX_LOGIC(X)
+#else
+#define MUTEX_LOGIC(X) X
+SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
+#endif /* defined(SQLITE_MUTEX_OMIT) */
+
+/************** End of mutex.h ***********************************************/
+/************** Continuing where we left off in sqliteInt.h ******************/
+
+/* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
+** synchronous setting to EXTRA. It is no longer supported.
+*/
+#ifdef SQLITE_EXTRA_DURABLE
+# warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
+# define SQLITE_DEFAULT_SYNCHRONOUS 3
+#endif
+
+/*
+** Default synchronous levels.
+**
+** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
+** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
+**
+** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
+** OFF 1 0
+** NORMAL 2 1
+** FULL 3 2
+** EXTRA 4 3
+**
+** The "PRAGMA synchronous" statement also uses the zero-based numbers.
+** In other words, the zero-based numbers are used for all external interfaces
+** and the one-based values are used internally.
+*/
+#ifndef SQLITE_DEFAULT_SYNCHRONOUS
+# define SQLITE_DEFAULT_SYNCHRONOUS 2
+#endif
+#ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
+# define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
+#endif
+
+/*
+** Each database file to be accessed by the system is an instance
+** of the following structure. There are normally two of these structures
+** in the sqlite.aDb[] array. aDb[0] is the main database file and
+** aDb[1] is the database file used to hold temporary tables. Additional
+** databases may be attached.
+*/
+struct Db {
+ char *zDbSName; /* Name of this database. (schema name, not filename) */
+ Btree *pBt; /* The B*Tree structure for this database file */
+ u8 safety_level; /* How aggressive at syncing data to disk */
+ u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
+ Schema *pSchema; /* Pointer to database schema (possibly shared) */
+};
+
+/*
+** An instance of the following structure stores a database schema.
+**
+** Most Schema objects are associated with a Btree. The exception is
+** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
+** In shared cache mode, a single Schema object can be shared by multiple
+** Btrees that refer to the same underlying BtShared object.
+**
+** Schema objects are automatically deallocated when the last Btree that
+** references them is destroyed. The TEMP Schema is manually freed by
+** sqlite3_close().
+*
+** A thread must be holding a mutex on the corresponding Btree in order
+** to access Schema content. This implies that the thread must also be
+** holding a mutex on the sqlite3 connection pointer that owns the Btree.
+** For a TEMP Schema, only the connection mutex is required.
+*/
+struct Schema {
+ int schema_cookie; /* Database schema version number for this file */
+ int iGeneration; /* Generation counter. Incremented with each change */
+ Hash tblHash; /* All tables indexed by name */
+ Hash idxHash; /* All (named) indices indexed by name */
+ Hash trigHash; /* All triggers indexed by name */
+ Hash fkeyHash; /* All foreign keys by referenced table name */
+ Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
+ u8 file_format; /* Schema format version for this file */
+ u8 enc; /* Text encoding used by this database */
+ u16 schemaFlags; /* Flags associated with this schema */
+ int cache_size; /* Number of pages to use in the cache */
+};
+
+/*
+** These macros can be used to test, set, or clear bits in the
+** Db.pSchema->flags field.
+*/
+#define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
+#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
+#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
+#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
+
+/*
+** Allowed values for the DB.pSchema->flags field.
+**
+** The DB_SchemaLoaded flag is set after the database schema has been
+** read into internal hash tables.
+**
+** DB_UnresetViews means that one or more views have column names that
+** have been filled out. If the schema changes, these column names might
+** changes and so the view will need to be reset.
+*/
+#define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
+#define DB_UnresetViews 0x0002 /* Some views have defined column names */
+#define DB_ResetWanted 0x0008 /* Reset the schema when nSchemaLock==0 */
+
+/*
+** The number of different kinds of things that can be limited
+** using the sqlite3_limit() interface.
+*/
+#define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
+
+/*
+** Lookaside malloc is a set of fixed-size buffers that can be used
+** to satisfy small transient memory allocation requests for objects
+** associated with a particular database connection. The use of
+** lookaside malloc provides a significant performance enhancement
+** (approx 10%) by avoiding numerous malloc/free requests while parsing
+** SQL statements.
+**
+** The Lookaside structure holds configuration information about the
+** lookaside malloc subsystem. Each available memory allocation in
+** the lookaside subsystem is stored on a linked list of LookasideSlot
+** objects.
+**
+** Lookaside allocations are only allowed for objects that are associated
+** with a particular database connection. Hence, schema information cannot
+** be stored in lookaside because in shared cache mode the schema information
+** is shared by multiple database connections. Therefore, while parsing
+** schema information, the Lookaside.bEnabled flag is cleared so that
+** lookaside allocations are not used to construct the schema objects.
+**
+** New lookaside allocations are only allowed if bDisable==0. When
+** bDisable is greater than zero, sz is set to zero which effectively
+** disables lookaside without adding a new test for the bDisable flag
+** in a performance-critical path. sz should be set by to szTrue whenever
+** bDisable changes back to zero.
+**
+** Lookaside buffers are initially held on the pInit list. As they are
+** used and freed, they are added back to the pFree list. New allocations
+** come off of pFree first, then pInit as a fallback. This dual-list
+** allows use to compute a high-water mark - the maximum number of allocations
+** outstanding at any point in the past - by subtracting the number of
+** allocations on the pInit list from the total number of allocations.
+**
+** Enhancement on 2019-12-12: Two-size-lookaside
+** The default lookaside configuration is 100 slots of 1200 bytes each.
+** The larger slot sizes are important for performance, but they waste
+** a lot of space, as most lookaside allocations are less than 128 bytes.
+** The two-size-lookaside enhancement breaks up the lookaside allocation
+** into two pools: One of 128-byte slots and the other of the default size
+** (1200-byte) slots. Allocations are filled from the small-pool first,
+** failing over to the full-size pool if that does not work. Thus more
+** lookaside slots are available while also using less memory.
+** This enhancement can be omitted by compiling with
+** SQLITE_OMIT_TWOSIZE_LOOKASIDE.
+*/
+struct Lookaside {
+ u32 bDisable; /* Only operate the lookaside when zero */
+ u16 sz; /* Size of each buffer in bytes */
+ u16 szTrue; /* True value of sz, even if disabled */
+ u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
+ u32 nSlot; /* Number of lookaside slots allocated */
+ u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
+ LookasideSlot *pInit; /* List of buffers not previously used */
+ LookasideSlot *pFree; /* List of available buffers */
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+ LookasideSlot *pSmallInit; /* List of small buffers not prediously used */
+ LookasideSlot *pSmallFree; /* List of available small buffers */
+ void *pMiddle; /* First byte past end of full-size buffers and
+ ** the first byte of LOOKASIDE_SMALL buffers */
+#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
+ void *pStart; /* First byte of available memory space */
+ void *pEnd; /* First byte past end of available space */
+};
+struct LookasideSlot {
+ LookasideSlot *pNext; /* Next buffer in the list of free buffers */
+};
+
+#define DisableLookaside db->lookaside.bDisable++;db->lookaside.sz=0
+#define EnableLookaside db->lookaside.bDisable--;\
+ db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue
+
+/* Size of the smaller allocations in two-size lookside */
+#ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+# define LOOKASIDE_SMALL 0
+#else
+# define LOOKASIDE_SMALL 128
+#endif
+
+/*
+** A hash table for built-in function definitions. (Application-defined
+** functions use a regular table table from hash.h.)
+**
+** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
+** Collisions are on the FuncDef.u.pHash chain. Use the SQLITE_FUNC_HASH()
+** macro to compute a hash on the function name.
+*/
+#define SQLITE_FUNC_HASH_SZ 23
+struct FuncDefHash {
+ FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
+};
+#define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ)
+
+#ifdef SQLITE_USER_AUTHENTICATION
+/*
+** Information held in the "sqlite3" database connection object and used
+** to manage user authentication.
+*/
+typedef struct sqlite3_userauth sqlite3_userauth;
+struct sqlite3_userauth {
+ u8 authLevel; /* Current authentication level */
+ int nAuthPW; /* Size of the zAuthPW in bytes */
+ char *zAuthPW; /* Password used to authenticate */
+ char *zAuthUser; /* User name used to authenticate */
+};
+
+/* Allowed values for sqlite3_userauth.authLevel */
+#define UAUTH_Unknown 0 /* Authentication not yet checked */
+#define UAUTH_Fail 1 /* User authentication failed */
+#define UAUTH_User 2 /* Authenticated as a normal user */
+#define UAUTH_Admin 3 /* Authenticated as an administrator */
+
+/* Functions used only by user authorization logic */
+SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
+SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
+SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
+SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
+
+#endif /* SQLITE_USER_AUTHENTICATION */
+
+/*
+** typedef for the authorization callback function.
+*/
+#ifdef SQLITE_USER_AUTHENTICATION
+ typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
+ const char*, const char*);
+#else
+ typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
+ const char*);
+#endif
+
+#ifndef SQLITE_OMIT_DEPRECATED
+/* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
+** in the style of sqlite3_trace()
+*/
+#define SQLITE_TRACE_LEGACY 0x40 /* Use the legacy xTrace */
+#define SQLITE_TRACE_XPROFILE 0x80 /* Use the legacy xProfile */
+#else
+#define SQLITE_TRACE_LEGACY 0
+#define SQLITE_TRACE_XPROFILE 0
+#endif /* SQLITE_OMIT_DEPRECATED */
+#define SQLITE_TRACE_NONLEGACY_MASK 0x0f /* Normal flags */
+
+
+/*
+** Each database connection is an instance of the following structure.
+*/
+struct sqlite3 {
+ sqlite3_vfs *pVfs; /* OS Interface */
+ struct Vdbe *pVdbe; /* List of active virtual machines */
+ CollSeq *pDfltColl; /* BINARY collseq for the database encoding */
+ sqlite3_mutex *mutex; /* Connection mutex */
+ Db *aDb; /* All backends */
+ int nDb; /* Number of backends currently in use */
+ u32 mDbFlags; /* flags recording internal state */
+ u64 flags; /* flags settable by pragmas. See below */
+ i64 lastRowid; /* ROWID of most recent insert (see above) */
+ i64 szMmap; /* Default mmap_size setting */
+ u32 nSchemaLock; /* Do not reset the schema when non-zero */
+ unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
+ int errCode; /* Most recent error code (SQLITE_*) */
+ int errMask; /* & result codes with this before returning */
+ int iSysErrno; /* Errno value from last system error */
+ u16 dbOptFlags; /* Flags to enable/disable optimizations */
+ u8 enc; /* Text encoding */
+ u8 autoCommit; /* The auto-commit flag. */
+ u8 temp_store; /* 1: file 2: memory 0: default */
+ u8 mallocFailed; /* True if we have seen a malloc failure */
+ u8 bBenignMalloc; /* Do not require OOMs if true */
+ u8 dfltLockMode; /* Default locking-mode for attached dbs */
+ signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
+ u8 suppressErr; /* Do not issue error messages if true */
+ u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
+ u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
+ u8 mTrace; /* zero or more SQLITE_TRACE flags */
+ u8 noSharedCache; /* True if no shared-cache backends */
+ u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
+ int nextPagesize; /* Pagesize after VACUUM if >0 */
+ u32 magic; /* Magic number for detect library misuse */
+ int nChange; /* Value returned by sqlite3_changes() */
+ int nTotalChange; /* Value returned by sqlite3_total_changes() */
+ int aLimit[SQLITE_N_LIMIT]; /* Limits */
+ int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
+ struct sqlite3InitInfo { /* Information used during initialization */
+ Pgno newTnum; /* Rootpage of table being initialized */
+ u8 iDb; /* Which db file is being initialized */
+ u8 busy; /* TRUE if currently initializing */
+ unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
+ unsigned imposterTable : 1; /* Building an imposter table */
+ unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */
+ char **azInit; /* "type", "name", and "tbl_name" columns */
+ } init;
+ int nVdbeActive; /* Number of VDBEs currently running */
+ int nVdbeRead; /* Number of active VDBEs that read or write */
+ int nVdbeWrite; /* Number of active VDBEs that read and write */
+ int nVdbeExec; /* Number of nested calls to VdbeExec() */
+ int nVDestroy; /* Number of active OP_VDestroy operations */
+ int nExtension; /* Number of loaded extensions */
+ void **aExtension; /* Array of shared library handles */
+ union {
+ void (*xLegacy)(void*,const char*); /* Legacy trace function */
+ int (*xV2)(u32,void*,void*,void*); /* V2 Trace function */
+ } trace;
+ void *pTraceArg; /* Argument to the trace function */
+#ifndef SQLITE_OMIT_DEPRECATED
+ void (*xProfile)(void*,const char*,u64); /* Profiling function */
+ void *pProfileArg; /* Argument to profile function */
+#endif
+ void *pCommitArg; /* Argument to xCommitCallback() */
+ int (*xCommitCallback)(void*); /* Invoked at every commit. */
+ void *pRollbackArg; /* Argument to xRollbackCallback() */
+ void (*xRollbackCallback)(void*); /* Invoked at every commit. */
+ void *pUpdateArg;
+ void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
+ Parse *pParse; /* Current parse */
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+ void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
+ void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
+ void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
+ );
+ PreUpdate *pPreUpdate; /* Context for active pre-update callback */
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
+#ifndef SQLITE_OMIT_WAL
+ int (*xWalCallback)(void *, sqlite3 *, const char *, int);
+ void *pWalArg;
+#endif
+ void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
+ void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
+ void *pCollNeededArg;
+ sqlite3_value *pErr; /* Most recent error message */
+ union {
+ volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
+ double notUsed1; /* Spacer */
+ } u1;
+ Lookaside lookaside; /* Lookaside malloc configuration */
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ sqlite3_xauth xAuth; /* Access authorization function */
+ void *pAuthArg; /* 1st argument to the access auth function */
+#endif
+#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
+ int (*xProgress)(void *); /* The progress callback */
+ void *pProgressArg; /* Argument to the progress callback */
+ unsigned nProgressOps; /* Number of opcodes for progress callback */
+#endif
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ int nVTrans; /* Allocated size of aVTrans */
+ Hash aModule; /* populated by sqlite3_create_module() */
+ VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
+ VTable **aVTrans; /* Virtual tables with open transactions */
+ VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
+#endif
+ Hash aFunc; /* Hash table of connection functions */
+ Hash aCollSeq; /* All collating sequences */
+ BusyHandler busyHandler; /* Busy callback */
+ Db aDbStatic[2]; /* Static space for the 2 default backends */
+ Savepoint *pSavepoint; /* List of active savepoints */
+ int nAnalysisLimit; /* Number of index rows to ANALYZE */
+ int busyTimeout; /* Busy handler timeout, in msec */
+ int nSavepoint; /* Number of non-transaction savepoints */
+ int nStatement; /* Number of nested statement-transactions */
+ i64 nDeferredCons; /* Net deferred constraints this transaction. */
+ i64 nDeferredImmCons; /* Net deferred immediate constraints */
+ int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
+#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
+ /* The following variables are all protected by the STATIC_MAIN
+ ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
+ **
+ ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
+ ** unlock so that it can proceed.
+ **
+ ** When X.pBlockingConnection==Y, that means that something that X tried
+ ** tried to do recently failed with an SQLITE_LOCKED error due to locks
+ ** held by Y.
+ */
+ sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
+ sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
+ void *pUnlockArg; /* Argument to xUnlockNotify */
+ void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
+ sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
+#endif
+#ifdef SQLITE_USER_AUTHENTICATION
+ sqlite3_userauth auth; /* User authentication information */
+#endif
+};
+
+/*
+** A macro to discover the encoding of a database.
+*/
+#define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
+#define ENC(db) ((db)->enc)
+
+/*
+** A u64 constant where the lower 32 bits are all zeros. Only the
+** upper 32 bits are included in the argument. Necessary because some
+** C-compilers still do not accept LL integer literals.
+*/
+#define HI(X) ((u64)(X)<<32)
+
+/*
+** Possible values for the sqlite3.flags.
+**
+** Value constraints (enforced via assert()):
+** SQLITE_FullFSync == PAGER_FULLFSYNC
+** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
+** SQLITE_CacheSpill == PAGER_CACHE_SPILL
+*/
+#define SQLITE_WriteSchema 0x00000001 /* OK to update SQLITE_SCHEMA */
+#define SQLITE_LegacyFileFmt 0x00000002 /* Create new databases in format 1 */
+#define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
+#define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
+#define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
+#define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
+#define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
+#define SQLITE_TrustedSchema 0x00000080 /* Allow unsafe functions and
+ ** vtabs in the schema definition */
+#define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
+ /* result set is empty */
+#define SQLITE_IgnoreChecks 0x00000200 /* Do not enforce check constraints */
+#define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */
+#define SQLITE_NoCkptOnClose 0x00000800 /* No checkpoint on close()/DETACH */
+#define SQLITE_ReverseOrder 0x00001000 /* Reverse unordered SELECTs */
+#define SQLITE_RecTriggers 0x00002000 /* Enable recursive triggers */
+#define SQLITE_ForeignKeys 0x00004000 /* Enforce foreign key constraints */
+#define SQLITE_AutoIndex 0x00008000 /* Enable automatic indexes */
+#define SQLITE_LoadExtension 0x00010000 /* Enable load_extension */
+#define SQLITE_LoadExtFunc 0x00020000 /* Enable load_extension() SQL func */
+#define SQLITE_EnableTrigger 0x00040000 /* True to enable triggers */
+#define SQLITE_DeferFKs 0x00080000 /* Defer all FK constraints */
+#define SQLITE_QueryOnly 0x00100000 /* Disable database changes */
+#define SQLITE_CellSizeCk 0x00200000 /* Check btree cell sizes on load */
+#define SQLITE_Fts3Tokenizer 0x00400000 /* Enable fts3_tokenizer(2) */
+#define SQLITE_EnableQPSG 0x00800000 /* Query Planner Stability Guarantee*/
+#define SQLITE_TriggerEQP 0x01000000 /* Show trigger EXPLAIN QUERY PLAN */
+#define SQLITE_ResetDatabase 0x02000000 /* Reset the database */
+#define SQLITE_LegacyAlter 0x04000000 /* Legacy ALTER TABLE behaviour */
+#define SQLITE_NoSchemaError 0x08000000 /* Do not report schema parse errors*/
+#define SQLITE_Defensive 0x10000000 /* Input SQL is likely hostile */
+#define SQLITE_DqsDDL 0x20000000 /* dbl-quoted strings allowed in DDL*/
+#define SQLITE_DqsDML 0x40000000 /* dbl-quoted strings allowed in DML*/
+#define SQLITE_EnableView 0x80000000 /* Enable the use of views */
+#define SQLITE_CountRows HI(0x00001) /* Count rows changed by INSERT, */
+ /* DELETE, or UPDATE and return */
+ /* the count using a callback. */
+
+/* Flags used only if debugging */
+#ifdef SQLITE_DEBUG
+#define SQLITE_SqlTrace HI(0x0100000) /* Debug print SQL as it executes */
+#define SQLITE_VdbeListing HI(0x0200000) /* Debug listings of VDBE progs */
+#define SQLITE_VdbeTrace HI(0x0400000) /* True to trace VDBE execution */
+#define SQLITE_VdbeAddopTrace HI(0x0800000) /* Trace sqlite3VdbeAddOp() calls */
+#define SQLITE_VdbeEQP HI(0x1000000) /* Debug EXPLAIN QUERY PLAN */
+#define SQLITE_ParserTrace HI(0x2000000) /* PRAGMA parser_trace=ON */
+#endif
+
+/*
+** Allowed values for sqlite3.mDbFlags
+*/
+#define DBFLAG_SchemaChange 0x0001 /* Uncommitted Hash table changes */
+#define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */
+#define DBFLAG_Vacuum 0x0004 /* Currently in a VACUUM */
+#define DBFLAG_VacuumInto 0x0008 /* Currently running VACUUM INTO */
+#define DBFLAG_SchemaKnownOk 0x0010 /* Schema is known to be valid */
+#define DBFLAG_InternalFunc 0x0020 /* Allow use of internal functions */
+#define DBFLAG_EncodingFixed 0x0040 /* No longer possible to change enc. */
+
+/*
+** Bits of the sqlite3.dbOptFlags field that are used by the
+** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
+** selectively disable various optimizations.
+*/
+#define SQLITE_QueryFlattener 0x0001 /* Query flattening */
+#define SQLITE_WindowFunc 0x0002 /* Use xInverse for window functions */
+#define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
+#define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
+#define SQLITE_DistinctOpt 0x0010 /* DISTINCT using indexes */
+#define SQLITE_CoverIdxScan 0x0020 /* Covering index scans */
+#define SQLITE_OrderByIdxJoin 0x0040 /* ORDER BY of joins via index */
+#define SQLITE_Transitive 0x0080 /* Transitive constraints */
+#define SQLITE_OmitNoopJoin 0x0100 /* Omit unused tables in joins */
+#define SQLITE_CountOfView 0x0200 /* The count-of-view optimization */
+#define SQLITE_CursorHints 0x0400 /* Add OP_CursorHint opcodes */
+#define SQLITE_Stat4 0x0800 /* Use STAT4 data */
+ /* TH3 expects the Stat4 ^^^^^^ value to be 0x0800. Don't change it */
+#define SQLITE_PushDown 0x1000 /* The push-down optimization */
+#define SQLITE_SimplifyJoin 0x2000 /* Convert LEFT JOIN to JOIN */
+#define SQLITE_SkipScan 0x4000 /* Skip-scans */
+#define SQLITE_PropagateConst 0x8000 /* The constant propagation opt */
+#define SQLITE_AllOpts 0xffff /* All optimizations */
+
+/*
+** Macros for testing whether or not optimizations are enabled or disabled.
+*/
+#define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
+#define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
+
+/*
+** Return true if it OK to factor constant expressions into the initialization
+** code. The argument is a Parse object for the code generator.
+*/
+#define ConstFactorOk(P) ((P)->okConstFactor)
+
+/*
+** Possible values for the sqlite.magic field.
+** The numbers are obtained at random and have no special meaning, other
+** than being distinct from one another.
+*/
+#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
+#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
+#define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
+#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
+#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
+#define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
+
+/*
+** Each SQL function is defined by an instance of the following
+** structure. For global built-in functions (ex: substr(), max(), count())
+** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
+** For per-connection application-defined functions, a pointer to this
+** structure is held in the db->aHash hash table.
+**
+** The u.pHash field is used by the global built-ins. The u.pDestructor
+** field is used by per-connection app-def functions.
+*/
+struct FuncDef {
+ i8 nArg; /* Number of arguments. -1 means unlimited */
+ u32 funcFlags; /* Some combination of SQLITE_FUNC_* */
+ void *pUserData; /* User data parameter */
+ FuncDef *pNext; /* Next function with same name */
+ void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
+ void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
+ void (*xValue)(sqlite3_context*); /* Current agg value */
+ void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
+ const char *zName; /* SQL name of the function. */
+ union {
+ FuncDef *pHash; /* Next with a different name but the same hash */
+ FuncDestructor *pDestructor; /* Reference counted destructor function */
+ } u;
+};
+
+/*
+** This structure encapsulates a user-function destructor callback (as
+** configured using create_function_v2()) and a reference counter. When
+** create_function_v2() is called to create a function with a destructor,
+** a single object of this type is allocated. FuncDestructor.nRef is set to
+** the number of FuncDef objects created (either 1 or 3, depending on whether
+** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
+** member of each of the new FuncDef objects is set to point to the allocated
+** FuncDestructor.
+**
+** Thereafter, when one of the FuncDef objects is deleted, the reference
+** count on this object is decremented. When it reaches 0, the destructor
+** is invoked and the FuncDestructor structure freed.
+*/
+struct FuncDestructor {
+ int nRef;
+ void (*xDestroy)(void *);
+ void *pUserData;
+};
+
+/*
+** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
+** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
+** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
+** are assert() statements in the code to verify this.
+**
+** Value constraints (enforced via assert()):
+** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
+** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
+** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
+** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
+** SQLITE_FUNC_DIRECT == SQLITE_DIRECTONLY from the API
+** SQLITE_FUNC_UNSAFE == SQLITE_INNOCUOUS
+** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
+*/
+#define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
+#define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
+#define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
+#define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
+#define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
+#define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
+#define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
+#define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
+/* 0x0200 -- available for reuse */
+#define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
+#define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
+#define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
+#define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
+ ** single query - might change over time */
+#define SQLITE_FUNC_TEST 0x4000 /* Built-in testing functions */
+#define SQLITE_FUNC_OFFSET 0x8000 /* Built-in sqlite_offset() function */
+#define SQLITE_FUNC_WINDOW 0x00010000 /* Built-in window-only function */
+#define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */
+#define SQLITE_FUNC_DIRECT 0x00080000 /* Not for use in TRIGGERs or VIEWs */
+#define SQLITE_FUNC_SUBTYPE 0x00100000 /* Result likely to have sub-type */
+#define SQLITE_FUNC_UNSAFE 0x00200000 /* Function has side effects */
+#define SQLITE_FUNC_INLINE 0x00400000 /* Functions implemented in-line */
+
+/* Identifier numbers for each in-line function */
+#define INLINEFUNC_coalesce 0
+#define INLINEFUNC_implies_nonnull_row 1
+#define INLINEFUNC_expr_implies_expr 2
+#define INLINEFUNC_expr_compare 3
+#define INLINEFUNC_affinity 4
+#define INLINEFUNC_iif 5
+#define INLINEFUNC_unlikely 99 /* Default case */
+
+/*
+** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
+** used to create the initializers for the FuncDef structures.
+**
+** FUNCTION(zName, nArg, iArg, bNC, xFunc)
+** Used to create a scalar function definition of a function zName
+** implemented by C function xFunc that accepts nArg arguments. The
+** value passed as iArg is cast to a (void*) and made available
+** as the user-data (sqlite3_user_data()) for the function. If
+** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
+**
+** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
+** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
+**
+** SFUNCTION(zName, nArg, iArg, bNC, xFunc)
+** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
+** adds the SQLITE_DIRECTONLY flag.
+**
+** INLINE_FUNC(zName, nArg, iFuncId, mFlags)
+** zName is the name of a function that is implemented by in-line
+** byte code rather than by the usual callbacks. The iFuncId
+** parameter determines the function id. The mFlags parameter is
+** optional SQLITE_FUNC_ flags for this function.
+**
+** TEST_FUNC(zName, nArg, iFuncId, mFlags)
+** zName is the name of a test-only function implemented by in-line
+** byte code rather than by the usual callbacks. The iFuncId
+** parameter determines the function id. The mFlags parameter is
+** optional SQLITE_FUNC_ flags for this function.
+**
+** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
+** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
+** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
+** and functions like sqlite_version() that can change, but not during
+** a single query. The iArg is ignored. The user-data is always set
+** to a NULL pointer. The bNC parameter is not used.
+**
+** PURE_DATE(zName, nArg, iArg, bNC, xFunc)
+** Used for "pure" date/time functions, this macro is like DFUNCTION
+** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is
+** ignored and the user-data for these functions is set to an
+** arbitrary non-NULL pointer. The bNC parameter is not used.
+**
+** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
+** Used to create an aggregate function definition implemented by
+** the C functions xStep and xFinal. The first four parameters
+** are interpreted in the same way as the first 4 parameters to
+** FUNCTION().
+**
+** WFUNCTION(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)
+** Used to create an aggregate function definition implemented by
+** the C functions xStep and xFinal. The first four parameters
+** are interpreted in the same way as the first 4 parameters to
+** FUNCTION().
+**
+** LIKEFUNC(zName, nArg, pArg, flags)
+** Used to create a scalar function definition of a function zName
+** that accepts nArg arguments and is implemented by a call to C
+** function likeFunc. Argument pArg is cast to a (void *) and made
+** available as the function user-data (sqlite3_user_data()). The
+** FuncDef.flags variable is set to the value passed as the flags
+** parameter.
+*/
+#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
+ {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
+ SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
+#define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
+ {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
+ SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
+#define SFUNCTION(zName, nArg, iArg, bNC, xFunc) \
+ {nArg, SQLITE_UTF8|SQLITE_DIRECTONLY|SQLITE_FUNC_UNSAFE, \
+ SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
+#define INLINE_FUNC(zName, nArg, iArg, mFlags) \
+ {nArg, SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
+ SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
+#define TEST_FUNC(zName, nArg, iArg, mFlags) \
+ {nArg, SQLITE_UTF8|SQLITE_FUNC_INTERNAL|SQLITE_FUNC_TEST| \
+ SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
+ SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
+#define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
+ {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
+ 0, 0, xFunc, 0, 0, 0, #zName, {0} }
+#define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
+ {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
+ (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }
+#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
+ {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
+ SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
+#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
+ {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
+ pArg, 0, xFunc, 0, 0, 0, #zName, }
+#define LIKEFUNC(zName, nArg, arg, flags) \
+ {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
+ (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
+#define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \
+ {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
+ SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
+#define INTERNAL_FUNCTION(zName, nArg, xFunc) \
+ {nArg, SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
+ 0, 0, xFunc, 0, 0, 0, #zName, {0} }
+
+
+/*
+** All current savepoints are stored in a linked list starting at
+** sqlite3.pSavepoint. The first element in the list is the most recently
+** opened savepoint. Savepoints are added to the list by the vdbe
+** OP_Savepoint instruction.
+*/
+struct Savepoint {
+ char *zName; /* Savepoint name (nul-terminated) */
+ i64 nDeferredCons; /* Number of deferred fk violations */
+ i64 nDeferredImmCons; /* Number of deferred imm fk. */
+ Savepoint *pNext; /* Parent savepoint (if any) */
+};
+
+/*
+** The following are used as the second parameter to sqlite3Savepoint(),
+** and as the P1 argument to the OP_Savepoint instruction.
+*/
+#define SAVEPOINT_BEGIN 0
+#define SAVEPOINT_RELEASE 1
+#define SAVEPOINT_ROLLBACK 2
+
+
+/*
+** Each SQLite module (virtual table definition) is defined by an
+** instance of the following structure, stored in the sqlite3.aModule
+** hash table.
+*/
+struct Module {
+ const sqlite3_module *pModule; /* Callback pointers */
+ const char *zName; /* Name passed to create_module() */
+ int nRefModule; /* Number of pointers to this object */
+ void *pAux; /* pAux passed to create_module() */
+ void (*xDestroy)(void *); /* Module destructor function */
+ Table *pEpoTab; /* Eponymous table for this module */
+};
+
+/*
+** Information about each column of an SQL table is held in an instance
+** of the Column structure, in the Table.aCol[] array.
+**
+** Definitions:
+**
+** "table column index" This is the index of the column in the
+** Table.aCol[] array, and also the index of
+** the column in the original CREATE TABLE stmt.
+**
+** "storage column index" This is the index of the column in the
+** record BLOB generated by the OP_MakeRecord
+** opcode. The storage column index is less than
+** or equal to the table column index. It is
+** equal if and only if there are no VIRTUAL
+** columns to the left.
+*/
+struct Column {
+ char *zName; /* Name of this column, \000, then the type */
+ Expr *pDflt; /* Default value or GENERATED ALWAYS AS value */
+ char *zColl; /* Collating sequence. If NULL, use the default */
+ u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
+ char affinity; /* One of the SQLITE_AFF_... values */
+ u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
+ u8 hName; /* Column name hash for faster lookup */
+ u16 colFlags; /* Boolean properties. See COLFLAG_ defines below */
+};
+
+/* Allowed values for Column.colFlags:
+*/
+#define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
+#define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
+#define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
+#define COLFLAG_UNIQUE 0x0008 /* Column def contains "UNIQUE" or "PK" */
+#define COLFLAG_SORTERREF 0x0010 /* Use sorter-refs with this column */
+#define COLFLAG_VIRTUAL 0x0020 /* GENERATED ALWAYS AS ... VIRTUAL */
+#define COLFLAG_STORED 0x0040 /* GENERATED ALWAYS AS ... STORED */
+#define COLFLAG_NOTAVAIL 0x0080 /* STORED column not yet calculated */
+#define COLFLAG_BUSY 0x0100 /* Blocks recursion on GENERATED columns */
+#define COLFLAG_GENERATED 0x0060 /* Combo: _STORED, _VIRTUAL */
+#define COLFLAG_NOINSERT 0x0062 /* Combo: _HIDDEN, _STORED, _VIRTUAL */
+
+/*
+** A "Collating Sequence" is defined by an instance of the following
+** structure. Conceptually, a collating sequence consists of a name and
+** a comparison routine that defines the order of that sequence.
+**
+** If CollSeq.xCmp is NULL, it means that the
+** collating sequence is undefined. Indices built on an undefined
+** collating sequence may not be read or written.
+*/
+struct CollSeq {
+ char *zName; /* Name of the collating sequence, UTF-8 encoded */
+ u8 enc; /* Text encoding handled by xCmp() */
+ void *pUser; /* First argument to xCmp() */
+ int (*xCmp)(void*,int, const void*, int, const void*);
+ void (*xDel)(void*); /* Destructor for pUser */
+};
+
+/*
+** A sort order can be either ASC or DESC.
+*/
+#define SQLITE_SO_ASC 0 /* Sort in ascending order */
+#define SQLITE_SO_DESC 1 /* Sort in ascending order */
+#define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
+
+/*
+** Column affinity types.
+**
+** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
+** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
+** the speed a little by numbering the values consecutively.
+**
+** But rather than start with 0 or 1, we begin with 'A'. That way,
+** when multiple affinity types are concatenated into a string and
+** used as the P4 operand, they will be more readable.
+**
+** Note also that the numeric types are grouped together so that testing
+** for a numeric type is a single comparison. And the BLOB type is first.
+*/
+#define SQLITE_AFF_NONE 0x40 /* '@' */
+#define SQLITE_AFF_BLOB 0x41 /* 'A' */
+#define SQLITE_AFF_TEXT 0x42 /* 'B' */
+#define SQLITE_AFF_NUMERIC 0x43 /* 'C' */
+#define SQLITE_AFF_INTEGER 0x44 /* 'D' */
+#define SQLITE_AFF_REAL 0x45 /* 'E' */
+
+#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
+
+/*
+** The SQLITE_AFF_MASK values masks off the significant bits of an
+** affinity value.
+*/
+#define SQLITE_AFF_MASK 0x47
+
+/*
+** Additional bit values that can be ORed with an affinity without
+** changing the affinity.
+**
+** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
+** It causes an assert() to fire if either operand to a comparison
+** operator is NULL. It is added to certain comparison operators to
+** prove that the operands are always NOT NULL.
+*/
+#define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */
+#define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
+#define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
+#define SQLITE_NULLEQ 0x80 /* NULL=NULL */
+#define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
+
+/*
+** An object of this type is created for each virtual table present in
+** the database schema.
+**
+** If the database schema is shared, then there is one instance of this
+** structure for each database connection (sqlite3*) that uses the shared
+** schema. This is because each database connection requires its own unique
+** instance of the sqlite3_vtab* handle used to access the virtual table
+** implementation. sqlite3_vtab* handles can not be shared between
+** database connections, even when the rest of the in-memory database
+** schema is shared, as the implementation often stores the database
+** connection handle passed to it via the xConnect() or xCreate() method
+** during initialization internally. This database connection handle may
+** then be used by the virtual table implementation to access real tables
+** within the database. So that they appear as part of the callers
+** transaction, these accesses need to be made via the same database
+** connection as that used to execute SQL operations on the virtual table.
+**
+** All VTable objects that correspond to a single table in a shared
+** database schema are initially stored in a linked-list pointed to by
+** the Table.pVTable member variable of the corresponding Table object.
+** When an sqlite3_prepare() operation is required to access the virtual
+** table, it searches the list for the VTable that corresponds to the
+** database connection doing the preparing so as to use the correct
+** sqlite3_vtab* handle in the compiled query.
+**
+** When an in-memory Table object is deleted (for example when the
+** schema is being reloaded for some reason), the VTable objects are not
+** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
+** immediately. Instead, they are moved from the Table.pVTable list to
+** another linked list headed by the sqlite3.pDisconnect member of the
+** corresponding sqlite3 structure. They are then deleted/xDisconnected
+** next time a statement is prepared using said sqlite3*. This is done
+** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
+** Refer to comments above function sqlite3VtabUnlockList() for an
+** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
+** list without holding the corresponding sqlite3.mutex mutex.
+**
+** The memory for objects of this type is always allocated by
+** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
+** the first argument.
+*/
+struct VTable {
+ sqlite3 *db; /* Database connection associated with this table */
+ Module *pMod; /* Pointer to module implementation */
+ sqlite3_vtab *pVtab; /* Pointer to vtab instance */
+ int nRef; /* Number of pointers to this structure */
+ u8 bConstraint; /* True if constraints are supported */
+ u8 eVtabRisk; /* Riskiness of allowing hacker access */
+ int iSavepoint; /* Depth of the SAVEPOINT stack */
+ VTable *pNext; /* Next in linked list (see above) */
+};
+
+/* Allowed values for VTable.eVtabRisk
+*/
+#define SQLITE_VTABRISK_Low 0
+#define SQLITE_VTABRISK_Normal 1
+#define SQLITE_VTABRISK_High 2
+
+/*
+** The schema for each SQL table and view is represented in memory
+** by an instance of the following structure.
+*/
+struct Table {
+ char *zName; /* Name of the table or view */
+ Column *aCol; /* Information about each column */
+ Index *pIndex; /* List of SQL indexes on this table. */
+ Select *pSelect; /* NULL for tables. Points to definition if a view. */
+ FKey *pFKey; /* Linked list of all foreign keys in this table */
+ char *zColAff; /* String defining the affinity of each column */
+ ExprList *pCheck; /* All CHECK constraints */
+ /* ... also used as column name list in a VIEW */
+ Pgno tnum; /* Root BTree page for this table */
+ u32 nTabRef; /* Number of pointers to this Table */
+ u32 tabFlags; /* Mask of TF_* values */
+ i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
+ i16 nCol; /* Number of columns in this table */
+ i16 nNVCol; /* Number of columns that are not VIRTUAL */
+ LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
+ LogEst szTabRow; /* Estimated size of each table row in bytes */
+#ifdef SQLITE_ENABLE_COSTMULT
+ LogEst costMult; /* Cost multiplier for using this table */
+#endif
+ u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
+#ifndef SQLITE_OMIT_ALTERTABLE
+ int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
+#endif
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ int nModuleArg; /* Number of arguments to the module */
+ char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
+ VTable *pVTable; /* List of VTable objects. */
+#endif
+ Trigger *pTrigger; /* List of triggers stored in pSchema */
+ Schema *pSchema; /* Schema that contains this table */
+ Table *pNextZombie; /* Next on the Parse.pZombieTab list */
+};
+
+/*
+** Allowed values for Table.tabFlags.
+**
+** TF_OOOHidden applies to tables or view that have hidden columns that are
+** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
+** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
+** the TF_OOOHidden attribute would apply in this case. Such tables require
+** special handling during INSERT processing. The "OOO" means "Out Of Order".
+**
+** Constraints:
+**
+** TF_HasVirtual == COLFLAG_Virtual
+** TF_HasStored == COLFLAG_Stored
+*/
+#define TF_Readonly 0x0001 /* Read-only system table */
+#define TF_Ephemeral 0x0002 /* An ephemeral table */
+#define TF_HasPrimaryKey 0x0004 /* Table has a primary key */
+#define TF_Autoincrement 0x0008 /* Integer primary key is autoincrement */
+#define TF_HasStat1 0x0010 /* nRowLogEst set from sqlite_stat1 */
+#define TF_HasVirtual 0x0020 /* Has one or more VIRTUAL columns */
+#define TF_HasStored 0x0040 /* Has one or more STORED columns */
+#define TF_HasGenerated 0x0060 /* Combo: HasVirtual + HasStored */
+#define TF_WithoutRowid 0x0080 /* No rowid. PRIMARY KEY is the key */
+#define TF_StatsUsed 0x0100 /* Query planner decisions affected by
+ ** Index.aiRowLogEst[] values */
+#define TF_NoVisibleRowid 0x0200 /* No user-visible "rowid" column */
+#define TF_OOOHidden 0x0400 /* Out-of-Order hidden columns */
+#define TF_HasNotNull 0x0800 /* Contains NOT NULL constraints */
+#define TF_Shadow 0x1000 /* True for a shadow table */
+
+/*
+** Test to see whether or not a table is a virtual table. This is
+** done as a macro so that it will be optimized out when virtual
+** table support is omitted from the build.
+*/
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+# define IsVirtual(X) ((X)->nModuleArg)
+# define ExprIsVtab(X) \
+ ((X)->op==TK_COLUMN && (X)->y.pTab!=0 && (X)->y.pTab->nModuleArg)
+#else
+# define IsVirtual(X) 0
+# define ExprIsVtab(X) 0
+#endif
+
+/*
+** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
+** only works for non-virtual tables (ordinary tables and views) and is
+** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
+** IsHiddenColumn() macro is general purpose.
+*/
+#if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
+# define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
+# define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
+#elif !defined(SQLITE_OMIT_VIRTUALTABLE)
+# define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
+# define IsOrdinaryHiddenColumn(X) 0
+#else
+# define IsHiddenColumn(X) 0
+# define IsOrdinaryHiddenColumn(X) 0
+#endif
+
+
+/* Does the table have a rowid */
+#define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
+#define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
+
+/*
+** Each foreign key constraint is an instance of the following structure.
+**
+** A foreign key is associated with two tables. The "from" table is
+** the table that contains the REFERENCES clause that creates the foreign
+** key. The "to" table is the table that is named in the REFERENCES clause.
+** Consider this example:
+**
+** CREATE TABLE ex1(
+** a INTEGER PRIMARY KEY,
+** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
+** );
+**
+** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
+** Equivalent names:
+**
+** from-table == child-table
+** to-table == parent-table
+**
+** Each REFERENCES clause generates an instance of the following structure
+** which is attached to the from-table. The to-table need not exist when
+** the from-table is created. The existence of the to-table is not checked.
+**
+** The list of all parents for child Table X is held at X.pFKey.
+**
+** A list of all children for a table named Z (which might not even exist)
+** is held in Schema.fkeyHash with a hash key of Z.
+*/
+struct FKey {
+ Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
+ FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
+ char *zTo; /* Name of table that the key points to (aka: Parent) */
+ FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
+ FKey *pPrevTo; /* Previous with the same zTo */
+ int nCol; /* Number of columns in this key */
+ /* EV: R-30323-21917 */
+ u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
+ u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
+ Trigger *apTrigger[2];/* Triggers for aAction[] actions */
+ struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
+ int iFrom; /* Index of column in pFrom */
+ char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
+ } aCol[1]; /* One entry for each of nCol columns */
+};
+
+/*
+** SQLite supports many different ways to resolve a constraint
+** error. ROLLBACK processing means that a constraint violation
+** causes the operation in process to fail and for the current transaction
+** to be rolled back. ABORT processing means the operation in process
+** fails and any prior changes from that one operation are backed out,
+** but the transaction is not rolled back. FAIL processing means that
+** the operation in progress stops and returns an error code. But prior
+** changes due to the same operation are not backed out and no rollback
+** occurs. IGNORE means that the particular row that caused the constraint
+** error is not inserted or updated. Processing continues and no error
+** is returned. REPLACE means that preexisting database rows that caused
+** a UNIQUE constraint violation are removed so that the new insert or
+** update can proceed. Processing continues and no error is reported.
+**
+** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
+** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
+** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
+** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
+** referenced table row is propagated into the row that holds the
+** foreign key.
+**
+** The following symbolic values are used to record which type
+** of action to take.
+*/
+#define OE_None 0 /* There is no constraint to check */
+#define OE_Rollback 1 /* Fail the operation and rollback the transaction */
+#define OE_Abort 2 /* Back out changes but do no rollback transaction */
+#define OE_Fail 3 /* Stop the operation but leave all prior changes */
+#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
+#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
+#define OE_Update 6 /* Process as a DO UPDATE in an upsert */
+#define OE_Restrict 7 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
+#define OE_SetNull 8 /* Set the foreign key value to NULL */
+#define OE_SetDflt 9 /* Set the foreign key value to its default */
+#define OE_Cascade 10 /* Cascade the changes */
+#define OE_Default 11 /* Do whatever the default action is */
+
+
+/*
+** An instance of the following structure is passed as the first
+** argument to sqlite3VdbeKeyCompare and is used to control the
+** comparison of the two index keys.
+**
+** Note that aSortOrder[] and aColl[] have nField+1 slots. There
+** are nField slots for the columns of an index then one extra slot
+** for the rowid at the end.
+*/
+struct KeyInfo {
+ u32 nRef; /* Number of references to this KeyInfo object */
+ u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
+ u16 nKeyField; /* Number of key columns in the index */
+ u16 nAllField; /* Total columns, including key plus others */
+ sqlite3 *db; /* The database connection */
+ u8 *aSortFlags; /* Sort order for each column. */
+ CollSeq *aColl[1]; /* Collating sequence for each term of the key */
+};
+
+/*
+** Allowed bit values for entries in the KeyInfo.aSortFlags[] array.
+*/
+#define KEYINFO_ORDER_DESC 0x01 /* DESC sort order */
+#define KEYINFO_ORDER_BIGNULL 0x02 /* NULL is larger than any other value */
+
+/*
+** This object holds a record which has been parsed out into individual
+** fields, for the purposes of doing a comparison.
+**
+** A record is an object that contains one or more fields of data.
+** Records are used to store the content of a table row and to store
+** the key of an index. A blob encoding of a record is created by
+** the OP_MakeRecord opcode of the VDBE and is disassembled by the
+** OP_Column opcode.
+**
+** An instance of this object serves as a "key" for doing a search on
+** an index b+tree. The goal of the search is to find the entry that
+** is closed to the key described by this object. This object might hold
+** just a prefix of the key. The number of fields is given by
+** pKeyInfo->nField.
+**
+** The r1 and r2 fields are the values to return if this key is less than
+** or greater than a key in the btree, respectively. These are normally
+** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
+** is in DESC order.
+**
+** The key comparison functions actually return default_rc when they find
+** an equals comparison. default_rc can be -1, 0, or +1. If there are
+** multiple entries in the b-tree with the same key (when only looking
+** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
+** cause the search to find the last match, or +1 to cause the search to
+** find the first match.
+**
+** The key comparison functions will set eqSeen to true if they ever
+** get and equal results when comparing this structure to a b-tree record.
+** When default_rc!=0, the search might end up on the record immediately
+** before the first match or immediately after the last match. The
+** eqSeen field will indicate whether or not an exact match exists in the
+** b-tree.
+*/
+struct UnpackedRecord {
+ KeyInfo *pKeyInfo; /* Collation and sort-order information */
+ Mem *aMem; /* Values */
+ u16 nField; /* Number of entries in apMem[] */
+ i8 default_rc; /* Comparison result if keys are equal */
+ u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
+ i8 r1; /* Value to return if (lhs < rhs) */
+ i8 r2; /* Value to return if (lhs > rhs) */
+ u8 eqSeen; /* True if an equality comparison has been seen */
+};
+
+
+/*
+** Each SQL index is represented in memory by an
+** instance of the following structure.
+**
+** The columns of the table that are to be indexed are described
+** by the aiColumn[] field of this structure. For example, suppose
+** we have the following table and index:
+**
+** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
+** CREATE INDEX Ex2 ON Ex1(c3,c1);
+**
+** In the Table structure describing Ex1, nCol==3 because there are
+** three columns in the table. In the Index structure describing
+** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
+** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
+** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
+** The second column to be indexed (c1) has an index of 0 in
+** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
+**
+** The Index.onError field determines whether or not the indexed columns
+** must be unique and what to do if they are not. When Index.onError=OE_None,
+** it means this is not a unique index. Otherwise it is a unique index
+** and the value of Index.onError indicate the which conflict resolution
+** algorithm to employ whenever an attempt is made to insert a non-unique
+** element.
+**
+** While parsing a CREATE TABLE or CREATE INDEX statement in order to
+** generate VDBE code (as opposed to parsing one read from an sqlite_schema
+** table as part of parsing an existing database schema), transient instances
+** of this structure may be created. In this case the Index.tnum variable is
+** used to store the address of a VDBE instruction, not a database page
+** number (it cannot - the database page is not allocated until the VDBE
+** program is executed). See convertToWithoutRowidTable() for details.
+*/
+struct Index {
+ char *zName; /* Name of this index */
+ i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
+ LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
+ Table *pTable; /* The SQL table being indexed */
+ char *zColAff; /* String defining the affinity of each column */
+ Index *pNext; /* The next index associated with the same table */
+ Schema *pSchema; /* Schema containing this index */
+ u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
+ const char **azColl; /* Array of collation sequence names for index */
+ Expr *pPartIdxWhere; /* WHERE clause for partial indices */
+ ExprList *aColExpr; /* Column expressions */
+ Pgno tnum; /* DB Page containing root of this index */
+ LogEst szIdxRow; /* Estimated average row size in bytes */
+ u16 nKeyCol; /* Number of columns forming the key */
+ u16 nColumn; /* Number of columns stored in the index */
+ u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
+ unsigned idxType:2; /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */
+ unsigned bUnordered:1; /* Use this index for == or IN queries only */
+ unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
+ unsigned isResized:1; /* True if resizeIndexObject() has been called */
+ unsigned isCovering:1; /* True if this is a covering index */
+ unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
+ unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
+ unsigned bNoQuery:1; /* Do not use this index to optimize queries */
+ unsigned bAscKeyBug:1; /* True if the bba7b69f9849b5bf bug applies */
+ unsigned bHasVCol:1; /* Index references one or more VIRTUAL columns */
+#ifdef SQLITE_ENABLE_STAT4
+ int nSample; /* Number of elements in aSample[] */
+ int nSampleCol; /* Size of IndexSample.anEq[] and so on */
+ tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
+ IndexSample *aSample; /* Samples of the left-most key */
+ tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
+ tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
+#endif
+ Bitmask colNotIdxed; /* 0 for unindexed columns in pTab */
+};
+
+/*
+** Allowed values for Index.idxType
+*/
+#define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
+#define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
+#define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
+#define SQLITE_IDXTYPE_IPK 3 /* INTEGER PRIMARY KEY index */
+
+/* Return true if index X is a PRIMARY KEY index */
+#define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
+
+/* Return true if index X is a UNIQUE index */
+#define IsUniqueIndex(X) ((X)->onError!=OE_None)
+
+/* The Index.aiColumn[] values are normally positive integer. But
+** there are some negative values that have special meaning:
+*/
+#define XN_ROWID (-1) /* Indexed column is the rowid */
+#define XN_EXPR (-2) /* Indexed column is an expression */
+
+/*
+** Each sample stored in the sqlite_stat4 table is represented in memory
+** using a structure of this type. See documentation at the top of the
+** analyze.c source file for additional information.
+*/
+struct IndexSample {
+ void *p; /* Pointer to sampled record */
+ int n; /* Size of record in bytes */
+ tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
+ tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
+ tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
+};
+
+/*
+** Possible values to use within the flags argument to sqlite3GetToken().
+*/
+#define SQLITE_TOKEN_QUOTED 0x1 /* Token is a quoted identifier. */
+#define SQLITE_TOKEN_KEYWORD 0x2 /* Token is a keyword. */
+
+/*
+** Each token coming out of the lexer is an instance of
+** this structure. Tokens are also used as part of an expression.
+**
+** The memory that "z" points to is owned by other objects. Take care
+** that the owner of the "z" string does not deallocate the string before
+** the Token goes out of scope! Very often, the "z" points to some place
+** in the middle of the Parse.zSql text. But it might also point to a
+** static string.
+*/
+struct Token {
+ const char *z; /* Text of the token. Not NULL-terminated! */
+ unsigned int n; /* Number of characters in this token */
+};
+
+/*
+** An instance of this structure contains information needed to generate
+** code for a SELECT that contains aggregate functions.
+**
+** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
+** pointer to this structure. The Expr.iAgg field is the index in
+** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
+** code for that node.
+**
+** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
+** original Select structure that describes the SELECT statement. These
+** fields do not need to be freed when deallocating the AggInfo structure.
+*/
+struct AggInfo {
+ u8 directMode; /* Direct rendering mode means take data directly
+ ** from source tables rather than from accumulators */
+ u8 useSortingIdx; /* In direct mode, reference the sorting index rather
+ ** than the source table */
+ int sortingIdx; /* Cursor number of the sorting index */
+ int sortingIdxPTab; /* Cursor number of pseudo-table */
+ int nSortingColumn; /* Number of columns in the sorting index */
+ int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
+ ExprList *pGroupBy; /* The group by clause */
+ struct AggInfo_col { /* For each column used in source tables */
+ Table *pTab; /* Source table */
+ Expr *pCExpr; /* The original expression */
+ int iTable; /* Cursor number of the source table */
+ int iMem; /* Memory location that acts as accumulator */
+ i16 iColumn; /* Column number within the source table */
+ i16 iSorterColumn; /* Column number in the sorting index */
+ } *aCol;
+ int nColumn; /* Number of used entries in aCol[] */
+ int nAccumulator; /* Number of columns that show through to the output.
+ ** Additional columns are used only as parameters to
+ ** aggregate functions */
+ struct AggInfo_func { /* For each aggregate function */
+ Expr *pFExpr; /* Expression encoding the function */
+ FuncDef *pFunc; /* The aggregate function implementation */
+ int iMem; /* Memory location that acts as accumulator */
+ int iDistinct; /* Ephemeral table used to enforce DISTINCT */
+ } *aFunc;
+ int nFunc; /* Number of entries in aFunc[] */
+ u32 selId; /* Select to which this AggInfo belongs */
+ AggInfo *pNext; /* Next in list of them all */
+};
+
+/*
+** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
+** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
+** than 32767 we have to make it 32-bit. 16-bit is preferred because
+** it uses less memory in the Expr object, which is a big memory user
+** in systems with lots of prepared statements. And few applications
+** need more than about 10 or 20 variables. But some extreme users want
+** to have prepared statements with over 32766 variables, and for them
+** the option is available (at compile-time).
+*/
+#if SQLITE_MAX_VARIABLE_NUMBER<32767
+typedef i16 ynVar;
+#else
+typedef int ynVar;
+#endif
+
+/*
+** Each node of an expression in the parse tree is an instance
+** of this structure.
+**
+** Expr.op is the opcode. The integer parser token codes are reused
+** as opcodes here. For example, the parser defines TK_GE to be an integer
+** code representing the ">=" operator. This same integer code is reused
+** to represent the greater-than-or-equal-to operator in the expression
+** tree.
+**
+** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
+** or TK_STRING), then Expr.token contains the text of the SQL literal. If
+** the expression is a variable (TK_VARIABLE), then Expr.token contains the
+** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
+** then Expr.token contains the name of the function.
+**
+** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
+** binary operator. Either or both may be NULL.
+**
+** Expr.x.pList is a list of arguments if the expression is an SQL function,
+** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
+** Expr.x.pSelect is used if the expression is a sub-select or an expression of
+** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
+** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
+** valid.
+**
+** An expression of the form ID or ID.ID refers to a column in a table.
+** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
+** the integer cursor number of a VDBE cursor pointing to that table and
+** Expr.iColumn is the column number for the specific column. If the
+** expression is used as a result in an aggregate SELECT, then the
+** value is also stored in the Expr.iAgg column in the aggregate so that
+** it can be accessed after all aggregates are computed.
+**
+** If the expression is an unbound variable marker (a question mark
+** character '?' in the original SQL) then the Expr.iTable holds the index
+** number for that variable.
+**
+** If the expression is a subquery then Expr.iColumn holds an integer
+** register number containing the result of the subquery. If the
+** subquery gives a constant result, then iTable is -1. If the subquery
+** gives a different answer at different times during statement processing
+** then iTable is the address of a subroutine that computes the subquery.
+**
+** If the Expr is of type OP_Column, and the table it is selecting from
+** is a disk table or the "old.*" pseudo-table, then pTab points to the
+** corresponding table definition.
+**
+** ALLOCATION NOTES:
+**
+** Expr objects can use a lot of memory space in database schema. To
+** help reduce memory requirements, sometimes an Expr object will be
+** truncated. And to reduce the number of memory allocations, sometimes
+** two or more Expr objects will be stored in a single memory allocation,
+** together with Expr.zToken strings.
+**
+** If the EP_Reduced and EP_TokenOnly flags are set when
+** an Expr object is truncated. When EP_Reduced is set, then all
+** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
+** are contained within the same memory allocation. Note, however, that
+** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
+** allocated, regardless of whether or not EP_Reduced is set.
+*/
+struct Expr {
+ u8 op; /* Operation performed by this node */
+ char affExpr; /* affinity, or RAISE type */
+ u8 op2; /* TK_REGISTER/TK_TRUTH: original value of Expr.op
+ ** TK_COLUMN: the value of p5 for OP_Column
+ ** TK_AGG_FUNCTION: nesting depth
+ ** TK_FUNCTION: NC_SelfRef flag if needs OP_PureFunc */
+#ifdef SQLITE_DEBUG
+ u8 vvaFlags; /* Verification flags. */
+#endif
+ u32 flags; /* Various flags. EP_* See below */
+ union {
+ char *zToken; /* Token value. Zero terminated and dequoted */
+ int iValue; /* Non-negative integer value if EP_IntValue */
+ } u;
+
+ /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
+ ** space is allocated for the fields below this point. An attempt to
+ ** access them will result in a segfault or malfunction.
+ *********************************************************************/
+
+ Expr *pLeft; /* Left subnode */
+ Expr *pRight; /* Right subnode */
+ union {
+ ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
+ Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
+ } x;
+
+ /* If the EP_Reduced flag is set in the Expr.flags mask, then no
+ ** space is allocated for the fields below this point. An attempt to
+ ** access them will result in a segfault or malfunction.
+ *********************************************************************/
+
+#if SQLITE_MAX_EXPR_DEPTH>0
+ int nHeight; /* Height of the tree headed by this node */
+#endif
+ int iTable; /* TK_COLUMN: cursor number of table holding column
+ ** TK_REGISTER: register number
+ ** TK_TRIGGER: 1 -> new, 0 -> old
+ ** EP_Unlikely: 134217728 times likelihood
+ ** TK_IN: ephemerial table holding RHS
+ ** TK_SELECT_COLUMN: Number of columns on the LHS
+ ** TK_SELECT: 1st register of result vector */
+ ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
+ ** TK_VARIABLE: variable number (always >= 1).
+ ** TK_SELECT_COLUMN: column of the result vector */
+ i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
+ i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
+ AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
+ union {
+ Table *pTab; /* TK_COLUMN: Table containing column. Can be NULL
+ ** for a column of an index on an expression */
+ Window *pWin; /* EP_WinFunc: Window/Filter defn for a function */
+ struct { /* TK_IN, TK_SELECT, and TK_EXISTS */
+ int iAddr; /* Subroutine entry address */
+ int regReturn; /* Register used to hold return address */
+ } sub;
+ } y;
+};
+
+/*
+** The following are the meanings of bits in the Expr.flags field.
+** Value restrictions:
+**
+** EP_Agg == NC_HasAgg == SF_HasAgg
+** EP_Win == NC_HasWin
+*/
+#define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
+#define EP_Distinct 0x000002 /* Aggregate function with DISTINCT keyword */
+#define EP_HasFunc 0x000004 /* Contains one or more functions of any kind */
+#define EP_FixedCol 0x000008 /* TK_Column with a known fixed value */
+#define EP_Agg 0x000010 /* Contains one or more aggregate functions */
+#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
+#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
+#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
+#define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
+#define EP_Commuted 0x000200 /* Comparison operator has been commuted */
+#define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
+#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
+#define EP_Skip 0x001000 /* Operator does not contribute to affinity */
+#define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
+#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
+#define EP_Win 0x008000 /* Contains window functions */
+#define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
+#define EP_IfNullRow 0x020000 /* The TK_IF_NULL_ROW opcode */
+#define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
+#define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
+#define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
+#define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
+#define EP_Alias 0x400000 /* Is an alias for a result set column */
+#define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
+#define EP_WinFunc 0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
+#define EP_Subrtn 0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */
+#define EP_Quoted 0x4000000 /* TK_ID was originally quoted */
+#define EP_Static 0x8000000 /* Held in memory not obtained from malloc() */
+#define EP_IsTrue 0x10000000 /* Always has boolean value of TRUE */
+#define EP_IsFalse 0x20000000 /* Always has boolean value of FALSE */
+#define EP_FromDDL 0x40000000 /* Originates from sqlite_schema */
+ /* 0x80000000 // Available */
+
+/*
+** The EP_Propagate mask is a set of properties that automatically propagate
+** upwards into parent nodes.
+*/
+#define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
+
+/*
+** These macros can be used to test, set, or clear bits in the
+** Expr.flags field.
+*/
+#define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
+#define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
+#define ExprSetProperty(E,P) (E)->flags|=(P)
+#define ExprClearProperty(E,P) (E)->flags&=~(P)
+#define ExprAlwaysTrue(E) (((E)->flags&(EP_FromJoin|EP_IsTrue))==EP_IsTrue)
+#define ExprAlwaysFalse(E) (((E)->flags&(EP_FromJoin|EP_IsFalse))==EP_IsFalse)
+
+
+/* Flags for use with Expr.vvaFlags
+*/
+#define EP_NoReduce 0x01 /* Cannot EXPRDUP_REDUCE this Expr */
+#define EP_Immutable 0x02 /* Do not change this Expr node */
+
+/* The ExprSetVVAProperty() macro is used for Verification, Validation,
+** and Accreditation only. It works like ExprSetProperty() during VVA
+** processes but is a no-op for delivery.
+*/
+#ifdef SQLITE_DEBUG
+# define ExprSetVVAProperty(E,P) (E)->vvaFlags|=(P)
+# define ExprHasVVAProperty(E,P) (((E)->vvaFlags&(P))!=0)
+# define ExprClearVVAProperties(E) (E)->vvaFlags = 0
+#else
+# define ExprSetVVAProperty(E,P)
+# define ExprHasVVAProperty(E,P) 0
+# define ExprClearVVAProperties(E)
+#endif
+
+/*
+** Macros to determine the number of bytes required by a normal Expr
+** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
+** and an Expr struct with the EP_TokenOnly flag set.
+*/
+#define EXPR_FULLSIZE sizeof(Expr) /* Full size */
+#define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
+#define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
+
+/*
+** Flags passed to the sqlite3ExprDup() function. See the header comment
+** above sqlite3ExprDup() for details.
+*/
+#define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
+
+/*
+** True if the expression passed as an argument was a function with
+** an OVER() clause (a window function).
+*/
+#ifdef SQLITE_OMIT_WINDOWFUNC
+# define IsWindowFunc(p) 0
+#else
+# define IsWindowFunc(p) ( \
+ ExprHasProperty((p), EP_WinFunc) && p->y.pWin->eFrmType!=TK_FILTER \
+ )
+#endif
+
+/*
+** A list of expressions. Each expression may optionally have a
+** name. An expr/name combination can be used in several ways, such
+** as the list of "expr AS ID" fields following a "SELECT" or in the
+** list of "ID = expr" items in an UPDATE. A list of expressions can
+** also be used as the argument to a function, in which case the a.zName
+** field is not used.
+**
+** In order to try to keep memory usage down, the Expr.a.zEName field
+** is used for multiple purposes:
+**
+** eEName Usage
+** ---------- -------------------------
+** ENAME_NAME (1) the AS of result set column
+** (2) COLUMN= of an UPDATE
+**
+** ENAME_TAB DB.TABLE.NAME used to resolve names
+** of subqueries
+**
+** ENAME_SPAN Text of the original result set
+** expression.
+*/
+struct ExprList {
+ int nExpr; /* Number of expressions on the list */
+ struct ExprList_item { /* For each expression in the list */
+ Expr *pExpr; /* The parse tree for this expression */
+ char *zEName; /* Token associated with this expression */
+ u8 sortFlags; /* Mask of KEYINFO_ORDER_* flags */
+ unsigned eEName :2; /* Meaning of zEName */
+ unsigned done :1; /* A flag to indicate when processing is finished */
+ unsigned reusable :1; /* Constant expression is reusable */
+ unsigned bSorterRef :1; /* Defer evaluation until after sorting */
+ unsigned bNulls: 1; /* True if explicit "NULLS FIRST/LAST" */
+ union {
+ struct {
+ u16 iOrderByCol; /* For ORDER BY, column number in result set */
+ u16 iAlias; /* Index into Parse.aAlias[] for zName */
+ } x;
+ int iConstExprReg; /* Register in which Expr value is cached */
+ } u;
+ } a[1]; /* One slot for each expression in the list */
+};
+
+/*
+** Allowed values for Expr.a.eEName
+*/
+#define ENAME_NAME 0 /* The AS clause of a result set */
+#define ENAME_SPAN 1 /* Complete text of the result set expression */
+#define ENAME_TAB 2 /* "DB.TABLE.NAME" for the result set */
+
+/*
+** An instance of this structure can hold a simple list of identifiers,
+** such as the list "a,b,c" in the following statements:
+**
+** INSERT INTO t(a,b,c) VALUES ...;
+** CREATE INDEX idx ON t(a,b,c);
+** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
+**
+** The IdList.a.idx field is used when the IdList represents the list of
+** column names after a table name in an INSERT statement. In the statement
+**
+** INSERT INTO t(a,b,c) ...
+**
+** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
+*/
+struct IdList {
+ struct IdList_item {
+ char *zName; /* Name of the identifier */
+ int idx; /* Index in some Table.aCol[] of a column named zName */
+ } *a;
+ int nId; /* Number of identifiers on the list */
+};
+
+/*
+** The following structure describes the FROM clause of a SELECT statement.
+** Each table or subquery in the FROM clause is a separate element of
+** the SrcList.a[] array.
+**
+** With the addition of multiple database support, the following structure
+** can also be used to describe a particular table such as the table that
+** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
+** such a table must be a simple name: ID. But in SQLite, the table can
+** now be identified by a database name, a dot, then the table name: ID.ID.
+**
+** The jointype starts out showing the join type between the current table
+** and the next table on the list. The parser builds the list this way.
+** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
+** jointype expresses the join between the table and the previous table.
+**
+** In the colUsed field, the high-order bit (bit 63) is set if the table
+** contains more than 63 columns and the 64-th or later column is used.
+*/
+struct SrcList {
+ int nSrc; /* Number of tables or subqueries in the FROM clause */
+ u32 nAlloc; /* Number of entries allocated in a[] below */
+ struct SrcList_item {
+ Schema *pSchema; /* Schema to which this item is fixed */
+ char *zDatabase; /* Name of database holding this table */
+ char *zName; /* Name of the table */
+ char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
+ Table *pTab; /* An SQL table corresponding to zName */
+ Select *pSelect; /* A SELECT statement used in place of a table name */
+ int addrFillSub; /* Address of subroutine to manifest a subquery */
+ int regReturn; /* Register holding return address of addrFillSub */
+ int regResult; /* Registers holding results of a co-routine */
+ struct {
+ u8 jointype; /* Type of join between this table and the previous */
+ unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
+ unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
+ unsigned isTabFunc :1; /* True if table-valued-function syntax */
+ unsigned isCorrelated :1; /* True if sub-query is correlated */
+ unsigned viaCoroutine :1; /* Implemented as a co-routine */
+ unsigned isRecursive :1; /* True for recursive reference in WITH */
+ unsigned fromDDL :1; /* Comes from sqlite_schema */
+ } fg;
+ int iCursor; /* The VDBE cursor number used to access this table */
+ Expr *pOn; /* The ON clause of a join */
+ IdList *pUsing; /* The USING clause of a join */
+ Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
+ union {
+ char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
+ ExprList *pFuncArg; /* Arguments to table-valued-function */
+ } u1;
+ Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
+ } a[1]; /* One entry for each identifier on the list */
+};
+
+/*
+** Permitted values of the SrcList.a.jointype field
+*/
+#define JT_INNER 0x0001 /* Any kind of inner or cross join */
+#define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
+#define JT_NATURAL 0x0004 /* True for a "natural" join */
+#define JT_LEFT 0x0008 /* Left outer join */
+#define JT_RIGHT 0x0010 /* Right outer join */
+#define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
+#define JT_ERROR 0x0040 /* unknown or unsupported join type */
+
+
+/*
+** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
+** and the WhereInfo.wctrlFlags member.
+**
+** Value constraints (enforced via assert()):
+** WHERE_USE_LIMIT == SF_FixedLimit
+*/
+#define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
+#define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
+#define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
+#define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
+#define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
+#define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
+#define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
+ ** the OR optimization */
+#define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
+#define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
+#define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
+#define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
+ /* 0x0400 not currently used */
+#define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
+ /* 0x1000 not currently used */
+ /* 0x2000 not currently used */
+#define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
+ /* 0x8000 not currently used */
+
+/* Allowed return values from sqlite3WhereIsDistinct()
+*/
+#define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
+#define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
+#define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
+#define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
+
+/*
+** A NameContext defines a context in which to resolve table and column
+** names. The context consists of a list of tables (the pSrcList) field and
+** a list of named expression (pEList). The named expression list may
+** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
+** to the table being operated on by INSERT, UPDATE, or DELETE. The
+** pEList corresponds to the result set of a SELECT and is NULL for
+** other statements.
+**
+** NameContexts can be nested. When resolving names, the inner-most
+** context is searched first. If no match is found, the next outer
+** context is checked. If there is still no match, the next context
+** is checked. This process continues until either a match is found
+** or all contexts are check. When a match is found, the nRef member of
+** the context containing the match is incremented.
+**
+** Each subquery gets a new NameContext. The pNext field points to the
+** NameContext in the parent query. Thus the process of scanning the
+** NameContext list corresponds to searching through successively outer
+** subqueries looking for a match.
+*/
+struct NameContext {
+ Parse *pParse; /* The parser */
+ SrcList *pSrcList; /* One or more tables used to resolve names */
+ union {
+ ExprList *pEList; /* Optional list of result-set columns */
+ AggInfo *pAggInfo; /* Information about aggregates at this level */
+ Upsert *pUpsert; /* ON CONFLICT clause information from an upsert */
+ } uNC;
+ NameContext *pNext; /* Next outer name context. NULL for outermost */
+ int nRef; /* Number of names resolved by this context */
+ int nErr; /* Number of errors encountered while resolving names */
+ int ncFlags; /* Zero or more NC_* flags defined below */
+ Select *pWinSelect; /* SELECT statement for any window functions */
+};
+
+/*
+** Allowed values for the NameContext, ncFlags field.
+**
+** Value constraints (all checked via assert()):
+** NC_HasAgg == SF_HasAgg == EP_Agg
+** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
+** NC_HasWin == EP_Win
+**
+*/
+#define NC_AllowAgg 0x00001 /* Aggregate functions are allowed here */
+#define NC_PartIdx 0x00002 /* True if resolving a partial index WHERE */
+#define NC_IsCheck 0x00004 /* True if resolving a CHECK constraint */
+#define NC_GenCol 0x00008 /* True for a GENERATED ALWAYS AS clause */
+#define NC_HasAgg 0x00010 /* One or more aggregate functions seen */
+#define NC_IdxExpr 0x00020 /* True if resolving columns of CREATE INDEX */
+#define NC_SelfRef 0x0002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */
+#define NC_VarSelect 0x00040 /* A correlated subquery has been seen */
+#define NC_UEList 0x00080 /* True if uNC.pEList is used */
+#define NC_UAggInfo 0x00100 /* True if uNC.pAggInfo is used */
+#define NC_UUpsert 0x00200 /* True if uNC.pUpsert is used */
+#define NC_MinMaxAgg 0x01000 /* min/max aggregates seen. See note above */
+#define NC_Complex 0x02000 /* True if a function or subquery seen */
+#define NC_AllowWin 0x04000 /* Window functions are allowed here */
+#define NC_HasWin 0x08000 /* One or more window functions seen */
+#define NC_IsDDL 0x10000 /* Resolving names in a CREATE statement */
+#define NC_InAggFunc 0x20000 /* True if analyzing arguments to an agg func */
+#define NC_FromDDL 0x40000 /* SQL text comes from sqlite_schema */
+
+/*
+** An instance of the following object describes a single ON CONFLICT
+** clause in an upsert.
+**
+** The pUpsertTarget field is only set if the ON CONFLICT clause includes
+** conflict-target clause. (In "ON CONFLICT(a,b)" the "(a,b)" is the
+** conflict-target clause.) The pUpsertTargetWhere is the optional
+** WHERE clause used to identify partial unique indexes.
+**
+** pUpsertSet is the list of column=expr terms of the UPDATE statement.
+** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING. The
+** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the
+** WHERE clause is omitted.
+*/
+struct Upsert {
+ ExprList *pUpsertTarget; /* Optional description of conflicting index */
+ Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */
+ ExprList *pUpsertSet; /* The SET clause from an ON CONFLICT UPDATE */
+ Expr *pUpsertWhere; /* WHERE clause for the ON CONFLICT UPDATE */
+ /* The fields above comprise the parse tree for the upsert clause.
+ ** The fields below are used to transfer information from the INSERT
+ ** processing down into the UPDATE processing while generating code.
+ ** Upsert owns the memory allocated above, but not the memory below. */
+ Index *pUpsertIdx; /* Constraint that pUpsertTarget identifies */
+ SrcList *pUpsertSrc; /* Table to be updated */
+ int regData; /* First register holding array of VALUES */
+ int iDataCur; /* Index of the data cursor */
+ int iIdxCur; /* Index of the first index cursor */
+};
+
+/*
+** An instance of the following structure contains all information
+** needed to generate code for a single SELECT statement.
+**
+** See the header comment on the computeLimitRegisters() routine for a
+** detailed description of the meaning of the iLimit and iOffset fields.
+**
+** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
+** These addresses must be stored so that we can go back and fill in
+** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
+** the number of columns in P2 can be computed at the same time
+** as the OP_OpenEphm instruction is coded because not
+** enough information about the compound query is known at that point.
+** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
+** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
+** sequences for the ORDER BY clause.
+*/
+struct Select {
+ u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
+ LogEst nSelectRow; /* Estimated number of result rows */
+ u32 selFlags; /* Various SF_* values */
+ int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
+ u32 selId; /* Unique identifier number for this SELECT */
+ int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
+ ExprList *pEList; /* The fields of the result */
+ SrcList *pSrc; /* The FROM clause */
+ Expr *pWhere; /* The WHERE clause */
+ ExprList *pGroupBy; /* The GROUP BY clause */
+ Expr *pHaving; /* The HAVING clause */
+ ExprList *pOrderBy; /* The ORDER BY clause */
+ Select *pPrior; /* Prior select in a compound select statement */
+ Select *pNext; /* Next select to the left in a compound */
+ Expr *pLimit; /* LIMIT expression. NULL means not used. */
+ With *pWith; /* WITH clause attached to this select. Or NULL. */
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ Window *pWin; /* List of window functions */
+ Window *pWinDefn; /* List of named window definitions */
+#endif
+};
+
+/*
+** Allowed values for Select.selFlags. The "SF" prefix stands for
+** "Select Flag".
+**
+** Value constraints (all checked via assert())
+** SF_HasAgg == NC_HasAgg
+** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
+** SF_FixedLimit == WHERE_USE_LIMIT
+*/
+#define SF_Distinct 0x0000001 /* Output should be DISTINCT */
+#define SF_All 0x0000002 /* Includes the ALL keyword */
+#define SF_Resolved 0x0000004 /* Identifiers have been resolved */
+#define SF_Aggregate 0x0000008 /* Contains agg functions or a GROUP BY */
+#define SF_HasAgg 0x0000010 /* Contains aggregate functions */
+#define SF_UsesEphemeral 0x0000020 /* Uses the OpenEphemeral opcode */
+#define SF_Expanded 0x0000040 /* sqlite3SelectExpand() called on this */
+#define SF_HasTypeInfo 0x0000080 /* FROM subqueries have Table metadata */
+#define SF_Compound 0x0000100 /* Part of a compound query */
+#define SF_Values 0x0000200 /* Synthesized from VALUES clause */
+#define SF_MultiValue 0x0000400 /* Single VALUES term with multiple rows */
+#define SF_NestedFrom 0x0000800 /* Part of a parenthesized FROM clause */
+#define SF_MinMaxAgg 0x0001000 /* Aggregate containing min() or max() */
+#define SF_Recursive 0x0002000 /* The recursive part of a recursive CTE */
+#define SF_FixedLimit 0x0004000 /* nSelectRow set by a constant LIMIT */
+#define SF_MaybeConvert 0x0008000 /* Need convertCompoundSelectToSubquery() */
+#define SF_Converted 0x0010000 /* By convertCompoundSelectToSubquery() */
+#define SF_IncludeHidden 0x0020000 /* Include hidden columns in output */
+#define SF_ComplexResult 0x0040000 /* Result contains subquery or function */
+#define SF_WhereBegin 0x0080000 /* Really a WhereBegin() call. Debug Only */
+#define SF_WinRewrite 0x0100000 /* Window function rewrite accomplished */
+#define SF_View 0x0200000 /* SELECT statement is a view */
+#define SF_NoopOrderBy 0x0400000 /* ORDER BY is ignored for this query */
+#define SF_UpdateFrom 0x0800000 /* Statement is an UPDATE...FROM */
+
+/*
+** The results of a SELECT can be distributed in several ways, as defined
+** by one of the following macros. The "SRT" prefix means "SELECT Result
+** Type".
+**
+** SRT_Union Store results as a key in a temporary index
+** identified by pDest->iSDParm.
+**
+** SRT_Except Remove results from the temporary index pDest->iSDParm.
+**
+** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
+** set is not empty.
+**
+** SRT_Discard Throw the results away. This is used by SELECT
+** statements within triggers whose only purpose is
+** the side-effects of functions.
+**
+** SRT_Output Generate a row of output (using the OP_ResultRow
+** opcode) for each row in the result set.
+**
+** SRT_Mem Only valid if the result is a single column.
+** Store the first column of the first result row
+** in register pDest->iSDParm then abandon the rest
+** of the query. This destination implies "LIMIT 1".
+**
+** SRT_Set The result must be a single column. Store each
+** row of result as the key in table pDest->iSDParm.
+** Apply the affinity pDest->affSdst before storing
+** results. Used to implement "IN (SELECT ...)".
+**
+** SRT_EphemTab Create an temporary table pDest->iSDParm and store
+** the result there. The cursor is left open after
+** returning. This is like SRT_Table except that
+** this destination uses OP_OpenEphemeral to create
+** the table first.
+**
+** SRT_Coroutine Generate a co-routine that returns a new row of
+** results each time it is invoked. The entry point
+** of the co-routine is stored in register pDest->iSDParm
+** and the result row is stored in pDest->nDest registers
+** starting with pDest->iSdst.
+**
+** SRT_Table Store results in temporary table pDest->iSDParm.
+** SRT_Fifo This is like SRT_EphemTab except that the table
+** is assumed to already be open. SRT_Fifo has
+** the additional property of being able to ignore
+** the ORDER BY clause.
+**
+** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
+** But also use temporary table pDest->iSDParm+1 as
+** a record of all prior results and ignore any duplicate
+** rows. Name means: "Distinct Fifo".
+**
+** SRT_Queue Store results in priority queue pDest->iSDParm (really
+** an index). Append a sequence number so that all entries
+** are distinct.
+**
+** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
+** the same record has never been stored before. The
+** index at pDest->iSDParm+1 hold all prior stores.
+**
+** SRT_Upfrom Store results in the temporary table already opened by
+** pDest->iSDParm. If (pDest->iSDParm<0), then the temp
+** table is an intkey table - in this case the first
+** column returned by the SELECT is used as the integer
+** key. If (pDest->iSDParm>0), then the table is an index
+** table. (pDest->iSDParm) is the number of key columns in
+** each index record in this case.
+*/
+#define SRT_Union 1 /* Store result as keys in an index */
+#define SRT_Except 2 /* Remove result from a UNION index */
+#define SRT_Exists 3 /* Store 1 if the result is not empty */
+#define SRT_Discard 4 /* Do not save the results anywhere */
+#define SRT_DistFifo 5 /* Like SRT_Fifo, but unique results only */
+#define SRT_DistQueue 6 /* Like SRT_Queue, but unique results only */
+
+/* The DISTINCT clause is ignored for all of the above. Not that
+** IgnorableDistinct() implies IgnorableOrderby() */
+#define IgnorableDistinct(X) ((X->eDest)<=SRT_DistQueue)
+
+#define SRT_Queue 7 /* Store result in an queue */
+#define SRT_Fifo 8 /* Store result as data with an automatic rowid */
+
+/* The ORDER BY clause is ignored for all of the above */
+#define IgnorableOrderby(X) ((X->eDest)<=SRT_Fifo)
+
+#define SRT_Output 9 /* Output each row of result */
+#define SRT_Mem 10 /* Store result in a memory cell */
+#define SRT_Set 11 /* Store results as keys in an index */
+#define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
+#define SRT_Coroutine 13 /* Generate a single row of result */
+#define SRT_Table 14 /* Store result as data with an automatic rowid */
+#define SRT_Upfrom 15 /* Store result as data with rowid */
+
+/*
+** An instance of this object describes where to put of the results of
+** a SELECT statement.
+*/
+struct SelectDest {
+ u8 eDest; /* How to dispose of the results. One of SRT_* above. */
+ int iSDParm; /* A parameter used by the eDest disposal method */
+ int iSDParm2; /* A second parameter for the eDest disposal method */
+ int iSdst; /* Base register where results are written */
+ int nSdst; /* Number of registers allocated */
+ char *zAffSdst; /* Affinity used when eDest==SRT_Set */
+ ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
+};
+
+/*
+** During code generation of statements that do inserts into AUTOINCREMENT
+** tables, the following information is attached to the Table.u.autoInc.p
+** pointer of each autoincrement table to record some side information that
+** the code generator needs. We have to keep per-table autoincrement
+** information in case inserts are done within triggers. Triggers do not
+** normally coordinate their activities, but we do need to coordinate the
+** loading and saving of autoincrement information.
+*/
+struct AutoincInfo {
+ AutoincInfo *pNext; /* Next info block in a list of them all */
+ Table *pTab; /* Table this info block refers to */
+ int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
+ int regCtr; /* Memory register holding the rowid counter */
+};
+
+/*
+** At least one instance of the following structure is created for each
+** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
+** statement. All such objects are stored in the linked list headed at
+** Parse.pTriggerPrg and deleted once statement compilation has been
+** completed.
+**
+** A Vdbe sub-program that implements the body and WHEN clause of trigger
+** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
+** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
+** The Parse.pTriggerPrg list never contains two entries with the same
+** values for both pTrigger and orconf.
+**
+** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
+** accessed (or set to 0 for triggers fired as a result of INSERT
+** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
+** a mask of new.* columns used by the program.
+*/
+struct TriggerPrg {
+ Trigger *pTrigger; /* Trigger this program was coded from */
+ TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
+ SubProgram *pProgram; /* Program implementing pTrigger/orconf */
+ int orconf; /* Default ON CONFLICT policy */
+ u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
+};
+
+/*
+** The yDbMask datatype for the bitmask of all attached databases.
+*/
+#if SQLITE_MAX_ATTACHED>30
+ typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
+# define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
+# define DbMaskZero(M) memset((M),0,sizeof(M))
+# define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
+# define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
+# define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
+#else
+ typedef unsigned int yDbMask;
+# define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
+# define DbMaskZero(M) (M)=0
+# define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
+# define DbMaskAllZero(M) (M)==0
+# define DbMaskNonZero(M) (M)!=0
+#endif
+
+/*
+** An SQL parser context. A copy of this structure is passed through
+** the parser and down into all the parser action routine in order to
+** carry around information that is global to the entire parse.
+**
+** The structure is divided into two parts. When the parser and code
+** generate call themselves recursively, the first part of the structure
+** is constant but the second part is reset at the beginning and end of
+** each recursion.
+**
+** The nTableLock and aTableLock variables are only used if the shared-cache
+** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
+** used to store the set of table-locks required by the statement being
+** compiled. Function sqlite3TableLock() is used to add entries to the
+** list.
+*/
+struct Parse {
+ sqlite3 *db; /* The main database structure */
+ char *zErrMsg; /* An error message */
+ Vdbe *pVdbe; /* An engine for executing database bytecode */
+ int rc; /* Return code from execution */
+ u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
+ u8 checkSchema; /* Causes schema cookie check after an error */
+ u8 nested; /* Number of nested calls to the parser/code generator */
+ u8 nTempReg; /* Number of temporary registers in aTempReg[] */
+ u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
+ u8 mayAbort; /* True if statement may throw an ABORT exception */
+ u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
+ u8 okConstFactor; /* OK to factor out constants */
+ u8 disableLookaside; /* Number of times lookaside has been disabled */
+ u8 disableVtab; /* Disable all virtual tables for this parse */
+ int nRangeReg; /* Size of the temporary register block */
+ int iRangeReg; /* First register in temporary register block */
+ int nErr; /* Number of errors seen */
+ int nTab; /* Number of previously allocated VDBE cursors */
+ int nMem; /* Number of memory cells used so far */
+ int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
+ int iSelfTab; /* Table associated with an index on expr, or negative
+ ** of the base register during check-constraint eval */
+ int nLabel; /* The *negative* of the number of labels used */
+ int nLabelAlloc; /* Number of slots in aLabel */
+ int *aLabel; /* Space to hold the labels */
+ ExprList *pConstExpr;/* Constant expressions */
+ Token constraintName;/* Name of the constraint currently being parsed */
+ yDbMask writeMask; /* Start a write transaction on these databases */
+ yDbMask cookieMask; /* Bitmask of schema verified databases */
+ int regRowid; /* Register holding rowid of CREATE TABLE entry */
+ int regRoot; /* Register holding root page number for new objects */
+ int nMaxArg; /* Max args passed to user function by sub-program */
+ int nSelect; /* Number of SELECT stmts. Counter for Select.selId */
+#ifndef SQLITE_OMIT_SHARED_CACHE
+ int nTableLock; /* Number of locks in aTableLock */
+ TableLock *aTableLock; /* Required table locks for shared-cache mode */
+#endif
+ AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
+ Parse *pToplevel; /* Parse structure for main program (or NULL) */
+ Table *pTriggerTab; /* Table triggers are being coded for */
+ Parse *pParentParse; /* Parent parser if this parser is nested */
+ AggInfo *pAggList; /* List of all AggInfo objects */
+ int addrCrTab; /* Address of OP_CreateBtree opcode on CREATE TABLE */
+ u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
+ u32 oldmask; /* Mask of old.* columns referenced */
+ u32 newmask; /* Mask of new.* columns referenced */
+ u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
+ u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
+ u8 disableTriggers; /* True to disable triggers */
+
+ /**************************************************************************
+ ** Fields above must be initialized to zero. The fields that follow,
+ ** down to the beginning of the recursive section, do not need to be
+ ** initialized as they will be set before being used. The boundary is
+ ** determined by offsetof(Parse,aTempReg).
+ **************************************************************************/
+
+ int aTempReg[8]; /* Holding area for temporary registers */
+ Token sNameToken; /* Token with unqualified schema object name */
+
+ /************************************************************************
+ ** Above is constant between recursions. Below is reset before and after
+ ** each recursion. The boundary between these two regions is determined
+ ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
+ ** first field in the recursive region.
+ ************************************************************************/
+
+ Token sLastToken; /* The last token parsed */
+ ynVar nVar; /* Number of '?' variables seen in the SQL so far */
+ u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
+ u8 explain; /* True if the EXPLAIN flag is found on the query */
+ u8 eParseMode; /* PARSE_MODE_XXX constant */
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ int nVtabLock; /* Number of virtual tables to lock */
+#endif
+ int nHeight; /* Expression tree height of current sub-select */
+#ifndef SQLITE_OMIT_EXPLAIN
+ int addrExplain; /* Address of current OP_Explain opcode */
+#endif
+ VList *pVList; /* Mapping between variable names and numbers */
+ Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
+ const char *zTail; /* All SQL text past the last semicolon parsed */
+ Table *pNewTable; /* A table being constructed by CREATE TABLE */
+ Index *pNewIndex; /* An index being constructed by CREATE INDEX.
+ ** Also used to hold redundant UNIQUE constraints
+ ** during a RENAME COLUMN */
+ Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
+ const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ Token sArg; /* Complete text of a module argument */
+ Table **apVtabLock; /* Pointer to virtual tables needing locking */
+#endif
+ Table *pZombieTab; /* List of Table objects to delete after code gen */
+ TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
+ With *pWith; /* Current WITH clause, or NULL */
+ With *pWithToFree; /* Free this WITH object at the end of the parse */
+#ifndef SQLITE_OMIT_ALTERTABLE
+ RenameToken *pRename; /* Tokens subject to renaming by ALTER TABLE */
+#endif
+};
+
+#define PARSE_MODE_NORMAL 0
+#define PARSE_MODE_DECLARE_VTAB 1
+#define PARSE_MODE_RENAME 2
+#define PARSE_MODE_UNMAP 3
+
+/*
+** Sizes and pointers of various parts of the Parse object.
+*/
+#define PARSE_HDR_SZ offsetof(Parse,aTempReg) /* Recursive part w/o aColCache*/
+#define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
+#define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
+#define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
+
+/*
+** Return true if currently inside an sqlite3_declare_vtab() call.
+*/
+#ifdef SQLITE_OMIT_VIRTUALTABLE
+ #define IN_DECLARE_VTAB 0
+#else
+ #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)
+#endif
+
+#if defined(SQLITE_OMIT_ALTERTABLE)
+ #define IN_RENAME_OBJECT 0
+#else
+ #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME)
+#endif
+
+#if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)
+ #define IN_SPECIAL_PARSE 0
+#else
+ #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)
+#endif
+
+/*
+** An instance of the following structure can be declared on a stack and used
+** to save the Parse.zAuthContext value so that it can be restored later.
+*/
+struct AuthContext {
+ const char *zAuthContext; /* Put saved Parse.zAuthContext here */
+ Parse *pParse; /* The Parse structure */
+};
+
+/*
+** Bitfield flags for P5 value in various opcodes.
+**
+** Value constraints (enforced via assert()):
+** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
+** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
+** OPFLAG_BULKCSR == BTREE_BULKLOAD
+** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
+** OPFLAG_FORDELETE == BTREE_FORDELETE
+** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
+** OPFLAG_AUXDELETE == BTREE_AUXDELETE
+*/
+#define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
+ /* Also used in P2 (not P5) of OP_Delete */
+#define OPFLAG_NOCHNG 0x01 /* OP_VColumn nochange for UPDATE */
+#define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
+#define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
+#define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
+#define OPFLAG_APPEND 0x08 /* This is likely to be an append */
+#define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
+#define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
+#define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
+#define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
+#define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
+#define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
+#define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
+#define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
+#define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
+#define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */
+#define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
+#define OPFLAG_NOCHNG_MAGIC 0x6d /* OP_MakeRecord: serialtype 10 is ok */
+
+/*
+ * Each trigger present in the database schema is stored as an instance of
+ * struct Trigger.
+ *
+ * Pointers to instances of struct Trigger are stored in two ways.
+ * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
+ * database). This allows Trigger structures to be retrieved by name.
+ * 2. All triggers associated with a single table form a linked list, using the
+ * pNext member of struct Trigger. A pointer to the first element of the
+ * linked list is stored as the "pTrigger" member of the associated
+ * struct Table.
+ *
+ * The "step_list" member points to the first element of a linked list
+ * containing the SQL statements specified as the trigger program.
+ */
+struct Trigger {
+ char *zName; /* The name of the trigger */
+ char *table; /* The table or view to which the trigger applies */
+ u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
+ u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
+ Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
+ IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
+ the <column-list> is stored here */
+ Schema *pSchema; /* Schema containing the trigger */
+ Schema *pTabSchema; /* Schema containing the table */
+ TriggerStep *step_list; /* Link list of trigger program steps */
+ Trigger *pNext; /* Next trigger associated with the table */
+};
+
+/*
+** A trigger is either a BEFORE or an AFTER trigger. The following constants
+** determine which.
+**
+** If there are multiple triggers, you might of some BEFORE and some AFTER.
+** In that cases, the constants below can be ORed together.
+*/
+#define TRIGGER_BEFORE 1
+#define TRIGGER_AFTER 2
+
+/*
+ * An instance of struct TriggerStep is used to store a single SQL statement
+ * that is a part of a trigger-program.
+ *
+ * Instances of struct TriggerStep are stored in a singly linked list (linked
+ * using the "pNext" member) referenced by the "step_list" member of the
+ * associated struct Trigger instance. The first element of the linked list is
+ * the first step of the trigger-program.
+ *
+ * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
+ * "SELECT" statement. The meanings of the other members is determined by the
+ * value of "op" as follows:
+ *
+ * (op == TK_INSERT)
+ * orconf -> stores the ON CONFLICT algorithm
+ * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
+ * this stores a pointer to the SELECT statement. Otherwise NULL.
+ * zTarget -> Dequoted name of the table to insert into.
+ * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
+ * this stores values to be inserted. Otherwise NULL.
+ * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
+ * statement, then this stores the column-names to be
+ * inserted into.
+ *
+ * (op == TK_DELETE)
+ * zTarget -> Dequoted name of the table to delete from.
+ * pWhere -> The WHERE clause of the DELETE statement if one is specified.
+ * Otherwise NULL.
+ *
+ * (op == TK_UPDATE)
+ * zTarget -> Dequoted name of the table to update.
+ * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
+ * Otherwise NULL.
+ * pExprList -> A list of the columns to update and the expressions to update
+ * them to. See sqlite3Update() documentation of "pChanges"
+ * argument.
+ *
+ */
+struct TriggerStep {
+ u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
+ u8 orconf; /* OE_Rollback etc. */
+ Trigger *pTrig; /* The trigger that this step is a part of */
+ Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
+ char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
+ SrcList *pFrom; /* FROM clause for UPDATE statement (if any) */
+ Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
+ ExprList *pExprList; /* SET clause for UPDATE */
+ IdList *pIdList; /* Column names for INSERT */
+ Upsert *pUpsert; /* Upsert clauses on an INSERT */
+ char *zSpan; /* Original SQL text of this command */
+ TriggerStep *pNext; /* Next in the link-list */
+ TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
+};
+
+/*
+** The following structure contains information used by the sqliteFix...
+** routines as they walk the parse tree to make database references
+** explicit.
+*/
+typedef struct DbFixer DbFixer;
+struct DbFixer {
+ Parse *pParse; /* The parsing context. Error messages written here */
+ Schema *pSchema; /* Fix items to this schema */
+ u8 bTemp; /* True for TEMP schema entries */
+ const char *zDb; /* Make sure all objects are contained in this database */
+ const char *zType; /* Type of the container - used for error messages */
+ const Token *pName; /* Name of the container - used for error messages */
+};
+
+/*
+** An objected used to accumulate the text of a string where we
+** do not necessarily know how big the string will be in the end.
+*/
+struct sqlite3_str {
+ sqlite3 *db; /* Optional database for lookaside. Can be NULL */
+ char *zText; /* The string collected so far */
+ u32 nAlloc; /* Amount of space allocated in zText */
+ u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
+ u32 nChar; /* Length of the string so far */
+ u8 accError; /* SQLITE_NOMEM or SQLITE_TOOBIG */
+ u8 printfFlags; /* SQLITE_PRINTF flags below */
+};
+#define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
+#define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
+#define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
+
+#define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
+
+
+/*
+** A pointer to this structure is used to communicate information
+** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
+*/
+typedef struct {
+ sqlite3 *db; /* The database being initialized */
+ char **pzErrMsg; /* Error message stored here */
+ int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
+ int rc; /* Result code stored here */
+ u32 mInitFlags; /* Flags controlling error messages */
+ u32 nInitRow; /* Number of rows processed */
+ Pgno mxPage; /* Maximum page number. 0 for no limit. */
+} InitData;
+
+/*
+** Allowed values for mInitFlags
+*/
+#define INITFLAG_AlterTable 0x0001 /* This is a reparse after ALTER TABLE */
+
+/*
+** Structure containing global configuration data for the SQLite library.
+**
+** This structure also contains some state information.
+*/
+struct Sqlite3Config {
+ int bMemstat; /* True to enable memory status */
+ u8 bCoreMutex; /* True to enable core mutexing */
+ u8 bFullMutex; /* True to enable full mutexing */
+ u8 bOpenUri; /* True to interpret filenames as URIs */
+ u8 bUseCis; /* Use covering indices for full-scans */
+ u8 bSmallMalloc; /* Avoid large memory allocations if true */
+ u8 bExtraSchemaChecks; /* Verify type,name,tbl_name in schema */
+ int mxStrlen; /* Maximum string length */
+ int neverCorrupt; /* Database is always well-formed */
+ int szLookaside; /* Default lookaside buffer size */
+ int nLookaside; /* Default lookaside buffer count */
+ int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
+ sqlite3_mem_methods m; /* Low-level memory allocation interface */
+ sqlite3_mutex_methods mutex; /* Low-level mutex interface */
+ sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
+ void *pHeap; /* Heap storage space */
+ int nHeap; /* Size of pHeap[] */
+ int mnReq, mxReq; /* Min and max heap requests sizes */
+ sqlite3_int64 szMmap; /* mmap() space per open file */
+ sqlite3_int64 mxMmap; /* Maximum value for szMmap */
+ void *pPage; /* Page cache memory */
+ int szPage; /* Size of each page in pPage[] */
+ int nPage; /* Number of pages in pPage[] */
+ int mxParserStack; /* maximum depth of the parser stack */
+ int sharedCacheEnabled; /* true if shared-cache mode enabled */
+ u32 szPma; /* Maximum Sorter PMA size */
+ /* The above might be initialized to non-zero. The following need to always
+ ** initially be zero, however. */
+ int isInit; /* True after initialization has finished */
+ int inProgress; /* True while initialization in progress */
+ int isMutexInit; /* True after mutexes are initialized */
+ int isMallocInit; /* True after malloc is initialized */
+ int isPCacheInit; /* True after malloc is initialized */
+ int nRefInitMutex; /* Number of users of pInitMutex */
+ sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
+ void (*xLog)(void*,int,const char*); /* Function for logging */
+ void *pLogArg; /* First argument to xLog() */
+#ifdef SQLITE_ENABLE_SQLLOG
+ void(*xSqllog)(void*,sqlite3*,const char*, int);
+ void *pSqllogArg;
+#endif
+#ifdef SQLITE_VDBE_COVERAGE
+ /* The following callback (if not NULL) is invoked on every VDBE branch
+ ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
+ */
+ void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx); /* Callback */
+ void *pVdbeBranchArg; /* 1st argument */
+#endif
+#ifdef SQLITE_ENABLE_DESERIALIZE
+ sqlite3_int64 mxMemdbSize; /* Default max memdb size */
+#endif
+#ifndef SQLITE_UNTESTABLE
+ int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
+#endif
+ int bLocaltimeFault; /* True to fail localtime() calls */
+ int iOnceResetThreshold; /* When to reset OP_Once counters */
+ u32 szSorterRef; /* Min size in bytes to use sorter-refs */
+ unsigned int iPrngSeed; /* Alternative fixed seed for the PRNG */
+};
+
+/*
+** This macro is used inside of assert() statements to indicate that
+** the assert is only valid on a well-formed database. Instead of:
+**
+** assert( X );
+**
+** One writes:
+**
+** assert( X || CORRUPT_DB );
+**
+** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
+** that the database is definitely corrupt, only that it might be corrupt.
+** For most test cases, CORRUPT_DB is set to false using a special
+** sqlite3_test_control(). This enables assert() statements to prove
+** things that are always true for well-formed databases.
+*/
+#define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
+
+/*
+** Context pointer passed down through the tree-walk.
+*/
+struct Walker {
+ Parse *pParse; /* Parser context. */
+ int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
+ int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
+ void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
+ int walkerDepth; /* Number of subqueries */
+ u16 eCode; /* A small processing code */
+ union { /* Extra data for callback */
+ NameContext *pNC; /* Naming context */
+ int n; /* A counter */
+ int iCur; /* A cursor number */
+ SrcList *pSrcList; /* FROM clause */
+ struct SrcCount *pSrcCount; /* Counting column references */
+ struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
+ int *aiCol; /* array of column indexes */
+ struct IdxCover *pIdxCover; /* Check for index coverage */
+ struct IdxExprTrans *pIdxTrans; /* Convert idxed expr to column */
+ ExprList *pGroupBy; /* GROUP BY clause */
+ Select *pSelect; /* HAVING to WHERE clause ctx */
+ struct WindowRewrite *pRewrite; /* Window rewrite context */
+ struct WhereConst *pConst; /* WHERE clause constants */
+ struct RenameCtx *pRename; /* RENAME COLUMN context */
+ struct Table *pTab; /* Table of generated column */
+ struct SrcList_item *pSrcItem; /* A single FROM clause item */
+ } u;
+};
+
+/* Forward declarations */
+SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
+SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
+SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
+SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
+SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
+SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
+SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
+SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
+SQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker*,Select*);
+SQLITE_PRIVATE void sqlite3WalkerDepthDecrease(Walker*,Select*);
+
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
+#endif
+
+/*
+** Return code from the parse-tree walking primitives and their
+** callbacks.
+*/
+#define WRC_Continue 0 /* Continue down into children */
+#define WRC_Prune 1 /* Omit children but continue walking siblings */
+#define WRC_Abort 2 /* Abandon the tree walk */
+
+/*
+** An instance of this structure represents a set of one or more CTEs
+** (common table expressions) created by a single WITH clause.
+*/
+struct With {
+ int nCte; /* Number of CTEs in the WITH clause */
+ With *pOuter; /* Containing WITH clause, or NULL */
+ struct Cte { /* For each CTE in the WITH clause.... */
+ char *zName; /* Name of this CTE */
+ ExprList *pCols; /* List of explicit column names, or NULL */
+ Select *pSelect; /* The definition of this CTE */
+ const char *zCteErr; /* Error message for circular references */
+ } a[1];
+};
+
+#ifdef SQLITE_DEBUG
+/*
+** An instance of the TreeView object is used for printing the content of
+** data structures on sqlite3DebugPrintf() using a tree-like view.
+*/
+struct TreeView {
+ int iLevel; /* Which level of the tree we are on */
+ u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
+};
+#endif /* SQLITE_DEBUG */
+
+/*
+** This object is used in various ways, most (but not all) related to window
+** functions.
+**
+** (1) A single instance of this structure is attached to the
+** the Expr.y.pWin field for each window function in an expression tree.
+** This object holds the information contained in the OVER clause,
+** plus additional fields used during code generation.
+**
+** (2) All window functions in a single SELECT form a linked-list
+** attached to Select.pWin. The Window.pFunc and Window.pExpr
+** fields point back to the expression that is the window function.
+**
+** (3) The terms of the WINDOW clause of a SELECT are instances of this
+** object on a linked list attached to Select.pWinDefn.
+**
+** (4) For an aggregate function with a FILTER clause, an instance
+** of this object is stored in Expr.y.pWin with eFrmType set to
+** TK_FILTER. In this case the only field used is Window.pFilter.
+**
+** The uses (1) and (2) are really the same Window object that just happens
+** to be accessible in two different ways. Use case (3) are separate objects.
+*/
+struct Window {
+ char *zName; /* Name of window (may be NULL) */
+ char *zBase; /* Name of base window for chaining (may be NULL) */
+ ExprList *pPartition; /* PARTITION BY clause */
+ ExprList *pOrderBy; /* ORDER BY clause */
+ u8 eFrmType; /* TK_RANGE, TK_GROUPS, TK_ROWS, or 0 */
+ u8 eStart; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
+ u8 eEnd; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
+ u8 bImplicitFrame; /* True if frame was implicitly specified */
+ u8 eExclude; /* TK_NO, TK_CURRENT, TK_TIES, TK_GROUP, or 0 */
+ Expr *pStart; /* Expression for "<expr> PRECEDING" */
+ Expr *pEnd; /* Expression for "<expr> FOLLOWING" */
+ Window **ppThis; /* Pointer to this object in Select.pWin list */
+ Window *pNextWin; /* Next window function belonging to this SELECT */
+ Expr *pFilter; /* The FILTER expression */
+ FuncDef *pFunc; /* The function */
+ int iEphCsr; /* Partition buffer or Peer buffer */
+ int regAccum; /* Accumulator */
+ int regResult; /* Interim result */
+ int csrApp; /* Function cursor (used by min/max) */
+ int regApp; /* Function register (also used by min/max) */
+ int regPart; /* Array of registers for PARTITION BY values */
+ Expr *pOwner; /* Expression object this window is attached to */
+ int nBufferCol; /* Number of columns in buffer table */
+ int iArgCol; /* Offset of first argument for this function */
+ int regOne; /* Register containing constant value 1 */
+ int regStartRowid;
+ int regEndRowid;
+ u8 bExprArgs; /* Defer evaluation of window function arguments
+ ** due to the SQLITE_SUBTYPE flag */
+};
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3*, Window*);
+SQLITE_PRIVATE void sqlite3WindowUnlinkFromSelect(Window*);
+SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p);
+SQLITE_PRIVATE Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8);
+SQLITE_PRIVATE void sqlite3WindowAttach(Parse*, Expr*, Window*);
+SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin);
+SQLITE_PRIVATE int sqlite3WindowCompare(Parse*, Window*, Window*, int);
+SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Select*);
+SQLITE_PRIVATE void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
+SQLITE_PRIVATE int sqlite3WindowRewrite(Parse*, Select*);
+SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, struct SrcList_item*);
+SQLITE_PRIVATE void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);
+SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);
+SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p);
+SQLITE_PRIVATE void sqlite3WindowFunctions(void);
+SQLITE_PRIVATE void sqlite3WindowChain(Parse*, Window*, Window*);
+SQLITE_PRIVATE Window *sqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprList*, Token*);
+#else
+# define sqlite3WindowDelete(a,b)
+# define sqlite3WindowFunctions()
+# define sqlite3WindowAttach(a,b,c)
+#endif
+
+/*
+** Assuming zIn points to the first byte of a UTF-8 character,
+** advance zIn to point to the first byte of the next UTF-8 character.
+*/
+#define SQLITE_SKIP_UTF8(zIn) { \
+ if( (*(zIn++))>=0xc0 ){ \
+ while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
+ } \
+}
+
+/*
+** The SQLITE_*_BKPT macros are substitutes for the error codes with
+** the same name but without the _BKPT suffix. These macros invoke
+** routines that report the line-number on which the error originated
+** using sqlite3_log(). The routines also provide a convenient place
+** to set a debugger breakpoint.
+*/
+SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType);
+SQLITE_PRIVATE int sqlite3CorruptError(int);
+SQLITE_PRIVATE int sqlite3MisuseError(int);
+SQLITE_PRIVATE int sqlite3CantopenError(int);
+#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
+#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
+#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE int sqlite3NomemError(int);
+SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
+# define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
+# define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
+#else
+# define SQLITE_NOMEM_BKPT SQLITE_NOMEM
+# define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
+#endif
+#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
+SQLITE_PRIVATE int sqlite3CorruptPgnoError(int,Pgno);
+# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
+#else
+# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
+#endif
+
+/*
+** FTS3 and FTS4 both require virtual table support
+*/
+#if defined(SQLITE_OMIT_VIRTUALTABLE)
+# undef SQLITE_ENABLE_FTS3
+# undef SQLITE_ENABLE_FTS4
+#endif
+
+/*
+** FTS4 is really an extension for FTS3. It is enabled using the
+** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
+** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
+*/
+#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
+# define SQLITE_ENABLE_FTS3 1
+#endif
+
+/*
+** The ctype.h header is needed for non-ASCII systems. It is also
+** needed by FTS3 when FTS3 is included in the amalgamation.
+*/
+#if !defined(SQLITE_ASCII) || \
+ (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
+# include <ctype.h>
+#endif
+
+/*
+** The following macros mimic the standard library functions toupper(),
+** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
+** sqlite versions only work for ASCII characters, regardless of locale.
+*/
+#ifdef SQLITE_ASCII
+# define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
+# define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
+# define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
+# define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
+# define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
+# define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
+# define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
+# define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
+#else
+# define sqlite3Toupper(x) toupper((unsigned char)(x))
+# define sqlite3Isspace(x) isspace((unsigned char)(x))
+# define sqlite3Isalnum(x) isalnum((unsigned char)(x))
+# define sqlite3Isalpha(x) isalpha((unsigned char)(x))
+# define sqlite3Isdigit(x) isdigit((unsigned char)(x))
+# define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
+# define sqlite3Tolower(x) tolower((unsigned char)(x))
+# define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
+#endif
+SQLITE_PRIVATE int sqlite3IsIdChar(u8);
+
+/*
+** Internal function prototypes
+*/
+SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
+SQLITE_PRIVATE int sqlite3Strlen30(const char*);
+#define sqlite3Strlen30NN(C) (strlen(C)&0x3fffffff)
+SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
+#define sqlite3StrNICmp sqlite3_strnicmp
+
+SQLITE_PRIVATE int sqlite3MallocInit(void);
+SQLITE_PRIVATE void sqlite3MallocEnd(void);
+SQLITE_PRIVATE void *sqlite3Malloc(u64);
+SQLITE_PRIVATE void *sqlite3MallocZero(u64);
+SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
+SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
+SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
+SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
+SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
+SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
+SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
+SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
+SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
+SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
+SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
+SQLITE_PRIVATE int sqlite3MallocSize(void*);
+SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
+SQLITE_PRIVATE void *sqlite3PageMalloc(int);
+SQLITE_PRIVATE void sqlite3PageFree(void*);
+SQLITE_PRIVATE void sqlite3MemSetDefault(void);
+#ifndef SQLITE_UNTESTABLE
+SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
+#endif
+SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
+
+/*
+** On systems with ample stack space and that support alloca(), make
+** use of alloca() to obtain space for large automatic objects. By default,
+** obtain space from malloc().
+**
+** The alloca() routine never returns NULL. This will cause code paths
+** that deal with sqlite3StackAlloc() failures to be unreachable.
+*/
+#ifdef SQLITE_USE_ALLOCA
+# define sqlite3StackAllocRaw(D,N) alloca(N)
+# define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
+# define sqlite3StackFree(D,P)
+#else
+# define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
+# define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
+# define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
+#endif
+
+/* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
+** are, disable MEMSYS3
+*/
+#ifdef SQLITE_ENABLE_MEMSYS5
+SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
+#undef SQLITE_ENABLE_MEMSYS3
+#endif
+#ifdef SQLITE_ENABLE_MEMSYS3
+SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
+#endif
+
+
+#ifndef SQLITE_MUTEX_OMIT
+SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
+SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
+SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
+SQLITE_PRIVATE int sqlite3MutexInit(void);
+SQLITE_PRIVATE int sqlite3MutexEnd(void);
+#endif
+#if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
+SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
+#else
+# define sqlite3MemoryBarrier()
+#endif
+
+SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
+SQLITE_PRIVATE void sqlite3StatusUp(int, int);
+SQLITE_PRIVATE void sqlite3StatusDown(int, int);
+SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
+SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
+
+/* Access to mutexes used by sqlite3_status() */
+SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
+SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
+
+#if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
+SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*);
+#else
+# define sqlite3MutexWarnOnContention(x)
+#endif
+
+#ifndef SQLITE_OMIT_FLOATING_POINT
+# define EXP754 (((u64)0x7ff)<<52)
+# define MAN754 ((((u64)1)<<52)-1)
+# define IsNaN(X) (((X)&EXP754)==EXP754 && ((X)&MAN754)!=0)
+SQLITE_PRIVATE int sqlite3IsNaN(double);
+#else
+# define IsNaN(X) 0
+# define sqlite3IsNaN(X) 0
+#endif
+
+/*
+** An instance of the following structure holds information about SQL
+** functions arguments that are the parameters to the printf() function.
+*/
+struct PrintfArguments {
+ int nArg; /* Total number of arguments */
+ int nUsed; /* Number of arguments used so far */
+ sqlite3_value **apArg; /* The argument values */
+};
+
+SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
+SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
+#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
+SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
+#endif
+#if defined(SQLITE_TEST)
+SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
+#endif
+
+#if defined(SQLITE_DEBUG)
+SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
+SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
+SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
+SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView*, const SrcList*);
+SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
+SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
+#ifndef SQLITE_OMIT_WINDOWFUNC
+SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView*, const Window*, u8);
+SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);
+#endif
+#endif
+
+
+SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
+SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
+SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3*,int);
+SQLITE_PRIVATE void sqlite3Dequote(char*);
+SQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);
+SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
+SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
+SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
+SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
+SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
+SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
+SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
+SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
+SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
+#endif
+SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
+SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
+SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
+SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
+SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
+SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse*,Expr*, Expr*);
+SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr*);
+SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*, int);
+SQLITE_PRIVATE void sqlite3ExprFunctionUsable(Parse*,Expr*,FuncDef*);
+SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
+SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
+SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse*, Expr*);
+SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
+SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
+SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int,int);
+SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
+SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
+SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
+SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
+SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index*);
+SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
+SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
+SQLITE_PRIVATE int sqlite3InitOne(sqlite3*, int, char**, u32);
+SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
+#endif
+SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
+SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
+SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
+SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
+SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
+SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
+SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*,char);
+SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*,char);
+SQLITE_PRIVATE void sqlite3OpenSchemaTable(Parse *, int);
+SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
+SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index*, i16);
+#ifdef SQLITE_OMIT_GENERATED_COLUMNS
+# define sqlite3TableColumnToStorage(T,X) (X) /* No-op pass-through */
+# define sqlite3StorageColumnToTable(T,X) (X) /* No-op pass-through */
+#else
+SQLITE_PRIVATE i16 sqlite3TableColumnToStorage(Table*, i16);
+SQLITE_PRIVATE i16 sqlite3StorageColumnToTable(Table*, i16);
+#endif
+SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
+#if SQLITE_ENABLE_HIDDEN_COLUMNS
+SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
+#else
+# define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
+#endif
+SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
+SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
+SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
+SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*, const char*, const char*);
+SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
+SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
+SQLITE_PRIVATE void sqlite3AddGenerated(Parse*,Expr*,Token*);
+SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
+SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
+ sqlite3_vfs**,char**,char **);
+#define sqlite3CodecQueryParameters(A,B,C) 0
+SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
+
+#ifdef SQLITE_UNTESTABLE
+# define sqlite3FaultSim(X) SQLITE_OK
+#else
+SQLITE_PRIVATE int sqlite3FaultSim(int);
+#endif
+
+SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
+SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
+SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
+SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
+SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
+SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
+SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
+#ifndef SQLITE_UNTESTABLE
+SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
+#endif
+
+SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*);
+SQLITE_PRIVATE void sqlite3RowSetDelete(void*);
+SQLITE_PRIVATE void sqlite3RowSetClear(void*);
+SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
+SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
+SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
+
+SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
+
+#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
+SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
+#else
+# define sqlite3ViewGetColumnNames(A,B) 0
+#endif
+
+#if SQLITE_MAX_ATTACHED>30
+SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
+#endif
+SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
+SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
+SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
+SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3*, Index*);
+#ifndef SQLITE_OMIT_AUTOINCREMENT
+SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
+SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
+#else
+# define sqlite3AutoincrementBegin(X)
+# define sqlite3AutoincrementEnd(X)
+#endif
+SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+SQLITE_PRIVATE void sqlite3ComputeGeneratedColumns(Parse*, int, Table*);
+#endif
+SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
+SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);
+SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
+SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int);
+SQLITE_PRIVATE SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2);
+SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*);
+SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
+ Token*, Select*, Expr*, IdList*);
+SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
+SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
+SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
+SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
+SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
+SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
+SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
+SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
+SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
+ Expr*, int, int, u8);
+SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
+SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
+SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
+ Expr*,ExprList*,u32,Expr*);
+SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
+SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
+SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
+SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
+#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
+SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
+#endif
+SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
+SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
+ Upsert*);
+SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
+SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
+SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
+SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
+SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
+SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);
+SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
+SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
+SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
+SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
+#define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
+#define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
+#define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
+SQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo*);
+SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
+SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
+SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
+SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
+SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(Parse*, Column*, int);
+#endif
+SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
+SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
+SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int);
+SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
+SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
+SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
+#define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
+#define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
+#define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
+#define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */
+SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
+SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
+SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
+SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
+#define LOCATE_VIEW 0x01
+#define LOCATE_NOERR 0x02
+SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
+SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
+SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
+SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
+SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
+SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*,Expr*);
+SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*);
+SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
+SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
+SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
+SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
+SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
+SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int);
+SQLITE_PRIVATE void sqlite3AggInfoPersistWalkerInit(Walker*,Parse*);
+SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
+SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
+SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
+SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
+SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
+#ifndef SQLITE_UNTESTABLE
+SQLITE_PRIVATE void sqlite3PrngSaveState(void);
+SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
+#endif
+SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
+SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
+SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
+SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
+SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
+SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
+SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
+SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
+SQLITE_PRIVATE u32 sqlite3IsTrueOrFalse(const char*);
+SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);
+SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);
+SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
+SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
+SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
+SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
+SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
+#ifdef SQLITE_ENABLE_CURSOR_HINTS
+SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
+#endif
+SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
+SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
+SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
+SQLITE_PRIVATE int sqlite3IsRowid(const char*);
+SQLITE_PRIVATE void sqlite3GenerateRowDelete(
+ Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
+SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
+SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
+SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
+SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);
+SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
+ u8,u8,int,int*,int*,Upsert*);
+#ifdef SQLITE_ENABLE_NULL_TRIM
+SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe*,Table*);
+#else
+# define sqlite3SetMakeRecordP5(A,B)
+#endif
+SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
+SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
+SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
+SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
+SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
+SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
+SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
+SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
+SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
+SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
+SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
+SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
+SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
+SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(int,const char*);
+SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
+SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
+SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
+SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
+SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
+SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
+SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
+SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
+
+#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
+SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
+#endif
+
+#ifndef SQLITE_OMIT_TRIGGER
+SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
+ Expr*,int, int);
+SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
+SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
+SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
+SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
+SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
+SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
+ int, int, int);
+SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
+ void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
+SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
+SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
+ const char*,const char*);
+SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,
+ Select*,u8,Upsert*,
+ const char*,const char*);
+SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,SrcList*,ExprList*,
+ Expr*, u8, const char*,const char*);
+SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,
+ const char*,const char*);
+SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
+SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
+SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
+SQLITE_PRIVATE SrcList *sqlite3TriggerStepSrc(Parse*, TriggerStep*);
+# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
+# define sqlite3IsToplevel(p) ((p)->pToplevel==0)
+#else
+# define sqlite3TriggersExist(B,C,D,E,F) 0
+# define sqlite3DeleteTrigger(A,B)
+# define sqlite3DropTriggerPtr(A,B)
+# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
+# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
+# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
+# define sqlite3TriggerList(X, Y) 0
+# define sqlite3ParseToplevel(p) p
+# define sqlite3IsToplevel(p) 1
+# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
+# define sqlite3TriggerStepSrc(A,B) 0
+#endif
+
+SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
+SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr*,int);
+SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
+SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
+#ifndef SQLITE_OMIT_AUTHORIZATION
+SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
+SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
+SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
+SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
+SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
+#else
+# define sqlite3AuthRead(a,b,c,d)
+# define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
+# define sqlite3AuthContextPush(a,b,c)
+# define sqlite3AuthContextPop(a) ((void)(a))
+#endif
+SQLITE_PRIVATE int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName);
+SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
+SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
+SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
+SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
+SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
+SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
+SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
+SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
+SQLITE_PRIVATE int sqlite3RealSameAsInt(double,sqlite3_int64);
+SQLITE_PRIVATE void sqlite3Int64ToText(i64,char*);
+SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
+SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
+SQLITE_PRIVATE int sqlite3GetUInt32(const char*, u32*);
+SQLITE_PRIVATE int sqlite3Atoi(const char*);
+#ifndef SQLITE_OMIT_UTF16
+SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
+#endif
+SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
+SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
+SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
+SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
+#endif
+#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
+ defined(SQLITE_ENABLE_STAT4) || \
+ defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
+SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
+#endif
+SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
+SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
+SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
+
+/*
+** Routines to read and write variable-length integers. These used to
+** be defined locally, but now we use the varint routines in the util.c
+** file.
+*/
+SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
+SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
+SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
+SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
+
+/*
+** The common case is for a varint to be a single byte. They following
+** macros handle the common case without a procedure call, but then call
+** the procedure for larger varints.
+*/
+#define getVarint32(A,B) \
+ (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
+#define getVarint32NR(A,B) \
+ B=(u32)*(A);if(B>=0x80)sqlite3GetVarint32((A),(u32*)&(B))
+#define putVarint32(A,B) \
+ (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
+ sqlite3PutVarint((A),(B)))
+#define getVarint sqlite3GetVarint
+#define putVarint sqlite3PutVarint
+
+
+SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
+SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
+SQLITE_PRIVATE char sqlite3CompareAffinity(const Expr *pExpr, char aff2);
+SQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity);
+SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
+SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr);
+SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
+SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
+SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
+SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
+SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
+SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
+SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
+SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
+
+#if defined(SQLITE_NEED_ERR_NAME)
+SQLITE_PRIVATE const char *sqlite3ErrName(int);
+#endif
+
+#ifdef SQLITE_ENABLE_DESERIALIZE
+SQLITE_PRIVATE int sqlite3MemdbInit(void);
+#endif
+
+SQLITE_PRIVATE const char *sqlite3ErrStr(int);
+SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
+SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
+SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq*);
+SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
+SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8);
+SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr);
+SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr);
+SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,const Expr*,const Expr*);
+SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
+SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
+SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
+SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr*);
+SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
+SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);
+SQLITE_PRIVATE int sqlite3CheckObjectName(Parse*, const char*,const char*,const char*);
+SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
+SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
+SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
+SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
+SQLITE_PRIVATE int sqlite3AbsInt32(int);
+#ifdef SQLITE_ENABLE_8_3_NAMES
+SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
+#else
+# define sqlite3FileSuffix3(X,Y)
+#endif
+SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
+
+SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
+SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
+SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
+ void(*)(void*));
+SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
+SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
+#ifndef SQLITE_UNTESTABLE
+SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context*);
+#endif
+SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
+#ifndef SQLITE_OMIT_UTF16
+SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
+#endif
+SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
+SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
+#ifndef SQLITE_AMALGAMATION
+SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
+SQLITE_PRIVATE const char sqlite3StrBINARY[];
+SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
+SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
+SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
+SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
+SQLITE_API extern u32 sqlite3_unsupported_selecttrace;
+#ifndef SQLITE_OMIT_WSD
+SQLITE_PRIVATE int sqlite3PendingByte;
+#endif
+#endif /* SQLITE_AMALGAMATION */
+#ifdef VDBE_PROFILE
+SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt;
+#endif
+SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, Pgno, Pgno);
+SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
+SQLITE_PRIVATE void sqlite3AlterFunctions(void);
+SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
+SQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);
+SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
+SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
+SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);
+SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int);
+SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);
+SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
+SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
+SQLITE_PRIVATE int sqlite3MatchEName(
+ const struct ExprList_item*,
+ const char*,
+ const char*,
+ const char*
+);
+SQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr*);
+SQLITE_PRIVATE u8 sqlite3StrIHash(const char*);
+SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
+SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
+SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
+SQLITE_PRIVATE int sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
+SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
+SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
+SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
+SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
+SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse*, void*, Token*);
+SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse*, void *pTo, void *pFrom);
+SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse*, Expr*);
+SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse*, ExprList*);
+SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
+SQLITE_PRIVATE char sqlite3AffinityType(const char*, Column*);
+SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
+SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
+SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
+SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
+SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
+SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
+SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
+SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
+SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
+SQLITE_PRIVATE void sqlite3SchemaClear(void *);
+SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
+SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
+SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
+SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
+SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
+SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
+SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);
+SQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse*, ExprList*);
+
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
+#endif
+SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
+ void (*)(sqlite3_context*,int,sqlite3_value **),
+ void (*)(sqlite3_context*,int,sqlite3_value **),
+ void (*)(sqlite3_context*),
+ void (*)(sqlite3_context*),
+ void (*)(sqlite3_context*,int,sqlite3_value **),
+ FuncDestructor *pDestructor
+);
+SQLITE_PRIVATE void sqlite3NoopDestructor(void*);
+SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
+SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
+SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
+SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
+
+SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
+SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
+SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
+SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
+
+SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
+SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
+
+#ifndef SQLITE_OMIT_SUBQUERY
+SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
+#else
+# define sqlite3ExprCheckIN(x,y) SQLITE_OK
+#endif
+
+#ifdef SQLITE_ENABLE_STAT4
+SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
+ Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
+SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
+SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
+SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
+SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
+#endif
+
+/*
+** The interface to the LEMON-generated parser
+*/
+#ifndef SQLITE_AMALGAMATION
+SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64), Parse*);
+SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
+#endif
+SQLITE_PRIVATE void sqlite3Parser(void*, int, Token);
+SQLITE_PRIVATE int sqlite3ParserFallback(int);
+#ifdef YYTRACKMAXSTACKDEPTH
+SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
+#endif
+
+SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
+#ifndef SQLITE_OMIT_LOAD_EXTENSION
+SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
+#else
+# define sqlite3CloseExtensions(X)
+#endif
+
+#ifndef SQLITE_OMIT_SHARED_CACHE
+SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, Pgno, u8, const char *);
+#else
+ #define sqlite3TableLock(v,w,x,y,z)
+#endif
+
+#ifdef SQLITE_TEST
+SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
+#endif
+
+#ifdef SQLITE_OMIT_VIRTUALTABLE
+# define sqlite3VtabClear(Y)
+# define sqlite3VtabSync(X,Y) SQLITE_OK
+# define sqlite3VtabRollback(X)
+# define sqlite3VtabCommit(X)
+# define sqlite3VtabInSync(db) 0
+# define sqlite3VtabLock(X)
+# define sqlite3VtabUnlock(X)
+# define sqlite3VtabModuleUnref(D,X)
+# define sqlite3VtabUnlockList(X)
+# define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
+# define sqlite3GetVTable(X,Y) ((VTable*)0)
+#else
+SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
+SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
+SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
+SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
+SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
+SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
+SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
+SQLITE_PRIVATE void sqlite3VtabModuleUnref(sqlite3*,Module*);
+SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
+SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
+SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
+SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
+SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
+ sqlite3*,
+ const char*,
+ const sqlite3_module*,
+ void*,
+ void(*)(void*)
+ );
+# define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
+#endif
+SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db);
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName);
+SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*);
+#else
+# define sqlite3ShadowTableName(A,B) 0
+# define sqlite3IsShadowTableOf(A,B,C) 0
+#endif
+SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
+SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
+SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
+SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
+SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
+SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
+SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
+SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
+SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
+SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
+SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
+SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
+SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
+SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
+SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
+SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
+#ifdef SQLITE_ENABLE_NORMALIZE
+SQLITE_PRIVATE char *sqlite3Normalize(Vdbe*, const char*);
+#endif
+SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
+SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
+SQLITE_PRIVATE CollSeq *sqlite3ExprCompareCollSeq(Parse*,const Expr*);
+SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, const Expr*, const Expr*);
+SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
+SQLITE_PRIVATE const char *sqlite3JournalModename(int);
+#ifndef SQLITE_OMIT_WAL
+SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
+SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
+#endif
+#ifndef SQLITE_OMIT_CTE
+SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
+SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
+SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
+#else
+#define sqlite3WithPush(x,y,z)
+#define sqlite3WithDelete(x,y)
+#endif
+#ifndef SQLITE_OMIT_UPSERT
+SQLITE_PRIVATE Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*);
+SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3*,Upsert*);
+SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);
+SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*);
+SQLITE_PRIVATE void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);
+#else
+#define sqlite3UpsertNew(v,w,x,y,z) ((Upsert*)0)
+#define sqlite3UpsertDelete(x,y)
+#define sqlite3UpsertDup(x,y) ((Upsert*)0)
+#endif
+
+
+/* Declarations for functions in fkey.c. All of these are replaced by
+** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
+** key functionality is available. If OMIT_TRIGGER is defined but
+** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
+** this case foreign keys are parsed, but no other functionality is
+** provided (enforcement of FK constraints requires the triggers sub-system).
+*/
+#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
+SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
+SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
+SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
+SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
+SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
+SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
+#else
+ #define sqlite3FkActions(a,b,c,d,e,f)
+ #define sqlite3FkCheck(a,b,c,d,e,f)
+ #define sqlite3FkDropTable(a,b,c)
+ #define sqlite3FkOldmask(a,b) 0
+ #define sqlite3FkRequired(a,b,c,d) 0
+ #define sqlite3FkReferences(a) 0
+#endif
+#ifndef SQLITE_OMIT_FOREIGN_KEY
+SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
+SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
+#else
+ #define sqlite3FkDelete(a,b)
+ #define sqlite3FkLocateIndex(a,b,c,d,e)
+#endif
+
+
+/*
+** Available fault injectors. Should be numbered beginning with 0.
+*/
+#define SQLITE_FAULTINJECTOR_MALLOC 0
+#define SQLITE_FAULTINJECTOR_COUNT 1
+
+/*
+** The interface to the code in fault.c used for identifying "benign"
+** malloc failures. This is only present if SQLITE_UNTESTABLE
+** is not defined.
+*/
+#ifndef SQLITE_UNTESTABLE
+SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
+SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
+#else
+ #define sqlite3BeginBenignMalloc()
+ #define sqlite3EndBenignMalloc()
+#endif
+
+/*
+** Allowed return values from sqlite3FindInIndex()
+*/
+#define IN_INDEX_ROWID 1 /* Search the rowid of the table */
+#define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
+#define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
+#define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
+#define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
+/*
+** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
+*/
+#define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
+#define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
+#define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
+SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*);
+
+SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
+SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
+#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
+ || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
+SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
+#endif
+
+SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
+SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
+
+SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
+#if SQLITE_MAX_EXPR_DEPTH>0
+SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
+SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
+#else
+ #define sqlite3SelectExprHeight(x) 0
+ #define sqlite3ExprCheckHeight(x,y)
+#endif
+
+SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
+SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
+
+#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
+SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
+SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
+SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
+#else
+ #define sqlite3ConnectionBlocked(x,y)
+ #define sqlite3ConnectionUnlocked(x)
+ #define sqlite3ConnectionClosed(x)
+#endif
+
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
+#endif
+#if defined(YYCOVERAGE)
+SQLITE_PRIVATE int sqlite3ParserCoverage(FILE*);
+#endif
+
+/*
+** If the SQLITE_ENABLE IOTRACE exists then the global variable
+** sqlite3IoTrace is a pointer to a printf-like routine used to
+** print I/O tracing messages.
+*/
+#ifdef SQLITE_ENABLE_IOTRACE
+# define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
+SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
+SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
+#else
+# define IOTRACE(A)
+# define sqlite3VdbeIOTraceSql(X)
+#endif
+
+/*
+** These routines are available for the mem2.c debugging memory allocator
+** only. They are used to verify that different "types" of memory
+** allocations are properly tracked by the system.
+**
+** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
+** the MEMTYPE_* macros defined below. The type must be a bitmask with
+** a single bit set.
+**
+** sqlite3MemdebugHasType() returns true if any of the bits in its second
+** argument match the type set by the previous sqlite3MemdebugSetType().
+** sqlite3MemdebugHasType() is intended for use inside assert() statements.
+**
+** sqlite3MemdebugNoType() returns true if none of the bits in its second
+** argument match the type set by the previous sqlite3MemdebugSetType().
+**
+** Perhaps the most important point is the difference between MEMTYPE_HEAP
+** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
+** it might have been allocated by lookaside, except the allocation was
+** too large or lookaside was already full. It is important to verify
+** that allocations that might have been satisfied by lookaside are not
+** passed back to non-lookaside free() routines. Asserts such as the
+** example above are placed on the non-lookaside free() routines to verify
+** this constraint.
+**
+** All of this is no-op for a production build. It only comes into
+** play when the SQLITE_MEMDEBUG compile-time option is used.
+*/
+#ifdef SQLITE_MEMDEBUG
+SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
+SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
+SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
+#else
+# define sqlite3MemdebugSetType(X,Y) /* no-op */
+# define sqlite3MemdebugHasType(X,Y) 1
+# define sqlite3MemdebugNoType(X,Y) 1
+#endif
+#define MEMTYPE_HEAP 0x01 /* General heap allocations */
+#define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
+#define MEMTYPE_PCACHE 0x04 /* Page cache allocations */
+
+/*
+** Threading interface
+*/
+#if SQLITE_MAX_WORKER_THREADS>0
+SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
+SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
+#endif
+
+#if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
+SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
+#endif
+#if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
+SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
+#endif
+
+SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
+SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
+SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
+SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
+SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
+
+#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
+SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
+#endif
+
+#endif /* SQLITEINT_H */
+
+/************** End of sqliteInt.h *******************************************/
+/************** Begin file global.c ******************************************/
+/*
+** 2008 June 13
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains definitions of global variables and constants.
+*/
+/* #include "sqliteInt.h" */
+
+/* An array to map all upper-case characters into their corresponding
+** lower-case character.
+**
+** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
+** handle case conversions for the UTF character set since the tables
+** involved are nearly as big or bigger than SQLite itself.
+*/
+SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
+#ifdef SQLITE_ASCII
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
+ 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
+ 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
+ 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
+ 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
+ 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
+ 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
+ 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
+ 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
+ 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
+ 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
+ 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
+ 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
+ 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
+ 252,253,254,255
+#endif
+#ifdef SQLITE_EBCDIC
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
+ 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
+ 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
+ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
+ 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
+ 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
+ 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
+ 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
+ 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
+ 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
+ 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
+ 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
+ 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
+ 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
+ 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
+ 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
+#endif
+};
+
+/*
+** The following 256 byte lookup table is used to support SQLites built-in
+** equivalents to the following standard library functions:
+**
+** isspace() 0x01
+** isalpha() 0x02
+** isdigit() 0x04
+** isalnum() 0x06
+** isxdigit() 0x08
+** toupper() 0x20
+** SQLite identifier character 0x40
+** Quote character 0x80
+**
+** Bit 0x20 is set if the mapped character requires translation to upper
+** case. i.e. if the character is a lower-case ASCII character.
+** If x is a lower-case ASCII character, then its upper-case equivalent
+** is (x - 0x20). Therefore toupper() can be implemented as:
+**
+** (x & ~(map[x]&0x20))
+**
+** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
+** array. tolower() is used more often than toupper() by SQLite.
+**
+** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
+** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
+** non-ASCII UTF character. Hence the test for whether or not a character is
+** part of an identifier is 0x46.
+*/
+SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
+ 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
+ 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
+ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
+ 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
+
+ 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
+ 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
+ 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
+ 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
+ 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
+ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
+ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
+ 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
+
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
+
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
+};
+
+/* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
+** compatibility for legacy applications, the URI filename capability is
+** disabled by default.
+**
+** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
+** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
+**
+** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
+** disabled. The default value may be changed by compiling with the
+** SQLITE_USE_URI symbol defined.
+*/
+#ifndef SQLITE_USE_URI
+# define SQLITE_USE_URI 0
+#endif
+
+/* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
+** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
+** that compile-time option is omitted.
+*/
+#if !defined(SQLITE_ALLOW_COVERING_INDEX_SCAN)
+# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
+#else
+# if !SQLITE_ALLOW_COVERING_INDEX_SCAN
+# error "Compile-time disabling of covering index scan using the\
+ -DSQLITE_ALLOW_COVERING_INDEX_SCAN=0 option is deprecated.\
+ Contact SQLite developers if this is a problem for you, and\
+ delete this #error macro to continue with your build."
+# endif
+#endif
+
+/* The minimum PMA size is set to this value multiplied by the database
+** page size in bytes.
+*/
+#ifndef SQLITE_SORTER_PMASZ
+# define SQLITE_SORTER_PMASZ 250
+#endif
+
+/* Statement journals spill to disk when their size exceeds the following
+** threshold (in bytes). 0 means that statement journals are created and
+** written to disk immediately (the default behavior for SQLite versions
+** before 3.12.0). -1 means always keep the entire statement journal in
+** memory. (The statement journal is also always held entirely in memory
+** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
+** setting.)
+*/
+#ifndef SQLITE_STMTJRNL_SPILL
+# define SQLITE_STMTJRNL_SPILL (64*1024)
+#endif
+
+/*
+** The default lookaside-configuration, the format "SZ,N". SZ is the
+** number of bytes in each lookaside slot (should be a multiple of 8)
+** and N is the number of slots. The lookaside-configuration can be
+** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
+** or at run-time for an individual database connection using
+** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
+**
+** With the two-size-lookaside enhancement, less lookaside is required.
+** The default configuration of 1200,40 actually provides 30 1200-byte slots
+** and 93 128-byte slots, which is more lookaside than is available
+** using the older 1200,100 configuration without two-size-lookaside.
+*/
+#ifndef SQLITE_DEFAULT_LOOKASIDE
+# ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+# define SQLITE_DEFAULT_LOOKASIDE 1200,100 /* 120KB of memory */
+# else
+# define SQLITE_DEFAULT_LOOKASIDE 1200,40 /* 48KB of memory */
+# endif
+#endif
+
+
+/* The default maximum size of an in-memory database created using
+** sqlite3_deserialize()
+*/
+#ifndef SQLITE_MEMDB_DEFAULT_MAXSIZE
+# define SQLITE_MEMDB_DEFAULT_MAXSIZE 1073741824
+#endif
+
+/*
+** The following singleton contains the global configuration for
+** the SQLite library.
+*/
+SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
+ SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
+ 1, /* bCoreMutex */
+ SQLITE_THREADSAFE==1, /* bFullMutex */
+ SQLITE_USE_URI, /* bOpenUri */
+ SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
+ 0, /* bSmallMalloc */
+ 1, /* bExtraSchemaChecks */
+ 0x7ffffffe, /* mxStrlen */
+ 0, /* neverCorrupt */
+ SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */
+ SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
+ {0,0,0,0,0,0,0,0}, /* m */
+ {0,0,0,0,0,0,0,0,0}, /* mutex */
+ {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
+ (void*)0, /* pHeap */
+ 0, /* nHeap */
+ 0, 0, /* mnHeap, mxHeap */
+ SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
+ SQLITE_MAX_MMAP_SIZE, /* mxMmap */
+ (void*)0, /* pPage */
+ 0, /* szPage */
+ SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
+ 0, /* mxParserStack */
+ 0, /* sharedCacheEnabled */
+ SQLITE_SORTER_PMASZ, /* szPma */
+ /* All the rest should always be initialized to zero */
+ 0, /* isInit */
+ 0, /* inProgress */
+ 0, /* isMutexInit */
+ 0, /* isMallocInit */
+ 0, /* isPCacheInit */
+ 0, /* nRefInitMutex */
+ 0, /* pInitMutex */
+ 0, /* xLog */
+ 0, /* pLogArg */
+#ifdef SQLITE_ENABLE_SQLLOG
+ 0, /* xSqllog */
+ 0, /* pSqllogArg */
+#endif
+#ifdef SQLITE_VDBE_COVERAGE
+ 0, /* xVdbeBranch */
+ 0, /* pVbeBranchArg */
+#endif
+#ifdef SQLITE_ENABLE_DESERIALIZE
+ SQLITE_MEMDB_DEFAULT_MAXSIZE, /* mxMemdbSize */
+#endif
+#ifndef SQLITE_UNTESTABLE
+ 0, /* xTestCallback */
+#endif
+ 0, /* bLocaltimeFault */
+ 0x7ffffffe, /* iOnceResetThreshold */
+ SQLITE_DEFAULT_SORTERREF_SIZE, /* szSorterRef */
+ 0, /* iPrngSeed */
+};
+
+/*
+** Hash table for global functions - functions common to all
+** database connections. After initialization, this table is
+** read-only.
+*/
+SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
+
+#ifdef VDBE_PROFILE
+/*
+** The following performance counter can be used in place of
+** sqlite3Hwtime() for profiling. This is a no-op on standard builds.
+*/
+SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt = 0;
+#endif
+
+/*
+** The value of the "pending" byte must be 0x40000000 (1 byte past the
+** 1-gibabyte boundary) in a compatible database. SQLite never uses
+** the database page that contains the pending byte. It never attempts
+** to read or write that page. The pending byte page is set aside
+** for use by the VFS layers as space for managing file locks.
+**
+** During testing, it is often desirable to move the pending byte to
+** a different position in the file. This allows code that has to
+** deal with the pending byte to run on files that are much smaller
+** than 1 GiB. The sqlite3_test_control() interface can be used to
+** move the pending byte.
+**
+** IMPORTANT: Changing the pending byte to any value other than
+** 0x40000000 results in an incompatible database file format!
+** Changing the pending byte during operation will result in undefined
+** and incorrect behavior.
+*/
+#ifndef SQLITE_OMIT_WSD
+SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
+#endif
+
+/*
+** Flags for select tracing and the ".selecttrace" macro of the CLI
+*/
+SQLITE_API u32 sqlite3_unsupported_selecttrace = 0;
+
+/* #include "opcodes.h" */
+/*
+** Properties of opcodes. The OPFLG_INITIALIZER macro is
+** created by mkopcodeh.awk during compilation. Data is obtained
+** from the comments following the "case OP_xxxx:" statements in
+** the vdbe.c file.
+*/
+SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
+
+/*
+** Name of the default collating sequence
+*/
+SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
+
+/************** End of global.c **********************************************/
+/************** Begin file status.c ******************************************/
+/*
+** 2008 June 18
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This module implements the sqlite3_status() interface and related
+** functionality.
+*/
+/* #include "sqliteInt.h" */
+/************** Include vdbeInt.h in the middle of status.c ******************/
+/************** Begin file vdbeInt.h *****************************************/
+/*
+** 2003 September 6
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This is the header file for information that is private to the
+** VDBE. This information used to all be at the top of the single
+** source code file "vdbe.c". When that file became too big (over
+** 6000 lines long) it was split up into several smaller files and
+** this header information was factored out.
+*/
+#ifndef SQLITE_VDBEINT_H
+#define SQLITE_VDBEINT_H
+
+/*
+** The maximum number of times that a statement will try to reparse
+** itself before giving up and returning SQLITE_SCHEMA.
+*/
+#ifndef SQLITE_MAX_SCHEMA_RETRY
+# define SQLITE_MAX_SCHEMA_RETRY 50
+#endif
+
+/*
+** VDBE_DISPLAY_P4 is true or false depending on whether or not the
+** "explain" P4 display logic is enabled.
+*/
+#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
+ || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) \
+ || defined(SQLITE_ENABLE_BYTECODE_VTAB)
+# define VDBE_DISPLAY_P4 1
+#else
+# define VDBE_DISPLAY_P4 0
+#endif
+
+/*
+** SQL is translated into a sequence of instructions to be
+** executed by a virtual machine. Each instruction is an instance
+** of the following structure.
+*/
+typedef struct VdbeOp Op;
+
+/*
+** Boolean values
+*/
+typedef unsigned Bool;
+
+/* Opaque type used by code in vdbesort.c */
+typedef struct VdbeSorter VdbeSorter;
+
+/* Elements of the linked list at Vdbe.pAuxData */
+typedef struct AuxData AuxData;
+
+/* Types of VDBE cursors */
+#define CURTYPE_BTREE 0
+#define CURTYPE_SORTER 1
+#define CURTYPE_VTAB 2
+#define CURTYPE_PSEUDO 3
+
+/*
+** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
+**
+** * A b-tree cursor
+** - In the main database or in an ephemeral database
+** - On either an index or a table
+** * A sorter
+** * A virtual table
+** * A one-row "pseudotable" stored in a single register
+*/
+typedef struct VdbeCursor VdbeCursor;
+struct VdbeCursor {
+ u8 eCurType; /* One of the CURTYPE_* values above */
+ i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
+ u8 nullRow; /* True if pointing to a row with no data */
+ u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
+ u8 isTable; /* True for rowid tables. False for indexes */
+#ifdef SQLITE_DEBUG
+ u8 seekOp; /* Most recent seek operation on this cursor */
+ u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
+#endif
+ Bool isEphemeral:1; /* True for an ephemeral table */
+ Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
+ Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
+ u16 seekHit; /* See the OP_SeekHit and OP_IfNoHope opcodes */
+ Btree *pBtx; /* Separate file holding temporary table */
+ i64 seqCount; /* Sequence counter */
+ u32 *aAltMap; /* Mapping from table to index column numbers */
+
+ /* Cached OP_Column parse information is only valid if cacheStatus matches
+ ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
+ ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
+ ** the cache is out of date. */
+ u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
+ int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0
+ ** if there have been no prior seeks on the cursor. */
+ /* seekResult does not distinguish between "no seeks have ever occurred
+ ** on this cursor" and "the most recent seek was an exact match".
+ ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
+
+ /* When a new VdbeCursor is allocated, only the fields above are zeroed.
+ ** The fields that follow are uninitialized, and must be individually
+ ** initialized prior to first use. */
+ VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
+ union {
+ BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */
+ sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
+ VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
+ } uc;
+ KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
+ u32 iHdrOffset; /* Offset to next unparsed byte of the header */
+ Pgno pgnoRoot; /* Root page of the open btree cursor */
+ i16 nField; /* Number of fields in the header */
+ u16 nHdrParsed; /* Number of header fields parsed so far */
+ i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
+ u32 *aOffset; /* Pointer to aType[nField] */
+ const u8 *aRow; /* Data for the current row, if all on one page */
+ u32 payloadSize; /* Total number of bytes in the record */
+ u32 szRow; /* Byte available in aRow */
+#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
+ u64 maskUsed; /* Mask of columns used by this cursor */
+#endif
+
+ /* 2*nField extra array elements allocated for aType[], beyond the one
+ ** static element declared in the structure. nField total array slots for
+ ** aType[] and nField+1 array slots for aOffset[] */
+ u32 aType[1]; /* Type values record decode. MUST BE LAST */
+};
+
+
+/*
+** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
+*/
+#define CACHE_STALE 0
+
+/*
+** When a sub-program is executed (OP_Program), a structure of this type
+** is allocated to store the current value of the program counter, as
+** well as the current memory cell array and various other frame specific
+** values stored in the Vdbe struct. When the sub-program is finished,
+** these values are copied back to the Vdbe from the VdbeFrame structure,
+** restoring the state of the VM to as it was before the sub-program
+** began executing.
+**
+** The memory for a VdbeFrame object is allocated and managed by a memory
+** cell in the parent (calling) frame. When the memory cell is deleted or
+** overwritten, the VdbeFrame object is not freed immediately. Instead, it
+** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
+** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
+** this instead of deleting the VdbeFrame immediately is to avoid recursive
+** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
+** child frame are released.
+**
+** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
+** set to NULL if the currently executing frame is the main program.
+*/
+typedef struct VdbeFrame VdbeFrame;
+struct VdbeFrame {
+ Vdbe *v; /* VM this frame belongs to */
+ VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
+ Op *aOp; /* Program instructions for parent frame */
+ i64 *anExec; /* Event counters from parent frame */
+ Mem *aMem; /* Array of memory cells for parent frame */
+ VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
+ u8 *aOnce; /* Bitmask used by OP_Once */
+ void *token; /* Copy of SubProgram.token */
+ i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
+ AuxData *pAuxData; /* Linked list of auxdata allocations */
+#if SQLITE_DEBUG
+ u32 iFrameMagic; /* magic number for sanity checking */
+#endif
+ int nCursor; /* Number of entries in apCsr */
+ int pc; /* Program Counter in parent (calling) frame */
+ int nOp; /* Size of aOp array */
+ int nMem; /* Number of entries in aMem */
+ int nChildMem; /* Number of memory cells for child frame */
+ int nChildCsr; /* Number of cursors for child frame */
+ int nChange; /* Statement changes (Vdbe.nChange) */
+ int nDbChange; /* Value of db->nChange */
+};
+
+/* Magic number for sanity checking on VdbeFrame objects */
+#define SQLITE_FRAME_MAGIC 0x879fb71e
+
+/*
+** Return a pointer to the array of registers allocated for use
+** by a VdbeFrame.
+*/
+#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
+
+/*
+** Internally, the vdbe manipulates nearly all SQL values as Mem
+** structures. Each Mem struct may cache multiple representations (string,
+** integer etc.) of the same value.
+*/
+struct sqlite3_value {
+ union MemValue {
+ double r; /* Real value used when MEM_Real is set in flags */
+ i64 i; /* Integer value used when MEM_Int is set in flags */
+ int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */
+ const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
+ FuncDef *pDef; /* Used only when flags==MEM_Agg */
+ } u;
+ u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
+ u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
+ u8 eSubtype; /* Subtype for this value */
+ int n; /* Number of characters in string value, excluding '\0' */
+ char *z; /* String or BLOB value */
+ /* ShallowCopy only needs to copy the information above */
+ char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
+ int szMalloc; /* Size of the zMalloc allocation */
+ u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
+ sqlite3 *db; /* The associated database connection */
+ void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
+#ifdef SQLITE_DEBUG
+ Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
+ u16 mScopyFlags; /* flags value immediately after the shallow copy */
+#endif
+};
+
+/*
+** Size of struct Mem not including the Mem.zMalloc member or anything that
+** follows.
+*/
+#define MEMCELLSIZE offsetof(Mem,zMalloc)
+
+/* One or more of the following flags are set to indicate the validOK
+** representations of the value stored in the Mem struct.
+**
+** If the MEM_Null flag is set, then the value is an SQL NULL value.
+** For a pointer type created using sqlite3_bind_pointer() or
+** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
+**
+** If the MEM_Str flag is set then Mem.z points at a string representation.
+** Usually this is encoded in the same unicode encoding as the main
+** database (see below for exceptions). If the MEM_Term flag is also
+** set, then the string is nul terminated. The MEM_Int and MEM_Real
+** flags may coexist with the MEM_Str flag.
+*/
+#define MEM_Null 0x0001 /* Value is NULL (or a pointer) */
+#define MEM_Str 0x0002 /* Value is a string */
+#define MEM_Int 0x0004 /* Value is an integer */
+#define MEM_Real 0x0008 /* Value is a real number */
+#define MEM_Blob 0x0010 /* Value is a BLOB */
+#define MEM_IntReal 0x0020 /* MEM_Int that stringifies like MEM_Real */
+#define MEM_AffMask 0x003f /* Mask of affinity bits */
+#define MEM_FromBind 0x0040 /* Value originates from sqlite3_bind() */
+#define MEM_Undefined 0x0080 /* Value is undefined */
+#define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
+#define MEM_TypeMask 0xc1bf /* Mask of type bits */
+
+
+/* Whenever Mem contains a valid string or blob representation, one of
+** the following flags must be set to determine the memory management
+** policy for Mem.z. The MEM_Term flag tells us whether or not the
+** string is \000 or \u0000 terminated
+*/
+#define MEM_Term 0x0200 /* String in Mem.z is zero terminated */
+#define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
+#define MEM_Static 0x0800 /* Mem.z points to a static string */
+#define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
+#define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
+#define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
+#define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
+#ifdef SQLITE_OMIT_INCRBLOB
+ #undef MEM_Zero
+ #define MEM_Zero 0x0000
+#endif
+
+/* Return TRUE if Mem X contains dynamically allocated content - anything
+** that needs to be deallocated to avoid a leak.
+*/
+#define VdbeMemDynamic(X) \
+ (((X)->flags&(MEM_Agg|MEM_Dyn))!=0)
+
+/*
+** Clear any existing type flags from a Mem and replace them with f
+*/
+#define MemSetTypeFlag(p, f) \
+ ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
+
+/*
+** True if Mem X is a NULL-nochng type.
+*/
+#define MemNullNochng(X) \
+ (((X)->flags&MEM_TypeMask)==(MEM_Null|MEM_Zero) \
+ && (X)->n==0 && (X)->u.nZero==0)
+
+/*
+** Return true if a memory cell is not marked as invalid. This macro
+** is for use inside assert() statements only.
+*/
+#ifdef SQLITE_DEBUG
+#define memIsValid(M) ((M)->flags & MEM_Undefined)==0
+#endif
+
+/*
+** Each auxiliary data pointer stored by a user defined function
+** implementation calling sqlite3_set_auxdata() is stored in an instance
+** of this structure. All such structures associated with a single VM
+** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
+** when the VM is halted (if not before).
+*/
+struct AuxData {
+ int iAuxOp; /* Instruction number of OP_Function opcode */
+ int iAuxArg; /* Index of function argument. */
+ void *pAux; /* Aux data pointer */
+ void (*xDeleteAux)(void*); /* Destructor for the aux data */
+ AuxData *pNextAux; /* Next element in list */
+};
+
+/*
+** The "context" argument for an installable function. A pointer to an
+** instance of this structure is the first argument to the routines used
+** implement the SQL functions.
+**
+** There is a typedef for this structure in sqlite.h. So all routines,
+** even the public interface to SQLite, can use a pointer to this structure.
+** But this file is the only place where the internal details of this
+** structure are known.
+**
+** This structure is defined inside of vdbeInt.h because it uses substructures
+** (Mem) which are only defined there.
+*/
+struct sqlite3_context {
+ Mem *pOut; /* The return value is stored here */
+ FuncDef *pFunc; /* Pointer to function information */
+ Mem *pMem; /* Memory cell used to store aggregate context */
+ Vdbe *pVdbe; /* The VM that owns this context */
+ int iOp; /* Instruction number of OP_Function */
+ int isError; /* Error code returned by the function. */
+ u8 skipFlag; /* Skip accumulator loading if true */
+ u8 argc; /* Number of arguments */
+ sqlite3_value *argv[1]; /* Argument set */
+};
+
+/* A bitfield type for use inside of structures. Always follow with :N where
+** N is the number of bits.
+*/
+typedef unsigned bft; /* Bit Field Type */
+
+/* The ScanStatus object holds a single value for the
+** sqlite3_stmt_scanstatus() interface.
+*/
+typedef struct ScanStatus ScanStatus;
+struct ScanStatus {
+ int addrExplain; /* OP_Explain for loop */
+ int addrLoop; /* Address of "loops" counter */
+ int addrVisit; /* Address of "rows visited" counter */
+ int iSelectID; /* The "Select-ID" for this loop */
+ LogEst nEst; /* Estimated output rows per loop */
+ char *zName; /* Name of table or index */
+};
+
+/* The DblquoteStr object holds the text of a double-quoted
+** string for a prepared statement. A linked list of these objects
+** is constructed during statement parsing and is held on Vdbe.pDblStr.
+** When computing a normalized SQL statement for an SQL statement, that
+** list is consulted for each double-quoted identifier to see if the
+** identifier should really be a string literal.
+*/
+typedef struct DblquoteStr DblquoteStr;
+struct DblquoteStr {
+ DblquoteStr *pNextStr; /* Next string literal in the list */
+ char z[8]; /* Dequoted value for the string */
+};
+
+/*
+** An instance of the virtual machine. This structure contains the complete
+** state of the virtual machine.
+**
+** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
+** is really a pointer to an instance of this structure.
+*/
+struct Vdbe {
+ sqlite3 *db; /* The database connection that owns this statement */
+ Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
+ Parse *pParse; /* Parsing context used to create this Vdbe */
+ ynVar nVar; /* Number of entries in aVar[] */
+ u32 magic; /* Magic number for sanity checking */
+ int nMem; /* Number of memory locations currently allocated */
+ int nCursor; /* Number of slots in apCsr[] */
+ u32 cacheCtr; /* VdbeCursor row cache generation counter */
+ int pc; /* The program counter */
+ int rc; /* Value to return */
+ int nChange; /* Number of db changes made since last reset */
+ int iStatement; /* Statement number (or 0 if has no opened stmt) */
+ i64 iCurrentTime; /* Value of julianday('now') for this statement */
+ i64 nFkConstraint; /* Number of imm. FK constraints this VM */
+ i64 nStmtDefCons; /* Number of def. constraints when stmt started */
+ i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
+ Mem *aMem; /* The memory locations */
+ Mem **apArg; /* Arguments to currently executing user function */
+ VdbeCursor **apCsr; /* One element of this array for each open cursor */
+ Mem *aVar; /* Values for the OP_Variable opcode. */
+
+ /* When allocating a new Vdbe object, all of the fields below should be
+ ** initialized to zero or NULL */
+
+ Op *aOp; /* Space to hold the virtual machine's program */
+ int nOp; /* Number of instructions in the program */
+ int nOpAlloc; /* Slots allocated for aOp[] */
+ Mem *aColName; /* Column names to return */
+ Mem *pResultSet; /* Pointer to an array of results */
+ char *zErrMsg; /* Error message written here */
+ VList *pVList; /* Name of variables */
+#ifndef SQLITE_OMIT_TRACE
+ i64 startTime; /* Time when query started - used for profiling */
+#endif
+#ifdef SQLITE_DEBUG
+ int rcApp; /* errcode set by sqlite3_result_error_code() */
+ u32 nWrite; /* Number of write operations that have occurred */
+#endif
+ u16 nResColumn; /* Number of columns in one row of the result set */
+ u8 errorAction; /* Recovery action to do in case of an error */
+ u8 minWriteFileFormat; /* Minimum file format for writable database files */
+ u8 prepFlags; /* SQLITE_PREPARE_* flags */
+ u8 doingRerun; /* True if rerunning after an auto-reprepare */
+ bft expired:2; /* 1: recompile VM immediately 2: when convenient */
+ bft explain:2; /* True if EXPLAIN present on SQL command */
+ bft changeCntOn:1; /* True to update the change-counter */
+ bft runOnlyOnce:1; /* Automatically expire on reset */
+ bft usesStmtJournal:1; /* True if uses a statement journal */
+ bft readOnly:1; /* True for statements that do not write */
+ bft bIsReader:1; /* True for statements that read */
+ yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
+ yDbMask lockMask; /* Subset of btreeMask that requires a lock */
+ u32 aCounter[7]; /* Counters used by sqlite3_stmt_status() */
+ char *zSql; /* Text of the SQL statement that generated this */
+#ifdef SQLITE_ENABLE_NORMALIZE
+ char *zNormSql; /* Normalization of the associated SQL statement */
+ DblquoteStr *pDblStr; /* List of double-quoted string literals */
+#endif
+ void *pFree; /* Free this when deleting the vdbe */
+ VdbeFrame *pFrame; /* Parent frame */
+ VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
+ int nFrame; /* Number of frames in pFrame list */
+ u32 expmask; /* Binding to these vars invalidates VM */
+ SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
+ AuxData *pAuxData; /* Linked list of auxdata allocations */
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+ i64 *anExec; /* Number of times each op has been executed */
+ int nScan; /* Entries in aScan[] */
+ ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
+#endif
+};
+
+/*
+** The following are allowed values for Vdbe.magic
+*/
+#define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
+#define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
+#define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
+#define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
+#define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
+
+/*
+** Structure used to store the context required by the
+** sqlite3_preupdate_*() API functions.
+*/
+struct PreUpdate {
+ Vdbe *v;
+ VdbeCursor *pCsr; /* Cursor to read old values from */
+ int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
+ u8 *aRecord; /* old.* database record */
+ KeyInfo keyinfo;
+ UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
+ UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
+ int iNewReg; /* Register for new.* values */
+ i64 iKey1; /* First key value passed to hook */
+ i64 iKey2; /* Second key value passed to hook */
+ Mem *aNew; /* Array of new.* values */
+ Table *pTab; /* Schema object being upated */
+ Index *pPk; /* PK index if pTab is WITHOUT ROWID */
+};
+
+/*
+** Function prototypes
+*/
+SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
+SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
+void sqliteVdbePopStack(Vdbe*,int);
+SQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor*);
+SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, u32*);
+SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
+SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
+SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
+SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
+SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
+SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
+
+int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
+SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
+SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
+SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
+#if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB)
+SQLITE_PRIVATE int sqlite3VdbeNextOpcode(Vdbe*,Mem*,int,int*,int*,Op**);
+SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3*,Op*);
+#endif
+#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
+SQLITE_PRIVATE char *sqlite3VdbeDisplayComment(sqlite3*,const Op*,const char*);
+#endif
+#if !defined(SQLITE_OMIT_EXPLAIN)
+SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
+#endif
+SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
+SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
+SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
+SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
+SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
+SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
+SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
+SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
+SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
+#ifdef SQLITE_OMIT_FLOATING_POINT
+# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
+#else
+SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
+#endif
+SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
+SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
+SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
+SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem*);
+#endif
+SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem*);
+SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
+SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
+SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
+SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
+SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
+SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull);
+SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
+SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
+SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
+SQLITE_PRIVATE int sqlite3VdbeMemCast(Mem*,u8,u8);
+SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
+SQLITE_PRIVATE int sqlite3VdbeMemFromBtreeZeroOffset(BtCursor*,u32,Mem*);
+SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
+SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
+#ifndef SQLITE_OMIT_WINDOWFUNC
+SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*);
+#endif
+#if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB)
+SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
+#endif
+SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
+SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
+SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame*);
+#endif
+SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void*); /* Destructor on Mem */
+SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); /* Actually deletes the Frame */
+SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
+#endif
+SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
+
+SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
+SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
+SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
+SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
+SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
+SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
+SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
+SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
+
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*);
+SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe*);
+#else
+# define sqlite3VdbeIncrWriteCounter(V,C)
+# define sqlite3VdbeAssertAbortable(V)
+#endif
+
+#if !defined(SQLITE_OMIT_SHARED_CACHE)
+SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
+#else
+# define sqlite3VdbeEnter(X)
+#endif
+
+#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
+SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
+#else
+# define sqlite3VdbeLeave(X)
+#endif
+
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
+SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
+#endif
+
+#ifndef SQLITE_OMIT_FOREIGN_KEY
+SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
+#else
+# define sqlite3VdbeCheckFk(p,i) 0
+#endif
+
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
+SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr);
+#endif
+#ifndef SQLITE_OMIT_UTF16
+SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
+SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
+#endif
+
+#ifndef SQLITE_OMIT_INCRBLOB
+SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
+ #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
+#else
+ #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
+ #define ExpandBlob(P) SQLITE_OK
+#endif
+
+#endif /* !defined(SQLITE_VDBEINT_H) */
+
+/************** End of vdbeInt.h *********************************************/
+/************** Continuing where we left off in status.c *********************/
+
+/*
+** Variables in which to record status information.
+*/
+#if SQLITE_PTRSIZE>4
+typedef sqlite3_int64 sqlite3StatValueType;
+#else
+typedef u32 sqlite3StatValueType;
+#endif
+typedef struct sqlite3StatType sqlite3StatType;
+static SQLITE_WSD struct sqlite3StatType {
+ sqlite3StatValueType nowValue[10]; /* Current value */
+ sqlite3StatValueType mxValue[10]; /* Maximum value */
+} sqlite3Stat = { {0,}, {0,} };
+
+/*
+** Elements of sqlite3Stat[] are protected by either the memory allocator
+** mutex, or by the pcache1 mutex. The following array determines which.
+*/
+static const char statMutex[] = {
+ 0, /* SQLITE_STATUS_MEMORY_USED */
+ 1, /* SQLITE_STATUS_PAGECACHE_USED */
+ 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
+ 0, /* SQLITE_STATUS_SCRATCH_USED */
+ 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
+ 0, /* SQLITE_STATUS_MALLOC_SIZE */
+ 0, /* SQLITE_STATUS_PARSER_STACK */
+ 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
+ 0, /* SQLITE_STATUS_SCRATCH_SIZE */
+ 0, /* SQLITE_STATUS_MALLOC_COUNT */
+};
+
+
+/* The "wsdStat" macro will resolve to the status information
+** state vector. If writable static data is unsupported on the target,
+** we have to locate the state vector at run-time. In the more common
+** case where writable static data is supported, wsdStat can refer directly
+** to the "sqlite3Stat" state vector declared above.
+*/
+#ifdef SQLITE_OMIT_WSD
+# define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
+# define wsdStat x[0]
+#else
+# define wsdStatInit
+# define wsdStat sqlite3Stat
+#endif
+
+/*
+** Return the current value of a status parameter. The caller must
+** be holding the appropriate mutex.
+*/
+SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
+ wsdStatInit;
+ assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
+ assert( op>=0 && op<ArraySize(statMutex) );
+ assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
+ : sqlite3MallocMutex()) );
+ return wsdStat.nowValue[op];
+}
+
+/*
+** Add N to the value of a status record. The caller must hold the
+** appropriate mutex. (Locking is checked by assert()).
+**
+** The StatusUp() routine can accept positive or negative values for N.
+** The value of N is added to the current status value and the high-water
+** mark is adjusted if necessary.
+**
+** The StatusDown() routine lowers the current value by N. The highwater
+** mark is unchanged. N must be non-negative for StatusDown().
+*/
+SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
+ wsdStatInit;
+ assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
+ assert( op>=0 && op<ArraySize(statMutex) );
+ assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
+ : sqlite3MallocMutex()) );
+ wsdStat.nowValue[op] += N;
+ if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
+ wsdStat.mxValue[op] = wsdStat.nowValue[op];
+ }
+}
+SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
+ wsdStatInit;
+ assert( N>=0 );
+ assert( op>=0 && op<ArraySize(statMutex) );
+ assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
+ : sqlite3MallocMutex()) );
+ assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
+ wsdStat.nowValue[op] -= N;
+}
+
+/*
+** Adjust the highwater mark if necessary.
+** The caller must hold the appropriate mutex.
+*/
+SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
+ sqlite3StatValueType newValue;
+ wsdStatInit;
+ assert( X>=0 );
+ newValue = (sqlite3StatValueType)X;
+ assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
+ assert( op>=0 && op<ArraySize(statMutex) );
+ assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
+ : sqlite3MallocMutex()) );
+ assert( op==SQLITE_STATUS_MALLOC_SIZE
+ || op==SQLITE_STATUS_PAGECACHE_SIZE
+ || op==SQLITE_STATUS_PARSER_STACK );
+ if( newValue>wsdStat.mxValue[op] ){
+ wsdStat.mxValue[op] = newValue;
+ }
+}
+
+/*
+** Query status information.
+*/
+SQLITE_API int sqlite3_status64(
+ int op,
+ sqlite3_int64 *pCurrent,
+ sqlite3_int64 *pHighwater,
+ int resetFlag
+){
+ sqlite3_mutex *pMutex;
+ wsdStatInit;
+ if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
+ return SQLITE_MISUSE_BKPT;
+ }
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
+#endif
+ pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
+ sqlite3_mutex_enter(pMutex);
+ *pCurrent = wsdStat.nowValue[op];
+ *pHighwater = wsdStat.mxValue[op];
+ if( resetFlag ){
+ wsdStat.mxValue[op] = wsdStat.nowValue[op];
+ }
+ sqlite3_mutex_leave(pMutex);
+ (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
+ return SQLITE_OK;
+}
+SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
+ sqlite3_int64 iCur = 0, iHwtr = 0;
+ int rc;
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
+#endif
+ rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
+ if( rc==0 ){
+ *pCurrent = (int)iCur;
+ *pHighwater = (int)iHwtr;
+ }
+ return rc;
+}
+
+/*
+** Return the number of LookasideSlot elements on the linked list
+*/
+static u32 countLookasideSlots(LookasideSlot *p){
+ u32 cnt = 0;
+ while( p ){
+ p = p->pNext;
+ cnt++;
+ }
+ return cnt;
+}
+
+/*
+** Count the number of slots of lookaside memory that are outstanding
+*/
+SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
+ u32 nInit = countLookasideSlots(db->lookaside.pInit);
+ u32 nFree = countLookasideSlots(db->lookaside.pFree);
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+ nInit += countLookasideSlots(db->lookaside.pSmallInit);
+ nFree += countLookasideSlots(db->lookaside.pSmallFree);
+#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
+ if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
+ return db->lookaside.nSlot - (nInit+nFree);
+}
+
+/*
+** Query status information for a single database connection
+*/
+SQLITE_API int sqlite3_db_status(
+ sqlite3 *db, /* The database connection whose status is desired */
+ int op, /* Status verb */
+ int *pCurrent, /* Write current value here */
+ int *pHighwater, /* Write high-water mark here */
+ int resetFlag /* Reset high-water mark if true */
+){
+ int rc = SQLITE_OK; /* Return code */
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
+ return SQLITE_MISUSE_BKPT;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ switch( op ){
+ case SQLITE_DBSTATUS_LOOKASIDE_USED: {
+ *pCurrent = sqlite3LookasideUsed(db, pHighwater);
+ if( resetFlag ){
+ LookasideSlot *p = db->lookaside.pFree;
+ if( p ){
+ while( p->pNext ) p = p->pNext;
+ p->pNext = db->lookaside.pInit;
+ db->lookaside.pInit = db->lookaside.pFree;
+ db->lookaside.pFree = 0;
+ }
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+ p = db->lookaside.pSmallFree;
+ if( p ){
+ while( p->pNext ) p = p->pNext;
+ p->pNext = db->lookaside.pSmallInit;
+ db->lookaside.pSmallInit = db->lookaside.pSmallFree;
+ db->lookaside.pSmallFree = 0;
+ }
+#endif
+ }
+ break;
+ }
+
+ case SQLITE_DBSTATUS_LOOKASIDE_HIT:
+ case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
+ case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
+ testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
+ testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
+ testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
+ assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
+ assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
+ *pCurrent = 0;
+ *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
+ if( resetFlag ){
+ db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
+ }
+ break;
+ }
+
+ /*
+ ** Return an approximation for the amount of memory currently used
+ ** by all pagers associated with the given database connection. The
+ ** highwater mark is meaningless and is returned as zero.
+ */
+ case SQLITE_DBSTATUS_CACHE_USED_SHARED:
+ case SQLITE_DBSTATUS_CACHE_USED: {
+ int totalUsed = 0;
+ int i;
+ sqlite3BtreeEnterAll(db);
+ for(i=0; i<db->nDb; i++){
+ Btree *pBt = db->aDb[i].pBt;
+ if( pBt ){
+ Pager *pPager = sqlite3BtreePager(pBt);
+ int nByte = sqlite3PagerMemUsed(pPager);
+ if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
+ nByte = nByte / sqlite3BtreeConnectionCount(pBt);
+ }
+ totalUsed += nByte;
+ }
+ }
+ sqlite3BtreeLeaveAll(db);
+ *pCurrent = totalUsed;
+ *pHighwater = 0;
+ break;
+ }
+
+ /*
+ ** *pCurrent gets an accurate estimate of the amount of memory used
+ ** to store the schema for all databases (main, temp, and any ATTACHed
+ ** databases. *pHighwater is set to zero.
+ */
+ case SQLITE_DBSTATUS_SCHEMA_USED: {
+ int i; /* Used to iterate through schemas */
+ int nByte = 0; /* Used to accumulate return value */
+
+ sqlite3BtreeEnterAll(db);
+ db->pnBytesFreed = &nByte;
+ for(i=0; i<db->nDb; i++){
+ Schema *pSchema = db->aDb[i].pSchema;
+ if( ALWAYS(pSchema!=0) ){
+ HashElem *p;
+
+ nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
+ pSchema->tblHash.count
+ + pSchema->trigHash.count
+ + pSchema->idxHash.count
+ + pSchema->fkeyHash.count
+ );
+ nByte += sqlite3_msize(pSchema->tblHash.ht);
+ nByte += sqlite3_msize(pSchema->trigHash.ht);
+ nByte += sqlite3_msize(pSchema->idxHash.ht);
+ nByte += sqlite3_msize(pSchema->fkeyHash.ht);
+
+ for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
+ sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
+ }
+ for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
+ sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
+ }
+ }
+ }
+ db->pnBytesFreed = 0;
+ sqlite3BtreeLeaveAll(db);
+
+ *pHighwater = 0;
+ *pCurrent = nByte;
+ break;
+ }
+
+ /*
+ ** *pCurrent gets an accurate estimate of the amount of memory used
+ ** to store all prepared statements.
+ ** *pHighwater is set to zero.
+ */
+ case SQLITE_DBSTATUS_STMT_USED: {
+ struct Vdbe *pVdbe; /* Used to iterate through VMs */
+ int nByte = 0; /* Used to accumulate return value */
+
+ db->pnBytesFreed = &nByte;
+ for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
+ sqlite3VdbeClearObject(db, pVdbe);
+ sqlite3DbFree(db, pVdbe);
+ }
+ db->pnBytesFreed = 0;
+
+ *pHighwater = 0; /* IMP: R-64479-57858 */
+ *pCurrent = nByte;
+
+ break;
+ }
+
+ /*
+ ** Set *pCurrent to the total cache hits or misses encountered by all
+ ** pagers the database handle is connected to. *pHighwater is always set
+ ** to zero.
+ */
+ case SQLITE_DBSTATUS_CACHE_SPILL:
+ op = SQLITE_DBSTATUS_CACHE_WRITE+1;
+ /* no break */ deliberate_fall_through
+ case SQLITE_DBSTATUS_CACHE_HIT:
+ case SQLITE_DBSTATUS_CACHE_MISS:
+ case SQLITE_DBSTATUS_CACHE_WRITE:{
+ int i;
+ int nRet = 0;
+ assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
+ assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
+
+ for(i=0; i<db->nDb; i++){
+ if( db->aDb[i].pBt ){
+ Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
+ sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
+ }
+ }
+ *pHighwater = 0; /* IMP: R-42420-56072 */
+ /* IMP: R-54100-20147 */
+ /* IMP: R-29431-39229 */
+ *pCurrent = nRet;
+ break;
+ }
+
+ /* Set *pCurrent to non-zero if there are unresolved deferred foreign
+ ** key constraints. Set *pCurrent to zero if all foreign key constraints
+ ** have been satisfied. The *pHighwater is always set to zero.
+ */
+ case SQLITE_DBSTATUS_DEFERRED_FKS: {
+ *pHighwater = 0; /* IMP: R-11967-56545 */
+ *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
+ break;
+ }
+
+ default: {
+ rc = SQLITE_ERROR;
+ }
+ }
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+/************** End of status.c **********************************************/
+/************** Begin file date.c ********************************************/
+/*
+** 2003 October 31
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains the C functions that implement date and time
+** functions for SQLite.
+**
+** There is only one exported symbol in this file - the function
+** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
+** All other code has file scope.
+**
+** SQLite processes all times and dates as julian day numbers. The
+** dates and times are stored as the number of days since noon
+** in Greenwich on November 24, 4714 B.C. according to the Gregorian
+** calendar system.
+**
+** 1970-01-01 00:00:00 is JD 2440587.5
+** 2000-01-01 00:00:00 is JD 2451544.5
+**
+** This implementation requires years to be expressed as a 4-digit number
+** which means that only dates between 0000-01-01 and 9999-12-31 can
+** be represented, even though julian day numbers allow a much wider
+** range of dates.
+**
+** The Gregorian calendar system is used for all dates and times,
+** even those that predate the Gregorian calendar. Historians usually
+** use the julian calendar for dates prior to 1582-10-15 and for some
+** dates afterwards, depending on locale. Beware of this difference.
+**
+** The conversion algorithms are implemented based on descriptions
+** in the following text:
+**
+** Jean Meeus
+** Astronomical Algorithms, 2nd Edition, 1998
+** ISBN 0-943396-61-1
+** Willmann-Bell, Inc
+** Richmond, Virginia (USA)
+*/
+/* #include "sqliteInt.h" */
+/* #include <stdlib.h> */
+/* #include <assert.h> */
+#include <time.h>
+
+#ifndef SQLITE_OMIT_DATETIME_FUNCS
+
+/*
+** The MSVC CRT on Windows CE may not have a localtime() function.
+** So declare a substitute. The substitute function itself is
+** defined in "os_win.c".
+*/
+#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
+ (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
+struct tm *__cdecl localtime(const time_t *);
+#endif
+
+/*
+** A structure for holding a single date and time.
+*/
+typedef struct DateTime DateTime;
+struct DateTime {
+ sqlite3_int64 iJD; /* The julian day number times 86400000 */
+ int Y, M, D; /* Year, month, and day */
+ int h, m; /* Hour and minutes */
+ int tz; /* Timezone offset in minutes */
+ double s; /* Seconds */
+ char validJD; /* True (1) if iJD is valid */
+ char rawS; /* Raw numeric value stored in s */
+ char validYMD; /* True (1) if Y,M,D are valid */
+ char validHMS; /* True (1) if h,m,s are valid */
+ char validTZ; /* True (1) if tz is valid */
+ char tzSet; /* Timezone was set explicitly */
+ char isError; /* An overflow has occurred */
+};
+
+
+/*
+** Convert zDate into one or more integers according to the conversion
+** specifier zFormat.
+**
+** zFormat[] contains 4 characters for each integer converted, except for
+** the last integer which is specified by three characters. The meaning
+** of a four-character format specifiers ABCD is:
+**
+** A: number of digits to convert. Always "2" or "4".
+** B: minimum value. Always "0" or "1".
+** C: maximum value, decoded as:
+** a: 12
+** b: 14
+** c: 24
+** d: 31
+** e: 59
+** f: 9999
+** D: the separator character, or \000 to indicate this is the
+** last number to convert.
+**
+** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
+** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
+** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
+** the 2-digit day which is the last integer in the set.
+**
+** The function returns the number of successful conversions.
+*/
+static int getDigits(const char *zDate, const char *zFormat, ...){
+ /* The aMx[] array translates the 3rd character of each format
+ ** spec into a max size: a b c d e f */
+ static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
+ va_list ap;
+ int cnt = 0;
+ char nextC;
+ va_start(ap, zFormat);
+ do{
+ char N = zFormat[0] - '0';
+ char min = zFormat[1] - '0';
+ int val = 0;
+ u16 max;
+
+ assert( zFormat[2]>='a' && zFormat[2]<='f' );
+ max = aMx[zFormat[2] - 'a'];
+ nextC = zFormat[3];
+ val = 0;
+ while( N-- ){
+ if( !sqlite3Isdigit(*zDate) ){
+ goto end_getDigits;
+ }
+ val = val*10 + *zDate - '0';
+ zDate++;
+ }
+ if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
+ goto end_getDigits;
+ }
+ *va_arg(ap,int*) = val;
+ zDate++;
+ cnt++;
+ zFormat += 4;
+ }while( nextC );
+end_getDigits:
+ va_end(ap);
+ return cnt;
+}
+
+/*
+** Parse a timezone extension on the end of a date-time.
+** The extension is of the form:
+**
+** (+/-)HH:MM
+**
+** Or the "zulu" notation:
+**
+** Z
+**
+** If the parse is successful, write the number of minutes
+** of change in p->tz and return 0. If a parser error occurs,
+** return non-zero.
+**
+** A missing specifier is not considered an error.
+*/
+static int parseTimezone(const char *zDate, DateTime *p){
+ int sgn = 0;
+ int nHr, nMn;
+ int c;
+ while( sqlite3Isspace(*zDate) ){ zDate++; }
+ p->tz = 0;
+ c = *zDate;
+ if( c=='-' ){
+ sgn = -1;
+ }else if( c=='+' ){
+ sgn = +1;
+ }else if( c=='Z' || c=='z' ){
+ zDate++;
+ goto zulu_time;
+ }else{
+ return c!=0;
+ }
+ zDate++;
+ if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
+ return 1;
+ }
+ zDate += 5;
+ p->tz = sgn*(nMn + nHr*60);
+zulu_time:
+ while( sqlite3Isspace(*zDate) ){ zDate++; }
+ p->tzSet = 1;
+ return *zDate!=0;
+}
+
+/*
+** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
+** The HH, MM, and SS must each be exactly 2 digits. The
+** fractional seconds FFFF can be one or more digits.
+**
+** Return 1 if there is a parsing error and 0 on success.
+*/
+static int parseHhMmSs(const char *zDate, DateTime *p){
+ int h, m, s;
+ double ms = 0.0;
+ if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
+ return 1;
+ }
+ zDate += 5;
+ if( *zDate==':' ){
+ zDate++;
+ if( getDigits(zDate, "20e", &s)!=1 ){
+ return 1;
+ }
+ zDate += 2;
+ if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
+ double rScale = 1.0;
+ zDate++;
+ while( sqlite3Isdigit(*zDate) ){
+ ms = ms*10.0 + *zDate - '0';
+ rScale *= 10.0;
+ zDate++;
+ }
+ ms /= rScale;
+ }
+ }else{
+ s = 0;
+ }
+ p->validJD = 0;
+ p->rawS = 0;
+ p->validHMS = 1;
+ p->h = h;
+ p->m = m;
+ p->s = s + ms;
+ if( parseTimezone(zDate, p) ) return 1;
+ p->validTZ = (p->tz!=0)?1:0;
+ return 0;
+}
+
+/*
+** Put the DateTime object into its error state.
+*/
+static void datetimeError(DateTime *p){
+ memset(p, 0, sizeof(*p));
+ p->isError = 1;
+}
+
+/*
+** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
+** that the YYYY-MM-DD is according to the Gregorian calendar.
+**
+** Reference: Meeus page 61
+*/
+static void computeJD(DateTime *p){
+ int Y, M, D, A, B, X1, X2;
+
+ if( p->validJD ) return;
+ if( p->validYMD ){
+ Y = p->Y;
+ M = p->M;
+ D = p->D;
+ }else{
+ Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
+ M = 1;
+ D = 1;
+ }
+ if( Y<-4713 || Y>9999 || p->rawS ){
+ datetimeError(p);
+ return;
+ }
+ if( M<=2 ){
+ Y--;
+ M += 12;
+ }
+ A = Y/100;
+ B = 2 - A + (A/4);
+ X1 = 36525*(Y+4716)/100;
+ X2 = 306001*(M+1)/10000;
+ p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
+ p->validJD = 1;
+ if( p->validHMS ){
+ p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
+ if( p->validTZ ){
+ p->iJD -= p->tz*60000;
+ p->validYMD = 0;
+ p->validHMS = 0;
+ p->validTZ = 0;
+ }
+ }
+}
+
+/*
+** Parse dates of the form
+**
+** YYYY-MM-DD HH:MM:SS.FFF
+** YYYY-MM-DD HH:MM:SS
+** YYYY-MM-DD HH:MM
+** YYYY-MM-DD
+**
+** Write the result into the DateTime structure and return 0
+** on success and 1 if the input string is not a well-formed
+** date.
+*/
+static int parseYyyyMmDd(const char *zDate, DateTime *p){
+ int Y, M, D, neg;
+
+ if( zDate[0]=='-' ){
+ zDate++;
+ neg = 1;
+ }else{
+ neg = 0;
+ }
+ if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
+ return 1;
+ }
+ zDate += 10;
+ while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
+ if( parseHhMmSs(zDate, p)==0 ){
+ /* We got the time */
+ }else if( *zDate==0 ){
+ p->validHMS = 0;
+ }else{
+ return 1;
+ }
+ p->validJD = 0;
+ p->validYMD = 1;
+ p->Y = neg ? -Y : Y;
+ p->M = M;
+ p->D = D;
+ if( p->validTZ ){
+ computeJD(p);
+ }
+ return 0;
+}
+
+/*
+** Set the time to the current time reported by the VFS.
+**
+** Return the number of errors.
+*/
+static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
+ p->iJD = sqlite3StmtCurrentTime(context);
+ if( p->iJD>0 ){
+ p->validJD = 1;
+ return 0;
+ }else{
+ return 1;
+ }
+}
+
+/*
+** Input "r" is a numeric quantity which might be a julian day number,
+** or the number of seconds since 1970. If the value if r is within
+** range of a julian day number, install it as such and set validJD.
+** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
+*/
+static void setRawDateNumber(DateTime *p, double r){
+ p->s = r;
+ p->rawS = 1;
+ if( r>=0.0 && r<5373484.5 ){
+ p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
+ p->validJD = 1;
+ }
+}
+
+/*
+** Attempt to parse the given string into a julian day number. Return
+** the number of errors.
+**
+** The following are acceptable forms for the input string:
+**
+** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
+** DDDD.DD
+** now
+**
+** In the first form, the +/-HH:MM is always optional. The fractional
+** seconds extension (the ".FFF") is optional. The seconds portion
+** (":SS.FFF") is option. The year and date can be omitted as long
+** as there is a time string. The time string can be omitted as long
+** as there is a year and date.
+*/
+static int parseDateOrTime(
+ sqlite3_context *context,
+ const char *zDate,
+ DateTime *p
+){
+ double r;
+ if( parseYyyyMmDd(zDate,p)==0 ){
+ return 0;
+ }else if( parseHhMmSs(zDate, p)==0 ){
+ return 0;
+ }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
+ return setDateTimeToCurrent(context, p);
+ }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8)>0 ){
+ setRawDateNumber(p, r);
+ return 0;
+ }
+ return 1;
+}
+
+/* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
+** Multiplying this by 86400000 gives 464269060799999 as the maximum value
+** for DateTime.iJD.
+**
+** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
+** such a large integer literal, so we have to encode it.
+*/
+#define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff)
+
+/*
+** Return TRUE if the given julian day number is within range.
+**
+** The input is the JulianDay times 86400000.
+*/
+static int validJulianDay(sqlite3_int64 iJD){
+ return iJD>=0 && iJD<=INT_464269060799999;
+}
+
+/*
+** Compute the Year, Month, and Day from the julian day number.
+*/
+static void computeYMD(DateTime *p){
+ int Z, A, B, C, D, E, X1;
+ if( p->validYMD ) return;
+ if( !p->validJD ){
+ p->Y = 2000;
+ p->M = 1;
+ p->D = 1;
+ }else if( !validJulianDay(p->iJD) ){
+ datetimeError(p);
+ return;
+ }else{
+ Z = (int)((p->iJD + 43200000)/86400000);
+ A = (int)((Z - 1867216.25)/36524.25);
+ A = Z + 1 + A - (A/4);
+ B = A + 1524;
+ C = (int)((B - 122.1)/365.25);
+ D = (36525*(C&32767))/100;
+ E = (int)((B-D)/30.6001);
+ X1 = (int)(30.6001*E);
+ p->D = B - D - X1;
+ p->M = E<14 ? E-1 : E-13;
+ p->Y = p->M>2 ? C - 4716 : C - 4715;
+ }
+ p->validYMD = 1;
+}
+
+/*
+** Compute the Hour, Minute, and Seconds from the julian day number.
+*/
+static void computeHMS(DateTime *p){
+ int s;
+ if( p->validHMS ) return;
+ computeJD(p);
+ s = (int)((p->iJD + 43200000) % 86400000);
+ p->s = s/1000.0;
+ s = (int)p->s;
+ p->s -= s;
+ p->h = s/3600;
+ s -= p->h*3600;
+ p->m = s/60;
+ p->s += s - p->m*60;
+ p->rawS = 0;
+ p->validHMS = 1;
+}
+
+/*
+** Compute both YMD and HMS
+*/
+static void computeYMD_HMS(DateTime *p){
+ computeYMD(p);
+ computeHMS(p);
+}
+
+/*
+** Clear the YMD and HMS and the TZ
+*/
+static void clearYMD_HMS_TZ(DateTime *p){
+ p->validYMD = 0;
+ p->validHMS = 0;
+ p->validTZ = 0;
+}
+
+#ifndef SQLITE_OMIT_LOCALTIME
+/*
+** On recent Windows platforms, the localtime_s() function is available
+** as part of the "Secure CRT". It is essentially equivalent to
+** localtime_r() available under most POSIX platforms, except that the
+** order of the parameters is reversed.
+**
+** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
+**
+** If the user has not indicated to use localtime_r() or localtime_s()
+** already, check for an MSVC build environment that provides
+** localtime_s().
+*/
+#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
+ && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
+#undef HAVE_LOCALTIME_S
+#define HAVE_LOCALTIME_S 1
+#endif
+
+/*
+** The following routine implements the rough equivalent of localtime_r()
+** using whatever operating-system specific localtime facility that
+** is available. This routine returns 0 on success and
+** non-zero on any kind of error.
+**
+** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
+** routine will always fail.
+**
+** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
+** library function localtime_r() is used to assist in the calculation of
+** local time.
+*/
+static int osLocaltime(time_t *t, struct tm *pTm){
+ int rc;
+#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
+ struct tm *pX;
+#if SQLITE_THREADSAFE>0
+ sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
+#endif
+ sqlite3_mutex_enter(mutex);
+ pX = localtime(t);
+#ifndef SQLITE_UNTESTABLE
+ if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
+#endif
+ if( pX ) *pTm = *pX;
+ sqlite3_mutex_leave(mutex);
+ rc = pX==0;
+#else
+#ifndef SQLITE_UNTESTABLE
+ if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
+#endif
+#if HAVE_LOCALTIME_R
+ rc = localtime_r(t, pTm)==0;
+#else
+ rc = localtime_s(pTm, t);
+#endif /* HAVE_LOCALTIME_R */
+#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
+ return rc;
+}
+#endif /* SQLITE_OMIT_LOCALTIME */
+
+
+#ifndef SQLITE_OMIT_LOCALTIME
+/*
+** Compute the difference (in milliseconds) between localtime and UTC
+** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
+** return this value and set *pRc to SQLITE_OK.
+**
+** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
+** is undefined in this case.
+*/
+static sqlite3_int64 localtimeOffset(
+ DateTime *p, /* Date at which to calculate offset */
+ sqlite3_context *pCtx, /* Write error here if one occurs */
+ int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
+){
+ DateTime x, y;
+ time_t t;
+ struct tm sLocal;
+
+ /* Initialize the contents of sLocal to avoid a compiler warning. */
+ memset(&sLocal, 0, sizeof(sLocal));
+
+ x = *p;
+ computeYMD_HMS(&x);
+ if( x.Y<1971 || x.Y>=2038 ){
+ /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
+ ** works for years between 1970 and 2037. For dates outside this range,
+ ** SQLite attempts to map the year into an equivalent year within this
+ ** range, do the calculation, then map the year back.
+ */
+ x.Y = 2000;
+ x.M = 1;
+ x.D = 1;
+ x.h = 0;
+ x.m = 0;
+ x.s = 0.0;
+ } else {
+ int s = (int)(x.s + 0.5);
+ x.s = s;
+ }
+ x.tz = 0;
+ x.validJD = 0;
+ computeJD(&x);
+ t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
+ if( osLocaltime(&t, &sLocal) ){
+ sqlite3_result_error(pCtx, "local time unavailable", -1);
+ *pRc = SQLITE_ERROR;
+ return 0;
+ }
+ y.Y = sLocal.tm_year + 1900;
+ y.M = sLocal.tm_mon + 1;
+ y.D = sLocal.tm_mday;
+ y.h = sLocal.tm_hour;
+ y.m = sLocal.tm_min;
+ y.s = sLocal.tm_sec;
+ y.validYMD = 1;
+ y.validHMS = 1;
+ y.validJD = 0;
+ y.rawS = 0;
+ y.validTZ = 0;
+ y.isError = 0;
+ computeJD(&y);
+ *pRc = SQLITE_OK;
+ return y.iJD - x.iJD;
+}
+#endif /* SQLITE_OMIT_LOCALTIME */
+
+/*
+** The following table defines various date transformations of the form
+**
+** 'NNN days'
+**
+** Where NNN is an arbitrary floating-point number and "days" can be one
+** of several units of time.
+*/
+static const struct {
+ u8 eType; /* Transformation type code */
+ u8 nName; /* Length of th name */
+ char *zName; /* Name of the transformation */
+ double rLimit; /* Maximum NNN value for this transform */
+ double rXform; /* Constant used for this transform */
+} aXformType[] = {
+ { 0, 6, "second", 464269060800.0, 1000.0 },
+ { 0, 6, "minute", 7737817680.0, 60000.0 },
+ { 0, 4, "hour", 128963628.0, 3600000.0 },
+ { 0, 3, "day", 5373485.0, 86400000.0 },
+ { 1, 5, "month", 176546.0, 2592000000.0 },
+ { 2, 4, "year", 14713.0, 31536000000.0 },
+};
+
+/*
+** Process a modifier to a date-time stamp. The modifiers are
+** as follows:
+**
+** NNN days
+** NNN hours
+** NNN minutes
+** NNN.NNNN seconds
+** NNN months
+** NNN years
+** start of month
+** start of year
+** start of week
+** start of day
+** weekday N
+** unixepoch
+** localtime
+** utc
+**
+** Return 0 on success and 1 if there is any kind of error. If the error
+** is in a system call (i.e. localtime()), then an error message is written
+** to context pCtx. If the error is an unrecognized modifier, no error is
+** written to pCtx.
+*/
+static int parseModifier(
+ sqlite3_context *pCtx, /* Function context */
+ const char *z, /* The text of the modifier */
+ int n, /* Length of zMod in bytes */
+ DateTime *p /* The date/time value to be modified */
+){
+ int rc = 1;
+ double r;
+ switch(sqlite3UpperToLower[(u8)z[0]] ){
+#ifndef SQLITE_OMIT_LOCALTIME
+ case 'l': {
+ /* localtime
+ **
+ ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
+ ** show local time.
+ */
+ if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
+ computeJD(p);
+ p->iJD += localtimeOffset(p, pCtx, &rc);
+ clearYMD_HMS_TZ(p);
+ }
+ break;
+ }
+#endif
+ case 'u': {
+ /*
+ ** unixepoch
+ **
+ ** Treat the current value of p->s as the number of
+ ** seconds since 1970. Convert to a real julian day number.
+ */
+ if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
+ r = p->s*1000.0 + 210866760000000.0;
+ if( r>=0.0 && r<464269060800000.0 ){
+ clearYMD_HMS_TZ(p);
+ p->iJD = (sqlite3_int64)(r + 0.5);
+ p->validJD = 1;
+ p->rawS = 0;
+ rc = 0;
+ }
+ }
+#ifndef SQLITE_OMIT_LOCALTIME
+ else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
+ if( p->tzSet==0 ){
+ sqlite3_int64 c1;
+ computeJD(p);
+ c1 = localtimeOffset(p, pCtx, &rc);
+ if( rc==SQLITE_OK ){
+ p->iJD -= c1;
+ clearYMD_HMS_TZ(p);
+ p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
+ }
+ p->tzSet = 1;
+ }else{
+ rc = SQLITE_OK;
+ }
+ }
+#endif
+ break;
+ }
+ case 'w': {
+ /*
+ ** weekday N
+ **
+ ** Move the date to the same time on the next occurrence of
+ ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
+ ** date is already on the appropriate weekday, this is a no-op.
+ */
+ if( sqlite3_strnicmp(z, "weekday ", 8)==0
+ && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)>0
+ && (n=(int)r)==r && n>=0 && r<7 ){
+ sqlite3_int64 Z;
+ computeYMD_HMS(p);
+ p->validTZ = 0;
+ p->validJD = 0;
+ computeJD(p);
+ Z = ((p->iJD + 129600000)/86400000) % 7;
+ if( Z>n ) Z -= 7;
+ p->iJD += (n - Z)*86400000;
+ clearYMD_HMS_TZ(p);
+ rc = 0;
+ }
+ break;
+ }
+ case 's': {
+ /*
+ ** start of TTTTT
+ **
+ ** Move the date backwards to the beginning of the current day,
+ ** or month or year.
+ */
+ if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
+ if( !p->validJD && !p->validYMD && !p->validHMS ) break;
+ z += 9;
+ computeYMD(p);
+ p->validHMS = 1;
+ p->h = p->m = 0;
+ p->s = 0.0;
+ p->rawS = 0;
+ p->validTZ = 0;
+ p->validJD = 0;
+ if( sqlite3_stricmp(z,"month")==0 ){
+ p->D = 1;
+ rc = 0;
+ }else if( sqlite3_stricmp(z,"year")==0 ){
+ p->M = 1;
+ p->D = 1;
+ rc = 0;
+ }else if( sqlite3_stricmp(z,"day")==0 ){
+ rc = 0;
+ }
+ break;
+ }
+ case '+':
+ case '-':
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9': {
+ double rRounder;
+ int i;
+ for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
+ if( sqlite3AtoF(z, &r, n, SQLITE_UTF8)<=0 ){
+ rc = 1;
+ break;
+ }
+ if( z[n]==':' ){
+ /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
+ ** specified number of hours, minutes, seconds, and fractional seconds
+ ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
+ ** omitted.
+ */
+ const char *z2 = z;
+ DateTime tx;
+ sqlite3_int64 day;
+ if( !sqlite3Isdigit(*z2) ) z2++;
+ memset(&tx, 0, sizeof(tx));
+ if( parseHhMmSs(z2, &tx) ) break;
+ computeJD(&tx);
+ tx.iJD -= 43200000;
+ day = tx.iJD/86400000;
+ tx.iJD -= day*86400000;
+ if( z[0]=='-' ) tx.iJD = -tx.iJD;
+ computeJD(p);
+ clearYMD_HMS_TZ(p);
+ p->iJD += tx.iJD;
+ rc = 0;
+ break;
+ }
+
+ /* If control reaches this point, it means the transformation is
+ ** one of the forms like "+NNN days". */
+ z += n;
+ while( sqlite3Isspace(*z) ) z++;
+ n = sqlite3Strlen30(z);
+ if( n>10 || n<3 ) break;
+ if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
+ computeJD(p);
+ rc = 1;
+ rRounder = r<0 ? -0.5 : +0.5;
+ for(i=0; i<ArraySize(aXformType); i++){
+ if( aXformType[i].nName==n
+ && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
+ && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
+ ){
+ switch( aXformType[i].eType ){
+ case 1: { /* Special processing to add months */
+ int x;
+ computeYMD_HMS(p);
+ p->M += (int)r;
+ x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
+ p->Y += x;
+ p->M -= x*12;
+ p->validJD = 0;
+ r -= (int)r;
+ break;
+ }
+ case 2: { /* Special processing to add years */
+ int y = (int)r;
+ computeYMD_HMS(p);
+ p->Y += y;
+ p->validJD = 0;
+ r -= (int)r;
+ break;
+ }
+ }
+ computeJD(p);
+ p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
+ rc = 0;
+ break;
+ }
+ }
+ clearYMD_HMS_TZ(p);
+ break;
+ }
+ default: {
+ break;
+ }
+ }
+ return rc;
+}
+
+/*
+** Process time function arguments. argv[0] is a date-time stamp.
+** argv[1] and following are modifiers. Parse them all and write
+** the resulting time into the DateTime structure p. Return 0
+** on success and 1 if there are any errors.
+**
+** If there are zero parameters (if even argv[0] is undefined)
+** then assume a default value of "now" for argv[0].
+*/
+static int isDate(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv,
+ DateTime *p
+){
+ int i, n;
+ const unsigned char *z;
+ int eType;
+ memset(p, 0, sizeof(*p));
+ if( argc==0 ){
+ return setDateTimeToCurrent(context, p);
+ }
+ if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
+ || eType==SQLITE_INTEGER ){
+ setRawDateNumber(p, sqlite3_value_double(argv[0]));
+ }else{
+ z = sqlite3_value_text(argv[0]);
+ if( !z || parseDateOrTime(context, (char*)z, p) ){
+ return 1;
+ }
+ }
+ for(i=1; i<argc; i++){
+ z = sqlite3_value_text(argv[i]);
+ n = sqlite3_value_bytes(argv[i]);
+ if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
+ }
+ computeJD(p);
+ if( p->isError || !validJulianDay(p->iJD) ) return 1;
+ return 0;
+}
+
+
+/*
+** The following routines implement the various date and time functions
+** of SQLite.
+*/
+
+/*
+** julianday( TIMESTRING, MOD, MOD, ...)
+**
+** Return the julian day number of the date specified in the arguments
+*/
+static void juliandayFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ DateTime x;
+ if( isDate(context, argc, argv, &x)==0 ){
+ computeJD(&x);
+ sqlite3_result_double(context, x.iJD/86400000.0);
+ }
+}
+
+/*
+** datetime( TIMESTRING, MOD, MOD, ...)
+**
+** Return YYYY-MM-DD HH:MM:SS
+*/
+static void datetimeFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ DateTime x;
+ if( isDate(context, argc, argv, &x)==0 ){
+ char zBuf[100];
+ computeYMD_HMS(&x);
+ sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
+ x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
+ sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
+ }
+}
+
+/*
+** time( TIMESTRING, MOD, MOD, ...)
+**
+** Return HH:MM:SS
+*/
+static void timeFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ DateTime x;
+ if( isDate(context, argc, argv, &x)==0 ){
+ char zBuf[100];
+ computeHMS(&x);
+ sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
+ sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
+ }
+}
+
+/*
+** date( TIMESTRING, MOD, MOD, ...)
+**
+** Return YYYY-MM-DD
+*/
+static void dateFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ DateTime x;
+ if( isDate(context, argc, argv, &x)==0 ){
+ char zBuf[100];
+ computeYMD(&x);
+ sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
+ sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
+ }
+}
+
+/*
+** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
+**
+** Return a string described by FORMAT. Conversions as follows:
+**
+** %d day of month
+** %f ** fractional seconds SS.SSS
+** %H hour 00-24
+** %j day of year 000-366
+** %J ** julian day number
+** %m month 01-12
+** %M minute 00-59
+** %s seconds since 1970-01-01
+** %S seconds 00-59
+** %w day of week 0-6 sunday==0
+** %W week of year 00-53
+** %Y year 0000-9999
+** %% %
+*/
+static void strftimeFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ DateTime x;
+ u64 n;
+ size_t i,j;
+ char *z;
+ sqlite3 *db;
+ const char *zFmt;
+ char zBuf[100];
+ if( argc==0 ) return;
+ zFmt = (const char*)sqlite3_value_text(argv[0]);
+ if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
+ db = sqlite3_context_db_handle(context);
+ for(i=0, n=1; zFmt[i]; i++, n++){
+ if( zFmt[i]=='%' ){
+ switch( zFmt[i+1] ){
+ case 'd':
+ case 'H':
+ case 'm':
+ case 'M':
+ case 'S':
+ case 'W':
+ n++;
+ /* fall thru */
+ case 'w':
+ case '%':
+ break;
+ case 'f':
+ n += 8;
+ break;
+ case 'j':
+ n += 3;
+ break;
+ case 'Y':
+ n += 8;
+ break;
+ case 's':
+ case 'J':
+ n += 50;
+ break;
+ default:
+ return; /* ERROR. return a NULL */
+ }
+ i++;
+ }
+ }
+ testcase( n==sizeof(zBuf)-1 );
+ testcase( n==sizeof(zBuf) );
+ testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
+ testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
+ if( n<sizeof(zBuf) ){
+ z = zBuf;
+ }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
+ sqlite3_result_error_toobig(context);
+ return;
+ }else{
+ z = sqlite3DbMallocRawNN(db, (int)n);
+ if( z==0 ){
+ sqlite3_result_error_nomem(context);
+ return;
+ }
+ }
+ computeJD(&x);
+ computeYMD_HMS(&x);
+ for(i=j=0; zFmt[i]; i++){
+ if( zFmt[i]!='%' ){
+ z[j++] = zFmt[i];
+ }else{
+ i++;
+ switch( zFmt[i] ){
+ case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
+ case 'f': {
+ double s = x.s;
+ if( s>59.999 ) s = 59.999;
+ sqlite3_snprintf(7, &z[j],"%06.3f", s);
+ j += sqlite3Strlen30(&z[j]);
+ break;
+ }
+ case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
+ case 'W': /* Fall thru */
+ case 'j': {
+ int nDay; /* Number of days since 1st day of year */
+ DateTime y = x;
+ y.validJD = 0;
+ y.M = 1;
+ y.D = 1;
+ computeJD(&y);
+ nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
+ if( zFmt[i]=='W' ){
+ int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
+ wd = (int)(((x.iJD+43200000)/86400000)%7);
+ sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
+ j += 2;
+ }else{
+ sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
+ j += 3;
+ }
+ break;
+ }
+ case 'J': {
+ sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
+ j+=sqlite3Strlen30(&z[j]);
+ break;
+ }
+ case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
+ case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
+ case 's': {
+ i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000);
+ sqlite3Int64ToText(iS, &z[j]);
+ j += sqlite3Strlen30(&z[j]);
+ break;
+ }
+ case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
+ case 'w': {
+ z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
+ break;
+ }
+ case 'Y': {
+ sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
+ break;
+ }
+ default: z[j++] = '%'; break;
+ }
+ }
+ }
+ z[j] = 0;
+ sqlite3_result_text(context, z, -1,
+ z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
+}
+
+/*
+** current_time()
+**
+** This function returns the same value as time('now').
+*/
+static void ctimeFunc(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **NotUsed2
+){
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ timeFunc(context, 0, 0);
+}
+
+/*
+** current_date()
+**
+** This function returns the same value as date('now').
+*/
+static void cdateFunc(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **NotUsed2
+){
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ dateFunc(context, 0, 0);
+}
+
+/*
+** current_timestamp()
+**
+** This function returns the same value as datetime('now').
+*/
+static void ctimestampFunc(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **NotUsed2
+){
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ datetimeFunc(context, 0, 0);
+}
+#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
+
+#ifdef SQLITE_OMIT_DATETIME_FUNCS
+/*
+** If the library is compiled to omit the full-scale date and time
+** handling (to get a smaller binary), the following minimal version
+** of the functions current_time(), current_date() and current_timestamp()
+** are included instead. This is to support column declarations that
+** include "DEFAULT CURRENT_TIME" etc.
+**
+** This function uses the C-library functions time(), gmtime()
+** and strftime(). The format string to pass to strftime() is supplied
+** as the user-data for the function.
+*/
+static void currentTimeFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ time_t t;
+ char *zFormat = (char *)sqlite3_user_data(context);
+ sqlite3_int64 iT;
+ struct tm *pTm;
+ struct tm sNow;
+ char zBuf[20];
+
+ UNUSED_PARAMETER(argc);
+ UNUSED_PARAMETER(argv);
+
+ iT = sqlite3StmtCurrentTime(context);
+ if( iT<=0 ) return;
+ t = iT/1000 - 10000*(sqlite3_int64)21086676;
+#if HAVE_GMTIME_R
+ pTm = gmtime_r(&t, &sNow);
+#else
+ sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
+ pTm = gmtime(&t);
+ if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
+ sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
+#endif
+ if( pTm ){
+ strftime(zBuf, 20, zFormat, &sNow);
+ sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
+ }
+}
+#endif
+
+/*
+** This function registered all of the above C functions as SQL
+** functions. This should be the only routine in this file with
+** external linkage.
+*/
+SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
+ static FuncDef aDateTimeFuncs[] = {
+#ifndef SQLITE_OMIT_DATETIME_FUNCS
+ PURE_DATE(julianday, -1, 0, 0, juliandayFunc ),
+ PURE_DATE(date, -1, 0, 0, dateFunc ),
+ PURE_DATE(time, -1, 0, 0, timeFunc ),
+ PURE_DATE(datetime, -1, 0, 0, datetimeFunc ),
+ PURE_DATE(strftime, -1, 0, 0, strftimeFunc ),
+ DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
+ DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
+ DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
+#else
+ STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
+ STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
+ STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
+#endif
+ };
+ sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
+}
+
+/************** End of date.c ************************************************/
+/************** Begin file os.c **********************************************/
+/*
+** 2005 November 29
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains OS interface code that is common to all
+** architectures.
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** If we compile with the SQLITE_TEST macro set, then the following block
+** of code will give us the ability to simulate a disk I/O error. This
+** is used for testing the I/O recovery logic.
+*/
+#if defined(SQLITE_TEST)
+SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
+SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
+SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
+SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
+SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
+SQLITE_API int sqlite3_diskfull_pending = 0;
+SQLITE_API int sqlite3_diskfull = 0;
+#endif /* defined(SQLITE_TEST) */
+
+/*
+** When testing, also keep a count of the number of open files.
+*/
+#if defined(SQLITE_TEST)
+SQLITE_API int sqlite3_open_file_count = 0;
+#endif /* defined(SQLITE_TEST) */
+
+/*
+** The default SQLite sqlite3_vfs implementations do not allocate
+** memory (actually, os_unix.c allocates a small amount of memory
+** from within OsOpen()), but some third-party implementations may.
+** So we test the effects of a malloc() failing and the sqlite3OsXXX()
+** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
+**
+** The following functions are instrumented for malloc() failure
+** testing:
+**
+** sqlite3OsRead()
+** sqlite3OsWrite()
+** sqlite3OsSync()
+** sqlite3OsFileSize()
+** sqlite3OsLock()
+** sqlite3OsCheckReservedLock()
+** sqlite3OsFileControl()
+** sqlite3OsShmMap()
+** sqlite3OsOpen()
+** sqlite3OsDelete()
+** sqlite3OsAccess()
+** sqlite3OsFullPathname()
+**
+*/
+#if defined(SQLITE_TEST)
+SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
+ #define DO_OS_MALLOC_TEST(x) \
+ if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
+ void *pTstAlloc = sqlite3Malloc(10); \
+ if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
+ sqlite3_free(pTstAlloc); \
+ }
+#else
+ #define DO_OS_MALLOC_TEST(x)
+#endif
+
+/*
+** The following routines are convenience wrappers around methods
+** of the sqlite3_file object. This is mostly just syntactic sugar. All
+** of this would be completely automatic if SQLite were coded using
+** C++ instead of plain old C.
+*/
+SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
+ if( pId->pMethods ){
+ pId->pMethods->xClose(pId);
+ pId->pMethods = 0;
+ }
+}
+SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
+ DO_OS_MALLOC_TEST(id);
+ return id->pMethods->xRead(id, pBuf, amt, offset);
+}
+SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
+ DO_OS_MALLOC_TEST(id);
+ return id->pMethods->xWrite(id, pBuf, amt, offset);
+}
+SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
+ return id->pMethods->xTruncate(id, size);
+}
+SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
+ DO_OS_MALLOC_TEST(id);
+ return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
+}
+SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
+ DO_OS_MALLOC_TEST(id);
+ return id->pMethods->xFileSize(id, pSize);
+}
+SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
+ DO_OS_MALLOC_TEST(id);
+ return id->pMethods->xLock(id, lockType);
+}
+SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
+ return id->pMethods->xUnlock(id, lockType);
+}
+SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
+ DO_OS_MALLOC_TEST(id);
+ return id->pMethods->xCheckReservedLock(id, pResOut);
+}
+
+/*
+** Use sqlite3OsFileControl() when we are doing something that might fail
+** and we need to know about the failures. Use sqlite3OsFileControlHint()
+** when simply tossing information over the wall to the VFS and we do not
+** really care if the VFS receives and understands the information since it
+** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
+** routine has no return value since the return value would be meaningless.
+*/
+SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
+ if( id->pMethods==0 ) return SQLITE_NOTFOUND;
+#ifdef SQLITE_TEST
+ if( op!=SQLITE_FCNTL_COMMIT_PHASETWO
+ && op!=SQLITE_FCNTL_LOCK_TIMEOUT
+ ){
+ /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
+ ** is using a regular VFS, it is called after the corresponding
+ ** transaction has been committed. Injecting a fault at this point
+ ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
+ ** but the transaction is committed anyway.
+ **
+ ** The core must call OsFileControl() though, not OsFileControlHint(),
+ ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
+ ** means the commit really has failed and an error should be returned
+ ** to the user. */
+ DO_OS_MALLOC_TEST(id);
+ }
+#endif
+ return id->pMethods->xFileControl(id, op, pArg);
+}
+SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
+ if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);
+}
+
+SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
+ int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
+ return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
+}
+SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
+ return id->pMethods->xDeviceCharacteristics(id);
+}
+#ifndef SQLITE_OMIT_WAL
+SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
+ return id->pMethods->xShmLock(id, offset, n, flags);
+}
+SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
+ id->pMethods->xShmBarrier(id);
+}
+SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
+ return id->pMethods->xShmUnmap(id, deleteFlag);
+}
+SQLITE_PRIVATE int sqlite3OsShmMap(
+ sqlite3_file *id, /* Database file handle */
+ int iPage,
+ int pgsz,
+ int bExtend, /* True to extend file if necessary */
+ void volatile **pp /* OUT: Pointer to mapping */
+){
+ DO_OS_MALLOC_TEST(id);
+ return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
+}
+#endif /* SQLITE_OMIT_WAL */
+
+#if SQLITE_MAX_MMAP_SIZE>0
+/* The real implementation of xFetch and xUnfetch */
+SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
+ DO_OS_MALLOC_TEST(id);
+ return id->pMethods->xFetch(id, iOff, iAmt, pp);
+}
+SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
+ return id->pMethods->xUnfetch(id, iOff, p);
+}
+#else
+/* No-op stubs to use when memory-mapped I/O is disabled */
+SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
+ *pp = 0;
+ return SQLITE_OK;
+}
+SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
+ return SQLITE_OK;
+}
+#endif
+
+/*
+** The next group of routines are convenience wrappers around the
+** VFS methods.
+*/
+SQLITE_PRIVATE int sqlite3OsOpen(
+ sqlite3_vfs *pVfs,
+ const char *zPath,
+ sqlite3_file *pFile,
+ int flags,
+ int *pFlagsOut
+){
+ int rc;
+ DO_OS_MALLOC_TEST(0);
+ /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
+ ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
+ ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
+ ** reaching the VFS. */
+ rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x1087f7f, pFlagsOut);
+ assert( rc==SQLITE_OK || pFile->pMethods==0 );
+ return rc;
+}
+SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
+ DO_OS_MALLOC_TEST(0);
+ assert( dirSync==0 || dirSync==1 );
+ return pVfs->xDelete(pVfs, zPath, dirSync);
+}
+SQLITE_PRIVATE int sqlite3OsAccess(
+ sqlite3_vfs *pVfs,
+ const char *zPath,
+ int flags,
+ int *pResOut
+){
+ DO_OS_MALLOC_TEST(0);
+ return pVfs->xAccess(pVfs, zPath, flags, pResOut);
+}
+SQLITE_PRIVATE int sqlite3OsFullPathname(
+ sqlite3_vfs *pVfs,
+ const char *zPath,
+ int nPathOut,
+ char *zPathOut
+){
+ DO_OS_MALLOC_TEST(0);
+ zPathOut[0] = 0;
+ return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
+}
+#ifndef SQLITE_OMIT_LOAD_EXTENSION
+SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
+ return pVfs->xDlOpen(pVfs, zPath);
+}
+SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
+ pVfs->xDlError(pVfs, nByte, zBufOut);
+}
+SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
+ return pVfs->xDlSym(pVfs, pHdle, zSym);
+}
+SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
+ pVfs->xDlClose(pVfs, pHandle);
+}
+#endif /* SQLITE_OMIT_LOAD_EXTENSION */
+SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
+ if( sqlite3Config.iPrngSeed ){
+ memset(zBufOut, 0, nByte);
+ if( ALWAYS(nByte>(signed)sizeof(unsigned)) ) nByte = sizeof(unsigned int);
+ memcpy(zBufOut, &sqlite3Config.iPrngSeed, nByte);
+ return SQLITE_OK;
+ }else{
+ return pVfs->xRandomness(pVfs, nByte, zBufOut);
+ }
+
+}
+SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
+ return pVfs->xSleep(pVfs, nMicro);
+}
+SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
+ return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
+}
+SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
+ int rc;
+ /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
+ ** method to get the current date and time if that method is available
+ ** (if iVersion is 2 or greater and the function pointer is not NULL) and
+ ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
+ ** unavailable.
+ */
+ if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
+ rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
+ }else{
+ double r;
+ rc = pVfs->xCurrentTime(pVfs, &r);
+ *pTimeOut = (sqlite3_int64)(r*86400000.0);
+ }
+ return rc;
+}
+
+SQLITE_PRIVATE int sqlite3OsOpenMalloc(
+ sqlite3_vfs *pVfs,
+ const char *zFile,
+ sqlite3_file **ppFile,
+ int flags,
+ int *pOutFlags
+){
+ int rc;
+ sqlite3_file *pFile;
+ pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
+ if( pFile ){
+ rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
+ if( rc!=SQLITE_OK ){
+ sqlite3_free(pFile);
+ }else{
+ *ppFile = pFile;
+ }
+ }else{
+ rc = SQLITE_NOMEM_BKPT;
+ }
+ return rc;
+}
+SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
+ assert( pFile );
+ sqlite3OsClose(pFile);
+ sqlite3_free(pFile);
+}
+
+/*
+** This function is a wrapper around the OS specific implementation of
+** sqlite3_os_init(). The purpose of the wrapper is to provide the
+** ability to simulate a malloc failure, so that the handling of an
+** error in sqlite3_os_init() by the upper layers can be tested.
+*/
+SQLITE_PRIVATE int sqlite3OsInit(void){
+ void *p = sqlite3_malloc(10);
+ if( p==0 ) return SQLITE_NOMEM_BKPT;
+ sqlite3_free(p);
+ return sqlite3_os_init();
+}
+
+/*
+** The list of all registered VFS implementations.
+*/
+static sqlite3_vfs * SQLITE_WSD vfsList = 0;
+#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
+
+/*
+** Locate a VFS by name. If no name is given, simply return the
+** first VFS on the list.
+*/
+SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
+ sqlite3_vfs *pVfs = 0;
+#if SQLITE_THREADSAFE
+ sqlite3_mutex *mutex;
+#endif
+#ifndef SQLITE_OMIT_AUTOINIT
+ int rc = sqlite3_initialize();
+ if( rc ) return 0;
+#endif
+#if SQLITE_THREADSAFE
+ mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
+#endif
+ sqlite3_mutex_enter(mutex);
+ for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
+ if( zVfs==0 ) break;
+ if( strcmp(zVfs, pVfs->zName)==0 ) break;
+ }
+ sqlite3_mutex_leave(mutex);
+ return pVfs;
+}
+
+/*
+** Unlink a VFS from the linked list
+*/
+static void vfsUnlink(sqlite3_vfs *pVfs){
+ assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN)) );
+ if( pVfs==0 ){
+ /* No-op */
+ }else if( vfsList==pVfs ){
+ vfsList = pVfs->pNext;
+ }else if( vfsList ){
+ sqlite3_vfs *p = vfsList;
+ while( p->pNext && p->pNext!=pVfs ){
+ p = p->pNext;
+ }
+ if( p->pNext==pVfs ){
+ p->pNext = pVfs->pNext;
+ }
+ }
+}
+
+/*
+** Register a VFS with the system. It is harmless to register the same
+** VFS multiple times. The new VFS becomes the default if makeDflt is
+** true.
+*/
+SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
+ MUTEX_LOGIC(sqlite3_mutex *mutex;)
+#ifndef SQLITE_OMIT_AUTOINIT
+ int rc = sqlite3_initialize();
+ if( rc ) return rc;
+#endif
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
+#endif
+
+ MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
+ sqlite3_mutex_enter(mutex);
+ vfsUnlink(pVfs);
+ if( makeDflt || vfsList==0 ){
+ pVfs->pNext = vfsList;
+ vfsList = pVfs;
+ }else{
+ pVfs->pNext = vfsList->pNext;
+ vfsList->pNext = pVfs;
+ }
+ assert(vfsList);
+ sqlite3_mutex_leave(mutex);
+ return SQLITE_OK;
+}
+
+/*
+** Unregister a VFS so that it is no longer accessible.
+*/
+SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
+ MUTEX_LOGIC(sqlite3_mutex *mutex;)
+#ifndef SQLITE_OMIT_AUTOINIT
+ int rc = sqlite3_initialize();
+ if( rc ) return rc;
+#endif
+ MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
+ sqlite3_mutex_enter(mutex);
+ vfsUnlink(pVfs);
+ sqlite3_mutex_leave(mutex);
+ return SQLITE_OK;
+}
+
+/************** End of os.c **************************************************/
+/************** Begin file fault.c *******************************************/
+/*
+** 2008 Jan 22
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains code to support the concept of "benign"
+** malloc failures (when the xMalloc() or xRealloc() method of the
+** sqlite3_mem_methods structure fails to allocate a block of memory
+** and returns 0).
+**
+** Most malloc failures are non-benign. After they occur, SQLite
+** abandons the current operation and returns an error code (usually
+** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
+** fatal. For example, if a malloc fails while resizing a hash table, this
+** is completely recoverable simply by not carrying out the resize. The
+** hash table will continue to function normally. So a malloc failure
+** during a hash table resize is a benign fault.
+*/
+
+/* #include "sqliteInt.h" */
+
+#ifndef SQLITE_UNTESTABLE
+
+/*
+** Global variables.
+*/
+typedef struct BenignMallocHooks BenignMallocHooks;
+static SQLITE_WSD struct BenignMallocHooks {
+ void (*xBenignBegin)(void);
+ void (*xBenignEnd)(void);
+} sqlite3Hooks = { 0, 0 };
+
+/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
+** structure. If writable static data is unsupported on the target,
+** we have to locate the state vector at run-time. In the more common
+** case where writable static data is supported, wsdHooks can refer directly
+** to the "sqlite3Hooks" state vector declared above.
+*/
+#ifdef SQLITE_OMIT_WSD
+# define wsdHooksInit \
+ BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
+# define wsdHooks x[0]
+#else
+# define wsdHooksInit
+# define wsdHooks sqlite3Hooks
+#endif
+
+
+/*
+** Register hooks to call when sqlite3BeginBenignMalloc() and
+** sqlite3EndBenignMalloc() are called, respectively.
+*/
+SQLITE_PRIVATE void sqlite3BenignMallocHooks(
+ void (*xBenignBegin)(void),
+ void (*xBenignEnd)(void)
+){
+ wsdHooksInit;
+ wsdHooks.xBenignBegin = xBenignBegin;
+ wsdHooks.xBenignEnd = xBenignEnd;
+}
+
+/*
+** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
+** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
+** indicates that subsequent malloc failures are non-benign.
+*/
+SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
+ wsdHooksInit;
+ if( wsdHooks.xBenignBegin ){
+ wsdHooks.xBenignBegin();
+ }
+}
+SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
+ wsdHooksInit;
+ if( wsdHooks.xBenignEnd ){
+ wsdHooks.xBenignEnd();
+ }
+}
+
+#endif /* #ifndef SQLITE_UNTESTABLE */
+
+/************** End of fault.c ***********************************************/
+/************** Begin file mem0.c ********************************************/
+/*
+** 2008 October 28
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains a no-op memory allocation drivers for use when
+** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
+** here always fail. SQLite will not operate with these drivers. These
+** are merely placeholders. Real drivers must be substituted using
+** sqlite3_config() before SQLite will operate.
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** This version of the memory allocator is the default. It is
+** used when no other memory allocator is specified using compile-time
+** macros.
+*/
+#ifdef SQLITE_ZERO_MALLOC
+
+/*
+** No-op versions of all memory allocation routines
+*/
+static void *sqlite3MemMalloc(int nByte){ return 0; }
+static void sqlite3MemFree(void *pPrior){ return; }
+static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
+static int sqlite3MemSize(void *pPrior){ return 0; }
+static int sqlite3MemRoundup(int n){ return n; }
+static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
+static void sqlite3MemShutdown(void *NotUsed){ return; }
+
+/*
+** This routine is the only routine in this file with external linkage.
+**
+** Populate the low-level memory allocation function pointers in
+** sqlite3GlobalConfig.m with pointers to the routines in this file.
+*/
+SQLITE_PRIVATE void sqlite3MemSetDefault(void){
+ static const sqlite3_mem_methods defaultMethods = {
+ sqlite3MemMalloc,
+ sqlite3MemFree,
+ sqlite3MemRealloc,
+ sqlite3MemSize,
+ sqlite3MemRoundup,
+ sqlite3MemInit,
+ sqlite3MemShutdown,
+ 0
+ };
+ sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
+}
+
+#endif /* SQLITE_ZERO_MALLOC */
+
+/************** End of mem0.c ************************************************/
+/************** Begin file mem1.c ********************************************/
+/*
+** 2007 August 14
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains low-level memory allocation drivers for when
+** SQLite will use the standard C-library malloc/realloc/free interface
+** to obtain the memory it needs.
+**
+** This file contains implementations of the low-level memory allocation
+** routines specified in the sqlite3_mem_methods object. The content of
+** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
+** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
+** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
+** default configuration is to use memory allocation routines in this
+** file.
+**
+** C-preprocessor macro summary:
+**
+** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
+** the malloc_usable_size() interface exists
+** on the target platform. Or, this symbol
+** can be set manually, if desired.
+** If an equivalent interface exists by
+** a different name, using a separate -D
+** option to rename it.
+**
+** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
+** memory allocator. Set this symbol to enable
+** building on older macs.
+**
+** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
+** _msize() on windows systems. This might
+** be necessary when compiling for Delphi,
+** for example.
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** This version of the memory allocator is the default. It is
+** used when no other memory allocator is specified using compile-time
+** macros.
+*/
+#ifdef SQLITE_SYSTEM_MALLOC
+#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
+
+/*
+** Use the zone allocator available on apple products unless the
+** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
+*/
+#include <sys/sysctl.h>
+#include <malloc/malloc.h>
+#ifdef SQLITE_MIGHT_BE_SINGLE_CORE
+#include <libkern/OSAtomic.h>
+#endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
+static malloc_zone_t* _sqliteZone_;
+#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
+#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
+#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
+#define SQLITE_MALLOCSIZE(x) \
+ (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
+
+#else /* if not __APPLE__ */
+
+/*
+** Use standard C library malloc and free on non-Apple systems.
+** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
+*/
+#define SQLITE_MALLOC(x) malloc(x)
+#define SQLITE_FREE(x) free(x)
+#define SQLITE_REALLOC(x,y) realloc((x),(y))
+
+/*
+** The malloc.h header file is needed for malloc_usable_size() function
+** on some systems (e.g. Linux).
+*/
+#if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
+# define SQLITE_USE_MALLOC_H 1
+# define SQLITE_USE_MALLOC_USABLE_SIZE 1
+/*
+** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
+** use of _msize() is automatic, but can be disabled by compiling with
+** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
+** the malloc.h header file.
+*/
+#elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
+# define SQLITE_USE_MALLOC_H
+# define SQLITE_USE_MSIZE
+#endif
+
+/*
+** Include the malloc.h header file, if necessary. Also set define macro
+** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
+** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
+** The memory size function can always be overridden manually by defining
+** the macro SQLITE_MALLOCSIZE to the desired function name.
+*/
+#if defined(SQLITE_USE_MALLOC_H)
+# include <malloc.h>
+# if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
+# if !defined(SQLITE_MALLOCSIZE)
+# define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
+# endif
+# elif defined(SQLITE_USE_MSIZE)
+# if !defined(SQLITE_MALLOCSIZE)
+# define SQLITE_MALLOCSIZE _msize
+# endif
+# endif
+#endif /* defined(SQLITE_USE_MALLOC_H) */
+
+#endif /* __APPLE__ or not __APPLE__ */
+
+/*
+** Like malloc(), but remember the size of the allocation
+** so that we can find it later using sqlite3MemSize().
+**
+** For this low-level routine, we are guaranteed that nByte>0 because
+** cases of nByte<=0 will be intercepted and dealt with by higher level
+** routines.
+*/
+static void *sqlite3MemMalloc(int nByte){
+#ifdef SQLITE_MALLOCSIZE
+ void *p;
+ testcase( ROUND8(nByte)==nByte );
+ p = SQLITE_MALLOC( nByte );
+ if( p==0 ){
+ testcase( sqlite3GlobalConfig.xLog!=0 );
+ sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
+ }
+ return p;
+#else
+ sqlite3_int64 *p;
+ assert( nByte>0 );
+ testcase( ROUND8(nByte)!=nByte );
+ p = SQLITE_MALLOC( nByte+8 );
+ if( p ){
+ p[0] = nByte;
+ p++;
+ }else{
+ testcase( sqlite3GlobalConfig.xLog!=0 );
+ sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
+ }
+ return (void *)p;
+#endif
+}
+
+/*
+** Like free() but works for allocations obtained from sqlite3MemMalloc()
+** or sqlite3MemRealloc().
+**
+** For this low-level routine, we already know that pPrior!=0 since
+** cases where pPrior==0 will have been intecepted and dealt with
+** by higher-level routines.
+*/
+static void sqlite3MemFree(void *pPrior){
+#ifdef SQLITE_MALLOCSIZE
+ SQLITE_FREE(pPrior);
+#else
+ sqlite3_int64 *p = (sqlite3_int64*)pPrior;
+ assert( pPrior!=0 );
+ p--;
+ SQLITE_FREE(p);
+#endif
+}
+
+/*
+** Report the allocated size of a prior return from xMalloc()
+** or xRealloc().
+*/
+static int sqlite3MemSize(void *pPrior){
+#ifdef SQLITE_MALLOCSIZE
+ assert( pPrior!=0 );
+ return (int)SQLITE_MALLOCSIZE(pPrior);
+#else
+ sqlite3_int64 *p;
+ assert( pPrior!=0 );
+ p = (sqlite3_int64*)pPrior;
+ p--;
+ return (int)p[0];
+#endif
+}
+
+/*
+** Like realloc(). Resize an allocation previously obtained from
+** sqlite3MemMalloc().
+**
+** For this low-level interface, we know that pPrior!=0. Cases where
+** pPrior==0 while have been intercepted by higher-level routine and
+** redirected to xMalloc. Similarly, we know that nByte>0 because
+** cases where nByte<=0 will have been intercepted by higher-level
+** routines and redirected to xFree.
+*/
+static void *sqlite3MemRealloc(void *pPrior, int nByte){
+#ifdef SQLITE_MALLOCSIZE
+ void *p = SQLITE_REALLOC(pPrior, nByte);
+ if( p==0 ){
+ testcase( sqlite3GlobalConfig.xLog!=0 );
+ sqlite3_log(SQLITE_NOMEM,
+ "failed memory resize %u to %u bytes",
+ SQLITE_MALLOCSIZE(pPrior), nByte);
+ }
+ return p;
+#else
+ sqlite3_int64 *p = (sqlite3_int64*)pPrior;
+ assert( pPrior!=0 && nByte>0 );
+ assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
+ p--;
+ p = SQLITE_REALLOC(p, nByte+8 );
+ if( p ){
+ p[0] = nByte;
+ p++;
+ }else{
+ testcase( sqlite3GlobalConfig.xLog!=0 );
+ sqlite3_log(SQLITE_NOMEM,
+ "failed memory resize %u to %u bytes",
+ sqlite3MemSize(pPrior), nByte);
+ }
+ return (void*)p;
+#endif
+}
+
+/*
+** Round up a request size to the next valid allocation size.
+*/
+static int sqlite3MemRoundup(int n){
+ return ROUND8(n);
+}
+
+/*
+** Initialize this module.
+*/
+static int sqlite3MemInit(void *NotUsed){
+#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
+ int cpuCount;
+ size_t len;
+ if( _sqliteZone_ ){
+ return SQLITE_OK;
+ }
+ len = sizeof(cpuCount);
+ /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
+ sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
+ if( cpuCount>1 ){
+ /* defer MT decisions to system malloc */
+ _sqliteZone_ = malloc_default_zone();
+ }else{
+ /* only 1 core, use our own zone to contention over global locks,
+ ** e.g. we have our own dedicated locks */
+ _sqliteZone_ = malloc_create_zone(4096, 0);
+ malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
+ }
+#endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
+ UNUSED_PARAMETER(NotUsed);
+ return SQLITE_OK;
+}
+
+/*
+** Deinitialize this module.
+*/
+static void sqlite3MemShutdown(void *NotUsed){
+ UNUSED_PARAMETER(NotUsed);
+ return;
+}
+
+/*
+** This routine is the only routine in this file with external linkage.
+**
+** Populate the low-level memory allocation function pointers in
+** sqlite3GlobalConfig.m with pointers to the routines in this file.
+*/
+SQLITE_PRIVATE void sqlite3MemSetDefault(void){
+ static const sqlite3_mem_methods defaultMethods = {
+ sqlite3MemMalloc,
+ sqlite3MemFree,
+ sqlite3MemRealloc,
+ sqlite3MemSize,
+ sqlite3MemRoundup,
+ sqlite3MemInit,
+ sqlite3MemShutdown,
+ 0
+ };
+ sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
+}
+
+#endif /* SQLITE_SYSTEM_MALLOC */
+
+/************** End of mem1.c ************************************************/
+/************** Begin file mem2.c ********************************************/
+/*
+** 2007 August 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains low-level memory allocation drivers for when
+** SQLite will use the standard C-library malloc/realloc/free interface
+** to obtain the memory it needs while adding lots of additional debugging
+** information to each allocation in order to help detect and fix memory
+** leaks and memory usage errors.
+**
+** This file contains implementations of the low-level memory allocation
+** routines specified in the sqlite3_mem_methods object.
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** This version of the memory allocator is used only if the
+** SQLITE_MEMDEBUG macro is defined
+*/
+#ifdef SQLITE_MEMDEBUG
+
+/*
+** The backtrace functionality is only available with GLIBC
+*/
+#ifdef __GLIBC__
+ extern int backtrace(void**,int);
+ extern void backtrace_symbols_fd(void*const*,int,int);
+#else
+# define backtrace(A,B) 1
+# define backtrace_symbols_fd(A,B,C)
+#endif
+/* #include <stdio.h> */
+
+/*
+** Each memory allocation looks like this:
+**
+** ------------------------------------------------------------------------
+** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
+** ------------------------------------------------------------------------
+**
+** The application code sees only a pointer to the allocation. We have
+** to back up from the allocation pointer to find the MemBlockHdr. The
+** MemBlockHdr tells us the size of the allocation and the number of
+** backtrace pointers. There is also a guard word at the end of the
+** MemBlockHdr.
+*/
+struct MemBlockHdr {
+ i64 iSize; /* Size of this allocation */
+ struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
+ char nBacktrace; /* Number of backtraces on this alloc */
+ char nBacktraceSlots; /* Available backtrace slots */
+ u8 nTitle; /* Bytes of title; includes '\0' */
+ u8 eType; /* Allocation type code */
+ int iForeGuard; /* Guard word for sanity */
+};
+
+/*
+** Guard words
+*/
+#define FOREGUARD 0x80F5E153
+#define REARGUARD 0xE4676B53
+
+/*
+** Number of malloc size increments to track.
+*/
+#define NCSIZE 1000
+
+/*
+** All of the static variables used by this module are collected
+** into a single structure named "mem". This is to keep the
+** static variables organized and to reduce namespace pollution
+** when this module is combined with other in the amalgamation.
+*/
+static struct {
+
+ /*
+ ** Mutex to control access to the memory allocation subsystem.
+ */
+ sqlite3_mutex *mutex;
+
+ /*
+ ** Head and tail of a linked list of all outstanding allocations
+ */
+ struct MemBlockHdr *pFirst;
+ struct MemBlockHdr *pLast;
+
+ /*
+ ** The number of levels of backtrace to save in new allocations.
+ */
+ int nBacktrace;
+ void (*xBacktrace)(int, int, void **);
+
+ /*
+ ** Title text to insert in front of each block
+ */
+ int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
+ char zTitle[100]; /* The title text */
+
+ /*
+ ** sqlite3MallocDisallow() increments the following counter.
+ ** sqlite3MallocAllow() decrements it.
+ */
+ int disallow; /* Do not allow memory allocation */
+
+ /*
+ ** Gather statistics on the sizes of memory allocations.
+ ** nAlloc[i] is the number of allocation attempts of i*8
+ ** bytes. i==NCSIZE is the number of allocation attempts for
+ ** sizes more than NCSIZE*8 bytes.
+ */
+ int nAlloc[NCSIZE]; /* Total number of allocations */
+ int nCurrent[NCSIZE]; /* Current number of allocations */
+ int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
+
+} mem;
+
+
+/*
+** Adjust memory usage statistics
+*/
+static void adjustStats(int iSize, int increment){
+ int i = ROUND8(iSize)/8;
+ if( i>NCSIZE-1 ){
+ i = NCSIZE - 1;
+ }
+ if( increment>0 ){
+ mem.nAlloc[i]++;
+ mem.nCurrent[i]++;
+ if( mem.nCurrent[i]>mem.mxCurrent[i] ){
+ mem.mxCurrent[i] = mem.nCurrent[i];
+ }
+ }else{
+ mem.nCurrent[i]--;
+ assert( mem.nCurrent[i]>=0 );
+ }
+}
+
+/*
+** Given an allocation, find the MemBlockHdr for that allocation.
+**
+** This routine checks the guards at either end of the allocation and
+** if they are incorrect it asserts.
+*/
+static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
+ struct MemBlockHdr *p;
+ int *pInt;
+ u8 *pU8;
+ int nReserve;
+
+ p = (struct MemBlockHdr*)pAllocation;
+ p--;
+ assert( p->iForeGuard==(int)FOREGUARD );
+ nReserve = ROUND8(p->iSize);
+ pInt = (int*)pAllocation;
+ pU8 = (u8*)pAllocation;
+ assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
+ /* This checks any of the "extra" bytes allocated due
+ ** to rounding up to an 8 byte boundary to ensure
+ ** they haven't been overwritten.
+ */
+ while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
+ return p;
+}
+
+/*
+** Return the number of bytes currently allocated at address p.
+*/
+static int sqlite3MemSize(void *p){
+ struct MemBlockHdr *pHdr;
+ if( !p ){
+ return 0;
+ }
+ pHdr = sqlite3MemsysGetHeader(p);
+ return (int)pHdr->iSize;
+}
+
+/*
+** Initialize the memory allocation subsystem.
+*/
+static int sqlite3MemInit(void *NotUsed){
+ UNUSED_PARAMETER(NotUsed);
+ assert( (sizeof(struct MemBlockHdr)&7) == 0 );
+ if( !sqlite3GlobalConfig.bMemstat ){
+ /* If memory status is enabled, then the malloc.c wrapper will already
+ ** hold the STATIC_MEM mutex when the routines here are invoked. */
+ mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Deinitialize the memory allocation subsystem.
+*/
+static void sqlite3MemShutdown(void *NotUsed){
+ UNUSED_PARAMETER(NotUsed);
+ mem.mutex = 0;
+}
+
+/*
+** Round up a request size to the next valid allocation size.
+*/
+static int sqlite3MemRoundup(int n){
+ return ROUND8(n);
+}
+
+/*
+** Fill a buffer with pseudo-random bytes. This is used to preset
+** the content of a new memory allocation to unpredictable values and
+** to clear the content of a freed allocation to unpredictable values.
+*/
+static void randomFill(char *pBuf, int nByte){
+ unsigned int x, y, r;
+ x = SQLITE_PTR_TO_INT(pBuf);
+ y = nByte | 1;
+ while( nByte >= 4 ){
+ x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
+ y = y*1103515245 + 12345;
+ r = x ^ y;
+ *(int*)pBuf = r;
+ pBuf += 4;
+ nByte -= 4;
+ }
+ while( nByte-- > 0 ){
+ x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
+ y = y*1103515245 + 12345;
+ r = x ^ y;
+ *(pBuf++) = r & 0xff;
+ }
+}
+
+/*
+** Allocate nByte bytes of memory.
+*/
+static void *sqlite3MemMalloc(int nByte){
+ struct MemBlockHdr *pHdr;
+ void **pBt;
+ char *z;
+ int *pInt;
+ void *p = 0;
+ int totalSize;
+ int nReserve;
+ sqlite3_mutex_enter(mem.mutex);
+ assert( mem.disallow==0 );
+ nReserve = ROUND8(nByte);
+ totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
+ mem.nBacktrace*sizeof(void*) + mem.nTitle;
+ p = malloc(totalSize);
+ if( p ){
+ z = p;
+ pBt = (void**)&z[mem.nTitle];
+ pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
+ pHdr->pNext = 0;
+ pHdr->pPrev = mem.pLast;
+ if( mem.pLast ){
+ mem.pLast->pNext = pHdr;
+ }else{
+ mem.pFirst = pHdr;
+ }
+ mem.pLast = pHdr;
+ pHdr->iForeGuard = FOREGUARD;
+ pHdr->eType = MEMTYPE_HEAP;
+ pHdr->nBacktraceSlots = mem.nBacktrace;
+ pHdr->nTitle = mem.nTitle;
+ if( mem.nBacktrace ){
+ void *aAddr[40];
+ pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
+ memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
+ assert(pBt[0]);
+ if( mem.xBacktrace ){
+ mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
+ }
+ }else{
+ pHdr->nBacktrace = 0;
+ }
+ if( mem.nTitle ){
+ memcpy(z, mem.zTitle, mem.nTitle);
+ }
+ pHdr->iSize = nByte;
+ adjustStats(nByte, +1);
+ pInt = (int*)&pHdr[1];
+ pInt[nReserve/sizeof(int)] = REARGUARD;
+ randomFill((char*)pInt, nByte);
+ memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
+ p = (void*)pInt;
+ }
+ sqlite3_mutex_leave(mem.mutex);
+ return p;
+}
+
+/*
+** Free memory.
+*/
+static void sqlite3MemFree(void *pPrior){
+ struct MemBlockHdr *pHdr;
+ void **pBt;
+ char *z;
+ assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
+ || mem.mutex!=0 );
+ pHdr = sqlite3MemsysGetHeader(pPrior);
+ pBt = (void**)pHdr;
+ pBt -= pHdr->nBacktraceSlots;
+ sqlite3_mutex_enter(mem.mutex);
+ if( pHdr->pPrev ){
+ assert( pHdr->pPrev->pNext==pHdr );
+ pHdr->pPrev->pNext = pHdr->pNext;
+ }else{
+ assert( mem.pFirst==pHdr );
+ mem.pFirst = pHdr->pNext;
+ }
+ if( pHdr->pNext ){
+ assert( pHdr->pNext->pPrev==pHdr );
+ pHdr->pNext->pPrev = pHdr->pPrev;
+ }else{
+ assert( mem.pLast==pHdr );
+ mem.pLast = pHdr->pPrev;
+ }
+ z = (char*)pBt;
+ z -= pHdr->nTitle;
+ adjustStats((int)pHdr->iSize, -1);
+ randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
+ (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
+ free(z);
+ sqlite3_mutex_leave(mem.mutex);
+}
+
+/*
+** Change the size of an existing memory allocation.
+**
+** For this debugging implementation, we *always* make a copy of the
+** allocation into a new place in memory. In this way, if the
+** higher level code is using pointer to the old allocation, it is
+** much more likely to break and we are much more liking to find
+** the error.
+*/
+static void *sqlite3MemRealloc(void *pPrior, int nByte){
+ struct MemBlockHdr *pOldHdr;
+ void *pNew;
+ assert( mem.disallow==0 );
+ assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
+ pOldHdr = sqlite3MemsysGetHeader(pPrior);
+ pNew = sqlite3MemMalloc(nByte);
+ if( pNew ){
+ memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
+ if( nByte>pOldHdr->iSize ){
+ randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
+ }
+ sqlite3MemFree(pPrior);
+ }
+ return pNew;
+}
+
+/*
+** Populate the low-level memory allocation function pointers in
+** sqlite3GlobalConfig.m with pointers to the routines in this file.
+*/
+SQLITE_PRIVATE void sqlite3MemSetDefault(void){
+ static const sqlite3_mem_methods defaultMethods = {
+ sqlite3MemMalloc,
+ sqlite3MemFree,
+ sqlite3MemRealloc,
+ sqlite3MemSize,
+ sqlite3MemRoundup,
+ sqlite3MemInit,
+ sqlite3MemShutdown,
+ 0
+ };
+ sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
+}
+
+/*
+** Set the "type" of an allocation.
+*/
+SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
+ if( p && sqlite3GlobalConfig.m.xFree==sqlite3MemFree ){
+ struct MemBlockHdr *pHdr;
+ pHdr = sqlite3MemsysGetHeader(p);
+ assert( pHdr->iForeGuard==FOREGUARD );
+ pHdr->eType = eType;
+ }
+}
+
+/*
+** Return TRUE if the mask of type in eType matches the type of the
+** allocation p. Also return true if p==NULL.
+**
+** This routine is designed for use within an assert() statement, to
+** verify the type of an allocation. For example:
+**
+** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
+*/
+SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
+ int rc = 1;
+ if( p && sqlite3GlobalConfig.m.xFree==sqlite3MemFree ){
+ struct MemBlockHdr *pHdr;
+ pHdr = sqlite3MemsysGetHeader(p);
+ assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
+ if( (pHdr->eType&eType)==0 ){
+ rc = 0;
+ }
+ }
+ return rc;
+}
+
+/*
+** Return TRUE if the mask of type in eType matches no bits of the type of the
+** allocation p. Also return true if p==NULL.
+**
+** This routine is designed for use within an assert() statement, to
+** verify the type of an allocation. For example:
+**
+** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
+*/
+SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
+ int rc = 1;
+ if( p && sqlite3GlobalConfig.m.xFree==sqlite3MemFree ){
+ struct MemBlockHdr *pHdr;
+ pHdr = sqlite3MemsysGetHeader(p);
+ assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
+ if( (pHdr->eType&eType)!=0 ){
+ rc = 0;
+ }
+ }
+ return rc;
+}
+
+/*
+** Set the number of backtrace levels kept for each allocation.
+** A value of zero turns off backtracing. The number is always rounded
+** up to a multiple of 2.
+*/
+SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
+ if( depth<0 ){ depth = 0; }
+ if( depth>20 ){ depth = 20; }
+ depth = (depth+1)&0xfe;
+ mem.nBacktrace = depth;
+}
+
+SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
+ mem.xBacktrace = xBacktrace;
+}
+
+/*
+** Set the title string for subsequent allocations.
+*/
+SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
+ unsigned int n = sqlite3Strlen30(zTitle) + 1;
+ sqlite3_mutex_enter(mem.mutex);
+ if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
+ memcpy(mem.zTitle, zTitle, n);
+ mem.zTitle[n] = 0;
+ mem.nTitle = ROUND8(n);
+ sqlite3_mutex_leave(mem.mutex);
+}
+
+SQLITE_PRIVATE void sqlite3MemdebugSync(){
+ struct MemBlockHdr *pHdr;
+ for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
+ void **pBt = (void**)pHdr;
+ pBt -= pHdr->nBacktraceSlots;
+ mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
+ }
+}
+
+/*
+** Open the file indicated and write a log of all unfreed memory
+** allocations into that log.
+*/
+SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
+ FILE *out;
+ struct MemBlockHdr *pHdr;
+ void **pBt;
+ int i;
+ out = fopen(zFilename, "w");
+ if( out==0 ){
+ fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
+ zFilename);
+ return;
+ }
+ for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
+ char *z = (char*)pHdr;
+ z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
+ fprintf(out, "**** %lld bytes at %p from %s ****\n",
+ pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
+ if( pHdr->nBacktrace ){
+ fflush(out);
+ pBt = (void**)pHdr;
+ pBt -= pHdr->nBacktraceSlots;
+ backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
+ fprintf(out, "\n");
+ }
+ }
+ fprintf(out, "COUNTS:\n");
+ for(i=0; i<NCSIZE-1; i++){
+ if( mem.nAlloc[i] ){
+ fprintf(out, " %5d: %10d %10d %10d\n",
+ i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
+ }
+ }
+ if( mem.nAlloc[NCSIZE-1] ){
+ fprintf(out, " %5d: %10d %10d %10d\n",
+ NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
+ mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
+ }
+ fclose(out);
+}
+
+/*
+** Return the number of times sqlite3MemMalloc() has been called.
+*/
+SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
+ int i;
+ int nTotal = 0;
+ for(i=0; i<NCSIZE; i++){
+ nTotal += mem.nAlloc[i];
+ }
+ return nTotal;
+}
+
+
+#endif /* SQLITE_MEMDEBUG */
+
+/************** End of mem2.c ************************************************/
+/************** Begin file mem3.c ********************************************/
+/*
+** 2007 October 14
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains the C functions that implement a memory
+** allocation subsystem for use by SQLite.
+**
+** This version of the memory allocation subsystem omits all
+** use of malloc(). The SQLite user supplies a block of memory
+** before calling sqlite3_initialize() from which allocations
+** are made and returned by the xMalloc() and xRealloc()
+** implementations. Once sqlite3_initialize() has been called,
+** the amount of memory available to SQLite is fixed and cannot
+** be changed.
+**
+** This version of the memory allocation subsystem is included
+** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** This version of the memory allocator is only built into the library
+** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
+** mean that the library will use a memory-pool by default, just that
+** it is available. The mempool allocator is activated by calling
+** sqlite3_config().
+*/
+#ifdef SQLITE_ENABLE_MEMSYS3
+
+/*
+** Maximum size (in Mem3Blocks) of a "small" chunk.
+*/
+#define MX_SMALL 10
+
+
+/*
+** Number of freelist hash slots
+*/
+#define N_HASH 61
+
+/*
+** A memory allocation (also called a "chunk") consists of two or
+** more blocks where each block is 8 bytes. The first 8 bytes are
+** a header that is not returned to the user.
+**
+** A chunk is two or more blocks that is either checked out or
+** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
+** size of the allocation in blocks if the allocation is free.
+** The u.hdr.size4x&1 bit is true if the chunk is checked out and
+** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
+** is true if the previous chunk is checked out and false if the
+** previous chunk is free. The u.hdr.prevSize field is the size of
+** the previous chunk in blocks if the previous chunk is on the
+** freelist. If the previous chunk is checked out, then
+** u.hdr.prevSize can be part of the data for that chunk and should
+** not be read or written.
+**
+** We often identify a chunk by its index in mem3.aPool[]. When
+** this is done, the chunk index refers to the second block of
+** the chunk. In this way, the first chunk has an index of 1.
+** A chunk index of 0 means "no such chunk" and is the equivalent
+** of a NULL pointer.
+**
+** The second block of free chunks is of the form u.list. The
+** two fields form a double-linked list of chunks of related sizes.
+** Pointers to the head of the list are stored in mem3.aiSmall[]
+** for smaller chunks and mem3.aiHash[] for larger chunks.
+**
+** The second block of a chunk is user data if the chunk is checked
+** out. If a chunk is checked out, the user data may extend into
+** the u.hdr.prevSize value of the following chunk.
+*/
+typedef struct Mem3Block Mem3Block;
+struct Mem3Block {
+ union {
+ struct {
+ u32 prevSize; /* Size of previous chunk in Mem3Block elements */
+ u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
+ } hdr;
+ struct {
+ u32 next; /* Index in mem3.aPool[] of next free chunk */
+ u32 prev; /* Index in mem3.aPool[] of previous free chunk */
+ } list;
+ } u;
+};
+
+/*
+** All of the static variables used by this module are collected
+** into a single structure named "mem3". This is to keep the
+** static variables organized and to reduce namespace pollution
+** when this module is combined with other in the amalgamation.
+*/
+static SQLITE_WSD struct Mem3Global {
+ /*
+ ** Memory available for allocation. nPool is the size of the array
+ ** (in Mem3Blocks) pointed to by aPool less 2.
+ */
+ u32 nPool;
+ Mem3Block *aPool;
+
+ /*
+ ** True if we are evaluating an out-of-memory callback.
+ */
+ int alarmBusy;
+
+ /*
+ ** Mutex to control access to the memory allocation subsystem.
+ */
+ sqlite3_mutex *mutex;
+
+ /*
+ ** The minimum amount of free space that we have seen.
+ */
+ u32 mnKeyBlk;
+
+ /*
+ ** iKeyBlk is the index of the key chunk. Most new allocations
+ ** occur off of this chunk. szKeyBlk is the size (in Mem3Blocks)
+ ** of the current key chunk. iKeyBlk is 0 if there is no key chunk.
+ ** The key chunk is not in either the aiHash[] or aiSmall[].
+ */
+ u32 iKeyBlk;
+ u32 szKeyBlk;
+
+ /*
+ ** Array of lists of free blocks according to the block size
+ ** for smaller chunks, or a hash on the block size for larger
+ ** chunks.
+ */
+ u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
+ u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
+} mem3 = { 97535575 };
+
+#define mem3 GLOBAL(struct Mem3Global, mem3)
+
+/*
+** Unlink the chunk at mem3.aPool[i] from list it is currently
+** on. *pRoot is the list that i is a member of.
+*/
+static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
+ u32 next = mem3.aPool[i].u.list.next;
+ u32 prev = mem3.aPool[i].u.list.prev;
+ assert( sqlite3_mutex_held(mem3.mutex) );
+ if( prev==0 ){
+ *pRoot = next;
+ }else{
+ mem3.aPool[prev].u.list.next = next;
+ }
+ if( next ){
+ mem3.aPool[next].u.list.prev = prev;
+ }
+ mem3.aPool[i].u.list.next = 0;
+ mem3.aPool[i].u.list.prev = 0;
+}
+
+/*
+** Unlink the chunk at index i from
+** whatever list is currently a member of.
+*/
+static void memsys3Unlink(u32 i){
+ u32 size, hash;
+ assert( sqlite3_mutex_held(mem3.mutex) );
+ assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
+ assert( i>=1 );
+ size = mem3.aPool[i-1].u.hdr.size4x/4;
+ assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
+ assert( size>=2 );
+ if( size <= MX_SMALL ){
+ memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
+ }else{
+ hash = size % N_HASH;
+ memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
+ }
+}
+
+/*
+** Link the chunk at mem3.aPool[i] so that is on the list rooted
+** at *pRoot.
+*/
+static void memsys3LinkIntoList(u32 i, u32 *pRoot){
+ assert( sqlite3_mutex_held(mem3.mutex) );
+ mem3.aPool[i].u.list.next = *pRoot;
+ mem3.aPool[i].u.list.prev = 0;
+ if( *pRoot ){
+ mem3.aPool[*pRoot].u.list.prev = i;
+ }
+ *pRoot = i;
+}
+
+/*
+** Link the chunk at index i into either the appropriate
+** small chunk list, or into the large chunk hash table.
+*/
+static void memsys3Link(u32 i){
+ u32 size, hash;
+ assert( sqlite3_mutex_held(mem3.mutex) );
+ assert( i>=1 );
+ assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
+ size = mem3.aPool[i-1].u.hdr.size4x/4;
+ assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
+ assert( size>=2 );
+ if( size <= MX_SMALL ){
+ memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
+ }else{
+ hash = size % N_HASH;
+ memsys3LinkIntoList(i, &mem3.aiHash[hash]);
+ }
+}
+
+/*
+** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
+** will already be held (obtained by code in malloc.c) if
+** sqlite3GlobalConfig.bMemStat is true.
+*/
+static void memsys3Enter(void){
+ if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
+ mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
+ }
+ sqlite3_mutex_enter(mem3.mutex);
+}
+static void memsys3Leave(void){
+ sqlite3_mutex_leave(mem3.mutex);
+}
+
+/*
+** Called when we are unable to satisfy an allocation of nBytes.
+*/
+static void memsys3OutOfMemory(int nByte){
+ if( !mem3.alarmBusy ){
+ mem3.alarmBusy = 1;
+ assert( sqlite3_mutex_held(mem3.mutex) );
+ sqlite3_mutex_leave(mem3.mutex);
+ sqlite3_release_memory(nByte);
+ sqlite3_mutex_enter(mem3.mutex);
+ mem3.alarmBusy = 0;
+ }
+}
+
+
+/*
+** Chunk i is a free chunk that has been unlinked. Adjust its
+** size parameters for check-out and return a pointer to the
+** user portion of the chunk.
+*/
+static void *memsys3Checkout(u32 i, u32 nBlock){
+ u32 x;
+ assert( sqlite3_mutex_held(mem3.mutex) );
+ assert( i>=1 );
+ assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
+ assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
+ x = mem3.aPool[i-1].u.hdr.size4x;
+ mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
+ mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
+ mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
+ return &mem3.aPool[i];
+}
+
+/*
+** Carve a piece off of the end of the mem3.iKeyBlk free chunk.
+** Return a pointer to the new allocation. Or, if the key chunk
+** is not large enough, return 0.
+*/
+static void *memsys3FromKeyBlk(u32 nBlock){
+ assert( sqlite3_mutex_held(mem3.mutex) );
+ assert( mem3.szKeyBlk>=nBlock );
+ if( nBlock>=mem3.szKeyBlk-1 ){
+ /* Use the entire key chunk */
+ void *p = memsys3Checkout(mem3.iKeyBlk, mem3.szKeyBlk);
+ mem3.iKeyBlk = 0;
+ mem3.szKeyBlk = 0;
+ mem3.mnKeyBlk = 0;
+ return p;
+ }else{
+ /* Split the key block. Return the tail. */
+ u32 newi, x;
+ newi = mem3.iKeyBlk + mem3.szKeyBlk - nBlock;
+ assert( newi > mem3.iKeyBlk+1 );
+ mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = nBlock;
+ mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x |= 2;
+ mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
+ mem3.szKeyBlk -= nBlock;
+ mem3.aPool[newi-1].u.hdr.prevSize = mem3.szKeyBlk;
+ x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
+ mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
+ if( mem3.szKeyBlk < mem3.mnKeyBlk ){
+ mem3.mnKeyBlk = mem3.szKeyBlk;
+ }
+ return (void*)&mem3.aPool[newi];
+ }
+}
+
+/*
+** *pRoot is the head of a list of free chunks of the same size
+** or same size hash. In other words, *pRoot is an entry in either
+** mem3.aiSmall[] or mem3.aiHash[].
+**
+** This routine examines all entries on the given list and tries
+** to coalesce each entries with adjacent free chunks.
+**
+** If it sees a chunk that is larger than mem3.iKeyBlk, it replaces
+** the current mem3.iKeyBlk with the new larger chunk. In order for
+** this mem3.iKeyBlk replacement to work, the key chunk must be
+** linked into the hash tables. That is not the normal state of
+** affairs, of course. The calling routine must link the key
+** chunk before invoking this routine, then must unlink the (possibly
+** changed) key chunk once this routine has finished.
+*/
+static void memsys3Merge(u32 *pRoot){
+ u32 iNext, prev, size, i, x;
+
+ assert( sqlite3_mutex_held(mem3.mutex) );
+ for(i=*pRoot; i>0; i=iNext){
+ iNext = mem3.aPool[i].u.list.next;
+ size = mem3.aPool[i-1].u.hdr.size4x;
+ assert( (size&1)==0 );
+ if( (size&2)==0 ){
+ memsys3UnlinkFromList(i, pRoot);
+ assert( i > mem3.aPool[i-1].u.hdr.prevSize );
+ prev = i - mem3.aPool[i-1].u.hdr.prevSize;
+ if( prev==iNext ){
+ iNext = mem3.aPool[prev].u.list.next;
+ }
+ memsys3Unlink(prev);
+ size = i + size/4 - prev;
+ x = mem3.aPool[prev-1].u.hdr.size4x & 2;
+ mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
+ mem3.aPool[prev+size-1].u.hdr.prevSize = size;
+ memsys3Link(prev);
+ i = prev;
+ }else{
+ size /= 4;
+ }
+ if( size>mem3.szKeyBlk ){
+ mem3.iKeyBlk = i;
+ mem3.szKeyBlk = size;
+ }
+ }
+}
+
+/*
+** Return a block of memory of at least nBytes in size.
+** Return NULL if unable.
+**
+** This function assumes that the necessary mutexes, if any, are
+** already held by the caller. Hence "Unsafe".
+*/
+static void *memsys3MallocUnsafe(int nByte){
+ u32 i;
+ u32 nBlock;
+ u32 toFree;
+
+ assert( sqlite3_mutex_held(mem3.mutex) );
+ assert( sizeof(Mem3Block)==8 );
+ if( nByte<=12 ){
+ nBlock = 2;
+ }else{
+ nBlock = (nByte + 11)/8;
+ }
+ assert( nBlock>=2 );
+
+ /* STEP 1:
+ ** Look for an entry of the correct size in either the small
+ ** chunk table or in the large chunk hash table. This is
+ ** successful most of the time (about 9 times out of 10).
+ */
+ if( nBlock <= MX_SMALL ){
+ i = mem3.aiSmall[nBlock-2];
+ if( i>0 ){
+ memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
+ return memsys3Checkout(i, nBlock);
+ }
+ }else{
+ int hash = nBlock % N_HASH;
+ for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
+ if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
+ memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
+ return memsys3Checkout(i, nBlock);
+ }
+ }
+ }
+
+ /* STEP 2:
+ ** Try to satisfy the allocation by carving a piece off of the end
+ ** of the key chunk. This step usually works if step 1 fails.
+ */
+ if( mem3.szKeyBlk>=nBlock ){
+ return memsys3FromKeyBlk(nBlock);
+ }
+
+
+ /* STEP 3:
+ ** Loop through the entire memory pool. Coalesce adjacent free
+ ** chunks. Recompute the key chunk as the largest free chunk.
+ ** Then try again to satisfy the allocation by carving a piece off
+ ** of the end of the key chunk. This step happens very
+ ** rarely (we hope!)
+ */
+ for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
+ memsys3OutOfMemory(toFree);
+ if( mem3.iKeyBlk ){
+ memsys3Link(mem3.iKeyBlk);
+ mem3.iKeyBlk = 0;
+ mem3.szKeyBlk = 0;
+ }
+ for(i=0; i<N_HASH; i++){
+ memsys3Merge(&mem3.aiHash[i]);
+ }
+ for(i=0; i<MX_SMALL-1; i++){
+ memsys3Merge(&mem3.aiSmall[i]);
+ }
+ if( mem3.szKeyBlk ){
+ memsys3Unlink(mem3.iKeyBlk);
+ if( mem3.szKeyBlk>=nBlock ){
+ return memsys3FromKeyBlk(nBlock);
+ }
+ }
+ }
+
+ /* If none of the above worked, then we fail. */
+ return 0;
+}
+
+/*
+** Free an outstanding memory allocation.
+**
+** This function assumes that the necessary mutexes, if any, are
+** already held by the caller. Hence "Unsafe".
+*/
+static void memsys3FreeUnsafe(void *pOld){
+ Mem3Block *p = (Mem3Block*)pOld;
+ int i;
+ u32 size, x;
+ assert( sqlite3_mutex_held(mem3.mutex) );
+ assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
+ i = p - mem3.aPool;
+ assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
+ size = mem3.aPool[i-1].u.hdr.size4x/4;
+ assert( i+size<=mem3.nPool+1 );
+ mem3.aPool[i-1].u.hdr.size4x &= ~1;
+ mem3.aPool[i+size-1].u.hdr.prevSize = size;
+ mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
+ memsys3Link(i);
+
+ /* Try to expand the key using the newly freed chunk */
+ if( mem3.iKeyBlk ){
+ while( (mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x&2)==0 ){
+ size = mem3.aPool[mem3.iKeyBlk-1].u.hdr.prevSize;
+ mem3.iKeyBlk -= size;
+ mem3.szKeyBlk += size;
+ memsys3Unlink(mem3.iKeyBlk);
+ x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
+ mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
+ mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk;
+ }
+ x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
+ while( (mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x&1)==0 ){
+ memsys3Unlink(mem3.iKeyBlk+mem3.szKeyBlk);
+ mem3.szKeyBlk += mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x/4;
+ mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
+ mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk;
+ }
+ }
+}
+
+/*
+** Return the size of an outstanding allocation, in bytes. The
+** size returned omits the 8-byte header overhead. This only
+** works for chunks that are currently checked out.
+*/
+static int memsys3Size(void *p){
+ Mem3Block *pBlock;
+ assert( p!=0 );
+ pBlock = (Mem3Block*)p;
+ assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
+ return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
+}
+
+/*
+** Round up a request size to the next valid allocation size.
+*/
+static int memsys3Roundup(int n){
+ if( n<=12 ){
+ return 12;
+ }else{
+ return ((n+11)&~7) - 4;
+ }
+}
+
+/*
+** Allocate nBytes of memory.
+*/
+static void *memsys3Malloc(int nBytes){
+ sqlite3_int64 *p;
+ assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
+ memsys3Enter();
+ p = memsys3MallocUnsafe(nBytes);
+ memsys3Leave();
+ return (void*)p;
+}
+
+/*
+** Free memory.
+*/
+static void memsys3Free(void *pPrior){
+ assert( pPrior );
+ memsys3Enter();
+ memsys3FreeUnsafe(pPrior);
+ memsys3Leave();
+}
+
+/*
+** Change the size of an existing memory allocation
+*/
+static void *memsys3Realloc(void *pPrior, int nBytes){
+ int nOld;
+ void *p;
+ if( pPrior==0 ){
+ return sqlite3_malloc(nBytes);
+ }
+ if( nBytes<=0 ){
+ sqlite3_free(pPrior);
+ return 0;
+ }
+ nOld = memsys3Size(pPrior);
+ if( nBytes<=nOld && nBytes>=nOld-128 ){
+ return pPrior;
+ }
+ memsys3Enter();
+ p = memsys3MallocUnsafe(nBytes);
+ if( p ){
+ if( nOld<nBytes ){
+ memcpy(p, pPrior, nOld);
+ }else{
+ memcpy(p, pPrior, nBytes);
+ }
+ memsys3FreeUnsafe(pPrior);
+ }
+ memsys3Leave();
+ return p;
+}
+
+/*
+** Initialize this module.
+*/
+static int memsys3Init(void *NotUsed){
+ UNUSED_PARAMETER(NotUsed);
+ if( !sqlite3GlobalConfig.pHeap ){
+ return SQLITE_ERROR;
+ }
+
+ /* Store a pointer to the memory block in global structure mem3. */
+ assert( sizeof(Mem3Block)==8 );
+ mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
+ mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
+
+ /* Initialize the key block. */
+ mem3.szKeyBlk = mem3.nPool;
+ mem3.mnKeyBlk = mem3.szKeyBlk;
+ mem3.iKeyBlk = 1;
+ mem3.aPool[0].u.hdr.size4x = (mem3.szKeyBlk<<2) + 2;
+ mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
+ mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
+
+ return SQLITE_OK;
+}
+
+/*
+** Deinitialize this module.
+*/
+static void memsys3Shutdown(void *NotUsed){
+ UNUSED_PARAMETER(NotUsed);
+ mem3.mutex = 0;
+ return;
+}
+
+
+
+/*
+** Open the file indicated and write a log of all unfreed memory
+** allocations into that log.
+*/
+SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
+#ifdef SQLITE_DEBUG
+ FILE *out;
+ u32 i, j;
+ u32 size;
+ if( zFilename==0 || zFilename[0]==0 ){
+ out = stdout;
+ }else{
+ out = fopen(zFilename, "w");
+ if( out==0 ){
+ fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
+ zFilename);
+ return;
+ }
+ }
+ memsys3Enter();
+ fprintf(out, "CHUNKS:\n");
+ for(i=1; i<=mem3.nPool; i+=size/4){
+ size = mem3.aPool[i-1].u.hdr.size4x;
+ if( size/4<=1 ){
+ fprintf(out, "%p size error\n", &mem3.aPool[i]);
+ assert( 0 );
+ break;
+ }
+ if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
+ fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
+ assert( 0 );
+ break;
+ }
+ if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
+ fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
+ assert( 0 );
+ break;
+ }
+ if( size&1 ){
+ fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
+ }else{
+ fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
+ i==mem3.iKeyBlk ? " **key**" : "");
+ }
+ }
+ for(i=0; i<MX_SMALL-1; i++){
+ if( mem3.aiSmall[i]==0 ) continue;
+ fprintf(out, "small(%2d):", i);
+ for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
+ fprintf(out, " %p(%d)", &mem3.aPool[j],
+ (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
+ }
+ fprintf(out, "\n");
+ }
+ for(i=0; i<N_HASH; i++){
+ if( mem3.aiHash[i]==0 ) continue;
+ fprintf(out, "hash(%2d):", i);
+ for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
+ fprintf(out, " %p(%d)", &mem3.aPool[j],
+ (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
+ }
+ fprintf(out, "\n");
+ }
+ fprintf(out, "key=%d\n", mem3.iKeyBlk);
+ fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szKeyBlk*8);
+ fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnKeyBlk*8);
+ sqlite3_mutex_leave(mem3.mutex);
+ if( out==stdout ){
+ fflush(stdout);
+ }else{
+ fclose(out);
+ }
+#else
+ UNUSED_PARAMETER(zFilename);
+#endif
+}
+
+/*
+** This routine is the only routine in this file with external
+** linkage.
+**
+** Populate the low-level memory allocation function pointers in
+** sqlite3GlobalConfig.m with pointers to the routines in this file. The
+** arguments specify the block of memory to manage.
+**
+** This routine is only called by sqlite3_config(), and therefore
+** is not required to be threadsafe (it is not).
+*/
+SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
+ static const sqlite3_mem_methods mempoolMethods = {
+ memsys3Malloc,
+ memsys3Free,
+ memsys3Realloc,
+ memsys3Size,
+ memsys3Roundup,
+ memsys3Init,
+ memsys3Shutdown,
+ 0
+ };
+ return &mempoolMethods;
+}
+
+#endif /* SQLITE_ENABLE_MEMSYS3 */
+
+/************** End of mem3.c ************************************************/
+/************** Begin file mem5.c ********************************************/
+/*
+** 2007 October 14
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains the C functions that implement a memory
+** allocation subsystem for use by SQLite.
+**
+** This version of the memory allocation subsystem omits all
+** use of malloc(). The application gives SQLite a block of memory
+** before calling sqlite3_initialize() from which allocations
+** are made and returned by the xMalloc() and xRealloc()
+** implementations. Once sqlite3_initialize() has been called,
+** the amount of memory available to SQLite is fixed and cannot
+** be changed.
+**
+** This version of the memory allocation subsystem is included
+** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
+**
+** This memory allocator uses the following algorithm:
+**
+** 1. All memory allocation sizes are rounded up to a power of 2.
+**
+** 2. If two adjacent free blocks are the halves of a larger block,
+** then the two blocks are coalesced into the single larger block.
+**
+** 3. New memory is allocated from the first available free block.
+**
+** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
+** Concerning Dynamic Storage Allocation". Journal of the Association for
+** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
+**
+** Let n be the size of the largest allocation divided by the minimum
+** allocation size (after rounding all sizes up to a power of 2.) Let M
+** be the maximum amount of memory ever outstanding at one time. Let
+** N be the total amount of memory available for allocation. Robson
+** proved that this memory allocator will never breakdown due to
+** fragmentation as long as the following constraint holds:
+**
+** N >= M*(1 + log2(n)/2) - n + 1
+**
+** The sqlite3_status() logic tracks the maximum values of n and M so
+** that an application can, at any time, verify this constraint.
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** This version of the memory allocator is used only when
+** SQLITE_ENABLE_MEMSYS5 is defined.
+*/
+#ifdef SQLITE_ENABLE_MEMSYS5
+
+/*
+** A minimum allocation is an instance of the following structure.
+** Larger allocations are an array of these structures where the
+** size of the array is a power of 2.
+**
+** The size of this object must be a power of two. That fact is
+** verified in memsys5Init().
+*/
+typedef struct Mem5Link Mem5Link;
+struct Mem5Link {
+ int next; /* Index of next free chunk */
+ int prev; /* Index of previous free chunk */
+};
+
+/*
+** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
+** mem5.szAtom is always at least 8 and 32-bit integers are used,
+** it is not actually possible to reach this limit.
+*/
+#define LOGMAX 30
+
+/*
+** Masks used for mem5.aCtrl[] elements.
+*/
+#define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
+#define CTRL_FREE 0x20 /* True if not checked out */
+
+/*
+** All of the static variables used by this module are collected
+** into a single structure named "mem5". This is to keep the
+** static variables organized and to reduce namespace pollution
+** when this module is combined with other in the amalgamation.
+*/
+static SQLITE_WSD struct Mem5Global {
+ /*
+ ** Memory available for allocation
+ */
+ int szAtom; /* Smallest possible allocation in bytes */
+ int nBlock; /* Number of szAtom sized blocks in zPool */
+ u8 *zPool; /* Memory available to be allocated */
+
+ /*
+ ** Mutex to control access to the memory allocation subsystem.
+ */
+ sqlite3_mutex *mutex;
+
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+ /*
+ ** Performance statistics
+ */
+ u64 nAlloc; /* Total number of calls to malloc */
+ u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
+ u64 totalExcess; /* Total internal fragmentation */
+ u32 currentOut; /* Current checkout, including internal fragmentation */
+ u32 currentCount; /* Current number of distinct checkouts */
+ u32 maxOut; /* Maximum instantaneous currentOut */
+ u32 maxCount; /* Maximum instantaneous currentCount */
+ u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
+#endif
+
+ /*
+ ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
+ ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
+ ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
+ */
+ int aiFreelist[LOGMAX+1];
+
+ /*
+ ** Space for tracking which blocks are checked out and the size
+ ** of each block. One byte per block.
+ */
+ u8 *aCtrl;
+
+} mem5;
+
+/*
+** Access the static variable through a macro for SQLITE_OMIT_WSD.
+*/
+#define mem5 GLOBAL(struct Mem5Global, mem5)
+
+/*
+** Assuming mem5.zPool is divided up into an array of Mem5Link
+** structures, return a pointer to the idx-th such link.
+*/
+#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
+
+/*
+** Unlink the chunk at mem5.aPool[i] from list it is currently
+** on. It should be found on mem5.aiFreelist[iLogsize].
+*/
+static void memsys5Unlink(int i, int iLogsize){
+ int next, prev;
+ assert( i>=0 && i<mem5.nBlock );
+ assert( iLogsize>=0 && iLogsize<=LOGMAX );
+ assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
+
+ next = MEM5LINK(i)->next;
+ prev = MEM5LINK(i)->prev;
+ if( prev<0 ){
+ mem5.aiFreelist[iLogsize] = next;
+ }else{
+ MEM5LINK(prev)->next = next;
+ }
+ if( next>=0 ){
+ MEM5LINK(next)->prev = prev;
+ }
+}
+
+/*
+** Link the chunk at mem5.aPool[i] so that is on the iLogsize
+** free list.
+*/
+static void memsys5Link(int i, int iLogsize){
+ int x;
+ assert( sqlite3_mutex_held(mem5.mutex) );
+ assert( i>=0 && i<mem5.nBlock );
+ assert( iLogsize>=0 && iLogsize<=LOGMAX );
+ assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
+
+ x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
+ MEM5LINK(i)->prev = -1;
+ if( x>=0 ){
+ assert( x<mem5.nBlock );
+ MEM5LINK(x)->prev = i;
+ }
+ mem5.aiFreelist[iLogsize] = i;
+}
+
+/*
+** Obtain or release the mutex needed to access global data structures.
+*/
+static void memsys5Enter(void){
+ sqlite3_mutex_enter(mem5.mutex);
+}
+static void memsys5Leave(void){
+ sqlite3_mutex_leave(mem5.mutex);
+}
+
+/*
+** Return the size of an outstanding allocation, in bytes.
+** This only works for chunks that are currently checked out.
+*/
+static int memsys5Size(void *p){
+ int iSize, i;
+ assert( p!=0 );
+ i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
+ assert( i>=0 && i<mem5.nBlock );
+ iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
+ return iSize;
+}
+
+/*
+** Return a block of memory of at least nBytes in size.
+** Return NULL if unable. Return NULL if nBytes==0.
+**
+** The caller guarantees that nByte is positive.
+**
+** The caller has obtained a mutex prior to invoking this
+** routine so there is never any chance that two or more
+** threads can be in this routine at the same time.
+*/
+static void *memsys5MallocUnsafe(int nByte){
+ int i; /* Index of a mem5.aPool[] slot */
+ int iBin; /* Index into mem5.aiFreelist[] */
+ int iFullSz; /* Size of allocation rounded up to power of 2 */
+ int iLogsize; /* Log2 of iFullSz/POW2_MIN */
+
+ /* nByte must be a positive */
+ assert( nByte>0 );
+
+ /* No more than 1GiB per allocation */
+ if( nByte > 0x40000000 ) return 0;
+
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+ /* Keep track of the maximum allocation request. Even unfulfilled
+ ** requests are counted */
+ if( (u32)nByte>mem5.maxRequest ){
+ mem5.maxRequest = nByte;
+ }
+#endif
+
+
+ /* Round nByte up to the next valid power of two */
+ for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
+
+ /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
+ ** block. If not, then split a block of the next larger power of
+ ** two in order to create a new free block of size iLogsize.
+ */
+ for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
+ if( iBin>LOGMAX ){
+ testcase( sqlite3GlobalConfig.xLog!=0 );
+ sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
+ return 0;
+ }
+ i = mem5.aiFreelist[iBin];
+ memsys5Unlink(i, iBin);
+ while( iBin>iLogsize ){
+ int newSize;
+
+ iBin--;
+ newSize = 1 << iBin;
+ mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
+ memsys5Link(i+newSize, iBin);
+ }
+ mem5.aCtrl[i] = iLogsize;
+
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+ /* Update allocator performance statistics. */
+ mem5.nAlloc++;
+ mem5.totalAlloc += iFullSz;
+ mem5.totalExcess += iFullSz - nByte;
+ mem5.currentCount++;
+ mem5.currentOut += iFullSz;
+ if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
+ if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
+#endif
+
+#ifdef SQLITE_DEBUG
+ /* Make sure the allocated memory does not assume that it is set to zero
+ ** or retains a value from a previous allocation */
+ memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
+#endif
+
+ /* Return a pointer to the allocated memory. */
+ return (void*)&mem5.zPool[i*mem5.szAtom];
+}
+
+/*
+** Free an outstanding memory allocation.
+*/
+static void memsys5FreeUnsafe(void *pOld){
+ u32 size, iLogsize;
+ int iBlock;
+
+ /* Set iBlock to the index of the block pointed to by pOld in
+ ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
+ */
+ iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
+
+ /* Check that the pointer pOld points to a valid, non-free block. */
+ assert( iBlock>=0 && iBlock<mem5.nBlock );
+ assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
+ assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
+
+ iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
+ size = 1<<iLogsize;
+ assert( iBlock+size-1<(u32)mem5.nBlock );
+
+ mem5.aCtrl[iBlock] |= CTRL_FREE;
+ mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
+
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+ assert( mem5.currentCount>0 );
+ assert( mem5.currentOut>=(size*mem5.szAtom) );
+ mem5.currentCount--;
+ mem5.currentOut -= size*mem5.szAtom;
+ assert( mem5.currentOut>0 || mem5.currentCount==0 );
+ assert( mem5.currentCount>0 || mem5.currentOut==0 );
+#endif
+
+ mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
+ while( ALWAYS(iLogsize<LOGMAX) ){
+ int iBuddy;
+ if( (iBlock>>iLogsize) & 1 ){
+ iBuddy = iBlock - size;
+ assert( iBuddy>=0 );
+ }else{
+ iBuddy = iBlock + size;
+ if( iBuddy>=mem5.nBlock ) break;
+ }
+ if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
+ memsys5Unlink(iBuddy, iLogsize);
+ iLogsize++;
+ if( iBuddy<iBlock ){
+ mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
+ mem5.aCtrl[iBlock] = 0;
+ iBlock = iBuddy;
+ }else{
+ mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
+ mem5.aCtrl[iBuddy] = 0;
+ }
+ size *= 2;
+ }
+
+#ifdef SQLITE_DEBUG
+ /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
+ ** not used after being freed */
+ memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
+#endif
+
+ memsys5Link(iBlock, iLogsize);
+}
+
+/*
+** Allocate nBytes of memory.
+*/
+static void *memsys5Malloc(int nBytes){
+ sqlite3_int64 *p = 0;
+ if( nBytes>0 ){
+ memsys5Enter();
+ p = memsys5MallocUnsafe(nBytes);
+ memsys5Leave();
+ }
+ return (void*)p;
+}
+
+/*
+** Free memory.
+**
+** The outer layer memory allocator prevents this routine from
+** being called with pPrior==0.
+*/
+static void memsys5Free(void *pPrior){
+ assert( pPrior!=0 );
+ memsys5Enter();
+ memsys5FreeUnsafe(pPrior);
+ memsys5Leave();
+}
+
+/*
+** Change the size of an existing memory allocation.
+**
+** The outer layer memory allocator prevents this routine from
+** being called with pPrior==0.
+**
+** nBytes is always a value obtained from a prior call to
+** memsys5Round(). Hence nBytes is always a non-negative power
+** of two. If nBytes==0 that means that an oversize allocation
+** (an allocation larger than 0x40000000) was requested and this
+** routine should return 0 without freeing pPrior.
+*/
+static void *memsys5Realloc(void *pPrior, int nBytes){
+ int nOld;
+ void *p;
+ assert( pPrior!=0 );
+ assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
+ assert( nBytes>=0 );
+ if( nBytes==0 ){
+ return 0;
+ }
+ nOld = memsys5Size(pPrior);
+ if( nBytes<=nOld ){
+ return pPrior;
+ }
+ p = memsys5Malloc(nBytes);
+ if( p ){
+ memcpy(p, pPrior, nOld);
+ memsys5Free(pPrior);
+ }
+ return p;
+}
+
+/*
+** Round up a request size to the next valid allocation size. If
+** the allocation is too large to be handled by this allocation system,
+** return 0.
+**
+** All allocations must be a power of two and must be expressed by a
+** 32-bit signed integer. Hence the largest allocation is 0x40000000
+** or 1073741824 bytes.
+*/
+static int memsys5Roundup(int n){
+ int iFullSz;
+ if( n > 0x40000000 ) return 0;
+ for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
+ return iFullSz;
+}
+
+/*
+** Return the ceiling of the logarithm base 2 of iValue.
+**
+** Examples: memsys5Log(1) -> 0
+** memsys5Log(2) -> 1
+** memsys5Log(4) -> 2
+** memsys5Log(5) -> 3
+** memsys5Log(8) -> 3
+** memsys5Log(9) -> 4
+*/
+static int memsys5Log(int iValue){
+ int iLog;
+ for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
+ return iLog;
+}
+
+/*
+** Initialize the memory allocator.
+**
+** This routine is not threadsafe. The caller must be holding a mutex
+** to prevent multiple threads from entering at the same time.
+*/
+static int memsys5Init(void *NotUsed){
+ int ii; /* Loop counter */
+ int nByte; /* Number of bytes of memory available to this allocator */
+ u8 *zByte; /* Memory usable by this allocator */
+ int nMinLog; /* Log base 2 of minimum allocation size in bytes */
+ int iOffset; /* An offset into mem5.aCtrl[] */
+
+ UNUSED_PARAMETER(NotUsed);
+
+ /* For the purposes of this routine, disable the mutex */
+ mem5.mutex = 0;
+
+ /* The size of a Mem5Link object must be a power of two. Verify that
+ ** this is case.
+ */
+ assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
+
+ nByte = sqlite3GlobalConfig.nHeap;
+ zByte = (u8*)sqlite3GlobalConfig.pHeap;
+ assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
+
+ /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
+ nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
+ mem5.szAtom = (1<<nMinLog);
+ while( (int)sizeof(Mem5Link)>mem5.szAtom ){
+ mem5.szAtom = mem5.szAtom << 1;
+ }
+
+ mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
+ mem5.zPool = zByte;
+ mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
+
+ for(ii=0; ii<=LOGMAX; ii++){
+ mem5.aiFreelist[ii] = -1;
+ }
+
+ iOffset = 0;
+ for(ii=LOGMAX; ii>=0; ii--){
+ int nAlloc = (1<<ii);
+ if( (iOffset+nAlloc)<=mem5.nBlock ){
+ mem5.aCtrl[iOffset] = ii | CTRL_FREE;
+ memsys5Link(iOffset, ii);
+ iOffset += nAlloc;
+ }
+ assert((iOffset+nAlloc)>mem5.nBlock);
+ }
+
+ /* If a mutex is required for normal operation, allocate one */
+ if( sqlite3GlobalConfig.bMemstat==0 ){
+ mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
+ }
+
+ return SQLITE_OK;
+}
+
+/*
+** Deinitialize this module.
+*/
+static void memsys5Shutdown(void *NotUsed){
+ UNUSED_PARAMETER(NotUsed);
+ mem5.mutex = 0;
+ return;
+}
+
+#ifdef SQLITE_TEST
+/*
+** Open the file indicated and write a log of all unfreed memory
+** allocations into that log.
+*/
+SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
+ FILE *out;
+ int i, j, n;
+ int nMinLog;
+
+ if( zFilename==0 || zFilename[0]==0 ){
+ out = stdout;
+ }else{
+ out = fopen(zFilename, "w");
+ if( out==0 ){
+ fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
+ zFilename);
+ return;
+ }
+ }
+ memsys5Enter();
+ nMinLog = memsys5Log(mem5.szAtom);
+ for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
+ for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
+ fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
+ }
+ fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
+ fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
+ fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
+ fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
+ fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
+ fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
+ fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
+ fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
+ memsys5Leave();
+ if( out==stdout ){
+ fflush(stdout);
+ }else{
+ fclose(out);
+ }
+}
+#endif
+
+/*
+** This routine is the only routine in this file with external
+** linkage. It returns a pointer to a static sqlite3_mem_methods
+** struct populated with the memsys5 methods.
+*/
+SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
+ static const sqlite3_mem_methods memsys5Methods = {
+ memsys5Malloc,
+ memsys5Free,
+ memsys5Realloc,
+ memsys5Size,
+ memsys5Roundup,
+ memsys5Init,
+ memsys5Shutdown,
+ 0
+ };
+ return &memsys5Methods;
+}
+
+#endif /* SQLITE_ENABLE_MEMSYS5 */
+
+/************** End of mem5.c ************************************************/
+/************** Begin file mutex.c *******************************************/
+/*
+** 2007 August 14
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains the C functions that implement mutexes.
+**
+** This file contains code that is common across all mutex implementations.
+*/
+/* #include "sqliteInt.h" */
+
+#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
+/*
+** For debugging purposes, record when the mutex subsystem is initialized
+** and uninitialized so that we can assert() if there is an attempt to
+** allocate a mutex while the system is uninitialized.
+*/
+static SQLITE_WSD int mutexIsInit = 0;
+#endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
+
+
+#ifndef SQLITE_MUTEX_OMIT
+
+#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
+/*
+** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains
+** the implementation of a wrapper around the system default mutex
+** implementation (sqlite3DefaultMutex()).
+**
+** Most calls are passed directly through to the underlying default
+** mutex implementation. Except, if a mutex is configured by calling
+** sqlite3MutexWarnOnContention() on it, then if contention is ever
+** encountered within xMutexEnter() a warning is emitted via sqlite3_log().
+**
+** This type of mutex is used as the database handle mutex when testing
+** apps that usually use SQLITE_CONFIG_MULTITHREAD mode.
+*/
+
+/*
+** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS
+** is defined. Variable CheckMutex.mutex is a pointer to the real mutex
+** allocated by the system mutex implementation. Variable iType is usually set
+** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST
+** or one of the static mutex identifiers. Or, if this is a recursive mutex
+** that has been configured using sqlite3MutexWarnOnContention(), it is
+** set to SQLITE_MUTEX_WARNONCONTENTION.
+*/
+typedef struct CheckMutex CheckMutex;
+struct CheckMutex {
+ int iType;
+ sqlite3_mutex *mutex;
+};
+
+#define SQLITE_MUTEX_WARNONCONTENTION (-1)
+
+/*
+** Pointer to real mutex methods object used by the CheckMutex
+** implementation. Set by checkMutexInit().
+*/
+static SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods;
+
+#ifdef SQLITE_DEBUG
+static int checkMutexHeld(sqlite3_mutex *p){
+ return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex);
+}
+static int checkMutexNotheld(sqlite3_mutex *p){
+ return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);
+}
+#endif
+
+/*
+** Initialize and deinitialize the mutex subsystem.
+*/
+static int checkMutexInit(void){
+ pGlobalMutexMethods = sqlite3DefaultMutex();
+ return SQLITE_OK;
+}
+static int checkMutexEnd(void){
+ pGlobalMutexMethods = 0;
+ return SQLITE_OK;
+}
+
+/*
+** Allocate a mutex.
+*/
+static sqlite3_mutex *checkMutexAlloc(int iType){
+ static CheckMutex staticMutexes[] = {
+ {2, 0}, {3, 0}, {4, 0}, {5, 0},
+ {6, 0}, {7, 0}, {8, 0}, {9, 0},
+ {10, 0}, {11, 0}, {12, 0}, {13, 0}
+ };
+ CheckMutex *p = 0;
+
+ assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 );
+ if( iType<2 ){
+ p = sqlite3MallocZero(sizeof(CheckMutex));
+ if( p==0 ) return 0;
+ p->iType = iType;
+ }else{
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( iType-2>=ArraySize(staticMutexes) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ p = &staticMutexes[iType-2];
+ }
+
+ if( p->mutex==0 ){
+ p->mutex = pGlobalMutexMethods->xMutexAlloc(iType);
+ if( p->mutex==0 ){
+ if( iType<2 ){
+ sqlite3_free(p);
+ }
+ p = 0;
+ }
+ }
+
+ return (sqlite3_mutex*)p;
+}
+
+/*
+** Free a mutex.
+*/
+static void checkMutexFree(sqlite3_mutex *p){
+ assert( SQLITE_MUTEX_RECURSIVE<2 );
+ assert( SQLITE_MUTEX_FAST<2 );
+ assert( SQLITE_MUTEX_WARNONCONTENTION<2 );
+
+#if SQLITE_ENABLE_API_ARMOR
+ if( ((CheckMutex*)p)->iType<2 )
+#endif
+ {
+ CheckMutex *pCheck = (CheckMutex*)p;
+ pGlobalMutexMethods->xMutexFree(pCheck->mutex);
+ sqlite3_free(pCheck);
+ }
+#ifdef SQLITE_ENABLE_API_ARMOR
+ else{
+ (void)SQLITE_MISUSE_BKPT;
+ }
+#endif
+}
+
+/*
+** Enter the mutex.
+*/
+static void checkMutexEnter(sqlite3_mutex *p){
+ CheckMutex *pCheck = (CheckMutex*)p;
+ if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){
+ if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){
+ return;
+ }
+ sqlite3_log(SQLITE_MISUSE,
+ "illegal multi-threaded access to database connection"
+ );
+ }
+ pGlobalMutexMethods->xMutexEnter(pCheck->mutex);
+}
+
+/*
+** Enter the mutex (do not block).
+*/
+static int checkMutexTry(sqlite3_mutex *p){
+ CheckMutex *pCheck = (CheckMutex*)p;
+ return pGlobalMutexMethods->xMutexTry(pCheck->mutex);
+}
+
+/*
+** Leave the mutex.
+*/
+static void checkMutexLeave(sqlite3_mutex *p){
+ CheckMutex *pCheck = (CheckMutex*)p;
+ pGlobalMutexMethods->xMutexLeave(pCheck->mutex);
+}
+
+sqlite3_mutex_methods const *multiThreadedCheckMutex(void){
+ static const sqlite3_mutex_methods sMutex = {
+ checkMutexInit,
+ checkMutexEnd,
+ checkMutexAlloc,
+ checkMutexFree,
+ checkMutexEnter,
+ checkMutexTry,
+ checkMutexLeave,
+#ifdef SQLITE_DEBUG
+ checkMutexHeld,
+ checkMutexNotheld
+#else
+ 0,
+ 0
+#endif
+ };
+ return &sMutex;
+}
+
+/*
+** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as
+** one on which there should be no contention.
+*/
+SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){
+ if( sqlite3GlobalConfig.mutex.xMutexAlloc==checkMutexAlloc ){
+ CheckMutex *pCheck = (CheckMutex*)p;
+ assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE );
+ pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION;
+ }
+}
+#endif /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */
+
+/*
+** Initialize the mutex system.
+*/
+SQLITE_PRIVATE int sqlite3MutexInit(void){
+ int rc = SQLITE_OK;
+ if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
+ /* If the xMutexAlloc method has not been set, then the user did not
+ ** install a mutex implementation via sqlite3_config() prior to
+ ** sqlite3_initialize() being called. This block copies pointers to
+ ** the default implementation into the sqlite3GlobalConfig structure.
+ */
+ sqlite3_mutex_methods const *pFrom;
+ sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
+
+ if( sqlite3GlobalConfig.bCoreMutex ){
+#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
+ pFrom = multiThreadedCheckMutex();
+#else
+ pFrom = sqlite3DefaultMutex();
+#endif
+ }else{
+ pFrom = sqlite3NoopMutex();
+ }
+ pTo->xMutexInit = pFrom->xMutexInit;
+ pTo->xMutexEnd = pFrom->xMutexEnd;
+ pTo->xMutexFree = pFrom->xMutexFree;
+ pTo->xMutexEnter = pFrom->xMutexEnter;
+ pTo->xMutexTry = pFrom->xMutexTry;
+ pTo->xMutexLeave = pFrom->xMutexLeave;
+ pTo->xMutexHeld = pFrom->xMutexHeld;
+ pTo->xMutexNotheld = pFrom->xMutexNotheld;
+ sqlite3MemoryBarrier();
+ pTo->xMutexAlloc = pFrom->xMutexAlloc;
+ }
+ assert( sqlite3GlobalConfig.mutex.xMutexInit );
+ rc = sqlite3GlobalConfig.mutex.xMutexInit();
+
+#ifdef SQLITE_DEBUG
+ GLOBAL(int, mutexIsInit) = 1;
+#endif
+
+ sqlite3MemoryBarrier();
+ return rc;
+}
+
+/*
+** Shutdown the mutex system. This call frees resources allocated by
+** sqlite3MutexInit().
+*/
+SQLITE_PRIVATE int sqlite3MutexEnd(void){
+ int rc = SQLITE_OK;
+ if( sqlite3GlobalConfig.mutex.xMutexEnd ){
+ rc = sqlite3GlobalConfig.mutex.xMutexEnd();
+ }
+
+#ifdef SQLITE_DEBUG
+ GLOBAL(int, mutexIsInit) = 0;
+#endif
+
+ return rc;
+}
+
+/*
+** Retrieve a pointer to a static mutex or allocate a new dynamic one.
+*/
+SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
+ if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
+#endif
+ assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
+ return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
+}
+
+SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
+ if( !sqlite3GlobalConfig.bCoreMutex ){
+ return 0;
+ }
+ assert( GLOBAL(int, mutexIsInit) );
+ assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
+ return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
+}
+
+/*
+** Free a dynamic mutex.
+*/
+SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
+ if( p ){
+ assert( sqlite3GlobalConfig.mutex.xMutexFree );
+ sqlite3GlobalConfig.mutex.xMutexFree(p);
+ }
+}
+
+/*
+** Obtain the mutex p. If some other thread already has the mutex, block
+** until it can be obtained.
+*/
+SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
+ if( p ){
+ assert( sqlite3GlobalConfig.mutex.xMutexEnter );
+ sqlite3GlobalConfig.mutex.xMutexEnter(p);
+ }
+}
+
+/*
+** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
+** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
+*/
+SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
+ int rc = SQLITE_OK;
+ if( p ){
+ assert( sqlite3GlobalConfig.mutex.xMutexTry );
+ return sqlite3GlobalConfig.mutex.xMutexTry(p);
+ }
+ return rc;
+}
+
+/*
+** The sqlite3_mutex_leave() routine exits a mutex that was previously
+** entered by the same thread. The behavior is undefined if the mutex
+** is not currently entered. If a NULL pointer is passed as an argument
+** this function is a no-op.
+*/
+SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
+ if( p ){
+ assert( sqlite3GlobalConfig.mutex.xMutexLeave );
+ sqlite3GlobalConfig.mutex.xMutexLeave(p);
+ }
+}
+
+#ifndef NDEBUG
+/*
+** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
+** intended for use inside assert() statements.
+*/
+SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
+ assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
+ return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
+}
+SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
+ assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
+ return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
+}
+#endif
+
+#endif /* !defined(SQLITE_MUTEX_OMIT) */
+
+/************** End of mutex.c ***********************************************/
+/************** Begin file mutex_noop.c **************************************/
+/*
+** 2008 October 07
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains the C functions that implement mutexes.
+**
+** This implementation in this file does not provide any mutual
+** exclusion and is thus suitable for use only in applications
+** that use SQLite in a single thread. The routines defined
+** here are place-holders. Applications can substitute working
+** mutex routines at start-time using the
+**
+** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
+**
+** interface.
+**
+** If compiled with SQLITE_DEBUG, then additional logic is inserted
+** that does error checking on mutexes to make sure they are being
+** called correctly.
+*/
+/* #include "sqliteInt.h" */
+
+#ifndef SQLITE_MUTEX_OMIT
+
+#ifndef SQLITE_DEBUG
+/*
+** Stub routines for all mutex methods.
+**
+** This routines provide no mutual exclusion or error checking.
+*/
+static int noopMutexInit(void){ return SQLITE_OK; }
+static int noopMutexEnd(void){ return SQLITE_OK; }
+static sqlite3_mutex *noopMutexAlloc(int id){
+ UNUSED_PARAMETER(id);
+ return (sqlite3_mutex*)8;
+}
+static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
+static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
+static int noopMutexTry(sqlite3_mutex *p){
+ UNUSED_PARAMETER(p);
+ return SQLITE_OK;
+}
+static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
+
+SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
+ static const sqlite3_mutex_methods sMutex = {
+ noopMutexInit,
+ noopMutexEnd,
+ noopMutexAlloc,
+ noopMutexFree,
+ noopMutexEnter,
+ noopMutexTry,
+ noopMutexLeave,
+
+ 0,
+ 0,
+ };
+
+ return &sMutex;
+}
+#endif /* !SQLITE_DEBUG */
+
+#ifdef SQLITE_DEBUG
+/*
+** In this implementation, error checking is provided for testing
+** and debugging purposes. The mutexes still do not provide any
+** mutual exclusion.
+*/
+
+/*
+** The mutex object
+*/
+typedef struct sqlite3_debug_mutex {
+ int id; /* The mutex type */
+ int cnt; /* Number of entries without a matching leave */
+} sqlite3_debug_mutex;
+
+/*
+** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
+** intended for use inside assert() statements.
+*/
+static int debugMutexHeld(sqlite3_mutex *pX){
+ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
+ return p==0 || p->cnt>0;
+}
+static int debugMutexNotheld(sqlite3_mutex *pX){
+ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
+ return p==0 || p->cnt==0;
+}
+
+/*
+** Initialize and deinitialize the mutex subsystem.
+*/
+static int debugMutexInit(void){ return SQLITE_OK; }
+static int debugMutexEnd(void){ return SQLITE_OK; }
+
+/*
+** The sqlite3_mutex_alloc() routine allocates a new
+** mutex and returns a pointer to it. If it returns NULL
+** that means that a mutex could not be allocated.
+*/
+static sqlite3_mutex *debugMutexAlloc(int id){
+ static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
+ sqlite3_debug_mutex *pNew = 0;
+ switch( id ){
+ case SQLITE_MUTEX_FAST:
+ case SQLITE_MUTEX_RECURSIVE: {
+ pNew = sqlite3Malloc(sizeof(*pNew));
+ if( pNew ){
+ pNew->id = id;
+ pNew->cnt = 0;
+ }
+ break;
+ }
+ default: {
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( id-2<0 || id-2>=ArraySize(aStatic) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ pNew = &aStatic[id-2];
+ pNew->id = id;
+ break;
+ }
+ }
+ return (sqlite3_mutex*)pNew;
+}
+
+/*
+** This routine deallocates a previously allocated mutex.
+*/
+static void debugMutexFree(sqlite3_mutex *pX){
+ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
+ assert( p->cnt==0 );
+ if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
+ sqlite3_free(p);
+ }else{
+#ifdef SQLITE_ENABLE_API_ARMOR
+ (void)SQLITE_MISUSE_BKPT;
+#endif
+ }
+}
+
+/*
+** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
+** to enter a mutex. If another thread is already within the mutex,
+** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
+** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
+** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
+** be entered multiple times by the same thread. In such cases the,
+** mutex must be exited an equal number of times before another thread
+** can enter. If the same thread tries to enter any other kind of mutex
+** more than once, the behavior is undefined.
+*/
+static void debugMutexEnter(sqlite3_mutex *pX){
+ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
+ assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
+ p->cnt++;
+}
+static int debugMutexTry(sqlite3_mutex *pX){
+ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
+ assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
+ p->cnt++;
+ return SQLITE_OK;
+}
+
+/*
+** The sqlite3_mutex_leave() routine exits a mutex that was
+** previously entered by the same thread. The behavior
+** is undefined if the mutex is not currently entered or
+** is not currently allocated. SQLite will never do either.
+*/
+static void debugMutexLeave(sqlite3_mutex *pX){
+ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
+ assert( debugMutexHeld(pX) );
+ p->cnt--;
+ assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
+}
+
+SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
+ static const sqlite3_mutex_methods sMutex = {
+ debugMutexInit,
+ debugMutexEnd,
+ debugMutexAlloc,
+ debugMutexFree,
+ debugMutexEnter,
+ debugMutexTry,
+ debugMutexLeave,
+
+ debugMutexHeld,
+ debugMutexNotheld
+ };
+
+ return &sMutex;
+}
+#endif /* SQLITE_DEBUG */
+
+/*
+** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
+** is used regardless of the run-time threadsafety setting.
+*/
+#ifdef SQLITE_MUTEX_NOOP
+SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
+ return sqlite3NoopMutex();
+}
+#endif /* defined(SQLITE_MUTEX_NOOP) */
+#endif /* !defined(SQLITE_MUTEX_OMIT) */
+
+/************** End of mutex_noop.c ******************************************/
+/************** Begin file mutex_unix.c **************************************/
+/*
+** 2007 August 28
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains the C functions that implement mutexes for pthreads
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** The code in this file is only used if we are compiling threadsafe
+** under unix with pthreads.
+**
+** Note that this implementation requires a version of pthreads that
+** supports recursive mutexes.
+*/
+#ifdef SQLITE_MUTEX_PTHREADS
+
+#include <pthread.h>
+
+/*
+** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
+** are necessary under two condidtions: (1) Debug builds and (2) using
+** home-grown mutexes. Encapsulate these conditions into a single #define.
+*/
+#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
+# define SQLITE_MUTEX_NREF 1
+#else
+# define SQLITE_MUTEX_NREF 0
+#endif
+
+/*
+** Each recursive mutex is an instance of the following structure.
+*/
+struct sqlite3_mutex {
+ pthread_mutex_t mutex; /* Mutex controlling the lock */
+#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
+ int id; /* Mutex type */
+#endif
+#if SQLITE_MUTEX_NREF
+ volatile int nRef; /* Number of entrances */
+ volatile pthread_t owner; /* Thread that is within this mutex */
+ int trace; /* True to trace changes */
+#endif
+};
+#if SQLITE_MUTEX_NREF
+# define SQLITE3_MUTEX_INITIALIZER(id) \
+ {PTHREAD_MUTEX_INITIALIZER,id,0,(pthread_t)0,0}
+#elif defined(SQLITE_ENABLE_API_ARMOR)
+# define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER, id }
+#else
+#define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER }
+#endif
+
+/*
+** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
+** intended for use only inside assert() statements. On some platforms,
+** there might be race conditions that can cause these routines to
+** deliver incorrect results. In particular, if pthread_equal() is
+** not an atomic operation, then these routines might delivery
+** incorrect results. On most platforms, pthread_equal() is a
+** comparison of two integers and is therefore atomic. But we are
+** told that HPUX is not such a platform. If so, then these routines
+** will not always work correctly on HPUX.
+**
+** On those platforms where pthread_equal() is not atomic, SQLite
+** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
+** make sure no assert() statements are evaluated and hence these
+** routines are never called.
+*/
+#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
+static int pthreadMutexHeld(sqlite3_mutex *p){
+ return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
+}
+static int pthreadMutexNotheld(sqlite3_mutex *p){
+ return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
+}
+#endif
+
+/*
+** Try to provide a memory barrier operation, needed for initialization
+** and also for the implementation of xShmBarrier in the VFS in cases
+** where SQLite is compiled without mutexes.
+*/
+SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
+#if defined(SQLITE_MEMORY_BARRIER)
+ SQLITE_MEMORY_BARRIER;
+#elif defined(__GNUC__) && GCC_VERSION>=4001000
+ __sync_synchronize();
+#endif
+}
+
+/*
+** Initialize and deinitialize the mutex subsystem.
+*/
+static int pthreadMutexInit(void){ return SQLITE_OK; }
+static int pthreadMutexEnd(void){ return SQLITE_OK; }
+
+/*
+** The sqlite3_mutex_alloc() routine allocates a new
+** mutex and returns a pointer to it. If it returns NULL
+** that means that a mutex could not be allocated. SQLite
+** will unwind its stack and return an error. The argument
+** to sqlite3_mutex_alloc() is one of these integer constants:
+**
+** <ul>
+** <li> SQLITE_MUTEX_FAST
+** <li> SQLITE_MUTEX_RECURSIVE
+** <li> SQLITE_MUTEX_STATIC_MAIN
+** <li> SQLITE_MUTEX_STATIC_MEM
+** <li> SQLITE_MUTEX_STATIC_OPEN
+** <li> SQLITE_MUTEX_STATIC_PRNG
+** <li> SQLITE_MUTEX_STATIC_LRU
+** <li> SQLITE_MUTEX_STATIC_PMEM
+** <li> SQLITE_MUTEX_STATIC_APP1
+** <li> SQLITE_MUTEX_STATIC_APP2
+** <li> SQLITE_MUTEX_STATIC_APP3
+** <li> SQLITE_MUTEX_STATIC_VFS1
+** <li> SQLITE_MUTEX_STATIC_VFS2
+** <li> SQLITE_MUTEX_STATIC_VFS3
+** </ul>
+**
+** The first two constants cause sqlite3_mutex_alloc() to create
+** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
+** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
+** The mutex implementation does not need to make a distinction
+** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
+** not want to. But SQLite will only request a recursive mutex in
+** cases where it really needs one. If a faster non-recursive mutex
+** implementation is available on the host platform, the mutex subsystem
+** might return such a mutex in response to SQLITE_MUTEX_FAST.
+**
+** The other allowed parameters to sqlite3_mutex_alloc() each return
+** a pointer to a static preexisting mutex. Six static mutexes are
+** used by the current version of SQLite. Future versions of SQLite
+** may add additional static mutexes. Static mutexes are for internal
+** use by SQLite only. Applications that use SQLite mutexes should
+** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
+** SQLITE_MUTEX_RECURSIVE.
+**
+** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
+** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
+** returns a different mutex on every call. But for the static
+** mutex types, the same mutex is returned on every call that has
+** the same type number.
+*/
+static sqlite3_mutex *pthreadMutexAlloc(int iType){
+ static sqlite3_mutex staticMutexes[] = {
+ SQLITE3_MUTEX_INITIALIZER(2),
+ SQLITE3_MUTEX_INITIALIZER(3),
+ SQLITE3_MUTEX_INITIALIZER(4),
+ SQLITE3_MUTEX_INITIALIZER(5),
+ SQLITE3_MUTEX_INITIALIZER(6),
+ SQLITE3_MUTEX_INITIALIZER(7),
+ SQLITE3_MUTEX_INITIALIZER(8),
+ SQLITE3_MUTEX_INITIALIZER(9),
+ SQLITE3_MUTEX_INITIALIZER(10),
+ SQLITE3_MUTEX_INITIALIZER(11),
+ SQLITE3_MUTEX_INITIALIZER(12),
+ SQLITE3_MUTEX_INITIALIZER(13)
+ };
+ sqlite3_mutex *p;
+ switch( iType ){
+ case SQLITE_MUTEX_RECURSIVE: {
+ p = sqlite3MallocZero( sizeof(*p) );
+ if( p ){
+#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
+ /* If recursive mutexes are not available, we will have to
+ ** build our own. See below. */
+ pthread_mutex_init(&p->mutex, 0);
+#else
+ /* Use a recursive mutex if it is available */
+ pthread_mutexattr_t recursiveAttr;
+ pthread_mutexattr_init(&recursiveAttr);
+ pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
+ pthread_mutex_init(&p->mutex, &recursiveAttr);
+ pthread_mutexattr_destroy(&recursiveAttr);
+#endif
+#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
+ p->id = SQLITE_MUTEX_RECURSIVE;
+#endif
+ }
+ break;
+ }
+ case SQLITE_MUTEX_FAST: {
+ p = sqlite3MallocZero( sizeof(*p) );
+ if( p ){
+ pthread_mutex_init(&p->mutex, 0);
+#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
+ p->id = SQLITE_MUTEX_FAST;
+#endif
+ }
+ break;
+ }
+ default: {
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ p = &staticMutexes[iType-2];
+ break;
+ }
+ }
+#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
+ assert( p==0 || p->id==iType );
+#endif
+ return p;
+}
+
+
+/*
+** This routine deallocates a previously
+** allocated mutex. SQLite is careful to deallocate every
+** mutex that it allocates.
+*/
+static void pthreadMutexFree(sqlite3_mutex *p){
+ assert( p->nRef==0 );
+#if SQLITE_ENABLE_API_ARMOR
+ if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
+#endif
+ {
+ pthread_mutex_destroy(&p->mutex);
+ sqlite3_free(p);
+ }
+#ifdef SQLITE_ENABLE_API_ARMOR
+ else{
+ (void)SQLITE_MISUSE_BKPT;
+ }
+#endif
+}
+
+/*
+** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
+** to enter a mutex. If another thread is already within the mutex,
+** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
+** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
+** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
+** be entered multiple times by the same thread. In such cases the,
+** mutex must be exited an equal number of times before another thread
+** can enter. If the same thread tries to enter any other kind of mutex
+** more than once, the behavior is undefined.
+*/
+static void pthreadMutexEnter(sqlite3_mutex *p){
+ assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
+
+#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
+ /* If recursive mutexes are not available, then we have to grow
+ ** our own. This implementation assumes that pthread_equal()
+ ** is atomic - that it cannot be deceived into thinking self
+ ** and p->owner are equal if p->owner changes between two values
+ ** that are not equal to self while the comparison is taking place.
+ ** This implementation also assumes a coherent cache - that
+ ** separate processes cannot read different values from the same
+ ** address at the same time. If either of these two conditions
+ ** are not met, then the mutexes will fail and problems will result.
+ */
+ {
+ pthread_t self = pthread_self();
+ if( p->nRef>0 && pthread_equal(p->owner, self) ){
+ p->nRef++;
+ }else{
+ pthread_mutex_lock(&p->mutex);
+ assert( p->nRef==0 );
+ p->owner = self;
+ p->nRef = 1;
+ }
+ }
+#else
+ /* Use the built-in recursive mutexes if they are available.
+ */
+ pthread_mutex_lock(&p->mutex);
+#if SQLITE_MUTEX_NREF
+ assert( p->nRef>0 || p->owner==0 );
+ p->owner = pthread_self();
+ p->nRef++;
+#endif
+#endif
+
+#ifdef SQLITE_DEBUG
+ if( p->trace ){
+ printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
+ }
+#endif
+}
+static int pthreadMutexTry(sqlite3_mutex *p){
+ int rc;
+ assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
+
+#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
+ /* If recursive mutexes are not available, then we have to grow
+ ** our own. This implementation assumes that pthread_equal()
+ ** is atomic - that it cannot be deceived into thinking self
+ ** and p->owner are equal if p->owner changes between two values
+ ** that are not equal to self while the comparison is taking place.
+ ** This implementation also assumes a coherent cache - that
+ ** separate processes cannot read different values from the same
+ ** address at the same time. If either of these two conditions
+ ** are not met, then the mutexes will fail and problems will result.
+ */
+ {
+ pthread_t self = pthread_self();
+ if( p->nRef>0 && pthread_equal(p->owner, self) ){
+ p->nRef++;
+ rc = SQLITE_OK;
+ }else if( pthread_mutex_trylock(&p->mutex)==0 ){
+ assert( p->nRef==0 );
+ p->owner = self;
+ p->nRef = 1;
+ rc = SQLITE_OK;
+ }else{
+ rc = SQLITE_BUSY;
+ }
+ }
+#else
+ /* Use the built-in recursive mutexes if they are available.
+ */
+ if( pthread_mutex_trylock(&p->mutex)==0 ){
+#if SQLITE_MUTEX_NREF
+ p->owner = pthread_self();
+ p->nRef++;
+#endif
+ rc = SQLITE_OK;
+ }else{
+ rc = SQLITE_BUSY;
+ }
+#endif
+
+#ifdef SQLITE_DEBUG
+ if( rc==SQLITE_OK && p->trace ){
+ printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
+ }
+#endif
+ return rc;
+}
+
+/*
+** The sqlite3_mutex_leave() routine exits a mutex that was
+** previously entered by the same thread. The behavior
+** is undefined if the mutex is not currently entered or
+** is not currently allocated. SQLite will never do either.
+*/
+static void pthreadMutexLeave(sqlite3_mutex *p){
+ assert( pthreadMutexHeld(p) );
+#if SQLITE_MUTEX_NREF
+ p->nRef--;
+ if( p->nRef==0 ) p->owner = 0;
+#endif
+ assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
+
+#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
+ if( p->nRef==0 ){
+ pthread_mutex_unlock(&p->mutex);
+ }
+#else
+ pthread_mutex_unlock(&p->mutex);
+#endif
+
+#ifdef SQLITE_DEBUG
+ if( p->trace ){
+ printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
+ }
+#endif
+}
+
+SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
+ static const sqlite3_mutex_methods sMutex = {
+ pthreadMutexInit,
+ pthreadMutexEnd,
+ pthreadMutexAlloc,
+ pthreadMutexFree,
+ pthreadMutexEnter,
+ pthreadMutexTry,
+ pthreadMutexLeave,
+#ifdef SQLITE_DEBUG
+ pthreadMutexHeld,
+ pthreadMutexNotheld
+#else
+ 0,
+ 0
+#endif
+ };
+
+ return &sMutex;
+}
+
+#endif /* SQLITE_MUTEX_PTHREADS */
+
+/************** End of mutex_unix.c ******************************************/
+/************** Begin file mutex_w32.c ***************************************/
+/*
+** 2007 August 14
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains the C functions that implement mutexes for Win32.
+*/
+/* #include "sqliteInt.h" */
+
+#if SQLITE_OS_WIN
+/*
+** Include code that is common to all os_*.c files
+*/
+/************** Include os_common.h in the middle of mutex_w32.c *************/
+/************** Begin file os_common.h ***************************************/
+/*
+** 2004 May 22
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains macros and a little bit of code that is common to
+** all of the platform-specific files (os_*.c) and is #included into those
+** files.
+**
+** This file should be #included by the os_*.c files only. It is not a
+** general purpose header file.
+*/
+#ifndef _OS_COMMON_H_
+#define _OS_COMMON_H_
+
+/*
+** At least two bugs have slipped in because we changed the MEMORY_DEBUG
+** macro to SQLITE_DEBUG and some older makefiles have not yet made the
+** switch. The following code should catch this problem at compile-time.
+*/
+#ifdef MEMORY_DEBUG
+# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
+#endif
+
+/*
+** Macros for performance tracing. Normally turned off. Only works
+** on i486 hardware.
+*/
+#ifdef SQLITE_PERFORMANCE_TRACE
+
+/*
+** hwtime.h contains inline assembler code for implementing
+** high-performance timing routines.
+*/
+/************** Include hwtime.h in the middle of os_common.h ****************/
+/************** Begin file hwtime.h ******************************************/
+/*
+** 2008 May 27
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains inline asm code for retrieving "high-performance"
+** counters for x86 and x86_64 class CPUs.
+*/
+#ifndef SQLITE_HWTIME_H
+#define SQLITE_HWTIME_H
+
+/*
+** The following routine only works on pentium-class (or newer) processors.
+** It uses the RDTSC opcode to read the cycle count value out of the
+** processor and returns that value. This can be used for high-res
+** profiling.
+*/
+#if !defined(__STRICT_ANSI__) && \
+ (defined(__GNUC__) || defined(_MSC_VER)) && \
+ (defined(i386) || defined(__i386__) || defined(_M_IX86))
+
+ #if defined(__GNUC__)
+
+ __inline__ sqlite_uint64 sqlite3Hwtime(void){
+ unsigned int lo, hi;
+ __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
+ return (sqlite_uint64)hi << 32 | lo;
+ }
+
+ #elif defined(_MSC_VER)
+
+ __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
+ __asm {
+ rdtsc
+ ret ; return value at EDX:EAX
+ }
+ }
+
+ #endif
+
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
+
+ __inline__ sqlite_uint64 sqlite3Hwtime(void){
+ unsigned long val;
+ __asm__ __volatile__ ("rdtsc" : "=A" (val));
+ return val;
+ }
+
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
+
+ __inline__ sqlite_uint64 sqlite3Hwtime(void){
+ unsigned long long retval;
+ unsigned long junk;
+ __asm__ __volatile__ ("\n\
+ 1: mftbu %1\n\
+ mftb %L0\n\
+ mftbu %0\n\
+ cmpw %0,%1\n\
+ bne 1b"
+ : "=r" (retval), "=r" (junk));
+ return retval;
+ }
+
+#else
+
+ /*
+ ** asm() is needed for hardware timing support. Without asm(),
+ ** disable the sqlite3Hwtime() routine.
+ **
+ ** sqlite3Hwtime() is only used for some obscure debugging
+ ** and analysis configurations, not in any deliverable, so this
+ ** should not be a great loss.
+ */
+SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
+
+#endif
+
+#endif /* !defined(SQLITE_HWTIME_H) */
+
+/************** End of hwtime.h **********************************************/
+/************** Continuing where we left off in os_common.h ******************/
+
+static sqlite_uint64 g_start;
+static sqlite_uint64 g_elapsed;
+#define TIMER_START g_start=sqlite3Hwtime()
+#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
+#define TIMER_ELAPSED g_elapsed
+#else
+#define TIMER_START
+#define TIMER_END
+#define TIMER_ELAPSED ((sqlite_uint64)0)
+#endif
+
+/*
+** If we compile with the SQLITE_TEST macro set, then the following block
+** of code will give us the ability to simulate a disk I/O error. This
+** is used for testing the I/O recovery logic.
+*/
+#if defined(SQLITE_TEST)
+SQLITE_API extern int sqlite3_io_error_hit;
+SQLITE_API extern int sqlite3_io_error_hardhit;
+SQLITE_API extern int sqlite3_io_error_pending;
+SQLITE_API extern int sqlite3_io_error_persist;
+SQLITE_API extern int sqlite3_io_error_benign;
+SQLITE_API extern int sqlite3_diskfull_pending;
+SQLITE_API extern int sqlite3_diskfull;
+#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
+#define SimulateIOError(CODE) \
+ if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
+ || sqlite3_io_error_pending-- == 1 ) \
+ { local_ioerr(); CODE; }
+static void local_ioerr(){
+ IOTRACE(("IOERR\n"));
+ sqlite3_io_error_hit++;
+ if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
+}
+#define SimulateDiskfullError(CODE) \
+ if( sqlite3_diskfull_pending ){ \
+ if( sqlite3_diskfull_pending == 1 ){ \
+ local_ioerr(); \
+ sqlite3_diskfull = 1; \
+ sqlite3_io_error_hit = 1; \
+ CODE; \
+ }else{ \
+ sqlite3_diskfull_pending--; \
+ } \
+ }
+#else
+#define SimulateIOErrorBenign(X)
+#define SimulateIOError(A)
+#define SimulateDiskfullError(A)
+#endif /* defined(SQLITE_TEST) */
+
+/*
+** When testing, keep a count of the number of open files.
+*/
+#if defined(SQLITE_TEST)
+SQLITE_API extern int sqlite3_open_file_count;
+#define OpenCounter(X) sqlite3_open_file_count+=(X)
+#else
+#define OpenCounter(X)
+#endif /* defined(SQLITE_TEST) */
+
+#endif /* !defined(_OS_COMMON_H_) */
+
+/************** End of os_common.h *******************************************/
+/************** Continuing where we left off in mutex_w32.c ******************/
+
+/*
+** Include the header file for the Windows VFS.
+*/
+/************** Include os_win.h in the middle of mutex_w32.c ****************/
+/************** Begin file os_win.h ******************************************/
+/*
+** 2013 November 25
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains code that is specific to Windows.
+*/
+#ifndef SQLITE_OS_WIN_H
+#define SQLITE_OS_WIN_H
+
+/*
+** Include the primary Windows SDK header file.
+*/
+#include "windows.h"
+
+#ifdef __CYGWIN__
+# include <sys/cygwin.h>
+# include <errno.h> /* amalgamator: dontcache */
+#endif
+
+/*
+** Determine if we are dealing with Windows NT.
+**
+** We ought to be able to determine if we are compiling for Windows 9x or
+** Windows NT using the _WIN32_WINNT macro as follows:
+**
+** #if defined(_WIN32_WINNT)
+** # define SQLITE_OS_WINNT 1
+** #else
+** # define SQLITE_OS_WINNT 0
+** #endif
+**
+** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
+** it ought to, so the above test does not work. We'll just assume that
+** everything is Windows NT unless the programmer explicitly says otherwise
+** by setting SQLITE_OS_WINNT to 0.
+*/
+#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
+# define SQLITE_OS_WINNT 1
+#endif
+
+/*
+** Determine if we are dealing with Windows CE - which has a much reduced
+** API.
+*/
+#if defined(_WIN32_WCE)
+# define SQLITE_OS_WINCE 1
+#else
+# define SQLITE_OS_WINCE 0
+#endif
+
+/*
+** Determine if we are dealing with WinRT, which provides only a subset of
+** the full Win32 API.
+*/
+#if !defined(SQLITE_OS_WINRT)
+# define SQLITE_OS_WINRT 0
+#endif
+
+/*
+** For WinCE, some API function parameters do not appear to be declared as
+** volatile.
+*/
+#if SQLITE_OS_WINCE
+# define SQLITE_WIN32_VOLATILE
+#else
+# define SQLITE_WIN32_VOLATILE volatile
+#endif
+
+/*
+** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
+** functions are not available (e.g. those not using MSVC, Cygwin, etc).
+*/
+#if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
+ SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
+# define SQLITE_OS_WIN_THREADS 1
+#else
+# define SQLITE_OS_WIN_THREADS 0
+#endif
+
+#endif /* SQLITE_OS_WIN_H */
+
+/************** End of os_win.h **********************************************/
+/************** Continuing where we left off in mutex_w32.c ******************/
+#endif
+
+/*
+** The code in this file is only used if we are compiling multithreaded
+** on a Win32 system.
+*/
+#ifdef SQLITE_MUTEX_W32
+
+/*
+** Each recursive mutex is an instance of the following structure.
+*/
+struct sqlite3_mutex {
+ CRITICAL_SECTION mutex; /* Mutex controlling the lock */
+ int id; /* Mutex type */
+#ifdef SQLITE_DEBUG
+ volatile int nRef; /* Number of enterances */
+ volatile DWORD owner; /* Thread holding this mutex */
+ volatile LONG trace; /* True to trace changes */
+#endif
+};
+
+/*
+** These are the initializer values used when declaring a "static" mutex
+** on Win32. It should be noted that all mutexes require initialization
+** on the Win32 platform.
+*/
+#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
+
+#ifdef SQLITE_DEBUG
+#define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id, \
+ 0L, (DWORD)0, 0 }
+#else
+#define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id }
+#endif
+
+#ifdef SQLITE_DEBUG
+/*
+** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
+** intended for use only inside assert() statements.
+*/
+static int winMutexHeld(sqlite3_mutex *p){
+ return p->nRef!=0 && p->owner==GetCurrentThreadId();
+}
+
+static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
+ return p->nRef==0 || p->owner!=tid;
+}
+
+static int winMutexNotheld(sqlite3_mutex *p){
+ DWORD tid = GetCurrentThreadId();
+ return winMutexNotheld2(p, tid);
+}
+#endif
+
+/*
+** Try to provide a memory barrier operation, needed for initialization
+** and also for the xShmBarrier method of the VFS in cases when SQLite is
+** compiled without mutexes (SQLITE_THREADSAFE=0).
+*/
+SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
+#if defined(SQLITE_MEMORY_BARRIER)
+ SQLITE_MEMORY_BARRIER;
+#elif defined(__GNUC__)
+ __sync_synchronize();
+#elif MSVC_VERSION>=1300
+ _ReadWriteBarrier();
+#elif defined(MemoryBarrier)
+ MemoryBarrier();
+#endif
+}
+
+/*
+** Initialize and deinitialize the mutex subsystem.
+*/
+static sqlite3_mutex winMutex_staticMutexes[] = {
+ SQLITE3_MUTEX_INITIALIZER(2),
+ SQLITE3_MUTEX_INITIALIZER(3),
+ SQLITE3_MUTEX_INITIALIZER(4),
+ SQLITE3_MUTEX_INITIALIZER(5),
+ SQLITE3_MUTEX_INITIALIZER(6),
+ SQLITE3_MUTEX_INITIALIZER(7),
+ SQLITE3_MUTEX_INITIALIZER(8),
+ SQLITE3_MUTEX_INITIALIZER(9),
+ SQLITE3_MUTEX_INITIALIZER(10),
+ SQLITE3_MUTEX_INITIALIZER(11),
+ SQLITE3_MUTEX_INITIALIZER(12),
+ SQLITE3_MUTEX_INITIALIZER(13)
+};
+
+static int winMutex_isInit = 0;
+static int winMutex_isNt = -1; /* <0 means "need to query" */
+
+/* As the winMutexInit() and winMutexEnd() functions are called as part
+** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
+** "interlocked" magic used here is probably not strictly necessary.
+*/
+static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
+
+SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
+SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
+
+static int winMutexInit(void){
+ /* The first to increment to 1 does actual initialization */
+ if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
+ int i;
+ for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
+#if SQLITE_OS_WINRT
+ InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
+#else
+ InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
+#endif
+ }
+ winMutex_isInit = 1;
+ }else{
+ /* Another thread is (in the process of) initializing the static
+ ** mutexes */
+ while( !winMutex_isInit ){
+ sqlite3_win32_sleep(1);
+ }
+ }
+ return SQLITE_OK;
+}
+
+static int winMutexEnd(void){
+ /* The first to decrement to 0 does actual shutdown
+ ** (which should be the last to shutdown.) */
+ if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
+ if( winMutex_isInit==1 ){
+ int i;
+ for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
+ DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
+ }
+ winMutex_isInit = 0;
+ }
+ }
+ return SQLITE_OK;
+}
+
+/*
+** The sqlite3_mutex_alloc() routine allocates a new
+** mutex and returns a pointer to it. If it returns NULL
+** that means that a mutex could not be allocated. SQLite
+** will unwind its stack and return an error. The argument
+** to sqlite3_mutex_alloc() is one of these integer constants:
+**
+** <ul>
+** <li> SQLITE_MUTEX_FAST
+** <li> SQLITE_MUTEX_RECURSIVE
+** <li> SQLITE_MUTEX_STATIC_MAIN
+** <li> SQLITE_MUTEX_STATIC_MEM
+** <li> SQLITE_MUTEX_STATIC_OPEN
+** <li> SQLITE_MUTEX_STATIC_PRNG
+** <li> SQLITE_MUTEX_STATIC_LRU
+** <li> SQLITE_MUTEX_STATIC_PMEM
+** <li> SQLITE_MUTEX_STATIC_APP1
+** <li> SQLITE_MUTEX_STATIC_APP2
+** <li> SQLITE_MUTEX_STATIC_APP3
+** <li> SQLITE_MUTEX_STATIC_VFS1
+** <li> SQLITE_MUTEX_STATIC_VFS2
+** <li> SQLITE_MUTEX_STATIC_VFS3
+** </ul>
+**
+** The first two constants cause sqlite3_mutex_alloc() to create
+** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
+** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
+** The mutex implementation does not need to make a distinction
+** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
+** not want to. But SQLite will only request a recursive mutex in
+** cases where it really needs one. If a faster non-recursive mutex
+** implementation is available on the host platform, the mutex subsystem
+** might return such a mutex in response to SQLITE_MUTEX_FAST.
+**
+** The other allowed parameters to sqlite3_mutex_alloc() each return
+** a pointer to a static preexisting mutex. Six static mutexes are
+** used by the current version of SQLite. Future versions of SQLite
+** may add additional static mutexes. Static mutexes are for internal
+** use by SQLite only. Applications that use SQLite mutexes should
+** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
+** SQLITE_MUTEX_RECURSIVE.
+**
+** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
+** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
+** returns a different mutex on every call. But for the static
+** mutex types, the same mutex is returned on every call that has
+** the same type number.
+*/
+static sqlite3_mutex *winMutexAlloc(int iType){
+ sqlite3_mutex *p;
+
+ switch( iType ){
+ case SQLITE_MUTEX_FAST:
+ case SQLITE_MUTEX_RECURSIVE: {
+ p = sqlite3MallocZero( sizeof(*p) );
+ if( p ){
+ p->id = iType;
+#ifdef SQLITE_DEBUG
+#ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
+ p->trace = 1;
+#endif
+#endif
+#if SQLITE_OS_WINRT
+ InitializeCriticalSectionEx(&p->mutex, 0, 0);
+#else
+ InitializeCriticalSection(&p->mutex);
+#endif
+ }
+ break;
+ }
+ default: {
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ p = &winMutex_staticMutexes[iType-2];
+#ifdef SQLITE_DEBUG
+#ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
+ InterlockedCompareExchange(&p->trace, 1, 0);
+#endif
+#endif
+ break;
+ }
+ }
+ assert( p==0 || p->id==iType );
+ return p;
+}
+
+
+/*
+** This routine deallocates a previously
+** allocated mutex. SQLite is careful to deallocate every
+** mutex that it allocates.
+*/
+static void winMutexFree(sqlite3_mutex *p){
+ assert( p );
+ assert( p->nRef==0 && p->owner==0 );
+ if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
+ DeleteCriticalSection(&p->mutex);
+ sqlite3_free(p);
+ }else{
+#ifdef SQLITE_ENABLE_API_ARMOR
+ (void)SQLITE_MISUSE_BKPT;
+#endif
+ }
+}
+
+/*
+** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
+** to enter a mutex. If another thread is already within the mutex,
+** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
+** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
+** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
+** be entered multiple times by the same thread. In such cases the,
+** mutex must be exited an equal number of times before another thread
+** can enter. If the same thread tries to enter any other kind of mutex
+** more than once, the behavior is undefined.
+*/
+static void winMutexEnter(sqlite3_mutex *p){
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+ DWORD tid = GetCurrentThreadId();
+#endif
+#ifdef SQLITE_DEBUG
+ assert( p );
+ assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
+#else
+ assert( p );
+#endif
+ assert( winMutex_isInit==1 );
+ EnterCriticalSection(&p->mutex);
+#ifdef SQLITE_DEBUG
+ assert( p->nRef>0 || p->owner==0 );
+ p->owner = tid;
+ p->nRef++;
+ if( p->trace ){
+ OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
+ tid, p->id, p, p->trace, p->nRef));
+ }
+#endif
+}
+
+static int winMutexTry(sqlite3_mutex *p){
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+ DWORD tid = GetCurrentThreadId();
+#endif
+ int rc = SQLITE_BUSY;
+ assert( p );
+ assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
+ /*
+ ** The sqlite3_mutex_try() routine is very rarely used, and when it
+ ** is used it is merely an optimization. So it is OK for it to always
+ ** fail.
+ **
+ ** The TryEnterCriticalSection() interface is only available on WinNT.
+ ** And some windows compilers complain if you try to use it without
+ ** first doing some #defines that prevent SQLite from building on Win98.
+ ** For that reason, we will omit this optimization for now. See
+ ** ticket #2685.
+ */
+#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
+ assert( winMutex_isInit==1 );
+ assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
+ if( winMutex_isNt<0 ){
+ winMutex_isNt = sqlite3_win32_is_nt();
+ }
+ assert( winMutex_isNt==0 || winMutex_isNt==1 );
+ if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
+#ifdef SQLITE_DEBUG
+ p->owner = tid;
+ p->nRef++;
+#endif
+ rc = SQLITE_OK;
+ }
+#else
+ UNUSED_PARAMETER(p);
+#endif
+#ifdef SQLITE_DEBUG
+ if( p->trace ){
+ OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
+ tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
+ }
+#endif
+ return rc;
+}
+
+/*
+** The sqlite3_mutex_leave() routine exits a mutex that was
+** previously entered by the same thread. The behavior
+** is undefined if the mutex is not currently entered or
+** is not currently allocated. SQLite will never do either.
+*/
+static void winMutexLeave(sqlite3_mutex *p){
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+ DWORD tid = GetCurrentThreadId();
+#endif
+ assert( p );
+#ifdef SQLITE_DEBUG
+ assert( p->nRef>0 );
+ assert( p->owner==tid );
+ p->nRef--;
+ if( p->nRef==0 ) p->owner = 0;
+ assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
+#endif
+ assert( winMutex_isInit==1 );
+ LeaveCriticalSection(&p->mutex);
+#ifdef SQLITE_DEBUG
+ if( p->trace ){
+ OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
+ tid, p->id, p, p->trace, p->nRef));
+ }
+#endif
+}
+
+SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
+ static const sqlite3_mutex_methods sMutex = {
+ winMutexInit,
+ winMutexEnd,
+ winMutexAlloc,
+ winMutexFree,
+ winMutexEnter,
+ winMutexTry,
+ winMutexLeave,
+#ifdef SQLITE_DEBUG
+ winMutexHeld,
+ winMutexNotheld
+#else
+ 0,
+ 0
+#endif
+ };
+ return &sMutex;
+}
+
+#endif /* SQLITE_MUTEX_W32 */
+
+/************** End of mutex_w32.c *******************************************/
+/************** Begin file malloc.c ******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** Memory allocation functions used throughout sqlite.
+*/
+/* #include "sqliteInt.h" */
+/* #include <stdarg.h> */
+
+/*
+** Attempt to release up to n bytes of non-essential memory currently
+** held by SQLite. An example of non-essential memory is memory used to
+** cache database pages that are not currently in use.
+*/
+SQLITE_API int sqlite3_release_memory(int n){
+#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
+ return sqlite3PcacheReleaseMemory(n);
+#else
+ /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
+ ** is a no-op returning zero if SQLite is not compiled with
+ ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
+ UNUSED_PARAMETER(n);
+ return 0;
+#endif
+}
+
+/*
+** Default value of the hard heap limit. 0 means "no limit".
+*/
+#ifndef SQLITE_MAX_MEMORY
+# define SQLITE_MAX_MEMORY 0
+#endif
+
+/*
+** State information local to the memory allocation subsystem.
+*/
+static SQLITE_WSD struct Mem0Global {
+ sqlite3_mutex *mutex; /* Mutex to serialize access */
+ sqlite3_int64 alarmThreshold; /* The soft heap limit */
+ sqlite3_int64 hardLimit; /* The hard upper bound on memory */
+
+ /*
+ ** True if heap is nearly "full" where "full" is defined by the
+ ** sqlite3_soft_heap_limit() setting.
+ */
+ int nearlyFull;
+} mem0 = { 0, SQLITE_MAX_MEMORY, SQLITE_MAX_MEMORY, 0 };
+
+#define mem0 GLOBAL(struct Mem0Global, mem0)
+
+/*
+** Return the memory allocator mutex. sqlite3_status() needs it.
+*/
+SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
+ return mem0.mutex;
+}
+
+#ifndef SQLITE_OMIT_DEPRECATED
+/*
+** Deprecated external interface. It used to set an alarm callback
+** that was invoked when memory usage grew too large. Now it is a
+** no-op.
+*/
+SQLITE_API int sqlite3_memory_alarm(
+ void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
+ void *pArg,
+ sqlite3_int64 iThreshold
+){
+ (void)xCallback;
+ (void)pArg;
+ (void)iThreshold;
+ return SQLITE_OK;
+}
+#endif
+
+/*
+** Set the soft heap-size limit for the library. An argument of
+** zero disables the limit. A negative argument is a no-op used to
+** obtain the return value.
+**
+** The return value is the value of the heap limit just before this
+** interface was called.
+**
+** If the hard heap limit is enabled, then the soft heap limit cannot
+** be disabled nor raised above the hard heap limit.
+*/
+SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
+ sqlite3_int64 priorLimit;
+ sqlite3_int64 excess;
+ sqlite3_int64 nUsed;
+#ifndef SQLITE_OMIT_AUTOINIT
+ int rc = sqlite3_initialize();
+ if( rc ) return -1;
+#endif
+ sqlite3_mutex_enter(mem0.mutex);
+ priorLimit = mem0.alarmThreshold;
+ if( n<0 ){
+ sqlite3_mutex_leave(mem0.mutex);
+ return priorLimit;
+ }
+ if( mem0.hardLimit>0 && (n>mem0.hardLimit || n==0) ){
+ n = mem0.hardLimit;
+ }
+ mem0.alarmThreshold = n;
+ nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
+ AtomicStore(&mem0.nearlyFull, n>0 && n<=nUsed);
+ sqlite3_mutex_leave(mem0.mutex);
+ excess = sqlite3_memory_used() - n;
+ if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
+ return priorLimit;
+}
+SQLITE_API void sqlite3_soft_heap_limit(int n){
+ if( n<0 ) n = 0;
+ sqlite3_soft_heap_limit64(n);
+}
+
+/*
+** Set the hard heap-size limit for the library. An argument of zero
+** disables the hard heap limit. A negative argument is a no-op used
+** to obtain the return value without affecting the hard heap limit.
+**
+** The return value is the value of the hard heap limit just prior to
+** calling this interface.
+**
+** Setting the hard heap limit will also activate the soft heap limit
+** and constrain the soft heap limit to be no more than the hard heap
+** limit.
+*/
+SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 n){
+ sqlite3_int64 priorLimit;
+#ifndef SQLITE_OMIT_AUTOINIT
+ int rc = sqlite3_initialize();
+ if( rc ) return -1;
+#endif
+ sqlite3_mutex_enter(mem0.mutex);
+ priorLimit = mem0.hardLimit;
+ if( n>=0 ){
+ mem0.hardLimit = n;
+ if( n<mem0.alarmThreshold || mem0.alarmThreshold==0 ){
+ mem0.alarmThreshold = n;
+ }
+ }
+ sqlite3_mutex_leave(mem0.mutex);
+ return priorLimit;
+}
+
+
+/*
+** Initialize the memory allocation subsystem.
+*/
+SQLITE_PRIVATE int sqlite3MallocInit(void){
+ int rc;
+ if( sqlite3GlobalConfig.m.xMalloc==0 ){
+ sqlite3MemSetDefault();
+ }
+ memset(&mem0, 0, sizeof(mem0));
+ mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
+ if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
+ || sqlite3GlobalConfig.nPage<=0 ){
+ sqlite3GlobalConfig.pPage = 0;
+ sqlite3GlobalConfig.szPage = 0;
+ }
+ rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
+ if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
+ return rc;
+}
+
+/*
+** Return true if the heap is currently under memory pressure - in other
+** words if the amount of heap used is close to the limit set by
+** sqlite3_soft_heap_limit().
+*/
+SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
+ return AtomicLoad(&mem0.nearlyFull);
+}
+
+/*
+** Deinitialize the memory allocation subsystem.
+*/
+SQLITE_PRIVATE void sqlite3MallocEnd(void){
+ if( sqlite3GlobalConfig.m.xShutdown ){
+ sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
+ }
+ memset(&mem0, 0, sizeof(mem0));
+}
+
+/*
+** Return the amount of memory currently checked out.
+*/
+SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
+ sqlite3_int64 res, mx;
+ sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
+ return res;
+}
+
+/*
+** Return the maximum amount of memory that has ever been
+** checked out since either the beginning of this process
+** or since the most recent reset.
+*/
+SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
+ sqlite3_int64 res, mx;
+ sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
+ return mx;
+}
+
+/*
+** Trigger the alarm
+*/
+static void sqlite3MallocAlarm(int nByte){
+ if( mem0.alarmThreshold<=0 ) return;
+ sqlite3_mutex_leave(mem0.mutex);
+ sqlite3_release_memory(nByte);
+ sqlite3_mutex_enter(mem0.mutex);
+}
+
+/*
+** Do a memory allocation with statistics and alarms. Assume the
+** lock is already held.
+*/
+static void mallocWithAlarm(int n, void **pp){
+ void *p;
+ int nFull;
+ assert( sqlite3_mutex_held(mem0.mutex) );
+ assert( n>0 );
+
+ /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
+ ** implementation of malloc_good_size(), which must be called in debug
+ ** mode and specifically when the DMD "Dark Matter Detector" is enabled
+ ** or else a crash results. Hence, do not attempt to optimize out the
+ ** following xRoundup() call. */
+ nFull = sqlite3GlobalConfig.m.xRoundup(n);
+
+ sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
+ if( mem0.alarmThreshold>0 ){
+ sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
+ if( nUsed >= mem0.alarmThreshold - nFull ){
+ AtomicStore(&mem0.nearlyFull, 1);
+ sqlite3MallocAlarm(nFull);
+ if( mem0.hardLimit ){
+ nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
+ if( nUsed >= mem0.hardLimit - nFull ){
+ *pp = 0;
+ return;
+ }
+ }
+ }else{
+ AtomicStore(&mem0.nearlyFull, 0);
+ }
+ }
+ p = sqlite3GlobalConfig.m.xMalloc(nFull);
+#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
+ if( p==0 && mem0.alarmThreshold>0 ){
+ sqlite3MallocAlarm(nFull);
+ p = sqlite3GlobalConfig.m.xMalloc(nFull);
+ }
+#endif
+ if( p ){
+ nFull = sqlite3MallocSize(p);
+ sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
+ sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
+ }
+ *pp = p;
+}
+
+/*
+** Allocate memory. This routine is like sqlite3_malloc() except that it
+** assumes the memory subsystem has already been initialized.
+*/
+SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
+ void *p;
+ if( n==0 || n>=0x7fffff00 ){
+ /* A memory allocation of a number of bytes which is near the maximum
+ ** signed integer value might cause an integer overflow inside of the
+ ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
+ ** 255 bytes of overhead. SQLite itself will never use anything near
+ ** this amount. The only way to reach the limit is with sqlite3_malloc() */
+ p = 0;
+ }else if( sqlite3GlobalConfig.bMemstat ){
+ sqlite3_mutex_enter(mem0.mutex);
+ mallocWithAlarm((int)n, &p);
+ sqlite3_mutex_leave(mem0.mutex);
+ }else{
+ p = sqlite3GlobalConfig.m.xMalloc((int)n);
+ }
+ assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
+ return p;
+}
+
+/*
+** This version of the memory allocation is for use by the application.
+** First make sure the memory subsystem is initialized, then do the
+** allocation.
+*/
+SQLITE_API void *sqlite3_malloc(int n){
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( sqlite3_initialize() ) return 0;
+#endif
+ return n<=0 ? 0 : sqlite3Malloc(n);
+}
+SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( sqlite3_initialize() ) return 0;
+#endif
+ return sqlite3Malloc(n);
+}
+
+/*
+** TRUE if p is a lookaside memory allocation from db
+*/
+#ifndef SQLITE_OMIT_LOOKASIDE
+static int isLookaside(sqlite3 *db, void *p){
+ return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
+}
+#else
+#define isLookaside(A,B) 0
+#endif
+
+/*
+** Return the size of a memory allocation previously obtained from
+** sqlite3Malloc() or sqlite3_malloc().
+*/
+SQLITE_PRIVATE int sqlite3MallocSize(void *p){
+ assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
+ return sqlite3GlobalConfig.m.xSize(p);
+}
+static int lookasideMallocSize(sqlite3 *db, void *p){
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+ return p<db->lookaside.pMiddle ? db->lookaside.szTrue : LOOKASIDE_SMALL;
+#else
+ return db->lookaside.szTrue;
+#endif
+}
+SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
+ assert( p!=0 );
+#ifdef SQLITE_DEBUG
+ if( db==0 || !isLookaside(db,p) ){
+ if( db==0 ){
+ assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
+ assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
+ }else{
+ assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
+ assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
+ }
+ }
+#endif
+ if( db ){
+ if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+ if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
+ assert( sqlite3_mutex_held(db->mutex) );
+ return LOOKASIDE_SMALL;
+ }
+#endif
+ if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
+ assert( sqlite3_mutex_held(db->mutex) );
+ return db->lookaside.szTrue;
+ }
+ }
+ }
+ return sqlite3GlobalConfig.m.xSize(p);
+}
+SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
+ assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
+ assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
+ return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
+}
+
+/*
+** Free memory previously obtained from sqlite3Malloc().
+*/
+SQLITE_API void sqlite3_free(void *p){
+ if( p==0 ) return; /* IMP: R-49053-54554 */
+ assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
+ assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
+ if( sqlite3GlobalConfig.bMemstat ){
+ sqlite3_mutex_enter(mem0.mutex);
+ sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
+ sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
+ sqlite3GlobalConfig.m.xFree(p);
+ sqlite3_mutex_leave(mem0.mutex);
+ }else{
+ sqlite3GlobalConfig.m.xFree(p);
+ }
+}
+
+/*
+** Add the size of memory allocation "p" to the count in
+** *db->pnBytesFreed.
+*/
+static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
+ *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
+}
+
+/*
+** Free memory that might be associated with a particular database
+** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
+** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
+*/
+SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
+ assert( db==0 || sqlite3_mutex_held(db->mutex) );
+ assert( p!=0 );
+ if( db ){
+ if( db->pnBytesFreed ){
+ measureAllocationSize(db, p);
+ return;
+ }
+ if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+ if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
+ LookasideSlot *pBuf = (LookasideSlot*)p;
+#ifdef SQLITE_DEBUG
+ memset(p, 0xaa, LOOKASIDE_SMALL); /* Trash freed content */
+#endif
+ pBuf->pNext = db->lookaside.pSmallFree;
+ db->lookaside.pSmallFree = pBuf;
+ return;
+ }
+#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
+ if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
+ LookasideSlot *pBuf = (LookasideSlot*)p;
+#ifdef SQLITE_DEBUG
+ memset(p, 0xaa, db->lookaside.szTrue); /* Trash freed content */
+#endif
+ pBuf->pNext = db->lookaside.pFree;
+ db->lookaside.pFree = pBuf;
+ return;
+ }
+ }
+ }
+ assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
+ assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
+ assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
+ sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
+ sqlite3_free(p);
+}
+SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
+ assert( db==0 || sqlite3_mutex_held(db->mutex) );
+ if( p ) sqlite3DbFreeNN(db, p);
+}
+
+/*
+** Change the size of an existing memory allocation
+*/
+SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
+ int nOld, nNew, nDiff;
+ void *pNew;
+ assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
+ assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
+ if( pOld==0 ){
+ return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
+ }
+ if( nBytes==0 ){
+ sqlite3_free(pOld); /* IMP: R-26507-47431 */
+ return 0;
+ }
+ if( nBytes>=0x7fffff00 ){
+ /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
+ return 0;
+ }
+ nOld = sqlite3MallocSize(pOld);
+ /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
+ ** argument to xRealloc is always a value returned by a prior call to
+ ** xRoundup. */
+ nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
+ if( nOld==nNew ){
+ pNew = pOld;
+ }else if( sqlite3GlobalConfig.bMemstat ){
+ sqlite3_mutex_enter(mem0.mutex);
+ sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
+ nDiff = nNew - nOld;
+ if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
+ mem0.alarmThreshold-nDiff ){
+ sqlite3MallocAlarm(nDiff);
+ }
+ pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
+#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
+ if( pNew==0 && mem0.alarmThreshold>0 ){
+ sqlite3MallocAlarm((int)nBytes);
+ pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
+ }
+#endif
+ if( pNew ){
+ nNew = sqlite3MallocSize(pNew);
+ sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
+ }
+ sqlite3_mutex_leave(mem0.mutex);
+ }else{
+ pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
+ }
+ assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
+ return pNew;
+}
+
+/*
+** The public interface to sqlite3Realloc. Make sure that the memory
+** subsystem is initialized prior to invoking sqliteRealloc.
+*/
+SQLITE_API void *sqlite3_realloc(void *pOld, int n){
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( sqlite3_initialize() ) return 0;
+#endif
+ if( n<0 ) n = 0; /* IMP: R-26507-47431 */
+ return sqlite3Realloc(pOld, n);
+}
+SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( sqlite3_initialize() ) return 0;
+#endif
+ return sqlite3Realloc(pOld, n);
+}
+
+
+/*
+** Allocate and zero memory.
+*/
+SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
+ void *p = sqlite3Malloc(n);
+ if( p ){
+ memset(p, 0, (size_t)n);
+ }
+ return p;
+}
+
+/*
+** Allocate and zero memory. If the allocation fails, make
+** the mallocFailed flag in the connection pointer.
+*/
+SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
+ void *p;
+ testcase( db==0 );
+ p = sqlite3DbMallocRaw(db, n);
+ if( p ) memset(p, 0, (size_t)n);
+ return p;
+}
+
+
+/* Finish the work of sqlite3DbMallocRawNN for the unusual and
+** slower case when the allocation cannot be fulfilled using lookaside.
+*/
+static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
+ void *p;
+ assert( db!=0 );
+ p = sqlite3Malloc(n);
+ if( !p ) sqlite3OomFault(db);
+ sqlite3MemdebugSetType(p,
+ (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
+ return p;
+}
+
+/*
+** Allocate memory, either lookaside (if possible) or heap.
+** If the allocation fails, set the mallocFailed flag in
+** the connection pointer.
+**
+** If db!=0 and db->mallocFailed is true (indicating a prior malloc
+** failure on the same database connection) then always return 0.
+** Hence for a particular database connection, once malloc starts
+** failing, it fails consistently until mallocFailed is reset.
+** This is an important assumption. There are many places in the
+** code that do things like this:
+**
+** int *a = (int*)sqlite3DbMallocRaw(db, 100);
+** int *b = (int*)sqlite3DbMallocRaw(db, 200);
+** if( b ) a[10] = 9;
+**
+** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
+** that all prior mallocs (ex: "a") worked too.
+**
+** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
+** not a NULL pointer.
+*/
+SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
+ void *p;
+ if( db ) return sqlite3DbMallocRawNN(db, n);
+ p = sqlite3Malloc(n);
+ sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
+ return p;
+}
+SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
+#ifndef SQLITE_OMIT_LOOKASIDE
+ LookasideSlot *pBuf;
+ assert( db!=0 );
+ assert( sqlite3_mutex_held(db->mutex) );
+ assert( db->pnBytesFreed==0 );
+ if( n>db->lookaside.sz ){
+ if( !db->lookaside.bDisable ){
+ db->lookaside.anStat[1]++;
+ }else if( db->mallocFailed ){
+ return 0;
+ }
+ return dbMallocRawFinish(db, n);
+ }
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+ if( n<=LOOKASIDE_SMALL ){
+ if( (pBuf = db->lookaside.pSmallFree)!=0 ){
+ db->lookaside.pSmallFree = pBuf->pNext;
+ db->lookaside.anStat[0]++;
+ return (void*)pBuf;
+ }else if( (pBuf = db->lookaside.pSmallInit)!=0 ){
+ db->lookaside.pSmallInit = pBuf->pNext;
+ db->lookaside.anStat[0]++;
+ return (void*)pBuf;
+ }
+ }
+#endif
+ if( (pBuf = db->lookaside.pFree)!=0 ){
+ db->lookaside.pFree = pBuf->pNext;
+ db->lookaside.anStat[0]++;
+ return (void*)pBuf;
+ }else if( (pBuf = db->lookaside.pInit)!=0 ){
+ db->lookaside.pInit = pBuf->pNext;
+ db->lookaside.anStat[0]++;
+ return (void*)pBuf;
+ }else{
+ db->lookaside.anStat[2]++;
+ }
+#else
+ assert( db!=0 );
+ assert( sqlite3_mutex_held(db->mutex) );
+ assert( db->pnBytesFreed==0 );
+ if( db->mallocFailed ){
+ return 0;
+ }
+#endif
+ return dbMallocRawFinish(db, n);
+}
+
+/* Forward declaration */
+static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
+
+/*
+** Resize the block of memory pointed to by p to n bytes. If the
+** resize fails, set the mallocFailed flag in the connection object.
+*/
+SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
+ assert( db!=0 );
+ if( p==0 ) return sqlite3DbMallocRawNN(db, n);
+ assert( sqlite3_mutex_held(db->mutex) );
+ if( ((uptr)p)<(uptr)db->lookaside.pEnd ){
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+ if( ((uptr)p)>=(uptr)db->lookaside.pMiddle ){
+ if( n<=LOOKASIDE_SMALL ) return p;
+ }else
+#endif
+ if( ((uptr)p)>=(uptr)db->lookaside.pStart ){
+ if( n<=db->lookaside.szTrue ) return p;
+ }
+ }
+ return dbReallocFinish(db, p, n);
+}
+static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
+ void *pNew = 0;
+ assert( db!=0 );
+ assert( p!=0 );
+ if( db->mallocFailed==0 ){
+ if( isLookaside(db, p) ){
+ pNew = sqlite3DbMallocRawNN(db, n);
+ if( pNew ){
+ memcpy(pNew, p, lookasideMallocSize(db, p));
+ sqlite3DbFree(db, p);
+ }
+ }else{
+ assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
+ assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
+ sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
+ pNew = sqlite3Realloc(p, n);
+ if( !pNew ){
+ sqlite3OomFault(db);
+ }
+ sqlite3MemdebugSetType(pNew,
+ (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
+ }
+ }
+ return pNew;
+}
+
+/*
+** Attempt to reallocate p. If the reallocation fails, then free p
+** and set the mallocFailed flag in the database connection.
+*/
+SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
+ void *pNew;
+ pNew = sqlite3DbRealloc(db, p, n);
+ if( !pNew ){
+ sqlite3DbFree(db, p);
+ }
+ return pNew;
+}
+
+/*
+** Make a copy of a string in memory obtained from sqliteMalloc(). These
+** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
+** is because when memory debugging is turned on, these two functions are
+** called via macros that record the current file and line number in the
+** ThreadData structure.
+*/
+SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
+ char *zNew;
+ size_t n;
+ if( z==0 ){
+ return 0;
+ }
+ n = strlen(z) + 1;
+ zNew = sqlite3DbMallocRaw(db, n);
+ if( zNew ){
+ memcpy(zNew, z, n);
+ }
+ return zNew;
+}
+SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
+ char *zNew;
+ assert( db!=0 );
+ assert( z!=0 || n==0 );
+ assert( (n&0x7fffffff)==n );
+ zNew = z ? sqlite3DbMallocRawNN(db, n+1) : 0;
+ if( zNew ){
+ memcpy(zNew, z, (size_t)n);
+ zNew[n] = 0;
+ }
+ return zNew;
+}
+
+/*
+** The text between zStart and zEnd represents a phrase within a larger
+** SQL statement. Make a copy of this phrase in space obtained form
+** sqlite3DbMalloc(). Omit leading and trailing whitespace.
+*/
+SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
+ int n;
+ while( sqlite3Isspace(zStart[0]) ) zStart++;
+ n = (int)(zEnd - zStart);
+ while( ALWAYS(n>0) && sqlite3Isspace(zStart[n-1]) ) n--;
+ return sqlite3DbStrNDup(db, zStart, n);
+}
+
+/*
+** Free any prior content in *pz and replace it with a copy of zNew.
+*/
+SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
+ sqlite3DbFree(db, *pz);
+ *pz = sqlite3DbStrDup(db, zNew);
+}
+
+/*
+** Call this routine to record the fact that an OOM (out-of-memory) error
+** has happened. This routine will set db->mallocFailed, and also
+** temporarily disable the lookaside memory allocator and interrupt
+** any running VDBEs.
+*/
+SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
+ if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
+ db->mallocFailed = 1;
+ if( db->nVdbeExec>0 ){
+ AtomicStore(&db->u1.isInterrupted, 1);
+ }
+ DisableLookaside;
+ if( db->pParse ){
+ db->pParse->rc = SQLITE_NOMEM_BKPT;
+ }
+ }
+}
+
+/*
+** This routine reactivates the memory allocator and clears the
+** db->mallocFailed flag as necessary.
+**
+** The memory allocator is not restarted if there are running
+** VDBEs.
+*/
+SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
+ if( db->mallocFailed && db->nVdbeExec==0 ){
+ db->mallocFailed = 0;
+ AtomicStore(&db->u1.isInterrupted, 0);
+ assert( db->lookaside.bDisable>0 );
+ EnableLookaside;
+ }
+}
+
+/*
+** Take actions at the end of an API call to indicate an OOM error
+*/
+static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
+ sqlite3OomClear(db);
+ sqlite3Error(db, SQLITE_NOMEM);
+ return SQLITE_NOMEM_BKPT;
+}
+
+/*
+** This function must be called before exiting any API function (i.e.
+** returning control to the user) that has called sqlite3_malloc or
+** sqlite3_realloc.
+**
+** The returned value is normally a copy of the second argument to this
+** function. However, if a malloc() failure has occurred since the previous
+** invocation SQLITE_NOMEM is returned instead.
+**
+** If an OOM as occurred, then the connection error-code (the value
+** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
+*/
+SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
+ /* If the db handle must hold the connection handle mutex here.
+ ** Otherwise the read (and possible write) of db->mallocFailed
+ ** is unsafe, as is the call to sqlite3Error().
+ */
+ assert( db!=0 );
+ assert( sqlite3_mutex_held(db->mutex) );
+ if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
+ return apiOomError(db);
+ }
+ return rc & db->errMask;
+}
+
+/************** End of malloc.c **********************************************/
+/************** Begin file printf.c ******************************************/
+/*
+** The "printf" code that follows dates from the 1980's. It is in
+** the public domain.
+**
+**************************************************************************
+**
+** This file contains code for a set of "printf"-like routines. These
+** routines format strings much like the printf() from the standard C
+** library, though the implementation here has enhancements to support
+** SQLite.
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** Conversion types fall into various categories as defined by the
+** following enumeration.
+*/
+#define etRADIX 0 /* non-decimal integer types. %x %o */
+#define etFLOAT 1 /* Floating point. %f */
+#define etEXP 2 /* Exponentional notation. %e and %E */
+#define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
+#define etSIZE 4 /* Return number of characters processed so far. %n */
+#define etSTRING 5 /* Strings. %s */
+#define etDYNSTRING 6 /* Dynamically allocated strings. %z */
+#define etPERCENT 7 /* Percent symbol. %% */
+#define etCHARX 8 /* Characters. %c */
+/* The rest are extensions, not normally found in printf() */
+#define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
+#define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
+ NULL pointers replaced by SQL NULL. %Q */
+#define etTOKEN 11 /* a pointer to a Token structure */
+#define etSRCLIST 12 /* a pointer to a SrcList */
+#define etPOINTER 13 /* The %p conversion */
+#define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
+#define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
+#define etDECIMAL 16 /* %d or %u, but not %x, %o */
+
+#define etINVALID 17 /* Any unrecognized conversion type */
+
+
+/*
+** An "etByte" is an 8-bit unsigned value.
+*/
+typedef unsigned char etByte;
+
+/*
+** Each builtin conversion character (ex: the 'd' in "%d") is described
+** by an instance of the following structure
+*/
+typedef struct et_info { /* Information about each format field */
+ char fmttype; /* The format field code letter */
+ etByte base; /* The base for radix conversion */
+ etByte flags; /* One or more of FLAG_ constants below */
+ etByte type; /* Conversion paradigm */
+ etByte charset; /* Offset into aDigits[] of the digits string */
+ etByte prefix; /* Offset into aPrefix[] of the prefix string */
+} et_info;
+
+/*
+** Allowed values for et_info.flags
+*/
+#define FLAG_SIGNED 1 /* True if the value to convert is signed */
+#define FLAG_STRING 4 /* Allow infinite precision */
+
+
+/*
+** The following table is searched linearly, so it is good to put the
+** most frequently used conversion types first.
+*/
+static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
+static const char aPrefix[] = "-x0\000X0";
+static const et_info fmtinfo[] = {
+ { 'd', 10, 1, etDECIMAL, 0, 0 },
+ { 's', 0, 4, etSTRING, 0, 0 },
+ { 'g', 0, 1, etGENERIC, 30, 0 },
+ { 'z', 0, 4, etDYNSTRING, 0, 0 },
+ { 'q', 0, 4, etSQLESCAPE, 0, 0 },
+ { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
+ { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
+ { 'c', 0, 0, etCHARX, 0, 0 },
+ { 'o', 8, 0, etRADIX, 0, 2 },
+ { 'u', 10, 0, etDECIMAL, 0, 0 },
+ { 'x', 16, 0, etRADIX, 16, 1 },
+ { 'X', 16, 0, etRADIX, 0, 4 },
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ { 'f', 0, 1, etFLOAT, 0, 0 },
+ { 'e', 0, 1, etEXP, 30, 0 },
+ { 'E', 0, 1, etEXP, 14, 0 },
+ { 'G', 0, 1, etGENERIC, 14, 0 },
+#endif
+ { 'i', 10, 1, etDECIMAL, 0, 0 },
+ { 'n', 0, 0, etSIZE, 0, 0 },
+ { '%', 0, 0, etPERCENT, 0, 0 },
+ { 'p', 16, 0, etPOINTER, 0, 1 },
+
+ /* All the rest are undocumented and are for internal use only */
+ { 'T', 0, 0, etTOKEN, 0, 0 },
+ { 'S', 0, 0, etSRCLIST, 0, 0 },
+ { 'r', 10, 1, etORDINAL, 0, 0 },
+};
+
+/* Floating point constants used for rounding */
+static const double arRound[] = {
+ 5.0e-01, 5.0e-02, 5.0e-03, 5.0e-04, 5.0e-05,
+ 5.0e-06, 5.0e-07, 5.0e-08, 5.0e-09, 5.0e-10,
+};
+
+/*
+** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
+** conversions will work.
+*/
+#ifndef SQLITE_OMIT_FLOATING_POINT
+/*
+** "*val" is a double such that 0.1 <= *val < 10.0
+** Return the ascii code for the leading digit of *val, then
+** multiply "*val" by 10.0 to renormalize.
+**
+** Example:
+** input: *val = 3.14159
+** output: *val = 1.4159 function return = '3'
+**
+** The counter *cnt is incremented each time. After counter exceeds
+** 16 (the number of significant digits in a 64-bit float) '0' is
+** always returned.
+*/
+static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
+ int digit;
+ LONGDOUBLE_TYPE d;
+ if( (*cnt)<=0 ) return '0';
+ (*cnt)--;
+ digit = (int)*val;
+ d = digit;
+ digit += '0';
+ *val = (*val - d)*10.0;
+ return (char)digit;
+}
+#endif /* SQLITE_OMIT_FLOATING_POINT */
+
+/*
+** Set the StrAccum object to an error mode.
+*/
+static void setStrAccumError(StrAccum *p, u8 eError){
+ assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
+ p->accError = eError;
+ if( p->mxAlloc ) sqlite3_str_reset(p);
+ if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError);
+}
+
+/*
+** Extra argument values from a PrintfArguments object
+*/
+static sqlite3_int64 getIntArg(PrintfArguments *p){
+ if( p->nArg<=p->nUsed ) return 0;
+ return sqlite3_value_int64(p->apArg[p->nUsed++]);
+}
+static double getDoubleArg(PrintfArguments *p){
+ if( p->nArg<=p->nUsed ) return 0.0;
+ return sqlite3_value_double(p->apArg[p->nUsed++]);
+}
+static char *getTextArg(PrintfArguments *p){
+ if( p->nArg<=p->nUsed ) return 0;
+ return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
+}
+
+/*
+** Allocate memory for a temporary buffer needed for printf rendering.
+**
+** If the requested size of the temp buffer is larger than the size
+** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
+** Do the size check before the memory allocation to prevent rogue
+** SQL from requesting large allocations using the precision or width
+** field of the printf() function.
+*/
+static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
+ char *z;
+ if( pAccum->accError ) return 0;
+ if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
+ setStrAccumError(pAccum, SQLITE_TOOBIG);
+ return 0;
+ }
+ z = sqlite3DbMallocRaw(pAccum->db, n);
+ if( z==0 ){
+ setStrAccumError(pAccum, SQLITE_NOMEM);
+ }
+ return z;
+}
+
+/*
+** On machines with a small stack size, you can redefine the
+** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
+*/
+#ifndef SQLITE_PRINT_BUF_SIZE
+# define SQLITE_PRINT_BUF_SIZE 70
+#endif
+#define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
+
+/*
+** Hard limit on the precision of floating-point conversions.
+*/
+#ifndef SQLITE_PRINTF_PRECISION_LIMIT
+# define SQLITE_FP_PRECISION_LIMIT 100000000
+#endif
+
+/*
+** Render a string given by "fmt" into the StrAccum object.
+*/
+SQLITE_API void sqlite3_str_vappendf(
+ sqlite3_str *pAccum, /* Accumulate results here */
+ const char *fmt, /* Format string */
+ va_list ap /* arguments */
+){
+ int c; /* Next character in the format string */
+ char *bufpt; /* Pointer to the conversion buffer */
+ int precision; /* Precision of the current field */
+ int length; /* Length of the field */
+ int idx; /* A general purpose loop counter */
+ int width; /* Width of the current field */
+ etByte flag_leftjustify; /* True if "-" flag is present */
+ etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
+ etByte flag_alternateform; /* True if "#" flag is present */
+ etByte flag_altform2; /* True if "!" flag is present */
+ etByte flag_zeropad; /* True if field width constant starts with zero */
+ etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */
+ etByte done; /* Loop termination flag */
+ etByte cThousand; /* Thousands separator for %d and %u */
+ etByte xtype = etINVALID; /* Conversion paradigm */
+ u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
+ char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
+ sqlite_uint64 longvalue; /* Value for integer types */
+ LONGDOUBLE_TYPE realvalue; /* Value for real types */
+ const et_info *infop; /* Pointer to the appropriate info structure */
+ char *zOut; /* Rendering buffer */
+ int nOut; /* Size of the rendering buffer */
+ char *zExtra = 0; /* Malloced memory used by some conversion */
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ int exp, e2; /* exponent of real numbers */
+ int nsd; /* Number of significant digits returned */
+ double rounder; /* Used for rounding floating point values */
+ etByte flag_dp; /* True if decimal point should be shown */
+ etByte flag_rtz; /* True if trailing zeros should be removed */
+#endif
+ PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
+ char buf[etBUFSIZE]; /* Conversion buffer */
+
+ /* pAccum never starts out with an empty buffer that was obtained from
+ ** malloc(). This precondition is required by the mprintf("%z...")
+ ** optimization. */
+ assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
+
+ bufpt = 0;
+ if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
+ pArgList = va_arg(ap, PrintfArguments*);
+ bArgList = 1;
+ }else{
+ bArgList = 0;
+ }
+ for(; (c=(*fmt))!=0; ++fmt){
+ if( c!='%' ){
+ bufpt = (char *)fmt;
+#if HAVE_STRCHRNUL
+ fmt = strchrnul(fmt, '%');
+#else
+ do{ fmt++; }while( *fmt && *fmt != '%' );
+#endif
+ sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
+ if( *fmt==0 ) break;
+ }
+ if( (c=(*++fmt))==0 ){
+ sqlite3_str_append(pAccum, "%", 1);
+ break;
+ }
+ /* Find out what flags are present */
+ flag_leftjustify = flag_prefix = cThousand =
+ flag_alternateform = flag_altform2 = flag_zeropad = 0;
+ done = 0;
+ width = 0;
+ flag_long = 0;
+ precision = -1;
+ do{
+ switch( c ){
+ case '-': flag_leftjustify = 1; break;
+ case '+': flag_prefix = '+'; break;
+ case ' ': flag_prefix = ' '; break;
+ case '#': flag_alternateform = 1; break;
+ case '!': flag_altform2 = 1; break;
+ case '0': flag_zeropad = 1; break;
+ case ',': cThousand = ','; break;
+ default: done = 1; break;
+ case 'l': {
+ flag_long = 1;
+ c = *++fmt;
+ if( c=='l' ){
+ c = *++fmt;
+ flag_long = 2;
+ }
+ done = 1;
+ break;
+ }
+ case '1': case '2': case '3': case '4': case '5':
+ case '6': case '7': case '8': case '9': {
+ unsigned wx = c - '0';
+ while( (c = *++fmt)>='0' && c<='9' ){
+ wx = wx*10 + c - '0';
+ }
+ testcase( wx>0x7fffffff );
+ width = wx & 0x7fffffff;
+#ifdef SQLITE_PRINTF_PRECISION_LIMIT
+ if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
+ width = SQLITE_PRINTF_PRECISION_LIMIT;
+ }
+#endif
+ if( c!='.' && c!='l' ){
+ done = 1;
+ }else{
+ fmt--;
+ }
+ break;
+ }
+ case '*': {
+ if( bArgList ){
+ width = (int)getIntArg(pArgList);
+ }else{
+ width = va_arg(ap,int);
+ }
+ if( width<0 ){
+ flag_leftjustify = 1;
+ width = width >= -2147483647 ? -width : 0;
+ }
+#ifdef SQLITE_PRINTF_PRECISION_LIMIT
+ if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
+ width = SQLITE_PRINTF_PRECISION_LIMIT;
+ }
+#endif
+ if( (c = fmt[1])!='.' && c!='l' ){
+ c = *++fmt;
+ done = 1;
+ }
+ break;
+ }
+ case '.': {
+ c = *++fmt;
+ if( c=='*' ){
+ if( bArgList ){
+ precision = (int)getIntArg(pArgList);
+ }else{
+ precision = va_arg(ap,int);
+ }
+ if( precision<0 ){
+ precision = precision >= -2147483647 ? -precision : -1;
+ }
+ c = *++fmt;
+ }else{
+ unsigned px = 0;
+ while( c>='0' && c<='9' ){
+ px = px*10 + c - '0';
+ c = *++fmt;
+ }
+ testcase( px>0x7fffffff );
+ precision = px & 0x7fffffff;
+ }
+#ifdef SQLITE_PRINTF_PRECISION_LIMIT
+ if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
+ precision = SQLITE_PRINTF_PRECISION_LIMIT;
+ }
+#endif
+ if( c=='l' ){
+ --fmt;
+ }else{
+ done = 1;
+ }
+ break;
+ }
+ }
+ }while( !done && (c=(*++fmt))!=0 );
+
+ /* Fetch the info entry for the field */
+ infop = &fmtinfo[0];
+ xtype = etINVALID;
+ for(idx=0; idx<ArraySize(fmtinfo); idx++){
+ if( c==fmtinfo[idx].fmttype ){
+ infop = &fmtinfo[idx];
+ xtype = infop->type;
+ break;
+ }
+ }
+
+ /*
+ ** At this point, variables are initialized as follows:
+ **
+ ** flag_alternateform TRUE if a '#' is present.
+ ** flag_altform2 TRUE if a '!' is present.
+ ** flag_prefix '+' or ' ' or zero
+ ** flag_leftjustify TRUE if a '-' is present or if the
+ ** field width was negative.
+ ** flag_zeropad TRUE if the width began with 0.
+ ** flag_long 1 for "l", 2 for "ll"
+ ** width The specified field width. This is
+ ** always non-negative. Zero is the default.
+ ** precision The specified precision. The default
+ ** is -1.
+ ** xtype The class of the conversion.
+ ** infop Pointer to the appropriate info struct.
+ */
+ assert( width>=0 );
+ assert( precision>=(-1) );
+ switch( xtype ){
+ case etPOINTER:
+ flag_long = sizeof(char*)==sizeof(i64) ? 2 :
+ sizeof(char*)==sizeof(long int) ? 1 : 0;
+ /* no break */ deliberate_fall_through
+ case etORDINAL:
+ case etRADIX:
+ cThousand = 0;
+ /* no break */ deliberate_fall_through
+ case etDECIMAL:
+ if( infop->flags & FLAG_SIGNED ){
+ i64 v;
+ if( bArgList ){
+ v = getIntArg(pArgList);
+ }else if( flag_long ){
+ if( flag_long==2 ){
+ v = va_arg(ap,i64) ;
+ }else{
+ v = va_arg(ap,long int);
+ }
+ }else{
+ v = va_arg(ap,int);
+ }
+ if( v<0 ){
+ testcase( v==SMALLEST_INT64 );
+ testcase( v==(-1) );
+ longvalue = ~v;
+ longvalue++;
+ prefix = '-';
+ }else{
+ longvalue = v;
+ prefix = flag_prefix;
+ }
+ }else{
+ if( bArgList ){
+ longvalue = (u64)getIntArg(pArgList);
+ }else if( flag_long ){
+ if( flag_long==2 ){
+ longvalue = va_arg(ap,u64);
+ }else{
+ longvalue = va_arg(ap,unsigned long int);
+ }
+ }else{
+ longvalue = va_arg(ap,unsigned int);
+ }
+ prefix = 0;
+ }
+ if( longvalue==0 ) flag_alternateform = 0;
+ if( flag_zeropad && precision<width-(prefix!=0) ){
+ precision = width-(prefix!=0);
+ }
+ if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
+ nOut = etBUFSIZE;
+ zOut = buf;
+ }else{
+ u64 n;
+ n = (u64)precision + 10;
+ if( cThousand ) n += precision/3;
+ zOut = zExtra = printfTempBuf(pAccum, n);
+ if( zOut==0 ) return;
+ nOut = (int)n;
+ }
+ bufpt = &zOut[nOut-1];
+ if( xtype==etORDINAL ){
+ static const char zOrd[] = "thstndrd";
+ int x = (int)(longvalue % 10);
+ if( x>=4 || (longvalue/10)%10==1 ){
+ x = 0;
+ }
+ *(--bufpt) = zOrd[x*2+1];
+ *(--bufpt) = zOrd[x*2];
+ }
+ {
+ const char *cset = &aDigits[infop->charset];
+ u8 base = infop->base;
+ do{ /* Convert to ascii */
+ *(--bufpt) = cset[longvalue%base];
+ longvalue = longvalue/base;
+ }while( longvalue>0 );
+ }
+ length = (int)(&zOut[nOut-1]-bufpt);
+ while( precision>length ){
+ *(--bufpt) = '0'; /* Zero pad */
+ length++;
+ }
+ if( cThousand ){
+ int nn = (length - 1)/3; /* Number of "," to insert */
+ int ix = (length - 1)%3 + 1;
+ bufpt -= nn;
+ for(idx=0; nn>0; idx++){
+ bufpt[idx] = bufpt[idx+nn];
+ ix--;
+ if( ix==0 ){
+ bufpt[++idx] = cThousand;
+ nn--;
+ ix = 3;
+ }
+ }
+ }
+ if( prefix ) *(--bufpt) = prefix; /* Add sign */
+ if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
+ const char *pre;
+ char x;
+ pre = &aPrefix[infop->prefix];
+ for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
+ }
+ length = (int)(&zOut[nOut-1]-bufpt);
+ break;
+ case etFLOAT:
+ case etEXP:
+ case etGENERIC:
+ if( bArgList ){
+ realvalue = getDoubleArg(pArgList);
+ }else{
+ realvalue = va_arg(ap,double);
+ }
+#ifdef SQLITE_OMIT_FLOATING_POINT
+ length = 0;
+#else
+ if( precision<0 ) precision = 6; /* Set default precision */
+#ifdef SQLITE_FP_PRECISION_LIMIT
+ if( precision>SQLITE_FP_PRECISION_LIMIT ){
+ precision = SQLITE_FP_PRECISION_LIMIT;
+ }
+#endif
+ if( realvalue<0.0 ){
+ realvalue = -realvalue;
+ prefix = '-';
+ }else{
+ prefix = flag_prefix;
+ }
+ if( xtype==etGENERIC && precision>0 ) precision--;
+ testcase( precision>0xfff );
+ idx = precision & 0xfff;
+ rounder = arRound[idx%10];
+ while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; }
+ if( xtype==etFLOAT ){
+ double rx = (double)realvalue;
+ sqlite3_uint64 u;
+ int ex;
+ memcpy(&u, &rx, sizeof(u));
+ ex = -1023 + (int)((u>>52)&0x7ff);
+ if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16;
+ realvalue += rounder;
+ }
+ /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
+ exp = 0;
+ if( sqlite3IsNaN((double)realvalue) ){
+ bufpt = "NaN";
+ length = 3;
+ break;
+ }
+ if( realvalue>0.0 ){
+ LONGDOUBLE_TYPE scale = 1.0;
+ while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
+ while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
+ while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
+ realvalue /= scale;
+ while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
+ while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
+ if( exp>350 ){
+ bufpt = buf;
+ buf[0] = prefix;
+ memcpy(buf+(prefix!=0),"Inf",4);
+ length = 3+(prefix!=0);
+ break;
+ }
+ }
+ bufpt = buf;
+ /*
+ ** If the field type is etGENERIC, then convert to either etEXP
+ ** or etFLOAT, as appropriate.
+ */
+ if( xtype!=etFLOAT ){
+ realvalue += rounder;
+ if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
+ }
+ if( xtype==etGENERIC ){
+ flag_rtz = !flag_alternateform;
+ if( exp<-4 || exp>precision ){
+ xtype = etEXP;
+ }else{
+ precision = precision - exp;
+ xtype = etFLOAT;
+ }
+ }else{
+ flag_rtz = flag_altform2;
+ }
+ if( xtype==etEXP ){
+ e2 = 0;
+ }else{
+ e2 = exp;
+ }
+ {
+ i64 szBufNeeded; /* Size of a temporary buffer needed */
+ szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
+ if( szBufNeeded > etBUFSIZE ){
+ bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
+ if( bufpt==0 ) return;
+ }
+ }
+ zOut = bufpt;
+ nsd = 16 + flag_altform2*10;
+ flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
+ /* The sign in front of the number */
+ if( prefix ){
+ *(bufpt++) = prefix;
+ }
+ /* Digits prior to the decimal point */
+ if( e2<0 ){
+ *(bufpt++) = '0';
+ }else{
+ for(; e2>=0; e2--){
+ *(bufpt++) = et_getdigit(&realvalue,&nsd);
+ }
+ }
+ /* The decimal point */
+ if( flag_dp ){
+ *(bufpt++) = '.';
+ }
+ /* "0" digits after the decimal point but before the first
+ ** significant digit of the number */
+ for(e2++; e2<0; precision--, e2++){
+ assert( precision>0 );
+ *(bufpt++) = '0';
+ }
+ /* Significant digits after the decimal point */
+ while( (precision--)>0 ){
+ *(bufpt++) = et_getdigit(&realvalue,&nsd);
+ }
+ /* Remove trailing zeros and the "." if no digits follow the "." */
+ if( flag_rtz && flag_dp ){
+ while( bufpt[-1]=='0' ) *(--bufpt) = 0;
+ assert( bufpt>zOut );
+ if( bufpt[-1]=='.' ){
+ if( flag_altform2 ){
+ *(bufpt++) = '0';
+ }else{
+ *(--bufpt) = 0;
+ }
+ }
+ }
+ /* Add the "eNNN" suffix */
+ if( xtype==etEXP ){
+ *(bufpt++) = aDigits[infop->charset];
+ if( exp<0 ){
+ *(bufpt++) = '-'; exp = -exp;
+ }else{
+ *(bufpt++) = '+';
+ }
+ if( exp>=100 ){
+ *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
+ exp %= 100;
+ }
+ *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
+ *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
+ }
+ *bufpt = 0;
+
+ /* The converted number is in buf[] and zero terminated. Output it.
+ ** Note that the number is in the usual order, not reversed as with
+ ** integer conversions. */
+ length = (int)(bufpt-zOut);
+ bufpt = zOut;
+
+ /* Special case: Add leading zeros if the flag_zeropad flag is
+ ** set and we are not left justified */
+ if( flag_zeropad && !flag_leftjustify && length < width){
+ int i;
+ int nPad = width - length;
+ for(i=width; i>=nPad; i--){
+ bufpt[i] = bufpt[i-nPad];
+ }
+ i = prefix!=0;
+ while( nPad-- ) bufpt[i++] = '0';
+ length = width;
+ }
+#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
+ break;
+ case etSIZE:
+ if( !bArgList ){
+ *(va_arg(ap,int*)) = pAccum->nChar;
+ }
+ length = width = 0;
+ break;
+ case etPERCENT:
+ buf[0] = '%';
+ bufpt = buf;
+ length = 1;
+ break;
+ case etCHARX:
+ if( bArgList ){
+ bufpt = getTextArg(pArgList);
+ length = 1;
+ if( bufpt ){
+ buf[0] = c = *(bufpt++);
+ if( (c&0xc0)==0xc0 ){
+ while( length<4 && (bufpt[0]&0xc0)==0x80 ){
+ buf[length++] = *(bufpt++);
+ }
+ }
+ }else{
+ buf[0] = 0;
+ }
+ }else{
+ unsigned int ch = va_arg(ap,unsigned int);
+ if( ch<0x00080 ){
+ buf[0] = ch & 0xff;
+ length = 1;
+ }else if( ch<0x00800 ){
+ buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
+ buf[1] = 0x80 + (u8)(ch & 0x3f);
+ length = 2;
+ }else if( ch<0x10000 ){
+ buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
+ buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
+ buf[2] = 0x80 + (u8)(ch & 0x3f);
+ length = 3;
+ }else{
+ buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
+ buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
+ buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
+ buf[3] = 0x80 + (u8)(ch & 0x3f);
+ length = 4;
+ }
+ }
+ if( precision>1 ){
+ width -= precision-1;
+ if( width>1 && !flag_leftjustify ){
+ sqlite3_str_appendchar(pAccum, width-1, ' ');
+ width = 0;
+ }
+ while( precision-- > 1 ){
+ sqlite3_str_append(pAccum, buf, length);
+ }
+ }
+ bufpt = buf;
+ flag_altform2 = 1;
+ goto adjust_width_for_utf8;
+ case etSTRING:
+ case etDYNSTRING:
+ if( bArgList ){
+ bufpt = getTextArg(pArgList);
+ xtype = etSTRING;
+ }else{
+ bufpt = va_arg(ap,char*);
+ }
+ if( bufpt==0 ){
+ bufpt = "";
+ }else if( xtype==etDYNSTRING ){
+ if( pAccum->nChar==0
+ && pAccum->mxAlloc
+ && width==0
+ && precision<0
+ && pAccum->accError==0
+ ){
+ /* Special optimization for sqlite3_mprintf("%z..."):
+ ** Extend an existing memory allocation rather than creating
+ ** a new one. */
+ assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
+ pAccum->zText = bufpt;
+ pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
+ pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
+ pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
+ length = 0;
+ break;
+ }
+ zExtra = bufpt;
+ }
+ if( precision>=0 ){
+ if( flag_altform2 ){
+ /* Set length to the number of bytes needed in order to display
+ ** precision characters */
+ unsigned char *z = (unsigned char*)bufpt;
+ while( precision-- > 0 && z[0] ){
+ SQLITE_SKIP_UTF8(z);
+ }
+ length = (int)(z - (unsigned char*)bufpt);
+ }else{
+ for(length=0; length<precision && bufpt[length]; length++){}
+ }
+ }else{
+ length = 0x7fffffff & (int)strlen(bufpt);
+ }
+ adjust_width_for_utf8:
+ if( flag_altform2 && width>0 ){
+ /* Adjust width to account for extra bytes in UTF-8 characters */
+ int ii = length - 1;
+ while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
+ }
+ break;
+ case etSQLESCAPE: /* %q: Escape ' characters */
+ case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */
+ case etSQLESCAPE3: { /* %w: Escape " characters */
+ int i, j, k, n, isnull;
+ int needQuote;
+ char ch;
+ char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
+ char *escarg;
+
+ if( bArgList ){
+ escarg = getTextArg(pArgList);
+ }else{
+ escarg = va_arg(ap,char*);
+ }
+ isnull = escarg==0;
+ if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
+ /* For %q, %Q, and %w, the precision is the number of bytes (or
+ ** characters if the ! flags is present) to use from the input.
+ ** Because of the extra quoting characters inserted, the number
+ ** of output characters may be larger than the precision.
+ */
+ k = precision;
+ for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
+ if( ch==q ) n++;
+ if( flag_altform2 && (ch&0xc0)==0xc0 ){
+ while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
+ }
+ }
+ needQuote = !isnull && xtype==etSQLESCAPE2;
+ n += i + 3;
+ if( n>etBUFSIZE ){
+ bufpt = zExtra = printfTempBuf(pAccum, n);
+ if( bufpt==0 ) return;
+ }else{
+ bufpt = buf;
+ }
+ j = 0;
+ if( needQuote ) bufpt[j++] = q;
+ k = i;
+ for(i=0; i<k; i++){
+ bufpt[j++] = ch = escarg[i];
+ if( ch==q ) bufpt[j++] = ch;
+ }
+ if( needQuote ) bufpt[j++] = q;
+ bufpt[j] = 0;
+ length = j;
+ goto adjust_width_for_utf8;
+ }
+ case etTOKEN: {
+ Token *pToken;
+ if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
+ pToken = va_arg(ap, Token*);
+ assert( bArgList==0 );
+ if( pToken && pToken->n ){
+ sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
+ }
+ length = width = 0;
+ break;
+ }
+ case etSRCLIST: {
+ SrcList *pSrc;
+ int k;
+ struct SrcList_item *pItem;
+ if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
+ pSrc = va_arg(ap, SrcList*);
+ k = va_arg(ap, int);
+ pItem = &pSrc->a[k];
+ assert( bArgList==0 );
+ assert( k>=0 && k<pSrc->nSrc );
+ if( pItem->zDatabase ){
+ sqlite3_str_appendall(pAccum, pItem->zDatabase);
+ sqlite3_str_append(pAccum, ".", 1);
+ }
+ sqlite3_str_appendall(pAccum, pItem->zName);
+ length = width = 0;
+ break;
+ }
+ default: {
+ assert( xtype==etINVALID );
+ return;
+ }
+ }/* End switch over the format type */
+ /*
+ ** The text of the conversion is pointed to by "bufpt" and is
+ ** "length" characters long. The field width is "width". Do
+ ** the output. Both length and width are in bytes, not characters,
+ ** at this point. If the "!" flag was present on string conversions
+ ** indicating that width and precision should be expressed in characters,
+ ** then the values have been translated prior to reaching this point.
+ */
+ width -= length;
+ if( width>0 ){
+ if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
+ sqlite3_str_append(pAccum, bufpt, length);
+ if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
+ }else{
+ sqlite3_str_append(pAccum, bufpt, length);
+ }
+
+ if( zExtra ){
+ sqlite3DbFree(pAccum->db, zExtra);
+ zExtra = 0;
+ }
+ }/* End for loop over the format string */
+} /* End of function */
+
+/*
+** Enlarge the memory allocation on a StrAccum object so that it is
+** able to accept at least N more bytes of text.
+**
+** Return the number of bytes of text that StrAccum is able to accept
+** after the attempted enlargement. The value returned might be zero.
+*/
+static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
+ char *zNew;
+ assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
+ if( p->accError ){
+ testcase(p->accError==SQLITE_TOOBIG);
+ testcase(p->accError==SQLITE_NOMEM);
+ return 0;
+ }
+ if( p->mxAlloc==0 ){
+ setStrAccumError(p, SQLITE_TOOBIG);
+ return p->nAlloc - p->nChar - 1;
+ }else{
+ char *zOld = isMalloced(p) ? p->zText : 0;
+ i64 szNew = p->nChar;
+ szNew += N + 1;
+ if( szNew+p->nChar<=p->mxAlloc ){
+ /* Force exponential buffer size growth as long as it does not overflow,
+ ** to avoid having to call this routine too often */
+ szNew += p->nChar;
+ }
+ if( szNew > p->mxAlloc ){
+ sqlite3_str_reset(p);
+ setStrAccumError(p, SQLITE_TOOBIG);
+ return 0;
+ }else{
+ p->nAlloc = (int)szNew;
+ }
+ if( p->db ){
+ zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
+ }else{
+ zNew = sqlite3Realloc(zOld, p->nAlloc);
+ }
+ if( zNew ){
+ assert( p->zText!=0 || p->nChar==0 );
+ if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
+ p->zText = zNew;
+ p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
+ p->printfFlags |= SQLITE_PRINTF_MALLOCED;
+ }else{
+ sqlite3_str_reset(p);
+ setStrAccumError(p, SQLITE_NOMEM);
+ return 0;
+ }
+ }
+ return N;
+}
+
+/*
+** Append N copies of character c to the given string buffer.
+*/
+SQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
+ testcase( p->nChar + (i64)N > 0x7fffffff );
+ if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
+ return;
+ }
+ while( (N--)>0 ) p->zText[p->nChar++] = c;
+}
+
+/*
+** The StrAccum "p" is not large enough to accept N new bytes of z[].
+** So enlarge if first, then do the append.
+**
+** This is a helper routine to sqlite3_str_append() that does special-case
+** work (enlarging the buffer) using tail recursion, so that the
+** sqlite3_str_append() routine can use fast calling semantics.
+*/
+static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
+ N = sqlite3StrAccumEnlarge(p, N);
+ if( N>0 ){
+ memcpy(&p->zText[p->nChar], z, N);
+ p->nChar += N;
+ }
+}
+
+/*
+** Append N bytes of text from z to the StrAccum object. Increase the
+** size of the memory allocation for StrAccum if necessary.
+*/
+SQLITE_API void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
+ assert( z!=0 || N==0 );
+ assert( p->zText!=0 || p->nChar==0 || p->accError );
+ assert( N>=0 );
+ assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
+ if( p->nChar+N >= p->nAlloc ){
+ enlargeAndAppend(p,z,N);
+ }else if( N ){
+ assert( p->zText );
+ p->nChar += N;
+ memcpy(&p->zText[p->nChar-N], z, N);
+ }
+}
+
+/*
+** Append the complete text of zero-terminated string z[] to the p string.
+*/
+SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){
+ sqlite3_str_append(p, z, sqlite3Strlen30(z));
+}
+
+
+/*
+** Finish off a string by making sure it is zero-terminated.
+** Return a pointer to the resulting string. Return a NULL
+** pointer if any kind of error was encountered.
+*/
+static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
+ char *zText;
+ assert( p->mxAlloc>0 && !isMalloced(p) );
+ zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
+ if( zText ){
+ memcpy(zText, p->zText, p->nChar+1);
+ p->printfFlags |= SQLITE_PRINTF_MALLOCED;
+ }else{
+ setStrAccumError(p, SQLITE_NOMEM);
+ }
+ p->zText = zText;
+ return zText;
+}
+SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
+ if( p->zText ){
+ p->zText[p->nChar] = 0;
+ if( p->mxAlloc>0 && !isMalloced(p) ){
+ return strAccumFinishRealloc(p);
+ }
+ }
+ return p->zText;
+}
+
+/*
+** This singleton is an sqlite3_str object that is returned if
+** sqlite3_malloc() fails to provide space for a real one. This
+** sqlite3_str object accepts no new text and always returns
+** an SQLITE_NOMEM error.
+*/
+static sqlite3_str sqlite3OomStr = {
+ 0, 0, 0, 0, 0, SQLITE_NOMEM, 0
+};
+
+/* Finalize a string created using sqlite3_str_new().
+*/
+SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){
+ char *z;
+ if( p!=0 && p!=&sqlite3OomStr ){
+ z = sqlite3StrAccumFinish(p);
+ sqlite3_free(p);
+ }else{
+ z = 0;
+ }
+ return z;
+}
+
+/* Return any error code associated with p */
+SQLITE_API int sqlite3_str_errcode(sqlite3_str *p){
+ return p ? p->accError : SQLITE_NOMEM;
+}
+
+/* Return the current length of p in bytes */
+SQLITE_API int sqlite3_str_length(sqlite3_str *p){
+ return p ? p->nChar : 0;
+}
+
+/* Return the current value for p */
+SQLITE_API char *sqlite3_str_value(sqlite3_str *p){
+ if( p==0 || p->nChar==0 ) return 0;
+ p->zText[p->nChar] = 0;
+ return p->zText;
+}
+
+/*
+** Reset an StrAccum string. Reclaim all malloced memory.
+*/
+SQLITE_API void sqlite3_str_reset(StrAccum *p){
+ if( isMalloced(p) ){
+ sqlite3DbFree(p->db, p->zText);
+ p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
+ }
+ p->nAlloc = 0;
+ p->nChar = 0;
+ p->zText = 0;
+}
+
+/*
+** Initialize a string accumulator.
+**
+** p: The accumulator to be initialized.
+** db: Pointer to a database connection. May be NULL. Lookaside
+** memory is used if not NULL. db->mallocFailed is set appropriately
+** when not NULL.
+** zBase: An initial buffer. May be NULL in which case the initial buffer
+** is malloced.
+** n: Size of zBase in bytes. If total space requirements never exceed
+** n then no memory allocations ever occur.
+** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
+** allocations will ever occur.
+*/
+SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
+ p->zText = zBase;
+ p->db = db;
+ p->nAlloc = n;
+ p->mxAlloc = mx;
+ p->nChar = 0;
+ p->accError = 0;
+ p->printfFlags = 0;
+}
+
+/* Allocate and initialize a new dynamic string object */
+SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3 *db){
+ sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
+ if( p ){
+ sqlite3StrAccumInit(p, 0, 0, 0,
+ db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
+ }else{
+ p = &sqlite3OomStr;
+ }
+ return p;
+}
+
+/*
+** Print into memory obtained from sqliteMalloc(). Use the internal
+** %-conversion extensions.
+*/
+SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
+ char *z;
+ char zBase[SQLITE_PRINT_BUF_SIZE];
+ StrAccum acc;
+ assert( db!=0 );
+ sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
+ db->aLimit[SQLITE_LIMIT_LENGTH]);
+ acc.printfFlags = SQLITE_PRINTF_INTERNAL;
+ sqlite3_str_vappendf(&acc, zFormat, ap);
+ z = sqlite3StrAccumFinish(&acc);
+ if( acc.accError==SQLITE_NOMEM ){
+ sqlite3OomFault(db);
+ }
+ return z;
+}
+
+/*
+** Print into memory obtained from sqliteMalloc(). Use the internal
+** %-conversion extensions.
+*/
+SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
+ va_list ap;
+ char *z;
+ va_start(ap, zFormat);
+ z = sqlite3VMPrintf(db, zFormat, ap);
+ va_end(ap);
+ return z;
+}
+
+/*
+** Print into memory obtained from sqlite3_malloc(). Omit the internal
+** %-conversion extensions.
+*/
+SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
+ char *z;
+ char zBase[SQLITE_PRINT_BUF_SIZE];
+ StrAccum acc;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( zFormat==0 ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( sqlite3_initialize() ) return 0;
+#endif
+ sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
+ sqlite3_str_vappendf(&acc, zFormat, ap);
+ z = sqlite3StrAccumFinish(&acc);
+ return z;
+}
+
+/*
+** Print into memory obtained from sqlite3_malloc()(). Omit the internal
+** %-conversion extensions.
+*/
+SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
+ va_list ap;
+ char *z;
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( sqlite3_initialize() ) return 0;
+#endif
+ va_start(ap, zFormat);
+ z = sqlite3_vmprintf(zFormat, ap);
+ va_end(ap);
+ return z;
+}
+
+/*
+** sqlite3_snprintf() works like snprintf() except that it ignores the
+** current locale settings. This is important for SQLite because we
+** are not able to use a "," as the decimal point in place of "." as
+** specified by some locales.
+**
+** Oops: The first two arguments of sqlite3_snprintf() are backwards
+** from the snprintf() standard. Unfortunately, it is too late to change
+** this without breaking compatibility, so we just have to live with the
+** mistake.
+**
+** sqlite3_vsnprintf() is the varargs version.
+*/
+SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
+ StrAccum acc;
+ if( n<=0 ) return zBuf;
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( zBuf==0 || zFormat==0 ) {
+ (void)SQLITE_MISUSE_BKPT;
+ if( zBuf ) zBuf[0] = 0;
+ return zBuf;
+ }
+#endif
+ sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
+ sqlite3_str_vappendf(&acc, zFormat, ap);
+ zBuf[acc.nChar] = 0;
+ return zBuf;
+}
+SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
+ char *z;
+ va_list ap;
+ va_start(ap,zFormat);
+ z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
+ va_end(ap);
+ return z;
+}
+
+/*
+** This is the routine that actually formats the sqlite3_log() message.
+** We house it in a separate routine from sqlite3_log() to avoid using
+** stack space on small-stack systems when logging is disabled.
+**
+** sqlite3_log() must render into a static buffer. It cannot dynamically
+** allocate memory because it might be called while the memory allocator
+** mutex is held.
+**
+** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
+** certain format characters (%q) or for very large precisions or widths.
+** Care must be taken that any sqlite3_log() calls that occur while the
+** memory mutex is held do not use these mechanisms.
+*/
+static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
+ StrAccum acc; /* String accumulator */
+ char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
+
+ sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
+ sqlite3_str_vappendf(&acc, zFormat, ap);
+ sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
+ sqlite3StrAccumFinish(&acc));
+}
+
+/*
+** Format and write a message to the log if logging is enabled.
+*/
+SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
+ va_list ap; /* Vararg list */
+ if( sqlite3GlobalConfig.xLog ){
+ va_start(ap, zFormat);
+ renderLogMsg(iErrCode, zFormat, ap);
+ va_end(ap);
+ }
+}
+
+#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
+/*
+** A version of printf() that understands %lld. Used for debugging.
+** The printf() built into some versions of windows does not understand %lld
+** and segfaults if you give it a long long int.
+*/
+SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
+ va_list ap;
+ StrAccum acc;
+ char zBuf[SQLITE_PRINT_BUF_SIZE*10];
+ sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
+ va_start(ap,zFormat);
+ sqlite3_str_vappendf(&acc, zFormat, ap);
+ va_end(ap);
+ sqlite3StrAccumFinish(&acc);
+#ifdef SQLITE_OS_TRACE_PROC
+ {
+ extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
+ SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
+ }
+#else
+ fprintf(stdout,"%s", zBuf);
+ fflush(stdout);
+#endif
+}
+#endif
+
+
+/*
+** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
+** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
+*/
+SQLITE_API void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
+ va_list ap;
+ va_start(ap,zFormat);
+ sqlite3_str_vappendf(p, zFormat, ap);
+ va_end(ap);
+}
+
+/************** End of printf.c **********************************************/
+/************** Begin file treeview.c ****************************************/
+/*
+** 2015-06-08
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains C code to implement the TreeView debugging routines.
+** These routines print a parse tree to standard output for debugging and
+** analysis.
+**
+** The interfaces in this file is only available when compiling
+** with SQLITE_DEBUG.
+*/
+/* #include "sqliteInt.h" */
+#ifdef SQLITE_DEBUG
+
+/*
+** Add a new subitem to the tree. The moreToFollow flag indicates that this
+** is not the last item in the tree.
+*/
+static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
+ if( p==0 ){
+ p = sqlite3_malloc64( sizeof(*p) );
+ if( p==0 ) return 0;
+ memset(p, 0, sizeof(*p));
+ }else{
+ p->iLevel++;
+ }
+ assert( moreToFollow==0 || moreToFollow==1 );
+ if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
+ return p;
+}
+
+/*
+** Finished with one layer of the tree
+*/
+static void sqlite3TreeViewPop(TreeView *p){
+ if( p==0 ) return;
+ p->iLevel--;
+ if( p->iLevel<0 ) sqlite3_free(p);
+}
+
+/*
+** Generate a single line of output for the tree, with a prefix that contains
+** all the appropriate tree lines
+*/
+static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
+ va_list ap;
+ int i;
+ StrAccum acc;
+ char zBuf[500];
+ sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
+ if( p ){
+ for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
+ sqlite3_str_append(&acc, p->bLine[i] ? "| " : " ", 4);
+ }
+ sqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
+ }
+ if( zFormat!=0 ){
+ va_start(ap, zFormat);
+ sqlite3_str_vappendf(&acc, zFormat, ap);
+ va_end(ap);
+ assert( acc.nChar>0 || acc.accError );
+ sqlite3_str_append(&acc, "\n", 1);
+ }
+ sqlite3StrAccumFinish(&acc);
+ fprintf(stdout,"%s", zBuf);
+ fflush(stdout);
+}
+
+/*
+** Shorthand for starting a new tree item that consists of a single label
+*/
+static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
+ p = sqlite3TreeViewPush(p, moreFollows);
+ sqlite3TreeViewLine(p, "%s", zLabel);
+}
+
+/*
+** Generate a human-readable description of a WITH clause.
+*/
+SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
+ int i;
+ if( pWith==0 ) return;
+ if( pWith->nCte==0 ) return;
+ if( pWith->pOuter ){
+ sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
+ }else{
+ sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
+ }
+ if( pWith->nCte>0 ){
+ pView = sqlite3TreeViewPush(pView, 1);
+ for(i=0; i<pWith->nCte; i++){
+ StrAccum x;
+ char zLine[1000];
+ const struct Cte *pCte = &pWith->a[i];
+ sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
+ sqlite3_str_appendf(&x, "%s", pCte->zName);
+ if( pCte->pCols && pCte->pCols->nExpr>0 ){
+ char cSep = '(';
+ int j;
+ for(j=0; j<pCte->pCols->nExpr; j++){
+ sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zEName);
+ cSep = ',';
+ }
+ sqlite3_str_appendf(&x, ")");
+ }
+ sqlite3_str_appendf(&x, " AS");
+ sqlite3StrAccumFinish(&x);
+ sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
+ sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
+ sqlite3TreeViewPop(pView);
+ }
+ sqlite3TreeViewPop(pView);
+ }
+}
+
+/*
+** Generate a human-readable description of a SrcList object.
+*/
+SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc){
+ int i;
+ for(i=0; i<pSrc->nSrc; i++){
+ const struct SrcList_item *pItem = &pSrc->a[i];
+ StrAccum x;
+ char zLine[100];
+ sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
+ sqlite3_str_appendf(&x, "{%d:*}", pItem->iCursor);
+ if( pItem->zDatabase ){
+ sqlite3_str_appendf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
+ }else if( pItem->zName ){
+ sqlite3_str_appendf(&x, " %s", pItem->zName);
+ }
+ if( pItem->pTab ){
+ sqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p used=%llx",
+ pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab, pItem->colUsed);
+ }
+ if( pItem->zAlias ){
+ sqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias);
+ }
+ if( pItem->fg.jointype & JT_LEFT ){
+ sqlite3_str_appendf(&x, " LEFT-JOIN");
+ }
+ if( pItem->fg.fromDDL ){
+ sqlite3_str_appendf(&x, " DDL");
+ }
+ sqlite3StrAccumFinish(&x);
+ sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1);
+ if( pItem->pSelect ){
+ sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
+ }
+ if( pItem->fg.isTabFunc ){
+ sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
+ }
+ sqlite3TreeViewPop(pView);
+ }
+}
+
+/*
+** Generate a human-readable description of a Select object.
+*/
+SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
+ int n = 0;
+ int cnt = 0;
+ if( p==0 ){
+ sqlite3TreeViewLine(pView, "nil-SELECT");
+ return;
+ }
+ pView = sqlite3TreeViewPush(pView, moreToFollow);
+ if( p->pWith ){
+ sqlite3TreeViewWith(pView, p->pWith, 1);
+ cnt = 1;
+ sqlite3TreeViewPush(pView, 1);
+ }
+ do{
+ if( p->selFlags & SF_WhereBegin ){
+ sqlite3TreeViewLine(pView, "sqlite3WhereBegin()");
+ }else{
+ sqlite3TreeViewLine(pView,
+ "SELECT%s%s (%u/%p) selFlags=0x%x nSelectRow=%d",
+ ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
+ ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""),
+ p->selId, p, p->selFlags,
+ (int)p->nSelectRow
+ );
+ }
+ if( cnt++ ) sqlite3TreeViewPop(pView);
+ if( p->pPrior ){
+ n = 1000;
+ }else{
+ n = 0;
+ if( p->pSrc && p->pSrc->nSrc ) n++;
+ if( p->pWhere ) n++;
+ if( p->pGroupBy ) n++;
+ if( p->pHaving ) n++;
+ if( p->pOrderBy ) n++;
+ if( p->pLimit ) n++;
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( p->pWin ) n++;
+ if( p->pWinDefn ) n++;
+#endif
+ }
+ if( p->pEList ){
+ sqlite3TreeViewExprList(pView, p->pEList, n>0, "result-set");
+ }
+ n--;
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( p->pWin ){
+ Window *pX;
+ pView = sqlite3TreeViewPush(pView, (n--)>0);
+ sqlite3TreeViewLine(pView, "window-functions");
+ for(pX=p->pWin; pX; pX=pX->pNextWin){
+ sqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0);
+ }
+ sqlite3TreeViewPop(pView);
+ }
+#endif
+ if( p->pSrc && p->pSrc->nSrc ){
+ pView = sqlite3TreeViewPush(pView, (n--)>0);
+ sqlite3TreeViewLine(pView, "FROM");
+ sqlite3TreeViewSrcList(pView, p->pSrc);
+ sqlite3TreeViewPop(pView);
+ }
+ if( p->pWhere ){
+ sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
+ sqlite3TreeViewExpr(pView, p->pWhere, 0);
+ sqlite3TreeViewPop(pView);
+ }
+ if( p->pGroupBy ){
+ sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
+ }
+ if( p->pHaving ){
+ sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
+ sqlite3TreeViewExpr(pView, p->pHaving, 0);
+ sqlite3TreeViewPop(pView);
+ }
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( p->pWinDefn ){
+ Window *pX;
+ sqlite3TreeViewItem(pView, "WINDOW", (n--)>0);
+ for(pX=p->pWinDefn; pX; pX=pX->pNextWin){
+ sqlite3TreeViewWindow(pView, pX, pX->pNextWin!=0);
+ }
+ sqlite3TreeViewPop(pView);
+ }
+#endif
+ if( p->pOrderBy ){
+ sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
+ }
+ if( p->pLimit ){
+ sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
+ sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
+ if( p->pLimit->pRight ){
+ sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
+ sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
+ sqlite3TreeViewPop(pView);
+ }
+ sqlite3TreeViewPop(pView);
+ }
+ if( p->pPrior ){
+ const char *zOp = "UNION";
+ switch( p->op ){
+ case TK_ALL: zOp = "UNION ALL"; break;
+ case TK_INTERSECT: zOp = "INTERSECT"; break;
+ case TK_EXCEPT: zOp = "EXCEPT"; break;
+ }
+ sqlite3TreeViewItem(pView, zOp, 1);
+ }
+ p = p->pPrior;
+ }while( p!=0 );
+ sqlite3TreeViewPop(pView);
+}
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+/*
+** Generate a description of starting or stopping bounds
+*/
+SQLITE_PRIVATE void sqlite3TreeViewBound(
+ TreeView *pView, /* View context */
+ u8 eBound, /* UNBOUNDED, CURRENT, PRECEDING, FOLLOWING */
+ Expr *pExpr, /* Value for PRECEDING or FOLLOWING */
+ u8 moreToFollow /* True if more to follow */
+){
+ switch( eBound ){
+ case TK_UNBOUNDED: {
+ sqlite3TreeViewItem(pView, "UNBOUNDED", moreToFollow);
+ sqlite3TreeViewPop(pView);
+ break;
+ }
+ case TK_CURRENT: {
+ sqlite3TreeViewItem(pView, "CURRENT", moreToFollow);
+ sqlite3TreeViewPop(pView);
+ break;
+ }
+ case TK_PRECEDING: {
+ sqlite3TreeViewItem(pView, "PRECEDING", moreToFollow);
+ sqlite3TreeViewExpr(pView, pExpr, 0);
+ sqlite3TreeViewPop(pView);
+ break;
+ }
+ case TK_FOLLOWING: {
+ sqlite3TreeViewItem(pView, "FOLLOWING", moreToFollow);
+ sqlite3TreeViewExpr(pView, pExpr, 0);
+ sqlite3TreeViewPop(pView);
+ break;
+ }
+ }
+}
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+/*
+** Generate a human-readable explanation for a Window object
+*/
+SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u8 more){
+ int nElement = 0;
+ if( pWin->pFilter ){
+ sqlite3TreeViewItem(pView, "FILTER", 1);
+ sqlite3TreeViewExpr(pView, pWin->pFilter, 0);
+ sqlite3TreeViewPop(pView);
+ }
+ pView = sqlite3TreeViewPush(pView, more);
+ if( pWin->zName ){
+ sqlite3TreeViewLine(pView, "OVER %s (%p)", pWin->zName, pWin);
+ }else{
+ sqlite3TreeViewLine(pView, "OVER (%p)", pWin);
+ }
+ if( pWin->zBase ) nElement++;
+ if( pWin->pOrderBy ) nElement++;
+ if( pWin->eFrmType ) nElement++;
+ if( pWin->eExclude ) nElement++;
+ if( pWin->zBase ){
+ sqlite3TreeViewPush(pView, (--nElement)>0);
+ sqlite3TreeViewLine(pView, "window: %s", pWin->zBase);
+ sqlite3TreeViewPop(pView);
+ }
+ if( pWin->pPartition ){
+ sqlite3TreeViewExprList(pView, pWin->pPartition, nElement>0,"PARTITION-BY");
+ }
+ if( pWin->pOrderBy ){
+ sqlite3TreeViewExprList(pView, pWin->pOrderBy, (--nElement)>0, "ORDER-BY");
+ }
+ if( pWin->eFrmType ){
+ char zBuf[30];
+ const char *zFrmType = "ROWS";
+ if( pWin->eFrmType==TK_RANGE ) zFrmType = "RANGE";
+ if( pWin->eFrmType==TK_GROUPS ) zFrmType = "GROUPS";
+ sqlite3_snprintf(sizeof(zBuf),zBuf,"%s%s",zFrmType,
+ pWin->bImplicitFrame ? " (implied)" : "");
+ sqlite3TreeViewItem(pView, zBuf, (--nElement)>0);
+ sqlite3TreeViewBound(pView, pWin->eStart, pWin->pStart, 1);
+ sqlite3TreeViewBound(pView, pWin->eEnd, pWin->pEnd, 0);
+ sqlite3TreeViewPop(pView);
+ }
+ if( pWin->eExclude ){
+ char zBuf[30];
+ const char *zExclude;
+ switch( pWin->eExclude ){
+ case TK_NO: zExclude = "NO OTHERS"; break;
+ case TK_CURRENT: zExclude = "CURRENT ROW"; break;
+ case TK_GROUP: zExclude = "GROUP"; break;
+ case TK_TIES: zExclude = "TIES"; break;
+ default:
+ sqlite3_snprintf(sizeof(zBuf),zBuf,"invalid(%d)", pWin->eExclude);
+ zExclude = zBuf;
+ break;
+ }
+ sqlite3TreeViewPush(pView, 0);
+ sqlite3TreeViewLine(pView, "EXCLUDE %s", zExclude);
+ sqlite3TreeViewPop(pView);
+ }
+ sqlite3TreeViewPop(pView);
+}
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+/*
+** Generate a human-readable explanation for a Window Function object
+*/
+SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView *pView, const Window *pWin, u8 more){
+ pView = sqlite3TreeViewPush(pView, more);
+ sqlite3TreeViewLine(pView, "WINFUNC %s(%d)",
+ pWin->pFunc->zName, pWin->pFunc->nArg);
+ sqlite3TreeViewWindow(pView, pWin, 0);
+ sqlite3TreeViewPop(pView);
+}
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+
+/*
+** Generate a human-readable explanation of an expression tree.
+*/
+SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
+ const char *zBinOp = 0; /* Binary operator */
+ const char *zUniOp = 0; /* Unary operator */
+ char zFlgs[200];
+ pView = sqlite3TreeViewPush(pView, moreToFollow);
+ if( pExpr==0 ){
+ sqlite3TreeViewLine(pView, "nil");
+ sqlite3TreeViewPop(pView);
+ return;
+ }
+ if( pExpr->flags || pExpr->affExpr || pExpr->vvaFlags ){
+ StrAccum x;
+ sqlite3StrAccumInit(&x, 0, zFlgs, sizeof(zFlgs), 0);
+ sqlite3_str_appendf(&x, " fg.af=%x.%c",
+ pExpr->flags, pExpr->affExpr ? pExpr->affExpr : 'n');
+ if( ExprHasProperty(pExpr, EP_FromJoin) ){
+ sqlite3_str_appendf(&x, " iRJT=%d", pExpr->iRightJoinTable);
+ }
+ if( ExprHasProperty(pExpr, EP_FromDDL) ){
+ sqlite3_str_appendf(&x, " DDL");
+ }
+ if( ExprHasVVAProperty(pExpr, EP_Immutable) ){
+ sqlite3_str_appendf(&x, " IMMUTABLE");
+ }
+ sqlite3StrAccumFinish(&x);
+ }else{
+ zFlgs[0] = 0;
+ }
+ switch( pExpr->op ){
+ case TK_AGG_COLUMN: {
+ sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
+ pExpr->iTable, pExpr->iColumn, zFlgs);
+ break;
+ }
+ case TK_COLUMN: {
+ if( pExpr->iTable<0 ){
+ /* This only happens when coding check constraints */
+ char zOp2[16];
+ if( pExpr->op2 ){
+ sqlite3_snprintf(sizeof(zOp2),zOp2," op2=0x%02x",pExpr->op2);
+ }else{
+ zOp2[0] = 0;
+ }
+ sqlite3TreeViewLine(pView, "COLUMN(%d)%s%s",
+ pExpr->iColumn, zFlgs, zOp2);
+ }else{
+ sqlite3TreeViewLine(pView, "{%d:%d} pTab=%p%s",
+ pExpr->iTable, pExpr->iColumn,
+ pExpr->y.pTab, zFlgs);
+ }
+ if( ExprHasProperty(pExpr, EP_FixedCol) ){
+ sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
+ }
+ break;
+ }
+ case TK_INTEGER: {
+ if( pExpr->flags & EP_IntValue ){
+ sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
+ }else{
+ sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
+ }
+ break;
+ }
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ case TK_FLOAT: {
+ sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
+ break;
+ }
+#endif
+ case TK_STRING: {
+ sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
+ break;
+ }
+ case TK_NULL: {
+ sqlite3TreeViewLine(pView,"NULL");
+ break;
+ }
+ case TK_TRUEFALSE: {
+ sqlite3TreeViewLine(pView,
+ sqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE");
+ break;
+ }
+#ifndef SQLITE_OMIT_BLOB_LITERAL
+ case TK_BLOB: {
+ sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
+ break;
+ }
+#endif
+ case TK_VARIABLE: {
+ sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
+ pExpr->u.zToken, pExpr->iColumn);
+ break;
+ }
+ case TK_REGISTER: {
+ sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
+ break;
+ }
+ case TK_ID: {
+ sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
+ break;
+ }
+#ifndef SQLITE_OMIT_CAST
+ case TK_CAST: {
+ /* Expressions of the form: CAST(pLeft AS token) */
+ sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
+ sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
+ break;
+ }
+#endif /* SQLITE_OMIT_CAST */
+ case TK_LT: zBinOp = "LT"; break;
+ case TK_LE: zBinOp = "LE"; break;
+ case TK_GT: zBinOp = "GT"; break;
+ case TK_GE: zBinOp = "GE"; break;
+ case TK_NE: zBinOp = "NE"; break;
+ case TK_EQ: zBinOp = "EQ"; break;
+ case TK_IS: zBinOp = "IS"; break;
+ case TK_ISNOT: zBinOp = "ISNOT"; break;
+ case TK_AND: zBinOp = "AND"; break;
+ case TK_OR: zBinOp = "OR"; break;
+ case TK_PLUS: zBinOp = "ADD"; break;
+ case TK_STAR: zBinOp = "MUL"; break;
+ case TK_MINUS: zBinOp = "SUB"; break;
+ case TK_REM: zBinOp = "REM"; break;
+ case TK_BITAND: zBinOp = "BITAND"; break;
+ case TK_BITOR: zBinOp = "BITOR"; break;
+ case TK_SLASH: zBinOp = "DIV"; break;
+ case TK_LSHIFT: zBinOp = "LSHIFT"; break;
+ case TK_RSHIFT: zBinOp = "RSHIFT"; break;
+ case TK_CONCAT: zBinOp = "CONCAT"; break;
+ case TK_DOT: zBinOp = "DOT"; break;
+ case TK_LIMIT: zBinOp = "LIMIT"; break;
+
+ case TK_UMINUS: zUniOp = "UMINUS"; break;
+ case TK_UPLUS: zUniOp = "UPLUS"; break;
+ case TK_BITNOT: zUniOp = "BITNOT"; break;
+ case TK_NOT: zUniOp = "NOT"; break;
+ case TK_ISNULL: zUniOp = "ISNULL"; break;
+ case TK_NOTNULL: zUniOp = "NOTNULL"; break;
+
+ case TK_TRUTH: {
+ int x;
+ const char *azOp[] = {
+ "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE"
+ };
+ assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT );
+ assert( pExpr->pRight );
+ assert( sqlite3ExprSkipCollate(pExpr->pRight)->op==TK_TRUEFALSE );
+ x = (pExpr->op2==TK_ISNOT)*2 + sqlite3ExprTruthValue(pExpr->pRight);
+ zUniOp = azOp[x];
+ break;
+ }
+
+ case TK_SPAN: {
+ sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
+ sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
+ break;
+ }
+
+ case TK_COLLATE: {
+ /* COLLATE operators without the EP_Collate flag are intended to
+ ** emulate collation associated with a table column. These show
+ ** up in the treeview output as "SOFT-COLLATE". Explicit COLLATE
+ ** operators that appear in the original SQL always have the
+ ** EP_Collate bit set and appear in treeview output as just "COLLATE" */
+ sqlite3TreeViewLine(pView, "%sCOLLATE %Q%s",
+ !ExprHasProperty(pExpr, EP_Collate) ? "SOFT-" : "",
+ pExpr->u.zToken, zFlgs);
+ sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
+ break;
+ }
+
+ case TK_AGG_FUNCTION:
+ case TK_FUNCTION: {
+ ExprList *pFarg; /* List of function arguments */
+ Window *pWin;
+ if( ExprHasProperty(pExpr, EP_TokenOnly) ){
+ pFarg = 0;
+ pWin = 0;
+ }else{
+ pFarg = pExpr->x.pList;
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ pWin = ExprHasProperty(pExpr, EP_WinFunc) ? pExpr->y.pWin : 0;
+#else
+ pWin = 0;
+#endif
+ }
+ if( pExpr->op==TK_AGG_FUNCTION ){
+ sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q%s agg=%d[%d]/%p",
+ pExpr->op2, pExpr->u.zToken, zFlgs,
+ pExpr->pAggInfo ? pExpr->pAggInfo->selId : 0,
+ pExpr->iAgg, pExpr->pAggInfo);
+ }else if( pExpr->op2!=0 ){
+ const char *zOp2;
+ char zBuf[8];
+ sqlite3_snprintf(sizeof(zBuf),zBuf,"0x%02x",pExpr->op2);
+ zOp2 = zBuf;
+ if( pExpr->op2==NC_IsCheck ) zOp2 = "NC_IsCheck";
+ if( pExpr->op2==NC_IdxExpr ) zOp2 = "NC_IdxExpr";
+ if( pExpr->op2==NC_PartIdx ) zOp2 = "NC_PartIdx";
+ if( pExpr->op2==NC_GenCol ) zOp2 = "NC_GenCol";
+ sqlite3TreeViewLine(pView, "FUNCTION %Q%s op2=%s",
+ pExpr->u.zToken, zFlgs, zOp2);
+ }else{
+ sqlite3TreeViewLine(pView, "FUNCTION %Q%s", pExpr->u.zToken, zFlgs);
+ }
+ if( pFarg ){
+ sqlite3TreeViewExprList(pView, pFarg, pWin!=0, 0);
+ }
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( pWin ){
+ sqlite3TreeViewWindow(pView, pWin, 0);
+ }
+#endif
+ break;
+ }
+#ifndef SQLITE_OMIT_SUBQUERY
+ case TK_EXISTS: {
+ sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
+ sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
+ break;
+ }
+ case TK_SELECT: {
+ sqlite3TreeViewLine(pView, "subquery-expr flags=0x%x", pExpr->flags);
+ sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
+ break;
+ }
+ case TK_IN: {
+ sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
+ sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
+ if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+ sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
+ }else{
+ sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
+ }
+ break;
+ }
+#endif /* SQLITE_OMIT_SUBQUERY */
+
+ /*
+ ** x BETWEEN y AND z
+ **
+ ** This is equivalent to
+ **
+ ** x>=y AND x<=z
+ **
+ ** X is stored in pExpr->pLeft.
+ ** Y is stored in pExpr->pList->a[0].pExpr.
+ ** Z is stored in pExpr->pList->a[1].pExpr.
+ */
+ case TK_BETWEEN: {
+ Expr *pX = pExpr->pLeft;
+ Expr *pY = pExpr->x.pList->a[0].pExpr;
+ Expr *pZ = pExpr->x.pList->a[1].pExpr;
+ sqlite3TreeViewLine(pView, "BETWEEN");
+ sqlite3TreeViewExpr(pView, pX, 1);
+ sqlite3TreeViewExpr(pView, pY, 1);
+ sqlite3TreeViewExpr(pView, pZ, 0);
+ break;
+ }
+ case TK_TRIGGER: {
+ /* If the opcode is TK_TRIGGER, then the expression is a reference
+ ** to a column in the new.* or old.* pseudo-tables available to
+ ** trigger programs. In this case Expr.iTable is set to 1 for the
+ ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
+ ** is set to the column of the pseudo-table to read, or to -1 to
+ ** read the rowid field.
+ */
+ sqlite3TreeViewLine(pView, "%s(%d)",
+ pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
+ break;
+ }
+ case TK_CASE: {
+ sqlite3TreeViewLine(pView, "CASE");
+ sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
+ sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
+ break;
+ }
+#ifndef SQLITE_OMIT_TRIGGER
+ case TK_RAISE: {
+ const char *zType = "unk";
+ switch( pExpr->affExpr ){
+ case OE_Rollback: zType = "rollback"; break;
+ case OE_Abort: zType = "abort"; break;
+ case OE_Fail: zType = "fail"; break;
+ case OE_Ignore: zType = "ignore"; break;
+ }
+ sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
+ break;
+ }
+#endif
+ case TK_MATCH: {
+ sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
+ pExpr->iTable, pExpr->iColumn, zFlgs);
+ sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
+ break;
+ }
+ case TK_VECTOR: {
+ char *z = sqlite3_mprintf("VECTOR%s",zFlgs);
+ sqlite3TreeViewBareExprList(pView, pExpr->x.pList, z);
+ sqlite3_free(z);
+ break;
+ }
+ case TK_SELECT_COLUMN: {
+ sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
+ sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
+ break;
+ }
+ case TK_IF_NULL_ROW: {
+ sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
+ sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
+ break;
+ }
+ default: {
+ sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
+ break;
+ }
+ }
+ if( zBinOp ){
+ sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
+ sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
+ sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
+ }else if( zUniOp ){
+ sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
+ sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
+ }
+ sqlite3TreeViewPop(pView);
+}
+
+
+/*
+** Generate a human-readable explanation of an expression list.
+*/
+SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
+ TreeView *pView,
+ const ExprList *pList,
+ const char *zLabel
+){
+ if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
+ if( pList==0 ){
+ sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
+ }else{
+ int i;
+ sqlite3TreeViewLine(pView, "%s", zLabel);
+ for(i=0; i<pList->nExpr; i++){
+ int j = pList->a[i].u.x.iOrderByCol;
+ char *zName = pList->a[i].zEName;
+ int moreToFollow = i<pList->nExpr - 1;
+ if( pList->a[i].eEName!=ENAME_NAME ) zName = 0;
+ if( j || zName ){
+ sqlite3TreeViewPush(pView, moreToFollow);
+ moreToFollow = 0;
+ sqlite3TreeViewLine(pView, 0);
+ if( zName ){
+ fprintf(stdout, "AS %s ", zName);
+ }
+ if( j ){
+ fprintf(stdout, "iOrderByCol=%d", j);
+ }
+ fprintf(stdout, "\n");
+ fflush(stdout);
+ }
+ sqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow);
+ if( j || zName ){
+ sqlite3TreeViewPop(pView);
+ }
+ }
+ }
+}
+SQLITE_PRIVATE void sqlite3TreeViewExprList(
+ TreeView *pView,
+ const ExprList *pList,
+ u8 moreToFollow,
+ const char *zLabel
+){
+ pView = sqlite3TreeViewPush(pView, moreToFollow);
+ sqlite3TreeViewBareExprList(pView, pList, zLabel);
+ sqlite3TreeViewPop(pView);
+}
+
+#endif /* SQLITE_DEBUG */
+
+/************** End of treeview.c ********************************************/
+/************** Begin file random.c ******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code to implement a pseudo-random number
+** generator (PRNG) for SQLite.
+**
+** Random numbers are used by some of the database backends in order
+** to generate random integer keys for tables or random filenames.
+*/
+/* #include "sqliteInt.h" */
+
+
+/* All threads share a single random number generator.
+** This structure is the current state of the generator.
+*/
+static SQLITE_WSD struct sqlite3PrngType {
+ unsigned char isInit; /* True if initialized */
+ unsigned char i, j; /* State variables */
+ unsigned char s[256]; /* State variables */
+} sqlite3Prng;
+
+/*
+** Return N random bytes.
+*/
+SQLITE_API void sqlite3_randomness(int N, void *pBuf){
+ unsigned char t;
+ unsigned char *zBuf = pBuf;
+
+ /* The "wsdPrng" macro will resolve to the pseudo-random number generator
+ ** state vector. If writable static data is unsupported on the target,
+ ** we have to locate the state vector at run-time. In the more common
+ ** case where writable static data is supported, wsdPrng can refer directly
+ ** to the "sqlite3Prng" state vector declared above.
+ */
+#ifdef SQLITE_OMIT_WSD
+ struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
+# define wsdPrng p[0]
+#else
+# define wsdPrng sqlite3Prng
+#endif
+
+#if SQLITE_THREADSAFE
+ sqlite3_mutex *mutex;
+#endif
+
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( sqlite3_initialize() ) return;
+#endif
+
+#if SQLITE_THREADSAFE
+ mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
+#endif
+
+ sqlite3_mutex_enter(mutex);
+ if( N<=0 || pBuf==0 ){
+ wsdPrng.isInit = 0;
+ sqlite3_mutex_leave(mutex);
+ return;
+ }
+
+ /* Initialize the state of the random number generator once,
+ ** the first time this routine is called. The seed value does
+ ** not need to contain a lot of randomness since we are not
+ ** trying to do secure encryption or anything like that...
+ **
+ ** Nothing in this file or anywhere else in SQLite does any kind of
+ ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
+ ** number generator) not as an encryption device.
+ */
+ if( !wsdPrng.isInit ){
+ int i;
+ char k[256];
+ wsdPrng.j = 0;
+ wsdPrng.i = 0;
+ sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
+ for(i=0; i<256; i++){
+ wsdPrng.s[i] = (u8)i;
+ }
+ for(i=0; i<256; i++){
+ wsdPrng.j += wsdPrng.s[i] + k[i];
+ t = wsdPrng.s[wsdPrng.j];
+ wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
+ wsdPrng.s[i] = t;
+ }
+ wsdPrng.isInit = 1;
+ }
+
+ assert( N>0 );
+ do{
+ wsdPrng.i++;
+ t = wsdPrng.s[wsdPrng.i];
+ wsdPrng.j += t;
+ wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
+ wsdPrng.s[wsdPrng.j] = t;
+ t += wsdPrng.s[wsdPrng.i];
+ *(zBuf++) = wsdPrng.s[t];
+ }while( --N );
+ sqlite3_mutex_leave(mutex);
+}
+
+#ifndef SQLITE_UNTESTABLE
+/*
+** For testing purposes, we sometimes want to preserve the state of
+** PRNG and restore the PRNG to its saved state at a later time, or
+** to reset the PRNG to its initial state. These routines accomplish
+** those tasks.
+**
+** The sqlite3_test_control() interface calls these routines to
+** control the PRNG.
+*/
+static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
+SQLITE_PRIVATE void sqlite3PrngSaveState(void){
+ memcpy(
+ &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
+ &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
+ sizeof(sqlite3Prng)
+ );
+}
+SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
+ memcpy(
+ &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
+ &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
+ sizeof(sqlite3Prng)
+ );
+}
+#endif /* SQLITE_UNTESTABLE */
+
+/************** End of random.c **********************************************/
+/************** Begin file threads.c *****************************************/
+/*
+** 2012 July 21
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file presents a simple cross-platform threading interface for
+** use internally by SQLite.
+**
+** A "thread" can be created using sqlite3ThreadCreate(). This thread
+** runs independently of its creator until it is joined using
+** sqlite3ThreadJoin(), at which point it terminates.
+**
+** Threads do not have to be real. It could be that the work of the
+** "thread" is done by the main thread at either the sqlite3ThreadCreate()
+** or sqlite3ThreadJoin() call. This is, in fact, what happens in
+** single threaded systems. Nothing in SQLite requires multiple threads.
+** This interface exists so that applications that want to take advantage
+** of multiple cores can do so, while also allowing applications to stay
+** single-threaded if desired.
+*/
+/* #include "sqliteInt.h" */
+#if SQLITE_OS_WIN
+/* # include "os_win.h" */
+#endif
+
+#if SQLITE_MAX_WORKER_THREADS>0
+
+/********************************* Unix Pthreads ****************************/
+#if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
+
+#define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
+/* #include <pthread.h> */
+
+/* A running thread */
+struct SQLiteThread {
+ pthread_t tid; /* Thread ID */
+ int done; /* Set to true when thread finishes */
+ void *pOut; /* Result returned by the thread */
+ void *(*xTask)(void*); /* The thread routine */
+ void *pIn; /* Argument to the thread */
+};
+
+/* Create a new thread */
+SQLITE_PRIVATE int sqlite3ThreadCreate(
+ SQLiteThread **ppThread, /* OUT: Write the thread object here */
+ void *(*xTask)(void*), /* Routine to run in a separate thread */
+ void *pIn /* Argument passed into xTask() */
+){
+ SQLiteThread *p;
+ int rc;
+
+ assert( ppThread!=0 );
+ assert( xTask!=0 );
+ /* This routine is never used in single-threaded mode */
+ assert( sqlite3GlobalConfig.bCoreMutex!=0 );
+
+ *ppThread = 0;
+ p = sqlite3Malloc(sizeof(*p));
+ if( p==0 ) return SQLITE_NOMEM_BKPT;
+ memset(p, 0, sizeof(*p));
+ p->xTask = xTask;
+ p->pIn = pIn;
+ /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
+ ** function that returns SQLITE_ERROR when passed the argument 200, that
+ ** forces worker threads to run sequentially and deterministically
+ ** for testing purposes. */
+ if( sqlite3FaultSim(200) ){
+ rc = 1;
+ }else{
+ rc = pthread_create(&p->tid, 0, xTask, pIn);
+ }
+ if( rc ){
+ p->done = 1;
+ p->pOut = xTask(pIn);
+ }
+ *ppThread = p;
+ return SQLITE_OK;
+}
+
+/* Get the results of the thread */
+SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
+ int rc;
+
+ assert( ppOut!=0 );
+ if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
+ if( p->done ){
+ *ppOut = p->pOut;
+ rc = SQLITE_OK;
+ }else{
+ rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
+ }
+ sqlite3_free(p);
+ return rc;
+}
+
+#endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
+/******************************** End Unix Pthreads *************************/
+
+
+/********************************* Win32 Threads ****************************/
+#if SQLITE_OS_WIN_THREADS
+
+#define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
+#include <process.h>
+
+/* A running thread */
+struct SQLiteThread {
+ void *tid; /* The thread handle */
+ unsigned id; /* The thread identifier */
+ void *(*xTask)(void*); /* The routine to run as a thread */
+ void *pIn; /* Argument to xTask */
+ void *pResult; /* Result of xTask */
+};
+
+/* Thread procedure Win32 compatibility shim */
+static unsigned __stdcall sqlite3ThreadProc(
+ void *pArg /* IN: Pointer to the SQLiteThread structure */
+){
+ SQLiteThread *p = (SQLiteThread *)pArg;
+
+ assert( p!=0 );
+#if 0
+ /*
+ ** This assert appears to trigger spuriously on certain
+ ** versions of Windows, possibly due to _beginthreadex()
+ ** and/or CreateThread() not fully setting their thread
+ ** ID parameter before starting the thread.
+ */
+ assert( p->id==GetCurrentThreadId() );
+#endif
+ assert( p->xTask!=0 );
+ p->pResult = p->xTask(p->pIn);
+
+ _endthreadex(0);
+ return 0; /* NOT REACHED */
+}
+
+/* Create a new thread */
+SQLITE_PRIVATE int sqlite3ThreadCreate(
+ SQLiteThread **ppThread, /* OUT: Write the thread object here */
+ void *(*xTask)(void*), /* Routine to run in a separate thread */
+ void *pIn /* Argument passed into xTask() */
+){
+ SQLiteThread *p;
+
+ assert( ppThread!=0 );
+ assert( xTask!=0 );
+ *ppThread = 0;
+ p = sqlite3Malloc(sizeof(*p));
+ if( p==0 ) return SQLITE_NOMEM_BKPT;
+ /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
+ ** function that returns SQLITE_ERROR when passed the argument 200, that
+ ** forces worker threads to run sequentially and deterministically
+ ** (via the sqlite3FaultSim() term of the conditional) for testing
+ ** purposes. */
+ if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
+ memset(p, 0, sizeof(*p));
+ }else{
+ p->xTask = xTask;
+ p->pIn = pIn;
+ p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
+ if( p->tid==0 ){
+ memset(p, 0, sizeof(*p));
+ }
+ }
+ if( p->xTask==0 ){
+ p->id = GetCurrentThreadId();
+ p->pResult = xTask(pIn);
+ }
+ *ppThread = p;
+ return SQLITE_OK;
+}
+
+SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
+
+/* Get the results of the thread */
+SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
+ DWORD rc;
+ BOOL bRc;
+
+ assert( ppOut!=0 );
+ if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
+ if( p->xTask==0 ){
+ /* assert( p->id==GetCurrentThreadId() ); */
+ rc = WAIT_OBJECT_0;
+ assert( p->tid==0 );
+ }else{
+ assert( p->id!=0 && p->id!=GetCurrentThreadId() );
+ rc = sqlite3Win32Wait((HANDLE)p->tid);
+ assert( rc!=WAIT_IO_COMPLETION );
+ bRc = CloseHandle((HANDLE)p->tid);
+ assert( bRc );
+ }
+ if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
+ sqlite3_free(p);
+ return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
+}
+
+#endif /* SQLITE_OS_WIN_THREADS */
+/******************************** End Win32 Threads *************************/
+
+
+/********************************* Single-Threaded **************************/
+#ifndef SQLITE_THREADS_IMPLEMENTED
+/*
+** This implementation does not actually create a new thread. It does the
+** work of the thread in the main thread, when either the thread is created
+** or when it is joined
+*/
+
+/* A running thread */
+struct SQLiteThread {
+ void *(*xTask)(void*); /* The routine to run as a thread */
+ void *pIn; /* Argument to xTask */
+ void *pResult; /* Result of xTask */
+};
+
+/* Create a new thread */
+SQLITE_PRIVATE int sqlite3ThreadCreate(
+ SQLiteThread **ppThread, /* OUT: Write the thread object here */
+ void *(*xTask)(void*), /* Routine to run in a separate thread */
+ void *pIn /* Argument passed into xTask() */
+){
+ SQLiteThread *p;
+
+ assert( ppThread!=0 );
+ assert( xTask!=0 );
+ *ppThread = 0;
+ p = sqlite3Malloc(sizeof(*p));
+ if( p==0 ) return SQLITE_NOMEM_BKPT;
+ if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
+ p->xTask = xTask;
+ p->pIn = pIn;
+ }else{
+ p->xTask = 0;
+ p->pResult = xTask(pIn);
+ }
+ *ppThread = p;
+ return SQLITE_OK;
+}
+
+/* Get the results of the thread */
+SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
+
+ assert( ppOut!=0 );
+ if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
+ if( p->xTask ){
+ *ppOut = p->xTask(p->pIn);
+ }else{
+ *ppOut = p->pResult;
+ }
+ sqlite3_free(p);
+
+#if defined(SQLITE_TEST)
+ {
+ void *pTstAlloc = sqlite3Malloc(10);
+ if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
+ sqlite3_free(pTstAlloc);
+ }
+#endif
+
+ return SQLITE_OK;
+}
+
+#endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
+/****************************** End Single-Threaded *************************/
+#endif /* SQLITE_MAX_WORKER_THREADS>0 */
+
+/************** End of threads.c *********************************************/
+/************** Begin file utf.c *********************************************/
+/*
+** 2004 April 13
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains routines used to translate between UTF-8,
+** UTF-16, UTF-16BE, and UTF-16LE.
+**
+** Notes on UTF-8:
+**
+** Byte-0 Byte-1 Byte-2 Byte-3 Value
+** 0xxxxxxx 00000000 00000000 0xxxxxxx
+** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
+** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
+** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
+**
+**
+** Notes on UTF-16: (with wwww+1==uuuuu)
+**
+** Word-0 Word-1 Value
+** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
+** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
+**
+**
+** BOM or Byte Order Mark:
+** 0xff 0xfe little-endian utf-16 follows
+** 0xfe 0xff big-endian utf-16 follows
+**
+*/
+/* #include "sqliteInt.h" */
+/* #include <assert.h> */
+/* #include "vdbeInt.h" */
+
+#if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
+/*
+** The following constant value is used by the SQLITE_BIGENDIAN and
+** SQLITE_LITTLEENDIAN macros.
+*/
+SQLITE_PRIVATE const int sqlite3one = 1;
+#endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
+
+/*
+** This lookup table is used to help decode the first byte of
+** a multi-byte UTF8 character.
+*/
+static const unsigned char sqlite3Utf8Trans1[] = {
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
+ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
+};
+
+
+#define WRITE_UTF8(zOut, c) { \
+ if( c<0x00080 ){ \
+ *zOut++ = (u8)(c&0xFF); \
+ } \
+ else if( c<0x00800 ){ \
+ *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
+ *zOut++ = 0x80 + (u8)(c & 0x3F); \
+ } \
+ else if( c<0x10000 ){ \
+ *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
+ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
+ *zOut++ = 0x80 + (u8)(c & 0x3F); \
+ }else{ \
+ *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
+ *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
+ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
+ *zOut++ = 0x80 + (u8)(c & 0x3F); \
+ } \
+}
+
+#define WRITE_UTF16LE(zOut, c) { \
+ if( c<=0xFFFF ){ \
+ *zOut++ = (u8)(c&0x00FF); \
+ *zOut++ = (u8)((c>>8)&0x00FF); \
+ }else{ \
+ *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
+ *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
+ *zOut++ = (u8)(c&0x00FF); \
+ *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
+ } \
+}
+
+#define WRITE_UTF16BE(zOut, c) { \
+ if( c<=0xFFFF ){ \
+ *zOut++ = (u8)((c>>8)&0x00FF); \
+ *zOut++ = (u8)(c&0x00FF); \
+ }else{ \
+ *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
+ *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
+ *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
+ *zOut++ = (u8)(c&0x00FF); \
+ } \
+}
+
+/*
+** Translate a single UTF-8 character. Return the unicode value.
+**
+** During translation, assume that the byte that zTerm points
+** is a 0x00.
+**
+** Write a pointer to the next unread byte back into *pzNext.
+**
+** Notes On Invalid UTF-8:
+**
+** * This routine never allows a 7-bit character (0x00 through 0x7f) to
+** be encoded as a multi-byte character. Any multi-byte character that
+** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
+**
+** * This routine never allows a UTF16 surrogate value to be encoded.
+** If a multi-byte character attempts to encode a value between
+** 0xd800 and 0xe000 then it is rendered as 0xfffd.
+**
+** * Bytes in the range of 0x80 through 0xbf which occur as the first
+** byte of a character are interpreted as single-byte characters
+** and rendered as themselves even though they are technically
+** invalid characters.
+**
+** * This routine accepts over-length UTF8 encodings
+** for unicode values 0x80 and greater. It does not change over-length
+** encodings to 0xfffd as some systems recommend.
+*/
+#define READ_UTF8(zIn, zTerm, c) \
+ c = *(zIn++); \
+ if( c>=0xc0 ){ \
+ c = sqlite3Utf8Trans1[c-0xc0]; \
+ while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
+ c = (c<<6) + (0x3f & *(zIn++)); \
+ } \
+ if( c<0x80 \
+ || (c&0xFFFFF800)==0xD800 \
+ || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
+ }
+SQLITE_PRIVATE u32 sqlite3Utf8Read(
+ const unsigned char **pz /* Pointer to string from which to read char */
+){
+ unsigned int c;
+
+ /* Same as READ_UTF8() above but without the zTerm parameter.
+ ** For this routine, we assume the UTF8 string is always zero-terminated.
+ */
+ c = *((*pz)++);
+ if( c>=0xc0 ){
+ c = sqlite3Utf8Trans1[c-0xc0];
+ while( (*(*pz) & 0xc0)==0x80 ){
+ c = (c<<6) + (0x3f & *((*pz)++));
+ }
+ if( c<0x80
+ || (c&0xFFFFF800)==0xD800
+ || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
+ }
+ return c;
+}
+
+
+
+
+/*
+** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
+** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
+*/
+/* #define TRANSLATE_TRACE 1 */
+
+#ifndef SQLITE_OMIT_UTF16
+/*
+** This routine transforms the internal text encoding used by pMem to
+** desiredEnc. It is an error if the string is already of the desired
+** encoding, or if *pMem does not contain a string value.
+*/
+SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
+ sqlite3_int64 len; /* Maximum length of output string in bytes */
+ unsigned char *zOut; /* Output buffer */
+ unsigned char *zIn; /* Input iterator */
+ unsigned char *zTerm; /* End of input */
+ unsigned char *z; /* Output iterator */
+ unsigned int c;
+
+ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
+ assert( pMem->flags&MEM_Str );
+ assert( pMem->enc!=desiredEnc );
+ assert( pMem->enc!=0 );
+ assert( pMem->n>=0 );
+
+#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
+ {
+ StrAccum acc;
+ char zBuf[1000];
+ sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
+ sqlite3VdbeMemPrettyPrint(pMem, &acc);
+ fprintf(stderr, "INPUT: %s\n", sqlite3StrAccumFinish(&acc));
+ }
+#endif
+
+ /* If the translation is between UTF-16 little and big endian, then
+ ** all that is required is to swap the byte order. This case is handled
+ ** differently from the others.
+ */
+ if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
+ u8 temp;
+ int rc;
+ rc = sqlite3VdbeMemMakeWriteable(pMem);
+ if( rc!=SQLITE_OK ){
+ assert( rc==SQLITE_NOMEM );
+ return SQLITE_NOMEM_BKPT;
+ }
+ zIn = (u8*)pMem->z;
+ zTerm = &zIn[pMem->n&~1];
+ while( zIn<zTerm ){
+ temp = *zIn;
+ *zIn = *(zIn+1);
+ zIn++;
+ *zIn++ = temp;
+ }
+ pMem->enc = desiredEnc;
+ goto translate_out;
+ }
+
+ /* Set len to the maximum number of bytes required in the output buffer. */
+ if( desiredEnc==SQLITE_UTF8 ){
+ /* When converting from UTF-16, the maximum growth results from
+ ** translating a 2-byte character to a 4-byte UTF-8 character.
+ ** A single byte is required for the output string
+ ** nul-terminator.
+ */
+ pMem->n &= ~1;
+ len = 2 * (sqlite3_int64)pMem->n + 1;
+ }else{
+ /* When converting from UTF-8 to UTF-16 the maximum growth is caused
+ ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
+ ** character. Two bytes are required in the output buffer for the
+ ** nul-terminator.
+ */
+ len = 2 * (sqlite3_int64)pMem->n + 2;
+ }
+
+ /* Set zIn to point at the start of the input buffer and zTerm to point 1
+ ** byte past the end.
+ **
+ ** Variable zOut is set to point at the output buffer, space obtained
+ ** from sqlite3_malloc().
+ */
+ zIn = (u8*)pMem->z;
+ zTerm = &zIn[pMem->n];
+ zOut = sqlite3DbMallocRaw(pMem->db, len);
+ if( !zOut ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ z = zOut;
+
+ if( pMem->enc==SQLITE_UTF8 ){
+ if( desiredEnc==SQLITE_UTF16LE ){
+ /* UTF-8 -> UTF-16 Little-endian */
+ while( zIn<zTerm ){
+ READ_UTF8(zIn, zTerm, c);
+ WRITE_UTF16LE(z, c);
+ }
+ }else{
+ assert( desiredEnc==SQLITE_UTF16BE );
+ /* UTF-8 -> UTF-16 Big-endian */
+ while( zIn<zTerm ){
+ READ_UTF8(zIn, zTerm, c);
+ WRITE_UTF16BE(z, c);
+ }
+ }
+ pMem->n = (int)(z - zOut);
+ *z++ = 0;
+ }else{
+ assert( desiredEnc==SQLITE_UTF8 );
+ if( pMem->enc==SQLITE_UTF16LE ){
+ /* UTF-16 Little-endian -> UTF-8 */
+ while( zIn<zTerm ){
+ c = *(zIn++);
+ c += (*(zIn++))<<8;
+ if( c>=0xd800 && c<0xe000 ){
+#ifdef SQLITE_REPLACE_INVALID_UTF
+ if( c>=0xdc00 || zIn>=zTerm ){
+ c = 0xfffd;
+ }else{
+ int c2 = *(zIn++);
+ c2 += (*(zIn++))<<8;
+ if( c2<0xdc00 || c2>=0xe000 ){
+ zIn -= 2;
+ c = 0xfffd;
+ }else{
+ c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000;
+ }
+ }
+#else
+ if( zIn<zTerm ){
+ int c2 = (*zIn++);
+ c2 += ((*zIn++)<<8);
+ c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);
+ }
+#endif
+ }
+ WRITE_UTF8(z, c);
+ }
+ }else{
+ /* UTF-16 Big-endian -> UTF-8 */
+ while( zIn<zTerm ){
+ c = (*(zIn++))<<8;
+ c += *(zIn++);
+ if( c>=0xd800 && c<0xe000 ){
+#ifdef SQLITE_REPLACE_INVALID_UTF
+ if( c>=0xdc00 || zIn>=zTerm ){
+ c = 0xfffd;
+ }else{
+ int c2 = (*(zIn++))<<8;
+ c2 += *(zIn++);
+ if( c2<0xdc00 || c2>=0xe000 ){
+ zIn -= 2;
+ c = 0xfffd;
+ }else{
+ c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000;
+ }
+ }
+#else
+ if( zIn<zTerm ){
+ int c2 = ((*zIn++)<<8);
+ c2 += (*zIn++);
+ c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);
+ }
+#endif
+ }
+ WRITE_UTF8(z, c);
+ }
+ }
+ pMem->n = (int)(z - zOut);
+ }
+ *z = 0;
+ assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
+
+ c = MEM_Str|MEM_Term|(pMem->flags&(MEM_AffMask|MEM_Subtype));
+ sqlite3VdbeMemRelease(pMem);
+ pMem->flags = c;
+ pMem->enc = desiredEnc;
+ pMem->z = (char*)zOut;
+ pMem->zMalloc = pMem->z;
+ pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
+
+translate_out:
+#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
+ {
+ StrAccum acc;
+ char zBuf[1000];
+ sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
+ sqlite3VdbeMemPrettyPrint(pMem, &acc);
+ fprintf(stderr, "OUTPUT: %s\n", sqlite3StrAccumFinish(&acc));
+ }
+#endif
+ return SQLITE_OK;
+}
+#endif /* SQLITE_OMIT_UTF16 */
+
+#ifndef SQLITE_OMIT_UTF16
+/*
+** This routine checks for a byte-order mark at the beginning of the
+** UTF-16 string stored in *pMem. If one is present, it is removed and
+** the encoding of the Mem adjusted. This routine does not do any
+** byte-swapping, it just sets Mem.enc appropriately.
+**
+** The allocation (static, dynamic etc.) and encoding of the Mem may be
+** changed by this function.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
+ int rc = SQLITE_OK;
+ u8 bom = 0;
+
+ assert( pMem->n>=0 );
+ if( pMem->n>1 ){
+ u8 b1 = *(u8 *)pMem->z;
+ u8 b2 = *(((u8 *)pMem->z) + 1);
+ if( b1==0xFE && b2==0xFF ){
+ bom = SQLITE_UTF16BE;
+ }
+ if( b1==0xFF && b2==0xFE ){
+ bom = SQLITE_UTF16LE;
+ }
+ }
+
+ if( bom ){
+ rc = sqlite3VdbeMemMakeWriteable(pMem);
+ if( rc==SQLITE_OK ){
+ pMem->n -= 2;
+ memmove(pMem->z, &pMem->z[2], pMem->n);
+ pMem->z[pMem->n] = '\0';
+ pMem->z[pMem->n+1] = '\0';
+ pMem->flags |= MEM_Term;
+ pMem->enc = bom;
+ }
+ }
+ return rc;
+}
+#endif /* SQLITE_OMIT_UTF16 */
+
+/*
+** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
+** return the number of unicode characters in pZ up to (but not including)
+** the first 0x00 byte. If nByte is not less than zero, return the
+** number of unicode characters in the first nByte of pZ (or up to
+** the first 0x00, whichever comes first).
+*/
+SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
+ int r = 0;
+ const u8 *z = (const u8*)zIn;
+ const u8 *zTerm;
+ if( nByte>=0 ){
+ zTerm = &z[nByte];
+ }else{
+ zTerm = (const u8*)(-1);
+ }
+ assert( z<=zTerm );
+ while( *z!=0 && z<zTerm ){
+ SQLITE_SKIP_UTF8(z);
+ r++;
+ }
+ return r;
+}
+
+/* This test function is not currently used by the automated test-suite.
+** Hence it is only available in debug builds.
+*/
+#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
+/*
+** Translate UTF-8 to UTF-8.
+**
+** This has the effect of making sure that the string is well-formed
+** UTF-8. Miscoded characters are removed.
+**
+** The translation is done in-place and aborted if the output
+** overruns the input.
+*/
+SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
+ unsigned char *zOut = zIn;
+ unsigned char *zStart = zIn;
+ u32 c;
+
+ while( zIn[0] && zOut<=zIn ){
+ c = sqlite3Utf8Read((const u8**)&zIn);
+ if( c!=0xfffd ){
+ WRITE_UTF8(zOut, c);
+ }
+ }
+ *zOut = 0;
+ return (int)(zOut - zStart);
+}
+#endif
+
+#ifndef SQLITE_OMIT_UTF16
+/*
+** Convert a UTF-16 string in the native encoding into a UTF-8 string.
+** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
+** be freed by the calling function.
+**
+** NULL is returned if there is an allocation error.
+*/
+SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
+ Mem m;
+ memset(&m, 0, sizeof(m));
+ m.db = db;
+ sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
+ sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
+ if( db->mallocFailed ){
+ sqlite3VdbeMemRelease(&m);
+ m.z = 0;
+ }
+ assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
+ assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
+ assert( m.z || db->mallocFailed );
+ return m.z;
+}
+
+/*
+** zIn is a UTF-16 encoded unicode string at least nChar characters long.
+** Return the number of bytes in the first nChar unicode characters
+** in pZ. nChar must be non-negative.
+*/
+SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
+ int c;
+ unsigned char const *z = zIn;
+ int n = 0;
+
+ if( SQLITE_UTF16NATIVE==SQLITE_UTF16LE ) z++;
+ while( n<nChar ){
+ c = z[0];
+ z += 2;
+ if( c>=0xd8 && c<0xdc && z[0]>=0xdc && z[0]<0xe0 ) z += 2;
+ n++;
+ }
+ return (int)(z-(unsigned char const *)zIn)
+ - (SQLITE_UTF16NATIVE==SQLITE_UTF16LE);
+}
+
+#if defined(SQLITE_TEST)
+/*
+** This routine is called from the TCL test function "translate_selftest".
+** It checks that the primitives for serializing and deserializing
+** characters in each encoding are inverses of each other.
+*/
+SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
+ unsigned int i, t;
+ unsigned char zBuf[20];
+ unsigned char *z;
+ int n;
+ unsigned int c;
+
+ for(i=0; i<0x00110000; i++){
+ z = zBuf;
+ WRITE_UTF8(z, i);
+ n = (int)(z-zBuf);
+ assert( n>0 && n<=4 );
+ z[0] = 0;
+ z = zBuf;
+ c = sqlite3Utf8Read((const u8**)&z);
+ t = i;
+ if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
+ if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
+ assert( c==t );
+ assert( (z-zBuf)==n );
+ }
+}
+#endif /* SQLITE_TEST */
+#endif /* SQLITE_OMIT_UTF16 */
+
+/************** End of utf.c *************************************************/
+/************** Begin file util.c ********************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** Utility functions used throughout sqlite.
+**
+** This file contains functions for allocating memory, comparing
+** strings, and stuff like that.
+**
+*/
+/* #include "sqliteInt.h" */
+/* #include <stdarg.h> */
+#ifndef SQLITE_OMIT_FLOATING_POINT
+#include <math.h>
+#endif
+
+/*
+** Routine needed to support the testcase() macro.
+*/
+#ifdef SQLITE_COVERAGE_TEST
+SQLITE_PRIVATE void sqlite3Coverage(int x){
+ static unsigned dummy = 0;
+ dummy += (unsigned)x;
+}
+#endif
+
+/*
+** Calls to sqlite3FaultSim() are used to simulate a failure during testing,
+** or to bypass normal error detection during testing in order to let
+** execute proceed futher downstream.
+**
+** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0). The
+** sqlite3FaultSim() function only returns non-zero during testing.
+**
+** During testing, if the test harness has set a fault-sim callback using
+** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then
+** each call to sqlite3FaultSim() is relayed to that application-supplied
+** callback and the integer return value form the application-supplied
+** callback is returned by sqlite3FaultSim().
+**
+** The integer argument to sqlite3FaultSim() is a code to identify which
+** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim()
+** should have a unique code. To prevent legacy testing applications from
+** breaking, the codes should not be changed or reused.
+*/
+#ifndef SQLITE_UNTESTABLE
+SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
+ int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
+ return xCallback ? xCallback(iTest) : SQLITE_OK;
+}
+#endif
+
+#ifndef SQLITE_OMIT_FLOATING_POINT
+/*
+** Return true if the floating point value is Not a Number (NaN).
+*/
+SQLITE_PRIVATE int sqlite3IsNaN(double x){
+ u64 y;
+ memcpy(&y,&x,sizeof(y));
+ return IsNaN(y);
+}
+#endif /* SQLITE_OMIT_FLOATING_POINT */
+
+/*
+** Compute a string length that is limited to what can be stored in
+** lower 30 bits of a 32-bit signed integer.
+**
+** The value returned will never be negative. Nor will it ever be greater
+** than the actual length of the string. For very long strings (greater
+** than 1GiB) the value returned might be less than the true string length.
+*/
+SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
+ if( z==0 ) return 0;
+ return 0x3fffffff & (int)strlen(z);
+}
+
+/*
+** Return the declared type of a column. Or return zDflt if the column
+** has no declared type.
+**
+** The column type is an extra string stored after the zero-terminator on
+** the column name if and only if the COLFLAG_HASTYPE flag is set.
+*/
+SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
+ if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
+ return pCol->zName + strlen(pCol->zName) + 1;
+}
+
+/*
+** Helper function for sqlite3Error() - called rarely. Broken out into
+** a separate routine to avoid unnecessary register saves on entry to
+** sqlite3Error().
+*/
+static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
+ if( db->pErr ) sqlite3ValueSetNull(db->pErr);
+ sqlite3SystemError(db, err_code);
+}
+
+/*
+** Set the current error code to err_code and clear any prior error message.
+** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
+** that would be appropriate.
+*/
+SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
+ assert( db!=0 );
+ db->errCode = err_code;
+ if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
+}
+
+/*
+** Load the sqlite3.iSysErrno field if that is an appropriate thing
+** to do based on the SQLite error code in rc.
+*/
+SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
+ if( rc==SQLITE_IOERR_NOMEM ) return;
+ rc &= 0xff;
+ if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
+ db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
+ }
+}
+
+/*
+** Set the most recent error code and error string for the sqlite
+** handle "db". The error code is set to "err_code".
+**
+** If it is not NULL, string zFormat specifies the format of the
+** error string in the style of the printf functions: The following
+** format characters are allowed:
+**
+** %s Insert a string
+** %z A string that should be freed after use
+** %d Insert an integer
+** %T Insert a token
+** %S Insert the first element of a SrcList
+**
+** zFormat and any string tokens that follow it are assumed to be
+** encoded in UTF-8.
+**
+** To clear the most recent error for sqlite handle "db", sqlite3Error
+** should be called with err_code set to SQLITE_OK and zFormat set
+** to NULL.
+*/
+SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
+ assert( db!=0 );
+ db->errCode = err_code;
+ sqlite3SystemError(db, err_code);
+ if( zFormat==0 ){
+ sqlite3Error(db, err_code);
+ }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
+ char *z;
+ va_list ap;
+ va_start(ap, zFormat);
+ z = sqlite3VMPrintf(db, zFormat, ap);
+ va_end(ap);
+ sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
+ }
+}
+
+/*
+** Add an error message to pParse->zErrMsg and increment pParse->nErr.
+** The following formatting characters are allowed:
+**
+** %s Insert a string
+** %z A string that should be freed after use
+** %d Insert an integer
+** %T Insert a token
+** %S Insert the first element of a SrcList
+**
+** This function should be used to report any error that occurs while
+** compiling an SQL statement (i.e. within sqlite3_prepare()). The
+** last thing the sqlite3_prepare() function does is copy the error
+** stored by this function into the database handle using sqlite3Error().
+** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
+** during statement execution (sqlite3_step() etc.).
+*/
+SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
+ char *zMsg;
+ va_list ap;
+ sqlite3 *db = pParse->db;
+ va_start(ap, zFormat);
+ zMsg = sqlite3VMPrintf(db, zFormat, ap);
+ va_end(ap);
+ if( db->suppressErr ){
+ sqlite3DbFree(db, zMsg);
+ }else{
+ pParse->nErr++;
+ sqlite3DbFree(db, pParse->zErrMsg);
+ pParse->zErrMsg = zMsg;
+ pParse->rc = SQLITE_ERROR;
+ pParse->pWith = 0;
+ }
+}
+
+/*
+** If database connection db is currently parsing SQL, then transfer
+** error code errCode to that parser if the parser has not already
+** encountered some other kind of error.
+*/
+SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3 *db, int errCode){
+ Parse *pParse;
+ if( db==0 || (pParse = db->pParse)==0 ) return errCode;
+ pParse->rc = errCode;
+ pParse->nErr++;
+ return errCode;
+}
+
+/*
+** Convert an SQL-style quoted string into a normal string by removing
+** the quote characters. The conversion is done in-place. If the
+** input does not begin with a quote character, then this routine
+** is a no-op.
+**
+** The input string must be zero-terminated. A new zero-terminator
+** is added to the dequoted string.
+**
+** The return value is -1 if no dequoting occurs or the length of the
+** dequoted string, exclusive of the zero terminator, if dequoting does
+** occur.
+**
+** 2002-02-14: This routine is extended to remove MS-Access style
+** brackets from around identifiers. For example: "[a-b-c]" becomes
+** "a-b-c".
+*/
+SQLITE_PRIVATE void sqlite3Dequote(char *z){
+ char quote;
+ int i, j;
+ if( z==0 ) return;
+ quote = z[0];
+ if( !sqlite3Isquote(quote) ) return;
+ if( quote=='[' ) quote = ']';
+ for(i=1, j=0;; i++){
+ assert( z[i] );
+ if( z[i]==quote ){
+ if( z[i+1]==quote ){
+ z[j++] = quote;
+ i++;
+ }else{
+ break;
+ }
+ }else{
+ z[j++] = z[i];
+ }
+ }
+ z[j] = 0;
+}
+SQLITE_PRIVATE void sqlite3DequoteExpr(Expr *p){
+ assert( sqlite3Isquote(p->u.zToken[0]) );
+ p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
+ sqlite3Dequote(p->u.zToken);
+}
+
+/*
+** Generate a Token object from a string
+*/
+SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
+ p->z = z;
+ p->n = sqlite3Strlen30(z);
+}
+
+/* Convenient short-hand */
+#define UpperToLower sqlite3UpperToLower
+
+/*
+** Some systems have stricmp(). Others have strcasecmp(). Because
+** there is no consistency, we will define our own.
+**
+** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
+** sqlite3_strnicmp() APIs allow applications and extensions to compare
+** the contents of two buffers containing UTF-8 strings in a
+** case-independent fashion, using the same definition of "case
+** independence" that SQLite uses internally when comparing identifiers.
+*/
+SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
+ if( zLeft==0 ){
+ return zRight ? -1 : 0;
+ }else if( zRight==0 ){
+ return 1;
+ }
+ return sqlite3StrICmp(zLeft, zRight);
+}
+SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
+ unsigned char *a, *b;
+ int c, x;
+ a = (unsigned char *)zLeft;
+ b = (unsigned char *)zRight;
+ for(;;){
+ c = *a;
+ x = *b;
+ if( c==x ){
+ if( c==0 ) break;
+ }else{
+ c = (int)UpperToLower[c] - (int)UpperToLower[x];
+ if( c ) break;
+ }
+ a++;
+ b++;
+ }
+ return c;
+}
+SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
+ register unsigned char *a, *b;
+ if( zLeft==0 ){
+ return zRight ? -1 : 0;
+ }else if( zRight==0 ){
+ return 1;
+ }
+ a = (unsigned char *)zLeft;
+ b = (unsigned char *)zRight;
+ while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
+ return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
+}
+
+/*
+** Compute an 8-bit hash on a string that is insensitive to case differences
+*/
+SQLITE_PRIVATE u8 sqlite3StrIHash(const char *z){
+ u8 h = 0;
+ if( z==0 ) return 0;
+ while( z[0] ){
+ h += UpperToLower[(unsigned char)z[0]];
+ z++;
+ }
+ return h;
+}
+
+/*
+** Compute 10 to the E-th power. Examples: E==1 results in 10.
+** E==2 results in 100. E==50 results in 1.0e50.
+**
+** This routine only works for values of E between 1 and 341.
+*/
+static LONGDOUBLE_TYPE sqlite3Pow10(int E){
+#if defined(_MSC_VER)
+ static const LONGDOUBLE_TYPE x[] = {
+ 1.0e+001L,
+ 1.0e+002L,
+ 1.0e+004L,
+ 1.0e+008L,
+ 1.0e+016L,
+ 1.0e+032L,
+ 1.0e+064L,
+ 1.0e+128L,
+ 1.0e+256L
+ };
+ LONGDOUBLE_TYPE r = 1.0;
+ int i;
+ assert( E>=0 && E<=307 );
+ for(i=0; E!=0; i++, E >>=1){
+ if( E & 1 ) r *= x[i];
+ }
+ return r;
+#else
+ LONGDOUBLE_TYPE x = 10.0;
+ LONGDOUBLE_TYPE r = 1.0;
+ while(1){
+ if( E & 1 ) r *= x;
+ E >>= 1;
+ if( E==0 ) break;
+ x *= x;
+ }
+ return r;
+#endif
+}
+
+/*
+** The string z[] is an text representation of a real number.
+** Convert this string to a double and write it into *pResult.
+**
+** The string z[] is length bytes in length (bytes, not characters) and
+** uses the encoding enc. The string is not necessarily zero-terminated.
+**
+** Return TRUE if the result is a valid real number (or integer) and FALSE
+** if the string is empty or contains extraneous text. More specifically
+** return
+** 1 => The input string is a pure integer
+** 2 or more => The input has a decimal point or eNNN clause
+** 0 or less => The input string is not a valid number
+** -1 => Not a valid number, but has a valid prefix which
+** includes a decimal point and/or an eNNN clause
+**
+** Valid numbers are in one of these formats:
+**
+** [+-]digits[E[+-]digits]
+** [+-]digits.[digits][E[+-]digits]
+** [+-].digits[E[+-]digits]
+**
+** Leading and trailing whitespace is ignored for the purpose of determining
+** validity.
+**
+** If some prefix of the input string is a valid number, this routine
+** returns FALSE but it still converts the prefix and writes the result
+** into *pResult.
+*/
+#if defined(_MSC_VER)
+#pragma warning(disable : 4756)
+#endif
+SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ int incr;
+ const char *zEnd;
+ /* sign * significand * (10 ^ (esign * exponent)) */
+ int sign = 1; /* sign of significand */
+ i64 s = 0; /* significand */
+ int d = 0; /* adjust exponent for shifting decimal point */
+ int esign = 1; /* sign of exponent */
+ int e = 0; /* exponent */
+ int eValid = 1; /* True exponent is either not used or is well-formed */
+ double result;
+ int nDigit = 0; /* Number of digits processed */
+ int eType = 1; /* 1: pure integer, 2+: fractional -1 or less: bad UTF16 */
+
+ assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
+ *pResult = 0.0; /* Default return value, in case of an error */
+ if( length==0 ) return 0;
+
+ if( enc==SQLITE_UTF8 ){
+ incr = 1;
+ zEnd = z + length;
+ }else{
+ int i;
+ incr = 2;
+ length &= ~1;
+ assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
+ testcase( enc==SQLITE_UTF16LE );
+ testcase( enc==SQLITE_UTF16BE );
+ for(i=3-enc; i<length && z[i]==0; i+=2){}
+ if( i<length ) eType = -100;
+ zEnd = &z[i^1];
+ z += (enc&1);
+ }
+
+ /* skip leading spaces */
+ while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
+ if( z>=zEnd ) return 0;
+
+ /* get sign of significand */
+ if( *z=='-' ){
+ sign = -1;
+ z+=incr;
+ }else if( *z=='+' ){
+ z+=incr;
+ }
+
+ /* copy max significant digits to significand */
+ while( z<zEnd && sqlite3Isdigit(*z) ){
+ s = s*10 + (*z - '0');
+ z+=incr; nDigit++;
+ if( s>=((LARGEST_INT64-9)/10) ){
+ /* skip non-significant significand digits
+ ** (increase exponent by d to shift decimal left) */
+ while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; d++; }
+ }
+ }
+ if( z>=zEnd ) goto do_atof_calc;
+
+ /* if decimal point is present */
+ if( *z=='.' ){
+ z+=incr;
+ eType++;
+ /* copy digits from after decimal to significand
+ ** (decrease exponent by d to shift decimal right) */
+ while( z<zEnd && sqlite3Isdigit(*z) ){
+ if( s<((LARGEST_INT64-9)/10) ){
+ s = s*10 + (*z - '0');
+ d--;
+ nDigit++;
+ }
+ z+=incr;
+ }
+ }
+ if( z>=zEnd ) goto do_atof_calc;
+
+ /* if exponent is present */
+ if( *z=='e' || *z=='E' ){
+ z+=incr;
+ eValid = 0;
+ eType++;
+
+ /* This branch is needed to avoid a (harmless) buffer overread. The
+ ** special comment alerts the mutation tester that the correct answer
+ ** is obtained even if the branch is omitted */
+ if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
+
+ /* get sign of exponent */
+ if( *z=='-' ){
+ esign = -1;
+ z+=incr;
+ }else if( *z=='+' ){
+ z+=incr;
+ }
+ /* copy digits to exponent */
+ while( z<zEnd && sqlite3Isdigit(*z) ){
+ e = e<10000 ? (e*10 + (*z - '0')) : 10000;
+ z+=incr;
+ eValid = 1;
+ }
+ }
+
+ /* skip trailing spaces */
+ while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
+
+do_atof_calc:
+ /* adjust exponent by d, and update sign */
+ e = (e*esign) + d;
+ if( e<0 ) {
+ esign = -1;
+ e *= -1;
+ } else {
+ esign = 1;
+ }
+
+ if( s==0 ) {
+ /* In the IEEE 754 standard, zero is signed. */
+ result = sign<0 ? -(double)0 : (double)0;
+ } else {
+ /* Attempt to reduce exponent.
+ **
+ ** Branches that are not required for the correct answer but which only
+ ** help to obtain the correct answer faster are marked with special
+ ** comments, as a hint to the mutation tester.
+ */
+ while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
+ if( esign>0 ){
+ if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
+ s *= 10;
+ }else{
+ if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
+ s /= 10;
+ }
+ e--;
+ }
+
+ /* adjust the sign of significand */
+ s = sign<0 ? -s : s;
+
+ if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
+ result = (double)s;
+ }else{
+ /* attempt to handle extremely small/large numbers better */
+ if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
+ if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
+ LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
+ if( esign<0 ){
+ result = s / scale;
+ result /= 1.0e+308;
+ }else{
+ result = s * scale;
+ result *= 1.0e+308;
+ }
+ }else{ assert( e>=342 );
+ if( esign<0 ){
+ result = 0.0*s;
+ }else{
+#ifdef INFINITY
+ result = INFINITY*s;
+#else
+ result = 1e308*1e308*s; /* Infinity */
+#endif
+ }
+ }
+ }else{
+ LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
+ if( esign<0 ){
+ result = s / scale;
+ }else{
+ result = s * scale;
+ }
+ }
+ }
+ }
+
+ /* store the result */
+ *pResult = result;
+
+ /* return true if number and no extra non-whitespace chracters after */
+ if( z==zEnd && nDigit>0 && eValid && eType>0 ){
+ return eType;
+ }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){
+ return -1;
+ }else{
+ return 0;
+ }
+#else
+ return !sqlite3Atoi64(z, pResult, length, enc);
+#endif /* SQLITE_OMIT_FLOATING_POINT */
+}
+#if defined(_MSC_VER)
+#pragma warning(default : 4756)
+#endif
+
+/*
+** Render an signed 64-bit integer as text. Store the result in zOut[].
+**
+** The caller must ensure that zOut[] is at least 21 bytes in size.
+*/
+SQLITE_PRIVATE void sqlite3Int64ToText(i64 v, char *zOut){
+ int i;
+ u64 x;
+ char zTemp[22];
+ if( v<0 ){
+ x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v;
+ }else{
+ x = v;
+ }
+ i = sizeof(zTemp)-2;
+ zTemp[sizeof(zTemp)-1] = 0;
+ do{
+ zTemp[i--] = (x%10) + '0';
+ x = x/10;
+ }while( x );
+ if( v<0 ) zTemp[i--] = '-';
+ memcpy(zOut, &zTemp[i+1], sizeof(zTemp)-1-i);
+}
+
+/*
+** Compare the 19-character string zNum against the text representation
+** value 2^63: 9223372036854775808. Return negative, zero, or positive
+** if zNum is less than, equal to, or greater than the string.
+** Note that zNum must contain exactly 19 characters.
+**
+** Unlike memcmp() this routine is guaranteed to return the difference
+** in the values of the last digit if the only difference is in the
+** last digit. So, for example,
+**
+** compare2pow63("9223372036854775800", 1)
+**
+** will return -8.
+*/
+static int compare2pow63(const char *zNum, int incr){
+ int c = 0;
+ int i;
+ /* 012345678901234567 */
+ const char *pow63 = "922337203685477580";
+ for(i=0; c==0 && i<18; i++){
+ c = (zNum[i*incr]-pow63[i])*10;
+ }
+ if( c==0 ){
+ c = zNum[18*incr] - '8';
+ testcase( c==(-1) );
+ testcase( c==0 );
+ testcase( c==(+1) );
+ }
+ return c;
+}
+
+/*
+** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
+** routine does *not* accept hexadecimal notation.
+**
+** Returns:
+**
+** -1 Not even a prefix of the input text looks like an integer
+** 0 Successful transformation. Fits in a 64-bit signed integer.
+** 1 Excess non-space text after the integer value
+** 2 Integer too large for a 64-bit signed integer or is malformed
+** 3 Special case of 9223372036854775808
+**
+** length is the number of bytes in the string (bytes, not characters).
+** The string is not necessarily zero-terminated. The encoding is
+** given by enc.
+*/
+SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
+ int incr;
+ u64 u = 0;
+ int neg = 0; /* assume positive */
+ int i;
+ int c = 0;
+ int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
+ int rc; /* Baseline return code */
+ const char *zStart;
+ const char *zEnd = zNum + length;
+ assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
+ if( enc==SQLITE_UTF8 ){
+ incr = 1;
+ }else{
+ incr = 2;
+ length &= ~1;
+ assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
+ for(i=3-enc; i<length && zNum[i]==0; i+=2){}
+ nonNum = i<length;
+ zEnd = &zNum[i^1];
+ zNum += (enc&1);
+ }
+ while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
+ if( zNum<zEnd ){
+ if( *zNum=='-' ){
+ neg = 1;
+ zNum+=incr;
+ }else if( *zNum=='+' ){
+ zNum+=incr;
+ }
+ }
+ zStart = zNum;
+ while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
+ for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
+ u = u*10 + c - '0';
+ }
+ testcase( i==18*incr );
+ testcase( i==19*incr );
+ testcase( i==20*incr );
+ if( u>LARGEST_INT64 ){
+ /* This test and assignment is needed only to suppress UB warnings
+ ** from clang and -fsanitize=undefined. This test and assignment make
+ ** the code a little larger and slower, and no harm comes from omitting
+ ** them, but we must appaise the undefined-behavior pharisees. */
+ *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
+ }else if( neg ){
+ *pNum = -(i64)u;
+ }else{
+ *pNum = (i64)u;
+ }
+ rc = 0;
+ if( i==0 && zStart==zNum ){ /* No digits */
+ rc = -1;
+ }else if( nonNum ){ /* UTF16 with high-order bytes non-zero */
+ rc = 1;
+ }else if( &zNum[i]<zEnd ){ /* Extra bytes at the end */
+ int jj = i;
+ do{
+ if( !sqlite3Isspace(zNum[jj]) ){
+ rc = 1; /* Extra non-space text after the integer */
+ break;
+ }
+ jj += incr;
+ }while( &zNum[jj]<zEnd );
+ }
+ if( i<19*incr ){
+ /* Less than 19 digits, so we know that it fits in 64 bits */
+ assert( u<=LARGEST_INT64 );
+ return rc;
+ }else{
+ /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
+ c = i>19*incr ? 1 : compare2pow63(zNum, incr);
+ if( c<0 ){
+ /* zNum is less than 9223372036854775808 so it fits */
+ assert( u<=LARGEST_INT64 );
+ return rc;
+ }else{
+ *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
+ if( c>0 ){
+ /* zNum is greater than 9223372036854775808 so it overflows */
+ return 2;
+ }else{
+ /* zNum is exactly 9223372036854775808. Fits if negative. The
+ ** special case 2 overflow if positive */
+ assert( u-1==LARGEST_INT64 );
+ return neg ? rc : 3;
+ }
+ }
+ }
+}
+
+/*
+** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
+** into a 64-bit signed integer. This routine accepts hexadecimal literals,
+** whereas sqlite3Atoi64() does not.
+**
+** Returns:
+**
+** 0 Successful transformation. Fits in a 64-bit signed integer.
+** 1 Excess text after the integer value
+** 2 Integer too large for a 64-bit signed integer or is malformed
+** 3 Special case of 9223372036854775808
+*/
+SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
+#ifndef SQLITE_OMIT_HEX_INTEGER
+ if( z[0]=='0'
+ && (z[1]=='x' || z[1]=='X')
+ ){
+ u64 u = 0;
+ int i, k;
+ for(i=2; z[i]=='0'; i++){}
+ for(k=i; sqlite3Isxdigit(z[k]); k++){
+ u = u*16 + sqlite3HexToInt(z[k]);
+ }
+ memcpy(pOut, &u, 8);
+ return (z[k]==0 && k-i<=16) ? 0 : 2;
+ }else
+#endif /* SQLITE_OMIT_HEX_INTEGER */
+ {
+ return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
+ }
+}
+
+/*
+** If zNum represents an integer that will fit in 32-bits, then set
+** *pValue to that integer and return true. Otherwise return false.
+**
+** This routine accepts both decimal and hexadecimal notation for integers.
+**
+** Any non-numeric characters that following zNum are ignored.
+** This is different from sqlite3Atoi64() which requires the
+** input number to be zero-terminated.
+*/
+SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
+ sqlite_int64 v = 0;
+ int i, c;
+ int neg = 0;
+ if( zNum[0]=='-' ){
+ neg = 1;
+ zNum++;
+ }else if( zNum[0]=='+' ){
+ zNum++;
+ }
+#ifndef SQLITE_OMIT_HEX_INTEGER
+ else if( zNum[0]=='0'
+ && (zNum[1]=='x' || zNum[1]=='X')
+ && sqlite3Isxdigit(zNum[2])
+ ){
+ u32 u = 0;
+ zNum += 2;
+ while( zNum[0]=='0' ) zNum++;
+ for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
+ u = u*16 + sqlite3HexToInt(zNum[i]);
+ }
+ if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
+ memcpy(pValue, &u, 4);
+ return 1;
+ }else{
+ return 0;
+ }
+ }
+#endif
+ if( !sqlite3Isdigit(zNum[0]) ) return 0;
+ while( zNum[0]=='0' ) zNum++;
+ for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
+ v = v*10 + c;
+ }
+
+ /* The longest decimal representation of a 32 bit integer is 10 digits:
+ **
+ ** 1234567890
+ ** 2^31 -> 2147483648
+ */
+ testcase( i==10 );
+ if( i>10 ){
+ return 0;
+ }
+ testcase( v-neg==2147483647 );
+ if( v-neg>2147483647 ){
+ return 0;
+ }
+ if( neg ){
+ v = -v;
+ }
+ *pValue = (int)v;
+ return 1;
+}
+
+/*
+** Return a 32-bit integer value extracted from a string. If the
+** string is not an integer, just return 0.
+*/
+SQLITE_PRIVATE int sqlite3Atoi(const char *z){
+ int x = 0;
+ sqlite3GetInt32(z, &x);
+ return x;
+}
+
+/*
+** Try to convert z into an unsigned 32-bit integer. Return true on
+** success and false if there is an error.
+**
+** Only decimal notation is accepted.
+*/
+SQLITE_PRIVATE int sqlite3GetUInt32(const char *z, u32 *pI){
+ u64 v = 0;
+ int i;
+ for(i=0; sqlite3Isdigit(z[i]); i++){
+ v = v*10 + z[i] - '0';
+ if( v>4294967296LL ){ *pI = 0; return 0; }
+ }
+ if( i==0 || z[i]!=0 ){ *pI = 0; return 0; }
+ *pI = (u32)v;
+ return 1;
+}
+
+/*
+** The variable-length integer encoding is as follows:
+**
+** KEY:
+** A = 0xxxxxxx 7 bits of data and one flag bit
+** B = 1xxxxxxx 7 bits of data and one flag bit
+** C = xxxxxxxx 8 bits of data
+**
+** 7 bits - A
+** 14 bits - BA
+** 21 bits - BBA
+** 28 bits - BBBA
+** 35 bits - BBBBA
+** 42 bits - BBBBBA
+** 49 bits - BBBBBBA
+** 56 bits - BBBBBBBA
+** 64 bits - BBBBBBBBC
+*/
+
+/*
+** Write a 64-bit variable-length integer to memory starting at p[0].
+** The length of data write will be between 1 and 9 bytes. The number
+** of bytes written is returned.
+**
+** A variable-length integer consists of the lower 7 bits of each byte
+** for all bytes that have the 8th bit set and one byte with the 8th
+** bit clear. Except, if we get to the 9th byte, it stores the full
+** 8 bits and is the last byte.
+*/
+static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
+ int i, j, n;
+ u8 buf[10];
+ if( v & (((u64)0xff000000)<<32) ){
+ p[8] = (u8)v;
+ v >>= 8;
+ for(i=7; i>=0; i--){
+ p[i] = (u8)((v & 0x7f) | 0x80);
+ v >>= 7;
+ }
+ return 9;
+ }
+ n = 0;
+ do{
+ buf[n++] = (u8)((v & 0x7f) | 0x80);
+ v >>= 7;
+ }while( v!=0 );
+ buf[0] &= 0x7f;
+ assert( n<=9 );
+ for(i=0, j=n-1; j>=0; j--, i++){
+ p[i] = buf[j];
+ }
+ return n;
+}
+SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
+ if( v<=0x7f ){
+ p[0] = v&0x7f;
+ return 1;
+ }
+ if( v<=0x3fff ){
+ p[0] = ((v>>7)&0x7f)|0x80;
+ p[1] = v&0x7f;
+ return 2;
+ }
+ return putVarint64(p,v);
+}
+
+/*
+** Bitmasks used by sqlite3GetVarint(). These precomputed constants
+** are defined here rather than simply putting the constant expressions
+** inline in order to work around bugs in the RVT compiler.
+**
+** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
+**
+** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
+*/
+#define SLOT_2_0 0x001fc07f
+#define SLOT_4_2_0 0xf01fc07f
+
+
+/*
+** Read a 64-bit variable-length integer from memory starting at p[0].
+** Return the number of bytes read. The value is stored in *v.
+*/
+SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
+ u32 a,b,s;
+
+ if( ((signed char*)p)[0]>=0 ){
+ *v = *p;
+ return 1;
+ }
+ if( ((signed char*)p)[1]>=0 ){
+ *v = ((u32)(p[0]&0x7f)<<7) | p[1];
+ return 2;
+ }
+
+ /* Verify that constants are precomputed correctly */
+ assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
+ assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
+
+ a = ((u32)p[0])<<14;
+ b = p[1];
+ p += 2;
+ a |= *p;
+ /* a: p0<<14 | p2 (unmasked) */
+ if (!(a&0x80))
+ {
+ a &= SLOT_2_0;
+ b &= 0x7f;
+ b = b<<7;
+ a |= b;
+ *v = a;
+ return 3;
+ }
+
+ /* CSE1 from below */
+ a &= SLOT_2_0;
+ p++;
+ b = b<<14;
+ b |= *p;
+ /* b: p1<<14 | p3 (unmasked) */
+ if (!(b&0x80))
+ {
+ b &= SLOT_2_0;
+ /* moved CSE1 up */
+ /* a &= (0x7f<<14)|(0x7f); */
+ a = a<<7;
+ a |= b;
+ *v = a;
+ return 4;
+ }
+
+ /* a: p0<<14 | p2 (masked) */
+ /* b: p1<<14 | p3 (unmasked) */
+ /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
+ /* moved CSE1 up */
+ /* a &= (0x7f<<14)|(0x7f); */
+ b &= SLOT_2_0;
+ s = a;
+ /* s: p0<<14 | p2 (masked) */
+
+ p++;
+ a = a<<14;
+ a |= *p;
+ /* a: p0<<28 | p2<<14 | p4 (unmasked) */
+ if (!(a&0x80))
+ {
+ /* we can skip these cause they were (effectively) done above
+ ** while calculating s */
+ /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
+ /* b &= (0x7f<<14)|(0x7f); */
+ b = b<<7;
+ a |= b;
+ s = s>>18;
+ *v = ((u64)s)<<32 | a;
+ return 5;
+ }
+
+ /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
+ s = s<<7;
+ s |= b;
+ /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
+
+ p++;
+ b = b<<14;
+ b |= *p;
+ /* b: p1<<28 | p3<<14 | p5 (unmasked) */
+ if (!(b&0x80))
+ {
+ /* we can skip this cause it was (effectively) done above in calc'ing s */
+ /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
+ a &= SLOT_2_0;
+ a = a<<7;
+ a |= b;
+ s = s>>18;
+ *v = ((u64)s)<<32 | a;
+ return 6;
+ }
+
+ p++;
+ a = a<<14;
+ a |= *p;
+ /* a: p2<<28 | p4<<14 | p6 (unmasked) */
+ if (!(a&0x80))
+ {
+ a &= SLOT_4_2_0;
+ b &= SLOT_2_0;
+ b = b<<7;
+ a |= b;
+ s = s>>11;
+ *v = ((u64)s)<<32 | a;
+ return 7;
+ }
+
+ /* CSE2 from below */
+ a &= SLOT_2_0;
+ p++;
+ b = b<<14;
+ b |= *p;
+ /* b: p3<<28 | p5<<14 | p7 (unmasked) */
+ if (!(b&0x80))
+ {
+ b &= SLOT_4_2_0;
+ /* moved CSE2 up */
+ /* a &= (0x7f<<14)|(0x7f); */
+ a = a<<7;
+ a |= b;
+ s = s>>4;
+ *v = ((u64)s)<<32 | a;
+ return 8;
+ }
+
+ p++;
+ a = a<<15;
+ a |= *p;
+ /* a: p4<<29 | p6<<15 | p8 (unmasked) */
+
+ /* moved CSE2 up */
+ /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
+ b &= SLOT_2_0;
+ b = b<<8;
+ a |= b;
+
+ s = s<<4;
+ b = p[-4];
+ b &= 0x7f;
+ b = b>>3;
+ s |= b;
+
+ *v = ((u64)s)<<32 | a;
+
+ return 9;
+}
+
+/*
+** Read a 32-bit variable-length integer from memory starting at p[0].
+** Return the number of bytes read. The value is stored in *v.
+**
+** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
+** integer, then set *v to 0xffffffff.
+**
+** A MACRO version, getVarint32, is provided which inlines the
+** single-byte case. All code should use the MACRO version as
+** this function assumes the single-byte case has already been handled.
+*/
+SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
+ u32 a,b;
+
+ /* The 1-byte case. Overwhelmingly the most common. Handled inline
+ ** by the getVarin32() macro */
+ a = *p;
+ /* a: p0 (unmasked) */
+#ifndef getVarint32
+ if (!(a&0x80))
+ {
+ /* Values between 0 and 127 */
+ *v = a;
+ return 1;
+ }
+#endif
+
+ /* The 2-byte case */
+ p++;
+ b = *p;
+ /* b: p1 (unmasked) */
+ if (!(b&0x80))
+ {
+ /* Values between 128 and 16383 */
+ a &= 0x7f;
+ a = a<<7;
+ *v = a | b;
+ return 2;
+ }
+
+ /* The 3-byte case */
+ p++;
+ a = a<<14;
+ a |= *p;
+ /* a: p0<<14 | p2 (unmasked) */
+ if (!(a&0x80))
+ {
+ /* Values between 16384 and 2097151 */
+ a &= (0x7f<<14)|(0x7f);
+ b &= 0x7f;
+ b = b<<7;
+ *v = a | b;
+ return 3;
+ }
+
+ /* A 32-bit varint is used to store size information in btrees.
+ ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
+ ** A 3-byte varint is sufficient, for example, to record the size
+ ** of a 1048569-byte BLOB or string.
+ **
+ ** We only unroll the first 1-, 2-, and 3- byte cases. The very
+ ** rare larger cases can be handled by the slower 64-bit varint
+ ** routine.
+ */
+#if 1
+ {
+ u64 v64;
+ u8 n;
+
+ n = sqlite3GetVarint(p-2, &v64);
+ assert( n>3 && n<=9 );
+ if( (v64 & SQLITE_MAX_U32)!=v64 ){
+ *v = 0xffffffff;
+ }else{
+ *v = (u32)v64;
+ }
+ return n;
+ }
+
+#else
+ /* For following code (kept for historical record only) shows an
+ ** unrolling for the 3- and 4-byte varint cases. This code is
+ ** slightly faster, but it is also larger and much harder to test.
+ */
+ p++;
+ b = b<<14;
+ b |= *p;
+ /* b: p1<<14 | p3 (unmasked) */
+ if (!(b&0x80))
+ {
+ /* Values between 2097152 and 268435455 */
+ b &= (0x7f<<14)|(0x7f);
+ a &= (0x7f<<14)|(0x7f);
+ a = a<<7;
+ *v = a | b;
+ return 4;
+ }
+
+ p++;
+ a = a<<14;
+ a |= *p;
+ /* a: p0<<28 | p2<<14 | p4 (unmasked) */
+ if (!(a&0x80))
+ {
+ /* Values between 268435456 and 34359738367 */
+ a &= SLOT_4_2_0;
+ b &= SLOT_4_2_0;
+ b = b<<7;
+ *v = a | b;
+ return 5;
+ }
+
+ /* We can only reach this point when reading a corrupt database
+ ** file. In that case we are not in any hurry. Use the (relatively
+ ** slow) general-purpose sqlite3GetVarint() routine to extract the
+ ** value. */
+ {
+ u64 v64;
+ u8 n;
+
+ p -= 4;
+ n = sqlite3GetVarint(p, &v64);
+ assert( n>5 && n<=9 );
+ *v = (u32)v64;
+ return n;
+ }
+#endif
+}
+
+/*
+** Return the number of bytes that will be needed to store the given
+** 64-bit integer.
+*/
+SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
+ int i;
+ for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
+ return i;
+}
+
+
+/*
+** Read or write a four-byte big-endian integer value.
+*/
+SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
+#if SQLITE_BYTEORDER==4321
+ u32 x;
+ memcpy(&x,p,4);
+ return x;
+#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
+ u32 x;
+ memcpy(&x,p,4);
+ return __builtin_bswap32(x);
+#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
+ u32 x;
+ memcpy(&x,p,4);
+ return _byteswap_ulong(x);
+#else
+ testcase( p[0]&0x80 );
+ return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
+#endif
+}
+SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
+#if SQLITE_BYTEORDER==4321
+ memcpy(p,&v,4);
+#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
+ u32 x = __builtin_bswap32(v);
+ memcpy(p,&x,4);
+#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
+ u32 x = _byteswap_ulong(v);
+ memcpy(p,&x,4);
+#else
+ p[0] = (u8)(v>>24);
+ p[1] = (u8)(v>>16);
+ p[2] = (u8)(v>>8);
+ p[3] = (u8)v;
+#endif
+}
+
+
+
+/*
+** Translate a single byte of Hex into an integer.
+** This routine only works if h really is a valid hexadecimal
+** character: 0..9a..fA..F
+*/
+SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
+ assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
+#ifdef SQLITE_ASCII
+ h += 9*(1&(h>>6));
+#endif
+#ifdef SQLITE_EBCDIC
+ h += 9*(1&~(h>>4));
+#endif
+ return (u8)(h & 0xf);
+}
+
+#if !defined(SQLITE_OMIT_BLOB_LITERAL)
+/*
+** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
+** value. Return a pointer to its binary value. Space to hold the
+** binary value has been obtained from malloc and must be freed by
+** the calling routine.
+*/
+SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
+ char *zBlob;
+ int i;
+
+ zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
+ n--;
+ if( zBlob ){
+ for(i=0; i<n; i+=2){
+ zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
+ }
+ zBlob[i/2] = 0;
+ }
+ return zBlob;
+}
+#endif /* !SQLITE_OMIT_BLOB_LITERAL */
+
+/*
+** Log an error that is an API call on a connection pointer that should
+** not have been used. The "type" of connection pointer is given as the
+** argument. The zType is a word like "NULL" or "closed" or "invalid".
+*/
+static void logBadConnection(const char *zType){
+ sqlite3_log(SQLITE_MISUSE,
+ "API call with %s database connection pointer",
+ zType
+ );
+}
+
+/*
+** Check to make sure we have a valid db pointer. This test is not
+** foolproof but it does provide some measure of protection against
+** misuse of the interface such as passing in db pointers that are
+** NULL or which have been previously closed. If this routine returns
+** 1 it means that the db pointer is valid and 0 if it should not be
+** dereferenced for any reason. The calling function should invoke
+** SQLITE_MISUSE immediately.
+**
+** sqlite3SafetyCheckOk() requires that the db pointer be valid for
+** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
+** open properly and is not fit for general use but which can be
+** used as an argument to sqlite3_errmsg() or sqlite3_close().
+*/
+SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
+ u32 magic;
+ if( db==0 ){
+ logBadConnection("NULL");
+ return 0;
+ }
+ magic = db->magic;
+ if( magic!=SQLITE_MAGIC_OPEN ){
+ if( sqlite3SafetyCheckSickOrOk(db) ){
+ testcase( sqlite3GlobalConfig.xLog!=0 );
+ logBadConnection("unopened");
+ }
+ return 0;
+ }else{
+ return 1;
+ }
+}
+SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
+ u32 magic;
+ magic = db->magic;
+ if( magic!=SQLITE_MAGIC_SICK &&
+ magic!=SQLITE_MAGIC_OPEN &&
+ magic!=SQLITE_MAGIC_BUSY ){
+ testcase( sqlite3GlobalConfig.xLog!=0 );
+ logBadConnection("invalid");
+ return 0;
+ }else{
+ return 1;
+ }
+}
+
+/*
+** Attempt to add, substract, or multiply the 64-bit signed value iB against
+** the other 64-bit signed integer at *pA and store the result in *pA.
+** Return 0 on success. Or if the operation would have resulted in an
+** overflow, leave *pA unchanged and return 1.
+*/
+SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
+#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
+ return __builtin_add_overflow(*pA, iB, pA);
+#else
+ i64 iA = *pA;
+ testcase( iA==0 ); testcase( iA==1 );
+ testcase( iB==-1 ); testcase( iB==0 );
+ if( iB>=0 ){
+ testcase( iA>0 && LARGEST_INT64 - iA == iB );
+ testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
+ if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
+ }else{
+ testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
+ testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
+ if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
+ }
+ *pA += iB;
+ return 0;
+#endif
+}
+SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
+#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
+ return __builtin_sub_overflow(*pA, iB, pA);
+#else
+ testcase( iB==SMALLEST_INT64+1 );
+ if( iB==SMALLEST_INT64 ){
+ testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
+ if( (*pA)>=0 ) return 1;
+ *pA -= iB;
+ return 0;
+ }else{
+ return sqlite3AddInt64(pA, -iB);
+ }
+#endif
+}
+SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
+#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
+ return __builtin_mul_overflow(*pA, iB, pA);
+#else
+ i64 iA = *pA;
+ if( iB>0 ){
+ if( iA>LARGEST_INT64/iB ) return 1;
+ if( iA<SMALLEST_INT64/iB ) return 1;
+ }else if( iB<0 ){
+ if( iA>0 ){
+ if( iB<SMALLEST_INT64/iA ) return 1;
+ }else if( iA<0 ){
+ if( iB==SMALLEST_INT64 ) return 1;
+ if( iA==SMALLEST_INT64 ) return 1;
+ if( -iA>LARGEST_INT64/-iB ) return 1;
+ }
+ }
+ *pA = iA*iB;
+ return 0;
+#endif
+}
+
+/*
+** Compute the absolute value of a 32-bit signed integer, of possible. Or
+** if the integer has a value of -2147483648, return +2147483647
+*/
+SQLITE_PRIVATE int sqlite3AbsInt32(int x){
+ if( x>=0 ) return x;
+ if( x==(int)0x80000000 ) return 0x7fffffff;
+ return -x;
+}
+
+#ifdef SQLITE_ENABLE_8_3_NAMES
+/*
+** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
+** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
+** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
+** three characters, then shorten the suffix on z[] to be the last three
+** characters of the original suffix.
+**
+** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
+** do the suffix shortening regardless of URI parameter.
+**
+** Examples:
+**
+** test.db-journal => test.nal
+** test.db-wal => test.wal
+** test.db-shm => test.shm
+** test.db-mj7f3319fa => test.9fa
+*/
+SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
+#if SQLITE_ENABLE_8_3_NAMES<2
+ if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
+#endif
+ {
+ int i, sz;
+ sz = sqlite3Strlen30(z);
+ for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
+ if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
+ }
+}
+#endif
+
+/*
+** Find (an approximate) sum of two LogEst values. This computation is
+** not a simple "+" operator because LogEst is stored as a logarithmic
+** value.
+**
+*/
+SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
+ static const unsigned char x[] = {
+ 10, 10, /* 0,1 */
+ 9, 9, /* 2,3 */
+ 8, 8, /* 4,5 */
+ 7, 7, 7, /* 6,7,8 */
+ 6, 6, 6, /* 9,10,11 */
+ 5, 5, 5, /* 12-14 */
+ 4, 4, 4, 4, /* 15-18 */
+ 3, 3, 3, 3, 3, 3, /* 19-24 */
+ 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
+ };
+ if( a>=b ){
+ if( a>b+49 ) return a;
+ if( a>b+31 ) return a+1;
+ return a+x[a-b];
+ }else{
+ if( b>a+49 ) return b;
+ if( b>a+31 ) return b+1;
+ return b+x[b-a];
+ }
+}
+
+/*
+** Convert an integer into a LogEst. In other words, compute an
+** approximation for 10*log2(x).
+*/
+SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
+ static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
+ LogEst y = 40;
+ if( x<8 ){
+ if( x<2 ) return 0;
+ while( x<8 ){ y -= 10; x <<= 1; }
+ }else{
+#if GCC_VERSION>=5004000
+ int i = 60 - __builtin_clzll(x);
+ y += i*10;
+ x >>= i;
+#else
+ while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
+ while( x>15 ){ y += 10; x >>= 1; }
+#endif
+ }
+ return a[x&7] + y - 10;
+}
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/*
+** Convert a double into a LogEst
+** In other words, compute an approximation for 10*log2(x).
+*/
+SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
+ u64 a;
+ LogEst e;
+ assert( sizeof(x)==8 && sizeof(a)==8 );
+ if( x<=1 ) return 0;
+ if( x<=2000000000 ) return sqlite3LogEst((u64)x);
+ memcpy(&a, &x, 8);
+ e = (a>>52) - 1022;
+ return e*10;
+}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
+ defined(SQLITE_ENABLE_STAT4) || \
+ defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
+/*
+** Convert a LogEst into an integer.
+**
+** Note that this routine is only used when one or more of various
+** non-standard compile-time options is enabled.
+*/
+SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
+ u64 n;
+ n = x%10;
+ x /= 10;
+ if( n>=5 ) n -= 2;
+ else if( n>=1 ) n -= 1;
+#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
+ defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
+ if( x>60 ) return (u64)LARGEST_INT64;
+#else
+ /* If only SQLITE_ENABLE_STAT4 is on, then the largest input
+ ** possible to this routine is 310, resulting in a maximum x of 31 */
+ assert( x<=60 );
+#endif
+ return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
+}
+#endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
+
+/*
+** Add a new name/number pair to a VList. This might require that the
+** VList object be reallocated, so return the new VList. If an OOM
+** error occurs, the original VList returned and the
+** db->mallocFailed flag is set.
+**
+** A VList is really just an array of integers. To destroy a VList,
+** simply pass it to sqlite3DbFree().
+**
+** The first integer is the number of integers allocated for the whole
+** VList. The second integer is the number of integers actually used.
+** Each name/number pair is encoded by subsequent groups of 3 or more
+** integers.
+**
+** Each name/number pair starts with two integers which are the numeric
+** value for the pair and the size of the name/number pair, respectively.
+** The text name overlays one or more following integers. The text name
+** is always zero-terminated.
+**
+** Conceptually:
+**
+** struct VList {
+** int nAlloc; // Number of allocated slots
+** int nUsed; // Number of used slots
+** struct VListEntry {
+** int iValue; // Value for this entry
+** int nSlot; // Slots used by this entry
+** // ... variable name goes here
+** } a[0];
+** }
+**
+** During code generation, pointers to the variable names within the
+** VList are taken. When that happens, nAlloc is set to zero as an
+** indication that the VList may never again be enlarged, since the
+** accompanying realloc() would invalidate the pointers.
+*/
+SQLITE_PRIVATE VList *sqlite3VListAdd(
+ sqlite3 *db, /* The database connection used for malloc() */
+ VList *pIn, /* The input VList. Might be NULL */
+ const char *zName, /* Name of symbol to add */
+ int nName, /* Bytes of text in zName */
+ int iVal /* Value to associate with zName */
+){
+ int nInt; /* number of sizeof(int) objects needed for zName */
+ char *z; /* Pointer to where zName will be stored */
+ int i; /* Index in pIn[] where zName is stored */
+
+ nInt = nName/4 + 3;
+ assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
+ if( pIn==0 || pIn[1]+nInt > pIn[0] ){
+ /* Enlarge the allocation */
+ sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt;
+ VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
+ if( pOut==0 ) return pIn;
+ if( pIn==0 ) pOut[1] = 2;
+ pIn = pOut;
+ pIn[0] = nAlloc;
+ }
+ i = pIn[1];
+ pIn[i] = iVal;
+ pIn[i+1] = nInt;
+ z = (char*)&pIn[i+2];
+ pIn[1] = i+nInt;
+ assert( pIn[1]<=pIn[0] );
+ memcpy(z, zName, nName);
+ z[nName] = 0;
+ return pIn;
+}
+
+/*
+** Return a pointer to the name of a variable in the given VList that
+** has the value iVal. Or return a NULL if there is no such variable in
+** the list
+*/
+SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
+ int i, mx;
+ if( pIn==0 ) return 0;
+ mx = pIn[1];
+ i = 2;
+ do{
+ if( pIn[i]==iVal ) return (char*)&pIn[i+2];
+ i += pIn[i+1];
+ }while( i<mx );
+ return 0;
+}
+
+/*
+** Return the number of the variable named zName, if it is in VList.
+** or return 0 if there is no such variable.
+*/
+SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
+ int i, mx;
+ if( pIn==0 ) return 0;
+ mx = pIn[1];
+ i = 2;
+ do{
+ const char *z = (const char*)&pIn[i+2];
+ if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
+ i += pIn[i+1];
+ }while( i<mx );
+ return 0;
+}
+
+/************** End of util.c ************************************************/
+/************** Begin file hash.c ********************************************/
+/*
+** 2001 September 22
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This is the implementation of generic hash-tables
+** used in SQLite.
+*/
+/* #include "sqliteInt.h" */
+/* #include <assert.h> */
+
+/* Turn bulk memory into a hash table object by initializing the
+** fields of the Hash structure.
+**
+** "pNew" is a pointer to the hash table that is to be initialized.
+*/
+SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
+ assert( pNew!=0 );
+ pNew->first = 0;
+ pNew->count = 0;
+ pNew->htsize = 0;
+ pNew->ht = 0;
+}
+
+/* Remove all entries from a hash table. Reclaim all memory.
+** Call this routine to delete a hash table or to reset a hash table
+** to the empty state.
+*/
+SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
+ HashElem *elem; /* For looping over all elements of the table */
+
+ assert( pH!=0 );
+ elem = pH->first;
+ pH->first = 0;
+ sqlite3_free(pH->ht);
+ pH->ht = 0;
+ pH->htsize = 0;
+ while( elem ){
+ HashElem *next_elem = elem->next;
+ sqlite3_free(elem);
+ elem = next_elem;
+ }
+ pH->count = 0;
+}
+
+/*
+** The hashing function.
+*/
+static unsigned int strHash(const char *z){
+ unsigned int h = 0;
+ unsigned char c;
+ while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
+ /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
+ ** 0x9e3779b1 is 2654435761 which is the closest prime number to
+ ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
+ h += sqlite3UpperToLower[c];
+ h *= 0x9e3779b1;
+ }
+ return h;
+}
+
+
+/* Link pNew element into the hash table pH. If pEntry!=0 then also
+** insert pNew into the pEntry hash bucket.
+*/
+static void insertElement(
+ Hash *pH, /* The complete hash table */
+ struct _ht *pEntry, /* The entry into which pNew is inserted */
+ HashElem *pNew /* The element to be inserted */
+){
+ HashElem *pHead; /* First element already in pEntry */
+ if( pEntry ){
+ pHead = pEntry->count ? pEntry->chain : 0;
+ pEntry->count++;
+ pEntry->chain = pNew;
+ }else{
+ pHead = 0;
+ }
+ if( pHead ){
+ pNew->next = pHead;
+ pNew->prev = pHead->prev;
+ if( pHead->prev ){ pHead->prev->next = pNew; }
+ else { pH->first = pNew; }
+ pHead->prev = pNew;
+ }else{
+ pNew->next = pH->first;
+ if( pH->first ){ pH->first->prev = pNew; }
+ pNew->prev = 0;
+ pH->first = pNew;
+ }
+}
+
+
+/* Resize the hash table so that it cantains "new_size" buckets.
+**
+** The hash table might fail to resize if sqlite3_malloc() fails or
+** if the new size is the same as the prior size.
+** Return TRUE if the resize occurs and false if not.
+*/
+static int rehash(Hash *pH, unsigned int new_size){
+ struct _ht *new_ht; /* The new hash table */
+ HashElem *elem, *next_elem; /* For looping over existing elements */
+
+#if SQLITE_MALLOC_SOFT_LIMIT>0
+ if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
+ new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
+ }
+ if( new_size==pH->htsize ) return 0;
+#endif
+
+ /* The inability to allocates space for a larger hash table is
+ ** a performance hit but it is not a fatal error. So mark the
+ ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
+ ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
+ ** only zeroes the requested number of bytes whereas this module will
+ ** use the actual amount of space allocated for the hash table (which
+ ** may be larger than the requested amount).
+ */
+ sqlite3BeginBenignMalloc();
+ new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
+ sqlite3EndBenignMalloc();
+
+ if( new_ht==0 ) return 0;
+ sqlite3_free(pH->ht);
+ pH->ht = new_ht;
+ pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
+ memset(new_ht, 0, new_size*sizeof(struct _ht));
+ for(elem=pH->first, pH->first=0; elem; elem = next_elem){
+ unsigned int h = strHash(elem->pKey) % new_size;
+ next_elem = elem->next;
+ insertElement(pH, &new_ht[h], elem);
+ }
+ return 1;
+}
+
+/* This function (for internal use only) locates an element in an
+** hash table that matches the given key. If no element is found,
+** a pointer to a static null element with HashElem.data==0 is returned.
+** If pH is not NULL, then the hash for this key is written to *pH.
+*/
+static HashElem *findElementWithHash(
+ const Hash *pH, /* The pH to be searched */
+ const char *pKey, /* The key we are searching for */
+ unsigned int *pHash /* Write the hash value here */
+){
+ HashElem *elem; /* Used to loop thru the element list */
+ unsigned int count; /* Number of elements left to test */
+ unsigned int h; /* The computed hash */
+ static HashElem nullElement = { 0, 0, 0, 0 };
+
+ if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
+ struct _ht *pEntry;
+ h = strHash(pKey) % pH->htsize;
+ pEntry = &pH->ht[h];
+ elem = pEntry->chain;
+ count = pEntry->count;
+ }else{
+ h = 0;
+ elem = pH->first;
+ count = pH->count;
+ }
+ if( pHash ) *pHash = h;
+ while( count-- ){
+ assert( elem!=0 );
+ if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
+ return elem;
+ }
+ elem = elem->next;
+ }
+ return &nullElement;
+}
+
+/* Remove a single entry from the hash table given a pointer to that
+** element and a hash on the element's key.
+*/
+static void removeElementGivenHash(
+ Hash *pH, /* The pH containing "elem" */
+ HashElem* elem, /* The element to be removed from the pH */
+ unsigned int h /* Hash value for the element */
+){
+ struct _ht *pEntry;
+ if( elem->prev ){
+ elem->prev->next = elem->next;
+ }else{
+ pH->first = elem->next;
+ }
+ if( elem->next ){
+ elem->next->prev = elem->prev;
+ }
+ if( pH->ht ){
+ pEntry = &pH->ht[h];
+ if( pEntry->chain==elem ){
+ pEntry->chain = elem->next;
+ }
+ assert( pEntry->count>0 );
+ pEntry->count--;
+ }
+ sqlite3_free( elem );
+ pH->count--;
+ if( pH->count==0 ){
+ assert( pH->first==0 );
+ assert( pH->count==0 );
+ sqlite3HashClear(pH);
+ }
+}
+
+/* Attempt to locate an element of the hash table pH with a key
+** that matches pKey. Return the data for this element if it is
+** found, or NULL if there is no match.
+*/
+SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
+ assert( pH!=0 );
+ assert( pKey!=0 );
+ return findElementWithHash(pH, pKey, 0)->data;
+}
+
+/* Insert an element into the hash table pH. The key is pKey
+** and the data is "data".
+**
+** If no element exists with a matching key, then a new
+** element is created and NULL is returned.
+**
+** If another element already exists with the same key, then the
+** new data replaces the old data and the old data is returned.
+** The key is not copied in this instance. If a malloc fails, then
+** the new data is returned and the hash table is unchanged.
+**
+** If the "data" parameter to this function is NULL, then the
+** element corresponding to "key" is removed from the hash table.
+*/
+SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
+ unsigned int h; /* the hash of the key modulo hash table size */
+ HashElem *elem; /* Used to loop thru the element list */
+ HashElem *new_elem; /* New element added to the pH */
+
+ assert( pH!=0 );
+ assert( pKey!=0 );
+ elem = findElementWithHash(pH,pKey,&h);
+ if( elem->data ){
+ void *old_data = elem->data;
+ if( data==0 ){
+ removeElementGivenHash(pH,elem,h);
+ }else{
+ elem->data = data;
+ elem->pKey = pKey;
+ }
+ return old_data;
+ }
+ if( data==0 ) return 0;
+ new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
+ if( new_elem==0 ) return data;
+ new_elem->pKey = pKey;
+ new_elem->data = data;
+ pH->count++;
+ if( pH->count>=10 && pH->count > 2*pH->htsize ){
+ if( rehash(pH, pH->count*2) ){
+ assert( pH->htsize>0 );
+ h = strHash(pKey) % pH->htsize;
+ }
+ }
+ insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
+ return 0;
+}
+
+/************** End of hash.c ************************************************/
+/************** Begin file opcodes.c *****************************************/
+/* Automatically generated. Do not edit */
+/* See the tool/mkopcodec.tcl script for details. */
+#if !defined(SQLITE_OMIT_EXPLAIN) \
+ || defined(VDBE_PROFILE) \
+ || defined(SQLITE_DEBUG)
+#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
+# define OpHelp(X) "\0" X
+#else
+# define OpHelp(X)
+#endif
+SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
+ static const char *const azName[] = {
+ /* 0 */ "Savepoint" OpHelp(""),
+ /* 1 */ "AutoCommit" OpHelp(""),
+ /* 2 */ "Transaction" OpHelp(""),
+ /* 3 */ "SorterNext" OpHelp(""),
+ /* 4 */ "Prev" OpHelp(""),
+ /* 5 */ "Next" OpHelp(""),
+ /* 6 */ "Checkpoint" OpHelp(""),
+ /* 7 */ "JournalMode" OpHelp(""),
+ /* 8 */ "Vacuum" OpHelp(""),
+ /* 9 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
+ /* 10 */ "VUpdate" OpHelp("data=r[P3@P2]"),
+ /* 11 */ "Goto" OpHelp(""),
+ /* 12 */ "Gosub" OpHelp(""),
+ /* 13 */ "InitCoroutine" OpHelp(""),
+ /* 14 */ "Yield" OpHelp(""),
+ /* 15 */ "MustBeInt" OpHelp(""),
+ /* 16 */ "Jump" OpHelp(""),
+ /* 17 */ "Once" OpHelp(""),
+ /* 18 */ "If" OpHelp(""),
+ /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
+ /* 20 */ "IfNot" OpHelp(""),
+ /* 21 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
+ /* 22 */ "SeekLT" OpHelp("key=r[P3@P4]"),
+ /* 23 */ "SeekLE" OpHelp("key=r[P3@P4]"),
+ /* 24 */ "SeekGE" OpHelp("key=r[P3@P4]"),
+ /* 25 */ "SeekGT" OpHelp("key=r[P3@P4]"),
+ /* 26 */ "IfNotOpen" OpHelp("if( !csr[P1] ) goto P2"),
+ /* 27 */ "IfNoHope" OpHelp("key=r[P3@P4]"),
+ /* 28 */ "NoConflict" OpHelp("key=r[P3@P4]"),
+ /* 29 */ "NotFound" OpHelp("key=r[P3@P4]"),
+ /* 30 */ "Found" OpHelp("key=r[P3@P4]"),
+ /* 31 */ "SeekRowid" OpHelp("intkey=r[P3]"),
+ /* 32 */ "NotExists" OpHelp("intkey=r[P3]"),
+ /* 33 */ "Last" OpHelp(""),
+ /* 34 */ "IfSmaller" OpHelp(""),
+ /* 35 */ "SorterSort" OpHelp(""),
+ /* 36 */ "Sort" OpHelp(""),
+ /* 37 */ "Rewind" OpHelp(""),
+ /* 38 */ "IdxLE" OpHelp("key=r[P3@P4]"),
+ /* 39 */ "IdxGT" OpHelp("key=r[P3@P4]"),
+ /* 40 */ "IdxLT" OpHelp("key=r[P3@P4]"),
+ /* 41 */ "IdxGE" OpHelp("key=r[P3@P4]"),
+ /* 42 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
+ /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
+ /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
+ /* 45 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
+ /* 46 */ "Program" OpHelp(""),
+ /* 47 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
+ /* 48 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
+ /* 49 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
+ /* 50 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
+ /* 51 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
+ /* 52 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
+ /* 53 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
+ /* 54 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
+ /* 55 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
+ /* 56 */ "Lt" OpHelp("IF r[P3]<r[P1]"),
+ /* 57 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),
+ /* 58 */ "ElseNotEq" OpHelp(""),
+ /* 59 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
+ /* 60 */ "IncrVacuum" OpHelp(""),
+ /* 61 */ "VNext" OpHelp(""),
+ /* 62 */ "Init" OpHelp("Start at P2"),
+ /* 63 */ "PureFunc" OpHelp("r[P3]=func(r[P2@NP])"),
+ /* 64 */ "Function" OpHelp("r[P3]=func(r[P2@NP])"),
+ /* 65 */ "Return" OpHelp(""),
+ /* 66 */ "EndCoroutine" OpHelp(""),
+ /* 67 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
+ /* 68 */ "Halt" OpHelp(""),
+ /* 69 */ "Integer" OpHelp("r[P2]=P1"),
+ /* 70 */ "Int64" OpHelp("r[P2]=P4"),
+ /* 71 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
+ /* 72 */ "Null" OpHelp("r[P2..P3]=NULL"),
+ /* 73 */ "SoftNull" OpHelp("r[P1]=NULL"),
+ /* 74 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
+ /* 75 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
+ /* 76 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
+ /* 77 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
+ /* 78 */ "SCopy" OpHelp("r[P2]=r[P1]"),
+ /* 79 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
+ /* 80 */ "ResultRow" OpHelp("output=r[P1@P2]"),
+ /* 81 */ "CollSeq" OpHelp(""),
+ /* 82 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
+ /* 83 */ "RealAffinity" OpHelp(""),
+ /* 84 */ "Cast" OpHelp("affinity(r[P1])"),
+ /* 85 */ "Permutation" OpHelp(""),
+ /* 86 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
+ /* 87 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
+ /* 88 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"),
+ /* 89 */ "Column" OpHelp("r[P3]=PX"),
+ /* 90 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
+ /* 91 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
+ /* 92 */ "Count" OpHelp("r[P2]=count()"),
+ /* 93 */ "ReadCookie" OpHelp(""),
+ /* 94 */ "SetCookie" OpHelp(""),
+ /* 95 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
+ /* 96 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
+ /* 97 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
+ /* 98 */ "OpenDup" OpHelp(""),
+ /* 99 */ "OpenAutoindex" OpHelp("nColumn=P2"),
+ /* 100 */ "OpenEphemeral" OpHelp("nColumn=P2"),
+ /* 101 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
+ /* 102 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
+ /* 103 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
+ /* 104 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
+ /* 105 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
+ /* 106 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
+ /* 107 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
+ /* 108 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
+ /* 109 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
+ /* 110 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
+ /* 111 */ "SorterOpen" OpHelp(""),
+ /* 112 */ "BitNot" OpHelp("r[P2]= ~r[P1]"),
+ /* 113 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
+ /* 114 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
+ /* 115 */ "String8" OpHelp("r[P2]='P4'"),
+ /* 116 */ "Close" OpHelp(""),
+ /* 117 */ "ColumnsUsed" OpHelp(""),
+ /* 118 */ "SeekScan" OpHelp("Scan-ahead up to P1 rows"),
+ /* 119 */ "SeekHit" OpHelp("set P2<=seekHit<=P3"),
+ /* 120 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
+ /* 121 */ "NewRowid" OpHelp("r[P2]=rowid"),
+ /* 122 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
+ /* 123 */ "Delete" OpHelp(""),
+ /* 124 */ "ResetCount" OpHelp(""),
+ /* 125 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
+ /* 126 */ "SorterData" OpHelp("r[P2]=data"),
+ /* 127 */ "RowData" OpHelp("r[P2]=data"),
+ /* 128 */ "Rowid" OpHelp("r[P2]=rowid"),
+ /* 129 */ "NullRow" OpHelp(""),
+ /* 130 */ "SeekEnd" OpHelp(""),
+ /* 131 */ "IdxInsert" OpHelp("key=r[P2]"),
+ /* 132 */ "SorterInsert" OpHelp("key=r[P2]"),
+ /* 133 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
+ /* 134 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
+ /* 135 */ "IdxRowid" OpHelp("r[P2]=rowid"),
+ /* 136 */ "FinishSeek" OpHelp(""),
+ /* 137 */ "Destroy" OpHelp(""),
+ /* 138 */ "Clear" OpHelp(""),
+ /* 139 */ "ResetSorter" OpHelp(""),
+ /* 140 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
+ /* 141 */ "SqlExec" OpHelp(""),
+ /* 142 */ "ParseSchema" OpHelp(""),
+ /* 143 */ "LoadAnalysis" OpHelp(""),
+ /* 144 */ "DropTable" OpHelp(""),
+ /* 145 */ "DropIndex" OpHelp(""),
+ /* 146 */ "DropTrigger" OpHelp(""),
+ /* 147 */ "IntegrityCk" OpHelp(""),
+ /* 148 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
+ /* 149 */ "Param" OpHelp(""),
+ /* 150 */ "Real" OpHelp("r[P2]=P4"),
+ /* 151 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
+ /* 152 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
+ /* 153 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
+ /* 154 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"),
+ /* 155 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
+ /* 156 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"),
+ /* 157 */ "AggValue" OpHelp("r[P3]=value N=P2"),
+ /* 158 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
+ /* 159 */ "Expire" OpHelp(""),
+ /* 160 */ "CursorLock" OpHelp(""),
+ /* 161 */ "CursorUnlock" OpHelp(""),
+ /* 162 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
+ /* 163 */ "VBegin" OpHelp(""),
+ /* 164 */ "VCreate" OpHelp(""),
+ /* 165 */ "VDestroy" OpHelp(""),
+ /* 166 */ "VOpen" OpHelp(""),
+ /* 167 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
+ /* 168 */ "VRename" OpHelp(""),
+ /* 169 */ "Pagecount" OpHelp(""),
+ /* 170 */ "MaxPgcnt" OpHelp(""),
+ /* 171 */ "Trace" OpHelp(""),
+ /* 172 */ "CursorHint" OpHelp(""),
+ /* 173 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"),
+ /* 174 */ "Noop" OpHelp(""),
+ /* 175 */ "Explain" OpHelp(""),
+ /* 176 */ "Abortable" OpHelp(""),
+ };
+ return azName[i];
+}
+#endif
+
+/************** End of opcodes.c *********************************************/
+/************** Begin file os_unix.c *****************************************/
+/*
+** 2004 May 22
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains the VFS implementation for unix-like operating systems
+** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
+**
+** There are actually several different VFS implementations in this file.
+** The differences are in the way that file locking is done. The default
+** implementation uses Posix Advisory Locks. Alternative implementations
+** use flock(), dot-files, various proprietary locking schemas, or simply
+** skip locking all together.
+**
+** This source file is organized into divisions where the logic for various
+** subfunctions is contained within the appropriate division. PLEASE
+** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
+** in the correct division and should be clearly labeled.
+**
+** The layout of divisions is as follows:
+**
+** * General-purpose declarations and utility functions.
+** * Unique file ID logic used by VxWorks.
+** * Various locking primitive implementations (all except proxy locking):
+** + for Posix Advisory Locks
+** + for no-op locks
+** + for dot-file locks
+** + for flock() locking
+** + for named semaphore locks (VxWorks only)
+** + for AFP filesystem locks (MacOSX only)
+** * sqlite3_file methods not associated with locking.
+** * Definitions of sqlite3_io_methods objects for all locking
+** methods plus "finder" functions for each locking method.
+** * sqlite3_vfs method implementations.
+** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
+** * Definitions of sqlite3_vfs objects for all locking methods
+** plus implementations of sqlite3_os_init() and sqlite3_os_end().
+*/
+/* #include "sqliteInt.h" */
+#if SQLITE_OS_UNIX /* This file is used on unix only */
+
+/*
+** There are various methods for file locking used for concurrency
+** control:
+**
+** 1. POSIX locking (the default),
+** 2. No locking,
+** 3. Dot-file locking,
+** 4. flock() locking,
+** 5. AFP locking (OSX only),
+** 6. Named POSIX semaphores (VXWorks only),
+** 7. proxy locking. (OSX only)
+**
+** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
+** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
+** selection of the appropriate locking style based on the filesystem
+** where the database is located.
+*/
+#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
+# if defined(__APPLE__)
+# define SQLITE_ENABLE_LOCKING_STYLE 1
+# else
+# define SQLITE_ENABLE_LOCKING_STYLE 0
+# endif
+#endif
+
+/* Use pread() and pwrite() if they are available */
+#if defined(__APPLE__)
+# define HAVE_PREAD 1
+# define HAVE_PWRITE 1
+#endif
+#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
+# undef USE_PREAD
+# define USE_PREAD64 1
+#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
+# undef USE_PREAD64
+# define USE_PREAD 1
+#endif
+
+/*
+** standard include files.
+*/
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+/* #include <time.h> */
+#include <sys/time.h>
+#include <errno.h>
+#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
+# include <sys/mman.h>
+#endif
+
+#if SQLITE_ENABLE_LOCKING_STYLE
+/* # include <sys/ioctl.h> */
+# include <sys/file.h>
+# include <sys/param.h>
+#endif /* SQLITE_ENABLE_LOCKING_STYLE */
+
+/*
+** Try to determine if gethostuuid() is available based on standard
+** macros. This might sometimes compute the wrong value for some
+** obscure platforms. For those cases, simply compile with one of
+** the following:
+**
+** -DHAVE_GETHOSTUUID=0
+** -DHAVE_GETHOSTUUID=1
+**
+** None if this matters except when building on Apple products with
+** -DSQLITE_ENABLE_LOCKING_STYLE.
+*/
+#ifndef HAVE_GETHOSTUUID
+# define HAVE_GETHOSTUUID 0
+# if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
+ (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
+# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
+ && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))\
+ && (!defined(TARGET_OS_MACCATALYST) || (TARGET_OS_MACCATALYST==0))
+# undef HAVE_GETHOSTUUID
+# define HAVE_GETHOSTUUID 1
+# else
+# warning "gethostuuid() is disabled."
+# endif
+# endif
+#endif
+
+
+#if OS_VXWORKS
+/* # include <sys/ioctl.h> */
+# include <semaphore.h>
+# include <limits.h>
+#endif /* OS_VXWORKS */
+
+#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
+# include <sys/mount.h>
+#endif
+
+#ifdef HAVE_UTIME
+# include <utime.h>
+#endif
+
+/*
+** Allowed values of unixFile.fsFlags
+*/
+#define SQLITE_FSFLAGS_IS_MSDOS 0x1
+
+/*
+** If we are to be thread-safe, include the pthreads header.
+*/
+#if SQLITE_THREADSAFE
+/* # include <pthread.h> */
+#endif
+
+/*
+** Default permissions when creating a new file
+*/
+#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
+# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
+#endif
+
+/*
+** Default permissions when creating auto proxy dir
+*/
+#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
+# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
+#endif
+
+/*
+** Maximum supported path-length.
+*/
+#define MAX_PATHNAME 512
+
+/*
+** Maximum supported symbolic links
+*/
+#define SQLITE_MAX_SYMLINKS 100
+
+/* Always cast the getpid() return type for compatibility with
+** kernel modules in VxWorks. */
+#define osGetpid(X) (pid_t)getpid()
+
+/*
+** Only set the lastErrno if the error code is a real error and not
+** a normal expected return code of SQLITE_BUSY or SQLITE_OK
+*/
+#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
+
+/* Forward references */
+typedef struct unixShm unixShm; /* Connection shared memory */
+typedef struct unixShmNode unixShmNode; /* Shared memory instance */
+typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
+typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
+
+/*
+** Sometimes, after a file handle is closed by SQLite, the file descriptor
+** cannot be closed immediately. In these cases, instances of the following
+** structure are used to store the file descriptor while waiting for an
+** opportunity to either close or reuse it.
+*/
+struct UnixUnusedFd {
+ int fd; /* File descriptor to close */
+ int flags; /* Flags this file descriptor was opened with */
+ UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
+};
+
+/*
+** The unixFile structure is subclass of sqlite3_file specific to the unix
+** VFS implementations.
+*/
+typedef struct unixFile unixFile;
+struct unixFile {
+ sqlite3_io_methods const *pMethod; /* Always the first entry */
+ sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
+ unixInodeInfo *pInode; /* Info about locks on this inode */
+ int h; /* The file descriptor */
+ unsigned char eFileLock; /* The type of lock held on this fd */
+ unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
+ int lastErrno; /* The unix errno from last I/O error */
+ void *lockingContext; /* Locking style specific state */
+ UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
+ const char *zPath; /* Name of the file */
+ unixShm *pShm; /* Shared memory segment information */
+ int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
+#if SQLITE_MAX_MMAP_SIZE>0
+ int nFetchOut; /* Number of outstanding xFetch refs */
+ sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
+ sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
+ sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
+ void *pMapRegion; /* Memory mapped region */
+#endif
+ int sectorSize; /* Device sector size */
+ int deviceCharacteristics; /* Precomputed device characteristics */
+#if SQLITE_ENABLE_LOCKING_STYLE
+ int openFlags; /* The flags specified at open() */
+#endif
+#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
+ unsigned fsFlags; /* cached details from statfs() */
+#endif
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+ unsigned iBusyTimeout; /* Wait this many millisec on locks */
+#endif
+#if OS_VXWORKS
+ struct vxworksFileId *pId; /* Unique file ID */
+#endif
+#ifdef SQLITE_DEBUG
+ /* The next group of variables are used to track whether or not the
+ ** transaction counter in bytes 24-27 of database files are updated
+ ** whenever any part of the database changes. An assertion fault will
+ ** occur if a file is updated without also updating the transaction
+ ** counter. This test is made to avoid new problems similar to the
+ ** one described by ticket #3584.
+ */
+ unsigned char transCntrChng; /* True if the transaction counter changed */
+ unsigned char dbUpdate; /* True if any part of database file changed */
+ unsigned char inNormalWrite; /* True if in a normal write operation */
+
+#endif
+
+#ifdef SQLITE_TEST
+ /* In test mode, increase the size of this structure a bit so that
+ ** it is larger than the struct CrashFile defined in test6.c.
+ */
+ char aPadding[32];
+#endif
+};
+
+/* This variable holds the process id (pid) from when the xRandomness()
+** method was called. If xOpen() is called from a different process id,
+** indicating that a fork() has occurred, the PRNG will be reset.
+*/
+static pid_t randomnessPid = 0;
+
+/*
+** Allowed values for the unixFile.ctrlFlags bitmask:
+*/
+#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
+#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
+#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
+#ifndef SQLITE_DISABLE_DIRSYNC
+# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
+#else
+# define UNIXFILE_DIRSYNC 0x00
+#endif
+#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
+#define UNIXFILE_DELETE 0x20 /* Delete on close */
+#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
+#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
+
+/*
+** Include code that is common to all os_*.c files
+*/
+/************** Include os_common.h in the middle of os_unix.c ***************/
+/************** Begin file os_common.h ***************************************/
+/*
+** 2004 May 22
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains macros and a little bit of code that is common to
+** all of the platform-specific files (os_*.c) and is #included into those
+** files.
+**
+** This file should be #included by the os_*.c files only. It is not a
+** general purpose header file.
+*/
+#ifndef _OS_COMMON_H_
+#define _OS_COMMON_H_
+
+/*
+** At least two bugs have slipped in because we changed the MEMORY_DEBUG
+** macro to SQLITE_DEBUG and some older makefiles have not yet made the
+** switch. The following code should catch this problem at compile-time.
+*/
+#ifdef MEMORY_DEBUG
+# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
+#endif
+
+/*
+** Macros for performance tracing. Normally turned off. Only works
+** on i486 hardware.
+*/
+#ifdef SQLITE_PERFORMANCE_TRACE
+
+/*
+** hwtime.h contains inline assembler code for implementing
+** high-performance timing routines.
+*/
+/************** Include hwtime.h in the middle of os_common.h ****************/
+/************** Begin file hwtime.h ******************************************/
+/*
+** 2008 May 27
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains inline asm code for retrieving "high-performance"
+** counters for x86 and x86_64 class CPUs.
+*/
+#ifndef SQLITE_HWTIME_H
+#define SQLITE_HWTIME_H
+
+/*
+** The following routine only works on pentium-class (or newer) processors.
+** It uses the RDTSC opcode to read the cycle count value out of the
+** processor and returns that value. This can be used for high-res
+** profiling.
+*/
+#if !defined(__STRICT_ANSI__) && \
+ (defined(__GNUC__) || defined(_MSC_VER)) && \
+ (defined(i386) || defined(__i386__) || defined(_M_IX86))
+
+ #if defined(__GNUC__)
+
+ __inline__ sqlite_uint64 sqlite3Hwtime(void){
+ unsigned int lo, hi;
+ __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
+ return (sqlite_uint64)hi << 32 | lo;
+ }
+
+ #elif defined(_MSC_VER)
+
+ __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
+ __asm {
+ rdtsc
+ ret ; return value at EDX:EAX
+ }
+ }
+
+ #endif
+
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
+
+ __inline__ sqlite_uint64 sqlite3Hwtime(void){
+ unsigned long val;
+ __asm__ __volatile__ ("rdtsc" : "=A" (val));
+ return val;
+ }
+
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
+
+ __inline__ sqlite_uint64 sqlite3Hwtime(void){
+ unsigned long long retval;
+ unsigned long junk;
+ __asm__ __volatile__ ("\n\
+ 1: mftbu %1\n\
+ mftb %L0\n\
+ mftbu %0\n\
+ cmpw %0,%1\n\
+ bne 1b"
+ : "=r" (retval), "=r" (junk));
+ return retval;
+ }
+
+#else
+
+ /*
+ ** asm() is needed for hardware timing support. Without asm(),
+ ** disable the sqlite3Hwtime() routine.
+ **
+ ** sqlite3Hwtime() is only used for some obscure debugging
+ ** and analysis configurations, not in any deliverable, so this
+ ** should not be a great loss.
+ */
+SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
+
+#endif
+
+#endif /* !defined(SQLITE_HWTIME_H) */
+
+/************** End of hwtime.h **********************************************/
+/************** Continuing where we left off in os_common.h ******************/
+
+static sqlite_uint64 g_start;
+static sqlite_uint64 g_elapsed;
+#define TIMER_START g_start=sqlite3Hwtime()
+#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
+#define TIMER_ELAPSED g_elapsed
+#else
+#define TIMER_START
+#define TIMER_END
+#define TIMER_ELAPSED ((sqlite_uint64)0)
+#endif
+
+/*
+** If we compile with the SQLITE_TEST macro set, then the following block
+** of code will give us the ability to simulate a disk I/O error. This
+** is used for testing the I/O recovery logic.
+*/
+#if defined(SQLITE_TEST)
+SQLITE_API extern int sqlite3_io_error_hit;
+SQLITE_API extern int sqlite3_io_error_hardhit;
+SQLITE_API extern int sqlite3_io_error_pending;
+SQLITE_API extern int sqlite3_io_error_persist;
+SQLITE_API extern int sqlite3_io_error_benign;
+SQLITE_API extern int sqlite3_diskfull_pending;
+SQLITE_API extern int sqlite3_diskfull;
+#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
+#define SimulateIOError(CODE) \
+ if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
+ || sqlite3_io_error_pending-- == 1 ) \
+ { local_ioerr(); CODE; }
+static void local_ioerr(){
+ IOTRACE(("IOERR\n"));
+ sqlite3_io_error_hit++;
+ if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
+}
+#define SimulateDiskfullError(CODE) \
+ if( sqlite3_diskfull_pending ){ \
+ if( sqlite3_diskfull_pending == 1 ){ \
+ local_ioerr(); \
+ sqlite3_diskfull = 1; \
+ sqlite3_io_error_hit = 1; \
+ CODE; \
+ }else{ \
+ sqlite3_diskfull_pending--; \
+ } \
+ }
+#else
+#define SimulateIOErrorBenign(X)
+#define SimulateIOError(A)
+#define SimulateDiskfullError(A)
+#endif /* defined(SQLITE_TEST) */
+
+/*
+** When testing, keep a count of the number of open files.
+*/
+#if defined(SQLITE_TEST)
+SQLITE_API extern int sqlite3_open_file_count;
+#define OpenCounter(X) sqlite3_open_file_count+=(X)
+#else
+#define OpenCounter(X)
+#endif /* defined(SQLITE_TEST) */
+
+#endif /* !defined(_OS_COMMON_H_) */
+
+/************** End of os_common.h *******************************************/
+/************** Continuing where we left off in os_unix.c ********************/
+
+/*
+** Define various macros that are missing from some systems.
+*/
+#ifndef O_LARGEFILE
+# define O_LARGEFILE 0
+#endif
+#ifdef SQLITE_DISABLE_LFS
+# undef O_LARGEFILE
+# define O_LARGEFILE 0
+#endif
+#ifndef O_NOFOLLOW
+# define O_NOFOLLOW 0
+#endif
+#ifndef O_BINARY
+# define O_BINARY 0
+#endif
+
+/*
+** The threadid macro resolves to the thread-id or to 0. Used for
+** testing and debugging only.
+*/
+#if SQLITE_THREADSAFE
+#define threadid pthread_self()
+#else
+#define threadid 0
+#endif
+
+/*
+** HAVE_MREMAP defaults to true on Linux and false everywhere else.
+*/
+#if !defined(HAVE_MREMAP)
+# if defined(__linux__) && defined(_GNU_SOURCE)
+# define HAVE_MREMAP 1
+# else
+# define HAVE_MREMAP 0
+# endif
+#endif
+
+/*
+** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
+** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
+*/
+#ifdef __ANDROID__
+# define lseek lseek64
+#endif
+
+#ifdef __linux__
+/*
+** Linux-specific IOCTL magic numbers used for controlling F2FS
+*/
+#define F2FS_IOCTL_MAGIC 0xf5
+#define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
+#define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
+#define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
+#define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
+#define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
+#define F2FS_FEATURE_ATOMIC_WRITE 0x0004
+#endif /* __linux__ */
+
+
+/*
+** Different Unix systems declare open() in different ways. Same use
+** open(const char*,int,mode_t). Others use open(const char*,int,...).
+** The difference is important when using a pointer to the function.
+**
+** The safest way to deal with the problem is to always use this wrapper
+** which always has the same well-defined interface.
+*/
+static int posixOpen(const char *zFile, int flags, int mode){
+ return open(zFile, flags, mode);
+}
+
+/* Forward reference */
+static int openDirectory(const char*, int*);
+static int unixGetpagesize(void);
+
+/*
+** Many system calls are accessed through pointer-to-functions so that
+** they may be overridden at runtime to facilitate fault injection during
+** testing and sandboxing. The following array holds the names and pointers
+** to all overrideable system calls.
+*/
+static struct unix_syscall {
+ const char *zName; /* Name of the system call */
+ sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
+ sqlite3_syscall_ptr pDefault; /* Default value */
+} aSyscall[] = {
+ { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
+#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
+
+ { "close", (sqlite3_syscall_ptr)close, 0 },
+#define osClose ((int(*)(int))aSyscall[1].pCurrent)
+
+ { "access", (sqlite3_syscall_ptr)access, 0 },
+#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
+
+ { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
+#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
+
+ { "stat", (sqlite3_syscall_ptr)stat, 0 },
+#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
+
+/*
+** The DJGPP compiler environment looks mostly like Unix, but it
+** lacks the fcntl() system call. So redefine fcntl() to be something
+** that always succeeds. This means that locking does not occur under
+** DJGPP. But it is DOS - what did you expect?
+*/
+#ifdef __DJGPP__
+ { "fstat", 0, 0 },
+#define osFstat(a,b,c) 0
+#else
+ { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
+#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
+#endif
+
+ { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
+#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
+
+ { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
+#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
+
+ { "read", (sqlite3_syscall_ptr)read, 0 },
+#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
+
+#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
+ { "pread", (sqlite3_syscall_ptr)pread, 0 },
+#else
+ { "pread", (sqlite3_syscall_ptr)0, 0 },
+#endif
+#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
+
+#if defined(USE_PREAD64)
+ { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
+#else
+ { "pread64", (sqlite3_syscall_ptr)0, 0 },
+#endif
+#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
+
+ { "write", (sqlite3_syscall_ptr)write, 0 },
+#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
+
+#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
+ { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
+#else
+ { "pwrite", (sqlite3_syscall_ptr)0, 0 },
+#endif
+#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
+ aSyscall[12].pCurrent)
+
+#if defined(USE_PREAD64)
+ { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
+#else
+ { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
+#endif
+#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
+ aSyscall[13].pCurrent)
+
+ { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
+#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
+
+#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
+ { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
+#else
+ { "fallocate", (sqlite3_syscall_ptr)0, 0 },
+#endif
+#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
+
+ { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
+#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
+
+ { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
+#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
+
+ { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
+#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
+
+ { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
+#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
+
+#if defined(HAVE_FCHOWN)
+ { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
+#else
+ { "fchown", (sqlite3_syscall_ptr)0, 0 },
+#endif
+#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
+
+#if defined(HAVE_FCHOWN)
+ { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
+#else
+ { "geteuid", (sqlite3_syscall_ptr)0, 0 },
+#endif
+#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
+
+#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
+ { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
+#else
+ { "mmap", (sqlite3_syscall_ptr)0, 0 },
+#endif
+#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
+
+#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
+ { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
+#else
+ { "munmap", (sqlite3_syscall_ptr)0, 0 },
+#endif
+#define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
+
+#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
+ { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
+#else
+ { "mremap", (sqlite3_syscall_ptr)0, 0 },
+#endif
+#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
+
+#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
+ { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
+#else
+ { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
+#endif
+#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
+
+#if defined(HAVE_READLINK)
+ { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
+#else
+ { "readlink", (sqlite3_syscall_ptr)0, 0 },
+#endif
+#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
+
+#if defined(HAVE_LSTAT)
+ { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
+#else
+ { "lstat", (sqlite3_syscall_ptr)0, 0 },
+#endif
+#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
+
+#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
+# ifdef __ANDROID__
+ { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
+#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
+# else
+ { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
+#define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent)
+# endif
+#else
+ { "ioctl", (sqlite3_syscall_ptr)0, 0 },
+#endif
+
+}; /* End of the overrideable system calls */
+
+
+/*
+** On some systems, calls to fchown() will trigger a message in a security
+** log if they come from non-root processes. So avoid calling fchown() if
+** we are not running as root.
+*/
+static int robustFchown(int fd, uid_t uid, gid_t gid){
+#if defined(HAVE_FCHOWN)
+ return osGeteuid() ? 0 : osFchown(fd,uid,gid);
+#else
+ return 0;
+#endif
+}
+
+/*
+** This is the xSetSystemCall() method of sqlite3_vfs for all of the
+** "unix" VFSes. Return SQLITE_OK opon successfully updating the
+** system call pointer, or SQLITE_NOTFOUND if there is no configurable
+** system call named zName.
+*/
+static int unixSetSystemCall(
+ sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
+ const char *zName, /* Name of system call to override */
+ sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
+){
+ unsigned int i;
+ int rc = SQLITE_NOTFOUND;
+
+ UNUSED_PARAMETER(pNotUsed);
+ if( zName==0 ){
+ /* If no zName is given, restore all system calls to their default
+ ** settings and return NULL
+ */
+ rc = SQLITE_OK;
+ for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
+ if( aSyscall[i].pDefault ){
+ aSyscall[i].pCurrent = aSyscall[i].pDefault;
+ }
+ }
+ }else{
+ /* If zName is specified, operate on only the one system call
+ ** specified.
+ */
+ for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
+ if( strcmp(zName, aSyscall[i].zName)==0 ){
+ if( aSyscall[i].pDefault==0 ){
+ aSyscall[i].pDefault = aSyscall[i].pCurrent;
+ }
+ rc = SQLITE_OK;
+ if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
+ aSyscall[i].pCurrent = pNewFunc;
+ break;
+ }
+ }
+ }
+ return rc;
+}
+
+/*
+** Return the value of a system call. Return NULL if zName is not a
+** recognized system call name. NULL is also returned if the system call
+** is currently undefined.
+*/
+static sqlite3_syscall_ptr unixGetSystemCall(
+ sqlite3_vfs *pNotUsed,
+ const char *zName
+){
+ unsigned int i;
+
+ UNUSED_PARAMETER(pNotUsed);
+ for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
+ if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
+ }
+ return 0;
+}
+
+/*
+** Return the name of the first system call after zName. If zName==NULL
+** then return the name of the first system call. Return NULL if zName
+** is the last system call or if zName is not the name of a valid
+** system call.
+*/
+static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
+ int i = -1;
+
+ UNUSED_PARAMETER(p);
+ if( zName ){
+ for(i=0; i<ArraySize(aSyscall)-1; i++){
+ if( strcmp(zName, aSyscall[i].zName)==0 ) break;
+ }
+ }
+ for(i++; i<ArraySize(aSyscall); i++){
+ if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
+ }
+ return 0;
+}
+
+/*
+** Do not accept any file descriptor less than this value, in order to avoid
+** opening database file using file descriptors that are commonly used for
+** standard input, output, and error.
+*/
+#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
+# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
+#endif
+
+/*
+** Invoke open(). Do so multiple times, until it either succeeds or
+** fails for some reason other than EINTR.
+**
+** If the file creation mode "m" is 0 then set it to the default for
+** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
+** 0644) as modified by the system umask. If m is not 0, then
+** make the file creation mode be exactly m ignoring the umask.
+**
+** The m parameter will be non-zero only when creating -wal, -journal,
+** and -shm files. We want those files to have *exactly* the same
+** permissions as their original database, unadulterated by the umask.
+** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
+** transaction crashes and leaves behind hot journals, then any
+** process that is able to write to the database will also be able to
+** recover the hot journals.
+*/
+static int robust_open(const char *z, int f, mode_t m){
+ int fd;
+ mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
+ while(1){
+#if defined(O_CLOEXEC)
+ fd = osOpen(z,f|O_CLOEXEC,m2);
+#else
+ fd = osOpen(z,f,m2);
+#endif
+ if( fd<0 ){
+ if( errno==EINTR ) continue;
+ break;
+ }
+ if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
+ osClose(fd);
+ sqlite3_log(SQLITE_WARNING,
+ "attempt to open \"%s\" as file descriptor %d", z, fd);
+ fd = -1;
+ if( osOpen("/dev/null", O_RDONLY, m)<0 ) break;
+ }
+ if( fd>=0 ){
+ if( m!=0 ){
+ struct stat statbuf;
+ if( osFstat(fd, &statbuf)==0
+ && statbuf.st_size==0
+ && (statbuf.st_mode&0777)!=m
+ ){
+ osFchmod(fd, m);
+ }
+ }
+#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
+ osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
+#endif
+ }
+ return fd;
+}
+
+/*
+** Helper functions to obtain and relinquish the global mutex. The
+** global mutex is used to protect the unixInodeInfo and
+** vxworksFileId objects used by this file, all of which may be
+** shared by multiple threads.
+**
+** Function unixMutexHeld() is used to assert() that the global mutex
+** is held when required. This function is only used as part of assert()
+** statements. e.g.
+**
+** unixEnterMutex()
+** assert( unixMutexHeld() );
+** unixEnterLeave()
+**
+** To prevent deadlock, the global unixBigLock must must be acquired
+** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
+** OK to get the pLockMutex without holding unixBigLock first, but if
+** that happens, the unixBigLock mutex must not be acquired until after
+** pLockMutex is released.
+**
+** OK: enter(unixBigLock), enter(pLockInfo)
+** OK: enter(unixBigLock)
+** OK: enter(pLockInfo)
+** ERROR: enter(pLockInfo), enter(unixBigLock)
+*/
+static sqlite3_mutex *unixBigLock = 0;
+static void unixEnterMutex(void){
+ assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
+ sqlite3_mutex_enter(unixBigLock);
+}
+static void unixLeaveMutex(void){
+ assert( sqlite3_mutex_held(unixBigLock) );
+ sqlite3_mutex_leave(unixBigLock);
+}
+#ifdef SQLITE_DEBUG
+static int unixMutexHeld(void) {
+ return sqlite3_mutex_held(unixBigLock);
+}
+#endif
+
+
+#ifdef SQLITE_HAVE_OS_TRACE
+/*
+** Helper function for printing out trace information from debugging
+** binaries. This returns the string representation of the supplied
+** integer lock-type.
+*/
+static const char *azFileLock(int eFileLock){
+ switch( eFileLock ){
+ case NO_LOCK: return "NONE";
+ case SHARED_LOCK: return "SHARED";
+ case RESERVED_LOCK: return "RESERVED";
+ case PENDING_LOCK: return "PENDING";
+ case EXCLUSIVE_LOCK: return "EXCLUSIVE";
+ }
+ return "ERROR";
+}
+#endif
+
+#ifdef SQLITE_LOCK_TRACE
+/*
+** Print out information about all locking operations.
+**
+** This routine is used for troubleshooting locks on multithreaded
+** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
+** command-line option on the compiler. This code is normally
+** turned off.
+*/
+static int lockTrace(int fd, int op, struct flock *p){
+ char *zOpName, *zType;
+ int s;
+ int savedErrno;
+ if( op==F_GETLK ){
+ zOpName = "GETLK";
+ }else if( op==F_SETLK ){
+ zOpName = "SETLK";
+ }else{
+ s = osFcntl(fd, op, p);
+ sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
+ return s;
+ }
+ if( p->l_type==F_RDLCK ){
+ zType = "RDLCK";
+ }else if( p->l_type==F_WRLCK ){
+ zType = "WRLCK";
+ }else if( p->l_type==F_UNLCK ){
+ zType = "UNLCK";
+ }else{
+ assert( 0 );
+ }
+ assert( p->l_whence==SEEK_SET );
+ s = osFcntl(fd, op, p);
+ savedErrno = errno;
+ sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
+ threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
+ (int)p->l_pid, s);
+ if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
+ struct flock l2;
+ l2 = *p;
+ osFcntl(fd, F_GETLK, &l2);
+ if( l2.l_type==F_RDLCK ){
+ zType = "RDLCK";
+ }else if( l2.l_type==F_WRLCK ){
+ zType = "WRLCK";
+ }else if( l2.l_type==F_UNLCK ){
+ zType = "UNLCK";
+ }else{
+ assert( 0 );
+ }
+ sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
+ zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
+ }
+ errno = savedErrno;
+ return s;
+}
+#undef osFcntl
+#define osFcntl lockTrace
+#endif /* SQLITE_LOCK_TRACE */
+
+/*
+** Retry ftruncate() calls that fail due to EINTR
+**
+** All calls to ftruncate() within this file should be made through
+** this wrapper. On the Android platform, bypassing the logic below
+** could lead to a corrupt database.
+*/
+static int robust_ftruncate(int h, sqlite3_int64 sz){
+ int rc;
+#ifdef __ANDROID__
+ /* On Android, ftruncate() always uses 32-bit offsets, even if
+ ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
+ ** truncate a file to any size larger than 2GiB. Silently ignore any
+ ** such attempts. */
+ if( sz>(sqlite3_int64)0x7FFFFFFF ){
+ rc = SQLITE_OK;
+ }else
+#endif
+ do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
+ return rc;
+}
+
+/*
+** This routine translates a standard POSIX errno code into something
+** useful to the clients of the sqlite3 functions. Specifically, it is
+** intended to translate a variety of "try again" errors into SQLITE_BUSY
+** and a variety of "please close the file descriptor NOW" errors into
+** SQLITE_IOERR
+**
+** Errors during initialization of locks, or file system support for locks,
+** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
+*/
+static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
+ assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
+ (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
+ (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
+ (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
+ switch (posixError) {
+ case EACCES:
+ case EAGAIN:
+ case ETIMEDOUT:
+ case EBUSY:
+ case EINTR:
+ case ENOLCK:
+ /* random NFS retry error, unless during file system support
+ * introspection, in which it actually means what it says */
+ return SQLITE_BUSY;
+
+ case EPERM:
+ return SQLITE_PERM;
+
+ default:
+ return sqliteIOErr;
+ }
+}
+
+
+/******************************************************************************
+****************** Begin Unique File ID Utility Used By VxWorks ***************
+**
+** On most versions of unix, we can get a unique ID for a file by concatenating
+** the device number and the inode number. But this does not work on VxWorks.
+** On VxWorks, a unique file id must be based on the canonical filename.
+**
+** A pointer to an instance of the following structure can be used as a
+** unique file ID in VxWorks. Each instance of this structure contains
+** a copy of the canonical filename. There is also a reference count.
+** The structure is reclaimed when the number of pointers to it drops to
+** zero.
+**
+** There are never very many files open at one time and lookups are not
+** a performance-critical path, so it is sufficient to put these
+** structures on a linked list.
+*/
+struct vxworksFileId {
+ struct vxworksFileId *pNext; /* Next in a list of them all */
+ int nRef; /* Number of references to this one */
+ int nName; /* Length of the zCanonicalName[] string */
+ char *zCanonicalName; /* Canonical filename */
+};
+
+#if OS_VXWORKS
+/*
+** All unique filenames are held on a linked list headed by this
+** variable:
+*/
+static struct vxworksFileId *vxworksFileList = 0;
+
+/*
+** Simplify a filename into its canonical form
+** by making the following changes:
+**
+** * removing any trailing and duplicate /
+** * convert /./ into just /
+** * convert /A/../ where A is any simple name into just /
+**
+** Changes are made in-place. Return the new name length.
+**
+** The original filename is in z[0..n-1]. Return the number of
+** characters in the simplified name.
+*/
+static int vxworksSimplifyName(char *z, int n){
+ int i, j;
+ while( n>1 && z[n-1]=='/' ){ n--; }
+ for(i=j=0; i<n; i++){
+ if( z[i]=='/' ){
+ if( z[i+1]=='/' ) continue;
+ if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
+ i += 1;
+ continue;
+ }
+ if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
+ while( j>0 && z[j-1]!='/' ){ j--; }
+ if( j>0 ){ j--; }
+ i += 2;
+ continue;
+ }
+ }
+ z[j++] = z[i];
+ }
+ z[j] = 0;
+ return j;
+}
+
+/*
+** Find a unique file ID for the given absolute pathname. Return
+** a pointer to the vxworksFileId object. This pointer is the unique
+** file ID.
+**
+** The nRef field of the vxworksFileId object is incremented before
+** the object is returned. A new vxworksFileId object is created
+** and added to the global list if necessary.
+**
+** If a memory allocation error occurs, return NULL.
+*/
+static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
+ struct vxworksFileId *pNew; /* search key and new file ID */
+ struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
+ int n; /* Length of zAbsoluteName string */
+
+ assert( zAbsoluteName[0]=='/' );
+ n = (int)strlen(zAbsoluteName);
+ pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
+ if( pNew==0 ) return 0;
+ pNew->zCanonicalName = (char*)&pNew[1];
+ memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
+ n = vxworksSimplifyName(pNew->zCanonicalName, n);
+
+ /* Search for an existing entry that matching the canonical name.
+ ** If found, increment the reference count and return a pointer to
+ ** the existing file ID.
+ */
+ unixEnterMutex();
+ for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
+ if( pCandidate->nName==n
+ && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
+ ){
+ sqlite3_free(pNew);
+ pCandidate->nRef++;
+ unixLeaveMutex();
+ return pCandidate;
+ }
+ }
+
+ /* No match was found. We will make a new file ID */
+ pNew->nRef = 1;
+ pNew->nName = n;
+ pNew->pNext = vxworksFileList;
+ vxworksFileList = pNew;
+ unixLeaveMutex();
+ return pNew;
+}
+
+/*
+** Decrement the reference count on a vxworksFileId object. Free
+** the object when the reference count reaches zero.
+*/
+static void vxworksReleaseFileId(struct vxworksFileId *pId){
+ unixEnterMutex();
+ assert( pId->nRef>0 );
+ pId->nRef--;
+ if( pId->nRef==0 ){
+ struct vxworksFileId **pp;
+ for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
+ assert( *pp==pId );
+ *pp = pId->pNext;
+ sqlite3_free(pId);
+ }
+ unixLeaveMutex();
+}
+#endif /* OS_VXWORKS */
+/*************** End of Unique File ID Utility Used By VxWorks ****************
+******************************************************************************/
+
+
+/******************************************************************************
+*************************** Posix Advisory Locking ****************************
+**
+** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
+** section 6.5.2.2 lines 483 through 490 specify that when a process
+** sets or clears a lock, that operation overrides any prior locks set
+** by the same process. It does not explicitly say so, but this implies
+** that it overrides locks set by the same process using a different
+** file descriptor. Consider this test case:
+**
+** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
+** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
+**
+** Suppose ./file1 and ./file2 are really the same file (because
+** one is a hard or symbolic link to the other) then if you set
+** an exclusive lock on fd1, then try to get an exclusive lock
+** on fd2, it works. I would have expected the second lock to
+** fail since there was already a lock on the file due to fd1.
+** But not so. Since both locks came from the same process, the
+** second overrides the first, even though they were on different
+** file descriptors opened on different file names.
+**
+** This means that we cannot use POSIX locks to synchronize file access
+** among competing threads of the same process. POSIX locks will work fine
+** to synchronize access for threads in separate processes, but not
+** threads within the same process.
+**
+** To work around the problem, SQLite has to manage file locks internally
+** on its own. Whenever a new database is opened, we have to find the
+** specific inode of the database file (the inode is determined by the
+** st_dev and st_ino fields of the stat structure that fstat() fills in)
+** and check for locks already existing on that inode. When locks are
+** created or removed, we have to look at our own internal record of the
+** locks to see if another thread has previously set a lock on that same
+** inode.
+**
+** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
+** For VxWorks, we have to use the alternative unique ID system based on
+** canonical filename and implemented in the previous division.)
+**
+** The sqlite3_file structure for POSIX is no longer just an integer file
+** descriptor. It is now a structure that holds the integer file
+** descriptor and a pointer to a structure that describes the internal
+** locks on the corresponding inode. There is one locking structure
+** per inode, so if the same inode is opened twice, both unixFile structures
+** point to the same locking structure. The locking structure keeps
+** a reference count (so we will know when to delete it) and a "cnt"
+** field that tells us its internal lock status. cnt==0 means the
+** file is unlocked. cnt==-1 means the file has an exclusive lock.
+** cnt>0 means there are cnt shared locks on the file.
+**
+** Any attempt to lock or unlock a file first checks the locking
+** structure. The fcntl() system call is only invoked to set a
+** POSIX lock if the internal lock structure transitions between
+** a locked and an unlocked state.
+**
+** But wait: there are yet more problems with POSIX advisory locks.
+**
+** If you close a file descriptor that points to a file that has locks,
+** all locks on that file that are owned by the current process are
+** released. To work around this problem, each unixInodeInfo object
+** maintains a count of the number of pending locks on tha inode.
+** When an attempt is made to close an unixFile, if there are
+** other unixFile open on the same inode that are holding locks, the call
+** to close() the file descriptor is deferred until all of the locks clear.
+** The unixInodeInfo structure keeps a list of file descriptors that need to
+** be closed and that list is walked (and cleared) when the last lock
+** clears.
+**
+** Yet another problem: LinuxThreads do not play well with posix locks.
+**
+** Many older versions of linux use the LinuxThreads library which is
+** not posix compliant. Under LinuxThreads, a lock created by thread
+** A cannot be modified or overridden by a different thread B.
+** Only thread A can modify the lock. Locking behavior is correct
+** if the appliation uses the newer Native Posix Thread Library (NPTL)
+** on linux - with NPTL a lock created by thread A can override locks
+** in thread B. But there is no way to know at compile-time which
+** threading library is being used. So there is no way to know at
+** compile-time whether or not thread A can override locks on thread B.
+** One has to do a run-time check to discover the behavior of the
+** current process.
+**
+** SQLite used to support LinuxThreads. But support for LinuxThreads
+** was dropped beginning with version 3.7.0. SQLite will still work with
+** LinuxThreads provided that (1) there is no more than one connection
+** per database file in the same process and (2) database connections
+** do not move across threads.
+*/
+
+/*
+** An instance of the following structure serves as the key used
+** to locate a particular unixInodeInfo object.
+*/
+struct unixFileId {
+ dev_t dev; /* Device number */
+#if OS_VXWORKS
+ struct vxworksFileId *pId; /* Unique file ID for vxworks. */
+#else
+ /* We are told that some versions of Android contain a bug that
+ ** sizes ino_t at only 32-bits instead of 64-bits. (See
+ ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
+ ** To work around this, always allocate 64-bits for the inode number.
+ ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
+ ** but that should not be a big deal. */
+ /* WAS: ino_t ino; */
+ u64 ino; /* Inode number */
+#endif
+};
+
+/*
+** An instance of the following structure is allocated for each open
+** inode.
+**
+** A single inode can have multiple file descriptors, so each unixFile
+** structure contains a pointer to an instance of this object and this
+** object keeps a count of the number of unixFile pointing to it.
+**
+** Mutex rules:
+**
+** (1) Only the pLockMutex mutex must be held in order to read or write
+** any of the locking fields:
+** nShared, nLock, eFileLock, bProcessLock, pUnused
+**
+** (2) When nRef>0, then the following fields are unchanging and can
+** be read (but not written) without holding any mutex:
+** fileId, pLockMutex
+**
+** (3) With the exceptions above, all the fields may only be read
+** or written while holding the global unixBigLock mutex.
+**
+** Deadlock prevention: The global unixBigLock mutex may not
+** be acquired while holding the pLockMutex mutex. If both unixBigLock
+** and pLockMutex are needed, then unixBigLock must be acquired first.
+*/
+struct unixInodeInfo {
+ struct unixFileId fileId; /* The lookup key */
+ sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
+ int nShared; /* Number of SHARED locks held */
+ int nLock; /* Number of outstanding file locks */
+ unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
+ unsigned char bProcessLock; /* An exclusive process lock is held */
+ UnixUnusedFd *pUnused; /* Unused file descriptors to close */
+ int nRef; /* Number of pointers to this structure */
+ unixShmNode *pShmNode; /* Shared memory associated with this inode */
+ unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
+ unixInodeInfo *pPrev; /* .... doubly linked */
+#if SQLITE_ENABLE_LOCKING_STYLE
+ unsigned long long sharedByte; /* for AFP simulated shared lock */
+#endif
+#if OS_VXWORKS
+ sem_t *pSem; /* Named POSIX semaphore */
+ char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
+#endif
+};
+
+/*
+** A lists of all unixInodeInfo objects.
+**
+** Must hold unixBigLock in order to read or write this variable.
+*/
+static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
+
+#ifdef SQLITE_DEBUG
+/*
+** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
+** This routine is used only within assert() to help verify correct mutex
+** usage.
+*/
+int unixFileMutexHeld(unixFile *pFile){
+ assert( pFile->pInode );
+ return sqlite3_mutex_held(pFile->pInode->pLockMutex);
+}
+int unixFileMutexNotheld(unixFile *pFile){
+ assert( pFile->pInode );
+ return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
+}
+#endif
+
+/*
+**
+** This function - unixLogErrorAtLine(), is only ever called via the macro
+** unixLogError().
+**
+** It is invoked after an error occurs in an OS function and errno has been
+** set. It logs a message using sqlite3_log() containing the current value of
+** errno and, if possible, the human-readable equivalent from strerror() or
+** strerror_r().
+**
+** The first argument passed to the macro should be the error code that
+** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
+** The two subsequent arguments should be the name of the OS function that
+** failed (e.g. "unlink", "open") and the associated file-system path,
+** if any.
+*/
+#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
+static int unixLogErrorAtLine(
+ int errcode, /* SQLite error code */
+ const char *zFunc, /* Name of OS function that failed */
+ const char *zPath, /* File path associated with error */
+ int iLine /* Source line number where error occurred */
+){
+ char *zErr; /* Message from strerror() or equivalent */
+ int iErrno = errno; /* Saved syscall error number */
+
+ /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
+ ** the strerror() function to obtain the human-readable error message
+ ** equivalent to errno. Otherwise, use strerror_r().
+ */
+#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
+ char aErr[80];
+ memset(aErr, 0, sizeof(aErr));
+ zErr = aErr;
+
+ /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
+ ** assume that the system provides the GNU version of strerror_r() that
+ ** returns a pointer to a buffer containing the error message. That pointer
+ ** may point to aErr[], or it may point to some static storage somewhere.
+ ** Otherwise, assume that the system provides the POSIX version of
+ ** strerror_r(), which always writes an error message into aErr[].
+ **
+ ** If the code incorrectly assumes that it is the POSIX version that is
+ ** available, the error message will often be an empty string. Not a
+ ** huge problem. Incorrectly concluding that the GNU version is available
+ ** could lead to a segfault though.
+ */
+#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
+ zErr =
+# endif
+ strerror_r(iErrno, aErr, sizeof(aErr)-1);
+
+#elif SQLITE_THREADSAFE
+ /* This is a threadsafe build, but strerror_r() is not available. */
+ zErr = "";
+#else
+ /* Non-threadsafe build, use strerror(). */
+ zErr = strerror(iErrno);
+#endif
+
+ if( zPath==0 ) zPath = "";
+ sqlite3_log(errcode,
+ "os_unix.c:%d: (%d) %s(%s) - %s",
+ iLine, iErrno, zFunc, zPath, zErr
+ );
+
+ return errcode;
+}
+
+/*
+** Close a file descriptor.
+**
+** We assume that close() almost always works, since it is only in a
+** very sick application or on a very sick platform that it might fail.
+** If it does fail, simply leak the file descriptor, but do log the
+** error.
+**
+** Note that it is not safe to retry close() after EINTR since the
+** file descriptor might have already been reused by another thread.
+** So we don't even try to recover from an EINTR. Just log the error
+** and move on.
+*/
+static void robust_close(unixFile *pFile, int h, int lineno){
+ if( osClose(h) ){
+ unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
+ pFile ? pFile->zPath : 0, lineno);
+ }
+}
+
+/*
+** Set the pFile->lastErrno. Do this in a subroutine as that provides
+** a convenient place to set a breakpoint.
+*/
+static void storeLastErrno(unixFile *pFile, int error){
+ pFile->lastErrno = error;
+}
+
+/*
+** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
+*/
+static void closePendingFds(unixFile *pFile){
+ unixInodeInfo *pInode = pFile->pInode;
+ UnixUnusedFd *p;
+ UnixUnusedFd *pNext;
+ assert( unixFileMutexHeld(pFile) );
+ for(p=pInode->pUnused; p; p=pNext){
+ pNext = p->pNext;
+ robust_close(pFile, p->fd, __LINE__);
+ sqlite3_free(p);
+ }
+ pInode->pUnused = 0;
+}
+
+/*
+** Release a unixInodeInfo structure previously allocated by findInodeInfo().
+**
+** The global mutex must be held when this routine is called, but the mutex
+** on the inode being deleted must NOT be held.
+*/
+static void releaseInodeInfo(unixFile *pFile){
+ unixInodeInfo *pInode = pFile->pInode;
+ assert( unixMutexHeld() );
+ assert( unixFileMutexNotheld(pFile) );
+ if( ALWAYS(pInode) ){
+ pInode->nRef--;
+ if( pInode->nRef==0 ){
+ assert( pInode->pShmNode==0 );
+ sqlite3_mutex_enter(pInode->pLockMutex);
+ closePendingFds(pFile);
+ sqlite3_mutex_leave(pInode->pLockMutex);
+ if( pInode->pPrev ){
+ assert( pInode->pPrev->pNext==pInode );
+ pInode->pPrev->pNext = pInode->pNext;
+ }else{
+ assert( inodeList==pInode );
+ inodeList = pInode->pNext;
+ }
+ if( pInode->pNext ){
+ assert( pInode->pNext->pPrev==pInode );
+ pInode->pNext->pPrev = pInode->pPrev;
+ }
+ sqlite3_mutex_free(pInode->pLockMutex);
+ sqlite3_free(pInode);
+ }
+ }
+}
+
+/*
+** Given a file descriptor, locate the unixInodeInfo object that
+** describes that file descriptor. Create a new one if necessary. The
+** return value might be uninitialized if an error occurs.
+**
+** The global mutex must held when calling this routine.
+**
+** Return an appropriate error code.
+*/
+static int findInodeInfo(
+ unixFile *pFile, /* Unix file with file desc used in the key */
+ unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
+){
+ int rc; /* System call return code */
+ int fd; /* The file descriptor for pFile */
+ struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
+ struct stat statbuf; /* Low-level file information */
+ unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
+
+ assert( unixMutexHeld() );
+
+ /* Get low-level information about the file that we can used to
+ ** create a unique name for the file.
+ */
+ fd = pFile->h;
+ rc = osFstat(fd, &statbuf);
+ if( rc!=0 ){
+ storeLastErrno(pFile, errno);
+#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
+ if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
+#endif
+ return SQLITE_IOERR;
+ }
+
+#ifdef __APPLE__
+ /* On OS X on an msdos filesystem, the inode number is reported
+ ** incorrectly for zero-size files. See ticket #3260. To work
+ ** around this problem (we consider it a bug in OS X, not SQLite)
+ ** we always increase the file size to 1 by writing a single byte
+ ** prior to accessing the inode number. The one byte written is
+ ** an ASCII 'S' character which also happens to be the first byte
+ ** in the header of every SQLite database. In this way, if there
+ ** is a race condition such that another thread has already populated
+ ** the first page of the database, no damage is done.
+ */
+ if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
+ do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
+ if( rc!=1 ){
+ storeLastErrno(pFile, errno);
+ return SQLITE_IOERR;
+ }
+ rc = osFstat(fd, &statbuf);
+ if( rc!=0 ){
+ storeLastErrno(pFile, errno);
+ return SQLITE_IOERR;
+ }
+ }
+#endif
+
+ memset(&fileId, 0, sizeof(fileId));
+ fileId.dev = statbuf.st_dev;
+#if OS_VXWORKS
+ fileId.pId = pFile->pId;
+#else
+ fileId.ino = (u64)statbuf.st_ino;
+#endif
+ assert( unixMutexHeld() );
+ pInode = inodeList;
+ while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
+ pInode = pInode->pNext;
+ }
+ if( pInode==0 ){
+ pInode = sqlite3_malloc64( sizeof(*pInode) );
+ if( pInode==0 ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ memset(pInode, 0, sizeof(*pInode));
+ memcpy(&pInode->fileId, &fileId, sizeof(fileId));
+ if( sqlite3GlobalConfig.bCoreMutex ){
+ pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
+ if( pInode->pLockMutex==0 ){
+ sqlite3_free(pInode);
+ return SQLITE_NOMEM_BKPT;
+ }
+ }
+ pInode->nRef = 1;
+ assert( unixMutexHeld() );
+ pInode->pNext = inodeList;
+ pInode->pPrev = 0;
+ if( inodeList ) inodeList->pPrev = pInode;
+ inodeList = pInode;
+ }else{
+ pInode->nRef++;
+ }
+ *ppInode = pInode;
+ return SQLITE_OK;
+}
+
+/*
+** Return TRUE if pFile has been renamed or unlinked since it was first opened.
+*/
+static int fileHasMoved(unixFile *pFile){
+#if OS_VXWORKS
+ return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
+#else
+ struct stat buf;
+ return pFile->pInode!=0 &&
+ (osStat(pFile->zPath, &buf)!=0
+ || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
+#endif
+}
+
+
+/*
+** Check a unixFile that is a database. Verify the following:
+**
+** (1) There is exactly one hard link on the file
+** (2) The file is not a symbolic link
+** (3) The file has not been renamed or unlinked
+**
+** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
+*/
+static void verifyDbFile(unixFile *pFile){
+ struct stat buf;
+ int rc;
+
+ /* These verifications occurs for the main database only */
+ if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
+
+ rc = osFstat(pFile->h, &buf);
+ if( rc!=0 ){
+ sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
+ return;
+ }
+ if( buf.st_nlink==0 ){
+ sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
+ return;
+ }
+ if( buf.st_nlink>1 ){
+ sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
+ return;
+ }
+ if( fileHasMoved(pFile) ){
+ sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
+ return;
+ }
+}
+
+
+/*
+** This routine checks if there is a RESERVED lock held on the specified
+** file by this or any other process. If such a lock is held, set *pResOut
+** to a non-zero value otherwise *pResOut is set to zero. The return value
+** is set to SQLITE_OK unless an I/O error occurs during lock checking.
+*/
+static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
+ int rc = SQLITE_OK;
+ int reserved = 0;
+ unixFile *pFile = (unixFile*)id;
+
+ SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
+
+ assert( pFile );
+ assert( pFile->eFileLock<=SHARED_LOCK );
+ sqlite3_mutex_enter(pFile->pInode->pLockMutex);
+
+ /* Check if a thread in this process holds such a lock */
+ if( pFile->pInode->eFileLock>SHARED_LOCK ){
+ reserved = 1;
+ }
+
+ /* Otherwise see if some other process holds it.
+ */
+#ifndef __DJGPP__
+ if( !reserved && !pFile->pInode->bProcessLock ){
+ struct flock lock;
+ lock.l_whence = SEEK_SET;
+ lock.l_start = RESERVED_BYTE;
+ lock.l_len = 1;
+ lock.l_type = F_WRLCK;
+ if( osFcntl(pFile->h, F_GETLK, &lock) ){
+ rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
+ storeLastErrno(pFile, errno);
+ } else if( lock.l_type!=F_UNLCK ){
+ reserved = 1;
+ }
+ }
+#endif
+
+ sqlite3_mutex_leave(pFile->pInode->pLockMutex);
+ OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
+
+ *pResOut = reserved;
+ return rc;
+}
+
+/* Forward declaration*/
+static int unixSleep(sqlite3_vfs*,int);
+
+/*
+** Set a posix-advisory-lock.
+**
+** There are two versions of this routine. If compiled with
+** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
+** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
+** value is set, then it is the number of milliseconds to wait before
+** failing the lock. The iBusyTimeout value is always reset back to
+** zero on each call.
+**
+** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
+** attempt to set the lock.
+*/
+#ifndef SQLITE_ENABLE_SETLK_TIMEOUT
+# define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
+#else
+static int osSetPosixAdvisoryLock(
+ int h, /* The file descriptor on which to take the lock */
+ struct flock *pLock, /* The description of the lock */
+ unixFile *pFile /* Structure holding timeout value */
+){
+ int tm = pFile->iBusyTimeout;
+ int rc = osFcntl(h,F_SETLK,pLock);
+ while( rc<0 && tm>0 ){
+ /* On systems that support some kind of blocking file lock with a timeout,
+ ** make appropriate changes here to invoke that blocking file lock. On
+ ** generic posix, however, there is no such API. So we simply try the
+ ** lock once every millisecond until either the timeout expires, or until
+ ** the lock is obtained. */
+ unixSleep(0,1000);
+ rc = osFcntl(h,F_SETLK,pLock);
+ tm--;
+ }
+ return rc;
+}
+#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
+
+
+/*
+** Attempt to set a system-lock on the file pFile. The lock is
+** described by pLock.
+**
+** If the pFile was opened read/write from unix-excl, then the only lock
+** ever obtained is an exclusive lock, and it is obtained exactly once
+** the first time any lock is attempted. All subsequent system locking
+** operations become no-ops. Locking operations still happen internally,
+** in order to coordinate access between separate database connections
+** within this process, but all of that is handled in memory and the
+** operating system does not participate.
+**
+** This function is a pass-through to fcntl(F_SETLK) if pFile is using
+** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
+** and is read-only.
+**
+** Zero is returned if the call completes successfully, or -1 if a call
+** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
+*/
+static int unixFileLock(unixFile *pFile, struct flock *pLock){
+ int rc;
+ unixInodeInfo *pInode = pFile->pInode;
+ assert( pInode!=0 );
+ assert( sqlite3_mutex_held(pInode->pLockMutex) );
+ if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
+ if( pInode->bProcessLock==0 ){
+ struct flock lock;
+ assert( pInode->nLock==0 );
+ lock.l_whence = SEEK_SET;
+ lock.l_start = SHARED_FIRST;
+ lock.l_len = SHARED_SIZE;
+ lock.l_type = F_WRLCK;
+ rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
+ if( rc<0 ) return rc;
+ pInode->bProcessLock = 1;
+ pInode->nLock++;
+ }else{
+ rc = 0;
+ }
+ }else{
+ rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
+ }
+ return rc;
+}
+
+/*
+** Lock the file with the lock specified by parameter eFileLock - one
+** of the following:
+**
+** (1) SHARED_LOCK
+** (2) RESERVED_LOCK
+** (3) PENDING_LOCK
+** (4) EXCLUSIVE_LOCK
+**
+** Sometimes when requesting one lock state, additional lock states
+** are inserted in between. The locking might fail on one of the later
+** transitions leaving the lock state different from what it started but
+** still short of its goal. The following chart shows the allowed
+** transitions and the inserted intermediate states:
+**
+** UNLOCKED -> SHARED
+** SHARED -> RESERVED
+** SHARED -> (PENDING) -> EXCLUSIVE
+** RESERVED -> (PENDING) -> EXCLUSIVE
+** PENDING -> EXCLUSIVE
+**
+** This routine will only increase a lock. Use the sqlite3OsUnlock()
+** routine to lower a locking level.
+*/
+static int unixLock(sqlite3_file *id, int eFileLock){
+ /* The following describes the implementation of the various locks and
+ ** lock transitions in terms of the POSIX advisory shared and exclusive
+ ** lock primitives (called read-locks and write-locks below, to avoid
+ ** confusion with SQLite lock names). The algorithms are complicated
+ ** slightly in order to be compatible with Windows95 systems simultaneously
+ ** accessing the same database file, in case that is ever required.
+ **
+ ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
+ ** byte', each single bytes at well known offsets, and the 'shared byte
+ ** range', a range of 510 bytes at a well known offset.
+ **
+ ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
+ ** byte'. If this is successful, 'shared byte range' is read-locked
+ ** and the lock on the 'pending byte' released. (Legacy note: When
+ ** SQLite was first developed, Windows95 systems were still very common,
+ ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
+ ** single randomly selected by from the 'shared byte range' is locked.
+ ** Windows95 is now pretty much extinct, but this work-around for the
+ ** lack of shared-locks on Windows95 lives on, for backwards
+ ** compatibility.)
+ **
+ ** A process may only obtain a RESERVED lock after it has a SHARED lock.
+ ** A RESERVED lock is implemented by grabbing a write-lock on the
+ ** 'reserved byte'.
+ **
+ ** A process may only obtain a PENDING lock after it has obtained a
+ ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
+ ** on the 'pending byte'. This ensures that no new SHARED locks can be
+ ** obtained, but existing SHARED locks are allowed to persist. A process
+ ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
+ ** This property is used by the algorithm for rolling back a journal file
+ ** after a crash.
+ **
+ ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
+ ** implemented by obtaining a write-lock on the entire 'shared byte
+ ** range'. Since all other locks require a read-lock on one of the bytes
+ ** within this range, this ensures that no other locks are held on the
+ ** database.
+ */
+ int rc = SQLITE_OK;
+ unixFile *pFile = (unixFile*)id;
+ unixInodeInfo *pInode;
+ struct flock lock;
+ int tErrno = 0;
+
+ assert( pFile );
+ OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
+ azFileLock(eFileLock), azFileLock(pFile->eFileLock),
+ azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
+ osGetpid(0)));
+
+ /* If there is already a lock of this type or more restrictive on the
+ ** unixFile, do nothing. Don't use the end_lock: exit path, as
+ ** unixEnterMutex() hasn't been called yet.
+ */
+ if( pFile->eFileLock>=eFileLock ){
+ OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
+ azFileLock(eFileLock)));
+ return SQLITE_OK;
+ }
+
+ /* Make sure the locking sequence is correct.
+ ** (1) We never move from unlocked to anything higher than shared lock.
+ ** (2) SQLite never explicitly requests a pendig lock.
+ ** (3) A shared lock is always held when a reserve lock is requested.
+ */
+ assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
+ assert( eFileLock!=PENDING_LOCK );
+ assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
+
+ /* This mutex is needed because pFile->pInode is shared across threads
+ */
+ pInode = pFile->pInode;
+ sqlite3_mutex_enter(pInode->pLockMutex);
+
+ /* If some thread using this PID has a lock via a different unixFile*
+ ** handle that precludes the requested lock, return BUSY.
+ */
+ if( (pFile->eFileLock!=pInode->eFileLock &&
+ (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
+ ){
+ rc = SQLITE_BUSY;
+ goto end_lock;
+ }
+
+ /* If a SHARED lock is requested, and some thread using this PID already
+ ** has a SHARED or RESERVED lock, then increment reference counts and
+ ** return SQLITE_OK.
+ */
+ if( eFileLock==SHARED_LOCK &&
+ (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
+ assert( eFileLock==SHARED_LOCK );
+ assert( pFile->eFileLock==0 );
+ assert( pInode->nShared>0 );
+ pFile->eFileLock = SHARED_LOCK;
+ pInode->nShared++;
+ pInode->nLock++;
+ goto end_lock;
+ }
+
+
+ /* A PENDING lock is needed before acquiring a SHARED lock and before
+ ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
+ ** be released.
+ */
+ lock.l_len = 1L;
+ lock.l_whence = SEEK_SET;
+ if( eFileLock==SHARED_LOCK
+ || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
+ ){
+ lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
+ lock.l_start = PENDING_BYTE;
+ if( unixFileLock(pFile, &lock) ){
+ tErrno = errno;
+ rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
+ if( rc!=SQLITE_BUSY ){
+ storeLastErrno(pFile, tErrno);
+ }
+ goto end_lock;
+ }
+ }
+
+
+ /* If control gets to this point, then actually go ahead and make
+ ** operating system calls for the specified lock.
+ */
+ if( eFileLock==SHARED_LOCK ){
+ assert( pInode->nShared==0 );
+ assert( pInode->eFileLock==0 );
+ assert( rc==SQLITE_OK );
+
+ /* Now get the read-lock */
+ lock.l_start = SHARED_FIRST;
+ lock.l_len = SHARED_SIZE;
+ if( unixFileLock(pFile, &lock) ){
+ tErrno = errno;
+ rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
+ }
+
+ /* Drop the temporary PENDING lock */
+ lock.l_start = PENDING_BYTE;
+ lock.l_len = 1L;
+ lock.l_type = F_UNLCK;
+ if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
+ /* This could happen with a network mount */
+ tErrno = errno;
+ rc = SQLITE_IOERR_UNLOCK;
+ }
+
+ if( rc ){
+ if( rc!=SQLITE_BUSY ){
+ storeLastErrno(pFile, tErrno);
+ }
+ goto end_lock;
+ }else{
+ pFile->eFileLock = SHARED_LOCK;
+ pInode->nLock++;
+ pInode->nShared = 1;
+ }
+ }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
+ /* We are trying for an exclusive lock but another thread in this
+ ** same process is still holding a shared lock. */
+ rc = SQLITE_BUSY;
+ }else{
+ /* The request was for a RESERVED or EXCLUSIVE lock. It is
+ ** assumed that there is a SHARED or greater lock on the file
+ ** already.
+ */
+ assert( 0!=pFile->eFileLock );
+ lock.l_type = F_WRLCK;
+
+ assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
+ if( eFileLock==RESERVED_LOCK ){
+ lock.l_start = RESERVED_BYTE;
+ lock.l_len = 1L;
+ }else{
+ lock.l_start = SHARED_FIRST;
+ lock.l_len = SHARED_SIZE;
+ }
+
+ if( unixFileLock(pFile, &lock) ){
+ tErrno = errno;
+ rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
+ if( rc!=SQLITE_BUSY ){
+ storeLastErrno(pFile, tErrno);
+ }
+ }
+ }
+
+
+#ifdef SQLITE_DEBUG
+ /* Set up the transaction-counter change checking flags when
+ ** transitioning from a SHARED to a RESERVED lock. The change
+ ** from SHARED to RESERVED marks the beginning of a normal
+ ** write operation (not a hot journal rollback).
+ */
+ if( rc==SQLITE_OK
+ && pFile->eFileLock<=SHARED_LOCK
+ && eFileLock==RESERVED_LOCK
+ ){
+ pFile->transCntrChng = 0;
+ pFile->dbUpdate = 0;
+ pFile->inNormalWrite = 1;
+ }
+#endif
+
+
+ if( rc==SQLITE_OK ){
+ pFile->eFileLock = eFileLock;
+ pInode->eFileLock = eFileLock;
+ }else if( eFileLock==EXCLUSIVE_LOCK ){
+ pFile->eFileLock = PENDING_LOCK;
+ pInode->eFileLock = PENDING_LOCK;
+ }
+
+end_lock:
+ sqlite3_mutex_leave(pInode->pLockMutex);
+ OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
+ rc==SQLITE_OK ? "ok" : "failed"));
+ return rc;
+}
+
+/*
+** Add the file descriptor used by file handle pFile to the corresponding
+** pUnused list.
+*/
+static void setPendingFd(unixFile *pFile){
+ unixInodeInfo *pInode = pFile->pInode;
+ UnixUnusedFd *p = pFile->pPreallocatedUnused;
+ assert( unixFileMutexHeld(pFile) );
+ p->pNext = pInode->pUnused;
+ pInode->pUnused = p;
+ pFile->h = -1;
+ pFile->pPreallocatedUnused = 0;
+}
+
+/*
+** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
+** must be either NO_LOCK or SHARED_LOCK.
+**
+** If the locking level of the file descriptor is already at or below
+** the requested locking level, this routine is a no-op.
+**
+** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
+** the byte range is divided into 2 parts and the first part is unlocked then
+** set to a read lock, then the other part is simply unlocked. This works
+** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
+** remove the write lock on a region when a read lock is set.
+*/
+static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
+ unixFile *pFile = (unixFile*)id;
+ unixInodeInfo *pInode;
+ struct flock lock;
+ int rc = SQLITE_OK;
+
+ assert( pFile );
+ OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
+ pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
+ osGetpid(0)));
+
+ assert( eFileLock<=SHARED_LOCK );
+ if( pFile->eFileLock<=eFileLock ){
+ return SQLITE_OK;
+ }
+ pInode = pFile->pInode;
+ sqlite3_mutex_enter(pInode->pLockMutex);
+ assert( pInode->nShared!=0 );
+ if( pFile->eFileLock>SHARED_LOCK ){
+ assert( pInode->eFileLock==pFile->eFileLock );
+
+#ifdef SQLITE_DEBUG
+ /* When reducing a lock such that other processes can start
+ ** reading the database file again, make sure that the
+ ** transaction counter was updated if any part of the database
+ ** file changed. If the transaction counter is not updated,
+ ** other connections to the same file might not realize that
+ ** the file has changed and hence might not know to flush their
+ ** cache. The use of a stale cache can lead to database corruption.
+ */
+ pFile->inNormalWrite = 0;
+#endif
+
+ /* downgrading to a shared lock on NFS involves clearing the write lock
+ ** before establishing the readlock - to avoid a race condition we downgrade
+ ** the lock in 2 blocks, so that part of the range will be covered by a
+ ** write lock until the rest is covered by a read lock:
+ ** 1: [WWWWW]
+ ** 2: [....W]
+ ** 3: [RRRRW]
+ ** 4: [RRRR.]
+ */
+ if( eFileLock==SHARED_LOCK ){
+#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
+ (void)handleNFSUnlock;
+ assert( handleNFSUnlock==0 );
+#endif
+#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
+ if( handleNFSUnlock ){
+ int tErrno; /* Error code from system call errors */
+ off_t divSize = SHARED_SIZE - 1;
+
+ lock.l_type = F_UNLCK;
+ lock.l_whence = SEEK_SET;
+ lock.l_start = SHARED_FIRST;
+ lock.l_len = divSize;
+ if( unixFileLock(pFile, &lock)==(-1) ){
+ tErrno = errno;
+ rc = SQLITE_IOERR_UNLOCK;
+ storeLastErrno(pFile, tErrno);
+ goto end_unlock;
+ }
+ lock.l_type = F_RDLCK;
+ lock.l_whence = SEEK_SET;
+ lock.l_start = SHARED_FIRST;
+ lock.l_len = divSize;
+ if( unixFileLock(pFile, &lock)==(-1) ){
+ tErrno = errno;
+ rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
+ if( IS_LOCK_ERROR(rc) ){
+ storeLastErrno(pFile, tErrno);
+ }
+ goto end_unlock;
+ }
+ lock.l_type = F_UNLCK;
+ lock.l_whence = SEEK_SET;
+ lock.l_start = SHARED_FIRST+divSize;
+ lock.l_len = SHARED_SIZE-divSize;
+ if( unixFileLock(pFile, &lock)==(-1) ){
+ tErrno = errno;
+ rc = SQLITE_IOERR_UNLOCK;
+ storeLastErrno(pFile, tErrno);
+ goto end_unlock;
+ }
+ }else
+#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
+ {
+ lock.l_type = F_RDLCK;
+ lock.l_whence = SEEK_SET;
+ lock.l_start = SHARED_FIRST;
+ lock.l_len = SHARED_SIZE;
+ if( unixFileLock(pFile, &lock) ){
+ /* In theory, the call to unixFileLock() cannot fail because another
+ ** process is holding an incompatible lock. If it does, this
+ ** indicates that the other process is not following the locking
+ ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
+ ** SQLITE_BUSY would confuse the upper layer (in practice it causes
+ ** an assert to fail). */
+ rc = SQLITE_IOERR_RDLOCK;
+ storeLastErrno(pFile, errno);
+ goto end_unlock;
+ }
+ }
+ }
+ lock.l_type = F_UNLCK;
+ lock.l_whence = SEEK_SET;
+ lock.l_start = PENDING_BYTE;
+ lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
+ if( unixFileLock(pFile, &lock)==0 ){
+ pInode->eFileLock = SHARED_LOCK;
+ }else{
+ rc = SQLITE_IOERR_UNLOCK;
+ storeLastErrno(pFile, errno);
+ goto end_unlock;
+ }
+ }
+ if( eFileLock==NO_LOCK ){
+ /* Decrement the shared lock counter. Release the lock using an
+ ** OS call only when all threads in this same process have released
+ ** the lock.
+ */
+ pInode->nShared--;
+ if( pInode->nShared==0 ){
+ lock.l_type = F_UNLCK;
+ lock.l_whence = SEEK_SET;
+ lock.l_start = lock.l_len = 0L;
+ if( unixFileLock(pFile, &lock)==0 ){
+ pInode->eFileLock = NO_LOCK;
+ }else{
+ rc = SQLITE_IOERR_UNLOCK;
+ storeLastErrno(pFile, errno);
+ pInode->eFileLock = NO_LOCK;
+ pFile->eFileLock = NO_LOCK;
+ }
+ }
+
+ /* Decrement the count of locks against this same file. When the
+ ** count reaches zero, close any other file descriptors whose close
+ ** was deferred because of outstanding locks.
+ */
+ pInode->nLock--;
+ assert( pInode->nLock>=0 );
+ if( pInode->nLock==0 ) closePendingFds(pFile);
+ }
+
+end_unlock:
+ sqlite3_mutex_leave(pInode->pLockMutex);
+ if( rc==SQLITE_OK ){
+ pFile->eFileLock = eFileLock;
+ }
+ return rc;
+}
+
+/*
+** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
+** must be either NO_LOCK or SHARED_LOCK.
+**
+** If the locking level of the file descriptor is already at or below
+** the requested locking level, this routine is a no-op.
+*/
+static int unixUnlock(sqlite3_file *id, int eFileLock){
+#if SQLITE_MAX_MMAP_SIZE>0
+ assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
+#endif
+ return posixUnlock(id, eFileLock, 0);
+}
+
+#if SQLITE_MAX_MMAP_SIZE>0
+static int unixMapfile(unixFile *pFd, i64 nByte);
+static void unixUnmapfile(unixFile *pFd);
+#endif
+
+/*
+** This function performs the parts of the "close file" operation
+** common to all locking schemes. It closes the directory and file
+** handles, if they are valid, and sets all fields of the unixFile
+** structure to 0.
+**
+** It is *not* necessary to hold the mutex when this routine is called,
+** even on VxWorks. A mutex will be acquired on VxWorks by the
+** vxworksReleaseFileId() routine.
+*/
+static int closeUnixFile(sqlite3_file *id){
+ unixFile *pFile = (unixFile*)id;
+#if SQLITE_MAX_MMAP_SIZE>0
+ unixUnmapfile(pFile);
+#endif
+ if( pFile->h>=0 ){
+ robust_close(pFile, pFile->h, __LINE__);
+ pFile->h = -1;
+ }
+#if OS_VXWORKS
+ if( pFile->pId ){
+ if( pFile->ctrlFlags & UNIXFILE_DELETE ){
+ osUnlink(pFile->pId->zCanonicalName);
+ }
+ vxworksReleaseFileId(pFile->pId);
+ pFile->pId = 0;
+ }
+#endif
+#ifdef SQLITE_UNLINK_AFTER_CLOSE
+ if( pFile->ctrlFlags & UNIXFILE_DELETE ){
+ osUnlink(pFile->zPath);
+ sqlite3_free(*(char**)&pFile->zPath);
+ pFile->zPath = 0;
+ }
+#endif
+ OSTRACE(("CLOSE %-3d\n", pFile->h));
+ OpenCounter(-1);
+ sqlite3_free(pFile->pPreallocatedUnused);
+ memset(pFile, 0, sizeof(unixFile));
+ return SQLITE_OK;
+}
+
+/*
+** Close a file.
+*/
+static int unixClose(sqlite3_file *id){
+ int rc = SQLITE_OK;
+ unixFile *pFile = (unixFile *)id;
+ unixInodeInfo *pInode = pFile->pInode;
+
+ assert( pInode!=0 );
+ verifyDbFile(pFile);
+ unixUnlock(id, NO_LOCK);
+ assert( unixFileMutexNotheld(pFile) );
+ unixEnterMutex();
+
+ /* unixFile.pInode is always valid here. Otherwise, a different close
+ ** routine (e.g. nolockClose()) would be called instead.
+ */
+ assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
+ sqlite3_mutex_enter(pInode->pLockMutex);
+ if( pInode->nLock ){
+ /* If there are outstanding locks, do not actually close the file just
+ ** yet because that would clear those locks. Instead, add the file
+ ** descriptor to pInode->pUnused list. It will be automatically closed
+ ** when the last lock is cleared.
+ */
+ setPendingFd(pFile);
+ }
+ sqlite3_mutex_leave(pInode->pLockMutex);
+ releaseInodeInfo(pFile);
+ assert( pFile->pShm==0 );
+ rc = closeUnixFile(id);
+ unixLeaveMutex();
+ return rc;
+}
+
+/************** End of the posix advisory lock implementation *****************
+******************************************************************************/
+
+/******************************************************************************
+****************************** No-op Locking **********************************
+**
+** Of the various locking implementations available, this is by far the
+** simplest: locking is ignored. No attempt is made to lock the database
+** file for reading or writing.
+**
+** This locking mode is appropriate for use on read-only databases
+** (ex: databases that are burned into CD-ROM, for example.) It can
+** also be used if the application employs some external mechanism to
+** prevent simultaneous access of the same database by two or more
+** database connections. But there is a serious risk of database
+** corruption if this locking mode is used in situations where multiple
+** database connections are accessing the same database file at the same
+** time and one or more of those connections are writing.
+*/
+
+static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
+ UNUSED_PARAMETER(NotUsed);
+ *pResOut = 0;
+ return SQLITE_OK;
+}
+static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ return SQLITE_OK;
+}
+static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ return SQLITE_OK;
+}
+
+/*
+** Close the file.
+*/
+static int nolockClose(sqlite3_file *id) {
+ return closeUnixFile(id);
+}
+
+/******************* End of the no-op lock implementation *********************
+******************************************************************************/
+
+/******************************************************************************
+************************* Begin dot-file Locking ******************************
+**
+** The dotfile locking implementation uses the existence of separate lock
+** files (really a directory) to control access to the database. This works
+** on just about every filesystem imaginable. But there are serious downsides:
+**
+** (1) There is zero concurrency. A single reader blocks all other
+** connections from reading or writing the database.
+**
+** (2) An application crash or power loss can leave stale lock files
+** sitting around that need to be cleared manually.
+**
+** Nevertheless, a dotlock is an appropriate locking mode for use if no
+** other locking strategy is available.
+**
+** Dotfile locking works by creating a subdirectory in the same directory as
+** the database and with the same name but with a ".lock" extension added.
+** The existence of a lock directory implies an EXCLUSIVE lock. All other
+** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
+*/
+
+/*
+** The file suffix added to the data base filename in order to create the
+** lock directory.
+*/
+#define DOTLOCK_SUFFIX ".lock"
+
+/*
+** This routine checks if there is a RESERVED lock held on the specified
+** file by this or any other process. If such a lock is held, set *pResOut
+** to a non-zero value otherwise *pResOut is set to zero. The return value
+** is set to SQLITE_OK unless an I/O error occurs during lock checking.
+**
+** In dotfile locking, either a lock exists or it does not. So in this
+** variation of CheckReservedLock(), *pResOut is set to true if any lock
+** is held on the file and false if the file is unlocked.
+*/
+static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
+ int rc = SQLITE_OK;
+ int reserved = 0;
+ unixFile *pFile = (unixFile*)id;
+
+ SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
+
+ assert( pFile );
+ reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
+ OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
+ *pResOut = reserved;
+ return rc;
+}
+
+/*
+** Lock the file with the lock specified by parameter eFileLock - one
+** of the following:
+**
+** (1) SHARED_LOCK
+** (2) RESERVED_LOCK
+** (3) PENDING_LOCK
+** (4) EXCLUSIVE_LOCK
+**
+** Sometimes when requesting one lock state, additional lock states
+** are inserted in between. The locking might fail on one of the later
+** transitions leaving the lock state different from what it started but
+** still short of its goal. The following chart shows the allowed
+** transitions and the inserted intermediate states:
+**
+** UNLOCKED -> SHARED
+** SHARED -> RESERVED
+** SHARED -> (PENDING) -> EXCLUSIVE
+** RESERVED -> (PENDING) -> EXCLUSIVE
+** PENDING -> EXCLUSIVE
+**
+** This routine will only increase a lock. Use the sqlite3OsUnlock()
+** routine to lower a locking level.
+**
+** With dotfile locking, we really only support state (4): EXCLUSIVE.
+** But we track the other locking levels internally.
+*/
+static int dotlockLock(sqlite3_file *id, int eFileLock) {
+ unixFile *pFile = (unixFile*)id;
+ char *zLockFile = (char *)pFile->lockingContext;
+ int rc = SQLITE_OK;
+
+
+ /* If we have any lock, then the lock file already exists. All we have
+ ** to do is adjust our internal record of the lock level.
+ */
+ if( pFile->eFileLock > NO_LOCK ){
+ pFile->eFileLock = eFileLock;
+ /* Always update the timestamp on the old file */
+#ifdef HAVE_UTIME
+ utime(zLockFile, NULL);
+#else
+ utimes(zLockFile, NULL);
+#endif
+ return SQLITE_OK;
+ }
+
+ /* grab an exclusive lock */
+ rc = osMkdir(zLockFile, 0777);
+ if( rc<0 ){
+ /* failed to open/create the lock directory */
+ int tErrno = errno;
+ if( EEXIST == tErrno ){
+ rc = SQLITE_BUSY;
+ } else {
+ rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
+ if( rc!=SQLITE_BUSY ){
+ storeLastErrno(pFile, tErrno);
+ }
+ }
+ return rc;
+ }
+
+ /* got it, set the type and return ok */
+ pFile->eFileLock = eFileLock;
+ return rc;
+}
+
+/*
+** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
+** must be either NO_LOCK or SHARED_LOCK.
+**
+** If the locking level of the file descriptor is already at or below
+** the requested locking level, this routine is a no-op.
+**
+** When the locking level reaches NO_LOCK, delete the lock file.
+*/
+static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
+ unixFile *pFile = (unixFile*)id;
+ char *zLockFile = (char *)pFile->lockingContext;
+ int rc;
+
+ assert( pFile );
+ OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
+ pFile->eFileLock, osGetpid(0)));
+ assert( eFileLock<=SHARED_LOCK );
+
+ /* no-op if possible */
+ if( pFile->eFileLock==eFileLock ){
+ return SQLITE_OK;
+ }
+
+ /* To downgrade to shared, simply update our internal notion of the
+ ** lock state. No need to mess with the file on disk.
+ */
+ if( eFileLock==SHARED_LOCK ){
+ pFile->eFileLock = SHARED_LOCK;
+ return SQLITE_OK;
+ }
+
+ /* To fully unlock the database, delete the lock file */
+ assert( eFileLock==NO_LOCK );
+ rc = osRmdir(zLockFile);
+ if( rc<0 ){
+ int tErrno = errno;
+ if( tErrno==ENOENT ){
+ rc = SQLITE_OK;
+ }else{
+ rc = SQLITE_IOERR_UNLOCK;
+ storeLastErrno(pFile, tErrno);
+ }
+ return rc;
+ }
+ pFile->eFileLock = NO_LOCK;
+ return SQLITE_OK;
+}
+
+/*
+** Close a file. Make sure the lock has been released before closing.
+*/
+static int dotlockClose(sqlite3_file *id) {
+ unixFile *pFile = (unixFile*)id;
+ assert( id!=0 );
+ dotlockUnlock(id, NO_LOCK);
+ sqlite3_free(pFile->lockingContext);
+ return closeUnixFile(id);
+}
+/****************** End of the dot-file lock implementation *******************
+******************************************************************************/
+
+/******************************************************************************
+************************** Begin flock Locking ********************************
+**
+** Use the flock() system call to do file locking.
+**
+** flock() locking is like dot-file locking in that the various
+** fine-grain locking levels supported by SQLite are collapsed into
+** a single exclusive lock. In other words, SHARED, RESERVED, and
+** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
+** still works when you do this, but concurrency is reduced since
+** only a single process can be reading the database at a time.
+**
+** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
+*/
+#if SQLITE_ENABLE_LOCKING_STYLE
+
+/*
+** Retry flock() calls that fail with EINTR
+*/
+#ifdef EINTR
+static int robust_flock(int fd, int op){
+ int rc;
+ do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
+ return rc;
+}
+#else
+# define robust_flock(a,b) flock(a,b)
+#endif
+
+
+/*
+** This routine checks if there is a RESERVED lock held on the specified
+** file by this or any other process. If such a lock is held, set *pResOut
+** to a non-zero value otherwise *pResOut is set to zero. The return value
+** is set to SQLITE_OK unless an I/O error occurs during lock checking.
+*/
+static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
+ int rc = SQLITE_OK;
+ int reserved = 0;
+ unixFile *pFile = (unixFile*)id;
+
+ SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
+
+ assert( pFile );
+
+ /* Check if a thread in this process holds such a lock */
+ if( pFile->eFileLock>SHARED_LOCK ){
+ reserved = 1;
+ }
+
+ /* Otherwise see if some other process holds it. */
+ if( !reserved ){
+ /* attempt to get the lock */
+ int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
+ if( !lrc ){
+ /* got the lock, unlock it */
+ lrc = robust_flock(pFile->h, LOCK_UN);
+ if ( lrc ) {
+ int tErrno = errno;
+ /* unlock failed with an error */
+ lrc = SQLITE_IOERR_UNLOCK;
+ storeLastErrno(pFile, tErrno);
+ rc = lrc;
+ }
+ } else {
+ int tErrno = errno;
+ reserved = 1;
+ /* someone else might have it reserved */
+ lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
+ if( IS_LOCK_ERROR(lrc) ){
+ storeLastErrno(pFile, tErrno);
+ rc = lrc;
+ }
+ }
+ }
+ OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
+
+#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
+ if( (rc & 0xff) == SQLITE_IOERR ){
+ rc = SQLITE_OK;
+ reserved=1;
+ }
+#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
+ *pResOut = reserved;
+ return rc;
+}
+
+/*
+** Lock the file with the lock specified by parameter eFileLock - one
+** of the following:
+**
+** (1) SHARED_LOCK
+** (2) RESERVED_LOCK
+** (3) PENDING_LOCK
+** (4) EXCLUSIVE_LOCK
+**
+** Sometimes when requesting one lock state, additional lock states
+** are inserted in between. The locking might fail on one of the later
+** transitions leaving the lock state different from what it started but
+** still short of its goal. The following chart shows the allowed
+** transitions and the inserted intermediate states:
+**
+** UNLOCKED -> SHARED
+** SHARED -> RESERVED
+** SHARED -> (PENDING) -> EXCLUSIVE
+** RESERVED -> (PENDING) -> EXCLUSIVE
+** PENDING -> EXCLUSIVE
+**
+** flock() only really support EXCLUSIVE locks. We track intermediate
+** lock states in the sqlite3_file structure, but all locks SHARED or
+** above are really EXCLUSIVE locks and exclude all other processes from
+** access the file.
+**
+** This routine will only increase a lock. Use the sqlite3OsUnlock()
+** routine to lower a locking level.
+*/
+static int flockLock(sqlite3_file *id, int eFileLock) {
+ int rc = SQLITE_OK;
+ unixFile *pFile = (unixFile*)id;
+
+ assert( pFile );
+
+ /* if we already have a lock, it is exclusive.
+ ** Just adjust level and punt on outta here. */
+ if (pFile->eFileLock > NO_LOCK) {
+ pFile->eFileLock = eFileLock;
+ return SQLITE_OK;
+ }
+
+ /* grab an exclusive lock */
+
+ if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
+ int tErrno = errno;
+ /* didn't get, must be busy */
+ rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
+ if( IS_LOCK_ERROR(rc) ){
+ storeLastErrno(pFile, tErrno);
+ }
+ } else {
+ /* got it, set the type and return ok */
+ pFile->eFileLock = eFileLock;
+ }
+ OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
+ rc==SQLITE_OK ? "ok" : "failed"));
+#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
+ if( (rc & 0xff) == SQLITE_IOERR ){
+ rc = SQLITE_BUSY;
+ }
+#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
+ return rc;
+}
+
+
+/*
+** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
+** must be either NO_LOCK or SHARED_LOCK.
+**
+** If the locking level of the file descriptor is already at or below
+** the requested locking level, this routine is a no-op.
+*/
+static int flockUnlock(sqlite3_file *id, int eFileLock) {
+ unixFile *pFile = (unixFile*)id;
+
+ assert( pFile );
+ OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
+ pFile->eFileLock, osGetpid(0)));
+ assert( eFileLock<=SHARED_LOCK );
+
+ /* no-op if possible */
+ if( pFile->eFileLock==eFileLock ){
+ return SQLITE_OK;
+ }
+
+ /* shared can just be set because we always have an exclusive */
+ if (eFileLock==SHARED_LOCK) {
+ pFile->eFileLock = eFileLock;
+ return SQLITE_OK;
+ }
+
+ /* no, really, unlock. */
+ if( robust_flock(pFile->h, LOCK_UN) ){
+#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
+ return SQLITE_OK;
+#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
+ return SQLITE_IOERR_UNLOCK;
+ }else{
+ pFile->eFileLock = NO_LOCK;
+ return SQLITE_OK;
+ }
+}
+
+/*
+** Close a file.
+*/
+static int flockClose(sqlite3_file *id) {
+ assert( id!=0 );
+ flockUnlock(id, NO_LOCK);
+ return closeUnixFile(id);
+}
+
+#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
+
+/******************* End of the flock lock implementation *********************
+******************************************************************************/
+
+/******************************************************************************
+************************ Begin Named Semaphore Locking ************************
+**
+** Named semaphore locking is only supported on VxWorks.
+**
+** Semaphore locking is like dot-lock and flock in that it really only
+** supports EXCLUSIVE locking. Only a single process can read or write
+** the database file at a time. This reduces potential concurrency, but
+** makes the lock implementation much easier.
+*/
+#if OS_VXWORKS
+
+/*
+** This routine checks if there is a RESERVED lock held on the specified
+** file by this or any other process. If such a lock is held, set *pResOut
+** to a non-zero value otherwise *pResOut is set to zero. The return value
+** is set to SQLITE_OK unless an I/O error occurs during lock checking.
+*/
+static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
+ int rc = SQLITE_OK;
+ int reserved = 0;
+ unixFile *pFile = (unixFile*)id;
+
+ SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
+
+ assert( pFile );
+
+ /* Check if a thread in this process holds such a lock */
+ if( pFile->eFileLock>SHARED_LOCK ){
+ reserved = 1;
+ }
+
+ /* Otherwise see if some other process holds it. */
+ if( !reserved ){
+ sem_t *pSem = pFile->pInode->pSem;
+
+ if( sem_trywait(pSem)==-1 ){
+ int tErrno = errno;
+ if( EAGAIN != tErrno ){
+ rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
+ storeLastErrno(pFile, tErrno);
+ } else {
+ /* someone else has the lock when we are in NO_LOCK */
+ reserved = (pFile->eFileLock < SHARED_LOCK);
+ }
+ }else{
+ /* we could have it if we want it */
+ sem_post(pSem);
+ }
+ }
+ OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
+
+ *pResOut = reserved;
+ return rc;
+}
+
+/*
+** Lock the file with the lock specified by parameter eFileLock - one
+** of the following:
+**
+** (1) SHARED_LOCK
+** (2) RESERVED_LOCK
+** (3) PENDING_LOCK
+** (4) EXCLUSIVE_LOCK
+**
+** Sometimes when requesting one lock state, additional lock states
+** are inserted in between. The locking might fail on one of the later
+** transitions leaving the lock state different from what it started but
+** still short of its goal. The following chart shows the allowed
+** transitions and the inserted intermediate states:
+**
+** UNLOCKED -> SHARED
+** SHARED -> RESERVED
+** SHARED -> (PENDING) -> EXCLUSIVE
+** RESERVED -> (PENDING) -> EXCLUSIVE
+** PENDING -> EXCLUSIVE
+**
+** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
+** lock states in the sqlite3_file structure, but all locks SHARED or
+** above are really EXCLUSIVE locks and exclude all other processes from
+** access the file.
+**
+** This routine will only increase a lock. Use the sqlite3OsUnlock()
+** routine to lower a locking level.
+*/
+static int semXLock(sqlite3_file *id, int eFileLock) {
+ unixFile *pFile = (unixFile*)id;
+ sem_t *pSem = pFile->pInode->pSem;
+ int rc = SQLITE_OK;
+
+ /* if we already have a lock, it is exclusive.
+ ** Just adjust level and punt on outta here. */
+ if (pFile->eFileLock > NO_LOCK) {
+ pFile->eFileLock = eFileLock;
+ rc = SQLITE_OK;
+ goto sem_end_lock;
+ }
+
+ /* lock semaphore now but bail out when already locked. */
+ if( sem_trywait(pSem)==-1 ){
+ rc = SQLITE_BUSY;
+ goto sem_end_lock;
+ }
+
+ /* got it, set the type and return ok */
+ pFile->eFileLock = eFileLock;
+
+ sem_end_lock:
+ return rc;
+}
+
+/*
+** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
+** must be either NO_LOCK or SHARED_LOCK.
+**
+** If the locking level of the file descriptor is already at or below
+** the requested locking level, this routine is a no-op.
+*/
+static int semXUnlock(sqlite3_file *id, int eFileLock) {
+ unixFile *pFile = (unixFile*)id;
+ sem_t *pSem = pFile->pInode->pSem;
+
+ assert( pFile );
+ assert( pSem );
+ OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
+ pFile->eFileLock, osGetpid(0)));
+ assert( eFileLock<=SHARED_LOCK );
+
+ /* no-op if possible */
+ if( pFile->eFileLock==eFileLock ){
+ return SQLITE_OK;
+ }
+
+ /* shared can just be set because we always have an exclusive */
+ if (eFileLock==SHARED_LOCK) {
+ pFile->eFileLock = eFileLock;
+ return SQLITE_OK;
+ }
+
+ /* no, really unlock. */
+ if ( sem_post(pSem)==-1 ) {
+ int rc, tErrno = errno;
+ rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
+ if( IS_LOCK_ERROR(rc) ){
+ storeLastErrno(pFile, tErrno);
+ }
+ return rc;
+ }
+ pFile->eFileLock = NO_LOCK;
+ return SQLITE_OK;
+}
+
+/*
+ ** Close a file.
+ */
+static int semXClose(sqlite3_file *id) {
+ if( id ){
+ unixFile *pFile = (unixFile*)id;
+ semXUnlock(id, NO_LOCK);
+ assert( pFile );
+ assert( unixFileMutexNotheld(pFile) );
+ unixEnterMutex();
+ releaseInodeInfo(pFile);
+ unixLeaveMutex();
+ closeUnixFile(id);
+ }
+ return SQLITE_OK;
+}
+
+#endif /* OS_VXWORKS */
+/*
+** Named semaphore locking is only available on VxWorks.
+**
+*************** End of the named semaphore lock implementation ****************
+******************************************************************************/
+
+
+/******************************************************************************
+*************************** Begin AFP Locking *********************************
+**
+** AFP is the Apple Filing Protocol. AFP is a network filesystem found
+** on Apple Macintosh computers - both OS9 and OSX.
+**
+** Third-party implementations of AFP are available. But this code here
+** only works on OSX.
+*/
+
+#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
+/*
+** The afpLockingContext structure contains all afp lock specific state
+*/
+typedef struct afpLockingContext afpLockingContext;
+struct afpLockingContext {
+ int reserved;
+ const char *dbPath; /* Name of the open file */
+};
+
+struct ByteRangeLockPB2
+{
+ unsigned long long offset; /* offset to first byte to lock */
+ unsigned long long length; /* nbr of bytes to lock */
+ unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
+ unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
+ unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
+ int fd; /* file desc to assoc this lock with */
+};
+
+#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
+
+/*
+** This is a utility for setting or clearing a bit-range lock on an
+** AFP filesystem.
+**
+** Return SQLITE_OK on success, SQLITE_BUSY on failure.
+*/
+static int afpSetLock(
+ const char *path, /* Name of the file to be locked or unlocked */
+ unixFile *pFile, /* Open file descriptor on path */
+ unsigned long long offset, /* First byte to be locked */
+ unsigned long long length, /* Number of bytes to lock */
+ int setLockFlag /* True to set lock. False to clear lock */
+){
+ struct ByteRangeLockPB2 pb;
+ int err;
+
+ pb.unLockFlag = setLockFlag ? 0 : 1;
+ pb.startEndFlag = 0;
+ pb.offset = offset;
+ pb.length = length;
+ pb.fd = pFile->h;
+
+ OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
+ (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
+ offset, length));
+ err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
+ if ( err==-1 ) {
+ int rc;
+ int tErrno = errno;
+ OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
+ path, tErrno, strerror(tErrno)));
+#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
+ rc = SQLITE_BUSY;
+#else
+ rc = sqliteErrorFromPosixError(tErrno,
+ setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
+#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
+ if( IS_LOCK_ERROR(rc) ){
+ storeLastErrno(pFile, tErrno);
+ }
+ return rc;
+ } else {
+ return SQLITE_OK;
+ }
+}
+
+/*
+** This routine checks if there is a RESERVED lock held on the specified
+** file by this or any other process. If such a lock is held, set *pResOut
+** to a non-zero value otherwise *pResOut is set to zero. The return value
+** is set to SQLITE_OK unless an I/O error occurs during lock checking.
+*/
+static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
+ int rc = SQLITE_OK;
+ int reserved = 0;
+ unixFile *pFile = (unixFile*)id;
+ afpLockingContext *context;
+
+ SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
+
+ assert( pFile );
+ context = (afpLockingContext *) pFile->lockingContext;
+ if( context->reserved ){
+ *pResOut = 1;
+ return SQLITE_OK;
+ }
+ sqlite3_mutex_enter(pFile->pInode->pLockMutex);
+ /* Check if a thread in this process holds such a lock */
+ if( pFile->pInode->eFileLock>SHARED_LOCK ){
+ reserved = 1;
+ }
+
+ /* Otherwise see if some other process holds it.
+ */
+ if( !reserved ){
+ /* lock the RESERVED byte */
+ int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
+ if( SQLITE_OK==lrc ){
+ /* if we succeeded in taking the reserved lock, unlock it to restore
+ ** the original state */
+ lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
+ } else {
+ /* if we failed to get the lock then someone else must have it */
+ reserved = 1;
+ }
+ if( IS_LOCK_ERROR(lrc) ){
+ rc=lrc;
+ }
+ }
+
+ sqlite3_mutex_leave(pFile->pInode->pLockMutex);
+ OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
+
+ *pResOut = reserved;
+ return rc;
+}
+
+/*
+** Lock the file with the lock specified by parameter eFileLock - one
+** of the following:
+**
+** (1) SHARED_LOCK
+** (2) RESERVED_LOCK
+** (3) PENDING_LOCK
+** (4) EXCLUSIVE_LOCK
+**
+** Sometimes when requesting one lock state, additional lock states
+** are inserted in between. The locking might fail on one of the later
+** transitions leaving the lock state different from what it started but
+** still short of its goal. The following chart shows the allowed
+** transitions and the inserted intermediate states:
+**
+** UNLOCKED -> SHARED
+** SHARED -> RESERVED
+** SHARED -> (PENDING) -> EXCLUSIVE
+** RESERVED -> (PENDING) -> EXCLUSIVE
+** PENDING -> EXCLUSIVE
+**
+** This routine will only increase a lock. Use the sqlite3OsUnlock()
+** routine to lower a locking level.
+*/
+static int afpLock(sqlite3_file *id, int eFileLock){
+ int rc = SQLITE_OK;
+ unixFile *pFile = (unixFile*)id;
+ unixInodeInfo *pInode = pFile->pInode;
+ afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
+
+ assert( pFile );
+ OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
+ azFileLock(eFileLock), azFileLock(pFile->eFileLock),
+ azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
+
+ /* If there is already a lock of this type or more restrictive on the
+ ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
+ ** unixEnterMutex() hasn't been called yet.
+ */
+ if( pFile->eFileLock>=eFileLock ){
+ OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
+ azFileLock(eFileLock)));
+ return SQLITE_OK;
+ }
+
+ /* Make sure the locking sequence is correct
+ ** (1) We never move from unlocked to anything higher than shared lock.
+ ** (2) SQLite never explicitly requests a pendig lock.
+ ** (3) A shared lock is always held when a reserve lock is requested.
+ */
+ assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
+ assert( eFileLock!=PENDING_LOCK );
+ assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
+
+ /* This mutex is needed because pFile->pInode is shared across threads
+ */
+ pInode = pFile->pInode;
+ sqlite3_mutex_enter(pInode->pLockMutex);
+
+ /* If some thread using this PID has a lock via a different unixFile*
+ ** handle that precludes the requested lock, return BUSY.
+ */
+ if( (pFile->eFileLock!=pInode->eFileLock &&
+ (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
+ ){
+ rc = SQLITE_BUSY;
+ goto afp_end_lock;
+ }
+
+ /* If a SHARED lock is requested, and some thread using this PID already
+ ** has a SHARED or RESERVED lock, then increment reference counts and
+ ** return SQLITE_OK.
+ */
+ if( eFileLock==SHARED_LOCK &&
+ (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
+ assert( eFileLock==SHARED_LOCK );
+ assert( pFile->eFileLock==0 );
+ assert( pInode->nShared>0 );
+ pFile->eFileLock = SHARED_LOCK;
+ pInode->nShared++;
+ pInode->nLock++;
+ goto afp_end_lock;
+ }
+
+ /* A PENDING lock is needed before acquiring a SHARED lock and before
+ ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
+ ** be released.
+ */
+ if( eFileLock==SHARED_LOCK
+ || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
+ ){
+ int failed;
+ failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
+ if (failed) {
+ rc = failed;
+ goto afp_end_lock;
+ }
+ }
+
+ /* If control gets to this point, then actually go ahead and make
+ ** operating system calls for the specified lock.
+ */
+ if( eFileLock==SHARED_LOCK ){
+ int lrc1, lrc2, lrc1Errno = 0;
+ long lk, mask;
+
+ assert( pInode->nShared==0 );
+ assert( pInode->eFileLock==0 );
+
+ mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
+ /* Now get the read-lock SHARED_LOCK */
+ /* note that the quality of the randomness doesn't matter that much */
+ lk = random();
+ pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
+ lrc1 = afpSetLock(context->dbPath, pFile,
+ SHARED_FIRST+pInode->sharedByte, 1, 1);
+ if( IS_LOCK_ERROR(lrc1) ){
+ lrc1Errno = pFile->lastErrno;
+ }
+ /* Drop the temporary PENDING lock */
+ lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
+
+ if( IS_LOCK_ERROR(lrc1) ) {
+ storeLastErrno(pFile, lrc1Errno);
+ rc = lrc1;
+ goto afp_end_lock;
+ } else if( IS_LOCK_ERROR(lrc2) ){
+ rc = lrc2;
+ goto afp_end_lock;
+ } else if( lrc1 != SQLITE_OK ) {
+ rc = lrc1;
+ } else {
+ pFile->eFileLock = SHARED_LOCK;
+ pInode->nLock++;
+ pInode->nShared = 1;
+ }
+ }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
+ /* We are trying for an exclusive lock but another thread in this
+ ** same process is still holding a shared lock. */
+ rc = SQLITE_BUSY;
+ }else{
+ /* The request was for a RESERVED or EXCLUSIVE lock. It is
+ ** assumed that there is a SHARED or greater lock on the file
+ ** already.
+ */
+ int failed = 0;
+ assert( 0!=pFile->eFileLock );
+ if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
+ /* Acquire a RESERVED lock */
+ failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
+ if( !failed ){
+ context->reserved = 1;
+ }
+ }
+ if (!failed && eFileLock == EXCLUSIVE_LOCK) {
+ /* Acquire an EXCLUSIVE lock */
+
+ /* Remove the shared lock before trying the range. we'll need to
+ ** reestablish the shared lock if we can't get the afpUnlock
+ */
+ if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
+ pInode->sharedByte, 1, 0)) ){
+ int failed2 = SQLITE_OK;
+ /* now attemmpt to get the exclusive lock range */
+ failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
+ SHARED_SIZE, 1);
+ if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
+ SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
+ /* Can't reestablish the shared lock. Sqlite can't deal, this is
+ ** a critical I/O error
+ */
+ rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
+ SQLITE_IOERR_LOCK;
+ goto afp_end_lock;
+ }
+ }else{
+ rc = failed;
+ }
+ }
+ if( failed ){
+ rc = failed;
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ pFile->eFileLock = eFileLock;
+ pInode->eFileLock = eFileLock;
+ }else if( eFileLock==EXCLUSIVE_LOCK ){
+ pFile->eFileLock = PENDING_LOCK;
+ pInode->eFileLock = PENDING_LOCK;
+ }
+
+afp_end_lock:
+ sqlite3_mutex_leave(pInode->pLockMutex);
+ OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
+ rc==SQLITE_OK ? "ok" : "failed"));
+ return rc;
+}
+
+/*
+** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
+** must be either NO_LOCK or SHARED_LOCK.
+**
+** If the locking level of the file descriptor is already at or below
+** the requested locking level, this routine is a no-op.
+*/
+static int afpUnlock(sqlite3_file *id, int eFileLock) {
+ int rc = SQLITE_OK;
+ unixFile *pFile = (unixFile*)id;
+ unixInodeInfo *pInode;
+ afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
+ int skipShared = 0;
+#ifdef SQLITE_TEST
+ int h = pFile->h;
+#endif
+
+ assert( pFile );
+ OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
+ pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
+ osGetpid(0)));
+
+ assert( eFileLock<=SHARED_LOCK );
+ if( pFile->eFileLock<=eFileLock ){
+ return SQLITE_OK;
+ }
+ pInode = pFile->pInode;
+ sqlite3_mutex_enter(pInode->pLockMutex);
+ assert( pInode->nShared!=0 );
+ if( pFile->eFileLock>SHARED_LOCK ){
+ assert( pInode->eFileLock==pFile->eFileLock );
+ SimulateIOErrorBenign(1);
+ SimulateIOError( h=(-1) )
+ SimulateIOErrorBenign(0);
+
+#ifdef SQLITE_DEBUG
+ /* When reducing a lock such that other processes can start
+ ** reading the database file again, make sure that the
+ ** transaction counter was updated if any part of the database
+ ** file changed. If the transaction counter is not updated,
+ ** other connections to the same file might not realize that
+ ** the file has changed and hence might not know to flush their
+ ** cache. The use of a stale cache can lead to database corruption.
+ */
+ assert( pFile->inNormalWrite==0
+ || pFile->dbUpdate==0
+ || pFile->transCntrChng==1 );
+ pFile->inNormalWrite = 0;
+#endif
+
+ if( pFile->eFileLock==EXCLUSIVE_LOCK ){
+ rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
+ if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
+ /* only re-establish the shared lock if necessary */
+ int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
+ rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
+ } else {
+ skipShared = 1;
+ }
+ }
+ if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
+ rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
+ }
+ if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
+ rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
+ if( !rc ){
+ context->reserved = 0;
+ }
+ }
+ if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
+ pInode->eFileLock = SHARED_LOCK;
+ }
+ }
+ if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
+
+ /* Decrement the shared lock counter. Release the lock using an
+ ** OS call only when all threads in this same process have released
+ ** the lock.
+ */
+ unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
+ pInode->nShared--;
+ if( pInode->nShared==0 ){
+ SimulateIOErrorBenign(1);
+ SimulateIOError( h=(-1) )
+ SimulateIOErrorBenign(0);
+ if( !skipShared ){
+ rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
+ }
+ if( !rc ){
+ pInode->eFileLock = NO_LOCK;
+ pFile->eFileLock = NO_LOCK;
+ }
+ }
+ if( rc==SQLITE_OK ){
+ pInode->nLock--;
+ assert( pInode->nLock>=0 );
+ if( pInode->nLock==0 ) closePendingFds(pFile);
+ }
+ }
+
+ sqlite3_mutex_leave(pInode->pLockMutex);
+ if( rc==SQLITE_OK ){
+ pFile->eFileLock = eFileLock;
+ }
+ return rc;
+}
+
+/*
+** Close a file & cleanup AFP specific locking context
+*/
+static int afpClose(sqlite3_file *id) {
+ int rc = SQLITE_OK;
+ unixFile *pFile = (unixFile*)id;
+ assert( id!=0 );
+ afpUnlock(id, NO_LOCK);
+ assert( unixFileMutexNotheld(pFile) );
+ unixEnterMutex();
+ if( pFile->pInode ){
+ unixInodeInfo *pInode = pFile->pInode;
+ sqlite3_mutex_enter(pInode->pLockMutex);
+ if( pInode->nLock ){
+ /* If there are outstanding locks, do not actually close the file just
+ ** yet because that would clear those locks. Instead, add the file
+ ** descriptor to pInode->aPending. It will be automatically closed when
+ ** the last lock is cleared.
+ */
+ setPendingFd(pFile);
+ }
+ sqlite3_mutex_leave(pInode->pLockMutex);
+ }
+ releaseInodeInfo(pFile);
+ sqlite3_free(pFile->lockingContext);
+ rc = closeUnixFile(id);
+ unixLeaveMutex();
+ return rc;
+}
+
+#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
+/*
+** The code above is the AFP lock implementation. The code is specific
+** to MacOSX and does not work on other unix platforms. No alternative
+** is available. If you don't compile for a mac, then the "unix-afp"
+** VFS is not available.
+**
+********************* End of the AFP lock implementation **********************
+******************************************************************************/
+
+/******************************************************************************
+*************************** Begin NFS Locking ********************************/
+
+#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
+/*
+ ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
+ ** must be either NO_LOCK or SHARED_LOCK.
+ **
+ ** If the locking level of the file descriptor is already at or below
+ ** the requested locking level, this routine is a no-op.
+ */
+static int nfsUnlock(sqlite3_file *id, int eFileLock){
+ return posixUnlock(id, eFileLock, 1);
+}
+
+#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
+/*
+** The code above is the NFS lock implementation. The code is specific
+** to MacOSX and does not work on other unix platforms. No alternative
+** is available.
+**
+********************* End of the NFS lock implementation **********************
+******************************************************************************/
+
+/******************************************************************************
+**************** Non-locking sqlite3_file methods *****************************
+**
+** The next division contains implementations for all methods of the
+** sqlite3_file object other than the locking methods. The locking
+** methods were defined in divisions above (one locking method per
+** division). Those methods that are common to all locking modes
+** are gather together into this division.
+*/
+
+/*
+** Seek to the offset passed as the second argument, then read cnt
+** bytes into pBuf. Return the number of bytes actually read.
+**
+** NB: If you define USE_PREAD or USE_PREAD64, then it might also
+** be necessary to define _XOPEN_SOURCE to be 500. This varies from
+** one system to another. Since SQLite does not define USE_PREAD
+** in any form by default, we will not attempt to define _XOPEN_SOURCE.
+** See tickets #2741 and #2681.
+**
+** To avoid stomping the errno value on a failed read the lastErrno value
+** is set before returning.
+*/
+static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
+ int got;
+ int prior = 0;
+#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
+ i64 newOffset;
+#endif
+ TIMER_START;
+ assert( cnt==(cnt&0x1ffff) );
+ assert( id->h>2 );
+ do{
+#if defined(USE_PREAD)
+ got = osPread(id->h, pBuf, cnt, offset);
+ SimulateIOError( got = -1 );
+#elif defined(USE_PREAD64)
+ got = osPread64(id->h, pBuf, cnt, offset);
+ SimulateIOError( got = -1 );
+#else
+ newOffset = lseek(id->h, offset, SEEK_SET);
+ SimulateIOError( newOffset = -1 );
+ if( newOffset<0 ){
+ storeLastErrno((unixFile*)id, errno);
+ return -1;
+ }
+ got = osRead(id->h, pBuf, cnt);
+#endif
+ if( got==cnt ) break;
+ if( got<0 ){
+ if( errno==EINTR ){ got = 1; continue; }
+ prior = 0;
+ storeLastErrno((unixFile*)id, errno);
+ break;
+ }else if( got>0 ){
+ cnt -= got;
+ offset += got;
+ prior += got;
+ pBuf = (void*)(got + (char*)pBuf);
+ }
+ }while( got>0 );
+ TIMER_END;
+ OSTRACE(("READ %-3d %5d %7lld %llu\n",
+ id->h, got+prior, offset-prior, TIMER_ELAPSED));
+ return got+prior;
+}
+
+/*
+** Read data from a file into a buffer. Return SQLITE_OK if all
+** bytes were read successfully and SQLITE_IOERR if anything goes
+** wrong.
+*/
+static int unixRead(
+ sqlite3_file *id,
+ void *pBuf,
+ int amt,
+ sqlite3_int64 offset
+){
+ unixFile *pFile = (unixFile *)id;
+ int got;
+ assert( id );
+ assert( offset>=0 );
+ assert( amt>0 );
+
+ /* If this is a database file (not a journal, super-journal or temp
+ ** file), the bytes in the locking range should never be read or written. */
+#if 0
+ assert( pFile->pPreallocatedUnused==0
+ || offset>=PENDING_BYTE+512
+ || offset+amt<=PENDING_BYTE
+ );
+#endif
+
+#if SQLITE_MAX_MMAP_SIZE>0
+ /* Deal with as much of this read request as possible by transfering
+ ** data from the memory mapping using memcpy(). */
+ if( offset<pFile->mmapSize ){
+ if( offset+amt <= pFile->mmapSize ){
+ memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
+ return SQLITE_OK;
+ }else{
+ int nCopy = pFile->mmapSize - offset;
+ memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
+ pBuf = &((u8 *)pBuf)[nCopy];
+ amt -= nCopy;
+ offset += nCopy;
+ }
+ }
+#endif
+
+ got = seekAndRead(pFile, offset, pBuf, amt);
+ if( got==amt ){
+ return SQLITE_OK;
+ }else if( got<0 ){
+ /* lastErrno set by seekAndRead */
+ return SQLITE_IOERR_READ;
+ }else{
+ storeLastErrno(pFile, 0); /* not a system error */
+ /* Unread parts of the buffer must be zero-filled */
+ memset(&((char*)pBuf)[got], 0, amt-got);
+ return SQLITE_IOERR_SHORT_READ;
+ }
+}
+
+/*
+** Attempt to seek the file-descriptor passed as the first argument to
+** absolute offset iOff, then attempt to write nBuf bytes of data from
+** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
+** return the actual number of bytes written (which may be less than
+** nBuf).
+*/
+static int seekAndWriteFd(
+ int fd, /* File descriptor to write to */
+ i64 iOff, /* File offset to begin writing at */
+ const void *pBuf, /* Copy data from this buffer to the file */
+ int nBuf, /* Size of buffer pBuf in bytes */
+ int *piErrno /* OUT: Error number if error occurs */
+){
+ int rc = 0; /* Value returned by system call */
+
+ assert( nBuf==(nBuf&0x1ffff) );
+ assert( fd>2 );
+ assert( piErrno!=0 );
+ nBuf &= 0x1ffff;
+ TIMER_START;
+
+#if defined(USE_PREAD)
+ do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
+#elif defined(USE_PREAD64)
+ do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
+#else
+ do{
+ i64 iSeek = lseek(fd, iOff, SEEK_SET);
+ SimulateIOError( iSeek = -1 );
+ if( iSeek<0 ){
+ rc = -1;
+ break;
+ }
+ rc = osWrite(fd, pBuf, nBuf);
+ }while( rc<0 && errno==EINTR );
+#endif
+
+ TIMER_END;
+ OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
+
+ if( rc<0 ) *piErrno = errno;
+ return rc;
+}
+
+
+/*
+** Seek to the offset in id->offset then read cnt bytes into pBuf.
+** Return the number of bytes actually read. Update the offset.
+**
+** To avoid stomping the errno value on a failed write the lastErrno value
+** is set before returning.
+*/
+static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
+ return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
+}
+
+
+/*
+** Write data from a buffer into a file. Return SQLITE_OK on success
+** or some other error code on failure.
+*/
+static int unixWrite(
+ sqlite3_file *id,
+ const void *pBuf,
+ int amt,
+ sqlite3_int64 offset
+){
+ unixFile *pFile = (unixFile*)id;
+ int wrote = 0;
+ assert( id );
+ assert( amt>0 );
+
+ /* If this is a database file (not a journal, super-journal or temp
+ ** file), the bytes in the locking range should never be read or written. */
+#if 0
+ assert( pFile->pPreallocatedUnused==0
+ || offset>=PENDING_BYTE+512
+ || offset+amt<=PENDING_BYTE
+ );
+#endif
+
+#ifdef SQLITE_DEBUG
+ /* If we are doing a normal write to a database file (as opposed to
+ ** doing a hot-journal rollback or a write to some file other than a
+ ** normal database file) then record the fact that the database
+ ** has changed. If the transaction counter is modified, record that
+ ** fact too.
+ */
+ if( pFile->inNormalWrite ){
+ pFile->dbUpdate = 1; /* The database has been modified */
+ if( offset<=24 && offset+amt>=27 ){
+ int rc;
+ char oldCntr[4];
+ SimulateIOErrorBenign(1);
+ rc = seekAndRead(pFile, 24, oldCntr, 4);
+ SimulateIOErrorBenign(0);
+ if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
+ pFile->transCntrChng = 1; /* The transaction counter has changed */
+ }
+ }
+ }
+#endif
+
+#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
+ /* Deal with as much of this write request as possible by transfering
+ ** data from the memory mapping using memcpy(). */
+ if( offset<pFile->mmapSize ){
+ if( offset+amt <= pFile->mmapSize ){
+ memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
+ return SQLITE_OK;
+ }else{
+ int nCopy = pFile->mmapSize - offset;
+ memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
+ pBuf = &((u8 *)pBuf)[nCopy];
+ amt -= nCopy;
+ offset += nCopy;
+ }
+ }
+#endif
+
+ while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
+ amt -= wrote;
+ offset += wrote;
+ pBuf = &((char*)pBuf)[wrote];
+ }
+ SimulateIOError(( wrote=(-1), amt=1 ));
+ SimulateDiskfullError(( wrote=0, amt=1 ));
+
+ if( amt>wrote ){
+ if( wrote<0 && pFile->lastErrno!=ENOSPC ){
+ /* lastErrno set by seekAndWrite */
+ return SQLITE_IOERR_WRITE;
+ }else{
+ storeLastErrno(pFile, 0); /* not a system error */
+ return SQLITE_FULL;
+ }
+ }
+
+ return SQLITE_OK;
+}
+
+#ifdef SQLITE_TEST
+/*
+** Count the number of fullsyncs and normal syncs. This is used to test
+** that syncs and fullsyncs are occurring at the right times.
+*/
+SQLITE_API int sqlite3_sync_count = 0;
+SQLITE_API int sqlite3_fullsync_count = 0;
+#endif
+
+/*
+** We do not trust systems to provide a working fdatasync(). Some do.
+** Others do no. To be safe, we will stick with the (slightly slower)
+** fsync(). If you know that your system does support fdatasync() correctly,
+** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
+*/
+#if !defined(fdatasync) && !HAVE_FDATASYNC
+# define fdatasync fsync
+#endif
+
+/*
+** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
+** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
+** only available on Mac OS X. But that could change.
+*/
+#ifdef F_FULLFSYNC
+# define HAVE_FULLFSYNC 1
+#else
+# define HAVE_FULLFSYNC 0
+#endif
+
+
+/*
+** The fsync() system call does not work as advertised on many
+** unix systems. The following procedure is an attempt to make
+** it work better.
+**
+** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
+** for testing when we want to run through the test suite quickly.
+** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
+** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
+** or power failure will likely corrupt the database file.
+**
+** SQLite sets the dataOnly flag if the size of the file is unchanged.
+** The idea behind dataOnly is that it should only write the file content
+** to disk, not the inode. We only set dataOnly if the file size is
+** unchanged since the file size is part of the inode. However,
+** Ted Ts'o tells us that fdatasync() will also write the inode if the
+** file size has changed. The only real difference between fdatasync()
+** and fsync(), Ted tells us, is that fdatasync() will not flush the
+** inode if the mtime or owner or other inode attributes have changed.
+** We only care about the file size, not the other file attributes, so
+** as far as SQLite is concerned, an fdatasync() is always adequate.
+** So, we always use fdatasync() if it is available, regardless of
+** the value of the dataOnly flag.
+*/
+static int full_fsync(int fd, int fullSync, int dataOnly){
+ int rc;
+
+ /* The following "ifdef/elif/else/" block has the same structure as
+ ** the one below. It is replicated here solely to avoid cluttering
+ ** up the real code with the UNUSED_PARAMETER() macros.
+ */
+#ifdef SQLITE_NO_SYNC
+ UNUSED_PARAMETER(fd);
+ UNUSED_PARAMETER(fullSync);
+ UNUSED_PARAMETER(dataOnly);
+#elif HAVE_FULLFSYNC
+ UNUSED_PARAMETER(dataOnly);
+#else
+ UNUSED_PARAMETER(fullSync);
+ UNUSED_PARAMETER(dataOnly);
+#endif
+
+ /* Record the number of times that we do a normal fsync() and
+ ** FULLSYNC. This is used during testing to verify that this procedure
+ ** gets called with the correct arguments.
+ */
+#ifdef SQLITE_TEST
+ if( fullSync ) sqlite3_fullsync_count++;
+ sqlite3_sync_count++;
+#endif
+
+ /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
+ ** no-op. But go ahead and call fstat() to validate the file
+ ** descriptor as we need a method to provoke a failure during
+ ** coverate testing.
+ */
+#ifdef SQLITE_NO_SYNC
+ {
+ struct stat buf;
+ rc = osFstat(fd, &buf);
+ }
+#elif HAVE_FULLFSYNC
+ if( fullSync ){
+ rc = osFcntl(fd, F_FULLFSYNC, 0);
+ }else{
+ rc = 1;
+ }
+ /* If the FULLFSYNC failed, fall back to attempting an fsync().
+ ** It shouldn't be possible for fullfsync to fail on the local
+ ** file system (on OSX), so failure indicates that FULLFSYNC
+ ** isn't supported for this file system. So, attempt an fsync
+ ** and (for now) ignore the overhead of a superfluous fcntl call.
+ ** It'd be better to detect fullfsync support once and avoid
+ ** the fcntl call every time sync is called.
+ */
+ if( rc ) rc = fsync(fd);
+
+#elif defined(__APPLE__)
+ /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
+ ** so currently we default to the macro that redefines fdatasync to fsync
+ */
+ rc = fsync(fd);
+#else
+ rc = fdatasync(fd);
+#if OS_VXWORKS
+ if( rc==-1 && errno==ENOTSUP ){
+ rc = fsync(fd);
+ }
+#endif /* OS_VXWORKS */
+#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
+
+ if( OS_VXWORKS && rc!= -1 ){
+ rc = 0;
+ }
+ return rc;
+}
+
+/*
+** Open a file descriptor to the directory containing file zFilename.
+** If successful, *pFd is set to the opened file descriptor and
+** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
+** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
+** value.
+**
+** The directory file descriptor is used for only one thing - to
+** fsync() a directory to make sure file creation and deletion events
+** are flushed to disk. Such fsyncs are not needed on newer
+** journaling filesystems, but are required on older filesystems.
+**
+** This routine can be overridden using the xSetSysCall interface.
+** The ability to override this routine was added in support of the
+** chromium sandbox. Opening a directory is a security risk (we are
+** told) so making it overrideable allows the chromium sandbox to
+** replace this routine with a harmless no-op. To make this routine
+** a no-op, replace it with a stub that returns SQLITE_OK but leaves
+** *pFd set to a negative number.
+**
+** If SQLITE_OK is returned, the caller is responsible for closing
+** the file descriptor *pFd using close().
+*/
+static int openDirectory(const char *zFilename, int *pFd){
+ int ii;
+ int fd = -1;
+ char zDirname[MAX_PATHNAME+1];
+
+ sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
+ for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
+ if( ii>0 ){
+ zDirname[ii] = '\0';
+ }else{
+ if( zDirname[0]!='/' ) zDirname[0] = '.';
+ zDirname[1] = 0;
+ }
+ fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
+ if( fd>=0 ){
+ OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
+ }
+ *pFd = fd;
+ if( fd>=0 ) return SQLITE_OK;
+ return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
+}
+
+/*
+** Make sure all writes to a particular file are committed to disk.
+**
+** If dataOnly==0 then both the file itself and its metadata (file
+** size, access time, etc) are synced. If dataOnly!=0 then only the
+** file data is synced.
+**
+** Under Unix, also make sure that the directory entry for the file
+** has been created by fsync-ing the directory that contains the file.
+** If we do not do this and we encounter a power failure, the directory
+** entry for the journal might not exist after we reboot. The next
+** SQLite to access the file will not know that the journal exists (because
+** the directory entry for the journal was never created) and the transaction
+** will not roll back - possibly leading to database corruption.
+*/
+static int unixSync(sqlite3_file *id, int flags){
+ int rc;
+ unixFile *pFile = (unixFile*)id;
+
+ int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
+ int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
+
+ /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
+ assert((flags&0x0F)==SQLITE_SYNC_NORMAL
+ || (flags&0x0F)==SQLITE_SYNC_FULL
+ );
+
+ /* Unix cannot, but some systems may return SQLITE_FULL from here. This
+ ** line is to test that doing so does not cause any problems.
+ */
+ SimulateDiskfullError( return SQLITE_FULL );
+
+ assert( pFile );
+ OSTRACE(("SYNC %-3d\n", pFile->h));
+ rc = full_fsync(pFile->h, isFullsync, isDataOnly);
+ SimulateIOError( rc=1 );
+ if( rc ){
+ storeLastErrno(pFile, errno);
+ return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
+ }
+
+ /* Also fsync the directory containing the file if the DIRSYNC flag
+ ** is set. This is a one-time occurrence. Many systems (examples: AIX)
+ ** are unable to fsync a directory, so ignore errors on the fsync.
+ */
+ if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
+ int dirfd;
+ OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
+ HAVE_FULLFSYNC, isFullsync));
+ rc = osOpenDirectory(pFile->zPath, &dirfd);
+ if( rc==SQLITE_OK ){
+ full_fsync(dirfd, 0, 0);
+ robust_close(pFile, dirfd, __LINE__);
+ }else{
+ assert( rc==SQLITE_CANTOPEN );
+ rc = SQLITE_OK;
+ }
+ pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
+ }
+ return rc;
+}
+
+/*
+** Truncate an open file to a specified size
+*/
+static int unixTruncate(sqlite3_file *id, i64 nByte){
+ unixFile *pFile = (unixFile *)id;
+ int rc;
+ assert( pFile );
+ SimulateIOError( return SQLITE_IOERR_TRUNCATE );
+
+ /* If the user has configured a chunk-size for this file, truncate the
+ ** file so that it consists of an integer number of chunks (i.e. the
+ ** actual file size after the operation may be larger than the requested
+ ** size).
+ */
+ if( pFile->szChunk>0 ){
+ nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
+ }
+
+ rc = robust_ftruncate(pFile->h, nByte);
+ if( rc ){
+ storeLastErrno(pFile, errno);
+ return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
+ }else{
+#ifdef SQLITE_DEBUG
+ /* If we are doing a normal write to a database file (as opposed to
+ ** doing a hot-journal rollback or a write to some file other than a
+ ** normal database file) and we truncate the file to zero length,
+ ** that effectively updates the change counter. This might happen
+ ** when restoring a database using the backup API from a zero-length
+ ** source.
+ */
+ if( pFile->inNormalWrite && nByte==0 ){
+ pFile->transCntrChng = 1;
+ }
+#endif
+
+#if SQLITE_MAX_MMAP_SIZE>0
+ /* If the file was just truncated to a size smaller than the currently
+ ** mapped region, reduce the effective mapping size as well. SQLite will
+ ** use read() and write() to access data beyond this point from now on.
+ */
+ if( nByte<pFile->mmapSize ){
+ pFile->mmapSize = nByte;
+ }
+#endif
+
+ return SQLITE_OK;
+ }
+}
+
+/*
+** Determine the current size of a file in bytes
+*/
+static int unixFileSize(sqlite3_file *id, i64 *pSize){
+ int rc;
+ struct stat buf;
+ assert( id );
+ rc = osFstat(((unixFile*)id)->h, &buf);
+ SimulateIOError( rc=1 );
+ if( rc!=0 ){
+ storeLastErrno((unixFile*)id, errno);
+ return SQLITE_IOERR_FSTAT;
+ }
+ *pSize = buf.st_size;
+
+ /* When opening a zero-size database, the findInodeInfo() procedure
+ ** writes a single byte into that file in order to work around a bug
+ ** in the OS-X msdos filesystem. In order to avoid problems with upper
+ ** layers, we need to report this file size as zero even though it is
+ ** really 1. Ticket #3260.
+ */
+ if( *pSize==1 ) *pSize = 0;
+
+
+ return SQLITE_OK;
+}
+
+#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
+/*
+** Handler for proxy-locking file-control verbs. Defined below in the
+** proxying locking division.
+*/
+static int proxyFileControl(sqlite3_file*,int,void*);
+#endif
+
+/*
+** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
+** file-control operation. Enlarge the database to nBytes in size
+** (rounded up to the next chunk-size). If the database is already
+** nBytes or larger, this routine is a no-op.
+*/
+static int fcntlSizeHint(unixFile *pFile, i64 nByte){
+ if( pFile->szChunk>0 ){
+ i64 nSize; /* Required file size */
+ struct stat buf; /* Used to hold return values of fstat() */
+
+ if( osFstat(pFile->h, &buf) ){
+ return SQLITE_IOERR_FSTAT;
+ }
+
+ nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
+ if( nSize>(i64)buf.st_size ){
+
+#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
+ /* The code below is handling the return value of osFallocate()
+ ** correctly. posix_fallocate() is defined to "returns zero on success,
+ ** or an error number on failure". See the manpage for details. */
+ int err;
+ do{
+ err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
+ }while( err==EINTR );
+ if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
+#else
+ /* If the OS does not have posix_fallocate(), fake it. Write a
+ ** single byte to the last byte in each block that falls entirely
+ ** within the extended region. Then, if required, a single byte
+ ** at offset (nSize-1), to set the size of the file correctly.
+ ** This is a similar technique to that used by glibc on systems
+ ** that do not have a real fallocate() call.
+ */
+ int nBlk = buf.st_blksize; /* File-system block size */
+ int nWrite = 0; /* Number of bytes written by seekAndWrite */
+ i64 iWrite; /* Next offset to write to */
+
+ iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
+ assert( iWrite>=buf.st_size );
+ assert( ((iWrite+1)%nBlk)==0 );
+ for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
+ if( iWrite>=nSize ) iWrite = nSize - 1;
+ nWrite = seekAndWrite(pFile, iWrite, "", 1);
+ if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
+ }
+#endif
+ }
+ }
+
+#if SQLITE_MAX_MMAP_SIZE>0
+ if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
+ int rc;
+ if( pFile->szChunk<=0 ){
+ if( robust_ftruncate(pFile->h, nByte) ){
+ storeLastErrno(pFile, errno);
+ return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
+ }
+ }
+
+ rc = unixMapfile(pFile, nByte);
+ return rc;
+ }
+#endif
+
+ return SQLITE_OK;
+}
+
+/*
+** If *pArg is initially negative then this is a query. Set *pArg to
+** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
+**
+** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
+*/
+static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
+ if( *pArg<0 ){
+ *pArg = (pFile->ctrlFlags & mask)!=0;
+ }else if( (*pArg)==0 ){
+ pFile->ctrlFlags &= ~mask;
+ }else{
+ pFile->ctrlFlags |= mask;
+ }
+}
+
+/* Forward declaration */
+static int unixGetTempname(int nBuf, char *zBuf);
+
+/*
+** Information and control of an open file handle.
+*/
+static int unixFileControl(sqlite3_file *id, int op, void *pArg){
+ unixFile *pFile = (unixFile*)id;
+ switch( op ){
+#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
+ case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
+ int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
+ return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
+ }
+ case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
+ int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
+ return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
+ }
+ case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
+ int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
+ return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
+ }
+#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
+
+ case SQLITE_FCNTL_LOCKSTATE: {
+ *(int*)pArg = pFile->eFileLock;
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_LAST_ERRNO: {
+ *(int*)pArg = pFile->lastErrno;
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_CHUNK_SIZE: {
+ pFile->szChunk = *(int *)pArg;
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_SIZE_HINT: {
+ int rc;
+ SimulateIOErrorBenign(1);
+ rc = fcntlSizeHint(pFile, *(i64 *)pArg);
+ SimulateIOErrorBenign(0);
+ return rc;
+ }
+ case SQLITE_FCNTL_PERSIST_WAL: {
+ unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
+ unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_VFSNAME: {
+ *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_TEMPFILENAME: {
+ char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
+ if( zTFile ){
+ unixGetTempname(pFile->pVfs->mxPathname, zTFile);
+ *(char**)pArg = zTFile;
+ }
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_HAS_MOVED: {
+ *(int*)pArg = fileHasMoved(pFile);
+ return SQLITE_OK;
+ }
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+ case SQLITE_FCNTL_LOCK_TIMEOUT: {
+ int iOld = pFile->iBusyTimeout;
+ pFile->iBusyTimeout = *(int*)pArg;
+ *(int*)pArg = iOld;
+ return SQLITE_OK;
+ }
+#endif
+#if SQLITE_MAX_MMAP_SIZE>0
+ case SQLITE_FCNTL_MMAP_SIZE: {
+ i64 newLimit = *(i64*)pArg;
+ int rc = SQLITE_OK;
+ if( newLimit>sqlite3GlobalConfig.mxMmap ){
+ newLimit = sqlite3GlobalConfig.mxMmap;
+ }
+
+ /* The value of newLimit may be eventually cast to (size_t) and passed
+ ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
+ ** 64-bit type. */
+ if( newLimit>0 && sizeof(size_t)<8 ){
+ newLimit = (newLimit & 0x7FFFFFFF);
+ }
+
+ *(i64*)pArg = pFile->mmapSizeMax;
+ if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
+ pFile->mmapSizeMax = newLimit;
+ if( pFile->mmapSize>0 ){
+ unixUnmapfile(pFile);
+ rc = unixMapfile(pFile, -1);
+ }
+ }
+ return rc;
+ }
+#endif
+#ifdef SQLITE_DEBUG
+ /* The pager calls this method to signal that it has done
+ ** a rollback and that the database is therefore unchanged and
+ ** it hence it is OK for the transaction change counter to be
+ ** unchanged.
+ */
+ case SQLITE_FCNTL_DB_UNCHANGED: {
+ ((unixFile*)id)->dbUpdate = 0;
+ return SQLITE_OK;
+ }
+#endif
+#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
+ case SQLITE_FCNTL_SET_LOCKPROXYFILE:
+ case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
+ return proxyFileControl(id,op,pArg);
+ }
+#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
+ }
+ return SQLITE_NOTFOUND;
+}
+
+/*
+** If pFd->sectorSize is non-zero when this function is called, it is a
+** no-op. Otherwise, the values of pFd->sectorSize and
+** pFd->deviceCharacteristics are set according to the file-system
+** characteristics.
+**
+** There are two versions of this function. One for QNX and one for all
+** other systems.
+*/
+#ifndef __QNXNTO__
+static void setDeviceCharacteristics(unixFile *pFd){
+ assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
+ if( pFd->sectorSize==0 ){
+#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
+ int res;
+ u32 f = 0;
+
+ /* Check for support for F2FS atomic batch writes. */
+ res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
+ if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
+ pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
+ }
+#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
+
+ /* Set the POWERSAFE_OVERWRITE flag if requested. */
+ if( pFd->ctrlFlags & UNIXFILE_PSOW ){
+ pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
+ }
+
+ pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
+ }
+}
+#else
+#include <sys/dcmd_blk.h>
+#include <sys/statvfs.h>
+static void setDeviceCharacteristics(unixFile *pFile){
+ if( pFile->sectorSize == 0 ){
+ struct statvfs fsInfo;
+
+ /* Set defaults for non-supported filesystems */
+ pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
+ pFile->deviceCharacteristics = 0;
+ if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
+ return;
+ }
+
+ if( !strcmp(fsInfo.f_basetype, "tmp") ) {
+ pFile->sectorSize = fsInfo.f_bsize;
+ pFile->deviceCharacteristics =
+ SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
+ SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
+ ** the write succeeds */
+ SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
+ ** so it is ordered */
+ 0;
+ }else if( strstr(fsInfo.f_basetype, "etfs") ){
+ pFile->sectorSize = fsInfo.f_bsize;
+ pFile->deviceCharacteristics =
+ /* etfs cluster size writes are atomic */
+ (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
+ SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
+ ** the write succeeds */
+ SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
+ ** so it is ordered */
+ 0;
+ }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
+ pFile->sectorSize = fsInfo.f_bsize;
+ pFile->deviceCharacteristics =
+ SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
+ SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
+ ** the write succeeds */
+ SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
+ ** so it is ordered */
+ 0;
+ }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
+ pFile->sectorSize = fsInfo.f_bsize;
+ pFile->deviceCharacteristics =
+ /* full bitset of atomics from max sector size and smaller */
+ ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
+ SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
+ ** so it is ordered */
+ 0;
+ }else if( strstr(fsInfo.f_basetype, "dos") ){
+ pFile->sectorSize = fsInfo.f_bsize;
+ pFile->deviceCharacteristics =
+ /* full bitset of atomics from max sector size and smaller */
+ ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
+ SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
+ ** so it is ordered */
+ 0;
+ }else{
+ pFile->deviceCharacteristics =
+ SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
+ SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
+ ** the write succeeds */
+ 0;
+ }
+ }
+ /* Last chance verification. If the sector size isn't a multiple of 512
+ ** then it isn't valid.*/
+ if( pFile->sectorSize % 512 != 0 ){
+ pFile->deviceCharacteristics = 0;
+ pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
+ }
+}
+#endif
+
+/*
+** Return the sector size in bytes of the underlying block device for
+** the specified file. This is almost always 512 bytes, but may be
+** larger for some devices.
+**
+** SQLite code assumes this function cannot fail. It also assumes that
+** if two files are created in the same file-system directory (i.e.
+** a database and its journal file) that the sector size will be the
+** same for both.
+*/
+static int unixSectorSize(sqlite3_file *id){
+ unixFile *pFd = (unixFile*)id;
+ setDeviceCharacteristics(pFd);
+ return pFd->sectorSize;
+}
+
+/*
+** Return the device characteristics for the file.
+**
+** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
+** However, that choice is controversial since technically the underlying
+** file system does not always provide powersafe overwrites. (In other
+** words, after a power-loss event, parts of the file that were never
+** written might end up being altered.) However, non-PSOW behavior is very,
+** very rare. And asserting PSOW makes a large reduction in the amount
+** of required I/O for journaling, since a lot of padding is eliminated.
+** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
+** available to turn it off and URI query parameter available to turn it off.
+*/
+static int unixDeviceCharacteristics(sqlite3_file *id){
+ unixFile *pFd = (unixFile*)id;
+ setDeviceCharacteristics(pFd);
+ return pFd->deviceCharacteristics;
+}
+
+#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
+
+/*
+** Return the system page size.
+**
+** This function should not be called directly by other code in this file.
+** Instead, it should be called via macro osGetpagesize().
+*/
+static int unixGetpagesize(void){
+#if OS_VXWORKS
+ return 1024;
+#elif defined(_BSD_SOURCE)
+ return getpagesize();
+#else
+ return (int)sysconf(_SC_PAGESIZE);
+#endif
+}
+
+#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
+
+#ifndef SQLITE_OMIT_WAL
+
+/*
+** Object used to represent an shared memory buffer.
+**
+** When multiple threads all reference the same wal-index, each thread
+** has its own unixShm object, but they all point to a single instance
+** of this unixShmNode object. In other words, each wal-index is opened
+** only once per process.
+**
+** Each unixShmNode object is connected to a single unixInodeInfo object.
+** We could coalesce this object into unixInodeInfo, but that would mean
+** every open file that does not use shared memory (in other words, most
+** open files) would have to carry around this extra information. So
+** the unixInodeInfo object contains a pointer to this unixShmNode object
+** and the unixShmNode object is created only when needed.
+**
+** unixMutexHeld() must be true when creating or destroying
+** this object or while reading or writing the following fields:
+**
+** nRef
+**
+** The following fields are read-only after the object is created:
+**
+** hShm
+** zFilename
+**
+** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
+** unixMutexHeld() is true when reading or writing any other field
+** in this structure.
+*/
+struct unixShmNode {
+ unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
+ sqlite3_mutex *pShmMutex; /* Mutex to access this object */
+ char *zFilename; /* Name of the mmapped file */
+ int hShm; /* Open file descriptor */
+ int szRegion; /* Size of shared-memory regions */
+ u16 nRegion; /* Size of array apRegion */
+ u8 isReadonly; /* True if read-only */
+ u8 isUnlocked; /* True if no DMS lock held */
+ char **apRegion; /* Array of mapped shared-memory regions */
+ int nRef; /* Number of unixShm objects pointing to this */
+ unixShm *pFirst; /* All unixShm objects pointing to this */
+ int aLock[SQLITE_SHM_NLOCK]; /* # shared locks on slot, -1==excl lock */
+#ifdef SQLITE_DEBUG
+ u8 exclMask; /* Mask of exclusive locks held */
+ u8 sharedMask; /* Mask of shared locks held */
+ u8 nextShmId; /* Next available unixShm.id value */
+#endif
+};
+
+/*
+** Structure used internally by this VFS to record the state of an
+** open shared memory connection.
+**
+** The following fields are initialized when this object is created and
+** are read-only thereafter:
+**
+** unixShm.pShmNode
+** unixShm.id
+**
+** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
+** be held while accessing any read/write fields.
+*/
+struct unixShm {
+ unixShmNode *pShmNode; /* The underlying unixShmNode object */
+ unixShm *pNext; /* Next unixShm with the same unixShmNode */
+ u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
+ u8 id; /* Id of this connection within its unixShmNode */
+ u16 sharedMask; /* Mask of shared locks held */
+ u16 exclMask; /* Mask of exclusive locks held */
+};
+
+/*
+** Constants used for locking
+*/
+#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
+#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
+
+/*
+** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
+**
+** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
+** otherwise.
+*/
+static int unixShmSystemLock(
+ unixFile *pFile, /* Open connection to the WAL file */
+ int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
+ int ofst, /* First byte of the locking range */
+ int n /* Number of bytes to lock */
+){
+ unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
+ struct flock f; /* The posix advisory locking structure */
+ int rc = SQLITE_OK; /* Result code form fcntl() */
+
+ /* Access to the unixShmNode object is serialized by the caller */
+ pShmNode = pFile->pInode->pShmNode;
+ assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
+ assert( pShmNode->nRef>0 || unixMutexHeld() );
+
+ /* Shared locks never span more than one byte */
+ assert( n==1 || lockType!=F_RDLCK );
+
+ /* Locks are within range */
+ assert( n>=1 && n<=SQLITE_SHM_NLOCK );
+
+ if( pShmNode->hShm>=0 ){
+ int res;
+ /* Initialize the locking parameters */
+ f.l_type = lockType;
+ f.l_whence = SEEK_SET;
+ f.l_start = ofst;
+ f.l_len = n;
+ res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
+ if( res==-1 ){
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+ rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY);
+#else
+ rc = SQLITE_BUSY;
+#endif
+ }
+ }
+
+ /* Update the global lock state and do debug tracing */
+#ifdef SQLITE_DEBUG
+ { u16 mask;
+ OSTRACE(("SHM-LOCK "));
+ mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
+ if( rc==SQLITE_OK ){
+ if( lockType==F_UNLCK ){
+ OSTRACE(("unlock %d ok", ofst));
+ pShmNode->exclMask &= ~mask;
+ pShmNode->sharedMask &= ~mask;
+ }else if( lockType==F_RDLCK ){
+ OSTRACE(("read-lock %d ok", ofst));
+ pShmNode->exclMask &= ~mask;
+ pShmNode->sharedMask |= mask;
+ }else{
+ assert( lockType==F_WRLCK );
+ OSTRACE(("write-lock %d ok", ofst));
+ pShmNode->exclMask |= mask;
+ pShmNode->sharedMask &= ~mask;
+ }
+ }else{
+ if( lockType==F_UNLCK ){
+ OSTRACE(("unlock %d failed", ofst));
+ }else if( lockType==F_RDLCK ){
+ OSTRACE(("read-lock failed"));
+ }else{
+ assert( lockType==F_WRLCK );
+ OSTRACE(("write-lock %d failed", ofst));
+ }
+ }
+ OSTRACE((" - afterwards %03x,%03x\n",
+ pShmNode->sharedMask, pShmNode->exclMask));
+ }
+#endif
+
+ return rc;
+}
+
+/*
+** Return the minimum number of 32KB shm regions that should be mapped at
+** a time, assuming that each mapping must be an integer multiple of the
+** current system page-size.
+**
+** Usually, this is 1. The exception seems to be systems that are configured
+** to use 64KB pages - in this case each mapping must cover at least two
+** shm regions.
+*/
+static int unixShmRegionPerMap(void){
+ int shmsz = 32*1024; /* SHM region size */
+ int pgsz = osGetpagesize(); /* System page size */
+ assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
+ if( pgsz<shmsz ) return 1;
+ return pgsz/shmsz;
+}
+
+/*
+** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
+**
+** This is not a VFS shared-memory method; it is a utility function called
+** by VFS shared-memory methods.
+*/
+static void unixShmPurge(unixFile *pFd){
+ unixShmNode *p = pFd->pInode->pShmNode;
+ assert( unixMutexHeld() );
+ if( p && ALWAYS(p->nRef==0) ){
+ int nShmPerMap = unixShmRegionPerMap();
+ int i;
+ assert( p->pInode==pFd->pInode );
+ sqlite3_mutex_free(p->pShmMutex);
+ for(i=0; i<p->nRegion; i+=nShmPerMap){
+ if( p->hShm>=0 ){
+ osMunmap(p->apRegion[i], p->szRegion);
+ }else{
+ sqlite3_free(p->apRegion[i]);
+ }
+ }
+ sqlite3_free(p->apRegion);
+ if( p->hShm>=0 ){
+ robust_close(pFd, p->hShm, __LINE__);
+ p->hShm = -1;
+ }
+ p->pInode->pShmNode = 0;
+ sqlite3_free(p);
+ }
+}
+
+/*
+** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
+** take it now. Return SQLITE_OK if successful, or an SQLite error
+** code otherwise.
+**
+** If the DMS cannot be locked because this is a readonly_shm=1
+** connection and no other process already holds a lock, return
+** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
+*/
+static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
+ struct flock lock;
+ int rc = SQLITE_OK;
+
+ /* Use F_GETLK to determine the locks other processes are holding
+ ** on the DMS byte. If it indicates that another process is holding
+ ** a SHARED lock, then this process may also take a SHARED lock
+ ** and proceed with opening the *-shm file.
+ **
+ ** Or, if no other process is holding any lock, then this process
+ ** is the first to open it. In this case take an EXCLUSIVE lock on the
+ ** DMS byte and truncate the *-shm file to zero bytes in size. Then
+ ** downgrade to a SHARED lock on the DMS byte.
+ **
+ ** If another process is holding an EXCLUSIVE lock on the DMS byte,
+ ** return SQLITE_BUSY to the caller (it will try again). An earlier
+ ** version of this code attempted the SHARED lock at this point. But
+ ** this introduced a subtle race condition: if the process holding
+ ** EXCLUSIVE failed just before truncating the *-shm file, then this
+ ** process might open and use the *-shm file without truncating it.
+ ** And if the *-shm file has been corrupted by a power failure or
+ ** system crash, the database itself may also become corrupt. */
+ lock.l_whence = SEEK_SET;
+ lock.l_start = UNIX_SHM_DMS;
+ lock.l_len = 1;
+ lock.l_type = F_WRLCK;
+ if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
+ rc = SQLITE_IOERR_LOCK;
+ }else if( lock.l_type==F_UNLCK ){
+ if( pShmNode->isReadonly ){
+ pShmNode->isUnlocked = 1;
+ rc = SQLITE_READONLY_CANTINIT;
+ }else{
+ rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
+ /* The first connection to attach must truncate the -shm file. We
+ ** truncate to 3 bytes (an arbitrary small number, less than the
+ ** -shm header size) rather than 0 as a system debugging aid, to
+ ** help detect if a -shm file truncation is legitimate or is the work
+ ** or a rogue process. */
+ if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
+ rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
+ }
+ }
+ }else if( lock.l_type==F_WRLCK ){
+ rc = SQLITE_BUSY;
+ }
+
+ if( rc==SQLITE_OK ){
+ assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
+ rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
+ }
+ return rc;
+}
+
+/*
+** Open a shared-memory area associated with open database file pDbFd.
+** This particular implementation uses mmapped files.
+**
+** The file used to implement shared-memory is in the same directory
+** as the open database file and has the same name as the open database
+** file with the "-shm" suffix added. For example, if the database file
+** is "/home/user1/config.db" then the file that is created and mmapped
+** for shared memory will be called "/home/user1/config.db-shm".
+**
+** Another approach to is to use files in /dev/shm or /dev/tmp or an
+** some other tmpfs mount. But if a file in a different directory
+** from the database file is used, then differing access permissions
+** or a chroot() might cause two different processes on the same
+** database to end up using different files for shared memory -
+** meaning that their memory would not really be shared - resulting
+** in database corruption. Nevertheless, this tmpfs file usage
+** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
+** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
+** option results in an incompatible build of SQLite; builds of SQLite
+** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
+** same database file at the same time, database corruption will likely
+** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
+** "unsupported" and may go away in a future SQLite release.
+**
+** When opening a new shared-memory file, if no other instances of that
+** file are currently open, in this process or in other processes, then
+** the file must be truncated to zero length or have its header cleared.
+**
+** If the original database file (pDbFd) is using the "unix-excl" VFS
+** that means that an exclusive lock is held on the database file and
+** that no other processes are able to read or write the database. In
+** that case, we do not really need shared memory. No shared memory
+** file is created. The shared memory will be simulated with heap memory.
+*/
+static int unixOpenSharedMemory(unixFile *pDbFd){
+ struct unixShm *p = 0; /* The connection to be opened */
+ struct unixShmNode *pShmNode; /* The underlying mmapped file */
+ int rc = SQLITE_OK; /* Result code */
+ unixInodeInfo *pInode; /* The inode of fd */
+ char *zShm; /* Name of the file used for SHM */
+ int nShmFilename; /* Size of the SHM filename in bytes */
+
+ /* Allocate space for the new unixShm object. */
+ p = sqlite3_malloc64( sizeof(*p) );
+ if( p==0 ) return SQLITE_NOMEM_BKPT;
+ memset(p, 0, sizeof(*p));
+ assert( pDbFd->pShm==0 );
+
+ /* Check to see if a unixShmNode object already exists. Reuse an existing
+ ** one if present. Create a new one if necessary.
+ */
+ assert( unixFileMutexNotheld(pDbFd) );
+ unixEnterMutex();
+ pInode = pDbFd->pInode;
+ pShmNode = pInode->pShmNode;
+ if( pShmNode==0 ){
+ struct stat sStat; /* fstat() info for database file */
+#ifndef SQLITE_SHM_DIRECTORY
+ const char *zBasePath = pDbFd->zPath;
+#endif
+
+ /* Call fstat() to figure out the permissions on the database file. If
+ ** a new *-shm file is created, an attempt will be made to create it
+ ** with the same permissions.
+ */
+ if( osFstat(pDbFd->h, &sStat) ){
+ rc = SQLITE_IOERR_FSTAT;
+ goto shm_open_err;
+ }
+
+#ifdef SQLITE_SHM_DIRECTORY
+ nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
+#else
+ nShmFilename = 6 + (int)strlen(zBasePath);
+#endif
+ pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
+ if( pShmNode==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto shm_open_err;
+ }
+ memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
+ zShm = pShmNode->zFilename = (char*)&pShmNode[1];
+#ifdef SQLITE_SHM_DIRECTORY
+ sqlite3_snprintf(nShmFilename, zShm,
+ SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
+ (u32)sStat.st_ino, (u32)sStat.st_dev);
+#else
+ sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
+ sqlite3FileSuffix3(pDbFd->zPath, zShm);
+#endif
+ pShmNode->hShm = -1;
+ pDbFd->pInode->pShmNode = pShmNode;
+ pShmNode->pInode = pDbFd->pInode;
+ if( sqlite3GlobalConfig.bCoreMutex ){
+ pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
+ if( pShmNode->pShmMutex==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto shm_open_err;
+ }
+ }
+
+ if( pInode->bProcessLock==0 ){
+ if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
+ pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,
+ (sStat.st_mode&0777));
+ }
+ if( pShmNode->hShm<0 ){
+ pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW,
+ (sStat.st_mode&0777));
+ if( pShmNode->hShm<0 ){
+ rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
+ goto shm_open_err;
+ }
+ pShmNode->isReadonly = 1;
+ }
+
+ /* If this process is running as root, make sure that the SHM file
+ ** is owned by the same user that owns the original database. Otherwise,
+ ** the original owner will not be able to connect.
+ */
+ robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
+
+ rc = unixLockSharedMemory(pDbFd, pShmNode);
+ if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
+ }
+ }
+
+ /* Make the new connection a child of the unixShmNode */
+ p->pShmNode = pShmNode;
+#ifdef SQLITE_DEBUG
+ p->id = pShmNode->nextShmId++;
+#endif
+ pShmNode->nRef++;
+ pDbFd->pShm = p;
+ unixLeaveMutex();
+
+ /* The reference count on pShmNode has already been incremented under
+ ** the cover of the unixEnterMutex() mutex and the pointer from the
+ ** new (struct unixShm) object to the pShmNode has been set. All that is
+ ** left to do is to link the new object into the linked list starting
+ ** at pShmNode->pFirst. This must be done while holding the
+ ** pShmNode->pShmMutex.
+ */
+ sqlite3_mutex_enter(pShmNode->pShmMutex);
+ p->pNext = pShmNode->pFirst;
+ pShmNode->pFirst = p;
+ sqlite3_mutex_leave(pShmNode->pShmMutex);
+ return rc;
+
+ /* Jump here on any error */
+shm_open_err:
+ unixShmPurge(pDbFd); /* This call frees pShmNode if required */
+ sqlite3_free(p);
+ unixLeaveMutex();
+ return rc;
+}
+
+/*
+** This function is called to obtain a pointer to region iRegion of the
+** shared-memory associated with the database file fd. Shared-memory regions
+** are numbered starting from zero. Each shared-memory region is szRegion
+** bytes in size.
+**
+** If an error occurs, an error code is returned and *pp is set to NULL.
+**
+** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
+** region has not been allocated (by any client, including one running in a
+** separate process), then *pp is set to NULL and SQLITE_OK returned. If
+** bExtend is non-zero and the requested shared-memory region has not yet
+** been allocated, it is allocated by this function.
+**
+** If the shared-memory region has already been allocated or is allocated by
+** this call as described above, then it is mapped into this processes
+** address space (if it is not already), *pp is set to point to the mapped
+** memory and SQLITE_OK returned.
+*/
+static int unixShmMap(
+ sqlite3_file *fd, /* Handle open on database file */
+ int iRegion, /* Region to retrieve */
+ int szRegion, /* Size of regions */
+ int bExtend, /* True to extend file if necessary */
+ void volatile **pp /* OUT: Mapped memory */
+){
+ unixFile *pDbFd = (unixFile*)fd;
+ unixShm *p;
+ unixShmNode *pShmNode;
+ int rc = SQLITE_OK;
+ int nShmPerMap = unixShmRegionPerMap();
+ int nReqRegion;
+
+ /* If the shared-memory file has not yet been opened, open it now. */
+ if( pDbFd->pShm==0 ){
+ rc = unixOpenSharedMemory(pDbFd);
+ if( rc!=SQLITE_OK ) return rc;
+ }
+
+ p = pDbFd->pShm;
+ pShmNode = p->pShmNode;
+ sqlite3_mutex_enter(pShmNode->pShmMutex);
+ if( pShmNode->isUnlocked ){
+ rc = unixLockSharedMemory(pDbFd, pShmNode);
+ if( rc!=SQLITE_OK ) goto shmpage_out;
+ pShmNode->isUnlocked = 0;
+ }
+ assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
+ assert( pShmNode->pInode==pDbFd->pInode );
+ assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
+ assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
+
+ /* Minimum number of regions required to be mapped. */
+ nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
+
+ if( pShmNode->nRegion<nReqRegion ){
+ char **apNew; /* New apRegion[] array */
+ int nByte = nReqRegion*szRegion; /* Minimum required file size */
+ struct stat sStat; /* Used by fstat() */
+
+ pShmNode->szRegion = szRegion;
+
+ if( pShmNode->hShm>=0 ){
+ /* The requested region is not mapped into this processes address space.
+ ** Check to see if it has been allocated (i.e. if the wal-index file is
+ ** large enough to contain the requested region).
+ */
+ if( osFstat(pShmNode->hShm, &sStat) ){
+ rc = SQLITE_IOERR_SHMSIZE;
+ goto shmpage_out;
+ }
+
+ if( sStat.st_size<nByte ){
+ /* The requested memory region does not exist. If bExtend is set to
+ ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
+ */
+ if( !bExtend ){
+ goto shmpage_out;
+ }
+
+ /* Alternatively, if bExtend is true, extend the file. Do this by
+ ** writing a single byte to the end of each (OS) page being
+ ** allocated or extended. Technically, we need only write to the
+ ** last page in order to extend the file. But writing to all new
+ ** pages forces the OS to allocate them immediately, which reduces
+ ** the chances of SIGBUS while accessing the mapped region later on.
+ */
+ else{
+ static const int pgsz = 4096;
+ int iPg;
+
+ /* Write to the last byte of each newly allocated or extended page */
+ assert( (nByte % pgsz)==0 );
+ for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
+ int x = 0;
+ if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
+ const char *zFile = pShmNode->zFilename;
+ rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
+ goto shmpage_out;
+ }
+ }
+ }
+ }
+ }
+
+ /* Map the requested memory region into this processes address space. */
+ apNew = (char **)sqlite3_realloc(
+ pShmNode->apRegion, nReqRegion*sizeof(char *)
+ );
+ if( !apNew ){
+ rc = SQLITE_IOERR_NOMEM_BKPT;
+ goto shmpage_out;
+ }
+ pShmNode->apRegion = apNew;
+ while( pShmNode->nRegion<nReqRegion ){
+ int nMap = szRegion*nShmPerMap;
+ int i;
+ void *pMem;
+ if( pShmNode->hShm>=0 ){
+ pMem = osMmap(0, nMap,
+ pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
+ MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
+ );
+ if( pMem==MAP_FAILED ){
+ rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
+ goto shmpage_out;
+ }
+ }else{
+ pMem = sqlite3_malloc64(nMap);
+ if( pMem==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto shmpage_out;
+ }
+ memset(pMem, 0, nMap);
+ }
+
+ for(i=0; i<nShmPerMap; i++){
+ pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
+ }
+ pShmNode->nRegion += nShmPerMap;
+ }
+ }
+
+shmpage_out:
+ if( pShmNode->nRegion>iRegion ){
+ *pp = pShmNode->apRegion[iRegion];
+ }else{
+ *pp = 0;
+ }
+ if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
+ sqlite3_mutex_leave(pShmNode->pShmMutex);
+ return rc;
+}
+
+/*
+** Check that the pShmNode->aLock[] array comports with the locking bitmasks
+** held by each client. Return true if it does, or false otherwise. This
+** is to be used in an assert(). e.g.
+**
+** assert( assertLockingArrayOk(pShmNode) );
+*/
+#ifdef SQLITE_DEBUG
+static int assertLockingArrayOk(unixShmNode *pShmNode){
+ unixShm *pX;
+ int aLock[SQLITE_SHM_NLOCK];
+ assert( sqlite3_mutex_held(pShmNode->pShmMutex) );
+
+ memset(aLock, 0, sizeof(aLock));
+ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
+ int i;
+ for(i=0; i<SQLITE_SHM_NLOCK; i++){
+ if( pX->exclMask & (1<<i) ){
+ assert( aLock[i]==0 );
+ aLock[i] = -1;
+ }else if( pX->sharedMask & (1<<i) ){
+ assert( aLock[i]>=0 );
+ aLock[i]++;
+ }
+ }
+ }
+
+ assert( 0==memcmp(pShmNode->aLock, aLock, sizeof(aLock)) );
+ return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0);
+}
+#endif
+
+/*
+** Change the lock state for a shared-memory segment.
+**
+** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
+** different here than in posix. In xShmLock(), one can go from unlocked
+** to shared and back or from unlocked to exclusive and back. But one may
+** not go from shared to exclusive or from exclusive to shared.
+*/
+static int unixShmLock(
+ sqlite3_file *fd, /* Database file holding the shared memory */
+ int ofst, /* First lock to acquire or release */
+ int n, /* Number of locks to acquire or release */
+ int flags /* What to do with the lock */
+){
+ unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
+ unixShm *p = pDbFd->pShm; /* The shared memory being locked */
+ unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
+ int rc = SQLITE_OK; /* Result code */
+ u16 mask; /* Mask of locks to take or release */
+ int *aLock = pShmNode->aLock;
+
+ assert( pShmNode==pDbFd->pInode->pShmNode );
+ assert( pShmNode->pInode==pDbFd->pInode );
+ assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
+ assert( n>=1 );
+ assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
+ || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
+ || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
+ || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
+ assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
+ assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
+ assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
+
+ /* Check that, if this to be a blocking lock, no locks that occur later
+ ** in the following list than the lock being obtained are already held:
+ **
+ ** 1. Checkpointer lock (ofst==1).
+ ** 2. Write lock (ofst==0).
+ ** 3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
+ **
+ ** In other words, if this is a blocking lock, none of the locks that
+ ** occur later in the above list than the lock being obtained may be
+ ** held.
+ **
+ ** It is not permitted to block on the RECOVER lock.
+ */
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+ assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
+ (ofst!=2) /* not RECOVER */
+ && (ofst!=1 || (p->exclMask|p->sharedMask)==0)
+ && (ofst!=0 || (p->exclMask|p->sharedMask)<3)
+ && (ofst<3 || (p->exclMask|p->sharedMask)<(1<<ofst))
+ ));
+#endif
+
+ mask = (1<<(ofst+n)) - (1<<ofst);
+ assert( n>1 || mask==(1<<ofst) );
+ sqlite3_mutex_enter(pShmNode->pShmMutex);
+ assert( assertLockingArrayOk(pShmNode) );
+ if( flags & SQLITE_SHM_UNLOCK ){
+ if( (p->exclMask|p->sharedMask) & mask ){
+ int ii;
+ int bUnlock = 1;
+
+ for(ii=ofst; ii<ofst+n; ii++){
+ if( aLock[ii]>((p->sharedMask & (1<<ii)) ? 1 : 0) ){
+ bUnlock = 0;
+ }
+ }
+
+ if( bUnlock ){
+ rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
+ if( rc==SQLITE_OK ){
+ memset(&aLock[ofst], 0, sizeof(int)*n);
+ }
+ }else if( p->sharedMask & (1<<ofst) ){
+ assert( n==1 && aLock[ofst]>1 );
+ aLock[ofst]--;
+ }
+
+ /* Undo the local locks */
+ if( rc==SQLITE_OK ){
+ p->exclMask &= ~mask;
+ p->sharedMask &= ~mask;
+ }
+ }
+ }else if( flags & SQLITE_SHM_SHARED ){
+ assert( n==1 );
+ assert( (p->exclMask & (1<<ofst))==0 );
+ if( (p->sharedMask & mask)==0 ){
+ if( aLock[ofst]<0 ){
+ rc = SQLITE_BUSY;
+ }else if( aLock[ofst]==0 ){
+ rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
+ }
+
+ /* Get the local shared locks */
+ if( rc==SQLITE_OK ){
+ p->sharedMask |= mask;
+ aLock[ofst]++;
+ }
+ }
+ }else{
+ /* Make sure no sibling connections hold locks that will block this
+ ** lock. If any do, return SQLITE_BUSY right away. */
+ int ii;
+ for(ii=ofst; ii<ofst+n; ii++){
+ assert( (p->sharedMask & mask)==0 );
+ if( (p->exclMask & (1<<ii))==0 && aLock[ii] ){
+ rc = SQLITE_BUSY;
+ break;
+ }
+ }
+
+ /* Get the exclusive locks at the system level. Then if successful
+ ** also update the in-memory values. */
+ if( rc==SQLITE_OK ){
+ rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
+ if( rc==SQLITE_OK ){
+ assert( (p->sharedMask & mask)==0 );
+ p->exclMask |= mask;
+ for(ii=ofst; ii<ofst+n; ii++){
+ aLock[ii] = -1;
+ }
+ }
+ }
+ }
+ assert( assertLockingArrayOk(pShmNode) );
+ sqlite3_mutex_leave(pShmNode->pShmMutex);
+ OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
+ p->id, osGetpid(0), p->sharedMask, p->exclMask));
+ return rc;
+}
+
+/*
+** Implement a memory barrier or memory fence on shared memory.
+**
+** All loads and stores begun before the barrier must complete before
+** any load or store begun after the barrier.
+*/
+static void unixShmBarrier(
+ sqlite3_file *fd /* Database file holding the shared memory */
+){
+ UNUSED_PARAMETER(fd);
+ sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
+ assert( fd->pMethods->xLock==nolockLock
+ || unixFileMutexNotheld((unixFile*)fd)
+ );
+ unixEnterMutex(); /* Also mutex, for redundancy */
+ unixLeaveMutex();
+}
+
+/*
+** Close a connection to shared-memory. Delete the underlying
+** storage if deleteFlag is true.
+**
+** If there is no shared memory associated with the connection then this
+** routine is a harmless no-op.
+*/
+static int unixShmUnmap(
+ sqlite3_file *fd, /* The underlying database file */
+ int deleteFlag /* Delete shared-memory if true */
+){
+ unixShm *p; /* The connection to be closed */
+ unixShmNode *pShmNode; /* The underlying shared-memory file */
+ unixShm **pp; /* For looping over sibling connections */
+ unixFile *pDbFd; /* The underlying database file */
+
+ pDbFd = (unixFile*)fd;
+ p = pDbFd->pShm;
+ if( p==0 ) return SQLITE_OK;
+ pShmNode = p->pShmNode;
+
+ assert( pShmNode==pDbFd->pInode->pShmNode );
+ assert( pShmNode->pInode==pDbFd->pInode );
+
+ /* Remove connection p from the set of connections associated
+ ** with pShmNode */
+ sqlite3_mutex_enter(pShmNode->pShmMutex);
+ for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
+ *pp = p->pNext;
+
+ /* Free the connection p */
+ sqlite3_free(p);
+ pDbFd->pShm = 0;
+ sqlite3_mutex_leave(pShmNode->pShmMutex);
+
+ /* If pShmNode->nRef has reached 0, then close the underlying
+ ** shared-memory file, too */
+ assert( unixFileMutexNotheld(pDbFd) );
+ unixEnterMutex();
+ assert( pShmNode->nRef>0 );
+ pShmNode->nRef--;
+ if( pShmNode->nRef==0 ){
+ if( deleteFlag && pShmNode->hShm>=0 ){
+ osUnlink(pShmNode->zFilename);
+ }
+ unixShmPurge(pDbFd);
+ }
+ unixLeaveMutex();
+
+ return SQLITE_OK;
+}
+
+
+#else
+# define unixShmMap 0
+# define unixShmLock 0
+# define unixShmBarrier 0
+# define unixShmUnmap 0
+#endif /* #ifndef SQLITE_OMIT_WAL */
+
+#if SQLITE_MAX_MMAP_SIZE>0
+/*
+** If it is currently memory mapped, unmap file pFd.
+*/
+static void unixUnmapfile(unixFile *pFd){
+ assert( pFd->nFetchOut==0 );
+ if( pFd->pMapRegion ){
+ osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
+ pFd->pMapRegion = 0;
+ pFd->mmapSize = 0;
+ pFd->mmapSizeActual = 0;
+ }
+}
+
+/*
+** Attempt to set the size of the memory mapping maintained by file
+** descriptor pFd to nNew bytes. Any existing mapping is discarded.
+**
+** If successful, this function sets the following variables:
+**
+** unixFile.pMapRegion
+** unixFile.mmapSize
+** unixFile.mmapSizeActual
+**
+** If unsuccessful, an error message is logged via sqlite3_log() and
+** the three variables above are zeroed. In this case SQLite should
+** continue accessing the database using the xRead() and xWrite()
+** methods.
+*/
+static void unixRemapfile(
+ unixFile *pFd, /* File descriptor object */
+ i64 nNew /* Required mapping size */
+){
+ const char *zErr = "mmap";
+ int h = pFd->h; /* File descriptor open on db file */
+ u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
+ i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
+ u8 *pNew = 0; /* Location of new mapping */
+ int flags = PROT_READ; /* Flags to pass to mmap() */
+
+ assert( pFd->nFetchOut==0 );
+ assert( nNew>pFd->mmapSize );
+ assert( nNew<=pFd->mmapSizeMax );
+ assert( nNew>0 );
+ assert( pFd->mmapSizeActual>=pFd->mmapSize );
+ assert( MAP_FAILED!=0 );
+
+#ifdef SQLITE_MMAP_READWRITE
+ if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
+#endif
+
+ if( pOrig ){
+#if HAVE_MREMAP
+ i64 nReuse = pFd->mmapSize;
+#else
+ const int szSyspage = osGetpagesize();
+ i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
+#endif
+ u8 *pReq = &pOrig[nReuse];
+
+ /* Unmap any pages of the existing mapping that cannot be reused. */
+ if( nReuse!=nOrig ){
+ osMunmap(pReq, nOrig-nReuse);
+ }
+
+#if HAVE_MREMAP
+ pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
+ zErr = "mremap";
+#else
+ pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
+ if( pNew!=MAP_FAILED ){
+ if( pNew!=pReq ){
+ osMunmap(pNew, nNew - nReuse);
+ pNew = 0;
+ }else{
+ pNew = pOrig;
+ }
+ }
+#endif
+
+ /* The attempt to extend the existing mapping failed. Free it. */
+ if( pNew==MAP_FAILED || pNew==0 ){
+ osMunmap(pOrig, nReuse);
+ }
+ }
+
+ /* If pNew is still NULL, try to create an entirely new mapping. */
+ if( pNew==0 ){
+ pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
+ }
+
+ if( pNew==MAP_FAILED ){
+ pNew = 0;
+ nNew = 0;
+ unixLogError(SQLITE_OK, zErr, pFd->zPath);
+
+ /* If the mmap() above failed, assume that all subsequent mmap() calls
+ ** will probably fail too. Fall back to using xRead/xWrite exclusively
+ ** in this case. */
+ pFd->mmapSizeMax = 0;
+ }
+ pFd->pMapRegion = (void *)pNew;
+ pFd->mmapSize = pFd->mmapSizeActual = nNew;
+}
+
+/*
+** Memory map or remap the file opened by file-descriptor pFd (if the file
+** is already mapped, the existing mapping is replaced by the new). Or, if
+** there already exists a mapping for this file, and there are still
+** outstanding xFetch() references to it, this function is a no-op.
+**
+** If parameter nByte is non-negative, then it is the requested size of
+** the mapping to create. Otherwise, if nByte is less than zero, then the
+** requested size is the size of the file on disk. The actual size of the
+** created mapping is either the requested size or the value configured
+** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
+**
+** SQLITE_OK is returned if no error occurs (even if the mapping is not
+** recreated as a result of outstanding references) or an SQLite error
+** code otherwise.
+*/
+static int unixMapfile(unixFile *pFd, i64 nMap){
+ assert( nMap>=0 || pFd->nFetchOut==0 );
+ assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
+ if( pFd->nFetchOut>0 ) return SQLITE_OK;
+
+ if( nMap<0 ){
+ struct stat statbuf; /* Low-level file information */
+ if( osFstat(pFd->h, &statbuf) ){
+ return SQLITE_IOERR_FSTAT;
+ }
+ nMap = statbuf.st_size;
+ }
+ if( nMap>pFd->mmapSizeMax ){
+ nMap = pFd->mmapSizeMax;
+ }
+
+ assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
+ if( nMap!=pFd->mmapSize ){
+ unixRemapfile(pFd, nMap);
+ }
+
+ return SQLITE_OK;
+}
+#endif /* SQLITE_MAX_MMAP_SIZE>0 */
+
+/*
+** If possible, return a pointer to a mapping of file fd starting at offset
+** iOff. The mapping must be valid for at least nAmt bytes.
+**
+** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
+** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
+** Finally, if an error does occur, return an SQLite error code. The final
+** value of *pp is undefined in this case.
+**
+** If this function does return a pointer, the caller must eventually
+** release the reference by calling unixUnfetch().
+*/
+static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
+#if SQLITE_MAX_MMAP_SIZE>0
+ unixFile *pFd = (unixFile *)fd; /* The underlying database file */
+#endif
+ *pp = 0;
+
+#if SQLITE_MAX_MMAP_SIZE>0
+ if( pFd->mmapSizeMax>0 ){
+ if( pFd->pMapRegion==0 ){
+ int rc = unixMapfile(pFd, -1);
+ if( rc!=SQLITE_OK ) return rc;
+ }
+ if( pFd->mmapSize >= iOff+nAmt ){
+ *pp = &((u8 *)pFd->pMapRegion)[iOff];
+ pFd->nFetchOut++;
+ }
+ }
+#endif
+ return SQLITE_OK;
+}
+
+/*
+** If the third argument is non-NULL, then this function releases a
+** reference obtained by an earlier call to unixFetch(). The second
+** argument passed to this function must be the same as the corresponding
+** argument that was passed to the unixFetch() invocation.
+**
+** Or, if the third argument is NULL, then this function is being called
+** to inform the VFS layer that, according to POSIX, any existing mapping
+** may now be invalid and should be unmapped.
+*/
+static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
+#if SQLITE_MAX_MMAP_SIZE>0
+ unixFile *pFd = (unixFile *)fd; /* The underlying database file */
+ UNUSED_PARAMETER(iOff);
+
+ /* If p==0 (unmap the entire file) then there must be no outstanding
+ ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
+ ** then there must be at least one outstanding. */
+ assert( (p==0)==(pFd->nFetchOut==0) );
+
+ /* If p!=0, it must match the iOff value. */
+ assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
+
+ if( p ){
+ pFd->nFetchOut--;
+ }else{
+ unixUnmapfile(pFd);
+ }
+
+ assert( pFd->nFetchOut>=0 );
+#else
+ UNUSED_PARAMETER(fd);
+ UNUSED_PARAMETER(p);
+ UNUSED_PARAMETER(iOff);
+#endif
+ return SQLITE_OK;
+}
+
+/*
+** Here ends the implementation of all sqlite3_file methods.
+**
+********************** End sqlite3_file Methods *******************************
+******************************************************************************/
+
+/*
+** This division contains definitions of sqlite3_io_methods objects that
+** implement various file locking strategies. It also contains definitions
+** of "finder" functions. A finder-function is used to locate the appropriate
+** sqlite3_io_methods object for a particular database file. The pAppData
+** field of the sqlite3_vfs VFS objects are initialized to be pointers to
+** the correct finder-function for that VFS.
+**
+** Most finder functions return a pointer to a fixed sqlite3_io_methods
+** object. The only interesting finder-function is autolockIoFinder, which
+** looks at the filesystem type and tries to guess the best locking
+** strategy from that.
+**
+** For finder-function F, two objects are created:
+**
+** (1) The real finder-function named "FImpt()".
+**
+** (2) A constant pointer to this function named just "F".
+**
+**
+** A pointer to the F pointer is used as the pAppData value for VFS
+** objects. We have to do this instead of letting pAppData point
+** directly at the finder-function since C90 rules prevent a void*
+** from be cast into a function pointer.
+**
+**
+** Each instance of this macro generates two objects:
+**
+** * A constant sqlite3_io_methods object call METHOD that has locking
+** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
+**
+** * An I/O method finder function called FINDER that returns a pointer
+** to the METHOD object in the previous bullet.
+*/
+#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
+static const sqlite3_io_methods METHOD = { \
+ VERSION, /* iVersion */ \
+ CLOSE, /* xClose */ \
+ unixRead, /* xRead */ \
+ unixWrite, /* xWrite */ \
+ unixTruncate, /* xTruncate */ \
+ unixSync, /* xSync */ \
+ unixFileSize, /* xFileSize */ \
+ LOCK, /* xLock */ \
+ UNLOCK, /* xUnlock */ \
+ CKLOCK, /* xCheckReservedLock */ \
+ unixFileControl, /* xFileControl */ \
+ unixSectorSize, /* xSectorSize */ \
+ unixDeviceCharacteristics, /* xDeviceCapabilities */ \
+ SHMMAP, /* xShmMap */ \
+ unixShmLock, /* xShmLock */ \
+ unixShmBarrier, /* xShmBarrier */ \
+ unixShmUnmap, /* xShmUnmap */ \
+ unixFetch, /* xFetch */ \
+ unixUnfetch, /* xUnfetch */ \
+}; \
+static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
+ UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
+ return &METHOD; \
+} \
+static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
+ = FINDER##Impl;
+
+/*
+** Here are all of the sqlite3_io_methods objects for each of the
+** locking strategies. Functions that return pointers to these methods
+** are also created.
+*/
+IOMETHODS(
+ posixIoFinder, /* Finder function name */
+ posixIoMethods, /* sqlite3_io_methods object name */
+ 3, /* shared memory and mmap are enabled */
+ unixClose, /* xClose method */
+ unixLock, /* xLock method */
+ unixUnlock, /* xUnlock method */
+ unixCheckReservedLock, /* xCheckReservedLock method */
+ unixShmMap /* xShmMap method */
+)
+IOMETHODS(
+ nolockIoFinder, /* Finder function name */
+ nolockIoMethods, /* sqlite3_io_methods object name */
+ 3, /* shared memory and mmap are enabled */
+ nolockClose, /* xClose method */
+ nolockLock, /* xLock method */
+ nolockUnlock, /* xUnlock method */
+ nolockCheckReservedLock, /* xCheckReservedLock method */
+ 0 /* xShmMap method */
+)
+IOMETHODS(
+ dotlockIoFinder, /* Finder function name */
+ dotlockIoMethods, /* sqlite3_io_methods object name */
+ 1, /* shared memory is disabled */
+ dotlockClose, /* xClose method */
+ dotlockLock, /* xLock method */
+ dotlockUnlock, /* xUnlock method */
+ dotlockCheckReservedLock, /* xCheckReservedLock method */
+ 0 /* xShmMap method */
+)
+
+#if SQLITE_ENABLE_LOCKING_STYLE
+IOMETHODS(
+ flockIoFinder, /* Finder function name */
+ flockIoMethods, /* sqlite3_io_methods object name */
+ 1, /* shared memory is disabled */
+ flockClose, /* xClose method */
+ flockLock, /* xLock method */
+ flockUnlock, /* xUnlock method */
+ flockCheckReservedLock, /* xCheckReservedLock method */
+ 0 /* xShmMap method */
+)
+#endif
+
+#if OS_VXWORKS
+IOMETHODS(
+ semIoFinder, /* Finder function name */
+ semIoMethods, /* sqlite3_io_methods object name */
+ 1, /* shared memory is disabled */
+ semXClose, /* xClose method */
+ semXLock, /* xLock method */
+ semXUnlock, /* xUnlock method */
+ semXCheckReservedLock, /* xCheckReservedLock method */
+ 0 /* xShmMap method */
+)
+#endif
+
+#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
+IOMETHODS(
+ afpIoFinder, /* Finder function name */
+ afpIoMethods, /* sqlite3_io_methods object name */
+ 1, /* shared memory is disabled */
+ afpClose, /* xClose method */
+ afpLock, /* xLock method */
+ afpUnlock, /* xUnlock method */
+ afpCheckReservedLock, /* xCheckReservedLock method */
+ 0 /* xShmMap method */
+)
+#endif
+
+/*
+** The proxy locking method is a "super-method" in the sense that it
+** opens secondary file descriptors for the conch and lock files and
+** it uses proxy, dot-file, AFP, and flock() locking methods on those
+** secondary files. For this reason, the division that implements
+** proxy locking is located much further down in the file. But we need
+** to go ahead and define the sqlite3_io_methods and finder function
+** for proxy locking here. So we forward declare the I/O methods.
+*/
+#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
+static int proxyClose(sqlite3_file*);
+static int proxyLock(sqlite3_file*, int);
+static int proxyUnlock(sqlite3_file*, int);
+static int proxyCheckReservedLock(sqlite3_file*, int*);
+IOMETHODS(
+ proxyIoFinder, /* Finder function name */
+ proxyIoMethods, /* sqlite3_io_methods object name */
+ 1, /* shared memory is disabled */
+ proxyClose, /* xClose method */
+ proxyLock, /* xLock method */
+ proxyUnlock, /* xUnlock method */
+ proxyCheckReservedLock, /* xCheckReservedLock method */
+ 0 /* xShmMap method */
+)
+#endif
+
+/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
+#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
+IOMETHODS(
+ nfsIoFinder, /* Finder function name */
+ nfsIoMethods, /* sqlite3_io_methods object name */
+ 1, /* shared memory is disabled */
+ unixClose, /* xClose method */
+ unixLock, /* xLock method */
+ nfsUnlock, /* xUnlock method */
+ unixCheckReservedLock, /* xCheckReservedLock method */
+ 0 /* xShmMap method */
+)
+#endif
+
+#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
+/*
+** This "finder" function attempts to determine the best locking strategy
+** for the database file "filePath". It then returns the sqlite3_io_methods
+** object that implements that strategy.
+**
+** This is for MacOSX only.
+*/
+static const sqlite3_io_methods *autolockIoFinderImpl(
+ const char *filePath, /* name of the database file */
+ unixFile *pNew /* open file object for the database file */
+){
+ static const struct Mapping {
+ const char *zFilesystem; /* Filesystem type name */
+ const sqlite3_io_methods *pMethods; /* Appropriate locking method */
+ } aMap[] = {
+ { "hfs", &posixIoMethods },
+ { "ufs", &posixIoMethods },
+ { "afpfs", &afpIoMethods },
+ { "smbfs", &afpIoMethods },
+ { "webdav", &nolockIoMethods },
+ { 0, 0 }
+ };
+ int i;
+ struct statfs fsInfo;
+ struct flock lockInfo;
+
+ if( !filePath ){
+ /* If filePath==NULL that means we are dealing with a transient file
+ ** that does not need to be locked. */
+ return &nolockIoMethods;
+ }
+ if( statfs(filePath, &fsInfo) != -1 ){
+ if( fsInfo.f_flags & MNT_RDONLY ){
+ return &nolockIoMethods;
+ }
+ for(i=0; aMap[i].zFilesystem; i++){
+ if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
+ return aMap[i].pMethods;
+ }
+ }
+ }
+
+ /* Default case. Handles, amongst others, "nfs".
+ ** Test byte-range lock using fcntl(). If the call succeeds,
+ ** assume that the file-system supports POSIX style locks.
+ */
+ lockInfo.l_len = 1;
+ lockInfo.l_start = 0;
+ lockInfo.l_whence = SEEK_SET;
+ lockInfo.l_type = F_RDLCK;
+ if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
+ if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
+ return &nfsIoMethods;
+ } else {
+ return &posixIoMethods;
+ }
+ }else{
+ return &dotlockIoMethods;
+ }
+}
+static const sqlite3_io_methods
+ *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
+
+#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
+
+#if OS_VXWORKS
+/*
+** This "finder" function for VxWorks checks to see if posix advisory
+** locking works. If it does, then that is what is used. If it does not
+** work, then fallback to named semaphore locking.
+*/
+static const sqlite3_io_methods *vxworksIoFinderImpl(
+ const char *filePath, /* name of the database file */
+ unixFile *pNew /* the open file object */
+){
+ struct flock lockInfo;
+
+ if( !filePath ){
+ /* If filePath==NULL that means we are dealing with a transient file
+ ** that does not need to be locked. */
+ return &nolockIoMethods;
+ }
+
+ /* Test if fcntl() is supported and use POSIX style locks.
+ ** Otherwise fall back to the named semaphore method.
+ */
+ lockInfo.l_len = 1;
+ lockInfo.l_start = 0;
+ lockInfo.l_whence = SEEK_SET;
+ lockInfo.l_type = F_RDLCK;
+ if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
+ return &posixIoMethods;
+ }else{
+ return &semIoMethods;
+ }
+}
+static const sqlite3_io_methods
+ *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
+
+#endif /* OS_VXWORKS */
+
+/*
+** An abstract type for a pointer to an IO method finder function:
+*/
+typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
+
+
+/****************************************************************************
+**************************** sqlite3_vfs methods ****************************
+**
+** This division contains the implementation of methods on the
+** sqlite3_vfs object.
+*/
+
+/*
+** Initialize the contents of the unixFile structure pointed to by pId.
+*/
+static int fillInUnixFile(
+ sqlite3_vfs *pVfs, /* Pointer to vfs object */
+ int h, /* Open file descriptor of file being opened */
+ sqlite3_file *pId, /* Write to the unixFile structure here */
+ const char *zFilename, /* Name of the file being opened */
+ int ctrlFlags /* Zero or more UNIXFILE_* values */
+){
+ const sqlite3_io_methods *pLockingStyle;
+ unixFile *pNew = (unixFile *)pId;
+ int rc = SQLITE_OK;
+
+ assert( pNew->pInode==NULL );
+
+ /* No locking occurs in temporary files */
+ assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
+
+ OSTRACE(("OPEN %-3d %s\n", h, zFilename));
+ pNew->h = h;
+ pNew->pVfs = pVfs;
+ pNew->zPath = zFilename;
+ pNew->ctrlFlags = (u8)ctrlFlags;
+#if SQLITE_MAX_MMAP_SIZE>0
+ pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
+#endif
+ if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
+ "psow", SQLITE_POWERSAFE_OVERWRITE) ){
+ pNew->ctrlFlags |= UNIXFILE_PSOW;
+ }
+ if( strcmp(pVfs->zName,"unix-excl")==0 ){
+ pNew->ctrlFlags |= UNIXFILE_EXCL;
+ }
+
+#if OS_VXWORKS
+ pNew->pId = vxworksFindFileId(zFilename);
+ if( pNew->pId==0 ){
+ ctrlFlags |= UNIXFILE_NOLOCK;
+ rc = SQLITE_NOMEM_BKPT;
+ }
+#endif
+
+ if( ctrlFlags & UNIXFILE_NOLOCK ){
+ pLockingStyle = &nolockIoMethods;
+ }else{
+ pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
+#if SQLITE_ENABLE_LOCKING_STYLE
+ /* Cache zFilename in the locking context (AFP and dotlock override) for
+ ** proxyLock activation is possible (remote proxy is based on db name)
+ ** zFilename remains valid until file is closed, to support */
+ pNew->lockingContext = (void*)zFilename;
+#endif
+ }
+
+ if( pLockingStyle == &posixIoMethods
+#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
+ || pLockingStyle == &nfsIoMethods
+#endif
+ ){
+ unixEnterMutex();
+ rc = findInodeInfo(pNew, &pNew->pInode);
+ if( rc!=SQLITE_OK ){
+ /* If an error occurred in findInodeInfo(), close the file descriptor
+ ** immediately, before releasing the mutex. findInodeInfo() may fail
+ ** in two scenarios:
+ **
+ ** (a) A call to fstat() failed.
+ ** (b) A malloc failed.
+ **
+ ** Scenario (b) may only occur if the process is holding no other
+ ** file descriptors open on the same file. If there were other file
+ ** descriptors on this file, then no malloc would be required by
+ ** findInodeInfo(). If this is the case, it is quite safe to close
+ ** handle h - as it is guaranteed that no posix locks will be released
+ ** by doing so.
+ **
+ ** If scenario (a) caused the error then things are not so safe. The
+ ** implicit assumption here is that if fstat() fails, things are in
+ ** such bad shape that dropping a lock or two doesn't matter much.
+ */
+ robust_close(pNew, h, __LINE__);
+ h = -1;
+ }
+ unixLeaveMutex();
+ }
+
+#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
+ else if( pLockingStyle == &afpIoMethods ){
+ /* AFP locking uses the file path so it needs to be included in
+ ** the afpLockingContext.
+ */
+ afpLockingContext *pCtx;
+ pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
+ if( pCtx==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ }else{
+ /* NB: zFilename exists and remains valid until the file is closed
+ ** according to requirement F11141. So we do not need to make a
+ ** copy of the filename. */
+ pCtx->dbPath = zFilename;
+ pCtx->reserved = 0;
+ srandomdev();
+ unixEnterMutex();
+ rc = findInodeInfo(pNew, &pNew->pInode);
+ if( rc!=SQLITE_OK ){
+ sqlite3_free(pNew->lockingContext);
+ robust_close(pNew, h, __LINE__);
+ h = -1;
+ }
+ unixLeaveMutex();
+ }
+ }
+#endif
+
+ else if( pLockingStyle == &dotlockIoMethods ){
+ /* Dotfile locking uses the file path so it needs to be included in
+ ** the dotlockLockingContext
+ */
+ char *zLockFile;
+ int nFilename;
+ assert( zFilename!=0 );
+ nFilename = (int)strlen(zFilename) + 6;
+ zLockFile = (char *)sqlite3_malloc64(nFilename);
+ if( zLockFile==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ }else{
+ sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
+ }
+ pNew->lockingContext = zLockFile;
+ }
+
+#if OS_VXWORKS
+ else if( pLockingStyle == &semIoMethods ){
+ /* Named semaphore locking uses the file path so it needs to be
+ ** included in the semLockingContext
+ */
+ unixEnterMutex();
+ rc = findInodeInfo(pNew, &pNew->pInode);
+ if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
+ char *zSemName = pNew->pInode->aSemName;
+ int n;
+ sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
+ pNew->pId->zCanonicalName);
+ for( n=1; zSemName[n]; n++ )
+ if( zSemName[n]=='/' ) zSemName[n] = '_';
+ pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
+ if( pNew->pInode->pSem == SEM_FAILED ){
+ rc = SQLITE_NOMEM_BKPT;
+ pNew->pInode->aSemName[0] = '\0';
+ }
+ }
+ unixLeaveMutex();
+ }
+#endif
+
+ storeLastErrno(pNew, 0);
+#if OS_VXWORKS
+ if( rc!=SQLITE_OK ){
+ if( h>=0 ) robust_close(pNew, h, __LINE__);
+ h = -1;
+ osUnlink(zFilename);
+ pNew->ctrlFlags |= UNIXFILE_DELETE;
+ }
+#endif
+ if( rc!=SQLITE_OK ){
+ if( h>=0 ) robust_close(pNew, h, __LINE__);
+ }else{
+ pId->pMethods = pLockingStyle;
+ OpenCounter(+1);
+ verifyDbFile(pNew);
+ }
+ return rc;
+}
+
+/*
+** Return the name of a directory in which to put temporary files.
+** If no suitable temporary file directory can be found, return NULL.
+*/
+static const char *unixTempFileDir(void){
+ static const char *azDirs[] = {
+ 0,
+ 0,
+ "/var/tmp",
+ "/usr/tmp",
+ "/tmp",
+ "."
+ };
+ unsigned int i = 0;
+ struct stat buf;
+ const char *zDir = sqlite3_temp_directory;
+
+ if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
+ if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
+ while(1){
+ if( zDir!=0
+ && osStat(zDir, &buf)==0
+ && S_ISDIR(buf.st_mode)
+ && osAccess(zDir, 03)==0
+ ){
+ return zDir;
+ }
+ if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
+ zDir = azDirs[i++];
+ }
+ return 0;
+}
+
+/*
+** Create a temporary file name in zBuf. zBuf must be allocated
+** by the calling process and must be big enough to hold at least
+** pVfs->mxPathname bytes.
+*/
+static int unixGetTempname(int nBuf, char *zBuf){
+ const char *zDir;
+ int iLimit = 0;
+
+ /* It's odd to simulate an io-error here, but really this is just
+ ** using the io-error infrastructure to test that SQLite handles this
+ ** function failing.
+ */
+ zBuf[0] = 0;
+ SimulateIOError( return SQLITE_IOERR );
+
+ zDir = unixTempFileDir();
+ if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
+ do{
+ u64 r;
+ sqlite3_randomness(sizeof(r), &r);
+ assert( nBuf>2 );
+ zBuf[nBuf-2] = 0;
+ sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
+ zDir, r, 0);
+ if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
+ }while( osAccess(zBuf,0)==0 );
+ return SQLITE_OK;
+}
+
+#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
+/*
+** Routine to transform a unixFile into a proxy-locking unixFile.
+** Implementation in the proxy-lock division, but used by unixOpen()
+** if SQLITE_PREFER_PROXY_LOCKING is defined.
+*/
+static int proxyTransformUnixFile(unixFile*, const char*);
+#endif
+
+/*
+** Search for an unused file descriptor that was opened on the database
+** file (not a journal or super-journal file) identified by pathname
+** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
+** argument to this function.
+**
+** Such a file descriptor may exist if a database connection was closed
+** but the associated file descriptor could not be closed because some
+** other file descriptor open on the same file is holding a file-lock.
+** Refer to comments in the unixClose() function and the lengthy comment
+** describing "Posix Advisory Locking" at the start of this file for
+** further details. Also, ticket #4018.
+**
+** If a suitable file descriptor is found, then it is returned. If no
+** such file descriptor is located, -1 is returned.
+*/
+static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
+ UnixUnusedFd *pUnused = 0;
+
+ /* Do not search for an unused file descriptor on vxworks. Not because
+ ** vxworks would not benefit from the change (it might, we're not sure),
+ ** but because no way to test it is currently available. It is better
+ ** not to risk breaking vxworks support for the sake of such an obscure
+ ** feature. */
+#if !OS_VXWORKS
+ struct stat sStat; /* Results of stat() call */
+
+ unixEnterMutex();
+
+ /* A stat() call may fail for various reasons. If this happens, it is
+ ** almost certain that an open() call on the same path will also fail.
+ ** For this reason, if an error occurs in the stat() call here, it is
+ ** ignored and -1 is returned. The caller will try to open a new file
+ ** descriptor on the same path, fail, and return an error to SQLite.
+ **
+ ** Even if a subsequent open() call does succeed, the consequences of
+ ** not searching for a reusable file descriptor are not dire. */
+ if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
+ unixInodeInfo *pInode;
+
+ pInode = inodeList;
+ while( pInode && (pInode->fileId.dev!=sStat.st_dev
+ || pInode->fileId.ino!=(u64)sStat.st_ino) ){
+ pInode = pInode->pNext;
+ }
+ if( pInode ){
+ UnixUnusedFd **pp;
+ assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
+ sqlite3_mutex_enter(pInode->pLockMutex);
+ flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
+ for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
+ pUnused = *pp;
+ if( pUnused ){
+ *pp = pUnused->pNext;
+ }
+ sqlite3_mutex_leave(pInode->pLockMutex);
+ }
+ }
+ unixLeaveMutex();
+#endif /* if !OS_VXWORKS */
+ return pUnused;
+}
+
+/*
+** Find the mode, uid and gid of file zFile.
+*/
+static int getFileMode(
+ const char *zFile, /* File name */
+ mode_t *pMode, /* OUT: Permissions of zFile */
+ uid_t *pUid, /* OUT: uid of zFile. */
+ gid_t *pGid /* OUT: gid of zFile. */
+){
+ struct stat sStat; /* Output of stat() on database file */
+ int rc = SQLITE_OK;
+ if( 0==osStat(zFile, &sStat) ){
+ *pMode = sStat.st_mode & 0777;
+ *pUid = sStat.st_uid;
+ *pGid = sStat.st_gid;
+ }else{
+ rc = SQLITE_IOERR_FSTAT;
+ }
+ return rc;
+}
+
+/*
+** This function is called by unixOpen() to determine the unix permissions
+** to create new files with. If no error occurs, then SQLITE_OK is returned
+** and a value suitable for passing as the third argument to open(2) is
+** written to *pMode. If an IO error occurs, an SQLite error code is
+** returned and the value of *pMode is not modified.
+**
+** In most cases, this routine sets *pMode to 0, which will become
+** an indication to robust_open() to create the file using
+** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
+** But if the file being opened is a WAL or regular journal file, then
+** this function queries the file-system for the permissions on the
+** corresponding database file and sets *pMode to this value. Whenever
+** possible, WAL and journal files are created using the same permissions
+** as the associated database file.
+**
+** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
+** original filename is unavailable. But 8_3_NAMES is only used for
+** FAT filesystems and permissions do not matter there, so just use
+** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero.
+*/
+static int findCreateFileMode(
+ const char *zPath, /* Path of file (possibly) being created */
+ int flags, /* Flags passed as 4th argument to xOpen() */
+ mode_t *pMode, /* OUT: Permissions to open file with */
+ uid_t *pUid, /* OUT: uid to set on the file */
+ gid_t *pGid /* OUT: gid to set on the file */
+){
+ int rc = SQLITE_OK; /* Return Code */
+ *pMode = 0;
+ *pUid = 0;
+ *pGid = 0;
+ if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
+ char zDb[MAX_PATHNAME+1]; /* Database file path */
+ int nDb; /* Number of valid bytes in zDb */
+
+ /* zPath is a path to a WAL or journal file. The following block derives
+ ** the path to the associated database file from zPath. This block handles
+ ** the following naming conventions:
+ **
+ ** "<path to db>-journal"
+ ** "<path to db>-wal"
+ ** "<path to db>-journalNN"
+ ** "<path to db>-walNN"
+ **
+ ** where NN is a decimal number. The NN naming schemes are
+ ** used by the test_multiplex.c module.
+ */
+ nDb = sqlite3Strlen30(zPath) - 1;
+ while( zPath[nDb]!='-' ){
+ /* In normal operation, the journal file name will always contain
+ ** a '-' character. However in 8+3 filename mode, or if a corrupt
+ ** rollback journal specifies a super-journal with a goofy name, then
+ ** the '-' might be missing. */
+ if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
+ nDb--;
+ }
+ memcpy(zDb, zPath, nDb);
+ zDb[nDb] = '\0';
+
+ rc = getFileMode(zDb, pMode, pUid, pGid);
+ }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
+ *pMode = 0600;
+ }else if( flags & SQLITE_OPEN_URI ){
+ /* If this is a main database file and the file was opened using a URI
+ ** filename, check for the "modeof" parameter. If present, interpret
+ ** its value as a filename and try to copy the mode, uid and gid from
+ ** that file. */
+ const char *z = sqlite3_uri_parameter(zPath, "modeof");
+ if( z ){
+ rc = getFileMode(z, pMode, pUid, pGid);
+ }
+ }
+ return rc;
+}
+
+/*
+** Open the file zPath.
+**
+** Previously, the SQLite OS layer used three functions in place of this
+** one:
+**
+** sqlite3OsOpenReadWrite();
+** sqlite3OsOpenReadOnly();
+** sqlite3OsOpenExclusive();
+**
+** These calls correspond to the following combinations of flags:
+**
+** ReadWrite() -> (READWRITE | CREATE)
+** ReadOnly() -> (READONLY)
+** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
+**
+** The old OpenExclusive() accepted a boolean argument - "delFlag". If
+** true, the file was configured to be automatically deleted when the
+** file handle closed. To achieve the same effect using this new
+** interface, add the DELETEONCLOSE flag to those specified above for
+** OpenExclusive().
+*/
+static int unixOpen(
+ sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
+ const char *zPath, /* Pathname of file to be opened */
+ sqlite3_file *pFile, /* The file descriptor to be filled in */
+ int flags, /* Input flags to control the opening */
+ int *pOutFlags /* Output flags returned to SQLite core */
+){
+ unixFile *p = (unixFile *)pFile;
+ int fd = -1; /* File descriptor returned by open() */
+ int openFlags = 0; /* Flags to pass to open() */
+ int eType = flags&0x0FFF00; /* Type of file to open */
+ int noLock; /* True to omit locking primitives */
+ int rc = SQLITE_OK; /* Function Return Code */
+ int ctrlFlags = 0; /* UNIXFILE_* flags */
+
+ int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
+ int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
+ int isCreate = (flags & SQLITE_OPEN_CREATE);
+ int isReadonly = (flags & SQLITE_OPEN_READONLY);
+ int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
+#if SQLITE_ENABLE_LOCKING_STYLE
+ int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
+#endif
+#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
+ struct statfs fsInfo;
+#endif
+
+ /* If creating a super- or main-file journal, this function will open
+ ** a file-descriptor on the directory too. The first time unixSync()
+ ** is called the directory file descriptor will be fsync()ed and close()d.
+ */
+ int isNewJrnl = (isCreate && (
+ eType==SQLITE_OPEN_SUPER_JOURNAL
+ || eType==SQLITE_OPEN_MAIN_JOURNAL
+ || eType==SQLITE_OPEN_WAL
+ ));
+
+ /* If argument zPath is a NULL pointer, this function is required to open
+ ** a temporary file. Use this buffer to store the file name in.
+ */
+ char zTmpname[MAX_PATHNAME+2];
+ const char *zName = zPath;
+
+ /* Check the following statements are true:
+ **
+ ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
+ ** (b) if CREATE is set, then READWRITE must also be set, and
+ ** (c) if EXCLUSIVE is set, then CREATE must also be set.
+ ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
+ */
+ assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
+ assert(isCreate==0 || isReadWrite);
+ assert(isExclusive==0 || isCreate);
+ assert(isDelete==0 || isCreate);
+
+ /* The main DB, main journal, WAL file and super-journal are never
+ ** automatically deleted. Nor are they ever temporary files. */
+ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
+ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
+ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL );
+ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
+
+ /* Assert that the upper layer has set one of the "file-type" flags. */
+ assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
+ || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
+ || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_SUPER_JOURNAL
+ || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
+ );
+
+ /* Detect a pid change and reset the PRNG. There is a race condition
+ ** here such that two or more threads all trying to open databases at
+ ** the same instant might all reset the PRNG. But multiple resets
+ ** are harmless.
+ */
+ if( randomnessPid!=osGetpid(0) ){
+ randomnessPid = osGetpid(0);
+ sqlite3_randomness(0,0);
+ }
+ memset(p, 0, sizeof(unixFile));
+
+ if( eType==SQLITE_OPEN_MAIN_DB ){
+ UnixUnusedFd *pUnused;
+ pUnused = findReusableFd(zName, flags);
+ if( pUnused ){
+ fd = pUnused->fd;
+ }else{
+ pUnused = sqlite3_malloc64(sizeof(*pUnused));
+ if( !pUnused ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ }
+ p->pPreallocatedUnused = pUnused;
+
+ /* Database filenames are double-zero terminated if they are not
+ ** URIs with parameters. Hence, they can always be passed into
+ ** sqlite3_uri_parameter(). */
+ assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
+
+ }else if( !zName ){
+ /* If zName is NULL, the upper layer is requesting a temp file. */
+ assert(isDelete && !isNewJrnl);
+ rc = unixGetTempname(pVfs->mxPathname, zTmpname);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ zName = zTmpname;
+
+ /* Generated temporary filenames are always double-zero terminated
+ ** for use by sqlite3_uri_parameter(). */
+ assert( zName[strlen(zName)+1]==0 );
+ }
+
+ /* Determine the value of the flags parameter passed to POSIX function
+ ** open(). These must be calculated even if open() is not called, as
+ ** they may be stored as part of the file handle and used by the
+ ** 'conch file' locking functions later on. */
+ if( isReadonly ) openFlags |= O_RDONLY;
+ if( isReadWrite ) openFlags |= O_RDWR;
+ if( isCreate ) openFlags |= O_CREAT;
+ if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
+ openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW);
+
+ if( fd<0 ){
+ mode_t openMode; /* Permissions to create file with */
+ uid_t uid; /* Userid for the file */
+ gid_t gid; /* Groupid for the file */
+ rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
+ if( rc!=SQLITE_OK ){
+ assert( !p->pPreallocatedUnused );
+ assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
+ return rc;
+ }
+ fd = robust_open(zName, openFlags, openMode);
+ OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
+ assert( !isExclusive || (openFlags & O_CREAT)!=0 );
+ if( fd<0 ){
+ if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
+ /* If unable to create a journal because the directory is not
+ ** writable, change the error code to indicate that. */
+ rc = SQLITE_READONLY_DIRECTORY;
+ }else if( errno!=EISDIR && isReadWrite ){
+ /* Failed to open the file for read/write access. Try read-only. */
+ flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
+ openFlags &= ~(O_RDWR|O_CREAT);
+ flags |= SQLITE_OPEN_READONLY;
+ openFlags |= O_RDONLY;
+ isReadonly = 1;
+ fd = robust_open(zName, openFlags, openMode);
+ }
+ }
+ if( fd<0 ){
+ int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
+ if( rc==SQLITE_OK ) rc = rc2;
+ goto open_finished;
+ }
+
+ /* The owner of the rollback journal or WAL file should always be the
+ ** same as the owner of the database file. Try to ensure that this is
+ ** the case. The chown() system call will be a no-op if the current
+ ** process lacks root privileges, be we should at least try. Without
+ ** this step, if a root process opens a database file, it can leave
+ ** behinds a journal/WAL that is owned by root and hence make the
+ ** database inaccessible to unprivileged processes.
+ **
+ ** If openMode==0, then that means uid and gid are not set correctly
+ ** (probably because SQLite is configured to use 8+3 filename mode) and
+ ** in that case we do not want to attempt the chown().
+ */
+ if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){
+ robustFchown(fd, uid, gid);
+ }
+ }
+ assert( fd>=0 );
+ if( pOutFlags ){
+ *pOutFlags = flags;
+ }
+
+ if( p->pPreallocatedUnused ){
+ p->pPreallocatedUnused->fd = fd;
+ p->pPreallocatedUnused->flags =
+ flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
+ }
+
+ if( isDelete ){
+#if OS_VXWORKS
+ zPath = zName;
+#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
+ zPath = sqlite3_mprintf("%s", zName);
+ if( zPath==0 ){
+ robust_close(p, fd, __LINE__);
+ return SQLITE_NOMEM_BKPT;
+ }
+#else
+ osUnlink(zName);
+#endif
+ }
+#if SQLITE_ENABLE_LOCKING_STYLE
+ else{
+ p->openFlags = openFlags;
+ }
+#endif
+
+#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
+ if( fstatfs(fd, &fsInfo) == -1 ){
+ storeLastErrno(p, errno);
+ robust_close(p, fd, __LINE__);
+ return SQLITE_IOERR_ACCESS;
+ }
+ if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
+ ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
+ }
+ if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
+ ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
+ }
+#endif
+
+ /* Set up appropriate ctrlFlags */
+ if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
+ if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
+ noLock = eType!=SQLITE_OPEN_MAIN_DB;
+ if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
+ if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
+ if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
+
+#if SQLITE_ENABLE_LOCKING_STYLE
+#if SQLITE_PREFER_PROXY_LOCKING
+ isAutoProxy = 1;
+#endif
+ if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
+ char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
+ int useProxy = 0;
+
+ /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
+ ** never use proxy, NULL means use proxy for non-local files only. */
+ if( envforce!=NULL ){
+ useProxy = atoi(envforce)>0;
+ }else{
+ useProxy = !(fsInfo.f_flags&MNT_LOCAL);
+ }
+ if( useProxy ){
+ rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
+ if( rc==SQLITE_OK ){
+ rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
+ if( rc!=SQLITE_OK ){
+ /* Use unixClose to clean up the resources added in fillInUnixFile
+ ** and clear all the structure's references. Specifically,
+ ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
+ */
+ unixClose(pFile);
+ return rc;
+ }
+ }
+ goto open_finished;
+ }
+ }
+#endif
+
+ assert( zPath==0 || zPath[0]=='/'
+ || eType==SQLITE_OPEN_SUPER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
+ );
+ rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
+
+open_finished:
+ if( rc!=SQLITE_OK ){
+ sqlite3_free(p->pPreallocatedUnused);
+ }
+ return rc;
+}
+
+
+/*
+** Delete the file at zPath. If the dirSync argument is true, fsync()
+** the directory after deleting the file.
+*/
+static int unixDelete(
+ sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
+ const char *zPath, /* Name of file to be deleted */
+ int dirSync /* If true, fsync() directory after deleting file */
+){
+ int rc = SQLITE_OK;
+ UNUSED_PARAMETER(NotUsed);
+ SimulateIOError(return SQLITE_IOERR_DELETE);
+ if( osUnlink(zPath)==(-1) ){
+ if( errno==ENOENT
+#if OS_VXWORKS
+ || osAccess(zPath,0)!=0
+#endif
+ ){
+ rc = SQLITE_IOERR_DELETE_NOENT;
+ }else{
+ rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
+ }
+ return rc;
+ }
+#ifndef SQLITE_DISABLE_DIRSYNC
+ if( (dirSync & 1)!=0 ){
+ int fd;
+ rc = osOpenDirectory(zPath, &fd);
+ if( rc==SQLITE_OK ){
+ if( full_fsync(fd,0,0) ){
+ rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
+ }
+ robust_close(0, fd, __LINE__);
+ }else{
+ assert( rc==SQLITE_CANTOPEN );
+ rc = SQLITE_OK;
+ }
+ }
+#endif
+ return rc;
+}
+
+/*
+** Test the existence of or access permissions of file zPath. The
+** test performed depends on the value of flags:
+**
+** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
+** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
+** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
+**
+** Otherwise return 0.
+*/
+static int unixAccess(
+ sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
+ const char *zPath, /* Path of the file to examine */
+ int flags, /* What do we want to learn about the zPath file? */
+ int *pResOut /* Write result boolean here */
+){
+ UNUSED_PARAMETER(NotUsed);
+ SimulateIOError( return SQLITE_IOERR_ACCESS; );
+ assert( pResOut!=0 );
+
+ /* The spec says there are three possible values for flags. But only
+ ** two of them are actually used */
+ assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
+
+ if( flags==SQLITE_ACCESS_EXISTS ){
+ struct stat buf;
+ *pResOut = 0==osStat(zPath, &buf) &&
+ (!S_ISREG(buf.st_mode) || buf.st_size>0);
+ }else{
+ *pResOut = osAccess(zPath, W_OK|R_OK)==0;
+ }
+ return SQLITE_OK;
+}
+
+/*
+**
+*/
+static int mkFullPathname(
+ const char *zPath, /* Input path */
+ char *zOut, /* Output buffer */
+ int nOut /* Allocated size of buffer zOut */
+){
+ int nPath = sqlite3Strlen30(zPath);
+ int iOff = 0;
+ if( zPath[0]!='/' ){
+ if( osGetcwd(zOut, nOut-2)==0 ){
+ return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
+ }
+ iOff = sqlite3Strlen30(zOut);
+ zOut[iOff++] = '/';
+ }
+ if( (iOff+nPath+1)>nOut ){
+ /* SQLite assumes that xFullPathname() nul-terminates the output buffer
+ ** even if it returns an error. */
+ zOut[iOff] = '\0';
+ return SQLITE_CANTOPEN_BKPT;
+ }
+ sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
+ return SQLITE_OK;
+}
+
+/*
+** Turn a relative pathname into a full pathname. The relative path
+** is stored as a nul-terminated string in the buffer pointed to by
+** zPath.
+**
+** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
+** (in this case, MAX_PATHNAME bytes). The full-path is written to
+** this buffer before returning.
+*/
+static int unixFullPathname(
+ sqlite3_vfs *pVfs, /* Pointer to vfs object */
+ const char *zPath, /* Possibly relative input path */
+ int nOut, /* Size of output buffer in bytes */
+ char *zOut /* Output buffer */
+){
+#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
+ return mkFullPathname(zPath, zOut, nOut);
+#else
+ int rc = SQLITE_OK;
+ int nByte;
+ int nLink = 0; /* Number of symbolic links followed so far */
+ const char *zIn = zPath; /* Input path for each iteration of loop */
+ char *zDel = 0;
+
+ assert( pVfs->mxPathname==MAX_PATHNAME );
+ UNUSED_PARAMETER(pVfs);
+
+ /* It's odd to simulate an io-error here, but really this is just
+ ** using the io-error infrastructure to test that SQLite handles this
+ ** function failing. This function could fail if, for example, the
+ ** current working directory has been unlinked.
+ */
+ SimulateIOError( return SQLITE_ERROR );
+
+ do {
+
+ /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
+ ** link, or false otherwise. */
+ int bLink = 0;
+ struct stat buf;
+ if( osLstat(zIn, &buf)!=0 ){
+ if( errno!=ENOENT ){
+ rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
+ }
+ }else{
+ bLink = S_ISLNK(buf.st_mode);
+ }
+
+ if( bLink ){
+ nLink++;
+ if( zDel==0 ){
+ zDel = sqlite3_malloc(nOut);
+ if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
+ }else if( nLink>=SQLITE_MAX_SYMLINKS ){
+ rc = SQLITE_CANTOPEN_BKPT;
+ }
+
+ if( rc==SQLITE_OK ){
+ nByte = osReadlink(zIn, zDel, nOut-1);
+ if( nByte<0 ){
+ rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
+ }else{
+ if( zDel[0]!='/' ){
+ int n;
+ for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
+ if( nByte+n+1>nOut ){
+ rc = SQLITE_CANTOPEN_BKPT;
+ }else{
+ memmove(&zDel[n], zDel, nByte+1);
+ memcpy(zDel, zIn, n);
+ nByte += n;
+ }
+ }
+ zDel[nByte] = '\0';
+ }
+ }
+
+ zIn = zDel;
+ }
+
+ assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
+ if( rc==SQLITE_OK && zIn!=zOut ){
+ rc = mkFullPathname(zIn, zOut, nOut);
+ }
+ if( bLink==0 ) break;
+ zIn = zOut;
+ }while( rc==SQLITE_OK );
+
+ sqlite3_free(zDel);
+ if( rc==SQLITE_OK && nLink ) rc = SQLITE_OK_SYMLINK;
+ return rc;
+#endif /* HAVE_READLINK && HAVE_LSTAT */
+}
+
+
+#ifndef SQLITE_OMIT_LOAD_EXTENSION
+/*
+** Interfaces for opening a shared library, finding entry points
+** within the shared library, and closing the shared library.
+*/
+#include <dlfcn.h>
+static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
+ UNUSED_PARAMETER(NotUsed);
+ return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
+}
+
+/*
+** SQLite calls this function immediately after a call to unixDlSym() or
+** unixDlOpen() fails (returns a null pointer). If a more detailed error
+** message is available, it is written to zBufOut. If no error message
+** is available, zBufOut is left unmodified and SQLite uses a default
+** error message.
+*/
+static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
+ const char *zErr;
+ UNUSED_PARAMETER(NotUsed);
+ unixEnterMutex();
+ zErr = dlerror();
+ if( zErr ){
+ sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
+ }
+ unixLeaveMutex();
+}
+static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
+ /*
+ ** GCC with -pedantic-errors says that C90 does not allow a void* to be
+ ** cast into a pointer to a function. And yet the library dlsym() routine
+ ** returns a void* which is really a pointer to a function. So how do we
+ ** use dlsym() with -pedantic-errors?
+ **
+ ** Variable x below is defined to be a pointer to a function taking
+ ** parameters void* and const char* and returning a pointer to a function.
+ ** We initialize x by assigning it a pointer to the dlsym() function.
+ ** (That assignment requires a cast.) Then we call the function that
+ ** x points to.
+ **
+ ** This work-around is unlikely to work correctly on any system where
+ ** you really cannot cast a function pointer into void*. But then, on the
+ ** other hand, dlsym() will not work on such a system either, so we have
+ ** not really lost anything.
+ */
+ void (*(*x)(void*,const char*))(void);
+ UNUSED_PARAMETER(NotUsed);
+ x = (void(*(*)(void*,const char*))(void))dlsym;
+ return (*x)(p, zSym);
+}
+static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
+ UNUSED_PARAMETER(NotUsed);
+ dlclose(pHandle);
+}
+#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
+ #define unixDlOpen 0
+ #define unixDlError 0
+ #define unixDlSym 0
+ #define unixDlClose 0
+#endif
+
+/*
+** Write nBuf bytes of random data to the supplied buffer zBuf.
+*/
+static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
+ UNUSED_PARAMETER(NotUsed);
+ assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
+
+ /* We have to initialize zBuf to prevent valgrind from reporting
+ ** errors. The reports issued by valgrind are incorrect - we would
+ ** prefer that the randomness be increased by making use of the
+ ** uninitialized space in zBuf - but valgrind errors tend to worry
+ ** some users. Rather than argue, it seems easier just to initialize
+ ** the whole array and silence valgrind, even if that means less randomness
+ ** in the random seed.
+ **
+ ** When testing, initializing zBuf[] to zero is all we do. That means
+ ** that we always use the same random number sequence. This makes the
+ ** tests repeatable.
+ */
+ memset(zBuf, 0, nBuf);
+ randomnessPid = osGetpid(0);
+#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
+ {
+ int fd, got;
+ fd = robust_open("/dev/urandom", O_RDONLY, 0);
+ if( fd<0 ){
+ time_t t;
+ time(&t);
+ memcpy(zBuf, &t, sizeof(t));
+ memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
+ assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
+ nBuf = sizeof(t) + sizeof(randomnessPid);
+ }else{
+ do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
+ robust_close(0, fd, __LINE__);
+ }
+ }
+#endif
+ return nBuf;
+}
+
+
+/*
+** Sleep for a little while. Return the amount of time slept.
+** The argument is the number of microseconds we want to sleep.
+** The return value is the number of microseconds of sleep actually
+** requested from the underlying operating system, a number which
+** might be greater than or equal to the argument, but not less
+** than the argument.
+*/
+static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
+#if OS_VXWORKS
+ struct timespec sp;
+
+ sp.tv_sec = microseconds / 1000000;
+ sp.tv_nsec = (microseconds % 1000000) * 1000;
+ nanosleep(&sp, NULL);
+ UNUSED_PARAMETER(NotUsed);
+ return microseconds;
+#elif defined(HAVE_USLEEP) && HAVE_USLEEP
+ if( microseconds>=1000000 ) sleep(microseconds/1000000);
+ if( microseconds%1000000 ) usleep(microseconds%1000000);
+ UNUSED_PARAMETER(NotUsed);
+ return microseconds;
+#else
+ int seconds = (microseconds+999999)/1000000;
+ sleep(seconds);
+ UNUSED_PARAMETER(NotUsed);
+ return seconds*1000000;
+#endif
+}
+
+/*
+** The following variable, if set to a non-zero value, is interpreted as
+** the number of seconds since 1970 and is used to set the result of
+** sqlite3OsCurrentTime() during testing.
+*/
+#ifdef SQLITE_TEST
+SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
+#endif
+
+/*
+** Find the current time (in Universal Coordinated Time). Write into *piNow
+** the current time and date as a Julian Day number times 86_400_000. In
+** other words, write into *piNow the number of milliseconds since the Julian
+** epoch of noon in Greenwich on November 24, 4714 B.C according to the
+** proleptic Gregorian calendar.
+**
+** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
+** cannot be found.
+*/
+static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
+ static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
+ int rc = SQLITE_OK;
+#if defined(NO_GETTOD)
+ time_t t;
+ time(&t);
+ *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
+#elif OS_VXWORKS
+ struct timespec sNow;
+ clock_gettime(CLOCK_REALTIME, &sNow);
+ *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
+#else
+ struct timeval sNow;
+ (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
+ *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
+#endif
+
+#ifdef SQLITE_TEST
+ if( sqlite3_current_time ){
+ *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
+ }
+#endif
+ UNUSED_PARAMETER(NotUsed);
+ return rc;
+}
+
+#ifndef SQLITE_OMIT_DEPRECATED
+/*
+** Find the current time (in Universal Coordinated Time). Write the
+** current time and date as a Julian Day number into *prNow and
+** return 0. Return 1 if the time and date cannot be found.
+*/
+static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
+ sqlite3_int64 i = 0;
+ int rc;
+ UNUSED_PARAMETER(NotUsed);
+ rc = unixCurrentTimeInt64(0, &i);
+ *prNow = i/86400000.0;
+ return rc;
+}
+#else
+# define unixCurrentTime 0
+#endif
+
+/*
+** The xGetLastError() method is designed to return a better
+** low-level error message when operating-system problems come up
+** during SQLite operation. Only the integer return code is currently
+** used.
+*/
+static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
+ UNUSED_PARAMETER(NotUsed);
+ UNUSED_PARAMETER(NotUsed2);
+ UNUSED_PARAMETER(NotUsed3);
+ return errno;
+}
+
+
+/*
+************************ End of sqlite3_vfs methods ***************************
+******************************************************************************/
+
+/******************************************************************************
+************************** Begin Proxy Locking ********************************
+**
+** Proxy locking is a "uber-locking-method" in this sense: It uses the
+** other locking methods on secondary lock files. Proxy locking is a
+** meta-layer over top of the primitive locking implemented above. For
+** this reason, the division that implements of proxy locking is deferred
+** until late in the file (here) after all of the other I/O methods have
+** been defined - so that the primitive locking methods are available
+** as services to help with the implementation of proxy locking.
+**
+****
+**
+** The default locking schemes in SQLite use byte-range locks on the
+** database file to coordinate safe, concurrent access by multiple readers
+** and writers [http://sqlite.org/lockingv3.html]. The five file locking
+** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
+** as POSIX read & write locks over fixed set of locations (via fsctl),
+** on AFP and SMB only exclusive byte-range locks are available via fsctl
+** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
+** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
+** address in the shared range is taken for a SHARED lock, the entire
+** shared range is taken for an EXCLUSIVE lock):
+**
+** PENDING_BYTE 0x40000000
+** RESERVED_BYTE 0x40000001
+** SHARED_RANGE 0x40000002 -> 0x40000200
+**
+** This works well on the local file system, but shows a nearly 100x
+** slowdown in read performance on AFP because the AFP client disables
+** the read cache when byte-range locks are present. Enabling the read
+** cache exposes a cache coherency problem that is present on all OS X
+** supported network file systems. NFS and AFP both observe the
+** close-to-open semantics for ensuring cache coherency
+** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
+** address the requirements for concurrent database access by multiple
+** readers and writers
+** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
+**
+** To address the performance and cache coherency issues, proxy file locking
+** changes the way database access is controlled by limiting access to a
+** single host at a time and moving file locks off of the database file
+** and onto a proxy file on the local file system.
+**
+**
+** Using proxy locks
+** -----------------
+**
+** C APIs
+**
+** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
+** <proxy_path> | ":auto:");
+** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
+** &<proxy_path>);
+**
+**
+** SQL pragmas
+**
+** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
+** PRAGMA [database.]lock_proxy_file
+**
+** Specifying ":auto:" means that if there is a conch file with a matching
+** host ID in it, the proxy path in the conch file will be used, otherwise
+** a proxy path based on the user's temp dir
+** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
+** actual proxy file name is generated from the name and path of the
+** database file. For example:
+**
+** For database path "/Users/me/foo.db"
+** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
+**
+** Once a lock proxy is configured for a database connection, it can not
+** be removed, however it may be switched to a different proxy path via
+** the above APIs (assuming the conch file is not being held by another
+** connection or process).
+**
+**
+** How proxy locking works
+** -----------------------
+**
+** Proxy file locking relies primarily on two new supporting files:
+**
+** * conch file to limit access to the database file to a single host
+** at a time
+**
+** * proxy file to act as a proxy for the advisory locks normally
+** taken on the database
+**
+** The conch file - to use a proxy file, sqlite must first "hold the conch"
+** by taking an sqlite-style shared lock on the conch file, reading the
+** contents and comparing the host's unique host ID (see below) and lock
+** proxy path against the values stored in the conch. The conch file is
+** stored in the same directory as the database file and the file name
+** is patterned after the database file name as ".<databasename>-conch".
+** If the conch file does not exist, or its contents do not match the
+** host ID and/or proxy path, then the lock is escalated to an exclusive
+** lock and the conch file contents is updated with the host ID and proxy
+** path and the lock is downgraded to a shared lock again. If the conch
+** is held by another process (with a shared lock), the exclusive lock
+** will fail and SQLITE_BUSY is returned.
+**
+** The proxy file - a single-byte file used for all advisory file locks
+** normally taken on the database file. This allows for safe sharing
+** of the database file for multiple readers and writers on the same
+** host (the conch ensures that they all use the same local lock file).
+**
+** Requesting the lock proxy does not immediately take the conch, it is
+** only taken when the first request to lock database file is made.
+** This matches the semantics of the traditional locking behavior, where
+** opening a connection to a database file does not take a lock on it.
+** The shared lock and an open file descriptor are maintained until
+** the connection to the database is closed.
+**
+** The proxy file and the lock file are never deleted so they only need
+** to be created the first time they are used.
+**
+** Configuration options
+** ---------------------
+**
+** SQLITE_PREFER_PROXY_LOCKING
+**
+** Database files accessed on non-local file systems are
+** automatically configured for proxy locking, lock files are
+** named automatically using the same logic as
+** PRAGMA lock_proxy_file=":auto:"
+**
+** SQLITE_PROXY_DEBUG
+**
+** Enables the logging of error messages during host id file
+** retrieval and creation
+**
+** LOCKPROXYDIR
+**
+** Overrides the default directory used for lock proxy files that
+** are named automatically via the ":auto:" setting
+**
+** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
+**
+** Permissions to use when creating a directory for storing the
+** lock proxy files, only used when LOCKPROXYDIR is not set.
+**
+**
+** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
+** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
+** force proxy locking to be used for every database file opened, and 0
+** will force automatic proxy locking to be disabled for all database
+** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
+** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
+*/
+
+/*
+** Proxy locking is only available on MacOSX
+*/
+#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
+
+/*
+** The proxyLockingContext has the path and file structures for the remote
+** and local proxy files in it
+*/
+typedef struct proxyLockingContext proxyLockingContext;
+struct proxyLockingContext {
+ unixFile *conchFile; /* Open conch file */
+ char *conchFilePath; /* Name of the conch file */
+ unixFile *lockProxy; /* Open proxy lock file */
+ char *lockProxyPath; /* Name of the proxy lock file */
+ char *dbPath; /* Name of the open file */
+ int conchHeld; /* 1 if the conch is held, -1 if lockless */
+ int nFails; /* Number of conch taking failures */
+ void *oldLockingContext; /* Original lockingcontext to restore on close */
+ sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
+};
+
+/*
+** The proxy lock file path for the database at dbPath is written into lPath,
+** which must point to valid, writable memory large enough for a maxLen length
+** file path.
+*/
+static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
+ int len;
+ int dbLen;
+ int i;
+
+#ifdef LOCKPROXYDIR
+ len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
+#else
+# ifdef _CS_DARWIN_USER_TEMP_DIR
+ {
+ if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
+ OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
+ lPath, errno, osGetpid(0)));
+ return SQLITE_IOERR_LOCK;
+ }
+ len = strlcat(lPath, "sqliteplocks", maxLen);
+ }
+# else
+ len = strlcpy(lPath, "/tmp/", maxLen);
+# endif
+#endif
+
+ if( lPath[len-1]!='/' ){
+ len = strlcat(lPath, "/", maxLen);
+ }
+
+ /* transform the db path to a unique cache name */
+ dbLen = (int)strlen(dbPath);
+ for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
+ char c = dbPath[i];
+ lPath[i+len] = (c=='/')?'_':c;
+ }
+ lPath[i+len]='\0';
+ strlcat(lPath, ":auto:", maxLen);
+ OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
+ return SQLITE_OK;
+}
+
+/*
+ ** Creates the lock file and any missing directories in lockPath
+ */
+static int proxyCreateLockPath(const char *lockPath){
+ int i, len;
+ char buf[MAXPATHLEN];
+ int start = 0;
+
+ assert(lockPath!=NULL);
+ /* try to create all the intermediate directories */
+ len = (int)strlen(lockPath);
+ buf[0] = lockPath[0];
+ for( i=1; i<len; i++ ){
+ if( lockPath[i] == '/' && (i - start > 0) ){
+ /* only mkdir if leaf dir != "." or "/" or ".." */
+ if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
+ || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
+ buf[i]='\0';
+ if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
+ int err=errno;
+ if( err!=EEXIST ) {
+ OSTRACE(("CREATELOCKPATH FAILED creating %s, "
+ "'%s' proxy lock path=%s pid=%d\n",
+ buf, strerror(err), lockPath, osGetpid(0)));
+ return err;
+ }
+ }
+ }
+ start=i+1;
+ }
+ buf[i] = lockPath[i];
+ }
+ OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
+ return 0;
+}
+
+/*
+** Create a new VFS file descriptor (stored in memory obtained from
+** sqlite3_malloc) and open the file named "path" in the file descriptor.
+**
+** The caller is responsible not only for closing the file descriptor
+** but also for freeing the memory associated with the file descriptor.
+*/
+static int proxyCreateUnixFile(
+ const char *path, /* path for the new unixFile */
+ unixFile **ppFile, /* unixFile created and returned by ref */
+ int islockfile /* if non zero missing dirs will be created */
+) {
+ int fd = -1;
+ unixFile *pNew;
+ int rc = SQLITE_OK;
+ int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW;
+ sqlite3_vfs dummyVfs;
+ int terrno = 0;
+ UnixUnusedFd *pUnused = NULL;
+
+ /* 1. first try to open/create the file
+ ** 2. if that fails, and this is a lock file (not-conch), try creating
+ ** the parent directories and then try again.
+ ** 3. if that fails, try to open the file read-only
+ ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
+ */
+ pUnused = findReusableFd(path, openFlags);
+ if( pUnused ){
+ fd = pUnused->fd;
+ }else{
+ pUnused = sqlite3_malloc64(sizeof(*pUnused));
+ if( !pUnused ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ }
+ if( fd<0 ){
+ fd = robust_open(path, openFlags, 0);
+ terrno = errno;
+ if( fd<0 && errno==ENOENT && islockfile ){
+ if( proxyCreateLockPath(path) == SQLITE_OK ){
+ fd = robust_open(path, openFlags, 0);
+ }
+ }
+ }
+ if( fd<0 ){
+ openFlags = O_RDONLY | O_NOFOLLOW;
+ fd = robust_open(path, openFlags, 0);
+ terrno = errno;
+ }
+ if( fd<0 ){
+ if( islockfile ){
+ return SQLITE_BUSY;
+ }
+ switch (terrno) {
+ case EACCES:
+ return SQLITE_PERM;
+ case EIO:
+ return SQLITE_IOERR_LOCK; /* even though it is the conch */
+ default:
+ return SQLITE_CANTOPEN_BKPT;
+ }
+ }
+
+ pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
+ if( pNew==NULL ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto end_create_proxy;
+ }
+ memset(pNew, 0, sizeof(unixFile));
+ pNew->openFlags = openFlags;
+ memset(&dummyVfs, 0, sizeof(dummyVfs));
+ dummyVfs.pAppData = (void*)&autolockIoFinder;
+ dummyVfs.zName = "dummy";
+ pUnused->fd = fd;
+ pUnused->flags = openFlags;
+ pNew->pPreallocatedUnused = pUnused;
+
+ rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
+ if( rc==SQLITE_OK ){
+ *ppFile = pNew;
+ return SQLITE_OK;
+ }
+end_create_proxy:
+ robust_close(pNew, fd, __LINE__);
+ sqlite3_free(pNew);
+ sqlite3_free(pUnused);
+ return rc;
+}
+
+#ifdef SQLITE_TEST
+/* simulate multiple hosts by creating unique hostid file paths */
+SQLITE_API int sqlite3_hostid_num = 0;
+#endif
+
+#define PROXY_HOSTIDLEN 16 /* conch file host id length */
+
+#if HAVE_GETHOSTUUID
+/* Not always defined in the headers as it ought to be */
+extern int gethostuuid(uuid_t id, const struct timespec *wait);
+#endif
+
+/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
+** bytes of writable memory.
+*/
+static int proxyGetHostID(unsigned char *pHostID, int *pError){
+ assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
+ memset(pHostID, 0, PROXY_HOSTIDLEN);
+#if HAVE_GETHOSTUUID
+ {
+ struct timespec timeout = {1, 0}; /* 1 sec timeout */
+ if( gethostuuid(pHostID, &timeout) ){
+ int err = errno;
+ if( pError ){
+ *pError = err;
+ }
+ return SQLITE_IOERR;
+ }
+ }
+#else
+ UNUSED_PARAMETER(pError);
+#endif
+#ifdef SQLITE_TEST
+ /* simulate multiple hosts by creating unique hostid file paths */
+ if( sqlite3_hostid_num != 0){
+ pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
+ }
+#endif
+
+ return SQLITE_OK;
+}
+
+/* The conch file contains the header, host id and lock file path
+ */
+#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
+#define PROXY_HEADERLEN 1 /* conch file header length */
+#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
+#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
+
+/*
+** Takes an open conch file, copies the contents to a new path and then moves
+** it back. The newly created file's file descriptor is assigned to the
+** conch file structure and finally the original conch file descriptor is
+** closed. Returns zero if successful.
+*/
+static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
+ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
+ unixFile *conchFile = pCtx->conchFile;
+ char tPath[MAXPATHLEN];
+ char buf[PROXY_MAXCONCHLEN];
+ char *cPath = pCtx->conchFilePath;
+ size_t readLen = 0;
+ size_t pathLen = 0;
+ char errmsg[64] = "";
+ int fd = -1;
+ int rc = -1;
+ UNUSED_PARAMETER(myHostID);
+
+ /* create a new path by replace the trailing '-conch' with '-break' */
+ pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
+ if( pathLen>MAXPATHLEN || pathLen<6 ||
+ (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
+ sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
+ goto end_breaklock;
+ }
+ /* read the conch content */
+ readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
+ if( readLen<PROXY_PATHINDEX ){
+ sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
+ goto end_breaklock;
+ }
+ /* write it out to the temporary break file */
+ fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW), 0);
+ if( fd<0 ){
+ sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
+ goto end_breaklock;
+ }
+ if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
+ sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
+ goto end_breaklock;
+ }
+ if( rename(tPath, cPath) ){
+ sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
+ goto end_breaklock;
+ }
+ rc = 0;
+ fprintf(stderr, "broke stale lock on %s\n", cPath);
+ robust_close(pFile, conchFile->h, __LINE__);
+ conchFile->h = fd;
+ conchFile->openFlags = O_RDWR | O_CREAT;
+
+end_breaklock:
+ if( rc ){
+ if( fd>=0 ){
+ osUnlink(tPath);
+ robust_close(pFile, fd, __LINE__);
+ }
+ fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
+ }
+ return rc;
+}
+
+/* Take the requested lock on the conch file and break a stale lock if the
+** host id matches.
+*/
+static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
+ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
+ unixFile *conchFile = pCtx->conchFile;
+ int rc = SQLITE_OK;
+ int nTries = 0;
+ struct timespec conchModTime;
+
+ memset(&conchModTime, 0, sizeof(conchModTime));
+ do {
+ rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
+ nTries ++;
+ if( rc==SQLITE_BUSY ){
+ /* If the lock failed (busy):
+ * 1st try: get the mod time of the conch, wait 0.5s and try again.
+ * 2nd try: fail if the mod time changed or host id is different, wait
+ * 10 sec and try again
+ * 3rd try: break the lock unless the mod time has changed.
+ */
+ struct stat buf;
+ if( osFstat(conchFile->h, &buf) ){
+ storeLastErrno(pFile, errno);
+ return SQLITE_IOERR_LOCK;
+ }
+
+ if( nTries==1 ){
+ conchModTime = buf.st_mtimespec;
+ unixSleep(0,500000); /* wait 0.5 sec and try the lock again*/
+ continue;
+ }
+
+ assert( nTries>1 );
+ if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
+ conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
+ return SQLITE_BUSY;
+ }
+
+ if( nTries==2 ){
+ char tBuf[PROXY_MAXCONCHLEN];
+ int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
+ if( len<0 ){
+ storeLastErrno(pFile, errno);
+ return SQLITE_IOERR_LOCK;
+ }
+ if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
+ /* don't break the lock if the host id doesn't match */
+ if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
+ return SQLITE_BUSY;
+ }
+ }else{
+ /* don't break the lock on short read or a version mismatch */
+ return SQLITE_BUSY;
+ }
+ unixSleep(0,10000000); /* wait 10 sec and try the lock again */
+ continue;
+ }
+
+ assert( nTries==3 );
+ if( 0==proxyBreakConchLock(pFile, myHostID) ){
+ rc = SQLITE_OK;
+ if( lockType==EXCLUSIVE_LOCK ){
+ rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
+ }
+ if( !rc ){
+ rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
+ }
+ }
+ }
+ } while( rc==SQLITE_BUSY && nTries<3 );
+
+ return rc;
+}
+
+/* Takes the conch by taking a shared lock and read the contents conch, if
+** lockPath is non-NULL, the host ID and lock file path must match. A NULL
+** lockPath means that the lockPath in the conch file will be used if the
+** host IDs match, or a new lock path will be generated automatically
+** and written to the conch file.
+*/
+static int proxyTakeConch(unixFile *pFile){
+ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
+
+ if( pCtx->conchHeld!=0 ){
+ return SQLITE_OK;
+ }else{
+ unixFile *conchFile = pCtx->conchFile;
+ uuid_t myHostID;
+ int pError = 0;
+ char readBuf[PROXY_MAXCONCHLEN];
+ char lockPath[MAXPATHLEN];
+ char *tempLockPath = NULL;
+ int rc = SQLITE_OK;
+ int createConch = 0;
+ int hostIdMatch = 0;
+ int readLen = 0;
+ int tryOldLockPath = 0;
+ int forceNewLockPath = 0;
+
+ OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
+ (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
+ osGetpid(0)));
+
+ rc = proxyGetHostID(myHostID, &pError);
+ if( (rc&0xff)==SQLITE_IOERR ){
+ storeLastErrno(pFile, pError);
+ goto end_takeconch;
+ }
+ rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
+ if( rc!=SQLITE_OK ){
+ goto end_takeconch;
+ }
+ /* read the existing conch file */
+ readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
+ if( readLen<0 ){
+ /* I/O error: lastErrno set by seekAndRead */
+ storeLastErrno(pFile, conchFile->lastErrno);
+ rc = SQLITE_IOERR_READ;
+ goto end_takeconch;
+ }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
+ readBuf[0]!=(char)PROXY_CONCHVERSION ){
+ /* a short read or version format mismatch means we need to create a new
+ ** conch file.
+ */
+ createConch = 1;
+ }
+ /* if the host id matches and the lock path already exists in the conch
+ ** we'll try to use the path there, if we can't open that path, we'll
+ ** retry with a new auto-generated path
+ */
+ do { /* in case we need to try again for an :auto: named lock file */
+
+ if( !createConch && !forceNewLockPath ){
+ hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
+ PROXY_HOSTIDLEN);
+ /* if the conch has data compare the contents */
+ if( !pCtx->lockProxyPath ){
+ /* for auto-named local lock file, just check the host ID and we'll
+ ** use the local lock file path that's already in there
+ */
+ if( hostIdMatch ){
+ size_t pathLen = (readLen - PROXY_PATHINDEX);
+
+ if( pathLen>=MAXPATHLEN ){
+ pathLen=MAXPATHLEN-1;
+ }
+ memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
+ lockPath[pathLen] = 0;
+ tempLockPath = lockPath;
+ tryOldLockPath = 1;
+ /* create a copy of the lock path if the conch is taken */
+ goto end_takeconch;
+ }
+ }else if( hostIdMatch
+ && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
+ readLen-PROXY_PATHINDEX)
+ ){
+ /* conch host and lock path match */
+ goto end_takeconch;
+ }
+ }
+
+ /* if the conch isn't writable and doesn't match, we can't take it */
+ if( (conchFile->openFlags&O_RDWR) == 0 ){
+ rc = SQLITE_BUSY;
+ goto end_takeconch;
+ }
+
+ /* either the conch didn't match or we need to create a new one */
+ if( !pCtx->lockProxyPath ){
+ proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
+ tempLockPath = lockPath;
+ /* create a copy of the lock path _only_ if the conch is taken */
+ }
+
+ /* update conch with host and path (this will fail if other process
+ ** has a shared lock already), if the host id matches, use the big
+ ** stick.
+ */
+ futimes(conchFile->h, NULL);
+ if( hostIdMatch && !createConch ){
+ if( conchFile->pInode && conchFile->pInode->nShared>1 ){
+ /* We are trying for an exclusive lock but another thread in this
+ ** same process is still holding a shared lock. */
+ rc = SQLITE_BUSY;
+ } else {
+ rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
+ }
+ }else{
+ rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
+ }
+ if( rc==SQLITE_OK ){
+ char writeBuffer[PROXY_MAXCONCHLEN];
+ int writeSize = 0;
+
+ writeBuffer[0] = (char)PROXY_CONCHVERSION;
+ memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
+ if( pCtx->lockProxyPath!=NULL ){
+ strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
+ MAXPATHLEN);
+ }else{
+ strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
+ }
+ writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
+ robust_ftruncate(conchFile->h, writeSize);
+ rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
+ full_fsync(conchFile->h,0,0);
+ /* If we created a new conch file (not just updated the contents of a
+ ** valid conch file), try to match the permissions of the database
+ */
+ if( rc==SQLITE_OK && createConch ){
+ struct stat buf;
+ int err = osFstat(pFile->h, &buf);
+ if( err==0 ){
+ mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
+ S_IROTH|S_IWOTH);
+ /* try to match the database file R/W permissions, ignore failure */
+#ifndef SQLITE_PROXY_DEBUG
+ osFchmod(conchFile->h, cmode);
+#else
+ do{
+ rc = osFchmod(conchFile->h, cmode);
+ }while( rc==(-1) && errno==EINTR );
+ if( rc!=0 ){
+ int code = errno;
+ fprintf(stderr, "fchmod %o FAILED with %d %s\n",
+ cmode, code, strerror(code));
+ } else {
+ fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
+ }
+ }else{
+ int code = errno;
+ fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
+ err, code, strerror(code));
+#endif
+ }
+ }
+ }
+ conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
+
+ end_takeconch:
+ OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
+ if( rc==SQLITE_OK && pFile->openFlags ){
+ int fd;
+ if( pFile->h>=0 ){
+ robust_close(pFile, pFile->h, __LINE__);
+ }
+ pFile->h = -1;
+ fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
+ OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
+ if( fd>=0 ){
+ pFile->h = fd;
+ }else{
+ rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
+ during locking */
+ }
+ }
+ if( rc==SQLITE_OK && !pCtx->lockProxy ){
+ char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
+ rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
+ if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
+ /* we couldn't create the proxy lock file with the old lock file path
+ ** so try again via auto-naming
+ */
+ forceNewLockPath = 1;
+ tryOldLockPath = 0;
+ continue; /* go back to the do {} while start point, try again */
+ }
+ }
+ if( rc==SQLITE_OK ){
+ /* Need to make a copy of path if we extracted the value
+ ** from the conch file or the path was allocated on the stack
+ */
+ if( tempLockPath ){
+ pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
+ if( !pCtx->lockProxyPath ){
+ rc = SQLITE_NOMEM_BKPT;
+ }
+ }
+ }
+ if( rc==SQLITE_OK ){
+ pCtx->conchHeld = 1;
+
+ if( pCtx->lockProxy->pMethod == &afpIoMethods ){
+ afpLockingContext *afpCtx;
+ afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
+ afpCtx->dbPath = pCtx->lockProxyPath;
+ }
+ } else {
+ conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
+ }
+ OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
+ rc==SQLITE_OK?"ok":"failed"));
+ return rc;
+ } while (1); /* in case we need to retry the :auto: lock file -
+ ** we should never get here except via the 'continue' call. */
+ }
+}
+
+/*
+** If pFile holds a lock on a conch file, then release that lock.
+*/
+static int proxyReleaseConch(unixFile *pFile){
+ int rc = SQLITE_OK; /* Subroutine return code */
+ proxyLockingContext *pCtx; /* The locking context for the proxy lock */
+ unixFile *conchFile; /* Name of the conch file */
+
+ pCtx = (proxyLockingContext *)pFile->lockingContext;
+ conchFile = pCtx->conchFile;
+ OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
+ (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
+ osGetpid(0)));
+ if( pCtx->conchHeld>0 ){
+ rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
+ }
+ pCtx->conchHeld = 0;
+ OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
+ (rc==SQLITE_OK ? "ok" : "failed")));
+ return rc;
+}
+
+/*
+** Given the name of a database file, compute the name of its conch file.
+** Store the conch filename in memory obtained from sqlite3_malloc64().
+** Make *pConchPath point to the new name. Return SQLITE_OK on success
+** or SQLITE_NOMEM if unable to obtain memory.
+**
+** The caller is responsible for ensuring that the allocated memory
+** space is eventually freed.
+**
+** *pConchPath is set to NULL if a memory allocation error occurs.
+*/
+static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
+ int i; /* Loop counter */
+ int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
+ char *conchPath; /* buffer in which to construct conch name */
+
+ /* Allocate space for the conch filename and initialize the name to
+ ** the name of the original database file. */
+ *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
+ if( conchPath==0 ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ memcpy(conchPath, dbPath, len+1);
+
+ /* now insert a "." before the last / character */
+ for( i=(len-1); i>=0; i-- ){
+ if( conchPath[i]=='/' ){
+ i++;
+ break;
+ }
+ }
+ conchPath[i]='.';
+ while ( i<len ){
+ conchPath[i+1]=dbPath[i];
+ i++;
+ }
+
+ /* append the "-conch" suffix to the file */
+ memcpy(&conchPath[i+1], "-conch", 7);
+ assert( (int)strlen(conchPath) == len+7 );
+
+ return SQLITE_OK;
+}
+
+
+/* Takes a fully configured proxy locking-style unix file and switches
+** the local lock file path
+*/
+static int switchLockProxyPath(unixFile *pFile, const char *path) {
+ proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
+ char *oldPath = pCtx->lockProxyPath;
+ int rc = SQLITE_OK;
+
+ if( pFile->eFileLock!=NO_LOCK ){
+ return SQLITE_BUSY;
+ }
+
+ /* nothing to do if the path is NULL, :auto: or matches the existing path */
+ if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
+ (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
+ return SQLITE_OK;
+ }else{
+ unixFile *lockProxy = pCtx->lockProxy;
+ pCtx->lockProxy=NULL;
+ pCtx->conchHeld = 0;
+ if( lockProxy!=NULL ){
+ rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
+ if( rc ) return rc;
+ sqlite3_free(lockProxy);
+ }
+ sqlite3_free(oldPath);
+ pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
+ }
+
+ return rc;
+}
+
+/*
+** pFile is a file that has been opened by a prior xOpen call. dbPath
+** is a string buffer at least MAXPATHLEN+1 characters in size.
+**
+** This routine find the filename associated with pFile and writes it
+** int dbPath.
+*/
+static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
+#if defined(__APPLE__)
+ if( pFile->pMethod == &afpIoMethods ){
+ /* afp style keeps a reference to the db path in the filePath field
+ ** of the struct */
+ assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
+ strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
+ MAXPATHLEN);
+ } else
+#endif
+ if( pFile->pMethod == &dotlockIoMethods ){
+ /* dot lock style uses the locking context to store the dot lock
+ ** file path */
+ int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
+ memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
+ }else{
+ /* all other styles use the locking context to store the db file path */
+ assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
+ strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Takes an already filled in unix file and alters it so all file locking
+** will be performed on the local proxy lock file. The following fields
+** are preserved in the locking context so that they can be restored and
+** the unix structure properly cleaned up at close time:
+** ->lockingContext
+** ->pMethod
+*/
+static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
+ proxyLockingContext *pCtx;
+ char dbPath[MAXPATHLEN+1]; /* Name of the database file */
+ char *lockPath=NULL;
+ int rc = SQLITE_OK;
+
+ if( pFile->eFileLock!=NO_LOCK ){
+ return SQLITE_BUSY;
+ }
+ proxyGetDbPathForUnixFile(pFile, dbPath);
+ if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
+ lockPath=NULL;
+ }else{
+ lockPath=(char *)path;
+ }
+
+ OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
+ (lockPath ? lockPath : ":auto:"), osGetpid(0)));
+
+ pCtx = sqlite3_malloc64( sizeof(*pCtx) );
+ if( pCtx==0 ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ memset(pCtx, 0, sizeof(*pCtx));
+
+ rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
+ if( rc==SQLITE_OK ){
+ rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
+ if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
+ /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
+ ** (c) the file system is read-only, then enable no-locking access.
+ ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
+ ** that openFlags will have only one of O_RDONLY or O_RDWR.
+ */
+ struct statfs fsInfo;
+ struct stat conchInfo;
+ int goLockless = 0;
+
+ if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
+ int err = errno;
+ if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
+ goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
+ }
+ }
+ if( goLockless ){
+ pCtx->conchHeld = -1; /* read only FS/ lockless */
+ rc = SQLITE_OK;
+ }
+ }
+ }
+ if( rc==SQLITE_OK && lockPath ){
+ pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
+ }
+
+ if( rc==SQLITE_OK ){
+ pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
+ if( pCtx->dbPath==NULL ){
+ rc = SQLITE_NOMEM_BKPT;
+ }
+ }
+ if( rc==SQLITE_OK ){
+ /* all memory is allocated, proxys are created and assigned,
+ ** switch the locking context and pMethod then return.
+ */
+ pCtx->oldLockingContext = pFile->lockingContext;
+ pFile->lockingContext = pCtx;
+ pCtx->pOldMethod = pFile->pMethod;
+ pFile->pMethod = &proxyIoMethods;
+ }else{
+ if( pCtx->conchFile ){
+ pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
+ sqlite3_free(pCtx->conchFile);
+ }
+ sqlite3DbFree(0, pCtx->lockProxyPath);
+ sqlite3_free(pCtx->conchFilePath);
+ sqlite3_free(pCtx);
+ }
+ OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
+ (rc==SQLITE_OK ? "ok" : "failed")));
+ return rc;
+}
+
+
+/*
+** This routine handles sqlite3_file_control() calls that are specific
+** to proxy locking.
+*/
+static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
+ switch( op ){
+ case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
+ unixFile *pFile = (unixFile*)id;
+ if( pFile->pMethod == &proxyIoMethods ){
+ proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
+ proxyTakeConch(pFile);
+ if( pCtx->lockProxyPath ){
+ *(const char **)pArg = pCtx->lockProxyPath;
+ }else{
+ *(const char **)pArg = ":auto: (not held)";
+ }
+ } else {
+ *(const char **)pArg = NULL;
+ }
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
+ unixFile *pFile = (unixFile*)id;
+ int rc = SQLITE_OK;
+ int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
+ if( pArg==NULL || (const char *)pArg==0 ){
+ if( isProxyStyle ){
+ /* turn off proxy locking - not supported. If support is added for
+ ** switching proxy locking mode off then it will need to fail if
+ ** the journal mode is WAL mode.
+ */
+ rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
+ }else{
+ /* turn off proxy locking - already off - NOOP */
+ rc = SQLITE_OK;
+ }
+ }else{
+ const char *proxyPath = (const char *)pArg;
+ if( isProxyStyle ){
+ proxyLockingContext *pCtx =
+ (proxyLockingContext*)pFile->lockingContext;
+ if( !strcmp(pArg, ":auto:")
+ || (pCtx->lockProxyPath &&
+ !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
+ ){
+ rc = SQLITE_OK;
+ }else{
+ rc = switchLockProxyPath(pFile, proxyPath);
+ }
+ }else{
+ /* turn on proxy file locking */
+ rc = proxyTransformUnixFile(pFile, proxyPath);
+ }
+ }
+ return rc;
+ }
+ default: {
+ assert( 0 ); /* The call assures that only valid opcodes are sent */
+ }
+ }
+ /*NOTREACHED*/ assert(0);
+ return SQLITE_ERROR;
+}
+
+/*
+** Within this division (the proxying locking implementation) the procedures
+** above this point are all utilities. The lock-related methods of the
+** proxy-locking sqlite3_io_method object follow.
+*/
+
+
+/*
+** This routine checks if there is a RESERVED lock held on the specified
+** file by this or any other process. If such a lock is held, set *pResOut
+** to a non-zero value otherwise *pResOut is set to zero. The return value
+** is set to SQLITE_OK unless an I/O error occurs during lock checking.
+*/
+static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
+ unixFile *pFile = (unixFile*)id;
+ int rc = proxyTakeConch(pFile);
+ if( rc==SQLITE_OK ){
+ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
+ if( pCtx->conchHeld>0 ){
+ unixFile *proxy = pCtx->lockProxy;
+ return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
+ }else{ /* conchHeld < 0 is lockless */
+ pResOut=0;
+ }
+ }
+ return rc;
+}
+
+/*
+** Lock the file with the lock specified by parameter eFileLock - one
+** of the following:
+**
+** (1) SHARED_LOCK
+** (2) RESERVED_LOCK
+** (3) PENDING_LOCK
+** (4) EXCLUSIVE_LOCK
+**
+** Sometimes when requesting one lock state, additional lock states
+** are inserted in between. The locking might fail on one of the later
+** transitions leaving the lock state different from what it started but
+** still short of its goal. The following chart shows the allowed
+** transitions and the inserted intermediate states:
+**
+** UNLOCKED -> SHARED
+** SHARED -> RESERVED
+** SHARED -> (PENDING) -> EXCLUSIVE
+** RESERVED -> (PENDING) -> EXCLUSIVE
+** PENDING -> EXCLUSIVE
+**
+** This routine will only increase a lock. Use the sqlite3OsUnlock()
+** routine to lower a locking level.
+*/
+static int proxyLock(sqlite3_file *id, int eFileLock) {
+ unixFile *pFile = (unixFile*)id;
+ int rc = proxyTakeConch(pFile);
+ if( rc==SQLITE_OK ){
+ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
+ if( pCtx->conchHeld>0 ){
+ unixFile *proxy = pCtx->lockProxy;
+ rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
+ pFile->eFileLock = proxy->eFileLock;
+ }else{
+ /* conchHeld < 0 is lockless */
+ }
+ }
+ return rc;
+}
+
+
+/*
+** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
+** must be either NO_LOCK or SHARED_LOCK.
+**
+** If the locking level of the file descriptor is already at or below
+** the requested locking level, this routine is a no-op.
+*/
+static int proxyUnlock(sqlite3_file *id, int eFileLock) {
+ unixFile *pFile = (unixFile*)id;
+ int rc = proxyTakeConch(pFile);
+ if( rc==SQLITE_OK ){
+ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
+ if( pCtx->conchHeld>0 ){
+ unixFile *proxy = pCtx->lockProxy;
+ rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
+ pFile->eFileLock = proxy->eFileLock;
+ }else{
+ /* conchHeld < 0 is lockless */
+ }
+ }
+ return rc;
+}
+
+/*
+** Close a file that uses proxy locks.
+*/
+static int proxyClose(sqlite3_file *id) {
+ if( ALWAYS(id) ){
+ unixFile *pFile = (unixFile*)id;
+ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
+ unixFile *lockProxy = pCtx->lockProxy;
+ unixFile *conchFile = pCtx->conchFile;
+ int rc = SQLITE_OK;
+
+ if( lockProxy ){
+ rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
+ if( rc ) return rc;
+ rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
+ if( rc ) return rc;
+ sqlite3_free(lockProxy);
+ pCtx->lockProxy = 0;
+ }
+ if( conchFile ){
+ if( pCtx->conchHeld ){
+ rc = proxyReleaseConch(pFile);
+ if( rc ) return rc;
+ }
+ rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
+ if( rc ) return rc;
+ sqlite3_free(conchFile);
+ }
+ sqlite3DbFree(0, pCtx->lockProxyPath);
+ sqlite3_free(pCtx->conchFilePath);
+ sqlite3DbFree(0, pCtx->dbPath);
+ /* restore the original locking context and pMethod then close it */
+ pFile->lockingContext = pCtx->oldLockingContext;
+ pFile->pMethod = pCtx->pOldMethod;
+ sqlite3_free(pCtx);
+ return pFile->pMethod->xClose(id);
+ }
+ return SQLITE_OK;
+}
+
+
+
+#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
+/*
+** The proxy locking style is intended for use with AFP filesystems.
+** And since AFP is only supported on MacOSX, the proxy locking is also
+** restricted to MacOSX.
+**
+**
+******************* End of the proxy lock implementation **********************
+******************************************************************************/
+
+/*
+** Initialize the operating system interface.
+**
+** This routine registers all VFS implementations for unix-like operating
+** systems. This routine, and the sqlite3_os_end() routine that follows,
+** should be the only routines in this file that are visible from other
+** files.
+**
+** This routine is called once during SQLite initialization and by a
+** single thread. The memory allocation and mutex subsystems have not
+** necessarily been initialized when this routine is called, and so they
+** should not be used.
+*/
+SQLITE_API int sqlite3_os_init(void){
+ /*
+ ** The following macro defines an initializer for an sqlite3_vfs object.
+ ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
+ ** to the "finder" function. (pAppData is a pointer to a pointer because
+ ** silly C90 rules prohibit a void* from being cast to a function pointer
+ ** and so we have to go through the intermediate pointer to avoid problems
+ ** when compiling with -pedantic-errors on GCC.)
+ **
+ ** The FINDER parameter to this macro is the name of the pointer to the
+ ** finder-function. The finder-function returns a pointer to the
+ ** sqlite_io_methods object that implements the desired locking
+ ** behaviors. See the division above that contains the IOMETHODS
+ ** macro for addition information on finder-functions.
+ **
+ ** Most finders simply return a pointer to a fixed sqlite3_io_methods
+ ** object. But the "autolockIoFinder" available on MacOSX does a little
+ ** more than that; it looks at the filesystem type that hosts the
+ ** database file and tries to choose an locking method appropriate for
+ ** that filesystem time.
+ */
+ #define UNIXVFS(VFSNAME, FINDER) { \
+ 3, /* iVersion */ \
+ sizeof(unixFile), /* szOsFile */ \
+ MAX_PATHNAME, /* mxPathname */ \
+ 0, /* pNext */ \
+ VFSNAME, /* zName */ \
+ (void*)&FINDER, /* pAppData */ \
+ unixOpen, /* xOpen */ \
+ unixDelete, /* xDelete */ \
+ unixAccess, /* xAccess */ \
+ unixFullPathname, /* xFullPathname */ \
+ unixDlOpen, /* xDlOpen */ \
+ unixDlError, /* xDlError */ \
+ unixDlSym, /* xDlSym */ \
+ unixDlClose, /* xDlClose */ \
+ unixRandomness, /* xRandomness */ \
+ unixSleep, /* xSleep */ \
+ unixCurrentTime, /* xCurrentTime */ \
+ unixGetLastError, /* xGetLastError */ \
+ unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
+ unixSetSystemCall, /* xSetSystemCall */ \
+ unixGetSystemCall, /* xGetSystemCall */ \
+ unixNextSystemCall, /* xNextSystemCall */ \
+ }
+
+ /*
+ ** All default VFSes for unix are contained in the following array.
+ **
+ ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
+ ** by the SQLite core when the VFS is registered. So the following
+ ** array cannot be const.
+ */
+ static sqlite3_vfs aVfs[] = {
+#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
+ UNIXVFS("unix", autolockIoFinder ),
+#elif OS_VXWORKS
+ UNIXVFS("unix", vxworksIoFinder ),
+#else
+ UNIXVFS("unix", posixIoFinder ),
+#endif
+ UNIXVFS("unix-none", nolockIoFinder ),
+ UNIXVFS("unix-dotfile", dotlockIoFinder ),
+ UNIXVFS("unix-excl", posixIoFinder ),
+#if OS_VXWORKS
+ UNIXVFS("unix-namedsem", semIoFinder ),
+#endif
+#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
+ UNIXVFS("unix-posix", posixIoFinder ),
+#endif
+#if SQLITE_ENABLE_LOCKING_STYLE
+ UNIXVFS("unix-flock", flockIoFinder ),
+#endif
+#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
+ UNIXVFS("unix-afp", afpIoFinder ),
+ UNIXVFS("unix-nfs", nfsIoFinder ),
+ UNIXVFS("unix-proxy", proxyIoFinder ),
+#endif
+ };
+ unsigned int i; /* Loop counter */
+
+ /* Double-check that the aSyscall[] array has been constructed
+ ** correctly. See ticket [bb3a86e890c8e96ab] */
+ assert( ArraySize(aSyscall)==29 );
+
+ /* Register all VFSes defined in the aVfs[] array */
+ for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
+ sqlite3_vfs_register(&aVfs[i], i==0);
+ }
+ unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
+ return SQLITE_OK;
+}
+
+/*
+** Shutdown the operating system interface.
+**
+** Some operating systems might need to do some cleanup in this routine,
+** to release dynamically allocated objects. But not on unix.
+** This routine is a no-op for unix.
+*/
+SQLITE_API int sqlite3_os_end(void){
+ unixBigLock = 0;
+ return SQLITE_OK;
+}
+
+#endif /* SQLITE_OS_UNIX */
+
+/************** End of os_unix.c *********************************************/
+/************** Begin file os_win.c ******************************************/
+/*
+** 2004 May 22
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains code that is specific to Windows.
+*/
+/* #include "sqliteInt.h" */
+#if SQLITE_OS_WIN /* This file is used for Windows only */
+
+/*
+** Include code that is common to all os_*.c files
+*/
+/************** Include os_common.h in the middle of os_win.c ****************/
+/************** Begin file os_common.h ***************************************/
+/*
+** 2004 May 22
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains macros and a little bit of code that is common to
+** all of the platform-specific files (os_*.c) and is #included into those
+** files.
+**
+** This file should be #included by the os_*.c files only. It is not a
+** general purpose header file.
+*/
+#ifndef _OS_COMMON_H_
+#define _OS_COMMON_H_
+
+/*
+** At least two bugs have slipped in because we changed the MEMORY_DEBUG
+** macro to SQLITE_DEBUG and some older makefiles have not yet made the
+** switch. The following code should catch this problem at compile-time.
+*/
+#ifdef MEMORY_DEBUG
+# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
+#endif
+
+/*
+** Macros for performance tracing. Normally turned off. Only works
+** on i486 hardware.
+*/
+#ifdef SQLITE_PERFORMANCE_TRACE
+
+/*
+** hwtime.h contains inline assembler code for implementing
+** high-performance timing routines.
+*/
+/************** Include hwtime.h in the middle of os_common.h ****************/
+/************** Begin file hwtime.h ******************************************/
+/*
+** 2008 May 27
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains inline asm code for retrieving "high-performance"
+** counters for x86 and x86_64 class CPUs.
+*/
+#ifndef SQLITE_HWTIME_H
+#define SQLITE_HWTIME_H
+
+/*
+** The following routine only works on pentium-class (or newer) processors.
+** It uses the RDTSC opcode to read the cycle count value out of the
+** processor and returns that value. This can be used for high-res
+** profiling.
+*/
+#if !defined(__STRICT_ANSI__) && \
+ (defined(__GNUC__) || defined(_MSC_VER)) && \
+ (defined(i386) || defined(__i386__) || defined(_M_IX86))
+
+ #if defined(__GNUC__)
+
+ __inline__ sqlite_uint64 sqlite3Hwtime(void){
+ unsigned int lo, hi;
+ __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
+ return (sqlite_uint64)hi << 32 | lo;
+ }
+
+ #elif defined(_MSC_VER)
+
+ __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
+ __asm {
+ rdtsc
+ ret ; return value at EDX:EAX
+ }
+ }
+
+ #endif
+
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
+
+ __inline__ sqlite_uint64 sqlite3Hwtime(void){
+ unsigned long val;
+ __asm__ __volatile__ ("rdtsc" : "=A" (val));
+ return val;
+ }
+
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
+
+ __inline__ sqlite_uint64 sqlite3Hwtime(void){
+ unsigned long long retval;
+ unsigned long junk;
+ __asm__ __volatile__ ("\n\
+ 1: mftbu %1\n\
+ mftb %L0\n\
+ mftbu %0\n\
+ cmpw %0,%1\n\
+ bne 1b"
+ : "=r" (retval), "=r" (junk));
+ return retval;
+ }
+
+#else
+
+ /*
+ ** asm() is needed for hardware timing support. Without asm(),
+ ** disable the sqlite3Hwtime() routine.
+ **
+ ** sqlite3Hwtime() is only used for some obscure debugging
+ ** and analysis configurations, not in any deliverable, so this
+ ** should not be a great loss.
+ */
+SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
+
+#endif
+
+#endif /* !defined(SQLITE_HWTIME_H) */
+
+/************** End of hwtime.h **********************************************/
+/************** Continuing where we left off in os_common.h ******************/
+
+static sqlite_uint64 g_start;
+static sqlite_uint64 g_elapsed;
+#define TIMER_START g_start=sqlite3Hwtime()
+#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
+#define TIMER_ELAPSED g_elapsed
+#else
+#define TIMER_START
+#define TIMER_END
+#define TIMER_ELAPSED ((sqlite_uint64)0)
+#endif
+
+/*
+** If we compile with the SQLITE_TEST macro set, then the following block
+** of code will give us the ability to simulate a disk I/O error. This
+** is used for testing the I/O recovery logic.
+*/
+#if defined(SQLITE_TEST)
+SQLITE_API extern int sqlite3_io_error_hit;
+SQLITE_API extern int sqlite3_io_error_hardhit;
+SQLITE_API extern int sqlite3_io_error_pending;
+SQLITE_API extern int sqlite3_io_error_persist;
+SQLITE_API extern int sqlite3_io_error_benign;
+SQLITE_API extern int sqlite3_diskfull_pending;
+SQLITE_API extern int sqlite3_diskfull;
+#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
+#define SimulateIOError(CODE) \
+ if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
+ || sqlite3_io_error_pending-- == 1 ) \
+ { local_ioerr(); CODE; }
+static void local_ioerr(){
+ IOTRACE(("IOERR\n"));
+ sqlite3_io_error_hit++;
+ if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
+}
+#define SimulateDiskfullError(CODE) \
+ if( sqlite3_diskfull_pending ){ \
+ if( sqlite3_diskfull_pending == 1 ){ \
+ local_ioerr(); \
+ sqlite3_diskfull = 1; \
+ sqlite3_io_error_hit = 1; \
+ CODE; \
+ }else{ \
+ sqlite3_diskfull_pending--; \
+ } \
+ }
+#else
+#define SimulateIOErrorBenign(X)
+#define SimulateIOError(A)
+#define SimulateDiskfullError(A)
+#endif /* defined(SQLITE_TEST) */
+
+/*
+** When testing, keep a count of the number of open files.
+*/
+#if defined(SQLITE_TEST)
+SQLITE_API extern int sqlite3_open_file_count;
+#define OpenCounter(X) sqlite3_open_file_count+=(X)
+#else
+#define OpenCounter(X)
+#endif /* defined(SQLITE_TEST) */
+
+#endif /* !defined(_OS_COMMON_H_) */
+
+/************** End of os_common.h *******************************************/
+/************** Continuing where we left off in os_win.c *********************/
+
+/*
+** Include the header file for the Windows VFS.
+*/
+/* #include "os_win.h" */
+
+/*
+** Compiling and using WAL mode requires several APIs that are only
+** available in Windows platforms based on the NT kernel.
+*/
+#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
+# error "WAL mode requires support from the Windows NT kernel, compile\
+ with SQLITE_OMIT_WAL."
+#endif
+
+#if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
+# error "Memory mapped files require support from the Windows NT kernel,\
+ compile with SQLITE_MAX_MMAP_SIZE=0."
+#endif
+
+/*
+** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
+** based on the sub-platform)?
+*/
+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
+# define SQLITE_WIN32_HAS_ANSI
+#endif
+
+/*
+** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
+** based on the sub-platform)?
+*/
+#if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
+ !defined(SQLITE_WIN32_NO_WIDE)
+# define SQLITE_WIN32_HAS_WIDE
+#endif
+
+/*
+** Make sure at least one set of Win32 APIs is available.
+*/
+#if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
+# error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
+ must be defined."
+#endif
+
+/*
+** Define the required Windows SDK version constants if they are not
+** already available.
+*/
+#ifndef NTDDI_WIN8
+# define NTDDI_WIN8 0x06020000
+#endif
+
+#ifndef NTDDI_WINBLUE
+# define NTDDI_WINBLUE 0x06030000
+#endif
+
+#ifndef NTDDI_WINTHRESHOLD
+# define NTDDI_WINTHRESHOLD 0x06040000
+#endif
+
+/*
+** Check to see if the GetVersionEx[AW] functions are deprecated on the
+** target system. GetVersionEx was first deprecated in Win8.1.
+*/
+#ifndef SQLITE_WIN32_GETVERSIONEX
+# if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
+# define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
+# else
+# define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
+# endif
+#endif
+
+/*
+** Check to see if the CreateFileMappingA function is supported on the
+** target system. It is unavailable when using "mincore.lib" on Win10.
+** When compiling for Windows 10, always assume "mincore.lib" is in use.
+*/
+#ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
+# if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
+# define SQLITE_WIN32_CREATEFILEMAPPINGA 0
+# else
+# define SQLITE_WIN32_CREATEFILEMAPPINGA 1
+# endif
+#endif
+
+/*
+** This constant should already be defined (in the "WinDef.h" SDK file).
+*/
+#ifndef MAX_PATH
+# define MAX_PATH (260)
+#endif
+
+/*
+** Maximum pathname length (in chars) for Win32. This should normally be
+** MAX_PATH.
+*/
+#ifndef SQLITE_WIN32_MAX_PATH_CHARS
+# define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
+#endif
+
+/*
+** This constant should already be defined (in the "WinNT.h" SDK file).
+*/
+#ifndef UNICODE_STRING_MAX_CHARS
+# define UNICODE_STRING_MAX_CHARS (32767)
+#endif
+
+/*
+** Maximum pathname length (in chars) for WinNT. This should normally be
+** UNICODE_STRING_MAX_CHARS.
+*/
+#ifndef SQLITE_WINNT_MAX_PATH_CHARS
+# define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
+#endif
+
+/*
+** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
+** characters, so we allocate 4 bytes per character assuming worst-case of
+** 4-bytes-per-character for UTF8.
+*/
+#ifndef SQLITE_WIN32_MAX_PATH_BYTES
+# define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
+#endif
+
+/*
+** Maximum pathname length (in bytes) for WinNT. This should normally be
+** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
+*/
+#ifndef SQLITE_WINNT_MAX_PATH_BYTES
+# define SQLITE_WINNT_MAX_PATH_BYTES \
+ (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
+#endif
+
+/*
+** Maximum error message length (in chars) for WinRT.
+*/
+#ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
+# define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
+#endif
+
+/*
+** Returns non-zero if the character should be treated as a directory
+** separator.
+*/
+#ifndef winIsDirSep
+# define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
+#endif
+
+/*
+** This macro is used when a local variable is set to a value that is
+** [sometimes] not used by the code (e.g. via conditional compilation).
+*/
+#ifndef UNUSED_VARIABLE_VALUE
+# define UNUSED_VARIABLE_VALUE(x) (void)(x)
+#endif
+
+/*
+** Returns the character that should be used as the directory separator.
+*/
+#ifndef winGetDirSep
+# define winGetDirSep() '\\'
+#endif
+
+/*
+** Do we need to manually define the Win32 file mapping APIs for use with WAL
+** mode or memory mapped files (e.g. these APIs are available in the Windows
+** CE SDK; however, they are not present in the header file)?
+*/
+#if SQLITE_WIN32_FILEMAPPING_API && \
+ (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
+/*
+** Two of the file mapping APIs are different under WinRT. Figure out which
+** set we need.
+*/
+#if SQLITE_OS_WINRT
+WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
+ LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
+
+WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
+#else
+#if defined(SQLITE_WIN32_HAS_ANSI)
+WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
+ DWORD, DWORD, DWORD, LPCSTR);
+#endif /* defined(SQLITE_WIN32_HAS_ANSI) */
+
+#if defined(SQLITE_WIN32_HAS_WIDE)
+WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
+ DWORD, DWORD, DWORD, LPCWSTR);
+#endif /* defined(SQLITE_WIN32_HAS_WIDE) */
+
+WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
+#endif /* SQLITE_OS_WINRT */
+
+/*
+** These file mapping APIs are common to both Win32 and WinRT.
+*/
+
+WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
+WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
+#endif /* SQLITE_WIN32_FILEMAPPING_API */
+
+/*
+** Some Microsoft compilers lack this definition.
+*/
+#ifndef INVALID_FILE_ATTRIBUTES
+# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
+#endif
+
+#ifndef FILE_FLAG_MASK
+# define FILE_FLAG_MASK (0xFF3C0000)
+#endif
+
+#ifndef FILE_ATTRIBUTE_MASK
+# define FILE_ATTRIBUTE_MASK (0x0003FFF7)
+#endif
+
+#ifndef SQLITE_OMIT_WAL
+/* Forward references to structures used for WAL */
+typedef struct winShm winShm; /* A connection to shared-memory */
+typedef struct winShmNode winShmNode; /* A region of shared-memory */
+#endif
+
+/*
+** WinCE lacks native support for file locking so we have to fake it
+** with some code of our own.
+*/
+#if SQLITE_OS_WINCE
+typedef struct winceLock {
+ int nReaders; /* Number of reader locks obtained */
+ BOOL bPending; /* Indicates a pending lock has been obtained */
+ BOOL bReserved; /* Indicates a reserved lock has been obtained */
+ BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
+} winceLock;
+#endif
+
+/*
+** The winFile structure is a subclass of sqlite3_file* specific to the win32
+** portability layer.
+*/
+typedef struct winFile winFile;
+struct winFile {
+ const sqlite3_io_methods *pMethod; /*** Must be first ***/
+ sqlite3_vfs *pVfs; /* The VFS used to open this file */
+ HANDLE h; /* Handle for accessing the file */
+ u8 locktype; /* Type of lock currently held on this file */
+ short sharedLockByte; /* Randomly chosen byte used as a shared lock */
+ u8 ctrlFlags; /* Flags. See WINFILE_* below */
+ DWORD lastErrno; /* The Windows errno from the last I/O error */
+#ifndef SQLITE_OMIT_WAL
+ winShm *pShm; /* Instance of shared memory on this file */
+#endif
+ const char *zPath; /* Full pathname of this file */
+ int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
+#if SQLITE_OS_WINCE
+ LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
+ HANDLE hMutex; /* Mutex used to control access to shared lock */
+ HANDLE hShared; /* Shared memory segment used for locking */
+ winceLock local; /* Locks obtained by this instance of winFile */
+ winceLock *shared; /* Global shared lock memory for the file */
+#endif
+#if SQLITE_MAX_MMAP_SIZE>0
+ int nFetchOut; /* Number of outstanding xFetch references */
+ HANDLE hMap; /* Handle for accessing memory mapping */
+ void *pMapRegion; /* Area memory mapped */
+ sqlite3_int64 mmapSize; /* Size of mapped region */
+ sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
+#endif
+};
+
+/*
+** The winVfsAppData structure is used for the pAppData member for all of the
+** Win32 VFS variants.
+*/
+typedef struct winVfsAppData winVfsAppData;
+struct winVfsAppData {
+ const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
+ void *pAppData; /* The extra pAppData, if any. */
+ BOOL bNoLock; /* Non-zero if locking is disabled. */
+};
+
+/*
+** Allowed values for winFile.ctrlFlags
+*/
+#define WINFILE_RDONLY 0x02 /* Connection is read only */
+#define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
+#define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
+
+/*
+ * The size of the buffer used by sqlite3_win32_write_debug().
+ */
+#ifndef SQLITE_WIN32_DBG_BUF_SIZE
+# define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
+#endif
+
+/*
+ * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
+ * various Win32 API heap functions instead of our own.
+ */
+#ifdef SQLITE_WIN32_MALLOC
+
+/*
+ * If this is non-zero, an isolated heap will be created by the native Win32
+ * allocator subsystem; otherwise, the default process heap will be used. This
+ * setting has no effect when compiling for WinRT. By default, this is enabled
+ * and an isolated heap will be created to store all allocated data.
+ *
+ ******************************************************************************
+ * WARNING: It is important to note that when this setting is non-zero and the
+ * winMemShutdown function is called (e.g. by the sqlite3_shutdown
+ * function), all data that was allocated using the isolated heap will
+ * be freed immediately and any attempt to access any of that freed
+ * data will almost certainly result in an immediate access violation.
+ ******************************************************************************
+ */
+#ifndef SQLITE_WIN32_HEAP_CREATE
+# define SQLITE_WIN32_HEAP_CREATE (TRUE)
+#endif
+
+/*
+ * This is the maximum possible initial size of the Win32-specific heap, in
+ * bytes.
+ */
+#ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
+# define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
+#endif
+
+/*
+ * This is the extra space for the initial size of the Win32-specific heap,
+ * in bytes. This value may be zero.
+ */
+#ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
+# define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
+#endif
+
+/*
+ * Calculate the maximum legal cache size, in pages, based on the maximum
+ * possible initial heap size and the default page size, setting aside the
+ * needed extra space.
+ */
+#ifndef SQLITE_WIN32_MAX_CACHE_SIZE
+# define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
+ (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
+ (SQLITE_DEFAULT_PAGE_SIZE))
+#endif
+
+/*
+ * This is cache size used in the calculation of the initial size of the
+ * Win32-specific heap. It cannot be negative.
+ */
+#ifndef SQLITE_WIN32_CACHE_SIZE
+# if SQLITE_DEFAULT_CACHE_SIZE>=0
+# define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
+# else
+# define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
+# endif
+#endif
+
+/*
+ * Make sure that the calculated cache size, in pages, cannot cause the
+ * initial size of the Win32-specific heap to exceed the maximum amount
+ * of memory that can be specified in the call to HeapCreate.
+ */
+#if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
+# undef SQLITE_WIN32_CACHE_SIZE
+# define SQLITE_WIN32_CACHE_SIZE (2000)
+#endif
+
+/*
+ * The initial size of the Win32-specific heap. This value may be zero.
+ */
+#ifndef SQLITE_WIN32_HEAP_INIT_SIZE
+# define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
+ (SQLITE_DEFAULT_PAGE_SIZE) + \
+ (SQLITE_WIN32_HEAP_INIT_EXTRA))
+#endif
+
+/*
+ * The maximum size of the Win32-specific heap. This value may be zero.
+ */
+#ifndef SQLITE_WIN32_HEAP_MAX_SIZE
+# define SQLITE_WIN32_HEAP_MAX_SIZE (0)
+#endif
+
+/*
+ * The extra flags to use in calls to the Win32 heap APIs. This value may be
+ * zero for the default behavior.
+ */
+#ifndef SQLITE_WIN32_HEAP_FLAGS
+# define SQLITE_WIN32_HEAP_FLAGS (0)
+#endif
+
+
+/*
+** The winMemData structure stores information required by the Win32-specific
+** sqlite3_mem_methods implementation.
+*/
+typedef struct winMemData winMemData;
+struct winMemData {
+#ifndef NDEBUG
+ u32 magic1; /* Magic number to detect structure corruption. */
+#endif
+ HANDLE hHeap; /* The handle to our heap. */
+ BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
+#ifndef NDEBUG
+ u32 magic2; /* Magic number to detect structure corruption. */
+#endif
+};
+
+#ifndef NDEBUG
+#define WINMEM_MAGIC1 0x42b2830b
+#define WINMEM_MAGIC2 0xbd4d7cf4
+#endif
+
+static struct winMemData win_mem_data = {
+#ifndef NDEBUG
+ WINMEM_MAGIC1,
+#endif
+ NULL, FALSE
+#ifndef NDEBUG
+ ,WINMEM_MAGIC2
+#endif
+};
+
+#ifndef NDEBUG
+#define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
+#define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
+#define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
+#else
+#define winMemAssertMagic()
+#endif
+
+#define winMemGetDataPtr() &win_mem_data
+#define winMemGetHeap() win_mem_data.hHeap
+#define winMemGetOwned() win_mem_data.bOwned
+
+static void *winMemMalloc(int nBytes);
+static void winMemFree(void *pPrior);
+static void *winMemRealloc(void *pPrior, int nBytes);
+static int winMemSize(void *p);
+static int winMemRoundup(int n);
+static int winMemInit(void *pAppData);
+static void winMemShutdown(void *pAppData);
+
+SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
+#endif /* SQLITE_WIN32_MALLOC */
+
+/*
+** The following variable is (normally) set once and never changes
+** thereafter. It records whether the operating system is Win9x
+** or WinNT.
+**
+** 0: Operating system unknown.
+** 1: Operating system is Win9x.
+** 2: Operating system is WinNT.
+**
+** In order to facilitate testing on a WinNT system, the test fixture
+** can manually set this value to 1 to emulate Win98 behavior.
+*/
+#ifdef SQLITE_TEST
+SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
+#else
+static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
+#endif
+
+#ifndef SYSCALL
+# define SYSCALL sqlite3_syscall_ptr
+#endif
+
+/*
+** This function is not available on Windows CE or WinRT.
+ */
+
+#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
+# define osAreFileApisANSI() 1
+#endif
+
+/*
+** Many system calls are accessed through pointer-to-functions so that
+** they may be overridden at runtime to facilitate fault injection during
+** testing and sandboxing. The following array holds the names and pointers
+** to all overrideable system calls.
+*/
+static struct win_syscall {
+ const char *zName; /* Name of the system call */
+ sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
+ sqlite3_syscall_ptr pDefault; /* Default value */
+} aSyscall[] = {
+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
+ { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
+#else
+ { "AreFileApisANSI", (SYSCALL)0, 0 },
+#endif
+
+#ifndef osAreFileApisANSI
+#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
+#endif
+
+#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
+ { "CharLowerW", (SYSCALL)CharLowerW, 0 },
+#else
+ { "CharLowerW", (SYSCALL)0, 0 },
+#endif
+
+#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
+
+#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
+ { "CharUpperW", (SYSCALL)CharUpperW, 0 },
+#else
+ { "CharUpperW", (SYSCALL)0, 0 },
+#endif
+
+#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
+
+ { "CloseHandle", (SYSCALL)CloseHandle, 0 },
+
+#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
+
+#if defined(SQLITE_WIN32_HAS_ANSI)
+ { "CreateFileA", (SYSCALL)CreateFileA, 0 },
+#else
+ { "CreateFileA", (SYSCALL)0, 0 },
+#endif
+
+#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
+ LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
+
+#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
+ { "CreateFileW", (SYSCALL)CreateFileW, 0 },
+#else
+ { "CreateFileW", (SYSCALL)0, 0 },
+#endif
+
+#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
+ LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
+
+#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
+ (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
+ SQLITE_WIN32_CREATEFILEMAPPINGA
+ { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
+#else
+ { "CreateFileMappingA", (SYSCALL)0, 0 },
+#endif
+
+#define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
+ DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
+
+#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
+ (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
+ { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
+#else
+ { "CreateFileMappingW", (SYSCALL)0, 0 },
+#endif
+
+#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
+ DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
+
+#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
+ { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
+#else
+ { "CreateMutexW", (SYSCALL)0, 0 },
+#endif
+
+#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
+ LPCWSTR))aSyscall[8].pCurrent)
+
+#if defined(SQLITE_WIN32_HAS_ANSI)
+ { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
+#else
+ { "DeleteFileA", (SYSCALL)0, 0 },
+#endif
+
+#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
+
+#if defined(SQLITE_WIN32_HAS_WIDE)
+ { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
+#else
+ { "DeleteFileW", (SYSCALL)0, 0 },
+#endif
+
+#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
+
+#if SQLITE_OS_WINCE
+ { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
+#else
+ { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
+#endif
+
+#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
+ LPFILETIME))aSyscall[11].pCurrent)
+
+#if SQLITE_OS_WINCE
+ { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
+#else
+ { "FileTimeToSystemTime", (SYSCALL)0, 0 },
+#endif
+
+#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
+ LPSYSTEMTIME))aSyscall[12].pCurrent)
+
+ { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
+
+#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
+
+#if defined(SQLITE_WIN32_HAS_ANSI)
+ { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
+#else
+ { "FormatMessageA", (SYSCALL)0, 0 },
+#endif
+
+#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
+ DWORD,va_list*))aSyscall[14].pCurrent)
+
+#if defined(SQLITE_WIN32_HAS_WIDE)
+ { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
+#else
+ { "FormatMessageW", (SYSCALL)0, 0 },
+#endif
+
+#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
+ DWORD,va_list*))aSyscall[15].pCurrent)
+
+#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
+ { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
+#else
+ { "FreeLibrary", (SYSCALL)0, 0 },
+#endif
+
+#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
+
+ { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
+
+#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
+
+#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
+ { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
+#else
+ { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
+#endif
+
+#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
+ LPDWORD))aSyscall[18].pCurrent)
+
+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
+ { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
+#else
+ { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
+#endif
+
+#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
+ LPDWORD))aSyscall[19].pCurrent)
+
+#if defined(SQLITE_WIN32_HAS_ANSI)
+ { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
+#else
+ { "GetFileAttributesA", (SYSCALL)0, 0 },
+#endif
+
+#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
+
+#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
+ { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
+#else
+ { "GetFileAttributesW", (SYSCALL)0, 0 },
+#endif
+
+#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
+
+#if defined(SQLITE_WIN32_HAS_WIDE)
+ { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
+#else
+ { "GetFileAttributesExW", (SYSCALL)0, 0 },
+#endif
+
+#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
+ LPVOID))aSyscall[22].pCurrent)
+
+#if !SQLITE_OS_WINRT
+ { "GetFileSize", (SYSCALL)GetFileSize, 0 },
+#else
+ { "GetFileSize", (SYSCALL)0, 0 },
+#endif
+
+#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
+
+#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
+ { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
+#else
+ { "GetFullPathNameA", (SYSCALL)0, 0 },
+#endif
+
+#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
+ LPSTR*))aSyscall[24].pCurrent)
+
+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
+ { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
+#else
+ { "GetFullPathNameW", (SYSCALL)0, 0 },
+#endif
+
+#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
+ LPWSTR*))aSyscall[25].pCurrent)
+
+ { "GetLastError", (SYSCALL)GetLastError, 0 },
+
+#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
+
+#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
+#if SQLITE_OS_WINCE
+ /* The GetProcAddressA() routine is only available on Windows CE. */
+ { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
+#else
+ /* All other Windows platforms expect GetProcAddress() to take
+ ** an ANSI string regardless of the _UNICODE setting */
+ { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
+#endif
+#else
+ { "GetProcAddressA", (SYSCALL)0, 0 },
+#endif
+
+#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
+ LPCSTR))aSyscall[27].pCurrent)
+
+#if !SQLITE_OS_WINRT
+ { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
+#else
+ { "GetSystemInfo", (SYSCALL)0, 0 },
+#endif
+
+#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
+
+ { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
+
+#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
+
+#if !SQLITE_OS_WINCE
+ { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
+#else
+ { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
+#endif
+
+#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
+ LPFILETIME))aSyscall[30].pCurrent)
+
+#if defined(SQLITE_WIN32_HAS_ANSI)
+ { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
+#else
+ { "GetTempPathA", (SYSCALL)0, 0 },
+#endif
+
+#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
+
+#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
+ { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
+#else
+ { "GetTempPathW", (SYSCALL)0, 0 },
+#endif
+
+#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
+
+#if !SQLITE_OS_WINRT
+ { "GetTickCount", (SYSCALL)GetTickCount, 0 },
+#else
+ { "GetTickCount", (SYSCALL)0, 0 },
+#endif
+
+#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
+
+#if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
+ { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
+#else
+ { "GetVersionExA", (SYSCALL)0, 0 },
+#endif
+
+#define osGetVersionExA ((BOOL(WINAPI*)( \
+ LPOSVERSIONINFOA))aSyscall[34].pCurrent)
+
+#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
+ SQLITE_WIN32_GETVERSIONEX
+ { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
+#else
+ { "GetVersionExW", (SYSCALL)0, 0 },
+#endif
+
+#define osGetVersionExW ((BOOL(WINAPI*)( \
+ LPOSVERSIONINFOW))aSyscall[35].pCurrent)
+
+ { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
+
+#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
+ SIZE_T))aSyscall[36].pCurrent)
+
+#if !SQLITE_OS_WINRT
+ { "HeapCreate", (SYSCALL)HeapCreate, 0 },
+#else
+ { "HeapCreate", (SYSCALL)0, 0 },
+#endif
+
+#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
+ SIZE_T))aSyscall[37].pCurrent)
+
+#if !SQLITE_OS_WINRT
+ { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
+#else
+ { "HeapDestroy", (SYSCALL)0, 0 },
+#endif
+
+#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
+
+ { "HeapFree", (SYSCALL)HeapFree, 0 },
+
+#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
+
+ { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
+
+#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
+ SIZE_T))aSyscall[40].pCurrent)
+
+ { "HeapSize", (SYSCALL)HeapSize, 0 },
+
+#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
+ LPCVOID))aSyscall[41].pCurrent)
+
+#if !SQLITE_OS_WINRT
+ { "HeapValidate", (SYSCALL)HeapValidate, 0 },
+#else
+ { "HeapValidate", (SYSCALL)0, 0 },
+#endif
+
+#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
+ LPCVOID))aSyscall[42].pCurrent)
+
+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
+ { "HeapCompact", (SYSCALL)HeapCompact, 0 },
+#else
+ { "HeapCompact", (SYSCALL)0, 0 },
+#endif
+
+#define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
+
+#if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
+ { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
+#else
+ { "LoadLibraryA", (SYSCALL)0, 0 },
+#endif
+
+#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
+
+#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
+ !defined(SQLITE_OMIT_LOAD_EXTENSION)
+ { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
+#else
+ { "LoadLibraryW", (SYSCALL)0, 0 },
+#endif
+
+#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
+
+#if !SQLITE_OS_WINRT
+ { "LocalFree", (SYSCALL)LocalFree, 0 },
+#else
+ { "LocalFree", (SYSCALL)0, 0 },
+#endif
+
+#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
+
+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
+ { "LockFile", (SYSCALL)LockFile, 0 },
+#else
+ { "LockFile", (SYSCALL)0, 0 },
+#endif
+
+#ifndef osLockFile
+#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
+ DWORD))aSyscall[47].pCurrent)
+#endif
+
+#if !SQLITE_OS_WINCE
+ { "LockFileEx", (SYSCALL)LockFileEx, 0 },
+#else
+ { "LockFileEx", (SYSCALL)0, 0 },
+#endif
+
+#ifndef osLockFileEx
+#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
+ LPOVERLAPPED))aSyscall[48].pCurrent)
+#endif
+
+#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
+ (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
+ { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
+#else
+ { "MapViewOfFile", (SYSCALL)0, 0 },
+#endif
+
+#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
+ SIZE_T))aSyscall[49].pCurrent)
+
+ { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
+
+#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
+ int))aSyscall[50].pCurrent)
+
+ { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
+
+#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
+ LARGE_INTEGER*))aSyscall[51].pCurrent)
+
+ { "ReadFile", (SYSCALL)ReadFile, 0 },
+
+#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
+ LPOVERLAPPED))aSyscall[52].pCurrent)
+
+ { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
+
+#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
+
+#if !SQLITE_OS_WINRT
+ { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
+#else
+ { "SetFilePointer", (SYSCALL)0, 0 },
+#endif
+
+#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
+ DWORD))aSyscall[54].pCurrent)
+
+#if !SQLITE_OS_WINRT
+ { "Sleep", (SYSCALL)Sleep, 0 },
+#else
+ { "Sleep", (SYSCALL)0, 0 },
+#endif
+
+#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
+
+ { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
+
+#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
+ LPFILETIME))aSyscall[56].pCurrent)
+
+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
+ { "UnlockFile", (SYSCALL)UnlockFile, 0 },
+#else
+ { "UnlockFile", (SYSCALL)0, 0 },
+#endif
+
+#ifndef osUnlockFile
+#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
+ DWORD))aSyscall[57].pCurrent)
+#endif
+
+#if !SQLITE_OS_WINCE
+ { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
+#else
+ { "UnlockFileEx", (SYSCALL)0, 0 },
+#endif
+
+#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
+ LPOVERLAPPED))aSyscall[58].pCurrent)
+
+#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
+ { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
+#else
+ { "UnmapViewOfFile", (SYSCALL)0, 0 },
+#endif
+
+#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
+
+ { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
+
+#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
+ LPCSTR,LPBOOL))aSyscall[60].pCurrent)
+
+ { "WriteFile", (SYSCALL)WriteFile, 0 },
+
+#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
+ LPOVERLAPPED))aSyscall[61].pCurrent)
+
+#if SQLITE_OS_WINRT
+ { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
+#else
+ { "CreateEventExW", (SYSCALL)0, 0 },
+#endif
+
+#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
+ DWORD,DWORD))aSyscall[62].pCurrent)
+
+#if !SQLITE_OS_WINRT
+ { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
+#else
+ { "WaitForSingleObject", (SYSCALL)0, 0 },
+#endif
+
+#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
+ DWORD))aSyscall[63].pCurrent)
+
+#if !SQLITE_OS_WINCE
+ { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
+#else
+ { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
+#endif
+
+#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
+ BOOL))aSyscall[64].pCurrent)
+
+#if SQLITE_OS_WINRT
+ { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
+#else
+ { "SetFilePointerEx", (SYSCALL)0, 0 },
+#endif
+
+#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
+ PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
+
+#if SQLITE_OS_WINRT
+ { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
+#else
+ { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
+#endif
+
+#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
+ FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
+
+#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
+ { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
+#else
+ { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
+#endif
+
+#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
+ SIZE_T))aSyscall[67].pCurrent)
+
+#if SQLITE_OS_WINRT
+ { "CreateFile2", (SYSCALL)CreateFile2, 0 },
+#else
+ { "CreateFile2", (SYSCALL)0, 0 },
+#endif
+
+#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
+ LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
+
+#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
+ { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
+#else
+ { "LoadPackagedLibrary", (SYSCALL)0, 0 },
+#endif
+
+#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
+ DWORD))aSyscall[69].pCurrent)
+
+#if SQLITE_OS_WINRT
+ { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
+#else
+ { "GetTickCount64", (SYSCALL)0, 0 },
+#endif
+
+#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
+
+#if SQLITE_OS_WINRT
+ { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
+#else
+ { "GetNativeSystemInfo", (SYSCALL)0, 0 },
+#endif
+
+#define osGetNativeSystemInfo ((VOID(WINAPI*)( \
+ LPSYSTEM_INFO))aSyscall[71].pCurrent)
+
+#if defined(SQLITE_WIN32_HAS_ANSI)
+ { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
+#else
+ { "OutputDebugStringA", (SYSCALL)0, 0 },
+#endif
+
+#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
+
+#if defined(SQLITE_WIN32_HAS_WIDE)
+ { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
+#else
+ { "OutputDebugStringW", (SYSCALL)0, 0 },
+#endif
+
+#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
+
+ { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
+
+#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
+
+#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
+ { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
+#else
+ { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
+#endif
+
+#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
+ LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
+
+/*
+** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
+** is really just a macro that uses a compiler intrinsic (e.g. x64).
+** So do not try to make this is into a redefinable interface.
+*/
+#if defined(InterlockedCompareExchange)
+ { "InterlockedCompareExchange", (SYSCALL)0, 0 },
+
+#define osInterlockedCompareExchange InterlockedCompareExchange
+#else
+ { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
+
+#define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
+ SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
+#endif /* defined(InterlockedCompareExchange) */
+
+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
+ { "UuidCreate", (SYSCALL)UuidCreate, 0 },
+#else
+ { "UuidCreate", (SYSCALL)0, 0 },
+#endif
+
+#define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
+
+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
+ { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
+#else
+ { "UuidCreateSequential", (SYSCALL)0, 0 },
+#endif
+
+#define osUuidCreateSequential \
+ ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
+
+#if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
+ { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
+#else
+ { "FlushViewOfFile", (SYSCALL)0, 0 },
+#endif
+
+#define osFlushViewOfFile \
+ ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
+
+}; /* End of the overrideable system calls */
+
+/*
+** This is the xSetSystemCall() method of sqlite3_vfs for all of the
+** "win32" VFSes. Return SQLITE_OK opon successfully updating the
+** system call pointer, or SQLITE_NOTFOUND if there is no configurable
+** system call named zName.
+*/
+static int winSetSystemCall(
+ sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
+ const char *zName, /* Name of system call to override */
+ sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
+){
+ unsigned int i;
+ int rc = SQLITE_NOTFOUND;
+
+ UNUSED_PARAMETER(pNotUsed);
+ if( zName==0 ){
+ /* If no zName is given, restore all system calls to their default
+ ** settings and return NULL
+ */
+ rc = SQLITE_OK;
+ for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
+ if( aSyscall[i].pDefault ){
+ aSyscall[i].pCurrent = aSyscall[i].pDefault;
+ }
+ }
+ }else{
+ /* If zName is specified, operate on only the one system call
+ ** specified.
+ */
+ for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
+ if( strcmp(zName, aSyscall[i].zName)==0 ){
+ if( aSyscall[i].pDefault==0 ){
+ aSyscall[i].pDefault = aSyscall[i].pCurrent;
+ }
+ rc = SQLITE_OK;
+ if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
+ aSyscall[i].pCurrent = pNewFunc;
+ break;
+ }
+ }
+ }
+ return rc;
+}
+
+/*
+** Return the value of a system call. Return NULL if zName is not a
+** recognized system call name. NULL is also returned if the system call
+** is currently undefined.
+*/
+static sqlite3_syscall_ptr winGetSystemCall(
+ sqlite3_vfs *pNotUsed,
+ const char *zName
+){
+ unsigned int i;
+
+ UNUSED_PARAMETER(pNotUsed);
+ for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
+ if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
+ }
+ return 0;
+}
+
+/*
+** Return the name of the first system call after zName. If zName==NULL
+** then return the name of the first system call. Return NULL if zName
+** is the last system call or if zName is not the name of a valid
+** system call.
+*/
+static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
+ int i = -1;
+
+ UNUSED_PARAMETER(p);
+ if( zName ){
+ for(i=0; i<ArraySize(aSyscall)-1; i++){
+ if( strcmp(zName, aSyscall[i].zName)==0 ) break;
+ }
+ }
+ for(i++; i<ArraySize(aSyscall); i++){
+ if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
+ }
+ return 0;
+}
+
+#ifdef SQLITE_WIN32_MALLOC
+/*
+** If a Win32 native heap has been configured, this function will attempt to
+** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
+** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
+** "pnLargest" argument, if non-zero, will be used to return the size of the
+** largest committed free block in the heap, in bytes.
+*/
+SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
+ int rc = SQLITE_OK;
+ UINT nLargest = 0;
+ HANDLE hHeap;
+
+ winMemAssertMagic();
+ hHeap = winMemGetHeap();
+ assert( hHeap!=0 );
+ assert( hHeap!=INVALID_HANDLE_VALUE );
+#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
+ assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
+#endif
+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
+ if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
+ DWORD lastErrno = osGetLastError();
+ if( lastErrno==NO_ERROR ){
+ sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
+ (void*)hHeap);
+ rc = SQLITE_NOMEM_BKPT;
+ }else{
+ sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
+ osGetLastError(), (void*)hHeap);
+ rc = SQLITE_ERROR;
+ }
+ }
+#else
+ sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
+ (void*)hHeap);
+ rc = SQLITE_NOTFOUND;
+#endif
+ if( pnLargest ) *pnLargest = nLargest;
+ return rc;
+}
+
+/*
+** If a Win32 native heap has been configured, this function will attempt to
+** destroy and recreate it. If the Win32 native heap is not isolated and/or
+** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
+** be returned and no changes will be made to the Win32 native heap.
+*/
+SQLITE_API int sqlite3_win32_reset_heap(){
+ int rc;
+ MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */
+ MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
+ MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
+ MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
+ sqlite3_mutex_enter(pMainMtx);
+ sqlite3_mutex_enter(pMem);
+ winMemAssertMagic();
+ if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
+ /*
+ ** At this point, there should be no outstanding memory allocations on
+ ** the heap. Also, since both the main and memsys locks are currently
+ ** being held by us, no other function (i.e. from another thread) should
+ ** be able to even access the heap. Attempt to destroy and recreate our
+ ** isolated Win32 native heap now.
+ */
+ assert( winMemGetHeap()!=NULL );
+ assert( winMemGetOwned() );
+ assert( sqlite3_memory_used()==0 );
+ winMemShutdown(winMemGetDataPtr());
+ assert( winMemGetHeap()==NULL );
+ assert( !winMemGetOwned() );
+ assert( sqlite3_memory_used()==0 );
+ rc = winMemInit(winMemGetDataPtr());
+ assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
+ assert( rc!=SQLITE_OK || winMemGetOwned() );
+ assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
+ }else{
+ /*
+ ** The Win32 native heap cannot be modified because it may be in use.
+ */
+ rc = SQLITE_BUSY;
+ }
+ sqlite3_mutex_leave(pMem);
+ sqlite3_mutex_leave(pMainMtx);
+ return rc;
+}
+#endif /* SQLITE_WIN32_MALLOC */
+
+/*
+** This function outputs the specified (ANSI) string to the Win32 debugger
+** (if available).
+*/
+
+SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
+ char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
+ int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
+ if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
+ assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !zBuf ){
+ (void)SQLITE_MISUSE_BKPT;
+ return;
+ }
+#endif
+#if defined(SQLITE_WIN32_HAS_ANSI)
+ if( nMin>0 ){
+ memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
+ memcpy(zDbgBuf, zBuf, nMin);
+ osOutputDebugStringA(zDbgBuf);
+ }else{
+ osOutputDebugStringA(zBuf);
+ }
+#elif defined(SQLITE_WIN32_HAS_WIDE)
+ memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
+ if ( osMultiByteToWideChar(
+ osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
+ nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
+ return;
+ }
+ osOutputDebugStringW((LPCWSTR)zDbgBuf);
+#else
+ if( nMin>0 ){
+ memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
+ memcpy(zDbgBuf, zBuf, nMin);
+ fprintf(stderr, "%s", zDbgBuf);
+ }else{
+ fprintf(stderr, "%s", zBuf);
+ }
+#endif
+}
+
+/*
+** The following routine suspends the current thread for at least ms
+** milliseconds. This is equivalent to the Win32 Sleep() interface.
+*/
+#if SQLITE_OS_WINRT
+static HANDLE sleepObj = NULL;
+#endif
+
+SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
+#if SQLITE_OS_WINRT
+ if ( sleepObj==NULL ){
+ sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
+ SYNCHRONIZE);
+ }
+ assert( sleepObj!=NULL );
+ osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
+#else
+ osSleep(milliseconds);
+#endif
+}
+
+#if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
+ SQLITE_THREADSAFE>0
+SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
+ DWORD rc;
+ while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
+ TRUE))==WAIT_IO_COMPLETION ){}
+ return rc;
+}
+#endif
+
+/*
+** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
+** or WinCE. Return false (zero) for Win95, Win98, or WinME.
+**
+** Here is an interesting observation: Win95, Win98, and WinME lack
+** the LockFileEx() API. But we can still statically link against that
+** API as long as we don't call it when running Win95/98/ME. A call to
+** this routine is used to determine if the host is Win95/98/ME or
+** WinNT/2K/XP so that we will know whether or not we can safely call
+** the LockFileEx() API.
+*/
+
+#if !SQLITE_WIN32_GETVERSIONEX
+# define osIsNT() (1)
+#elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
+# define osIsNT() (1)
+#elif !defined(SQLITE_WIN32_HAS_WIDE)
+# define osIsNT() (0)
+#else
+# define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
+#endif
+
+/*
+** This function determines if the machine is running a version of Windows
+** based on the NT kernel.
+*/
+SQLITE_API int sqlite3_win32_is_nt(void){
+#if SQLITE_OS_WINRT
+ /*
+ ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
+ ** kernel.
+ */
+ return 1;
+#elif SQLITE_WIN32_GETVERSIONEX
+ if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
+#if defined(SQLITE_WIN32_HAS_ANSI)
+ OSVERSIONINFOA sInfo;
+ sInfo.dwOSVersionInfoSize = sizeof(sInfo);
+ osGetVersionExA(&sInfo);
+ osInterlockedCompareExchange(&sqlite3_os_type,
+ (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
+#elif defined(SQLITE_WIN32_HAS_WIDE)
+ OSVERSIONINFOW sInfo;
+ sInfo.dwOSVersionInfoSize = sizeof(sInfo);
+ osGetVersionExW(&sInfo);
+ osInterlockedCompareExchange(&sqlite3_os_type,
+ (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
+#endif
+ }
+ return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
+#elif SQLITE_TEST
+ return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
+#else
+ /*
+ ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
+ ** deprecated are always assumed to be based on the NT kernel.
+ */
+ return 1;
+#endif
+}
+
+#ifdef SQLITE_WIN32_MALLOC
+/*
+** Allocate nBytes of memory.
+*/
+static void *winMemMalloc(int nBytes){
+ HANDLE hHeap;
+ void *p;
+
+ winMemAssertMagic();
+ hHeap = winMemGetHeap();
+ assert( hHeap!=0 );
+ assert( hHeap!=INVALID_HANDLE_VALUE );
+#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
+ assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
+#endif
+ assert( nBytes>=0 );
+ p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
+ if( !p ){
+ sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
+ nBytes, osGetLastError(), (void*)hHeap);
+ }
+ return p;
+}
+
+/*
+** Free memory.
+*/
+static void winMemFree(void *pPrior){
+ HANDLE hHeap;
+
+ winMemAssertMagic();
+ hHeap = winMemGetHeap();
+ assert( hHeap!=0 );
+ assert( hHeap!=INVALID_HANDLE_VALUE );
+#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
+ assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
+#endif
+ if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
+ if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
+ sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
+ pPrior, osGetLastError(), (void*)hHeap);
+ }
+}
+
+/*
+** Change the size of an existing memory allocation
+*/
+static void *winMemRealloc(void *pPrior, int nBytes){
+ HANDLE hHeap;
+ void *p;
+
+ winMemAssertMagic();
+ hHeap = winMemGetHeap();
+ assert( hHeap!=0 );
+ assert( hHeap!=INVALID_HANDLE_VALUE );
+#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
+ assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
+#endif
+ assert( nBytes>=0 );
+ if( !pPrior ){
+ p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
+ }else{
+ p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
+ }
+ if( !p ){
+ sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
+ pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
+ (void*)hHeap);
+ }
+ return p;
+}
+
+/*
+** Return the size of an outstanding allocation, in bytes.
+*/
+static int winMemSize(void *p){
+ HANDLE hHeap;
+ SIZE_T n;
+
+ winMemAssertMagic();
+ hHeap = winMemGetHeap();
+ assert( hHeap!=0 );
+ assert( hHeap!=INVALID_HANDLE_VALUE );
+#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
+ assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
+#endif
+ if( !p ) return 0;
+ n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
+ if( n==(SIZE_T)-1 ){
+ sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
+ p, osGetLastError(), (void*)hHeap);
+ return 0;
+ }
+ return (int)n;
+}
+
+/*
+** Round up a request size to the next valid allocation size.
+*/
+static int winMemRoundup(int n){
+ return n;
+}
+
+/*
+** Initialize this module.
+*/
+static int winMemInit(void *pAppData){
+ winMemData *pWinMemData = (winMemData *)pAppData;
+
+ if( !pWinMemData ) return SQLITE_ERROR;
+ assert( pWinMemData->magic1==WINMEM_MAGIC1 );
+ assert( pWinMemData->magic2==WINMEM_MAGIC2 );
+
+#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
+ if( !pWinMemData->hHeap ){
+ DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
+ DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
+ if( dwMaximumSize==0 ){
+ dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
+ }else if( dwInitialSize>dwMaximumSize ){
+ dwInitialSize = dwMaximumSize;
+ }
+ pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
+ dwInitialSize, dwMaximumSize);
+ if( !pWinMemData->hHeap ){
+ sqlite3_log(SQLITE_NOMEM,
+ "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
+ osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
+ dwMaximumSize);
+ return SQLITE_NOMEM_BKPT;
+ }
+ pWinMemData->bOwned = TRUE;
+ assert( pWinMemData->bOwned );
+ }
+#else
+ pWinMemData->hHeap = osGetProcessHeap();
+ if( !pWinMemData->hHeap ){
+ sqlite3_log(SQLITE_NOMEM,
+ "failed to GetProcessHeap (%lu)", osGetLastError());
+ return SQLITE_NOMEM_BKPT;
+ }
+ pWinMemData->bOwned = FALSE;
+ assert( !pWinMemData->bOwned );
+#endif
+ assert( pWinMemData->hHeap!=0 );
+ assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
+#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
+ assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
+#endif
+ return SQLITE_OK;
+}
+
+/*
+** Deinitialize this module.
+*/
+static void winMemShutdown(void *pAppData){
+ winMemData *pWinMemData = (winMemData *)pAppData;
+
+ if( !pWinMemData ) return;
+ assert( pWinMemData->magic1==WINMEM_MAGIC1 );
+ assert( pWinMemData->magic2==WINMEM_MAGIC2 );
+
+ if( pWinMemData->hHeap ){
+ assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
+#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
+ assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
+#endif
+ if( pWinMemData->bOwned ){
+ if( !osHeapDestroy(pWinMemData->hHeap) ){
+ sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
+ osGetLastError(), (void*)pWinMemData->hHeap);
+ }
+ pWinMemData->bOwned = FALSE;
+ }
+ pWinMemData->hHeap = NULL;
+ }
+}
+
+/*
+** Populate the low-level memory allocation function pointers in
+** sqlite3GlobalConfig.m with pointers to the routines in this file. The
+** arguments specify the block of memory to manage.
+**
+** This routine is only called by sqlite3_config(), and therefore
+** is not required to be threadsafe (it is not).
+*/
+SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
+ static const sqlite3_mem_methods winMemMethods = {
+ winMemMalloc,
+ winMemFree,
+ winMemRealloc,
+ winMemSize,
+ winMemRoundup,
+ winMemInit,
+ winMemShutdown,
+ &win_mem_data
+ };
+ return &winMemMethods;
+}
+
+SQLITE_PRIVATE void sqlite3MemSetDefault(void){
+ sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
+}
+#endif /* SQLITE_WIN32_MALLOC */
+
+/*
+** Convert a UTF-8 string to Microsoft Unicode.
+**
+** Space to hold the returned string is obtained from sqlite3_malloc().
+*/
+static LPWSTR winUtf8ToUnicode(const char *zText){
+ int nChar;
+ LPWSTR zWideText;
+
+ nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
+ if( nChar==0 ){
+ return 0;
+ }
+ zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
+ if( zWideText==0 ){
+ return 0;
+ }
+ nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
+ nChar);
+ if( nChar==0 ){
+ sqlite3_free(zWideText);
+ zWideText = 0;
+ }
+ return zWideText;
+}
+
+/*
+** Convert a Microsoft Unicode string to UTF-8.
+**
+** Space to hold the returned string is obtained from sqlite3_malloc().
+*/
+static char *winUnicodeToUtf8(LPCWSTR zWideText){
+ int nByte;
+ char *zText;
+
+ nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
+ if( nByte == 0 ){
+ return 0;
+ }
+ zText = sqlite3MallocZero( nByte );
+ if( zText==0 ){
+ return 0;
+ }
+ nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
+ 0, 0);
+ if( nByte == 0 ){
+ sqlite3_free(zText);
+ zText = 0;
+ }
+ return zText;
+}
+
+/*
+** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
+** code page.
+**
+** Space to hold the returned string is obtained from sqlite3_malloc().
+*/
+static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
+ int nByte;
+ LPWSTR zMbcsText;
+ int codepage = useAnsi ? CP_ACP : CP_OEMCP;
+
+ nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
+ 0)*sizeof(WCHAR);
+ if( nByte==0 ){
+ return 0;
+ }
+ zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
+ if( zMbcsText==0 ){
+ return 0;
+ }
+ nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
+ nByte);
+ if( nByte==0 ){
+ sqlite3_free(zMbcsText);
+ zMbcsText = 0;
+ }
+ return zMbcsText;
+}
+
+/*
+** Convert a Microsoft Unicode string to a multi-byte character string,
+** using the ANSI or OEM code page.
+**
+** Space to hold the returned string is obtained from sqlite3_malloc().
+*/
+static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
+ int nByte;
+ char *zText;
+ int codepage = useAnsi ? CP_ACP : CP_OEMCP;
+
+ nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
+ if( nByte == 0 ){
+ return 0;
+ }
+ zText = sqlite3MallocZero( nByte );
+ if( zText==0 ){
+ return 0;
+ }
+ nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
+ nByte, 0, 0);
+ if( nByte == 0 ){
+ sqlite3_free(zText);
+ zText = 0;
+ }
+ return zText;
+}
+
+/*
+** Convert a multi-byte character string to UTF-8.
+**
+** Space to hold the returned string is obtained from sqlite3_malloc().
+*/
+static char *winMbcsToUtf8(const char *zText, int useAnsi){
+ char *zTextUtf8;
+ LPWSTR zTmpWide;
+
+ zTmpWide = winMbcsToUnicode(zText, useAnsi);
+ if( zTmpWide==0 ){
+ return 0;
+ }
+ zTextUtf8 = winUnicodeToUtf8(zTmpWide);
+ sqlite3_free(zTmpWide);
+ return zTextUtf8;
+}
+
+/*
+** Convert a UTF-8 string to a multi-byte character string.
+**
+** Space to hold the returned string is obtained from sqlite3_malloc().
+*/
+static char *winUtf8ToMbcs(const char *zText, int useAnsi){
+ char *zTextMbcs;
+ LPWSTR zTmpWide;
+
+ zTmpWide = winUtf8ToUnicode(zText);
+ if( zTmpWide==0 ){
+ return 0;
+ }
+ zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
+ sqlite3_free(zTmpWide);
+ return zTextMbcs;
+}
+
+/*
+** This is a public wrapper for the winUtf8ToUnicode() function.
+*/
+SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !zText ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( sqlite3_initialize() ) return 0;
+#endif
+ return winUtf8ToUnicode(zText);
+}
+
+/*
+** This is a public wrapper for the winUnicodeToUtf8() function.
+*/
+SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !zWideText ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( sqlite3_initialize() ) return 0;
+#endif
+ return winUnicodeToUtf8(zWideText);
+}
+
+/*
+** This is a public wrapper for the winMbcsToUtf8() function.
+*/
+SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !zText ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( sqlite3_initialize() ) return 0;
+#endif
+ return winMbcsToUtf8(zText, osAreFileApisANSI());
+}
+
+/*
+** This is a public wrapper for the winMbcsToUtf8() function.
+*/
+SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !zText ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( sqlite3_initialize() ) return 0;
+#endif
+ return winMbcsToUtf8(zText, useAnsi);
+}
+
+/*
+** This is a public wrapper for the winUtf8ToMbcs() function.
+*/
+SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !zText ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( sqlite3_initialize() ) return 0;
+#endif
+ return winUtf8ToMbcs(zText, osAreFileApisANSI());
+}
+
+/*
+** This is a public wrapper for the winUtf8ToMbcs() function.
+*/
+SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !zText ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( sqlite3_initialize() ) return 0;
+#endif
+ return winUtf8ToMbcs(zText, useAnsi);
+}
+
+/*
+** This function is the same as sqlite3_win32_set_directory (below); however,
+** it accepts a UTF-8 string.
+*/
+SQLITE_API int sqlite3_win32_set_directory8(
+ unsigned long type, /* Identifier for directory being set or reset */
+ const char *zValue /* New value for directory being set or reset */
+){
+ char **ppDirectory = 0;
+#ifndef SQLITE_OMIT_AUTOINIT
+ int rc = sqlite3_initialize();
+ if( rc ) return rc;
+#endif
+ if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
+ ppDirectory = &sqlite3_data_directory;
+ }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
+ ppDirectory = &sqlite3_temp_directory;
+ }
+ assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
+ || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
+ );
+ assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
+ if( ppDirectory ){
+ char *zCopy = 0;
+ if( zValue && zValue[0] ){
+ zCopy = sqlite3_mprintf("%s", zValue);
+ if ( zCopy==0 ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ }
+ sqlite3_free(*ppDirectory);
+ *ppDirectory = zCopy;
+ return SQLITE_OK;
+ }
+ return SQLITE_ERROR;
+}
+
+/*
+** This function is the same as sqlite3_win32_set_directory (below); however,
+** it accepts a UTF-16 string.
+*/
+SQLITE_API int sqlite3_win32_set_directory16(
+ unsigned long type, /* Identifier for directory being set or reset */
+ const void *zValue /* New value for directory being set or reset */
+){
+ int rc;
+ char *zUtf8 = 0;
+ if( zValue ){
+ zUtf8 = sqlite3_win32_unicode_to_utf8(zValue);
+ if( zUtf8==0 ) return SQLITE_NOMEM_BKPT;
+ }
+ rc = sqlite3_win32_set_directory8(type, zUtf8);
+ if( zUtf8 ) sqlite3_free(zUtf8);
+ return rc;
+}
+
+/*
+** This function sets the data directory or the temporary directory based on
+** the provided arguments. The type argument must be 1 in order to set the
+** data directory or 2 in order to set the temporary directory. The zValue
+** argument is the name of the directory to use. The return value will be
+** SQLITE_OK if successful.
+*/
+SQLITE_API int sqlite3_win32_set_directory(
+ unsigned long type, /* Identifier for directory being set or reset */
+ void *zValue /* New value for directory being set or reset */
+){
+ return sqlite3_win32_set_directory16(type, zValue);
+}
+
+/*
+** The return value of winGetLastErrorMsg
+** is zero if the error message fits in the buffer, or non-zero
+** otherwise (if the message was truncated).
+*/
+static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
+ /* FormatMessage returns 0 on failure. Otherwise it
+ ** returns the number of TCHARs written to the output
+ ** buffer, excluding the terminating null char.
+ */
+ DWORD dwLen = 0;
+ char *zOut = 0;
+
+ if( osIsNT() ){
+#if SQLITE_OS_WINRT
+ WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
+ dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL,
+ lastErrno,
+ 0,
+ zTempWide,
+ SQLITE_WIN32_MAX_ERRMSG_CHARS,
+ 0);
+#else
+ LPWSTR zTempWide = NULL;
+ dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
+ FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL,
+ lastErrno,
+ 0,
+ (LPWSTR) &zTempWide,
+ 0,
+ 0);
+#endif
+ if( dwLen > 0 ){
+ /* allocate a buffer and convert to UTF8 */
+ sqlite3BeginBenignMalloc();
+ zOut = winUnicodeToUtf8(zTempWide);
+ sqlite3EndBenignMalloc();
+#if !SQLITE_OS_WINRT
+ /* free the system buffer allocated by FormatMessage */
+ osLocalFree(zTempWide);
+#endif
+ }
+ }
+#ifdef SQLITE_WIN32_HAS_ANSI
+ else{
+ char *zTemp = NULL;
+ dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
+ FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL,
+ lastErrno,
+ 0,
+ (LPSTR) &zTemp,
+ 0,
+ 0);
+ if( dwLen > 0 ){
+ /* allocate a buffer and convert to UTF8 */
+ sqlite3BeginBenignMalloc();
+ zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
+ sqlite3EndBenignMalloc();
+ /* free the system buffer allocated by FormatMessage */
+ osLocalFree(zTemp);
+ }
+ }
+#endif
+ if( 0 == dwLen ){
+ sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
+ }else{
+ /* copy a maximum of nBuf chars to output buffer */
+ sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
+ /* free the UTF8 buffer */
+ sqlite3_free(zOut);
+ }
+ return 0;
+}
+
+/*
+**
+** This function - winLogErrorAtLine() - is only ever called via the macro
+** winLogError().
+**
+** This routine is invoked after an error occurs in an OS function.
+** It logs a message using sqlite3_log() containing the current value of
+** error code and, if possible, the human-readable equivalent from
+** FormatMessage.
+**
+** The first argument passed to the macro should be the error code that
+** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
+** The two subsequent arguments should be the name of the OS function that
+** failed and the associated file-system path, if any.
+*/
+#define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
+static int winLogErrorAtLine(
+ int errcode, /* SQLite error code */
+ DWORD lastErrno, /* Win32 last error */
+ const char *zFunc, /* Name of OS function that failed */
+ const char *zPath, /* File path associated with error */
+ int iLine /* Source line number where error occurred */
+){
+ char zMsg[500]; /* Human readable error text */
+ int i; /* Loop counter */
+
+ zMsg[0] = 0;
+ winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
+ assert( errcode!=SQLITE_OK );
+ if( zPath==0 ) zPath = "";
+ for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
+ zMsg[i] = 0;
+ sqlite3_log(errcode,
+ "os_win.c:%d: (%lu) %s(%s) - %s",
+ iLine, lastErrno, zFunc, zPath, zMsg
+ );
+
+ return errcode;
+}
+
+/*
+** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
+** will be retried following a locking error - probably caused by
+** antivirus software. Also the initial delay before the first retry.
+** The delay increases linearly with each retry.
+*/
+#ifndef SQLITE_WIN32_IOERR_RETRY
+# define SQLITE_WIN32_IOERR_RETRY 10
+#endif
+#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
+# define SQLITE_WIN32_IOERR_RETRY_DELAY 25
+#endif
+static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
+static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
+
+/*
+** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
+** error code obtained via GetLastError() is eligible to be retried. It
+** must accept the error code DWORD as its only argument and should return
+** non-zero if the error code is transient in nature and the operation
+** responsible for generating the original error might succeed upon being
+** retried. The argument to this macro should be a variable.
+**
+** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
+** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
+** returns zero. The "winIoerrCanRetry2" macro is completely optional and
+** may be used to include additional error codes in the set that should
+** result in the failing I/O operation being retried by the caller. If
+** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
+** identical to those of the "winIoerrCanRetry1" macro.
+*/
+#if !defined(winIoerrCanRetry1)
+#define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
+ ((a)==ERROR_SHARING_VIOLATION) || \
+ ((a)==ERROR_LOCK_VIOLATION) || \
+ ((a)==ERROR_DEV_NOT_EXIST) || \
+ ((a)==ERROR_NETNAME_DELETED) || \
+ ((a)==ERROR_SEM_TIMEOUT) || \
+ ((a)==ERROR_NETWORK_UNREACHABLE))
+#endif
+
+/*
+** If a ReadFile() or WriteFile() error occurs, invoke this routine
+** to see if it should be retried. Return TRUE to retry. Return FALSE
+** to give up with an error.
+*/
+static int winRetryIoerr(int *pnRetry, DWORD *pError){
+ DWORD e = osGetLastError();
+ if( *pnRetry>=winIoerrRetry ){
+ if( pError ){
+ *pError = e;
+ }
+ return 0;
+ }
+ if( winIoerrCanRetry1(e) ){
+ sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
+ ++*pnRetry;
+ return 1;
+ }
+#if defined(winIoerrCanRetry2)
+ else if( winIoerrCanRetry2(e) ){
+ sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
+ ++*pnRetry;
+ return 1;
+ }
+#endif
+ if( pError ){
+ *pError = e;
+ }
+ return 0;
+}
+
+/*
+** Log a I/O error retry episode.
+*/
+static void winLogIoerr(int nRetry, int lineno){
+ if( nRetry ){
+ sqlite3_log(SQLITE_NOTICE,
+ "delayed %dms for lock/sharing conflict at line %d",
+ winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
+ );
+ }
+}
+
+/*
+** This #if does not rely on the SQLITE_OS_WINCE define because the
+** corresponding section in "date.c" cannot use it.
+*/
+#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
+ (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
+/*
+** The MSVC CRT on Windows CE may not have a localtime() function.
+** So define a substitute.
+*/
+/* # include <time.h> */
+struct tm *__cdecl localtime(const time_t *t)
+{
+ static struct tm y;
+ FILETIME uTm, lTm;
+ SYSTEMTIME pTm;
+ sqlite3_int64 t64;
+ t64 = *t;
+ t64 = (t64 + 11644473600)*10000000;
+ uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
+ uTm.dwHighDateTime= (DWORD)(t64 >> 32);
+ osFileTimeToLocalFileTime(&uTm,&lTm);
+ osFileTimeToSystemTime(&lTm,&pTm);
+ y.tm_year = pTm.wYear - 1900;
+ y.tm_mon = pTm.wMonth - 1;
+ y.tm_wday = pTm.wDayOfWeek;
+ y.tm_mday = pTm.wDay;
+ y.tm_hour = pTm.wHour;
+ y.tm_min = pTm.wMinute;
+ y.tm_sec = pTm.wSecond;
+ return &y;
+}
+#endif
+
+#if SQLITE_OS_WINCE
+/*************************************************************************
+** This section contains code for WinCE only.
+*/
+#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
+
+/*
+** Acquire a lock on the handle h
+*/
+static void winceMutexAcquire(HANDLE h){
+ DWORD dwErr;
+ do {
+ dwErr = osWaitForSingleObject(h, INFINITE);
+ } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
+}
+/*
+** Release a lock acquired by winceMutexAcquire()
+*/
+#define winceMutexRelease(h) ReleaseMutex(h)
+
+/*
+** Create the mutex and shared memory used for locking in the file
+** descriptor pFile
+*/
+static int winceCreateLock(const char *zFilename, winFile *pFile){
+ LPWSTR zTok;
+ LPWSTR zName;
+ DWORD lastErrno;
+ BOOL bLogged = FALSE;
+ BOOL bInit = TRUE;
+
+ zName = winUtf8ToUnicode(zFilename);
+ if( zName==0 ){
+ /* out of memory */
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+
+ /* Initialize the local lockdata */
+ memset(&pFile->local, 0, sizeof(pFile->local));
+
+ /* Replace the backslashes from the filename and lowercase it
+ ** to derive a mutex name. */
+ zTok = osCharLowerW(zName);
+ for (;*zTok;zTok++){
+ if (*zTok == '\\') *zTok = '_';
+ }
+
+ /* Create/open the named mutex */
+ pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
+ if (!pFile->hMutex){
+ pFile->lastErrno = osGetLastError();
+ sqlite3_free(zName);
+ return winLogError(SQLITE_IOERR, pFile->lastErrno,
+ "winceCreateLock1", zFilename);
+ }
+
+ /* Acquire the mutex before continuing */
+ winceMutexAcquire(pFile->hMutex);
+
+ /* Since the names of named mutexes, semaphores, file mappings etc are
+ ** case-sensitive, take advantage of that by uppercasing the mutex name
+ ** and using that as the shared filemapping name.
+ */
+ osCharUpperW(zName);
+ pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
+ PAGE_READWRITE, 0, sizeof(winceLock),
+ zName);
+
+ /* Set a flag that indicates we're the first to create the memory so it
+ ** must be zero-initialized */
+ lastErrno = osGetLastError();
+ if (lastErrno == ERROR_ALREADY_EXISTS){
+ bInit = FALSE;
+ }
+
+ sqlite3_free(zName);
+
+ /* If we succeeded in making the shared memory handle, map it. */
+ if( pFile->hShared ){
+ pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
+ FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
+ /* If mapping failed, close the shared memory handle and erase it */
+ if( !pFile->shared ){
+ pFile->lastErrno = osGetLastError();
+ winLogError(SQLITE_IOERR, pFile->lastErrno,
+ "winceCreateLock2", zFilename);
+ bLogged = TRUE;
+ osCloseHandle(pFile->hShared);
+ pFile->hShared = NULL;
+ }
+ }
+
+ /* If shared memory could not be created, then close the mutex and fail */
+ if( pFile->hShared==NULL ){
+ if( !bLogged ){
+ pFile->lastErrno = lastErrno;
+ winLogError(SQLITE_IOERR, pFile->lastErrno,
+ "winceCreateLock3", zFilename);
+ bLogged = TRUE;
+ }
+ winceMutexRelease(pFile->hMutex);
+ osCloseHandle(pFile->hMutex);
+ pFile->hMutex = NULL;
+ return SQLITE_IOERR;
+ }
+
+ /* Initialize the shared memory if we're supposed to */
+ if( bInit ){
+ memset(pFile->shared, 0, sizeof(winceLock));
+ }
+
+ winceMutexRelease(pFile->hMutex);
+ return SQLITE_OK;
+}
+
+/*
+** Destroy the part of winFile that deals with wince locks
+*/
+static void winceDestroyLock(winFile *pFile){
+ if (pFile->hMutex){
+ /* Acquire the mutex */
+ winceMutexAcquire(pFile->hMutex);
+
+ /* The following blocks should probably assert in debug mode, but they
+ are to cleanup in case any locks remained open */
+ if (pFile->local.nReaders){
+ pFile->shared->nReaders --;
+ }
+ if (pFile->local.bReserved){
+ pFile->shared->bReserved = FALSE;
+ }
+ if (pFile->local.bPending){
+ pFile->shared->bPending = FALSE;
+ }
+ if (pFile->local.bExclusive){
+ pFile->shared->bExclusive = FALSE;
+ }
+
+ /* De-reference and close our copy of the shared memory handle */
+ osUnmapViewOfFile(pFile->shared);
+ osCloseHandle(pFile->hShared);
+
+ /* Done with the mutex */
+ winceMutexRelease(pFile->hMutex);
+ osCloseHandle(pFile->hMutex);
+ pFile->hMutex = NULL;
+ }
+}
+
+/*
+** An implementation of the LockFile() API of Windows for CE
+*/
+static BOOL winceLockFile(
+ LPHANDLE phFile,
+ DWORD dwFileOffsetLow,
+ DWORD dwFileOffsetHigh,
+ DWORD nNumberOfBytesToLockLow,
+ DWORD nNumberOfBytesToLockHigh
+){
+ winFile *pFile = HANDLE_TO_WINFILE(phFile);
+ BOOL bReturn = FALSE;
+
+ UNUSED_PARAMETER(dwFileOffsetHigh);
+ UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
+
+ if (!pFile->hMutex) return TRUE;
+ winceMutexAcquire(pFile->hMutex);
+
+ /* Wanting an exclusive lock? */
+ if (dwFileOffsetLow == (DWORD)SHARED_FIRST
+ && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
+ if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
+ pFile->shared->bExclusive = TRUE;
+ pFile->local.bExclusive = TRUE;
+ bReturn = TRUE;
+ }
+ }
+
+ /* Want a read-only lock? */
+ else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
+ nNumberOfBytesToLockLow == 1){
+ if (pFile->shared->bExclusive == 0){
+ pFile->local.nReaders ++;
+ if (pFile->local.nReaders == 1){
+ pFile->shared->nReaders ++;
+ }
+ bReturn = TRUE;
+ }
+ }
+
+ /* Want a pending lock? */
+ else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
+ && nNumberOfBytesToLockLow == 1){
+ /* If no pending lock has been acquired, then acquire it */
+ if (pFile->shared->bPending == 0) {
+ pFile->shared->bPending = TRUE;
+ pFile->local.bPending = TRUE;
+ bReturn = TRUE;
+ }
+ }
+
+ /* Want a reserved lock? */
+ else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
+ && nNumberOfBytesToLockLow == 1){
+ if (pFile->shared->bReserved == 0) {
+ pFile->shared->bReserved = TRUE;
+ pFile->local.bReserved = TRUE;
+ bReturn = TRUE;
+ }
+ }
+
+ winceMutexRelease(pFile->hMutex);
+ return bReturn;
+}
+
+/*
+** An implementation of the UnlockFile API of Windows for CE
+*/
+static BOOL winceUnlockFile(
+ LPHANDLE phFile,
+ DWORD dwFileOffsetLow,
+ DWORD dwFileOffsetHigh,
+ DWORD nNumberOfBytesToUnlockLow,
+ DWORD nNumberOfBytesToUnlockHigh
+){
+ winFile *pFile = HANDLE_TO_WINFILE(phFile);
+ BOOL bReturn = FALSE;
+
+ UNUSED_PARAMETER(dwFileOffsetHigh);
+ UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
+
+ if (!pFile->hMutex) return TRUE;
+ winceMutexAcquire(pFile->hMutex);
+
+ /* Releasing a reader lock or an exclusive lock */
+ if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
+ /* Did we have an exclusive lock? */
+ if (pFile->local.bExclusive){
+ assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
+ pFile->local.bExclusive = FALSE;
+ pFile->shared->bExclusive = FALSE;
+ bReturn = TRUE;
+ }
+
+ /* Did we just have a reader lock? */
+ else if (pFile->local.nReaders){
+ assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
+ || nNumberOfBytesToUnlockLow == 1);
+ pFile->local.nReaders --;
+ if (pFile->local.nReaders == 0)
+ {
+ pFile->shared->nReaders --;
+ }
+ bReturn = TRUE;
+ }
+ }
+
+ /* Releasing a pending lock */
+ else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
+ && nNumberOfBytesToUnlockLow == 1){
+ if (pFile->local.bPending){
+ pFile->local.bPending = FALSE;
+ pFile->shared->bPending = FALSE;
+ bReturn = TRUE;
+ }
+ }
+ /* Releasing a reserved lock */
+ else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
+ && nNumberOfBytesToUnlockLow == 1){
+ if (pFile->local.bReserved) {
+ pFile->local.bReserved = FALSE;
+ pFile->shared->bReserved = FALSE;
+ bReturn = TRUE;
+ }
+ }
+
+ winceMutexRelease(pFile->hMutex);
+ return bReturn;
+}
+/*
+** End of the special code for wince
+*****************************************************************************/
+#endif /* SQLITE_OS_WINCE */
+
+/*
+** Lock a file region.
+*/
+static BOOL winLockFile(
+ LPHANDLE phFile,
+ DWORD flags,
+ DWORD offsetLow,
+ DWORD offsetHigh,
+ DWORD numBytesLow,
+ DWORD numBytesHigh
+){
+#if SQLITE_OS_WINCE
+ /*
+ ** NOTE: Windows CE is handled differently here due its lack of the Win32
+ ** API LockFile.
+ */
+ return winceLockFile(phFile, offsetLow, offsetHigh,
+ numBytesLow, numBytesHigh);
+#else
+ if( osIsNT() ){
+ OVERLAPPED ovlp;
+ memset(&ovlp, 0, sizeof(OVERLAPPED));
+ ovlp.Offset = offsetLow;
+ ovlp.OffsetHigh = offsetHigh;
+ return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
+ }else{
+ return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
+ numBytesHigh);
+ }
+#endif
+}
+
+/*
+** Unlock a file region.
+ */
+static BOOL winUnlockFile(
+ LPHANDLE phFile,
+ DWORD offsetLow,
+ DWORD offsetHigh,
+ DWORD numBytesLow,
+ DWORD numBytesHigh
+){
+#if SQLITE_OS_WINCE
+ /*
+ ** NOTE: Windows CE is handled differently here due its lack of the Win32
+ ** API UnlockFile.
+ */
+ return winceUnlockFile(phFile, offsetLow, offsetHigh,
+ numBytesLow, numBytesHigh);
+#else
+ if( osIsNT() ){
+ OVERLAPPED ovlp;
+ memset(&ovlp, 0, sizeof(OVERLAPPED));
+ ovlp.Offset = offsetLow;
+ ovlp.OffsetHigh = offsetHigh;
+ return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
+ }else{
+ return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
+ numBytesHigh);
+ }
+#endif
+}
+
+/*****************************************************************************
+** The next group of routines implement the I/O methods specified
+** by the sqlite3_io_methods object.
+******************************************************************************/
+
+/*
+** Some Microsoft compilers lack this definition.
+*/
+#ifndef INVALID_SET_FILE_POINTER
+# define INVALID_SET_FILE_POINTER ((DWORD)-1)
+#endif
+
+/*
+** Move the current position of the file handle passed as the first
+** argument to offset iOffset within the file. If successful, return 0.
+** Otherwise, set pFile->lastErrno and return non-zero.
+*/
+static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
+#if !SQLITE_OS_WINRT
+ LONG upperBits; /* Most sig. 32 bits of new offset */
+ LONG lowerBits; /* Least sig. 32 bits of new offset */
+ DWORD dwRet; /* Value returned by SetFilePointer() */
+ DWORD lastErrno; /* Value returned by GetLastError() */
+
+ OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
+
+ upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
+ lowerBits = (LONG)(iOffset & 0xffffffff);
+
+ /* API oddity: If successful, SetFilePointer() returns a dword
+ ** containing the lower 32-bits of the new file-offset. Or, if it fails,
+ ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
+ ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
+ ** whether an error has actually occurred, it is also necessary to call
+ ** GetLastError().
+ */
+ dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
+
+ if( (dwRet==INVALID_SET_FILE_POINTER
+ && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
+ pFile->lastErrno = lastErrno;
+ winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
+ "winSeekFile", pFile->zPath);
+ OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
+ return 1;
+ }
+
+ OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
+ return 0;
+#else
+ /*
+ ** Same as above, except that this implementation works for WinRT.
+ */
+
+ LARGE_INTEGER x; /* The new offset */
+ BOOL bRet; /* Value returned by SetFilePointerEx() */
+
+ x.QuadPart = iOffset;
+ bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
+
+ if(!bRet){
+ pFile->lastErrno = osGetLastError();
+ winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
+ "winSeekFile", pFile->zPath);
+ OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
+ return 1;
+ }
+
+ OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
+ return 0;
+#endif
+}
+
+#if SQLITE_MAX_MMAP_SIZE>0
+/* Forward references to VFS helper methods used for memory mapped files */
+static int winMapfile(winFile*, sqlite3_int64);
+static int winUnmapfile(winFile*);
+#endif
+
+/*
+** Close a file.
+**
+** It is reported that an attempt to close a handle might sometimes
+** fail. This is a very unreasonable result, but Windows is notorious
+** for being unreasonable so I do not doubt that it might happen. If
+** the close fails, we pause for 100 milliseconds and try again. As
+** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
+** giving up and returning an error.
+*/
+#define MX_CLOSE_ATTEMPT 3
+static int winClose(sqlite3_file *id){
+ int rc, cnt = 0;
+ winFile *pFile = (winFile*)id;
+
+ assert( id!=0 );
+#ifndef SQLITE_OMIT_WAL
+ assert( pFile->pShm==0 );
+#endif
+ assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
+ OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
+ osGetCurrentProcessId(), pFile, pFile->h));
+
+#if SQLITE_MAX_MMAP_SIZE>0
+ winUnmapfile(pFile);
+#endif
+
+ do{
+ rc = osCloseHandle(pFile->h);
+ /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
+ }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
+#if SQLITE_OS_WINCE
+#define WINCE_DELETION_ATTEMPTS 3
+ {
+ winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
+ if( pAppData==NULL || !pAppData->bNoLock ){
+ winceDestroyLock(pFile);
+ }
+ }
+ if( pFile->zDeleteOnClose ){
+ int cnt = 0;
+ while(
+ osDeleteFileW(pFile->zDeleteOnClose)==0
+ && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
+ && cnt++ < WINCE_DELETION_ATTEMPTS
+ ){
+ sqlite3_win32_sleep(100); /* Wait a little before trying again */
+ }
+ sqlite3_free(pFile->zDeleteOnClose);
+ }
+#endif
+ if( rc ){
+ pFile->h = NULL;
+ }
+ OpenCounter(-1);
+ OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
+ osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
+ return rc ? SQLITE_OK
+ : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
+ "winClose", pFile->zPath);
+}
+
+/*
+** Read data from a file into a buffer. Return SQLITE_OK if all
+** bytes were read successfully and SQLITE_IOERR if anything goes
+** wrong.
+*/
+static int winRead(
+ sqlite3_file *id, /* File to read from */
+ void *pBuf, /* Write content into this buffer */
+ int amt, /* Number of bytes to read */
+ sqlite3_int64 offset /* Begin reading at this offset */
+){
+#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
+ OVERLAPPED overlapped; /* The offset for ReadFile. */
+#endif
+ winFile *pFile = (winFile*)id; /* file handle */
+ DWORD nRead; /* Number of bytes actually read from file */
+ int nRetry = 0; /* Number of retrys */
+
+ assert( id!=0 );
+ assert( amt>0 );
+ assert( offset>=0 );
+ SimulateIOError(return SQLITE_IOERR_READ);
+ OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
+ "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
+ pFile->h, pBuf, amt, offset, pFile->locktype));
+
+#if SQLITE_MAX_MMAP_SIZE>0
+ /* Deal with as much of this read request as possible by transfering
+ ** data from the memory mapping using memcpy(). */
+ if( offset<pFile->mmapSize ){
+ if( offset+amt <= pFile->mmapSize ){
+ memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
+ OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
+ osGetCurrentProcessId(), pFile, pFile->h));
+ return SQLITE_OK;
+ }else{
+ int nCopy = (int)(pFile->mmapSize - offset);
+ memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
+ pBuf = &((u8 *)pBuf)[nCopy];
+ amt -= nCopy;
+ offset += nCopy;
+ }
+ }
+#endif
+
+#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
+ if( winSeekFile(pFile, offset) ){
+ OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
+ osGetCurrentProcessId(), pFile, pFile->h));
+ return SQLITE_FULL;
+ }
+ while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
+#else
+ memset(&overlapped, 0, sizeof(OVERLAPPED));
+ overlapped.Offset = (LONG)(offset & 0xffffffff);
+ overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
+ while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
+ osGetLastError()!=ERROR_HANDLE_EOF ){
+#endif
+ DWORD lastErrno;
+ if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
+ pFile->lastErrno = lastErrno;
+ OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
+ osGetCurrentProcessId(), pFile, pFile->h));
+ return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
+ "winRead", pFile->zPath);
+ }
+ winLogIoerr(nRetry, __LINE__);
+ if( nRead<(DWORD)amt ){
+ /* Unread parts of the buffer must be zero-filled */
+ memset(&((char*)pBuf)[nRead], 0, amt-nRead);
+ OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
+ osGetCurrentProcessId(), pFile, pFile->h));
+ return SQLITE_IOERR_SHORT_READ;
+ }
+
+ OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
+ osGetCurrentProcessId(), pFile, pFile->h));
+ return SQLITE_OK;
+}
+
+/*
+** Write data from a buffer into a file. Return SQLITE_OK on success
+** or some other error code on failure.
+*/
+static int winWrite(
+ sqlite3_file *id, /* File to write into */
+ const void *pBuf, /* The bytes to be written */
+ int amt, /* Number of bytes to write */
+ sqlite3_int64 offset /* Offset into the file to begin writing at */
+){
+ int rc = 0; /* True if error has occurred, else false */
+ winFile *pFile = (winFile*)id; /* File handle */
+ int nRetry = 0; /* Number of retries */
+
+ assert( amt>0 );
+ assert( pFile );
+ SimulateIOError(return SQLITE_IOERR_WRITE);
+ SimulateDiskfullError(return SQLITE_FULL);
+
+ OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
+ "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
+ pFile->h, pBuf, amt, offset, pFile->locktype));
+
+#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
+ /* Deal with as much of this write request as possible by transfering
+ ** data from the memory mapping using memcpy(). */
+ if( offset<pFile->mmapSize ){
+ if( offset+amt <= pFile->mmapSize ){
+ memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
+ OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
+ osGetCurrentProcessId(), pFile, pFile->h));
+ return SQLITE_OK;
+ }else{
+ int nCopy = (int)(pFile->mmapSize - offset);
+ memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
+ pBuf = &((u8 *)pBuf)[nCopy];
+ amt -= nCopy;
+ offset += nCopy;
+ }
+ }
+#endif
+
+#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
+ rc = winSeekFile(pFile, offset);
+ if( rc==0 ){
+#else
+ {
+#endif
+#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
+ OVERLAPPED overlapped; /* The offset for WriteFile. */
+#endif
+ u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
+ int nRem = amt; /* Number of bytes yet to be written */
+ DWORD nWrite; /* Bytes written by each WriteFile() call */
+ DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
+
+#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
+ memset(&overlapped, 0, sizeof(OVERLAPPED));
+ overlapped.Offset = (LONG)(offset & 0xffffffff);
+ overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
+#endif
+
+ while( nRem>0 ){
+#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
+ if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
+#else
+ if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
+#endif
+ if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
+ break;
+ }
+ assert( nWrite==0 || nWrite<=(DWORD)nRem );
+ if( nWrite==0 || nWrite>(DWORD)nRem ){
+ lastErrno = osGetLastError();
+ break;
+ }
+#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
+ offset += nWrite;
+ overlapped.Offset = (LONG)(offset & 0xffffffff);
+ overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
+#endif
+ aRem += nWrite;
+ nRem -= nWrite;
+ }
+ if( nRem>0 ){
+ pFile->lastErrno = lastErrno;
+ rc = 1;
+ }
+ }
+
+ if( rc ){
+ if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
+ || ( pFile->lastErrno==ERROR_DISK_FULL )){
+ OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
+ osGetCurrentProcessId(), pFile, pFile->h));
+ return winLogError(SQLITE_FULL, pFile->lastErrno,
+ "winWrite1", pFile->zPath);
+ }
+ OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
+ osGetCurrentProcessId(), pFile, pFile->h));
+ return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
+ "winWrite2", pFile->zPath);
+ }else{
+ winLogIoerr(nRetry, __LINE__);
+ }
+ OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
+ osGetCurrentProcessId(), pFile, pFile->h));
+ return SQLITE_OK;
+}
+
+/*
+** Truncate an open file to a specified size
+*/
+static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
+ winFile *pFile = (winFile*)id; /* File handle object */
+ int rc = SQLITE_OK; /* Return code for this function */
+ DWORD lastErrno;
+#if SQLITE_MAX_MMAP_SIZE>0
+ sqlite3_int64 oldMmapSize;
+ if( pFile->nFetchOut>0 ){
+ /* File truncation is a no-op if there are outstanding memory mapped
+ ** pages. This is because truncating the file means temporarily unmapping
+ ** the file, and that might delete memory out from under existing cursors.
+ **
+ ** This can result in incremental vacuum not truncating the file,
+ ** if there is an active read cursor when the incremental vacuum occurs.
+ ** No real harm comes of this - the database file is not corrupted,
+ ** though some folks might complain that the file is bigger than it
+ ** needs to be.
+ **
+ ** The only feasible work-around is to defer the truncation until after
+ ** all references to memory-mapped content are closed. That is doable,
+ ** but involves adding a few branches in the common write code path which
+ ** could slow down normal operations slightly. Hence, we have decided for
+ ** now to simply make trancations a no-op if there are pending reads. We
+ ** can maybe revisit this decision in the future.
+ */
+ return SQLITE_OK;
+ }
+#endif
+
+ assert( pFile );
+ SimulateIOError(return SQLITE_IOERR_TRUNCATE);
+ OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
+ osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
+
+ /* If the user has configured a chunk-size for this file, truncate the
+ ** file so that it consists of an integer number of chunks (i.e. the
+ ** actual file size after the operation may be larger than the requested
+ ** size).
+ */
+ if( pFile->szChunk>0 ){
+ nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
+ }
+
+#if SQLITE_MAX_MMAP_SIZE>0
+ if( pFile->pMapRegion ){
+ oldMmapSize = pFile->mmapSize;
+ }else{
+ oldMmapSize = 0;
+ }
+ winUnmapfile(pFile);
+#endif
+
+ /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
+ if( winSeekFile(pFile, nByte) ){
+ rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
+ "winTruncate1", pFile->zPath);
+ }else if( 0==osSetEndOfFile(pFile->h) &&
+ ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
+ pFile->lastErrno = lastErrno;
+ rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
+ "winTruncate2", pFile->zPath);
+ }
+
+#if SQLITE_MAX_MMAP_SIZE>0
+ if( rc==SQLITE_OK && oldMmapSize>0 ){
+ if( oldMmapSize>nByte ){
+ winMapfile(pFile, -1);
+ }else{
+ winMapfile(pFile, oldMmapSize);
+ }
+ }
+#endif
+
+ OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
+ osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
+ return rc;
+}
+
+#ifdef SQLITE_TEST
+/*
+** Count the number of fullsyncs and normal syncs. This is used to test
+** that syncs and fullsyncs are occuring at the right times.
+*/
+SQLITE_API int sqlite3_sync_count = 0;
+SQLITE_API int sqlite3_fullsync_count = 0;
+#endif
+
+/*
+** Make sure all writes to a particular file are committed to disk.
+*/
+static int winSync(sqlite3_file *id, int flags){
+#ifndef SQLITE_NO_SYNC
+ /*
+ ** Used only when SQLITE_NO_SYNC is not defined.
+ */
+ BOOL rc;
+#endif
+#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
+ defined(SQLITE_HAVE_OS_TRACE)
+ /*
+ ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
+ ** OSTRACE() macros.
+ */
+ winFile *pFile = (winFile*)id;
+#else
+ UNUSED_PARAMETER(id);
+#endif
+
+ assert( pFile );
+ /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
+ assert((flags&0x0F)==SQLITE_SYNC_NORMAL
+ || (flags&0x0F)==SQLITE_SYNC_FULL
+ );
+
+ /* Unix cannot, but some systems may return SQLITE_FULL from here. This
+ ** line is to test that doing so does not cause any problems.
+ */
+ SimulateDiskfullError( return SQLITE_FULL );
+
+ OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
+ osGetCurrentProcessId(), pFile, pFile->h, flags,
+ pFile->locktype));
+
+#ifndef SQLITE_TEST
+ UNUSED_PARAMETER(flags);
+#else
+ if( (flags&0x0F)==SQLITE_SYNC_FULL ){
+ sqlite3_fullsync_count++;
+ }
+ sqlite3_sync_count++;
+#endif
+
+ /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
+ ** no-op
+ */
+#ifdef SQLITE_NO_SYNC
+ OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
+ osGetCurrentProcessId(), pFile, pFile->h));
+ return SQLITE_OK;
+#else
+#if SQLITE_MAX_MMAP_SIZE>0
+ if( pFile->pMapRegion ){
+ if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
+ OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
+ "rc=SQLITE_OK\n", osGetCurrentProcessId(),
+ pFile, pFile->pMapRegion));
+ }else{
+ pFile->lastErrno = osGetLastError();
+ OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
+ "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
+ pFile, pFile->pMapRegion));
+ return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
+ "winSync1", pFile->zPath);
+ }
+ }
+#endif
+ rc = osFlushFileBuffers(pFile->h);
+ SimulateIOError( rc=FALSE );
+ if( rc ){
+ OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
+ osGetCurrentProcessId(), pFile, pFile->h));
+ return SQLITE_OK;
+ }else{
+ pFile->lastErrno = osGetLastError();
+ OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
+ osGetCurrentProcessId(), pFile, pFile->h));
+ return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
+ "winSync2", pFile->zPath);
+ }
+#endif
+}
+
+/*
+** Determine the current size of a file in bytes
+*/
+static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
+ winFile *pFile = (winFile*)id;
+ int rc = SQLITE_OK;
+
+ assert( id!=0 );
+ assert( pSize!=0 );
+ SimulateIOError(return SQLITE_IOERR_FSTAT);
+ OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
+
+#if SQLITE_OS_WINRT
+ {
+ FILE_STANDARD_INFO info;
+ if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
+ &info, sizeof(info)) ){
+ *pSize = info.EndOfFile.QuadPart;
+ }else{
+ pFile->lastErrno = osGetLastError();
+ rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
+ "winFileSize", pFile->zPath);
+ }
+ }
+#else
+ {
+ DWORD upperBits;
+ DWORD lowerBits;
+ DWORD lastErrno;
+
+ lowerBits = osGetFileSize(pFile->h, &upperBits);
+ *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
+ if( (lowerBits == INVALID_FILE_SIZE)
+ && ((lastErrno = osGetLastError())!=NO_ERROR) ){
+ pFile->lastErrno = lastErrno;
+ rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
+ "winFileSize", pFile->zPath);
+ }
+ }
+#endif
+ OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
+ pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
+ return rc;
+}
+
+/*
+** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
+*/
+#ifndef LOCKFILE_FAIL_IMMEDIATELY
+# define LOCKFILE_FAIL_IMMEDIATELY 1
+#endif
+
+#ifndef LOCKFILE_EXCLUSIVE_LOCK
+# define LOCKFILE_EXCLUSIVE_LOCK 2
+#endif
+
+/*
+** Historically, SQLite has used both the LockFile and LockFileEx functions.
+** When the LockFile function was used, it was always expected to fail
+** immediately if the lock could not be obtained. Also, it always expected to
+** obtain an exclusive lock. These flags are used with the LockFileEx function
+** and reflect those expectations; therefore, they should not be changed.
+*/
+#ifndef SQLITE_LOCKFILE_FLAGS
+# define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
+ LOCKFILE_EXCLUSIVE_LOCK)
+#endif
+
+/*
+** Currently, SQLite never calls the LockFileEx function without wanting the
+** call to fail immediately if the lock cannot be obtained.
+*/
+#ifndef SQLITE_LOCKFILEEX_FLAGS
+# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
+#endif
+
+/*
+** Acquire a reader lock.
+** Different API routines are called depending on whether or not this
+** is Win9x or WinNT.
+*/
+static int winGetReadLock(winFile *pFile){
+ int res;
+ OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
+ if( osIsNT() ){
+#if SQLITE_OS_WINCE
+ /*
+ ** NOTE: Windows CE is handled differently here due its lack of the Win32
+ ** API LockFileEx.
+ */
+ res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
+#else
+ res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
+ SHARED_SIZE, 0);
+#endif
+ }
+#ifdef SQLITE_WIN32_HAS_ANSI
+ else{
+ int lk;
+ sqlite3_randomness(sizeof(lk), &lk);
+ pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
+ res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
+ SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
+ }
+#endif
+ if( res == 0 ){
+ pFile->lastErrno = osGetLastError();
+ /* No need to log a failure to lock */
+ }
+ OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
+ return res;
+}
+
+/*
+** Undo a readlock
+*/
+static int winUnlockReadLock(winFile *pFile){
+ int res;
+ DWORD lastErrno;
+ OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
+ if( osIsNT() ){
+ res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
+ }
+#ifdef SQLITE_WIN32_HAS_ANSI
+ else{
+ res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
+ }
+#endif
+ if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
+ pFile->lastErrno = lastErrno;
+ winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
+ "winUnlockReadLock", pFile->zPath);
+ }
+ OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
+ return res;
+}
+
+/*
+** Lock the file with the lock specified by parameter locktype - one
+** of the following:
+**
+** (1) SHARED_LOCK
+** (2) RESERVED_LOCK
+** (3) PENDING_LOCK
+** (4) EXCLUSIVE_LOCK
+**
+** Sometimes when requesting one lock state, additional lock states
+** are inserted in between. The locking might fail on one of the later
+** transitions leaving the lock state different from what it started but
+** still short of its goal. The following chart shows the allowed
+** transitions and the inserted intermediate states:
+**
+** UNLOCKED -> SHARED
+** SHARED -> RESERVED
+** SHARED -> (PENDING) -> EXCLUSIVE
+** RESERVED -> (PENDING) -> EXCLUSIVE
+** PENDING -> EXCLUSIVE
+**
+** This routine will only increase a lock. The winUnlock() routine
+** erases all locks at once and returns us immediately to locking level 0.
+** It is not possible to lower the locking level one step at a time. You
+** must go straight to locking level 0.
+*/
+static int winLock(sqlite3_file *id, int locktype){
+ int rc = SQLITE_OK; /* Return code from subroutines */
+ int res = 1; /* Result of a Windows lock call */
+ int newLocktype; /* Set pFile->locktype to this value before exiting */
+ int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
+ winFile *pFile = (winFile*)id;
+ DWORD lastErrno = NO_ERROR;
+
+ assert( id!=0 );
+ OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
+ pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
+
+ /* If there is already a lock of this type or more restrictive on the
+ ** OsFile, do nothing. Don't use the end_lock: exit path, as
+ ** sqlite3OsEnterMutex() hasn't been called yet.
+ */
+ if( pFile->locktype>=locktype ){
+ OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
+ return SQLITE_OK;
+ }
+
+ /* Do not allow any kind of write-lock on a read-only database
+ */
+ if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
+ return SQLITE_IOERR_LOCK;
+ }
+
+ /* Make sure the locking sequence is correct
+ */
+ assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
+ assert( locktype!=PENDING_LOCK );
+ assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
+
+ /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
+ ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
+ ** the PENDING_LOCK byte is temporary.
+ */
+ newLocktype = pFile->locktype;
+ if( pFile->locktype==NO_LOCK
+ || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
+ ){
+ int cnt = 3;
+ while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
+ PENDING_BYTE, 0, 1, 0))==0 ){
+ /* Try 3 times to get the pending lock. This is needed to work
+ ** around problems caused by indexing and/or anti-virus software on
+ ** Windows systems.
+ ** If you are using this code as a model for alternative VFSes, do not
+ ** copy this retry logic. It is a hack intended for Windows only.
+ */
+ lastErrno = osGetLastError();
+ OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
+ pFile->h, cnt, res));
+ if( lastErrno==ERROR_INVALID_HANDLE ){
+ pFile->lastErrno = lastErrno;
+ rc = SQLITE_IOERR_LOCK;
+ OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
+ pFile->h, cnt, sqlite3ErrName(rc)));
+ return rc;
+ }
+ if( cnt ) sqlite3_win32_sleep(1);
+ }
+ gotPendingLock = res;
+ if( !res ){
+ lastErrno = osGetLastError();
+ }
+ }
+
+ /* Acquire a shared lock
+ */
+ if( locktype==SHARED_LOCK && res ){
+ assert( pFile->locktype==NO_LOCK );
+ res = winGetReadLock(pFile);
+ if( res ){
+ newLocktype = SHARED_LOCK;
+ }else{
+ lastErrno = osGetLastError();
+ }
+ }
+
+ /* Acquire a RESERVED lock
+ */
+ if( locktype==RESERVED_LOCK && res ){
+ assert( pFile->locktype==SHARED_LOCK );
+ res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
+ if( res ){
+ newLocktype = RESERVED_LOCK;
+ }else{
+ lastErrno = osGetLastError();
+ }
+ }
+
+ /* Acquire a PENDING lock
+ */
+ if( locktype==EXCLUSIVE_LOCK && res ){
+ newLocktype = PENDING_LOCK;
+ gotPendingLock = 0;
+ }
+
+ /* Acquire an EXCLUSIVE lock
+ */
+ if( locktype==EXCLUSIVE_LOCK && res ){
+ assert( pFile->locktype>=SHARED_LOCK );
+ res = winUnlockReadLock(pFile);
+ res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
+ SHARED_SIZE, 0);
+ if( res ){
+ newLocktype = EXCLUSIVE_LOCK;
+ }else{
+ lastErrno = osGetLastError();
+ winGetReadLock(pFile);
+ }
+ }
+
+ /* If we are holding a PENDING lock that ought to be released, then
+ ** release it now.
+ */
+ if( gotPendingLock && locktype==SHARED_LOCK ){
+ winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
+ }
+
+ /* Update the state of the lock has held in the file descriptor then
+ ** return the appropriate result code.
+ */
+ if( res ){
+ rc = SQLITE_OK;
+ }else{
+ pFile->lastErrno = lastErrno;
+ rc = SQLITE_BUSY;
+ OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
+ pFile->h, locktype, newLocktype));
+ }
+ pFile->locktype = (u8)newLocktype;
+ OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
+ pFile->h, pFile->locktype, sqlite3ErrName(rc)));
+ return rc;
+}
+
+/*
+** This routine checks if there is a RESERVED lock held on the specified
+** file by this or any other process. If such a lock is held, return
+** non-zero, otherwise zero.
+*/
+static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
+ int res;
+ winFile *pFile = (winFile*)id;
+
+ SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
+ OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
+
+ assert( id!=0 );
+ if( pFile->locktype>=RESERVED_LOCK ){
+ res = 1;
+ OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
+ }else{
+ res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
+ if( res ){
+ winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
+ }
+ res = !res;
+ OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
+ }
+ *pResOut = res;
+ OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
+ pFile->h, pResOut, *pResOut));
+ return SQLITE_OK;
+}
+
+/*
+** Lower the locking level on file descriptor id to locktype. locktype
+** must be either NO_LOCK or SHARED_LOCK.
+**
+** If the locking level of the file descriptor is already at or below
+** the requested locking level, this routine is a no-op.
+**
+** It is not possible for this routine to fail if the second argument
+** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
+** might return SQLITE_IOERR;
+*/
+static int winUnlock(sqlite3_file *id, int locktype){
+ int type;
+ winFile *pFile = (winFile*)id;
+ int rc = SQLITE_OK;
+ assert( pFile!=0 );
+ assert( locktype<=SHARED_LOCK );
+ OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
+ pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
+ type = pFile->locktype;
+ if( type>=EXCLUSIVE_LOCK ){
+ winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
+ if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
+ /* This should never happen. We should always be able to
+ ** reacquire the read lock */
+ rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
+ "winUnlock", pFile->zPath);
+ }
+ }
+ if( type>=RESERVED_LOCK ){
+ winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
+ }
+ if( locktype==NO_LOCK && type>=SHARED_LOCK ){
+ winUnlockReadLock(pFile);
+ }
+ if( type>=PENDING_LOCK ){
+ winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
+ }
+ pFile->locktype = (u8)locktype;
+ OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
+ pFile->h, pFile->locktype, sqlite3ErrName(rc)));
+ return rc;
+}
+
+/******************************************************************************
+****************************** No-op Locking **********************************
+**
+** Of the various locking implementations available, this is by far the
+** simplest: locking is ignored. No attempt is made to lock the database
+** file for reading or writing.
+**
+** This locking mode is appropriate for use on read-only databases
+** (ex: databases that are burned into CD-ROM, for example.) It can
+** also be used if the application employs some external mechanism to
+** prevent simultaneous access of the same database by two or more
+** database connections. But there is a serious risk of database
+** corruption if this locking mode is used in situations where multiple
+** database connections are accessing the same database file at the same
+** time and one or more of those connections are writing.
+*/
+
+static int winNolockLock(sqlite3_file *id, int locktype){
+ UNUSED_PARAMETER(id);
+ UNUSED_PARAMETER(locktype);
+ return SQLITE_OK;
+}
+
+static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
+ UNUSED_PARAMETER(id);
+ UNUSED_PARAMETER(pResOut);
+ return SQLITE_OK;
+}
+
+static int winNolockUnlock(sqlite3_file *id, int locktype){
+ UNUSED_PARAMETER(id);
+ UNUSED_PARAMETER(locktype);
+ return SQLITE_OK;
+}
+
+/******************* End of the no-op lock implementation *********************
+******************************************************************************/
+
+/*
+** If *pArg is initially negative then this is a query. Set *pArg to
+** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
+**
+** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
+*/
+static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
+ if( *pArg<0 ){
+ *pArg = (pFile->ctrlFlags & mask)!=0;
+ }else if( (*pArg)==0 ){
+ pFile->ctrlFlags &= ~mask;
+ }else{
+ pFile->ctrlFlags |= mask;
+ }
+}
+
+/* Forward references to VFS helper methods used for temporary files */
+static int winGetTempname(sqlite3_vfs *, char **);
+static int winIsDir(const void *);
+static BOOL winIsLongPathPrefix(const char *);
+static BOOL winIsDriveLetterAndColon(const char *);
+
+/*
+** Control and query of the open file handle.
+*/
+static int winFileControl(sqlite3_file *id, int op, void *pArg){
+ winFile *pFile = (winFile*)id;
+ OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
+ switch( op ){
+ case SQLITE_FCNTL_LOCKSTATE: {
+ *(int*)pArg = pFile->locktype;
+ OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_LAST_ERRNO: {
+ *(int*)pArg = (int)pFile->lastErrno;
+ OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_CHUNK_SIZE: {
+ pFile->szChunk = *(int *)pArg;
+ OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_SIZE_HINT: {
+ if( pFile->szChunk>0 ){
+ sqlite3_int64 oldSz;
+ int rc = winFileSize(id, &oldSz);
+ if( rc==SQLITE_OK ){
+ sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
+ if( newSz>oldSz ){
+ SimulateIOErrorBenign(1);
+ rc = winTruncate(id, newSz);
+ SimulateIOErrorBenign(0);
+ }
+ }
+ OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
+ return rc;
+ }
+ OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_PERSIST_WAL: {
+ winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
+ OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
+ winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
+ OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_VFSNAME: {
+ *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
+ OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_WIN32_AV_RETRY: {
+ int *a = (int*)pArg;
+ if( a[0]>0 ){
+ winIoerrRetry = a[0];
+ }else{
+ a[0] = winIoerrRetry;
+ }
+ if( a[1]>0 ){
+ winIoerrRetryDelay = a[1];
+ }else{
+ a[1] = winIoerrRetryDelay;
+ }
+ OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
+ return SQLITE_OK;
+ }
+ case SQLITE_FCNTL_WIN32_GET_HANDLE: {
+ LPHANDLE phFile = (LPHANDLE)pArg;
+ *phFile = pFile->h;
+ OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
+ return SQLITE_OK;
+ }
+#ifdef SQLITE_TEST
+ case SQLITE_FCNTL_WIN32_SET_HANDLE: {
+ LPHANDLE phFile = (LPHANDLE)pArg;
+ HANDLE hOldFile = pFile->h;
+ pFile->h = *phFile;
+ *phFile = hOldFile;
+ OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
+ hOldFile, pFile->h));
+ return SQLITE_OK;
+ }
+#endif
+ case SQLITE_FCNTL_TEMPFILENAME: {
+ char *zTFile = 0;
+ int rc = winGetTempname(pFile->pVfs, &zTFile);
+ if( rc==SQLITE_OK ){
+ *(char**)pArg = zTFile;
+ }
+ OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
+ return rc;
+ }
+#if SQLITE_MAX_MMAP_SIZE>0
+ case SQLITE_FCNTL_MMAP_SIZE: {
+ i64 newLimit = *(i64*)pArg;
+ int rc = SQLITE_OK;
+ if( newLimit>sqlite3GlobalConfig.mxMmap ){
+ newLimit = sqlite3GlobalConfig.mxMmap;
+ }
+
+ /* The value of newLimit may be eventually cast to (SIZE_T) and passed
+ ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
+ ** least a 64-bit type. */
+ if( newLimit>0 && sizeof(SIZE_T)<8 ){
+ newLimit = (newLimit & 0x7FFFFFFF);
+ }
+
+ *(i64*)pArg = pFile->mmapSizeMax;
+ if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
+ pFile->mmapSizeMax = newLimit;
+ if( pFile->mmapSize>0 ){
+ winUnmapfile(pFile);
+ rc = winMapfile(pFile, -1);
+ }
+ }
+ OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
+ return rc;
+ }
+#endif
+ }
+ OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
+ return SQLITE_NOTFOUND;
+}
+
+/*
+** Return the sector size in bytes of the underlying block device for
+** the specified file. This is almost always 512 bytes, but may be
+** larger for some devices.
+**
+** SQLite code assumes this function cannot fail. It also assumes that
+** if two files are created in the same file-system directory (i.e.
+** a database and its journal file) that the sector size will be the
+** same for both.
+*/
+static int winSectorSize(sqlite3_file *id){
+ (void)id;
+ return SQLITE_DEFAULT_SECTOR_SIZE;
+}
+
+/*
+** Return a vector of device characteristics.
+*/
+static int winDeviceCharacteristics(sqlite3_file *id){
+ winFile *p = (winFile*)id;
+ return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
+ ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
+}
+
+/*
+** Windows will only let you create file view mappings
+** on allocation size granularity boundaries.
+** During sqlite3_os_init() we do a GetSystemInfo()
+** to get the granularity size.
+*/
+static SYSTEM_INFO winSysInfo;
+
+#ifndef SQLITE_OMIT_WAL
+
+/*
+** Helper functions to obtain and relinquish the global mutex. The
+** global mutex is used to protect the winLockInfo objects used by
+** this file, all of which may be shared by multiple threads.
+**
+** Function winShmMutexHeld() is used to assert() that the global mutex
+** is held when required. This function is only used as part of assert()
+** statements. e.g.
+**
+** winShmEnterMutex()
+** assert( winShmMutexHeld() );
+** winShmLeaveMutex()
+*/
+static sqlite3_mutex *winBigLock = 0;
+static void winShmEnterMutex(void){
+ sqlite3_mutex_enter(winBigLock);
+}
+static void winShmLeaveMutex(void){
+ sqlite3_mutex_leave(winBigLock);
+}
+#ifndef NDEBUG
+static int winShmMutexHeld(void) {
+ return sqlite3_mutex_held(winBigLock);
+}
+#endif
+
+/*
+** Object used to represent a single file opened and mmapped to provide
+** shared memory. When multiple threads all reference the same
+** log-summary, each thread has its own winFile object, but they all
+** point to a single instance of this object. In other words, each
+** log-summary is opened only once per process.
+**
+** winShmMutexHeld() must be true when creating or destroying
+** this object or while reading or writing the following fields:
+**
+** nRef
+** pNext
+**
+** The following fields are read-only after the object is created:
+**
+** fid
+** zFilename
+**
+** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
+** winShmMutexHeld() is true when reading or writing any other field
+** in this structure.
+**
+*/
+struct winShmNode {
+ sqlite3_mutex *mutex; /* Mutex to access this object */
+ char *zFilename; /* Name of the file */
+ winFile hFile; /* File handle from winOpen */
+
+ int szRegion; /* Size of shared-memory regions */
+ int nRegion; /* Size of array apRegion */
+ u8 isReadonly; /* True if read-only */
+ u8 isUnlocked; /* True if no DMS lock held */
+
+ struct ShmRegion {
+ HANDLE hMap; /* File handle from CreateFileMapping */
+ void *pMap;
+ } *aRegion;
+ DWORD lastErrno; /* The Windows errno from the last I/O error */
+
+ int nRef; /* Number of winShm objects pointing to this */
+ winShm *pFirst; /* All winShm objects pointing to this */
+ winShmNode *pNext; /* Next in list of all winShmNode objects */
+#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
+ u8 nextShmId; /* Next available winShm.id value */
+#endif
+};
+
+/*
+** A global array of all winShmNode objects.
+**
+** The winShmMutexHeld() must be true while reading or writing this list.
+*/
+static winShmNode *winShmNodeList = 0;
+
+/*
+** Structure used internally by this VFS to record the state of an
+** open shared memory connection.
+**
+** The following fields are initialized when this object is created and
+** are read-only thereafter:
+**
+** winShm.pShmNode
+** winShm.id
+**
+** All other fields are read/write. The winShm.pShmNode->mutex must be held
+** while accessing any read/write fields.
+*/
+struct winShm {
+ winShmNode *pShmNode; /* The underlying winShmNode object */
+ winShm *pNext; /* Next winShm with the same winShmNode */
+ u8 hasMutex; /* True if holding the winShmNode mutex */
+ u16 sharedMask; /* Mask of shared locks held */
+ u16 exclMask; /* Mask of exclusive locks held */
+#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
+ u8 id; /* Id of this connection with its winShmNode */
+#endif
+};
+
+/*
+** Constants used for locking
+*/
+#define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
+#define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
+
+/*
+** Apply advisory locks for all n bytes beginning at ofst.
+*/
+#define WINSHM_UNLCK 1
+#define WINSHM_RDLCK 2
+#define WINSHM_WRLCK 3
+static int winShmSystemLock(
+ winShmNode *pFile, /* Apply locks to this open shared-memory segment */
+ int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
+ int ofst, /* Offset to first byte to be locked/unlocked */
+ int nByte /* Number of bytes to lock or unlock */
+){
+ int rc = 0; /* Result code form Lock/UnlockFileEx() */
+
+ /* Access to the winShmNode object is serialized by the caller */
+ assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );
+
+ OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
+ pFile->hFile.h, lockType, ofst, nByte));
+
+ /* Release/Acquire the system-level lock */
+ if( lockType==WINSHM_UNLCK ){
+ rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
+ }else{
+ /* Initialize the locking parameters */
+ DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
+ if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
+ rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
+ }
+
+ if( rc!= 0 ){
+ rc = SQLITE_OK;
+ }else{
+ pFile->lastErrno = osGetLastError();
+ rc = SQLITE_BUSY;
+ }
+
+ OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
+ pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
+ "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
+
+ return rc;
+}
+
+/* Forward references to VFS methods */
+static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
+static int winDelete(sqlite3_vfs *,const char*,int);
+
+/*
+** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
+**
+** This is not a VFS shared-memory method; it is a utility function called
+** by VFS shared-memory methods.
+*/
+static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
+ winShmNode **pp;
+ winShmNode *p;
+ assert( winShmMutexHeld() );
+ OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
+ osGetCurrentProcessId(), deleteFlag));
+ pp = &winShmNodeList;
+ while( (p = *pp)!=0 ){
+ if( p->nRef==0 ){
+ int i;
+ if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
+ for(i=0; i<p->nRegion; i++){
+ BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
+ OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
+ osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
+ UNUSED_VARIABLE_VALUE(bRc);
+ bRc = osCloseHandle(p->aRegion[i].hMap);
+ OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
+ osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
+ UNUSED_VARIABLE_VALUE(bRc);
+ }
+ if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
+ SimulateIOErrorBenign(1);
+ winClose((sqlite3_file *)&p->hFile);
+ SimulateIOErrorBenign(0);
+ }
+ if( deleteFlag ){
+ SimulateIOErrorBenign(1);
+ sqlite3BeginBenignMalloc();
+ winDelete(pVfs, p->zFilename, 0);
+ sqlite3EndBenignMalloc();
+ SimulateIOErrorBenign(0);
+ }
+ *pp = p->pNext;
+ sqlite3_free(p->aRegion);
+ sqlite3_free(p);
+ }else{
+ pp = &p->pNext;
+ }
+ }
+}
+
+/*
+** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
+** take it now. Return SQLITE_OK if successful, or an SQLite error
+** code otherwise.
+**
+** If the DMS cannot be locked because this is a readonly_shm=1
+** connection and no other process already holds a lock, return
+** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
+*/
+static int winLockSharedMemory(winShmNode *pShmNode){
+ int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);
+
+ if( rc==SQLITE_OK ){
+ if( pShmNode->isReadonly ){
+ pShmNode->isUnlocked = 1;
+ winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
+ return SQLITE_READONLY_CANTINIT;
+ }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
+ winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
+ return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
+ "winLockSharedMemory", pShmNode->zFilename);
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
+ }
+
+ return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
+}
+
+/*
+** Open the shared-memory area associated with database file pDbFd.
+**
+** When opening a new shared-memory file, if no other instances of that
+** file are currently open, in this process or in other processes, then
+** the file must be truncated to zero length or have its header cleared.
+*/
+static int winOpenSharedMemory(winFile *pDbFd){
+ struct winShm *p; /* The connection to be opened */
+ winShmNode *pShmNode = 0; /* The underlying mmapped file */
+ int rc = SQLITE_OK; /* Result code */
+ winShmNode *pNew; /* Newly allocated winShmNode */
+ int nName; /* Size of zName in bytes */
+
+ assert( pDbFd->pShm==0 ); /* Not previously opened */
+
+ /* Allocate space for the new sqlite3_shm object. Also speculatively
+ ** allocate space for a new winShmNode and filename.
+ */
+ p = sqlite3MallocZero( sizeof(*p) );
+ if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
+ nName = sqlite3Strlen30(pDbFd->zPath);
+ pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
+ if( pNew==0 ){
+ sqlite3_free(p);
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ pNew->zFilename = (char*)&pNew[1];
+ sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
+ sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
+
+ /* Look to see if there is an existing winShmNode that can be used.
+ ** If no matching winShmNode currently exists, create a new one.
+ */
+ winShmEnterMutex();
+ for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
+ /* TBD need to come up with better match here. Perhaps
+ ** use FILE_ID_BOTH_DIR_INFO Structure.
+ */
+ if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
+ }
+ if( pShmNode ){
+ sqlite3_free(pNew);
+ }else{
+ int inFlags = SQLITE_OPEN_WAL;
+ int outFlags = 0;
+
+ pShmNode = pNew;
+ pNew = 0;
+ ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
+ pShmNode->pNext = winShmNodeList;
+ winShmNodeList = pShmNode;
+
+ if( sqlite3GlobalConfig.bCoreMutex ){
+ pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
+ if( pShmNode->mutex==0 ){
+ rc = SQLITE_IOERR_NOMEM_BKPT;
+ goto shm_open_err;
+ }
+ }
+
+ if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
+ inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
+ }else{
+ inFlags |= SQLITE_OPEN_READONLY;
+ }
+ rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
+ (sqlite3_file*)&pShmNode->hFile,
+ inFlags, &outFlags);
+ if( rc!=SQLITE_OK ){
+ rc = winLogError(rc, osGetLastError(), "winOpenShm",
+ pShmNode->zFilename);
+ goto shm_open_err;
+ }
+ if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;
+
+ rc = winLockSharedMemory(pShmNode);
+ if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
+ }
+
+ /* Make the new connection a child of the winShmNode */
+ p->pShmNode = pShmNode;
+#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
+ p->id = pShmNode->nextShmId++;
+#endif
+ pShmNode->nRef++;
+ pDbFd->pShm = p;
+ winShmLeaveMutex();
+
+ /* The reference count on pShmNode has already been incremented under
+ ** the cover of the winShmEnterMutex() mutex and the pointer from the
+ ** new (struct winShm) object to the pShmNode has been set. All that is
+ ** left to do is to link the new object into the linked list starting
+ ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
+ ** mutex.
+ */
+ sqlite3_mutex_enter(pShmNode->mutex);
+ p->pNext = pShmNode->pFirst;
+ pShmNode->pFirst = p;
+ sqlite3_mutex_leave(pShmNode->mutex);
+ return rc;
+
+ /* Jump here on any error */
+shm_open_err:
+ winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
+ winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
+ sqlite3_free(p);
+ sqlite3_free(pNew);
+ winShmLeaveMutex();
+ return rc;
+}
+
+/*
+** Close a connection to shared-memory. Delete the underlying
+** storage if deleteFlag is true.
+*/
+static int winShmUnmap(
+ sqlite3_file *fd, /* Database holding shared memory */
+ int deleteFlag /* Delete after closing if true */
+){
+ winFile *pDbFd; /* Database holding shared-memory */
+ winShm *p; /* The connection to be closed */
+ winShmNode *pShmNode; /* The underlying shared-memory file */
+ winShm **pp; /* For looping over sibling connections */
+
+ pDbFd = (winFile*)fd;
+ p = pDbFd->pShm;
+ if( p==0 ) return SQLITE_OK;
+ pShmNode = p->pShmNode;
+
+ /* Remove connection p from the set of connections associated
+ ** with pShmNode */
+ sqlite3_mutex_enter(pShmNode->mutex);
+ for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
+ *pp = p->pNext;
+
+ /* Free the connection p */
+ sqlite3_free(p);
+ pDbFd->pShm = 0;
+ sqlite3_mutex_leave(pShmNode->mutex);
+
+ /* If pShmNode->nRef has reached 0, then close the underlying
+ ** shared-memory file, too */
+ winShmEnterMutex();
+ assert( pShmNode->nRef>0 );
+ pShmNode->nRef--;
+ if( pShmNode->nRef==0 ){
+ winShmPurge(pDbFd->pVfs, deleteFlag);
+ }
+ winShmLeaveMutex();
+
+ return SQLITE_OK;
+}
+
+/*
+** Change the lock state for a shared-memory segment.
+*/
+static int winShmLock(
+ sqlite3_file *fd, /* Database file holding the shared memory */
+ int ofst, /* First lock to acquire or release */
+ int n, /* Number of locks to acquire or release */
+ int flags /* What to do with the lock */
+){
+ winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
+ winShm *p = pDbFd->pShm; /* The shared memory being locked */
+ winShm *pX; /* For looping over all siblings */
+ winShmNode *pShmNode = p->pShmNode;
+ int rc = SQLITE_OK; /* Result code */
+ u16 mask; /* Mask of locks to take or release */
+
+ assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
+ assert( n>=1 );
+ assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
+ || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
+ || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
+ || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
+ assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
+
+ mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
+ assert( n>1 || mask==(1<<ofst) );
+ sqlite3_mutex_enter(pShmNode->mutex);
+ if( flags & SQLITE_SHM_UNLOCK ){
+ u16 allMask = 0; /* Mask of locks held by siblings */
+
+ /* See if any siblings hold this same lock */
+ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
+ if( pX==p ) continue;
+ assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
+ allMask |= pX->sharedMask;
+ }
+
+ /* Unlock the system-level locks */
+ if( (mask & allMask)==0 ){
+ rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
+ }else{
+ rc = SQLITE_OK;
+ }
+
+ /* Undo the local locks */
+ if( rc==SQLITE_OK ){
+ p->exclMask &= ~mask;
+ p->sharedMask &= ~mask;
+ }
+ }else if( flags & SQLITE_SHM_SHARED ){
+ u16 allShared = 0; /* Union of locks held by connections other than "p" */
+
+ /* Find out which shared locks are already held by sibling connections.
+ ** If any sibling already holds an exclusive lock, go ahead and return
+ ** SQLITE_BUSY.
+ */
+ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
+ if( (pX->exclMask & mask)!=0 ){
+ rc = SQLITE_BUSY;
+ break;
+ }
+ allShared |= pX->sharedMask;
+ }
+
+ /* Get shared locks at the system level, if necessary */
+ if( rc==SQLITE_OK ){
+ if( (allShared & mask)==0 ){
+ rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
+ }else{
+ rc = SQLITE_OK;
+ }
+ }
+
+ /* Get the local shared locks */
+ if( rc==SQLITE_OK ){
+ p->sharedMask |= mask;
+ }
+ }else{
+ /* Make sure no sibling connections hold locks that will block this
+ ** lock. If any do, return SQLITE_BUSY right away.
+ */
+ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
+ if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
+ rc = SQLITE_BUSY;
+ break;
+ }
+ }
+
+ /* Get the exclusive locks at the system level. Then if successful
+ ** also mark the local connection as being locked.
+ */
+ if( rc==SQLITE_OK ){
+ rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
+ if( rc==SQLITE_OK ){
+ assert( (p->sharedMask & mask)==0 );
+ p->exclMask |= mask;
+ }
+ }
+ }
+ sqlite3_mutex_leave(pShmNode->mutex);
+ OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
+ osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
+ sqlite3ErrName(rc)));
+ return rc;
+}
+
+/*
+** Implement a memory barrier or memory fence on shared memory.
+**
+** All loads and stores begun before the barrier must complete before
+** any load or store begun after the barrier.
+*/
+static void winShmBarrier(
+ sqlite3_file *fd /* Database holding the shared memory */
+){
+ UNUSED_PARAMETER(fd);
+ sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
+ winShmEnterMutex(); /* Also mutex, for redundancy */
+ winShmLeaveMutex();
+}
+
+/*
+** This function is called to obtain a pointer to region iRegion of the
+** shared-memory associated with the database file fd. Shared-memory regions
+** are numbered starting from zero. Each shared-memory region is szRegion
+** bytes in size.
+**
+** If an error occurs, an error code is returned and *pp is set to NULL.
+**
+** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
+** region has not been allocated (by any client, including one running in a
+** separate process), then *pp is set to NULL and SQLITE_OK returned. If
+** isWrite is non-zero and the requested shared-memory region has not yet
+** been allocated, it is allocated by this function.
+**
+** If the shared-memory region has already been allocated or is allocated by
+** this call as described above, then it is mapped into this processes
+** address space (if it is not already), *pp is set to point to the mapped
+** memory and SQLITE_OK returned.
+*/
+static int winShmMap(
+ sqlite3_file *fd, /* Handle open on database file */
+ int iRegion, /* Region to retrieve */
+ int szRegion, /* Size of regions */
+ int isWrite, /* True to extend file if necessary */
+ void volatile **pp /* OUT: Mapped memory */
+){
+ winFile *pDbFd = (winFile*)fd;
+ winShm *pShm = pDbFd->pShm;
+ winShmNode *pShmNode;
+ DWORD protect = PAGE_READWRITE;
+ DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;
+ int rc = SQLITE_OK;
+
+ if( !pShm ){
+ rc = winOpenSharedMemory(pDbFd);
+ if( rc!=SQLITE_OK ) return rc;
+ pShm = pDbFd->pShm;
+ assert( pShm!=0 );
+ }
+ pShmNode = pShm->pShmNode;
+
+ sqlite3_mutex_enter(pShmNode->mutex);
+ if( pShmNode->isUnlocked ){
+ rc = winLockSharedMemory(pShmNode);
+ if( rc!=SQLITE_OK ) goto shmpage_out;
+ pShmNode->isUnlocked = 0;
+ }
+ assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
+
+ if( pShmNode->nRegion<=iRegion ){
+ struct ShmRegion *apNew; /* New aRegion[] array */
+ int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
+ sqlite3_int64 sz; /* Current size of wal-index file */
+
+ pShmNode->szRegion = szRegion;
+
+ /* The requested region is not mapped into this processes address space.
+ ** Check to see if it has been allocated (i.e. if the wal-index file is
+ ** large enough to contain the requested region).
+ */
+ rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
+ if( rc!=SQLITE_OK ){
+ rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
+ "winShmMap1", pDbFd->zPath);
+ goto shmpage_out;
+ }
+
+ if( sz<nByte ){
+ /* The requested memory region does not exist. If isWrite is set to
+ ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
+ **
+ ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
+ ** the requested memory region.
+ */
+ if( !isWrite ) goto shmpage_out;
+ rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
+ if( rc!=SQLITE_OK ){
+ rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
+ "winShmMap2", pDbFd->zPath);
+ goto shmpage_out;
+ }
+ }
+
+ /* Map the requested memory region into this processes address space. */
+ apNew = (struct ShmRegion *)sqlite3_realloc64(
+ pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
+ );
+ if( !apNew ){
+ rc = SQLITE_IOERR_NOMEM_BKPT;
+ goto shmpage_out;
+ }
+ pShmNode->aRegion = apNew;
+
+ if( pShmNode->isReadonly ){
+ protect = PAGE_READONLY;
+ flags = FILE_MAP_READ;
+ }
+
+ while( pShmNode->nRegion<=iRegion ){
+ HANDLE hMap = NULL; /* file-mapping handle */
+ void *pMap = 0; /* Mapped memory region */
+
+#if SQLITE_OS_WINRT
+ hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
+ NULL, protect, nByte, NULL
+ );
+#elif defined(SQLITE_WIN32_HAS_WIDE)
+ hMap = osCreateFileMappingW(pShmNode->hFile.h,
+ NULL, protect, 0, nByte, NULL
+ );
+#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
+ hMap = osCreateFileMappingA(pShmNode->hFile.h,
+ NULL, protect, 0, nByte, NULL
+ );
+#endif
+ OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
+ osGetCurrentProcessId(), pShmNode->nRegion, nByte,
+ hMap ? "ok" : "failed"));
+ if( hMap ){
+ int iOffset = pShmNode->nRegion*szRegion;
+ int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
+#if SQLITE_OS_WINRT
+ pMap = osMapViewOfFileFromApp(hMap, flags,
+ iOffset - iOffsetShift, szRegion + iOffsetShift
+ );
+#else
+ pMap = osMapViewOfFile(hMap, flags,
+ 0, iOffset - iOffsetShift, szRegion + iOffsetShift
+ );
+#endif
+ OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
+ osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
+ szRegion, pMap ? "ok" : "failed"));
+ }
+ if( !pMap ){
+ pShmNode->lastErrno = osGetLastError();
+ rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
+ "winShmMap3", pDbFd->zPath);
+ if( hMap ) osCloseHandle(hMap);
+ goto shmpage_out;
+ }
+
+ pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
+ pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
+ pShmNode->nRegion++;
+ }
+ }
+
+shmpage_out:
+ if( pShmNode->nRegion>iRegion ){
+ int iOffset = iRegion*szRegion;
+ int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
+ char *p = (char *)pShmNode->aRegion[iRegion].pMap;
+ *pp = (void *)&p[iOffsetShift];
+ }else{
+ *pp = 0;
+ }
+ if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
+ sqlite3_mutex_leave(pShmNode->mutex);
+ return rc;
+}
+
+#else
+# define winShmMap 0
+# define winShmLock 0
+# define winShmBarrier 0
+# define winShmUnmap 0
+#endif /* #ifndef SQLITE_OMIT_WAL */
+
+/*
+** Cleans up the mapped region of the specified file, if any.
+*/
+#if SQLITE_MAX_MMAP_SIZE>0
+static int winUnmapfile(winFile *pFile){
+ assert( pFile!=0 );
+ OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
+ "mmapSize=%lld, mmapSizeMax=%lld\n",
+ osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
+ pFile->mmapSize, pFile->mmapSizeMax));
+ if( pFile->pMapRegion ){
+ if( !osUnmapViewOfFile(pFile->pMapRegion) ){
+ pFile->lastErrno = osGetLastError();
+ OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
+ "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
+ pFile->pMapRegion));
+ return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
+ "winUnmapfile1", pFile->zPath);
+ }
+ pFile->pMapRegion = 0;
+ pFile->mmapSize = 0;
+ }
+ if( pFile->hMap!=NULL ){
+ if( !osCloseHandle(pFile->hMap) ){
+ pFile->lastErrno = osGetLastError();
+ OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
+ osGetCurrentProcessId(), pFile, pFile->hMap));
+ return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
+ "winUnmapfile2", pFile->zPath);
+ }
+ pFile->hMap = NULL;
+ }
+ OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
+ osGetCurrentProcessId(), pFile));
+ return SQLITE_OK;
+}
+
+/*
+** Memory map or remap the file opened by file-descriptor pFd (if the file
+** is already mapped, the existing mapping is replaced by the new). Or, if
+** there already exists a mapping for this file, and there are still
+** outstanding xFetch() references to it, this function is a no-op.
+**
+** If parameter nByte is non-negative, then it is the requested size of
+** the mapping to create. Otherwise, if nByte is less than zero, then the
+** requested size is the size of the file on disk. The actual size of the
+** created mapping is either the requested size or the value configured
+** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
+**
+** SQLITE_OK is returned if no error occurs (even if the mapping is not
+** recreated as a result of outstanding references) or an SQLite error
+** code otherwise.
+*/
+static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
+ sqlite3_int64 nMap = nByte;
+ int rc;
+
+ assert( nMap>=0 || pFd->nFetchOut==0 );
+ OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
+ osGetCurrentProcessId(), pFd, nByte));
+
+ if( pFd->nFetchOut>0 ) return SQLITE_OK;
+
+ if( nMap<0 ){
+ rc = winFileSize((sqlite3_file*)pFd, &nMap);
+ if( rc ){
+ OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
+ osGetCurrentProcessId(), pFd));
+ return SQLITE_IOERR_FSTAT;
+ }
+ }
+ if( nMap>pFd->mmapSizeMax ){
+ nMap = pFd->mmapSizeMax;
+ }
+ nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
+
+ if( nMap==0 && pFd->mmapSize>0 ){
+ winUnmapfile(pFd);
+ }
+ if( nMap!=pFd->mmapSize ){
+ void *pNew = 0;
+ DWORD protect = PAGE_READONLY;
+ DWORD flags = FILE_MAP_READ;
+
+ winUnmapfile(pFd);
+#ifdef SQLITE_MMAP_READWRITE
+ if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
+ protect = PAGE_READWRITE;
+ flags |= FILE_MAP_WRITE;
+ }
+#endif
+#if SQLITE_OS_WINRT
+ pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
+#elif defined(SQLITE_WIN32_HAS_WIDE)
+ pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
+ (DWORD)((nMap>>32) & 0xffffffff),
+ (DWORD)(nMap & 0xffffffff), NULL);
+#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
+ pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
+ (DWORD)((nMap>>32) & 0xffffffff),
+ (DWORD)(nMap & 0xffffffff), NULL);
+#endif
+ if( pFd->hMap==NULL ){
+ pFd->lastErrno = osGetLastError();
+ rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
+ "winMapfile1", pFd->zPath);
+ /* Log the error, but continue normal operation using xRead/xWrite */
+ OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
+ osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
+ return SQLITE_OK;
+ }
+ assert( (nMap % winSysInfo.dwPageSize)==0 );
+ assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
+#if SQLITE_OS_WINRT
+ pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
+#else
+ pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
+#endif
+ if( pNew==NULL ){
+ osCloseHandle(pFd->hMap);
+ pFd->hMap = NULL;
+ pFd->lastErrno = osGetLastError();
+ rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
+ "winMapfile2", pFd->zPath);
+ /* Log the error, but continue normal operation using xRead/xWrite */
+ OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
+ osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
+ return SQLITE_OK;
+ }
+ pFd->pMapRegion = pNew;
+ pFd->mmapSize = nMap;
+ }
+
+ OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
+ osGetCurrentProcessId(), pFd));
+ return SQLITE_OK;
+}
+#endif /* SQLITE_MAX_MMAP_SIZE>0 */
+
+/*
+** If possible, return a pointer to a mapping of file fd starting at offset
+** iOff. The mapping must be valid for at least nAmt bytes.
+**
+** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
+** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
+** Finally, if an error does occur, return an SQLite error code. The final
+** value of *pp is undefined in this case.
+**
+** If this function does return a pointer, the caller must eventually
+** release the reference by calling winUnfetch().
+*/
+static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
+#if SQLITE_MAX_MMAP_SIZE>0
+ winFile *pFd = (winFile*)fd; /* The underlying database file */
+#endif
+ *pp = 0;
+
+ OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
+ osGetCurrentProcessId(), fd, iOff, nAmt, pp));
+
+#if SQLITE_MAX_MMAP_SIZE>0
+ if( pFd->mmapSizeMax>0 ){
+ if( pFd->pMapRegion==0 ){
+ int rc = winMapfile(pFd, -1);
+ if( rc!=SQLITE_OK ){
+ OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
+ osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
+ return rc;
+ }
+ }
+ if( pFd->mmapSize >= iOff+nAmt ){
+ assert( pFd->pMapRegion!=0 );
+ *pp = &((u8 *)pFd->pMapRegion)[iOff];
+ pFd->nFetchOut++;
+ }
+ }
+#endif
+
+ OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
+ osGetCurrentProcessId(), fd, pp, *pp));
+ return SQLITE_OK;
+}
+
+/*
+** If the third argument is non-NULL, then this function releases a
+** reference obtained by an earlier call to winFetch(). The second
+** argument passed to this function must be the same as the corresponding
+** argument that was passed to the winFetch() invocation.
+**
+** Or, if the third argument is NULL, then this function is being called
+** to inform the VFS layer that, according to POSIX, any existing mapping
+** may now be invalid and should be unmapped.
+*/
+static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
+#if SQLITE_MAX_MMAP_SIZE>0
+ winFile *pFd = (winFile*)fd; /* The underlying database file */
+
+ /* If p==0 (unmap the entire file) then there must be no outstanding
+ ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
+ ** then there must be at least one outstanding. */
+ assert( (p==0)==(pFd->nFetchOut==0) );
+
+ /* If p!=0, it must match the iOff value. */
+ assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
+
+ OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
+ osGetCurrentProcessId(), pFd, iOff, p));
+
+ if( p ){
+ pFd->nFetchOut--;
+ }else{
+ /* FIXME: If Windows truly always prevents truncating or deleting a
+ ** file while a mapping is held, then the following winUnmapfile() call
+ ** is unnecessary can be omitted - potentially improving
+ ** performance. */
+ winUnmapfile(pFd);
+ }
+
+ assert( pFd->nFetchOut>=0 );
+#endif
+
+ OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
+ osGetCurrentProcessId(), fd));
+ return SQLITE_OK;
+}
+
+/*
+** Here ends the implementation of all sqlite3_file methods.
+**
+********************** End sqlite3_file Methods *******************************
+******************************************************************************/
+
+/*
+** This vector defines all the methods that can operate on an
+** sqlite3_file for win32.
+*/
+static const sqlite3_io_methods winIoMethod = {
+ 3, /* iVersion */
+ winClose, /* xClose */
+ winRead, /* xRead */
+ winWrite, /* xWrite */
+ winTruncate, /* xTruncate */
+ winSync, /* xSync */
+ winFileSize, /* xFileSize */
+ winLock, /* xLock */
+ winUnlock, /* xUnlock */
+ winCheckReservedLock, /* xCheckReservedLock */
+ winFileControl, /* xFileControl */
+ winSectorSize, /* xSectorSize */
+ winDeviceCharacteristics, /* xDeviceCharacteristics */
+ winShmMap, /* xShmMap */
+ winShmLock, /* xShmLock */
+ winShmBarrier, /* xShmBarrier */
+ winShmUnmap, /* xShmUnmap */
+ winFetch, /* xFetch */
+ winUnfetch /* xUnfetch */
+};
+
+/*
+** This vector defines all the methods that can operate on an
+** sqlite3_file for win32 without performing any locking.
+*/
+static const sqlite3_io_methods winIoNolockMethod = {
+ 3, /* iVersion */
+ winClose, /* xClose */
+ winRead, /* xRead */
+ winWrite, /* xWrite */
+ winTruncate, /* xTruncate */
+ winSync, /* xSync */
+ winFileSize, /* xFileSize */
+ winNolockLock, /* xLock */
+ winNolockUnlock, /* xUnlock */
+ winNolockCheckReservedLock, /* xCheckReservedLock */
+ winFileControl, /* xFileControl */
+ winSectorSize, /* xSectorSize */
+ winDeviceCharacteristics, /* xDeviceCharacteristics */
+ winShmMap, /* xShmMap */
+ winShmLock, /* xShmLock */
+ winShmBarrier, /* xShmBarrier */
+ winShmUnmap, /* xShmUnmap */
+ winFetch, /* xFetch */
+ winUnfetch /* xUnfetch */
+};
+
+static winVfsAppData winAppData = {
+ &winIoMethod, /* pMethod */
+ 0, /* pAppData */
+ 0 /* bNoLock */
+};
+
+static winVfsAppData winNolockAppData = {
+ &winIoNolockMethod, /* pMethod */
+ 0, /* pAppData */
+ 1 /* bNoLock */
+};
+
+/****************************************************************************
+**************************** sqlite3_vfs methods ****************************
+**
+** This division contains the implementation of methods on the
+** sqlite3_vfs object.
+*/
+
+#if defined(__CYGWIN__)
+/*
+** Convert a filename from whatever the underlying operating system
+** supports for filenames into UTF-8. Space to hold the result is
+** obtained from malloc and must be freed by the calling function.
+*/
+static char *winConvertToUtf8Filename(const void *zFilename){
+ char *zConverted = 0;
+ if( osIsNT() ){
+ zConverted = winUnicodeToUtf8(zFilename);
+ }
+#ifdef SQLITE_WIN32_HAS_ANSI
+ else{
+ zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
+ }
+#endif
+ /* caller will handle out of memory */
+ return zConverted;
+}
+#endif
+
+/*
+** Convert a UTF-8 filename into whatever form the underlying
+** operating system wants filenames in. Space to hold the result
+** is obtained from malloc and must be freed by the calling
+** function.
+*/
+static void *winConvertFromUtf8Filename(const char *zFilename){
+ void *zConverted = 0;
+ if( osIsNT() ){
+ zConverted = winUtf8ToUnicode(zFilename);
+ }
+#ifdef SQLITE_WIN32_HAS_ANSI
+ else{
+ zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
+ }
+#endif
+ /* caller will handle out of memory */
+ return zConverted;
+}
+
+/*
+** This function returns non-zero if the specified UTF-8 string buffer
+** ends with a directory separator character or one was successfully
+** added to it.
+*/
+static int winMakeEndInDirSep(int nBuf, char *zBuf){
+ if( zBuf ){
+ int nLen = sqlite3Strlen30(zBuf);
+ if( nLen>0 ){
+ if( winIsDirSep(zBuf[nLen-1]) ){
+ return 1;
+ }else if( nLen+1<nBuf ){
+ zBuf[nLen] = winGetDirSep();
+ zBuf[nLen+1] = '\0';
+ return 1;
+ }
+ }
+ }
+ return 0;
+}
+
+/*
+** Create a temporary file name and store the resulting pointer into pzBuf.
+** The pointer returned in pzBuf must be freed via sqlite3_free().
+*/
+static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
+ static char zChars[] =
+ "abcdefghijklmnopqrstuvwxyz"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "0123456789";
+ size_t i, j;
+ int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
+ int nMax, nBuf, nDir, nLen;
+ char *zBuf;
+
+ /* It's odd to simulate an io-error here, but really this is just
+ ** using the io-error infrastructure to test that SQLite handles this
+ ** function failing.
+ */
+ SimulateIOError( return SQLITE_IOERR );
+
+ /* Allocate a temporary buffer to store the fully qualified file
+ ** name for the temporary file. If this fails, we cannot continue.
+ */
+ nMax = pVfs->mxPathname; nBuf = nMax + 2;
+ zBuf = sqlite3MallocZero( nBuf );
+ if( !zBuf ){
+ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+
+ /* Figure out the effective temporary directory. First, check if one
+ ** has been explicitly set by the application; otherwise, use the one
+ ** configured by the operating system.
+ */
+ nDir = nMax - (nPre + 15);
+ assert( nDir>0 );
+ if( sqlite3_temp_directory ){
+ int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
+ if( nDirLen>0 ){
+ if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
+ nDirLen++;
+ }
+ if( nDirLen>nDir ){
+ sqlite3_free(zBuf);
+ OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
+ return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
+ }
+ sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
+ }
+ }
+#if defined(__CYGWIN__)
+ else{
+ static const char *azDirs[] = {
+ 0, /* getenv("SQLITE_TMPDIR") */
+ 0, /* getenv("TMPDIR") */
+ 0, /* getenv("TMP") */
+ 0, /* getenv("TEMP") */
+ 0, /* getenv("USERPROFILE") */
+ "/var/tmp",
+ "/usr/tmp",
+ "/tmp",
+ ".",
+ 0 /* List terminator */
+ };
+ unsigned int i;
+ const char *zDir = 0;
+
+ if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
+ if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
+ if( !azDirs[2] ) azDirs[2] = getenv("TMP");
+ if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
+ if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
+ for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
+ void *zConverted;
+ if( zDir==0 ) continue;
+ /* If the path starts with a drive letter followed by the colon
+ ** character, assume it is already a native Win32 path; otherwise,
+ ** it must be converted to a native Win32 path via the Cygwin API
+ ** prior to using it.
+ */
+ if( winIsDriveLetterAndColon(zDir) ){
+ zConverted = winConvertFromUtf8Filename(zDir);
+ if( !zConverted ){
+ sqlite3_free(zBuf);
+ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ if( winIsDir(zConverted) ){
+ sqlite3_snprintf(nMax, zBuf, "%s", zDir);
+ sqlite3_free(zConverted);
+ break;
+ }
+ sqlite3_free(zConverted);
+ }else{
+ zConverted = sqlite3MallocZero( nMax+1 );
+ if( !zConverted ){
+ sqlite3_free(zBuf);
+ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ if( cygwin_conv_path(
+ osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
+ zConverted, nMax+1)<0 ){
+ sqlite3_free(zConverted);
+ sqlite3_free(zBuf);
+ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
+ return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
+ "winGetTempname2", zDir);
+ }
+ if( winIsDir(zConverted) ){
+ /* At this point, we know the candidate directory exists and should
+ ** be used. However, we may need to convert the string containing
+ ** its name into UTF-8 (i.e. if it is UTF-16 right now).
+ */
+ char *zUtf8 = winConvertToUtf8Filename(zConverted);
+ if( !zUtf8 ){
+ sqlite3_free(zConverted);
+ sqlite3_free(zBuf);
+ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
+ sqlite3_free(zUtf8);
+ sqlite3_free(zConverted);
+ break;
+ }
+ sqlite3_free(zConverted);
+ }
+ }
+ }
+#elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
+ else if( osIsNT() ){
+ char *zMulti;
+ LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
+ if( !zWidePath ){
+ sqlite3_free(zBuf);
+ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ if( osGetTempPathW(nMax, zWidePath)==0 ){
+ sqlite3_free(zWidePath);
+ sqlite3_free(zBuf);
+ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
+ return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
+ "winGetTempname2", 0);
+ }
+ zMulti = winUnicodeToUtf8(zWidePath);
+ if( zMulti ){
+ sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
+ sqlite3_free(zMulti);
+ sqlite3_free(zWidePath);
+ }else{
+ sqlite3_free(zWidePath);
+ sqlite3_free(zBuf);
+ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ }
+#ifdef SQLITE_WIN32_HAS_ANSI
+ else{
+ char *zUtf8;
+ char *zMbcsPath = sqlite3MallocZero( nMax );
+ if( !zMbcsPath ){
+ sqlite3_free(zBuf);
+ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ if( osGetTempPathA(nMax, zMbcsPath)==0 ){
+ sqlite3_free(zBuf);
+ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
+ return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
+ "winGetTempname3", 0);
+ }
+ zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
+ if( zUtf8 ){
+ sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
+ sqlite3_free(zUtf8);
+ }else{
+ sqlite3_free(zBuf);
+ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ }
+#endif /* SQLITE_WIN32_HAS_ANSI */
+#endif /* !SQLITE_OS_WINRT */
+
+ /*
+ ** Check to make sure the temporary directory ends with an appropriate
+ ** separator. If it does not and there is not enough space left to add
+ ** one, fail.
+ */
+ if( !winMakeEndInDirSep(nDir+1, zBuf) ){
+ sqlite3_free(zBuf);
+ OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
+ return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
+ }
+
+ /*
+ ** Check that the output buffer is large enough for the temporary file
+ ** name in the following format:
+ **
+ ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
+ **
+ ** If not, return SQLITE_ERROR. The number 17 is used here in order to
+ ** account for the space used by the 15 character random suffix and the
+ ** two trailing NUL characters. The final directory separator character
+ ** has already added if it was not already present.
+ */
+ nLen = sqlite3Strlen30(zBuf);
+ if( (nLen + nPre + 17) > nBuf ){
+ sqlite3_free(zBuf);
+ OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
+ return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
+ }
+
+ sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
+
+ j = sqlite3Strlen30(zBuf);
+ sqlite3_randomness(15, &zBuf[j]);
+ for(i=0; i<15; i++, j++){
+ zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
+ }
+ zBuf[j] = 0;
+ zBuf[j+1] = 0;
+ *pzBuf = zBuf;
+
+ OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
+ return SQLITE_OK;
+}
+
+/*
+** Return TRUE if the named file is really a directory. Return false if
+** it is something other than a directory, or if there is any kind of memory
+** allocation failure.
+*/
+static int winIsDir(const void *zConverted){
+ DWORD attr;
+ int rc = 0;
+ DWORD lastErrno;
+
+ if( osIsNT() ){
+ int cnt = 0;
+ WIN32_FILE_ATTRIBUTE_DATA sAttrData;
+ memset(&sAttrData, 0, sizeof(sAttrData));
+ while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
+ GetFileExInfoStandard,
+ &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
+ if( !rc ){
+ return 0; /* Invalid name? */
+ }
+ attr = sAttrData.dwFileAttributes;
+#if SQLITE_OS_WINCE==0
+ }else{
+ attr = osGetFileAttributesA((char*)zConverted);
+#endif
+ }
+ return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
+}
+
+/* forward reference */
+static int winAccess(
+ sqlite3_vfs *pVfs, /* Not used on win32 */
+ const char *zFilename, /* Name of file to check */
+ int flags, /* Type of test to make on this file */
+ int *pResOut /* OUT: Result */
+);
+
+/*
+** Open a file.
+*/
+static int winOpen(
+ sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
+ const char *zName, /* Name of the file (UTF-8) */
+ sqlite3_file *id, /* Write the SQLite file handle here */
+ int flags, /* Open mode flags */
+ int *pOutFlags /* Status return flags */
+){
+ HANDLE h;
+ DWORD lastErrno = 0;
+ DWORD dwDesiredAccess;
+ DWORD dwShareMode;
+ DWORD dwCreationDisposition;
+ DWORD dwFlagsAndAttributes = 0;
+#if SQLITE_OS_WINCE
+ int isTemp = 0;
+#endif
+ winVfsAppData *pAppData;
+ winFile *pFile = (winFile*)id;
+ void *zConverted; /* Filename in OS encoding */
+ const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
+ int cnt = 0;
+
+ /* If argument zPath is a NULL pointer, this function is required to open
+ ** a temporary file. Use this buffer to store the file name in.
+ */
+ char *zTmpname = 0; /* For temporary filename, if necessary. */
+
+ int rc = SQLITE_OK; /* Function Return Code */
+#if !defined(NDEBUG) || SQLITE_OS_WINCE
+ int eType = flags&0xFFFFFF00; /* Type of file to open */
+#endif
+
+ int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
+ int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
+ int isCreate = (flags & SQLITE_OPEN_CREATE);
+ int isReadonly = (flags & SQLITE_OPEN_READONLY);
+ int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
+
+#ifndef NDEBUG
+ int isOpenJournal = (isCreate && (
+ eType==SQLITE_OPEN_SUPER_JOURNAL
+ || eType==SQLITE_OPEN_MAIN_JOURNAL
+ || eType==SQLITE_OPEN_WAL
+ ));
+#endif
+
+ OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
+ zUtf8Name, id, flags, pOutFlags));
+
+ /* Check the following statements are true:
+ **
+ ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
+ ** (b) if CREATE is set, then READWRITE must also be set, and
+ ** (c) if EXCLUSIVE is set, then CREATE must also be set.
+ ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
+ */
+ assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
+ assert(isCreate==0 || isReadWrite);
+ assert(isExclusive==0 || isCreate);
+ assert(isDelete==0 || isCreate);
+
+ /* The main DB, main journal, WAL file and super-journal are never
+ ** automatically deleted. Nor are they ever temporary files. */
+ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
+ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
+ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL );
+ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
+
+ /* Assert that the upper layer has set one of the "file-type" flags. */
+ assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
+ || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
+ || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_SUPER_JOURNAL
+ || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
+ );
+
+ assert( pFile!=0 );
+ memset(pFile, 0, sizeof(winFile));
+ pFile->h = INVALID_HANDLE_VALUE;
+
+#if SQLITE_OS_WINRT
+ if( !zUtf8Name && !sqlite3_temp_directory ){
+ sqlite3_log(SQLITE_ERROR,
+ "sqlite3_temp_directory variable should be set for WinRT");
+ }
+#endif
+
+ /* If the second argument to this function is NULL, generate a
+ ** temporary file name to use
+ */
+ if( !zUtf8Name ){
+ assert( isDelete && !isOpenJournal );
+ rc = winGetTempname(pVfs, &zTmpname);
+ if( rc!=SQLITE_OK ){
+ OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
+ return rc;
+ }
+ zUtf8Name = zTmpname;
+ }
+
+ /* Database filenames are double-zero terminated if they are not
+ ** URIs with parameters. Hence, they can always be passed into
+ ** sqlite3_uri_parameter().
+ */
+ assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
+ zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
+
+ /* Convert the filename to the system encoding. */
+ zConverted = winConvertFromUtf8Filename(zUtf8Name);
+ if( zConverted==0 ){
+ sqlite3_free(zTmpname);
+ OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+
+ if( winIsDir(zConverted) ){
+ sqlite3_free(zConverted);
+ sqlite3_free(zTmpname);
+ OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
+ return SQLITE_CANTOPEN_ISDIR;
+ }
+
+ if( isReadWrite ){
+ dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
+ }else{
+ dwDesiredAccess = GENERIC_READ;
+ }
+
+ /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
+ ** created. SQLite doesn't use it to indicate "exclusive access"
+ ** as it is usually understood.
+ */
+ if( isExclusive ){
+ /* Creates a new file, only if it does not already exist. */
+ /* If the file exists, it fails. */
+ dwCreationDisposition = CREATE_NEW;
+ }else if( isCreate ){
+ /* Open existing file, or create if it doesn't exist */
+ dwCreationDisposition = OPEN_ALWAYS;
+ }else{
+ /* Opens a file, only if it exists. */
+ dwCreationDisposition = OPEN_EXISTING;
+ }
+
+ dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
+
+ if( isDelete ){
+#if SQLITE_OS_WINCE
+ dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
+ isTemp = 1;
+#else
+ dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
+ | FILE_ATTRIBUTE_HIDDEN
+ | FILE_FLAG_DELETE_ON_CLOSE;
+#endif
+ }else{
+ dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
+ }
+ /* Reports from the internet are that performance is always
+ ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
+#if SQLITE_OS_WINCE
+ dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
+#endif
+
+ if( osIsNT() ){
+#if SQLITE_OS_WINRT
+ CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
+ extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
+ extendedParameters.dwFileAttributes =
+ dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
+ extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
+ extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
+ extendedParameters.lpSecurityAttributes = NULL;
+ extendedParameters.hTemplateFile = NULL;
+ do{
+ h = osCreateFile2((LPCWSTR)zConverted,
+ dwDesiredAccess,
+ dwShareMode,
+ dwCreationDisposition,
+ &extendedParameters);
+ if( h!=INVALID_HANDLE_VALUE ) break;
+ if( isReadWrite ){
+ int rc2, isRO = 0;
+ sqlite3BeginBenignMalloc();
+ rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
+ sqlite3EndBenignMalloc();
+ if( rc2==SQLITE_OK && isRO ) break;
+ }
+ }while( winRetryIoerr(&cnt, &lastErrno) );
+#else
+ do{
+ h = osCreateFileW((LPCWSTR)zConverted,
+ dwDesiredAccess,
+ dwShareMode, NULL,
+ dwCreationDisposition,
+ dwFlagsAndAttributes,
+ NULL);
+ if( h!=INVALID_HANDLE_VALUE ) break;
+ if( isReadWrite ){
+ int rc2, isRO = 0;
+ sqlite3BeginBenignMalloc();
+ rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
+ sqlite3EndBenignMalloc();
+ if( rc2==SQLITE_OK && isRO ) break;
+ }
+ }while( winRetryIoerr(&cnt, &lastErrno) );
+#endif
+ }
+#ifdef SQLITE_WIN32_HAS_ANSI
+ else{
+ do{
+ h = osCreateFileA((LPCSTR)zConverted,
+ dwDesiredAccess,
+ dwShareMode, NULL,
+ dwCreationDisposition,
+ dwFlagsAndAttributes,
+ NULL);
+ if( h!=INVALID_HANDLE_VALUE ) break;
+ if( isReadWrite ){
+ int rc2, isRO = 0;
+ sqlite3BeginBenignMalloc();
+ rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
+ sqlite3EndBenignMalloc();
+ if( rc2==SQLITE_OK && isRO ) break;
+ }
+ }while( winRetryIoerr(&cnt, &lastErrno) );
+ }
+#endif
+ winLogIoerr(cnt, __LINE__);
+
+ OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
+ dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
+
+ if( h==INVALID_HANDLE_VALUE ){
+ sqlite3_free(zConverted);
+ sqlite3_free(zTmpname);
+ if( isReadWrite && !isExclusive ){
+ return winOpen(pVfs, zName, id,
+ ((flags|SQLITE_OPEN_READONLY) &
+ ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
+ pOutFlags);
+ }else{
+ pFile->lastErrno = lastErrno;
+ winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
+ return SQLITE_CANTOPEN_BKPT;
+ }
+ }
+
+ if( pOutFlags ){
+ if( isReadWrite ){
+ *pOutFlags = SQLITE_OPEN_READWRITE;
+ }else{
+ *pOutFlags = SQLITE_OPEN_READONLY;
+ }
+ }
+
+ OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
+ "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
+ *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
+
+ pAppData = (winVfsAppData*)pVfs->pAppData;
+
+#if SQLITE_OS_WINCE
+ {
+ if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
+ && ((pAppData==NULL) || !pAppData->bNoLock)
+ && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
+ ){
+ osCloseHandle(h);
+ sqlite3_free(zConverted);
+ sqlite3_free(zTmpname);
+ OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
+ return rc;
+ }
+ }
+ if( isTemp ){
+ pFile->zDeleteOnClose = zConverted;
+ }else
+#endif
+ {
+ sqlite3_free(zConverted);
+ }
+
+ sqlite3_free(zTmpname);
+ id->pMethods = pAppData ? pAppData->pMethod : &winIoMethod;
+ pFile->pVfs = pVfs;
+ pFile->h = h;
+ if( isReadonly ){
+ pFile->ctrlFlags |= WINFILE_RDONLY;
+ }
+ if( (flags & SQLITE_OPEN_MAIN_DB)
+ && sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE)
+ ){
+ pFile->ctrlFlags |= WINFILE_PSOW;
+ }
+ pFile->lastErrno = NO_ERROR;
+ pFile->zPath = zName;
+#if SQLITE_MAX_MMAP_SIZE>0
+ pFile->hMap = NULL;
+ pFile->pMapRegion = 0;
+ pFile->mmapSize = 0;
+ pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
+#endif
+
+ OpenCounter(+1);
+ return rc;
+}
+
+/*
+** Delete the named file.
+**
+** Note that Windows does not allow a file to be deleted if some other
+** process has it open. Sometimes a virus scanner or indexing program
+** will open a journal file shortly after it is created in order to do
+** whatever it does. While this other process is holding the
+** file open, we will be unable to delete it. To work around this
+** problem, we delay 100 milliseconds and try to delete again. Up
+** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
+** up and returning an error.
+*/
+static int winDelete(
+ sqlite3_vfs *pVfs, /* Not used on win32 */
+ const char *zFilename, /* Name of file to delete */
+ int syncDir /* Not used on win32 */
+){
+ int cnt = 0;
+ int rc;
+ DWORD attr;
+ DWORD lastErrno = 0;
+ void *zConverted;
+ UNUSED_PARAMETER(pVfs);
+ UNUSED_PARAMETER(syncDir);
+
+ SimulateIOError(return SQLITE_IOERR_DELETE);
+ OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
+
+ zConverted = winConvertFromUtf8Filename(zFilename);
+ if( zConverted==0 ){
+ OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ if( osIsNT() ){
+ do {
+#if SQLITE_OS_WINRT
+ WIN32_FILE_ATTRIBUTE_DATA sAttrData;
+ memset(&sAttrData, 0, sizeof(sAttrData));
+ if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
+ &sAttrData) ){
+ attr = sAttrData.dwFileAttributes;
+ }else{
+ lastErrno = osGetLastError();
+ if( lastErrno==ERROR_FILE_NOT_FOUND
+ || lastErrno==ERROR_PATH_NOT_FOUND ){
+ rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
+ }else{
+ rc = SQLITE_ERROR;
+ }
+ break;
+ }
+#else
+ attr = osGetFileAttributesW(zConverted);
+#endif
+ if ( attr==INVALID_FILE_ATTRIBUTES ){
+ lastErrno = osGetLastError();
+ if( lastErrno==ERROR_FILE_NOT_FOUND
+ || lastErrno==ERROR_PATH_NOT_FOUND ){
+ rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
+ }else{
+ rc = SQLITE_ERROR;
+ }
+ break;
+ }
+ if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
+ rc = SQLITE_ERROR; /* Files only. */
+ break;
+ }
+ if ( osDeleteFileW(zConverted) ){
+ rc = SQLITE_OK; /* Deleted OK. */
+ break;
+ }
+ if ( !winRetryIoerr(&cnt, &lastErrno) ){
+ rc = SQLITE_ERROR; /* No more retries. */
+ break;
+ }
+ } while(1);
+ }
+#ifdef SQLITE_WIN32_HAS_ANSI
+ else{
+ do {
+ attr = osGetFileAttributesA(zConverted);
+ if ( attr==INVALID_FILE_ATTRIBUTES ){
+ lastErrno = osGetLastError();
+ if( lastErrno==ERROR_FILE_NOT_FOUND
+ || lastErrno==ERROR_PATH_NOT_FOUND ){
+ rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
+ }else{
+ rc = SQLITE_ERROR;
+ }
+ break;
+ }
+ if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
+ rc = SQLITE_ERROR; /* Files only. */
+ break;
+ }
+ if ( osDeleteFileA(zConverted) ){
+ rc = SQLITE_OK; /* Deleted OK. */
+ break;
+ }
+ if ( !winRetryIoerr(&cnt, &lastErrno) ){
+ rc = SQLITE_ERROR; /* No more retries. */
+ break;
+ }
+ } while(1);
+ }
+#endif
+ if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
+ rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
+ }else{
+ winLogIoerr(cnt, __LINE__);
+ }
+ sqlite3_free(zConverted);
+ OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
+ return rc;
+}
+
+/*
+** Check the existence and status of a file.
+*/
+static int winAccess(
+ sqlite3_vfs *pVfs, /* Not used on win32 */
+ const char *zFilename, /* Name of file to check */
+ int flags, /* Type of test to make on this file */
+ int *pResOut /* OUT: Result */
+){
+ DWORD attr;
+ int rc = 0;
+ DWORD lastErrno = 0;
+ void *zConverted;
+ UNUSED_PARAMETER(pVfs);
+
+ SimulateIOError( return SQLITE_IOERR_ACCESS; );
+ OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
+ zFilename, flags, pResOut));
+
+ zConverted = winConvertFromUtf8Filename(zFilename);
+ if( zConverted==0 ){
+ OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ if( osIsNT() ){
+ int cnt = 0;
+ WIN32_FILE_ATTRIBUTE_DATA sAttrData;
+ memset(&sAttrData, 0, sizeof(sAttrData));
+ while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
+ GetFileExInfoStandard,
+ &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
+ if( rc ){
+ /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
+ ** as if it does not exist.
+ */
+ if( flags==SQLITE_ACCESS_EXISTS
+ && sAttrData.nFileSizeHigh==0
+ && sAttrData.nFileSizeLow==0 ){
+ attr = INVALID_FILE_ATTRIBUTES;
+ }else{
+ attr = sAttrData.dwFileAttributes;
+ }
+ }else{
+ winLogIoerr(cnt, __LINE__);
+ if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
+ sqlite3_free(zConverted);
+ return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
+ zFilename);
+ }else{
+ attr = INVALID_FILE_ATTRIBUTES;
+ }
+ }
+ }
+#ifdef SQLITE_WIN32_HAS_ANSI
+ else{
+ attr = osGetFileAttributesA((char*)zConverted);
+ }
+#endif
+ sqlite3_free(zConverted);
+ switch( flags ){
+ case SQLITE_ACCESS_READ:
+ case SQLITE_ACCESS_EXISTS:
+ rc = attr!=INVALID_FILE_ATTRIBUTES;
+ break;
+ case SQLITE_ACCESS_READWRITE:
+ rc = attr!=INVALID_FILE_ATTRIBUTES &&
+ (attr & FILE_ATTRIBUTE_READONLY)==0;
+ break;
+ default:
+ assert(!"Invalid flags argument");
+ }
+ *pResOut = rc;
+ OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
+ zFilename, pResOut, *pResOut));
+ return SQLITE_OK;
+}
+
+/*
+** Returns non-zero if the specified path name starts with the "long path"
+** prefix.
+*/
+static BOOL winIsLongPathPrefix(
+ const char *zPathname
+){
+ return ( zPathname[0]=='\\' && zPathname[1]=='\\'
+ && zPathname[2]=='?' && zPathname[3]=='\\' );
+}
+
+/*
+** Returns non-zero if the specified path name starts with a drive letter
+** followed by a colon character.
+*/
+static BOOL winIsDriveLetterAndColon(
+ const char *zPathname
+){
+ return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
+}
+
+/*
+** Returns non-zero if the specified path name should be used verbatim. If
+** non-zero is returned from this function, the calling function must simply
+** use the provided path name verbatim -OR- resolve it into a full path name
+** using the GetFullPathName Win32 API function (if available).
+*/
+static BOOL winIsVerbatimPathname(
+ const char *zPathname
+){
+ /*
+ ** If the path name starts with a forward slash or a backslash, it is either
+ ** a legal UNC name, a volume relative path, or an absolute path name in the
+ ** "Unix" format on Windows. There is no easy way to differentiate between
+ ** the final two cases; therefore, we return the safer return value of TRUE
+ ** so that callers of this function will simply use it verbatim.
+ */
+ if ( winIsDirSep(zPathname[0]) ){
+ return TRUE;
+ }
+
+ /*
+ ** If the path name starts with a letter and a colon it is either a volume
+ ** relative path or an absolute path. Callers of this function must not
+ ** attempt to treat it as a relative path name (i.e. they should simply use
+ ** it verbatim).
+ */
+ if ( winIsDriveLetterAndColon(zPathname) ){
+ return TRUE;
+ }
+
+ /*
+ ** If we get to this point, the path name should almost certainly be a purely
+ ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
+ */
+ return FALSE;
+}
+
+/*
+** Turn a relative pathname into a full pathname. Write the full
+** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
+** bytes in size.
+*/
+static int winFullPathname(
+ sqlite3_vfs *pVfs, /* Pointer to vfs object */
+ const char *zRelative, /* Possibly relative input path */
+ int nFull, /* Size of output buffer in bytes */
+ char *zFull /* Output buffer */
+){
+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
+ DWORD nByte;
+ void *zConverted;
+ char *zOut;
+#endif
+
+ /* If this path name begins with "/X:" or "\\?\", where "X" is any
+ ** alphabetic character, discard the initial "/" from the pathname.
+ */
+ if( zRelative[0]=='/' && (winIsDriveLetterAndColon(zRelative+1)
+ || winIsLongPathPrefix(zRelative+1)) ){
+ zRelative++;
+ }
+
+#if defined(__CYGWIN__)
+ SimulateIOError( return SQLITE_ERROR );
+ UNUSED_PARAMETER(nFull);
+ assert( nFull>=pVfs->mxPathname );
+ if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
+ /*
+ ** NOTE: We are dealing with a relative path name and the data
+ ** directory has been set. Therefore, use it as the basis
+ ** for converting the relative path name to an absolute
+ ** one by prepending the data directory and a slash.
+ */
+ char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
+ if( !zOut ){
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ if( cygwin_conv_path(
+ (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
+ CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
+ sqlite3_free(zOut);
+ return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
+ "winFullPathname1", zRelative);
+ }else{
+ char *zUtf8 = winConvertToUtf8Filename(zOut);
+ if( !zUtf8 ){
+ sqlite3_free(zOut);
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
+ sqlite3_data_directory, winGetDirSep(), zUtf8);
+ sqlite3_free(zUtf8);
+ sqlite3_free(zOut);
+ }
+ }else{
+ char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
+ if( !zOut ){
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ if( cygwin_conv_path(
+ (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
+ zRelative, zOut, pVfs->mxPathname+1)<0 ){
+ sqlite3_free(zOut);
+ return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
+ "winFullPathname2", zRelative);
+ }else{
+ char *zUtf8 = winConvertToUtf8Filename(zOut);
+ if( !zUtf8 ){
+ sqlite3_free(zOut);
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
+ sqlite3_free(zUtf8);
+ sqlite3_free(zOut);
+ }
+ }
+ return SQLITE_OK;
+#endif
+
+#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
+ SimulateIOError( return SQLITE_ERROR );
+ /* WinCE has no concept of a relative pathname, or so I am told. */
+ /* WinRT has no way to convert a relative path to an absolute one. */
+ if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
+ /*
+ ** NOTE: We are dealing with a relative path name and the data
+ ** directory has been set. Therefore, use it as the basis
+ ** for converting the relative path name to an absolute
+ ** one by prepending the data directory and a backslash.
+ */
+ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
+ sqlite3_data_directory, winGetDirSep(), zRelative);
+ }else{
+ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
+ }
+ return SQLITE_OK;
+#endif
+
+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
+ /* It's odd to simulate an io-error here, but really this is just
+ ** using the io-error infrastructure to test that SQLite handles this
+ ** function failing. This function could fail if, for example, the
+ ** current working directory has been unlinked.
+ */
+ SimulateIOError( return SQLITE_ERROR );
+ if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
+ /*
+ ** NOTE: We are dealing with a relative path name and the data
+ ** directory has been set. Therefore, use it as the basis
+ ** for converting the relative path name to an absolute
+ ** one by prepending the data directory and a backslash.
+ */
+ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
+ sqlite3_data_directory, winGetDirSep(), zRelative);
+ return SQLITE_OK;
+ }
+ zConverted = winConvertFromUtf8Filename(zRelative);
+ if( zConverted==0 ){
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ if( osIsNT() ){
+ LPWSTR zTemp;
+ nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
+ if( nByte==0 ){
+ sqlite3_free(zConverted);
+ return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
+ "winFullPathname1", zRelative);
+ }
+ nByte += 3;
+ zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
+ if( zTemp==0 ){
+ sqlite3_free(zConverted);
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
+ if( nByte==0 ){
+ sqlite3_free(zConverted);
+ sqlite3_free(zTemp);
+ return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
+ "winFullPathname2", zRelative);
+ }
+ sqlite3_free(zConverted);
+ zOut = winUnicodeToUtf8(zTemp);
+ sqlite3_free(zTemp);
+ }
+#ifdef SQLITE_WIN32_HAS_ANSI
+ else{
+ char *zTemp;
+ nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
+ if( nByte==0 ){
+ sqlite3_free(zConverted);
+ return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
+ "winFullPathname3", zRelative);
+ }
+ nByte += 3;
+ zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
+ if( zTemp==0 ){
+ sqlite3_free(zConverted);
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
+ if( nByte==0 ){
+ sqlite3_free(zConverted);
+ sqlite3_free(zTemp);
+ return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
+ "winFullPathname4", zRelative);
+ }
+ sqlite3_free(zConverted);
+ zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
+ sqlite3_free(zTemp);
+ }
+#endif
+ if( zOut ){
+ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
+ sqlite3_free(zOut);
+ return SQLITE_OK;
+ }else{
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+#endif
+}
+
+#ifndef SQLITE_OMIT_LOAD_EXTENSION
+/*
+** Interfaces for opening a shared library, finding entry points
+** within the shared library, and closing the shared library.
+*/
+static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
+ HANDLE h;
+#if defined(__CYGWIN__)
+ int nFull = pVfs->mxPathname+1;
+ char *zFull = sqlite3MallocZero( nFull );
+ void *zConverted = 0;
+ if( zFull==0 ){
+ OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
+ return 0;
+ }
+ if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
+ sqlite3_free(zFull);
+ OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
+ return 0;
+ }
+ zConverted = winConvertFromUtf8Filename(zFull);
+ sqlite3_free(zFull);
+#else
+ void *zConverted = winConvertFromUtf8Filename(zFilename);
+ UNUSED_PARAMETER(pVfs);
+#endif
+ if( zConverted==0 ){
+ OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
+ return 0;
+ }
+ if( osIsNT() ){
+#if SQLITE_OS_WINRT
+ h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
+#else
+ h = osLoadLibraryW((LPCWSTR)zConverted);
+#endif
+ }
+#ifdef SQLITE_WIN32_HAS_ANSI
+ else{
+ h = osLoadLibraryA((char*)zConverted);
+ }
+#endif
+ OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
+ sqlite3_free(zConverted);
+ return (void*)h;
+}
+static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
+ UNUSED_PARAMETER(pVfs);
+ winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
+}
+static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
+ FARPROC proc;
+ UNUSED_PARAMETER(pVfs);
+ proc = osGetProcAddressA((HANDLE)pH, zSym);
+ OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
+ (void*)pH, zSym, (void*)proc));
+ return (void(*)(void))proc;
+}
+static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
+ UNUSED_PARAMETER(pVfs);
+ osFreeLibrary((HANDLE)pHandle);
+ OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
+}
+#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
+ #define winDlOpen 0
+ #define winDlError 0
+ #define winDlSym 0
+ #define winDlClose 0
+#endif
+
+/* State information for the randomness gatherer. */
+typedef struct EntropyGatherer EntropyGatherer;
+struct EntropyGatherer {
+ unsigned char *a; /* Gather entropy into this buffer */
+ int na; /* Size of a[] in bytes */
+ int i; /* XOR next input into a[i] */
+ int nXor; /* Number of XOR operations done */
+};
+
+#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
+/* Mix sz bytes of entropy into p. */
+static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
+ int j, k;
+ for(j=0, k=p->i; j<sz; j++){
+ p->a[k++] ^= x[j];
+ if( k>=p->na ) k = 0;
+ }
+ p->i = k;
+ p->nXor += sz;
+}
+#endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
+
+/*
+** Write up to nBuf bytes of randomness into zBuf.
+*/
+static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
+#if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
+ UNUSED_PARAMETER(pVfs);
+ memset(zBuf, 0, nBuf);
+ return nBuf;
+#else
+ EntropyGatherer e;
+ UNUSED_PARAMETER(pVfs);
+ memset(zBuf, 0, nBuf);
+ e.a = (unsigned char*)zBuf;
+ e.na = nBuf;
+ e.nXor = 0;
+ e.i = 0;
+ {
+ SYSTEMTIME x;
+ osGetSystemTime(&x);
+ xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
+ }
+ {
+ DWORD pid = osGetCurrentProcessId();
+ xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
+ }
+#if SQLITE_OS_WINRT
+ {
+ ULONGLONG cnt = osGetTickCount64();
+ xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
+ }
+#else
+ {
+ DWORD cnt = osGetTickCount();
+ xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
+ }
+#endif /* SQLITE_OS_WINRT */
+ {
+ LARGE_INTEGER i;
+ osQueryPerformanceCounter(&i);
+ xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
+ }
+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
+ {
+ UUID id;
+ memset(&id, 0, sizeof(UUID));
+ osUuidCreate(&id);
+ xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
+ memset(&id, 0, sizeof(UUID));
+ osUuidCreateSequential(&id);
+ xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
+ }
+#endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
+ return e.nXor>nBuf ? nBuf : e.nXor;
+#endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
+}
+
+
+/*
+** Sleep for a little while. Return the amount of time slept.
+*/
+static int winSleep(sqlite3_vfs *pVfs, int microsec){
+ sqlite3_win32_sleep((microsec+999)/1000);
+ UNUSED_PARAMETER(pVfs);
+ return ((microsec+999)/1000)*1000;
+}
+
+/*
+** The following variable, if set to a non-zero value, is interpreted as
+** the number of seconds since 1970 and is used to set the result of
+** sqlite3OsCurrentTime() during testing.
+*/
+#ifdef SQLITE_TEST
+SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
+#endif
+
+/*
+** Find the current time (in Universal Coordinated Time). Write into *piNow
+** the current time and date as a Julian Day number times 86_400_000. In
+** other words, write into *piNow the number of milliseconds since the Julian
+** epoch of noon in Greenwich on November 24, 4714 B.C according to the
+** proleptic Gregorian calendar.
+**
+** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
+** cannot be found.
+*/
+static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
+ /* FILETIME structure is a 64-bit value representing the number of
+ 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
+ */
+ FILETIME ft;
+ static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
+#ifdef SQLITE_TEST
+ static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
+#endif
+ /* 2^32 - to avoid use of LL and warnings in gcc */
+ static const sqlite3_int64 max32BitValue =
+ (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
+ (sqlite3_int64)294967296;
+
+#if SQLITE_OS_WINCE
+ SYSTEMTIME time;
+ osGetSystemTime(&time);
+ /* if SystemTimeToFileTime() fails, it returns zero. */
+ if (!osSystemTimeToFileTime(&time,&ft)){
+ return SQLITE_ERROR;
+ }
+#else
+ osGetSystemTimeAsFileTime( &ft );
+#endif
+
+ *piNow = winFiletimeEpoch +
+ ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
+ (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
+
+#ifdef SQLITE_TEST
+ if( sqlite3_current_time ){
+ *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
+ }
+#endif
+ UNUSED_PARAMETER(pVfs);
+ return SQLITE_OK;
+}
+
+/*
+** Find the current time (in Universal Coordinated Time). Write the
+** current time and date as a Julian Day number into *prNow and
+** return 0. Return 1 if the time and date cannot be found.
+*/
+static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
+ int rc;
+ sqlite3_int64 i;
+ rc = winCurrentTimeInt64(pVfs, &i);
+ if( !rc ){
+ *prNow = i/86400000.0;
+ }
+ return rc;
+}
+
+/*
+** The idea is that this function works like a combination of
+** GetLastError() and FormatMessage() on Windows (or errno and
+** strerror_r() on Unix). After an error is returned by an OS
+** function, SQLite calls this function with zBuf pointing to
+** a buffer of nBuf bytes. The OS layer should populate the
+** buffer with a nul-terminated UTF-8 encoded error message
+** describing the last IO error to have occurred within the calling
+** thread.
+**
+** If the error message is too large for the supplied buffer,
+** it should be truncated. The return value of xGetLastError
+** is zero if the error message fits in the buffer, or non-zero
+** otherwise (if the message was truncated). If non-zero is returned,
+** then it is not necessary to include the nul-terminator character
+** in the output buffer.
+**
+** Not supplying an error message will have no adverse effect
+** on SQLite. It is fine to have an implementation that never
+** returns an error message:
+**
+** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
+** assert(zBuf[0]=='\0');
+** return 0;
+** }
+**
+** However if an error message is supplied, it will be incorporated
+** by sqlite into the error message available to the user using
+** sqlite3_errmsg(), possibly making IO errors easier to debug.
+*/
+static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
+ DWORD e = osGetLastError();
+ UNUSED_PARAMETER(pVfs);
+ if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
+ return e;
+}
+
+/*
+** Initialize and deinitialize the operating system interface.
+*/
+SQLITE_API int sqlite3_os_init(void){
+ static sqlite3_vfs winVfs = {
+ 3, /* iVersion */
+ sizeof(winFile), /* szOsFile */
+ SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
+ 0, /* pNext */
+ "win32", /* zName */
+ &winAppData, /* pAppData */
+ winOpen, /* xOpen */
+ winDelete, /* xDelete */
+ winAccess, /* xAccess */
+ winFullPathname, /* xFullPathname */
+ winDlOpen, /* xDlOpen */
+ winDlError, /* xDlError */
+ winDlSym, /* xDlSym */
+ winDlClose, /* xDlClose */
+ winRandomness, /* xRandomness */
+ winSleep, /* xSleep */
+ winCurrentTime, /* xCurrentTime */
+ winGetLastError, /* xGetLastError */
+ winCurrentTimeInt64, /* xCurrentTimeInt64 */
+ winSetSystemCall, /* xSetSystemCall */
+ winGetSystemCall, /* xGetSystemCall */
+ winNextSystemCall, /* xNextSystemCall */
+ };
+#if defined(SQLITE_WIN32_HAS_WIDE)
+ static sqlite3_vfs winLongPathVfs = {
+ 3, /* iVersion */
+ sizeof(winFile), /* szOsFile */
+ SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
+ 0, /* pNext */
+ "win32-longpath", /* zName */
+ &winAppData, /* pAppData */
+ winOpen, /* xOpen */
+ winDelete, /* xDelete */
+ winAccess, /* xAccess */
+ winFullPathname, /* xFullPathname */
+ winDlOpen, /* xDlOpen */
+ winDlError, /* xDlError */
+ winDlSym, /* xDlSym */
+ winDlClose, /* xDlClose */
+ winRandomness, /* xRandomness */
+ winSleep, /* xSleep */
+ winCurrentTime, /* xCurrentTime */
+ winGetLastError, /* xGetLastError */
+ winCurrentTimeInt64, /* xCurrentTimeInt64 */
+ winSetSystemCall, /* xSetSystemCall */
+ winGetSystemCall, /* xGetSystemCall */
+ winNextSystemCall, /* xNextSystemCall */
+ };
+#endif
+ static sqlite3_vfs winNolockVfs = {
+ 3, /* iVersion */
+ sizeof(winFile), /* szOsFile */
+ SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
+ 0, /* pNext */
+ "win32-none", /* zName */
+ &winNolockAppData, /* pAppData */
+ winOpen, /* xOpen */
+ winDelete, /* xDelete */
+ winAccess, /* xAccess */
+ winFullPathname, /* xFullPathname */
+ winDlOpen, /* xDlOpen */
+ winDlError, /* xDlError */
+ winDlSym, /* xDlSym */
+ winDlClose, /* xDlClose */
+ winRandomness, /* xRandomness */
+ winSleep, /* xSleep */
+ winCurrentTime, /* xCurrentTime */
+ winGetLastError, /* xGetLastError */
+ winCurrentTimeInt64, /* xCurrentTimeInt64 */
+ winSetSystemCall, /* xSetSystemCall */
+ winGetSystemCall, /* xGetSystemCall */
+ winNextSystemCall, /* xNextSystemCall */
+ };
+#if defined(SQLITE_WIN32_HAS_WIDE)
+ static sqlite3_vfs winLongPathNolockVfs = {
+ 3, /* iVersion */
+ sizeof(winFile), /* szOsFile */
+ SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
+ 0, /* pNext */
+ "win32-longpath-none", /* zName */
+ &winNolockAppData, /* pAppData */
+ winOpen, /* xOpen */
+ winDelete, /* xDelete */
+ winAccess, /* xAccess */
+ winFullPathname, /* xFullPathname */
+ winDlOpen, /* xDlOpen */
+ winDlError, /* xDlError */
+ winDlSym, /* xDlSym */
+ winDlClose, /* xDlClose */
+ winRandomness, /* xRandomness */
+ winSleep, /* xSleep */
+ winCurrentTime, /* xCurrentTime */
+ winGetLastError, /* xGetLastError */
+ winCurrentTimeInt64, /* xCurrentTimeInt64 */
+ winSetSystemCall, /* xSetSystemCall */
+ winGetSystemCall, /* xGetSystemCall */
+ winNextSystemCall, /* xNextSystemCall */
+ };
+#endif
+
+ /* Double-check that the aSyscall[] array has been constructed
+ ** correctly. See ticket [bb3a86e890c8e96ab] */
+ assert( ArraySize(aSyscall)==80 );
+
+ /* get memory map allocation granularity */
+ memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
+#if SQLITE_OS_WINRT
+ osGetNativeSystemInfo(&winSysInfo);
+#else
+ osGetSystemInfo(&winSysInfo);
+#endif
+ assert( winSysInfo.dwAllocationGranularity>0 );
+ assert( winSysInfo.dwPageSize>0 );
+
+ sqlite3_vfs_register(&winVfs, 1);
+
+#if defined(SQLITE_WIN32_HAS_WIDE)
+ sqlite3_vfs_register(&winLongPathVfs, 0);
+#endif
+
+ sqlite3_vfs_register(&winNolockVfs, 0);
+
+#if defined(SQLITE_WIN32_HAS_WIDE)
+ sqlite3_vfs_register(&winLongPathNolockVfs, 0);
+#endif
+
+#ifndef SQLITE_OMIT_WAL
+ winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
+#endif
+
+ return SQLITE_OK;
+}
+
+SQLITE_API int sqlite3_os_end(void){
+#if SQLITE_OS_WINRT
+ if( sleepObj!=NULL ){
+ osCloseHandle(sleepObj);
+ sleepObj = NULL;
+ }
+#endif
+
+#ifndef SQLITE_OMIT_WAL
+ winBigLock = 0;
+#endif
+
+ return SQLITE_OK;
+}
+
+#endif /* SQLITE_OS_WIN */
+
+/************** End of os_win.c **********************************************/
+/************** Begin file memdb.c *******************************************/
+/*
+** 2016-09-07
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file implements an in-memory VFS. A database is held as a contiguous
+** block of memory.
+**
+** This file also implements interface sqlite3_serialize() and
+** sqlite3_deserialize().
+*/
+/* #include "sqliteInt.h" */
+#ifdef SQLITE_ENABLE_DESERIALIZE
+
+/*
+** Forward declaration of objects used by this utility
+*/
+typedef struct sqlite3_vfs MemVfs;
+typedef struct MemFile MemFile;
+
+/* Access to a lower-level VFS that (might) implement dynamic loading,
+** access to randomness, etc.
+*/
+#define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
+
+/* An open file */
+struct MemFile {
+ sqlite3_file base; /* IO methods */
+ sqlite3_int64 sz; /* Size of the file */
+ sqlite3_int64 szAlloc; /* Space allocated to aData */
+ sqlite3_int64 szMax; /* Maximum allowed size of the file */
+ unsigned char *aData; /* content of the file */
+ int nMmap; /* Number of memory mapped pages */
+ unsigned mFlags; /* Flags */
+ int eLock; /* Most recent lock against this file */
+};
+
+/*
+** Methods for MemFile
+*/
+static int memdbClose(sqlite3_file*);
+static int memdbRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
+static int memdbWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
+static int memdbTruncate(sqlite3_file*, sqlite3_int64 size);
+static int memdbSync(sqlite3_file*, int flags);
+static int memdbFileSize(sqlite3_file*, sqlite3_int64 *pSize);
+static int memdbLock(sqlite3_file*, int);
+/* static int memdbCheckReservedLock(sqlite3_file*, int *pResOut);// not used */
+static int memdbFileControl(sqlite3_file*, int op, void *pArg);
+/* static int memdbSectorSize(sqlite3_file*); // not used */
+static int memdbDeviceCharacteristics(sqlite3_file*);
+static int memdbFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
+static int memdbUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
+
+/*
+** Methods for MemVfs
+*/
+static int memdbOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
+/* static int memdbDelete(sqlite3_vfs*, const char *zName, int syncDir); */
+static int memdbAccess(sqlite3_vfs*, const char *zName, int flags, int *);
+static int memdbFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
+static void *memdbDlOpen(sqlite3_vfs*, const char *zFilename);
+static void memdbDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
+static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
+static void memdbDlClose(sqlite3_vfs*, void*);
+static int memdbRandomness(sqlite3_vfs*, int nByte, char *zOut);
+static int memdbSleep(sqlite3_vfs*, int microseconds);
+/* static int memdbCurrentTime(sqlite3_vfs*, double*); */
+static int memdbGetLastError(sqlite3_vfs*, int, char *);
+static int memdbCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
+
+static sqlite3_vfs memdb_vfs = {
+ 2, /* iVersion */
+ 0, /* szOsFile (set when registered) */
+ 1024, /* mxPathname */
+ 0, /* pNext */
+ "memdb", /* zName */
+ 0, /* pAppData (set when registered) */
+ memdbOpen, /* xOpen */
+ 0, /* memdbDelete, */ /* xDelete */
+ memdbAccess, /* xAccess */
+ memdbFullPathname, /* xFullPathname */
+ memdbDlOpen, /* xDlOpen */
+ memdbDlError, /* xDlError */
+ memdbDlSym, /* xDlSym */
+ memdbDlClose, /* xDlClose */
+ memdbRandomness, /* xRandomness */
+ memdbSleep, /* xSleep */
+ 0, /* memdbCurrentTime, */ /* xCurrentTime */
+ memdbGetLastError, /* xGetLastError */
+ memdbCurrentTimeInt64 /* xCurrentTimeInt64 */
+};
+
+static const sqlite3_io_methods memdb_io_methods = {
+ 3, /* iVersion */
+ memdbClose, /* xClose */
+ memdbRead, /* xRead */
+ memdbWrite, /* xWrite */
+ memdbTruncate, /* xTruncate */
+ memdbSync, /* xSync */
+ memdbFileSize, /* xFileSize */
+ memdbLock, /* xLock */
+ memdbLock, /* xUnlock - same as xLock in this case */
+ 0, /* memdbCheckReservedLock, */ /* xCheckReservedLock */
+ memdbFileControl, /* xFileControl */
+ 0, /* memdbSectorSize,*/ /* xSectorSize */
+ memdbDeviceCharacteristics, /* xDeviceCharacteristics */
+ 0, /* xShmMap */
+ 0, /* xShmLock */
+ 0, /* xShmBarrier */
+ 0, /* xShmUnmap */
+ memdbFetch, /* xFetch */
+ memdbUnfetch /* xUnfetch */
+};
+
+
+
+/*
+** Close an memdb-file.
+**
+** The pData pointer is owned by the application, so there is nothing
+** to free.
+*/
+static int memdbClose(sqlite3_file *pFile){
+ MemFile *p = (MemFile *)pFile;
+ if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ) sqlite3_free(p->aData);
+ return SQLITE_OK;
+}
+
+/*
+** Read data from an memdb-file.
+*/
+static int memdbRead(
+ sqlite3_file *pFile,
+ void *zBuf,
+ int iAmt,
+ sqlite_int64 iOfst
+){
+ MemFile *p = (MemFile *)pFile;
+ if( iOfst+iAmt>p->sz ){
+ memset(zBuf, 0, iAmt);
+ if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst);
+ return SQLITE_IOERR_SHORT_READ;
+ }
+ memcpy(zBuf, p->aData+iOfst, iAmt);
+ return SQLITE_OK;
+}
+
+/*
+** Try to enlarge the memory allocation to hold at least sz bytes
+*/
+static int memdbEnlarge(MemFile *p, sqlite3_int64 newSz){
+ unsigned char *pNew;
+ if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || p->nMmap>0 ){
+ return SQLITE_FULL;
+ }
+ if( newSz>p->szMax ){
+ return SQLITE_FULL;
+ }
+ newSz *= 2;
+ if( newSz>p->szMax ) newSz = p->szMax;
+ pNew = sqlite3Realloc(p->aData, newSz);
+ if( pNew==0 ) return SQLITE_NOMEM;
+ p->aData = pNew;
+ p->szAlloc = newSz;
+ return SQLITE_OK;
+}
+
+/*
+** Write data to an memdb-file.
+*/
+static int memdbWrite(
+ sqlite3_file *pFile,
+ const void *z,
+ int iAmt,
+ sqlite_int64 iOfst
+){
+ MemFile *p = (MemFile *)pFile;
+ if( NEVER(p->mFlags & SQLITE_DESERIALIZE_READONLY) ) return SQLITE_READONLY;
+ if( iOfst+iAmt>p->sz ){
+ int rc;
+ if( iOfst+iAmt>p->szAlloc
+ && (rc = memdbEnlarge(p, iOfst+iAmt))!=SQLITE_OK
+ ){
+ return rc;
+ }
+ if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz);
+ p->sz = iOfst+iAmt;
+ }
+ memcpy(p->aData+iOfst, z, iAmt);
+ return SQLITE_OK;
+}
+
+/*
+** Truncate an memdb-file.
+**
+** In rollback mode (which is always the case for memdb, as it does not
+** support WAL mode) the truncate() method is only used to reduce
+** the size of a file, never to increase the size.
+*/
+static int memdbTruncate(sqlite3_file *pFile, sqlite_int64 size){
+ MemFile *p = (MemFile *)pFile;
+ if( NEVER(size>p->sz) ) return SQLITE_FULL;
+ p->sz = size;
+ return SQLITE_OK;
+}
+
+/*
+** Sync an memdb-file.
+*/
+static int memdbSync(sqlite3_file *pFile, int flags){
+ return SQLITE_OK;
+}
+
+/*
+** Return the current file-size of an memdb-file.
+*/
+static int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
+ MemFile *p = (MemFile *)pFile;
+ *pSize = p->sz;
+ return SQLITE_OK;
+}
+
+/*
+** Lock an memdb-file.
+*/
+static int memdbLock(sqlite3_file *pFile, int eLock){
+ MemFile *p = (MemFile *)pFile;
+ if( eLock>SQLITE_LOCK_SHARED
+ && (p->mFlags & SQLITE_DESERIALIZE_READONLY)!=0
+ ){
+ return SQLITE_READONLY;
+ }
+ p->eLock = eLock;
+ return SQLITE_OK;
+}
+
+#if 0 /* Never used because memdbAccess() always returns false */
+/*
+** Check if another file-handle holds a RESERVED lock on an memdb-file.
+*/
+static int memdbCheckReservedLock(sqlite3_file *pFile, int *pResOut){
+ *pResOut = 0;
+ return SQLITE_OK;
+}
+#endif
+
+/*
+** File control method. For custom operations on an memdb-file.
+*/
+static int memdbFileControl(sqlite3_file *pFile, int op, void *pArg){
+ MemFile *p = (MemFile *)pFile;
+ int rc = SQLITE_NOTFOUND;
+ if( op==SQLITE_FCNTL_VFSNAME ){
+ *(char**)pArg = sqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz);
+ rc = SQLITE_OK;
+ }
+ if( op==SQLITE_FCNTL_SIZE_LIMIT ){
+ sqlite3_int64 iLimit = *(sqlite3_int64*)pArg;
+ if( iLimit<p->sz ){
+ if( iLimit<0 ){
+ iLimit = p->szMax;
+ }else{
+ iLimit = p->sz;
+ }
+ }
+ p->szMax = iLimit;
+ *(sqlite3_int64*)pArg = iLimit;
+ rc = SQLITE_OK;
+ }
+ return rc;
+}
+
+#if 0 /* Not used because of SQLITE_IOCAP_POWERSAFE_OVERWRITE */
+/*
+** Return the sector-size in bytes for an memdb-file.
+*/
+static int memdbSectorSize(sqlite3_file *pFile){
+ return 1024;
+}
+#endif
+
+/*
+** Return the device characteristic flags supported by an memdb-file.
+*/
+static int memdbDeviceCharacteristics(sqlite3_file *pFile){
+ return SQLITE_IOCAP_ATOMIC |
+ SQLITE_IOCAP_POWERSAFE_OVERWRITE |
+ SQLITE_IOCAP_SAFE_APPEND |
+ SQLITE_IOCAP_SEQUENTIAL;
+}
+
+/* Fetch a page of a memory-mapped file */
+static int memdbFetch(
+ sqlite3_file *pFile,
+ sqlite3_int64 iOfst,
+ int iAmt,
+ void **pp
+){
+ MemFile *p = (MemFile *)pFile;
+ if( iOfst+iAmt>p->sz ){
+ *pp = 0;
+ }else{
+ p->nMmap++;
+ *pp = (void*)(p->aData + iOfst);
+ }
+ return SQLITE_OK;
+}
+
+/* Release a memory-mapped page */
+static int memdbUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
+ MemFile *p = (MemFile *)pFile;
+ p->nMmap--;
+ return SQLITE_OK;
+}
+
+/*
+** Open an mem file handle.
+*/
+static int memdbOpen(
+ sqlite3_vfs *pVfs,
+ const char *zName,
+ sqlite3_file *pFile,
+ int flags,
+ int *pOutFlags
+){
+ MemFile *p = (MemFile*)pFile;
+ if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
+ return ORIGVFS(pVfs)->xOpen(ORIGVFS(pVfs), zName, pFile, flags, pOutFlags);
+ }
+ memset(p, 0, sizeof(*p));
+ p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
+ assert( pOutFlags!=0 ); /* True because flags==SQLITE_OPEN_MAIN_DB */
+ *pOutFlags = flags | SQLITE_OPEN_MEMORY;
+ pFile->pMethods = &memdb_io_methods;
+ p->szMax = sqlite3GlobalConfig.mxMemdbSize;
+ return SQLITE_OK;
+}
+
+#if 0 /* Only used to delete rollback journals, super-journals, and WAL
+ ** files, none of which exist in memdb. So this routine is never used */
+/*
+** Delete the file located at zPath. If the dirSync argument is true,
+** ensure the file-system modifications are synced to disk before
+** returning.
+*/
+static int memdbDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
+ return SQLITE_IOERR_DELETE;
+}
+#endif
+
+/*
+** Test for access permissions. Return true if the requested permission
+** is available, or false otherwise.
+**
+** With memdb, no files ever exist on disk. So always return false.
+*/
+static int memdbAccess(
+ sqlite3_vfs *pVfs,
+ const char *zPath,
+ int flags,
+ int *pResOut
+){
+ *pResOut = 0;
+ return SQLITE_OK;
+}
+
+/*
+** Populate buffer zOut with the full canonical pathname corresponding
+** to the pathname in zPath. zOut is guaranteed to point to a buffer
+** of at least (INST_MAX_PATHNAME+1) bytes.
+*/
+static int memdbFullPathname(
+ sqlite3_vfs *pVfs,
+ const char *zPath,
+ int nOut,
+ char *zOut
+){
+ sqlite3_snprintf(nOut, zOut, "%s", zPath);
+ return SQLITE_OK;
+}
+
+/*
+** Open the dynamic library located at zPath and return a handle.
+*/
+static void *memdbDlOpen(sqlite3_vfs *pVfs, const char *zPath){
+ return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
+}
+
+/*
+** Populate the buffer zErrMsg (size nByte bytes) with a human readable
+** utf-8 string describing the most recent error encountered associated
+** with dynamic libraries.
+*/
+static void memdbDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
+ ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
+}
+
+/*
+** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
+*/
+static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
+ return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
+}
+
+/*
+** Close the dynamic library handle pHandle.
+*/
+static void memdbDlClose(sqlite3_vfs *pVfs, void *pHandle){
+ ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
+}
+
+/*
+** Populate the buffer pointed to by zBufOut with nByte bytes of
+** random data.
+*/
+static int memdbRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
+ return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
+}
+
+/*
+** Sleep for nMicro microseconds. Return the number of microseconds
+** actually slept.
+*/
+static int memdbSleep(sqlite3_vfs *pVfs, int nMicro){
+ return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
+}
+
+#if 0 /* Never used. Modern cores only call xCurrentTimeInt64() */
+/*
+** Return the current time as a Julian Day number in *pTimeOut.
+*/
+static int memdbCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
+ return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
+}
+#endif
+
+static int memdbGetLastError(sqlite3_vfs *pVfs, int a, char *b){
+ return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
+}
+static int memdbCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
+ return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
+}
+
+/*
+** Translate a database connection pointer and schema name into a
+** MemFile pointer.
+*/
+static MemFile *memdbFromDbSchema(sqlite3 *db, const char *zSchema){
+ MemFile *p = 0;
+ int rc = sqlite3_file_control(db, zSchema, SQLITE_FCNTL_FILE_POINTER, &p);
+ if( rc ) return 0;
+ if( p->base.pMethods!=&memdb_io_methods ) return 0;
+ return p;
+}
+
+/*
+** Return the serialization of a database
+*/
+SQLITE_API unsigned char *sqlite3_serialize(
+ sqlite3 *db, /* The database connection */
+ const char *zSchema, /* Which database within the connection */
+ sqlite3_int64 *piSize, /* Write size here, if not NULL */
+ unsigned int mFlags /* Maybe SQLITE_SERIALIZE_NOCOPY */
+){
+ MemFile *p;
+ int iDb;
+ Btree *pBt;
+ sqlite3_int64 sz;
+ int szPage = 0;
+ sqlite3_stmt *pStmt = 0;
+ unsigned char *pOut;
+ char *zSql;
+ int rc;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+
+ if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
+ p = memdbFromDbSchema(db, zSchema);
+ iDb = sqlite3FindDbName(db, zSchema);
+ if( piSize ) *piSize = -1;
+ if( iDb<0 ) return 0;
+ if( p ){
+ if( piSize ) *piSize = p->sz;
+ if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
+ pOut = p->aData;
+ }else{
+ pOut = sqlite3_malloc64( p->sz );
+ if( pOut ) memcpy(pOut, p->aData, p->sz);
+ }
+ return pOut;
+ }
+ pBt = db->aDb[iDb].pBt;
+ if( pBt==0 ) return 0;
+ szPage = sqlite3BtreeGetPageSize(pBt);
+ zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema);
+ rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
+ sqlite3_free(zSql);
+ if( rc ) return 0;
+ rc = sqlite3_step(pStmt);
+ if( rc!=SQLITE_ROW ){
+ pOut = 0;
+ }else{
+ sz = sqlite3_column_int64(pStmt, 0)*szPage;
+ if( piSize ) *piSize = sz;
+ if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
+ pOut = 0;
+ }else{
+ pOut = sqlite3_malloc64( sz );
+ if( pOut ){
+ int nPage = sqlite3_column_int(pStmt, 0);
+ Pager *pPager = sqlite3BtreePager(pBt);
+ int pgno;
+ for(pgno=1; pgno<=nPage; pgno++){
+ DbPage *pPage = 0;
+ unsigned char *pTo = pOut + szPage*(sqlite3_int64)(pgno-1);
+ rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pPage, 0);
+ if( rc==SQLITE_OK ){
+ memcpy(pTo, sqlite3PagerGetData(pPage), szPage);
+ }else{
+ memset(pTo, 0, szPage);
+ }
+ sqlite3PagerUnref(pPage);
+ }
+ }
+ }
+ }
+ sqlite3_finalize(pStmt);
+ return pOut;
+}
+
+/* Convert zSchema to a MemDB and initialize its content.
+*/
+SQLITE_API int sqlite3_deserialize(
+ sqlite3 *db, /* The database connection */
+ const char *zSchema, /* Which DB to reopen with the deserialization */
+ unsigned char *pData, /* The serialized database content */
+ sqlite3_int64 szDb, /* Number bytes in the deserialization */
+ sqlite3_int64 szBuf, /* Total size of buffer pData[] */
+ unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
+){
+ MemFile *p;
+ char *zSql;
+ sqlite3_stmt *pStmt = 0;
+ int rc;
+ int iDb;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ return SQLITE_MISUSE_BKPT;
+ }
+ if( szDb<0 ) return SQLITE_MISUSE_BKPT;
+ if( szBuf<0 ) return SQLITE_MISUSE_BKPT;
+#endif
+
+ sqlite3_mutex_enter(db->mutex);
+ if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
+ iDb = sqlite3FindDbName(db, zSchema);
+ if( iDb<0 ){
+ rc = SQLITE_ERROR;
+ goto end_deserialize;
+ }
+ zSql = sqlite3_mprintf("ATTACH x AS %Q", zSchema);
+ rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
+ sqlite3_free(zSql);
+ if( rc ) goto end_deserialize;
+ db->init.iDb = (u8)iDb;
+ db->init.reopenMemdb = 1;
+ rc = sqlite3_step(pStmt);
+ db->init.reopenMemdb = 0;
+ if( rc!=SQLITE_DONE ){
+ rc = SQLITE_ERROR;
+ goto end_deserialize;
+ }
+ p = memdbFromDbSchema(db, zSchema);
+ if( p==0 ){
+ rc = SQLITE_ERROR;
+ }else{
+ p->aData = pData;
+ p->sz = szDb;
+ p->szAlloc = szBuf;
+ p->szMax = szBuf;
+ if( p->szMax<sqlite3GlobalConfig.mxMemdbSize ){
+ p->szMax = sqlite3GlobalConfig.mxMemdbSize;
+ }
+ p->mFlags = mFlags;
+ rc = SQLITE_OK;
+ }
+
+end_deserialize:
+ sqlite3_finalize(pStmt);
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+/*
+** This routine is called when the extension is loaded.
+** Register the new VFS.
+*/
+SQLITE_PRIVATE int sqlite3MemdbInit(void){
+ sqlite3_vfs *pLower = sqlite3_vfs_find(0);
+ int sz = pLower->szOsFile;
+ memdb_vfs.pAppData = pLower;
+ /* The following conditional can only be true when compiled for
+ ** Windows x86 and SQLITE_MAX_MMAP_SIZE=0. We always leave
+ ** it in, to be safe, but it is marked as NO_TEST since there
+ ** is no way to reach it under most builds. */
+ if( sz<sizeof(MemFile) ) sz = sizeof(MemFile); /*NO_TEST*/
+ memdb_vfs.szOsFile = sz;
+ return sqlite3_vfs_register(&memdb_vfs, 0);
+}
+#endif /* SQLITE_ENABLE_DESERIALIZE */
+
+/************** End of memdb.c ***********************************************/
+/************** Begin file bitvec.c ******************************************/
+/*
+** 2008 February 16
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file implements an object that represents a fixed-length
+** bitmap. Bits are numbered starting with 1.
+**
+** A bitmap is used to record which pages of a database file have been
+** journalled during a transaction, or which pages have the "dont-write"
+** property. Usually only a few pages are meet either condition.
+** So the bitmap is usually sparse and has low cardinality.
+** But sometimes (for example when during a DROP of a large table) most
+** or all of the pages in a database can get journalled. In those cases,
+** the bitmap becomes dense with high cardinality. The algorithm needs
+** to handle both cases well.
+**
+** The size of the bitmap is fixed when the object is created.
+**
+** All bits are clear when the bitmap is created. Individual bits
+** may be set or cleared one at a time.
+**
+** Test operations are about 100 times more common that set operations.
+** Clear operations are exceedingly rare. There are usually between
+** 5 and 500 set operations per Bitvec object, though the number of sets can
+** sometimes grow into tens of thousands or larger. The size of the
+** Bitvec object is the number of pages in the database file at the
+** start of a transaction, and is thus usually less than a few thousand,
+** but can be as large as 2 billion for a really big database.
+*/
+/* #include "sqliteInt.h" */
+
+/* Size of the Bitvec structure in bytes. */
+#define BITVEC_SZ 512
+
+/* Round the union size down to the nearest pointer boundary, since that's how
+** it will be aligned within the Bitvec struct. */
+#define BITVEC_USIZE \
+ (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
+
+/* Type of the array "element" for the bitmap representation.
+** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
+** Setting this to the "natural word" size of your CPU may improve
+** performance. */
+#define BITVEC_TELEM u8
+/* Size, in bits, of the bitmap element. */
+#define BITVEC_SZELEM 8
+/* Number of elements in a bitmap array. */
+#define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
+/* Number of bits in the bitmap array. */
+#define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
+
+/* Number of u32 values in hash table. */
+#define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
+/* Maximum number of entries in hash table before
+** sub-dividing and re-hashing. */
+#define BITVEC_MXHASH (BITVEC_NINT/2)
+/* Hashing function for the aHash representation.
+** Empirical testing showed that the *37 multiplier
+** (an arbitrary prime)in the hash function provided
+** no fewer collisions than the no-op *1. */
+#define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
+
+#define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
+
+
+/*
+** A bitmap is an instance of the following structure.
+**
+** This bitmap records the existence of zero or more bits
+** with values between 1 and iSize, inclusive.
+**
+** There are three possible representations of the bitmap.
+** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
+** bitmap. The least significant bit is bit 1.
+**
+** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
+** a hash table that will hold up to BITVEC_MXHASH distinct values.
+**
+** Otherwise, the value i is redirected into one of BITVEC_NPTR
+** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
+** handles up to iDivisor separate values of i. apSub[0] holds
+** values between 1 and iDivisor. apSub[1] holds values between
+** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
+** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
+** to hold deal with values between 1 and iDivisor.
+*/
+struct Bitvec {
+ u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
+ u32 nSet; /* Number of bits that are set - only valid for aHash
+ ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
+ ** this would be 125. */
+ u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
+ /* Should >=0 for apSub element. */
+ /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
+ /* For a BITVEC_SZ of 512, this would be 34,359,739. */
+ union {
+ BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
+ u32 aHash[BITVEC_NINT]; /* Hash table representation */
+ Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
+ } u;
+};
+
+/*
+** Create a new bitmap object able to handle bits between 0 and iSize,
+** inclusive. Return a pointer to the new object. Return NULL if
+** malloc fails.
+*/
+SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
+ Bitvec *p;
+ assert( sizeof(*p)==BITVEC_SZ );
+ p = sqlite3MallocZero( sizeof(*p) );
+ if( p ){
+ p->iSize = iSize;
+ }
+ return p;
+}
+
+/*
+** Check to see if the i-th bit is set. Return true or false.
+** If p is NULL (if the bitmap has not been created) or if
+** i is out of range, then return false.
+*/
+SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
+ assert( p!=0 );
+ i--;
+ if( i>=p->iSize ) return 0;
+ while( p->iDivisor ){
+ u32 bin = i/p->iDivisor;
+ i = i%p->iDivisor;
+ p = p->u.apSub[bin];
+ if (!p) {
+ return 0;
+ }
+ }
+ if( p->iSize<=BITVEC_NBIT ){
+ return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
+ } else{
+ u32 h = BITVEC_HASH(i++);
+ while( p->u.aHash[h] ){
+ if( p->u.aHash[h]==i ) return 1;
+ h = (h+1) % BITVEC_NINT;
+ }
+ return 0;
+ }
+}
+SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
+ return p!=0 && sqlite3BitvecTestNotNull(p,i);
+}
+
+/*
+** Set the i-th bit. Return 0 on success and an error code if
+** anything goes wrong.
+**
+** This routine might cause sub-bitmaps to be allocated. Failing
+** to get the memory needed to hold the sub-bitmap is the only
+** that can go wrong with an insert, assuming p and i are valid.
+**
+** The calling function must ensure that p is a valid Bitvec object
+** and that the value for "i" is within range of the Bitvec object.
+** Otherwise the behavior is undefined.
+*/
+SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
+ u32 h;
+ if( p==0 ) return SQLITE_OK;
+ assert( i>0 );
+ assert( i<=p->iSize );
+ i--;
+ while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
+ u32 bin = i/p->iDivisor;
+ i = i%p->iDivisor;
+ if( p->u.apSub[bin]==0 ){
+ p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
+ if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
+ }
+ p = p->u.apSub[bin];
+ }
+ if( p->iSize<=BITVEC_NBIT ){
+ p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
+ return SQLITE_OK;
+ }
+ h = BITVEC_HASH(i++);
+ /* if there wasn't a hash collision, and this doesn't */
+ /* completely fill the hash, then just add it without */
+ /* worring about sub-dividing and re-hashing. */
+ if( !p->u.aHash[h] ){
+ if (p->nSet<(BITVEC_NINT-1)) {
+ goto bitvec_set_end;
+ } else {
+ goto bitvec_set_rehash;
+ }
+ }
+ /* there was a collision, check to see if it's already */
+ /* in hash, if not, try to find a spot for it */
+ do {
+ if( p->u.aHash[h]==i ) return SQLITE_OK;
+ h++;
+ if( h>=BITVEC_NINT ) h = 0;
+ } while( p->u.aHash[h] );
+ /* we didn't find it in the hash. h points to the first */
+ /* available free spot. check to see if this is going to */
+ /* make our hash too "full". */
+bitvec_set_rehash:
+ if( p->nSet>=BITVEC_MXHASH ){
+ unsigned int j;
+ int rc;
+ u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
+ if( aiValues==0 ){
+ return SQLITE_NOMEM_BKPT;
+ }else{
+ memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
+ memset(p->u.apSub, 0, sizeof(p->u.apSub));
+ p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
+ rc = sqlite3BitvecSet(p, i);
+ for(j=0; j<BITVEC_NINT; j++){
+ if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
+ }
+ sqlite3StackFree(0, aiValues);
+ return rc;
+ }
+ }
+bitvec_set_end:
+ p->nSet++;
+ p->u.aHash[h] = i;
+ return SQLITE_OK;
+}
+
+/*
+** Clear the i-th bit.
+**
+** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
+** that BitvecClear can use to rebuilt its hash table.
+*/
+SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
+ if( p==0 ) return;
+ assert( i>0 );
+ i--;
+ while( p->iDivisor ){
+ u32 bin = i/p->iDivisor;
+ i = i%p->iDivisor;
+ p = p->u.apSub[bin];
+ if (!p) {
+ return;
+ }
+ }
+ if( p->iSize<=BITVEC_NBIT ){
+ p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
+ }else{
+ unsigned int j;
+ u32 *aiValues = pBuf;
+ memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
+ memset(p->u.aHash, 0, sizeof(p->u.aHash));
+ p->nSet = 0;
+ for(j=0; j<BITVEC_NINT; j++){
+ if( aiValues[j] && aiValues[j]!=(i+1) ){
+ u32 h = BITVEC_HASH(aiValues[j]-1);
+ p->nSet++;
+ while( p->u.aHash[h] ){
+ h++;
+ if( h>=BITVEC_NINT ) h = 0;
+ }
+ p->u.aHash[h] = aiValues[j];
+ }
+ }
+ }
+}
+
+/*
+** Destroy a bitmap object. Reclaim all memory used.
+*/
+SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
+ if( p==0 ) return;
+ if( p->iDivisor ){
+ unsigned int i;
+ for(i=0; i<BITVEC_NPTR; i++){
+ sqlite3BitvecDestroy(p->u.apSub[i]);
+ }
+ }
+ sqlite3_free(p);
+}
+
+/*
+** Return the value of the iSize parameter specified when Bitvec *p
+** was created.
+*/
+SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
+ return p->iSize;
+}
+
+#ifndef SQLITE_UNTESTABLE
+/*
+** Let V[] be an array of unsigned characters sufficient to hold
+** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
+** Then the following macros can be used to set, clear, or test
+** individual bits within V.
+*/
+#define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
+#define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
+#define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
+
+/*
+** This routine runs an extensive test of the Bitvec code.
+**
+** The input is an array of integers that acts as a program
+** to test the Bitvec. The integers are opcodes followed
+** by 0, 1, or 3 operands, depending on the opcode. Another
+** opcode follows immediately after the last operand.
+**
+** There are 6 opcodes numbered from 0 through 5. 0 is the
+** "halt" opcode and causes the test to end.
+**
+** 0 Halt and return the number of errors
+** 1 N S X Set N bits beginning with S and incrementing by X
+** 2 N S X Clear N bits beginning with S and incrementing by X
+** 3 N Set N randomly chosen bits
+** 4 N Clear N randomly chosen bits
+** 5 N S X Set N bits from S increment X in array only, not in bitvec
+**
+** The opcodes 1 through 4 perform set and clear operations are performed
+** on both a Bitvec object and on a linear array of bits obtained from malloc.
+** Opcode 5 works on the linear array only, not on the Bitvec.
+** Opcode 5 is used to deliberately induce a fault in order to
+** confirm that error detection works.
+**
+** At the conclusion of the test the linear array is compared
+** against the Bitvec object. If there are any differences,
+** an error is returned. If they are the same, zero is returned.
+**
+** If a memory allocation error occurs, return -1.
+*/
+SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
+ Bitvec *pBitvec = 0;
+ unsigned char *pV = 0;
+ int rc = -1;
+ int i, nx, pc, op;
+ void *pTmpSpace;
+
+ /* Allocate the Bitvec to be tested and a linear array of
+ ** bits to act as the reference */
+ pBitvec = sqlite3BitvecCreate( sz );
+ pV = sqlite3MallocZero( (sz+7)/8 + 1 );
+ pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
+ if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
+
+ /* NULL pBitvec tests */
+ sqlite3BitvecSet(0, 1);
+ sqlite3BitvecClear(0, 1, pTmpSpace);
+
+ /* Run the program */
+ pc = 0;
+ while( (op = aOp[pc])!=0 ){
+ switch( op ){
+ case 1:
+ case 2:
+ case 5: {
+ nx = 4;
+ i = aOp[pc+2] - 1;
+ aOp[pc+2] += aOp[pc+3];
+ break;
+ }
+ case 3:
+ case 4:
+ default: {
+ nx = 2;
+ sqlite3_randomness(sizeof(i), &i);
+ break;
+ }
+ }
+ if( (--aOp[pc+1]) > 0 ) nx = 0;
+ pc += nx;
+ i = (i & 0x7fffffff)%sz;
+ if( (op & 1)!=0 ){
+ SETBIT(pV, (i+1));
+ if( op!=5 ){
+ if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
+ }
+ }else{
+ CLEARBIT(pV, (i+1));
+ sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
+ }
+ }
+
+ /* Test to make sure the linear array exactly matches the
+ ** Bitvec object. Start with the assumption that they do
+ ** match (rc==0). Change rc to non-zero if a discrepancy
+ ** is found.
+ */
+ rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
+ + sqlite3BitvecTest(pBitvec, 0)
+ + (sqlite3BitvecSize(pBitvec) - sz);
+ for(i=1; i<=sz; i++){
+ if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
+ rc = i;
+ break;
+ }
+ }
+
+ /* Free allocated structure */
+bitvec_end:
+ sqlite3_free(pTmpSpace);
+ sqlite3_free(pV);
+ sqlite3BitvecDestroy(pBitvec);
+ return rc;
+}
+#endif /* SQLITE_UNTESTABLE */
+
+/************** End of bitvec.c **********************************************/
+/************** Begin file pcache.c ******************************************/
+/*
+** 2008 August 05
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file implements that page cache.
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** A complete page cache is an instance of this structure. Every
+** entry in the cache holds a single page of the database file. The
+** btree layer only operates on the cached copy of the database pages.
+**
+** A page cache entry is "clean" if it exactly matches what is currently
+** on disk. A page is "dirty" if it has been modified and needs to be
+** persisted to disk.
+**
+** pDirty, pDirtyTail, pSynced:
+** All dirty pages are linked into the doubly linked list using
+** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
+** such that p was added to the list more recently than p->pDirtyNext.
+** PCache.pDirty points to the first (newest) element in the list and
+** pDirtyTail to the last (oldest).
+**
+** The PCache.pSynced variable is used to optimize searching for a dirty
+** page to eject from the cache mid-transaction. It is better to eject
+** a page that does not require a journal sync than one that does.
+** Therefore, pSynced is maintained so that it *almost* always points
+** to either the oldest page in the pDirty/pDirtyTail list that has a
+** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
+** (so that the right page to eject can be found by following pDirtyPrev
+** pointers).
+*/
+struct PCache {
+ PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
+ PgHdr *pSynced; /* Last synced page in dirty page list */
+ int nRefSum; /* Sum of ref counts over all pages */
+ int szCache; /* Configured cache size */
+ int szSpill; /* Size before spilling occurs */
+ int szPage; /* Size of every page in this cache */
+ int szExtra; /* Size of extra space for each page */
+ u8 bPurgeable; /* True if pages are on backing store */
+ u8 eCreate; /* eCreate value for for xFetch() */
+ int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
+ void *pStress; /* Argument to xStress */
+ sqlite3_pcache *pCache; /* Pluggable cache module */
+};
+
+/********************************** Test and Debug Logic **********************/
+/*
+** Debug tracing macros. Enable by by changing the "0" to "1" and
+** recompiling.
+**
+** When sqlite3PcacheTrace is 1, single line trace messages are issued.
+** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
+** is displayed for many operations, resulting in a lot of output.
+*/
+#if defined(SQLITE_DEBUG) && 0
+ int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
+ int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
+# define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
+ void pcacheDump(PCache *pCache){
+ int N;
+ int i, j;
+ sqlite3_pcache_page *pLower;
+ PgHdr *pPg;
+ unsigned char *a;
+
+ if( sqlite3PcacheTrace<2 ) return;
+ if( pCache->pCache==0 ) return;
+ N = sqlite3PcachePagecount(pCache);
+ if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
+ for(i=1; i<=N; i++){
+ pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
+ if( pLower==0 ) continue;
+ pPg = (PgHdr*)pLower->pExtra;
+ printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
+ a = (unsigned char *)pLower->pBuf;
+ for(j=0; j<12; j++) printf("%02x", a[j]);
+ printf("\n");
+ if( pPg->pPage==0 ){
+ sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
+ }
+ }
+ }
+ #else
+# define pcacheTrace(X)
+# define pcacheDump(X)
+#endif
+
+/*
+** Check invariants on a PgHdr entry. Return true if everything is OK.
+** Return false if any invariant is violated.
+**
+** This routine is for use inside of assert() statements only. For
+** example:
+**
+** assert( sqlite3PcachePageSanity(pPg) );
+*/
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
+ PCache *pCache;
+ assert( pPg!=0 );
+ assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */
+ pCache = pPg->pCache;
+ assert( pCache!=0 ); /* Every page has an associated PCache */
+ if( pPg->flags & PGHDR_CLEAN ){
+ assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
+ assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
+ assert( pCache->pDirtyTail!=pPg );
+ }
+ /* WRITEABLE pages must also be DIRTY */
+ if( pPg->flags & PGHDR_WRITEABLE ){
+ assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
+ }
+ /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
+ ** for example, when using the sqlite3PagerDontWrite() optimization:
+ ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
+ ** (2) Page X moved to freelist, WRITEABLE is cleared
+ ** (3) Page X reused, WRITEABLE is set again
+ ** If NEED_SYNC had been cleared in step 2, then it would not be reset
+ ** in step 3, and page might be written into the database without first
+ ** syncing the rollback journal, which might cause corruption on a power
+ ** loss.
+ **
+ ** Another example is when the database page size is smaller than the
+ ** disk sector size. When any page of a sector is journalled, all pages
+ ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
+ ** in case they are later modified, since all pages in the same sector
+ ** must be journalled and synced before any of those pages can be safely
+ ** written.
+ */
+ return 1;
+}
+#endif /* SQLITE_DEBUG */
+
+
+/********************************** Linked List Management ********************/
+
+/* Allowed values for second argument to pcacheManageDirtyList() */
+#define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
+#define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
+#define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
+
+/*
+** Manage pPage's participation on the dirty list. Bits of the addRemove
+** argument determines what operation to do. The 0x01 bit means first
+** remove pPage from the dirty list. The 0x02 means add pPage back to
+** the dirty list. Doing both moves pPage to the front of the dirty list.
+*/
+static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
+ PCache *p = pPage->pCache;
+
+ pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
+ addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
+ pPage->pgno));
+ if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
+ assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
+ assert( pPage->pDirtyPrev || pPage==p->pDirty );
+
+ /* Update the PCache1.pSynced variable if necessary. */
+ if( p->pSynced==pPage ){
+ p->pSynced = pPage->pDirtyPrev;
+ }
+
+ if( pPage->pDirtyNext ){
+ pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
+ }else{
+ assert( pPage==p->pDirtyTail );
+ p->pDirtyTail = pPage->pDirtyPrev;
+ }
+ if( pPage->pDirtyPrev ){
+ pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
+ }else{
+ /* If there are now no dirty pages in the cache, set eCreate to 2.
+ ** This is an optimization that allows sqlite3PcacheFetch() to skip
+ ** searching for a dirty page to eject from the cache when it might
+ ** otherwise have to. */
+ assert( pPage==p->pDirty );
+ p->pDirty = pPage->pDirtyNext;
+ assert( p->bPurgeable || p->eCreate==2 );
+ if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
+ assert( p->bPurgeable==0 || p->eCreate==1 );
+ p->eCreate = 2;
+ }
+ }
+ }
+ if( addRemove & PCACHE_DIRTYLIST_ADD ){
+ pPage->pDirtyPrev = 0;
+ pPage->pDirtyNext = p->pDirty;
+ if( pPage->pDirtyNext ){
+ assert( pPage->pDirtyNext->pDirtyPrev==0 );
+ pPage->pDirtyNext->pDirtyPrev = pPage;
+ }else{
+ p->pDirtyTail = pPage;
+ if( p->bPurgeable ){
+ assert( p->eCreate==2 );
+ p->eCreate = 1;
+ }
+ }
+ p->pDirty = pPage;
+
+ /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
+ ** pSynced to point to it. Checking the NEED_SYNC flag is an
+ ** optimization, as if pSynced points to a page with the NEED_SYNC
+ ** flag set sqlite3PcacheFetchStress() searches through all newer
+ ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
+ if( !p->pSynced
+ && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
+ ){
+ p->pSynced = pPage;
+ }
+ }
+ pcacheDump(p);
+}
+
+/*
+** Wrapper around the pluggable caches xUnpin method. If the cache is
+** being used for an in-memory database, this function is a no-op.
+*/
+static void pcacheUnpin(PgHdr *p){
+ if( p->pCache->bPurgeable ){
+ pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
+ sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
+ pcacheDump(p->pCache);
+ }
+}
+
+/*
+** Compute the number of pages of cache requested. p->szCache is the
+** cache size requested by the "PRAGMA cache_size" statement.
+*/
+static int numberOfCachePages(PCache *p){
+ if( p->szCache>=0 ){
+ /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
+ ** suggested cache size is set to N. */
+ return p->szCache;
+ }else{
+ /* IMPLEMANTATION-OF: R-59858-46238 If the argument N is negative, then the
+ ** number of cache pages is adjusted to be a number of pages that would
+ ** use approximately abs(N*1024) bytes of memory based on the current
+ ** page size. */
+ return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
+ }
+}
+
+/*************************************************** General Interfaces ******
+**
+** Initialize and shutdown the page cache subsystem. Neither of these
+** functions are threadsafe.
+*/
+SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
+ if( sqlite3GlobalConfig.pcache2.xInit==0 ){
+ /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
+ ** built-in default page cache is used instead of the application defined
+ ** page cache. */
+ sqlite3PCacheSetDefault();
+ assert( sqlite3GlobalConfig.pcache2.xInit!=0 );
+ }
+ return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
+}
+SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
+ if( sqlite3GlobalConfig.pcache2.xShutdown ){
+ /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
+ sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
+ }
+}
+
+/*
+** Return the size in bytes of a PCache object.
+*/
+SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
+
+/*
+** Create a new PCache object. Storage space to hold the object
+** has already been allocated and is passed in as the p pointer.
+** The caller discovers how much space needs to be allocated by
+** calling sqlite3PcacheSize().
+**
+** szExtra is some extra space allocated for each page. The first
+** 8 bytes of the extra space will be zeroed as the page is allocated,
+** but remaining content will be uninitialized. Though it is opaque
+** to this module, the extra space really ends up being the MemPage
+** structure in the pager.
+*/
+SQLITE_PRIVATE int sqlite3PcacheOpen(
+ int szPage, /* Size of every page */
+ int szExtra, /* Extra space associated with each page */
+ int bPurgeable, /* True if pages are on backing store */
+ int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
+ void *pStress, /* Argument to xStress */
+ PCache *p /* Preallocated space for the PCache */
+){
+ memset(p, 0, sizeof(PCache));
+ p->szPage = 1;
+ p->szExtra = szExtra;
+ assert( szExtra>=8 ); /* First 8 bytes will be zeroed */
+ p->bPurgeable = bPurgeable;
+ p->eCreate = 2;
+ p->xStress = xStress;
+ p->pStress = pStress;
+ p->szCache = 100;
+ p->szSpill = 1;
+ pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
+ return sqlite3PcacheSetPageSize(p, szPage);
+}
+
+/*
+** Change the page size for PCache object. The caller must ensure that there
+** are no outstanding page references when this function is called.
+*/
+SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
+ assert( pCache->nRefSum==0 && pCache->pDirty==0 );
+ if( pCache->szPage ){
+ sqlite3_pcache *pNew;
+ pNew = sqlite3GlobalConfig.pcache2.xCreate(
+ szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
+ pCache->bPurgeable
+ );
+ if( pNew==0 ) return SQLITE_NOMEM_BKPT;
+ sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
+ if( pCache->pCache ){
+ sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
+ }
+ pCache->pCache = pNew;
+ pCache->szPage = szPage;
+ pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Try to obtain a page from the cache.
+**
+** This routine returns a pointer to an sqlite3_pcache_page object if
+** such an object is already in cache, or if a new one is created.
+** This routine returns a NULL pointer if the object was not in cache
+** and could not be created.
+**
+** The createFlags should be 0 to check for existing pages and should
+** be 3 (not 1, but 3) to try to create a new page.
+**
+** If the createFlag is 0, then NULL is always returned if the page
+** is not already in the cache. If createFlag is 1, then a new page
+** is created only if that can be done without spilling dirty pages
+** and without exceeding the cache size limit.
+**
+** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
+** initialize the sqlite3_pcache_page object and convert it into a
+** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
+** routines are split this way for performance reasons. When separated
+** they can both (usually) operate without having to push values to
+** the stack on entry and pop them back off on exit, which saves a
+** lot of pushing and popping.
+*/
+SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
+ PCache *pCache, /* Obtain the page from this cache */
+ Pgno pgno, /* Page number to obtain */
+ int createFlag /* If true, create page if it does not exist already */
+){
+ int eCreate;
+ sqlite3_pcache_page *pRes;
+
+ assert( pCache!=0 );
+ assert( pCache->pCache!=0 );
+ assert( createFlag==3 || createFlag==0 );
+ assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
+
+ /* eCreate defines what to do if the page does not exist.
+ ** 0 Do not allocate a new page. (createFlag==0)
+ ** 1 Allocate a new page if doing so is inexpensive.
+ ** (createFlag==1 AND bPurgeable AND pDirty)
+ ** 2 Allocate a new page even it doing so is difficult.
+ ** (createFlag==1 AND !(bPurgeable AND pDirty)
+ */
+ eCreate = createFlag & pCache->eCreate;
+ assert( eCreate==0 || eCreate==1 || eCreate==2 );
+ assert( createFlag==0 || pCache->eCreate==eCreate );
+ assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
+ pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
+ pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
+ createFlag?" create":"",pRes));
+ return pRes;
+}
+
+/*
+** If the sqlite3PcacheFetch() routine is unable to allocate a new
+** page because no clean pages are available for reuse and the cache
+** size limit has been reached, then this routine can be invoked to
+** try harder to allocate a page. This routine might invoke the stress
+** callback to spill dirty pages to the journal. It will then try to
+** allocate the new page and will only fail to allocate a new page on
+** an OOM error.
+**
+** This routine should be invoked only after sqlite3PcacheFetch() fails.
+*/
+SQLITE_PRIVATE int sqlite3PcacheFetchStress(
+ PCache *pCache, /* Obtain the page from this cache */
+ Pgno pgno, /* Page number to obtain */
+ sqlite3_pcache_page **ppPage /* Write result here */
+){
+ PgHdr *pPg;
+ if( pCache->eCreate==2 ) return 0;
+
+ if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
+ /* Find a dirty page to write-out and recycle. First try to find a
+ ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
+ ** cleared), but if that is not possible settle for any other
+ ** unreferenced dirty page.
+ **
+ ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
+ ** flag is currently referenced, then the following may leave pSynced
+ ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
+ ** cleared). This is Ok, as pSynced is just an optimization. */
+ for(pPg=pCache->pSynced;
+ pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
+ pPg=pPg->pDirtyPrev
+ );
+ pCache->pSynced = pPg;
+ if( !pPg ){
+ for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
+ }
+ if( pPg ){
+ int rc;
+#ifdef SQLITE_LOG_CACHE_SPILL
+ sqlite3_log(SQLITE_FULL,
+ "spill page %d making room for %d - cache used: %d/%d",
+ pPg->pgno, pgno,
+ sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache),
+ numberOfCachePages(pCache));
+#endif
+ pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
+ rc = pCache->xStress(pCache->pStress, pPg);
+ pcacheDump(pCache);
+ if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
+ return rc;
+ }
+ }
+ }
+ *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
+ return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
+}
+
+/*
+** This is a helper routine for sqlite3PcacheFetchFinish()
+**
+** In the uncommon case where the page being fetched has not been
+** initialized, this routine is invoked to do the initialization.
+** This routine is broken out into a separate function since it
+** requires extra stack manipulation that can be avoided in the common
+** case.
+*/
+static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
+ PCache *pCache, /* Obtain the page from this cache */
+ Pgno pgno, /* Page number obtained */
+ sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
+){
+ PgHdr *pPgHdr;
+ assert( pPage!=0 );
+ pPgHdr = (PgHdr*)pPage->pExtra;
+ assert( pPgHdr->pPage==0 );
+ memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
+ pPgHdr->pPage = pPage;
+ pPgHdr->pData = pPage->pBuf;
+ pPgHdr->pExtra = (void *)&pPgHdr[1];
+ memset(pPgHdr->pExtra, 0, 8);
+ pPgHdr->pCache = pCache;
+ pPgHdr->pgno = pgno;
+ pPgHdr->flags = PGHDR_CLEAN;
+ return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
+}
+
+/*
+** This routine converts the sqlite3_pcache_page object returned by
+** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
+** must be called after sqlite3PcacheFetch() in order to get a usable
+** result.
+*/
+SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
+ PCache *pCache, /* Obtain the page from this cache */
+ Pgno pgno, /* Page number obtained */
+ sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
+){
+ PgHdr *pPgHdr;
+
+ assert( pPage!=0 );
+ pPgHdr = (PgHdr *)pPage->pExtra;
+
+ if( !pPgHdr->pPage ){
+ return pcacheFetchFinishWithInit(pCache, pgno, pPage);
+ }
+ pCache->nRefSum++;
+ pPgHdr->nRef++;
+ assert( sqlite3PcachePageSanity(pPgHdr) );
+ return pPgHdr;
+}
+
+/*
+** Decrement the reference count on a page. If the page is clean and the
+** reference count drops to 0, then it is made eligible for recycling.
+*/
+SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
+ assert( p->nRef>0 );
+ p->pCache->nRefSum--;
+ if( (--p->nRef)==0 ){
+ if( p->flags&PGHDR_CLEAN ){
+ pcacheUnpin(p);
+ }else{
+ pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
+ }
+ }
+}
+
+/*
+** Increase the reference count of a supplied page by 1.
+*/
+SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
+ assert(p->nRef>0);
+ assert( sqlite3PcachePageSanity(p) );
+ p->nRef++;
+ p->pCache->nRefSum++;
+}
+
+/*
+** Drop a page from the cache. There must be exactly one reference to the
+** page. This function deletes that reference, so after it returns the
+** page pointed to by p is invalid.
+*/
+SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
+ assert( p->nRef==1 );
+ assert( sqlite3PcachePageSanity(p) );
+ if( p->flags&PGHDR_DIRTY ){
+ pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
+ }
+ p->pCache->nRefSum--;
+ sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
+}
+
+/*
+** Make sure the page is marked as dirty. If it isn't dirty already,
+** make it so.
+*/
+SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
+ assert( p->nRef>0 );
+ assert( sqlite3PcachePageSanity(p) );
+ if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
+ p->flags &= ~PGHDR_DONT_WRITE;
+ if( p->flags & PGHDR_CLEAN ){
+ p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
+ pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
+ assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
+ pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
+ }
+ assert( sqlite3PcachePageSanity(p) );
+ }
+}
+
+/*
+** Make sure the page is marked as clean. If it isn't clean already,
+** make it so.
+*/
+SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
+ assert( sqlite3PcachePageSanity(p) );
+ assert( (p->flags & PGHDR_DIRTY)!=0 );
+ assert( (p->flags & PGHDR_CLEAN)==0 );
+ pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
+ p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
+ p->flags |= PGHDR_CLEAN;
+ pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
+ assert( sqlite3PcachePageSanity(p) );
+ if( p->nRef==0 ){
+ pcacheUnpin(p);
+ }
+}
+
+/*
+** Make every page in the cache clean.
+*/
+SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
+ PgHdr *p;
+ pcacheTrace(("%p.CLEAN-ALL\n",pCache));
+ while( (p = pCache->pDirty)!=0 ){
+ sqlite3PcacheMakeClean(p);
+ }
+}
+
+/*
+** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
+*/
+SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
+ PgHdr *p;
+ pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
+ for(p=pCache->pDirty; p; p=p->pDirtyNext){
+ p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
+ }
+ pCache->pSynced = pCache->pDirtyTail;
+}
+
+/*
+** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
+*/
+SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
+ PgHdr *p;
+ for(p=pCache->pDirty; p; p=p->pDirtyNext){
+ p->flags &= ~PGHDR_NEED_SYNC;
+ }
+ pCache->pSynced = pCache->pDirtyTail;
+}
+
+/*
+** Change the page number of page p to newPgno.
+*/
+SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
+ PCache *pCache = p->pCache;
+ assert( p->nRef>0 );
+ assert( newPgno>0 );
+ assert( sqlite3PcachePageSanity(p) );
+ pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
+ sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
+ p->pgno = newPgno;
+ if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
+ pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
+ }
+}
+
+/*
+** Drop every cache entry whose page number is greater than "pgno". The
+** caller must ensure that there are no outstanding references to any pages
+** other than page 1 with a page number greater than pgno.
+**
+** If there is a reference to page 1 and the pgno parameter passed to this
+** function is 0, then the data area associated with page 1 is zeroed, but
+** the page object is not dropped.
+*/
+SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
+ if( pCache->pCache ){
+ PgHdr *p;
+ PgHdr *pNext;
+ pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
+ for(p=pCache->pDirty; p; p=pNext){
+ pNext = p->pDirtyNext;
+ /* This routine never gets call with a positive pgno except right
+ ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
+ ** it must be that pgno==0.
+ */
+ assert( p->pgno>0 );
+ if( p->pgno>pgno ){
+ assert( p->flags&PGHDR_DIRTY );
+ sqlite3PcacheMakeClean(p);
+ }
+ }
+ if( pgno==0 && pCache->nRefSum ){
+ sqlite3_pcache_page *pPage1;
+ pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
+ if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
+ ** pCache->nRefSum>0 */
+ memset(pPage1->pBuf, 0, pCache->szPage);
+ pgno = 1;
+ }
+ }
+ sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
+ }
+}
+
+/*
+** Close a cache.
+*/
+SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
+ assert( pCache->pCache!=0 );
+ pcacheTrace(("%p.CLOSE\n",pCache));
+ sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
+}
+
+/*
+** Discard the contents of the cache.
+*/
+SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
+ sqlite3PcacheTruncate(pCache, 0);
+}
+
+/*
+** Merge two lists of pages connected by pDirty and in pgno order.
+** Do not bother fixing the pDirtyPrev pointers.
+*/
+static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
+ PgHdr result, *pTail;
+ pTail = &result;
+ assert( pA!=0 && pB!=0 );
+ for(;;){
+ if( pA->pgno<pB->pgno ){
+ pTail->pDirty = pA;
+ pTail = pA;
+ pA = pA->pDirty;
+ if( pA==0 ){
+ pTail->pDirty = pB;
+ break;
+ }
+ }else{
+ pTail->pDirty = pB;
+ pTail = pB;
+ pB = pB->pDirty;
+ if( pB==0 ){
+ pTail->pDirty = pA;
+ break;
+ }
+ }
+ }
+ return result.pDirty;
+}
+
+/*
+** Sort the list of pages in accending order by pgno. Pages are
+** connected by pDirty pointers. The pDirtyPrev pointers are
+** corrupted by this sort.
+**
+** Since there cannot be more than 2^31 distinct pages in a database,
+** there cannot be more than 31 buckets required by the merge sorter.
+** One extra bucket is added to catch overflow in case something
+** ever changes to make the previous sentence incorrect.
+*/
+#define N_SORT_BUCKET 32
+static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
+ PgHdr *a[N_SORT_BUCKET], *p;
+ int i;
+ memset(a, 0, sizeof(a));
+ while( pIn ){
+ p = pIn;
+ pIn = p->pDirty;
+ p->pDirty = 0;
+ for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
+ if( a[i]==0 ){
+ a[i] = p;
+ break;
+ }else{
+ p = pcacheMergeDirtyList(a[i], p);
+ a[i] = 0;
+ }
+ }
+ if( NEVER(i==N_SORT_BUCKET-1) ){
+ /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
+ ** the input list. But that is impossible.
+ */
+ a[i] = pcacheMergeDirtyList(a[i], p);
+ }
+ }
+ p = a[0];
+ for(i=1; i<N_SORT_BUCKET; i++){
+ if( a[i]==0 ) continue;
+ p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
+ }
+ return p;
+}
+
+/*
+** Return a list of all dirty pages in the cache, sorted by page number.
+*/
+SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
+ PgHdr *p;
+ for(p=pCache->pDirty; p; p=p->pDirtyNext){
+ p->pDirty = p->pDirtyNext;
+ }
+ return pcacheSortDirtyList(pCache->pDirty);
+}
+
+/*
+** Return the total number of references to all pages held by the cache.
+**
+** This is not the total number of pages referenced, but the sum of the
+** reference count for all pages.
+*/
+SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
+ return pCache->nRefSum;
+}
+
+/*
+** Return the number of references to the page supplied as an argument.
+*/
+SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
+ return p->nRef;
+}
+
+/*
+** Return the total number of pages in the cache.
+*/
+SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
+ assert( pCache->pCache!=0 );
+ return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
+}
+
+#ifdef SQLITE_TEST
+/*
+** Get the suggested cache-size value.
+*/
+SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
+ return numberOfCachePages(pCache);
+}
+#endif
+
+/*
+** Set the suggested cache-size value.
+*/
+SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
+ assert( pCache->pCache!=0 );
+ pCache->szCache = mxPage;
+ sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
+ numberOfCachePages(pCache));
+}
+
+/*
+** Set the suggested cache-spill value. Make no changes if if the
+** argument is zero. Return the effective cache-spill size, which will
+** be the larger of the szSpill and szCache.
+*/
+SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
+ int res;
+ assert( p->pCache!=0 );
+ if( mxPage ){
+ if( mxPage<0 ){
+ mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
+ }
+ p->szSpill = mxPage;
+ }
+ res = numberOfCachePages(p);
+ if( res<p->szSpill ) res = p->szSpill;
+ return res;
+}
+
+/*
+** Free up as much memory as possible from the page cache.
+*/
+SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
+ assert( pCache->pCache!=0 );
+ sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
+}
+
+/*
+** Return the size of the header added by this middleware layer
+** in the page-cache hierarchy.
+*/
+SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
+
+/*
+** Return the number of dirty pages currently in the cache, as a percentage
+** of the configured cache size.
+*/
+SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
+ PgHdr *pDirty;
+ int nDirty = 0;
+ int nCache = numberOfCachePages(pCache);
+ for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
+ return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
+}
+
+#ifdef SQLITE_DIRECT_OVERFLOW_READ
+/*
+** Return true if there are one or more dirty pages in the cache. Else false.
+*/
+SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache){
+ return (pCache->pDirty!=0);
+}
+#endif
+
+#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
+/*
+** For all dirty pages currently in the cache, invoke the specified
+** callback. This is only used if the SQLITE_CHECK_PAGES macro is
+** defined.
+*/
+SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
+ PgHdr *pDirty;
+ for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
+ xIter(pDirty);
+ }
+}
+#endif
+
+/************** End of pcache.c **********************************************/
+/************** Begin file pcache1.c *****************************************/
+/*
+** 2008 November 05
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file implements the default page cache implementation (the
+** sqlite3_pcache interface). It also contains part of the implementation
+** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
+** If the default page cache implementation is overridden, then neither of
+** these two features are available.
+**
+** A Page cache line looks like this:
+**
+** -------------------------------------------------------------
+** | database page content | PgHdr1 | MemPage | PgHdr |
+** -------------------------------------------------------------
+**
+** The database page content is up front (so that buffer overreads tend to
+** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
+** is the extension added by the btree.c module containing information such
+** as the database page number and how that database page is used. PgHdr
+** is added by the pcache.c layer and contains information used to keep track
+** of which pages are "dirty". PgHdr1 is an extension added by this
+** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
+** PgHdr1 contains information needed to look up a page by its page number.
+** The superclass sqlite3_pcache_page.pBuf points to the start of the
+** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
+**
+** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
+** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
+** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
+** size can vary according to architecture, compile-time options, and
+** SQLite library version number.
+**
+** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
+** using a separate memory allocation from the database page content. This
+** seeks to overcome the "clownshoe" problem (also called "internal
+** fragmentation" in academic literature) of allocating a few bytes more
+** than a power of two with the memory allocator rounding up to the next
+** power of two, and leaving the rounded-up space unused.
+**
+** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
+** with this module. Information is passed back and forth as PgHdr1 pointers.
+**
+** The pcache.c and pager.c modules deal pointers to PgHdr objects.
+** The btree.c module deals with pointers to MemPage objects.
+**
+** SOURCE OF PAGE CACHE MEMORY:
+**
+** Memory for a page might come from any of three sources:
+**
+** (1) The general-purpose memory allocator - sqlite3Malloc()
+** (2) Global page-cache memory provided using sqlite3_config() with
+** SQLITE_CONFIG_PAGECACHE.
+** (3) PCache-local bulk allocation.
+**
+** The third case is a chunk of heap memory (defaulting to 100 pages worth)
+** that is allocated when the page cache is created. The size of the local
+** bulk allocation can be adjusted using
+**
+** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
+**
+** If N is positive, then N pages worth of memory are allocated using a single
+** sqlite3Malloc() call and that memory is used for the first N pages allocated.
+** Or if N is negative, then -1024*N bytes of memory are allocated and used
+** for as many pages as can be accomodated.
+**
+** Only one of (2) or (3) can be used. Once the memory available to (2) or
+** (3) is exhausted, subsequent allocations fail over to the general-purpose
+** memory allocator (1).
+**
+** Earlier versions of SQLite used only methods (1) and (2). But experiments
+** show that method (3) with N==100 provides about a 5% performance boost for
+** common workloads.
+*/
+/* #include "sqliteInt.h" */
+
+typedef struct PCache1 PCache1;
+typedef struct PgHdr1 PgHdr1;
+typedef struct PgFreeslot PgFreeslot;
+typedef struct PGroup PGroup;
+
+/*
+** Each cache entry is represented by an instance of the following
+** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
+** PgHdr1.pCache->szPage bytes is allocated directly before this structure
+** in memory.
+**
+** Note: Variables isBulkLocal and isAnchor were once type "u8". That works,
+** but causes a 2-byte gap in the structure for most architectures (since
+** pointers must be either 4 or 8-byte aligned). As this structure is located
+** in memory directly after the associated page data, if the database is
+** corrupt, code at the b-tree layer may overread the page buffer and
+** read part of this structure before the corruption is detected. This
+** can cause a valgrind error if the unitialized gap is accessed. Using u16
+** ensures there is no such gap, and therefore no bytes of unitialized memory
+** in the structure.
+*/
+struct PgHdr1 {
+ sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
+ unsigned int iKey; /* Key value (page number) */
+ u16 isBulkLocal; /* This page from bulk local storage */
+ u16 isAnchor; /* This is the PGroup.lru element */
+ PgHdr1 *pNext; /* Next in hash table chain */
+ PCache1 *pCache; /* Cache that currently owns this page */
+ PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
+ PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
+ /* NB: pLruPrev is only valid if pLruNext!=0 */
+};
+
+/*
+** A page is pinned if it is not on the LRU list. To be "pinned" means
+** that the page is in active use and must not be deallocated.
+*/
+#define PAGE_IS_PINNED(p) ((p)->pLruNext==0)
+#define PAGE_IS_UNPINNED(p) ((p)->pLruNext!=0)
+
+/* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
+** of one or more PCaches that are able to recycle each other's unpinned
+** pages when they are under memory pressure. A PGroup is an instance of
+** the following object.
+**
+** This page cache implementation works in one of two modes:
+**
+** (1) Every PCache is the sole member of its own PGroup. There is
+** one PGroup per PCache.
+**
+** (2) There is a single global PGroup that all PCaches are a member
+** of.
+**
+** Mode 1 uses more memory (since PCache instances are not able to rob
+** unused pages from other PCaches) but it also operates without a mutex,
+** and is therefore often faster. Mode 2 requires a mutex in order to be
+** threadsafe, but recycles pages more efficiently.
+**
+** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
+** PGroup which is the pcache1.grp global variable and its mutex is
+** SQLITE_MUTEX_STATIC_LRU.
+*/
+struct PGroup {
+ sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
+ unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
+ unsigned int nMinPage; /* Sum of nMin for purgeable caches */
+ unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
+ unsigned int nPurgeable; /* Number of purgeable pages allocated */
+ PgHdr1 lru; /* The beginning and end of the LRU list */
+};
+
+/* Each page cache is an instance of the following object. Every
+** open database file (including each in-memory database and each
+** temporary or transient database) has a single page cache which
+** is an instance of this object.
+**
+** Pointers to structures of this type are cast and returned as
+** opaque sqlite3_pcache* handles.
+*/
+struct PCache1 {
+ /* Cache configuration parameters. Page size (szPage) and the purgeable
+ ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
+ ** cache is created and are never changed thereafter. nMax may be
+ ** modified at any time by a call to the pcache1Cachesize() method.
+ ** The PGroup mutex must be held when accessing nMax.
+ */
+ PGroup *pGroup; /* PGroup this cache belongs to */
+ unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */
+ int szPage; /* Size of database content section */
+ int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
+ int szAlloc; /* Total size of one pcache line */
+ int bPurgeable; /* True if cache is purgeable */
+ unsigned int nMin; /* Minimum number of pages reserved */
+ unsigned int nMax; /* Configured "cache_size" value */
+ unsigned int n90pct; /* nMax*9/10 */
+ unsigned int iMaxKey; /* Largest key seen since xTruncate() */
+ unsigned int nPurgeableDummy; /* pnPurgeable points here when not used*/
+
+ /* Hash table of all pages. The following variables may only be accessed
+ ** when the accessor is holding the PGroup mutex.
+ */
+ unsigned int nRecyclable; /* Number of pages in the LRU list */
+ unsigned int nPage; /* Total number of pages in apHash */
+ unsigned int nHash; /* Number of slots in apHash[] */
+ PgHdr1 **apHash; /* Hash table for fast lookup by key */
+ PgHdr1 *pFree; /* List of unused pcache-local pages */
+ void *pBulk; /* Bulk memory used by pcache-local */
+};
+
+/*
+** Free slots in the allocator used to divide up the global page cache
+** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
+*/
+struct PgFreeslot {
+ PgFreeslot *pNext; /* Next free slot */
+};
+
+/*
+** Global data used by this cache.
+*/
+static SQLITE_WSD struct PCacheGlobal {
+ PGroup grp; /* The global PGroup for mode (2) */
+
+ /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
+ ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
+ ** fixed at sqlite3_initialize() time and do not require mutex protection.
+ ** The nFreeSlot and pFree values do require mutex protection.
+ */
+ int isInit; /* True if initialized */
+ int separateCache; /* Use a new PGroup for each PCache */
+ int nInitPage; /* Initial bulk allocation size */
+ int szSlot; /* Size of each free slot */
+ int nSlot; /* The number of pcache slots */
+ int nReserve; /* Try to keep nFreeSlot above this */
+ void *pStart, *pEnd; /* Bounds of global page cache memory */
+ /* Above requires no mutex. Use mutex below for variable that follow. */
+ sqlite3_mutex *mutex; /* Mutex for accessing the following: */
+ PgFreeslot *pFree; /* Free page blocks */
+ int nFreeSlot; /* Number of unused pcache slots */
+ /* The following value requires a mutex to change. We skip the mutex on
+ ** reading because (1) most platforms read a 32-bit integer atomically and
+ ** (2) even if an incorrect value is read, no great harm is done since this
+ ** is really just an optimization. */
+ int bUnderPressure; /* True if low on PAGECACHE memory */
+} pcache1_g;
+
+/*
+** All code in this file should access the global structure above via the
+** alias "pcache1". This ensures that the WSD emulation is used when
+** compiling for systems that do not support real WSD.
+*/
+#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
+
+/*
+** Macros to enter and leave the PCache LRU mutex.
+*/
+#if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
+# define pcache1EnterMutex(X) assert((X)->mutex==0)
+# define pcache1LeaveMutex(X) assert((X)->mutex==0)
+# define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
+#else
+# define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
+# define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
+# define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
+#endif
+
+/******************************************************************************/
+/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
+
+
+/*
+** This function is called during initialization if a static buffer is
+** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
+** verb to sqlite3_config(). Parameter pBuf points to an allocation large
+** enough to contain 'n' buffers of 'sz' bytes each.
+**
+** This routine is called from sqlite3_initialize() and so it is guaranteed
+** to be serialized already. There is no need for further mutexing.
+*/
+SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
+ if( pcache1.isInit ){
+ PgFreeslot *p;
+ if( pBuf==0 ) sz = n = 0;
+ if( n==0 ) sz = 0;
+ sz = ROUNDDOWN8(sz);
+ pcache1.szSlot = sz;
+ pcache1.nSlot = pcache1.nFreeSlot = n;
+ pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
+ pcache1.pStart = pBuf;
+ pcache1.pFree = 0;
+ pcache1.bUnderPressure = 0;
+ while( n-- ){
+ p = (PgFreeslot*)pBuf;
+ p->pNext = pcache1.pFree;
+ pcache1.pFree = p;
+ pBuf = (void*)&((char*)pBuf)[sz];
+ }
+ pcache1.pEnd = pBuf;
+ }
+}
+
+/*
+** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
+** true if pCache->pFree ends up containing one or more free pages.
+*/
+static int pcache1InitBulk(PCache1 *pCache){
+ i64 szBulk;
+ char *zBulk;
+ if( pcache1.nInitPage==0 ) return 0;
+ /* Do not bother with a bulk allocation if the cache size very small */
+ if( pCache->nMax<3 ) return 0;
+ sqlite3BeginBenignMalloc();
+ if( pcache1.nInitPage>0 ){
+ szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
+ }else{
+ szBulk = -1024 * (i64)pcache1.nInitPage;
+ }
+ if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
+ szBulk = pCache->szAlloc*(i64)pCache->nMax;
+ }
+ zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
+ sqlite3EndBenignMalloc();
+ if( zBulk ){
+ int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
+ do{
+ PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
+ pX->page.pBuf = zBulk;
+ pX->page.pExtra = &pX[1];
+ pX->isBulkLocal = 1;
+ pX->isAnchor = 0;
+ pX->pNext = pCache->pFree;
+ pX->pLruPrev = 0; /* Initializing this saves a valgrind error */
+ pCache->pFree = pX;
+ zBulk += pCache->szAlloc;
+ }while( --nBulk );
+ }
+ return pCache->pFree!=0;
+}
+
+/*
+** Malloc function used within this file to allocate space from the buffer
+** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
+** such buffer exists or there is no space left in it, this function falls
+** back to sqlite3Malloc().
+**
+** Multiple threads can run this routine at the same time. Global variables
+** in pcache1 need to be protected via mutex.
+*/
+static void *pcache1Alloc(int nByte){
+ void *p = 0;
+ assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
+ if( nByte<=pcache1.szSlot ){
+ sqlite3_mutex_enter(pcache1.mutex);
+ p = (PgHdr1 *)pcache1.pFree;
+ if( p ){
+ pcache1.pFree = pcache1.pFree->pNext;
+ pcache1.nFreeSlot--;
+ pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
+ assert( pcache1.nFreeSlot>=0 );
+ sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
+ sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
+ }
+ sqlite3_mutex_leave(pcache1.mutex);
+ }
+ if( p==0 ){
+ /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
+ ** it from sqlite3Malloc instead.
+ */
+ p = sqlite3Malloc(nByte);
+#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
+ if( p ){
+ int sz = sqlite3MallocSize(p);
+ sqlite3_mutex_enter(pcache1.mutex);
+ sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
+ sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
+ sqlite3_mutex_leave(pcache1.mutex);
+ }
+#endif
+ sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
+ }
+ return p;
+}
+
+/*
+** Free an allocated buffer obtained from pcache1Alloc().
+*/
+static void pcache1Free(void *p){
+ if( p==0 ) return;
+ if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
+ PgFreeslot *pSlot;
+ sqlite3_mutex_enter(pcache1.mutex);
+ sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
+ pSlot = (PgFreeslot*)p;
+ pSlot->pNext = pcache1.pFree;
+ pcache1.pFree = pSlot;
+ pcache1.nFreeSlot++;
+ pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
+ assert( pcache1.nFreeSlot<=pcache1.nSlot );
+ sqlite3_mutex_leave(pcache1.mutex);
+ }else{
+ assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
+ sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
+#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
+ {
+ int nFreed = 0;
+ nFreed = sqlite3MallocSize(p);
+ sqlite3_mutex_enter(pcache1.mutex);
+ sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
+ sqlite3_mutex_leave(pcache1.mutex);
+ }
+#endif
+ sqlite3_free(p);
+ }
+}
+
+#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
+/*
+** Return the size of a pcache allocation
+*/
+static int pcache1MemSize(void *p){
+ if( p>=pcache1.pStart && p<pcache1.pEnd ){
+ return pcache1.szSlot;
+ }else{
+ int iSize;
+ assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
+ sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
+ iSize = sqlite3MallocSize(p);
+ sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
+ return iSize;
+ }
+}
+#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
+
+/*
+** Allocate a new page object initially associated with cache pCache.
+*/
+static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
+ PgHdr1 *p = 0;
+ void *pPg;
+
+ assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
+ if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
+ assert( pCache->pFree!=0 );
+ p = pCache->pFree;
+ pCache->pFree = p->pNext;
+ p->pNext = 0;
+ }else{
+#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
+ /* The group mutex must be released before pcache1Alloc() is called. This
+ ** is because it might call sqlite3_release_memory(), which assumes that
+ ** this mutex is not held. */
+ assert( pcache1.separateCache==0 );
+ assert( pCache->pGroup==&pcache1.grp );
+ pcache1LeaveMutex(pCache->pGroup);
+#endif
+ if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
+#ifdef SQLITE_PCACHE_SEPARATE_HEADER
+ pPg = pcache1Alloc(pCache->szPage);
+ p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
+ if( !pPg || !p ){
+ pcache1Free(pPg);
+ sqlite3_free(p);
+ pPg = 0;
+ }
+#else
+ pPg = pcache1Alloc(pCache->szAlloc);
+#endif
+ if( benignMalloc ){ sqlite3EndBenignMalloc(); }
+#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
+ pcache1EnterMutex(pCache->pGroup);
+#endif
+ if( pPg==0 ) return 0;
+#ifndef SQLITE_PCACHE_SEPARATE_HEADER
+ p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
+#endif
+ p->page.pBuf = pPg;
+ p->page.pExtra = &p[1];
+ p->isBulkLocal = 0;
+ p->isAnchor = 0;
+ }
+ (*pCache->pnPurgeable)++;
+ return p;
+}
+
+/*
+** Free a page object allocated by pcache1AllocPage().
+*/
+static void pcache1FreePage(PgHdr1 *p){
+ PCache1 *pCache;
+ assert( p!=0 );
+ pCache = p->pCache;
+ assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
+ if( p->isBulkLocal ){
+ p->pNext = pCache->pFree;
+ pCache->pFree = p;
+ }else{
+ pcache1Free(p->page.pBuf);
+#ifdef SQLITE_PCACHE_SEPARATE_HEADER
+ sqlite3_free(p);
+#endif
+ }
+ (*pCache->pnPurgeable)--;
+}
+
+/*
+** Malloc function used by SQLite to obtain space from the buffer configured
+** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
+** exists, this function falls back to sqlite3Malloc().
+*/
+SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
+ assert( sz<=65536+8 ); /* These allocations are never very large */
+ return pcache1Alloc(sz);
+}
+
+/*
+** Free an allocated buffer obtained from sqlite3PageMalloc().
+*/
+SQLITE_PRIVATE void sqlite3PageFree(void *p){
+ pcache1Free(p);
+}
+
+
+/*
+** Return true if it desirable to avoid allocating a new page cache
+** entry.
+**
+** If memory was allocated specifically to the page cache using
+** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
+** it is desirable to avoid allocating a new page cache entry because
+** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
+** for all page cache needs and we should not need to spill the
+** allocation onto the heap.
+**
+** Or, the heap is used for all page cache memory but the heap is
+** under memory pressure, then again it is desirable to avoid
+** allocating a new page cache entry in order to avoid stressing
+** the heap even further.
+*/
+static int pcache1UnderMemoryPressure(PCache1 *pCache){
+ if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
+ return pcache1.bUnderPressure;
+ }else{
+ return sqlite3HeapNearlyFull();
+ }
+}
+
+/******************************************************************************/
+/******** General Implementation Functions ************************************/
+
+/*
+** This function is used to resize the hash table used by the cache passed
+** as the first argument.
+**
+** The PCache mutex must be held when this function is called.
+*/
+static void pcache1ResizeHash(PCache1 *p){
+ PgHdr1 **apNew;
+ unsigned int nNew;
+ unsigned int i;
+
+ assert( sqlite3_mutex_held(p->pGroup->mutex) );
+
+ nNew = p->nHash*2;
+ if( nNew<256 ){
+ nNew = 256;
+ }
+
+ pcache1LeaveMutex(p->pGroup);
+ if( p->nHash ){ sqlite3BeginBenignMalloc(); }
+ apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
+ if( p->nHash ){ sqlite3EndBenignMalloc(); }
+ pcache1EnterMutex(p->pGroup);
+ if( apNew ){
+ for(i=0; i<p->nHash; i++){
+ PgHdr1 *pPage;
+ PgHdr1 *pNext = p->apHash[i];
+ while( (pPage = pNext)!=0 ){
+ unsigned int h = pPage->iKey % nNew;
+ pNext = pPage->pNext;
+ pPage->pNext = apNew[h];
+ apNew[h] = pPage;
+ }
+ }
+ sqlite3_free(p->apHash);
+ p->apHash = apNew;
+ p->nHash = nNew;
+ }
+}
+
+/*
+** This function is used internally to remove the page pPage from the
+** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
+** LRU list, then this function is a no-op.
+**
+** The PGroup mutex must be held when this function is called.
+*/
+static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
+ assert( pPage!=0 );
+ assert( PAGE_IS_UNPINNED(pPage) );
+ assert( pPage->pLruNext );
+ assert( pPage->pLruPrev );
+ assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
+ pPage->pLruPrev->pLruNext = pPage->pLruNext;
+ pPage->pLruNext->pLruPrev = pPage->pLruPrev;
+ pPage->pLruNext = 0;
+ /* pPage->pLruPrev = 0;
+ ** No need to clear pLruPrev as it is never accessed if pLruNext is 0 */
+ assert( pPage->isAnchor==0 );
+ assert( pPage->pCache->pGroup->lru.isAnchor==1 );
+ pPage->pCache->nRecyclable--;
+ return pPage;
+}
+
+
+/*
+** Remove the page supplied as an argument from the hash table
+** (PCache1.apHash structure) that it is currently stored in.
+** Also free the page if freePage is true.
+**
+** The PGroup mutex must be held when this function is called.
+*/
+static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
+ unsigned int h;
+ PCache1 *pCache = pPage->pCache;
+ PgHdr1 **pp;
+
+ assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
+ h = pPage->iKey % pCache->nHash;
+ for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
+ *pp = (*pp)->pNext;
+
+ pCache->nPage--;
+ if( freeFlag ) pcache1FreePage(pPage);
+}
+
+/*
+** If there are currently more than nMaxPage pages allocated, try
+** to recycle pages to reduce the number allocated to nMaxPage.
+*/
+static void pcache1EnforceMaxPage(PCache1 *pCache){
+ PGroup *pGroup = pCache->pGroup;
+ PgHdr1 *p;
+ assert( sqlite3_mutex_held(pGroup->mutex) );
+ while( pGroup->nPurgeable>pGroup->nMaxPage
+ && (p=pGroup->lru.pLruPrev)->isAnchor==0
+ ){
+ assert( p->pCache->pGroup==pGroup );
+ assert( PAGE_IS_UNPINNED(p) );
+ pcache1PinPage(p);
+ pcache1RemoveFromHash(p, 1);
+ }
+ if( pCache->nPage==0 && pCache->pBulk ){
+ sqlite3_free(pCache->pBulk);
+ pCache->pBulk = pCache->pFree = 0;
+ }
+}
+
+/*
+** Discard all pages from cache pCache with a page number (key value)
+** greater than or equal to iLimit. Any pinned pages that meet this
+** criteria are unpinned before they are discarded.
+**
+** The PCache mutex must be held when this function is called.
+*/
+static void pcache1TruncateUnsafe(
+ PCache1 *pCache, /* The cache to truncate */
+ unsigned int iLimit /* Drop pages with this pgno or larger */
+){
+ TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
+ unsigned int h, iStop;
+ assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
+ assert( pCache->iMaxKey >= iLimit );
+ assert( pCache->nHash > 0 );
+ if( pCache->iMaxKey - iLimit < pCache->nHash ){
+ /* If we are just shaving the last few pages off the end of the
+ ** cache, then there is no point in scanning the entire hash table.
+ ** Only scan those hash slots that might contain pages that need to
+ ** be removed. */
+ h = iLimit % pCache->nHash;
+ iStop = pCache->iMaxKey % pCache->nHash;
+ TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
+ }else{
+ /* This is the general case where many pages are being removed.
+ ** It is necessary to scan the entire hash table */
+ h = pCache->nHash/2;
+ iStop = h - 1;
+ }
+ for(;;){
+ PgHdr1 **pp;
+ PgHdr1 *pPage;
+ assert( h<pCache->nHash );
+ pp = &pCache->apHash[h];
+ while( (pPage = *pp)!=0 ){
+ if( pPage->iKey>=iLimit ){
+ pCache->nPage--;
+ *pp = pPage->pNext;
+ if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
+ pcache1FreePage(pPage);
+ }else{
+ pp = &pPage->pNext;
+ TESTONLY( if( nPage>=0 ) nPage++; )
+ }
+ }
+ if( h==iStop ) break;
+ h = (h+1) % pCache->nHash;
+ }
+ assert( nPage<0 || pCache->nPage==(unsigned)nPage );
+}
+
+/******************************************************************************/
+/******** sqlite3_pcache Methods **********************************************/
+
+/*
+** Implementation of the sqlite3_pcache.xInit method.
+*/
+static int pcache1Init(void *NotUsed){
+ UNUSED_PARAMETER(NotUsed);
+ assert( pcache1.isInit==0 );
+ memset(&pcache1, 0, sizeof(pcache1));
+
+
+ /*
+ ** The pcache1.separateCache variable is true if each PCache has its own
+ ** private PGroup (mode-1). pcache1.separateCache is false if the single
+ ** PGroup in pcache1.grp is used for all page caches (mode-2).
+ **
+ ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
+ **
+ ** * Use a unified cache in single-threaded applications that have
+ ** configured a start-time buffer for use as page-cache memory using
+ ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
+ ** pBuf argument.
+ **
+ ** * Otherwise use separate caches (mode-1)
+ */
+#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
+ pcache1.separateCache = 0;
+#elif SQLITE_THREADSAFE
+ pcache1.separateCache = sqlite3GlobalConfig.pPage==0
+ || sqlite3GlobalConfig.bCoreMutex>0;
+#else
+ pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
+#endif
+
+#if SQLITE_THREADSAFE
+ if( sqlite3GlobalConfig.bCoreMutex ){
+ pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
+ pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
+ }
+#endif
+ if( pcache1.separateCache
+ && sqlite3GlobalConfig.nPage!=0
+ && sqlite3GlobalConfig.pPage==0
+ ){
+ pcache1.nInitPage = sqlite3GlobalConfig.nPage;
+ }else{
+ pcache1.nInitPage = 0;
+ }
+ pcache1.grp.mxPinned = 10;
+ pcache1.isInit = 1;
+ return SQLITE_OK;
+}
+
+/*
+** Implementation of the sqlite3_pcache.xShutdown method.
+** Note that the static mutex allocated in xInit does
+** not need to be freed.
+*/
+static void pcache1Shutdown(void *NotUsed){
+ UNUSED_PARAMETER(NotUsed);
+ assert( pcache1.isInit!=0 );
+ memset(&pcache1, 0, sizeof(pcache1));
+}
+
+/* forward declaration */
+static void pcache1Destroy(sqlite3_pcache *p);
+
+/*
+** Implementation of the sqlite3_pcache.xCreate method.
+**
+** Allocate a new cache.
+*/
+static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
+ PCache1 *pCache; /* The newly created page cache */
+ PGroup *pGroup; /* The group the new page cache will belong to */
+ int sz; /* Bytes of memory required to allocate the new cache */
+
+ assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
+ assert( szExtra < 300 );
+
+ sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
+ pCache = (PCache1 *)sqlite3MallocZero(sz);
+ if( pCache ){
+ if( pcache1.separateCache ){
+ pGroup = (PGroup*)&pCache[1];
+ pGroup->mxPinned = 10;
+ }else{
+ pGroup = &pcache1.grp;
+ }
+ pcache1EnterMutex(pGroup);
+ if( pGroup->lru.isAnchor==0 ){
+ pGroup->lru.isAnchor = 1;
+ pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
+ }
+ pCache->pGroup = pGroup;
+ pCache->szPage = szPage;
+ pCache->szExtra = szExtra;
+ pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
+ pCache->bPurgeable = (bPurgeable ? 1 : 0);
+ pcache1ResizeHash(pCache);
+ if( bPurgeable ){
+ pCache->nMin = 10;
+ pGroup->nMinPage += pCache->nMin;
+ pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
+ pCache->pnPurgeable = &pGroup->nPurgeable;
+ }else{
+ pCache->pnPurgeable = &pCache->nPurgeableDummy;
+ }
+ pcache1LeaveMutex(pGroup);
+ if( pCache->nHash==0 ){
+ pcache1Destroy((sqlite3_pcache*)pCache);
+ pCache = 0;
+ }
+ }
+ return (sqlite3_pcache *)pCache;
+}
+
+/*
+** Implementation of the sqlite3_pcache.xCachesize method.
+**
+** Configure the cache_size limit for a cache.
+*/
+static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
+ PCache1 *pCache = (PCache1 *)p;
+ if( pCache->bPurgeable ){
+ PGroup *pGroup = pCache->pGroup;
+ pcache1EnterMutex(pGroup);
+ pGroup->nMaxPage += (nMax - pCache->nMax);
+ pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
+ pCache->nMax = nMax;
+ pCache->n90pct = pCache->nMax*9/10;
+ pcache1EnforceMaxPage(pCache);
+ pcache1LeaveMutex(pGroup);
+ }
+}
+
+/*
+** Implementation of the sqlite3_pcache.xShrink method.
+**
+** Free up as much memory as possible.
+*/
+static void pcache1Shrink(sqlite3_pcache *p){
+ PCache1 *pCache = (PCache1*)p;
+ if( pCache->bPurgeable ){
+ PGroup *pGroup = pCache->pGroup;
+ int savedMaxPage;
+ pcache1EnterMutex(pGroup);
+ savedMaxPage = pGroup->nMaxPage;
+ pGroup->nMaxPage = 0;
+ pcache1EnforceMaxPage(pCache);
+ pGroup->nMaxPage = savedMaxPage;
+ pcache1LeaveMutex(pGroup);
+ }
+}
+
+/*
+** Implementation of the sqlite3_pcache.xPagecount method.
+*/
+static int pcache1Pagecount(sqlite3_pcache *p){
+ int n;
+ PCache1 *pCache = (PCache1*)p;
+ pcache1EnterMutex(pCache->pGroup);
+ n = pCache->nPage;
+ pcache1LeaveMutex(pCache->pGroup);
+ return n;
+}
+
+
+/*
+** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
+** in the header of the pcache1Fetch() procedure.
+**
+** This steps are broken out into a separate procedure because they are
+** usually not needed, and by avoiding the stack initialization required
+** for these steps, the main pcache1Fetch() procedure can run faster.
+*/
+static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
+ PCache1 *pCache,
+ unsigned int iKey,
+ int createFlag
+){
+ unsigned int nPinned;
+ PGroup *pGroup = pCache->pGroup;
+ PgHdr1 *pPage = 0;
+
+ /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
+ assert( pCache->nPage >= pCache->nRecyclable );
+ nPinned = pCache->nPage - pCache->nRecyclable;
+ assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
+ assert( pCache->n90pct == pCache->nMax*9/10 );
+ if( createFlag==1 && (
+ nPinned>=pGroup->mxPinned
+ || nPinned>=pCache->n90pct
+ || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
+ )){
+ return 0;
+ }
+
+ if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
+ assert( pCache->nHash>0 && pCache->apHash );
+
+ /* Step 4. Try to recycle a page. */
+ if( pCache->bPurgeable
+ && !pGroup->lru.pLruPrev->isAnchor
+ && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
+ ){
+ PCache1 *pOther;
+ pPage = pGroup->lru.pLruPrev;
+ assert( PAGE_IS_UNPINNED(pPage) );
+ pcache1RemoveFromHash(pPage, 0);
+ pcache1PinPage(pPage);
+ pOther = pPage->pCache;
+ if( pOther->szAlloc != pCache->szAlloc ){
+ pcache1FreePage(pPage);
+ pPage = 0;
+ }else{
+ pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
+ }
+ }
+
+ /* Step 5. If a usable page buffer has still not been found,
+ ** attempt to allocate a new one.
+ */
+ if( !pPage ){
+ pPage = pcache1AllocPage(pCache, createFlag==1);
+ }
+
+ if( pPage ){
+ unsigned int h = iKey % pCache->nHash;
+ pCache->nPage++;
+ pPage->iKey = iKey;
+ pPage->pNext = pCache->apHash[h];
+ pPage->pCache = pCache;
+ pPage->pLruNext = 0;
+ /* pPage->pLruPrev = 0;
+ ** No need to clear pLruPrev since it is not accessed when pLruNext==0 */
+ *(void **)pPage->page.pExtra = 0;
+ pCache->apHash[h] = pPage;
+ if( iKey>pCache->iMaxKey ){
+ pCache->iMaxKey = iKey;
+ }
+ }
+ return pPage;
+}
+
+/*
+** Implementation of the sqlite3_pcache.xFetch method.
+**
+** Fetch a page by key value.
+**
+** Whether or not a new page may be allocated by this function depends on
+** the value of the createFlag argument. 0 means do not allocate a new
+** page. 1 means allocate a new page if space is easily available. 2
+** means to try really hard to allocate a new page.
+**
+** For a non-purgeable cache (a cache used as the storage for an in-memory
+** database) there is really no difference between createFlag 1 and 2. So
+** the calling function (pcache.c) will never have a createFlag of 1 on
+** a non-purgeable cache.
+**
+** There are three different approaches to obtaining space for a page,
+** depending on the value of parameter createFlag (which may be 0, 1 or 2).
+**
+** 1. Regardless of the value of createFlag, the cache is searched for a
+** copy of the requested page. If one is found, it is returned.
+**
+** 2. If createFlag==0 and the page is not already in the cache, NULL is
+** returned.
+**
+** 3. If createFlag is 1, and the page is not already in the cache, then
+** return NULL (do not allocate a new page) if any of the following
+** conditions are true:
+**
+** (a) the number of pages pinned by the cache is greater than
+** PCache1.nMax, or
+**
+** (b) the number of pages pinned by the cache is greater than
+** the sum of nMax for all purgeable caches, less the sum of
+** nMin for all other purgeable caches, or
+**
+** 4. If none of the first three conditions apply and the cache is marked
+** as purgeable, and if one of the following is true:
+**
+** (a) The number of pages allocated for the cache is already
+** PCache1.nMax, or
+**
+** (b) The number of pages allocated for all purgeable caches is
+** already equal to or greater than the sum of nMax for all
+** purgeable caches,
+**
+** (c) The system is under memory pressure and wants to avoid
+** unnecessary pages cache entry allocations
+**
+** then attempt to recycle a page from the LRU list. If it is the right
+** size, return the recycled buffer. Otherwise, free the buffer and
+** proceed to step 5.
+**
+** 5. Otherwise, allocate and return a new page buffer.
+**
+** There are two versions of this routine. pcache1FetchWithMutex() is
+** the general case. pcache1FetchNoMutex() is a faster implementation for
+** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
+** invokes the appropriate routine.
+*/
+static PgHdr1 *pcache1FetchNoMutex(
+ sqlite3_pcache *p,
+ unsigned int iKey,
+ int createFlag
+){
+ PCache1 *pCache = (PCache1 *)p;
+ PgHdr1 *pPage = 0;
+
+ /* Step 1: Search the hash table for an existing entry. */
+ pPage = pCache->apHash[iKey % pCache->nHash];
+ while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
+
+ /* Step 2: If the page was found in the hash table, then return it.
+ ** If the page was not in the hash table and createFlag is 0, abort.
+ ** Otherwise (page not in hash and createFlag!=0) continue with
+ ** subsequent steps to try to create the page. */
+ if( pPage ){
+ if( PAGE_IS_UNPINNED(pPage) ){
+ return pcache1PinPage(pPage);
+ }else{
+ return pPage;
+ }
+ }else if( createFlag ){
+ /* Steps 3, 4, and 5 implemented by this subroutine */
+ return pcache1FetchStage2(pCache, iKey, createFlag);
+ }else{
+ return 0;
+ }
+}
+#if PCACHE1_MIGHT_USE_GROUP_MUTEX
+static PgHdr1 *pcache1FetchWithMutex(
+ sqlite3_pcache *p,
+ unsigned int iKey,
+ int createFlag
+){
+ PCache1 *pCache = (PCache1 *)p;
+ PgHdr1 *pPage;
+
+ pcache1EnterMutex(pCache->pGroup);
+ pPage = pcache1FetchNoMutex(p, iKey, createFlag);
+ assert( pPage==0 || pCache->iMaxKey>=iKey );
+ pcache1LeaveMutex(pCache->pGroup);
+ return pPage;
+}
+#endif
+static sqlite3_pcache_page *pcache1Fetch(
+ sqlite3_pcache *p,
+ unsigned int iKey,
+ int createFlag
+){
+#if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
+ PCache1 *pCache = (PCache1 *)p;
+#endif
+
+ assert( offsetof(PgHdr1,page)==0 );
+ assert( pCache->bPurgeable || createFlag!=1 );
+ assert( pCache->bPurgeable || pCache->nMin==0 );
+ assert( pCache->bPurgeable==0 || pCache->nMin==10 );
+ assert( pCache->nMin==0 || pCache->bPurgeable );
+ assert( pCache->nHash>0 );
+#if PCACHE1_MIGHT_USE_GROUP_MUTEX
+ if( pCache->pGroup->mutex ){
+ return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
+ }else
+#endif
+ {
+ return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
+ }
+}
+
+
+/*
+** Implementation of the sqlite3_pcache.xUnpin method.
+**
+** Mark a page as unpinned (eligible for asynchronous recycling).
+*/
+static void pcache1Unpin(
+ sqlite3_pcache *p,
+ sqlite3_pcache_page *pPg,
+ int reuseUnlikely
+){
+ PCache1 *pCache = (PCache1 *)p;
+ PgHdr1 *pPage = (PgHdr1 *)pPg;
+ PGroup *pGroup = pCache->pGroup;
+
+ assert( pPage->pCache==pCache );
+ pcache1EnterMutex(pGroup);
+
+ /* It is an error to call this function if the page is already
+ ** part of the PGroup LRU list.
+ */
+ assert( pPage->pLruNext==0 );
+ assert( PAGE_IS_PINNED(pPage) );
+
+ if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
+ pcache1RemoveFromHash(pPage, 1);
+ }else{
+ /* Add the page to the PGroup LRU list. */
+ PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
+ pPage->pLruPrev = &pGroup->lru;
+ (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
+ *ppFirst = pPage;
+ pCache->nRecyclable++;
+ }
+
+ pcache1LeaveMutex(pCache->pGroup);
+}
+
+/*
+** Implementation of the sqlite3_pcache.xRekey method.
+*/
+static void pcache1Rekey(
+ sqlite3_pcache *p,
+ sqlite3_pcache_page *pPg,
+ unsigned int iOld,
+ unsigned int iNew
+){
+ PCache1 *pCache = (PCache1 *)p;
+ PgHdr1 *pPage = (PgHdr1 *)pPg;
+ PgHdr1 **pp;
+ unsigned int h;
+ assert( pPage->iKey==iOld );
+ assert( pPage->pCache==pCache );
+
+ pcache1EnterMutex(pCache->pGroup);
+
+ h = iOld%pCache->nHash;
+ pp = &pCache->apHash[h];
+ while( (*pp)!=pPage ){
+ pp = &(*pp)->pNext;
+ }
+ *pp = pPage->pNext;
+
+ h = iNew%pCache->nHash;
+ pPage->iKey = iNew;
+ pPage->pNext = pCache->apHash[h];
+ pCache->apHash[h] = pPage;
+ if( iNew>pCache->iMaxKey ){
+ pCache->iMaxKey = iNew;
+ }
+
+ pcache1LeaveMutex(pCache->pGroup);
+}
+
+/*
+** Implementation of the sqlite3_pcache.xTruncate method.
+**
+** Discard all unpinned pages in the cache with a page number equal to
+** or greater than parameter iLimit. Any pinned pages with a page number
+** equal to or greater than iLimit are implicitly unpinned.
+*/
+static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
+ PCache1 *pCache = (PCache1 *)p;
+ pcache1EnterMutex(pCache->pGroup);
+ if( iLimit<=pCache->iMaxKey ){
+ pcache1TruncateUnsafe(pCache, iLimit);
+ pCache->iMaxKey = iLimit-1;
+ }
+ pcache1LeaveMutex(pCache->pGroup);
+}
+
+/*
+** Implementation of the sqlite3_pcache.xDestroy method.
+**
+** Destroy a cache allocated using pcache1Create().
+*/
+static void pcache1Destroy(sqlite3_pcache *p){
+ PCache1 *pCache = (PCache1 *)p;
+ PGroup *pGroup = pCache->pGroup;
+ assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
+ pcache1EnterMutex(pGroup);
+ if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
+ assert( pGroup->nMaxPage >= pCache->nMax );
+ pGroup->nMaxPage -= pCache->nMax;
+ assert( pGroup->nMinPage >= pCache->nMin );
+ pGroup->nMinPage -= pCache->nMin;
+ pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
+ pcache1EnforceMaxPage(pCache);
+ pcache1LeaveMutex(pGroup);
+ sqlite3_free(pCache->pBulk);
+ sqlite3_free(pCache->apHash);
+ sqlite3_free(pCache);
+}
+
+/*
+** This function is called during initialization (sqlite3_initialize()) to
+** install the default pluggable cache module, assuming the user has not
+** already provided an alternative.
+*/
+SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
+ static const sqlite3_pcache_methods2 defaultMethods = {
+ 1, /* iVersion */
+ 0, /* pArg */
+ pcache1Init, /* xInit */
+ pcache1Shutdown, /* xShutdown */
+ pcache1Create, /* xCreate */
+ pcache1Cachesize, /* xCachesize */
+ pcache1Pagecount, /* xPagecount */
+ pcache1Fetch, /* xFetch */
+ pcache1Unpin, /* xUnpin */
+ pcache1Rekey, /* xRekey */
+ pcache1Truncate, /* xTruncate */
+ pcache1Destroy, /* xDestroy */
+ pcache1Shrink /* xShrink */
+ };
+ sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
+}
+
+/*
+** Return the size of the header on each page of this PCACHE implementation.
+*/
+SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
+
+/*
+** Return the global mutex used by this PCACHE implementation. The
+** sqlite3_status() routine needs access to this mutex.
+*/
+SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
+ return pcache1.mutex;
+}
+
+#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
+/*
+** This function is called to free superfluous dynamically allocated memory
+** held by the pager system. Memory in use by any SQLite pager allocated
+** by the current thread may be sqlite3_free()ed.
+**
+** nReq is the number of bytes of memory required. Once this much has
+** been released, the function returns. The return value is the total number
+** of bytes of memory released.
+*/
+SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
+ int nFree = 0;
+ assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
+ assert( sqlite3_mutex_notheld(pcache1.mutex) );
+ if( sqlite3GlobalConfig.pPage==0 ){
+ PgHdr1 *p;
+ pcache1EnterMutex(&pcache1.grp);
+ while( (nReq<0 || nFree<nReq)
+ && (p=pcache1.grp.lru.pLruPrev)!=0
+ && p->isAnchor==0
+ ){
+ nFree += pcache1MemSize(p->page.pBuf);
+#ifdef SQLITE_PCACHE_SEPARATE_HEADER
+ nFree += sqlite3MemSize(p);
+#endif
+ assert( PAGE_IS_UNPINNED(p) );
+ pcache1PinPage(p);
+ pcache1RemoveFromHash(p, 1);
+ }
+ pcache1LeaveMutex(&pcache1.grp);
+ }
+ return nFree;
+}
+#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
+
+#ifdef SQLITE_TEST
+/*
+** This function is used by test procedures to inspect the internal state
+** of the global cache.
+*/
+SQLITE_PRIVATE void sqlite3PcacheStats(
+ int *pnCurrent, /* OUT: Total number of pages cached */
+ int *pnMax, /* OUT: Global maximum cache size */
+ int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
+ int *pnRecyclable /* OUT: Total number of pages available for recycling */
+){
+ PgHdr1 *p;
+ int nRecyclable = 0;
+ for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
+ assert( PAGE_IS_UNPINNED(p) );
+ nRecyclable++;
+ }
+ *pnCurrent = pcache1.grp.nPurgeable;
+ *pnMax = (int)pcache1.grp.nMaxPage;
+ *pnMin = (int)pcache1.grp.nMinPage;
+ *pnRecyclable = nRecyclable;
+}
+#endif
+
+/************** End of pcache1.c *********************************************/
+/************** Begin file rowset.c ******************************************/
+/*
+** 2008 December 3
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This module implements an object we call a "RowSet".
+**
+** The RowSet object is a collection of rowids. Rowids
+** are inserted into the RowSet in an arbitrary order. Inserts
+** can be intermixed with tests to see if a given rowid has been
+** previously inserted into the RowSet.
+**
+** After all inserts are finished, it is possible to extract the
+** elements of the RowSet in sorted order. Once this extraction
+** process has started, no new elements may be inserted.
+**
+** Hence, the primitive operations for a RowSet are:
+**
+** CREATE
+** INSERT
+** TEST
+** SMALLEST
+** DESTROY
+**
+** The CREATE and DESTROY primitives are the constructor and destructor,
+** obviously. The INSERT primitive adds a new element to the RowSet.
+** TEST checks to see if an element is already in the RowSet. SMALLEST
+** extracts the least value from the RowSet.
+**
+** The INSERT primitive might allocate additional memory. Memory is
+** allocated in chunks so most INSERTs do no allocation. There is an
+** upper bound on the size of allocated memory. No memory is freed
+** until DESTROY.
+**
+** The TEST primitive includes a "batch" number. The TEST primitive
+** will only see elements that were inserted before the last change
+** in the batch number. In other words, if an INSERT occurs between
+** two TESTs where the TESTs have the same batch nubmer, then the
+** value added by the INSERT will not be visible to the second TEST.
+** The initial batch number is zero, so if the very first TEST contains
+** a non-zero batch number, it will see all prior INSERTs.
+**
+** No INSERTs may occurs after a SMALLEST. An assertion will fail if
+** that is attempted.
+**
+** The cost of an INSERT is roughly constant. (Sometimes new memory
+** has to be allocated on an INSERT.) The cost of a TEST with a new
+** batch number is O(NlogN) where N is the number of elements in the RowSet.
+** The cost of a TEST using the same batch number is O(logN). The cost
+** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
+** primitives are constant time. The cost of DESTROY is O(N).
+**
+** TEST and SMALLEST may not be used by the same RowSet. This used to
+** be possible, but the feature was not used, so it was removed in order
+** to simplify the code.
+*/
+/* #include "sqliteInt.h" */
+
+
+/*
+** Target size for allocation chunks.
+*/
+#define ROWSET_ALLOCATION_SIZE 1024
+
+/*
+** The number of rowset entries per allocation chunk.
+*/
+#define ROWSET_ENTRY_PER_CHUNK \
+ ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
+
+/*
+** Each entry in a RowSet is an instance of the following object.
+**
+** This same object is reused to store a linked list of trees of RowSetEntry
+** objects. In that alternative use, pRight points to the next entry
+** in the list, pLeft points to the tree, and v is unused. The
+** RowSet.pForest value points to the head of this forest list.
+*/
+struct RowSetEntry {
+ i64 v; /* ROWID value for this entry */
+ struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
+ struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
+};
+
+/*
+** RowSetEntry objects are allocated in large chunks (instances of the
+** following structure) to reduce memory allocation overhead. The
+** chunks are kept on a linked list so that they can be deallocated
+** when the RowSet is destroyed.
+*/
+struct RowSetChunk {
+ struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
+ struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
+};
+
+/*
+** A RowSet in an instance of the following structure.
+**
+** A typedef of this structure if found in sqliteInt.h.
+*/
+struct RowSet {
+ struct RowSetChunk *pChunk; /* List of all chunk allocations */
+ sqlite3 *db; /* The database connection */
+ struct RowSetEntry *pEntry; /* List of entries using pRight */
+ struct RowSetEntry *pLast; /* Last entry on the pEntry list */
+ struct RowSetEntry *pFresh; /* Source of new entry objects */
+ struct RowSetEntry *pForest; /* List of binary trees of entries */
+ u16 nFresh; /* Number of objects on pFresh */
+ u16 rsFlags; /* Various flags */
+ int iBatch; /* Current insert batch */
+};
+
+/*
+** Allowed values for RowSet.rsFlags
+*/
+#define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
+#define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
+
+/*
+** Allocate a RowSet object. Return NULL if a memory allocation
+** error occurs.
+*/
+SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db){
+ RowSet *p = sqlite3DbMallocRawNN(db, sizeof(*p));
+ if( p ){
+ int N = sqlite3DbMallocSize(db, p);
+ p->pChunk = 0;
+ p->db = db;
+ p->pEntry = 0;
+ p->pLast = 0;
+ p->pForest = 0;
+ p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
+ p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
+ p->rsFlags = ROWSET_SORTED;
+ p->iBatch = 0;
+ }
+ return p;
+}
+
+/*
+** Deallocate all chunks from a RowSet. This frees all memory that
+** the RowSet has allocated over its lifetime. This routine is
+** the destructor for the RowSet.
+*/
+SQLITE_PRIVATE void sqlite3RowSetClear(void *pArg){
+ RowSet *p = (RowSet*)pArg;
+ struct RowSetChunk *pChunk, *pNextChunk;
+ for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
+ pNextChunk = pChunk->pNextChunk;
+ sqlite3DbFree(p->db, pChunk);
+ }
+ p->pChunk = 0;
+ p->nFresh = 0;
+ p->pEntry = 0;
+ p->pLast = 0;
+ p->pForest = 0;
+ p->rsFlags = ROWSET_SORTED;
+}
+
+/*
+** Deallocate all chunks from a RowSet. This frees all memory that
+** the RowSet has allocated over its lifetime. This routine is
+** the destructor for the RowSet.
+*/
+SQLITE_PRIVATE void sqlite3RowSetDelete(void *pArg){
+ sqlite3RowSetClear(pArg);
+ sqlite3DbFree(((RowSet*)pArg)->db, pArg);
+}
+
+/*
+** Allocate a new RowSetEntry object that is associated with the
+** given RowSet. Return a pointer to the new and completely uninitialized
+** object.
+**
+** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
+** routine returns NULL.
+*/
+static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
+ assert( p!=0 );
+ if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
+ /* We could allocate a fresh RowSetEntry each time one is needed, but it
+ ** is more efficient to pull a preallocated entry from the pool */
+ struct RowSetChunk *pNew;
+ pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
+ if( pNew==0 ){
+ return 0;
+ }
+ pNew->pNextChunk = p->pChunk;
+ p->pChunk = pNew;
+ p->pFresh = pNew->aEntry;
+ p->nFresh = ROWSET_ENTRY_PER_CHUNK;
+ }
+ p->nFresh--;
+ return p->pFresh++;
+}
+
+/*
+** Insert a new value into a RowSet.
+**
+** The mallocFailed flag of the database connection is set if a
+** memory allocation fails.
+*/
+SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
+ struct RowSetEntry *pEntry; /* The new entry */
+ struct RowSetEntry *pLast; /* The last prior entry */
+
+ /* This routine is never called after sqlite3RowSetNext() */
+ assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
+
+ pEntry = rowSetEntryAlloc(p);
+ if( pEntry==0 ) return;
+ pEntry->v = rowid;
+ pEntry->pRight = 0;
+ pLast = p->pLast;
+ if( pLast ){
+ if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
+ /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
+ ** where possible */
+ p->rsFlags &= ~ROWSET_SORTED;
+ }
+ pLast->pRight = pEntry;
+ }else{
+ p->pEntry = pEntry;
+ }
+ p->pLast = pEntry;
+}
+
+/*
+** Merge two lists of RowSetEntry objects. Remove duplicates.
+**
+** The input lists are connected via pRight pointers and are
+** assumed to each already be in sorted order.
+*/
+static struct RowSetEntry *rowSetEntryMerge(
+ struct RowSetEntry *pA, /* First sorted list to be merged */
+ struct RowSetEntry *pB /* Second sorted list to be merged */
+){
+ struct RowSetEntry head;
+ struct RowSetEntry *pTail;
+
+ pTail = &head;
+ assert( pA!=0 && pB!=0 );
+ for(;;){
+ assert( pA->pRight==0 || pA->v<=pA->pRight->v );
+ assert( pB->pRight==0 || pB->v<=pB->pRight->v );
+ if( pA->v<=pB->v ){
+ if( pA->v<pB->v ) pTail = pTail->pRight = pA;
+ pA = pA->pRight;
+ if( pA==0 ){
+ pTail->pRight = pB;
+ break;
+ }
+ }else{
+ pTail = pTail->pRight = pB;
+ pB = pB->pRight;
+ if( pB==0 ){
+ pTail->pRight = pA;
+ break;
+ }
+ }
+ }
+ return head.pRight;
+}
+
+/*
+** Sort all elements on the list of RowSetEntry objects into order of
+** increasing v.
+*/
+static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
+ unsigned int i;
+ struct RowSetEntry *pNext, *aBucket[40];
+
+ memset(aBucket, 0, sizeof(aBucket));
+ while( pIn ){
+ pNext = pIn->pRight;
+ pIn->pRight = 0;
+ for(i=0; aBucket[i]; i++){
+ pIn = rowSetEntryMerge(aBucket[i], pIn);
+ aBucket[i] = 0;
+ }
+ aBucket[i] = pIn;
+ pIn = pNext;
+ }
+ pIn = aBucket[0];
+ for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
+ if( aBucket[i]==0 ) continue;
+ pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
+ }
+ return pIn;
+}
+
+
+/*
+** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
+** Convert this tree into a linked list connected by the pRight pointers
+** and return pointers to the first and last elements of the new list.
+*/
+static void rowSetTreeToList(
+ struct RowSetEntry *pIn, /* Root of the input tree */
+ struct RowSetEntry **ppFirst, /* Write head of the output list here */
+ struct RowSetEntry **ppLast /* Write tail of the output list here */
+){
+ assert( pIn!=0 );
+ if( pIn->pLeft ){
+ struct RowSetEntry *p;
+ rowSetTreeToList(pIn->pLeft, ppFirst, &p);
+ p->pRight = pIn;
+ }else{
+ *ppFirst = pIn;
+ }
+ if( pIn->pRight ){
+ rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
+ }else{
+ *ppLast = pIn;
+ }
+ assert( (*ppLast)->pRight==0 );
+}
+
+
+/*
+** Convert a sorted list of elements (connected by pRight) into a binary
+** tree with depth of iDepth. A depth of 1 means the tree contains a single
+** node taken from the head of *ppList. A depth of 2 means a tree with
+** three nodes. And so forth.
+**
+** Use as many entries from the input list as required and update the
+** *ppList to point to the unused elements of the list. If the input
+** list contains too few elements, then construct an incomplete tree
+** and leave *ppList set to NULL.
+**
+** Return a pointer to the root of the constructed binary tree.
+*/
+static struct RowSetEntry *rowSetNDeepTree(
+ struct RowSetEntry **ppList,
+ int iDepth
+){
+ struct RowSetEntry *p; /* Root of the new tree */
+ struct RowSetEntry *pLeft; /* Left subtree */
+ if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
+ /* Prevent unnecessary deep recursion when we run out of entries */
+ return 0;
+ }
+ if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
+ /* This branch causes a *balanced* tree to be generated. A valid tree
+ ** is still generated without this branch, but the tree is wildly
+ ** unbalanced and inefficient. */
+ pLeft = rowSetNDeepTree(ppList, iDepth-1);
+ p = *ppList;
+ if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
+ /* It is safe to always return here, but the resulting tree
+ ** would be unbalanced */
+ return pLeft;
+ }
+ p->pLeft = pLeft;
+ *ppList = p->pRight;
+ p->pRight = rowSetNDeepTree(ppList, iDepth-1);
+ }else{
+ p = *ppList;
+ *ppList = p->pRight;
+ p->pLeft = p->pRight = 0;
+ }
+ return p;
+}
+
+/*
+** Convert a sorted list of elements into a binary tree. Make the tree
+** as deep as it needs to be in order to contain the entire list.
+*/
+static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
+ int iDepth; /* Depth of the tree so far */
+ struct RowSetEntry *p; /* Current tree root */
+ struct RowSetEntry *pLeft; /* Left subtree */
+
+ assert( pList!=0 );
+ p = pList;
+ pList = p->pRight;
+ p->pLeft = p->pRight = 0;
+ for(iDepth=1; pList; iDepth++){
+ pLeft = p;
+ p = pList;
+ pList = p->pRight;
+ p->pLeft = pLeft;
+ p->pRight = rowSetNDeepTree(&pList, iDepth);
+ }
+ return p;
+}
+
+/*
+** Extract the smallest element from the RowSet.
+** Write the element into *pRowid. Return 1 on success. Return
+** 0 if the RowSet is already empty.
+**
+** After this routine has been called, the sqlite3RowSetInsert()
+** routine may not be called again.
+**
+** This routine may not be called after sqlite3RowSetTest() has
+** been used. Older versions of RowSet allowed that, but as the
+** capability was not used by the code generator, it was removed
+** for code economy.
+*/
+SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
+ assert( p!=0 );
+ assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
+
+ /* Merge the forest into a single sorted list on first call */
+ if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
+ if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
+ p->pEntry = rowSetEntrySort(p->pEntry);
+ }
+ p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
+ }
+
+ /* Return the next entry on the list */
+ if( p->pEntry ){
+ *pRowid = p->pEntry->v;
+ p->pEntry = p->pEntry->pRight;
+ if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
+ /* Free memory immediately, rather than waiting on sqlite3_finalize() */
+ sqlite3RowSetClear(p);
+ }
+ return 1;
+ }else{
+ return 0;
+ }
+}
+
+/*
+** Check to see if element iRowid was inserted into the rowset as
+** part of any insert batch prior to iBatch. Return 1 or 0.
+**
+** If this is the first test of a new batch and if there exist entries
+** on pRowSet->pEntry, then sort those entries into the forest at
+** pRowSet->pForest so that they can be tested.
+*/
+SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
+ struct RowSetEntry *p, *pTree;
+
+ /* This routine is never called after sqlite3RowSetNext() */
+ assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
+
+ /* Sort entries into the forest on the first test of a new batch.
+ ** To save unnecessary work, only do this when the batch number changes.
+ */
+ if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
+ p = pRowSet->pEntry;
+ if( p ){
+ struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
+ if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
+ /* Only sort the current set of entries if they need it */
+ p = rowSetEntrySort(p);
+ }
+ for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
+ ppPrevTree = &pTree->pRight;
+ if( pTree->pLeft==0 ){
+ pTree->pLeft = rowSetListToTree(p);
+ break;
+ }else{
+ struct RowSetEntry *pAux, *pTail;
+ rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
+ pTree->pLeft = 0;
+ p = rowSetEntryMerge(pAux, p);
+ }
+ }
+ if( pTree==0 ){
+ *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
+ if( pTree ){
+ pTree->v = 0;
+ pTree->pRight = 0;
+ pTree->pLeft = rowSetListToTree(p);
+ }
+ }
+ pRowSet->pEntry = 0;
+ pRowSet->pLast = 0;
+ pRowSet->rsFlags |= ROWSET_SORTED;
+ }
+ pRowSet->iBatch = iBatch;
+ }
+
+ /* Test to see if the iRowid value appears anywhere in the forest.
+ ** Return 1 if it does and 0 if not.
+ */
+ for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
+ p = pTree->pLeft;
+ while( p ){
+ if( p->v<iRowid ){
+ p = p->pRight;
+ }else if( p->v>iRowid ){
+ p = p->pLeft;
+ }else{
+ return 1;
+ }
+ }
+ }
+ return 0;
+}
+
+/************** End of rowset.c **********************************************/
+/************** Begin file pager.c *******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This is the implementation of the page cache subsystem or "pager".
+**
+** The pager is used to access a database disk file. It implements
+** atomic commit and rollback through the use of a journal file that
+** is separate from the database file. The pager also implements file
+** locking to prevent two processes from writing the same database
+** file simultaneously, or one process from reading the database while
+** another is writing.
+*/
+#ifndef SQLITE_OMIT_DISKIO
+/* #include "sqliteInt.h" */
+/************** Include wal.h in the middle of pager.c ***********************/
+/************** Begin file wal.h *********************************************/
+/*
+** 2010 February 1
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This header file defines the interface to the write-ahead logging
+** system. Refer to the comments below and the header comment attached to
+** the implementation of each function in log.c for further details.
+*/
+
+#ifndef SQLITE_WAL_H
+#define SQLITE_WAL_H
+
+/* #include "sqliteInt.h" */
+
+/* Macros for extracting appropriate sync flags for either transaction
+** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
+*/
+#define WAL_SYNC_FLAGS(X) ((X)&0x03)
+#define CKPT_SYNC_FLAGS(X) (((X)>>2)&0x03)
+
+#ifdef SQLITE_OMIT_WAL
+# define sqlite3WalOpen(x,y,z) 0
+# define sqlite3WalLimit(x,y)
+# define sqlite3WalClose(v,w,x,y,z) 0
+# define sqlite3WalBeginReadTransaction(y,z) 0
+# define sqlite3WalEndReadTransaction(z)
+# define sqlite3WalDbsize(y) 0
+# define sqlite3WalBeginWriteTransaction(y) 0
+# define sqlite3WalEndWriteTransaction(x) 0
+# define sqlite3WalUndo(x,y,z) 0
+# define sqlite3WalSavepoint(y,z)
+# define sqlite3WalSavepointUndo(y,z) 0
+# define sqlite3WalFrames(u,v,w,x,y,z) 0
+# define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
+# define sqlite3WalCallback(z) 0
+# define sqlite3WalExclusiveMode(y,z) 0
+# define sqlite3WalHeapMemory(z) 0
+# define sqlite3WalFramesize(z) 0
+# define sqlite3WalFindFrame(x,y,z) 0
+# define sqlite3WalFile(x) 0
+#else
+
+#define WAL_SAVEPOINT_NDATA 4
+
+/* Connection to a write-ahead log (WAL) file.
+** There is one object of this type for each pager.
+*/
+typedef struct Wal Wal;
+
+/* Open and close a connection to a write-ahead log. */
+SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
+SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
+
+/* Set the limiting size of a WAL file. */
+SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
+
+/* Used by readers to open (lock) and close (unlock) a snapshot. A
+** snapshot is like a read-transaction. It is the state of the database
+** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
+** preserves the current state even if the other threads or processes
+** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
+** transaction and releases the lock.
+*/
+SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
+SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
+
+/* Read a page from the write-ahead log, if it is present. */
+SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
+SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
+
+/* If the WAL is not empty, return the size of the database. */
+SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
+
+/* Obtain or release the WRITER lock. */
+SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
+SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
+
+/* Undo any frames written (but not committed) to the log */
+SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
+
+/* Return an integer that records the current (uncommitted) write
+** position in the WAL */
+SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
+
+/* Move the write position of the WAL back to iFrame. Called in
+** response to a ROLLBACK TO command. */
+SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
+
+/* Write a frame or frames to the log. */
+SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
+
+/* Copy pages from the log to the database file */
+SQLITE_PRIVATE int sqlite3WalCheckpoint(
+ Wal *pWal, /* Write-ahead log connection */
+ sqlite3 *db, /* Check this handle's interrupt flag */
+ int eMode, /* One of PASSIVE, FULL and RESTART */
+ int (*xBusy)(void*), /* Function to call when busy */
+ void *pBusyArg, /* Context argument for xBusyHandler */
+ int sync_flags, /* Flags to sync db file with (or 0) */
+ int nBuf, /* Size of buffer nBuf */
+ u8 *zBuf, /* Temporary buffer to use */
+ int *pnLog, /* OUT: Number of frames in WAL */
+ int *pnCkpt /* OUT: Number of backfilled frames in WAL */
+);
+
+/* Return the value to pass to a sqlite3_wal_hook callback, the
+** number of frames in the WAL at the point of the last commit since
+** sqlite3WalCallback() was called. If no commits have occurred since
+** the last call, then return 0.
+*/
+SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
+
+/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
+** by the pager layer on the database file.
+*/
+SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
+
+/* Return true if the argument is non-NULL and the WAL module is using
+** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
+** WAL module is using shared-memory, return false.
+*/
+SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
+
+#ifdef SQLITE_ENABLE_SNAPSHOT
+SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
+SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
+SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
+SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot);
+SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal);
+#endif
+
+#ifdef SQLITE_ENABLE_ZIPVFS
+/* If the WAL file is not empty, return the number of bytes of content
+** stored in each frame (i.e. the db page-size when the WAL was created).
+*/
+SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
+#endif
+
+/* Return the sqlite3_file object for the WAL file */
+SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
+
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+SQLITE_PRIVATE int sqlite3WalWriteLock(Wal *pWal, int bLock);
+SQLITE_PRIVATE void sqlite3WalDb(Wal *pWal, sqlite3 *db);
+#endif
+
+#endif /* ifndef SQLITE_OMIT_WAL */
+#endif /* SQLITE_WAL_H */
+
+/************** End of wal.h *************************************************/
+/************** Continuing where we left off in pager.c **********************/
+
+
+/******************* NOTES ON THE DESIGN OF THE PAGER ************************
+**
+** This comment block describes invariants that hold when using a rollback
+** journal. These invariants do not apply for journal_mode=WAL,
+** journal_mode=MEMORY, or journal_mode=OFF.
+**
+** Within this comment block, a page is deemed to have been synced
+** automatically as soon as it is written when PRAGMA synchronous=OFF.
+** Otherwise, the page is not synced until the xSync method of the VFS
+** is called successfully on the file containing the page.
+**
+** Definition: A page of the database file is said to be "overwriteable" if
+** one or more of the following are true about the page:
+**
+** (a) The original content of the page as it was at the beginning of
+** the transaction has been written into the rollback journal and
+** synced.
+**
+** (b) The page was a freelist leaf page at the start of the transaction.
+**
+** (c) The page number is greater than the largest page that existed in
+** the database file at the start of the transaction.
+**
+** (1) A page of the database file is never overwritten unless one of the
+** following are true:
+**
+** (a) The page and all other pages on the same sector are overwriteable.
+**
+** (b) The atomic page write optimization is enabled, and the entire
+** transaction other than the update of the transaction sequence
+** number consists of a single page change.
+**
+** (2) The content of a page written into the rollback journal exactly matches
+** both the content in the database when the rollback journal was written
+** and the content in the database at the beginning of the current
+** transaction.
+**
+** (3) Writes to the database file are an integer multiple of the page size
+** in length and are aligned on a page boundary.
+**
+** (4) Reads from the database file are either aligned on a page boundary and
+** an integer multiple of the page size in length or are taken from the
+** first 100 bytes of the database file.
+**
+** (5) All writes to the database file are synced prior to the rollback journal
+** being deleted, truncated, or zeroed.
+**
+** (6) If a super-journal file is used, then all writes to the database file
+** are synced prior to the super-journal being deleted.
+**
+** Definition: Two databases (or the same database at two points it time)
+** are said to be "logically equivalent" if they give the same answer to
+** all queries. Note in particular the content of freelist leaf
+** pages can be changed arbitrarily without affecting the logical equivalence
+** of the database.
+**
+** (7) At any time, if any subset, including the empty set and the total set,
+** of the unsynced changes to a rollback journal are removed and the
+** journal is rolled back, the resulting database file will be logically
+** equivalent to the database file at the beginning of the transaction.
+**
+** (8) When a transaction is rolled back, the xTruncate method of the VFS
+** is called to restore the database file to the same size it was at
+** the beginning of the transaction. (In some VFSes, the xTruncate
+** method is a no-op, but that does not change the fact the SQLite will
+** invoke it.)
+**
+** (9) Whenever the database file is modified, at least one bit in the range
+** of bytes from 24 through 39 inclusive will be changed prior to releasing
+** the EXCLUSIVE lock, thus signaling other connections on the same
+** database to flush their caches.
+**
+** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
+** than one billion transactions.
+**
+** (11) A database file is well-formed at the beginning and at the conclusion
+** of every transaction.
+**
+** (12) An EXCLUSIVE lock is held on the database file when writing to
+** the database file.
+**
+** (13) A SHARED lock is held on the database file while reading any
+** content out of the database file.
+**
+******************************************************************************/
+
+/*
+** Macros for troubleshooting. Normally turned off
+*/
+#if 0
+int sqlite3PagerTrace=1; /* True to enable tracing */
+#define sqlite3DebugPrintf printf
+#define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
+#else
+#define PAGERTRACE(X)
+#endif
+
+/*
+** The following two macros are used within the PAGERTRACE() macros above
+** to print out file-descriptors.
+**
+** PAGERID() takes a pointer to a Pager struct as its argument. The
+** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
+** struct as its argument.
+*/
+#define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
+#define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))
+
+/*
+** The Pager.eState variable stores the current 'state' of a pager. A
+** pager may be in any one of the seven states shown in the following
+** state diagram.
+**
+** OPEN <------+------+
+** | | |
+** V | |
+** +---------> READER-------+ |
+** | | |
+** | V |
+** |<-------WRITER_LOCKED------> ERROR
+** | | ^
+** | V |
+** |<------WRITER_CACHEMOD-------->|
+** | | |
+** | V |
+** |<-------WRITER_DBMOD---------->|
+** | | |
+** | V |
+** +<------WRITER_FINISHED-------->+
+**
+**
+** List of state transitions and the C [function] that performs each:
+**
+** OPEN -> READER [sqlite3PagerSharedLock]
+** READER -> OPEN [pager_unlock]
+**
+** READER -> WRITER_LOCKED [sqlite3PagerBegin]
+** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
+** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
+** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
+** WRITER_*** -> READER [pager_end_transaction]
+**
+** WRITER_*** -> ERROR [pager_error]
+** ERROR -> OPEN [pager_unlock]
+**
+**
+** OPEN:
+**
+** The pager starts up in this state. Nothing is guaranteed in this
+** state - the file may or may not be locked and the database size is
+** unknown. The database may not be read or written.
+**
+** * No read or write transaction is active.
+** * Any lock, or no lock at all, may be held on the database file.
+** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
+**
+** READER:
+**
+** In this state all the requirements for reading the database in
+** rollback (non-WAL) mode are met. Unless the pager is (or recently
+** was) in exclusive-locking mode, a user-level read transaction is
+** open. The database size is known in this state.
+**
+** A connection running with locking_mode=normal enters this state when
+** it opens a read-transaction on the database and returns to state
+** OPEN after the read-transaction is completed. However a connection
+** running in locking_mode=exclusive (including temp databases) remains in
+** this state even after the read-transaction is closed. The only way
+** a locking_mode=exclusive connection can transition from READER to OPEN
+** is via the ERROR state (see below).
+**
+** * A read transaction may be active (but a write-transaction cannot).
+** * A SHARED or greater lock is held on the database file.
+** * The dbSize variable may be trusted (even if a user-level read
+** transaction is not active). The dbOrigSize and dbFileSize variables
+** may not be trusted at this point.
+** * If the database is a WAL database, then the WAL connection is open.
+** * Even if a read-transaction is not open, it is guaranteed that
+** there is no hot-journal in the file-system.
+**
+** WRITER_LOCKED:
+**
+** The pager moves to this state from READER when a write-transaction
+** is first opened on the database. In WRITER_LOCKED state, all locks
+** required to start a write-transaction are held, but no actual
+** modifications to the cache or database have taken place.
+**
+** In rollback mode, a RESERVED or (if the transaction was opened with
+** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
+** moving to this state, but the journal file is not written to or opened
+** to in this state. If the transaction is committed or rolled back while
+** in WRITER_LOCKED state, all that is required is to unlock the database
+** file.
+**
+** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
+** If the connection is running with locking_mode=exclusive, an attempt
+** is made to obtain an EXCLUSIVE lock on the database file.
+**
+** * A write transaction is active.
+** * If the connection is open in rollback-mode, a RESERVED or greater
+** lock is held on the database file.
+** * If the connection is open in WAL-mode, a WAL write transaction
+** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
+** called).
+** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
+** * The contents of the pager cache have not been modified.
+** * The journal file may or may not be open.
+** * Nothing (not even the first header) has been written to the journal.
+**
+** WRITER_CACHEMOD:
+**
+** A pager moves from WRITER_LOCKED state to this state when a page is
+** first modified by the upper layer. In rollback mode the journal file
+** is opened (if it is not already open) and a header written to the
+** start of it. The database file on disk has not been modified.
+**
+** * A write transaction is active.
+** * A RESERVED or greater lock is held on the database file.
+** * The journal file is open and the first header has been written
+** to it, but the header has not been synced to disk.
+** * The contents of the page cache have been modified.
+**
+** WRITER_DBMOD:
+**
+** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
+** when it modifies the contents of the database file. WAL connections
+** never enter this state (since they do not modify the database file,
+** just the log file).
+**
+** * A write transaction is active.
+** * An EXCLUSIVE or greater lock is held on the database file.
+** * The journal file is open and the first header has been written
+** and synced to disk.
+** * The contents of the page cache have been modified (and possibly
+** written to disk).
+**
+** WRITER_FINISHED:
+**
+** It is not possible for a WAL connection to enter this state.
+**
+** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
+** state after the entire transaction has been successfully written into the
+** database file. In this state the transaction may be committed simply
+** by finalizing the journal file. Once in WRITER_FINISHED state, it is
+** not possible to modify the database further. At this point, the upper
+** layer must either commit or rollback the transaction.
+**
+** * A write transaction is active.
+** * An EXCLUSIVE or greater lock is held on the database file.
+** * All writing and syncing of journal and database data has finished.
+** If no error occurred, all that remains is to finalize the journal to
+** commit the transaction. If an error did occur, the caller will need
+** to rollback the transaction.
+**
+** ERROR:
+**
+** The ERROR state is entered when an IO or disk-full error (including
+** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
+** difficult to be sure that the in-memory pager state (cache contents,
+** db size etc.) are consistent with the contents of the file-system.
+**
+** Temporary pager files may enter the ERROR state, but in-memory pagers
+** cannot.
+**
+** For example, if an IO error occurs while performing a rollback,
+** the contents of the page-cache may be left in an inconsistent state.
+** At this point it would be dangerous to change back to READER state
+** (as usually happens after a rollback). Any subsequent readers might
+** report database corruption (due to the inconsistent cache), and if
+** they upgrade to writers, they may inadvertently corrupt the database
+** file. To avoid this hazard, the pager switches into the ERROR state
+** instead of READER following such an error.
+**
+** Once it has entered the ERROR state, any attempt to use the pager
+** to read or write data returns an error. Eventually, once all
+** outstanding transactions have been abandoned, the pager is able to
+** transition back to OPEN state, discarding the contents of the
+** page-cache and any other in-memory state at the same time. Everything
+** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
+** when a read-transaction is next opened on the pager (transitioning
+** the pager into READER state). At that point the system has recovered
+** from the error.
+**
+** Specifically, the pager jumps into the ERROR state if:
+**
+** 1. An error occurs while attempting a rollback. This happens in
+** function sqlite3PagerRollback().
+**
+** 2. An error occurs while attempting to finalize a journal file
+** following a commit in function sqlite3PagerCommitPhaseTwo().
+**
+** 3. An error occurs while attempting to write to the journal or
+** database file in function pagerStress() in order to free up
+** memory.
+**
+** In other cases, the error is returned to the b-tree layer. The b-tree
+** layer then attempts a rollback operation. If the error condition
+** persists, the pager enters the ERROR state via condition (1) above.
+**
+** Condition (3) is necessary because it can be triggered by a read-only
+** statement executed within a transaction. In this case, if the error
+** code were simply returned to the user, the b-tree layer would not
+** automatically attempt a rollback, as it assumes that an error in a
+** read-only statement cannot leave the pager in an internally inconsistent
+** state.
+**
+** * The Pager.errCode variable is set to something other than SQLITE_OK.
+** * There are one or more outstanding references to pages (after the
+** last reference is dropped the pager should move back to OPEN state).
+** * The pager is not an in-memory pager.
+**
+**
+** Notes:
+**
+** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
+** connection is open in WAL mode. A WAL connection is always in one
+** of the first four states.
+**
+** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
+** state. There are two exceptions: immediately after exclusive-mode has
+** been turned on (and before any read or write transactions are
+** executed), and when the pager is leaving the "error state".
+**
+** * See also: assert_pager_state().
+*/
+#define PAGER_OPEN 0
+#define PAGER_READER 1
+#define PAGER_WRITER_LOCKED 2
+#define PAGER_WRITER_CACHEMOD 3
+#define PAGER_WRITER_DBMOD 4
+#define PAGER_WRITER_FINISHED 5
+#define PAGER_ERROR 6
+
+/*
+** The Pager.eLock variable is almost always set to one of the
+** following locking-states, according to the lock currently held on
+** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
+** This variable is kept up to date as locks are taken and released by
+** the pagerLockDb() and pagerUnlockDb() wrappers.
+**
+** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
+** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
+** the operation was successful. In these circumstances pagerLockDb() and
+** pagerUnlockDb() take a conservative approach - eLock is always updated
+** when unlocking the file, and only updated when locking the file if the
+** VFS call is successful. This way, the Pager.eLock variable may be set
+** to a less exclusive (lower) value than the lock that is actually held
+** at the system level, but it is never set to a more exclusive value.
+**
+** This is usually safe. If an xUnlock fails or appears to fail, there may
+** be a few redundant xLock() calls or a lock may be held for longer than
+** required, but nothing really goes wrong.
+**
+** The exception is when the database file is unlocked as the pager moves
+** from ERROR to OPEN state. At this point there may be a hot-journal file
+** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
+** transition, by the same pager or any other). If the call to xUnlock()
+** fails at this point and the pager is left holding an EXCLUSIVE lock, this
+** can confuse the call to xCheckReservedLock() call made later as part
+** of hot-journal detection.
+**
+** xCheckReservedLock() is defined as returning true "if there is a RESERVED
+** lock held by this process or any others". So xCheckReservedLock may
+** return true because the caller itself is holding an EXCLUSIVE lock (but
+** doesn't know it because of a previous error in xUnlock). If this happens
+** a hot-journal may be mistaken for a journal being created by an active
+** transaction in another process, causing SQLite to read from the database
+** without rolling it back.
+**
+** To work around this, if a call to xUnlock() fails when unlocking the
+** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
+** is only changed back to a real locking state after a successful call
+** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
+** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
+** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
+** lock on the database file before attempting to roll it back. See function
+** PagerSharedLock() for more detail.
+**
+** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
+** PAGER_OPEN state.
+*/
+#define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
+
+/*
+** The maximum allowed sector size. 64KiB. If the xSectorsize() method
+** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
+** This could conceivably cause corruption following a power failure on
+** such a system. This is currently an undocumented limit.
+*/
+#define MAX_SECTOR_SIZE 0x10000
+
+
+/*
+** An instance of the following structure is allocated for each active
+** savepoint and statement transaction in the system. All such structures
+** are stored in the Pager.aSavepoint[] array, which is allocated and
+** resized using sqlite3Realloc().
+**
+** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
+** set to 0. If a journal-header is written into the main journal while
+** the savepoint is active, then iHdrOffset is set to the byte offset
+** immediately following the last journal record written into the main
+** journal before the journal-header. This is required during savepoint
+** rollback (see pagerPlaybackSavepoint()).
+*/
+typedef struct PagerSavepoint PagerSavepoint;
+struct PagerSavepoint {
+ i64 iOffset; /* Starting offset in main journal */
+ i64 iHdrOffset; /* See above */
+ Bitvec *pInSavepoint; /* Set of pages in this savepoint */
+ Pgno nOrig; /* Original number of pages in file */
+ Pgno iSubRec; /* Index of first record in sub-journal */
+#ifndef SQLITE_OMIT_WAL
+ u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
+#endif
+};
+
+/*
+** Bits of the Pager.doNotSpill flag. See further description below.
+*/
+#define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
+#define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
+#define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
+
+/*
+** An open page cache is an instance of struct Pager. A description of
+** some of the more important member variables follows:
+**
+** eState
+**
+** The current 'state' of the pager object. See the comment and state
+** diagram above for a description of the pager state.
+**
+** eLock
+**
+** For a real on-disk database, the current lock held on the database file -
+** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
+**
+** For a temporary or in-memory database (neither of which require any
+** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
+** databases always have Pager.exclusiveMode==1, this tricks the pager
+** logic into thinking that it already has all the locks it will ever
+** need (and no reason to release them).
+**
+** In some (obscure) circumstances, this variable may also be set to
+** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
+** details.
+**
+** changeCountDone
+**
+** This boolean variable is used to make sure that the change-counter
+** (the 4-byte header field at byte offset 24 of the database file) is
+** not updated more often than necessary.
+**
+** It is set to true when the change-counter field is updated, which
+** can only happen if an exclusive lock is held on the database file.
+** It is cleared (set to false) whenever an exclusive lock is
+** relinquished on the database file. Each time a transaction is committed,
+** The changeCountDone flag is inspected. If it is true, the work of
+** updating the change-counter is omitted for the current transaction.
+**
+** This mechanism means that when running in exclusive mode, a connection
+** need only update the change-counter once, for the first transaction
+** committed.
+**
+** setSuper
+**
+** When PagerCommitPhaseOne() is called to commit a transaction, it may
+** (or may not) specify a super-journal name to be written into the
+** journal file before it is synced to disk.
+**
+** Whether or not a journal file contains a super-journal pointer affects
+** the way in which the journal file is finalized after the transaction is
+** committed or rolled back when running in "journal_mode=PERSIST" mode.
+** If a journal file does not contain a super-journal pointer, it is
+** finalized by overwriting the first journal header with zeroes. If
+** it does contain a super-journal pointer the journal file is finalized
+** by truncating it to zero bytes, just as if the connection were
+** running in "journal_mode=truncate" mode.
+**
+** Journal files that contain super-journal pointers cannot be finalized
+** simply by overwriting the first journal-header with zeroes, as the
+** super-journal pointer could interfere with hot-journal rollback of any
+** subsequently interrupted transaction that reuses the journal file.
+**
+** The flag is cleared as soon as the journal file is finalized (either
+** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
+** journal file from being successfully finalized, the setSuper flag
+** is cleared anyway (and the pager will move to ERROR state).
+**
+** doNotSpill
+**
+** This variables control the behavior of cache-spills (calls made by
+** the pcache module to the pagerStress() routine to write cached data
+** to the file-system in order to free up memory).
+**
+** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
+** writing to the database from pagerStress() is disabled altogether.
+** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
+** comes up during savepoint rollback that requires the pcache module
+** to allocate a new page to prevent the journal file from being written
+** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
+** case is a user preference.
+**
+** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
+** pagerStress() is permitted, but syncing the journal file is not.
+** This flag is set by sqlite3PagerWrite() when the file-system sector-size
+** is larger than the database page-size in order to prevent a journal sync
+** from happening in between the journalling of two pages on the same sector.
+**
+** subjInMemory
+**
+** This is a boolean variable. If true, then any required sub-journal
+** is opened as an in-memory journal file. If false, then in-memory
+** sub-journals are only used for in-memory pager files.
+**
+** This variable is updated by the upper layer each time a new
+** write-transaction is opened.
+**
+** dbSize, dbOrigSize, dbFileSize
+**
+** Variable dbSize is set to the number of pages in the database file.
+** It is valid in PAGER_READER and higher states (all states except for
+** OPEN and ERROR).
+**
+** dbSize is set based on the size of the database file, which may be
+** larger than the size of the database (the value stored at offset
+** 28 of the database header by the btree). If the size of the file
+** is not an integer multiple of the page-size, the value stored in
+** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
+** Except, any file that is greater than 0 bytes in size is considered
+** to have at least one page. (i.e. a 1KB file with 2K page-size leads
+** to dbSize==1).
+**
+** During a write-transaction, if pages with page-numbers greater than
+** dbSize are modified in the cache, dbSize is updated accordingly.
+** Similarly, if the database is truncated using PagerTruncateImage(),
+** dbSize is updated.
+**
+** Variables dbOrigSize and dbFileSize are valid in states
+** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
+** variable at the start of the transaction. It is used during rollback,
+** and to determine whether or not pages need to be journalled before
+** being modified.
+**
+** Throughout a write-transaction, dbFileSize contains the size of
+** the file on disk in pages. It is set to a copy of dbSize when the
+** write-transaction is first opened, and updated when VFS calls are made
+** to write or truncate the database file on disk.
+**
+** The only reason the dbFileSize variable is required is to suppress
+** unnecessary calls to xTruncate() after committing a transaction. If,
+** when a transaction is committed, the dbFileSize variable indicates
+** that the database file is larger than the database image (Pager.dbSize),
+** pager_truncate() is called. The pager_truncate() call uses xFilesize()
+** to measure the database file on disk, and then truncates it if required.
+** dbFileSize is not used when rolling back a transaction. In this case
+** pager_truncate() is called unconditionally (which means there may be
+** a call to xFilesize() that is not strictly required). In either case,
+** pager_truncate() may cause the file to become smaller or larger.
+**
+** dbHintSize
+**
+** The dbHintSize variable is used to limit the number of calls made to
+** the VFS xFileControl(FCNTL_SIZE_HINT) method.
+**
+** dbHintSize is set to a copy of the dbSize variable when a
+** write-transaction is opened (at the same time as dbFileSize and
+** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
+** dbHintSize is increased to the number of pages that correspond to the
+** size-hint passed to the method call. See pager_write_pagelist() for
+** details.
+**
+** errCode
+**
+** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
+** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
+** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
+** sub-codes.
+**
+** syncFlags, walSyncFlags
+**
+** syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).
+** syncFlags is used for rollback mode. walSyncFlags is used for WAL mode
+** and contains the flags used to sync the checkpoint operations in the
+** lower two bits, and sync flags used for transaction commits in the WAL
+** file in bits 0x04 and 0x08. In other words, to get the correct sync flags
+** for checkpoint operations, use (walSyncFlags&0x03) and to get the correct
+** sync flags for transaction commit, use ((walSyncFlags>>2)&0x03). Note
+** that with synchronous=NORMAL in WAL mode, transaction commit is not synced
+** meaning that the 0x04 and 0x08 bits are both zero.
+*/
+struct Pager {
+ sqlite3_vfs *pVfs; /* OS functions to use for IO */
+ u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
+ u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
+ u8 useJournal; /* Use a rollback journal on this file */
+ u8 noSync; /* Do not sync the journal if true */
+ u8 fullSync; /* Do extra syncs of the journal for robustness */
+ u8 extraSync; /* sync directory after journal delete */
+ u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
+ u8 walSyncFlags; /* See description above */
+ u8 tempFile; /* zFilename is a temporary or immutable file */
+ u8 noLock; /* Do not lock (except in WAL mode) */
+ u8 readOnly; /* True for a read-only database */
+ u8 memDb; /* True to inhibit all file I/O */
+
+ /**************************************************************************
+ ** The following block contains those class members that change during
+ ** routine operation. Class members not in this block are either fixed
+ ** when the pager is first created or else only change when there is a
+ ** significant mode change (such as changing the page_size, locking_mode,
+ ** or the journal_mode). From another view, these class members describe
+ ** the "state" of the pager, while other class members describe the
+ ** "configuration" of the pager.
+ */
+ u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
+ u8 eLock; /* Current lock held on database file */
+ u8 changeCountDone; /* Set after incrementing the change-counter */
+ u8 setSuper; /* Super-jrnl name is written into jrnl */
+ u8 doNotSpill; /* Do not spill the cache when non-zero */
+ u8 subjInMemory; /* True to use in-memory sub-journals */
+ u8 bUseFetch; /* True to use xFetch() */
+ u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
+ Pgno dbSize; /* Number of pages in the database */
+ Pgno dbOrigSize; /* dbSize before the current transaction */
+ Pgno dbFileSize; /* Number of pages in the database file */
+ Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
+ int errCode; /* One of several kinds of errors */
+ int nRec; /* Pages journalled since last j-header written */
+ u32 cksumInit; /* Quasi-random value added to every checksum */
+ u32 nSubRec; /* Number of records written to sub-journal */
+ Bitvec *pInJournal; /* One bit for each page in the database file */
+ sqlite3_file *fd; /* File descriptor for database */
+ sqlite3_file *jfd; /* File descriptor for main journal */
+ sqlite3_file *sjfd; /* File descriptor for sub-journal */
+ i64 journalOff; /* Current write offset in the journal file */
+ i64 journalHdr; /* Byte offset to previous journal header */
+ sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
+ PagerSavepoint *aSavepoint; /* Array of active savepoints */
+ int nSavepoint; /* Number of elements in aSavepoint[] */
+ u32 iDataVersion; /* Changes whenever database content changes */
+ char dbFileVers[16]; /* Changes whenever database file changes */
+
+ int nMmapOut; /* Number of mmap pages currently outstanding */
+ sqlite3_int64 szMmap; /* Desired maximum mmap size */
+ PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
+ /*
+ ** End of the routinely-changing class members
+ ***************************************************************************/
+
+ u16 nExtra; /* Add this many bytes to each in-memory page */
+ i16 nReserve; /* Number of unused bytes at end of each page */
+ u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
+ u32 sectorSize; /* Assumed sector size during rollback */
+ int pageSize; /* Number of bytes in a page */
+ Pgno mxPgno; /* Maximum allowed size of the database */
+ i64 journalSizeLimit; /* Size limit for persistent journal files */
+ char *zFilename; /* Name of the database file */
+ char *zJournal; /* Name of the journal file */
+ int (*xBusyHandler)(void*); /* Function to call when busy */
+ void *pBusyHandlerArg; /* Context argument for xBusyHandler */
+ int aStat[4]; /* Total cache hits, misses, writes, spills */
+#ifdef SQLITE_TEST
+ int nRead; /* Database pages read */
+#endif
+ void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
+ int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
+ char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
+ PCache *pPCache; /* Pointer to page cache object */
+#ifndef SQLITE_OMIT_WAL
+ Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
+ char *zWal; /* File name for write-ahead log */
+#endif
+};
+
+/*
+** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
+** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
+** or CACHE_WRITE to sqlite3_db_status().
+*/
+#define PAGER_STAT_HIT 0
+#define PAGER_STAT_MISS 1
+#define PAGER_STAT_WRITE 2
+#define PAGER_STAT_SPILL 3
+
+/*
+** The following global variables hold counters used for
+** testing purposes only. These variables do not exist in
+** a non-testing build. These variables are not thread-safe.
+*/
+#ifdef SQLITE_TEST
+SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
+SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
+SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
+# define PAGER_INCR(v) v++
+#else
+# define PAGER_INCR(v)
+#endif
+
+
+
+/*
+** Journal files begin with the following magic string. The data
+** was obtained from /dev/random. It is used only as a sanity check.
+**
+** Since version 2.8.0, the journal format contains additional sanity
+** checking information. If the power fails while the journal is being
+** written, semi-random garbage data might appear in the journal
+** file after power is restored. If an attempt is then made
+** to roll the journal back, the database could be corrupted. The additional
+** sanity checking data is an attempt to discover the garbage in the
+** journal and ignore it.
+**
+** The sanity checking information for the new journal format consists
+** of a 32-bit checksum on each page of data. The checksum covers both
+** the page number and the pPager->pageSize bytes of data for the page.
+** This cksum is initialized to a 32-bit random value that appears in the
+** journal file right after the header. The random initializer is important,
+** because garbage data that appears at the end of a journal is likely
+** data that was once in other files that have now been deleted. If the
+** garbage data came from an obsolete journal file, the checksums might
+** be correct. But by initializing the checksum to random value which
+** is different for every journal, we minimize that risk.
+*/
+static const unsigned char aJournalMagic[] = {
+ 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
+};
+
+/*
+** The size of the of each page record in the journal is given by
+** the following macro.
+*/
+#define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
+
+/*
+** The journal header size for this pager. This is usually the same
+** size as a single disk sector. See also setSectorSize().
+*/
+#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
+
+/*
+** The macro MEMDB is true if we are dealing with an in-memory database.
+** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
+** the value of MEMDB will be a constant and the compiler will optimize
+** out code that would never execute.
+*/
+#ifdef SQLITE_OMIT_MEMORYDB
+# define MEMDB 0
+#else
+# define MEMDB pPager->memDb
+#endif
+
+/*
+** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
+** interfaces to access the database using memory-mapped I/O.
+*/
+#if SQLITE_MAX_MMAP_SIZE>0
+# define USEFETCH(x) ((x)->bUseFetch)
+#else
+# define USEFETCH(x) 0
+#endif
+
+/*
+** The argument to this macro is a file descriptor (type sqlite3_file*).
+** Return 0 if it is not open, or non-zero (but not 1) if it is.
+**
+** This is so that expressions can be written as:
+**
+** if( isOpen(pPager->jfd) ){ ...
+**
+** instead of
+**
+** if( pPager->jfd->pMethods ){ ...
+*/
+#define isOpen(pFd) ((pFd)->pMethods!=0)
+
+#ifdef SQLITE_DIRECT_OVERFLOW_READ
+/*
+** Return true if page pgno can be read directly from the database file
+** by the b-tree layer. This is the case if:
+**
+** * the database file is open,
+** * there are no dirty pages in the cache, and
+** * the desired page is not currently in the wal file.
+*/
+SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){
+ if( pPager->fd->pMethods==0 ) return 0;
+ if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0;
+#ifndef SQLITE_OMIT_WAL
+ if( pPager->pWal ){
+ u32 iRead = 0;
+ int rc;
+ rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
+ return (rc==SQLITE_OK && iRead==0);
+ }
+#endif
+ return 1;
+}
+#endif
+
+#ifndef SQLITE_OMIT_WAL
+# define pagerUseWal(x) ((x)->pWal!=0)
+#else
+# define pagerUseWal(x) 0
+# define pagerRollbackWal(x) 0
+# define pagerWalFrames(v,w,x,y) 0
+# define pagerOpenWalIfPresent(z) SQLITE_OK
+# define pagerBeginReadTransaction(z) SQLITE_OK
+#endif
+
+#ifndef NDEBUG
+/*
+** Usage:
+**
+** assert( assert_pager_state(pPager) );
+**
+** This function runs many asserts to try to find inconsistencies in
+** the internal state of the Pager object.
+*/
+static int assert_pager_state(Pager *p){
+ Pager *pPager = p;
+
+ /* State must be valid. */
+ assert( p->eState==PAGER_OPEN
+ || p->eState==PAGER_READER
+ || p->eState==PAGER_WRITER_LOCKED
+ || p->eState==PAGER_WRITER_CACHEMOD
+ || p->eState==PAGER_WRITER_DBMOD
+ || p->eState==PAGER_WRITER_FINISHED
+ || p->eState==PAGER_ERROR
+ );
+
+ /* Regardless of the current state, a temp-file connection always behaves
+ ** as if it has an exclusive lock on the database file. It never updates
+ ** the change-counter field, so the changeCountDone flag is always set.
+ */
+ assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
+ assert( p->tempFile==0 || pPager->changeCountDone );
+
+ /* If the useJournal flag is clear, the journal-mode must be "OFF".
+ ** And if the journal-mode is "OFF", the journal file must not be open.
+ */
+ assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
+ assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
+
+ /* Check that MEMDB implies noSync. And an in-memory journal. Since
+ ** this means an in-memory pager performs no IO at all, it cannot encounter
+ ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
+ ** a journal file. (although the in-memory journal implementation may
+ ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
+ ** is therefore not possible for an in-memory pager to enter the ERROR
+ ** state.
+ */
+ if( MEMDB ){
+ assert( !isOpen(p->fd) );
+ assert( p->noSync );
+ assert( p->journalMode==PAGER_JOURNALMODE_OFF
+ || p->journalMode==PAGER_JOURNALMODE_MEMORY
+ );
+ assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
+ assert( pagerUseWal(p)==0 );
+ }
+
+ /* If changeCountDone is set, a RESERVED lock or greater must be held
+ ** on the file.
+ */
+ assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
+ assert( p->eLock!=PENDING_LOCK );
+
+ switch( p->eState ){
+ case PAGER_OPEN:
+ assert( !MEMDB );
+ assert( pPager->errCode==SQLITE_OK );
+ assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
+ break;
+
+ case PAGER_READER:
+ assert( pPager->errCode==SQLITE_OK );
+ assert( p->eLock!=UNKNOWN_LOCK );
+ assert( p->eLock>=SHARED_LOCK );
+ break;
+
+ case PAGER_WRITER_LOCKED:
+ assert( p->eLock!=UNKNOWN_LOCK );
+ assert( pPager->errCode==SQLITE_OK );
+ if( !pagerUseWal(pPager) ){
+ assert( p->eLock>=RESERVED_LOCK );
+ }
+ assert( pPager->dbSize==pPager->dbOrigSize );
+ assert( pPager->dbOrigSize==pPager->dbFileSize );
+ assert( pPager->dbOrigSize==pPager->dbHintSize );
+ assert( pPager->setSuper==0 );
+ break;
+
+ case PAGER_WRITER_CACHEMOD:
+ assert( p->eLock!=UNKNOWN_LOCK );
+ assert( pPager->errCode==SQLITE_OK );
+ if( !pagerUseWal(pPager) ){
+ /* It is possible that if journal_mode=wal here that neither the
+ ** journal file nor the WAL file are open. This happens during
+ ** a rollback transaction that switches from journal_mode=off
+ ** to journal_mode=wal.
+ */
+ assert( p->eLock>=RESERVED_LOCK );
+ assert( isOpen(p->jfd)
+ || p->journalMode==PAGER_JOURNALMODE_OFF
+ || p->journalMode==PAGER_JOURNALMODE_WAL
+ );
+ }
+ assert( pPager->dbOrigSize==pPager->dbFileSize );
+ assert( pPager->dbOrigSize==pPager->dbHintSize );
+ break;
+
+ case PAGER_WRITER_DBMOD:
+ assert( p->eLock==EXCLUSIVE_LOCK );
+ assert( pPager->errCode==SQLITE_OK );
+ assert( !pagerUseWal(pPager) );
+ assert( p->eLock>=EXCLUSIVE_LOCK );
+ assert( isOpen(p->jfd)
+ || p->journalMode==PAGER_JOURNALMODE_OFF
+ || p->journalMode==PAGER_JOURNALMODE_WAL
+ || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
+ );
+ assert( pPager->dbOrigSize<=pPager->dbHintSize );
+ break;
+
+ case PAGER_WRITER_FINISHED:
+ assert( p->eLock==EXCLUSIVE_LOCK );
+ assert( pPager->errCode==SQLITE_OK );
+ assert( !pagerUseWal(pPager) );
+ assert( isOpen(p->jfd)
+ || p->journalMode==PAGER_JOURNALMODE_OFF
+ || p->journalMode==PAGER_JOURNALMODE_WAL
+ || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
+ );
+ break;
+
+ case PAGER_ERROR:
+ /* There must be at least one outstanding reference to the pager if
+ ** in ERROR state. Otherwise the pager should have already dropped
+ ** back to OPEN state.
+ */
+ assert( pPager->errCode!=SQLITE_OK );
+ assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
+ break;
+ }
+
+ return 1;
+}
+#endif /* ifndef NDEBUG */
+
+#ifdef SQLITE_DEBUG
+/*
+** Return a pointer to a human readable string in a static buffer
+** containing the state of the Pager object passed as an argument. This
+** is intended to be used within debuggers. For example, as an alternative
+** to "print *pPager" in gdb:
+**
+** (gdb) printf "%s", print_pager_state(pPager)
+**
+** This routine has external linkage in order to suppress compiler warnings
+** about an unused function. It is enclosed within SQLITE_DEBUG and so does
+** not appear in normal builds.
+*/
+char *print_pager_state(Pager *p){
+ static char zRet[1024];
+
+ sqlite3_snprintf(1024, zRet,
+ "Filename: %s\n"
+ "State: %s errCode=%d\n"
+ "Lock: %s\n"
+ "Locking mode: locking_mode=%s\n"
+ "Journal mode: journal_mode=%s\n"
+ "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
+ "Journal: journalOff=%lld journalHdr=%lld\n"
+ "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
+ , p->zFilename
+ , p->eState==PAGER_OPEN ? "OPEN" :
+ p->eState==PAGER_READER ? "READER" :
+ p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
+ p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
+ p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
+ p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
+ p->eState==PAGER_ERROR ? "ERROR" : "?error?"
+ , (int)p->errCode
+ , p->eLock==NO_LOCK ? "NO_LOCK" :
+ p->eLock==RESERVED_LOCK ? "RESERVED" :
+ p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
+ p->eLock==SHARED_LOCK ? "SHARED" :
+ p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
+ , p->exclusiveMode ? "exclusive" : "normal"
+ , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
+ p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
+ p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
+ p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
+ p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
+ p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
+ , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
+ , p->journalOff, p->journalHdr
+ , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
+ );
+
+ return zRet;
+}
+#endif
+
+/* Forward references to the various page getters */
+static int getPageNormal(Pager*,Pgno,DbPage**,int);
+static int getPageError(Pager*,Pgno,DbPage**,int);
+#if SQLITE_MAX_MMAP_SIZE>0
+static int getPageMMap(Pager*,Pgno,DbPage**,int);
+#endif
+
+/*
+** Set the Pager.xGet method for the appropriate routine used to fetch
+** content from the pager.
+*/
+static void setGetterMethod(Pager *pPager){
+ if( pPager->errCode ){
+ pPager->xGet = getPageError;
+#if SQLITE_MAX_MMAP_SIZE>0
+ }else if( USEFETCH(pPager) ){
+ pPager->xGet = getPageMMap;
+#endif /* SQLITE_MAX_MMAP_SIZE>0 */
+ }else{
+ pPager->xGet = getPageNormal;
+ }
+}
+
+/*
+** Return true if it is necessary to write page *pPg into the sub-journal.
+** A page needs to be written into the sub-journal if there exists one
+** or more open savepoints for which:
+**
+** * The page-number is less than or equal to PagerSavepoint.nOrig, and
+** * The bit corresponding to the page-number is not set in
+** PagerSavepoint.pInSavepoint.
+*/
+static int subjRequiresPage(PgHdr *pPg){
+ Pager *pPager = pPg->pPager;
+ PagerSavepoint *p;
+ Pgno pgno = pPg->pgno;
+ int i;
+ for(i=0; i<pPager->nSavepoint; i++){
+ p = &pPager->aSavepoint[i];
+ if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
+ return 1;
+ }
+ }
+ return 0;
+}
+
+#ifdef SQLITE_DEBUG
+/*
+** Return true if the page is already in the journal file.
+*/
+static int pageInJournal(Pager *pPager, PgHdr *pPg){
+ return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
+}
+#endif
+
+/*
+** Read a 32-bit integer from the given file descriptor. Store the integer
+** that is read in *pRes. Return SQLITE_OK if everything worked, or an
+** error code is something goes wrong.
+**
+** All values are stored on disk as big-endian.
+*/
+static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
+ unsigned char ac[4];
+ int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
+ if( rc==SQLITE_OK ){
+ *pRes = sqlite3Get4byte(ac);
+ }
+ return rc;
+}
+
+/*
+** Write a 32-bit integer into a string buffer in big-endian byte order.
+*/
+#define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
+
+
+/*
+** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
+** on success or an error code is something goes wrong.
+*/
+static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
+ char ac[4];
+ put32bits(ac, val);
+ return sqlite3OsWrite(fd, ac, 4, offset);
+}
+
+/*
+** Unlock the database file to level eLock, which must be either NO_LOCK
+** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
+** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
+**
+** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
+** called, do not modify it. See the comment above the #define of
+** UNKNOWN_LOCK for an explanation of this.
+*/
+static int pagerUnlockDb(Pager *pPager, int eLock){
+ int rc = SQLITE_OK;
+
+ assert( !pPager->exclusiveMode || pPager->eLock==eLock );
+ assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
+ assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
+ if( isOpen(pPager->fd) ){
+ assert( pPager->eLock>=eLock );
+ rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
+ if( pPager->eLock!=UNKNOWN_LOCK ){
+ pPager->eLock = (u8)eLock;
+ }
+ IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
+ }
+ pPager->changeCountDone = pPager->tempFile; /* ticket fb3b3024ea238d5c */
+ return rc;
+}
+
+/*
+** Lock the database file to level eLock, which must be either SHARED_LOCK,
+** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
+** Pager.eLock variable to the new locking state.
+**
+** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
+** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
+** See the comment above the #define of UNKNOWN_LOCK for an explanation
+** of this.
+*/
+static int pagerLockDb(Pager *pPager, int eLock){
+ int rc = SQLITE_OK;
+
+ assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
+ if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
+ rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
+ if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
+ pPager->eLock = (u8)eLock;
+ IOTRACE(("LOCK %p %d\n", pPager, eLock))
+ }
+ }
+ return rc;
+}
+
+/*
+** This function determines whether or not the atomic-write or
+** atomic-batch-write optimizations can be used with this pager. The
+** atomic-write optimization can be used if:
+**
+** (a) the value returned by OsDeviceCharacteristics() indicates that
+** a database page may be written atomically, and
+** (b) the value returned by OsSectorSize() is less than or equal
+** to the page size.
+**
+** If it can be used, then the value returned is the size of the journal
+** file when it contains rollback data for exactly one page.
+**
+** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
+** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
+** returned in this case.
+**
+** If neither optimization can be used, 0 is returned.
+*/
+static int jrnlBufferSize(Pager *pPager){
+ assert( !MEMDB );
+
+#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
+ || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
+ int dc; /* Device characteristics */
+
+ assert( isOpen(pPager->fd) );
+ dc = sqlite3OsDeviceCharacteristics(pPager->fd);
+#else
+ UNUSED_PARAMETER(pPager);
+#endif
+
+#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
+ if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){
+ return -1;
+ }
+#endif
+
+#ifdef SQLITE_ENABLE_ATOMIC_WRITE
+ {
+ int nSector = pPager->sectorSize;
+ int szPage = pPager->pageSize;
+
+ assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
+ assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
+ if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
+ return 0;
+ }
+ }
+
+ return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
+#endif
+
+ return 0;
+}
+
+/*
+** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
+** on the cache using a hash function. This is used for testing
+** and debugging only.
+*/
+#ifdef SQLITE_CHECK_PAGES
+/*
+** Return a 32-bit hash of the page data for pPage.
+*/
+static u32 pager_datahash(int nByte, unsigned char *pData){
+ u32 hash = 0;
+ int i;
+ for(i=0; i<nByte; i++){
+ hash = (hash*1039) + pData[i];
+ }
+ return hash;
+}
+static u32 pager_pagehash(PgHdr *pPage){
+ return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
+}
+static void pager_set_pagehash(PgHdr *pPage){
+ pPage->pageHash = pager_pagehash(pPage);
+}
+
+/*
+** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
+** is defined, and NDEBUG is not defined, an assert() statement checks
+** that the page is either dirty or still matches the calculated page-hash.
+*/
+#define CHECK_PAGE(x) checkPage(x)
+static void checkPage(PgHdr *pPg){
+ Pager *pPager = pPg->pPager;
+ assert( pPager->eState!=PAGER_ERROR );
+ assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
+}
+
+#else
+#define pager_datahash(X,Y) 0
+#define pager_pagehash(X) 0
+#define pager_set_pagehash(X)
+#define CHECK_PAGE(x)
+#endif /* SQLITE_CHECK_PAGES */
+
+/*
+** When this is called the journal file for pager pPager must be open.
+** This function attempts to read a super-journal file name from the
+** end of the file and, if successful, copies it into memory supplied
+** by the caller. See comments above writeSuperJournal() for the format
+** used to store a super-journal file name at the end of a journal file.
+**
+** zSuper must point to a buffer of at least nSuper bytes allocated by
+** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
+** enough space to write the super-journal name). If the super-journal
+** name in the journal is longer than nSuper bytes (including a
+** nul-terminator), then this is handled as if no super-journal name
+** were present in the journal.
+**
+** If a super-journal file name is present at the end of the journal
+** file, then it is copied into the buffer pointed to by zSuper. A
+** nul-terminator byte is appended to the buffer following the
+** super-journal file name.
+**
+** If it is determined that no super-journal file name is present
+** zSuper[0] is set to 0 and SQLITE_OK returned.
+**
+** If an error occurs while reading from the journal file, an SQLite
+** error code is returned.
+*/
+static int readSuperJournal(sqlite3_file *pJrnl, char *zSuper, u32 nSuper){
+ int rc; /* Return code */
+ u32 len; /* Length in bytes of super-journal name */
+ i64 szJ; /* Total size in bytes of journal file pJrnl */
+ u32 cksum; /* MJ checksum value read from journal */
+ u32 u; /* Unsigned loop counter */
+ unsigned char aMagic[8]; /* A buffer to hold the magic header */
+ zSuper[0] = '\0';
+
+ if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
+ || szJ<16
+ || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
+ || len>=nSuper
+ || len>szJ-16
+ || len==0
+ || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
+ || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
+ || memcmp(aMagic, aJournalMagic, 8)
+ || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zSuper, len, szJ-16-len))
+ ){
+ return rc;
+ }
+
+ /* See if the checksum matches the super-journal name */
+ for(u=0; u<len; u++){
+ cksum -= zSuper[u];
+ }
+ if( cksum ){
+ /* If the checksum doesn't add up, then one or more of the disk sectors
+ ** containing the super-journal filename is corrupted. This means
+ ** definitely roll back, so just return SQLITE_OK and report a (nul)
+ ** super-journal filename.
+ */
+ len = 0;
+ }
+ zSuper[len] = '\0';
+ zSuper[len+1] = '\0';
+
+ return SQLITE_OK;
+}
+
+/*
+** Return the offset of the sector boundary at or immediately
+** following the value in pPager->journalOff, assuming a sector
+** size of pPager->sectorSize bytes.
+**
+** i.e for a sector size of 512:
+**
+** Pager.journalOff Return value
+** ---------------------------------------
+** 0 0
+** 512 512
+** 100 512
+** 2000 2048
+**
+*/
+static i64 journalHdrOffset(Pager *pPager){
+ i64 offset = 0;
+ i64 c = pPager->journalOff;
+ if( c ){
+ offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
+ }
+ assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
+ assert( offset>=c );
+ assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
+ return offset;
+}
+
+/*
+** The journal file must be open when this function is called.
+**
+** This function is a no-op if the journal file has not been written to
+** within the current transaction (i.e. if Pager.journalOff==0).
+**
+** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
+** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
+** zero the 28-byte header at the start of the journal file. In either case,
+** if the pager is not in no-sync mode, sync the journal file immediately
+** after writing or truncating it.
+**
+** If Pager.journalSizeLimit is set to a positive, non-zero value, and
+** following the truncation or zeroing described above the size of the
+** journal file in bytes is larger than this value, then truncate the
+** journal file to Pager.journalSizeLimit bytes. The journal file does
+** not need to be synced following this operation.
+**
+** If an IO error occurs, abandon processing and return the IO error code.
+** Otherwise, return SQLITE_OK.
+*/
+static int zeroJournalHdr(Pager *pPager, int doTruncate){
+ int rc = SQLITE_OK; /* Return code */
+ assert( isOpen(pPager->jfd) );
+ assert( !sqlite3JournalIsInMemory(pPager->jfd) );
+ if( pPager->journalOff ){
+ const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
+
+ IOTRACE(("JZEROHDR %p\n", pPager))
+ if( doTruncate || iLimit==0 ){
+ rc = sqlite3OsTruncate(pPager->jfd, 0);
+ }else{
+ static const char zeroHdr[28] = {0};
+ rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
+ }
+ if( rc==SQLITE_OK && !pPager->noSync ){
+ rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
+ }
+
+ /* At this point the transaction is committed but the write lock
+ ** is still held on the file. If there is a size limit configured for
+ ** the persistent journal and the journal file currently consumes more
+ ** space than that limit allows for, truncate it now. There is no need
+ ** to sync the file following this operation.
+ */
+ if( rc==SQLITE_OK && iLimit>0 ){
+ i64 sz;
+ rc = sqlite3OsFileSize(pPager->jfd, &sz);
+ if( rc==SQLITE_OK && sz>iLimit ){
+ rc = sqlite3OsTruncate(pPager->jfd, iLimit);
+ }
+ }
+ }
+ return rc;
+}
+
+/*
+** The journal file must be open when this routine is called. A journal
+** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
+** current location.
+**
+** The format for the journal header is as follows:
+** - 8 bytes: Magic identifying journal format.
+** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
+** - 4 bytes: Random number used for page hash.
+** - 4 bytes: Initial database page count.
+** - 4 bytes: Sector size used by the process that wrote this journal.
+** - 4 bytes: Database page size.
+**
+** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
+*/
+static int writeJournalHdr(Pager *pPager){
+ int rc = SQLITE_OK; /* Return code */
+ char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
+ u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
+ u32 nWrite; /* Bytes of header sector written */
+ int ii; /* Loop counter */
+
+ assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
+
+ if( nHeader>JOURNAL_HDR_SZ(pPager) ){
+ nHeader = JOURNAL_HDR_SZ(pPager);
+ }
+
+ /* If there are active savepoints and any of them were created
+ ** since the most recent journal header was written, update the
+ ** PagerSavepoint.iHdrOffset fields now.
+ */
+ for(ii=0; ii<pPager->nSavepoint; ii++){
+ if( pPager->aSavepoint[ii].iHdrOffset==0 ){
+ pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
+ }
+ }
+
+ pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
+
+ /*
+ ** Write the nRec Field - the number of page records that follow this
+ ** journal header. Normally, zero is written to this value at this time.
+ ** After the records are added to the journal (and the journal synced,
+ ** if in full-sync mode), the zero is overwritten with the true number
+ ** of records (see syncJournal()).
+ **
+ ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
+ ** reading the journal this value tells SQLite to assume that the
+ ** rest of the journal file contains valid page records. This assumption
+ ** is dangerous, as if a failure occurred whilst writing to the journal
+ ** file it may contain some garbage data. There are two scenarios
+ ** where this risk can be ignored:
+ **
+ ** * When the pager is in no-sync mode. Corruption can follow a
+ ** power failure in this case anyway.
+ **
+ ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
+ ** that garbage data is never appended to the journal file.
+ */
+ assert( isOpen(pPager->fd) || pPager->noSync );
+ if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
+ || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
+ ){
+ memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
+ put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
+ }else{
+ memset(zHeader, 0, sizeof(aJournalMagic)+4);
+ }
+
+ /* The random check-hash initializer */
+ sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
+ put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
+ /* The initial database size */
+ put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
+ /* The assumed sector size for this process */
+ put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
+
+ /* The page size */
+ put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
+
+ /* Initializing the tail of the buffer is not necessary. Everything
+ ** works find if the following memset() is omitted. But initializing
+ ** the memory prevents valgrind from complaining, so we are willing to
+ ** take the performance hit.
+ */
+ memset(&zHeader[sizeof(aJournalMagic)+20], 0,
+ nHeader-(sizeof(aJournalMagic)+20));
+
+ /* In theory, it is only necessary to write the 28 bytes that the
+ ** journal header consumes to the journal file here. Then increment the
+ ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
+ ** record is written to the following sector (leaving a gap in the file
+ ** that will be implicitly filled in by the OS).
+ **
+ ** However it has been discovered that on some systems this pattern can
+ ** be significantly slower than contiguously writing data to the file,
+ ** even if that means explicitly writing data to the block of
+ ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
+ ** is done.
+ **
+ ** The loop is required here in case the sector-size is larger than the
+ ** database page size. Since the zHeader buffer is only Pager.pageSize
+ ** bytes in size, more than one call to sqlite3OsWrite() may be required
+ ** to populate the entire journal header sector.
+ */
+ for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
+ IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
+ rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
+ assert( pPager->journalHdr <= pPager->journalOff );
+ pPager->journalOff += nHeader;
+ }
+
+ return rc;
+}
+
+/*
+** The journal file must be open when this is called. A journal header file
+** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
+** file. The current location in the journal file is given by
+** pPager->journalOff. See comments above function writeJournalHdr() for
+** a description of the journal header format.
+**
+** If the header is read successfully, *pNRec is set to the number of
+** page records following this header and *pDbSize is set to the size of the
+** database before the transaction began, in pages. Also, pPager->cksumInit
+** is set to the value read from the journal header. SQLITE_OK is returned
+** in this case.
+**
+** If the journal header file appears to be corrupted, SQLITE_DONE is
+** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
+** cannot be read from the journal file an error code is returned.
+*/
+static int readJournalHdr(
+ Pager *pPager, /* Pager object */
+ int isHot,
+ i64 journalSize, /* Size of the open journal file in bytes */
+ u32 *pNRec, /* OUT: Value read from the nRec field */
+ u32 *pDbSize /* OUT: Value of original database size field */
+){
+ int rc; /* Return code */
+ unsigned char aMagic[8]; /* A buffer to hold the magic header */
+ i64 iHdrOff; /* Offset of journal header being read */
+
+ assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
+
+ /* Advance Pager.journalOff to the start of the next sector. If the
+ ** journal file is too small for there to be a header stored at this
+ ** point, return SQLITE_DONE.
+ */
+ pPager->journalOff = journalHdrOffset(pPager);
+ if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
+ return SQLITE_DONE;
+ }
+ iHdrOff = pPager->journalOff;
+
+ /* Read in the first 8 bytes of the journal header. If they do not match
+ ** the magic string found at the start of each journal header, return
+ ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
+ ** proceed.
+ */
+ if( isHot || iHdrOff!=pPager->journalHdr ){
+ rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
+ if( rc ){
+ return rc;
+ }
+ if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
+ return SQLITE_DONE;
+ }
+ }
+
+ /* Read the first three 32-bit fields of the journal header: The nRec
+ ** field, the checksum-initializer and the database size at the start
+ ** of the transaction. Return an error code if anything goes wrong.
+ */
+ if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
+ || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
+ || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
+ ){
+ return rc;
+ }
+
+ if( pPager->journalOff==0 ){
+ u32 iPageSize; /* Page-size field of journal header */
+ u32 iSectorSize; /* Sector-size field of journal header */
+
+ /* Read the page-size and sector-size journal header fields. */
+ if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
+ || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
+ ){
+ return rc;
+ }
+
+ /* Versions of SQLite prior to 3.5.8 set the page-size field of the
+ ** journal header to zero. In this case, assume that the Pager.pageSize
+ ** variable is already set to the correct page size.
+ */
+ if( iPageSize==0 ){
+ iPageSize = pPager->pageSize;
+ }
+
+ /* Check that the values read from the page-size and sector-size fields
+ ** are within range. To be 'in range', both values need to be a power
+ ** of two greater than or equal to 512 or 32, and not greater than their
+ ** respective compile time maximum limits.
+ */
+ if( iPageSize<512 || iSectorSize<32
+ || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
+ || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
+ ){
+ /* If the either the page-size or sector-size in the journal-header is
+ ** invalid, then the process that wrote the journal-header must have
+ ** crashed before the header was synced. In this case stop reading
+ ** the journal file here.
+ */
+ return SQLITE_DONE;
+ }
+
+ /* Update the page-size to match the value read from the journal.
+ ** Use a testcase() macro to make sure that malloc failure within
+ ** PagerSetPagesize() is tested.
+ */
+ rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
+ testcase( rc!=SQLITE_OK );
+
+ /* Update the assumed sector-size to match the value used by
+ ** the process that created this journal. If this journal was
+ ** created by a process other than this one, then this routine
+ ** is being called from within pager_playback(). The local value
+ ** of Pager.sectorSize is restored at the end of that routine.
+ */
+ pPager->sectorSize = iSectorSize;
+ }
+
+ pPager->journalOff += JOURNAL_HDR_SZ(pPager);
+ return rc;
+}
+
+
+/*
+** Write the supplied super-journal name into the journal file for pager
+** pPager at the current location. The super-journal name must be the last
+** thing written to a journal file. If the pager is in full-sync mode, the
+** journal file descriptor is advanced to the next sector boundary before
+** anything is written. The format is:
+**
+** + 4 bytes: PAGER_MJ_PGNO.
+** + N bytes: super-journal filename in utf-8.
+** + 4 bytes: N (length of super-journal name in bytes, no nul-terminator).
+** + 4 bytes: super-journal name checksum.
+** + 8 bytes: aJournalMagic[].
+**
+** The super-journal page checksum is the sum of the bytes in thesuper-journal
+** name, where each byte is interpreted as a signed 8-bit integer.
+**
+** If zSuper is a NULL pointer (occurs for a single database transaction),
+** this call is a no-op.
+*/
+static int writeSuperJournal(Pager *pPager, const char *zSuper){
+ int rc; /* Return code */
+ int nSuper; /* Length of string zSuper */
+ i64 iHdrOff; /* Offset of header in journal file */
+ i64 jrnlSize; /* Size of journal file on disk */
+ u32 cksum = 0; /* Checksum of string zSuper */
+
+ assert( pPager->setSuper==0 );
+ assert( !pagerUseWal(pPager) );
+
+ if( !zSuper
+ || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
+ || !isOpen(pPager->jfd)
+ ){
+ return SQLITE_OK;
+ }
+ pPager->setSuper = 1;
+ assert( pPager->journalHdr <= pPager->journalOff );
+
+ /* Calculate the length in bytes and the checksum of zSuper */
+ for(nSuper=0; zSuper[nSuper]; nSuper++){
+ cksum += zSuper[nSuper];
+ }
+
+ /* If in full-sync mode, advance to the next disk sector before writing
+ ** the super-journal name. This is in case the previous page written to
+ ** the journal has already been synced.
+ */
+ if( pPager->fullSync ){
+ pPager->journalOff = journalHdrOffset(pPager);
+ }
+ iHdrOff = pPager->journalOff;
+
+ /* Write the super-journal data to the end of the journal file. If
+ ** an error occurs, return the error code to the caller.
+ */
+ if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
+ || (0 != (rc = sqlite3OsWrite(pPager->jfd, zSuper, nSuper, iHdrOff+4)))
+ || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper, nSuper)))
+ || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper+4, cksum)))
+ || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
+ iHdrOff+4+nSuper+8)))
+ ){
+ return rc;
+ }
+ pPager->journalOff += (nSuper+20);
+
+ /* If the pager is in peristent-journal mode, then the physical
+ ** journal-file may extend past the end of the super-journal name
+ ** and 8 bytes of magic data just written to the file. This is
+ ** dangerous because the code to rollback a hot-journal file
+ ** will not be able to find the super-journal name to determine
+ ** whether or not the journal is hot.
+ **
+ ** Easiest thing to do in this scenario is to truncate the journal
+ ** file to the required size.
+ */
+ if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
+ && jrnlSize>pPager->journalOff
+ ){
+ rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
+ }
+ return rc;
+}
+
+/*
+** Discard the entire contents of the in-memory page-cache.
+*/
+static void pager_reset(Pager *pPager){
+ pPager->iDataVersion++;
+ sqlite3BackupRestart(pPager->pBackup);
+ sqlite3PcacheClear(pPager->pPCache);
+}
+
+/*
+** Return the pPager->iDataVersion value
+*/
+SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
+ return pPager->iDataVersion;
+}
+
+/*
+** Free all structures in the Pager.aSavepoint[] array and set both
+** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
+** if it is open and the pager is not in exclusive mode.
+*/
+static void releaseAllSavepoints(Pager *pPager){
+ int ii; /* Iterator for looping through Pager.aSavepoint */
+ for(ii=0; ii<pPager->nSavepoint; ii++){
+ sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
+ }
+ if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
+ sqlite3OsClose(pPager->sjfd);
+ }
+ sqlite3_free(pPager->aSavepoint);
+ pPager->aSavepoint = 0;
+ pPager->nSavepoint = 0;
+ pPager->nSubRec = 0;
+}
+
+/*
+** Set the bit number pgno in the PagerSavepoint.pInSavepoint
+** bitvecs of all open savepoints. Return SQLITE_OK if successful
+** or SQLITE_NOMEM if a malloc failure occurs.
+*/
+static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
+ int ii; /* Loop counter */
+ int rc = SQLITE_OK; /* Result code */
+
+ for(ii=0; ii<pPager->nSavepoint; ii++){
+ PagerSavepoint *p = &pPager->aSavepoint[ii];
+ if( pgno<=p->nOrig ){
+ rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
+ testcase( rc==SQLITE_NOMEM );
+ assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
+ }
+ }
+ return rc;
+}
+
+/*
+** This function is a no-op if the pager is in exclusive mode and not
+** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
+** state.
+**
+** If the pager is not in exclusive-access mode, the database file is
+** completely unlocked. If the file is unlocked and the file-system does
+** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
+** closed (if it is open).
+**
+** If the pager is in ERROR state when this function is called, the
+** contents of the pager cache are discarded before switching back to
+** the OPEN state. Regardless of whether the pager is in exclusive-mode
+** or not, any journal file left in the file-system will be treated
+** as a hot-journal and rolled back the next time a read-transaction
+** is opened (by this or by any other connection).
+*/
+static void pager_unlock(Pager *pPager){
+
+ assert( pPager->eState==PAGER_READER
+ || pPager->eState==PAGER_OPEN
+ || pPager->eState==PAGER_ERROR
+ );
+
+ sqlite3BitvecDestroy(pPager->pInJournal);
+ pPager->pInJournal = 0;
+ releaseAllSavepoints(pPager);
+
+ if( pagerUseWal(pPager) ){
+ assert( !isOpen(pPager->jfd) );
+ sqlite3WalEndReadTransaction(pPager->pWal);
+ pPager->eState = PAGER_OPEN;
+ }else if( !pPager->exclusiveMode ){
+ int rc; /* Error code returned by pagerUnlockDb() */
+ int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
+
+ /* If the operating system support deletion of open files, then
+ ** close the journal file when dropping the database lock. Otherwise
+ ** another connection with journal_mode=delete might delete the file
+ ** out from under us.
+ */
+ assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
+ assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
+ assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
+ assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
+ assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
+ assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
+ if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
+ || 1!=(pPager->journalMode & 5)
+ ){
+ sqlite3OsClose(pPager->jfd);
+ }
+
+ /* If the pager is in the ERROR state and the call to unlock the database
+ ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
+ ** above the #define for UNKNOWN_LOCK for an explanation of why this
+ ** is necessary.
+ */
+ rc = pagerUnlockDb(pPager, NO_LOCK);
+ if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
+ pPager->eLock = UNKNOWN_LOCK;
+ }
+
+ /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
+ ** without clearing the error code. This is intentional - the error
+ ** code is cleared and the cache reset in the block below.
+ */
+ assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
+ pPager->eState = PAGER_OPEN;
+ }
+
+ /* If Pager.errCode is set, the contents of the pager cache cannot be
+ ** trusted. Now that there are no outstanding references to the pager,
+ ** it can safely move back to PAGER_OPEN state. This happens in both
+ ** normal and exclusive-locking mode.
+ */
+ assert( pPager->errCode==SQLITE_OK || !MEMDB );
+ if( pPager->errCode ){
+ if( pPager->tempFile==0 ){
+ pager_reset(pPager);
+ pPager->changeCountDone = 0;
+ pPager->eState = PAGER_OPEN;
+ }else{
+ pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
+ }
+ if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
+ pPager->errCode = SQLITE_OK;
+ setGetterMethod(pPager);
+ }
+
+ pPager->journalOff = 0;
+ pPager->journalHdr = 0;
+ pPager->setSuper = 0;
+}
+
+/*
+** This function is called whenever an IOERR or FULL error that requires
+** the pager to transition into the ERROR state may ahve occurred.
+** The first argument is a pointer to the pager structure, the second
+** the error-code about to be returned by a pager API function. The
+** value returned is a copy of the second argument to this function.
+**
+** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
+** IOERR sub-codes, the pager enters the ERROR state and the error code
+** is stored in Pager.errCode. While the pager remains in the ERROR state,
+** all major API calls on the Pager will immediately return Pager.errCode.
+**
+** The ERROR state indicates that the contents of the pager-cache
+** cannot be trusted. This state can be cleared by completely discarding
+** the contents of the pager-cache. If a transaction was active when
+** the persistent error occurred, then the rollback journal may need
+** to be replayed to restore the contents of the database file (as if
+** it were a hot-journal).
+*/
+static int pager_error(Pager *pPager, int rc){
+ int rc2 = rc & 0xff;
+ assert( rc==SQLITE_OK || !MEMDB );
+ assert(
+ pPager->errCode==SQLITE_FULL ||
+ pPager->errCode==SQLITE_OK ||
+ (pPager->errCode & 0xff)==SQLITE_IOERR
+ );
+ if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
+ pPager->errCode = rc;
+ pPager->eState = PAGER_ERROR;
+ setGetterMethod(pPager);
+ }
+ return rc;
+}
+
+static int pager_truncate(Pager *pPager, Pgno nPage);
+
+/*
+** The write transaction open on pPager is being committed (bCommit==1)
+** or rolled back (bCommit==0).
+**
+** Return TRUE if and only if all dirty pages should be flushed to disk.
+**
+** Rules:
+**
+** * For non-TEMP databases, always sync to disk. This is necessary
+** for transactions to be durable.
+**
+** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
+** file has been created already (via a spill on pagerStress()) and
+** when the number of dirty pages in memory exceeds 25% of the total
+** cache size.
+*/
+static int pagerFlushOnCommit(Pager *pPager, int bCommit){
+ if( pPager->tempFile==0 ) return 1;
+ if( !bCommit ) return 0;
+ if( !isOpen(pPager->fd) ) return 0;
+ return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
+}
+
+/*
+** This routine ends a transaction. A transaction is usually ended by
+** either a COMMIT or a ROLLBACK operation. This routine may be called
+** after rollback of a hot-journal, or if an error occurs while opening
+** the journal file or writing the very first journal-header of a
+** database transaction.
+**
+** This routine is never called in PAGER_ERROR state. If it is called
+** in PAGER_NONE or PAGER_SHARED state and the lock held is less
+** exclusive than a RESERVED lock, it is a no-op.
+**
+** Otherwise, any active savepoints are released.
+**
+** If the journal file is open, then it is "finalized". Once a journal
+** file has been finalized it is not possible to use it to roll back a
+** transaction. Nor will it be considered to be a hot-journal by this
+** or any other database connection. Exactly how a journal is finalized
+** depends on whether or not the pager is running in exclusive mode and
+** the current journal-mode (Pager.journalMode value), as follows:
+**
+** journalMode==MEMORY
+** Journal file descriptor is simply closed. This destroys an
+** in-memory journal.
+**
+** journalMode==TRUNCATE
+** Journal file is truncated to zero bytes in size.
+**
+** journalMode==PERSIST
+** The first 28 bytes of the journal file are zeroed. This invalidates
+** the first journal header in the file, and hence the entire journal
+** file. An invalid journal file cannot be rolled back.
+**
+** journalMode==DELETE
+** The journal file is closed and deleted using sqlite3OsDelete().
+**
+** If the pager is running in exclusive mode, this method of finalizing
+** the journal file is never used. Instead, if the journalMode is
+** DELETE and the pager is in exclusive mode, the method described under
+** journalMode==PERSIST is used instead.
+**
+** After the journal is finalized, the pager moves to PAGER_READER state.
+** If running in non-exclusive rollback mode, the lock on the file is
+** downgraded to a SHARED_LOCK.
+**
+** SQLITE_OK is returned if no error occurs. If an error occurs during
+** any of the IO operations to finalize the journal file or unlock the
+** database then the IO error code is returned to the user. If the
+** operation to finalize the journal file fails, then the code still
+** tries to unlock the database file if not in exclusive mode. If the
+** unlock operation fails as well, then the first error code related
+** to the first error encountered (the journal finalization one) is
+** returned.
+*/
+static int pager_end_transaction(Pager *pPager, int hasSuper, int bCommit){
+ int rc = SQLITE_OK; /* Error code from journal finalization operation */
+ int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
+
+ /* Do nothing if the pager does not have an open write transaction
+ ** or at least a RESERVED lock. This function may be called when there
+ ** is no write-transaction active but a RESERVED or greater lock is
+ ** held under two circumstances:
+ **
+ ** 1. After a successful hot-journal rollback, it is called with
+ ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
+ **
+ ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
+ ** lock switches back to locking_mode=normal and then executes a
+ ** read-transaction, this function is called with eState==PAGER_READER
+ ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
+ */
+ assert( assert_pager_state(pPager) );
+ assert( pPager->eState!=PAGER_ERROR );
+ if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
+ return SQLITE_OK;
+ }
+
+ releaseAllSavepoints(pPager);
+ assert( isOpen(pPager->jfd) || pPager->pInJournal==0
+ || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
+ );
+ if( isOpen(pPager->jfd) ){
+ assert( !pagerUseWal(pPager) );
+
+ /* Finalize the journal file. */
+ if( sqlite3JournalIsInMemory(pPager->jfd) ){
+ /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
+ sqlite3OsClose(pPager->jfd);
+ }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
+ if( pPager->journalOff==0 ){
+ rc = SQLITE_OK;
+ }else{
+ rc = sqlite3OsTruncate(pPager->jfd, 0);
+ if( rc==SQLITE_OK && pPager->fullSync ){
+ /* Make sure the new file size is written into the inode right away.
+ ** Otherwise the journal might resurrect following a power loss and
+ ** cause the last transaction to roll back. See
+ ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
+ */
+ rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
+ }
+ }
+ pPager->journalOff = 0;
+ }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
+ || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
+ ){
+ rc = zeroJournalHdr(pPager, hasSuper||pPager->tempFile);
+ pPager->journalOff = 0;
+ }else{
+ /* This branch may be executed with Pager.journalMode==MEMORY if
+ ** a hot-journal was just rolled back. In this case the journal
+ ** file should be closed and deleted. If this connection writes to
+ ** the database file, it will do so using an in-memory journal.
+ */
+ int bDelete = !pPager->tempFile;
+ assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
+ assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
+ || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
+ || pPager->journalMode==PAGER_JOURNALMODE_WAL
+ );
+ sqlite3OsClose(pPager->jfd);
+ if( bDelete ){
+ rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
+ }
+ }
+ }
+
+#ifdef SQLITE_CHECK_PAGES
+ sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
+ if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
+ PgHdr *p = sqlite3PagerLookup(pPager, 1);
+ if( p ){
+ p->pageHash = 0;
+ sqlite3PagerUnrefNotNull(p);
+ }
+ }
+#endif
+
+ sqlite3BitvecDestroy(pPager->pInJournal);
+ pPager->pInJournal = 0;
+ pPager->nRec = 0;
+ if( rc==SQLITE_OK ){
+ if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
+ sqlite3PcacheCleanAll(pPager->pPCache);
+ }else{
+ sqlite3PcacheClearWritable(pPager->pPCache);
+ }
+ sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
+ }
+
+ if( pagerUseWal(pPager) ){
+ /* Drop the WAL write-lock, if any. Also, if the connection was in
+ ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
+ ** lock held on the database file.
+ */
+ rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
+ assert( rc2==SQLITE_OK );
+ }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
+ /* This branch is taken when committing a transaction in rollback-journal
+ ** mode if the database file on disk is larger than the database image.
+ ** At this point the journal has been finalized and the transaction
+ ** successfully committed, but the EXCLUSIVE lock is still held on the
+ ** file. So it is safe to truncate the database file to its minimum
+ ** required size. */
+ assert( pPager->eLock==EXCLUSIVE_LOCK );
+ rc = pager_truncate(pPager, pPager->dbSize);
+ }
+
+ if( rc==SQLITE_OK && bCommit ){
+ rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
+ if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
+ }
+
+ if( !pPager->exclusiveMode
+ && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
+ ){
+ rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
+ }
+ pPager->eState = PAGER_READER;
+ pPager->setSuper = 0;
+
+ return (rc==SQLITE_OK?rc2:rc);
+}
+
+/*
+** Execute a rollback if a transaction is active and unlock the
+** database file.
+**
+** If the pager has already entered the ERROR state, do not attempt
+** the rollback at this time. Instead, pager_unlock() is called. The
+** call to pager_unlock() will discard all in-memory pages, unlock
+** the database file and move the pager back to OPEN state. If this
+** means that there is a hot-journal left in the file-system, the next
+** connection to obtain a shared lock on the pager (which may be this one)
+** will roll it back.
+**
+** If the pager has not already entered the ERROR state, but an IO or
+** malloc error occurs during a rollback, then this will itself cause
+** the pager to enter the ERROR state. Which will be cleared by the
+** call to pager_unlock(), as described above.
+*/
+static void pagerUnlockAndRollback(Pager *pPager){
+ if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
+ assert( assert_pager_state(pPager) );
+ if( pPager->eState>=PAGER_WRITER_LOCKED ){
+ sqlite3BeginBenignMalloc();
+ sqlite3PagerRollback(pPager);
+ sqlite3EndBenignMalloc();
+ }else if( !pPager->exclusiveMode ){
+ assert( pPager->eState==PAGER_READER );
+ pager_end_transaction(pPager, 0, 0);
+ }
+ }
+ pager_unlock(pPager);
+}
+
+/*
+** Parameter aData must point to a buffer of pPager->pageSize bytes
+** of data. Compute and return a checksum based ont the contents of the
+** page of data and the current value of pPager->cksumInit.
+**
+** This is not a real checksum. It is really just the sum of the
+** random initial value (pPager->cksumInit) and every 200th byte
+** of the page data, starting with byte offset (pPager->pageSize%200).
+** Each byte is interpreted as an 8-bit unsigned integer.
+**
+** Changing the formula used to compute this checksum results in an
+** incompatible journal file format.
+**
+** If journal corruption occurs due to a power failure, the most likely
+** scenario is that one end or the other of the record will be changed.
+** It is much less likely that the two ends of the journal record will be
+** correct and the middle be corrupt. Thus, this "checksum" scheme,
+** though fast and simple, catches the mostly likely kind of corruption.
+*/
+static u32 pager_cksum(Pager *pPager, const u8 *aData){
+ u32 cksum = pPager->cksumInit; /* Checksum value to return */
+ int i = pPager->pageSize-200; /* Loop counter */
+ while( i>0 ){
+ cksum += aData[i];
+ i -= 200;
+ }
+ return cksum;
+}
+
+/*
+** Read a single page from either the journal file (if isMainJrnl==1) or
+** from the sub-journal (if isMainJrnl==0) and playback that page.
+** The page begins at offset *pOffset into the file. The *pOffset
+** value is increased to the start of the next page in the journal.
+**
+** The main rollback journal uses checksums - the statement journal does
+** not.
+**
+** If the page number of the page record read from the (sub-)journal file
+** is greater than the current value of Pager.dbSize, then playback is
+** skipped and SQLITE_OK is returned.
+**
+** If pDone is not NULL, then it is a record of pages that have already
+** been played back. If the page at *pOffset has already been played back
+** (if the corresponding pDone bit is set) then skip the playback.
+** Make sure the pDone bit corresponding to the *pOffset page is set
+** prior to returning.
+**
+** If the page record is successfully read from the (sub-)journal file
+** and played back, then SQLITE_OK is returned. If an IO error occurs
+** while reading the record from the (sub-)journal file or while writing
+** to the database file, then the IO error code is returned. If data
+** is successfully read from the (sub-)journal file but appears to be
+** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
+** two circumstances:
+**
+** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
+** * If the record is being rolled back from the main journal file
+** and the checksum field does not match the record content.
+**
+** Neither of these two scenarios are possible during a savepoint rollback.
+**
+** If this is a savepoint rollback, then memory may have to be dynamically
+** allocated by this function. If this is the case and an allocation fails,
+** SQLITE_NOMEM is returned.
+*/
+static int pager_playback_one_page(
+ Pager *pPager, /* The pager being played back */
+ i64 *pOffset, /* Offset of record to playback */
+ Bitvec *pDone, /* Bitvec of pages already played back */
+ int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
+ int isSavepnt /* True for a savepoint rollback */
+){
+ int rc;
+ PgHdr *pPg; /* An existing page in the cache */
+ Pgno pgno; /* The page number of a page in journal */
+ u32 cksum; /* Checksum used for sanity checking */
+ char *aData; /* Temporary storage for the page */
+ sqlite3_file *jfd; /* The file descriptor for the journal file */
+ int isSynced; /* True if journal page is synced */
+
+ assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
+ assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
+ assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
+ assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
+
+ aData = pPager->pTmpSpace;
+ assert( aData ); /* Temp storage must have already been allocated */
+ assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
+
+ /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
+ ** or savepoint rollback done at the request of the caller) or this is
+ ** a hot-journal rollback. If it is a hot-journal rollback, the pager
+ ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
+ ** only reads from the main journal, not the sub-journal.
+ */
+ assert( pPager->eState>=PAGER_WRITER_CACHEMOD
+ || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
+ );
+ assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
+
+ /* Read the page number and page data from the journal or sub-journal
+ ** file. Return an error code to the caller if an IO error occurs.
+ */
+ jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
+ rc = read32bits(jfd, *pOffset, &pgno);
+ if( rc!=SQLITE_OK ) return rc;
+ rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
+ if( rc!=SQLITE_OK ) return rc;
+ *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
+
+ /* Sanity checking on the page. This is more important that I originally
+ ** thought. If a power failure occurs while the journal is being written,
+ ** it could cause invalid data to be written into the journal. We need to
+ ** detect this invalid data (with high probability) and ignore it.
+ */
+ if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
+ assert( !isSavepnt );
+ return SQLITE_DONE;
+ }
+ if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
+ return SQLITE_OK;
+ }
+ if( isMainJrnl ){
+ rc = read32bits(jfd, (*pOffset)-4, &cksum);
+ if( rc ) return rc;
+ if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
+ return SQLITE_DONE;
+ }
+ }
+
+ /* If this page has already been played back before during the current
+ ** rollback, then don't bother to play it back again.
+ */
+ if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
+ return rc;
+ }
+
+ /* When playing back page 1, restore the nReserve setting
+ */
+ if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
+ pPager->nReserve = ((u8*)aData)[20];
+ }
+
+ /* If the pager is in CACHEMOD state, then there must be a copy of this
+ ** page in the pager cache. In this case just update the pager cache,
+ ** not the database file. The page is left marked dirty in this case.
+ **
+ ** An exception to the above rule: If the database is in no-sync mode
+ ** and a page is moved during an incremental vacuum then the page may
+ ** not be in the pager cache. Later: if a malloc() or IO error occurs
+ ** during a Movepage() call, then the page may not be in the cache
+ ** either. So the condition described in the above paragraph is not
+ ** assert()able.
+ **
+ ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
+ ** pager cache if it exists and the main file. The page is then marked
+ ** not dirty. Since this code is only executed in PAGER_OPEN state for
+ ** a hot-journal rollback, it is guaranteed that the page-cache is empty
+ ** if the pager is in OPEN state.
+ **
+ ** Ticket #1171: The statement journal might contain page content that is
+ ** different from the page content at the start of the transaction.
+ ** This occurs when a page is changed prior to the start of a statement
+ ** then changed again within the statement. When rolling back such a
+ ** statement we must not write to the original database unless we know
+ ** for certain that original page contents are synced into the main rollback
+ ** journal. Otherwise, a power loss might leave modified data in the
+ ** database file without an entry in the rollback journal that can
+ ** restore the database to its original form. Two conditions must be
+ ** met before writing to the database files. (1) the database must be
+ ** locked. (2) we know that the original page content is fully synced
+ ** in the main journal either because the page is not in cache or else
+ ** the page is marked as needSync==0.
+ **
+ ** 2008-04-14: When attempting to vacuum a corrupt database file, it
+ ** is possible to fail a statement on a database that does not yet exist.
+ ** Do not attempt to write if database file has never been opened.
+ */
+ if( pagerUseWal(pPager) ){
+ pPg = 0;
+ }else{
+ pPg = sqlite3PagerLookup(pPager, pgno);
+ }
+ assert( pPg || !MEMDB );
+ assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
+ PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
+ PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
+ (isMainJrnl?"main-journal":"sub-journal")
+ ));
+ if( isMainJrnl ){
+ isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
+ }else{
+ isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
+ }
+ if( isOpen(pPager->fd)
+ && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
+ && isSynced
+ ){
+ i64 ofst = (pgno-1)*(i64)pPager->pageSize;
+ testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
+ assert( !pagerUseWal(pPager) );
+
+ /* Write the data read from the journal back into the database file.
+ ** This is usually safe even for an encrypted database - as the data
+ ** was encrypted before it was written to the journal file. The exception
+ ** is if the data was just read from an in-memory sub-journal. In that
+ ** case it must be encrypted here before it is copied into the database
+ ** file. */
+ rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
+
+ if( pgno>pPager->dbFileSize ){
+ pPager->dbFileSize = pgno;
+ }
+ if( pPager->pBackup ){
+ sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
+ }
+ }else if( !isMainJrnl && pPg==0 ){
+ /* If this is a rollback of a savepoint and data was not written to
+ ** the database and the page is not in-memory, there is a potential
+ ** problem. When the page is next fetched by the b-tree layer, it
+ ** will be read from the database file, which may or may not be
+ ** current.
+ **
+ ** There are a couple of different ways this can happen. All are quite
+ ** obscure. When running in synchronous mode, this can only happen
+ ** if the page is on the free-list at the start of the transaction, then
+ ** populated, then moved using sqlite3PagerMovepage().
+ **
+ ** The solution is to add an in-memory page to the cache containing
+ ** the data just read from the sub-journal. Mark the page as dirty
+ ** and if the pager requires a journal-sync, then mark the page as
+ ** requiring a journal-sync before it is written.
+ */
+ assert( isSavepnt );
+ assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
+ pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
+ rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
+ assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
+ pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
+ if( rc!=SQLITE_OK ) return rc;
+ sqlite3PcacheMakeDirty(pPg);
+ }
+ if( pPg ){
+ /* No page should ever be explicitly rolled back that is in use, except
+ ** for page 1 which is held in use in order to keep the lock on the
+ ** database active. However such a page may be rolled back as a result
+ ** of an internal error resulting in an automatic call to
+ ** sqlite3PagerRollback().
+ */
+ void *pData;
+ pData = pPg->pData;
+ memcpy(pData, (u8*)aData, pPager->pageSize);
+ pPager->xReiniter(pPg);
+ /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
+ ** that call was dangerous and had no detectable benefit since the cache
+ ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
+ ** has been removed. */
+ pager_set_pagehash(pPg);
+
+ /* If this was page 1, then restore the value of Pager.dbFileVers.
+ ** Do this before any decoding. */
+ if( pgno==1 ){
+ memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
+ }
+ sqlite3PcacheRelease(pPg);
+ }
+ return rc;
+}
+
+/*
+** Parameter zSuper is the name of a super-journal file. A single journal
+** file that referred to the super-journal file has just been rolled back.
+** This routine checks if it is possible to delete the super-journal file,
+** and does so if it is.
+**
+** Argument zSuper may point to Pager.pTmpSpace. So that buffer is not
+** available for use within this function.
+**
+** When a super-journal file is created, it is populated with the names
+** of all of its child journals, one after another, formatted as utf-8
+** encoded text. The end of each child journal file is marked with a
+** nul-terminator byte (0x00). i.e. the entire contents of a super-journal
+** file for a transaction involving two databases might be:
+**
+** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
+**
+** A super-journal file may only be deleted once all of its child
+** journals have been rolled back.
+**
+** This function reads the contents of the super-journal file into
+** memory and loops through each of the child journal names. For
+** each child journal, it checks if:
+**
+** * if the child journal exists, and if so
+** * if the child journal contains a reference to super-journal
+** file zSuper
+**
+** If a child journal can be found that matches both of the criteria
+** above, this function returns without doing anything. Otherwise, if
+** no such child journal can be found, file zSuper is deleted from
+** the file-system using sqlite3OsDelete().
+**
+** If an IO error within this function, an error code is returned. This
+** function allocates memory by calling sqlite3Malloc(). If an allocation
+** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
+** occur, SQLITE_OK is returned.
+**
+** TODO: This function allocates a single block of memory to load
+** the entire contents of the super-journal file. This could be
+** a couple of kilobytes or so - potentially larger than the page
+** size.
+*/
+static int pager_delsuper(Pager *pPager, const char *zSuper){
+ sqlite3_vfs *pVfs = pPager->pVfs;
+ int rc; /* Return code */
+ sqlite3_file *pSuper; /* Malloc'd super-journal file descriptor */
+ sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
+ char *zSuperJournal = 0; /* Contents of super-journal file */
+ i64 nSuperJournal; /* Size of super-journal file */
+ char *zJournal; /* Pointer to one journal within MJ file */
+ char *zSuperPtr; /* Space to hold super-journal filename */
+ int nSuperPtr; /* Amount of space allocated to zSuperPtr[] */
+
+ /* Allocate space for both the pJournal and pSuper file descriptors.
+ ** If successful, open the super-journal file for reading.
+ */
+ pSuper = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
+ if( !pSuper ){
+ rc = SQLITE_NOMEM_BKPT;
+ pJournal = 0;
+ }else{
+ const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL);
+ rc = sqlite3OsOpen(pVfs, zSuper, pSuper, flags, 0);
+ pJournal = (sqlite3_file *)(((u8 *)pSuper) + pVfs->szOsFile);
+ }
+ if( rc!=SQLITE_OK ) goto delsuper_out;
+
+ /* Load the entire super-journal file into space obtained from
+ ** sqlite3_malloc() and pointed to by zSuperJournal. Also obtain
+ ** sufficient space (in zSuperPtr) to hold the names of super-journal
+ ** files extracted from regular rollback-journals.
+ */
+ rc = sqlite3OsFileSize(pSuper, &nSuperJournal);
+ if( rc!=SQLITE_OK ) goto delsuper_out;
+ nSuperPtr = pVfs->mxPathname+1;
+ zSuperJournal = sqlite3Malloc(nSuperJournal + nSuperPtr + 2);
+ if( !zSuperJournal ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto delsuper_out;
+ }
+ zSuperPtr = &zSuperJournal[nSuperJournal+2];
+ rc = sqlite3OsRead(pSuper, zSuperJournal, (int)nSuperJournal, 0);
+ if( rc!=SQLITE_OK ) goto delsuper_out;
+ zSuperJournal[nSuperJournal] = 0;
+ zSuperJournal[nSuperJournal+1] = 0;
+
+ zJournal = zSuperJournal;
+ while( (zJournal-zSuperJournal)<nSuperJournal ){
+ int exists;
+ rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
+ if( rc!=SQLITE_OK ){
+ goto delsuper_out;
+ }
+ if( exists ){
+ /* One of the journals pointed to by the super-journal exists.
+ ** Open it and check if it points at the super-journal. If
+ ** so, return without deleting the super-journal file.
+ ** NB: zJournal is really a MAIN_JOURNAL. But call it a
+ ** SUPER_JOURNAL here so that the VFS will not send the zJournal
+ ** name into sqlite3_database_file_object().
+ */
+ int c;
+ int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL);
+ rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
+ if( rc!=SQLITE_OK ){
+ goto delsuper_out;
+ }
+
+ rc = readSuperJournal(pJournal, zSuperPtr, nSuperPtr);
+ sqlite3OsClose(pJournal);
+ if( rc!=SQLITE_OK ){
+ goto delsuper_out;
+ }
+
+ c = zSuperPtr[0]!=0 && strcmp(zSuperPtr, zSuper)==0;
+ if( c ){
+ /* We have a match. Do not delete the super-journal file. */
+ goto delsuper_out;
+ }
+ }
+ zJournal += (sqlite3Strlen30(zJournal)+1);
+ }
+
+ sqlite3OsClose(pSuper);
+ rc = sqlite3OsDelete(pVfs, zSuper, 0);
+
+delsuper_out:
+ sqlite3_free(zSuperJournal);
+ if( pSuper ){
+ sqlite3OsClose(pSuper);
+ assert( !isOpen(pJournal) );
+ sqlite3_free(pSuper);
+ }
+ return rc;
+}
+
+
+/*
+** This function is used to change the actual size of the database
+** file in the file-system. This only happens when committing a transaction,
+** or rolling back a transaction (including rolling back a hot-journal).
+**
+** If the main database file is not open, or the pager is not in either
+** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
+** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
+** If the file on disk is currently larger than nPage pages, then use the VFS
+** xTruncate() method to truncate it.
+**
+** Or, it might be the case that the file on disk is smaller than
+** nPage pages. Some operating system implementations can get confused if
+** you try to truncate a file to some size that is larger than it
+** currently is, so detect this case and write a single zero byte to
+** the end of the new file instead.
+**
+** If successful, return SQLITE_OK. If an IO error occurs while modifying
+** the database file, return the error code to the caller.
+*/
+static int pager_truncate(Pager *pPager, Pgno nPage){
+ int rc = SQLITE_OK;
+ assert( pPager->eState!=PAGER_ERROR );
+ assert( pPager->eState!=PAGER_READER );
+
+ if( isOpen(pPager->fd)
+ && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
+ ){
+ i64 currentSize, newSize;
+ int szPage = pPager->pageSize;
+ assert( pPager->eLock==EXCLUSIVE_LOCK );
+ /* TODO: Is it safe to use Pager.dbFileSize here? */
+ rc = sqlite3OsFileSize(pPager->fd, &currentSize);
+ newSize = szPage*(i64)nPage;
+ if( rc==SQLITE_OK && currentSize!=newSize ){
+ if( currentSize>newSize ){
+ rc = sqlite3OsTruncate(pPager->fd, newSize);
+ }else if( (currentSize+szPage)<=newSize ){
+ char *pTmp = pPager->pTmpSpace;
+ memset(pTmp, 0, szPage);
+ testcase( (newSize-szPage) == currentSize );
+ testcase( (newSize-szPage) > currentSize );
+ rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
+ }
+ if( rc==SQLITE_OK ){
+ pPager->dbFileSize = nPage;
+ }
+ }
+ }
+ return rc;
+}
+
+/*
+** Return a sanitized version of the sector-size of OS file pFile. The
+** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
+*/
+SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
+ int iRet = sqlite3OsSectorSize(pFile);
+ if( iRet<32 ){
+ iRet = 512;
+ }else if( iRet>MAX_SECTOR_SIZE ){
+ assert( MAX_SECTOR_SIZE>=512 );
+ iRet = MAX_SECTOR_SIZE;
+ }
+ return iRet;
+}
+
+/*
+** Set the value of the Pager.sectorSize variable for the given
+** pager based on the value returned by the xSectorSize method
+** of the open database file. The sector size will be used
+** to determine the size and alignment of journal header and
+** super-journal pointers within created journal files.
+**
+** For temporary files the effective sector size is always 512 bytes.
+**
+** Otherwise, for non-temporary files, the effective sector size is
+** the value returned by the xSectorSize() method rounded up to 32 if
+** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
+** is greater than MAX_SECTOR_SIZE.
+**
+** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
+** the effective sector size to its minimum value (512). The purpose of
+** pPager->sectorSize is to define the "blast radius" of bytes that
+** might change if a crash occurs while writing to a single byte in
+** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
+** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
+** size. For backwards compatibility of the rollback journal file format,
+** we cannot reduce the effective sector size below 512.
+*/
+static void setSectorSize(Pager *pPager){
+ assert( isOpen(pPager->fd) || pPager->tempFile );
+
+ if( pPager->tempFile
+ || (sqlite3OsDeviceCharacteristics(pPager->fd) &
+ SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
+ ){
+ /* Sector size doesn't matter for temporary files. Also, the file
+ ** may not have been opened yet, in which case the OsSectorSize()
+ ** call will segfault. */
+ pPager->sectorSize = 512;
+ }else{
+ pPager->sectorSize = sqlite3SectorSize(pPager->fd);
+ }
+}
+
+/*
+** Playback the journal and thus restore the database file to
+** the state it was in before we started making changes.
+**
+** The journal file format is as follows:
+**
+** (1) 8 byte prefix. A copy of aJournalMagic[].
+** (2) 4 byte big-endian integer which is the number of valid page records
+** in the journal. If this value is 0xffffffff, then compute the
+** number of page records from the journal size.
+** (3) 4 byte big-endian integer which is the initial value for the
+** sanity checksum.
+** (4) 4 byte integer which is the number of pages to truncate the
+** database to during a rollback.
+** (5) 4 byte big-endian integer which is the sector size. The header
+** is this many bytes in size.
+** (6) 4 byte big-endian integer which is the page size.
+** (7) zero padding out to the next sector size.
+** (8) Zero or more pages instances, each as follows:
+** + 4 byte page number.
+** + pPager->pageSize bytes of data.
+** + 4 byte checksum
+**
+** When we speak of the journal header, we mean the first 7 items above.
+** Each entry in the journal is an instance of the 8th item.
+**
+** Call the value from the second bullet "nRec". nRec is the number of
+** valid page entries in the journal. In most cases, you can compute the
+** value of nRec from the size of the journal file. But if a power
+** failure occurred while the journal was being written, it could be the
+** case that the size of the journal file had already been increased but
+** the extra entries had not yet made it safely to disk. In such a case,
+** the value of nRec computed from the file size would be too large. For
+** that reason, we always use the nRec value in the header.
+**
+** If the nRec value is 0xffffffff it means that nRec should be computed
+** from the file size. This value is used when the user selects the
+** no-sync option for the journal. A power failure could lead to corruption
+** in this case. But for things like temporary table (which will be
+** deleted when the power is restored) we don't care.
+**
+** If the file opened as the journal file is not a well-formed
+** journal file then all pages up to the first corrupted page are rolled
+** back (or no pages if the journal header is corrupted). The journal file
+** is then deleted and SQLITE_OK returned, just as if no corruption had
+** been encountered.
+**
+** If an I/O or malloc() error occurs, the journal-file is not deleted
+** and an error code is returned.
+**
+** The isHot parameter indicates that we are trying to rollback a journal
+** that might be a hot journal. Or, it could be that the journal is
+** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
+** If the journal really is hot, reset the pager cache prior rolling
+** back any content. If the journal is merely persistent, no reset is
+** needed.
+*/
+static int pager_playback(Pager *pPager, int isHot){
+ sqlite3_vfs *pVfs = pPager->pVfs;
+ i64 szJ; /* Size of the journal file in bytes */
+ u32 nRec; /* Number of Records in the journal */
+ u32 u; /* Unsigned loop counter */
+ Pgno mxPg = 0; /* Size of the original file in pages */
+ int rc; /* Result code of a subroutine */
+ int res = 1; /* Value returned by sqlite3OsAccess() */
+ char *zSuper = 0; /* Name of super-journal file if any */
+ int needPagerReset; /* True to reset page prior to first page rollback */
+ int nPlayback = 0; /* Total number of pages restored from journal */
+ u32 savedPageSize = pPager->pageSize;
+
+ /* Figure out how many records are in the journal. Abort early if
+ ** the journal is empty.
+ */
+ assert( isOpen(pPager->jfd) );
+ rc = sqlite3OsFileSize(pPager->jfd, &szJ);
+ if( rc!=SQLITE_OK ){
+ goto end_playback;
+ }
+
+ /* Read the super-journal name from the journal, if it is present.
+ ** If a super-journal file name is specified, but the file is not
+ ** present on disk, then the journal is not hot and does not need to be
+ ** played back.
+ **
+ ** TODO: Technically the following is an error because it assumes that
+ ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
+ ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
+ ** mxPathname is 512, which is the same as the minimum allowable value
+ ** for pageSize.
+ */
+ zSuper = pPager->pTmpSpace;
+ rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1);
+ if( rc==SQLITE_OK && zSuper[0] ){
+ rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);
+ }
+ zSuper = 0;
+ if( rc!=SQLITE_OK || !res ){
+ goto end_playback;
+ }
+ pPager->journalOff = 0;
+ needPagerReset = isHot;
+
+ /* This loop terminates either when a readJournalHdr() or
+ ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
+ ** occurs.
+ */
+ while( 1 ){
+ /* Read the next journal header from the journal file. If there are
+ ** not enough bytes left in the journal file for a complete header, or
+ ** it is corrupted, then a process must have failed while writing it.
+ ** This indicates nothing more needs to be rolled back.
+ */
+ rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
+ if( rc!=SQLITE_OK ){
+ if( rc==SQLITE_DONE ){
+ rc = SQLITE_OK;
+ }
+ goto end_playback;
+ }
+
+ /* If nRec is 0xffffffff, then this journal was created by a process
+ ** working in no-sync mode. This means that the rest of the journal
+ ** file consists of pages, there are no more journal headers. Compute
+ ** the value of nRec based on this assumption.
+ */
+ if( nRec==0xffffffff ){
+ assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
+ nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
+ }
+
+ /* If nRec is 0 and this rollback is of a transaction created by this
+ ** process and if this is the final header in the journal, then it means
+ ** that this part of the journal was being filled but has not yet been
+ ** synced to disk. Compute the number of pages based on the remaining
+ ** size of the file.
+ **
+ ** The third term of the test was added to fix ticket #2565.
+ ** When rolling back a hot journal, nRec==0 always means that the next
+ ** chunk of the journal contains zero pages to be rolled back. But
+ ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
+ ** the journal, it means that the journal might contain additional
+ ** pages that need to be rolled back and that the number of pages
+ ** should be computed based on the journal file size.
+ */
+ if( nRec==0 && !isHot &&
+ pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
+ nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
+ }
+
+ /* If this is the first header read from the journal, truncate the
+ ** database file back to its original size.
+ */
+ if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
+ rc = pager_truncate(pPager, mxPg);
+ if( rc!=SQLITE_OK ){
+ goto end_playback;
+ }
+ pPager->dbSize = mxPg;
+ }
+
+ /* Copy original pages out of the journal and back into the
+ ** database file and/or page cache.
+ */
+ for(u=0; u<nRec; u++){
+ if( needPagerReset ){
+ pager_reset(pPager);
+ needPagerReset = 0;
+ }
+ rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
+ if( rc==SQLITE_OK ){
+ nPlayback++;
+ }else{
+ if( rc==SQLITE_DONE ){
+ pPager->journalOff = szJ;
+ break;
+ }else if( rc==SQLITE_IOERR_SHORT_READ ){
+ /* If the journal has been truncated, simply stop reading and
+ ** processing the journal. This might happen if the journal was
+ ** not completely written and synced prior to a crash. In that
+ ** case, the database should have never been written in the
+ ** first place so it is OK to simply abandon the rollback. */
+ rc = SQLITE_OK;
+ goto end_playback;
+ }else{
+ /* If we are unable to rollback, quit and return the error
+ ** code. This will cause the pager to enter the error state
+ ** so that no further harm will be done. Perhaps the next
+ ** process to come along will be able to rollback the database.
+ */
+ goto end_playback;
+ }
+ }
+ }
+ }
+ /*NOTREACHED*/
+ assert( 0 );
+
+end_playback:
+ if( rc==SQLITE_OK ){
+ rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
+ }
+ /* Following a rollback, the database file should be back in its original
+ ** state prior to the start of the transaction, so invoke the
+ ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
+ ** assertion that the transaction counter was modified.
+ */
+#ifdef SQLITE_DEBUG
+ sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
+#endif
+
+ /* If this playback is happening automatically as a result of an IO or
+ ** malloc error that occurred after the change-counter was updated but
+ ** before the transaction was committed, then the change-counter
+ ** modification may just have been reverted. If this happens in exclusive
+ ** mode, then subsequent transactions performed by the connection will not
+ ** update the change-counter at all. This may lead to cache inconsistency
+ ** problems for other processes at some point in the future. So, just
+ ** in case this has happened, clear the changeCountDone flag now.
+ */
+ pPager->changeCountDone = pPager->tempFile;
+
+ if( rc==SQLITE_OK ){
+ zSuper = pPager->pTmpSpace;
+ rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1);
+ testcase( rc!=SQLITE_OK );
+ }
+ if( rc==SQLITE_OK
+ && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
+ ){
+ rc = sqlite3PagerSync(pPager, 0);
+ }
+ if( rc==SQLITE_OK ){
+ rc = pager_end_transaction(pPager, zSuper[0]!='\0', 0);
+ testcase( rc!=SQLITE_OK );
+ }
+ if( rc==SQLITE_OK && zSuper[0] && res ){
+ /* If there was a super-journal and this routine will return success,
+ ** see if it is possible to delete the super-journal.
+ */
+ rc = pager_delsuper(pPager, zSuper);
+ testcase( rc!=SQLITE_OK );
+ }
+ if( isHot && nPlayback ){
+ sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
+ nPlayback, pPager->zJournal);
+ }
+
+ /* The Pager.sectorSize variable may have been updated while rolling
+ ** back a journal created by a process with a different sector size
+ ** value. Reset it to the correct value for this process.
+ */
+ setSectorSize(pPager);
+ return rc;
+}
+
+
+/*
+** Read the content for page pPg out of the database file (or out of
+** the WAL if that is where the most recent copy if found) into
+** pPg->pData. A shared lock or greater must be held on the database
+** file before this function is called.
+**
+** If page 1 is read, then the value of Pager.dbFileVers[] is set to
+** the value read from the database file.
+**
+** If an IO error occurs, then the IO error is returned to the caller.
+** Otherwise, SQLITE_OK is returned.
+*/
+static int readDbPage(PgHdr *pPg){
+ Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
+ int rc = SQLITE_OK; /* Return code */
+
+#ifndef SQLITE_OMIT_WAL
+ u32 iFrame = 0; /* Frame of WAL containing pgno */
+
+ assert( pPager->eState>=PAGER_READER && !MEMDB );
+ assert( isOpen(pPager->fd) );
+
+ if( pagerUseWal(pPager) ){
+ rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
+ if( rc ) return rc;
+ }
+ if( iFrame ){
+ rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
+ }else
+#endif
+ {
+ i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
+ rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
+ if( rc==SQLITE_IOERR_SHORT_READ ){
+ rc = SQLITE_OK;
+ }
+ }
+
+ if( pPg->pgno==1 ){
+ if( rc ){
+ /* If the read is unsuccessful, set the dbFileVers[] to something
+ ** that will never be a valid file version. dbFileVers[] is a copy
+ ** of bytes 24..39 of the database. Bytes 28..31 should always be
+ ** zero or the size of the database in page. Bytes 32..35 and 35..39
+ ** should be page numbers which are never 0xffffffff. So filling
+ ** pPager->dbFileVers[] with all 0xff bytes should suffice.
+ **
+ ** For an encrypted database, the situation is more complex: bytes
+ ** 24..39 of the database are white noise. But the probability of
+ ** white noise equaling 16 bytes of 0xff is vanishingly small so
+ ** we should still be ok.
+ */
+ memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
+ }else{
+ u8 *dbFileVers = &((u8*)pPg->pData)[24];
+ memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
+ }
+ }
+ PAGER_INCR(sqlite3_pager_readdb_count);
+ PAGER_INCR(pPager->nRead);
+ IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
+ PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
+ PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
+
+ return rc;
+}
+
+/*
+** Update the value of the change-counter at offsets 24 and 92 in
+** the header and the sqlite version number at offset 96.
+**
+** This is an unconditional update. See also the pager_incr_changecounter()
+** routine which only updates the change-counter if the update is actually
+** needed, as determined by the pPager->changeCountDone state variable.
+*/
+static void pager_write_changecounter(PgHdr *pPg){
+ u32 change_counter;
+
+ /* Increment the value just read and write it back to byte 24. */
+ change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
+ put32bits(((char*)pPg->pData)+24, change_counter);
+
+ /* Also store the SQLite version number in bytes 96..99 and in
+ ** bytes 92..95 store the change counter for which the version number
+ ** is valid. */
+ put32bits(((char*)pPg->pData)+92, change_counter);
+ put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
+}
+
+#ifndef SQLITE_OMIT_WAL
+/*
+** This function is invoked once for each page that has already been
+** written into the log file when a WAL transaction is rolled back.
+** Parameter iPg is the page number of said page. The pCtx argument
+** is actually a pointer to the Pager structure.
+**
+** If page iPg is present in the cache, and has no outstanding references,
+** it is discarded. Otherwise, if there are one or more outstanding
+** references, the page content is reloaded from the database. If the
+** attempt to reload content from the database is required and fails,
+** return an SQLite error code. Otherwise, SQLITE_OK.
+*/
+static int pagerUndoCallback(void *pCtx, Pgno iPg){
+ int rc = SQLITE_OK;
+ Pager *pPager = (Pager *)pCtx;
+ PgHdr *pPg;
+
+ assert( pagerUseWal(pPager) );
+ pPg = sqlite3PagerLookup(pPager, iPg);
+ if( pPg ){
+ if( sqlite3PcachePageRefcount(pPg)==1 ){
+ sqlite3PcacheDrop(pPg);
+ }else{
+ rc = readDbPage(pPg);
+ if( rc==SQLITE_OK ){
+ pPager->xReiniter(pPg);
+ }
+ sqlite3PagerUnrefNotNull(pPg);
+ }
+ }
+
+ /* Normally, if a transaction is rolled back, any backup processes are
+ ** updated as data is copied out of the rollback journal and into the
+ ** database. This is not generally possible with a WAL database, as
+ ** rollback involves simply truncating the log file. Therefore, if one
+ ** or more frames have already been written to the log (and therefore
+ ** also copied into the backup databases) as part of this transaction,
+ ** the backups must be restarted.
+ */
+ sqlite3BackupRestart(pPager->pBackup);
+
+ return rc;
+}
+
+/*
+** This function is called to rollback a transaction on a WAL database.
+*/
+static int pagerRollbackWal(Pager *pPager){
+ int rc; /* Return Code */
+ PgHdr *pList; /* List of dirty pages to revert */
+
+ /* For all pages in the cache that are currently dirty or have already
+ ** been written (but not committed) to the log file, do one of the
+ ** following:
+ **
+ ** + Discard the cached page (if refcount==0), or
+ ** + Reload page content from the database (if refcount>0).
+ */
+ pPager->dbSize = pPager->dbOrigSize;
+ rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
+ pList = sqlite3PcacheDirtyList(pPager->pPCache);
+ while( pList && rc==SQLITE_OK ){
+ PgHdr *pNext = pList->pDirty;
+ rc = pagerUndoCallback((void *)pPager, pList->pgno);
+ pList = pNext;
+ }
+
+ return rc;
+}
+
+/*
+** This function is a wrapper around sqlite3WalFrames(). As well as logging
+** the contents of the list of pages headed by pList (connected by pDirty),
+** this function notifies any active backup processes that the pages have
+** changed.
+**
+** The list of pages passed into this routine is always sorted by page number.
+** Hence, if page 1 appears anywhere on the list, it will be the first page.
+*/
+static int pagerWalFrames(
+ Pager *pPager, /* Pager object */
+ PgHdr *pList, /* List of frames to log */
+ Pgno nTruncate, /* Database size after this commit */
+ int isCommit /* True if this is a commit */
+){
+ int rc; /* Return code */
+ int nList; /* Number of pages in pList */
+ PgHdr *p; /* For looping over pages */
+
+ assert( pPager->pWal );
+ assert( pList );
+#ifdef SQLITE_DEBUG
+ /* Verify that the page list is in accending order */
+ for(p=pList; p && p->pDirty; p=p->pDirty){
+ assert( p->pgno < p->pDirty->pgno );
+ }
+#endif
+
+ assert( pList->pDirty==0 || isCommit );
+ if( isCommit ){
+ /* If a WAL transaction is being committed, there is no point in writing
+ ** any pages with page numbers greater than nTruncate into the WAL file.
+ ** They will never be read by any client. So remove them from the pDirty
+ ** list here. */
+ PgHdr **ppNext = &pList;
+ nList = 0;
+ for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
+ if( p->pgno<=nTruncate ){
+ ppNext = &p->pDirty;
+ nList++;
+ }
+ }
+ assert( pList );
+ }else{
+ nList = 1;
+ }
+ pPager->aStat[PAGER_STAT_WRITE] += nList;
+
+ if( pList->pgno==1 ) pager_write_changecounter(pList);
+ rc = sqlite3WalFrames(pPager->pWal,
+ pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
+ );
+ if( rc==SQLITE_OK && pPager->pBackup ){
+ for(p=pList; p; p=p->pDirty){
+ sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
+ }
+ }
+
+#ifdef SQLITE_CHECK_PAGES
+ pList = sqlite3PcacheDirtyList(pPager->pPCache);
+ for(p=pList; p; p=p->pDirty){
+ pager_set_pagehash(p);
+ }
+#endif
+
+ return rc;
+}
+
+/*
+** Begin a read transaction on the WAL.
+**
+** This routine used to be called "pagerOpenSnapshot()" because it essentially
+** makes a snapshot of the database at the current point in time and preserves
+** that snapshot for use by the reader in spite of concurrently changes by
+** other writers or checkpointers.
+*/
+static int pagerBeginReadTransaction(Pager *pPager){
+ int rc; /* Return code */
+ int changed = 0; /* True if cache must be reset */
+
+ assert( pagerUseWal(pPager) );
+ assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
+
+ /* sqlite3WalEndReadTransaction() was not called for the previous
+ ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
+ ** are in locking_mode=NORMAL and EndRead() was previously called,
+ ** the duplicate call is harmless.
+ */
+ sqlite3WalEndReadTransaction(pPager->pWal);
+
+ rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
+ if( rc!=SQLITE_OK || changed ){
+ pager_reset(pPager);
+ if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
+ }
+
+ return rc;
+}
+#endif
+
+/*
+** This function is called as part of the transition from PAGER_OPEN
+** to PAGER_READER state to determine the size of the database file
+** in pages (assuming the page size currently stored in Pager.pageSize).
+**
+** If no error occurs, SQLITE_OK is returned and the size of the database
+** in pages is stored in *pnPage. Otherwise, an error code (perhaps
+** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
+*/
+static int pagerPagecount(Pager *pPager, Pgno *pnPage){
+ Pgno nPage; /* Value to return via *pnPage */
+
+ /* Query the WAL sub-system for the database size. The WalDbsize()
+ ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
+ ** if the database size is not available. The database size is not
+ ** available from the WAL sub-system if the log file is empty or
+ ** contains no valid committed transactions.
+ */
+ assert( pPager->eState==PAGER_OPEN );
+ assert( pPager->eLock>=SHARED_LOCK );
+ assert( isOpen(pPager->fd) );
+ assert( pPager->tempFile==0 );
+ nPage = sqlite3WalDbsize(pPager->pWal);
+
+ /* If the number of pages in the database is not available from the
+ ** WAL sub-system, determine the page count based on the size of
+ ** the database file. If the size of the database file is not an
+ ** integer multiple of the page-size, round up the result.
+ */
+ if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
+ i64 n = 0; /* Size of db file in bytes */
+ int rc = sqlite3OsFileSize(pPager->fd, &n);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
+ }
+
+ /* If the current number of pages in the file is greater than the
+ ** configured maximum pager number, increase the allowed limit so
+ ** that the file can be read.
+ */
+ if( nPage>pPager->mxPgno ){
+ pPager->mxPgno = (Pgno)nPage;
+ }
+
+ *pnPage = nPage;
+ return SQLITE_OK;
+}
+
+#ifndef SQLITE_OMIT_WAL
+/*
+** Check if the *-wal file that corresponds to the database opened by pPager
+** exists if the database is not empy, or verify that the *-wal file does
+** not exist (by deleting it) if the database file is empty.
+**
+** If the database is not empty and the *-wal file exists, open the pager
+** in WAL mode. If the database is empty or if no *-wal file exists and
+** if no error occurs, make sure Pager.journalMode is not set to
+** PAGER_JOURNALMODE_WAL.
+**
+** Return SQLITE_OK or an error code.
+**
+** The caller must hold a SHARED lock on the database file to call this
+** function. Because an EXCLUSIVE lock on the db file is required to delete
+** a WAL on a none-empty database, this ensures there is no race condition
+** between the xAccess() below and an xDelete() being executed by some
+** other connection.
+*/
+static int pagerOpenWalIfPresent(Pager *pPager){
+ int rc = SQLITE_OK;
+ assert( pPager->eState==PAGER_OPEN );
+ assert( pPager->eLock>=SHARED_LOCK );
+
+ if( !pPager->tempFile ){
+ int isWal; /* True if WAL file exists */
+ rc = sqlite3OsAccess(
+ pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
+ );
+ if( rc==SQLITE_OK ){
+ if( isWal ){
+ Pgno nPage; /* Size of the database file */
+
+ rc = pagerPagecount(pPager, &nPage);
+ if( rc ) return rc;
+ if( nPage==0 ){
+ rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
+ }else{
+ testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
+ rc = sqlite3PagerOpenWal(pPager, 0);
+ }
+ }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
+ pPager->journalMode = PAGER_JOURNALMODE_DELETE;
+ }
+ }
+ }
+ return rc;
+}
+#endif
+
+/*
+** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
+** the entire super-journal file. The case pSavepoint==NULL occurs when
+** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
+** savepoint.
+**
+** When pSavepoint is not NULL (meaning a non-transaction savepoint is
+** being rolled back), then the rollback consists of up to three stages,
+** performed in the order specified:
+**
+** * Pages are played back from the main journal starting at byte
+** offset PagerSavepoint.iOffset and continuing to
+** PagerSavepoint.iHdrOffset, or to the end of the main journal
+** file if PagerSavepoint.iHdrOffset is zero.
+**
+** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
+** back starting from the journal header immediately following
+** PagerSavepoint.iHdrOffset to the end of the main journal file.
+**
+** * Pages are then played back from the sub-journal file, starting
+** with the PagerSavepoint.iSubRec and continuing to the end of
+** the journal file.
+**
+** Throughout the rollback process, each time a page is rolled back, the
+** corresponding bit is set in a bitvec structure (variable pDone in the
+** implementation below). This is used to ensure that a page is only
+** rolled back the first time it is encountered in either journal.
+**
+** If pSavepoint is NULL, then pages are only played back from the main
+** journal file. There is no need for a bitvec in this case.
+**
+** In either case, before playback commences the Pager.dbSize variable
+** is reset to the value that it held at the start of the savepoint
+** (or transaction). No page with a page-number greater than this value
+** is played back. If one is encountered it is simply skipped.
+*/
+static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
+ i64 szJ; /* Effective size of the main journal */
+ i64 iHdrOff; /* End of first segment of main-journal records */
+ int rc = SQLITE_OK; /* Return code */
+ Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
+
+ assert( pPager->eState!=PAGER_ERROR );
+ assert( pPager->eState>=PAGER_WRITER_LOCKED );
+
+ /* Allocate a bitvec to use to store the set of pages rolled back */
+ if( pSavepoint ){
+ pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
+ if( !pDone ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ }
+
+ /* Set the database size back to the value it was before the savepoint
+ ** being reverted was opened.
+ */
+ pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
+ pPager->changeCountDone = pPager->tempFile;
+
+ if( !pSavepoint && pagerUseWal(pPager) ){
+ return pagerRollbackWal(pPager);
+ }
+
+ /* Use pPager->journalOff as the effective size of the main rollback
+ ** journal. The actual file might be larger than this in
+ ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
+ ** past pPager->journalOff is off-limits to us.
+ */
+ szJ = pPager->journalOff;
+ assert( pagerUseWal(pPager)==0 || szJ==0 );
+
+ /* Begin by rolling back records from the main journal starting at
+ ** PagerSavepoint.iOffset and continuing to the next journal header.
+ ** There might be records in the main journal that have a page number
+ ** greater than the current database size (pPager->dbSize) but those
+ ** will be skipped automatically. Pages are added to pDone as they
+ ** are played back.
+ */
+ if( pSavepoint && !pagerUseWal(pPager) ){
+ iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
+ pPager->journalOff = pSavepoint->iOffset;
+ while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
+ rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
+ }
+ assert( rc!=SQLITE_DONE );
+ }else{
+ pPager->journalOff = 0;
+ }
+
+ /* Continue rolling back records out of the main journal starting at
+ ** the first journal header seen and continuing until the effective end
+ ** of the main journal file. Continue to skip out-of-range pages and
+ ** continue adding pages rolled back to pDone.
+ */
+ while( rc==SQLITE_OK && pPager->journalOff<szJ ){
+ u32 ii; /* Loop counter */
+ u32 nJRec = 0; /* Number of Journal Records */
+ u32 dummy;
+ rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
+ assert( rc!=SQLITE_DONE );
+
+ /*
+ ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
+ ** test is related to ticket #2565. See the discussion in the
+ ** pager_playback() function for additional information.
+ */
+ if( nJRec==0
+ && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
+ ){
+ nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
+ }
+ for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
+ rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
+ }
+ assert( rc!=SQLITE_DONE );
+ }
+ assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
+
+ /* Finally, rollback pages from the sub-journal. Page that were
+ ** previously rolled back out of the main journal (and are hence in pDone)
+ ** will be skipped. Out-of-range pages are also skipped.
+ */
+ if( pSavepoint ){
+ u32 ii; /* Loop counter */
+ i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
+
+ if( pagerUseWal(pPager) ){
+ rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
+ }
+ for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
+ assert( offset==(i64)ii*(4+pPager->pageSize) );
+ rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
+ }
+ assert( rc!=SQLITE_DONE );
+ }
+
+ sqlite3BitvecDestroy(pDone);
+ if( rc==SQLITE_OK ){
+ pPager->journalOff = szJ;
+ }
+
+ return rc;
+}
+
+/*
+** Change the maximum number of in-memory pages that are allowed
+** before attempting to recycle clean and unused pages.
+*/
+SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
+ sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
+}
+
+/*
+** Change the maximum number of in-memory pages that are allowed
+** before attempting to spill pages to journal.
+*/
+SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
+ return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
+}
+
+/*
+** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
+*/
+static void pagerFixMaplimit(Pager *pPager){
+#if SQLITE_MAX_MMAP_SIZE>0
+ sqlite3_file *fd = pPager->fd;
+ if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
+ sqlite3_int64 sz;
+ sz = pPager->szMmap;
+ pPager->bUseFetch = (sz>0);
+ setGetterMethod(pPager);
+ sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
+ }
+#endif
+}
+
+/*
+** Change the maximum size of any memory mapping made of the database file.
+*/
+SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
+ pPager->szMmap = szMmap;
+ pagerFixMaplimit(pPager);
+}
+
+/*
+** Free as much memory as possible from the pager.
+*/
+SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
+ sqlite3PcacheShrink(pPager->pPCache);
+}
+
+/*
+** Adjust settings of the pager to those specified in the pgFlags parameter.
+**
+** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
+** of the database to damage due to OS crashes or power failures by
+** changing the number of syncs()s when writing the journals.
+** There are four levels:
+**
+** OFF sqlite3OsSync() is never called. This is the default
+** for temporary and transient files.
+**
+** NORMAL The journal is synced once before writes begin on the
+** database. This is normally adequate protection, but
+** it is theoretically possible, though very unlikely,
+** that an inopertune power failure could leave the journal
+** in a state which would cause damage to the database
+** when it is rolled back.
+**
+** FULL The journal is synced twice before writes begin on the
+** database (with some additional information - the nRec field
+** of the journal header - being written in between the two
+** syncs). If we assume that writing a
+** single disk sector is atomic, then this mode provides
+** assurance that the journal will not be corrupted to the
+** point of causing damage to the database during rollback.
+**
+** EXTRA This is like FULL except that is also syncs the directory
+** that contains the rollback journal after the rollback
+** journal is unlinked.
+**
+** The above is for a rollback-journal mode. For WAL mode, OFF continues
+** to mean that no syncs ever occur. NORMAL means that the WAL is synced
+** prior to the start of checkpoint and that the database file is synced
+** at the conclusion of the checkpoint if the entire content of the WAL
+** was written back into the database. But no sync operations occur for
+** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
+** file is synced following each commit operation, in addition to the
+** syncs associated with NORMAL. There is no difference between FULL
+** and EXTRA for WAL mode.
+**
+** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
+** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
+** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
+** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
+** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
+** synchronous=FULL versus synchronous=NORMAL setting determines when
+** the xSync primitive is called and is relevant to all platforms.
+**
+** Numeric values associated with these states are OFF==1, NORMAL=2,
+** and FULL=3.
+*/
+#ifndef SQLITE_OMIT_PAGER_PRAGMAS
+SQLITE_PRIVATE void sqlite3PagerSetFlags(
+ Pager *pPager, /* The pager to set safety level for */
+ unsigned pgFlags /* Various flags */
+){
+ unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
+ if( pPager->tempFile ){
+ pPager->noSync = 1;
+ pPager->fullSync = 0;
+ pPager->extraSync = 0;
+ }else{
+ pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
+ pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
+ pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
+ }
+ if( pPager->noSync ){
+ pPager->syncFlags = 0;
+ }else if( pgFlags & PAGER_FULLFSYNC ){
+ pPager->syncFlags = SQLITE_SYNC_FULL;
+ }else{
+ pPager->syncFlags = SQLITE_SYNC_NORMAL;
+ }
+ pPager->walSyncFlags = (pPager->syncFlags<<2);
+ if( pPager->fullSync ){
+ pPager->walSyncFlags |= pPager->syncFlags;
+ }
+ if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
+ pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
+ }
+ if( pgFlags & PAGER_CACHESPILL ){
+ pPager->doNotSpill &= ~SPILLFLAG_OFF;
+ }else{
+ pPager->doNotSpill |= SPILLFLAG_OFF;
+ }
+}
+#endif
+
+/*
+** The following global variable is incremented whenever the library
+** attempts to open a temporary file. This information is used for
+** testing and analysis only.
+*/
+#ifdef SQLITE_TEST
+SQLITE_API int sqlite3_opentemp_count = 0;
+#endif
+
+/*
+** Open a temporary file.
+**
+** Write the file descriptor into *pFile. Return SQLITE_OK on success
+** or some other error code if we fail. The OS will automatically
+** delete the temporary file when it is closed.
+**
+** The flags passed to the VFS layer xOpen() call are those specified
+** by parameter vfsFlags ORed with the following:
+**
+** SQLITE_OPEN_READWRITE
+** SQLITE_OPEN_CREATE
+** SQLITE_OPEN_EXCLUSIVE
+** SQLITE_OPEN_DELETEONCLOSE
+*/
+static int pagerOpentemp(
+ Pager *pPager, /* The pager object */
+ sqlite3_file *pFile, /* Write the file descriptor here */
+ int vfsFlags /* Flags passed through to the VFS */
+){
+ int rc; /* Return code */
+
+#ifdef SQLITE_TEST
+ sqlite3_opentemp_count++; /* Used for testing and analysis only */
+#endif
+
+ vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
+ SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
+ rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
+ assert( rc!=SQLITE_OK || isOpen(pFile) );
+ return rc;
+}
+
+/*
+** Set the busy handler function.
+**
+** The pager invokes the busy-handler if sqlite3OsLock() returns
+** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
+** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
+** lock. It does *not* invoke the busy handler when upgrading from
+** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
+** (which occurs during hot-journal rollback). Summary:
+**
+** Transition | Invokes xBusyHandler
+** --------------------------------------------------------
+** NO_LOCK -> SHARED_LOCK | Yes
+** SHARED_LOCK -> RESERVED_LOCK | No
+** SHARED_LOCK -> EXCLUSIVE_LOCK | No
+** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
+**
+** If the busy-handler callback returns non-zero, the lock is
+** retried. If it returns zero, then the SQLITE_BUSY error is
+** returned to the caller of the pager API function.
+*/
+SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(
+ Pager *pPager, /* Pager object */
+ int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
+ void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
+){
+ void **ap;
+ pPager->xBusyHandler = xBusyHandler;
+ pPager->pBusyHandlerArg = pBusyHandlerArg;
+ ap = (void **)&pPager->xBusyHandler;
+ assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
+ assert( ap[1]==pBusyHandlerArg );
+ sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
+}
+
+/*
+** Change the page size used by the Pager object. The new page size
+** is passed in *pPageSize.
+**
+** If the pager is in the error state when this function is called, it
+** is a no-op. The value returned is the error state error code (i.e.
+** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
+**
+** Otherwise, if all of the following are true:
+**
+** * the new page size (value of *pPageSize) is valid (a power
+** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
+**
+** * there are no outstanding page references, and
+**
+** * the database is either not an in-memory database or it is
+** an in-memory database that currently consists of zero pages.
+**
+** then the pager object page size is set to *pPageSize.
+**
+** If the page size is changed, then this function uses sqlite3PagerMalloc()
+** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
+** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
+** In all other cases, SQLITE_OK is returned.
+**
+** If the page size is not changed, either because one of the enumerated
+** conditions above is not true, the pager was in error state when this
+** function was called, or because the memory allocation attempt failed,
+** then *pPageSize is set to the old, retained page size before returning.
+*/
+SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
+ int rc = SQLITE_OK;
+
+ /* It is not possible to do a full assert_pager_state() here, as this
+ ** function may be called from within PagerOpen(), before the state
+ ** of the Pager object is internally consistent.
+ **
+ ** At one point this function returned an error if the pager was in
+ ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
+ ** there is at least one outstanding page reference, this function
+ ** is a no-op for that case anyhow.
+ */
+
+ u32 pageSize = *pPageSize;
+ assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
+ if( (pPager->memDb==0 || pPager->dbSize==0)
+ && sqlite3PcacheRefCount(pPager->pPCache)==0
+ && pageSize && pageSize!=(u32)pPager->pageSize
+ ){
+ char *pNew = NULL; /* New temp space */
+ i64 nByte = 0;
+
+ if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
+ rc = sqlite3OsFileSize(pPager->fd, &nByte);
+ }
+ if( rc==SQLITE_OK ){
+ /* 8 bytes of zeroed overrun space is sufficient so that the b-tree
+ * cell header parser will never run off the end of the allocation */
+ pNew = (char *)sqlite3PageMalloc(pageSize+8);
+ if( !pNew ){
+ rc = SQLITE_NOMEM_BKPT;
+ }else{
+ memset(pNew+pageSize, 0, 8);
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ pager_reset(pPager);
+ rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
+ }
+ if( rc==SQLITE_OK ){
+ sqlite3PageFree(pPager->pTmpSpace);
+ pPager->pTmpSpace = pNew;
+ pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
+ pPager->pageSize = pageSize;
+ }else{
+ sqlite3PageFree(pNew);
+ }
+ }
+
+ *pPageSize = pPager->pageSize;
+ if( rc==SQLITE_OK ){
+ if( nReserve<0 ) nReserve = pPager->nReserve;
+ assert( nReserve>=0 && nReserve<1000 );
+ pPager->nReserve = (i16)nReserve;
+ pagerFixMaplimit(pPager);
+ }
+ return rc;
+}
+
+/*
+** Return a pointer to the "temporary page" buffer held internally
+** by the pager. This is a buffer that is big enough to hold the
+** entire content of a database page. This buffer is used internally
+** during rollback and will be overwritten whenever a rollback
+** occurs. But other modules are free to use it too, as long as
+** no rollbacks are happening.
+*/
+SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
+ return pPager->pTmpSpace;
+}
+
+/*
+** Attempt to set the maximum database page count if mxPage is positive.
+** Make no changes if mxPage is zero or negative. And never reduce the
+** maximum page count below the current size of the database.
+**
+** Regardless of mxPage, return the current maximum page count.
+*/
+SQLITE_PRIVATE Pgno sqlite3PagerMaxPageCount(Pager *pPager, Pgno mxPage){
+ if( mxPage>0 ){
+ pPager->mxPgno = mxPage;
+ }
+ assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
+ /* assert( pPager->mxPgno>=pPager->dbSize ); */
+ /* OP_MaxPgcnt ensures that the parameter passed to this function is not
+ ** less than the total number of valid pages in the database. But this
+ ** may be less than Pager.dbSize, and so the assert() above is not valid */
+ return pPager->mxPgno;
+}
+
+/*
+** The following set of routines are used to disable the simulated
+** I/O error mechanism. These routines are used to avoid simulated
+** errors in places where we do not care about errors.
+**
+** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
+** and generate no code.
+*/
+#ifdef SQLITE_TEST
+SQLITE_API extern int sqlite3_io_error_pending;
+SQLITE_API extern int sqlite3_io_error_hit;
+static int saved_cnt;
+void disable_simulated_io_errors(void){
+ saved_cnt = sqlite3_io_error_pending;
+ sqlite3_io_error_pending = -1;
+}
+void enable_simulated_io_errors(void){
+ sqlite3_io_error_pending = saved_cnt;
+}
+#else
+# define disable_simulated_io_errors()
+# define enable_simulated_io_errors()
+#endif
+
+/*
+** Read the first N bytes from the beginning of the file into memory
+** that pDest points to.
+**
+** If the pager was opened on a transient file (zFilename==""), or
+** opened on a file less than N bytes in size, the output buffer is
+** zeroed and SQLITE_OK returned. The rationale for this is that this
+** function is used to read database headers, and a new transient or
+** zero sized database has a header than consists entirely of zeroes.
+**
+** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
+** the error code is returned to the caller and the contents of the
+** output buffer undefined.
+*/
+SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
+ int rc = SQLITE_OK;
+ memset(pDest, 0, N);
+ assert( isOpen(pPager->fd) || pPager->tempFile );
+
+ /* This routine is only called by btree immediately after creating
+ ** the Pager object. There has not been an opportunity to transition
+ ** to WAL mode yet.
+ */
+ assert( !pagerUseWal(pPager) );
+
+ if( isOpen(pPager->fd) ){
+ IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
+ rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
+ if( rc==SQLITE_IOERR_SHORT_READ ){
+ rc = SQLITE_OK;
+ }
+ }
+ return rc;
+}
+
+/*
+** This function may only be called when a read-transaction is open on
+** the pager. It returns the total number of pages in the database.
+**
+** However, if the file is between 1 and <page-size> bytes in size, then
+** this is considered a 1 page file.
+*/
+SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
+ assert( pPager->eState>=PAGER_READER );
+ assert( pPager->eState!=PAGER_WRITER_FINISHED );
+ *pnPage = (int)pPager->dbSize;
+}
+
+
+/*
+** Try to obtain a lock of type locktype on the database file. If
+** a similar or greater lock is already held, this function is a no-op
+** (returning SQLITE_OK immediately).
+**
+** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
+** the busy callback if the lock is currently not available. Repeat
+** until the busy callback returns false or until the attempt to
+** obtain the lock succeeds.
+**
+** Return SQLITE_OK on success and an error code if we cannot obtain
+** the lock. If the lock is obtained successfully, set the Pager.state
+** variable to locktype before returning.
+*/
+static int pager_wait_on_lock(Pager *pPager, int locktype){
+ int rc; /* Return code */
+
+ /* Check that this is either a no-op (because the requested lock is
+ ** already held), or one of the transitions that the busy-handler
+ ** may be invoked during, according to the comment above
+ ** sqlite3PagerSetBusyhandler().
+ */
+ assert( (pPager->eLock>=locktype)
+ || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
+ || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
+ );
+
+ do {
+ rc = pagerLockDb(pPager, locktype);
+ }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
+ return rc;
+}
+
+/*
+** Function assertTruncateConstraint(pPager) checks that one of the
+** following is true for all dirty pages currently in the page-cache:
+**
+** a) The page number is less than or equal to the size of the
+** current database image, in pages, OR
+**
+** b) if the page content were written at this time, it would not
+** be necessary to write the current content out to the sub-journal
+** (as determined by function subjRequiresPage()).
+**
+** If the condition asserted by this function were not true, and the
+** dirty page were to be discarded from the cache via the pagerStress()
+** routine, pagerStress() would not write the current page content to
+** the database file. If a savepoint transaction were rolled back after
+** this happened, the correct behavior would be to restore the current
+** content of the page. However, since this content is not present in either
+** the database file or the portion of the rollback journal and
+** sub-journal rolled back the content could not be restored and the
+** database image would become corrupt. It is therefore fortunate that
+** this circumstance cannot arise.
+*/
+#if defined(SQLITE_DEBUG)
+static void assertTruncateConstraintCb(PgHdr *pPg){
+ assert( pPg->flags&PGHDR_DIRTY );
+ assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
+}
+static void assertTruncateConstraint(Pager *pPager){
+ sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
+}
+#else
+# define assertTruncateConstraint(pPager)
+#endif
+
+/*
+** Truncate the in-memory database file image to nPage pages. This
+** function does not actually modify the database file on disk. It
+** just sets the internal state of the pager object so that the
+** truncation will be done when the current transaction is committed.
+**
+** This function is only called right before committing a transaction.
+** Once this function has been called, the transaction must either be
+** rolled back or committed. It is not safe to call this function and
+** then continue writing to the database.
+*/
+SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
+ assert( pPager->dbSize>=nPage );
+ assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
+ pPager->dbSize = nPage;
+
+ /* At one point the code here called assertTruncateConstraint() to
+ ** ensure that all pages being truncated away by this operation are,
+ ** if one or more savepoints are open, present in the savepoint
+ ** journal so that they can be restored if the savepoint is rolled
+ ** back. This is no longer necessary as this function is now only
+ ** called right before committing a transaction. So although the
+ ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
+ ** they cannot be rolled back. So the assertTruncateConstraint() call
+ ** is no longer correct. */
+}
+
+
+/*
+** This function is called before attempting a hot-journal rollback. It
+** syncs the journal file to disk, then sets pPager->journalHdr to the
+** size of the journal file so that the pager_playback() routine knows
+** that the entire journal file has been synced.
+**
+** Syncing a hot-journal to disk before attempting to roll it back ensures
+** that if a power-failure occurs during the rollback, the process that
+** attempts rollback following system recovery sees the same journal
+** content as this process.
+**
+** If everything goes as planned, SQLITE_OK is returned. Otherwise,
+** an SQLite error code.
+*/
+static int pagerSyncHotJournal(Pager *pPager){
+ int rc = SQLITE_OK;
+ if( !pPager->noSync ){
+ rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
+ }
+ return rc;
+}
+
+#if SQLITE_MAX_MMAP_SIZE>0
+/*
+** Obtain a reference to a memory mapped page object for page number pgno.
+** The new object will use the pointer pData, obtained from xFetch().
+** If successful, set *ppPage to point to the new page reference
+** and return SQLITE_OK. Otherwise, return an SQLite error code and set
+** *ppPage to zero.
+**
+** Page references obtained by calling this function should be released
+** by calling pagerReleaseMapPage().
+*/
+static int pagerAcquireMapPage(
+ Pager *pPager, /* Pager object */
+ Pgno pgno, /* Page number */
+ void *pData, /* xFetch()'d data for this page */
+ PgHdr **ppPage /* OUT: Acquired page object */
+){
+ PgHdr *p; /* Memory mapped page to return */
+
+ if( pPager->pMmapFreelist ){
+ *ppPage = p = pPager->pMmapFreelist;
+ pPager->pMmapFreelist = p->pDirty;
+ p->pDirty = 0;
+ assert( pPager->nExtra>=8 );
+ memset(p->pExtra, 0, 8);
+ }else{
+ *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
+ if( p==0 ){
+ sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
+ return SQLITE_NOMEM_BKPT;
+ }
+ p->pExtra = (void *)&p[1];
+ p->flags = PGHDR_MMAP;
+ p->nRef = 1;
+ p->pPager = pPager;
+ }
+
+ assert( p->pExtra==(void *)&p[1] );
+ assert( p->pPage==0 );
+ assert( p->flags==PGHDR_MMAP );
+ assert( p->pPager==pPager );
+ assert( p->nRef==1 );
+
+ p->pgno = pgno;
+ p->pData = pData;
+ pPager->nMmapOut++;
+
+ return SQLITE_OK;
+}
+#endif
+
+/*
+** Release a reference to page pPg. pPg must have been returned by an
+** earlier call to pagerAcquireMapPage().
+*/
+static void pagerReleaseMapPage(PgHdr *pPg){
+ Pager *pPager = pPg->pPager;
+ pPager->nMmapOut--;
+ pPg->pDirty = pPager->pMmapFreelist;
+ pPager->pMmapFreelist = pPg;
+
+ assert( pPager->fd->pMethods->iVersion>=3 );
+ sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
+}
+
+/*
+** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
+*/
+static void pagerFreeMapHdrs(Pager *pPager){
+ PgHdr *p;
+ PgHdr *pNext;
+ for(p=pPager->pMmapFreelist; p; p=pNext){
+ pNext = p->pDirty;
+ sqlite3_free(p);
+ }
+}
+
+/* Verify that the database file has not be deleted or renamed out from
+** under the pager. Return SQLITE_OK if the database is still where it ought
+** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
+** code from sqlite3OsAccess()) if the database has gone missing.
+*/
+static int databaseIsUnmoved(Pager *pPager){
+ int bHasMoved = 0;
+ int rc;
+
+ if( pPager->tempFile ) return SQLITE_OK;
+ if( pPager->dbSize==0 ) return SQLITE_OK;
+ assert( pPager->zFilename && pPager->zFilename[0] );
+ rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
+ if( rc==SQLITE_NOTFOUND ){
+ /* If the HAS_MOVED file-control is unimplemented, assume that the file
+ ** has not been moved. That is the historical behavior of SQLite: prior to
+ ** version 3.8.3, it never checked */
+ rc = SQLITE_OK;
+ }else if( rc==SQLITE_OK && bHasMoved ){
+ rc = SQLITE_READONLY_DBMOVED;
+ }
+ return rc;
+}
+
+
+/*
+** Shutdown the page cache. Free all memory and close all files.
+**
+** If a transaction was in progress when this routine is called, that
+** transaction is rolled back. All outstanding pages are invalidated
+** and their memory is freed. Any attempt to use a page associated
+** with this page cache after this function returns will likely
+** result in a coredump.
+**
+** This function always succeeds. If a transaction is active an attempt
+** is made to roll it back. If an error occurs during the rollback
+** a hot journal may be left in the filesystem but no error is returned
+** to the caller.
+*/
+SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
+ u8 *pTmp = (u8*)pPager->pTmpSpace;
+ assert( db || pagerUseWal(pPager)==0 );
+ assert( assert_pager_state(pPager) );
+ disable_simulated_io_errors();
+ sqlite3BeginBenignMalloc();
+ pagerFreeMapHdrs(pPager);
+ /* pPager->errCode = 0; */
+ pPager->exclusiveMode = 0;
+#ifndef SQLITE_OMIT_WAL
+ {
+ u8 *a = 0;
+ assert( db || pPager->pWal==0 );
+ if( db && 0==(db->flags & SQLITE_NoCkptOnClose)
+ && SQLITE_OK==databaseIsUnmoved(pPager)
+ ){
+ a = pTmp;
+ }
+ sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a);
+ pPager->pWal = 0;
+ }
+#endif
+ pager_reset(pPager);
+ if( MEMDB ){
+ pager_unlock(pPager);
+ }else{
+ /* If it is open, sync the journal file before calling UnlockAndRollback.
+ ** If this is not done, then an unsynced portion of the open journal
+ ** file may be played back into the database. If a power failure occurs
+ ** while this is happening, the database could become corrupt.
+ **
+ ** If an error occurs while trying to sync the journal, shift the pager
+ ** into the ERROR state. This causes UnlockAndRollback to unlock the
+ ** database and close the journal file without attempting to roll it
+ ** back or finalize it. The next database user will have to do hot-journal
+ ** rollback before accessing the database file.
+ */
+ if( isOpen(pPager->jfd) ){
+ pager_error(pPager, pagerSyncHotJournal(pPager));
+ }
+ pagerUnlockAndRollback(pPager);
+ }
+ sqlite3EndBenignMalloc();
+ enable_simulated_io_errors();
+ PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
+ IOTRACE(("CLOSE %p\n", pPager))
+ sqlite3OsClose(pPager->jfd);
+ sqlite3OsClose(pPager->fd);
+ sqlite3PageFree(pTmp);
+ sqlite3PcacheClose(pPager->pPCache);
+ assert( !pPager->aSavepoint && !pPager->pInJournal );
+ assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
+
+ sqlite3_free(pPager);
+ return SQLITE_OK;
+}
+
+#if !defined(NDEBUG) || defined(SQLITE_TEST)
+/*
+** Return the page number for page pPg.
+*/
+SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
+ return pPg->pgno;
+}
+#endif
+
+/*
+** Increment the reference count for page pPg.
+*/
+SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
+ sqlite3PcacheRef(pPg);
+}
+
+/*
+** Sync the journal. In other words, make sure all the pages that have
+** been written to the journal have actually reached the surface of the
+** disk and can be restored in the event of a hot-journal rollback.
+**
+** If the Pager.noSync flag is set, then this function is a no-op.
+** Otherwise, the actions required depend on the journal-mode and the
+** device characteristics of the file-system, as follows:
+**
+** * If the journal file is an in-memory journal file, no action need
+** be taken.
+**
+** * Otherwise, if the device does not support the SAFE_APPEND property,
+** then the nRec field of the most recently written journal header
+** is updated to contain the number of journal records that have
+** been written following it. If the pager is operating in full-sync
+** mode, then the journal file is synced before this field is updated.
+**
+** * If the device does not support the SEQUENTIAL property, then
+** journal file is synced.
+**
+** Or, in pseudo-code:
+**
+** if( NOT <in-memory journal> ){
+** if( NOT SAFE_APPEND ){
+** if( <full-sync mode> ) xSync(<journal file>);
+** <update nRec field>
+** }
+** if( NOT SEQUENTIAL ) xSync(<journal file>);
+** }
+**
+** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
+** page currently held in memory before returning SQLITE_OK. If an IO
+** error is encountered, then the IO error code is returned to the caller.
+*/
+static int syncJournal(Pager *pPager, int newHdr){
+ int rc; /* Return code */
+
+ assert( pPager->eState==PAGER_WRITER_CACHEMOD
+ || pPager->eState==PAGER_WRITER_DBMOD
+ );
+ assert( assert_pager_state(pPager) );
+ assert( !pagerUseWal(pPager) );
+
+ rc = sqlite3PagerExclusiveLock(pPager);
+ if( rc!=SQLITE_OK ) return rc;
+
+ if( !pPager->noSync ){
+ assert( !pPager->tempFile );
+ if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
+ const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
+ assert( isOpen(pPager->jfd) );
+
+ if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
+ /* This block deals with an obscure problem. If the last connection
+ ** that wrote to this database was operating in persistent-journal
+ ** mode, then the journal file may at this point actually be larger
+ ** than Pager.journalOff bytes. If the next thing in the journal
+ ** file happens to be a journal-header (written as part of the
+ ** previous connection's transaction), and a crash or power-failure
+ ** occurs after nRec is updated but before this connection writes
+ ** anything else to the journal file (or commits/rolls back its
+ ** transaction), then SQLite may become confused when doing the
+ ** hot-journal rollback following recovery. It may roll back all
+ ** of this connections data, then proceed to rolling back the old,
+ ** out-of-date data that follows it. Database corruption.
+ **
+ ** To work around this, if the journal file does appear to contain
+ ** a valid header following Pager.journalOff, then write a 0x00
+ ** byte to the start of it to prevent it from being recognized.
+ **
+ ** Variable iNextHdrOffset is set to the offset at which this
+ ** problematic header will occur, if it exists. aMagic is used
+ ** as a temporary buffer to inspect the first couple of bytes of
+ ** the potential journal header.
+ */
+ i64 iNextHdrOffset;
+ u8 aMagic[8];
+ u8 zHeader[sizeof(aJournalMagic)+4];
+
+ memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
+ put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
+
+ iNextHdrOffset = journalHdrOffset(pPager);
+ rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
+ if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
+ static const u8 zerobyte = 0;
+ rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
+ }
+ if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
+ return rc;
+ }
+
+ /* Write the nRec value into the journal file header. If in
+ ** full-synchronous mode, sync the journal first. This ensures that
+ ** all data has really hit the disk before nRec is updated to mark
+ ** it as a candidate for rollback.
+ **
+ ** This is not required if the persistent media supports the
+ ** SAFE_APPEND property. Because in this case it is not possible
+ ** for garbage data to be appended to the file, the nRec field
+ ** is populated with 0xFFFFFFFF when the journal header is written
+ ** and never needs to be updated.
+ */
+ if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
+ PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
+ IOTRACE(("JSYNC %p\n", pPager))
+ rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
+ if( rc!=SQLITE_OK ) return rc;
+ }
+ IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
+ rc = sqlite3OsWrite(
+ pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
+ );
+ if( rc!=SQLITE_OK ) return rc;
+ }
+ if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
+ PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
+ IOTRACE(("JSYNC %p\n", pPager))
+ rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
+ (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
+ );
+ if( rc!=SQLITE_OK ) return rc;
+ }
+
+ pPager->journalHdr = pPager->journalOff;
+ if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
+ pPager->nRec = 0;
+ rc = writeJournalHdr(pPager);
+ if( rc!=SQLITE_OK ) return rc;
+ }
+ }else{
+ pPager->journalHdr = pPager->journalOff;
+ }
+ }
+
+ /* Unless the pager is in noSync mode, the journal file was just
+ ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
+ ** all pages.
+ */
+ sqlite3PcacheClearSyncFlags(pPager->pPCache);
+ pPager->eState = PAGER_WRITER_DBMOD;
+ assert( assert_pager_state(pPager) );
+ return SQLITE_OK;
+}
+
+/*
+** The argument is the first in a linked list of dirty pages connected
+** by the PgHdr.pDirty pointer. This function writes each one of the
+** in-memory pages in the list to the database file. The argument may
+** be NULL, representing an empty list. In this case this function is
+** a no-op.
+**
+** The pager must hold at least a RESERVED lock when this function
+** is called. Before writing anything to the database file, this lock
+** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
+** SQLITE_BUSY is returned and no data is written to the database file.
+**
+** If the pager is a temp-file pager and the actual file-system file
+** is not yet open, it is created and opened before any data is
+** written out.
+**
+** Once the lock has been upgraded and, if necessary, the file opened,
+** the pages are written out to the database file in list order. Writing
+** a page is skipped if it meets either of the following criteria:
+**
+** * The page number is greater than Pager.dbSize, or
+** * The PGHDR_DONT_WRITE flag is set on the page.
+**
+** If writing out a page causes the database file to grow, Pager.dbFileSize
+** is updated accordingly. If page 1 is written out, then the value cached
+** in Pager.dbFileVers[] is updated to match the new value stored in
+** the database file.
+**
+** If everything is successful, SQLITE_OK is returned. If an IO error
+** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
+** be obtained, SQLITE_BUSY is returned.
+*/
+static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
+ int rc = SQLITE_OK; /* Return code */
+
+ /* This function is only called for rollback pagers in WRITER_DBMOD state. */
+ assert( !pagerUseWal(pPager) );
+ assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
+ assert( pPager->eLock==EXCLUSIVE_LOCK );
+ assert( isOpen(pPager->fd) || pList->pDirty==0 );
+
+ /* If the file is a temp-file has not yet been opened, open it now. It
+ ** is not possible for rc to be other than SQLITE_OK if this branch
+ ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
+ */
+ if( !isOpen(pPager->fd) ){
+ assert( pPager->tempFile && rc==SQLITE_OK );
+ rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
+ }
+
+ /* Before the first write, give the VFS a hint of what the final
+ ** file size will be.
+ */
+ assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
+ if( rc==SQLITE_OK
+ && pPager->dbHintSize<pPager->dbSize
+ && (pList->pDirty || pList->pgno>pPager->dbHintSize)
+ ){
+ sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
+ sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
+ pPager->dbHintSize = pPager->dbSize;
+ }
+
+ while( rc==SQLITE_OK && pList ){
+ Pgno pgno = pList->pgno;
+
+ /* If there are dirty pages in the page cache with page numbers greater
+ ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
+ ** make the file smaller (presumably by auto-vacuum code). Do not write
+ ** any such pages to the file.
+ **
+ ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
+ ** set (set by sqlite3PagerDontWrite()).
+ */
+ if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
+ i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
+ char *pData; /* Data to write */
+
+ assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
+ if( pList->pgno==1 ) pager_write_changecounter(pList);
+
+ pData = pList->pData;
+
+ /* Write out the page data. */
+ rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
+
+ /* If page 1 was just written, update Pager.dbFileVers to match
+ ** the value now stored in the database file. If writing this
+ ** page caused the database file to grow, update dbFileSize.
+ */
+ if( pgno==1 ){
+ memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
+ }
+ if( pgno>pPager->dbFileSize ){
+ pPager->dbFileSize = pgno;
+ }
+ pPager->aStat[PAGER_STAT_WRITE]++;
+
+ /* Update any backup objects copying the contents of this pager. */
+ sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
+
+ PAGERTRACE(("STORE %d page %d hash(%08x)\n",
+ PAGERID(pPager), pgno, pager_pagehash(pList)));
+ IOTRACE(("PGOUT %p %d\n", pPager, pgno));
+ PAGER_INCR(sqlite3_pager_writedb_count);
+ }else{
+ PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
+ }
+ pager_set_pagehash(pList);
+ pList = pList->pDirty;
+ }
+
+ return rc;
+}
+
+/*
+** Ensure that the sub-journal file is open. If it is already open, this
+** function is a no-op.
+**
+** SQLITE_OK is returned if everything goes according to plan. An
+** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
+** fails.
+*/
+static int openSubJournal(Pager *pPager){
+ int rc = SQLITE_OK;
+ if( !isOpen(pPager->sjfd) ){
+ const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
+ | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
+ | SQLITE_OPEN_DELETEONCLOSE;
+ int nStmtSpill = sqlite3Config.nStmtSpill;
+ if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
+ nStmtSpill = -1;
+ }
+ rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
+ }
+ return rc;
+}
+
+/*
+** Append a record of the current state of page pPg to the sub-journal.
+**
+** If successful, set the bit corresponding to pPg->pgno in the bitvecs
+** for all open savepoints before returning.
+**
+** This function returns SQLITE_OK if everything is successful, an IO
+** error code if the attempt to write to the sub-journal fails, or
+** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
+** bitvec.
+*/
+static int subjournalPage(PgHdr *pPg){
+ int rc = SQLITE_OK;
+ Pager *pPager = pPg->pPager;
+ if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
+
+ /* Open the sub-journal, if it has not already been opened */
+ assert( pPager->useJournal );
+ assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
+ assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
+ assert( pagerUseWal(pPager)
+ || pageInJournal(pPager, pPg)
+ || pPg->pgno>pPager->dbOrigSize
+ );
+ rc = openSubJournal(pPager);
+
+ /* If the sub-journal was opened successfully (or was already open),
+ ** write the journal record into the file. */
+ if( rc==SQLITE_OK ){
+ void *pData = pPg->pData;
+ i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
+ char *pData2;
+ pData2 = pData;
+ PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
+ rc = write32bits(pPager->sjfd, offset, pPg->pgno);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
+ }
+ }
+ }
+ if( rc==SQLITE_OK ){
+ pPager->nSubRec++;
+ assert( pPager->nSavepoint>0 );
+ rc = addToSavepointBitvecs(pPager, pPg->pgno);
+ }
+ return rc;
+}
+static int subjournalPageIfRequired(PgHdr *pPg){
+ if( subjRequiresPage(pPg) ){
+ return subjournalPage(pPg);
+ }else{
+ return SQLITE_OK;
+ }
+}
+
+/*
+** This function is called by the pcache layer when it has reached some
+** soft memory limit. The first argument is a pointer to a Pager object
+** (cast as a void*). The pager is always 'purgeable' (not an in-memory
+** database). The second argument is a reference to a page that is
+** currently dirty but has no outstanding references. The page
+** is always associated with the Pager object passed as the first
+** argument.
+**
+** The job of this function is to make pPg clean by writing its contents
+** out to the database file, if possible. This may involve syncing the
+** journal file.
+**
+** If successful, sqlite3PcacheMakeClean() is called on the page and
+** SQLITE_OK returned. If an IO error occurs while trying to make the
+** page clean, the IO error code is returned. If the page cannot be
+** made clean for some other reason, but no error occurs, then SQLITE_OK
+** is returned by sqlite3PcacheMakeClean() is not called.
+*/
+static int pagerStress(void *p, PgHdr *pPg){
+ Pager *pPager = (Pager *)p;
+ int rc = SQLITE_OK;
+
+ assert( pPg->pPager==pPager );
+ assert( pPg->flags&PGHDR_DIRTY );
+
+ /* The doNotSpill NOSYNC bit is set during times when doing a sync of
+ ** journal (and adding a new header) is not allowed. This occurs
+ ** during calls to sqlite3PagerWrite() while trying to journal multiple
+ ** pages belonging to the same sector.
+ **
+ ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
+ ** regardless of whether or not a sync is required. This is set during
+ ** a rollback or by user request, respectively.
+ **
+ ** Spilling is also prohibited when in an error state since that could
+ ** lead to database corruption. In the current implementation it
+ ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
+ ** while in the error state, hence it is impossible for this routine to
+ ** be called in the error state. Nevertheless, we include a NEVER()
+ ** test for the error state as a safeguard against future changes.
+ */
+ if( NEVER(pPager->errCode) ) return SQLITE_OK;
+ testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
+ testcase( pPager->doNotSpill & SPILLFLAG_OFF );
+ testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
+ if( pPager->doNotSpill
+ && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
+ || (pPg->flags & PGHDR_NEED_SYNC)!=0)
+ ){
+ return SQLITE_OK;
+ }
+
+ pPager->aStat[PAGER_STAT_SPILL]++;
+ pPg->pDirty = 0;
+ if( pagerUseWal(pPager) ){
+ /* Write a single frame for this page to the log. */
+ rc = subjournalPageIfRequired(pPg);
+ if( rc==SQLITE_OK ){
+ rc = pagerWalFrames(pPager, pPg, 0, 0);
+ }
+ }else{
+
+#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
+ if( pPager->tempFile==0 ){
+ rc = sqlite3JournalCreate(pPager->jfd);
+ if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
+ }
+#endif
+
+ /* Sync the journal file if required. */
+ if( pPg->flags&PGHDR_NEED_SYNC
+ || pPager->eState==PAGER_WRITER_CACHEMOD
+ ){
+ rc = syncJournal(pPager, 1);
+ }
+
+ /* Write the contents of the page out to the database file. */
+ if( rc==SQLITE_OK ){
+ assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
+ rc = pager_write_pagelist(pPager, pPg);
+ }
+ }
+
+ /* Mark the page as clean. */
+ if( rc==SQLITE_OK ){
+ PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
+ sqlite3PcacheMakeClean(pPg);
+ }
+
+ return pager_error(pPager, rc);
+}
+
+/*
+** Flush all unreferenced dirty pages to disk.
+*/
+SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
+ int rc = pPager->errCode;
+ if( !MEMDB ){
+ PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
+ assert( assert_pager_state(pPager) );
+ while( rc==SQLITE_OK && pList ){
+ PgHdr *pNext = pList->pDirty;
+ if( pList->nRef==0 ){
+ rc = pagerStress((void*)pPager, pList);
+ }
+ pList = pNext;
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Allocate and initialize a new Pager object and put a pointer to it
+** in *ppPager. The pager should eventually be freed by passing it
+** to sqlite3PagerClose().
+**
+** The zFilename argument is the path to the database file to open.
+** If zFilename is NULL then a randomly-named temporary file is created
+** and used as the file to be cached. Temporary files are be deleted
+** automatically when they are closed. If zFilename is ":memory:" then
+** all information is held in cache. It is never written to disk.
+** This can be used to implement an in-memory database.
+**
+** The nExtra parameter specifies the number of bytes of space allocated
+** along with each page reference. This space is available to the user
+** via the sqlite3PagerGetExtra() API. When a new page is allocated, the
+** first 8 bytes of this space are zeroed but the remainder is uninitialized.
+** (The extra space is used by btree as the MemPage object.)
+**
+** The flags argument is used to specify properties that affect the
+** operation of the pager. It should be passed some bitwise combination
+** of the PAGER_* flags.
+**
+** The vfsFlags parameter is a bitmask to pass to the flags parameter
+** of the xOpen() method of the supplied VFS when opening files.
+**
+** If the pager object is allocated and the specified file opened
+** successfully, SQLITE_OK is returned and *ppPager set to point to
+** the new pager object. If an error occurs, *ppPager is set to NULL
+** and error code returned. This function may return SQLITE_NOMEM
+** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
+** various SQLITE_IO_XXX errors.
+*/
+SQLITE_PRIVATE int sqlite3PagerOpen(
+ sqlite3_vfs *pVfs, /* The virtual file system to use */
+ Pager **ppPager, /* OUT: Return the Pager structure here */
+ const char *zFilename, /* Name of the database file to open */
+ int nExtra, /* Extra bytes append to each in-memory page */
+ int flags, /* flags controlling this file */
+ int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
+ void (*xReinit)(DbPage*) /* Function to reinitialize pages */
+){
+ u8 *pPtr;
+ Pager *pPager = 0; /* Pager object to allocate and return */
+ int rc = SQLITE_OK; /* Return code */
+ int tempFile = 0; /* True for temp files (incl. in-memory files) */
+ int memDb = 0; /* True if this is an in-memory file */
+#ifdef SQLITE_ENABLE_DESERIALIZE
+ int memJM = 0; /* Memory journal mode */
+#else
+# define memJM 0
+#endif
+ int readOnly = 0; /* True if this is a read-only file */
+ int journalFileSize; /* Bytes to allocate for each journal fd */
+ char *zPathname = 0; /* Full path to database file */
+ int nPathname = 0; /* Number of bytes in zPathname */
+ int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
+ int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
+ u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
+ const char *zUri = 0; /* URI args to copy */
+ int nUriByte = 1; /* Number of bytes of URI args at *zUri */
+ int nUri = 0; /* Number of URI parameters */
+
+ /* Figure out how much space is required for each journal file-handle
+ ** (there are two of them, the main journal and the sub-journal). */
+ journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
+
+ /* Set the output variable to NULL in case an error occurs. */
+ *ppPager = 0;
+
+#ifndef SQLITE_OMIT_MEMORYDB
+ if( flags & PAGER_MEMORY ){
+ memDb = 1;
+ if( zFilename && zFilename[0] ){
+ zPathname = sqlite3DbStrDup(0, zFilename);
+ if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
+ nPathname = sqlite3Strlen30(zPathname);
+ zFilename = 0;
+ }
+ }
+#endif
+
+ /* Compute and store the full pathname in an allocated buffer pointed
+ ** to by zPathname, length nPathname. Or, if this is a temporary file,
+ ** leave both nPathname and zPathname set to 0.
+ */
+ if( zFilename && zFilename[0] ){
+ const char *z;
+ nPathname = pVfs->mxPathname+1;
+ zPathname = sqlite3DbMallocRaw(0, nPathname*2);
+ if( zPathname==0 ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
+ rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
+ if( rc!=SQLITE_OK ){
+ if( rc==SQLITE_OK_SYMLINK ){
+ if( vfsFlags & SQLITE_OPEN_NOFOLLOW ){
+ rc = SQLITE_CANTOPEN_SYMLINK;
+ }else{
+ rc = SQLITE_OK;
+ }
+ }
+ }
+ nPathname = sqlite3Strlen30(zPathname);
+ z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
+ while( *z ){
+ z += strlen(z)+1;
+ z += strlen(z)+1;
+ nUri++;
+ }
+ nUriByte = (int)(&z[1] - zUri);
+ assert( nUriByte>=1 );
+ if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
+ /* This branch is taken when the journal path required by
+ ** the database being opened will be more than pVfs->mxPathname
+ ** bytes in length. This means the database cannot be opened,
+ ** as it will not be possible to open the journal file or even
+ ** check for a hot-journal before reading.
+ */
+ rc = SQLITE_CANTOPEN_BKPT;
+ }
+ if( rc!=SQLITE_OK ){
+ sqlite3DbFree(0, zPathname);
+ return rc;
+ }
+ }
+
+ /* Allocate memory for the Pager structure, PCache object, the
+ ** three file descriptors, the database file name and the journal
+ ** file name. The layout in memory is as follows:
+ **
+ ** Pager object (sizeof(Pager) bytes)
+ ** PCache object (sqlite3PcacheSize() bytes)
+ ** Database file handle (pVfs->szOsFile bytes)
+ ** Sub-journal file handle (journalFileSize bytes)
+ ** Main journal file handle (journalFileSize bytes)
+ ** Ptr back to the Pager (sizeof(Pager*) bytes)
+ ** \0\0\0\0 database prefix (4 bytes)
+ ** Database file name (nPathname+1 bytes)
+ ** URI query parameters (nUriByte bytes)
+ ** Journal filename (nPathname+8+1 bytes)
+ ** WAL filename (nPathname+4+1 bytes)
+ ** \0\0\0 terminator (3 bytes)
+ **
+ ** Some 3rd-party software, over which we have no control, depends on
+ ** the specific order of the filenames and the \0 separators between them
+ ** so that it can (for example) find the database filename given the WAL
+ ** filename without using the sqlite3_filename_database() API. This is a
+ ** misuse of SQLite and a bug in the 3rd-party software, but the 3rd-party
+ ** software is in widespread use, so we try to avoid changing the filename
+ ** order and formatting if possible. In particular, the details of the
+ ** filename format expected by 3rd-party software should be as follows:
+ **
+ ** - Main Database Path
+ ** - \0
+ ** - Multiple URI components consisting of:
+ ** - Key
+ ** - \0
+ ** - Value
+ ** - \0
+ ** - \0
+ ** - Journal Path
+ ** - \0
+ ** - WAL Path (zWALName)
+ ** - \0
+ **
+ ** The sqlite3_create_filename() interface and the databaseFilename() utility
+ ** that is used by sqlite3_filename_database() and kin also depend on the
+ ** specific formatting and order of the various filenames, so if the format
+ ** changes here, be sure to change it there as well.
+ */
+ pPtr = (u8 *)sqlite3MallocZero(
+ ROUND8(sizeof(*pPager)) + /* Pager structure */
+ ROUND8(pcacheSize) + /* PCache object */
+ ROUND8(pVfs->szOsFile) + /* The main db file */
+ journalFileSize * 2 + /* The two journal files */
+ sizeof(pPager) + /* Space to hold a pointer */
+ 4 + /* Database prefix */
+ nPathname + 1 + /* database filename */
+ nUriByte + /* query parameters */
+ nPathname + 8 + 1 + /* Journal filename */
+#ifndef SQLITE_OMIT_WAL
+ nPathname + 4 + 1 + /* WAL filename */
+#endif
+ 3 /* Terminator */
+ );
+ assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
+ if( !pPtr ){
+ sqlite3DbFree(0, zPathname);
+ return SQLITE_NOMEM_BKPT;
+ }
+ pPager = (Pager*)pPtr; pPtr += ROUND8(sizeof(*pPager));
+ pPager->pPCache = (PCache*)pPtr; pPtr += ROUND8(pcacheSize);
+ pPager->fd = (sqlite3_file*)pPtr; pPtr += ROUND8(pVfs->szOsFile);
+ pPager->sjfd = (sqlite3_file*)pPtr; pPtr += journalFileSize;
+ pPager->jfd = (sqlite3_file*)pPtr; pPtr += journalFileSize;
+ assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
+ memcpy(pPtr, &pPager, sizeof(pPager)); pPtr += sizeof(pPager);
+
+ /* Fill in the Pager.zFilename and pPager.zQueryParam fields */
+ pPtr += 4; /* Skip zero prefix */
+ pPager->zFilename = (char*)pPtr;
+ if( nPathname>0 ){
+ memcpy(pPtr, zPathname, nPathname); pPtr += nPathname + 1;
+ if( zUri ){
+ memcpy(pPtr, zUri, nUriByte); pPtr += nUriByte;
+ }else{
+ pPtr++;
+ }
+ }
+
+
+ /* Fill in Pager.zJournal */
+ if( nPathname>0 ){
+ pPager->zJournal = (char*)pPtr;
+ memcpy(pPtr, zPathname, nPathname); pPtr += nPathname;
+ memcpy(pPtr, "-journal",8); pPtr += 8 + 1;
+#ifdef SQLITE_ENABLE_8_3_NAMES
+ sqlite3FileSuffix3(zFilename,pPager->zJournal);
+ pPtr = (u8*)(pPager->zJournal + sqlite3Strlen30(pPager->zJournal)+1);
+#endif
+ }else{
+ pPager->zJournal = 0;
+ }
+
+#ifndef SQLITE_OMIT_WAL
+ /* Fill in Pager.zWal */
+ if( nPathname>0 ){
+ pPager->zWal = (char*)pPtr;
+ memcpy(pPtr, zPathname, nPathname); pPtr += nPathname;
+ memcpy(pPtr, "-wal", 4); pPtr += 4 + 1;
+#ifdef SQLITE_ENABLE_8_3_NAMES
+ sqlite3FileSuffix3(zFilename, pPager->zWal);
+ pPtr = (u8*)(pPager->zWal + sqlite3Strlen30(pPager->zWal)+1);
+#endif
+ }else{
+ pPager->zWal = 0;
+ }
+#endif
+
+ if( nPathname ) sqlite3DbFree(0, zPathname);
+ pPager->pVfs = pVfs;
+ pPager->vfsFlags = vfsFlags;
+
+ /* Open the pager file.
+ */
+ if( zFilename && zFilename[0] ){
+ int fout = 0; /* VFS flags returned by xOpen() */
+ rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
+ assert( !memDb );
+#ifdef SQLITE_ENABLE_DESERIALIZE
+ memJM = (fout&SQLITE_OPEN_MEMORY)!=0;
+#endif
+ readOnly = (fout&SQLITE_OPEN_READONLY)!=0;
+
+ /* If the file was successfully opened for read/write access,
+ ** choose a default page size in case we have to create the
+ ** database file. The default page size is the maximum of:
+ **
+ ** + SQLITE_DEFAULT_PAGE_SIZE,
+ ** + The value returned by sqlite3OsSectorSize()
+ ** + The largest page size that can be written atomically.
+ */
+ if( rc==SQLITE_OK ){
+ int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
+ if( !readOnly ){
+ setSectorSize(pPager);
+ assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
+ if( szPageDflt<pPager->sectorSize ){
+ if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
+ szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
+ }else{
+ szPageDflt = (u32)pPager->sectorSize;
+ }
+ }
+#ifdef SQLITE_ENABLE_ATOMIC_WRITE
+ {
+ int ii;
+ assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
+ assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
+ assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
+ for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
+ if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
+ szPageDflt = ii;
+ }
+ }
+ }
+#endif
+ }
+ pPager->noLock = sqlite3_uri_boolean(pPager->zFilename, "nolock", 0);
+ if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
+ || sqlite3_uri_boolean(pPager->zFilename, "immutable", 0) ){
+ vfsFlags |= SQLITE_OPEN_READONLY;
+ goto act_like_temp_file;
+ }
+ }
+ }else{
+ /* If a temporary file is requested, it is not opened immediately.
+ ** In this case we accept the default page size and delay actually
+ ** opening the file until the first call to OsWrite().
+ **
+ ** This branch is also run for an in-memory database. An in-memory
+ ** database is the same as a temp-file that is never written out to
+ ** disk and uses an in-memory rollback journal.
+ **
+ ** This branch also runs for files marked as immutable.
+ */
+act_like_temp_file:
+ tempFile = 1;
+ pPager->eState = PAGER_READER; /* Pretend we already have a lock */
+ pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
+ pPager->noLock = 1; /* Do no locking */
+ readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
+ }
+
+ /* The following call to PagerSetPagesize() serves to set the value of
+ ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
+ */
+ if( rc==SQLITE_OK ){
+ assert( pPager->memDb==0 );
+ rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
+ testcase( rc!=SQLITE_OK );
+ }
+
+ /* Initialize the PCache object. */
+ if( rc==SQLITE_OK ){
+ nExtra = ROUND8(nExtra);
+ assert( nExtra>=8 && nExtra<1000 );
+ rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
+ !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
+ }
+
+ /* If an error occurred above, free the Pager structure and close the file.
+ */
+ if( rc!=SQLITE_OK ){
+ sqlite3OsClose(pPager->fd);
+ sqlite3PageFree(pPager->pTmpSpace);
+ sqlite3_free(pPager);
+ return rc;
+ }
+
+ PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
+ IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
+
+ pPager->useJournal = (u8)useJournal;
+ /* pPager->stmtOpen = 0; */
+ /* pPager->stmtInUse = 0; */
+ /* pPager->nRef = 0; */
+ /* pPager->stmtSize = 0; */
+ /* pPager->stmtJSize = 0; */
+ /* pPager->nPage = 0; */
+ pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
+ /* pPager->state = PAGER_UNLOCK; */
+ /* pPager->errMask = 0; */
+ pPager->tempFile = (u8)tempFile;
+ assert( tempFile==PAGER_LOCKINGMODE_NORMAL
+ || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
+ assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
+ pPager->exclusiveMode = (u8)tempFile;
+ pPager->changeCountDone = pPager->tempFile;
+ pPager->memDb = (u8)memDb;
+ pPager->readOnly = (u8)readOnly;
+ assert( useJournal || pPager->tempFile );
+ pPager->noSync = pPager->tempFile;
+ if( pPager->noSync ){
+ assert( pPager->fullSync==0 );
+ assert( pPager->extraSync==0 );
+ assert( pPager->syncFlags==0 );
+ assert( pPager->walSyncFlags==0 );
+ }else{
+ pPager->fullSync = 1;
+ pPager->extraSync = 0;
+ pPager->syncFlags = SQLITE_SYNC_NORMAL;
+ pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);
+ }
+ /* pPager->pFirst = 0; */
+ /* pPager->pFirstSynced = 0; */
+ /* pPager->pLast = 0; */
+ pPager->nExtra = (u16)nExtra;
+ pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
+ assert( isOpen(pPager->fd) || tempFile );
+ setSectorSize(pPager);
+ if( !useJournal ){
+ pPager->journalMode = PAGER_JOURNALMODE_OFF;
+ }else if( memDb || memJM ){
+ pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
+ }
+ /* pPager->xBusyHandler = 0; */
+ /* pPager->pBusyHandlerArg = 0; */
+ pPager->xReiniter = xReinit;
+ setGetterMethod(pPager);
+ /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
+ /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
+
+ *ppPager = pPager;
+ return SQLITE_OK;
+}
+
+/*
+** Return the sqlite3_file for the main database given the name
+** of the corresonding WAL or Journal name as passed into
+** xOpen.
+*/
+SQLITE_API sqlite3_file *sqlite3_database_file_object(const char *zName){
+ Pager *pPager;
+ while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
+ zName--;
+ }
+ pPager = *(Pager**)(zName - 4 - sizeof(Pager*));
+ return pPager->fd;
+}
+
+
+/*
+** This function is called after transitioning from PAGER_UNLOCK to
+** PAGER_SHARED state. It tests if there is a hot journal present in
+** the file-system for the given pager. A hot journal is one that
+** needs to be played back. According to this function, a hot-journal
+** file exists if the following criteria are met:
+**
+** * The journal file exists in the file system, and
+** * No process holds a RESERVED or greater lock on the database file, and
+** * The database file itself is greater than 0 bytes in size, and
+** * The first byte of the journal file exists and is not 0x00.
+**
+** If the current size of the database file is 0 but a journal file
+** exists, that is probably an old journal left over from a prior
+** database with the same name. In this case the journal file is
+** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
+** is returned.
+**
+** This routine does not check if there is a super-journal filename
+** at the end of the file. If there is, and that super-journal file
+** does not exist, then the journal file is not really hot. In this
+** case this routine will return a false-positive. The pager_playback()
+** routine will discover that the journal file is not really hot and
+** will not roll it back.
+**
+** If a hot-journal file is found to exist, *pExists is set to 1 and
+** SQLITE_OK returned. If no hot-journal file is present, *pExists is
+** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
+** to determine whether or not a hot-journal file exists, the IO error
+** code is returned and the value of *pExists is undefined.
+*/
+static int hasHotJournal(Pager *pPager, int *pExists){
+ sqlite3_vfs * const pVfs = pPager->pVfs;
+ int rc = SQLITE_OK; /* Return code */
+ int exists = 1; /* True if a journal file is present */
+ int jrnlOpen = !!isOpen(pPager->jfd);
+
+ assert( pPager->useJournal );
+ assert( isOpen(pPager->fd) );
+ assert( pPager->eState==PAGER_OPEN );
+
+ assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
+ SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
+ ));
+
+ *pExists = 0;
+ if( !jrnlOpen ){
+ rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
+ }
+ if( rc==SQLITE_OK && exists ){
+ int locked = 0; /* True if some process holds a RESERVED lock */
+
+ /* Race condition here: Another process might have been holding the
+ ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
+ ** call above, but then delete the journal and drop the lock before
+ ** we get to the following sqlite3OsCheckReservedLock() call. If that
+ ** is the case, this routine might think there is a hot journal when
+ ** in fact there is none. This results in a false-positive which will
+ ** be dealt with by the playback routine. Ticket #3883.
+ */
+ rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
+ if( rc==SQLITE_OK && !locked ){
+ Pgno nPage; /* Number of pages in database file */
+
+ assert( pPager->tempFile==0 );
+ rc = pagerPagecount(pPager, &nPage);
+ if( rc==SQLITE_OK ){
+ /* If the database is zero pages in size, that means that either (1) the
+ ** journal is a remnant from a prior database with the same name where
+ ** the database file but not the journal was deleted, or (2) the initial
+ ** transaction that populates a new database is being rolled back.
+ ** In either case, the journal file can be deleted. However, take care
+ ** not to delete the journal file if it is already open due to
+ ** journal_mode=PERSIST.
+ */
+ if( nPage==0 && !jrnlOpen ){
+ sqlite3BeginBenignMalloc();
+ if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
+ sqlite3OsDelete(pVfs, pPager->zJournal, 0);
+ if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
+ }
+ sqlite3EndBenignMalloc();
+ }else{
+ /* The journal file exists and no other connection has a reserved
+ ** or greater lock on the database file. Now check that there is
+ ** at least one non-zero bytes at the start of the journal file.
+ ** If there is, then we consider this journal to be hot. If not,
+ ** it can be ignored.
+ */
+ if( !jrnlOpen ){
+ int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
+ rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
+ }
+ if( rc==SQLITE_OK ){
+ u8 first = 0;
+ rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
+ if( rc==SQLITE_IOERR_SHORT_READ ){
+ rc = SQLITE_OK;
+ }
+ if( !jrnlOpen ){
+ sqlite3OsClose(pPager->jfd);
+ }
+ *pExists = (first!=0);
+ }else if( rc==SQLITE_CANTOPEN ){
+ /* If we cannot open the rollback journal file in order to see if
+ ** it has a zero header, that might be due to an I/O error, or
+ ** it might be due to the race condition described above and in
+ ** ticket #3883. Either way, assume that the journal is hot.
+ ** This might be a false positive. But if it is, then the
+ ** automatic journal playback and recovery mechanism will deal
+ ** with it under an EXCLUSIVE lock where we do not need to
+ ** worry so much with race conditions.
+ */
+ *pExists = 1;
+ rc = SQLITE_OK;
+ }
+ }
+ }
+ }
+ }
+
+ return rc;
+}
+
+/*
+** This function is called to obtain a shared lock on the database file.
+** It is illegal to call sqlite3PagerGet() until after this function
+** has been successfully called. If a shared-lock is already held when
+** this function is called, it is a no-op.
+**
+** The following operations are also performed by this function.
+**
+** 1) If the pager is currently in PAGER_OPEN state (no lock held
+** on the database file), then an attempt is made to obtain a
+** SHARED lock on the database file. Immediately after obtaining
+** the SHARED lock, the file-system is checked for a hot-journal,
+** which is played back if present. Following any hot-journal
+** rollback, the contents of the cache are validated by checking
+** the 'change-counter' field of the database file header and
+** discarded if they are found to be invalid.
+**
+** 2) If the pager is running in exclusive-mode, and there are currently
+** no outstanding references to any pages, and is in the error state,
+** then an attempt is made to clear the error state by discarding
+** the contents of the page cache and rolling back any open journal
+** file.
+**
+** If everything is successful, SQLITE_OK is returned. If an IO error
+** occurs while locking the database, checking for a hot-journal file or
+** rolling back a journal file, the IO error code is returned.
+*/
+SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
+ int rc = SQLITE_OK; /* Return code */
+
+ /* This routine is only called from b-tree and only when there are no
+ ** outstanding pages. This implies that the pager state should either
+ ** be OPEN or READER. READER is only possible if the pager is or was in
+ ** exclusive access mode. */
+ assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
+ assert( assert_pager_state(pPager) );
+ assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
+ assert( pPager->errCode==SQLITE_OK );
+
+ if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
+ int bHotJournal = 1; /* True if there exists a hot journal-file */
+
+ assert( !MEMDB );
+ assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
+
+ rc = pager_wait_on_lock(pPager, SHARED_LOCK);
+ if( rc!=SQLITE_OK ){
+ assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
+ goto failed;
+ }
+
+ /* If a journal file exists, and there is no RESERVED lock on the
+ ** database file, then it either needs to be played back or deleted.
+ */
+ if( pPager->eLock<=SHARED_LOCK ){
+ rc = hasHotJournal(pPager, &bHotJournal);
+ }
+ if( rc!=SQLITE_OK ){
+ goto failed;
+ }
+ if( bHotJournal ){
+ if( pPager->readOnly ){
+ rc = SQLITE_READONLY_ROLLBACK;
+ goto failed;
+ }
+
+ /* Get an EXCLUSIVE lock on the database file. At this point it is
+ ** important that a RESERVED lock is not obtained on the way to the
+ ** EXCLUSIVE lock. If it were, another process might open the
+ ** database file, detect the RESERVED lock, and conclude that the
+ ** database is safe to read while this process is still rolling the
+ ** hot-journal back.
+ **
+ ** Because the intermediate RESERVED lock is not requested, any
+ ** other process attempting to access the database file will get to
+ ** this point in the code and fail to obtain its own EXCLUSIVE lock
+ ** on the database file.
+ **
+ ** Unless the pager is in locking_mode=exclusive mode, the lock is
+ ** downgraded to SHARED_LOCK before this function returns.
+ */
+ rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
+ if( rc!=SQLITE_OK ){
+ goto failed;
+ }
+
+ /* If it is not already open and the file exists on disk, open the
+ ** journal for read/write access. Write access is required because
+ ** in exclusive-access mode the file descriptor will be kept open
+ ** and possibly used for a transaction later on. Also, write-access
+ ** is usually required to finalize the journal in journal_mode=persist
+ ** mode (and also for journal_mode=truncate on some systems).
+ **
+ ** If the journal does not exist, it usually means that some
+ ** other connection managed to get in and roll it back before
+ ** this connection obtained the exclusive lock above. Or, it
+ ** may mean that the pager was in the error-state when this
+ ** function was called and the journal file does not exist.
+ */
+ if( !isOpen(pPager->jfd) ){
+ sqlite3_vfs * const pVfs = pPager->pVfs;
+ int bExists; /* True if journal file exists */
+ rc = sqlite3OsAccess(
+ pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
+ if( rc==SQLITE_OK && bExists ){
+ int fout = 0;
+ int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
+ assert( !pPager->tempFile );
+ rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
+ assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
+ if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
+ rc = SQLITE_CANTOPEN_BKPT;
+ sqlite3OsClose(pPager->jfd);
+ }
+ }
+ }
+
+ /* Playback and delete the journal. Drop the database write
+ ** lock and reacquire the read lock. Purge the cache before
+ ** playing back the hot-journal so that we don't end up with
+ ** an inconsistent cache. Sync the hot journal before playing
+ ** it back since the process that crashed and left the hot journal
+ ** probably did not sync it and we are required to always sync
+ ** the journal before playing it back.
+ */
+ if( isOpen(pPager->jfd) ){
+ assert( rc==SQLITE_OK );
+ rc = pagerSyncHotJournal(pPager);
+ if( rc==SQLITE_OK ){
+ rc = pager_playback(pPager, !pPager->tempFile);
+ pPager->eState = PAGER_OPEN;
+ }
+ }else if( !pPager->exclusiveMode ){
+ pagerUnlockDb(pPager, SHARED_LOCK);
+ }
+
+ if( rc!=SQLITE_OK ){
+ /* This branch is taken if an error occurs while trying to open
+ ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
+ ** pager_unlock() routine will be called before returning to unlock
+ ** the file. If the unlock attempt fails, then Pager.eLock must be
+ ** set to UNKNOWN_LOCK (see the comment above the #define for
+ ** UNKNOWN_LOCK above for an explanation).
+ **
+ ** In order to get pager_unlock() to do this, set Pager.eState to
+ ** PAGER_ERROR now. This is not actually counted as a transition
+ ** to ERROR state in the state diagram at the top of this file,
+ ** since we know that the same call to pager_unlock() will very
+ ** shortly transition the pager object to the OPEN state. Calling
+ ** assert_pager_state() would fail now, as it should not be possible
+ ** to be in ERROR state when there are zero outstanding page
+ ** references.
+ */
+ pager_error(pPager, rc);
+ goto failed;
+ }
+
+ assert( pPager->eState==PAGER_OPEN );
+ assert( (pPager->eLock==SHARED_LOCK)
+ || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
+ );
+ }
+
+ if( !pPager->tempFile && pPager->hasHeldSharedLock ){
+ /* The shared-lock has just been acquired then check to
+ ** see if the database has been modified. If the database has changed,
+ ** flush the cache. The hasHeldSharedLock flag prevents this from
+ ** occurring on the very first access to a file, in order to save a
+ ** single unnecessary sqlite3OsRead() call at the start-up.
+ **
+ ** Database changes are detected by looking at 15 bytes beginning
+ ** at offset 24 into the file. The first 4 of these 16 bytes are
+ ** a 32-bit counter that is incremented with each change. The
+ ** other bytes change randomly with each file change when
+ ** a codec is in use.
+ **
+ ** There is a vanishingly small chance that a change will not be
+ ** detected. The chance of an undetected change is so small that
+ ** it can be neglected.
+ */
+ char dbFileVers[sizeof(pPager->dbFileVers)];
+
+ IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
+ rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
+ if( rc!=SQLITE_OK ){
+ if( rc!=SQLITE_IOERR_SHORT_READ ){
+ goto failed;
+ }
+ memset(dbFileVers, 0, sizeof(dbFileVers));
+ }
+
+ if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
+ pager_reset(pPager);
+
+ /* Unmap the database file. It is possible that external processes
+ ** may have truncated the database file and then extended it back
+ ** to its original size while this process was not holding a lock.
+ ** In this case there may exist a Pager.pMap mapping that appears
+ ** to be the right size but is not actually valid. Avoid this
+ ** possibility by unmapping the db here. */
+ if( USEFETCH(pPager) ){
+ sqlite3OsUnfetch(pPager->fd, 0, 0);
+ }
+ }
+ }
+
+ /* If there is a WAL file in the file-system, open this database in WAL
+ ** mode. Otherwise, the following function call is a no-op.
+ */
+ rc = pagerOpenWalIfPresent(pPager);
+#ifndef SQLITE_OMIT_WAL
+ assert( pPager->pWal==0 || rc==SQLITE_OK );
+#endif
+ }
+
+ if( pagerUseWal(pPager) ){
+ assert( rc==SQLITE_OK );
+ rc = pagerBeginReadTransaction(pPager);
+ }
+
+ if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
+ rc = pagerPagecount(pPager, &pPager->dbSize);
+ }
+
+ failed:
+ if( rc!=SQLITE_OK ){
+ assert( !MEMDB );
+ pager_unlock(pPager);
+ assert( pPager->eState==PAGER_OPEN );
+ }else{
+ pPager->eState = PAGER_READER;
+ pPager->hasHeldSharedLock = 1;
+ }
+ return rc;
+}
+
+/*
+** If the reference count has reached zero, rollback any active
+** transaction and unlock the pager.
+**
+** Except, in locking_mode=EXCLUSIVE when there is nothing to in
+** the rollback journal, the unlock is not performed and there is
+** nothing to rollback, so this routine is a no-op.
+*/
+static void pagerUnlockIfUnused(Pager *pPager){
+ if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
+ assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
+ pagerUnlockAndRollback(pPager);
+ }
+}
+
+/*
+** The page getter methods each try to acquire a reference to a
+** page with page number pgno. If the requested reference is
+** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
+**
+** There are different implementations of the getter method depending
+** on the current state of the pager.
+**
+** getPageNormal() -- The normal getter
+** getPageError() -- Used if the pager is in an error state
+** getPageMmap() -- Used if memory-mapped I/O is enabled
+**
+** If the requested page is already in the cache, it is returned.
+** Otherwise, a new page object is allocated and populated with data
+** read from the database file. In some cases, the pcache module may
+** choose not to allocate a new page object and may reuse an existing
+** object with no outstanding references.
+**
+** The extra data appended to a page is always initialized to zeros the
+** first time a page is loaded into memory. If the page requested is
+** already in the cache when this function is called, then the extra
+** data is left as it was when the page object was last used.
+**
+** If the database image is smaller than the requested page or if
+** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
+** requested page is not already stored in the cache, then no
+** actual disk read occurs. In this case the memory image of the
+** page is initialized to all zeros.
+**
+** If PAGER_GET_NOCONTENT is true, it means that we do not care about
+** the contents of the page. This occurs in two scenarios:
+**
+** a) When reading a free-list leaf page from the database, and
+**
+** b) When a savepoint is being rolled back and we need to load
+** a new page into the cache to be filled with the data read
+** from the savepoint journal.
+**
+** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
+** of being read from the database. Additionally, the bits corresponding
+** to pgno in Pager.pInJournal (bitvec of pages already written to the
+** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
+** savepoints are set. This means if the page is made writable at any
+** point in the future, using a call to sqlite3PagerWrite(), its contents
+** will not be journaled. This saves IO.
+**
+** The acquisition might fail for several reasons. In all cases,
+** an appropriate error code is returned and *ppPage is set to NULL.
+**
+** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
+** to find a page in the in-memory cache first. If the page is not already
+** in memory, this routine goes to disk to read it in whereas Lookup()
+** just returns 0. This routine acquires a read-lock the first time it
+** has to go to disk, and could also playback an old journal if necessary.
+** Since Lookup() never goes to disk, it never has to deal with locks
+** or journal files.
+*/
+static int getPageNormal(
+ Pager *pPager, /* The pager open on the database file */
+ Pgno pgno, /* Page number to fetch */
+ DbPage **ppPage, /* Write a pointer to the page here */
+ int flags /* PAGER_GET_XXX flags */
+){
+ int rc = SQLITE_OK;
+ PgHdr *pPg;
+ u8 noContent; /* True if PAGER_GET_NOCONTENT is set */
+ sqlite3_pcache_page *pBase;
+
+ assert( pPager->errCode==SQLITE_OK );
+ assert( pPager->eState>=PAGER_READER );
+ assert( assert_pager_state(pPager) );
+ assert( pPager->hasHeldSharedLock==1 );
+
+ if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
+ pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
+ if( pBase==0 ){
+ pPg = 0;
+ rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
+ if( rc!=SQLITE_OK ) goto pager_acquire_err;
+ if( pBase==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto pager_acquire_err;
+ }
+ }
+ pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
+ assert( pPg==(*ppPage) );
+ assert( pPg->pgno==pgno );
+ assert( pPg->pPager==pPager || pPg->pPager==0 );
+
+ noContent = (flags & PAGER_GET_NOCONTENT)!=0;
+ if( pPg->pPager && !noContent ){
+ /* In this case the pcache already contains an initialized copy of
+ ** the page. Return without further ado. */
+ assert( pgno!=PAGER_MJ_PGNO(pPager) );
+ pPager->aStat[PAGER_STAT_HIT]++;
+ return SQLITE_OK;
+
+ }else{
+ /* The pager cache has created a new page. Its content needs to
+ ** be initialized. But first some error checks:
+ **
+ ** (*) obsolete. Was: maximum page number is 2^31
+ ** (2) Never try to fetch the locking page
+ */
+ if( pgno==PAGER_MJ_PGNO(pPager) ){
+ rc = SQLITE_CORRUPT_BKPT;
+ goto pager_acquire_err;
+ }
+
+ pPg->pPager = pPager;
+
+ assert( !isOpen(pPager->fd) || !MEMDB );
+ if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
+ if( pgno>pPager->mxPgno ){
+ rc = SQLITE_FULL;
+ goto pager_acquire_err;
+ }
+ if( noContent ){
+ /* Failure to set the bits in the InJournal bit-vectors is benign.
+ ** It merely means that we might do some extra work to journal a
+ ** page that does not need to be journaled. Nevertheless, be sure
+ ** to test the case where a malloc error occurs while trying to set
+ ** a bit in a bit vector.
+ */
+ sqlite3BeginBenignMalloc();
+ if( pgno<=pPager->dbOrigSize ){
+ TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
+ testcase( rc==SQLITE_NOMEM );
+ }
+ TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
+ testcase( rc==SQLITE_NOMEM );
+ sqlite3EndBenignMalloc();
+ }
+ memset(pPg->pData, 0, pPager->pageSize);
+ IOTRACE(("ZERO %p %d\n", pPager, pgno));
+ }else{
+ assert( pPg->pPager==pPager );
+ pPager->aStat[PAGER_STAT_MISS]++;
+ rc = readDbPage(pPg);
+ if( rc!=SQLITE_OK ){
+ goto pager_acquire_err;
+ }
+ }
+ pager_set_pagehash(pPg);
+ }
+ return SQLITE_OK;
+
+pager_acquire_err:
+ assert( rc!=SQLITE_OK );
+ if( pPg ){
+ sqlite3PcacheDrop(pPg);
+ }
+ pagerUnlockIfUnused(pPager);
+ *ppPage = 0;
+ return rc;
+}
+
+#if SQLITE_MAX_MMAP_SIZE>0
+/* The page getter for when memory-mapped I/O is enabled */
+static int getPageMMap(
+ Pager *pPager, /* The pager open on the database file */
+ Pgno pgno, /* Page number to fetch */
+ DbPage **ppPage, /* Write a pointer to the page here */
+ int flags /* PAGER_GET_XXX flags */
+){
+ int rc = SQLITE_OK;
+ PgHdr *pPg = 0;
+ u32 iFrame = 0; /* Frame to read from WAL file */
+
+ /* It is acceptable to use a read-only (mmap) page for any page except
+ ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
+ ** flag was specified by the caller. And so long as the db is not a
+ ** temporary or in-memory database. */
+ const int bMmapOk = (pgno>1
+ && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
+ );
+
+ assert( USEFETCH(pPager) );
+
+ /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
+ ** allows the compiler optimizer to reuse the results of the "pgno>1"
+ ** test in the previous statement, and avoid testing pgno==0 in the
+ ** common case where pgno is large. */
+ if( pgno<=1 && pgno==0 ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+ assert( pPager->eState>=PAGER_READER );
+ assert( assert_pager_state(pPager) );
+ assert( pPager->hasHeldSharedLock==1 );
+ assert( pPager->errCode==SQLITE_OK );
+
+ if( bMmapOk && pagerUseWal(pPager) ){
+ rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
+ if( rc!=SQLITE_OK ){
+ *ppPage = 0;
+ return rc;
+ }
+ }
+ if( bMmapOk && iFrame==0 ){
+ void *pData = 0;
+ rc = sqlite3OsFetch(pPager->fd,
+ (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
+ );
+ if( rc==SQLITE_OK && pData ){
+ if( pPager->eState>PAGER_READER || pPager->tempFile ){
+ pPg = sqlite3PagerLookup(pPager, pgno);
+ }
+ if( pPg==0 ){
+ rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
+ }else{
+ sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
+ }
+ if( pPg ){
+ assert( rc==SQLITE_OK );
+ *ppPage = pPg;
+ return SQLITE_OK;
+ }
+ }
+ if( rc!=SQLITE_OK ){
+ *ppPage = 0;
+ return rc;
+ }
+ }
+ return getPageNormal(pPager, pgno, ppPage, flags);
+}
+#endif /* SQLITE_MAX_MMAP_SIZE>0 */
+
+/* The page getter method for when the pager is an error state */
+static int getPageError(
+ Pager *pPager, /* The pager open on the database file */
+ Pgno pgno, /* Page number to fetch */
+ DbPage **ppPage, /* Write a pointer to the page here */
+ int flags /* PAGER_GET_XXX flags */
+){
+ UNUSED_PARAMETER(pgno);
+ UNUSED_PARAMETER(flags);
+ assert( pPager->errCode!=SQLITE_OK );
+ *ppPage = 0;
+ return pPager->errCode;
+}
+
+
+/* Dispatch all page fetch requests to the appropriate getter method.
+*/
+SQLITE_PRIVATE int sqlite3PagerGet(
+ Pager *pPager, /* The pager open on the database file */
+ Pgno pgno, /* Page number to fetch */
+ DbPage **ppPage, /* Write a pointer to the page here */
+ int flags /* PAGER_GET_XXX flags */
+){
+ return pPager->xGet(pPager, pgno, ppPage, flags);
+}
+
+/*
+** Acquire a page if it is already in the in-memory cache. Do
+** not read the page from disk. Return a pointer to the page,
+** or 0 if the page is not in cache.
+**
+** See also sqlite3PagerGet(). The difference between this routine
+** and sqlite3PagerGet() is that _get() will go to the disk and read
+** in the page if the page is not already in cache. This routine
+** returns NULL if the page is not in cache or if a disk I/O error
+** has ever happened.
+*/
+SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
+ sqlite3_pcache_page *pPage;
+ assert( pPager!=0 );
+ assert( pgno!=0 );
+ assert( pPager->pPCache!=0 );
+ pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
+ assert( pPage==0 || pPager->hasHeldSharedLock );
+ if( pPage==0 ) return 0;
+ return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
+}
+
+/*
+** Release a page reference.
+**
+** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be
+** used if we know that the page being released is not the last page.
+** The btree layer always holds page1 open until the end, so these first
+** to routines can be used to release any page other than BtShared.pPage1.
+**
+** Use sqlite3PagerUnrefPageOne() to release page1. This latter routine
+** checks the total number of outstanding pages and if the number of
+** pages reaches zero it drops the database lock.
+*/
+SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
+ TESTONLY( Pager *pPager = pPg->pPager; )
+ assert( pPg!=0 );
+ if( pPg->flags & PGHDR_MMAP ){
+ assert( pPg->pgno!=1 ); /* Page1 is never memory mapped */
+ pagerReleaseMapPage(pPg);
+ }else{
+ sqlite3PcacheRelease(pPg);
+ }
+ /* Do not use this routine to release the last reference to page1 */
+ assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
+}
+SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
+ if( pPg ) sqlite3PagerUnrefNotNull(pPg);
+}
+SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
+ Pager *pPager;
+ assert( pPg!=0 );
+ assert( pPg->pgno==1 );
+ assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
+ pPager = pPg->pPager;
+ sqlite3PcacheRelease(pPg);
+ pagerUnlockIfUnused(pPager);
+}
+
+/*
+** This function is called at the start of every write transaction.
+** There must already be a RESERVED or EXCLUSIVE lock on the database
+** file when this routine is called.
+**
+** Open the journal file for pager pPager and write a journal header
+** to the start of it. If there are active savepoints, open the sub-journal
+** as well. This function is only used when the journal file is being
+** opened to write a rollback log for a transaction. It is not used
+** when opening a hot journal file to roll it back.
+**
+** If the journal file is already open (as it may be in exclusive mode),
+** then this function just writes a journal header to the start of the
+** already open file.
+**
+** Whether or not the journal file is opened by this function, the
+** Pager.pInJournal bitvec structure is allocated.
+**
+** Return SQLITE_OK if everything is successful. Otherwise, return
+** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
+** an IO error code if opening or writing the journal file fails.
+*/
+static int pager_open_journal(Pager *pPager){
+ int rc = SQLITE_OK; /* Return code */
+ sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
+
+ assert( pPager->eState==PAGER_WRITER_LOCKED );
+ assert( assert_pager_state(pPager) );
+ assert( pPager->pInJournal==0 );
+
+ /* If already in the error state, this function is a no-op. But on
+ ** the other hand, this routine is never called if we are already in
+ ** an error state. */
+ if( NEVER(pPager->errCode) ) return pPager->errCode;
+
+ if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
+ pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
+ if( pPager->pInJournal==0 ){
+ return SQLITE_NOMEM_BKPT;
+ }
+
+ /* Open the journal file if it is not already open. */
+ if( !isOpen(pPager->jfd) ){
+ if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
+ sqlite3MemJournalOpen(pPager->jfd);
+ }else{
+ int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
+ int nSpill;
+
+ if( pPager->tempFile ){
+ flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
+ nSpill = sqlite3Config.nStmtSpill;
+ }else{
+ flags |= SQLITE_OPEN_MAIN_JOURNAL;
+ nSpill = jrnlBufferSize(pPager);
+ }
+
+ /* Verify that the database still has the same name as it did when
+ ** it was originally opened. */
+ rc = databaseIsUnmoved(pPager);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3JournalOpen (
+ pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
+ );
+ }
+ }
+ assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
+ }
+
+
+ /* Write the first journal header to the journal file and open
+ ** the sub-journal if necessary.
+ */
+ if( rc==SQLITE_OK ){
+ /* TODO: Check if all of these are really required. */
+ pPager->nRec = 0;
+ pPager->journalOff = 0;
+ pPager->setSuper = 0;
+ pPager->journalHdr = 0;
+ rc = writeJournalHdr(pPager);
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ sqlite3BitvecDestroy(pPager->pInJournal);
+ pPager->pInJournal = 0;
+ }else{
+ assert( pPager->eState==PAGER_WRITER_LOCKED );
+ pPager->eState = PAGER_WRITER_CACHEMOD;
+ }
+
+ return rc;
+}
+
+/*
+** Begin a write-transaction on the specified pager object. If a
+** write-transaction has already been opened, this function is a no-op.
+**
+** If the exFlag argument is false, then acquire at least a RESERVED
+** lock on the database file. If exFlag is true, then acquire at least
+** an EXCLUSIVE lock. If such a lock is already held, no locking
+** functions need be called.
+**
+** If the subjInMemory argument is non-zero, then any sub-journal opened
+** within this transaction will be opened as an in-memory file. This
+** has no effect if the sub-journal is already opened (as it may be when
+** running in exclusive mode) or if the transaction does not require a
+** sub-journal. If the subjInMemory argument is zero, then any required
+** sub-journal is implemented in-memory if pPager is an in-memory database,
+** or using a temporary file otherwise.
+*/
+SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
+ int rc = SQLITE_OK;
+
+ if( pPager->errCode ) return pPager->errCode;
+ assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
+ pPager->subjInMemory = (u8)subjInMemory;
+
+ if( ALWAYS(pPager->eState==PAGER_READER) ){
+ assert( pPager->pInJournal==0 );
+
+ if( pagerUseWal(pPager) ){
+ /* If the pager is configured to use locking_mode=exclusive, and an
+ ** exclusive lock on the database is not already held, obtain it now.
+ */
+ if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
+ rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
+ }
+
+ /* Grab the write lock on the log file. If successful, upgrade to
+ ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
+ ** The busy-handler is not invoked if another connection already
+ ** holds the write-lock. If possible, the upper layer will call it.
+ */
+ rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
+ }else{
+ /* Obtain a RESERVED lock on the database file. If the exFlag parameter
+ ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
+ ** busy-handler callback can be used when upgrading to the EXCLUSIVE
+ ** lock, but not when obtaining the RESERVED lock.
+ */
+ rc = pagerLockDb(pPager, RESERVED_LOCK);
+ if( rc==SQLITE_OK && exFlag ){
+ rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ /* Change to WRITER_LOCKED state.
+ **
+ ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
+ ** when it has an open transaction, but never to DBMOD or FINISHED.
+ ** This is because in those states the code to roll back savepoint
+ ** transactions may copy data from the sub-journal into the database
+ ** file as well as into the page cache. Which would be incorrect in
+ ** WAL mode.
+ */
+ pPager->eState = PAGER_WRITER_LOCKED;
+ pPager->dbHintSize = pPager->dbSize;
+ pPager->dbFileSize = pPager->dbSize;
+ pPager->dbOrigSize = pPager->dbSize;
+ pPager->journalOff = 0;
+ }
+
+ assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
+ assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
+ assert( assert_pager_state(pPager) );
+ }
+
+ PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
+ return rc;
+}
+
+/*
+** Write page pPg onto the end of the rollback journal.
+*/
+static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
+ Pager *pPager = pPg->pPager;
+ int rc;
+ u32 cksum;
+ char *pData2;
+ i64 iOff = pPager->journalOff;
+
+ /* We should never write to the journal file the page that
+ ** contains the database locks. The following assert verifies
+ ** that we do not. */
+ assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
+
+ assert( pPager->journalHdr<=pPager->journalOff );
+ pData2 = pPg->pData;
+ cksum = pager_cksum(pPager, (u8*)pData2);
+
+ /* Even if an IO or diskfull error occurs while journalling the
+ ** page in the block above, set the need-sync flag for the page.
+ ** Otherwise, when the transaction is rolled back, the logic in
+ ** playback_one_page() will think that the page needs to be restored
+ ** in the database file. And if an IO error occurs while doing so,
+ ** then corruption may follow.
+ */
+ pPg->flags |= PGHDR_NEED_SYNC;
+
+ rc = write32bits(pPager->jfd, iOff, pPg->pgno);
+ if( rc!=SQLITE_OK ) return rc;
+ rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
+ if( rc!=SQLITE_OK ) return rc;
+ rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
+ if( rc!=SQLITE_OK ) return rc;
+
+ IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
+ pPager->journalOff, pPager->pageSize));
+ PAGER_INCR(sqlite3_pager_writej_count);
+ PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
+ PAGERID(pPager), pPg->pgno,
+ ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
+
+ pPager->journalOff += 8 + pPager->pageSize;
+ pPager->nRec++;
+ assert( pPager->pInJournal!=0 );
+ rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
+ testcase( rc==SQLITE_NOMEM );
+ assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
+ rc |= addToSavepointBitvecs(pPager, pPg->pgno);
+ assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
+ return rc;
+}
+
+/*
+** Mark a single data page as writeable. The page is written into the
+** main journal or sub-journal as required. If the page is written into
+** one of the journals, the corresponding bit is set in the
+** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
+** of any open savepoints as appropriate.
+*/
+static int pager_write(PgHdr *pPg){
+ Pager *pPager = pPg->pPager;
+ int rc = SQLITE_OK;
+
+ /* This routine is not called unless a write-transaction has already
+ ** been started. The journal file may or may not be open at this point.
+ ** It is never called in the ERROR state.
+ */
+ assert( pPager->eState==PAGER_WRITER_LOCKED
+ || pPager->eState==PAGER_WRITER_CACHEMOD
+ || pPager->eState==PAGER_WRITER_DBMOD
+ );
+ assert( assert_pager_state(pPager) );
+ assert( pPager->errCode==0 );
+ assert( pPager->readOnly==0 );
+ CHECK_PAGE(pPg);
+
+ /* The journal file needs to be opened. Higher level routines have already
+ ** obtained the necessary locks to begin the write-transaction, but the
+ ** rollback journal might not yet be open. Open it now if this is the case.
+ **
+ ** This is done before calling sqlite3PcacheMakeDirty() on the page.
+ ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
+ ** an error might occur and the pager would end up in WRITER_LOCKED state
+ ** with pages marked as dirty in the cache.
+ */
+ if( pPager->eState==PAGER_WRITER_LOCKED ){
+ rc = pager_open_journal(pPager);
+ if( rc!=SQLITE_OK ) return rc;
+ }
+ assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
+ assert( assert_pager_state(pPager) );
+
+ /* Mark the page that is about to be modified as dirty. */
+ sqlite3PcacheMakeDirty(pPg);
+
+ /* If a rollback journal is in use, them make sure the page that is about
+ ** to change is in the rollback journal, or if the page is a new page off
+ ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
+ */
+ assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
+ if( pPager->pInJournal!=0
+ && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
+ ){
+ assert( pagerUseWal(pPager)==0 );
+ if( pPg->pgno<=pPager->dbOrigSize ){
+ rc = pagerAddPageToRollbackJournal(pPg);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ }else{
+ if( pPager->eState!=PAGER_WRITER_DBMOD ){
+ pPg->flags |= PGHDR_NEED_SYNC;
+ }
+ PAGERTRACE(("APPEND %d page %d needSync=%d\n",
+ PAGERID(pPager), pPg->pgno,
+ ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
+ }
+ }
+
+ /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
+ ** and before writing the page into the rollback journal. Wait until now,
+ ** after the page has been successfully journalled, before setting the
+ ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
+ */
+ pPg->flags |= PGHDR_WRITEABLE;
+
+ /* If the statement journal is open and the page is not in it,
+ ** then write the page into the statement journal.
+ */
+ if( pPager->nSavepoint>0 ){
+ rc = subjournalPageIfRequired(pPg);
+ }
+
+ /* Update the database size and return. */
+ if( pPager->dbSize<pPg->pgno ){
+ pPager->dbSize = pPg->pgno;
+ }
+ return rc;
+}
+
+/*
+** This is a variant of sqlite3PagerWrite() that runs when the sector size
+** is larger than the page size. SQLite makes the (reasonable) assumption that
+** all bytes of a sector are written together by hardware. Hence, all bytes of
+** a sector need to be journalled in case of a power loss in the middle of
+** a write.
+**
+** Usually, the sector size is less than or equal to the page size, in which
+** case pages can be individually written. This routine only runs in the
+** exceptional case where the page size is smaller than the sector size.
+*/
+static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
+ int rc = SQLITE_OK; /* Return code */
+ Pgno nPageCount; /* Total number of pages in database file */
+ Pgno pg1; /* First page of the sector pPg is located on. */
+ int nPage = 0; /* Number of pages starting at pg1 to journal */
+ int ii; /* Loop counter */
+ int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
+ Pager *pPager = pPg->pPager; /* The pager that owns pPg */
+ Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
+
+ /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
+ ** a journal header to be written between the pages journaled by
+ ** this function.
+ */
+ assert( !MEMDB );
+ assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
+ pPager->doNotSpill |= SPILLFLAG_NOSYNC;
+
+ /* This trick assumes that both the page-size and sector-size are
+ ** an integer power of 2. It sets variable pg1 to the identifier
+ ** of the first page of the sector pPg is located on.
+ */
+ pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
+
+ nPageCount = pPager->dbSize;
+ if( pPg->pgno>nPageCount ){
+ nPage = (pPg->pgno - pg1)+1;
+ }else if( (pg1+nPagePerSector-1)>nPageCount ){
+ nPage = nPageCount+1-pg1;
+ }else{
+ nPage = nPagePerSector;
+ }
+ assert(nPage>0);
+ assert(pg1<=pPg->pgno);
+ assert((pg1+nPage)>pPg->pgno);
+
+ for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
+ Pgno pg = pg1+ii;
+ PgHdr *pPage;
+ if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
+ if( pg!=PAGER_MJ_PGNO(pPager) ){
+ rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
+ if( rc==SQLITE_OK ){
+ rc = pager_write(pPage);
+ if( pPage->flags&PGHDR_NEED_SYNC ){
+ needSync = 1;
+ }
+ sqlite3PagerUnrefNotNull(pPage);
+ }
+ }
+ }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
+ if( pPage->flags&PGHDR_NEED_SYNC ){
+ needSync = 1;
+ }
+ sqlite3PagerUnrefNotNull(pPage);
+ }
+ }
+
+ /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
+ ** starting at pg1, then it needs to be set for all of them. Because
+ ** writing to any of these nPage pages may damage the others, the
+ ** journal file must contain sync()ed copies of all of them
+ ** before any of them can be written out to the database file.
+ */
+ if( rc==SQLITE_OK && needSync ){
+ assert( !MEMDB );
+ for(ii=0; ii<nPage; ii++){
+ PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
+ if( pPage ){
+ pPage->flags |= PGHDR_NEED_SYNC;
+ sqlite3PagerUnrefNotNull(pPage);
+ }
+ }
+ }
+
+ assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
+ pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
+ return rc;
+}
+
+/*
+** Mark a data page as writeable. This routine must be called before
+** making changes to a page. The caller must check the return value
+** of this function and be careful not to change any page data unless
+** this routine returns SQLITE_OK.
+**
+** The difference between this function and pager_write() is that this
+** function also deals with the special case where 2 or more pages
+** fit on a single disk sector. In this case all co-resident pages
+** must have been written to the journal file before returning.
+**
+** If an error occurs, SQLITE_NOMEM or an IO error code is returned
+** as appropriate. Otherwise, SQLITE_OK.
+*/
+SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
+ Pager *pPager = pPg->pPager;
+ assert( (pPg->flags & PGHDR_MMAP)==0 );
+ assert( pPager->eState>=PAGER_WRITER_LOCKED );
+ assert( assert_pager_state(pPager) );
+ if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
+ if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
+ return SQLITE_OK;
+ }else if( pPager->errCode ){
+ return pPager->errCode;
+ }else if( pPager->sectorSize > (u32)pPager->pageSize ){
+ assert( pPager->tempFile==0 );
+ return pagerWriteLargeSector(pPg);
+ }else{
+ return pager_write(pPg);
+ }
+}
+
+/*
+** Return TRUE if the page given in the argument was previously passed
+** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
+** to change the content of the page.
+*/
+#ifndef NDEBUG
+SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
+ return pPg->flags & PGHDR_WRITEABLE;
+}
+#endif
+
+/*
+** A call to this routine tells the pager that it is not necessary to
+** write the information on page pPg back to the disk, even though
+** that page might be marked as dirty. This happens, for example, when
+** the page has been added as a leaf of the freelist and so its
+** content no longer matters.
+**
+** The overlying software layer calls this routine when all of the data
+** on the given page is unused. The pager marks the page as clean so
+** that it does not get written to disk.
+**
+** Tests show that this optimization can quadruple the speed of large
+** DELETE operations.
+**
+** This optimization cannot be used with a temp-file, as the page may
+** have been dirty at the start of the transaction. In that case, if
+** memory pressure forces page pPg out of the cache, the data does need
+** to be written out to disk so that it may be read back in if the
+** current transaction is rolled back.
+*/
+SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
+ Pager *pPager = pPg->pPager;
+ if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
+ PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
+ IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
+ pPg->flags |= PGHDR_DONT_WRITE;
+ pPg->flags &= ~PGHDR_WRITEABLE;
+ testcase( pPg->flags & PGHDR_NEED_SYNC );
+ pager_set_pagehash(pPg);
+ }
+}
+
+/*
+** This routine is called to increment the value of the database file
+** change-counter, stored as a 4-byte big-endian integer starting at
+** byte offset 24 of the pager file. The secondary change counter at
+** 92 is also updated, as is the SQLite version number at offset 96.
+**
+** But this only happens if the pPager->changeCountDone flag is false.
+** To avoid excess churning of page 1, the update only happens once.
+** See also the pager_write_changecounter() routine that does an
+** unconditional update of the change counters.
+**
+** If the isDirectMode flag is zero, then this is done by calling
+** sqlite3PagerWrite() on page 1, then modifying the contents of the
+** page data. In this case the file will be updated when the current
+** transaction is committed.
+**
+** The isDirectMode flag may only be non-zero if the library was compiled
+** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
+** if isDirect is non-zero, then the database file is updated directly
+** by writing an updated version of page 1 using a call to the
+** sqlite3OsWrite() function.
+*/
+static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
+ int rc = SQLITE_OK;
+
+ assert( pPager->eState==PAGER_WRITER_CACHEMOD
+ || pPager->eState==PAGER_WRITER_DBMOD
+ );
+ assert( assert_pager_state(pPager) );
+
+ /* Declare and initialize constant integer 'isDirect'. If the
+ ** atomic-write optimization is enabled in this build, then isDirect
+ ** is initialized to the value passed as the isDirectMode parameter
+ ** to this function. Otherwise, it is always set to zero.
+ **
+ ** The idea is that if the atomic-write optimization is not
+ ** enabled at compile time, the compiler can omit the tests of
+ ** 'isDirect' below, as well as the block enclosed in the
+ ** "if( isDirect )" condition.
+ */
+#ifndef SQLITE_ENABLE_ATOMIC_WRITE
+# define DIRECT_MODE 0
+ assert( isDirectMode==0 );
+ UNUSED_PARAMETER(isDirectMode);
+#else
+# define DIRECT_MODE isDirectMode
+#endif
+
+ if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
+ PgHdr *pPgHdr; /* Reference to page 1 */
+
+ assert( !pPager->tempFile && isOpen(pPager->fd) );
+
+ /* Open page 1 of the file for writing. */
+ rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
+ assert( pPgHdr==0 || rc==SQLITE_OK );
+
+ /* If page one was fetched successfully, and this function is not
+ ** operating in direct-mode, make page 1 writable. When not in
+ ** direct mode, page 1 is always held in cache and hence the PagerGet()
+ ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
+ */
+ if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
+ rc = sqlite3PagerWrite(pPgHdr);
+ }
+
+ if( rc==SQLITE_OK ){
+ /* Actually do the update of the change counter */
+ pager_write_changecounter(pPgHdr);
+
+ /* If running in direct mode, write the contents of page 1 to the file. */
+ if( DIRECT_MODE ){
+ const void *zBuf;
+ assert( pPager->dbFileSize>0 );
+ zBuf = pPgHdr->pData;
+ if( rc==SQLITE_OK ){
+ rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
+ pPager->aStat[PAGER_STAT_WRITE]++;
+ }
+ if( rc==SQLITE_OK ){
+ /* Update the pager's copy of the change-counter. Otherwise, the
+ ** next time a read transaction is opened the cache will be
+ ** flushed (as the change-counter values will not match). */
+ const void *pCopy = (const void *)&((const char *)zBuf)[24];
+ memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
+ pPager->changeCountDone = 1;
+ }
+ }else{
+ pPager->changeCountDone = 1;
+ }
+ }
+
+ /* Release the page reference. */
+ sqlite3PagerUnref(pPgHdr);
+ }
+ return rc;
+}
+
+/*
+** Sync the database file to disk. This is a no-op for in-memory databases
+** or pages with the Pager.noSync flag set.
+**
+** If successful, or if called on a pager for which it is a no-op, this
+** function returns SQLITE_OK. Otherwise, an IO error code is returned.
+*/
+SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zSuper){
+ int rc = SQLITE_OK;
+ void *pArg = (void*)zSuper;
+ rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
+ if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
+ if( rc==SQLITE_OK && !pPager->noSync ){
+ assert( !MEMDB );
+ rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
+ }
+ return rc;
+}
+
+/*
+** This function may only be called while a write-transaction is active in
+** rollback. If the connection is in WAL mode, this call is a no-op.
+** Otherwise, if the connection does not already have an EXCLUSIVE lock on
+** the database file, an attempt is made to obtain one.
+**
+** If the EXCLUSIVE lock is already held or the attempt to obtain it is
+** successful, or the connection is in WAL mode, SQLITE_OK is returned.
+** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
+** returned.
+*/
+SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
+ int rc = pPager->errCode;
+ assert( assert_pager_state(pPager) );
+ if( rc==SQLITE_OK ){
+ assert( pPager->eState==PAGER_WRITER_CACHEMOD
+ || pPager->eState==PAGER_WRITER_DBMOD
+ || pPager->eState==PAGER_WRITER_LOCKED
+ );
+ assert( assert_pager_state(pPager) );
+ if( 0==pagerUseWal(pPager) ){
+ rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
+ }
+ }
+ return rc;
+}
+
+/*
+** Sync the database file for the pager pPager. zSuper points to the name
+** of a super-journal file that should be written into the individual
+** journal file. zSuper may be NULL, which is interpreted as no
+** super-journal (a single database transaction).
+**
+** This routine ensures that:
+**
+** * The database file change-counter is updated,
+** * the journal is synced (unless the atomic-write optimization is used),
+** * all dirty pages are written to the database file,
+** * the database file is truncated (if required), and
+** * the database file synced.
+**
+** The only thing that remains to commit the transaction is to finalize
+** (delete, truncate or zero the first part of) the journal file (or
+** delete the super-journal file if specified).
+**
+** Note that if zSuper==NULL, this does not overwrite a previous value
+** passed to an sqlite3PagerCommitPhaseOne() call.
+**
+** If the final parameter - noSync - is true, then the database file itself
+** is not synced. The caller must call sqlite3PagerSync() directly to
+** sync the database file before calling CommitPhaseTwo() to delete the
+** journal file in this case.
+*/
+SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
+ Pager *pPager, /* Pager object */
+ const char *zSuper, /* If not NULL, the super-journal name */
+ int noSync /* True to omit the xSync on the db file */
+){
+ int rc = SQLITE_OK; /* Return code */
+
+ assert( pPager->eState==PAGER_WRITER_LOCKED
+ || pPager->eState==PAGER_WRITER_CACHEMOD
+ || pPager->eState==PAGER_WRITER_DBMOD
+ || pPager->eState==PAGER_ERROR
+ );
+ assert( assert_pager_state(pPager) );
+
+ /* If a prior error occurred, report that error again. */
+ if( NEVER(pPager->errCode) ) return pPager->errCode;
+
+ /* Provide the ability to easily simulate an I/O error during testing */
+ if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
+
+ PAGERTRACE(("DATABASE SYNC: File=%s zSuper=%s nSize=%d\n",
+ pPager->zFilename, zSuper, pPager->dbSize));
+
+ /* If no database changes have been made, return early. */
+ if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
+
+ assert( MEMDB==0 || pPager->tempFile );
+ assert( isOpen(pPager->fd) || pPager->tempFile );
+ if( 0==pagerFlushOnCommit(pPager, 1) ){
+ /* If this is an in-memory db, or no pages have been written to, or this
+ ** function has already been called, it is mostly a no-op. However, any
+ ** backup in progress needs to be restarted. */
+ sqlite3BackupRestart(pPager->pBackup);
+ }else{
+ PgHdr *pList;
+ if( pagerUseWal(pPager) ){
+ PgHdr *pPageOne = 0;
+ pList = sqlite3PcacheDirtyList(pPager->pPCache);
+ if( pList==0 ){
+ /* Must have at least one page for the WAL commit flag.
+ ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
+ rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
+ pList = pPageOne;
+ pList->pDirty = 0;
+ }
+ assert( rc==SQLITE_OK );
+ if( ALWAYS(pList) ){
+ rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
+ }
+ sqlite3PagerUnref(pPageOne);
+ if( rc==SQLITE_OK ){
+ sqlite3PcacheCleanAll(pPager->pPCache);
+ }
+ }else{
+ /* The bBatch boolean is true if the batch-atomic-write commit method
+ ** should be used. No rollback journal is created if batch-atomic-write
+ ** is enabled.
+ */
+#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
+ sqlite3_file *fd = pPager->fd;
+ int bBatch = zSuper==0 /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
+ && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
+ && !pPager->noSync
+ && sqlite3JournalIsInMemory(pPager->jfd);
+#else
+# define bBatch 0
+#endif
+
+#ifdef SQLITE_ENABLE_ATOMIC_WRITE
+ /* The following block updates the change-counter. Exactly how it
+ ** does this depends on whether or not the atomic-update optimization
+ ** was enabled at compile time, and if this transaction meets the
+ ** runtime criteria to use the operation:
+ **
+ ** * The file-system supports the atomic-write property for
+ ** blocks of size page-size, and
+ ** * This commit is not part of a multi-file transaction, and
+ ** * Exactly one page has been modified and store in the journal file.
+ **
+ ** If the optimization was not enabled at compile time, then the
+ ** pager_incr_changecounter() function is called to update the change
+ ** counter in 'indirect-mode'. If the optimization is compiled in but
+ ** is not applicable to this transaction, call sqlite3JournalCreate()
+ ** to make sure the journal file has actually been created, then call
+ ** pager_incr_changecounter() to update the change-counter in indirect
+ ** mode.
+ **
+ ** Otherwise, if the optimization is both enabled and applicable,
+ ** then call pager_incr_changecounter() to update the change-counter
+ ** in 'direct' mode. In this case the journal file will never be
+ ** created for this transaction.
+ */
+ if( bBatch==0 ){
+ PgHdr *pPg;
+ assert( isOpen(pPager->jfd)
+ || pPager->journalMode==PAGER_JOURNALMODE_OFF
+ || pPager->journalMode==PAGER_JOURNALMODE_WAL
+ );
+ if( !zSuper && isOpen(pPager->jfd)
+ && pPager->journalOff==jrnlBufferSize(pPager)
+ && pPager->dbSize>=pPager->dbOrigSize
+ && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
+ ){
+ /* Update the db file change counter via the direct-write method. The
+ ** following call will modify the in-memory representation of page 1
+ ** to include the updated change counter and then write page 1
+ ** directly to the database file. Because of the atomic-write
+ ** property of the host file-system, this is safe.
+ */
+ rc = pager_incr_changecounter(pPager, 1);
+ }else{
+ rc = sqlite3JournalCreate(pPager->jfd);
+ if( rc==SQLITE_OK ){
+ rc = pager_incr_changecounter(pPager, 0);
+ }
+ }
+ }
+#else /* SQLITE_ENABLE_ATOMIC_WRITE */
+#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
+ if( zSuper ){
+ rc = sqlite3JournalCreate(pPager->jfd);
+ if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
+ assert( bBatch==0 );
+ }
+#endif
+ rc = pager_incr_changecounter(pPager, 0);
+#endif /* !SQLITE_ENABLE_ATOMIC_WRITE */
+ if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
+
+ /* Write the super-journal name into the journal file. If a
+ ** super-journal file name has already been written to the journal file,
+ ** or if zSuper is NULL (no super-journal), then this call is a no-op.
+ */
+ rc = writeSuperJournal(pPager, zSuper);
+ if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
+
+ /* Sync the journal file and write all dirty pages to the database.
+ ** If the atomic-update optimization is being used, this sync will not
+ ** create the journal file or perform any real IO.
+ **
+ ** Because the change-counter page was just modified, unless the
+ ** atomic-update optimization is used it is almost certain that the
+ ** journal requires a sync here. However, in locking_mode=exclusive
+ ** on a system under memory pressure it is just possible that this is
+ ** not the case. In this case it is likely enough that the redundant
+ ** xSync() call will be changed to a no-op by the OS anyhow.
+ */
+ rc = syncJournal(pPager, 0);
+ if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
+
+ pList = sqlite3PcacheDirtyList(pPager->pPCache);
+#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
+ if( bBatch ){
+ rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
+ if( rc==SQLITE_OK ){
+ rc = pager_write_pagelist(pPager, pList);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
+ }
+ if( rc!=SQLITE_OK ){
+ sqlite3OsFileControlHint(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);
+ }
+ }
+
+ if( (rc&0xFF)==SQLITE_IOERR && rc!=SQLITE_IOERR_NOMEM ){
+ rc = sqlite3JournalCreate(pPager->jfd);
+ if( rc!=SQLITE_OK ){
+ sqlite3OsClose(pPager->jfd);
+ goto commit_phase_one_exit;
+ }
+ bBatch = 0;
+ }else{
+ sqlite3OsClose(pPager->jfd);
+ }
+ }
+#endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
+
+ if( bBatch==0 ){
+ rc = pager_write_pagelist(pPager, pList);
+ }
+ if( rc!=SQLITE_OK ){
+ assert( rc!=SQLITE_IOERR_BLOCKED );
+ goto commit_phase_one_exit;
+ }
+ sqlite3PcacheCleanAll(pPager->pPCache);
+
+ /* If the file on disk is smaller than the database image, use
+ ** pager_truncate to grow the file here. This can happen if the database
+ ** image was extended as part of the current transaction and then the
+ ** last page in the db image moved to the free-list. In this case the
+ ** last page is never written out to disk, leaving the database file
+ ** undersized. Fix this now if it is the case. */
+ if( pPager->dbSize>pPager->dbFileSize ){
+ Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
+ assert( pPager->eState==PAGER_WRITER_DBMOD );
+ rc = pager_truncate(pPager, nNew);
+ if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
+ }
+
+ /* Finally, sync the database file. */
+ if( !noSync ){
+ rc = sqlite3PagerSync(pPager, zSuper);
+ }
+ IOTRACE(("DBSYNC %p\n", pPager))
+ }
+ }
+
+commit_phase_one_exit:
+ if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
+ pPager->eState = PAGER_WRITER_FINISHED;
+ }
+ return rc;
+}
+
+
+/*
+** When this function is called, the database file has been completely
+** updated to reflect the changes made by the current transaction and
+** synced to disk. The journal file still exists in the file-system
+** though, and if a failure occurs at this point it will eventually
+** be used as a hot-journal and the current transaction rolled back.
+**
+** This function finalizes the journal file, either by deleting,
+** truncating or partially zeroing it, so that it cannot be used
+** for hot-journal rollback. Once this is done the transaction is
+** irrevocably committed.
+**
+** If an error occurs, an IO error code is returned and the pager
+** moves into the error state. Otherwise, SQLITE_OK is returned.
+*/
+SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
+ int rc = SQLITE_OK; /* Return code */
+
+ /* This routine should not be called if a prior error has occurred.
+ ** But if (due to a coding error elsewhere in the system) it does get
+ ** called, just return the same error code without doing anything. */
+ if( NEVER(pPager->errCode) ) return pPager->errCode;
+ pPager->iDataVersion++;
+
+ assert( pPager->eState==PAGER_WRITER_LOCKED
+ || pPager->eState==PAGER_WRITER_FINISHED
+ || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
+ );
+ assert( assert_pager_state(pPager) );
+
+ /* An optimization. If the database was not actually modified during
+ ** this transaction, the pager is running in exclusive-mode and is
+ ** using persistent journals, then this function is a no-op.
+ **
+ ** The start of the journal file currently contains a single journal
+ ** header with the nRec field set to 0. If such a journal is used as
+ ** a hot-journal during hot-journal rollback, 0 changes will be made
+ ** to the database file. So there is no need to zero the journal
+ ** header. Since the pager is in exclusive mode, there is no need
+ ** to drop any locks either.
+ */
+ if( pPager->eState==PAGER_WRITER_LOCKED
+ && pPager->exclusiveMode
+ && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
+ ){
+ assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
+ pPager->eState = PAGER_READER;
+ return SQLITE_OK;
+ }
+
+ PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
+ rc = pager_end_transaction(pPager, pPager->setSuper, 1);
+ return pager_error(pPager, rc);
+}
+
+/*
+** If a write transaction is open, then all changes made within the
+** transaction are reverted and the current write-transaction is closed.
+** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
+** state if an error occurs.
+**
+** If the pager is already in PAGER_ERROR state when this function is called,
+** it returns Pager.errCode immediately. No work is performed in this case.
+**
+** Otherwise, in rollback mode, this function performs two functions:
+**
+** 1) It rolls back the journal file, restoring all database file and
+** in-memory cache pages to the state they were in when the transaction
+** was opened, and
+**
+** 2) It finalizes the journal file, so that it is not used for hot
+** rollback at any point in the future.
+**
+** Finalization of the journal file (task 2) is only performed if the
+** rollback is successful.
+**
+** In WAL mode, all cache-entries containing data modified within the
+** current transaction are either expelled from the cache or reverted to
+** their pre-transaction state by re-reading data from the database or
+** WAL files. The WAL transaction is then closed.
+*/
+SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
+ int rc = SQLITE_OK; /* Return code */
+ PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
+
+ /* PagerRollback() is a no-op if called in READER or OPEN state. If
+ ** the pager is already in the ERROR state, the rollback is not
+ ** attempted here. Instead, the error code is returned to the caller.
+ */
+ assert( assert_pager_state(pPager) );
+ if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
+ if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
+
+ if( pagerUseWal(pPager) ){
+ int rc2;
+ rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
+ rc2 = pager_end_transaction(pPager, pPager->setSuper, 0);
+ if( rc==SQLITE_OK ) rc = rc2;
+ }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
+ int eState = pPager->eState;
+ rc = pager_end_transaction(pPager, 0, 0);
+ if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
+ /* This can happen using journal_mode=off. Move the pager to the error
+ ** state to indicate that the contents of the cache may not be trusted.
+ ** Any active readers will get SQLITE_ABORT.
+ */
+ pPager->errCode = SQLITE_ABORT;
+ pPager->eState = PAGER_ERROR;
+ setGetterMethod(pPager);
+ return rc;
+ }
+ }else{
+ rc = pager_playback(pPager, 0);
+ }
+
+ assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
+ assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
+ || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
+ || rc==SQLITE_CANTOPEN
+ );
+
+ /* If an error occurs during a ROLLBACK, we can no longer trust the pager
+ ** cache. So call pager_error() on the way out to make any error persistent.
+ */
+ return pager_error(pPager, rc);
+}
+
+/*
+** Return TRUE if the database file is opened read-only. Return FALSE
+** if the database is (in theory) writable.
+*/
+SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
+ return pPager->readOnly;
+}
+
+#ifdef SQLITE_DEBUG
+/*
+** Return the sum of the reference counts for all pages held by pPager.
+*/
+SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
+ return sqlite3PcacheRefCount(pPager->pPCache);
+}
+#endif
+
+/*
+** Return the approximate number of bytes of memory currently
+** used by the pager and its associated cache.
+*/
+SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
+ int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
+ + 5*sizeof(void*);
+ return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
+ + sqlite3MallocSize(pPager)
+ + pPager->pageSize;
+}
+
+/*
+** Return the number of references to the specified page.
+*/
+SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
+ return sqlite3PcachePageRefcount(pPage);
+}
+
+#ifdef SQLITE_TEST
+/*
+** This routine is used for testing and analysis only.
+*/
+SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
+ static int a[11];
+ a[0] = sqlite3PcacheRefCount(pPager->pPCache);
+ a[1] = sqlite3PcachePagecount(pPager->pPCache);
+ a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
+ a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
+ a[4] = pPager->eState;
+ a[5] = pPager->errCode;
+ a[6] = pPager->aStat[PAGER_STAT_HIT];
+ a[7] = pPager->aStat[PAGER_STAT_MISS];
+ a[8] = 0; /* Used to be pPager->nOvfl */
+ a[9] = pPager->nRead;
+ a[10] = pPager->aStat[PAGER_STAT_WRITE];
+ return a;
+}
+#endif
+
+/*
+** Parameter eStat must be one of SQLITE_DBSTATUS_CACHE_HIT, _MISS, _WRITE,
+** or _WRITE+1. The SQLITE_DBSTATUS_CACHE_WRITE+1 case is a translation
+** of SQLITE_DBSTATUS_CACHE_SPILL. The _SPILL case is not contiguous because
+** it was added later.
+**
+** Before returning, *pnVal is incremented by the
+** current cache hit or miss count, according to the value of eStat. If the
+** reset parameter is non-zero, the cache hit or miss count is zeroed before
+** returning.
+*/
+SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
+
+ assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
+ || eStat==SQLITE_DBSTATUS_CACHE_MISS
+ || eStat==SQLITE_DBSTATUS_CACHE_WRITE
+ || eStat==SQLITE_DBSTATUS_CACHE_WRITE+1
+ );
+
+ assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
+ assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
+ assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1
+ && PAGER_STAT_WRITE==2 && PAGER_STAT_SPILL==3 );
+
+ eStat -= SQLITE_DBSTATUS_CACHE_HIT;
+ *pnVal += pPager->aStat[eStat];
+ if( reset ){
+ pPager->aStat[eStat] = 0;
+ }
+}
+
+/*
+** Return true if this is an in-memory or temp-file backed pager.
+*/
+SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
+ return pPager->tempFile;
+}
+
+/*
+** Check that there are at least nSavepoint savepoints open. If there are
+** currently less than nSavepoints open, then open one or more savepoints
+** to make up the difference. If the number of savepoints is already
+** equal to nSavepoint, then this function is a no-op.
+**
+** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
+** occurs while opening the sub-journal file, then an IO error code is
+** returned. Otherwise, SQLITE_OK.
+*/
+static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
+ int rc = SQLITE_OK; /* Return code */
+ int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
+ int ii; /* Iterator variable */
+ PagerSavepoint *aNew; /* New Pager.aSavepoint array */
+
+ assert( pPager->eState>=PAGER_WRITER_LOCKED );
+ assert( assert_pager_state(pPager) );
+ assert( nSavepoint>nCurrent && pPager->useJournal );
+
+ /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
+ ** if the allocation fails. Otherwise, zero the new portion in case a
+ ** malloc failure occurs while populating it in the for(...) loop below.
+ */
+ aNew = (PagerSavepoint *)sqlite3Realloc(
+ pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
+ );
+ if( !aNew ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
+ pPager->aSavepoint = aNew;
+
+ /* Populate the PagerSavepoint structures just allocated. */
+ for(ii=nCurrent; ii<nSavepoint; ii++){
+ aNew[ii].nOrig = pPager->dbSize;
+ if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
+ aNew[ii].iOffset = pPager->journalOff;
+ }else{
+ aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
+ }
+ aNew[ii].iSubRec = pPager->nSubRec;
+ aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
+ if( !aNew[ii].pInSavepoint ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ if( pagerUseWal(pPager) ){
+ sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
+ }
+ pPager->nSavepoint = ii+1;
+ }
+ assert( pPager->nSavepoint==nSavepoint );
+ assertTruncateConstraint(pPager);
+ return rc;
+}
+SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
+ assert( pPager->eState>=PAGER_WRITER_LOCKED );
+ assert( assert_pager_state(pPager) );
+
+ if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
+ return pagerOpenSavepoint(pPager, nSavepoint);
+ }else{
+ return SQLITE_OK;
+ }
+}
+
+
+/*
+** This function is called to rollback or release (commit) a savepoint.
+** The savepoint to release or rollback need not be the most recently
+** created savepoint.
+**
+** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
+** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
+** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
+** that have occurred since the specified savepoint was created.
+**
+** The savepoint to rollback or release is identified by parameter
+** iSavepoint. A value of 0 means to operate on the outermost savepoint
+** (the first created). A value of (Pager.nSavepoint-1) means operate
+** on the most recently created savepoint. If iSavepoint is greater than
+** (Pager.nSavepoint-1), then this function is a no-op.
+**
+** If a negative value is passed to this function, then the current
+** transaction is rolled back. This is different to calling
+** sqlite3PagerRollback() because this function does not terminate
+** the transaction or unlock the database, it just restores the
+** contents of the database to its original state.
+**
+** In any case, all savepoints with an index greater than iSavepoint
+** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
+** then savepoint iSavepoint is also destroyed.
+**
+** This function may return SQLITE_NOMEM if a memory allocation fails,
+** or an IO error code if an IO error occurs while rolling back a
+** savepoint. If no errors occur, SQLITE_OK is returned.
+*/
+SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
+ int rc = pPager->errCode;
+
+#ifdef SQLITE_ENABLE_ZIPVFS
+ if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
+#endif
+
+ assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
+ assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
+
+ if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
+ int ii; /* Iterator variable */
+ int nNew; /* Number of remaining savepoints after this op. */
+
+ /* Figure out how many savepoints will still be active after this
+ ** operation. Store this value in nNew. Then free resources associated
+ ** with any savepoints that are destroyed by this operation.
+ */
+ nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
+ for(ii=nNew; ii<pPager->nSavepoint; ii++){
+ sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
+ }
+ pPager->nSavepoint = nNew;
+
+ /* If this is a release of the outermost savepoint, truncate
+ ** the sub-journal to zero bytes in size. */
+ if( op==SAVEPOINT_RELEASE ){
+ if( nNew==0 && isOpen(pPager->sjfd) ){
+ /* Only truncate if it is an in-memory sub-journal. */
+ if( sqlite3JournalIsInMemory(pPager->sjfd) ){
+ rc = sqlite3OsTruncate(pPager->sjfd, 0);
+ assert( rc==SQLITE_OK );
+ }
+ pPager->nSubRec = 0;
+ }
+ }
+ /* Else this is a rollback operation, playback the specified savepoint.
+ ** If this is a temp-file, it is possible that the journal file has
+ ** not yet been opened. In this case there have been no changes to
+ ** the database file, so the playback operation can be skipped.
+ */
+ else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
+ PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
+ rc = pagerPlaybackSavepoint(pPager, pSavepoint);
+ assert(rc!=SQLITE_DONE);
+ }
+
+#ifdef SQLITE_ENABLE_ZIPVFS
+ /* If the cache has been modified but the savepoint cannot be rolled
+ ** back journal_mode=off, put the pager in the error state. This way,
+ ** if the VFS used by this pager includes ZipVFS, the entire transaction
+ ** can be rolled back at the ZipVFS level. */
+ else if(
+ pPager->journalMode==PAGER_JOURNALMODE_OFF
+ && pPager->eState>=PAGER_WRITER_CACHEMOD
+ ){
+ pPager->errCode = SQLITE_ABORT;
+ pPager->eState = PAGER_ERROR;
+ setGetterMethod(pPager);
+ }
+#endif
+ }
+
+ return rc;
+}
+
+/*
+** Return the full pathname of the database file.
+**
+** Except, if the pager is in-memory only, then return an empty string if
+** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
+** used to report the filename to the user, for compatibility with legacy
+** behavior. But when the Btree needs to know the filename for matching to
+** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
+** participate in shared-cache.
+**
+** The return value to this routine is always safe to use with
+** sqlite3_uri_parameter() and sqlite3_filename_database() and friends.
+*/
+SQLITE_PRIVATE const char *sqlite3PagerFilename(const Pager *pPager, int nullIfMemDb){
+ static const char zFake[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
+ return (nullIfMemDb && pPager->memDb) ? &zFake[4] : pPager->zFilename;
+}
+
+/*
+** Return the VFS structure for the pager.
+*/
+SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
+ return pPager->pVfs;
+}
+
+/*
+** Return the file handle for the database file associated
+** with the pager. This might return NULL if the file has
+** not yet been opened.
+*/
+SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
+ return pPager->fd;
+}
+
+/*
+** Return the file handle for the journal file (if it exists).
+** This will be either the rollback journal or the WAL file.
+*/
+SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
+#if SQLITE_OMIT_WAL
+ return pPager->jfd;
+#else
+ return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
+#endif
+}
+
+/*
+** Return the full pathname of the journal file.
+*/
+SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
+ return pPager->zJournal;
+}
+
+#ifndef SQLITE_OMIT_AUTOVACUUM
+/*
+** Move the page pPg to location pgno in the file.
+**
+** There must be no references to the page previously located at
+** pgno (which we call pPgOld) though that page is allowed to be
+** in cache. If the page previously located at pgno is not already
+** in the rollback journal, it is not put there by by this routine.
+**
+** References to the page pPg remain valid. Updating any
+** meta-data associated with pPg (i.e. data stored in the nExtra bytes
+** allocated along with the page) is the responsibility of the caller.
+**
+** A transaction must be active when this routine is called. It used to be
+** required that a statement transaction was not active, but this restriction
+** has been removed (CREATE INDEX needs to move a page when a statement
+** transaction is active).
+**
+** If the fourth argument, isCommit, is non-zero, then this page is being
+** moved as part of a database reorganization just before the transaction
+** is being committed. In this case, it is guaranteed that the database page
+** pPg refers to will not be written to again within this transaction.
+**
+** This function may return SQLITE_NOMEM or an IO error code if an error
+** occurs. Otherwise, it returns SQLITE_OK.
+*/
+SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
+ PgHdr *pPgOld; /* The page being overwritten. */
+ Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
+ int rc; /* Return code */
+ Pgno origPgno; /* The original page number */
+
+ assert( pPg->nRef>0 );
+ assert( pPager->eState==PAGER_WRITER_CACHEMOD
+ || pPager->eState==PAGER_WRITER_DBMOD
+ );
+ assert( assert_pager_state(pPager) );
+
+ /* In order to be able to rollback, an in-memory database must journal
+ ** the page we are moving from.
+ */
+ assert( pPager->tempFile || !MEMDB );
+ if( pPager->tempFile ){
+ rc = sqlite3PagerWrite(pPg);
+ if( rc ) return rc;
+ }
+
+ /* If the page being moved is dirty and has not been saved by the latest
+ ** savepoint, then save the current contents of the page into the
+ ** sub-journal now. This is required to handle the following scenario:
+ **
+ ** BEGIN;
+ ** <journal page X, then modify it in memory>
+ ** SAVEPOINT one;
+ ** <Move page X to location Y>
+ ** ROLLBACK TO one;
+ **
+ ** If page X were not written to the sub-journal here, it would not
+ ** be possible to restore its contents when the "ROLLBACK TO one"
+ ** statement were is processed.
+ **
+ ** subjournalPage() may need to allocate space to store pPg->pgno into
+ ** one or more savepoint bitvecs. This is the reason this function
+ ** may return SQLITE_NOMEM.
+ */
+ if( (pPg->flags & PGHDR_DIRTY)!=0
+ && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
+ ){
+ return rc;
+ }
+
+ PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
+ PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
+ IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
+
+ /* If the journal needs to be sync()ed before page pPg->pgno can
+ ** be written to, store pPg->pgno in local variable needSyncPgno.
+ **
+ ** If the isCommit flag is set, there is no need to remember that
+ ** the journal needs to be sync()ed before database page pPg->pgno
+ ** can be written to. The caller has already promised not to write to it.
+ */
+ if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
+ needSyncPgno = pPg->pgno;
+ assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
+ pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
+ assert( pPg->flags&PGHDR_DIRTY );
+ }
+
+ /* If the cache contains a page with page-number pgno, remove it
+ ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
+ ** page pgno before the 'move' operation, it needs to be retained
+ ** for the page moved there.
+ */
+ pPg->flags &= ~PGHDR_NEED_SYNC;
+ pPgOld = sqlite3PagerLookup(pPager, pgno);
+ assert( !pPgOld || pPgOld->nRef==1 || CORRUPT_DB );
+ if( pPgOld ){
+ if( pPgOld->nRef>1 ){
+ sqlite3PagerUnrefNotNull(pPgOld);
+ return SQLITE_CORRUPT_BKPT;
+ }
+ pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
+ if( pPager->tempFile ){
+ /* Do not discard pages from an in-memory database since we might
+ ** need to rollback later. Just move the page out of the way. */
+ sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
+ }else{
+ sqlite3PcacheDrop(pPgOld);
+ }
+ }
+
+ origPgno = pPg->pgno;
+ sqlite3PcacheMove(pPg, pgno);
+ sqlite3PcacheMakeDirty(pPg);
+
+ /* For an in-memory database, make sure the original page continues
+ ** to exist, in case the transaction needs to roll back. Use pPgOld
+ ** as the original page since it has already been allocated.
+ */
+ if( pPager->tempFile && pPgOld ){
+ sqlite3PcacheMove(pPgOld, origPgno);
+ sqlite3PagerUnrefNotNull(pPgOld);
+ }
+
+ if( needSyncPgno ){
+ /* If needSyncPgno is non-zero, then the journal file needs to be
+ ** sync()ed before any data is written to database file page needSyncPgno.
+ ** Currently, no such page exists in the page-cache and the
+ ** "is journaled" bitvec flag has been set. This needs to be remedied by
+ ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
+ ** flag.
+ **
+ ** If the attempt to load the page into the page-cache fails, (due
+ ** to a malloc() or IO failure), clear the bit in the pInJournal[]
+ ** array. Otherwise, if the page is loaded and written again in
+ ** this transaction, it may be written to the database file before
+ ** it is synced into the journal file. This way, it may end up in
+ ** the journal file twice, but that is not a problem.
+ */
+ PgHdr *pPgHdr;
+ rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
+ if( rc!=SQLITE_OK ){
+ if( needSyncPgno<=pPager->dbOrigSize ){
+ assert( pPager->pTmpSpace!=0 );
+ sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
+ }
+ return rc;
+ }
+ pPgHdr->flags |= PGHDR_NEED_SYNC;
+ sqlite3PcacheMakeDirty(pPgHdr);
+ sqlite3PagerUnrefNotNull(pPgHdr);
+ }
+
+ return SQLITE_OK;
+}
+#endif
+
+/*
+** The page handle passed as the first argument refers to a dirty page
+** with a page number other than iNew. This function changes the page's
+** page number to iNew and sets the value of the PgHdr.flags field to
+** the value passed as the third parameter.
+*/
+SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
+ assert( pPg->pgno!=iNew );
+ pPg->flags = flags;
+ sqlite3PcacheMove(pPg, iNew);
+}
+
+/*
+** Return a pointer to the data for the specified page.
+*/
+SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
+ assert( pPg->nRef>0 || pPg->pPager->memDb );
+ return pPg->pData;
+}
+
+/*
+** Return a pointer to the Pager.nExtra bytes of "extra" space
+** allocated along with the specified page.
+*/
+SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
+ return pPg->pExtra;
+}
+
+/*
+** Get/set the locking-mode for this pager. Parameter eMode must be one
+** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
+** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
+** the locking-mode is set to the value specified.
+**
+** The returned value is either PAGER_LOCKINGMODE_NORMAL or
+** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
+** locking-mode.
+*/
+SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
+ assert( eMode==PAGER_LOCKINGMODE_QUERY
+ || eMode==PAGER_LOCKINGMODE_NORMAL
+ || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
+ assert( PAGER_LOCKINGMODE_QUERY<0 );
+ assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
+ assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
+ if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
+ pPager->exclusiveMode = (u8)eMode;
+ }
+ return (int)pPager->exclusiveMode;
+}
+
+/*
+** Set the journal-mode for this pager. Parameter eMode must be one of:
+**
+** PAGER_JOURNALMODE_DELETE
+** PAGER_JOURNALMODE_TRUNCATE
+** PAGER_JOURNALMODE_PERSIST
+** PAGER_JOURNALMODE_OFF
+** PAGER_JOURNALMODE_MEMORY
+** PAGER_JOURNALMODE_WAL
+**
+** The journalmode is set to the value specified if the change is allowed.
+** The change may be disallowed for the following reasons:
+**
+** * An in-memory database can only have its journal_mode set to _OFF
+** or _MEMORY.
+**
+** * Temporary databases cannot have _WAL journalmode.
+**
+** The returned indicate the current (possibly updated) journal-mode.
+*/
+SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
+ u8 eOld = pPager->journalMode; /* Prior journalmode */
+
+ /* The eMode parameter is always valid */
+ assert( eMode==PAGER_JOURNALMODE_DELETE
+ || eMode==PAGER_JOURNALMODE_TRUNCATE
+ || eMode==PAGER_JOURNALMODE_PERSIST
+ || eMode==PAGER_JOURNALMODE_OFF
+ || eMode==PAGER_JOURNALMODE_WAL
+ || eMode==PAGER_JOURNALMODE_MEMORY );
+
+ /* This routine is only called from the OP_JournalMode opcode, and
+ ** the logic there will never allow a temporary file to be changed
+ ** to WAL mode.
+ */
+ assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
+
+ /* Do allow the journalmode of an in-memory database to be set to
+ ** anything other than MEMORY or OFF
+ */
+ if( MEMDB ){
+ assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
+ if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
+ eMode = eOld;
+ }
+ }
+
+ if( eMode!=eOld ){
+
+ /* Change the journal mode. */
+ assert( pPager->eState!=PAGER_ERROR );
+ pPager->journalMode = (u8)eMode;
+
+ /* When transistioning from TRUNCATE or PERSIST to any other journal
+ ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
+ ** delete the journal file.
+ */
+ assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
+ assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
+ assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
+ assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
+ assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
+ assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
+
+ assert( isOpen(pPager->fd) || pPager->exclusiveMode );
+ if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
+
+ /* In this case we would like to delete the journal file. If it is
+ ** not possible, then that is not a problem. Deleting the journal file
+ ** here is an optimization only.
+ **
+ ** Before deleting the journal file, obtain a RESERVED lock on the
+ ** database file. This ensures that the journal file is not deleted
+ ** while it is in use by some other client.
+ */
+ sqlite3OsClose(pPager->jfd);
+ if( pPager->eLock>=RESERVED_LOCK ){
+ sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
+ }else{
+ int rc = SQLITE_OK;
+ int state = pPager->eState;
+ assert( state==PAGER_OPEN || state==PAGER_READER );
+ if( state==PAGER_OPEN ){
+ rc = sqlite3PagerSharedLock(pPager);
+ }
+ if( pPager->eState==PAGER_READER ){
+ assert( rc==SQLITE_OK );
+ rc = pagerLockDb(pPager, RESERVED_LOCK);
+ }
+ if( rc==SQLITE_OK ){
+ sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
+ }
+ if( rc==SQLITE_OK && state==PAGER_READER ){
+ pagerUnlockDb(pPager, SHARED_LOCK);
+ }else if( state==PAGER_OPEN ){
+ pager_unlock(pPager);
+ }
+ assert( state==pPager->eState );
+ }
+ }else if( eMode==PAGER_JOURNALMODE_OFF ){
+ sqlite3OsClose(pPager->jfd);
+ }
+ }
+
+ /* Return the new journal mode */
+ return (int)pPager->journalMode;
+}
+
+/*
+** Return the current journal mode.
+*/
+SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
+ return (int)pPager->journalMode;
+}
+
+/*
+** Return TRUE if the pager is in a state where it is OK to change the
+** journalmode. Journalmode changes can only happen when the database
+** is unmodified.
+*/
+SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
+ assert( assert_pager_state(pPager) );
+ if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
+ if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
+ return 1;
+}
+
+/*
+** Get/set the size-limit used for persistent journal files.
+**
+** Setting the size limit to -1 means no limit is enforced.
+** An attempt to set a limit smaller than -1 is a no-op.
+*/
+SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
+ if( iLimit>=-1 ){
+ pPager->journalSizeLimit = iLimit;
+ sqlite3WalLimit(pPager->pWal, iLimit);
+ }
+ return pPager->journalSizeLimit;
+}
+
+/*
+** Return a pointer to the pPager->pBackup variable. The backup module
+** in backup.c maintains the content of this variable. This module
+** uses it opaquely as an argument to sqlite3BackupRestart() and
+** sqlite3BackupUpdate() only.
+*/
+SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
+ return &pPager->pBackup;
+}
+
+#ifndef SQLITE_OMIT_VACUUM
+/*
+** Unless this is an in-memory or temporary database, clear the pager cache.
+*/
+SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
+ assert( MEMDB==0 || pPager->tempFile );
+ if( pPager->tempFile==0 ) pager_reset(pPager);
+}
+#endif
+
+
+#ifndef SQLITE_OMIT_WAL
+/*
+** This function is called when the user invokes "PRAGMA wal_checkpoint",
+** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
+** or wal_blocking_checkpoint() API functions.
+**
+** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
+*/
+SQLITE_PRIVATE int sqlite3PagerCheckpoint(
+ Pager *pPager, /* Checkpoint on this pager */
+ sqlite3 *db, /* Db handle used to check for interrupts */
+ int eMode, /* Type of checkpoint */
+ int *pnLog, /* OUT: Final number of frames in log */
+ int *pnCkpt /* OUT: Final number of checkpointed frames */
+){
+ int rc = SQLITE_OK;
+ if( pPager->pWal ){
+ rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
+ (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
+ pPager->pBusyHandlerArg,
+ pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
+ pnLog, pnCkpt
+ );
+ }
+ return rc;
+}
+
+SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
+ return sqlite3WalCallback(pPager->pWal);
+}
+
+/*
+** Return true if the underlying VFS for the given pager supports the
+** primitives necessary for write-ahead logging.
+*/
+SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
+ const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
+ if( pPager->noLock ) return 0;
+ return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
+}
+
+/*
+** Attempt to take an exclusive lock on the database file. If a PENDING lock
+** is obtained instead, immediately release it.
+*/
+static int pagerExclusiveLock(Pager *pPager){
+ int rc; /* Return code */
+
+ assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
+ rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
+ if( rc!=SQLITE_OK ){
+ /* If the attempt to grab the exclusive lock failed, release the
+ ** pending lock that may have been obtained instead. */
+ pagerUnlockDb(pPager, SHARED_LOCK);
+ }
+
+ return rc;
+}
+
+/*
+** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
+** exclusive-locking mode when this function is called, take an EXCLUSIVE
+** lock on the database file and use heap-memory to store the wal-index
+** in. Otherwise, use the normal shared-memory.
+*/
+static int pagerOpenWal(Pager *pPager){
+ int rc = SQLITE_OK;
+
+ assert( pPager->pWal==0 && pPager->tempFile==0 );
+ assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
+
+ /* If the pager is already in exclusive-mode, the WAL module will use
+ ** heap-memory for the wal-index instead of the VFS shared-memory
+ ** implementation. Take the exclusive lock now, before opening the WAL
+ ** file, to make sure this is safe.
+ */
+ if( pPager->exclusiveMode ){
+ rc = pagerExclusiveLock(pPager);
+ }
+
+ /* Open the connection to the log file. If this operation fails,
+ ** (e.g. due to malloc() failure), return an error code.
+ */
+ if( rc==SQLITE_OK ){
+ rc = sqlite3WalOpen(pPager->pVfs,
+ pPager->fd, pPager->zWal, pPager->exclusiveMode,
+ pPager->journalSizeLimit, &pPager->pWal
+ );
+ }
+ pagerFixMaplimit(pPager);
+
+ return rc;
+}
+
+
+/*
+** The caller must be holding a SHARED lock on the database file to call
+** this function.
+**
+** If the pager passed as the first argument is open on a real database
+** file (not a temp file or an in-memory database), and the WAL file
+** is not already open, make an attempt to open it now. If successful,
+** return SQLITE_OK. If an error occurs or the VFS used by the pager does
+** not support the xShmXXX() methods, return an error code. *pbOpen is
+** not modified in either case.
+**
+** If the pager is open on a temp-file (or in-memory database), or if
+** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
+** without doing anything.
+*/
+SQLITE_PRIVATE int sqlite3PagerOpenWal(
+ Pager *pPager, /* Pager object */
+ int *pbOpen /* OUT: Set to true if call is a no-op */
+){
+ int rc = SQLITE_OK; /* Return code */
+
+ assert( assert_pager_state(pPager) );
+ assert( pPager->eState==PAGER_OPEN || pbOpen );
+ assert( pPager->eState==PAGER_READER || !pbOpen );
+ assert( pbOpen==0 || *pbOpen==0 );
+ assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
+
+ if( !pPager->tempFile && !pPager->pWal ){
+ if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
+
+ /* Close any rollback journal previously open */
+ sqlite3OsClose(pPager->jfd);
+
+ rc = pagerOpenWal(pPager);
+ if( rc==SQLITE_OK ){
+ pPager->journalMode = PAGER_JOURNALMODE_WAL;
+ pPager->eState = PAGER_OPEN;
+ }
+ }else{
+ *pbOpen = 1;
+ }
+
+ return rc;
+}
+
+/*
+** This function is called to close the connection to the log file prior
+** to switching from WAL to rollback mode.
+**
+** Before closing the log file, this function attempts to take an
+** EXCLUSIVE lock on the database file. If this cannot be obtained, an
+** error (SQLITE_BUSY) is returned and the log connection is not closed.
+** If successful, the EXCLUSIVE lock is not released before returning.
+*/
+SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
+ int rc = SQLITE_OK;
+
+ assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
+
+ /* If the log file is not already open, but does exist in the file-system,
+ ** it may need to be checkpointed before the connection can switch to
+ ** rollback mode. Open it now so this can happen.
+ */
+ if( !pPager->pWal ){
+ int logexists = 0;
+ rc = pagerLockDb(pPager, SHARED_LOCK);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3OsAccess(
+ pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
+ );
+ }
+ if( rc==SQLITE_OK && logexists ){
+ rc = pagerOpenWal(pPager);
+ }
+ }
+
+ /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
+ ** the database file, the log and log-summary files will be deleted.
+ */
+ if( rc==SQLITE_OK && pPager->pWal ){
+ rc = pagerExclusiveLock(pPager);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
+ pPager->pageSize, (u8*)pPager->pTmpSpace);
+ pPager->pWal = 0;
+ pagerFixMaplimit(pPager);
+ if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
+ }
+ }
+ return rc;
+}
+
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+/*
+** If pager pPager is a wal-mode database not in exclusive locking mode,
+** invoke the sqlite3WalWriteLock() function on the associated Wal object
+** with the same db and bLock parameters as were passed to this function.
+** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
+*/
+SQLITE_PRIVATE int sqlite3PagerWalWriteLock(Pager *pPager, int bLock){
+ int rc = SQLITE_OK;
+ if( pagerUseWal(pPager) && pPager->exclusiveMode==0 ){
+ rc = sqlite3WalWriteLock(pPager->pWal, bLock);
+ }
+ return rc;
+}
+
+/*
+** Set the database handle used by the wal layer to determine if
+** blocking locks are required.
+*/
+SQLITE_PRIVATE void sqlite3PagerWalDb(Pager *pPager, sqlite3 *db){
+ if( pagerUseWal(pPager) ){
+ sqlite3WalDb(pPager->pWal, db);
+ }
+}
+#endif
+
+#ifdef SQLITE_ENABLE_SNAPSHOT
+/*
+** If this is a WAL database, obtain a snapshot handle for the snapshot
+** currently open. Otherwise, return an error.
+*/
+SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
+ int rc = SQLITE_ERROR;
+ if( pPager->pWal ){
+ rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
+ }
+ return rc;
+}
+
+/*
+** If this is a WAL database, store a pointer to pSnapshot. Next time a
+** read transaction is opened, attempt to read from the snapshot it
+** identifies. If this is not a WAL database, return an error.
+*/
+SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(
+ Pager *pPager,
+ sqlite3_snapshot *pSnapshot
+){
+ int rc = SQLITE_OK;
+ if( pPager->pWal ){
+ sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
+ }else{
+ rc = SQLITE_ERROR;
+ }
+ return rc;
+}
+
+/*
+** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
+** is not a WAL database, return an error.
+*/
+SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
+ int rc;
+ if( pPager->pWal ){
+ rc = sqlite3WalSnapshotRecover(pPager->pWal);
+ }else{
+ rc = SQLITE_ERROR;
+ }
+ return rc;
+}
+
+/*
+** The caller currently has a read transaction open on the database.
+** If this is not a WAL database, SQLITE_ERROR is returned. Otherwise,
+** this function takes a SHARED lock on the CHECKPOINTER slot and then
+** checks if the snapshot passed as the second argument is still
+** available. If so, SQLITE_OK is returned.
+**
+** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
+** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
+** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
+** lock is released before returning.
+*/
+SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot){
+ int rc;
+ if( pPager->pWal ){
+ rc = sqlite3WalSnapshotCheck(pPager->pWal, pSnapshot);
+ }else{
+ rc = SQLITE_ERROR;
+ }
+ return rc;
+}
+
+/*
+** Release a lock obtained by an earlier successful call to
+** sqlite3PagerSnapshotCheck().
+*/
+SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager){
+ assert( pPager->pWal );
+ sqlite3WalSnapshotUnlock(pPager->pWal);
+}
+
+#endif /* SQLITE_ENABLE_SNAPSHOT */
+#endif /* !SQLITE_OMIT_WAL */
+
+#ifdef SQLITE_ENABLE_ZIPVFS
+/*
+** A read-lock must be held on the pager when this function is called. If
+** the pager is in WAL mode and the WAL file currently contains one or more
+** frames, return the size in bytes of the page images stored within the
+** WAL frames. Otherwise, if this is not a WAL database or the WAL file
+** is empty, return 0.
+*/
+SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
+ assert( pPager->eState>=PAGER_READER );
+ return sqlite3WalFramesize(pPager->pWal);
+}
+#endif
+
+#endif /* SQLITE_OMIT_DISKIO */
+
+/************** End of pager.c ***********************************************/
+/************** Begin file wal.c *********************************************/
+/*
+** 2010 February 1
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains the implementation of a write-ahead log (WAL) used in
+** "journal_mode=WAL" mode.
+**
+** WRITE-AHEAD LOG (WAL) FILE FORMAT
+**
+** A WAL file consists of a header followed by zero or more "frames".
+** Each frame records the revised content of a single page from the
+** database file. All changes to the database are recorded by writing
+** frames into the WAL. Transactions commit when a frame is written that
+** contains a commit marker. A single WAL can and usually does record
+** multiple transactions. Periodically, the content of the WAL is
+** transferred back into the database file in an operation called a
+** "checkpoint".
+**
+** A single WAL file can be used multiple times. In other words, the
+** WAL can fill up with frames and then be checkpointed and then new
+** frames can overwrite the old ones. A WAL always grows from beginning
+** toward the end. Checksums and counters attached to each frame are
+** used to determine which frames within the WAL are valid and which
+** are leftovers from prior checkpoints.
+**
+** The WAL header is 32 bytes in size and consists of the following eight
+** big-endian 32-bit unsigned integer values:
+**
+** 0: Magic number. 0x377f0682 or 0x377f0683
+** 4: File format version. Currently 3007000
+** 8: Database page size. Example: 1024
+** 12: Checkpoint sequence number
+** 16: Salt-1, random integer incremented with each checkpoint
+** 20: Salt-2, a different random integer changing with each ckpt
+** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
+** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
+**
+** Immediately following the wal-header are zero or more frames. Each
+** frame consists of a 24-byte frame-header followed by a <page-size> bytes
+** of page data. The frame-header is six big-endian 32-bit unsigned
+** integer values, as follows:
+**
+** 0: Page number.
+** 4: For commit records, the size of the database image in pages
+** after the commit. For all other records, zero.
+** 8: Salt-1 (copied from the header)
+** 12: Salt-2 (copied from the header)
+** 16: Checksum-1.
+** 20: Checksum-2.
+**
+** A frame is considered valid if and only if the following conditions are
+** true:
+**
+** (1) The salt-1 and salt-2 values in the frame-header match
+** salt values in the wal-header
+**
+** (2) The checksum values in the final 8 bytes of the frame-header
+** exactly match the checksum computed consecutively on the
+** WAL header and the first 8 bytes and the content of all frames
+** up to and including the current frame.
+**
+** The checksum is computed using 32-bit big-endian integers if the
+** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
+** is computed using little-endian if the magic number is 0x377f0682.
+** The checksum values are always stored in the frame header in a
+** big-endian format regardless of which byte order is used to compute
+** the checksum. The checksum is computed by interpreting the input as
+** an even number of unsigned 32-bit integers: x[0] through x[N]. The
+** algorithm used for the checksum is as follows:
+**
+** for i from 0 to n-1 step 2:
+** s0 += x[i] + s1;
+** s1 += x[i+1] + s0;
+** endfor
+**
+** Note that s0 and s1 are both weighted checksums using fibonacci weights
+** in reverse order (the largest fibonacci weight occurs on the first element
+** of the sequence being summed.) The s1 value spans all 32-bit
+** terms of the sequence whereas s0 omits the final term.
+**
+** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
+** WAL is transferred into the database, then the database is VFS.xSync-ed.
+** The VFS.xSync operations serve as write barriers - all writes launched
+** before the xSync must complete before any write that launches after the
+** xSync begins.
+**
+** After each checkpoint, the salt-1 value is incremented and the salt-2
+** value is randomized. This prevents old and new frames in the WAL from
+** being considered valid at the same time and being checkpointing together
+** following a crash.
+**
+** READER ALGORITHM
+**
+** To read a page from the database (call it page number P), a reader
+** first checks the WAL to see if it contains page P. If so, then the
+** last valid instance of page P that is a followed by a commit frame
+** or is a commit frame itself becomes the value read. If the WAL
+** contains no copies of page P that are valid and which are a commit
+** frame or are followed by a commit frame, then page P is read from
+** the database file.
+**
+** To start a read transaction, the reader records the index of the last
+** valid frame in the WAL. The reader uses this recorded "mxFrame" value
+** for all subsequent read operations. New transactions can be appended
+** to the WAL, but as long as the reader uses its original mxFrame value
+** and ignores the newly appended content, it will see a consistent snapshot
+** of the database from a single point in time. This technique allows
+** multiple concurrent readers to view different versions of the database
+** content simultaneously.
+**
+** The reader algorithm in the previous paragraphs works correctly, but
+** because frames for page P can appear anywhere within the WAL, the
+** reader has to scan the entire WAL looking for page P frames. If the
+** WAL is large (multiple megabytes is typical) that scan can be slow,
+** and read performance suffers. To overcome this problem, a separate
+** data structure called the wal-index is maintained to expedite the
+** search for frames of a particular page.
+**
+** WAL-INDEX FORMAT
+**
+** Conceptually, the wal-index is shared memory, though VFS implementations
+** might choose to implement the wal-index using a mmapped file. Because
+** the wal-index is shared memory, SQLite does not support journal_mode=WAL
+** on a network filesystem. All users of the database must be able to
+** share memory.
+**
+** In the default unix and windows implementation, the wal-index is a mmapped
+** file whose name is the database name with a "-shm" suffix added. For that
+** reason, the wal-index is sometimes called the "shm" file.
+**
+** The wal-index is transient. After a crash, the wal-index can (and should
+** be) reconstructed from the original WAL file. In fact, the VFS is required
+** to either truncate or zero the header of the wal-index when the last
+** connection to it closes. Because the wal-index is transient, it can
+** use an architecture-specific format; it does not have to be cross-platform.
+** Hence, unlike the database and WAL file formats which store all values
+** as big endian, the wal-index can store multi-byte values in the native
+** byte order of the host computer.
+**
+** The purpose of the wal-index is to answer this question quickly: Given
+** a page number P and a maximum frame index M, return the index of the
+** last frame in the wal before frame M for page P in the WAL, or return
+** NULL if there are no frames for page P in the WAL prior to M.
+**
+** The wal-index consists of a header region, followed by an one or
+** more index blocks.
+**
+** The wal-index header contains the total number of frames within the WAL
+** in the mxFrame field.
+**
+** Each index block except for the first contains information on
+** HASHTABLE_NPAGE frames. The first index block contains information on
+** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
+** HASHTABLE_NPAGE are selected so that together the wal-index header and
+** first index block are the same size as all other index blocks in the
+** wal-index.
+**
+** Each index block contains two sections, a page-mapping that contains the
+** database page number associated with each wal frame, and a hash-table
+** that allows readers to query an index block for a specific page number.
+** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
+** for the first index block) 32-bit page numbers. The first entry in the
+** first index-block contains the database page number corresponding to the
+** first frame in the WAL file. The first entry in the second index block
+** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
+** the log, and so on.
+**
+** The last index block in a wal-index usually contains less than the full
+** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
+** depending on the contents of the WAL file. This does not change the
+** allocated size of the page-mapping array - the page-mapping array merely
+** contains unused entries.
+**
+** Even without using the hash table, the last frame for page P
+** can be found by scanning the page-mapping sections of each index block
+** starting with the last index block and moving toward the first, and
+** within each index block, starting at the end and moving toward the
+** beginning. The first entry that equals P corresponds to the frame
+** holding the content for that page.
+**
+** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
+** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
+** hash table for each page number in the mapping section, so the hash
+** table is never more than half full. The expected number of collisions
+** prior to finding a match is 1. Each entry of the hash table is an
+** 1-based index of an entry in the mapping section of the same
+** index block. Let K be the 1-based index of the largest entry in
+** the mapping section. (For index blocks other than the last, K will
+** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
+** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
+** contain a value of 0.
+**
+** To look for page P in the hash table, first compute a hash iKey on
+** P as follows:
+**
+** iKey = (P * 383) % HASHTABLE_NSLOT
+**
+** Then start scanning entries of the hash table, starting with iKey
+** (wrapping around to the beginning when the end of the hash table is
+** reached) until an unused hash slot is found. Let the first unused slot
+** be at index iUnused. (iUnused might be less than iKey if there was
+** wrap-around.) Because the hash table is never more than half full,
+** the search is guaranteed to eventually hit an unused entry. Let
+** iMax be the value between iKey and iUnused, closest to iUnused,
+** where aHash[iMax]==P. If there is no iMax entry (if there exists
+** no hash slot such that aHash[i]==p) then page P is not in the
+** current index block. Otherwise the iMax-th mapping entry of the
+** current index block corresponds to the last entry that references
+** page P.
+**
+** A hash search begins with the last index block and moves toward the
+** first index block, looking for entries corresponding to page P. On
+** average, only two or three slots in each index block need to be
+** examined in order to either find the last entry for page P, or to
+** establish that no such entry exists in the block. Each index block
+** holds over 4000 entries. So two or three index blocks are sufficient
+** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
+** comparisons (on average) suffice to either locate a frame in the
+** WAL or to establish that the frame does not exist in the WAL. This
+** is much faster than scanning the entire 10MB WAL.
+**
+** Note that entries are added in order of increasing K. Hence, one
+** reader might be using some value K0 and a second reader that started
+** at a later time (after additional transactions were added to the WAL
+** and to the wal-index) might be using a different value K1, where K1>K0.
+** Both readers can use the same hash table and mapping section to get
+** the correct result. There may be entries in the hash table with
+** K>K0 but to the first reader, those entries will appear to be unused
+** slots in the hash table and so the first reader will get an answer as
+** if no values greater than K0 had ever been inserted into the hash table
+** in the first place - which is what reader one wants. Meanwhile, the
+** second reader using K1 will see additional values that were inserted
+** later, which is exactly what reader two wants.
+**
+** When a rollback occurs, the value of K is decreased. Hash table entries
+** that correspond to frames greater than the new K value are removed
+** from the hash table at this point.
+*/
+#ifndef SQLITE_OMIT_WAL
+
+/* #include "wal.h" */
+
+/*
+** Trace output macros
+*/
+#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
+SQLITE_PRIVATE int sqlite3WalTrace = 0;
+# define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
+#else
+# define WALTRACE(X)
+#endif
+
+/*
+** The maximum (and only) versions of the wal and wal-index formats
+** that may be interpreted by this version of SQLite.
+**
+** If a client begins recovering a WAL file and finds that (a) the checksum
+** values in the wal-header are correct and (b) the version field is not
+** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
+**
+** Similarly, if a client successfully reads a wal-index header (i.e. the
+** checksum test is successful) and finds that the version field is not
+** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
+** returns SQLITE_CANTOPEN.
+*/
+#define WAL_MAX_VERSION 3007000
+#define WALINDEX_MAX_VERSION 3007000
+
+/*
+** Index numbers for various locking bytes. WAL_NREADER is the number
+** of available reader locks and should be at least 3. The default
+** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
+**
+** Technically, the various VFSes are free to implement these locks however
+** they see fit. However, compatibility is encouraged so that VFSes can
+** interoperate. The standard implemention used on both unix and windows
+** is for the index number to indicate a byte offset into the
+** WalCkptInfo.aLock[] array in the wal-index header. In other words, all
+** locks are on the shm file. The WALINDEX_LOCK_OFFSET constant (which
+** should be 120) is the location in the shm file for the first locking
+** byte.
+*/
+#define WAL_WRITE_LOCK 0
+#define WAL_ALL_BUT_WRITE 1
+#define WAL_CKPT_LOCK 1
+#define WAL_RECOVER_LOCK 2
+#define WAL_READ_LOCK(I) (3+(I))
+#define WAL_NREADER (SQLITE_SHM_NLOCK-3)
+
+
+/* Object declarations */
+typedef struct WalIndexHdr WalIndexHdr;
+typedef struct WalIterator WalIterator;
+typedef struct WalCkptInfo WalCkptInfo;
+
+
+/*
+** The following object holds a copy of the wal-index header content.
+**
+** The actual header in the wal-index consists of two copies of this
+** object followed by one instance of the WalCkptInfo object.
+** For all versions of SQLite through 3.10.0 and probably beyond,
+** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
+** the total header size is 136 bytes.
+**
+** The szPage value can be any power of 2 between 512 and 32768, inclusive.
+** Or it can be 1 to represent a 65536-byte page. The latter case was
+** added in 3.7.1 when support for 64K pages was added.
+*/
+struct WalIndexHdr {
+ u32 iVersion; /* Wal-index version */
+ u32 unused; /* Unused (padding) field */
+ u32 iChange; /* Counter incremented each transaction */
+ u8 isInit; /* 1 when initialized */
+ u8 bigEndCksum; /* True if checksums in WAL are big-endian */
+ u16 szPage; /* Database page size in bytes. 1==64K */
+ u32 mxFrame; /* Index of last valid frame in the WAL */
+ u32 nPage; /* Size of database in pages */
+ u32 aFrameCksum[2]; /* Checksum of last frame in log */
+ u32 aSalt[2]; /* Two salt values copied from WAL header */
+ u32 aCksum[2]; /* Checksum over all prior fields */
+};
+
+/*
+** A copy of the following object occurs in the wal-index immediately
+** following the second copy of the WalIndexHdr. This object stores
+** information used by checkpoint.
+**
+** nBackfill is the number of frames in the WAL that have been written
+** back into the database. (We call the act of moving content from WAL to
+** database "backfilling".) The nBackfill number is never greater than
+** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
+** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
+** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
+** mxFrame back to zero when the WAL is reset.
+**
+** nBackfillAttempted is the largest value of nBackfill that a checkpoint
+** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
+** the nBackfillAttempted is set before any backfilling is done and the
+** nBackfill is only set after all backfilling completes. So if a checkpoint
+** crashes, nBackfillAttempted might be larger than nBackfill. The
+** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
+**
+** The aLock[] field is a set of bytes used for locking. These bytes should
+** never be read or written.
+**
+** There is one entry in aReadMark[] for each reader lock. If a reader
+** holds read-lock K, then the value in aReadMark[K] is no greater than
+** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
+** for any aReadMark[] means that entry is unused. aReadMark[0] is
+** a special case; its value is never used and it exists as a place-holder
+** to avoid having to offset aReadMark[] indexs by one. Readers holding
+** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
+** directly from the database.
+**
+** The value of aReadMark[K] may only be changed by a thread that
+** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
+** aReadMark[K] cannot changed while there is a reader is using that mark
+** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
+**
+** The checkpointer may only transfer frames from WAL to database where
+** the frame numbers are less than or equal to every aReadMark[] that is
+** in use (that is, every aReadMark[j] for which there is a corresponding
+** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
+** largest value and will increase an unused aReadMark[] to mxFrame if there
+** is not already an aReadMark[] equal to mxFrame. The exception to the
+** previous sentence is when nBackfill equals mxFrame (meaning that everything
+** in the WAL has been backfilled into the database) then new readers
+** will choose aReadMark[0] which has value 0 and hence such reader will
+** get all their all content directly from the database file and ignore
+** the WAL.
+**
+** Writers normally append new frames to the end of the WAL. However,
+** if nBackfill equals mxFrame (meaning that all WAL content has been
+** written back into the database) and if no readers are using the WAL
+** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
+** the writer will first "reset" the WAL back to the beginning and start
+** writing new content beginning at frame 1.
+**
+** We assume that 32-bit loads are atomic and so no locks are needed in
+** order to read from any aReadMark[] entries.
+*/
+struct WalCkptInfo {
+ u32 nBackfill; /* Number of WAL frames backfilled into DB */
+ u32 aReadMark[WAL_NREADER]; /* Reader marks */
+ u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
+ u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
+ u32 notUsed0; /* Available for future enhancements */
+};
+#define READMARK_NOT_USED 0xffffffff
+
+
+/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
+** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
+** only support mandatory file-locks, we do not read or write data
+** from the region of the file on which locks are applied.
+*/
+#define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
+#define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
+
+/* Size of header before each frame in wal */
+#define WAL_FRAME_HDRSIZE 24
+
+/* Size of write ahead log header, including checksum. */
+#define WAL_HDRSIZE 32
+
+/* WAL magic value. Either this value, or the same value with the least
+** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
+** big-endian format in the first 4 bytes of a WAL file.
+**
+** If the LSB is set, then the checksums for each frame within the WAL
+** file are calculated by treating all data as an array of 32-bit
+** big-endian words. Otherwise, they are calculated by interpreting
+** all data as 32-bit little-endian words.
+*/
+#define WAL_MAGIC 0x377f0682
+
+/*
+** Return the offset of frame iFrame in the write-ahead log file,
+** assuming a database page size of szPage bytes. The offset returned
+** is to the start of the write-ahead log frame-header.
+*/
+#define walFrameOffset(iFrame, szPage) ( \
+ WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
+)
+
+/*
+** An open write-ahead log file is represented by an instance of the
+** following object.
+*/
+struct Wal {
+ sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
+ sqlite3_file *pDbFd; /* File handle for the database file */
+ sqlite3_file *pWalFd; /* File handle for WAL file */
+ u32 iCallback; /* Value to pass to log callback (or 0) */
+ i64 mxWalSize; /* Truncate WAL to this size upon reset */
+ int nWiData; /* Size of array apWiData */
+ int szFirstBlock; /* Size of first block written to WAL file */
+ volatile u32 **apWiData; /* Pointer to wal-index content in memory */
+ u32 szPage; /* Database page size */
+ i16 readLock; /* Which read lock is being held. -1 for none */
+ u8 syncFlags; /* Flags to use to sync header writes */
+ u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
+ u8 writeLock; /* True if in a write transaction */
+ u8 ckptLock; /* True if holding a checkpoint lock */
+ u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
+ u8 truncateOnCommit; /* True to truncate WAL file on commit */
+ u8 syncHeader; /* Fsync the WAL header if true */
+ u8 padToSectorBoundary; /* Pad transactions out to the next sector */
+ u8 bShmUnreliable; /* SHM content is read-only and unreliable */
+ WalIndexHdr hdr; /* Wal-index header for current transaction */
+ u32 minFrame; /* Ignore wal frames before this one */
+ u32 iReCksum; /* On commit, recalculate checksums from here */
+ const char *zWalName; /* Name of WAL file */
+ u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
+#ifdef SQLITE_DEBUG
+ u8 lockError; /* True if a locking error has occurred */
+#endif
+#ifdef SQLITE_ENABLE_SNAPSHOT
+ WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
+#endif
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+ sqlite3 *db;
+#endif
+};
+
+/*
+** Candidate values for Wal.exclusiveMode.
+*/
+#define WAL_NORMAL_MODE 0
+#define WAL_EXCLUSIVE_MODE 1
+#define WAL_HEAPMEMORY_MODE 2
+
+/*
+** Possible values for WAL.readOnly
+*/
+#define WAL_RDWR 0 /* Normal read/write connection */
+#define WAL_RDONLY 1 /* The WAL file is readonly */
+#define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
+
+/*
+** Each page of the wal-index mapping contains a hash-table made up of
+** an array of HASHTABLE_NSLOT elements of the following type.
+*/
+typedef u16 ht_slot;
+
+/*
+** This structure is used to implement an iterator that loops through
+** all frames in the WAL in database page order. Where two or more frames
+** correspond to the same database page, the iterator visits only the
+** frame most recently written to the WAL (in other words, the frame with
+** the largest index).
+**
+** The internals of this structure are only accessed by:
+**
+** walIteratorInit() - Create a new iterator,
+** walIteratorNext() - Step an iterator,
+** walIteratorFree() - Free an iterator.
+**
+** This functionality is used by the checkpoint code (see walCheckpoint()).
+*/
+struct WalIterator {
+ u32 iPrior; /* Last result returned from the iterator */
+ int nSegment; /* Number of entries in aSegment[] */
+ struct WalSegment {
+ int iNext; /* Next slot in aIndex[] not yet returned */
+ ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
+ u32 *aPgno; /* Array of page numbers. */
+ int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
+ int iZero; /* Frame number associated with aPgno[0] */
+ } aSegment[1]; /* One for every 32KB page in the wal-index */
+};
+
+/*
+** Define the parameters of the hash tables in the wal-index file. There
+** is a hash-table following every HASHTABLE_NPAGE page numbers in the
+** wal-index.
+**
+** Changing any of these constants will alter the wal-index format and
+** create incompatibilities.
+*/
+#define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
+#define HASHTABLE_HASH_1 383 /* Should be prime */
+#define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
+
+/*
+** The block of page numbers associated with the first hash-table in a
+** wal-index is smaller than usual. This is so that there is a complete
+** hash-table on each aligned 32KB page of the wal-index.
+*/
+#define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
+
+/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
+#define WALINDEX_PGSZ ( \
+ sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
+)
+
+/*
+** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
+** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
+** numbered from zero.
+**
+** If the wal-index is currently smaller the iPage pages then the size
+** of the wal-index might be increased, but only if it is safe to do
+** so. It is safe to enlarge the wal-index if pWal->writeLock is true
+** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
+**
+** If this call is successful, *ppPage is set to point to the wal-index
+** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
+** then an SQLite error code is returned and *ppPage is set to 0.
+*/
+static SQLITE_NOINLINE int walIndexPageRealloc(
+ Wal *pWal, /* The WAL context */
+ int iPage, /* The page we seek */
+ volatile u32 **ppPage /* Write the page pointer here */
+){
+ int rc = SQLITE_OK;
+
+ /* Enlarge the pWal->apWiData[] array if required */
+ if( pWal->nWiData<=iPage ){
+ sqlite3_int64 nByte = sizeof(u32*)*(iPage+1);
+ volatile u32 **apNew;
+ apNew = (volatile u32 **)sqlite3Realloc((void *)pWal->apWiData, nByte);
+ if( !apNew ){
+ *ppPage = 0;
+ return SQLITE_NOMEM_BKPT;
+ }
+ memset((void*)&apNew[pWal->nWiData], 0,
+ sizeof(u32*)*(iPage+1-pWal->nWiData));
+ pWal->apWiData = apNew;
+ pWal->nWiData = iPage+1;
+ }
+
+ /* Request a pointer to the required page from the VFS */
+ assert( pWal->apWiData[iPage]==0 );
+ if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
+ pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
+ if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
+ }else{
+ rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
+ pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
+ );
+ assert( pWal->apWiData[iPage]!=0 || rc!=SQLITE_OK || pWal->writeLock==0 );
+ testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
+ if( rc==SQLITE_OK ){
+ if( iPage>0 && sqlite3FaultSim(600) ) rc = SQLITE_NOMEM;
+ }else if( (rc&0xff)==SQLITE_READONLY ){
+ pWal->readOnly |= WAL_SHM_RDONLY;
+ if( rc==SQLITE_READONLY ){
+ rc = SQLITE_OK;
+ }
+ }
+ }
+
+ *ppPage = pWal->apWiData[iPage];
+ assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
+ return rc;
+}
+static int walIndexPage(
+ Wal *pWal, /* The WAL context */
+ int iPage, /* The page we seek */
+ volatile u32 **ppPage /* Write the page pointer here */
+){
+ if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
+ return walIndexPageRealloc(pWal, iPage, ppPage);
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Return a pointer to the WalCkptInfo structure in the wal-index.
+*/
+static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
+ assert( pWal->nWiData>0 && pWal->apWiData[0] );
+ return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
+}
+
+/*
+** Return a pointer to the WalIndexHdr structure in the wal-index.
+*/
+static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
+ assert( pWal->nWiData>0 && pWal->apWiData[0] );
+ return (volatile WalIndexHdr*)pWal->apWiData[0];
+}
+
+/*
+** The argument to this macro must be of type u32. On a little-endian
+** architecture, it returns the u32 value that results from interpreting
+** the 4 bytes as a big-endian value. On a big-endian architecture, it
+** returns the value that would be produced by interpreting the 4 bytes
+** of the input value as a little-endian integer.
+*/
+#define BYTESWAP32(x) ( \
+ (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
+ + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
+)
+
+/*
+** Generate or extend an 8 byte checksum based on the data in
+** array aByte[] and the initial values of aIn[0] and aIn[1] (or
+** initial values of 0 and 0 if aIn==NULL).
+**
+** The checksum is written back into aOut[] before returning.
+**
+** nByte must be a positive multiple of 8.
+*/
+static void walChecksumBytes(
+ int nativeCksum, /* True for native byte-order, false for non-native */
+ u8 *a, /* Content to be checksummed */
+ int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
+ const u32 *aIn, /* Initial checksum value input */
+ u32 *aOut /* OUT: Final checksum value output */
+){
+ u32 s1, s2;
+ u32 *aData = (u32 *)a;
+ u32 *aEnd = (u32 *)&a[nByte];
+
+ if( aIn ){
+ s1 = aIn[0];
+ s2 = aIn[1];
+ }else{
+ s1 = s2 = 0;
+ }
+
+ assert( nByte>=8 );
+ assert( (nByte&0x00000007)==0 );
+ assert( nByte<=65536 );
+
+ if( nativeCksum ){
+ do {
+ s1 += *aData++ + s2;
+ s2 += *aData++ + s1;
+ }while( aData<aEnd );
+ }else{
+ do {
+ s1 += BYTESWAP32(aData[0]) + s2;
+ s2 += BYTESWAP32(aData[1]) + s1;
+ aData += 2;
+ }while( aData<aEnd );
+ }
+
+ aOut[0] = s1;
+ aOut[1] = s2;
+}
+
+/*
+** If there is the possibility of concurrent access to the SHM file
+** from multiple threads and/or processes, then do a memory barrier.
+*/
+static void walShmBarrier(Wal *pWal){
+ if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
+ sqlite3OsShmBarrier(pWal->pDbFd);
+ }
+}
+
+/*
+** Add the SQLITE_NO_TSAN as part of the return-type of a function
+** definition as a hint that the function contains constructs that
+** might give false-positive TSAN warnings.
+**
+** See tag-20200519-1.
+*/
+#if defined(__clang__) && !defined(SQLITE_NO_TSAN)
+# define SQLITE_NO_TSAN __attribute__((no_sanitize_thread))
+#else
+# define SQLITE_NO_TSAN
+#endif
+
+/*
+** Write the header information in pWal->hdr into the wal-index.
+**
+** The checksum on pWal->hdr is updated before it is written.
+*/
+static SQLITE_NO_TSAN void walIndexWriteHdr(Wal *pWal){
+ volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
+ const int nCksum = offsetof(WalIndexHdr, aCksum);
+
+ assert( pWal->writeLock );
+ pWal->hdr.isInit = 1;
+ pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
+ walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
+ /* Possible TSAN false-positive. See tag-20200519-1 */
+ memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
+ walShmBarrier(pWal);
+ memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
+}
+
+/*
+** This function encodes a single frame header and writes it to a buffer
+** supplied by the caller. A frame-header is made up of a series of
+** 4-byte big-endian integers, as follows:
+**
+** 0: Page number.
+** 4: For commit records, the size of the database image in pages
+** after the commit. For all other records, zero.
+** 8: Salt-1 (copied from the wal-header)
+** 12: Salt-2 (copied from the wal-header)
+** 16: Checksum-1.
+** 20: Checksum-2.
+*/
+static void walEncodeFrame(
+ Wal *pWal, /* The write-ahead log */
+ u32 iPage, /* Database page number for frame */
+ u32 nTruncate, /* New db size (or 0 for non-commit frames) */
+ u8 *aData, /* Pointer to page data */
+ u8 *aFrame /* OUT: Write encoded frame here */
+){
+ int nativeCksum; /* True for native byte-order checksums */
+ u32 *aCksum = pWal->hdr.aFrameCksum;
+ assert( WAL_FRAME_HDRSIZE==24 );
+ sqlite3Put4byte(&aFrame[0], iPage);
+ sqlite3Put4byte(&aFrame[4], nTruncate);
+ if( pWal->iReCksum==0 ){
+ memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
+
+ nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
+ walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
+ walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
+
+ sqlite3Put4byte(&aFrame[16], aCksum[0]);
+ sqlite3Put4byte(&aFrame[20], aCksum[1]);
+ }else{
+ memset(&aFrame[8], 0, 16);
+ }
+}
+
+/*
+** Check to see if the frame with header in aFrame[] and content
+** in aData[] is valid. If it is a valid frame, fill *piPage and
+** *pnTruncate and return true. Return if the frame is not valid.
+*/
+static int walDecodeFrame(
+ Wal *pWal, /* The write-ahead log */
+ u32 *piPage, /* OUT: Database page number for frame */
+ u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
+ u8 *aData, /* Pointer to page data (for checksum) */
+ u8 *aFrame /* Frame data */
+){
+ int nativeCksum; /* True for native byte-order checksums */
+ u32 *aCksum = pWal->hdr.aFrameCksum;
+ u32 pgno; /* Page number of the frame */
+ assert( WAL_FRAME_HDRSIZE==24 );
+
+ /* A frame is only valid if the salt values in the frame-header
+ ** match the salt values in the wal-header.
+ */
+ if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
+ return 0;
+ }
+
+ /* A frame is only valid if the page number is creater than zero.
+ */
+ pgno = sqlite3Get4byte(&aFrame[0]);
+ if( pgno==0 ){
+ return 0;
+ }
+
+ /* A frame is only valid if a checksum of the WAL header,
+ ** all prior frams, the first 16 bytes of this frame-header,
+ ** and the frame-data matches the checksum in the last 8
+ ** bytes of this frame-header.
+ */
+ nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
+ walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
+ walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
+ if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
+ || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
+ ){
+ /* Checksum failed. */
+ return 0;
+ }
+
+ /* If we reach this point, the frame is valid. Return the page number
+ ** and the new database size.
+ */
+ *piPage = pgno;
+ *pnTruncate = sqlite3Get4byte(&aFrame[4]);
+ return 1;
+}
+
+
+#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
+/*
+** Names of locks. This routine is used to provide debugging output and is not
+** a part of an ordinary build.
+*/
+static const char *walLockName(int lockIdx){
+ if( lockIdx==WAL_WRITE_LOCK ){
+ return "WRITE-LOCK";
+ }else if( lockIdx==WAL_CKPT_LOCK ){
+ return "CKPT-LOCK";
+ }else if( lockIdx==WAL_RECOVER_LOCK ){
+ return "RECOVER-LOCK";
+ }else{
+ static char zName[15];
+ sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
+ lockIdx-WAL_READ_LOCK(0));
+ return zName;
+ }
+}
+#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
+
+
+/*
+** Set or release locks on the WAL. Locks are either shared or exclusive.
+** A lock cannot be moved directly between shared and exclusive - it must go
+** through the unlocked state first.
+**
+** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
+*/
+static int walLockShared(Wal *pWal, int lockIdx){
+ int rc;
+ if( pWal->exclusiveMode ) return SQLITE_OK;
+ rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
+ SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
+ WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
+ walLockName(lockIdx), rc ? "failed" : "ok"));
+ VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
+ return rc;
+}
+static void walUnlockShared(Wal *pWal, int lockIdx){
+ if( pWal->exclusiveMode ) return;
+ (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
+ SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
+ WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
+}
+static int walLockExclusive(Wal *pWal, int lockIdx, int n){
+ int rc;
+ if( pWal->exclusiveMode ) return SQLITE_OK;
+ rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
+ SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
+ WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
+ walLockName(lockIdx), n, rc ? "failed" : "ok"));
+ VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
+ return rc;
+}
+static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
+ if( pWal->exclusiveMode ) return;
+ (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
+ SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
+ WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
+ walLockName(lockIdx), n));
+}
+
+/*
+** Compute a hash on a page number. The resulting hash value must land
+** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
+** the hash to the next value in the event of a collision.
+*/
+static int walHash(u32 iPage){
+ assert( iPage>0 );
+ assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
+ return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
+}
+static int walNextHash(int iPriorHash){
+ return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
+}
+
+/*
+** An instance of the WalHashLoc object is used to describe the location
+** of a page hash table in the wal-index. This becomes the return value
+** from walHashGet().
+*/
+typedef struct WalHashLoc WalHashLoc;
+struct WalHashLoc {
+ volatile ht_slot *aHash; /* Start of the wal-index hash table */
+ volatile u32 *aPgno; /* aPgno[1] is the page of first frame indexed */
+ u32 iZero; /* One less than the frame number of first indexed*/
+};
+
+/*
+** Return pointers to the hash table and page number array stored on
+** page iHash of the wal-index. The wal-index is broken into 32KB pages
+** numbered starting from 0.
+**
+** Set output variable pLoc->aHash to point to the start of the hash table
+** in the wal-index file. Set pLoc->iZero to one less than the frame
+** number of the first frame indexed by this hash table. If a
+** slot in the hash table is set to N, it refers to frame number
+** (pLoc->iZero+N) in the log.
+**
+** Finally, set pLoc->aPgno so that pLoc->aPgno[1] is the page number of the
+** first frame indexed by the hash table, frame (pLoc->iZero+1).
+*/
+static int walHashGet(
+ Wal *pWal, /* WAL handle */
+ int iHash, /* Find the iHash'th table */
+ WalHashLoc *pLoc /* OUT: Hash table location */
+){
+ int rc; /* Return code */
+
+ rc = walIndexPage(pWal, iHash, &pLoc->aPgno);
+ assert( rc==SQLITE_OK || iHash>0 );
+
+ if( rc==SQLITE_OK ){
+ pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];
+ if( iHash==0 ){
+ pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
+ pLoc->iZero = 0;
+ }else{
+ pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
+ }
+ pLoc->aPgno = &pLoc->aPgno[-1];
+ }
+ return rc;
+}
+
+/*
+** Return the number of the wal-index page that contains the hash-table
+** and page-number array that contain entries corresponding to WAL frame
+** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
+** are numbered starting from 0.
+*/
+static int walFramePage(u32 iFrame){
+ int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
+ assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
+ && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
+ && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
+ && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
+ && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
+ );
+ assert( iHash>=0 );
+ return iHash;
+}
+
+/*
+** Return the page number associated with frame iFrame in this WAL.
+*/
+static u32 walFramePgno(Wal *pWal, u32 iFrame){
+ int iHash = walFramePage(iFrame);
+ if( iHash==0 ){
+ return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
+ }
+ return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
+}
+
+/*
+** Remove entries from the hash table that point to WAL slots greater
+** than pWal->hdr.mxFrame.
+**
+** This function is called whenever pWal->hdr.mxFrame is decreased due
+** to a rollback or savepoint.
+**
+** At most only the hash table containing pWal->hdr.mxFrame needs to be
+** updated. Any later hash tables will be automatically cleared when
+** pWal->hdr.mxFrame advances to the point where those hash tables are
+** actually needed.
+*/
+static void walCleanupHash(Wal *pWal){
+ WalHashLoc sLoc; /* Hash table location */
+ int iLimit = 0; /* Zero values greater than this */
+ int nByte; /* Number of bytes to zero in aPgno[] */
+ int i; /* Used to iterate through aHash[] */
+ int rc; /* Return code form walHashGet() */
+
+ assert( pWal->writeLock );
+ testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
+ testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
+ testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
+
+ if( pWal->hdr.mxFrame==0 ) return;
+
+ /* Obtain pointers to the hash-table and page-number array containing
+ ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
+ ** that the page said hash-table and array reside on is already mapped.(1)
+ */
+ assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
+ assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
+ rc = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
+ if( NEVER(rc) ) return; /* Defense-in-depth, in case (1) above is wrong */
+
+ /* Zero all hash-table entries that correspond to frame numbers greater
+ ** than pWal->hdr.mxFrame.
+ */
+ iLimit = pWal->hdr.mxFrame - sLoc.iZero;
+ assert( iLimit>0 );
+ for(i=0; i<HASHTABLE_NSLOT; i++){
+ if( sLoc.aHash[i]>iLimit ){
+ sLoc.aHash[i] = 0;
+ }
+ }
+
+ /* Zero the entries in the aPgno array that correspond to frames with
+ ** frame numbers greater than pWal->hdr.mxFrame.
+ */
+ nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit+1]);
+ memset((void *)&sLoc.aPgno[iLimit+1], 0, nByte);
+
+#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
+ /* Verify that the every entry in the mapping region is still reachable
+ ** via the hash table even after the cleanup.
+ */
+ if( iLimit ){
+ int j; /* Loop counter */
+ int iKey; /* Hash key */
+ for(j=1; j<=iLimit; j++){
+ for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){
+ if( sLoc.aHash[iKey]==j ) break;
+ }
+ assert( sLoc.aHash[iKey]==j );
+ }
+ }
+#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
+}
+
+
+/*
+** Set an entry in the wal-index that will map database page number
+** pPage into WAL frame iFrame.
+*/
+static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
+ int rc; /* Return code */
+ WalHashLoc sLoc; /* Wal-index hash table location */
+
+ rc = walHashGet(pWal, walFramePage(iFrame), &sLoc);
+
+ /* Assuming the wal-index file was successfully mapped, populate the
+ ** page number array and hash table entry.
+ */
+ if( rc==SQLITE_OK ){
+ int iKey; /* Hash table key */
+ int idx; /* Value to write to hash-table slot */
+ int nCollide; /* Number of hash collisions */
+
+ idx = iFrame - sLoc.iZero;
+ assert( idx <= HASHTABLE_NSLOT/2 + 1 );
+
+ /* If this is the first entry to be added to this hash-table, zero the
+ ** entire hash table and aPgno[] array before proceeding.
+ */
+ if( idx==1 ){
+ int nByte = (int)((u8 *)&sLoc.aHash[HASHTABLE_NSLOT]
+ - (u8 *)&sLoc.aPgno[1]);
+ memset((void*)&sLoc.aPgno[1], 0, nByte);
+ }
+
+ /* If the entry in aPgno[] is already set, then the previous writer
+ ** must have exited unexpectedly in the middle of a transaction (after
+ ** writing one or more dirty pages to the WAL to free up memory).
+ ** Remove the remnants of that writers uncommitted transaction from
+ ** the hash-table before writing any new entries.
+ */
+ if( sLoc.aPgno[idx] ){
+ walCleanupHash(pWal);
+ assert( !sLoc.aPgno[idx] );
+ }
+
+ /* Write the aPgno[] array entry and the hash-table slot. */
+ nCollide = idx;
+ for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
+ if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
+ }
+ sLoc.aPgno[idx] = iPage;
+ AtomicStore(&sLoc.aHash[iKey], (ht_slot)idx);
+
+#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
+ /* Verify that the number of entries in the hash table exactly equals
+ ** the number of entries in the mapping region.
+ */
+ {
+ int i; /* Loop counter */
+ int nEntry = 0; /* Number of entries in the hash table */
+ for(i=0; i<HASHTABLE_NSLOT; i++){ if( sLoc.aHash[i] ) nEntry++; }
+ assert( nEntry==idx );
+ }
+
+ /* Verify that the every entry in the mapping region is reachable
+ ** via the hash table. This turns out to be a really, really expensive
+ ** thing to check, so only do this occasionally - not on every
+ ** iteration.
+ */
+ if( (idx&0x3ff)==0 ){
+ int i; /* Loop counter */
+ for(i=1; i<=idx; i++){
+ for(iKey=walHash(sLoc.aPgno[i]);
+ sLoc.aHash[iKey];
+ iKey=walNextHash(iKey)){
+ if( sLoc.aHash[iKey]==i ) break;
+ }
+ assert( sLoc.aHash[iKey]==i );
+ }
+ }
+#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
+ }
+
+
+ return rc;
+}
+
+
+/*
+** Recover the wal-index by reading the write-ahead log file.
+**
+** This routine first tries to establish an exclusive lock on the
+** wal-index to prevent other threads/processes from doing anything
+** with the WAL or wal-index while recovery is running. The
+** WAL_RECOVER_LOCK is also held so that other threads will know
+** that this thread is running recovery. If unable to establish
+** the necessary locks, this routine returns SQLITE_BUSY.
+*/
+static int walIndexRecover(Wal *pWal){
+ int rc; /* Return Code */
+ i64 nSize; /* Size of log file */
+ u32 aFrameCksum[2] = {0, 0};
+ int iLock; /* Lock offset to lock for checkpoint */
+
+ /* Obtain an exclusive lock on all byte in the locking range not already
+ ** locked by the caller. The caller is guaranteed to have locked the
+ ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
+ ** If successful, the same bytes that are locked here are unlocked before
+ ** this function returns.
+ */
+ assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
+ assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
+ assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
+ assert( pWal->writeLock );
+ iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
+ rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
+ if( rc ){
+ return rc;
+ }
+
+ WALTRACE(("WAL%p: recovery begin...\n", pWal));
+
+ memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
+
+ rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
+ if( rc!=SQLITE_OK ){
+ goto recovery_error;
+ }
+
+ if( nSize>WAL_HDRSIZE ){
+ u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
+ u32 *aPrivate = 0; /* Heap copy of *-shm hash being populated */
+ u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
+ int szFrame; /* Number of bytes in buffer aFrame[] */
+ u8 *aData; /* Pointer to data part of aFrame buffer */
+ int szPage; /* Page size according to the log */
+ u32 magic; /* Magic value read from WAL header */
+ u32 version; /* Magic value read from WAL header */
+ int isValid; /* True if this frame is valid */
+ u32 iPg; /* Current 32KB wal-index page */
+ u32 iLastFrame; /* Last frame in wal, based on nSize alone */
+
+ /* Read in the WAL header. */
+ rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
+ if( rc!=SQLITE_OK ){
+ goto recovery_error;
+ }
+
+ /* If the database page size is not a power of two, or is greater than
+ ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
+ ** data. Similarly, if the 'magic' value is invalid, ignore the whole
+ ** WAL file.
+ */
+ magic = sqlite3Get4byte(&aBuf[0]);
+ szPage = sqlite3Get4byte(&aBuf[8]);
+ if( (magic&0xFFFFFFFE)!=WAL_MAGIC
+ || szPage&(szPage-1)
+ || szPage>SQLITE_MAX_PAGE_SIZE
+ || szPage<512
+ ){
+ goto finished;
+ }
+ pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
+ pWal->szPage = szPage;
+ pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
+ memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
+
+ /* Verify that the WAL header checksum is correct */
+ walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
+ aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
+ );
+ if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
+ || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
+ ){
+ goto finished;
+ }
+
+ /* Verify that the version number on the WAL format is one that
+ ** are able to understand */
+ version = sqlite3Get4byte(&aBuf[4]);
+ if( version!=WAL_MAX_VERSION ){
+ rc = SQLITE_CANTOPEN_BKPT;
+ goto finished;
+ }
+
+ /* Malloc a buffer to read frames into. */
+ szFrame = szPage + WAL_FRAME_HDRSIZE;
+ aFrame = (u8 *)sqlite3_malloc64(szFrame + WALINDEX_PGSZ);
+ if( !aFrame ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto recovery_error;
+ }
+ aData = &aFrame[WAL_FRAME_HDRSIZE];
+ aPrivate = (u32*)&aData[szPage];
+
+ /* Read all frames from the log file. */
+ iLastFrame = (nSize - WAL_HDRSIZE) / szFrame;
+ for(iPg=0; iPg<=(u32)walFramePage(iLastFrame); iPg++){
+ u32 *aShare;
+ u32 iFrame; /* Index of last frame read */
+ u32 iLast = MIN(iLastFrame, HASHTABLE_NPAGE_ONE+iPg*HASHTABLE_NPAGE);
+ u32 iFirst = 1 + (iPg==0?0:HASHTABLE_NPAGE_ONE+(iPg-1)*HASHTABLE_NPAGE);
+ u32 nHdr, nHdr32;
+ rc = walIndexPage(pWal, iPg, (volatile u32**)&aShare);
+ if( rc ) break;
+ pWal->apWiData[iPg] = aPrivate;
+
+ for(iFrame=iFirst; iFrame<=iLast; iFrame++){
+ i64 iOffset = walFrameOffset(iFrame, szPage);
+ u32 pgno; /* Database page number for frame */
+ u32 nTruncate; /* dbsize field from frame header */
+
+ /* Read and decode the next log frame. */
+ rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
+ if( rc!=SQLITE_OK ) break;
+ isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
+ if( !isValid ) break;
+ rc = walIndexAppend(pWal, iFrame, pgno);
+ if( NEVER(rc!=SQLITE_OK) ) break;
+
+ /* If nTruncate is non-zero, this is a commit record. */
+ if( nTruncate ){
+ pWal->hdr.mxFrame = iFrame;
+ pWal->hdr.nPage = nTruncate;
+ pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
+ testcase( szPage<=32768 );
+ testcase( szPage>=65536 );
+ aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
+ aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
+ }
+ }
+ pWal->apWiData[iPg] = aShare;
+ nHdr = (iPg==0 ? WALINDEX_HDR_SIZE : 0);
+ nHdr32 = nHdr / sizeof(u32);
+#ifndef SQLITE_SAFER_WALINDEX_RECOVERY
+ /* Memcpy() should work fine here, on all reasonable implementations.
+ ** Technically, memcpy() might change the destination to some
+ ** intermediate value before setting to the final value, and that might
+ ** cause a concurrent reader to malfunction. Memcpy() is allowed to
+ ** do that, according to the spec, but no memcpy() implementation that
+ ** we know of actually does that, which is why we say that memcpy()
+ ** is safe for this. Memcpy() is certainly a lot faster.
+ */
+ memcpy(&aShare[nHdr32], &aPrivate[nHdr32], WALINDEX_PGSZ-nHdr);
+#else
+ /* In the event that some platform is found for which memcpy()
+ ** changes the destination to some intermediate value before
+ ** setting the final value, this alternative copy routine is
+ ** provided.
+ */
+ {
+ int i;
+ for(i=nHdr32; i<WALINDEX_PGSZ/sizeof(u32); i++){
+ if( aShare[i]!=aPrivate[i] ){
+ /* Atomic memory operations are not required here because if
+ ** the value needs to be changed, that means it is not being
+ ** accessed concurrently. */
+ aShare[i] = aPrivate[i];
+ }
+ }
+ }
+#endif
+ if( iFrame<=iLast ) break;
+ }
+
+ sqlite3_free(aFrame);
+ }
+
+finished:
+ if( rc==SQLITE_OK ){
+ volatile WalCkptInfo *pInfo;
+ int i;
+ pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
+ pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
+ walIndexWriteHdr(pWal);
+
+ /* Reset the checkpoint-header. This is safe because this thread is
+ ** currently holding locks that exclude all other writers and
+ ** checkpointers. Then set the values of read-mark slots 1 through N.
+ */
+ pInfo = walCkptInfo(pWal);
+ pInfo->nBackfill = 0;
+ pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
+ pInfo->aReadMark[0] = 0;
+ for(i=1; i<WAL_NREADER; i++){
+ rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
+ if( rc==SQLITE_OK ){
+ if( i==1 && pWal->hdr.mxFrame ){
+ pInfo->aReadMark[i] = pWal->hdr.mxFrame;
+ }else{
+ pInfo->aReadMark[i] = READMARK_NOT_USED;
+ }
+ walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
+ }else if( rc!=SQLITE_BUSY ){
+ goto recovery_error;
+ }
+ }
+
+ /* If more than one frame was recovered from the log file, report an
+ ** event via sqlite3_log(). This is to help with identifying performance
+ ** problems caused by applications routinely shutting down without
+ ** checkpointing the log file.
+ */
+ if( pWal->hdr.nPage ){
+ sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
+ "recovered %d frames from WAL file %s",
+ pWal->hdr.mxFrame, pWal->zWalName
+ );
+ }
+ }
+
+recovery_error:
+ WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
+ walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
+ return rc;
+}
+
+/*
+** Close an open wal-index.
+*/
+static void walIndexClose(Wal *pWal, int isDelete){
+ if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
+ int i;
+ for(i=0; i<pWal->nWiData; i++){
+ sqlite3_free((void *)pWal->apWiData[i]);
+ pWal->apWiData[i] = 0;
+ }
+ }
+ if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
+ sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
+ }
+}
+
+/*
+** Open a connection to the WAL file zWalName. The database file must
+** already be opened on connection pDbFd. The buffer that zWalName points
+** to must remain valid for the lifetime of the returned Wal* handle.
+**
+** A SHARED lock should be held on the database file when this function
+** is called. The purpose of this SHARED lock is to prevent any other
+** client from unlinking the WAL or wal-index file. If another process
+** were to do this just after this client opened one of these files, the
+** system would be badly broken.
+**
+** If the log file is successfully opened, SQLITE_OK is returned and
+** *ppWal is set to point to a new WAL handle. If an error occurs,
+** an SQLite error code is returned and *ppWal is left unmodified.
+*/
+SQLITE_PRIVATE int sqlite3WalOpen(
+ sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
+ sqlite3_file *pDbFd, /* The open database file */
+ const char *zWalName, /* Name of the WAL file */
+ int bNoShm, /* True to run in heap-memory mode */
+ i64 mxWalSize, /* Truncate WAL to this size on reset */
+ Wal **ppWal /* OUT: Allocated Wal handle */
+){
+ int rc; /* Return Code */
+ Wal *pRet; /* Object to allocate and return */
+ int flags; /* Flags passed to OsOpen() */
+
+ assert( zWalName && zWalName[0] );
+ assert( pDbFd );
+
+ /* In the amalgamation, the os_unix.c and os_win.c source files come before
+ ** this source file. Verify that the #defines of the locking byte offsets
+ ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
+ ** For that matter, if the lock offset ever changes from its initial design
+ ** value of 120, we need to know that so there is an assert() to check it.
+ */
+ assert( 120==WALINDEX_LOCK_OFFSET );
+ assert( 136==WALINDEX_HDR_SIZE );
+#ifdef WIN_SHM_BASE
+ assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
+#endif
+#ifdef UNIX_SHM_BASE
+ assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
+#endif
+
+
+ /* Allocate an instance of struct Wal to return. */
+ *ppWal = 0;
+ pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
+ if( !pRet ){
+ return SQLITE_NOMEM_BKPT;
+ }
+
+ pRet->pVfs = pVfs;
+ pRet->pWalFd = (sqlite3_file *)&pRet[1];
+ pRet->pDbFd = pDbFd;
+ pRet->readLock = -1;
+ pRet->mxWalSize = mxWalSize;
+ pRet->zWalName = zWalName;
+ pRet->syncHeader = 1;
+ pRet->padToSectorBoundary = 1;
+ pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
+
+ /* Open file handle on the write-ahead log file. */
+ flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
+ rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
+ if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
+ pRet->readOnly = WAL_RDONLY;
+ }
+
+ if( rc!=SQLITE_OK ){
+ walIndexClose(pRet, 0);
+ sqlite3OsClose(pRet->pWalFd);
+ sqlite3_free(pRet);
+ }else{
+ int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
+ if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
+ if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
+ pRet->padToSectorBoundary = 0;
+ }
+ *ppWal = pRet;
+ WALTRACE(("WAL%d: opened\n", pRet));
+ }
+ return rc;
+}
+
+/*
+** Change the size to which the WAL file is trucated on each reset.
+*/
+SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
+ if( pWal ) pWal->mxWalSize = iLimit;
+}
+
+/*
+** Find the smallest page number out of all pages held in the WAL that
+** has not been returned by any prior invocation of this method on the
+** same WalIterator object. Write into *piFrame the frame index where
+** that page was last written into the WAL. Write into *piPage the page
+** number.
+**
+** Return 0 on success. If there are no pages in the WAL with a page
+** number larger than *piPage, then return 1.
+*/
+static int walIteratorNext(
+ WalIterator *p, /* Iterator */
+ u32 *piPage, /* OUT: The page number of the next page */
+ u32 *piFrame /* OUT: Wal frame index of next page */
+){
+ u32 iMin; /* Result pgno must be greater than iMin */
+ u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
+ int i; /* For looping through segments */
+
+ iMin = p->iPrior;
+ assert( iMin<0xffffffff );
+ for(i=p->nSegment-1; i>=0; i--){
+ struct WalSegment *pSegment = &p->aSegment[i];
+ while( pSegment->iNext<pSegment->nEntry ){
+ u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
+ if( iPg>iMin ){
+ if( iPg<iRet ){
+ iRet = iPg;
+ *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
+ }
+ break;
+ }
+ pSegment->iNext++;
+ }
+ }
+
+ *piPage = p->iPrior = iRet;
+ return (iRet==0xFFFFFFFF);
+}
+
+/*
+** This function merges two sorted lists into a single sorted list.
+**
+** aLeft[] and aRight[] are arrays of indices. The sort key is
+** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
+** is guaranteed for all J<K:
+**
+** aContent[aLeft[J]] < aContent[aLeft[K]]
+** aContent[aRight[J]] < aContent[aRight[K]]
+**
+** This routine overwrites aRight[] with a new (probably longer) sequence
+** of indices such that the aRight[] contains every index that appears in
+** either aLeft[] or the old aRight[] and such that the second condition
+** above is still met.
+**
+** The aContent[aLeft[X]] values will be unique for all X. And the
+** aContent[aRight[X]] values will be unique too. But there might be
+** one or more combinations of X and Y such that
+**
+** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
+**
+** When that happens, omit the aLeft[X] and use the aRight[Y] index.
+*/
+static void walMerge(
+ const u32 *aContent, /* Pages in wal - keys for the sort */
+ ht_slot *aLeft, /* IN: Left hand input list */
+ int nLeft, /* IN: Elements in array *paLeft */
+ ht_slot **paRight, /* IN/OUT: Right hand input list */
+ int *pnRight, /* IN/OUT: Elements in *paRight */
+ ht_slot *aTmp /* Temporary buffer */
+){
+ int iLeft = 0; /* Current index in aLeft */
+ int iRight = 0; /* Current index in aRight */
+ int iOut = 0; /* Current index in output buffer */
+ int nRight = *pnRight;
+ ht_slot *aRight = *paRight;
+
+ assert( nLeft>0 && nRight>0 );
+ while( iRight<nRight || iLeft<nLeft ){
+ ht_slot logpage;
+ Pgno dbpage;
+
+ if( (iLeft<nLeft)
+ && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
+ ){
+ logpage = aLeft[iLeft++];
+ }else{
+ logpage = aRight[iRight++];
+ }
+ dbpage = aContent[logpage];
+
+ aTmp[iOut++] = logpage;
+ if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
+
+ assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
+ assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
+ }
+
+ *paRight = aLeft;
+ *pnRight = iOut;
+ memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
+}
+
+/*
+** Sort the elements in list aList using aContent[] as the sort key.
+** Remove elements with duplicate keys, preferring to keep the
+** larger aList[] values.
+**
+** The aList[] entries are indices into aContent[]. The values in
+** aList[] are to be sorted so that for all J<K:
+**
+** aContent[aList[J]] < aContent[aList[K]]
+**
+** For any X and Y such that
+**
+** aContent[aList[X]] == aContent[aList[Y]]
+**
+** Keep the larger of the two values aList[X] and aList[Y] and discard
+** the smaller.
+*/
+static void walMergesort(
+ const u32 *aContent, /* Pages in wal */
+ ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
+ ht_slot *aList, /* IN/OUT: List to sort */
+ int *pnList /* IN/OUT: Number of elements in aList[] */
+){
+ struct Sublist {
+ int nList; /* Number of elements in aList */
+ ht_slot *aList; /* Pointer to sub-list content */
+ };
+
+ const int nList = *pnList; /* Size of input list */
+ int nMerge = 0; /* Number of elements in list aMerge */
+ ht_slot *aMerge = 0; /* List to be merged */
+ int iList; /* Index into input list */
+ u32 iSub = 0; /* Index into aSub array */
+ struct Sublist aSub[13]; /* Array of sub-lists */
+
+ memset(aSub, 0, sizeof(aSub));
+ assert( nList<=HASHTABLE_NPAGE && nList>0 );
+ assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
+
+ for(iList=0; iList<nList; iList++){
+ nMerge = 1;
+ aMerge = &aList[iList];
+ for(iSub=0; iList & (1<<iSub); iSub++){
+ struct Sublist *p;
+ assert( iSub<ArraySize(aSub) );
+ p = &aSub[iSub];
+ assert( p->aList && p->nList<=(1<<iSub) );
+ assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
+ walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
+ }
+ aSub[iSub].aList = aMerge;
+ aSub[iSub].nList = nMerge;
+ }
+
+ for(iSub++; iSub<ArraySize(aSub); iSub++){
+ if( nList & (1<<iSub) ){
+ struct Sublist *p;
+ assert( iSub<ArraySize(aSub) );
+ p = &aSub[iSub];
+ assert( p->nList<=(1<<iSub) );
+ assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
+ walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
+ }
+ }
+ assert( aMerge==aList );
+ *pnList = nMerge;
+
+#ifdef SQLITE_DEBUG
+ {
+ int i;
+ for(i=1; i<*pnList; i++){
+ assert( aContent[aList[i]] > aContent[aList[i-1]] );
+ }
+ }
+#endif
+}
+
+/*
+** Free an iterator allocated by walIteratorInit().
+*/
+static void walIteratorFree(WalIterator *p){
+ sqlite3_free(p);
+}
+
+/*
+** Construct a WalInterator object that can be used to loop over all
+** pages in the WAL following frame nBackfill in ascending order. Frames
+** nBackfill or earlier may be included - excluding them is an optimization
+** only. The caller must hold the checkpoint lock.
+**
+** On success, make *pp point to the newly allocated WalInterator object
+** return SQLITE_OK. Otherwise, return an error code. If this routine
+** returns an error, the value of *pp is undefined.
+**
+** The calling routine should invoke walIteratorFree() to destroy the
+** WalIterator object when it has finished with it.
+*/
+static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
+ WalIterator *p; /* Return value */
+ int nSegment; /* Number of segments to merge */
+ u32 iLast; /* Last frame in log */
+ sqlite3_int64 nByte; /* Number of bytes to allocate */
+ int i; /* Iterator variable */
+ ht_slot *aTmp; /* Temp space used by merge-sort */
+ int rc = SQLITE_OK; /* Return Code */
+
+ /* This routine only runs while holding the checkpoint lock. And
+ ** it only runs if there is actually content in the log (mxFrame>0).
+ */
+ assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
+ iLast = pWal->hdr.mxFrame;
+
+ /* Allocate space for the WalIterator object. */
+ nSegment = walFramePage(iLast) + 1;
+ nByte = sizeof(WalIterator)
+ + (nSegment-1)*sizeof(struct WalSegment)
+ + iLast*sizeof(ht_slot);
+ p = (WalIterator *)sqlite3_malloc64(nByte);
+ if( !p ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ memset(p, 0, nByte);
+ p->nSegment = nSegment;
+
+ /* Allocate temporary space used by the merge-sort routine. This block
+ ** of memory will be freed before this function returns.
+ */
+ aTmp = (ht_slot *)sqlite3_malloc64(
+ sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
+ );
+ if( !aTmp ){
+ rc = SQLITE_NOMEM_BKPT;
+ }
+
+ for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){
+ WalHashLoc sLoc;
+
+ rc = walHashGet(pWal, i, &sLoc);
+ if( rc==SQLITE_OK ){
+ int j; /* Counter variable */
+ int nEntry; /* Number of entries in this segment */
+ ht_slot *aIndex; /* Sorted index for this segment */
+
+ sLoc.aPgno++;
+ if( (i+1)==nSegment ){
+ nEntry = (int)(iLast - sLoc.iZero);
+ }else{
+ nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);
+ }
+ aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
+ sLoc.iZero++;
+
+ for(j=0; j<nEntry; j++){
+ aIndex[j] = (ht_slot)j;
+ }
+ walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry);
+ p->aSegment[i].iZero = sLoc.iZero;
+ p->aSegment[i].nEntry = nEntry;
+ p->aSegment[i].aIndex = aIndex;
+ p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;
+ }
+ }
+ sqlite3_free(aTmp);
+
+ if( rc!=SQLITE_OK ){
+ walIteratorFree(p);
+ p = 0;
+ }
+ *pp = p;
+ return rc;
+}
+
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+/*
+** Attempt to enable blocking locks. Blocking locks are enabled only if (a)
+** they are supported by the VFS, and (b) the database handle is configured
+** with a busy-timeout. Return 1 if blocking locks are successfully enabled,
+** or 0 otherwise.
+*/
+static int walEnableBlocking(Wal *pWal){
+ int res = 0;
+ if( pWal->db ){
+ int tmout = pWal->db->busyTimeout;
+ if( tmout ){
+ int rc;
+ rc = sqlite3OsFileControl(
+ pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout
+ );
+ res = (rc==SQLITE_OK);
+ }
+ }
+ return res;
+}
+
+/*
+** Disable blocking locks.
+*/
+static void walDisableBlocking(Wal *pWal){
+ int tmout = 0;
+ sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout);
+}
+
+/*
+** If parameter bLock is true, attempt to enable blocking locks, take
+** the WRITER lock, and then disable blocking locks. If blocking locks
+** cannot be enabled, no attempt to obtain the WRITER lock is made. Return
+** an SQLite error code if an error occurs, or SQLITE_OK otherwise. It is not
+** an error if blocking locks can not be enabled.
+**
+** If the bLock parameter is false and the WRITER lock is held, release it.
+*/
+SQLITE_PRIVATE int sqlite3WalWriteLock(Wal *pWal, int bLock){
+ int rc = SQLITE_OK;
+ assert( pWal->readLock<0 || bLock==0 );
+ if( bLock ){
+ assert( pWal->db );
+ if( walEnableBlocking(pWal) ){
+ rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
+ if( rc==SQLITE_OK ){
+ pWal->writeLock = 1;
+ }
+ walDisableBlocking(pWal);
+ }
+ }else if( pWal->writeLock ){
+ walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
+ pWal->writeLock = 0;
+ }
+ return rc;
+}
+
+/*
+** Set the database handle used to determine if blocking locks are required.
+*/
+SQLITE_PRIVATE void sqlite3WalDb(Wal *pWal, sqlite3 *db){
+ pWal->db = db;
+}
+
+/*
+** Take an exclusive WRITE lock. Blocking if so configured.
+*/
+static int walLockWriter(Wal *pWal){
+ int rc;
+ walEnableBlocking(pWal);
+ rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
+ walDisableBlocking(pWal);
+ return rc;
+}
+#else
+# define walEnableBlocking(x) 0
+# define walDisableBlocking(x)
+# define walLockWriter(pWal) walLockExclusive((pWal), WAL_WRITE_LOCK, 1)
+# define sqlite3WalDb(pWal, db)
+#endif /* ifdef SQLITE_ENABLE_SETLK_TIMEOUT */
+
+
+/*
+** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
+** n. If the attempt fails and parameter xBusy is not NULL, then it is a
+** busy-handler function. Invoke it and retry the lock until either the
+** lock is successfully obtained or the busy-handler returns 0.
+*/
+static int walBusyLock(
+ Wal *pWal, /* WAL connection */
+ int (*xBusy)(void*), /* Function to call when busy */
+ void *pBusyArg, /* Context argument for xBusyHandler */
+ int lockIdx, /* Offset of first byte to lock */
+ int n /* Number of bytes to lock */
+){
+ int rc;
+ do {
+ rc = walLockExclusive(pWal, lockIdx, n);
+ }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+ if( rc==SQLITE_BUSY_TIMEOUT ){
+ walDisableBlocking(pWal);
+ rc = SQLITE_BUSY;
+ }
+#endif
+ return rc;
+}
+
+/*
+** The cache of the wal-index header must be valid to call this function.
+** Return the page-size in bytes used by the database.
+*/
+static int walPagesize(Wal *pWal){
+ return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
+}
+
+/*
+** The following is guaranteed when this function is called:
+**
+** a) the WRITER lock is held,
+** b) the entire log file has been checkpointed, and
+** c) any existing readers are reading exclusively from the database
+** file - there are no readers that may attempt to read a frame from
+** the log file.
+**
+** This function updates the shared-memory structures so that the next
+** client to write to the database (which may be this one) does so by
+** writing frames into the start of the log file.
+**
+** The value of parameter salt1 is used as the aSalt[1] value in the
+** new wal-index header. It should be passed a pseudo-random value (i.e.
+** one obtained from sqlite3_randomness()).
+*/
+static void walRestartHdr(Wal *pWal, u32 salt1){
+ volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
+ int i; /* Loop counter */
+ u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
+ pWal->nCkpt++;
+ pWal->hdr.mxFrame = 0;
+ sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
+ memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
+ walIndexWriteHdr(pWal);
+ AtomicStore(&pInfo->nBackfill, 0);
+ pInfo->nBackfillAttempted = 0;
+ pInfo->aReadMark[1] = 0;
+ for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
+ assert( pInfo->aReadMark[0]==0 );
+}
+
+/*
+** Copy as much content as we can from the WAL back into the database file
+** in response to an sqlite3_wal_checkpoint() request or the equivalent.
+**
+** The amount of information copies from WAL to database might be limited
+** by active readers. This routine will never overwrite a database page
+** that a concurrent reader might be using.
+**
+** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
+** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
+** checkpoints are always run by a background thread or background
+** process, foreground threads will never block on a lengthy fsync call.
+**
+** Fsync is called on the WAL before writing content out of the WAL and
+** into the database. This ensures that if the new content is persistent
+** in the WAL and can be recovered following a power-loss or hard reset.
+**
+** Fsync is also called on the database file if (and only if) the entire
+** WAL content is copied into the database file. This second fsync makes
+** it safe to delete the WAL since the new content will persist in the
+** database file.
+**
+** This routine uses and updates the nBackfill field of the wal-index header.
+** This is the only routine that will increase the value of nBackfill.
+** (A WAL reset or recovery will revert nBackfill to zero, but not increase
+** its value.)
+**
+** The caller must be holding sufficient locks to ensure that no other
+** checkpoint is running (in any other thread or process) at the same
+** time.
+*/
+static int walCheckpoint(
+ Wal *pWal, /* Wal connection */
+ sqlite3 *db, /* Check for interrupts on this handle */
+ int eMode, /* One of PASSIVE, FULL or RESTART */
+ int (*xBusy)(void*), /* Function to call when busy */
+ void *pBusyArg, /* Context argument for xBusyHandler */
+ int sync_flags, /* Flags for OsSync() (or 0) */
+ u8 *zBuf /* Temporary buffer to use */
+){
+ int rc = SQLITE_OK; /* Return code */
+ int szPage; /* Database page-size */
+ WalIterator *pIter = 0; /* Wal iterator context */
+ u32 iDbpage = 0; /* Next database page to write */
+ u32 iFrame = 0; /* Wal frame containing data for iDbpage */
+ u32 mxSafeFrame; /* Max frame that can be backfilled */
+ u32 mxPage; /* Max database page to write */
+ int i; /* Loop counter */
+ volatile WalCkptInfo *pInfo; /* The checkpoint status information */
+
+ szPage = walPagesize(pWal);
+ testcase( szPage<=32768 );
+ testcase( szPage>=65536 );
+ pInfo = walCkptInfo(pWal);
+ if( pInfo->nBackfill<pWal->hdr.mxFrame ){
+
+ /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
+ ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
+ assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
+
+ /* Compute in mxSafeFrame the index of the last frame of the WAL that is
+ ** safe to write into the database. Frames beyond mxSafeFrame might
+ ** overwrite database pages that are in use by active readers and thus
+ ** cannot be backfilled from the WAL.
+ */
+ mxSafeFrame = pWal->hdr.mxFrame;
+ mxPage = pWal->hdr.nPage;
+ for(i=1; i<WAL_NREADER; i++){
+ u32 y = AtomicLoad(pInfo->aReadMark+i);
+ if( mxSafeFrame>y ){
+ assert( y<=pWal->hdr.mxFrame );
+ rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
+ if( rc==SQLITE_OK ){
+ u32 iMark = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
+ AtomicStore(pInfo->aReadMark+i, iMark);
+ walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
+ }else if( rc==SQLITE_BUSY ){
+ mxSafeFrame = y;
+ xBusy = 0;
+ }else{
+ goto walcheckpoint_out;
+ }
+ }
+ }
+
+ /* Allocate the iterator */
+ if( pInfo->nBackfill<mxSafeFrame ){
+ rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
+ assert( rc==SQLITE_OK || pIter==0 );
+ }
+
+ if( pIter
+ && (rc = walBusyLock(pWal,xBusy,pBusyArg,WAL_READ_LOCK(0),1))==SQLITE_OK
+ ){
+ u32 nBackfill = pInfo->nBackfill;
+
+ pInfo->nBackfillAttempted = mxSafeFrame;
+
+ /* Sync the WAL to disk */
+ rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
+
+ /* If the database may grow as a result of this checkpoint, hint
+ ** about the eventual size of the db file to the VFS layer.
+ */
+ if( rc==SQLITE_OK ){
+ i64 nReq = ((i64)mxPage * szPage);
+ i64 nSize; /* Current size of database file */
+ sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0);
+ rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
+ if( rc==SQLITE_OK && nSize<nReq ){
+ if( (nSize+65536+(i64)pWal->hdr.mxFrame*szPage)<nReq ){
+ /* If the size of the final database is larger than the current
+ ** database plus the amount of data in the wal file, plus the
+ ** maximum size of the pending-byte page (65536 bytes), then
+ ** must be corruption somewhere. */
+ rc = SQLITE_CORRUPT_BKPT;
+ }else{
+ sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT,&nReq);
+ }
+ }
+
+ }
+
+ /* Iterate through the contents of the WAL, copying data to the db file */
+ while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
+ i64 iOffset;
+ assert( walFramePgno(pWal, iFrame)==iDbpage );
+ if( AtomicLoad(&db->u1.isInterrupted) ){
+ rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
+ break;
+ }
+ if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
+ continue;
+ }
+ iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
+ /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
+ rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
+ if( rc!=SQLITE_OK ) break;
+ iOffset = (iDbpage-1)*(i64)szPage;
+ testcase( IS_BIG_INT(iOffset) );
+ rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
+ if( rc!=SQLITE_OK ) break;
+ }
+ sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0);
+
+ /* If work was actually accomplished... */
+ if( rc==SQLITE_OK ){
+ if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
+ i64 szDb = pWal->hdr.nPage*(i64)szPage;
+ testcase( IS_BIG_INT(szDb) );
+ rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
+ }
+ }
+ if( rc==SQLITE_OK ){
+ AtomicStore(&pInfo->nBackfill, mxSafeFrame);
+ }
+ }
+
+ /* Release the reader lock held while backfilling */
+ walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
+ }
+
+ if( rc==SQLITE_BUSY ){
+ /* Reset the return code so as not to report a checkpoint failure
+ ** just because there are active readers. */
+ rc = SQLITE_OK;
+ }
+ }
+
+ /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
+ ** entire wal file has been copied into the database file, then block
+ ** until all readers have finished using the wal file. This ensures that
+ ** the next process to write to the database restarts the wal file.
+ */
+ if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
+ assert( pWal->writeLock );
+ if( pInfo->nBackfill<pWal->hdr.mxFrame ){
+ rc = SQLITE_BUSY;
+ }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
+ u32 salt1;
+ sqlite3_randomness(4, &salt1);
+ assert( pInfo->nBackfill==pWal->hdr.mxFrame );
+ rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
+ if( rc==SQLITE_OK ){
+ if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
+ /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
+ ** SQLITE_CHECKPOINT_RESTART with the addition that it also
+ ** truncates the log file to zero bytes just prior to a
+ ** successful return.
+ **
+ ** In theory, it might be safe to do this without updating the
+ ** wal-index header in shared memory, as all subsequent reader or
+ ** writer clients should see that the entire log file has been
+ ** checkpointed and behave accordingly. This seems unsafe though,
+ ** as it would leave the system in a state where the contents of
+ ** the wal-index header do not match the contents of the
+ ** file-system. To avoid this, update the wal-index header to
+ ** indicate that the log file contains zero valid frames. */
+ walRestartHdr(pWal, salt1);
+ rc = sqlite3OsTruncate(pWal->pWalFd, 0);
+ }
+ walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
+ }
+ }
+ }
+
+ walcheckpoint_out:
+ walIteratorFree(pIter);
+ return rc;
+}
+
+/*
+** If the WAL file is currently larger than nMax bytes in size, truncate
+** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
+*/
+static void walLimitSize(Wal *pWal, i64 nMax){
+ i64 sz;
+ int rx;
+ sqlite3BeginBenignMalloc();
+ rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
+ if( rx==SQLITE_OK && (sz > nMax ) ){
+ rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
+ }
+ sqlite3EndBenignMalloc();
+ if( rx ){
+ sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
+ }
+}
+
+/*
+** Close a connection to a log file.
+*/
+SQLITE_PRIVATE int sqlite3WalClose(
+ Wal *pWal, /* Wal to close */
+ sqlite3 *db, /* For interrupt flag */
+ int sync_flags, /* Flags to pass to OsSync() (or 0) */
+ int nBuf,
+ u8 *zBuf /* Buffer of at least nBuf bytes */
+){
+ int rc = SQLITE_OK;
+ if( pWal ){
+ int isDelete = 0; /* True to unlink wal and wal-index files */
+
+ /* If an EXCLUSIVE lock can be obtained on the database file (using the
+ ** ordinary, rollback-mode locking methods, this guarantees that the
+ ** connection associated with this log file is the only connection to
+ ** the database. In this case checkpoint the database and unlink both
+ ** the wal and wal-index files.
+ **
+ ** The EXCLUSIVE lock is not released before returning.
+ */
+ if( zBuf!=0
+ && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
+ ){
+ if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
+ pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
+ }
+ rc = sqlite3WalCheckpoint(pWal, db,
+ SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
+ );
+ if( rc==SQLITE_OK ){
+ int bPersist = -1;
+ sqlite3OsFileControlHint(
+ pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
+ );
+ if( bPersist!=1 ){
+ /* Try to delete the WAL file if the checkpoint completed and
+ ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
+ ** mode (!bPersist) */
+ isDelete = 1;
+ }else if( pWal->mxWalSize>=0 ){
+ /* Try to truncate the WAL file to zero bytes if the checkpoint
+ ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
+ ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
+ ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
+ ** to zero bytes as truncating to the journal_size_limit might
+ ** leave a corrupt WAL file on disk. */
+ walLimitSize(pWal, 0);
+ }
+ }
+ }
+
+ walIndexClose(pWal, isDelete);
+ sqlite3OsClose(pWal->pWalFd);
+ if( isDelete ){
+ sqlite3BeginBenignMalloc();
+ sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
+ sqlite3EndBenignMalloc();
+ }
+ WALTRACE(("WAL%p: closed\n", pWal));
+ sqlite3_free((void *)pWal->apWiData);
+ sqlite3_free(pWal);
+ }
+ return rc;
+}
+
+/*
+** Try to read the wal-index header. Return 0 on success and 1 if
+** there is a problem.
+**
+** The wal-index is in shared memory. Another thread or process might
+** be writing the header at the same time this procedure is trying to
+** read it, which might result in inconsistency. A dirty read is detected
+** by verifying that both copies of the header are the same and also by
+** a checksum on the header.
+**
+** If and only if the read is consistent and the header is different from
+** pWal->hdr, then pWal->hdr is updated to the content of the new header
+** and *pChanged is set to 1.
+**
+** If the checksum cannot be verified return non-zero. If the header
+** is read successfully and the checksum verified, return zero.
+*/
+static SQLITE_NO_TSAN int walIndexTryHdr(Wal *pWal, int *pChanged){
+ u32 aCksum[2]; /* Checksum on the header content */
+ WalIndexHdr h1, h2; /* Two copies of the header content */
+ WalIndexHdr volatile *aHdr; /* Header in shared memory */
+
+ /* The first page of the wal-index must be mapped at this point. */
+ assert( pWal->nWiData>0 && pWal->apWiData[0] );
+
+ /* Read the header. This might happen concurrently with a write to the
+ ** same area of shared memory on a different CPU in a SMP,
+ ** meaning it is possible that an inconsistent snapshot is read
+ ** from the file. If this happens, return non-zero.
+ **
+ ** tag-20200519-1:
+ ** There are two copies of the header at the beginning of the wal-index.
+ ** When reading, read [0] first then [1]. Writes are in the reverse order.
+ ** Memory barriers are used to prevent the compiler or the hardware from
+ ** reordering the reads and writes. TSAN and similar tools can sometimes
+ ** give false-positive warnings about these accesses because the tools do not
+ ** account for the double-read and the memory barrier. The use of mutexes
+ ** here would be problematic as the memory being accessed is potentially
+ ** shared among multiple processes and not all mutex implementions work
+ ** reliably in that environment.
+ */
+ aHdr = walIndexHdr(pWal);
+ memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); /* Possible TSAN false-positive */
+ walShmBarrier(pWal);
+ memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
+
+ if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
+ return 1; /* Dirty read */
+ }
+ if( h1.isInit==0 ){
+ return 1; /* Malformed header - probably all zeros */
+ }
+ walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
+ if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
+ return 1; /* Checksum does not match */
+ }
+
+ if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
+ *pChanged = 1;
+ memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
+ pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
+ testcase( pWal->szPage<=32768 );
+ testcase( pWal->szPage>=65536 );
+ }
+
+ /* The header was successfully read. Return zero. */
+ return 0;
+}
+
+/*
+** This is the value that walTryBeginRead returns when it needs to
+** be retried.
+*/
+#define WAL_RETRY (-1)
+
+/*
+** Read the wal-index header from the wal-index and into pWal->hdr.
+** If the wal-header appears to be corrupt, try to reconstruct the
+** wal-index from the WAL before returning.
+**
+** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
+** changed by this operation. If pWal->hdr is unchanged, set *pChanged
+** to 0.
+**
+** If the wal-index header is successfully read, return SQLITE_OK.
+** Otherwise an SQLite error code.
+*/
+static int walIndexReadHdr(Wal *pWal, int *pChanged){
+ int rc; /* Return code */
+ int badHdr; /* True if a header read failed */
+ volatile u32 *page0; /* Chunk of wal-index containing header */
+
+ /* Ensure that page 0 of the wal-index (the page that contains the
+ ** wal-index header) is mapped. Return early if an error occurs here.
+ */
+ assert( pChanged );
+ rc = walIndexPage(pWal, 0, &page0);
+ if( rc!=SQLITE_OK ){
+ assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */
+ if( rc==SQLITE_READONLY_CANTINIT ){
+ /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
+ ** was openable but is not writable, and this thread is unable to
+ ** confirm that another write-capable connection has the shared-memory
+ ** open, and hence the content of the shared-memory is unreliable,
+ ** since the shared-memory might be inconsistent with the WAL file
+ ** and there is no writer on hand to fix it. */
+ assert( page0==0 );
+ assert( pWal->writeLock==0 );
+ assert( pWal->readOnly & WAL_SHM_RDONLY );
+ pWal->bShmUnreliable = 1;
+ pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
+ *pChanged = 1;
+ }else{
+ return rc; /* Any other non-OK return is just an error */
+ }
+ }else{
+ /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
+ ** is zero, which prevents the SHM from growing */
+ testcase( page0!=0 );
+ }
+ assert( page0!=0 || pWal->writeLock==0 );
+
+ /* If the first page of the wal-index has been mapped, try to read the
+ ** wal-index header immediately, without holding any lock. This usually
+ ** works, but may fail if the wal-index header is corrupt or currently
+ ** being modified by another thread or process.
+ */
+ badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
+
+ /* If the first attempt failed, it might have been due to a race
+ ** with a writer. So get a WRITE lock and try again.
+ */
+ if( badHdr ){
+ if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
+ if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
+ walUnlockShared(pWal, WAL_WRITE_LOCK);
+ rc = SQLITE_READONLY_RECOVERY;
+ }
+ }else{
+ int bWriteLock = pWal->writeLock;
+ if( bWriteLock || SQLITE_OK==(rc = walLockWriter(pWal)) ){
+ pWal->writeLock = 1;
+ if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
+ badHdr = walIndexTryHdr(pWal, pChanged);
+ if( badHdr ){
+ /* If the wal-index header is still malformed even while holding
+ ** a WRITE lock, it can only mean that the header is corrupted and
+ ** needs to be reconstructed. So run recovery to do exactly that.
+ */
+ rc = walIndexRecover(pWal);
+ *pChanged = 1;
+ }
+ }
+ if( bWriteLock==0 ){
+ pWal->writeLock = 0;
+ walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
+ }
+ }
+ }
+ }
+
+ /* If the header is read successfully, check the version number to make
+ ** sure the wal-index was not constructed with some future format that
+ ** this version of SQLite cannot understand.
+ */
+ if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
+ rc = SQLITE_CANTOPEN_BKPT;
+ }
+ if( pWal->bShmUnreliable ){
+ if( rc!=SQLITE_OK ){
+ walIndexClose(pWal, 0);
+ pWal->bShmUnreliable = 0;
+ assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
+ /* walIndexRecover() might have returned SHORT_READ if a concurrent
+ ** writer truncated the WAL out from under it. If that happens, it
+ ** indicates that a writer has fixed the SHM file for us, so retry */
+ if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;
+ }
+ pWal->exclusiveMode = WAL_NORMAL_MODE;
+ }
+
+ return rc;
+}
+
+/*
+** Open a transaction in a connection where the shared-memory is read-only
+** and where we cannot verify that there is a separate write-capable connection
+** on hand to keep the shared-memory up-to-date with the WAL file.
+**
+** This can happen, for example, when the shared-memory is implemented by
+** memory-mapping a *-shm file, where a prior writer has shut down and
+** left the *-shm file on disk, and now the present connection is trying
+** to use that database but lacks write permission on the *-shm file.
+** Other scenarios are also possible, depending on the VFS implementation.
+**
+** Precondition:
+**
+** The *-wal file has been read and an appropriate wal-index has been
+** constructed in pWal->apWiData[] using heap memory instead of shared
+** memory.
+**
+** If this function returns SQLITE_OK, then the read transaction has
+** been successfully opened. In this case output variable (*pChanged)
+** is set to true before returning if the caller should discard the
+** contents of the page cache before proceeding. Or, if it returns
+** WAL_RETRY, then the heap memory wal-index has been discarded and
+** the caller should retry opening the read transaction from the
+** beginning (including attempting to map the *-shm file).
+**
+** If an error occurs, an SQLite error code is returned.
+*/
+static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
+ i64 szWal; /* Size of wal file on disk in bytes */
+ i64 iOffset; /* Current offset when reading wal file */
+ u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
+ u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
+ int szFrame; /* Number of bytes in buffer aFrame[] */
+ u8 *aData; /* Pointer to data part of aFrame buffer */
+ volatile void *pDummy; /* Dummy argument for xShmMap */
+ int rc; /* Return code */
+ u32 aSaveCksum[2]; /* Saved copy of pWal->hdr.aFrameCksum */
+
+ assert( pWal->bShmUnreliable );
+ assert( pWal->readOnly & WAL_SHM_RDONLY );
+ assert( pWal->nWiData>0 && pWal->apWiData[0] );
+
+ /* Take WAL_READ_LOCK(0). This has the effect of preventing any
+ ** writers from running a checkpoint, but does not stop them
+ ** from running recovery. */
+ rc = walLockShared(pWal, WAL_READ_LOCK(0));
+ if( rc!=SQLITE_OK ){
+ if( rc==SQLITE_BUSY ) rc = WAL_RETRY;
+ goto begin_unreliable_shm_out;
+ }
+ pWal->readLock = 0;
+
+ /* Check to see if a separate writer has attached to the shared-memory area,
+ ** thus making the shared-memory "reliable" again. Do this by invoking
+ ** the xShmMap() routine of the VFS and looking to see if the return
+ ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
+ **
+ ** If the shared-memory is now "reliable" return WAL_RETRY, which will
+ ** cause the heap-memory WAL-index to be discarded and the actual
+ ** shared memory to be used in its place.
+ **
+ ** This step is important because, even though this connection is holding
+ ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
+ ** have already checkpointed the WAL file and, while the current
+ ** is active, wrap the WAL and start overwriting frames that this
+ ** process wants to use.
+ **
+ ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
+ ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
+ ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
+ ** even if some external agent does a "chmod" to make the shared-memory
+ ** writable by us, until sqlite3OsShmUnmap() has been called.
+ ** This is a requirement on the VFS implementation.
+ */
+ rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
+ assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
+ if( rc!=SQLITE_READONLY_CANTINIT ){
+ rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
+ goto begin_unreliable_shm_out;
+ }
+
+ /* We reach this point only if the real shared-memory is still unreliable.
+ ** Assume the in-memory WAL-index substitute is correct and load it
+ ** into pWal->hdr.
+ */
+ memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
+
+ /* Make sure some writer hasn't come in and changed the WAL file out
+ ** from under us, then disconnected, while we were not looking.
+ */
+ rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
+ if( rc!=SQLITE_OK ){
+ goto begin_unreliable_shm_out;
+ }
+ if( szWal<WAL_HDRSIZE ){
+ /* If the wal file is too small to contain a wal-header and the
+ ** wal-index header has mxFrame==0, then it must be safe to proceed
+ ** reading the database file only. However, the page cache cannot
+ ** be trusted, as a read/write connection may have connected, written
+ ** the db, run a checkpoint, truncated the wal file and disconnected
+ ** since this client's last read transaction. */
+ *pChanged = 1;
+ rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
+ goto begin_unreliable_shm_out;
+ }
+
+ /* Check the salt keys at the start of the wal file still match. */
+ rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
+ if( rc!=SQLITE_OK ){
+ goto begin_unreliable_shm_out;
+ }
+ if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
+ /* Some writer has wrapped the WAL file while we were not looking.
+ ** Return WAL_RETRY which will cause the in-memory WAL-index to be
+ ** rebuilt. */
+ rc = WAL_RETRY;
+ goto begin_unreliable_shm_out;
+ }
+
+ /* Allocate a buffer to read frames into */
+ szFrame = pWal->hdr.szPage + WAL_FRAME_HDRSIZE;
+ aFrame = (u8 *)sqlite3_malloc64(szFrame);
+ if( aFrame==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto begin_unreliable_shm_out;
+ }
+ aData = &aFrame[WAL_FRAME_HDRSIZE];
+
+ /* Check to see if a complete transaction has been appended to the
+ ** wal file since the heap-memory wal-index was created. If so, the
+ ** heap-memory wal-index is discarded and WAL_RETRY returned to
+ ** the caller. */
+ aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
+ aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
+ for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage);
+ iOffset+szFrame<=szWal;
+ iOffset+=szFrame
+ ){
+ u32 pgno; /* Database page number for frame */
+ u32 nTruncate; /* dbsize field from frame header */
+
+ /* Read and decode the next log frame. */
+ rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
+ if( rc!=SQLITE_OK ) break;
+ if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;
+
+ /* If nTruncate is non-zero, then a complete transaction has been
+ ** appended to this wal file. Set rc to WAL_RETRY and break out of
+ ** the loop. */
+ if( nTruncate ){
+ rc = WAL_RETRY;
+ break;
+ }
+ }
+ pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
+ pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
+
+ begin_unreliable_shm_out:
+ sqlite3_free(aFrame);
+ if( rc!=SQLITE_OK ){
+ int i;
+ for(i=0; i<pWal->nWiData; i++){
+ sqlite3_free((void*)pWal->apWiData[i]);
+ pWal->apWiData[i] = 0;
+ }
+ pWal->bShmUnreliable = 0;
+ sqlite3WalEndReadTransaction(pWal);
+ *pChanged = 1;
+ }
+ return rc;
+}
+
+/*
+** Attempt to start a read transaction. This might fail due to a race or
+** other transient condition. When that happens, it returns WAL_RETRY to
+** indicate to the caller that it is safe to retry immediately.
+**
+** On success return SQLITE_OK. On a permanent failure (such an
+** I/O error or an SQLITE_BUSY because another process is running
+** recovery) return a positive error code.
+**
+** The useWal parameter is true to force the use of the WAL and disable
+** the case where the WAL is bypassed because it has been completely
+** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
+** to make a copy of the wal-index header into pWal->hdr. If the
+** wal-index header has changed, *pChanged is set to 1 (as an indication
+** to the caller that the local page cache is obsolete and needs to be
+** flushed.) When useWal==1, the wal-index header is assumed to already
+** be loaded and the pChanged parameter is unused.
+**
+** The caller must set the cnt parameter to the number of prior calls to
+** this routine during the current read attempt that returned WAL_RETRY.
+** This routine will start taking more aggressive measures to clear the
+** race conditions after multiple WAL_RETRY returns, and after an excessive
+** number of errors will ultimately return SQLITE_PROTOCOL. The
+** SQLITE_PROTOCOL return indicates that some other process has gone rogue
+** and is not honoring the locking protocol. There is a vanishingly small
+** chance that SQLITE_PROTOCOL could be returned because of a run of really
+** bad luck when there is lots of contention for the wal-index, but that
+** possibility is so small that it can be safely neglected, we believe.
+**
+** On success, this routine obtains a read lock on
+** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
+** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
+** that means the Wal does not hold any read lock. The reader must not
+** access any database page that is modified by a WAL frame up to and
+** including frame number aReadMark[pWal->readLock]. The reader will
+** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
+** Or if pWal->readLock==0, then the reader will ignore the WAL
+** completely and get all content directly from the database file.
+** If the useWal parameter is 1 then the WAL will never be ignored and
+** this routine will always set pWal->readLock>0 on success.
+** When the read transaction is completed, the caller must release the
+** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
+**
+** This routine uses the nBackfill and aReadMark[] fields of the header
+** to select a particular WAL_READ_LOCK() that strives to let the
+** checkpoint process do as much work as possible. This routine might
+** update values of the aReadMark[] array in the header, but if it does
+** so it takes care to hold an exclusive lock on the corresponding
+** WAL_READ_LOCK() while changing values.
+*/
+static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
+ volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
+ u32 mxReadMark; /* Largest aReadMark[] value */
+ int mxI; /* Index of largest aReadMark[] value */
+ int i; /* Loop counter */
+ int rc = SQLITE_OK; /* Return code */
+ u32 mxFrame; /* Wal frame to lock to */
+
+ assert( pWal->readLock<0 ); /* Not currently locked */
+
+ /* useWal may only be set for read/write connections */
+ assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
+
+ /* Take steps to avoid spinning forever if there is a protocol error.
+ **
+ ** Circumstances that cause a RETRY should only last for the briefest
+ ** instances of time. No I/O or other system calls are done while the
+ ** locks are held, so the locks should not be held for very long. But
+ ** if we are unlucky, another process that is holding a lock might get
+ ** paged out or take a page-fault that is time-consuming to resolve,
+ ** during the few nanoseconds that it is holding the lock. In that case,
+ ** it might take longer than normal for the lock to free.
+ **
+ ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
+ ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
+ ** is more of a scheduler yield than an actual delay. But on the 10th
+ ** an subsequent retries, the delays start becoming longer and longer,
+ ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
+ ** The total delay time before giving up is less than 10 seconds.
+ */
+ if( cnt>5 ){
+ int nDelay = 1; /* Pause time in microseconds */
+ if( cnt>100 ){
+ VVA_ONLY( pWal->lockError = 1; )
+ return SQLITE_PROTOCOL;
+ }
+ if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
+ sqlite3OsSleep(pWal->pVfs, nDelay);
+ }
+
+ if( !useWal ){
+ assert( rc==SQLITE_OK );
+ if( pWal->bShmUnreliable==0 ){
+ rc = walIndexReadHdr(pWal, pChanged);
+ }
+ if( rc==SQLITE_BUSY ){
+ /* If there is not a recovery running in another thread or process
+ ** then convert BUSY errors to WAL_RETRY. If recovery is known to
+ ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
+ ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
+ ** would be technically correct. But the race is benign since with
+ ** WAL_RETRY this routine will be called again and will probably be
+ ** right on the second iteration.
+ */
+ if( pWal->apWiData[0]==0 ){
+ /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
+ ** We assume this is a transient condition, so return WAL_RETRY. The
+ ** xShmMap() implementation used by the default unix and win32 VFS
+ ** modules may return SQLITE_BUSY due to a race condition in the
+ ** code that determines whether or not the shared-memory region
+ ** must be zeroed before the requested page is returned.
+ */
+ rc = WAL_RETRY;
+ }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
+ walUnlockShared(pWal, WAL_RECOVER_LOCK);
+ rc = WAL_RETRY;
+ }else if( rc==SQLITE_BUSY ){
+ rc = SQLITE_BUSY_RECOVERY;
+ }
+ }
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ else if( pWal->bShmUnreliable ){
+ return walBeginShmUnreliable(pWal, pChanged);
+ }
+ }
+
+ assert( pWal->nWiData>0 );
+ assert( pWal->apWiData[0]!=0 );
+ pInfo = walCkptInfo(pWal);
+ if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame
+#ifdef SQLITE_ENABLE_SNAPSHOT
+ && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
+#endif
+ ){
+ /* The WAL has been completely backfilled (or it is empty).
+ ** and can be safely ignored.
+ */
+ rc = walLockShared(pWal, WAL_READ_LOCK(0));
+ walShmBarrier(pWal);
+ if( rc==SQLITE_OK ){
+ if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
+ /* It is not safe to allow the reader to continue here if frames
+ ** may have been appended to the log before READ_LOCK(0) was obtained.
+ ** When holding READ_LOCK(0), the reader ignores the entire log file,
+ ** which implies that the database file contains a trustworthy
+ ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
+ ** happening, this is usually correct.
+ **
+ ** However, if frames have been appended to the log (or if the log
+ ** is wrapped and written for that matter) before the READ_LOCK(0)
+ ** is obtained, that is not necessarily true. A checkpointer may
+ ** have started to backfill the appended frames but crashed before
+ ** it finished. Leaving a corrupt image in the database file.
+ */
+ walUnlockShared(pWal, WAL_READ_LOCK(0));
+ return WAL_RETRY;
+ }
+ pWal->readLock = 0;
+ return SQLITE_OK;
+ }else if( rc!=SQLITE_BUSY ){
+ return rc;
+ }
+ }
+
+ /* If we get this far, it means that the reader will want to use
+ ** the WAL to get at content from recent commits. The job now is
+ ** to select one of the aReadMark[] entries that is closest to
+ ** but not exceeding pWal->hdr.mxFrame and lock that entry.
+ */
+ mxReadMark = 0;
+ mxI = 0;
+ mxFrame = pWal->hdr.mxFrame;
+#ifdef SQLITE_ENABLE_SNAPSHOT
+ if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
+ mxFrame = pWal->pSnapshot->mxFrame;
+ }
+#endif
+ for(i=1; i<WAL_NREADER; i++){
+ u32 thisMark = AtomicLoad(pInfo->aReadMark+i);
+ if( mxReadMark<=thisMark && thisMark<=mxFrame ){
+ assert( thisMark!=READMARK_NOT_USED );
+ mxReadMark = thisMark;
+ mxI = i;
+ }
+ }
+ if( (pWal->readOnly & WAL_SHM_RDONLY)==0
+ && (mxReadMark<mxFrame || mxI==0)
+ ){
+ for(i=1; i<WAL_NREADER; i++){
+ rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
+ if( rc==SQLITE_OK ){
+ AtomicStore(pInfo->aReadMark+i,mxFrame);
+ mxReadMark = mxFrame;
+ mxI = i;
+ walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
+ break;
+ }else if( rc!=SQLITE_BUSY ){
+ return rc;
+ }
+ }
+ }
+ if( mxI==0 ){
+ assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
+ return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
+ }
+
+ rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
+ if( rc ){
+ return rc==SQLITE_BUSY ? WAL_RETRY : rc;
+ }
+ /* Now that the read-lock has been obtained, check that neither the
+ ** value in the aReadMark[] array or the contents of the wal-index
+ ** header have changed.
+ **
+ ** It is necessary to check that the wal-index header did not change
+ ** between the time it was read and when the shared-lock was obtained
+ ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
+ ** that the log file may have been wrapped by a writer, or that frames
+ ** that occur later in the log than pWal->hdr.mxFrame may have been
+ ** copied into the database by a checkpointer. If either of these things
+ ** happened, then reading the database with the current value of
+ ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
+ ** instead.
+ **
+ ** Before checking that the live wal-index header has not changed
+ ** since it was read, set Wal.minFrame to the first frame in the wal
+ ** file that has not yet been checkpointed. This client will not need
+ ** to read any frames earlier than minFrame from the wal file - they
+ ** can be safely read directly from the database file.
+ **
+ ** Because a ShmBarrier() call is made between taking the copy of
+ ** nBackfill and checking that the wal-header in shared-memory still
+ ** matches the one cached in pWal->hdr, it is guaranteed that the
+ ** checkpointer that set nBackfill was not working with a wal-index
+ ** header newer than that cached in pWal->hdr. If it were, that could
+ ** cause a problem. The checkpointer could omit to checkpoint
+ ** a version of page X that lies before pWal->minFrame (call that version
+ ** A) on the basis that there is a newer version (version B) of the same
+ ** page later in the wal file. But if version B happens to like past
+ ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
+ ** that it can read version A from the database file. However, since
+ ** we can guarantee that the checkpointer that set nBackfill could not
+ ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
+ */
+ pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1;
+ walShmBarrier(pWal);
+ if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
+ || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
+ ){
+ walUnlockShared(pWal, WAL_READ_LOCK(mxI));
+ return WAL_RETRY;
+ }else{
+ assert( mxReadMark<=pWal->hdr.mxFrame );
+ pWal->readLock = (i16)mxI;
+ }
+ return rc;
+}
+
+#ifdef SQLITE_ENABLE_SNAPSHOT
+/*
+** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
+** variable so that older snapshots can be accessed. To do this, loop
+** through all wal frames from nBackfillAttempted to (nBackfill+1),
+** comparing their content to the corresponding page with the database
+** file, if any. Set nBackfillAttempted to the frame number of the
+** first frame for which the wal file content matches the db file.
+**
+** This is only really safe if the file-system is such that any page
+** writes made by earlier checkpointers were atomic operations, which
+** is not always true. It is also possible that nBackfillAttempted
+** may be left set to a value larger than expected, if a wal frame
+** contains content that duplicate of an earlier version of the same
+** page.
+**
+** SQLITE_OK is returned if successful, or an SQLite error code if an
+** error occurs. It is not an error if nBackfillAttempted cannot be
+** decreased at all.
+*/
+SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
+ int rc;
+
+ assert( pWal->readLock>=0 );
+ rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
+ if( rc==SQLITE_OK ){
+ volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
+ int szPage = (int)pWal->szPage;
+ i64 szDb; /* Size of db file in bytes */
+
+ rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
+ if( rc==SQLITE_OK ){
+ void *pBuf1 = sqlite3_malloc(szPage);
+ void *pBuf2 = sqlite3_malloc(szPage);
+ if( pBuf1==0 || pBuf2==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ u32 i = pInfo->nBackfillAttempted;
+ for(i=pInfo->nBackfillAttempted; i>AtomicLoad(&pInfo->nBackfill); i--){
+ WalHashLoc sLoc; /* Hash table location */
+ u32 pgno; /* Page number in db file */
+ i64 iDbOff; /* Offset of db file entry */
+ i64 iWalOff; /* Offset of wal file entry */
+
+ rc = walHashGet(pWal, walFramePage(i), &sLoc);
+ if( rc!=SQLITE_OK ) break;
+ pgno = sLoc.aPgno[i-sLoc.iZero];
+ iDbOff = (i64)(pgno-1) * szPage;
+
+ if( iDbOff+szPage<=szDb ){
+ iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
+ rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
+
+ if( rc==SQLITE_OK ){
+ rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
+ }
+
+ if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
+ break;
+ }
+ }
+
+ pInfo->nBackfillAttempted = i-1;
+ }
+ }
+
+ sqlite3_free(pBuf1);
+ sqlite3_free(pBuf2);
+ }
+ walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
+ }
+
+ return rc;
+}
+#endif /* SQLITE_ENABLE_SNAPSHOT */
+
+/*
+** Begin a read transaction on the database.
+**
+** This routine used to be called sqlite3OpenSnapshot() and with good reason:
+** it takes a snapshot of the state of the WAL and wal-index for the current
+** instant in time. The current thread will continue to use this snapshot.
+** Other threads might append new content to the WAL and wal-index but
+** that extra content is ignored by the current thread.
+**
+** If the database contents have changes since the previous read
+** transaction, then *pChanged is set to 1 before returning. The
+** Pager layer will use this to know that its cache is stale and
+** needs to be flushed.
+*/
+SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
+ int rc; /* Return code */
+ int cnt = 0; /* Number of TryBeginRead attempts */
+#ifdef SQLITE_ENABLE_SNAPSHOT
+ int bChanged = 0;
+ WalIndexHdr *pSnapshot = pWal->pSnapshot;
+#endif
+
+ assert( pWal->ckptLock==0 );
+
+#ifdef SQLITE_ENABLE_SNAPSHOT
+ if( pSnapshot ){
+ if( memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
+ bChanged = 1;
+ }
+
+ /* It is possible that there is a checkpointer thread running
+ ** concurrent with this code. If this is the case, it may be that the
+ ** checkpointer has already determined that it will checkpoint
+ ** snapshot X, where X is later in the wal file than pSnapshot, but
+ ** has not yet set the pInfo->nBackfillAttempted variable to indicate
+ ** its intent. To avoid the race condition this leads to, ensure that
+ ** there is no checkpointer process by taking a shared CKPT lock
+ ** before checking pInfo->nBackfillAttempted. */
+ (void)walEnableBlocking(pWal);
+ rc = walLockShared(pWal, WAL_CKPT_LOCK);
+ walDisableBlocking(pWal);
+
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ pWal->ckptLock = 1;
+ }
+#endif
+
+ do{
+ rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
+ }while( rc==WAL_RETRY );
+ testcase( (rc&0xff)==SQLITE_BUSY );
+ testcase( (rc&0xff)==SQLITE_IOERR );
+ testcase( rc==SQLITE_PROTOCOL );
+ testcase( rc==SQLITE_OK );
+
+#ifdef SQLITE_ENABLE_SNAPSHOT
+ if( rc==SQLITE_OK ){
+ if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
+ /* At this point the client has a lock on an aReadMark[] slot holding
+ ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
+ ** is populated with the wal-index header corresponding to the head
+ ** of the wal file. Verify that pSnapshot is still valid before
+ ** continuing. Reasons why pSnapshot might no longer be valid:
+ **
+ ** (1) The WAL file has been reset since the snapshot was taken.
+ ** In this case, the salt will have changed.
+ **
+ ** (2) A checkpoint as been attempted that wrote frames past
+ ** pSnapshot->mxFrame into the database file. Note that the
+ ** checkpoint need not have completed for this to cause problems.
+ */
+ volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
+
+ assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
+ assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
+
+ /* Check that the wal file has not been wrapped. Assuming that it has
+ ** not, also check that no checkpointer has attempted to checkpoint any
+ ** frames beyond pSnapshot->mxFrame. If either of these conditions are
+ ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
+ ** with *pSnapshot and set *pChanged as appropriate for opening the
+ ** snapshot. */
+ if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
+ && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
+ ){
+ assert( pWal->readLock>0 );
+ memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
+ *pChanged = bChanged;
+ }else{
+ rc = SQLITE_ERROR_SNAPSHOT;
+ }
+
+ /* A client using a non-current snapshot may not ignore any frames
+ ** from the start of the wal file. This is because, for a system
+ ** where (minFrame < iSnapshot < maxFrame), a checkpointer may
+ ** have omitted to checkpoint a frame earlier than minFrame in
+ ** the file because there exists a frame after iSnapshot that
+ ** is the same database page. */
+ pWal->minFrame = 1;
+
+ if( rc!=SQLITE_OK ){
+ sqlite3WalEndReadTransaction(pWal);
+ }
+ }
+ }
+
+ /* Release the shared CKPT lock obtained above. */
+ if( pWal->ckptLock ){
+ assert( pSnapshot );
+ walUnlockShared(pWal, WAL_CKPT_LOCK);
+ pWal->ckptLock = 0;
+ }
+#endif
+ return rc;
+}
+
+/*
+** Finish with a read transaction. All this does is release the
+** read-lock.
+*/
+SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
+ sqlite3WalEndWriteTransaction(pWal);
+ if( pWal->readLock>=0 ){
+ walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
+ pWal->readLock = -1;
+ }
+}
+
+/*
+** Search the wal file for page pgno. If found, set *piRead to the frame that
+** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
+** to zero.
+**
+** Return SQLITE_OK if successful, or an error code if an error occurs. If an
+** error does occur, the final value of *piRead is undefined.
+*/
+SQLITE_PRIVATE int sqlite3WalFindFrame(
+ Wal *pWal, /* WAL handle */
+ Pgno pgno, /* Database page number to read data for */
+ u32 *piRead /* OUT: Frame number (or zero) */
+){
+ u32 iRead = 0; /* If !=0, WAL frame to return data from */
+ u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
+ int iHash; /* Used to loop through N hash tables */
+ int iMinHash;
+
+ /* This routine is only be called from within a read transaction. */
+ assert( pWal->readLock>=0 || pWal->lockError );
+
+ /* If the "last page" field of the wal-index header snapshot is 0, then
+ ** no data will be read from the wal under any circumstances. Return early
+ ** in this case as an optimization. Likewise, if pWal->readLock==0,
+ ** then the WAL is ignored by the reader so return early, as if the
+ ** WAL were empty.
+ */
+ if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
+ *piRead = 0;
+ return SQLITE_OK;
+ }
+
+ /* Search the hash table or tables for an entry matching page number
+ ** pgno. Each iteration of the following for() loop searches one
+ ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
+ **
+ ** This code might run concurrently to the code in walIndexAppend()
+ ** that adds entries to the wal-index (and possibly to this hash
+ ** table). This means the value just read from the hash
+ ** slot (aHash[iKey]) may have been added before or after the
+ ** current read transaction was opened. Values added after the
+ ** read transaction was opened may have been written incorrectly -
+ ** i.e. these slots may contain garbage data. However, we assume
+ ** that any slots written before the current read transaction was
+ ** opened remain unmodified.
+ **
+ ** For the reasons above, the if(...) condition featured in the inner
+ ** loop of the following block is more stringent that would be required
+ ** if we had exclusive access to the hash-table:
+ **
+ ** (aPgno[iFrame]==pgno):
+ ** This condition filters out normal hash-table collisions.
+ **
+ ** (iFrame<=iLast):
+ ** This condition filters out entries that were added to the hash
+ ** table after the current read-transaction had started.
+ */
+ iMinHash = walFramePage(pWal->minFrame);
+ for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
+ WalHashLoc sLoc; /* Hash table location */
+ int iKey; /* Hash slot index */
+ int nCollide; /* Number of hash collisions remaining */
+ int rc; /* Error code */
+ u32 iH;
+
+ rc = walHashGet(pWal, iHash, &sLoc);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ nCollide = HASHTABLE_NSLOT;
+ iKey = walHash(pgno);
+ while( (iH = AtomicLoad(&sLoc.aHash[iKey]))!=0 ){
+ u32 iFrame = iH + sLoc.iZero;
+ if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH]==pgno ){
+ assert( iFrame>iRead || CORRUPT_DB );
+ iRead = iFrame;
+ }
+ if( (nCollide--)==0 ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+ iKey = walNextHash(iKey);
+ }
+ if( iRead ) break;
+ }
+
+#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
+ /* If expensive assert() statements are available, do a linear search
+ ** of the wal-index file content. Make sure the results agree with the
+ ** result obtained using the hash indexes above. */
+ {
+ u32 iRead2 = 0;
+ u32 iTest;
+ assert( pWal->bShmUnreliable || pWal->minFrame>0 );
+ for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
+ if( walFramePgno(pWal, iTest)==pgno ){
+ iRead2 = iTest;
+ break;
+ }
+ }
+ assert( iRead==iRead2 );
+ }
+#endif
+
+ *piRead = iRead;
+ return SQLITE_OK;
+}
+
+/*
+** Read the contents of frame iRead from the wal file into buffer pOut
+** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
+** error code otherwise.
+*/
+SQLITE_PRIVATE int sqlite3WalReadFrame(
+ Wal *pWal, /* WAL handle */
+ u32 iRead, /* Frame to read */
+ int nOut, /* Size of buffer pOut in bytes */
+ u8 *pOut /* Buffer to write page data to */
+){
+ int sz;
+ i64 iOffset;
+ sz = pWal->hdr.szPage;
+ sz = (sz&0xfe00) + ((sz&0x0001)<<16);
+ testcase( sz<=32768 );
+ testcase( sz>=65536 );
+ iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
+ /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
+ return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
+}
+
+/*
+** Return the size of the database in pages (or zero, if unknown).
+*/
+SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
+ if( pWal && ALWAYS(pWal->readLock>=0) ){
+ return pWal->hdr.nPage;
+ }
+ return 0;
+}
+
+
+/*
+** This function starts a write transaction on the WAL.
+**
+** A read transaction must have already been started by a prior call
+** to sqlite3WalBeginReadTransaction().
+**
+** If another thread or process has written into the database since
+** the read transaction was started, then it is not possible for this
+** thread to write as doing so would cause a fork. So this routine
+** returns SQLITE_BUSY in that case and no write transaction is started.
+**
+** There can only be a single writer active at a time.
+*/
+SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
+ int rc;
+
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+ /* If the write-lock is already held, then it was obtained before the
+ ** read-transaction was even opened, making this call a no-op.
+ ** Return early. */
+ if( pWal->writeLock ){
+ assert( !memcmp(&pWal->hdr,(void *)walIndexHdr(pWal),sizeof(WalIndexHdr)) );
+ return SQLITE_OK;
+ }
+#endif
+
+ /* Cannot start a write transaction without first holding a read
+ ** transaction. */
+ assert( pWal->readLock>=0 );
+ assert( pWal->writeLock==0 && pWal->iReCksum==0 );
+
+ if( pWal->readOnly ){
+ return SQLITE_READONLY;
+ }
+
+ /* Only one writer allowed at a time. Get the write lock. Return
+ ** SQLITE_BUSY if unable.
+ */
+ rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
+ if( rc ){
+ return rc;
+ }
+ pWal->writeLock = 1;
+
+ /* If another connection has written to the database file since the
+ ** time the read transaction on this connection was started, then
+ ** the write is disallowed.
+ */
+ if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
+ walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
+ pWal->writeLock = 0;
+ rc = SQLITE_BUSY_SNAPSHOT;
+ }
+
+ return rc;
+}
+
+/*
+** End a write transaction. The commit has already been done. This
+** routine merely releases the lock.
+*/
+SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
+ if( pWal->writeLock ){
+ walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
+ pWal->writeLock = 0;
+ pWal->iReCksum = 0;
+ pWal->truncateOnCommit = 0;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** If any data has been written (but not committed) to the log file, this
+** function moves the write-pointer back to the start of the transaction.
+**
+** Additionally, the callback function is invoked for each frame written
+** to the WAL since the start of the transaction. If the callback returns
+** other than SQLITE_OK, it is not invoked again and the error code is
+** returned to the caller.
+**
+** Otherwise, if the callback function does not return an error, this
+** function returns SQLITE_OK.
+*/
+SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
+ int rc = SQLITE_OK;
+ if( ALWAYS(pWal->writeLock) ){
+ Pgno iMax = pWal->hdr.mxFrame;
+ Pgno iFrame;
+
+ /* Restore the clients cache of the wal-index header to the state it
+ ** was in before the client began writing to the database.
+ */
+ memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
+
+ for(iFrame=pWal->hdr.mxFrame+1;
+ ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
+ iFrame++
+ ){
+ /* This call cannot fail. Unless the page for which the page number
+ ** is passed as the second argument is (a) in the cache and
+ ** (b) has an outstanding reference, then xUndo is either a no-op
+ ** (if (a) is false) or simply expels the page from the cache (if (b)
+ ** is false).
+ **
+ ** If the upper layer is doing a rollback, it is guaranteed that there
+ ** are no outstanding references to any page other than page 1. And
+ ** page 1 is never written to the log until the transaction is
+ ** committed. As a result, the call to xUndo may not fail.
+ */
+ assert( walFramePgno(pWal, iFrame)!=1 );
+ rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
+ }
+ if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
+ }
+ return rc;
+}
+
+/*
+** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
+** values. This function populates the array with values required to
+** "rollback" the write position of the WAL handle back to the current
+** point in the event of a savepoint rollback (via WalSavepointUndo()).
+*/
+SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
+ assert( pWal->writeLock );
+ aWalData[0] = pWal->hdr.mxFrame;
+ aWalData[1] = pWal->hdr.aFrameCksum[0];
+ aWalData[2] = pWal->hdr.aFrameCksum[1];
+ aWalData[3] = pWal->nCkpt;
+}
+
+/*
+** Move the write position of the WAL back to the point identified by
+** the values in the aWalData[] array. aWalData must point to an array
+** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
+** by a call to WalSavepoint().
+*/
+SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
+ int rc = SQLITE_OK;
+
+ assert( pWal->writeLock );
+ assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
+
+ if( aWalData[3]!=pWal->nCkpt ){
+ /* This savepoint was opened immediately after the write-transaction
+ ** was started. Right after that, the writer decided to wrap around
+ ** to the start of the log. Update the savepoint values to match.
+ */
+ aWalData[0] = 0;
+ aWalData[3] = pWal->nCkpt;
+ }
+
+ if( aWalData[0]<pWal->hdr.mxFrame ){
+ pWal->hdr.mxFrame = aWalData[0];
+ pWal->hdr.aFrameCksum[0] = aWalData[1];
+ pWal->hdr.aFrameCksum[1] = aWalData[2];
+ walCleanupHash(pWal);
+ }
+
+ return rc;
+}
+
+/*
+** This function is called just before writing a set of frames to the log
+** file (see sqlite3WalFrames()). It checks to see if, instead of appending
+** to the current log file, it is possible to overwrite the start of the
+** existing log file with the new frames (i.e. "reset" the log). If so,
+** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
+** unchanged.
+**
+** SQLITE_OK is returned if no error is encountered (regardless of whether
+** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
+** if an error occurs.
+*/
+static int walRestartLog(Wal *pWal){
+ int rc = SQLITE_OK;
+ int cnt;
+
+ if( pWal->readLock==0 ){
+ volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
+ assert( pInfo->nBackfill==pWal->hdr.mxFrame );
+ if( pInfo->nBackfill>0 ){
+ u32 salt1;
+ sqlite3_randomness(4, &salt1);
+ rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
+ if( rc==SQLITE_OK ){
+ /* If all readers are using WAL_READ_LOCK(0) (in other words if no
+ ** readers are currently using the WAL), then the transactions
+ ** frames will overwrite the start of the existing log. Update the
+ ** wal-index header to reflect this.
+ **
+ ** In theory it would be Ok to update the cache of the header only
+ ** at this point. But updating the actual wal-index header is also
+ ** safe and means there is no special case for sqlite3WalUndo()
+ ** to handle if this transaction is rolled back. */
+ walRestartHdr(pWal, salt1);
+ walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
+ }else if( rc!=SQLITE_BUSY ){
+ return rc;
+ }
+ }
+ walUnlockShared(pWal, WAL_READ_LOCK(0));
+ pWal->readLock = -1;
+ cnt = 0;
+ do{
+ int notUsed;
+ rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
+ }while( rc==WAL_RETRY );
+ assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
+ testcase( (rc&0xff)==SQLITE_IOERR );
+ testcase( rc==SQLITE_PROTOCOL );
+ testcase( rc==SQLITE_OK );
+ }
+ return rc;
+}
+
+/*
+** Information about the current state of the WAL file and where
+** the next fsync should occur - passed from sqlite3WalFrames() into
+** walWriteToLog().
+*/
+typedef struct WalWriter {
+ Wal *pWal; /* The complete WAL information */
+ sqlite3_file *pFd; /* The WAL file to which we write */
+ sqlite3_int64 iSyncPoint; /* Fsync at this offset */
+ int syncFlags; /* Flags for the fsync */
+ int szPage; /* Size of one page */
+} WalWriter;
+
+/*
+** Write iAmt bytes of content into the WAL file beginning at iOffset.
+** Do a sync when crossing the p->iSyncPoint boundary.
+**
+** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
+** first write the part before iSyncPoint, then sync, then write the
+** rest.
+*/
+static int walWriteToLog(
+ WalWriter *p, /* WAL to write to */
+ void *pContent, /* Content to be written */
+ int iAmt, /* Number of bytes to write */
+ sqlite3_int64 iOffset /* Start writing at this offset */
+){
+ int rc;
+ if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
+ int iFirstAmt = (int)(p->iSyncPoint - iOffset);
+ rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
+ if( rc ) return rc;
+ iOffset += iFirstAmt;
+ iAmt -= iFirstAmt;
+ pContent = (void*)(iFirstAmt + (char*)pContent);
+ assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
+ rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
+ if( iAmt==0 || rc ) return rc;
+ }
+ rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
+ return rc;
+}
+
+/*
+** Write out a single frame of the WAL
+*/
+static int walWriteOneFrame(
+ WalWriter *p, /* Where to write the frame */
+ PgHdr *pPage, /* The page of the frame to be written */
+ int nTruncate, /* The commit flag. Usually 0. >0 for commit */
+ sqlite3_int64 iOffset /* Byte offset at which to write */
+){
+ int rc; /* Result code from subfunctions */
+ void *pData; /* Data actually written */
+ u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
+ pData = pPage->pData;
+ walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
+ rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
+ if( rc ) return rc;
+ /* Write the page data */
+ rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
+ return rc;
+}
+
+/*
+** This function is called as part of committing a transaction within which
+** one or more frames have been overwritten. It updates the checksums for
+** all frames written to the wal file by the current transaction starting
+** with the earliest to have been overwritten.
+**
+** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
+*/
+static int walRewriteChecksums(Wal *pWal, u32 iLast){
+ const int szPage = pWal->szPage;/* Database page size */
+ int rc = SQLITE_OK; /* Return code */
+ u8 *aBuf; /* Buffer to load data from wal file into */
+ u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
+ u32 iRead; /* Next frame to read from wal file */
+ i64 iCksumOff;
+
+ aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
+ if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
+
+ /* Find the checksum values to use as input for the recalculating the
+ ** first checksum. If the first frame is frame 1 (implying that the current
+ ** transaction restarted the wal file), these values must be read from the
+ ** wal-file header. Otherwise, read them from the frame header of the
+ ** previous frame. */
+ assert( pWal->iReCksum>0 );
+ if( pWal->iReCksum==1 ){
+ iCksumOff = 24;
+ }else{
+ iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
+ }
+ rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
+ pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
+ pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
+
+ iRead = pWal->iReCksum;
+ pWal->iReCksum = 0;
+ for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
+ i64 iOff = walFrameOffset(iRead, szPage);
+ rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
+ if( rc==SQLITE_OK ){
+ u32 iPgno, nDbSize;
+ iPgno = sqlite3Get4byte(aBuf);
+ nDbSize = sqlite3Get4byte(&aBuf[4]);
+
+ walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
+ rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
+ }
+ }
+
+ sqlite3_free(aBuf);
+ return rc;
+}
+
+/*
+** Write a set of frames to the log. The caller must hold the write-lock
+** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
+*/
+SQLITE_PRIVATE int sqlite3WalFrames(
+ Wal *pWal, /* Wal handle to write to */
+ int szPage, /* Database page-size in bytes */
+ PgHdr *pList, /* List of dirty pages to write */
+ Pgno nTruncate, /* Database size after this commit */
+ int isCommit, /* True if this is a commit */
+ int sync_flags /* Flags to pass to OsSync() (or 0) */
+){
+ int rc; /* Used to catch return codes */
+ u32 iFrame; /* Next frame address */
+ PgHdr *p; /* Iterator to run through pList with. */
+ PgHdr *pLast = 0; /* Last frame in list */
+ int nExtra = 0; /* Number of extra copies of last page */
+ int szFrame; /* The size of a single frame */
+ i64 iOffset; /* Next byte to write in WAL file */
+ WalWriter w; /* The writer */
+ u32 iFirst = 0; /* First frame that may be overwritten */
+ WalIndexHdr *pLive; /* Pointer to shared header */
+
+ assert( pList );
+ assert( pWal->writeLock );
+
+ /* If this frame set completes a transaction, then nTruncate>0. If
+ ** nTruncate==0 then this frame set does not complete the transaction. */
+ assert( (isCommit!=0)==(nTruncate!=0) );
+
+#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
+ { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
+ WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
+ pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
+ }
+#endif
+
+ pLive = (WalIndexHdr*)walIndexHdr(pWal);
+ if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
+ iFirst = pLive->mxFrame+1;
+ }
+
+ /* See if it is possible to write these frames into the start of the
+ ** log file, instead of appending to it at pWal->hdr.mxFrame.
+ */
+ if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
+ return rc;
+ }
+
+ /* If this is the first frame written into the log, write the WAL
+ ** header to the start of the WAL file. See comments at the top of
+ ** this source file for a description of the WAL header format.
+ */
+ iFrame = pWal->hdr.mxFrame;
+ if( iFrame==0 ){
+ u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
+ u32 aCksum[2]; /* Checksum for wal-header */
+
+ sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
+ sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
+ sqlite3Put4byte(&aWalHdr[8], szPage);
+ sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
+ if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
+ memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
+ walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
+ sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
+ sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
+
+ pWal->szPage = szPage;
+ pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
+ pWal->hdr.aFrameCksum[0] = aCksum[0];
+ pWal->hdr.aFrameCksum[1] = aCksum[1];
+ pWal->truncateOnCommit = 1;
+
+ rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
+ WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+
+ /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
+ ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
+ ** an out-of-order write following a WAL restart could result in
+ ** database corruption. See the ticket:
+ **
+ ** https://sqlite.org/src/info/ff5be73dee
+ */
+ if( pWal->syncHeader ){
+ rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
+ if( rc ) return rc;
+ }
+ }
+ assert( (int)pWal->szPage==szPage );
+
+ /* Setup information needed to write frames into the WAL */
+ w.pWal = pWal;
+ w.pFd = pWal->pWalFd;
+ w.iSyncPoint = 0;
+ w.syncFlags = sync_flags;
+ w.szPage = szPage;
+ iOffset = walFrameOffset(iFrame+1, szPage);
+ szFrame = szPage + WAL_FRAME_HDRSIZE;
+
+ /* Write all frames into the log file exactly once */
+ for(p=pList; p; p=p->pDirty){
+ int nDbSize; /* 0 normally. Positive == commit flag */
+
+ /* Check if this page has already been written into the wal file by
+ ** the current transaction. If so, overwrite the existing frame and
+ ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
+ ** checksums must be recomputed when the transaction is committed. */
+ if( iFirst && (p->pDirty || isCommit==0) ){
+ u32 iWrite = 0;
+ VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
+ assert( rc==SQLITE_OK || iWrite==0 );
+ if( iWrite>=iFirst ){
+ i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
+ void *pData;
+ if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
+ pWal->iReCksum = iWrite;
+ }
+ pData = p->pData;
+ rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
+ if( rc ) return rc;
+ p->flags &= ~PGHDR_WAL_APPEND;
+ continue;
+ }
+ }
+
+ iFrame++;
+ assert( iOffset==walFrameOffset(iFrame, szPage) );
+ nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
+ rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
+ if( rc ) return rc;
+ pLast = p;
+ iOffset += szFrame;
+ p->flags |= PGHDR_WAL_APPEND;
+ }
+
+ /* Recalculate checksums within the wal file if required. */
+ if( isCommit && pWal->iReCksum ){
+ rc = walRewriteChecksums(pWal, iFrame);
+ if( rc ) return rc;
+ }
+
+ /* If this is the end of a transaction, then we might need to pad
+ ** the transaction and/or sync the WAL file.
+ **
+ ** Padding and syncing only occur if this set of frames complete a
+ ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
+ ** or synchronous==OFF, then no padding or syncing are needed.
+ **
+ ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
+ ** needed and only the sync is done. If padding is needed, then the
+ ** final frame is repeated (with its commit mark) until the next sector
+ ** boundary is crossed. Only the part of the WAL prior to the last
+ ** sector boundary is synced; the part of the last frame that extends
+ ** past the sector boundary is written after the sync.
+ */
+ if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
+ int bSync = 1;
+ if( pWal->padToSectorBoundary ){
+ int sectorSize = sqlite3SectorSize(pWal->pWalFd);
+ w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
+ bSync = (w.iSyncPoint==iOffset);
+ testcase( bSync );
+ while( iOffset<w.iSyncPoint ){
+ rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
+ if( rc ) return rc;
+ iOffset += szFrame;
+ nExtra++;
+ assert( pLast!=0 );
+ }
+ }
+ if( bSync ){
+ assert( rc==SQLITE_OK );
+ rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
+ }
+ }
+
+ /* If this frame set completes the first transaction in the WAL and
+ ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
+ ** journal size limit, if possible.
+ */
+ if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
+ i64 sz = pWal->mxWalSize;
+ if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
+ sz = walFrameOffset(iFrame+nExtra+1, szPage);
+ }
+ walLimitSize(pWal, sz);
+ pWal->truncateOnCommit = 0;
+ }
+
+ /* Append data to the wal-index. It is not necessary to lock the
+ ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
+ ** guarantees that there are no other writers, and no data that may
+ ** be in use by existing readers is being overwritten.
+ */
+ iFrame = pWal->hdr.mxFrame;
+ for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
+ if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
+ iFrame++;
+ rc = walIndexAppend(pWal, iFrame, p->pgno);
+ }
+ assert( pLast!=0 || nExtra==0 );
+ while( rc==SQLITE_OK && nExtra>0 ){
+ iFrame++;
+ nExtra--;
+ rc = walIndexAppend(pWal, iFrame, pLast->pgno);
+ }
+
+ if( rc==SQLITE_OK ){
+ /* Update the private copy of the header. */
+ pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
+ testcase( szPage<=32768 );
+ testcase( szPage>=65536 );
+ pWal->hdr.mxFrame = iFrame;
+ if( isCommit ){
+ pWal->hdr.iChange++;
+ pWal->hdr.nPage = nTruncate;
+ }
+ /* If this is a commit, update the wal-index header too. */
+ if( isCommit ){
+ walIndexWriteHdr(pWal);
+ pWal->iCallback = iFrame;
+ }
+ }
+
+ WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
+ return rc;
+}
+
+/*
+** This routine is called to implement sqlite3_wal_checkpoint() and
+** related interfaces.
+**
+** Obtain a CHECKPOINT lock and then backfill as much information as
+** we can from WAL into the database.
+**
+** If parameter xBusy is not NULL, it is a pointer to a busy-handler
+** callback. In this case this function runs a blocking checkpoint.
+*/
+SQLITE_PRIVATE int sqlite3WalCheckpoint(
+ Wal *pWal, /* Wal connection */
+ sqlite3 *db, /* Check this handle's interrupt flag */
+ int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
+ int (*xBusy)(void*), /* Function to call when busy */
+ void *pBusyArg, /* Context argument for xBusyHandler */
+ int sync_flags, /* Flags to sync db file with (or 0) */
+ int nBuf, /* Size of temporary buffer */
+ u8 *zBuf, /* Temporary buffer to use */
+ int *pnLog, /* OUT: Number of frames in WAL */
+ int *pnCkpt /* OUT: Number of backfilled frames in WAL */
+){
+ int rc; /* Return code */
+ int isChanged = 0; /* True if a new wal-index header is loaded */
+ int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
+ int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
+
+ assert( pWal->ckptLock==0 );
+ assert( pWal->writeLock==0 );
+
+ /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
+ ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
+ assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
+
+ if( pWal->readOnly ) return SQLITE_READONLY;
+ WALTRACE(("WAL%p: checkpoint begins\n", pWal));
+
+ /* Enable blocking locks, if possible. If blocking locks are successfully
+ ** enabled, set xBusy2=0 so that the busy-handler is never invoked. */
+ sqlite3WalDb(pWal, db);
+ (void)walEnableBlocking(pWal);
+
+ /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
+ ** "checkpoint" lock on the database file.
+ ** EVIDENCE-OF: R-10421-19736 If any other process is running a
+ ** checkpoint operation at the same time, the lock cannot be obtained and
+ ** SQLITE_BUSY is returned.
+ ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
+ ** it will not be invoked in this case.
+ */
+ rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
+ testcase( rc==SQLITE_BUSY );
+ testcase( rc!=SQLITE_OK && xBusy2!=0 );
+ if( rc==SQLITE_OK ){
+ pWal->ckptLock = 1;
+
+ /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
+ ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
+ ** file.
+ **
+ ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
+ ** immediately, and a busy-handler is configured, it is invoked and the
+ ** writer lock retried until either the busy-handler returns 0 or the
+ ** lock is successfully obtained.
+ */
+ if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
+ rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, 1);
+ if( rc==SQLITE_OK ){
+ pWal->writeLock = 1;
+ }else if( rc==SQLITE_BUSY ){
+ eMode2 = SQLITE_CHECKPOINT_PASSIVE;
+ xBusy2 = 0;
+ rc = SQLITE_OK;
+ }
+ }
+ }
+
+
+ /* Read the wal-index header. */
+ if( rc==SQLITE_OK ){
+ walDisableBlocking(pWal);
+ rc = walIndexReadHdr(pWal, &isChanged);
+ (void)walEnableBlocking(pWal);
+ if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
+ sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
+ }
+ }
+
+ /* Copy data from the log to the database file. */
+ if( rc==SQLITE_OK ){
+
+ if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
+ rc = SQLITE_CORRUPT_BKPT;
+ }else{
+ rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
+ }
+
+ /* If no error occurred, set the output variables. */
+ if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
+ if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
+ if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
+ }
+ }
+
+ if( isChanged ){
+ /* If a new wal-index header was loaded before the checkpoint was
+ ** performed, then the pager-cache associated with pWal is now
+ ** out of date. So zero the cached wal-index header to ensure that
+ ** next time the pager opens a snapshot on this database it knows that
+ ** the cache needs to be reset.
+ */
+ memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
+ }
+
+ walDisableBlocking(pWal);
+ sqlite3WalDb(pWal, 0);
+
+ /* Release the locks. */
+ sqlite3WalEndWriteTransaction(pWal);
+ if( pWal->ckptLock ){
+ walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
+ pWal->ckptLock = 0;
+ }
+ WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+ if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
+#endif
+ return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
+}
+
+/* Return the value to pass to a sqlite3_wal_hook callback, the
+** number of frames in the WAL at the point of the last commit since
+** sqlite3WalCallback() was called. If no commits have occurred since
+** the last call, then return 0.
+*/
+SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
+ u32 ret = 0;
+ if( pWal ){
+ ret = pWal->iCallback;
+ pWal->iCallback = 0;
+ }
+ return (int)ret;
+}
+
+/*
+** This function is called to change the WAL subsystem into or out
+** of locking_mode=EXCLUSIVE.
+**
+** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
+** into locking_mode=NORMAL. This means that we must acquire a lock
+** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
+** or if the acquisition of the lock fails, then return 0. If the
+** transition out of exclusive-mode is successful, return 1. This
+** operation must occur while the pager is still holding the exclusive
+** lock on the main database file.
+**
+** If op is one, then change from locking_mode=NORMAL into
+** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
+** be released. Return 1 if the transition is made and 0 if the
+** WAL is already in exclusive-locking mode - meaning that this
+** routine is a no-op. The pager must already hold the exclusive lock
+** on the main database file before invoking this operation.
+**
+** If op is negative, then do a dry-run of the op==1 case but do
+** not actually change anything. The pager uses this to see if it
+** should acquire the database exclusive lock prior to invoking
+** the op==1 case.
+*/
+SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
+ int rc;
+ assert( pWal->writeLock==0 );
+ assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
+
+ /* pWal->readLock is usually set, but might be -1 if there was a
+ ** prior error while attempting to acquire are read-lock. This cannot
+ ** happen if the connection is actually in exclusive mode (as no xShmLock
+ ** locks are taken in this case). Nor should the pager attempt to
+ ** upgrade to exclusive-mode following such an error.
+ */
+ assert( pWal->readLock>=0 || pWal->lockError );
+ assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
+
+ if( op==0 ){
+ if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
+ pWal->exclusiveMode = WAL_NORMAL_MODE;
+ if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
+ pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
+ }
+ rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
+ }else{
+ /* Already in locking_mode=NORMAL */
+ rc = 0;
+ }
+ }else if( op>0 ){
+ assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
+ assert( pWal->readLock>=0 );
+ walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
+ pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
+ rc = 1;
+ }else{
+ rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
+ }
+ return rc;
+}
+
+/*
+** Return true if the argument is non-NULL and the WAL module is using
+** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
+** WAL module is using shared-memory, return false.
+*/
+SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
+ return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
+}
+
+#ifdef SQLITE_ENABLE_SNAPSHOT
+/* Create a snapshot object. The content of a snapshot is opaque to
+** every other subsystem, so the WAL module can put whatever it needs
+** in the object.
+*/
+SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
+ int rc = SQLITE_OK;
+ WalIndexHdr *pRet;
+ static const u32 aZero[4] = { 0, 0, 0, 0 };
+
+ assert( pWal->readLock>=0 && pWal->writeLock==0 );
+
+ if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
+ *ppSnapshot = 0;
+ return SQLITE_ERROR;
+ }
+ pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
+ if( pRet==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ }else{
+ memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
+ *ppSnapshot = (sqlite3_snapshot*)pRet;
+ }
+
+ return rc;
+}
+
+/* Try to open on pSnapshot when the next read-transaction starts
+*/
+SQLITE_PRIVATE void sqlite3WalSnapshotOpen(
+ Wal *pWal,
+ sqlite3_snapshot *pSnapshot
+){
+ pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
+}
+
+/*
+** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
+** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
+*/
+SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
+ WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
+ WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
+
+ /* aSalt[0] is a copy of the value stored in the wal file header. It
+ ** is incremented each time the wal file is restarted. */
+ if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
+ if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
+ if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
+ if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
+ return 0;
+}
+
+/*
+** The caller currently has a read transaction open on the database.
+** This function takes a SHARED lock on the CHECKPOINTER slot and then
+** checks if the snapshot passed as the second argument is still
+** available. If so, SQLITE_OK is returned.
+**
+** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
+** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
+** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
+** lock is released before returning.
+*/
+SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){
+ int rc;
+ rc = walLockShared(pWal, WAL_CKPT_LOCK);
+ if( rc==SQLITE_OK ){
+ WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot;
+ if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
+ || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted
+ ){
+ rc = SQLITE_ERROR_SNAPSHOT;
+ walUnlockShared(pWal, WAL_CKPT_LOCK);
+ }
+ }
+ return rc;
+}
+
+/*
+** Release a lock obtained by an earlier successful call to
+** sqlite3WalSnapshotCheck().
+*/
+SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal){
+ assert( pWal );
+ walUnlockShared(pWal, WAL_CKPT_LOCK);
+}
+
+
+#endif /* SQLITE_ENABLE_SNAPSHOT */
+
+#ifdef SQLITE_ENABLE_ZIPVFS
+/*
+** If the argument is not NULL, it points to a Wal object that holds a
+** read-lock. This function returns the database page-size if it is known,
+** or zero if it is not (or if pWal is NULL).
+*/
+SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
+ assert( pWal==0 || pWal->readLock>=0 );
+ return (pWal ? pWal->szPage : 0);
+}
+#endif
+
+/* Return the sqlite3_file object for the WAL file
+*/
+SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
+ return pWal->pWalFd;
+}
+
+#endif /* #ifndef SQLITE_OMIT_WAL */
+
+/************** End of wal.c *************************************************/
+/************** Begin file btmutex.c *****************************************/
+/*
+** 2007 August 27
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains code used to implement mutexes on Btree objects.
+** This code really belongs in btree.c. But btree.c is getting too
+** big and we want to break it down some. This packaged seemed like
+** a good breakout.
+*/
+/************** Include btreeInt.h in the middle of btmutex.c ****************/
+/************** Begin file btreeInt.h ****************************************/
+/*
+** 2004 April 6
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file implements an external (disk-based) database using BTrees.
+** For a detailed discussion of BTrees, refer to
+**
+** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
+** "Sorting And Searching", pages 473-480. Addison-Wesley
+** Publishing Company, Reading, Massachusetts.
+**
+** The basic idea is that each page of the file contains N database
+** entries and N+1 pointers to subpages.
+**
+** ----------------------------------------------------------------
+** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
+** ----------------------------------------------------------------
+**
+** All of the keys on the page that Ptr(0) points to have values less
+** than Key(0). All of the keys on page Ptr(1) and its subpages have
+** values greater than Key(0) and less than Key(1). All of the keys
+** on Ptr(N) and its subpages have values greater than Key(N-1). And
+** so forth.
+**
+** Finding a particular key requires reading O(log(M)) pages from the
+** disk where M is the number of entries in the tree.
+**
+** In this implementation, a single file can hold one or more separate
+** BTrees. Each BTree is identified by the index of its root page. The
+** key and data for any entry are combined to form the "payload". A
+** fixed amount of payload can be carried directly on the database
+** page. If the payload is larger than the preset amount then surplus
+** bytes are stored on overflow pages. The payload for an entry
+** and the preceding pointer are combined to form a "Cell". Each
+** page has a small header which contains the Ptr(N) pointer and other
+** information such as the size of key and data.
+**
+** FORMAT DETAILS
+**
+** The file is divided into pages. The first page is called page 1,
+** the second is page 2, and so forth. A page number of zero indicates
+** "no such page". The page size can be any power of 2 between 512 and 65536.
+** Each page can be either a btree page, a freelist page, an overflow
+** page, or a pointer-map page.
+**
+** The first page is always a btree page. The first 100 bytes of the first
+** page contain a special header (the "file header") that describes the file.
+** The format of the file header is as follows:
+**
+** OFFSET SIZE DESCRIPTION
+** 0 16 Header string: "SQLite format 3\000"
+** 16 2 Page size in bytes. (1 means 65536)
+** 18 1 File format write version
+** 19 1 File format read version
+** 20 1 Bytes of unused space at the end of each page
+** 21 1 Max embedded payload fraction (must be 64)
+** 22 1 Min embedded payload fraction (must be 32)
+** 23 1 Min leaf payload fraction (must be 32)
+** 24 4 File change counter
+** 28 4 Reserved for future use
+** 32 4 First freelist page
+** 36 4 Number of freelist pages in the file
+** 40 60 15 4-byte meta values passed to higher layers
+**
+** 40 4 Schema cookie
+** 44 4 File format of schema layer
+** 48 4 Size of page cache
+** 52 4 Largest root-page (auto/incr_vacuum)
+** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
+** 60 4 User version
+** 64 4 Incremental vacuum mode
+** 68 4 Application-ID
+** 72 20 unused
+** 92 4 The version-valid-for number
+** 96 4 SQLITE_VERSION_NUMBER
+**
+** All of the integer values are big-endian (most significant byte first).
+**
+** The file change counter is incremented when the database is changed
+** This counter allows other processes to know when the file has changed
+** and thus when they need to flush their cache.
+**
+** The max embedded payload fraction is the amount of the total usable
+** space in a page that can be consumed by a single cell for standard
+** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
+** is to limit the maximum cell size so that at least 4 cells will fit
+** on one page. Thus the default max embedded payload fraction is 64.
+**
+** If the payload for a cell is larger than the max payload, then extra
+** payload is spilled to overflow pages. Once an overflow page is allocated,
+** as many bytes as possible are moved into the overflow pages without letting
+** the cell size drop below the min embedded payload fraction.
+**
+** The min leaf payload fraction is like the min embedded payload fraction
+** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
+** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
+** not specified in the header.
+**
+** Each btree pages is divided into three sections: The header, the
+** cell pointer array, and the cell content area. Page 1 also has a 100-byte
+** file header that occurs before the page header.
+**
+** |----------------|
+** | file header | 100 bytes. Page 1 only.
+** |----------------|
+** | page header | 8 bytes for leaves. 12 bytes for interior nodes
+** |----------------|
+** | cell pointer | | 2 bytes per cell. Sorted order.
+** | array | | Grows downward
+** | | v
+** |----------------|
+** | unallocated |
+** | space |
+** |----------------| ^ Grows upwards
+** | cell content | | Arbitrary order interspersed with freeblocks.
+** | area | | and free space fragments.
+** |----------------|
+**
+** The page headers looks like this:
+**
+** OFFSET SIZE DESCRIPTION
+** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
+** 1 2 byte offset to the first freeblock
+** 3 2 number of cells on this page
+** 5 2 first byte of the cell content area
+** 7 1 number of fragmented free bytes
+** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
+**
+** The flags define the format of this btree page. The leaf flag means that
+** this page has no children. The zerodata flag means that this page carries
+** only keys and no data. The intkey flag means that the key is an integer
+** which is stored in the key size entry of the cell header rather than in
+** the payload area.
+**
+** The cell pointer array begins on the first byte after the page header.
+** The cell pointer array contains zero or more 2-byte numbers which are
+** offsets from the beginning of the page to the cell content in the cell
+** content area. The cell pointers occur in sorted order. The system strives
+** to keep free space after the last cell pointer so that new cells can
+** be easily added without having to defragment the page.
+**
+** Cell content is stored at the very end of the page and grows toward the
+** beginning of the page.
+**
+** Unused space within the cell content area is collected into a linked list of
+** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
+** to the first freeblock is given in the header. Freeblocks occur in
+** increasing order. Because a freeblock must be at least 4 bytes in size,
+** any group of 3 or fewer unused bytes in the cell content area cannot
+** exist on the freeblock chain. A group of 3 or fewer free bytes is called
+** a fragment. The total number of bytes in all fragments is recorded.
+** in the page header at offset 7.
+**
+** SIZE DESCRIPTION
+** 2 Byte offset of the next freeblock
+** 2 Bytes in this freeblock
+**
+** Cells are of variable length. Cells are stored in the cell content area at
+** the end of the page. Pointers to the cells are in the cell pointer array
+** that immediately follows the page header. Cells is not necessarily
+** contiguous or in order, but cell pointers are contiguous and in order.
+**
+** Cell content makes use of variable length integers. A variable
+** length integer is 1 to 9 bytes where the lower 7 bits of each
+** byte are used. The integer consists of all bytes that have bit 8 set and
+** the first byte with bit 8 clear. The most significant byte of the integer
+** appears first. A variable-length integer may not be more than 9 bytes long.
+** As a special case, all 8 bytes of the 9th byte are used as data. This
+** allows a 64-bit integer to be encoded in 9 bytes.
+**
+** 0x00 becomes 0x00000000
+** 0x7f becomes 0x0000007f
+** 0x81 0x00 becomes 0x00000080
+** 0x82 0x00 becomes 0x00000100
+** 0x80 0x7f becomes 0x0000007f
+** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
+** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
+**
+** Variable length integers are used for rowids and to hold the number of
+** bytes of key and data in a btree cell.
+**
+** The content of a cell looks like this:
+**
+** SIZE DESCRIPTION
+** 4 Page number of the left child. Omitted if leaf flag is set.
+** var Number of bytes of data. Omitted if the zerodata flag is set.
+** var Number of bytes of key. Or the key itself if intkey flag is set.
+** * Payload
+** 4 First page of the overflow chain. Omitted if no overflow
+**
+** Overflow pages form a linked list. Each page except the last is completely
+** filled with data (pagesize - 4 bytes). The last page can have as little
+** as 1 byte of data.
+**
+** SIZE DESCRIPTION
+** 4 Page number of next overflow page
+** * Data
+**
+** Freelist pages come in two subtypes: trunk pages and leaf pages. The
+** file header points to the first in a linked list of trunk page. Each trunk
+** page points to multiple leaf pages. The content of a leaf page is
+** unspecified. A trunk page looks like this:
+**
+** SIZE DESCRIPTION
+** 4 Page number of next trunk page
+** 4 Number of leaf pointers on this page
+** * zero or more pages numbers of leaves
+*/
+/* #include "sqliteInt.h" */
+
+
+/* The following value is the maximum cell size assuming a maximum page
+** size give above.
+*/
+#define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
+
+/* The maximum number of cells on a single page of the database. This
+** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
+** plus 2 bytes for the index to the cell in the page header). Such
+** small cells will be rare, but they are possible.
+*/
+#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
+
+/* Forward declarations */
+typedef struct MemPage MemPage;
+typedef struct BtLock BtLock;
+typedef struct CellInfo CellInfo;
+
+/*
+** This is a magic string that appears at the beginning of every
+** SQLite database in order to identify the file as a real database.
+**
+** You can change this value at compile-time by specifying a
+** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
+** header must be exactly 16 bytes including the zero-terminator so
+** the string itself should be 15 characters long. If you change
+** the header, then your custom library will not be able to read
+** databases generated by the standard tools and the standard tools
+** will not be able to read databases created by your custom library.
+*/
+#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
+# define SQLITE_FILE_HEADER "SQLite format 3"
+#endif
+
+/*
+** Page type flags. An ORed combination of these flags appear as the
+** first byte of on-disk image of every BTree page.
+*/
+#define PTF_INTKEY 0x01
+#define PTF_ZERODATA 0x02
+#define PTF_LEAFDATA 0x04
+#define PTF_LEAF 0x08
+
+/*
+** An instance of this object stores information about each a single database
+** page that has been loaded into memory. The information in this object
+** is derived from the raw on-disk page content.
+**
+** As each database page is loaded into memory, the pager allocats an
+** instance of this object and zeros the first 8 bytes. (This is the
+** "extra" information associated with each page of the pager.)
+**
+** Access to all fields of this structure is controlled by the mutex
+** stored in MemPage.pBt->mutex.
+*/
+struct MemPage {
+ u8 isInit; /* True if previously initialized. MUST BE FIRST! */
+ u8 bBusy; /* Prevent endless loops on corrupt database files */
+ u8 intKey; /* True if table b-trees. False for index b-trees */
+ u8 intKeyLeaf; /* True if the leaf of an intKey table */
+ Pgno pgno; /* Page number for this page */
+ /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
+ ** is allocated. All fields that follow must be initialized before use */
+ u8 leaf; /* True if a leaf page */
+ u8 hdrOffset; /* 100 for page 1. 0 otherwise */
+ u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
+ u8 max1bytePayload; /* min(maxLocal,127) */
+ u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
+ u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
+ u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
+ u16 cellOffset; /* Index in aData of first cell pointer */
+ int nFree; /* Number of free bytes on the page. -1 for unknown */
+ u16 nCell; /* Number of cells on this page, local and ovfl */
+ u16 maskPage; /* Mask for page offset */
+ u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th
+ ** non-overflow cell */
+ u8 *apOvfl[4]; /* Pointers to the body of overflow cells */
+ BtShared *pBt; /* Pointer to BtShared that this page is part of */
+ u8 *aData; /* Pointer to disk image of the page data */
+ u8 *aDataEnd; /* One byte past the end of usable data */
+ u8 *aCellIdx; /* The cell index area */
+ u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
+ DbPage *pDbPage; /* Pager page handle */
+ u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
+ void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
+};
+
+/*
+** A linked list of the following structures is stored at BtShared.pLock.
+** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
+** is opened on the table with root page BtShared.iTable. Locks are removed
+** from this list when a transaction is committed or rolled back, or when
+** a btree handle is closed.
+*/
+struct BtLock {
+ Btree *pBtree; /* Btree handle holding this lock */
+ Pgno iTable; /* Root page of table */
+ u8 eLock; /* READ_LOCK or WRITE_LOCK */
+ BtLock *pNext; /* Next in BtShared.pLock list */
+};
+
+/* Candidate values for BtLock.eLock */
+#define READ_LOCK 1
+#define WRITE_LOCK 2
+
+/* A Btree handle
+**
+** A database connection contains a pointer to an instance of
+** this object for every database file that it has open. This structure
+** is opaque to the database connection. The database connection cannot
+** see the internals of this structure and only deals with pointers to
+** this structure.
+**
+** For some database files, the same underlying database cache might be
+** shared between multiple connections. In that case, each connection
+** has it own instance of this object. But each instance of this object
+** points to the same BtShared object. The database cache and the
+** schema associated with the database file are all contained within
+** the BtShared object.
+**
+** All fields in this structure are accessed under sqlite3.mutex.
+** The pBt pointer itself may not be changed while there exists cursors
+** in the referenced BtShared that point back to this Btree since those
+** cursors have to go through this Btree to find their BtShared and
+** they often do so without holding sqlite3.mutex.
+*/
+struct Btree {
+ sqlite3 *db; /* The database connection holding this btree */
+ BtShared *pBt; /* Sharable content of this btree */
+ u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
+ u8 sharable; /* True if we can share pBt with another db */
+ u8 locked; /* True if db currently has pBt locked */
+ u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
+ int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
+ int nBackup; /* Number of backup operations reading this btree */
+ u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
+ Btree *pNext; /* List of other sharable Btrees from the same db */
+ Btree *pPrev; /* Back pointer of the same list */
+#ifdef SQLITE_DEBUG
+ u64 nSeek; /* Calls to sqlite3BtreeMovetoUnpacked() */
+#endif
+#ifndef SQLITE_OMIT_SHARED_CACHE
+ BtLock lock; /* Object used to lock page 1 */
+#endif
+};
+
+/*
+** Btree.inTrans may take one of the following values.
+**
+** If the shared-data extension is enabled, there may be multiple users
+** of the Btree structure. At most one of these may open a write transaction,
+** but any number may have active read transactions.
+**
+** These values must match SQLITE_TXN_NONE, SQLITE_TXN_READ, and
+** SQLITE_TXN_WRITE
+*/
+#define TRANS_NONE 0
+#define TRANS_READ 1
+#define TRANS_WRITE 2
+
+#if TRANS_NONE!=SQLITE_TXN_NONE
+# error wrong numeric code for no-transaction
+#endif
+#if TRANS_READ!=SQLITE_TXN_READ
+# error wrong numeric code for read-transaction
+#endif
+#if TRANS_WRITE!=SQLITE_TXN_WRITE
+# error wrong numeric code for write-transaction
+#endif
+
+
+/*
+** An instance of this object represents a single database file.
+**
+** A single database file can be in use at the same time by two
+** or more database connections. When two or more connections are
+** sharing the same database file, each connection has it own
+** private Btree object for the file and each of those Btrees points
+** to this one BtShared object. BtShared.nRef is the number of
+** connections currently sharing this database file.
+**
+** Fields in this structure are accessed under the BtShared.mutex
+** mutex, except for nRef and pNext which are accessed under the
+** global SQLITE_MUTEX_STATIC_MAIN mutex. The pPager field
+** may not be modified once it is initially set as long as nRef>0.
+** The pSchema field may be set once under BtShared.mutex and
+** thereafter is unchanged as long as nRef>0.
+**
+** isPending:
+**
+** If a BtShared client fails to obtain a write-lock on a database
+** table (because there exists one or more read-locks on the table),
+** the shared-cache enters 'pending-lock' state and isPending is
+** set to true.
+**
+** The shared-cache leaves the 'pending lock' state when either of
+** the following occur:
+**
+** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
+** 2) The number of locks held by other connections drops to zero.
+**
+** while in the 'pending-lock' state, no connection may start a new
+** transaction.
+**
+** This feature is included to help prevent writer-starvation.
+*/
+struct BtShared {
+ Pager *pPager; /* The page cache */
+ sqlite3 *db; /* Database connection currently using this Btree */
+ BtCursor *pCursor; /* A list of all open cursors */
+ MemPage *pPage1; /* First page of the database */
+ u8 openFlags; /* Flags to sqlite3BtreeOpen() */
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ u8 autoVacuum; /* True if auto-vacuum is enabled */
+ u8 incrVacuum; /* True if incr-vacuum is enabled */
+ u8 bDoTruncate; /* True to truncate db on commit */
+#endif
+ u8 inTransaction; /* Transaction state */
+ u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
+ u8 nReserveWanted; /* Desired number of extra bytes per page */
+ u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
+ u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
+ u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
+ u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
+ u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
+ u32 pageSize; /* Total number of bytes on a page */
+ u32 usableSize; /* Number of usable bytes on each page */
+ int nTransaction; /* Number of open transactions (read + write) */
+ u32 nPage; /* Number of pages in the database */
+ void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
+ void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
+ sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
+ Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
+#ifndef SQLITE_OMIT_SHARED_CACHE
+ int nRef; /* Number of references to this structure */
+ BtShared *pNext; /* Next on a list of sharable BtShared structs */
+ BtLock *pLock; /* List of locks held on this shared-btree struct */
+ Btree *pWriter; /* Btree with currently open write transaction */
+#endif
+ u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
+};
+
+/*
+** Allowed values for BtShared.btsFlags
+*/
+#define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
+#define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
+#define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
+#define BTS_OVERWRITE 0x0008 /* Overwrite deleted content with zeros */
+#define BTS_FAST_SECURE 0x000c /* Combination of the previous two */
+#define BTS_INITIALLY_EMPTY 0x0010 /* Database was empty at trans start */
+#define BTS_NO_WAL 0x0020 /* Do not open write-ahead-log files */
+#define BTS_EXCLUSIVE 0x0040 /* pWriter has an exclusive lock */
+#define BTS_PENDING 0x0080 /* Waiting for read-locks to clear */
+
+/*
+** An instance of the following structure is used to hold information
+** about a cell. The parseCellPtr() function fills in this structure
+** based on information extract from the raw disk page.
+*/
+struct CellInfo {
+ i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
+ u8 *pPayload; /* Pointer to the start of payload */
+ u32 nPayload; /* Bytes of payload */
+ u16 nLocal; /* Amount of payload held locally, not on overflow */
+ u16 nSize; /* Size of the cell content on the main b-tree page */
+};
+
+/*
+** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
+** this will be declared corrupt. This value is calculated based on a
+** maximum database size of 2^31 pages a minimum fanout of 2 for a
+** root-node and 3 for all other internal nodes.
+**
+** If a tree that appears to be taller than this is encountered, it is
+** assumed that the database is corrupt.
+*/
+#define BTCURSOR_MAX_DEPTH 20
+
+/*
+** A cursor is a pointer to a particular entry within a particular
+** b-tree within a database file.
+**
+** The entry is identified by its MemPage and the index in
+** MemPage.aCell[] of the entry.
+**
+** A single database file can be shared by two more database connections,
+** but cursors cannot be shared. Each cursor is associated with a
+** particular database connection identified BtCursor.pBtree.db.
+**
+** Fields in this structure are accessed under the BtShared.mutex
+** found at self->pBt->mutex.
+**
+** skipNext meaning:
+** The meaning of skipNext depends on the value of eState:
+**
+** eState Meaning of skipNext
+** VALID skipNext is meaningless and is ignored
+** INVALID skipNext is meaningless and is ignored
+** SKIPNEXT sqlite3BtreeNext() is a no-op if skipNext>0 and
+** sqlite3BtreePrevious() is no-op if skipNext<0.
+** REQUIRESEEK restoreCursorPosition() restores the cursor to
+** eState=SKIPNEXT if skipNext!=0
+** FAULT skipNext holds the cursor fault error code.
+*/
+struct BtCursor {
+ u8 eState; /* One of the CURSOR_XXX constants (see below) */
+ u8 curFlags; /* zero or more BTCF_* flags defined below */
+ u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
+ u8 hints; /* As configured by CursorSetHints() */
+ int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
+ ** Error code if eState==CURSOR_FAULT */
+ Btree *pBtree; /* The Btree to which this cursor belongs */
+ Pgno *aOverflow; /* Cache of overflow page locations */
+ void *pKey; /* Saved key that was cursor last known position */
+ /* All fields above are zeroed when the cursor is allocated. See
+ ** sqlite3BtreeCursorZero(). Fields that follow must be manually
+ ** initialized. */
+#define BTCURSOR_FIRST_UNINIT pBt /* Name of first uninitialized field */
+ BtShared *pBt; /* The BtShared this cursor points to */
+ BtCursor *pNext; /* Forms a linked list of all cursors */
+ CellInfo info; /* A parse of the cell we are pointing at */
+ i64 nKey; /* Size of pKey, or last integer key */
+ Pgno pgnoRoot; /* The root page of this tree */
+ i8 iPage; /* Index of current page in apPage */
+ u8 curIntKey; /* Value of apPage[0]->intKey */
+ u16 ix; /* Current index for apPage[iPage] */
+ u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */
+ struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */
+ MemPage *pPage; /* Current page */
+ MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
+};
+
+/*
+** Legal values for BtCursor.curFlags
+*/
+#define BTCF_WriteFlag 0x01 /* True if a write cursor */
+#define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
+#define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
+#define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
+#define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
+#define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
+#define BTCF_Pinned 0x40 /* Cursor is busy and cannot be moved */
+
+/*
+** Potential values for BtCursor.eState.
+**
+** CURSOR_INVALID:
+** Cursor does not point to a valid entry. This can happen (for example)
+** because the table is empty or because BtreeCursorFirst() has not been
+** called.
+**
+** CURSOR_VALID:
+** Cursor points to a valid entry. getPayload() etc. may be called.
+**
+** CURSOR_SKIPNEXT:
+** Cursor is valid except that the Cursor.skipNext field is non-zero
+** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
+** operation should be a no-op.
+**
+** CURSOR_REQUIRESEEK:
+** The table that this cursor was opened on still exists, but has been
+** modified since the cursor was last used. The cursor position is saved
+** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
+** this state, restoreCursorPosition() can be called to attempt to
+** seek the cursor to the saved position.
+**
+** CURSOR_FAULT:
+** An unrecoverable error (an I/O error or a malloc failure) has occurred
+** on a different connection that shares the BtShared cache with this
+** cursor. The error has left the cache in an inconsistent state.
+** Do nothing else with this cursor. Any attempt to use the cursor
+** should return the error code stored in BtCursor.skipNext
+*/
+#define CURSOR_VALID 0
+#define CURSOR_INVALID 1
+#define CURSOR_SKIPNEXT 2
+#define CURSOR_REQUIRESEEK 3
+#define CURSOR_FAULT 4
+
+/*
+** The database page the PENDING_BYTE occupies. This page is never used.
+*/
+# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
+
+/*
+** These macros define the location of the pointer-map entry for a
+** database page. The first argument to each is the number of usable
+** bytes on each page of the database (often 1024). The second is the
+** page number to look up in the pointer map.
+**
+** PTRMAP_PAGENO returns the database page number of the pointer-map
+** page that stores the required pointer. PTRMAP_PTROFFSET returns
+** the offset of the requested map entry.
+**
+** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
+** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
+** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
+** this test.
+*/
+#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
+#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
+#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
+
+/*
+** The pointer map is a lookup table that identifies the parent page for
+** each child page in the database file. The parent page is the page that
+** contains a pointer to the child. Every page in the database contains
+** 0 or 1 parent pages. (In this context 'database page' refers
+** to any page that is not part of the pointer map itself.) Each pointer map
+** entry consists of a single byte 'type' and a 4 byte parent page number.
+** The PTRMAP_XXX identifiers below are the valid types.
+**
+** The purpose of the pointer map is to facility moving pages from one
+** position in the file to another as part of autovacuum. When a page
+** is moved, the pointer in its parent must be updated to point to the
+** new location. The pointer map is used to locate the parent page quickly.
+**
+** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
+** used in this case.
+**
+** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
+** is not used in this case.
+**
+** PTRMAP_OVERFLOW1: The database page is the first page in a list of
+** overflow pages. The page number identifies the page that
+** contains the cell with a pointer to this overflow page.
+**
+** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
+** overflow pages. The page-number identifies the previous
+** page in the overflow page list.
+**
+** PTRMAP_BTREE: The database page is a non-root btree page. The page number
+** identifies the parent page in the btree.
+*/
+#define PTRMAP_ROOTPAGE 1
+#define PTRMAP_FREEPAGE 2
+#define PTRMAP_OVERFLOW1 3
+#define PTRMAP_OVERFLOW2 4
+#define PTRMAP_BTREE 5
+
+/* A bunch of assert() statements to check the transaction state variables
+** of handle p (type Btree*) are internally consistent.
+*/
+#define btreeIntegrity(p) \
+ assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
+ assert( p->pBt->inTransaction>=p->inTrans );
+
+
+/*
+** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
+** if the database supports auto-vacuum or not. Because it is used
+** within an expression that is an argument to another macro
+** (sqliteMallocRaw), it is not possible to use conditional compilation.
+** So, this macro is defined instead.
+*/
+#ifndef SQLITE_OMIT_AUTOVACUUM
+#define ISAUTOVACUUM (pBt->autoVacuum)
+#else
+#define ISAUTOVACUUM 0
+#endif
+
+
+/*
+** This structure is passed around through all the sanity checking routines
+** in order to keep track of some global state information.
+**
+** The aRef[] array is allocated so that there is 1 bit for each page in
+** the database. As the integrity-check proceeds, for each page used in
+** the database the corresponding bit is set. This allows integrity-check to
+** detect pages that are used twice and orphaned pages (both of which
+** indicate corruption).
+*/
+typedef struct IntegrityCk IntegrityCk;
+struct IntegrityCk {
+ BtShared *pBt; /* The tree being checked out */
+ Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
+ u8 *aPgRef; /* 1 bit per page in the db (see above) */
+ Pgno nPage; /* Number of pages in the database */
+ int mxErr; /* Stop accumulating errors when this reaches zero */
+ int nErr; /* Number of messages written to zErrMsg so far */
+ int bOomFault; /* A memory allocation error has occurred */
+ const char *zPfx; /* Error message prefix */
+ Pgno v1; /* Value for first %u substitution in zPfx */
+ int v2; /* Value for second %d substitution in zPfx */
+ StrAccum errMsg; /* Accumulate the error message text here */
+ u32 *heap; /* Min-heap used for analyzing cell coverage */
+ sqlite3 *db; /* Database connection running the check */
+};
+
+/*
+** Routines to read or write a two- and four-byte big-endian integer values.
+*/
+#define get2byte(x) ((x)[0]<<8 | (x)[1])
+#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
+#define get4byte sqlite3Get4byte
+#define put4byte sqlite3Put4byte
+
+/*
+** get2byteAligned(), unlike get2byte(), requires that its argument point to a
+** two-byte aligned address. get2bytea() is only used for accessing the
+** cell addresses in a btree header.
+*/
+#if SQLITE_BYTEORDER==4321
+# define get2byteAligned(x) (*(u16*)(x))
+#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
+# define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
+#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
+# define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
+#else
+# define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
+#endif
+
+/************** End of btreeInt.h ********************************************/
+/************** Continuing where we left off in btmutex.c ********************/
+#ifndef SQLITE_OMIT_SHARED_CACHE
+#if SQLITE_THREADSAFE
+
+/*
+** Obtain the BtShared mutex associated with B-Tree handle p. Also,
+** set BtShared.db to the database handle associated with p and the
+** p->locked boolean to true.
+*/
+static void lockBtreeMutex(Btree *p){
+ assert( p->locked==0 );
+ assert( sqlite3_mutex_notheld(p->pBt->mutex) );
+ assert( sqlite3_mutex_held(p->db->mutex) );
+
+ sqlite3_mutex_enter(p->pBt->mutex);
+ p->pBt->db = p->db;
+ p->locked = 1;
+}
+
+/*
+** Release the BtShared mutex associated with B-Tree handle p and
+** clear the p->locked boolean.
+*/
+static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
+ BtShared *pBt = p->pBt;
+ assert( p->locked==1 );
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ assert( sqlite3_mutex_held(p->db->mutex) );
+ assert( p->db==pBt->db );
+
+ sqlite3_mutex_leave(pBt->mutex);
+ p->locked = 0;
+}
+
+/* Forward reference */
+static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
+
+/*
+** Enter a mutex on the given BTree object.
+**
+** If the object is not sharable, then no mutex is ever required
+** and this routine is a no-op. The underlying mutex is non-recursive.
+** But we keep a reference count in Btree.wantToLock so the behavior
+** of this interface is recursive.
+**
+** To avoid deadlocks, multiple Btrees are locked in the same order
+** by all database connections. The p->pNext is a list of other
+** Btrees belonging to the same database connection as the p Btree
+** which need to be locked after p. If we cannot get a lock on
+** p, then first unlock all of the others on p->pNext, then wait
+** for the lock to become available on p, then relock all of the
+** subsequent Btrees that desire a lock.
+*/
+SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
+ /* Some basic sanity checking on the Btree. The list of Btrees
+ ** connected by pNext and pPrev should be in sorted order by
+ ** Btree.pBt value. All elements of the list should belong to
+ ** the same connection. Only shared Btrees are on the list. */
+ assert( p->pNext==0 || p->pNext->pBt>p->pBt );
+ assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
+ assert( p->pNext==0 || p->pNext->db==p->db );
+ assert( p->pPrev==0 || p->pPrev->db==p->db );
+ assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
+
+ /* Check for locking consistency */
+ assert( !p->locked || p->wantToLock>0 );
+ assert( p->sharable || p->wantToLock==0 );
+
+ /* We should already hold a lock on the database connection */
+ assert( sqlite3_mutex_held(p->db->mutex) );
+
+ /* Unless the database is sharable and unlocked, then BtShared.db
+ ** should already be set correctly. */
+ assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
+
+ if( !p->sharable ) return;
+ p->wantToLock++;
+ if( p->locked ) return;
+ btreeLockCarefully(p);
+}
+
+/* This is a helper function for sqlite3BtreeLock(). By moving
+** complex, but seldom used logic, out of sqlite3BtreeLock() and
+** into this routine, we avoid unnecessary stack pointer changes
+** and thus help the sqlite3BtreeLock() routine to run much faster
+** in the common case.
+*/
+static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
+ Btree *pLater;
+
+ /* In most cases, we should be able to acquire the lock we
+ ** want without having to go through the ascending lock
+ ** procedure that follows. Just be sure not to block.
+ */
+ if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
+ p->pBt->db = p->db;
+ p->locked = 1;
+ return;
+ }
+
+ /* To avoid deadlock, first release all locks with a larger
+ ** BtShared address. Then acquire our lock. Then reacquire
+ ** the other BtShared locks that we used to hold in ascending
+ ** order.
+ */
+ for(pLater=p->pNext; pLater; pLater=pLater->pNext){
+ assert( pLater->sharable );
+ assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
+ assert( !pLater->locked || pLater->wantToLock>0 );
+ if( pLater->locked ){
+ unlockBtreeMutex(pLater);
+ }
+ }
+ lockBtreeMutex(p);
+ for(pLater=p->pNext; pLater; pLater=pLater->pNext){
+ if( pLater->wantToLock ){
+ lockBtreeMutex(pLater);
+ }
+ }
+}
+
+
+/*
+** Exit the recursive mutex on a Btree.
+*/
+SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
+ assert( sqlite3_mutex_held(p->db->mutex) );
+ if( p->sharable ){
+ assert( p->wantToLock>0 );
+ p->wantToLock--;
+ if( p->wantToLock==0 ){
+ unlockBtreeMutex(p);
+ }
+ }
+}
+
+#ifndef NDEBUG
+/*
+** Return true if the BtShared mutex is held on the btree, or if the
+** B-Tree is not marked as sharable.
+**
+** This routine is used only from within assert() statements.
+*/
+SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
+ assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
+ assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
+ assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
+ assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
+
+ return (p->sharable==0 || p->locked);
+}
+#endif
+
+
+/*
+** Enter the mutex on every Btree associated with a database
+** connection. This is needed (for example) prior to parsing
+** a statement since we will be comparing table and column names
+** against all schemas and we do not want those schemas being
+** reset out from under us.
+**
+** There is a corresponding leave-all procedures.
+**
+** Enter the mutexes in accending order by BtShared pointer address
+** to avoid the possibility of deadlock when two threads with
+** two or more btrees in common both try to lock all their btrees
+** at the same instant.
+*/
+static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
+ int i;
+ int skipOk = 1;
+ Btree *p;
+ assert( sqlite3_mutex_held(db->mutex) );
+ for(i=0; i<db->nDb; i++){
+ p = db->aDb[i].pBt;
+ if( p && p->sharable ){
+ sqlite3BtreeEnter(p);
+ skipOk = 0;
+ }
+ }
+ db->noSharedCache = skipOk;
+}
+SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
+ if( db->noSharedCache==0 ) btreeEnterAll(db);
+}
+static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
+ int i;
+ Btree *p;
+ assert( sqlite3_mutex_held(db->mutex) );
+ for(i=0; i<db->nDb; i++){
+ p = db->aDb[i].pBt;
+ if( p ) sqlite3BtreeLeave(p);
+ }
+}
+SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
+ if( db->noSharedCache==0 ) btreeLeaveAll(db);
+}
+
+#ifndef NDEBUG
+/*
+** Return true if the current thread holds the database connection
+** mutex and all required BtShared mutexes.
+**
+** This routine is used inside assert() statements only.
+*/
+SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
+ int i;
+ if( !sqlite3_mutex_held(db->mutex) ){
+ return 0;
+ }
+ for(i=0; i<db->nDb; i++){
+ Btree *p;
+ p = db->aDb[i].pBt;
+ if( p && p->sharable &&
+ (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
+ return 0;
+ }
+ }
+ return 1;
+}
+#endif /* NDEBUG */
+
+#ifndef NDEBUG
+/*
+** Return true if the correct mutexes are held for accessing the
+** db->aDb[iDb].pSchema structure. The mutexes required for schema
+** access are:
+**
+** (1) The mutex on db
+** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
+**
+** If pSchema is not NULL, then iDb is computed from pSchema and
+** db using sqlite3SchemaToIndex().
+*/
+SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
+ Btree *p;
+ assert( db!=0 );
+ if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
+ assert( iDb>=0 && iDb<db->nDb );
+ if( !sqlite3_mutex_held(db->mutex) ) return 0;
+ if( iDb==1 ) return 1;
+ p = db->aDb[iDb].pBt;
+ assert( p!=0 );
+ return p->sharable==0 || p->locked==1;
+}
+#endif /* NDEBUG */
+
+#else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
+/*
+** The following are special cases for mutex enter routines for use
+** in single threaded applications that use shared cache. Except for
+** these two routines, all mutex operations are no-ops in that case and
+** are null #defines in btree.h.
+**
+** If shared cache is disabled, then all btree mutex routines, including
+** the ones below, are no-ops and are null #defines in btree.h.
+*/
+
+SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
+ p->pBt->db = p->db;
+}
+SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
+ int i;
+ for(i=0; i<db->nDb; i++){
+ Btree *p = db->aDb[i].pBt;
+ if( p ){
+ p->pBt->db = p->db;
+ }
+ }
+}
+#endif /* if SQLITE_THREADSAFE */
+
+#ifndef SQLITE_OMIT_INCRBLOB
+/*
+** Enter a mutex on a Btree given a cursor owned by that Btree.
+**
+** These entry points are used by incremental I/O only. Enter() is required
+** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
+** the build is threadsafe. Leave() is only required by threadsafe builds.
+*/
+SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
+ sqlite3BtreeEnter(pCur->pBtree);
+}
+# if SQLITE_THREADSAFE
+SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
+ sqlite3BtreeLeave(pCur->pBtree);
+}
+# endif
+#endif /* ifndef SQLITE_OMIT_INCRBLOB */
+
+#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
+
+/************** End of btmutex.c *********************************************/
+/************** Begin file btree.c *******************************************/
+/*
+** 2004 April 6
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file implements an external (disk-based) database using BTrees.
+** See the header comment on "btreeInt.h" for additional information.
+** Including a description of file format and an overview of operation.
+*/
+/* #include "btreeInt.h" */
+
+/*
+** The header string that appears at the beginning of every
+** SQLite database.
+*/
+static const char zMagicHeader[] = SQLITE_FILE_HEADER;
+
+/*
+** Set this global variable to 1 to enable tracing using the TRACE
+** macro.
+*/
+#if 0
+int sqlite3BtreeTrace=1; /* True to enable tracing */
+# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
+#else
+# define TRACE(X)
+#endif
+
+/*
+** Extract a 2-byte big-endian integer from an array of unsigned bytes.
+** But if the value is zero, make it 65536.
+**
+** This routine is used to extract the "offset to cell content area" value
+** from the header of a btree page. If the page size is 65536 and the page
+** is empty, the offset should be 65536, but the 2-byte value stores zero.
+** This routine makes the necessary adjustment to 65536.
+*/
+#define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
+
+/*
+** Values passed as the 5th argument to allocateBtreePage()
+*/
+#define BTALLOC_ANY 0 /* Allocate any page */
+#define BTALLOC_EXACT 1 /* Allocate exact page if possible */
+#define BTALLOC_LE 2 /* Allocate any page <= the parameter */
+
+/*
+** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
+** defined, or 0 if it is. For example:
+**
+** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
+*/
+#ifndef SQLITE_OMIT_AUTOVACUUM
+#define IfNotOmitAV(expr) (expr)
+#else
+#define IfNotOmitAV(expr) 0
+#endif
+
+#ifndef SQLITE_OMIT_SHARED_CACHE
+/*
+** A list of BtShared objects that are eligible for participation
+** in shared cache. This variable has file scope during normal builds,
+** but the test harness needs to access it so we make it global for
+** test builds.
+**
+** Access to this variable is protected by SQLITE_MUTEX_STATIC_MAIN.
+*/
+#ifdef SQLITE_TEST
+SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
+#else
+static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
+#endif
+#endif /* SQLITE_OMIT_SHARED_CACHE */
+
+#ifndef SQLITE_OMIT_SHARED_CACHE
+/*
+** Enable or disable the shared pager and schema features.
+**
+** This routine has no effect on existing database connections.
+** The shared cache setting effects only future calls to
+** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
+*/
+SQLITE_API int sqlite3_enable_shared_cache(int enable){
+ sqlite3GlobalConfig.sharedCacheEnabled = enable;
+ return SQLITE_OK;
+}
+#endif
+
+
+
+#ifdef SQLITE_OMIT_SHARED_CACHE
+ /*
+ ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
+ ** and clearAllSharedCacheTableLocks()
+ ** manipulate entries in the BtShared.pLock linked list used to store
+ ** shared-cache table level locks. If the library is compiled with the
+ ** shared-cache feature disabled, then there is only ever one user
+ ** of each BtShared structure and so this locking is not necessary.
+ ** So define the lock related functions as no-ops.
+ */
+ #define querySharedCacheTableLock(a,b,c) SQLITE_OK
+ #define setSharedCacheTableLock(a,b,c) SQLITE_OK
+ #define clearAllSharedCacheTableLocks(a)
+ #define downgradeAllSharedCacheTableLocks(a)
+ #define hasSharedCacheTableLock(a,b,c,d) 1
+ #define hasReadConflicts(a, b) 0
+#endif
+
+#ifdef SQLITE_DEBUG
+/*
+** Return an reset the seek counter for a Btree object.
+*/
+SQLITE_PRIVATE sqlite3_uint64 sqlite3BtreeSeekCount(Btree *pBt){
+ u64 n = pBt->nSeek;
+ pBt->nSeek = 0;
+ return n;
+}
+#endif
+
+/*
+** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
+** (MemPage*) as an argument. The (MemPage*) must not be NULL.
+**
+** If SQLITE_DEBUG is not defined, then this macro is equivalent to
+** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
+** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
+** with the page number and filename associated with the (MemPage*).
+*/
+#ifdef SQLITE_DEBUG
+int corruptPageError(int lineno, MemPage *p){
+ char *zMsg;
+ sqlite3BeginBenignMalloc();
+ zMsg = sqlite3_mprintf("database corruption page %d of %s",
+ (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
+ );
+ sqlite3EndBenignMalloc();
+ if( zMsg ){
+ sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
+ }
+ sqlite3_free(zMsg);
+ return SQLITE_CORRUPT_BKPT;
+}
+# define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
+#else
+# define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
+#endif
+
+#ifndef SQLITE_OMIT_SHARED_CACHE
+
+#ifdef SQLITE_DEBUG
+/*
+**** This function is only used as part of an assert() statement. ***
+**
+** Check to see if pBtree holds the required locks to read or write to the
+** table with root page iRoot. Return 1 if it does and 0 if not.
+**
+** For example, when writing to a table with root-page iRoot via
+** Btree connection pBtree:
+**
+** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
+**
+** When writing to an index that resides in a sharable database, the
+** caller should have first obtained a lock specifying the root page of
+** the corresponding table. This makes things a bit more complicated,
+** as this module treats each table as a separate structure. To determine
+** the table corresponding to the index being written, this
+** function has to search through the database schema.
+**
+** Instead of a lock on the table/index rooted at page iRoot, the caller may
+** hold a write-lock on the schema table (root page 1). This is also
+** acceptable.
+*/
+static int hasSharedCacheTableLock(
+ Btree *pBtree, /* Handle that must hold lock */
+ Pgno iRoot, /* Root page of b-tree */
+ int isIndex, /* True if iRoot is the root of an index b-tree */
+ int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
+){
+ Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
+ Pgno iTab = 0;
+ BtLock *pLock;
+
+ /* If this database is not shareable, or if the client is reading
+ ** and has the read-uncommitted flag set, then no lock is required.
+ ** Return true immediately.
+ */
+ if( (pBtree->sharable==0)
+ || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
+ ){
+ return 1;
+ }
+
+ /* If the client is reading or writing an index and the schema is
+ ** not loaded, then it is too difficult to actually check to see if
+ ** the correct locks are held. So do not bother - just return true.
+ ** This case does not come up very often anyhow.
+ */
+ if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
+ return 1;
+ }
+
+ /* Figure out the root-page that the lock should be held on. For table
+ ** b-trees, this is just the root page of the b-tree being read or
+ ** written. For index b-trees, it is the root page of the associated
+ ** table. */
+ if( isIndex ){
+ HashElem *p;
+ int bSeen = 0;
+ for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
+ Index *pIdx = (Index *)sqliteHashData(p);
+ if( pIdx->tnum==(int)iRoot ){
+ if( bSeen ){
+ /* Two or more indexes share the same root page. There must
+ ** be imposter tables. So just return true. The assert is not
+ ** useful in that case. */
+ return 1;
+ }
+ iTab = pIdx->pTable->tnum;
+ bSeen = 1;
+ }
+ }
+ }else{
+ iTab = iRoot;
+ }
+
+ /* Search for the required lock. Either a write-lock on root-page iTab, a
+ ** write-lock on the schema table, or (if the client is reading) a
+ ** read-lock on iTab will suffice. Return 1 if any of these are found. */
+ for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
+ if( pLock->pBtree==pBtree
+ && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
+ && pLock->eLock>=eLockType
+ ){
+ return 1;
+ }
+ }
+
+ /* Failed to find the required lock. */
+ return 0;
+}
+#endif /* SQLITE_DEBUG */
+
+#ifdef SQLITE_DEBUG
+/*
+**** This function may be used as part of assert() statements only. ****
+**
+** Return true if it would be illegal for pBtree to write into the
+** table or index rooted at iRoot because other shared connections are
+** simultaneously reading that same table or index.
+**
+** It is illegal for pBtree to write if some other Btree object that
+** shares the same BtShared object is currently reading or writing
+** the iRoot table. Except, if the other Btree object has the
+** read-uncommitted flag set, then it is OK for the other object to
+** have a read cursor.
+**
+** For example, before writing to any part of the table or index
+** rooted at page iRoot, one should call:
+**
+** assert( !hasReadConflicts(pBtree, iRoot) );
+*/
+static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
+ BtCursor *p;
+ for(p=pBtree->pBt->pCursor; p; p=p->pNext){
+ if( p->pgnoRoot==iRoot
+ && p->pBtree!=pBtree
+ && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
+ ){
+ return 1;
+ }
+ }
+ return 0;
+}
+#endif /* #ifdef SQLITE_DEBUG */
+
+/*
+** Query to see if Btree handle p may obtain a lock of type eLock
+** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
+** SQLITE_OK if the lock may be obtained (by calling
+** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
+*/
+static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
+ BtShared *pBt = p->pBt;
+ BtLock *pIter;
+
+ assert( sqlite3BtreeHoldsMutex(p) );
+ assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
+ assert( p->db!=0 );
+ assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
+
+ /* If requesting a write-lock, then the Btree must have an open write
+ ** transaction on this file. And, obviously, for this to be so there
+ ** must be an open write transaction on the file itself.
+ */
+ assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
+ assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
+
+ /* This routine is a no-op if the shared-cache is not enabled */
+ if( !p->sharable ){
+ return SQLITE_OK;
+ }
+
+ /* If some other connection is holding an exclusive lock, the
+ ** requested lock may not be obtained.
+ */
+ if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
+ sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
+ return SQLITE_LOCKED_SHAREDCACHE;
+ }
+
+ for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
+ /* The condition (pIter->eLock!=eLock) in the following if(...)
+ ** statement is a simplification of:
+ **
+ ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
+ **
+ ** since we know that if eLock==WRITE_LOCK, then no other connection
+ ** may hold a WRITE_LOCK on any table in this file (since there can
+ ** only be a single writer).
+ */
+ assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
+ assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
+ if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
+ sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
+ if( eLock==WRITE_LOCK ){
+ assert( p==pBt->pWriter );
+ pBt->btsFlags |= BTS_PENDING;
+ }
+ return SQLITE_LOCKED_SHAREDCACHE;
+ }
+ }
+ return SQLITE_OK;
+}
+#endif /* !SQLITE_OMIT_SHARED_CACHE */
+
+#ifndef SQLITE_OMIT_SHARED_CACHE
+/*
+** Add a lock on the table with root-page iTable to the shared-btree used
+** by Btree handle p. Parameter eLock must be either READ_LOCK or
+** WRITE_LOCK.
+**
+** This function assumes the following:
+**
+** (a) The specified Btree object p is connected to a sharable
+** database (one with the BtShared.sharable flag set), and
+**
+** (b) No other Btree objects hold a lock that conflicts
+** with the requested lock (i.e. querySharedCacheTableLock() has
+** already been called and returned SQLITE_OK).
+**
+** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
+** is returned if a malloc attempt fails.
+*/
+static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
+ BtShared *pBt = p->pBt;
+ BtLock *pLock = 0;
+ BtLock *pIter;
+
+ assert( sqlite3BtreeHoldsMutex(p) );
+ assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
+ assert( p->db!=0 );
+
+ /* A connection with the read-uncommitted flag set will never try to
+ ** obtain a read-lock using this function. The only read-lock obtained
+ ** by a connection in read-uncommitted mode is on the sqlite_schema
+ ** table, and that lock is obtained in BtreeBeginTrans(). */
+ assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
+
+ /* This function should only be called on a sharable b-tree after it
+ ** has been determined that no other b-tree holds a conflicting lock. */
+ assert( p->sharable );
+ assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
+
+ /* First search the list for an existing lock on this table. */
+ for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
+ if( pIter->iTable==iTable && pIter->pBtree==p ){
+ pLock = pIter;
+ break;
+ }
+ }
+
+ /* If the above search did not find a BtLock struct associating Btree p
+ ** with table iTable, allocate one and link it into the list.
+ */
+ if( !pLock ){
+ pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
+ if( !pLock ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ pLock->iTable = iTable;
+ pLock->pBtree = p;
+ pLock->pNext = pBt->pLock;
+ pBt->pLock = pLock;
+ }
+
+ /* Set the BtLock.eLock variable to the maximum of the current lock
+ ** and the requested lock. This means if a write-lock was already held
+ ** and a read-lock requested, we don't incorrectly downgrade the lock.
+ */
+ assert( WRITE_LOCK>READ_LOCK );
+ if( eLock>pLock->eLock ){
+ pLock->eLock = eLock;
+ }
+
+ return SQLITE_OK;
+}
+#endif /* !SQLITE_OMIT_SHARED_CACHE */
+
+#ifndef SQLITE_OMIT_SHARED_CACHE
+/*
+** Release all the table locks (locks obtained via calls to
+** the setSharedCacheTableLock() procedure) held by Btree object p.
+**
+** This function assumes that Btree p has an open read or write
+** transaction. If it does not, then the BTS_PENDING flag
+** may be incorrectly cleared.
+*/
+static void clearAllSharedCacheTableLocks(Btree *p){
+ BtShared *pBt = p->pBt;
+ BtLock **ppIter = &pBt->pLock;
+
+ assert( sqlite3BtreeHoldsMutex(p) );
+ assert( p->sharable || 0==*ppIter );
+ assert( p->inTrans>0 );
+
+ while( *ppIter ){
+ BtLock *pLock = *ppIter;
+ assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
+ assert( pLock->pBtree->inTrans>=pLock->eLock );
+ if( pLock->pBtree==p ){
+ *ppIter = pLock->pNext;
+ assert( pLock->iTable!=1 || pLock==&p->lock );
+ if( pLock->iTable!=1 ){
+ sqlite3_free(pLock);
+ }
+ }else{
+ ppIter = &pLock->pNext;
+ }
+ }
+
+ assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
+ if( pBt->pWriter==p ){
+ pBt->pWriter = 0;
+ pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
+ }else if( pBt->nTransaction==2 ){
+ /* This function is called when Btree p is concluding its
+ ** transaction. If there currently exists a writer, and p is not
+ ** that writer, then the number of locks held by connections other
+ ** than the writer must be about to drop to zero. In this case
+ ** set the BTS_PENDING flag to 0.
+ **
+ ** If there is not currently a writer, then BTS_PENDING must
+ ** be zero already. So this next line is harmless in that case.
+ */
+ pBt->btsFlags &= ~BTS_PENDING;
+ }
+}
+
+/*
+** This function changes all write-locks held by Btree p into read-locks.
+*/
+static void downgradeAllSharedCacheTableLocks(Btree *p){
+ BtShared *pBt = p->pBt;
+ if( pBt->pWriter==p ){
+ BtLock *pLock;
+ pBt->pWriter = 0;
+ pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
+ for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
+ assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
+ pLock->eLock = READ_LOCK;
+ }
+ }
+}
+
+#endif /* SQLITE_OMIT_SHARED_CACHE */
+
+static void releasePage(MemPage *pPage); /* Forward reference */
+static void releasePageOne(MemPage *pPage); /* Forward reference */
+static void releasePageNotNull(MemPage *pPage); /* Forward reference */
+
+/*
+***** This routine is used inside of assert() only ****
+**
+** Verify that the cursor holds the mutex on its BtShared
+*/
+#ifdef SQLITE_DEBUG
+static int cursorHoldsMutex(BtCursor *p){
+ return sqlite3_mutex_held(p->pBt->mutex);
+}
+
+/* Verify that the cursor and the BtShared agree about what is the current
+** database connetion. This is important in shared-cache mode. If the database
+** connection pointers get out-of-sync, it is possible for routines like
+** btreeInitPage() to reference an stale connection pointer that references a
+** a connection that has already closed. This routine is used inside assert()
+** statements only and for the purpose of double-checking that the btree code
+** does keep the database connection pointers up-to-date.
+*/
+static int cursorOwnsBtShared(BtCursor *p){
+ assert( cursorHoldsMutex(p) );
+ return (p->pBtree->db==p->pBt->db);
+}
+#endif
+
+/*
+** Invalidate the overflow cache of the cursor passed as the first argument.
+** on the shared btree structure pBt.
+*/
+#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
+
+/*
+** Invalidate the overflow page-list cache for all cursors opened
+** on the shared btree structure pBt.
+*/
+static void invalidateAllOverflowCache(BtShared *pBt){
+ BtCursor *p;
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ for(p=pBt->pCursor; p; p=p->pNext){
+ invalidateOverflowCache(p);
+ }
+}
+
+#ifndef SQLITE_OMIT_INCRBLOB
+/*
+** This function is called before modifying the contents of a table
+** to invalidate any incrblob cursors that are open on the
+** row or one of the rows being modified.
+**
+** If argument isClearTable is true, then the entire contents of the
+** table is about to be deleted. In this case invalidate all incrblob
+** cursors open on any row within the table with root-page pgnoRoot.
+**
+** Otherwise, if argument isClearTable is false, then the row with
+** rowid iRow is being replaced or deleted. In this case invalidate
+** only those incrblob cursors open on that specific row.
+*/
+static void invalidateIncrblobCursors(
+ Btree *pBtree, /* The database file to check */
+ Pgno pgnoRoot, /* The table that might be changing */
+ i64 iRow, /* The rowid that might be changing */
+ int isClearTable /* True if all rows are being deleted */
+){
+ BtCursor *p;
+ if( pBtree->hasIncrblobCur==0 ) return;
+ assert( sqlite3BtreeHoldsMutex(pBtree) );
+ pBtree->hasIncrblobCur = 0;
+ for(p=pBtree->pBt->pCursor; p; p=p->pNext){
+ if( (p->curFlags & BTCF_Incrblob)!=0 ){
+ pBtree->hasIncrblobCur = 1;
+ if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
+ p->eState = CURSOR_INVALID;
+ }
+ }
+ }
+}
+
+#else
+ /* Stub function when INCRBLOB is omitted */
+ #define invalidateIncrblobCursors(w,x,y,z)
+#endif /* SQLITE_OMIT_INCRBLOB */
+
+/*
+** Set bit pgno of the BtShared.pHasContent bitvec. This is called
+** when a page that previously contained data becomes a free-list leaf
+** page.
+**
+** The BtShared.pHasContent bitvec exists to work around an obscure
+** bug caused by the interaction of two useful IO optimizations surrounding
+** free-list leaf pages:
+**
+** 1) When all data is deleted from a page and the page becomes
+** a free-list leaf page, the page is not written to the database
+** (as free-list leaf pages contain no meaningful data). Sometimes
+** such a page is not even journalled (as it will not be modified,
+** why bother journalling it?).
+**
+** 2) When a free-list leaf page is reused, its content is not read
+** from the database or written to the journal file (why should it
+** be, if it is not at all meaningful?).
+**
+** By themselves, these optimizations work fine and provide a handy
+** performance boost to bulk delete or insert operations. However, if
+** a page is moved to the free-list and then reused within the same
+** transaction, a problem comes up. If the page is not journalled when
+** it is moved to the free-list and it is also not journalled when it
+** is extracted from the free-list and reused, then the original data
+** may be lost. In the event of a rollback, it may not be possible
+** to restore the database to its original configuration.
+**
+** The solution is the BtShared.pHasContent bitvec. Whenever a page is
+** moved to become a free-list leaf page, the corresponding bit is
+** set in the bitvec. Whenever a leaf page is extracted from the free-list,
+** optimization 2 above is omitted if the corresponding bit is already
+** set in BtShared.pHasContent. The contents of the bitvec are cleared
+** at the end of every transaction.
+*/
+static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
+ int rc = SQLITE_OK;
+ if( !pBt->pHasContent ){
+ assert( pgno<=pBt->nPage );
+ pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
+ if( !pBt->pHasContent ){
+ rc = SQLITE_NOMEM_BKPT;
+ }
+ }
+ if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
+ rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
+ }
+ return rc;
+}
+
+/*
+** Query the BtShared.pHasContent vector.
+**
+** This function is called when a free-list leaf page is removed from the
+** free-list for reuse. It returns false if it is safe to retrieve the
+** page from the pager layer with the 'no-content' flag set. True otherwise.
+*/
+static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
+ Bitvec *p = pBt->pHasContent;
+ return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno));
+}
+
+/*
+** Clear (destroy) the BtShared.pHasContent bitvec. This should be
+** invoked at the conclusion of each write-transaction.
+*/
+static void btreeClearHasContent(BtShared *pBt){
+ sqlite3BitvecDestroy(pBt->pHasContent);
+ pBt->pHasContent = 0;
+}
+
+/*
+** Release all of the apPage[] pages for a cursor.
+*/
+static void btreeReleaseAllCursorPages(BtCursor *pCur){
+ int i;
+ if( pCur->iPage>=0 ){
+ for(i=0; i<pCur->iPage; i++){
+ releasePageNotNull(pCur->apPage[i]);
+ }
+ releasePageNotNull(pCur->pPage);
+ pCur->iPage = -1;
+ }
+}
+
+/*
+** The cursor passed as the only argument must point to a valid entry
+** when this function is called (i.e. have eState==CURSOR_VALID). This
+** function saves the current cursor key in variables pCur->nKey and
+** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
+** code otherwise.
+**
+** If the cursor is open on an intkey table, then the integer key
+** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
+** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
+** set to point to a malloced buffer pCur->nKey bytes in size containing
+** the key.
+*/
+static int saveCursorKey(BtCursor *pCur){
+ int rc = SQLITE_OK;
+ assert( CURSOR_VALID==pCur->eState );
+ assert( 0==pCur->pKey );
+ assert( cursorHoldsMutex(pCur) );
+
+ if( pCur->curIntKey ){
+ /* Only the rowid is required for a table btree */
+ pCur->nKey = sqlite3BtreeIntegerKey(pCur);
+ }else{
+ /* For an index btree, save the complete key content. It is possible
+ ** that the current key is corrupt. In that case, it is possible that
+ ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
+ ** up to the size of 1 varint plus 1 8-byte value when the cursor
+ ** position is restored. Hence the 17 bytes of padding allocated
+ ** below. */
+ void *pKey;
+ pCur->nKey = sqlite3BtreePayloadSize(pCur);
+ pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
+ if( pKey ){
+ rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
+ if( rc==SQLITE_OK ){
+ memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
+ pCur->pKey = pKey;
+ }else{
+ sqlite3_free(pKey);
+ }
+ }else{
+ rc = SQLITE_NOMEM_BKPT;
+ }
+ }
+ assert( !pCur->curIntKey || !pCur->pKey );
+ return rc;
+}
+
+/*
+** Save the current cursor position in the variables BtCursor.nKey
+** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
+**
+** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
+** prior to calling this routine.
+*/
+static int saveCursorPosition(BtCursor *pCur){
+ int rc;
+
+ assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
+ assert( 0==pCur->pKey );
+ assert( cursorHoldsMutex(pCur) );
+
+ if( pCur->curFlags & BTCF_Pinned ){
+ return SQLITE_CONSTRAINT_PINNED;
+ }
+ if( pCur->eState==CURSOR_SKIPNEXT ){
+ pCur->eState = CURSOR_VALID;
+ }else{
+ pCur->skipNext = 0;
+ }
+
+ rc = saveCursorKey(pCur);
+ if( rc==SQLITE_OK ){
+ btreeReleaseAllCursorPages(pCur);
+ pCur->eState = CURSOR_REQUIRESEEK;
+ }
+
+ pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
+ return rc;
+}
+
+/* Forward reference */
+static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
+
+/*
+** Save the positions of all cursors (except pExcept) that are open on
+** the table with root-page iRoot. "Saving the cursor position" means that
+** the location in the btree is remembered in such a way that it can be
+** moved back to the same spot after the btree has been modified. This
+** routine is called just before cursor pExcept is used to modify the
+** table, for example in BtreeDelete() or BtreeInsert().
+**
+** If there are two or more cursors on the same btree, then all such
+** cursors should have their BTCF_Multiple flag set. The btreeCursor()
+** routine enforces that rule. This routine only needs to be called in
+** the uncommon case when pExpect has the BTCF_Multiple flag set.
+**
+** If pExpect!=NULL and if no other cursors are found on the same root-page,
+** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
+** pointless call to this routine.
+**
+** Implementation note: This routine merely checks to see if any cursors
+** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
+** event that cursors are in need to being saved.
+*/
+static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
+ BtCursor *p;
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ assert( pExcept==0 || pExcept->pBt==pBt );
+ for(p=pBt->pCursor; p; p=p->pNext){
+ if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
+ }
+ if( p ) return saveCursorsOnList(p, iRoot, pExcept);
+ if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
+ return SQLITE_OK;
+}
+
+/* This helper routine to saveAllCursors does the actual work of saving
+** the cursors if and when a cursor is found that actually requires saving.
+** The common case is that no cursors need to be saved, so this routine is
+** broken out from its caller to avoid unnecessary stack pointer movement.
+*/
+static int SQLITE_NOINLINE saveCursorsOnList(
+ BtCursor *p, /* The first cursor that needs saving */
+ Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
+ BtCursor *pExcept /* Do not save this cursor */
+){
+ do{
+ if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
+ if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
+ int rc = saveCursorPosition(p);
+ if( SQLITE_OK!=rc ){
+ return rc;
+ }
+ }else{
+ testcase( p->iPage>=0 );
+ btreeReleaseAllCursorPages(p);
+ }
+ }
+ p = p->pNext;
+ }while( p );
+ return SQLITE_OK;
+}
+
+/*
+** Clear the current cursor position.
+*/
+SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
+ assert( cursorHoldsMutex(pCur) );
+ sqlite3_free(pCur->pKey);
+ pCur->pKey = 0;
+ pCur->eState = CURSOR_INVALID;
+}
+
+/*
+** In this version of BtreeMoveto, pKey is a packed index record
+** such as is generated by the OP_MakeRecord opcode. Unpack the
+** record and then call BtreeMovetoUnpacked() to do the work.
+*/
+static int btreeMoveto(
+ BtCursor *pCur, /* Cursor open on the btree to be searched */
+ const void *pKey, /* Packed key if the btree is an index */
+ i64 nKey, /* Integer key for tables. Size of pKey for indices */
+ int bias, /* Bias search to the high end */
+ int *pRes /* Write search results here */
+){
+ int rc; /* Status code */
+ UnpackedRecord *pIdxKey; /* Unpacked index key */
+
+ if( pKey ){
+ KeyInfo *pKeyInfo = pCur->pKeyInfo;
+ assert( nKey==(i64)(int)nKey );
+ pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
+ if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
+ sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
+ if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
+ rc = SQLITE_CORRUPT_BKPT;
+ goto moveto_done;
+ }
+ }else{
+ pIdxKey = 0;
+ }
+ rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
+moveto_done:
+ if( pIdxKey ){
+ sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
+ }
+ return rc;
+}
+
+/*
+** Restore the cursor to the position it was in (or as close to as possible)
+** when saveCursorPosition() was called. Note that this call deletes the
+** saved position info stored by saveCursorPosition(), so there can be
+** at most one effective restoreCursorPosition() call after each
+** saveCursorPosition().
+*/
+static int btreeRestoreCursorPosition(BtCursor *pCur){
+ int rc;
+ int skipNext = 0;
+ assert( cursorOwnsBtShared(pCur) );
+ assert( pCur->eState>=CURSOR_REQUIRESEEK );
+ if( pCur->eState==CURSOR_FAULT ){
+ return pCur->skipNext;
+ }
+ pCur->eState = CURSOR_INVALID;
+ if( sqlite3FaultSim(410) ){
+ rc = SQLITE_IOERR;
+ }else{
+ rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
+ }
+ if( rc==SQLITE_OK ){
+ sqlite3_free(pCur->pKey);
+ pCur->pKey = 0;
+ assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
+ if( skipNext ) pCur->skipNext = skipNext;
+ if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
+ pCur->eState = CURSOR_SKIPNEXT;
+ }
+ }
+ return rc;
+}
+
+#define restoreCursorPosition(p) \
+ (p->eState>=CURSOR_REQUIRESEEK ? \
+ btreeRestoreCursorPosition(p) : \
+ SQLITE_OK)
+
+/*
+** Determine whether or not a cursor has moved from the position where
+** it was last placed, or has been invalidated for any other reason.
+** Cursors can move when the row they are pointing at is deleted out
+** from under them, for example. Cursor might also move if a btree
+** is rebalanced.
+**
+** Calling this routine with a NULL cursor pointer returns false.
+**
+** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
+** back to where it ought to be if this routine returns true.
+*/
+SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
+ assert( EIGHT_BYTE_ALIGNMENT(pCur)
+ || pCur==sqlite3BtreeFakeValidCursor() );
+ assert( offsetof(BtCursor, eState)==0 );
+ assert( sizeof(pCur->eState)==1 );
+ return CURSOR_VALID != *(u8*)pCur;
+}
+
+/*
+** Return a pointer to a fake BtCursor object that will always answer
+** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
+** cursor returned must not be used with any other Btree interface.
+*/
+SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){
+ static u8 fakeCursor = CURSOR_VALID;
+ assert( offsetof(BtCursor, eState)==0 );
+ return (BtCursor*)&fakeCursor;
+}
+
+/*
+** This routine restores a cursor back to its original position after it
+** has been moved by some outside activity (such as a btree rebalance or
+** a row having been deleted out from under the cursor).
+**
+** On success, the *pDifferentRow parameter is false if the cursor is left
+** pointing at exactly the same row. *pDifferntRow is the row the cursor
+** was pointing to has been deleted, forcing the cursor to point to some
+** nearby row.
+**
+** This routine should only be called for a cursor that just returned
+** TRUE from sqlite3BtreeCursorHasMoved().
+*/
+SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
+ int rc;
+
+ assert( pCur!=0 );
+ assert( pCur->eState!=CURSOR_VALID );
+ rc = restoreCursorPosition(pCur);
+ if( rc ){
+ *pDifferentRow = 1;
+ return rc;
+ }
+ if( pCur->eState!=CURSOR_VALID ){
+ *pDifferentRow = 1;
+ }else{
+ *pDifferentRow = 0;
+ }
+ return SQLITE_OK;
+}
+
+#ifdef SQLITE_ENABLE_CURSOR_HINTS
+/*
+** Provide hints to the cursor. The particular hint given (and the type
+** and number of the varargs parameters) is determined by the eHintType
+** parameter. See the definitions of the BTREE_HINT_* macros for details.
+*/
+SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
+ /* Used only by system that substitute their own storage engine */
+}
+#endif
+
+/*
+** Provide flag hints to the cursor.
+*/
+SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
+ assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
+ pCur->hints = x;
+}
+
+
+#ifndef SQLITE_OMIT_AUTOVACUUM
+/*
+** Given a page number of a regular database page, return the page
+** number for the pointer-map page that contains the entry for the
+** input page number.
+**
+** Return 0 (not a valid page) for pgno==1 since there is
+** no pointer map associated with page 1. The integrity_check logic
+** requires that ptrmapPageno(*,1)!=1.
+*/
+static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
+ int nPagesPerMapPage;
+ Pgno iPtrMap, ret;
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ if( pgno<2 ) return 0;
+ nPagesPerMapPage = (pBt->usableSize/5)+1;
+ iPtrMap = (pgno-2)/nPagesPerMapPage;
+ ret = (iPtrMap*nPagesPerMapPage) + 2;
+ if( ret==PENDING_BYTE_PAGE(pBt) ){
+ ret++;
+ }
+ return ret;
+}
+
+/*
+** Write an entry into the pointer map.
+**
+** This routine updates the pointer map entry for page number 'key'
+** so that it maps to type 'eType' and parent page number 'pgno'.
+**
+** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
+** a no-op. If an error occurs, the appropriate error code is written
+** into *pRC.
+*/
+static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
+ DbPage *pDbPage; /* The pointer map page */
+ u8 *pPtrmap; /* The pointer map data */
+ Pgno iPtrmap; /* The pointer map page number */
+ int offset; /* Offset in pointer map page */
+ int rc; /* Return code from subfunctions */
+
+ if( *pRC ) return;
+
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ /* The super-journal page number must never be used as a pointer map page */
+ assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
+
+ assert( pBt->autoVacuum );
+ if( key==0 ){
+ *pRC = SQLITE_CORRUPT_BKPT;
+ return;
+ }
+ iPtrmap = PTRMAP_PAGENO(pBt, key);
+ rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
+ if( rc!=SQLITE_OK ){
+ *pRC = rc;
+ return;
+ }
+ if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
+ /* The first byte of the extra data is the MemPage.isInit byte.
+ ** If that byte is set, it means this page is also being used
+ ** as a btree page. */
+ *pRC = SQLITE_CORRUPT_BKPT;
+ goto ptrmap_exit;
+ }
+ offset = PTRMAP_PTROFFSET(iPtrmap, key);
+ if( offset<0 ){
+ *pRC = SQLITE_CORRUPT_BKPT;
+ goto ptrmap_exit;
+ }
+ assert( offset <= (int)pBt->usableSize-5 );
+ pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
+
+ if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
+ TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
+ *pRC= rc = sqlite3PagerWrite(pDbPage);
+ if( rc==SQLITE_OK ){
+ pPtrmap[offset] = eType;
+ put4byte(&pPtrmap[offset+1], parent);
+ }
+ }
+
+ptrmap_exit:
+ sqlite3PagerUnref(pDbPage);
+}
+
+/*
+** Read an entry from the pointer map.
+**
+** This routine retrieves the pointer map entry for page 'key', writing
+** the type and parent page number to *pEType and *pPgno respectively.
+** An error code is returned if something goes wrong, otherwise SQLITE_OK.
+*/
+static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
+ DbPage *pDbPage; /* The pointer map page */
+ int iPtrmap; /* Pointer map page index */
+ u8 *pPtrmap; /* Pointer map page data */
+ int offset; /* Offset of entry in pointer map */
+ int rc;
+
+ assert( sqlite3_mutex_held(pBt->mutex) );
+
+ iPtrmap = PTRMAP_PAGENO(pBt, key);
+ rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
+ if( rc!=0 ){
+ return rc;
+ }
+ pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
+
+ offset = PTRMAP_PTROFFSET(iPtrmap, key);
+ if( offset<0 ){
+ sqlite3PagerUnref(pDbPage);
+ return SQLITE_CORRUPT_BKPT;
+ }
+ assert( offset <= (int)pBt->usableSize-5 );
+ assert( pEType!=0 );
+ *pEType = pPtrmap[offset];
+ if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
+
+ sqlite3PagerUnref(pDbPage);
+ if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
+ return SQLITE_OK;
+}
+
+#else /* if defined SQLITE_OMIT_AUTOVACUUM */
+ #define ptrmapPut(w,x,y,z,rc)
+ #define ptrmapGet(w,x,y,z) SQLITE_OK
+ #define ptrmapPutOvflPtr(x, y, z, rc)
+#endif
+
+/*
+** Given a btree page and a cell index (0 means the first cell on
+** the page, 1 means the second cell, and so forth) return a pointer
+** to the cell content.
+**
+** findCellPastPtr() does the same except it skips past the initial
+** 4-byte child pointer found on interior pages, if there is one.
+**
+** This routine works only for pages that do not contain overflow cells.
+*/
+#define findCell(P,I) \
+ ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
+#define findCellPastPtr(P,I) \
+ ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
+
+
+/*
+** This is common tail processing for btreeParseCellPtr() and
+** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
+** on a single B-tree page. Make necessary adjustments to the CellInfo
+** structure.
+*/
+static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
+ MemPage *pPage, /* Page containing the cell */
+ u8 *pCell, /* Pointer to the cell text. */
+ CellInfo *pInfo /* Fill in this structure */
+){
+ /* If the payload will not fit completely on the local page, we have
+ ** to decide how much to store locally and how much to spill onto
+ ** overflow pages. The strategy is to minimize the amount of unused
+ ** space on overflow pages while keeping the amount of local storage
+ ** in between minLocal and maxLocal.
+ **
+ ** Warning: changing the way overflow payload is distributed in any
+ ** way will result in an incompatible file format.
+ */
+ int minLocal; /* Minimum amount of payload held locally */
+ int maxLocal; /* Maximum amount of payload held locally */
+ int surplus; /* Overflow payload available for local storage */
+
+ minLocal = pPage->minLocal;
+ maxLocal = pPage->maxLocal;
+ surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
+ testcase( surplus==maxLocal );
+ testcase( surplus==maxLocal+1 );
+ if( surplus <= maxLocal ){
+ pInfo->nLocal = (u16)surplus;
+ }else{
+ pInfo->nLocal = (u16)minLocal;
+ }
+ pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
+}
+
+/*
+** The following routines are implementations of the MemPage.xParseCell()
+** method.
+**
+** Parse a cell content block and fill in the CellInfo structure.
+**
+** btreeParseCellPtr() => table btree leaf nodes
+** btreeParseCellNoPayload() => table btree internal nodes
+** btreeParseCellPtrIndex() => index btree nodes
+**
+** There is also a wrapper function btreeParseCell() that works for
+** all MemPage types and that references the cell by index rather than
+** by pointer.
+*/
+static void btreeParseCellPtrNoPayload(
+ MemPage *pPage, /* Page containing the cell */
+ u8 *pCell, /* Pointer to the cell text. */
+ CellInfo *pInfo /* Fill in this structure */
+){
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ assert( pPage->leaf==0 );
+ assert( pPage->childPtrSize==4 );
+#ifndef SQLITE_DEBUG
+ UNUSED_PARAMETER(pPage);
+#endif
+ pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
+ pInfo->nPayload = 0;
+ pInfo->nLocal = 0;
+ pInfo->pPayload = 0;
+ return;
+}
+static void btreeParseCellPtr(
+ MemPage *pPage, /* Page containing the cell */
+ u8 *pCell, /* Pointer to the cell text. */
+ CellInfo *pInfo /* Fill in this structure */
+){
+ u8 *pIter; /* For scanning through pCell */
+ u32 nPayload; /* Number of bytes of cell payload */
+ u64 iKey; /* Extracted Key value */
+
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ assert( pPage->leaf==0 || pPage->leaf==1 );
+ assert( pPage->intKeyLeaf );
+ assert( pPage->childPtrSize==0 );
+ pIter = pCell;
+
+ /* The next block of code is equivalent to:
+ **
+ ** pIter += getVarint32(pIter, nPayload);
+ **
+ ** The code is inlined to avoid a function call.
+ */
+ nPayload = *pIter;
+ if( nPayload>=0x80 ){
+ u8 *pEnd = &pIter[8];
+ nPayload &= 0x7f;
+ do{
+ nPayload = (nPayload<<7) | (*++pIter & 0x7f);
+ }while( (*pIter)>=0x80 && pIter<pEnd );
+ }
+ pIter++;
+
+ /* The next block of code is equivalent to:
+ **
+ ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
+ **
+ ** The code is inlined to avoid a function call.
+ */
+ iKey = *pIter;
+ if( iKey>=0x80 ){
+ u8 *pEnd = &pIter[7];
+ iKey &= 0x7f;
+ while(1){
+ iKey = (iKey<<7) | (*++pIter & 0x7f);
+ if( (*pIter)<0x80 ) break;
+ if( pIter>=pEnd ){
+ iKey = (iKey<<8) | *++pIter;
+ break;
+ }
+ }
+ }
+ pIter++;
+
+ pInfo->nKey = *(i64*)&iKey;
+ pInfo->nPayload = nPayload;
+ pInfo->pPayload = pIter;
+ testcase( nPayload==pPage->maxLocal );
+ testcase( nPayload==pPage->maxLocal+1 );
+ if( nPayload<=pPage->maxLocal ){
+ /* This is the (easy) common case where the entire payload fits
+ ** on the local page. No overflow is required.
+ */
+ pInfo->nSize = nPayload + (u16)(pIter - pCell);
+ if( pInfo->nSize<4 ) pInfo->nSize = 4;
+ pInfo->nLocal = (u16)nPayload;
+ }else{
+ btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
+ }
+}
+static void btreeParseCellPtrIndex(
+ MemPage *pPage, /* Page containing the cell */
+ u8 *pCell, /* Pointer to the cell text. */
+ CellInfo *pInfo /* Fill in this structure */
+){
+ u8 *pIter; /* For scanning through pCell */
+ u32 nPayload; /* Number of bytes of cell payload */
+
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ assert( pPage->leaf==0 || pPage->leaf==1 );
+ assert( pPage->intKeyLeaf==0 );
+ pIter = pCell + pPage->childPtrSize;
+ nPayload = *pIter;
+ if( nPayload>=0x80 ){
+ u8 *pEnd = &pIter[8];
+ nPayload &= 0x7f;
+ do{
+ nPayload = (nPayload<<7) | (*++pIter & 0x7f);
+ }while( *(pIter)>=0x80 && pIter<pEnd );
+ }
+ pIter++;
+ pInfo->nKey = nPayload;
+ pInfo->nPayload = nPayload;
+ pInfo->pPayload = pIter;
+ testcase( nPayload==pPage->maxLocal );
+ testcase( nPayload==pPage->maxLocal+1 );
+ if( nPayload<=pPage->maxLocal ){
+ /* This is the (easy) common case where the entire payload fits
+ ** on the local page. No overflow is required.
+ */
+ pInfo->nSize = nPayload + (u16)(pIter - pCell);
+ if( pInfo->nSize<4 ) pInfo->nSize = 4;
+ pInfo->nLocal = (u16)nPayload;
+ }else{
+ btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
+ }
+}
+static void btreeParseCell(
+ MemPage *pPage, /* Page containing the cell */
+ int iCell, /* The cell index. First cell is 0 */
+ CellInfo *pInfo /* Fill in this structure */
+){
+ pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
+}
+
+/*
+** The following routines are implementations of the MemPage.xCellSize
+** method.
+**
+** Compute the total number of bytes that a Cell needs in the cell
+** data area of the btree-page. The return number includes the cell
+** data header and the local payload, but not any overflow page or
+** the space used by the cell pointer.
+**
+** cellSizePtrNoPayload() => table internal nodes
+** cellSizePtr() => all index nodes & table leaf nodes
+*/
+static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
+ u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
+ u8 *pEnd; /* End mark for a varint */
+ u32 nSize; /* Size value to return */
+
+#ifdef SQLITE_DEBUG
+ /* The value returned by this function should always be the same as
+ ** the (CellInfo.nSize) value found by doing a full parse of the
+ ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
+ ** this function verifies that this invariant is not violated. */
+ CellInfo debuginfo;
+ pPage->xParseCell(pPage, pCell, &debuginfo);
+#endif
+
+ nSize = *pIter;
+ if( nSize>=0x80 ){
+ pEnd = &pIter[8];
+ nSize &= 0x7f;
+ do{
+ nSize = (nSize<<7) | (*++pIter & 0x7f);
+ }while( *(pIter)>=0x80 && pIter<pEnd );
+ }
+ pIter++;
+ if( pPage->intKey ){
+ /* pIter now points at the 64-bit integer key value, a variable length
+ ** integer. The following block moves pIter to point at the first byte
+ ** past the end of the key value. */
+ pEnd = &pIter[9];
+ while( (*pIter++)&0x80 && pIter<pEnd );
+ }
+ testcase( nSize==pPage->maxLocal );
+ testcase( nSize==pPage->maxLocal+1 );
+ if( nSize<=pPage->maxLocal ){
+ nSize += (u32)(pIter - pCell);
+ if( nSize<4 ) nSize = 4;
+ }else{
+ int minLocal = pPage->minLocal;
+ nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
+ testcase( nSize==pPage->maxLocal );
+ testcase( nSize==pPage->maxLocal+1 );
+ if( nSize>pPage->maxLocal ){
+ nSize = minLocal;
+ }
+ nSize += 4 + (u16)(pIter - pCell);
+ }
+ assert( nSize==debuginfo.nSize || CORRUPT_DB );
+ return (u16)nSize;
+}
+static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
+ u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
+ u8 *pEnd; /* End mark for a varint */
+
+#ifdef SQLITE_DEBUG
+ /* The value returned by this function should always be the same as
+ ** the (CellInfo.nSize) value found by doing a full parse of the
+ ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
+ ** this function verifies that this invariant is not violated. */
+ CellInfo debuginfo;
+ pPage->xParseCell(pPage, pCell, &debuginfo);
+#else
+ UNUSED_PARAMETER(pPage);
+#endif
+
+ assert( pPage->childPtrSize==4 );
+ pEnd = pIter + 9;
+ while( (*pIter++)&0x80 && pIter<pEnd );
+ assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
+ return (u16)(pIter - pCell);
+}
+
+
+#ifdef SQLITE_DEBUG
+/* This variation on cellSizePtr() is used inside of assert() statements
+** only. */
+static u16 cellSize(MemPage *pPage, int iCell){
+ return pPage->xCellSize(pPage, findCell(pPage, iCell));
+}
+#endif
+
+#ifndef SQLITE_OMIT_AUTOVACUUM
+/*
+** The cell pCell is currently part of page pSrc but will ultimately be part
+** of pPage. (pSrc and pPager are often the same.) If pCell contains a
+** pointer to an overflow page, insert an entry into the pointer-map for
+** the overflow page that will be valid after pCell has been moved to pPage.
+*/
+static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
+ CellInfo info;
+ if( *pRC ) return;
+ assert( pCell!=0 );
+ pPage->xParseCell(pPage, pCell, &info);
+ if( info.nLocal<info.nPayload ){
+ Pgno ovfl;
+ if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
+ testcase( pSrc!=pPage );
+ *pRC = SQLITE_CORRUPT_BKPT;
+ return;
+ }
+ ovfl = get4byte(&pCell[info.nSize-4]);
+ ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
+ }
+}
+#endif
+
+
+/*
+** Defragment the page given. This routine reorganizes cells within the
+** page so that there are no free-blocks on the free-block list.
+**
+** Parameter nMaxFrag is the maximum amount of fragmented space that may be
+** present in the page after this routine returns.
+**
+** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
+** b-tree page so that there are no freeblocks or fragment bytes, all
+** unused bytes are contained in the unallocated space region, and all
+** cells are packed tightly at the end of the page.
+*/
+static int defragmentPage(MemPage *pPage, int nMaxFrag){
+ int i; /* Loop counter */
+ int pc; /* Address of the i-th cell */
+ int hdr; /* Offset to the page header */
+ int size; /* Size of a cell */
+ int usableSize; /* Number of usable bytes on a page */
+ int cellOffset; /* Offset to the cell pointer array */
+ int cbrk; /* Offset to the cell content area */
+ int nCell; /* Number of cells on the page */
+ unsigned char *data; /* The page data */
+ unsigned char *temp; /* Temp area for cell content */
+ unsigned char *src; /* Source of content */
+ int iCellFirst; /* First allowable cell index */
+ int iCellLast; /* Last possible cell index */
+
+ assert( sqlite3PagerIswriteable(pPage->pDbPage) );
+ assert( pPage->pBt!=0 );
+ assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
+ assert( pPage->nOverflow==0 );
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ temp = 0;
+ src = data = pPage->aData;
+ hdr = pPage->hdrOffset;
+ cellOffset = pPage->cellOffset;
+ nCell = pPage->nCell;
+ assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
+ iCellFirst = cellOffset + 2*nCell;
+ usableSize = pPage->pBt->usableSize;
+
+ /* This block handles pages with two or fewer free blocks and nMaxFrag
+ ** or fewer fragmented bytes. In this case it is faster to move the
+ ** two (or one) blocks of cells using memmove() and add the required
+ ** offsets to each pointer in the cell-pointer array than it is to
+ ** reconstruct the entire page. */
+ if( (int)data[hdr+7]<=nMaxFrag ){
+ int iFree = get2byte(&data[hdr+1]);
+ if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
+ if( iFree ){
+ int iFree2 = get2byte(&data[iFree]);
+ if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
+ if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
+ u8 *pEnd = &data[cellOffset + nCell*2];
+ u8 *pAddr;
+ int sz2 = 0;
+ int sz = get2byte(&data[iFree+2]);
+ int top = get2byte(&data[hdr+5]);
+ if( top>=iFree ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ if( iFree2 ){
+ if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
+ sz2 = get2byte(&data[iFree2+2]);
+ if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
+ memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
+ sz += sz2;
+ }else if( NEVER(iFree+sz>usableSize) ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+
+ cbrk = top+sz;
+ assert( cbrk+(iFree-top) <= usableSize );
+ memmove(&data[cbrk], &data[top], iFree-top);
+ for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
+ pc = get2byte(pAddr);
+ if( pc<iFree ){ put2byte(pAddr, pc+sz); }
+ else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
+ }
+ goto defragment_out;
+ }
+ }
+ }
+
+ cbrk = usableSize;
+ iCellLast = usableSize - 4;
+ for(i=0; i<nCell; i++){
+ u8 *pAddr; /* The i-th cell pointer */
+ pAddr = &data[cellOffset + i*2];
+ pc = get2byte(pAddr);
+ testcase( pc==iCellFirst );
+ testcase( pc==iCellLast );
+ /* These conditions have already been verified in btreeInitPage()
+ ** if PRAGMA cell_size_check=ON.
+ */
+ if( pc<iCellFirst || pc>iCellLast ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ assert( pc>=iCellFirst && pc<=iCellLast );
+ size = pPage->xCellSize(pPage, &src[pc]);
+ cbrk -= size;
+ if( cbrk<iCellFirst || pc+size>usableSize ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
+ testcase( cbrk+size==usableSize );
+ testcase( pc+size==usableSize );
+ put2byte(pAddr, cbrk);
+ if( temp==0 ){
+ int x;
+ if( cbrk==pc ) continue;
+ temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
+ x = get2byte(&data[hdr+5]);
+ memcpy(&temp[x], &data[x], (cbrk+size) - x);
+ src = temp;
+ }
+ memcpy(&data[cbrk], &src[pc], size);
+ }
+ data[hdr+7] = 0;
+
+ defragment_out:
+ assert( pPage->nFree>=0 );
+ if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ assert( cbrk>=iCellFirst );
+ put2byte(&data[hdr+5], cbrk);
+ data[hdr+1] = 0;
+ data[hdr+2] = 0;
+ memset(&data[iCellFirst], 0, cbrk-iCellFirst);
+ assert( sqlite3PagerIswriteable(pPage->pDbPage) );
+ return SQLITE_OK;
+}
+
+/*
+** Search the free-list on page pPg for space to store a cell nByte bytes in
+** size. If one can be found, return a pointer to the space and remove it
+** from the free-list.
+**
+** If no suitable space can be found on the free-list, return NULL.
+**
+** This function may detect corruption within pPg. If corruption is
+** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
+**
+** Slots on the free list that are between 1 and 3 bytes larger than nByte
+** will be ignored if adding the extra space to the fragmentation count
+** causes the fragmentation count to exceed 60.
+*/
+static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
+ const int hdr = pPg->hdrOffset; /* Offset to page header */
+ u8 * const aData = pPg->aData; /* Page data */
+ int iAddr = hdr + 1; /* Address of ptr to pc */
+ int pc = get2byte(&aData[iAddr]); /* Address of a free slot */
+ int x; /* Excess size of the slot */
+ int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */
+ int size; /* Size of the free slot */
+
+ assert( pc>0 );
+ while( pc<=maxPC ){
+ /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
+ ** freeblock form a big-endian integer which is the size of the freeblock
+ ** in bytes, including the 4-byte header. */
+ size = get2byte(&aData[pc+2]);
+ if( (x = size - nByte)>=0 ){
+ testcase( x==4 );
+ testcase( x==3 );
+ if( x<4 ){
+ /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
+ ** number of bytes in fragments may not exceed 60. */
+ if( aData[hdr+7]>57 ) return 0;
+
+ /* Remove the slot from the free-list. Update the number of
+ ** fragmented bytes within the page. */
+ memcpy(&aData[iAddr], &aData[pc], 2);
+ aData[hdr+7] += (u8)x;
+ }else if( x+pc > maxPC ){
+ /* This slot extends off the end of the usable part of the page */
+ *pRc = SQLITE_CORRUPT_PAGE(pPg);
+ return 0;
+ }else{
+ /* The slot remains on the free-list. Reduce its size to account
+ ** for the portion used by the new allocation. */
+ put2byte(&aData[pc+2], x);
+ }
+ return &aData[pc + x];
+ }
+ iAddr = pc;
+ pc = get2byte(&aData[pc]);
+ if( pc<=iAddr+size ){
+ if( pc ){
+ /* The next slot in the chain is not past the end of the current slot */
+ *pRc = SQLITE_CORRUPT_PAGE(pPg);
+ }
+ return 0;
+ }
+ }
+ if( pc>maxPC+nByte-4 ){
+ /* The free slot chain extends off the end of the page */
+ *pRc = SQLITE_CORRUPT_PAGE(pPg);
+ }
+ return 0;
+}
+
+/*
+** Allocate nByte bytes of space from within the B-Tree page passed
+** as the first argument. Write into *pIdx the index into pPage->aData[]
+** of the first byte of allocated space. Return either SQLITE_OK or
+** an error code (usually SQLITE_CORRUPT).
+**
+** The caller guarantees that there is sufficient space to make the
+** allocation. This routine might need to defragment in order to bring
+** all the space together, however. This routine will avoid using
+** the first two bytes past the cell pointer area since presumably this
+** allocation is being made in order to insert a new cell, so we will
+** also end up needing a new cell pointer.
+*/
+static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
+ const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
+ u8 * const data = pPage->aData; /* Local cache of pPage->aData */
+ int top; /* First byte of cell content area */
+ int rc = SQLITE_OK; /* Integer return code */
+ int gap; /* First byte of gap between cell pointers and cell content */
+
+ assert( sqlite3PagerIswriteable(pPage->pDbPage) );
+ assert( pPage->pBt );
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ assert( nByte>=0 ); /* Minimum cell size is 4 */
+ assert( pPage->nFree>=nByte );
+ assert( pPage->nOverflow==0 );
+ assert( nByte < (int)(pPage->pBt->usableSize-8) );
+
+ assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
+ gap = pPage->cellOffset + 2*pPage->nCell;
+ assert( gap<=65536 );
+ /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
+ ** and the reserved space is zero (the usual value for reserved space)
+ ** then the cell content offset of an empty page wants to be 65536.
+ ** However, that integer is too large to be stored in a 2-byte unsigned
+ ** integer, so a value of 0 is used in its place. */
+ top = get2byte(&data[hdr+5]);
+ assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */
+ if( gap>top ){
+ if( top==0 && pPage->pBt->usableSize==65536 ){
+ top = 65536;
+ }else{
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ }
+
+ /* If there is enough space between gap and top for one more cell pointer,
+ ** and if the freelist is not empty, then search the
+ ** freelist looking for a slot big enough to satisfy the request.
+ */
+ testcase( gap+2==top );
+ testcase( gap+1==top );
+ testcase( gap==top );
+ if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
+ u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
+ if( pSpace ){
+ int g2;
+ assert( pSpace+nByte<=data+pPage->pBt->usableSize );
+ *pIdx = g2 = (int)(pSpace-data);
+ if( NEVER(g2<=gap) ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }else{
+ return SQLITE_OK;
+ }
+ }else if( rc ){
+ return rc;
+ }
+ }
+
+ /* The request could not be fulfilled using a freelist slot. Check
+ ** to see if defragmentation is necessary.
+ */
+ testcase( gap+2+nByte==top );
+ if( gap+2+nByte>top ){
+ assert( pPage->nCell>0 || CORRUPT_DB );
+ assert( pPage->nFree>=0 );
+ rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
+ if( rc ) return rc;
+ top = get2byteNotZero(&data[hdr+5]);
+ assert( gap+2+nByte<=top );
+ }
+
+
+ /* Allocate memory from the gap in between the cell pointer array
+ ** and the cell content area. The btreeComputeFreeSpace() call has already
+ ** validated the freelist. Given that the freelist is valid, there
+ ** is no way that the allocation can extend off the end of the page.
+ ** The assert() below verifies the previous sentence.
+ */
+ top -= nByte;
+ put2byte(&data[hdr+5], top);
+ assert( top+nByte <= (int)pPage->pBt->usableSize );
+ *pIdx = top;
+ return SQLITE_OK;
+}
+
+/*
+** Return a section of the pPage->aData to the freelist.
+** The first byte of the new free block is pPage->aData[iStart]
+** and the size of the block is iSize bytes.
+**
+** Adjacent freeblocks are coalesced.
+**
+** Even though the freeblock list was checked by btreeComputeFreeSpace(),
+** that routine will not detect overlap between cells or freeblocks. Nor
+** does it detect cells or freeblocks that encrouch into the reserved bytes
+** at the end of the page. So do additional corruption checks inside this
+** routine and return SQLITE_CORRUPT if any problems are found.
+*/
+static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
+ u16 iPtr; /* Address of ptr to next freeblock */
+ u16 iFreeBlk; /* Address of the next freeblock */
+ u8 hdr; /* Page header size. 0 or 100 */
+ u8 nFrag = 0; /* Reduction in fragmentation */
+ u16 iOrigSize = iSize; /* Original value of iSize */
+ u16 x; /* Offset to cell content area */
+ u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
+ unsigned char *data = pPage->aData; /* Page content */
+
+ assert( pPage->pBt!=0 );
+ assert( sqlite3PagerIswriteable(pPage->pDbPage) );
+ assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
+ assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ assert( iSize>=4 ); /* Minimum cell size is 4 */
+ assert( iStart<=pPage->pBt->usableSize-4 );
+
+ /* The list of freeblocks must be in ascending order. Find the
+ ** spot on the list where iStart should be inserted.
+ */
+ hdr = pPage->hdrOffset;
+ iPtr = hdr + 1;
+ if( data[iPtr+1]==0 && data[iPtr]==0 ){
+ iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
+ }else{
+ while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
+ if( iFreeBlk<iPtr+4 ){
+ if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ iPtr = iFreeBlk;
+ }
+ if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ assert( iFreeBlk>iPtr || iFreeBlk==0 );
+
+ /* At this point:
+ ** iFreeBlk: First freeblock after iStart, or zero if none
+ ** iPtr: The address of a pointer to iFreeBlk
+ **
+ ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
+ */
+ if( iFreeBlk && iEnd+3>=iFreeBlk ){
+ nFrag = iFreeBlk - iEnd;
+ if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
+ iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
+ if( iEnd > pPage->pBt->usableSize ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ iSize = iEnd - iStart;
+ iFreeBlk = get2byte(&data[iFreeBlk]);
+ }
+
+ /* If iPtr is another freeblock (that is, if iPtr is not the freelist
+ ** pointer in the page header) then check to see if iStart should be
+ ** coalesced onto the end of iPtr.
+ */
+ if( iPtr>hdr+1 ){
+ int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
+ if( iPtrEnd+3>=iStart ){
+ if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
+ nFrag += iStart - iPtrEnd;
+ iSize = iEnd - iPtr;
+ iStart = iPtr;
+ }
+ }
+ if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
+ data[hdr+7] -= nFrag;
+ }
+ x = get2byte(&data[hdr+5]);
+ if( iStart<=x ){
+ /* The new freeblock is at the beginning of the cell content area,
+ ** so just extend the cell content area rather than create another
+ ** freelist entry */
+ if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
+ if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
+ put2byte(&data[hdr+1], iFreeBlk);
+ put2byte(&data[hdr+5], iEnd);
+ }else{
+ /* Insert the new freeblock into the freelist */
+ put2byte(&data[iPtr], iStart);
+ }
+ if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
+ /* Overwrite deleted information with zeros when the secure_delete
+ ** option is enabled */
+ memset(&data[iStart], 0, iSize);
+ }
+ put2byte(&data[iStart], iFreeBlk);
+ put2byte(&data[iStart+2], iSize);
+ pPage->nFree += iOrigSize;
+ return SQLITE_OK;
+}
+
+/*
+** Decode the flags byte (the first byte of the header) for a page
+** and initialize fields of the MemPage structure accordingly.
+**
+** Only the following combinations are supported. Anything different
+** indicates a corrupt database files:
+**
+** PTF_ZERODATA
+** PTF_ZERODATA | PTF_LEAF
+** PTF_LEAFDATA | PTF_INTKEY
+** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
+*/
+static int decodeFlags(MemPage *pPage, int flagByte){
+ BtShared *pBt; /* A copy of pPage->pBt */
+
+ assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
+ flagByte &= ~PTF_LEAF;
+ pPage->childPtrSize = 4-4*pPage->leaf;
+ pPage->xCellSize = cellSizePtr;
+ pBt = pPage->pBt;
+ if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
+ /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
+ ** interior table b-tree page. */
+ assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
+ /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
+ ** leaf table b-tree page. */
+ assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
+ pPage->intKey = 1;
+ if( pPage->leaf ){
+ pPage->intKeyLeaf = 1;
+ pPage->xParseCell = btreeParseCellPtr;
+ }else{
+ pPage->intKeyLeaf = 0;
+ pPage->xCellSize = cellSizePtrNoPayload;
+ pPage->xParseCell = btreeParseCellPtrNoPayload;
+ }
+ pPage->maxLocal = pBt->maxLeaf;
+ pPage->minLocal = pBt->minLeaf;
+ }else if( flagByte==PTF_ZERODATA ){
+ /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
+ ** interior index b-tree page. */
+ assert( (PTF_ZERODATA)==2 );
+ /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
+ ** leaf index b-tree page. */
+ assert( (PTF_ZERODATA|PTF_LEAF)==10 );
+ pPage->intKey = 0;
+ pPage->intKeyLeaf = 0;
+ pPage->xParseCell = btreeParseCellPtrIndex;
+ pPage->maxLocal = pBt->maxLocal;
+ pPage->minLocal = pBt->minLocal;
+ }else{
+ /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
+ ** an error. */
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ pPage->max1bytePayload = pBt->max1bytePayload;
+ return SQLITE_OK;
+}
+
+/*
+** Compute the amount of freespace on the page. In other words, fill
+** in the pPage->nFree field.
+*/
+static int btreeComputeFreeSpace(MemPage *pPage){
+ int pc; /* Address of a freeblock within pPage->aData[] */
+ u8 hdr; /* Offset to beginning of page header */
+ u8 *data; /* Equal to pPage->aData */
+ int usableSize; /* Amount of usable space on each page */
+ int nFree; /* Number of unused bytes on the page */
+ int top; /* First byte of the cell content area */
+ int iCellFirst; /* First allowable cell or freeblock offset */
+ int iCellLast; /* Last possible cell or freeblock offset */
+
+ assert( pPage->pBt!=0 );
+ assert( pPage->pBt->db!=0 );
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
+ assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
+ assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
+ assert( pPage->isInit==1 );
+ assert( pPage->nFree<0 );
+
+ usableSize = pPage->pBt->usableSize;
+ hdr = pPage->hdrOffset;
+ data = pPage->aData;
+ /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
+ ** the start of the cell content area. A zero value for this integer is
+ ** interpreted as 65536. */
+ top = get2byteNotZero(&data[hdr+5]);
+ iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
+ iCellLast = usableSize - 4;
+
+ /* Compute the total free space on the page
+ ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
+ ** start of the first freeblock on the page, or is zero if there are no
+ ** freeblocks. */
+ pc = get2byte(&data[hdr+1]);
+ nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
+ if( pc>0 ){
+ u32 next, size;
+ if( pc<top ){
+ /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
+ ** always be at least one cell before the first freeblock.
+ */
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ while( 1 ){
+ if( pc>iCellLast ){
+ /* Freeblock off the end of the page */
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ next = get2byte(&data[pc]);
+ size = get2byte(&data[pc+2]);
+ nFree = nFree + size;
+ if( next<=pc+size+3 ) break;
+ pc = next;
+ }
+ if( next>0 ){
+ /* Freeblock not in ascending order */
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ if( pc+size>(unsigned int)usableSize ){
+ /* Last freeblock extends past page end */
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ }
+
+ /* At this point, nFree contains the sum of the offset to the start
+ ** of the cell-content area plus the number of free bytes within
+ ** the cell-content area. If this is greater than the usable-size
+ ** of the page, then the page must be corrupted. This check also
+ ** serves to verify that the offset to the start of the cell-content
+ ** area, according to the page header, lies within the page.
+ */
+ if( nFree>usableSize || nFree<iCellFirst ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ pPage->nFree = (u16)(nFree - iCellFirst);
+ return SQLITE_OK;
+}
+
+/*
+** Do additional sanity check after btreeInitPage() if
+** PRAGMA cell_size_check=ON
+*/
+static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
+ int iCellFirst; /* First allowable cell or freeblock offset */
+ int iCellLast; /* Last possible cell or freeblock offset */
+ int i; /* Index into the cell pointer array */
+ int sz; /* Size of a cell */
+ int pc; /* Address of a freeblock within pPage->aData[] */
+ u8 *data; /* Equal to pPage->aData */
+ int usableSize; /* Maximum usable space on the page */
+ int cellOffset; /* Start of cell content area */
+
+ iCellFirst = pPage->cellOffset + 2*pPage->nCell;
+ usableSize = pPage->pBt->usableSize;
+ iCellLast = usableSize - 4;
+ data = pPage->aData;
+ cellOffset = pPage->cellOffset;
+ if( !pPage->leaf ) iCellLast--;
+ for(i=0; i<pPage->nCell; i++){
+ pc = get2byteAligned(&data[cellOffset+i*2]);
+ testcase( pc==iCellFirst );
+ testcase( pc==iCellLast );
+ if( pc<iCellFirst || pc>iCellLast ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ sz = pPage->xCellSize(pPage, &data[pc]);
+ testcase( pc+sz==usableSize );
+ if( pc+sz>usableSize ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Initialize the auxiliary information for a disk block.
+**
+** Return SQLITE_OK on success. If we see that the page does
+** not contain a well-formed database page, then return
+** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
+** guarantee that the page is well-formed. It only shows that
+** we failed to detect any corruption.
+*/
+static int btreeInitPage(MemPage *pPage){
+ u8 *data; /* Equal to pPage->aData */
+ BtShared *pBt; /* The main btree structure */
+
+ assert( pPage->pBt!=0 );
+ assert( pPage->pBt->db!=0 );
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
+ assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
+ assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
+ assert( pPage->isInit==0 );
+
+ pBt = pPage->pBt;
+ data = pPage->aData + pPage->hdrOffset;
+ /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
+ ** the b-tree page type. */
+ if( decodeFlags(pPage, data[0]) ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
+ pPage->maskPage = (u16)(pBt->pageSize - 1);
+ pPage->nOverflow = 0;
+ pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
+ pPage->aCellIdx = data + pPage->childPtrSize + 8;
+ pPage->aDataEnd = pPage->aData + pBt->usableSize;
+ pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
+ /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
+ ** number of cells on the page. */
+ pPage->nCell = get2byte(&data[3]);
+ if( pPage->nCell>MX_CELL(pBt) ){
+ /* To many cells for a single page. The page must be corrupt */
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ testcase( pPage->nCell==MX_CELL(pBt) );
+ /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
+ ** possible for a root page of a table that contains no rows) then the
+ ** offset to the cell content area will equal the page size minus the
+ ** bytes of reserved space. */
+ assert( pPage->nCell>0
+ || get2byteNotZero(&data[5])==(int)pBt->usableSize
+ || CORRUPT_DB );
+ pPage->nFree = -1; /* Indicate that this value is yet uncomputed */
+ pPage->isInit = 1;
+ if( pBt->db->flags & SQLITE_CellSizeCk ){
+ return btreeCellSizeCheck(pPage);
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Set up a raw page so that it looks like a database page holding
+** no entries.
+*/
+static void zeroPage(MemPage *pPage, int flags){
+ unsigned char *data = pPage->aData;
+ BtShared *pBt = pPage->pBt;
+ u8 hdr = pPage->hdrOffset;
+ u16 first;
+
+ assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
+ assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
+ assert( sqlite3PagerGetData(pPage->pDbPage) == data );
+ assert( sqlite3PagerIswriteable(pPage->pDbPage) );
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ if( pBt->btsFlags & BTS_FAST_SECURE ){
+ memset(&data[hdr], 0, pBt->usableSize - hdr);
+ }
+ data[hdr] = (char)flags;
+ first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
+ memset(&data[hdr+1], 0, 4);
+ data[hdr+7] = 0;
+ put2byte(&data[hdr+5], pBt->usableSize);
+ pPage->nFree = (u16)(pBt->usableSize - first);
+ decodeFlags(pPage, flags);
+ pPage->cellOffset = first;
+ pPage->aDataEnd = &data[pBt->usableSize];
+ pPage->aCellIdx = &data[first];
+ pPage->aDataOfst = &data[pPage->childPtrSize];
+ pPage->nOverflow = 0;
+ assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
+ pPage->maskPage = (u16)(pBt->pageSize - 1);
+ pPage->nCell = 0;
+ pPage->isInit = 1;
+}
+
+
+/*
+** Convert a DbPage obtained from the pager into a MemPage used by
+** the btree layer.
+*/
+static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
+ MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
+ if( pgno!=pPage->pgno ){
+ pPage->aData = sqlite3PagerGetData(pDbPage);
+ pPage->pDbPage = pDbPage;
+ pPage->pBt = pBt;
+ pPage->pgno = pgno;
+ pPage->hdrOffset = pgno==1 ? 100 : 0;
+ }
+ assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
+ return pPage;
+}
+
+/*
+** Get a page from the pager. Initialize the MemPage.pBt and
+** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
+**
+** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
+** about the content of the page at this time. So do not go to the disk
+** to fetch the content. Just fill in the content with zeros for now.
+** If in the future we call sqlite3PagerWrite() on this page, that
+** means we have started to be concerned about content and the disk
+** read should occur at that point.
+*/
+static int btreeGetPage(
+ BtShared *pBt, /* The btree */
+ Pgno pgno, /* Number of the page to fetch */
+ MemPage **ppPage, /* Return the page in this parameter */
+ int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
+){
+ int rc;
+ DbPage *pDbPage;
+
+ assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
+ if( rc ) return rc;
+ *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
+ return SQLITE_OK;
+}
+
+/*
+** Retrieve a page from the pager cache. If the requested page is not
+** already in the pager cache return NULL. Initialize the MemPage.pBt and
+** MemPage.aData elements if needed.
+*/
+static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
+ DbPage *pDbPage;
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
+ if( pDbPage ){
+ return btreePageFromDbPage(pDbPage, pgno, pBt);
+ }
+ return 0;
+}
+
+/*
+** Return the size of the database file in pages. If there is any kind of
+** error, return ((unsigned int)-1).
+*/
+static Pgno btreePagecount(BtShared *pBt){
+ return pBt->nPage;
+}
+SQLITE_PRIVATE Pgno sqlite3BtreeLastPage(Btree *p){
+ assert( sqlite3BtreeHoldsMutex(p) );
+ return btreePagecount(p->pBt);
+}
+
+/*
+** Get a page from the pager and initialize it.
+**
+** If pCur!=0 then the page is being fetched as part of a moveToChild()
+** call. Do additional sanity checking on the page in this case.
+** And if the fetch fails, this routine must decrement pCur->iPage.
+**
+** The page is fetched as read-write unless pCur is not NULL and is
+** a read-only cursor.
+**
+** If an error occurs, then *ppPage is undefined. It
+** may remain unchanged, or it may be set to an invalid value.
+*/
+static int getAndInitPage(
+ BtShared *pBt, /* The database file */
+ Pgno pgno, /* Number of the page to get */
+ MemPage **ppPage, /* Write the page pointer here */
+ BtCursor *pCur, /* Cursor to receive the page, or NULL */
+ int bReadOnly /* True for a read-only page */
+){
+ int rc;
+ DbPage *pDbPage;
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ assert( pCur==0 || ppPage==&pCur->pPage );
+ assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
+ assert( pCur==0 || pCur->iPage>0 );
+
+ if( pgno>btreePagecount(pBt) ){
+ rc = SQLITE_CORRUPT_BKPT;
+ goto getAndInitPage_error1;
+ }
+ rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
+ if( rc ){
+ goto getAndInitPage_error1;
+ }
+ *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
+ if( (*ppPage)->isInit==0 ){
+ btreePageFromDbPage(pDbPage, pgno, pBt);
+ rc = btreeInitPage(*ppPage);
+ if( rc!=SQLITE_OK ){
+ goto getAndInitPage_error2;
+ }
+ }
+ assert( (*ppPage)->pgno==pgno );
+ assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
+
+ /* If obtaining a child page for a cursor, we must verify that the page is
+ ** compatible with the root page. */
+ if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
+ rc = SQLITE_CORRUPT_PGNO(pgno);
+ goto getAndInitPage_error2;
+ }
+ return SQLITE_OK;
+
+getAndInitPage_error2:
+ releasePage(*ppPage);
+getAndInitPage_error1:
+ if( pCur ){
+ pCur->iPage--;
+ pCur->pPage = pCur->apPage[pCur->iPage];
+ }
+ testcase( pgno==0 );
+ assert( pgno!=0 || rc==SQLITE_CORRUPT );
+ return rc;
+}
+
+/*
+** Release a MemPage. This should be called once for each prior
+** call to btreeGetPage.
+**
+** Page1 is a special case and must be released using releasePageOne().
+*/
+static void releasePageNotNull(MemPage *pPage){
+ assert( pPage->aData );
+ assert( pPage->pBt );
+ assert( pPage->pDbPage!=0 );
+ assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
+ assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ sqlite3PagerUnrefNotNull(pPage->pDbPage);
+}
+static void releasePage(MemPage *pPage){
+ if( pPage ) releasePageNotNull(pPage);
+}
+static void releasePageOne(MemPage *pPage){
+ assert( pPage!=0 );
+ assert( pPage->aData );
+ assert( pPage->pBt );
+ assert( pPage->pDbPage!=0 );
+ assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
+ assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ sqlite3PagerUnrefPageOne(pPage->pDbPage);
+}
+
+/*
+** Get an unused page.
+**
+** This works just like btreeGetPage() with the addition:
+**
+** * If the page is already in use for some other purpose, immediately
+** release it and return an SQLITE_CURRUPT error.
+** * Make sure the isInit flag is clear
+*/
+static int btreeGetUnusedPage(
+ BtShared *pBt, /* The btree */
+ Pgno pgno, /* Number of the page to fetch */
+ MemPage **ppPage, /* Return the page in this parameter */
+ int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
+){
+ int rc = btreeGetPage(pBt, pgno, ppPage, flags);
+ if( rc==SQLITE_OK ){
+ if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
+ releasePage(*ppPage);
+ *ppPage = 0;
+ return SQLITE_CORRUPT_BKPT;
+ }
+ (*ppPage)->isInit = 0;
+ }else{
+ *ppPage = 0;
+ }
+ return rc;
+}
+
+
+/*
+** During a rollback, when the pager reloads information into the cache
+** so that the cache is restored to its original state at the start of
+** the transaction, for each page restored this routine is called.
+**
+** This routine needs to reset the extra data section at the end of the
+** page to agree with the restored data.
+*/
+static void pageReinit(DbPage *pData){
+ MemPage *pPage;
+ pPage = (MemPage *)sqlite3PagerGetExtra(pData);
+ assert( sqlite3PagerPageRefcount(pData)>0 );
+ if( pPage->isInit ){
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ pPage->isInit = 0;
+ if( sqlite3PagerPageRefcount(pData)>1 ){
+ /* pPage might not be a btree page; it might be an overflow page
+ ** or ptrmap page or a free page. In those cases, the following
+ ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
+ ** But no harm is done by this. And it is very important that
+ ** btreeInitPage() be called on every btree page so we make
+ ** the call for every page that comes in for re-initing. */
+ btreeInitPage(pPage);
+ }
+ }
+}
+
+/*
+** Invoke the busy handler for a btree.
+*/
+static int btreeInvokeBusyHandler(void *pArg){
+ BtShared *pBt = (BtShared*)pArg;
+ assert( pBt->db );
+ assert( sqlite3_mutex_held(pBt->db->mutex) );
+ return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
+}
+
+/*
+** Open a database file.
+**
+** zFilename is the name of the database file. If zFilename is NULL
+** then an ephemeral database is created. The ephemeral database might
+** be exclusively in memory, or it might use a disk-based memory cache.
+** Either way, the ephemeral database will be automatically deleted
+** when sqlite3BtreeClose() is called.
+**
+** If zFilename is ":memory:" then an in-memory database is created
+** that is automatically destroyed when it is closed.
+**
+** The "flags" parameter is a bitmask that might contain bits like
+** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
+**
+** If the database is already opened in the same database connection
+** and we are in shared cache mode, then the open will fail with an
+** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
+** objects in the same database connection since doing so will lead
+** to problems with locking.
+*/
+SQLITE_PRIVATE int sqlite3BtreeOpen(
+ sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
+ const char *zFilename, /* Name of the file containing the BTree database */
+ sqlite3 *db, /* Associated database handle */
+ Btree **ppBtree, /* Pointer to new Btree object written here */
+ int flags, /* Options */
+ int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
+){
+ BtShared *pBt = 0; /* Shared part of btree structure */
+ Btree *p; /* Handle to return */
+ sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
+ int rc = SQLITE_OK; /* Result code from this function */
+ u8 nReserve; /* Byte of unused space on each page */
+ unsigned char zDbHeader[100]; /* Database header content */
+
+ /* True if opening an ephemeral, temporary database */
+ const int isTempDb = zFilename==0 || zFilename[0]==0;
+
+ /* Set the variable isMemdb to true for an in-memory database, or
+ ** false for a file-based database.
+ */
+#ifdef SQLITE_OMIT_MEMORYDB
+ const int isMemdb = 0;
+#else
+ const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
+ || (isTempDb && sqlite3TempInMemory(db))
+ || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
+#endif
+
+ assert( db!=0 );
+ assert( pVfs!=0 );
+ assert( sqlite3_mutex_held(db->mutex) );
+ assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
+
+ /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
+ assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
+
+ /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
+ assert( (flags & BTREE_SINGLE)==0 || isTempDb );
+
+ if( isMemdb ){
+ flags |= BTREE_MEMORY;
+ }
+ if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
+ vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
+ }
+ p = sqlite3MallocZero(sizeof(Btree));
+ if( !p ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ p->inTrans = TRANS_NONE;
+ p->db = db;
+#ifndef SQLITE_OMIT_SHARED_CACHE
+ p->lock.pBtree = p;
+ p->lock.iTable = 1;
+#endif
+
+#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
+ /*
+ ** If this Btree is a candidate for shared cache, try to find an
+ ** existing BtShared object that we can share with
+ */
+ if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
+ if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
+ int nFilename = sqlite3Strlen30(zFilename)+1;
+ int nFullPathname = pVfs->mxPathname+1;
+ char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
+ MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
+
+ p->sharable = 1;
+ if( !zFullPathname ){
+ sqlite3_free(p);
+ return SQLITE_NOMEM_BKPT;
+ }
+ if( isMemdb ){
+ memcpy(zFullPathname, zFilename, nFilename);
+ }else{
+ rc = sqlite3OsFullPathname(pVfs, zFilename,
+ nFullPathname, zFullPathname);
+ if( rc ){
+ if( rc==SQLITE_OK_SYMLINK ){
+ rc = SQLITE_OK;
+ }else{
+ sqlite3_free(zFullPathname);
+ sqlite3_free(p);
+ return rc;
+ }
+ }
+ }
+#if SQLITE_THREADSAFE
+ mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
+ sqlite3_mutex_enter(mutexOpen);
+ mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
+ sqlite3_mutex_enter(mutexShared);
+#endif
+ for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
+ assert( pBt->nRef>0 );
+ if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
+ && sqlite3PagerVfs(pBt->pPager)==pVfs ){
+ int iDb;
+ for(iDb=db->nDb-1; iDb>=0; iDb--){
+ Btree *pExisting = db->aDb[iDb].pBt;
+ if( pExisting && pExisting->pBt==pBt ){
+ sqlite3_mutex_leave(mutexShared);
+ sqlite3_mutex_leave(mutexOpen);
+ sqlite3_free(zFullPathname);
+ sqlite3_free(p);
+ return SQLITE_CONSTRAINT;
+ }
+ }
+ p->pBt = pBt;
+ pBt->nRef++;
+ break;
+ }
+ }
+ sqlite3_mutex_leave(mutexShared);
+ sqlite3_free(zFullPathname);
+ }
+#ifdef SQLITE_DEBUG
+ else{
+ /* In debug mode, we mark all persistent databases as sharable
+ ** even when they are not. This exercises the locking code and
+ ** gives more opportunity for asserts(sqlite3_mutex_held())
+ ** statements to find locking problems.
+ */
+ p->sharable = 1;
+ }
+#endif
+ }
+#endif
+ if( pBt==0 ){
+ /*
+ ** The following asserts make sure that structures used by the btree are
+ ** the right size. This is to guard against size changes that result
+ ** when compiling on a different architecture.
+ */
+ assert( sizeof(i64)==8 );
+ assert( sizeof(u64)==8 );
+ assert( sizeof(u32)==4 );
+ assert( sizeof(u16)==2 );
+ assert( sizeof(Pgno)==4 );
+
+ pBt = sqlite3MallocZero( sizeof(*pBt) );
+ if( pBt==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto btree_open_out;
+ }
+ rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
+ sizeof(MemPage), flags, vfsFlags, pageReinit);
+ if( rc==SQLITE_OK ){
+ sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
+ rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
+ }
+ if( rc!=SQLITE_OK ){
+ goto btree_open_out;
+ }
+ pBt->openFlags = (u8)flags;
+ pBt->db = db;
+ sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
+ p->pBt = pBt;
+
+ pBt->pCursor = 0;
+ pBt->pPage1 = 0;
+ if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
+#if defined(SQLITE_SECURE_DELETE)
+ pBt->btsFlags |= BTS_SECURE_DELETE;
+#elif defined(SQLITE_FAST_SECURE_DELETE)
+ pBt->btsFlags |= BTS_OVERWRITE;
+#endif
+ /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
+ ** determined by the 2-byte integer located at an offset of 16 bytes from
+ ** the beginning of the database file. */
+ pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
+ if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
+ || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
+ pBt->pageSize = 0;
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ /* If the magic name ":memory:" will create an in-memory database, then
+ ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
+ ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
+ ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
+ ** regular file-name. In this case the auto-vacuum applies as per normal.
+ */
+ if( zFilename && !isMemdb ){
+ pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
+ pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
+ }
+#endif
+ nReserve = 0;
+ }else{
+ /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
+ ** determined by the one-byte unsigned integer found at an offset of 20
+ ** into the database file header. */
+ nReserve = zDbHeader[20];
+ pBt->btsFlags |= BTS_PAGESIZE_FIXED;
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
+ pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
+#endif
+ }
+ rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
+ if( rc ) goto btree_open_out;
+ pBt->usableSize = pBt->pageSize - nReserve;
+ assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
+
+#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
+ /* Add the new BtShared object to the linked list sharable BtShareds.
+ */
+ pBt->nRef = 1;
+ if( p->sharable ){
+ MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
+ MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
+ if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
+ pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
+ if( pBt->mutex==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto btree_open_out;
+ }
+ }
+ sqlite3_mutex_enter(mutexShared);
+ pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
+ GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
+ sqlite3_mutex_leave(mutexShared);
+ }
+#endif
+ }
+
+#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
+ /* If the new Btree uses a sharable pBtShared, then link the new
+ ** Btree into the list of all sharable Btrees for the same connection.
+ ** The list is kept in ascending order by pBt address.
+ */
+ if( p->sharable ){
+ int i;
+ Btree *pSib;
+ for(i=0; i<db->nDb; i++){
+ if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
+ while( pSib->pPrev ){ pSib = pSib->pPrev; }
+ if( (uptr)p->pBt<(uptr)pSib->pBt ){
+ p->pNext = pSib;
+ p->pPrev = 0;
+ pSib->pPrev = p;
+ }else{
+ while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
+ pSib = pSib->pNext;
+ }
+ p->pNext = pSib->pNext;
+ p->pPrev = pSib;
+ if( p->pNext ){
+ p->pNext->pPrev = p;
+ }
+ pSib->pNext = p;
+ }
+ break;
+ }
+ }
+ }
+#endif
+ *ppBtree = p;
+
+btree_open_out:
+ if( rc!=SQLITE_OK ){
+ if( pBt && pBt->pPager ){
+ sqlite3PagerClose(pBt->pPager, 0);
+ }
+ sqlite3_free(pBt);
+ sqlite3_free(p);
+ *ppBtree = 0;
+ }else{
+ sqlite3_file *pFile;
+
+ /* If the B-Tree was successfully opened, set the pager-cache size to the
+ ** default value. Except, when opening on an existing shared pager-cache,
+ ** do not change the pager-cache size.
+ */
+ if( sqlite3BtreeSchema(p, 0, 0)==0 ){
+ sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE);
+ }
+
+ pFile = sqlite3PagerFile(pBt->pPager);
+ if( pFile->pMethods ){
+ sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
+ }
+ }
+ if( mutexOpen ){
+ assert( sqlite3_mutex_held(mutexOpen) );
+ sqlite3_mutex_leave(mutexOpen);
+ }
+ assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
+ return rc;
+}
+
+/*
+** Decrement the BtShared.nRef counter. When it reaches zero,
+** remove the BtShared structure from the sharing list. Return
+** true if the BtShared.nRef counter reaches zero and return
+** false if it is still positive.
+*/
+static int removeFromSharingList(BtShared *pBt){
+#ifndef SQLITE_OMIT_SHARED_CACHE
+ MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
+ BtShared *pList;
+ int removed = 0;
+
+ assert( sqlite3_mutex_notheld(pBt->mutex) );
+ MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
+ sqlite3_mutex_enter(pMainMtx);
+ pBt->nRef--;
+ if( pBt->nRef<=0 ){
+ if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
+ GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
+ }else{
+ pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
+ while( ALWAYS(pList) && pList->pNext!=pBt ){
+ pList=pList->pNext;
+ }
+ if( ALWAYS(pList) ){
+ pList->pNext = pBt->pNext;
+ }
+ }
+ if( SQLITE_THREADSAFE ){
+ sqlite3_mutex_free(pBt->mutex);
+ }
+ removed = 1;
+ }
+ sqlite3_mutex_leave(pMainMtx);
+ return removed;
+#else
+ return 1;
+#endif
+}
+
+/*
+** Make sure pBt->pTmpSpace points to an allocation of
+** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
+** pointer.
+*/
+static void allocateTempSpace(BtShared *pBt){
+ if( !pBt->pTmpSpace ){
+ pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
+
+ /* One of the uses of pBt->pTmpSpace is to format cells before
+ ** inserting them into a leaf page (function fillInCell()). If
+ ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
+ ** by the various routines that manipulate binary cells. Which
+ ** can mean that fillInCell() only initializes the first 2 or 3
+ ** bytes of pTmpSpace, but that the first 4 bytes are copied from
+ ** it into a database page. This is not actually a problem, but it
+ ** does cause a valgrind error when the 1 or 2 bytes of unitialized
+ ** data is passed to system call write(). So to avoid this error,
+ ** zero the first 4 bytes of temp space here.
+ **
+ ** Also: Provide four bytes of initialized space before the
+ ** beginning of pTmpSpace as an area available to prepend the
+ ** left-child pointer to the beginning of a cell.
+ */
+ if( pBt->pTmpSpace ){
+ memset(pBt->pTmpSpace, 0, 8);
+ pBt->pTmpSpace += 4;
+ }
+ }
+}
+
+/*
+** Free the pBt->pTmpSpace allocation
+*/
+static void freeTempSpace(BtShared *pBt){
+ if( pBt->pTmpSpace ){
+ pBt->pTmpSpace -= 4;
+ sqlite3PageFree(pBt->pTmpSpace);
+ pBt->pTmpSpace = 0;
+ }
+}
+
+/*
+** Close an open database and invalidate all cursors.
+*/
+SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
+ BtShared *pBt = p->pBt;
+ BtCursor *pCur;
+
+ /* Close all cursors opened via this handle. */
+ assert( sqlite3_mutex_held(p->db->mutex) );
+ sqlite3BtreeEnter(p);
+ pCur = pBt->pCursor;
+ while( pCur ){
+ BtCursor *pTmp = pCur;
+ pCur = pCur->pNext;
+ if( pTmp->pBtree==p ){
+ sqlite3BtreeCloseCursor(pTmp);
+ }
+ }
+
+ /* Rollback any active transaction and free the handle structure.
+ ** The call to sqlite3BtreeRollback() drops any table-locks held by
+ ** this handle.
+ */
+ sqlite3BtreeRollback(p, SQLITE_OK, 0);
+ sqlite3BtreeLeave(p);
+
+ /* If there are still other outstanding references to the shared-btree
+ ** structure, return now. The remainder of this procedure cleans
+ ** up the shared-btree.
+ */
+ assert( p->wantToLock==0 && p->locked==0 );
+ if( !p->sharable || removeFromSharingList(pBt) ){
+ /* The pBt is no longer on the sharing list, so we can access
+ ** it without having to hold the mutex.
+ **
+ ** Clean out and delete the BtShared object.
+ */
+ assert( !pBt->pCursor );
+ sqlite3PagerClose(pBt->pPager, p->db);
+ if( pBt->xFreeSchema && pBt->pSchema ){
+ pBt->xFreeSchema(pBt->pSchema);
+ }
+ sqlite3DbFree(0, pBt->pSchema);
+ freeTempSpace(pBt);
+ sqlite3_free(pBt);
+ }
+
+#ifndef SQLITE_OMIT_SHARED_CACHE
+ assert( p->wantToLock==0 );
+ assert( p->locked==0 );
+ if( p->pPrev ) p->pPrev->pNext = p->pNext;
+ if( p->pNext ) p->pNext->pPrev = p->pPrev;
+#endif
+
+ sqlite3_free(p);
+ return SQLITE_OK;
+}
+
+/*
+** Change the "soft" limit on the number of pages in the cache.
+** Unused and unmodified pages will be recycled when the number of
+** pages in the cache exceeds this soft limit. But the size of the
+** cache is allowed to grow larger than this limit if it contains
+** dirty pages or pages still in active use.
+*/
+SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
+ BtShared *pBt = p->pBt;
+ assert( sqlite3_mutex_held(p->db->mutex) );
+ sqlite3BtreeEnter(p);
+ sqlite3PagerSetCachesize(pBt->pPager, mxPage);
+ sqlite3BtreeLeave(p);
+ return SQLITE_OK;
+}
+
+/*
+** Change the "spill" limit on the number of pages in the cache.
+** If the number of pages exceeds this limit during a write transaction,
+** the pager might attempt to "spill" pages to the journal early in
+** order to free up memory.
+**
+** The value returned is the current spill size. If zero is passed
+** as an argument, no changes are made to the spill size setting, so
+** using mxPage of 0 is a way to query the current spill size.
+*/
+SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
+ BtShared *pBt = p->pBt;
+ int res;
+ assert( sqlite3_mutex_held(p->db->mutex) );
+ sqlite3BtreeEnter(p);
+ res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
+ sqlite3BtreeLeave(p);
+ return res;
+}
+
+#if SQLITE_MAX_MMAP_SIZE>0
+/*
+** Change the limit on the amount of the database file that may be
+** memory mapped.
+*/
+SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
+ BtShared *pBt = p->pBt;
+ assert( sqlite3_mutex_held(p->db->mutex) );
+ sqlite3BtreeEnter(p);
+ sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
+ sqlite3BtreeLeave(p);
+ return SQLITE_OK;
+}
+#endif /* SQLITE_MAX_MMAP_SIZE>0 */
+
+/*
+** Change the way data is synced to disk in order to increase or decrease
+** how well the database resists damage due to OS crashes and power
+** failures. Level 1 is the same as asynchronous (no syncs() occur and
+** there is a high probability of damage) Level 2 is the default. There
+** is a very low but non-zero probability of damage. Level 3 reduces the
+** probability of damage to near zero but with a write performance reduction.
+*/
+#ifndef SQLITE_OMIT_PAGER_PRAGMAS
+SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
+ Btree *p, /* The btree to set the safety level on */
+ unsigned pgFlags /* Various PAGER_* flags */
+){
+ BtShared *pBt = p->pBt;
+ assert( sqlite3_mutex_held(p->db->mutex) );
+ sqlite3BtreeEnter(p);
+ sqlite3PagerSetFlags(pBt->pPager, pgFlags);
+ sqlite3BtreeLeave(p);
+ return SQLITE_OK;
+}
+#endif
+
+/*
+** Change the default pages size and the number of reserved bytes per page.
+** Or, if the page size has already been fixed, return SQLITE_READONLY
+** without changing anything.
+**
+** The page size must be a power of 2 between 512 and 65536. If the page
+** size supplied does not meet this constraint then the page size is not
+** changed.
+**
+** Page sizes are constrained to be a power of two so that the region
+** of the database file used for locking (beginning at PENDING_BYTE,
+** the first byte past the 1GB boundary, 0x40000000) needs to occur
+** at the beginning of a page.
+**
+** If parameter nReserve is less than zero, then the number of reserved
+** bytes per page is left unchanged.
+**
+** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
+** and autovacuum mode can no longer be changed.
+*/
+SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
+ int rc = SQLITE_OK;
+ int x;
+ BtShared *pBt = p->pBt;
+ assert( nReserve>=0 && nReserve<=255 );
+ sqlite3BtreeEnter(p);
+ pBt->nReserveWanted = nReserve;
+ x = pBt->pageSize - pBt->usableSize;
+ if( nReserve<x ) nReserve = x;
+ if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
+ sqlite3BtreeLeave(p);
+ return SQLITE_READONLY;
+ }
+ assert( nReserve>=0 && nReserve<=255 );
+ if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
+ ((pageSize-1)&pageSize)==0 ){
+ assert( (pageSize & 7)==0 );
+ assert( !pBt->pCursor );
+ pBt->pageSize = (u32)pageSize;
+ freeTempSpace(pBt);
+ }
+ rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
+ pBt->usableSize = pBt->pageSize - (u16)nReserve;
+ if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
+ sqlite3BtreeLeave(p);
+ return rc;
+}
+
+/*
+** Return the currently defined page size
+*/
+SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
+ return p->pBt->pageSize;
+}
+
+/*
+** This function is similar to sqlite3BtreeGetReserve(), except that it
+** may only be called if it is guaranteed that the b-tree mutex is already
+** held.
+**
+** This is useful in one special case in the backup API code where it is
+** known that the shared b-tree mutex is held, but the mutex on the
+** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
+** were to be called, it might collide with some other operation on the
+** database handle that owns *p, causing undefined behavior.
+*/
+SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
+ int n;
+ assert( sqlite3_mutex_held(p->pBt->mutex) );
+ n = p->pBt->pageSize - p->pBt->usableSize;
+ return n;
+}
+
+/*
+** Return the number of bytes of space at the end of every page that
+** are intentually left unused. This is the "reserved" space that is
+** sometimes used by extensions.
+**
+** The value returned is the larger of the current reserve size and
+** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
+** The amount of reserve can only grow - never shrink.
+*/
+SQLITE_PRIVATE int sqlite3BtreeGetRequestedReserve(Btree *p){
+ int n1, n2;
+ sqlite3BtreeEnter(p);
+ n1 = (int)p->pBt->nReserveWanted;
+ n2 = sqlite3BtreeGetReserveNoMutex(p);
+ sqlite3BtreeLeave(p);
+ return n1>n2 ? n1 : n2;
+}
+
+
+/*
+** Set the maximum page count for a database if mxPage is positive.
+** No changes are made if mxPage is 0 or negative.
+** Regardless of the value of mxPage, return the maximum page count.
+*/
+SQLITE_PRIVATE Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
+ Pgno n;
+ sqlite3BtreeEnter(p);
+ n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
+ sqlite3BtreeLeave(p);
+ return n;
+}
+
+/*
+** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
+**
+** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
+** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
+** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
+** newFlag==(-1) No changes
+**
+** This routine acts as a query if newFlag is less than zero
+**
+** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
+** freelist leaf pages are not written back to the database. Thus in-page
+** deleted content is cleared, but freelist deleted content is not.
+**
+** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
+** that freelist leaf pages are written back into the database, increasing
+** the amount of disk I/O.
+*/
+SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
+ int b;
+ if( p==0 ) return 0;
+ sqlite3BtreeEnter(p);
+ assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
+ assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
+ if( newFlag>=0 ){
+ p->pBt->btsFlags &= ~BTS_FAST_SECURE;
+ p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
+ }
+ b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
+ sqlite3BtreeLeave(p);
+ return b;
+}
+
+/*
+** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
+** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
+** is disabled. The default value for the auto-vacuum property is
+** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
+*/
+SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
+#ifdef SQLITE_OMIT_AUTOVACUUM
+ return SQLITE_READONLY;
+#else
+ BtShared *pBt = p->pBt;
+ int rc = SQLITE_OK;
+ u8 av = (u8)autoVacuum;
+
+ sqlite3BtreeEnter(p);
+ if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
+ rc = SQLITE_READONLY;
+ }else{
+ pBt->autoVacuum = av ?1:0;
+ pBt->incrVacuum = av==2 ?1:0;
+ }
+ sqlite3BtreeLeave(p);
+ return rc;
+#endif
+}
+
+/*
+** Return the value of the 'auto-vacuum' property. If auto-vacuum is
+** enabled 1 is returned. Otherwise 0.
+*/
+SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
+#ifdef SQLITE_OMIT_AUTOVACUUM
+ return BTREE_AUTOVACUUM_NONE;
+#else
+ int rc;
+ sqlite3BtreeEnter(p);
+ rc = (
+ (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
+ (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
+ BTREE_AUTOVACUUM_INCR
+ );
+ sqlite3BtreeLeave(p);
+ return rc;
+#endif
+}
+
+/*
+** If the user has not set the safety-level for this database connection
+** using "PRAGMA synchronous", and if the safety-level is not already
+** set to the value passed to this function as the second parameter,
+** set it so.
+*/
+#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
+ && !defined(SQLITE_OMIT_WAL)
+static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
+ sqlite3 *db;
+ Db *pDb;
+ if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
+ while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
+ if( pDb->bSyncSet==0
+ && pDb->safety_level!=safety_level
+ && pDb!=&db->aDb[1]
+ ){
+ pDb->safety_level = safety_level;
+ sqlite3PagerSetFlags(pBt->pPager,
+ pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
+ }
+ }
+}
+#else
+# define setDefaultSyncFlag(pBt,safety_level)
+#endif
+
+/* Forward declaration */
+static int newDatabase(BtShared*);
+
+
+/*
+** Get a reference to pPage1 of the database file. This will
+** also acquire a readlock on that file.
+**
+** SQLITE_OK is returned on success. If the file is not a
+** well-formed database file, then SQLITE_CORRUPT is returned.
+** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
+** is returned if we run out of memory.
+*/
+static int lockBtree(BtShared *pBt){
+ int rc; /* Result code from subfunctions */
+ MemPage *pPage1; /* Page 1 of the database file */
+ u32 nPage; /* Number of pages in the database */
+ u32 nPageFile = 0; /* Number of pages in the database file */
+ u32 nPageHeader; /* Number of pages in the database according to hdr */
+
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ assert( pBt->pPage1==0 );
+ rc = sqlite3PagerSharedLock(pBt->pPager);
+ if( rc!=SQLITE_OK ) return rc;
+ rc = btreeGetPage(pBt, 1, &pPage1, 0);
+ if( rc!=SQLITE_OK ) return rc;
+
+ /* Do some checking to help insure the file we opened really is
+ ** a valid database file.
+ */
+ nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
+ sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
+ if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
+ nPage = nPageFile;
+ }
+ if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
+ nPage = 0;
+ }
+ if( nPage>0 ){
+ u32 pageSize;
+ u32 usableSize;
+ u8 *page1 = pPage1->aData;
+ rc = SQLITE_NOTADB;
+ /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
+ ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
+ ** 61 74 20 33 00. */
+ if( memcmp(page1, zMagicHeader, 16)!=0 ){
+ goto page1_init_failed;
+ }
+
+#ifdef SQLITE_OMIT_WAL
+ if( page1[18]>1 ){
+ pBt->btsFlags |= BTS_READ_ONLY;
+ }
+ if( page1[19]>1 ){
+ goto page1_init_failed;
+ }
+#else
+ if( page1[18]>2 ){
+ pBt->btsFlags |= BTS_READ_ONLY;
+ }
+ if( page1[19]>2 ){
+ goto page1_init_failed;
+ }
+
+ /* If the write version is set to 2, this database should be accessed
+ ** in WAL mode. If the log is not already open, open it now. Then
+ ** return SQLITE_OK and return without populating BtShared.pPage1.
+ ** The caller detects this and calls this function again. This is
+ ** required as the version of page 1 currently in the page1 buffer
+ ** may not be the latest version - there may be a newer one in the log
+ ** file.
+ */
+ if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
+ int isOpen = 0;
+ rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
+ if( rc!=SQLITE_OK ){
+ goto page1_init_failed;
+ }else{
+ setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
+ if( isOpen==0 ){
+ releasePageOne(pPage1);
+ return SQLITE_OK;
+ }
+ }
+ rc = SQLITE_NOTADB;
+ }else{
+ setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
+ }
+#endif
+
+ /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
+ ** fractions and the leaf payload fraction values must be 64, 32, and 32.
+ **
+ ** The original design allowed these amounts to vary, but as of
+ ** version 3.6.0, we require them to be fixed.
+ */
+ if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
+ goto page1_init_failed;
+ }
+ /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
+ ** determined by the 2-byte integer located at an offset of 16 bytes from
+ ** the beginning of the database file. */
+ pageSize = (page1[16]<<8) | (page1[17]<<16);
+ /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
+ ** between 512 and 65536 inclusive. */
+ if( ((pageSize-1)&pageSize)!=0
+ || pageSize>SQLITE_MAX_PAGE_SIZE
+ || pageSize<=256
+ ){
+ goto page1_init_failed;
+ }
+ pBt->btsFlags |= BTS_PAGESIZE_FIXED;
+ assert( (pageSize & 7)==0 );
+ /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
+ ** integer at offset 20 is the number of bytes of space at the end of
+ ** each page to reserve for extensions.
+ **
+ ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
+ ** determined by the one-byte unsigned integer found at an offset of 20
+ ** into the database file header. */
+ usableSize = pageSize - page1[20];
+ if( (u32)pageSize!=pBt->pageSize ){
+ /* After reading the first page of the database assuming a page size
+ ** of BtShared.pageSize, we have discovered that the page-size is
+ ** actually pageSize. Unlock the database, leave pBt->pPage1 at
+ ** zero and return SQLITE_OK. The caller will call this function
+ ** again with the correct page-size.
+ */
+ releasePageOne(pPage1);
+ pBt->usableSize = usableSize;
+ pBt->pageSize = pageSize;
+ freeTempSpace(pBt);
+ rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
+ pageSize-usableSize);
+ return rc;
+ }
+ if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){
+ rc = SQLITE_CORRUPT_BKPT;
+ goto page1_init_failed;
+ }
+ /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
+ ** be less than 480. In other words, if the page size is 512, then the
+ ** reserved space size cannot exceed 32. */
+ if( usableSize<480 ){
+ goto page1_init_failed;
+ }
+ pBt->pageSize = pageSize;
+ pBt->usableSize = usableSize;
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
+ pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
+#endif
+ }
+
+ /* maxLocal is the maximum amount of payload to store locally for
+ ** a cell. Make sure it is small enough so that at least minFanout
+ ** cells can will fit on one page. We assume a 10-byte page header.
+ ** Besides the payload, the cell must store:
+ ** 2-byte pointer to the cell
+ ** 4-byte child pointer
+ ** 9-byte nKey value
+ ** 4-byte nData value
+ ** 4-byte overflow page pointer
+ ** So a cell consists of a 2-byte pointer, a header which is as much as
+ ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
+ ** page pointer.
+ */
+ pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
+ pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
+ pBt->maxLeaf = (u16)(pBt->usableSize - 35);
+ pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
+ if( pBt->maxLocal>127 ){
+ pBt->max1bytePayload = 127;
+ }else{
+ pBt->max1bytePayload = (u8)pBt->maxLocal;
+ }
+ assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
+ pBt->pPage1 = pPage1;
+ pBt->nPage = nPage;
+ return SQLITE_OK;
+
+page1_init_failed:
+ releasePageOne(pPage1);
+ pBt->pPage1 = 0;
+ return rc;
+}
+
+#ifndef NDEBUG
+/*
+** Return the number of cursors open on pBt. This is for use
+** in assert() expressions, so it is only compiled if NDEBUG is not
+** defined.
+**
+** Only write cursors are counted if wrOnly is true. If wrOnly is
+** false then all cursors are counted.
+**
+** For the purposes of this routine, a cursor is any cursor that
+** is capable of reading or writing to the database. Cursors that
+** have been tripped into the CURSOR_FAULT state are not counted.
+*/
+static int countValidCursors(BtShared *pBt, int wrOnly){
+ BtCursor *pCur;
+ int r = 0;
+ for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
+ if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
+ && pCur->eState!=CURSOR_FAULT ) r++;
+ }
+ return r;
+}
+#endif
+
+/*
+** If there are no outstanding cursors and we are not in the middle
+** of a transaction but there is a read lock on the database, then
+** this routine unrefs the first page of the database file which
+** has the effect of releasing the read lock.
+**
+** If there is a transaction in progress, this routine is a no-op.
+*/
+static void unlockBtreeIfUnused(BtShared *pBt){
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
+ if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
+ MemPage *pPage1 = pBt->pPage1;
+ assert( pPage1->aData );
+ assert( sqlite3PagerRefcount(pBt->pPager)==1 );
+ pBt->pPage1 = 0;
+ releasePageOne(pPage1);
+ }
+}
+
+/*
+** If pBt points to an empty file then convert that empty file
+** into a new empty database by initializing the first page of
+** the database.
+*/
+static int newDatabase(BtShared *pBt){
+ MemPage *pP1;
+ unsigned char *data;
+ int rc;
+
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ if( pBt->nPage>0 ){
+ return SQLITE_OK;
+ }
+ pP1 = pBt->pPage1;
+ assert( pP1!=0 );
+ data = pP1->aData;
+ rc = sqlite3PagerWrite(pP1->pDbPage);
+ if( rc ) return rc;
+ memcpy(data, zMagicHeader, sizeof(zMagicHeader));
+ assert( sizeof(zMagicHeader)==16 );
+ data[16] = (u8)((pBt->pageSize>>8)&0xff);
+ data[17] = (u8)((pBt->pageSize>>16)&0xff);
+ data[18] = 1;
+ data[19] = 1;
+ assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
+ data[20] = (u8)(pBt->pageSize - pBt->usableSize);
+ data[21] = 64;
+ data[22] = 32;
+ data[23] = 32;
+ memset(&data[24], 0, 100-24);
+ zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
+ pBt->btsFlags |= BTS_PAGESIZE_FIXED;
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
+ assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
+ put4byte(&data[36 + 4*4], pBt->autoVacuum);
+ put4byte(&data[36 + 7*4], pBt->incrVacuum);
+#endif
+ pBt->nPage = 1;
+ data[31] = 1;
+ return SQLITE_OK;
+}
+
+/*
+** Initialize the first page of the database file (creating a database
+** consisting of a single page and no schema objects). Return SQLITE_OK
+** if successful, or an SQLite error code otherwise.
+*/
+SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
+ int rc;
+ sqlite3BtreeEnter(p);
+ p->pBt->nPage = 0;
+ rc = newDatabase(p->pBt);
+ sqlite3BtreeLeave(p);
+ return rc;
+}
+
+/*
+** Attempt to start a new transaction. A write-transaction
+** is started if the second argument is nonzero, otherwise a read-
+** transaction. If the second argument is 2 or more and exclusive
+** transaction is started, meaning that no other process is allowed
+** to access the database. A preexisting transaction may not be
+** upgraded to exclusive by calling this routine a second time - the
+** exclusivity flag only works for a new transaction.
+**
+** A write-transaction must be started before attempting any
+** changes to the database. None of the following routines
+** will work unless a transaction is started first:
+**
+** sqlite3BtreeCreateTable()
+** sqlite3BtreeCreateIndex()
+** sqlite3BtreeClearTable()
+** sqlite3BtreeDropTable()
+** sqlite3BtreeInsert()
+** sqlite3BtreeDelete()
+** sqlite3BtreeUpdateMeta()
+**
+** If an initial attempt to acquire the lock fails because of lock contention
+** and the database was previously unlocked, then invoke the busy handler
+** if there is one. But if there was previously a read-lock, do not
+** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
+** returned when there is already a read-lock in order to avoid a deadlock.
+**
+** Suppose there are two processes A and B. A has a read lock and B has
+** a reserved lock. B tries to promote to exclusive but is blocked because
+** of A's read lock. A tries to promote to reserved but is blocked by B.
+** One or the other of the two processes must give way or there can be
+** no progress. By returning SQLITE_BUSY and not invoking the busy callback
+** when A already has a read lock, we encourage A to give up and let B
+** proceed.
+*/
+SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
+ BtShared *pBt = p->pBt;
+ Pager *pPager = pBt->pPager;
+ int rc = SQLITE_OK;
+
+ sqlite3BtreeEnter(p);
+ btreeIntegrity(p);
+
+ /* If the btree is already in a write-transaction, or it
+ ** is already in a read-transaction and a read-transaction
+ ** is requested, this is a no-op.
+ */
+ if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
+ goto trans_begun;
+ }
+ assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
+
+ if( (p->db->flags & SQLITE_ResetDatabase)
+ && sqlite3PagerIsreadonly(pPager)==0
+ ){
+ pBt->btsFlags &= ~BTS_READ_ONLY;
+ }
+
+ /* Write transactions are not possible on a read-only database */
+ if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
+ rc = SQLITE_READONLY;
+ goto trans_begun;
+ }
+
+#ifndef SQLITE_OMIT_SHARED_CACHE
+ {
+ sqlite3 *pBlock = 0;
+ /* If another database handle has already opened a write transaction
+ ** on this shared-btree structure and a second write transaction is
+ ** requested, return SQLITE_LOCKED.
+ */
+ if( (wrflag && pBt->inTransaction==TRANS_WRITE)
+ || (pBt->btsFlags & BTS_PENDING)!=0
+ ){
+ pBlock = pBt->pWriter->db;
+ }else if( wrflag>1 ){
+ BtLock *pIter;
+ for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
+ if( pIter->pBtree!=p ){
+ pBlock = pIter->pBtree->db;
+ break;
+ }
+ }
+ }
+ if( pBlock ){
+ sqlite3ConnectionBlocked(p->db, pBlock);
+ rc = SQLITE_LOCKED_SHAREDCACHE;
+ goto trans_begun;
+ }
+ }
+#endif
+
+ /* Any read-only or read-write transaction implies a read-lock on
+ ** page 1. So if some other shared-cache client already has a write-lock
+ ** on page 1, the transaction cannot be opened. */
+ rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
+ if( SQLITE_OK!=rc ) goto trans_begun;
+
+ pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
+ if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
+ do {
+ sqlite3PagerWalDb(pPager, p->db);
+
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+ /* If transitioning from no transaction directly to a write transaction,
+ ** block for the WRITER lock first if possible. */
+ if( pBt->pPage1==0 && wrflag ){
+ assert( pBt->inTransaction==TRANS_NONE );
+ rc = sqlite3PagerWalWriteLock(pPager, 1);
+ if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
+ }
+#endif
+
+ /* Call lockBtree() until either pBt->pPage1 is populated or
+ ** lockBtree() returns something other than SQLITE_OK. lockBtree()
+ ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
+ ** reading page 1 it discovers that the page-size of the database
+ ** file is not pBt->pageSize. In this case lockBtree() will update
+ ** pBt->pageSize to the page-size of the file on disk.
+ */
+ while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
+
+ if( rc==SQLITE_OK && wrflag ){
+ if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
+ rc = SQLITE_READONLY;
+ }else{
+ rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
+ if( rc==SQLITE_OK ){
+ rc = newDatabase(pBt);
+ }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
+ /* if there was no transaction opened when this function was
+ ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
+ ** code to SQLITE_BUSY. */
+ rc = SQLITE_BUSY;
+ }
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ (void)sqlite3PagerWalWriteLock(pPager, 0);
+ unlockBtreeIfUnused(pBt);
+ }
+ }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
+ btreeInvokeBusyHandler(pBt) );
+ sqlite3PagerWalDb(pPager, 0);
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+ if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
+#endif
+
+ if( rc==SQLITE_OK ){
+ if( p->inTrans==TRANS_NONE ){
+ pBt->nTransaction++;
+#ifndef SQLITE_OMIT_SHARED_CACHE
+ if( p->sharable ){
+ assert( p->lock.pBtree==p && p->lock.iTable==1 );
+ p->lock.eLock = READ_LOCK;
+ p->lock.pNext = pBt->pLock;
+ pBt->pLock = &p->lock;
+ }
+#endif
+ }
+ p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
+ if( p->inTrans>pBt->inTransaction ){
+ pBt->inTransaction = p->inTrans;
+ }
+ if( wrflag ){
+ MemPage *pPage1 = pBt->pPage1;
+#ifndef SQLITE_OMIT_SHARED_CACHE
+ assert( !pBt->pWriter );
+ pBt->pWriter = p;
+ pBt->btsFlags &= ~BTS_EXCLUSIVE;
+ if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
+#endif
+
+ /* If the db-size header field is incorrect (as it may be if an old
+ ** client has been writing the database file), update it now. Doing
+ ** this sooner rather than later means the database size can safely
+ ** re-read the database size from page 1 if a savepoint or transaction
+ ** rollback occurs within the transaction.
+ */
+ if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
+ rc = sqlite3PagerWrite(pPage1->pDbPage);
+ if( rc==SQLITE_OK ){
+ put4byte(&pPage1->aData[28], pBt->nPage);
+ }
+ }
+ }
+ }
+
+trans_begun:
+ if( rc==SQLITE_OK ){
+ if( pSchemaVersion ){
+ *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
+ }
+ if( wrflag ){
+ /* This call makes sure that the pager has the correct number of
+ ** open savepoints. If the second parameter is greater than 0 and
+ ** the sub-journal is not already open, then it will be opened here.
+ */
+ rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
+ }
+ }
+
+ btreeIntegrity(p);
+ sqlite3BtreeLeave(p);
+ return rc;
+}
+
+#ifndef SQLITE_OMIT_AUTOVACUUM
+
+/*
+** Set the pointer-map entries for all children of page pPage. Also, if
+** pPage contains cells that point to overflow pages, set the pointer
+** map entries for the overflow pages as well.
+*/
+static int setChildPtrmaps(MemPage *pPage){
+ int i; /* Counter variable */
+ int nCell; /* Number of cells in page pPage */
+ int rc; /* Return code */
+ BtShared *pBt = pPage->pBt;
+ Pgno pgno = pPage->pgno;
+
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
+ if( rc!=SQLITE_OK ) return rc;
+ nCell = pPage->nCell;
+
+ for(i=0; i<nCell; i++){
+ u8 *pCell = findCell(pPage, i);
+
+ ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
+
+ if( !pPage->leaf ){
+ Pgno childPgno = get4byte(pCell);
+ ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
+ }
+ }
+
+ if( !pPage->leaf ){
+ Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
+ ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
+ }
+
+ return rc;
+}
+
+/*
+** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
+** that it points to iTo. Parameter eType describes the type of pointer to
+** be modified, as follows:
+**
+** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
+** page of pPage.
+**
+** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
+** page pointed to by one of the cells on pPage.
+**
+** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
+** overflow page in the list.
+*/
+static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ assert( sqlite3PagerIswriteable(pPage->pDbPage) );
+ if( eType==PTRMAP_OVERFLOW2 ){
+ /* The pointer is always the first 4 bytes of the page in this case. */
+ if( get4byte(pPage->aData)!=iFrom ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ put4byte(pPage->aData, iTo);
+ }else{
+ int i;
+ int nCell;
+ int rc;
+
+ rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
+ if( rc ) return rc;
+ nCell = pPage->nCell;
+
+ for(i=0; i<nCell; i++){
+ u8 *pCell = findCell(pPage, i);
+ if( eType==PTRMAP_OVERFLOW1 ){
+ CellInfo info;
+ pPage->xParseCell(pPage, pCell, &info);
+ if( info.nLocal<info.nPayload ){
+ if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ if( iFrom==get4byte(pCell+info.nSize-4) ){
+ put4byte(pCell+info.nSize-4, iTo);
+ break;
+ }
+ }
+ }else{
+ if( get4byte(pCell)==iFrom ){
+ put4byte(pCell, iTo);
+ break;
+ }
+ }
+ }
+
+ if( i==nCell ){
+ if( eType!=PTRMAP_BTREE ||
+ get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
+ }
+ }
+ return SQLITE_OK;
+}
+
+
+/*
+** Move the open database page pDbPage to location iFreePage in the
+** database. The pDbPage reference remains valid.
+**
+** The isCommit flag indicates that there is no need to remember that
+** the journal needs to be sync()ed before database page pDbPage->pgno
+** can be written to. The caller has already promised not to write to that
+** page.
+*/
+static int relocatePage(
+ BtShared *pBt, /* Btree */
+ MemPage *pDbPage, /* Open page to move */
+ u8 eType, /* Pointer map 'type' entry for pDbPage */
+ Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
+ Pgno iFreePage, /* The location to move pDbPage to */
+ int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
+){
+ MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
+ Pgno iDbPage = pDbPage->pgno;
+ Pager *pPager = pBt->pPager;
+ int rc;
+
+ assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
+ eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ assert( pDbPage->pBt==pBt );
+ if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
+
+ /* Move page iDbPage from its current location to page number iFreePage */
+ TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
+ iDbPage, iFreePage, iPtrPage, eType));
+ rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ pDbPage->pgno = iFreePage;
+
+ /* If pDbPage was a btree-page, then it may have child pages and/or cells
+ ** that point to overflow pages. The pointer map entries for all these
+ ** pages need to be changed.
+ **
+ ** If pDbPage is an overflow page, then the first 4 bytes may store a
+ ** pointer to a subsequent overflow page. If this is the case, then
+ ** the pointer map needs to be updated for the subsequent overflow page.
+ */
+ if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
+ rc = setChildPtrmaps(pDbPage);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ }else{
+ Pgno nextOvfl = get4byte(pDbPage->aData);
+ if( nextOvfl!=0 ){
+ ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ }
+ }
+
+ /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
+ ** that it points at iFreePage. Also fix the pointer map entry for
+ ** iPtrPage.
+ */
+ if( eType!=PTRMAP_ROOTPAGE ){
+ rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ rc = sqlite3PagerWrite(pPtrPage->pDbPage);
+ if( rc!=SQLITE_OK ){
+ releasePage(pPtrPage);
+ return rc;
+ }
+ rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
+ releasePage(pPtrPage);
+ if( rc==SQLITE_OK ){
+ ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
+ }
+ }
+ return rc;
+}
+
+/* Forward declaration required by incrVacuumStep(). */
+static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
+
+/*
+** Perform a single step of an incremental-vacuum. If successful, return
+** SQLITE_OK. If there is no work to do (and therefore no point in
+** calling this function again), return SQLITE_DONE. Or, if an error
+** occurs, return some other error code.
+**
+** More specifically, this function attempts to re-organize the database so
+** that the last page of the file currently in use is no longer in use.
+**
+** Parameter nFin is the number of pages that this database would contain
+** were this function called until it returns SQLITE_DONE.
+**
+** If the bCommit parameter is non-zero, this function assumes that the
+** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
+** or an error. bCommit is passed true for an auto-vacuum-on-commit
+** operation, or false for an incremental vacuum.
+*/
+static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
+ Pgno nFreeList; /* Number of pages still on the free-list */
+ int rc;
+
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ assert( iLastPg>nFin );
+
+ if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
+ u8 eType;
+ Pgno iPtrPage;
+
+ nFreeList = get4byte(&pBt->pPage1->aData[36]);
+ if( nFreeList==0 ){
+ return SQLITE_DONE;
+ }
+
+ rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ if( eType==PTRMAP_ROOTPAGE ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+
+ if( eType==PTRMAP_FREEPAGE ){
+ if( bCommit==0 ){
+ /* Remove the page from the files free-list. This is not required
+ ** if bCommit is non-zero. In that case, the free-list will be
+ ** truncated to zero after this function returns, so it doesn't
+ ** matter if it still contains some garbage entries.
+ */
+ Pgno iFreePg;
+ MemPage *pFreePg;
+ rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ assert( iFreePg==iLastPg );
+ releasePage(pFreePg);
+ }
+ } else {
+ Pgno iFreePg; /* Index of free page to move pLastPg to */
+ MemPage *pLastPg;
+ u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
+ Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
+
+ rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+
+ /* If bCommit is zero, this loop runs exactly once and page pLastPg
+ ** is swapped with the first free page pulled off the free list.
+ **
+ ** On the other hand, if bCommit is greater than zero, then keep
+ ** looping until a free-page located within the first nFin pages
+ ** of the file is found.
+ */
+ if( bCommit==0 ){
+ eMode = BTALLOC_LE;
+ iNear = nFin;
+ }
+ do {
+ MemPage *pFreePg;
+ rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
+ if( rc!=SQLITE_OK ){
+ releasePage(pLastPg);
+ return rc;
+ }
+ releasePage(pFreePg);
+ }while( bCommit && iFreePg>nFin );
+ assert( iFreePg<iLastPg );
+
+ rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
+ releasePage(pLastPg);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ }
+ }
+
+ if( bCommit==0 ){
+ do {
+ iLastPg--;
+ }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
+ pBt->bDoTruncate = 1;
+ pBt->nPage = iLastPg;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** The database opened by the first argument is an auto-vacuum database
+** nOrig pages in size containing nFree free pages. Return the expected
+** size of the database in pages following an auto-vacuum operation.
+*/
+static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
+ int nEntry; /* Number of entries on one ptrmap page */
+ Pgno nPtrmap; /* Number of PtrMap pages to be freed */
+ Pgno nFin; /* Return value */
+
+ nEntry = pBt->usableSize/5;
+ nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
+ nFin = nOrig - nFree - nPtrmap;
+ if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
+ nFin--;
+ }
+ while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
+ nFin--;
+ }
+
+ return nFin;
+}
+
+/*
+** A write-transaction must be opened before calling this function.
+** It performs a single unit of work towards an incremental vacuum.
+**
+** If the incremental vacuum is finished after this function has run,
+** SQLITE_DONE is returned. If it is not finished, but no error occurred,
+** SQLITE_OK is returned. Otherwise an SQLite error code.
+*/
+SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
+ int rc;
+ BtShared *pBt = p->pBt;
+
+ sqlite3BtreeEnter(p);
+ assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
+ if( !pBt->autoVacuum ){
+ rc = SQLITE_DONE;
+ }else{
+ Pgno nOrig = btreePagecount(pBt);
+ Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
+ Pgno nFin = finalDbSize(pBt, nOrig, nFree);
+
+ if( nOrig<nFin || nFree>=nOrig ){
+ rc = SQLITE_CORRUPT_BKPT;
+ }else if( nFree>0 ){
+ rc = saveAllCursors(pBt, 0, 0);
+ if( rc==SQLITE_OK ){
+ invalidateAllOverflowCache(pBt);
+ rc = incrVacuumStep(pBt, nFin, nOrig, 0);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
+ put4byte(&pBt->pPage1->aData[28], pBt->nPage);
+ }
+ }else{
+ rc = SQLITE_DONE;
+ }
+ }
+ sqlite3BtreeLeave(p);
+ return rc;
+}
+
+/*
+** This routine is called prior to sqlite3PagerCommit when a transaction
+** is committed for an auto-vacuum database.
+**
+** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
+** the database file should be truncated to during the commit process.
+** i.e. the database has been reorganized so that only the first *pnTrunc
+** pages are in use.
+*/
+static int autoVacuumCommit(BtShared *pBt){
+ int rc = SQLITE_OK;
+ Pager *pPager = pBt->pPager;
+ VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
+
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ invalidateAllOverflowCache(pBt);
+ assert(pBt->autoVacuum);
+ if( !pBt->incrVacuum ){
+ Pgno nFin; /* Number of pages in database after autovacuuming */
+ Pgno nFree; /* Number of pages on the freelist initially */
+ Pgno iFree; /* The next page to be freed */
+ Pgno nOrig; /* Database size before freeing */
+
+ nOrig = btreePagecount(pBt);
+ if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
+ /* It is not possible to create a database for which the final page
+ ** is either a pointer-map page or the pending-byte page. If one
+ ** is encountered, this indicates corruption.
+ */
+ return SQLITE_CORRUPT_BKPT;
+ }
+
+ nFree = get4byte(&pBt->pPage1->aData[36]);
+ nFin = finalDbSize(pBt, nOrig, nFree);
+ if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
+ if( nFin<nOrig ){
+ rc = saveAllCursors(pBt, 0, 0);
+ }
+ for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
+ rc = incrVacuumStep(pBt, nFin, iFree, 1);
+ }
+ if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
+ rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
+ put4byte(&pBt->pPage1->aData[32], 0);
+ put4byte(&pBt->pPage1->aData[36], 0);
+ put4byte(&pBt->pPage1->aData[28], nFin);
+ pBt->bDoTruncate = 1;
+ pBt->nPage = nFin;
+ }
+ if( rc!=SQLITE_OK ){
+ sqlite3PagerRollback(pPager);
+ }
+ }
+
+ assert( nRef>=sqlite3PagerRefcount(pPager) );
+ return rc;
+}
+
+#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
+# define setChildPtrmaps(x) SQLITE_OK
+#endif
+
+/*
+** This routine does the first phase of a two-phase commit. This routine
+** causes a rollback journal to be created (if it does not already exist)
+** and populated with enough information so that if a power loss occurs
+** the database can be restored to its original state by playing back
+** the journal. Then the contents of the journal are flushed out to
+** the disk. After the journal is safely on oxide, the changes to the
+** database are written into the database file and flushed to oxide.
+** At the end of this call, the rollback journal still exists on the
+** disk and we are still holding all locks, so the transaction has not
+** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
+** commit process.
+**
+** This call is a no-op if no write-transaction is currently active on pBt.
+**
+** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
+** the name of a super-journal file that should be written into the
+** individual journal file, or is NULL, indicating no super-journal file
+** (single database transaction).
+**
+** When this is called, the super-journal should already have been
+** created, populated with this journal pointer and synced to disk.
+**
+** Once this is routine has returned, the only thing required to commit
+** the write-transaction for this database file is to delete the journal.
+*/
+SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
+ int rc = SQLITE_OK;
+ if( p->inTrans==TRANS_WRITE ){
+ BtShared *pBt = p->pBt;
+ sqlite3BtreeEnter(p);
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ if( pBt->autoVacuum ){
+ rc = autoVacuumCommit(pBt);
+ if( rc!=SQLITE_OK ){
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
+ }
+ if( pBt->bDoTruncate ){
+ sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
+ }
+#endif
+ rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
+ sqlite3BtreeLeave(p);
+ }
+ return rc;
+}
+
+/*
+** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
+** at the conclusion of a transaction.
+*/
+static void btreeEndTransaction(Btree *p){
+ BtShared *pBt = p->pBt;
+ sqlite3 *db = p->db;
+ assert( sqlite3BtreeHoldsMutex(p) );
+
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ pBt->bDoTruncate = 0;
+#endif
+ if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
+ /* If there are other active statements that belong to this database
+ ** handle, downgrade to a read-only transaction. The other statements
+ ** may still be reading from the database. */
+ downgradeAllSharedCacheTableLocks(p);
+ p->inTrans = TRANS_READ;
+ }else{
+ /* If the handle had any kind of transaction open, decrement the
+ ** transaction count of the shared btree. If the transaction count
+ ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
+ ** call below will unlock the pager. */
+ if( p->inTrans!=TRANS_NONE ){
+ clearAllSharedCacheTableLocks(p);
+ pBt->nTransaction--;
+ if( 0==pBt->nTransaction ){
+ pBt->inTransaction = TRANS_NONE;
+ }
+ }
+
+ /* Set the current transaction state to TRANS_NONE and unlock the
+ ** pager if this call closed the only read or write transaction. */
+ p->inTrans = TRANS_NONE;
+ unlockBtreeIfUnused(pBt);
+ }
+
+ btreeIntegrity(p);
+}
+
+/*
+** Commit the transaction currently in progress.
+**
+** This routine implements the second phase of a 2-phase commit. The
+** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
+** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
+** routine did all the work of writing information out to disk and flushing the
+** contents so that they are written onto the disk platter. All this
+** routine has to do is delete or truncate or zero the header in the
+** the rollback journal (which causes the transaction to commit) and
+** drop locks.
+**
+** Normally, if an error occurs while the pager layer is attempting to
+** finalize the underlying journal file, this function returns an error and
+** the upper layer will attempt a rollback. However, if the second argument
+** is non-zero then this b-tree transaction is part of a multi-file
+** transaction. In this case, the transaction has already been committed
+** (by deleting a super-journal file) and the caller will ignore this
+** functions return code. So, even if an error occurs in the pager layer,
+** reset the b-tree objects internal state to indicate that the write
+** transaction has been closed. This is quite safe, as the pager will have
+** transitioned to the error state.
+**
+** This will release the write lock on the database file. If there
+** are no active cursors, it also releases the read lock.
+*/
+SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
+
+ if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
+ sqlite3BtreeEnter(p);
+ btreeIntegrity(p);
+
+ /* If the handle has a write-transaction open, commit the shared-btrees
+ ** transaction and set the shared state to TRANS_READ.
+ */
+ if( p->inTrans==TRANS_WRITE ){
+ int rc;
+ BtShared *pBt = p->pBt;
+ assert( pBt->inTransaction==TRANS_WRITE );
+ assert( pBt->nTransaction>0 );
+ rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
+ if( rc!=SQLITE_OK && bCleanup==0 ){
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
+ p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
+ pBt->inTransaction = TRANS_READ;
+ btreeClearHasContent(pBt);
+ }
+
+ btreeEndTransaction(p);
+ sqlite3BtreeLeave(p);
+ return SQLITE_OK;
+}
+
+/*
+** Do both phases of a commit.
+*/
+SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
+ int rc;
+ sqlite3BtreeEnter(p);
+ rc = sqlite3BtreeCommitPhaseOne(p, 0);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3BtreeCommitPhaseTwo(p, 0);
+ }
+ sqlite3BtreeLeave(p);
+ return rc;
+}
+
+/*
+** This routine sets the state to CURSOR_FAULT and the error
+** code to errCode for every cursor on any BtShared that pBtree
+** references. Or if the writeOnly flag is set to 1, then only
+** trip write cursors and leave read cursors unchanged.
+**
+** Every cursor is a candidate to be tripped, including cursors
+** that belong to other database connections that happen to be
+** sharing the cache with pBtree.
+**
+** This routine gets called when a rollback occurs. If the writeOnly
+** flag is true, then only write-cursors need be tripped - read-only
+** cursors save their current positions so that they may continue
+** following the rollback. Or, if writeOnly is false, all cursors are
+** tripped. In general, writeOnly is false if the transaction being
+** rolled back modified the database schema. In this case b-tree root
+** pages may be moved or deleted from the database altogether, making
+** it unsafe for read cursors to continue.
+**
+** If the writeOnly flag is true and an error is encountered while
+** saving the current position of a read-only cursor, all cursors,
+** including all read-cursors are tripped.
+**
+** SQLITE_OK is returned if successful, or if an error occurs while
+** saving a cursor position, an SQLite error code.
+*/
+SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
+ BtCursor *p;
+ int rc = SQLITE_OK;
+
+ assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
+ if( pBtree ){
+ sqlite3BtreeEnter(pBtree);
+ for(p=pBtree->pBt->pCursor; p; p=p->pNext){
+ if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
+ if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
+ rc = saveCursorPosition(p);
+ if( rc!=SQLITE_OK ){
+ (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
+ break;
+ }
+ }
+ }else{
+ sqlite3BtreeClearCursor(p);
+ p->eState = CURSOR_FAULT;
+ p->skipNext = errCode;
+ }
+ btreeReleaseAllCursorPages(p);
+ }
+ sqlite3BtreeLeave(pBtree);
+ }
+ return rc;
+}
+
+/*
+** Set the pBt->nPage field correctly, according to the current
+** state of the database. Assume pBt->pPage1 is valid.
+*/
+static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
+ int nPage = get4byte(&pPage1->aData[28]);
+ testcase( nPage==0 );
+ if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
+ testcase( pBt->nPage!=nPage );
+ pBt->nPage = nPage;
+}
+
+/*
+** Rollback the transaction in progress.
+**
+** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
+** Only write cursors are tripped if writeOnly is true but all cursors are
+** tripped if writeOnly is false. Any attempt to use
+** a tripped cursor will result in an error.
+**
+** This will release the write lock on the database file. If there
+** are no active cursors, it also releases the read lock.
+*/
+SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
+ int rc;
+ BtShared *pBt = p->pBt;
+ MemPage *pPage1;
+
+ assert( writeOnly==1 || writeOnly==0 );
+ assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
+ sqlite3BtreeEnter(p);
+ if( tripCode==SQLITE_OK ){
+ rc = tripCode = saveAllCursors(pBt, 0, 0);
+ if( rc ) writeOnly = 0;
+ }else{
+ rc = SQLITE_OK;
+ }
+ if( tripCode ){
+ int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
+ assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
+ if( rc2!=SQLITE_OK ) rc = rc2;
+ }
+ btreeIntegrity(p);
+
+ if( p->inTrans==TRANS_WRITE ){
+ int rc2;
+
+ assert( TRANS_WRITE==pBt->inTransaction );
+ rc2 = sqlite3PagerRollback(pBt->pPager);
+ if( rc2!=SQLITE_OK ){
+ rc = rc2;
+ }
+
+ /* The rollback may have destroyed the pPage1->aData value. So
+ ** call btreeGetPage() on page 1 again to make
+ ** sure pPage1->aData is set correctly. */
+ if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
+ btreeSetNPage(pBt, pPage1);
+ releasePageOne(pPage1);
+ }
+ assert( countValidCursors(pBt, 1)==0 );
+ pBt->inTransaction = TRANS_READ;
+ btreeClearHasContent(pBt);
+ }
+
+ btreeEndTransaction(p);
+ sqlite3BtreeLeave(p);
+ return rc;
+}
+
+/*
+** Start a statement subtransaction. The subtransaction can be rolled
+** back independently of the main transaction. You must start a transaction
+** before starting a subtransaction. The subtransaction is ended automatically
+** if the main transaction commits or rolls back.
+**
+** Statement subtransactions are used around individual SQL statements
+** that are contained within a BEGIN...COMMIT block. If a constraint
+** error occurs within the statement, the effect of that one statement
+** can be rolled back without having to rollback the entire transaction.
+**
+** A statement sub-transaction is implemented as an anonymous savepoint. The
+** value passed as the second parameter is the total number of savepoints,
+** including the new anonymous savepoint, open on the B-Tree. i.e. if there
+** are no active savepoints and no other statement-transactions open,
+** iStatement is 1. This anonymous savepoint can be released or rolled back
+** using the sqlite3BtreeSavepoint() function.
+*/
+SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
+ int rc;
+ BtShared *pBt = p->pBt;
+ sqlite3BtreeEnter(p);
+ assert( p->inTrans==TRANS_WRITE );
+ assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
+ assert( iStatement>0 );
+ assert( iStatement>p->db->nSavepoint );
+ assert( pBt->inTransaction==TRANS_WRITE );
+ /* At the pager level, a statement transaction is a savepoint with
+ ** an index greater than all savepoints created explicitly using
+ ** SQL statements. It is illegal to open, release or rollback any
+ ** such savepoints while the statement transaction savepoint is active.
+ */
+ rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
+ sqlite3BtreeLeave(p);
+ return rc;
+}
+
+/*
+** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
+** or SAVEPOINT_RELEASE. This function either releases or rolls back the
+** savepoint identified by parameter iSavepoint, depending on the value
+** of op.
+**
+** Normally, iSavepoint is greater than or equal to zero. However, if op is
+** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
+** contents of the entire transaction are rolled back. This is different
+** from a normal transaction rollback, as no locks are released and the
+** transaction remains open.
+*/
+SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
+ int rc = SQLITE_OK;
+ if( p && p->inTrans==TRANS_WRITE ){
+ BtShared *pBt = p->pBt;
+ assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
+ assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
+ sqlite3BtreeEnter(p);
+ if( op==SAVEPOINT_ROLLBACK ){
+ rc = saveAllCursors(pBt, 0, 0);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
+ }
+ if( rc==SQLITE_OK ){
+ if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
+ pBt->nPage = 0;
+ }
+ rc = newDatabase(pBt);
+ btreeSetNPage(pBt, pBt->pPage1);
+
+ /* pBt->nPage might be zero if the database was corrupt when
+ ** the transaction was started. Otherwise, it must be at least 1. */
+ assert( CORRUPT_DB || pBt->nPage>0 );
+ }
+ sqlite3BtreeLeave(p);
+ }
+ return rc;
+}
+
+/*
+** Create a new cursor for the BTree whose root is on the page
+** iTable. If a read-only cursor is requested, it is assumed that
+** the caller already has at least a read-only transaction open
+** on the database already. If a write-cursor is requested, then
+** the caller is assumed to have an open write transaction.
+**
+** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
+** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
+** can be used for reading or for writing if other conditions for writing
+** are also met. These are the conditions that must be met in order
+** for writing to be allowed:
+**
+** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
+**
+** 2: Other database connections that share the same pager cache
+** but which are not in the READ_UNCOMMITTED state may not have
+** cursors open with wrFlag==0 on the same table. Otherwise
+** the changes made by this write cursor would be visible to
+** the read cursors in the other database connection.
+**
+** 3: The database must be writable (not on read-only media)
+**
+** 4: There must be an active transaction.
+**
+** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
+** is set. If FORDELETE is set, that is a hint to the implementation that
+** this cursor will only be used to seek to and delete entries of an index
+** as part of a larger DELETE statement. The FORDELETE hint is not used by
+** this implementation. But in a hypothetical alternative storage engine
+** in which index entries are automatically deleted when corresponding table
+** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
+** operations on this cursor can be no-ops and all READ operations can
+** return a null row (2-bytes: 0x01 0x00).
+**
+** No checking is done to make sure that page iTable really is the
+** root page of a b-tree. If it is not, then the cursor acquired
+** will not work correctly.
+**
+** It is assumed that the sqlite3BtreeCursorZero() has been called
+** on pCur to initialize the memory space prior to invoking this routine.
+*/
+static int btreeCursor(
+ Btree *p, /* The btree */
+ Pgno iTable, /* Root page of table to open */
+ int wrFlag, /* 1 to write. 0 read-only */
+ struct KeyInfo *pKeyInfo, /* First arg to comparison function */
+ BtCursor *pCur /* Space for new cursor */
+){
+ BtShared *pBt = p->pBt; /* Shared b-tree handle */
+ BtCursor *pX; /* Looping over other all cursors */
+
+ assert( sqlite3BtreeHoldsMutex(p) );
+ assert( wrFlag==0
+ || wrFlag==BTREE_WRCSR
+ || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
+ );
+
+ /* The following assert statements verify that if this is a sharable
+ ** b-tree database, the connection is holding the required table locks,
+ ** and that no other connection has any open cursor that conflicts with
+ ** this lock. The iTable<1 term disables the check for corrupt schemas. */
+ assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
+ || iTable<1 );
+ assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
+
+ /* Assert that the caller has opened the required transaction. */
+ assert( p->inTrans>TRANS_NONE );
+ assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
+ assert( pBt->pPage1 && pBt->pPage1->aData );
+ assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
+
+ if( wrFlag ){
+ allocateTempSpace(pBt);
+ if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
+ }
+ if( iTable<=1 ){
+ if( iTable<1 ){
+ return SQLITE_CORRUPT_BKPT;
+ }else if( btreePagecount(pBt)==0 ){
+ assert( wrFlag==0 );
+ iTable = 0;
+ }
+ }
+
+ /* Now that no other errors can occur, finish filling in the BtCursor
+ ** variables and link the cursor into the BtShared list. */
+ pCur->pgnoRoot = iTable;
+ pCur->iPage = -1;
+ pCur->pKeyInfo = pKeyInfo;
+ pCur->pBtree = p;
+ pCur->pBt = pBt;
+ pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
+ pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
+ /* If there are two or more cursors on the same btree, then all such
+ ** cursors *must* have the BTCF_Multiple flag set. */
+ for(pX=pBt->pCursor; pX; pX=pX->pNext){
+ if( pX->pgnoRoot==iTable ){
+ pX->curFlags |= BTCF_Multiple;
+ pCur->curFlags |= BTCF_Multiple;
+ }
+ }
+ pCur->pNext = pBt->pCursor;
+ pBt->pCursor = pCur;
+ pCur->eState = CURSOR_INVALID;
+ return SQLITE_OK;
+}
+static int btreeCursorWithLock(
+ Btree *p, /* The btree */
+ Pgno iTable, /* Root page of table to open */
+ int wrFlag, /* 1 to write. 0 read-only */
+ struct KeyInfo *pKeyInfo, /* First arg to comparison function */
+ BtCursor *pCur /* Space for new cursor */
+){
+ int rc;
+ sqlite3BtreeEnter(p);
+ rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
+ sqlite3BtreeLeave(p);
+ return rc;
+}
+SQLITE_PRIVATE int sqlite3BtreeCursor(
+ Btree *p, /* The btree */
+ Pgno iTable, /* Root page of table to open */
+ int wrFlag, /* 1 to write. 0 read-only */
+ struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
+ BtCursor *pCur /* Write new cursor here */
+){
+ if( p->sharable ){
+ return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
+ }else{
+ return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
+ }
+}
+
+/*
+** Return the size of a BtCursor object in bytes.
+**
+** This interfaces is needed so that users of cursors can preallocate
+** sufficient storage to hold a cursor. The BtCursor object is opaque
+** to users so they cannot do the sizeof() themselves - they must call
+** this routine.
+*/
+SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
+ return ROUND8(sizeof(BtCursor));
+}
+
+/*
+** Initialize memory that will be converted into a BtCursor object.
+**
+** The simple approach here would be to memset() the entire object
+** to zero. But it turns out that the apPage[] and aiIdx[] arrays
+** do not need to be zeroed and they are large, so we can save a lot
+** of run-time by skipping the initialization of those elements.
+*/
+SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
+ memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
+}
+
+/*
+** Close a cursor. The read lock on the database file is released
+** when the last cursor is closed.
+*/
+SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
+ Btree *pBtree = pCur->pBtree;
+ if( pBtree ){
+ BtShared *pBt = pCur->pBt;
+ sqlite3BtreeEnter(pBtree);
+ assert( pBt->pCursor!=0 );
+ if( pBt->pCursor==pCur ){
+ pBt->pCursor = pCur->pNext;
+ }else{
+ BtCursor *pPrev = pBt->pCursor;
+ do{
+ if( pPrev->pNext==pCur ){
+ pPrev->pNext = pCur->pNext;
+ break;
+ }
+ pPrev = pPrev->pNext;
+ }while( ALWAYS(pPrev) );
+ }
+ btreeReleaseAllCursorPages(pCur);
+ unlockBtreeIfUnused(pBt);
+ sqlite3_free(pCur->aOverflow);
+ sqlite3_free(pCur->pKey);
+ sqlite3BtreeLeave(pBtree);
+ pCur->pBtree = 0;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Make sure the BtCursor* given in the argument has a valid
+** BtCursor.info structure. If it is not already valid, call
+** btreeParseCell() to fill it in.
+**
+** BtCursor.info is a cache of the information in the current cell.
+** Using this cache reduces the number of calls to btreeParseCell().
+*/
+#ifndef NDEBUG
+ static int cellInfoEqual(CellInfo *a, CellInfo *b){
+ if( a->nKey!=b->nKey ) return 0;
+ if( a->pPayload!=b->pPayload ) return 0;
+ if( a->nPayload!=b->nPayload ) return 0;
+ if( a->nLocal!=b->nLocal ) return 0;
+ if( a->nSize!=b->nSize ) return 0;
+ return 1;
+ }
+ static void assertCellInfo(BtCursor *pCur){
+ CellInfo info;
+ memset(&info, 0, sizeof(info));
+ btreeParseCell(pCur->pPage, pCur->ix, &info);
+ assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
+ }
+#else
+ #define assertCellInfo(x)
+#endif
+static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
+ if( pCur->info.nSize==0 ){
+ pCur->curFlags |= BTCF_ValidNKey;
+ btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
+ }else{
+ assertCellInfo(pCur);
+ }
+}
+
+#ifndef NDEBUG /* The next routine used only within assert() statements */
+/*
+** Return true if the given BtCursor is valid. A valid cursor is one
+** that is currently pointing to a row in a (non-empty) table.
+** This is a verification routine is used only within assert() statements.
+*/
+SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
+ return pCur && pCur->eState==CURSOR_VALID;
+}
+#endif /* NDEBUG */
+SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
+ assert( pCur!=0 );
+ return pCur->eState==CURSOR_VALID;
+}
+
+/*
+** Return the value of the integer key or "rowid" for a table btree.
+** This routine is only valid for a cursor that is pointing into a
+** ordinary table btree. If the cursor points to an index btree or
+** is invalid, the result of this routine is undefined.
+*/
+SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
+ assert( cursorHoldsMutex(pCur) );
+ assert( pCur->eState==CURSOR_VALID );
+ assert( pCur->curIntKey );
+ getCellInfo(pCur);
+ return pCur->info.nKey;
+}
+
+/*
+** Pin or unpin a cursor.
+*/
+SQLITE_PRIVATE void sqlite3BtreeCursorPin(BtCursor *pCur){
+ assert( (pCur->curFlags & BTCF_Pinned)==0 );
+ pCur->curFlags |= BTCF_Pinned;
+}
+SQLITE_PRIVATE void sqlite3BtreeCursorUnpin(BtCursor *pCur){
+ assert( (pCur->curFlags & BTCF_Pinned)!=0 );
+ pCur->curFlags &= ~BTCF_Pinned;
+}
+
+#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
+/*
+** Return the offset into the database file for the start of the
+** payload to which the cursor is pointing.
+*/
+SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor *pCur){
+ assert( cursorHoldsMutex(pCur) );
+ assert( pCur->eState==CURSOR_VALID );
+ getCellInfo(pCur);
+ return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
+ (i64)(pCur->info.pPayload - pCur->pPage->aData);
+}
+#endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
+
+/*
+** Return the number of bytes of payload for the entry that pCur is
+** currently pointing to. For table btrees, this will be the amount
+** of data. For index btrees, this will be the size of the key.
+**
+** The caller must guarantee that the cursor is pointing to a non-NULL
+** valid entry. In other words, the calling procedure must guarantee
+** that the cursor has Cursor.eState==CURSOR_VALID.
+*/
+SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
+ assert( cursorHoldsMutex(pCur) );
+ assert( pCur->eState==CURSOR_VALID );
+ getCellInfo(pCur);
+ return pCur->info.nPayload;
+}
+
+/*
+** Return an upper bound on the size of any record for the table
+** that the cursor is pointing into.
+**
+** This is an optimization. Everything will still work if this
+** routine always returns 2147483647 (which is the largest record
+** that SQLite can handle) or more. But returning a smaller value might
+** prevent large memory allocations when trying to interpret a
+** corrupt datrabase.
+**
+** The current implementation merely returns the size of the underlying
+** database file.
+*/
+SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
+ assert( cursorHoldsMutex(pCur) );
+ assert( pCur->eState==CURSOR_VALID );
+ return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
+}
+
+/*
+** Given the page number of an overflow page in the database (parameter
+** ovfl), this function finds the page number of the next page in the
+** linked list of overflow pages. If possible, it uses the auto-vacuum
+** pointer-map data instead of reading the content of page ovfl to do so.
+**
+** If an error occurs an SQLite error code is returned. Otherwise:
+**
+** The page number of the next overflow page in the linked list is
+** written to *pPgnoNext. If page ovfl is the last page in its linked
+** list, *pPgnoNext is set to zero.
+**
+** If ppPage is not NULL, and a reference to the MemPage object corresponding
+** to page number pOvfl was obtained, then *ppPage is set to point to that
+** reference. It is the responsibility of the caller to call releasePage()
+** on *ppPage to free the reference. In no reference was obtained (because
+** the pointer-map was used to obtain the value for *pPgnoNext), then
+** *ppPage is set to zero.
+*/
+static int getOverflowPage(
+ BtShared *pBt, /* The database file */
+ Pgno ovfl, /* Current overflow page number */
+ MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
+ Pgno *pPgnoNext /* OUT: Next overflow page number */
+){
+ Pgno next = 0;
+ MemPage *pPage = 0;
+ int rc = SQLITE_OK;
+
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ assert(pPgnoNext);
+
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ /* Try to find the next page in the overflow list using the
+ ** autovacuum pointer-map pages. Guess that the next page in
+ ** the overflow list is page number (ovfl+1). If that guess turns
+ ** out to be wrong, fall back to loading the data of page
+ ** number ovfl to determine the next page number.
+ */
+ if( pBt->autoVacuum ){
+ Pgno pgno;
+ Pgno iGuess = ovfl+1;
+ u8 eType;
+
+ while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
+ iGuess++;
+ }
+
+ if( iGuess<=btreePagecount(pBt) ){
+ rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
+ if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
+ next = iGuess;
+ rc = SQLITE_DONE;
+ }
+ }
+ }
+#endif
+
+ assert( next==0 || rc==SQLITE_DONE );
+ if( rc==SQLITE_OK ){
+ rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
+ assert( rc==SQLITE_OK || pPage==0 );
+ if( rc==SQLITE_OK ){
+ next = get4byte(pPage->aData);
+ }
+ }
+
+ *pPgnoNext = next;
+ if( ppPage ){
+ *ppPage = pPage;
+ }else{
+ releasePage(pPage);
+ }
+ return (rc==SQLITE_DONE ? SQLITE_OK : rc);
+}
+
+/*
+** Copy data from a buffer to a page, or from a page to a buffer.
+**
+** pPayload is a pointer to data stored on database page pDbPage.
+** If argument eOp is false, then nByte bytes of data are copied
+** from pPayload to the buffer pointed at by pBuf. If eOp is true,
+** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
+** of data are copied from the buffer pBuf to pPayload.
+**
+** SQLITE_OK is returned on success, otherwise an error code.
+*/
+static int copyPayload(
+ void *pPayload, /* Pointer to page data */
+ void *pBuf, /* Pointer to buffer */
+ int nByte, /* Number of bytes to copy */
+ int eOp, /* 0 -> copy from page, 1 -> copy to page */
+ DbPage *pDbPage /* Page containing pPayload */
+){
+ if( eOp ){
+ /* Copy data from buffer to page (a write operation) */
+ int rc = sqlite3PagerWrite(pDbPage);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ memcpy(pPayload, pBuf, nByte);
+ }else{
+ /* Copy data from page to buffer (a read operation) */
+ memcpy(pBuf, pPayload, nByte);
+ }
+ return SQLITE_OK;
+}
+
+/*
+** This function is used to read or overwrite payload information
+** for the entry that the pCur cursor is pointing to. The eOp
+** argument is interpreted as follows:
+**
+** 0: The operation is a read. Populate the overflow cache.
+** 1: The operation is a write. Populate the overflow cache.
+**
+** A total of "amt" bytes are read or written beginning at "offset".
+** Data is read to or from the buffer pBuf.
+**
+** The content being read or written might appear on the main page
+** or be scattered out on multiple overflow pages.
+**
+** If the current cursor entry uses one or more overflow pages
+** this function may allocate space for and lazily populate
+** the overflow page-list cache array (BtCursor.aOverflow).
+** Subsequent calls use this cache to make seeking to the supplied offset
+** more efficient.
+**
+** Once an overflow page-list cache has been allocated, it must be
+** invalidated if some other cursor writes to the same table, or if
+** the cursor is moved to a different row. Additionally, in auto-vacuum
+** mode, the following events may invalidate an overflow page-list cache.
+**
+** * An incremental vacuum,
+** * A commit in auto_vacuum="full" mode,
+** * Creating a table (may require moving an overflow page).
+*/
+static int accessPayload(
+ BtCursor *pCur, /* Cursor pointing to entry to read from */
+ u32 offset, /* Begin reading this far into payload */
+ u32 amt, /* Read this many bytes */
+ unsigned char *pBuf, /* Write the bytes into this buffer */
+ int eOp /* zero to read. non-zero to write. */
+){
+ unsigned char *aPayload;
+ int rc = SQLITE_OK;
+ int iIdx = 0;
+ MemPage *pPage = pCur->pPage; /* Btree page of current entry */
+ BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
+#ifdef SQLITE_DIRECT_OVERFLOW_READ
+ unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
+#endif
+
+ assert( pPage );
+ assert( eOp==0 || eOp==1 );
+ assert( pCur->eState==CURSOR_VALID );
+ assert( pCur->ix<pPage->nCell );
+ assert( cursorHoldsMutex(pCur) );
+
+ getCellInfo(pCur);
+ aPayload = pCur->info.pPayload;
+ assert( offset+amt <= pCur->info.nPayload );
+
+ assert( aPayload > pPage->aData );
+ if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
+ /* Trying to read or write past the end of the data is an error. The
+ ** conditional above is really:
+ ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
+ ** but is recast into its current form to avoid integer overflow problems
+ */
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+
+ /* Check if data must be read/written to/from the btree page itself. */
+ if( offset<pCur->info.nLocal ){
+ int a = amt;
+ if( a+offset>pCur->info.nLocal ){
+ a = pCur->info.nLocal - offset;
+ }
+ rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
+ offset = 0;
+ pBuf += a;
+ amt -= a;
+ }else{
+ offset -= pCur->info.nLocal;
+ }
+
+
+ if( rc==SQLITE_OK && amt>0 ){
+ const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
+ Pgno nextPage;
+
+ nextPage = get4byte(&aPayload[pCur->info.nLocal]);
+
+ /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
+ **
+ ** The aOverflow[] array is sized at one entry for each overflow page
+ ** in the overflow chain. The page number of the first overflow page is
+ ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
+ ** means "not yet known" (the cache is lazily populated).
+ */
+ if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
+ int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
+ if( pCur->aOverflow==0
+ || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
+ ){
+ Pgno *aNew = (Pgno*)sqlite3Realloc(
+ pCur->aOverflow, nOvfl*2*sizeof(Pgno)
+ );
+ if( aNew==0 ){
+ return SQLITE_NOMEM_BKPT;
+ }else{
+ pCur->aOverflow = aNew;
+ }
+ }
+ memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
+ pCur->curFlags |= BTCF_ValidOvfl;
+ }else{
+ /* If the overflow page-list cache has been allocated and the
+ ** entry for the first required overflow page is valid, skip
+ ** directly to it.
+ */
+ if( pCur->aOverflow[offset/ovflSize] ){
+ iIdx = (offset/ovflSize);
+ nextPage = pCur->aOverflow[iIdx];
+ offset = (offset%ovflSize);
+ }
+ }
+
+ assert( rc==SQLITE_OK && amt>0 );
+ while( nextPage ){
+ /* If required, populate the overflow page-list cache. */
+ if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
+ assert( pCur->aOverflow[iIdx]==0
+ || pCur->aOverflow[iIdx]==nextPage
+ || CORRUPT_DB );
+ pCur->aOverflow[iIdx] = nextPage;
+
+ if( offset>=ovflSize ){
+ /* The only reason to read this page is to obtain the page
+ ** number for the next page in the overflow chain. The page
+ ** data is not required. So first try to lookup the overflow
+ ** page-list cache, if any, then fall back to the getOverflowPage()
+ ** function.
+ */
+ assert( pCur->curFlags & BTCF_ValidOvfl );
+ assert( pCur->pBtree->db==pBt->db );
+ if( pCur->aOverflow[iIdx+1] ){
+ nextPage = pCur->aOverflow[iIdx+1];
+ }else{
+ rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
+ }
+ offset -= ovflSize;
+ }else{
+ /* Need to read this page properly. It contains some of the
+ ** range of data that is being read (eOp==0) or written (eOp!=0).
+ */
+ int a = amt;
+ if( a + offset > ovflSize ){
+ a = ovflSize - offset;
+ }
+
+#ifdef SQLITE_DIRECT_OVERFLOW_READ
+ /* If all the following are true:
+ **
+ ** 1) this is a read operation, and
+ ** 2) data is required from the start of this overflow page, and
+ ** 3) there are no dirty pages in the page-cache
+ ** 4) the database is file-backed, and
+ ** 5) the page is not in the WAL file
+ ** 6) at least 4 bytes have already been read into the output buffer
+ **
+ ** then data can be read directly from the database file into the
+ ** output buffer, bypassing the page-cache altogether. This speeds
+ ** up loading large records that span many overflow pages.
+ */
+ if( eOp==0 /* (1) */
+ && offset==0 /* (2) */
+ && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
+ && &pBuf[-4]>=pBufStart /* (6) */
+ ){
+ sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
+ u8 aSave[4];
+ u8 *aWrite = &pBuf[-4];
+ assert( aWrite>=pBufStart ); /* due to (6) */
+ memcpy(aSave, aWrite, 4);
+ rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
+ if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
+ nextPage = get4byte(aWrite);
+ memcpy(aWrite, aSave, 4);
+ }else
+#endif
+
+ {
+ DbPage *pDbPage;
+ rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
+ (eOp==0 ? PAGER_GET_READONLY : 0)
+ );
+ if( rc==SQLITE_OK ){
+ aPayload = sqlite3PagerGetData(pDbPage);
+ nextPage = get4byte(aPayload);
+ rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
+ sqlite3PagerUnref(pDbPage);
+ offset = 0;
+ }
+ }
+ amt -= a;
+ if( amt==0 ) return rc;
+ pBuf += a;
+ }
+ if( rc ) break;
+ iIdx++;
+ }
+ }
+
+ if( rc==SQLITE_OK && amt>0 ){
+ /* Overflow chain ends prematurely */
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ return rc;
+}
+
+/*
+** Read part of the payload for the row at which that cursor pCur is currently
+** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
+** begins at "offset".
+**
+** pCur can be pointing to either a table or an index b-tree.
+** If pointing to a table btree, then the content section is read. If
+** pCur is pointing to an index b-tree then the key section is read.
+**
+** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
+** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
+** cursor might be invalid or might need to be restored before being read.
+**
+** Return SQLITE_OK on success or an error code if anything goes
+** wrong. An error is returned if "offset+amt" is larger than
+** the available payload.
+*/
+SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
+ assert( cursorHoldsMutex(pCur) );
+ assert( pCur->eState==CURSOR_VALID );
+ assert( pCur->iPage>=0 && pCur->pPage );
+ assert( pCur->ix<pCur->pPage->nCell );
+ return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
+}
+
+/*
+** This variant of sqlite3BtreePayload() works even if the cursor has not
+** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
+** interface.
+*/
+#ifndef SQLITE_OMIT_INCRBLOB
+static SQLITE_NOINLINE int accessPayloadChecked(
+ BtCursor *pCur,
+ u32 offset,
+ u32 amt,
+ void *pBuf
+){
+ int rc;
+ if ( pCur->eState==CURSOR_INVALID ){
+ return SQLITE_ABORT;
+ }
+ assert( cursorOwnsBtShared(pCur) );
+ rc = btreeRestoreCursorPosition(pCur);
+ return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
+}
+SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
+ if( pCur->eState==CURSOR_VALID ){
+ assert( cursorOwnsBtShared(pCur) );
+ return accessPayload(pCur, offset, amt, pBuf, 0);
+ }else{
+ return accessPayloadChecked(pCur, offset, amt, pBuf);
+ }
+}
+#endif /* SQLITE_OMIT_INCRBLOB */
+
+/*
+** Return a pointer to payload information from the entry that the
+** pCur cursor is pointing to. The pointer is to the beginning of
+** the key if index btrees (pPage->intKey==0) and is the data for
+** table btrees (pPage->intKey==1). The number of bytes of available
+** key/data is written into *pAmt. If *pAmt==0, then the value
+** returned will not be a valid pointer.
+**
+** This routine is an optimization. It is common for the entire key
+** and data to fit on the local page and for there to be no overflow
+** pages. When that is so, this routine can be used to access the
+** key and data without making a copy. If the key and/or data spills
+** onto overflow pages, then accessPayload() must be used to reassemble
+** the key/data and copy it into a preallocated buffer.
+**
+** The pointer returned by this routine looks directly into the cached
+** page of the database. The data might change or move the next time
+** any btree routine is called.
+*/
+static const void *fetchPayload(
+ BtCursor *pCur, /* Cursor pointing to entry to read from */
+ u32 *pAmt /* Write the number of available bytes here */
+){
+ int amt;
+ assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
+ assert( pCur->eState==CURSOR_VALID );
+ assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
+ assert( cursorOwnsBtShared(pCur) );
+ assert( pCur->ix<pCur->pPage->nCell );
+ assert( pCur->info.nSize>0 );
+ assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
+ assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
+ amt = pCur->info.nLocal;
+ if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
+ /* There is too little space on the page for the expected amount
+ ** of local content. Database must be corrupt. */
+ assert( CORRUPT_DB );
+ amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
+ }
+ *pAmt = (u32)amt;
+ return (void*)pCur->info.pPayload;
+}
+
+
+/*
+** For the entry that cursor pCur is point to, return as
+** many bytes of the key or data as are available on the local
+** b-tree page. Write the number of available bytes into *pAmt.
+**
+** The pointer returned is ephemeral. The key/data may move
+** or be destroyed on the next call to any Btree routine,
+** including calls from other threads against the same cache.
+** Hence, a mutex on the BtShared should be held prior to calling
+** this routine.
+**
+** These routines is used to get quick access to key and data
+** in the common case where no overflow pages are used.
+*/
+SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
+ return fetchPayload(pCur, pAmt);
+}
+
+
+/*
+** Move the cursor down to a new child page. The newPgno argument is the
+** page number of the child page to move to.
+**
+** This function returns SQLITE_CORRUPT if the page-header flags field of
+** the new child page does not match the flags field of the parent (i.e.
+** if an intkey page appears to be the parent of a non-intkey page, or
+** vice-versa).
+*/
+static int moveToChild(BtCursor *pCur, u32 newPgno){
+ BtShared *pBt = pCur->pBt;
+
+ assert( cursorOwnsBtShared(pCur) );
+ assert( pCur->eState==CURSOR_VALID );
+ assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
+ assert( pCur->iPage>=0 );
+ if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+ pCur->info.nSize = 0;
+ pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
+ pCur->aiIdx[pCur->iPage] = pCur->ix;
+ pCur->apPage[pCur->iPage] = pCur->pPage;
+ pCur->ix = 0;
+ pCur->iPage++;
+ return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
+}
+
+#ifdef SQLITE_DEBUG
+/*
+** Page pParent is an internal (non-leaf) tree page. This function
+** asserts that page number iChild is the left-child if the iIdx'th
+** cell in page pParent. Or, if iIdx is equal to the total number of
+** cells in pParent, that page number iChild is the right-child of
+** the page.
+*/
+static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
+ if( CORRUPT_DB ) return; /* The conditions tested below might not be true
+ ** in a corrupt database */
+ assert( iIdx<=pParent->nCell );
+ if( iIdx==pParent->nCell ){
+ assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
+ }else{
+ assert( get4byte(findCell(pParent, iIdx))==iChild );
+ }
+}
+#else
+# define assertParentIndex(x,y,z)
+#endif
+
+/*
+** Move the cursor up to the parent page.
+**
+** pCur->idx is set to the cell index that contains the pointer
+** to the page we are coming from. If we are coming from the
+** right-most child page then pCur->idx is set to one more than
+** the largest cell index.
+*/
+static void moveToParent(BtCursor *pCur){
+ MemPage *pLeaf;
+ assert( cursorOwnsBtShared(pCur) );
+ assert( pCur->eState==CURSOR_VALID );
+ assert( pCur->iPage>0 );
+ assert( pCur->pPage );
+ assertParentIndex(
+ pCur->apPage[pCur->iPage-1],
+ pCur->aiIdx[pCur->iPage-1],
+ pCur->pPage->pgno
+ );
+ testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
+ pCur->info.nSize = 0;
+ pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
+ pCur->ix = pCur->aiIdx[pCur->iPage-1];
+ pLeaf = pCur->pPage;
+ pCur->pPage = pCur->apPage[--pCur->iPage];
+ releasePageNotNull(pLeaf);
+}
+
+/*
+** Move the cursor to point to the root page of its b-tree structure.
+**
+** If the table has a virtual root page, then the cursor is moved to point
+** to the virtual root page instead of the actual root page. A table has a
+** virtual root page when the actual root page contains no cells and a
+** single child page. This can only happen with the table rooted at page 1.
+**
+** If the b-tree structure is empty, the cursor state is set to
+** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
+** the cursor is set to point to the first cell located on the root
+** (or virtual root) page and the cursor state is set to CURSOR_VALID.
+**
+** If this function returns successfully, it may be assumed that the
+** page-header flags indicate that the [virtual] root-page is the expected
+** kind of b-tree page (i.e. if when opening the cursor the caller did not
+** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
+** indicating a table b-tree, or if the caller did specify a KeyInfo
+** structure the flags byte is set to 0x02 or 0x0A, indicating an index
+** b-tree).
+*/
+static int moveToRoot(BtCursor *pCur){
+ MemPage *pRoot;
+ int rc = SQLITE_OK;
+
+ assert( cursorOwnsBtShared(pCur) );
+ assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
+ assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
+ assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
+ assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
+ assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
+
+ if( pCur->iPage>=0 ){
+ if( pCur->iPage ){
+ releasePageNotNull(pCur->pPage);
+ while( --pCur->iPage ){
+ releasePageNotNull(pCur->apPage[pCur->iPage]);
+ }
+ pCur->pPage = pCur->apPage[0];
+ goto skip_init;
+ }
+ }else if( pCur->pgnoRoot==0 ){
+ pCur->eState = CURSOR_INVALID;
+ return SQLITE_EMPTY;
+ }else{
+ assert( pCur->iPage==(-1) );
+ if( pCur->eState>=CURSOR_REQUIRESEEK ){
+ if( pCur->eState==CURSOR_FAULT ){
+ assert( pCur->skipNext!=SQLITE_OK );
+ return pCur->skipNext;
+ }
+ sqlite3BtreeClearCursor(pCur);
+ }
+ rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
+ 0, pCur->curPagerFlags);
+ if( rc!=SQLITE_OK ){
+ pCur->eState = CURSOR_INVALID;
+ return rc;
+ }
+ pCur->iPage = 0;
+ pCur->curIntKey = pCur->pPage->intKey;
+ }
+ pRoot = pCur->pPage;
+ assert( pRoot->pgno==pCur->pgnoRoot );
+
+ /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
+ ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
+ ** NULL, the caller expects a table b-tree. If this is not the case,
+ ** return an SQLITE_CORRUPT error.
+ **
+ ** Earlier versions of SQLite assumed that this test could not fail
+ ** if the root page was already loaded when this function was called (i.e.
+ ** if pCur->iPage>=0). But this is not so if the database is corrupted
+ ** in such a way that page pRoot is linked into a second b-tree table
+ ** (or the freelist). */
+ assert( pRoot->intKey==1 || pRoot->intKey==0 );
+ if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
+ return SQLITE_CORRUPT_PAGE(pCur->pPage);
+ }
+
+skip_init:
+ pCur->ix = 0;
+ pCur->info.nSize = 0;
+ pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
+
+ pRoot = pCur->pPage;
+ if( pRoot->nCell>0 ){
+ pCur->eState = CURSOR_VALID;
+ }else if( !pRoot->leaf ){
+ Pgno subpage;
+ if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
+ subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
+ pCur->eState = CURSOR_VALID;
+ rc = moveToChild(pCur, subpage);
+ }else{
+ pCur->eState = CURSOR_INVALID;
+ rc = SQLITE_EMPTY;
+ }
+ return rc;
+}
+
+/*
+** Move the cursor down to the left-most leaf entry beneath the
+** entry to which it is currently pointing.
+**
+** The left-most leaf is the one with the smallest key - the first
+** in ascending order.
+*/
+static int moveToLeftmost(BtCursor *pCur){
+ Pgno pgno;
+ int rc = SQLITE_OK;
+ MemPage *pPage;
+
+ assert( cursorOwnsBtShared(pCur) );
+ assert( pCur->eState==CURSOR_VALID );
+ while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
+ assert( pCur->ix<pPage->nCell );
+ pgno = get4byte(findCell(pPage, pCur->ix));
+ rc = moveToChild(pCur, pgno);
+ }
+ return rc;
+}
+
+/*
+** Move the cursor down to the right-most leaf entry beneath the
+** page to which it is currently pointing. Notice the difference
+** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
+** finds the left-most entry beneath the *entry* whereas moveToRightmost()
+** finds the right-most entry beneath the *page*.
+**
+** The right-most entry is the one with the largest key - the last
+** key in ascending order.
+*/
+static int moveToRightmost(BtCursor *pCur){
+ Pgno pgno;
+ int rc = SQLITE_OK;
+ MemPage *pPage = 0;
+
+ assert( cursorOwnsBtShared(pCur) );
+ assert( pCur->eState==CURSOR_VALID );
+ while( !(pPage = pCur->pPage)->leaf ){
+ pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
+ pCur->ix = pPage->nCell;
+ rc = moveToChild(pCur, pgno);
+ if( rc ) return rc;
+ }
+ pCur->ix = pPage->nCell-1;
+ assert( pCur->info.nSize==0 );
+ assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
+ return SQLITE_OK;
+}
+
+/* Move the cursor to the first entry in the table. Return SQLITE_OK
+** on success. Set *pRes to 0 if the cursor actually points to something
+** or set *pRes to 1 if the table is empty.
+*/
+SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
+ int rc;
+
+ assert( cursorOwnsBtShared(pCur) );
+ assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
+ rc = moveToRoot(pCur);
+ if( rc==SQLITE_OK ){
+ assert( pCur->pPage->nCell>0 );
+ *pRes = 0;
+ rc = moveToLeftmost(pCur);
+ }else if( rc==SQLITE_EMPTY ){
+ assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
+ *pRes = 1;
+ rc = SQLITE_OK;
+ }
+ return rc;
+}
+
+/* Move the cursor to the last entry in the table. Return SQLITE_OK
+** on success. Set *pRes to 0 if the cursor actually points to something
+** or set *pRes to 1 if the table is empty.
+*/
+SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
+ int rc;
+
+ assert( cursorOwnsBtShared(pCur) );
+ assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
+
+ /* If the cursor already points to the last entry, this is a no-op. */
+ if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
+#ifdef SQLITE_DEBUG
+ /* This block serves to assert() that the cursor really does point
+ ** to the last entry in the b-tree. */
+ int ii;
+ for(ii=0; ii<pCur->iPage; ii++){
+ assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
+ }
+ assert( pCur->ix==pCur->pPage->nCell-1 );
+ assert( pCur->pPage->leaf );
+#endif
+ *pRes = 0;
+ return SQLITE_OK;
+ }
+
+ rc = moveToRoot(pCur);
+ if( rc==SQLITE_OK ){
+ assert( pCur->eState==CURSOR_VALID );
+ *pRes = 0;
+ rc = moveToRightmost(pCur);
+ if( rc==SQLITE_OK ){
+ pCur->curFlags |= BTCF_AtLast;
+ }else{
+ pCur->curFlags &= ~BTCF_AtLast;
+ }
+ }else if( rc==SQLITE_EMPTY ){
+ assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
+ *pRes = 1;
+ rc = SQLITE_OK;
+ }
+ return rc;
+}
+
+/* Move the cursor so that it points to an entry near the key
+** specified by pIdxKey or intKey. Return a success code.
+**
+** For INTKEY tables, the intKey parameter is used. pIdxKey
+** must be NULL. For index tables, pIdxKey is used and intKey
+** is ignored.
+**
+** If an exact match is not found, then the cursor is always
+** left pointing at a leaf page which would hold the entry if it
+** were present. The cursor might point to an entry that comes
+** before or after the key.
+**
+** An integer is written into *pRes which is the result of
+** comparing the key with the entry to which the cursor is
+** pointing. The meaning of the integer written into
+** *pRes is as follows:
+**
+** *pRes<0 The cursor is left pointing at an entry that
+** is smaller than intKey/pIdxKey or if the table is empty
+** and the cursor is therefore left point to nothing.
+**
+** *pRes==0 The cursor is left pointing at an entry that
+** exactly matches intKey/pIdxKey.
+**
+** *pRes>0 The cursor is left pointing at an entry that
+** is larger than intKey/pIdxKey.
+**
+** For index tables, the pIdxKey->eqSeen field is set to 1 if there
+** exists an entry in the table that exactly matches pIdxKey.
+*/
+SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
+ BtCursor *pCur, /* The cursor to be moved */
+ UnpackedRecord *pIdxKey, /* Unpacked index key */
+ i64 intKey, /* The table key */
+ int biasRight, /* If true, bias the search to the high end */
+ int *pRes /* Write search results here */
+){
+ int rc;
+ RecordCompare xRecordCompare;
+
+ assert( cursorOwnsBtShared(pCur) );
+ assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
+ assert( pRes );
+ assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
+ assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
+
+ /* If the cursor is already positioned at the point we are trying
+ ** to move to, then just return without doing any work */
+ if( pIdxKey==0
+ && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
+ ){
+ if( pCur->info.nKey==intKey ){
+ *pRes = 0;
+ return SQLITE_OK;
+ }
+ if( pCur->info.nKey<intKey ){
+ if( (pCur->curFlags & BTCF_AtLast)!=0 ){
+ *pRes = -1;
+ return SQLITE_OK;
+ }
+ /* If the requested key is one more than the previous key, then
+ ** try to get there using sqlite3BtreeNext() rather than a full
+ ** binary search. This is an optimization only. The correct answer
+ ** is still obtained without this case, only a little more slowely */
+ if( pCur->info.nKey+1==intKey ){
+ *pRes = 0;
+ rc = sqlite3BtreeNext(pCur, 0);
+ if( rc==SQLITE_OK ){
+ getCellInfo(pCur);
+ if( pCur->info.nKey==intKey ){
+ return SQLITE_OK;
+ }
+ }else if( rc==SQLITE_DONE ){
+ rc = SQLITE_OK;
+ }else{
+ return rc;
+ }
+ }
+ }
+ }
+
+#ifdef SQLITE_DEBUG
+ pCur->pBtree->nSeek++; /* Performance measurement during testing */
+#endif
+
+ if( pIdxKey ){
+ xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
+ pIdxKey->errCode = 0;
+ assert( pIdxKey->default_rc==1
+ || pIdxKey->default_rc==0
+ || pIdxKey->default_rc==-1
+ );
+ }else{
+ xRecordCompare = 0; /* All keys are integers */
+ }
+
+ rc = moveToRoot(pCur);
+ if( rc ){
+ if( rc==SQLITE_EMPTY ){
+ assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
+ *pRes = -1;
+ return SQLITE_OK;
+ }
+ return rc;
+ }
+ assert( pCur->pPage );
+ assert( pCur->pPage->isInit );
+ assert( pCur->eState==CURSOR_VALID );
+ assert( pCur->pPage->nCell > 0 );
+ assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
+ assert( pCur->curIntKey || pIdxKey );
+ for(;;){
+ int lwr, upr, idx, c;
+ Pgno chldPg;
+ MemPage *pPage = pCur->pPage;
+ u8 *pCell; /* Pointer to current cell in pPage */
+
+ /* pPage->nCell must be greater than zero. If this is the root-page
+ ** the cursor would have been INVALID above and this for(;;) loop
+ ** not run. If this is not the root-page, then the moveToChild() routine
+ ** would have already detected db corruption. Similarly, pPage must
+ ** be the right kind (index or table) of b-tree page. Otherwise
+ ** a moveToChild() or moveToRoot() call would have detected corruption. */
+ assert( pPage->nCell>0 );
+ assert( pPage->intKey==(pIdxKey==0) );
+ lwr = 0;
+ upr = pPage->nCell-1;
+ assert( biasRight==0 || biasRight==1 );
+ idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
+ pCur->ix = (u16)idx;
+ if( xRecordCompare==0 ){
+ for(;;){
+ i64 nCellKey;
+ pCell = findCellPastPtr(pPage, idx);
+ if( pPage->intKeyLeaf ){
+ while( 0x80 <= *(pCell++) ){
+ if( pCell>=pPage->aDataEnd ){
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ }
+ }
+ getVarint(pCell, (u64*)&nCellKey);
+ if( nCellKey<intKey ){
+ lwr = idx+1;
+ if( lwr>upr ){ c = -1; break; }
+ }else if( nCellKey>intKey ){
+ upr = idx-1;
+ if( lwr>upr ){ c = +1; break; }
+ }else{
+ assert( nCellKey==intKey );
+ pCur->ix = (u16)idx;
+ if( !pPage->leaf ){
+ lwr = idx;
+ goto moveto_next_layer;
+ }else{
+ pCur->curFlags |= BTCF_ValidNKey;
+ pCur->info.nKey = nCellKey;
+ pCur->info.nSize = 0;
+ *pRes = 0;
+ return SQLITE_OK;
+ }
+ }
+ assert( lwr+upr>=0 );
+ idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
+ }
+ }else{
+ for(;;){
+ int nCell; /* Size of the pCell cell in bytes */
+ pCell = findCellPastPtr(pPage, idx);
+
+ /* The maximum supported page-size is 65536 bytes. This means that
+ ** the maximum number of record bytes stored on an index B-Tree
+ ** page is less than 16384 bytes and may be stored as a 2-byte
+ ** varint. This information is used to attempt to avoid parsing
+ ** the entire cell by checking for the cases where the record is
+ ** stored entirely within the b-tree page by inspecting the first
+ ** 2 bytes of the cell.
+ */
+ nCell = pCell[0];
+ if( nCell<=pPage->max1bytePayload ){
+ /* This branch runs if the record-size field of the cell is a
+ ** single byte varint and the record fits entirely on the main
+ ** b-tree page. */
+ testcase( pCell+nCell+1==pPage->aDataEnd );
+ c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
+ }else if( !(pCell[1] & 0x80)
+ && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
+ ){
+ /* The record-size field is a 2 byte varint and the record
+ ** fits entirely on the main b-tree page. */
+ testcase( pCell+nCell+2==pPage->aDataEnd );
+ c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
+ }else{
+ /* The record flows over onto one or more overflow pages. In
+ ** this case the whole cell needs to be parsed, a buffer allocated
+ ** and accessPayload() used to retrieve the record into the
+ ** buffer before VdbeRecordCompare() can be called.
+ **
+ ** If the record is corrupt, the xRecordCompare routine may read
+ ** up to two varints past the end of the buffer. An extra 18
+ ** bytes of padding is allocated at the end of the buffer in
+ ** case this happens. */
+ void *pCellKey;
+ u8 * const pCellBody = pCell - pPage->childPtrSize;
+ const int nOverrun = 18; /* Size of the overrun padding */
+ pPage->xParseCell(pPage, pCellBody, &pCur->info);
+ nCell = (int)pCur->info.nKey;
+ testcase( nCell<0 ); /* True if key size is 2^32 or more */
+ testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
+ testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
+ testcase( nCell==2 ); /* Minimum legal index key size */
+ if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
+ rc = SQLITE_CORRUPT_PAGE(pPage);
+ goto moveto_finish;
+ }
+ pCellKey = sqlite3Malloc( nCell+nOverrun );
+ if( pCellKey==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto moveto_finish;
+ }
+ pCur->ix = (u16)idx;
+ rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
+ memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
+ pCur->curFlags &= ~BTCF_ValidOvfl;
+ if( rc ){
+ sqlite3_free(pCellKey);
+ goto moveto_finish;
+ }
+ c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
+ sqlite3_free(pCellKey);
+ }
+ assert(
+ (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
+ && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
+ );
+ if( c<0 ){
+ lwr = idx+1;
+ }else if( c>0 ){
+ upr = idx-1;
+ }else{
+ assert( c==0 );
+ *pRes = 0;
+ rc = SQLITE_OK;
+ pCur->ix = (u16)idx;
+ if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
+ goto moveto_finish;
+ }
+ if( lwr>upr ) break;
+ assert( lwr+upr>=0 );
+ idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
+ }
+ }
+ assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
+ assert( pPage->isInit );
+ if( pPage->leaf ){
+ assert( pCur->ix<pCur->pPage->nCell );
+ pCur->ix = (u16)idx;
+ *pRes = c;
+ rc = SQLITE_OK;
+ goto moveto_finish;
+ }
+moveto_next_layer:
+ if( lwr>=pPage->nCell ){
+ chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
+ }else{
+ chldPg = get4byte(findCell(pPage, lwr));
+ }
+ pCur->ix = (u16)lwr;
+ rc = moveToChild(pCur, chldPg);
+ if( rc ) break;
+ }
+moveto_finish:
+ pCur->info.nSize = 0;
+ assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
+ return rc;
+}
+
+
+/*
+** Return TRUE if the cursor is not pointing at an entry of the table.
+**
+** TRUE will be returned after a call to sqlite3BtreeNext() moves
+** past the last entry in the table or sqlite3BtreePrev() moves past
+** the first entry. TRUE is also returned if the table is empty.
+*/
+SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
+ /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
+ ** have been deleted? This API will need to change to return an error code
+ ** as well as the boolean result value.
+ */
+ return (CURSOR_VALID!=pCur->eState);
+}
+
+/*
+** Return an estimate for the number of rows in the table that pCur is
+** pointing to. Return a negative number if no estimate is currently
+** available.
+*/
+SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
+ i64 n;
+ u8 i;
+
+ assert( cursorOwnsBtShared(pCur) );
+ assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
+
+ /* Currently this interface is only called by the OP_IfSmaller
+ ** opcode, and it that case the cursor will always be valid and
+ ** will always point to a leaf node. */
+ if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
+ if( NEVER(pCur->pPage->leaf==0) ) return -1;
+
+ n = pCur->pPage->nCell;
+ for(i=0; i<pCur->iPage; i++){
+ n *= pCur->apPage[i]->nCell;
+ }
+ return n;
+}
+
+/*
+** Advance the cursor to the next entry in the database.
+** Return value:
+**
+** SQLITE_OK success
+** SQLITE_DONE cursor is already pointing at the last element
+** otherwise some kind of error occurred
+**
+** The main entry point is sqlite3BtreeNext(). That routine is optimized
+** for the common case of merely incrementing the cell counter BtCursor.aiIdx
+** to the next cell on the current page. The (slower) btreeNext() helper
+** routine is called when it is necessary to move to a different page or
+** to restore the cursor.
+**
+** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
+** cursor corresponds to an SQL index and this routine could have been
+** skipped if the SQL index had been a unique index. The F argument
+** is a hint to the implement. SQLite btree implementation does not use
+** this hint, but COMDB2 does.
+*/
+static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
+ int rc;
+ int idx;
+ MemPage *pPage;
+
+ assert( cursorOwnsBtShared(pCur) );
+ if( pCur->eState!=CURSOR_VALID ){
+ assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
+ rc = restoreCursorPosition(pCur);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ if( CURSOR_INVALID==pCur->eState ){
+ return SQLITE_DONE;
+ }
+ if( pCur->eState==CURSOR_SKIPNEXT ){
+ pCur->eState = CURSOR_VALID;
+ if( pCur->skipNext>0 ) return SQLITE_OK;
+ }
+ }
+
+ pPage = pCur->pPage;
+ idx = ++pCur->ix;
+ if( !pPage->isInit || sqlite3FaultSim(412) ){
+ /* The only known way for this to happen is for there to be a
+ ** recursive SQL function that does a DELETE operation as part of a
+ ** SELECT which deletes content out from under an active cursor
+ ** in a corrupt database file where the table being DELETE-ed from
+ ** has pages in common with the table being queried. See TH3
+ ** module cov1/btree78.test testcase 220 (2018-06-08) for an
+ ** example. */
+ return SQLITE_CORRUPT_BKPT;
+ }
+
+ /* If the database file is corrupt, it is possible for the value of idx
+ ** to be invalid here. This can only occur if a second cursor modifies
+ ** the page while cursor pCur is holding a reference to it. Which can
+ ** only happen if the database is corrupt in such a way as to link the
+ ** page into more than one b-tree structure.
+ **
+ ** Update 2019-12-23: appears to long longer be possible after the
+ ** addition of anotherValidCursor() condition on balance_deeper(). */
+ harmless( idx>pPage->nCell );
+
+ if( idx>=pPage->nCell ){
+ if( !pPage->leaf ){
+ rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
+ if( rc ) return rc;
+ return moveToLeftmost(pCur);
+ }
+ do{
+ if( pCur->iPage==0 ){
+ pCur->eState = CURSOR_INVALID;
+ return SQLITE_DONE;
+ }
+ moveToParent(pCur);
+ pPage = pCur->pPage;
+ }while( pCur->ix>=pPage->nCell );
+ if( pPage->intKey ){
+ return sqlite3BtreeNext(pCur, 0);
+ }else{
+ return SQLITE_OK;
+ }
+ }
+ if( pPage->leaf ){
+ return SQLITE_OK;
+ }else{
+ return moveToLeftmost(pCur);
+ }
+}
+SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){
+ MemPage *pPage;
+ UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
+ assert( cursorOwnsBtShared(pCur) );
+ assert( flags==0 || flags==1 );
+ pCur->info.nSize = 0;
+ pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
+ if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
+ pPage = pCur->pPage;
+ if( (++pCur->ix)>=pPage->nCell ){
+ pCur->ix--;
+ return btreeNext(pCur);
+ }
+ if( pPage->leaf ){
+ return SQLITE_OK;
+ }else{
+ return moveToLeftmost(pCur);
+ }
+}
+
+/*
+** Step the cursor to the back to the previous entry in the database.
+** Return values:
+**
+** SQLITE_OK success
+** SQLITE_DONE the cursor is already on the first element of the table
+** otherwise some kind of error occurred
+**
+** The main entry point is sqlite3BtreePrevious(). That routine is optimized
+** for the common case of merely decrementing the cell counter BtCursor.aiIdx
+** to the previous cell on the current page. The (slower) btreePrevious()
+** helper routine is called when it is necessary to move to a different page
+** or to restore the cursor.
+**
+** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
+** the cursor corresponds to an SQL index and this routine could have been
+** skipped if the SQL index had been a unique index. The F argument is a
+** hint to the implement. The native SQLite btree implementation does not
+** use this hint, but COMDB2 does.
+*/
+static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
+ int rc;
+ MemPage *pPage;
+
+ assert( cursorOwnsBtShared(pCur) );
+ assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
+ assert( pCur->info.nSize==0 );
+ if( pCur->eState!=CURSOR_VALID ){
+ rc = restoreCursorPosition(pCur);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ if( CURSOR_INVALID==pCur->eState ){
+ return SQLITE_DONE;
+ }
+ if( CURSOR_SKIPNEXT==pCur->eState ){
+ pCur->eState = CURSOR_VALID;
+ if( pCur->skipNext<0 ) return SQLITE_OK;
+ }
+ }
+
+ pPage = pCur->pPage;
+ assert( pPage->isInit );
+ if( !pPage->leaf ){
+ int idx = pCur->ix;
+ rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
+ if( rc ) return rc;
+ rc = moveToRightmost(pCur);
+ }else{
+ while( pCur->ix==0 ){
+ if( pCur->iPage==0 ){
+ pCur->eState = CURSOR_INVALID;
+ return SQLITE_DONE;
+ }
+ moveToParent(pCur);
+ }
+ assert( pCur->info.nSize==0 );
+ assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
+
+ pCur->ix--;
+ pPage = pCur->pPage;
+ if( pPage->intKey && !pPage->leaf ){
+ rc = sqlite3BtreePrevious(pCur, 0);
+ }else{
+ rc = SQLITE_OK;
+ }
+ }
+ return rc;
+}
+SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
+ assert( cursorOwnsBtShared(pCur) );
+ assert( flags==0 || flags==1 );
+ UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
+ pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
+ pCur->info.nSize = 0;
+ if( pCur->eState!=CURSOR_VALID
+ || pCur->ix==0
+ || pCur->pPage->leaf==0
+ ){
+ return btreePrevious(pCur);
+ }
+ pCur->ix--;
+ return SQLITE_OK;
+}
+
+/*
+** Allocate a new page from the database file.
+**
+** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
+** has already been called on the new page.) The new page has also
+** been referenced and the calling routine is responsible for calling
+** sqlite3PagerUnref() on the new page when it is done.
+**
+** SQLITE_OK is returned on success. Any other return value indicates
+** an error. *ppPage is set to NULL in the event of an error.
+**
+** If the "nearby" parameter is not 0, then an effort is made to
+** locate a page close to the page number "nearby". This can be used in an
+** attempt to keep related pages close to each other in the database file,
+** which in turn can make database access faster.
+**
+** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
+** anywhere on the free-list, then it is guaranteed to be returned. If
+** eMode is BTALLOC_LT then the page returned will be less than or equal
+** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
+** are no restrictions on which page is returned.
+*/
+static int allocateBtreePage(
+ BtShared *pBt, /* The btree */
+ MemPage **ppPage, /* Store pointer to the allocated page here */
+ Pgno *pPgno, /* Store the page number here */
+ Pgno nearby, /* Search for a page near this one */
+ u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
+){
+ MemPage *pPage1;
+ int rc;
+ u32 n; /* Number of pages on the freelist */
+ u32 k; /* Number of leaves on the trunk of the freelist */
+ MemPage *pTrunk = 0;
+ MemPage *pPrevTrunk = 0;
+ Pgno mxPage; /* Total size of the database file */
+
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
+ pPage1 = pBt->pPage1;
+ mxPage = btreePagecount(pBt);
+ /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
+ ** stores stores the total number of pages on the freelist. */
+ n = get4byte(&pPage1->aData[36]);
+ testcase( n==mxPage-1 );
+ if( n>=mxPage ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+ if( n>0 ){
+ /* There are pages on the freelist. Reuse one of those pages. */
+ Pgno iTrunk;
+ u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
+ u32 nSearch = 0; /* Count of the number of search attempts */
+
+ /* If eMode==BTALLOC_EXACT and a query of the pointer-map
+ ** shows that the page 'nearby' is somewhere on the free-list, then
+ ** the entire-list will be searched for that page.
+ */
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ if( eMode==BTALLOC_EXACT ){
+ if( nearby<=mxPage ){
+ u8 eType;
+ assert( nearby>0 );
+ assert( pBt->autoVacuum );
+ rc = ptrmapGet(pBt, nearby, &eType, 0);
+ if( rc ) return rc;
+ if( eType==PTRMAP_FREEPAGE ){
+ searchList = 1;
+ }
+ }
+ }else if( eMode==BTALLOC_LE ){
+ searchList = 1;
+ }
+#endif
+
+ /* Decrement the free-list count by 1. Set iTrunk to the index of the
+ ** first free-list trunk page. iPrevTrunk is initially 1.
+ */
+ rc = sqlite3PagerWrite(pPage1->pDbPage);
+ if( rc ) return rc;
+ put4byte(&pPage1->aData[36], n-1);
+
+ /* The code within this loop is run only once if the 'searchList' variable
+ ** is not true. Otherwise, it runs once for each trunk-page on the
+ ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
+ ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
+ */
+ do {
+ pPrevTrunk = pTrunk;
+ if( pPrevTrunk ){
+ /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
+ ** is the page number of the next freelist trunk page in the list or
+ ** zero if this is the last freelist trunk page. */
+ iTrunk = get4byte(&pPrevTrunk->aData[0]);
+ }else{
+ /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
+ ** stores the page number of the first page of the freelist, or zero if
+ ** the freelist is empty. */
+ iTrunk = get4byte(&pPage1->aData[32]);
+ }
+ testcase( iTrunk==mxPage );
+ if( iTrunk>mxPage || nSearch++ > n ){
+ rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
+ }else{
+ rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
+ }
+ if( rc ){
+ pTrunk = 0;
+ goto end_allocate_page;
+ }
+ assert( pTrunk!=0 );
+ assert( pTrunk->aData!=0 );
+ /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
+ ** is the number of leaf page pointers to follow. */
+ k = get4byte(&pTrunk->aData[4]);
+ if( k==0 && !searchList ){
+ /* The trunk has no leaves and the list is not being searched.
+ ** So extract the trunk page itself and use it as the newly
+ ** allocated page */
+ assert( pPrevTrunk==0 );
+ rc = sqlite3PagerWrite(pTrunk->pDbPage);
+ if( rc ){
+ goto end_allocate_page;
+ }
+ *pPgno = iTrunk;
+ memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
+ *ppPage = pTrunk;
+ pTrunk = 0;
+ TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
+ }else if( k>(u32)(pBt->usableSize/4 - 2) ){
+ /* Value of k is out of range. Database corruption */
+ rc = SQLITE_CORRUPT_PGNO(iTrunk);
+ goto end_allocate_page;
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ }else if( searchList
+ && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
+ ){
+ /* The list is being searched and this trunk page is the page
+ ** to allocate, regardless of whether it has leaves.
+ */
+ *pPgno = iTrunk;
+ *ppPage = pTrunk;
+ searchList = 0;
+ rc = sqlite3PagerWrite(pTrunk->pDbPage);
+ if( rc ){
+ goto end_allocate_page;
+ }
+ if( k==0 ){
+ if( !pPrevTrunk ){
+ memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
+ }else{
+ rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
+ if( rc!=SQLITE_OK ){
+ goto end_allocate_page;
+ }
+ memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
+ }
+ }else{
+ /* The trunk page is required by the caller but it contains
+ ** pointers to free-list leaves. The first leaf becomes a trunk
+ ** page in this case.
+ */
+ MemPage *pNewTrunk;
+ Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
+ if( iNewTrunk>mxPage ){
+ rc = SQLITE_CORRUPT_PGNO(iTrunk);
+ goto end_allocate_page;
+ }
+ testcase( iNewTrunk==mxPage );
+ rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
+ if( rc!=SQLITE_OK ){
+ goto end_allocate_page;
+ }
+ rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
+ if( rc!=SQLITE_OK ){
+ releasePage(pNewTrunk);
+ goto end_allocate_page;
+ }
+ memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
+ put4byte(&pNewTrunk->aData[4], k-1);
+ memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
+ releasePage(pNewTrunk);
+ if( !pPrevTrunk ){
+ assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
+ put4byte(&pPage1->aData[32], iNewTrunk);
+ }else{
+ rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
+ if( rc ){
+ goto end_allocate_page;
+ }
+ put4byte(&pPrevTrunk->aData[0], iNewTrunk);
+ }
+ }
+ pTrunk = 0;
+ TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
+#endif
+ }else if( k>0 ){
+ /* Extract a leaf from the trunk */
+ u32 closest;
+ Pgno iPage;
+ unsigned char *aData = pTrunk->aData;
+ if( nearby>0 ){
+ u32 i;
+ closest = 0;
+ if( eMode==BTALLOC_LE ){
+ for(i=0; i<k; i++){
+ iPage = get4byte(&aData[8+i*4]);
+ if( iPage<=nearby ){
+ closest = i;
+ break;
+ }
+ }
+ }else{
+ int dist;
+ dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
+ for(i=1; i<k; i++){
+ int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
+ if( d2<dist ){
+ closest = i;
+ dist = d2;
+ }
+ }
+ }
+ }else{
+ closest = 0;
+ }
+
+ iPage = get4byte(&aData[8+closest*4]);
+ testcase( iPage==mxPage );
+ if( iPage>mxPage ){
+ rc = SQLITE_CORRUPT_PGNO(iTrunk);
+ goto end_allocate_page;
+ }
+ testcase( iPage==mxPage );
+ if( !searchList
+ || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
+ ){
+ int noContent;
+ *pPgno = iPage;
+ TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
+ ": %d more free pages\n",
+ *pPgno, closest+1, k, pTrunk->pgno, n-1));
+ rc = sqlite3PagerWrite(pTrunk->pDbPage);
+ if( rc ) goto end_allocate_page;
+ if( closest<k-1 ){
+ memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
+ }
+ put4byte(&aData[4], k-1);
+ noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
+ rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3PagerWrite((*ppPage)->pDbPage);
+ if( rc!=SQLITE_OK ){
+ releasePage(*ppPage);
+ *ppPage = 0;
+ }
+ }
+ searchList = 0;
+ }
+ }
+ releasePage(pPrevTrunk);
+ pPrevTrunk = 0;
+ }while( searchList );
+ }else{
+ /* There are no pages on the freelist, so append a new page to the
+ ** database image.
+ **
+ ** Normally, new pages allocated by this block can be requested from the
+ ** pager layer with the 'no-content' flag set. This prevents the pager
+ ** from trying to read the pages content from disk. However, if the
+ ** current transaction has already run one or more incremental-vacuum
+ ** steps, then the page we are about to allocate may contain content
+ ** that is required in the event of a rollback. In this case, do
+ ** not set the no-content flag. This causes the pager to load and journal
+ ** the current page content before overwriting it.
+ **
+ ** Note that the pager will not actually attempt to load or journal
+ ** content for any page that really does lie past the end of the database
+ ** file on disk. So the effects of disabling the no-content optimization
+ ** here are confined to those pages that lie between the end of the
+ ** database image and the end of the database file.
+ */
+ int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
+
+ rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
+ if( rc ) return rc;
+ pBt->nPage++;
+ if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
+
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
+ /* If *pPgno refers to a pointer-map page, allocate two new pages
+ ** at the end of the file instead of one. The first allocated page
+ ** becomes a new pointer-map page, the second is used by the caller.
+ */
+ MemPage *pPg = 0;
+ TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
+ assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
+ rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3PagerWrite(pPg->pDbPage);
+ releasePage(pPg);
+ }
+ if( rc ) return rc;
+ pBt->nPage++;
+ if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
+ }
+#endif
+ put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
+ *pPgno = pBt->nPage;
+
+ assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
+ rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
+ if( rc ) return rc;
+ rc = sqlite3PagerWrite((*ppPage)->pDbPage);
+ if( rc!=SQLITE_OK ){
+ releasePage(*ppPage);
+ *ppPage = 0;
+ }
+ TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
+ }
+
+ assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
+
+end_allocate_page:
+ releasePage(pTrunk);
+ releasePage(pPrevTrunk);
+ assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
+ assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
+ return rc;
+}
+
+/*
+** This function is used to add page iPage to the database file free-list.
+** It is assumed that the page is not already a part of the free-list.
+**
+** The value passed as the second argument to this function is optional.
+** If the caller happens to have a pointer to the MemPage object
+** corresponding to page iPage handy, it may pass it as the second value.
+** Otherwise, it may pass NULL.
+**
+** If a pointer to a MemPage object is passed as the second argument,
+** its reference count is not altered by this function.
+*/
+static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
+ MemPage *pTrunk = 0; /* Free-list trunk page */
+ Pgno iTrunk = 0; /* Page number of free-list trunk page */
+ MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
+ MemPage *pPage; /* Page being freed. May be NULL. */
+ int rc; /* Return Code */
+ u32 nFree; /* Initial number of pages on free-list */
+
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ assert( CORRUPT_DB || iPage>1 );
+ assert( !pMemPage || pMemPage->pgno==iPage );
+
+ if( iPage<2 || iPage>pBt->nPage ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+ if( pMemPage ){
+ pPage = pMemPage;
+ sqlite3PagerRef(pPage->pDbPage);
+ }else{
+ pPage = btreePageLookup(pBt, iPage);
+ }
+
+ /* Increment the free page count on pPage1 */
+ rc = sqlite3PagerWrite(pPage1->pDbPage);
+ if( rc ) goto freepage_out;
+ nFree = get4byte(&pPage1->aData[36]);
+ put4byte(&pPage1->aData[36], nFree+1);
+
+ if( pBt->btsFlags & BTS_SECURE_DELETE ){
+ /* If the secure_delete option is enabled, then
+ ** always fully overwrite deleted information with zeros.
+ */
+ if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
+ || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
+ ){
+ goto freepage_out;
+ }
+ memset(pPage->aData, 0, pPage->pBt->pageSize);
+ }
+
+ /* If the database supports auto-vacuum, write an entry in the pointer-map
+ ** to indicate that the page is free.
+ */
+ if( ISAUTOVACUUM ){
+ ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
+ if( rc ) goto freepage_out;
+ }
+
+ /* Now manipulate the actual database free-list structure. There are two
+ ** possibilities. If the free-list is currently empty, or if the first
+ ** trunk page in the free-list is full, then this page will become a
+ ** new free-list trunk page. Otherwise, it will become a leaf of the
+ ** first trunk page in the current free-list. This block tests if it
+ ** is possible to add the page as a new free-list leaf.
+ */
+ if( nFree!=0 ){
+ u32 nLeaf; /* Initial number of leaf cells on trunk page */
+
+ iTrunk = get4byte(&pPage1->aData[32]);
+ if( iTrunk>btreePagecount(pBt) ){
+ rc = SQLITE_CORRUPT_BKPT;
+ goto freepage_out;
+ }
+ rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
+ if( rc!=SQLITE_OK ){
+ goto freepage_out;
+ }
+
+ nLeaf = get4byte(&pTrunk->aData[4]);
+ assert( pBt->usableSize>32 );
+ if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
+ rc = SQLITE_CORRUPT_BKPT;
+ goto freepage_out;
+ }
+ if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
+ /* In this case there is room on the trunk page to insert the page
+ ** being freed as a new leaf.
+ **
+ ** Note that the trunk page is not really full until it contains
+ ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
+ ** coded. But due to a coding error in versions of SQLite prior to
+ ** 3.6.0, databases with freelist trunk pages holding more than
+ ** usableSize/4 - 8 entries will be reported as corrupt. In order
+ ** to maintain backwards compatibility with older versions of SQLite,
+ ** we will continue to restrict the number of entries to usableSize/4 - 8
+ ** for now. At some point in the future (once everyone has upgraded
+ ** to 3.6.0 or later) we should consider fixing the conditional above
+ ** to read "usableSize/4-2" instead of "usableSize/4-8".
+ **
+ ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
+ ** avoid using the last six entries in the freelist trunk page array in
+ ** order that database files created by newer versions of SQLite can be
+ ** read by older versions of SQLite.
+ */
+ rc = sqlite3PagerWrite(pTrunk->pDbPage);
+ if( rc==SQLITE_OK ){
+ put4byte(&pTrunk->aData[4], nLeaf+1);
+ put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
+ if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
+ sqlite3PagerDontWrite(pPage->pDbPage);
+ }
+ rc = btreeSetHasContent(pBt, iPage);
+ }
+ TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
+ goto freepage_out;
+ }
+ }
+
+ /* If control flows to this point, then it was not possible to add the
+ ** the page being freed as a leaf page of the first trunk in the free-list.
+ ** Possibly because the free-list is empty, or possibly because the
+ ** first trunk in the free-list is full. Either way, the page being freed
+ ** will become the new first trunk page in the free-list.
+ */
+ if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
+ goto freepage_out;
+ }
+ rc = sqlite3PagerWrite(pPage->pDbPage);
+ if( rc!=SQLITE_OK ){
+ goto freepage_out;
+ }
+ put4byte(pPage->aData, iTrunk);
+ put4byte(&pPage->aData[4], 0);
+ put4byte(&pPage1->aData[32], iPage);
+ TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
+
+freepage_out:
+ if( pPage ){
+ pPage->isInit = 0;
+ }
+ releasePage(pPage);
+ releasePage(pTrunk);
+ return rc;
+}
+static void freePage(MemPage *pPage, int *pRC){
+ if( (*pRC)==SQLITE_OK ){
+ *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
+ }
+}
+
+/*
+** Free any overflow pages associated with the given Cell. Store
+** size information about the cell in pInfo.
+*/
+static int clearCell(
+ MemPage *pPage, /* The page that contains the Cell */
+ unsigned char *pCell, /* First byte of the Cell */
+ CellInfo *pInfo /* Size information about the cell */
+){
+ BtShared *pBt;
+ Pgno ovflPgno;
+ int rc;
+ int nOvfl;
+ u32 ovflPageSize;
+
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ pPage->xParseCell(pPage, pCell, pInfo);
+ if( pInfo->nLocal==pInfo->nPayload ){
+ return SQLITE_OK; /* No overflow pages. Return without doing anything */
+ }
+ testcase( pCell + pInfo->nSize == pPage->aDataEnd );
+ testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
+ if( pCell + pInfo->nSize > pPage->aDataEnd ){
+ /* Cell extends past end of page */
+ return SQLITE_CORRUPT_PAGE(pPage);
+ }
+ ovflPgno = get4byte(pCell + pInfo->nSize - 4);
+ pBt = pPage->pBt;
+ assert( pBt->usableSize > 4 );
+ ovflPageSize = pBt->usableSize - 4;
+ nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
+ assert( nOvfl>0 ||
+ (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
+ );
+ while( nOvfl-- ){
+ Pgno iNext = 0;
+ MemPage *pOvfl = 0;
+ if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
+ /* 0 is not a legal page number and page 1 cannot be an
+ ** overflow page. Therefore if ovflPgno<2 or past the end of the
+ ** file the database must be corrupt. */
+ return SQLITE_CORRUPT_BKPT;
+ }
+ if( nOvfl ){
+ rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
+ if( rc ) return rc;
+ }
+
+ if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
+ && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
+ ){
+ /* There is no reason any cursor should have an outstanding reference
+ ** to an overflow page belonging to a cell that is being deleted/updated.
+ ** So if there exists more than one reference to this page, then it
+ ** must not really be an overflow page and the database must be corrupt.
+ ** It is helpful to detect this before calling freePage2(), as
+ ** freePage2() may zero the page contents if secure-delete mode is
+ ** enabled. If this 'overflow' page happens to be a page that the
+ ** caller is iterating through or using in some other way, this
+ ** can be problematic.
+ */
+ rc = SQLITE_CORRUPT_BKPT;
+ }else{
+ rc = freePage2(pBt, pOvfl, ovflPgno);
+ }
+
+ if( pOvfl ){
+ sqlite3PagerUnref(pOvfl->pDbPage);
+ }
+ if( rc ) return rc;
+ ovflPgno = iNext;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Create the byte sequence used to represent a cell on page pPage
+** and write that byte sequence into pCell[]. Overflow pages are
+** allocated and filled in as necessary. The calling procedure
+** is responsible for making sure sufficient space has been allocated
+** for pCell[].
+**
+** Note that pCell does not necessary need to point to the pPage->aData
+** area. pCell might point to some temporary storage. The cell will
+** be constructed in this temporary area then copied into pPage->aData
+** later.
+*/
+static int fillInCell(
+ MemPage *pPage, /* The page that contains the cell */
+ unsigned char *pCell, /* Complete text of the cell */
+ const BtreePayload *pX, /* Payload with which to construct the cell */
+ int *pnSize /* Write cell size here */
+){
+ int nPayload;
+ const u8 *pSrc;
+ int nSrc, n, rc, mn;
+ int spaceLeft;
+ MemPage *pToRelease;
+ unsigned char *pPrior;
+ unsigned char *pPayload;
+ BtShared *pBt;
+ Pgno pgnoOvfl;
+ int nHeader;
+
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+
+ /* pPage is not necessarily writeable since pCell might be auxiliary
+ ** buffer space that is separate from the pPage buffer area */
+ assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
+ || sqlite3PagerIswriteable(pPage->pDbPage) );
+
+ /* Fill in the header. */
+ nHeader = pPage->childPtrSize;
+ if( pPage->intKey ){
+ nPayload = pX->nData + pX->nZero;
+ pSrc = pX->pData;
+ nSrc = pX->nData;
+ assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
+ nHeader += putVarint32(&pCell[nHeader], nPayload);
+ nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
+ }else{
+ assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
+ nSrc = nPayload = (int)pX->nKey;
+ pSrc = pX->pKey;
+ nHeader += putVarint32(&pCell[nHeader], nPayload);
+ }
+
+ /* Fill in the payload */
+ pPayload = &pCell[nHeader];
+ if( nPayload<=pPage->maxLocal ){
+ /* This is the common case where everything fits on the btree page
+ ** and no overflow pages are required. */
+ n = nHeader + nPayload;
+ testcase( n==3 );
+ testcase( n==4 );
+ if( n<4 ) n = 4;
+ *pnSize = n;
+ assert( nSrc<=nPayload );
+ testcase( nSrc<nPayload );
+ memcpy(pPayload, pSrc, nSrc);
+ memset(pPayload+nSrc, 0, nPayload-nSrc);
+ return SQLITE_OK;
+ }
+
+ /* If we reach this point, it means that some of the content will need
+ ** to spill onto overflow pages.
+ */
+ mn = pPage->minLocal;
+ n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
+ testcase( n==pPage->maxLocal );
+ testcase( n==pPage->maxLocal+1 );
+ if( n > pPage->maxLocal ) n = mn;
+ spaceLeft = n;
+ *pnSize = n + nHeader + 4;
+ pPrior = &pCell[nHeader+n];
+ pToRelease = 0;
+ pgnoOvfl = 0;
+ pBt = pPage->pBt;
+
+ /* At this point variables should be set as follows:
+ **
+ ** nPayload Total payload size in bytes
+ ** pPayload Begin writing payload here
+ ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
+ ** that means content must spill into overflow pages.
+ ** *pnSize Size of the local cell (not counting overflow pages)
+ ** pPrior Where to write the pgno of the first overflow page
+ **
+ ** Use a call to btreeParseCellPtr() to verify that the values above
+ ** were computed correctly.
+ */
+#ifdef SQLITE_DEBUG
+ {
+ CellInfo info;
+ pPage->xParseCell(pPage, pCell, &info);
+ assert( nHeader==(int)(info.pPayload - pCell) );
+ assert( info.nKey==pX->nKey );
+ assert( *pnSize == info.nSize );
+ assert( spaceLeft == info.nLocal );
+ }
+#endif
+
+ /* Write the payload into the local Cell and any extra into overflow pages */
+ while( 1 ){
+ n = nPayload;
+ if( n>spaceLeft ) n = spaceLeft;
+
+ /* If pToRelease is not zero than pPayload points into the data area
+ ** of pToRelease. Make sure pToRelease is still writeable. */
+ assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
+
+ /* If pPayload is part of the data area of pPage, then make sure pPage
+ ** is still writeable */
+ assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
+ || sqlite3PagerIswriteable(pPage->pDbPage) );
+
+ if( nSrc>=n ){
+ memcpy(pPayload, pSrc, n);
+ }else if( nSrc>0 ){
+ n = nSrc;
+ memcpy(pPayload, pSrc, n);
+ }else{
+ memset(pPayload, 0, n);
+ }
+ nPayload -= n;
+ if( nPayload<=0 ) break;
+ pPayload += n;
+ pSrc += n;
+ nSrc -= n;
+ spaceLeft -= n;
+ if( spaceLeft==0 ){
+ MemPage *pOvfl = 0;
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
+ if( pBt->autoVacuum ){
+ do{
+ pgnoOvfl++;
+ } while(
+ PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
+ );
+ }
+#endif
+ rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ /* If the database supports auto-vacuum, and the second or subsequent
+ ** overflow page is being allocated, add an entry to the pointer-map
+ ** for that page now.
+ **
+ ** If this is the first overflow page, then write a partial entry
+ ** to the pointer-map. If we write nothing to this pointer-map slot,
+ ** then the optimistic overflow chain processing in clearCell()
+ ** may misinterpret the uninitialized values and delete the
+ ** wrong pages from the database.
+ */
+ if( pBt->autoVacuum && rc==SQLITE_OK ){
+ u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
+ ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
+ if( rc ){
+ releasePage(pOvfl);
+ }
+ }
+#endif
+ if( rc ){
+ releasePage(pToRelease);
+ return rc;
+ }
+
+ /* If pToRelease is not zero than pPrior points into the data area
+ ** of pToRelease. Make sure pToRelease is still writeable. */
+ assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
+
+ /* If pPrior is part of the data area of pPage, then make sure pPage
+ ** is still writeable */
+ assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
+ || sqlite3PagerIswriteable(pPage->pDbPage) );
+
+ put4byte(pPrior, pgnoOvfl);
+ releasePage(pToRelease);
+ pToRelease = pOvfl;
+ pPrior = pOvfl->aData;
+ put4byte(pPrior, 0);
+ pPayload = &pOvfl->aData[4];
+ spaceLeft = pBt->usableSize - 4;
+ }
+ }
+ releasePage(pToRelease);
+ return SQLITE_OK;
+}
+
+/*
+** Remove the i-th cell from pPage. This routine effects pPage only.
+** The cell content is not freed or deallocated. It is assumed that
+** the cell content has been copied someplace else. This routine just
+** removes the reference to the cell from pPage.
+**
+** "sz" must be the number of bytes in the cell.
+*/
+static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
+ u32 pc; /* Offset to cell content of cell being deleted */
+ u8 *data; /* pPage->aData */
+ u8 *ptr; /* Used to move bytes around within data[] */
+ int rc; /* The return code */
+ int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
+
+ if( *pRC ) return;
+ assert( idx>=0 && idx<pPage->nCell );
+ assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
+ assert( sqlite3PagerIswriteable(pPage->pDbPage) );
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ assert( pPage->nFree>=0 );
+ data = pPage->aData;
+ ptr = &pPage->aCellIdx[2*idx];
+ pc = get2byte(ptr);
+ hdr = pPage->hdrOffset;
+ testcase( pc==get2byte(&data[hdr+5]) );
+ testcase( pc+sz==pPage->pBt->usableSize );
+ if( pc+sz > pPage->pBt->usableSize ){
+ *pRC = SQLITE_CORRUPT_BKPT;
+ return;
+ }
+ rc = freeSpace(pPage, pc, sz);
+ if( rc ){
+ *pRC = rc;
+ return;
+ }
+ pPage->nCell--;
+ if( pPage->nCell==0 ){
+ memset(&data[hdr+1], 0, 4);
+ data[hdr+7] = 0;
+ put2byte(&data[hdr+5], pPage->pBt->usableSize);
+ pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
+ - pPage->childPtrSize - 8;
+ }else{
+ memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
+ put2byte(&data[hdr+3], pPage->nCell);
+ pPage->nFree += 2;
+ }
+}
+
+/*
+** Insert a new cell on pPage at cell index "i". pCell points to the
+** content of the cell.
+**
+** If the cell content will fit on the page, then put it there. If it
+** will not fit, then make a copy of the cell content into pTemp if
+** pTemp is not null. Regardless of pTemp, allocate a new entry
+** in pPage->apOvfl[] and make it point to the cell content (either
+** in pTemp or the original pCell) and also record its index.
+** Allocating a new entry in pPage->aCell[] implies that
+** pPage->nOverflow is incremented.
+**
+** *pRC must be SQLITE_OK when this routine is called.
+*/
+static void insertCell(
+ MemPage *pPage, /* Page into which we are copying */
+ int i, /* New cell becomes the i-th cell of the page */
+ u8 *pCell, /* Content of the new cell */
+ int sz, /* Bytes of content in pCell */
+ u8 *pTemp, /* Temp storage space for pCell, if needed */
+ Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
+ int *pRC /* Read and write return code from here */
+){
+ int idx = 0; /* Where to write new cell content in data[] */
+ int j; /* Loop counter */
+ u8 *data; /* The content of the whole page */
+ u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
+
+ assert( *pRC==SQLITE_OK );
+ assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
+ assert( MX_CELL(pPage->pBt)<=10921 );
+ assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
+ assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
+ assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
+ assert( pPage->nFree>=0 );
+ if( pPage->nOverflow || sz+2>pPage->nFree ){
+ if( pTemp ){
+ memcpy(pTemp, pCell, sz);
+ pCell = pTemp;
+ }
+ if( iChild ){
+ put4byte(pCell, iChild);
+ }
+ j = pPage->nOverflow++;
+ /* Comparison against ArraySize-1 since we hold back one extra slot
+ ** as a contingency. In other words, never need more than 3 overflow
+ ** slots but 4 are allocated, just to be safe. */
+ assert( j < ArraySize(pPage->apOvfl)-1 );
+ pPage->apOvfl[j] = pCell;
+ pPage->aiOvfl[j] = (u16)i;
+
+ /* When multiple overflows occur, they are always sequential and in
+ ** sorted order. This invariants arise because multiple overflows can
+ ** only occur when inserting divider cells into the parent page during
+ ** balancing, and the dividers are adjacent and sorted.
+ */
+ assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
+ assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
+ }else{
+ int rc = sqlite3PagerWrite(pPage->pDbPage);
+ if( rc!=SQLITE_OK ){
+ *pRC = rc;
+ return;
+ }
+ assert( sqlite3PagerIswriteable(pPage->pDbPage) );
+ data = pPage->aData;
+ assert( &data[pPage->cellOffset]==pPage->aCellIdx );
+ rc = allocateSpace(pPage, sz, &idx);
+ if( rc ){ *pRC = rc; return; }
+ /* The allocateSpace() routine guarantees the following properties
+ ** if it returns successfully */
+ assert( idx >= 0 );
+ assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
+ assert( idx+sz <= (int)pPage->pBt->usableSize );
+ pPage->nFree -= (u16)(2 + sz);
+ if( iChild ){
+ /* In a corrupt database where an entry in the cell index section of
+ ** a btree page has a value of 3 or less, the pCell value might point
+ ** as many as 4 bytes in front of the start of the aData buffer for
+ ** the source page. Make sure this does not cause problems by not
+ ** reading the first 4 bytes */
+ memcpy(&data[idx+4], pCell+4, sz-4);
+ put4byte(&data[idx], iChild);
+ }else{
+ memcpy(&data[idx], pCell, sz);
+ }
+ pIns = pPage->aCellIdx + i*2;
+ memmove(pIns+2, pIns, 2*(pPage->nCell - i));
+ put2byte(pIns, idx);
+ pPage->nCell++;
+ /* increment the cell count */
+ if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
+ assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ if( pPage->pBt->autoVacuum ){
+ /* The cell may contain a pointer to an overflow page. If so, write
+ ** the entry for the overflow page into the pointer map.
+ */
+ ptrmapPutOvflPtr(pPage, pPage, pCell, pRC);
+ }
+#endif
+ }
+}
+
+/*
+** The following parameters determine how many adjacent pages get involved
+** in a balancing operation. NN is the number of neighbors on either side
+** of the page that participate in the balancing operation. NB is the
+** total number of pages that participate, including the target page and
+** NN neighbors on either side.
+**
+** The minimum value of NN is 1 (of course). Increasing NN above 1
+** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
+** in exchange for a larger degradation in INSERT and UPDATE performance.
+** The value of NN appears to give the best results overall.
+**
+** (Later:) The description above makes it seem as if these values are
+** tunable - as if you could change them and recompile and it would all work.
+** But that is unlikely. NB has been 3 since the inception of SQLite and
+** we have never tested any other value.
+*/
+#define NN 1 /* Number of neighbors on either side of pPage */
+#define NB 3 /* (NN*2+1): Total pages involved in the balance */
+
+/*
+** A CellArray object contains a cache of pointers and sizes for a
+** consecutive sequence of cells that might be held on multiple pages.
+**
+** The cells in this array are the divider cell or cells from the pParent
+** page plus up to three child pages. There are a total of nCell cells.
+**
+** pRef is a pointer to one of the pages that contributes cells. This is
+** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
+** which should be common to all pages that contribute cells to this array.
+**
+** apCell[] and szCell[] hold, respectively, pointers to the start of each
+** cell and the size of each cell. Some of the apCell[] pointers might refer
+** to overflow cells. In other words, some apCel[] pointers might not point
+** to content area of the pages.
+**
+** A szCell[] of zero means the size of that cell has not yet been computed.
+**
+** The cells come from as many as four different pages:
+**
+** -----------
+** | Parent |
+** -----------
+** / | \
+** / | \
+** --------- --------- ---------
+** |Child-1| |Child-2| |Child-3|
+** --------- --------- ---------
+**
+** The order of cells is in the array is for an index btree is:
+**
+** 1. All cells from Child-1 in order
+** 2. The first divider cell from Parent
+** 3. All cells from Child-2 in order
+** 4. The second divider cell from Parent
+** 5. All cells from Child-3 in order
+**
+** For a table-btree (with rowids) the items 2 and 4 are empty because
+** content exists only in leaves and there are no divider cells.
+**
+** For an index btree, the apEnd[] array holds pointer to the end of page
+** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
+** respectively. The ixNx[] array holds the number of cells contained in
+** each of these 5 stages, and all stages to the left. Hence:
+**
+** ixNx[0] = Number of cells in Child-1.
+** ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
+** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
+** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
+** ixNx[4] = Total number of cells.
+**
+** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
+** are used and they point to the leaf pages only, and the ixNx value are:
+**
+** ixNx[0] = Number of cells in Child-1.
+** ixNx[1] = Number of cells in Child-1 and Child-2.
+** ixNx[2] = Total number of cells.
+**
+** Sometimes when deleting, a child page can have zero cells. In those
+** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
+** entries, shift down. The end result is that each ixNx[] entry should
+** be larger than the previous
+*/
+typedef struct CellArray CellArray;
+struct CellArray {
+ int nCell; /* Number of cells in apCell[] */
+ MemPage *pRef; /* Reference page */
+ u8 **apCell; /* All cells begin balanced */
+ u16 *szCell; /* Local size of all cells in apCell[] */
+ u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */
+ int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */
+};
+
+/*
+** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
+** computed.
+*/
+static void populateCellCache(CellArray *p, int idx, int N){
+ assert( idx>=0 && idx+N<=p->nCell );
+ while( N>0 ){
+ assert( p->apCell[idx]!=0 );
+ if( p->szCell[idx]==0 ){
+ p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
+ }else{
+ assert( CORRUPT_DB ||
+ p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
+ }
+ idx++;
+ N--;
+ }
+}
+
+/*
+** Return the size of the Nth element of the cell array
+*/
+static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
+ assert( N>=0 && N<p->nCell );
+ assert( p->szCell[N]==0 );
+ p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
+ return p->szCell[N];
+}
+static u16 cachedCellSize(CellArray *p, int N){
+ assert( N>=0 && N<p->nCell );
+ if( p->szCell[N] ) return p->szCell[N];
+ return computeCellSize(p, N);
+}
+
+/*
+** Array apCell[] contains pointers to nCell b-tree page cells. The
+** szCell[] array contains the size in bytes of each cell. This function
+** replaces the current contents of page pPg with the contents of the cell
+** array.
+**
+** Some of the cells in apCell[] may currently be stored in pPg. This
+** function works around problems caused by this by making a copy of any
+** such cells before overwriting the page data.
+**
+** The MemPage.nFree field is invalidated by this function. It is the
+** responsibility of the caller to set it correctly.
+*/
+static int rebuildPage(
+ CellArray *pCArray, /* Content to be added to page pPg */
+ int iFirst, /* First cell in pCArray to use */
+ int nCell, /* Final number of cells on page */
+ MemPage *pPg /* The page to be reconstructed */
+){
+ const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
+ u8 * const aData = pPg->aData; /* Pointer to data for pPg */
+ const int usableSize = pPg->pBt->usableSize;
+ u8 * const pEnd = &aData[usableSize];
+ int i = iFirst; /* Which cell to copy from pCArray*/
+ u32 j; /* Start of cell content area */
+ int iEnd = i+nCell; /* Loop terminator */
+ u8 *pCellptr = pPg->aCellIdx;
+ u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
+ u8 *pData;
+ int k; /* Current slot in pCArray->apEnd[] */
+ u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */
+
+ assert( i<iEnd );
+ j = get2byte(&aData[hdr+5]);
+ if( NEVER(j>(u32)usableSize) ){ j = 0; }
+ memcpy(&pTmp[j], &aData[j], usableSize - j);
+
+ for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
+ pSrcEnd = pCArray->apEnd[k];
+
+ pData = pEnd;
+ while( 1/*exit by break*/ ){
+ u8 *pCell = pCArray->apCell[i];
+ u16 sz = pCArray->szCell[i];
+ assert( sz>0 );
+ if( SQLITE_WITHIN(pCell,aData,pEnd) ){
+ if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
+ pCell = &pTmp[pCell - aData];
+ }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
+ && (uptr)(pCell)<(uptr)pSrcEnd
+ ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+
+ pData -= sz;
+ put2byte(pCellptr, (pData - aData));
+ pCellptr += 2;
+ if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
+ memcpy(pData, pCell, sz);
+ assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
+ testcase( sz!=pPg->xCellSize(pPg,pCell) )
+ i++;
+ if( i>=iEnd ) break;
+ if( pCArray->ixNx[k]<=i ){
+ k++;
+ pSrcEnd = pCArray->apEnd[k];
+ }
+ }
+
+ /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
+ pPg->nCell = nCell;
+ pPg->nOverflow = 0;
+
+ put2byte(&aData[hdr+1], 0);
+ put2byte(&aData[hdr+3], pPg->nCell);
+ put2byte(&aData[hdr+5], pData - aData);
+ aData[hdr+7] = 0x00;
+ return SQLITE_OK;
+}
+
+/*
+** The pCArray objects contains pointers to b-tree cells and the cell sizes.
+** This function attempts to add the cells stored in the array to page pPg.
+** If it cannot (because the page needs to be defragmented before the cells
+** will fit), non-zero is returned. Otherwise, if the cells are added
+** successfully, zero is returned.
+**
+** Argument pCellptr points to the first entry in the cell-pointer array
+** (part of page pPg) to populate. After cell apCell[0] is written to the
+** page body, a 16-bit offset is written to pCellptr. And so on, for each
+** cell in the array. It is the responsibility of the caller to ensure
+** that it is safe to overwrite this part of the cell-pointer array.
+**
+** When this function is called, *ppData points to the start of the
+** content area on page pPg. If the size of the content area is extended,
+** *ppData is updated to point to the new start of the content area
+** before returning.
+**
+** Finally, argument pBegin points to the byte immediately following the
+** end of the space required by this page for the cell-pointer area (for
+** all cells - not just those inserted by the current call). If the content
+** area must be extended to before this point in order to accomodate all
+** cells in apCell[], then the cells do not fit and non-zero is returned.
+*/
+static int pageInsertArray(
+ MemPage *pPg, /* Page to add cells to */
+ u8 *pBegin, /* End of cell-pointer array */
+ u8 **ppData, /* IN/OUT: Page content-area pointer */
+ u8 *pCellptr, /* Pointer to cell-pointer area */
+ int iFirst, /* Index of first cell to add */
+ int nCell, /* Number of cells to add to pPg */
+ CellArray *pCArray /* Array of cells */
+){
+ int i = iFirst; /* Loop counter - cell index to insert */
+ u8 *aData = pPg->aData; /* Complete page */
+ u8 *pData = *ppData; /* Content area. A subset of aData[] */
+ int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */
+ int k; /* Current slot in pCArray->apEnd[] */
+ u8 *pEnd; /* Maximum extent of cell data */
+ assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
+ if( iEnd<=iFirst ) return 0;
+ for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
+ pEnd = pCArray->apEnd[k];
+ while( 1 /*Exit by break*/ ){
+ int sz, rc;
+ u8 *pSlot;
+ assert( pCArray->szCell[i]!=0 );
+ sz = pCArray->szCell[i];
+ if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
+ if( (pData - pBegin)<sz ) return 1;
+ pData -= sz;
+ pSlot = pData;
+ }
+ /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
+ ** database. But they might for a corrupt database. Hence use memmove()
+ ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
+ assert( (pSlot+sz)<=pCArray->apCell[i]
+ || pSlot>=(pCArray->apCell[i]+sz)
+ || CORRUPT_DB );
+ if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
+ && (uptr)(pCArray->apCell[i])<(uptr)pEnd
+ ){
+ assert( CORRUPT_DB );
+ (void)SQLITE_CORRUPT_BKPT;
+ return 1;
+ }
+ memmove(pSlot, pCArray->apCell[i], sz);
+ put2byte(pCellptr, (pSlot - aData));
+ pCellptr += 2;
+ i++;
+ if( i>=iEnd ) break;
+ if( pCArray->ixNx[k]<=i ){
+ k++;
+ pEnd = pCArray->apEnd[k];
+ }
+ }
+ *ppData = pData;
+ return 0;
+}
+
+/*
+** The pCArray object contains pointers to b-tree cells and their sizes.
+**
+** This function adds the space associated with each cell in the array
+** that is currently stored within the body of pPg to the pPg free-list.
+** The cell-pointers and other fields of the page are not updated.
+**
+** This function returns the total number of cells added to the free-list.
+*/
+static int pageFreeArray(
+ MemPage *pPg, /* Page to edit */
+ int iFirst, /* First cell to delete */
+ int nCell, /* Cells to delete */
+ CellArray *pCArray /* Array of cells */
+){
+ u8 * const aData = pPg->aData;
+ u8 * const pEnd = &aData[pPg->pBt->usableSize];
+ u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
+ int nRet = 0;
+ int i;
+ int iEnd = iFirst + nCell;
+ u8 *pFree = 0;
+ int szFree = 0;
+
+ for(i=iFirst; i<iEnd; i++){
+ u8 *pCell = pCArray->apCell[i];
+ if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
+ int sz;
+ /* No need to use cachedCellSize() here. The sizes of all cells that
+ ** are to be freed have already been computing while deciding which
+ ** cells need freeing */
+ sz = pCArray->szCell[i]; assert( sz>0 );
+ if( pFree!=(pCell + sz) ){
+ if( pFree ){
+ assert( pFree>aData && (pFree - aData)<65536 );
+ freeSpace(pPg, (u16)(pFree - aData), szFree);
+ }
+ pFree = pCell;
+ szFree = sz;
+ if( pFree+sz>pEnd ) return 0;
+ }else{
+ pFree = pCell;
+ szFree += sz;
+ }
+ nRet++;
+ }
+ }
+ if( pFree ){
+ assert( pFree>aData && (pFree - aData)<65536 );
+ freeSpace(pPg, (u16)(pFree - aData), szFree);
+ }
+ return nRet;
+}
+
+/*
+** pCArray contains pointers to and sizes of all cells in the page being
+** balanced. The current page, pPg, has pPg->nCell cells starting with
+** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells
+** starting at apCell[iNew].
+**
+** This routine makes the necessary adjustments to pPg so that it contains
+** the correct cells after being balanced.
+**
+** The pPg->nFree field is invalid when this function returns. It is the
+** responsibility of the caller to set it correctly.
+*/
+static int editPage(
+ MemPage *pPg, /* Edit this page */
+ int iOld, /* Index of first cell currently on page */
+ int iNew, /* Index of new first cell on page */
+ int nNew, /* Final number of cells on page */
+ CellArray *pCArray /* Array of cells and sizes */
+){
+ u8 * const aData = pPg->aData;
+ const int hdr = pPg->hdrOffset;
+ u8 *pBegin = &pPg->aCellIdx[nNew * 2];
+ int nCell = pPg->nCell; /* Cells stored on pPg */
+ u8 *pData;
+ u8 *pCellptr;
+ int i;
+ int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
+ int iNewEnd = iNew + nNew;
+
+#ifdef SQLITE_DEBUG
+ u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
+ memcpy(pTmp, aData, pPg->pBt->usableSize);
+#endif
+
+ /* Remove cells from the start and end of the page */
+ assert( nCell>=0 );
+ if( iOld<iNew ){
+ int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
+ if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
+ memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
+ nCell -= nShift;
+ }
+ if( iNewEnd < iOldEnd ){
+ int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
+ assert( nCell>=nTail );
+ nCell -= nTail;
+ }
+
+ pData = &aData[get2byteNotZero(&aData[hdr+5])];
+ if( pData<pBegin ) goto editpage_fail;
+
+ /* Add cells to the start of the page */
+ if( iNew<iOld ){
+ int nAdd = MIN(nNew,iOld-iNew);
+ assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
+ assert( nAdd>=0 );
+ pCellptr = pPg->aCellIdx;
+ memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
+ if( pageInsertArray(
+ pPg, pBegin, &pData, pCellptr,
+ iNew, nAdd, pCArray
+ ) ) goto editpage_fail;
+ nCell += nAdd;
+ }
+
+ /* Add any overflow cells */
+ for(i=0; i<pPg->nOverflow; i++){
+ int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
+ if( iCell>=0 && iCell<nNew ){
+ pCellptr = &pPg->aCellIdx[iCell * 2];
+ if( nCell>iCell ){
+ memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
+ }
+ nCell++;
+ cachedCellSize(pCArray, iCell+iNew);
+ if( pageInsertArray(
+ pPg, pBegin, &pData, pCellptr,
+ iCell+iNew, 1, pCArray
+ ) ) goto editpage_fail;
+ }
+ }
+
+ /* Append cells to the end of the page */
+ assert( nCell>=0 );
+ pCellptr = &pPg->aCellIdx[nCell*2];
+ if( pageInsertArray(
+ pPg, pBegin, &pData, pCellptr,
+ iNew+nCell, nNew-nCell, pCArray
+ ) ) goto editpage_fail;
+
+ pPg->nCell = nNew;
+ pPg->nOverflow = 0;
+
+ put2byte(&aData[hdr+3], pPg->nCell);
+ put2byte(&aData[hdr+5], pData - aData);
+
+#ifdef SQLITE_DEBUG
+ for(i=0; i<nNew && !CORRUPT_DB; i++){
+ u8 *pCell = pCArray->apCell[i+iNew];
+ int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
+ if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
+ pCell = &pTmp[pCell - aData];
+ }
+ assert( 0==memcmp(pCell, &aData[iOff],
+ pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
+ }
+#endif
+
+ return SQLITE_OK;
+ editpage_fail:
+ /* Unable to edit this page. Rebuild it from scratch instead. */
+ populateCellCache(pCArray, iNew, nNew);
+ return rebuildPage(pCArray, iNew, nNew, pPg);
+}
+
+
+#ifndef SQLITE_OMIT_QUICKBALANCE
+/*
+** This version of balance() handles the common special case where
+** a new entry is being inserted on the extreme right-end of the
+** tree, in other words, when the new entry will become the largest
+** entry in the tree.
+**
+** Instead of trying to balance the 3 right-most leaf pages, just add
+** a new page to the right-hand side and put the one new entry in
+** that page. This leaves the right side of the tree somewhat
+** unbalanced. But odds are that we will be inserting new entries
+** at the end soon afterwards so the nearly empty page will quickly
+** fill up. On average.
+**
+** pPage is the leaf page which is the right-most page in the tree.
+** pParent is its parent. pPage must have a single overflow entry
+** which is also the right-most entry on the page.
+**
+** The pSpace buffer is used to store a temporary copy of the divider
+** cell that will be inserted into pParent. Such a cell consists of a 4
+** byte page number followed by a variable length integer. In other
+** words, at most 13 bytes. Hence the pSpace buffer must be at
+** least 13 bytes in size.
+*/
+static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
+ BtShared *const pBt = pPage->pBt; /* B-Tree Database */
+ MemPage *pNew; /* Newly allocated page */
+ int rc; /* Return Code */
+ Pgno pgnoNew; /* Page number of pNew */
+
+ assert( sqlite3_mutex_held(pPage->pBt->mutex) );
+ assert( sqlite3PagerIswriteable(pParent->pDbPage) );
+ assert( pPage->nOverflow==1 );
+
+ if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */
+ assert( pPage->nFree>=0 );
+ assert( pParent->nFree>=0 );
+
+ /* Allocate a new page. This page will become the right-sibling of
+ ** pPage. Make the parent page writable, so that the new divider cell
+ ** may be inserted. If both these operations are successful, proceed.
+ */
+ rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
+
+ if( rc==SQLITE_OK ){
+
+ u8 *pOut = &pSpace[4];
+ u8 *pCell = pPage->apOvfl[0];
+ u16 szCell = pPage->xCellSize(pPage, pCell);
+ u8 *pStop;
+ CellArray b;
+
+ assert( sqlite3PagerIswriteable(pNew->pDbPage) );
+ assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
+ zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
+ b.nCell = 1;
+ b.pRef = pPage;
+ b.apCell = &pCell;
+ b.szCell = &szCell;
+ b.apEnd[0] = pPage->aDataEnd;
+ b.ixNx[0] = 2;
+ rc = rebuildPage(&b, 0, 1, pNew);
+ if( NEVER(rc) ){
+ releasePage(pNew);
+ return rc;
+ }
+ pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
+
+ /* If this is an auto-vacuum database, update the pointer map
+ ** with entries for the new page, and any pointer from the
+ ** cell on the page to an overflow page. If either of these
+ ** operations fails, the return code is set, but the contents
+ ** of the parent page are still manipulated by thh code below.
+ ** That is Ok, at this point the parent page is guaranteed to
+ ** be marked as dirty. Returning an error code will cause a
+ ** rollback, undoing any changes made to the parent page.
+ */
+ if( ISAUTOVACUUM ){
+ ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
+ if( szCell>pNew->minLocal ){
+ ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
+ }
+ }
+
+ /* Create a divider cell to insert into pParent. The divider cell
+ ** consists of a 4-byte page number (the page number of pPage) and
+ ** a variable length key value (which must be the same value as the
+ ** largest key on pPage).
+ **
+ ** To find the largest key value on pPage, first find the right-most
+ ** cell on pPage. The first two fields of this cell are the
+ ** record-length (a variable length integer at most 32-bits in size)
+ ** and the key value (a variable length integer, may have any value).
+ ** The first of the while(...) loops below skips over the record-length
+ ** field. The second while(...) loop copies the key value from the
+ ** cell on pPage into the pSpace buffer.
+ */
+ pCell = findCell(pPage, pPage->nCell-1);
+ pStop = &pCell[9];
+ while( (*(pCell++)&0x80) && pCell<pStop );
+ pStop = &pCell[9];
+ while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
+
+ /* Insert the new divider cell into pParent. */
+ if( rc==SQLITE_OK ){
+ insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
+ 0, pPage->pgno, &rc);
+ }
+
+ /* Set the right-child pointer of pParent to point to the new page. */
+ put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
+
+ /* Release the reference to the new page. */
+ releasePage(pNew);
+ }
+
+ return rc;
+}
+#endif /* SQLITE_OMIT_QUICKBALANCE */
+
+#if 0
+/*
+** This function does not contribute anything to the operation of SQLite.
+** it is sometimes activated temporarily while debugging code responsible
+** for setting pointer-map entries.
+*/
+static int ptrmapCheckPages(MemPage **apPage, int nPage){
+ int i, j;
+ for(i=0; i<nPage; i++){
+ Pgno n;
+ u8 e;
+ MemPage *pPage = apPage[i];
+ BtShared *pBt = pPage->pBt;
+ assert( pPage->isInit );
+
+ for(j=0; j<pPage->nCell; j++){
+ CellInfo info;
+ u8 *z;
+
+ z = findCell(pPage, j);
+ pPage->xParseCell(pPage, z, &info);
+ if( info.nLocal<info.nPayload ){
+ Pgno ovfl = get4byte(&z[info.nSize-4]);
+ ptrmapGet(pBt, ovfl, &e, &n);
+ assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
+ }
+ if( !pPage->leaf ){
+ Pgno child = get4byte(z);
+ ptrmapGet(pBt, child, &e, &n);
+ assert( n==pPage->pgno && e==PTRMAP_BTREE );
+ }
+ }
+ if( !pPage->leaf ){
+ Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
+ ptrmapGet(pBt, child, &e, &n);
+ assert( n==pPage->pgno && e==PTRMAP_BTREE );
+ }
+ }
+ return 1;
+}
+#endif
+
+/*
+** This function is used to copy the contents of the b-tree node stored
+** on page pFrom to page pTo. If page pFrom was not a leaf page, then
+** the pointer-map entries for each child page are updated so that the
+** parent page stored in the pointer map is page pTo. If pFrom contained
+** any cells with overflow page pointers, then the corresponding pointer
+** map entries are also updated so that the parent page is page pTo.
+**
+** If pFrom is currently carrying any overflow cells (entries in the
+** MemPage.apOvfl[] array), they are not copied to pTo.
+**
+** Before returning, page pTo is reinitialized using btreeInitPage().
+**
+** The performance of this function is not critical. It is only used by
+** the balance_shallower() and balance_deeper() procedures, neither of
+** which are called often under normal circumstances.
+*/
+static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
+ if( (*pRC)==SQLITE_OK ){
+ BtShared * const pBt = pFrom->pBt;
+ u8 * const aFrom = pFrom->aData;
+ u8 * const aTo = pTo->aData;
+ int const iFromHdr = pFrom->hdrOffset;
+ int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
+ int rc;
+ int iData;
+
+
+ assert( pFrom->isInit );
+ assert( pFrom->nFree>=iToHdr );
+ assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
+
+ /* Copy the b-tree node content from page pFrom to page pTo. */
+ iData = get2byte(&aFrom[iFromHdr+5]);
+ memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
+ memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
+
+ /* Reinitialize page pTo so that the contents of the MemPage structure
+ ** match the new data. The initialization of pTo can actually fail under
+ ** fairly obscure circumstances, even though it is a copy of initialized
+ ** page pFrom.
+ */
+ pTo->isInit = 0;
+ rc = btreeInitPage(pTo);
+ if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
+ if( rc!=SQLITE_OK ){
+ *pRC = rc;
+ return;
+ }
+
+ /* If this is an auto-vacuum database, update the pointer-map entries
+ ** for any b-tree or overflow pages that pTo now contains the pointers to.
+ */
+ if( ISAUTOVACUUM ){
+ *pRC = setChildPtrmaps(pTo);
+ }
+ }
+}
+
+/*
+** This routine redistributes cells on the iParentIdx'th child of pParent
+** (hereafter "the page") and up to 2 siblings so that all pages have about the
+** same amount of free space. Usually a single sibling on either side of the
+** page are used in the balancing, though both siblings might come from one
+** side if the page is the first or last child of its parent. If the page
+** has fewer than 2 siblings (something which can only happen if the page
+** is a root page or a child of a root page) then all available siblings
+** participate in the balancing.
+**
+** The number of siblings of the page might be increased or decreased by
+** one or two in an effort to keep pages nearly full but not over full.
+**
+** Note that when this routine is called, some of the cells on the page
+** might not actually be stored in MemPage.aData[]. This can happen
+** if the page is overfull. This routine ensures that all cells allocated
+** to the page and its siblings fit into MemPage.aData[] before returning.
+**
+** In the course of balancing the page and its siblings, cells may be
+** inserted into or removed from the parent page (pParent). Doing so
+** may cause the parent page to become overfull or underfull. If this
+** happens, it is the responsibility of the caller to invoke the correct
+** balancing routine to fix this problem (see the balance() routine).
+**
+** If this routine fails for any reason, it might leave the database
+** in a corrupted state. So if this routine fails, the database should
+** be rolled back.
+**
+** The third argument to this function, aOvflSpace, is a pointer to a
+** buffer big enough to hold one page. If while inserting cells into the parent
+** page (pParent) the parent page becomes overfull, this buffer is
+** used to store the parent's overflow cells. Because this function inserts
+** a maximum of four divider cells into the parent page, and the maximum
+** size of a cell stored within an internal node is always less than 1/4
+** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
+** enough for all overflow cells.
+**
+** If aOvflSpace is set to a null pointer, this function returns
+** SQLITE_NOMEM.
+*/
+static int balance_nonroot(
+ MemPage *pParent, /* Parent page of siblings being balanced */
+ int iParentIdx, /* Index of "the page" in pParent */
+ u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
+ int isRoot, /* True if pParent is a root-page */
+ int bBulk /* True if this call is part of a bulk load */
+){
+ BtShared *pBt; /* The whole database */
+ int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
+ int nNew = 0; /* Number of pages in apNew[] */
+ int nOld; /* Number of pages in apOld[] */
+ int i, j, k; /* Loop counters */
+ int nxDiv; /* Next divider slot in pParent->aCell[] */
+ int rc = SQLITE_OK; /* The return code */
+ u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
+ int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
+ int usableSpace; /* Bytes in pPage beyond the header */
+ int pageFlags; /* Value of pPage->aData[0] */
+ int iSpace1 = 0; /* First unused byte of aSpace1[] */
+ int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
+ int szScratch; /* Size of scratch memory requested */
+ MemPage *apOld[NB]; /* pPage and up to two siblings */
+ MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
+ u8 *pRight; /* Location in parent of right-sibling pointer */
+ u8 *apDiv[NB-1]; /* Divider cells in pParent */
+ int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
+ int cntOld[NB+2]; /* Old index in b.apCell[] */
+ int szNew[NB+2]; /* Combined size of cells placed on i-th page */
+ u8 *aSpace1; /* Space for copies of dividers cells */
+ Pgno pgno; /* Temp var to store a page number in */
+ u8 abDone[NB+2]; /* True after i'th new page is populated */
+ Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
+ Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
+ u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
+ CellArray b; /* Parsed information on cells being balanced */
+
+ memset(abDone, 0, sizeof(abDone));
+ b.nCell = 0;
+ b.apCell = 0;
+ pBt = pParent->pBt;
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ assert( sqlite3PagerIswriteable(pParent->pDbPage) );
+
+ /* At this point pParent may have at most one overflow cell. And if
+ ** this overflow cell is present, it must be the cell with
+ ** index iParentIdx. This scenario comes about when this function
+ ** is called (indirectly) from sqlite3BtreeDelete().
+ */
+ assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
+ assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
+
+ if( !aOvflSpace ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ assert( pParent->nFree>=0 );
+
+ /* Find the sibling pages to balance. Also locate the cells in pParent
+ ** that divide the siblings. An attempt is made to find NN siblings on
+ ** either side of pPage. More siblings are taken from one side, however,
+ ** if there are fewer than NN siblings on the other side. If pParent
+ ** has NB or fewer children then all children of pParent are taken.
+ **
+ ** This loop also drops the divider cells from the parent page. This
+ ** way, the remainder of the function does not have to deal with any
+ ** overflow cells in the parent page, since if any existed they will
+ ** have already been removed.
+ */
+ i = pParent->nOverflow + pParent->nCell;
+ if( i<2 ){
+ nxDiv = 0;
+ }else{
+ assert( bBulk==0 || bBulk==1 );
+ if( iParentIdx==0 ){
+ nxDiv = 0;
+ }else if( iParentIdx==i ){
+ nxDiv = i-2+bBulk;
+ }else{
+ nxDiv = iParentIdx-1;
+ }
+ i = 2-bBulk;
+ }
+ nOld = i+1;
+ if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
+ pRight = &pParent->aData[pParent->hdrOffset+8];
+ }else{
+ pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
+ }
+ pgno = get4byte(pRight);
+ while( 1 ){
+ rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
+ if( rc ){
+ memset(apOld, 0, (i+1)*sizeof(MemPage*));
+ goto balance_cleanup;
+ }
+ if( apOld[i]->nFree<0 ){
+ rc = btreeComputeFreeSpace(apOld[i]);
+ if( rc ){
+ memset(apOld, 0, (i)*sizeof(MemPage*));
+ goto balance_cleanup;
+ }
+ }
+ if( (i--)==0 ) break;
+
+ if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
+ apDiv[i] = pParent->apOvfl[0];
+ pgno = get4byte(apDiv[i]);
+ szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
+ pParent->nOverflow = 0;
+ }else{
+ apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
+ pgno = get4byte(apDiv[i]);
+ szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
+
+ /* Drop the cell from the parent page. apDiv[i] still points to
+ ** the cell within the parent, even though it has been dropped.
+ ** This is safe because dropping a cell only overwrites the first
+ ** four bytes of it, and this function does not need the first
+ ** four bytes of the divider cell. So the pointer is safe to use
+ ** later on.
+ **
+ ** But not if we are in secure-delete mode. In secure-delete mode,
+ ** the dropCell() routine will overwrite the entire cell with zeroes.
+ ** In this case, temporarily copy the cell into the aOvflSpace[]
+ ** buffer. It will be copied out again as soon as the aSpace[] buffer
+ ** is allocated. */
+ if( pBt->btsFlags & BTS_FAST_SECURE ){
+ int iOff;
+
+ iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
+ if( (iOff+szNew[i])>(int)pBt->usableSize ){
+ rc = SQLITE_CORRUPT_BKPT;
+ memset(apOld, 0, (i+1)*sizeof(MemPage*));
+ goto balance_cleanup;
+ }else{
+ memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
+ apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
+ }
+ }
+ dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
+ }
+ }
+
+ /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
+ ** alignment */
+ nMaxCells = nOld*(MX_CELL(pBt) + ArraySize(pParent->apOvfl));
+ nMaxCells = (nMaxCells + 3)&~3;
+
+ /*
+ ** Allocate space for memory structures
+ */
+ szScratch =
+ nMaxCells*sizeof(u8*) /* b.apCell */
+ + nMaxCells*sizeof(u16) /* b.szCell */
+ + pBt->pageSize; /* aSpace1 */
+
+ assert( szScratch<=7*(int)pBt->pageSize );
+ b.apCell = sqlite3StackAllocRaw(0, szScratch );
+ if( b.apCell==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto balance_cleanup;
+ }
+ b.szCell = (u16*)&b.apCell[nMaxCells];
+ aSpace1 = (u8*)&b.szCell[nMaxCells];
+ assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
+
+ /*
+ ** Load pointers to all cells on sibling pages and the divider cells
+ ** into the local b.apCell[] array. Make copies of the divider cells
+ ** into space obtained from aSpace1[]. The divider cells have already
+ ** been removed from pParent.
+ **
+ ** If the siblings are on leaf pages, then the child pointers of the
+ ** divider cells are stripped from the cells before they are copied
+ ** into aSpace1[]. In this way, all cells in b.apCell[] are without
+ ** child pointers. If siblings are not leaves, then all cell in
+ ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
+ ** are alike.
+ **
+ ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
+ ** leafData: 1 if pPage holds key+data and pParent holds only keys.
+ */
+ b.pRef = apOld[0];
+ leafCorrection = b.pRef->leaf*4;
+ leafData = b.pRef->intKeyLeaf;
+ for(i=0; i<nOld; i++){
+ MemPage *pOld = apOld[i];
+ int limit = pOld->nCell;
+ u8 *aData = pOld->aData;
+ u16 maskPage = pOld->maskPage;
+ u8 *piCell = aData + pOld->cellOffset;
+ u8 *piEnd;
+ VVA_ONLY( int nCellAtStart = b.nCell; )
+
+ /* Verify that all sibling pages are of the same "type" (table-leaf,
+ ** table-interior, index-leaf, or index-interior).
+ */
+ if( pOld->aData[0]!=apOld[0]->aData[0] ){
+ rc = SQLITE_CORRUPT_BKPT;
+ goto balance_cleanup;
+ }
+
+ /* Load b.apCell[] with pointers to all cells in pOld. If pOld
+ ** contains overflow cells, include them in the b.apCell[] array
+ ** in the correct spot.
+ **
+ ** Note that when there are multiple overflow cells, it is always the
+ ** case that they are sequential and adjacent. This invariant arises
+ ** because multiple overflows can only occurs when inserting divider
+ ** cells into a parent on a prior balance, and divider cells are always
+ ** adjacent and are inserted in order. There is an assert() tagged
+ ** with "NOTE 1" in the overflow cell insertion loop to prove this
+ ** invariant.
+ **
+ ** This must be done in advance. Once the balance starts, the cell
+ ** offset section of the btree page will be overwritten and we will no
+ ** long be able to find the cells if a pointer to each cell is not saved
+ ** first.
+ */
+ memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
+ if( pOld->nOverflow>0 ){
+ if( NEVER(limit<pOld->aiOvfl[0]) ){
+ rc = SQLITE_CORRUPT_BKPT;
+ goto balance_cleanup;
+ }
+ limit = pOld->aiOvfl[0];
+ for(j=0; j<limit; j++){
+ b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
+ piCell += 2;
+ b.nCell++;
+ }
+ for(k=0; k<pOld->nOverflow; k++){
+ assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
+ b.apCell[b.nCell] = pOld->apOvfl[k];
+ b.nCell++;
+ }
+ }
+ piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
+ while( piCell<piEnd ){
+ assert( b.nCell<nMaxCells );
+ b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
+ piCell += 2;
+ b.nCell++;
+ }
+ assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
+
+ cntOld[i] = b.nCell;
+ if( i<nOld-1 && !leafData){
+ u16 sz = (u16)szNew[i];
+ u8 *pTemp;
+ assert( b.nCell<nMaxCells );
+ b.szCell[b.nCell] = sz;
+ pTemp = &aSpace1[iSpace1];
+ iSpace1 += sz;
+ assert( sz<=pBt->maxLocal+23 );
+ assert( iSpace1 <= (int)pBt->pageSize );
+ memcpy(pTemp, apDiv[i], sz);
+ b.apCell[b.nCell] = pTemp+leafCorrection;
+ assert( leafCorrection==0 || leafCorrection==4 );
+ b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
+ if( !pOld->leaf ){
+ assert( leafCorrection==0 );
+ assert( pOld->hdrOffset==0 );
+ /* The right pointer of the child page pOld becomes the left
+ ** pointer of the divider cell */
+ memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
+ }else{
+ assert( leafCorrection==4 );
+ while( b.szCell[b.nCell]<4 ){
+ /* Do not allow any cells smaller than 4 bytes. If a smaller cell
+ ** does exist, pad it with 0x00 bytes. */
+ assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
+ assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
+ aSpace1[iSpace1++] = 0x00;
+ b.szCell[b.nCell]++;
+ }
+ }
+ b.nCell++;
+ }
+ }
+
+ /*
+ ** Figure out the number of pages needed to hold all b.nCell cells.
+ ** Store this number in "k". Also compute szNew[] which is the total
+ ** size of all cells on the i-th page and cntNew[] which is the index
+ ** in b.apCell[] of the cell that divides page i from page i+1.
+ ** cntNew[k] should equal b.nCell.
+ **
+ ** Values computed by this block:
+ **
+ ** k: The total number of sibling pages
+ ** szNew[i]: Spaced used on the i-th sibling page.
+ ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
+ ** the right of the i-th sibling page.
+ ** usableSpace: Number of bytes of space available on each sibling.
+ **
+ */
+ usableSpace = pBt->usableSize - 12 + leafCorrection;
+ for(i=k=0; i<nOld; i++, k++){
+ MemPage *p = apOld[i];
+ b.apEnd[k] = p->aDataEnd;
+ b.ixNx[k] = cntOld[i];
+ if( k && b.ixNx[k]==b.ixNx[k-1] ){
+ k--; /* Omit b.ixNx[] entry for child pages with no cells */
+ }
+ if( !leafData ){
+ k++;
+ b.apEnd[k] = pParent->aDataEnd;
+ b.ixNx[k] = cntOld[i]+1;
+ }
+ assert( p->nFree>=0 );
+ szNew[i] = usableSpace - p->nFree;
+ for(j=0; j<p->nOverflow; j++){
+ szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
+ }
+ cntNew[i] = cntOld[i];
+ }
+ k = nOld;
+ for(i=0; i<k; i++){
+ int sz;
+ while( szNew[i]>usableSpace ){
+ if( i+1>=k ){
+ k = i+2;
+ if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
+ szNew[k-1] = 0;
+ cntNew[k-1] = b.nCell;
+ }
+ sz = 2 + cachedCellSize(&b, cntNew[i]-1);
+ szNew[i] -= sz;
+ if( !leafData ){
+ if( cntNew[i]<b.nCell ){
+ sz = 2 + cachedCellSize(&b, cntNew[i]);
+ }else{
+ sz = 0;
+ }
+ }
+ szNew[i+1] += sz;
+ cntNew[i]--;
+ }
+ while( cntNew[i]<b.nCell ){
+ sz = 2 + cachedCellSize(&b, cntNew[i]);
+ if( szNew[i]+sz>usableSpace ) break;
+ szNew[i] += sz;
+ cntNew[i]++;
+ if( !leafData ){
+ if( cntNew[i]<b.nCell ){
+ sz = 2 + cachedCellSize(&b, cntNew[i]);
+ }else{
+ sz = 0;
+ }
+ }
+ szNew[i+1] -= sz;
+ }
+ if( cntNew[i]>=b.nCell ){
+ k = i+1;
+ }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
+ rc = SQLITE_CORRUPT_BKPT;
+ goto balance_cleanup;
+ }
+ }
+
+ /*
+ ** The packing computed by the previous block is biased toward the siblings
+ ** on the left side (siblings with smaller keys). The left siblings are
+ ** always nearly full, while the right-most sibling might be nearly empty.
+ ** The next block of code attempts to adjust the packing of siblings to
+ ** get a better balance.
+ **
+ ** This adjustment is more than an optimization. The packing above might
+ ** be so out of balance as to be illegal. For example, the right-most
+ ** sibling might be completely empty. This adjustment is not optional.
+ */
+ for(i=k-1; i>0; i--){
+ int szRight = szNew[i]; /* Size of sibling on the right */
+ int szLeft = szNew[i-1]; /* Size of sibling on the left */
+ int r; /* Index of right-most cell in left sibling */
+ int d; /* Index of first cell to the left of right sibling */
+
+ r = cntNew[i-1] - 1;
+ d = r + 1 - leafData;
+ (void)cachedCellSize(&b, d);
+ do{
+ assert( d<nMaxCells );
+ assert( r<nMaxCells );
+ (void)cachedCellSize(&b, r);
+ if( szRight!=0
+ && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
+ break;
+ }
+ szRight += b.szCell[d] + 2;
+ szLeft -= b.szCell[r] + 2;
+ cntNew[i-1] = r;
+ r--;
+ d--;
+ }while( r>=0 );
+ szNew[i] = szRight;
+ szNew[i-1] = szLeft;
+ if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
+ rc = SQLITE_CORRUPT_BKPT;
+ goto balance_cleanup;
+ }
+ }
+
+ /* Sanity check: For a non-corrupt database file one of the follwing
+ ** must be true:
+ ** (1) We found one or more cells (cntNew[0])>0), or
+ ** (2) pPage is a virtual root page. A virtual root page is when
+ ** the real root page is page 1 and we are the only child of
+ ** that page.
+ */
+ assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
+ TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
+ apOld[0]->pgno, apOld[0]->nCell,
+ nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
+ nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
+ ));
+
+ /*
+ ** Allocate k new pages. Reuse old pages where possible.
+ */
+ pageFlags = apOld[0]->aData[0];
+ for(i=0; i<k; i++){
+ MemPage *pNew;
+ if( i<nOld ){
+ pNew = apNew[i] = apOld[i];
+ apOld[i] = 0;
+ rc = sqlite3PagerWrite(pNew->pDbPage);
+ nNew++;
+ if( rc ) goto balance_cleanup;
+ }else{
+ assert( i>0 );
+ rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
+ if( rc ) goto balance_cleanup;
+ zeroPage(pNew, pageFlags);
+ apNew[i] = pNew;
+ nNew++;
+ cntOld[i] = b.nCell;
+
+ /* Set the pointer-map entry for the new sibling page. */
+ if( ISAUTOVACUUM ){
+ ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
+ if( rc!=SQLITE_OK ){
+ goto balance_cleanup;
+ }
+ }
+ }
+ }
+
+ /*
+ ** Reassign page numbers so that the new pages are in ascending order.
+ ** This helps to keep entries in the disk file in order so that a scan
+ ** of the table is closer to a linear scan through the file. That in turn
+ ** helps the operating system to deliver pages from the disk more rapidly.
+ **
+ ** An O(n^2) insertion sort algorithm is used, but since n is never more
+ ** than (NB+2) (a small constant), that should not be a problem.
+ **
+ ** When NB==3, this one optimization makes the database about 25% faster
+ ** for large insertions and deletions.
+ */
+ for(i=0; i<nNew; i++){
+ aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
+ aPgFlags[i] = apNew[i]->pDbPage->flags;
+ for(j=0; j<i; j++){
+ if( aPgno[j]==aPgno[i] ){
+ /* This branch is taken if the set of sibling pages somehow contains
+ ** duplicate entries. This can happen if the database is corrupt.
+ ** It would be simpler to detect this as part of the loop below, but
+ ** we do the detection here in order to avoid populating the pager
+ ** cache with two separate objects associated with the same
+ ** page number. */
+ assert( CORRUPT_DB );
+ rc = SQLITE_CORRUPT_BKPT;
+ goto balance_cleanup;
+ }
+ }
+ }
+ for(i=0; i<nNew; i++){
+ int iBest = 0; /* aPgno[] index of page number to use */
+ for(j=1; j<nNew; j++){
+ if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
+ }
+ pgno = aPgOrder[iBest];
+ aPgOrder[iBest] = 0xffffffff;
+ if( iBest!=i ){
+ if( iBest>i ){
+ sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
+ }
+ sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
+ apNew[i]->pgno = pgno;
+ }
+ }
+
+ TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
+ "%d(%d nc=%d) %d(%d nc=%d)\n",
+ apNew[0]->pgno, szNew[0], cntNew[0],
+ nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
+ nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
+ nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
+ nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
+ nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
+ nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
+ nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
+ nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
+ ));
+
+ assert( sqlite3PagerIswriteable(pParent->pDbPage) );
+ assert( nNew>=1 && nNew<=ArraySize(apNew) );
+ assert( apNew[nNew-1]!=0 );
+ put4byte(pRight, apNew[nNew-1]->pgno);
+
+ /* If the sibling pages are not leaves, ensure that the right-child pointer
+ ** of the right-most new sibling page is set to the value that was
+ ** originally in the same field of the right-most old sibling page. */
+ if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
+ MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
+ memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
+ }
+
+ /* Make any required updates to pointer map entries associated with
+ ** cells stored on sibling pages following the balance operation. Pointer
+ ** map entries associated with divider cells are set by the insertCell()
+ ** routine. The associated pointer map entries are:
+ **
+ ** a) if the cell contains a reference to an overflow chain, the
+ ** entry associated with the first page in the overflow chain, and
+ **
+ ** b) if the sibling pages are not leaves, the child page associated
+ ** with the cell.
+ **
+ ** If the sibling pages are not leaves, then the pointer map entry
+ ** associated with the right-child of each sibling may also need to be
+ ** updated. This happens below, after the sibling pages have been
+ ** populated, not here.
+ */
+ if( ISAUTOVACUUM ){
+ MemPage *pOld;
+ MemPage *pNew = pOld = apNew[0];
+ int cntOldNext = pNew->nCell + pNew->nOverflow;
+ int iNew = 0;
+ int iOld = 0;
+
+ for(i=0; i<b.nCell; i++){
+ u8 *pCell = b.apCell[i];
+ while( i==cntOldNext ){
+ iOld++;
+ assert( iOld<nNew || iOld<nOld );
+ assert( iOld>=0 && iOld<NB );
+ pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
+ cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
+ }
+ if( i==cntNew[iNew] ){
+ pNew = apNew[++iNew];
+ if( !leafData ) continue;
+ }
+
+ /* Cell pCell is destined for new sibling page pNew. Originally, it
+ ** was either part of sibling page iOld (possibly an overflow cell),
+ ** or else the divider cell to the left of sibling page iOld. So,
+ ** if sibling page iOld had the same page number as pNew, and if
+ ** pCell really was a part of sibling page iOld (not a divider or
+ ** overflow cell), we can skip updating the pointer map entries. */
+ if( iOld>=nNew
+ || pNew->pgno!=aPgno[iOld]
+ || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
+ ){
+ if( !leafCorrection ){
+ ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
+ }
+ if( cachedCellSize(&b,i)>pNew->minLocal ){
+ ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
+ }
+ if( rc ) goto balance_cleanup;
+ }
+ }
+ }
+
+ /* Insert new divider cells into pParent. */
+ for(i=0; i<nNew-1; i++){
+ u8 *pCell;
+ u8 *pTemp;
+ int sz;
+ MemPage *pNew = apNew[i];
+ j = cntNew[i];
+
+ assert( j<nMaxCells );
+ assert( b.apCell[j]!=0 );
+ pCell = b.apCell[j];
+ sz = b.szCell[j] + leafCorrection;
+ pTemp = &aOvflSpace[iOvflSpace];
+ if( !pNew->leaf ){
+ memcpy(&pNew->aData[8], pCell, 4);
+ }else if( leafData ){
+ /* If the tree is a leaf-data tree, and the siblings are leaves,
+ ** then there is no divider cell in b.apCell[]. Instead, the divider
+ ** cell consists of the integer key for the right-most cell of
+ ** the sibling-page assembled above only.
+ */
+ CellInfo info;
+ j--;
+ pNew->xParseCell(pNew, b.apCell[j], &info);
+ pCell = pTemp;
+ sz = 4 + putVarint(&pCell[4], info.nKey);
+ pTemp = 0;
+ }else{
+ pCell -= 4;
+ /* Obscure case for non-leaf-data trees: If the cell at pCell was
+ ** previously stored on a leaf node, and its reported size was 4
+ ** bytes, then it may actually be smaller than this
+ ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
+ ** any cell). But it is important to pass the correct size to
+ ** insertCell(), so reparse the cell now.
+ **
+ ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
+ ** and WITHOUT ROWID tables with exactly one column which is the
+ ** primary key.
+ */
+ if( b.szCell[j]==4 ){
+ assert(leafCorrection==4);
+ sz = pParent->xCellSize(pParent, pCell);
+ }
+ }
+ iOvflSpace += sz;
+ assert( sz<=pBt->maxLocal+23 );
+ assert( iOvflSpace <= (int)pBt->pageSize );
+ insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
+ if( rc!=SQLITE_OK ) goto balance_cleanup;
+ assert( sqlite3PagerIswriteable(pParent->pDbPage) );
+ }
+
+ /* Now update the actual sibling pages. The order in which they are updated
+ ** is important, as this code needs to avoid disrupting any page from which
+ ** cells may still to be read. In practice, this means:
+ **
+ ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
+ ** then it is not safe to update page apNew[iPg] until after
+ ** the left-hand sibling apNew[iPg-1] has been updated.
+ **
+ ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
+ ** then it is not safe to update page apNew[iPg] until after
+ ** the right-hand sibling apNew[iPg+1] has been updated.
+ **
+ ** If neither of the above apply, the page is safe to update.
+ **
+ ** The iPg value in the following loop starts at nNew-1 goes down
+ ** to 0, then back up to nNew-1 again, thus making two passes over
+ ** the pages. On the initial downward pass, only condition (1) above
+ ** needs to be tested because (2) will always be true from the previous
+ ** step. On the upward pass, both conditions are always true, so the
+ ** upwards pass simply processes pages that were missed on the downward
+ ** pass.
+ */
+ for(i=1-nNew; i<nNew; i++){
+ int iPg = i<0 ? -i : i;
+ assert( iPg>=0 && iPg<nNew );
+ if( abDone[iPg] ) continue; /* Skip pages already processed */
+ if( i>=0 /* On the upwards pass, or... */
+ || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
+ ){
+ int iNew;
+ int iOld;
+ int nNewCell;
+
+ /* Verify condition (1): If cells are moving left, update iPg
+ ** only after iPg-1 has already been updated. */
+ assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
+
+ /* Verify condition (2): If cells are moving right, update iPg
+ ** only after iPg+1 has already been updated. */
+ assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
+
+ if( iPg==0 ){
+ iNew = iOld = 0;
+ nNewCell = cntNew[0];
+ }else{
+ iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
+ iNew = cntNew[iPg-1] + !leafData;
+ nNewCell = cntNew[iPg] - iNew;
+ }
+
+ rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
+ if( rc ) goto balance_cleanup;
+ abDone[iPg]++;
+ apNew[iPg]->nFree = usableSpace-szNew[iPg];
+ assert( apNew[iPg]->nOverflow==0 );
+ assert( apNew[iPg]->nCell==nNewCell );
+ }
+ }
+
+ /* All pages have been processed exactly once */
+ assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
+
+ assert( nOld>0 );
+ assert( nNew>0 );
+
+ if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
+ /* The root page of the b-tree now contains no cells. The only sibling
+ ** page is the right-child of the parent. Copy the contents of the
+ ** child page into the parent, decreasing the overall height of the
+ ** b-tree structure by one. This is described as the "balance-shallower"
+ ** sub-algorithm in some documentation.
+ **
+ ** If this is an auto-vacuum database, the call to copyNodeContent()
+ ** sets all pointer-map entries corresponding to database image pages
+ ** for which the pointer is stored within the content being copied.
+ **
+ ** It is critical that the child page be defragmented before being
+ ** copied into the parent, because if the parent is page 1 then it will
+ ** by smaller than the child due to the database header, and so all the
+ ** free space needs to be up front.
+ */
+ assert( nNew==1 || CORRUPT_DB );
+ rc = defragmentPage(apNew[0], -1);
+ testcase( rc!=SQLITE_OK );
+ assert( apNew[0]->nFree ==
+ (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
+ - apNew[0]->nCell*2)
+ || rc!=SQLITE_OK
+ );
+ copyNodeContent(apNew[0], pParent, &rc);
+ freePage(apNew[0], &rc);
+ }else if( ISAUTOVACUUM && !leafCorrection ){
+ /* Fix the pointer map entries associated with the right-child of each
+ ** sibling page. All other pointer map entries have already been taken
+ ** care of. */
+ for(i=0; i<nNew; i++){
+ u32 key = get4byte(&apNew[i]->aData[8]);
+ ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
+ }
+ }
+
+ assert( pParent->isInit );
+ TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
+ nOld, nNew, b.nCell));
+
+ /* Free any old pages that were not reused as new pages.
+ */
+ for(i=nNew; i<nOld; i++){
+ freePage(apOld[i], &rc);
+ }
+
+#if 0
+ if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
+ /* The ptrmapCheckPages() contains assert() statements that verify that
+ ** all pointer map pages are set correctly. This is helpful while
+ ** debugging. This is usually disabled because a corrupt database may
+ ** cause an assert() statement to fail. */
+ ptrmapCheckPages(apNew, nNew);
+ ptrmapCheckPages(&pParent, 1);
+ }
+#endif
+
+ /*
+ ** Cleanup before returning.
+ */
+balance_cleanup:
+ sqlite3StackFree(0, b.apCell);
+ for(i=0; i<nOld; i++){
+ releasePage(apOld[i]);
+ }
+ for(i=0; i<nNew; i++){
+ releasePage(apNew[i]);
+ }
+
+ return rc;
+}
+
+
+/*
+** This function is called when the root page of a b-tree structure is
+** overfull (has one or more overflow pages).
+**
+** A new child page is allocated and the contents of the current root
+** page, including overflow cells, are copied into the child. The root
+** page is then overwritten to make it an empty page with the right-child
+** pointer pointing to the new page.
+**
+** Before returning, all pointer-map entries corresponding to pages
+** that the new child-page now contains pointers to are updated. The
+** entry corresponding to the new right-child pointer of the root
+** page is also updated.
+**
+** If successful, *ppChild is set to contain a reference to the child
+** page and SQLITE_OK is returned. In this case the caller is required
+** to call releasePage() on *ppChild exactly once. If an error occurs,
+** an error code is returned and *ppChild is set to 0.
+*/
+static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
+ int rc; /* Return value from subprocedures */
+ MemPage *pChild = 0; /* Pointer to a new child page */
+ Pgno pgnoChild = 0; /* Page number of the new child page */
+ BtShared *pBt = pRoot->pBt; /* The BTree */
+
+ assert( pRoot->nOverflow>0 );
+ assert( sqlite3_mutex_held(pBt->mutex) );
+
+ /* Make pRoot, the root page of the b-tree, writable. Allocate a new
+ ** page that will become the new right-child of pPage. Copy the contents
+ ** of the node stored on pRoot into the new child page.
+ */
+ rc = sqlite3PagerWrite(pRoot->pDbPage);
+ if( rc==SQLITE_OK ){
+ rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
+ copyNodeContent(pRoot, pChild, &rc);
+ if( ISAUTOVACUUM ){
+ ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
+ }
+ }
+ if( rc ){
+ *ppChild = 0;
+ releasePage(pChild);
+ return rc;
+ }
+ assert( sqlite3PagerIswriteable(pChild->pDbPage) );
+ assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
+ assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
+
+ TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
+
+ /* Copy the overflow cells from pRoot to pChild */
+ memcpy(pChild->aiOvfl, pRoot->aiOvfl,
+ pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
+ memcpy(pChild->apOvfl, pRoot->apOvfl,
+ pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
+ pChild->nOverflow = pRoot->nOverflow;
+
+ /* Zero the contents of pRoot. Then install pChild as the right-child. */
+ zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
+ put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
+
+ *ppChild = pChild;
+ return SQLITE_OK;
+}
+
+/*
+** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
+** on the same B-tree as pCur.
+**
+** This can if a database is corrupt with two or more SQL tables
+** pointing to the same b-tree. If an insert occurs on one SQL table
+** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
+** table linked to the same b-tree. If the secondary insert causes a
+** rebalance, that can change content out from under the cursor on the
+** first SQL table, violating invariants on the first insert.
+*/
+static int anotherValidCursor(BtCursor *pCur){
+ BtCursor *pOther;
+ for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
+ if( pOther!=pCur
+ && pOther->eState==CURSOR_VALID
+ && pOther->pPage==pCur->pPage
+ ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+ }
+ return SQLITE_OK;
+}
+
+/*
+** The page that pCur currently points to has just been modified in
+** some way. This function figures out if this modification means the
+** tree needs to be balanced, and if so calls the appropriate balancing
+** routine. Balancing routines are:
+**
+** balance_quick()
+** balance_deeper()
+** balance_nonroot()
+*/
+static int balance(BtCursor *pCur){
+ int rc = SQLITE_OK;
+ const int nMin = pCur->pBt->usableSize * 2 / 3;
+ u8 aBalanceQuickSpace[13];
+ u8 *pFree = 0;
+
+ VVA_ONLY( int balance_quick_called = 0 );
+ VVA_ONLY( int balance_deeper_called = 0 );
+
+ do {
+ int iPage;
+ MemPage *pPage = pCur->pPage;
+
+ if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
+ if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
+ break;
+ }else if( (iPage = pCur->iPage)==0 ){
+ if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
+ /* The root page of the b-tree is overfull. In this case call the
+ ** balance_deeper() function to create a new child for the root-page
+ ** and copy the current contents of the root-page to it. The
+ ** next iteration of the do-loop will balance the child page.
+ */
+ assert( balance_deeper_called==0 );
+ VVA_ONLY( balance_deeper_called++ );
+ rc = balance_deeper(pPage, &pCur->apPage[1]);
+ if( rc==SQLITE_OK ){
+ pCur->iPage = 1;
+ pCur->ix = 0;
+ pCur->aiIdx[0] = 0;
+ pCur->apPage[0] = pPage;
+ pCur->pPage = pCur->apPage[1];
+ assert( pCur->pPage->nOverflow );
+ }
+ }else{
+ break;
+ }
+ }else{
+ MemPage * const pParent = pCur->apPage[iPage-1];
+ int const iIdx = pCur->aiIdx[iPage-1];
+
+ rc = sqlite3PagerWrite(pParent->pDbPage);
+ if( rc==SQLITE_OK && pParent->nFree<0 ){
+ rc = btreeComputeFreeSpace(pParent);
+ }
+ if( rc==SQLITE_OK ){
+#ifndef SQLITE_OMIT_QUICKBALANCE
+ if( pPage->intKeyLeaf
+ && pPage->nOverflow==1
+ && pPage->aiOvfl[0]==pPage->nCell
+ && pParent->pgno!=1
+ && pParent->nCell==iIdx
+ ){
+ /* Call balance_quick() to create a new sibling of pPage on which
+ ** to store the overflow cell. balance_quick() inserts a new cell
+ ** into pParent, which may cause pParent overflow. If this
+ ** happens, the next iteration of the do-loop will balance pParent
+ ** use either balance_nonroot() or balance_deeper(). Until this
+ ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
+ ** buffer.
+ **
+ ** The purpose of the following assert() is to check that only a
+ ** single call to balance_quick() is made for each call to this
+ ** function. If this were not verified, a subtle bug involving reuse
+ ** of the aBalanceQuickSpace[] might sneak in.
+ */
+ assert( balance_quick_called==0 );
+ VVA_ONLY( balance_quick_called++ );
+ rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
+ }else
+#endif
+ {
+ /* In this case, call balance_nonroot() to redistribute cells
+ ** between pPage and up to 2 of its sibling pages. This involves
+ ** modifying the contents of pParent, which may cause pParent to
+ ** become overfull or underfull. The next iteration of the do-loop
+ ** will balance the parent page to correct this.
+ **
+ ** If the parent page becomes overfull, the overflow cell or cells
+ ** are stored in the pSpace buffer allocated immediately below.
+ ** A subsequent iteration of the do-loop will deal with this by
+ ** calling balance_nonroot() (balance_deeper() may be called first,
+ ** but it doesn't deal with overflow cells - just moves them to a
+ ** different page). Once this subsequent call to balance_nonroot()
+ ** has completed, it is safe to release the pSpace buffer used by
+ ** the previous call, as the overflow cell data will have been
+ ** copied either into the body of a database page or into the new
+ ** pSpace buffer passed to the latter call to balance_nonroot().
+ */
+ u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
+ rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
+ pCur->hints&BTREE_BULKLOAD);
+ if( pFree ){
+ /* If pFree is not NULL, it points to the pSpace buffer used
+ ** by a previous call to balance_nonroot(). Its contents are
+ ** now stored either on real database pages or within the
+ ** new pSpace buffer, so it may be safely freed here. */
+ sqlite3PageFree(pFree);
+ }
+
+ /* The pSpace buffer will be freed after the next call to
+ ** balance_nonroot(), or just before this function returns, whichever
+ ** comes first. */
+ pFree = pSpace;
+ }
+ }
+
+ pPage->nOverflow = 0;
+
+ /* The next iteration of the do-loop balances the parent page. */
+ releasePage(pPage);
+ pCur->iPage--;
+ assert( pCur->iPage>=0 );
+ pCur->pPage = pCur->apPage[pCur->iPage];
+ }
+ }while( rc==SQLITE_OK );
+
+ if( pFree ){
+ sqlite3PageFree(pFree);
+ }
+ return rc;
+}
+
+/* Overwrite content from pX into pDest. Only do the write if the
+** content is different from what is already there.
+*/
+static int btreeOverwriteContent(
+ MemPage *pPage, /* MemPage on which writing will occur */
+ u8 *pDest, /* Pointer to the place to start writing */
+ const BtreePayload *pX, /* Source of data to write */
+ int iOffset, /* Offset of first byte to write */
+ int iAmt /* Number of bytes to be written */
+){
+ int nData = pX->nData - iOffset;
+ if( nData<=0 ){
+ /* Overwritting with zeros */
+ int i;
+ for(i=0; i<iAmt && pDest[i]==0; i++){}
+ if( i<iAmt ){
+ int rc = sqlite3PagerWrite(pPage->pDbPage);
+ if( rc ) return rc;
+ memset(pDest + i, 0, iAmt - i);
+ }
+ }else{
+ if( nData<iAmt ){
+ /* Mixed read data and zeros at the end. Make a recursive call
+ ** to write the zeros then fall through to write the real data */
+ int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
+ iAmt-nData);
+ if( rc ) return rc;
+ iAmt = nData;
+ }
+ if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
+ int rc = sqlite3PagerWrite(pPage->pDbPage);
+ if( rc ) return rc;
+ /* In a corrupt database, it is possible for the source and destination
+ ** buffers to overlap. This is harmless since the database is already
+ ** corrupt but it does cause valgrind and ASAN warnings. So use
+ ** memmove(). */
+ memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
+ }
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Overwrite the cell that cursor pCur is pointing to with fresh content
+** contained in pX.
+*/
+static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
+ int iOffset; /* Next byte of pX->pData to write */
+ int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
+ int rc; /* Return code */
+ MemPage *pPage = pCur->pPage; /* Page being written */
+ BtShared *pBt; /* Btree */
+ Pgno ovflPgno; /* Next overflow page to write */
+ u32 ovflPageSize; /* Size to write on overflow page */
+
+ if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
+ || pCur->info.pPayload < pPage->aData + pPage->cellOffset
+ ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+ /* Overwrite the local portion first */
+ rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
+ 0, pCur->info.nLocal);
+ if( rc ) return rc;
+ if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
+
+ /* Now overwrite the overflow pages */
+ iOffset = pCur->info.nLocal;
+ assert( nTotal>=0 );
+ assert( iOffset>=0 );
+ ovflPgno = get4byte(pCur->info.pPayload + iOffset);
+ pBt = pPage->pBt;
+ ovflPageSize = pBt->usableSize - 4;
+ do{
+ rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
+ if( rc ) return rc;
+ if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
+ rc = SQLITE_CORRUPT_BKPT;
+ }else{
+ if( iOffset+ovflPageSize<(u32)nTotal ){
+ ovflPgno = get4byte(pPage->aData);
+ }else{
+ ovflPageSize = nTotal - iOffset;
+ }
+ rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
+ iOffset, ovflPageSize);
+ }
+ sqlite3PagerUnref(pPage->pDbPage);
+ if( rc ) return rc;
+ iOffset += ovflPageSize;
+ }while( iOffset<nTotal );
+ return SQLITE_OK;
+}
+
+
+/*
+** Insert a new record into the BTree. The content of the new record
+** is described by the pX object. The pCur cursor is used only to
+** define what table the record should be inserted into, and is left
+** pointing at a random location.
+**
+** For a table btree (used for rowid tables), only the pX.nKey value of
+** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
+** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
+** hold the content of the row.
+**
+** For an index btree (used for indexes and WITHOUT ROWID tables), the
+** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
+** pX.pData,nData,nZero fields must be zero.
+**
+** If the seekResult parameter is non-zero, then a successful call to
+** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
+** been performed. In other words, if seekResult!=0 then the cursor
+** is currently pointing to a cell that will be adjacent to the cell
+** to be inserted. If seekResult<0 then pCur points to a cell that is
+** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
+** that is larger than (pKey,nKey).
+**
+** If seekResult==0, that means pCur is pointing at some unknown location.
+** In that case, this routine must seek the cursor to the correct insertion
+** point for (pKey,nKey) before doing the insertion. For index btrees,
+** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
+** key values and pX->aMem can be used instead of pX->pKey to avoid having
+** to decode the key.
+*/
+SQLITE_PRIVATE int sqlite3BtreeInsert(
+ BtCursor *pCur, /* Insert data into the table of this cursor */
+ const BtreePayload *pX, /* Content of the row to be inserted */
+ int flags, /* True if this is likely an append */
+ int seekResult /* Result of prior MovetoUnpacked() call */
+){
+ int rc;
+ int loc = seekResult; /* -1: before desired location +1: after */
+ int szNew = 0;
+ int idx;
+ MemPage *pPage;
+ Btree *p = pCur->pBtree;
+ BtShared *pBt = p->pBt;
+ unsigned char *oldCell;
+ unsigned char *newCell = 0;
+
+ assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
+
+ if( pCur->eState==CURSOR_FAULT ){
+ assert( pCur->skipNext!=SQLITE_OK );
+ return pCur->skipNext;
+ }
+
+ assert( cursorOwnsBtShared(pCur) );
+ assert( (pCur->curFlags & BTCF_WriteFlag)!=0
+ && pBt->inTransaction==TRANS_WRITE
+ && (pBt->btsFlags & BTS_READ_ONLY)==0 );
+ assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
+
+ /* Assert that the caller has been consistent. If this cursor was opened
+ ** expecting an index b-tree, then the caller should be inserting blob
+ ** keys with no associated data. If the cursor was opened expecting an
+ ** intkey table, the caller should be inserting integer keys with a
+ ** blob of associated data. */
+ assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
+
+ /* Save the positions of any other cursors open on this table.
+ **
+ ** In some cases, the call to btreeMoveto() below is a no-op. For
+ ** example, when inserting data into a table with auto-generated integer
+ ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
+ ** integer key to use. It then calls this function to actually insert the
+ ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
+ ** that the cursor is already where it needs to be and returns without
+ ** doing any work. To avoid thwarting these optimizations, it is important
+ ** not to clear the cursor here.
+ */
+ if( pCur->curFlags & BTCF_Multiple ){
+ rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
+ if( rc ) return rc;
+ }
+
+ if( pCur->pKeyInfo==0 ){
+ assert( pX->pKey==0 );
+ /* If this is an insert into a table b-tree, invalidate any incrblob
+ ** cursors open on the row being replaced */
+ invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
+
+ /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
+ ** to a row with the same key as the new entry being inserted.
+ */
+#ifdef SQLITE_DEBUG
+ if( flags & BTREE_SAVEPOSITION ){
+ assert( pCur->curFlags & BTCF_ValidNKey );
+ assert( pX->nKey==pCur->info.nKey );
+ assert( loc==0 );
+ }
+#endif
+
+ /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
+ ** that the cursor is not pointing to a row to be overwritten.
+ ** So do a complete check.
+ */
+ if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
+ /* The cursor is pointing to the entry that is to be
+ ** overwritten */
+ assert( pX->nData>=0 && pX->nZero>=0 );
+ if( pCur->info.nSize!=0
+ && pCur->info.nPayload==(u32)pX->nData+pX->nZero
+ ){
+ /* New entry is the same size as the old. Do an overwrite */
+ return btreeOverwriteCell(pCur, pX);
+ }
+ assert( loc==0 );
+ }else if( loc==0 ){
+ /* The cursor is *not* pointing to the cell to be overwritten, nor
+ ** to an adjacent cell. Move the cursor so that it is pointing either
+ ** to the cell to be overwritten or an adjacent cell.
+ */
+ rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
+ if( rc ) return rc;
+ }
+ }else{
+ /* This is an index or a WITHOUT ROWID table */
+
+ /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
+ ** to a row with the same key as the new entry being inserted.
+ */
+ assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
+
+ /* If the cursor is not already pointing either to the cell to be
+ ** overwritten, or if a new cell is being inserted, if the cursor is
+ ** not pointing to an immediately adjacent cell, then move the cursor
+ ** so that it does.
+ */
+ if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
+ if( pX->nMem ){
+ UnpackedRecord r;
+ r.pKeyInfo = pCur->pKeyInfo;
+ r.aMem = pX->aMem;
+ r.nField = pX->nMem;
+ r.default_rc = 0;
+ r.errCode = 0;
+ r.r1 = 0;
+ r.r2 = 0;
+ r.eqSeen = 0;
+ rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
+ }else{
+ rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
+ }
+ if( rc ) return rc;
+ }
+
+ /* If the cursor is currently pointing to an entry to be overwritten
+ ** and the new content is the same as as the old, then use the
+ ** overwrite optimization.
+ */
+ if( loc==0 ){
+ getCellInfo(pCur);
+ if( pCur->info.nKey==pX->nKey ){
+ BtreePayload x2;
+ x2.pData = pX->pKey;
+ x2.nData = pX->nKey;
+ x2.nZero = 0;
+ return btreeOverwriteCell(pCur, &x2);
+ }
+ }
+
+ }
+ assert( pCur->eState==CURSOR_VALID
+ || (pCur->eState==CURSOR_INVALID && loc)
+ || CORRUPT_DB );
+
+ pPage = pCur->pPage;
+ assert( pPage->intKey || pX->nKey>=0 );
+ assert( pPage->leaf || !pPage->intKey );
+ if( pPage->nFree<0 ){
+ if( pCur->eState>CURSOR_INVALID ){
+ rc = SQLITE_CORRUPT_BKPT;
+ }else{
+ rc = btreeComputeFreeSpace(pPage);
+ }
+ if( rc ) return rc;
+ }
+
+ TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
+ pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
+ loc==0 ? "overwrite" : "new entry"));
+ assert( pPage->isInit );
+ newCell = pBt->pTmpSpace;
+ assert( newCell!=0 );
+ rc = fillInCell(pPage, newCell, pX, &szNew);
+ if( rc ) goto end_insert;
+ assert( szNew==pPage->xCellSize(pPage, newCell) );
+ assert( szNew <= MX_CELL_SIZE(pBt) );
+ idx = pCur->ix;
+ if( loc==0 ){
+ CellInfo info;
+ assert( idx<pPage->nCell );
+ rc = sqlite3PagerWrite(pPage->pDbPage);
+ if( rc ){
+ goto end_insert;
+ }
+ oldCell = findCell(pPage, idx);
+ if( !pPage->leaf ){
+ memcpy(newCell, oldCell, 4);
+ }
+ rc = clearCell(pPage, oldCell, &info);
+ testcase( pCur->curFlags & BTCF_ValidOvfl );
+ invalidateOverflowCache(pCur);
+ if( info.nSize==szNew && info.nLocal==info.nPayload
+ && (!ISAUTOVACUUM || szNew<pPage->minLocal)
+ ){
+ /* Overwrite the old cell with the new if they are the same size.
+ ** We could also try to do this if the old cell is smaller, then add
+ ** the leftover space to the free list. But experiments show that
+ ** doing that is no faster then skipping this optimization and just
+ ** calling dropCell() and insertCell().
+ **
+ ** This optimization cannot be used on an autovacuum database if the
+ ** new entry uses overflow pages, as the insertCell() call below is
+ ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
+ assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
+ if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+ if( oldCell+szNew > pPage->aDataEnd ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+ memcpy(oldCell, newCell, szNew);
+ return SQLITE_OK;
+ }
+ dropCell(pPage, idx, info.nSize, &rc);
+ if( rc ) goto end_insert;
+ }else if( loc<0 && pPage->nCell>0 ){
+ assert( pPage->leaf );
+ idx = ++pCur->ix;
+ pCur->curFlags &= ~BTCF_ValidNKey;
+ }else{
+ assert( pPage->leaf );
+ }
+ insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
+ assert( pPage->nOverflow==0 || rc==SQLITE_OK );
+ assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
+
+ /* If no error has occurred and pPage has an overflow cell, call balance()
+ ** to redistribute the cells within the tree. Since balance() may move
+ ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
+ ** variables.
+ **
+ ** Previous versions of SQLite called moveToRoot() to move the cursor
+ ** back to the root page as balance() used to invalidate the contents
+ ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
+ ** set the cursor state to "invalid". This makes common insert operations
+ ** slightly faster.
+ **
+ ** There is a subtle but important optimization here too. When inserting
+ ** multiple records into an intkey b-tree using a single cursor (as can
+ ** happen while processing an "INSERT INTO ... SELECT" statement), it
+ ** is advantageous to leave the cursor pointing to the last entry in
+ ** the b-tree if possible. If the cursor is left pointing to the last
+ ** entry in the table, and the next row inserted has an integer key
+ ** larger than the largest existing key, it is possible to insert the
+ ** row without seeking the cursor. This can be a big performance boost.
+ */
+ pCur->info.nSize = 0;
+ if( pPage->nOverflow ){
+ assert( rc==SQLITE_OK );
+ pCur->curFlags &= ~(BTCF_ValidNKey);
+ rc = balance(pCur);
+
+ /* Must make sure nOverflow is reset to zero even if the balance()
+ ** fails. Internal data structure corruption will result otherwise.
+ ** Also, set the cursor state to invalid. This stops saveCursorPosition()
+ ** from trying to save the current position of the cursor. */
+ pCur->pPage->nOverflow = 0;
+ pCur->eState = CURSOR_INVALID;
+ if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
+ btreeReleaseAllCursorPages(pCur);
+ if( pCur->pKeyInfo ){
+ assert( pCur->pKey==0 );
+ pCur->pKey = sqlite3Malloc( pX->nKey );
+ if( pCur->pKey==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memcpy(pCur->pKey, pX->pKey, pX->nKey);
+ }
+ }
+ pCur->eState = CURSOR_REQUIRESEEK;
+ pCur->nKey = pX->nKey;
+ }
+ }
+ assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
+
+end_insert:
+ return rc;
+}
+
+/*
+** Delete the entry that the cursor is pointing to.
+**
+** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
+** the cursor is left pointing at an arbitrary location after the delete.
+** But if that bit is set, then the cursor is left in a state such that
+** the next call to BtreeNext() or BtreePrev() moves it to the same row
+** as it would have been on if the call to BtreeDelete() had been omitted.
+**
+** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
+** associated with a single table entry and its indexes. Only one of those
+** deletes is considered the "primary" delete. The primary delete occurs
+** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
+** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
+** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
+** but which might be used by alternative storage engines.
+*/
+SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
+ Btree *p = pCur->pBtree;
+ BtShared *pBt = p->pBt;
+ int rc; /* Return code */
+ MemPage *pPage; /* Page to delete cell from */
+ unsigned char *pCell; /* Pointer to cell to delete */
+ int iCellIdx; /* Index of cell to delete */
+ int iCellDepth; /* Depth of node containing pCell */
+ CellInfo info; /* Size of the cell being deleted */
+ int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
+ u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
+
+ assert( cursorOwnsBtShared(pCur) );
+ assert( pBt->inTransaction==TRANS_WRITE );
+ assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
+ assert( pCur->curFlags & BTCF_WriteFlag );
+ assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
+ assert( !hasReadConflicts(p, pCur->pgnoRoot) );
+ assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
+ if( pCur->eState==CURSOR_REQUIRESEEK ){
+ rc = btreeRestoreCursorPosition(pCur);
+ if( rc ) return rc;
+ }
+ assert( pCur->eState==CURSOR_VALID );
+
+ iCellDepth = pCur->iPage;
+ iCellIdx = pCur->ix;
+ pPage = pCur->pPage;
+ pCell = findCell(pPage, iCellIdx);
+ if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT;
+
+ /* If the bPreserve flag is set to true, then the cursor position must
+ ** be preserved following this delete operation. If the current delete
+ ** will cause a b-tree rebalance, then this is done by saving the cursor
+ ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
+ ** returning.
+ **
+ ** Or, if the current delete will not cause a rebalance, then the cursor
+ ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
+ ** before or after the deleted entry. In this case set bSkipnext to true. */
+ if( bPreserve ){
+ if( !pPage->leaf
+ || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
+ || pPage->nCell==1 /* See dbfuzz001.test for a test case */
+ ){
+ /* A b-tree rebalance will be required after deleting this entry.
+ ** Save the cursor key. */
+ rc = saveCursorKey(pCur);
+ if( rc ) return rc;
+ }else{
+ bSkipnext = 1;
+ }
+ }
+
+ /* If the page containing the entry to delete is not a leaf page, move
+ ** the cursor to the largest entry in the tree that is smaller than
+ ** the entry being deleted. This cell will replace the cell being deleted
+ ** from the internal node. The 'previous' entry is used for this instead
+ ** of the 'next' entry, as the previous entry is always a part of the
+ ** sub-tree headed by the child page of the cell being deleted. This makes
+ ** balancing the tree following the delete operation easier. */
+ if( !pPage->leaf ){
+ rc = sqlite3BtreePrevious(pCur, 0);
+ assert( rc!=SQLITE_DONE );
+ if( rc ) return rc;
+ }
+
+ /* Save the positions of any other cursors open on this table before
+ ** making any modifications. */
+ if( pCur->curFlags & BTCF_Multiple ){
+ rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
+ if( rc ) return rc;
+ }
+
+ /* If this is a delete operation to remove a row from a table b-tree,
+ ** invalidate any incrblob cursors open on the row being deleted. */
+ if( pCur->pKeyInfo==0 ){
+ invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
+ }
+
+ /* Make the page containing the entry to be deleted writable. Then free any
+ ** overflow pages associated with the entry and finally remove the cell
+ ** itself from within the page. */
+ rc = sqlite3PagerWrite(pPage->pDbPage);
+ if( rc ) return rc;
+ rc = clearCell(pPage, pCell, &info);
+ dropCell(pPage, iCellIdx, info.nSize, &rc);
+ if( rc ) return rc;
+
+ /* If the cell deleted was not located on a leaf page, then the cursor
+ ** is currently pointing to the largest entry in the sub-tree headed
+ ** by the child-page of the cell that was just deleted from an internal
+ ** node. The cell from the leaf node needs to be moved to the internal
+ ** node to replace the deleted cell. */
+ if( !pPage->leaf ){
+ MemPage *pLeaf = pCur->pPage;
+ int nCell;
+ Pgno n;
+ unsigned char *pTmp;
+
+ if( pLeaf->nFree<0 ){
+ rc = btreeComputeFreeSpace(pLeaf);
+ if( rc ) return rc;
+ }
+ if( iCellDepth<pCur->iPage-1 ){
+ n = pCur->apPage[iCellDepth+1]->pgno;
+ }else{
+ n = pCur->pPage->pgno;
+ }
+ pCell = findCell(pLeaf, pLeaf->nCell-1);
+ if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
+ nCell = pLeaf->xCellSize(pLeaf, pCell);
+ assert( MX_CELL_SIZE(pBt) >= nCell );
+ pTmp = pBt->pTmpSpace;
+ assert( pTmp!=0 );
+ rc = sqlite3PagerWrite(pLeaf->pDbPage);
+ if( rc==SQLITE_OK ){
+ insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
+ }
+ dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
+ if( rc ) return rc;
+ }
+
+ /* Balance the tree. If the entry deleted was located on a leaf page,
+ ** then the cursor still points to that page. In this case the first
+ ** call to balance() repairs the tree, and the if(...) condition is
+ ** never true.
+ **
+ ** Otherwise, if the entry deleted was on an internal node page, then
+ ** pCur is pointing to the leaf page from which a cell was removed to
+ ** replace the cell deleted from the internal node. This is slightly
+ ** tricky as the leaf node may be underfull, and the internal node may
+ ** be either under or overfull. In this case run the balancing algorithm
+ ** on the leaf node first. If the balance proceeds far enough up the
+ ** tree that we can be sure that any problem in the internal node has
+ ** been corrected, so be it. Otherwise, after balancing the leaf node,
+ ** walk the cursor up the tree to the internal node and balance it as
+ ** well. */
+ rc = balance(pCur);
+ if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
+ releasePageNotNull(pCur->pPage);
+ pCur->iPage--;
+ while( pCur->iPage>iCellDepth ){
+ releasePage(pCur->apPage[pCur->iPage--]);
+ }
+ pCur->pPage = pCur->apPage[pCur->iPage];
+ rc = balance(pCur);
+ }
+
+ if( rc==SQLITE_OK ){
+ if( bSkipnext ){
+ assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
+ assert( pPage==pCur->pPage || CORRUPT_DB );
+ assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
+ pCur->eState = CURSOR_SKIPNEXT;
+ if( iCellIdx>=pPage->nCell ){
+ pCur->skipNext = -1;
+ pCur->ix = pPage->nCell-1;
+ }else{
+ pCur->skipNext = 1;
+ }
+ }else{
+ rc = moveToRoot(pCur);
+ if( bPreserve ){
+ btreeReleaseAllCursorPages(pCur);
+ pCur->eState = CURSOR_REQUIRESEEK;
+ }
+ if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
+ }
+ }
+ return rc;
+}
+
+/*
+** Create a new BTree table. Write into *piTable the page
+** number for the root page of the new table.
+**
+** The type of type is determined by the flags parameter. Only the
+** following values of flags are currently in use. Other values for
+** flags might not work:
+**
+** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
+** BTREE_ZERODATA Used for SQL indices
+*/
+static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
+ BtShared *pBt = p->pBt;
+ MemPage *pRoot;
+ Pgno pgnoRoot;
+ int rc;
+ int ptfFlags; /* Page-type flage for the root page of new table */
+
+ assert( sqlite3BtreeHoldsMutex(p) );
+ assert( pBt->inTransaction==TRANS_WRITE );
+ assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
+
+#ifdef SQLITE_OMIT_AUTOVACUUM
+ rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
+ if( rc ){
+ return rc;
+ }
+#else
+ if( pBt->autoVacuum ){
+ Pgno pgnoMove; /* Move a page here to make room for the root-page */
+ MemPage *pPageMove; /* The page to move to. */
+
+ /* Creating a new table may probably require moving an existing database
+ ** to make room for the new tables root page. In case this page turns
+ ** out to be an overflow page, delete all overflow page-map caches
+ ** held by open cursors.
+ */
+ invalidateAllOverflowCache(pBt);
+
+ /* Read the value of meta[3] from the database to determine where the
+ ** root page of the new table should go. meta[3] is the largest root-page
+ ** created so far, so the new root-page is (meta[3]+1).
+ */
+ sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
+ if( pgnoRoot>btreePagecount(pBt) ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+ pgnoRoot++;
+
+ /* The new root-page may not be allocated on a pointer-map page, or the
+ ** PENDING_BYTE page.
+ */
+ while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
+ pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
+ pgnoRoot++;
+ }
+ assert( pgnoRoot>=3 );
+
+ /* Allocate a page. The page that currently resides at pgnoRoot will
+ ** be moved to the allocated page (unless the allocated page happens
+ ** to reside at pgnoRoot).
+ */
+ rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+
+ if( pgnoMove!=pgnoRoot ){
+ /* pgnoRoot is the page that will be used for the root-page of
+ ** the new table (assuming an error did not occur). But we were
+ ** allocated pgnoMove. If required (i.e. if it was not allocated
+ ** by extending the file), the current page at position pgnoMove
+ ** is already journaled.
+ */
+ u8 eType = 0;
+ Pgno iPtrPage = 0;
+
+ /* Save the positions of any open cursors. This is required in
+ ** case they are holding a reference to an xFetch reference
+ ** corresponding to page pgnoRoot. */
+ rc = saveAllCursors(pBt, 0, 0);
+ releasePage(pPageMove);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+
+ /* Move the page currently at pgnoRoot to pgnoMove. */
+ rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
+ if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
+ rc = SQLITE_CORRUPT_BKPT;
+ }
+ if( rc!=SQLITE_OK ){
+ releasePage(pRoot);
+ return rc;
+ }
+ assert( eType!=PTRMAP_ROOTPAGE );
+ assert( eType!=PTRMAP_FREEPAGE );
+ rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
+ releasePage(pRoot);
+
+ /* Obtain the page at pgnoRoot */
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ rc = sqlite3PagerWrite(pRoot->pDbPage);
+ if( rc!=SQLITE_OK ){
+ releasePage(pRoot);
+ return rc;
+ }
+ }else{
+ pRoot = pPageMove;
+ }
+
+ /* Update the pointer-map and meta-data with the new root-page number. */
+ ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
+ if( rc ){
+ releasePage(pRoot);
+ return rc;
+ }
+
+ /* When the new root page was allocated, page 1 was made writable in
+ ** order either to increase the database filesize, or to decrement the
+ ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
+ */
+ assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
+ rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
+ if( NEVER(rc) ){
+ releasePage(pRoot);
+ return rc;
+ }
+
+ }else{
+ rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
+ if( rc ) return rc;
+ }
+#endif
+ assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
+ if( createTabFlags & BTREE_INTKEY ){
+ ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
+ }else{
+ ptfFlags = PTF_ZERODATA | PTF_LEAF;
+ }
+ zeroPage(pRoot, ptfFlags);
+ sqlite3PagerUnref(pRoot->pDbPage);
+ assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
+ *piTable = pgnoRoot;
+ return SQLITE_OK;
+}
+SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
+ int rc;
+ sqlite3BtreeEnter(p);
+ rc = btreeCreateTable(p, piTable, flags);
+ sqlite3BtreeLeave(p);
+ return rc;
+}
+
+/*
+** Erase the given database page and all its children. Return
+** the page to the freelist.
+*/
+static int clearDatabasePage(
+ BtShared *pBt, /* The BTree that contains the table */
+ Pgno pgno, /* Page number to clear */
+ int freePageFlag, /* Deallocate page if true */
+ int *pnChange /* Add number of Cells freed to this counter */
+){
+ MemPage *pPage;
+ int rc;
+ unsigned char *pCell;
+ int i;
+ int hdr;
+ CellInfo info;
+
+ assert( sqlite3_mutex_held(pBt->mutex) );
+ if( pgno>btreePagecount(pBt) ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+ rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
+ if( rc ) return rc;
+ if( pPage->bBusy ){
+ rc = SQLITE_CORRUPT_BKPT;
+ goto cleardatabasepage_out;
+ }
+ pPage->bBusy = 1;
+ hdr = pPage->hdrOffset;
+ for(i=0; i<pPage->nCell; i++){
+ pCell = findCell(pPage, i);
+ if( !pPage->leaf ){
+ rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
+ if( rc ) goto cleardatabasepage_out;
+ }
+ rc = clearCell(pPage, pCell, &info);
+ if( rc ) goto cleardatabasepage_out;
+ }
+ if( !pPage->leaf ){
+ rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
+ if( rc ) goto cleardatabasepage_out;
+ }else if( pnChange ){
+ assert( pPage->intKey || CORRUPT_DB );
+ testcase( !pPage->intKey );
+ *pnChange += pPage->nCell;
+ }
+ if( freePageFlag ){
+ freePage(pPage, &rc);
+ }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
+ zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
+ }
+
+cleardatabasepage_out:
+ pPage->bBusy = 0;
+ releasePage(pPage);
+ return rc;
+}
+
+/*
+** Delete all information from a single table in the database. iTable is
+** the page number of the root of the table. After this routine returns,
+** the root page is empty, but still exists.
+**
+** This routine will fail with SQLITE_LOCKED if there are any open
+** read cursors on the table. Open write cursors are moved to the
+** root of the table.
+**
+** If pnChange is not NULL, then table iTable must be an intkey table. The
+** integer value pointed to by pnChange is incremented by the number of
+** entries in the table.
+*/
+SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
+ int rc;
+ BtShared *pBt = p->pBt;
+ sqlite3BtreeEnter(p);
+ assert( p->inTrans==TRANS_WRITE );
+
+ rc = saveAllCursors(pBt, (Pgno)iTable, 0);
+
+ if( SQLITE_OK==rc ){
+ /* Invalidate all incrblob cursors open on table iTable (assuming iTable
+ ** is the root of a table b-tree - if it is not, the following call is
+ ** a no-op). */
+ invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
+ rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
+ }
+ sqlite3BtreeLeave(p);
+ return rc;
+}
+
+/*
+** Delete all information from the single table that pCur is open on.
+**
+** This routine only work for pCur on an ephemeral table.
+*/
+SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
+ return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
+}
+
+/*
+** Erase all information in a table and add the root of the table to
+** the freelist. Except, the root of the principle table (the one on
+** page 1) is never added to the freelist.
+**
+** This routine will fail with SQLITE_LOCKED if there are any open
+** cursors on the table.
+**
+** If AUTOVACUUM is enabled and the page at iTable is not the last
+** root page in the database file, then the last root page
+** in the database file is moved into the slot formerly occupied by
+** iTable and that last slot formerly occupied by the last root page
+** is added to the freelist instead of iTable. In this say, all
+** root pages are kept at the beginning of the database file, which
+** is necessary for AUTOVACUUM to work right. *piMoved is set to the
+** page number that used to be the last root page in the file before
+** the move. If no page gets moved, *piMoved is set to 0.
+** The last root page is recorded in meta[3] and the value of
+** meta[3] is updated by this procedure.
+*/
+static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
+ int rc;
+ MemPage *pPage = 0;
+ BtShared *pBt = p->pBt;
+
+ assert( sqlite3BtreeHoldsMutex(p) );
+ assert( p->inTrans==TRANS_WRITE );
+ assert( iTable>=2 );
+ if( iTable>btreePagecount(pBt) ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+
+ rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
+ if( rc ) return rc;
+ rc = sqlite3BtreeClearTable(p, iTable, 0);
+ if( rc ){
+ releasePage(pPage);
+ return rc;
+ }
+
+ *piMoved = 0;
+
+#ifdef SQLITE_OMIT_AUTOVACUUM
+ freePage(pPage, &rc);
+ releasePage(pPage);
+#else
+ if( pBt->autoVacuum ){
+ Pgno maxRootPgno;
+ sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
+
+ if( iTable==maxRootPgno ){
+ /* If the table being dropped is the table with the largest root-page
+ ** number in the database, put the root page on the free list.
+ */
+ freePage(pPage, &rc);
+ releasePage(pPage);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ }else{
+ /* The table being dropped does not have the largest root-page
+ ** number in the database. So move the page that does into the
+ ** gap left by the deleted root-page.
+ */
+ MemPage *pMove;
+ releasePage(pPage);
+ rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
+ releasePage(pMove);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ pMove = 0;
+ rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
+ freePage(pMove, &rc);
+ releasePage(pMove);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ *piMoved = maxRootPgno;
+ }
+
+ /* Set the new 'max-root-page' value in the database header. This
+ ** is the old value less one, less one more if that happens to
+ ** be a root-page number, less one again if that is the
+ ** PENDING_BYTE_PAGE.
+ */
+ maxRootPgno--;
+ while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
+ || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
+ maxRootPgno--;
+ }
+ assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
+
+ rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
+ }else{
+ freePage(pPage, &rc);
+ releasePage(pPage);
+ }
+#endif
+ return rc;
+}
+SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
+ int rc;
+ sqlite3BtreeEnter(p);
+ rc = btreeDropTable(p, iTable, piMoved);
+ sqlite3BtreeLeave(p);
+ return rc;
+}
+
+
+/*
+** This function may only be called if the b-tree connection already
+** has a read or write transaction open on the database.
+**
+** Read the meta-information out of a database file. Meta[0]
+** is the number of free pages currently in the database. Meta[1]
+** through meta[15] are available for use by higher layers. Meta[0]
+** is read-only, the others are read/write.
+**
+** The schema layer numbers meta values differently. At the schema
+** layer (and the SetCookie and ReadCookie opcodes) the number of
+** free pages is not visible. So Cookie[0] is the same as Meta[1].
+**
+** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
+** of reading the value out of the header, it instead loads the "DataVersion"
+** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
+** database file. It is a number computed by the pager. But its access
+** pattern is the same as header meta values, and so it is convenient to
+** read it from this routine.
+*/
+SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
+ BtShared *pBt = p->pBt;
+
+ sqlite3BtreeEnter(p);
+ assert( p->inTrans>TRANS_NONE );
+ assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
+ assert( pBt->pPage1 );
+ assert( idx>=0 && idx<=15 );
+
+ if( idx==BTREE_DATA_VERSION ){
+ *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
+ }else{
+ *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
+ }
+
+ /* If auto-vacuum is disabled in this build and this is an auto-vacuum
+ ** database, mark the database as read-only. */
+#ifdef SQLITE_OMIT_AUTOVACUUM
+ if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
+ pBt->btsFlags |= BTS_READ_ONLY;
+ }
+#endif
+
+ sqlite3BtreeLeave(p);
+}
+
+/*
+** Write meta-information back into the database. Meta[0] is
+** read-only and may not be written.
+*/
+SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
+ BtShared *pBt = p->pBt;
+ unsigned char *pP1;
+ int rc;
+ assert( idx>=1 && idx<=15 );
+ sqlite3BtreeEnter(p);
+ assert( p->inTrans==TRANS_WRITE );
+ assert( pBt->pPage1!=0 );
+ pP1 = pBt->pPage1->aData;
+ rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
+ if( rc==SQLITE_OK ){
+ put4byte(&pP1[36 + idx*4], iMeta);
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ if( idx==BTREE_INCR_VACUUM ){
+ assert( pBt->autoVacuum || iMeta==0 );
+ assert( iMeta==0 || iMeta==1 );
+ pBt->incrVacuum = (u8)iMeta;
+ }
+#endif
+ }
+ sqlite3BtreeLeave(p);
+ return rc;
+}
+
+/*
+** The first argument, pCur, is a cursor opened on some b-tree. Count the
+** number of entries in the b-tree and write the result to *pnEntry.
+**
+** SQLITE_OK is returned if the operation is successfully executed.
+** Otherwise, if an error is encountered (i.e. an IO error or database
+** corruption) an SQLite error code is returned.
+*/
+SQLITE_PRIVATE int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
+ i64 nEntry = 0; /* Value to return in *pnEntry */
+ int rc; /* Return code */
+
+ rc = moveToRoot(pCur);
+ if( rc==SQLITE_EMPTY ){
+ *pnEntry = 0;
+ return SQLITE_OK;
+ }
+
+ /* Unless an error occurs, the following loop runs one iteration for each
+ ** page in the B-Tree structure (not including overflow pages).
+ */
+ while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
+ int iIdx; /* Index of child node in parent */
+ MemPage *pPage; /* Current page of the b-tree */
+
+ /* If this is a leaf page or the tree is not an int-key tree, then
+ ** this page contains countable entries. Increment the entry counter
+ ** accordingly.
+ */
+ pPage = pCur->pPage;
+ if( pPage->leaf || !pPage->intKey ){
+ nEntry += pPage->nCell;
+ }
+
+ /* pPage is a leaf node. This loop navigates the cursor so that it
+ ** points to the first interior cell that it points to the parent of
+ ** the next page in the tree that has not yet been visited. The
+ ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
+ ** of the page, or to the number of cells in the page if the next page
+ ** to visit is the right-child of its parent.
+ **
+ ** If all pages in the tree have been visited, return SQLITE_OK to the
+ ** caller.
+ */
+ if( pPage->leaf ){
+ do {
+ if( pCur->iPage==0 ){
+ /* All pages of the b-tree have been visited. Return successfully. */
+ *pnEntry = nEntry;
+ return moveToRoot(pCur);
+ }
+ moveToParent(pCur);
+ }while ( pCur->ix>=pCur->pPage->nCell );
+
+ pCur->ix++;
+ pPage = pCur->pPage;
+ }
+
+ /* Descend to the child node of the cell that the cursor currently
+ ** points at. This is the right-child if (iIdx==pPage->nCell).
+ */
+ iIdx = pCur->ix;
+ if( iIdx==pPage->nCell ){
+ rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
+ }else{
+ rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
+ }
+ }
+
+ /* An error has occurred. Return an error code. */
+ return rc;
+}
+
+/*
+** Return the pager associated with a BTree. This routine is used for
+** testing and debugging only.
+*/
+SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
+ return p->pBt->pPager;
+}
+
+#ifndef SQLITE_OMIT_INTEGRITY_CHECK
+/*
+** Append a message to the error message string.
+*/
+static void checkAppendMsg(
+ IntegrityCk *pCheck,
+ const char *zFormat,
+ ...
+){
+ va_list ap;
+ if( !pCheck->mxErr ) return;
+ pCheck->mxErr--;
+ pCheck->nErr++;
+ va_start(ap, zFormat);
+ if( pCheck->errMsg.nChar ){
+ sqlite3_str_append(&pCheck->errMsg, "\n", 1);
+ }
+ if( pCheck->zPfx ){
+ sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
+ }
+ sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
+ va_end(ap);
+ if( pCheck->errMsg.accError==SQLITE_NOMEM ){
+ pCheck->bOomFault = 1;
+ }
+}
+#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
+
+#ifndef SQLITE_OMIT_INTEGRITY_CHECK
+
+/*
+** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
+** corresponds to page iPg is already set.
+*/
+static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
+ assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
+ return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
+}
+
+/*
+** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
+*/
+static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
+ assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
+ pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
+}
+
+
+/*
+** Add 1 to the reference count for page iPage. If this is the second
+** reference to the page, add an error message to pCheck->zErrMsg.
+** Return 1 if there are 2 or more references to the page and 0 if
+** if this is the first reference to the page.
+**
+** Also check that the page number is in bounds.
+*/
+static int checkRef(IntegrityCk *pCheck, Pgno iPage){
+ if( iPage>pCheck->nPage || iPage==0 ){
+ checkAppendMsg(pCheck, "invalid page number %d", iPage);
+ return 1;
+ }
+ if( getPageReferenced(pCheck, iPage) ){
+ checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
+ return 1;
+ }
+ if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1;
+ setPageReferenced(pCheck, iPage);
+ return 0;
+}
+
+#ifndef SQLITE_OMIT_AUTOVACUUM
+/*
+** Check that the entry in the pointer-map for page iChild maps to
+** page iParent, pointer type ptrType. If not, append an error message
+** to pCheck.
+*/
+static void checkPtrmap(
+ IntegrityCk *pCheck, /* Integrity check context */
+ Pgno iChild, /* Child page number */
+ u8 eType, /* Expected pointer map type */
+ Pgno iParent /* Expected pointer map parent page number */
+){
+ int rc;
+ u8 ePtrmapType;
+ Pgno iPtrmapParent;
+
+ rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
+ if( rc!=SQLITE_OK ){
+ if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->bOomFault = 1;
+ checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
+ return;
+ }
+
+ if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
+ checkAppendMsg(pCheck,
+ "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
+ iChild, eType, iParent, ePtrmapType, iPtrmapParent);
+ }
+}
+#endif
+
+/*
+** Check the integrity of the freelist or of an overflow page list.
+** Verify that the number of pages on the list is N.
+*/
+static void checkList(
+ IntegrityCk *pCheck, /* Integrity checking context */
+ int isFreeList, /* True for a freelist. False for overflow page list */
+ Pgno iPage, /* Page number for first page in the list */
+ u32 N /* Expected number of pages in the list */
+){
+ int i;
+ u32 expected = N;
+ int nErrAtStart = pCheck->nErr;
+ while( iPage!=0 && pCheck->mxErr ){
+ DbPage *pOvflPage;
+ unsigned char *pOvflData;
+ if( checkRef(pCheck, iPage) ) break;
+ N--;
+ if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
+ checkAppendMsg(pCheck, "failed to get page %d", iPage);
+ break;
+ }
+ pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
+ if( isFreeList ){
+ u32 n = (u32)get4byte(&pOvflData[4]);
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ if( pCheck->pBt->autoVacuum ){
+ checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
+ }
+#endif
+ if( n>pCheck->pBt->usableSize/4-2 ){
+ checkAppendMsg(pCheck,
+ "freelist leaf count too big on page %d", iPage);
+ N--;
+ }else{
+ for(i=0; i<(int)n; i++){
+ Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ if( pCheck->pBt->autoVacuum ){
+ checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
+ }
+#endif
+ checkRef(pCheck, iFreePage);
+ }
+ N -= n;
+ }
+ }
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ else{
+ /* If this database supports auto-vacuum and iPage is not the last
+ ** page in this overflow list, check that the pointer-map entry for
+ ** the following page matches iPage.
+ */
+ if( pCheck->pBt->autoVacuum && N>0 ){
+ i = get4byte(pOvflData);
+ checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
+ }
+ }
+#endif
+ iPage = get4byte(pOvflData);
+ sqlite3PagerUnref(pOvflPage);
+ }
+ if( N && nErrAtStart==pCheck->nErr ){
+ checkAppendMsg(pCheck,
+ "%s is %d but should be %d",
+ isFreeList ? "size" : "overflow list length",
+ expected-N, expected);
+ }
+}
+#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
+
+/*
+** An implementation of a min-heap.
+**
+** aHeap[0] is the number of elements on the heap. aHeap[1] is the
+** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
+** and aHeap[N*2+1].
+**
+** The heap property is this: Every node is less than or equal to both
+** of its daughter nodes. A consequence of the heap property is that the
+** root node aHeap[1] is always the minimum value currently in the heap.
+**
+** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
+** the heap, preserving the heap property. The btreeHeapPull() routine
+** removes the root element from the heap (the minimum value in the heap)
+** and then moves other nodes around as necessary to preserve the heap
+** property.
+**
+** This heap is used for cell overlap and coverage testing. Each u32
+** entry represents the span of a cell or freeblock on a btree page.
+** The upper 16 bits are the index of the first byte of a range and the
+** lower 16 bits are the index of the last byte of that range.
+*/
+static void btreeHeapInsert(u32 *aHeap, u32 x){
+ u32 j, i = ++aHeap[0];
+ aHeap[i] = x;
+ while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
+ x = aHeap[j];
+ aHeap[j] = aHeap[i];
+ aHeap[i] = x;
+ i = j;
+ }
+}
+static int btreeHeapPull(u32 *aHeap, u32 *pOut){
+ u32 j, i, x;
+ if( (x = aHeap[0])==0 ) return 0;
+ *pOut = aHeap[1];
+ aHeap[1] = aHeap[x];
+ aHeap[x] = 0xffffffff;
+ aHeap[0]--;
+ i = 1;
+ while( (j = i*2)<=aHeap[0] ){
+ if( aHeap[j]>aHeap[j+1] ) j++;
+ if( aHeap[i]<aHeap[j] ) break;
+ x = aHeap[i];
+ aHeap[i] = aHeap[j];
+ aHeap[j] = x;
+ i = j;
+ }
+ return 1;
+}
+
+#ifndef SQLITE_OMIT_INTEGRITY_CHECK
+/*
+** Do various sanity checks on a single page of a tree. Return
+** the tree depth. Root pages return 0. Parents of root pages
+** return 1, and so forth.
+**
+** These checks are done:
+**
+** 1. Make sure that cells and freeblocks do not overlap
+** but combine to completely cover the page.
+** 2. Make sure integer cell keys are in order.
+** 3. Check the integrity of overflow pages.
+** 4. Recursively call checkTreePage on all children.
+** 5. Verify that the depth of all children is the same.
+*/
+static int checkTreePage(
+ IntegrityCk *pCheck, /* Context for the sanity check */
+ Pgno iPage, /* Page number of the page to check */
+ i64 *piMinKey, /* Write minimum integer primary key here */
+ i64 maxKey /* Error if integer primary key greater than this */
+){
+ MemPage *pPage = 0; /* The page being analyzed */
+ int i; /* Loop counter */
+ int rc; /* Result code from subroutine call */
+ int depth = -1, d2; /* Depth of a subtree */
+ int pgno; /* Page number */
+ int nFrag; /* Number of fragmented bytes on the page */
+ int hdr; /* Offset to the page header */
+ int cellStart; /* Offset to the start of the cell pointer array */
+ int nCell; /* Number of cells */
+ int doCoverageCheck = 1; /* True if cell coverage checking should be done */
+ int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
+ ** False if IPK must be strictly less than maxKey */
+ u8 *data; /* Page content */
+ u8 *pCell; /* Cell content */
+ u8 *pCellIdx; /* Next element of the cell pointer array */
+ BtShared *pBt; /* The BtShared object that owns pPage */
+ u32 pc; /* Address of a cell */
+ u32 usableSize; /* Usable size of the page */
+ u32 contentOffset; /* Offset to the start of the cell content area */
+ u32 *heap = 0; /* Min-heap used for checking cell coverage */
+ u32 x, prev = 0; /* Next and previous entry on the min-heap */
+ const char *saved_zPfx = pCheck->zPfx;
+ int saved_v1 = pCheck->v1;
+ int saved_v2 = pCheck->v2;
+ u8 savedIsInit = 0;
+
+ /* Check that the page exists
+ */
+ pBt = pCheck->pBt;
+ usableSize = pBt->usableSize;
+ if( iPage==0 ) return 0;
+ if( checkRef(pCheck, iPage) ) return 0;
+ pCheck->zPfx = "Page %u: ";
+ pCheck->v1 = iPage;
+ if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
+ checkAppendMsg(pCheck,
+ "unable to get the page. error code=%d", rc);
+ goto end_of_check;
+ }
+
+ /* Clear MemPage.isInit to make sure the corruption detection code in
+ ** btreeInitPage() is executed. */
+ savedIsInit = pPage->isInit;
+ pPage->isInit = 0;
+ if( (rc = btreeInitPage(pPage))!=0 ){
+ assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
+ checkAppendMsg(pCheck,
+ "btreeInitPage() returns error code %d", rc);
+ goto end_of_check;
+ }
+ if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
+ assert( rc==SQLITE_CORRUPT );
+ checkAppendMsg(pCheck, "free space corruption", rc);
+ goto end_of_check;
+ }
+ data = pPage->aData;
+ hdr = pPage->hdrOffset;
+
+ /* Set up for cell analysis */
+ pCheck->zPfx = "On tree page %u cell %d: ";
+ contentOffset = get2byteNotZero(&data[hdr+5]);
+ assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
+
+ /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
+ ** number of cells on the page. */
+ nCell = get2byte(&data[hdr+3]);
+ assert( pPage->nCell==nCell );
+
+ /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
+ ** immediately follows the b-tree page header. */
+ cellStart = hdr + 12 - 4*pPage->leaf;
+ assert( pPage->aCellIdx==&data[cellStart] );
+ pCellIdx = &data[cellStart + 2*(nCell-1)];
+
+ if( !pPage->leaf ){
+ /* Analyze the right-child page of internal pages */
+ pgno = get4byte(&data[hdr+8]);
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ if( pBt->autoVacuum ){
+ pCheck->zPfx = "On page %u at right child: ";
+ checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
+ }
+#endif
+ depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
+ keyCanBeEqual = 0;
+ }else{
+ /* For leaf pages, the coverage check will occur in the same loop
+ ** as the other cell checks, so initialize the heap. */
+ heap = pCheck->heap;
+ heap[0] = 0;
+ }
+
+ /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
+ ** integer offsets to the cell contents. */
+ for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
+ CellInfo info;
+
+ /* Check cell size */
+ pCheck->v2 = i;
+ assert( pCellIdx==&data[cellStart + i*2] );
+ pc = get2byteAligned(pCellIdx);
+ pCellIdx -= 2;
+ if( pc<contentOffset || pc>usableSize-4 ){
+ checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
+ pc, contentOffset, usableSize-4);
+ doCoverageCheck = 0;
+ continue;
+ }
+ pCell = &data[pc];
+ pPage->xParseCell(pPage, pCell, &info);
+ if( pc+info.nSize>usableSize ){
+ checkAppendMsg(pCheck, "Extends off end of page");
+ doCoverageCheck = 0;
+ continue;
+ }
+
+ /* Check for integer primary key out of range */
+ if( pPage->intKey ){
+ if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
+ checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
+ }
+ maxKey = info.nKey;
+ keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
+ }
+
+ /* Check the content overflow list */
+ if( info.nPayload>info.nLocal ){
+ u32 nPage; /* Number of pages on the overflow chain */
+ Pgno pgnoOvfl; /* First page of the overflow chain */
+ assert( pc + info.nSize - 4 <= usableSize );
+ nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
+ pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ if( pBt->autoVacuum ){
+ checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
+ }
+#endif
+ checkList(pCheck, 0, pgnoOvfl, nPage);
+ }
+
+ if( !pPage->leaf ){
+ /* Check sanity of left child page for internal pages */
+ pgno = get4byte(pCell);
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ if( pBt->autoVacuum ){
+ checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
+ }
+#endif
+ d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
+ keyCanBeEqual = 0;
+ if( d2!=depth ){
+ checkAppendMsg(pCheck, "Child page depth differs");
+ depth = d2;
+ }
+ }else{
+ /* Populate the coverage-checking heap for leaf pages */
+ btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
+ }
+ }
+ *piMinKey = maxKey;
+
+ /* Check for complete coverage of the page
+ */
+ pCheck->zPfx = 0;
+ if( doCoverageCheck && pCheck->mxErr>0 ){
+ /* For leaf pages, the min-heap has already been initialized and the
+ ** cells have already been inserted. But for internal pages, that has
+ ** not yet been done, so do it now */
+ if( !pPage->leaf ){
+ heap = pCheck->heap;
+ heap[0] = 0;
+ for(i=nCell-1; i>=0; i--){
+ u32 size;
+ pc = get2byteAligned(&data[cellStart+i*2]);
+ size = pPage->xCellSize(pPage, &data[pc]);
+ btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
+ }
+ }
+ /* Add the freeblocks to the min-heap
+ **
+ ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
+ ** is the offset of the first freeblock, or zero if there are no
+ ** freeblocks on the page.
+ */
+ i = get2byte(&data[hdr+1]);
+ while( i>0 ){
+ int size, j;
+ assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
+ size = get2byte(&data[i+2]);
+ assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
+ btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
+ /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
+ ** big-endian integer which is the offset in the b-tree page of the next
+ ** freeblock in the chain, or zero if the freeblock is the last on the
+ ** chain. */
+ j = get2byte(&data[i]);
+ /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
+ ** increasing offset. */
+ assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */
+ assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
+ i = j;
+ }
+ /* Analyze the min-heap looking for overlap between cells and/or
+ ** freeblocks, and counting the number of untracked bytes in nFrag.
+ **
+ ** Each min-heap entry is of the form: (start_address<<16)|end_address.
+ ** There is an implied first entry the covers the page header, the cell
+ ** pointer index, and the gap between the cell pointer index and the start
+ ** of cell content.
+ **
+ ** The loop below pulls entries from the min-heap in order and compares
+ ** the start_address against the previous end_address. If there is an
+ ** overlap, that means bytes are used multiple times. If there is a gap,
+ ** that gap is added to the fragmentation count.
+ */
+ nFrag = 0;
+ prev = contentOffset - 1; /* Implied first min-heap entry */
+ while( btreeHeapPull(heap,&x) ){
+ if( (prev&0xffff)>=(x>>16) ){
+ checkAppendMsg(pCheck,
+ "Multiple uses for byte %u of page %u", x>>16, iPage);
+ break;
+ }else{
+ nFrag += (x>>16) - (prev&0xffff) - 1;
+ prev = x;
+ }
+ }
+ nFrag += usableSize - (prev&0xffff) - 1;
+ /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
+ ** is stored in the fifth field of the b-tree page header.
+ ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
+ ** number of fragmented free bytes within the cell content area.
+ */
+ if( heap[0]==0 && nFrag!=data[hdr+7] ){
+ checkAppendMsg(pCheck,
+ "Fragmentation of %d bytes reported as %d on page %u",
+ nFrag, data[hdr+7], iPage);
+ }
+ }
+
+end_of_check:
+ if( !doCoverageCheck ) pPage->isInit = savedIsInit;
+ releasePage(pPage);
+ pCheck->zPfx = saved_zPfx;
+ pCheck->v1 = saved_v1;
+ pCheck->v2 = saved_v2;
+ return depth+1;
+}
+#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
+
+#ifndef SQLITE_OMIT_INTEGRITY_CHECK
+/*
+** This routine does a complete check of the given BTree file. aRoot[] is
+** an array of pages numbers were each page number is the root page of
+** a table. nRoot is the number of entries in aRoot.
+**
+** A read-only or read-write transaction must be opened before calling
+** this function.
+**
+** Write the number of error seen in *pnErr. Except for some memory
+** allocation errors, an error message held in memory obtained from
+** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
+** returned. If a memory allocation error occurs, NULL is returned.
+**
+** If the first entry in aRoot[] is 0, that indicates that the list of
+** root pages is incomplete. This is a "partial integrity-check". This
+** happens when performing an integrity check on a single table. The
+** zero is skipped, of course. But in addition, the freelist checks
+** and the checks to make sure every page is referenced are also skipped,
+** since obviously it is not possible to know which pages are covered by
+** the unverified btrees. Except, if aRoot[1] is 1, then the freelist
+** checks are still performed.
+*/
+SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
+ sqlite3 *db, /* Database connection that is running the check */
+ Btree *p, /* The btree to be checked */
+ Pgno *aRoot, /* An array of root pages numbers for individual trees */
+ int nRoot, /* Number of entries in aRoot[] */
+ int mxErr, /* Stop reporting errors after this many */
+ int *pnErr /* Write number of errors seen to this variable */
+){
+ Pgno i;
+ IntegrityCk sCheck;
+ BtShared *pBt = p->pBt;
+ u64 savedDbFlags = pBt->db->flags;
+ char zErr[100];
+ int bPartial = 0; /* True if not checking all btrees */
+ int bCkFreelist = 1; /* True to scan the freelist */
+ VVA_ONLY( int nRef );
+ assert( nRoot>0 );
+
+ /* aRoot[0]==0 means this is a partial check */
+ if( aRoot[0]==0 ){
+ assert( nRoot>1 );
+ bPartial = 1;
+ if( aRoot[1]!=1 ) bCkFreelist = 0;
+ }
+
+ sqlite3BtreeEnter(p);
+ assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
+ VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
+ assert( nRef>=0 );
+ sCheck.db = db;
+ sCheck.pBt = pBt;
+ sCheck.pPager = pBt->pPager;
+ sCheck.nPage = btreePagecount(sCheck.pBt);
+ sCheck.mxErr = mxErr;
+ sCheck.nErr = 0;
+ sCheck.bOomFault = 0;
+ sCheck.zPfx = 0;
+ sCheck.v1 = 0;
+ sCheck.v2 = 0;
+ sCheck.aPgRef = 0;
+ sCheck.heap = 0;
+ sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
+ sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
+ if( sCheck.nPage==0 ){
+ goto integrity_ck_cleanup;
+ }
+
+ sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
+ if( !sCheck.aPgRef ){
+ sCheck.bOomFault = 1;
+ goto integrity_ck_cleanup;
+ }
+ sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
+ if( sCheck.heap==0 ){
+ sCheck.bOomFault = 1;
+ goto integrity_ck_cleanup;
+ }
+
+ i = PENDING_BYTE_PAGE(pBt);
+ if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
+
+ /* Check the integrity of the freelist
+ */
+ if( bCkFreelist ){
+ sCheck.zPfx = "Main freelist: ";
+ checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
+ get4byte(&pBt->pPage1->aData[36]));
+ sCheck.zPfx = 0;
+ }
+
+ /* Check all the tables.
+ */
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ if( !bPartial ){
+ if( pBt->autoVacuum ){
+ Pgno mx = 0;
+ Pgno mxInHdr;
+ for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
+ mxInHdr = get4byte(&pBt->pPage1->aData[52]);
+ if( mx!=mxInHdr ){
+ checkAppendMsg(&sCheck,
+ "max rootpage (%d) disagrees with header (%d)",
+ mx, mxInHdr
+ );
+ }
+ }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
+ checkAppendMsg(&sCheck,
+ "incremental_vacuum enabled with a max rootpage of zero"
+ );
+ }
+ }
+#endif
+ testcase( pBt->db->flags & SQLITE_CellSizeCk );
+ pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
+ for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
+ i64 notUsed;
+ if( aRoot[i]==0 ) continue;
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
+ checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
+ }
+#endif
+ checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
+ }
+ pBt->db->flags = savedDbFlags;
+
+ /* Make sure every page in the file is referenced
+ */
+ if( !bPartial ){
+ for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
+#ifdef SQLITE_OMIT_AUTOVACUUM
+ if( getPageReferenced(&sCheck, i)==0 ){
+ checkAppendMsg(&sCheck, "Page %d is never used", i);
+ }
+#else
+ /* If the database supports auto-vacuum, make sure no tables contain
+ ** references to pointer-map pages.
+ */
+ if( getPageReferenced(&sCheck, i)==0 &&
+ (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
+ checkAppendMsg(&sCheck, "Page %d is never used", i);
+ }
+ if( getPageReferenced(&sCheck, i)!=0 &&
+ (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
+ checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
+ }
+#endif
+ }
+ }
+
+ /* Clean up and report errors.
+ */
+integrity_ck_cleanup:
+ sqlite3PageFree(sCheck.heap);
+ sqlite3_free(sCheck.aPgRef);
+ if( sCheck.bOomFault ){
+ sqlite3_str_reset(&sCheck.errMsg);
+ sCheck.nErr++;
+ }
+ *pnErr = sCheck.nErr;
+ if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
+ /* Make sure this analysis did not leave any unref() pages. */
+ assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
+ sqlite3BtreeLeave(p);
+ return sqlite3StrAccumFinish(&sCheck.errMsg);
+}
+#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
+
+/*
+** Return the full pathname of the underlying database file. Return
+** an empty string if the database is in-memory or a TEMP database.
+**
+** The pager filename is invariant as long as the pager is
+** open so it is safe to access without the BtShared mutex.
+*/
+SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
+ assert( p->pBt->pPager!=0 );
+ return sqlite3PagerFilename(p->pBt->pPager, 1);
+}
+
+/*
+** Return the pathname of the journal file for this database. The return
+** value of this routine is the same regardless of whether the journal file
+** has been created or not.
+**
+** The pager journal filename is invariant as long as the pager is
+** open so it is safe to access without the BtShared mutex.
+*/
+SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
+ assert( p->pBt->pPager!=0 );
+ return sqlite3PagerJournalname(p->pBt->pPager);
+}
+
+/*
+** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
+** to describe the current transaction state of Btree p.
+*/
+SQLITE_PRIVATE int sqlite3BtreeTxnState(Btree *p){
+ assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
+ return p ? p->inTrans : 0;
+}
+
+#ifndef SQLITE_OMIT_WAL
+/*
+** Run a checkpoint on the Btree passed as the first argument.
+**
+** Return SQLITE_LOCKED if this or any other connection has an open
+** transaction on the shared-cache the argument Btree is connected to.
+**
+** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
+*/
+SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
+ int rc = SQLITE_OK;
+ if( p ){
+ BtShared *pBt = p->pBt;
+ sqlite3BtreeEnter(p);
+ if( pBt->inTransaction!=TRANS_NONE ){
+ rc = SQLITE_LOCKED;
+ }else{
+ rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
+ }
+ sqlite3BtreeLeave(p);
+ }
+ return rc;
+}
+#endif
+
+/*
+** Return true if there is currently a backup running on Btree p.
+*/
+SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
+ assert( p );
+ assert( sqlite3_mutex_held(p->db->mutex) );
+ return p->nBackup!=0;
+}
+
+/*
+** This function returns a pointer to a blob of memory associated with
+** a single shared-btree. The memory is used by client code for its own
+** purposes (for example, to store a high-level schema associated with
+** the shared-btree). The btree layer manages reference counting issues.
+**
+** The first time this is called on a shared-btree, nBytes bytes of memory
+** are allocated, zeroed, and returned to the caller. For each subsequent
+** call the nBytes parameter is ignored and a pointer to the same blob
+** of memory returned.
+**
+** If the nBytes parameter is 0 and the blob of memory has not yet been
+** allocated, a null pointer is returned. If the blob has already been
+** allocated, it is returned as normal.
+**
+** Just before the shared-btree is closed, the function passed as the
+** xFree argument when the memory allocation was made is invoked on the
+** blob of allocated memory. The xFree function should not call sqlite3_free()
+** on the memory, the btree layer does that.
+*/
+SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
+ BtShared *pBt = p->pBt;
+ sqlite3BtreeEnter(p);
+ if( !pBt->pSchema && nBytes ){
+ pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
+ pBt->xFreeSchema = xFree;
+ }
+ sqlite3BtreeLeave(p);
+ return pBt->pSchema;
+}
+
+/*
+** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
+** btree as the argument handle holds an exclusive lock on the
+** sqlite_schema table. Otherwise SQLITE_OK.
+*/
+SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
+ int rc;
+ assert( sqlite3_mutex_held(p->db->mutex) );
+ sqlite3BtreeEnter(p);
+ rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
+ assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
+ sqlite3BtreeLeave(p);
+ return rc;
+}
+
+
+#ifndef SQLITE_OMIT_SHARED_CACHE
+/*
+** Obtain a lock on the table whose root page is iTab. The
+** lock is a write lock if isWritelock is true or a read lock
+** if it is false.
+*/
+SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
+ int rc = SQLITE_OK;
+ assert( p->inTrans!=TRANS_NONE );
+ if( p->sharable ){
+ u8 lockType = READ_LOCK + isWriteLock;
+ assert( READ_LOCK+1==WRITE_LOCK );
+ assert( isWriteLock==0 || isWriteLock==1 );
+
+ sqlite3BtreeEnter(p);
+ rc = querySharedCacheTableLock(p, iTab, lockType);
+ if( rc==SQLITE_OK ){
+ rc = setSharedCacheTableLock(p, iTab, lockType);
+ }
+ sqlite3BtreeLeave(p);
+ }
+ return rc;
+}
+#endif
+
+#ifndef SQLITE_OMIT_INCRBLOB
+/*
+** Argument pCsr must be a cursor opened for writing on an
+** INTKEY table currently pointing at a valid table entry.
+** This function modifies the data stored as part of that entry.
+**
+** Only the data content may only be modified, it is not possible to
+** change the length of the data stored. If this function is called with
+** parameters that attempt to write past the end of the existing data,
+** no modifications are made and SQLITE_CORRUPT is returned.
+*/
+SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
+ int rc;
+ assert( cursorOwnsBtShared(pCsr) );
+ assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
+ assert( pCsr->curFlags & BTCF_Incrblob );
+
+ rc = restoreCursorPosition(pCsr);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ assert( pCsr->eState!=CURSOR_REQUIRESEEK );
+ if( pCsr->eState!=CURSOR_VALID ){
+ return SQLITE_ABORT;
+ }
+
+ /* Save the positions of all other cursors open on this table. This is
+ ** required in case any of them are holding references to an xFetch
+ ** version of the b-tree page modified by the accessPayload call below.
+ **
+ ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
+ ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
+ ** saveAllCursors can only return SQLITE_OK.
+ */
+ VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
+ assert( rc==SQLITE_OK );
+
+ /* Check some assumptions:
+ ** (a) the cursor is open for writing,
+ ** (b) there is a read/write transaction open,
+ ** (c) the connection holds a write-lock on the table (if required),
+ ** (d) there are no conflicting read-locks, and
+ ** (e) the cursor points at a valid row of an intKey table.
+ */
+ if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
+ return SQLITE_READONLY;
+ }
+ assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
+ && pCsr->pBt->inTransaction==TRANS_WRITE );
+ assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
+ assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
+ assert( pCsr->pPage->intKey );
+
+ return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
+}
+
+/*
+** Mark this cursor as an incremental blob cursor.
+*/
+SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
+ pCur->curFlags |= BTCF_Incrblob;
+ pCur->pBtree->hasIncrblobCur = 1;
+}
+#endif
+
+/*
+** Set both the "read version" (single byte at byte offset 18) and
+** "write version" (single byte at byte offset 19) fields in the database
+** header to iVersion.
+*/
+SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
+ BtShared *pBt = pBtree->pBt;
+ int rc; /* Return code */
+
+ assert( iVersion==1 || iVersion==2 );
+
+ /* If setting the version fields to 1, do not automatically open the
+ ** WAL connection, even if the version fields are currently set to 2.
+ */
+ pBt->btsFlags &= ~BTS_NO_WAL;
+ if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
+
+ rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
+ if( rc==SQLITE_OK ){
+ u8 *aData = pBt->pPage1->aData;
+ if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
+ rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
+ if( rc==SQLITE_OK ){
+ aData[18] = (u8)iVersion;
+ aData[19] = (u8)iVersion;
+ }
+ }
+ }
+ }
+
+ pBt->btsFlags &= ~BTS_NO_WAL;
+ return rc;
+}
+
+/*
+** Return true if the cursor has a hint specified. This routine is
+** only used from within assert() statements
+*/
+SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
+ return (pCsr->hints & mask)!=0;
+}
+
+/*
+** Return true if the given Btree is read-only.
+*/
+SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
+ return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
+}
+
+/*
+** Return the size of the header added to each page by this module.
+*/
+SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
+
+#if !defined(SQLITE_OMIT_SHARED_CACHE)
+/*
+** Return true if the Btree passed as the only argument is sharable.
+*/
+SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
+ return p->sharable;
+}
+
+/*
+** Return the number of connections to the BtShared object accessed by
+** the Btree handle passed as the only argument. For private caches
+** this is always 1. For shared caches it may be 1 or greater.
+*/
+SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
+ testcase( p->sharable );
+ return p->pBt->nRef;
+}
+#endif
+
+/************** End of btree.c ***********************************************/
+/************** Begin file backup.c ******************************************/
+/*
+** 2009 January 28
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains the implementation of the sqlite3_backup_XXX()
+** API functions and the related features.
+*/
+/* #include "sqliteInt.h" */
+/* #include "btreeInt.h" */
+
+/*
+** Structure allocated for each backup operation.
+*/
+struct sqlite3_backup {
+ sqlite3* pDestDb; /* Destination database handle */
+ Btree *pDest; /* Destination b-tree file */
+ u32 iDestSchema; /* Original schema cookie in destination */
+ int bDestLocked; /* True once a write-transaction is open on pDest */
+
+ Pgno iNext; /* Page number of the next source page to copy */
+ sqlite3* pSrcDb; /* Source database handle */
+ Btree *pSrc; /* Source b-tree file */
+
+ int rc; /* Backup process error code */
+
+ /* These two variables are set by every call to backup_step(). They are
+ ** read by calls to backup_remaining() and backup_pagecount().
+ */
+ Pgno nRemaining; /* Number of pages left to copy */
+ Pgno nPagecount; /* Total number of pages to copy */
+
+ int isAttached; /* True once backup has been registered with pager */
+ sqlite3_backup *pNext; /* Next backup associated with source pager */
+};
+
+/*
+** THREAD SAFETY NOTES:
+**
+** Once it has been created using backup_init(), a single sqlite3_backup
+** structure may be accessed via two groups of thread-safe entry points:
+**
+** * Via the sqlite3_backup_XXX() API function backup_step() and
+** backup_finish(). Both these functions obtain the source database
+** handle mutex and the mutex associated with the source BtShared
+** structure, in that order.
+**
+** * Via the BackupUpdate() and BackupRestart() functions, which are
+** invoked by the pager layer to report various state changes in
+** the page cache associated with the source database. The mutex
+** associated with the source database BtShared structure will always
+** be held when either of these functions are invoked.
+**
+** The other sqlite3_backup_XXX() API functions, backup_remaining() and
+** backup_pagecount() are not thread-safe functions. If they are called
+** while some other thread is calling backup_step() or backup_finish(),
+** the values returned may be invalid. There is no way for a call to
+** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
+** or backup_pagecount().
+**
+** Depending on the SQLite configuration, the database handles and/or
+** the Btree objects may have their own mutexes that require locking.
+** Non-sharable Btrees (in-memory databases for example), do not have
+** associated mutexes.
+*/
+
+/*
+** Return a pointer corresponding to database zDb (i.e. "main", "temp")
+** in connection handle pDb. If such a database cannot be found, return
+** a NULL pointer and write an error message to pErrorDb.
+**
+** If the "temp" database is requested, it may need to be opened by this
+** function. If an error occurs while doing so, return 0 and write an
+** error message to pErrorDb.
+*/
+static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
+ int i = sqlite3FindDbName(pDb, zDb);
+
+ if( i==1 ){
+ Parse sParse;
+ int rc = 0;
+ memset(&sParse, 0, sizeof(sParse));
+ sParse.db = pDb;
+ if( sqlite3OpenTempDatabase(&sParse) ){
+ sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
+ rc = SQLITE_ERROR;
+ }
+ sqlite3DbFree(pErrorDb, sParse.zErrMsg);
+ sqlite3ParserReset(&sParse);
+ if( rc ){
+ return 0;
+ }
+ }
+
+ if( i<0 ){
+ sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
+ return 0;
+ }
+
+ return pDb->aDb[i].pBt;
+}
+
+/*
+** Attempt to set the page size of the destination to match the page size
+** of the source.
+*/
+static int setDestPgsz(sqlite3_backup *p){
+ int rc;
+ rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),0,0);
+ return rc;
+}
+
+/*
+** Check that there is no open read-transaction on the b-tree passed as the
+** second argument. If there is not, return SQLITE_OK. Otherwise, if there
+** is an open read-transaction, return SQLITE_ERROR and leave an error
+** message in database handle db.
+*/
+static int checkReadTransaction(sqlite3 *db, Btree *p){
+ if( sqlite3BtreeTxnState(p)!=SQLITE_TXN_NONE ){
+ sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
+ return SQLITE_ERROR;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Create an sqlite3_backup process to copy the contents of zSrcDb from
+** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
+** a pointer to the new sqlite3_backup object.
+**
+** If an error occurs, NULL is returned and an error code and error message
+** stored in database handle pDestDb.
+*/
+SQLITE_API sqlite3_backup *sqlite3_backup_init(
+ sqlite3* pDestDb, /* Database to write to */
+ const char *zDestDb, /* Name of database within pDestDb */
+ sqlite3* pSrcDb, /* Database connection to read from */
+ const char *zSrcDb /* Name of database within pSrcDb */
+){
+ sqlite3_backup *p; /* Value to return */
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+
+ /* Lock the source database handle. The destination database
+ ** handle is not locked in this routine, but it is locked in
+ ** sqlite3_backup_step(). The user is required to ensure that no
+ ** other thread accesses the destination handle for the duration
+ ** of the backup operation. Any attempt to use the destination
+ ** database connection while a backup is in progress may cause
+ ** a malfunction or a deadlock.
+ */
+ sqlite3_mutex_enter(pSrcDb->mutex);
+ sqlite3_mutex_enter(pDestDb->mutex);
+
+ if( pSrcDb==pDestDb ){
+ sqlite3ErrorWithMsg(
+ pDestDb, SQLITE_ERROR, "source and destination must be distinct"
+ );
+ p = 0;
+ }else {
+ /* Allocate space for a new sqlite3_backup object...
+ ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
+ ** call to sqlite3_backup_init() and is destroyed by a call to
+ ** sqlite3_backup_finish(). */
+ p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
+ if( !p ){
+ sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
+ }
+ }
+
+ /* If the allocation succeeded, populate the new object. */
+ if( p ){
+ p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
+ p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
+ p->pDestDb = pDestDb;
+ p->pSrcDb = pSrcDb;
+ p->iNext = 1;
+ p->isAttached = 0;
+
+ if( 0==p->pSrc || 0==p->pDest
+ || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
+ ){
+ /* One (or both) of the named databases did not exist or an OOM
+ ** error was hit. Or there is a transaction open on the destination
+ ** database. The error has already been written into the pDestDb
+ ** handle. All that is left to do here is free the sqlite3_backup
+ ** structure. */
+ sqlite3_free(p);
+ p = 0;
+ }
+ }
+ if( p ){
+ p->pSrc->nBackup++;
+ }
+
+ sqlite3_mutex_leave(pDestDb->mutex);
+ sqlite3_mutex_leave(pSrcDb->mutex);
+ return p;
+}
+
+/*
+** Argument rc is an SQLite error code. Return true if this error is
+** considered fatal if encountered during a backup operation. All errors
+** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
+*/
+static int isFatalError(int rc){
+ return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
+}
+
+/*
+** Parameter zSrcData points to a buffer containing the data for
+** page iSrcPg from the source database. Copy this data into the
+** destination database.
+*/
+static int backupOnePage(
+ sqlite3_backup *p, /* Backup handle */
+ Pgno iSrcPg, /* Source database page to backup */
+ const u8 *zSrcData, /* Source database page data */
+ int bUpdate /* True for an update, false otherwise */
+){
+ Pager * const pDestPager = sqlite3BtreePager(p->pDest);
+ const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
+ int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
+ const int nCopy = MIN(nSrcPgsz, nDestPgsz);
+ const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
+ int rc = SQLITE_OK;
+ i64 iOff;
+
+ assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
+ assert( p->bDestLocked );
+ assert( !isFatalError(p->rc) );
+ assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
+ assert( zSrcData );
+
+ /* Catch the case where the destination is an in-memory database and the
+ ** page sizes of the source and destination differ.
+ */
+ if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
+ rc = SQLITE_READONLY;
+ }
+
+ /* This loop runs once for each destination page spanned by the source
+ ** page. For each iteration, variable iOff is set to the byte offset
+ ** of the destination page.
+ */
+ for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
+ DbPage *pDestPg = 0;
+ Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
+ if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
+ if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
+ && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
+ ){
+ const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
+ u8 *zDestData = sqlite3PagerGetData(pDestPg);
+ u8 *zOut = &zDestData[iOff%nDestPgsz];
+
+ /* Copy the data from the source page into the destination page.
+ ** Then clear the Btree layer MemPage.isInit flag. Both this module
+ ** and the pager code use this trick (clearing the first byte
+ ** of the page 'extra' space to invalidate the Btree layers
+ ** cached parse of the page). MemPage.isInit is marked
+ ** "MUST BE FIRST" for this purpose.
+ */
+ memcpy(zOut, zIn, nCopy);
+ ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
+ if( iOff==0 && bUpdate==0 ){
+ sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
+ }
+ }
+ sqlite3PagerUnref(pDestPg);
+ }
+
+ return rc;
+}
+
+/*
+** If pFile is currently larger than iSize bytes, then truncate it to
+** exactly iSize bytes. If pFile is not larger than iSize bytes, then
+** this function is a no-op.
+**
+** Return SQLITE_OK if everything is successful, or an SQLite error
+** code if an error occurs.
+*/
+static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
+ i64 iCurrent;
+ int rc = sqlite3OsFileSize(pFile, &iCurrent);
+ if( rc==SQLITE_OK && iCurrent>iSize ){
+ rc = sqlite3OsTruncate(pFile, iSize);
+ }
+ return rc;
+}
+
+/*
+** Register this backup object with the associated source pager for
+** callbacks when pages are changed or the cache invalidated.
+*/
+static void attachBackupObject(sqlite3_backup *p){
+ sqlite3_backup **pp;
+ assert( sqlite3BtreeHoldsMutex(p->pSrc) );
+ pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
+ p->pNext = *pp;
+ *pp = p;
+ p->isAttached = 1;
+}
+
+/*
+** Copy nPage pages from the source b-tree to the destination.
+*/
+SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
+ int rc;
+ int destMode; /* Destination journal mode */
+ int pgszSrc = 0; /* Source page size */
+ int pgszDest = 0; /* Destination page size */
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( p==0 ) return SQLITE_MISUSE_BKPT;
+#endif
+ sqlite3_mutex_enter(p->pSrcDb->mutex);
+ sqlite3BtreeEnter(p->pSrc);
+ if( p->pDestDb ){
+ sqlite3_mutex_enter(p->pDestDb->mutex);
+ }
+
+ rc = p->rc;
+ if( !isFatalError(rc) ){
+ Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
+ Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
+ int ii; /* Iterator variable */
+ int nSrcPage = -1; /* Size of source db in pages */
+ int bCloseTrans = 0; /* True if src db requires unlocking */
+
+ /* If the source pager is currently in a write-transaction, return
+ ** SQLITE_BUSY immediately.
+ */
+ if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
+ rc = SQLITE_BUSY;
+ }else{
+ rc = SQLITE_OK;
+ }
+
+ /* If there is no open read-transaction on the source database, open
+ ** one now. If a transaction is opened here, then it will be closed
+ ** before this function exits.
+ */
+ if( rc==SQLITE_OK && SQLITE_TXN_NONE==sqlite3BtreeTxnState(p->pSrc) ){
+ rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
+ bCloseTrans = 1;
+ }
+
+ /* If the destination database has not yet been locked (i.e. if this
+ ** is the first call to backup_step() for the current backup operation),
+ ** try to set its page size to the same as the source database. This
+ ** is especially important on ZipVFS systems, as in that case it is
+ ** not possible to create a database file that uses one page size by
+ ** writing to it with another. */
+ if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
+ rc = SQLITE_NOMEM;
+ }
+
+ /* Lock the destination database, if it is not locked already. */
+ if( SQLITE_OK==rc && p->bDestLocked==0
+ && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2,
+ (int*)&p->iDestSchema))
+ ){
+ p->bDestLocked = 1;
+ }
+
+ /* Do not allow backup if the destination database is in WAL mode
+ ** and the page sizes are different between source and destination */
+ pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
+ pgszDest = sqlite3BtreeGetPageSize(p->pDest);
+ destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
+ if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
+ rc = SQLITE_READONLY;
+ }
+
+ /* Now that there is a read-lock on the source database, query the
+ ** source pager for the number of pages in the database.
+ */
+ nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
+ assert( nSrcPage>=0 );
+ for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
+ const Pgno iSrcPg = p->iNext; /* Source page number */
+ if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
+ DbPage *pSrcPg; /* Source page object */
+ rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
+ if( rc==SQLITE_OK ){
+ rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
+ sqlite3PagerUnref(pSrcPg);
+ }
+ }
+ p->iNext++;
+ }
+ if( rc==SQLITE_OK ){
+ p->nPagecount = nSrcPage;
+ p->nRemaining = nSrcPage+1-p->iNext;
+ if( p->iNext>(Pgno)nSrcPage ){
+ rc = SQLITE_DONE;
+ }else if( !p->isAttached ){
+ attachBackupObject(p);
+ }
+ }
+
+ /* Update the schema version field in the destination database. This
+ ** is to make sure that the schema-version really does change in
+ ** the case where the source and destination databases have the
+ ** same schema version.
+ */
+ if( rc==SQLITE_DONE ){
+ if( nSrcPage==0 ){
+ rc = sqlite3BtreeNewDb(p->pDest);
+ nSrcPage = 1;
+ }
+ if( rc==SQLITE_OK || rc==SQLITE_DONE ){
+ rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
+ }
+ if( rc==SQLITE_OK ){
+ if( p->pDestDb ){
+ sqlite3ResetAllSchemasOfConnection(p->pDestDb);
+ }
+ if( destMode==PAGER_JOURNALMODE_WAL ){
+ rc = sqlite3BtreeSetVersion(p->pDest, 2);
+ }
+ }
+ if( rc==SQLITE_OK ){
+ int nDestTruncate;
+ /* Set nDestTruncate to the final number of pages in the destination
+ ** database. The complication here is that the destination page
+ ** size may be different to the source page size.
+ **
+ ** If the source page size is smaller than the destination page size,
+ ** round up. In this case the call to sqlite3OsTruncate() below will
+ ** fix the size of the file. However it is important to call
+ ** sqlite3PagerTruncateImage() here so that any pages in the
+ ** destination file that lie beyond the nDestTruncate page mark are
+ ** journalled by PagerCommitPhaseOne() before they are destroyed
+ ** by the file truncation.
+ */
+ assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
+ assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
+ if( pgszSrc<pgszDest ){
+ int ratio = pgszDest/pgszSrc;
+ nDestTruncate = (nSrcPage+ratio-1)/ratio;
+ if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
+ nDestTruncate--;
+ }
+ }else{
+ nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
+ }
+ assert( nDestTruncate>0 );
+
+ if( pgszSrc<pgszDest ){
+ /* If the source page-size is smaller than the destination page-size,
+ ** two extra things may need to happen:
+ **
+ ** * The destination may need to be truncated, and
+ **
+ ** * Data stored on the pages immediately following the
+ ** pending-byte page in the source database may need to be
+ ** copied into the destination database.
+ */
+ const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
+ sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
+ Pgno iPg;
+ int nDstPage;
+ i64 iOff;
+ i64 iEnd;
+
+ assert( pFile );
+ assert( nDestTruncate==0
+ || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
+ nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
+ && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
+ ));
+
+ /* This block ensures that all data required to recreate the original
+ ** database has been stored in the journal for pDestPager and the
+ ** journal synced to disk. So at this point we may safely modify
+ ** the database file in any way, knowing that if a power failure
+ ** occurs, the original database will be reconstructed from the
+ ** journal file. */
+ sqlite3PagerPagecount(pDestPager, &nDstPage);
+ for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
+ if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
+ DbPage *pPg;
+ rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3PagerWrite(pPg);
+ sqlite3PagerUnref(pPg);
+ }
+ }
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
+ }
+
+ /* Write the extra pages and truncate the database file as required */
+ iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
+ for(
+ iOff=PENDING_BYTE+pgszSrc;
+ rc==SQLITE_OK && iOff<iEnd;
+ iOff+=pgszSrc
+ ){
+ PgHdr *pSrcPg = 0;
+ const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
+ rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
+ if( rc==SQLITE_OK ){
+ u8 *zData = sqlite3PagerGetData(pSrcPg);
+ rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
+ }
+ sqlite3PagerUnref(pSrcPg);
+ }
+ if( rc==SQLITE_OK ){
+ rc = backupTruncateFile(pFile, iSize);
+ }
+
+ /* Sync the database file to disk. */
+ if( rc==SQLITE_OK ){
+ rc = sqlite3PagerSync(pDestPager, 0);
+ }
+ }else{
+ sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
+ rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
+ }
+
+ /* Finish committing the transaction to the destination database. */
+ if( SQLITE_OK==rc
+ && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
+ ){
+ rc = SQLITE_DONE;
+ }
+ }
+ }
+
+ /* If bCloseTrans is true, then this function opened a read transaction
+ ** on the source database. Close the read transaction here. There is
+ ** no need to check the return values of the btree methods here, as
+ ** "committing" a read-only transaction cannot fail.
+ */
+ if( bCloseTrans ){
+ TESTONLY( int rc2 );
+ TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
+ TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
+ assert( rc2==SQLITE_OK );
+ }
+
+ if( rc==SQLITE_IOERR_NOMEM ){
+ rc = SQLITE_NOMEM_BKPT;
+ }
+ p->rc = rc;
+ }
+ if( p->pDestDb ){
+ sqlite3_mutex_leave(p->pDestDb->mutex);
+ }
+ sqlite3BtreeLeave(p->pSrc);
+ sqlite3_mutex_leave(p->pSrcDb->mutex);
+ return rc;
+}
+
+/*
+** Release all resources associated with an sqlite3_backup* handle.
+*/
+SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
+ sqlite3_backup **pp; /* Ptr to head of pagers backup list */
+ sqlite3 *pSrcDb; /* Source database connection */
+ int rc; /* Value to return */
+
+ /* Enter the mutexes */
+ if( p==0 ) return SQLITE_OK;
+ pSrcDb = p->pSrcDb;
+ sqlite3_mutex_enter(pSrcDb->mutex);
+ sqlite3BtreeEnter(p->pSrc);
+ if( p->pDestDb ){
+ sqlite3_mutex_enter(p->pDestDb->mutex);
+ }
+
+ /* Detach this backup from the source pager. */
+ if( p->pDestDb ){
+ p->pSrc->nBackup--;
+ }
+ if( p->isAttached ){
+ pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
+ assert( pp!=0 );
+ while( *pp!=p ){
+ pp = &(*pp)->pNext;
+ assert( pp!=0 );
+ }
+ *pp = p->pNext;
+ }
+
+ /* If a transaction is still open on the Btree, roll it back. */
+ sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
+
+ /* Set the error code of the destination database handle. */
+ rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
+ if( p->pDestDb ){
+ sqlite3Error(p->pDestDb, rc);
+
+ /* Exit the mutexes and free the backup context structure. */
+ sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
+ }
+ sqlite3BtreeLeave(p->pSrc);
+ if( p->pDestDb ){
+ /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
+ ** call to sqlite3_backup_init() and is destroyed by a call to
+ ** sqlite3_backup_finish(). */
+ sqlite3_free(p);
+ }
+ sqlite3LeaveMutexAndCloseZombie(pSrcDb);
+ return rc;
+}
+
+/*
+** Return the number of pages still to be backed up as of the most recent
+** call to sqlite3_backup_step().
+*/
+SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( p==0 ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ return p->nRemaining;
+}
+
+/*
+** Return the total number of pages in the source database as of the most
+** recent call to sqlite3_backup_step().
+*/
+SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( p==0 ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ return p->nPagecount;
+}
+
+/*
+** This function is called after the contents of page iPage of the
+** source database have been modified. If page iPage has already been
+** copied into the destination database, then the data written to the
+** destination is now invalidated. The destination copy of iPage needs
+** to be updated with the new data before the backup operation is
+** complete.
+**
+** It is assumed that the mutex associated with the BtShared object
+** corresponding to the source database is held when this function is
+** called.
+*/
+static SQLITE_NOINLINE void backupUpdate(
+ sqlite3_backup *p,
+ Pgno iPage,
+ const u8 *aData
+){
+ assert( p!=0 );
+ do{
+ assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
+ if( !isFatalError(p->rc) && iPage<p->iNext ){
+ /* The backup process p has already copied page iPage. But now it
+ ** has been modified by a transaction on the source pager. Copy
+ ** the new data into the backup.
+ */
+ int rc;
+ assert( p->pDestDb );
+ sqlite3_mutex_enter(p->pDestDb->mutex);
+ rc = backupOnePage(p, iPage, aData, 1);
+ sqlite3_mutex_leave(p->pDestDb->mutex);
+ assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
+ if( rc!=SQLITE_OK ){
+ p->rc = rc;
+ }
+ }
+ }while( (p = p->pNext)!=0 );
+}
+SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
+ if( pBackup ) backupUpdate(pBackup, iPage, aData);
+}
+
+/*
+** Restart the backup process. This is called when the pager layer
+** detects that the database has been modified by an external database
+** connection. In this case there is no way of knowing which of the
+** pages that have been copied into the destination database are still
+** valid and which are not, so the entire process needs to be restarted.
+**
+** It is assumed that the mutex associated with the BtShared object
+** corresponding to the source database is held when this function is
+** called.
+*/
+SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
+ sqlite3_backup *p; /* Iterator variable */
+ for(p=pBackup; p; p=p->pNext){
+ assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
+ p->iNext = 1;
+ }
+}
+
+#ifndef SQLITE_OMIT_VACUUM
+/*
+** Copy the complete content of pBtFrom into pBtTo. A transaction
+** must be active for both files.
+**
+** The size of file pTo may be reduced by this operation. If anything
+** goes wrong, the transaction on pTo is rolled back. If successful, the
+** transaction is committed before returning.
+*/
+SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
+ int rc;
+ sqlite3_file *pFd; /* File descriptor for database pTo */
+ sqlite3_backup b;
+ sqlite3BtreeEnter(pTo);
+ sqlite3BtreeEnter(pFrom);
+
+ assert( sqlite3BtreeTxnState(pTo)==SQLITE_TXN_WRITE );
+ pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
+ if( pFd->pMethods ){
+ i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
+ rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
+ if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
+ if( rc ) goto copy_finished;
+ }
+
+ /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
+ ** to 0. This is used by the implementations of sqlite3_backup_step()
+ ** and sqlite3_backup_finish() to detect that they are being called
+ ** from this function, not directly by the user.
+ */
+ memset(&b, 0, sizeof(b));
+ b.pSrcDb = pFrom->db;
+ b.pSrc = pFrom;
+ b.pDest = pTo;
+ b.iNext = 1;
+
+ /* 0x7FFFFFFF is the hard limit for the number of pages in a database
+ ** file. By passing this as the number of pages to copy to
+ ** sqlite3_backup_step(), we can guarantee that the copy finishes
+ ** within a single call (unless an error occurs). The assert() statement
+ ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
+ ** or an error code. */
+ sqlite3_backup_step(&b, 0x7FFFFFFF);
+ assert( b.rc!=SQLITE_OK );
+
+ rc = sqlite3_backup_finish(&b);
+ if( rc==SQLITE_OK ){
+ pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
+ }else{
+ sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
+ }
+
+ assert( sqlite3BtreeTxnState(pTo)!=SQLITE_TXN_WRITE );
+copy_finished:
+ sqlite3BtreeLeave(pFrom);
+ sqlite3BtreeLeave(pTo);
+ return rc;
+}
+#endif /* SQLITE_OMIT_VACUUM */
+
+/************** End of backup.c **********************************************/
+/************** Begin file vdbemem.c *****************************************/
+/*
+** 2004 May 26
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains code use to manipulate "Mem" structure. A "Mem"
+** stores a single value in the VDBE. Mem is an opaque structure visible
+** only within the VDBE. Interface routines refer to a Mem using the
+** name sqlite_value
+*/
+/* #include "sqliteInt.h" */
+/* #include "vdbeInt.h" */
+
+/* True if X is a power of two. 0 is considered a power of two here.
+** In other words, return true if X has at most one bit set.
+*/
+#define ISPOWEROF2(X) (((X)&((X)-1))==0)
+
+#ifdef SQLITE_DEBUG
+/*
+** Check invariants on a Mem object.
+**
+** This routine is intended for use inside of assert() statements, like
+** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
+*/
+SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
+ /* If MEM_Dyn is set then Mem.xDel!=0.
+ ** Mem.xDel might not be initialized if MEM_Dyn is clear.
+ */
+ assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
+
+ /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
+ ** ensure that if Mem.szMalloc>0 then it is safe to do
+ ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
+ ** That saves a few cycles in inner loops. */
+ assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
+
+ /* Cannot have more than one of MEM_Int, MEM_Real, or MEM_IntReal */
+ assert( ISPOWEROF2(p->flags & (MEM_Int|MEM_Real|MEM_IntReal)) );
+
+ if( p->flags & MEM_Null ){
+ /* Cannot be both MEM_Null and some other type */
+ assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 );
+
+ /* If MEM_Null is set, then either the value is a pure NULL (the usual
+ ** case) or it is a pointer set using sqlite3_bind_pointer() or
+ ** sqlite3_result_pointer(). If a pointer, then MEM_Term must also be
+ ** set.
+ */
+ if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
+ /* This is a pointer type. There may be a flag to indicate what to
+ ** do with the pointer. */
+ assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
+ ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
+ ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
+
+ /* No other bits set */
+ assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype|MEM_FromBind
+ |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
+ }else{
+ /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
+ ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
+ }
+ }else{
+ /* The MEM_Cleared bit is only allowed on NULLs */
+ assert( (p->flags & MEM_Cleared)==0 );
+ }
+
+ /* The szMalloc field holds the correct memory allocation size */
+ assert( p->szMalloc==0
+ || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
+
+ /* If p holds a string or blob, the Mem.z must point to exactly
+ ** one of the following:
+ **
+ ** (1) Memory in Mem.zMalloc and managed by the Mem object
+ ** (2) Memory to be freed using Mem.xDel
+ ** (3) An ephemeral string or blob
+ ** (4) A static string or blob
+ */
+ if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
+ assert(
+ ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
+ ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
+ ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
+ ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
+ );
+ }
+ return 1;
+}
+#endif
+
+/*
+** Render a Mem object which is one of MEM_Int, MEM_Real, or MEM_IntReal
+** into a buffer.
+*/
+static void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){
+ StrAccum acc;
+ assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) );
+ assert( sz>22 );
+ if( p->flags & MEM_Int ){
+#if GCC_VERSION>=7000000
+ /* Work-around for GCC bug
+ ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96270 */
+ i64 x;
+ assert( (p->flags&MEM_Int)*2==sizeof(x) );
+ memcpy(&x, (char*)&p->u, (p->flags&MEM_Int)*2);
+ sqlite3Int64ToText(x, zBuf);
+#else
+ sqlite3Int64ToText(p->u.i, zBuf);
+#endif
+ }else{
+ sqlite3StrAccumInit(&acc, 0, zBuf, sz, 0);
+ sqlite3_str_appendf(&acc, "%!.15g",
+ (p->flags & MEM_IntReal)!=0 ? (double)p->u.i : p->u.r);
+ assert( acc.zText==zBuf && acc.mxAlloc<=0 );
+ zBuf[acc.nChar] = 0; /* Fast version of sqlite3StrAccumFinish(&acc) */
+ }
+}
+
+#ifdef SQLITE_DEBUG
+/*
+** Validity checks on pMem. pMem holds a string.
+**
+** (1) Check that string value of pMem agrees with its integer or real value.
+** (2) Check that the string is correctly zero terminated
+**
+** A single int or real value always converts to the same strings. But
+** many different strings can be converted into the same int or real.
+** If a table contains a numeric value and an index is based on the
+** corresponding string value, then it is important that the string be
+** derived from the numeric value, not the other way around, to ensure
+** that the index and table are consistent. See ticket
+** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for
+** an example.
+**
+** This routine looks at pMem to verify that if it has both a numeric
+** representation and a string representation then the string rep has
+** been derived from the numeric and not the other way around. It returns
+** true if everything is ok and false if there is a problem.
+**
+** This routine is for use inside of assert() statements only.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemValidStrRep(Mem *p){
+ char zBuf[100];
+ char *z;
+ int i, j, incr;
+ if( (p->flags & MEM_Str)==0 ) return 1;
+ if( p->flags & MEM_Term ){
+ /* Insure that the string is properly zero-terminated. Pay particular
+ ** attention to the case where p->n is odd */
+ if( p->szMalloc>0 && p->z==p->zMalloc ){
+ assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 );
+ assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 );
+ }
+ assert( p->z[p->n]==0 );
+ assert( p->enc==SQLITE_UTF8 || p->z[(p->n+1)&~1]==0 );
+ assert( p->enc==SQLITE_UTF8 || p->z[((p->n+1)&~1)+1]==0 );
+ }
+ if( (p->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ) return 1;
+ vdbeMemRenderNum(sizeof(zBuf), zBuf, p);
+ z = p->z;
+ i = j = 0;
+ incr = 1;
+ if( p->enc!=SQLITE_UTF8 ){
+ incr = 2;
+ if( p->enc==SQLITE_UTF16BE ) z++;
+ }
+ while( zBuf[j] ){
+ if( zBuf[j++]!=z[i] ) return 0;
+ i += incr;
+ }
+ return 1;
+}
+#endif /* SQLITE_DEBUG */
+
+/*
+** If pMem is an object with a valid string representation, this routine
+** ensures the internal encoding for the string representation is
+** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
+**
+** If pMem is not a string object, or the encoding of the string
+** representation is already stored using the requested encoding, then this
+** routine is a no-op.
+**
+** SQLITE_OK is returned if the conversion is successful (or not required).
+** SQLITE_NOMEM may be returned if a malloc() fails during conversion
+** between formats.
+*/
+SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
+#ifndef SQLITE_OMIT_UTF16
+ int rc;
+#endif
+ assert( !sqlite3VdbeMemIsRowSet(pMem) );
+ assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
+ || desiredEnc==SQLITE_UTF16BE );
+ if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
+ return SQLITE_OK;
+ }
+ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
+#ifdef SQLITE_OMIT_UTF16
+ return SQLITE_ERROR;
+#else
+
+ /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
+ ** then the encoding of the value may not have changed.
+ */
+ rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
+ assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
+ assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
+ assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
+ return rc;
+#endif
+}
+
+/*
+** Make sure pMem->z points to a writable allocation of at least n bytes.
+**
+** If the bPreserve argument is true, then copy of the content of
+** pMem->z into the new allocation. pMem must be either a string or
+** blob if bPreserve is true. If bPreserve is false, any prior content
+** in pMem->z is discarded.
+*/
+SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
+ assert( sqlite3VdbeCheckMemInvariants(pMem) );
+ assert( !sqlite3VdbeMemIsRowSet(pMem) );
+ testcase( pMem->db==0 );
+
+ /* If the bPreserve flag is set to true, then the memory cell must already
+ ** contain a valid string or blob value. */
+ assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
+ testcase( bPreserve && pMem->z==0 );
+
+ assert( pMem->szMalloc==0
+ || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
+ if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
+ if( pMem->db ){
+ pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
+ }else{
+ pMem->zMalloc = sqlite3Realloc(pMem->z, n);
+ if( pMem->zMalloc==0 ) sqlite3_free(pMem->z);
+ pMem->z = pMem->zMalloc;
+ }
+ bPreserve = 0;
+ }else{
+ if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
+ pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
+ }
+ if( pMem->zMalloc==0 ){
+ sqlite3VdbeMemSetNull(pMem);
+ pMem->z = 0;
+ pMem->szMalloc = 0;
+ return SQLITE_NOMEM_BKPT;
+ }else{
+ pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
+ }
+
+ if( bPreserve && pMem->z ){
+ assert( pMem->z!=pMem->zMalloc );
+ memcpy(pMem->zMalloc, pMem->z, pMem->n);
+ }
+ if( (pMem->flags&MEM_Dyn)!=0 ){
+ assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
+ pMem->xDel((void *)(pMem->z));
+ }
+
+ pMem->z = pMem->zMalloc;
+ pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
+ return SQLITE_OK;
+}
+
+/*
+** Change the pMem->zMalloc allocation to be at least szNew bytes.
+** If pMem->zMalloc already meets or exceeds the requested size, this
+** routine is a no-op.
+**
+** Any prior string or blob content in the pMem object may be discarded.
+** The pMem->xDel destructor is called, if it exists. Though MEM_Str
+** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, MEM_IntReal,
+** and MEM_Null values are preserved.
+**
+** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
+** if unable to complete the resizing.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
+ assert( CORRUPT_DB || szNew>0 );
+ assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
+ if( pMem->szMalloc<szNew ){
+ return sqlite3VdbeMemGrow(pMem, szNew, 0);
+ }
+ assert( (pMem->flags & MEM_Dyn)==0 );
+ pMem->z = pMem->zMalloc;
+ pMem->flags &= (MEM_Null|MEM_Int|MEM_Real|MEM_IntReal);
+ return SQLITE_OK;
+}
+
+/*
+** It is already known that pMem contains an unterminated string.
+** Add the zero terminator.
+**
+** Three bytes of zero are added. In this way, there is guaranteed
+** to be a double-zero byte at an even byte boundary in order to
+** terminate a UTF16 string, even if the initial size of the buffer
+** is an odd number of bytes.
+*/
+static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
+ if( sqlite3VdbeMemGrow(pMem, pMem->n+3, 1) ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ pMem->z[pMem->n] = 0;
+ pMem->z[pMem->n+1] = 0;
+ pMem->z[pMem->n+2] = 0;
+ pMem->flags |= MEM_Term;
+ return SQLITE_OK;
+}
+
+/*
+** Change pMem so that its MEM_Str or MEM_Blob value is stored in
+** MEM.zMalloc, where it can be safely written.
+**
+** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
+ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
+ assert( !sqlite3VdbeMemIsRowSet(pMem) );
+ if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
+ if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
+ if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
+ int rc = vdbeMemAddTerminator(pMem);
+ if( rc ) return rc;
+ }
+ }
+ pMem->flags &= ~MEM_Ephem;
+#ifdef SQLITE_DEBUG
+ pMem->pScopyFrom = 0;
+#endif
+
+ return SQLITE_OK;
+}
+
+/*
+** If the given Mem* has a zero-filled tail, turn it into an ordinary
+** blob stored in dynamically allocated space.
+*/
+#ifndef SQLITE_OMIT_INCRBLOB
+SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
+ int nByte;
+ assert( pMem->flags & MEM_Zero );
+ assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) );
+ testcase( sqlite3_value_nochange(pMem) );
+ assert( !sqlite3VdbeMemIsRowSet(pMem) );
+ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
+
+ /* Set nByte to the number of bytes required to store the expanded blob. */
+ nByte = pMem->n + pMem->u.nZero;
+ if( nByte<=0 ){
+ if( (pMem->flags & MEM_Blob)==0 ) return SQLITE_OK;
+ nByte = 1;
+ }
+ if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
+ return SQLITE_NOMEM_BKPT;
+ }
+
+ memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
+ pMem->n += pMem->u.nZero;
+ pMem->flags &= ~(MEM_Zero|MEM_Term);
+ return SQLITE_OK;
+}
+#endif
+
+/*
+** Make sure the given Mem is \u0000 terminated.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
+ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
+ testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
+ testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
+ if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
+ return SQLITE_OK; /* Nothing to do */
+ }else{
+ return vdbeMemAddTerminator(pMem);
+ }
+}
+
+/*
+** Add MEM_Str to the set of representations for the given Mem. This
+** routine is only called if pMem is a number of some kind, not a NULL
+** or a BLOB.
+**
+** Existing representations MEM_Int, MEM_Real, or MEM_IntReal are invalidated
+** if bForce is true but are retained if bForce is false.
+**
+** A MEM_Null value will never be passed to this function. This function is
+** used for converting values to text for returning to the user (i.e. via
+** sqlite3_value_text()), or for ensuring that values to be used as btree
+** keys are strings. In the former case a NULL pointer is returned the
+** user and the latter is an internal programming error.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
+ const int nByte = 32;
+
+ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
+ assert( !(pMem->flags&MEM_Zero) );
+ assert( !(pMem->flags&(MEM_Str|MEM_Blob)) );
+ assert( pMem->flags&(MEM_Int|MEM_Real|MEM_IntReal) );
+ assert( !sqlite3VdbeMemIsRowSet(pMem) );
+ assert( EIGHT_BYTE_ALIGNMENT(pMem) );
+
+
+ if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
+ pMem->enc = 0;
+ return SQLITE_NOMEM_BKPT;
+ }
+
+ vdbeMemRenderNum(nByte, pMem->z, pMem);
+ assert( pMem->z!=0 );
+ pMem->n = sqlite3Strlen30NN(pMem->z);
+ pMem->enc = SQLITE_UTF8;
+ pMem->flags |= MEM_Str|MEM_Term;
+ if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
+ sqlite3VdbeChangeEncoding(pMem, enc);
+ return SQLITE_OK;
+}
+
+/*
+** Memory cell pMem contains the context of an aggregate function.
+** This routine calls the finalize method for that function. The
+** result of the aggregate is stored back into pMem.
+**
+** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
+** otherwise.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
+ sqlite3_context ctx;
+ Mem t;
+ assert( pFunc!=0 );
+ assert( pFunc->xFinalize!=0 );
+ assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
+ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
+ memset(&ctx, 0, sizeof(ctx));
+ memset(&t, 0, sizeof(t));
+ t.flags = MEM_Null;
+ t.db = pMem->db;
+ ctx.pOut = &t;
+ ctx.pMem = pMem;
+ ctx.pFunc = pFunc;
+ pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
+ assert( (pMem->flags & MEM_Dyn)==0 );
+ if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
+ memcpy(pMem, &t, sizeof(t));
+ return ctx.isError;
+}
+
+/*
+** Memory cell pAccum contains the context of an aggregate function.
+** This routine calls the xValue method for that function and stores
+** the results in memory cell pMem.
+**
+** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK
+** otherwise.
+*/
+#ifndef SQLITE_OMIT_WINDOWFUNC
+SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){
+ sqlite3_context ctx;
+ assert( pFunc!=0 );
+ assert( pFunc->xValue!=0 );
+ assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );
+ assert( pAccum->db==0 || sqlite3_mutex_held(pAccum->db->mutex) );
+ memset(&ctx, 0, sizeof(ctx));
+ sqlite3VdbeMemSetNull(pOut);
+ ctx.pOut = pOut;
+ ctx.pMem = pAccum;
+ ctx.pFunc = pFunc;
+ pFunc->xValue(&ctx);
+ return ctx.isError;
+}
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+
+/*
+** If the memory cell contains a value that must be freed by
+** invoking the external callback in Mem.xDel, then this routine
+** will free that value. It also sets Mem.flags to MEM_Null.
+**
+** This is a helper routine for sqlite3VdbeMemSetNull() and
+** for sqlite3VdbeMemRelease(). Use those other routines as the
+** entry point for releasing Mem resources.
+*/
+static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
+ assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
+ assert( VdbeMemDynamic(p) );
+ if( p->flags&MEM_Agg ){
+ sqlite3VdbeMemFinalize(p, p->u.pDef);
+ assert( (p->flags & MEM_Agg)==0 );
+ testcase( p->flags & MEM_Dyn );
+ }
+ if( p->flags&MEM_Dyn ){
+ assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
+ p->xDel((void *)p->z);
+ }
+ p->flags = MEM_Null;
+}
+
+/*
+** Release memory held by the Mem p, both external memory cleared
+** by p->xDel and memory in p->zMalloc.
+**
+** This is a helper routine invoked by sqlite3VdbeMemRelease() in
+** the unusual case where there really is memory in p that needs
+** to be freed.
+*/
+static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
+ if( VdbeMemDynamic(p) ){
+ vdbeMemClearExternAndSetNull(p);
+ }
+ if( p->szMalloc ){
+ sqlite3DbFreeNN(p->db, p->zMalloc);
+ p->szMalloc = 0;
+ }
+ p->z = 0;
+}
+
+/*
+** Release any memory resources held by the Mem. Both the memory that is
+** free by Mem.xDel and the Mem.zMalloc allocation are freed.
+**
+** Use this routine prior to clean up prior to abandoning a Mem, or to
+** reset a Mem back to its minimum memory utilization.
+**
+** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
+** prior to inserting new content into the Mem.
+*/
+SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
+ assert( sqlite3VdbeCheckMemInvariants(p) );
+ if( VdbeMemDynamic(p) || p->szMalloc ){
+ vdbeMemClear(p);
+ }
+}
+
+/*
+** Convert a 64-bit IEEE double into a 64-bit signed integer.
+** If the double is out of range of a 64-bit signed integer then
+** return the closest available 64-bit signed integer.
+*/
+static SQLITE_NOINLINE i64 doubleToInt64(double r){
+#ifdef SQLITE_OMIT_FLOATING_POINT
+ /* When floating-point is omitted, double and int64 are the same thing */
+ return r;
+#else
+ /*
+ ** Many compilers we encounter do not define constants for the
+ ** minimum and maximum 64-bit integers, or they define them
+ ** inconsistently. And many do not understand the "LL" notation.
+ ** So we define our own static constants here using nothing
+ ** larger than a 32-bit integer constant.
+ */
+ static const i64 maxInt = LARGEST_INT64;
+ static const i64 minInt = SMALLEST_INT64;
+
+ if( r<=(double)minInt ){
+ return minInt;
+ }else if( r>=(double)maxInt ){
+ return maxInt;
+ }else{
+ return (i64)r;
+ }
+#endif
+}
+
+/*
+** Return some kind of integer value which is the best we can do
+** at representing the value that *pMem describes as an integer.
+** If pMem is an integer, then the value is exact. If pMem is
+** a floating-point then the value returned is the integer part.
+** If pMem is a string or blob, then we make an attempt to convert
+** it into an integer and return that. If pMem represents an
+** an SQL-NULL value, return 0.
+**
+** If pMem represents a string value, its encoding might be changed.
+*/
+static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
+ i64 value = 0;
+ sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
+ return value;
+}
+SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
+ int flags;
+ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
+ assert( EIGHT_BYTE_ALIGNMENT(pMem) );
+ flags = pMem->flags;
+ if( flags & (MEM_Int|MEM_IntReal) ){
+ testcase( flags & MEM_IntReal );
+ return pMem->u.i;
+ }else if( flags & MEM_Real ){
+ return doubleToInt64(pMem->u.r);
+ }else if( (flags & (MEM_Str|MEM_Blob))!=0 && pMem->z!=0 ){
+ return memIntValue(pMem);
+ }else{
+ return 0;
+ }
+}
+
+/*
+** Return the best representation of pMem that we can get into a
+** double. If pMem is already a double or an integer, return its
+** value. If it is a string or blob, try to convert it to a double.
+** If it is a NULL, return 0.0.
+*/
+static SQLITE_NOINLINE double memRealValue(Mem *pMem){
+ /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
+ double val = (double)0;
+ sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
+ return val;
+}
+SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
+ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
+ assert( EIGHT_BYTE_ALIGNMENT(pMem) );
+ if( pMem->flags & MEM_Real ){
+ return pMem->u.r;
+ }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
+ testcase( pMem->flags & MEM_IntReal );
+ return (double)pMem->u.i;
+ }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
+ return memRealValue(pMem);
+ }else{
+ /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
+ return (double)0;
+ }
+}
+
+/*
+** Return 1 if pMem represents true, and return 0 if pMem represents false.
+** Return the value ifNull if pMem is NULL.
+*/
+SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
+ testcase( pMem->flags & MEM_IntReal );
+ if( pMem->flags & (MEM_Int|MEM_IntReal) ) return pMem->u.i!=0;
+ if( pMem->flags & MEM_Null ) return ifNull;
+ return sqlite3VdbeRealValue(pMem)!=0.0;
+}
+
+/*
+** The MEM structure is already a MEM_Real. Try to also make it a
+** MEM_Int if we can.
+*/
+SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
+ i64 ix;
+ assert( pMem->flags & MEM_Real );
+ assert( !sqlite3VdbeMemIsRowSet(pMem) );
+ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
+ assert( EIGHT_BYTE_ALIGNMENT(pMem) );
+
+ ix = doubleToInt64(pMem->u.r);
+
+ /* Only mark the value as an integer if
+ **
+ ** (1) the round-trip conversion real->int->real is a no-op, and
+ ** (2) The integer is neither the largest nor the smallest
+ ** possible integer (ticket #3922)
+ **
+ ** The second and third terms in the following conditional enforces
+ ** the second condition under the assumption that addition overflow causes
+ ** values to wrap around.
+ */
+ if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
+ pMem->u.i = ix;
+ MemSetTypeFlag(pMem, MEM_Int);
+ }
+}
+
+/*
+** Convert pMem to type integer. Invalidate any prior representations.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
+ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
+ assert( !sqlite3VdbeMemIsRowSet(pMem) );
+ assert( EIGHT_BYTE_ALIGNMENT(pMem) );
+
+ pMem->u.i = sqlite3VdbeIntValue(pMem);
+ MemSetTypeFlag(pMem, MEM_Int);
+ return SQLITE_OK;
+}
+
+/*
+** Convert pMem so that it is of type MEM_Real.
+** Invalidate any prior representations.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
+ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
+ assert( EIGHT_BYTE_ALIGNMENT(pMem) );
+
+ pMem->u.r = sqlite3VdbeRealValue(pMem);
+ MemSetTypeFlag(pMem, MEM_Real);
+ return SQLITE_OK;
+}
+
+/* Compare a floating point value to an integer. Return true if the two
+** values are the same within the precision of the floating point value.
+**
+** This function assumes that i was obtained by assignment from r1.
+**
+** For some versions of GCC on 32-bit machines, if you do the more obvious
+** comparison of "r1==(double)i" you sometimes get an answer of false even
+** though the r1 and (double)i values are bit-for-bit the same.
+*/
+SQLITE_PRIVATE int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
+ double r2 = (double)i;
+ return r1==0.0
+ || (memcmp(&r1, &r2, sizeof(r1))==0
+ && i >= -2251799813685248LL && i < 2251799813685248LL);
+}
+
+/*
+** Convert pMem so that it has type MEM_Real or MEM_Int.
+** Invalidate any prior representations.
+**
+** Every effort is made to force the conversion, even if the input
+** is a string that does not look completely like a number. Convert
+** as much of the string as we can and ignore the rest.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
+ testcase( pMem->flags & MEM_Int );
+ testcase( pMem->flags & MEM_Real );
+ testcase( pMem->flags & MEM_IntReal );
+ testcase( pMem->flags & MEM_Null );
+ if( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))==0 ){
+ int rc;
+ sqlite3_int64 ix;
+ assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
+ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
+ rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
+ if( ((rc==0 || rc==1) && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1)
+ || sqlite3RealSameAsInt(pMem->u.r, (ix = (i64)pMem->u.r))
+ ){
+ pMem->u.i = ix;
+ MemSetTypeFlag(pMem, MEM_Int);
+ }else{
+ MemSetTypeFlag(pMem, MEM_Real);
+ }
+ }
+ assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))!=0 );
+ pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
+ return SQLITE_OK;
+}
+
+/*
+** Cast the datatype of the value in pMem according to the affinity
+** "aff". Casting is different from applying affinity in that a cast
+** is forced. In other words, the value is converted into the desired
+** affinity even if that results in loss of data. This routine is
+** used (for example) to implement the SQL "cast()" operator.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
+ if( pMem->flags & MEM_Null ) return SQLITE_OK;
+ switch( aff ){
+ case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
+ if( (pMem->flags & MEM_Blob)==0 ){
+ sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
+ assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
+ if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
+ }else{
+ pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
+ }
+ break;
+ }
+ case SQLITE_AFF_NUMERIC: {
+ sqlite3VdbeMemNumerify(pMem);
+ break;
+ }
+ case SQLITE_AFF_INTEGER: {
+ sqlite3VdbeMemIntegerify(pMem);
+ break;
+ }
+ case SQLITE_AFF_REAL: {
+ sqlite3VdbeMemRealify(pMem);
+ break;
+ }
+ default: {
+ assert( aff==SQLITE_AFF_TEXT );
+ assert( MEM_Str==(MEM_Blob>>3) );
+ pMem->flags |= (pMem->flags&MEM_Blob)>>3;
+ sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
+ assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
+ pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal|MEM_Blob|MEM_Zero);
+ return sqlite3VdbeChangeEncoding(pMem, encoding);
+ }
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Initialize bulk memory to be a consistent Mem object.
+**
+** The minimum amount of initialization feasible is performed.
+*/
+SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
+ assert( (flags & ~MEM_TypeMask)==0 );
+ pMem->flags = flags;
+ pMem->db = db;
+ pMem->szMalloc = 0;
+}
+
+
+/*
+** Delete any previous value and set the value stored in *pMem to NULL.
+**
+** This routine calls the Mem.xDel destructor to dispose of values that
+** require the destructor. But it preserves the Mem.zMalloc memory allocation.
+** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
+** routine to invoke the destructor and deallocates Mem.zMalloc.
+**
+** Use this routine to reset the Mem prior to insert a new value.
+**
+** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
+*/
+SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
+ if( VdbeMemDynamic(pMem) ){
+ vdbeMemClearExternAndSetNull(pMem);
+ }else{
+ pMem->flags = MEM_Null;
+ }
+}
+SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
+ sqlite3VdbeMemSetNull((Mem*)p);
+}
+
+/*
+** Delete any previous value and set the value to be a BLOB of length
+** n containing all zeros.
+*/
+SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
+ sqlite3VdbeMemRelease(pMem);
+ pMem->flags = MEM_Blob|MEM_Zero;
+ pMem->n = 0;
+ if( n<0 ) n = 0;
+ pMem->u.nZero = n;
+ pMem->enc = SQLITE_UTF8;
+ pMem->z = 0;
+}
+
+/*
+** The pMem is known to contain content that needs to be destroyed prior
+** to a value change. So invoke the destructor, then set the value to
+** a 64-bit integer.
+*/
+static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
+ sqlite3VdbeMemSetNull(pMem);
+ pMem->u.i = val;
+ pMem->flags = MEM_Int;
+}
+
+/*
+** Delete any previous value and set the value stored in *pMem to val,
+** manifest type INTEGER.
+*/
+SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
+ if( VdbeMemDynamic(pMem) ){
+ vdbeReleaseAndSetInt64(pMem, val);
+ }else{
+ pMem->u.i = val;
+ pMem->flags = MEM_Int;
+ }
+}
+
+/* A no-op destructor */
+SQLITE_PRIVATE void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
+
+/*
+** Set the value stored in *pMem should already be a NULL.
+** Also store a pointer to go with it.
+*/
+SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
+ Mem *pMem,
+ void *pPtr,
+ const char *zPType,
+ void (*xDestructor)(void*)
+){
+ assert( pMem->flags==MEM_Null );
+ pMem->u.zPType = zPType ? zPType : "";
+ pMem->z = pPtr;
+ pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
+ pMem->eSubtype = 'p';
+ pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
+}
+
+#ifndef SQLITE_OMIT_FLOATING_POINT
+/*
+** Delete any previous value and set the value stored in *pMem to val,
+** manifest type REAL.
+*/
+SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
+ sqlite3VdbeMemSetNull(pMem);
+ if( !sqlite3IsNaN(val) ){
+ pMem->u.r = val;
+ pMem->flags = MEM_Real;
+ }
+}
+#endif
+
+#ifdef SQLITE_DEBUG
+/*
+** Return true if the Mem holds a RowSet object. This routine is intended
+** for use inside of assert() statements.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem *pMem){
+ return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn)
+ && pMem->xDel==sqlite3RowSetDelete;
+}
+#endif
+
+/*
+** Delete any previous value and set the value of pMem to be an
+** empty boolean index.
+**
+** Return SQLITE_OK on success and SQLITE_NOMEM if a memory allocation
+** error occurs.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem *pMem){
+ sqlite3 *db = pMem->db;
+ RowSet *p;
+ assert( db!=0 );
+ assert( !sqlite3VdbeMemIsRowSet(pMem) );
+ sqlite3VdbeMemRelease(pMem);
+ p = sqlite3RowSetInit(db);
+ if( p==0 ) return SQLITE_NOMEM;
+ pMem->z = (char*)p;
+ pMem->flags = MEM_Blob|MEM_Dyn;
+ pMem->xDel = sqlite3RowSetDelete;
+ return SQLITE_OK;
+}
+
+/*
+** Return true if the Mem object contains a TEXT or BLOB that is
+** too large - whose size exceeds SQLITE_MAX_LENGTH.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
+ assert( p->db!=0 );
+ if( p->flags & (MEM_Str|MEM_Blob) ){
+ int n = p->n;
+ if( p->flags & MEM_Zero ){
+ n += p->u.nZero;
+ }
+ return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
+ }
+ return 0;
+}
+
+#ifdef SQLITE_DEBUG
+/*
+** This routine prepares a memory cell for modification by breaking
+** its link to a shallow copy and by marking any current shallow
+** copies of this cell as invalid.
+**
+** This is used for testing and debugging only - to help ensure that shallow
+** copies (created by OP_SCopy) are not misused.
+*/
+SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
+ int i;
+ Mem *pX;
+ for(i=1, pX=pVdbe->aMem+1; i<pVdbe->nMem; i++, pX++){
+ if( pX->pScopyFrom==pMem ){
+ u16 mFlags;
+ if( pVdbe->db->flags & SQLITE_VdbeTrace ){
+ sqlite3DebugPrintf("Invalidate R[%d] due to change in R[%d]\n",
+ (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem));
+ }
+ /* If pX is marked as a shallow copy of pMem, then try to verify that
+ ** no significant changes have been made to pX since the OP_SCopy.
+ ** A significant change would indicated a missed call to this
+ ** function for pX. Minor changes, such as adding or removing a
+ ** dual type, are allowed, as long as the underlying value is the
+ ** same. */
+ mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
+ assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i );
+
+ /* pMem is the register that is changing. But also mark pX as
+ ** undefined so that we can quickly detect the shallow-copy error */
+ pX->flags = MEM_Undefined;
+ pX->pScopyFrom = 0;
+ }
+ }
+ pMem->pScopyFrom = 0;
+}
+#endif /* SQLITE_DEBUG */
+
+/*
+** Make an shallow copy of pFrom into pTo. Prior contents of
+** pTo are freed. The pFrom->z field is not duplicated. If
+** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
+** and flags gets srcType (either MEM_Ephem or MEM_Static).
+*/
+static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
+ vdbeMemClearExternAndSetNull(pTo);
+ assert( !VdbeMemDynamic(pTo) );
+ sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
+}
+SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
+ assert( !sqlite3VdbeMemIsRowSet(pFrom) );
+ assert( pTo->db==pFrom->db );
+ if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
+ memcpy(pTo, pFrom, MEMCELLSIZE);
+ if( (pFrom->flags&MEM_Static)==0 ){
+ pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
+ assert( srcType==MEM_Ephem || srcType==MEM_Static );
+ pTo->flags |= srcType;
+ }
+}
+
+/*
+** Make a full copy of pFrom into pTo. Prior contents of pTo are
+** freed before the copy is made.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
+ int rc = SQLITE_OK;
+
+ assert( !sqlite3VdbeMemIsRowSet(pFrom) );
+ if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
+ memcpy(pTo, pFrom, MEMCELLSIZE);
+ pTo->flags &= ~MEM_Dyn;
+ if( pTo->flags&(MEM_Str|MEM_Blob) ){
+ if( 0==(pFrom->flags&MEM_Static) ){
+ pTo->flags |= MEM_Ephem;
+ rc = sqlite3VdbeMemMakeWriteable(pTo);
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Transfer the contents of pFrom to pTo. Any existing value in pTo is
+** freed. If pFrom contains ephemeral data, a copy is made.
+**
+** pFrom contains an SQL NULL when this routine returns.
+*/
+SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
+ assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
+ assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
+ assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
+
+ sqlite3VdbeMemRelease(pTo);
+ memcpy(pTo, pFrom, sizeof(Mem));
+ pFrom->flags = MEM_Null;
+ pFrom->szMalloc = 0;
+}
+
+/*
+** Change the value of a Mem to be a string or a BLOB.
+**
+** The memory management strategy depends on the value of the xDel
+** parameter. If the value passed is SQLITE_TRANSIENT, then the
+** string is copied into a (possibly existing) buffer managed by the
+** Mem structure. Otherwise, any existing buffer is freed and the
+** pointer copied.
+**
+** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
+** size limit) then no memory allocation occurs. If the string can be
+** stored without allocating memory, then it is. If a memory allocation
+** is required to store the string, then value of pMem is unchanged. In
+** either case, SQLITE_TOOBIG is returned.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
+ Mem *pMem, /* Memory cell to set to string value */
+ const char *z, /* String pointer */
+ int n, /* Bytes in string, or negative */
+ u8 enc, /* Encoding of z. 0 for BLOBs */
+ void (*xDel)(void*) /* Destructor function */
+){
+ int nByte = n; /* New value for pMem->n */
+ int iLimit; /* Maximum allowed string or blob size */
+ u16 flags = 0; /* New value for pMem->flags */
+
+ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
+ assert( !sqlite3VdbeMemIsRowSet(pMem) );
+
+ /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
+ if( !z ){
+ sqlite3VdbeMemSetNull(pMem);
+ return SQLITE_OK;
+ }
+
+ if( pMem->db ){
+ iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
+ }else{
+ iLimit = SQLITE_MAX_LENGTH;
+ }
+ flags = (enc==0?MEM_Blob:MEM_Str);
+ if( nByte<0 ){
+ assert( enc!=0 );
+ if( enc==SQLITE_UTF8 ){
+ nByte = 0x7fffffff & (int)strlen(z);
+ }else{
+ for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
+ }
+ flags |= MEM_Term;
+ }
+
+ /* The following block sets the new values of Mem.z and Mem.xDel. It
+ ** also sets a flag in local variable "flags" to indicate the memory
+ ** management (one of MEM_Dyn or MEM_Static).
+ */
+ if( xDel==SQLITE_TRANSIENT ){
+ u32 nAlloc = nByte;
+ if( flags&MEM_Term ){
+ nAlloc += (enc==SQLITE_UTF8?1:2);
+ }
+ if( nByte>iLimit ){
+ return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);
+ }
+ testcase( nAlloc==0 );
+ testcase( nAlloc==31 );
+ testcase( nAlloc==32 );
+ if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ memcpy(pMem->z, z, nAlloc);
+ }else{
+ sqlite3VdbeMemRelease(pMem);
+ pMem->z = (char *)z;
+ if( xDel==SQLITE_DYNAMIC ){
+ pMem->zMalloc = pMem->z;
+ pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
+ }else{
+ pMem->xDel = xDel;
+ flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
+ }
+ }
+
+ pMem->n = nByte;
+ pMem->flags = flags;
+ if( enc ){
+ pMem->enc = enc;
+#ifdef SQLITE_ENABLE_SESSION
+ }else if( pMem->db==0 ){
+ pMem->enc = SQLITE_UTF8;
+#endif
+ }else{
+ assert( pMem->db!=0 );
+ pMem->enc = ENC(pMem->db);
+ }
+
+#ifndef SQLITE_OMIT_UTF16
+ if( enc>SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
+ return SQLITE_NOMEM_BKPT;
+ }
+#endif
+
+ if( nByte>iLimit ){
+ return SQLITE_TOOBIG;
+ }
+
+ return SQLITE_OK;
+}
+
+/*
+** Move data out of a btree key or data field and into a Mem structure.
+** The data is payload from the entry that pCur is currently pointing
+** to. offset and amt determine what portion of the data or key to retrieve.
+** The result is written into the pMem element.
+**
+** The pMem object must have been initialized. This routine will use
+** pMem->zMalloc to hold the content from the btree, if possible. New
+** pMem->zMalloc space will be allocated if necessary. The calling routine
+** is responsible for making sure that the pMem object is eventually
+** destroyed.
+**
+** If this routine fails for any reason (malloc returns NULL or unable
+** to read from the disk) then the pMem is left in an inconsistent state.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
+ BtCursor *pCur, /* Cursor pointing at record to retrieve. */
+ u32 offset, /* Offset from the start of data to return bytes from. */
+ u32 amt, /* Number of bytes to return. */
+ Mem *pMem /* OUT: Return data in this Mem structure. */
+){
+ int rc;
+ pMem->flags = MEM_Null;
+ if( sqlite3BtreeMaxRecordSize(pCur)<offset+amt ){
+ return SQLITE_CORRUPT_BKPT;
+ }
+ if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
+ rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
+ if( rc==SQLITE_OK ){
+ pMem->z[amt] = 0; /* Overrun area used when reading malformed records */
+ pMem->flags = MEM_Blob;
+ pMem->n = (int)amt;
+ }else{
+ sqlite3VdbeMemRelease(pMem);
+ }
+ }
+ return rc;
+}
+SQLITE_PRIVATE int sqlite3VdbeMemFromBtreeZeroOffset(
+ BtCursor *pCur, /* Cursor pointing at record to retrieve. */
+ u32 amt, /* Number of bytes to return. */
+ Mem *pMem /* OUT: Return data in this Mem structure. */
+){
+ u32 available = 0; /* Number of bytes available on the local btree page */
+ int rc = SQLITE_OK; /* Return code */
+
+ assert( sqlite3BtreeCursorIsValid(pCur) );
+ assert( !VdbeMemDynamic(pMem) );
+
+ /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
+ ** that both the BtShared and database handle mutexes are held. */
+ assert( !sqlite3VdbeMemIsRowSet(pMem) );
+ pMem->z = (char *)sqlite3BtreePayloadFetch(pCur, &available);
+ assert( pMem->z!=0 );
+
+ if( amt<=available ){
+ pMem->flags = MEM_Blob|MEM_Ephem;
+ pMem->n = (int)amt;
+ }else{
+ rc = sqlite3VdbeMemFromBtree(pCur, 0, amt, pMem);
+ }
+
+ return rc;
+}
+
+/*
+** The pVal argument is known to be a value other than NULL.
+** Convert it into a string with encoding enc and return a pointer
+** to a zero-terminated version of that string.
+*/
+static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
+ assert( pVal!=0 );
+ assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
+ assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
+ assert( !sqlite3VdbeMemIsRowSet(pVal) );
+ assert( (pVal->flags & (MEM_Null))==0 );
+ if( pVal->flags & (MEM_Blob|MEM_Str) ){
+ if( ExpandBlob(pVal) ) return 0;
+ pVal->flags |= MEM_Str;
+ if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
+ sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
+ }
+ if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
+ assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
+ if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
+ return 0;
+ }
+ }
+ sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
+ }else{
+ sqlite3VdbeMemStringify(pVal, enc, 0);
+ assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
+ }
+ assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
+ || pVal->db->mallocFailed );
+ if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
+ assert( sqlite3VdbeMemValidStrRep(pVal) );
+ return pVal->z;
+ }else{
+ return 0;
+ }
+}
+
+/* This function is only available internally, it is not part of the
+** external API. It works in a similar way to sqlite3_value_text(),
+** except the data returned is in the encoding specified by the second
+** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
+** SQLITE_UTF8.
+**
+** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
+** If that is the case, then the result must be aligned on an even byte
+** boundary.
+*/
+SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
+ if( !pVal ) return 0;
+ assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
+ assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
+ assert( !sqlite3VdbeMemIsRowSet(pVal) );
+ if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
+ assert( sqlite3VdbeMemValidStrRep(pVal) );
+ return pVal->z;
+ }
+ if( pVal->flags&MEM_Null ){
+ return 0;
+ }
+ return valueToText(pVal, enc);
+}
+
+/*
+** Create a new sqlite3_value object.
+*/
+SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
+ Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
+ if( p ){
+ p->flags = MEM_Null;
+ p->db = db;
+ }
+ return p;
+}
+
+/*
+** Context object passed by sqlite3Stat4ProbeSetValue() through to
+** valueNew(). See comments above valueNew() for details.
+*/
+struct ValueNewStat4Ctx {
+ Parse *pParse;
+ Index *pIdx;
+ UnpackedRecord **ppRec;
+ int iVal;
+};
+
+/*
+** Allocate and return a pointer to a new sqlite3_value object. If
+** the second argument to this function is NULL, the object is allocated
+** by calling sqlite3ValueNew().
+**
+** Otherwise, if the second argument is non-zero, then this function is
+** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
+** already been allocated, allocate the UnpackedRecord structure that
+** that function will return to its caller here. Then return a pointer to
+** an sqlite3_value within the UnpackedRecord.a[] array.
+*/
+static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
+#ifdef SQLITE_ENABLE_STAT4
+ if( p ){
+ UnpackedRecord *pRec = p->ppRec[0];
+
+ if( pRec==0 ){
+ Index *pIdx = p->pIdx; /* Index being probed */
+ int nByte; /* Bytes of space to allocate */
+ int i; /* Counter variable */
+ int nCol = pIdx->nColumn; /* Number of index columns including rowid */
+
+ nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
+ pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
+ if( pRec ){
+ pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
+ if( pRec->pKeyInfo ){
+ assert( pRec->pKeyInfo->nAllField==nCol );
+ assert( pRec->pKeyInfo->enc==ENC(db) );
+ pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
+ for(i=0; i<nCol; i++){
+ pRec->aMem[i].flags = MEM_Null;
+ pRec->aMem[i].db = db;
+ }
+ }else{
+ sqlite3DbFreeNN(db, pRec);
+ pRec = 0;
+ }
+ }
+ if( pRec==0 ) return 0;
+ p->ppRec[0] = pRec;
+ }
+
+ pRec->nField = p->iVal+1;
+ return &pRec->aMem[p->iVal];
+ }
+#else
+ UNUSED_PARAMETER(p);
+#endif /* defined(SQLITE_ENABLE_STAT4) */
+ return sqlite3ValueNew(db);
+}
+
+/*
+** The expression object indicated by the second argument is guaranteed
+** to be a scalar SQL function. If
+**
+** * all function arguments are SQL literals,
+** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
+** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
+**
+** then this routine attempts to invoke the SQL function. Assuming no
+** error occurs, output parameter (*ppVal) is set to point to a value
+** object containing the result before returning SQLITE_OK.
+**
+** Affinity aff is applied to the result of the function before returning.
+** If the result is a text value, the sqlite3_value object uses encoding
+** enc.
+**
+** If the conditions above are not met, this function returns SQLITE_OK
+** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
+** NULL and an SQLite error code returned.
+*/
+#ifdef SQLITE_ENABLE_STAT4
+static int valueFromFunction(
+ sqlite3 *db, /* The database connection */
+ Expr *p, /* The expression to evaluate */
+ u8 enc, /* Encoding to use */
+ u8 aff, /* Affinity to use */
+ sqlite3_value **ppVal, /* Write the new value here */
+ struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
+){
+ sqlite3_context ctx; /* Context object for function invocation */
+ sqlite3_value **apVal = 0; /* Function arguments */
+ int nVal = 0; /* Size of apVal[] array */
+ FuncDef *pFunc = 0; /* Function definition */
+ sqlite3_value *pVal = 0; /* New value */
+ int rc = SQLITE_OK; /* Return code */
+ ExprList *pList = 0; /* Function arguments */
+ int i; /* Iterator variable */
+
+ assert( pCtx!=0 );
+ assert( (p->flags & EP_TokenOnly)==0 );
+ pList = p->x.pList;
+ if( pList ) nVal = pList->nExpr;
+ pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
+ assert( pFunc );
+ if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
+ || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
+ ){
+ return SQLITE_OK;
+ }
+
+ if( pList ){
+ apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
+ if( apVal==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto value_from_function_out;
+ }
+ for(i=0; i<nVal; i++){
+ rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
+ if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
+ }
+ }
+
+ pVal = valueNew(db, pCtx);
+ if( pVal==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto value_from_function_out;
+ }
+
+ assert( pCtx->pParse->rc==SQLITE_OK );
+ memset(&ctx, 0, sizeof(ctx));
+ ctx.pOut = pVal;
+ ctx.pFunc = pFunc;
+ pFunc->xSFunc(&ctx, nVal, apVal);
+ if( ctx.isError ){
+ rc = ctx.isError;
+ sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
+ }else{
+ sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
+ assert( rc==SQLITE_OK );
+ rc = sqlite3VdbeChangeEncoding(pVal, enc);
+ if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
+ rc = SQLITE_TOOBIG;
+ pCtx->pParse->nErr++;
+ }
+ }
+ pCtx->pParse->rc = rc;
+
+ value_from_function_out:
+ if( rc!=SQLITE_OK ){
+ pVal = 0;
+ }
+ if( apVal ){
+ for(i=0; i<nVal; i++){
+ sqlite3ValueFree(apVal[i]);
+ }
+ sqlite3DbFreeNN(db, apVal);
+ }
+
+ *ppVal = pVal;
+ return rc;
+}
+#else
+# define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
+#endif /* defined(SQLITE_ENABLE_STAT4) */
+
+/*
+** Extract a value from the supplied expression in the manner described
+** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
+** using valueNew().
+**
+** If pCtx is NULL and an error occurs after the sqlite3_value object
+** has been allocated, it is freed before returning. Or, if pCtx is not
+** NULL, it is assumed that the caller will free any allocated object
+** in all cases.
+*/
+static int valueFromExpr(
+ sqlite3 *db, /* The database connection */
+ Expr *pExpr, /* The expression to evaluate */
+ u8 enc, /* Encoding to use */
+ u8 affinity, /* Affinity to use */
+ sqlite3_value **ppVal, /* Write the new value here */
+ struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
+){
+ int op;
+ char *zVal = 0;
+ sqlite3_value *pVal = 0;
+ int negInt = 1;
+ const char *zNeg = "";
+ int rc = SQLITE_OK;
+
+ assert( pExpr!=0 );
+ while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
+#if defined(SQLITE_ENABLE_STAT4)
+ if( op==TK_REGISTER ) op = pExpr->op2;
+#else
+ if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
+#endif
+
+ /* Compressed expressions only appear when parsing the DEFAULT clause
+ ** on a table column definition, and hence only when pCtx==0. This
+ ** check ensures that an EP_TokenOnly expression is never passed down
+ ** into valueFromFunction(). */
+ assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
+
+ if( op==TK_CAST ){
+ u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
+ rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
+ testcase( rc!=SQLITE_OK );
+ if( *ppVal ){
+ sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
+ sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
+ }
+ return rc;
+ }
+
+ /* Handle negative integers in a single step. This is needed in the
+ ** case when the value is -9223372036854775808.
+ */
+ if( op==TK_UMINUS
+ && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
+ pExpr = pExpr->pLeft;
+ op = pExpr->op;
+ negInt = -1;
+ zNeg = "-";
+ }
+
+ if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
+ pVal = valueNew(db, pCtx);
+ if( pVal==0 ) goto no_mem;
+ if( ExprHasProperty(pExpr, EP_IntValue) ){
+ sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
+ }else{
+ zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
+ if( zVal==0 ) goto no_mem;
+ sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
+ }
+ if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
+ sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
+ }else{
+ sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
+ }
+ assert( (pVal->flags & MEM_IntReal)==0 );
+ if( pVal->flags & (MEM_Int|MEM_IntReal|MEM_Real) ){
+ testcase( pVal->flags & MEM_Int );
+ testcase( pVal->flags & MEM_Real );
+ pVal->flags &= ~MEM_Str;
+ }
+ if( enc!=SQLITE_UTF8 ){
+ rc = sqlite3VdbeChangeEncoding(pVal, enc);
+ }
+ }else if( op==TK_UMINUS ) {
+ /* This branch happens for multiple negative signs. Ex: -(-5) */
+ if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
+ && pVal!=0
+ ){
+ sqlite3VdbeMemNumerify(pVal);
+ if( pVal->flags & MEM_Real ){
+ pVal->u.r = -pVal->u.r;
+ }else if( pVal->u.i==SMALLEST_INT64 ){
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ pVal->u.r = -(double)SMALLEST_INT64;
+#else
+ pVal->u.r = LARGEST_INT64;
+#endif
+ MemSetTypeFlag(pVal, MEM_Real);
+ }else{
+ pVal->u.i = -pVal->u.i;
+ }
+ sqlite3ValueApplyAffinity(pVal, affinity, enc);
+ }
+ }else if( op==TK_NULL ){
+ pVal = valueNew(db, pCtx);
+ if( pVal==0 ) goto no_mem;
+ sqlite3VdbeMemSetNull(pVal);
+ }
+#ifndef SQLITE_OMIT_BLOB_LITERAL
+ else if( op==TK_BLOB ){
+ int nVal;
+ assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
+ assert( pExpr->u.zToken[1]=='\'' );
+ pVal = valueNew(db, pCtx);
+ if( !pVal ) goto no_mem;
+ zVal = &pExpr->u.zToken[2];
+ nVal = sqlite3Strlen30(zVal)-1;
+ assert( zVal[nVal]=='\'' );
+ sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
+ 0, SQLITE_DYNAMIC);
+ }
+#endif
+#ifdef SQLITE_ENABLE_STAT4
+ else if( op==TK_FUNCTION && pCtx!=0 ){
+ rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
+ }
+#endif
+ else if( op==TK_TRUEFALSE ){
+ pVal = valueNew(db, pCtx);
+ if( pVal ){
+ pVal->flags = MEM_Int;
+ pVal->u.i = pExpr->u.zToken[4]==0;
+ }
+ }
+
+ *ppVal = pVal;
+ return rc;
+
+no_mem:
+#ifdef SQLITE_ENABLE_STAT4
+ if( pCtx==0 || pCtx->pParse->nErr==0 )
+#endif
+ sqlite3OomFault(db);
+ sqlite3DbFree(db, zVal);
+ assert( *ppVal==0 );
+#ifdef SQLITE_ENABLE_STAT4
+ if( pCtx==0 ) sqlite3ValueFree(pVal);
+#else
+ assert( pCtx==0 ); sqlite3ValueFree(pVal);
+#endif
+ return SQLITE_NOMEM_BKPT;
+}
+
+/*
+** Create a new sqlite3_value object, containing the value of pExpr.
+**
+** This only works for very simple expressions that consist of one constant
+** token (i.e. "5", "5.1", "'a string'"). If the expression can
+** be converted directly into a value, then the value is allocated and
+** a pointer written to *ppVal. The caller is responsible for deallocating
+** the value by passing it to sqlite3ValueFree() later on. If the expression
+** cannot be converted to a value, then *ppVal is set to NULL.
+*/
+SQLITE_PRIVATE int sqlite3ValueFromExpr(
+ sqlite3 *db, /* The database connection */
+ Expr *pExpr, /* The expression to evaluate */
+ u8 enc, /* Encoding to use */
+ u8 affinity, /* Affinity to use */
+ sqlite3_value **ppVal /* Write the new value here */
+){
+ return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
+}
+
+#ifdef SQLITE_ENABLE_STAT4
+/*
+** Attempt to extract a value from pExpr and use it to construct *ppVal.
+**
+** If pAlloc is not NULL, then an UnpackedRecord object is created for
+** pAlloc if one does not exist and the new value is added to the
+** UnpackedRecord object.
+**
+** A value is extracted in the following cases:
+**
+** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
+**
+** * The expression is a bound variable, and this is a reprepare, or
+**
+** * The expression is a literal value.
+**
+** On success, *ppVal is made to point to the extracted value. The caller
+** is responsible for ensuring that the value is eventually freed.
+*/
+static int stat4ValueFromExpr(
+ Parse *pParse, /* Parse context */
+ Expr *pExpr, /* The expression to extract a value from */
+ u8 affinity, /* Affinity to use */
+ struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
+ sqlite3_value **ppVal /* OUT: New value object (or NULL) */
+){
+ int rc = SQLITE_OK;
+ sqlite3_value *pVal = 0;
+ sqlite3 *db = pParse->db;
+
+ /* Skip over any TK_COLLATE nodes */
+ pExpr = sqlite3ExprSkipCollate(pExpr);
+
+ assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
+ if( !pExpr ){
+ pVal = valueNew(db, pAlloc);
+ if( pVal ){
+ sqlite3VdbeMemSetNull((Mem*)pVal);
+ }
+ }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
+ Vdbe *v;
+ int iBindVar = pExpr->iColumn;
+ sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
+ if( (v = pParse->pReprepare)!=0 ){
+ pVal = valueNew(db, pAlloc);
+ if( pVal ){
+ rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
+ sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
+ pVal->db = pParse->db;
+ }
+ }
+ }else{
+ rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
+ }
+
+ assert( pVal==0 || pVal->db==db );
+ *ppVal = pVal;
+ return rc;
+}
+
+/*
+** This function is used to allocate and populate UnpackedRecord
+** structures intended to be compared against sample index keys stored
+** in the sqlite_stat4 table.
+**
+** A single call to this function populates zero or more fields of the
+** record starting with field iVal (fields are numbered from left to
+** right starting with 0). A single field is populated if:
+**
+** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
+**
+** * The expression is a bound variable, and this is a reprepare, or
+**
+** * The sqlite3ValueFromExpr() function is able to extract a value
+** from the expression (i.e. the expression is a literal value).
+**
+** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
+** vector components that match either of the two latter criteria listed
+** above.
+**
+** Before any value is appended to the record, the affinity of the
+** corresponding column within index pIdx is applied to it. Before
+** this function returns, output parameter *pnExtract is set to the
+** number of values appended to the record.
+**
+** When this function is called, *ppRec must either point to an object
+** allocated by an earlier call to this function, or must be NULL. If it
+** is NULL and a value can be successfully extracted, a new UnpackedRecord
+** is allocated (and *ppRec set to point to it) before returning.
+**
+** Unless an error is encountered, SQLITE_OK is returned. It is not an
+** error if a value cannot be extracted from pExpr. If an error does
+** occur, an SQLite error code is returned.
+*/
+SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
+ Parse *pParse, /* Parse context */
+ Index *pIdx, /* Index being probed */
+ UnpackedRecord **ppRec, /* IN/OUT: Probe record */
+ Expr *pExpr, /* The expression to extract a value from */
+ int nElem, /* Maximum number of values to append */
+ int iVal, /* Array element to populate */
+ int *pnExtract /* OUT: Values appended to the record */
+){
+ int rc = SQLITE_OK;
+ int nExtract = 0;
+
+ if( pExpr==0 || pExpr->op!=TK_SELECT ){
+ int i;
+ struct ValueNewStat4Ctx alloc;
+
+ alloc.pParse = pParse;
+ alloc.pIdx = pIdx;
+ alloc.ppRec = ppRec;
+
+ for(i=0; i<nElem; i++){
+ sqlite3_value *pVal = 0;
+ Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
+ u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
+ alloc.iVal = iVal+i;
+ rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
+ if( !pVal ) break;
+ nExtract++;
+ }
+ }
+
+ *pnExtract = nExtract;
+ return rc;
+}
+
+/*
+** Attempt to extract a value from expression pExpr using the methods
+** as described for sqlite3Stat4ProbeSetValue() above.
+**
+** If successful, set *ppVal to point to a new value object and return
+** SQLITE_OK. If no value can be extracted, but no other error occurs
+** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
+** does occur, return an SQLite error code. The final value of *ppVal
+** is undefined in this case.
+*/
+SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
+ Parse *pParse, /* Parse context */
+ Expr *pExpr, /* The expression to extract a value from */
+ u8 affinity, /* Affinity to use */
+ sqlite3_value **ppVal /* OUT: New value object (or NULL) */
+){
+ return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
+}
+
+/*
+** Extract the iCol-th column from the nRec-byte record in pRec. Write
+** the column value into *ppVal. If *ppVal is initially NULL then a new
+** sqlite3_value object is allocated.
+**
+** If *ppVal is initially NULL then the caller is responsible for
+** ensuring that the value written into *ppVal is eventually freed.
+*/
+SQLITE_PRIVATE int sqlite3Stat4Column(
+ sqlite3 *db, /* Database handle */
+ const void *pRec, /* Pointer to buffer containing record */
+ int nRec, /* Size of buffer pRec in bytes */
+ int iCol, /* Column to extract */
+ sqlite3_value **ppVal /* OUT: Extracted value */
+){
+ u32 t = 0; /* a column type code */
+ int nHdr; /* Size of the header in the record */
+ int iHdr; /* Next unread header byte */
+ int iField; /* Next unread data byte */
+ int szField = 0; /* Size of the current data field */
+ int i; /* Column index */
+ u8 *a = (u8*)pRec; /* Typecast byte array */
+ Mem *pMem = *ppVal; /* Write result into this Mem object */
+
+ assert( iCol>0 );
+ iHdr = getVarint32(a, nHdr);
+ if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
+ iField = nHdr;
+ for(i=0; i<=iCol; i++){
+ iHdr += getVarint32(&a[iHdr], t);
+ testcase( iHdr==nHdr );
+ testcase( iHdr==nHdr+1 );
+ if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
+ szField = sqlite3VdbeSerialTypeLen(t);
+ iField += szField;
+ }
+ testcase( iField==nRec );
+ testcase( iField==nRec+1 );
+ if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
+ if( pMem==0 ){
+ pMem = *ppVal = sqlite3ValueNew(db);
+ if( pMem==0 ) return SQLITE_NOMEM_BKPT;
+ }
+ sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
+ pMem->enc = ENC(db);
+ return SQLITE_OK;
+}
+
+/*
+** Unless it is NULL, the argument must be an UnpackedRecord object returned
+** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
+** the object.
+*/
+SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
+ if( pRec ){
+ int i;
+ int nCol = pRec->pKeyInfo->nAllField;
+ Mem *aMem = pRec->aMem;
+ sqlite3 *db = aMem[0].db;
+ for(i=0; i<nCol; i++){
+ sqlite3VdbeMemRelease(&aMem[i]);
+ }
+ sqlite3KeyInfoUnref(pRec->pKeyInfo);
+ sqlite3DbFreeNN(db, pRec);
+ }
+}
+#endif /* ifdef SQLITE_ENABLE_STAT4 */
+
+/*
+** Change the string value of an sqlite3_value object
+*/
+SQLITE_PRIVATE void sqlite3ValueSetStr(
+ sqlite3_value *v, /* Value to be set */
+ int n, /* Length of string z */
+ const void *z, /* Text of the new string */
+ u8 enc, /* Encoding to use */
+ void (*xDel)(void*) /* Destructor for the string */
+){
+ if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
+}
+
+/*
+** Free an sqlite3_value object
+*/
+SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
+ if( !v ) return;
+ sqlite3VdbeMemRelease((Mem *)v);
+ sqlite3DbFreeNN(((Mem*)v)->db, v);
+}
+
+/*
+** The sqlite3ValueBytes() routine returns the number of bytes in the
+** sqlite3_value object assuming that it uses the encoding "enc".
+** The valueBytes() routine is a helper function.
+*/
+static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
+ return valueToText(pVal, enc)!=0 ? pVal->n : 0;
+}
+SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
+ Mem *p = (Mem*)pVal;
+ assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
+ if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
+ return p->n;
+ }
+ if( (p->flags & MEM_Blob)!=0 ){
+ if( p->flags & MEM_Zero ){
+ return p->n + p->u.nZero;
+ }else{
+ return p->n;
+ }
+ }
+ if( p->flags & MEM_Null ) return 0;
+ return valueBytes(pVal, enc);
+}
+
+/************** End of vdbemem.c *********************************************/
+/************** Begin file vdbeaux.c *****************************************/
+/*
+** 2003 September 6
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code used for creating, destroying, and populating
+** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
+*/
+/* #include "sqliteInt.h" */
+/* #include "vdbeInt.h" */
+
+/* Forward references */
+static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef);
+static void vdbeFreeOpArray(sqlite3 *, Op *, int);
+
+/*
+** Create a new virtual database engine.
+*/
+SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
+ sqlite3 *db = pParse->db;
+ Vdbe *p;
+ p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
+ if( p==0 ) return 0;
+ memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
+ p->db = db;
+ if( db->pVdbe ){
+ db->pVdbe->pPrev = p;
+ }
+ p->pNext = db->pVdbe;
+ p->pPrev = 0;
+ db->pVdbe = p;
+ p->magic = VDBE_MAGIC_INIT;
+ p->pParse = pParse;
+ pParse->pVdbe = p;
+ assert( pParse->aLabel==0 );
+ assert( pParse->nLabel==0 );
+ assert( p->nOpAlloc==0 );
+ assert( pParse->szOpAlloc==0 );
+ sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
+ return p;
+}
+
+/*
+** Return the Parse object that owns a Vdbe object.
+*/
+SQLITE_PRIVATE Parse *sqlite3VdbeParser(Vdbe *p){
+ return p->pParse;
+}
+
+/*
+** Change the error string stored in Vdbe.zErrMsg
+*/
+SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
+ va_list ap;
+ sqlite3DbFree(p->db, p->zErrMsg);
+ va_start(ap, zFormat);
+ p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
+ va_end(ap);
+}
+
+/*
+** Remember the SQL string for a prepared statement.
+*/
+SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
+ if( p==0 ) return;
+ p->prepFlags = prepFlags;
+ if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
+ p->expmask = 0;
+ }
+ assert( p->zSql==0 );
+ p->zSql = sqlite3DbStrNDup(p->db, z, n);
+}
+
+#ifdef SQLITE_ENABLE_NORMALIZE
+/*
+** Add a new element to the Vdbe->pDblStr list.
+*/
+SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3 *db, Vdbe *p, const char *z){
+ if( p ){
+ int n = sqlite3Strlen30(z);
+ DblquoteStr *pStr = sqlite3DbMallocRawNN(db,
+ sizeof(*pStr)+n+1-sizeof(pStr->z));
+ if( pStr ){
+ pStr->pNextStr = p->pDblStr;
+ p->pDblStr = pStr;
+ memcpy(pStr->z, z, n+1);
+ }
+ }
+}
+#endif
+
+#ifdef SQLITE_ENABLE_NORMALIZE
+/*
+** zId of length nId is a double-quoted identifier. Check to see if
+** that identifier is really used as a string literal.
+*/
+SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(
+ Vdbe *pVdbe, /* The prepared statement */
+ const char *zId /* The double-quoted identifier, already dequoted */
+){
+ DblquoteStr *pStr;
+ assert( zId!=0 );
+ if( pVdbe->pDblStr==0 ) return 0;
+ for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){
+ if( strcmp(zId, pStr->z)==0 ) return 1;
+ }
+ return 0;
+}
+#endif
+
+/*
+** Swap all content between two VDBE structures.
+*/
+SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
+ Vdbe tmp, *pTmp;
+ char *zTmp;
+ assert( pA->db==pB->db );
+ tmp = *pA;
+ *pA = *pB;
+ *pB = tmp;
+ pTmp = pA->pNext;
+ pA->pNext = pB->pNext;
+ pB->pNext = pTmp;
+ pTmp = pA->pPrev;
+ pA->pPrev = pB->pPrev;
+ pB->pPrev = pTmp;
+ zTmp = pA->zSql;
+ pA->zSql = pB->zSql;
+ pB->zSql = zTmp;
+#ifdef SQLITE_ENABLE_NORMALIZE
+ zTmp = pA->zNormSql;
+ pA->zNormSql = pB->zNormSql;
+ pB->zNormSql = zTmp;
+#endif
+ pB->expmask = pA->expmask;
+ pB->prepFlags = pA->prepFlags;
+ memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
+ pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
+}
+
+/*
+** Resize the Vdbe.aOp array so that it is at least nOp elements larger
+** than its current size. nOp is guaranteed to be less than or equal
+** to 1024/sizeof(Op).
+**
+** If an out-of-memory error occurs while resizing the array, return
+** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
+** unchanged (this is so that any opcodes already allocated can be
+** correctly deallocated along with the rest of the Vdbe).
+*/
+static int growOpArray(Vdbe *v, int nOp){
+ VdbeOp *pNew;
+ Parse *p = v->pParse;
+
+ /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
+ ** more frequent reallocs and hence provide more opportunities for
+ ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
+ ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
+ ** by the minimum* amount required until the size reaches 512. Normal
+ ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
+ ** size of the op array or add 1KB of space, whichever is smaller. */
+#ifdef SQLITE_TEST_REALLOC_STRESS
+ sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc
+ : (sqlite3_int64)v->nOpAlloc+nOp);
+#else
+ sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc
+ : (sqlite3_int64)(1024/sizeof(Op)));
+ UNUSED_PARAMETER(nOp);
+#endif
+
+ /* Ensure that the size of a VDBE does not grow too large */
+ if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
+ sqlite3OomFault(p->db);
+ return SQLITE_NOMEM;
+ }
+
+ assert( nOp<=(1024/sizeof(Op)) );
+ assert( nNew>=(v->nOpAlloc+nOp) );
+ pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
+ if( pNew ){
+ p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
+ v->nOpAlloc = p->szOpAlloc/sizeof(Op);
+ v->aOp = pNew;
+ }
+ return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
+}
+
+#ifdef SQLITE_DEBUG
+/* This routine is just a convenient place to set a breakpoint that will
+** fire after each opcode is inserted and displayed using
+** "PRAGMA vdbe_addoptrace=on". Parameters "pc" (program counter) and
+** pOp are available to make the breakpoint conditional.
+**
+** Other useful labels for breakpoints include:
+** test_trace_breakpoint(pc,pOp)
+** sqlite3CorruptError(lineno)
+** sqlite3MisuseError(lineno)
+** sqlite3CantopenError(lineno)
+*/
+static void test_addop_breakpoint(int pc, Op *pOp){
+ static int n = 0;
+ n++;
+}
+#endif
+
+/*
+** Add a new instruction to the list of instructions current in the
+** VDBE. Return the address of the new instruction.
+**
+** Parameters:
+**
+** p Pointer to the VDBE
+**
+** op The opcode for this instruction
+**
+** p1, p2, p3 Operands
+**
+** Use the sqlite3VdbeResolveLabel() function to fix an address and
+** the sqlite3VdbeChangeP4() function to change the value of the P4
+** operand.
+*/
+static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
+ assert( p->nOpAlloc<=p->nOp );
+ if( growOpArray(p, 1) ) return 1;
+ assert( p->nOpAlloc>p->nOp );
+ return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
+}
+SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
+ int i;
+ VdbeOp *pOp;
+
+ i = p->nOp;
+ assert( p->magic==VDBE_MAGIC_INIT );
+ assert( op>=0 && op<0xff );
+ if( p->nOpAlloc<=i ){
+ return growOp3(p, op, p1, p2, p3);
+ }
+ p->nOp++;
+ pOp = &p->aOp[i];
+ pOp->opcode = (u8)op;
+ pOp->p5 = 0;
+ pOp->p1 = p1;
+ pOp->p2 = p2;
+ pOp->p3 = p3;
+ pOp->p4.p = 0;
+ pOp->p4type = P4_NOTUSED;
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+ pOp->zComment = 0;
+#endif
+#ifdef SQLITE_DEBUG
+ if( p->db->flags & SQLITE_VdbeAddopTrace ){
+ sqlite3VdbePrintOp(0, i, &p->aOp[i]);
+ test_addop_breakpoint(i, &p->aOp[i]);
+ }
+#endif
+#ifdef VDBE_PROFILE
+ pOp->cycles = 0;
+ pOp->cnt = 0;
+#endif
+#ifdef SQLITE_VDBE_COVERAGE
+ pOp->iSrcLine = 0;
+#endif
+ return i;
+}
+SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
+ return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
+}
+SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
+ return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
+}
+SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
+ return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
+}
+
+/* Generate code for an unconditional jump to instruction iDest
+*/
+SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
+ return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
+}
+
+/* Generate code to cause the string zStr to be loaded into
+** register iDest
+*/
+SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
+ return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
+}
+
+/*
+** Generate code that initializes multiple registers to string or integer
+** constants. The registers begin with iDest and increase consecutively.
+** One register is initialized for each characgter in zTypes[]. For each
+** "s" character in zTypes[], the register is a string if the argument is
+** not NULL, or OP_Null if the value is a null pointer. For each "i" character
+** in zTypes[], the register is initialized to an integer.
+**
+** If the input string does not end with "X" then an OP_ResultRow instruction
+** is generated for the values inserted.
+*/
+SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
+ va_list ap;
+ int i;
+ char c;
+ va_start(ap, zTypes);
+ for(i=0; (c = zTypes[i])!=0; i++){
+ if( c=='s' ){
+ const char *z = va_arg(ap, const char*);
+ sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
+ }else if( c=='i' ){
+ sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
+ }else{
+ goto skip_op_resultrow;
+ }
+ }
+ sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
+skip_op_resultrow:
+ va_end(ap);
+}
+
+/*
+** Add an opcode that includes the p4 value as a pointer.
+*/
+SQLITE_PRIVATE int sqlite3VdbeAddOp4(
+ Vdbe *p, /* Add the opcode to this VM */
+ int op, /* The new opcode */
+ int p1, /* The P1 operand */
+ int p2, /* The P2 operand */
+ int p3, /* The P3 operand */
+ const char *zP4, /* The P4 operand */
+ int p4type /* P4 operand type */
+){
+ int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
+ sqlite3VdbeChangeP4(p, addr, zP4, p4type);
+ return addr;
+}
+
+/*
+** Add an OP_Function or OP_PureFunc opcode.
+**
+** The eCallCtx argument is information (typically taken from Expr.op2)
+** that describes the calling context of the function. 0 means a general
+** function call. NC_IsCheck means called by a check constraint,
+** NC_IdxExpr means called as part of an index expression. NC_PartIdx
+** means in the WHERE clause of a partial index. NC_GenCol means called
+** while computing a generated column value. 0 is the usual case.
+*/
+SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall(
+ Parse *pParse, /* Parsing context */
+ int p1, /* Constant argument mask */
+ int p2, /* First argument register */
+ int p3, /* Register into which results are written */
+ int nArg, /* Number of argument */
+ const FuncDef *pFunc, /* The function to be invoked */
+ int eCallCtx /* Calling context */
+){
+ Vdbe *v = pParse->pVdbe;
+ int nByte;
+ int addr;
+ sqlite3_context *pCtx;
+ assert( v );
+ nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*);
+ pCtx = sqlite3DbMallocRawNN(pParse->db, nByte);
+ if( pCtx==0 ){
+ assert( pParse->db->mallocFailed );
+ freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);
+ return 0;
+ }
+ pCtx->pOut = 0;
+ pCtx->pFunc = (FuncDef*)pFunc;
+ pCtx->pVdbe = 0;
+ pCtx->isError = 0;
+ pCtx->argc = nArg;
+ pCtx->iOp = sqlite3VdbeCurrentAddr(v);
+ addr = sqlite3VdbeAddOp4(v, eCallCtx ? OP_PureFunc : OP_Function,
+ p1, p2, p3, (char*)pCtx, P4_FUNCCTX);
+ sqlite3VdbeChangeP5(v, eCallCtx & NC_SelfRef);
+ return addr;
+}
+
+/*
+** Add an opcode that includes the p4 value with a P4_INT64 or
+** P4_REAL type.
+*/
+SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
+ Vdbe *p, /* Add the opcode to this VM */
+ int op, /* The new opcode */
+ int p1, /* The P1 operand */
+ int p2, /* The P2 operand */
+ int p3, /* The P3 operand */
+ const u8 *zP4, /* The P4 operand */
+ int p4type /* P4 operand type */
+){
+ char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
+ if( p4copy ) memcpy(p4copy, zP4, 8);
+ return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
+}
+
+#ifndef SQLITE_OMIT_EXPLAIN
+/*
+** Return the address of the current EXPLAIN QUERY PLAN baseline.
+** 0 means "none".
+*/
+SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse *pParse){
+ VdbeOp *pOp;
+ if( pParse->addrExplain==0 ) return 0;
+ pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
+ return pOp->p2;
+}
+
+/*
+** Set a debugger breakpoint on the following routine in order to
+** monitor the EXPLAIN QUERY PLAN code generation.
+*/
+#if defined(SQLITE_DEBUG)
+SQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char *z1, const char *z2){
+ (void)z1;
+ (void)z2;
+}
+#endif
+
+/*
+** Add a new OP_Explain opcode.
+**
+** If the bPush flag is true, then make this opcode the parent for
+** subsequent Explains until sqlite3VdbeExplainPop() is called.
+*/
+SQLITE_PRIVATE void sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
+#ifndef SQLITE_DEBUG
+ /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.
+ ** But omit them (for performance) during production builds */
+ if( pParse->explain==2 )
+#endif
+ {
+ char *zMsg;
+ Vdbe *v;
+ va_list ap;
+ int iThis;
+ va_start(ap, zFmt);
+ zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
+ va_end(ap);
+ v = pParse->pVdbe;
+ iThis = v->nOp;
+ sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
+ zMsg, P4_DYNAMIC);
+ sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetOp(v,-1)->p4.z);
+ if( bPush){
+ pParse->addrExplain = iThis;
+ }
+ }
+}
+
+/*
+** Pop the EXPLAIN QUERY PLAN stack one level.
+*/
+SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse *pParse){
+ sqlite3ExplainBreakpoint("POP", 0);
+ pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
+}
+#endif /* SQLITE_OMIT_EXPLAIN */
+
+/*
+** Add an OP_ParseSchema opcode. This routine is broken out from
+** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
+** as having been used.
+**
+** The zWhere string must have been obtained from sqlite3_malloc().
+** This routine will take ownership of the allocated memory.
+*/
+SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
+ int j;
+ sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
+ for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
+}
+
+/*
+** Add an opcode that includes the p4 value as an integer.
+*/
+SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
+ Vdbe *p, /* Add the opcode to this VM */
+ int op, /* The new opcode */
+ int p1, /* The P1 operand */
+ int p2, /* The P2 operand */
+ int p3, /* The P3 operand */
+ int p4 /* The P4 operand as an integer */
+){
+ int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
+ if( p->db->mallocFailed==0 ){
+ VdbeOp *pOp = &p->aOp[addr];
+ pOp->p4type = P4_INT32;
+ pOp->p4.i = p4;
+ }
+ return addr;
+}
+
+/* Insert the end of a co-routine
+*/
+SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
+ sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
+
+ /* Clear the temporary register cache, thereby ensuring that each
+ ** co-routine has its own independent set of registers, because co-routines
+ ** might expect their registers to be preserved across an OP_Yield, and
+ ** that could cause problems if two or more co-routines are using the same
+ ** temporary register.
+ */
+ v->pParse->nTempReg = 0;
+ v->pParse->nRangeReg = 0;
+}
+
+/*
+** Create a new symbolic label for an instruction that has yet to be
+** coded. The symbolic label is really just a negative number. The
+** label can be used as the P2 value of an operation. Later, when
+** the label is resolved to a specific address, the VDBE will scan
+** through its operation list and change all values of P2 which match
+** the label into the resolved address.
+**
+** The VDBE knows that a P2 value is a label because labels are
+** always negative and P2 values are suppose to be non-negative.
+** Hence, a negative P2 value is a label that has yet to be resolved.
+** (Later:) This is only true for opcodes that have the OPFLG_JUMP
+** property.
+**
+** Variable usage notes:
+**
+** Parse.aLabel[x] Stores the address that the x-th label resolves
+** into. For testing (SQLITE_DEBUG), unresolved
+** labels stores -1, but that is not required.
+** Parse.nLabelAlloc Number of slots allocated to Parse.aLabel[]
+** Parse.nLabel The *negative* of the number of labels that have
+** been issued. The negative is stored because
+** that gives a performance improvement over storing
+** the equivalent positive value.
+*/
+SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse *pParse){
+ return --pParse->nLabel;
+}
+
+/*
+** Resolve label "x" to be the address of the next instruction to
+** be inserted. The parameter "x" must have been obtained from
+** a prior call to sqlite3VdbeMakeLabel().
+*/
+static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){
+ int nNewSize = 10 - p->nLabel;
+ p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
+ nNewSize*sizeof(p->aLabel[0]));
+ if( p->aLabel==0 ){
+ p->nLabelAlloc = 0;
+ }else{
+#ifdef SQLITE_DEBUG
+ int i;
+ for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;
+#endif
+ p->nLabelAlloc = nNewSize;
+ p->aLabel[j] = v->nOp;
+ }
+}
+SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
+ Parse *p = v->pParse;
+ int j = ADDR(x);
+ assert( v->magic==VDBE_MAGIC_INIT );
+ assert( j<-p->nLabel );
+ assert( j>=0 );
+#ifdef SQLITE_DEBUG
+ if( p->db->flags & SQLITE_VdbeAddopTrace ){
+ printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
+ }
+#endif
+ if( p->nLabelAlloc + p->nLabel < 0 ){
+ resizeResolveLabel(p,v,j);
+ }else{
+ assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
+ p->aLabel[j] = v->nOp;
+ }
+}
+
+/*
+** Mark the VDBE as one that can only be run one time.
+*/
+SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
+ p->runOnlyOnce = 1;
+}
+
+/*
+** Mark the VDBE as one that can only be run multiple times.
+*/
+SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
+ p->runOnlyOnce = 0;
+}
+
+#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
+
+/*
+** The following type and function are used to iterate through all opcodes
+** in a Vdbe main program and each of the sub-programs (triggers) it may
+** invoke directly or indirectly. It should be used as follows:
+**
+** Op *pOp;
+** VdbeOpIter sIter;
+**
+** memset(&sIter, 0, sizeof(sIter));
+** sIter.v = v; // v is of type Vdbe*
+** while( (pOp = opIterNext(&sIter)) ){
+** // Do something with pOp
+** }
+** sqlite3DbFree(v->db, sIter.apSub);
+**
+*/
+typedef struct VdbeOpIter VdbeOpIter;
+struct VdbeOpIter {
+ Vdbe *v; /* Vdbe to iterate through the opcodes of */
+ SubProgram **apSub; /* Array of subprograms */
+ int nSub; /* Number of entries in apSub */
+ int iAddr; /* Address of next instruction to return */
+ int iSub; /* 0 = main program, 1 = first sub-program etc. */
+};
+static Op *opIterNext(VdbeOpIter *p){
+ Vdbe *v = p->v;
+ Op *pRet = 0;
+ Op *aOp;
+ int nOp;
+
+ if( p->iSub<=p->nSub ){
+
+ if( p->iSub==0 ){
+ aOp = v->aOp;
+ nOp = v->nOp;
+ }else{
+ aOp = p->apSub[p->iSub-1]->aOp;
+ nOp = p->apSub[p->iSub-1]->nOp;
+ }
+ assert( p->iAddr<nOp );
+
+ pRet = &aOp[p->iAddr];
+ p->iAddr++;
+ if( p->iAddr==nOp ){
+ p->iSub++;
+ p->iAddr = 0;
+ }
+
+ if( pRet->p4type==P4_SUBPROGRAM ){
+ int nByte = (p->nSub+1)*sizeof(SubProgram*);
+ int j;
+ for(j=0; j<p->nSub; j++){
+ if( p->apSub[j]==pRet->p4.pProgram ) break;
+ }
+ if( j==p->nSub ){
+ p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
+ if( !p->apSub ){
+ pRet = 0;
+ }else{
+ p->apSub[p->nSub++] = pRet->p4.pProgram;
+ }
+ }
+ }
+ }
+
+ return pRet;
+}
+
+/*
+** Check if the program stored in the VM associated with pParse may
+** throw an ABORT exception (causing the statement, but not entire transaction
+** to be rolled back). This condition is true if the main program or any
+** sub-programs contains any of the following:
+**
+** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
+** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
+** * OP_Destroy
+** * OP_VUpdate
+** * OP_VCreate
+** * OP_VRename
+** * OP_FkCounter with P2==0 (immediate foreign key constraint)
+** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
+** (for CREATE TABLE AS SELECT ...)
+**
+** Then check that the value of Parse.mayAbort is true if an
+** ABORT may be thrown, or false otherwise. Return true if it does
+** match, or false otherwise. This function is intended to be used as
+** part of an assert statement in the compiler. Similar to:
+**
+** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
+*/
+SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
+ int hasAbort = 0;
+ int hasFkCounter = 0;
+ int hasCreateTable = 0;
+ int hasCreateIndex = 0;
+ int hasInitCoroutine = 0;
+ Op *pOp;
+ VdbeOpIter sIter;
+ memset(&sIter, 0, sizeof(sIter));
+ sIter.v = v;
+
+ while( (pOp = opIterNext(&sIter))!=0 ){
+ int opcode = pOp->opcode;
+ if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
+ || opcode==OP_VDestroy
+ || opcode==OP_VCreate
+ || (opcode==OP_ParseSchema && pOp->p4.z==0)
+ || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
+ && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
+ ){
+ hasAbort = 1;
+ break;
+ }
+ if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
+ if( mayAbort ){
+ /* hasCreateIndex may also be set for some DELETE statements that use
+ ** OP_Clear. So this routine may end up returning true in the case
+ ** where a "DELETE FROM tbl" has a statement-journal but does not
+ ** require one. This is not so bad - it is an inefficiency, not a bug. */
+ if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1;
+ if( opcode==OP_Clear ) hasCreateIndex = 1;
+ }
+ if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
+#ifndef SQLITE_OMIT_FOREIGN_KEY
+ if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
+ hasFkCounter = 1;
+ }
+#endif
+ }
+ sqlite3DbFree(v->db, sIter.apSub);
+
+ /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
+ ** If malloc failed, then the while() loop above may not have iterated
+ ** through all opcodes and hasAbort may be set incorrectly. Return
+ ** true for this case to prevent the assert() in the callers frame
+ ** from failing. */
+ return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
+ || (hasCreateTable && hasInitCoroutine) || hasCreateIndex
+ );
+}
+#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
+
+#ifdef SQLITE_DEBUG
+/*
+** Increment the nWrite counter in the VDBE if the cursor is not an
+** ephemeral cursor, or if the cursor argument is NULL.
+*/
+SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){
+ if( pC==0
+ || (pC->eCurType!=CURTYPE_SORTER
+ && pC->eCurType!=CURTYPE_PSEUDO
+ && !pC->isEphemeral)
+ ){
+ p->nWrite++;
+ }
+}
+#endif
+
+#ifdef SQLITE_DEBUG
+/*
+** Assert if an Abort at this point in time might result in a corrupt
+** database.
+*/
+SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){
+ assert( p->nWrite==0 || p->usesStmtJournal );
+}
+#endif
+
+/*
+** This routine is called after all opcodes have been inserted. It loops
+** through all the opcodes and fixes up some details.
+**
+** (1) For each jump instruction with a negative P2 value (a label)
+** resolve the P2 value to an actual address.
+**
+** (2) Compute the maximum number of arguments used by any SQL function
+** and store that value in *pMaxFuncArgs.
+**
+** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
+** indicate what the prepared statement actually does.
+**
+** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
+**
+** (5) Reclaim the memory allocated for storing labels.
+**
+** This routine will only function correctly if the mkopcodeh.tcl generator
+** script numbers the opcodes correctly. Changes to this routine must be
+** coordinated with changes to mkopcodeh.tcl.
+*/
+static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
+ int nMaxArgs = *pMaxFuncArgs;
+ Op *pOp;
+ Parse *pParse = p->pParse;
+ int *aLabel = pParse->aLabel;
+ p->readOnly = 1;
+ p->bIsReader = 0;
+ pOp = &p->aOp[p->nOp-1];
+ while(1){
+
+ /* Only JUMP opcodes and the short list of special opcodes in the switch
+ ** below need to be considered. The mkopcodeh.tcl generator script groups
+ ** all these opcodes together near the front of the opcode list. Skip
+ ** any opcode that does not need processing by virtual of the fact that
+ ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
+ */
+ if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
+ /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
+ ** cases from this switch! */
+ switch( pOp->opcode ){
+ case OP_Transaction: {
+ if( pOp->p2!=0 ) p->readOnly = 0;
+ /* no break */ deliberate_fall_through
+ }
+ case OP_AutoCommit:
+ case OP_Savepoint: {
+ p->bIsReader = 1;
+ break;
+ }
+#ifndef SQLITE_OMIT_WAL
+ case OP_Checkpoint:
+#endif
+ case OP_Vacuum:
+ case OP_JournalMode: {
+ p->readOnly = 0;
+ p->bIsReader = 1;
+ break;
+ }
+ case OP_Next:
+ case OP_SorterNext: {
+ pOp->p4.xAdvance = sqlite3BtreeNext;
+ pOp->p4type = P4_ADVANCE;
+ /* The code generator never codes any of these opcodes as a jump
+ ** to a label. They are always coded as a jump backwards to a
+ ** known address */
+ assert( pOp->p2>=0 );
+ break;
+ }
+ case OP_Prev: {
+ pOp->p4.xAdvance = sqlite3BtreePrevious;
+ pOp->p4type = P4_ADVANCE;
+ /* The code generator never codes any of these opcodes as a jump
+ ** to a label. They are always coded as a jump backwards to a
+ ** known address */
+ assert( pOp->p2>=0 );
+ break;
+ }
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ case OP_VUpdate: {
+ if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
+ break;
+ }
+ case OP_VFilter: {
+ int n;
+ assert( (pOp - p->aOp) >= 3 );
+ assert( pOp[-1].opcode==OP_Integer );
+ n = pOp[-1].p1;
+ if( n>nMaxArgs ) nMaxArgs = n;
+ /* Fall through into the default case */
+ /* no break */ deliberate_fall_through
+ }
+#endif
+ default: {
+ if( pOp->p2<0 ){
+ /* The mkopcodeh.tcl script has so arranged things that the only
+ ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
+ ** have non-negative values for P2. */
+ assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
+ assert( ADDR(pOp->p2)<-pParse->nLabel );
+ pOp->p2 = aLabel[ADDR(pOp->p2)];
+ }
+ break;
+ }
+ }
+ /* The mkopcodeh.tcl script has so arranged things that the only
+ ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
+ ** have non-negative values for P2. */
+ assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
+ }
+ if( pOp==p->aOp ) break;
+ pOp--;
+ }
+ sqlite3DbFree(p->db, pParse->aLabel);
+ pParse->aLabel = 0;
+ pParse->nLabel = 0;
+ *pMaxFuncArgs = nMaxArgs;
+ assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
+}
+
+/*
+** Return the address of the next instruction to be inserted.
+*/
+SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
+ assert( p->magic==VDBE_MAGIC_INIT );
+ return p->nOp;
+}
+
+/*
+** Verify that at least N opcode slots are available in p without
+** having to malloc for more space (except when compiled using
+** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
+** to verify that certain calls to sqlite3VdbeAddOpList() can never
+** fail due to a OOM fault and hence that the return value from
+** sqlite3VdbeAddOpList() will always be non-NULL.
+*/
+#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
+SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
+ assert( p->nOp + N <= p->nOpAlloc );
+}
+#endif
+
+/*
+** Verify that the VM passed as the only argument does not contain
+** an OP_ResultRow opcode. Fail an assert() if it does. This is used
+** by code in pragma.c to ensure that the implementation of certain
+** pragmas comports with the flags specified in the mkpragmatab.tcl
+** script.
+*/
+#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
+SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
+ int i;
+ for(i=0; i<p->nOp; i++){
+ assert( p->aOp[i].opcode!=OP_ResultRow );
+ }
+}
+#endif
+
+/*
+** Generate code (a single OP_Abortable opcode) that will
+** verify that the VDBE program can safely call Abort in the current
+** context.
+*/
+#if defined(SQLITE_DEBUG)
+SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
+ if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
+}
+#endif
+
+/*
+** This function returns a pointer to the array of opcodes associated with
+** the Vdbe passed as the first argument. It is the callers responsibility
+** to arrange for the returned array to be eventually freed using the
+** vdbeFreeOpArray() function.
+**
+** Before returning, *pnOp is set to the number of entries in the returned
+** array. Also, *pnMaxArg is set to the larger of its current value and
+** the number of entries in the Vdbe.apArg[] array required to execute the
+** returned program.
+*/
+SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
+ VdbeOp *aOp = p->aOp;
+ assert( aOp && !p->db->mallocFailed );
+
+ /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
+ assert( DbMaskAllZero(p->btreeMask) );
+
+ resolveP2Values(p, pnMaxArg);
+ *pnOp = p->nOp;
+ p->aOp = 0;
+ return aOp;
+}
+
+/*
+** Add a whole list of operations to the operation stack. Return a
+** pointer to the first operation inserted.
+**
+** Non-zero P2 arguments to jump instructions are automatically adjusted
+** so that the jump target is relative to the first operation inserted.
+*/
+SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
+ Vdbe *p, /* Add opcodes to the prepared statement */
+ int nOp, /* Number of opcodes to add */
+ VdbeOpList const *aOp, /* The opcodes to be added */
+ int iLineno /* Source-file line number of first opcode */
+){
+ int i;
+ VdbeOp *pOut, *pFirst;
+ assert( nOp>0 );
+ assert( p->magic==VDBE_MAGIC_INIT );
+ if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){
+ return 0;
+ }
+ pFirst = pOut = &p->aOp[p->nOp];
+ for(i=0; i<nOp; i++, aOp++, pOut++){
+ pOut->opcode = aOp->opcode;
+ pOut->p1 = aOp->p1;
+ pOut->p2 = aOp->p2;
+ assert( aOp->p2>=0 );
+ if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
+ pOut->p2 += p->nOp;
+ }
+ pOut->p3 = aOp->p3;
+ pOut->p4type = P4_NOTUSED;
+ pOut->p4.p = 0;
+ pOut->p5 = 0;
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+ pOut->zComment = 0;
+#endif
+#ifdef SQLITE_VDBE_COVERAGE
+ pOut->iSrcLine = iLineno+i;
+#else
+ (void)iLineno;
+#endif
+#ifdef SQLITE_DEBUG
+ if( p->db->flags & SQLITE_VdbeAddopTrace ){
+ sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
+ }
+#endif
+ }
+ p->nOp += nOp;
+ return pFirst;
+}
+
+#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
+/*
+** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
+*/
+SQLITE_PRIVATE void sqlite3VdbeScanStatus(
+ Vdbe *p, /* VM to add scanstatus() to */
+ int addrExplain, /* Address of OP_Explain (or 0) */
+ int addrLoop, /* Address of loop counter */
+ int addrVisit, /* Address of rows visited counter */
+ LogEst nEst, /* Estimated number of output rows */
+ const char *zName /* Name of table or index being scanned */
+){
+ sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);
+ ScanStatus *aNew;
+ aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
+ if( aNew ){
+ ScanStatus *pNew = &aNew[p->nScan++];
+ pNew->addrExplain = addrExplain;
+ pNew->addrLoop = addrLoop;
+ pNew->addrVisit = addrVisit;
+ pNew->nEst = nEst;
+ pNew->zName = sqlite3DbStrDup(p->db, zName);
+ p->aScan = aNew;
+ }
+}
+#endif
+
+
+/*
+** Change the value of the opcode, or P1, P2, P3, or P5 operands
+** for a specific instruction.
+*/
+SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){
+ sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
+}
+SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
+ sqlite3VdbeGetOp(p,addr)->p1 = val;
+}
+SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
+ sqlite3VdbeGetOp(p,addr)->p2 = val;
+}
+SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
+ sqlite3VdbeGetOp(p,addr)->p3 = val;
+}
+SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
+ assert( p->nOp>0 || p->db->mallocFailed );
+ if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
+}
+
+/*
+** Change the P2 operand of instruction addr so that it points to
+** the address of the next instruction to be coded.
+*/
+SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
+ sqlite3VdbeChangeP2(p, addr, p->nOp);
+}
+
+/*
+** Change the P2 operand of the jump instruction at addr so that
+** the jump lands on the next opcode. Or if the jump instruction was
+** the previous opcode (and is thus a no-op) then simply back up
+** the next instruction counter by one slot so that the jump is
+** overwritten by the next inserted opcode.
+**
+** This routine is an optimization of sqlite3VdbeJumpHere() that
+** strives to omit useless byte-code like this:
+**
+** 7 Once 0 8 0
+** 8 ...
+*/
+SQLITE_PRIVATE void sqlite3VdbeJumpHereOrPopInst(Vdbe *p, int addr){
+ if( addr==p->nOp-1 ){
+ assert( p->aOp[addr].opcode==OP_Once
+ || p->aOp[addr].opcode==OP_If
+ || p->aOp[addr].opcode==OP_FkIfZero );
+ assert( p->aOp[addr].p4type==0 );
+#ifdef SQLITE_VDBE_COVERAGE
+ sqlite3VdbeGetOp(p,-1)->iSrcLine = 0; /* Erase VdbeCoverage() macros */
+#endif
+ p->nOp--;
+ }else{
+ sqlite3VdbeChangeP2(p, addr, p->nOp);
+ }
+}
+
+
+/*
+** If the input FuncDef structure is ephemeral, then free it. If
+** the FuncDef is not ephermal, then do nothing.
+*/
+static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
+ if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
+ sqlite3DbFreeNN(db, pDef);
+ }
+}
+
+/*
+** Delete a P4 value if necessary.
+*/
+static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
+ if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
+ sqlite3DbFreeNN(db, p);
+}
+static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
+ freeEphemeralFunction(db, p->pFunc);
+ sqlite3DbFreeNN(db, p);
+}
+static void freeP4(sqlite3 *db, int p4type, void *p4){
+ assert( db );
+ switch( p4type ){
+ case P4_FUNCCTX: {
+ freeP4FuncCtx(db, (sqlite3_context*)p4);
+ break;
+ }
+ case P4_REAL:
+ case P4_INT64:
+ case P4_DYNAMIC:
+ case P4_DYNBLOB:
+ case P4_INTARRAY: {
+ sqlite3DbFree(db, p4);
+ break;
+ }
+ case P4_KEYINFO: {
+ if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
+ break;
+ }
+#ifdef SQLITE_ENABLE_CURSOR_HINTS
+ case P4_EXPR: {
+ sqlite3ExprDelete(db, (Expr*)p4);
+ break;
+ }
+#endif
+ case P4_FUNCDEF: {
+ freeEphemeralFunction(db, (FuncDef*)p4);
+ break;
+ }
+ case P4_MEM: {
+ if( db->pnBytesFreed==0 ){
+ sqlite3ValueFree((sqlite3_value*)p4);
+ }else{
+ freeP4Mem(db, (Mem*)p4);
+ }
+ break;
+ }
+ case P4_VTAB : {
+ if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
+ break;
+ }
+ }
+}
+
+/*
+** Free the space allocated for aOp and any p4 values allocated for the
+** opcodes contained within. If aOp is not NULL it is assumed to contain
+** nOp entries.
+*/
+static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
+ if( aOp ){
+ Op *pOp;
+ for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
+ if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+ sqlite3DbFree(db, pOp->zComment);
+#endif
+ }
+ sqlite3DbFreeNN(db, aOp);
+ }
+}
+
+/*
+** Link the SubProgram object passed as the second argument into the linked
+** list at Vdbe.pSubProgram. This list is used to delete all sub-program
+** objects when the VM is no longer required.
+*/
+SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
+ p->pNext = pVdbe->pProgram;
+ pVdbe->pProgram = p;
+}
+
+/*
+** Return true if the given Vdbe has any SubPrograms.
+*/
+SQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe *pVdbe){
+ return pVdbe->pProgram!=0;
+}
+
+/*
+** Change the opcode at addr into OP_Noop
+*/
+SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
+ VdbeOp *pOp;
+ if( p->db->mallocFailed ) return 0;
+ assert( addr>=0 && addr<p->nOp );
+ pOp = &p->aOp[addr];
+ freeP4(p->db, pOp->p4type, pOp->p4.p);
+ pOp->p4type = P4_NOTUSED;
+ pOp->p4.z = 0;
+ pOp->opcode = OP_Noop;
+ return 1;
+}
+
+/*
+** If the last opcode is "op" and it is not a jump destination,
+** then remove it. Return true if and only if an opcode was removed.
+*/
+SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
+ if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
+ return sqlite3VdbeChangeToNoop(p, p->nOp-1);
+ }else{
+ return 0;
+ }
+}
+
+#ifdef SQLITE_DEBUG
+/*
+** Generate an OP_ReleaseReg opcode to indicate that a range of
+** registers, except any identified by mask, are no longer in use.
+*/
+SQLITE_PRIVATE void sqlite3VdbeReleaseRegisters(
+ Parse *pParse, /* Parsing context */
+ int iFirst, /* Index of first register to be released */
+ int N, /* Number of registers to release */
+ u32 mask, /* Mask of registers to NOT release */
+ int bUndefine /* If true, mark registers as undefined */
+){
+ if( N==0 ) return;
+ assert( pParse->pVdbe );
+ assert( iFirst>=1 );
+ assert( iFirst+N-1<=pParse->nMem );
+ if( N<=31 && mask!=0 ){
+ while( N>0 && (mask&1)!=0 ){
+ mask >>= 1;
+ iFirst++;
+ N--;
+ }
+ while( N>0 && N<=32 && (mask & MASKBIT32(N-1))!=0 ){
+ mask &= ~MASKBIT32(N-1);
+ N--;
+ }
+ }
+ if( N>0 ){
+ sqlite3VdbeAddOp3(pParse->pVdbe, OP_ReleaseReg, iFirst, N, *(int*)&mask);
+ if( bUndefine ) sqlite3VdbeChangeP5(pParse->pVdbe, 1);
+ }
+}
+#endif /* SQLITE_DEBUG */
+
+
+/*
+** Change the value of the P4 operand for a specific instruction.
+** This routine is useful when a large program is loaded from a
+** static array using sqlite3VdbeAddOpList but we want to make a
+** few minor changes to the program.
+**
+** If n>=0 then the P4 operand is dynamic, meaning that a copy of
+** the string is made into memory obtained from sqlite3_malloc().
+** A value of n==0 means copy bytes of zP4 up to and including the
+** first null byte. If n>0 then copy n+1 bytes of zP4.
+**
+** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
+** to a string or structure that is guaranteed to exist for the lifetime of
+** the Vdbe. In these cases we can just copy the pointer.
+**
+** If addr<0 then change P4 on the most recently inserted instruction.
+*/
+static void SQLITE_NOINLINE vdbeChangeP4Full(
+ Vdbe *p,
+ Op *pOp,
+ const char *zP4,
+ int n
+){
+ if( pOp->p4type ){
+ freeP4(p->db, pOp->p4type, pOp->p4.p);
+ pOp->p4type = 0;
+ pOp->p4.p = 0;
+ }
+ if( n<0 ){
+ sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
+ }else{
+ if( n==0 ) n = sqlite3Strlen30(zP4);
+ pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
+ pOp->p4type = P4_DYNAMIC;
+ }
+}
+SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
+ Op *pOp;
+ sqlite3 *db;
+ assert( p!=0 );
+ db = p->db;
+ assert( p->magic==VDBE_MAGIC_INIT );
+ assert( p->aOp!=0 || db->mallocFailed );
+ if( db->mallocFailed ){
+ if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
+ return;
+ }
+ assert( p->nOp>0 );
+ assert( addr<p->nOp );
+ if( addr<0 ){
+ addr = p->nOp - 1;
+ }
+ pOp = &p->aOp[addr];
+ if( n>=0 || pOp->p4type ){
+ vdbeChangeP4Full(p, pOp, zP4, n);
+ return;
+ }
+ if( n==P4_INT32 ){
+ /* Note: this cast is safe, because the origin data point was an int
+ ** that was cast to a (const char *). */
+ pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
+ pOp->p4type = P4_INT32;
+ }else if( zP4!=0 ){
+ assert( n<0 );
+ pOp->p4.p = (void*)zP4;
+ pOp->p4type = (signed char)n;
+ if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
+ }
+}
+
+/*
+** Change the P4 operand of the most recently coded instruction
+** to the value defined by the arguments. This is a high-speed
+** version of sqlite3VdbeChangeP4().
+**
+** The P4 operand must not have been previously defined. And the new
+** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
+** those cases.
+*/
+SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
+ VdbeOp *pOp;
+ assert( n!=P4_INT32 && n!=P4_VTAB );
+ assert( n<=0 );
+ if( p->db->mallocFailed ){
+ freeP4(p->db, n, pP4);
+ }else{
+ assert( pP4!=0 );
+ assert( p->nOp>0 );
+ pOp = &p->aOp[p->nOp-1];
+ assert( pOp->p4type==P4_NOTUSED );
+ pOp->p4type = n;
+ pOp->p4.p = pP4;
+ }
+}
+
+/*
+** Set the P4 on the most recently added opcode to the KeyInfo for the
+** index given.
+*/
+SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
+ Vdbe *v = pParse->pVdbe;
+ KeyInfo *pKeyInfo;
+ assert( v!=0 );
+ assert( pIdx!=0 );
+ pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
+ if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
+}
+
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+/*
+** Change the comment on the most recently coded instruction. Or
+** insert a No-op and add the comment to that new instruction. This
+** makes the code easier to read during debugging. None of this happens
+** in a production build.
+*/
+static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
+ assert( p->nOp>0 || p->aOp==0 );
+ assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed
+ || p->pParse->nErr>0 );
+ if( p->nOp ){
+ assert( p->aOp );
+ sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
+ p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
+ }
+}
+SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
+ va_list ap;
+ if( p ){
+ va_start(ap, zFormat);
+ vdbeVComment(p, zFormat, ap);
+ va_end(ap);
+ }
+}
+SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
+ va_list ap;
+ if( p ){
+ sqlite3VdbeAddOp0(p, OP_Noop);
+ va_start(ap, zFormat);
+ vdbeVComment(p, zFormat, ap);
+ va_end(ap);
+ }
+}
+#endif /* NDEBUG */
+
+#ifdef SQLITE_VDBE_COVERAGE
+/*
+** Set the value if the iSrcLine field for the previously coded instruction.
+*/
+SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
+ sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
+}
+#endif /* SQLITE_VDBE_COVERAGE */
+
+/*
+** Return the opcode for a given address. If the address is -1, then
+** return the most recently inserted opcode.
+**
+** If a memory allocation error has occurred prior to the calling of this
+** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
+** is readable but not writable, though it is cast to a writable value.
+** The return of a dummy opcode allows the call to continue functioning
+** after an OOM fault without having to check to see if the return from
+** this routine is a valid pointer. But because the dummy.opcode is 0,
+** dummy will never be written to. This is verified by code inspection and
+** by running with Valgrind.
+*/
+SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
+ /* C89 specifies that the constant "dummy" will be initialized to all
+ ** zeros, which is correct. MSVC generates a warning, nevertheless. */
+ static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
+ assert( p->magic==VDBE_MAGIC_INIT );
+ if( addr<0 ){
+ addr = p->nOp - 1;
+ }
+ assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
+ if( p->db->mallocFailed ){
+ return (VdbeOp*)&dummy;
+ }else{
+ return &p->aOp[addr];
+ }
+}
+
+#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
+/*
+** Return an integer value for one of the parameters to the opcode pOp
+** determined by character c.
+*/
+static int translateP(char c, const Op *pOp){
+ if( c=='1' ) return pOp->p1;
+ if( c=='2' ) return pOp->p2;
+ if( c=='3' ) return pOp->p3;
+ if( c=='4' ) return pOp->p4.i;
+ return pOp->p5;
+}
+
+/*
+** Compute a string for the "comment" field of a VDBE opcode listing.
+**
+** The Synopsis: field in comments in the vdbe.c source file gets converted
+** to an extra string that is appended to the sqlite3OpcodeName(). In the
+** absence of other comments, this synopsis becomes the comment on the opcode.
+** Some translation occurs:
+**
+** "PX" -> "r[X]"
+** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
+** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
+** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
+*/
+SQLITE_PRIVATE char *sqlite3VdbeDisplayComment(
+ sqlite3 *db, /* Optional - Oom error reporting only */
+ const Op *pOp, /* The opcode to be commented */
+ const char *zP4 /* Previously obtained value for P4 */
+){
+ const char *zOpName;
+ const char *zSynopsis;
+ int nOpName;
+ int ii;
+ char zAlt[50];
+ StrAccum x;
+
+ sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
+ zOpName = sqlite3OpcodeName(pOp->opcode);
+ nOpName = sqlite3Strlen30(zOpName);
+ if( zOpName[nOpName+1] ){
+ int seenCom = 0;
+ char c;
+ zSynopsis = zOpName += nOpName + 1;
+ if( strncmp(zSynopsis,"IF ",3)==0 ){
+ if( pOp->p5 & SQLITE_STOREP2 ){
+ sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
+ }else{
+ sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
+ }
+ zSynopsis = zAlt;
+ }
+ for(ii=0; (c = zSynopsis[ii])!=0; ii++){
+ if( c=='P' ){
+ c = zSynopsis[++ii];
+ if( c=='4' ){
+ sqlite3_str_appendall(&x, zP4);
+ }else if( c=='X' ){
+ sqlite3_str_appendall(&x, pOp->zComment);
+ seenCom = 1;
+ }else{
+ int v1 = translateP(c, pOp);
+ int v2;
+ if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
+ ii += 3;
+ v2 = translateP(zSynopsis[ii], pOp);
+ if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
+ ii += 2;
+ v2++;
+ }
+ if( v2<2 ){
+ sqlite3_str_appendf(&x, "%d", v1);
+ }else{
+ sqlite3_str_appendf(&x, "%d..%d", v1, v1+v2-1);
+ }
+ }else if( strncmp(zSynopsis+ii+1, "@NP", 3)==0 ){
+ sqlite3_context *pCtx = pOp->p4.pCtx;
+ if( pOp->p4type!=P4_FUNCCTX || pCtx->argc==1 ){
+ sqlite3_str_appendf(&x, "%d", v1);
+ }else if( pCtx->argc>1 ){
+ sqlite3_str_appendf(&x, "%d..%d", v1, v1+pCtx->argc-1);
+ }else{
+ assert( x.nChar>2 );
+ x.nChar -= 2;
+ ii++;
+ }
+ ii += 3;
+ }else{
+ sqlite3_str_appendf(&x, "%d", v1);
+ if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
+ ii += 4;
+ }
+ }
+ }
+ }else{
+ sqlite3_str_appendchar(&x, 1, c);
+ }
+ }
+ if( !seenCom && pOp->zComment ){
+ sqlite3_str_appendf(&x, "; %s", pOp->zComment);
+ }
+ }else if( pOp->zComment ){
+ sqlite3_str_appendall(&x, pOp->zComment);
+ }
+ if( (x.accError & SQLITE_NOMEM)!=0 && db!=0 ){
+ sqlite3OomFault(db);
+ }
+ return sqlite3StrAccumFinish(&x);
+}
+#endif /* SQLITE_ENABLE_EXPLAIN_COMMENTS */
+
+#if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
+/*
+** Translate the P4.pExpr value for an OP_CursorHint opcode into text
+** that can be displayed in the P4 column of EXPLAIN output.
+*/
+static void displayP4Expr(StrAccum *p, Expr *pExpr){
+ const char *zOp = 0;
+ switch( pExpr->op ){
+ case TK_STRING:
+ sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
+ break;
+ case TK_INTEGER:
+ sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
+ break;
+ case TK_NULL:
+ sqlite3_str_appendf(p, "NULL");
+ break;
+ case TK_REGISTER: {
+ sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
+ break;
+ }
+ case TK_COLUMN: {
+ if( pExpr->iColumn<0 ){
+ sqlite3_str_appendf(p, "rowid");
+ }else{
+ sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
+ }
+ break;
+ }
+ case TK_LT: zOp = "LT"; break;
+ case TK_LE: zOp = "LE"; break;
+ case TK_GT: zOp = "GT"; break;
+ case TK_GE: zOp = "GE"; break;
+ case TK_NE: zOp = "NE"; break;
+ case TK_EQ: zOp = "EQ"; break;
+ case TK_IS: zOp = "IS"; break;
+ case TK_ISNOT: zOp = "ISNOT"; break;
+ case TK_AND: zOp = "AND"; break;
+ case TK_OR: zOp = "OR"; break;
+ case TK_PLUS: zOp = "ADD"; break;
+ case TK_STAR: zOp = "MUL"; break;
+ case TK_MINUS: zOp = "SUB"; break;
+ case TK_REM: zOp = "REM"; break;
+ case TK_BITAND: zOp = "BITAND"; break;
+ case TK_BITOR: zOp = "BITOR"; break;
+ case TK_SLASH: zOp = "DIV"; break;
+ case TK_LSHIFT: zOp = "LSHIFT"; break;
+ case TK_RSHIFT: zOp = "RSHIFT"; break;
+ case TK_CONCAT: zOp = "CONCAT"; break;
+ case TK_UMINUS: zOp = "MINUS"; break;
+ case TK_UPLUS: zOp = "PLUS"; break;
+ case TK_BITNOT: zOp = "BITNOT"; break;
+ case TK_NOT: zOp = "NOT"; break;
+ case TK_ISNULL: zOp = "ISNULL"; break;
+ case TK_NOTNULL: zOp = "NOTNULL"; break;
+
+ default:
+ sqlite3_str_appendf(p, "%s", "expr");
+ break;
+ }
+
+ if( zOp ){
+ sqlite3_str_appendf(p, "%s(", zOp);
+ displayP4Expr(p, pExpr->pLeft);
+ if( pExpr->pRight ){
+ sqlite3_str_append(p, ",", 1);
+ displayP4Expr(p, pExpr->pRight);
+ }
+ sqlite3_str_append(p, ")", 1);
+ }
+}
+#endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
+
+
+#if VDBE_DISPLAY_P4
+/*
+** Compute a string that describes the P4 parameter for an opcode.
+** Use zTemp for any required temporary buffer space.
+*/
+SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3 *db, Op *pOp){
+ char *zP4 = 0;
+ StrAccum x;
+
+ sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
+ switch( pOp->p4type ){
+ case P4_KEYINFO: {
+ int j;
+ KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
+ assert( pKeyInfo->aSortFlags!=0 );
+ sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
+ for(j=0; j<pKeyInfo->nKeyField; j++){
+ CollSeq *pColl = pKeyInfo->aColl[j];
+ const char *zColl = pColl ? pColl->zName : "";
+ if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
+ sqlite3_str_appendf(&x, ",%s%s%s",
+ (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "",
+ (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "",
+ zColl);
+ }
+ sqlite3_str_append(&x, ")", 1);
+ break;
+ }
+#ifdef SQLITE_ENABLE_CURSOR_HINTS
+ case P4_EXPR: {
+ displayP4Expr(&x, pOp->p4.pExpr);
+ break;
+ }
+#endif
+ case P4_COLLSEQ: {
+ static const char *const encnames[] = {"?", "8", "16LE", "16BE"};
+ CollSeq *pColl = pOp->p4.pColl;
+ assert( pColl->enc>=0 && pColl->enc<4 );
+ sqlite3_str_appendf(&x, "%.18s-%s", pColl->zName,
+ encnames[pColl->enc]);
+ break;
+ }
+ case P4_FUNCDEF: {
+ FuncDef *pDef = pOp->p4.pFunc;
+ sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
+ break;
+ }
+ case P4_FUNCCTX: {
+ FuncDef *pDef = pOp->p4.pCtx->pFunc;
+ sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
+ break;
+ }
+ case P4_INT64: {
+ sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
+ break;
+ }
+ case P4_INT32: {
+ sqlite3_str_appendf(&x, "%d", pOp->p4.i);
+ break;
+ }
+ case P4_REAL: {
+ sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
+ break;
+ }
+ case P4_MEM: {
+ Mem *pMem = pOp->p4.pMem;
+ if( pMem->flags & MEM_Str ){
+ zP4 = pMem->z;
+ }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
+ sqlite3_str_appendf(&x, "%lld", pMem->u.i);
+ }else if( pMem->flags & MEM_Real ){
+ sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
+ }else if( pMem->flags & MEM_Null ){
+ zP4 = "NULL";
+ }else{
+ assert( pMem->flags & MEM_Blob );
+ zP4 = "(blob)";
+ }
+ break;
+ }
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ case P4_VTAB: {
+ sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
+ sqlite3_str_appendf(&x, "vtab:%p", pVtab);
+ break;
+ }
+#endif
+ case P4_INTARRAY: {
+ u32 i;
+ u32 *ai = pOp->p4.ai;
+ u32 n = ai[0]; /* The first element of an INTARRAY is always the
+ ** count of the number of elements to follow */
+ for(i=1; i<=n; i++){
+ sqlite3_str_appendf(&x, "%c%u", (i==1 ? '[' : ','), ai[i]);
+ }
+ sqlite3_str_append(&x, "]", 1);
+ break;
+ }
+ case P4_SUBPROGRAM: {
+ zP4 = "program";
+ break;
+ }
+ case P4_DYNBLOB:
+ case P4_ADVANCE: {
+ break;
+ }
+ case P4_TABLE: {
+ zP4 = pOp->p4.pTab->zName;
+ break;
+ }
+ default: {
+ zP4 = pOp->p4.z;
+ }
+ }
+ if( zP4 ) sqlite3_str_appendall(&x, zP4);
+ if( (x.accError & SQLITE_NOMEM)!=0 ){
+ sqlite3OomFault(db);
+ }
+ return sqlite3StrAccumFinish(&x);
+}
+#endif /* VDBE_DISPLAY_P4 */
+
+/*
+** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
+**
+** The prepared statements need to know in advance the complete set of
+** attached databases that will be use. A mask of these databases
+** is maintained in p->btreeMask. The p->lockMask value is the subset of
+** p->btreeMask of databases that will require a lock.
+*/
+SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
+ assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
+ assert( i<(int)sizeof(p->btreeMask)*8 );
+ DbMaskSet(p->btreeMask, i);
+ if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
+ DbMaskSet(p->lockMask, i);
+ }
+}
+
+#if !defined(SQLITE_OMIT_SHARED_CACHE)
+/*
+** If SQLite is compiled to support shared-cache mode and to be threadsafe,
+** this routine obtains the mutex associated with each BtShared structure
+** that may be accessed by the VM passed as an argument. In doing so it also
+** sets the BtShared.db member of each of the BtShared structures, ensuring
+** that the correct busy-handler callback is invoked if required.
+**
+** If SQLite is not threadsafe but does support shared-cache mode, then
+** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
+** of all of BtShared structures accessible via the database handle
+** associated with the VM.
+**
+** If SQLite is not threadsafe and does not support shared-cache mode, this
+** function is a no-op.
+**
+** The p->btreeMask field is a bitmask of all btrees that the prepared
+** statement p will ever use. Let N be the number of bits in p->btreeMask
+** corresponding to btrees that use shared cache. Then the runtime of
+** this routine is N*N. But as N is rarely more than 1, this should not
+** be a problem.
+*/
+SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
+ int i;
+ sqlite3 *db;
+ Db *aDb;
+ int nDb;
+ if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
+ db = p->db;
+ aDb = db->aDb;
+ nDb = db->nDb;
+ for(i=0; i<nDb; i++){
+ if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
+ sqlite3BtreeEnter(aDb[i].pBt);
+ }
+ }
+}
+#endif
+
+#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
+/*
+** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
+*/
+static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
+ int i;
+ sqlite3 *db;
+ Db *aDb;
+ int nDb;
+ db = p->db;
+ aDb = db->aDb;
+ nDb = db->nDb;
+ for(i=0; i<nDb; i++){
+ if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
+ sqlite3BtreeLeave(aDb[i].pBt);
+ }
+ }
+}
+SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
+ if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
+ vdbeLeave(p);
+}
+#endif
+
+#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
+/*
+** Print a single opcode. This routine is used for debugging only.
+*/
+SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
+ char *zP4;
+ char *zCom;
+ sqlite3 dummyDb;
+ static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
+ if( pOut==0 ) pOut = stdout;
+ sqlite3BeginBenignMalloc();
+ dummyDb.mallocFailed = 1;
+ zP4 = sqlite3VdbeDisplayP4(&dummyDb, pOp);
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+ zCom = sqlite3VdbeDisplayComment(0, pOp, zP4);
+#else
+ zCom = 0;
+#endif
+ /* NB: The sqlite3OpcodeName() function is implemented by code created
+ ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
+ ** information from the vdbe.c source text */
+ fprintf(pOut, zFormat1, pc,
+ sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3,
+ zP4 ? zP4 : "", pOp->p5,
+ zCom ? zCom : ""
+ );
+ fflush(pOut);
+ sqlite3_free(zP4);
+ sqlite3_free(zCom);
+ sqlite3EndBenignMalloc();
+}
+#endif
+
+/*
+** Initialize an array of N Mem element.
+*/
+static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
+ while( (N--)>0 ){
+ p->db = db;
+ p->flags = flags;
+ p->szMalloc = 0;
+#ifdef SQLITE_DEBUG
+ p->pScopyFrom = 0;
+#endif
+ p++;
+ }
+}
+
+/*
+** Release an array of N Mem elements
+*/
+static void releaseMemArray(Mem *p, int N){
+ if( p && N ){
+ Mem *pEnd = &p[N];
+ sqlite3 *db = p->db;
+ if( db->pnBytesFreed ){
+ do{
+ if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
+ }while( (++p)<pEnd );
+ return;
+ }
+ do{
+ assert( (&p[1])==pEnd || p[0].db==p[1].db );
+ assert( sqlite3VdbeCheckMemInvariants(p) );
+
+ /* This block is really an inlined version of sqlite3VdbeMemRelease()
+ ** that takes advantage of the fact that the memory cell value is
+ ** being set to NULL after releasing any dynamic resources.
+ **
+ ** The justification for duplicating code is that according to
+ ** callgrind, this causes a certain test case to hit the CPU 4.7
+ ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
+ ** sqlite3MemRelease() were called from here. With -O2, this jumps
+ ** to 6.6 percent. The test case is inserting 1000 rows into a table
+ ** with no indexes using a single prepared INSERT statement, bind()
+ ** and reset(). Inserts are grouped into a transaction.
+ */
+ testcase( p->flags & MEM_Agg );
+ testcase( p->flags & MEM_Dyn );
+ testcase( p->xDel==sqlite3VdbeFrameMemDel );
+ if( p->flags&(MEM_Agg|MEM_Dyn) ){
+ sqlite3VdbeMemRelease(p);
+ }else if( p->szMalloc ){
+ sqlite3DbFreeNN(db, p->zMalloc);
+ p->szMalloc = 0;
+ }
+
+ p->flags = MEM_Undefined;
+ }while( (++p)<pEnd );
+ }
+}
+
+#ifdef SQLITE_DEBUG
+/*
+** Verify that pFrame is a valid VdbeFrame pointer. Return true if it is
+** and false if something is wrong.
+**
+** This routine is intended for use inside of assert() statements only.
+*/
+SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame *pFrame){
+ if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
+ return 1;
+}
+#endif
+
+
+/*
+** This is a destructor on a Mem object (which is really an sqlite3_value)
+** that deletes the Frame object that is attached to it as a blob.
+**
+** This routine does not delete the Frame right away. It merely adds the
+** frame to a list of frames to be deleted when the Vdbe halts.
+*/
+SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void *pArg){
+ VdbeFrame *pFrame = (VdbeFrame*)pArg;
+ assert( sqlite3VdbeFrameIsValid(pFrame) );
+ pFrame->pParent = pFrame->v->pDelFrame;
+ pFrame->v->pDelFrame = pFrame;
+}
+
+#if defined(SQLITE_ENABLE_BYTECODE_VTAB) || !defined(SQLITE_OMIT_EXPLAIN)
+/*
+** Locate the next opcode to be displayed in EXPLAIN or EXPLAIN
+** QUERY PLAN output.
+**
+** Return SQLITE_ROW on success. Return SQLITE_DONE if there are no
+** more opcodes to be displayed.
+*/
+SQLITE_PRIVATE int sqlite3VdbeNextOpcode(
+ Vdbe *p, /* The statement being explained */
+ Mem *pSub, /* Storage for keeping track of subprogram nesting */
+ int eMode, /* 0: normal. 1: EQP. 2: TablesUsed */
+ int *piPc, /* IN/OUT: Current rowid. Overwritten with next rowid */
+ int *piAddr, /* OUT: Write index into (*paOp)[] here */
+ Op **paOp /* OUT: Write the opcode array here */
+){
+ int nRow; /* Stop when row count reaches this */
+ int nSub = 0; /* Number of sub-vdbes seen so far */
+ SubProgram **apSub = 0; /* Array of sub-vdbes */
+ int i; /* Next instruction address */
+ int rc = SQLITE_OK; /* Result code */
+ Op *aOp = 0; /* Opcode array */
+ int iPc; /* Rowid. Copy of value in *piPc */
+
+ /* When the number of output rows reaches nRow, that means the
+ ** listing has finished and sqlite3_step() should return SQLITE_DONE.
+ ** nRow is the sum of the number of rows in the main program, plus
+ ** the sum of the number of rows in all trigger subprograms encountered
+ ** so far. The nRow value will increase as new trigger subprograms are
+ ** encountered, but p->pc will eventually catch up to nRow.
+ */
+ nRow = p->nOp;
+ if( pSub!=0 ){
+ if( pSub->flags&MEM_Blob ){
+ /* pSub is initiallly NULL. It is initialized to a BLOB by
+ ** the P4_SUBPROGRAM processing logic below */
+ nSub = pSub->n/sizeof(Vdbe*);
+ apSub = (SubProgram **)pSub->z;
+ }
+ for(i=0; i<nSub; i++){
+ nRow += apSub[i]->nOp;
+ }
+ }
+ iPc = *piPc;
+ while(1){ /* Loop exits via break */
+ i = iPc++;
+ if( i>=nRow ){
+ p->rc = SQLITE_OK;
+ rc = SQLITE_DONE;
+ break;
+ }
+ if( i<p->nOp ){
+ /* The rowid is small enough that we are still in the
+ ** main program. */
+ aOp = p->aOp;
+ }else{
+ /* We are currently listing subprograms. Figure out which one and
+ ** pick up the appropriate opcode. */
+ int j;
+ i -= p->nOp;
+ assert( apSub!=0 );
+ assert( nSub>0 );
+ for(j=0; i>=apSub[j]->nOp; j++){
+ i -= apSub[j]->nOp;
+ assert( i<apSub[j]->nOp || j+1<nSub );
+ }
+ aOp = apSub[j]->aOp;
+ }
+
+ /* When an OP_Program opcode is encounter (the only opcode that has
+ ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
+ ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
+ ** has not already been seen.
+ */
+ if( pSub!=0 && aOp[i].p4type==P4_SUBPROGRAM ){
+ int nByte = (nSub+1)*sizeof(SubProgram*);
+ int j;
+ for(j=0; j<nSub; j++){
+ if( apSub[j]==aOp[i].p4.pProgram ) break;
+ }
+ if( j==nSub ){
+ p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
+ if( p->rc!=SQLITE_OK ){
+ rc = SQLITE_ERROR;
+ break;
+ }
+ apSub = (SubProgram **)pSub->z;
+ apSub[nSub++] = aOp[i].p4.pProgram;
+ MemSetTypeFlag(pSub, MEM_Blob);
+ pSub->n = nSub*sizeof(SubProgram*);
+ nRow += aOp[i].p4.pProgram->nOp;
+ }
+ }
+ if( eMode==0 ) break;
+#ifdef SQLITE_ENABLE_BYTECODE_VTAB
+ if( eMode==2 ){
+ Op *pOp = aOp + i;
+ if( pOp->opcode==OP_OpenRead ) break;
+ if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break;
+ if( pOp->opcode==OP_ReopenIdx ) break;
+ }else
+#endif
+ {
+ assert( eMode==1 );
+ if( aOp[i].opcode==OP_Explain ) break;
+ if( aOp[i].opcode==OP_Init && iPc>1 ) break;
+ }
+ }
+ *piPc = iPc;
+ *piAddr = i;
+ *paOp = aOp;
+ return rc;
+}
+#endif /* SQLITE_ENABLE_BYTECODE_VTAB || !SQLITE_OMIT_EXPLAIN */
+
+
+/*
+** Delete a VdbeFrame object and its contents. VdbeFrame objects are
+** allocated by the OP_Program opcode in sqlite3VdbeExec().
+*/
+SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
+ int i;
+ Mem *aMem = VdbeFrameMem(p);
+ VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
+ assert( sqlite3VdbeFrameIsValid(p) );
+ for(i=0; i<p->nChildCsr; i++){
+ sqlite3VdbeFreeCursor(p->v, apCsr[i]);
+ }
+ releaseMemArray(aMem, p->nChildMem);
+ sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
+ sqlite3DbFree(p->v->db, p);
+}
+
+#ifndef SQLITE_OMIT_EXPLAIN
+/*
+** Give a listing of the program in the virtual machine.
+**
+** The interface is the same as sqlite3VdbeExec(). But instead of
+** running the code, it invokes the callback once for each instruction.
+** This feature is used to implement "EXPLAIN".
+**
+** When p->explain==1, each instruction is listed. When
+** p->explain==2, only OP_Explain instructions are listed and these
+** are shown in a different format. p->explain==2 is used to implement
+** EXPLAIN QUERY PLAN.
+** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers
+** are also shown, so that the boundaries between the main program and
+** each trigger are clear.
+**
+** When p->explain==1, first the main program is listed, then each of
+** the trigger subprograms are listed one by one.
+*/
+SQLITE_PRIVATE int sqlite3VdbeList(
+ Vdbe *p /* The VDBE */
+){
+ Mem *pSub = 0; /* Memory cell hold array of subprogs */
+ sqlite3 *db = p->db; /* The database connection */
+ int i; /* Loop counter */
+ int rc = SQLITE_OK; /* Return code */
+ Mem *pMem = &p->aMem[1]; /* First Mem of result set */
+ int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
+ Op *aOp; /* Array of opcodes */
+ Op *pOp; /* Current opcode */
+
+ assert( p->explain );
+ assert( p->magic==VDBE_MAGIC_RUN );
+ assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
+
+ /* Even though this opcode does not use dynamic strings for
+ ** the result, result columns may become dynamic if the user calls
+ ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
+ */
+ releaseMemArray(pMem, 8);
+ p->pResultSet = 0;
+
+ if( p->rc==SQLITE_NOMEM ){
+ /* This happens if a malloc() inside a call to sqlite3_column_text() or
+ ** sqlite3_column_text16() failed. */
+ sqlite3OomFault(db);
+ return SQLITE_ERROR;
+ }
+
+ if( bListSubprogs ){
+ /* The first 8 memory cells are used for the result set. So we will
+ ** commandeer the 9th cell to use as storage for an array of pointers
+ ** to trigger subprograms. The VDBE is guaranteed to have at least 9
+ ** cells. */
+ assert( p->nMem>9 );
+ pSub = &p->aMem[9];
+ }else{
+ pSub = 0;
+ }
+
+ /* Figure out which opcode is next to display */
+ rc = sqlite3VdbeNextOpcode(p, pSub, p->explain==2, &p->pc, &i, &aOp);
+
+ if( rc==SQLITE_OK ){
+ pOp = aOp + i;
+ if( AtomicLoad(&db->u1.isInterrupted) ){
+ p->rc = SQLITE_INTERRUPT;
+ rc = SQLITE_ERROR;
+ sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
+ }else{
+ char *zP4 = sqlite3VdbeDisplayP4(db, pOp);
+ if( p->explain==2 ){
+ sqlite3VdbeMemSetInt64(pMem, pOp->p1);
+ sqlite3VdbeMemSetInt64(pMem+1, pOp->p2);
+ sqlite3VdbeMemSetInt64(pMem+2, pOp->p3);
+ sqlite3VdbeMemSetStr(pMem+3, zP4, -1, SQLITE_UTF8, sqlite3_free);
+ p->nResColumn = 4;
+ }else{
+ sqlite3VdbeMemSetInt64(pMem+0, i);
+ sqlite3VdbeMemSetStr(pMem+1, (char*)sqlite3OpcodeName(pOp->opcode),
+ -1, SQLITE_UTF8, SQLITE_STATIC);
+ sqlite3VdbeMemSetInt64(pMem+2, pOp->p1);
+ sqlite3VdbeMemSetInt64(pMem+3, pOp->p2);
+ sqlite3VdbeMemSetInt64(pMem+4, pOp->p3);
+ /* pMem+5 for p4 is done last */
+ sqlite3VdbeMemSetInt64(pMem+6, pOp->p5);
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+ {
+ char *zCom = sqlite3VdbeDisplayComment(db, pOp, zP4);
+ sqlite3VdbeMemSetStr(pMem+7, zCom, -1, SQLITE_UTF8, sqlite3_free);
+ }
+#else
+ sqlite3VdbeMemSetNull(pMem+7);
+#endif
+ sqlite3VdbeMemSetStr(pMem+5, zP4, -1, SQLITE_UTF8, sqlite3_free);
+ p->nResColumn = 8;
+ }
+ p->pResultSet = pMem;
+ if( db->mallocFailed ){
+ p->rc = SQLITE_NOMEM;
+ rc = SQLITE_ERROR;
+ }else{
+ p->rc = SQLITE_OK;
+ rc = SQLITE_ROW;
+ }
+ }
+ }
+ return rc;
+}
+#endif /* SQLITE_OMIT_EXPLAIN */
+
+#ifdef SQLITE_DEBUG
+/*
+** Print the SQL that was used to generate a VDBE program.
+*/
+SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
+ const char *z = 0;
+ if( p->zSql ){
+ z = p->zSql;
+ }else if( p->nOp>=1 ){
+ const VdbeOp *pOp = &p->aOp[0];
+ if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
+ z = pOp->p4.z;
+ while( sqlite3Isspace(*z) ) z++;
+ }
+ }
+ if( z ) printf("SQL: [%s]\n", z);
+}
+#endif
+
+#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
+/*
+** Print an IOTRACE message showing SQL content.
+*/
+SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
+ int nOp = p->nOp;
+ VdbeOp *pOp;
+ if( sqlite3IoTrace==0 ) return;
+ if( nOp<1 ) return;
+ pOp = &p->aOp[0];
+ if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
+ int i, j;
+ char z[1000];
+ sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
+ for(i=0; sqlite3Isspace(z[i]); i++){}
+ for(j=0; z[i]; i++){
+ if( sqlite3Isspace(z[i]) ){
+ if( z[i-1]!=' ' ){
+ z[j++] = ' ';
+ }
+ }else{
+ z[j++] = z[i];
+ }
+ }
+ z[j] = 0;
+ sqlite3IoTrace("SQL %s\n", z);
+ }
+}
+#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
+
+/* An instance of this object describes bulk memory available for use
+** by subcomponents of a prepared statement. Space is allocated out
+** of a ReusableSpace object by the allocSpace() routine below.
+*/
+struct ReusableSpace {
+ u8 *pSpace; /* Available memory */
+ sqlite3_int64 nFree; /* Bytes of available memory */
+ sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */
+};
+
+/* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
+** from the ReusableSpace object. Return a pointer to the allocated
+** memory on success. If insufficient memory is available in the
+** ReusableSpace object, increase the ReusableSpace.nNeeded
+** value by the amount needed and return NULL.
+**
+** If pBuf is not initially NULL, that means that the memory has already
+** been allocated by a prior call to this routine, so just return a copy
+** of pBuf and leave ReusableSpace unchanged.
+**
+** This allocator is employed to repurpose unused slots at the end of the
+** opcode array of prepared state for other memory needs of the prepared
+** statement.
+*/
+static void *allocSpace(
+ struct ReusableSpace *p, /* Bulk memory available for allocation */
+ void *pBuf, /* Pointer to a prior allocation */
+ sqlite3_int64 nByte /* Bytes of memory needed */
+){
+ assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
+ if( pBuf==0 ){
+ nByte = ROUND8(nByte);
+ if( nByte <= p->nFree ){
+ p->nFree -= nByte;
+ pBuf = &p->pSpace[p->nFree];
+ }else{
+ p->nNeeded += nByte;
+ }
+ }
+ assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
+ return pBuf;
+}
+
+/*
+** Rewind the VDBE back to the beginning in preparation for
+** running it.
+*/
+SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
+#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
+ int i;
+#endif
+ assert( p!=0 );
+ assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
+
+ /* There should be at least one opcode.
+ */
+ assert( p->nOp>0 );
+
+ /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
+ p->magic = VDBE_MAGIC_RUN;
+
+#ifdef SQLITE_DEBUG
+ for(i=0; i<p->nMem; i++){
+ assert( p->aMem[i].db==p->db );
+ }
+#endif
+ p->pc = -1;
+ p->rc = SQLITE_OK;
+ p->errorAction = OE_Abort;
+ p->nChange = 0;
+ p->cacheCtr = 1;
+ p->minWriteFileFormat = 255;
+ p->iStatement = 0;
+ p->nFkConstraint = 0;
+#ifdef VDBE_PROFILE
+ for(i=0; i<p->nOp; i++){
+ p->aOp[i].cnt = 0;
+ p->aOp[i].cycles = 0;
+ }
+#endif
+}
+
+/*
+** Prepare a virtual machine for execution for the first time after
+** creating the virtual machine. This involves things such
+** as allocating registers and initializing the program counter.
+** After the VDBE has be prepped, it can be executed by one or more
+** calls to sqlite3VdbeExec().
+**
+** This function may be called exactly once on each virtual machine.
+** After this routine is called the VM has been "packaged" and is ready
+** to run. After this routine is called, further calls to
+** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
+** the Vdbe from the Parse object that helped generate it so that the
+** the Vdbe becomes an independent entity and the Parse object can be
+** destroyed.
+**
+** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
+** to its initial state after it has been run.
+*/
+SQLITE_PRIVATE void sqlite3VdbeMakeReady(
+ Vdbe *p, /* The VDBE */
+ Parse *pParse /* Parsing context */
+){
+ sqlite3 *db; /* The database connection */
+ int nVar; /* Number of parameters */
+ int nMem; /* Number of VM memory registers */
+ int nCursor; /* Number of cursors required */
+ int nArg; /* Number of arguments in subprograms */
+ int n; /* Loop counter */
+ struct ReusableSpace x; /* Reusable bulk memory */
+
+ assert( p!=0 );
+ assert( p->nOp>0 );
+ assert( pParse!=0 );
+ assert( p->magic==VDBE_MAGIC_INIT );
+ assert( pParse==p->pParse );
+ db = p->db;
+ assert( db->mallocFailed==0 );
+ nVar = pParse->nVar;
+ nMem = pParse->nMem;
+ nCursor = pParse->nTab;
+ nArg = pParse->nMaxArg;
+
+ /* Each cursor uses a memory cell. The first cursor (cursor 0) can
+ ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
+ ** space at the end of aMem[] for cursors 1 and greater.
+ ** See also: allocateCursor().
+ */
+ nMem += nCursor;
+ if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
+
+ /* Figure out how much reusable memory is available at the end of the
+ ** opcode array. This extra memory will be reallocated for other elements
+ ** of the prepared statement.
+ */
+ n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
+ x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
+ assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
+ x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
+ assert( x.nFree>=0 );
+ assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
+
+ resolveP2Values(p, &nArg);
+ p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
+ if( pParse->explain ){
+ static const char * const azColName[] = {
+ "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
+ "id", "parent", "notused", "detail"
+ };
+ int iFirst, mx, i;
+ if( nMem<10 ) nMem = 10;
+ p->explain = pParse->explain;
+ if( pParse->explain==2 ){
+ sqlite3VdbeSetNumCols(p, 4);
+ iFirst = 8;
+ mx = 12;
+ }else{
+ sqlite3VdbeSetNumCols(p, 8);
+ iFirst = 0;
+ mx = 8;
+ }
+ for(i=iFirst; i<mx; i++){
+ sqlite3VdbeSetColName(p, i-iFirst, COLNAME_NAME,
+ azColName[i], SQLITE_STATIC);
+ }
+ }
+ p->expired = 0;
+
+ /* Memory for registers, parameters, cursor, etc, is allocated in one or two
+ ** passes. On the first pass, we try to reuse unused memory at the
+ ** end of the opcode array. If we are unable to satisfy all memory
+ ** requirements by reusing the opcode array tail, then the second
+ ** pass will fill in the remainder using a fresh memory allocation.
+ **
+ ** This two-pass approach that reuses as much memory as possible from
+ ** the leftover memory at the end of the opcode array. This can significantly
+ ** reduce the amount of memory held by a prepared statement.
+ */
+ x.nNeeded = 0;
+ p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));
+ p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));
+ p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));
+ p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+ p->anExec = allocSpace(&x, 0, p->nOp*sizeof(i64));
+#endif
+ if( x.nNeeded ){
+ x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
+ x.nFree = x.nNeeded;
+ if( !db->mallocFailed ){
+ p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
+ p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
+ p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
+ p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+ p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
+#endif
+ }
+ }
+
+ p->pVList = pParse->pVList;
+ pParse->pVList = 0;
+ if( db->mallocFailed ){
+ p->nVar = 0;
+ p->nCursor = 0;
+ p->nMem = 0;
+ }else{
+ p->nCursor = nCursor;
+ p->nVar = (ynVar)nVar;
+ initMemArray(p->aVar, nVar, db, MEM_Null);
+ p->nMem = nMem;
+ initMemArray(p->aMem, nMem, db, MEM_Undefined);
+ memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+ memset(p->anExec, 0, p->nOp*sizeof(i64));
+#endif
+ }
+ sqlite3VdbeRewind(p);
+}
+
+/*
+** Close a VDBE cursor and release all the resources that cursor
+** happens to hold.
+*/
+SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
+ if( pCx==0 ){
+ return;
+ }
+ assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
+ switch( pCx->eCurType ){
+ case CURTYPE_SORTER: {
+ sqlite3VdbeSorterClose(p->db, pCx);
+ break;
+ }
+ case CURTYPE_BTREE: {
+ if( pCx->isEphemeral ){
+ if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
+ /* The pCx->pCursor will be close automatically, if it exists, by
+ ** the call above. */
+ }else{
+ assert( pCx->uc.pCursor!=0 );
+ sqlite3BtreeCloseCursor(pCx->uc.pCursor);
+ }
+ break;
+ }
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ case CURTYPE_VTAB: {
+ sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
+ const sqlite3_module *pModule = pVCur->pVtab->pModule;
+ assert( pVCur->pVtab->nRef>0 );
+ pVCur->pVtab->nRef--;
+ pModule->xClose(pVCur);
+ break;
+ }
+#endif
+ }
+}
+
+/*
+** Close all cursors in the current frame.
+*/
+static void closeCursorsInFrame(Vdbe *p){
+ if( p->apCsr ){
+ int i;
+ for(i=0; i<p->nCursor; i++){
+ VdbeCursor *pC = p->apCsr[i];
+ if( pC ){
+ sqlite3VdbeFreeCursor(p, pC);
+ p->apCsr[i] = 0;
+ }
+ }
+ }
+}
+
+/*
+** Copy the values stored in the VdbeFrame structure to its Vdbe. This
+** is used, for example, when a trigger sub-program is halted to restore
+** control to the main program.
+*/
+SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
+ Vdbe *v = pFrame->v;
+ closeCursorsInFrame(v);
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+ v->anExec = pFrame->anExec;
+#endif
+ v->aOp = pFrame->aOp;
+ v->nOp = pFrame->nOp;
+ v->aMem = pFrame->aMem;
+ v->nMem = pFrame->nMem;
+ v->apCsr = pFrame->apCsr;
+ v->nCursor = pFrame->nCursor;
+ v->db->lastRowid = pFrame->lastRowid;
+ v->nChange = pFrame->nChange;
+ v->db->nChange = pFrame->nDbChange;
+ sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
+ v->pAuxData = pFrame->pAuxData;
+ pFrame->pAuxData = 0;
+ return pFrame->pc;
+}
+
+/*
+** Close all cursors.
+**
+** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
+** cell array. This is necessary as the memory cell array may contain
+** pointers to VdbeFrame objects, which may in turn contain pointers to
+** open cursors.
+*/
+static void closeAllCursors(Vdbe *p){
+ if( p->pFrame ){
+ VdbeFrame *pFrame;
+ for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
+ sqlite3VdbeFrameRestore(pFrame);
+ p->pFrame = 0;
+ p->nFrame = 0;
+ }
+ assert( p->nFrame==0 );
+ closeCursorsInFrame(p);
+ if( p->aMem ){
+ releaseMemArray(p->aMem, p->nMem);
+ }
+ while( p->pDelFrame ){
+ VdbeFrame *pDel = p->pDelFrame;
+ p->pDelFrame = pDel->pParent;
+ sqlite3VdbeFrameDelete(pDel);
+ }
+
+ /* Delete any auxdata allocations made by the VM */
+ if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
+ assert( p->pAuxData==0 );
+}
+
+/*
+** Set the number of result columns that will be returned by this SQL
+** statement. This is now set at compile time, rather than during
+** execution of the vdbe program so that sqlite3_column_count() can
+** be called on an SQL statement before sqlite3_step().
+*/
+SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
+ int n;
+ sqlite3 *db = p->db;
+
+ if( p->nResColumn ){
+ releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
+ sqlite3DbFree(db, p->aColName);
+ }
+ n = nResColumn*COLNAME_N;
+ p->nResColumn = (u16)nResColumn;
+ p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
+ if( p->aColName==0 ) return;
+ initMemArray(p->aColName, n, db, MEM_Null);
+}
+
+/*
+** Set the name of the idx'th column to be returned by the SQL statement.
+** zName must be a pointer to a nul terminated string.
+**
+** This call must be made after a call to sqlite3VdbeSetNumCols().
+**
+** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
+** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
+** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
+*/
+SQLITE_PRIVATE int sqlite3VdbeSetColName(
+ Vdbe *p, /* Vdbe being configured */
+ int idx, /* Index of column zName applies to */
+ int var, /* One of the COLNAME_* constants */
+ const char *zName, /* Pointer to buffer containing name */
+ void (*xDel)(void*) /* Memory management strategy for zName */
+){
+ int rc;
+ Mem *pColName;
+ assert( idx<p->nResColumn );
+ assert( var<COLNAME_N );
+ if( p->db->mallocFailed ){
+ assert( !zName || xDel!=SQLITE_DYNAMIC );
+ return SQLITE_NOMEM_BKPT;
+ }
+ assert( p->aColName!=0 );
+ pColName = &(p->aColName[idx+var*p->nResColumn]);
+ rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
+ assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
+ return rc;
+}
+
+/*
+** A read or write transaction may or may not be active on database handle
+** db. If a transaction is active, commit it. If there is a
+** write-transaction spanning more than one database file, this routine
+** takes care of the super-journal trickery.
+*/
+static int vdbeCommit(sqlite3 *db, Vdbe *p){
+ int i;
+ int nTrans = 0; /* Number of databases with an active write-transaction
+ ** that are candidates for a two-phase commit using a
+ ** super-journal */
+ int rc = SQLITE_OK;
+ int needXcommit = 0;
+
+#ifdef SQLITE_OMIT_VIRTUALTABLE
+ /* With this option, sqlite3VtabSync() is defined to be simply
+ ** SQLITE_OK so p is not used.
+ */
+ UNUSED_PARAMETER(p);
+#endif
+
+ /* Before doing anything else, call the xSync() callback for any
+ ** virtual module tables written in this transaction. This has to
+ ** be done before determining whether a super-journal file is
+ ** required, as an xSync() callback may add an attached database
+ ** to the transaction.
+ */
+ rc = sqlite3VtabSync(db, p);
+
+ /* This loop determines (a) if the commit hook should be invoked and
+ ** (b) how many database files have open write transactions, not
+ ** including the temp database. (b) is important because if more than
+ ** one database file has an open write transaction, a super-journal
+ ** file is required for an atomic commit.
+ */
+ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
+ Btree *pBt = db->aDb[i].pBt;
+ if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
+ /* Whether or not a database might need a super-journal depends upon
+ ** its journal mode (among other things). This matrix determines which
+ ** journal modes use a super-journal and which do not */
+ static const u8 aMJNeeded[] = {
+ /* DELETE */ 1,
+ /* PERSIST */ 1,
+ /* OFF */ 0,
+ /* TRUNCATE */ 1,
+ /* MEMORY */ 0,
+ /* WAL */ 0
+ };
+ Pager *pPager; /* Pager associated with pBt */
+ needXcommit = 1;
+ sqlite3BtreeEnter(pBt);
+ pPager = sqlite3BtreePager(pBt);
+ if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
+ && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
+ && sqlite3PagerIsMemdb(pPager)==0
+ ){
+ assert( i!=1 );
+ nTrans++;
+ }
+ rc = sqlite3PagerExclusiveLock(pPager);
+ sqlite3BtreeLeave(pBt);
+ }
+ }
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+
+ /* If there are any write-transactions at all, invoke the commit hook */
+ if( needXcommit && db->xCommitCallback ){
+ rc = db->xCommitCallback(db->pCommitArg);
+ if( rc ){
+ return SQLITE_CONSTRAINT_COMMITHOOK;
+ }
+ }
+
+ /* The simple case - no more than one database file (not counting the
+ ** TEMP database) has a transaction active. There is no need for the
+ ** super-journal.
+ **
+ ** If the return value of sqlite3BtreeGetFilename() is a zero length
+ ** string, it means the main database is :memory: or a temp file. In
+ ** that case we do not support atomic multi-file commits, so use the
+ ** simple case then too.
+ */
+ if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
+ || nTrans<=1
+ ){
+ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
+ Btree *pBt = db->aDb[i].pBt;
+ if( pBt ){
+ rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
+ }
+ }
+
+ /* Do the commit only if all databases successfully complete phase 1.
+ ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
+ ** IO error while deleting or truncating a journal file. It is unlikely,
+ ** but could happen. In this case abandon processing and return the error.
+ */
+ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
+ Btree *pBt = db->aDb[i].pBt;
+ if( pBt ){
+ rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
+ }
+ }
+ if( rc==SQLITE_OK ){
+ sqlite3VtabCommit(db);
+ }
+ }
+
+ /* The complex case - There is a multi-file write-transaction active.
+ ** This requires a super-journal file to ensure the transaction is
+ ** committed atomically.
+ */
+#ifndef SQLITE_OMIT_DISKIO
+ else{
+ sqlite3_vfs *pVfs = db->pVfs;
+ char *zSuper = 0; /* File-name for the super-journal */
+ char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
+ sqlite3_file *pSuperJrnl = 0;
+ i64 offset = 0;
+ int res;
+ int retryCount = 0;
+ int nMainFile;
+
+ /* Select a super-journal file name */
+ nMainFile = sqlite3Strlen30(zMainFile);
+ zSuper = sqlite3MPrintf(db, "%.4c%s%.16c", 0,zMainFile,0);
+ if( zSuper==0 ) return SQLITE_NOMEM_BKPT;
+ zSuper += 4;
+ do {
+ u32 iRandom;
+ if( retryCount ){
+ if( retryCount>100 ){
+ sqlite3_log(SQLITE_FULL, "MJ delete: %s", zSuper);
+ sqlite3OsDelete(pVfs, zSuper, 0);
+ break;
+ }else if( retryCount==1 ){
+ sqlite3_log(SQLITE_FULL, "MJ collide: %s", zSuper);
+ }
+ }
+ retryCount++;
+ sqlite3_randomness(sizeof(iRandom), &iRandom);
+ sqlite3_snprintf(13, &zSuper[nMainFile], "-mj%06X9%02X",
+ (iRandom>>8)&0xffffff, iRandom&0xff);
+ /* The antipenultimate character of the super-journal name must
+ ** be "9" to avoid name collisions when using 8+3 filenames. */
+ assert( zSuper[sqlite3Strlen30(zSuper)-3]=='9' );
+ sqlite3FileSuffix3(zMainFile, zSuper);
+ rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);
+ }while( rc==SQLITE_OK && res );
+ if( rc==SQLITE_OK ){
+ /* Open the super-journal. */
+ rc = sqlite3OsOpenMalloc(pVfs, zSuper, &pSuperJrnl,
+ SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
+ SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_SUPER_JOURNAL, 0
+ );
+ }
+ if( rc!=SQLITE_OK ){
+ sqlite3DbFree(db, zSuper-4);
+ return rc;
+ }
+
+ /* Write the name of each database file in the transaction into the new
+ ** super-journal file. If an error occurs at this point close
+ ** and delete the super-journal file. All the individual journal files
+ ** still have 'null' as the super-journal pointer, so they will roll
+ ** back independently if a failure occurs.
+ */
+ for(i=0; i<db->nDb; i++){
+ Btree *pBt = db->aDb[i].pBt;
+ if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
+ char const *zFile = sqlite3BtreeGetJournalname(pBt);
+ if( zFile==0 ){
+ continue; /* Ignore TEMP and :memory: databases */
+ }
+ assert( zFile[0]!=0 );
+ rc = sqlite3OsWrite(pSuperJrnl, zFile, sqlite3Strlen30(zFile)+1,offset);
+ offset += sqlite3Strlen30(zFile)+1;
+ if( rc!=SQLITE_OK ){
+ sqlite3OsCloseFree(pSuperJrnl);
+ sqlite3OsDelete(pVfs, zSuper, 0);
+ sqlite3DbFree(db, zSuper-4);
+ return rc;
+ }
+ }
+ }
+
+ /* Sync the super-journal file. If the IOCAP_SEQUENTIAL device
+ ** flag is set this is not required.
+ */
+ if( 0==(sqlite3OsDeviceCharacteristics(pSuperJrnl)&SQLITE_IOCAP_SEQUENTIAL)
+ && SQLITE_OK!=(rc = sqlite3OsSync(pSuperJrnl, SQLITE_SYNC_NORMAL))
+ ){
+ sqlite3OsCloseFree(pSuperJrnl);
+ sqlite3OsDelete(pVfs, zSuper, 0);
+ sqlite3DbFree(db, zSuper-4);
+ return rc;
+ }
+
+ /* Sync all the db files involved in the transaction. The same call
+ ** sets the super-journal pointer in each individual journal. If
+ ** an error occurs here, do not delete the super-journal file.
+ **
+ ** If the error occurs during the first call to
+ ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
+ ** super-journal file will be orphaned. But we cannot delete it,
+ ** in case the super-journal file name was written into the journal
+ ** file before the failure occurred.
+ */
+ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
+ Btree *pBt = db->aDb[i].pBt;
+ if( pBt ){
+ rc = sqlite3BtreeCommitPhaseOne(pBt, zSuper);
+ }
+ }
+ sqlite3OsCloseFree(pSuperJrnl);
+ assert( rc!=SQLITE_BUSY );
+ if( rc!=SQLITE_OK ){
+ sqlite3DbFree(db, zSuper-4);
+ return rc;
+ }
+
+ /* Delete the super-journal file. This commits the transaction. After
+ ** doing this the directory is synced again before any individual
+ ** transaction files are deleted.
+ */
+ rc = sqlite3OsDelete(pVfs, zSuper, 1);
+ sqlite3DbFree(db, zSuper-4);
+ zSuper = 0;
+ if( rc ){
+ return rc;
+ }
+
+ /* All files and directories have already been synced, so the following
+ ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
+ ** deleting or truncating journals. If something goes wrong while
+ ** this is happening we don't really care. The integrity of the
+ ** transaction is already guaranteed, but some stray 'cold' journals
+ ** may be lying around. Returning an error code won't help matters.
+ */
+ disable_simulated_io_errors();
+ sqlite3BeginBenignMalloc();
+ for(i=0; i<db->nDb; i++){
+ Btree *pBt = db->aDb[i].pBt;
+ if( pBt ){
+ sqlite3BtreeCommitPhaseTwo(pBt, 1);
+ }
+ }
+ sqlite3EndBenignMalloc();
+ enable_simulated_io_errors();
+
+ sqlite3VtabCommit(db);
+ }
+#endif
+
+ return rc;
+}
+
+/*
+** This routine checks that the sqlite3.nVdbeActive count variable
+** matches the number of vdbe's in the list sqlite3.pVdbe that are
+** currently active. An assertion fails if the two counts do not match.
+** This is an internal self-check only - it is not an essential processing
+** step.
+**
+** This is a no-op if NDEBUG is defined.
+*/
+#ifndef NDEBUG
+static void checkActiveVdbeCnt(sqlite3 *db){
+ Vdbe *p;
+ int cnt = 0;
+ int nWrite = 0;
+ int nRead = 0;
+ p = db->pVdbe;
+ while( p ){
+ if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
+ cnt++;
+ if( p->readOnly==0 ) nWrite++;
+ if( p->bIsReader ) nRead++;
+ }
+ p = p->pNext;
+ }
+ assert( cnt==db->nVdbeActive );
+ assert( nWrite==db->nVdbeWrite );
+ assert( nRead==db->nVdbeRead );
+}
+#else
+#define checkActiveVdbeCnt(x)
+#endif
+
+/*
+** If the Vdbe passed as the first argument opened a statement-transaction,
+** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
+** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
+** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
+** statement transaction is committed.
+**
+** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
+** Otherwise SQLITE_OK.
+*/
+static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
+ sqlite3 *const db = p->db;
+ int rc = SQLITE_OK;
+ int i;
+ const int iSavepoint = p->iStatement-1;
+
+ assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
+ assert( db->nStatement>0 );
+ assert( p->iStatement==(db->nStatement+db->nSavepoint) );
+
+ for(i=0; i<db->nDb; i++){
+ int rc2 = SQLITE_OK;
+ Btree *pBt = db->aDb[i].pBt;
+ if( pBt ){
+ if( eOp==SAVEPOINT_ROLLBACK ){
+ rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
+ }
+ if( rc2==SQLITE_OK ){
+ rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
+ }
+ if( rc==SQLITE_OK ){
+ rc = rc2;
+ }
+ }
+ }
+ db->nStatement--;
+ p->iStatement = 0;
+
+ if( rc==SQLITE_OK ){
+ if( eOp==SAVEPOINT_ROLLBACK ){
+ rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
+ }
+ }
+
+ /* If the statement transaction is being rolled back, also restore the
+ ** database handles deferred constraint counter to the value it had when
+ ** the statement transaction was opened. */
+ if( eOp==SAVEPOINT_ROLLBACK ){
+ db->nDeferredCons = p->nStmtDefCons;
+ db->nDeferredImmCons = p->nStmtDefImmCons;
+ }
+ return rc;
+}
+SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
+ if( p->db->nStatement && p->iStatement ){
+ return vdbeCloseStatement(p, eOp);
+ }
+ return SQLITE_OK;
+}
+
+
+/*
+** This function is called when a transaction opened by the database
+** handle associated with the VM passed as an argument is about to be
+** committed. If there are outstanding deferred foreign key constraint
+** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
+**
+** If there are outstanding FK violations and this function returns
+** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
+** and write an error message to it. Then return SQLITE_ERROR.
+*/
+#ifndef SQLITE_OMIT_FOREIGN_KEY
+SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
+ sqlite3 *db = p->db;
+ if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
+ || (!deferred && p->nFkConstraint>0)
+ ){
+ p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
+ p->errorAction = OE_Abort;
+ sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
+ return SQLITE_ERROR;
+ }
+ return SQLITE_OK;
+}
+#endif
+
+/*
+** This routine is called the when a VDBE tries to halt. If the VDBE
+** has made changes and is in autocommit mode, then commit those
+** changes. If a rollback is needed, then do the rollback.
+**
+** This routine is the only way to move the state of a VM from
+** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
+** call this on a VM that is in the SQLITE_MAGIC_HALT state.
+**
+** Return an error code. If the commit could not complete because of
+** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
+** means the close did not happen and needs to be repeated.
+*/
+SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
+ int rc; /* Used to store transient return codes */
+ sqlite3 *db = p->db;
+
+ /* This function contains the logic that determines if a statement or
+ ** transaction will be committed or rolled back as a result of the
+ ** execution of this virtual machine.
+ **
+ ** If any of the following errors occur:
+ **
+ ** SQLITE_NOMEM
+ ** SQLITE_IOERR
+ ** SQLITE_FULL
+ ** SQLITE_INTERRUPT
+ **
+ ** Then the internal cache might have been left in an inconsistent
+ ** state. We need to rollback the statement transaction, if there is
+ ** one, or the complete transaction if there is no statement transaction.
+ */
+
+ if( p->magic!=VDBE_MAGIC_RUN ){
+ return SQLITE_OK;
+ }
+ if( db->mallocFailed ){
+ p->rc = SQLITE_NOMEM_BKPT;
+ }
+ closeAllCursors(p);
+ checkActiveVdbeCnt(db);
+
+ /* No commit or rollback needed if the program never started or if the
+ ** SQL statement does not read or write a database file. */
+ if( p->pc>=0 && p->bIsReader ){
+ int mrc; /* Primary error code from p->rc */
+ int eStatementOp = 0;
+ int isSpecialError; /* Set to true if a 'special' error */
+
+ /* Lock all btrees used by the statement */
+ sqlite3VdbeEnter(p);
+
+ /* Check for one of the special errors */
+ mrc = p->rc & 0xff;
+ isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
+ || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
+ if( isSpecialError ){
+ /* If the query was read-only and the error code is SQLITE_INTERRUPT,
+ ** no rollback is necessary. Otherwise, at least a savepoint
+ ** transaction must be rolled back to restore the database to a
+ ** consistent state.
+ **
+ ** Even if the statement is read-only, it is important to perform
+ ** a statement or transaction rollback operation. If the error
+ ** occurred while writing to the journal, sub-journal or database
+ ** file as part of an effort to free up cache space (see function
+ ** pagerStress() in pager.c), the rollback is required to restore
+ ** the pager to a consistent state.
+ */
+ if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
+ if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
+ eStatementOp = SAVEPOINT_ROLLBACK;
+ }else{
+ /* We are forced to roll back the active transaction. Before doing
+ ** so, abort any other statements this handle currently has active.
+ */
+ sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
+ sqlite3CloseSavepoints(db);
+ db->autoCommit = 1;
+ p->nChange = 0;
+ }
+ }
+ }
+
+ /* Check for immediate foreign key violations. */
+ if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
+ sqlite3VdbeCheckFk(p, 0);
+ }
+
+ /* If the auto-commit flag is set and this is the only active writer
+ ** VM, then we do either a commit or rollback of the current transaction.
+ **
+ ** Note: This block also runs if one of the special errors handled
+ ** above has occurred.
+ */
+ if( !sqlite3VtabInSync(db)
+ && db->autoCommit
+ && db->nVdbeWrite==(p->readOnly==0)
+ ){
+ if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
+ rc = sqlite3VdbeCheckFk(p, 1);
+ if( rc!=SQLITE_OK ){
+ if( NEVER(p->readOnly) ){
+ sqlite3VdbeLeave(p);
+ return SQLITE_ERROR;
+ }
+ rc = SQLITE_CONSTRAINT_FOREIGNKEY;
+ }else{
+ /* The auto-commit flag is true, the vdbe program was successful
+ ** or hit an 'OR FAIL' constraint and there are no deferred foreign
+ ** key constraints to hold up the transaction. This means a commit
+ ** is required. */
+ rc = vdbeCommit(db, p);
+ }
+ if( rc==SQLITE_BUSY && p->readOnly ){
+ sqlite3VdbeLeave(p);
+ return SQLITE_BUSY;
+ }else if( rc!=SQLITE_OK ){
+ p->rc = rc;
+ sqlite3RollbackAll(db, SQLITE_OK);
+ p->nChange = 0;
+ }else{
+ db->nDeferredCons = 0;
+ db->nDeferredImmCons = 0;
+ db->flags &= ~(u64)SQLITE_DeferFKs;
+ sqlite3CommitInternalChanges(db);
+ }
+ }else{
+ sqlite3RollbackAll(db, SQLITE_OK);
+ p->nChange = 0;
+ }
+ db->nStatement = 0;
+ }else if( eStatementOp==0 ){
+ if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
+ eStatementOp = SAVEPOINT_RELEASE;
+ }else if( p->errorAction==OE_Abort ){
+ eStatementOp = SAVEPOINT_ROLLBACK;
+ }else{
+ sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
+ sqlite3CloseSavepoints(db);
+ db->autoCommit = 1;
+ p->nChange = 0;
+ }
+ }
+
+ /* If eStatementOp is non-zero, then a statement transaction needs to
+ ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
+ ** do so. If this operation returns an error, and the current statement
+ ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
+ ** current statement error code.
+ */
+ if( eStatementOp ){
+ rc = sqlite3VdbeCloseStatement(p, eStatementOp);
+ if( rc ){
+ if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
+ p->rc = rc;
+ sqlite3DbFree(db, p->zErrMsg);
+ p->zErrMsg = 0;
+ }
+ sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
+ sqlite3CloseSavepoints(db);
+ db->autoCommit = 1;
+ p->nChange = 0;
+ }
+ }
+
+ /* If this was an INSERT, UPDATE or DELETE and no statement transaction
+ ** has been rolled back, update the database connection change-counter.
+ */
+ if( p->changeCntOn ){
+ if( eStatementOp!=SAVEPOINT_ROLLBACK ){
+ sqlite3VdbeSetChanges(db, p->nChange);
+ }else{
+ sqlite3VdbeSetChanges(db, 0);
+ }
+ p->nChange = 0;
+ }
+
+ /* Release the locks */
+ sqlite3VdbeLeave(p);
+ }
+
+ /* We have successfully halted and closed the VM. Record this fact. */
+ if( p->pc>=0 ){
+ db->nVdbeActive--;
+ if( !p->readOnly ) db->nVdbeWrite--;
+ if( p->bIsReader ) db->nVdbeRead--;
+ assert( db->nVdbeActive>=db->nVdbeRead );
+ assert( db->nVdbeRead>=db->nVdbeWrite );
+ assert( db->nVdbeWrite>=0 );
+ }
+ p->magic = VDBE_MAGIC_HALT;
+ checkActiveVdbeCnt(db);
+ if( db->mallocFailed ){
+ p->rc = SQLITE_NOMEM_BKPT;
+ }
+
+ /* If the auto-commit flag is set to true, then any locks that were held
+ ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
+ ** to invoke any required unlock-notify callbacks.
+ */
+ if( db->autoCommit ){
+ sqlite3ConnectionUnlocked(db);
+ }
+
+ assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
+ return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
+}
+
+
+/*
+** Each VDBE holds the result of the most recent sqlite3_step() call
+** in p->rc. This routine sets that result back to SQLITE_OK.
+*/
+SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
+ p->rc = SQLITE_OK;
+}
+
+/*
+** Copy the error code and error message belonging to the VDBE passed
+** as the first argument to its database handle (so that they will be
+** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
+**
+** This function does not clear the VDBE error code or message, just
+** copies them to the database handle.
+*/
+SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
+ sqlite3 *db = p->db;
+ int rc = p->rc;
+ if( p->zErrMsg ){
+ db->bBenignMalloc++;
+ sqlite3BeginBenignMalloc();
+ if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
+ sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
+ sqlite3EndBenignMalloc();
+ db->bBenignMalloc--;
+ }else if( db->pErr ){
+ sqlite3ValueSetNull(db->pErr);
+ }
+ db->errCode = rc;
+ return rc;
+}
+
+#ifdef SQLITE_ENABLE_SQLLOG
+/*
+** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
+** invoke it.
+*/
+static void vdbeInvokeSqllog(Vdbe *v){
+ if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
+ char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
+ assert( v->db->init.busy==0 );
+ if( zExpanded ){
+ sqlite3GlobalConfig.xSqllog(
+ sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
+ );
+ sqlite3DbFree(v->db, zExpanded);
+ }
+ }
+}
+#else
+# define vdbeInvokeSqllog(x)
+#endif
+
+/*
+** Clean up a VDBE after execution but do not delete the VDBE just yet.
+** Write any error messages into *pzErrMsg. Return the result code.
+**
+** After this routine is run, the VDBE should be ready to be executed
+** again.
+**
+** To look at it another way, this routine resets the state of the
+** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
+** VDBE_MAGIC_INIT.
+*/
+SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
+#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
+ int i;
+#endif
+
+ sqlite3 *db;
+ db = p->db;
+
+ /* If the VM did not run to completion or if it encountered an
+ ** error, then it might not have been halted properly. So halt
+ ** it now.
+ */
+ sqlite3VdbeHalt(p);
+
+ /* If the VDBE has been run even partially, then transfer the error code
+ ** and error message from the VDBE into the main database structure. But
+ ** if the VDBE has just been set to run but has not actually executed any
+ ** instructions yet, leave the main database error information unchanged.
+ */
+ if( p->pc>=0 ){
+ vdbeInvokeSqllog(p);
+ if( db->pErr || p->zErrMsg ){
+ sqlite3VdbeTransferError(p);
+ }else{
+ db->errCode = p->rc;
+ }
+ if( p->runOnlyOnce ) p->expired = 1;
+ }else if( p->rc && p->expired ){
+ /* The expired flag was set on the VDBE before the first call
+ ** to sqlite3_step(). For consistency (since sqlite3_step() was
+ ** called), set the database error in this case as well.
+ */
+ sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
+ }
+
+ /* Reset register contents and reclaim error message memory.
+ */
+#ifdef SQLITE_DEBUG
+ /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
+ ** Vdbe.aMem[] arrays have already been cleaned up. */
+ if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
+ if( p->aMem ){
+ for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
+ }
+#endif
+ if( p->zErrMsg ){
+ sqlite3DbFree(db, p->zErrMsg);
+ p->zErrMsg = 0;
+ }
+ p->pResultSet = 0;
+#ifdef SQLITE_DEBUG
+ p->nWrite = 0;
+#endif
+
+ /* Save profiling information from this VDBE run.
+ */
+#ifdef VDBE_PROFILE
+ {
+ FILE *out = fopen("vdbe_profile.out", "a");
+ if( out ){
+ fprintf(out, "---- ");
+ for(i=0; i<p->nOp; i++){
+ fprintf(out, "%02x", p->aOp[i].opcode);
+ }
+ fprintf(out, "\n");
+ if( p->zSql ){
+ char c, pc = 0;
+ fprintf(out, "-- ");
+ for(i=0; (c = p->zSql[i])!=0; i++){
+ if( pc=='\n' ) fprintf(out, "-- ");
+ putc(c, out);
+ pc = c;
+ }
+ if( pc!='\n' ) fprintf(out, "\n");
+ }
+ for(i=0; i<p->nOp; i++){
+ char zHdr[100];
+ sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
+ p->aOp[i].cnt,
+ p->aOp[i].cycles,
+ p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
+ );
+ fprintf(out, "%s", zHdr);
+ sqlite3VdbePrintOp(out, i, &p->aOp[i]);
+ }
+ fclose(out);
+ }
+ }
+#endif
+ p->magic = VDBE_MAGIC_RESET;
+ return p->rc & db->errMask;
+}
+
+/*
+** Clean up and delete a VDBE after execution. Return an integer which is
+** the result code. Write any error message text into *pzErrMsg.
+*/
+SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
+ int rc = SQLITE_OK;
+ if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
+ rc = sqlite3VdbeReset(p);
+ assert( (rc & p->db->errMask)==rc );
+ }
+ sqlite3VdbeDelete(p);
+ return rc;
+}
+
+/*
+** If parameter iOp is less than zero, then invoke the destructor for
+** all auxiliary data pointers currently cached by the VM passed as
+** the first argument.
+**
+** Or, if iOp is greater than or equal to zero, then the destructor is
+** only invoked for those auxiliary data pointers created by the user
+** function invoked by the OP_Function opcode at instruction iOp of
+** VM pVdbe, and only then if:
+**
+** * the associated function parameter is the 32nd or later (counting
+** from left to right), or
+**
+** * the corresponding bit in argument mask is clear (where the first
+** function parameter corresponds to bit 0 etc.).
+*/
+SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
+ while( *pp ){
+ AuxData *pAux = *pp;
+ if( (iOp<0)
+ || (pAux->iAuxOp==iOp
+ && pAux->iAuxArg>=0
+ && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
+ ){
+ testcase( pAux->iAuxArg==31 );
+ if( pAux->xDeleteAux ){
+ pAux->xDeleteAux(pAux->pAux);
+ }
+ *pp = pAux->pNextAux;
+ sqlite3DbFree(db, pAux);
+ }else{
+ pp= &pAux->pNextAux;
+ }
+ }
+}
+
+/*
+** Free all memory associated with the Vdbe passed as the second argument,
+** except for object itself, which is preserved.
+**
+** The difference between this function and sqlite3VdbeDelete() is that
+** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
+** the database connection and frees the object itself.
+*/
+SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
+ SubProgram *pSub, *pNext;
+ assert( p->db==0 || p->db==db );
+ releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
+ for(pSub=p->pProgram; pSub; pSub=pNext){
+ pNext = pSub->pNext;
+ vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
+ sqlite3DbFree(db, pSub);
+ }
+ if( p->magic!=VDBE_MAGIC_INIT ){
+ releaseMemArray(p->aVar, p->nVar);
+ sqlite3DbFree(db, p->pVList);
+ sqlite3DbFree(db, p->pFree);
+ }
+ vdbeFreeOpArray(db, p->aOp, p->nOp);
+ sqlite3DbFree(db, p->aColName);
+ sqlite3DbFree(db, p->zSql);
+#ifdef SQLITE_ENABLE_NORMALIZE
+ sqlite3DbFree(db, p->zNormSql);
+ {
+ DblquoteStr *pThis, *pNext;
+ for(pThis=p->pDblStr; pThis; pThis=pNext){
+ pNext = pThis->pNextStr;
+ sqlite3DbFree(db, pThis);
+ }
+ }
+#endif
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+ {
+ int i;
+ for(i=0; i<p->nScan; i++){
+ sqlite3DbFree(db, p->aScan[i].zName);
+ }
+ sqlite3DbFree(db, p->aScan);
+ }
+#endif
+}
+
+/*
+** Delete an entire VDBE.
+*/
+SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
+ sqlite3 *db;
+
+ assert( p!=0 );
+ db = p->db;
+ assert( sqlite3_mutex_held(db->mutex) );
+ sqlite3VdbeClearObject(db, p);
+ if( p->pPrev ){
+ p->pPrev->pNext = p->pNext;
+ }else{
+ assert( db->pVdbe==p );
+ db->pVdbe = p->pNext;
+ }
+ if( p->pNext ){
+ p->pNext->pPrev = p->pPrev;
+ }
+ p->magic = VDBE_MAGIC_DEAD;
+ p->db = 0;
+ sqlite3DbFreeNN(db, p);
+}
+
+/*
+** The cursor "p" has a pending seek operation that has not yet been
+** carried out. Seek the cursor now. If an error occurs, return
+** the appropriate error code.
+*/
+SQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor *p){
+ int res, rc;
+#ifdef SQLITE_TEST
+ extern int sqlite3_search_count;
+#endif
+ assert( p->deferredMoveto );
+ assert( p->isTable );
+ assert( p->eCurType==CURTYPE_BTREE );
+ rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
+ if( rc ) return rc;
+ if( res!=0 ) return SQLITE_CORRUPT_BKPT;
+#ifdef SQLITE_TEST
+ sqlite3_search_count++;
+#endif
+ p->deferredMoveto = 0;
+ p->cacheStatus = CACHE_STALE;
+ return SQLITE_OK;
+}
+
+/*
+** Something has moved cursor "p" out of place. Maybe the row it was
+** pointed to was deleted out from under it. Or maybe the btree was
+** rebalanced. Whatever the cause, try to restore "p" to the place it
+** is supposed to be pointing. If the row was deleted out from under the
+** cursor, set the cursor to point to a NULL row.
+*/
+static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
+ int isDifferentRow, rc;
+ assert( p->eCurType==CURTYPE_BTREE );
+ assert( p->uc.pCursor!=0 );
+ assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
+ rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
+ p->cacheStatus = CACHE_STALE;
+ if( isDifferentRow ) p->nullRow = 1;
+ return rc;
+}
+
+/*
+** Check to ensure that the cursor is valid. Restore the cursor
+** if need be. Return any I/O error from the restore operation.
+*/
+SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
+ assert( p->eCurType==CURTYPE_BTREE );
+ if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
+ return handleMovedCursor(p);
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Make sure the cursor p is ready to read or write the row to which it
+** was last positioned. Return an error code if an OOM fault or I/O error
+** prevents us from positioning the cursor to its correct position.
+**
+** If a MoveTo operation is pending on the given cursor, then do that
+** MoveTo now. If no move is pending, check to see if the row has been
+** deleted out from under the cursor and if it has, mark the row as
+** a NULL row.
+**
+** If the cursor is already pointing to the correct row and that row has
+** not been deleted out from under the cursor, then this routine is a no-op.
+*/
+SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, u32 *piCol){
+ VdbeCursor *p = *pp;
+ assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
+ if( p->deferredMoveto ){
+ u32 iMap;
+ if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 && !p->nullRow ){
+ *pp = p->pAltCursor;
+ *piCol = iMap - 1;
+ return SQLITE_OK;
+ }
+ return sqlite3VdbeFinishMoveto(p);
+ }
+ if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
+ return handleMovedCursor(p);
+ }
+ return SQLITE_OK;
+}
+
+/*
+** The following functions:
+**
+** sqlite3VdbeSerialType()
+** sqlite3VdbeSerialTypeLen()
+** sqlite3VdbeSerialLen()
+** sqlite3VdbeSerialPut()
+** sqlite3VdbeSerialGet()
+**
+** encapsulate the code that serializes values for storage in SQLite
+** data and index records. Each serialized value consists of a
+** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
+** integer, stored as a varint.
+**
+** In an SQLite index record, the serial type is stored directly before
+** the blob of data that it corresponds to. In a table record, all serial
+** types are stored at the start of the record, and the blobs of data at
+** the end. Hence these functions allow the caller to handle the
+** serial-type and data blob separately.
+**
+** The following table describes the various storage classes for data:
+**
+** serial type bytes of data type
+** -------------- --------------- ---------------
+** 0 0 NULL
+** 1 1 signed integer
+** 2 2 signed integer
+** 3 3 signed integer
+** 4 4 signed integer
+** 5 6 signed integer
+** 6 8 signed integer
+** 7 8 IEEE float
+** 8 0 Integer constant 0
+** 9 0 Integer constant 1
+** 10,11 reserved for expansion
+** N>=12 and even (N-12)/2 BLOB
+** N>=13 and odd (N-13)/2 text
+**
+** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
+** of SQLite will not understand those serial types.
+*/
+
+#if 0 /* Inlined into the OP_MakeRecord opcode */
+/*
+** Return the serial-type for the value stored in pMem.
+**
+** This routine might convert a large MEM_IntReal value into MEM_Real.
+**
+** 2019-07-11: The primary user of this subroutine was the OP_MakeRecord
+** opcode in the byte-code engine. But by moving this routine in-line, we
+** can omit some redundant tests and make that opcode a lot faster. So
+** this routine is now only used by the STAT3 logic and STAT3 support has
+** ended. The code is kept here for historical reference only.
+*/
+SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
+ int flags = pMem->flags;
+ u32 n;
+
+ assert( pLen!=0 );
+ if( flags&MEM_Null ){
+ *pLen = 0;
+ return 0;
+ }
+ if( flags&(MEM_Int|MEM_IntReal) ){
+ /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
+# define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
+ i64 i = pMem->u.i;
+ u64 u;
+ testcase( flags & MEM_Int );
+ testcase( flags & MEM_IntReal );
+ if( i<0 ){
+ u = ~i;
+ }else{
+ u = i;
+ }
+ if( u<=127 ){
+ if( (i&1)==i && file_format>=4 ){
+ *pLen = 0;
+ return 8+(u32)u;
+ }else{
+ *pLen = 1;
+ return 1;
+ }
+ }
+ if( u<=32767 ){ *pLen = 2; return 2; }
+ if( u<=8388607 ){ *pLen = 3; return 3; }
+ if( u<=2147483647 ){ *pLen = 4; return 4; }
+ if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
+ *pLen = 8;
+ if( flags&MEM_IntReal ){
+ /* If the value is IntReal and is going to take up 8 bytes to store
+ ** as an integer, then we might as well make it an 8-byte floating
+ ** point value */
+ pMem->u.r = (double)pMem->u.i;
+ pMem->flags &= ~MEM_IntReal;
+ pMem->flags |= MEM_Real;
+ return 7;
+ }
+ return 6;
+ }
+ if( flags&MEM_Real ){
+ *pLen = 8;
+ return 7;
+ }
+ assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
+ assert( pMem->n>=0 );
+ n = (u32)pMem->n;
+ if( flags & MEM_Zero ){
+ n += pMem->u.nZero;
+ }
+ *pLen = n;
+ return ((n*2) + 12 + ((flags&MEM_Str)!=0));
+}
+#endif /* inlined into OP_MakeRecord */
+
+/*
+** The sizes for serial types less than 128
+*/
+static const u8 sqlite3SmallTypeSizes[] = {
+ /* 0 1 2 3 4 5 6 7 8 9 */
+/* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
+/* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
+/* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
+/* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
+/* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
+/* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
+/* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
+/* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
+/* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
+/* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
+/* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
+/* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
+/* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
+};
+
+/*
+** Return the length of the data corresponding to the supplied serial-type.
+*/
+SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
+ if( serial_type>=128 ){
+ return (serial_type-12)/2;
+ }else{
+ assert( serial_type<12
+ || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
+ return sqlite3SmallTypeSizes[serial_type];
+ }
+}
+SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
+ assert( serial_type<128 );
+ return sqlite3SmallTypeSizes[serial_type];
+}
+
+/*
+** If we are on an architecture with mixed-endian floating
+** points (ex: ARM7) then swap the lower 4 bytes with the
+** upper 4 bytes. Return the result.
+**
+** For most architectures, this is a no-op.
+**
+** (later): It is reported to me that the mixed-endian problem
+** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
+** that early versions of GCC stored the two words of a 64-bit
+** float in the wrong order. And that error has been propagated
+** ever since. The blame is not necessarily with GCC, though.
+** GCC might have just copying the problem from a prior compiler.
+** I am also told that newer versions of GCC that follow a different
+** ABI get the byte order right.
+**
+** Developers using SQLite on an ARM7 should compile and run their
+** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
+** enabled, some asserts below will ensure that the byte order of
+** floating point values is correct.
+**
+** (2007-08-30) Frank van Vugt has studied this problem closely
+** and has send his findings to the SQLite developers. Frank
+** writes that some Linux kernels offer floating point hardware
+** emulation that uses only 32-bit mantissas instead of a full
+** 48-bits as required by the IEEE standard. (This is the
+** CONFIG_FPE_FASTFPE option.) On such systems, floating point
+** byte swapping becomes very complicated. To avoid problems,
+** the necessary byte swapping is carried out using a 64-bit integer
+** rather than a 64-bit float. Frank assures us that the code here
+** works for him. We, the developers, have no way to independently
+** verify this, but Frank seems to know what he is talking about
+** so we trust him.
+*/
+#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
+static u64 floatSwap(u64 in){
+ union {
+ u64 r;
+ u32 i[2];
+ } u;
+ u32 t;
+
+ u.r = in;
+ t = u.i[0];
+ u.i[0] = u.i[1];
+ u.i[1] = t;
+ return u.r;
+}
+# define swapMixedEndianFloat(X) X = floatSwap(X)
+#else
+# define swapMixedEndianFloat(X)
+#endif
+
+/*
+** Write the serialized data blob for the value stored in pMem into
+** buf. It is assumed that the caller has allocated sufficient space.
+** Return the number of bytes written.
+**
+** nBuf is the amount of space left in buf[]. The caller is responsible
+** for allocating enough space to buf[] to hold the entire field, exclusive
+** of the pMem->u.nZero bytes for a MEM_Zero value.
+**
+** Return the number of bytes actually written into buf[]. The number
+** of bytes in the zero-filled tail is included in the return value only
+** if those bytes were zeroed in buf[].
+*/
+SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
+ u32 len;
+
+ /* Integer and Real */
+ if( serial_type<=7 && serial_type>0 ){
+ u64 v;
+ u32 i;
+ if( serial_type==7 ){
+ assert( sizeof(v)==sizeof(pMem->u.r) );
+ memcpy(&v, &pMem->u.r, sizeof(v));
+ swapMixedEndianFloat(v);
+ }else{
+ v = pMem->u.i;
+ }
+ len = i = sqlite3SmallTypeSizes[serial_type];
+ assert( i>0 );
+ do{
+ buf[--i] = (u8)(v&0xFF);
+ v >>= 8;
+ }while( i );
+ return len;
+ }
+
+ /* String or blob */
+ if( serial_type>=12 ){
+ assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
+ == (int)sqlite3VdbeSerialTypeLen(serial_type) );
+ len = pMem->n;
+ if( len>0 ) memcpy(buf, pMem->z, len);
+ return len;
+ }
+
+ /* NULL or constants 0 or 1 */
+ return 0;
+}
+
+/* Input "x" is a sequence of unsigned characters that represent a
+** big-endian integer. Return the equivalent native integer
+*/
+#define ONE_BYTE_INT(x) ((i8)(x)[0])
+#define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
+#define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
+#define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
+#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
+
+/*
+** Deserialize the data blob pointed to by buf as serial type serial_type
+** and store the result in pMem. Return the number of bytes read.
+**
+** This function is implemented as two separate routines for performance.
+** The few cases that require local variables are broken out into a separate
+** routine so that in most cases the overhead of moving the stack pointer
+** is avoided.
+*/
+static u32 serialGet(
+ const unsigned char *buf, /* Buffer to deserialize from */
+ u32 serial_type, /* Serial type to deserialize */
+ Mem *pMem /* Memory cell to write value into */
+){
+ u64 x = FOUR_BYTE_UINT(buf);
+ u32 y = FOUR_BYTE_UINT(buf+4);
+ x = (x<<32) + y;
+ if( serial_type==6 ){
+ /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
+ ** twos-complement integer. */
+ pMem->u.i = *(i64*)&x;
+ pMem->flags = MEM_Int;
+ testcase( pMem->u.i<0 );
+ }else{
+ /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
+ ** floating point number. */
+#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
+ /* Verify that integers and floating point values use the same
+ ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
+ ** defined that 64-bit floating point values really are mixed
+ ** endian.
+ */
+ static const u64 t1 = ((u64)0x3ff00000)<<32;
+ static const double r1 = 1.0;
+ u64 t2 = t1;
+ swapMixedEndianFloat(t2);
+ assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
+#endif
+ assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
+ swapMixedEndianFloat(x);
+ memcpy(&pMem->u.r, &x, sizeof(x));
+ pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real;
+ }
+ return 8;
+}
+SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
+ const unsigned char *buf, /* Buffer to deserialize from */
+ u32 serial_type, /* Serial type to deserialize */
+ Mem *pMem /* Memory cell to write value into */
+){
+ switch( serial_type ){
+ case 10: { /* Internal use only: NULL with virtual table
+ ** UPDATE no-change flag set */
+ pMem->flags = MEM_Null|MEM_Zero;
+ pMem->n = 0;
+ pMem->u.nZero = 0;
+ break;
+ }
+ case 11: /* Reserved for future use */
+ case 0: { /* Null */
+ /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
+ pMem->flags = MEM_Null;
+ break;
+ }
+ case 1: {
+ /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
+ ** integer. */
+ pMem->u.i = ONE_BYTE_INT(buf);
+ pMem->flags = MEM_Int;
+ testcase( pMem->u.i<0 );
+ return 1;
+ }
+ case 2: { /* 2-byte signed integer */
+ /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
+ ** twos-complement integer. */
+ pMem->u.i = TWO_BYTE_INT(buf);
+ pMem->flags = MEM_Int;
+ testcase( pMem->u.i<0 );
+ return 2;
+ }
+ case 3: { /* 3-byte signed integer */
+ /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
+ ** twos-complement integer. */
+ pMem->u.i = THREE_BYTE_INT(buf);
+ pMem->flags = MEM_Int;
+ testcase( pMem->u.i<0 );
+ return 3;
+ }
+ case 4: { /* 4-byte signed integer */
+ /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
+ ** twos-complement integer. */
+ pMem->u.i = FOUR_BYTE_INT(buf);
+#ifdef __HP_cc
+ /* Work around a sign-extension bug in the HP compiler for HP/UX */
+ if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
+#endif
+ pMem->flags = MEM_Int;
+ testcase( pMem->u.i<0 );
+ return 4;
+ }
+ case 5: { /* 6-byte signed integer */
+ /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
+ ** twos-complement integer. */
+ pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
+ pMem->flags = MEM_Int;
+ testcase( pMem->u.i<0 );
+ return 6;
+ }
+ case 6: /* 8-byte signed integer */
+ case 7: { /* IEEE floating point */
+ /* These use local variables, so do them in a separate routine
+ ** to avoid having to move the frame pointer in the common case */
+ return serialGet(buf,serial_type,pMem);
+ }
+ case 8: /* Integer 0 */
+ case 9: { /* Integer 1 */
+ /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
+ /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
+ pMem->u.i = serial_type-8;
+ pMem->flags = MEM_Int;
+ return 0;
+ }
+ default: {
+ /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
+ ** length.
+ ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
+ ** (N-13)/2 bytes in length. */
+ static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
+ pMem->z = (char *)buf;
+ pMem->n = (serial_type-12)/2;
+ pMem->flags = aFlag[serial_type&1];
+ return pMem->n;
+ }
+ }
+ return 0;
+}
+/*
+** This routine is used to allocate sufficient space for an UnpackedRecord
+** structure large enough to be used with sqlite3VdbeRecordUnpack() if
+** the first argument is a pointer to KeyInfo structure pKeyInfo.
+**
+** The space is either allocated using sqlite3DbMallocRaw() or from within
+** the unaligned buffer passed via the second and third arguments (presumably
+** stack space). If the former, then *ppFree is set to a pointer that should
+** be eventually freed by the caller using sqlite3DbFree(). Or, if the
+** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
+** before returning.
+**
+** If an OOM error occurs, NULL is returned.
+*/
+SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
+ KeyInfo *pKeyInfo /* Description of the record */
+){
+ UnpackedRecord *p; /* Unpacked record to return */
+ int nByte; /* Number of bytes required for *p */
+ nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
+ p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
+ if( !p ) return 0;
+ p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
+ assert( pKeyInfo->aSortFlags!=0 );
+ p->pKeyInfo = pKeyInfo;
+ p->nField = pKeyInfo->nKeyField + 1;
+ return p;
+}
+
+/*
+** Given the nKey-byte encoding of a record in pKey[], populate the
+** UnpackedRecord structure indicated by the fourth argument with the
+** contents of the decoded record.
+*/
+SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
+ KeyInfo *pKeyInfo, /* Information about the record format */
+ int nKey, /* Size of the binary record */
+ const void *pKey, /* The binary record */
+ UnpackedRecord *p /* Populate this structure before returning. */
+){
+ const unsigned char *aKey = (const unsigned char *)pKey;
+ u32 d;
+ u32 idx; /* Offset in aKey[] to read from */
+ u16 u; /* Unsigned loop counter */
+ u32 szHdr;
+ Mem *pMem = p->aMem;
+
+ p->default_rc = 0;
+ assert( EIGHT_BYTE_ALIGNMENT(pMem) );
+ idx = getVarint32(aKey, szHdr);
+ d = szHdr;
+ u = 0;
+ while( idx<szHdr && d<=(u32)nKey ){
+ u32 serial_type;
+
+ idx += getVarint32(&aKey[idx], serial_type);
+ pMem->enc = pKeyInfo->enc;
+ pMem->db = pKeyInfo->db;
+ /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
+ pMem->szMalloc = 0;
+ pMem->z = 0;
+ d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
+ pMem++;
+ if( (++u)>=p->nField ) break;
+ }
+ if( d>(u32)nKey && u ){
+ assert( CORRUPT_DB );
+ /* In a corrupt record entry, the last pMem might have been set up using
+ ** uninitialized memory. Overwrite its value with NULL, to prevent
+ ** warnings from MSAN. */
+ sqlite3VdbeMemSetNull(pMem-1);
+ }
+ assert( u<=pKeyInfo->nKeyField + 1 );
+ p->nField = u;
+}
+
+#ifdef SQLITE_DEBUG
+/*
+** This function compares two index or table record keys in the same way
+** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
+** this function deserializes and compares values using the
+** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
+** in assert() statements to ensure that the optimized code in
+** sqlite3VdbeRecordCompare() returns results with these two primitives.
+**
+** Return true if the result of comparison is equivalent to desiredResult.
+** Return false if there is a disagreement.
+*/
+static int vdbeRecordCompareDebug(
+ int nKey1, const void *pKey1, /* Left key */
+ const UnpackedRecord *pPKey2, /* Right key */
+ int desiredResult /* Correct answer */
+){
+ u32 d1; /* Offset into aKey[] of next data element */
+ u32 idx1; /* Offset into aKey[] of next header element */
+ u32 szHdr1; /* Number of bytes in header */
+ int i = 0;
+ int rc = 0;
+ const unsigned char *aKey1 = (const unsigned char *)pKey1;
+ KeyInfo *pKeyInfo;
+ Mem mem1;
+
+ pKeyInfo = pPKey2->pKeyInfo;
+ if( pKeyInfo->db==0 ) return 1;
+ mem1.enc = pKeyInfo->enc;
+ mem1.db = pKeyInfo->db;
+ /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
+ VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
+
+ /* Compilers may complain that mem1.u.i is potentially uninitialized.
+ ** We could initialize it, as shown here, to silence those complaints.
+ ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
+ ** the unnecessary initialization has a measurable negative performance
+ ** impact, since this routine is a very high runner. And so, we choose
+ ** to ignore the compiler warnings and leave this variable uninitialized.
+ */
+ /* mem1.u.i = 0; // not needed, here to silence compiler warning */
+
+ idx1 = getVarint32(aKey1, szHdr1);
+ if( szHdr1>98307 ) return SQLITE_CORRUPT;
+ d1 = szHdr1;
+ assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
+ assert( pKeyInfo->aSortFlags!=0 );
+ assert( pKeyInfo->nKeyField>0 );
+ assert( idx1<=szHdr1 || CORRUPT_DB );
+ do{
+ u32 serial_type1;
+
+ /* Read the serial types for the next element in each key. */
+ idx1 += getVarint32( aKey1+idx1, serial_type1 );
+
+ /* Verify that there is enough key space remaining to avoid
+ ** a buffer overread. The "d1+serial_type1+2" subexpression will
+ ** always be greater than or equal to the amount of required key space.
+ ** Use that approximation to avoid the more expensive call to
+ ** sqlite3VdbeSerialTypeLen() in the common case.
+ */
+ if( d1+(u64)serial_type1+2>(u64)nKey1
+ && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1
+ ){
+ break;
+ }
+
+ /* Extract the values to be compared.
+ */
+ d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
+
+ /* Do the comparison
+ */
+ rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
+ pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);
+ if( rc!=0 ){
+ assert( mem1.szMalloc==0 ); /* See comment below */
+ if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
+ && ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null))
+ ){
+ rc = -rc;
+ }
+ if( pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC ){
+ rc = -rc; /* Invert the result for DESC sort order. */
+ }
+ goto debugCompareEnd;
+ }
+ i++;
+ }while( idx1<szHdr1 && i<pPKey2->nField );
+
+ /* No memory allocation is ever used on mem1. Prove this using
+ ** the following assert(). If the assert() fails, it indicates a
+ ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
+ */
+ assert( mem1.szMalloc==0 );
+
+ /* rc==0 here means that one of the keys ran out of fields and
+ ** all the fields up to that point were equal. Return the default_rc
+ ** value. */
+ rc = pPKey2->default_rc;
+
+debugCompareEnd:
+ if( desiredResult==0 && rc==0 ) return 1;
+ if( desiredResult<0 && rc<0 ) return 1;
+ if( desiredResult>0 && rc>0 ) return 1;
+ if( CORRUPT_DB ) return 1;
+ if( pKeyInfo->db->mallocFailed ) return 1;
+ return 0;
+}
+#endif
+
+#ifdef SQLITE_DEBUG
+/*
+** Count the number of fields (a.k.a. columns) in the record given by
+** pKey,nKey. The verify that this count is less than or equal to the
+** limit given by pKeyInfo->nAllField.
+**
+** If this constraint is not satisfied, it means that the high-speed
+** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
+** not work correctly. If this assert() ever fires, it probably means
+** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
+** incorrectly.
+*/
+static void vdbeAssertFieldCountWithinLimits(
+ int nKey, const void *pKey, /* The record to verify */
+ const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
+){
+ int nField = 0;
+ u32 szHdr;
+ u32 idx;
+ u32 notUsed;
+ const unsigned char *aKey = (const unsigned char*)pKey;
+
+ if( CORRUPT_DB ) return;
+ idx = getVarint32(aKey, szHdr);
+ assert( nKey>=0 );
+ assert( szHdr<=(u32)nKey );
+ while( idx<szHdr ){
+ idx += getVarint32(aKey+idx, notUsed);
+ nField++;
+ }
+ assert( nField <= pKeyInfo->nAllField );
+}
+#else
+# define vdbeAssertFieldCountWithinLimits(A,B,C)
+#endif
+
+/*
+** Both *pMem1 and *pMem2 contain string values. Compare the two values
+** using the collation sequence pColl. As usual, return a negative , zero
+** or positive value if *pMem1 is less than, equal to or greater than
+** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
+*/
+static int vdbeCompareMemString(
+ const Mem *pMem1,
+ const Mem *pMem2,
+ const CollSeq *pColl,
+ u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
+){
+ if( pMem1->enc==pColl->enc ){
+ /* The strings are already in the correct encoding. Call the
+ ** comparison function directly */
+ return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
+ }else{
+ int rc;
+ const void *v1, *v2;
+ Mem c1;
+ Mem c2;
+ sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
+ sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
+ sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
+ sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
+ v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
+ v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
+ if( (v1==0 || v2==0) ){
+ if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
+ rc = 0;
+ }else{
+ rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
+ }
+ sqlite3VdbeMemRelease(&c1);
+ sqlite3VdbeMemRelease(&c2);
+ return rc;
+ }
+}
+
+/*
+** The input pBlob is guaranteed to be a Blob that is not marked
+** with MEM_Zero. Return true if it could be a zero-blob.
+*/
+static int isAllZero(const char *z, int n){
+ int i;
+ for(i=0; i<n; i++){
+ if( z[i] ) return 0;
+ }
+ return 1;
+}
+
+/*
+** Compare two blobs. Return negative, zero, or positive if the first
+** is less than, equal to, or greater than the second, respectively.
+** If one blob is a prefix of the other, then the shorter is the lessor.
+*/
+SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
+ int c;
+ int n1 = pB1->n;
+ int n2 = pB2->n;
+
+ /* It is possible to have a Blob value that has some non-zero content
+ ** followed by zero content. But that only comes up for Blobs formed
+ ** by the OP_MakeRecord opcode, and such Blobs never get passed into
+ ** sqlite3MemCompare(). */
+ assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
+ assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
+
+ if( (pB1->flags|pB2->flags) & MEM_Zero ){
+ if( pB1->flags & pB2->flags & MEM_Zero ){
+ return pB1->u.nZero - pB2->u.nZero;
+ }else if( pB1->flags & MEM_Zero ){
+ if( !isAllZero(pB2->z, pB2->n) ) return -1;
+ return pB1->u.nZero - n2;
+ }else{
+ if( !isAllZero(pB1->z, pB1->n) ) return +1;
+ return n1 - pB2->u.nZero;
+ }
+ }
+ c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
+ if( c ) return c;
+ return n1 - n2;
+}
+
+/*
+** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
+** number. Return negative, zero, or positive if the first (i64) is less than,
+** equal to, or greater than the second (double).
+*/
+static int sqlite3IntFloatCompare(i64 i, double r){
+ if( sizeof(LONGDOUBLE_TYPE)>8 ){
+ LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
+ if( x<r ) return -1;
+ if( x>r ) return +1;
+ return 0;
+ }else{
+ i64 y;
+ double s;
+ if( r<-9223372036854775808.0 ) return +1;
+ if( r>=9223372036854775808.0 ) return -1;
+ y = (i64)r;
+ if( i<y ) return -1;
+ if( i>y ) return +1;
+ s = (double)i;
+ if( s<r ) return -1;
+ if( s>r ) return +1;
+ return 0;
+ }
+}
+
+/*
+** Compare the values contained by the two memory cells, returning
+** negative, zero or positive if pMem1 is less than, equal to, or greater
+** than pMem2. Sorting order is NULL's first, followed by numbers (integers
+** and reals) sorted numerically, followed by text ordered by the collating
+** sequence pColl and finally blob's ordered by memcmp().
+**
+** Two NULL values are considered equal by this function.
+*/
+SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
+ int f1, f2;
+ int combined_flags;
+
+ f1 = pMem1->flags;
+ f2 = pMem2->flags;
+ combined_flags = f1|f2;
+ assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );
+
+ /* If one value is NULL, it is less than the other. If both values
+ ** are NULL, return 0.
+ */
+ if( combined_flags&MEM_Null ){
+ return (f2&MEM_Null) - (f1&MEM_Null);
+ }
+
+ /* At least one of the two values is a number
+ */
+ if( combined_flags&(MEM_Int|MEM_Real|MEM_IntReal) ){
+ testcase( combined_flags & MEM_Int );
+ testcase( combined_flags & MEM_Real );
+ testcase( combined_flags & MEM_IntReal );
+ if( (f1 & f2 & (MEM_Int|MEM_IntReal))!=0 ){
+ testcase( f1 & f2 & MEM_Int );
+ testcase( f1 & f2 & MEM_IntReal );
+ if( pMem1->u.i < pMem2->u.i ) return -1;
+ if( pMem1->u.i > pMem2->u.i ) return +1;
+ return 0;
+ }
+ if( (f1 & f2 & MEM_Real)!=0 ){
+ if( pMem1->u.r < pMem2->u.r ) return -1;
+ if( pMem1->u.r > pMem2->u.r ) return +1;
+ return 0;
+ }
+ if( (f1&(MEM_Int|MEM_IntReal))!=0 ){
+ testcase( f1 & MEM_Int );
+ testcase( f1 & MEM_IntReal );
+ if( (f2&MEM_Real)!=0 ){
+ return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
+ }else if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
+ if( pMem1->u.i < pMem2->u.i ) return -1;
+ if( pMem1->u.i > pMem2->u.i ) return +1;
+ return 0;
+ }else{
+ return -1;
+ }
+ }
+ if( (f1&MEM_Real)!=0 ){
+ if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
+ testcase( f2 & MEM_Int );
+ testcase( f2 & MEM_IntReal );
+ return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
+ }else{
+ return -1;
+ }
+ }
+ return +1;
+ }
+
+ /* If one value is a string and the other is a blob, the string is less.
+ ** If both are strings, compare using the collating functions.
+ */
+ if( combined_flags&MEM_Str ){
+ if( (f1 & MEM_Str)==0 ){
+ return 1;
+ }
+ if( (f2 & MEM_Str)==0 ){
+ return -1;
+ }
+
+ assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
+ assert( pMem1->enc==SQLITE_UTF8 ||
+ pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
+
+ /* The collation sequence must be defined at this point, even if
+ ** the user deletes the collation sequence after the vdbe program is
+ ** compiled (this was not always the case).
+ */
+ assert( !pColl || pColl->xCmp );
+
+ if( pColl ){
+ return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
+ }
+ /* If a NULL pointer was passed as the collate function, fall through
+ ** to the blob case and use memcmp(). */
+ }
+
+ /* Both values must be blobs. Compare using memcmp(). */
+ return sqlite3BlobCompare(pMem1, pMem2);
+}
+
+
+/*
+** The first argument passed to this function is a serial-type that
+** corresponds to an integer - all values between 1 and 9 inclusive
+** except 7. The second points to a buffer containing an integer value
+** serialized according to serial_type. This function deserializes
+** and returns the value.
+*/
+static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
+ u32 y;
+ assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
+ switch( serial_type ){
+ case 0:
+ case 1:
+ testcase( aKey[0]&0x80 );
+ return ONE_BYTE_INT(aKey);
+ case 2:
+ testcase( aKey[0]&0x80 );
+ return TWO_BYTE_INT(aKey);
+ case 3:
+ testcase( aKey[0]&0x80 );
+ return THREE_BYTE_INT(aKey);
+ case 4: {
+ testcase( aKey[0]&0x80 );
+ y = FOUR_BYTE_UINT(aKey);
+ return (i64)*(int*)&y;
+ }
+ case 5: {
+ testcase( aKey[0]&0x80 );
+ return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
+ }
+ case 6: {
+ u64 x = FOUR_BYTE_UINT(aKey);
+ testcase( aKey[0]&0x80 );
+ x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
+ return (i64)*(i64*)&x;
+ }
+ }
+
+ return (serial_type - 8);
+}
+
+/*
+** This function compares the two table rows or index records
+** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
+** or positive integer if key1 is less than, equal to or
+** greater than key2. The {nKey1, pKey1} key must be a blob
+** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
+** key must be a parsed key such as obtained from
+** sqlite3VdbeParseRecord.
+**
+** If argument bSkip is non-zero, it is assumed that the caller has already
+** determined that the first fields of the keys are equal.
+**
+** Key1 and Key2 do not have to contain the same number of fields. If all
+** fields that appear in both keys are equal, then pPKey2->default_rc is
+** returned.
+**
+** If database corruption is discovered, set pPKey2->errCode to
+** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
+** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
+** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
+*/
+SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
+ int nKey1, const void *pKey1, /* Left key */
+ UnpackedRecord *pPKey2, /* Right key */
+ int bSkip /* If true, skip the first field */
+){
+ u32 d1; /* Offset into aKey[] of next data element */
+ int i; /* Index of next field to compare */
+ u32 szHdr1; /* Size of record header in bytes */
+ u32 idx1; /* Offset of first type in header */
+ int rc = 0; /* Return value */
+ Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
+ KeyInfo *pKeyInfo;
+ const unsigned char *aKey1 = (const unsigned char *)pKey1;
+ Mem mem1;
+
+ /* If bSkip is true, then the caller has already determined that the first
+ ** two elements in the keys are equal. Fix the various stack variables so
+ ** that this routine begins comparing at the second field. */
+ if( bSkip ){
+ u32 s1;
+ idx1 = 1 + getVarint32(&aKey1[1], s1);
+ szHdr1 = aKey1[0];
+ d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
+ i = 1;
+ pRhs++;
+ }else{
+ idx1 = getVarint32(aKey1, szHdr1);
+ d1 = szHdr1;
+ i = 0;
+ }
+ if( d1>(unsigned)nKey1 ){
+ pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
+ return 0; /* Corruption */
+ }
+
+ VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
+ assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
+ || CORRUPT_DB );
+ assert( pPKey2->pKeyInfo->aSortFlags!=0 );
+ assert( pPKey2->pKeyInfo->nKeyField>0 );
+ assert( idx1<=szHdr1 || CORRUPT_DB );
+ do{
+ u32 serial_type;
+
+ /* RHS is an integer */
+ if( pRhs->flags & (MEM_Int|MEM_IntReal) ){
+ testcase( pRhs->flags & MEM_Int );
+ testcase( pRhs->flags & MEM_IntReal );
+ serial_type = aKey1[idx1];
+ testcase( serial_type==12 );
+ if( serial_type>=10 ){
+ rc = +1;
+ }else if( serial_type==0 ){
+ rc = -1;
+ }else if( serial_type==7 ){
+ sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
+ rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
+ }else{
+ i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
+ i64 rhs = pRhs->u.i;
+ if( lhs<rhs ){
+ rc = -1;
+ }else if( lhs>rhs ){
+ rc = +1;
+ }
+ }
+ }
+
+ /* RHS is real */
+ else if( pRhs->flags & MEM_Real ){
+ serial_type = aKey1[idx1];
+ if( serial_type>=10 ){
+ /* Serial types 12 or greater are strings and blobs (greater than
+ ** numbers). Types 10 and 11 are currently "reserved for future
+ ** use", so it doesn't really matter what the results of comparing
+ ** them to numberic values are. */
+ rc = +1;
+ }else if( serial_type==0 ){
+ rc = -1;
+ }else{
+ sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
+ if( serial_type==7 ){
+ if( mem1.u.r<pRhs->u.r ){
+ rc = -1;
+ }else if( mem1.u.r>pRhs->u.r ){
+ rc = +1;
+ }
+ }else{
+ rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
+ }
+ }
+ }
+
+ /* RHS is a string */
+ else if( pRhs->flags & MEM_Str ){
+ getVarint32NR(&aKey1[idx1], serial_type);
+ testcase( serial_type==12 );
+ if( serial_type<12 ){
+ rc = -1;
+ }else if( !(serial_type & 0x01) ){
+ rc = +1;
+ }else{
+ mem1.n = (serial_type - 12) / 2;
+ testcase( (d1+mem1.n)==(unsigned)nKey1 );
+ testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
+ if( (d1+mem1.n) > (unsigned)nKey1
+ || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i
+ ){
+ pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
+ return 0; /* Corruption */
+ }else if( pKeyInfo->aColl[i] ){
+ mem1.enc = pKeyInfo->enc;
+ mem1.db = pKeyInfo->db;
+ mem1.flags = MEM_Str;
+ mem1.z = (char*)&aKey1[d1];
+ rc = vdbeCompareMemString(
+ &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
+ );
+ }else{
+ int nCmp = MIN(mem1.n, pRhs->n);
+ rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
+ if( rc==0 ) rc = mem1.n - pRhs->n;
+ }
+ }
+ }
+
+ /* RHS is a blob */
+ else if( pRhs->flags & MEM_Blob ){
+ assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
+ getVarint32NR(&aKey1[idx1], serial_type);
+ testcase( serial_type==12 );
+ if( serial_type<12 || (serial_type & 0x01) ){
+ rc = -1;
+ }else{
+ int nStr = (serial_type - 12) / 2;
+ testcase( (d1+nStr)==(unsigned)nKey1 );
+ testcase( (d1+nStr+1)==(unsigned)nKey1 );
+ if( (d1+nStr) > (unsigned)nKey1 ){
+ pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
+ return 0; /* Corruption */
+ }else if( pRhs->flags & MEM_Zero ){
+ if( !isAllZero((const char*)&aKey1[d1],nStr) ){
+ rc = 1;
+ }else{
+ rc = nStr - pRhs->u.nZero;
+ }
+ }else{
+ int nCmp = MIN(nStr, pRhs->n);
+ rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
+ if( rc==0 ) rc = nStr - pRhs->n;
+ }
+ }
+ }
+
+ /* RHS is null */
+ else{
+ serial_type = aKey1[idx1];
+ rc = (serial_type!=0);
+ }
+
+ if( rc!=0 ){
+ int sortFlags = pPKey2->pKeyInfo->aSortFlags[i];
+ if( sortFlags ){
+ if( (sortFlags & KEYINFO_ORDER_BIGNULL)==0
+ || ((sortFlags & KEYINFO_ORDER_DESC)
+ !=(serial_type==0 || (pRhs->flags&MEM_Null)))
+ ){
+ rc = -rc;
+ }
+ }
+ assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
+ assert( mem1.szMalloc==0 ); /* See comment below */
+ return rc;
+ }
+
+ i++;
+ if( i==pPKey2->nField ) break;
+ pRhs++;
+ d1 += sqlite3VdbeSerialTypeLen(serial_type);
+ idx1 += sqlite3VarintLen(serial_type);
+ }while( idx1<(unsigned)szHdr1 && d1<=(unsigned)nKey1 );
+
+ /* No memory allocation is ever used on mem1. Prove this using
+ ** the following assert(). If the assert() fails, it indicates a
+ ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
+ assert( mem1.szMalloc==0 );
+
+ /* rc==0 here means that one or both of the keys ran out of fields and
+ ** all the fields up to that point were equal. Return the default_rc
+ ** value. */
+ assert( CORRUPT_DB
+ || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
+ || pPKey2->pKeyInfo->db->mallocFailed
+ );
+ pPKey2->eqSeen = 1;
+ return pPKey2->default_rc;
+}
+SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
+ int nKey1, const void *pKey1, /* Left key */
+ UnpackedRecord *pPKey2 /* Right key */
+){
+ return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
+}
+
+
+/*
+** This function is an optimized version of sqlite3VdbeRecordCompare()
+** that (a) the first field of pPKey2 is an integer, and (b) the
+** size-of-header varint at the start of (pKey1/nKey1) fits in a single
+** byte (i.e. is less than 128).
+**
+** To avoid concerns about buffer overreads, this routine is only used
+** on schemas where the maximum valid header size is 63 bytes or less.
+*/
+static int vdbeRecordCompareInt(
+ int nKey1, const void *pKey1, /* Left key */
+ UnpackedRecord *pPKey2 /* Right key */
+){
+ const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
+ int serial_type = ((const u8*)pKey1)[1];
+ int res;
+ u32 y;
+ u64 x;
+ i64 v;
+ i64 lhs;
+
+ vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
+ assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
+ switch( serial_type ){
+ case 1: { /* 1-byte signed integer */
+ lhs = ONE_BYTE_INT(aKey);
+ testcase( lhs<0 );
+ break;
+ }
+ case 2: { /* 2-byte signed integer */
+ lhs = TWO_BYTE_INT(aKey);
+ testcase( lhs<0 );
+ break;
+ }
+ case 3: { /* 3-byte signed integer */
+ lhs = THREE_BYTE_INT(aKey);
+ testcase( lhs<0 );
+ break;
+ }
+ case 4: { /* 4-byte signed integer */
+ y = FOUR_BYTE_UINT(aKey);
+ lhs = (i64)*(int*)&y;
+ testcase( lhs<0 );
+ break;
+ }
+ case 5: { /* 6-byte signed integer */
+ lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
+ testcase( lhs<0 );
+ break;
+ }
+ case 6: { /* 8-byte signed integer */
+ x = FOUR_BYTE_UINT(aKey);
+ x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
+ lhs = *(i64*)&x;
+ testcase( lhs<0 );
+ break;
+ }
+ case 8:
+ lhs = 0;
+ break;
+ case 9:
+ lhs = 1;
+ break;
+
+ /* This case could be removed without changing the results of running
+ ** this code. Including it causes gcc to generate a faster switch
+ ** statement (since the range of switch targets now starts at zero and
+ ** is contiguous) but does not cause any duplicate code to be generated
+ ** (as gcc is clever enough to combine the two like cases). Other
+ ** compilers might be similar. */
+ case 0: case 7:
+ return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
+
+ default:
+ return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
+ }
+
+ v = pPKey2->aMem[0].u.i;
+ if( v>lhs ){
+ res = pPKey2->r1;
+ }else if( v<lhs ){
+ res = pPKey2->r2;
+ }else if( pPKey2->nField>1 ){
+ /* The first fields of the two keys are equal. Compare the trailing
+ ** fields. */
+ res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
+ }else{
+ /* The first fields of the two keys are equal and there are no trailing
+ ** fields. Return pPKey2->default_rc in this case. */
+ res = pPKey2->default_rc;
+ pPKey2->eqSeen = 1;
+ }
+
+ assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
+ return res;
+}
+
+/*
+** This function is an optimized version of sqlite3VdbeRecordCompare()
+** that (a) the first field of pPKey2 is a string, that (b) the first field
+** uses the collation sequence BINARY and (c) that the size-of-header varint
+** at the start of (pKey1/nKey1) fits in a single byte.
+*/
+static int vdbeRecordCompareString(
+ int nKey1, const void *pKey1, /* Left key */
+ UnpackedRecord *pPKey2 /* Right key */
+){
+ const u8 *aKey1 = (const u8*)pKey1;
+ int serial_type;
+ int res;
+
+ assert( pPKey2->aMem[0].flags & MEM_Str );
+ vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
+ serial_type = (u8)(aKey1[1]);
+ if( serial_type >= 0x80 ){
+ sqlite3GetVarint32(&aKey1[1], (u32*)&serial_type);
+ }
+ if( serial_type<12 ){
+ res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
+ }else if( !(serial_type & 0x01) ){
+ res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
+ }else{
+ int nCmp;
+ int nStr;
+ int szHdr = aKey1[0];
+
+ nStr = (serial_type-12) / 2;
+ if( (szHdr + nStr) > nKey1 ){
+ pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
+ return 0; /* Corruption */
+ }
+ nCmp = MIN( pPKey2->aMem[0].n, nStr );
+ res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
+
+ if( res>0 ){
+ res = pPKey2->r2;
+ }else if( res<0 ){
+ res = pPKey2->r1;
+ }else{
+ res = nStr - pPKey2->aMem[0].n;
+ if( res==0 ){
+ if( pPKey2->nField>1 ){
+ res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
+ }else{
+ res = pPKey2->default_rc;
+ pPKey2->eqSeen = 1;
+ }
+ }else if( res>0 ){
+ res = pPKey2->r2;
+ }else{
+ res = pPKey2->r1;
+ }
+ }
+ }
+
+ assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
+ || CORRUPT_DB
+ || pPKey2->pKeyInfo->db->mallocFailed
+ );
+ return res;
+}
+
+/*
+** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
+** suitable for comparing serialized records to the unpacked record passed
+** as the only argument.
+*/
+SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
+ /* varintRecordCompareInt() and varintRecordCompareString() both assume
+ ** that the size-of-header varint that occurs at the start of each record
+ ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
+ ** also assumes that it is safe to overread a buffer by at least the
+ ** maximum possible legal header size plus 8 bytes. Because there is
+ ** guaranteed to be at least 74 (but not 136) bytes of padding following each
+ ** buffer passed to varintRecordCompareInt() this makes it convenient to
+ ** limit the size of the header to 64 bytes in cases where the first field
+ ** is an integer.
+ **
+ ** The easiest way to enforce this limit is to consider only records with
+ ** 13 fields or less. If the first field is an integer, the maximum legal
+ ** header size is (12*5 + 1 + 1) bytes. */
+ if( p->pKeyInfo->nAllField<=13 ){
+ int flags = p->aMem[0].flags;
+ if( p->pKeyInfo->aSortFlags[0] ){
+ if( p->pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL ){
+ return sqlite3VdbeRecordCompare;
+ }
+ p->r1 = 1;
+ p->r2 = -1;
+ }else{
+ p->r1 = -1;
+ p->r2 = 1;
+ }
+ if( (flags & MEM_Int) ){
+ return vdbeRecordCompareInt;
+ }
+ testcase( flags & MEM_Real );
+ testcase( flags & MEM_Null );
+ testcase( flags & MEM_Blob );
+ if( (flags & (MEM_Real|MEM_IntReal|MEM_Null|MEM_Blob))==0
+ && p->pKeyInfo->aColl[0]==0
+ ){
+ assert( flags & MEM_Str );
+ return vdbeRecordCompareString;
+ }
+ }
+
+ return sqlite3VdbeRecordCompare;
+}
+
+/*
+** pCur points at an index entry created using the OP_MakeRecord opcode.
+** Read the rowid (the last field in the record) and store it in *rowid.
+** Return SQLITE_OK if everything works, or an error code otherwise.
+**
+** pCur might be pointing to text obtained from a corrupt database file.
+** So the content cannot be trusted. Do appropriate checks on the content.
+*/
+SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
+ i64 nCellKey = 0;
+ int rc;
+ u32 szHdr; /* Size of the header */
+ u32 typeRowid; /* Serial type of the rowid */
+ u32 lenRowid; /* Size of the rowid */
+ Mem m, v;
+
+ /* Get the size of the index entry. Only indices entries of less
+ ** than 2GiB are support - anything large must be database corruption.
+ ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
+ ** this code can safely assume that nCellKey is 32-bits
+ */
+ assert( sqlite3BtreeCursorIsValid(pCur) );
+ nCellKey = sqlite3BtreePayloadSize(pCur);
+ assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
+
+ /* Read in the complete content of the index entry */
+ sqlite3VdbeMemInit(&m, db, 0);
+ rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
+ if( rc ){
+ return rc;
+ }
+
+ /* The index entry must begin with a header size */
+ getVarint32NR((u8*)m.z, szHdr);
+ testcase( szHdr==3 );
+ testcase( szHdr==m.n );
+ testcase( szHdr>0x7fffffff );
+ assert( m.n>=0 );
+ if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
+ goto idx_rowid_corruption;
+ }
+
+ /* The last field of the index should be an integer - the ROWID.
+ ** Verify that the last entry really is an integer. */
+ getVarint32NR((u8*)&m.z[szHdr-1], typeRowid);
+ testcase( typeRowid==1 );
+ testcase( typeRowid==2 );
+ testcase( typeRowid==3 );
+ testcase( typeRowid==4 );
+ testcase( typeRowid==5 );
+ testcase( typeRowid==6 );
+ testcase( typeRowid==8 );
+ testcase( typeRowid==9 );
+ if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
+ goto idx_rowid_corruption;
+ }
+ lenRowid = sqlite3SmallTypeSizes[typeRowid];
+ testcase( (u32)m.n==szHdr+lenRowid );
+ if( unlikely((u32)m.n<szHdr+lenRowid) ){
+ goto idx_rowid_corruption;
+ }
+
+ /* Fetch the integer off the end of the index record */
+ sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
+ *rowid = v.u.i;
+ sqlite3VdbeMemRelease(&m);
+ return SQLITE_OK;
+
+ /* Jump here if database corruption is detected after m has been
+ ** allocated. Free the m object and return SQLITE_CORRUPT. */
+idx_rowid_corruption:
+ testcase( m.szMalloc!=0 );
+ sqlite3VdbeMemRelease(&m);
+ return SQLITE_CORRUPT_BKPT;
+}
+
+/*
+** Compare the key of the index entry that cursor pC is pointing to against
+** the key string in pUnpacked. Write into *pRes a number
+** that is negative, zero, or positive if pC is less than, equal to,
+** or greater than pUnpacked. Return SQLITE_OK on success.
+**
+** pUnpacked is either created without a rowid or is truncated so that it
+** omits the rowid at the end. The rowid at the end of the index entry
+** is ignored as well. Hence, this routine only compares the prefixes
+** of the keys prior to the final rowid, not the entire key.
+*/
+SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
+ sqlite3 *db, /* Database connection */
+ VdbeCursor *pC, /* The cursor to compare against */
+ UnpackedRecord *pUnpacked, /* Unpacked version of key */
+ int *res /* Write the comparison result here */
+){
+ i64 nCellKey = 0;
+ int rc;
+ BtCursor *pCur;
+ Mem m;
+
+ assert( pC->eCurType==CURTYPE_BTREE );
+ pCur = pC->uc.pCursor;
+ assert( sqlite3BtreeCursorIsValid(pCur) );
+ nCellKey = sqlite3BtreePayloadSize(pCur);
+ /* nCellKey will always be between 0 and 0xffffffff because of the way
+ ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
+ if( nCellKey<=0 || nCellKey>0x7fffffff ){
+ *res = 0;
+ return SQLITE_CORRUPT_BKPT;
+ }
+ sqlite3VdbeMemInit(&m, db, 0);
+ rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
+ if( rc ){
+ return rc;
+ }
+ *res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0);
+ sqlite3VdbeMemRelease(&m);
+ return SQLITE_OK;
+}
+
+/*
+** This routine sets the value to be returned by subsequent calls to
+** sqlite3_changes() on the database handle 'db'.
+*/
+SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
+ assert( sqlite3_mutex_held(db->mutex) );
+ db->nChange = nChange;
+ db->nTotalChange += nChange;
+}
+
+/*
+** Set a flag in the vdbe to update the change counter when it is finalised
+** or reset.
+*/
+SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
+ v->changeCntOn = 1;
+}
+
+/*
+** Mark every prepared statement associated with a database connection
+** as expired.
+**
+** An expired statement means that recompilation of the statement is
+** recommend. Statements expire when things happen that make their
+** programs obsolete. Removing user-defined functions or collating
+** sequences, or changing an authorization function are the types of
+** things that make prepared statements obsolete.
+**
+** If iCode is 1, then expiration is advisory. The statement should
+** be reprepared before being restarted, but if it is already running
+** it is allowed to run to completion.
+**
+** Internally, this function just sets the Vdbe.expired flag on all
+** prepared statements. The flag is set to 1 for an immediate expiration
+** and set to 2 for an advisory expiration.
+*/
+SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){
+ Vdbe *p;
+ for(p = db->pVdbe; p; p=p->pNext){
+ p->expired = iCode+1;
+ }
+}
+
+/*
+** Return the database associated with the Vdbe.
+*/
+SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
+ return v->db;
+}
+
+/*
+** Return the SQLITE_PREPARE flags for a Vdbe.
+*/
+SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
+ return v->prepFlags;
+}
+
+/*
+** Return a pointer to an sqlite3_value structure containing the value bound
+** parameter iVar of VM v. Except, if the value is an SQL NULL, return
+** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
+** constants) to the value before returning it.
+**
+** The returned value must be freed by the caller using sqlite3ValueFree().
+*/
+SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
+ assert( iVar>0 );
+ if( v ){
+ Mem *pMem = &v->aVar[iVar-1];
+ assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
+ if( 0==(pMem->flags & MEM_Null) ){
+ sqlite3_value *pRet = sqlite3ValueNew(v->db);
+ if( pRet ){
+ sqlite3VdbeMemCopy((Mem *)pRet, pMem);
+ sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
+ }
+ return pRet;
+ }
+ }
+ return 0;
+}
+
+/*
+** Configure SQL variable iVar so that binding a new value to it signals
+** to sqlite3_reoptimize() that re-preparing the statement may result
+** in a better query plan.
+*/
+SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
+ assert( iVar>0 );
+ assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
+ if( iVar>=32 ){
+ v->expmask |= 0x80000000;
+ }else{
+ v->expmask |= ((u32)1 << (iVar-1));
+ }
+}
+
+/*
+** Cause a function to throw an error if it was call from OP_PureFunc
+** rather than OP_Function.
+**
+** OP_PureFunc means that the function must be deterministic, and should
+** throw an error if it is given inputs that would make it non-deterministic.
+** This routine is invoked by date/time functions that use non-deterministic
+** features such as 'now'.
+*/
+SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
+ const VdbeOp *pOp;
+#ifdef SQLITE_ENABLE_STAT4
+ if( pCtx->pVdbe==0 ) return 1;
+#endif
+ pOp = pCtx->pVdbe->aOp + pCtx->iOp;
+ if( pOp->opcode==OP_PureFunc ){
+ const char *zContext;
+ char *zMsg;
+ if( pOp->p5 & NC_IsCheck ){
+ zContext = "a CHECK constraint";
+ }else if( pOp->p5 & NC_GenCol ){
+ zContext = "a generated column";
+ }else{
+ zContext = "an index";
+ }
+ zMsg = sqlite3_mprintf("non-deterministic use of %s() in %s",
+ pCtx->pFunc->zName, zContext);
+ sqlite3_result_error(pCtx, zMsg, -1);
+ sqlite3_free(zMsg);
+ return 0;
+ }
+ return 1;
+}
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/*
+** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
+** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
+** in memory obtained from sqlite3DbMalloc).
+*/
+SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
+ if( pVtab->zErrMsg ){
+ sqlite3 *db = p->db;
+ sqlite3DbFree(db, p->zErrMsg);
+ p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
+ sqlite3_free(pVtab->zErrMsg);
+ pVtab->zErrMsg = 0;
+ }
+}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+
+/*
+** If the second argument is not NULL, release any allocations associated
+** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
+** structure itself, using sqlite3DbFree().
+**
+** This function is used to free UnpackedRecord structures allocated by
+** the vdbeUnpackRecord() function found in vdbeapi.c.
+*/
+static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
+ if( p ){
+ int i;
+ for(i=0; i<nField; i++){
+ Mem *pMem = &p->aMem[i];
+ if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
+ }
+ sqlite3DbFreeNN(db, p);
+ }
+}
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
+
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+/*
+** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
+** then cursor passed as the second argument should point to the row about
+** to be update or deleted. If the application calls sqlite3_preupdate_old(),
+** the required value will be read from the row the cursor points to.
+*/
+SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
+ Vdbe *v, /* Vdbe pre-update hook is invoked by */
+ VdbeCursor *pCsr, /* Cursor to grab old.* values from */
+ int op, /* SQLITE_INSERT, UPDATE or DELETE */
+ const char *zDb, /* Database name */
+ Table *pTab, /* Modified table */
+ i64 iKey1, /* Initial key value */
+ int iReg /* Register for new.* record */
+){
+ sqlite3 *db = v->db;
+ i64 iKey2;
+ PreUpdate preupdate;
+ const char *zTbl = pTab->zName;
+ static const u8 fakeSortOrder = 0;
+
+ assert( db->pPreUpdate==0 );
+ memset(&preupdate, 0, sizeof(PreUpdate));
+ if( HasRowid(pTab)==0 ){
+ iKey1 = iKey2 = 0;
+ preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
+ }else{
+ if( op==SQLITE_UPDATE ){
+ iKey2 = v->aMem[iReg].u.i;
+ }else{
+ iKey2 = iKey1;
+ }
+ }
+
+ assert( pCsr->nField==pTab->nCol
+ || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
+ );
+
+ preupdate.v = v;
+ preupdate.pCsr = pCsr;
+ preupdate.op = op;
+ preupdate.iNewReg = iReg;
+ preupdate.keyinfo.db = db;
+ preupdate.keyinfo.enc = ENC(db);
+ preupdate.keyinfo.nKeyField = pTab->nCol;
+ preupdate.keyinfo.aSortFlags = (u8*)&fakeSortOrder;
+ preupdate.iKey1 = iKey1;
+ preupdate.iKey2 = iKey2;
+ preupdate.pTab = pTab;
+
+ db->pPreUpdate = &preupdate;
+ db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
+ db->pPreUpdate = 0;
+ sqlite3DbFree(db, preupdate.aRecord);
+ vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
+ vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
+ if( preupdate.aNew ){
+ int i;
+ for(i=0; i<pCsr->nField; i++){
+ sqlite3VdbeMemRelease(&preupdate.aNew[i]);
+ }
+ sqlite3DbFreeNN(db, preupdate.aNew);
+ }
+}
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
+
+/************** End of vdbeaux.c *********************************************/
+/************** Begin file vdbeapi.c *****************************************/
+/*
+** 2004 May 26
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains code use to implement APIs that are part of the
+** VDBE.
+*/
+/* #include "sqliteInt.h" */
+/* #include "vdbeInt.h" */
+
+#ifndef SQLITE_OMIT_DEPRECATED
+/*
+** Return TRUE (non-zero) of the statement supplied as an argument needs
+** to be recompiled. A statement needs to be recompiled whenever the
+** execution environment changes in a way that would alter the program
+** that sqlite3_prepare() generates. For example, if new functions or
+** collating sequences are registered or if an authorizer function is
+** added or changed.
+*/
+SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
+ Vdbe *p = (Vdbe*)pStmt;
+ return p==0 || p->expired;
+}
+#endif
+
+/*
+** Check on a Vdbe to make sure it has not been finalized. Log
+** an error and return true if it has been finalized (or is otherwise
+** invalid). Return false if it is ok.
+*/
+static int vdbeSafety(Vdbe *p){
+ if( p->db==0 ){
+ sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
+ return 1;
+ }else{
+ return 0;
+ }
+}
+static int vdbeSafetyNotNull(Vdbe *p){
+ if( p==0 ){
+ sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
+ return 1;
+ }else{
+ return vdbeSafety(p);
+ }
+}
+
+#ifndef SQLITE_OMIT_TRACE
+/*
+** Invoke the profile callback. This routine is only called if we already
+** know that the profile callback is defined and needs to be invoked.
+*/
+static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
+ sqlite3_int64 iNow;
+ sqlite3_int64 iElapse;
+ assert( p->startTime>0 );
+ assert( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 );
+ assert( db->init.busy==0 );
+ assert( p->zSql!=0 );
+ sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
+ iElapse = (iNow - p->startTime)*1000000;
+#ifndef SQLITE_OMIT_DEPRECATED
+ if( db->xProfile ){
+ db->xProfile(db->pProfileArg, p->zSql, iElapse);
+ }
+#endif
+ if( db->mTrace & SQLITE_TRACE_PROFILE ){
+ db->trace.xV2(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
+ }
+ p->startTime = 0;
+}
+/*
+** The checkProfileCallback(DB,P) macro checks to see if a profile callback
+** is needed, and it invokes the callback if it is needed.
+*/
+# define checkProfileCallback(DB,P) \
+ if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
+#else
+# define checkProfileCallback(DB,P) /*no-op*/
+#endif
+
+/*
+** The following routine destroys a virtual machine that is created by
+** the sqlite3_compile() routine. The integer returned is an SQLITE_
+** success/failure code that describes the result of executing the virtual
+** machine.
+**
+** This routine sets the error code and string returned by
+** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
+*/
+SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
+ int rc;
+ if( pStmt==0 ){
+ /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
+ ** pointer is a harmless no-op. */
+ rc = SQLITE_OK;
+ }else{
+ Vdbe *v = (Vdbe*)pStmt;
+ sqlite3 *db = v->db;
+ if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
+ sqlite3_mutex_enter(db->mutex);
+ checkProfileCallback(db, v);
+ rc = sqlite3VdbeFinalize(v);
+ rc = sqlite3ApiExit(db, rc);
+ sqlite3LeaveMutexAndCloseZombie(db);
+ }
+ return rc;
+}
+
+/*
+** Terminate the current execution of an SQL statement and reset it
+** back to its starting state so that it can be reused. A success code from
+** the prior execution is returned.
+**
+** This routine sets the error code and string returned by
+** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
+*/
+SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
+ int rc;
+ if( pStmt==0 ){
+ rc = SQLITE_OK;
+ }else{
+ Vdbe *v = (Vdbe*)pStmt;
+ sqlite3 *db = v->db;
+ sqlite3_mutex_enter(db->mutex);
+ checkProfileCallback(db, v);
+ rc = sqlite3VdbeReset(v);
+ sqlite3VdbeRewind(v);
+ assert( (rc & (db->errMask))==rc );
+ rc = sqlite3ApiExit(db, rc);
+ sqlite3_mutex_leave(db->mutex);
+ }
+ return rc;
+}
+
+/*
+** Set all the parameters in the compiled SQL statement to NULL.
+*/
+SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
+ int i;
+ int rc = SQLITE_OK;
+ Vdbe *p = (Vdbe*)pStmt;
+#if SQLITE_THREADSAFE
+ sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
+#endif
+ sqlite3_mutex_enter(mutex);
+ for(i=0; i<p->nVar; i++){
+ sqlite3VdbeMemRelease(&p->aVar[i]);
+ p->aVar[i].flags = MEM_Null;
+ }
+ assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
+ if( p->expmask ){
+ p->expired = 1;
+ }
+ sqlite3_mutex_leave(mutex);
+ return rc;
+}
+
+
+/**************************** sqlite3_value_ *******************************
+** The following routines extract information from a Mem or sqlite3_value
+** structure.
+*/
+SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
+ Mem *p = (Mem*)pVal;
+ if( p->flags & (MEM_Blob|MEM_Str) ){
+ if( ExpandBlob(p)!=SQLITE_OK ){
+ assert( p->flags==MEM_Null && p->z==0 );
+ return 0;
+ }
+ p->flags |= MEM_Blob;
+ return p->n ? p->z : 0;
+ }else{
+ return sqlite3_value_text(pVal);
+ }
+}
+SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
+ return sqlite3ValueBytes(pVal, SQLITE_UTF8);
+}
+SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
+ return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
+}
+SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
+ return sqlite3VdbeRealValue((Mem*)pVal);
+}
+SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
+ return (int)sqlite3VdbeIntValue((Mem*)pVal);
+}
+SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
+ return sqlite3VdbeIntValue((Mem*)pVal);
+}
+SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
+ Mem *pMem = (Mem*)pVal;
+ return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
+}
+SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
+ Mem *p = (Mem*)pVal;
+ if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
+ (MEM_Null|MEM_Term|MEM_Subtype)
+ && zPType!=0
+ && p->eSubtype=='p'
+ && strcmp(p->u.zPType, zPType)==0
+ ){
+ return (void*)p->z;
+ }else{
+ return 0;
+ }
+}
+SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
+ return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
+}
+#ifndef SQLITE_OMIT_UTF16
+SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
+ return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
+}
+SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
+ return sqlite3ValueText(pVal, SQLITE_UTF16BE);
+}
+SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
+ return sqlite3ValueText(pVal, SQLITE_UTF16LE);
+}
+#endif /* SQLITE_OMIT_UTF16 */
+/* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
+** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
+** point number string BLOB NULL
+*/
+SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
+ static const u8 aType[] = {
+ SQLITE_BLOB, /* 0x00 (not possible) */
+ SQLITE_NULL, /* 0x01 NULL */
+ SQLITE_TEXT, /* 0x02 TEXT */
+ SQLITE_NULL, /* 0x03 (not possible) */
+ SQLITE_INTEGER, /* 0x04 INTEGER */
+ SQLITE_NULL, /* 0x05 (not possible) */
+ SQLITE_INTEGER, /* 0x06 INTEGER + TEXT */
+ SQLITE_NULL, /* 0x07 (not possible) */
+ SQLITE_FLOAT, /* 0x08 FLOAT */
+ SQLITE_NULL, /* 0x09 (not possible) */
+ SQLITE_FLOAT, /* 0x0a FLOAT + TEXT */
+ SQLITE_NULL, /* 0x0b (not possible) */
+ SQLITE_INTEGER, /* 0x0c (not possible) */
+ SQLITE_NULL, /* 0x0d (not possible) */
+ SQLITE_INTEGER, /* 0x0e (not possible) */
+ SQLITE_NULL, /* 0x0f (not possible) */
+ SQLITE_BLOB, /* 0x10 BLOB */
+ SQLITE_NULL, /* 0x11 (not possible) */
+ SQLITE_TEXT, /* 0x12 (not possible) */
+ SQLITE_NULL, /* 0x13 (not possible) */
+ SQLITE_INTEGER, /* 0x14 INTEGER + BLOB */
+ SQLITE_NULL, /* 0x15 (not possible) */
+ SQLITE_INTEGER, /* 0x16 (not possible) */
+ SQLITE_NULL, /* 0x17 (not possible) */
+ SQLITE_FLOAT, /* 0x18 FLOAT + BLOB */
+ SQLITE_NULL, /* 0x19 (not possible) */
+ SQLITE_FLOAT, /* 0x1a (not possible) */
+ SQLITE_NULL, /* 0x1b (not possible) */
+ SQLITE_INTEGER, /* 0x1c (not possible) */
+ SQLITE_NULL, /* 0x1d (not possible) */
+ SQLITE_INTEGER, /* 0x1e (not possible) */
+ SQLITE_NULL, /* 0x1f (not possible) */
+ SQLITE_FLOAT, /* 0x20 INTREAL */
+ SQLITE_NULL, /* 0x21 (not possible) */
+ SQLITE_TEXT, /* 0x22 INTREAL + TEXT */
+ SQLITE_NULL, /* 0x23 (not possible) */
+ SQLITE_FLOAT, /* 0x24 (not possible) */
+ SQLITE_NULL, /* 0x25 (not possible) */
+ SQLITE_FLOAT, /* 0x26 (not possible) */
+ SQLITE_NULL, /* 0x27 (not possible) */
+ SQLITE_FLOAT, /* 0x28 (not possible) */
+ SQLITE_NULL, /* 0x29 (not possible) */
+ SQLITE_FLOAT, /* 0x2a (not possible) */
+ SQLITE_NULL, /* 0x2b (not possible) */
+ SQLITE_FLOAT, /* 0x2c (not possible) */
+ SQLITE_NULL, /* 0x2d (not possible) */
+ SQLITE_FLOAT, /* 0x2e (not possible) */
+ SQLITE_NULL, /* 0x2f (not possible) */
+ SQLITE_BLOB, /* 0x30 (not possible) */
+ SQLITE_NULL, /* 0x31 (not possible) */
+ SQLITE_TEXT, /* 0x32 (not possible) */
+ SQLITE_NULL, /* 0x33 (not possible) */
+ SQLITE_FLOAT, /* 0x34 (not possible) */
+ SQLITE_NULL, /* 0x35 (not possible) */
+ SQLITE_FLOAT, /* 0x36 (not possible) */
+ SQLITE_NULL, /* 0x37 (not possible) */
+ SQLITE_FLOAT, /* 0x38 (not possible) */
+ SQLITE_NULL, /* 0x39 (not possible) */
+ SQLITE_FLOAT, /* 0x3a (not possible) */
+ SQLITE_NULL, /* 0x3b (not possible) */
+ SQLITE_FLOAT, /* 0x3c (not possible) */
+ SQLITE_NULL, /* 0x3d (not possible) */
+ SQLITE_FLOAT, /* 0x3e (not possible) */
+ SQLITE_NULL, /* 0x3f (not possible) */
+ };
+#ifdef SQLITE_DEBUG
+ {
+ int eType = SQLITE_BLOB;
+ if( pVal->flags & MEM_Null ){
+ eType = SQLITE_NULL;
+ }else if( pVal->flags & (MEM_Real|MEM_IntReal) ){
+ eType = SQLITE_FLOAT;
+ }else if( pVal->flags & MEM_Int ){
+ eType = SQLITE_INTEGER;
+ }else if( pVal->flags & MEM_Str ){
+ eType = SQLITE_TEXT;
+ }
+ assert( eType == aType[pVal->flags&MEM_AffMask] );
+ }
+#endif
+ return aType[pVal->flags&MEM_AffMask];
+}
+
+/* Return true if a parameter to xUpdate represents an unchanged column */
+SQLITE_API int sqlite3_value_nochange(sqlite3_value *pVal){
+ return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
+}
+
+/* Return true if a parameter value originated from an sqlite3_bind() */
+SQLITE_API int sqlite3_value_frombind(sqlite3_value *pVal){
+ return (pVal->flags&MEM_FromBind)!=0;
+}
+
+/* Make a copy of an sqlite3_value object
+*/
+SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
+ sqlite3_value *pNew;
+ if( pOrig==0 ) return 0;
+ pNew = sqlite3_malloc( sizeof(*pNew) );
+ if( pNew==0 ) return 0;
+ memset(pNew, 0, sizeof(*pNew));
+ memcpy(pNew, pOrig, MEMCELLSIZE);
+ pNew->flags &= ~MEM_Dyn;
+ pNew->db = 0;
+ if( pNew->flags&(MEM_Str|MEM_Blob) ){
+ pNew->flags &= ~(MEM_Static|MEM_Dyn);
+ pNew->flags |= MEM_Ephem;
+ if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
+ sqlite3ValueFree(pNew);
+ pNew = 0;
+ }
+ }
+ return pNew;
+}
+
+/* Destroy an sqlite3_value object previously obtained from
+** sqlite3_value_dup().
+*/
+SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
+ sqlite3ValueFree(pOld);
+}
+
+
+/**************************** sqlite3_result_ *******************************
+** The following routines are used by user-defined functions to specify
+** the function result.
+**
+** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
+** result as a string or blob but if the string or blob is too large, it
+** then sets the error code to SQLITE_TOOBIG
+**
+** The invokeValueDestructor(P,X) routine invokes destructor function X()
+** on value P is not going to be used and need to be destroyed.
+*/
+static void setResultStrOrError(
+ sqlite3_context *pCtx, /* Function context */
+ const char *z, /* String pointer */
+ int n, /* Bytes in string, or negative */
+ u8 enc, /* Encoding of z. 0 for BLOBs */
+ void (*xDel)(void*) /* Destructor function */
+){
+ if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
+ sqlite3_result_error_toobig(pCtx);
+ }
+}
+static int invokeValueDestructor(
+ const void *p, /* Value to destroy */
+ void (*xDel)(void*), /* The destructor */
+ sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
+){
+ assert( xDel!=SQLITE_DYNAMIC );
+ if( xDel==0 ){
+ /* noop */
+ }else if( xDel==SQLITE_TRANSIENT ){
+ /* noop */
+ }else{
+ xDel((void*)p);
+ }
+ if( pCtx ) sqlite3_result_error_toobig(pCtx);
+ return SQLITE_TOOBIG;
+}
+SQLITE_API void sqlite3_result_blob(
+ sqlite3_context *pCtx,
+ const void *z,
+ int n,
+ void (*xDel)(void *)
+){
+ assert( n>=0 );
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ setResultStrOrError(pCtx, z, n, 0, xDel);
+}
+SQLITE_API void sqlite3_result_blob64(
+ sqlite3_context *pCtx,
+ const void *z,
+ sqlite3_uint64 n,
+ void (*xDel)(void *)
+){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ assert( xDel!=SQLITE_DYNAMIC );
+ if( n>0x7fffffff ){
+ (void)invokeValueDestructor(z, xDel, pCtx);
+ }else{
+ setResultStrOrError(pCtx, z, (int)n, 0, xDel);
+ }
+}
+SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
+}
+SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ pCtx->isError = SQLITE_ERROR;
+ sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
+}
+#ifndef SQLITE_OMIT_UTF16
+SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ pCtx->isError = SQLITE_ERROR;
+ sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
+}
+#endif
+SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
+}
+SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
+}
+SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ sqlite3VdbeMemSetNull(pCtx->pOut);
+}
+SQLITE_API void sqlite3_result_pointer(
+ sqlite3_context *pCtx,
+ void *pPtr,
+ const char *zPType,
+ void (*xDestructor)(void*)
+){
+ Mem *pOut = pCtx->pOut;
+ assert( sqlite3_mutex_held(pOut->db->mutex) );
+ sqlite3VdbeMemRelease(pOut);
+ pOut->flags = MEM_Null;
+ sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
+}
+SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
+ Mem *pOut = pCtx->pOut;
+ assert( sqlite3_mutex_held(pOut->db->mutex) );
+ pOut->eSubtype = eSubtype & 0xff;
+ pOut->flags |= MEM_Subtype;
+}
+SQLITE_API void sqlite3_result_text(
+ sqlite3_context *pCtx,
+ const char *z,
+ int n,
+ void (*xDel)(void *)
+){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
+}
+SQLITE_API void sqlite3_result_text64(
+ sqlite3_context *pCtx,
+ const char *z,
+ sqlite3_uint64 n,
+ void (*xDel)(void *),
+ unsigned char enc
+){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ assert( xDel!=SQLITE_DYNAMIC );
+ if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
+ if( n>0x7fffffff ){
+ (void)invokeValueDestructor(z, xDel, pCtx);
+ }else{
+ setResultStrOrError(pCtx, z, (int)n, enc, xDel);
+ }
+}
+#ifndef SQLITE_OMIT_UTF16
+SQLITE_API void sqlite3_result_text16(
+ sqlite3_context *pCtx,
+ const void *z,
+ int n,
+ void (*xDel)(void *)
+){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
+}
+SQLITE_API void sqlite3_result_text16be(
+ sqlite3_context *pCtx,
+ const void *z,
+ int n,
+ void (*xDel)(void *)
+){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
+}
+SQLITE_API void sqlite3_result_text16le(
+ sqlite3_context *pCtx,
+ const void *z,
+ int n,
+ void (*xDel)(void *)
+){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
+}
+#endif /* SQLITE_OMIT_UTF16 */
+SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ sqlite3VdbeMemCopy(pCtx->pOut, pValue);
+}
+SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
+}
+SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
+ Mem *pOut = pCtx->pOut;
+ assert( sqlite3_mutex_held(pOut->db->mutex) );
+ if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
+ return SQLITE_TOOBIG;
+ }
+ sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
+ return SQLITE_OK;
+}
+SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
+ pCtx->isError = errCode ? errCode : -1;
+#ifdef SQLITE_DEBUG
+ if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
+#endif
+ if( pCtx->pOut->flags & MEM_Null ){
+ sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
+ SQLITE_UTF8, SQLITE_STATIC);
+ }
+}
+
+/* Force an SQLITE_TOOBIG error. */
+SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ pCtx->isError = SQLITE_TOOBIG;
+ sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
+ SQLITE_UTF8, SQLITE_STATIC);
+}
+
+/* An SQLITE_NOMEM error. */
+SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ sqlite3VdbeMemSetNull(pCtx->pOut);
+ pCtx->isError = SQLITE_NOMEM_BKPT;
+ sqlite3OomFault(pCtx->pOut->db);
+}
+
+#ifndef SQLITE_UNTESTABLE
+/* Force the INT64 value currently stored as the result to be
+** a MEM_IntReal value. See the SQLITE_TESTCTRL_RESULT_INTREAL
+** test-control.
+*/
+SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context *pCtx){
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+ if( pCtx->pOut->flags & MEM_Int ){
+ pCtx->pOut->flags &= ~MEM_Int;
+ pCtx->pOut->flags |= MEM_IntReal;
+ }
+}
+#endif
+
+
+/*
+** This function is called after a transaction has been committed. It
+** invokes callbacks registered with sqlite3_wal_hook() as required.
+*/
+static int doWalCallbacks(sqlite3 *db){
+ int rc = SQLITE_OK;
+#ifndef SQLITE_OMIT_WAL
+ int i;
+ for(i=0; i<db->nDb; i++){
+ Btree *pBt = db->aDb[i].pBt;
+ if( pBt ){
+ int nEntry;
+ sqlite3BtreeEnter(pBt);
+ nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
+ sqlite3BtreeLeave(pBt);
+ if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
+ rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
+ }
+ }
+ }
+#endif
+ return rc;
+}
+
+
+/*
+** Execute the statement pStmt, either until a row of data is ready, the
+** statement is completely executed or an error occurs.
+**
+** This routine implements the bulk of the logic behind the sqlite_step()
+** API. The only thing omitted is the automatic recompile if a
+** schema change has occurred. That detail is handled by the
+** outer sqlite3_step() wrapper procedure.
+*/
+static int sqlite3Step(Vdbe *p){
+ sqlite3 *db;
+ int rc;
+
+ assert(p);
+ if( p->magic!=VDBE_MAGIC_RUN ){
+ /* We used to require that sqlite3_reset() be called before retrying
+ ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
+ ** with version 3.7.0, we changed this so that sqlite3_reset() would
+ ** be called automatically instead of throwing the SQLITE_MISUSE error.
+ ** This "automatic-reset" change is not technically an incompatibility,
+ ** since any application that receives an SQLITE_MISUSE is broken by
+ ** definition.
+ **
+ ** Nevertheless, some published applications that were originally written
+ ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
+ ** returns, and those were broken by the automatic-reset change. As a
+ ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
+ ** legacy behavior of returning SQLITE_MISUSE for cases where the
+ ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
+ ** or SQLITE_BUSY error.
+ */
+#ifdef SQLITE_OMIT_AUTORESET
+ if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
+ sqlite3_reset((sqlite3_stmt*)p);
+ }else{
+ return SQLITE_MISUSE_BKPT;
+ }
+#else
+ sqlite3_reset((sqlite3_stmt*)p);
+#endif
+ }
+
+ /* Check that malloc() has not failed. If it has, return early. */
+ db = p->db;
+ if( db->mallocFailed ){
+ p->rc = SQLITE_NOMEM;
+ return SQLITE_NOMEM_BKPT;
+ }
+
+ if( p->pc<0 && p->expired ){
+ p->rc = SQLITE_SCHEMA;
+ rc = SQLITE_ERROR;
+ if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
+ /* If this statement was prepared using saved SQL and an
+ ** error has occurred, then return the error code in p->rc to the
+ ** caller. Set the error code in the database handle to the same value.
+ */
+ rc = sqlite3VdbeTransferError(p);
+ }
+ goto end_of_step;
+ }
+ if( p->pc<0 ){
+ /* If there are no other statements currently running, then
+ ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
+ ** from interrupting a statement that has not yet started.
+ */
+ if( db->nVdbeActive==0 ){
+ AtomicStore(&db->u1.isInterrupted, 0);
+ }
+
+ assert( db->nVdbeWrite>0 || db->autoCommit==0
+ || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
+ );
+
+#ifndef SQLITE_OMIT_TRACE
+ if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0
+ && !db->init.busy && p->zSql ){
+ sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
+ }else{
+ assert( p->startTime==0 );
+ }
+#endif
+
+ db->nVdbeActive++;
+ if( p->readOnly==0 ) db->nVdbeWrite++;
+ if( p->bIsReader ) db->nVdbeRead++;
+ p->pc = 0;
+ }
+#ifdef SQLITE_DEBUG
+ p->rcApp = SQLITE_OK;
+#endif
+#ifndef SQLITE_OMIT_EXPLAIN
+ if( p->explain ){
+ rc = sqlite3VdbeList(p);
+ }else
+#endif /* SQLITE_OMIT_EXPLAIN */
+ {
+ db->nVdbeExec++;
+ rc = sqlite3VdbeExec(p);
+ db->nVdbeExec--;
+ }
+
+ if( rc!=SQLITE_ROW ){
+#ifndef SQLITE_OMIT_TRACE
+ /* If the statement completed successfully, invoke the profile callback */
+ checkProfileCallback(db, p);
+#endif
+
+ if( rc==SQLITE_DONE && db->autoCommit ){
+ assert( p->rc==SQLITE_OK );
+ p->rc = doWalCallbacks(db);
+ if( p->rc!=SQLITE_OK ){
+ rc = SQLITE_ERROR;
+ }
+ }else if( rc!=SQLITE_DONE && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
+ /* If this statement was prepared using saved SQL and an
+ ** error has occurred, then return the error code in p->rc to the
+ ** caller. Set the error code in the database handle to the same value.
+ */
+ rc = sqlite3VdbeTransferError(p);
+ }
+ }
+
+ db->errCode = rc;
+ if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
+ p->rc = SQLITE_NOMEM_BKPT;
+ if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ) rc = p->rc;
+ }
+end_of_step:
+ /* There are only a limited number of result codes allowed from the
+ ** statements prepared using the legacy sqlite3_prepare() interface */
+ assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
+ || rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
+ || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
+ );
+ return (rc&db->errMask);
+}
+
+/*
+** This is the top-level implementation of sqlite3_step(). Call
+** sqlite3Step() to do most of the work. If a schema error occurs,
+** call sqlite3Reprepare() and try again.
+*/
+SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
+ int rc = SQLITE_OK; /* Result from sqlite3Step() */
+ Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
+ int cnt = 0; /* Counter to prevent infinite loop of reprepares */
+ sqlite3 *db; /* The database connection */
+
+ if( vdbeSafetyNotNull(v) ){
+ return SQLITE_MISUSE_BKPT;
+ }
+ db = v->db;
+ sqlite3_mutex_enter(db->mutex);
+ v->doingRerun = 0;
+ while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
+ && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
+ int savedPc = v->pc;
+ rc = sqlite3Reprepare(v);
+ if( rc!=SQLITE_OK ){
+ /* This case occurs after failing to recompile an sql statement.
+ ** The error message from the SQL compiler has already been loaded
+ ** into the database handle. This block copies the error message
+ ** from the database handle into the statement and sets the statement
+ ** program counter to 0 to ensure that when the statement is
+ ** finalized or reset the parser error message is available via
+ ** sqlite3_errmsg() and sqlite3_errcode().
+ */
+ const char *zErr = (const char *)sqlite3_value_text(db->pErr);
+ sqlite3DbFree(db, v->zErrMsg);
+ if( !db->mallocFailed ){
+ v->zErrMsg = sqlite3DbStrDup(db, zErr);
+ v->rc = rc = sqlite3ApiExit(db, rc);
+ } else {
+ v->zErrMsg = 0;
+ v->rc = rc = SQLITE_NOMEM_BKPT;
+ }
+ break;
+ }
+ sqlite3_reset(pStmt);
+ if( savedPc>=0 ) v->doingRerun = 1;
+ assert( v->expired==0 );
+ }
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+
+/*
+** Extract the user data from a sqlite3_context structure and return a
+** pointer to it.
+*/
+SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
+ assert( p && p->pFunc );
+ return p->pFunc->pUserData;
+}
+
+/*
+** Extract the user data from a sqlite3_context structure and return a
+** pointer to it.
+**
+** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
+** returns a copy of the pointer to the database connection (the 1st
+** parameter) of the sqlite3_create_function() and
+** sqlite3_create_function16() routines that originally registered the
+** application defined function.
+*/
+SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
+ assert( p && p->pOut );
+ return p->pOut->db;
+}
+
+/*
+** If this routine is invoked from within an xColumn method of a virtual
+** table, then it returns true if and only if the the call is during an
+** UPDATE operation and the value of the column will not be modified
+** by the UPDATE.
+**
+** If this routine is called from any context other than within the
+** xColumn method of a virtual table, then the return value is meaningless
+** and arbitrary.
+**
+** Virtual table implements might use this routine to optimize their
+** performance by substituting a NULL result, or some other light-weight
+** value, as a signal to the xUpdate routine that the column is unchanged.
+*/
+SQLITE_API int sqlite3_vtab_nochange(sqlite3_context *p){
+ assert( p );
+ return sqlite3_value_nochange(p->pOut);
+}
+
+/*
+** Return the current time for a statement. If the current time
+** is requested more than once within the same run of a single prepared
+** statement, the exact same time is returned for each invocation regardless
+** of the amount of time that elapses between invocations. In other words,
+** the time returned is always the time of the first call.
+*/
+SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
+ int rc;
+#ifndef SQLITE_ENABLE_STAT4
+ sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
+ assert( p->pVdbe!=0 );
+#else
+ sqlite3_int64 iTime = 0;
+ sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
+#endif
+ if( *piTime==0 ){
+ rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
+ if( rc ) *piTime = 0;
+ }
+ return *piTime;
+}
+
+/*
+** Create a new aggregate context for p and return a pointer to
+** its pMem->z element.
+*/
+static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
+ Mem *pMem = p->pMem;
+ assert( (pMem->flags & MEM_Agg)==0 );
+ if( nByte<=0 ){
+ sqlite3VdbeMemSetNull(pMem);
+ pMem->z = 0;
+ }else{
+ sqlite3VdbeMemClearAndResize(pMem, nByte);
+ pMem->flags = MEM_Agg;
+ pMem->u.pDef = p->pFunc;
+ if( pMem->z ){
+ memset(pMem->z, 0, nByte);
+ }
+ }
+ return (void*)pMem->z;
+}
+
+/*
+** Allocate or return the aggregate context for a user function. A new
+** context is allocated on the first call. Subsequent calls return the
+** same context that was returned on prior calls.
+*/
+SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
+ assert( p && p->pFunc && p->pFunc->xFinalize );
+ assert( sqlite3_mutex_held(p->pOut->db->mutex) );
+ testcase( nByte<0 );
+ if( (p->pMem->flags & MEM_Agg)==0 ){
+ return createAggContext(p, nByte);
+ }else{
+ return (void*)p->pMem->z;
+ }
+}
+
+/*
+** Return the auxiliary data pointer, if any, for the iArg'th argument to
+** the user-function defined by pCtx.
+**
+** The left-most argument is 0.
+**
+** Undocumented behavior: If iArg is negative then access a cache of
+** auxiliary data pointers that is available to all functions within a
+** single prepared statement. The iArg values must match.
+*/
+SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
+ AuxData *pAuxData;
+
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+#if SQLITE_ENABLE_STAT4
+ if( pCtx->pVdbe==0 ) return 0;
+#else
+ assert( pCtx->pVdbe!=0 );
+#endif
+ for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
+ if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
+ return pAuxData->pAux;
+ }
+ }
+ return 0;
+}
+
+/*
+** Set the auxiliary data pointer and delete function, for the iArg'th
+** argument to the user-function defined by pCtx. Any previous value is
+** deleted by calling the delete function specified when it was set.
+**
+** The left-most argument is 0.
+**
+** Undocumented behavior: If iArg is negative then make the data available
+** to all functions within the current prepared statement using iArg as an
+** access code.
+*/
+SQLITE_API void sqlite3_set_auxdata(
+ sqlite3_context *pCtx,
+ int iArg,
+ void *pAux,
+ void (*xDelete)(void*)
+){
+ AuxData *pAuxData;
+ Vdbe *pVdbe = pCtx->pVdbe;
+
+ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
+#ifdef SQLITE_ENABLE_STAT4
+ if( pVdbe==0 ) goto failed;
+#else
+ assert( pVdbe!=0 );
+#endif
+
+ for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
+ if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
+ break;
+ }
+ }
+ if( pAuxData==0 ){
+ pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
+ if( !pAuxData ) goto failed;
+ pAuxData->iAuxOp = pCtx->iOp;
+ pAuxData->iAuxArg = iArg;
+ pAuxData->pNextAux = pVdbe->pAuxData;
+ pVdbe->pAuxData = pAuxData;
+ if( pCtx->isError==0 ) pCtx->isError = -1;
+ }else if( pAuxData->xDeleteAux ){
+ pAuxData->xDeleteAux(pAuxData->pAux);
+ }
+
+ pAuxData->pAux = pAux;
+ pAuxData->xDeleteAux = xDelete;
+ return;
+
+failed:
+ if( xDelete ){
+ xDelete(pAux);
+ }
+}
+
+#ifndef SQLITE_OMIT_DEPRECATED
+/*
+** Return the number of times the Step function of an aggregate has been
+** called.
+**
+** This function is deprecated. Do not use it for new code. It is
+** provide only to avoid breaking legacy code. New aggregate function
+** implementations should keep their own counts within their aggregate
+** context.
+*/
+SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
+ assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
+ return p->pMem->n;
+}
+#endif
+
+/*
+** Return the number of columns in the result set for the statement pStmt.
+*/
+SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
+ Vdbe *pVm = (Vdbe *)pStmt;
+ return pVm ? pVm->nResColumn : 0;
+}
+
+/*
+** Return the number of values available from the current row of the
+** currently executing statement pStmt.
+*/
+SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
+ Vdbe *pVm = (Vdbe *)pStmt;
+ if( pVm==0 || pVm->pResultSet==0 ) return 0;
+ return pVm->nResColumn;
+}
+
+/*
+** Return a pointer to static memory containing an SQL NULL value.
+*/
+static const Mem *columnNullValue(void){
+ /* Even though the Mem structure contains an element
+ ** of type i64, on certain architectures (x86) with certain compiler
+ ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
+ ** instead of an 8-byte one. This all works fine, except that when
+ ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
+ ** that a Mem structure is located on an 8-byte boundary. To prevent
+ ** these assert()s from failing, when building with SQLITE_DEBUG defined
+ ** using gcc, we force nullMem to be 8-byte aligned using the magical
+ ** __attribute__((aligned(8))) macro. */
+ static const Mem nullMem
+#if defined(SQLITE_DEBUG) && defined(__GNUC__)
+ __attribute__((aligned(8)))
+#endif
+ = {
+ /* .u = */ {0},
+ /* .flags = */ (u16)MEM_Null,
+ /* .enc = */ (u8)0,
+ /* .eSubtype = */ (u8)0,
+ /* .n = */ (int)0,
+ /* .z = */ (char*)0,
+ /* .zMalloc = */ (char*)0,
+ /* .szMalloc = */ (int)0,
+ /* .uTemp = */ (u32)0,
+ /* .db = */ (sqlite3*)0,
+ /* .xDel = */ (void(*)(void*))0,
+#ifdef SQLITE_DEBUG
+ /* .pScopyFrom = */ (Mem*)0,
+ /* .mScopyFlags= */ 0,
+#endif
+ };
+ return &nullMem;
+}
+
+/*
+** Check to see if column iCol of the given statement is valid. If
+** it is, return a pointer to the Mem for the value of that column.
+** If iCol is not valid, return a pointer to a Mem which has a value
+** of NULL.
+*/
+static Mem *columnMem(sqlite3_stmt *pStmt, int i){
+ Vdbe *pVm;
+ Mem *pOut;
+
+ pVm = (Vdbe *)pStmt;
+ if( pVm==0 ) return (Mem*)columnNullValue();
+ assert( pVm->db );
+ sqlite3_mutex_enter(pVm->db->mutex);
+ if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
+ pOut = &pVm->pResultSet[i];
+ }else{
+ sqlite3Error(pVm->db, SQLITE_RANGE);
+ pOut = (Mem*)columnNullValue();
+ }
+ return pOut;
+}
+
+/*
+** This function is called after invoking an sqlite3_value_XXX function on a
+** column value (i.e. a value returned by evaluating an SQL expression in the
+** select list of a SELECT statement) that may cause a malloc() failure. If
+** malloc() has failed, the threads mallocFailed flag is cleared and the result
+** code of statement pStmt set to SQLITE_NOMEM.
+**
+** Specifically, this is called from within:
+**
+** sqlite3_column_int()
+** sqlite3_column_int64()
+** sqlite3_column_text()
+** sqlite3_column_text16()
+** sqlite3_column_real()
+** sqlite3_column_bytes()
+** sqlite3_column_bytes16()
+** sqiite3_column_blob()
+*/
+static void columnMallocFailure(sqlite3_stmt *pStmt)
+{
+ /* If malloc() failed during an encoding conversion within an
+ ** sqlite3_column_XXX API, then set the return code of the statement to
+ ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
+ ** and _finalize() will return NOMEM.
+ */
+ Vdbe *p = (Vdbe *)pStmt;
+ if( p ){
+ assert( p->db!=0 );
+ assert( sqlite3_mutex_held(p->db->mutex) );
+ p->rc = sqlite3ApiExit(p->db, p->rc);
+ sqlite3_mutex_leave(p->db->mutex);
+ }
+}
+
+/**************************** sqlite3_column_ *******************************
+** The following routines are used to access elements of the current row
+** in the result set.
+*/
+SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
+ const void *val;
+ val = sqlite3_value_blob( columnMem(pStmt,i) );
+ /* Even though there is no encoding conversion, value_blob() might
+ ** need to call malloc() to expand the result of a zeroblob()
+ ** expression.
+ */
+ columnMallocFailure(pStmt);
+ return val;
+}
+SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
+ int val = sqlite3_value_bytes( columnMem(pStmt,i) );
+ columnMallocFailure(pStmt);
+ return val;
+}
+SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
+ int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
+ columnMallocFailure(pStmt);
+ return val;
+}
+SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
+ double val = sqlite3_value_double( columnMem(pStmt,i) );
+ columnMallocFailure(pStmt);
+ return val;
+}
+SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
+ int val = sqlite3_value_int( columnMem(pStmt,i) );
+ columnMallocFailure(pStmt);
+ return val;
+}
+SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
+ sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
+ columnMallocFailure(pStmt);
+ return val;
+}
+SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
+ const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
+ columnMallocFailure(pStmt);
+ return val;
+}
+SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
+ Mem *pOut = columnMem(pStmt, i);
+ if( pOut->flags&MEM_Static ){
+ pOut->flags &= ~MEM_Static;
+ pOut->flags |= MEM_Ephem;
+ }
+ columnMallocFailure(pStmt);
+ return (sqlite3_value *)pOut;
+}
+#ifndef SQLITE_OMIT_UTF16
+SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
+ const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
+ columnMallocFailure(pStmt);
+ return val;
+}
+#endif /* SQLITE_OMIT_UTF16 */
+SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
+ int iType = sqlite3_value_type( columnMem(pStmt,i) );
+ columnMallocFailure(pStmt);
+ return iType;
+}
+
+/*
+** Convert the N-th element of pStmt->pColName[] into a string using
+** xFunc() then return that string. If N is out of range, return 0.
+**
+** There are up to 5 names for each column. useType determines which
+** name is returned. Here are the names:
+**
+** 0 The column name as it should be displayed for output
+** 1 The datatype name for the column
+** 2 The name of the database that the column derives from
+** 3 The name of the table that the column derives from
+** 4 The name of the table column that the result column derives from
+**
+** If the result is not a simple column reference (if it is an expression
+** or a constant) then useTypes 2, 3, and 4 return NULL.
+*/
+static const void *columnName(
+ sqlite3_stmt *pStmt, /* The statement */
+ int N, /* Which column to get the name for */
+ int useUtf16, /* True to return the name as UTF16 */
+ int useType /* What type of name */
+){
+ const void *ret;
+ Vdbe *p;
+ int n;
+ sqlite3 *db;
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( pStmt==0 ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ ret = 0;
+ p = (Vdbe *)pStmt;
+ db = p->db;
+ assert( db!=0 );
+ n = sqlite3_column_count(pStmt);
+ if( N<n && N>=0 ){
+ N += useType*n;
+ sqlite3_mutex_enter(db->mutex);
+ assert( db->mallocFailed==0 );
+#ifndef SQLITE_OMIT_UTF16
+ if( useUtf16 ){
+ ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);
+ }else
+#endif
+ {
+ ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);
+ }
+ /* A malloc may have failed inside of the _text() call. If this
+ ** is the case, clear the mallocFailed flag and return NULL.
+ */
+ if( db->mallocFailed ){
+ sqlite3OomClear(db);
+ ret = 0;
+ }
+ sqlite3_mutex_leave(db->mutex);
+ }
+ return ret;
+}
+
+/*
+** Return the name of the Nth column of the result set returned by SQL
+** statement pStmt.
+*/
+SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
+ return columnName(pStmt, N, 0, COLNAME_NAME);
+}
+#ifndef SQLITE_OMIT_UTF16
+SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
+ return columnName(pStmt, N, 1, COLNAME_NAME);
+}
+#endif
+
+/*
+** Constraint: If you have ENABLE_COLUMN_METADATA then you must
+** not define OMIT_DECLTYPE.
+*/
+#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
+# error "Must not define both SQLITE_OMIT_DECLTYPE \
+ and SQLITE_ENABLE_COLUMN_METADATA"
+#endif
+
+#ifndef SQLITE_OMIT_DECLTYPE
+/*
+** Return the column declaration type (if applicable) of the 'i'th column
+** of the result set of SQL statement pStmt.
+*/
+SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
+ return columnName(pStmt, N, 0, COLNAME_DECLTYPE);
+}
+#ifndef SQLITE_OMIT_UTF16
+SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
+ return columnName(pStmt, N, 1, COLNAME_DECLTYPE);
+}
+#endif /* SQLITE_OMIT_UTF16 */
+#endif /* SQLITE_OMIT_DECLTYPE */
+
+#ifdef SQLITE_ENABLE_COLUMN_METADATA
+/*
+** Return the name of the database from which a result column derives.
+** NULL is returned if the result column is an expression or constant or
+** anything else which is not an unambiguous reference to a database column.
+*/
+SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
+ return columnName(pStmt, N, 0, COLNAME_DATABASE);
+}
+#ifndef SQLITE_OMIT_UTF16
+SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
+ return columnName(pStmt, N, 1, COLNAME_DATABASE);
+}
+#endif /* SQLITE_OMIT_UTF16 */
+
+/*
+** Return the name of the table from which a result column derives.
+** NULL is returned if the result column is an expression or constant or
+** anything else which is not an unambiguous reference to a database column.
+*/
+SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
+ return columnName(pStmt, N, 0, COLNAME_TABLE);
+}
+#ifndef SQLITE_OMIT_UTF16
+SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
+ return columnName(pStmt, N, 1, COLNAME_TABLE);
+}
+#endif /* SQLITE_OMIT_UTF16 */
+
+/*
+** Return the name of the table column from which a result column derives.
+** NULL is returned if the result column is an expression or constant or
+** anything else which is not an unambiguous reference to a database column.
+*/
+SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
+ return columnName(pStmt, N, 0, COLNAME_COLUMN);
+}
+#ifndef SQLITE_OMIT_UTF16
+SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
+ return columnName(pStmt, N, 1, COLNAME_COLUMN);
+}
+#endif /* SQLITE_OMIT_UTF16 */
+#endif /* SQLITE_ENABLE_COLUMN_METADATA */
+
+
+/******************************* sqlite3_bind_ ***************************
+**
+** Routines used to attach values to wildcards in a compiled SQL statement.
+*/
+/*
+** Unbind the value bound to variable i in virtual machine p. This is the
+** the same as binding a NULL value to the column. If the "i" parameter is
+** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
+**
+** A successful evaluation of this routine acquires the mutex on p.
+** the mutex is released if any kind of error occurs.
+**
+** The error code stored in database p->db is overwritten with the return
+** value in any case.
+*/
+static int vdbeUnbind(Vdbe *p, int i){
+ Mem *pVar;
+ if( vdbeSafetyNotNull(p) ){
+ return SQLITE_MISUSE_BKPT;
+ }
+ sqlite3_mutex_enter(p->db->mutex);
+ if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
+ sqlite3Error(p->db, SQLITE_MISUSE);
+ sqlite3_mutex_leave(p->db->mutex);
+ sqlite3_log(SQLITE_MISUSE,
+ "bind on a busy prepared statement: [%s]", p->zSql);
+ return SQLITE_MISUSE_BKPT;
+ }
+ if( i<1 || i>p->nVar ){
+ sqlite3Error(p->db, SQLITE_RANGE);
+ sqlite3_mutex_leave(p->db->mutex);
+ return SQLITE_RANGE;
+ }
+ i--;
+ pVar = &p->aVar[i];
+ sqlite3VdbeMemRelease(pVar);
+ pVar->flags = MEM_Null;
+ p->db->errCode = SQLITE_OK;
+
+ /* If the bit corresponding to this variable in Vdbe.expmask is set, then
+ ** binding a new value to this variable invalidates the current query plan.
+ **
+ ** IMPLEMENTATION-OF: R-57496-20354 If the specific value bound to a host
+ ** parameter in the WHERE clause might influence the choice of query plan
+ ** for a statement, then the statement will be automatically recompiled,
+ ** as if there had been a schema change, on the first sqlite3_step() call
+ ** following any change to the bindings of that parameter.
+ */
+ assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
+ if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
+ p->expired = 1;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Bind a text or BLOB value.
+*/
+static int bindText(
+ sqlite3_stmt *pStmt, /* The statement to bind against */
+ int i, /* Index of the parameter to bind */
+ const void *zData, /* Pointer to the data to be bound */
+ int nData, /* Number of bytes of data to be bound */
+ void (*xDel)(void*), /* Destructor for the data */
+ u8 encoding /* Encoding for the data */
+){
+ Vdbe *p = (Vdbe *)pStmt;
+ Mem *pVar;
+ int rc;
+
+ rc = vdbeUnbind(p, i);
+ if( rc==SQLITE_OK ){
+ if( zData!=0 ){
+ pVar = &p->aVar[i-1];
+ rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
+ if( rc==SQLITE_OK && encoding!=0 ){
+ rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
+ }
+ if( rc ){
+ sqlite3Error(p->db, rc);
+ rc = sqlite3ApiExit(p->db, rc);
+ }
+ }
+ sqlite3_mutex_leave(p->db->mutex);
+ }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
+ xDel((void*)zData);
+ }
+ return rc;
+}
+
+
+/*
+** Bind a blob value to an SQL statement variable.
+*/
+SQLITE_API int sqlite3_bind_blob(
+ sqlite3_stmt *pStmt,
+ int i,
+ const void *zData,
+ int nData,
+ void (*xDel)(void*)
+){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( nData<0 ) return SQLITE_MISUSE_BKPT;
+#endif
+ return bindText(pStmt, i, zData, nData, xDel, 0);
+}
+SQLITE_API int sqlite3_bind_blob64(
+ sqlite3_stmt *pStmt,
+ int i,
+ const void *zData,
+ sqlite3_uint64 nData,
+ void (*xDel)(void*)
+){
+ assert( xDel!=SQLITE_DYNAMIC );
+ if( nData>0x7fffffff ){
+ return invokeValueDestructor(zData, xDel, 0);
+ }else{
+ return bindText(pStmt, i, zData, (int)nData, xDel, 0);
+ }
+}
+SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
+ int rc;
+ Vdbe *p = (Vdbe *)pStmt;
+ rc = vdbeUnbind(p, i);
+ if( rc==SQLITE_OK ){
+ sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
+ sqlite3_mutex_leave(p->db->mutex);
+ }
+ return rc;
+}
+SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
+ return sqlite3_bind_int64(p, i, (i64)iValue);
+}
+SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
+ int rc;
+ Vdbe *p = (Vdbe *)pStmt;
+ rc = vdbeUnbind(p, i);
+ if( rc==SQLITE_OK ){
+ sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
+ sqlite3_mutex_leave(p->db->mutex);
+ }
+ return rc;
+}
+SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
+ int rc;
+ Vdbe *p = (Vdbe*)pStmt;
+ rc = vdbeUnbind(p, i);
+ if( rc==SQLITE_OK ){
+ sqlite3_mutex_leave(p->db->mutex);
+ }
+ return rc;
+}
+SQLITE_API int sqlite3_bind_pointer(
+ sqlite3_stmt *pStmt,
+ int i,
+ void *pPtr,
+ const char *zPTtype,
+ void (*xDestructor)(void*)
+){
+ int rc;
+ Vdbe *p = (Vdbe*)pStmt;
+ rc = vdbeUnbind(p, i);
+ if( rc==SQLITE_OK ){
+ sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
+ sqlite3_mutex_leave(p->db->mutex);
+ }else if( xDestructor ){
+ xDestructor(pPtr);
+ }
+ return rc;
+}
+SQLITE_API int sqlite3_bind_text(
+ sqlite3_stmt *pStmt,
+ int i,
+ const char *zData,
+ int nData,
+ void (*xDel)(void*)
+){
+ return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
+}
+SQLITE_API int sqlite3_bind_text64(
+ sqlite3_stmt *pStmt,
+ int i,
+ const char *zData,
+ sqlite3_uint64 nData,
+ void (*xDel)(void*),
+ unsigned char enc
+){
+ assert( xDel!=SQLITE_DYNAMIC );
+ if( nData>0x7fffffff ){
+ return invokeValueDestructor(zData, xDel, 0);
+ }else{
+ if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
+ return bindText(pStmt, i, zData, (int)nData, xDel, enc);
+ }
+}
+#ifndef SQLITE_OMIT_UTF16
+SQLITE_API int sqlite3_bind_text16(
+ sqlite3_stmt *pStmt,
+ int i,
+ const void *zData,
+ int nData,
+ void (*xDel)(void*)
+){
+ return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
+}
+#endif /* SQLITE_OMIT_UTF16 */
+SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
+ int rc;
+ switch( sqlite3_value_type((sqlite3_value*)pValue) ){
+ case SQLITE_INTEGER: {
+ rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
+ break;
+ }
+ case SQLITE_FLOAT: {
+ rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
+ break;
+ }
+ case SQLITE_BLOB: {
+ if( pValue->flags & MEM_Zero ){
+ rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
+ }else{
+ rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
+ }
+ break;
+ }
+ case SQLITE_TEXT: {
+ rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
+ pValue->enc);
+ break;
+ }
+ default: {
+ rc = sqlite3_bind_null(pStmt, i);
+ break;
+ }
+ }
+ return rc;
+}
+SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
+ int rc;
+ Vdbe *p = (Vdbe *)pStmt;
+ rc = vdbeUnbind(p, i);
+ if( rc==SQLITE_OK ){
+ sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
+ sqlite3_mutex_leave(p->db->mutex);
+ }
+ return rc;
+}
+SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
+ int rc;
+ Vdbe *p = (Vdbe *)pStmt;
+ sqlite3_mutex_enter(p->db->mutex);
+ if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
+ rc = SQLITE_TOOBIG;
+ }else{
+ assert( (n & 0x7FFFFFFF)==n );
+ rc = sqlite3_bind_zeroblob(pStmt, i, n);
+ }
+ rc = sqlite3ApiExit(p->db, rc);
+ sqlite3_mutex_leave(p->db->mutex);
+ return rc;
+}
+
+/*
+** Return the number of wildcards that can be potentially bound to.
+** This routine is added to support DBD::SQLite.
+*/
+SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
+ Vdbe *p = (Vdbe*)pStmt;
+ return p ? p->nVar : 0;
+}
+
+/*
+** Return the name of a wildcard parameter. Return NULL if the index
+** is out of range or if the wildcard is unnamed.
+**
+** The result is always UTF-8.
+*/
+SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
+ Vdbe *p = (Vdbe*)pStmt;
+ if( p==0 ) return 0;
+ return sqlite3VListNumToName(p->pVList, i);
+}
+
+/*
+** Given a wildcard parameter name, return the index of the variable
+** with that name. If there is no variable with the given name,
+** return 0.
+*/
+SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
+ if( p==0 || zName==0 ) return 0;
+ return sqlite3VListNameToNum(p->pVList, zName, nName);
+}
+SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
+ return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
+}
+
+/*
+** Transfer all bindings from the first statement over to the second.
+*/
+SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
+ Vdbe *pFrom = (Vdbe*)pFromStmt;
+ Vdbe *pTo = (Vdbe*)pToStmt;
+ int i;
+ assert( pTo->db==pFrom->db );
+ assert( pTo->nVar==pFrom->nVar );
+ sqlite3_mutex_enter(pTo->db->mutex);
+ for(i=0; i<pFrom->nVar; i++){
+ sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
+ }
+ sqlite3_mutex_leave(pTo->db->mutex);
+ return SQLITE_OK;
+}
+
+#ifndef SQLITE_OMIT_DEPRECATED
+/*
+** Deprecated external interface. Internal/core SQLite code
+** should call sqlite3TransferBindings.
+**
+** It is misuse to call this routine with statements from different
+** database connections. But as this is a deprecated interface, we
+** will not bother to check for that condition.
+**
+** If the two statements contain a different number of bindings, then
+** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
+** SQLITE_OK is returned.
+*/
+SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
+ Vdbe *pFrom = (Vdbe*)pFromStmt;
+ Vdbe *pTo = (Vdbe*)pToStmt;
+ if( pFrom->nVar!=pTo->nVar ){
+ return SQLITE_ERROR;
+ }
+ assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
+ if( pTo->expmask ){
+ pTo->expired = 1;
+ }
+ assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
+ if( pFrom->expmask ){
+ pFrom->expired = 1;
+ }
+ return sqlite3TransferBindings(pFromStmt, pToStmt);
+}
+#endif
+
+/*
+** Return the sqlite3* database handle to which the prepared statement given
+** in the argument belongs. This is the same database handle that was
+** the first argument to the sqlite3_prepare() that was used to create
+** the statement in the first place.
+*/
+SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
+ return pStmt ? ((Vdbe*)pStmt)->db : 0;
+}
+
+/*
+** Return true if the prepared statement is guaranteed to not modify the
+** database.
+*/
+SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
+ return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
+}
+
+/*
+** Return 1 if the statement is an EXPLAIN and return 2 if the
+** statement is an EXPLAIN QUERY PLAN
+*/
+SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt){
+ return pStmt ? ((Vdbe*)pStmt)->explain : 0;
+}
+
+/*
+** Return true if the prepared statement is in need of being reset.
+*/
+SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
+ Vdbe *v = (Vdbe*)pStmt;
+ return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
+}
+
+/*
+** Return a pointer to the next prepared statement after pStmt associated
+** with database connection pDb. If pStmt is NULL, return the first
+** prepared statement for the database connection. Return NULL if there
+** are no more.
+*/
+SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
+ sqlite3_stmt *pNext;
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(pDb) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ sqlite3_mutex_enter(pDb->mutex);
+ if( pStmt==0 ){
+ pNext = (sqlite3_stmt*)pDb->pVdbe;
+ }else{
+ pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
+ }
+ sqlite3_mutex_leave(pDb->mutex);
+ return pNext;
+}
+
+/*
+** Return the value of a status counter for a prepared statement
+*/
+SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
+ Vdbe *pVdbe = (Vdbe*)pStmt;
+ u32 v;
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !pStmt
+ || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
+ ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ if( op==SQLITE_STMTSTATUS_MEMUSED ){
+ sqlite3 *db = pVdbe->db;
+ sqlite3_mutex_enter(db->mutex);
+ v = 0;
+ db->pnBytesFreed = (int*)&v;
+ sqlite3VdbeClearObject(db, pVdbe);
+ sqlite3DbFree(db, pVdbe);
+ db->pnBytesFreed = 0;
+ sqlite3_mutex_leave(db->mutex);
+ }else{
+ v = pVdbe->aCounter[op];
+ if( resetFlag ) pVdbe->aCounter[op] = 0;
+ }
+ return (int)v;
+}
+
+/*
+** Return the SQL associated with a prepared statement
+*/
+SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
+ Vdbe *p = (Vdbe *)pStmt;
+ return p ? p->zSql : 0;
+}
+
+/*
+** Return the SQL associated with a prepared statement with
+** bound parameters expanded. Space to hold the returned string is
+** obtained from sqlite3_malloc(). The caller is responsible for
+** freeing the returned string by passing it to sqlite3_free().
+**
+** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
+** expanded bound parameters.
+*/
+SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
+#ifdef SQLITE_OMIT_TRACE
+ return 0;
+#else
+ char *z = 0;
+ const char *zSql = sqlite3_sql(pStmt);
+ if( zSql ){
+ Vdbe *p = (Vdbe *)pStmt;
+ sqlite3_mutex_enter(p->db->mutex);
+ z = sqlite3VdbeExpandSql(p, zSql);
+ sqlite3_mutex_leave(p->db->mutex);
+ }
+ return z;
+#endif
+}
+
+#ifdef SQLITE_ENABLE_NORMALIZE
+/*
+** Return the normalized SQL associated with a prepared statement.
+*/
+SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){
+ Vdbe *p = (Vdbe *)pStmt;
+ if( p==0 ) return 0;
+ if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){
+ sqlite3_mutex_enter(p->db->mutex);
+ p->zNormSql = sqlite3Normalize(p, p->zSql);
+ sqlite3_mutex_leave(p->db->mutex);
+ }
+ return p->zNormSql;
+}
+#endif /* SQLITE_ENABLE_NORMALIZE */
+
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+/*
+** Allocate and populate an UnpackedRecord structure based on the serialized
+** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
+** if successful, or a NULL pointer if an OOM error is encountered.
+*/
+static UnpackedRecord *vdbeUnpackRecord(
+ KeyInfo *pKeyInfo,
+ int nKey,
+ const void *pKey
+){
+ UnpackedRecord *pRet; /* Return value */
+
+ pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
+ if( pRet ){
+ memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
+ sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
+ }
+ return pRet;
+}
+
+/*
+** This function is called from within a pre-update callback to retrieve
+** a field of the row currently being updated or deleted.
+*/
+SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
+ PreUpdate *p = db->pPreUpdate;
+ Mem *pMem;
+ int rc = SQLITE_OK;
+
+ /* Test that this call is being made from within an SQLITE_DELETE or
+ ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
+ if( !p || p->op==SQLITE_INSERT ){
+ rc = SQLITE_MISUSE_BKPT;
+ goto preupdate_old_out;
+ }
+ if( p->pPk ){
+ iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
+ }
+ if( iIdx>=p->pCsr->nField || iIdx<0 ){
+ rc = SQLITE_RANGE;
+ goto preupdate_old_out;
+ }
+
+ /* If the old.* record has not yet been loaded into memory, do so now. */
+ if( p->pUnpacked==0 ){
+ u32 nRec;
+ u8 *aRec;
+
+ nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
+ aRec = sqlite3DbMallocRaw(db, nRec);
+ if( !aRec ) goto preupdate_old_out;
+ rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
+ if( rc==SQLITE_OK ){
+ p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
+ if( !p->pUnpacked ) rc = SQLITE_NOMEM;
+ }
+ if( rc!=SQLITE_OK ){
+ sqlite3DbFree(db, aRec);
+ goto preupdate_old_out;
+ }
+ p->aRecord = aRec;
+ }
+
+ pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
+ if( iIdx==p->pTab->iPKey ){
+ sqlite3VdbeMemSetInt64(pMem, p->iKey1);
+ }else if( iIdx>=p->pUnpacked->nField ){
+ *ppValue = (sqlite3_value *)columnNullValue();
+ }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
+ if( pMem->flags & (MEM_Int|MEM_IntReal) ){
+ testcase( pMem->flags & MEM_Int );
+ testcase( pMem->flags & MEM_IntReal );
+ sqlite3VdbeMemRealify(pMem);
+ }
+ }
+
+ preupdate_old_out:
+ sqlite3Error(db, rc);
+ return sqlite3ApiExit(db, rc);
+}
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
+
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+/*
+** This function is called from within a pre-update callback to retrieve
+** the number of columns in the row being updated, deleted or inserted.
+*/
+SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
+ PreUpdate *p = db->pPreUpdate;
+ return (p ? p->keyinfo.nKeyField : 0);
+}
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
+
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+/*
+** This function is designed to be called from within a pre-update callback
+** only. It returns zero if the change that caused the callback was made
+** immediately by a user SQL statement. Or, if the change was made by a
+** trigger program, it returns the number of trigger programs currently
+** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
+** top-level trigger etc.).
+**
+** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
+** or SET DEFAULT action is considered a trigger.
+*/
+SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
+ PreUpdate *p = db->pPreUpdate;
+ return (p ? p->v->nFrame : 0);
+}
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
+
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+/*
+** This function is called from within a pre-update callback to retrieve
+** a field of the row currently being updated or inserted.
+*/
+SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
+ PreUpdate *p = db->pPreUpdate;
+ int rc = SQLITE_OK;
+ Mem *pMem;
+
+ if( !p || p->op==SQLITE_DELETE ){
+ rc = SQLITE_MISUSE_BKPT;
+ goto preupdate_new_out;
+ }
+ if( p->pPk && p->op!=SQLITE_UPDATE ){
+ iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
+ }
+ if( iIdx>=p->pCsr->nField || iIdx<0 ){
+ rc = SQLITE_RANGE;
+ goto preupdate_new_out;
+ }
+
+ if( p->op==SQLITE_INSERT ){
+ /* For an INSERT, memory cell p->iNewReg contains the serialized record
+ ** that is being inserted. Deserialize it. */
+ UnpackedRecord *pUnpack = p->pNewUnpacked;
+ if( !pUnpack ){
+ Mem *pData = &p->v->aMem[p->iNewReg];
+ rc = ExpandBlob(pData);
+ if( rc!=SQLITE_OK ) goto preupdate_new_out;
+ pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
+ if( !pUnpack ){
+ rc = SQLITE_NOMEM;
+ goto preupdate_new_out;
+ }
+ p->pNewUnpacked = pUnpack;
+ }
+ pMem = &pUnpack->aMem[iIdx];
+ if( iIdx==p->pTab->iPKey ){
+ sqlite3VdbeMemSetInt64(pMem, p->iKey2);
+ }else if( iIdx>=pUnpack->nField ){
+ pMem = (sqlite3_value *)columnNullValue();
+ }
+ }else{
+ /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
+ ** value. Make a copy of the cell contents and return a pointer to it.
+ ** It is not safe to return a pointer to the memory cell itself as the
+ ** caller may modify the value text encoding.
+ */
+ assert( p->op==SQLITE_UPDATE );
+ if( !p->aNew ){
+ p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
+ if( !p->aNew ){
+ rc = SQLITE_NOMEM;
+ goto preupdate_new_out;
+ }
+ }
+ assert( iIdx>=0 && iIdx<p->pCsr->nField );
+ pMem = &p->aNew[iIdx];
+ if( pMem->flags==0 ){
+ if( iIdx==p->pTab->iPKey ){
+ sqlite3VdbeMemSetInt64(pMem, p->iKey2);
+ }else{
+ rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
+ if( rc!=SQLITE_OK ) goto preupdate_new_out;
+ }
+ }
+ }
+ *ppValue = pMem;
+
+ preupdate_new_out:
+ sqlite3Error(db, rc);
+ return sqlite3ApiExit(db, rc);
+}
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
+
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+/*
+** Return status data for a single loop within query pStmt.
+*/
+SQLITE_API int sqlite3_stmt_scanstatus(
+ sqlite3_stmt *pStmt, /* Prepared statement being queried */
+ int idx, /* Index of loop to report on */
+ int iScanStatusOp, /* Which metric to return */
+ void *pOut /* OUT: Write the answer here */
+){
+ Vdbe *p = (Vdbe*)pStmt;
+ ScanStatus *pScan;
+ if( idx<0 || idx>=p->nScan ) return 1;
+ pScan = &p->aScan[idx];
+ switch( iScanStatusOp ){
+ case SQLITE_SCANSTAT_NLOOP: {
+ *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
+ break;
+ }
+ case SQLITE_SCANSTAT_NVISIT: {
+ *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
+ break;
+ }
+ case SQLITE_SCANSTAT_EST: {
+ double r = 1.0;
+ LogEst x = pScan->nEst;
+ while( x<100 ){
+ x += 10;
+ r *= 0.5;
+ }
+ *(double*)pOut = r*sqlite3LogEstToInt(x);
+ break;
+ }
+ case SQLITE_SCANSTAT_NAME: {
+ *(const char**)pOut = pScan->zName;
+ break;
+ }
+ case SQLITE_SCANSTAT_EXPLAIN: {
+ if( pScan->addrExplain ){
+ *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
+ }else{
+ *(const char**)pOut = 0;
+ }
+ break;
+ }
+ case SQLITE_SCANSTAT_SELECTID: {
+ if( pScan->addrExplain ){
+ *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
+ }else{
+ *(int*)pOut = -1;
+ }
+ break;
+ }
+ default: {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/*
+** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
+*/
+SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
+ Vdbe *p = (Vdbe*)pStmt;
+ memset(p->anExec, 0, p->nOp * sizeof(i64));
+}
+#endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
+
+/************** End of vdbeapi.c *********************************************/
+/************** Begin file vdbetrace.c ***************************************/
+/*
+** 2009 November 25
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains code used to insert the values of host parameters
+** (aka "wildcards") into the SQL text output by sqlite3_trace().
+**
+** The Vdbe parse-tree explainer is also found here.
+*/
+/* #include "sqliteInt.h" */
+/* #include "vdbeInt.h" */
+
+#ifndef SQLITE_OMIT_TRACE
+
+/*
+** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
+** bytes in this text up to but excluding the first character in
+** a host parameter. If the text contains no host parameters, return
+** the total number of bytes in the text.
+*/
+static int findNextHostParameter(const char *zSql, int *pnToken){
+ int tokenType;
+ int nTotal = 0;
+ int n;
+
+ *pnToken = 0;
+ while( zSql[0] ){
+ n = sqlite3GetToken((u8*)zSql, &tokenType);
+ assert( n>0 && tokenType!=TK_ILLEGAL );
+ if( tokenType==TK_VARIABLE ){
+ *pnToken = n;
+ break;
+ }
+ nTotal += n;
+ zSql += n;
+ }
+ return nTotal;
+}
+
+/*
+** This function returns a pointer to a nul-terminated string in memory
+** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
+** string contains a copy of zRawSql but with host parameters expanded to
+** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
+** then the returned string holds a copy of zRawSql with "-- " prepended
+** to each line of text.
+**
+** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
+** then long strings and blobs are truncated to that many bytes. This
+** can be used to prevent unreasonably large trace strings when dealing
+** with large (multi-megabyte) strings and blobs.
+**
+** The calling function is responsible for making sure the memory returned
+** is eventually freed.
+**
+** ALGORITHM: Scan the input string looking for host parameters in any of
+** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
+** string literals, quoted identifier names, and comments. For text forms,
+** the host parameter index is found by scanning the prepared
+** statement for the corresponding OP_Variable opcode. Once the host
+** parameter index is known, locate the value in p->aVar[]. Then render
+** the value as a literal in place of the host parameter name.
+*/
+SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
+ Vdbe *p, /* The prepared statement being evaluated */
+ const char *zRawSql /* Raw text of the SQL statement */
+){
+ sqlite3 *db; /* The database connection */
+ int idx = 0; /* Index of a host parameter */
+ int nextIndex = 1; /* Index of next ? host parameter */
+ int n; /* Length of a token prefix */
+ int nToken; /* Length of the parameter token */
+ int i; /* Loop counter */
+ Mem *pVar; /* Value of a host parameter */
+ StrAccum out; /* Accumulate the output here */
+#ifndef SQLITE_OMIT_UTF16
+ Mem utf8; /* Used to convert UTF16 into UTF8 for display */
+#endif
+ char zBase[100]; /* Initial working space */
+
+ db = p->db;
+ sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
+ db->aLimit[SQLITE_LIMIT_LENGTH]);
+ if( db->nVdbeExec>1 ){
+ while( *zRawSql ){
+ const char *zStart = zRawSql;
+ while( *(zRawSql++)!='\n' && *zRawSql );
+ sqlite3_str_append(&out, "-- ", 3);
+ assert( (zRawSql - zStart) > 0 );
+ sqlite3_str_append(&out, zStart, (int)(zRawSql-zStart));
+ }
+ }else if( p->nVar==0 ){
+ sqlite3_str_append(&out, zRawSql, sqlite3Strlen30(zRawSql));
+ }else{
+ while( zRawSql[0] ){
+ n = findNextHostParameter(zRawSql, &nToken);
+ assert( n>0 );
+ sqlite3_str_append(&out, zRawSql, n);
+ zRawSql += n;
+ assert( zRawSql[0] || nToken==0 );
+ if( nToken==0 ) break;
+ if( zRawSql[0]=='?' ){
+ if( nToken>1 ){
+ assert( sqlite3Isdigit(zRawSql[1]) );
+ sqlite3GetInt32(&zRawSql[1], &idx);
+ }else{
+ idx = nextIndex;
+ }
+ }else{
+ assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
+ zRawSql[0]=='@' || zRawSql[0]=='#' );
+ testcase( zRawSql[0]==':' );
+ testcase( zRawSql[0]=='$' );
+ testcase( zRawSql[0]=='@' );
+ testcase( zRawSql[0]=='#' );
+ idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
+ assert( idx>0 );
+ }
+ zRawSql += nToken;
+ nextIndex = idx + 1;
+ assert( idx>0 && idx<=p->nVar );
+ pVar = &p->aVar[idx-1];
+ if( pVar->flags & MEM_Null ){
+ sqlite3_str_append(&out, "NULL", 4);
+ }else if( pVar->flags & (MEM_Int|MEM_IntReal) ){
+ sqlite3_str_appendf(&out, "%lld", pVar->u.i);
+ }else if( pVar->flags & MEM_Real ){
+ sqlite3_str_appendf(&out, "%!.15g", pVar->u.r);
+ }else if( pVar->flags & MEM_Str ){
+ int nOut; /* Number of bytes of the string text to include in output */
+#ifndef SQLITE_OMIT_UTF16
+ u8 enc = ENC(db);
+ if( enc!=SQLITE_UTF8 ){
+ memset(&utf8, 0, sizeof(utf8));
+ utf8.db = db;
+ sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
+ if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
+ out.accError = SQLITE_NOMEM;
+ out.nAlloc = 0;
+ }
+ pVar = &utf8;
+ }
+#endif
+ nOut = pVar->n;
+#ifdef SQLITE_TRACE_SIZE_LIMIT
+ if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
+ nOut = SQLITE_TRACE_SIZE_LIMIT;
+ while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
+ }
+#endif
+ sqlite3_str_appendf(&out, "'%.*q'", nOut, pVar->z);
+#ifdef SQLITE_TRACE_SIZE_LIMIT
+ if( nOut<pVar->n ){
+ sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
+ }
+#endif
+#ifndef SQLITE_OMIT_UTF16
+ if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
+#endif
+ }else if( pVar->flags & MEM_Zero ){
+ sqlite3_str_appendf(&out, "zeroblob(%d)", pVar->u.nZero);
+ }else{
+ int nOut; /* Number of bytes of the blob to include in output */
+ assert( pVar->flags & MEM_Blob );
+ sqlite3_str_append(&out, "x'", 2);
+ nOut = pVar->n;
+#ifdef SQLITE_TRACE_SIZE_LIMIT
+ if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
+#endif
+ for(i=0; i<nOut; i++){
+ sqlite3_str_appendf(&out, "%02x", pVar->z[i]&0xff);
+ }
+ sqlite3_str_append(&out, "'", 1);
+#ifdef SQLITE_TRACE_SIZE_LIMIT
+ if( nOut<pVar->n ){
+ sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
+ }
+#endif
+ }
+ }
+ }
+ if( out.accError ) sqlite3_str_reset(&out);
+ return sqlite3StrAccumFinish(&out);
+}
+
+#endif /* #ifndef SQLITE_OMIT_TRACE */
+
+/************** End of vdbetrace.c *******************************************/
+/************** Begin file vdbe.c ********************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** The code in this file implements the function that runs the
+** bytecode of a prepared statement.
+**
+** Various scripts scan this source file in order to generate HTML
+** documentation, headers files, or other derived files. The formatting
+** of the code in this file is, therefore, important. See other comments
+** in this file for details. If in doubt, do not deviate from existing
+** commenting and indentation practices when changing or adding code.
+*/
+/* #include "sqliteInt.h" */
+/* #include "vdbeInt.h" */
+
+/*
+** Invoke this macro on memory cells just prior to changing the
+** value of the cell. This macro verifies that shallow copies are
+** not misused. A shallow copy of a string or blob just copies a
+** pointer to the string or blob, not the content. If the original
+** is changed while the copy is still in use, the string or blob might
+** be changed out from under the copy. This macro verifies that nothing
+** like that ever happens.
+*/
+#ifdef SQLITE_DEBUG
+# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
+#else
+# define memAboutToChange(P,M)
+#endif
+
+/*
+** The following global variable is incremented every time a cursor
+** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
+** procedures use this information to make sure that indices are
+** working correctly. This variable has no function other than to
+** help verify the correct operation of the library.
+*/
+#ifdef SQLITE_TEST
+SQLITE_API int sqlite3_search_count = 0;
+#endif
+
+/*
+** When this global variable is positive, it gets decremented once before
+** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
+** field of the sqlite3 structure is set in order to simulate an interrupt.
+**
+** This facility is used for testing purposes only. It does not function
+** in an ordinary build.
+*/
+#ifdef SQLITE_TEST
+SQLITE_API int sqlite3_interrupt_count = 0;
+#endif
+
+/*
+** The next global variable is incremented each type the OP_Sort opcode
+** is executed. The test procedures use this information to make sure that
+** sorting is occurring or not occurring at appropriate times. This variable
+** has no function other than to help verify the correct operation of the
+** library.
+*/
+#ifdef SQLITE_TEST
+SQLITE_API int sqlite3_sort_count = 0;
+#endif
+
+/*
+** The next global variable records the size of the largest MEM_Blob
+** or MEM_Str that has been used by a VDBE opcode. The test procedures
+** use this information to make sure that the zero-blob functionality
+** is working correctly. This variable has no function other than to
+** help verify the correct operation of the library.
+*/
+#ifdef SQLITE_TEST
+SQLITE_API int sqlite3_max_blobsize = 0;
+static void updateMaxBlobsize(Mem *p){
+ if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
+ sqlite3_max_blobsize = p->n;
+ }
+}
+#endif
+
+/*
+** This macro evaluates to true if either the update hook or the preupdate
+** hook are enabled for database connect DB.
+*/
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+# define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
+#else
+# define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
+#endif
+
+/*
+** The next global variable is incremented each time the OP_Found opcode
+** is executed. This is used to test whether or not the foreign key
+** operation implemented using OP_FkIsZero is working. This variable
+** has no function other than to help verify the correct operation of the
+** library.
+*/
+#ifdef SQLITE_TEST
+SQLITE_API int sqlite3_found_count = 0;
+#endif
+
+/*
+** Test a register to see if it exceeds the current maximum blob size.
+** If it does, record the new maximum blob size.
+*/
+#if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
+# define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
+#else
+# define UPDATE_MAX_BLOBSIZE(P)
+#endif
+
+#ifdef SQLITE_DEBUG
+/* This routine provides a convenient place to set a breakpoint during
+** tracing with PRAGMA vdbe_trace=on. The breakpoint fires right after
+** each opcode is printed. Variables "pc" (program counter) and pOp are
+** available to add conditionals to the breakpoint. GDB example:
+**
+** break test_trace_breakpoint if pc=22
+**
+** Other useful labels for breakpoints include:
+** test_addop_breakpoint(pc,pOp)
+** sqlite3CorruptError(lineno)
+** sqlite3MisuseError(lineno)
+** sqlite3CantopenError(lineno)
+*/
+static void test_trace_breakpoint(int pc, Op *pOp, Vdbe *v){
+ static int n = 0;
+ n++;
+}
+#endif
+
+/*
+** Invoke the VDBE coverage callback, if that callback is defined. This
+** feature is used for test suite validation only and does not appear an
+** production builds.
+**
+** M is the type of branch. I is the direction taken for this instance of
+** the branch.
+**
+** M: 2 - two-way branch (I=0: fall-thru 1: jump )
+** 3 - two-way + NULL (I=0: fall-thru 1: jump 2: NULL )
+** 4 - OP_Jump (I=0: jump p1 1: jump p2 2: jump p3)
+**
+** In other words, if M is 2, then I is either 0 (for fall-through) or
+** 1 (for when the branch is taken). If M is 3, the I is 0 for an
+** ordinary fall-through, I is 1 if the branch was taken, and I is 2
+** if the result of comparison is NULL. For M=3, I=2 the jump may or
+** may not be taken, depending on the SQLITE_JUMPIFNULL flags in p5.
+** When M is 4, that means that an OP_Jump is being run. I is 0, 1, or 2
+** depending on if the operands are less than, equal, or greater than.
+**
+** iSrcLine is the source code line (from the __LINE__ macro) that
+** generated the VDBE instruction combined with flag bits. The source
+** code line number is in the lower 24 bits of iSrcLine and the upper
+** 8 bytes are flags. The lower three bits of the flags indicate
+** values for I that should never occur. For example, if the branch is
+** always taken, the flags should be 0x05 since the fall-through and
+** alternate branch are never taken. If a branch is never taken then
+** flags should be 0x06 since only the fall-through approach is allowed.
+**
+** Bit 0x08 of the flags indicates an OP_Jump opcode that is only
+** interested in equal or not-equal. In other words, I==0 and I==2
+** should be treated as equivalent
+**
+** Since only a line number is retained, not the filename, this macro
+** only works for amalgamation builds. But that is ok, since these macros
+** should be no-ops except for special builds used to measure test coverage.
+*/
+#if !defined(SQLITE_VDBE_COVERAGE)
+# define VdbeBranchTaken(I,M)
+#else
+# define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
+ static void vdbeTakeBranch(u32 iSrcLine, u8 I, u8 M){
+ u8 mNever;
+ assert( I<=2 ); /* 0: fall through, 1: taken, 2: alternate taken */
+ assert( M<=4 ); /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */
+ assert( I<M ); /* I can only be 2 if M is 3 or 4 */
+ /* Transform I from a integer [0,1,2] into a bitmask of [1,2,4] */
+ I = 1<<I;
+ /* The upper 8 bits of iSrcLine are flags. The lower three bits of
+ ** the flags indicate directions that the branch can never go. If
+ ** a branch really does go in one of those directions, assert right
+ ** away. */
+ mNever = iSrcLine >> 24;
+ assert( (I & mNever)==0 );
+ if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
+ /* Invoke the branch coverage callback with three arguments:
+ ** iSrcLine - the line number of the VdbeCoverage() macro, with
+ ** flags removed.
+ ** I - Mask of bits 0x07 indicating which cases are are
+ ** fulfilled by this instance of the jump. 0x01 means
+ ** fall-thru, 0x02 means taken, 0x04 means NULL. Any
+ ** impossible cases (ex: if the comparison is never NULL)
+ ** are filled in automatically so that the coverage
+ ** measurement logic does not flag those impossible cases
+ ** as missed coverage.
+ ** M - Type of jump. Same as M argument above
+ */
+ I |= mNever;
+ if( M==2 ) I |= 0x04;
+ if( M==4 ){
+ I |= 0x08;
+ if( (mNever&0x08)!=0 && (I&0x05)!=0) I |= 0x05; /*NO_TEST*/
+ }
+ sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
+ iSrcLine&0xffffff, I, M);
+ }
+#endif
+
+/*
+** An ephemeral string value (signified by the MEM_Ephem flag) contains
+** a pointer to a dynamically allocated string where some other entity
+** is responsible for deallocating that string. Because the register
+** does not control the string, it might be deleted without the register
+** knowing it.
+**
+** This routine converts an ephemeral string into a dynamically allocated
+** string that the register itself controls. In other words, it
+** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
+*/
+#define Deephemeralize(P) \
+ if( ((P)->flags&MEM_Ephem)!=0 \
+ && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
+
+/* Return true if the cursor was opened using the OP_OpenSorter opcode. */
+#define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
+
+/*
+** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
+** if we run out of memory.
+*/
+static VdbeCursor *allocateCursor(
+ Vdbe *p, /* The virtual machine */
+ int iCur, /* Index of the new VdbeCursor */
+ int nField, /* Number of fields in the table or index */
+ int iDb, /* Database the cursor belongs to, or -1 */
+ u8 eCurType /* Type of the new cursor */
+){
+ /* Find the memory cell that will be used to store the blob of memory
+ ** required for this VdbeCursor structure. It is convenient to use a
+ ** vdbe memory cell to manage the memory allocation required for a
+ ** VdbeCursor structure for the following reasons:
+ **
+ ** * Sometimes cursor numbers are used for a couple of different
+ ** purposes in a vdbe program. The different uses might require
+ ** different sized allocations. Memory cells provide growable
+ ** allocations.
+ **
+ ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
+ ** be freed lazily via the sqlite3_release_memory() API. This
+ ** minimizes the number of malloc calls made by the system.
+ **
+ ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
+ ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
+ ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
+ */
+ Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
+
+ int nByte;
+ VdbeCursor *pCx = 0;
+ nByte =
+ ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
+ (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
+
+ assert( iCur>=0 && iCur<p->nCursor );
+ if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
+ /* Before calling sqlite3VdbeFreeCursor(), ensure the isEphemeral flag
+ ** is clear. Otherwise, if this is an ephemeral cursor created by
+ ** OP_OpenDup, the cursor will not be closed and will still be part
+ ** of a BtShared.pCursor list. */
+ if( p->apCsr[iCur]->pBtx==0 ) p->apCsr[iCur]->isEphemeral = 0;
+ sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
+ p->apCsr[iCur] = 0;
+ }
+ if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
+ p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
+ memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
+ pCx->eCurType = eCurType;
+ pCx->iDb = iDb;
+ pCx->nField = nField;
+ pCx->aOffset = &pCx->aType[nField];
+ if( eCurType==CURTYPE_BTREE ){
+ pCx->uc.pCursor = (BtCursor*)
+ &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
+ sqlite3BtreeCursorZero(pCx->uc.pCursor);
+ }
+ }
+ return pCx;
+}
+
+/*
+** The string in pRec is known to look like an integer and to have a
+** floating point value of rValue. Return true and set *piValue to the
+** integer value if the string is in range to be an integer. Otherwise,
+** return false.
+*/
+static int alsoAnInt(Mem *pRec, double rValue, i64 *piValue){
+ i64 iValue = (double)rValue;
+ if( sqlite3RealSameAsInt(rValue,iValue) ){
+ *piValue = iValue;
+ return 1;
+ }
+ return 0==sqlite3Atoi64(pRec->z, piValue, pRec->n, pRec->enc);
+}
+
+/*
+** Try to convert a value into a numeric representation if we can
+** do so without loss of information. In other words, if the string
+** looks like a number, convert it into a number. If it does not
+** look like a number, leave it alone.
+**
+** If the bTryForInt flag is true, then extra effort is made to give
+** an integer representation. Strings that look like floating point
+** values but which have no fractional component (example: '48.00')
+** will have a MEM_Int representation when bTryForInt is true.
+**
+** If bTryForInt is false, then if the input string contains a decimal
+** point or exponential notation, the result is only MEM_Real, even
+** if there is an exact integer representation of the quantity.
+*/
+static void applyNumericAffinity(Mem *pRec, int bTryForInt){
+ double rValue;
+ u8 enc = pRec->enc;
+ int rc;
+ assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str );
+ rc = sqlite3AtoF(pRec->z, &rValue, pRec->n, enc);
+ if( rc<=0 ) return;
+ if( rc==1 && alsoAnInt(pRec, rValue, &pRec->u.i) ){
+ pRec->flags |= MEM_Int;
+ }else{
+ pRec->u.r = rValue;
+ pRec->flags |= MEM_Real;
+ if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
+ }
+ /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
+ ** string representation after computing a numeric equivalent, because the
+ ** string representation might not be the canonical representation for the
+ ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
+ pRec->flags &= ~MEM_Str;
+}
+
+/*
+** Processing is determine by the affinity parameter:
+**
+** SQLITE_AFF_INTEGER:
+** SQLITE_AFF_REAL:
+** SQLITE_AFF_NUMERIC:
+** Try to convert pRec to an integer representation or a
+** floating-point representation if an integer representation
+** is not possible. Note that the integer representation is
+** always preferred, even if the affinity is REAL, because
+** an integer representation is more space efficient on disk.
+**
+** SQLITE_AFF_TEXT:
+** Convert pRec to a text representation.
+**
+** SQLITE_AFF_BLOB:
+** SQLITE_AFF_NONE:
+** No-op. pRec is unchanged.
+*/
+static void applyAffinity(
+ Mem *pRec, /* The value to apply affinity to */
+ char affinity, /* The affinity to be applied */
+ u8 enc /* Use this text encoding */
+){
+ if( affinity>=SQLITE_AFF_NUMERIC ){
+ assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
+ || affinity==SQLITE_AFF_NUMERIC );
+ if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
+ if( (pRec->flags & MEM_Real)==0 ){
+ if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
+ }else{
+ sqlite3VdbeIntegerAffinity(pRec);
+ }
+ }
+ }else if( affinity==SQLITE_AFF_TEXT ){
+ /* Only attempt the conversion to TEXT if there is an integer or real
+ ** representation (blob and NULL do not get converted) but no string
+ ** representation. It would be harmless to repeat the conversion if
+ ** there is already a string rep, but it is pointless to waste those
+ ** CPU cycles. */
+ if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
+ if( (pRec->flags&(MEM_Real|MEM_Int|MEM_IntReal)) ){
+ testcase( pRec->flags & MEM_Int );
+ testcase( pRec->flags & MEM_Real );
+ testcase( pRec->flags & MEM_IntReal );
+ sqlite3VdbeMemStringify(pRec, enc, 1);
+ }
+ }
+ pRec->flags &= ~(MEM_Real|MEM_Int|MEM_IntReal);
+ }
+}
+
+/*
+** Try to convert the type of a function argument or a result column
+** into a numeric representation. Use either INTEGER or REAL whichever
+** is appropriate. But only do the conversion if it is possible without
+** loss of information and return the revised type of the argument.
+*/
+SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
+ int eType = sqlite3_value_type(pVal);
+ if( eType==SQLITE_TEXT ){
+ Mem *pMem = (Mem*)pVal;
+ applyNumericAffinity(pMem, 0);
+ eType = sqlite3_value_type(pVal);
+ }
+ return eType;
+}
+
+/*
+** Exported version of applyAffinity(). This one works on sqlite3_value*,
+** not the internal Mem* type.
+*/
+SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
+ sqlite3_value *pVal,
+ u8 affinity,
+ u8 enc
+){
+ applyAffinity((Mem *)pVal, affinity, enc);
+}
+
+/*
+** pMem currently only holds a string type (or maybe a BLOB that we can
+** interpret as a string if we want to). Compute its corresponding
+** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
+** accordingly.
+*/
+static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
+ int rc;
+ sqlite3_int64 ix;
+ assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 );
+ assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
+ ExpandBlob(pMem);
+ rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
+ if( rc<=0 ){
+ if( rc==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){
+ pMem->u.i = ix;
+ return MEM_Int;
+ }else{
+ return MEM_Real;
+ }
+ }else if( rc==1 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){
+ pMem->u.i = ix;
+ return MEM_Int;
+ }
+ return MEM_Real;
+}
+
+/*
+** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
+** none.
+**
+** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
+** But it does set pMem->u.r and pMem->u.i appropriately.
+*/
+static u16 numericType(Mem *pMem){
+ if( pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal) ){
+ testcase( pMem->flags & MEM_Int );
+ testcase( pMem->flags & MEM_Real );
+ testcase( pMem->flags & MEM_IntReal );
+ return pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal);
+ }
+ if( pMem->flags & (MEM_Str|MEM_Blob) ){
+ testcase( pMem->flags & MEM_Str );
+ testcase( pMem->flags & MEM_Blob );
+ return computeNumericType(pMem);
+ }
+ return 0;
+}
+
+#ifdef SQLITE_DEBUG
+/*
+** Write a nice string representation of the contents of cell pMem
+** into buffer zBuf, length nBuf.
+*/
+SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr){
+ int f = pMem->flags;
+ static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
+ if( f&MEM_Blob ){
+ int i;
+ char c;
+ if( f & MEM_Dyn ){
+ c = 'z';
+ assert( (f & (MEM_Static|MEM_Ephem))==0 );
+ }else if( f & MEM_Static ){
+ c = 't';
+ assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
+ }else if( f & MEM_Ephem ){
+ c = 'e';
+ assert( (f & (MEM_Static|MEM_Dyn))==0 );
+ }else{
+ c = 's';
+ }
+ sqlite3_str_appendf(pStr, "%cx[", c);
+ for(i=0; i<25 && i<pMem->n; i++){
+ sqlite3_str_appendf(pStr, "%02X", ((int)pMem->z[i] & 0xFF));
+ }
+ sqlite3_str_appendf(pStr, "|");
+ for(i=0; i<25 && i<pMem->n; i++){
+ char z = pMem->z[i];
+ sqlite3_str_appendchar(pStr, 1, (z<32||z>126)?'.':z);
+ }
+ sqlite3_str_appendf(pStr,"]");
+ if( f & MEM_Zero ){
+ sqlite3_str_appendf(pStr, "+%dz",pMem->u.nZero);
+ }
+ }else if( f & MEM_Str ){
+ int j;
+ u8 c;
+ if( f & MEM_Dyn ){
+ c = 'z';
+ assert( (f & (MEM_Static|MEM_Ephem))==0 );
+ }else if( f & MEM_Static ){
+ c = 't';
+ assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
+ }else if( f & MEM_Ephem ){
+ c = 'e';
+ assert( (f & (MEM_Static|MEM_Dyn))==0 );
+ }else{
+ c = 's';
+ }
+ sqlite3_str_appendf(pStr, " %c%d[", c, pMem->n);
+ for(j=0; j<25 && j<pMem->n; j++){
+ c = pMem->z[j];
+ sqlite3_str_appendchar(pStr, 1, (c>=0x20&&c<=0x7f) ? c : '.');
+ }
+ sqlite3_str_appendf(pStr, "]%s", encnames[pMem->enc]);
+ }
+}
+#endif
+
+#ifdef SQLITE_DEBUG
+/*
+** Print the value of a register for tracing purposes:
+*/
+static void memTracePrint(Mem *p){
+ if( p->flags & MEM_Undefined ){
+ printf(" undefined");
+ }else if( p->flags & MEM_Null ){
+ printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
+ }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
+ printf(" si:%lld", p->u.i);
+ }else if( (p->flags & (MEM_IntReal))!=0 ){
+ printf(" ir:%lld", p->u.i);
+ }else if( p->flags & MEM_Int ){
+ printf(" i:%lld", p->u.i);
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ }else if( p->flags & MEM_Real ){
+ printf(" r:%.17g", p->u.r);
+#endif
+ }else if( sqlite3VdbeMemIsRowSet(p) ){
+ printf(" (rowset)");
+ }else{
+ StrAccum acc;
+ char zBuf[1000];
+ sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
+ sqlite3VdbeMemPrettyPrint(p, &acc);
+ printf(" %s", sqlite3StrAccumFinish(&acc));
+ }
+ if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
+}
+static void registerTrace(int iReg, Mem *p){
+ printf("R[%d] = ", iReg);
+ memTracePrint(p);
+ if( p->pScopyFrom ){
+ printf(" <== R[%d]", (int)(p->pScopyFrom - &p[-iReg]));
+ }
+ printf("\n");
+ sqlite3VdbeCheckMemInvariants(p);
+}
+#endif
+
+#ifdef SQLITE_DEBUG
+/*
+** Show the values of all registers in the virtual machine. Used for
+** interactive debugging.
+*/
+SQLITE_PRIVATE void sqlite3VdbeRegisterDump(Vdbe *v){
+ int i;
+ for(i=1; i<v->nMem; i++) registerTrace(i, v->aMem+i);
+}
+#endif /* SQLITE_DEBUG */
+
+
+#ifdef SQLITE_DEBUG
+# define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
+#else
+# define REGISTER_TRACE(R,M)
+#endif
+
+
+#ifdef VDBE_PROFILE
+
+/*
+** hwtime.h contains inline assembler code for implementing
+** high-performance timing routines.
+*/
+/************** Include hwtime.h in the middle of vdbe.c *********************/
+/************** Begin file hwtime.h ******************************************/
+/*
+** 2008 May 27
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains inline asm code for retrieving "high-performance"
+** counters for x86 and x86_64 class CPUs.
+*/
+#ifndef SQLITE_HWTIME_H
+#define SQLITE_HWTIME_H
+
+/*
+** The following routine only works on pentium-class (or newer) processors.
+** It uses the RDTSC opcode to read the cycle count value out of the
+** processor and returns that value. This can be used for high-res
+** profiling.
+*/
+#if !defined(__STRICT_ANSI__) && \
+ (defined(__GNUC__) || defined(_MSC_VER)) && \
+ (defined(i386) || defined(__i386__) || defined(_M_IX86))
+
+ #if defined(__GNUC__)
+
+ __inline__ sqlite_uint64 sqlite3Hwtime(void){
+ unsigned int lo, hi;
+ __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
+ return (sqlite_uint64)hi << 32 | lo;
+ }
+
+ #elif defined(_MSC_VER)
+
+ __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
+ __asm {
+ rdtsc
+ ret ; return value at EDX:EAX
+ }
+ }
+
+ #endif
+
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
+
+ __inline__ sqlite_uint64 sqlite3Hwtime(void){
+ unsigned long val;
+ __asm__ __volatile__ ("rdtsc" : "=A" (val));
+ return val;
+ }
+
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
+
+ __inline__ sqlite_uint64 sqlite3Hwtime(void){
+ unsigned long long retval;
+ unsigned long junk;
+ __asm__ __volatile__ ("\n\
+ 1: mftbu %1\n\
+ mftb %L0\n\
+ mftbu %0\n\
+ cmpw %0,%1\n\
+ bne 1b"
+ : "=r" (retval), "=r" (junk));
+ return retval;
+ }
+
+#else
+
+ /*
+ ** asm() is needed for hardware timing support. Without asm(),
+ ** disable the sqlite3Hwtime() routine.
+ **
+ ** sqlite3Hwtime() is only used for some obscure debugging
+ ** and analysis configurations, not in any deliverable, so this
+ ** should not be a great loss.
+ */
+SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
+
+#endif
+
+#endif /* !defined(SQLITE_HWTIME_H) */
+
+/************** End of hwtime.h **********************************************/
+/************** Continuing where we left off in vdbe.c ***********************/
+
+#endif
+
+#ifndef NDEBUG
+/*
+** This function is only called from within an assert() expression. It
+** checks that the sqlite3.nTransaction variable is correctly set to
+** the number of non-transaction savepoints currently in the
+** linked list starting at sqlite3.pSavepoint.
+**
+** Usage:
+**
+** assert( checkSavepointCount(db) );
+*/
+static int checkSavepointCount(sqlite3 *db){
+ int n = 0;
+ Savepoint *p;
+ for(p=db->pSavepoint; p; p=p->pNext) n++;
+ assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
+ return 1;
+}
+#endif
+
+/*
+** Return the register of pOp->p2 after first preparing it to be
+** overwritten with an integer value.
+*/
+static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
+ sqlite3VdbeMemSetNull(pOut);
+ pOut->flags = MEM_Int;
+ return pOut;
+}
+static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
+ Mem *pOut;
+ assert( pOp->p2>0 );
+ assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
+ pOut = &p->aMem[pOp->p2];
+ memAboutToChange(p, pOut);
+ if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
+ return out2PrereleaseWithClear(pOut);
+ }else{
+ pOut->flags = MEM_Int;
+ return pOut;
+ }
+}
+
+
+/*
+** Execute as much of a VDBE program as we can.
+** This is the core of sqlite3_step().
+*/
+SQLITE_PRIVATE int sqlite3VdbeExec(
+ Vdbe *p /* The VDBE */
+){
+ Op *aOp = p->aOp; /* Copy of p->aOp */
+ Op *pOp = aOp; /* Current operation */
+#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
+ Op *pOrigOp; /* Value of pOp at the top of the loop */
+#endif
+#ifdef SQLITE_DEBUG
+ int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
+#endif
+ int rc = SQLITE_OK; /* Value to return */
+ sqlite3 *db = p->db; /* The database */
+ u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
+ u8 encoding = ENC(db); /* The database encoding */
+ int iCompare = 0; /* Result of last comparison */
+ u64 nVmStep = 0; /* Number of virtual machine steps */
+#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
+ u64 nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
+#endif
+ Mem *aMem = p->aMem; /* Copy of p->aMem */
+ Mem *pIn1 = 0; /* 1st input operand */
+ Mem *pIn2 = 0; /* 2nd input operand */
+ Mem *pIn3 = 0; /* 3rd input operand */
+ Mem *pOut = 0; /* Output operand */
+#ifdef VDBE_PROFILE
+ u64 start; /* CPU clock count at start of opcode */
+#endif
+ /*** INSERT STACK UNION HERE ***/
+
+ assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
+ sqlite3VdbeEnter(p);
+#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
+ if( db->xProgress ){
+ u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
+ assert( 0 < db->nProgressOps );
+ nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
+ }else{
+ nProgressLimit = LARGEST_UINT64;
+ }
+#endif
+ if( p->rc==SQLITE_NOMEM ){
+ /* This happens if a malloc() inside a call to sqlite3_column_text() or
+ ** sqlite3_column_text16() failed. */
+ goto no_mem;
+ }
+ assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
+ testcase( p->rc!=SQLITE_OK );
+ p->rc = SQLITE_OK;
+ assert( p->bIsReader || p->readOnly!=0 );
+ p->iCurrentTime = 0;
+ assert( p->explain==0 );
+ p->pResultSet = 0;
+ db->busyHandler.nBusy = 0;
+ if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
+ sqlite3VdbeIOTraceSql(p);
+#ifdef SQLITE_DEBUG
+ sqlite3BeginBenignMalloc();
+ if( p->pc==0
+ && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
+ ){
+ int i;
+ int once = 1;
+ sqlite3VdbePrintSql(p);
+ if( p->db->flags & SQLITE_VdbeListing ){
+ printf("VDBE Program Listing:\n");
+ for(i=0; i<p->nOp; i++){
+ sqlite3VdbePrintOp(stdout, i, &aOp[i]);
+ }
+ }
+ if( p->db->flags & SQLITE_VdbeEQP ){
+ for(i=0; i<p->nOp; i++){
+ if( aOp[i].opcode==OP_Explain ){
+ if( once ) printf("VDBE Query Plan:\n");
+ printf("%s\n", aOp[i].p4.z);
+ once = 0;
+ }
+ }
+ }
+ if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
+ }
+ sqlite3EndBenignMalloc();
+#endif
+ for(pOp=&aOp[p->pc]; 1; pOp++){
+ /* Errors are detected by individual opcodes, with an immediate
+ ** jumps to abort_due_to_error. */
+ assert( rc==SQLITE_OK );
+
+ assert( pOp>=aOp && pOp<&aOp[p->nOp]);
+#ifdef VDBE_PROFILE
+ start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
+#endif
+ nVmStep++;
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+ if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
+#endif
+
+ /* Only allow tracing if SQLITE_DEBUG is defined.
+ */
+#ifdef SQLITE_DEBUG
+ if( db->flags & SQLITE_VdbeTrace ){
+ sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
+ test_trace_breakpoint((int)(pOp - aOp),pOp,p);
+ }
+#endif
+
+
+ /* Check to see if we need to simulate an interrupt. This only happens
+ ** if we have a special test build.
+ */
+#ifdef SQLITE_TEST
+ if( sqlite3_interrupt_count>0 ){
+ sqlite3_interrupt_count--;
+ if( sqlite3_interrupt_count==0 ){
+ sqlite3_interrupt(db);
+ }
+ }
+#endif
+
+ /* Sanity checking on other operands */
+#ifdef SQLITE_DEBUG
+ {
+ u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
+ if( (opProperty & OPFLG_IN1)!=0 ){
+ assert( pOp->p1>0 );
+ assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
+ assert( memIsValid(&aMem[pOp->p1]) );
+ assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
+ REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
+ }
+ if( (opProperty & OPFLG_IN2)!=0 ){
+ assert( pOp->p2>0 );
+ assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
+ assert( memIsValid(&aMem[pOp->p2]) );
+ assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
+ REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
+ }
+ if( (opProperty & OPFLG_IN3)!=0 ){
+ assert( pOp->p3>0 );
+ assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
+ assert( memIsValid(&aMem[pOp->p3]) );
+ assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
+ REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
+ }
+ if( (opProperty & OPFLG_OUT2)!=0 ){
+ assert( pOp->p2>0 );
+ assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
+ memAboutToChange(p, &aMem[pOp->p2]);
+ }
+ if( (opProperty & OPFLG_OUT3)!=0 ){
+ assert( pOp->p3>0 );
+ assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
+ memAboutToChange(p, &aMem[pOp->p3]);
+ }
+ }
+#endif
+#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
+ pOrigOp = pOp;
+#endif
+
+ switch( pOp->opcode ){
+
+/*****************************************************************************
+** What follows is a massive switch statement where each case implements a
+** separate instruction in the virtual machine. If we follow the usual
+** indentation conventions, each case should be indented by 6 spaces. But
+** that is a lot of wasted space on the left margin. So the code within
+** the switch statement will break with convention and be flush-left. Another
+** big comment (similar to this one) will mark the point in the code where
+** we transition back to normal indentation.
+**
+** The formatting of each case is important. The makefile for SQLite
+** generates two C files "opcodes.h" and "opcodes.c" by scanning this
+** file looking for lines that begin with "case OP_". The opcodes.h files
+** will be filled with #defines that give unique integer values to each
+** opcode and the opcodes.c file is filled with an array of strings where
+** each string is the symbolic name for the corresponding opcode. If the
+** case statement is followed by a comment of the form "/# same as ... #/"
+** that comment is used to determine the particular value of the opcode.
+**
+** Other keywords in the comment that follows each case are used to
+** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
+** Keywords include: in1, in2, in3, out2, out3. See
+** the mkopcodeh.awk script for additional information.
+**
+** Documentation about VDBE opcodes is generated by scanning this file
+** for lines of that contain "Opcode:". That line and all subsequent
+** comment lines are used in the generation of the opcode.html documentation
+** file.
+**
+** SUMMARY:
+**
+** Formatting is important to scripts that scan this file.
+** Do not deviate from the formatting style currently in use.
+**
+*****************************************************************************/
+
+/* Opcode: Goto * P2 * * *
+**
+** An unconditional jump to address P2.
+** The next instruction executed will be
+** the one at index P2 from the beginning of
+** the program.
+**
+** The P1 parameter is not actually used by this opcode. However, it
+** is sometimes set to 1 instead of 0 as a hint to the command-line shell
+** that this Goto is the bottom of a loop and that the lines from P2 down
+** to the current line should be indented for EXPLAIN output.
+*/
+case OP_Goto: { /* jump */
+
+#ifdef SQLITE_DEBUG
+ /* In debuggging mode, when the p5 flags is set on an OP_Goto, that
+ ** means we should really jump back to the preceeding OP_ReleaseReg
+ ** instruction. */
+ if( pOp->p5 ){
+ assert( pOp->p2 < (int)(pOp - aOp) );
+ assert( pOp->p2 > 1 );
+ pOp = &aOp[pOp->p2 - 2];
+ assert( pOp[1].opcode==OP_ReleaseReg );
+ goto check_for_interrupt;
+ }
+#endif
+
+jump_to_p2_and_check_for_interrupt:
+ pOp = &aOp[pOp->p2 - 1];
+
+ /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
+ ** OP_VNext, or OP_SorterNext) all jump here upon
+ ** completion. Check to see if sqlite3_interrupt() has been called
+ ** or if the progress callback needs to be invoked.
+ **
+ ** This code uses unstructured "goto" statements and does not look clean.
+ ** But that is not due to sloppy coding habits. The code is written this
+ ** way for performance, to avoid having to run the interrupt and progress
+ ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
+ ** faster according to "valgrind --tool=cachegrind" */
+check_for_interrupt:
+ if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
+#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
+ /* Call the progress callback if it is configured and the required number
+ ** of VDBE ops have been executed (either since this invocation of
+ ** sqlite3VdbeExec() or since last time the progress callback was called).
+ ** If the progress callback returns non-zero, exit the virtual machine with
+ ** a return code SQLITE_ABORT.
+ */
+ while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
+ assert( db->nProgressOps!=0 );
+ nProgressLimit += db->nProgressOps;
+ if( db->xProgress(db->pProgressArg) ){
+ nProgressLimit = LARGEST_UINT64;
+ rc = SQLITE_INTERRUPT;
+ goto abort_due_to_error;
+ }
+ }
+#endif
+
+ break;
+}
+
+/* Opcode: Gosub P1 P2 * * *
+**
+** Write the current address onto register P1
+** and then jump to address P2.
+*/
+case OP_Gosub: { /* jump */
+ assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
+ pIn1 = &aMem[pOp->p1];
+ assert( VdbeMemDynamic(pIn1)==0 );
+ memAboutToChange(p, pIn1);
+ pIn1->flags = MEM_Int;
+ pIn1->u.i = (int)(pOp-aOp);
+ REGISTER_TRACE(pOp->p1, pIn1);
+
+ /* Most jump operations do a goto to this spot in order to update
+ ** the pOp pointer. */
+jump_to_p2:
+ pOp = &aOp[pOp->p2 - 1];
+ break;
+}
+
+/* Opcode: Return P1 * * * *
+**
+** Jump to the next instruction after the address in register P1. After
+** the jump, register P1 becomes undefined.
+*/
+case OP_Return: { /* in1 */
+ pIn1 = &aMem[pOp->p1];
+ assert( pIn1->flags==MEM_Int );
+ pOp = &aOp[pIn1->u.i];
+ pIn1->flags = MEM_Undefined;
+ break;
+}
+
+/* Opcode: InitCoroutine P1 P2 P3 * *
+**
+** Set up register P1 so that it will Yield to the coroutine
+** located at address P3.
+**
+** If P2!=0 then the coroutine implementation immediately follows
+** this opcode. So jump over the coroutine implementation to
+** address P2.
+**
+** See also: EndCoroutine
+*/
+case OP_InitCoroutine: { /* jump */
+ assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
+ assert( pOp->p2>=0 && pOp->p2<p->nOp );
+ assert( pOp->p3>=0 && pOp->p3<p->nOp );
+ pOut = &aMem[pOp->p1];
+ assert( !VdbeMemDynamic(pOut) );
+ pOut->u.i = pOp->p3 - 1;
+ pOut->flags = MEM_Int;
+ if( pOp->p2 ) goto jump_to_p2;
+ break;
+}
+
+/* Opcode: EndCoroutine P1 * * * *
+**
+** The instruction at the address in register P1 is a Yield.
+** Jump to the P2 parameter of that Yield.
+** After the jump, register P1 becomes undefined.
+**
+** See also: InitCoroutine
+*/
+case OP_EndCoroutine: { /* in1 */
+ VdbeOp *pCaller;
+ pIn1 = &aMem[pOp->p1];
+ assert( pIn1->flags==MEM_Int );
+ assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
+ pCaller = &aOp[pIn1->u.i];
+ assert( pCaller->opcode==OP_Yield );
+ assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
+ pOp = &aOp[pCaller->p2 - 1];
+ pIn1->flags = MEM_Undefined;
+ break;
+}
+
+/* Opcode: Yield P1 P2 * * *
+**
+** Swap the program counter with the value in register P1. This
+** has the effect of yielding to a coroutine.
+**
+** If the coroutine that is launched by this instruction ends with
+** Yield or Return then continue to the next instruction. But if
+** the coroutine launched by this instruction ends with
+** EndCoroutine, then jump to P2 rather than continuing with the
+** next instruction.
+**
+** See also: InitCoroutine
+*/
+case OP_Yield: { /* in1, jump */
+ int pcDest;
+ pIn1 = &aMem[pOp->p1];
+ assert( VdbeMemDynamic(pIn1)==0 );
+ pIn1->flags = MEM_Int;
+ pcDest = (int)pIn1->u.i;
+ pIn1->u.i = (int)(pOp - aOp);
+ REGISTER_TRACE(pOp->p1, pIn1);
+ pOp = &aOp[pcDest];
+ break;
+}
+
+/* Opcode: HaltIfNull P1 P2 P3 P4 P5
+** Synopsis: if r[P3]=null halt
+**
+** Check the value in register P3. If it is NULL then Halt using
+** parameter P1, P2, and P4 as if this were a Halt instruction. If the
+** value in register P3 is not NULL, then this routine is a no-op.
+** The P5 parameter should be 1.
+*/
+case OP_HaltIfNull: { /* in3 */
+ pIn3 = &aMem[pOp->p3];
+#ifdef SQLITE_DEBUG
+ if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
+#endif
+ if( (pIn3->flags & MEM_Null)==0 ) break;
+ /* Fall through into OP_Halt */
+ /* no break */ deliberate_fall_through
+}
+
+/* Opcode: Halt P1 P2 * P4 P5
+**
+** Exit immediately. All open cursors, etc are closed
+** automatically.
+**
+** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
+** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
+** For errors, it can be some other value. If P1!=0 then P2 will determine
+** whether or not to rollback the current transaction. Do not rollback
+** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
+** then back out all changes that have occurred during this execution of the
+** VDBE, but do not rollback the transaction.
+**
+** If P4 is not null then it is an error message string.
+**
+** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
+**
+** 0: (no change)
+** 1: NOT NULL contraint failed: P4
+** 2: UNIQUE constraint failed: P4
+** 3: CHECK constraint failed: P4
+** 4: FOREIGN KEY constraint failed: P4
+**
+** If P5 is not zero and P4 is NULL, then everything after the ":" is
+** omitted.
+**
+** There is an implied "Halt 0 0 0" instruction inserted at the very end of
+** every program. So a jump past the last instruction of the program
+** is the same as executing Halt.
+*/
+case OP_Halt: {
+ VdbeFrame *pFrame;
+ int pcx;
+
+ pcx = (int)(pOp - aOp);
+#ifdef SQLITE_DEBUG
+ if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
+#endif
+ if( pOp->p1==SQLITE_OK && p->pFrame ){
+ /* Halt the sub-program. Return control to the parent frame. */
+ pFrame = p->pFrame;
+ p->pFrame = pFrame->pParent;
+ p->nFrame--;
+ sqlite3VdbeSetChanges(db, p->nChange);
+ pcx = sqlite3VdbeFrameRestore(pFrame);
+ if( pOp->p2==OE_Ignore ){
+ /* Instruction pcx is the OP_Program that invoked the sub-program
+ ** currently being halted. If the p2 instruction of this OP_Halt
+ ** instruction is set to OE_Ignore, then the sub-program is throwing
+ ** an IGNORE exception. In this case jump to the address specified
+ ** as the p2 of the calling OP_Program. */
+ pcx = p->aOp[pcx].p2-1;
+ }
+ aOp = p->aOp;
+ aMem = p->aMem;
+ pOp = &aOp[pcx];
+ break;
+ }
+ p->rc = pOp->p1;
+ p->errorAction = (u8)pOp->p2;
+ p->pc = pcx;
+ assert( pOp->p5<=4 );
+ if( p->rc ){
+ if( pOp->p5 ){
+ static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
+ "FOREIGN KEY" };
+ testcase( pOp->p5==1 );
+ testcase( pOp->p5==2 );
+ testcase( pOp->p5==3 );
+ testcase( pOp->p5==4 );
+ sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
+ if( pOp->p4.z ){
+ p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
+ }
+ }else{
+ sqlite3VdbeError(p, "%s", pOp->p4.z);
+ }
+ sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
+ }
+ rc = sqlite3VdbeHalt(p);
+ assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
+ if( rc==SQLITE_BUSY ){
+ p->rc = SQLITE_BUSY;
+ }else{
+ assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
+ assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
+ rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
+ }
+ goto vdbe_return;
+}
+
+/* Opcode: Integer P1 P2 * * *
+** Synopsis: r[P2]=P1
+**
+** The 32-bit integer value P1 is written into register P2.
+*/
+case OP_Integer: { /* out2 */
+ pOut = out2Prerelease(p, pOp);
+ pOut->u.i = pOp->p1;
+ break;
+}
+
+/* Opcode: Int64 * P2 * P4 *
+** Synopsis: r[P2]=P4
+**
+** P4 is a pointer to a 64-bit integer value.
+** Write that value into register P2.
+*/
+case OP_Int64: { /* out2 */
+ pOut = out2Prerelease(p, pOp);
+ assert( pOp->p4.pI64!=0 );
+ pOut->u.i = *pOp->p4.pI64;
+ break;
+}
+
+#ifndef SQLITE_OMIT_FLOATING_POINT
+/* Opcode: Real * P2 * P4 *
+** Synopsis: r[P2]=P4
+**
+** P4 is a pointer to a 64-bit floating point value.
+** Write that value into register P2.
+*/
+case OP_Real: { /* same as TK_FLOAT, out2 */
+ pOut = out2Prerelease(p, pOp);
+ pOut->flags = MEM_Real;
+ assert( !sqlite3IsNaN(*pOp->p4.pReal) );
+ pOut->u.r = *pOp->p4.pReal;
+ break;
+}
+#endif
+
+/* Opcode: String8 * P2 * P4 *
+** Synopsis: r[P2]='P4'
+**
+** P4 points to a nul terminated UTF-8 string. This opcode is transformed
+** into a String opcode before it is executed for the first time. During
+** this transformation, the length of string P4 is computed and stored
+** as the P1 parameter.
+*/
+case OP_String8: { /* same as TK_STRING, out2 */
+ assert( pOp->p4.z!=0 );
+ pOut = out2Prerelease(p, pOp);
+ pOp->p1 = sqlite3Strlen30(pOp->p4.z);
+
+#ifndef SQLITE_OMIT_UTF16
+ if( encoding!=SQLITE_UTF8 ){
+ rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
+ assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
+ if( rc ) goto too_big;
+ if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
+ assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
+ assert( VdbeMemDynamic(pOut)==0 );
+ pOut->szMalloc = 0;
+ pOut->flags |= MEM_Static;
+ if( pOp->p4type==P4_DYNAMIC ){
+ sqlite3DbFree(db, pOp->p4.z);
+ }
+ pOp->p4type = P4_DYNAMIC;
+ pOp->p4.z = pOut->z;
+ pOp->p1 = pOut->n;
+ }
+#endif
+ if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
+ goto too_big;
+ }
+ pOp->opcode = OP_String;
+ assert( rc==SQLITE_OK );
+ /* Fall through to the next case, OP_String */
+ /* no break */ deliberate_fall_through
+}
+
+/* Opcode: String P1 P2 P3 P4 P5
+** Synopsis: r[P2]='P4' (len=P1)
+**
+** The string value P4 of length P1 (bytes) is stored in register P2.
+**
+** If P3 is not zero and the content of register P3 is equal to P5, then
+** the datatype of the register P2 is converted to BLOB. The content is
+** the same sequence of bytes, it is merely interpreted as a BLOB instead
+** of a string, as if it had been CAST. In other words:
+**
+** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
+*/
+case OP_String: { /* out2 */
+ assert( pOp->p4.z!=0 );
+ pOut = out2Prerelease(p, pOp);
+ pOut->flags = MEM_Str|MEM_Static|MEM_Term;
+ pOut->z = pOp->p4.z;
+ pOut->n = pOp->p1;
+ pOut->enc = encoding;
+ UPDATE_MAX_BLOBSIZE(pOut);
+#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
+ if( pOp->p3>0 ){
+ assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
+ pIn3 = &aMem[pOp->p3];
+ assert( pIn3->flags & MEM_Int );
+ if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
+ }
+#endif
+ break;
+}
+
+/* Opcode: Null P1 P2 P3 * *
+** Synopsis: r[P2..P3]=NULL
+**
+** Write a NULL into registers P2. If P3 greater than P2, then also write
+** NULL into register P3 and every register in between P2 and P3. If P3
+** is less than P2 (typically P3 is zero) then only register P2 is
+** set to NULL.
+**
+** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
+** NULL values will not compare equal even if SQLITE_NULLEQ is set on
+** OP_Ne or OP_Eq.
+*/
+case OP_Null: { /* out2 */
+ int cnt;
+ u16 nullFlag;
+ pOut = out2Prerelease(p, pOp);
+ cnt = pOp->p3-pOp->p2;
+ assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
+ pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
+ pOut->n = 0;
+#ifdef SQLITE_DEBUG
+ pOut->uTemp = 0;
+#endif
+ while( cnt>0 ){
+ pOut++;
+ memAboutToChange(p, pOut);
+ sqlite3VdbeMemSetNull(pOut);
+ pOut->flags = nullFlag;
+ pOut->n = 0;
+ cnt--;
+ }
+ break;
+}
+
+/* Opcode: SoftNull P1 * * * *
+** Synopsis: r[P1]=NULL
+**
+** Set register P1 to have the value NULL as seen by the OP_MakeRecord
+** instruction, but do not free any string or blob memory associated with
+** the register, so that if the value was a string or blob that was
+** previously copied using OP_SCopy, the copies will continue to be valid.
+*/
+case OP_SoftNull: {
+ assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
+ pOut = &aMem[pOp->p1];
+ pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
+ break;
+}
+
+/* Opcode: Blob P1 P2 * P4 *
+** Synopsis: r[P2]=P4 (len=P1)
+**
+** P4 points to a blob of data P1 bytes long. Store this
+** blob in register P2.
+*/
+case OP_Blob: { /* out2 */
+ assert( pOp->p1 <= SQLITE_MAX_LENGTH );
+ pOut = out2Prerelease(p, pOp);
+ sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
+ pOut->enc = encoding;
+ UPDATE_MAX_BLOBSIZE(pOut);
+ break;
+}
+
+/* Opcode: Variable P1 P2 * P4 *
+** Synopsis: r[P2]=parameter(P1,P4)
+**
+** Transfer the values of bound parameter P1 into register P2
+**
+** If the parameter is named, then its name appears in P4.
+** The P4 value is used by sqlite3_bind_parameter_name().
+*/
+case OP_Variable: { /* out2 */
+ Mem *pVar; /* Value being transferred */
+
+ assert( pOp->p1>0 && pOp->p1<=p->nVar );
+ assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
+ pVar = &p->aVar[pOp->p1 - 1];
+ if( sqlite3VdbeMemTooBig(pVar) ){
+ goto too_big;
+ }
+ pOut = &aMem[pOp->p2];
+ if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
+ memcpy(pOut, pVar, MEMCELLSIZE);
+ pOut->flags &= ~(MEM_Dyn|MEM_Ephem);
+ pOut->flags |= MEM_Static|MEM_FromBind;
+ UPDATE_MAX_BLOBSIZE(pOut);
+ break;
+}
+
+/* Opcode: Move P1 P2 P3 * *
+** Synopsis: r[P2@P3]=r[P1@P3]
+**
+** Move the P3 values in register P1..P1+P3-1 over into
+** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
+** left holding a NULL. It is an error for register ranges
+** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
+** for P3 to be less than 1.
+*/
+case OP_Move: {
+ int n; /* Number of registers left to copy */
+ int p1; /* Register to copy from */
+ int p2; /* Register to copy to */
+
+ n = pOp->p3;
+ p1 = pOp->p1;
+ p2 = pOp->p2;
+ assert( n>0 && p1>0 && p2>0 );
+ assert( p1+n<=p2 || p2+n<=p1 );
+
+ pIn1 = &aMem[p1];
+ pOut = &aMem[p2];
+ do{
+ assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
+ assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
+ assert( memIsValid(pIn1) );
+ memAboutToChange(p, pOut);
+ sqlite3VdbeMemMove(pOut, pIn1);
+#ifdef SQLITE_DEBUG
+ pIn1->pScopyFrom = 0;
+ { int i;
+ for(i=1; i<p->nMem; i++){
+ if( aMem[i].pScopyFrom==pIn1 ){
+ aMem[i].pScopyFrom = pOut;
+ }
+ }
+ }
+#endif
+ Deephemeralize(pOut);
+ REGISTER_TRACE(p2++, pOut);
+ pIn1++;
+ pOut++;
+ }while( --n );
+ break;
+}
+
+/* Opcode: Copy P1 P2 P3 * *
+** Synopsis: r[P2@P3+1]=r[P1@P3+1]
+**
+** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
+**
+** This instruction makes a deep copy of the value. A duplicate
+** is made of any string or blob constant. See also OP_SCopy.
+*/
+case OP_Copy: {
+ int n;
+
+ n = pOp->p3;
+ pIn1 = &aMem[pOp->p1];
+ pOut = &aMem[pOp->p2];
+ assert( pOut!=pIn1 );
+ while( 1 ){
+ memAboutToChange(p, pOut);
+ sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
+ Deephemeralize(pOut);
+#ifdef SQLITE_DEBUG
+ pOut->pScopyFrom = 0;
+#endif
+ REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
+ if( (n--)==0 ) break;
+ pOut++;
+ pIn1++;
+ }
+ break;
+}
+
+/* Opcode: SCopy P1 P2 * * *
+** Synopsis: r[P2]=r[P1]
+**
+** Make a shallow copy of register P1 into register P2.
+**
+** This instruction makes a shallow copy of the value. If the value
+** is a string or blob, then the copy is only a pointer to the
+** original and hence if the original changes so will the copy.
+** Worse, if the original is deallocated, the copy becomes invalid.
+** Thus the program must guarantee that the original will not change
+** during the lifetime of the copy. Use OP_Copy to make a complete
+** copy.
+*/
+case OP_SCopy: { /* out2 */
+ pIn1 = &aMem[pOp->p1];
+ pOut = &aMem[pOp->p2];
+ assert( pOut!=pIn1 );
+ sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
+#ifdef SQLITE_DEBUG
+ pOut->pScopyFrom = pIn1;
+ pOut->mScopyFlags = pIn1->flags;
+#endif
+ break;
+}
+
+/* Opcode: IntCopy P1 P2 * * *
+** Synopsis: r[P2]=r[P1]
+**
+** Transfer the integer value held in register P1 into register P2.
+**
+** This is an optimized version of SCopy that works only for integer
+** values.
+*/
+case OP_IntCopy: { /* out2 */
+ pIn1 = &aMem[pOp->p1];
+ assert( (pIn1->flags & MEM_Int)!=0 );
+ pOut = &aMem[pOp->p2];
+ sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
+ break;
+}
+
+/* Opcode: ResultRow P1 P2 * * *
+** Synopsis: output=r[P1@P2]
+**
+** The registers P1 through P1+P2-1 contain a single row of
+** results. This opcode causes the sqlite3_step() call to terminate
+** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
+** structure to provide access to the r(P1)..r(P1+P2-1) values as
+** the result row.
+*/
+case OP_ResultRow: {
+ Mem *pMem;
+ int i;
+ assert( p->nResColumn==pOp->p2 );
+ assert( pOp->p1>0 );
+ assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
+
+ /* If this statement has violated immediate foreign key constraints, do
+ ** not return the number of rows modified. And do not RELEASE the statement
+ ** transaction. It needs to be rolled back. */
+ if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
+ assert( db->flags&SQLITE_CountRows );
+ assert( p->usesStmtJournal );
+ goto abort_due_to_error;
+ }
+
+ /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
+ ** DML statements invoke this opcode to return the number of rows
+ ** modified to the user. This is the only way that a VM that
+ ** opens a statement transaction may invoke this opcode.
+ **
+ ** In case this is such a statement, close any statement transaction
+ ** opened by this VM before returning control to the user. This is to
+ ** ensure that statement-transactions are always nested, not overlapping.
+ ** If the open statement-transaction is not closed here, then the user
+ ** may step another VM that opens its own statement transaction. This
+ ** may lead to overlapping statement transactions.
+ **
+ ** The statement transaction is never a top-level transaction. Hence
+ ** the RELEASE call below can never fail.
+ */
+ assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
+ rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
+ assert( rc==SQLITE_OK );
+
+ /* Invalidate all ephemeral cursor row caches */
+ p->cacheCtr = (p->cacheCtr + 2)|1;
+
+ /* Make sure the results of the current row are \000 terminated
+ ** and have an assigned type. The results are de-ephemeralized as
+ ** a side effect.
+ */
+ pMem = p->pResultSet = &aMem[pOp->p1];
+ for(i=0; i<pOp->p2; i++){
+ assert( memIsValid(&pMem[i]) );
+ Deephemeralize(&pMem[i]);
+ assert( (pMem[i].flags & MEM_Ephem)==0
+ || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
+ sqlite3VdbeMemNulTerminate(&pMem[i]);
+ REGISTER_TRACE(pOp->p1+i, &pMem[i]);
+#ifdef SQLITE_DEBUG
+ /* The registers in the result will not be used again when the
+ ** prepared statement restarts. This is because sqlite3_column()
+ ** APIs might have caused type conversions of made other changes to
+ ** the register values. Therefore, we can go ahead and break any
+ ** OP_SCopy dependencies. */
+ pMem[i].pScopyFrom = 0;
+#endif
+ }
+ if( db->mallocFailed ) goto no_mem;
+
+ if( db->mTrace & SQLITE_TRACE_ROW ){
+ db->trace.xV2(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
+ }
+
+
+ /* Return SQLITE_ROW
+ */
+ p->pc = (int)(pOp - aOp) + 1;
+ rc = SQLITE_ROW;
+ goto vdbe_return;
+}
+
+/* Opcode: Concat P1 P2 P3 * *
+** Synopsis: r[P3]=r[P2]+r[P1]
+**
+** Add the text in register P1 onto the end of the text in
+** register P2 and store the result in register P3.
+** If either the P1 or P2 text are NULL then store NULL in P3.
+**
+** P3 = P2 || P1
+**
+** It is illegal for P1 and P3 to be the same register. Sometimes,
+** if P3 is the same register as P2, the implementation is able
+** to avoid a memcpy().
+*/
+case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
+ i64 nByte; /* Total size of the output string or blob */
+ u16 flags1; /* Initial flags for P1 */
+ u16 flags2; /* Initial flags for P2 */
+
+ pIn1 = &aMem[pOp->p1];
+ pIn2 = &aMem[pOp->p2];
+ pOut = &aMem[pOp->p3];
+ testcase( pOut==pIn2 );
+ assert( pIn1!=pOut );
+ flags1 = pIn1->flags;
+ testcase( flags1 & MEM_Null );
+ testcase( pIn2->flags & MEM_Null );
+ if( (flags1 | pIn2->flags) & MEM_Null ){
+ sqlite3VdbeMemSetNull(pOut);
+ break;
+ }
+ if( (flags1 & (MEM_Str|MEM_Blob))==0 ){
+ if( sqlite3VdbeMemStringify(pIn1,encoding,0) ) goto no_mem;
+ flags1 = pIn1->flags & ~MEM_Str;
+ }else if( (flags1 & MEM_Zero)!=0 ){
+ if( sqlite3VdbeMemExpandBlob(pIn1) ) goto no_mem;
+ flags1 = pIn1->flags & ~MEM_Str;
+ }
+ flags2 = pIn2->flags;
+ if( (flags2 & (MEM_Str|MEM_Blob))==0 ){
+ if( sqlite3VdbeMemStringify(pIn2,encoding,0) ) goto no_mem;
+ flags2 = pIn2->flags & ~MEM_Str;
+ }else if( (flags2 & MEM_Zero)!=0 ){
+ if( sqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem;
+ flags2 = pIn2->flags & ~MEM_Str;
+ }
+ nByte = pIn1->n + pIn2->n;
+ if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
+ goto too_big;
+ }
+ if( sqlite3VdbeMemGrow(pOut, (int)nByte+3, pOut==pIn2) ){
+ goto no_mem;
+ }
+ MemSetTypeFlag(pOut, MEM_Str);
+ if( pOut!=pIn2 ){
+ memcpy(pOut->z, pIn2->z, pIn2->n);
+ assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) );
+ pIn2->flags = flags2;
+ }
+ memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
+ assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
+ pIn1->flags = flags1;
+ pOut->z[nByte]=0;
+ pOut->z[nByte+1] = 0;
+ pOut->z[nByte+2] = 0;
+ pOut->flags |= MEM_Term;
+ pOut->n = (int)nByte;
+ pOut->enc = encoding;
+ UPDATE_MAX_BLOBSIZE(pOut);
+ break;
+}
+
+/* Opcode: Add P1 P2 P3 * *
+** Synopsis: r[P3]=r[P1]+r[P2]
+**
+** Add the value in register P1 to the value in register P2
+** and store the result in register P3.
+** If either input is NULL, the result is NULL.
+*/
+/* Opcode: Multiply P1 P2 P3 * *
+** Synopsis: r[P3]=r[P1]*r[P2]
+**
+**
+** Multiply the value in register P1 by the value in register P2
+** and store the result in register P3.
+** If either input is NULL, the result is NULL.
+*/
+/* Opcode: Subtract P1 P2 P3 * *
+** Synopsis: r[P3]=r[P2]-r[P1]
+**
+** Subtract the value in register P1 from the value in register P2
+** and store the result in register P3.
+** If either input is NULL, the result is NULL.
+*/
+/* Opcode: Divide P1 P2 P3 * *
+** Synopsis: r[P3]=r[P2]/r[P1]
+**
+** Divide the value in register P1 by the value in register P2
+** and store the result in register P3 (P3=P2/P1). If the value in
+** register P1 is zero, then the result is NULL. If either input is
+** NULL, the result is NULL.
+*/
+/* Opcode: Remainder P1 P2 P3 * *
+** Synopsis: r[P3]=r[P2]%r[P1]
+**
+** Compute the remainder after integer register P2 is divided by
+** register P1 and store the result in register P3.
+** If the value in register P1 is zero the result is NULL.
+** If either operand is NULL, the result is NULL.
+*/
+case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
+case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
+case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
+case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
+case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
+ u16 flags; /* Combined MEM_* flags from both inputs */
+ u16 type1; /* Numeric type of left operand */
+ u16 type2; /* Numeric type of right operand */
+ i64 iA; /* Integer value of left operand */
+ i64 iB; /* Integer value of right operand */
+ double rA; /* Real value of left operand */
+ double rB; /* Real value of right operand */
+
+ pIn1 = &aMem[pOp->p1];
+ type1 = numericType(pIn1);
+ pIn2 = &aMem[pOp->p2];
+ type2 = numericType(pIn2);
+ pOut = &aMem[pOp->p3];
+ flags = pIn1->flags | pIn2->flags;
+ if( (type1 & type2 & MEM_Int)!=0 ){
+ iA = pIn1->u.i;
+ iB = pIn2->u.i;
+ switch( pOp->opcode ){
+ case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
+ case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
+ case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
+ case OP_Divide: {
+ if( iA==0 ) goto arithmetic_result_is_null;
+ if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
+ iB /= iA;
+ break;
+ }
+ default: {
+ if( iA==0 ) goto arithmetic_result_is_null;
+ if( iA==-1 ) iA = 1;
+ iB %= iA;
+ break;
+ }
+ }
+ pOut->u.i = iB;
+ MemSetTypeFlag(pOut, MEM_Int);
+ }else if( (flags & MEM_Null)!=0 ){
+ goto arithmetic_result_is_null;
+ }else{
+fp_math:
+ rA = sqlite3VdbeRealValue(pIn1);
+ rB = sqlite3VdbeRealValue(pIn2);
+ switch( pOp->opcode ){
+ case OP_Add: rB += rA; break;
+ case OP_Subtract: rB -= rA; break;
+ case OP_Multiply: rB *= rA; break;
+ case OP_Divide: {
+ /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
+ if( rA==(double)0 ) goto arithmetic_result_is_null;
+ rB /= rA;
+ break;
+ }
+ default: {
+ iA = sqlite3VdbeIntValue(pIn1);
+ iB = sqlite3VdbeIntValue(pIn2);
+ if( iA==0 ) goto arithmetic_result_is_null;
+ if( iA==-1 ) iA = 1;
+ rB = (double)(iB % iA);
+ break;
+ }
+ }
+#ifdef SQLITE_OMIT_FLOATING_POINT
+ pOut->u.i = rB;
+ MemSetTypeFlag(pOut, MEM_Int);
+#else
+ if( sqlite3IsNaN(rB) ){
+ goto arithmetic_result_is_null;
+ }
+ pOut->u.r = rB;
+ MemSetTypeFlag(pOut, MEM_Real);
+#endif
+ }
+ break;
+
+arithmetic_result_is_null:
+ sqlite3VdbeMemSetNull(pOut);
+ break;
+}
+
+/* Opcode: CollSeq P1 * * P4
+**
+** P4 is a pointer to a CollSeq object. If the next call to a user function
+** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
+** be returned. This is used by the built-in min(), max() and nullif()
+** functions.
+**
+** If P1 is not zero, then it is a register that a subsequent min() or
+** max() aggregate will set to 1 if the current row is not the minimum or
+** maximum. The P1 register is initialized to 0 by this instruction.
+**
+** The interface used by the implementation of the aforementioned functions
+** to retrieve the collation sequence set by this opcode is not available
+** publicly. Only built-in functions have access to this feature.
+*/
+case OP_CollSeq: {
+ assert( pOp->p4type==P4_COLLSEQ );
+ if( pOp->p1 ){
+ sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
+ }
+ break;
+}
+
+/* Opcode: BitAnd P1 P2 P3 * *
+** Synopsis: r[P3]=r[P1]&r[P2]
+**
+** Take the bit-wise AND of the values in register P1 and P2 and
+** store the result in register P3.
+** If either input is NULL, the result is NULL.
+*/
+/* Opcode: BitOr P1 P2 P3 * *
+** Synopsis: r[P3]=r[P1]|r[P2]
+**
+** Take the bit-wise OR of the values in register P1 and P2 and
+** store the result in register P3.
+** If either input is NULL, the result is NULL.
+*/
+/* Opcode: ShiftLeft P1 P2 P3 * *
+** Synopsis: r[P3]=r[P2]<<r[P1]
+**
+** Shift the integer value in register P2 to the left by the
+** number of bits specified by the integer in register P1.
+** Store the result in register P3.
+** If either input is NULL, the result is NULL.
+*/
+/* Opcode: ShiftRight P1 P2 P3 * *
+** Synopsis: r[P3]=r[P2]>>r[P1]
+**
+** Shift the integer value in register P2 to the right by the
+** number of bits specified by the integer in register P1.
+** Store the result in register P3.
+** If either input is NULL, the result is NULL.
+*/
+case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
+case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
+case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
+case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
+ i64 iA;
+ u64 uA;
+ i64 iB;
+ u8 op;
+
+ pIn1 = &aMem[pOp->p1];
+ pIn2 = &aMem[pOp->p2];
+ pOut = &aMem[pOp->p3];
+ if( (pIn1->flags | pIn2->flags) & MEM_Null ){
+ sqlite3VdbeMemSetNull(pOut);
+ break;
+ }
+ iA = sqlite3VdbeIntValue(pIn2);
+ iB = sqlite3VdbeIntValue(pIn1);
+ op = pOp->opcode;
+ if( op==OP_BitAnd ){
+ iA &= iB;
+ }else if( op==OP_BitOr ){
+ iA |= iB;
+ }else if( iB!=0 ){
+ assert( op==OP_ShiftRight || op==OP_ShiftLeft );
+
+ /* If shifting by a negative amount, shift in the other direction */
+ if( iB<0 ){
+ assert( OP_ShiftRight==OP_ShiftLeft+1 );
+ op = 2*OP_ShiftLeft + 1 - op;
+ iB = iB>(-64) ? -iB : 64;
+ }
+
+ if( iB>=64 ){
+ iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
+ }else{
+ memcpy(&uA, &iA, sizeof(uA));
+ if( op==OP_ShiftLeft ){
+ uA <<= iB;
+ }else{
+ uA >>= iB;
+ /* Sign-extend on a right shift of a negative number */
+ if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
+ }
+ memcpy(&iA, &uA, sizeof(iA));
+ }
+ }
+ pOut->u.i = iA;
+ MemSetTypeFlag(pOut, MEM_Int);
+ break;
+}
+
+/* Opcode: AddImm P1 P2 * * *
+** Synopsis: r[P1]=r[P1]+P2
+**
+** Add the constant P2 to the value in register P1.
+** The result is always an integer.
+**
+** To force any register to be an integer, just add 0.
+*/
+case OP_AddImm: { /* in1 */
+ pIn1 = &aMem[pOp->p1];
+ memAboutToChange(p, pIn1);
+ sqlite3VdbeMemIntegerify(pIn1);
+ pIn1->u.i += pOp->p2;
+ break;
+}
+
+/* Opcode: MustBeInt P1 P2 * * *
+**
+** Force the value in register P1 to be an integer. If the value
+** in P1 is not an integer and cannot be converted into an integer
+** without data loss, then jump immediately to P2, or if P2==0
+** raise an SQLITE_MISMATCH exception.
+*/
+case OP_MustBeInt: { /* jump, in1 */
+ pIn1 = &aMem[pOp->p1];
+ if( (pIn1->flags & MEM_Int)==0 ){
+ applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
+ if( (pIn1->flags & MEM_Int)==0 ){
+ VdbeBranchTaken(1, 2);
+ if( pOp->p2==0 ){
+ rc = SQLITE_MISMATCH;
+ goto abort_due_to_error;
+ }else{
+ goto jump_to_p2;
+ }
+ }
+ }
+ VdbeBranchTaken(0, 2);
+ MemSetTypeFlag(pIn1, MEM_Int);
+ break;
+}
+
+#ifndef SQLITE_OMIT_FLOATING_POINT
+/* Opcode: RealAffinity P1 * * * *
+**
+** If register P1 holds an integer convert it to a real value.
+**
+** This opcode is used when extracting information from a column that
+** has REAL affinity. Such column values may still be stored as
+** integers, for space efficiency, but after extraction we want them
+** to have only a real value.
+*/
+case OP_RealAffinity: { /* in1 */
+ pIn1 = &aMem[pOp->p1];
+ if( pIn1->flags & (MEM_Int|MEM_IntReal) ){
+ testcase( pIn1->flags & MEM_Int );
+ testcase( pIn1->flags & MEM_IntReal );
+ sqlite3VdbeMemRealify(pIn1);
+ REGISTER_TRACE(pOp->p1, pIn1);
+ }
+ break;
+}
+#endif
+
+#ifndef SQLITE_OMIT_CAST
+/* Opcode: Cast P1 P2 * * *
+** Synopsis: affinity(r[P1])
+**
+** Force the value in register P1 to be the type defined by P2.
+**
+** <ul>
+** <li> P2=='A' &rarr; BLOB
+** <li> P2=='B' &rarr; TEXT
+** <li> P2=='C' &rarr; NUMERIC
+** <li> P2=='D' &rarr; INTEGER
+** <li> P2=='E' &rarr; REAL
+** </ul>
+**
+** A NULL value is not changed by this routine. It remains NULL.
+*/
+case OP_Cast: { /* in1 */
+ assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
+ testcase( pOp->p2==SQLITE_AFF_TEXT );
+ testcase( pOp->p2==SQLITE_AFF_BLOB );
+ testcase( pOp->p2==SQLITE_AFF_NUMERIC );
+ testcase( pOp->p2==SQLITE_AFF_INTEGER );
+ testcase( pOp->p2==SQLITE_AFF_REAL );
+ pIn1 = &aMem[pOp->p1];
+ memAboutToChange(p, pIn1);
+ rc = ExpandBlob(pIn1);
+ if( rc ) goto abort_due_to_error;
+ rc = sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
+ if( rc ) goto abort_due_to_error;
+ UPDATE_MAX_BLOBSIZE(pIn1);
+ REGISTER_TRACE(pOp->p1, pIn1);
+ break;
+}
+#endif /* SQLITE_OMIT_CAST */
+
+/* Opcode: Eq P1 P2 P3 P4 P5
+** Synopsis: IF r[P3]==r[P1]
+**
+** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
+** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
+** store the result of comparison in register P2.
+**
+** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
+** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
+** to coerce both inputs according to this affinity before the
+** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
+** affinity is used. Note that the affinity conversions are stored
+** back into the input registers P1 and P3. So this opcode can cause
+** persistent changes to registers P1 and P3.
+**
+** Once any conversions have taken place, and neither value is NULL,
+** the values are compared. If both values are blobs then memcmp() is
+** used to determine the results of the comparison. If both values
+** are text, then the appropriate collating function specified in
+** P4 is used to do the comparison. If P4 is not specified then
+** memcmp() is used to compare text string. If both values are
+** numeric, then a numeric comparison is used. If the two values
+** are of different types, then numbers are considered less than
+** strings and strings are considered less than blobs.
+**
+** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
+** true or false and is never NULL. If both operands are NULL then the result
+** of comparison is true. If either operand is NULL then the result is false.
+** If neither operand is NULL the result is the same as it would be if
+** the SQLITE_NULLEQ flag were omitted from P5.
+**
+** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
+** content of r[P2] is only changed if the new value is NULL or 0 (false).
+** In other words, a prior r[P2] value will not be overwritten by 1 (true).
+*/
+/* Opcode: Ne P1 P2 P3 P4 P5
+** Synopsis: IF r[P3]!=r[P1]
+**
+** This works just like the Eq opcode except that the jump is taken if
+** the operands in registers P1 and P3 are not equal. See the Eq opcode for
+** additional information.
+**
+** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
+** content of r[P2] is only changed if the new value is NULL or 1 (true).
+** In other words, a prior r[P2] value will not be overwritten by 0 (false).
+*/
+/* Opcode: Lt P1 P2 P3 P4 P5
+** Synopsis: IF r[P3]<r[P1]
+**
+** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
+** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
+** the result of comparison (0 or 1 or NULL) into register P2.
+**
+** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
+** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
+** bit is clear then fall through if either operand is NULL.
+**
+** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
+** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
+** to coerce both inputs according to this affinity before the
+** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
+** affinity is used. Note that the affinity conversions are stored
+** back into the input registers P1 and P3. So this opcode can cause
+** persistent changes to registers P1 and P3.
+**
+** Once any conversions have taken place, and neither value is NULL,
+** the values are compared. If both values are blobs then memcmp() is
+** used to determine the results of the comparison. If both values
+** are text, then the appropriate collating function specified in
+** P4 is used to do the comparison. If P4 is not specified then
+** memcmp() is used to compare text string. If both values are
+** numeric, then a numeric comparison is used. If the two values
+** are of different types, then numbers are considered less than
+** strings and strings are considered less than blobs.
+*/
+/* Opcode: Le P1 P2 P3 P4 P5
+** Synopsis: IF r[P3]<=r[P1]
+**
+** This works just like the Lt opcode except that the jump is taken if
+** the content of register P3 is less than or equal to the content of
+** register P1. See the Lt opcode for additional information.
+*/
+/* Opcode: Gt P1 P2 P3 P4 P5
+** Synopsis: IF r[P3]>r[P1]
+**
+** This works just like the Lt opcode except that the jump is taken if
+** the content of register P3 is greater than the content of
+** register P1. See the Lt opcode for additional information.
+*/
+/* Opcode: Ge P1 P2 P3 P4 P5
+** Synopsis: IF r[P3]>=r[P1]
+**
+** This works just like the Lt opcode except that the jump is taken if
+** the content of register P3 is greater than or equal to the content of
+** register P1. See the Lt opcode for additional information.
+*/
+case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
+case OP_Ne: /* same as TK_NE, jump, in1, in3 */
+case OP_Lt: /* same as TK_LT, jump, in1, in3 */
+case OP_Le: /* same as TK_LE, jump, in1, in3 */
+case OP_Gt: /* same as TK_GT, jump, in1, in3 */
+case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
+ int res, res2; /* Result of the comparison of pIn1 against pIn3 */
+ char affinity; /* Affinity to use for comparison */
+ u16 flags1; /* Copy of initial value of pIn1->flags */
+ u16 flags3; /* Copy of initial value of pIn3->flags */
+
+ pIn1 = &aMem[pOp->p1];
+ pIn3 = &aMem[pOp->p3];
+ flags1 = pIn1->flags;
+ flags3 = pIn3->flags;
+ if( (flags1 | flags3)&MEM_Null ){
+ /* One or both operands are NULL */
+ if( pOp->p5 & SQLITE_NULLEQ ){
+ /* If SQLITE_NULLEQ is set (which will only happen if the operator is
+ ** OP_Eq or OP_Ne) then take the jump or not depending on whether
+ ** or not both operands are null.
+ */
+ assert( (flags1 & MEM_Cleared)==0 );
+ assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB );
+ testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 );
+ if( (flags1&flags3&MEM_Null)!=0
+ && (flags3&MEM_Cleared)==0
+ ){
+ res = 0; /* Operands are equal */
+ }else{
+ res = ((flags3 & MEM_Null) ? -1 : +1); /* Operands are not equal */
+ }
+ }else{
+ /* SQLITE_NULLEQ is clear and at least one operand is NULL,
+ ** then the result is always NULL.
+ ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
+ */
+ if( pOp->p5 & SQLITE_STOREP2 ){
+ pOut = &aMem[pOp->p2];
+ iCompare = 1; /* Operands are not equal */
+ memAboutToChange(p, pOut);
+ MemSetTypeFlag(pOut, MEM_Null);
+ REGISTER_TRACE(pOp->p2, pOut);
+ }else{
+ VdbeBranchTaken(2,3);
+ if( pOp->p5 & SQLITE_JUMPIFNULL ){
+ goto jump_to_p2;
+ }
+ }
+ break;
+ }
+ }else{
+ /* Neither operand is NULL. Do a comparison. */
+ affinity = pOp->p5 & SQLITE_AFF_MASK;
+ if( affinity>=SQLITE_AFF_NUMERIC ){
+ if( (flags1 | flags3)&MEM_Str ){
+ if( (flags1 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
+ applyNumericAffinity(pIn1,0);
+ testcase( flags3==pIn3->flags );
+ flags3 = pIn3->flags;
+ }
+ if( (flags3 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
+ applyNumericAffinity(pIn3,0);
+ }
+ }
+ /* Handle the common case of integer comparison here, as an
+ ** optimization, to avoid a call to sqlite3MemCompare() */
+ if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
+ if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
+ if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
+ res = 0;
+ goto compare_op;
+ }
+ }else if( affinity==SQLITE_AFF_TEXT ){
+ if( (flags1 & MEM_Str)==0 && (flags1&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
+ testcase( pIn1->flags & MEM_Int );
+ testcase( pIn1->flags & MEM_Real );
+ testcase( pIn1->flags & MEM_IntReal );
+ sqlite3VdbeMemStringify(pIn1, encoding, 1);
+ testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
+ flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
+ if( NEVER(pIn1==pIn3) ) flags3 = flags1 | MEM_Str;
+ }
+ if( (flags3 & MEM_Str)==0 && (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
+ testcase( pIn3->flags & MEM_Int );
+ testcase( pIn3->flags & MEM_Real );
+ testcase( pIn3->flags & MEM_IntReal );
+ sqlite3VdbeMemStringify(pIn3, encoding, 1);
+ testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
+ flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
+ }
+ }
+ assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
+ res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
+ }
+compare_op:
+ /* At this point, res is negative, zero, or positive if reg[P1] is
+ ** less than, equal to, or greater than reg[P3], respectively. Compute
+ ** the answer to this operator in res2, depending on what the comparison
+ ** operator actually is. The next block of code depends on the fact
+ ** that the 6 comparison operators are consecutive integers in this
+ ** order: NE, EQ, GT, LE, LT, GE */
+ assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
+ assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
+ if( res<0 ){ /* ne, eq, gt, le, lt, ge */
+ static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
+ res2 = aLTb[pOp->opcode - OP_Ne];
+ }else if( res==0 ){
+ static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
+ res2 = aEQb[pOp->opcode - OP_Ne];
+ }else{
+ static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
+ res2 = aGTb[pOp->opcode - OP_Ne];
+ }
+
+ /* Undo any changes made by applyAffinity() to the input registers. */
+ assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
+ pIn3->flags = flags3;
+ assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
+ pIn1->flags = flags1;
+
+ if( pOp->p5 & SQLITE_STOREP2 ){
+ pOut = &aMem[pOp->p2];
+ iCompare = res;
+ if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
+ /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
+ ** and prevents OP_Ne from overwriting NULL with 0. This flag
+ ** is only used in contexts where either:
+ ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
+ ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
+ ** Therefore it is not necessary to check the content of r[P2] for
+ ** NULL. */
+ assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
+ assert( res2==0 || res2==1 );
+ testcase( res2==0 && pOp->opcode==OP_Eq );
+ testcase( res2==1 && pOp->opcode==OP_Eq );
+ testcase( res2==0 && pOp->opcode==OP_Ne );
+ testcase( res2==1 && pOp->opcode==OP_Ne );
+ if( (pOp->opcode==OP_Eq)==res2 ) break;
+ }
+ memAboutToChange(p, pOut);
+ MemSetTypeFlag(pOut, MEM_Int);
+ pOut->u.i = res2;
+ REGISTER_TRACE(pOp->p2, pOut);
+ }else{
+ VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
+ if( res2 ){
+ goto jump_to_p2;
+ }
+ }
+ break;
+}
+
+/* Opcode: ElseNotEq * P2 * * *
+**
+** This opcode must follow an OP_Lt or OP_Gt comparison operator. There
+** can be zero or more OP_ReleaseReg opcodes intervening, but no other
+** opcodes are allowed to occur between this instruction and the previous
+** OP_Lt or OP_Gt. Furthermore, the prior OP_Lt or OP_Gt must have the
+** SQLITE_STOREP2 bit set in the P5 field.
+**
+** If result of an OP_Eq comparison on the same two operands as the
+** prior OP_Lt or OP_Gt would have been NULL or false (0), then then
+** jump to P2. If the result of an OP_Eq comparison on the two previous
+** operands would have been true (1), then fall through.
+*/
+case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
+
+#ifdef SQLITE_DEBUG
+ /* Verify the preconditions of this opcode - that it follows an OP_Lt or
+ ** OP_Gt with the SQLITE_STOREP2 flag set, with zero or more intervening
+ ** OP_ReleaseReg opcodes */
+ int iAddr;
+ for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){
+ if( aOp[iAddr].opcode==OP_ReleaseReg ) continue;
+ assert( aOp[iAddr].opcode==OP_Lt || aOp[iAddr].opcode==OP_Gt );
+ assert( aOp[iAddr].p5 & SQLITE_STOREP2 );
+ break;
+ }
+#endif /* SQLITE_DEBUG */
+ VdbeBranchTaken(iCompare!=0, 2);
+ if( iCompare!=0 ) goto jump_to_p2;
+ break;
+}
+
+
+/* Opcode: Permutation * * * P4 *
+**
+** Set the permutation used by the OP_Compare operator in the next
+** instruction. The permutation is stored in the P4 operand.
+**
+** The permutation is only valid until the next OP_Compare that has
+** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
+** occur immediately prior to the OP_Compare.
+**
+** The first integer in the P4 integer array is the length of the array
+** and does not become part of the permutation.
+*/
+case OP_Permutation: {
+ assert( pOp->p4type==P4_INTARRAY );
+ assert( pOp->p4.ai );
+ assert( pOp[1].opcode==OP_Compare );
+ assert( pOp[1].p5 & OPFLAG_PERMUTE );
+ break;
+}
+
+/* Opcode: Compare P1 P2 P3 P4 P5
+** Synopsis: r[P1@P3] <-> r[P2@P3]
+**
+** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
+** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
+** the comparison for use by the next OP_Jump instruct.
+**
+** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
+** determined by the most recent OP_Permutation operator. If the
+** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
+** order.
+**
+** P4 is a KeyInfo structure that defines collating sequences and sort
+** orders for the comparison. The permutation applies to registers
+** only. The KeyInfo elements are used sequentially.
+**
+** The comparison is a sort comparison, so NULLs compare equal,
+** NULLs are less than numbers, numbers are less than strings,
+** and strings are less than blobs.
+*/
+case OP_Compare: {
+ int n;
+ int i;
+ int p1;
+ int p2;
+ const KeyInfo *pKeyInfo;
+ u32 idx;
+ CollSeq *pColl; /* Collating sequence to use on this term */
+ int bRev; /* True for DESCENDING sort order */
+ u32 *aPermute; /* The permutation */
+
+ if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
+ aPermute = 0;
+ }else{
+ assert( pOp>aOp );
+ assert( pOp[-1].opcode==OP_Permutation );
+ assert( pOp[-1].p4type==P4_INTARRAY );
+ aPermute = pOp[-1].p4.ai + 1;
+ assert( aPermute!=0 );
+ }
+ n = pOp->p3;
+ pKeyInfo = pOp->p4.pKeyInfo;
+ assert( n>0 );
+ assert( pKeyInfo!=0 );
+ p1 = pOp->p1;
+ p2 = pOp->p2;
+#ifdef SQLITE_DEBUG
+ if( aPermute ){
+ int k, mx = 0;
+ for(k=0; k<n; k++) if( aPermute[k]>(u32)mx ) mx = aPermute[k];
+ assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
+ assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
+ }else{
+ assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
+ assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
+ }
+#endif /* SQLITE_DEBUG */
+ for(i=0; i<n; i++){
+ idx = aPermute ? aPermute[i] : (u32)i;
+ assert( memIsValid(&aMem[p1+idx]) );
+ assert( memIsValid(&aMem[p2+idx]) );
+ REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
+ REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
+ assert( i<pKeyInfo->nKeyField );
+ pColl = pKeyInfo->aColl[i];
+ bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC);
+ iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
+ if( iCompare ){
+ if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
+ && ((aMem[p1+idx].flags & MEM_Null) || (aMem[p2+idx].flags & MEM_Null))
+ ){
+ iCompare = -iCompare;
+ }
+ if( bRev ) iCompare = -iCompare;
+ break;
+ }
+ }
+ break;
+}
+
+/* Opcode: Jump P1 P2 P3 * *
+**
+** Jump to the instruction at address P1, P2, or P3 depending on whether
+** in the most recent OP_Compare instruction the P1 vector was less than
+** equal to, or greater than the P2 vector, respectively.
+*/
+case OP_Jump: { /* jump */
+ if( iCompare<0 ){
+ VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];
+ }else if( iCompare==0 ){
+ VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];
+ }else{
+ VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];
+ }
+ break;
+}
+
+/* Opcode: And P1 P2 P3 * *
+** Synopsis: r[P3]=(r[P1] && r[P2])
+**
+** Take the logical AND of the values in registers P1 and P2 and
+** write the result into register P3.
+**
+** If either P1 or P2 is 0 (false) then the result is 0 even if
+** the other input is NULL. A NULL and true or two NULLs give
+** a NULL output.
+*/
+/* Opcode: Or P1 P2 P3 * *
+** Synopsis: r[P3]=(r[P1] || r[P2])
+**
+** Take the logical OR of the values in register P1 and P2 and
+** store the answer in register P3.
+**
+** If either P1 or P2 is nonzero (true) then the result is 1 (true)
+** even if the other input is NULL. A NULL and false or two NULLs
+** give a NULL output.
+*/
+case OP_And: /* same as TK_AND, in1, in2, out3 */
+case OP_Or: { /* same as TK_OR, in1, in2, out3 */
+ int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
+ int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
+
+ v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
+ v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
+ if( pOp->opcode==OP_And ){
+ static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
+ v1 = and_logic[v1*3+v2];
+ }else{
+ static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
+ v1 = or_logic[v1*3+v2];
+ }
+ pOut = &aMem[pOp->p3];
+ if( v1==2 ){
+ MemSetTypeFlag(pOut, MEM_Null);
+ }else{
+ pOut->u.i = v1;
+ MemSetTypeFlag(pOut, MEM_Int);
+ }
+ break;
+}
+
+/* Opcode: IsTrue P1 P2 P3 P4 *
+** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
+**
+** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
+** IS NOT FALSE operators.
+**
+** Interpret the value in register P1 as a boolean value. Store that
+** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
+** NULL, then the P3 is stored in register P2. Invert the answer if P4
+** is 1.
+**
+** The logic is summarized like this:
+**
+** <ul>
+** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
+** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
+** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
+** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
+** </ul>
+*/
+case OP_IsTrue: { /* in1, out2 */
+ assert( pOp->p4type==P4_INT32 );
+ assert( pOp->p4.i==0 || pOp->p4.i==1 );
+ assert( pOp->p3==0 || pOp->p3==1 );
+ sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
+ sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
+ break;
+}
+
+/* Opcode: Not P1 P2 * * *
+** Synopsis: r[P2]= !r[P1]
+**
+** Interpret the value in register P1 as a boolean value. Store the
+** boolean complement in register P2. If the value in register P1 is
+** NULL, then a NULL is stored in P2.
+*/
+case OP_Not: { /* same as TK_NOT, in1, out2 */
+ pIn1 = &aMem[pOp->p1];
+ pOut = &aMem[pOp->p2];
+ if( (pIn1->flags & MEM_Null)==0 ){
+ sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
+ }else{
+ sqlite3VdbeMemSetNull(pOut);
+ }
+ break;
+}
+
+/* Opcode: BitNot P1 P2 * * *
+** Synopsis: r[P2]= ~r[P1]
+**
+** Interpret the content of register P1 as an integer. Store the
+** ones-complement of the P1 value into register P2. If P1 holds
+** a NULL then store a NULL in P2.
+*/
+case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
+ pIn1 = &aMem[pOp->p1];
+ pOut = &aMem[pOp->p2];
+ sqlite3VdbeMemSetNull(pOut);
+ if( (pIn1->flags & MEM_Null)==0 ){
+ pOut->flags = MEM_Int;
+ pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
+ }
+ break;
+}
+
+/* Opcode: Once P1 P2 * * *
+**
+** Fall through to the next instruction the first time this opcode is
+** encountered on each invocation of the byte-code program. Jump to P2
+** on the second and all subsequent encounters during the same invocation.
+**
+** Top-level programs determine first invocation by comparing the P1
+** operand against the P1 operand on the OP_Init opcode at the beginning
+** of the program. If the P1 values differ, then fall through and make
+** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
+** the same then take the jump.
+**
+** For subprograms, there is a bitmask in the VdbeFrame that determines
+** whether or not the jump should be taken. The bitmask is necessary
+** because the self-altering code trick does not work for recursive
+** triggers.
+*/
+case OP_Once: { /* jump */
+ u32 iAddr; /* Address of this instruction */
+ assert( p->aOp[0].opcode==OP_Init );
+ if( p->pFrame ){
+ iAddr = (int)(pOp - p->aOp);
+ if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
+ VdbeBranchTaken(1, 2);
+ goto jump_to_p2;
+ }
+ p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
+ }else{
+ if( p->aOp[0].p1==pOp->p1 ){
+ VdbeBranchTaken(1, 2);
+ goto jump_to_p2;
+ }
+ }
+ VdbeBranchTaken(0, 2);
+ pOp->p1 = p->aOp[0].p1;
+ break;
+}
+
+/* Opcode: If P1 P2 P3 * *
+**
+** Jump to P2 if the value in register P1 is true. The value
+** is considered true if it is numeric and non-zero. If the value
+** in P1 is NULL then take the jump if and only if P3 is non-zero.
+*/
+case OP_If: { /* jump, in1 */
+ int c;
+ c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
+ VdbeBranchTaken(c!=0, 2);
+ if( c ) goto jump_to_p2;
+ break;
+}
+
+/* Opcode: IfNot P1 P2 P3 * *
+**
+** Jump to P2 if the value in register P1 is False. The value
+** is considered false if it has a numeric value of zero. If the value
+** in P1 is NULL then take the jump if and only if P3 is non-zero.
+*/
+case OP_IfNot: { /* jump, in1 */
+ int c;
+ c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
+ VdbeBranchTaken(c!=0, 2);
+ if( c ) goto jump_to_p2;
+ break;
+}
+
+/* Opcode: IsNull P1 P2 * * *
+** Synopsis: if r[P1]==NULL goto P2
+**
+** Jump to P2 if the value in register P1 is NULL.
+*/
+case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
+ pIn1 = &aMem[pOp->p1];
+ VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
+ if( (pIn1->flags & MEM_Null)!=0 ){
+ goto jump_to_p2;
+ }
+ break;
+}
+
+/* Opcode: NotNull P1 P2 * * *
+** Synopsis: if r[P1]!=NULL goto P2
+**
+** Jump to P2 if the value in register P1 is not NULL.
+*/
+case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
+ pIn1 = &aMem[pOp->p1];
+ VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
+ if( (pIn1->flags & MEM_Null)==0 ){
+ goto jump_to_p2;
+ }
+ break;
+}
+
+/* Opcode: IfNullRow P1 P2 P3 * *
+** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
+**
+** Check the cursor P1 to see if it is currently pointing at a NULL row.
+** If it is, then set register P3 to NULL and jump immediately to P2.
+** If P1 is not on a NULL row, then fall through without making any
+** changes.
+*/
+case OP_IfNullRow: { /* jump */
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ assert( p->apCsr[pOp->p1]!=0 );
+ if( p->apCsr[pOp->p1]->nullRow ){
+ sqlite3VdbeMemSetNull(aMem + pOp->p3);
+ goto jump_to_p2;
+ }
+ break;
+}
+
+#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
+/* Opcode: Offset P1 P2 P3 * *
+** Synopsis: r[P3] = sqlite_offset(P1)
+**
+** Store in register r[P3] the byte offset into the database file that is the
+** start of the payload for the record at which that cursor P1 is currently
+** pointing.
+**
+** P2 is the column number for the argument to the sqlite_offset() function.
+** This opcode does not use P2 itself, but the P2 value is used by the
+** code generator. The P1, P2, and P3 operands to this opcode are the
+** same as for OP_Column.
+**
+** This opcode is only available if SQLite is compiled with the
+** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
+*/
+case OP_Offset: { /* out3 */
+ VdbeCursor *pC; /* The VDBE cursor */
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ pOut = &p->aMem[pOp->p3];
+ if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
+ sqlite3VdbeMemSetNull(pOut);
+ }else{
+ sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
+ }
+ break;
+}
+#endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
+
+/* Opcode: Column P1 P2 P3 P4 P5
+** Synopsis: r[P3]=PX
+**
+** Interpret the data that cursor P1 points to as a structure built using
+** the MakeRecord instruction. (See the MakeRecord opcode for additional
+** information about the format of the data.) Extract the P2-th column
+** from this record. If there are less that (P2+1)
+** values in the record, extract a NULL.
+**
+** The value extracted is stored in register P3.
+**
+** If the record contains fewer than P2 fields, then extract a NULL. Or,
+** if the P4 argument is a P4_MEM use the value of the P4 argument as
+** the result.
+**
+** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
+** the result is guaranteed to only be used as the argument of a length()
+** or typeof() function, respectively. The loading of large blobs can be
+** skipped for length() and all content loading can be skipped for typeof().
+*/
+case OP_Column: {
+ u32 p2; /* column number to retrieve */
+ VdbeCursor *pC; /* The VDBE cursor */
+ BtCursor *pCrsr; /* The BTree cursor */
+ u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
+ int len; /* The length of the serialized data for the column */
+ int i; /* Loop counter */
+ Mem *pDest; /* Where to write the extracted value */
+ Mem sMem; /* For storing the record being decoded */
+ const u8 *zData; /* Part of the record being decoded */
+ const u8 *zHdr; /* Next unparsed byte of the header */
+ const u8 *zEndHdr; /* Pointer to first byte after the header */
+ u64 offset64; /* 64-bit offset */
+ u32 t; /* A type code from the record header */
+ Mem *pReg; /* PseudoTable input register */
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ p2 = (u32)pOp->p2;
+
+ /* If the cursor cache is stale (meaning it is not currently point at
+ ** the correct row) then bring it up-to-date by doing the necessary
+ ** B-Tree seek. */
+ rc = sqlite3VdbeCursorMoveto(&pC, &p2);
+ if( rc ) goto abort_due_to_error;
+
+ assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
+ pDest = &aMem[pOp->p3];
+ memAboutToChange(p, pDest);
+ assert( pC!=0 );
+ assert( p2<(u32)pC->nField );
+ aOffset = pC->aOffset;
+ assert( pC->eCurType!=CURTYPE_VTAB );
+ assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
+ assert( pC->eCurType!=CURTYPE_SORTER );
+
+ if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
+ if( pC->nullRow ){
+ if( pC->eCurType==CURTYPE_PSEUDO ){
+ /* For the special case of as pseudo-cursor, the seekResult field
+ ** identifies the register that holds the record */
+ assert( pC->seekResult>0 );
+ pReg = &aMem[pC->seekResult];
+ assert( pReg->flags & MEM_Blob );
+ assert( memIsValid(pReg) );
+ pC->payloadSize = pC->szRow = pReg->n;
+ pC->aRow = (u8*)pReg->z;
+ }else{
+ sqlite3VdbeMemSetNull(pDest);
+ goto op_column_out;
+ }
+ }else{
+ pCrsr = pC->uc.pCursor;
+ assert( pC->eCurType==CURTYPE_BTREE );
+ assert( pCrsr );
+ assert( sqlite3BtreeCursorIsValid(pCrsr) );
+ pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
+ pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
+ assert( pC->szRow<=pC->payloadSize );
+ assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
+ if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
+ goto too_big;
+ }
+ }
+ pC->cacheStatus = p->cacheCtr;
+ pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
+ pC->nHdrParsed = 0;
+
+
+ if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
+ /* pC->aRow does not have to hold the entire row, but it does at least
+ ** need to cover the header of the record. If pC->aRow does not contain
+ ** the complete header, then set it to zero, forcing the header to be
+ ** dynamically allocated. */
+ pC->aRow = 0;
+ pC->szRow = 0;
+
+ /* Make sure a corrupt database has not given us an oversize header.
+ ** Do this now to avoid an oversize memory allocation.
+ **
+ ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
+ ** types use so much data space that there can only be 4096 and 32 of
+ ** them, respectively. So the maximum header length results from a
+ ** 3-byte type for each of the maximum of 32768 columns plus three
+ ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
+ */
+ if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
+ goto op_column_corrupt;
+ }
+ }else{
+ /* This is an optimization. By skipping over the first few tests
+ ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
+ ** measurable performance gain.
+ **
+ ** This branch is taken even if aOffset[0]==0. Such a record is never
+ ** generated by SQLite, and could be considered corruption, but we
+ ** accept it for historical reasons. When aOffset[0]==0, the code this
+ ** branch jumps to reads past the end of the record, but never more
+ ** than a few bytes. Even if the record occurs at the end of the page
+ ** content area, the "page header" comes after the page content and so
+ ** this overread is harmless. Similar overreads can occur for a corrupt
+ ** database file.
+ */
+ zData = pC->aRow;
+ assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
+ testcase( aOffset[0]==0 );
+ goto op_column_read_header;
+ }
+ }
+
+ /* Make sure at least the first p2+1 entries of the header have been
+ ** parsed and valid information is in aOffset[] and pC->aType[].
+ */
+ if( pC->nHdrParsed<=p2 ){
+ /* If there is more header available for parsing in the record, try
+ ** to extract additional fields up through the p2+1-th field
+ */
+ if( pC->iHdrOffset<aOffset[0] ){
+ /* Make sure zData points to enough of the record to cover the header. */
+ if( pC->aRow==0 ){
+ memset(&sMem, 0, sizeof(sMem));
+ rc = sqlite3VdbeMemFromBtreeZeroOffset(pC->uc.pCursor,aOffset[0],&sMem);
+ if( rc!=SQLITE_OK ) goto abort_due_to_error;
+ zData = (u8*)sMem.z;
+ }else{
+ zData = pC->aRow;
+ }
+
+ /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
+ op_column_read_header:
+ i = pC->nHdrParsed;
+ offset64 = aOffset[i];
+ zHdr = zData + pC->iHdrOffset;
+ zEndHdr = zData + aOffset[0];
+ testcase( zHdr>=zEndHdr );
+ do{
+ if( (pC->aType[i] = t = zHdr[0])<0x80 ){
+ zHdr++;
+ offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
+ }else{
+ zHdr += sqlite3GetVarint32(zHdr, &t);
+ pC->aType[i] = t;
+ offset64 += sqlite3VdbeSerialTypeLen(t);
+ }
+ aOffset[++i] = (u32)(offset64 & 0xffffffff);
+ }while( (u32)i<=p2 && zHdr<zEndHdr );
+
+ /* The record is corrupt if any of the following are true:
+ ** (1) the bytes of the header extend past the declared header size
+ ** (2) the entire header was used but not all data was used
+ ** (3) the end of the data extends beyond the end of the record.
+ */
+ if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
+ || (offset64 > pC->payloadSize)
+ ){
+ if( aOffset[0]==0 ){
+ i = 0;
+ zHdr = zEndHdr;
+ }else{
+ if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
+ goto op_column_corrupt;
+ }
+ }
+
+ pC->nHdrParsed = i;
+ pC->iHdrOffset = (u32)(zHdr - zData);
+ if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
+ }else{
+ t = 0;
+ }
+
+ /* If after trying to extract new entries from the header, nHdrParsed is
+ ** still not up to p2, that means that the record has fewer than p2
+ ** columns. So the result will be either the default value or a NULL.
+ */
+ if( pC->nHdrParsed<=p2 ){
+ if( pOp->p4type==P4_MEM ){
+ sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
+ }else{
+ sqlite3VdbeMemSetNull(pDest);
+ }
+ goto op_column_out;
+ }
+ }else{
+ t = pC->aType[p2];
+ }
+
+ /* Extract the content for the p2+1-th column. Control can only
+ ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
+ ** all valid.
+ */
+ assert( p2<pC->nHdrParsed );
+ assert( rc==SQLITE_OK );
+ assert( sqlite3VdbeCheckMemInvariants(pDest) );
+ if( VdbeMemDynamic(pDest) ){
+ sqlite3VdbeMemSetNull(pDest);
+ }
+ assert( t==pC->aType[p2] );
+ if( pC->szRow>=aOffset[p2+1] ){
+ /* This is the common case where the desired content fits on the original
+ ** page - where the content is not on an overflow page */
+ zData = pC->aRow + aOffset[p2];
+ if( t<12 ){
+ sqlite3VdbeSerialGet(zData, t, pDest);
+ }else{
+ /* If the column value is a string, we need a persistent value, not
+ ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
+ ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
+ */
+ static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
+ pDest->n = len = (t-12)/2;
+ pDest->enc = encoding;
+ if( pDest->szMalloc < len+2 ){
+ pDest->flags = MEM_Null;
+ if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
+ }else{
+ pDest->z = pDest->zMalloc;
+ }
+ memcpy(pDest->z, zData, len);
+ pDest->z[len] = 0;
+ pDest->z[len+1] = 0;
+ pDest->flags = aFlag[t&1];
+ }
+ }else{
+ pDest->enc = encoding;
+ /* This branch happens only when content is on overflow pages */
+ if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
+ && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
+ || (len = sqlite3VdbeSerialTypeLen(t))==0
+ ){
+ /* Content is irrelevant for
+ ** 1. the typeof() function,
+ ** 2. the length(X) function if X is a blob, and
+ ** 3. if the content length is zero.
+ ** So we might as well use bogus content rather than reading
+ ** content from disk.
+ **
+ ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
+ ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
+ ** read more. Use the global constant sqlite3CtypeMap[] as the array,
+ ** as that array is 256 bytes long (plenty for VdbeMemPrettyPrint())
+ ** and it begins with a bunch of zeros.
+ */
+ sqlite3VdbeSerialGet((u8*)sqlite3CtypeMap, t, pDest);
+ }else{
+ rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
+ if( rc!=SQLITE_OK ) goto abort_due_to_error;
+ sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
+ pDest->flags &= ~MEM_Ephem;
+ }
+ }
+
+op_column_out:
+ UPDATE_MAX_BLOBSIZE(pDest);
+ REGISTER_TRACE(pOp->p3, pDest);
+ break;
+
+op_column_corrupt:
+ if( aOp[0].p3>0 ){
+ pOp = &aOp[aOp[0].p3-1];
+ break;
+ }else{
+ rc = SQLITE_CORRUPT_BKPT;
+ goto abort_due_to_error;
+ }
+}
+
+/* Opcode: Affinity P1 P2 * P4 *
+** Synopsis: affinity(r[P1@P2])
+**
+** Apply affinities to a range of P2 registers starting with P1.
+**
+** P4 is a string that is P2 characters long. The N-th character of the
+** string indicates the column affinity that should be used for the N-th
+** memory cell in the range.
+*/
+case OP_Affinity: {
+ const char *zAffinity; /* The affinity to be applied */
+
+ zAffinity = pOp->p4.z;
+ assert( zAffinity!=0 );
+ assert( pOp->p2>0 );
+ assert( zAffinity[pOp->p2]==0 );
+ pIn1 = &aMem[pOp->p1];
+ while( 1 /*exit-by-break*/ ){
+ assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
+ assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) );
+ applyAffinity(pIn1, zAffinity[0], encoding);
+ if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){
+ /* When applying REAL affinity, if the result is still an MEM_Int
+ ** that will fit in 6 bytes, then change the type to MEM_IntReal
+ ** so that we keep the high-resolution integer value but know that
+ ** the type really wants to be REAL. */
+ testcase( pIn1->u.i==140737488355328LL );
+ testcase( pIn1->u.i==140737488355327LL );
+ testcase( pIn1->u.i==-140737488355328LL );
+ testcase( pIn1->u.i==-140737488355329LL );
+ if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){
+ pIn1->flags |= MEM_IntReal;
+ pIn1->flags &= ~MEM_Int;
+ }else{
+ pIn1->u.r = (double)pIn1->u.i;
+ pIn1->flags |= MEM_Real;
+ pIn1->flags &= ~MEM_Int;
+ }
+ }
+ REGISTER_TRACE((int)(pIn1-aMem), pIn1);
+ zAffinity++;
+ if( zAffinity[0]==0 ) break;
+ pIn1++;
+ }
+ break;
+}
+
+/* Opcode: MakeRecord P1 P2 P3 P4 *
+** Synopsis: r[P3]=mkrec(r[P1@P2])
+**
+** Convert P2 registers beginning with P1 into the [record format]
+** use as a data record in a database table or as a key
+** in an index. The OP_Column opcode can decode the record later.
+**
+** P4 may be a string that is P2 characters long. The N-th character of the
+** string indicates the column affinity that should be used for the N-th
+** field of the index key.
+**
+** The mapping from character to affinity is given by the SQLITE_AFF_
+** macros defined in sqliteInt.h.
+**
+** If P4 is NULL then all index fields have the affinity BLOB.
+**
+** The meaning of P5 depends on whether or not the SQLITE_ENABLE_NULL_TRIM
+** compile-time option is enabled:
+**
+** * If SQLITE_ENABLE_NULL_TRIM is enabled, then the P5 is the index
+** of the right-most table that can be null-trimmed.
+**
+** * If SQLITE_ENABLE_NULL_TRIM is omitted, then P5 has the value
+** OPFLAG_NOCHNG_MAGIC if the OP_MakeRecord opcode is allowed to
+** accept no-change records with serial_type 10. This value is
+** only used inside an assert() and does not affect the end result.
+*/
+case OP_MakeRecord: {
+ Mem *pRec; /* The new record */
+ u64 nData; /* Number of bytes of data space */
+ int nHdr; /* Number of bytes of header space */
+ i64 nByte; /* Data space required for this record */
+ i64 nZero; /* Number of zero bytes at the end of the record */
+ int nVarint; /* Number of bytes in a varint */
+ u32 serial_type; /* Type field */
+ Mem *pData0; /* First field to be combined into the record */
+ Mem *pLast; /* Last field of the record */
+ int nField; /* Number of fields in the record */
+ char *zAffinity; /* The affinity string for the record */
+ int file_format; /* File format to use for encoding */
+ u32 len; /* Length of a field */
+ u8 *zHdr; /* Where to write next byte of the header */
+ u8 *zPayload; /* Where to write next byte of the payload */
+
+ /* Assuming the record contains N fields, the record format looks
+ ** like this:
+ **
+ ** ------------------------------------------------------------------------
+ ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
+ ** ------------------------------------------------------------------------
+ **
+ ** Data(0) is taken from register P1. Data(1) comes from register P1+1
+ ** and so forth.
+ **
+ ** Each type field is a varint representing the serial type of the
+ ** corresponding data element (see sqlite3VdbeSerialType()). The
+ ** hdr-size field is also a varint which is the offset from the beginning
+ ** of the record to data0.
+ */
+ nData = 0; /* Number of bytes of data space */
+ nHdr = 0; /* Number of bytes of header space */
+ nZero = 0; /* Number of zero bytes at the end of the record */
+ nField = pOp->p1;
+ zAffinity = pOp->p4.z;
+ assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
+ pData0 = &aMem[nField];
+ nField = pOp->p2;
+ pLast = &pData0[nField-1];
+ file_format = p->minWriteFileFormat;
+
+ /* Identify the output register */
+ assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
+ pOut = &aMem[pOp->p3];
+ memAboutToChange(p, pOut);
+
+ /* Apply the requested affinity to all inputs
+ */
+ assert( pData0<=pLast );
+ if( zAffinity ){
+ pRec = pData0;
+ do{
+ applyAffinity(pRec, zAffinity[0], encoding);
+ if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
+ pRec->flags |= MEM_IntReal;
+ pRec->flags &= ~(MEM_Int);
+ }
+ REGISTER_TRACE((int)(pRec-aMem), pRec);
+ zAffinity++;
+ pRec++;
+ assert( zAffinity[0]==0 || pRec<=pLast );
+ }while( zAffinity[0] );
+ }
+
+#ifdef SQLITE_ENABLE_NULL_TRIM
+ /* NULLs can be safely trimmed from the end of the record, as long as
+ ** as the schema format is 2 or more and none of the omitted columns
+ ** have a non-NULL default value. Also, the record must be left with
+ ** at least one field. If P5>0 then it will be one more than the
+ ** index of the right-most column with a non-NULL default value */
+ if( pOp->p5 ){
+ while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
+ pLast--;
+ nField--;
+ }
+ }
+#endif
+
+ /* Loop through the elements that will make up the record to figure
+ ** out how much space is required for the new record. After this loop,
+ ** the Mem.uTemp field of each term should hold the serial-type that will
+ ** be used for that term in the generated record:
+ **
+ ** Mem.uTemp value type
+ ** --------------- ---------------
+ ** 0 NULL
+ ** 1 1-byte signed integer
+ ** 2 2-byte signed integer
+ ** 3 3-byte signed integer
+ ** 4 4-byte signed integer
+ ** 5 6-byte signed integer
+ ** 6 8-byte signed integer
+ ** 7 IEEE float
+ ** 8 Integer constant 0
+ ** 9 Integer constant 1
+ ** 10,11 reserved for expansion
+ ** N>=12 and even BLOB
+ ** N>=13 and odd text
+ **
+ ** The following additional values are computed:
+ ** nHdr Number of bytes needed for the record header
+ ** nData Number of bytes of data space needed for the record
+ ** nZero Zero bytes at the end of the record
+ */
+ pRec = pLast;
+ do{
+ assert( memIsValid(pRec) );
+ if( pRec->flags & MEM_Null ){
+ if( pRec->flags & MEM_Zero ){
+ /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
+ ** table methods that never invoke sqlite3_result_xxxxx() while
+ ** computing an unchanging column value in an UPDATE statement.
+ ** Give such values a special internal-use-only serial-type of 10
+ ** so that they can be passed through to xUpdate and have
+ ** a true sqlite3_value_nochange(). */
+#ifndef SQLITE_ENABLE_NULL_TRIM
+ assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
+#endif
+ pRec->uTemp = 10;
+ }else{
+ pRec->uTemp = 0;
+ }
+ nHdr++;
+ }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){
+ /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
+ i64 i = pRec->u.i;
+ u64 uu;
+ testcase( pRec->flags & MEM_Int );
+ testcase( pRec->flags & MEM_IntReal );
+ if( i<0 ){
+ uu = ~i;
+ }else{
+ uu = i;
+ }
+ nHdr++;
+ testcase( uu==127 ); testcase( uu==128 );
+ testcase( uu==32767 ); testcase( uu==32768 );
+ testcase( uu==8388607 ); testcase( uu==8388608 );
+ testcase( uu==2147483647 ); testcase( uu==2147483648 );
+ testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL );
+ if( uu<=127 ){
+ if( (i&1)==i && file_format>=4 ){
+ pRec->uTemp = 8+(u32)uu;
+ }else{
+ nData++;
+ pRec->uTemp = 1;
+ }
+ }else if( uu<=32767 ){
+ nData += 2;
+ pRec->uTemp = 2;
+ }else if( uu<=8388607 ){
+ nData += 3;
+ pRec->uTemp = 3;
+ }else if( uu<=2147483647 ){
+ nData += 4;
+ pRec->uTemp = 4;
+ }else if( uu<=140737488355327LL ){
+ nData += 6;
+ pRec->uTemp = 5;
+ }else{
+ nData += 8;
+ if( pRec->flags & MEM_IntReal ){
+ /* If the value is IntReal and is going to take up 8 bytes to store
+ ** as an integer, then we might as well make it an 8-byte floating
+ ** point value */
+ pRec->u.r = (double)pRec->u.i;
+ pRec->flags &= ~MEM_IntReal;
+ pRec->flags |= MEM_Real;
+ pRec->uTemp = 7;
+ }else{
+ pRec->uTemp = 6;
+ }
+ }
+ }else if( pRec->flags & MEM_Real ){
+ nHdr++;
+ nData += 8;
+ pRec->uTemp = 7;
+ }else{
+ assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
+ assert( pRec->n>=0 );
+ len = (u32)pRec->n;
+ serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
+ if( pRec->flags & MEM_Zero ){
+ serial_type += pRec->u.nZero*2;
+ if( nData ){
+ if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
+ len += pRec->u.nZero;
+ }else{
+ nZero += pRec->u.nZero;
+ }
+ }
+ nData += len;
+ nHdr += sqlite3VarintLen(serial_type);
+ pRec->uTemp = serial_type;
+ }
+ if( pRec==pData0 ) break;
+ pRec--;
+ }while(1);
+
+ /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
+ ** which determines the total number of bytes in the header. The varint
+ ** value is the size of the header in bytes including the size varint
+ ** itself. */
+ testcase( nHdr==126 );
+ testcase( nHdr==127 );
+ if( nHdr<=126 ){
+ /* The common case */
+ nHdr += 1;
+ }else{
+ /* Rare case of a really large header */
+ nVarint = sqlite3VarintLen(nHdr);
+ nHdr += nVarint;
+ if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
+ }
+ nByte = nHdr+nData;
+
+ /* Make sure the output register has a buffer large enough to store
+ ** the new record. The output register (pOp->p3) is not allowed to
+ ** be one of the input registers (because the following call to
+ ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
+ */
+ if( nByte+nZero<=pOut->szMalloc ){
+ /* The output register is already large enough to hold the record.
+ ** No error checks or buffer enlargement is required */
+ pOut->z = pOut->zMalloc;
+ }else{
+ /* Need to make sure that the output is not too big and then enlarge
+ ** the output register to hold the full result */
+ if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
+ goto too_big;
+ }
+ if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
+ goto no_mem;
+ }
+ }
+ pOut->n = (int)nByte;
+ pOut->flags = MEM_Blob;
+ if( nZero ){
+ pOut->u.nZero = nZero;
+ pOut->flags |= MEM_Zero;
+ }
+ UPDATE_MAX_BLOBSIZE(pOut);
+ zHdr = (u8 *)pOut->z;
+ zPayload = zHdr + nHdr;
+
+ /* Write the record */
+ zHdr += putVarint32(zHdr, nHdr);
+ assert( pData0<=pLast );
+ pRec = pData0;
+ do{
+ serial_type = pRec->uTemp;
+ /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
+ ** additional varints, one per column. */
+ zHdr += putVarint32(zHdr, serial_type); /* serial type */
+ /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
+ ** immediately follow the header. */
+ zPayload += sqlite3VdbeSerialPut(zPayload, pRec, serial_type); /* content */
+ }while( (++pRec)<=pLast );
+ assert( nHdr==(int)(zHdr - (u8*)pOut->z) );
+ assert( nByte==(int)(zPayload - (u8*)pOut->z) );
+
+ assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
+ REGISTER_TRACE(pOp->p3, pOut);
+ break;
+}
+
+/* Opcode: Count P1 P2 p3 * *
+** Synopsis: r[P2]=count()
+**
+** Store the number of entries (an integer value) in the table or index
+** opened by cursor P1 in register P2.
+**
+** If P3==0, then an exact count is obtained, which involves visiting
+** every btree page of the table. But if P3 is non-zero, an estimate
+** is returned based on the current cursor position.
+*/
+case OP_Count: { /* out2 */
+ i64 nEntry;
+ BtCursor *pCrsr;
+
+ assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
+ pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
+ assert( pCrsr );
+ if( pOp->p3 ){
+ nEntry = sqlite3BtreeRowCountEst(pCrsr);
+ }else{
+ nEntry = 0; /* Not needed. Only used to silence a warning. */
+ rc = sqlite3BtreeCount(db, pCrsr, &nEntry);
+ if( rc ) goto abort_due_to_error;
+ }
+ pOut = out2Prerelease(p, pOp);
+ pOut->u.i = nEntry;
+ goto check_for_interrupt;
+}
+
+/* Opcode: Savepoint P1 * * P4 *
+**
+** Open, release or rollback the savepoint named by parameter P4, depending
+** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN).
+** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE).
+** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK).
+*/
+case OP_Savepoint: {
+ int p1; /* Value of P1 operand */
+ char *zName; /* Name of savepoint */
+ int nName;
+ Savepoint *pNew;
+ Savepoint *pSavepoint;
+ Savepoint *pTmp;
+ int iSavepoint;
+ int ii;
+
+ p1 = pOp->p1;
+ zName = pOp->p4.z;
+
+ /* Assert that the p1 parameter is valid. Also that if there is no open
+ ** transaction, then there cannot be any savepoints.
+ */
+ assert( db->pSavepoint==0 || db->autoCommit==0 );
+ assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
+ assert( db->pSavepoint || db->isTransactionSavepoint==0 );
+ assert( checkSavepointCount(db) );
+ assert( p->bIsReader );
+
+ if( p1==SAVEPOINT_BEGIN ){
+ if( db->nVdbeWrite>0 ){
+ /* A new savepoint cannot be created if there are active write
+ ** statements (i.e. open read/write incremental blob handles).
+ */
+ sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
+ rc = SQLITE_BUSY;
+ }else{
+ nName = sqlite3Strlen30(zName);
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ /* This call is Ok even if this savepoint is actually a transaction
+ ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
+ ** If this is a transaction savepoint being opened, it is guaranteed
+ ** that the db->aVTrans[] array is empty. */
+ assert( db->autoCommit==0 || db->nVTrans==0 );
+ rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
+ db->nStatement+db->nSavepoint);
+ if( rc!=SQLITE_OK ) goto abort_due_to_error;
+#endif
+
+ /* Create a new savepoint structure. */
+ pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
+ if( pNew ){
+ pNew->zName = (char *)&pNew[1];
+ memcpy(pNew->zName, zName, nName+1);
+
+ /* If there is no open transaction, then mark this as a special
+ ** "transaction savepoint". */
+ if( db->autoCommit ){
+ db->autoCommit = 0;
+ db->isTransactionSavepoint = 1;
+ }else{
+ db->nSavepoint++;
+ }
+
+ /* Link the new savepoint into the database handle's list. */
+ pNew->pNext = db->pSavepoint;
+ db->pSavepoint = pNew;
+ pNew->nDeferredCons = db->nDeferredCons;
+ pNew->nDeferredImmCons = db->nDeferredImmCons;
+ }
+ }
+ }else{
+ assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK );
+ iSavepoint = 0;
+
+ /* Find the named savepoint. If there is no such savepoint, then an
+ ** an error is returned to the user. */
+ for(
+ pSavepoint = db->pSavepoint;
+ pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
+ pSavepoint = pSavepoint->pNext
+ ){
+ iSavepoint++;
+ }
+ if( !pSavepoint ){
+ sqlite3VdbeError(p, "no such savepoint: %s", zName);
+ rc = SQLITE_ERROR;
+ }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
+ /* It is not possible to release (commit) a savepoint if there are
+ ** active write statements.
+ */
+ sqlite3VdbeError(p, "cannot release savepoint - "
+ "SQL statements in progress");
+ rc = SQLITE_BUSY;
+ }else{
+
+ /* Determine whether or not this is a transaction savepoint. If so,
+ ** and this is a RELEASE command, then the current transaction
+ ** is committed.
+ */
+ int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
+ if( isTransaction && p1==SAVEPOINT_RELEASE ){
+ if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
+ goto vdbe_return;
+ }
+ db->autoCommit = 1;
+ if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
+ p->pc = (int)(pOp - aOp);
+ db->autoCommit = 0;
+ p->rc = rc = SQLITE_BUSY;
+ goto vdbe_return;
+ }
+ rc = p->rc;
+ if( rc ){
+ db->autoCommit = 0;
+ }else{
+ db->isTransactionSavepoint = 0;
+ }
+ }else{
+ int isSchemaChange;
+ iSavepoint = db->nSavepoint - iSavepoint - 1;
+ if( p1==SAVEPOINT_ROLLBACK ){
+ isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
+ for(ii=0; ii<db->nDb; ii++){
+ rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
+ SQLITE_ABORT_ROLLBACK,
+ isSchemaChange==0);
+ if( rc!=SQLITE_OK ) goto abort_due_to_error;
+ }
+ }else{
+ assert( p1==SAVEPOINT_RELEASE );
+ isSchemaChange = 0;
+ }
+ for(ii=0; ii<db->nDb; ii++){
+ rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
+ if( rc!=SQLITE_OK ){
+ goto abort_due_to_error;
+ }
+ }
+ if( isSchemaChange ){
+ sqlite3ExpirePreparedStatements(db, 0);
+ sqlite3ResetAllSchemasOfConnection(db);
+ db->mDbFlags |= DBFLAG_SchemaChange;
+ }
+ }
+ if( rc ) goto abort_due_to_error;
+
+ /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
+ ** savepoints nested inside of the savepoint being operated on. */
+ while( db->pSavepoint!=pSavepoint ){
+ pTmp = db->pSavepoint;
+ db->pSavepoint = pTmp->pNext;
+ sqlite3DbFree(db, pTmp);
+ db->nSavepoint--;
+ }
+
+ /* If it is a RELEASE, then destroy the savepoint being operated on
+ ** too. If it is a ROLLBACK TO, then set the number of deferred
+ ** constraint violations present in the database to the value stored
+ ** when the savepoint was created. */
+ if( p1==SAVEPOINT_RELEASE ){
+ assert( pSavepoint==db->pSavepoint );
+ db->pSavepoint = pSavepoint->pNext;
+ sqlite3DbFree(db, pSavepoint);
+ if( !isTransaction ){
+ db->nSavepoint--;
+ }
+ }else{
+ assert( p1==SAVEPOINT_ROLLBACK );
+ db->nDeferredCons = pSavepoint->nDeferredCons;
+ db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
+ }
+
+ if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
+ rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
+ if( rc!=SQLITE_OK ) goto abort_due_to_error;
+ }
+ }
+ }
+ if( rc ) goto abort_due_to_error;
+
+ break;
+}
+
+/* Opcode: AutoCommit P1 P2 * * *
+**
+** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
+** back any currently active btree transactions. If there are any active
+** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
+** there are active writing VMs or active VMs that use shared cache.
+**
+** This instruction causes the VM to halt.
+*/
+case OP_AutoCommit: {
+ int desiredAutoCommit;
+ int iRollback;
+
+ desiredAutoCommit = pOp->p1;
+ iRollback = pOp->p2;
+ assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
+ assert( desiredAutoCommit==1 || iRollback==0 );
+ assert( db->nVdbeActive>0 ); /* At least this one VM is active */
+ assert( p->bIsReader );
+
+ if( desiredAutoCommit!=db->autoCommit ){
+ if( iRollback ){
+ assert( desiredAutoCommit==1 );
+ sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
+ db->autoCommit = 1;
+ }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
+ /* If this instruction implements a COMMIT and other VMs are writing
+ ** return an error indicating that the other VMs must complete first.
+ */
+ sqlite3VdbeError(p, "cannot commit transaction - "
+ "SQL statements in progress");
+ rc = SQLITE_BUSY;
+ goto abort_due_to_error;
+ }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
+ goto vdbe_return;
+ }else{
+ db->autoCommit = (u8)desiredAutoCommit;
+ }
+ if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
+ p->pc = (int)(pOp - aOp);
+ db->autoCommit = (u8)(1-desiredAutoCommit);
+ p->rc = rc = SQLITE_BUSY;
+ goto vdbe_return;
+ }
+ sqlite3CloseSavepoints(db);
+ if( p->rc==SQLITE_OK ){
+ rc = SQLITE_DONE;
+ }else{
+ rc = SQLITE_ERROR;
+ }
+ goto vdbe_return;
+ }else{
+ sqlite3VdbeError(p,
+ (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
+ (iRollback)?"cannot rollback - no transaction is active":
+ "cannot commit - no transaction is active"));
+
+ rc = SQLITE_ERROR;
+ goto abort_due_to_error;
+ }
+ /*NOTREACHED*/ assert(0);
+}
+
+/* Opcode: Transaction P1 P2 P3 P4 P5
+**
+** Begin a transaction on database P1 if a transaction is not already
+** active.
+** If P2 is non-zero, then a write-transaction is started, or if a
+** read-transaction is already active, it is upgraded to a write-transaction.
+** If P2 is zero, then a read-transaction is started.
+**
+** P1 is the index of the database file on which the transaction is
+** started. Index 0 is the main database file and index 1 is the
+** file used for temporary tables. Indices of 2 or more are used for
+** attached databases.
+**
+** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
+** true (this flag is set if the Vdbe may modify more than one row and may
+** throw an ABORT exception), a statement transaction may also be opened.
+** More specifically, a statement transaction is opened iff the database
+** connection is currently not in autocommit mode, or if there are other
+** active statements. A statement transaction allows the changes made by this
+** VDBE to be rolled back after an error without having to roll back the
+** entire transaction. If no error is encountered, the statement transaction
+** will automatically commit when the VDBE halts.
+**
+** If P5!=0 then this opcode also checks the schema cookie against P3
+** and the schema generation counter against P4.
+** The cookie changes its value whenever the database schema changes.
+** This operation is used to detect when that the cookie has changed
+** and that the current process needs to reread the schema. If the schema
+** cookie in P3 differs from the schema cookie in the database header or
+** if the schema generation counter in P4 differs from the current
+** generation counter, then an SQLITE_SCHEMA error is raised and execution
+** halts. The sqlite3_step() wrapper function might then reprepare the
+** statement and rerun it from the beginning.
+*/
+case OP_Transaction: {
+ Btree *pBt;
+ int iMeta = 0;
+
+ assert( p->bIsReader );
+ assert( p->readOnly==0 || pOp->p2==0 );
+ assert( pOp->p1>=0 && pOp->p1<db->nDb );
+ assert( DbMaskTest(p->btreeMask, pOp->p1) );
+ if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
+ rc = SQLITE_READONLY;
+ goto abort_due_to_error;
+ }
+ pBt = db->aDb[pOp->p1].pBt;
+
+ if( pBt ){
+ rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
+ testcase( rc==SQLITE_BUSY_SNAPSHOT );
+ testcase( rc==SQLITE_BUSY_RECOVERY );
+ if( rc!=SQLITE_OK ){
+ if( (rc&0xff)==SQLITE_BUSY ){
+ p->pc = (int)(pOp - aOp);
+ p->rc = rc;
+ goto vdbe_return;
+ }
+ goto abort_due_to_error;
+ }
+
+ if( p->usesStmtJournal
+ && pOp->p2
+ && (db->autoCommit==0 || db->nVdbeRead>1)
+ ){
+ assert( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE );
+ if( p->iStatement==0 ){
+ assert( db->nStatement>=0 && db->nSavepoint>=0 );
+ db->nStatement++;
+ p->iStatement = db->nSavepoint + db->nStatement;
+ }
+
+ rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
+ }
+
+ /* Store the current value of the database handles deferred constraint
+ ** counter. If the statement transaction needs to be rolled back,
+ ** the value of this counter needs to be restored too. */
+ p->nStmtDefCons = db->nDeferredCons;
+ p->nStmtDefImmCons = db->nDeferredImmCons;
+ }
+ }
+ assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
+ if( pOp->p5
+ && (iMeta!=pOp->p3
+ || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i)
+ ){
+ /*
+ ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
+ ** version is checked to ensure that the schema has not changed since the
+ ** SQL statement was prepared.
+ */
+ sqlite3DbFree(db, p->zErrMsg);
+ p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
+ /* If the schema-cookie from the database file matches the cookie
+ ** stored with the in-memory representation of the schema, do
+ ** not reload the schema from the database file.
+ **
+ ** If virtual-tables are in use, this is not just an optimization.
+ ** Often, v-tables store their data in other SQLite tables, which
+ ** are queried from within xNext() and other v-table methods using
+ ** prepared queries. If such a query is out-of-date, we do not want to
+ ** discard the database schema, as the user code implementing the
+ ** v-table would have to be ready for the sqlite3_vtab structure itself
+ ** to be invalidated whenever sqlite3_step() is called from within
+ ** a v-table method.
+ */
+ if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
+ sqlite3ResetOneSchema(db, pOp->p1);
+ }
+ p->expired = 1;
+ rc = SQLITE_SCHEMA;
+ }
+ if( rc ) goto abort_due_to_error;
+ break;
+}
+
+/* Opcode: ReadCookie P1 P2 P3 * *
+**
+** Read cookie number P3 from database P1 and write it into register P2.
+** P3==1 is the schema version. P3==2 is the database format.
+** P3==3 is the recommended pager cache size, and so forth. P1==0 is
+** the main database file and P1==1 is the database file used to store
+** temporary tables.
+**
+** There must be a read-lock on the database (either a transaction
+** must be started or there must be an open cursor) before
+** executing this instruction.
+*/
+case OP_ReadCookie: { /* out2 */
+ int iMeta;
+ int iDb;
+ int iCookie;
+
+ assert( p->bIsReader );
+ iDb = pOp->p1;
+ iCookie = pOp->p3;
+ assert( pOp->p3<SQLITE_N_BTREE_META );
+ assert( iDb>=0 && iDb<db->nDb );
+ assert( db->aDb[iDb].pBt!=0 );
+ assert( DbMaskTest(p->btreeMask, iDb) );
+
+ sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
+ pOut = out2Prerelease(p, pOp);
+ pOut->u.i = iMeta;
+ break;
+}
+
+/* Opcode: SetCookie P1 P2 P3 * P5
+**
+** Write the integer value P3 into cookie number P2 of database P1.
+** P2==1 is the schema version. P2==2 is the database format.
+** P2==3 is the recommended pager cache
+** size, and so forth. P1==0 is the main database file and P1==1 is the
+** database file used to store temporary tables.
+**
+** A transaction must be started before executing this opcode.
+**
+** If P2 is the SCHEMA_VERSION cookie (cookie number 1) then the internal
+** schema version is set to P3-P5. The "PRAGMA schema_version=N" statement
+** has P5 set to 1, so that the internal schema version will be different
+** from the database schema version, resulting in a schema reset.
+*/
+case OP_SetCookie: {
+ Db *pDb;
+
+ sqlite3VdbeIncrWriteCounter(p, 0);
+ assert( pOp->p2<SQLITE_N_BTREE_META );
+ assert( pOp->p1>=0 && pOp->p1<db->nDb );
+ assert( DbMaskTest(p->btreeMask, pOp->p1) );
+ assert( p->readOnly==0 );
+ pDb = &db->aDb[pOp->p1];
+ assert( pDb->pBt!=0 );
+ assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
+ /* See note about index shifting on OP_ReadCookie */
+ rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
+ if( pOp->p2==BTREE_SCHEMA_VERSION ){
+ /* When the schema cookie changes, record the new cookie internally */
+ pDb->pSchema->schema_cookie = pOp->p3 - pOp->p5;
+ db->mDbFlags |= DBFLAG_SchemaChange;
+ }else if( pOp->p2==BTREE_FILE_FORMAT ){
+ /* Record changes in the file format */
+ pDb->pSchema->file_format = pOp->p3;
+ }
+ if( pOp->p1==1 ){
+ /* Invalidate all prepared statements whenever the TEMP database
+ ** schema is changed. Ticket #1644 */
+ sqlite3ExpirePreparedStatements(db, 0);
+ p->expired = 0;
+ }
+ if( rc ) goto abort_due_to_error;
+ break;
+}
+
+/* Opcode: OpenRead P1 P2 P3 P4 P5
+** Synopsis: root=P2 iDb=P3
+**
+** Open a read-only cursor for the database table whose root page is
+** P2 in a database file. The database file is determined by P3.
+** P3==0 means the main database, P3==1 means the database used for
+** temporary tables, and P3>1 means used the corresponding attached
+** database. Give the new cursor an identifier of P1. The P1
+** values need not be contiguous but all P1 values should be small integers.
+** It is an error for P1 to be negative.
+**
+** Allowed P5 bits:
+** <ul>
+** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
+** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
+** of OP_SeekLE/OP_IdxLT)
+** </ul>
+**
+** The P4 value may be either an integer (P4_INT32) or a pointer to
+** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
+** object, then table being opened must be an [index b-tree] where the
+** KeyInfo object defines the content and collating
+** sequence of that index b-tree. Otherwise, if P4 is an integer
+** value, then the table being opened must be a [table b-tree] with a
+** number of columns no less than the value of P4.
+**
+** See also: OpenWrite, ReopenIdx
+*/
+/* Opcode: ReopenIdx P1 P2 P3 P4 P5
+** Synopsis: root=P2 iDb=P3
+**
+** The ReopenIdx opcode works like OP_OpenRead except that it first
+** checks to see if the cursor on P1 is already open on the same
+** b-tree and if it is this opcode becomes a no-op. In other words,
+** if the cursor is already open, do not reopen it.
+**
+** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
+** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must
+** be the same as every other ReopenIdx or OpenRead for the same cursor
+** number.
+**
+** Allowed P5 bits:
+** <ul>
+** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
+** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
+** of OP_SeekLE/OP_IdxLT)
+** </ul>
+**
+** See also: OP_OpenRead, OP_OpenWrite
+*/
+/* Opcode: OpenWrite P1 P2 P3 P4 P5
+** Synopsis: root=P2 iDb=P3
+**
+** Open a read/write cursor named P1 on the table or index whose root
+** page is P2 (or whose root page is held in register P2 if the
+** OPFLAG_P2ISREG bit is set in P5 - see below).
+**
+** The P4 value may be either an integer (P4_INT32) or a pointer to
+** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
+** object, then table being opened must be an [index b-tree] where the
+** KeyInfo object defines the content and collating
+** sequence of that index b-tree. Otherwise, if P4 is an integer
+** value, then the table being opened must be a [table b-tree] with a
+** number of columns no less than the value of P4.
+**
+** Allowed P5 bits:
+** <ul>
+** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
+** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
+** of OP_SeekLE/OP_IdxLT)
+** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
+** and subsequently delete entries in an index btree. This is a
+** hint to the storage engine that the storage engine is allowed to
+** ignore. The hint is not used by the official SQLite b*tree storage
+** engine, but is used by COMDB2.
+** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
+** as the root page, not the value of P2 itself.
+** </ul>
+**
+** This instruction works like OpenRead except that it opens the cursor
+** in read/write mode.
+**
+** See also: OP_OpenRead, OP_ReopenIdx
+*/
+case OP_ReopenIdx: {
+ int nField;
+ KeyInfo *pKeyInfo;
+ u32 p2;
+ int iDb;
+ int wrFlag;
+ Btree *pX;
+ VdbeCursor *pCur;
+ Db *pDb;
+
+ assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
+ assert( pOp->p4type==P4_KEYINFO );
+ pCur = p->apCsr[pOp->p1];
+ if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
+ assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
+ goto open_cursor_set_hints;
+ }
+ /* If the cursor is not currently open or is open on a different
+ ** index, then fall through into OP_OpenRead to force a reopen */
+case OP_OpenRead:
+case OP_OpenWrite:
+
+ assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
+ assert( p->bIsReader );
+ assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
+ || p->readOnly==0 );
+
+ if( p->expired==1 ){
+ rc = SQLITE_ABORT_ROLLBACK;
+ goto abort_due_to_error;
+ }
+
+ nField = 0;
+ pKeyInfo = 0;
+ p2 = (u32)pOp->p2;
+ iDb = pOp->p3;
+ assert( iDb>=0 && iDb<db->nDb );
+ assert( DbMaskTest(p->btreeMask, iDb) );
+ pDb = &db->aDb[iDb];
+ pX = pDb->pBt;
+ assert( pX!=0 );
+ if( pOp->opcode==OP_OpenWrite ){
+ assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
+ wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ if( pDb->pSchema->file_format < p->minWriteFileFormat ){
+ p->minWriteFileFormat = pDb->pSchema->file_format;
+ }
+ }else{
+ wrFlag = 0;
+ }
+ if( pOp->p5 & OPFLAG_P2ISREG ){
+ assert( p2>0 );
+ assert( p2<=(u32)(p->nMem+1 - p->nCursor) );
+ assert( pOp->opcode==OP_OpenWrite );
+ pIn2 = &aMem[p2];
+ assert( memIsValid(pIn2) );
+ assert( (pIn2->flags & MEM_Int)!=0 );
+ sqlite3VdbeMemIntegerify(pIn2);
+ p2 = (int)pIn2->u.i;
+ /* The p2 value always comes from a prior OP_CreateBtree opcode and
+ ** that opcode will always set the p2 value to 2 or more or else fail.
+ ** If there were a failure, the prepared statement would have halted
+ ** before reaching this instruction. */
+ assert( p2>=2 );
+ }
+ if( pOp->p4type==P4_KEYINFO ){
+ pKeyInfo = pOp->p4.pKeyInfo;
+ assert( pKeyInfo->enc==ENC(db) );
+ assert( pKeyInfo->db==db );
+ nField = pKeyInfo->nAllField;
+ }else if( pOp->p4type==P4_INT32 ){
+ nField = pOp->p4.i;
+ }
+ assert( pOp->p1>=0 );
+ assert( nField>=0 );
+ testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
+ pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
+ if( pCur==0 ) goto no_mem;
+ pCur->nullRow = 1;
+ pCur->isOrdered = 1;
+ pCur->pgnoRoot = p2;
+#ifdef SQLITE_DEBUG
+ pCur->wrFlag = wrFlag;
+#endif
+ rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
+ pCur->pKeyInfo = pKeyInfo;
+ /* Set the VdbeCursor.isTable variable. Previous versions of
+ ** SQLite used to check if the root-page flags were sane at this point
+ ** and report database corruption if they were not, but this check has
+ ** since moved into the btree layer. */
+ pCur->isTable = pOp->p4type!=P4_KEYINFO;
+
+open_cursor_set_hints:
+ assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
+ assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
+ testcase( pOp->p5 & OPFLAG_BULKCSR );
+ testcase( pOp->p2 & OPFLAG_SEEKEQ );
+ sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
+ (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
+ if( rc ) goto abort_due_to_error;
+ break;
+}
+
+/* Opcode: OpenDup P1 P2 * * *
+**
+** Open a new cursor P1 that points to the same ephemeral table as
+** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
+** opcode. Only ephemeral cursors may be duplicated.
+**
+** Duplicate ephemeral cursors are used for self-joins of materialized views.
+*/
+case OP_OpenDup: {
+ VdbeCursor *pOrig; /* The original cursor to be duplicated */
+ VdbeCursor *pCx; /* The new cursor */
+
+ pOrig = p->apCsr[pOp->p2];
+ assert( pOrig );
+ assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
+
+ pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
+ if( pCx==0 ) goto no_mem;
+ pCx->nullRow = 1;
+ pCx->isEphemeral = 1;
+ pCx->pKeyInfo = pOrig->pKeyInfo;
+ pCx->isTable = pOrig->isTable;
+ pCx->pgnoRoot = pOrig->pgnoRoot;
+ pCx->isOrdered = pOrig->isOrdered;
+ rc = sqlite3BtreeCursor(pOrig->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
+ pCx->pKeyInfo, pCx->uc.pCursor);
+ /* The sqlite3BtreeCursor() routine can only fail for the first cursor
+ ** opened for a database. Since there is already an open cursor when this
+ ** opcode is run, the sqlite3BtreeCursor() cannot fail */
+ assert( rc==SQLITE_OK );
+ break;
+}
+
+
+/* Opcode: OpenEphemeral P1 P2 * P4 P5
+** Synopsis: nColumn=P2
+**
+** Open a new cursor P1 to a transient table.
+** The cursor is always opened read/write even if
+** the main database is read-only. The ephemeral
+** table is deleted automatically when the cursor is closed.
+**
+** If the cursor P1 is already opened on an ephemeral table, the table
+** is cleared (all content is erased).
+**
+** P2 is the number of columns in the ephemeral table.
+** The cursor points to a BTree table if P4==0 and to a BTree index
+** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
+** that defines the format of keys in the index.
+**
+** The P5 parameter can be a mask of the BTREE_* flags defined
+** in btree.h. These flags control aspects of the operation of
+** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
+** added automatically.
+*/
+/* Opcode: OpenAutoindex P1 P2 * P4 *
+** Synopsis: nColumn=P2
+**
+** This opcode works the same as OP_OpenEphemeral. It has a
+** different name to distinguish its use. Tables created using
+** by this opcode will be used for automatically created transient
+** indices in joins.
+*/
+case OP_OpenAutoindex:
+case OP_OpenEphemeral: {
+ VdbeCursor *pCx;
+ KeyInfo *pKeyInfo;
+
+ static const int vfsFlags =
+ SQLITE_OPEN_READWRITE |
+ SQLITE_OPEN_CREATE |
+ SQLITE_OPEN_EXCLUSIVE |
+ SQLITE_OPEN_DELETEONCLOSE |
+ SQLITE_OPEN_TRANSIENT_DB;
+ assert( pOp->p1>=0 );
+ assert( pOp->p2>=0 );
+ pCx = p->apCsr[pOp->p1];
+ if( pCx && pCx->pBtx ){
+ /* If the ephermeral table is already open, erase all existing content
+ ** so that the table is empty again, rather than creating a new table. */
+ assert( pCx->isEphemeral );
+ pCx->seqCount = 0;
+ pCx->cacheStatus = CACHE_STALE;
+ rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0);
+ }else{
+ pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
+ if( pCx==0 ) goto no_mem;
+ pCx->isEphemeral = 1;
+ rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
+ BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
+ vfsFlags);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0);
+ }
+ if( rc==SQLITE_OK ){
+ /* If a transient index is required, create it by calling
+ ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
+ ** opening it. If a transient table is required, just use the
+ ** automatically created table with root-page 1 (an BLOB_INTKEY table).
+ */
+ if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
+ assert( pOp->p4type==P4_KEYINFO );
+ rc = sqlite3BtreeCreateTable(pCx->pBtx, &pCx->pgnoRoot,
+ BTREE_BLOBKEY | pOp->p5);
+ if( rc==SQLITE_OK ){
+ assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
+ assert( pKeyInfo->db==db );
+ assert( pKeyInfo->enc==ENC(db) );
+ rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
+ pKeyInfo, pCx->uc.pCursor);
+ }
+ pCx->isTable = 0;
+ }else{
+ pCx->pgnoRoot = SCHEMA_ROOT;
+ rc = sqlite3BtreeCursor(pCx->pBtx, SCHEMA_ROOT, BTREE_WRCSR,
+ 0, pCx->uc.pCursor);
+ pCx->isTable = 1;
+ }
+ }
+ pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
+ }
+ if( rc ) goto abort_due_to_error;
+ pCx->nullRow = 1;
+ break;
+}
+
+/* Opcode: SorterOpen P1 P2 P3 P4 *
+**
+** This opcode works like OP_OpenEphemeral except that it opens
+** a transient index that is specifically designed to sort large
+** tables using an external merge-sort algorithm.
+**
+** If argument P3 is non-zero, then it indicates that the sorter may
+** assume that a stable sort considering the first P3 fields of each
+** key is sufficient to produce the required results.
+*/
+case OP_SorterOpen: {
+ VdbeCursor *pCx;
+
+ assert( pOp->p1>=0 );
+ assert( pOp->p2>=0 );
+ pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
+ if( pCx==0 ) goto no_mem;
+ pCx->pKeyInfo = pOp->p4.pKeyInfo;
+ assert( pCx->pKeyInfo->db==db );
+ assert( pCx->pKeyInfo->enc==ENC(db) );
+ rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
+ if( rc ) goto abort_due_to_error;
+ break;
+}
+
+/* Opcode: SequenceTest P1 P2 * * *
+** Synopsis: if( cursor[P1].ctr++ ) pc = P2
+**
+** P1 is a sorter cursor. If the sequence counter is currently zero, jump
+** to P2. Regardless of whether or not the jump is taken, increment the
+** the sequence value.
+*/
+case OP_SequenceTest: {
+ VdbeCursor *pC;
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( isSorter(pC) );
+ if( (pC->seqCount++)==0 ){
+ goto jump_to_p2;
+ }
+ break;
+}
+
+/* Opcode: OpenPseudo P1 P2 P3 * *
+** Synopsis: P3 columns in r[P2]
+**
+** Open a new cursor that points to a fake table that contains a single
+** row of data. The content of that one row is the content of memory
+** register P2. In other words, cursor P1 becomes an alias for the
+** MEM_Blob content contained in register P2.
+**
+** A pseudo-table created by this opcode is used to hold a single
+** row output from the sorter so that the row can be decomposed into
+** individual columns using the OP_Column opcode. The OP_Column opcode
+** is the only cursor opcode that works with a pseudo-table.
+**
+** P3 is the number of fields in the records that will be stored by
+** the pseudo-table.
+*/
+case OP_OpenPseudo: {
+ VdbeCursor *pCx;
+
+ assert( pOp->p1>=0 );
+ assert( pOp->p3>=0 );
+ pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
+ if( pCx==0 ) goto no_mem;
+ pCx->nullRow = 1;
+ pCx->seekResult = pOp->p2;
+ pCx->isTable = 1;
+ /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
+ ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
+ ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
+ ** which is a performance optimization */
+ pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
+ assert( pOp->p5==0 );
+ break;
+}
+
+/* Opcode: Close P1 * * * *
+**
+** Close a cursor previously opened as P1. If P1 is not
+** currently open, this instruction is a no-op.
+*/
+case OP_Close: {
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
+ p->apCsr[pOp->p1] = 0;
+ break;
+}
+
+#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
+/* Opcode: ColumnsUsed P1 * * P4 *
+**
+** This opcode (which only exists if SQLite was compiled with
+** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
+** table or index for cursor P1 are used. P4 is a 64-bit integer
+** (P4_INT64) in which the first 63 bits are one for each of the
+** first 63 columns of the table or index that are actually used
+** by the cursor. The high-order bit is set if any column after
+** the 64th is used.
+*/
+case OP_ColumnsUsed: {
+ VdbeCursor *pC;
+ pC = p->apCsr[pOp->p1];
+ assert( pC->eCurType==CURTYPE_BTREE );
+ pC->maskUsed = *(u64*)pOp->p4.pI64;
+ break;
+}
+#endif
+
+/* Opcode: SeekGE P1 P2 P3 P4 *
+** Synopsis: key=r[P3@P4]
+**
+** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
+** use the value in register P3 as the key. If cursor P1 refers
+** to an SQL index, then P3 is the first in an array of P4 registers
+** that are used as an unpacked index key.
+**
+** Reposition cursor P1 so that it points to the smallest entry that
+** is greater than or equal to the key value. If there are no records
+** greater than or equal to the key and P2 is not zero, then jump to P2.
+**
+** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
+** opcode will either land on a record that exactly matches the key, or
+** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ,
+** this opcode must be followed by an IdxLE opcode with the same arguments.
+** The IdxGT opcode will be skipped if this opcode succeeds, but the
+** IdxGT opcode will be used on subsequent loop iterations. The
+** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
+** is an equality search.
+**
+** This opcode leaves the cursor configured to move in forward order,
+** from the beginning toward the end. In other words, the cursor is
+** configured to use Next, not Prev.
+**
+** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
+*/
+/* Opcode: SeekGT P1 P2 P3 P4 *
+** Synopsis: key=r[P3@P4]
+**
+** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
+** use the value in register P3 as a key. If cursor P1 refers
+** to an SQL index, then P3 is the first in an array of P4 registers
+** that are used as an unpacked index key.
+**
+** Reposition cursor P1 so that it points to the smallest entry that
+** is greater than the key value. If there are no records greater than
+** the key and P2 is not zero, then jump to P2.
+**
+** This opcode leaves the cursor configured to move in forward order,
+** from the beginning toward the end. In other words, the cursor is
+** configured to use Next, not Prev.
+**
+** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
+*/
+/* Opcode: SeekLT P1 P2 P3 P4 *
+** Synopsis: key=r[P3@P4]
+**
+** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
+** use the value in register P3 as a key. If cursor P1 refers
+** to an SQL index, then P3 is the first in an array of P4 registers
+** that are used as an unpacked index key.
+**
+** Reposition cursor P1 so that it points to the largest entry that
+** is less than the key value. If there are no records less than
+** the key and P2 is not zero, then jump to P2.
+**
+** This opcode leaves the cursor configured to move in reverse order,
+** from the end toward the beginning. In other words, the cursor is
+** configured to use Prev, not Next.
+**
+** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
+*/
+/* Opcode: SeekLE P1 P2 P3 P4 *
+** Synopsis: key=r[P3@P4]
+**
+** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
+** use the value in register P3 as a key. If cursor P1 refers
+** to an SQL index, then P3 is the first in an array of P4 registers
+** that are used as an unpacked index key.
+**
+** Reposition cursor P1 so that it points to the largest entry that
+** is less than or equal to the key value. If there are no records
+** less than or equal to the key and P2 is not zero, then jump to P2.
+**
+** This opcode leaves the cursor configured to move in reverse order,
+** from the end toward the beginning. In other words, the cursor is
+** configured to use Prev, not Next.
+**
+** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
+** opcode will either land on a record that exactly matches the key, or
+** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ,
+** this opcode must be followed by an IdxLE opcode with the same arguments.
+** The IdxGE opcode will be skipped if this opcode succeeds, but the
+** IdxGE opcode will be used on subsequent loop iterations. The
+** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
+** is an equality search.
+**
+** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
+*/
+case OP_SeekLT: /* jump, in3, group */
+case OP_SeekLE: /* jump, in3, group */
+case OP_SeekGE: /* jump, in3, group */
+case OP_SeekGT: { /* jump, in3, group */
+ int res; /* Comparison result */
+ int oc; /* Opcode */
+ VdbeCursor *pC; /* The cursor to seek */
+ UnpackedRecord r; /* The key to seek for */
+ int nField; /* Number of columns or fields in the key */
+ i64 iKey; /* The rowid we are to seek to */
+ int eqOnly; /* Only interested in == results */
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ assert( pOp->p2!=0 );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( pC->eCurType==CURTYPE_BTREE );
+ assert( OP_SeekLE == OP_SeekLT+1 );
+ assert( OP_SeekGE == OP_SeekLT+2 );
+ assert( OP_SeekGT == OP_SeekLT+3 );
+ assert( pC->isOrdered );
+ assert( pC->uc.pCursor!=0 );
+ oc = pOp->opcode;
+ eqOnly = 0;
+ pC->nullRow = 0;
+#ifdef SQLITE_DEBUG
+ pC->seekOp = pOp->opcode;
+#endif
+
+ pC->deferredMoveto = 0;
+ pC->cacheStatus = CACHE_STALE;
+ if( pC->isTable ){
+ u16 flags3, newType;
+ /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */
+ assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
+ || CORRUPT_DB );
+
+ /* The input value in P3 might be of any type: integer, real, string,
+ ** blob, or NULL. But it needs to be an integer before we can do
+ ** the seek, so convert it. */
+ pIn3 = &aMem[pOp->p3];
+ flags3 = pIn3->flags;
+ if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){
+ applyNumericAffinity(pIn3, 0);
+ }
+ iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */
+ newType = pIn3->flags; /* Record the type after applying numeric affinity */
+ pIn3->flags = flags3; /* But convert the type back to its original */
+
+ /* If the P3 value could not be converted into an integer without
+ ** loss of information, then special processing is required... */
+ if( (newType & (MEM_Int|MEM_IntReal))==0 ){
+ if( (newType & MEM_Real)==0 ){
+ if( (newType & MEM_Null) || oc>=OP_SeekGE ){
+ VdbeBranchTaken(1,2);
+ goto jump_to_p2;
+ }else{
+ rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
+ if( rc!=SQLITE_OK ) goto abort_due_to_error;
+ goto seek_not_found;
+ }
+ }else
+
+ /* If the approximation iKey is larger than the actual real search
+ ** term, substitute >= for > and < for <=. e.g. if the search term
+ ** is 4.9 and the integer approximation 5:
+ **
+ ** (x > 4.9) -> (x >= 5)
+ ** (x <= 4.9) -> (x < 5)
+ */
+ if( pIn3->u.r<(double)iKey ){
+ assert( OP_SeekGE==(OP_SeekGT-1) );
+ assert( OP_SeekLT==(OP_SeekLE-1) );
+ assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
+ if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
+ }
+
+ /* If the approximation iKey is smaller than the actual real search
+ ** term, substitute <= for < and > for >=. */
+ else if( pIn3->u.r>(double)iKey ){
+ assert( OP_SeekLE==(OP_SeekLT+1) );
+ assert( OP_SeekGT==(OP_SeekGE+1) );
+ assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
+ if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
+ }
+ }
+ rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
+ pC->movetoTarget = iKey; /* Used by OP_Delete */
+ if( rc!=SQLITE_OK ){
+ goto abort_due_to_error;
+ }
+ }else{
+ /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the
+ ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be
+ ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively,
+ ** with the same key.
+ */
+ if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
+ eqOnly = 1;
+ assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
+ assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
+ assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );
+ assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );
+ assert( pOp[1].p1==pOp[0].p1 );
+ assert( pOp[1].p2==pOp[0].p2 );
+ assert( pOp[1].p3==pOp[0].p3 );
+ assert( pOp[1].p4.i==pOp[0].p4.i );
+ }
+
+ nField = pOp->p4.i;
+ assert( pOp->p4type==P4_INT32 );
+ assert( nField>0 );
+ r.pKeyInfo = pC->pKeyInfo;
+ r.nField = (u16)nField;
+
+ /* The next line of code computes as follows, only faster:
+ ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
+ ** r.default_rc = -1;
+ ** }else{
+ ** r.default_rc = +1;
+ ** }
+ */
+ r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
+ assert( oc!=OP_SeekGT || r.default_rc==-1 );
+ assert( oc!=OP_SeekLE || r.default_rc==-1 );
+ assert( oc!=OP_SeekGE || r.default_rc==+1 );
+ assert( oc!=OP_SeekLT || r.default_rc==+1 );
+
+ r.aMem = &aMem[pOp->p3];
+#ifdef SQLITE_DEBUG
+ { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
+#endif
+ r.eqSeen = 0;
+ rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
+ if( rc!=SQLITE_OK ){
+ goto abort_due_to_error;
+ }
+ if( eqOnly && r.eqSeen==0 ){
+ assert( res!=0 );
+ goto seek_not_found;
+ }
+ }
+#ifdef SQLITE_TEST
+ sqlite3_search_count++;
+#endif
+ if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
+ if( res<0 || (res==0 && oc==OP_SeekGT) ){
+ res = 0;
+ rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
+ if( rc!=SQLITE_OK ){
+ if( rc==SQLITE_DONE ){
+ rc = SQLITE_OK;
+ res = 1;
+ }else{
+ goto abort_due_to_error;
+ }
+ }
+ }else{
+ res = 0;
+ }
+ }else{
+ assert( oc==OP_SeekLT || oc==OP_SeekLE );
+ if( res>0 || (res==0 && oc==OP_SeekLT) ){
+ res = 0;
+ rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
+ if( rc!=SQLITE_OK ){
+ if( rc==SQLITE_DONE ){
+ rc = SQLITE_OK;
+ res = 1;
+ }else{
+ goto abort_due_to_error;
+ }
+ }
+ }else{
+ /* res might be negative because the table is empty. Check to
+ ** see if this is the case.
+ */
+ res = sqlite3BtreeEof(pC->uc.pCursor);
+ }
+ }
+seek_not_found:
+ assert( pOp->p2>0 );
+ VdbeBranchTaken(res!=0,2);
+ if( res ){
+ goto jump_to_p2;
+ }else if( eqOnly ){
+ assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
+ pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
+ }
+ break;
+}
+
+
+/* Opcode: SeekScan P1 P2 * * *
+** Synopsis: Scan-ahead up to P1 rows
+**
+** This opcode is a prefix opcode to OP_SeekGE. In other words, this
+** opcode must be immediately followed by OP_SeekGE. This constraint is
+** checked by assert() statements.
+**
+** This opcode uses the P1 through P4 operands of the subsequent
+** OP_SeekGE. In the text that follows, the operands of the subsequent
+** OP_SeekGE opcode are denoted as SeekOP.P1 through SeekOP.P4. Only
+** the P1 and P2 operands of this opcode are also used, and are called
+** This.P1 and This.P2.
+**
+** This opcode helps to optimize IN operators on a multi-column index
+** where the IN operator is on the later terms of the index by avoiding
+** unnecessary seeks on the btree, substituting steps to the next row
+** of the b-tree instead. A correct answer is obtained if this opcode
+** is omitted or is a no-op.
+**
+** The SeekGE.P3 and SeekGE.P4 operands identify an unpacked key which
+** is the desired entry that we want the cursor SeekGE.P1 to be pointing
+** to. Call this SeekGE.P4/P5 row the "target".
+**
+** If the SeekGE.P1 cursor is not currently pointing to a valid row,
+** then this opcode is a no-op and control passes through into the OP_SeekGE.
+**
+** If the SeekGE.P1 cursor is pointing to a valid row, then that row
+** might be the target row, or it might be near and slightly before the
+** target row. This opcode attempts to position the cursor on the target
+** row by, perhaps by invoking sqlite3BtreeStep() on the cursor
+** between 0 and This.P1 times.
+**
+** There are three possible outcomes from this opcode:<ol>
+**
+** <li> If after This.P1 steps, the cursor is still point to a place that
+** is earlier in the btree than the target row,
+** then fall through into the subsquence OP_SeekGE opcode.
+**
+** <li> If the cursor is successfully moved to the target row by 0 or more
+** sqlite3BtreeNext() calls, then jump to This.P2, which will land just
+** past the OP_IdxGT opcode that follows the OP_SeekGE.
+**
+** <li> If the cursor ends up past the target row (indicating the the target
+** row does not exist in the btree) then jump to SeekOP.P2.
+** </ol>
+*/
+case OP_SeekScan: {
+ VdbeCursor *pC;
+ int res;
+ int nStep;
+ UnpackedRecord r;
+
+ assert( pOp[1].opcode==OP_SeekGE );
+
+ /* pOp->p2 points to the first instruction past the OP_IdxGT that
+ ** follows the OP_SeekGE. */
+ assert( pOp->p2>=(int)(pOp-aOp)+2 );
+ assert( aOp[pOp->p2-1].opcode==OP_IdxGT );
+ assert( pOp[1].p1==aOp[pOp->p2-1].p1 );
+ assert( pOp[1].p2==aOp[pOp->p2-1].p2 );
+ assert( pOp[1].p3==aOp[pOp->p2-1].p3 );
+
+ assert( pOp->p1>0 );
+ pC = p->apCsr[pOp[1].p1];
+ assert( pC!=0 );
+ assert( pC->eCurType==CURTYPE_BTREE );
+ assert( !pC->isTable );
+ if( !sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) ){
+#ifdef SQLITE_DEBUG
+ if( db->flags&SQLITE_VdbeTrace ){
+ printf("... cursor not valid - fall through\n");
+ }
+#endif
+ break;
+ }
+ nStep = pOp->p1;
+ assert( nStep>=1 );
+ r.pKeyInfo = pC->pKeyInfo;
+ r.nField = (u16)pOp[1].p4.i;
+ r.default_rc = 0;
+ r.aMem = &aMem[pOp[1].p3];
+#ifdef SQLITE_DEBUG
+ {
+ int i;
+ for(i=0; i<r.nField; i++){
+ assert( memIsValid(&r.aMem[i]) );
+ REGISTER_TRACE(pOp[1].p3+i, &aMem[pOp[1].p3+i]);
+ }
+ }
+#endif
+ res = 0; /* Not needed. Only used to silence a warning. */
+ while(1){
+ rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
+ if( rc ) goto abort_due_to_error;
+ if( res>0 ){
+ seekscan_search_fail:
+#ifdef SQLITE_DEBUG
+ if( db->flags&SQLITE_VdbeTrace ){
+ printf("... %d steps and then skip\n", pOp->p1 - nStep);
+ }
+#endif
+ VdbeBranchTaken(1,3);
+ pOp++;
+ goto jump_to_p2;
+ }
+ if( res==0 ){
+#ifdef SQLITE_DEBUG
+ if( db->flags&SQLITE_VdbeTrace ){
+ printf("... %d steps and then success\n", pOp->p1 - nStep);
+ }
+#endif
+ VdbeBranchTaken(2,3);
+ goto jump_to_p2;
+ break;
+ }
+ if( nStep<=0 ){
+#ifdef SQLITE_DEBUG
+ if( db->flags&SQLITE_VdbeTrace ){
+ printf("... fall through after %d steps\n", pOp->p1);
+ }
+#endif
+ VdbeBranchTaken(0,3);
+ break;
+ }
+ nStep--;
+ rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
+ if( rc ){
+ if( rc==SQLITE_DONE ){
+ rc = SQLITE_OK;
+ goto seekscan_search_fail;
+ }else{
+ goto abort_due_to_error;
+ }
+ }
+ }
+
+ break;
+}
+
+
+/* Opcode: SeekHit P1 P2 P3 * *
+** Synopsis: set P2<=seekHit<=P3
+**
+** Increase or decrease the seekHit value for cursor P1, if necessary,
+** so that it is no less than P2 and no greater than P3.
+**
+** The seekHit integer represents the maximum of terms in an index for which
+** there is known to be at least one match. If the seekHit value is smaller
+** than the total number of equality terms in an index lookup, then the
+** OP_IfNoHope opcode might run to see if the IN loop can be abandoned
+** early, thus saving work. This is part of the IN-early-out optimization.
+**
+** P1 must be a valid b-tree cursor.
+*/
+case OP_SeekHit: {
+ VdbeCursor *pC;
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( pOp->p3>=pOp->p2 );
+ if( pC->seekHit<pOp->p2 ){
+ pC->seekHit = pOp->p2;
+ }else if( pC->seekHit>pOp->p3 ){
+ pC->seekHit = pOp->p3;
+ }
+ break;
+}
+
+/* Opcode: IfNotOpen P1 P2 * * *
+** Synopsis: if( !csr[P1] ) goto P2
+**
+** If cursor P1 is not open, jump to instruction P2. Otherwise, fall through.
+*/
+case OP_IfNotOpen: { /* jump */
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ VdbeBranchTaken(p->apCsr[pOp->p1]==0, 2);
+ if( !p->apCsr[pOp->p1] ){
+ goto jump_to_p2_and_check_for_interrupt;
+ }
+ break;
+}
+
+/* Opcode: Found P1 P2 P3 P4 *
+** Synopsis: key=r[P3@P4]
+**
+** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
+** P4>0 then register P3 is the first of P4 registers that form an unpacked
+** record.
+**
+** Cursor P1 is on an index btree. If the record identified by P3 and P4
+** is a prefix of any entry in P1 then a jump is made to P2 and
+** P1 is left pointing at the matching entry.
+**
+** This operation leaves the cursor in a state where it can be
+** advanced in the forward direction. The Next instruction will work,
+** but not the Prev instruction.
+**
+** See also: NotFound, NoConflict, NotExists. SeekGe
+*/
+/* Opcode: NotFound P1 P2 P3 P4 *
+** Synopsis: key=r[P3@P4]
+**
+** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
+** P4>0 then register P3 is the first of P4 registers that form an unpacked
+** record.
+**
+** Cursor P1 is on an index btree. If the record identified by P3 and P4
+** is not the prefix of any entry in P1 then a jump is made to P2. If P1
+** does contain an entry whose prefix matches the P3/P4 record then control
+** falls through to the next instruction and P1 is left pointing at the
+** matching entry.
+**
+** This operation leaves the cursor in a state where it cannot be
+** advanced in either direction. In other words, the Next and Prev
+** opcodes do not work after this operation.
+**
+** See also: Found, NotExists, NoConflict, IfNoHope
+*/
+/* Opcode: IfNoHope P1 P2 P3 P4 *
+** Synopsis: key=r[P3@P4]
+**
+** Register P3 is the first of P4 registers that form an unpacked
+** record. Cursor P1 is an index btree. P2 is a jump destination.
+** In other words, the operands to this opcode are the same as the
+** operands to OP_NotFound and OP_IdxGT.
+**
+** This opcode is an optimization attempt only. If this opcode always
+** falls through, the correct answer is still obtained, but extra works
+** is performed.
+**
+** A value of N in the seekHit flag of cursor P1 means that there exists
+** a key P3:N that will match some record in the index. We want to know
+** if it is possible for a record P3:P4 to match some record in the
+** index. If it is not possible, we can skips some work. So if seekHit
+** is less than P4, attempt to find out if a match is possible by running
+** OP_NotFound.
+**
+** This opcode is used in IN clause processing for a multi-column key.
+** If an IN clause is attached to an element of the key other than the
+** left-most element, and if there are no matches on the most recent
+** seek over the whole key, then it might be that one of the key element
+** to the left is prohibiting a match, and hence there is "no hope" of
+** any match regardless of how many IN clause elements are checked.
+** In such a case, we abandon the IN clause search early, using this
+** opcode. The opcode name comes from the fact that the
+** jump is taken if there is "no hope" of achieving a match.
+**
+** See also: NotFound, SeekHit
+*/
+/* Opcode: NoConflict P1 P2 P3 P4 *
+** Synopsis: key=r[P3@P4]
+**
+** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
+** P4>0 then register P3 is the first of P4 registers that form an unpacked
+** record.
+**
+** Cursor P1 is on an index btree. If the record identified by P3 and P4
+** contains any NULL value, jump immediately to P2. If all terms of the
+** record are not-NULL then a check is done to determine if any row in the
+** P1 index btree has a matching key prefix. If there are no matches, jump
+** immediately to P2. If there is a match, fall through and leave the P1
+** cursor pointing to the matching row.
+**
+** This opcode is similar to OP_NotFound with the exceptions that the
+** branch is always taken if any part of the search key input is NULL.
+**
+** This operation leaves the cursor in a state where it cannot be
+** advanced in either direction. In other words, the Next and Prev
+** opcodes do not work after this operation.
+**
+** See also: NotFound, Found, NotExists
+*/
+case OP_IfNoHope: { /* jump, in3 */
+ VdbeCursor *pC;
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ if( pC->seekHit>=pOp->p4.i ) break;
+ /* Fall through into OP_NotFound */
+ /* no break */ deliberate_fall_through
+}
+case OP_NoConflict: /* jump, in3 */
+case OP_NotFound: /* jump, in3 */
+case OP_Found: { /* jump, in3 */
+ int alreadyExists;
+ int takeJump;
+ int ii;
+ VdbeCursor *pC;
+ int res;
+ UnpackedRecord *pFree;
+ UnpackedRecord *pIdxKey;
+ UnpackedRecord r;
+
+#ifdef SQLITE_TEST
+ if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
+#endif
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ assert( pOp->p4type==P4_INT32 );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+#ifdef SQLITE_DEBUG
+ pC->seekOp = pOp->opcode;
+#endif
+ pIn3 = &aMem[pOp->p3];
+ assert( pC->eCurType==CURTYPE_BTREE );
+ assert( pC->uc.pCursor!=0 );
+ assert( pC->isTable==0 );
+ if( pOp->p4.i>0 ){
+ r.pKeyInfo = pC->pKeyInfo;
+ r.nField = (u16)pOp->p4.i;
+ r.aMem = pIn3;
+#ifdef SQLITE_DEBUG
+ for(ii=0; ii<r.nField; ii++){
+ assert( memIsValid(&r.aMem[ii]) );
+ assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
+ if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
+ }
+#endif
+ pIdxKey = &r;
+ pFree = 0;
+ }else{
+ assert( pIn3->flags & MEM_Blob );
+ rc = ExpandBlob(pIn3);
+ assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
+ if( rc ) goto no_mem;
+ pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
+ if( pIdxKey==0 ) goto no_mem;
+ sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
+ }
+ pIdxKey->default_rc = 0;
+ takeJump = 0;
+ if( pOp->opcode==OP_NoConflict ){
+ /* For the OP_NoConflict opcode, take the jump if any of the
+ ** input fields are NULL, since any key with a NULL will not
+ ** conflict */
+ for(ii=0; ii<pIdxKey->nField; ii++){
+ if( pIdxKey->aMem[ii].flags & MEM_Null ){
+ takeJump = 1;
+ break;
+ }
+ }
+ }
+ rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
+ if( pFree ) sqlite3DbFreeNN(db, pFree);
+ if( rc!=SQLITE_OK ){
+ goto abort_due_to_error;
+ }
+ pC->seekResult = res;
+ alreadyExists = (res==0);
+ pC->nullRow = 1-alreadyExists;
+ pC->deferredMoveto = 0;
+ pC->cacheStatus = CACHE_STALE;
+ if( pOp->opcode==OP_Found ){
+ VdbeBranchTaken(alreadyExists!=0,2);
+ if( alreadyExists ) goto jump_to_p2;
+ }else{
+ VdbeBranchTaken(takeJump||alreadyExists==0,2);
+ if( takeJump || !alreadyExists ) goto jump_to_p2;
+ if( pOp->opcode==OP_IfNoHope ) pC->seekHit = pOp->p4.i;
+ }
+ break;
+}
+
+/* Opcode: SeekRowid P1 P2 P3 * *
+** Synopsis: intkey=r[P3]
+**
+** P1 is the index of a cursor open on an SQL table btree (with integer
+** keys). If register P3 does not contain an integer or if P1 does not
+** contain a record with rowid P3 then jump immediately to P2.
+** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
+** a record with rowid P3 then
+** leave the cursor pointing at that record and fall through to the next
+** instruction.
+**
+** The OP_NotExists opcode performs the same operation, but with OP_NotExists
+** the P3 register must be guaranteed to contain an integer value. With this
+** opcode, register P3 might not contain an integer.
+**
+** The OP_NotFound opcode performs the same operation on index btrees
+** (with arbitrary multi-value keys).
+**
+** This opcode leaves the cursor in a state where it cannot be advanced
+** in either direction. In other words, the Next and Prev opcodes will
+** not work following this opcode.
+**
+** See also: Found, NotFound, NoConflict, SeekRowid
+*/
+/* Opcode: NotExists P1 P2 P3 * *
+** Synopsis: intkey=r[P3]
+**
+** P1 is the index of a cursor open on an SQL table btree (with integer
+** keys). P3 is an integer rowid. If P1 does not contain a record with
+** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
+** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
+** leave the cursor pointing at that record and fall through to the next
+** instruction.
+**
+** The OP_SeekRowid opcode performs the same operation but also allows the
+** P3 register to contain a non-integer value, in which case the jump is
+** always taken. This opcode requires that P3 always contain an integer.
+**
+** The OP_NotFound opcode performs the same operation on index btrees
+** (with arbitrary multi-value keys).
+**
+** This opcode leaves the cursor in a state where it cannot be advanced
+** in either direction. In other words, the Next and Prev opcodes will
+** not work following this opcode.
+**
+** See also: Found, NotFound, NoConflict, SeekRowid
+*/
+case OP_SeekRowid: { /* jump, in3 */
+ VdbeCursor *pC;
+ BtCursor *pCrsr;
+ int res;
+ u64 iKey;
+
+ pIn3 = &aMem[pOp->p3];
+ testcase( pIn3->flags & MEM_Int );
+ testcase( pIn3->flags & MEM_IntReal );
+ testcase( pIn3->flags & MEM_Real );
+ testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str );
+ if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
+ /* If pIn3->u.i does not contain an integer, compute iKey as the
+ ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted
+ ** into an integer without loss of information. Take care to avoid
+ ** changing the datatype of pIn3, however, as it is used by other
+ ** parts of the prepared statement. */
+ Mem x = pIn3[0];
+ applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding);
+ if( (x.flags & MEM_Int)==0 ) goto jump_to_p2;
+ iKey = x.u.i;
+ goto notExistsWithKey;
+ }
+ /* Fall through into OP_NotExists */
+ /* no break */ deliberate_fall_through
+case OP_NotExists: /* jump, in3 */
+ pIn3 = &aMem[pOp->p3];
+ assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ iKey = pIn3->u.i;
+notExistsWithKey:
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+#ifdef SQLITE_DEBUG
+ if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
+#endif
+ assert( pC->isTable );
+ assert( pC->eCurType==CURTYPE_BTREE );
+ pCrsr = pC->uc.pCursor;
+ assert( pCrsr!=0 );
+ res = 0;
+ rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
+ assert( rc==SQLITE_OK || res==0 );
+ pC->movetoTarget = iKey; /* Used by OP_Delete */
+ pC->nullRow = 0;
+ pC->cacheStatus = CACHE_STALE;
+ pC->deferredMoveto = 0;
+ VdbeBranchTaken(res!=0,2);
+ pC->seekResult = res;
+ if( res!=0 ){
+ assert( rc==SQLITE_OK );
+ if( pOp->p2==0 ){
+ rc = SQLITE_CORRUPT_BKPT;
+ }else{
+ goto jump_to_p2;
+ }
+ }
+ if( rc ) goto abort_due_to_error;
+ break;
+}
+
+/* Opcode: Sequence P1 P2 * * *
+** Synopsis: r[P2]=cursor[P1].ctr++
+**
+** Find the next available sequence number for cursor P1.
+** Write the sequence number into register P2.
+** The sequence number on the cursor is incremented after this
+** instruction.
+*/
+case OP_Sequence: { /* out2 */
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ assert( p->apCsr[pOp->p1]!=0 );
+ assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
+ pOut = out2Prerelease(p, pOp);
+ pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
+ break;
+}
+
+
+/* Opcode: NewRowid P1 P2 P3 * *
+** Synopsis: r[P2]=rowid
+**
+** Get a new integer record number (a.k.a "rowid") used as the key to a table.
+** The record number is not previously used as a key in the database
+** table that cursor P1 points to. The new record number is written
+** written to register P2.
+**
+** If P3>0 then P3 is a register in the root frame of this VDBE that holds
+** the largest previously generated record number. No new record numbers are
+** allowed to be less than this value. When this value reaches its maximum,
+** an SQLITE_FULL error is generated. The P3 register is updated with the '
+** generated record number. This P3 mechanism is used to help implement the
+** AUTOINCREMENT feature.
+*/
+case OP_NewRowid: { /* out2 */
+ i64 v; /* The new rowid */
+ VdbeCursor *pC; /* Cursor of table to get the new rowid */
+ int res; /* Result of an sqlite3BtreeLast() */
+ int cnt; /* Counter to limit the number of searches */
+ Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
+ VdbeFrame *pFrame; /* Root frame of VDBE */
+
+ v = 0;
+ res = 0;
+ pOut = out2Prerelease(p, pOp);
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( pC->isTable );
+ assert( pC->eCurType==CURTYPE_BTREE );
+ assert( pC->uc.pCursor!=0 );
+ {
+ /* The next rowid or record number (different terms for the same
+ ** thing) is obtained in a two-step algorithm.
+ **
+ ** First we attempt to find the largest existing rowid and add one
+ ** to that. But if the largest existing rowid is already the maximum
+ ** positive integer, we have to fall through to the second
+ ** probabilistic algorithm
+ **
+ ** The second algorithm is to select a rowid at random and see if
+ ** it already exists in the table. If it does not exist, we have
+ ** succeeded. If the random rowid does exist, we select a new one
+ ** and try again, up to 100 times.
+ */
+ assert( pC->isTable );
+
+#ifdef SQLITE_32BIT_ROWID
+# define MAX_ROWID 0x7fffffff
+#else
+ /* Some compilers complain about constants of the form 0x7fffffffffffffff.
+ ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
+ ** to provide the constant while making all compilers happy.
+ */
+# define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
+#endif
+
+ if( !pC->useRandomRowid ){
+ rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
+ if( rc!=SQLITE_OK ){
+ goto abort_due_to_error;
+ }
+ if( res ){
+ v = 1; /* IMP: R-61914-48074 */
+ }else{
+ assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
+ v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
+ if( v>=MAX_ROWID ){
+ pC->useRandomRowid = 1;
+ }else{
+ v++; /* IMP: R-29538-34987 */
+ }
+ }
+ }
+
+#ifndef SQLITE_OMIT_AUTOINCREMENT
+ if( pOp->p3 ){
+ /* Assert that P3 is a valid memory cell. */
+ assert( pOp->p3>0 );
+ if( p->pFrame ){
+ for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
+ /* Assert that P3 is a valid memory cell. */
+ assert( pOp->p3<=pFrame->nMem );
+ pMem = &pFrame->aMem[pOp->p3];
+ }else{
+ /* Assert that P3 is a valid memory cell. */
+ assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
+ pMem = &aMem[pOp->p3];
+ memAboutToChange(p, pMem);
+ }
+ assert( memIsValid(pMem) );
+
+ REGISTER_TRACE(pOp->p3, pMem);
+ sqlite3VdbeMemIntegerify(pMem);
+ assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
+ if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
+ rc = SQLITE_FULL; /* IMP: R-17817-00630 */
+ goto abort_due_to_error;
+ }
+ if( v<pMem->u.i+1 ){
+ v = pMem->u.i + 1;
+ }
+ pMem->u.i = v;
+ }
+#endif
+ if( pC->useRandomRowid ){
+ /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
+ ** largest possible integer (9223372036854775807) then the database
+ ** engine starts picking positive candidate ROWIDs at random until
+ ** it finds one that is not previously used. */
+ assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
+ ** an AUTOINCREMENT table. */
+ cnt = 0;
+ do{
+ sqlite3_randomness(sizeof(v), &v);
+ v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
+ }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
+ 0, &res))==SQLITE_OK)
+ && (res==0)
+ && (++cnt<100));
+ if( rc ) goto abort_due_to_error;
+ if( res==0 ){
+ rc = SQLITE_FULL; /* IMP: R-38219-53002 */
+ goto abort_due_to_error;
+ }
+ assert( v>0 ); /* EV: R-40812-03570 */
+ }
+ pC->deferredMoveto = 0;
+ pC->cacheStatus = CACHE_STALE;
+ }
+ pOut->u.i = v;
+ break;
+}
+
+/* Opcode: Insert P1 P2 P3 P4 P5
+** Synopsis: intkey=r[P3] data=r[P2]
+**
+** Write an entry into the table of cursor P1. A new entry is
+** created if it doesn't already exist or the data for an existing
+** entry is overwritten. The data is the value MEM_Blob stored in register
+** number P2. The key is stored in register P3. The key must
+** be a MEM_Int.
+**
+** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
+** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
+** then rowid is stored for subsequent return by the
+** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
+**
+** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
+** run faster by avoiding an unnecessary seek on cursor P1. However,
+** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
+** seeks on the cursor or if the most recent seek used a key equal to P3.
+**
+** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
+** UPDATE operation. Otherwise (if the flag is clear) then this opcode
+** is part of an INSERT operation. The difference is only important to
+** the update hook.
+**
+** Parameter P4 may point to a Table structure, or may be NULL. If it is
+** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
+** following a successful insert.
+**
+** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
+** allocated, then ownership of P2 is transferred to the pseudo-cursor
+** and register P2 becomes ephemeral. If the cursor is changed, the
+** value of register P2 will then change. Make sure this does not
+** cause any problems.)
+**
+** This instruction only works on tables. The equivalent instruction
+** for indices is OP_IdxInsert.
+*/
+case OP_Insert: {
+ Mem *pData; /* MEM cell holding data for the record to be inserted */
+ Mem *pKey; /* MEM cell holding key for the record */
+ VdbeCursor *pC; /* Cursor to table into which insert is written */
+ int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
+ const char *zDb; /* database name - used by the update hook */
+ Table *pTab; /* Table structure - used by update and pre-update hooks */
+ BtreePayload x; /* Payload to be inserted */
+
+ pData = &aMem[pOp->p2];
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ assert( memIsValid(pData) );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( pC->eCurType==CURTYPE_BTREE );
+ assert( pC->deferredMoveto==0 );
+ assert( pC->uc.pCursor!=0 );
+ assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
+ assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
+ REGISTER_TRACE(pOp->p2, pData);
+ sqlite3VdbeIncrWriteCounter(p, pC);
+
+ pKey = &aMem[pOp->p3];
+ assert( pKey->flags & MEM_Int );
+ assert( memIsValid(pKey) );
+ REGISTER_TRACE(pOp->p3, pKey);
+ x.nKey = pKey->u.i;
+
+ if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
+ assert( pC->iDb>=0 );
+ zDb = db->aDb[pC->iDb].zDbSName;
+ pTab = pOp->p4.pTab;
+ assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
+ }else{
+ pTab = 0;
+ zDb = 0; /* Not needed. Silence a compiler warning. */
+ }
+
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+ /* Invoke the pre-update hook, if any */
+ if( pTab ){
+ if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
+ sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
+ }
+ if( db->xUpdateCallback==0 || pTab->aCol==0 ){
+ /* Prevent post-update hook from running in cases when it should not */
+ pTab = 0;
+ }
+ }
+ if( pOp->p5 & OPFLAG_ISNOOP ) break;
+#endif
+
+ if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
+ if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
+ assert( pData->flags & (MEM_Blob|MEM_Str) );
+ x.pData = pData->z;
+ x.nData = pData->n;
+ seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
+ if( pData->flags & MEM_Zero ){
+ x.nZero = pData->u.nZero;
+ }else{
+ x.nZero = 0;
+ }
+ x.pKey = 0;
+ rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
+ (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
+ );
+ pC->deferredMoveto = 0;
+ pC->cacheStatus = CACHE_STALE;
+
+ /* Invoke the update-hook if required. */
+ if( rc ) goto abort_due_to_error;
+ if( pTab ){
+ assert( db->xUpdateCallback!=0 );
+ assert( pTab->aCol!=0 );
+ db->xUpdateCallback(db->pUpdateArg,
+ (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
+ zDb, pTab->zName, x.nKey);
+ }
+ break;
+}
+
+/* Opcode: Delete P1 P2 P3 P4 P5
+**
+** Delete the record at which the P1 cursor is currently pointing.
+**
+** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
+** the cursor will be left pointing at either the next or the previous
+** record in the table. If it is left pointing at the next record, then
+** the next Next instruction will be a no-op. As a result, in this case
+** it is ok to delete a record from within a Next loop. If
+** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
+** left in an undefined state.
+**
+** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
+** delete one of several associated with deleting a table row and all its
+** associated index entries. Exactly one of those deletes is the "primary"
+** delete. The others are all on OPFLAG_FORDELETE cursors or else are
+** marked with the AUXDELETE flag.
+**
+** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
+** change count is incremented (otherwise not).
+**
+** P1 must not be pseudo-table. It has to be a real table with
+** multiple rows.
+**
+** If P4 is not NULL then it points to a Table object. In this case either
+** the update or pre-update hook, or both, may be invoked. The P1 cursor must
+** have been positioned using OP_NotFound prior to invoking this opcode in
+** this case. Specifically, if one is configured, the pre-update hook is
+** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
+** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
+**
+** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
+** of the memory cell that contains the value that the rowid of the row will
+** be set to by the update.
+*/
+case OP_Delete: {
+ VdbeCursor *pC;
+ const char *zDb;
+ Table *pTab;
+ int opflags;
+
+ opflags = pOp->p2;
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( pC->eCurType==CURTYPE_BTREE );
+ assert( pC->uc.pCursor!=0 );
+ assert( pC->deferredMoveto==0 );
+ sqlite3VdbeIncrWriteCounter(p, pC);
+
+#ifdef SQLITE_DEBUG
+ if( pOp->p4type==P4_TABLE
+ && HasRowid(pOp->p4.pTab)
+ && pOp->p5==0
+ && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
+ ){
+ /* If p5 is zero, the seek operation that positioned the cursor prior to
+ ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
+ ** the row that is being deleted */
+ i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
+ assert( CORRUPT_DB || pC->movetoTarget==iKey );
+ }
+#endif
+
+ /* If the update-hook or pre-update-hook will be invoked, set zDb to
+ ** the name of the db to pass as to it. Also set local pTab to a copy
+ ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
+ ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
+ ** VdbeCursor.movetoTarget to the current rowid. */
+ if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
+ assert( pC->iDb>=0 );
+ assert( pOp->p4.pTab!=0 );
+ zDb = db->aDb[pC->iDb].zDbSName;
+ pTab = pOp->p4.pTab;
+ if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
+ pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
+ }
+ }else{
+ zDb = 0; /* Not needed. Silence a compiler warning. */
+ pTab = 0; /* Not needed. Silence a compiler warning. */
+ }
+
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+ /* Invoke the pre-update-hook if required. */
+ if( db->xPreUpdateCallback && pOp->p4.pTab ){
+ assert( !(opflags & OPFLAG_ISUPDATE)
+ || HasRowid(pTab)==0
+ || (aMem[pOp->p3].flags & MEM_Int)
+ );
+ sqlite3VdbePreUpdateHook(p, pC,
+ (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
+ zDb, pTab, pC->movetoTarget,
+ pOp->p3
+ );
+ }
+ if( opflags & OPFLAG_ISNOOP ) break;
+#endif
+
+ /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
+ assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
+ assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
+ assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
+
+#ifdef SQLITE_DEBUG
+ if( p->pFrame==0 ){
+ if( pC->isEphemeral==0
+ && (pOp->p5 & OPFLAG_AUXDELETE)==0
+ && (pC->wrFlag & OPFLAG_FORDELETE)==0
+ ){
+ nExtraDelete++;
+ }
+ if( pOp->p2 & OPFLAG_NCHANGE ){
+ nExtraDelete--;
+ }
+ }
+#endif
+
+ rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
+ pC->cacheStatus = CACHE_STALE;
+ pC->seekResult = 0;
+ if( rc ) goto abort_due_to_error;
+
+ /* Invoke the update-hook if required. */
+ if( opflags & OPFLAG_NCHANGE ){
+ p->nChange++;
+ if( db->xUpdateCallback && HasRowid(pTab) ){
+ db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
+ pC->movetoTarget);
+ assert( pC->iDb>=0 );
+ }
+ }
+
+ break;
+}
+/* Opcode: ResetCount * * * * *
+**
+** The value of the change counter is copied to the database handle
+** change counter (returned by subsequent calls to sqlite3_changes()).
+** Then the VMs internal change counter resets to 0.
+** This is used by trigger programs.
+*/
+case OP_ResetCount: {
+ sqlite3VdbeSetChanges(db, p->nChange);
+ p->nChange = 0;
+ break;
+}
+
+/* Opcode: SorterCompare P1 P2 P3 P4
+** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
+**
+** P1 is a sorter cursor. This instruction compares a prefix of the
+** record blob in register P3 against a prefix of the entry that
+** the sorter cursor currently points to. Only the first P4 fields
+** of r[P3] and the sorter record are compared.
+**
+** If either P3 or the sorter contains a NULL in one of their significant
+** fields (not counting the P4 fields at the end which are ignored) then
+** the comparison is assumed to be equal.
+**
+** Fall through to next instruction if the two records compare equal to
+** each other. Jump to P2 if they are different.
+*/
+case OP_SorterCompare: {
+ VdbeCursor *pC;
+ int res;
+ int nKeyCol;
+
+ pC = p->apCsr[pOp->p1];
+ assert( isSorter(pC) );
+ assert( pOp->p4type==P4_INT32 );
+ pIn3 = &aMem[pOp->p3];
+ nKeyCol = pOp->p4.i;
+ res = 0;
+ rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
+ VdbeBranchTaken(res!=0,2);
+ if( rc ) goto abort_due_to_error;
+ if( res ) goto jump_to_p2;
+ break;
+};
+
+/* Opcode: SorterData P1 P2 P3 * *
+** Synopsis: r[P2]=data
+**
+** Write into register P2 the current sorter data for sorter cursor P1.
+** Then clear the column header cache on cursor P3.
+**
+** This opcode is normally use to move a record out of the sorter and into
+** a register that is the source for a pseudo-table cursor created using
+** OpenPseudo. That pseudo-table cursor is the one that is identified by
+** parameter P3. Clearing the P3 column cache as part of this opcode saves
+** us from having to issue a separate NullRow instruction to clear that cache.
+*/
+case OP_SorterData: {
+ VdbeCursor *pC;
+
+ pOut = &aMem[pOp->p2];
+ pC = p->apCsr[pOp->p1];
+ assert( isSorter(pC) );
+ rc = sqlite3VdbeSorterRowkey(pC, pOut);
+ assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ if( rc ) goto abort_due_to_error;
+ p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
+ break;
+}
+
+/* Opcode: RowData P1 P2 P3 * *
+** Synopsis: r[P2]=data
+**
+** Write into register P2 the complete row content for the row at
+** which cursor P1 is currently pointing.
+** There is no interpretation of the data.
+** It is just copied onto the P2 register exactly as
+** it is found in the database file.
+**
+** If cursor P1 is an index, then the content is the key of the row.
+** If cursor P2 is a table, then the content extracted is the data.
+**
+** If the P1 cursor must be pointing to a valid row (not a NULL row)
+** of a real table, not a pseudo-table.
+**
+** If P3!=0 then this opcode is allowed to make an ephemeral pointer
+** into the database page. That means that the content of the output
+** register will be invalidated as soon as the cursor moves - including
+** moves caused by other cursors that "save" the current cursors
+** position in order that they can write to the same table. If P3==0
+** then a copy of the data is made into memory. P3!=0 is faster, but
+** P3==0 is safer.
+**
+** If P3!=0 then the content of the P2 register is unsuitable for use
+** in OP_Result and any OP_Result will invalidate the P2 register content.
+** The P2 register content is invalidated by opcodes like OP_Function or
+** by any use of another cursor pointing to the same table.
+*/
+case OP_RowData: {
+ VdbeCursor *pC;
+ BtCursor *pCrsr;
+ u32 n;
+
+ pOut = out2Prerelease(p, pOp);
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( pC->eCurType==CURTYPE_BTREE );
+ assert( isSorter(pC)==0 );
+ assert( pC->nullRow==0 );
+ assert( pC->uc.pCursor!=0 );
+ pCrsr = pC->uc.pCursor;
+
+ /* The OP_RowData opcodes always follow OP_NotExists or
+ ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
+ ** that might invalidate the cursor.
+ ** If this where not the case, on of the following assert()s
+ ** would fail. Should this ever change (because of changes in the code
+ ** generator) then the fix would be to insert a call to
+ ** sqlite3VdbeCursorMoveto().
+ */
+ assert( pC->deferredMoveto==0 );
+ assert( sqlite3BtreeCursorIsValid(pCrsr) );
+
+ n = sqlite3BtreePayloadSize(pCrsr);
+ if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
+ goto too_big;
+ }
+ testcase( n==0 );
+ rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut);
+ if( rc ) goto abort_due_to_error;
+ if( !pOp->p3 ) Deephemeralize(pOut);
+ UPDATE_MAX_BLOBSIZE(pOut);
+ REGISTER_TRACE(pOp->p2, pOut);
+ break;
+}
+
+/* Opcode: Rowid P1 P2 * * *
+** Synopsis: r[P2]=rowid
+**
+** Store in register P2 an integer which is the key of the table entry that
+** P1 is currently point to.
+**
+** P1 can be either an ordinary table or a virtual table. There used to
+** be a separate OP_VRowid opcode for use with virtual tables, but this
+** one opcode now works for both table types.
+*/
+case OP_Rowid: { /* out2 */
+ VdbeCursor *pC;
+ i64 v;
+ sqlite3_vtab *pVtab;
+ const sqlite3_module *pModule;
+
+ pOut = out2Prerelease(p, pOp);
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
+ if( pC->nullRow ){
+ pOut->flags = MEM_Null;
+ break;
+ }else if( pC->deferredMoveto ){
+ v = pC->movetoTarget;
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ }else if( pC->eCurType==CURTYPE_VTAB ){
+ assert( pC->uc.pVCur!=0 );
+ pVtab = pC->uc.pVCur->pVtab;
+ pModule = pVtab->pModule;
+ assert( pModule->xRowid );
+ rc = pModule->xRowid(pC->uc.pVCur, &v);
+ sqlite3VtabImportErrmsg(p, pVtab);
+ if( rc ) goto abort_due_to_error;
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+ }else{
+ assert( pC->eCurType==CURTYPE_BTREE );
+ assert( pC->uc.pCursor!=0 );
+ rc = sqlite3VdbeCursorRestore(pC);
+ if( rc ) goto abort_due_to_error;
+ if( pC->nullRow ){
+ pOut->flags = MEM_Null;
+ break;
+ }
+ v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
+ }
+ pOut->u.i = v;
+ break;
+}
+
+/* Opcode: NullRow P1 * * * *
+**
+** Move the cursor P1 to a null row. Any OP_Column operations
+** that occur while the cursor is on the null row will always
+** write a NULL.
+*/
+case OP_NullRow: {
+ VdbeCursor *pC;
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ pC->nullRow = 1;
+ pC->cacheStatus = CACHE_STALE;
+ if( pC->eCurType==CURTYPE_BTREE ){
+ assert( pC->uc.pCursor!=0 );
+ sqlite3BtreeClearCursor(pC->uc.pCursor);
+ }
+#ifdef SQLITE_DEBUG
+ if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
+#endif
+ break;
+}
+
+/* Opcode: SeekEnd P1 * * * *
+**
+** Position cursor P1 at the end of the btree for the purpose of
+** appending a new entry onto the btree.
+**
+** It is assumed that the cursor is used only for appending and so
+** if the cursor is valid, then the cursor must already be pointing
+** at the end of the btree and so no changes are made to
+** the cursor.
+*/
+/* Opcode: Last P1 P2 * * *
+**
+** The next use of the Rowid or Column or Prev instruction for P1
+** will refer to the last entry in the database table or index.
+** If the table or index is empty and P2>0, then jump immediately to P2.
+** If P2 is 0 or if the table or index is not empty, fall through
+** to the following instruction.
+**
+** This opcode leaves the cursor configured to move in reverse order,
+** from the end toward the beginning. In other words, the cursor is
+** configured to use Prev, not Next.
+*/
+case OP_SeekEnd:
+case OP_Last: { /* jump */
+ VdbeCursor *pC;
+ BtCursor *pCrsr;
+ int res;
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( pC->eCurType==CURTYPE_BTREE );
+ pCrsr = pC->uc.pCursor;
+ res = 0;
+ assert( pCrsr!=0 );
+#ifdef SQLITE_DEBUG
+ pC->seekOp = pOp->opcode;
+#endif
+ if( pOp->opcode==OP_SeekEnd ){
+ assert( pOp->p2==0 );
+ pC->seekResult = -1;
+ if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
+ break;
+ }
+ }
+ rc = sqlite3BtreeLast(pCrsr, &res);
+ pC->nullRow = (u8)res;
+ pC->deferredMoveto = 0;
+ pC->cacheStatus = CACHE_STALE;
+ if( rc ) goto abort_due_to_error;
+ if( pOp->p2>0 ){
+ VdbeBranchTaken(res!=0,2);
+ if( res ) goto jump_to_p2;
+ }
+ break;
+}
+
+/* Opcode: IfSmaller P1 P2 P3 * *
+**
+** Estimate the number of rows in the table P1. Jump to P2 if that
+** estimate is less than approximately 2**(0.1*P3).
+*/
+case OP_IfSmaller: { /* jump */
+ VdbeCursor *pC;
+ BtCursor *pCrsr;
+ int res;
+ i64 sz;
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ pCrsr = pC->uc.pCursor;
+ assert( pCrsr );
+ rc = sqlite3BtreeFirst(pCrsr, &res);
+ if( rc ) goto abort_due_to_error;
+ if( res==0 ){
+ sz = sqlite3BtreeRowCountEst(pCrsr);
+ if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
+ }
+ VdbeBranchTaken(res!=0,2);
+ if( res ) goto jump_to_p2;
+ break;
+}
+
+
+/* Opcode: SorterSort P1 P2 * * *
+**
+** After all records have been inserted into the Sorter object
+** identified by P1, invoke this opcode to actually do the sorting.
+** Jump to P2 if there are no records to be sorted.
+**
+** This opcode is an alias for OP_Sort and OP_Rewind that is used
+** for Sorter objects.
+*/
+/* Opcode: Sort P1 P2 * * *
+**
+** This opcode does exactly the same thing as OP_Rewind except that
+** it increments an undocumented global variable used for testing.
+**
+** Sorting is accomplished by writing records into a sorting index,
+** then rewinding that index and playing it back from beginning to
+** end. We use the OP_Sort opcode instead of OP_Rewind to do the
+** rewinding so that the global variable will be incremented and
+** regression tests can determine whether or not the optimizer is
+** correctly optimizing out sorts.
+*/
+case OP_SorterSort: /* jump */
+case OP_Sort: { /* jump */
+#ifdef SQLITE_TEST
+ sqlite3_sort_count++;
+ sqlite3_search_count--;
+#endif
+ p->aCounter[SQLITE_STMTSTATUS_SORT]++;
+ /* Fall through into OP_Rewind */
+ /* no break */ deliberate_fall_through
+}
+/* Opcode: Rewind P1 P2 * * *
+**
+** The next use of the Rowid or Column or Next instruction for P1
+** will refer to the first entry in the database table or index.
+** If the table or index is empty, jump immediately to P2.
+** If the table or index is not empty, fall through to the following
+** instruction.
+**
+** This opcode leaves the cursor configured to move in forward order,
+** from the beginning toward the end. In other words, the cursor is
+** configured to use Next, not Prev.
+*/
+case OP_Rewind: { /* jump */
+ VdbeCursor *pC;
+ BtCursor *pCrsr;
+ int res;
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ assert( pOp->p5==0 );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
+ res = 1;
+#ifdef SQLITE_DEBUG
+ pC->seekOp = OP_Rewind;
+#endif
+ if( isSorter(pC) ){
+ rc = sqlite3VdbeSorterRewind(pC, &res);
+ }else{
+ assert( pC->eCurType==CURTYPE_BTREE );
+ pCrsr = pC->uc.pCursor;
+ assert( pCrsr );
+ rc = sqlite3BtreeFirst(pCrsr, &res);
+ pC->deferredMoveto = 0;
+ pC->cacheStatus = CACHE_STALE;
+ }
+ if( rc ) goto abort_due_to_error;
+ pC->nullRow = (u8)res;
+ assert( pOp->p2>0 && pOp->p2<p->nOp );
+ VdbeBranchTaken(res!=0,2);
+ if( res ) goto jump_to_p2;
+ break;
+}
+
+/* Opcode: Next P1 P2 P3 P4 P5
+**
+** Advance cursor P1 so that it points to the next key/data pair in its
+** table or index. If there are no more key/value pairs then fall through
+** to the following instruction. But if the cursor advance was successful,
+** jump immediately to P2.
+**
+** The Next opcode is only valid following an SeekGT, SeekGE, or
+** OP_Rewind opcode used to position the cursor. Next is not allowed
+** to follow SeekLT, SeekLE, or OP_Last.
+**
+** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
+** been opened prior to this opcode or the program will segfault.
+**
+** The P3 value is a hint to the btree implementation. If P3==1, that
+** means P1 is an SQL index and that this instruction could have been
+** omitted if that index had been unique. P3 is usually 0. P3 is
+** always either 0 or 1.
+**
+** P4 is always of type P4_ADVANCE. The function pointer points to
+** sqlite3BtreeNext().
+**
+** If P5 is positive and the jump is taken, then event counter
+** number P5-1 in the prepared statement is incremented.
+**
+** See also: Prev
+*/
+/* Opcode: Prev P1 P2 P3 P4 P5
+**
+** Back up cursor P1 so that it points to the previous key/data pair in its
+** table or index. If there is no previous key/value pairs then fall through
+** to the following instruction. But if the cursor backup was successful,
+** jump immediately to P2.
+**
+**
+** The Prev opcode is only valid following an SeekLT, SeekLE, or
+** OP_Last opcode used to position the cursor. Prev is not allowed
+** to follow SeekGT, SeekGE, or OP_Rewind.
+**
+** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
+** not open then the behavior is undefined.
+**
+** The P3 value is a hint to the btree implementation. If P3==1, that
+** means P1 is an SQL index and that this instruction could have been
+** omitted if that index had been unique. P3 is usually 0. P3 is
+** always either 0 or 1.
+**
+** P4 is always of type P4_ADVANCE. The function pointer points to
+** sqlite3BtreePrevious().
+**
+** If P5 is positive and the jump is taken, then event counter
+** number P5-1 in the prepared statement is incremented.
+*/
+/* Opcode: SorterNext P1 P2 * * P5
+**
+** This opcode works just like OP_Next except that P1 must be a
+** sorter object for which the OP_SorterSort opcode has been
+** invoked. This opcode advances the cursor to the next sorted
+** record, or jumps to P2 if there are no more sorted records.
+*/
+case OP_SorterNext: { /* jump */
+ VdbeCursor *pC;
+
+ pC = p->apCsr[pOp->p1];
+ assert( isSorter(pC) );
+ rc = sqlite3VdbeSorterNext(db, pC);
+ goto next_tail;
+case OP_Prev: /* jump */
+case OP_Next: /* jump */
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ assert( pOp->p5<ArraySize(p->aCounter) );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( pC->deferredMoveto==0 );
+ assert( pC->eCurType==CURTYPE_BTREE );
+ assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
+ assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
+
+ /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found.
+ ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
+ assert( pOp->opcode!=OP_Next
+ || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
+ || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
+ || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid
+ || pC->seekOp==OP_IfNoHope);
+ assert( pOp->opcode!=OP_Prev
+ || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
+ || pC->seekOp==OP_Last || pC->seekOp==OP_IfNoHope
+ || pC->seekOp==OP_NullRow);
+
+ rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
+next_tail:
+ pC->cacheStatus = CACHE_STALE;
+ VdbeBranchTaken(rc==SQLITE_OK,2);
+ if( rc==SQLITE_OK ){
+ pC->nullRow = 0;
+ p->aCounter[pOp->p5]++;
+#ifdef SQLITE_TEST
+ sqlite3_search_count++;
+#endif
+ goto jump_to_p2_and_check_for_interrupt;
+ }
+ if( rc!=SQLITE_DONE ) goto abort_due_to_error;
+ rc = SQLITE_OK;
+ pC->nullRow = 1;
+ goto check_for_interrupt;
+}
+
+/* Opcode: IdxInsert P1 P2 P3 P4 P5
+** Synopsis: key=r[P2]
+**
+** Register P2 holds an SQL index key made using the
+** MakeRecord instructions. This opcode writes that key
+** into the index P1. Data for the entry is nil.
+**
+** If P4 is not zero, then it is the number of values in the unpacked
+** key of reg(P2). In that case, P3 is the index of the first register
+** for the unpacked key. The availability of the unpacked key can sometimes
+** be an optimization.
+**
+** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
+** that this insert is likely to be an append.
+**
+** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
+** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
+** then the change counter is unchanged.
+**
+** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
+** run faster by avoiding an unnecessary seek on cursor P1. However,
+** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
+** seeks on the cursor or if the most recent seek used a key equivalent
+** to P2.
+**
+** This instruction only works for indices. The equivalent instruction
+** for tables is OP_Insert.
+*/
+case OP_IdxInsert: { /* in2 */
+ VdbeCursor *pC;
+ BtreePayload x;
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ sqlite3VdbeIncrWriteCounter(p, pC);
+ assert( pC!=0 );
+ assert( !isSorter(pC) );
+ pIn2 = &aMem[pOp->p2];
+ assert( pIn2->flags & MEM_Blob );
+ if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
+ assert( pC->eCurType==CURTYPE_BTREE );
+ assert( pC->isTable==0 );
+ rc = ExpandBlob(pIn2);
+ if( rc ) goto abort_due_to_error;
+ x.nKey = pIn2->n;
+ x.pKey = pIn2->z;
+ x.aMem = aMem + pOp->p3;
+ x.nMem = (u16)pOp->p4.i;
+ rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
+ (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
+ ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
+ );
+ assert( pC->deferredMoveto==0 );
+ pC->cacheStatus = CACHE_STALE;
+ if( rc) goto abort_due_to_error;
+ break;
+}
+
+/* Opcode: SorterInsert P1 P2 * * *
+** Synopsis: key=r[P2]
+**
+** Register P2 holds an SQL index key made using the
+** MakeRecord instructions. This opcode writes that key
+** into the sorter P1. Data for the entry is nil.
+*/
+case OP_SorterInsert: { /* in2 */
+ VdbeCursor *pC;
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ sqlite3VdbeIncrWriteCounter(p, pC);
+ assert( pC!=0 );
+ assert( isSorter(pC) );
+ pIn2 = &aMem[pOp->p2];
+ assert( pIn2->flags & MEM_Blob );
+ assert( pC->isTable==0 );
+ rc = ExpandBlob(pIn2);
+ if( rc ) goto abort_due_to_error;
+ rc = sqlite3VdbeSorterWrite(pC, pIn2);
+ if( rc) goto abort_due_to_error;
+ break;
+}
+
+/* Opcode: IdxDelete P1 P2 P3 * P5
+** Synopsis: key=r[P2@P3]
+**
+** The content of P3 registers starting at register P2 form
+** an unpacked index key. This opcode removes that entry from the
+** index opened by cursor P1.
+**
+** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
+** if no matching index entry is found. This happens when running
+** an UPDATE or DELETE statement and the index entry to be updated
+** or deleted is not found. For some uses of IdxDelete
+** (example: the EXCEPT operator) it does not matter that no matching
+** entry is found. For those cases, P5 is zero.
+*/
+case OP_IdxDelete: {
+ VdbeCursor *pC;
+ BtCursor *pCrsr;
+ int res;
+ UnpackedRecord r;
+
+ assert( pOp->p3>0 );
+ assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( pC->eCurType==CURTYPE_BTREE );
+ sqlite3VdbeIncrWriteCounter(p, pC);
+ pCrsr = pC->uc.pCursor;
+ assert( pCrsr!=0 );
+ r.pKeyInfo = pC->pKeyInfo;
+ r.nField = (u16)pOp->p3;
+ r.default_rc = 0;
+ r.aMem = &aMem[pOp->p2];
+ rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
+ if( rc ) goto abort_due_to_error;
+ if( res==0 ){
+ rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
+ if( rc ) goto abort_due_to_error;
+ }else if( pOp->p5 ){
+ rc = SQLITE_CORRUPT_INDEX;
+ goto abort_due_to_error;
+ }
+ assert( pC->deferredMoveto==0 );
+ pC->cacheStatus = CACHE_STALE;
+ pC->seekResult = 0;
+ break;
+}
+
+/* Opcode: DeferredSeek P1 * P3 P4 *
+** Synopsis: Move P3 to P1.rowid if needed
+**
+** P1 is an open index cursor and P3 is a cursor on the corresponding
+** table. This opcode does a deferred seek of the P3 table cursor
+** to the row that corresponds to the current row of P1.
+**
+** This is a deferred seek. Nothing actually happens until
+** the cursor is used to read a record. That way, if no reads
+** occur, no unnecessary I/O happens.
+**
+** P4 may be an array of integers (type P4_INTARRAY) containing
+** one entry for each column in the P3 table. If array entry a(i)
+** is non-zero, then reading column a(i)-1 from cursor P3 is
+** equivalent to performing the deferred seek and then reading column i
+** from P1. This information is stored in P3 and used to redirect
+** reads against P3 over to P1, thus possibly avoiding the need to
+** seek and read cursor P3.
+*/
+/* Opcode: IdxRowid P1 P2 * * *
+** Synopsis: r[P2]=rowid
+**
+** Write into register P2 an integer which is the last entry in the record at
+** the end of the index key pointed to by cursor P1. This integer should be
+** the rowid of the table entry to which this index entry points.
+**
+** See also: Rowid, MakeRecord.
+*/
+case OP_DeferredSeek:
+case OP_IdxRowid: { /* out2 */
+ VdbeCursor *pC; /* The P1 index cursor */
+ VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
+ i64 rowid; /* Rowid that P1 current points to */
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( pC->eCurType==CURTYPE_BTREE );
+ assert( pC->uc.pCursor!=0 );
+ assert( pC->isTable==0 );
+ assert( pC->deferredMoveto==0 );
+ assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
+
+ /* The IdxRowid and Seek opcodes are combined because of the commonality
+ ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
+ rc = sqlite3VdbeCursorRestore(pC);
+
+ /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
+ ** out from under the cursor. That will never happens for an IdxRowid
+ ** or Seek opcode */
+ if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
+
+ if( !pC->nullRow ){
+ rowid = 0; /* Not needed. Only used to silence a warning. */
+ rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
+ if( rc!=SQLITE_OK ){
+ goto abort_due_to_error;
+ }
+ if( pOp->opcode==OP_DeferredSeek ){
+ assert( pOp->p3>=0 && pOp->p3<p->nCursor );
+ pTabCur = p->apCsr[pOp->p3];
+ assert( pTabCur!=0 );
+ assert( pTabCur->eCurType==CURTYPE_BTREE );
+ assert( pTabCur->uc.pCursor!=0 );
+ assert( pTabCur->isTable );
+ pTabCur->nullRow = 0;
+ pTabCur->movetoTarget = rowid;
+ pTabCur->deferredMoveto = 1;
+ assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
+ pTabCur->aAltMap = pOp->p4.ai;
+ pTabCur->pAltCursor = pC;
+ }else{
+ pOut = out2Prerelease(p, pOp);
+ pOut->u.i = rowid;
+ }
+ }else{
+ assert( pOp->opcode==OP_IdxRowid );
+ sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
+ }
+ break;
+}
+
+/* Opcode: FinishSeek P1 * * * *
+**
+** If cursor P1 was previously moved via OP_DeferredSeek, complete that
+** seek operation now, without further delay. If the cursor seek has
+** already occurred, this instruction is a no-op.
+*/
+case OP_FinishSeek: {
+ VdbeCursor *pC; /* The P1 index cursor */
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ if( pC->deferredMoveto ){
+ rc = sqlite3VdbeFinishMoveto(pC);
+ if( rc ) goto abort_due_to_error;
+ }
+ break;
+}
+
+/* Opcode: IdxGE P1 P2 P3 P4 *
+** Synopsis: key=r[P3@P4]
+**
+** The P4 register values beginning with P3 form an unpacked index
+** key that omits the PRIMARY KEY. Compare this key value against the index
+** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
+** fields at the end.
+**
+** If the P1 index entry is greater than or equal to the key value
+** then jump to P2. Otherwise fall through to the next instruction.
+*/
+/* Opcode: IdxGT P1 P2 P3 P4 *
+** Synopsis: key=r[P3@P4]
+**
+** The P4 register values beginning with P3 form an unpacked index
+** key that omits the PRIMARY KEY. Compare this key value against the index
+** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
+** fields at the end.
+**
+** If the P1 index entry is greater than the key value
+** then jump to P2. Otherwise fall through to the next instruction.
+*/
+/* Opcode: IdxLT P1 P2 P3 P4 *
+** Synopsis: key=r[P3@P4]
+**
+** The P4 register values beginning with P3 form an unpacked index
+** key that omits the PRIMARY KEY or ROWID. Compare this key value against
+** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
+** ROWID on the P1 index.
+**
+** If the P1 index entry is less than the key value then jump to P2.
+** Otherwise fall through to the next instruction.
+*/
+/* Opcode: IdxLE P1 P2 P3 P4 *
+** Synopsis: key=r[P3@P4]
+**
+** The P4 register values beginning with P3 form an unpacked index
+** key that omits the PRIMARY KEY or ROWID. Compare this key value against
+** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
+** ROWID on the P1 index.
+**
+** If the P1 index entry is less than or equal to the key value then jump
+** to P2. Otherwise fall through to the next instruction.
+*/
+case OP_IdxLE: /* jump */
+case OP_IdxGT: /* jump */
+case OP_IdxLT: /* jump */
+case OP_IdxGE: { /* jump */
+ VdbeCursor *pC;
+ int res;
+ UnpackedRecord r;
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( pC->isOrdered );
+ assert( pC->eCurType==CURTYPE_BTREE );
+ assert( pC->uc.pCursor!=0);
+ assert( pC->deferredMoveto==0 );
+ assert( pOp->p4type==P4_INT32 );
+ r.pKeyInfo = pC->pKeyInfo;
+ r.nField = (u16)pOp->p4.i;
+ if( pOp->opcode<OP_IdxLT ){
+ assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
+ r.default_rc = -1;
+ }else{
+ assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
+ r.default_rc = 0;
+ }
+ r.aMem = &aMem[pOp->p3];
+#ifdef SQLITE_DEBUG
+ {
+ int i;
+ for(i=0; i<r.nField; i++){
+ assert( memIsValid(&r.aMem[i]) );
+ REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
+ }
+ }
+#endif
+
+ /* Inlined version of sqlite3VdbeIdxKeyCompare() */
+ {
+ i64 nCellKey = 0;
+ BtCursor *pCur;
+ Mem m;
+
+ assert( pC->eCurType==CURTYPE_BTREE );
+ pCur = pC->uc.pCursor;
+ assert( sqlite3BtreeCursorIsValid(pCur) );
+ nCellKey = sqlite3BtreePayloadSize(pCur);
+ /* nCellKey will always be between 0 and 0xffffffff because of the way
+ ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
+ if( nCellKey<=0 || nCellKey>0x7fffffff ){
+ rc = SQLITE_CORRUPT_BKPT;
+ goto abort_due_to_error;
+ }
+ sqlite3VdbeMemInit(&m, db, 0);
+ rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
+ if( rc ) goto abort_due_to_error;
+ res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, &r, 0);
+ sqlite3VdbeMemRelease(&m);
+ }
+ /* End of inlined sqlite3VdbeIdxKeyCompare() */
+
+ assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
+ if( (pOp->opcode&1)==(OP_IdxLT&1) ){
+ assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
+ res = -res;
+ }else{
+ assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
+ res++;
+ }
+ VdbeBranchTaken(res>0,2);
+ assert( rc==SQLITE_OK );
+ if( res>0 ) goto jump_to_p2;
+ break;
+}
+
+/* Opcode: Destroy P1 P2 P3 * *
+**
+** Delete an entire database table or index whose root page in the database
+** file is given by P1.
+**
+** The table being destroyed is in the main database file if P3==0. If
+** P3==1 then the table to be clear is in the auxiliary database file
+** that is used to store tables create using CREATE TEMPORARY TABLE.
+**
+** If AUTOVACUUM is enabled then it is possible that another root page
+** might be moved into the newly deleted root page in order to keep all
+** root pages contiguous at the beginning of the database. The former
+** value of the root page that moved - its value before the move occurred -
+** is stored in register P2. If no page movement was required (because the
+** table being dropped was already the last one in the database) then a
+** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
+** is stored in register P2.
+**
+** This opcode throws an error if there are any active reader VMs when
+** it is invoked. This is done to avoid the difficulty associated with
+** updating existing cursors when a root page is moved in an AUTOVACUUM
+** database. This error is thrown even if the database is not an AUTOVACUUM
+** db in order to avoid introducing an incompatibility between autovacuum
+** and non-autovacuum modes.
+**
+** See also: Clear
+*/
+case OP_Destroy: { /* out2 */
+ int iMoved;
+ int iDb;
+
+ sqlite3VdbeIncrWriteCounter(p, 0);
+ assert( p->readOnly==0 );
+ assert( pOp->p1>1 );
+ pOut = out2Prerelease(p, pOp);
+ pOut->flags = MEM_Null;
+ if( db->nVdbeRead > db->nVDestroy+1 ){
+ rc = SQLITE_LOCKED;
+ p->errorAction = OE_Abort;
+ goto abort_due_to_error;
+ }else{
+ iDb = pOp->p3;
+ assert( DbMaskTest(p->btreeMask, iDb) );
+ iMoved = 0; /* Not needed. Only to silence a warning. */
+ rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
+ pOut->flags = MEM_Int;
+ pOut->u.i = iMoved;
+ if( rc ) goto abort_due_to_error;
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ if( iMoved!=0 ){
+ sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
+ /* All OP_Destroy operations occur on the same btree */
+ assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
+ resetSchemaOnFault = iDb+1;
+ }
+#endif
+ }
+ break;
+}
+
+/* Opcode: Clear P1 P2 P3
+**
+** Delete all contents of the database table or index whose root page
+** in the database file is given by P1. But, unlike Destroy, do not
+** remove the table or index from the database file.
+**
+** The table being clear is in the main database file if P2==0. If
+** P2==1 then the table to be clear is in the auxiliary database file
+** that is used to store tables create using CREATE TEMPORARY TABLE.
+**
+** If the P3 value is non-zero, then the table referred to must be an
+** intkey table (an SQL table, not an index). In this case the row change
+** count is incremented by the number of rows in the table being cleared.
+** If P3 is greater than zero, then the value stored in register P3 is
+** also incremented by the number of rows in the table being cleared.
+**
+** See also: Destroy
+*/
+case OP_Clear: {
+ int nChange;
+
+ sqlite3VdbeIncrWriteCounter(p, 0);
+ nChange = 0;
+ assert( p->readOnly==0 );
+ assert( DbMaskTest(p->btreeMask, pOp->p2) );
+ rc = sqlite3BtreeClearTable(
+ db->aDb[pOp->p2].pBt, (u32)pOp->p1, (pOp->p3 ? &nChange : 0)
+ );
+ if( pOp->p3 ){
+ p->nChange += nChange;
+ if( pOp->p3>0 ){
+ assert( memIsValid(&aMem[pOp->p3]) );
+ memAboutToChange(p, &aMem[pOp->p3]);
+ aMem[pOp->p3].u.i += nChange;
+ }
+ }
+ if( rc ) goto abort_due_to_error;
+ break;
+}
+
+/* Opcode: ResetSorter P1 * * * *
+**
+** Delete all contents from the ephemeral table or sorter
+** that is open on cursor P1.
+**
+** This opcode only works for cursors used for sorting and
+** opened with OP_OpenEphemeral or OP_SorterOpen.
+*/
+case OP_ResetSorter: {
+ VdbeCursor *pC;
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ if( isSorter(pC) ){
+ sqlite3VdbeSorterReset(db, pC->uc.pSorter);
+ }else{
+ assert( pC->eCurType==CURTYPE_BTREE );
+ assert( pC->isEphemeral );
+ rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
+ if( rc ) goto abort_due_to_error;
+ }
+ break;
+}
+
+/* Opcode: CreateBtree P1 P2 P3 * *
+** Synopsis: r[P2]=root iDb=P1 flags=P3
+**
+** Allocate a new b-tree in the main database file if P1==0 or in the
+** TEMP database file if P1==1 or in an attached database if
+** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
+** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
+** The root page number of the new b-tree is stored in register P2.
+*/
+case OP_CreateBtree: { /* out2 */
+ Pgno pgno;
+ Db *pDb;
+
+ sqlite3VdbeIncrWriteCounter(p, 0);
+ pOut = out2Prerelease(p, pOp);
+ pgno = 0;
+ assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
+ assert( pOp->p1>=0 && pOp->p1<db->nDb );
+ assert( DbMaskTest(p->btreeMask, pOp->p1) );
+ assert( p->readOnly==0 );
+ pDb = &db->aDb[pOp->p1];
+ assert( pDb->pBt!=0 );
+ rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
+ if( rc ) goto abort_due_to_error;
+ pOut->u.i = pgno;
+ break;
+}
+
+/* Opcode: SqlExec * * * P4 *
+**
+** Run the SQL statement or statements specified in the P4 string.
+*/
+case OP_SqlExec: {
+ sqlite3VdbeIncrWriteCounter(p, 0);
+ db->nSqlExec++;
+ rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
+ db->nSqlExec--;
+ if( rc ) goto abort_due_to_error;
+ break;
+}
+
+/* Opcode: ParseSchema P1 * * P4 *
+**
+** Read and parse all entries from the schema table of database P1
+** that match the WHERE clause P4. If P4 is a NULL pointer, then the
+** entire schema for P1 is reparsed.
+**
+** This opcode invokes the parser to create a new virtual machine,
+** then runs the new virtual machine. It is thus a re-entrant opcode.
+*/
+case OP_ParseSchema: {
+ int iDb;
+ const char *zSchema;
+ char *zSql;
+ InitData initData;
+
+ /* Any prepared statement that invokes this opcode will hold mutexes
+ ** on every btree. This is a prerequisite for invoking
+ ** sqlite3InitCallback().
+ */
+#ifdef SQLITE_DEBUG
+ for(iDb=0; iDb<db->nDb; iDb++){
+ assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
+ }
+#endif
+
+ iDb = pOp->p1;
+ assert( iDb>=0 && iDb<db->nDb );
+ assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
+
+#ifndef SQLITE_OMIT_ALTERTABLE
+ if( pOp->p4.z==0 ){
+ sqlite3SchemaClear(db->aDb[iDb].pSchema);
+ db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
+ rc = sqlite3InitOne(db, iDb, &p->zErrMsg, INITFLAG_AlterTable);
+ db->mDbFlags |= DBFLAG_SchemaChange;
+ p->expired = 0;
+ }else
+#endif
+ {
+ zSchema = DFLT_SCHEMA_TABLE;
+ initData.db = db;
+ initData.iDb = iDb;
+ initData.pzErrMsg = &p->zErrMsg;
+ initData.mInitFlags = 0;
+ initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt);
+ zSql = sqlite3MPrintf(db,
+ "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid",
+ db->aDb[iDb].zDbSName, zSchema, pOp->p4.z);
+ if( zSql==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ }else{
+ assert( db->init.busy==0 );
+ db->init.busy = 1;
+ initData.rc = SQLITE_OK;
+ initData.nInitRow = 0;
+ assert( !db->mallocFailed );
+ rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
+ if( rc==SQLITE_OK ) rc = initData.rc;
+ if( rc==SQLITE_OK && initData.nInitRow==0 ){
+ /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
+ ** at least one SQL statement. Any less than that indicates that
+ ** the sqlite_schema table is corrupt. */
+ rc = SQLITE_CORRUPT_BKPT;
+ }
+ sqlite3DbFreeNN(db, zSql);
+ db->init.busy = 0;
+ }
+ }
+ if( rc ){
+ sqlite3ResetAllSchemasOfConnection(db);
+ if( rc==SQLITE_NOMEM ){
+ goto no_mem;
+ }
+ goto abort_due_to_error;
+ }
+ break;
+}
+
+#if !defined(SQLITE_OMIT_ANALYZE)
+/* Opcode: LoadAnalysis P1 * * * *
+**
+** Read the sqlite_stat1 table for database P1 and load the content
+** of that table into the internal index hash table. This will cause
+** the analysis to be used when preparing all subsequent queries.
+*/
+case OP_LoadAnalysis: {
+ assert( pOp->p1>=0 && pOp->p1<db->nDb );
+ rc = sqlite3AnalysisLoad(db, pOp->p1);
+ if( rc ) goto abort_due_to_error;
+ break;
+}
+#endif /* !defined(SQLITE_OMIT_ANALYZE) */
+
+/* Opcode: DropTable P1 * * P4 *
+**
+** Remove the internal (in-memory) data structures that describe
+** the table named P4 in database P1. This is called after a table
+** is dropped from disk (using the Destroy opcode) in order to keep
+** the internal representation of the
+** schema consistent with what is on disk.
+*/
+case OP_DropTable: {
+ sqlite3VdbeIncrWriteCounter(p, 0);
+ sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
+ break;
+}
+
+/* Opcode: DropIndex P1 * * P4 *
+**
+** Remove the internal (in-memory) data structures that describe
+** the index named P4 in database P1. This is called after an index
+** is dropped from disk (using the Destroy opcode)
+** in order to keep the internal representation of the
+** schema consistent with what is on disk.
+*/
+case OP_DropIndex: {
+ sqlite3VdbeIncrWriteCounter(p, 0);
+ sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
+ break;
+}
+
+/* Opcode: DropTrigger P1 * * P4 *
+**
+** Remove the internal (in-memory) data structures that describe
+** the trigger named P4 in database P1. This is called after a trigger
+** is dropped from disk (using the Destroy opcode) in order to keep
+** the internal representation of the
+** schema consistent with what is on disk.
+*/
+case OP_DropTrigger: {
+ sqlite3VdbeIncrWriteCounter(p, 0);
+ sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
+ break;
+}
+
+
+#ifndef SQLITE_OMIT_INTEGRITY_CHECK
+/* Opcode: IntegrityCk P1 P2 P3 P4 P5
+**
+** Do an analysis of the currently open database. Store in
+** register P1 the text of an error message describing any problems.
+** If no problems are found, store a NULL in register P1.
+**
+** The register P3 contains one less than the maximum number of allowed errors.
+** At most reg(P3) errors will be reported.
+** In other words, the analysis stops as soon as reg(P1) errors are
+** seen. Reg(P1) is updated with the number of errors remaining.
+**
+** The root page numbers of all tables in the database are integers
+** stored in P4_INTARRAY argument.
+**
+** If P5 is not zero, the check is done on the auxiliary database
+** file, not the main database file.
+**
+** This opcode is used to implement the integrity_check pragma.
+*/
+case OP_IntegrityCk: {
+ int nRoot; /* Number of tables to check. (Number of root pages.) */
+ Pgno *aRoot; /* Array of rootpage numbers for tables to be checked */
+ int nErr; /* Number of errors reported */
+ char *z; /* Text of the error report */
+ Mem *pnErr; /* Register keeping track of errors remaining */
+
+ assert( p->bIsReader );
+ nRoot = pOp->p2;
+ aRoot = pOp->p4.ai;
+ assert( nRoot>0 );
+ assert( aRoot[0]==(Pgno)nRoot );
+ assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
+ pnErr = &aMem[pOp->p3];
+ assert( (pnErr->flags & MEM_Int)!=0 );
+ assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
+ pIn1 = &aMem[pOp->p1];
+ assert( pOp->p5<db->nDb );
+ assert( DbMaskTest(p->btreeMask, pOp->p5) );
+ z = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
+ (int)pnErr->u.i+1, &nErr);
+ sqlite3VdbeMemSetNull(pIn1);
+ if( nErr==0 ){
+ assert( z==0 );
+ }else if( z==0 ){
+ goto no_mem;
+ }else{
+ pnErr->u.i -= nErr-1;
+ sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
+ }
+ UPDATE_MAX_BLOBSIZE(pIn1);
+ sqlite3VdbeChangeEncoding(pIn1, encoding);
+ goto check_for_interrupt;
+}
+#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
+
+/* Opcode: RowSetAdd P1 P2 * * *
+** Synopsis: rowset(P1)=r[P2]
+**
+** Insert the integer value held by register P2 into a RowSet object
+** held in register P1.
+**
+** An assertion fails if P2 is not an integer.
+*/
+case OP_RowSetAdd: { /* in1, in2 */
+ pIn1 = &aMem[pOp->p1];
+ pIn2 = &aMem[pOp->p2];
+ assert( (pIn2->flags & MEM_Int)!=0 );
+ if( (pIn1->flags & MEM_Blob)==0 ){
+ if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
+ }
+ assert( sqlite3VdbeMemIsRowSet(pIn1) );
+ sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
+ break;
+}
+
+/* Opcode: RowSetRead P1 P2 P3 * *
+** Synopsis: r[P3]=rowset(P1)
+**
+** Extract the smallest value from the RowSet object in P1
+** and put that value into register P3.
+** Or, if RowSet object P1 is initially empty, leave P3
+** unchanged and jump to instruction P2.
+*/
+case OP_RowSetRead: { /* jump, in1, out3 */
+ i64 val;
+
+ pIn1 = &aMem[pOp->p1];
+ assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
+ if( (pIn1->flags & MEM_Blob)==0
+ || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
+ ){
+ /* The boolean index is empty */
+ sqlite3VdbeMemSetNull(pIn1);
+ VdbeBranchTaken(1,2);
+ goto jump_to_p2_and_check_for_interrupt;
+ }else{
+ /* A value was pulled from the index */
+ VdbeBranchTaken(0,2);
+ sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
+ }
+ goto check_for_interrupt;
+}
+
+/* Opcode: RowSetTest P1 P2 P3 P4
+** Synopsis: if r[P3] in rowset(P1) goto P2
+**
+** Register P3 is assumed to hold a 64-bit integer value. If register P1
+** contains a RowSet object and that RowSet object contains
+** the value held in P3, jump to register P2. Otherwise, insert the
+** integer in P3 into the RowSet and continue on to the
+** next opcode.
+**
+** The RowSet object is optimized for the case where sets of integers
+** are inserted in distinct phases, which each set contains no duplicates.
+** Each set is identified by a unique P4 value. The first set
+** must have P4==0, the final set must have P4==-1, and for all other sets
+** must have P4>0.
+**
+** This allows optimizations: (a) when P4==0 there is no need to test
+** the RowSet object for P3, as it is guaranteed not to contain it,
+** (b) when P4==-1 there is no need to insert the value, as it will
+** never be tested for, and (c) when a value that is part of set X is
+** inserted, there is no need to search to see if the same value was
+** previously inserted as part of set X (only if it was previously
+** inserted as part of some other set).
+*/
+case OP_RowSetTest: { /* jump, in1, in3 */
+ int iSet;
+ int exists;
+
+ pIn1 = &aMem[pOp->p1];
+ pIn3 = &aMem[pOp->p3];
+ iSet = pOp->p4.i;
+ assert( pIn3->flags&MEM_Int );
+
+ /* If there is anything other than a rowset object in memory cell P1,
+ ** delete it now and initialize P1 with an empty rowset
+ */
+ if( (pIn1->flags & MEM_Blob)==0 ){
+ if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
+ }
+ assert( sqlite3VdbeMemIsRowSet(pIn1) );
+ assert( pOp->p4type==P4_INT32 );
+ assert( iSet==-1 || iSet>=0 );
+ if( iSet ){
+ exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
+ VdbeBranchTaken(exists!=0,2);
+ if( exists ) goto jump_to_p2;
+ }
+ if( iSet>=0 ){
+ sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
+ }
+ break;
+}
+
+
+#ifndef SQLITE_OMIT_TRIGGER
+
+/* Opcode: Program P1 P2 P3 P4 P5
+**
+** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
+**
+** P1 contains the address of the memory cell that contains the first memory
+** cell in an array of values used as arguments to the sub-program. P2
+** contains the address to jump to if the sub-program throws an IGNORE
+** exception using the RAISE() function. Register P3 contains the address
+** of a memory cell in this (the parent) VM that is used to allocate the
+** memory required by the sub-vdbe at runtime.
+**
+** P4 is a pointer to the VM containing the trigger program.
+**
+** If P5 is non-zero, then recursive program invocation is enabled.
+*/
+case OP_Program: { /* jump */
+ int nMem; /* Number of memory registers for sub-program */
+ int nByte; /* Bytes of runtime space required for sub-program */
+ Mem *pRt; /* Register to allocate runtime space */
+ Mem *pMem; /* Used to iterate through memory cells */
+ Mem *pEnd; /* Last memory cell in new array */
+ VdbeFrame *pFrame; /* New vdbe frame to execute in */
+ SubProgram *pProgram; /* Sub-program to execute */
+ void *t; /* Token identifying trigger */
+
+ pProgram = pOp->p4.pProgram;
+ pRt = &aMem[pOp->p3];
+ assert( pProgram->nOp>0 );
+
+ /* If the p5 flag is clear, then recursive invocation of triggers is
+ ** disabled for backwards compatibility (p5 is set if this sub-program
+ ** is really a trigger, not a foreign key action, and the flag set
+ ** and cleared by the "PRAGMA recursive_triggers" command is clear).
+ **
+ ** It is recursive invocation of triggers, at the SQL level, that is
+ ** disabled. In some cases a single trigger may generate more than one
+ ** SubProgram (if the trigger may be executed with more than one different
+ ** ON CONFLICT algorithm). SubProgram structures associated with a
+ ** single trigger all have the same value for the SubProgram.token
+ ** variable. */
+ if( pOp->p5 ){
+ t = pProgram->token;
+ for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
+ if( pFrame ) break;
+ }
+
+ if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
+ rc = SQLITE_ERROR;
+ sqlite3VdbeError(p, "too many levels of trigger recursion");
+ goto abort_due_to_error;
+ }
+
+ /* Register pRt is used to store the memory required to save the state
+ ** of the current program, and the memory required at runtime to execute
+ ** the trigger program. If this trigger has been fired before, then pRt
+ ** is already allocated. Otherwise, it must be initialized. */
+ if( (pRt->flags&MEM_Blob)==0 ){
+ /* SubProgram.nMem is set to the number of memory cells used by the
+ ** program stored in SubProgram.aOp. As well as these, one memory
+ ** cell is required for each cursor used by the program. Set local
+ ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
+ */
+ nMem = pProgram->nMem + pProgram->nCsr;
+ assert( nMem>0 );
+ if( pProgram->nCsr==0 ) nMem++;
+ nByte = ROUND8(sizeof(VdbeFrame))
+ + nMem * sizeof(Mem)
+ + pProgram->nCsr * sizeof(VdbeCursor*)
+ + (pProgram->nOp + 7)/8;
+ pFrame = sqlite3DbMallocZero(db, nByte);
+ if( !pFrame ){
+ goto no_mem;
+ }
+ sqlite3VdbeMemRelease(pRt);
+ pRt->flags = MEM_Blob|MEM_Dyn;
+ pRt->z = (char*)pFrame;
+ pRt->n = nByte;
+ pRt->xDel = sqlite3VdbeFrameMemDel;
+
+ pFrame->v = p;
+ pFrame->nChildMem = nMem;
+ pFrame->nChildCsr = pProgram->nCsr;
+ pFrame->pc = (int)(pOp - aOp);
+ pFrame->aMem = p->aMem;
+ pFrame->nMem = p->nMem;
+ pFrame->apCsr = p->apCsr;
+ pFrame->nCursor = p->nCursor;
+ pFrame->aOp = p->aOp;
+ pFrame->nOp = p->nOp;
+ pFrame->token = pProgram->token;
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+ pFrame->anExec = p->anExec;
+#endif
+#ifdef SQLITE_DEBUG
+ pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
+#endif
+
+ pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
+ for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
+ pMem->flags = MEM_Undefined;
+ pMem->db = db;
+ }
+ }else{
+ pFrame = (VdbeFrame*)pRt->z;
+ assert( pRt->xDel==sqlite3VdbeFrameMemDel );
+ assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
+ || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
+ assert( pProgram->nCsr==pFrame->nChildCsr );
+ assert( (int)(pOp - aOp)==pFrame->pc );
+ }
+
+ p->nFrame++;
+ pFrame->pParent = p->pFrame;
+ pFrame->lastRowid = db->lastRowid;
+ pFrame->nChange = p->nChange;
+ pFrame->nDbChange = p->db->nChange;
+ assert( pFrame->pAuxData==0 );
+ pFrame->pAuxData = p->pAuxData;
+ p->pAuxData = 0;
+ p->nChange = 0;
+ p->pFrame = pFrame;
+ p->aMem = aMem = VdbeFrameMem(pFrame);
+ p->nMem = pFrame->nChildMem;
+ p->nCursor = (u16)pFrame->nChildCsr;
+ p->apCsr = (VdbeCursor **)&aMem[p->nMem];
+ pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
+ memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
+ p->aOp = aOp = pProgram->aOp;
+ p->nOp = pProgram->nOp;
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+ p->anExec = 0;
+#endif
+#ifdef SQLITE_DEBUG
+ /* Verify that second and subsequent executions of the same trigger do not
+ ** try to reuse register values from the first use. */
+ {
+ int i;
+ for(i=0; i<p->nMem; i++){
+ aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */
+ MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */
+ }
+ }
+#endif
+ pOp = &aOp[-1];
+ goto check_for_interrupt;
+}
+
+/* Opcode: Param P1 P2 * * *
+**
+** This opcode is only ever present in sub-programs called via the
+** OP_Program instruction. Copy a value currently stored in a memory
+** cell of the calling (parent) frame to cell P2 in the current frames
+** address space. This is used by trigger programs to access the new.*
+** and old.* values.
+**
+** The address of the cell in the parent frame is determined by adding
+** the value of the P1 argument to the value of the P1 argument to the
+** calling OP_Program instruction.
+*/
+case OP_Param: { /* out2 */
+ VdbeFrame *pFrame;
+ Mem *pIn;
+ pOut = out2Prerelease(p, pOp);
+ pFrame = p->pFrame;
+ pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
+ sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
+ break;
+}
+
+#endif /* #ifndef SQLITE_OMIT_TRIGGER */
+
+#ifndef SQLITE_OMIT_FOREIGN_KEY
+/* Opcode: FkCounter P1 P2 * * *
+** Synopsis: fkctr[P1]+=P2
+**
+** Increment a "constraint counter" by P2 (P2 may be negative or positive).
+** If P1 is non-zero, the database constraint counter is incremented
+** (deferred foreign key constraints). Otherwise, if P1 is zero, the
+** statement counter is incremented (immediate foreign key constraints).
+*/
+case OP_FkCounter: {
+ if( db->flags & SQLITE_DeferFKs ){
+ db->nDeferredImmCons += pOp->p2;
+ }else if( pOp->p1 ){
+ db->nDeferredCons += pOp->p2;
+ }else{
+ p->nFkConstraint += pOp->p2;
+ }
+ break;
+}
+
+/* Opcode: FkIfZero P1 P2 * * *
+** Synopsis: if fkctr[P1]==0 goto P2
+**
+** This opcode tests if a foreign key constraint-counter is currently zero.
+** If so, jump to instruction P2. Otherwise, fall through to the next
+** instruction.
+**
+** If P1 is non-zero, then the jump is taken if the database constraint-counter
+** is zero (the one that counts deferred constraint violations). If P1 is
+** zero, the jump is taken if the statement constraint-counter is zero
+** (immediate foreign key constraint violations).
+*/
+case OP_FkIfZero: { /* jump */
+ if( pOp->p1 ){
+ VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
+ if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
+ }else{
+ VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
+ if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
+ }
+ break;
+}
+#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
+
+#ifndef SQLITE_OMIT_AUTOINCREMENT
+/* Opcode: MemMax P1 P2 * * *
+** Synopsis: r[P1]=max(r[P1],r[P2])
+**
+** P1 is a register in the root frame of this VM (the root frame is
+** different from the current frame if this instruction is being executed
+** within a sub-program). Set the value of register P1 to the maximum of
+** its current value and the value in register P2.
+**
+** This instruction throws an error if the memory cell is not initially
+** an integer.
+*/
+case OP_MemMax: { /* in2 */
+ VdbeFrame *pFrame;
+ if( p->pFrame ){
+ for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
+ pIn1 = &pFrame->aMem[pOp->p1];
+ }else{
+ pIn1 = &aMem[pOp->p1];
+ }
+ assert( memIsValid(pIn1) );
+ sqlite3VdbeMemIntegerify(pIn1);
+ pIn2 = &aMem[pOp->p2];
+ sqlite3VdbeMemIntegerify(pIn2);
+ if( pIn1->u.i<pIn2->u.i){
+ pIn1->u.i = pIn2->u.i;
+ }
+ break;
+}
+#endif /* SQLITE_OMIT_AUTOINCREMENT */
+
+/* Opcode: IfPos P1 P2 P3 * *
+** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
+**
+** Register P1 must contain an integer.
+** If the value of register P1 is 1 or greater, subtract P3 from the
+** value in P1 and jump to P2.
+**
+** If the initial value of register P1 is less than 1, then the
+** value is unchanged and control passes through to the next instruction.
+*/
+case OP_IfPos: { /* jump, in1 */
+ pIn1 = &aMem[pOp->p1];
+ assert( pIn1->flags&MEM_Int );
+ VdbeBranchTaken( pIn1->u.i>0, 2);
+ if( pIn1->u.i>0 ){
+ pIn1->u.i -= pOp->p3;
+ goto jump_to_p2;
+ }
+ break;
+}
+
+/* Opcode: OffsetLimit P1 P2 P3 * *
+** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
+**
+** This opcode performs a commonly used computation associated with
+** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
+** holds the offset counter. The opcode computes the combined value
+** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
+** value computed is the total number of rows that will need to be
+** visited in order to complete the query.
+**
+** If r[P3] is zero or negative, that means there is no OFFSET
+** and r[P2] is set to be the value of the LIMIT, r[P1].
+**
+** if r[P1] is zero or negative, that means there is no LIMIT
+** and r[P2] is set to -1.
+**
+** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
+*/
+case OP_OffsetLimit: { /* in1, out2, in3 */
+ i64 x;
+ pIn1 = &aMem[pOp->p1];
+ pIn3 = &aMem[pOp->p3];
+ pOut = out2Prerelease(p, pOp);
+ assert( pIn1->flags & MEM_Int );
+ assert( pIn3->flags & MEM_Int );
+ x = pIn1->u.i;
+ if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
+ /* If the LIMIT is less than or equal to zero, loop forever. This
+ ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
+ ** also loop forever. This is undocumented. In fact, one could argue
+ ** that the loop should terminate. But assuming 1 billion iterations
+ ** per second (far exceeding the capabilities of any current hardware)
+ ** it would take nearly 300 years to actually reach the limit. So
+ ** looping forever is a reasonable approximation. */
+ pOut->u.i = -1;
+ }else{
+ pOut->u.i = x;
+ }
+ break;
+}
+
+/* Opcode: IfNotZero P1 P2 * * *
+** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
+**
+** Register P1 must contain an integer. If the content of register P1 is
+** initially greater than zero, then decrement the value in register P1.
+** If it is non-zero (negative or positive) and then also jump to P2.
+** If register P1 is initially zero, leave it unchanged and fall through.
+*/
+case OP_IfNotZero: { /* jump, in1 */
+ pIn1 = &aMem[pOp->p1];
+ assert( pIn1->flags&MEM_Int );
+ VdbeBranchTaken(pIn1->u.i<0, 2);
+ if( pIn1->u.i ){
+ if( pIn1->u.i>0 ) pIn1->u.i--;
+ goto jump_to_p2;
+ }
+ break;
+}
+
+/* Opcode: DecrJumpZero P1 P2 * * *
+** Synopsis: if (--r[P1])==0 goto P2
+**
+** Register P1 must hold an integer. Decrement the value in P1
+** and jump to P2 if the new value is exactly zero.
+*/
+case OP_DecrJumpZero: { /* jump, in1 */
+ pIn1 = &aMem[pOp->p1];
+ assert( pIn1->flags&MEM_Int );
+ if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
+ VdbeBranchTaken(pIn1->u.i==0, 2);
+ if( pIn1->u.i==0 ) goto jump_to_p2;
+ break;
+}
+
+
+/* Opcode: AggStep * P2 P3 P4 P5
+** Synopsis: accum=r[P3] step(r[P2@P5])
+**
+** Execute the xStep function for an aggregate.
+** The function has P5 arguments. P4 is a pointer to the
+** FuncDef structure that specifies the function. Register P3 is the
+** accumulator.
+**
+** The P5 arguments are taken from register P2 and its
+** successors.
+*/
+/* Opcode: AggInverse * P2 P3 P4 P5
+** Synopsis: accum=r[P3] inverse(r[P2@P5])
+**
+** Execute the xInverse function for an aggregate.
+** The function has P5 arguments. P4 is a pointer to the
+** FuncDef structure that specifies the function. Register P3 is the
+** accumulator.
+**
+** The P5 arguments are taken from register P2 and its
+** successors.
+*/
+/* Opcode: AggStep1 P1 P2 P3 P4 P5
+** Synopsis: accum=r[P3] step(r[P2@P5])
+**
+** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
+** aggregate. The function has P5 arguments. P4 is a pointer to the
+** FuncDef structure that specifies the function. Register P3 is the
+** accumulator.
+**
+** The P5 arguments are taken from register P2 and its
+** successors.
+**
+** This opcode is initially coded as OP_AggStep0. On first evaluation,
+** the FuncDef stored in P4 is converted into an sqlite3_context and
+** the opcode is changed. In this way, the initialization of the
+** sqlite3_context only happens once, instead of on each call to the
+** step function.
+*/
+case OP_AggInverse:
+case OP_AggStep: {
+ int n;
+ sqlite3_context *pCtx;
+
+ assert( pOp->p4type==P4_FUNCDEF );
+ n = pOp->p5;
+ assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
+ assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
+ assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
+ pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
+ (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
+ if( pCtx==0 ) goto no_mem;
+ pCtx->pMem = 0;
+ pCtx->pOut = (Mem*)&(pCtx->argv[n]);
+ sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
+ pCtx->pFunc = pOp->p4.pFunc;
+ pCtx->iOp = (int)(pOp - aOp);
+ pCtx->pVdbe = p;
+ pCtx->skipFlag = 0;
+ pCtx->isError = 0;
+ pCtx->argc = n;
+ pOp->p4type = P4_FUNCCTX;
+ pOp->p4.pCtx = pCtx;
+
+ /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
+ assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
+
+ pOp->opcode = OP_AggStep1;
+ /* Fall through into OP_AggStep */
+ /* no break */ deliberate_fall_through
+}
+case OP_AggStep1: {
+ int i;
+ sqlite3_context *pCtx;
+ Mem *pMem;
+
+ assert( pOp->p4type==P4_FUNCCTX );
+ pCtx = pOp->p4.pCtx;
+ pMem = &aMem[pOp->p3];
+
+#ifdef SQLITE_DEBUG
+ if( pOp->p1 ){
+ /* This is an OP_AggInverse call. Verify that xStep has always
+ ** been called at least once prior to any xInverse call. */
+ assert( pMem->uTemp==0x1122e0e3 );
+ }else{
+ /* This is an OP_AggStep call. Mark it as such. */
+ pMem->uTemp = 0x1122e0e3;
+ }
+#endif
+
+ /* If this function is inside of a trigger, the register array in aMem[]
+ ** might change from one evaluation to the next. The next block of code
+ ** checks to see if the register array has changed, and if so it
+ ** reinitializes the relavant parts of the sqlite3_context object */
+ if( pCtx->pMem != pMem ){
+ pCtx->pMem = pMem;
+ for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
+ }
+
+#ifdef SQLITE_DEBUG
+ for(i=0; i<pCtx->argc; i++){
+ assert( memIsValid(pCtx->argv[i]) );
+ REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
+ }
+#endif
+
+ pMem->n++;
+ assert( pCtx->pOut->flags==MEM_Null );
+ assert( pCtx->isError==0 );
+ assert( pCtx->skipFlag==0 );
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( pOp->p1 ){
+ (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
+ }else
+#endif
+ (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
+
+ if( pCtx->isError ){
+ if( pCtx->isError>0 ){
+ sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
+ rc = pCtx->isError;
+ }
+ if( pCtx->skipFlag ){
+ assert( pOp[-1].opcode==OP_CollSeq );
+ i = pOp[-1].p1;
+ if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
+ pCtx->skipFlag = 0;
+ }
+ sqlite3VdbeMemRelease(pCtx->pOut);
+ pCtx->pOut->flags = MEM_Null;
+ pCtx->isError = 0;
+ if( rc ) goto abort_due_to_error;
+ }
+ assert( pCtx->pOut->flags==MEM_Null );
+ assert( pCtx->skipFlag==0 );
+ break;
+}
+
+/* Opcode: AggFinal P1 P2 * P4 *
+** Synopsis: accum=r[P1] N=P2
+**
+** P1 is the memory location that is the accumulator for an aggregate
+** or window function. Execute the finalizer function
+** for an aggregate and store the result in P1.
+**
+** P2 is the number of arguments that the step function takes and
+** P4 is a pointer to the FuncDef for this function. The P2
+** argument is not used by this opcode. It is only there to disambiguate
+** functions that can take varying numbers of arguments. The
+** P4 argument is only needed for the case where
+** the step function was not previously called.
+*/
+/* Opcode: AggValue * P2 P3 P4 *
+** Synopsis: r[P3]=value N=P2
+**
+** Invoke the xValue() function and store the result in register P3.
+**
+** P2 is the number of arguments that the step function takes and
+** P4 is a pointer to the FuncDef for this function. The P2
+** argument is not used by this opcode. It is only there to disambiguate
+** functions that can take varying numbers of arguments. The
+** P4 argument is only needed for the case where
+** the step function was not previously called.
+*/
+case OP_AggValue:
+case OP_AggFinal: {
+ Mem *pMem;
+ assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
+ assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
+ pMem = &aMem[pOp->p1];
+ assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( pOp->p3 ){
+ memAboutToChange(p, &aMem[pOp->p3]);
+ rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
+ pMem = &aMem[pOp->p3];
+ }else
+#endif
+ {
+ rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
+ }
+
+ if( rc ){
+ sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
+ goto abort_due_to_error;
+ }
+ sqlite3VdbeChangeEncoding(pMem, encoding);
+ UPDATE_MAX_BLOBSIZE(pMem);
+ if( sqlite3VdbeMemTooBig(pMem) ){
+ goto too_big;
+ }
+ break;
+}
+
+#ifndef SQLITE_OMIT_WAL
+/* Opcode: Checkpoint P1 P2 P3 * *
+**
+** Checkpoint database P1. This is a no-op if P1 is not currently in
+** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
+** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
+** SQLITE_BUSY or not, respectively. Write the number of pages in the
+** WAL after the checkpoint into mem[P3+1] and the number of pages
+** in the WAL that have been checkpointed after the checkpoint
+** completes into mem[P3+2]. However on an error, mem[P3+1] and
+** mem[P3+2] are initialized to -1.
+*/
+case OP_Checkpoint: {
+ int i; /* Loop counter */
+ int aRes[3]; /* Results */
+ Mem *pMem; /* Write results here */
+
+ assert( p->readOnly==0 );
+ aRes[0] = 0;
+ aRes[1] = aRes[2] = -1;
+ assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
+ || pOp->p2==SQLITE_CHECKPOINT_FULL
+ || pOp->p2==SQLITE_CHECKPOINT_RESTART
+ || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
+ );
+ rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
+ if( rc ){
+ if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
+ rc = SQLITE_OK;
+ aRes[0] = 1;
+ }
+ for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
+ sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
+ }
+ break;
+};
+#endif
+
+#ifndef SQLITE_OMIT_PRAGMA
+/* Opcode: JournalMode P1 P2 P3 * *
+**
+** Change the journal mode of database P1 to P3. P3 must be one of the
+** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
+** modes (delete, truncate, persist, off and memory), this is a simple
+** operation. No IO is required.
+**
+** If changing into or out of WAL mode the procedure is more complicated.
+**
+** Write a string containing the final journal-mode to register P2.
+*/
+case OP_JournalMode: { /* out2 */
+ Btree *pBt; /* Btree to change journal mode of */
+ Pager *pPager; /* Pager associated with pBt */
+ int eNew; /* New journal mode */
+ int eOld; /* The old journal mode */
+#ifndef SQLITE_OMIT_WAL
+ const char *zFilename; /* Name of database file for pPager */
+#endif
+
+ pOut = out2Prerelease(p, pOp);
+ eNew = pOp->p3;
+ assert( eNew==PAGER_JOURNALMODE_DELETE
+ || eNew==PAGER_JOURNALMODE_TRUNCATE
+ || eNew==PAGER_JOURNALMODE_PERSIST
+ || eNew==PAGER_JOURNALMODE_OFF
+ || eNew==PAGER_JOURNALMODE_MEMORY
+ || eNew==PAGER_JOURNALMODE_WAL
+ || eNew==PAGER_JOURNALMODE_QUERY
+ );
+ assert( pOp->p1>=0 && pOp->p1<db->nDb );
+ assert( p->readOnly==0 );
+
+ pBt = db->aDb[pOp->p1].pBt;
+ pPager = sqlite3BtreePager(pBt);
+ eOld = sqlite3PagerGetJournalMode(pPager);
+ if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
+ if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
+
+#ifndef SQLITE_OMIT_WAL
+ zFilename = sqlite3PagerFilename(pPager, 1);
+
+ /* Do not allow a transition to journal_mode=WAL for a database
+ ** in temporary storage or if the VFS does not support shared memory
+ */
+ if( eNew==PAGER_JOURNALMODE_WAL
+ && (sqlite3Strlen30(zFilename)==0 /* Temp file */
+ || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
+ ){
+ eNew = eOld;
+ }
+
+ if( (eNew!=eOld)
+ && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
+ ){
+ if( !db->autoCommit || db->nVdbeRead>1 ){
+ rc = SQLITE_ERROR;
+ sqlite3VdbeError(p,
+ "cannot change %s wal mode from within a transaction",
+ (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
+ );
+ goto abort_due_to_error;
+ }else{
+
+ if( eOld==PAGER_JOURNALMODE_WAL ){
+ /* If leaving WAL mode, close the log file. If successful, the call
+ ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
+ ** file. An EXCLUSIVE lock may still be held on the database file
+ ** after a successful return.
+ */
+ rc = sqlite3PagerCloseWal(pPager, db);
+ if( rc==SQLITE_OK ){
+ sqlite3PagerSetJournalMode(pPager, eNew);
+ }
+ }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
+ /* Cannot transition directly from MEMORY to WAL. Use mode OFF
+ ** as an intermediate */
+ sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
+ }
+
+ /* Open a transaction on the database file. Regardless of the journal
+ ** mode, this transaction always uses a rollback journal.
+ */
+ assert( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE );
+ if( rc==SQLITE_OK ){
+ rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
+ }
+ }
+ }
+#endif /* ifndef SQLITE_OMIT_WAL */
+
+ if( rc ) eNew = eOld;
+ eNew = sqlite3PagerSetJournalMode(pPager, eNew);
+
+ pOut->flags = MEM_Str|MEM_Static|MEM_Term;
+ pOut->z = (char *)sqlite3JournalModename(eNew);
+ pOut->n = sqlite3Strlen30(pOut->z);
+ pOut->enc = SQLITE_UTF8;
+ sqlite3VdbeChangeEncoding(pOut, encoding);
+ if( rc ) goto abort_due_to_error;
+ break;
+};
+#endif /* SQLITE_OMIT_PRAGMA */
+
+#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
+/* Opcode: Vacuum P1 P2 * * *
+**
+** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
+** for an attached database. The "temp" database may not be vacuumed.
+**
+** If P2 is not zero, then it is a register holding a string which is
+** the file into which the result of vacuum should be written. When
+** P2 is zero, the vacuum overwrites the original database.
+*/
+case OP_Vacuum: {
+ assert( p->readOnly==0 );
+ rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
+ pOp->p2 ? &aMem[pOp->p2] : 0);
+ if( rc ) goto abort_due_to_error;
+ break;
+}
+#endif
+
+#if !defined(SQLITE_OMIT_AUTOVACUUM)
+/* Opcode: IncrVacuum P1 P2 * * *
+**
+** Perform a single step of the incremental vacuum procedure on
+** the P1 database. If the vacuum has finished, jump to instruction
+** P2. Otherwise, fall through to the next instruction.
+*/
+case OP_IncrVacuum: { /* jump */
+ Btree *pBt;
+
+ assert( pOp->p1>=0 && pOp->p1<db->nDb );
+ assert( DbMaskTest(p->btreeMask, pOp->p1) );
+ assert( p->readOnly==0 );
+ pBt = db->aDb[pOp->p1].pBt;
+ rc = sqlite3BtreeIncrVacuum(pBt);
+ VdbeBranchTaken(rc==SQLITE_DONE,2);
+ if( rc ){
+ if( rc!=SQLITE_DONE ) goto abort_due_to_error;
+ rc = SQLITE_OK;
+ goto jump_to_p2;
+ }
+ break;
+}
+#endif
+
+/* Opcode: Expire P1 P2 * * *
+**
+** Cause precompiled statements to expire. When an expired statement
+** is executed using sqlite3_step() it will either automatically
+** reprepare itself (if it was originally created using sqlite3_prepare_v2())
+** or it will fail with SQLITE_SCHEMA.
+**
+** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
+** then only the currently executing statement is expired.
+**
+** If P2 is 0, then SQL statements are expired immediately. If P2 is 1,
+** then running SQL statements are allowed to continue to run to completion.
+** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
+** that might help the statement run faster but which does not affect the
+** correctness of operation.
+*/
+case OP_Expire: {
+ assert( pOp->p2==0 || pOp->p2==1 );
+ if( !pOp->p1 ){
+ sqlite3ExpirePreparedStatements(db, pOp->p2);
+ }else{
+ p->expired = pOp->p2+1;
+ }
+ break;
+}
+
+/* Opcode: CursorLock P1 * * * *
+**
+** Lock the btree to which cursor P1 is pointing so that the btree cannot be
+** written by an other cursor.
+*/
+case OP_CursorLock: {
+ VdbeCursor *pC;
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( pC->eCurType==CURTYPE_BTREE );
+ sqlite3BtreeCursorPin(pC->uc.pCursor);
+ break;
+}
+
+/* Opcode: CursorUnlock P1 * * * *
+**
+** Unlock the btree to which cursor P1 is pointing so that it can be
+** written by other cursors.
+*/
+case OP_CursorUnlock: {
+ VdbeCursor *pC;
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ pC = p->apCsr[pOp->p1];
+ assert( pC!=0 );
+ assert( pC->eCurType==CURTYPE_BTREE );
+ sqlite3BtreeCursorUnpin(pC->uc.pCursor);
+ break;
+}
+
+#ifndef SQLITE_OMIT_SHARED_CACHE
+/* Opcode: TableLock P1 P2 P3 P4 *
+** Synopsis: iDb=P1 root=P2 write=P3
+**
+** Obtain a lock on a particular table. This instruction is only used when
+** the shared-cache feature is enabled.
+**
+** P1 is the index of the database in sqlite3.aDb[] of the database
+** on which the lock is acquired. A readlock is obtained if P3==0 or
+** a write lock if P3==1.
+**
+** P2 contains the root-page of the table to lock.
+**
+** P4 contains a pointer to the name of the table being locked. This is only
+** used to generate an error message if the lock cannot be obtained.
+*/
+case OP_TableLock: {
+ u8 isWriteLock = (u8)pOp->p3;
+ if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
+ int p1 = pOp->p1;
+ assert( p1>=0 && p1<db->nDb );
+ assert( DbMaskTest(p->btreeMask, p1) );
+ assert( isWriteLock==0 || isWriteLock==1 );
+ rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
+ if( rc ){
+ if( (rc&0xFF)==SQLITE_LOCKED ){
+ const char *z = pOp->p4.z;
+ sqlite3VdbeError(p, "database table is locked: %s", z);
+ }
+ goto abort_due_to_error;
+ }
+ }
+ break;
+}
+#endif /* SQLITE_OMIT_SHARED_CACHE */
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/* Opcode: VBegin * * * P4 *
+**
+** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
+** xBegin method for that table.
+**
+** Also, whether or not P4 is set, check that this is not being called from
+** within a callback to a virtual table xSync() method. If it is, the error
+** code will be set to SQLITE_LOCKED.
+*/
+case OP_VBegin: {
+ VTable *pVTab;
+ pVTab = pOp->p4.pVtab;
+ rc = sqlite3VtabBegin(db, pVTab);
+ if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
+ if( rc ) goto abort_due_to_error;
+ break;
+}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/* Opcode: VCreate P1 P2 * * *
+**
+** P2 is a register that holds the name of a virtual table in database
+** P1. Call the xCreate method for that table.
+*/
+case OP_VCreate: {
+ Mem sMem; /* For storing the record being decoded */
+ const char *zTab; /* Name of the virtual table */
+
+ memset(&sMem, 0, sizeof(sMem));
+ sMem.db = db;
+ /* Because P2 is always a static string, it is impossible for the
+ ** sqlite3VdbeMemCopy() to fail */
+ assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
+ assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
+ rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
+ assert( rc==SQLITE_OK );
+ zTab = (const char*)sqlite3_value_text(&sMem);
+ assert( zTab || db->mallocFailed );
+ if( zTab ){
+ rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
+ }
+ sqlite3VdbeMemRelease(&sMem);
+ if( rc ) goto abort_due_to_error;
+ break;
+}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/* Opcode: VDestroy P1 * * P4 *
+**
+** P4 is the name of a virtual table in database P1. Call the xDestroy method
+** of that table.
+*/
+case OP_VDestroy: {
+ db->nVDestroy++;
+ rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
+ db->nVDestroy--;
+ assert( p->errorAction==OE_Abort && p->usesStmtJournal );
+ if( rc ) goto abort_due_to_error;
+ break;
+}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/* Opcode: VOpen P1 * * P4 *
+**
+** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
+** P1 is a cursor number. This opcode opens a cursor to the virtual
+** table and stores that cursor in P1.
+*/
+case OP_VOpen: {
+ VdbeCursor *pCur;
+ sqlite3_vtab_cursor *pVCur;
+ sqlite3_vtab *pVtab;
+ const sqlite3_module *pModule;
+
+ assert( p->bIsReader );
+ pCur = 0;
+ pVCur = 0;
+ pVtab = pOp->p4.pVtab->pVtab;
+ if( pVtab==0 || NEVER(pVtab->pModule==0) ){
+ rc = SQLITE_LOCKED;
+ goto abort_due_to_error;
+ }
+ pModule = pVtab->pModule;
+ rc = pModule->xOpen(pVtab, &pVCur);
+ sqlite3VtabImportErrmsg(p, pVtab);
+ if( rc ) goto abort_due_to_error;
+
+ /* Initialize sqlite3_vtab_cursor base class */
+ pVCur->pVtab = pVtab;
+
+ /* Initialize vdbe cursor object */
+ pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
+ if( pCur ){
+ pCur->uc.pVCur = pVCur;
+ pVtab->nRef++;
+ }else{
+ assert( db->mallocFailed );
+ pModule->xClose(pVCur);
+ goto no_mem;
+ }
+ break;
+}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/* Opcode: VFilter P1 P2 P3 P4 *
+** Synopsis: iplan=r[P3] zplan='P4'
+**
+** P1 is a cursor opened using VOpen. P2 is an address to jump to if
+** the filtered result set is empty.
+**
+** P4 is either NULL or a string that was generated by the xBestIndex
+** method of the module. The interpretation of the P4 string is left
+** to the module implementation.
+**
+** This opcode invokes the xFilter method on the virtual table specified
+** by P1. The integer query plan parameter to xFilter is stored in register
+** P3. Register P3+1 stores the argc parameter to be passed to the
+** xFilter method. Registers P3+2..P3+1+argc are the argc
+** additional parameters which are passed to
+** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
+**
+** A jump is made to P2 if the result set after filtering would be empty.
+*/
+case OP_VFilter: { /* jump */
+ int nArg;
+ int iQuery;
+ const sqlite3_module *pModule;
+ Mem *pQuery;
+ Mem *pArgc;
+ sqlite3_vtab_cursor *pVCur;
+ sqlite3_vtab *pVtab;
+ VdbeCursor *pCur;
+ int res;
+ int i;
+ Mem **apArg;
+
+ pQuery = &aMem[pOp->p3];
+ pArgc = &pQuery[1];
+ pCur = p->apCsr[pOp->p1];
+ assert( memIsValid(pQuery) );
+ REGISTER_TRACE(pOp->p3, pQuery);
+ assert( pCur->eCurType==CURTYPE_VTAB );
+ pVCur = pCur->uc.pVCur;
+ pVtab = pVCur->pVtab;
+ pModule = pVtab->pModule;
+
+ /* Grab the index number and argc parameters */
+ assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
+ nArg = (int)pArgc->u.i;
+ iQuery = (int)pQuery->u.i;
+
+ /* Invoke the xFilter method */
+ res = 0;
+ apArg = p->apArg;
+ for(i = 0; i<nArg; i++){
+ apArg[i] = &pArgc[i+1];
+ }
+ rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
+ sqlite3VtabImportErrmsg(p, pVtab);
+ if( rc ) goto abort_due_to_error;
+ res = pModule->xEof(pVCur);
+ pCur->nullRow = 0;
+ VdbeBranchTaken(res!=0,2);
+ if( res ) goto jump_to_p2;
+ break;
+}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/* Opcode: VColumn P1 P2 P3 * P5
+** Synopsis: r[P3]=vcolumn(P2)
+**
+** Store in register P3 the value of the P2-th column of
+** the current row of the virtual-table of cursor P1.
+**
+** If the VColumn opcode is being used to fetch the value of
+** an unchanging column during an UPDATE operation, then the P5
+** value is OPFLAG_NOCHNG. This will cause the sqlite3_vtab_nochange()
+** function to return true inside the xColumn method of the virtual
+** table implementation. The P5 column might also contain other
+** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
+** unused by OP_VColumn.
+*/
+case OP_VColumn: {
+ sqlite3_vtab *pVtab;
+ const sqlite3_module *pModule;
+ Mem *pDest;
+ sqlite3_context sContext;
+
+ VdbeCursor *pCur = p->apCsr[pOp->p1];
+ assert( pCur->eCurType==CURTYPE_VTAB );
+ assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
+ pDest = &aMem[pOp->p3];
+ memAboutToChange(p, pDest);
+ if( pCur->nullRow ){
+ sqlite3VdbeMemSetNull(pDest);
+ break;
+ }
+ pVtab = pCur->uc.pVCur->pVtab;
+ pModule = pVtab->pModule;
+ assert( pModule->xColumn );
+ memset(&sContext, 0, sizeof(sContext));
+ sContext.pOut = pDest;
+ assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
+ if( pOp->p5 & OPFLAG_NOCHNG ){
+ sqlite3VdbeMemSetNull(pDest);
+ pDest->flags = MEM_Null|MEM_Zero;
+ pDest->u.nZero = 0;
+ }else{
+ MemSetTypeFlag(pDest, MEM_Null);
+ }
+ rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
+ sqlite3VtabImportErrmsg(p, pVtab);
+ if( sContext.isError>0 ){
+ sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
+ rc = sContext.isError;
+ }
+ sqlite3VdbeChangeEncoding(pDest, encoding);
+ REGISTER_TRACE(pOp->p3, pDest);
+ UPDATE_MAX_BLOBSIZE(pDest);
+
+ if( sqlite3VdbeMemTooBig(pDest) ){
+ goto too_big;
+ }
+ if( rc ) goto abort_due_to_error;
+ break;
+}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/* Opcode: VNext P1 P2 * * *
+**
+** Advance virtual table P1 to the next row in its result set and
+** jump to instruction P2. Or, if the virtual table has reached
+** the end of its result set, then fall through to the next instruction.
+*/
+case OP_VNext: { /* jump */
+ sqlite3_vtab *pVtab;
+ const sqlite3_module *pModule;
+ int res;
+ VdbeCursor *pCur;
+
+ res = 0;
+ pCur = p->apCsr[pOp->p1];
+ assert( pCur->eCurType==CURTYPE_VTAB );
+ if( pCur->nullRow ){
+ break;
+ }
+ pVtab = pCur->uc.pVCur->pVtab;
+ pModule = pVtab->pModule;
+ assert( pModule->xNext );
+
+ /* Invoke the xNext() method of the module. There is no way for the
+ ** underlying implementation to return an error if one occurs during
+ ** xNext(). Instead, if an error occurs, true is returned (indicating that
+ ** data is available) and the error code returned when xColumn or
+ ** some other method is next invoked on the save virtual table cursor.
+ */
+ rc = pModule->xNext(pCur->uc.pVCur);
+ sqlite3VtabImportErrmsg(p, pVtab);
+ if( rc ) goto abort_due_to_error;
+ res = pModule->xEof(pCur->uc.pVCur);
+ VdbeBranchTaken(!res,2);
+ if( !res ){
+ /* If there is data, jump to P2 */
+ goto jump_to_p2_and_check_for_interrupt;
+ }
+ goto check_for_interrupt;
+}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/* Opcode: VRename P1 * * P4 *
+**
+** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
+** This opcode invokes the corresponding xRename method. The value
+** in register P1 is passed as the zName argument to the xRename method.
+*/
+case OP_VRename: {
+ sqlite3_vtab *pVtab;
+ Mem *pName;
+ int isLegacy;
+
+ isLegacy = (db->flags & SQLITE_LegacyAlter);
+ db->flags |= SQLITE_LegacyAlter;
+ pVtab = pOp->p4.pVtab->pVtab;
+ pName = &aMem[pOp->p1];
+ assert( pVtab->pModule->xRename );
+ assert( memIsValid(pName) );
+ assert( p->readOnly==0 );
+ REGISTER_TRACE(pOp->p1, pName);
+ assert( pName->flags & MEM_Str );
+ testcase( pName->enc==SQLITE_UTF8 );
+ testcase( pName->enc==SQLITE_UTF16BE );
+ testcase( pName->enc==SQLITE_UTF16LE );
+ rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
+ if( rc ) goto abort_due_to_error;
+ rc = pVtab->pModule->xRename(pVtab, pName->z);
+ if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
+ sqlite3VtabImportErrmsg(p, pVtab);
+ p->expired = 0;
+ if( rc ) goto abort_due_to_error;
+ break;
+}
+#endif
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/* Opcode: VUpdate P1 P2 P3 P4 P5
+** Synopsis: data=r[P3@P2]
+**
+** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
+** This opcode invokes the corresponding xUpdate method. P2 values
+** are contiguous memory cells starting at P3 to pass to the xUpdate
+** invocation. The value in register (P3+P2-1) corresponds to the
+** p2th element of the argv array passed to xUpdate.
+**
+** The xUpdate method will do a DELETE or an INSERT or both.
+** The argv[0] element (which corresponds to memory cell P3)
+** is the rowid of a row to delete. If argv[0] is NULL then no
+** deletion occurs. The argv[1] element is the rowid of the new
+** row. This can be NULL to have the virtual table select the new
+** rowid for itself. The subsequent elements in the array are
+** the values of columns in the new row.
+**
+** If P2==1 then no insert is performed. argv[0] is the rowid of
+** a row to delete.
+**
+** P1 is a boolean flag. If it is set to true and the xUpdate call
+** is successful, then the value returned by sqlite3_last_insert_rowid()
+** is set to the value of the rowid for the row just inserted.
+**
+** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
+** apply in the case of a constraint failure on an insert or update.
+*/
+case OP_VUpdate: {
+ sqlite3_vtab *pVtab;
+ const sqlite3_module *pModule;
+ int nArg;
+ int i;
+ sqlite_int64 rowid;
+ Mem **apArg;
+ Mem *pX;
+
+ assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
+ || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
+ );
+ assert( p->readOnly==0 );
+ if( db->mallocFailed ) goto no_mem;
+ sqlite3VdbeIncrWriteCounter(p, 0);
+ pVtab = pOp->p4.pVtab->pVtab;
+ if( pVtab==0 || NEVER(pVtab->pModule==0) ){
+ rc = SQLITE_LOCKED;
+ goto abort_due_to_error;
+ }
+ pModule = pVtab->pModule;
+ nArg = pOp->p2;
+ assert( pOp->p4type==P4_VTAB );
+ if( ALWAYS(pModule->xUpdate) ){
+ u8 vtabOnConflict = db->vtabOnConflict;
+ apArg = p->apArg;
+ pX = &aMem[pOp->p3];
+ for(i=0; i<nArg; i++){
+ assert( memIsValid(pX) );
+ memAboutToChange(p, pX);
+ apArg[i] = pX;
+ pX++;
+ }
+ db->vtabOnConflict = pOp->p5;
+ rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
+ db->vtabOnConflict = vtabOnConflict;
+ sqlite3VtabImportErrmsg(p, pVtab);
+ if( rc==SQLITE_OK && pOp->p1 ){
+ assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
+ db->lastRowid = rowid;
+ }
+ if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
+ if( pOp->p5==OE_Ignore ){
+ rc = SQLITE_OK;
+ }else{
+ p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
+ }
+ }else{
+ p->nChange++;
+ }
+ if( rc ) goto abort_due_to_error;
+ }
+ break;
+}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+#ifndef SQLITE_OMIT_PAGER_PRAGMAS
+/* Opcode: Pagecount P1 P2 * * *
+**
+** Write the current number of pages in database P1 to memory cell P2.
+*/
+case OP_Pagecount: { /* out2 */
+ pOut = out2Prerelease(p, pOp);
+ pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
+ break;
+}
+#endif
+
+
+#ifndef SQLITE_OMIT_PAGER_PRAGMAS
+/* Opcode: MaxPgcnt P1 P2 P3 * *
+**
+** Try to set the maximum page count for database P1 to the value in P3.
+** Do not let the maximum page count fall below the current page count and
+** do not change the maximum page count value if P3==0.
+**
+** Store the maximum page count after the change in register P2.
+*/
+case OP_MaxPgcnt: { /* out2 */
+ unsigned int newMax;
+ Btree *pBt;
+
+ pOut = out2Prerelease(p, pOp);
+ pBt = db->aDb[pOp->p1].pBt;
+ newMax = 0;
+ if( pOp->p3 ){
+ newMax = sqlite3BtreeLastPage(pBt);
+ if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
+ }
+ pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
+ break;
+}
+#endif
+
+/* Opcode: Function P1 P2 P3 P4 *
+** Synopsis: r[P3]=func(r[P2@NP])
+**
+** Invoke a user function (P4 is a pointer to an sqlite3_context object that
+** contains a pointer to the function to be run) with arguments taken
+** from register P2 and successors. The number of arguments is in
+** the sqlite3_context object that P4 points to.
+** The result of the function is stored
+** in register P3. Register P3 must not be one of the function inputs.
+**
+** P1 is a 32-bit bitmask indicating whether or not each argument to the
+** function was determined to be constant at compile time. If the first
+** argument was constant then bit 0 of P1 is set. This is used to determine
+** whether meta data associated with a user function argument using the
+** sqlite3_set_auxdata() API may be safely retained until the next
+** invocation of this opcode.
+**
+** See also: AggStep, AggFinal, PureFunc
+*/
+/* Opcode: PureFunc P1 P2 P3 P4 *
+** Synopsis: r[P3]=func(r[P2@NP])
+**
+** Invoke a user function (P4 is a pointer to an sqlite3_context object that
+** contains a pointer to the function to be run) with arguments taken
+** from register P2 and successors. The number of arguments is in
+** the sqlite3_context object that P4 points to.
+** The result of the function is stored
+** in register P3. Register P3 must not be one of the function inputs.
+**
+** P1 is a 32-bit bitmask indicating whether or not each argument to the
+** function was determined to be constant at compile time. If the first
+** argument was constant then bit 0 of P1 is set. This is used to determine
+** whether meta data associated with a user function argument using the
+** sqlite3_set_auxdata() API may be safely retained until the next
+** invocation of this opcode.
+**
+** This opcode works exactly like OP_Function. The only difference is in
+** its name. This opcode is used in places where the function must be
+** purely non-deterministic. Some built-in date/time functions can be
+** either determinitic of non-deterministic, depending on their arguments.
+** When those function are used in a non-deterministic way, they will check
+** to see if they were called using OP_PureFunc instead of OP_Function, and
+** if they were, they throw an error.
+**
+** See also: AggStep, AggFinal, Function
+*/
+case OP_PureFunc: /* group */
+case OP_Function: { /* group */
+ int i;
+ sqlite3_context *pCtx;
+
+ assert( pOp->p4type==P4_FUNCCTX );
+ pCtx = pOp->p4.pCtx;
+
+ /* If this function is inside of a trigger, the register array in aMem[]
+ ** might change from one evaluation to the next. The next block of code
+ ** checks to see if the register array has changed, and if so it
+ ** reinitializes the relavant parts of the sqlite3_context object */
+ pOut = &aMem[pOp->p3];
+ if( pCtx->pOut != pOut ){
+ pCtx->pVdbe = p;
+ pCtx->pOut = pOut;
+ for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
+ }
+ assert( pCtx->pVdbe==p );
+
+ memAboutToChange(p, pOut);
+#ifdef SQLITE_DEBUG
+ for(i=0; i<pCtx->argc; i++){
+ assert( memIsValid(pCtx->argv[i]) );
+ REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
+ }
+#endif
+ MemSetTypeFlag(pOut, MEM_Null);
+ assert( pCtx->isError==0 );
+ (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
+
+ /* If the function returned an error, throw an exception */
+ if( pCtx->isError ){
+ if( pCtx->isError>0 ){
+ sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
+ rc = pCtx->isError;
+ }
+ sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
+ pCtx->isError = 0;
+ if( rc ) goto abort_due_to_error;
+ }
+
+ /* Copy the result of the function into register P3 */
+ if( pOut->flags & (MEM_Str|MEM_Blob) ){
+ sqlite3VdbeChangeEncoding(pOut, encoding);
+ if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
+ }
+
+ REGISTER_TRACE(pOp->p3, pOut);
+ UPDATE_MAX_BLOBSIZE(pOut);
+ break;
+}
+
+/* Opcode: Trace P1 P2 * P4 *
+**
+** Write P4 on the statement trace output if statement tracing is
+** enabled.
+**
+** Operand P1 must be 0x7fffffff and P2 must positive.
+*/
+/* Opcode: Init P1 P2 P3 P4 *
+** Synopsis: Start at P2
+**
+** Programs contain a single instance of this opcode as the very first
+** opcode.
+**
+** If tracing is enabled (by the sqlite3_trace()) interface, then
+** the UTF-8 string contained in P4 is emitted on the trace callback.
+** Or if P4 is blank, use the string returned by sqlite3_sql().
+**
+** If P2 is not zero, jump to instruction P2.
+**
+** Increment the value of P1 so that OP_Once opcodes will jump the
+** first time they are evaluated for this run.
+**
+** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
+** error is encountered.
+*/
+case OP_Trace:
+case OP_Init: { /* jump */
+ int i;
+#ifndef SQLITE_OMIT_TRACE
+ char *zTrace;
+#endif
+
+ /* If the P4 argument is not NULL, then it must be an SQL comment string.
+ ** The "--" string is broken up to prevent false-positives with srcck1.c.
+ **
+ ** This assert() provides evidence for:
+ ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
+ ** would have been returned by the legacy sqlite3_trace() interface by
+ ** using the X argument when X begins with "--" and invoking
+ ** sqlite3_expanded_sql(P) otherwise.
+ */
+ assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
+
+ /* OP_Init is always instruction 0 */
+ assert( pOp==p->aOp || pOp->opcode==OP_Trace );
+
+#ifndef SQLITE_OMIT_TRACE
+ if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
+ && !p->doingRerun
+ && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
+ ){
+#ifndef SQLITE_OMIT_DEPRECATED
+ if( db->mTrace & SQLITE_TRACE_LEGACY ){
+ char *z = sqlite3VdbeExpandSql(p, zTrace);
+ db->trace.xLegacy(db->pTraceArg, z);
+ sqlite3_free(z);
+ }else
+#endif
+ if( db->nVdbeExec>1 ){
+ char *z = sqlite3MPrintf(db, "-- %s", zTrace);
+ (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
+ sqlite3DbFree(db, z);
+ }else{
+ (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
+ }
+ }
+#ifdef SQLITE_USE_FCNTL_TRACE
+ zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
+ if( zTrace ){
+ int j;
+ for(j=0; j<db->nDb; j++){
+ if( DbMaskTest(p->btreeMask, j)==0 ) continue;
+ sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
+ }
+ }
+#endif /* SQLITE_USE_FCNTL_TRACE */
+#ifdef SQLITE_DEBUG
+ if( (db->flags & SQLITE_SqlTrace)!=0
+ && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
+ ){
+ sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
+ }
+#endif /* SQLITE_DEBUG */
+#endif /* SQLITE_OMIT_TRACE */
+ assert( pOp->p2>0 );
+ if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
+ if( pOp->opcode==OP_Trace ) break;
+ for(i=1; i<p->nOp; i++){
+ if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
+ }
+ pOp->p1 = 0;
+ }
+ pOp->p1++;
+ p->aCounter[SQLITE_STMTSTATUS_RUN]++;
+ goto jump_to_p2;
+}
+
+#ifdef SQLITE_ENABLE_CURSOR_HINTS
+/* Opcode: CursorHint P1 * * P4 *
+**
+** Provide a hint to cursor P1 that it only needs to return rows that
+** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
+** to values currently held in registers. TK_COLUMN terms in the P4
+** expression refer to columns in the b-tree to which cursor P1 is pointing.
+*/
+case OP_CursorHint: {
+ VdbeCursor *pC;
+
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+ assert( pOp->p4type==P4_EXPR );
+ pC = p->apCsr[pOp->p1];
+ if( pC ){
+ assert( pC->eCurType==CURTYPE_BTREE );
+ sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
+ pOp->p4.pExpr, aMem);
+ }
+ break;
+}
+#endif /* SQLITE_ENABLE_CURSOR_HINTS */
+
+#ifdef SQLITE_DEBUG
+/* Opcode: Abortable * * * * *
+**
+** Verify that an Abort can happen. Assert if an Abort at this point
+** might cause database corruption. This opcode only appears in debugging
+** builds.
+**
+** An Abort is safe if either there have been no writes, or if there is
+** an active statement journal.
+*/
+case OP_Abortable: {
+ sqlite3VdbeAssertAbortable(p);
+ break;
+}
+#endif
+
+#ifdef SQLITE_DEBUG
+/* Opcode: ReleaseReg P1 P2 P3 * P5
+** Synopsis: release r[P1@P2] mask P3
+**
+** Release registers from service. Any content that was in the
+** the registers is unreliable after this opcode completes.
+**
+** The registers released will be the P2 registers starting at P1,
+** except if bit ii of P3 set, then do not release register P1+ii.
+** In other words, P3 is a mask of registers to preserve.
+**
+** Releasing a register clears the Mem.pScopyFrom pointer. That means
+** that if the content of the released register was set using OP_SCopy,
+** a change to the value of the source register for the OP_SCopy will no longer
+** generate an assertion fault in sqlite3VdbeMemAboutToChange().
+**
+** If P5 is set, then all released registers have their type set
+** to MEM_Undefined so that any subsequent attempt to read the released
+** register (before it is reinitialized) will generate an assertion fault.
+**
+** P5 ought to be set on every call to this opcode.
+** However, there are places in the code generator will release registers
+** before their are used, under the (valid) assumption that the registers
+** will not be reallocated for some other purpose before they are used and
+** hence are safe to release.
+**
+** This opcode is only available in testing and debugging builds. It is
+** not generated for release builds. The purpose of this opcode is to help
+** validate the generated bytecode. This opcode does not actually contribute
+** to computing an answer.
+*/
+case OP_ReleaseReg: {
+ Mem *pMem;
+ int i;
+ u32 constMask;
+ assert( pOp->p1>0 );
+ assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
+ pMem = &aMem[pOp->p1];
+ constMask = pOp->p3;
+ for(i=0; i<pOp->p2; i++, pMem++){
+ if( i>=32 || (constMask & MASKBIT32(i))==0 ){
+ pMem->pScopyFrom = 0;
+ if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);
+ }
+ }
+ break;
+}
+#endif
+
+/* Opcode: Noop * * * * *
+**
+** Do nothing. This instruction is often useful as a jump
+** destination.
+*/
+/*
+** The magic Explain opcode are only inserted when explain==2 (which
+** is to say when the EXPLAIN QUERY PLAN syntax is used.)
+** This opcode records information from the optimizer. It is the
+** the same as a no-op. This opcodesnever appears in a real VM program.
+*/
+default: { /* This is really OP_Noop, OP_Explain */
+ assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
+
+ break;
+}
+
+/*****************************************************************************
+** The cases of the switch statement above this line should all be indented
+** by 6 spaces. But the left-most 6 spaces have been removed to improve the
+** readability. From this point on down, the normal indentation rules are
+** restored.
+*****************************************************************************/
+ }
+
+#ifdef VDBE_PROFILE
+ {
+ u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
+ if( endTime>start ) pOrigOp->cycles += endTime - start;
+ pOrigOp->cnt++;
+ }
+#endif
+
+ /* The following code adds nothing to the actual functionality
+ ** of the program. It is only here for testing and debugging.
+ ** On the other hand, it does burn CPU cycles every time through
+ ** the evaluator loop. So we can leave it out when NDEBUG is defined.
+ */
+#ifndef NDEBUG
+ assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
+
+#ifdef SQLITE_DEBUG
+ if( db->flags & SQLITE_VdbeTrace ){
+ u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
+ if( rc!=0 ) printf("rc=%d\n",rc);
+ if( opProperty & (OPFLG_OUT2) ){
+ registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
+ }
+ if( opProperty & OPFLG_OUT3 ){
+ registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
+ }
+ if( opProperty==0xff ){
+ /* Never happens. This code exists to avoid a harmless linkage
+ ** warning aboud sqlite3VdbeRegisterDump() being defined but not
+ ** used. */
+ sqlite3VdbeRegisterDump(p);
+ }
+ }
+#endif /* SQLITE_DEBUG */
+#endif /* NDEBUG */
+ } /* The end of the for(;;) loop the loops through opcodes */
+
+ /* If we reach this point, it means that execution is finished with
+ ** an error of some kind.
+ */
+abort_due_to_error:
+ if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
+ assert( rc );
+ if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
+ sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
+ }
+ p->rc = rc;
+ sqlite3SystemError(db, rc);
+ testcase( sqlite3GlobalConfig.xLog!=0 );
+ sqlite3_log(rc, "statement aborts at %d: [%s] %s",
+ (int)(pOp - aOp), p->zSql, p->zErrMsg);
+ sqlite3VdbeHalt(p);
+ if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
+ rc = SQLITE_ERROR;
+ if( resetSchemaOnFault>0 ){
+ sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
+ }
+
+ /* This is the only way out of this procedure. We have to
+ ** release the mutexes on btrees that were acquired at the
+ ** top. */
+vdbe_return:
+#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
+ while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
+ nProgressLimit += db->nProgressOps;
+ if( db->xProgress(db->pProgressArg) ){
+ nProgressLimit = LARGEST_UINT64;
+ rc = SQLITE_INTERRUPT;
+ goto abort_due_to_error;
+ }
+ }
+#endif
+ p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
+ sqlite3VdbeLeave(p);
+ assert( rc!=SQLITE_OK || nExtraDelete==0
+ || sqlite3_strlike("DELETE%",p->zSql,0)!=0
+ );
+ return rc;
+
+ /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
+ ** is encountered.
+ */
+too_big:
+ sqlite3VdbeError(p, "string or blob too big");
+ rc = SQLITE_TOOBIG;
+ goto abort_due_to_error;
+
+ /* Jump to here if a malloc() fails.
+ */
+no_mem:
+ sqlite3OomFault(db);
+ sqlite3VdbeError(p, "out of memory");
+ rc = SQLITE_NOMEM_BKPT;
+ goto abort_due_to_error;
+
+ /* Jump to here if the sqlite3_interrupt() API sets the interrupt
+ ** flag.
+ */
+abort_due_to_interrupt:
+ assert( AtomicLoad(&db->u1.isInterrupted) );
+ rc = SQLITE_INTERRUPT;
+ goto abort_due_to_error;
+}
+
+
+/************** End of vdbe.c ************************************************/
+/************** Begin file vdbeblob.c ****************************************/
+/*
+** 2007 May 1
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains code used to implement incremental BLOB I/O.
+*/
+
+/* #include "sqliteInt.h" */
+/* #include "vdbeInt.h" */
+
+#ifndef SQLITE_OMIT_INCRBLOB
+
+/*
+** Valid sqlite3_blob* handles point to Incrblob structures.
+*/
+typedef struct Incrblob Incrblob;
+struct Incrblob {
+ int nByte; /* Size of open blob, in bytes */
+ int iOffset; /* Byte offset of blob in cursor data */
+ u16 iCol; /* Table column this handle is open on */
+ BtCursor *pCsr; /* Cursor pointing at blob row */
+ sqlite3_stmt *pStmt; /* Statement holding cursor open */
+ sqlite3 *db; /* The associated database */
+ char *zDb; /* Database name */
+ Table *pTab; /* Table object */
+};
+
+
+/*
+** This function is used by both blob_open() and blob_reopen(). It seeks
+** the b-tree cursor associated with blob handle p to point to row iRow.
+** If successful, SQLITE_OK is returned and subsequent calls to
+** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
+**
+** If an error occurs, or if the specified row does not exist or does not
+** contain a value of type TEXT or BLOB in the column nominated when the
+** blob handle was opened, then an error code is returned and *pzErr may
+** be set to point to a buffer containing an error message. It is the
+** responsibility of the caller to free the error message buffer using
+** sqlite3DbFree().
+**
+** If an error does occur, then the b-tree cursor is closed. All subsequent
+** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
+** immediately return SQLITE_ABORT.
+*/
+static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
+ int rc; /* Error code */
+ char *zErr = 0; /* Error message */
+ Vdbe *v = (Vdbe *)p->pStmt;
+
+ /* Set the value of register r[1] in the SQL statement to integer iRow.
+ ** This is done directly as a performance optimization
+ */
+ v->aMem[1].flags = MEM_Int;
+ v->aMem[1].u.i = iRow;
+
+ /* If the statement has been run before (and is paused at the OP_ResultRow)
+ ** then back it up to the point where it does the OP_NotExists. This could
+ ** have been down with an extra OP_Goto, but simply setting the program
+ ** counter is faster. */
+ if( v->pc>4 ){
+ v->pc = 4;
+ assert( v->aOp[v->pc].opcode==OP_NotExists );
+ rc = sqlite3VdbeExec(v);
+ }else{
+ rc = sqlite3_step(p->pStmt);
+ }
+ if( rc==SQLITE_ROW ){
+ VdbeCursor *pC = v->apCsr[0];
+ u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
+ testcase( pC->nHdrParsed==p->iCol );
+ testcase( pC->nHdrParsed==p->iCol+1 );
+ if( type<12 ){
+ zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
+ type==0?"null": type==7?"real": "integer"
+ );
+ rc = SQLITE_ERROR;
+ sqlite3_finalize(p->pStmt);
+ p->pStmt = 0;
+ }else{
+ p->iOffset = pC->aType[p->iCol + pC->nField];
+ p->nByte = sqlite3VdbeSerialTypeLen(type);
+ p->pCsr = pC->uc.pCursor;
+ sqlite3BtreeIncrblobCursor(p->pCsr);
+ }
+ }
+
+ if( rc==SQLITE_ROW ){
+ rc = SQLITE_OK;
+ }else if( p->pStmt ){
+ rc = sqlite3_finalize(p->pStmt);
+ p->pStmt = 0;
+ if( rc==SQLITE_OK ){
+ zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
+ rc = SQLITE_ERROR;
+ }else{
+ zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
+ }
+ }
+
+ assert( rc!=SQLITE_OK || zErr==0 );
+ assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
+
+ *pzErr = zErr;
+ return rc;
+}
+
+/*
+** Open a blob handle.
+*/
+SQLITE_API int sqlite3_blob_open(
+ sqlite3* db, /* The database connection */
+ const char *zDb, /* The attached database containing the blob */
+ const char *zTable, /* The table containing the blob */
+ const char *zColumn, /* The column containing the blob */
+ sqlite_int64 iRow, /* The row containing the glob */
+ int wrFlag, /* True -> read/write access, false -> read-only */
+ sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
+){
+ int nAttempt = 0;
+ int iCol; /* Index of zColumn in row-record */
+ int rc = SQLITE_OK;
+ char *zErr = 0;
+ Table *pTab;
+ Incrblob *pBlob = 0;
+ Parse sParse;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( ppBlob==0 ){
+ return SQLITE_MISUSE_BKPT;
+ }
+#endif
+ *ppBlob = 0;
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
+ return SQLITE_MISUSE_BKPT;
+ }
+#endif
+ wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */
+
+ sqlite3_mutex_enter(db->mutex);
+
+ pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
+ do {
+ memset(&sParse, 0, sizeof(Parse));
+ if( !pBlob ) goto blob_open_out;
+ sParse.db = db;
+ sqlite3DbFree(db, zErr);
+ zErr = 0;
+
+ sqlite3BtreeEnterAll(db);
+ pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
+ if( pTab && IsVirtual(pTab) ){
+ pTab = 0;
+ sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
+ }
+ if( pTab && !HasRowid(pTab) ){
+ pTab = 0;
+ sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
+ }
+#ifndef SQLITE_OMIT_VIEW
+ if( pTab && pTab->pSelect ){
+ pTab = 0;
+ sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
+ }
+#endif
+ if( !pTab ){
+ if( sParse.zErrMsg ){
+ sqlite3DbFree(db, zErr);
+ zErr = sParse.zErrMsg;
+ sParse.zErrMsg = 0;
+ }
+ rc = SQLITE_ERROR;
+ sqlite3BtreeLeaveAll(db);
+ goto blob_open_out;
+ }
+ pBlob->pTab = pTab;
+ pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
+
+ /* Now search pTab for the exact column. */
+ for(iCol=0; iCol<pTab->nCol; iCol++) {
+ if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
+ break;
+ }
+ }
+ if( iCol==pTab->nCol ){
+ sqlite3DbFree(db, zErr);
+ zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
+ rc = SQLITE_ERROR;
+ sqlite3BtreeLeaveAll(db);
+ goto blob_open_out;
+ }
+
+ /* If the value is being opened for writing, check that the
+ ** column is not indexed, and that it is not part of a foreign key.
+ */
+ if( wrFlag ){
+ const char *zFault = 0;
+ Index *pIdx;
+#ifndef SQLITE_OMIT_FOREIGN_KEY
+ if( db->flags&SQLITE_ForeignKeys ){
+ /* Check that the column is not part of an FK child key definition. It
+ ** is not necessary to check if it is part of a parent key, as parent
+ ** key columns must be indexed. The check below will pick up this
+ ** case. */
+ FKey *pFKey;
+ for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
+ int j;
+ for(j=0; j<pFKey->nCol; j++){
+ if( pFKey->aCol[j].iFrom==iCol ){
+ zFault = "foreign key";
+ }
+ }
+ }
+ }
+#endif
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+ int j;
+ for(j=0; j<pIdx->nKeyCol; j++){
+ /* FIXME: Be smarter about indexes that use expressions */
+ if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
+ zFault = "indexed";
+ }
+ }
+ }
+ if( zFault ){
+ sqlite3DbFree(db, zErr);
+ zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
+ rc = SQLITE_ERROR;
+ sqlite3BtreeLeaveAll(db);
+ goto blob_open_out;
+ }
+ }
+
+ pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
+ assert( pBlob->pStmt || db->mallocFailed );
+ if( pBlob->pStmt ){
+
+ /* This VDBE program seeks a btree cursor to the identified
+ ** db/table/row entry. The reason for using a vdbe program instead
+ ** of writing code to use the b-tree layer directly is that the
+ ** vdbe program will take advantage of the various transaction,
+ ** locking and error handling infrastructure built into the vdbe.
+ **
+ ** After seeking the cursor, the vdbe executes an OP_ResultRow.
+ ** Code external to the Vdbe then "borrows" the b-tree cursor and
+ ** uses it to implement the blob_read(), blob_write() and
+ ** blob_bytes() functions.
+ **
+ ** The sqlite3_blob_close() function finalizes the vdbe program,
+ ** which closes the b-tree cursor and (possibly) commits the
+ ** transaction.
+ */
+ static const int iLn = VDBE_OFFSET_LINENO(2);
+ static const VdbeOpList openBlob[] = {
+ {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
+ {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
+ /* blobSeekToRow() will initialize r[1] to the desired rowid */
+ {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */
+ {OP_Column, 0, 0, 1}, /* 3 */
+ {OP_ResultRow, 1, 0, 0}, /* 4 */
+ {OP_Halt, 0, 0, 0}, /* 5 */
+ };
+ Vdbe *v = (Vdbe *)pBlob->pStmt;
+ int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ VdbeOp *aOp;
+
+ sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
+ pTab->pSchema->schema_cookie,
+ pTab->pSchema->iGeneration);
+ sqlite3VdbeChangeP5(v, 1);
+ assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
+ aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
+
+ /* Make sure a mutex is held on the table to be accessed */
+ sqlite3VdbeUsesBtree(v, iDb);
+
+ if( db->mallocFailed==0 ){
+ assert( aOp!=0 );
+ /* Configure the OP_TableLock instruction */
+#ifdef SQLITE_OMIT_SHARED_CACHE
+ aOp[0].opcode = OP_Noop;
+#else
+ aOp[0].p1 = iDb;
+ aOp[0].p2 = pTab->tnum;
+ aOp[0].p3 = wrFlag;
+ sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
+ }
+ if( db->mallocFailed==0 ){
+#endif
+
+ /* Remove either the OP_OpenWrite or OpenRead. Set the P2
+ ** parameter of the other to pTab->tnum. */
+ if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
+ aOp[1].p2 = pTab->tnum;
+ aOp[1].p3 = iDb;
+
+ /* Configure the number of columns. Configure the cursor to
+ ** think that the table has one more column than it really
+ ** does. An OP_Column to retrieve this imaginary column will
+ ** always return an SQL NULL. This is useful because it means
+ ** we can invoke OP_Column to fill in the vdbe cursors type
+ ** and offset cache without causing any IO.
+ */
+ aOp[1].p4type = P4_INT32;
+ aOp[1].p4.i = pTab->nCol+1;
+ aOp[3].p2 = pTab->nCol;
+
+ sParse.nVar = 0;
+ sParse.nMem = 1;
+ sParse.nTab = 1;
+ sqlite3VdbeMakeReady(v, &sParse);
+ }
+ }
+
+ pBlob->iCol = iCol;
+ pBlob->db = db;
+ sqlite3BtreeLeaveAll(db);
+ if( db->mallocFailed ){
+ goto blob_open_out;
+ }
+ rc = blobSeekToRow(pBlob, iRow, &zErr);
+ } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
+
+blob_open_out:
+ if( rc==SQLITE_OK && db->mallocFailed==0 ){
+ *ppBlob = (sqlite3_blob *)pBlob;
+ }else{
+ if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
+ sqlite3DbFree(db, pBlob);
+ }
+ sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
+ sqlite3DbFree(db, zErr);
+ sqlite3ParserReset(&sParse);
+ rc = sqlite3ApiExit(db, rc);
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+/*
+** Close a blob handle that was previously created using
+** sqlite3_blob_open().
+*/
+SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
+ Incrblob *p = (Incrblob *)pBlob;
+ int rc;
+ sqlite3 *db;
+
+ if( p ){
+ sqlite3_stmt *pStmt = p->pStmt;
+ db = p->db;
+ sqlite3_mutex_enter(db->mutex);
+ sqlite3DbFree(db, p);
+ sqlite3_mutex_leave(db->mutex);
+ rc = sqlite3_finalize(pStmt);
+ }else{
+ rc = SQLITE_OK;
+ }
+ return rc;
+}
+
+/*
+** Perform a read or write operation on a blob
+*/
+static int blobReadWrite(
+ sqlite3_blob *pBlob,
+ void *z,
+ int n,
+ int iOffset,
+ int (*xCall)(BtCursor*, u32, u32, void*)
+){
+ int rc;
+ Incrblob *p = (Incrblob *)pBlob;
+ Vdbe *v;
+ sqlite3 *db;
+
+ if( p==0 ) return SQLITE_MISUSE_BKPT;
+ db = p->db;
+ sqlite3_mutex_enter(db->mutex);
+ v = (Vdbe*)p->pStmt;
+
+ if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
+ /* Request is out of range. Return a transient error. */
+ rc = SQLITE_ERROR;
+ }else if( v==0 ){
+ /* If there is no statement handle, then the blob-handle has
+ ** already been invalidated. Return SQLITE_ABORT in this case.
+ */
+ rc = SQLITE_ABORT;
+ }else{
+ /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
+ ** returned, clean-up the statement handle.
+ */
+ assert( db == v->db );
+ sqlite3BtreeEnterCursor(p->pCsr);
+
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+ if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
+ /* If a pre-update hook is registered and this is a write cursor,
+ ** invoke it here.
+ **
+ ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
+ ** operation should really be an SQLITE_UPDATE. This is probably
+ ** incorrect, but is convenient because at this point the new.* values
+ ** are not easily obtainable. And for the sessions module, an
+ ** SQLITE_UPDATE where the PK columns do not change is handled in the
+ ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
+ ** slightly more efficient). Since you cannot write to a PK column
+ ** using the incremental-blob API, this works. For the sessions module
+ ** anyhow.
+ */
+ sqlite3_int64 iKey;
+ iKey = sqlite3BtreeIntegerKey(p->pCsr);
+ sqlite3VdbePreUpdateHook(
+ v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
+ );
+ }
+#endif
+
+ rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
+ sqlite3BtreeLeaveCursor(p->pCsr);
+ if( rc==SQLITE_ABORT ){
+ sqlite3VdbeFinalize(v);
+ p->pStmt = 0;
+ }else{
+ v->rc = rc;
+ }
+ }
+ sqlite3Error(db, rc);
+ rc = sqlite3ApiExit(db, rc);
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+/*
+** Read data from a blob handle.
+*/
+SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
+ return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
+}
+
+/*
+** Write data to a blob handle.
+*/
+SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
+ return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
+}
+
+/*
+** Query a blob handle for the size of the data.
+**
+** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
+** so no mutex is required for access.
+*/
+SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
+ Incrblob *p = (Incrblob *)pBlob;
+ return (p && p->pStmt) ? p->nByte : 0;
+}
+
+/*
+** Move an existing blob handle to point to a different row of the same
+** database table.
+**
+** If an error occurs, or if the specified row does not exist or does not
+** contain a blob or text value, then an error code is returned and the
+** database handle error code and message set. If this happens, then all
+** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
+** immediately return SQLITE_ABORT.
+*/
+SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
+ int rc;
+ Incrblob *p = (Incrblob *)pBlob;
+ sqlite3 *db;
+
+ if( p==0 ) return SQLITE_MISUSE_BKPT;
+ db = p->db;
+ sqlite3_mutex_enter(db->mutex);
+
+ if( p->pStmt==0 ){
+ /* If there is no statement handle, then the blob-handle has
+ ** already been invalidated. Return SQLITE_ABORT in this case.
+ */
+ rc = SQLITE_ABORT;
+ }else{
+ char *zErr;
+ rc = blobSeekToRow(p, iRow, &zErr);
+ if( rc!=SQLITE_OK ){
+ sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
+ sqlite3DbFree(db, zErr);
+ }
+ assert( rc!=SQLITE_SCHEMA );
+ }
+
+ rc = sqlite3ApiExit(db, rc);
+ assert( rc==SQLITE_OK || p->pStmt==0 );
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
+
+/************** End of vdbeblob.c ********************************************/
+/************** Begin file vdbesort.c ****************************************/
+/*
+** 2011-07-09
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code for the VdbeSorter object, used in concert with
+** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
+** or by SELECT statements with ORDER BY clauses that cannot be satisfied
+** using indexes and without LIMIT clauses.
+**
+** The VdbeSorter object implements a multi-threaded external merge sort
+** algorithm that is efficient even if the number of elements being sorted
+** exceeds the available memory.
+**
+** Here is the (internal, non-API) interface between this module and the
+** rest of the SQLite system:
+**
+** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
+**
+** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
+** object. The row is a binary blob in the
+** OP_MakeRecord format that contains both
+** the ORDER BY key columns and result columns
+** in the case of a SELECT w/ ORDER BY, or
+** the complete record for an index entry
+** in the case of a CREATE INDEX.
+**
+** sqlite3VdbeSorterRewind() Sort all content previously added.
+** Position the read cursor on the
+** first sorted element.
+**
+** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
+** element.
+**
+** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
+** row currently under the read cursor.
+**
+** sqlite3VdbeSorterCompare() Compare the binary blob for the row
+** currently under the read cursor against
+** another binary blob X and report if
+** X is strictly less than the read cursor.
+** Used to enforce uniqueness in a
+** CREATE UNIQUE INDEX statement.
+**
+** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
+** all resources.
+**
+** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
+** is like Close() followed by Init() only
+** much faster.
+**
+** The interfaces above must be called in a particular order. Write() can
+** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
+** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
+**
+** Init()
+** for each record: Write()
+** Rewind()
+** Rowkey()/Compare()
+** Next()
+** Close()
+**
+** Algorithm:
+**
+** Records passed to the sorter via calls to Write() are initially held
+** unsorted in main memory. Assuming the amount of memory used never exceeds
+** a threshold, when Rewind() is called the set of records is sorted using
+** an in-memory merge sort. In this case, no temporary files are required
+** and subsequent calls to Rowkey(), Next() and Compare() read records
+** directly from main memory.
+**
+** If the amount of space used to store records in main memory exceeds the
+** threshold, then the set of records currently in memory are sorted and
+** written to a temporary file in "Packed Memory Array" (PMA) format.
+** A PMA created at this point is known as a "level-0 PMA". Higher levels
+** of PMAs may be created by merging existing PMAs together - for example
+** merging two or more level-0 PMAs together creates a level-1 PMA.
+**
+** The threshold for the amount of main memory to use before flushing
+** records to a PMA is roughly the same as the limit configured for the
+** page-cache of the main database. Specifically, the threshold is set to
+** the value returned by "PRAGMA main.page_size" multipled by
+** that returned by "PRAGMA main.cache_size", in bytes.
+**
+** If the sorter is running in single-threaded mode, then all PMAs generated
+** are appended to a single temporary file. Or, if the sorter is running in
+** multi-threaded mode then up to (N+1) temporary files may be opened, where
+** N is the configured number of worker threads. In this case, instead of
+** sorting the records and writing the PMA to a temporary file itself, the
+** calling thread usually launches a worker thread to do so. Except, if
+** there are already N worker threads running, the main thread does the work
+** itself.
+**
+** The sorter is running in multi-threaded mode if (a) the library was built
+** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
+** than zero, and (b) worker threads have been enabled at runtime by calling
+** "PRAGMA threads=N" with some value of N greater than 0.
+**
+** When Rewind() is called, any data remaining in memory is flushed to a
+** final PMA. So at this point the data is stored in some number of sorted
+** PMAs within temporary files on disk.
+**
+** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
+** sorter is running in single-threaded mode, then these PMAs are merged
+** incrementally as keys are retreived from the sorter by the VDBE. The
+** MergeEngine object, described in further detail below, performs this
+** merge.
+**
+** Or, if running in multi-threaded mode, then a background thread is
+** launched to merge the existing PMAs. Once the background thread has
+** merged T bytes of data into a single sorted PMA, the main thread
+** begins reading keys from that PMA while the background thread proceeds
+** with merging the next T bytes of data. And so on.
+**
+** Parameter T is set to half the value of the memory threshold used
+** by Write() above to determine when to create a new PMA.
+**
+** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
+** Rewind() is called, then a hierarchy of incremental-merges is used.
+** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
+** disk are merged together. Then T bytes of data from the second set, and
+** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
+** PMAs at a time. This done is to improve locality.
+**
+** If running in multi-threaded mode and there are more than
+** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
+** than one background thread may be created. Specifically, there may be
+** one background thread for each temporary file on disk, and one background
+** thread to merge the output of each of the others to a single PMA for
+** the main thread to read from.
+*/
+/* #include "sqliteInt.h" */
+/* #include "vdbeInt.h" */
+
+/*
+** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
+** messages to stderr that may be helpful in understanding the performance
+** characteristics of the sorter in multi-threaded mode.
+*/
+#if 0
+# define SQLITE_DEBUG_SORTER_THREADS 1
+#endif
+
+/*
+** Hard-coded maximum amount of data to accumulate in memory before flushing
+** to a level 0 PMA. The purpose of this limit is to prevent various integer
+** overflows. 512MiB.
+*/
+#define SQLITE_MAX_PMASZ (1<<29)
+
+/*
+** Private objects used by the sorter
+*/
+typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
+typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
+typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
+typedef struct SorterRecord SorterRecord; /* A record being sorted */
+typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
+typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
+typedef struct SorterList SorterList; /* In-memory list of records */
+typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
+
+/*
+** A container for a temp file handle and the current amount of data
+** stored in the file.
+*/
+struct SorterFile {
+ sqlite3_file *pFd; /* File handle */
+ i64 iEof; /* Bytes of data stored in pFd */
+};
+
+/*
+** An in-memory list of objects to be sorted.
+**
+** If aMemory==0 then each object is allocated separately and the objects
+** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
+** are stored in the aMemory[] bulk memory, one right after the other, and
+** are connected using SorterRecord.u.iNext.
+*/
+struct SorterList {
+ SorterRecord *pList; /* Linked list of records */
+ u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
+ int szPMA; /* Size of pList as PMA in bytes */
+};
+
+/*
+** The MergeEngine object is used to combine two or more smaller PMAs into
+** one big PMA using a merge operation. Separate PMAs all need to be
+** combined into one big PMA in order to be able to step through the sorted
+** records in order.
+**
+** The aReadr[] array contains a PmaReader object for each of the PMAs being
+** merged. An aReadr[] object either points to a valid key or else is at EOF.
+** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
+** For the purposes of the paragraphs below, we assume that the array is
+** actually N elements in size, where N is the smallest power of 2 greater
+** to or equal to the number of PMAs being merged. The extra aReadr[] elements
+** are treated as if they are empty (always at EOF).
+**
+** The aTree[] array is also N elements in size. The value of N is stored in
+** the MergeEngine.nTree variable.
+**
+** The final (N/2) elements of aTree[] contain the results of comparing
+** pairs of PMA keys together. Element i contains the result of
+** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
+** aTree element is set to the index of it.
+**
+** For the purposes of this comparison, EOF is considered greater than any
+** other key value. If the keys are equal (only possible with two EOF
+** values), it doesn't matter which index is stored.
+**
+** The (N/4) elements of aTree[] that precede the final (N/2) described
+** above contains the index of the smallest of each block of 4 PmaReaders
+** And so on. So that aTree[1] contains the index of the PmaReader that
+** currently points to the smallest key value. aTree[0] is unused.
+**
+** Example:
+**
+** aReadr[0] -> Banana
+** aReadr[1] -> Feijoa
+** aReadr[2] -> Elderberry
+** aReadr[3] -> Currant
+** aReadr[4] -> Grapefruit
+** aReadr[5] -> Apple
+** aReadr[6] -> Durian
+** aReadr[7] -> EOF
+**
+** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
+**
+** The current element is "Apple" (the value of the key indicated by
+** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
+** be advanced to the next key in its segment. Say the next key is
+** "Eggplant":
+**
+** aReadr[5] -> Eggplant
+**
+** The contents of aTree[] are updated first by comparing the new PmaReader
+** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
+** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
+** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
+** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
+** so the value written into element 1 of the array is 0. As follows:
+**
+** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
+**
+** In other words, each time we advance to the next sorter element, log2(N)
+** key comparison operations are required, where N is the number of segments
+** being merged (rounded up to the next power of 2).
+*/
+struct MergeEngine {
+ int nTree; /* Used size of aTree/aReadr (power of 2) */
+ SortSubtask *pTask; /* Used by this thread only */
+ int *aTree; /* Current state of incremental merge */
+ PmaReader *aReadr; /* Array of PmaReaders to merge data from */
+};
+
+/*
+** This object represents a single thread of control in a sort operation.
+** Exactly VdbeSorter.nTask instances of this object are allocated
+** as part of each VdbeSorter object. Instances are never allocated any
+** other way. VdbeSorter.nTask is set to the number of worker threads allowed
+** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
+** single-threaded operation, there is exactly one instance of this object
+** and for multi-threaded operation there are two or more instances.
+**
+** Essentially, this structure contains all those fields of the VdbeSorter
+** structure for which each thread requires a separate instance. For example,
+** each thread requries its own UnpackedRecord object to unpack records in
+** as part of comparison operations.
+**
+** Before a background thread is launched, variable bDone is set to 0. Then,
+** right before it exits, the thread itself sets bDone to 1. This is used for
+** two purposes:
+**
+** 1. When flushing the contents of memory to a level-0 PMA on disk, to
+** attempt to select a SortSubtask for which there is not already an
+** active background thread (since doing so causes the main thread
+** to block until it finishes).
+**
+** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
+** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
+** block provoke debugging output.
+**
+** In both cases, the effects of the main thread seeing (bDone==0) even
+** after the thread has finished are not dire. So we don't worry about
+** memory barriers and such here.
+*/
+typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
+struct SortSubtask {
+ SQLiteThread *pThread; /* Background thread, if any */
+ int bDone; /* Set if thread is finished but not joined */
+ VdbeSorter *pSorter; /* Sorter that owns this sub-task */
+ UnpackedRecord *pUnpacked; /* Space to unpack a record */
+ SorterList list; /* List for thread to write to a PMA */
+ int nPMA; /* Number of PMAs currently in file */
+ SorterCompare xCompare; /* Compare function to use */
+ SorterFile file; /* Temp file for level-0 PMAs */
+ SorterFile file2; /* Space for other PMAs */
+};
+
+
+/*
+** Main sorter structure. A single instance of this is allocated for each
+** sorter cursor created by the VDBE.
+**
+** mxKeysize:
+** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
+** this variable is updated so as to be set to the size on disk of the
+** largest record in the sorter.
+*/
+struct VdbeSorter {
+ int mnPmaSize; /* Minimum PMA size, in bytes */
+ int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
+ int mxKeysize; /* Largest serialized key seen so far */
+ int pgsz; /* Main database page size */
+ PmaReader *pReader; /* Readr data from here after Rewind() */
+ MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
+ sqlite3 *db; /* Database connection */
+ KeyInfo *pKeyInfo; /* How to compare records */
+ UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
+ SorterList list; /* List of in-memory records */
+ int iMemory; /* Offset of free space in list.aMemory */
+ int nMemory; /* Size of list.aMemory allocation in bytes */
+ u8 bUsePMA; /* True if one or more PMAs created */
+ u8 bUseThreads; /* True to use background threads */
+ u8 iPrev; /* Previous thread used to flush PMA */
+ u8 nTask; /* Size of aTask[] array */
+ u8 typeMask;
+ SortSubtask aTask[1]; /* One or more subtasks */
+};
+
+#define SORTER_TYPE_INTEGER 0x01
+#define SORTER_TYPE_TEXT 0x02
+
+/*
+** An instance of the following object is used to read records out of a
+** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
+** aKey might point into aMap or into aBuffer. If neither of those locations
+** contain a contiguous representation of the key, then aAlloc is allocated
+** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
+**
+** pFd==0 at EOF.
+*/
+struct PmaReader {
+ i64 iReadOff; /* Current read offset */
+ i64 iEof; /* 1 byte past EOF for this PmaReader */
+ int nAlloc; /* Bytes of space at aAlloc */
+ int nKey; /* Number of bytes in key */
+ sqlite3_file *pFd; /* File handle we are reading from */
+ u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
+ u8 *aKey; /* Pointer to current key */
+ u8 *aBuffer; /* Current read buffer */
+ int nBuffer; /* Size of read buffer in bytes */
+ u8 *aMap; /* Pointer to mapping of entire file */
+ IncrMerger *pIncr; /* Incremental merger */
+};
+
+/*
+** Normally, a PmaReader object iterates through an existing PMA stored
+** within a temp file. However, if the PmaReader.pIncr variable points to
+** an object of the following type, it may be used to iterate/merge through
+** multiple PMAs simultaneously.
+**
+** There are two types of IncrMerger object - single (bUseThread==0) and
+** multi-threaded (bUseThread==1).
+**
+** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
+** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
+** size. When the IncrMerger is initialized, it reads enough data from
+** pMerger to populate aFile[0]. It then sets variables within the
+** corresponding PmaReader object to read from that file and kicks off
+** a background thread to populate aFile[1] with the next mxSz bytes of
+** sorted record data from pMerger.
+**
+** When the PmaReader reaches the end of aFile[0], it blocks until the
+** background thread has finished populating aFile[1]. It then exchanges
+** the contents of the aFile[0] and aFile[1] variables within this structure,
+** sets the PmaReader fields to read from the new aFile[0] and kicks off
+** another background thread to populate the new aFile[1]. And so on, until
+** the contents of pMerger are exhausted.
+**
+** A single-threaded IncrMerger does not open any temporary files of its
+** own. Instead, it has exclusive access to mxSz bytes of space beginning
+** at offset iStartOff of file pTask->file2. And instead of using a
+** background thread to prepare data for the PmaReader, with a single
+** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
+** keys from pMerger by the calling thread whenever the PmaReader runs out
+** of data.
+*/
+struct IncrMerger {
+ SortSubtask *pTask; /* Task that owns this merger */
+ MergeEngine *pMerger; /* Merge engine thread reads data from */
+ i64 iStartOff; /* Offset to start writing file at */
+ int mxSz; /* Maximum bytes of data to store */
+ int bEof; /* Set to true when merge is finished */
+ int bUseThread; /* True to use a bg thread for this object */
+ SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
+};
+
+/*
+** An instance of this object is used for writing a PMA.
+**
+** The PMA is written one record at a time. Each record is of an arbitrary
+** size. But I/O is more efficient if it occurs in page-sized blocks where
+** each block is aligned on a page boundary. This object caches writes to
+** the PMA so that aligned, page-size blocks are written.
+*/
+struct PmaWriter {
+ int eFWErr; /* Non-zero if in an error state */
+ u8 *aBuffer; /* Pointer to write buffer */
+ int nBuffer; /* Size of write buffer in bytes */
+ int iBufStart; /* First byte of buffer to write */
+ int iBufEnd; /* Last byte of buffer to write */
+ i64 iWriteOff; /* Offset of start of buffer in file */
+ sqlite3_file *pFd; /* File handle to write to */
+};
+
+/*
+** This object is the header on a single record while that record is being
+** held in memory and prior to being written out as part of a PMA.
+**
+** How the linked list is connected depends on how memory is being managed
+** by this module. If using a separate allocation for each in-memory record
+** (VdbeSorter.list.aMemory==0), then the list is always connected using the
+** SorterRecord.u.pNext pointers.
+**
+** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
+** then while records are being accumulated the list is linked using the
+** SorterRecord.u.iNext offset. This is because the aMemory[] array may
+** be sqlite3Realloc()ed while records are being accumulated. Once the VM
+** has finished passing records to the sorter, or when the in-memory buffer
+** is full, the list is sorted. As part of the sorting process, it is
+** converted to use the SorterRecord.u.pNext pointers. See function
+** vdbeSorterSort() for details.
+*/
+struct SorterRecord {
+ int nVal; /* Size of the record in bytes */
+ union {
+ SorterRecord *pNext; /* Pointer to next record in list */
+ int iNext; /* Offset within aMemory of next record */
+ } u;
+ /* The data for the record immediately follows this header */
+};
+
+/* Return a pointer to the buffer containing the record data for SorterRecord
+** object p. Should be used as if:
+**
+** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
+*/
+#define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
+
+
+/* Maximum number of PMAs that a single MergeEngine can merge */
+#define SORTER_MAX_MERGE_COUNT 16
+
+static int vdbeIncrSwap(IncrMerger*);
+static void vdbeIncrFree(IncrMerger *);
+
+/*
+** Free all memory belonging to the PmaReader object passed as the
+** argument. All structure fields are set to zero before returning.
+*/
+static void vdbePmaReaderClear(PmaReader *pReadr){
+ sqlite3_free(pReadr->aAlloc);
+ sqlite3_free(pReadr->aBuffer);
+ if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
+ vdbeIncrFree(pReadr->pIncr);
+ memset(pReadr, 0, sizeof(PmaReader));
+}
+
+/*
+** Read the next nByte bytes of data from the PMA p.
+** If successful, set *ppOut to point to a buffer containing the data
+** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
+** error code.
+**
+** The buffer returned in *ppOut is only valid until the
+** next call to this function.
+*/
+static int vdbePmaReadBlob(
+ PmaReader *p, /* PmaReader from which to take the blob */
+ int nByte, /* Bytes of data to read */
+ u8 **ppOut /* OUT: Pointer to buffer containing data */
+){
+ int iBuf; /* Offset within buffer to read from */
+ int nAvail; /* Bytes of data available in buffer */
+
+ if( p->aMap ){
+ *ppOut = &p->aMap[p->iReadOff];
+ p->iReadOff += nByte;
+ return SQLITE_OK;
+ }
+
+ assert( p->aBuffer );
+
+ /* If there is no more data to be read from the buffer, read the next
+ ** p->nBuffer bytes of data from the file into it. Or, if there are less
+ ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
+ iBuf = p->iReadOff % p->nBuffer;
+ if( iBuf==0 ){
+ int nRead; /* Bytes to read from disk */
+ int rc; /* sqlite3OsRead() return code */
+
+ /* Determine how many bytes of data to read. */
+ if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
+ nRead = p->nBuffer;
+ }else{
+ nRead = (int)(p->iEof - p->iReadOff);
+ }
+ assert( nRead>0 );
+
+ /* Readr data from the file. Return early if an error occurs. */
+ rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
+ assert( rc!=SQLITE_IOERR_SHORT_READ );
+ if( rc!=SQLITE_OK ) return rc;
+ }
+ nAvail = p->nBuffer - iBuf;
+
+ if( nByte<=nAvail ){
+ /* The requested data is available in the in-memory buffer. In this
+ ** case there is no need to make a copy of the data, just return a
+ ** pointer into the buffer to the caller. */
+ *ppOut = &p->aBuffer[iBuf];
+ p->iReadOff += nByte;
+ }else{
+ /* The requested data is not all available in the in-memory buffer.
+ ** In this case, allocate space at p->aAlloc[] to copy the requested
+ ** range into. Then return a copy of pointer p->aAlloc to the caller. */
+ int nRem; /* Bytes remaining to copy */
+
+ /* Extend the p->aAlloc[] allocation if required. */
+ if( p->nAlloc<nByte ){
+ u8 *aNew;
+ sqlite3_int64 nNew = MAX(128, 2*(sqlite3_int64)p->nAlloc);
+ while( nByte>nNew ) nNew = nNew*2;
+ aNew = sqlite3Realloc(p->aAlloc, nNew);
+ if( !aNew ) return SQLITE_NOMEM_BKPT;
+ p->nAlloc = nNew;
+ p->aAlloc = aNew;
+ }
+
+ /* Copy as much data as is available in the buffer into the start of
+ ** p->aAlloc[]. */
+ memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
+ p->iReadOff += nAvail;
+ nRem = nByte - nAvail;
+
+ /* The following loop copies up to p->nBuffer bytes per iteration into
+ ** the p->aAlloc[] buffer. */
+ while( nRem>0 ){
+ int rc; /* vdbePmaReadBlob() return code */
+ int nCopy; /* Number of bytes to copy */
+ u8 *aNext; /* Pointer to buffer to copy data from */
+
+ nCopy = nRem;
+ if( nRem>p->nBuffer ) nCopy = p->nBuffer;
+ rc = vdbePmaReadBlob(p, nCopy, &aNext);
+ if( rc!=SQLITE_OK ) return rc;
+ assert( aNext!=p->aAlloc );
+ memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
+ nRem -= nCopy;
+ }
+
+ *ppOut = p->aAlloc;
+ }
+
+ return SQLITE_OK;
+}
+
+/*
+** Read a varint from the stream of data accessed by p. Set *pnOut to
+** the value read.
+*/
+static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
+ int iBuf;
+
+ if( p->aMap ){
+ p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
+ }else{
+ iBuf = p->iReadOff % p->nBuffer;
+ if( iBuf && (p->nBuffer-iBuf)>=9 ){
+ p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
+ }else{
+ u8 aVarint[16], *a;
+ int i = 0, rc;
+ do{
+ rc = vdbePmaReadBlob(p, 1, &a);
+ if( rc ) return rc;
+ aVarint[(i++)&0xf] = a[0];
+ }while( (a[0]&0x80)!=0 );
+ sqlite3GetVarint(aVarint, pnOut);
+ }
+ }
+
+ return SQLITE_OK;
+}
+
+/*
+** Attempt to memory map file pFile. If successful, set *pp to point to the
+** new mapping and return SQLITE_OK. If the mapping is not attempted
+** (because the file is too large or the VFS layer is configured not to use
+** mmap), return SQLITE_OK and set *pp to NULL.
+**
+** Or, if an error occurs, return an SQLite error code. The final value of
+** *pp is undefined in this case.
+*/
+static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
+ int rc = SQLITE_OK;
+ if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
+ sqlite3_file *pFd = pFile->pFd;
+ if( pFd->pMethods->iVersion>=3 ){
+ rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
+ testcase( rc!=SQLITE_OK );
+ }
+ }
+ return rc;
+}
+
+/*
+** Attach PmaReader pReadr to file pFile (if it is not already attached to
+** that file) and seek it to offset iOff within the file. Return SQLITE_OK
+** if successful, or an SQLite error code if an error occurs.
+*/
+static int vdbePmaReaderSeek(
+ SortSubtask *pTask, /* Task context */
+ PmaReader *pReadr, /* Reader whose cursor is to be moved */
+ SorterFile *pFile, /* Sorter file to read from */
+ i64 iOff /* Offset in pFile */
+){
+ int rc = SQLITE_OK;
+
+ assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
+
+ if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
+ if( pReadr->aMap ){
+ sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
+ pReadr->aMap = 0;
+ }
+ pReadr->iReadOff = iOff;
+ pReadr->iEof = pFile->iEof;
+ pReadr->pFd = pFile->pFd;
+
+ rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
+ if( rc==SQLITE_OK && pReadr->aMap==0 ){
+ int pgsz = pTask->pSorter->pgsz;
+ int iBuf = pReadr->iReadOff % pgsz;
+ if( pReadr->aBuffer==0 ){
+ pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
+ if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
+ pReadr->nBuffer = pgsz;
+ }
+ if( rc==SQLITE_OK && iBuf ){
+ int nRead = pgsz - iBuf;
+ if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
+ nRead = (int)(pReadr->iEof - pReadr->iReadOff);
+ }
+ rc = sqlite3OsRead(
+ pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
+ );
+ testcase( rc!=SQLITE_OK );
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
+** no error occurs, or an SQLite error code if one does.
+*/
+static int vdbePmaReaderNext(PmaReader *pReadr){
+ int rc = SQLITE_OK; /* Return Code */
+ u64 nRec = 0; /* Size of record in bytes */
+
+
+ if( pReadr->iReadOff>=pReadr->iEof ){
+ IncrMerger *pIncr = pReadr->pIncr;
+ int bEof = 1;
+ if( pIncr ){
+ rc = vdbeIncrSwap(pIncr);
+ if( rc==SQLITE_OK && pIncr->bEof==0 ){
+ rc = vdbePmaReaderSeek(
+ pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
+ );
+ bEof = 0;
+ }
+ }
+
+ if( bEof ){
+ /* This is an EOF condition */
+ vdbePmaReaderClear(pReadr);
+ testcase( rc!=SQLITE_OK );
+ return rc;
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = vdbePmaReadVarint(pReadr, &nRec);
+ }
+ if( rc==SQLITE_OK ){
+ pReadr->nKey = (int)nRec;
+ rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
+ testcase( rc!=SQLITE_OK );
+ }
+
+ return rc;
+}
+
+/*
+** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
+** starting at offset iStart and ending at offset iEof-1. This function
+** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
+** PMA is empty).
+**
+** If the pnByte parameter is NULL, then it is assumed that the file
+** contains a single PMA, and that that PMA omits the initial length varint.
+*/
+static int vdbePmaReaderInit(
+ SortSubtask *pTask, /* Task context */
+ SorterFile *pFile, /* Sorter file to read from */
+ i64 iStart, /* Start offset in pFile */
+ PmaReader *pReadr, /* PmaReader to populate */
+ i64 *pnByte /* IN/OUT: Increment this value by PMA size */
+){
+ int rc;
+
+ assert( pFile->iEof>iStart );
+ assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
+ assert( pReadr->aBuffer==0 );
+ assert( pReadr->aMap==0 );
+
+ rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
+ if( rc==SQLITE_OK ){
+ u64 nByte = 0; /* Size of PMA in bytes */
+ rc = vdbePmaReadVarint(pReadr, &nByte);
+ pReadr->iEof = pReadr->iReadOff + nByte;
+ *pnByte += nByte;
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = vdbePmaReaderNext(pReadr);
+ }
+ return rc;
+}
+
+/*
+** A version of vdbeSorterCompare() that assumes that it has already been
+** determined that the first field of key1 is equal to the first field of
+** key2.
+*/
+static int vdbeSorterCompareTail(
+ SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
+ int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
+ const void *pKey1, int nKey1, /* Left side of comparison */
+ const void *pKey2, int nKey2 /* Right side of comparison */
+){
+ UnpackedRecord *r2 = pTask->pUnpacked;
+ if( *pbKey2Cached==0 ){
+ sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
+ *pbKey2Cached = 1;
+ }
+ return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
+}
+
+/*
+** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
+** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
+** used by the comparison. Return the result of the comparison.
+**
+** If IN/OUT parameter *pbKey2Cached is true when this function is called,
+** it is assumed that (pTask->pUnpacked) contains the unpacked version
+** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
+** version of key2 and *pbKey2Cached set to true before returning.
+**
+** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
+** to SQLITE_NOMEM.
+*/
+static int vdbeSorterCompare(
+ SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
+ int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
+ const void *pKey1, int nKey1, /* Left side of comparison */
+ const void *pKey2, int nKey2 /* Right side of comparison */
+){
+ UnpackedRecord *r2 = pTask->pUnpacked;
+ if( !*pbKey2Cached ){
+ sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
+ *pbKey2Cached = 1;
+ }
+ return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
+}
+
+/*
+** A specially optimized version of vdbeSorterCompare() that assumes that
+** the first field of each key is a TEXT value and that the collation
+** sequence to compare them with is BINARY.
+*/
+static int vdbeSorterCompareText(
+ SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
+ int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
+ const void *pKey1, int nKey1, /* Left side of comparison */
+ const void *pKey2, int nKey2 /* Right side of comparison */
+){
+ const u8 * const p1 = (const u8 * const)pKey1;
+ const u8 * const p2 = (const u8 * const)pKey2;
+ const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
+ const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
+
+ int n1;
+ int n2;
+ int res;
+
+ getVarint32NR(&p1[1], n1);
+ getVarint32NR(&p2[1], n2);
+ res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
+ if( res==0 ){
+ res = n1 - n2;
+ }
+
+ if( res==0 ){
+ if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
+ res = vdbeSorterCompareTail(
+ pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
+ );
+ }
+ }else{
+ assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );
+ if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){
+ res = res * -1;
+ }
+ }
+
+ return res;
+}
+
+/*
+** A specially optimized version of vdbeSorterCompare() that assumes that
+** the first field of each key is an INTEGER value.
+*/
+static int vdbeSorterCompareInt(
+ SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
+ int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
+ const void *pKey1, int nKey1, /* Left side of comparison */
+ const void *pKey2, int nKey2 /* Right side of comparison */
+){
+ const u8 * const p1 = (const u8 * const)pKey1;
+ const u8 * const p2 = (const u8 * const)pKey2;
+ const int s1 = p1[1]; /* Left hand serial type */
+ const int s2 = p2[1]; /* Right hand serial type */
+ const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
+ const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
+ int res; /* Return value */
+
+ assert( (s1>0 && s1<7) || s1==8 || s1==9 );
+ assert( (s2>0 && s2<7) || s2==8 || s2==9 );
+
+ if( s1==s2 ){
+ /* The two values have the same sign. Compare using memcmp(). */
+ static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
+ const u8 n = aLen[s1];
+ int i;
+ res = 0;
+ for(i=0; i<n; i++){
+ if( (res = v1[i] - v2[i])!=0 ){
+ if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
+ res = v1[0] & 0x80 ? -1 : +1;
+ }
+ break;
+ }
+ }
+ }else if( s1>7 && s2>7 ){
+ res = s1 - s2;
+ }else{
+ if( s2>7 ){
+ res = +1;
+ }else if( s1>7 ){
+ res = -1;
+ }else{
+ res = s1 - s2;
+ }
+ assert( res!=0 );
+
+ if( res>0 ){
+ if( *v1 & 0x80 ) res = -1;
+ }else{
+ if( *v2 & 0x80 ) res = +1;
+ }
+ }
+
+ if( res==0 ){
+ if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
+ res = vdbeSorterCompareTail(
+ pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
+ );
+ }
+ }else if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){
+ assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );
+ res = res * -1;
+ }
+
+ return res;
+}
+
+/*
+** Initialize the temporary index cursor just opened as a sorter cursor.
+**
+** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
+** to determine the number of fields that should be compared from the
+** records being sorted. However, if the value passed as argument nField
+** is non-zero and the sorter is able to guarantee a stable sort, nField
+** is used instead. This is used when sorting records for a CREATE INDEX
+** statement. In this case, keys are always delivered to the sorter in
+** order of the primary key, which happens to be make up the final part
+** of the records being sorted. So if the sort is stable, there is never
+** any reason to compare PK fields and they can be ignored for a small
+** performance boost.
+**
+** The sorter can guarantee a stable sort when running in single-threaded
+** mode, but not in multi-threaded mode.
+**
+** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
+*/
+SQLITE_PRIVATE int sqlite3VdbeSorterInit(
+ sqlite3 *db, /* Database connection (for malloc()) */
+ int nField, /* Number of key fields in each record */
+ VdbeCursor *pCsr /* Cursor that holds the new sorter */
+){
+ int pgsz; /* Page size of main database */
+ int i; /* Used to iterate through aTask[] */
+ VdbeSorter *pSorter; /* The new sorter */
+ KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
+ int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
+ int sz; /* Size of pSorter in bytes */
+ int rc = SQLITE_OK;
+#if SQLITE_MAX_WORKER_THREADS==0
+# define nWorker 0
+#else
+ int nWorker;
+#endif
+
+ /* Initialize the upper limit on the number of worker threads */
+#if SQLITE_MAX_WORKER_THREADS>0
+ if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
+ nWorker = 0;
+ }else{
+ nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
+ }
+#endif
+
+ /* Do not allow the total number of threads (main thread + all workers)
+ ** to exceed the maximum merge count */
+#if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
+ if( nWorker>=SORTER_MAX_MERGE_COUNT ){
+ nWorker = SORTER_MAX_MERGE_COUNT-1;
+ }
+#endif
+
+ assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
+ assert( pCsr->eCurType==CURTYPE_SORTER );
+ szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
+ sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
+
+ pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
+ pCsr->uc.pSorter = pSorter;
+ if( pSorter==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ }else{
+ Btree *pBt = db->aDb[0].pBt;
+ pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
+ memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
+ pKeyInfo->db = 0;
+ if( nField && nWorker==0 ){
+ pKeyInfo->nKeyField = nField;
+ }
+ sqlite3BtreeEnter(pBt);
+ pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(pBt);
+ sqlite3BtreeLeave(pBt);
+ pSorter->nTask = nWorker + 1;
+ pSorter->iPrev = (u8)(nWorker - 1);
+ pSorter->bUseThreads = (pSorter->nTask>1);
+ pSorter->db = db;
+ for(i=0; i<pSorter->nTask; i++){
+ SortSubtask *pTask = &pSorter->aTask[i];
+ pTask->pSorter = pSorter;
+ }
+
+ if( !sqlite3TempInMemory(db) ){
+ i64 mxCache; /* Cache size in bytes*/
+ u32 szPma = sqlite3GlobalConfig.szPma;
+ pSorter->mnPmaSize = szPma * pgsz;
+
+ mxCache = db->aDb[0].pSchema->cache_size;
+ if( mxCache<0 ){
+ /* A negative cache-size value C indicates that the cache is abs(C)
+ ** KiB in size. */
+ mxCache = mxCache * -1024;
+ }else{
+ mxCache = mxCache * pgsz;
+ }
+ mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
+ pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
+
+ /* Avoid large memory allocations if the application has requested
+ ** SQLITE_CONFIG_SMALL_MALLOC. */
+ if( sqlite3GlobalConfig.bSmallMalloc==0 ){
+ assert( pSorter->iMemory==0 );
+ pSorter->nMemory = pgsz;
+ pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
+ if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
+ }
+ }
+
+ if( pKeyInfo->nAllField<13
+ && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
+ && (pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL)==0
+ ){
+ pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
+ }
+ }
+
+ return rc;
+}
+#undef nWorker /* Defined at the top of this function */
+
+/*
+** Free the list of sorted records starting at pRecord.
+*/
+static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
+ SorterRecord *p;
+ SorterRecord *pNext;
+ for(p=pRecord; p; p=pNext){
+ pNext = p->u.pNext;
+ sqlite3DbFree(db, p);
+ }
+}
+
+/*
+** Free all resources owned by the object indicated by argument pTask. All
+** fields of *pTask are zeroed before returning.
+*/
+static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
+ sqlite3DbFree(db, pTask->pUnpacked);
+#if SQLITE_MAX_WORKER_THREADS>0
+ /* pTask->list.aMemory can only be non-zero if it was handed memory
+ ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
+ if( pTask->list.aMemory ){
+ sqlite3_free(pTask->list.aMemory);
+ }else
+#endif
+ {
+ assert( pTask->list.aMemory==0 );
+ vdbeSorterRecordFree(0, pTask->list.pList);
+ }
+ if( pTask->file.pFd ){
+ sqlite3OsCloseFree(pTask->file.pFd);
+ }
+ if( pTask->file2.pFd ){
+ sqlite3OsCloseFree(pTask->file2.pFd);
+ }
+ memset(pTask, 0, sizeof(SortSubtask));
+}
+
+#ifdef SQLITE_DEBUG_SORTER_THREADS
+static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
+ i64 t;
+ int iTask = (pTask - pTask->pSorter->aTask);
+ sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
+ fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
+}
+static void vdbeSorterRewindDebug(const char *zEvent){
+ i64 t;
+ sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
+ fprintf(stderr, "%lld:X %s\n", t, zEvent);
+}
+static void vdbeSorterPopulateDebug(
+ SortSubtask *pTask,
+ const char *zEvent
+){
+ i64 t;
+ int iTask = (pTask - pTask->pSorter->aTask);
+ sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
+ fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
+}
+static void vdbeSorterBlockDebug(
+ SortSubtask *pTask,
+ int bBlocked,
+ const char *zEvent
+){
+ if( bBlocked ){
+ i64 t;
+ sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
+ fprintf(stderr, "%lld:main %s\n", t, zEvent);
+ }
+}
+#else
+# define vdbeSorterWorkDebug(x,y)
+# define vdbeSorterRewindDebug(y)
+# define vdbeSorterPopulateDebug(x,y)
+# define vdbeSorterBlockDebug(x,y,z)
+#endif
+
+#if SQLITE_MAX_WORKER_THREADS>0
+/*
+** Join thread pTask->thread.
+*/
+static int vdbeSorterJoinThread(SortSubtask *pTask){
+ int rc = SQLITE_OK;
+ if( pTask->pThread ){
+#ifdef SQLITE_DEBUG_SORTER_THREADS
+ int bDone = pTask->bDone;
+#endif
+ void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
+ vdbeSorterBlockDebug(pTask, !bDone, "enter");
+ (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
+ vdbeSorterBlockDebug(pTask, !bDone, "exit");
+ rc = SQLITE_PTR_TO_INT(pRet);
+ assert( pTask->bDone==1 );
+ pTask->bDone = 0;
+ pTask->pThread = 0;
+ }
+ return rc;
+}
+
+/*
+** Launch a background thread to run xTask(pIn).
+*/
+static int vdbeSorterCreateThread(
+ SortSubtask *pTask, /* Thread will use this task object */
+ void *(*xTask)(void*), /* Routine to run in a separate thread */
+ void *pIn /* Argument passed into xTask() */
+){
+ assert( pTask->pThread==0 && pTask->bDone==0 );
+ return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
+}
+
+/*
+** Join all outstanding threads launched by SorterWrite() to create
+** level-0 PMAs.
+*/
+static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
+ int rc = rcin;
+ int i;
+
+ /* This function is always called by the main user thread.
+ **
+ ** If this function is being called after SorterRewind() has been called,
+ ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
+ ** is currently attempt to join one of the other threads. To avoid a race
+ ** condition where this thread also attempts to join the same object, join
+ ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
+ for(i=pSorter->nTask-1; i>=0; i--){
+ SortSubtask *pTask = &pSorter->aTask[i];
+ int rc2 = vdbeSorterJoinThread(pTask);
+ if( rc==SQLITE_OK ) rc = rc2;
+ }
+ return rc;
+}
+#else
+# define vdbeSorterJoinAll(x,rcin) (rcin)
+# define vdbeSorterJoinThread(pTask) SQLITE_OK
+#endif
+
+/*
+** Allocate a new MergeEngine object capable of handling up to
+** nReader PmaReader inputs.
+**
+** nReader is automatically rounded up to the next power of two.
+** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
+*/
+static MergeEngine *vdbeMergeEngineNew(int nReader){
+ int N = 2; /* Smallest power of two >= nReader */
+ int nByte; /* Total bytes of space to allocate */
+ MergeEngine *pNew; /* Pointer to allocated object to return */
+
+ assert( nReader<=SORTER_MAX_MERGE_COUNT );
+
+ while( N<nReader ) N += N;
+ nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
+
+ pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
+ if( pNew ){
+ pNew->nTree = N;
+ pNew->pTask = 0;
+ pNew->aReadr = (PmaReader*)&pNew[1];
+ pNew->aTree = (int*)&pNew->aReadr[N];
+ }
+ return pNew;
+}
+
+/*
+** Free the MergeEngine object passed as the only argument.
+*/
+static void vdbeMergeEngineFree(MergeEngine *pMerger){
+ int i;
+ if( pMerger ){
+ for(i=0; i<pMerger->nTree; i++){
+ vdbePmaReaderClear(&pMerger->aReadr[i]);
+ }
+ }
+ sqlite3_free(pMerger);
+}
+
+/*
+** Free all resources associated with the IncrMerger object indicated by
+** the first argument.
+*/
+static void vdbeIncrFree(IncrMerger *pIncr){
+ if( pIncr ){
+#if SQLITE_MAX_WORKER_THREADS>0
+ if( pIncr->bUseThread ){
+ vdbeSorterJoinThread(pIncr->pTask);
+ if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
+ if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
+ }
+#endif
+ vdbeMergeEngineFree(pIncr->pMerger);
+ sqlite3_free(pIncr);
+ }
+}
+
+/*
+** Reset a sorting cursor back to its original empty state.
+*/
+SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
+ int i;
+ (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
+ assert( pSorter->bUseThreads || pSorter->pReader==0 );
+#if SQLITE_MAX_WORKER_THREADS>0
+ if( pSorter->pReader ){
+ vdbePmaReaderClear(pSorter->pReader);
+ sqlite3DbFree(db, pSorter->pReader);
+ pSorter->pReader = 0;
+ }
+#endif
+ vdbeMergeEngineFree(pSorter->pMerger);
+ pSorter->pMerger = 0;
+ for(i=0; i<pSorter->nTask; i++){
+ SortSubtask *pTask = &pSorter->aTask[i];
+ vdbeSortSubtaskCleanup(db, pTask);
+ pTask->pSorter = pSorter;
+ }
+ if( pSorter->list.aMemory==0 ){
+ vdbeSorterRecordFree(0, pSorter->list.pList);
+ }
+ pSorter->list.pList = 0;
+ pSorter->list.szPMA = 0;
+ pSorter->bUsePMA = 0;
+ pSorter->iMemory = 0;
+ pSorter->mxKeysize = 0;
+ sqlite3DbFree(db, pSorter->pUnpacked);
+ pSorter->pUnpacked = 0;
+}
+
+/*
+** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
+*/
+SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
+ VdbeSorter *pSorter;
+ assert( pCsr->eCurType==CURTYPE_SORTER );
+ pSorter = pCsr->uc.pSorter;
+ if( pSorter ){
+ sqlite3VdbeSorterReset(db, pSorter);
+ sqlite3_free(pSorter->list.aMemory);
+ sqlite3DbFree(db, pSorter);
+ pCsr->uc.pSorter = 0;
+ }
+}
+
+#if SQLITE_MAX_MMAP_SIZE>0
+/*
+** The first argument is a file-handle open on a temporary file. The file
+** is guaranteed to be nByte bytes or smaller in size. This function
+** attempts to extend the file to nByte bytes in size and to ensure that
+** the VFS has memory mapped it.
+**
+** Whether or not the file does end up memory mapped of course depends on
+** the specific VFS implementation.
+*/
+static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
+ if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
+ void *p = 0;
+ int chunksize = 4*1024;
+ sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
+ sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
+ sqlite3OsFetch(pFd, 0, (int)nByte, &p);
+ sqlite3OsUnfetch(pFd, 0, p);
+ }
+}
+#else
+# define vdbeSorterExtendFile(x,y,z)
+#endif
+
+/*
+** Allocate space for a file-handle and open a temporary file. If successful,
+** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
+** Otherwise, set *ppFd to 0 and return an SQLite error code.
+*/
+static int vdbeSorterOpenTempFile(
+ sqlite3 *db, /* Database handle doing sort */
+ i64 nExtend, /* Attempt to extend file to this size */
+ sqlite3_file **ppFd
+){
+ int rc;
+ if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
+ rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
+ SQLITE_OPEN_TEMP_JOURNAL |
+ SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
+ SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
+ );
+ if( rc==SQLITE_OK ){
+ i64 max = SQLITE_MAX_MMAP_SIZE;
+ sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
+ if( nExtend>0 ){
+ vdbeSorterExtendFile(db, *ppFd, nExtend);
+ }
+ }
+ return rc;
+}
+
+/*
+** If it has not already been allocated, allocate the UnpackedRecord
+** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
+** if no allocation was required), or SQLITE_NOMEM otherwise.
+*/
+static int vdbeSortAllocUnpacked(SortSubtask *pTask){
+ if( pTask->pUnpacked==0 ){
+ pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
+ if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
+ pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
+ pTask->pUnpacked->errCode = 0;
+ }
+ return SQLITE_OK;
+}
+
+
+/*
+** Merge the two sorted lists p1 and p2 into a single list.
+*/
+static SorterRecord *vdbeSorterMerge(
+ SortSubtask *pTask, /* Calling thread context */
+ SorterRecord *p1, /* First list to merge */
+ SorterRecord *p2 /* Second list to merge */
+){
+ SorterRecord *pFinal = 0;
+ SorterRecord **pp = &pFinal;
+ int bCached = 0;
+
+ assert( p1!=0 && p2!=0 );
+ for(;;){
+ int res;
+ res = pTask->xCompare(
+ pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
+ );
+
+ if( res<=0 ){
+ *pp = p1;
+ pp = &p1->u.pNext;
+ p1 = p1->u.pNext;
+ if( p1==0 ){
+ *pp = p2;
+ break;
+ }
+ }else{
+ *pp = p2;
+ pp = &p2->u.pNext;
+ p2 = p2->u.pNext;
+ bCached = 0;
+ if( p2==0 ){
+ *pp = p1;
+ break;
+ }
+ }
+ }
+ return pFinal;
+}
+
+/*
+** Return the SorterCompare function to compare values collected by the
+** sorter object passed as the only argument.
+*/
+static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
+ if( p->typeMask==SORTER_TYPE_INTEGER ){
+ return vdbeSorterCompareInt;
+ }else if( p->typeMask==SORTER_TYPE_TEXT ){
+ return vdbeSorterCompareText;
+ }
+ return vdbeSorterCompare;
+}
+
+/*
+** Sort the linked list of records headed at pTask->pList. Return
+** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
+** an error occurs.
+*/
+static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
+ int i;
+ SorterRecord *p;
+ int rc;
+ SorterRecord *aSlot[64];
+
+ rc = vdbeSortAllocUnpacked(pTask);
+ if( rc!=SQLITE_OK ) return rc;
+
+ p = pList->pList;
+ pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
+ memset(aSlot, 0, sizeof(aSlot));
+
+ while( p ){
+ SorterRecord *pNext;
+ if( pList->aMemory ){
+ if( (u8*)p==pList->aMemory ){
+ pNext = 0;
+ }else{
+ assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
+ pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
+ }
+ }else{
+ pNext = p->u.pNext;
+ }
+
+ p->u.pNext = 0;
+ for(i=0; aSlot[i]; i++){
+ p = vdbeSorterMerge(pTask, p, aSlot[i]);
+ aSlot[i] = 0;
+ }
+ aSlot[i] = p;
+ p = pNext;
+ }
+
+ p = 0;
+ for(i=0; i<ArraySize(aSlot); i++){
+ if( aSlot[i]==0 ) continue;
+ p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
+ }
+ pList->pList = p;
+
+ assert( pTask->pUnpacked->errCode==SQLITE_OK
+ || pTask->pUnpacked->errCode==SQLITE_NOMEM
+ );
+ return pTask->pUnpacked->errCode;
+}
+
+/*
+** Initialize a PMA-writer object.
+*/
+static void vdbePmaWriterInit(
+ sqlite3_file *pFd, /* File handle to write to */
+ PmaWriter *p, /* Object to populate */
+ int nBuf, /* Buffer size */
+ i64 iStart /* Offset of pFd to begin writing at */
+){
+ memset(p, 0, sizeof(PmaWriter));
+ p->aBuffer = (u8*)sqlite3Malloc(nBuf);
+ if( !p->aBuffer ){
+ p->eFWErr = SQLITE_NOMEM_BKPT;
+ }else{
+ p->iBufEnd = p->iBufStart = (iStart % nBuf);
+ p->iWriteOff = iStart - p->iBufStart;
+ p->nBuffer = nBuf;
+ p->pFd = pFd;
+ }
+}
+
+/*
+** Write nData bytes of data to the PMA. Return SQLITE_OK
+** if successful, or an SQLite error code if an error occurs.
+*/
+static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
+ int nRem = nData;
+ while( nRem>0 && p->eFWErr==0 ){
+ int nCopy = nRem;
+ if( nCopy>(p->nBuffer - p->iBufEnd) ){
+ nCopy = p->nBuffer - p->iBufEnd;
+ }
+
+ memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
+ p->iBufEnd += nCopy;
+ if( p->iBufEnd==p->nBuffer ){
+ p->eFWErr = sqlite3OsWrite(p->pFd,
+ &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
+ p->iWriteOff + p->iBufStart
+ );
+ p->iBufStart = p->iBufEnd = 0;
+ p->iWriteOff += p->nBuffer;
+ }
+ assert( p->iBufEnd<p->nBuffer );
+
+ nRem -= nCopy;
+ }
+}
+
+/*
+** Flush any buffered data to disk and clean up the PMA-writer object.
+** The results of using the PMA-writer after this call are undefined.
+** Return SQLITE_OK if flushing the buffered data succeeds or is not
+** required. Otherwise, return an SQLite error code.
+**
+** Before returning, set *piEof to the offset immediately following the
+** last byte written to the file.
+*/
+static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
+ int rc;
+ if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
+ p->eFWErr = sqlite3OsWrite(p->pFd,
+ &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
+ p->iWriteOff + p->iBufStart
+ );
+ }
+ *piEof = (p->iWriteOff + p->iBufEnd);
+ sqlite3_free(p->aBuffer);
+ rc = p->eFWErr;
+ memset(p, 0, sizeof(PmaWriter));
+ return rc;
+}
+
+/*
+** Write value iVal encoded as a varint to the PMA. Return
+** SQLITE_OK if successful, or an SQLite error code if an error occurs.
+*/
+static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
+ int nByte;
+ u8 aByte[10];
+ nByte = sqlite3PutVarint(aByte, iVal);
+ vdbePmaWriteBlob(p, aByte, nByte);
+}
+
+/*
+** Write the current contents of in-memory linked-list pList to a level-0
+** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
+** successful, or an SQLite error code otherwise.
+**
+** The format of a PMA is:
+**
+** * A varint. This varint contains the total number of bytes of content
+** in the PMA (not including the varint itself).
+**
+** * One or more records packed end-to-end in order of ascending keys.
+** Each record consists of a varint followed by a blob of data (the
+** key). The varint is the number of bytes in the blob of data.
+*/
+static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
+ sqlite3 *db = pTask->pSorter->db;
+ int rc = SQLITE_OK; /* Return code */
+ PmaWriter writer; /* Object used to write to the file */
+
+#ifdef SQLITE_DEBUG
+ /* Set iSz to the expected size of file pTask->file after writing the PMA.
+ ** This is used by an assert() statement at the end of this function. */
+ i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
+#endif
+
+ vdbeSorterWorkDebug(pTask, "enter");
+ memset(&writer, 0, sizeof(PmaWriter));
+ assert( pList->szPMA>0 );
+
+ /* If the first temporary PMA file has not been opened, open it now. */
+ if( pTask->file.pFd==0 ){
+ rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
+ assert( rc!=SQLITE_OK || pTask->file.pFd );
+ assert( pTask->file.iEof==0 );
+ assert( pTask->nPMA==0 );
+ }
+
+ /* Try to get the file to memory map */
+ if( rc==SQLITE_OK ){
+ vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
+ }
+
+ /* Sort the list */
+ if( rc==SQLITE_OK ){
+ rc = vdbeSorterSort(pTask, pList);
+ }
+
+ if( rc==SQLITE_OK ){
+ SorterRecord *p;
+ SorterRecord *pNext = 0;
+
+ vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
+ pTask->file.iEof);
+ pTask->nPMA++;
+ vdbePmaWriteVarint(&writer, pList->szPMA);
+ for(p=pList->pList; p; p=pNext){
+ pNext = p->u.pNext;
+ vdbePmaWriteVarint(&writer, p->nVal);
+ vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
+ if( pList->aMemory==0 ) sqlite3_free(p);
+ }
+ pList->pList = p;
+ rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
+ }
+
+ vdbeSorterWorkDebug(pTask, "exit");
+ assert( rc!=SQLITE_OK || pList->pList==0 );
+ assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
+ return rc;
+}
+
+/*
+** Advance the MergeEngine to its next entry.
+** Set *pbEof to true there is no next entry because
+** the MergeEngine has reached the end of all its inputs.
+**
+** Return SQLITE_OK if successful or an error code if an error occurs.
+*/
+static int vdbeMergeEngineStep(
+ MergeEngine *pMerger, /* The merge engine to advance to the next row */
+ int *pbEof /* Set TRUE at EOF. Set false for more content */
+){
+ int rc;
+ int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
+ SortSubtask *pTask = pMerger->pTask;
+
+ /* Advance the current PmaReader */
+ rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
+
+ /* Update contents of aTree[] */
+ if( rc==SQLITE_OK ){
+ int i; /* Index of aTree[] to recalculate */
+ PmaReader *pReadr1; /* First PmaReader to compare */
+ PmaReader *pReadr2; /* Second PmaReader to compare */
+ int bCached = 0;
+
+ /* Find the first two PmaReaders to compare. The one that was just
+ ** advanced (iPrev) and the one next to it in the array. */
+ pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
+ pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
+
+ for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
+ /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
+ int iRes;
+ if( pReadr1->pFd==0 ){
+ iRes = +1;
+ }else if( pReadr2->pFd==0 ){
+ iRes = -1;
+ }else{
+ iRes = pTask->xCompare(pTask, &bCached,
+ pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
+ );
+ }
+
+ /* If pReadr1 contained the smaller value, set aTree[i] to its index.
+ ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
+ ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
+ ** pKey2 to point to the record belonging to pReadr2.
+ **
+ ** Alternatively, if pReadr2 contains the smaller of the two values,
+ ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
+ ** was actually called above, then pTask->pUnpacked now contains
+ ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
+ ** vdbeSorterCompare() from decoding pReadr2 again.
+ **
+ ** If the two values were equal, then the value from the oldest
+ ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
+ ** is sorted from oldest to newest, so pReadr1 contains older values
+ ** than pReadr2 iff (pReadr1<pReadr2). */
+ if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
+ pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
+ pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
+ bCached = 0;
+ }else{
+ if( pReadr1->pFd ) bCached = 0;
+ pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
+ pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
+ }
+ }
+ *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
+ }
+
+ return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
+}
+
+#if SQLITE_MAX_WORKER_THREADS>0
+/*
+** The main routine for background threads that write level-0 PMAs.
+*/
+static void *vdbeSorterFlushThread(void *pCtx){
+ SortSubtask *pTask = (SortSubtask*)pCtx;
+ int rc; /* Return code */
+ assert( pTask->bDone==0 );
+ rc = vdbeSorterListToPMA(pTask, &pTask->list);
+ pTask->bDone = 1;
+ return SQLITE_INT_TO_PTR(rc);
+}
+#endif /* SQLITE_MAX_WORKER_THREADS>0 */
+
+/*
+** Flush the current contents of VdbeSorter.list to a new PMA, possibly
+** using a background thread.
+*/
+static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
+#if SQLITE_MAX_WORKER_THREADS==0
+ pSorter->bUsePMA = 1;
+ return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
+#else
+ int rc = SQLITE_OK;
+ int i;
+ SortSubtask *pTask = 0; /* Thread context used to create new PMA */
+ int nWorker = (pSorter->nTask-1);
+
+ /* Set the flag to indicate that at least one PMA has been written.
+ ** Or will be, anyhow. */
+ pSorter->bUsePMA = 1;
+
+ /* Select a sub-task to sort and flush the current list of in-memory
+ ** records to disk. If the sorter is running in multi-threaded mode,
+ ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
+ ** the background thread from a sub-tasks previous turn is still running,
+ ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
+ ** fall back to using the final sub-task. The first (pSorter->nTask-1)
+ ** sub-tasks are prefered as they use background threads - the final
+ ** sub-task uses the main thread. */
+ for(i=0; i<nWorker; i++){
+ int iTest = (pSorter->iPrev + i + 1) % nWorker;
+ pTask = &pSorter->aTask[iTest];
+ if( pTask->bDone ){
+ rc = vdbeSorterJoinThread(pTask);
+ }
+ if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
+ }
+
+ if( rc==SQLITE_OK ){
+ if( i==nWorker ){
+ /* Use the foreground thread for this operation */
+ rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
+ }else{
+ /* Launch a background thread for this operation */
+ u8 *aMem;
+ void *pCtx;
+
+ assert( pTask!=0 );
+ assert( pTask->pThread==0 && pTask->bDone==0 );
+ assert( pTask->list.pList==0 );
+ assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
+
+ aMem = pTask->list.aMemory;
+ pCtx = (void*)pTask;
+ pSorter->iPrev = (u8)(pTask - pSorter->aTask);
+ pTask->list = pSorter->list;
+ pSorter->list.pList = 0;
+ pSorter->list.szPMA = 0;
+ if( aMem ){
+ pSorter->list.aMemory = aMem;
+ pSorter->nMemory = sqlite3MallocSize(aMem);
+ }else if( pSorter->list.aMemory ){
+ pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
+ if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
+ }
+
+ rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
+ }
+ }
+
+ return rc;
+#endif /* SQLITE_MAX_WORKER_THREADS!=0 */
+}
+
+/*
+** Add a record to the sorter.
+*/
+SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
+ const VdbeCursor *pCsr, /* Sorter cursor */
+ Mem *pVal /* Memory cell containing record */
+){
+ VdbeSorter *pSorter;
+ int rc = SQLITE_OK; /* Return Code */
+ SorterRecord *pNew; /* New list element */
+ int bFlush; /* True to flush contents of memory to PMA */
+ int nReq; /* Bytes of memory required */
+ int nPMA; /* Bytes of PMA space required */
+ int t; /* serial type of first record field */
+
+ assert( pCsr->eCurType==CURTYPE_SORTER );
+ pSorter = pCsr->uc.pSorter;
+ getVarint32NR((const u8*)&pVal->z[1], t);
+ if( t>0 && t<10 && t!=7 ){
+ pSorter->typeMask &= SORTER_TYPE_INTEGER;
+ }else if( t>10 && (t & 0x01) ){
+ pSorter->typeMask &= SORTER_TYPE_TEXT;
+ }else{
+ pSorter->typeMask = 0;
+ }
+
+ assert( pSorter );
+
+ /* Figure out whether or not the current contents of memory should be
+ ** flushed to a PMA before continuing. If so, do so.
+ **
+ ** If using the single large allocation mode (pSorter->aMemory!=0), then
+ ** flush the contents of memory to a new PMA if (a) at least one value is
+ ** already in memory and (b) the new value will not fit in memory.
+ **
+ ** Or, if using separate allocations for each record, flush the contents
+ ** of memory to a PMA if either of the following are true:
+ **
+ ** * The total memory allocated for the in-memory list is greater
+ ** than (page-size * cache-size), or
+ **
+ ** * The total memory allocated for the in-memory list is greater
+ ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
+ */
+ nReq = pVal->n + sizeof(SorterRecord);
+ nPMA = pVal->n + sqlite3VarintLen(pVal->n);
+ if( pSorter->mxPmaSize ){
+ if( pSorter->list.aMemory ){
+ bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
+ }else{
+ bFlush = (
+ (pSorter->list.szPMA > pSorter->mxPmaSize)
+ || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
+ );
+ }
+ if( bFlush ){
+ rc = vdbeSorterFlushPMA(pSorter);
+ pSorter->list.szPMA = 0;
+ pSorter->iMemory = 0;
+ assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
+ }
+ }
+
+ pSorter->list.szPMA += nPMA;
+ if( nPMA>pSorter->mxKeysize ){
+ pSorter->mxKeysize = nPMA;
+ }
+
+ if( pSorter->list.aMemory ){
+ int nMin = pSorter->iMemory + nReq;
+
+ if( nMin>pSorter->nMemory ){
+ u8 *aNew;
+ sqlite3_int64 nNew = 2 * (sqlite3_int64)pSorter->nMemory;
+ int iListOff = -1;
+ if( pSorter->list.pList ){
+ iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
+ }
+ while( nNew < nMin ) nNew = nNew*2;
+ if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
+ if( nNew < nMin ) nNew = nMin;
+ aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
+ if( !aNew ) return SQLITE_NOMEM_BKPT;
+ if( iListOff>=0 ){
+ pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
+ }
+ pSorter->list.aMemory = aNew;
+ pSorter->nMemory = nNew;
+ }
+
+ pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
+ pSorter->iMemory += ROUND8(nReq);
+ if( pSorter->list.pList ){
+ pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
+ }
+ }else{
+ pNew = (SorterRecord *)sqlite3Malloc(nReq);
+ if( pNew==0 ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ pNew->u.pNext = pSorter->list.pList;
+ }
+
+ memcpy(SRVAL(pNew), pVal->z, pVal->n);
+ pNew->nVal = pVal->n;
+ pSorter->list.pList = pNew;
+
+ return rc;
+}
+
+/*
+** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
+** of the data stored in aFile[1] is the same as that used by regular PMAs,
+** except that the number-of-bytes varint is omitted from the start.
+*/
+static int vdbeIncrPopulate(IncrMerger *pIncr){
+ int rc = SQLITE_OK;
+ int rc2;
+ i64 iStart = pIncr->iStartOff;
+ SorterFile *pOut = &pIncr->aFile[1];
+ SortSubtask *pTask = pIncr->pTask;
+ MergeEngine *pMerger = pIncr->pMerger;
+ PmaWriter writer;
+ assert( pIncr->bEof==0 );
+
+ vdbeSorterPopulateDebug(pTask, "enter");
+
+ vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
+ while( rc==SQLITE_OK ){
+ int dummy;
+ PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
+ int nKey = pReader->nKey;
+ i64 iEof = writer.iWriteOff + writer.iBufEnd;
+
+ /* Check if the output file is full or if the input has been exhausted.
+ ** In either case exit the loop. */
+ if( pReader->pFd==0 ) break;
+ if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
+
+ /* Write the next key to the output. */
+ vdbePmaWriteVarint(&writer, nKey);
+ vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
+ assert( pIncr->pMerger->pTask==pTask );
+ rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
+ }
+
+ rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
+ if( rc==SQLITE_OK ) rc = rc2;
+ vdbeSorterPopulateDebug(pTask, "exit");
+ return rc;
+}
+
+#if SQLITE_MAX_WORKER_THREADS>0
+/*
+** The main routine for background threads that populate aFile[1] of
+** multi-threaded IncrMerger objects.
+*/
+static void *vdbeIncrPopulateThread(void *pCtx){
+ IncrMerger *pIncr = (IncrMerger*)pCtx;
+ void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
+ pIncr->pTask->bDone = 1;
+ return pRet;
+}
+
+/*
+** Launch a background thread to populate aFile[1] of pIncr.
+*/
+static int vdbeIncrBgPopulate(IncrMerger *pIncr){
+ void *p = (void*)pIncr;
+ assert( pIncr->bUseThread );
+ return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
+}
+#endif
+
+/*
+** This function is called when the PmaReader corresponding to pIncr has
+** finished reading the contents of aFile[0]. Its purpose is to "refill"
+** aFile[0] such that the PmaReader should start rereading it from the
+** beginning.
+**
+** For single-threaded objects, this is accomplished by literally reading
+** keys from pIncr->pMerger and repopulating aFile[0].
+**
+** For multi-threaded objects, all that is required is to wait until the
+** background thread is finished (if it is not already) and then swap
+** aFile[0] and aFile[1] in place. If the contents of pMerger have not
+** been exhausted, this function also launches a new background thread
+** to populate the new aFile[1].
+**
+** SQLITE_OK is returned on success, or an SQLite error code otherwise.
+*/
+static int vdbeIncrSwap(IncrMerger *pIncr){
+ int rc = SQLITE_OK;
+
+#if SQLITE_MAX_WORKER_THREADS>0
+ if( pIncr->bUseThread ){
+ rc = vdbeSorterJoinThread(pIncr->pTask);
+
+ if( rc==SQLITE_OK ){
+ SorterFile f0 = pIncr->aFile[0];
+ pIncr->aFile[0] = pIncr->aFile[1];
+ pIncr->aFile[1] = f0;
+ }
+
+ if( rc==SQLITE_OK ){
+ if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
+ pIncr->bEof = 1;
+ }else{
+ rc = vdbeIncrBgPopulate(pIncr);
+ }
+ }
+ }else
+#endif
+ {
+ rc = vdbeIncrPopulate(pIncr);
+ pIncr->aFile[0] = pIncr->aFile[1];
+ if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
+ pIncr->bEof = 1;
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Allocate and return a new IncrMerger object to read data from pMerger.
+**
+** If an OOM condition is encountered, return NULL. In this case free the
+** pMerger argument before returning.
+*/
+static int vdbeIncrMergerNew(
+ SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
+ MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
+ IncrMerger **ppOut /* Write the new IncrMerger here */
+){
+ int rc = SQLITE_OK;
+ IncrMerger *pIncr = *ppOut = (IncrMerger*)
+ (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
+ if( pIncr ){
+ pIncr->pMerger = pMerger;
+ pIncr->pTask = pTask;
+ pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
+ pTask->file2.iEof += pIncr->mxSz;
+ }else{
+ vdbeMergeEngineFree(pMerger);
+ rc = SQLITE_NOMEM_BKPT;
+ }
+ return rc;
+}
+
+#if SQLITE_MAX_WORKER_THREADS>0
+/*
+** Set the "use-threads" flag on object pIncr.
+*/
+static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
+ pIncr->bUseThread = 1;
+ pIncr->pTask->file2.iEof -= pIncr->mxSz;
+}
+#endif /* SQLITE_MAX_WORKER_THREADS>0 */
+
+
+
+/*
+** Recompute pMerger->aTree[iOut] by comparing the next keys on the
+** two PmaReaders that feed that entry. Neither of the PmaReaders
+** are advanced. This routine merely does the comparison.
+*/
+static void vdbeMergeEngineCompare(
+ MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
+ int iOut /* Store the result in pMerger->aTree[iOut] */
+){
+ int i1;
+ int i2;
+ int iRes;
+ PmaReader *p1;
+ PmaReader *p2;
+
+ assert( iOut<pMerger->nTree && iOut>0 );
+
+ if( iOut>=(pMerger->nTree/2) ){
+ i1 = (iOut - pMerger->nTree/2) * 2;
+ i2 = i1 + 1;
+ }else{
+ i1 = pMerger->aTree[iOut*2];
+ i2 = pMerger->aTree[iOut*2+1];
+ }
+
+ p1 = &pMerger->aReadr[i1];
+ p2 = &pMerger->aReadr[i2];
+
+ if( p1->pFd==0 ){
+ iRes = i2;
+ }else if( p2->pFd==0 ){
+ iRes = i1;
+ }else{
+ SortSubtask *pTask = pMerger->pTask;
+ int bCached = 0;
+ int res;
+ assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
+ res = pTask->xCompare(
+ pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
+ );
+ if( res<=0 ){
+ iRes = i1;
+ }else{
+ iRes = i2;
+ }
+ }
+
+ pMerger->aTree[iOut] = iRes;
+}
+
+/*
+** Allowed values for the eMode parameter to vdbeMergeEngineInit()
+** and vdbePmaReaderIncrMergeInit().
+**
+** Only INCRINIT_NORMAL is valid in single-threaded builds (when
+** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
+** when there exists one or more separate worker threads.
+*/
+#define INCRINIT_NORMAL 0
+#define INCRINIT_TASK 1
+#define INCRINIT_ROOT 2
+
+/*
+** Forward reference required as the vdbeIncrMergeInit() and
+** vdbePmaReaderIncrInit() routines are called mutually recursively when
+** building a merge tree.
+*/
+static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
+
+/*
+** Initialize the MergeEngine object passed as the second argument. Once this
+** function returns, the first key of merged data may be read from the
+** MergeEngine object in the usual fashion.
+**
+** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
+** objects attached to the PmaReader objects that the merger reads from have
+** already been populated, but that they have not yet populated aFile[0] and
+** set the PmaReader objects up to read from it. In this case all that is
+** required is to call vdbePmaReaderNext() on each PmaReader to point it at
+** its first key.
+**
+** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
+** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
+** to pMerger.
+**
+** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
+*/
+static int vdbeMergeEngineInit(
+ SortSubtask *pTask, /* Thread that will run pMerger */
+ MergeEngine *pMerger, /* MergeEngine to initialize */
+ int eMode /* One of the INCRINIT_XXX constants */
+){
+ int rc = SQLITE_OK; /* Return code */
+ int i; /* For looping over PmaReader objects */
+ int nTree; /* Number of subtrees to merge */
+
+ /* Failure to allocate the merge would have been detected prior to
+ ** invoking this routine */
+ assert( pMerger!=0 );
+
+ /* eMode is always INCRINIT_NORMAL in single-threaded mode */
+ assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
+
+ /* Verify that the MergeEngine is assigned to a single thread */
+ assert( pMerger->pTask==0 );
+ pMerger->pTask = pTask;
+
+ nTree = pMerger->nTree;
+ for(i=0; i<nTree; i++){
+ if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
+ /* PmaReaders should be normally initialized in order, as if they are
+ ** reading from the same temp file this makes for more linear file IO.
+ ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
+ ** in use it will block the vdbePmaReaderNext() call while it uses
+ ** the main thread to fill its buffer. So calling PmaReaderNext()
+ ** on this PmaReader before any of the multi-threaded PmaReaders takes
+ ** better advantage of multi-processor hardware. */
+ rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
+ }else{
+ rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
+ }
+ if( rc!=SQLITE_OK ) return rc;
+ }
+
+ for(i=pMerger->nTree-1; i>0; i--){
+ vdbeMergeEngineCompare(pMerger, i);
+ }
+ return pTask->pUnpacked->errCode;
+}
+
+/*
+** The PmaReader passed as the first argument is guaranteed to be an
+** incremental-reader (pReadr->pIncr!=0). This function serves to open
+** and/or initialize the temp file related fields of the IncrMerge
+** object at (pReadr->pIncr).
+**
+** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
+** in the sub-tree headed by pReadr are also initialized. Data is then
+** loaded into the buffers belonging to pReadr and it is set to point to
+** the first key in its range.
+**
+** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
+** to be a multi-threaded PmaReader and this function is being called in a
+** background thread. In this case all PmaReaders in the sub-tree are
+** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
+** pReadr is populated. However, pReadr itself is not set up to point
+** to its first key. A call to vdbePmaReaderNext() is still required to do
+** that.
+**
+** The reason this function does not call vdbePmaReaderNext() immediately
+** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
+** to block on thread (pTask->thread) before accessing aFile[1]. But, since
+** this entire function is being run by thread (pTask->thread), that will
+** lead to the current background thread attempting to join itself.
+**
+** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
+** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
+** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
+** In this case vdbePmaReaderNext() is called on all child PmaReaders and
+** the current PmaReader set to point to the first key in its range.
+**
+** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
+*/
+static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
+ int rc = SQLITE_OK;
+ IncrMerger *pIncr = pReadr->pIncr;
+ SortSubtask *pTask = pIncr->pTask;
+ sqlite3 *db = pTask->pSorter->db;
+
+ /* eMode is always INCRINIT_NORMAL in single-threaded mode */
+ assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
+
+ rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
+
+ /* Set up the required files for pIncr. A multi-theaded IncrMerge object
+ ** requires two temp files to itself, whereas a single-threaded object
+ ** only requires a region of pTask->file2. */
+ if( rc==SQLITE_OK ){
+ int mxSz = pIncr->mxSz;
+#if SQLITE_MAX_WORKER_THREADS>0
+ if( pIncr->bUseThread ){
+ rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
+ if( rc==SQLITE_OK ){
+ rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
+ }
+ }else
+#endif
+ /*if( !pIncr->bUseThread )*/{
+ if( pTask->file2.pFd==0 ){
+ assert( pTask->file2.iEof>0 );
+ rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
+ pTask->file2.iEof = 0;
+ }
+ if( rc==SQLITE_OK ){
+ pIncr->aFile[1].pFd = pTask->file2.pFd;
+ pIncr->iStartOff = pTask->file2.iEof;
+ pTask->file2.iEof += mxSz;
+ }
+ }
+ }
+
+#if SQLITE_MAX_WORKER_THREADS>0
+ if( rc==SQLITE_OK && pIncr->bUseThread ){
+ /* Use the current thread to populate aFile[1], even though this
+ ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
+ ** then this function is already running in background thread
+ ** pIncr->pTask->thread.
+ **
+ ** If this is the INCRINIT_ROOT object, then it is running in the
+ ** main VDBE thread. But that is Ok, as that thread cannot return
+ ** control to the VDBE or proceed with anything useful until the
+ ** first results are ready from this merger object anyway.
+ */
+ assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
+ rc = vdbeIncrPopulate(pIncr);
+ }
+#endif
+
+ if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
+ rc = vdbePmaReaderNext(pReadr);
+ }
+
+ return rc;
+}
+
+#if SQLITE_MAX_WORKER_THREADS>0
+/*
+** The main routine for vdbePmaReaderIncrMergeInit() operations run in
+** background threads.
+*/
+static void *vdbePmaReaderBgIncrInit(void *pCtx){
+ PmaReader *pReader = (PmaReader*)pCtx;
+ void *pRet = SQLITE_INT_TO_PTR(
+ vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
+ );
+ pReader->pIncr->pTask->bDone = 1;
+ return pRet;
+}
+#endif
+
+/*
+** If the PmaReader passed as the first argument is not an incremental-reader
+** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
+** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
+** this routine to initialize the incremental merge.
+**
+** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
+** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
+** Or, if the IncrMerger is single threaded, the same function is called
+** using the current thread.
+*/
+static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
+ IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
+ int rc = SQLITE_OK; /* Return code */
+ if( pIncr ){
+#if SQLITE_MAX_WORKER_THREADS>0
+ assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
+ if( pIncr->bUseThread ){
+ void *pCtx = (void*)pReadr;
+ rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
+ }else
+#endif
+ {
+ rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
+ }
+ }
+ return rc;
+}
+
+/*
+** Allocate a new MergeEngine object to merge the contents of nPMA level-0
+** PMAs from pTask->file. If no error occurs, set *ppOut to point to
+** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
+** to NULL and return an SQLite error code.
+**
+** When this function is called, *piOffset is set to the offset of the
+** first PMA to read from pTask->file. Assuming no error occurs, it is
+** set to the offset immediately following the last byte of the last
+** PMA before returning. If an error does occur, then the final value of
+** *piOffset is undefined.
+*/
+static int vdbeMergeEngineLevel0(
+ SortSubtask *pTask, /* Sorter task to read from */
+ int nPMA, /* Number of PMAs to read */
+ i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
+ MergeEngine **ppOut /* OUT: New merge-engine */
+){
+ MergeEngine *pNew; /* Merge engine to return */
+ i64 iOff = *piOffset;
+ int i;
+ int rc = SQLITE_OK;
+
+ *ppOut = pNew = vdbeMergeEngineNew(nPMA);
+ if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
+
+ for(i=0; i<nPMA && rc==SQLITE_OK; i++){
+ i64 nDummy = 0;
+ PmaReader *pReadr = &pNew->aReadr[i];
+ rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
+ iOff = pReadr->iEof;
+ }
+
+ if( rc!=SQLITE_OK ){
+ vdbeMergeEngineFree(pNew);
+ *ppOut = 0;
+ }
+ *piOffset = iOff;
+ return rc;
+}
+
+/*
+** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
+** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
+**
+** i.e.
+**
+** nPMA<=16 -> TreeDepth() == 0
+** nPMA<=256 -> TreeDepth() == 1
+** nPMA<=65536 -> TreeDepth() == 2
+*/
+static int vdbeSorterTreeDepth(int nPMA){
+ int nDepth = 0;
+ i64 nDiv = SORTER_MAX_MERGE_COUNT;
+ while( nDiv < (i64)nPMA ){
+ nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
+ nDepth++;
+ }
+ return nDepth;
+}
+
+/*
+** pRoot is the root of an incremental merge-tree with depth nDepth (according
+** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
+** tree, counting from zero. This function adds pLeaf to the tree.
+**
+** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
+** code is returned and pLeaf is freed.
+*/
+static int vdbeSorterAddToTree(
+ SortSubtask *pTask, /* Task context */
+ int nDepth, /* Depth of tree according to TreeDepth() */
+ int iSeq, /* Sequence number of leaf within tree */
+ MergeEngine *pRoot, /* Root of tree */
+ MergeEngine *pLeaf /* Leaf to add to tree */
+){
+ int rc = SQLITE_OK;
+ int nDiv = 1;
+ int i;
+ MergeEngine *p = pRoot;
+ IncrMerger *pIncr;
+
+ rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
+
+ for(i=1; i<nDepth; i++){
+ nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
+ }
+
+ for(i=1; i<nDepth && rc==SQLITE_OK; i++){
+ int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
+ PmaReader *pReadr = &p->aReadr[iIter];
+
+ if( pReadr->pIncr==0 ){
+ MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
+ if( pNew==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ }else{
+ rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
+ }
+ }
+ if( rc==SQLITE_OK ){
+ p = pReadr->pIncr->pMerger;
+ nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
+ }else{
+ vdbeIncrFree(pIncr);
+ }
+ return rc;
+}
+
+/*
+** This function is called as part of a SorterRewind() operation on a sorter
+** that has already written two or more level-0 PMAs to one or more temp
+** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
+** can be used to incrementally merge all PMAs on disk.
+**
+** If successful, SQLITE_OK is returned and *ppOut set to point to the
+** MergeEngine object at the root of the tree before returning. Or, if an
+** error occurs, an SQLite error code is returned and the final value
+** of *ppOut is undefined.
+*/
+static int vdbeSorterMergeTreeBuild(
+ VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
+ MergeEngine **ppOut /* Write the MergeEngine here */
+){
+ MergeEngine *pMain = 0;
+ int rc = SQLITE_OK;
+ int iTask;
+
+#if SQLITE_MAX_WORKER_THREADS>0
+ /* If the sorter uses more than one task, then create the top-level
+ ** MergeEngine here. This MergeEngine will read data from exactly
+ ** one PmaReader per sub-task. */
+ assert( pSorter->bUseThreads || pSorter->nTask==1 );
+ if( pSorter->nTask>1 ){
+ pMain = vdbeMergeEngineNew(pSorter->nTask);
+ if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
+ }
+#endif
+
+ for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
+ SortSubtask *pTask = &pSorter->aTask[iTask];
+ assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
+ if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
+ MergeEngine *pRoot = 0; /* Root node of tree for this task */
+ int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
+ i64 iReadOff = 0;
+
+ if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
+ rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
+ }else{
+ int i;
+ int iSeq = 0;
+ pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
+ if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
+ for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
+ MergeEngine *pMerger = 0; /* New level-0 PMA merger */
+ int nReader; /* Number of level-0 PMAs to merge */
+
+ nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
+ rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
+ if( rc==SQLITE_OK ){
+ rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
+ }
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+#if SQLITE_MAX_WORKER_THREADS>0
+ if( pMain!=0 ){
+ rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
+ }else
+#endif
+ {
+ assert( pMain==0 );
+ pMain = pRoot;
+ }
+ }else{
+ vdbeMergeEngineFree(pRoot);
+ }
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ vdbeMergeEngineFree(pMain);
+ pMain = 0;
+ }
+ *ppOut = pMain;
+ return rc;
+}
+
+/*
+** This function is called as part of an sqlite3VdbeSorterRewind() operation
+** on a sorter that has written two or more PMAs to temporary files. It sets
+** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
+** (for multi-threaded sorters) so that it can be used to iterate through
+** all records stored in the sorter.
+**
+** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
+*/
+static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
+ int rc; /* Return code */
+ SortSubtask *pTask0 = &pSorter->aTask[0];
+ MergeEngine *pMain = 0;
+#if SQLITE_MAX_WORKER_THREADS
+ sqlite3 *db = pTask0->pSorter->db;
+ int i;
+ SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
+ for(i=0; i<pSorter->nTask; i++){
+ pSorter->aTask[i].xCompare = xCompare;
+ }
+#endif
+
+ rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
+ if( rc==SQLITE_OK ){
+#if SQLITE_MAX_WORKER_THREADS
+ assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
+ if( pSorter->bUseThreads ){
+ int iTask;
+ PmaReader *pReadr = 0;
+ SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
+ rc = vdbeSortAllocUnpacked(pLast);
+ if( rc==SQLITE_OK ){
+ pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
+ pSorter->pReader = pReadr;
+ if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
+ }
+ if( rc==SQLITE_OK ){
+ rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
+ if( rc==SQLITE_OK ){
+ vdbeIncrMergerSetThreads(pReadr->pIncr);
+ for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
+ IncrMerger *pIncr;
+ if( (pIncr = pMain->aReadr[iTask].pIncr) ){
+ vdbeIncrMergerSetThreads(pIncr);
+ assert( pIncr->pTask!=pLast );
+ }
+ }
+ for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
+ /* Check that:
+ **
+ ** a) The incremental merge object is configured to use the
+ ** right task, and
+ ** b) If it is using task (nTask-1), it is configured to run
+ ** in single-threaded mode. This is important, as the
+ ** root merge (INCRINIT_ROOT) will be using the same task
+ ** object.
+ */
+ PmaReader *p = &pMain->aReadr[iTask];
+ assert( p->pIncr==0 || (
+ (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
+ && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
+ ));
+ rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
+ }
+ }
+ pMain = 0;
+ }
+ if( rc==SQLITE_OK ){
+ rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
+ }
+ }else
+#endif
+ {
+ rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
+ pSorter->pMerger = pMain;
+ pMain = 0;
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ vdbeMergeEngineFree(pMain);
+ }
+ return rc;
+}
+
+
+/*
+** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
+** this function is called to prepare for iterating through the records
+** in sorted order.
+*/
+SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
+ VdbeSorter *pSorter;
+ int rc = SQLITE_OK; /* Return code */
+
+ assert( pCsr->eCurType==CURTYPE_SORTER );
+ pSorter = pCsr->uc.pSorter;
+ assert( pSorter );
+
+ /* If no data has been written to disk, then do not do so now. Instead,
+ ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
+ ** from the in-memory list. */
+ if( pSorter->bUsePMA==0 ){
+ if( pSorter->list.pList ){
+ *pbEof = 0;
+ rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
+ }else{
+ *pbEof = 1;
+ }
+ return rc;
+ }
+
+ /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
+ ** function flushes the contents of memory to disk, it immediately always
+ ** creates a new list consisting of a single key immediately afterwards.
+ ** So the list is never empty at this point. */
+ assert( pSorter->list.pList );
+ rc = vdbeSorterFlushPMA(pSorter);
+
+ /* Join all threads */
+ rc = vdbeSorterJoinAll(pSorter, rc);
+
+ vdbeSorterRewindDebug("rewind");
+
+ /* Assuming no errors have occurred, set up a merger structure to
+ ** incrementally read and merge all remaining PMAs. */
+ assert( pSorter->pReader==0 );
+ if( rc==SQLITE_OK ){
+ rc = vdbeSorterSetupMerge(pSorter);
+ *pbEof = 0;
+ }
+
+ vdbeSorterRewindDebug("rewinddone");
+ return rc;
+}
+
+/*
+** Advance to the next element in the sorter. Return value:
+**
+** SQLITE_OK success
+** SQLITE_DONE end of data
+** otherwise some kind of error.
+*/
+SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
+ VdbeSorter *pSorter;
+ int rc; /* Return code */
+
+ assert( pCsr->eCurType==CURTYPE_SORTER );
+ pSorter = pCsr->uc.pSorter;
+ assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
+ if( pSorter->bUsePMA ){
+ assert( pSorter->pReader==0 || pSorter->pMerger==0 );
+ assert( pSorter->bUseThreads==0 || pSorter->pReader );
+ assert( pSorter->bUseThreads==1 || pSorter->pMerger );
+#if SQLITE_MAX_WORKER_THREADS>0
+ if( pSorter->bUseThreads ){
+ rc = vdbePmaReaderNext(pSorter->pReader);
+ if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
+ }else
+#endif
+ /*if( !pSorter->bUseThreads )*/ {
+ int res = 0;
+ assert( pSorter->pMerger!=0 );
+ assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
+ rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
+ if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
+ }
+ }else{
+ SorterRecord *pFree = pSorter->list.pList;
+ pSorter->list.pList = pFree->u.pNext;
+ pFree->u.pNext = 0;
+ if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
+ rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
+ }
+ return rc;
+}
+
+/*
+** Return a pointer to a buffer owned by the sorter that contains the
+** current key.
+*/
+static void *vdbeSorterRowkey(
+ const VdbeSorter *pSorter, /* Sorter object */
+ int *pnKey /* OUT: Size of current key in bytes */
+){
+ void *pKey;
+ if( pSorter->bUsePMA ){
+ PmaReader *pReader;
+#if SQLITE_MAX_WORKER_THREADS>0
+ if( pSorter->bUseThreads ){
+ pReader = pSorter->pReader;
+ }else
+#endif
+ /*if( !pSorter->bUseThreads )*/{
+ pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
+ }
+ *pnKey = pReader->nKey;
+ pKey = pReader->aKey;
+ }else{
+ *pnKey = pSorter->list.pList->nVal;
+ pKey = SRVAL(pSorter->list.pList);
+ }
+ return pKey;
+}
+
+/*
+** Copy the current sorter key into the memory cell pOut.
+*/
+SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
+ VdbeSorter *pSorter;
+ void *pKey; int nKey; /* Sorter key to copy into pOut */
+
+ assert( pCsr->eCurType==CURTYPE_SORTER );
+ pSorter = pCsr->uc.pSorter;
+ pKey = vdbeSorterRowkey(pSorter, &nKey);
+ if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ pOut->n = nKey;
+ MemSetTypeFlag(pOut, MEM_Blob);
+ memcpy(pOut->z, pKey, nKey);
+
+ return SQLITE_OK;
+}
+
+/*
+** Compare the key in memory cell pVal with the key that the sorter cursor
+** passed as the first argument currently points to. For the purposes of
+** the comparison, ignore the rowid field at the end of each record.
+**
+** If the sorter cursor key contains any NULL values, consider it to be
+** less than pVal. Even if pVal also contains NULL values.
+**
+** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
+** Otherwise, set *pRes to a negative, zero or positive value if the
+** key in pVal is smaller than, equal to or larger than the current sorter
+** key.
+**
+** This routine forms the core of the OP_SorterCompare opcode, which in
+** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
+*/
+SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
+ const VdbeCursor *pCsr, /* Sorter cursor */
+ Mem *pVal, /* Value to compare to current sorter key */
+ int nKeyCol, /* Compare this many columns */
+ int *pRes /* OUT: Result of comparison */
+){
+ VdbeSorter *pSorter;
+ UnpackedRecord *r2;
+ KeyInfo *pKeyInfo;
+ int i;
+ void *pKey; int nKey; /* Sorter key to compare pVal with */
+
+ assert( pCsr->eCurType==CURTYPE_SORTER );
+ pSorter = pCsr->uc.pSorter;
+ r2 = pSorter->pUnpacked;
+ pKeyInfo = pCsr->pKeyInfo;
+ if( r2==0 ){
+ r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
+ if( r2==0 ) return SQLITE_NOMEM_BKPT;
+ r2->nField = nKeyCol;
+ }
+ assert( r2->nField==nKeyCol );
+
+ pKey = vdbeSorterRowkey(pSorter, &nKey);
+ sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
+ for(i=0; i<nKeyCol; i++){
+ if( r2->aMem[i].flags & MEM_Null ){
+ *pRes = -1;
+ return SQLITE_OK;
+ }
+ }
+
+ *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
+ return SQLITE_OK;
+}
+
+/************** End of vdbesort.c ********************************************/
+/************** Begin file vdbevtab.c ****************************************/
+/*
+** 2020-03-23
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file implements virtual-tables for examining the bytecode content
+** of a prepared statement.
+*/
+/* #include "sqliteInt.h" */
+#if defined(SQLITE_ENABLE_BYTECODE_VTAB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
+/* #include "vdbeInt.h" */
+
+/* An instance of the bytecode() table-valued function.
+*/
+typedef struct bytecodevtab bytecodevtab;
+struct bytecodevtab {
+ sqlite3_vtab base; /* Base class - must be first */
+ sqlite3 *db; /* Database connection */
+ int bTablesUsed; /* 2 for tables_used(). 0 for bytecode(). */
+};
+
+/* A cursor for scanning through the bytecode
+*/
+typedef struct bytecodevtab_cursor bytecodevtab_cursor;
+struct bytecodevtab_cursor {
+ sqlite3_vtab_cursor base; /* Base class - must be first */
+ sqlite3_stmt *pStmt; /* The statement whose bytecode is displayed */
+ int iRowid; /* The rowid of the output table */
+ int iAddr; /* Address */
+ int needFinalize; /* Cursors owns pStmt and must finalize it */
+ int showSubprograms; /* Provide a listing of subprograms */
+ Op *aOp; /* Operand array */
+ char *zP4; /* Rendered P4 value */
+ const char *zType; /* tables_used.type */
+ const char *zSchema; /* tables_used.schema */
+ const char *zName; /* tables_used.name */
+ Mem sub; /* Subprograms */
+};
+
+/*
+** Create a new bytecode() table-valued function.
+*/
+static int bytecodevtabConnect(
+ sqlite3 *db,
+ void *pAux,
+ int argc, const char *const*argv,
+ sqlite3_vtab **ppVtab,
+ char **pzErr
+){
+ bytecodevtab *pNew;
+ int rc;
+ int isTabUsed = pAux!=0;
+ const char *azSchema[2] = {
+ /* bytecode() schema */
+ "CREATE TABLE x("
+ "addr INT,"
+ "opcode TEXT,"
+ "p1 INT,"
+ "p2 INT,"
+ "p3 INT,"
+ "p4 TEXT,"
+ "p5 INT,"
+ "comment TEXT,"
+ "subprog TEXT,"
+ "stmt HIDDEN"
+ ");",
+
+ /* Tables_used() schema */
+ "CREATE TABLE x("
+ "type TEXT,"
+ "schema TEXT,"
+ "name TEXT,"
+ "wr INT,"
+ "subprog TEXT,"
+ "stmt HIDDEN"
+ ");"
+ };
+
+ rc = sqlite3_declare_vtab(db, azSchema[isTabUsed]);
+ if( rc==SQLITE_OK ){
+ pNew = sqlite3_malloc( sizeof(*pNew) );
+ *ppVtab = (sqlite3_vtab*)pNew;
+ if( pNew==0 ) return SQLITE_NOMEM;
+ memset(pNew, 0, sizeof(*pNew));
+ pNew->db = db;
+ pNew->bTablesUsed = isTabUsed*2;
+ }
+ return rc;
+}
+
+/*
+** This method is the destructor for bytecodevtab objects.
+*/
+static int bytecodevtabDisconnect(sqlite3_vtab *pVtab){
+ bytecodevtab *p = (bytecodevtab*)pVtab;
+ sqlite3_free(p);
+ return SQLITE_OK;
+}
+
+/*
+** Constructor for a new bytecodevtab_cursor object.
+*/
+static int bytecodevtabOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
+ bytecodevtab *pVTab = (bytecodevtab*)p;
+ bytecodevtab_cursor *pCur;
+ pCur = sqlite3_malloc( sizeof(*pCur) );
+ if( pCur==0 ) return SQLITE_NOMEM;
+ memset(pCur, 0, sizeof(*pCur));
+ sqlite3VdbeMemInit(&pCur->sub, pVTab->db, 1);
+ *ppCursor = &pCur->base;
+ return SQLITE_OK;
+}
+
+/*
+** Clear all internal content from a bytecodevtab cursor.
+*/
+static void bytecodevtabCursorClear(bytecodevtab_cursor *pCur){
+ sqlite3_free(pCur->zP4);
+ pCur->zP4 = 0;
+ sqlite3VdbeMemRelease(&pCur->sub);
+ sqlite3VdbeMemSetNull(&pCur->sub);
+ if( pCur->needFinalize ){
+ sqlite3_finalize(pCur->pStmt);
+ }
+ pCur->pStmt = 0;
+ pCur->needFinalize = 0;
+ pCur->zType = 0;
+ pCur->zSchema = 0;
+ pCur->zName = 0;
+}
+
+/*
+** Destructor for a bytecodevtab_cursor.
+*/
+static int bytecodevtabClose(sqlite3_vtab_cursor *cur){
+ bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
+ bytecodevtabCursorClear(pCur);
+ sqlite3_free(pCur);
+ return SQLITE_OK;
+}
+
+
+/*
+** Advance a bytecodevtab_cursor to its next row of output.
+*/
+static int bytecodevtabNext(sqlite3_vtab_cursor *cur){
+ bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
+ bytecodevtab *pTab = (bytecodevtab*)cur->pVtab;
+ int rc;
+ if( pCur->zP4 ){
+ sqlite3_free(pCur->zP4);
+ pCur->zP4 = 0;
+ }
+ if( pCur->zName ){
+ pCur->zName = 0;
+ pCur->zType = 0;
+ pCur->zSchema = 0;
+ }
+ rc = sqlite3VdbeNextOpcode(
+ (Vdbe*)pCur->pStmt,
+ pCur->showSubprograms ? &pCur->sub : 0,
+ pTab->bTablesUsed,
+ &pCur->iRowid,
+ &pCur->iAddr,
+ &pCur->aOp);
+ if( rc!=SQLITE_OK ){
+ sqlite3VdbeMemSetNull(&pCur->sub);
+ pCur->aOp = 0;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Return TRUE if the cursor has been moved off of the last
+** row of output.
+*/
+static int bytecodevtabEof(sqlite3_vtab_cursor *cur){
+ bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
+ return pCur->aOp==0;
+}
+
+/*
+** Return values of columns for the row at which the bytecodevtab_cursor
+** is currently pointing.
+*/
+static int bytecodevtabColumn(
+ sqlite3_vtab_cursor *cur, /* The cursor */
+ sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
+ int i /* Which column to return */
+){
+ bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
+ bytecodevtab *pVTab = (bytecodevtab*)cur->pVtab;
+ Op *pOp = pCur->aOp + pCur->iAddr;
+ if( pVTab->bTablesUsed ){
+ if( i==4 ){
+ i = 8;
+ }else{
+ if( i<=2 && pCur->zType==0 ){
+ Schema *pSchema;
+ HashElem *k;
+ int iDb = pOp->p3;
+ Pgno iRoot = (Pgno)pOp->p2;
+ sqlite3 *db = pVTab->db;
+ pSchema = db->aDb[iDb].pSchema;
+ pCur->zSchema = db->aDb[iDb].zDbSName;
+ for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
+ Table *pTab = (Table*)sqliteHashData(k);
+ if( !IsVirtual(pTab) && pTab->tnum==iRoot ){
+ pCur->zName = pTab->zName;
+ pCur->zType = "table";
+ break;
+ }
+ }
+ if( pCur->zName==0 ){
+ for(k=sqliteHashFirst(&pSchema->idxHash); k; k=sqliteHashNext(k)){
+ Index *pIdx = (Index*)sqliteHashData(k);
+ if( pIdx->tnum==iRoot ){
+ pCur->zName = pIdx->zName;
+ pCur->zType = "index";
+ }
+ }
+ }
+ }
+ i += 10;
+ }
+ }
+ switch( i ){
+ case 0: /* addr */
+ sqlite3_result_int(ctx, pCur->iAddr);
+ break;
+ case 1: /* opcode */
+ sqlite3_result_text(ctx, (char*)sqlite3OpcodeName(pOp->opcode),
+ -1, SQLITE_STATIC);
+ break;
+ case 2: /* p1 */
+ sqlite3_result_int(ctx, pOp->p1);
+ break;
+ case 3: /* p2 */
+ sqlite3_result_int(ctx, pOp->p2);
+ break;
+ case 4: /* p3 */
+ sqlite3_result_int(ctx, pOp->p3);
+ break;
+ case 5: /* p4 */
+ case 7: /* comment */
+ if( pCur->zP4==0 ){
+ pCur->zP4 = sqlite3VdbeDisplayP4(pVTab->db, pOp);
+ }
+ if( i==5 ){
+ sqlite3_result_text(ctx, pCur->zP4, -1, SQLITE_STATIC);
+ }else{
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+ char *zCom = sqlite3VdbeDisplayComment(pVTab->db, pOp, pCur->zP4);
+ sqlite3_result_text(ctx, zCom, -1, sqlite3_free);
+#endif
+ }
+ break;
+ case 6: /* p5 */
+ sqlite3_result_int(ctx, pOp->p5);
+ break;
+ case 8: { /* subprog */
+ Op *aOp = pCur->aOp;
+ assert( aOp[0].opcode==OP_Init );
+ assert( aOp[0].p4.z==0 || strncmp(aOp[0].p4.z,"-" "- ",3)==0 );
+ if( pCur->iRowid==pCur->iAddr+1 ){
+ break; /* Result is NULL for the main program */
+ }else if( aOp[0].p4.z!=0 ){
+ sqlite3_result_text(ctx, aOp[0].p4.z+3, -1, SQLITE_STATIC);
+ }else{
+ sqlite3_result_text(ctx, "(FK)", 4, SQLITE_STATIC);
+ }
+ break;
+ }
+ case 10: /* tables_used.type */
+ sqlite3_result_text(ctx, pCur->zType, -1, SQLITE_STATIC);
+ break;
+ case 11: /* tables_used.schema */
+ sqlite3_result_text(ctx, pCur->zSchema, -1, SQLITE_STATIC);
+ break;
+ case 12: /* tables_used.name */
+ sqlite3_result_text(ctx, pCur->zName, -1, SQLITE_STATIC);
+ break;
+ case 13: /* tables_used.wr */
+ sqlite3_result_int(ctx, pOp->opcode==OP_OpenWrite);
+ break;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Return the rowid for the current row. In this implementation, the
+** rowid is the same as the output value.
+*/
+static int bytecodevtabRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
+ bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
+ *pRowid = pCur->iRowid;
+ return SQLITE_OK;
+}
+
+/*
+** Initialize a cursor.
+**
+** idxNum==0 means show all subprograms
+** idxNum==1 means show only the main bytecode and omit subprograms.
+*/
+static int bytecodevtabFilter(
+ sqlite3_vtab_cursor *pVtabCursor,
+ int idxNum, const char *idxStr,
+ int argc, sqlite3_value **argv
+){
+ bytecodevtab_cursor *pCur = (bytecodevtab_cursor *)pVtabCursor;
+ bytecodevtab *pVTab = (bytecodevtab *)pVtabCursor->pVtab;
+ int rc = SQLITE_OK;
+
+ bytecodevtabCursorClear(pCur);
+ pCur->iRowid = 0;
+ pCur->iAddr = 0;
+ pCur->showSubprograms = idxNum==0;
+ assert( argc==1 );
+ if( sqlite3_value_type(argv[0])==SQLITE_TEXT ){
+ const char *zSql = (const char*)sqlite3_value_text(argv[0]);
+ if( zSql==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ rc = sqlite3_prepare_v2(pVTab->db, zSql, -1, &pCur->pStmt, 0);
+ pCur->needFinalize = 1;
+ }
+ }else{
+ pCur->pStmt = (sqlite3_stmt*)sqlite3_value_pointer(argv[0],"stmt-pointer");
+ }
+ if( pCur->pStmt==0 ){
+ pVTab->base.zErrMsg = sqlite3_mprintf(
+ "argument to %s() is not a valid SQL statement",
+ pVTab->bTablesUsed ? "tables_used" : "bytecode"
+ );
+ rc = SQLITE_ERROR;
+ }else{
+ bytecodevtabNext(pVtabCursor);
+ }
+ return rc;
+}
+
+/*
+** We must have a single stmt=? constraint that will be passed through
+** into the xFilter method. If there is no valid stmt=? constraint,
+** then return an SQLITE_CONSTRAINT error.
+*/
+static int bytecodevtabBestIndex(
+ sqlite3_vtab *tab,
+ sqlite3_index_info *pIdxInfo
+){
+ int i;
+ int rc = SQLITE_CONSTRAINT;
+ struct sqlite3_index_constraint *p;
+ bytecodevtab *pVTab = (bytecodevtab*)tab;
+ int iBaseCol = pVTab->bTablesUsed ? 4 : 8;
+ pIdxInfo->estimatedCost = (double)100;
+ pIdxInfo->estimatedRows = 100;
+ pIdxInfo->idxNum = 0;
+ for(i=0, p=pIdxInfo->aConstraint; i<pIdxInfo->nConstraint; i++, p++){
+ if( p->usable==0 ) continue;
+ if( p->op==SQLITE_INDEX_CONSTRAINT_EQ && p->iColumn==iBaseCol+1 ){
+ rc = SQLITE_OK;
+ pIdxInfo->aConstraintUsage[i].omit = 1;
+ pIdxInfo->aConstraintUsage[i].argvIndex = 1;
+ }
+ if( p->op==SQLITE_INDEX_CONSTRAINT_ISNULL && p->iColumn==iBaseCol ){
+ pIdxInfo->aConstraintUsage[i].omit = 1;
+ pIdxInfo->idxNum = 1;
+ }
+ }
+ return rc;
+}
+
+/*
+** This following structure defines all the methods for the
+** virtual table.
+*/
+static sqlite3_module bytecodevtabModule = {
+ /* iVersion */ 0,
+ /* xCreate */ 0,
+ /* xConnect */ bytecodevtabConnect,
+ /* xBestIndex */ bytecodevtabBestIndex,
+ /* xDisconnect */ bytecodevtabDisconnect,
+ /* xDestroy */ 0,
+ /* xOpen */ bytecodevtabOpen,
+ /* xClose */ bytecodevtabClose,
+ /* xFilter */ bytecodevtabFilter,
+ /* xNext */ bytecodevtabNext,
+ /* xEof */ bytecodevtabEof,
+ /* xColumn */ bytecodevtabColumn,
+ /* xRowid */ bytecodevtabRowid,
+ /* xUpdate */ 0,
+ /* xBegin */ 0,
+ /* xSync */ 0,
+ /* xCommit */ 0,
+ /* xRollback */ 0,
+ /* xFindMethod */ 0,
+ /* xRename */ 0,
+ /* xSavepoint */ 0,
+ /* xRelease */ 0,
+ /* xRollbackTo */ 0,
+ /* xShadowName */ 0
+};
+
+
+SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3 *db){
+ int rc;
+ rc = sqlite3_create_module(db, "bytecode", &bytecodevtabModule, 0);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_create_module(db, "tables_used", &bytecodevtabModule, &db);
+ }
+ return rc;
+}
+#elif defined(SQLITE_ENABLE_BYTECODE_VTAB)
+SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3 *db){ return SQLITE_OK; }
+#endif /* SQLITE_ENABLE_BYTECODE_VTAB */
+
+/************** End of vdbevtab.c ********************************************/
+/************** Begin file memjournal.c **************************************/
+/*
+** 2008 October 7
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains code use to implement an in-memory rollback journal.
+** The in-memory rollback journal is used to journal transactions for
+** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
+**
+** Update: The in-memory journal is also used to temporarily cache
+** smaller journals that are not critical for power-loss recovery.
+** For example, statement journals that are not too big will be held
+** entirely in memory, thus reducing the number of file I/O calls, and
+** more importantly, reducing temporary file creation events. If these
+** journals become too large for memory, they are spilled to disk. But
+** in the common case, they are usually small and no file I/O needs to
+** occur.
+*/
+/* #include "sqliteInt.h" */
+
+/* Forward references to internal structures */
+typedef struct MemJournal MemJournal;
+typedef struct FilePoint FilePoint;
+typedef struct FileChunk FileChunk;
+
+/*
+** The rollback journal is composed of a linked list of these structures.
+**
+** The zChunk array is always at least 8 bytes in size - usually much more.
+** Its actual size is stored in the MemJournal.nChunkSize variable.
+*/
+struct FileChunk {
+ FileChunk *pNext; /* Next chunk in the journal */
+ u8 zChunk[8]; /* Content of this chunk */
+};
+
+/*
+** By default, allocate this many bytes of memory for each FileChunk object.
+*/
+#define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
+
+/*
+** For chunk size nChunkSize, return the number of bytes that should
+** be allocated for each FileChunk structure.
+*/
+#define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
+
+/*
+** An instance of this object serves as a cursor into the rollback journal.
+** The cursor can be either for reading or writing.
+*/
+struct FilePoint {
+ sqlite3_int64 iOffset; /* Offset from the beginning of the file */
+ FileChunk *pChunk; /* Specific chunk into which cursor points */
+};
+
+/*
+** This structure is a subclass of sqlite3_file. Each open memory-journal
+** is an instance of this class.
+*/
+struct MemJournal {
+ const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
+ int nChunkSize; /* In-memory chunk-size */
+
+ int nSpill; /* Bytes of data before flushing */
+ int nSize; /* Bytes of data currently in memory */
+ FileChunk *pFirst; /* Head of in-memory chunk-list */
+ FilePoint endpoint; /* Pointer to the end of the file */
+ FilePoint readpoint; /* Pointer to the end of the last xRead() */
+
+ int flags; /* xOpen flags */
+ sqlite3_vfs *pVfs; /* The "real" underlying VFS */
+ const char *zJournal; /* Name of the journal file */
+};
+
+/*
+** Read data from the in-memory journal file. This is the implementation
+** of the sqlite3_vfs.xRead method.
+*/
+static int memjrnlRead(
+ sqlite3_file *pJfd, /* The journal file from which to read */
+ void *zBuf, /* Put the results here */
+ int iAmt, /* Number of bytes to read */
+ sqlite_int64 iOfst /* Begin reading at this offset */
+){
+ MemJournal *p = (MemJournal *)pJfd;
+ u8 *zOut = zBuf;
+ int nRead = iAmt;
+ int iChunkOffset;
+ FileChunk *pChunk;
+
+ if( (iAmt+iOfst)>p->endpoint.iOffset ){
+ return SQLITE_IOERR_SHORT_READ;
+ }
+ assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
+ if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
+ sqlite3_int64 iOff = 0;
+ for(pChunk=p->pFirst;
+ ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
+ pChunk=pChunk->pNext
+ ){
+ iOff += p->nChunkSize;
+ }
+ }else{
+ pChunk = p->readpoint.pChunk;
+ assert( pChunk!=0 );
+ }
+
+ iChunkOffset = (int)(iOfst%p->nChunkSize);
+ do {
+ int iSpace = p->nChunkSize - iChunkOffset;
+ int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
+ memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
+ zOut += nCopy;
+ nRead -= iSpace;
+ iChunkOffset = 0;
+ } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
+ p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
+ p->readpoint.pChunk = pChunk;
+
+ return SQLITE_OK;
+}
+
+/*
+** Free the list of FileChunk structures headed at MemJournal.pFirst.
+*/
+static void memjrnlFreeChunks(MemJournal *p){
+ FileChunk *pIter;
+ FileChunk *pNext;
+ for(pIter=p->pFirst; pIter; pIter=pNext){
+ pNext = pIter->pNext;
+ sqlite3_free(pIter);
+ }
+ p->pFirst = 0;
+}
+
+/*
+** Flush the contents of memory to a real file on disk.
+*/
+static int memjrnlCreateFile(MemJournal *p){
+ int rc;
+ sqlite3_file *pReal = (sqlite3_file*)p;
+ MemJournal copy = *p;
+
+ memset(p, 0, sizeof(MemJournal));
+ rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
+ if( rc==SQLITE_OK ){
+ int nChunk = copy.nChunkSize;
+ i64 iOff = 0;
+ FileChunk *pIter;
+ for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
+ if( iOff + nChunk > copy.endpoint.iOffset ){
+ nChunk = copy.endpoint.iOffset - iOff;
+ }
+ rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
+ if( rc ) break;
+ iOff += nChunk;
+ }
+ if( rc==SQLITE_OK ){
+ /* No error has occurred. Free the in-memory buffers. */
+ memjrnlFreeChunks(&copy);
+ }
+ }
+ if( rc!=SQLITE_OK ){
+ /* If an error occurred while creating or writing to the file, restore
+ ** the original before returning. This way, SQLite uses the in-memory
+ ** journal data to roll back changes made to the internal page-cache
+ ** before this function was called. */
+ sqlite3OsClose(pReal);
+ *p = copy;
+ }
+ return rc;
+}
+
+
+/*
+** Write data to the file.
+*/
+static int memjrnlWrite(
+ sqlite3_file *pJfd, /* The journal file into which to write */
+ const void *zBuf, /* Take data to be written from here */
+ int iAmt, /* Number of bytes to write */
+ sqlite_int64 iOfst /* Begin writing at this offset into the file */
+){
+ MemJournal *p = (MemJournal *)pJfd;
+ int nWrite = iAmt;
+ u8 *zWrite = (u8 *)zBuf;
+
+ /* If the file should be created now, create it and write the new data
+ ** into the file on disk. */
+ if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
+ int rc = memjrnlCreateFile(p);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
+ }
+ return rc;
+ }
+
+ /* If the contents of this write should be stored in memory */
+ else{
+ /* An in-memory journal file should only ever be appended to. Random
+ ** access writes are not required. The only exception to this is when
+ ** the in-memory journal is being used by a connection using the
+ ** atomic-write optimization. In this case the first 28 bytes of the
+ ** journal file may be written as part of committing the transaction. */
+ assert( iOfst==p->endpoint.iOffset || iOfst==0 );
+#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
+ || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
+ if( iOfst==0 && p->pFirst ){
+ assert( p->nChunkSize>iAmt );
+ memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
+ }else
+#else
+ assert( iOfst>0 || p->pFirst==0 );
+#endif
+ {
+ while( nWrite>0 ){
+ FileChunk *pChunk = p->endpoint.pChunk;
+ int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
+ int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
+
+ if( iChunkOffset==0 ){
+ /* New chunk is required to extend the file. */
+ FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
+ if( !pNew ){
+ return SQLITE_IOERR_NOMEM_BKPT;
+ }
+ pNew->pNext = 0;
+ if( pChunk ){
+ assert( p->pFirst );
+ pChunk->pNext = pNew;
+ }else{
+ assert( !p->pFirst );
+ p->pFirst = pNew;
+ }
+ p->endpoint.pChunk = pNew;
+ }
+
+ memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
+ zWrite += iSpace;
+ nWrite -= iSpace;
+ p->endpoint.iOffset += iSpace;
+ }
+ p->nSize = iAmt + iOfst;
+ }
+ }
+
+ return SQLITE_OK;
+}
+
+/*
+** Truncate the file.
+**
+** If the journal file is already on disk, truncate it there. Or, if it
+** is still in main memory but is being truncated to zero bytes in size,
+** ignore
+*/
+static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
+ MemJournal *p = (MemJournal *)pJfd;
+ if( ALWAYS(size==0) ){
+ memjrnlFreeChunks(p);
+ p->nSize = 0;
+ p->endpoint.pChunk = 0;
+ p->endpoint.iOffset = 0;
+ p->readpoint.pChunk = 0;
+ p->readpoint.iOffset = 0;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Close the file.
+*/
+static int memjrnlClose(sqlite3_file *pJfd){
+ MemJournal *p = (MemJournal *)pJfd;
+ memjrnlFreeChunks(p);
+ return SQLITE_OK;
+}
+
+/*
+** Sync the file.
+**
+** If the real file has been created, call its xSync method. Otherwise,
+** syncing an in-memory journal is a no-op.
+*/
+static int memjrnlSync(sqlite3_file *pJfd, int flags){
+ UNUSED_PARAMETER2(pJfd, flags);
+ return SQLITE_OK;
+}
+
+/*
+** Query the size of the file in bytes.
+*/
+static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
+ MemJournal *p = (MemJournal *)pJfd;
+ *pSize = (sqlite_int64) p->endpoint.iOffset;
+ return SQLITE_OK;
+}
+
+/*
+** Table of methods for MemJournal sqlite3_file object.
+*/
+static const struct sqlite3_io_methods MemJournalMethods = {
+ 1, /* iVersion */
+ memjrnlClose, /* xClose */
+ memjrnlRead, /* xRead */
+ memjrnlWrite, /* xWrite */
+ memjrnlTruncate, /* xTruncate */
+ memjrnlSync, /* xSync */
+ memjrnlFileSize, /* xFileSize */
+ 0, /* xLock */
+ 0, /* xUnlock */
+ 0, /* xCheckReservedLock */
+ 0, /* xFileControl */
+ 0, /* xSectorSize */
+ 0, /* xDeviceCharacteristics */
+ 0, /* xShmMap */
+ 0, /* xShmLock */
+ 0, /* xShmBarrier */
+ 0, /* xShmUnmap */
+ 0, /* xFetch */
+ 0 /* xUnfetch */
+};
+
+/*
+** Open a journal file.
+**
+** The behaviour of the journal file depends on the value of parameter
+** nSpill. If nSpill is 0, then the journal file is always create and
+** accessed using the underlying VFS. If nSpill is less than zero, then
+** all content is always stored in main-memory. Finally, if nSpill is a
+** positive value, then the journal file is initially created in-memory
+** but may be flushed to disk later on. In this case the journal file is
+** flushed to disk either when it grows larger than nSpill bytes in size,
+** or when sqlite3JournalCreate() is called.
+*/
+SQLITE_PRIVATE int sqlite3JournalOpen(
+ sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
+ const char *zName, /* Name of the journal file */
+ sqlite3_file *pJfd, /* Preallocated, blank file handle */
+ int flags, /* Opening flags */
+ int nSpill /* Bytes buffered before opening the file */
+){
+ MemJournal *p = (MemJournal*)pJfd;
+
+ /* Zero the file-handle object. If nSpill was passed zero, initialize
+ ** it using the sqlite3OsOpen() function of the underlying VFS. In this
+ ** case none of the code in this module is executed as a result of calls
+ ** made on the journal file-handle. */
+ memset(p, 0, sizeof(MemJournal));
+ if( nSpill==0 ){
+ return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
+ }
+
+ if( nSpill>0 ){
+ p->nChunkSize = nSpill;
+ }else{
+ p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
+ assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
+ }
+
+ pJfd->pMethods = (const sqlite3_io_methods*)&MemJournalMethods;
+ p->nSpill = nSpill;
+ p->flags = flags;
+ p->zJournal = zName;
+ p->pVfs = pVfs;
+ return SQLITE_OK;
+}
+
+/*
+** Open an in-memory journal file.
+*/
+SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
+ sqlite3JournalOpen(0, 0, pJfd, 0, -1);
+}
+
+#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
+ || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
+/*
+** If the argument p points to a MemJournal structure that is not an
+** in-memory-only journal file (i.e. is one that was opened with a +ve
+** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying
+** file has not yet been created, create it now.
+*/
+SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){
+ int rc = SQLITE_OK;
+ MemJournal *p = (MemJournal*)pJfd;
+ if( pJfd->pMethods==&MemJournalMethods && (
+#ifdef SQLITE_ENABLE_ATOMIC_WRITE
+ p->nSpill>0
+#else
+ /* While this appears to not be possible without ATOMIC_WRITE, the
+ ** paths are complex, so it seems prudent to leave the test in as
+ ** a NEVER(), in case our analysis is subtly flawed. */
+ NEVER(p->nSpill>0)
+#endif
+#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
+ || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
+#endif
+ )){
+ rc = memjrnlCreateFile(p);
+ }
+ return rc;
+}
+#endif
+
+/*
+** The file-handle passed as the only argument is open on a journal file.
+** Return true if this "journal file" is currently stored in heap memory,
+** or false otherwise.
+*/
+SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
+ return p->pMethods==&MemJournalMethods;
+}
+
+/*
+** Return the number of bytes required to store a JournalFile that uses vfs
+** pVfs to create the underlying on-disk files.
+*/
+SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
+ return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
+}
+
+/************** End of memjournal.c ******************************************/
+/************** Begin file walker.c ******************************************/
+/*
+** 2008 August 16
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains routines used for walking the parser tree for
+** an SQL statement.
+*/
+/* #include "sqliteInt.h" */
+/* #include <stdlib.h> */
+/* #include <string.h> */
+
+
+#if !defined(SQLITE_OMIT_WINDOWFUNC)
+/*
+** Walk all expressions linked into the list of Window objects passed
+** as the second argument.
+*/
+static int walkWindowList(Walker *pWalker, Window *pList){
+ Window *pWin;
+ for(pWin=pList; pWin; pWin=pWin->pNextWin){
+ int rc;
+ rc = sqlite3WalkExprList(pWalker, pWin->pOrderBy);
+ if( rc ) return WRC_Abort;
+ rc = sqlite3WalkExprList(pWalker, pWin->pPartition);
+ if( rc ) return WRC_Abort;
+ rc = sqlite3WalkExpr(pWalker, pWin->pFilter);
+ if( rc ) return WRC_Abort;
+
+ /* The next two are purely for calls to sqlite3RenameExprUnmap()
+ ** within sqlite3WindowOffsetExpr(). Because of constraints imposed
+ ** by sqlite3WindowOffsetExpr(), they can never fail. The results do
+ ** not matter anyhow. */
+ rc = sqlite3WalkExpr(pWalker, pWin->pStart);
+ if( NEVER(rc) ) return WRC_Abort;
+ rc = sqlite3WalkExpr(pWalker, pWin->pEnd);
+ if( NEVER(rc) ) return WRC_Abort;
+ }
+ return WRC_Continue;
+}
+#endif
+
+/*
+** Walk an expression tree. Invoke the callback once for each node
+** of the expression, while descending. (In other words, the callback
+** is invoked before visiting children.)
+**
+** The return value from the callback should be one of the WRC_*
+** constants to specify how to proceed with the walk.
+**
+** WRC_Continue Continue descending down the tree.
+**
+** WRC_Prune Do not descend into child nodes, but allow
+** the walk to continue with sibling nodes.
+**
+** WRC_Abort Do no more callbacks. Unwind the stack and
+** return from the top-level walk call.
+**
+** The return value from this routine is WRC_Abort to abandon the tree walk
+** and WRC_Continue to continue.
+*/
+static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
+ int rc;
+ testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
+ testcase( ExprHasProperty(pExpr, EP_Reduced) );
+ while(1){
+ rc = pWalker->xExprCallback(pWalker, pExpr);
+ if( rc ) return rc & WRC_Abort;
+ if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
+ assert( pExpr->x.pList==0 || pExpr->pRight==0 );
+ if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
+ if( pExpr->pRight ){
+ assert( !ExprHasProperty(pExpr, EP_WinFunc) );
+ pExpr = pExpr->pRight;
+ continue;
+ }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+ assert( !ExprHasProperty(pExpr, EP_WinFunc) );
+ if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
+ }else{
+ if( pExpr->x.pList ){
+ if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
+ }
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( ExprHasProperty(pExpr, EP_WinFunc) ){
+ if( walkWindowList(pWalker, pExpr->y.pWin) ) return WRC_Abort;
+ }
+#endif
+ }
+ }
+ break;
+ }
+ return WRC_Continue;
+}
+SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
+ return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
+}
+
+/*
+** Call sqlite3WalkExpr() for every expression in list p or until
+** an abort request is seen.
+*/
+SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
+ int i;
+ struct ExprList_item *pItem;
+ if( p ){
+ for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
+ if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
+ }
+ }
+ return WRC_Continue;
+}
+
+/*
+** Walk all expressions associated with SELECT statement p. Do
+** not invoke the SELECT callback on p, but do (of course) invoke
+** any expr callbacks and SELECT callbacks that come from subqueries.
+** Return WRC_Abort or WRC_Continue.
+*/
+SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
+ if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
+ if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
+ if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
+ if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
+ if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
+ if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
+#if !defined(SQLITE_OMIT_WINDOWFUNC) && !defined(SQLITE_OMIT_ALTERTABLE)
+ {
+ Parse *pParse = pWalker->pParse;
+ if( pParse && IN_RENAME_OBJECT ){
+ /* The following may return WRC_Abort if there are unresolvable
+ ** symbols (e.g. a table that does not exist) in a window definition. */
+ int rc = walkWindowList(pWalker, p->pWinDefn);
+ return rc;
+ }
+ }
+#endif
+ return WRC_Continue;
+}
+
+/*
+** Walk the parse trees associated with all subqueries in the
+** FROM clause of SELECT statement p. Do not invoke the select
+** callback on p, but do invoke it on each FROM clause subquery
+** and on any subqueries further down in the tree. Return
+** WRC_Abort or WRC_Continue;
+*/
+SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
+ SrcList *pSrc;
+ int i;
+ struct SrcList_item *pItem;
+
+ pSrc = p->pSrc;
+ if( pSrc ){
+ for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
+ if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
+ return WRC_Abort;
+ }
+ if( pItem->fg.isTabFunc
+ && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
+ ){
+ return WRC_Abort;
+ }
+ }
+ }
+ return WRC_Continue;
+}
+
+/*
+** Call sqlite3WalkExpr() for every expression in Select statement p.
+** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
+** on the compound select chain, p->pPrior.
+**
+** If it is not NULL, the xSelectCallback() callback is invoked before
+** the walk of the expressions and FROM clause. The xSelectCallback2()
+** method is invoked following the walk of the expressions and FROM clause,
+** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
+** and if the expressions and FROM clause both return WRC_Continue;
+**
+** Return WRC_Continue under normal conditions. Return WRC_Abort if
+** there is an abort request.
+**
+** If the Walker does not have an xSelectCallback() then this routine
+** is a no-op returning WRC_Continue.
+*/
+SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
+ int rc;
+ if( p==0 ) return WRC_Continue;
+ if( pWalker->xSelectCallback==0 ) return WRC_Continue;
+ do{
+ rc = pWalker->xSelectCallback(pWalker, p);
+ if( rc ) return rc & WRC_Abort;
+ if( sqlite3WalkSelectExpr(pWalker, p)
+ || sqlite3WalkSelectFrom(pWalker, p)
+ ){
+ return WRC_Abort;
+ }
+ if( pWalker->xSelectCallback2 ){
+ pWalker->xSelectCallback2(pWalker, p);
+ }
+ p = p->pPrior;
+ }while( p!=0 );
+ return WRC_Continue;
+}
+
+/* Increase the walkerDepth when entering a subquery, and
+** descrease when leaving the subquery.
+*/
+SQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker *pWalker, Select *pSelect){
+ UNUSED_PARAMETER(pSelect);
+ pWalker->walkerDepth++;
+ return WRC_Continue;
+}
+SQLITE_PRIVATE void sqlite3WalkerDepthDecrease(Walker *pWalker, Select *pSelect){
+ UNUSED_PARAMETER(pSelect);
+ pWalker->walkerDepth--;
+}
+
+
+/*
+** No-op routine for the parse-tree walker.
+**
+** When this routine is the Walker.xExprCallback then expression trees
+** are walked without any actions being taken at each node. Presumably,
+** when this routine is used for Walker.xExprCallback then
+** Walker.xSelectCallback is set to do something useful for every
+** subquery in the parser tree.
+*/
+SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ return WRC_Continue;
+}
+
+/*
+** No-op routine for the parse-tree walker for SELECT statements.
+** subquery in the parser tree.
+*/
+SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ return WRC_Continue;
+}
+
+/************** End of walker.c **********************************************/
+/************** Begin file resolve.c *****************************************/
+/*
+** 2008 August 18
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains routines used for walking the parser tree and
+** resolve all identifiers by associating them with a particular
+** table and column.
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** Magic table number to mean the EXCLUDED table in an UPSERT statement.
+*/
+#define EXCLUDED_TABLE_NUMBER 2
+
+/*
+** Walk the expression tree pExpr and increase the aggregate function
+** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
+** This needs to occur when copying a TK_AGG_FUNCTION node from an
+** outer query into an inner subquery.
+**
+** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
+** is a helper function - a callback for the tree walker.
+**
+** See also the sqlite3WindowExtraAggFuncDepth() routine in window.c
+*/
+static int incrAggDepth(Walker *pWalker, Expr *pExpr){
+ if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
+ return WRC_Continue;
+}
+static void incrAggFunctionDepth(Expr *pExpr, int N){
+ if( N>0 ){
+ Walker w;
+ memset(&w, 0, sizeof(w));
+ w.xExprCallback = incrAggDepth;
+ w.u.n = N;
+ sqlite3WalkExpr(&w, pExpr);
+ }
+}
+
+/*
+** Turn the pExpr expression into an alias for the iCol-th column of the
+** result set in pEList.
+**
+** If the reference is followed by a COLLATE operator, then make sure
+** the COLLATE operator is preserved. For example:
+**
+** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
+**
+** Should be transformed into:
+**
+** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
+**
+** The nSubquery parameter specifies how many levels of subquery the
+** alias is removed from the original expression. The usual value is
+** zero but it might be more if the alias is contained within a subquery
+** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
+** structures must be increased by the nSubquery amount.
+*/
+static void resolveAlias(
+ Parse *pParse, /* Parsing context */
+ ExprList *pEList, /* A result set */
+ int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
+ Expr *pExpr, /* Transform this into an alias to the result set */
+ const char *zType, /* "GROUP" or "ORDER" or "" */
+ int nSubquery /* Number of subqueries that the label is moving */
+){
+ Expr *pOrig; /* The iCol-th column of the result set */
+ Expr *pDup; /* Copy of pOrig */
+ sqlite3 *db; /* The database connection */
+
+ assert( iCol>=0 && iCol<pEList->nExpr );
+ pOrig = pEList->a[iCol].pExpr;
+ assert( pOrig!=0 );
+ db = pParse->db;
+ pDup = sqlite3ExprDup(db, pOrig, 0);
+ if( pDup!=0 ){
+ if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
+ if( pExpr->op==TK_COLLATE ){
+ pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
+ }
+
+ /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
+ ** prevents ExprDelete() from deleting the Expr structure itself,
+ ** allowing it to be repopulated by the memcpy() on the following line.
+ ** The pExpr->u.zToken might point into memory that will be freed by the
+ ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
+ ** make a copy of the token before doing the sqlite3DbFree().
+ */
+ ExprSetProperty(pExpr, EP_Static);
+ sqlite3ExprDelete(db, pExpr);
+ memcpy(pExpr, pDup, sizeof(*pExpr));
+ if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
+ assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
+ pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
+ pExpr->flags |= EP_MemToken;
+ }
+ if( ExprHasProperty(pExpr, EP_WinFunc) ){
+ if( pExpr->y.pWin!=0 ){
+ pExpr->y.pWin->pOwner = pExpr;
+ }else{
+ assert( db->mallocFailed );
+ }
+ }
+ sqlite3DbFree(db, pDup);
+ }
+ ExprSetProperty(pExpr, EP_Alias);
+}
+
+
+/*
+** Return TRUE if the name zCol occurs anywhere in the USING clause.
+**
+** Return FALSE if the USING clause is NULL or if it does not contain
+** zCol.
+*/
+static int nameInUsingClause(IdList *pUsing, const char *zCol){
+ if( pUsing ){
+ int k;
+ for(k=0; k<pUsing->nId; k++){
+ if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
+ }
+ }
+ return 0;
+}
+
+/*
+** Subqueries stores the original database, table and column names for their
+** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
+** Check to see if the zSpan given to this routine matches the zDb, zTab,
+** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
+** match anything.
+*/
+SQLITE_PRIVATE int sqlite3MatchEName(
+ const struct ExprList_item *pItem,
+ const char *zCol,
+ const char *zTab,
+ const char *zDb
+){
+ int n;
+ const char *zSpan;
+ if( pItem->eEName!=ENAME_TAB ) return 0;
+ zSpan = pItem->zEName;
+ for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
+ if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
+ return 0;
+ }
+ zSpan += n+1;
+ for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
+ if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
+ return 0;
+ }
+ zSpan += n+1;
+ if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
+ return 0;
+ }
+ return 1;
+}
+
+/*
+** Return TRUE if the double-quoted string mis-feature should be supported.
+*/
+static int areDoubleQuotedStringsEnabled(sqlite3 *db, NameContext *pTopNC){
+ if( db->init.busy ) return 1; /* Always support for legacy schemas */
+ if( pTopNC->ncFlags & NC_IsDDL ){
+ /* Currently parsing a DDL statement */
+ if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){
+ return 1;
+ }
+ return (db->flags & SQLITE_DqsDDL)!=0;
+ }else{
+ /* Currently parsing a DML statement */
+ return (db->flags & SQLITE_DqsDML)!=0;
+ }
+}
+
+/*
+** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
+** return the appropriate colUsed mask.
+*/
+SQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr *pExpr){
+ int n;
+ Table *pExTab;
+
+ n = pExpr->iColumn;
+ pExTab = pExpr->y.pTab;
+ assert( pExTab!=0 );
+ if( (pExTab->tabFlags & TF_HasGenerated)!=0
+ && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0
+ ){
+ testcase( pExTab->nCol==BMS-1 );
+ testcase( pExTab->nCol==BMS );
+ return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1;
+ }else{
+ testcase( n==BMS-1 );
+ testcase( n==BMS );
+ if( n>=BMS ) n = BMS-1;
+ return ((Bitmask)1)<<n;
+ }
+}
+
+/*
+** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
+** that name in the set of source tables in pSrcList and make the pExpr
+** expression node refer back to that source column. The following changes
+** are made to pExpr:
+**
+** pExpr->iDb Set the index in db->aDb[] of the database X
+** (even if X is implied).
+** pExpr->iTable Set to the cursor number for the table obtained
+** from pSrcList.
+** pExpr->y.pTab Points to the Table structure of X.Y (even if
+** X and/or Y are implied.)
+** pExpr->iColumn Set to the column number within the table.
+** pExpr->op Set to TK_COLUMN.
+** pExpr->pLeft Any expression this points to is deleted
+** pExpr->pRight Any expression this points to is deleted.
+**
+** The zDb variable is the name of the database (the "X"). This value may be
+** NULL meaning that name is of the form Y.Z or Z. Any available database
+** can be used. The zTable variable is the name of the table (the "Y"). This
+** value can be NULL if zDb is also NULL. If zTable is NULL it
+** means that the form of the name is Z and that columns from any table
+** can be used.
+**
+** If the name cannot be resolved unambiguously, leave an error message
+** in pParse and return WRC_Abort. Return WRC_Prune on success.
+*/
+static int lookupName(
+ Parse *pParse, /* The parsing context */
+ const char *zDb, /* Name of the database containing table, or NULL */
+ const char *zTab, /* Name of table containing column, or NULL */
+ const char *zCol, /* Name of the column. */
+ NameContext *pNC, /* The name context used to resolve the name */
+ Expr *pExpr /* Make this EXPR node point to the selected column */
+){
+ int i, j; /* Loop counters */
+ int cnt = 0; /* Number of matching column names */
+ int cntTab = 0; /* Number of matching table names */
+ int nSubquery = 0; /* How many levels of subquery */
+ sqlite3 *db = pParse->db; /* The database connection */
+ struct SrcList_item *pItem; /* Use for looping over pSrcList items */
+ struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
+ NameContext *pTopNC = pNC; /* First namecontext in the list */
+ Schema *pSchema = 0; /* Schema of the expression */
+ int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */
+ Table *pTab = 0; /* Table hold the row */
+ Column *pCol; /* A column of pTab */
+
+ assert( pNC ); /* the name context cannot be NULL. */
+ assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
+ assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
+
+ /* Initialize the node to no-match */
+ pExpr->iTable = -1;
+ ExprSetVVAProperty(pExpr, EP_NoReduce);
+
+ /* Translate the schema name in zDb into a pointer to the corresponding
+ ** schema. If not found, pSchema will remain NULL and nothing will match
+ ** resulting in an appropriate error message toward the end of this routine
+ */
+ if( zDb ){
+ testcase( pNC->ncFlags & NC_PartIdx );
+ testcase( pNC->ncFlags & NC_IsCheck );
+ if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
+ /* Silently ignore database qualifiers inside CHECK constraints and
+ ** partial indices. Do not raise errors because that might break
+ ** legacy and because it does not hurt anything to just ignore the
+ ** database name. */
+ zDb = 0;
+ }else{
+ for(i=0; i<db->nDb; i++){
+ assert( db->aDb[i].zDbSName );
+ if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
+ pSchema = db->aDb[i].pSchema;
+ break;
+ }
+ }
+ if( i==db->nDb && sqlite3StrICmp("main", zDb)==0 ){
+ /* This branch is taken when the main database has been renamed
+ ** using SQLITE_DBCONFIG_MAINDBNAME. */
+ pSchema = db->aDb[0].pSchema;
+ zDb = db->aDb[0].zDbSName;
+ }
+ }
+ }
+
+ /* Start at the inner-most context and move outward until a match is found */
+ assert( pNC && cnt==0 );
+ do{
+ ExprList *pEList;
+ SrcList *pSrcList = pNC->pSrcList;
+
+ if( pSrcList ){
+ for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
+ u8 hCol;
+ pTab = pItem->pTab;
+ assert( pTab!=0 && pTab->zName!=0 );
+ assert( pTab->nCol>0 );
+ if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
+ int hit = 0;
+ pEList = pItem->pSelect->pEList;
+ for(j=0; j<pEList->nExpr; j++){
+ if( sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb) ){
+ cnt++;
+ cntTab = 2;
+ pMatch = pItem;
+ pExpr->iColumn = j;
+ hit = 1;
+ }
+ }
+ if( hit || zTab==0 ) continue;
+ }
+ if( zDb && pTab->pSchema!=pSchema ){
+ continue;
+ }
+ if( zTab ){
+ const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
+ assert( zTabName!=0 );
+ if( sqlite3StrICmp(zTabName, zTab)!=0 ){
+ continue;
+ }
+ if( IN_RENAME_OBJECT && pItem->zAlias ){
+ sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
+ }
+ }
+ if( 0==(cntTab++) ){
+ pMatch = pItem;
+ }
+ hCol = sqlite3StrIHash(zCol);
+ for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
+ if( pCol->hName==hCol && sqlite3StrICmp(pCol->zName, zCol)==0 ){
+ /* If there has been exactly one prior match and this match
+ ** is for the right-hand table of a NATURAL JOIN or is in a
+ ** USING clause, then skip this match.
+ */
+ if( cnt==1 ){
+ if( pItem->fg.jointype & JT_NATURAL ) continue;
+ if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
+ }
+ cnt++;
+ pMatch = pItem;
+ /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
+ pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
+ break;
+ }
+ }
+ }
+ if( pMatch ){
+ pExpr->iTable = pMatch->iCursor;
+ pExpr->y.pTab = pMatch->pTab;
+ /* RIGHT JOIN not (yet) supported */
+ assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
+ if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
+ ExprSetProperty(pExpr, EP_CanBeNull);
+ }
+ pSchema = pExpr->y.pTab->pSchema;
+ }
+ } /* if( pSrcList ) */
+
+#if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
+ /* If we have not already resolved the name, then maybe
+ ** it is a new.* or old.* trigger argument reference. Or
+ ** maybe it is an excluded.* from an upsert.
+ */
+ if( zDb==0 && zTab!=0 && cntTab==0 ){
+ pTab = 0;
+#ifndef SQLITE_OMIT_TRIGGER
+ if( pParse->pTriggerTab!=0 ){
+ int op = pParse->eTriggerOp;
+ assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
+ if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
+ pExpr->iTable = 1;
+ pTab = pParse->pTriggerTab;
+ }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
+ pExpr->iTable = 0;
+ pTab = pParse->pTriggerTab;
+ }
+ }
+#endif /* SQLITE_OMIT_TRIGGER */
+#ifndef SQLITE_OMIT_UPSERT
+ if( (pNC->ncFlags & NC_UUpsert)!=0 ){
+ Upsert *pUpsert = pNC->uNC.pUpsert;
+ if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
+ pTab = pUpsert->pUpsertSrc->a[0].pTab;
+ pExpr->iTable = EXCLUDED_TABLE_NUMBER;
+ }
+ }
+#endif /* SQLITE_OMIT_UPSERT */
+
+ if( pTab ){
+ int iCol;
+ u8 hCol = sqlite3StrIHash(zCol);
+ pSchema = pTab->pSchema;
+ cntTab++;
+ for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
+ if( pCol->hName==hCol && sqlite3StrICmp(pCol->zName, zCol)==0 ){
+ if( iCol==pTab->iPKey ){
+ iCol = -1;
+ }
+ break;
+ }
+ }
+ if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
+ /* IMP: R-51414-32910 */
+ iCol = -1;
+ }
+ if( iCol<pTab->nCol ){
+ cnt++;
+#ifndef SQLITE_OMIT_UPSERT
+ if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){
+ testcase( iCol==(-1) );
+ if( IN_RENAME_OBJECT ){
+ pExpr->iColumn = iCol;
+ pExpr->y.pTab = pTab;
+ eNewExprOp = TK_COLUMN;
+ }else{
+ pExpr->iTable = pNC->uNC.pUpsert->regData +
+ sqlite3TableColumnToStorage(pTab, iCol);
+ eNewExprOp = TK_REGISTER;
+ ExprSetProperty(pExpr, EP_Alias);
+ }
+ }else
+#endif /* SQLITE_OMIT_UPSERT */
+ {
+#ifndef SQLITE_OMIT_TRIGGER
+ if( iCol<0 ){
+ pExpr->affExpr = SQLITE_AFF_INTEGER;
+ }else if( pExpr->iTable==0 ){
+ testcase( iCol==31 );
+ testcase( iCol==32 );
+ pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
+ }else{
+ testcase( iCol==31 );
+ testcase( iCol==32 );
+ pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
+ }
+ pExpr->y.pTab = pTab;
+ pExpr->iColumn = (i16)iCol;
+ eNewExprOp = TK_TRIGGER;
+#endif /* SQLITE_OMIT_TRIGGER */
+ }
+ }
+ }
+ }
+#endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
+
+ /*
+ ** Perhaps the name is a reference to the ROWID
+ */
+ if( cnt==0
+ && cntTab==1
+ && pMatch
+ && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
+ && sqlite3IsRowid(zCol)
+ && VisibleRowid(pMatch->pTab)
+ ){
+ cnt = 1;
+ pExpr->iColumn = -1;
+ pExpr->affExpr = SQLITE_AFF_INTEGER;
+ }
+
+ /*
+ ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
+ ** might refer to an result-set alias. This happens, for example, when
+ ** we are resolving names in the WHERE clause of the following command:
+ **
+ ** SELECT a+b AS x FROM table WHERE x<10;
+ **
+ ** In cases like this, replace pExpr with a copy of the expression that
+ ** forms the result set entry ("a+b" in the example) and return immediately.
+ ** Note that the expression in the result set should have already been
+ ** resolved by the time the WHERE clause is resolved.
+ **
+ ** The ability to use an output result-set column in the WHERE, GROUP BY,
+ ** or HAVING clauses, or as part of a larger expression in the ORDER BY
+ ** clause is not standard SQL. This is a (goofy) SQLite extension, that
+ ** is supported for backwards compatibility only. Hence, we issue a warning
+ ** on sqlite3_log() whenever the capability is used.
+ */
+ if( (pNC->ncFlags & NC_UEList)!=0
+ && cnt==0
+ && zTab==0
+ ){
+ pEList = pNC->uNC.pEList;
+ assert( pEList!=0 );
+ for(j=0; j<pEList->nExpr; j++){
+ char *zAs = pEList->a[j].zEName;
+ if( pEList->a[j].eEName==ENAME_NAME
+ && sqlite3_stricmp(zAs, zCol)==0
+ ){
+ Expr *pOrig;
+ assert( pExpr->pLeft==0 && pExpr->pRight==0 );
+ assert( pExpr->x.pList==0 );
+ assert( pExpr->x.pSelect==0 );
+ pOrig = pEList->a[j].pExpr;
+ if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
+ sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
+ return WRC_Abort;
+ }
+ if( ExprHasProperty(pOrig, EP_Win)
+ && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC )
+ ){
+ sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs);
+ return WRC_Abort;
+ }
+ if( sqlite3ExprVectorSize(pOrig)!=1 ){
+ sqlite3ErrorMsg(pParse, "row value misused");
+ return WRC_Abort;
+ }
+ resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
+ cnt = 1;
+ pMatch = 0;
+ assert( zTab==0 && zDb==0 );
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
+ }
+ goto lookupname_end;
+ }
+ }
+ }
+
+ /* Advance to the next name context. The loop will exit when either
+ ** we have a match (cnt>0) or when we run out of name contexts.
+ */
+ if( cnt ) break;
+ pNC = pNC->pNext;
+ nSubquery++;
+ }while( pNC );
+
+
+ /*
+ ** If X and Y are NULL (in other words if only the column name Z is
+ ** supplied) and the value of Z is enclosed in double-quotes, then
+ ** Z is a string literal if it doesn't match any column names. In that
+ ** case, we need to return right away and not make any changes to
+ ** pExpr.
+ **
+ ** Because no reference was made to outer contexts, the pNC->nRef
+ ** fields are not changed in any context.
+ */
+ if( cnt==0 && zTab==0 ){
+ assert( pExpr->op==TK_ID );
+ if( ExprHasProperty(pExpr,EP_DblQuoted)
+ && areDoubleQuotedStringsEnabled(db, pTopNC)
+ ){
+ /* If a double-quoted identifier does not match any known column name,
+ ** then treat it as a string.
+ **
+ ** This hack was added in the early days of SQLite in a misguided attempt
+ ** to be compatible with MySQL 3.x, which used double-quotes for strings.
+ ** I now sorely regret putting in this hack. The effect of this hack is
+ ** that misspelled identifier names are silently converted into strings
+ ** rather than causing an error, to the frustration of countless
+ ** programmers. To all those frustrated programmers, my apologies.
+ **
+ ** Someday, I hope to get rid of this hack. Unfortunately there is
+ ** a huge amount of legacy SQL that uses it. So for now, we just
+ ** issue a warning.
+ */
+ sqlite3_log(SQLITE_WARNING,
+ "double-quoted string literal: \"%w\"", zCol);
+#ifdef SQLITE_ENABLE_NORMALIZE
+ sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
+#endif
+ pExpr->op = TK_STRING;
+ pExpr->y.pTab = 0;
+ return WRC_Prune;
+ }
+ if( sqlite3ExprIdToTrueFalse(pExpr) ){
+ return WRC_Prune;
+ }
+ }
+
+ /*
+ ** cnt==0 means there was not match. cnt>1 means there were two or
+ ** more matches. Either way, we have an error.
+ */
+ if( cnt!=1 ){
+ const char *zErr;
+ zErr = cnt==0 ? "no such column" : "ambiguous column name";
+ if( zDb ){
+ sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
+ }else if( zTab ){
+ sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
+ }else{
+ sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
+ }
+ pParse->checkSchema = 1;
+ pTopNC->nErr++;
+ }
+
+ /* If a column from a table in pSrcList is referenced, then record
+ ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
+ ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is
+ ** set if the 63rd or any subsequent column is used.
+ **
+ ** The colUsed mask is an optimization used to help determine if an
+ ** index is a covering index. The correct answer is still obtained
+ ** if the mask contains extra set bits. However, it is important to
+ ** avoid setting bits beyond the maximum column number of the table.
+ ** (See ticket [b92e5e8ec2cdbaa1]).
+ **
+ ** If a generated column is referenced, set bits for every column
+ ** of the table.
+ */
+ if( pExpr->iColumn>=0 && pMatch!=0 ){
+ pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
+ }
+
+ /* Clean up and return
+ */
+ sqlite3ExprDelete(db, pExpr->pLeft);
+ pExpr->pLeft = 0;
+ sqlite3ExprDelete(db, pExpr->pRight);
+ pExpr->pRight = 0;
+ pExpr->op = eNewExprOp;
+ ExprSetProperty(pExpr, EP_Leaf);
+lookupname_end:
+ if( cnt==1 ){
+ assert( pNC!=0 );
+ if( !ExprHasProperty(pExpr, EP_Alias) ){
+ sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
+ }
+ /* Increment the nRef value on all name contexts from TopNC up to
+ ** the point where the name matched. */
+ for(;;){
+ assert( pTopNC!=0 );
+ pTopNC->nRef++;
+ if( pTopNC==pNC ) break;
+ pTopNC = pTopNC->pNext;
+ }
+ return WRC_Prune;
+ } else {
+ return WRC_Abort;
+ }
+}
+
+/*
+** Allocate and return a pointer to an expression to load the column iCol
+** from datasource iSrc in SrcList pSrc.
+*/
+SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
+ Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
+ if( p ){
+ struct SrcList_item *pItem = &pSrc->a[iSrc];
+ Table *pTab = p->y.pTab = pItem->pTab;
+ p->iTable = pItem->iCursor;
+ if( p->y.pTab->iPKey==iCol ){
+ p->iColumn = -1;
+ }else{
+ p->iColumn = (ynVar)iCol;
+ if( (pTab->tabFlags & TF_HasGenerated)!=0
+ && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0
+ ){
+ testcase( pTab->nCol==63 );
+ testcase( pTab->nCol==64 );
+ pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1;
+ }else{
+ testcase( iCol==BMS );
+ testcase( iCol==BMS-1 );
+ pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
+ }
+ }
+ }
+ return p;
+}
+
+/*
+** Report an error that an expression is not valid for some set of
+** pNC->ncFlags values determined by validMask.
+**
+** static void notValid(
+** Parse *pParse, // Leave error message here
+** NameContext *pNC, // The name context
+** const char *zMsg, // Type of error
+** int validMask, // Set of contexts for which prohibited
+** Expr *pExpr // Invalidate this expression on error
+** ){...}
+**
+** As an optimization, since the conditional is almost always false
+** (because errors are rare), the conditional is moved outside of the
+** function call using a macro.
+*/
+static void notValidImpl(
+ Parse *pParse, /* Leave error message here */
+ NameContext *pNC, /* The name context */
+ const char *zMsg, /* Type of error */
+ Expr *pExpr /* Invalidate this expression on error */
+){
+ const char *zIn = "partial index WHERE clauses";
+ if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
+#ifndef SQLITE_OMIT_CHECK
+ else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
+#endif
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns";
+#endif
+ sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
+ if( pExpr ) pExpr->op = TK_NULL;
+}
+#define sqlite3ResolveNotValid(P,N,M,X,E) \
+ assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
+ if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E);
+
+/*
+** Expression p should encode a floating point value between 1.0 and 0.0.
+** Return 1024 times this value. Or return -1 if p is not a floating point
+** value between 1.0 and 0.0.
+*/
+static int exprProbability(Expr *p){
+ double r = -1.0;
+ if( p->op!=TK_FLOAT ) return -1;
+ sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
+ assert( r>=0.0 );
+ if( r>1.0 ) return -1;
+ return (int)(r*134217728.0);
+}
+
+/*
+** This routine is callback for sqlite3WalkExpr().
+**
+** Resolve symbolic names into TK_COLUMN operators for the current
+** node in the expression tree. Return 0 to continue the search down
+** the tree or 2 to abort the tree walk.
+**
+** This routine also does error checking and name resolution for
+** function names. The operator for aggregate functions is changed
+** to TK_AGG_FUNCTION.
+*/
+static int resolveExprStep(Walker *pWalker, Expr *pExpr){
+ NameContext *pNC;
+ Parse *pParse;
+
+ pNC = pWalker->u.pNC;
+ assert( pNC!=0 );
+ pParse = pNC->pParse;
+ assert( pParse==pWalker->pParse );
+
+#ifndef NDEBUG
+ if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
+ SrcList *pSrcList = pNC->pSrcList;
+ int i;
+ for(i=0; i<pNC->pSrcList->nSrc; i++){
+ assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
+ }
+ }
+#endif
+ switch( pExpr->op ){
+
+ /* The special operator TK_ROW means use the rowid for the first
+ ** column in the FROM clause. This is used by the LIMIT and ORDER BY
+ ** clause processing on UPDATE and DELETE statements, and by
+ ** UPDATE ... FROM statement processing.
+ */
+ case TK_ROW: {
+ SrcList *pSrcList = pNC->pSrcList;
+ struct SrcList_item *pItem;
+ assert( pSrcList && pSrcList->nSrc>=1 );
+ pItem = pSrcList->a;
+ pExpr->op = TK_COLUMN;
+ pExpr->y.pTab = pItem->pTab;
+ pExpr->iTable = pItem->iCursor;
+ pExpr->iColumn--;
+ pExpr->affExpr = SQLITE_AFF_INTEGER;
+ break;
+ }
+
+ /* A column name: ID
+ ** Or table name and column name: ID.ID
+ ** Or a database, table and column: ID.ID.ID
+ **
+ ** The TK_ID and TK_OUT cases are combined so that there will only
+ ** be one call to lookupName(). Then the compiler will in-line
+ ** lookupName() for a size reduction and performance increase.
+ */
+ case TK_ID:
+ case TK_DOT: {
+ const char *zColumn;
+ const char *zTable;
+ const char *zDb;
+ Expr *pRight;
+
+ if( pExpr->op==TK_ID ){
+ zDb = 0;
+ zTable = 0;
+ zColumn = pExpr->u.zToken;
+ }else{
+ Expr *pLeft = pExpr->pLeft;
+ testcase( pNC->ncFlags & NC_IdxExpr );
+ testcase( pNC->ncFlags & NC_GenCol );
+ sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator",
+ NC_IdxExpr|NC_GenCol, 0);
+ pRight = pExpr->pRight;
+ if( pRight->op==TK_ID ){
+ zDb = 0;
+ }else{
+ assert( pRight->op==TK_DOT );
+ zDb = pLeft->u.zToken;
+ pLeft = pRight->pLeft;
+ pRight = pRight->pRight;
+ }
+ zTable = pLeft->u.zToken;
+ zColumn = pRight->u.zToken;
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
+ sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
+ }
+ }
+ return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
+ }
+
+ /* Resolve function names
+ */
+ case TK_FUNCTION: {
+ ExprList *pList = pExpr->x.pList; /* The argument list */
+ int n = pList ? pList->nExpr : 0; /* Number of arguments */
+ int no_such_func = 0; /* True if no such function exists */
+ int wrong_num_args = 0; /* True if wrong number of arguments */
+ int is_agg = 0; /* True if is an aggregate function */
+ int nId; /* Number of characters in function name */
+ const char *zId; /* The function name. */
+ FuncDef *pDef; /* Information about the function */
+ u8 enc = ENC(pParse->db); /* The database encoding */
+ int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
+#endif
+ assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
+ zId = pExpr->u.zToken;
+ nId = sqlite3Strlen30(zId);
+ pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
+ if( pDef==0 ){
+ pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
+ if( pDef==0 ){
+ no_such_func = 1;
+ }else{
+ wrong_num_args = 1;
+ }
+ }else{
+ is_agg = pDef->xFinalize!=0;
+ if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
+ ExprSetProperty(pExpr, EP_Unlikely);
+ if( n==2 ){
+ pExpr->iTable = exprProbability(pList->a[1].pExpr);
+ if( pExpr->iTable<0 ){
+ sqlite3ErrorMsg(pParse,
+ "second argument to likelihood() must be a "
+ "constant between 0.0 and 1.0");
+ pNC->nErr++;
+ }
+ }else{
+ /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
+ ** equivalent to likelihood(X, 0.0625).
+ ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
+ ** short-hand for likelihood(X,0.0625).
+ ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
+ ** for likelihood(X,0.9375).
+ ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
+ ** to likelihood(X,0.9375). */
+ /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
+ pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
+ }
+ }
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ {
+ int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
+ if( auth!=SQLITE_OK ){
+ if( auth==SQLITE_DENY ){
+ sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
+ pDef->zName);
+ pNC->nErr++;
+ }
+ pExpr->op = TK_NULL;
+ return WRC_Prune;
+ }
+ }
+#endif
+ if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
+ /* For the purposes of the EP_ConstFunc flag, date and time
+ ** functions and other functions that change slowly are considered
+ ** constant because they are constant for the duration of one query.
+ ** This allows them to be factored out of inner loops. */
+ ExprSetProperty(pExpr,EP_ConstFunc);
+ }
+ if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
+ /* Clearly non-deterministic functions like random(), but also
+ ** date/time functions that use 'now', and other functions like
+ ** sqlite_version() that might change over time cannot be used
+ ** in an index or generated column. Curiously, they can be used
+ ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all
+ ** all this. */
+ sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",
+ NC_IdxExpr|NC_PartIdx|NC_GenCol, 0);
+ }else{
+ assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */
+ pExpr->op2 = pNC->ncFlags & NC_SelfRef;
+ if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);
+ }
+ if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
+ && pParse->nested==0
+ && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0
+ ){
+ /* Internal-use-only functions are disallowed unless the
+ ** SQL is being compiled using sqlite3NestedParse() or
+ ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
+ ** used to activate internal functionsn for testing purposes */
+ no_such_func = 1;
+ pDef = 0;
+ }else
+ if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0
+ && !IN_RENAME_OBJECT
+ ){
+ sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
+ }
+ }
+
+ if( 0==IN_RENAME_OBJECT ){
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
+ || (pDef->xValue==0 && pDef->xInverse==0)
+ || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
+ );
+ if( pDef && pDef->xValue==0 && pWin ){
+ sqlite3ErrorMsg(pParse,
+ "%.*s() may not be used as a window function", nId, zId
+ );
+ pNC->nErr++;
+ }else if(
+ (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
+ || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
+ || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)
+ ){
+ const char *zType;
+ if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){
+ zType = "window";
+ }else{
+ zType = "aggregate";
+ }
+ sqlite3ErrorMsg(pParse, "misuse of %s function %.*s()",zType,nId,zId);
+ pNC->nErr++;
+ is_agg = 0;
+ }
+#else
+ if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
+ sqlite3ErrorMsg(pParse,"misuse of aggregate function %.*s()",nId,zId);
+ pNC->nErr++;
+ is_agg = 0;
+ }
+#endif
+ else if( no_such_func && pParse->db->init.busy==0
+#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
+ && pParse->explain==0
+#endif
+ ){
+ sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
+ pNC->nErr++;
+ }else if( wrong_num_args ){
+ sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
+ nId, zId);
+ pNC->nErr++;
+ }
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
+ sqlite3ErrorMsg(pParse,
+ "FILTER may not be used with non-aggregate %.*s()",
+ nId, zId
+ );
+ pNC->nErr++;
+ }
+#endif
+ if( is_agg ){
+ /* Window functions may not be arguments of aggregate functions.
+ ** Or arguments of other window functions. But aggregate functions
+ ** may be arguments for window functions. */
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
+#else
+ pNC->ncFlags &= ~NC_AllowAgg;
+#endif
+ }
+ }
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ else if( ExprHasProperty(pExpr, EP_WinFunc) ){
+ is_agg = 1;
+ }
+#endif
+ sqlite3WalkExprList(pWalker, pList);
+ if( is_agg ){
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( pWin ){
+ Select *pSel = pNC->pWinSelect;
+ assert( pWin==pExpr->y.pWin );
+ if( IN_RENAME_OBJECT==0 ){
+ sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
+ }
+ sqlite3WalkExprList(pWalker, pWin->pPartition);
+ sqlite3WalkExprList(pWalker, pWin->pOrderBy);
+ sqlite3WalkExpr(pWalker, pWin->pFilter);
+ sqlite3WindowLink(pSel, pWin);
+ pNC->ncFlags |= NC_HasWin;
+ }else
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+ {
+ NameContext *pNC2 = pNC;
+ pExpr->op = TK_AGG_FUNCTION;
+ pExpr->op2 = 0;
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( ExprHasProperty(pExpr, EP_WinFunc) ){
+ sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
+ }
+#endif
+ while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
+ pExpr->op2++;
+ pNC2 = pNC2->pNext;
+ }
+ assert( pDef!=0 || IN_RENAME_OBJECT );
+ if( pNC2 && pDef ){
+ assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
+ testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
+ pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
+
+ }
+ }
+ pNC->ncFlags |= savedAllowFlags;
+ }
+ /* FIX ME: Compute pExpr->affinity based on the expected return
+ ** type of the function
+ */
+ return WRC_Prune;
+ }
+#ifndef SQLITE_OMIT_SUBQUERY
+ case TK_SELECT:
+ case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
+#endif
+ case TK_IN: {
+ testcase( pExpr->op==TK_IN );
+ if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+ int nRef = pNC->nRef;
+ testcase( pNC->ncFlags & NC_IsCheck );
+ testcase( pNC->ncFlags & NC_PartIdx );
+ testcase( pNC->ncFlags & NC_IdxExpr );
+ testcase( pNC->ncFlags & NC_GenCol );
+ sqlite3ResolveNotValid(pParse, pNC, "subqueries",
+ NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr);
+ sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
+ assert( pNC->nRef>=nRef );
+ if( nRef!=pNC->nRef ){
+ ExprSetProperty(pExpr, EP_VarSelect);
+ pNC->ncFlags |= NC_VarSelect;
+ }
+ }
+ break;
+ }
+ case TK_VARIABLE: {
+ testcase( pNC->ncFlags & NC_IsCheck );
+ testcase( pNC->ncFlags & NC_PartIdx );
+ testcase( pNC->ncFlags & NC_IdxExpr );
+ testcase( pNC->ncFlags & NC_GenCol );
+ sqlite3ResolveNotValid(pParse, pNC, "parameters",
+ NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr);
+ break;
+ }
+ case TK_IS:
+ case TK_ISNOT: {
+ Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
+ assert( !ExprHasProperty(pExpr, EP_Reduced) );
+ /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
+ ** and "x IS NOT FALSE". */
+ if( pRight && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
+ int rc = resolveExprStep(pWalker, pRight);
+ if( rc==WRC_Abort ) return WRC_Abort;
+ if( pRight->op==TK_TRUEFALSE ){
+ pExpr->op2 = pExpr->op;
+ pExpr->op = TK_TRUTH;
+ return WRC_Continue;
+ }
+ }
+ /* no break */ deliberate_fall_through
+ }
+ case TK_BETWEEN:
+ case TK_EQ:
+ case TK_NE:
+ case TK_LT:
+ case TK_LE:
+ case TK_GT:
+ case TK_GE: {
+ int nLeft, nRight;
+ if( pParse->db->mallocFailed ) break;
+ assert( pExpr->pLeft!=0 );
+ nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
+ if( pExpr->op==TK_BETWEEN ){
+ nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
+ if( nRight==nLeft ){
+ nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
+ }
+ }else{
+ assert( pExpr->pRight!=0 );
+ nRight = sqlite3ExprVectorSize(pExpr->pRight);
+ }
+ if( nLeft!=nRight ){
+ testcase( pExpr->op==TK_EQ );
+ testcase( pExpr->op==TK_NE );
+ testcase( pExpr->op==TK_LT );
+ testcase( pExpr->op==TK_LE );
+ testcase( pExpr->op==TK_GT );
+ testcase( pExpr->op==TK_GE );
+ testcase( pExpr->op==TK_IS );
+ testcase( pExpr->op==TK_ISNOT );
+ testcase( pExpr->op==TK_BETWEEN );
+ sqlite3ErrorMsg(pParse, "row value misused");
+ }
+ break;
+ }
+ }
+ return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
+}
+
+/*
+** pEList is a list of expressions which are really the result set of the
+** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
+** This routine checks to see if pE is a simple identifier which corresponds
+** to the AS-name of one of the terms of the expression list. If it is,
+** this routine return an integer between 1 and N where N is the number of
+** elements in pEList, corresponding to the matching entry. If there is
+** no match, or if pE is not a simple identifier, then this routine
+** return 0.
+**
+** pEList has been resolved. pE has not.
+*/
+static int resolveAsName(
+ Parse *pParse, /* Parsing context for error messages */
+ ExprList *pEList, /* List of expressions to scan */
+ Expr *pE /* Expression we are trying to match */
+){
+ int i; /* Loop counter */
+
+ UNUSED_PARAMETER(pParse);
+
+ if( pE->op==TK_ID ){
+ char *zCol = pE->u.zToken;
+ for(i=0; i<pEList->nExpr; i++){
+ if( pEList->a[i].eEName==ENAME_NAME
+ && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
+ ){
+ return i+1;
+ }
+ }
+ }
+ return 0;
+}
+
+/*
+** pE is a pointer to an expression which is a single term in the
+** ORDER BY of a compound SELECT. The expression has not been
+** name resolved.
+**
+** At the point this routine is called, we already know that the
+** ORDER BY term is not an integer index into the result set. That
+** case is handled by the calling routine.
+**
+** Attempt to match pE against result set columns in the left-most
+** SELECT statement. Return the index i of the matching column,
+** as an indication to the caller that it should sort by the i-th column.
+** The left-most column is 1. In other words, the value returned is the
+** same integer value that would be used in the SQL statement to indicate
+** the column.
+**
+** If there is no match, return 0. Return -1 if an error occurs.
+*/
+static int resolveOrderByTermToExprList(
+ Parse *pParse, /* Parsing context for error messages */
+ Select *pSelect, /* The SELECT statement with the ORDER BY clause */
+ Expr *pE /* The specific ORDER BY term */
+){
+ int i; /* Loop counter */
+ ExprList *pEList; /* The columns of the result set */
+ NameContext nc; /* Name context for resolving pE */
+ sqlite3 *db; /* Database connection */
+ int rc; /* Return code from subprocedures */
+ u8 savedSuppErr; /* Saved value of db->suppressErr */
+
+ assert( sqlite3ExprIsInteger(pE, &i)==0 );
+ pEList = pSelect->pEList;
+
+ /* Resolve all names in the ORDER BY term expression
+ */
+ memset(&nc, 0, sizeof(nc));
+ nc.pParse = pParse;
+ nc.pSrcList = pSelect->pSrc;
+ nc.uNC.pEList = pEList;
+ nc.ncFlags = NC_AllowAgg|NC_UEList;
+ nc.nErr = 0;
+ db = pParse->db;
+ savedSuppErr = db->suppressErr;
+ if( IN_RENAME_OBJECT==0 ) db->suppressErr = 1;
+ rc = sqlite3ResolveExprNames(&nc, pE);
+ db->suppressErr = savedSuppErr;
+ if( rc ) return 0;
+
+ /* Try to match the ORDER BY expression against an expression
+ ** in the result set. Return an 1-based index of the matching
+ ** result-set entry.
+ */
+ for(i=0; i<pEList->nExpr; i++){
+ if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
+ return i+1;
+ }
+ }
+
+ /* If no match, return 0. */
+ return 0;
+}
+
+/*
+** Generate an ORDER BY or GROUP BY term out-of-range error.
+*/
+static void resolveOutOfRangeError(
+ Parse *pParse, /* The error context into which to write the error */
+ const char *zType, /* "ORDER" or "GROUP" */
+ int i, /* The index (1-based) of the term out of range */
+ int mx /* Largest permissible value of i */
+){
+ sqlite3ErrorMsg(pParse,
+ "%r %s BY term out of range - should be "
+ "between 1 and %d", i, zType, mx);
+}
+
+/*
+** Analyze the ORDER BY clause in a compound SELECT statement. Modify
+** each term of the ORDER BY clause is a constant integer between 1
+** and N where N is the number of columns in the compound SELECT.
+**
+** ORDER BY terms that are already an integer between 1 and N are
+** unmodified. ORDER BY terms that are integers outside the range of
+** 1 through N generate an error. ORDER BY terms that are expressions
+** are matched against result set expressions of compound SELECT
+** beginning with the left-most SELECT and working toward the right.
+** At the first match, the ORDER BY expression is transformed into
+** the integer column number.
+**
+** Return the number of errors seen.
+*/
+static int resolveCompoundOrderBy(
+ Parse *pParse, /* Parsing context. Leave error messages here */
+ Select *pSelect /* The SELECT statement containing the ORDER BY */
+){
+ int i;
+ ExprList *pOrderBy;
+ ExprList *pEList;
+ sqlite3 *db;
+ int moreToDo = 1;
+
+ pOrderBy = pSelect->pOrderBy;
+ if( pOrderBy==0 ) return 0;
+ db = pParse->db;
+ if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
+ sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
+ return 1;
+ }
+ for(i=0; i<pOrderBy->nExpr; i++){
+ pOrderBy->a[i].done = 0;
+ }
+ pSelect->pNext = 0;
+ while( pSelect->pPrior ){
+ pSelect->pPrior->pNext = pSelect;
+ pSelect = pSelect->pPrior;
+ }
+ while( pSelect && moreToDo ){
+ struct ExprList_item *pItem;
+ moreToDo = 0;
+ pEList = pSelect->pEList;
+ assert( pEList!=0 );
+ for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
+ int iCol = -1;
+ Expr *pE, *pDup;
+ if( pItem->done ) continue;
+ pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
+ if( sqlite3ExprIsInteger(pE, &iCol) ){
+ if( iCol<=0 || iCol>pEList->nExpr ){
+ resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
+ return 1;
+ }
+ }else{
+ iCol = resolveAsName(pParse, pEList, pE);
+ if( iCol==0 ){
+ /* Now test if expression pE matches one of the values returned
+ ** by pSelect. In the usual case this is done by duplicating the
+ ** expression, resolving any symbols in it, and then comparing
+ ** it against each expression returned by the SELECT statement.
+ ** Once the comparisons are finished, the duplicate expression
+ ** is deleted.
+ **
+ ** Or, if this is running as part of an ALTER TABLE operation,
+ ** resolve the symbols in the actual expression, not a duplicate.
+ ** And, if one of the comparisons is successful, leave the expression
+ ** as is instead of transforming it to an integer as in the usual
+ ** case. This allows the code in alter.c to modify column
+ ** refererences within the ORDER BY expression as required. */
+ if( IN_RENAME_OBJECT ){
+ pDup = pE;
+ }else{
+ pDup = sqlite3ExprDup(db, pE, 0);
+ }
+ if( !db->mallocFailed ){
+ assert(pDup);
+ iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
+ }
+ if( !IN_RENAME_OBJECT ){
+ sqlite3ExprDelete(db, pDup);
+ }
+ }
+ }
+ if( iCol>0 ){
+ /* Convert the ORDER BY term into an integer column number iCol,
+ ** taking care to preserve the COLLATE clause if it exists */
+ if( !IN_RENAME_OBJECT ){
+ Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
+ if( pNew==0 ) return 1;
+ pNew->flags |= EP_IntValue;
+ pNew->u.iValue = iCol;
+ if( pItem->pExpr==pE ){
+ pItem->pExpr = pNew;
+ }else{
+ Expr *pParent = pItem->pExpr;
+ assert( pParent->op==TK_COLLATE );
+ while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
+ assert( pParent->pLeft==pE );
+ pParent->pLeft = pNew;
+ }
+ sqlite3ExprDelete(db, pE);
+ pItem->u.x.iOrderByCol = (u16)iCol;
+ }
+ pItem->done = 1;
+ }else{
+ moreToDo = 1;
+ }
+ }
+ pSelect = pSelect->pNext;
+ }
+ for(i=0; i<pOrderBy->nExpr; i++){
+ if( pOrderBy->a[i].done==0 ){
+ sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
+ "column in the result set", i+1);
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/*
+** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
+** the SELECT statement pSelect. If any term is reference to a
+** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
+** field) then convert that term into a copy of the corresponding result set
+** column.
+**
+** If any errors are detected, add an error message to pParse and
+** return non-zero. Return zero if no errors are seen.
+*/
+SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
+ Parse *pParse, /* Parsing context. Leave error messages here */
+ Select *pSelect, /* The SELECT statement containing the clause */
+ ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
+ const char *zType /* "ORDER" or "GROUP" */
+){
+ int i;
+ sqlite3 *db = pParse->db;
+ ExprList *pEList;
+ struct ExprList_item *pItem;
+
+ if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;
+ if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
+ sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
+ return 1;
+ }
+ pEList = pSelect->pEList;
+ assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
+ for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
+ if( pItem->u.x.iOrderByCol ){
+ if( pItem->u.x.iOrderByCol>pEList->nExpr ){
+ resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
+ return 1;
+ }
+ resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
+ zType,0);
+ }
+ }
+ return 0;
+}
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+/*
+** Walker callback for windowRemoveExprFromSelect().
+*/
+static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
+ UNUSED_PARAMETER(pWalker);
+ if( ExprHasProperty(pExpr, EP_WinFunc) ){
+ Window *pWin = pExpr->y.pWin;
+ sqlite3WindowUnlinkFromSelect(pWin);
+ }
+ return WRC_Continue;
+}
+
+/*
+** Remove any Window objects owned by the expression pExpr from the
+** Select.pWin list of Select object pSelect.
+*/
+static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){
+ if( pSelect->pWin ){
+ Walker sWalker;
+ memset(&sWalker, 0, sizeof(Walker));
+ sWalker.xExprCallback = resolveRemoveWindowsCb;
+ sWalker.u.pSelect = pSelect;
+ sqlite3WalkExpr(&sWalker, pExpr);
+ }
+}
+#else
+# define windowRemoveExprFromSelect(a, b)
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+
+/*
+** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
+** The Name context of the SELECT statement is pNC. zType is either
+** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
+**
+** This routine resolves each term of the clause into an expression.
+** If the order-by term is an integer I between 1 and N (where N is the
+** number of columns in the result set of the SELECT) then the expression
+** in the resolution is a copy of the I-th result-set expression. If
+** the order-by term is an identifier that corresponds to the AS-name of
+** a result-set expression, then the term resolves to a copy of the
+** result-set expression. Otherwise, the expression is resolved in
+** the usual way - using sqlite3ResolveExprNames().
+**
+** This routine returns the number of errors. If errors occur, then
+** an appropriate error message might be left in pParse. (OOM errors
+** excepted.)
+*/
+static int resolveOrderGroupBy(
+ NameContext *pNC, /* The name context of the SELECT statement */
+ Select *pSelect, /* The SELECT statement holding pOrderBy */
+ ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
+ const char *zType /* Either "ORDER" or "GROUP", as appropriate */
+){
+ int i, j; /* Loop counters */
+ int iCol; /* Column number */
+ struct ExprList_item *pItem; /* A term of the ORDER BY clause */
+ Parse *pParse; /* Parsing context */
+ int nResult; /* Number of terms in the result set */
+
+ if( pOrderBy==0 ) return 0;
+ nResult = pSelect->pEList->nExpr;
+ pParse = pNC->pParse;
+ for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
+ Expr *pE = pItem->pExpr;
+ Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
+ if( zType[0]!='G' ){
+ iCol = resolveAsName(pParse, pSelect->pEList, pE2);
+ if( iCol>0 ){
+ /* If an AS-name match is found, mark this ORDER BY column as being
+ ** a copy of the iCol-th result-set column. The subsequent call to
+ ** sqlite3ResolveOrderGroupBy() will convert the expression to a
+ ** copy of the iCol-th result-set expression. */
+ pItem->u.x.iOrderByCol = (u16)iCol;
+ continue;
+ }
+ }
+ if( sqlite3ExprIsInteger(pE2, &iCol) ){
+ /* The ORDER BY term is an integer constant. Again, set the column
+ ** number so that sqlite3ResolveOrderGroupBy() will convert the
+ ** order-by term to a copy of the result-set expression */
+ if( iCol<1 || iCol>0xffff ){
+ resolveOutOfRangeError(pParse, zType, i+1, nResult);
+ return 1;
+ }
+ pItem->u.x.iOrderByCol = (u16)iCol;
+ continue;
+ }
+
+ /* Otherwise, treat the ORDER BY term as an ordinary expression */
+ pItem->u.x.iOrderByCol = 0;
+ if( sqlite3ResolveExprNames(pNC, pE) ){
+ return 1;
+ }
+ for(j=0; j<pSelect->pEList->nExpr; j++){
+ if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
+ /* Since this expresion is being changed into a reference
+ ** to an identical expression in the result set, remove all Window
+ ** objects belonging to the expression from the Select.pWin list. */
+ windowRemoveExprFromSelect(pSelect, pE);
+ pItem->u.x.iOrderByCol = j+1;
+ }
+ }
+ }
+ return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
+}
+
+/*
+** Resolve names in the SELECT statement p and all of its descendants.
+*/
+static int resolveSelectStep(Walker *pWalker, Select *p){
+ NameContext *pOuterNC; /* Context that contains this SELECT */
+ NameContext sNC; /* Name context of this SELECT */
+ int isCompound; /* True if p is a compound select */
+ int nCompound; /* Number of compound terms processed so far */
+ Parse *pParse; /* Parsing context */
+ int i; /* Loop counter */
+ ExprList *pGroupBy; /* The GROUP BY clause */
+ Select *pLeftmost; /* Left-most of SELECT of a compound */
+ sqlite3 *db; /* Database connection */
+
+
+ assert( p!=0 );
+ if( p->selFlags & SF_Resolved ){
+ return WRC_Prune;
+ }
+ pOuterNC = pWalker->u.pNC;
+ pParse = pWalker->pParse;
+ db = pParse->db;
+
+ /* Normally sqlite3SelectExpand() will be called first and will have
+ ** already expanded this SELECT. However, if this is a subquery within
+ ** an expression, sqlite3ResolveExprNames() will be called without a
+ ** prior call to sqlite3SelectExpand(). When that happens, let
+ ** sqlite3SelectPrep() do all of the processing for this SELECT.
+ ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
+ ** this routine in the correct order.
+ */
+ if( (p->selFlags & SF_Expanded)==0 ){
+ sqlite3SelectPrep(pParse, p, pOuterNC);
+ return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
+ }
+
+ isCompound = p->pPrior!=0;
+ nCompound = 0;
+ pLeftmost = p;
+ while( p ){
+ assert( (p->selFlags & SF_Expanded)!=0 );
+ assert( (p->selFlags & SF_Resolved)==0 );
+ p->selFlags |= SF_Resolved;
+
+ /* Resolve the expressions in the LIMIT and OFFSET clauses. These
+ ** are not allowed to refer to any names, so pass an empty NameContext.
+ */
+ memset(&sNC, 0, sizeof(sNC));
+ sNC.pParse = pParse;
+ sNC.pWinSelect = p;
+ if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
+ return WRC_Abort;
+ }
+
+ /* If the SF_Converted flags is set, then this Select object was
+ ** was created by the convertCompoundSelectToSubquery() function.
+ ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
+ ** as if it were part of the sub-query, not the parent. This block
+ ** moves the pOrderBy down to the sub-query. It will be moved back
+ ** after the names have been resolved. */
+ if( p->selFlags & SF_Converted ){
+ Select *pSub = p->pSrc->a[0].pSelect;
+ assert( p->pSrc->nSrc==1 && p->pOrderBy );
+ assert( pSub->pPrior && pSub->pOrderBy==0 );
+ pSub->pOrderBy = p->pOrderBy;
+ p->pOrderBy = 0;
+ }
+
+ /* Recursively resolve names in all subqueries
+ */
+ for(i=0; i<p->pSrc->nSrc; i++){
+ struct SrcList_item *pItem = &p->pSrc->a[i];
+ if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
+ NameContext *pNC; /* Used to iterate name contexts */
+ int nRef = 0; /* Refcount for pOuterNC and outer contexts */
+ const char *zSavedContext = pParse->zAuthContext;
+
+ /* Count the total number of references to pOuterNC and all of its
+ ** parent contexts. After resolving references to expressions in
+ ** pItem->pSelect, check if this value has changed. If so, then
+ ** SELECT statement pItem->pSelect must be correlated. Set the
+ ** pItem->fg.isCorrelated flag if this is the case. */
+ for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
+
+ if( pItem->zName ) pParse->zAuthContext = pItem->zName;
+ sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
+ pParse->zAuthContext = zSavedContext;
+ if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
+
+ for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
+ assert( pItem->fg.isCorrelated==0 && nRef<=0 );
+ pItem->fg.isCorrelated = (nRef!=0);
+ }
+ }
+
+ /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
+ ** resolve the result-set expression list.
+ */
+ sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
+ sNC.pSrcList = p->pSrc;
+ sNC.pNext = pOuterNC;
+
+ /* Resolve names in the result set. */
+ if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
+ sNC.ncFlags &= ~NC_AllowWin;
+
+ /* If there are no aggregate functions in the result-set, and no GROUP BY
+ ** expression, do not allow aggregates in any of the other expressions.
+ */
+ assert( (p->selFlags & SF_Aggregate)==0 );
+ pGroupBy = p->pGroupBy;
+ if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
+ assert( NC_MinMaxAgg==SF_MinMaxAgg );
+ p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
+ }else{
+ sNC.ncFlags &= ~NC_AllowAgg;
+ }
+
+ /* If a HAVING clause is present, then there must be a GROUP BY clause.
+ */
+ if( p->pHaving && !pGroupBy ){
+ sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
+ return WRC_Abort;
+ }
+
+ /* Add the output column list to the name-context before parsing the
+ ** other expressions in the SELECT statement. This is so that
+ ** expressions in the WHERE clause (etc.) can refer to expressions by
+ ** aliases in the result set.
+ **
+ ** Minor point: If this is the case, then the expression will be
+ ** re-evaluated for each reference to it.
+ */
+ assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert))==0 );
+ sNC.uNC.pEList = p->pEList;
+ sNC.ncFlags |= NC_UEList;
+ if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
+ if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
+
+ /* Resolve names in table-valued-function arguments */
+ for(i=0; i<p->pSrc->nSrc; i++){
+ struct SrcList_item *pItem = &p->pSrc->a[i];
+ if( pItem->fg.isTabFunc
+ && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
+ ){
+ return WRC_Abort;
+ }
+ }
+
+ /* The ORDER BY and GROUP BY clauses may not refer to terms in
+ ** outer queries
+ */
+ sNC.pNext = 0;
+ sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
+
+ /* If this is a converted compound query, move the ORDER BY clause from
+ ** the sub-query back to the parent query. At this point each term
+ ** within the ORDER BY clause has been transformed to an integer value.
+ ** These integers will be replaced by copies of the corresponding result
+ ** set expressions by the call to resolveOrderGroupBy() below. */
+ if( p->selFlags & SF_Converted ){
+ Select *pSub = p->pSrc->a[0].pSelect;
+ p->pOrderBy = pSub->pOrderBy;
+ pSub->pOrderBy = 0;
+ }
+
+ /* Process the ORDER BY clause for singleton SELECT statements.
+ ** The ORDER BY clause for compounds SELECT statements is handled
+ ** below, after all of the result-sets for all of the elements of
+ ** the compound have been resolved.
+ **
+ ** If there is an ORDER BY clause on a term of a compound-select other
+ ** than the right-most term, then that is a syntax error. But the error
+ ** is not detected until much later, and so we need to go ahead and
+ ** resolve those symbols on the incorrect ORDER BY for consistency.
+ */
+ if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
+ && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
+ ){
+ return WRC_Abort;
+ }
+ if( db->mallocFailed ){
+ return WRC_Abort;
+ }
+ sNC.ncFlags &= ~NC_AllowWin;
+
+ /* Resolve the GROUP BY clause. At the same time, make sure
+ ** the GROUP BY clause does not contain aggregate functions.
+ */
+ if( pGroupBy ){
+ struct ExprList_item *pItem;
+
+ if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
+ return WRC_Abort;
+ }
+ for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
+ if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
+ sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
+ "the GROUP BY clause");
+ return WRC_Abort;
+ }
+ }
+ }
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( IN_RENAME_OBJECT ){
+ Window *pWin;
+ for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
+ if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
+ || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
+ ){
+ return WRC_Abort;
+ }
+ }
+ }
+#endif
+
+ /* If this is part of a compound SELECT, check that it has the right
+ ** number of expressions in the select list. */
+ if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
+ sqlite3SelectWrongNumTermsError(pParse, p->pNext);
+ return WRC_Abort;
+ }
+
+ /* Advance to the next term of the compound
+ */
+ p = p->pPrior;
+ nCompound++;
+ }
+
+ /* Resolve the ORDER BY on a compound SELECT after all terms of
+ ** the compound have been resolved.
+ */
+ if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
+ return WRC_Abort;
+ }
+
+ return WRC_Prune;
+}
+
+/*
+** This routine walks an expression tree and resolves references to
+** table columns and result-set columns. At the same time, do error
+** checking on function usage and set a flag if any aggregate functions
+** are seen.
+**
+** To resolve table columns references we look for nodes (or subtrees) of the
+** form X.Y.Z or Y.Z or just Z where
+**
+** X: The name of a database. Ex: "main" or "temp" or
+** the symbolic name assigned to an ATTACH-ed database.
+**
+** Y: The name of a table in a FROM clause. Or in a trigger
+** one of the special names "old" or "new".
+**
+** Z: The name of a column in table Y.
+**
+** The node at the root of the subtree is modified as follows:
+**
+** Expr.op Changed to TK_COLUMN
+** Expr.pTab Points to the Table object for X.Y
+** Expr.iColumn The column index in X.Y. -1 for the rowid.
+** Expr.iTable The VDBE cursor number for X.Y
+**
+**
+** To resolve result-set references, look for expression nodes of the
+** form Z (with no X and Y prefix) where the Z matches the right-hand
+** size of an AS clause in the result-set of a SELECT. The Z expression
+** is replaced by a copy of the left-hand side of the result-set expression.
+** Table-name and function resolution occurs on the substituted expression
+** tree. For example, in:
+**
+** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
+**
+** The "x" term of the order by is replaced by "a+b" to render:
+**
+** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
+**
+** Function calls are checked to make sure that the function is
+** defined and that the correct number of arguments are specified.
+** If the function is an aggregate function, then the NC_HasAgg flag is
+** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
+** If an expression contains aggregate functions then the EP_Agg
+** property on the expression is set.
+**
+** An error message is left in pParse if anything is amiss. The number
+** if errors is returned.
+*/
+SQLITE_PRIVATE int sqlite3ResolveExprNames(
+ NameContext *pNC, /* Namespace to resolve expressions in. */
+ Expr *pExpr /* The expression to be analyzed. */
+){
+ int savedHasAgg;
+ Walker w;
+
+ if( pExpr==0 ) return SQLITE_OK;
+ savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
+ pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
+ w.pParse = pNC->pParse;
+ w.xExprCallback = resolveExprStep;
+ w.xSelectCallback = resolveSelectStep;
+ w.xSelectCallback2 = 0;
+ w.u.pNC = pNC;
+#if SQLITE_MAX_EXPR_DEPTH>0
+ w.pParse->nHeight += pExpr->nHeight;
+ if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
+ return SQLITE_ERROR;
+ }
+#endif
+ sqlite3WalkExpr(&w, pExpr);
+#if SQLITE_MAX_EXPR_DEPTH>0
+ w.pParse->nHeight -= pExpr->nHeight;
+#endif
+ assert( EP_Agg==NC_HasAgg );
+ assert( EP_Win==NC_HasWin );
+ testcase( pNC->ncFlags & NC_HasAgg );
+ testcase( pNC->ncFlags & NC_HasWin );
+ ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
+ pNC->ncFlags |= savedHasAgg;
+ return pNC->nErr>0 || w.pParse->nErr>0;
+}
+
+/*
+** Resolve all names for all expression in an expression list. This is
+** just like sqlite3ResolveExprNames() except that it works for an expression
+** list rather than a single expression.
+*/
+SQLITE_PRIVATE int sqlite3ResolveExprListNames(
+ NameContext *pNC, /* Namespace to resolve expressions in. */
+ ExprList *pList /* The expression list to be analyzed. */
+){
+ int i;
+ int savedHasAgg = 0;
+ Walker w;
+ if( pList==0 ) return WRC_Continue;
+ w.pParse = pNC->pParse;
+ w.xExprCallback = resolveExprStep;
+ w.xSelectCallback = resolveSelectStep;
+ w.xSelectCallback2 = 0;
+ w.u.pNC = pNC;
+ savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
+ pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
+ for(i=0; i<pList->nExpr; i++){
+ Expr *pExpr = pList->a[i].pExpr;
+ if( pExpr==0 ) continue;
+#if SQLITE_MAX_EXPR_DEPTH>0
+ w.pParse->nHeight += pExpr->nHeight;
+ if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
+ return WRC_Abort;
+ }
+#endif
+ sqlite3WalkExpr(&w, pExpr);
+#if SQLITE_MAX_EXPR_DEPTH>0
+ w.pParse->nHeight -= pExpr->nHeight;
+#endif
+ assert( EP_Agg==NC_HasAgg );
+ assert( EP_Win==NC_HasWin );
+ testcase( pNC->ncFlags & NC_HasAgg );
+ testcase( pNC->ncFlags & NC_HasWin );
+ if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin) ){
+ ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
+ savedHasAgg |= pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
+ pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
+ }
+ if( pNC->nErr>0 || w.pParse->nErr>0 ) return WRC_Abort;
+ }
+ pNC->ncFlags |= savedHasAgg;
+ return WRC_Continue;
+}
+
+/*
+** Resolve all names in all expressions of a SELECT and in all
+** decendents of the SELECT, including compounds off of p->pPrior,
+** subqueries in expressions, and subqueries used as FROM clause
+** terms.
+**
+** See sqlite3ResolveExprNames() for a description of the kinds of
+** transformations that occur.
+**
+** All SELECT statements should have been expanded using
+** sqlite3SelectExpand() prior to invoking this routine.
+*/
+SQLITE_PRIVATE void sqlite3ResolveSelectNames(
+ Parse *pParse, /* The parser context */
+ Select *p, /* The SELECT statement being coded. */
+ NameContext *pOuterNC /* Name context for parent SELECT statement */
+){
+ Walker w;
+
+ assert( p!=0 );
+ w.xExprCallback = resolveExprStep;
+ w.xSelectCallback = resolveSelectStep;
+ w.xSelectCallback2 = 0;
+ w.pParse = pParse;
+ w.u.pNC = pOuterNC;
+ sqlite3WalkSelect(&w, p);
+}
+
+/*
+** Resolve names in expressions that can only reference a single table
+** or which cannot reference any tables at all. Examples:
+**
+** "type" flag
+** ------------
+** (1) CHECK constraints NC_IsCheck
+** (2) WHERE clauses on partial indices NC_PartIdx
+** (3) Expressions in indexes on expressions NC_IdxExpr
+** (4) Expression arguments to VACUUM INTO. 0
+** (5) GENERATED ALWAYS as expressions NC_GenCol
+**
+** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
+** nodes of the expression is set to -1 and the Expr.iColumn value is
+** set to the column number. In case (4), TK_COLUMN nodes cause an error.
+**
+** Any errors cause an error message to be set in pParse.
+*/
+SQLITE_PRIVATE int sqlite3ResolveSelfReference(
+ Parse *pParse, /* Parsing context */
+ Table *pTab, /* The table being referenced, or NULL */
+ int type, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
+ Expr *pExpr, /* Expression to resolve. May be NULL. */
+ ExprList *pList /* Expression list to resolve. May be NULL. */
+){
+ SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
+ NameContext sNC; /* Name context for pParse->pNewTable */
+ int rc;
+
+ assert( type==0 || pTab!=0 );
+ assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr
+ || type==NC_GenCol || pTab==0 );
+ memset(&sNC, 0, sizeof(sNC));
+ memset(&sSrc, 0, sizeof(sSrc));
+ if( pTab ){
+ sSrc.nSrc = 1;
+ sSrc.a[0].zName = pTab->zName;
+ sSrc.a[0].pTab = pTab;
+ sSrc.a[0].iCursor = -1;
+ if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){
+ /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
+ ** schema elements */
+ type |= NC_FromDDL;
+ }
+ }
+ sNC.pParse = pParse;
+ sNC.pSrcList = &sSrc;
+ sNC.ncFlags = type | NC_IsDDL;
+ if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
+ if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
+ return rc;
+}
+
+/************** End of resolve.c *********************************************/
+/************** Begin file expr.c ********************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains routines used for analyzing expressions and
+** for generating VDBE code that evaluates expressions in SQLite.
+*/
+/* #include "sqliteInt.h" */
+
+/* Forward declarations */
+static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
+static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
+
+/*
+** Return the affinity character for a single column of a table.
+*/
+SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
+ assert( iCol<pTab->nCol );
+ return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
+}
+
+/*
+** Return the 'affinity' of the expression pExpr if any.
+**
+** If pExpr is a column, a reference to a column via an 'AS' alias,
+** or a sub-select with a column as the return value, then the
+** affinity of that column is returned. Otherwise, 0x00 is returned,
+** indicating no affinity for the expression.
+**
+** i.e. the WHERE clause expressions in the following statements all
+** have an affinity:
+**
+** CREATE TABLE t1(a);
+** SELECT * FROM t1 WHERE a;
+** SELECT a AS b FROM t1 WHERE b;
+** SELECT * FROM t1 WHERE (select a from t1);
+*/
+SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr){
+ int op;
+ while( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){
+ assert( pExpr->op==TK_COLLATE
+ || pExpr->op==TK_IF_NULL_ROW
+ || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) );
+ pExpr = pExpr->pLeft;
+ assert( pExpr!=0 );
+ }
+ op = pExpr->op;
+ if( op==TK_SELECT ){
+ assert( pExpr->flags&EP_xIsSelect );
+ assert( pExpr->x.pSelect!=0 );
+ assert( pExpr->x.pSelect->pEList!=0 );
+ assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 );
+ return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
+ }
+ if( op==TK_REGISTER ) op = pExpr->op2;
+#ifndef SQLITE_OMIT_CAST
+ if( op==TK_CAST ){
+ assert( !ExprHasProperty(pExpr, EP_IntValue) );
+ return sqlite3AffinityType(pExpr->u.zToken, 0);
+ }
+#endif
+ if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
+ return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
+ }
+ if( op==TK_SELECT_COLUMN ){
+ assert( pExpr->pLeft->flags&EP_xIsSelect );
+ return sqlite3ExprAffinity(
+ pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
+ );
+ }
+ if( op==TK_VECTOR ){
+ return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
+ }
+ return pExpr->affExpr;
+}
+
+/*
+** Set the collating sequence for expression pExpr to be the collating
+** sequence named by pToken. Return a pointer to a new Expr node that
+** implements the COLLATE operator.
+**
+** If a memory allocation error occurs, that fact is recorded in pParse->db
+** and the pExpr parameter is returned unchanged.
+*/
+SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
+ Parse *pParse, /* Parsing context */
+ Expr *pExpr, /* Add the "COLLATE" clause to this expression */
+ const Token *pCollName, /* Name of collating sequence */
+ int dequote /* True to dequote pCollName */
+){
+ if( pCollName->n>0 ){
+ Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
+ if( pNew ){
+ pNew->pLeft = pExpr;
+ pNew->flags |= EP_Collate|EP_Skip;
+ pExpr = pNew;
+ }
+ }
+ return pExpr;
+}
+SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
+ Token s;
+ assert( zC!=0 );
+ sqlite3TokenInit(&s, (char*)zC);
+ return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
+}
+
+/*
+** Skip over any TK_COLLATE operators.
+*/
+SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
+ while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
+ assert( pExpr->op==TK_COLLATE );
+ pExpr = pExpr->pLeft;
+ }
+ return pExpr;
+}
+
+/*
+** Skip over any TK_COLLATE operators and/or any unlikely()
+** or likelihood() or likely() functions at the root of an
+** expression.
+*/
+SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
+ while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
+ if( ExprHasProperty(pExpr, EP_Unlikely) ){
+ assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
+ assert( pExpr->x.pList->nExpr>0 );
+ assert( pExpr->op==TK_FUNCTION );
+ pExpr = pExpr->x.pList->a[0].pExpr;
+ }else{
+ assert( pExpr->op==TK_COLLATE );
+ pExpr = pExpr->pLeft;
+ }
+ }
+ return pExpr;
+}
+
+/*
+** Return the collation sequence for the expression pExpr. If
+** there is no defined collating sequence, return NULL.
+**
+** See also: sqlite3ExprNNCollSeq()
+**
+** The sqlite3ExprNNCollSeq() works the same exact that it returns the
+** default collation if pExpr has no defined collation.
+**
+** The collating sequence might be determined by a COLLATE operator
+** or by the presence of a column with a defined collating sequence.
+** COLLATE operators take first precedence. Left operands take
+** precedence over right operands.
+*/
+SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){
+ sqlite3 *db = pParse->db;
+ CollSeq *pColl = 0;
+ const Expr *p = pExpr;
+ while( p ){
+ int op = p->op;
+ if( op==TK_REGISTER ) op = p->op2;
+ if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)
+ && p->y.pTab!=0
+ ){
+ /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
+ ** a TK_COLUMN but was previously evaluated and cached in a register */
+ int j = p->iColumn;
+ if( j>=0 ){
+ const char *zColl = p->y.pTab->aCol[j].zColl;
+ pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
+ }
+ break;
+ }
+ if( op==TK_CAST || op==TK_UPLUS ){
+ p = p->pLeft;
+ continue;
+ }
+ if( op==TK_VECTOR ){
+ p = p->x.pList->a[0].pExpr;
+ continue;
+ }
+ if( op==TK_COLLATE ){
+ pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
+ break;
+ }
+ if( p->flags & EP_Collate ){
+ if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
+ p = p->pLeft;
+ }else{
+ Expr *pNext = p->pRight;
+ /* The Expr.x union is never used at the same time as Expr.pRight */
+ assert( p->x.pList==0 || p->pRight==0 );
+ if( p->x.pList!=0
+ && !db->mallocFailed
+ && ALWAYS(!ExprHasProperty(p, EP_xIsSelect))
+ ){
+ int i;
+ for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
+ if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
+ pNext = p->x.pList->a[i].pExpr;
+ break;
+ }
+ }
+ }
+ p = pNext;
+ }
+ }else{
+ break;
+ }
+ }
+ if( sqlite3CheckCollSeq(pParse, pColl) ){
+ pColl = 0;
+ }
+ return pColl;
+}
+
+/*
+** Return the collation sequence for the expression pExpr. If
+** there is no defined collating sequence, return a pointer to the
+** defautl collation sequence.
+**
+** See also: sqlite3ExprCollSeq()
+**
+** The sqlite3ExprCollSeq() routine works the same except that it
+** returns NULL if there is no defined collation.
+*/
+SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){
+ CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
+ if( p==0 ) p = pParse->db->pDfltColl;
+ assert( p!=0 );
+ return p;
+}
+
+/*
+** Return TRUE if the two expressions have equivalent collating sequences.
+*/
+SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){
+ CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
+ CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
+ return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
+}
+
+/*
+** pExpr is an operand of a comparison operator. aff2 is the
+** type affinity of the other operand. This routine returns the
+** type affinity that should be used for the comparison operator.
+*/
+SQLITE_PRIVATE char sqlite3CompareAffinity(const Expr *pExpr, char aff2){
+ char aff1 = sqlite3ExprAffinity(pExpr);
+ if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
+ /* Both sides of the comparison are columns. If one has numeric
+ ** affinity, use that. Otherwise use no affinity.
+ */
+ if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
+ return SQLITE_AFF_NUMERIC;
+ }else{
+ return SQLITE_AFF_BLOB;
+ }
+ }else{
+ /* One side is a column, the other is not. Use the columns affinity. */
+ assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
+ return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
+ }
+}
+
+/*
+** pExpr is a comparison operator. Return the type affinity that should
+** be applied to both operands prior to doing the comparison.
+*/
+static char comparisonAffinity(const Expr *pExpr){
+ char aff;
+ assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
+ pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
+ pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
+ assert( pExpr->pLeft );
+ aff = sqlite3ExprAffinity(pExpr->pLeft);
+ if( pExpr->pRight ){
+ aff = sqlite3CompareAffinity(pExpr->pRight, aff);
+ }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+ aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
+ }else if( aff==0 ){
+ aff = SQLITE_AFF_BLOB;
+ }
+ return aff;
+}
+
+/*
+** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
+** idx_affinity is the affinity of an indexed column. Return true
+** if the index with affinity idx_affinity may be used to implement
+** the comparison in pExpr.
+*/
+SQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){
+ char aff = comparisonAffinity(pExpr);
+ if( aff<SQLITE_AFF_TEXT ){
+ return 1;
+ }
+ if( aff==SQLITE_AFF_TEXT ){
+ return idx_affinity==SQLITE_AFF_TEXT;
+ }
+ return sqlite3IsNumericAffinity(idx_affinity);
+}
+
+/*
+** Return the P5 value that should be used for a binary comparison
+** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
+*/
+static u8 binaryCompareP5(
+ const Expr *pExpr1, /* Left operand */
+ const Expr *pExpr2, /* Right operand */
+ int jumpIfNull /* Extra flags added to P5 */
+){
+ u8 aff = (char)sqlite3ExprAffinity(pExpr2);
+ aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
+ return aff;
+}
+
+/*
+** Return a pointer to the collation sequence that should be used by
+** a binary comparison operator comparing pLeft and pRight.
+**
+** If the left hand expression has a collating sequence type, then it is
+** used. Otherwise the collation sequence for the right hand expression
+** is used, or the default (BINARY) if neither expression has a collating
+** type.
+**
+** Argument pRight (but not pLeft) may be a null pointer. In this case,
+** it is not considered.
+*/
+SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
+ Parse *pParse,
+ const Expr *pLeft,
+ const Expr *pRight
+){
+ CollSeq *pColl;
+ assert( pLeft );
+ if( pLeft->flags & EP_Collate ){
+ pColl = sqlite3ExprCollSeq(pParse, pLeft);
+ }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
+ pColl = sqlite3ExprCollSeq(pParse, pRight);
+ }else{
+ pColl = sqlite3ExprCollSeq(pParse, pLeft);
+ if( !pColl ){
+ pColl = sqlite3ExprCollSeq(pParse, pRight);
+ }
+ }
+ return pColl;
+}
+
+/* Expresssion p is a comparison operator. Return a collation sequence
+** appropriate for the comparison operator.
+**
+** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
+** However, if the OP_Commuted flag is set, then the order of the operands
+** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
+** correct collating sequence is found.
+*/
+SQLITE_PRIVATE CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){
+ if( ExprHasProperty(p, EP_Commuted) ){
+ return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
+ }else{
+ return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
+ }
+}
+
+/*
+** Generate code for a comparison operator.
+*/
+static int codeCompare(
+ Parse *pParse, /* The parsing (and code generating) context */
+ Expr *pLeft, /* The left operand */
+ Expr *pRight, /* The right operand */
+ int opcode, /* The comparison opcode */
+ int in1, int in2, /* Register holding operands */
+ int dest, /* Jump here if true. */
+ int jumpIfNull, /* If true, jump if either operand is NULL */
+ int isCommuted /* The comparison has been commuted */
+){
+ int p5;
+ int addr;
+ CollSeq *p4;
+
+ if( pParse->nErr ) return 0;
+ if( isCommuted ){
+ p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
+ }else{
+ p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
+ }
+ p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
+ addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
+ (void*)p4, P4_COLLSEQ);
+ sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
+ return addr;
+}
+
+/*
+** Return true if expression pExpr is a vector, or false otherwise.
+**
+** A vector is defined as any expression that results in two or more
+** columns of result. Every TK_VECTOR node is an vector because the
+** parser will not generate a TK_VECTOR with fewer than two entries.
+** But a TK_SELECT might be either a vector or a scalar. It is only
+** considered a vector if it has two or more result columns.
+*/
+SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
+ return sqlite3ExprVectorSize(pExpr)>1;
+}
+
+/*
+** If the expression passed as the only argument is of type TK_VECTOR
+** return the number of expressions in the vector. Or, if the expression
+** is a sub-select, return the number of columns in the sub-select. For
+** any other type of expression, return 1.
+*/
+SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
+ u8 op = pExpr->op;
+ if( op==TK_REGISTER ) op = pExpr->op2;
+ if( op==TK_VECTOR ){
+ return pExpr->x.pList->nExpr;
+ }else if( op==TK_SELECT ){
+ return pExpr->x.pSelect->pEList->nExpr;
+ }else{
+ return 1;
+ }
+}
+
+/*
+** Return a pointer to a subexpression of pVector that is the i-th
+** column of the vector (numbered starting with 0). The caller must
+** ensure that i is within range.
+**
+** If pVector is really a scalar (and "scalar" here includes subqueries
+** that return a single column!) then return pVector unmodified.
+**
+** pVector retains ownership of the returned subexpression.
+**
+** If the vector is a (SELECT ...) then the expression returned is
+** just the expression for the i-th term of the result set, and may
+** not be ready for evaluation because the table cursor has not yet
+** been positioned.
+*/
+SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
+ assert( i<sqlite3ExprVectorSize(pVector) );
+ if( sqlite3ExprIsVector(pVector) ){
+ assert( pVector->op2==0 || pVector->op==TK_REGISTER );
+ if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
+ return pVector->x.pSelect->pEList->a[i].pExpr;
+ }else{
+ return pVector->x.pList->a[i].pExpr;
+ }
+ }
+ return pVector;
+}
+
+/*
+** Compute and return a new Expr object which when passed to
+** sqlite3ExprCode() will generate all necessary code to compute
+** the iField-th column of the vector expression pVector.
+**
+** It is ok for pVector to be a scalar (as long as iField==0).
+** In that case, this routine works like sqlite3ExprDup().
+**
+** The caller owns the returned Expr object and is responsible for
+** ensuring that the returned value eventually gets freed.
+**
+** The caller retains ownership of pVector. If pVector is a TK_SELECT,
+** then the returned object will reference pVector and so pVector must remain
+** valid for the life of the returned object. If pVector is a TK_VECTOR
+** or a scalar expression, then it can be deleted as soon as this routine
+** returns.
+**
+** A trick to cause a TK_SELECT pVector to be deleted together with
+** the returned Expr object is to attach the pVector to the pRight field
+** of the returned TK_SELECT_COLUMN Expr object.
+*/
+SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
+ Parse *pParse, /* Parsing context */
+ Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
+ int iField /* Which column of the vector to return */
+){
+ Expr *pRet;
+ if( pVector->op==TK_SELECT ){
+ assert( pVector->flags & EP_xIsSelect );
+ /* The TK_SELECT_COLUMN Expr node:
+ **
+ ** pLeft: pVector containing TK_SELECT. Not deleted.
+ ** pRight: not used. But recursively deleted.
+ ** iColumn: Index of a column in pVector
+ ** iTable: 0 or the number of columns on the LHS of an assignment
+ ** pLeft->iTable: First in an array of register holding result, or 0
+ ** if the result is not yet computed.
+ **
+ ** sqlite3ExprDelete() specifically skips the recursive delete of
+ ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
+ ** can be attached to pRight to cause this node to take ownership of
+ ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
+ ** with the same pLeft pointer to the pVector, but only one of them
+ ** will own the pVector.
+ */
+ pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
+ if( pRet ){
+ pRet->iColumn = iField;
+ pRet->pLeft = pVector;
+ }
+ assert( pRet==0 || pRet->iTable==0 );
+ }else{
+ if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
+ pRet = sqlite3ExprDup(pParse->db, pVector, 0);
+ sqlite3RenameTokenRemap(pParse, pRet, pVector);
+ }
+ return pRet;
+}
+
+/*
+** If expression pExpr is of type TK_SELECT, generate code to evaluate
+** it. Return the register in which the result is stored (or, if the
+** sub-select returns more than one column, the first in an array
+** of registers in which the result is stored).
+**
+** If pExpr is not a TK_SELECT expression, return 0.
+*/
+static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
+ int reg = 0;
+#ifndef SQLITE_OMIT_SUBQUERY
+ if( pExpr->op==TK_SELECT ){
+ reg = sqlite3CodeSubselect(pParse, pExpr);
+ }
+#endif
+ return reg;
+}
+
+/*
+** Argument pVector points to a vector expression - either a TK_VECTOR
+** or TK_SELECT that returns more than one column. This function returns
+** the register number of a register that contains the value of
+** element iField of the vector.
+**
+** If pVector is a TK_SELECT expression, then code for it must have
+** already been generated using the exprCodeSubselect() routine. In this
+** case parameter regSelect should be the first in an array of registers
+** containing the results of the sub-select.
+**
+** If pVector is of type TK_VECTOR, then code for the requested field
+** is generated. In this case (*pRegFree) may be set to the number of
+** a temporary register to be freed by the caller before returning.
+**
+** Before returning, output parameter (*ppExpr) is set to point to the
+** Expr object corresponding to element iElem of the vector.
+*/
+static int exprVectorRegister(
+ Parse *pParse, /* Parse context */
+ Expr *pVector, /* Vector to extract element from */
+ int iField, /* Field to extract from pVector */
+ int regSelect, /* First in array of registers */
+ Expr **ppExpr, /* OUT: Expression element */
+ int *pRegFree /* OUT: Temp register to free */
+){
+ u8 op = pVector->op;
+ assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
+ if( op==TK_REGISTER ){
+ *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
+ return pVector->iTable+iField;
+ }
+ if( op==TK_SELECT ){
+ *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
+ return regSelect+iField;
+ }
+ *ppExpr = pVector->x.pList->a[iField].pExpr;
+ return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
+}
+
+/*
+** Expression pExpr is a comparison between two vector values. Compute
+** the result of the comparison (1, 0, or NULL) and write that
+** result into register dest.
+**
+** The caller must satisfy the following preconditions:
+**
+** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
+** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
+** otherwise: op==pExpr->op and p5==0
+*/
+static void codeVectorCompare(
+ Parse *pParse, /* Code generator context */
+ Expr *pExpr, /* The comparison operation */
+ int dest, /* Write results into this register */
+ u8 op, /* Comparison operator */
+ u8 p5 /* SQLITE_NULLEQ or zero */
+){
+ Vdbe *v = pParse->pVdbe;
+ Expr *pLeft = pExpr->pLeft;
+ Expr *pRight = pExpr->pRight;
+ int nLeft = sqlite3ExprVectorSize(pLeft);
+ int i;
+ int regLeft = 0;
+ int regRight = 0;
+ u8 opx = op;
+ int addrDone = sqlite3VdbeMakeLabel(pParse);
+ int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
+
+ assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
+ if( pParse->nErr ) return;
+ if( nLeft!=sqlite3ExprVectorSize(pRight) ){
+ sqlite3ErrorMsg(pParse, "row value misused");
+ return;
+ }
+ assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
+ || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
+ || pExpr->op==TK_LT || pExpr->op==TK_GT
+ || pExpr->op==TK_LE || pExpr->op==TK_GE
+ );
+ assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
+ || (pExpr->op==TK_ISNOT && op==TK_NE) );
+ assert( p5==0 || pExpr->op!=op );
+ assert( p5==SQLITE_NULLEQ || pExpr->op==op );
+
+ p5 |= SQLITE_STOREP2;
+ if( opx==TK_LE ) opx = TK_LT;
+ if( opx==TK_GE ) opx = TK_GT;
+
+ regLeft = exprCodeSubselect(pParse, pLeft);
+ regRight = exprCodeSubselect(pParse, pRight);
+
+ for(i=0; 1 /*Loop exits by "break"*/; i++){
+ int regFree1 = 0, regFree2 = 0;
+ Expr *pL, *pR;
+ int r1, r2;
+ assert( i>=0 && i<nLeft );
+ r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
+ r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
+ codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5, isCommuted);
+ testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
+ testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
+ testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
+ testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
+ testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
+ testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
+ sqlite3ReleaseTempReg(pParse, regFree1);
+ sqlite3ReleaseTempReg(pParse, regFree2);
+ if( i==nLeft-1 ){
+ break;
+ }
+ if( opx==TK_EQ ){
+ sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
+ p5 |= SQLITE_KEEPNULL;
+ }else if( opx==TK_NE ){
+ sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
+ p5 |= SQLITE_KEEPNULL;
+ }else{
+ assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
+ sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
+ VdbeCoverageIf(v, op==TK_LT);
+ VdbeCoverageIf(v, op==TK_GT);
+ VdbeCoverageIf(v, op==TK_LE);
+ VdbeCoverageIf(v, op==TK_GE);
+ if( i==nLeft-2 ) opx = op;
+ }
+ }
+ sqlite3VdbeResolveLabel(v, addrDone);
+}
+
+#if SQLITE_MAX_EXPR_DEPTH>0
+/*
+** Check that argument nHeight is less than or equal to the maximum
+** expression depth allowed. If it is not, leave an error message in
+** pParse.
+*/
+SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
+ int rc = SQLITE_OK;
+ int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
+ if( nHeight>mxHeight ){
+ sqlite3ErrorMsg(pParse,
+ "Expression tree is too large (maximum depth %d)", mxHeight
+ );
+ rc = SQLITE_ERROR;
+ }
+ return rc;
+}
+
+/* The following three functions, heightOfExpr(), heightOfExprList()
+** and heightOfSelect(), are used to determine the maximum height
+** of any expression tree referenced by the structure passed as the
+** first argument.
+**
+** If this maximum height is greater than the current value pointed
+** to by pnHeight, the second parameter, then set *pnHeight to that
+** value.
+*/
+static void heightOfExpr(Expr *p, int *pnHeight){
+ if( p ){
+ if( p->nHeight>*pnHeight ){
+ *pnHeight = p->nHeight;
+ }
+ }
+}
+static void heightOfExprList(ExprList *p, int *pnHeight){
+ if( p ){
+ int i;
+ for(i=0; i<p->nExpr; i++){
+ heightOfExpr(p->a[i].pExpr, pnHeight);
+ }
+ }
+}
+static void heightOfSelect(Select *pSelect, int *pnHeight){
+ Select *p;
+ for(p=pSelect; p; p=p->pPrior){
+ heightOfExpr(p->pWhere, pnHeight);
+ heightOfExpr(p->pHaving, pnHeight);
+ heightOfExpr(p->pLimit, pnHeight);
+ heightOfExprList(p->pEList, pnHeight);
+ heightOfExprList(p->pGroupBy, pnHeight);
+ heightOfExprList(p->pOrderBy, pnHeight);
+ }
+}
+
+/*
+** Set the Expr.nHeight variable in the structure passed as an
+** argument. An expression with no children, Expr.pList or
+** Expr.pSelect member has a height of 1. Any other expression
+** has a height equal to the maximum height of any other
+** referenced Expr plus one.
+**
+** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
+** if appropriate.
+*/
+static void exprSetHeight(Expr *p){
+ int nHeight = 0;
+ heightOfExpr(p->pLeft, &nHeight);
+ heightOfExpr(p->pRight, &nHeight);
+ if( ExprHasProperty(p, EP_xIsSelect) ){
+ heightOfSelect(p->x.pSelect, &nHeight);
+ }else if( p->x.pList ){
+ heightOfExprList(p->x.pList, &nHeight);
+ p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
+ }
+ p->nHeight = nHeight + 1;
+}
+
+/*
+** Set the Expr.nHeight variable using the exprSetHeight() function. If
+** the height is greater than the maximum allowed expression depth,
+** leave an error in pParse.
+**
+** Also propagate all EP_Propagate flags from the Expr.x.pList into
+** Expr.flags.
+*/
+SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
+ if( pParse->nErr ) return;
+ exprSetHeight(p);
+ sqlite3ExprCheckHeight(pParse, p->nHeight);
+}
+
+/*
+** Return the maximum height of any expression tree referenced
+** by the select statement passed as an argument.
+*/
+SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
+ int nHeight = 0;
+ heightOfSelect(p, &nHeight);
+ return nHeight;
+}
+#else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
+/*
+** Propagate all EP_Propagate flags from the Expr.x.pList into
+** Expr.flags.
+*/
+SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
+ if( pParse->nErr ) return;
+ if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
+ p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
+ }
+}
+#define exprSetHeight(y)
+#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
+
+/*
+** This routine is the core allocator for Expr nodes.
+**
+** Construct a new expression node and return a pointer to it. Memory
+** for this node and for the pToken argument is a single allocation
+** obtained from sqlite3DbMalloc(). The calling function
+** is responsible for making sure the node eventually gets freed.
+**
+** If dequote is true, then the token (if it exists) is dequoted.
+** If dequote is false, no dequoting is performed. The deQuote
+** parameter is ignored if pToken is NULL or if the token does not
+** appear to be quoted. If the quotes were of the form "..." (double-quotes)
+** then the EP_DblQuoted flag is set on the expression node.
+**
+** Special case: If op==TK_INTEGER and pToken points to a string that
+** can be translated into a 32-bit integer, then the token is not
+** stored in u.zToken. Instead, the integer values is written
+** into u.iValue and the EP_IntValue flag is set. No extra storage
+** is allocated to hold the integer text and the dequote flag is ignored.
+*/
+SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
+ sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
+ int op, /* Expression opcode */
+ const Token *pToken, /* Token argument. Might be NULL */
+ int dequote /* True to dequote */
+){
+ Expr *pNew;
+ int nExtra = 0;
+ int iValue = 0;
+
+ assert( db!=0 );
+ if( pToken ){
+ if( op!=TK_INTEGER || pToken->z==0
+ || sqlite3GetInt32(pToken->z, &iValue)==0 ){
+ nExtra = pToken->n+1;
+ assert( iValue>=0 );
+ }
+ }
+ pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
+ if( pNew ){
+ memset(pNew, 0, sizeof(Expr));
+ pNew->op = (u8)op;
+ pNew->iAgg = -1;
+ if( pToken ){
+ if( nExtra==0 ){
+ pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
+ pNew->u.iValue = iValue;
+ }else{
+ pNew->u.zToken = (char*)&pNew[1];
+ assert( pToken->z!=0 || pToken->n==0 );
+ if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
+ pNew->u.zToken[pToken->n] = 0;
+ if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
+ sqlite3DequoteExpr(pNew);
+ }
+ }
+ }
+#if SQLITE_MAX_EXPR_DEPTH>0
+ pNew->nHeight = 1;
+#endif
+ }
+ return pNew;
+}
+
+/*
+** Allocate a new expression node from a zero-terminated token that has
+** already been dequoted.
+*/
+SQLITE_PRIVATE Expr *sqlite3Expr(
+ sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
+ int op, /* Expression opcode */
+ const char *zToken /* Token argument. Might be NULL */
+){
+ Token x;
+ x.z = zToken;
+ x.n = sqlite3Strlen30(zToken);
+ return sqlite3ExprAlloc(db, op, &x, 0);
+}
+
+/*
+** Attach subtrees pLeft and pRight to the Expr node pRoot.
+**
+** If pRoot==NULL that means that a memory allocation error has occurred.
+** In that case, delete the subtrees pLeft and pRight.
+*/
+SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
+ sqlite3 *db,
+ Expr *pRoot,
+ Expr *pLeft,
+ Expr *pRight
+){
+ if( pRoot==0 ){
+ assert( db->mallocFailed );
+ sqlite3ExprDelete(db, pLeft);
+ sqlite3ExprDelete(db, pRight);
+ }else{
+ if( pRight ){
+ pRoot->pRight = pRight;
+ pRoot->flags |= EP_Propagate & pRight->flags;
+ }
+ if( pLeft ){
+ pRoot->pLeft = pLeft;
+ pRoot->flags |= EP_Propagate & pLeft->flags;
+ }
+ exprSetHeight(pRoot);
+ }
+}
+
+/*
+** Allocate an Expr node which joins as many as two subtrees.
+**
+** One or both of the subtrees can be NULL. Return a pointer to the new
+** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
+** free the subtrees and return NULL.
+*/
+SQLITE_PRIVATE Expr *sqlite3PExpr(
+ Parse *pParse, /* Parsing context */
+ int op, /* Expression opcode */
+ Expr *pLeft, /* Left operand */
+ Expr *pRight /* Right operand */
+){
+ Expr *p;
+ p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
+ if( p ){
+ memset(p, 0, sizeof(Expr));
+ p->op = op & 0xff;
+ p->iAgg = -1;
+ sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
+ sqlite3ExprCheckHeight(pParse, p->nHeight);
+ }else{
+ sqlite3ExprDelete(pParse->db, pLeft);
+ sqlite3ExprDelete(pParse->db, pRight);
+ }
+ return p;
+}
+
+/*
+** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
+** do a memory allocation failure) then delete the pSelect object.
+*/
+SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
+ if( pExpr ){
+ pExpr->x.pSelect = pSelect;
+ ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
+ sqlite3ExprSetHeightAndFlags(pParse, pExpr);
+ }else{
+ assert( pParse->db->mallocFailed );
+ sqlite3SelectDelete(pParse->db, pSelect);
+ }
+}
+
+
+/*
+** Join two expressions using an AND operator. If either expression is
+** NULL, then just return the other expression.
+**
+** If one side or the other of the AND is known to be false, then instead
+** of returning an AND expression, just return a constant expression with
+** a value of false.
+*/
+SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
+ sqlite3 *db = pParse->db;
+ if( pLeft==0 ){
+ return pRight;
+ }else if( pRight==0 ){
+ return pLeft;
+ }else if( (ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight))
+ && !IN_RENAME_OBJECT
+ ){
+ sqlite3ExprDelete(db, pLeft);
+ sqlite3ExprDelete(db, pRight);
+ return sqlite3Expr(db, TK_INTEGER, "0");
+ }else{
+ return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
+ }
+}
+
+/*
+** Construct a new expression node for a function with multiple
+** arguments.
+*/
+SQLITE_PRIVATE Expr *sqlite3ExprFunction(
+ Parse *pParse, /* Parsing context */
+ ExprList *pList, /* Argument list */
+ Token *pToken, /* Name of the function */
+ int eDistinct /* SF_Distinct or SF_ALL or 0 */
+){
+ Expr *pNew;
+ sqlite3 *db = pParse->db;
+ assert( pToken );
+ pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
+ if( pNew==0 ){
+ sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
+ return 0;
+ }
+ if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
+ sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
+ }
+ pNew->x.pList = pList;
+ ExprSetProperty(pNew, EP_HasFunc);
+ assert( !ExprHasProperty(pNew, EP_xIsSelect) );
+ sqlite3ExprSetHeightAndFlags(pParse, pNew);
+ if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
+ return pNew;
+}
+
+/*
+** Check to see if a function is usable according to current access
+** rules:
+**
+** SQLITE_FUNC_DIRECT - Only usable from top-level SQL
+**
+** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from
+** top-level SQL
+**
+** If the function is not usable, create an error.
+*/
+SQLITE_PRIVATE void sqlite3ExprFunctionUsable(
+ Parse *pParse, /* Parsing and code generating context */
+ Expr *pExpr, /* The function invocation */
+ FuncDef *pDef /* The function being invoked */
+){
+ assert( !IN_RENAME_OBJECT );
+ assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
+ if( ExprHasProperty(pExpr, EP_FromDDL) ){
+ if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
+ || (pParse->db->flags & SQLITE_TrustedSchema)==0
+ ){
+ /* Functions prohibited in triggers and views if:
+ ** (1) tagged with SQLITE_DIRECTONLY
+ ** (2) not tagged with SQLITE_INNOCUOUS (which means it
+ ** is tagged with SQLITE_FUNC_UNSAFE) and
+ ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
+ ** that the schema is possibly tainted).
+ */
+ sqlite3ErrorMsg(pParse, "unsafe use of %s()", pDef->zName);
+ }
+ }
+}
+
+/*
+** Assign a variable number to an expression that encodes a wildcard
+** in the original SQL statement.
+**
+** Wildcards consisting of a single "?" are assigned the next sequential
+** variable number.
+**
+** Wildcards of the form "?nnn" are assigned the number "nnn". We make
+** sure "nnn" is not too big to avoid a denial of service attack when
+** the SQL statement comes from an external source.
+**
+** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
+** as the previous instance of the same wildcard. Or if this is the first
+** instance of the wildcard, the next sequential variable number is
+** assigned.
+*/
+SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
+ sqlite3 *db = pParse->db;
+ const char *z;
+ ynVar x;
+
+ if( pExpr==0 ) return;
+ assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
+ z = pExpr->u.zToken;
+ assert( z!=0 );
+ assert( z[0]!=0 );
+ assert( n==(u32)sqlite3Strlen30(z) );
+ if( z[1]==0 ){
+ /* Wildcard of the form "?". Assign the next variable number */
+ assert( z[0]=='?' );
+ x = (ynVar)(++pParse->nVar);
+ }else{
+ int doAdd = 0;
+ if( z[0]=='?' ){
+ /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
+ ** use it as the variable number */
+ i64 i;
+ int bOk;
+ if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
+ i = z[1]-'0'; /* The common case of ?N for a single digit N */
+ bOk = 1;
+ }else{
+ bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
+ }
+ testcase( i==0 );
+ testcase( i==1 );
+ testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
+ testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
+ if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
+ sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
+ db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
+ return;
+ }
+ x = (ynVar)i;
+ if( x>pParse->nVar ){
+ pParse->nVar = (int)x;
+ doAdd = 1;
+ }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
+ doAdd = 1;
+ }
+ }else{
+ /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
+ ** number as the prior appearance of the same name, or if the name
+ ** has never appeared before, reuse the same variable number
+ */
+ x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
+ if( x==0 ){
+ x = (ynVar)(++pParse->nVar);
+ doAdd = 1;
+ }
+ }
+ if( doAdd ){
+ pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
+ }
+ }
+ pExpr->iColumn = x;
+ if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
+ sqlite3ErrorMsg(pParse, "too many SQL variables");
+ }
+}
+
+/*
+** Recursively delete an expression tree.
+*/
+static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
+ assert( p!=0 );
+ /* Sanity check: Assert that the IntValue is non-negative if it exists */
+ assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
+
+ assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
+ assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
+ || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
+#ifdef SQLITE_DEBUG
+ if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
+ assert( p->pLeft==0 );
+ assert( p->pRight==0 );
+ assert( p->x.pSelect==0 );
+ }
+#endif
+ if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
+ /* The Expr.x union is never used at the same time as Expr.pRight */
+ assert( p->x.pList==0 || p->pRight==0 );
+ if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
+ if( p->pRight ){
+ assert( !ExprHasProperty(p, EP_WinFunc) );
+ sqlite3ExprDeleteNN(db, p->pRight);
+ }else if( ExprHasProperty(p, EP_xIsSelect) ){
+ assert( !ExprHasProperty(p, EP_WinFunc) );
+ sqlite3SelectDelete(db, p->x.pSelect);
+ }else{
+ sqlite3ExprListDelete(db, p->x.pList);
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( ExprHasProperty(p, EP_WinFunc) ){
+ sqlite3WindowDelete(db, p->y.pWin);
+ }
+#endif
+ }
+ }
+ if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
+ if( !ExprHasProperty(p, EP_Static) ){
+ sqlite3DbFreeNN(db, p);
+ }
+}
+SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
+ if( p ) sqlite3ExprDeleteNN(db, p);
+}
+
+/* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
+** expression.
+*/
+SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
+ if( p ){
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameExprUnmap(pParse, p);
+ }
+ sqlite3ExprDeleteNN(pParse->db, p);
+ }
+}
+
+/*
+** Return the number of bytes allocated for the expression structure
+** passed as the first argument. This is always one of EXPR_FULLSIZE,
+** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
+*/
+static int exprStructSize(Expr *p){
+ if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
+ if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
+ return EXPR_FULLSIZE;
+}
+
+/*
+** The dupedExpr*Size() routines each return the number of bytes required
+** to store a copy of an expression or expression tree. They differ in
+** how much of the tree is measured.
+**
+** dupedExprStructSize() Size of only the Expr structure
+** dupedExprNodeSize() Size of Expr + space for token
+** dupedExprSize() Expr + token + subtree components
+**
+***************************************************************************
+**
+** The dupedExprStructSize() function returns two values OR-ed together:
+** (1) the space required for a copy of the Expr structure only and
+** (2) the EP_xxx flags that indicate what the structure size should be.
+** The return values is always one of:
+**
+** EXPR_FULLSIZE
+** EXPR_REDUCEDSIZE | EP_Reduced
+** EXPR_TOKENONLYSIZE | EP_TokenOnly
+**
+** The size of the structure can be found by masking the return value
+** of this routine with 0xfff. The flags can be found by masking the
+** return value with EP_Reduced|EP_TokenOnly.
+**
+** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
+** (unreduced) Expr objects as they or originally constructed by the parser.
+** During expression analysis, extra information is computed and moved into
+** later parts of the Expr object and that extra information might get chopped
+** off if the expression is reduced. Note also that it does not work to
+** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
+** to reduce a pristine expression tree from the parser. The implementation
+** of dupedExprStructSize() contain multiple assert() statements that attempt
+** to enforce this constraint.
+*/
+static int dupedExprStructSize(Expr *p, int flags){
+ int nSize;
+ assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
+ assert( EXPR_FULLSIZE<=0xfff );
+ assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
+ if( 0==flags || p->op==TK_SELECT_COLUMN
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ || ExprHasProperty(p, EP_WinFunc)
+#endif
+ ){
+ nSize = EXPR_FULLSIZE;
+ }else{
+ assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
+ assert( !ExprHasProperty(p, EP_FromJoin) );
+ assert( !ExprHasProperty(p, EP_MemToken) );
+ assert( !ExprHasVVAProperty(p, EP_NoReduce) );
+ if( p->pLeft || p->x.pList ){
+ nSize = EXPR_REDUCEDSIZE | EP_Reduced;
+ }else{
+ assert( p->pRight==0 );
+ nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
+ }
+ }
+ return nSize;
+}
+
+/*
+** This function returns the space in bytes required to store the copy
+** of the Expr structure and a copy of the Expr.u.zToken string (if that
+** string is defined.)
+*/
+static int dupedExprNodeSize(Expr *p, int flags){
+ int nByte = dupedExprStructSize(p, flags) & 0xfff;
+ if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
+ nByte += sqlite3Strlen30NN(p->u.zToken)+1;
+ }
+ return ROUND8(nByte);
+}
+
+/*
+** Return the number of bytes required to create a duplicate of the
+** expression passed as the first argument. The second argument is a
+** mask containing EXPRDUP_XXX flags.
+**
+** The value returned includes space to create a copy of the Expr struct
+** itself and the buffer referred to by Expr.u.zToken, if any.
+**
+** If the EXPRDUP_REDUCE flag is set, then the return value includes
+** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
+** and Expr.pRight variables (but not for any structures pointed to or
+** descended from the Expr.x.pList or Expr.x.pSelect variables).
+*/
+static int dupedExprSize(Expr *p, int flags){
+ int nByte = 0;
+ if( p ){
+ nByte = dupedExprNodeSize(p, flags);
+ if( flags&EXPRDUP_REDUCE ){
+ nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
+ }
+ }
+ return nByte;
+}
+
+/*
+** This function is similar to sqlite3ExprDup(), except that if pzBuffer
+** is not NULL then *pzBuffer is assumed to point to a buffer large enough
+** to store the copy of expression p, the copies of p->u.zToken
+** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
+** if any. Before returning, *pzBuffer is set to the first byte past the
+** portion of the buffer copied into by this function.
+*/
+static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
+ Expr *pNew; /* Value to return */
+ u8 *zAlloc; /* Memory space from which to build Expr object */
+ u32 staticFlag; /* EP_Static if space not obtained from malloc */
+
+ assert( db!=0 );
+ assert( p );
+ assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
+ assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
+
+ /* Figure out where to write the new Expr structure. */
+ if( pzBuffer ){
+ zAlloc = *pzBuffer;
+ staticFlag = EP_Static;
+ }else{
+ zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
+ staticFlag = 0;
+ }
+ pNew = (Expr *)zAlloc;
+
+ if( pNew ){
+ /* Set nNewSize to the size allocated for the structure pointed to
+ ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
+ ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
+ ** by the copy of the p->u.zToken string (if any).
+ */
+ const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
+ const int nNewSize = nStructSize & 0xfff;
+ int nToken;
+ if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
+ nToken = sqlite3Strlen30(p->u.zToken) + 1;
+ }else{
+ nToken = 0;
+ }
+ if( dupFlags ){
+ assert( ExprHasProperty(p, EP_Reduced)==0 );
+ memcpy(zAlloc, p, nNewSize);
+ }else{
+ u32 nSize = (u32)exprStructSize(p);
+ memcpy(zAlloc, p, nSize);
+ if( nSize<EXPR_FULLSIZE ){
+ memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
+ }
+ }
+
+ /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
+ pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
+ pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
+ pNew->flags |= staticFlag;
+ ExprClearVVAProperties(pNew);
+ if( dupFlags ){
+ ExprSetVVAProperty(pNew, EP_Immutable);
+ }
+
+ /* Copy the p->u.zToken string, if any. */
+ if( nToken ){
+ char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
+ memcpy(zToken, p->u.zToken, nToken);
+ }
+
+ if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
+ /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
+ if( ExprHasProperty(p, EP_xIsSelect) ){
+ pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
+ }else{
+ pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
+ }
+ }
+
+ /* Fill in pNew->pLeft and pNew->pRight. */
+ if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
+ zAlloc += dupedExprNodeSize(p, dupFlags);
+ if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
+ pNew->pLeft = p->pLeft ?
+ exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
+ pNew->pRight = p->pRight ?
+ exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
+ }
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( ExprHasProperty(p, EP_WinFunc) ){
+ pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
+ assert( ExprHasProperty(pNew, EP_WinFunc) );
+ }
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+ if( pzBuffer ){
+ *pzBuffer = zAlloc;
+ }
+ }else{
+ if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
+ if( pNew->op==TK_SELECT_COLUMN ){
+ pNew->pLeft = p->pLeft;
+ assert( p->iColumn==0 || p->pRight==0 );
+ assert( p->pRight==0 || p->pRight==p->pLeft );
+ }else{
+ pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
+ }
+ pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
+ }
+ }
+ }
+ return pNew;
+}
+
+/*
+** Create and return a deep copy of the object passed as the second
+** argument. If an OOM condition is encountered, NULL is returned
+** and the db->mallocFailed flag set.
+*/
+#ifndef SQLITE_OMIT_CTE
+static With *withDup(sqlite3 *db, With *p){
+ With *pRet = 0;
+ if( p ){
+ sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
+ pRet = sqlite3DbMallocZero(db, nByte);
+ if( pRet ){
+ int i;
+ pRet->nCte = p->nCte;
+ for(i=0; i<p->nCte; i++){
+ pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
+ pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
+ pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
+ }
+ }
+ }
+ return pRet;
+}
+#else
+# define withDup(x,y) 0
+#endif
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+/*
+** The gatherSelectWindows() procedure and its helper routine
+** gatherSelectWindowsCallback() are used to scan all the expressions
+** an a newly duplicated SELECT statement and gather all of the Window
+** objects found there, assembling them onto the linked list at Select->pWin.
+*/
+static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
+ if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
+ Select *pSelect = pWalker->u.pSelect;
+ Window *pWin = pExpr->y.pWin;
+ assert( pWin );
+ assert( IsWindowFunc(pExpr) );
+ assert( pWin->ppThis==0 );
+ sqlite3WindowLink(pSelect, pWin);
+ }
+ return WRC_Continue;
+}
+static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
+ return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
+}
+static void gatherSelectWindows(Select *p){
+ Walker w;
+ w.xExprCallback = gatherSelectWindowsCallback;
+ w.xSelectCallback = gatherSelectWindowsSelectCallback;
+ w.xSelectCallback2 = 0;
+ w.pParse = 0;
+ w.u.pSelect = p;
+ sqlite3WalkSelect(&w, p);
+}
+#endif
+
+
+/*
+** The following group of routines make deep copies of expressions,
+** expression lists, ID lists, and select statements. The copies can
+** be deleted (by being passed to their respective ...Delete() routines)
+** without effecting the originals.
+**
+** The expression list, ID, and source lists return by sqlite3ExprListDup(),
+** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
+** by subsequent calls to sqlite*ListAppend() routines.
+**
+** Any tables that the SrcList might point to are not duplicated.
+**
+** The flags parameter contains a combination of the EXPRDUP_XXX flags.
+** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
+** truncated version of the usual Expr structure that will be stored as
+** part of the in-memory representation of the database schema.
+*/
+SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
+ assert( flags==0 || flags==EXPRDUP_REDUCE );
+ return p ? exprDup(db, p, flags, 0) : 0;
+}
+SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
+ ExprList *pNew;
+ struct ExprList_item *pItem, *pOldItem;
+ int i;
+ Expr *pPriorSelectCol = 0;
+ assert( db!=0 );
+ if( p==0 ) return 0;
+ pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
+ if( pNew==0 ) return 0;
+ pNew->nExpr = p->nExpr;
+ pItem = pNew->a;
+ pOldItem = p->a;
+ for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
+ Expr *pOldExpr = pOldItem->pExpr;
+ Expr *pNewExpr;
+ pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
+ if( pOldExpr
+ && pOldExpr->op==TK_SELECT_COLUMN
+ && (pNewExpr = pItem->pExpr)!=0
+ ){
+ assert( pNewExpr->iColumn==0 || i>0 );
+ if( pNewExpr->iColumn==0 ){
+ assert( pOldExpr->pLeft==pOldExpr->pRight );
+ pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
+ }else{
+ assert( i>0 );
+ assert( pItem[-1].pExpr!=0 );
+ assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
+ assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
+ pNewExpr->pLeft = pPriorSelectCol;
+ }
+ }
+ pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
+ pItem->sortFlags = pOldItem->sortFlags;
+ pItem->eEName = pOldItem->eEName;
+ pItem->done = 0;
+ pItem->bNulls = pOldItem->bNulls;
+ pItem->bSorterRef = pOldItem->bSorterRef;
+ pItem->u = pOldItem->u;
+ }
+ return pNew;
+}
+
+/*
+** If cursors, triggers, views and subqueries are all omitted from
+** the build, then none of the following routines, except for
+** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
+** called with a NULL argument.
+*/
+#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
+ || !defined(SQLITE_OMIT_SUBQUERY)
+SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
+ SrcList *pNew;
+ int i;
+ int nByte;
+ assert( db!=0 );
+ if( p==0 ) return 0;
+ nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
+ pNew = sqlite3DbMallocRawNN(db, nByte );
+ if( pNew==0 ) return 0;
+ pNew->nSrc = pNew->nAlloc = p->nSrc;
+ for(i=0; i<p->nSrc; i++){
+ struct SrcList_item *pNewItem = &pNew->a[i];
+ struct SrcList_item *pOldItem = &p->a[i];
+ Table *pTab;
+ pNewItem->pSchema = pOldItem->pSchema;
+ pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
+ pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
+ pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
+ pNewItem->fg = pOldItem->fg;
+ pNewItem->iCursor = pOldItem->iCursor;
+ pNewItem->addrFillSub = pOldItem->addrFillSub;
+ pNewItem->regReturn = pOldItem->regReturn;
+ if( pNewItem->fg.isIndexedBy ){
+ pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
+ }
+ pNewItem->pIBIndex = pOldItem->pIBIndex;
+ if( pNewItem->fg.isTabFunc ){
+ pNewItem->u1.pFuncArg =
+ sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
+ }
+ pTab = pNewItem->pTab = pOldItem->pTab;
+ if( pTab ){
+ pTab->nTabRef++;
+ }
+ pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
+ pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
+ pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
+ pNewItem->colUsed = pOldItem->colUsed;
+ }
+ return pNew;
+}
+SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
+ IdList *pNew;
+ int i;
+ assert( db!=0 );
+ if( p==0 ) return 0;
+ pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
+ if( pNew==0 ) return 0;
+ pNew->nId = p->nId;
+ pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
+ if( pNew->a==0 ){
+ sqlite3DbFreeNN(db, pNew);
+ return 0;
+ }
+ /* Note that because the size of the allocation for p->a[] is not
+ ** necessarily a power of two, sqlite3IdListAppend() may not be called
+ ** on the duplicate created by this function. */
+ for(i=0; i<p->nId; i++){
+ struct IdList_item *pNewItem = &pNew->a[i];
+ struct IdList_item *pOldItem = &p->a[i];
+ pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
+ pNewItem->idx = pOldItem->idx;
+ }
+ return pNew;
+}
+SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
+ Select *pRet = 0;
+ Select *pNext = 0;
+ Select **pp = &pRet;
+ Select *p;
+
+ assert( db!=0 );
+ for(p=pDup; p; p=p->pPrior){
+ Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
+ if( pNew==0 ) break;
+ pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
+ pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
+ pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
+ pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
+ pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
+ pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
+ pNew->op = p->op;
+ pNew->pNext = pNext;
+ pNew->pPrior = 0;
+ pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
+ pNew->iLimit = 0;
+ pNew->iOffset = 0;
+ pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
+ pNew->addrOpenEphm[0] = -1;
+ pNew->addrOpenEphm[1] = -1;
+ pNew->nSelectRow = p->nSelectRow;
+ pNew->pWith = withDup(db, p->pWith);
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ pNew->pWin = 0;
+ pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
+ if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
+#endif
+ pNew->selId = p->selId;
+ *pp = pNew;
+ pp = &pNew->pPrior;
+ pNext = pNew;
+ }
+
+ return pRet;
+}
+#else
+SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
+ assert( p==0 );
+ return 0;
+}
+#endif
+
+
+/*
+** Add a new element to the end of an expression list. If pList is
+** initially NULL, then create a new expression list.
+**
+** The pList argument must be either NULL or a pointer to an ExprList
+** obtained from a prior call to sqlite3ExprListAppend(). This routine
+** may not be used with an ExprList obtained from sqlite3ExprListDup().
+** Reason: This routine assumes that the number of slots in pList->a[]
+** is a power of two. That is true for sqlite3ExprListAppend() returns
+** but is not necessarily true from the return value of sqlite3ExprListDup().
+**
+** If a memory allocation error occurs, the entire list is freed and
+** NULL is returned. If non-NULL is returned, then it is guaranteed
+** that the new entry was successfully appended.
+*/
+SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
+ Parse *pParse, /* Parsing context */
+ ExprList *pList, /* List to which to append. Might be NULL */
+ Expr *pExpr /* Expression to be appended. Might be NULL */
+){
+ struct ExprList_item *pItem;
+ sqlite3 *db = pParse->db;
+ assert( db!=0 );
+ if( pList==0 ){
+ pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
+ if( pList==0 ){
+ goto no_mem;
+ }
+ pList->nExpr = 0;
+ }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
+ ExprList *pNew;
+ pNew = sqlite3DbRealloc(db, pList,
+ sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0]));
+ if( pNew==0 ){
+ goto no_mem;
+ }
+ pList = pNew;
+ }
+ pItem = &pList->a[pList->nExpr++];
+ assert( offsetof(struct ExprList_item,zEName)==sizeof(pItem->pExpr) );
+ assert( offsetof(struct ExprList_item,pExpr)==0 );
+ memset(&pItem->zEName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zEName));
+ pItem->pExpr = pExpr;
+ return pList;
+
+no_mem:
+ /* Avoid leaking memory if malloc has failed. */
+ sqlite3ExprDelete(db, pExpr);
+ sqlite3ExprListDelete(db, pList);
+ return 0;
+}
+
+/*
+** pColumns and pExpr form a vector assignment which is part of the SET
+** clause of an UPDATE statement. Like this:
+**
+** (a,b,c) = (expr1,expr2,expr3)
+** Or: (a,b,c) = (SELECT x,y,z FROM ....)
+**
+** For each term of the vector assignment, append new entries to the
+** expression list pList. In the case of a subquery on the RHS, append
+** TK_SELECT_COLUMN expressions.
+*/
+SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
+ Parse *pParse, /* Parsing context */
+ ExprList *pList, /* List to which to append. Might be NULL */
+ IdList *pColumns, /* List of names of LHS of the assignment */
+ Expr *pExpr /* Vector expression to be appended. Might be NULL */
+){
+ sqlite3 *db = pParse->db;
+ int n;
+ int i;
+ int iFirst = pList ? pList->nExpr : 0;
+ /* pColumns can only be NULL due to an OOM but an OOM will cause an
+ ** exit prior to this routine being invoked */
+ if( NEVER(pColumns==0) ) goto vector_append_error;
+ if( pExpr==0 ) goto vector_append_error;
+
+ /* If the RHS is a vector, then we can immediately check to see that
+ ** the size of the RHS and LHS match. But if the RHS is a SELECT,
+ ** wildcards ("*") in the result set of the SELECT must be expanded before
+ ** we can do the size check, so defer the size check until code generation.
+ */
+ if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
+ sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
+ pColumns->nId, n);
+ goto vector_append_error;
+ }
+
+ for(i=0; i<pColumns->nId; i++){
+ Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
+ assert( pSubExpr!=0 || db->mallocFailed );
+ assert( pSubExpr==0 || pSubExpr->iTable==0 );
+ if( pSubExpr==0 ) continue;
+ pSubExpr->iTable = pColumns->nId;
+ pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
+ if( pList ){
+ assert( pList->nExpr==iFirst+i+1 );
+ pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;
+ pColumns->a[i].zName = 0;
+ }
+ }
+
+ if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
+ Expr *pFirst = pList->a[iFirst].pExpr;
+ assert( pFirst!=0 );
+ assert( pFirst->op==TK_SELECT_COLUMN );
+
+ /* Store the SELECT statement in pRight so it will be deleted when
+ ** sqlite3ExprListDelete() is called */
+ pFirst->pRight = pExpr;
+ pExpr = 0;
+
+ /* Remember the size of the LHS in iTable so that we can check that
+ ** the RHS and LHS sizes match during code generation. */
+ pFirst->iTable = pColumns->nId;
+ }
+
+vector_append_error:
+ sqlite3ExprUnmapAndDelete(pParse, pExpr);
+ sqlite3IdListDelete(db, pColumns);
+ return pList;
+}
+
+/*
+** Set the sort order for the last element on the given ExprList.
+*/
+SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
+ struct ExprList_item *pItem;
+ if( p==0 ) return;
+ assert( p->nExpr>0 );
+
+ assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
+ assert( iSortOrder==SQLITE_SO_UNDEFINED
+ || iSortOrder==SQLITE_SO_ASC
+ || iSortOrder==SQLITE_SO_DESC
+ );
+ assert( eNulls==SQLITE_SO_UNDEFINED
+ || eNulls==SQLITE_SO_ASC
+ || eNulls==SQLITE_SO_DESC
+ );
+
+ pItem = &p->a[p->nExpr-1];
+ assert( pItem->bNulls==0 );
+ if( iSortOrder==SQLITE_SO_UNDEFINED ){
+ iSortOrder = SQLITE_SO_ASC;
+ }
+ pItem->sortFlags = (u8)iSortOrder;
+
+ if( eNulls!=SQLITE_SO_UNDEFINED ){
+ pItem->bNulls = 1;
+ if( iSortOrder!=eNulls ){
+ pItem->sortFlags |= KEYINFO_ORDER_BIGNULL;
+ }
+ }
+}
+
+/*
+** Set the ExprList.a[].zEName element of the most recently added item
+** on the expression list.
+**
+** pList might be NULL following an OOM error. But pName should never be
+** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
+** is set.
+*/
+SQLITE_PRIVATE void sqlite3ExprListSetName(
+ Parse *pParse, /* Parsing context */
+ ExprList *pList, /* List to which to add the span. */
+ Token *pName, /* Name to be added */
+ int dequote /* True to cause the name to be dequoted */
+){
+ assert( pList!=0 || pParse->db->mallocFailed!=0 );
+ assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 );
+ if( pList ){
+ struct ExprList_item *pItem;
+ assert( pList->nExpr>0 );
+ pItem = &pList->a[pList->nExpr-1];
+ assert( pItem->zEName==0 );
+ assert( pItem->eEName==ENAME_NAME );
+ pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
+ if( dequote ){
+ /* If dequote==0, then pName->z does not point to part of a DDL
+ ** statement handled by the parser. And so no token need be added
+ ** to the token-map. */
+ sqlite3Dequote(pItem->zEName);
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameTokenMap(pParse, (void*)pItem->zEName, pName);
+ }
+ }
+ }
+}
+
+/*
+** Set the ExprList.a[].zSpan element of the most recently added item
+** on the expression list.
+**
+** pList might be NULL following an OOM error. But pSpan should never be
+** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
+** is set.
+*/
+SQLITE_PRIVATE void sqlite3ExprListSetSpan(
+ Parse *pParse, /* Parsing context */
+ ExprList *pList, /* List to which to add the span. */
+ const char *zStart, /* Start of the span */
+ const char *zEnd /* End of the span */
+){
+ sqlite3 *db = pParse->db;
+ assert( pList!=0 || db->mallocFailed!=0 );
+ if( pList ){
+ struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
+ assert( pList->nExpr>0 );
+ if( pItem->zEName==0 ){
+ pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);
+ pItem->eEName = ENAME_SPAN;
+ }
+ }
+}
+
+/*
+** If the expression list pEList contains more than iLimit elements,
+** leave an error message in pParse.
+*/
+SQLITE_PRIVATE void sqlite3ExprListCheckLength(
+ Parse *pParse,
+ ExprList *pEList,
+ const char *zObject
+){
+ int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
+ testcase( pEList && pEList->nExpr==mx );
+ testcase( pEList && pEList->nExpr==mx+1 );
+ if( pEList && pEList->nExpr>mx ){
+ sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
+ }
+}
+
+/*
+** Delete an entire expression list.
+*/
+static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
+ int i = pList->nExpr;
+ struct ExprList_item *pItem = pList->a;
+ assert( pList->nExpr>0 );
+ do{
+ sqlite3ExprDelete(db, pItem->pExpr);
+ sqlite3DbFree(db, pItem->zEName);
+ pItem++;
+ }while( --i>0 );
+ sqlite3DbFreeNN(db, pList);
+}
+SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
+ if( pList ) exprListDeleteNN(db, pList);
+}
+
+/*
+** Return the bitwise-OR of all Expr.flags fields in the given
+** ExprList.
+*/
+SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
+ int i;
+ u32 m = 0;
+ assert( pList!=0 );
+ for(i=0; i<pList->nExpr; i++){
+ Expr *pExpr = pList->a[i].pExpr;
+ assert( pExpr!=0 );
+ m |= pExpr->flags;
+ }
+ return m;
+}
+
+/*
+** This is a SELECT-node callback for the expression walker that
+** always "fails". By "fail" in this case, we mean set
+** pWalker->eCode to zero and abort.
+**
+** This callback is used by multiple expression walkers.
+*/
+SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
+ UNUSED_PARAMETER(NotUsed);
+ pWalker->eCode = 0;
+ return WRC_Abort;
+}
+
+/*
+** Check the input string to see if it is "true" or "false" (in any case).
+**
+** If the string is.... Return
+** "true" EP_IsTrue
+** "false" EP_IsFalse
+** anything else 0
+*/
+SQLITE_PRIVATE u32 sqlite3IsTrueOrFalse(const char *zIn){
+ if( sqlite3StrICmp(zIn, "true")==0 ) return EP_IsTrue;
+ if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse;
+ return 0;
+}
+
+
+/*
+** If the input expression is an ID with the name "true" or "false"
+** then convert it into an TK_TRUEFALSE term. Return non-zero if
+** the conversion happened, and zero if the expression is unaltered.
+*/
+SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr *pExpr){
+ u32 v;
+ assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
+ if( !ExprHasProperty(pExpr, EP_Quoted)
+ && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
+ ){
+ pExpr->op = TK_TRUEFALSE;
+ ExprSetProperty(pExpr, v);
+ return 1;
+ }
+ return 0;
+}
+
+/*
+** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
+** and 0 if it is FALSE.
+*/
+SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr *pExpr){
+ pExpr = sqlite3ExprSkipCollate((Expr*)pExpr);
+ assert( pExpr->op==TK_TRUEFALSE );
+ assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
+ || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
+ return pExpr->u.zToken[4]==0;
+}
+
+/*
+** If pExpr is an AND or OR expression, try to simplify it by eliminating
+** terms that are always true or false. Return the simplified expression.
+** Or return the original expression if no simplification is possible.
+**
+** Examples:
+**
+** (x<10) AND true => (x<10)
+** (x<10) AND false => false
+** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
+** (x<10) AND (y=22 OR true) => (x<10)
+** (y=22) OR true => true
+*/
+SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
+ assert( pExpr!=0 );
+ if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
+ Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
+ Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
+ if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
+ pExpr = pExpr->op==TK_AND ? pRight : pLeft;
+ }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
+ pExpr = pExpr->op==TK_AND ? pLeft : pRight;
+ }
+ }
+ return pExpr;
+}
+
+
+/*
+** These routines are Walker callbacks used to check expressions to
+** see if they are "constant" for some definition of constant. The
+** Walker.eCode value determines the type of "constant" we are looking
+** for.
+**
+** These callback routines are used to implement the following:
+**
+** sqlite3ExprIsConstant() pWalker->eCode==1
+** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
+** sqlite3ExprIsTableConstant() pWalker->eCode==3
+** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
+**
+** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
+** is found to not be a constant.
+**
+** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
+** expressions in a CREATE TABLE statement. The Walker.eCode value is 5
+** when parsing an existing schema out of the sqlite_schema table and 4
+** when processing a new CREATE TABLE statement. A bound parameter raises
+** an error for new statements, but is silently converted
+** to NULL for existing schemas. This allows sqlite_schema tables that
+** contain a bound parameter because they were generated by older versions
+** of SQLite to be parsed by newer versions of SQLite without raising a
+** malformed schema error.
+*/
+static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
+
+ /* If pWalker->eCode is 2 then any term of the expression that comes from
+ ** the ON or USING clauses of a left join disqualifies the expression
+ ** from being considered constant. */
+ if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
+ pWalker->eCode = 0;
+ return WRC_Abort;
+ }
+
+ switch( pExpr->op ){
+ /* Consider functions to be constant if all their arguments are constant
+ ** and either pWalker->eCode==4 or 5 or the function has the
+ ** SQLITE_FUNC_CONST flag. */
+ case TK_FUNCTION:
+ if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
+ && !ExprHasProperty(pExpr, EP_WinFunc)
+ ){
+ if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);
+ return WRC_Continue;
+ }else{
+ pWalker->eCode = 0;
+ return WRC_Abort;
+ }
+ case TK_ID:
+ /* Convert "true" or "false" in a DEFAULT clause into the
+ ** appropriate TK_TRUEFALSE operator */
+ if( sqlite3ExprIdToTrueFalse(pExpr) ){
+ return WRC_Prune;
+ }
+ /* no break */ deliberate_fall_through
+ case TK_COLUMN:
+ case TK_AGG_FUNCTION:
+ case TK_AGG_COLUMN:
+ testcase( pExpr->op==TK_ID );
+ testcase( pExpr->op==TK_COLUMN );
+ testcase( pExpr->op==TK_AGG_FUNCTION );
+ testcase( pExpr->op==TK_AGG_COLUMN );
+ if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
+ return WRC_Continue;
+ }
+ if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
+ return WRC_Continue;
+ }
+ /* no break */ deliberate_fall_through
+ case TK_IF_NULL_ROW:
+ case TK_REGISTER:
+ case TK_DOT:
+ testcase( pExpr->op==TK_REGISTER );
+ testcase( pExpr->op==TK_IF_NULL_ROW );
+ testcase( pExpr->op==TK_DOT );
+ pWalker->eCode = 0;
+ return WRC_Abort;
+ case TK_VARIABLE:
+ if( pWalker->eCode==5 ){
+ /* Silently convert bound parameters that appear inside of CREATE
+ ** statements into a NULL when parsing the CREATE statement text out
+ ** of the sqlite_schema table */
+ pExpr->op = TK_NULL;
+ }else if( pWalker->eCode==4 ){
+ /* A bound parameter in a CREATE statement that originates from
+ ** sqlite3_prepare() causes an error */
+ pWalker->eCode = 0;
+ return WRC_Abort;
+ }
+ /* no break */ deliberate_fall_through
+ default:
+ testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
+ testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
+ return WRC_Continue;
+ }
+}
+static int exprIsConst(Expr *p, int initFlag, int iCur){
+ Walker w;
+ w.eCode = initFlag;
+ w.xExprCallback = exprNodeIsConstant;
+ w.xSelectCallback = sqlite3SelectWalkFail;
+#ifdef SQLITE_DEBUG
+ w.xSelectCallback2 = sqlite3SelectWalkAssert2;
+#endif
+ w.u.iCur = iCur;
+ sqlite3WalkExpr(&w, p);
+ return w.eCode;
+}
+
+/*
+** Walk an expression tree. Return non-zero if the expression is constant
+** and 0 if it involves variables or function calls.
+**
+** For the purposes of this function, a double-quoted string (ex: "abc")
+** is considered a variable but a single-quoted string (ex: 'abc') is
+** a constant.
+*/
+SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
+ return exprIsConst(p, 1, 0);
+}
+
+/*
+** Walk an expression tree. Return non-zero if
+**
+** (1) the expression is constant, and
+** (2) the expression does originate in the ON or USING clause
+** of a LEFT JOIN, and
+** (3) the expression does not contain any EP_FixedCol TK_COLUMN
+** operands created by the constant propagation optimization.
+**
+** When this routine returns true, it indicates that the expression
+** can be added to the pParse->pConstExpr list and evaluated once when
+** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce().
+*/
+SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
+ return exprIsConst(p, 2, 0);
+}
+
+/*
+** Walk an expression tree. Return non-zero if the expression is constant
+** for any single row of the table with cursor iCur. In other words, the
+** expression must not refer to any non-deterministic function nor any
+** table other than iCur.
+*/
+SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
+ return exprIsConst(p, 3, iCur);
+}
+
+
+/*
+** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
+*/
+static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
+ ExprList *pGroupBy = pWalker->u.pGroupBy;
+ int i;
+
+ /* Check if pExpr is identical to any GROUP BY term. If so, consider
+ ** it constant. */
+ for(i=0; i<pGroupBy->nExpr; i++){
+ Expr *p = pGroupBy->a[i].pExpr;
+ if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
+ CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
+ if( sqlite3IsBinary(pColl) ){
+ return WRC_Prune;
+ }
+ }
+ }
+
+ /* Check if pExpr is a sub-select. If so, consider it variable. */
+ if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+ pWalker->eCode = 0;
+ return WRC_Abort;
+ }
+
+ return exprNodeIsConstant(pWalker, pExpr);
+}
+
+/*
+** Walk the expression tree passed as the first argument. Return non-zero
+** if the expression consists entirely of constants or copies of terms
+** in pGroupBy that sort with the BINARY collation sequence.
+**
+** This routine is used to determine if a term of the HAVING clause can
+** be promoted into the WHERE clause. In order for such a promotion to work,
+** the value of the HAVING clause term must be the same for all members of
+** a "group". The requirement that the GROUP BY term must be BINARY
+** assumes that no other collating sequence will have a finer-grained
+** grouping than binary. In other words (A=B COLLATE binary) implies
+** A=B in every other collating sequence. The requirement that the
+** GROUP BY be BINARY is stricter than necessary. It would also work
+** to promote HAVING clauses that use the same alternative collating
+** sequence as the GROUP BY term, but that is much harder to check,
+** alternative collating sequences are uncommon, and this is only an
+** optimization, so we take the easy way out and simply require the
+** GROUP BY to use the BINARY collating sequence.
+*/
+SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
+ Walker w;
+ w.eCode = 1;
+ w.xExprCallback = exprNodeIsConstantOrGroupBy;
+ w.xSelectCallback = 0;
+ w.u.pGroupBy = pGroupBy;
+ w.pParse = pParse;
+ sqlite3WalkExpr(&w, p);
+ return w.eCode;
+}
+
+/*
+** Walk an expression tree for the DEFAULT field of a column definition
+** in a CREATE TABLE statement. Return non-zero if the expression is
+** acceptable for use as a DEFAULT. That is to say, return non-zero if
+** the expression is constant or a function call with constant arguments.
+** Return and 0 if there are any variables.
+**
+** isInit is true when parsing from sqlite_schema. isInit is false when
+** processing a new CREATE TABLE statement. When isInit is true, parameters
+** (such as ? or $abc) in the expression are converted into NULL. When
+** isInit is false, parameters raise an error. Parameters should not be
+** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
+** allowed it, so we need to support it when reading sqlite_schema for
+** backwards compatibility.
+**
+** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
+**
+** For the purposes of this function, a double-quoted string (ex: "abc")
+** is considered a variable but a single-quoted string (ex: 'abc') is
+** a constant.
+*/
+SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
+ assert( isInit==0 || isInit==1 );
+ return exprIsConst(p, 4+isInit, 0);
+}
+
+#ifdef SQLITE_ENABLE_CURSOR_HINTS
+/*
+** Walk an expression tree. Return 1 if the expression contains a
+** subquery of some kind. Return 0 if there are no subqueries.
+*/
+SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
+ Walker w;
+ w.eCode = 1;
+ w.xExprCallback = sqlite3ExprWalkNoop;
+ w.xSelectCallback = sqlite3SelectWalkFail;
+#ifdef SQLITE_DEBUG
+ w.xSelectCallback2 = sqlite3SelectWalkAssert2;
+#endif
+ sqlite3WalkExpr(&w, p);
+ return w.eCode==0;
+}
+#endif
+
+/*
+** If the expression p codes a constant integer that is small enough
+** to fit in a 32-bit integer, return 1 and put the value of the integer
+** in *pValue. If the expression is not an integer or if it is too big
+** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
+*/
+SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
+ int rc = 0;
+ if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */
+
+ /* If an expression is an integer literal that fits in a signed 32-bit
+ ** integer, then the EP_IntValue flag will have already been set */
+ assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
+ || sqlite3GetInt32(p->u.zToken, &rc)==0 );
+
+ if( p->flags & EP_IntValue ){
+ *pValue = p->u.iValue;
+ return 1;
+ }
+ switch( p->op ){
+ case TK_UPLUS: {
+ rc = sqlite3ExprIsInteger(p->pLeft, pValue);
+ break;
+ }
+ case TK_UMINUS: {
+ int v;
+ if( sqlite3ExprIsInteger(p->pLeft, &v) ){
+ assert( v!=(-2147483647-1) );
+ *pValue = -v;
+ rc = 1;
+ }
+ break;
+ }
+ default: break;
+ }
+ return rc;
+}
+
+/*
+** Return FALSE if there is no chance that the expression can be NULL.
+**
+** If the expression might be NULL or if the expression is too complex
+** to tell return TRUE.
+**
+** This routine is used as an optimization, to skip OP_IsNull opcodes
+** when we know that a value cannot be NULL. Hence, a false positive
+** (returning TRUE when in fact the expression can never be NULL) might
+** be a small performance hit but is otherwise harmless. On the other
+** hand, a false negative (returning FALSE when the result could be NULL)
+** will likely result in an incorrect answer. So when in doubt, return
+** TRUE.
+*/
+SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
+ u8 op;
+ while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
+ p = p->pLeft;
+ }
+ op = p->op;
+ if( op==TK_REGISTER ) op = p->op2;
+ switch( op ){
+ case TK_INTEGER:
+ case TK_STRING:
+ case TK_FLOAT:
+ case TK_BLOB:
+ return 0;
+ case TK_COLUMN:
+ return ExprHasProperty(p, EP_CanBeNull) ||
+ p->y.pTab==0 || /* Reference to column of index on expression */
+ (p->iColumn>=0
+ && ALWAYS(p->y.pTab->aCol!=0) /* Defense against OOM problems */
+ && p->y.pTab->aCol[p->iColumn].notNull==0);
+ default:
+ return 1;
+ }
+}
+
+/*
+** Return TRUE if the given expression is a constant which would be
+** unchanged by OP_Affinity with the affinity given in the second
+** argument.
+**
+** This routine is used to determine if the OP_Affinity operation
+** can be omitted. When in doubt return FALSE. A false negative
+** is harmless. A false positive, however, can result in the wrong
+** answer.
+*/
+SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
+ u8 op;
+ int unaryMinus = 0;
+ if( aff==SQLITE_AFF_BLOB ) return 1;
+ while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
+ if( p->op==TK_UMINUS ) unaryMinus = 1;
+ p = p->pLeft;
+ }
+ op = p->op;
+ if( op==TK_REGISTER ) op = p->op2;
+ switch( op ){
+ case TK_INTEGER: {
+ return aff>=SQLITE_AFF_NUMERIC;
+ }
+ case TK_FLOAT: {
+ return aff>=SQLITE_AFF_NUMERIC;
+ }
+ case TK_STRING: {
+ return !unaryMinus && aff==SQLITE_AFF_TEXT;
+ }
+ case TK_BLOB: {
+ return !unaryMinus;
+ }
+ case TK_COLUMN: {
+ assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
+ return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
+ }
+ default: {
+ return 0;
+ }
+ }
+}
+
+/*
+** Return TRUE if the given string is a row-id column name.
+*/
+SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
+ if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
+ if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
+ if( sqlite3StrICmp(z, "OID")==0 ) return 1;
+ return 0;
+}
+
+/*
+** pX is the RHS of an IN operator. If pX is a SELECT statement
+** that can be simplified to a direct table access, then return
+** a pointer to the SELECT statement. If pX is not a SELECT statement,
+** or if the SELECT statement needs to be manifested into a transient
+** table, then return NULL.
+*/
+#ifndef SQLITE_OMIT_SUBQUERY
+static Select *isCandidateForInOpt(Expr *pX){
+ Select *p;
+ SrcList *pSrc;
+ ExprList *pEList;
+ Table *pTab;
+ int i;
+ if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
+ if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
+ p = pX->x.pSelect;
+ if( p->pPrior ) return 0; /* Not a compound SELECT */
+ if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
+ testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
+ testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
+ return 0; /* No DISTINCT keyword and no aggregate functions */
+ }
+ assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
+ if( p->pLimit ) return 0; /* Has no LIMIT clause */
+ if( p->pWhere ) return 0; /* Has no WHERE clause */
+ pSrc = p->pSrc;
+ assert( pSrc!=0 );
+ if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
+ if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
+ pTab = pSrc->a[0].pTab;
+ assert( pTab!=0 );
+ assert( pTab->pSelect==0 ); /* FROM clause is not a view */
+ if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
+ pEList = p->pEList;
+ assert( pEList!=0 );
+ /* All SELECT results must be columns. */
+ for(i=0; i<pEList->nExpr; i++){
+ Expr *pRes = pEList->a[i].pExpr;
+ if( pRes->op!=TK_COLUMN ) return 0;
+ assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
+ }
+ return p;
+}
+#endif /* SQLITE_OMIT_SUBQUERY */
+
+#ifndef SQLITE_OMIT_SUBQUERY
+/*
+** Generate code that checks the left-most column of index table iCur to see if
+** it contains any NULL entries. Cause the register at regHasNull to be set
+** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
+** to be set to NULL if iCur contains one or more NULL values.
+*/
+static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
+ int addr1;
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
+ addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
+ sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
+ sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
+ VdbeComment((v, "first_entry_in(%d)", iCur));
+ sqlite3VdbeJumpHere(v, addr1);
+}
+#endif
+
+
+#ifndef SQLITE_OMIT_SUBQUERY
+/*
+** The argument is an IN operator with a list (not a subquery) on the
+** right-hand side. Return TRUE if that list is constant.
+*/
+static int sqlite3InRhsIsConstant(Expr *pIn){
+ Expr *pLHS;
+ int res;
+ assert( !ExprHasProperty(pIn, EP_xIsSelect) );
+ pLHS = pIn->pLeft;
+ pIn->pLeft = 0;
+ res = sqlite3ExprIsConstant(pIn);
+ pIn->pLeft = pLHS;
+ return res;
+}
+#endif
+
+/*
+** This function is used by the implementation of the IN (...) operator.
+** The pX parameter is the expression on the RHS of the IN operator, which
+** might be either a list of expressions or a subquery.
+**
+** The job of this routine is to find or create a b-tree object that can
+** be used either to test for membership in the RHS set or to iterate through
+** all members of the RHS set, skipping duplicates.
+**
+** A cursor is opened on the b-tree object that is the RHS of the IN operator
+** and pX->iTable is set to the index of that cursor.
+**
+** The returned value of this function indicates the b-tree type, as follows:
+**
+** IN_INDEX_ROWID - The cursor was opened on a database table.
+** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
+** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
+** IN_INDEX_EPH - The cursor was opened on a specially created and
+** populated epheremal table.
+** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
+** implemented as a sequence of comparisons.
+**
+** An existing b-tree might be used if the RHS expression pX is a simple
+** subquery such as:
+**
+** SELECT <column1>, <column2>... FROM <table>
+**
+** If the RHS of the IN operator is a list or a more complex subquery, then
+** an ephemeral table might need to be generated from the RHS and then
+** pX->iTable made to point to the ephemeral table instead of an
+** existing table.
+**
+** The inFlags parameter must contain, at a minimum, one of the bits
+** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
+** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
+** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
+** be used to loop over all values of the RHS of the IN operator.
+**
+** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
+** through the set members) then the b-tree must not contain duplicates.
+** An epheremal table will be created unless the selected columns are guaranteed
+** to be unique - either because it is an INTEGER PRIMARY KEY or due to
+** a UNIQUE constraint or index.
+**
+** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
+** for fast set membership tests) then an epheremal table must
+** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
+** index can be found with the specified <columns> as its left-most.
+**
+** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
+** if the RHS of the IN operator is a list (not a subquery) then this
+** routine might decide that creating an ephemeral b-tree for membership
+** testing is too expensive and return IN_INDEX_NOOP. In that case, the
+** calling routine should implement the IN operator using a sequence
+** of Eq or Ne comparison operations.
+**
+** When the b-tree is being used for membership tests, the calling function
+** might need to know whether or not the RHS side of the IN operator
+** contains a NULL. If prRhsHasNull is not a NULL pointer and
+** if there is any chance that the (...) might contain a NULL value at
+** runtime, then a register is allocated and the register number written
+** to *prRhsHasNull. If there is no chance that the (...) contains a
+** NULL value, then *prRhsHasNull is left unchanged.
+**
+** If a register is allocated and its location stored in *prRhsHasNull, then
+** the value in that register will be NULL if the b-tree contains one or more
+** NULL values, and it will be some non-NULL value if the b-tree contains no
+** NULL values.
+**
+** If the aiMap parameter is not NULL, it must point to an array containing
+** one element for each column returned by the SELECT statement on the RHS
+** of the IN(...) operator. The i'th entry of the array is populated with the
+** offset of the index column that matches the i'th column returned by the
+** SELECT. For example, if the expression and selected index are:
+**
+** (?,?,?) IN (SELECT a, b, c FROM t1)
+** CREATE INDEX i1 ON t1(b, c, a);
+**
+** then aiMap[] is populated with {2, 0, 1}.
+*/
+#ifndef SQLITE_OMIT_SUBQUERY
+SQLITE_PRIVATE int sqlite3FindInIndex(
+ Parse *pParse, /* Parsing context */
+ Expr *pX, /* The IN expression */
+ u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
+ int *prRhsHasNull, /* Register holding NULL status. See notes */
+ int *aiMap, /* Mapping from Index fields to RHS fields */
+ int *piTab /* OUT: index to use */
+){
+ Select *p; /* SELECT to the right of IN operator */
+ int eType = 0; /* Type of RHS table. IN_INDEX_* */
+ int iTab = pParse->nTab++; /* Cursor of the RHS table */
+ int mustBeUnique; /* True if RHS must be unique */
+ Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
+
+ assert( pX->op==TK_IN );
+ mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
+
+ /* If the RHS of this IN(...) operator is a SELECT, and if it matters
+ ** whether or not the SELECT result contains NULL values, check whether
+ ** or not NULL is actually possible (it may not be, for example, due
+ ** to NOT NULL constraints in the schema). If no NULL values are possible,
+ ** set prRhsHasNull to 0 before continuing. */
+ if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
+ int i;
+ ExprList *pEList = pX->x.pSelect->pEList;
+ for(i=0; i<pEList->nExpr; i++){
+ if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
+ }
+ if( i==pEList->nExpr ){
+ prRhsHasNull = 0;
+ }
+ }
+
+ /* Check to see if an existing table or index can be used to
+ ** satisfy the query. This is preferable to generating a new
+ ** ephemeral table. */
+ if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
+ sqlite3 *db = pParse->db; /* Database connection */
+ Table *pTab; /* Table <table>. */
+ int iDb; /* Database idx for pTab */
+ ExprList *pEList = p->pEList;
+ int nExpr = pEList->nExpr;
+
+ assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
+ assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
+ assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
+ pTab = p->pSrc->a[0].pTab;
+
+ /* Code an OP_Transaction and OP_TableLock for <table>. */
+ iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ assert( iDb>=0 && iDb<SQLITE_MAX_ATTACHED );
+ sqlite3CodeVerifySchema(pParse, iDb);
+ sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
+
+ assert(v); /* sqlite3GetVdbe() has always been previously called */
+ if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
+ /* The "x IN (SELECT rowid FROM table)" case */
+ int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
+ VdbeCoverage(v);
+
+ sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
+ eType = IN_INDEX_ROWID;
+ ExplainQueryPlan((pParse, 0,
+ "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
+ sqlite3VdbeJumpHere(v, iAddr);
+ }else{
+ Index *pIdx; /* Iterator variable */
+ int affinity_ok = 1;
+ int i;
+
+ /* Check that the affinity that will be used to perform each
+ ** comparison is the same as the affinity of each column in table
+ ** on the RHS of the IN operator. If it not, it is not possible to
+ ** use any index of the RHS table. */
+ for(i=0; i<nExpr && affinity_ok; i++){
+ Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
+ int iCol = pEList->a[i].pExpr->iColumn;
+ char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
+ char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
+ testcase( cmpaff==SQLITE_AFF_BLOB );
+ testcase( cmpaff==SQLITE_AFF_TEXT );
+ switch( cmpaff ){
+ case SQLITE_AFF_BLOB:
+ break;
+ case SQLITE_AFF_TEXT:
+ /* sqlite3CompareAffinity() only returns TEXT if one side or the
+ ** other has no affinity and the other side is TEXT. Hence,
+ ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
+ ** and for the term on the LHS of the IN to have no affinity. */
+ assert( idxaff==SQLITE_AFF_TEXT );
+ break;
+ default:
+ affinity_ok = sqlite3IsNumericAffinity(idxaff);
+ }
+ }
+
+ if( affinity_ok ){
+ /* Search for an existing index that will work for this IN operator */
+ for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
+ Bitmask colUsed; /* Columns of the index used */
+ Bitmask mCol; /* Mask for the current column */
+ if( pIdx->nColumn<nExpr ) continue;
+ if( pIdx->pPartIdxWhere!=0 ) continue;
+ /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
+ ** BITMASK(nExpr) without overflowing */
+ testcase( pIdx->nColumn==BMS-2 );
+ testcase( pIdx->nColumn==BMS-1 );
+ if( pIdx->nColumn>=BMS-1 ) continue;
+ if( mustBeUnique ){
+ if( pIdx->nKeyCol>nExpr
+ ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
+ ){
+ continue; /* This index is not unique over the IN RHS columns */
+ }
+ }
+
+ colUsed = 0; /* Columns of index used so far */
+ for(i=0; i<nExpr; i++){
+ Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
+ Expr *pRhs = pEList->a[i].pExpr;
+ CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
+ int j;
+
+ assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
+ for(j=0; j<nExpr; j++){
+ if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
+ assert( pIdx->azColl[j] );
+ if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
+ continue;
+ }
+ break;
+ }
+ if( j==nExpr ) break;
+ mCol = MASKBIT(j);
+ if( mCol & colUsed ) break; /* Each column used only once */
+ colUsed |= mCol;
+ if( aiMap ) aiMap[i] = j;
+ }
+
+ assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
+ if( colUsed==(MASKBIT(nExpr)-1) ){
+ /* If we reach this point, that means the index pIdx is usable */
+ int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
+ ExplainQueryPlan((pParse, 0,
+ "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
+ sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
+ sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
+ VdbeComment((v, "%s", pIdx->zName));
+ assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
+ eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
+
+ if( prRhsHasNull ){
+#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
+ i64 mask = (1<<nExpr)-1;
+ sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
+ iTab, 0, 0, (u8*)&mask, P4_INT64);
+#endif
+ *prRhsHasNull = ++pParse->nMem;
+ if( nExpr==1 ){
+ sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
+ }
+ }
+ sqlite3VdbeJumpHere(v, iAddr);
+ }
+ } /* End loop over indexes */
+ } /* End if( affinity_ok ) */
+ } /* End if not an rowid index */
+ } /* End attempt to optimize using an index */
+
+ /* If no preexisting index is available for the IN clause
+ ** and IN_INDEX_NOOP is an allowed reply
+ ** and the RHS of the IN operator is a list, not a subquery
+ ** and the RHS is not constant or has two or fewer terms,
+ ** then it is not worth creating an ephemeral table to evaluate
+ ** the IN operator so return IN_INDEX_NOOP.
+ */
+ if( eType==0
+ && (inFlags & IN_INDEX_NOOP_OK)
+ && !ExprHasProperty(pX, EP_xIsSelect)
+ && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
+ ){
+ eType = IN_INDEX_NOOP;
+ }
+
+ if( eType==0 ){
+ /* Could not find an existing table or index to use as the RHS b-tree.
+ ** We will have to generate an ephemeral table to do the job.
+ */
+ u32 savedNQueryLoop = pParse->nQueryLoop;
+ int rMayHaveNull = 0;
+ eType = IN_INDEX_EPH;
+ if( inFlags & IN_INDEX_LOOP ){
+ pParse->nQueryLoop = 0;
+ }else if( prRhsHasNull ){
+ *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
+ }
+ assert( pX->op==TK_IN );
+ sqlite3CodeRhsOfIN(pParse, pX, iTab);
+ if( rMayHaveNull ){
+ sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
+ }
+ pParse->nQueryLoop = savedNQueryLoop;
+ }
+
+ if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
+ int i, n;
+ n = sqlite3ExprVectorSize(pX->pLeft);
+ for(i=0; i<n; i++) aiMap[i] = i;
+ }
+ *piTab = iTab;
+ return eType;
+}
+#endif
+
+#ifndef SQLITE_OMIT_SUBQUERY
+/*
+** Argument pExpr is an (?, ?...) IN(...) expression. This
+** function allocates and returns a nul-terminated string containing
+** the affinities to be used for each column of the comparison.
+**
+** It is the responsibility of the caller to ensure that the returned
+** string is eventually freed using sqlite3DbFree().
+*/
+static char *exprINAffinity(Parse *pParse, Expr *pExpr){
+ Expr *pLeft = pExpr->pLeft;
+ int nVal = sqlite3ExprVectorSize(pLeft);
+ Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
+ char *zRet;
+
+ assert( pExpr->op==TK_IN );
+ zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
+ if( zRet ){
+ int i;
+ for(i=0; i<nVal; i++){
+ Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
+ char a = sqlite3ExprAffinity(pA);
+ if( pSelect ){
+ zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
+ }else{
+ zRet[i] = a;
+ }
+ }
+ zRet[nVal] = '\0';
+ }
+ return zRet;
+}
+#endif
+
+#ifndef SQLITE_OMIT_SUBQUERY
+/*
+** Load the Parse object passed as the first argument with an error
+** message of the form:
+**
+** "sub-select returns N columns - expected M"
+*/
+SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
+ if( pParse->nErr==0 ){
+ const char *zFmt = "sub-select returns %d columns - expected %d";
+ sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
+ }
+}
+#endif
+
+/*
+** Expression pExpr is a vector that has been used in a context where
+** it is not permitted. If pExpr is a sub-select vector, this routine
+** loads the Parse object with a message of the form:
+**
+** "sub-select returns N columns - expected 1"
+**
+** Or, if it is a regular scalar vector:
+**
+** "row value misused"
+*/
+SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
+#ifndef SQLITE_OMIT_SUBQUERY
+ if( pExpr->flags & EP_xIsSelect ){
+ sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
+ }else
+#endif
+ {
+ sqlite3ErrorMsg(pParse, "row value misused");
+ }
+}
+
+#ifndef SQLITE_OMIT_SUBQUERY
+/*
+** Generate code that will construct an ephemeral table containing all terms
+** in the RHS of an IN operator. The IN operator can be in either of two
+** forms:
+**
+** x IN (4,5,11) -- IN operator with list on right-hand side
+** x IN (SELECT a FROM b) -- IN operator with subquery on the right
+**
+** The pExpr parameter is the IN operator. The cursor number for the
+** constructed ephermeral table is returned. The first time the ephemeral
+** table is computed, the cursor number is also stored in pExpr->iTable,
+** however the cursor number returned might not be the same, as it might
+** have been duplicated using OP_OpenDup.
+**
+** If the LHS expression ("x" in the examples) is a column value, or
+** the SELECT statement returns a column value, then the affinity of that
+** column is used to build the index keys. If both 'x' and the
+** SELECT... statement are columns, then numeric affinity is used
+** if either column has NUMERIC or INTEGER affinity. If neither
+** 'x' nor the SELECT... statement are columns, then numeric affinity
+** is used.
+*/
+SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
+ Parse *pParse, /* Parsing context */
+ Expr *pExpr, /* The IN operator */
+ int iTab /* Use this cursor number */
+){
+ int addrOnce = 0; /* Address of the OP_Once instruction at top */
+ int addr; /* Address of OP_OpenEphemeral instruction */
+ Expr *pLeft; /* the LHS of the IN operator */
+ KeyInfo *pKeyInfo = 0; /* Key information */
+ int nVal; /* Size of vector pLeft */
+ Vdbe *v; /* The prepared statement under construction */
+
+ v = pParse->pVdbe;
+ assert( v!=0 );
+
+ /* The evaluation of the IN must be repeated every time it
+ ** is encountered if any of the following is true:
+ **
+ ** * The right-hand side is a correlated subquery
+ ** * The right-hand side is an expression list containing variables
+ ** * We are inside a trigger
+ **
+ ** If all of the above are false, then we can compute the RHS just once
+ ** and reuse it many names.
+ */
+ if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
+ /* Reuse of the RHS is allowed */
+ /* If this routine has already been coded, but the previous code
+ ** might not have been invoked yet, so invoke it now as a subroutine.
+ */
+ if( ExprHasProperty(pExpr, EP_Subrtn) ){
+ addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
+ if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+ ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
+ pExpr->x.pSelect->selId));
+ }
+ sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
+ pExpr->y.sub.iAddr);
+ sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
+ sqlite3VdbeJumpHere(v, addrOnce);
+ return;
+ }
+
+ /* Begin coding the subroutine */
+ ExprSetProperty(pExpr, EP_Subrtn);
+ assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
+ pExpr->y.sub.regReturn = ++pParse->nMem;
+ pExpr->y.sub.iAddr =
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
+ VdbeComment((v, "return address"));
+
+ addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
+ }
+
+ /* Check to see if this is a vector IN operator */
+ pLeft = pExpr->pLeft;
+ nVal = sqlite3ExprVectorSize(pLeft);
+
+ /* Construct the ephemeral table that will contain the content of
+ ** RHS of the IN operator.
+ */
+ pExpr->iTable = iTab;
+ addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+ if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+ VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
+ }else{
+ VdbeComment((v, "RHS of IN operator"));
+ }
+#endif
+ pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
+
+ if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+ /* Case 1: expr IN (SELECT ...)
+ **
+ ** Generate code to write the results of the select into the temporary
+ ** table allocated and opened above.
+ */
+ Select *pSelect = pExpr->x.pSelect;
+ ExprList *pEList = pSelect->pEList;
+
+ ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
+ addrOnce?"":"CORRELATED ", pSelect->selId
+ ));
+ /* If the LHS and RHS of the IN operator do not match, that
+ ** error will have been caught long before we reach this point. */
+ if( ALWAYS(pEList->nExpr==nVal) ){
+ SelectDest dest;
+ int i;
+ sqlite3SelectDestInit(&dest, SRT_Set, iTab);
+ dest.zAffSdst = exprINAffinity(pParse, pExpr);
+ pSelect->iLimit = 0;
+ testcase( pSelect->selFlags & SF_Distinct );
+ testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
+ if( sqlite3Select(pParse, pSelect, &dest) ){
+ sqlite3DbFree(pParse->db, dest.zAffSdst);
+ sqlite3KeyInfoUnref(pKeyInfo);
+ return;
+ }
+ sqlite3DbFree(pParse->db, dest.zAffSdst);
+ assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
+ assert( pEList!=0 );
+ assert( pEList->nExpr>0 );
+ assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
+ for(i=0; i<nVal; i++){
+ Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
+ pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
+ pParse, p, pEList->a[i].pExpr
+ );
+ }
+ }
+ }else if( ALWAYS(pExpr->x.pList!=0) ){
+ /* Case 2: expr IN (exprlist)
+ **
+ ** For each expression, build an index key from the evaluation and
+ ** store it in the temporary table. If <expr> is a column, then use
+ ** that columns affinity when building index keys. If <expr> is not
+ ** a column, use numeric affinity.
+ */
+ char affinity; /* Affinity of the LHS of the IN */
+ int i;
+ ExprList *pList = pExpr->x.pList;
+ struct ExprList_item *pItem;
+ int r1, r2;
+ affinity = sqlite3ExprAffinity(pLeft);
+ if( affinity<=SQLITE_AFF_NONE ){
+ affinity = SQLITE_AFF_BLOB;
+ }else if( affinity==SQLITE_AFF_REAL ){
+ affinity = SQLITE_AFF_NUMERIC;
+ }
+ if( pKeyInfo ){
+ assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
+ pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
+ }
+
+ /* Loop through each expression in <exprlist>. */
+ r1 = sqlite3GetTempReg(pParse);
+ r2 = sqlite3GetTempReg(pParse);
+ for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
+ Expr *pE2 = pItem->pExpr;
+
+ /* If the expression is not constant then we will need to
+ ** disable the test that was generated above that makes sure
+ ** this code only executes once. Because for a non-constant
+ ** expression we need to rerun this code each time.
+ */
+ if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
+ sqlite3VdbeChangeToNoop(v, addrOnce);
+ ExprClearProperty(pExpr, EP_Subrtn);
+ addrOnce = 0;
+ }
+
+ /* Evaluate the expression and insert it into the temp table */
+ sqlite3ExprCode(pParse, pE2, r1);
+ sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
+ }
+ sqlite3ReleaseTempReg(pParse, r1);
+ sqlite3ReleaseTempReg(pParse, r2);
+ }
+ if( pKeyInfo ){
+ sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
+ }
+ if( addrOnce ){
+ sqlite3VdbeJumpHere(v, addrOnce);
+ /* Subroutine return */
+ sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
+ sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
+ sqlite3ClearTempRegCache(pParse);
+ }
+}
+#endif /* SQLITE_OMIT_SUBQUERY */
+
+/*
+** Generate code for scalar subqueries used as a subquery expression
+** or EXISTS operator:
+**
+** (SELECT a FROM b) -- subquery
+** EXISTS (SELECT a FROM b) -- EXISTS subquery
+**
+** The pExpr parameter is the SELECT or EXISTS operator to be coded.
+**
+** Return the register that holds the result. For a multi-column SELECT,
+** the result is stored in a contiguous array of registers and the
+** return value is the register of the left-most result column.
+** Return 0 if an error occurs.
+*/
+#ifndef SQLITE_OMIT_SUBQUERY
+SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
+ int addrOnce = 0; /* Address of OP_Once at top of subroutine */
+ int rReg = 0; /* Register storing resulting */
+ Select *pSel; /* SELECT statement to encode */
+ SelectDest dest; /* How to deal with SELECT result */
+ int nReg; /* Registers to allocate */
+ Expr *pLimit; /* New limit expression */
+
+ Vdbe *v = pParse->pVdbe;
+ assert( v!=0 );
+ testcase( pExpr->op==TK_EXISTS );
+ testcase( pExpr->op==TK_SELECT );
+ assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
+ assert( ExprHasProperty(pExpr, EP_xIsSelect) );
+ pSel = pExpr->x.pSelect;
+
+ /* The evaluation of the EXISTS/SELECT must be repeated every time it
+ ** is encountered if any of the following is true:
+ **
+ ** * The right-hand side is a correlated subquery
+ ** * The right-hand side is an expression list containing variables
+ ** * We are inside a trigger
+ **
+ ** If all of the above are false, then we can run this code just once
+ ** save the results, and reuse the same result on subsequent invocations.
+ */
+ if( !ExprHasProperty(pExpr, EP_VarSelect) ){
+ /* If this routine has already been coded, then invoke it as a
+ ** subroutine. */
+ if( ExprHasProperty(pExpr, EP_Subrtn) ){
+ ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
+ sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
+ pExpr->y.sub.iAddr);
+ return pExpr->iTable;
+ }
+
+ /* Begin coding the subroutine */
+ ExprSetProperty(pExpr, EP_Subrtn);
+ pExpr->y.sub.regReturn = ++pParse->nMem;
+ pExpr->y.sub.iAddr =
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
+ VdbeComment((v, "return address"));
+
+ addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
+ }
+
+ /* For a SELECT, generate code to put the values for all columns of
+ ** the first row into an array of registers and return the index of
+ ** the first register.
+ **
+ ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
+ ** into a register and return that register number.
+ **
+ ** In both cases, the query is augmented with "LIMIT 1". Any
+ ** preexisting limit is discarded in place of the new LIMIT 1.
+ */
+ ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d",
+ addrOnce?"":"CORRELATED ", pSel->selId));
+ nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
+ sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
+ pParse->nMem += nReg;
+ if( pExpr->op==TK_SELECT ){
+ dest.eDest = SRT_Mem;
+ dest.iSdst = dest.iSDParm;
+ dest.nSdst = nReg;
+ sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
+ VdbeComment((v, "Init subquery result"));
+ }else{
+ dest.eDest = SRT_Exists;
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
+ VdbeComment((v, "Init EXISTS result"));
+ }
+ if( pSel->pLimit ){
+ /* The subquery already has a limit. If the pre-existing limit is X
+ ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
+ sqlite3 *db = pParse->db;
+ pLimit = sqlite3Expr(db, TK_INTEGER, "0");
+ if( pLimit ){
+ pLimit->affExpr = SQLITE_AFF_NUMERIC;
+ pLimit = sqlite3PExpr(pParse, TK_NE,
+ sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
+ }
+ sqlite3ExprDelete(db, pSel->pLimit->pLeft);
+ pSel->pLimit->pLeft = pLimit;
+ }else{
+ /* If there is no pre-existing limit add a limit of 1 */
+ pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
+ pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
+ }
+ pSel->iLimit = 0;
+ if( sqlite3Select(pParse, pSel, &dest) ){
+ return 0;
+ }
+ pExpr->iTable = rReg = dest.iSDParm;
+ ExprSetVVAProperty(pExpr, EP_NoReduce);
+ if( addrOnce ){
+ sqlite3VdbeJumpHere(v, addrOnce);
+
+ /* Subroutine return */
+ sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
+ sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
+ sqlite3ClearTempRegCache(pParse);
+ }
+
+ return rReg;
+}
+#endif /* SQLITE_OMIT_SUBQUERY */
+
+#ifndef SQLITE_OMIT_SUBQUERY
+/*
+** Expr pIn is an IN(...) expression. This function checks that the
+** sub-select on the RHS of the IN() operator has the same number of
+** columns as the vector on the LHS. Or, if the RHS of the IN() is not
+** a sub-query, that the LHS is a vector of size 1.
+*/
+SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
+ int nVector = sqlite3ExprVectorSize(pIn->pLeft);
+ if( (pIn->flags & EP_xIsSelect) ){
+ if( nVector!=pIn->x.pSelect->pEList->nExpr ){
+ sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
+ return 1;
+ }
+ }else if( nVector!=1 ){
+ sqlite3VectorErrorMsg(pParse, pIn->pLeft);
+ return 1;
+ }
+ return 0;
+}
+#endif
+
+#ifndef SQLITE_OMIT_SUBQUERY
+/*
+** Generate code for an IN expression.
+**
+** x IN (SELECT ...)
+** x IN (value, value, ...)
+**
+** The left-hand side (LHS) is a scalar or vector expression. The
+** right-hand side (RHS) is an array of zero or more scalar values, or a
+** subquery. If the RHS is a subquery, the number of result columns must
+** match the number of columns in the vector on the LHS. If the RHS is
+** a list of values, the LHS must be a scalar.
+**
+** The IN operator is true if the LHS value is contained within the RHS.
+** The result is false if the LHS is definitely not in the RHS. The
+** result is NULL if the presence of the LHS in the RHS cannot be
+** determined due to NULLs.
+**
+** This routine generates code that jumps to destIfFalse if the LHS is not
+** contained within the RHS. If due to NULLs we cannot determine if the LHS
+** is contained in the RHS then jump to destIfNull. If the LHS is contained
+** within the RHS then fall through.
+**
+** See the separate in-operator.md documentation file in the canonical
+** SQLite source tree for additional information.
+*/
+static void sqlite3ExprCodeIN(
+ Parse *pParse, /* Parsing and code generating context */
+ Expr *pExpr, /* The IN expression */
+ int destIfFalse, /* Jump here if LHS is not contained in the RHS */
+ int destIfNull /* Jump here if the results are unknown due to NULLs */
+){
+ int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
+ int eType; /* Type of the RHS */
+ int rLhs; /* Register(s) holding the LHS values */
+ int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
+ Vdbe *v; /* Statement under construction */
+ int *aiMap = 0; /* Map from vector field to index column */
+ char *zAff = 0; /* Affinity string for comparisons */
+ int nVector; /* Size of vectors for this IN operator */
+ int iDummy; /* Dummy parameter to exprCodeVector() */
+ Expr *pLeft; /* The LHS of the IN operator */
+ int i; /* loop counter */
+ int destStep2; /* Where to jump when NULLs seen in step 2 */
+ int destStep6 = 0; /* Start of code for Step 6 */
+ int addrTruthOp; /* Address of opcode that determines the IN is true */
+ int destNotNull; /* Jump here if a comparison is not true in step 6 */
+ int addrTop; /* Top of the step-6 loop */
+ int iTab = 0; /* Index to use */
+ u8 okConstFactor = pParse->okConstFactor;
+
+ assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
+ pLeft = pExpr->pLeft;
+ if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
+ zAff = exprINAffinity(pParse, pExpr);
+ nVector = sqlite3ExprVectorSize(pExpr->pLeft);
+ aiMap = (int*)sqlite3DbMallocZero(
+ pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
+ );
+ if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
+
+ /* Attempt to compute the RHS. After this step, if anything other than
+ ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
+ ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
+ ** the RHS has not yet been coded. */
+ v = pParse->pVdbe;
+ assert( v!=0 ); /* OOM detected prior to this routine */
+ VdbeNoopComment((v, "begin IN expr"));
+ eType = sqlite3FindInIndex(pParse, pExpr,
+ IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
+ destIfFalse==destIfNull ? 0 : &rRhsHasNull,
+ aiMap, &iTab);
+
+ assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
+ || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
+ );
+#ifdef SQLITE_DEBUG
+ /* Confirm that aiMap[] contains nVector integer values between 0 and
+ ** nVector-1. */
+ for(i=0; i<nVector; i++){
+ int j, cnt;
+ for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
+ assert( cnt==1 );
+ }
+#endif
+
+ /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
+ ** vector, then it is stored in an array of nVector registers starting
+ ** at r1.
+ **
+ ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
+ ** so that the fields are in the same order as an existing index. The
+ ** aiMap[] array contains a mapping from the original LHS field order to
+ ** the field order that matches the RHS index.
+ **
+ ** Avoid factoring the LHS of the IN(...) expression out of the loop,
+ ** even if it is constant, as OP_Affinity may be used on the register
+ ** by code generated below. */
+ assert( pParse->okConstFactor==okConstFactor );
+ pParse->okConstFactor = 0;
+ rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
+ pParse->okConstFactor = okConstFactor;
+ for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
+ if( i==nVector ){
+ /* LHS fields are not reordered */
+ rLhs = rLhsOrig;
+ }else{
+ /* Need to reorder the LHS fields according to aiMap */
+ rLhs = sqlite3GetTempRange(pParse, nVector);
+ for(i=0; i<nVector; i++){
+ sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
+ }
+ }
+
+ /* If sqlite3FindInIndex() did not find or create an index that is
+ ** suitable for evaluating the IN operator, then evaluate using a
+ ** sequence of comparisons.
+ **
+ ** This is step (1) in the in-operator.md optimized algorithm.
+ */
+ if( eType==IN_INDEX_NOOP ){
+ ExprList *pList = pExpr->x.pList;
+ CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
+ int labelOk = sqlite3VdbeMakeLabel(pParse);
+ int r2, regToFree;
+ int regCkNull = 0;
+ int ii;
+ assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
+ if( destIfNull!=destIfFalse ){
+ regCkNull = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
+ }
+ for(ii=0; ii<pList->nExpr; ii++){
+ r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
+ if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
+ sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
+ }
+ sqlite3ReleaseTempReg(pParse, regToFree);
+ if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
+ int op = rLhs!=r2 ? OP_Eq : OP_NotNull;
+ sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2,
+ (void*)pColl, P4_COLLSEQ);
+ VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
+ VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
+ VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
+ VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
+ sqlite3VdbeChangeP5(v, zAff[0]);
+ }else{
+ int op = rLhs!=r2 ? OP_Ne : OP_IsNull;
+ assert( destIfNull==destIfFalse );
+ sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2,
+ (void*)pColl, P4_COLLSEQ);
+ VdbeCoverageIf(v, op==OP_Ne);
+ VdbeCoverageIf(v, op==OP_IsNull);
+ sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
+ }
+ }
+ if( regCkNull ){
+ sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
+ sqlite3VdbeGoto(v, destIfFalse);
+ }
+ sqlite3VdbeResolveLabel(v, labelOk);
+ sqlite3ReleaseTempReg(pParse, regCkNull);
+ goto sqlite3ExprCodeIN_finished;
+ }
+
+ /* Step 2: Check to see if the LHS contains any NULL columns. If the
+ ** LHS does contain NULLs then the result must be either FALSE or NULL.
+ ** We will then skip the binary search of the RHS.
+ */
+ if( destIfNull==destIfFalse ){
+ destStep2 = destIfFalse;
+ }else{
+ destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
+ }
+ if( pParse->nErr ) goto sqlite3ExprCodeIN_finished;
+ for(i=0; i<nVector; i++){
+ Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
+ if( sqlite3ExprCanBeNull(p) ){
+ sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
+ VdbeCoverage(v);
+ }
+ }
+
+ /* Step 3. The LHS is now known to be non-NULL. Do the binary search
+ ** of the RHS using the LHS as a probe. If found, the result is
+ ** true.
+ */
+ if( eType==IN_INDEX_ROWID ){
+ /* In this case, the RHS is the ROWID of table b-tree and so we also
+ ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
+ ** into a single opcode. */
+ sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
+ VdbeCoverage(v);
+ addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
+ }else{
+ sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
+ if( destIfFalse==destIfNull ){
+ /* Combine Step 3 and Step 5 into a single opcode */
+ sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
+ rLhs, nVector); VdbeCoverage(v);
+ goto sqlite3ExprCodeIN_finished;
+ }
+ /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
+ addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
+ rLhs, nVector); VdbeCoverage(v);
+ }
+
+ /* Step 4. If the RHS is known to be non-NULL and we did not find
+ ** an match on the search above, then the result must be FALSE.
+ */
+ if( rRhsHasNull && nVector==1 ){
+ sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
+ VdbeCoverage(v);
+ }
+
+ /* Step 5. If we do not care about the difference between NULL and
+ ** FALSE, then just return false.
+ */
+ if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
+
+ /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
+ ** If any comparison is NULL, then the result is NULL. If all
+ ** comparisons are FALSE then the final result is FALSE.
+ **
+ ** For a scalar LHS, it is sufficient to check just the first row
+ ** of the RHS.
+ */
+ if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
+ addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
+ VdbeCoverage(v);
+ if( nVector>1 ){
+ destNotNull = sqlite3VdbeMakeLabel(pParse);
+ }else{
+ /* For nVector==1, combine steps 6 and 7 by immediately returning
+ ** FALSE if the first comparison is not NULL */
+ destNotNull = destIfFalse;
+ }
+ for(i=0; i<nVector; i++){
+ Expr *p;
+ CollSeq *pColl;
+ int r3 = sqlite3GetTempReg(pParse);
+ p = sqlite3VectorFieldSubexpr(pLeft, i);
+ pColl = sqlite3ExprCollSeq(pParse, p);
+ sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
+ sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
+ (void*)pColl, P4_COLLSEQ);
+ VdbeCoverage(v);
+ sqlite3ReleaseTempReg(pParse, r3);
+ }
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
+ if( nVector>1 ){
+ sqlite3VdbeResolveLabel(v, destNotNull);
+ sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
+ VdbeCoverage(v);
+
+ /* Step 7: If we reach this point, we know that the result must
+ ** be false. */
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
+ }
+
+ /* Jumps here in order to return true. */
+ sqlite3VdbeJumpHere(v, addrTruthOp);
+
+sqlite3ExprCodeIN_finished:
+ if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
+ VdbeComment((v, "end IN expr"));
+sqlite3ExprCodeIN_oom_error:
+ sqlite3DbFree(pParse->db, aiMap);
+ sqlite3DbFree(pParse->db, zAff);
+}
+#endif /* SQLITE_OMIT_SUBQUERY */
+
+#ifndef SQLITE_OMIT_FLOATING_POINT
+/*
+** Generate an instruction that will put the floating point
+** value described by z[0..n-1] into register iMem.
+**
+** The z[] string will probably not be zero-terminated. But the
+** z[n] character is guaranteed to be something that does not look
+** like the continuation of the number.
+*/
+static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
+ if( ALWAYS(z!=0) ){
+ double value;
+ sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
+ assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
+ if( negateFlag ) value = -value;
+ sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
+ }
+}
+#endif
+
+
+/*
+** Generate an instruction that will put the integer describe by
+** text z[0..n-1] into register iMem.
+**
+** Expr.u.zToken is always UTF8 and zero-terminated.
+*/
+static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
+ Vdbe *v = pParse->pVdbe;
+ if( pExpr->flags & EP_IntValue ){
+ int i = pExpr->u.iValue;
+ assert( i>=0 );
+ if( negFlag ) i = -i;
+ sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
+ }else{
+ int c;
+ i64 value;
+ const char *z = pExpr->u.zToken;
+ assert( z!=0 );
+ c = sqlite3DecOrHexToI64(z, &value);
+ if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
+#ifdef SQLITE_OMIT_FLOATING_POINT
+ sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
+#else
+#ifndef SQLITE_OMIT_HEX_INTEGER
+ if( sqlite3_strnicmp(z,"0x",2)==0 ){
+ sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
+ }else
+#endif
+ {
+ codeReal(v, z, negFlag, iMem);
+ }
+#endif
+ }else{
+ if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
+ sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
+ }
+ }
+}
+
+
+/* Generate code that will load into register regOut a value that is
+** appropriate for the iIdxCol-th column of index pIdx.
+*/
+SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
+ Parse *pParse, /* The parsing context */
+ Index *pIdx, /* The index whose column is to be loaded */
+ int iTabCur, /* Cursor pointing to a table row */
+ int iIdxCol, /* The column of the index to be loaded */
+ int regOut /* Store the index column value in this register */
+){
+ i16 iTabCol = pIdx->aiColumn[iIdxCol];
+ if( iTabCol==XN_EXPR ){
+ assert( pIdx->aColExpr );
+ assert( pIdx->aColExpr->nExpr>iIdxCol );
+ pParse->iSelfTab = iTabCur + 1;
+ sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
+ pParse->iSelfTab = 0;
+ }else{
+ sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
+ iTabCol, regOut);
+ }
+}
+
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+/*
+** Generate code that will compute the value of generated column pCol
+** and store the result in register regOut
+*/
+SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(
+ Parse *pParse,
+ Column *pCol,
+ int regOut
+){
+ int iAddr;
+ Vdbe *v = pParse->pVdbe;
+ assert( v!=0 );
+ assert( pParse->iSelfTab!=0 );
+ if( pParse->iSelfTab>0 ){
+ iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
+ }else{
+ iAddr = 0;
+ }
+ sqlite3ExprCodeCopy(pParse, pCol->pDflt, regOut);
+ if( pCol->affinity>=SQLITE_AFF_TEXT ){
+ sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
+ }
+ if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
+}
+#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
+
+/*
+** Generate code to extract the value of the iCol-th column of a table.
+*/
+SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
+ Vdbe *v, /* Parsing context */
+ Table *pTab, /* The table containing the value */
+ int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
+ int iCol, /* Index of the column to extract */
+ int regOut /* Extract the value into this register */
+){
+ Column *pCol;
+ assert( v!=0 );
+ if( pTab==0 ){
+ sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
+ return;
+ }
+ if( iCol<0 || iCol==pTab->iPKey ){
+ sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
+ }else{
+ int op;
+ int x;
+ if( IsVirtual(pTab) ){
+ op = OP_VColumn;
+ x = iCol;
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
+ Parse *pParse = sqlite3VdbeParser(v);
+ if( pCol->colFlags & COLFLAG_BUSY ){
+ sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pCol->zName);
+ }else{
+ int savedSelfTab = pParse->iSelfTab;
+ pCol->colFlags |= COLFLAG_BUSY;
+ pParse->iSelfTab = iTabCur+1;
+ sqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut);
+ pParse->iSelfTab = savedSelfTab;
+ pCol->colFlags &= ~COLFLAG_BUSY;
+ }
+ return;
+#endif
+ }else if( !HasRowid(pTab) ){
+ testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
+ x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
+ op = OP_Column;
+ }else{
+ x = sqlite3TableColumnToStorage(pTab,iCol);
+ testcase( x!=iCol );
+ op = OP_Column;
+ }
+ sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
+ sqlite3ColumnDefault(v, pTab, iCol, regOut);
+ }
+}
+
+/*
+** Generate code that will extract the iColumn-th column from
+** table pTab and store the column value in register iReg.
+**
+** There must be an open cursor to pTab in iTable when this routine
+** is called. If iColumn<0 then code is generated that extracts the rowid.
+*/
+SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
+ Parse *pParse, /* Parsing and code generating context */
+ Table *pTab, /* Description of the table we are reading from */
+ int iColumn, /* Index of the table column */
+ int iTable, /* The cursor pointing to the table */
+ int iReg, /* Store results here */
+ u8 p5 /* P5 value for OP_Column + FLAGS */
+){
+ assert( pParse->pVdbe!=0 );
+ sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
+ if( p5 ){
+ VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1);
+ if( pOp->opcode==OP_Column ) pOp->p5 = p5;
+ }
+ return iReg;
+}
+
+/*
+** Generate code to move content from registers iFrom...iFrom+nReg-1
+** over to iTo..iTo+nReg-1.
+*/
+SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
+ sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
+}
+
+/*
+** Convert a scalar expression node to a TK_REGISTER referencing
+** register iReg. The caller must ensure that iReg already contains
+** the correct value for the expression.
+*/
+static void exprToRegister(Expr *pExpr, int iReg){
+ Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
+ p->op2 = p->op;
+ p->op = TK_REGISTER;
+ p->iTable = iReg;
+ ExprClearProperty(p, EP_Skip);
+}
+
+/*
+** Evaluate an expression (either a vector or a scalar expression) and store
+** the result in continguous temporary registers. Return the index of
+** the first register used to store the result.
+**
+** If the returned result register is a temporary scalar, then also write
+** that register number into *piFreeable. If the returned result register
+** is not a temporary or if the expression is a vector set *piFreeable
+** to 0.
+*/
+static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
+ int iResult;
+ int nResult = sqlite3ExprVectorSize(p);
+ if( nResult==1 ){
+ iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
+ }else{
+ *piFreeable = 0;
+ if( p->op==TK_SELECT ){
+#if SQLITE_OMIT_SUBQUERY
+ iResult = 0;
+#else
+ iResult = sqlite3CodeSubselect(pParse, p);
+#endif
+ }else{
+ int i;
+ iResult = pParse->nMem+1;
+ pParse->nMem += nResult;
+ for(i=0; i<nResult; i++){
+ sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
+ }
+ }
+ }
+ return iResult;
+}
+
+/*
+** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
+** so that a subsequent copy will not be merged into this one.
+*/
+static void setDoNotMergeFlagOnCopy(Vdbe *v){
+ if( sqlite3VdbeGetOp(v, -1)->opcode==OP_Copy ){
+ sqlite3VdbeChangeP5(v, 1); /* Tag trailing OP_Copy as not mergable */
+ }
+}
+
+/*
+** Generate code to implement special SQL functions that are implemented
+** in-line rather than by using the usual callbacks.
+*/
+static int exprCodeInlineFunction(
+ Parse *pParse, /* Parsing context */
+ ExprList *pFarg, /* List of function arguments */
+ int iFuncId, /* Function ID. One of the INTFUNC_... values */
+ int target /* Store function result in this register */
+){
+ int nFarg;
+ Vdbe *v = pParse->pVdbe;
+ assert( v!=0 );
+ assert( pFarg!=0 );
+ nFarg = pFarg->nExpr;
+ assert( nFarg>0 ); /* All in-line functions have at least one argument */
+ switch( iFuncId ){
+ case INLINEFUNC_coalesce: {
+ /* Attempt a direct implementation of the built-in COALESCE() and
+ ** IFNULL() functions. This avoids unnecessary evaluation of
+ ** arguments past the first non-NULL argument.
+ */
+ int endCoalesce = sqlite3VdbeMakeLabel(pParse);
+ int i;
+ assert( nFarg>=2 );
+ sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
+ for(i=1; i<nFarg; i++){
+ sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
+ VdbeCoverage(v);
+ sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
+ }
+ setDoNotMergeFlagOnCopy(v);
+ sqlite3VdbeResolveLabel(v, endCoalesce);
+ break;
+ }
+ case INLINEFUNC_iif: {
+ Expr caseExpr;
+ memset(&caseExpr, 0, sizeof(caseExpr));
+ caseExpr.op = TK_CASE;
+ caseExpr.x.pList = pFarg;
+ return sqlite3ExprCodeTarget(pParse, &caseExpr, target);
+ }
+
+ default: {
+ /* The UNLIKELY() function is a no-op. The result is the value
+ ** of the first argument.
+ */
+ assert( nFarg==1 || nFarg==2 );
+ target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
+ break;
+ }
+
+ /***********************************************************************
+ ** Test-only SQL functions that are only usable if enabled
+ ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
+ */
+ case INLINEFUNC_expr_compare: {
+ /* Compare two expressions using sqlite3ExprCompare() */
+ assert( nFarg==2 );
+ sqlite3VdbeAddOp2(v, OP_Integer,
+ sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
+ target);
+ break;
+ }
+
+ case INLINEFUNC_expr_implies_expr: {
+ /* Compare two expressions using sqlite3ExprImpliesExpr() */
+ assert( nFarg==2 );
+ sqlite3VdbeAddOp2(v, OP_Integer,
+ sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
+ target);
+ break;
+ }
+
+ case INLINEFUNC_implies_nonnull_row: {
+ /* REsult of sqlite3ExprImpliesNonNullRow() */
+ Expr *pA1;
+ assert( nFarg==2 );
+ pA1 = pFarg->a[1].pExpr;
+ if( pA1->op==TK_COLUMN ){
+ sqlite3VdbeAddOp2(v, OP_Integer,
+ sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable),
+ target);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Null, 0, target);
+ }
+ break;
+ }
+
+#ifdef SQLITE_DEBUG
+ case INLINEFUNC_affinity: {
+ /* The AFFINITY() function evaluates to a string that describes
+ ** the type affinity of the argument. This is used for testing of
+ ** the SQLite type logic.
+ */
+ const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
+ char aff;
+ assert( nFarg==1 );
+ aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
+ sqlite3VdbeLoadString(v, target,
+ (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
+ break;
+ }
+#endif
+ }
+ return target;
+}
+
+
+/*
+** Generate code into the current Vdbe to evaluate the given
+** expression. Attempt to store the results in register "target".
+** Return the register where results are stored.
+**
+** With this routine, there is no guarantee that results will
+** be stored in target. The result might be stored in some other
+** register if it is convenient to do so. The calling function
+** must check the return code and move the results to the desired
+** register.
+*/
+SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
+ Vdbe *v = pParse->pVdbe; /* The VM under construction */
+ int op; /* The opcode being coded */
+ int inReg = target; /* Results stored in register inReg */
+ int regFree1 = 0; /* If non-zero free this temporary register */
+ int regFree2 = 0; /* If non-zero free this temporary register */
+ int r1, r2; /* Various register numbers */
+ Expr tempX; /* Temporary expression node */
+ int p5 = 0;
+
+ assert( target>0 && target<=pParse->nMem );
+ assert( v!=0 );
+
+expr_code_doover:
+ if( pExpr==0 ){
+ op = TK_NULL;
+ }else{
+ assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
+ op = pExpr->op;
+ }
+ switch( op ){
+ case TK_AGG_COLUMN: {
+ AggInfo *pAggInfo = pExpr->pAggInfo;
+ struct AggInfo_col *pCol;
+ assert( pAggInfo!=0 );
+ assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
+ pCol = &pAggInfo->aCol[pExpr->iAgg];
+ if( !pAggInfo->directMode ){
+ assert( pCol->iMem>0 );
+ return pCol->iMem;
+ }else if( pAggInfo->useSortingIdx ){
+ Table *pTab = pCol->pTab;
+ sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
+ pCol->iSorterColumn, target);
+ if( pCol->iColumn<0 ){
+ VdbeComment((v,"%s.rowid",pTab->zName));
+ }else{
+ VdbeComment((v,"%s.%s",pTab->zName,pTab->aCol[pCol->iColumn].zName));
+ if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){
+ sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
+ }
+ }
+ return target;
+ }
+ /* Otherwise, fall thru into the TK_COLUMN case */
+ /* no break */ deliberate_fall_through
+ }
+ case TK_COLUMN: {
+ int iTab = pExpr->iTable;
+ int iReg;
+ if( ExprHasProperty(pExpr, EP_FixedCol) ){
+ /* This COLUMN expression is really a constant due to WHERE clause
+ ** constraints, and that constant is coded by the pExpr->pLeft
+ ** expresssion. However, make sure the constant has the correct
+ ** datatype by applying the Affinity of the table column to the
+ ** constant.
+ */
+ int aff;
+ iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
+ if( pExpr->y.pTab ){
+ aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
+ }else{
+ aff = pExpr->affExpr;
+ }
+ if( aff>SQLITE_AFF_BLOB ){
+ static const char zAff[] = "B\000C\000D\000E";
+ assert( SQLITE_AFF_BLOB=='A' );
+ assert( SQLITE_AFF_TEXT=='B' );
+ sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
+ &zAff[(aff-'B')*2], P4_STATIC);
+ }
+ return iReg;
+ }
+ if( iTab<0 ){
+ if( pParse->iSelfTab<0 ){
+ /* Other columns in the same row for CHECK constraints or
+ ** generated columns or for inserting into partial index.
+ ** The row is unpacked into registers beginning at
+ ** 0-(pParse->iSelfTab). The rowid (if any) is in a register
+ ** immediately prior to the first column.
+ */
+ Column *pCol;
+ Table *pTab = pExpr->y.pTab;
+ int iSrc;
+ int iCol = pExpr->iColumn;
+ assert( pTab!=0 );
+ assert( iCol>=XN_ROWID );
+ assert( iCol<pTab->nCol );
+ if( iCol<0 ){
+ return -1-pParse->iSelfTab;
+ }
+ pCol = pTab->aCol + iCol;
+ testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
+ iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ if( pCol->colFlags & COLFLAG_GENERATED ){
+ if( pCol->colFlags & COLFLAG_BUSY ){
+ sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
+ pCol->zName);
+ return 0;
+ }
+ pCol->colFlags |= COLFLAG_BUSY;
+ if( pCol->colFlags & COLFLAG_NOTAVAIL ){
+ sqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc);
+ }
+ pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
+ return iSrc;
+ }else
+#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
+ if( pCol->affinity==SQLITE_AFF_REAL ){
+ sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
+ sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
+ return target;
+ }else{
+ return iSrc;
+ }
+ }else{
+ /* Coding an expression that is part of an index where column names
+ ** in the index refer to the table to which the index belongs */
+ iTab = pParse->iSelfTab - 1;
+ }
+ }
+ iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
+ pExpr->iColumn, iTab, target,
+ pExpr->op2);
+ if( pExpr->y.pTab==0 && pExpr->affExpr==SQLITE_AFF_REAL ){
+ sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
+ }
+ return iReg;
+ }
+ case TK_INTEGER: {
+ codeInteger(pParse, pExpr, 0, target);
+ return target;
+ }
+ case TK_TRUEFALSE: {
+ sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
+ return target;
+ }
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ case TK_FLOAT: {
+ assert( !ExprHasProperty(pExpr, EP_IntValue) );
+ codeReal(v, pExpr->u.zToken, 0, target);
+ return target;
+ }
+#endif
+ case TK_STRING: {
+ assert( !ExprHasProperty(pExpr, EP_IntValue) );
+ sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
+ return target;
+ }
+ default: {
+ /* Make NULL the default case so that if a bug causes an illegal
+ ** Expr node to be passed into this function, it will be handled
+ ** sanely and not crash. But keep the assert() to bring the problem
+ ** to the attention of the developers. */
+ assert( op==TK_NULL );
+ sqlite3VdbeAddOp2(v, OP_Null, 0, target);
+ return target;
+ }
+#ifndef SQLITE_OMIT_BLOB_LITERAL
+ case TK_BLOB: {
+ int n;
+ const char *z;
+ char *zBlob;
+ assert( !ExprHasProperty(pExpr, EP_IntValue) );
+ assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
+ assert( pExpr->u.zToken[1]=='\'' );
+ z = &pExpr->u.zToken[2];
+ n = sqlite3Strlen30(z) - 1;
+ assert( z[n]=='\'' );
+ zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
+ sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
+ return target;
+ }
+#endif
+ case TK_VARIABLE: {
+ assert( !ExprHasProperty(pExpr, EP_IntValue) );
+ assert( pExpr->u.zToken!=0 );
+ assert( pExpr->u.zToken[0]!=0 );
+ sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
+ if( pExpr->u.zToken[1]!=0 ){
+ const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
+ assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) );
+ pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
+ sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
+ }
+ return target;
+ }
+ case TK_REGISTER: {
+ return pExpr->iTable;
+ }
+#ifndef SQLITE_OMIT_CAST
+ case TK_CAST: {
+ /* Expressions of the form: CAST(pLeft AS token) */
+ inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
+ if( inReg!=target ){
+ sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
+ inReg = target;
+ }
+ sqlite3VdbeAddOp2(v, OP_Cast, target,
+ sqlite3AffinityType(pExpr->u.zToken, 0));
+ return inReg;
+ }
+#endif /* SQLITE_OMIT_CAST */
+ case TK_IS:
+ case TK_ISNOT:
+ op = (op==TK_IS) ? TK_EQ : TK_NE;
+ p5 = SQLITE_NULLEQ;
+ /* fall-through */
+ case TK_LT:
+ case TK_LE:
+ case TK_GT:
+ case TK_GE:
+ case TK_NE:
+ case TK_EQ: {
+ Expr *pLeft = pExpr->pLeft;
+ if( sqlite3ExprIsVector(pLeft) ){
+ codeVectorCompare(pParse, pExpr, target, op, p5);
+ }else{
+ r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
+ r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
+ codeCompare(pParse, pLeft, pExpr->pRight, op,
+ r1, r2, inReg, SQLITE_STOREP2 | p5,
+ ExprHasProperty(pExpr,EP_Commuted));
+ assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
+ assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
+ assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
+ assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
+ assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
+ assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
+ testcase( regFree1==0 );
+ testcase( regFree2==0 );
+ }
+ break;
+ }
+ case TK_AND:
+ case TK_OR:
+ case TK_PLUS:
+ case TK_STAR:
+ case TK_MINUS:
+ case TK_REM:
+ case TK_BITAND:
+ case TK_BITOR:
+ case TK_SLASH:
+ case TK_LSHIFT:
+ case TK_RSHIFT:
+ case TK_CONCAT: {
+ assert( TK_AND==OP_And ); testcase( op==TK_AND );
+ assert( TK_OR==OP_Or ); testcase( op==TK_OR );
+ assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
+ assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
+ assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
+ assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
+ assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
+ assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
+ assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
+ assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
+ assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
+ r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
+ sqlite3VdbeAddOp3(v, op, r2, r1, target);
+ testcase( regFree1==0 );
+ testcase( regFree2==0 );
+ break;
+ }
+ case TK_UMINUS: {
+ Expr *pLeft = pExpr->pLeft;
+ assert( pLeft );
+ if( pLeft->op==TK_INTEGER ){
+ codeInteger(pParse, pLeft, 1, target);
+ return target;
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ }else if( pLeft->op==TK_FLOAT ){
+ assert( !ExprHasProperty(pExpr, EP_IntValue) );
+ codeReal(v, pLeft->u.zToken, 1, target);
+ return target;
+#endif
+ }else{
+ tempX.op = TK_INTEGER;
+ tempX.flags = EP_IntValue|EP_TokenOnly;
+ tempX.u.iValue = 0;
+ ExprClearVVAProperties(&tempX);
+ r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
+ r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
+ sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
+ testcase( regFree2==0 );
+ }
+ break;
+ }
+ case TK_BITNOT:
+ case TK_NOT: {
+ assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
+ assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
+ testcase( regFree1==0 );
+ sqlite3VdbeAddOp2(v, op, r1, inReg);
+ break;
+ }
+ case TK_TRUTH: {
+ int isTrue; /* IS TRUE or IS NOT TRUE */
+ int bNormal; /* IS TRUE or IS FALSE */
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
+ testcase( regFree1==0 );
+ isTrue = sqlite3ExprTruthValue(pExpr->pRight);
+ bNormal = pExpr->op2==TK_IS;
+ testcase( isTrue && bNormal);
+ testcase( !isTrue && bNormal);
+ sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
+ break;
+ }
+ case TK_ISNULL:
+ case TK_NOTNULL: {
+ int addr;
+ assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
+ assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
+ testcase( regFree1==0 );
+ addr = sqlite3VdbeAddOp1(v, op, r1);
+ VdbeCoverageIf(v, op==TK_ISNULL);
+ VdbeCoverageIf(v, op==TK_NOTNULL);
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
+ sqlite3VdbeJumpHere(v, addr);
+ break;
+ }
+ case TK_AGG_FUNCTION: {
+ AggInfo *pInfo = pExpr->pAggInfo;
+ if( pInfo==0
+ || NEVER(pExpr->iAgg<0)
+ || NEVER(pExpr->iAgg>=pInfo->nFunc)
+ ){
+ assert( !ExprHasProperty(pExpr, EP_IntValue) );
+ sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
+ }else{
+ return pInfo->aFunc[pExpr->iAgg].iMem;
+ }
+ break;
+ }
+ case TK_FUNCTION: {
+ ExprList *pFarg; /* List of function arguments */
+ int nFarg; /* Number of function arguments */
+ FuncDef *pDef; /* The function definition object */
+ const char *zId; /* The function name */
+ u32 constMask = 0; /* Mask of function arguments that are constant */
+ int i; /* Loop counter */
+ sqlite3 *db = pParse->db; /* The database connection */
+ u8 enc = ENC(db); /* The text encoding used by this database */
+ CollSeq *pColl = 0; /* A collating sequence */
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( ExprHasProperty(pExpr, EP_WinFunc) ){
+ return pExpr->y.pWin->regResult;
+ }
+#endif
+
+ if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
+ /* SQL functions can be expensive. So try to avoid running them
+ ** multiple times if we know they always give the same result */
+ return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
+ }
+ assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
+ assert( !ExprHasProperty(pExpr, EP_TokenOnly) );
+ pFarg = pExpr->x.pList;
+ nFarg = pFarg ? pFarg->nExpr : 0;
+ assert( !ExprHasProperty(pExpr, EP_IntValue) );
+ zId = pExpr->u.zToken;
+ pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
+#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
+ if( pDef==0 && pParse->explain ){
+ pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
+ }
+#endif
+ if( pDef==0 || pDef->xFinalize!=0 ){
+ sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
+ break;
+ }
+ if( pDef->funcFlags & SQLITE_FUNC_INLINE ){
+ assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
+ assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );
+ return exprCodeInlineFunction(pParse, pFarg,
+ SQLITE_PTR_TO_INT(pDef->pUserData), target);
+ }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){
+ sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
+ }
+
+ for(i=0; i<nFarg; i++){
+ if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
+ testcase( i==31 );
+ constMask |= MASKBIT32(i);
+ }
+ if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
+ pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
+ }
+ }
+ if( pFarg ){
+ if( constMask ){
+ r1 = pParse->nMem+1;
+ pParse->nMem += nFarg;
+ }else{
+ r1 = sqlite3GetTempRange(pParse, nFarg);
+ }
+
+ /* For length() and typeof() functions with a column argument,
+ ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
+ ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
+ ** loading.
+ */
+ if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
+ u8 exprOp;
+ assert( nFarg==1 );
+ assert( pFarg->a[0].pExpr!=0 );
+ exprOp = pFarg->a[0].pExpr->op;
+ if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
+ assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
+ assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
+ testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
+ pFarg->a[0].pExpr->op2 =
+ pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
+ }
+ }
+
+ sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
+ SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
+ }else{
+ r1 = 0;
+ }
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ /* Possibly overload the function if the first argument is
+ ** a virtual table column.
+ **
+ ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
+ ** second argument, not the first, as the argument to test to
+ ** see if it is a column in a virtual table. This is done because
+ ** the left operand of infix functions (the operand we want to
+ ** control overloading) ends up as the second argument to the
+ ** function. The expression "A glob B" is equivalent to
+ ** "glob(B,A). We want to use the A in "A glob B" to test
+ ** for function overloading. But we use the B term in "glob(B,A)".
+ */
+ if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
+ pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
+ }else if( nFarg>0 ){
+ pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
+ }
+#endif
+ if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
+ if( !pColl ) pColl = db->pDfltColl;
+ sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
+ }
+#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
+ if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
+ Expr *pArg = pFarg->a[0].pExpr;
+ if( pArg->op==TK_COLUMN ){
+ sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Null, 0, target);
+ }
+ }else
+#endif
+ {
+ sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
+ pDef, pExpr->op2);
+ }
+ if( nFarg ){
+ if( constMask==0 ){
+ sqlite3ReleaseTempRange(pParse, r1, nFarg);
+ }else{
+ sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1);
+ }
+ }
+ return target;
+ }
+#ifndef SQLITE_OMIT_SUBQUERY
+ case TK_EXISTS:
+ case TK_SELECT: {
+ int nCol;
+ testcase( op==TK_EXISTS );
+ testcase( op==TK_SELECT );
+ if( pParse->db->mallocFailed ){
+ return 0;
+ }else if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
+ sqlite3SubselectError(pParse, nCol, 1);
+ }else{
+ return sqlite3CodeSubselect(pParse, pExpr);
+ }
+ break;
+ }
+ case TK_SELECT_COLUMN: {
+ int n;
+ if( pExpr->pLeft->iTable==0 ){
+ pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);
+ }
+ assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
+ if( pExpr->iTable!=0
+ && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
+ ){
+ sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
+ pExpr->iTable, n);
+ }
+ return pExpr->pLeft->iTable + pExpr->iColumn;
+ }
+ case TK_IN: {
+ int destIfFalse = sqlite3VdbeMakeLabel(pParse);
+ int destIfNull = sqlite3VdbeMakeLabel(pParse);
+ sqlite3VdbeAddOp2(v, OP_Null, 0, target);
+ sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
+ sqlite3VdbeResolveLabel(v, destIfFalse);
+ sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
+ sqlite3VdbeResolveLabel(v, destIfNull);
+ return target;
+ }
+#endif /* SQLITE_OMIT_SUBQUERY */
+
+
+ /*
+ ** x BETWEEN y AND z
+ **
+ ** This is equivalent to
+ **
+ ** x>=y AND x<=z
+ **
+ ** X is stored in pExpr->pLeft.
+ ** Y is stored in pExpr->pList->a[0].pExpr.
+ ** Z is stored in pExpr->pList->a[1].pExpr.
+ */
+ case TK_BETWEEN: {
+ exprCodeBetween(pParse, pExpr, target, 0, 0);
+ return target;
+ }
+ case TK_SPAN:
+ case TK_COLLATE:
+ case TK_UPLUS: {
+ pExpr = pExpr->pLeft;
+ goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
+ }
+
+ case TK_TRIGGER: {
+ /* If the opcode is TK_TRIGGER, then the expression is a reference
+ ** to a column in the new.* or old.* pseudo-tables available to
+ ** trigger programs. In this case Expr.iTable is set to 1 for the
+ ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
+ ** is set to the column of the pseudo-table to read, or to -1 to
+ ** read the rowid field.
+ **
+ ** The expression is implemented using an OP_Param opcode. The p1
+ ** parameter is set to 0 for an old.rowid reference, or to (i+1)
+ ** to reference another column of the old.* pseudo-table, where
+ ** i is the index of the column. For a new.rowid reference, p1 is
+ ** set to (n+1), where n is the number of columns in each pseudo-table.
+ ** For a reference to any other column in the new.* pseudo-table, p1
+ ** is set to (n+2+i), where n and i are as defined previously. For
+ ** example, if the table on which triggers are being fired is
+ ** declared as:
+ **
+ ** CREATE TABLE t1(a, b);
+ **
+ ** Then p1 is interpreted as follows:
+ **
+ ** p1==0 -> old.rowid p1==3 -> new.rowid
+ ** p1==1 -> old.a p1==4 -> new.a
+ ** p1==2 -> old.b p1==5 -> new.b
+ */
+ Table *pTab = pExpr->y.pTab;
+ int iCol = pExpr->iColumn;
+ int p1 = pExpr->iTable * (pTab->nCol+1) + 1
+ + sqlite3TableColumnToStorage(pTab, iCol);
+
+ assert( pExpr->iTable==0 || pExpr->iTable==1 );
+ assert( iCol>=-1 && iCol<pTab->nCol );
+ assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
+ assert( p1>=0 && p1<(pTab->nCol*2+2) );
+
+ sqlite3VdbeAddOp2(v, OP_Param, p1, target);
+ VdbeComment((v, "r[%d]=%s.%s", target,
+ (pExpr->iTable ? "new" : "old"),
+ (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zName)
+ ));
+
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ /* If the column has REAL affinity, it may currently be stored as an
+ ** integer. Use OP_RealAffinity to make sure it is really real.
+ **
+ ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
+ ** floating point when extracting it from the record. */
+ if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
+ sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
+ }
+#endif
+ break;
+ }
+
+ case TK_VECTOR: {
+ sqlite3ErrorMsg(pParse, "row value misused");
+ break;
+ }
+
+ /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
+ ** that derive from the right-hand table of a LEFT JOIN. The
+ ** Expr.iTable value is the table number for the right-hand table.
+ ** The expression is only evaluated if that table is not currently
+ ** on a LEFT JOIN NULL row.
+ */
+ case TK_IF_NULL_ROW: {
+ int addrINR;
+ u8 okConstFactor = pParse->okConstFactor;
+ addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
+ /* Temporarily disable factoring of constant expressions, since
+ ** even though expressions may appear to be constant, they are not
+ ** really constant because they originate from the right-hand side
+ ** of a LEFT JOIN. */
+ pParse->okConstFactor = 0;
+ inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
+ pParse->okConstFactor = okConstFactor;
+ sqlite3VdbeJumpHere(v, addrINR);
+ sqlite3VdbeChangeP3(v, addrINR, inReg);
+ break;
+ }
+
+ /*
+ ** Form A:
+ ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
+ **
+ ** Form B:
+ ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
+ **
+ ** Form A is can be transformed into the equivalent form B as follows:
+ ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
+ ** WHEN x=eN THEN rN ELSE y END
+ **
+ ** X (if it exists) is in pExpr->pLeft.
+ ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
+ ** odd. The Y is also optional. If the number of elements in x.pList
+ ** is even, then Y is omitted and the "otherwise" result is NULL.
+ ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
+ **
+ ** The result of the expression is the Ri for the first matching Ei,
+ ** or if there is no matching Ei, the ELSE term Y, or if there is
+ ** no ELSE term, NULL.
+ */
+ case TK_CASE: {
+ int endLabel; /* GOTO label for end of CASE stmt */
+ int nextCase; /* GOTO label for next WHEN clause */
+ int nExpr; /* 2x number of WHEN terms */
+ int i; /* Loop counter */
+ ExprList *pEList; /* List of WHEN terms */
+ struct ExprList_item *aListelem; /* Array of WHEN terms */
+ Expr opCompare; /* The X==Ei expression */
+ Expr *pX; /* The X expression */
+ Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
+ Expr *pDel = 0;
+ sqlite3 *db = pParse->db;
+
+ assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
+ assert(pExpr->x.pList->nExpr > 0);
+ pEList = pExpr->x.pList;
+ aListelem = pEList->a;
+ nExpr = pEList->nExpr;
+ endLabel = sqlite3VdbeMakeLabel(pParse);
+ if( (pX = pExpr->pLeft)!=0 ){
+ pDel = sqlite3ExprDup(db, pX, 0);
+ if( db->mallocFailed ){
+ sqlite3ExprDelete(db, pDel);
+ break;
+ }
+ testcase( pX->op==TK_COLUMN );
+ exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
+ testcase( regFree1==0 );
+ memset(&opCompare, 0, sizeof(opCompare));
+ opCompare.op = TK_EQ;
+ opCompare.pLeft = pDel;
+ pTest = &opCompare;
+ /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
+ ** The value in regFree1 might get SCopy-ed into the file result.
+ ** So make sure that the regFree1 register is not reused for other
+ ** purposes and possibly overwritten. */
+ regFree1 = 0;
+ }
+ for(i=0; i<nExpr-1; i=i+2){
+ if( pX ){
+ assert( pTest!=0 );
+ opCompare.pRight = aListelem[i].pExpr;
+ }else{
+ pTest = aListelem[i].pExpr;
+ }
+ nextCase = sqlite3VdbeMakeLabel(pParse);
+ testcase( pTest->op==TK_COLUMN );
+ sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
+ testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
+ sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
+ sqlite3VdbeGoto(v, endLabel);
+ sqlite3VdbeResolveLabel(v, nextCase);
+ }
+ if( (nExpr&1)!=0 ){
+ sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Null, 0, target);
+ }
+ sqlite3ExprDelete(db, pDel);
+ setDoNotMergeFlagOnCopy(v);
+ sqlite3VdbeResolveLabel(v, endLabel);
+ break;
+ }
+#ifndef SQLITE_OMIT_TRIGGER
+ case TK_RAISE: {
+ assert( pExpr->affExpr==OE_Rollback
+ || pExpr->affExpr==OE_Abort
+ || pExpr->affExpr==OE_Fail
+ || pExpr->affExpr==OE_Ignore
+ );
+ if( !pParse->pTriggerTab && !pParse->nested ){
+ sqlite3ErrorMsg(pParse,
+ "RAISE() may only be used within a trigger-program");
+ return 0;
+ }
+ if( pExpr->affExpr==OE_Abort ){
+ sqlite3MayAbort(pParse);
+ }
+ assert( !ExprHasProperty(pExpr, EP_IntValue) );
+ if( pExpr->affExpr==OE_Ignore ){
+ sqlite3VdbeAddOp4(
+ v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
+ VdbeCoverage(v);
+ }else{
+ sqlite3HaltConstraint(pParse,
+ pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
+ pExpr->affExpr, pExpr->u.zToken, 0, 0);
+ }
+
+ break;
+ }
+#endif
+ }
+ sqlite3ReleaseTempReg(pParse, regFree1);
+ sqlite3ReleaseTempReg(pParse, regFree2);
+ return inReg;
+}
+
+/*
+** Generate code that will evaluate expression pExpr just one time
+** per prepared statement execution.
+**
+** If the expression uses functions (that might throw an exception) then
+** guard them with an OP_Once opcode to ensure that the code is only executed
+** once. If no functions are involved, then factor the code out and put it at
+** the end of the prepared statement in the initialization section.
+**
+** If regDest>=0 then the result is always stored in that register and the
+** result is not reusable. If regDest<0 then this routine is free to
+** store the value whereever it wants. The register where the expression
+** is stored is returned. When regDest<0, two identical expressions might
+** code to the same register, if they do not contain function calls and hence
+** are factored out into the initialization section at the end of the
+** prepared statement.
+*/
+SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(
+ Parse *pParse, /* Parsing context */
+ Expr *pExpr, /* The expression to code when the VDBE initializes */
+ int regDest /* Store the value in this register */
+){
+ ExprList *p;
+ assert( ConstFactorOk(pParse) );
+ p = pParse->pConstExpr;
+ if( regDest<0 && p ){
+ struct ExprList_item *pItem;
+ int i;
+ for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
+ if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
+ return pItem->u.iConstExprReg;
+ }
+ }
+ }
+ pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
+ if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){
+ Vdbe *v = pParse->pVdbe;
+ int addr;
+ assert( v );
+ addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
+ pParse->okConstFactor = 0;
+ if( !pParse->db->mallocFailed ){
+ if( regDest<0 ) regDest = ++pParse->nMem;
+ sqlite3ExprCode(pParse, pExpr, regDest);
+ }
+ pParse->okConstFactor = 1;
+ sqlite3ExprDelete(pParse->db, pExpr);
+ sqlite3VdbeJumpHere(v, addr);
+ }else{
+ p = sqlite3ExprListAppend(pParse, p, pExpr);
+ if( p ){
+ struct ExprList_item *pItem = &p->a[p->nExpr-1];
+ pItem->reusable = regDest<0;
+ if( regDest<0 ) regDest = ++pParse->nMem;
+ pItem->u.iConstExprReg = regDest;
+ }
+ pParse->pConstExpr = p;
+ }
+ return regDest;
+}
+
+/*
+** Generate code to evaluate an expression and store the results
+** into a register. Return the register number where the results
+** are stored.
+**
+** If the register is a temporary register that can be deallocated,
+** then write its number into *pReg. If the result register is not
+** a temporary, then set *pReg to zero.
+**
+** If pExpr is a constant, then this routine might generate this
+** code to fill the register in the initialization section of the
+** VDBE program, in order to factor it out of the evaluation loop.
+*/
+SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
+ int r2;
+ pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
+ if( ConstFactorOk(pParse)
+ && pExpr->op!=TK_REGISTER
+ && sqlite3ExprIsConstantNotJoin(pExpr)
+ ){
+ *pReg = 0;
+ r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
+ }else{
+ int r1 = sqlite3GetTempReg(pParse);
+ r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
+ if( r2==r1 ){
+ *pReg = r1;
+ }else{
+ sqlite3ReleaseTempReg(pParse, r1);
+ *pReg = 0;
+ }
+ }
+ return r2;
+}
+
+/*
+** Generate code that will evaluate expression pExpr and store the
+** results in register target. The results are guaranteed to appear
+** in register target.
+*/
+SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
+ int inReg;
+
+ assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) );
+ assert( target>0 && target<=pParse->nMem );
+ assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
+ if( pParse->pVdbe==0 ) return;
+ inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
+ if( inReg!=target ){
+ u8 op;
+ if( ExprHasProperty(pExpr,EP_Subquery) ){
+ op = OP_Copy;
+ }else{
+ op = OP_SCopy;
+ }
+ sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
+ }
+}
+
+/*
+** Make a transient copy of expression pExpr and then code it using
+** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
+** except that the input expression is guaranteed to be unchanged.
+*/
+SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
+ sqlite3 *db = pParse->db;
+ pExpr = sqlite3ExprDup(db, pExpr, 0);
+ if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
+ sqlite3ExprDelete(db, pExpr);
+}
+
+/*
+** Generate code that will evaluate expression pExpr and store the
+** results in register target. The results are guaranteed to appear
+** in register target. If the expression is constant, then this routine
+** might choose to code the expression at initialization time.
+*/
+SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
+ if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
+ sqlite3ExprCodeRunJustOnce(pParse, pExpr, target);
+ }else{
+ sqlite3ExprCodeCopy(pParse, pExpr, target);
+ }
+}
+
+/*
+** Generate code that pushes the value of every element of the given
+** expression list into a sequence of registers beginning at target.
+**
+** Return the number of elements evaluated. The number returned will
+** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
+** is defined.
+**
+** The SQLITE_ECEL_DUP flag prevents the arguments from being
+** filled using OP_SCopy. OP_Copy must be used instead.
+**
+** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
+** factored out into initialization code.
+**
+** The SQLITE_ECEL_REF flag means that expressions in the list with
+** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
+** in registers at srcReg, and so the value can be copied from there.
+** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
+** are simply omitted rather than being copied from srcReg.
+*/
+SQLITE_PRIVATE int sqlite3ExprCodeExprList(
+ Parse *pParse, /* Parsing context */
+ ExprList *pList, /* The expression list to be coded */
+ int target, /* Where to write results */
+ int srcReg, /* Source registers if SQLITE_ECEL_REF */
+ u8 flags /* SQLITE_ECEL_* flags */
+){
+ struct ExprList_item *pItem;
+ int i, j, n;
+ u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
+ Vdbe *v = pParse->pVdbe;
+ assert( pList!=0 );
+ assert( target>0 );
+ assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
+ n = pList->nExpr;
+ if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
+ for(pItem=pList->a, i=0; i<n; i++, pItem++){
+ Expr *pExpr = pItem->pExpr;
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ if( pItem->bSorterRef ){
+ i--;
+ n--;
+ }else
+#endif
+ if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
+ if( flags & SQLITE_ECEL_OMITREF ){
+ i--;
+ n--;
+ }else{
+ sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
+ }
+ }else if( (flags & SQLITE_ECEL_FACTOR)!=0
+ && sqlite3ExprIsConstantNotJoin(pExpr)
+ ){
+ sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i);
+ }else{
+ int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
+ if( inReg!=target+i ){
+ VdbeOp *pOp;
+ if( copyOp==OP_Copy
+ && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
+ && pOp->p1+pOp->p3+1==inReg
+ && pOp->p2+pOp->p3+1==target+i
+ && pOp->p5==0 /* The do-not-merge flag must be clear */
+ ){
+ pOp->p3++;
+ }else{
+ sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
+ }
+ }
+ }
+ }
+ return n;
+}
+
+/*
+** Generate code for a BETWEEN operator.
+**
+** x BETWEEN y AND z
+**
+** The above is equivalent to
+**
+** x>=y AND x<=z
+**
+** Code it as such, taking care to do the common subexpression
+** elimination of x.
+**
+** The xJumpIf parameter determines details:
+**
+** NULL: Store the boolean result in reg[dest]
+** sqlite3ExprIfTrue: Jump to dest if true
+** sqlite3ExprIfFalse: Jump to dest if false
+**
+** The jumpIfNull parameter is ignored if xJumpIf is NULL.
+*/
+static void exprCodeBetween(
+ Parse *pParse, /* Parsing and code generating context */
+ Expr *pExpr, /* The BETWEEN expression */
+ int dest, /* Jump destination or storage location */
+ void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
+ int jumpIfNull /* Take the jump if the BETWEEN is NULL */
+){
+ Expr exprAnd; /* The AND operator in x>=y AND x<=z */
+ Expr compLeft; /* The x>=y term */
+ Expr compRight; /* The x<=z term */
+ int regFree1 = 0; /* Temporary use register */
+ Expr *pDel = 0;
+ sqlite3 *db = pParse->db;
+
+ memset(&compLeft, 0, sizeof(Expr));
+ memset(&compRight, 0, sizeof(Expr));
+ memset(&exprAnd, 0, sizeof(Expr));
+
+ assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
+ pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
+ if( db->mallocFailed==0 ){
+ exprAnd.op = TK_AND;
+ exprAnd.pLeft = &compLeft;
+ exprAnd.pRight = &compRight;
+ compLeft.op = TK_GE;
+ compLeft.pLeft = pDel;
+ compLeft.pRight = pExpr->x.pList->a[0].pExpr;
+ compRight.op = TK_LE;
+ compRight.pLeft = pDel;
+ compRight.pRight = pExpr->x.pList->a[1].pExpr;
+ exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
+ if( xJump ){
+ xJump(pParse, &exprAnd, dest, jumpIfNull);
+ }else{
+ /* Mark the expression is being from the ON or USING clause of a join
+ ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
+ ** it into the Parse.pConstExpr list. We should use a new bit for this,
+ ** for clarity, but we are out of bits in the Expr.flags field so we
+ ** have to reuse the EP_FromJoin bit. Bummer. */
+ pDel->flags |= EP_FromJoin;
+ sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
+ }
+ sqlite3ReleaseTempReg(pParse, regFree1);
+ }
+ sqlite3ExprDelete(db, pDel);
+
+ /* Ensure adequate test coverage */
+ testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
+ testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
+ testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
+ testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
+ testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
+ testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
+ testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
+ testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
+ testcase( xJump==0 );
+}
+
+/*
+** Generate code for a boolean expression such that a jump is made
+** to the label "dest" if the expression is true but execution
+** continues straight thru if the expression is false.
+**
+** If the expression evaluates to NULL (neither true nor false), then
+** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
+**
+** This code depends on the fact that certain token values (ex: TK_EQ)
+** are the same as opcode values (ex: OP_Eq) that implement the corresponding
+** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
+** the make process cause these values to align. Assert()s in the code
+** below verify that the numbers are aligned correctly.
+*/
+SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
+ Vdbe *v = pParse->pVdbe;
+ int op = 0;
+ int regFree1 = 0;
+ int regFree2 = 0;
+ int r1, r2;
+
+ assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
+ if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
+ if( NEVER(pExpr==0) ) return; /* No way this can happen */
+ assert( !ExprHasVVAProperty(pExpr, EP_Immutable) );
+ op = pExpr->op;
+ switch( op ){
+ case TK_AND:
+ case TK_OR: {
+ Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
+ if( pAlt!=pExpr ){
+ sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
+ }else if( op==TK_AND ){
+ int d2 = sqlite3VdbeMakeLabel(pParse);
+ testcase( jumpIfNull==0 );
+ sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
+ jumpIfNull^SQLITE_JUMPIFNULL);
+ sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
+ sqlite3VdbeResolveLabel(v, d2);
+ }else{
+ testcase( jumpIfNull==0 );
+ sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
+ sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
+ }
+ break;
+ }
+ case TK_NOT: {
+ testcase( jumpIfNull==0 );
+ sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
+ break;
+ }
+ case TK_TRUTH: {
+ int isNot; /* IS NOT TRUE or IS NOT FALSE */
+ int isTrue; /* IS TRUE or IS NOT TRUE */
+ testcase( jumpIfNull==0 );
+ isNot = pExpr->op2==TK_ISNOT;
+ isTrue = sqlite3ExprTruthValue(pExpr->pRight);
+ testcase( isTrue && isNot );
+ testcase( !isTrue && isNot );
+ if( isTrue ^ isNot ){
+ sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
+ isNot ? SQLITE_JUMPIFNULL : 0);
+ }else{
+ sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
+ isNot ? SQLITE_JUMPIFNULL : 0);
+ }
+ break;
+ }
+ case TK_IS:
+ case TK_ISNOT:
+ testcase( op==TK_IS );
+ testcase( op==TK_ISNOT );
+ op = (op==TK_IS) ? TK_EQ : TK_NE;
+ jumpIfNull = SQLITE_NULLEQ;
+ /* no break */ deliberate_fall_through
+ case TK_LT:
+ case TK_LE:
+ case TK_GT:
+ case TK_GE:
+ case TK_NE:
+ case TK_EQ: {
+ if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
+ testcase( jumpIfNull==0 );
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
+ r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
+ codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
+ r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
+ assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
+ assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
+ assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
+ assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
+ assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
+ VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
+ VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
+ assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
+ VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
+ VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
+ testcase( regFree1==0 );
+ testcase( regFree2==0 );
+ break;
+ }
+ case TK_ISNULL:
+ case TK_NOTNULL: {
+ assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
+ assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
+ sqlite3VdbeAddOp2(v, op, r1, dest);
+ VdbeCoverageIf(v, op==TK_ISNULL);
+ VdbeCoverageIf(v, op==TK_NOTNULL);
+ testcase( regFree1==0 );
+ break;
+ }
+ case TK_BETWEEN: {
+ testcase( jumpIfNull==0 );
+ exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
+ break;
+ }
+#ifndef SQLITE_OMIT_SUBQUERY
+ case TK_IN: {
+ int destIfFalse = sqlite3VdbeMakeLabel(pParse);
+ int destIfNull = jumpIfNull ? dest : destIfFalse;
+ sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
+ sqlite3VdbeGoto(v, dest);
+ sqlite3VdbeResolveLabel(v, destIfFalse);
+ break;
+ }
+#endif
+ default: {
+ default_expr:
+ if( ExprAlwaysTrue(pExpr) ){
+ sqlite3VdbeGoto(v, dest);
+ }else if( ExprAlwaysFalse(pExpr) ){
+ /* No-op */
+ }else{
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
+ sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
+ VdbeCoverage(v);
+ testcase( regFree1==0 );
+ testcase( jumpIfNull==0 );
+ }
+ break;
+ }
+ }
+ sqlite3ReleaseTempReg(pParse, regFree1);
+ sqlite3ReleaseTempReg(pParse, regFree2);
+}
+
+/*
+** Generate code for a boolean expression such that a jump is made
+** to the label "dest" if the expression is false but execution
+** continues straight thru if the expression is true.
+**
+** If the expression evaluates to NULL (neither true nor false) then
+** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
+** is 0.
+*/
+SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
+ Vdbe *v = pParse->pVdbe;
+ int op = 0;
+ int regFree1 = 0;
+ int regFree2 = 0;
+ int r1, r2;
+
+ assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
+ if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
+ if( pExpr==0 ) return;
+ assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
+
+ /* The value of pExpr->op and op are related as follows:
+ **
+ ** pExpr->op op
+ ** --------- ----------
+ ** TK_ISNULL OP_NotNull
+ ** TK_NOTNULL OP_IsNull
+ ** TK_NE OP_Eq
+ ** TK_EQ OP_Ne
+ ** TK_GT OP_Le
+ ** TK_LE OP_Gt
+ ** TK_GE OP_Lt
+ ** TK_LT OP_Ge
+ **
+ ** For other values of pExpr->op, op is undefined and unused.
+ ** The value of TK_ and OP_ constants are arranged such that we
+ ** can compute the mapping above using the following expression.
+ ** Assert()s verify that the computation is correct.
+ */
+ op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
+
+ /* Verify correct alignment of TK_ and OP_ constants
+ */
+ assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
+ assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
+ assert( pExpr->op!=TK_NE || op==OP_Eq );
+ assert( pExpr->op!=TK_EQ || op==OP_Ne );
+ assert( pExpr->op!=TK_LT || op==OP_Ge );
+ assert( pExpr->op!=TK_LE || op==OP_Gt );
+ assert( pExpr->op!=TK_GT || op==OP_Le );
+ assert( pExpr->op!=TK_GE || op==OP_Lt );
+
+ switch( pExpr->op ){
+ case TK_AND:
+ case TK_OR: {
+ Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
+ if( pAlt!=pExpr ){
+ sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
+ }else if( pExpr->op==TK_AND ){
+ testcase( jumpIfNull==0 );
+ sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
+ sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
+ }else{
+ int d2 = sqlite3VdbeMakeLabel(pParse);
+ testcase( jumpIfNull==0 );
+ sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
+ jumpIfNull^SQLITE_JUMPIFNULL);
+ sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
+ sqlite3VdbeResolveLabel(v, d2);
+ }
+ break;
+ }
+ case TK_NOT: {
+ testcase( jumpIfNull==0 );
+ sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
+ break;
+ }
+ case TK_TRUTH: {
+ int isNot; /* IS NOT TRUE or IS NOT FALSE */
+ int isTrue; /* IS TRUE or IS NOT TRUE */
+ testcase( jumpIfNull==0 );
+ isNot = pExpr->op2==TK_ISNOT;
+ isTrue = sqlite3ExprTruthValue(pExpr->pRight);
+ testcase( isTrue && isNot );
+ testcase( !isTrue && isNot );
+ if( isTrue ^ isNot ){
+ /* IS TRUE and IS NOT FALSE */
+ sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
+ isNot ? 0 : SQLITE_JUMPIFNULL);
+
+ }else{
+ /* IS FALSE and IS NOT TRUE */
+ sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
+ isNot ? 0 : SQLITE_JUMPIFNULL);
+ }
+ break;
+ }
+ case TK_IS:
+ case TK_ISNOT:
+ testcase( pExpr->op==TK_IS );
+ testcase( pExpr->op==TK_ISNOT );
+ op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
+ jumpIfNull = SQLITE_NULLEQ;
+ /* no break */ deliberate_fall_through
+ case TK_LT:
+ case TK_LE:
+ case TK_GT:
+ case TK_GE:
+ case TK_NE:
+ case TK_EQ: {
+ if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
+ testcase( jumpIfNull==0 );
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
+ r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
+ codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
+ r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
+ assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
+ assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
+ assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
+ assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
+ assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
+ VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
+ VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
+ assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
+ VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
+ VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
+ testcase( regFree1==0 );
+ testcase( regFree2==0 );
+ break;
+ }
+ case TK_ISNULL:
+ case TK_NOTNULL: {
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
+ sqlite3VdbeAddOp2(v, op, r1, dest);
+ testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
+ testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
+ testcase( regFree1==0 );
+ break;
+ }
+ case TK_BETWEEN: {
+ testcase( jumpIfNull==0 );
+ exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
+ break;
+ }
+#ifndef SQLITE_OMIT_SUBQUERY
+ case TK_IN: {
+ if( jumpIfNull ){
+ sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
+ }else{
+ int destIfNull = sqlite3VdbeMakeLabel(pParse);
+ sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
+ sqlite3VdbeResolveLabel(v, destIfNull);
+ }
+ break;
+ }
+#endif
+ default: {
+ default_expr:
+ if( ExprAlwaysFalse(pExpr) ){
+ sqlite3VdbeGoto(v, dest);
+ }else if( ExprAlwaysTrue(pExpr) ){
+ /* no-op */
+ }else{
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
+ sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
+ VdbeCoverage(v);
+ testcase( regFree1==0 );
+ testcase( jumpIfNull==0 );
+ }
+ break;
+ }
+ }
+ sqlite3ReleaseTempReg(pParse, regFree1);
+ sqlite3ReleaseTempReg(pParse, regFree2);
+}
+
+/*
+** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
+** code generation, and that copy is deleted after code generation. This
+** ensures that the original pExpr is unchanged.
+*/
+SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
+ sqlite3 *db = pParse->db;
+ Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
+ if( db->mallocFailed==0 ){
+ sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
+ }
+ sqlite3ExprDelete(db, pCopy);
+}
+
+/*
+** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
+** type of expression.
+**
+** If pExpr is a simple SQL value - an integer, real, string, blob
+** or NULL value - then the VDBE currently being prepared is configured
+** to re-prepare each time a new value is bound to variable pVar.
+**
+** Additionally, if pExpr is a simple SQL value and the value is the
+** same as that currently bound to variable pVar, non-zero is returned.
+** Otherwise, if the values are not the same or if pExpr is not a simple
+** SQL value, zero is returned.
+*/
+static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
+ int res = 0;
+ int iVar;
+ sqlite3_value *pL, *pR = 0;
+
+ sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
+ if( pR ){
+ iVar = pVar->iColumn;
+ sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
+ pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
+ if( pL ){
+ if( sqlite3_value_type(pL)==SQLITE_TEXT ){
+ sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
+ }
+ res = 0==sqlite3MemCompare(pL, pR, 0);
+ }
+ sqlite3ValueFree(pR);
+ sqlite3ValueFree(pL);
+ }
+
+ return res;
+}
+
+/*
+** Do a deep comparison of two expression trees. Return 0 if the two
+** expressions are completely identical. Return 1 if they differ only
+** by a COLLATE operator at the top level. Return 2 if there are differences
+** other than the top-level COLLATE operator.
+**
+** If any subelement of pB has Expr.iTable==(-1) then it is allowed
+** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
+**
+** The pA side might be using TK_REGISTER. If that is the case and pB is
+** not using TK_REGISTER but is otherwise equivalent, then still return 0.
+**
+** Sometimes this routine will return 2 even if the two expressions
+** really are equivalent. If we cannot prove that the expressions are
+** identical, we return 2 just to be safe. So if this routine
+** returns 2, then you do not really know for certain if the two
+** expressions are the same. But if you get a 0 or 1 return, then you
+** can be sure the expressions are the same. In the places where
+** this routine is used, it does not hurt to get an extra 2 - that
+** just might result in some slightly slower code. But returning
+** an incorrect 0 or 1 could lead to a malfunction.
+**
+** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
+** pParse->pReprepare can be matched against literals in pB. The
+** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
+** If pParse is NULL (the normal case) then any TK_VARIABLE term in
+** Argument pParse should normally be NULL. If it is not NULL and pA or
+** pB causes a return value of 2.
+*/
+SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
+ u32 combinedFlags;
+ if( pA==0 || pB==0 ){
+ return pB==pA ? 0 : 2;
+ }
+ if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
+ return 0;
+ }
+ combinedFlags = pA->flags | pB->flags;
+ if( combinedFlags & EP_IntValue ){
+ if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
+ return 0;
+ }
+ return 2;
+ }
+ if( pA->op!=pB->op || pA->op==TK_RAISE ){
+ if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
+ return 1;
+ }
+ if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
+ return 1;
+ }
+ return 2;
+ }
+ if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
+ if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
+ if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ assert( pA->op==pB->op );
+ if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
+ return 2;
+ }
+ if( ExprHasProperty(pA,EP_WinFunc) ){
+ if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
+ return 2;
+ }
+ }
+#endif
+ }else if( pA->op==TK_NULL ){
+ return 0;
+ }else if( pA->op==TK_COLLATE ){
+ if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
+ }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
+ return 2;
+ }
+ }
+ if( (pA->flags & (EP_Distinct|EP_Commuted))
+ != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
+ if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
+ if( combinedFlags & EP_xIsSelect ) return 2;
+ if( (combinedFlags & EP_FixedCol)==0
+ && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
+ if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
+ if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
+ if( pA->op!=TK_STRING
+ && pA->op!=TK_TRUEFALSE
+ && ALWAYS((combinedFlags & EP_Reduced)==0)
+ ){
+ if( pA->iColumn!=pB->iColumn ) return 2;
+ if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2;
+ if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
+ return 2;
+ }
+ }
+ }
+ return 0;
+}
+
+/*
+** Compare two ExprList objects. Return 0 if they are identical, 1
+** if they are certainly different, or 2 if it is not possible to
+** determine if they are identical or not.
+**
+** If any subelement of pB has Expr.iTable==(-1) then it is allowed
+** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
+**
+** This routine might return non-zero for equivalent ExprLists. The
+** only consequence will be disabled optimizations. But this routine
+** must never return 0 if the two ExprList objects are different, or
+** a malfunction will result.
+**
+** Two NULL pointers are considered to be the same. But a NULL pointer
+** always differs from a non-NULL pointer.
+*/
+SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
+ int i;
+ if( pA==0 && pB==0 ) return 0;
+ if( pA==0 || pB==0 ) return 1;
+ if( pA->nExpr!=pB->nExpr ) return 1;
+ for(i=0; i<pA->nExpr; i++){
+ int res;
+ Expr *pExprA = pA->a[i].pExpr;
+ Expr *pExprB = pB->a[i].pExpr;
+ if( pA->a[i].sortFlags!=pB->a[i].sortFlags ) return 1;
+ if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res;
+ }
+ return 0;
+}
+
+/*
+** Like sqlite3ExprCompare() except COLLATE operators at the top-level
+** are ignored.
+*/
+SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
+ return sqlite3ExprCompare(0,
+ sqlite3ExprSkipCollateAndLikely(pA),
+ sqlite3ExprSkipCollateAndLikely(pB),
+ iTab);
+}
+
+/*
+** Return non-zero if Expr p can only be true if pNN is not NULL.
+**
+** Or if seenNot is true, return non-zero if Expr p can only be
+** non-NULL if pNN is not NULL
+*/
+static int exprImpliesNotNull(
+ Parse *pParse, /* Parsing context */
+ Expr *p, /* The expression to be checked */
+ Expr *pNN, /* The expression that is NOT NULL */
+ int iTab, /* Table being evaluated */
+ int seenNot /* Return true only if p can be any non-NULL value */
+){
+ assert( p );
+ assert( pNN );
+ if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
+ return pNN->op!=TK_NULL;
+ }
+ switch( p->op ){
+ case TK_IN: {
+ if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
+ assert( ExprHasProperty(p,EP_xIsSelect)
+ || (p->x.pList!=0 && p->x.pList->nExpr>0) );
+ return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
+ }
+ case TK_BETWEEN: {
+ ExprList *pList = p->x.pList;
+ assert( pList!=0 );
+ assert( pList->nExpr==2 );
+ if( seenNot ) return 0;
+ if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
+ || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
+ ){
+ return 1;
+ }
+ return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
+ }
+ case TK_EQ:
+ case TK_NE:
+ case TK_LT:
+ case TK_LE:
+ case TK_GT:
+ case TK_GE:
+ case TK_PLUS:
+ case TK_MINUS:
+ case TK_BITOR:
+ case TK_LSHIFT:
+ case TK_RSHIFT:
+ case TK_CONCAT:
+ seenNot = 1;
+ /* no break */ deliberate_fall_through
+ case TK_STAR:
+ case TK_REM:
+ case TK_BITAND:
+ case TK_SLASH: {
+ if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
+ /* no break */ deliberate_fall_through
+ }
+ case TK_SPAN:
+ case TK_COLLATE:
+ case TK_UPLUS:
+ case TK_UMINUS: {
+ return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
+ }
+ case TK_TRUTH: {
+ if( seenNot ) return 0;
+ if( p->op2!=TK_IS ) return 0;
+ return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
+ }
+ case TK_BITNOT:
+ case TK_NOT: {
+ return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
+ }
+ }
+ return 0;
+}
+
+/*
+** Return true if we can prove the pE2 will always be true if pE1 is
+** true. Return false if we cannot complete the proof or if pE2 might
+** be false. Examples:
+**
+** pE1: x==5 pE2: x==5 Result: true
+** pE1: x>0 pE2: x==5 Result: false
+** pE1: x=21 pE2: x=21 OR y=43 Result: true
+** pE1: x!=123 pE2: x IS NOT NULL Result: true
+** pE1: x!=?1 pE2: x IS NOT NULL Result: true
+** pE1: x IS NULL pE2: x IS NOT NULL Result: false
+** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
+**
+** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
+** Expr.iTable<0 then assume a table number given by iTab.
+**
+** If pParse is not NULL, then the values of bound variables in pE1 are
+** compared against literal values in pE2 and pParse->pVdbe->expmask is
+** modified to record which bound variables are referenced. If pParse
+** is NULL, then false will be returned if pE1 contains any bound variables.
+**
+** When in doubt, return false. Returning true might give a performance
+** improvement. Returning false might cause a performance reduction, but
+** it will always give the correct answer and is hence always safe.
+*/
+SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
+ if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
+ return 1;
+ }
+ if( pE2->op==TK_OR
+ && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
+ || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
+ ){
+ return 1;
+ }
+ if( pE2->op==TK_NOTNULL
+ && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
+ ){
+ return 1;
+ }
+ return 0;
+}
+
+/*
+** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
+** If the expression node requires that the table at pWalker->iCur
+** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
+**
+** This routine controls an optimization. False positives (setting
+** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
+** (never setting pWalker->eCode) is a harmless missed optimization.
+*/
+static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
+ testcase( pExpr->op==TK_AGG_COLUMN );
+ testcase( pExpr->op==TK_AGG_FUNCTION );
+ if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
+ switch( pExpr->op ){
+ case TK_ISNOT:
+ case TK_ISNULL:
+ case TK_NOTNULL:
+ case TK_IS:
+ case TK_OR:
+ case TK_VECTOR:
+ case TK_CASE:
+ case TK_IN:
+ case TK_FUNCTION:
+ case TK_TRUTH:
+ testcase( pExpr->op==TK_ISNOT );
+ testcase( pExpr->op==TK_ISNULL );
+ testcase( pExpr->op==TK_NOTNULL );
+ testcase( pExpr->op==TK_IS );
+ testcase( pExpr->op==TK_OR );
+ testcase( pExpr->op==TK_VECTOR );
+ testcase( pExpr->op==TK_CASE );
+ testcase( pExpr->op==TK_IN );
+ testcase( pExpr->op==TK_FUNCTION );
+ testcase( pExpr->op==TK_TRUTH );
+ return WRC_Prune;
+ case TK_COLUMN:
+ if( pWalker->u.iCur==pExpr->iTable ){
+ pWalker->eCode = 1;
+ return WRC_Abort;
+ }
+ return WRC_Prune;
+
+ case TK_AND:
+ if( pWalker->eCode==0 ){
+ sqlite3WalkExpr(pWalker, pExpr->pLeft);
+ if( pWalker->eCode ){
+ pWalker->eCode = 0;
+ sqlite3WalkExpr(pWalker, pExpr->pRight);
+ }
+ }
+ return WRC_Prune;
+
+ case TK_BETWEEN:
+ if( sqlite3WalkExpr(pWalker, pExpr->pLeft)==WRC_Abort ){
+ assert( pWalker->eCode );
+ return WRC_Abort;
+ }
+ return WRC_Prune;
+
+ /* Virtual tables are allowed to use constraints like x=NULL. So
+ ** a term of the form x=y does not prove that y is not null if x
+ ** is the column of a virtual table */
+ case TK_EQ:
+ case TK_NE:
+ case TK_LT:
+ case TK_LE:
+ case TK_GT:
+ case TK_GE: {
+ Expr *pLeft = pExpr->pLeft;
+ Expr *pRight = pExpr->pRight;
+ testcase( pExpr->op==TK_EQ );
+ testcase( pExpr->op==TK_NE );
+ testcase( pExpr->op==TK_LT );
+ testcase( pExpr->op==TK_LE );
+ testcase( pExpr->op==TK_GT );
+ testcase( pExpr->op==TK_GE );
+ /* The y.pTab=0 assignment in wherecode.c always happens after the
+ ** impliesNotNullRow() test */
+ if( (pLeft->op==TK_COLUMN && ALWAYS(pLeft->y.pTab!=0)
+ && IsVirtual(pLeft->y.pTab))
+ || (pRight->op==TK_COLUMN && ALWAYS(pRight->y.pTab!=0)
+ && IsVirtual(pRight->y.pTab))
+ ){
+ return WRC_Prune;
+ }
+ /* no break */ deliberate_fall_through
+ }
+ default:
+ return WRC_Continue;
+ }
+}
+
+/*
+** Return true (non-zero) if expression p can only be true if at least
+** one column of table iTab is non-null. In other words, return true
+** if expression p will always be NULL or false if every column of iTab
+** is NULL.
+**
+** False negatives are acceptable. In other words, it is ok to return
+** zero even if expression p will never be true of every column of iTab
+** is NULL. A false negative is merely a missed optimization opportunity.
+**
+** False positives are not allowed, however. A false positive may result
+** in an incorrect answer.
+**
+** Terms of p that are marked with EP_FromJoin (and hence that come from
+** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
+**
+** This routine is used to check if a LEFT JOIN can be converted into
+** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
+** clause requires that some column of the right table of the LEFT JOIN
+** be non-NULL, then the LEFT JOIN can be safely converted into an
+** ordinary join.
+*/
+SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
+ Walker w;
+ p = sqlite3ExprSkipCollateAndLikely(p);
+ if( p==0 ) return 0;
+ if( p->op==TK_NOTNULL ){
+ p = p->pLeft;
+ }else{
+ while( p->op==TK_AND ){
+ if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
+ p = p->pRight;
+ }
+ }
+ w.xExprCallback = impliesNotNullRow;
+ w.xSelectCallback = 0;
+ w.xSelectCallback2 = 0;
+ w.eCode = 0;
+ w.u.iCur = iTab;
+ sqlite3WalkExpr(&w, p);
+ return w.eCode;
+}
+
+/*
+** An instance of the following structure is used by the tree walker
+** to determine if an expression can be evaluated by reference to the
+** index only, without having to do a search for the corresponding
+** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
+** is the cursor for the table.
+*/
+struct IdxCover {
+ Index *pIdx; /* The index to be tested for coverage */
+ int iCur; /* Cursor number for the table corresponding to the index */
+};
+
+/*
+** Check to see if there are references to columns in table
+** pWalker->u.pIdxCover->iCur can be satisfied using the index
+** pWalker->u.pIdxCover->pIdx.
+*/
+static int exprIdxCover(Walker *pWalker, Expr *pExpr){
+ if( pExpr->op==TK_COLUMN
+ && pExpr->iTable==pWalker->u.pIdxCover->iCur
+ && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
+ ){
+ pWalker->eCode = 1;
+ return WRC_Abort;
+ }
+ return WRC_Continue;
+}
+
+/*
+** Determine if an index pIdx on table with cursor iCur contains will
+** the expression pExpr. Return true if the index does cover the
+** expression and false if the pExpr expression references table columns
+** that are not found in the index pIdx.
+**
+** An index covering an expression means that the expression can be
+** evaluated using only the index and without having to lookup the
+** corresponding table entry.
+*/
+SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
+ Expr *pExpr, /* The index to be tested */
+ int iCur, /* The cursor number for the corresponding table */
+ Index *pIdx /* The index that might be used for coverage */
+){
+ Walker w;
+ struct IdxCover xcov;
+ memset(&w, 0, sizeof(w));
+ xcov.iCur = iCur;
+ xcov.pIdx = pIdx;
+ w.xExprCallback = exprIdxCover;
+ w.u.pIdxCover = &xcov;
+ sqlite3WalkExpr(&w, pExpr);
+ return !w.eCode;
+}
+
+
+/*
+** An instance of the following structure is used by the tree walker
+** to count references to table columns in the arguments of an
+** aggregate function, in order to implement the
+** sqlite3FunctionThisSrc() routine.
+*/
+struct SrcCount {
+ SrcList *pSrc; /* One particular FROM clause in a nested query */
+ int iSrcInner; /* Smallest cursor number in this context */
+ int nThis; /* Number of references to columns in pSrcList */
+ int nOther; /* Number of references to columns in other FROM clauses */
+};
+
+/*
+** xSelect callback for sqlite3FunctionUsesThisSrc(). If this is the first
+** SELECT with a FROM clause encountered during this iteration, set
+** SrcCount.iSrcInner to the cursor number of the leftmost object in
+** the FROM cause.
+*/
+static int selectSrcCount(Walker *pWalker, Select *pSel){
+ struct SrcCount *p = pWalker->u.pSrcCount;
+ if( p->iSrcInner==0x7FFFFFFF && ALWAYS(pSel->pSrc) && pSel->pSrc->nSrc ){
+ pWalker->u.pSrcCount->iSrcInner = pSel->pSrc->a[0].iCursor;
+ }
+ return WRC_Continue;
+}
+
+/*
+** Count the number of references to columns.
+*/
+static int exprSrcCount(Walker *pWalker, Expr *pExpr){
+ /* There was once a NEVER() on the second term on the grounds that
+ ** sqlite3FunctionUsesThisSrc() was always called before
+ ** sqlite3ExprAnalyzeAggregates() and so the TK_COLUMNs have not yet
+ ** been converted into TK_AGG_COLUMN. But this is no longer true due
+ ** to window functions - sqlite3WindowRewrite() may now indirectly call
+ ** FunctionUsesThisSrc() when creating a new sub-select. */
+ if( pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN ){
+ int i;
+ struct SrcCount *p = pWalker->u.pSrcCount;
+ SrcList *pSrc = p->pSrc;
+ int nSrc = pSrc ? pSrc->nSrc : 0;
+ for(i=0; i<nSrc; i++){
+ if( pExpr->iTable==pSrc->a[i].iCursor ) break;
+ }
+ if( i<nSrc ){
+ p->nThis++;
+ }else if( pExpr->iTable<p->iSrcInner ){
+ /* In a well-formed parse tree (no name resolution errors),
+ ** TK_COLUMN nodes with smaller Expr.iTable values are in an
+ ** outer context. Those are the only ones to count as "other" */
+ p->nOther++;
+ }
+ }
+ return WRC_Continue;
+}
+
+/*
+** Determine if any of the arguments to the pExpr Function reference
+** pSrcList. Return true if they do. Also return true if the function
+** has no arguments or has only constant arguments. Return false if pExpr
+** references columns but not columns of tables found in pSrcList.
+*/
+SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
+ Walker w;
+ struct SrcCount cnt;
+ assert( pExpr->op==TK_AGG_FUNCTION );
+ memset(&w, 0, sizeof(w));
+ w.xExprCallback = exprSrcCount;
+ w.xSelectCallback = selectSrcCount;
+ w.u.pSrcCount = &cnt;
+ cnt.pSrc = pSrcList;
+ cnt.iSrcInner = (pSrcList&&pSrcList->nSrc)?pSrcList->a[0].iCursor:0x7FFFFFFF;
+ cnt.nThis = 0;
+ cnt.nOther = 0;
+ sqlite3WalkExprList(&w, pExpr->x.pList);
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( ExprHasProperty(pExpr, EP_WinFunc) ){
+ sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
+ }
+#endif
+ return cnt.nThis>0 || cnt.nOther==0;
+}
+
+/*
+** This is a Walker expression node callback.
+**
+** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
+** object that is referenced does not refer directly to the Expr. If
+** it does, make a copy. This is done because the pExpr argument is
+** subject to change.
+**
+** The copy is stored on pParse->pConstExpr with a register number of 0.
+** This will cause the expression to be deleted automatically when the
+** Parse object is destroyed, but the zero register number means that it
+** will not generate any code in the preamble.
+*/
+static int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){
+ if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced))
+ && pExpr->pAggInfo!=0
+ ){
+ AggInfo *pAggInfo = pExpr->pAggInfo;
+ int iAgg = pExpr->iAgg;
+ Parse *pParse = pWalker->pParse;
+ sqlite3 *db = pParse->db;
+ assert( pExpr->op==TK_AGG_COLUMN || pExpr->op==TK_AGG_FUNCTION );
+ if( pExpr->op==TK_AGG_COLUMN ){
+ assert( iAgg>=0 && iAgg<pAggInfo->nColumn );
+ if( pAggInfo->aCol[iAgg].pCExpr==pExpr ){
+ pExpr = sqlite3ExprDup(db, pExpr, 0);
+ if( pExpr ){
+ pAggInfo->aCol[iAgg].pCExpr = pExpr;
+ pParse->pConstExpr =
+ sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr);
+ }
+ }
+ }else{
+ assert( iAgg>=0 && iAgg<pAggInfo->nFunc );
+ if( pAggInfo->aFunc[iAgg].pFExpr==pExpr ){
+ pExpr = sqlite3ExprDup(db, pExpr, 0);
+ if( pExpr ){
+ pAggInfo->aFunc[iAgg].pFExpr = pExpr;
+ pParse->pConstExpr =
+ sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr);
+ }
+ }
+ }
+ }
+ return WRC_Continue;
+}
+
+/*
+** Initialize a Walker object so that will persist AggInfo entries referenced
+** by the tree that is walked.
+*/
+SQLITE_PRIVATE void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){
+ memset(pWalker, 0, sizeof(*pWalker));
+ pWalker->pParse = pParse;
+ pWalker->xExprCallback = agginfoPersistExprCb;
+ pWalker->xSelectCallback = sqlite3SelectWalkNoop;
+}
+
+/*
+** Add a new element to the pAggInfo->aCol[] array. Return the index of
+** the new element. Return a negative number if malloc fails.
+*/
+static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
+ int i;
+ pInfo->aCol = sqlite3ArrayAllocate(
+ db,
+ pInfo->aCol,
+ sizeof(pInfo->aCol[0]),
+ &pInfo->nColumn,
+ &i
+ );
+ return i;
+}
+
+/*
+** Add a new element to the pAggInfo->aFunc[] array. Return the index of
+** the new element. Return a negative number if malloc fails.
+*/
+static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
+ int i;
+ pInfo->aFunc = sqlite3ArrayAllocate(
+ db,
+ pInfo->aFunc,
+ sizeof(pInfo->aFunc[0]),
+ &pInfo->nFunc,
+ &i
+ );
+ return i;
+}
+
+/*
+** This is the xExprCallback for a tree walker. It is used to
+** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
+** for additional information.
+*/
+static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
+ int i;
+ NameContext *pNC = pWalker->u.pNC;
+ Parse *pParse = pNC->pParse;
+ SrcList *pSrcList = pNC->pSrcList;
+ AggInfo *pAggInfo = pNC->uNC.pAggInfo;
+
+ assert( pNC->ncFlags & NC_UAggInfo );
+ switch( pExpr->op ){
+ case TK_AGG_COLUMN:
+ case TK_COLUMN: {
+ testcase( pExpr->op==TK_AGG_COLUMN );
+ testcase( pExpr->op==TK_COLUMN );
+ /* Check to see if the column is in one of the tables in the FROM
+ ** clause of the aggregate query */
+ if( ALWAYS(pSrcList!=0) ){
+ struct SrcList_item *pItem = pSrcList->a;
+ for(i=0; i<pSrcList->nSrc; i++, pItem++){
+ struct AggInfo_col *pCol;
+ assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
+ if( pExpr->iTable==pItem->iCursor ){
+ /* If we reach this point, it means that pExpr refers to a table
+ ** that is in the FROM clause of the aggregate query.
+ **
+ ** Make an entry for the column in pAggInfo->aCol[] if there
+ ** is not an entry there already.
+ */
+ int k;
+ pCol = pAggInfo->aCol;
+ for(k=0; k<pAggInfo->nColumn; k++, pCol++){
+ if( pCol->iTable==pExpr->iTable &&
+ pCol->iColumn==pExpr->iColumn ){
+ break;
+ }
+ }
+ if( (k>=pAggInfo->nColumn)
+ && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
+ ){
+ pCol = &pAggInfo->aCol[k];
+ pCol->pTab = pExpr->y.pTab;
+ pCol->iTable = pExpr->iTable;
+ pCol->iColumn = pExpr->iColumn;
+ pCol->iMem = ++pParse->nMem;
+ pCol->iSorterColumn = -1;
+ pCol->pCExpr = pExpr;
+ if( pAggInfo->pGroupBy ){
+ int j, n;
+ ExprList *pGB = pAggInfo->pGroupBy;
+ struct ExprList_item *pTerm = pGB->a;
+ n = pGB->nExpr;
+ for(j=0; j<n; j++, pTerm++){
+ Expr *pE = pTerm->pExpr;
+ if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
+ pE->iColumn==pExpr->iColumn ){
+ pCol->iSorterColumn = j;
+ break;
+ }
+ }
+ }
+ if( pCol->iSorterColumn<0 ){
+ pCol->iSorterColumn = pAggInfo->nSortingColumn++;
+ }
+ }
+ /* There is now an entry for pExpr in pAggInfo->aCol[] (either
+ ** because it was there before or because we just created it).
+ ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
+ ** pAggInfo->aCol[] entry.
+ */
+ ExprSetVVAProperty(pExpr, EP_NoReduce);
+ pExpr->pAggInfo = pAggInfo;
+ pExpr->op = TK_AGG_COLUMN;
+ pExpr->iAgg = (i16)k;
+ break;
+ } /* endif pExpr->iTable==pItem->iCursor */
+ } /* end loop over pSrcList */
+ }
+ return WRC_Prune;
+ }
+ case TK_AGG_FUNCTION: {
+ if( (pNC->ncFlags & NC_InAggFunc)==0
+ && pWalker->walkerDepth==pExpr->op2
+ ){
+ /* Check to see if pExpr is a duplicate of another aggregate
+ ** function that is already in the pAggInfo structure
+ */
+ struct AggInfo_func *pItem = pAggInfo->aFunc;
+ for(i=0; i<pAggInfo->nFunc; i++, pItem++){
+ if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){
+ break;
+ }
+ }
+ if( i>=pAggInfo->nFunc ){
+ /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
+ */
+ u8 enc = ENC(pParse->db);
+ i = addAggInfoFunc(pParse->db, pAggInfo);
+ if( i>=0 ){
+ assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
+ pItem = &pAggInfo->aFunc[i];
+ pItem->pFExpr = pExpr;
+ pItem->iMem = ++pParse->nMem;
+ assert( !ExprHasProperty(pExpr, EP_IntValue) );
+ pItem->pFunc = sqlite3FindFunction(pParse->db,
+ pExpr->u.zToken,
+ pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
+ if( pExpr->flags & EP_Distinct ){
+ pItem->iDistinct = pParse->nTab++;
+ }else{
+ pItem->iDistinct = -1;
+ }
+ }
+ }
+ /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
+ */
+ assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
+ ExprSetVVAProperty(pExpr, EP_NoReduce);
+ pExpr->iAgg = (i16)i;
+ pExpr->pAggInfo = pAggInfo;
+ return WRC_Prune;
+ }else{
+ return WRC_Continue;
+ }
+ }
+ }
+ return WRC_Continue;
+}
+
+/*
+** Analyze the pExpr expression looking for aggregate functions and
+** for variables that need to be added to AggInfo object that pNC->pAggInfo
+** points to. Additional entries are made on the AggInfo object as
+** necessary.
+**
+** This routine should only be called after the expression has been
+** analyzed by sqlite3ResolveExprNames().
+*/
+SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
+ Walker w;
+ w.xExprCallback = analyzeAggregate;
+ w.xSelectCallback = sqlite3WalkerDepthIncrease;
+ w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
+ w.walkerDepth = 0;
+ w.u.pNC = pNC;
+ w.pParse = 0;
+ assert( pNC->pSrcList!=0 );
+ sqlite3WalkExpr(&w, pExpr);
+}
+
+/*
+** Call sqlite3ExprAnalyzeAggregates() for every expression in an
+** expression list. Return the number of errors.
+**
+** If an error is found, the analysis is cut short.
+*/
+SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
+ struct ExprList_item *pItem;
+ int i;
+ if( pList ){
+ for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
+ sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
+ }
+ }
+}
+
+/*
+** Allocate a single new register for use to hold some intermediate result.
+*/
+SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
+ if( pParse->nTempReg==0 ){
+ return ++pParse->nMem;
+ }
+ return pParse->aTempReg[--pParse->nTempReg];
+}
+
+/*
+** Deallocate a register, making available for reuse for some other
+** purpose.
+*/
+SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
+ if( iReg ){
+ sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0);
+ if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
+ pParse->aTempReg[pParse->nTempReg++] = iReg;
+ }
+ }
+}
+
+/*
+** Allocate or deallocate a block of nReg consecutive registers.
+*/
+SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
+ int i, n;
+ if( nReg==1 ) return sqlite3GetTempReg(pParse);
+ i = pParse->iRangeReg;
+ n = pParse->nRangeReg;
+ if( nReg<=n ){
+ pParse->iRangeReg += nReg;
+ pParse->nRangeReg -= nReg;
+ }else{
+ i = pParse->nMem+1;
+ pParse->nMem += nReg;
+ }
+ return i;
+}
+SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
+ if( nReg==1 ){
+ sqlite3ReleaseTempReg(pParse, iReg);
+ return;
+ }
+ sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0);
+ if( nReg>pParse->nRangeReg ){
+ pParse->nRangeReg = nReg;
+ pParse->iRangeReg = iReg;
+ }
+}
+
+/*
+** Mark all temporary registers as being unavailable for reuse.
+**
+** Always invoke this procedure after coding a subroutine or co-routine
+** that might be invoked from other parts of the code, to ensure that
+** the sub/co-routine does not use registers in common with the code that
+** invokes the sub/co-routine.
+*/
+SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
+ pParse->nTempReg = 0;
+ pParse->nRangeReg = 0;
+}
+
+/*
+** Validate that no temporary register falls within the range of
+** iFirst..iLast, inclusive. This routine is only call from within assert()
+** statements.
+*/
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
+ int i;
+ if( pParse->nRangeReg>0
+ && pParse->iRangeReg+pParse->nRangeReg > iFirst
+ && pParse->iRangeReg <= iLast
+ ){
+ return 0;
+ }
+ for(i=0; i<pParse->nTempReg; i++){
+ if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
+ return 0;
+ }
+ }
+ return 1;
+}
+#endif /* SQLITE_DEBUG */
+
+/************** End of expr.c ************************************************/
+/************** Begin file alter.c *******************************************/
+/*
+** 2005 February 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains C code routines that used to generate VDBE code
+** that implements the ALTER TABLE command.
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** The code in this file only exists if we are not omitting the
+** ALTER TABLE logic from the build.
+*/
+#ifndef SQLITE_OMIT_ALTERTABLE
+
+/*
+** Parameter zName is the name of a table that is about to be altered
+** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
+** If the table is a system table, this function leaves an error message
+** in pParse->zErr (system tables may not be altered) and returns non-zero.
+**
+** Or, if zName is not a system table, zero is returned.
+*/
+static int isAlterableTable(Parse *pParse, Table *pTab){
+ if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ || ( (pTab->tabFlags & TF_Shadow)!=0
+ && sqlite3ReadOnlyShadowTables(pParse->db)
+ )
+#endif
+ ){
+ sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
+ return 1;
+ }
+ return 0;
+}
+
+/*
+** Generate code to verify that the schemas of database zDb and, if
+** bTemp is not true, database "temp", can still be parsed. This is
+** called at the end of the generation of an ALTER TABLE ... RENAME ...
+** statement to ensure that the operation has not rendered any schema
+** objects unusable.
+*/
+static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
+ sqlite3NestedParse(pParse,
+ "SELECT 1 "
+ "FROM \"%w\"." DFLT_SCHEMA_TABLE " "
+ "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
+ " AND sql NOT LIKE 'create virtual%%'"
+ " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
+ zDb,
+ zDb, bTemp
+ );
+
+ if( bTemp==0 ){
+ sqlite3NestedParse(pParse,
+ "SELECT 1 "
+ "FROM temp." DFLT_SCHEMA_TABLE " "
+ "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
+ " AND sql NOT LIKE 'create virtual%%'"
+ " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
+ zDb
+ );
+ }
+}
+
+/*
+** Generate code to reload the schema for database iDb. And, if iDb!=1, for
+** the temp database as well.
+*/
+static void renameReloadSchema(Parse *pParse, int iDb){
+ Vdbe *v = pParse->pVdbe;
+ if( v ){
+ sqlite3ChangeCookie(pParse, iDb);
+ sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
+ if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
+ }
+}
+
+/*
+** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
+** command.
+*/
+SQLITE_PRIVATE void sqlite3AlterRenameTable(
+ Parse *pParse, /* Parser context. */
+ SrcList *pSrc, /* The table to rename. */
+ Token *pName /* The new table name. */
+){
+ int iDb; /* Database that contains the table */
+ char *zDb; /* Name of database iDb */
+ Table *pTab; /* Table being renamed */
+ char *zName = 0; /* NULL-terminated version of pName */
+ sqlite3 *db = pParse->db; /* Database connection */
+ int nTabName; /* Number of UTF-8 characters in zTabName */
+ const char *zTabName; /* Original name of the table */
+ Vdbe *v;
+ VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
+ u32 savedDbFlags; /* Saved value of db->mDbFlags */
+
+ savedDbFlags = db->mDbFlags;
+ if( NEVER(db->mallocFailed) ) goto exit_rename_table;
+ assert( pSrc->nSrc==1 );
+ assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
+
+ pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
+ if( !pTab ) goto exit_rename_table;
+ iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
+ zDb = db->aDb[iDb].zDbSName;
+ db->mDbFlags |= DBFLAG_PreferBuiltin;
+
+ /* Get a NULL terminated version of the new table name. */
+ zName = sqlite3NameFromToken(db, pName);
+ if( !zName ) goto exit_rename_table;
+
+ /* Check that a table or index named 'zName' does not already exist
+ ** in database iDb. If so, this is an error.
+ */
+ if( sqlite3FindTable(db, zName, zDb)
+ || sqlite3FindIndex(db, zName, zDb)
+ || sqlite3IsShadowTableOf(db, pTab, zName)
+ ){
+ sqlite3ErrorMsg(pParse,
+ "there is already another table or index with this name: %s", zName);
+ goto exit_rename_table;
+ }
+
+ /* Make sure it is not a system table being altered, or a reserved name
+ ** that the table is being renamed to.
+ */
+ if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
+ goto exit_rename_table;
+ }
+ if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
+ goto exit_rename_table;
+ }
+
+#ifndef SQLITE_OMIT_VIEW
+ if( pTab->pSelect ){
+ sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
+ goto exit_rename_table;
+ }
+#endif
+
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ /* Invoke the authorization callback. */
+ if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
+ goto exit_rename_table;
+ }
+#endif
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( sqlite3ViewGetColumnNames(pParse, pTab) ){
+ goto exit_rename_table;
+ }
+ if( IsVirtual(pTab) ){
+ pVTab = sqlite3GetVTable(db, pTab);
+ if( pVTab->pVtab->pModule->xRename==0 ){
+ pVTab = 0;
+ }
+ }
+#endif
+
+ /* Begin a transaction for database iDb. Then modify the schema cookie
+ ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
+ ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
+ ** nested SQL may raise an exception. */
+ v = sqlite3GetVdbe(pParse);
+ if( v==0 ){
+ goto exit_rename_table;
+ }
+ sqlite3MayAbort(pParse);
+
+ /* figure out how many UTF-8 characters are in zName */
+ zTabName = pTab->zName;
+ nTabName = sqlite3Utf8CharLen(zTabName, -1);
+
+ /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
+ ** the schema to use the new table name. */
+ sqlite3NestedParse(pParse,
+ "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
+ "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
+ "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
+ "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
+ , zDb, zDb, zTabName, zName, (iDb==1), zTabName
+ );
+
+ /* Update the tbl_name and name columns of the sqlite_schema table
+ ** as required. */
+ sqlite3NestedParse(pParse,
+ "UPDATE %Q." DFLT_SCHEMA_TABLE " SET "
+ "tbl_name = %Q, "
+ "name = CASE "
+ "WHEN type='table' THEN %Q "
+ "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
+ " AND type='index' THEN "
+ "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
+ "ELSE name END "
+ "WHERE tbl_name=%Q COLLATE nocase AND "
+ "(type='table' OR type='index' OR type='trigger');",
+ zDb,
+ zName, zName, zName,
+ nTabName, zTabName
+ );
+
+#ifndef SQLITE_OMIT_AUTOINCREMENT
+ /* If the sqlite_sequence table exists in this database, then update
+ ** it with the new table name.
+ */
+ if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
+ sqlite3NestedParse(pParse,
+ "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
+ zDb, zName, pTab->zName);
+ }
+#endif
+
+ /* If the table being renamed is not itself part of the temp database,
+ ** edit view and trigger definitions within the temp database
+ ** as required. */
+ if( iDb!=1 ){
+ sqlite3NestedParse(pParse,
+ "UPDATE sqlite_temp_schema SET "
+ "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
+ "tbl_name = "
+ "CASE WHEN tbl_name=%Q COLLATE nocase AND "
+ " sqlite_rename_test(%Q, sql, type, name, 1) "
+ "THEN %Q ELSE tbl_name END "
+ "WHERE type IN ('view', 'trigger')"
+ , zDb, zTabName, zName, zTabName, zDb, zName);
+ }
+
+ /* If this is a virtual table, invoke the xRename() function if
+ ** one is defined. The xRename() callback will modify the names
+ ** of any resources used by the v-table implementation (including other
+ ** SQLite tables) that are identified by the name of the virtual table.
+ */
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( pVTab ){
+ int i = ++pParse->nMem;
+ sqlite3VdbeLoadString(v, i, zName);
+ sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
+ }
+#endif
+
+ renameReloadSchema(pParse, iDb);
+ renameTestSchema(pParse, zDb, iDb==1);
+
+exit_rename_table:
+ sqlite3SrcListDelete(db, pSrc);
+ sqlite3DbFree(db, zName);
+ db->mDbFlags = savedDbFlags;
+}
+
+/*
+** Write code that will raise an error if the table described by
+** zDb and zTab is not empty.
+*/
+static void sqlite3ErrorIfNotEmpty(
+ Parse *pParse, /* Parsing context */
+ const char *zDb, /* Schema holding the table */
+ const char *zTab, /* Table to check for empty */
+ const char *zErr /* Error message text */
+){
+ sqlite3NestedParse(pParse,
+ "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"",
+ zErr, zDb, zTab
+ );
+}
+
+/*
+** This function is called after an "ALTER TABLE ... ADD" statement
+** has been parsed. Argument pColDef contains the text of the new
+** column definition.
+**
+** The Table structure pParse->pNewTable was extended to include
+** the new column during parsing.
+*/
+SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
+ Table *pNew; /* Copy of pParse->pNewTable */
+ Table *pTab; /* Table being altered */
+ int iDb; /* Database number */
+ const char *zDb; /* Database name */
+ const char *zTab; /* Table name */
+ char *zCol; /* Null-terminated column definition */
+ Column *pCol; /* The new column */
+ Expr *pDflt; /* Default value for the new column */
+ sqlite3 *db; /* The database connection; */
+ Vdbe *v; /* The prepared statement under construction */
+ int r1; /* Temporary registers */
+
+ db = pParse->db;
+ if( pParse->nErr || db->mallocFailed ) return;
+ pNew = pParse->pNewTable;
+ assert( pNew );
+
+ assert( sqlite3BtreeHoldsAllMutexes(db) );
+ iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
+ zDb = db->aDb[iDb].zDbSName;
+ zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
+ pCol = &pNew->aCol[pNew->nCol-1];
+ pDflt = pCol->pDflt;
+ pTab = sqlite3FindTable(db, zTab, zDb);
+ assert( pTab );
+
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ /* Invoke the authorization callback. */
+ if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
+ return;
+ }
+#endif
+
+
+ /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
+ ** If there is a NOT NULL constraint, then the default value for the
+ ** column must not be NULL.
+ */
+ if( pCol->colFlags & COLFLAG_PRIMKEY ){
+ sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
+ return;
+ }
+ if( pNew->pIndex ){
+ sqlite3ErrorMsg(pParse,
+ "Cannot add a UNIQUE column");
+ return;
+ }
+ if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
+ /* If the default value for the new column was specified with a
+ ** literal NULL, then set pDflt to 0. This simplifies checking
+ ** for an SQL NULL default below.
+ */
+ assert( pDflt==0 || pDflt->op==TK_SPAN );
+ if( pDflt && pDflt->pLeft->op==TK_NULL ){
+ pDflt = 0;
+ }
+ if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
+ sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
+ "Cannot add a REFERENCES column with non-NULL default value");
+ }
+ if( pCol->notNull && !pDflt ){
+ sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
+ "Cannot add a NOT NULL column with default value NULL");
+ }
+
+
+ /* Ensure the default expression is something that sqlite3ValueFromExpr()
+ ** can handle (i.e. not CURRENT_TIME etc.)
+ */
+ if( pDflt ){
+ sqlite3_value *pVal = 0;
+ int rc;
+ rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
+ assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
+ if( rc!=SQLITE_OK ){
+ assert( db->mallocFailed == 1 );
+ return;
+ }
+ if( !pVal ){
+ sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
+ "Cannot add a column with non-constant default");
+ }
+ sqlite3ValueFree(pVal);
+ }
+ }else if( pCol->colFlags & COLFLAG_STORED ){
+ sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
+ }
+
+
+ /* Modify the CREATE TABLE statement. */
+ zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
+ if( zCol ){
+ char *zEnd = &zCol[pColDef->n-1];
+ u32 savedDbFlags = db->mDbFlags;
+ while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
+ *zEnd-- = '\0';
+ }
+ db->mDbFlags |= DBFLAG_PreferBuiltin;
+ sqlite3NestedParse(pParse,
+ "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
+ "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
+ "WHERE type = 'table' AND name = %Q",
+ zDb, pNew->addColOffset, zCol, pNew->addColOffset+1,
+ zTab
+ );
+ sqlite3DbFree(db, zCol);
+ db->mDbFlags = savedDbFlags;
+ }
+
+ /* Make sure the schema version is at least 3. But do not upgrade
+ ** from less than 3 to 4, as that will corrupt any preexisting DESC
+ ** index.
+ */
+ v = sqlite3GetVdbe(pParse);
+ if( v ){
+ r1 = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
+ sqlite3VdbeUsesBtree(v, iDb);
+ sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
+ sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
+ VdbeCoverage(v);
+ sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
+ sqlite3ReleaseTempReg(pParse, r1);
+ }
+
+ /* Reload the table definition */
+ renameReloadSchema(pParse, iDb);
+}
+
+/*
+** This function is called by the parser after the table-name in
+** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
+** pSrc is the full-name of the table being altered.
+**
+** This routine makes a (partial) copy of the Table structure
+** for the table being altered and sets Parse.pNewTable to point
+** to it. Routines called by the parser as the column definition
+** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
+** the copy. The copy of the Table structure is deleted by tokenize.c
+** after parsing is finished.
+**
+** Routine sqlite3AlterFinishAddColumn() will be called to complete
+** coding the "ALTER TABLE ... ADD" statement.
+*/
+SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
+ Table *pNew;
+ Table *pTab;
+ int iDb;
+ int i;
+ int nAlloc;
+ sqlite3 *db = pParse->db;
+
+ /* Look up the table being altered. */
+ assert( pParse->pNewTable==0 );
+ assert( sqlite3BtreeHoldsAllMutexes(db) );
+ if( db->mallocFailed ) goto exit_begin_add_column;
+ pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
+ if( !pTab ) goto exit_begin_add_column;
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( IsVirtual(pTab) ){
+ sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
+ goto exit_begin_add_column;
+ }
+#endif
+
+ /* Make sure this is not an attempt to ALTER a view. */
+ if( pTab->pSelect ){
+ sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
+ goto exit_begin_add_column;
+ }
+ if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
+ goto exit_begin_add_column;
+ }
+
+ sqlite3MayAbort(pParse);
+ assert( pTab->addColOffset>0 );
+ iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+
+ /* Put a copy of the Table struct in Parse.pNewTable for the
+ ** sqlite3AddColumn() function and friends to modify. But modify
+ ** the name by adding an "sqlite_altertab_" prefix. By adding this
+ ** prefix, we insure that the name will not collide with an existing
+ ** table because user table are not allowed to have the "sqlite_"
+ ** prefix on their name.
+ */
+ pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
+ if( !pNew ) goto exit_begin_add_column;
+ pParse->pNewTable = pNew;
+ pNew->nTabRef = 1;
+ pNew->nCol = pTab->nCol;
+ assert( pNew->nCol>0 );
+ nAlloc = (((pNew->nCol-1)/8)*8)+8;
+ assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
+ pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
+ pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
+ if( !pNew->aCol || !pNew->zName ){
+ assert( db->mallocFailed );
+ goto exit_begin_add_column;
+ }
+ memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
+ for(i=0; i<pNew->nCol; i++){
+ Column *pCol = &pNew->aCol[i];
+ pCol->zName = sqlite3DbStrDup(db, pCol->zName);
+ pCol->hName = sqlite3StrIHash(pCol->zName);
+ pCol->zColl = 0;
+ pCol->pDflt = 0;
+ }
+ pNew->pSchema = db->aDb[iDb].pSchema;
+ pNew->addColOffset = pTab->addColOffset;
+ pNew->nTabRef = 1;
+
+exit_begin_add_column:
+ sqlite3SrcListDelete(db, pSrc);
+ return;
+}
+
+/*
+** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
+** command. This function checks if the table is a view or virtual
+** table (columns of views or virtual tables may not be renamed). If so,
+** it loads an error message into pParse and returns non-zero.
+**
+** Or, if pTab is not a view or virtual table, zero is returned.
+*/
+#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
+static int isRealTable(Parse *pParse, Table *pTab){
+ const char *zType = 0;
+#ifndef SQLITE_OMIT_VIEW
+ if( pTab->pSelect ){
+ zType = "view";
+ }
+#endif
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( IsVirtual(pTab) ){
+ zType = "virtual table";
+ }
+#endif
+ if( zType ){
+ sqlite3ErrorMsg(
+ pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
+ );
+ return 1;
+ }
+ return 0;
+}
+#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
+# define isRealTable(x,y) (0)
+#endif
+
+/*
+** Handles the following parser reduction:
+**
+** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
+*/
+SQLITE_PRIVATE void sqlite3AlterRenameColumn(
+ Parse *pParse, /* Parsing context */
+ SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
+ Token *pOld, /* Name of column being changed */
+ Token *pNew /* New column name */
+){
+ sqlite3 *db = pParse->db; /* Database connection */
+ Table *pTab; /* Table being updated */
+ int iCol; /* Index of column being renamed */
+ char *zOld = 0; /* Old column name */
+ char *zNew = 0; /* New column name */
+ const char *zDb; /* Name of schema containing the table */
+ int iSchema; /* Index of the schema */
+ int bQuote; /* True to quote the new name */
+
+ /* Locate the table to be altered */
+ pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
+ if( !pTab ) goto exit_rename_column;
+
+ /* Cannot alter a system table */
+ if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
+ if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
+
+ /* Which schema holds the table to be altered */
+ iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
+ assert( iSchema>=0 );
+ zDb = db->aDb[iSchema].zDbSName;
+
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ /* Invoke the authorization callback. */
+ if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
+ goto exit_rename_column;
+ }
+#endif
+
+ /* Make sure the old name really is a column name in the table to be
+ ** altered. Set iCol to be the index of the column being renamed */
+ zOld = sqlite3NameFromToken(db, pOld);
+ if( !zOld ) goto exit_rename_column;
+ for(iCol=0; iCol<pTab->nCol; iCol++){
+ if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
+ }
+ if( iCol==pTab->nCol ){
+ sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
+ goto exit_rename_column;
+ }
+
+ /* Do the rename operation using a recursive UPDATE statement that
+ ** uses the sqlite_rename_column() SQL function to compute the new
+ ** CREATE statement text for the sqlite_schema table.
+ */
+ sqlite3MayAbort(pParse);
+ zNew = sqlite3NameFromToken(db, pNew);
+ if( !zNew ) goto exit_rename_column;
+ assert( pNew->n>0 );
+ bQuote = sqlite3Isquote(pNew->z[0]);
+ sqlite3NestedParse(pParse,
+ "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
+ "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
+ "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
+ " AND (type != 'index' OR tbl_name = %Q)"
+ " AND sql NOT LIKE 'create virtual%%'",
+ zDb,
+ zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
+ pTab->zName
+ );
+
+ sqlite3NestedParse(pParse,
+ "UPDATE temp." DFLT_SCHEMA_TABLE " SET "
+ "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
+ "WHERE type IN ('trigger', 'view')",
+ zDb, pTab->zName, iCol, zNew, bQuote
+ );
+
+ /* Drop and reload the database schema. */
+ renameReloadSchema(pParse, iSchema);
+ renameTestSchema(pParse, zDb, iSchema==1);
+
+ exit_rename_column:
+ sqlite3SrcListDelete(db, pSrc);
+ sqlite3DbFree(db, zOld);
+ sqlite3DbFree(db, zNew);
+ return;
+}
+
+/*
+** Each RenameToken object maps an element of the parse tree into
+** the token that generated that element. The parse tree element
+** might be one of:
+**
+** * A pointer to an Expr that represents an ID
+** * The name of a table column in Column.zName
+**
+** A list of RenameToken objects can be constructed during parsing.
+** Each new object is created by sqlite3RenameTokenMap().
+** As the parse tree is transformed, the sqlite3RenameTokenRemap()
+** routine is used to keep the mapping current.
+**
+** After the parse finishes, renameTokenFind() routine can be used
+** to look up the actual token value that created some element in
+** the parse tree.
+*/
+struct RenameToken {
+ void *p; /* Parse tree element created by token t */
+ Token t; /* The token that created parse tree element p */
+ RenameToken *pNext; /* Next is a list of all RenameToken objects */
+};
+
+/*
+** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
+** down into the Walker.
+*/
+typedef struct RenameCtx RenameCtx;
+struct RenameCtx {
+ RenameToken *pList; /* List of tokens to overwrite */
+ int nList; /* Number of tokens in pList */
+ int iCol; /* Index of column being renamed */
+ Table *pTab; /* Table being ALTERed */
+ const char *zOld; /* Old column name */
+};
+
+#ifdef SQLITE_DEBUG
+/*
+** This function is only for debugging. It performs two tasks:
+**
+** 1. Checks that pointer pPtr does not already appear in the
+** rename-token list.
+**
+** 2. Dereferences each pointer in the rename-token list.
+**
+** The second is most effective when debugging under valgrind or
+** address-sanitizer or similar. If any of these pointers no longer
+** point to valid objects, an exception is raised by the memory-checking
+** tool.
+**
+** The point of this is to prevent comparisons of invalid pointer values.
+** Even though this always seems to work, it is undefined according to the
+** C standard. Example of undefined comparison:
+**
+** sqlite3_free(x);
+** if( x==y ) ...
+**
+** Technically, as x no longer points into a valid object or to the byte
+** following a valid object, it may not be used in comparison operations.
+*/
+static void renameTokenCheckAll(Parse *pParse, void *pPtr){
+ if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
+ RenameToken *p;
+ u8 i = 0;
+ for(p=pParse->pRename; p; p=p->pNext){
+ if( p->p ){
+ assert( p->p!=pPtr );
+ i += *(u8*)(p->p);
+ }
+ }
+ }
+}
+#else
+# define renameTokenCheckAll(x,y)
+#endif
+
+/*
+** Remember that the parser tree element pPtr was created using
+** the token pToken.
+**
+** In other words, construct a new RenameToken object and add it
+** to the list of RenameToken objects currently being built up
+** in pParse->pRename.
+**
+** The pPtr argument is returned so that this routine can be used
+** with tail recursion in tokenExpr() routine, for a small performance
+** improvement.
+*/
+SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
+ RenameToken *pNew;
+ assert( pPtr || pParse->db->mallocFailed );
+ renameTokenCheckAll(pParse, pPtr);
+ if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
+ pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
+ if( pNew ){
+ pNew->p = pPtr;
+ pNew->t = *pToken;
+ pNew->pNext = pParse->pRename;
+ pParse->pRename = pNew;
+ }
+ }
+
+ return pPtr;
+}
+
+/*
+** It is assumed that there is already a RenameToken object associated
+** with parse tree element pFrom. This function remaps the associated token
+** to parse tree element pTo.
+*/
+SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
+ RenameToken *p;
+ renameTokenCheckAll(pParse, pTo);
+ for(p=pParse->pRename; p; p=p->pNext){
+ if( p->p==pFrom ){
+ p->p = pTo;
+ break;
+ }
+ }
+}
+
+/*
+** Walker callback used by sqlite3RenameExprUnmap().
+*/
+static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
+ Parse *pParse = pWalker->pParse;
+ sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
+ return WRC_Continue;
+}
+
+/*
+** Iterate through the Select objects that are part of WITH clauses attached
+** to select statement pSelect.
+*/
+static void renameWalkWith(Walker *pWalker, Select *pSelect){
+ With *pWith = pSelect->pWith;
+ if( pWith ){
+ int i;
+ for(i=0; i<pWith->nCte; i++){
+ Select *p = pWith->a[i].pSelect;
+ NameContext sNC;
+ memset(&sNC, 0, sizeof(sNC));
+ sNC.pParse = pWalker->pParse;
+ sqlite3SelectPrep(sNC.pParse, p, &sNC);
+ sqlite3WalkSelect(pWalker, p);
+ sqlite3RenameExprlistUnmap(pWalker->pParse, pWith->a[i].pCols);
+ }
+ }
+}
+
+/*
+** Unmap all tokens in the IdList object passed as the second argument.
+*/
+static void unmapColumnIdlistNames(
+ Parse *pParse,
+ IdList *pIdList
+){
+ if( pIdList ){
+ int ii;
+ for(ii=0; ii<pIdList->nId; ii++){
+ sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName);
+ }
+ }
+}
+
+/*
+** Walker callback used by sqlite3RenameExprUnmap().
+*/
+static int renameUnmapSelectCb(Walker *pWalker, Select *p){
+ Parse *pParse = pWalker->pParse;
+ int i;
+ if( pParse->nErr ) return WRC_Abort;
+ if( NEVER(p->selFlags & SF_View) ) return WRC_Prune;
+ if( ALWAYS(p->pEList) ){
+ ExprList *pList = p->pEList;
+ for(i=0; i<pList->nExpr; i++){
+ if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
+ sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
+ }
+ }
+ }
+ if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
+ SrcList *pSrc = p->pSrc;
+ for(i=0; i<pSrc->nSrc; i++){
+ sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
+ if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
+ unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
+ }
+ }
+
+ renameWalkWith(pWalker, p);
+ return WRC_Continue;
+}
+
+/*
+** Remove all nodes that are part of expression pExpr from the rename list.
+*/
+SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
+ u8 eMode = pParse->eParseMode;
+ Walker sWalker;
+ memset(&sWalker, 0, sizeof(Walker));
+ sWalker.pParse = pParse;
+ sWalker.xExprCallback = renameUnmapExprCb;
+ sWalker.xSelectCallback = renameUnmapSelectCb;
+ pParse->eParseMode = PARSE_MODE_UNMAP;
+ sqlite3WalkExpr(&sWalker, pExpr);
+ pParse->eParseMode = eMode;
+}
+
+/*
+** Remove all nodes that are part of expression-list pEList from the
+** rename list.
+*/
+SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
+ if( pEList ){
+ int i;
+ Walker sWalker;
+ memset(&sWalker, 0, sizeof(Walker));
+ sWalker.pParse = pParse;
+ sWalker.xExprCallback = renameUnmapExprCb;
+ sqlite3WalkExprList(&sWalker, pEList);
+ for(i=0; i<pEList->nExpr; i++){
+ if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
+ sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
+ }
+ }
+ }
+}
+
+/*
+** Free the list of RenameToken objects given in the second argument
+*/
+static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
+ RenameToken *pNext;
+ RenameToken *p;
+ for(p=pToken; p; p=pNext){
+ pNext = p->pNext;
+ sqlite3DbFree(db, p);
+ }
+}
+
+/*
+** Search the Parse object passed as the first argument for a RenameToken
+** object associated with parse tree element pPtr. If found, remove it
+** from the Parse object and add it to the list maintained by the
+** RenameCtx object passed as the second argument.
+*/
+static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
+ RenameToken **pp;
+ assert( pPtr!=0 );
+ for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
+ if( (*pp)->p==pPtr ){
+ RenameToken *pToken = *pp;
+ *pp = pToken->pNext;
+ pToken->pNext = pCtx->pList;
+ pCtx->pList = pToken;
+ pCtx->nList++;
+ break;
+ }
+ }
+}
+
+/*
+** This is a Walker select callback. It does nothing. It is only required
+** because without a dummy callback, sqlite3WalkExpr() and similar do not
+** descend into sub-select statements.
+*/
+static int renameColumnSelectCb(Walker *pWalker, Select *p){
+ if( p->selFlags & SF_View ) return WRC_Prune;
+ renameWalkWith(pWalker, p);
+ return WRC_Continue;
+}
+
+/*
+** This is a Walker expression callback.
+**
+** For every TK_COLUMN node in the expression tree, search to see
+** if the column being references is the column being renamed by an
+** ALTER TABLE statement. If it is, then attach its associated
+** RenameToken object to the list of RenameToken objects being
+** constructed in RenameCtx object at pWalker->u.pRename.
+*/
+static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
+ RenameCtx *p = pWalker->u.pRename;
+ if( pExpr->op==TK_TRIGGER
+ && pExpr->iColumn==p->iCol
+ && pWalker->pParse->pTriggerTab==p->pTab
+ ){
+ renameTokenFind(pWalker->pParse, p, (void*)pExpr);
+ }else if( pExpr->op==TK_COLUMN
+ && pExpr->iColumn==p->iCol
+ && p->pTab==pExpr->y.pTab
+ ){
+ renameTokenFind(pWalker->pParse, p, (void*)pExpr);
+ }
+ return WRC_Continue;
+}
+
+/*
+** The RenameCtx contains a list of tokens that reference a column that
+** is being renamed by an ALTER TABLE statement. Return the "last"
+** RenameToken in the RenameCtx and remove that RenameToken from the
+** RenameContext. "Last" means the last RenameToken encountered when
+** the input SQL is parsed from left to right. Repeated calls to this routine
+** return all column name tokens in the order that they are encountered
+** in the SQL statement.
+*/
+static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
+ RenameToken *pBest = pCtx->pList;
+ RenameToken *pToken;
+ RenameToken **pp;
+
+ for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
+ if( pToken->t.z>pBest->t.z ) pBest = pToken;
+ }
+ for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
+ *pp = pBest->pNext;
+
+ return pBest;
+}
+
+/*
+** An error occured while parsing or otherwise processing a database
+** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
+** ALTER TABLE RENAME COLUMN program. The error message emitted by the
+** sub-routine is currently stored in pParse->zErrMsg. This function
+** adds context to the error message and then stores it in pCtx.
+*/
+static void renameColumnParseError(
+ sqlite3_context *pCtx,
+ int bPost,
+ sqlite3_value *pType,
+ sqlite3_value *pObject,
+ Parse *pParse
+){
+ const char *zT = (const char*)sqlite3_value_text(pType);
+ const char *zN = (const char*)sqlite3_value_text(pObject);
+ char *zErr;
+
+ zErr = sqlite3_mprintf("error in %s %s%s: %s",
+ zT, zN, (bPost ? " after rename" : ""),
+ pParse->zErrMsg
+ );
+ sqlite3_result_error(pCtx, zErr, -1);
+ sqlite3_free(zErr);
+}
+
+/*
+** For each name in the the expression-list pEList (i.e. each
+** pEList->a[i].zName) that matches the string in zOld, extract the
+** corresponding rename-token from Parse object pParse and add it
+** to the RenameCtx pCtx.
+*/
+static void renameColumnElistNames(
+ Parse *pParse,
+ RenameCtx *pCtx,
+ ExprList *pEList,
+ const char *zOld
+){
+ if( pEList ){
+ int i;
+ for(i=0; i<pEList->nExpr; i++){
+ char *zName = pEList->a[i].zEName;
+ if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
+ && ALWAYS(zName!=0)
+ && 0==sqlite3_stricmp(zName, zOld)
+ ){
+ renameTokenFind(pParse, pCtx, (void*)zName);
+ }
+ }
+ }
+}
+
+/*
+** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
+** that matches the string in zOld, extract the corresponding rename-token
+** from Parse object pParse and add it to the RenameCtx pCtx.
+*/
+static void renameColumnIdlistNames(
+ Parse *pParse,
+ RenameCtx *pCtx,
+ IdList *pIdList,
+ const char *zOld
+){
+ if( pIdList ){
+ int i;
+ for(i=0; i<pIdList->nId; i++){
+ char *zName = pIdList->a[i].zName;
+ if( 0==sqlite3_stricmp(zName, zOld) ){
+ renameTokenFind(pParse, pCtx, (void*)zName);
+ }
+ }
+ }
+}
+
+
+/*
+** Parse the SQL statement zSql using Parse object (*p). The Parse object
+** is initialized by this function before it is used.
+*/
+static int renameParseSql(
+ Parse *p, /* Memory to use for Parse object */
+ const char *zDb, /* Name of schema SQL belongs to */
+ sqlite3 *db, /* Database handle */
+ const char *zSql, /* SQL to parse */
+ int bTemp /* True if SQL is from temp schema */
+){
+ int rc;
+ char *zErr = 0;
+
+ db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
+
+ /* Parse the SQL statement passed as the first argument. If no error
+ ** occurs and the parse does not result in a new table, index or
+ ** trigger object, the database must be corrupt. */
+ memset(p, 0, sizeof(Parse));
+ p->eParseMode = PARSE_MODE_RENAME;
+ p->db = db;
+ p->nQueryLoop = 1;
+ rc = sqlite3RunParser(p, zSql, &zErr);
+ assert( p->zErrMsg==0 );
+ assert( rc!=SQLITE_OK || zErr==0 );
+ p->zErrMsg = zErr;
+ if( db->mallocFailed ) rc = SQLITE_NOMEM;
+ if( rc==SQLITE_OK
+ && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
+ ){
+ rc = SQLITE_CORRUPT_BKPT;
+ }
+
+#ifdef SQLITE_DEBUG
+ /* Ensure that all mappings in the Parse.pRename list really do map to
+ ** a part of the input string. */
+ if( rc==SQLITE_OK ){
+ int nSql = sqlite3Strlen30(zSql);
+ RenameToken *pToken;
+ for(pToken=p->pRename; pToken; pToken=pToken->pNext){
+ assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
+ }
+ }
+#endif
+
+ db->init.iDb = 0;
+ return rc;
+}
+
+/*
+** This function edits SQL statement zSql, replacing each token identified
+** by the linked list pRename with the text of zNew. If argument bQuote is
+** true, then zNew is always quoted first. If no error occurs, the result
+** is loaded into context object pCtx as the result.
+**
+** Or, if an error occurs (i.e. an OOM condition), an error is left in
+** pCtx and an SQLite error code returned.
+*/
+static int renameEditSql(
+ sqlite3_context *pCtx, /* Return result here */
+ RenameCtx *pRename, /* Rename context */
+ const char *zSql, /* SQL statement to edit */
+ const char *zNew, /* New token text */
+ int bQuote /* True to always quote token */
+){
+ int nNew = sqlite3Strlen30(zNew);
+ int nSql = sqlite3Strlen30(zSql);
+ sqlite3 *db = sqlite3_context_db_handle(pCtx);
+ int rc = SQLITE_OK;
+ char *zQuot;
+ char *zOut;
+ int nQuot;
+
+ /* Set zQuot to point to a buffer containing a quoted copy of the
+ ** identifier zNew. If the corresponding identifier in the original
+ ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
+ ** point to zQuot so that all substitutions are made using the
+ ** quoted version of the new column name. */
+ zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
+ if( zQuot==0 ){
+ return SQLITE_NOMEM;
+ }else{
+ nQuot = sqlite3Strlen30(zQuot);
+ }
+ if( bQuote ){
+ zNew = zQuot;
+ nNew = nQuot;
+ }
+
+ /* At this point pRename->pList contains a list of RenameToken objects
+ ** corresponding to all tokens in the input SQL that must be replaced
+ ** with the new column name. All that remains is to construct and
+ ** return the edited SQL string. */
+ assert( nQuot>=nNew );
+ zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
+ if( zOut ){
+ int nOut = nSql;
+ memcpy(zOut, zSql, nSql);
+ while( pRename->pList ){
+ int iOff; /* Offset of token to replace in zOut */
+ RenameToken *pBest = renameColumnTokenNext(pRename);
+
+ u32 nReplace;
+ const char *zReplace;
+ if( sqlite3IsIdChar(*pBest->t.z) ){
+ nReplace = nNew;
+ zReplace = zNew;
+ }else{
+ nReplace = nQuot;
+ zReplace = zQuot;
+ }
+
+ iOff = pBest->t.z - zSql;
+ if( pBest->t.n!=nReplace ){
+ memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
+ nOut - (iOff + pBest->t.n)
+ );
+ nOut += nReplace - pBest->t.n;
+ zOut[nOut] = '\0';
+ }
+ memcpy(&zOut[iOff], zReplace, nReplace);
+ sqlite3DbFree(db, pBest);
+ }
+
+ sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
+ sqlite3DbFree(db, zOut);
+ }else{
+ rc = SQLITE_NOMEM;
+ }
+
+ sqlite3_free(zQuot);
+ return rc;
+}
+
+/*
+** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
+** it was read from the schema of database zDb. Return SQLITE_OK if
+** successful. Otherwise, return an SQLite error code and leave an error
+** message in the Parse object.
+*/
+static int renameResolveTrigger(Parse *pParse){
+ sqlite3 *db = pParse->db;
+ Trigger *pNew = pParse->pNewTrigger;
+ TriggerStep *pStep;
+ NameContext sNC;
+ int rc = SQLITE_OK;
+
+ memset(&sNC, 0, sizeof(sNC));
+ sNC.pParse = pParse;
+ assert( pNew->pTabSchema );
+ pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
+ db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
+ );
+ pParse->eTriggerOp = pNew->op;
+ /* ALWAYS() because if the table of the trigger does not exist, the
+ ** error would have been hit before this point */
+ if( ALWAYS(pParse->pTriggerTab) ){
+ rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
+ }
+
+ /* Resolve symbols in WHEN clause */
+ if( rc==SQLITE_OK && pNew->pWhen ){
+ rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
+ }
+
+ for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
+ if( pStep->pSelect ){
+ sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
+ if( pParse->nErr ) rc = pParse->rc;
+ }
+ if( rc==SQLITE_OK && pStep->zTarget ){
+ SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
+ if( pSrc ){
+ int i;
+ for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
+ struct SrcList_item *p = &pSrc->a[i];
+ p->pTab = sqlite3LocateTableItem(pParse, 0, p);
+ p->iCursor = pParse->nTab++;
+ if( p->pTab==0 ){
+ rc = SQLITE_ERROR;
+ }else{
+ p->pTab->nTabRef++;
+ rc = sqlite3ViewGetColumnNames(pParse, p->pTab);
+ }
+ }
+ sNC.pSrcList = pSrc;
+ if( rc==SQLITE_OK && pStep->pWhere ){
+ rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
+ }
+ assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
+ if( pStep->pUpsert ){
+ Upsert *pUpsert = pStep->pUpsert;
+ assert( rc==SQLITE_OK );
+ pUpsert->pUpsertSrc = pSrc;
+ sNC.uNC.pUpsert = pUpsert;
+ sNC.ncFlags = NC_UUpsert;
+ rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
+ if( rc==SQLITE_OK ){
+ ExprList *pUpsertSet = pUpsert->pUpsertSet;
+ rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
+ }
+ sNC.ncFlags = 0;
+ }
+ sNC.pSrcList = 0;
+ sqlite3SrcListDelete(db, pSrc);
+ }else{
+ rc = SQLITE_NOMEM;
+ }
+ }
+ }
+ return rc;
+}
+
+/*
+** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
+** objects that are part of the trigger passed as the second argument.
+*/
+static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
+ TriggerStep *pStep;
+
+ /* Find tokens to edit in WHEN clause */
+ sqlite3WalkExpr(pWalker, pTrigger->pWhen);
+
+ /* Find tokens to edit in trigger steps */
+ for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
+ sqlite3WalkSelect(pWalker, pStep->pSelect);
+ sqlite3WalkExpr(pWalker, pStep->pWhere);
+ sqlite3WalkExprList(pWalker, pStep->pExprList);
+ if( pStep->pUpsert ){
+ Upsert *pUpsert = pStep->pUpsert;
+ sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
+ sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
+ sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
+ sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
+ }
+ }
+}
+
+/*
+** Free the contents of Parse object (*pParse). Do not free the memory
+** occupied by the Parse object itself.
+*/
+static void renameParseCleanup(Parse *pParse){
+ sqlite3 *db = pParse->db;
+ Index *pIdx;
+ if( pParse->pVdbe ){
+ sqlite3VdbeFinalize(pParse->pVdbe);
+ }
+ sqlite3DeleteTable(db, pParse->pNewTable);
+ while( (pIdx = pParse->pNewIndex)!=0 ){
+ pParse->pNewIndex = pIdx->pNext;
+ sqlite3FreeIndex(db, pIdx);
+ }
+ sqlite3DeleteTrigger(db, pParse->pNewTrigger);
+ sqlite3DbFree(db, pParse->zErrMsg);
+ renameTokenFree(db, pParse->pRename);
+ sqlite3ParserReset(pParse);
+}
+
+/*
+** SQL function:
+**
+** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
+**
+** 0. zSql: SQL statement to rewrite
+** 1. type: Type of object ("table", "view" etc.)
+** 2. object: Name of object
+** 3. Database: Database name (e.g. "main")
+** 4. Table: Table name
+** 5. iCol: Index of column to rename
+** 6. zNew: New column name
+** 7. bQuote: Non-zero if the new column name should be quoted.
+** 8. bTemp: True if zSql comes from temp schema
+**
+** Do a column rename operation on the CREATE statement given in zSql.
+** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
+** into zNew. The name should be quoted if bQuote is true.
+**
+** This function is used internally by the ALTER TABLE RENAME COLUMN command.
+** It is only accessible to SQL created using sqlite3NestedParse(). It is
+** not reachable from ordinary SQL passed into sqlite3_prepare().
+*/
+static void renameColumnFunc(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **argv
+){
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ RenameCtx sCtx;
+ const char *zSql = (const char*)sqlite3_value_text(argv[0]);
+ const char *zDb = (const char*)sqlite3_value_text(argv[3]);
+ const char *zTable = (const char*)sqlite3_value_text(argv[4]);
+ int iCol = sqlite3_value_int(argv[5]);
+ const char *zNew = (const char*)sqlite3_value_text(argv[6]);
+ int bQuote = sqlite3_value_int(argv[7]);
+ int bTemp = sqlite3_value_int(argv[8]);
+ const char *zOld;
+ int rc;
+ Parse sParse;
+ Walker sWalker;
+ Index *pIdx;
+ int i;
+ Table *pTab;
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ sqlite3_xauth xAuth = db->xAuth;
+#endif
+
+ UNUSED_PARAMETER(NotUsed);
+ if( zSql==0 ) return;
+ if( zTable==0 ) return;
+ if( zNew==0 ) return;
+ if( iCol<0 ) return;
+ sqlite3BtreeEnterAll(db);
+ pTab = sqlite3FindTable(db, zTable, zDb);
+ if( pTab==0 || iCol>=pTab->nCol ){
+ sqlite3BtreeLeaveAll(db);
+ return;
+ }
+ zOld = pTab->aCol[iCol].zName;
+ memset(&sCtx, 0, sizeof(sCtx));
+ sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
+
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ db->xAuth = 0;
+#endif
+ rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
+
+ /* Find tokens that need to be replaced. */
+ memset(&sWalker, 0, sizeof(Walker));
+ sWalker.pParse = &sParse;
+ sWalker.xExprCallback = renameColumnExprCb;
+ sWalker.xSelectCallback = renameColumnSelectCb;
+ sWalker.u.pRename = &sCtx;
+
+ sCtx.pTab = pTab;
+ if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
+ if( sParse.pNewTable ){
+ Select *pSelect = sParse.pNewTable->pSelect;
+ if( pSelect ){
+ pSelect->selFlags &= ~SF_View;
+ sParse.rc = SQLITE_OK;
+ sqlite3SelectPrep(&sParse, pSelect, 0);
+ rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
+ if( rc==SQLITE_OK ){
+ sqlite3WalkSelect(&sWalker, pSelect);
+ }
+ if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
+ }else{
+ /* A regular table */
+ int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
+ FKey *pFKey;
+ assert( sParse.pNewTable->pSelect==0 );
+ sCtx.pTab = sParse.pNewTable;
+ if( bFKOnly==0 ){
+ renameTokenFind(
+ &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
+ );
+ if( sCtx.iCol<0 ){
+ renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
+ }
+ sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
+ for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
+ sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
+ }
+ for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
+ sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
+ }
+ }
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ for(i=0; i<sParse.pNewTable->nCol; i++){
+ sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
+ }
+#endif
+
+ for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
+ for(i=0; i<pFKey->nCol; i++){
+ if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
+ renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
+ }
+ if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
+ && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
+ ){
+ renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
+ }
+ }
+ }
+ }
+ }else if( sParse.pNewIndex ){
+ sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
+ sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
+ }else{
+ /* A trigger */
+ TriggerStep *pStep;
+ rc = renameResolveTrigger(&sParse);
+ if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
+
+ for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
+ if( pStep->zTarget ){
+ Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
+ if( pTarget==pTab ){
+ if( pStep->pUpsert ){
+ ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
+ renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
+ }
+ renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
+ renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
+ }
+ }
+ }
+
+
+ /* Find tokens to edit in UPDATE OF clause */
+ if( sParse.pTriggerTab==pTab ){
+ renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
+ }
+
+ /* Find tokens to edit in various expressions and selects */
+ renameWalkTrigger(&sWalker, sParse.pNewTrigger);
+ }
+
+ assert( rc==SQLITE_OK );
+ rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
+
+renameColumnFunc_done:
+ if( rc!=SQLITE_OK ){
+ if( sParse.zErrMsg ){
+ renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
+ }else{
+ sqlite3_result_error_code(context, rc);
+ }
+ }
+
+ renameParseCleanup(&sParse);
+ renameTokenFree(db, sCtx.pList);
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ db->xAuth = xAuth;
+#endif
+ sqlite3BtreeLeaveAll(db);
+}
+
+/*
+** Walker expression callback used by "RENAME TABLE".
+*/
+static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
+ RenameCtx *p = pWalker->u.pRename;
+ if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
+ renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
+ }
+ return WRC_Continue;
+}
+
+/*
+** Walker select callback used by "RENAME TABLE".
+*/
+static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
+ int i;
+ RenameCtx *p = pWalker->u.pRename;
+ SrcList *pSrc = pSelect->pSrc;
+ if( pSelect->selFlags & SF_View ) return WRC_Prune;
+ if( pSrc==0 ){
+ assert( pWalker->pParse->db->mallocFailed );
+ return WRC_Abort;
+ }
+ for(i=0; i<pSrc->nSrc; i++){
+ struct SrcList_item *pItem = &pSrc->a[i];
+ if( pItem->pTab==p->pTab ){
+ renameTokenFind(pWalker->pParse, p, pItem->zName);
+ }
+ }
+ renameWalkWith(pWalker, pSelect);
+
+ return WRC_Continue;
+}
+
+
+/*
+** This C function implements an SQL user function that is used by SQL code
+** generated by the ALTER TABLE ... RENAME command to modify the definition
+** of any foreign key constraints that use the table being renamed as the
+** parent table. It is passed three arguments:
+**
+** 0: The database containing the table being renamed.
+** 1. type: Type of object ("table", "view" etc.)
+** 2. object: Name of object
+** 3: The complete text of the schema statement being modified,
+** 4: The old name of the table being renamed, and
+** 5: The new name of the table being renamed.
+** 6: True if the schema statement comes from the temp db.
+**
+** It returns the new schema statement. For example:
+**
+** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
+** -> 'CREATE TABLE t1(a REFERENCES t3)'
+*/
+static void renameTableFunc(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **argv
+){
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ const char *zDb = (const char*)sqlite3_value_text(argv[0]);
+ const char *zInput = (const char*)sqlite3_value_text(argv[3]);
+ const char *zOld = (const char*)sqlite3_value_text(argv[4]);
+ const char *zNew = (const char*)sqlite3_value_text(argv[5]);
+ int bTemp = sqlite3_value_int(argv[6]);
+ UNUSED_PARAMETER(NotUsed);
+
+ if( zInput && zOld && zNew ){
+ Parse sParse;
+ int rc;
+ int bQuote = 1;
+ RenameCtx sCtx;
+ Walker sWalker;
+
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ sqlite3_xauth xAuth = db->xAuth;
+ db->xAuth = 0;
+#endif
+
+ sqlite3BtreeEnterAll(db);
+
+ memset(&sCtx, 0, sizeof(RenameCtx));
+ sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
+ memset(&sWalker, 0, sizeof(Walker));
+ sWalker.pParse = &sParse;
+ sWalker.xExprCallback = renameTableExprCb;
+ sWalker.xSelectCallback = renameTableSelectCb;
+ sWalker.u.pRename = &sCtx;
+
+ rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
+
+ if( rc==SQLITE_OK ){
+ int isLegacy = (db->flags & SQLITE_LegacyAlter);
+ if( sParse.pNewTable ){
+ Table *pTab = sParse.pNewTable;
+
+ if( pTab->pSelect ){
+ if( isLegacy==0 ){
+ Select *pSelect = pTab->pSelect;
+ NameContext sNC;
+ memset(&sNC, 0, sizeof(sNC));
+ sNC.pParse = &sParse;
+
+ assert( pSelect->selFlags & SF_View );
+ pSelect->selFlags &= ~SF_View;
+ sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
+ if( sParse.nErr ){
+ rc = sParse.rc;
+ }else{
+ sqlite3WalkSelect(&sWalker, pTab->pSelect);
+ }
+ }
+ }else{
+ /* Modify any FK definitions to point to the new table. */
+#ifndef SQLITE_OMIT_FOREIGN_KEY
+ if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
+ FKey *pFKey;
+ for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
+ if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
+ renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
+ }
+ }
+ }
+#endif
+
+ /* If this is the table being altered, fix any table refs in CHECK
+ ** expressions. Also update the name that appears right after the
+ ** "CREATE [VIRTUAL] TABLE" bit. */
+ if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
+ sCtx.pTab = pTab;
+ if( isLegacy==0 ){
+ sqlite3WalkExprList(&sWalker, pTab->pCheck);
+ }
+ renameTokenFind(&sParse, &sCtx, pTab->zName);
+ }
+ }
+ }
+
+ else if( sParse.pNewIndex ){
+ renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
+ if( isLegacy==0 ){
+ sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
+ }
+ }
+
+#ifndef SQLITE_OMIT_TRIGGER
+ else{
+ Trigger *pTrigger = sParse.pNewTrigger;
+ TriggerStep *pStep;
+ if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
+ && sCtx.pTab->pSchema==pTrigger->pTabSchema
+ ){
+ renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
+ }
+
+ if( isLegacy==0 ){
+ rc = renameResolveTrigger(&sParse);
+ if( rc==SQLITE_OK ){
+ renameWalkTrigger(&sWalker, pTrigger);
+ for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
+ if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
+ renameTokenFind(&sParse, &sCtx, pStep->zTarget);
+ }
+ }
+ }
+ }
+ }
+#endif
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
+ }
+ if( rc!=SQLITE_OK ){
+ if( sParse.zErrMsg ){
+ renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
+ }else{
+ sqlite3_result_error_code(context, rc);
+ }
+ }
+
+ renameParseCleanup(&sParse);
+ renameTokenFree(db, sCtx.pList);
+ sqlite3BtreeLeaveAll(db);
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ db->xAuth = xAuth;
+#endif
+ }
+
+ return;
+}
+
+/*
+** An SQL user function that checks that there are no parse or symbol
+** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
+** After an ALTER TABLE .. RENAME operation is performed and the schema
+** reloaded, this function is called on each SQL statement in the schema
+** to ensure that it is still usable.
+**
+** 0: Database name ("main", "temp" etc.).
+** 1: SQL statement.
+** 2: Object type ("view", "table", "trigger" or "index").
+** 3: Object name.
+** 4: True if object is from temp schema.
+**
+** Unless it finds an error, this function normally returns NULL. However, it
+** returns integer value 1 if:
+**
+** * the SQL argument creates a trigger, and
+** * the table that the trigger is attached to is in database zDb.
+*/
+static void renameTableTest(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **argv
+){
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ char const *zDb = (const char*)sqlite3_value_text(argv[0]);
+ char const *zInput = (const char*)sqlite3_value_text(argv[1]);
+ int bTemp = sqlite3_value_int(argv[4]);
+ int isLegacy = (db->flags & SQLITE_LegacyAlter);
+
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ sqlite3_xauth xAuth = db->xAuth;
+ db->xAuth = 0;
+#endif
+
+ UNUSED_PARAMETER(NotUsed);
+ if( zDb && zInput ){
+ int rc;
+ Parse sParse;
+ rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
+ if( rc==SQLITE_OK ){
+ if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
+ NameContext sNC;
+ memset(&sNC, 0, sizeof(sNC));
+ sNC.pParse = &sParse;
+ sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
+ if( sParse.nErr ) rc = sParse.rc;
+ }
+
+ else if( sParse.pNewTrigger ){
+ if( isLegacy==0 ){
+ rc = renameResolveTrigger(&sParse);
+ }
+ if( rc==SQLITE_OK ){
+ int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
+ int i2 = sqlite3FindDbName(db, zDb);
+ if( i1==i2 ) sqlite3_result_int(context, 1);
+ }
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
+ }
+ renameParseCleanup(&sParse);
+ }
+
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ db->xAuth = xAuth;
+#endif
+}
+
+/*
+** Register built-in functions used to help implement ALTER TABLE
+*/
+SQLITE_PRIVATE void sqlite3AlterFunctions(void){
+ static FuncDef aAlterTableFuncs[] = {
+ INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
+ INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
+ INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest),
+ };
+ sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
+}
+#endif /* SQLITE_ALTER_TABLE */
+
+/************** End of alter.c ***********************************************/
+/************** Begin file analyze.c *****************************************/
+/*
+** 2005-07-08
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code associated with the ANALYZE command.
+**
+** The ANALYZE command gather statistics about the content of tables
+** and indices. These statistics are made available to the query planner
+** to help it make better decisions about how to perform queries.
+**
+** The following system tables are or have been supported:
+**
+** CREATE TABLE sqlite_stat1(tbl, idx, stat);
+** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
+** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
+** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
+**
+** Additional tables might be added in future releases of SQLite.
+** The sqlite_stat2 table is not created or used unless the SQLite version
+** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
+** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
+** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
+** created and used by SQLite versions 3.7.9 through 3.29.0 when
+** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
+** is a superset of sqlite_stat2 and is also now deprecated. The
+** sqlite_stat4 is an enhanced version of sqlite_stat3 and is only
+** available when compiled with SQLITE_ENABLE_STAT4 and in SQLite
+** versions 3.8.1 and later. STAT4 is the only variant that is still
+** supported.
+**
+** For most applications, sqlite_stat1 provides all the statistics required
+** for the query planner to make good choices.
+**
+** Format of sqlite_stat1:
+**
+** There is normally one row per index, with the index identified by the
+** name in the idx column. The tbl column is the name of the table to
+** which the index belongs. In each such row, the stat column will be
+** a string consisting of a list of integers. The first integer in this
+** list is the number of rows in the index. (This is the same as the
+** number of rows in the table, except for partial indices.) The second
+** integer is the average number of rows in the index that have the same
+** value in the first column of the index. The third integer is the average
+** number of rows in the index that have the same value for the first two
+** columns. The N-th integer (for N>1) is the average number of rows in
+** the index which have the same value for the first N-1 columns. For
+** a K-column index, there will be K+1 integers in the stat column. If
+** the index is unique, then the last integer will be 1.
+**
+** The list of integers in the stat column can optionally be followed
+** by the keyword "unordered". The "unordered" keyword, if it is present,
+** must be separated from the last integer by a single space. If the
+** "unordered" keyword is present, then the query planner assumes that
+** the index is unordered and will not use the index for a range query.
+**
+** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
+** column contains a single integer which is the (estimated) number of
+** rows in the table identified by sqlite_stat1.tbl.
+**
+** Format of sqlite_stat2:
+**
+** The sqlite_stat2 is only created and is only used if SQLite is compiled
+** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
+** 3.6.18 and 3.7.8. The "stat2" table contains additional information
+** about the distribution of keys within an index. The index is identified by
+** the "idx" column and the "tbl" column is the name of the table to which
+** the index belongs. There are usually 10 rows in the sqlite_stat2
+** table for each index.
+**
+** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
+** inclusive are samples of the left-most key value in the index taken at
+** evenly spaced points along the index. Let the number of samples be S
+** (10 in the standard build) and let C be the number of rows in the index.
+** Then the sampled rows are given by:
+**
+** rownumber = (i*C*2 + C)/(S*2)
+**
+** For i between 0 and S-1. Conceptually, the index space is divided into
+** S uniform buckets and the samples are the middle row from each bucket.
+**
+** The format for sqlite_stat2 is recorded here for legacy reference. This
+** version of SQLite does not support sqlite_stat2. It neither reads nor
+** writes the sqlite_stat2 table. This version of SQLite only supports
+** sqlite_stat3.
+**
+** Format for sqlite_stat3:
+**
+** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
+** sqlite_stat4 format will be described first. Further information
+** about sqlite_stat3 follows the sqlite_stat4 description.
+**
+** Format for sqlite_stat4:
+**
+** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
+** to aid the query planner in choosing good indices based on the values
+** that indexed columns are compared against in the WHERE clauses of
+** queries.
+**
+** The sqlite_stat4 table contains multiple entries for each index.
+** The idx column names the index and the tbl column is the table of the
+** index. If the idx and tbl columns are the same, then the sample is
+** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
+** binary encoding of a key from the index. The nEq column is a
+** list of integers. The first integer is the approximate number
+** of entries in the index whose left-most column exactly matches
+** the left-most column of the sample. The second integer in nEq
+** is the approximate number of entries in the index where the
+** first two columns match the first two columns of the sample.
+** And so forth. nLt is another list of integers that show the approximate
+** number of entries that are strictly less than the sample. The first
+** integer in nLt contains the number of entries in the index where the
+** left-most column is less than the left-most column of the sample.
+** The K-th integer in the nLt entry is the number of index entries
+** where the first K columns are less than the first K columns of the
+** sample. The nDLt column is like nLt except that it contains the
+** number of distinct entries in the index that are less than the
+** sample.
+**
+** There can be an arbitrary number of sqlite_stat4 entries per index.
+** The ANALYZE command will typically generate sqlite_stat4 tables
+** that contain between 10 and 40 samples which are distributed across
+** the key space, though not uniformly, and which include samples with
+** large nEq values.
+**
+** Format for sqlite_stat3 redux:
+**
+** The sqlite_stat3 table is like sqlite_stat4 except that it only
+** looks at the left-most column of the index. The sqlite_stat3.sample
+** column contains the actual value of the left-most column instead
+** of a blob encoding of the complete index key as is found in
+** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
+** all contain just a single integer which is the same as the first
+** integer in the equivalent columns in sqlite_stat4.
+*/
+#ifndef SQLITE_OMIT_ANALYZE
+/* #include "sqliteInt.h" */
+
+#if defined(SQLITE_ENABLE_STAT4)
+# define IsStat4 1
+#else
+# define IsStat4 0
+# undef SQLITE_STAT4_SAMPLES
+# define SQLITE_STAT4_SAMPLES 1
+#endif
+
+/*
+** This routine generates code that opens the sqlite_statN tables.
+** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
+** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
+** appropriate compile-time options are provided.
+**
+** If the sqlite_statN tables do not previously exist, it is created.
+**
+** Argument zWhere may be a pointer to a buffer containing a table name,
+** or it may be a NULL pointer. If it is not NULL, then all entries in
+** the sqlite_statN tables associated with the named table are deleted.
+** If zWhere==0, then code is generated to delete all stat table entries.
+*/
+static void openStatTable(
+ Parse *pParse, /* Parsing context */
+ int iDb, /* The database we are looking in */
+ int iStatCur, /* Open the sqlite_stat1 table on this cursor */
+ const char *zWhere, /* Delete entries for this table or index */
+ const char *zWhereType /* Either "tbl" or "idx" */
+){
+ static const struct {
+ const char *zName;
+ const char *zCols;
+ } aTable[] = {
+ { "sqlite_stat1", "tbl,idx,stat" },
+#if defined(SQLITE_ENABLE_STAT4)
+ { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
+#else
+ { "sqlite_stat4", 0 },
+#endif
+ { "sqlite_stat3", 0 },
+ };
+ int i;
+ sqlite3 *db = pParse->db;
+ Db *pDb;
+ Vdbe *v = sqlite3GetVdbe(pParse);
+ u32 aRoot[ArraySize(aTable)];
+ u8 aCreateTbl[ArraySize(aTable)];
+#ifdef SQLITE_ENABLE_STAT4
+ const int nToOpen = OptimizationEnabled(db,SQLITE_Stat4) ? 2 : 1;
+#else
+ const int nToOpen = 1;
+#endif
+
+ if( v==0 ) return;
+ assert( sqlite3BtreeHoldsAllMutexes(db) );
+ assert( sqlite3VdbeDb(v)==db );
+ pDb = &db->aDb[iDb];
+
+ /* Create new statistic tables if they do not exist, or clear them
+ ** if they do already exist.
+ */
+ for(i=0; i<ArraySize(aTable); i++){
+ const char *zTab = aTable[i].zName;
+ Table *pStat;
+ aCreateTbl[i] = 0;
+ if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
+ if( i<nToOpen ){
+ /* The sqlite_statN table does not exist. Create it. Note that a
+ ** side-effect of the CREATE TABLE statement is to leave the rootpage
+ ** of the new table in register pParse->regRoot. This is important
+ ** because the OpenWrite opcode below will be needing it. */
+ sqlite3NestedParse(pParse,
+ "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
+ );
+ aRoot[i] = (u32)pParse->regRoot;
+ aCreateTbl[i] = OPFLAG_P2ISREG;
+ }
+ }else{
+ /* The table already exists. If zWhere is not NULL, delete all entries
+ ** associated with the table zWhere. If zWhere is NULL, delete the
+ ** entire contents of the table. */
+ aRoot[i] = pStat->tnum;
+ sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
+ if( zWhere ){
+ sqlite3NestedParse(pParse,
+ "DELETE FROM %Q.%s WHERE %s=%Q",
+ pDb->zDbSName, zTab, zWhereType, zWhere
+ );
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+ }else if( db->xPreUpdateCallback ){
+ sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab);
+#endif
+ }else{
+ /* The sqlite_stat[134] table already exists. Delete all rows. */
+ sqlite3VdbeAddOp2(v, OP_Clear, (int)aRoot[i], iDb);
+ }
+ }
+ }
+
+ /* Open the sqlite_stat[134] tables for writing. */
+ for(i=0; i<nToOpen; i++){
+ assert( i<ArraySize(aTable) );
+ sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, (int)aRoot[i], iDb, 3);
+ sqlite3VdbeChangeP5(v, aCreateTbl[i]);
+ VdbeComment((v, aTable[i].zName));
+ }
+}
+
+/*
+** Recommended number of samples for sqlite_stat4
+*/
+#ifndef SQLITE_STAT4_SAMPLES
+# define SQLITE_STAT4_SAMPLES 24
+#endif
+
+/*
+** Three SQL functions - stat_init(), stat_push(), and stat_get() -
+** share an instance of the following structure to hold their state
+** information.
+*/
+typedef struct StatAccum StatAccum;
+typedef struct StatSample StatSample;
+struct StatSample {
+ tRowcnt *anEq; /* sqlite_stat4.nEq */
+ tRowcnt *anDLt; /* sqlite_stat4.nDLt */
+#ifdef SQLITE_ENABLE_STAT4
+ tRowcnt *anLt; /* sqlite_stat4.nLt */
+ union {
+ i64 iRowid; /* Rowid in main table of the key */
+ u8 *aRowid; /* Key for WITHOUT ROWID tables */
+ } u;
+ u32 nRowid; /* Sizeof aRowid[] */
+ u8 isPSample; /* True if a periodic sample */
+ int iCol; /* If !isPSample, the reason for inclusion */
+ u32 iHash; /* Tiebreaker hash */
+#endif
+};
+struct StatAccum {
+ sqlite3 *db; /* Database connection, for malloc() */
+ tRowcnt nEst; /* Estimated number of rows */
+ tRowcnt nRow; /* Number of rows visited so far */
+ int nLimit; /* Analysis row-scan limit */
+ int nCol; /* Number of columns in index + pk/rowid */
+ int nKeyCol; /* Number of index columns w/o the pk/rowid */
+ u8 nSkipAhead; /* Number of times of skip-ahead */
+ StatSample current; /* Current row as a StatSample */
+#ifdef SQLITE_ENABLE_STAT4
+ tRowcnt nPSample; /* How often to do a periodic sample */
+ int mxSample; /* Maximum number of samples to accumulate */
+ u32 iPrn; /* Pseudo-random number used for sampling */
+ StatSample *aBest; /* Array of nCol best samples */
+ int iMin; /* Index in a[] of entry with minimum score */
+ int nSample; /* Current number of samples */
+ int nMaxEqZero; /* Max leading 0 in anEq[] for any a[] entry */
+ int iGet; /* Index of current sample accessed by stat_get() */
+ StatSample *a; /* Array of mxSample StatSample objects */
+#endif
+};
+
+/* Reclaim memory used by a StatSample
+*/
+#ifdef SQLITE_ENABLE_STAT4
+static void sampleClear(sqlite3 *db, StatSample *p){
+ assert( db!=0 );
+ if( p->nRowid ){
+ sqlite3DbFree(db, p->u.aRowid);
+ p->nRowid = 0;
+ }
+}
+#endif
+
+/* Initialize the BLOB value of a ROWID
+*/
+#ifdef SQLITE_ENABLE_STAT4
+static void sampleSetRowid(sqlite3 *db, StatSample *p, int n, const u8 *pData){
+ assert( db!=0 );
+ if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
+ p->u.aRowid = sqlite3DbMallocRawNN(db, n);
+ if( p->u.aRowid ){
+ p->nRowid = n;
+ memcpy(p->u.aRowid, pData, n);
+ }else{
+ p->nRowid = 0;
+ }
+}
+#endif
+
+/* Initialize the INTEGER value of a ROWID.
+*/
+#ifdef SQLITE_ENABLE_STAT4
+static void sampleSetRowidInt64(sqlite3 *db, StatSample *p, i64 iRowid){
+ assert( db!=0 );
+ if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
+ p->nRowid = 0;
+ p->u.iRowid = iRowid;
+}
+#endif
+
+
+/*
+** Copy the contents of object (*pFrom) into (*pTo).
+*/
+#ifdef SQLITE_ENABLE_STAT4
+static void sampleCopy(StatAccum *p, StatSample *pTo, StatSample *pFrom){
+ pTo->isPSample = pFrom->isPSample;
+ pTo->iCol = pFrom->iCol;
+ pTo->iHash = pFrom->iHash;
+ memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
+ memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
+ memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
+ if( pFrom->nRowid ){
+ sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
+ }else{
+ sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
+ }
+}
+#endif
+
+/*
+** Reclaim all memory of a StatAccum structure.
+*/
+static void statAccumDestructor(void *pOld){
+ StatAccum *p = (StatAccum*)pOld;
+#ifdef SQLITE_ENABLE_STAT4
+ if( p->mxSample ){
+ int i;
+ for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
+ for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
+ sampleClear(p->db, &p->current);
+ }
+#endif
+ sqlite3DbFree(p->db, p);
+}
+
+/*
+** Implementation of the stat_init(N,K,C,L) SQL function. The four parameters
+** are:
+** N: The number of columns in the index including the rowid/pk (note 1)
+** K: The number of columns in the index excluding the rowid/pk.
+** C: Estimated number of rows in the index
+** L: A limit on the number of rows to scan, or 0 for no-limit
+**
+** Note 1: In the special case of the covering index that implements a
+** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
+** total number of columns in the table.
+**
+** For indexes on ordinary rowid tables, N==K+1. But for indexes on
+** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
+** PRIMARY KEY of the table. The covering index that implements the
+** original WITHOUT ROWID table as N==K as a special case.
+**
+** This routine allocates the StatAccum object in heap memory. The return
+** value is a pointer to the StatAccum object. The datatype of the
+** return value is BLOB, but it is really just a pointer to the StatAccum
+** object.
+*/
+static void statInit(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ StatAccum *p;
+ int nCol; /* Number of columns in index being sampled */
+ int nKeyCol; /* Number of key columns */
+ int nColUp; /* nCol rounded up for alignment */
+ int n; /* Bytes of space to allocate */
+ sqlite3 *db = sqlite3_context_db_handle(context); /* Database connection */
+#ifdef SQLITE_ENABLE_STAT4
+ /* Maximum number of samples. 0 if STAT4 data is not collected */
+ int mxSample = OptimizationEnabled(db,SQLITE_Stat4) ?SQLITE_STAT4_SAMPLES :0;
+#endif
+
+ /* Decode the three function arguments */
+ UNUSED_PARAMETER(argc);
+ nCol = sqlite3_value_int(argv[0]);
+ assert( nCol>0 );
+ nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
+ nKeyCol = sqlite3_value_int(argv[1]);
+ assert( nKeyCol<=nCol );
+ assert( nKeyCol>0 );
+
+ /* Allocate the space required for the StatAccum object */
+ n = sizeof(*p)
+ + sizeof(tRowcnt)*nColUp /* StatAccum.anEq */
+ + sizeof(tRowcnt)*nColUp; /* StatAccum.anDLt */
+#ifdef SQLITE_ENABLE_STAT4
+ if( mxSample ){
+ n += sizeof(tRowcnt)*nColUp /* StatAccum.anLt */
+ + sizeof(StatSample)*(nCol+mxSample) /* StatAccum.aBest[], a[] */
+ + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample);
+ }
+#endif
+ db = sqlite3_context_db_handle(context);
+ p = sqlite3DbMallocZero(db, n);
+ if( p==0 ){
+ sqlite3_result_error_nomem(context);
+ return;
+ }
+
+ p->db = db;
+ p->nEst = sqlite3_value_int64(argv[2]);
+ p->nRow = 0;
+ p->nLimit = sqlite3_value_int64(argv[3]);
+ p->nCol = nCol;
+ p->nKeyCol = nKeyCol;
+ p->nSkipAhead = 0;
+ p->current.anDLt = (tRowcnt*)&p[1];
+ p->current.anEq = &p->current.anDLt[nColUp];
+
+#ifdef SQLITE_ENABLE_STAT4
+ p->mxSample = p->nLimit==0 ? mxSample : 0;
+ if( mxSample ){
+ u8 *pSpace; /* Allocated space not yet assigned */
+ int i; /* Used to iterate through p->aSample[] */
+
+ p->iGet = -1;
+ p->nPSample = (tRowcnt)(p->nEst/(mxSample/3+1) + 1);
+ p->current.anLt = &p->current.anEq[nColUp];
+ p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
+
+ /* Set up the StatAccum.a[] and aBest[] arrays */
+ p->a = (struct StatSample*)&p->current.anLt[nColUp];
+ p->aBest = &p->a[mxSample];
+ pSpace = (u8*)(&p->a[mxSample+nCol]);
+ for(i=0; i<(mxSample+nCol); i++){
+ p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
+ p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
+ p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
+ }
+ assert( (pSpace - (u8*)p)==n );
+
+ for(i=0; i<nCol; i++){
+ p->aBest[i].iCol = i;
+ }
+ }
+#endif
+
+ /* Return a pointer to the allocated object to the caller. Note that
+ ** only the pointer (the 2nd parameter) matters. The size of the object
+ ** (given by the 3rd parameter) is never used and can be any positive
+ ** value. */
+ sqlite3_result_blob(context, p, sizeof(*p), statAccumDestructor);
+}
+static const FuncDef statInitFuncdef = {
+ 4, /* nArg */
+ SQLITE_UTF8, /* funcFlags */
+ 0, /* pUserData */
+ 0, /* pNext */
+ statInit, /* xSFunc */
+ 0, /* xFinalize */
+ 0, 0, /* xValue, xInverse */
+ "stat_init", /* zName */
+ {0}
+};
+
+#ifdef SQLITE_ENABLE_STAT4
+/*
+** pNew and pOld are both candidate non-periodic samples selected for
+** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
+** considering only any trailing columns and the sample hash value, this
+** function returns true if sample pNew is to be preferred over pOld.
+** In other words, if we assume that the cardinalities of the selected
+** column for pNew and pOld are equal, is pNew to be preferred over pOld.
+**
+** This function assumes that for each argument sample, the contents of
+** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
+*/
+static int sampleIsBetterPost(
+ StatAccum *pAccum,
+ StatSample *pNew,
+ StatSample *pOld
+){
+ int nCol = pAccum->nCol;
+ int i;
+ assert( pNew->iCol==pOld->iCol );
+ for(i=pNew->iCol+1; i<nCol; i++){
+ if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
+ if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
+ }
+ if( pNew->iHash>pOld->iHash ) return 1;
+ return 0;
+}
+#endif
+
+#ifdef SQLITE_ENABLE_STAT4
+/*
+** Return true if pNew is to be preferred over pOld.
+**
+** This function assumes that for each argument sample, the contents of
+** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
+*/
+static int sampleIsBetter(
+ StatAccum *pAccum,
+ StatSample *pNew,
+ StatSample *pOld
+){
+ tRowcnt nEqNew = pNew->anEq[pNew->iCol];
+ tRowcnt nEqOld = pOld->anEq[pOld->iCol];
+
+ assert( pOld->isPSample==0 && pNew->isPSample==0 );
+ assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
+
+ if( (nEqNew>nEqOld) ) return 1;
+ if( nEqNew==nEqOld ){
+ if( pNew->iCol<pOld->iCol ) return 1;
+ return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
+ }
+ return 0;
+}
+
+/*
+** Copy the contents of sample *pNew into the p->a[] array. If necessary,
+** remove the least desirable sample from p->a[] to make room.
+*/
+static void sampleInsert(StatAccum *p, StatSample *pNew, int nEqZero){
+ StatSample *pSample = 0;
+ int i;
+
+ assert( IsStat4 || nEqZero==0 );
+
+ /* StatAccum.nMaxEqZero is set to the maximum number of leading 0
+ ** values in the anEq[] array of any sample in StatAccum.a[]. In
+ ** other words, if nMaxEqZero is n, then it is guaranteed that there
+ ** are no samples with StatSample.anEq[m]==0 for (m>=n). */
+ if( nEqZero>p->nMaxEqZero ){
+ p->nMaxEqZero = nEqZero;
+ }
+ if( pNew->isPSample==0 ){
+ StatSample *pUpgrade = 0;
+ assert( pNew->anEq[pNew->iCol]>0 );
+
+ /* This sample is being added because the prefix that ends in column
+ ** iCol occurs many times in the table. However, if we have already
+ ** added a sample that shares this prefix, there is no need to add
+ ** this one. Instead, upgrade the priority of the highest priority
+ ** existing sample that shares this prefix. */
+ for(i=p->nSample-1; i>=0; i--){
+ StatSample *pOld = &p->a[i];
+ if( pOld->anEq[pNew->iCol]==0 ){
+ if( pOld->isPSample ) return;
+ assert( pOld->iCol>pNew->iCol );
+ assert( sampleIsBetter(p, pNew, pOld) );
+ if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
+ pUpgrade = pOld;
+ }
+ }
+ }
+ if( pUpgrade ){
+ pUpgrade->iCol = pNew->iCol;
+ pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
+ goto find_new_min;
+ }
+ }
+
+ /* If necessary, remove sample iMin to make room for the new sample. */
+ if( p->nSample>=p->mxSample ){
+ StatSample *pMin = &p->a[p->iMin];
+ tRowcnt *anEq = pMin->anEq;
+ tRowcnt *anLt = pMin->anLt;
+ tRowcnt *anDLt = pMin->anDLt;
+ sampleClear(p->db, pMin);
+ memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
+ pSample = &p->a[p->nSample-1];
+ pSample->nRowid = 0;
+ pSample->anEq = anEq;
+ pSample->anDLt = anDLt;
+ pSample->anLt = anLt;
+ p->nSample = p->mxSample-1;
+ }
+
+ /* The "rows less-than" for the rowid column must be greater than that
+ ** for the last sample in the p->a[] array. Otherwise, the samples would
+ ** be out of order. */
+ assert( p->nSample==0
+ || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
+
+ /* Insert the new sample */
+ pSample = &p->a[p->nSample];
+ sampleCopy(p, pSample, pNew);
+ p->nSample++;
+
+ /* Zero the first nEqZero entries in the anEq[] array. */
+ memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
+
+find_new_min:
+ if( p->nSample>=p->mxSample ){
+ int iMin = -1;
+ for(i=0; i<p->mxSample; i++){
+ if( p->a[i].isPSample ) continue;
+ if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
+ iMin = i;
+ }
+ }
+ assert( iMin>=0 );
+ p->iMin = iMin;
+ }
+}
+#endif /* SQLITE_ENABLE_STAT4 */
+
+#ifdef SQLITE_ENABLE_STAT4
+/*
+** Field iChng of the index being scanned has changed. So at this point
+** p->current contains a sample that reflects the previous row of the
+** index. The value of anEq[iChng] and subsequent anEq[] elements are
+** correct at this point.
+*/
+static void samplePushPrevious(StatAccum *p, int iChng){
+ int i;
+
+ /* Check if any samples from the aBest[] array should be pushed
+ ** into IndexSample.a[] at this point. */
+ for(i=(p->nCol-2); i>=iChng; i--){
+ StatSample *pBest = &p->aBest[i];
+ pBest->anEq[i] = p->current.anEq[i];
+ if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
+ sampleInsert(p, pBest, i);
+ }
+ }
+
+ /* Check that no sample contains an anEq[] entry with an index of
+ ** p->nMaxEqZero or greater set to zero. */
+ for(i=p->nSample-1; i>=0; i--){
+ int j;
+ for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
+ }
+
+ /* Update the anEq[] fields of any samples already collected. */
+ if( iChng<p->nMaxEqZero ){
+ for(i=p->nSample-1; i>=0; i--){
+ int j;
+ for(j=iChng; j<p->nCol; j++){
+ if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
+ }
+ }
+ p->nMaxEqZero = iChng;
+ }
+}
+#endif /* SQLITE_ENABLE_STAT4 */
+
+/*
+** Implementation of the stat_push SQL function: stat_push(P,C,R)
+** Arguments:
+**
+** P Pointer to the StatAccum object created by stat_init()
+** C Index of left-most column to differ from previous row
+** R Rowid for the current row. Might be a key record for
+** WITHOUT ROWID tables.
+**
+** The purpose of this routine is to collect statistical data and/or
+** samples from the index being analyzed into the StatAccum object.
+** The stat_get() SQL function will be used afterwards to
+** retrieve the information gathered.
+**
+** This SQL function usually returns NULL, but might return an integer
+** if it wants the byte-code to do special processing.
+**
+** The R parameter is only used for STAT4
+*/
+static void statPush(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ int i;
+
+ /* The three function arguments */
+ StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]);
+ int iChng = sqlite3_value_int(argv[1]);
+
+ UNUSED_PARAMETER( argc );
+ UNUSED_PARAMETER( context );
+ assert( p->nCol>0 );
+ assert( iChng<p->nCol );
+
+ if( p->nRow==0 ){
+ /* This is the first call to this function. Do initialization. */
+ for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
+ }else{
+ /* Second and subsequent calls get processed here */
+#ifdef SQLITE_ENABLE_STAT4
+ if( p->mxSample ) samplePushPrevious(p, iChng);
+#endif
+
+ /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
+ ** to the current row of the index. */
+ for(i=0; i<iChng; i++){
+ p->current.anEq[i]++;
+ }
+ for(i=iChng; i<p->nCol; i++){
+ p->current.anDLt[i]++;
+#ifdef SQLITE_ENABLE_STAT4
+ if( p->mxSample ) p->current.anLt[i] += p->current.anEq[i];
+#endif
+ p->current.anEq[i] = 1;
+ }
+ }
+
+ p->nRow++;
+#ifdef SQLITE_ENABLE_STAT4
+ if( p->mxSample ){
+ tRowcnt nLt;
+ if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
+ sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
+ }else{
+ sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
+ sqlite3_value_blob(argv[2]));
+ }
+ p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
+
+ nLt = p->current.anLt[p->nCol-1];
+ /* Check if this is to be a periodic sample. If so, add it. */
+ if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
+ p->current.isPSample = 1;
+ p->current.iCol = 0;
+ sampleInsert(p, &p->current, p->nCol-1);
+ p->current.isPSample = 0;
+ }
+
+ /* Update the aBest[] array. */
+ for(i=0; i<(p->nCol-1); i++){
+ p->current.iCol = i;
+ if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
+ sampleCopy(p, &p->aBest[i], &p->current);
+ }
+ }
+ }else
+#endif
+ if( p->nLimit && p->nRow>(tRowcnt)p->nLimit*(p->nSkipAhead+1) ){
+ p->nSkipAhead++;
+ sqlite3_result_int(context, p->current.anDLt[0]>0);
+ }
+}
+
+static const FuncDef statPushFuncdef = {
+ 2+IsStat4, /* nArg */
+ SQLITE_UTF8, /* funcFlags */
+ 0, /* pUserData */
+ 0, /* pNext */
+ statPush, /* xSFunc */
+ 0, /* xFinalize */
+ 0, 0, /* xValue, xInverse */
+ "stat_push", /* zName */
+ {0}
+};
+
+#define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
+#define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
+#define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
+#define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
+#define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
+
+/*
+** Implementation of the stat_get(P,J) SQL function. This routine is
+** used to query statistical information that has been gathered into
+** the StatAccum object by prior calls to stat_push(). The P parameter
+** has type BLOB but it is really just a pointer to the StatAccum object.
+** The content to returned is determined by the parameter J
+** which is one of the STAT_GET_xxxx values defined above.
+**
+** The stat_get(P,J) function is not available to generic SQL. It is
+** inserted as part of a manually constructed bytecode program. (See
+** the callStatGet() routine below.) It is guaranteed that the P
+** parameter will always be a pointer to a StatAccum object, never a
+** NULL.
+**
+** If STAT4 is not enabled, then J is always
+** STAT_GET_STAT1 and is hence omitted and this routine becomes
+** a one-parameter function, stat_get(P), that always returns the
+** stat1 table entry information.
+*/
+static void statGet(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]);
+#ifdef SQLITE_ENABLE_STAT4
+ /* STAT4 has a parameter on this routine. */
+ int eCall = sqlite3_value_int(argv[1]);
+ assert( argc==2 );
+ assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
+ || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
+ || eCall==STAT_GET_NDLT
+ );
+ assert( eCall==STAT_GET_STAT1 || p->mxSample );
+ if( eCall==STAT_GET_STAT1 )
+#else
+ assert( argc==1 );
+#endif
+ {
+ /* Return the value to store in the "stat" column of the sqlite_stat1
+ ** table for this index.
+ **
+ ** The value is a string composed of a list of integers describing
+ ** the index. The first integer in the list is the total number of
+ ** entries in the index. There is one additional integer in the list
+ ** for each indexed column. This additional integer is an estimate of
+ ** the number of rows matched by a equality query on the index using
+ ** a key with the corresponding number of fields. In other words,
+ ** if the index is on columns (a,b) and the sqlite_stat1 value is
+ ** "100 10 2", then SQLite estimates that:
+ **
+ ** * the index contains 100 rows,
+ ** * "WHERE a=?" matches 10 rows, and
+ ** * "WHERE a=? AND b=?" matches 2 rows.
+ **
+ ** If D is the count of distinct values and K is the total number of
+ ** rows, then each estimate is computed as:
+ **
+ ** I = (K+D-1)/D
+ */
+ char *z;
+ int i;
+
+ char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
+ if( zRet==0 ){
+ sqlite3_result_error_nomem(context);
+ return;
+ }
+
+ sqlite3_snprintf(24, zRet, "%llu",
+ p->nSkipAhead ? (u64)p->nEst : (u64)p->nRow);
+ z = zRet + sqlite3Strlen30(zRet);
+ for(i=0; i<p->nKeyCol; i++){
+ u64 nDistinct = p->current.anDLt[i] + 1;
+ u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
+ sqlite3_snprintf(24, z, " %llu", iVal);
+ z += sqlite3Strlen30(z);
+ assert( p->current.anEq[i] );
+ }
+ assert( z[0]=='\0' && z>zRet );
+
+ sqlite3_result_text(context, zRet, -1, sqlite3_free);
+ }
+#ifdef SQLITE_ENABLE_STAT4
+ else if( eCall==STAT_GET_ROWID ){
+ if( p->iGet<0 ){
+ samplePushPrevious(p, 0);
+ p->iGet = 0;
+ }
+ if( p->iGet<p->nSample ){
+ StatSample *pS = p->a + p->iGet;
+ if( pS->nRowid==0 ){
+ sqlite3_result_int64(context, pS->u.iRowid);
+ }else{
+ sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
+ SQLITE_TRANSIENT);
+ }
+ }
+ }else{
+ tRowcnt *aCnt = 0;
+
+ assert( p->iGet<p->nSample );
+ switch( eCall ){
+ case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
+ case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
+ default: {
+ aCnt = p->a[p->iGet].anDLt;
+ p->iGet++;
+ break;
+ }
+ }
+
+ {
+ char *zRet = sqlite3MallocZero(p->nCol * 25);
+ if( zRet==0 ){
+ sqlite3_result_error_nomem(context);
+ }else{
+ int i;
+ char *z = zRet;
+ for(i=0; i<p->nCol; i++){
+ sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
+ z += sqlite3Strlen30(z);
+ }
+ assert( z[0]=='\0' && z>zRet );
+ z[-1] = '\0';
+ sqlite3_result_text(context, zRet, -1, sqlite3_free);
+ }
+ }
+ }
+#endif /* SQLITE_ENABLE_STAT4 */
+#ifndef SQLITE_DEBUG
+ UNUSED_PARAMETER( argc );
+#endif
+}
+static const FuncDef statGetFuncdef = {
+ 1+IsStat4, /* nArg */
+ SQLITE_UTF8, /* funcFlags */
+ 0, /* pUserData */
+ 0, /* pNext */
+ statGet, /* xSFunc */
+ 0, /* xFinalize */
+ 0, 0, /* xValue, xInverse */
+ "stat_get", /* zName */
+ {0}
+};
+
+static void callStatGet(Parse *pParse, int regStat, int iParam, int regOut){
+#ifdef SQLITE_ENABLE_STAT4
+ sqlite3VdbeAddOp2(pParse->pVdbe, OP_Integer, iParam, regStat+1);
+#elif SQLITE_DEBUG
+ assert( iParam==STAT_GET_STAT1 );
+#else
+ UNUSED_PARAMETER( iParam );
+#endif
+ assert( regOut!=regStat && regOut!=regStat+1 );
+ sqlite3VdbeAddFunctionCall(pParse, 0, regStat, regOut, 1+IsStat4,
+ &statGetFuncdef, 0);
+}
+
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+/* Add a comment to the most recent VDBE opcode that is the name
+** of the k-th column of the pIdx index.
+*/
+static void analyzeVdbeCommentIndexWithColumnName(
+ Vdbe *v, /* Prepared statement under construction */
+ Index *pIdx, /* Index whose column is being loaded */
+ int k /* Which column index */
+){
+ int i; /* Index of column in the table */
+ assert( k>=0 && k<pIdx->nColumn );
+ i = pIdx->aiColumn[k];
+ if( NEVER(i==XN_ROWID) ){
+ VdbeComment((v,"%s.rowid",pIdx->zName));
+ }else if( i==XN_EXPR ){
+ VdbeComment((v,"%s.expr(%d)",pIdx->zName, k));
+ }else{
+ VdbeComment((v,"%s.%s", pIdx->zName, pIdx->pTable->aCol[i].zName));
+ }
+}
+#else
+# define analyzeVdbeCommentIndexWithColumnName(a,b,c)
+#endif /* SQLITE_DEBUG */
+
+/*
+** Generate code to do an analysis of all indices associated with
+** a single table.
+*/
+static void analyzeOneTable(
+ Parse *pParse, /* Parser context */
+ Table *pTab, /* Table whose indices are to be analyzed */
+ Index *pOnlyIdx, /* If not NULL, only analyze this one index */
+ int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
+ int iMem, /* Available memory locations begin here */
+ int iTab /* Next available cursor */
+){
+ sqlite3 *db = pParse->db; /* Database handle */
+ Index *pIdx; /* An index to being analyzed */
+ int iIdxCur; /* Cursor open on index being analyzed */
+ int iTabCur; /* Table cursor */
+ Vdbe *v; /* The virtual machine being built up */
+ int i; /* Loop counter */
+ int jZeroRows = -1; /* Jump from here if number of rows is zero */
+ int iDb; /* Index of database containing pTab */
+ u8 needTableCnt = 1; /* True to count the table */
+ int regNewRowid = iMem++; /* Rowid for the inserted record */
+ int regStat = iMem++; /* Register to hold StatAccum object */
+ int regChng = iMem++; /* Index of changed index field */
+ int regRowid = iMem++; /* Rowid argument passed to stat_push() */
+ int regTemp = iMem++; /* Temporary use register */
+ int regTemp2 = iMem++; /* Second temporary use register */
+ int regTabname = iMem++; /* Register containing table name */
+ int regIdxname = iMem++; /* Register containing index name */
+ int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
+ int regPrev = iMem; /* MUST BE LAST (see below) */
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+ Table *pStat1 = 0;
+#endif
+
+ pParse->nMem = MAX(pParse->nMem, iMem);
+ v = sqlite3GetVdbe(pParse);
+ if( v==0 || NEVER(pTab==0) ){
+ return;
+ }
+ if( pTab->tnum==0 ){
+ /* Do not gather statistics on views or virtual tables */
+ return;
+ }
+ if( sqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){
+ /* Do not gather statistics on system tables */
+ return;
+ }
+ assert( sqlite3BtreeHoldsAllMutexes(db) );
+ iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ assert( iDb>=0 );
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
+ db->aDb[iDb].zDbSName ) ){
+ return;
+ }
+#endif
+
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+ if( db->xPreUpdateCallback ){
+ pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13);
+ if( pStat1==0 ) return;
+ pStat1->zName = (char*)&pStat1[1];
+ memcpy(pStat1->zName, "sqlite_stat1", 13);
+ pStat1->nCol = 3;
+ pStat1->iPKey = -1;
+ sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB);
+ }
+#endif
+
+ /* Establish a read-lock on the table at the shared-cache level.
+ ** Open a read-only cursor on the table. Also allocate a cursor number
+ ** to use for scanning indexes (iIdxCur). No index cursor is opened at
+ ** this time though. */
+ sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
+ iTabCur = iTab++;
+ iIdxCur = iTab++;
+ pParse->nTab = MAX(pParse->nTab, iTab);
+ sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
+ sqlite3VdbeLoadString(v, regTabname, pTab->zName);
+
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+ int nCol; /* Number of columns in pIdx. "N" */
+ int addrRewind; /* Address of "OP_Rewind iIdxCur" */
+ int addrNextRow; /* Address of "next_row:" */
+ const char *zIdxName; /* Name of the index */
+ int nColTest; /* Number of columns to test for changes */
+
+ if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
+ if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
+ if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
+ nCol = pIdx->nKeyCol;
+ zIdxName = pTab->zName;
+ nColTest = nCol - 1;
+ }else{
+ nCol = pIdx->nColumn;
+ zIdxName = pIdx->zName;
+ nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
+ }
+
+ /* Populate the register containing the index name. */
+ sqlite3VdbeLoadString(v, regIdxname, zIdxName);
+ VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
+
+ /*
+ ** Pseudo-code for loop that calls stat_push():
+ **
+ ** Rewind csr
+ ** if eof(csr) goto end_of_scan;
+ ** regChng = 0
+ ** goto chng_addr_0;
+ **
+ ** next_row:
+ ** regChng = 0
+ ** if( idx(0) != regPrev(0) ) goto chng_addr_0
+ ** regChng = 1
+ ** if( idx(1) != regPrev(1) ) goto chng_addr_1
+ ** ...
+ ** regChng = N
+ ** goto chng_addr_N
+ **
+ ** chng_addr_0:
+ ** regPrev(0) = idx(0)
+ ** chng_addr_1:
+ ** regPrev(1) = idx(1)
+ ** ...
+ **
+ ** endDistinctTest:
+ ** regRowid = idx(rowid)
+ ** stat_push(P, regChng, regRowid)
+ ** Next csr
+ ** if !eof(csr) goto next_row;
+ **
+ ** end_of_scan:
+ */
+
+ /* Make sure there are enough memory cells allocated to accommodate
+ ** the regPrev array and a trailing rowid (the rowid slot is required
+ ** when building a record to insert into the sample column of
+ ** the sqlite_stat4 table. */
+ pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
+
+ /* Open a read-only cursor on the index being analyzed. */
+ assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
+ sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
+ sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
+ VdbeComment((v, "%s", pIdx->zName));
+
+ /* Invoke the stat_init() function. The arguments are:
+ **
+ ** (1) the number of columns in the index including the rowid
+ ** (or for a WITHOUT ROWID table, the number of PK columns),
+ ** (2) the number of columns in the key without the rowid/pk
+ ** (3) estimated number of rows in the index,
+ */
+ sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat+1);
+ assert( regRowid==regStat+2 );
+ sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regRowid);
+#ifdef SQLITE_ENABLE_STAT4
+ if( OptimizationEnabled(db, SQLITE_Stat4) ){
+ sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regTemp);
+ addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
+ VdbeCoverage(v);
+ }else
+#endif
+ {
+ addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
+ VdbeCoverage(v);
+ sqlite3VdbeAddOp3(v, OP_Count, iIdxCur, regTemp, 1);
+ }
+ assert( regTemp2==regStat+4 );
+ sqlite3VdbeAddOp2(v, OP_Integer, db->nAnalysisLimit, regTemp2);
+ sqlite3VdbeAddFunctionCall(pParse, 0, regStat+1, regStat, 4,
+ &statInitFuncdef, 0);
+
+ /* Implementation of the following:
+ **
+ ** Rewind csr
+ ** if eof(csr) goto end_of_scan;
+ ** regChng = 0
+ ** goto next_push_0;
+ **
+ */
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
+ addrNextRow = sqlite3VdbeCurrentAddr(v);
+
+ if( nColTest>0 ){
+ int endDistinctTest = sqlite3VdbeMakeLabel(pParse);
+ int *aGotoChng; /* Array of jump instruction addresses */
+ aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
+ if( aGotoChng==0 ) continue;
+
+ /*
+ ** next_row:
+ ** regChng = 0
+ ** if( idx(0) != regPrev(0) ) goto chng_addr_0
+ ** regChng = 1
+ ** if( idx(1) != regPrev(1) ) goto chng_addr_1
+ ** ...
+ ** regChng = N
+ ** goto endDistinctTest
+ */
+ sqlite3VdbeAddOp0(v, OP_Goto);
+ addrNextRow = sqlite3VdbeCurrentAddr(v);
+ if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
+ /* For a single-column UNIQUE index, once we have found a non-NULL
+ ** row, we know that all the rest will be distinct, so skip
+ ** subsequent distinctness tests. */
+ sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
+ VdbeCoverage(v);
+ }
+ for(i=0; i<nColTest; i++){
+ char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
+ sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
+ sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
+ analyzeVdbeCommentIndexWithColumnName(v,pIdx,i);
+ aGotoChng[i] =
+ sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
+ sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
+ VdbeCoverage(v);
+ }
+ sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
+ sqlite3VdbeGoto(v, endDistinctTest);
+
+
+ /*
+ ** chng_addr_0:
+ ** regPrev(0) = idx(0)
+ ** chng_addr_1:
+ ** regPrev(1) = idx(1)
+ ** ...
+ */
+ sqlite3VdbeJumpHere(v, addrNextRow-1);
+ for(i=0; i<nColTest; i++){
+ sqlite3VdbeJumpHere(v, aGotoChng[i]);
+ sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
+ analyzeVdbeCommentIndexWithColumnName(v,pIdx,i);
+ }
+ sqlite3VdbeResolveLabel(v, endDistinctTest);
+ sqlite3DbFree(db, aGotoChng);
+ }
+
+ /*
+ ** chng_addr_N:
+ ** regRowid = idx(rowid) // STAT4 only
+ ** stat_push(P, regChng, regRowid) // 3rd parameter STAT4 only
+ ** Next csr
+ ** if !eof(csr) goto next_row;
+ */
+#ifdef SQLITE_ENABLE_STAT4
+ if( OptimizationEnabled(db, SQLITE_Stat4) ){
+ assert( regRowid==(regStat+2) );
+ if( HasRowid(pTab) ){
+ sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
+ }else{
+ Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
+ int j, k, regKey;
+ regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
+ for(j=0; j<pPk->nKeyCol; j++){
+ k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
+ assert( k>=0 && k<pIdx->nColumn );
+ sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
+ analyzeVdbeCommentIndexWithColumnName(v,pIdx,k);
+ }
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
+ sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
+ }
+ }
+#endif
+ assert( regChng==(regStat+1) );
+ {
+ sqlite3VdbeAddFunctionCall(pParse, 1, regStat, regTemp, 2+IsStat4,
+ &statPushFuncdef, 0);
+ if( db->nAnalysisLimit ){
+ int j1, j2, j3;
+ j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regTemp); VdbeCoverage(v);
+ j2 = sqlite3VdbeAddOp1(v, OP_If, regTemp); VdbeCoverage(v);
+ j3 = sqlite3VdbeAddOp4Int(v, OP_SeekGT, iIdxCur, 0, regPrev, 1);
+ VdbeCoverage(v);
+ sqlite3VdbeJumpHere(v, j1);
+ sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
+ sqlite3VdbeJumpHere(v, j2);
+ sqlite3VdbeJumpHere(v, j3);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
+ }
+ }
+
+ /* Add the entry to the stat1 table. */
+ callStatGet(pParse, regStat, STAT_GET_STAT1, regStat1);
+ assert( "BBB"[0]==SQLITE_AFF_TEXT );
+ sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
+ sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
+ sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+ sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
+#endif
+ sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
+
+ /* Add the entries to the stat4 table. */
+#ifdef SQLITE_ENABLE_STAT4
+ if( OptimizationEnabled(db, SQLITE_Stat4) && db->nAnalysisLimit==0 ){
+ int regEq = regStat1;
+ int regLt = regStat1+1;
+ int regDLt = regStat1+2;
+ int regSample = regStat1+3;
+ int regCol = regStat1+4;
+ int regSampleRowid = regCol + nCol;
+ int addrNext;
+ int addrIsNull;
+ u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
+
+ pParse->nMem = MAX(pParse->nMem, regCol+nCol);
+
+ addrNext = sqlite3VdbeCurrentAddr(v);
+ callStatGet(pParse, regStat, STAT_GET_ROWID, regSampleRowid);
+ addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
+ VdbeCoverage(v);
+ callStatGet(pParse, regStat, STAT_GET_NEQ, regEq);
+ callStatGet(pParse, regStat, STAT_GET_NLT, regLt);
+ callStatGet(pParse, regStat, STAT_GET_NDLT, regDLt);
+ sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
+ VdbeCoverage(v);
+ for(i=0; i<nCol; i++){
+ sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
+ }
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
+ sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
+ sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
+ sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
+ sqlite3VdbeJumpHere(v, addrIsNull);
+ }
+#endif /* SQLITE_ENABLE_STAT4 */
+
+ /* End of analysis */
+ sqlite3VdbeJumpHere(v, addrRewind);
+ }
+
+
+ /* Create a single sqlite_stat1 entry containing NULL as the index
+ ** name and the row count as the content.
+ */
+ if( pOnlyIdx==0 && needTableCnt ){
+ VdbeComment((v, "%s", pTab->zName));
+ sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
+ jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
+ sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
+ assert( "BBB"[0]==SQLITE_AFF_TEXT );
+ sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
+ sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
+ sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
+ sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+ sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
+#endif
+ sqlite3VdbeJumpHere(v, jZeroRows);
+ }
+}
+
+
+/*
+** Generate code that will cause the most recent index analysis to
+** be loaded into internal hash tables where is can be used.
+*/
+static void loadAnalysis(Parse *pParse, int iDb){
+ Vdbe *v = sqlite3GetVdbe(pParse);
+ if( v ){
+ sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
+ }
+}
+
+/*
+** Generate code that will do an analysis of an entire database
+*/
+static void analyzeDatabase(Parse *pParse, int iDb){
+ sqlite3 *db = pParse->db;
+ Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
+ HashElem *k;
+ int iStatCur;
+ int iMem;
+ int iTab;
+
+ sqlite3BeginWriteOperation(pParse, 0, iDb);
+ iStatCur = pParse->nTab;
+ pParse->nTab += 3;
+ openStatTable(pParse, iDb, iStatCur, 0, 0);
+ iMem = pParse->nMem+1;
+ iTab = pParse->nTab;
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
+ Table *pTab = (Table*)sqliteHashData(k);
+ analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
+ }
+ loadAnalysis(pParse, iDb);
+}
+
+/*
+** Generate code that will do an analysis of a single table in
+** a database. If pOnlyIdx is not NULL then it is a single index
+** in pTab that should be analyzed.
+*/
+static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
+ int iDb;
+ int iStatCur;
+
+ assert( pTab!=0 );
+ assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
+ iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
+ sqlite3BeginWriteOperation(pParse, 0, iDb);
+ iStatCur = pParse->nTab;
+ pParse->nTab += 3;
+ if( pOnlyIdx ){
+ openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
+ }else{
+ openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
+ }
+ analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
+ loadAnalysis(pParse, iDb);
+}
+
+/*
+** Generate code for the ANALYZE command. The parser calls this routine
+** when it recognizes an ANALYZE command.
+**
+** ANALYZE -- 1
+** ANALYZE <database> -- 2
+** ANALYZE ?<database>.?<tablename> -- 3
+**
+** Form 1 causes all indices in all attached databases to be analyzed.
+** Form 2 analyzes all indices the single database named.
+** Form 3 analyzes all indices associated with the named table.
+*/
+SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
+ sqlite3 *db = pParse->db;
+ int iDb;
+ int i;
+ char *z, *zDb;
+ Table *pTab;
+ Index *pIdx;
+ Token *pTableName;
+ Vdbe *v;
+
+ /* Read the database schema. If an error occurs, leave an error message
+ ** and code in pParse and return NULL. */
+ assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
+ if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
+ return;
+ }
+
+ assert( pName2!=0 || pName1==0 );
+ if( pName1==0 ){
+ /* Form 1: Analyze everything */
+ for(i=0; i<db->nDb; i++){
+ if( i==1 ) continue; /* Do not analyze the TEMP database */
+ analyzeDatabase(pParse, i);
+ }
+ }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
+ /* Analyze the schema named as the argument */
+ analyzeDatabase(pParse, iDb);
+ }else{
+ /* Form 3: Analyze the table or index named as an argument */
+ iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
+ if( iDb>=0 ){
+ zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
+ z = sqlite3NameFromToken(db, pTableName);
+ if( z ){
+ if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
+ analyzeTable(pParse, pIdx->pTable, pIdx);
+ }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
+ analyzeTable(pParse, pTab, 0);
+ }
+ sqlite3DbFree(db, z);
+ }
+ }
+ }
+ if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
+ sqlite3VdbeAddOp0(v, OP_Expire);
+ }
+}
+
+/*
+** Used to pass information from the analyzer reader through to the
+** callback routine.
+*/
+typedef struct analysisInfo analysisInfo;
+struct analysisInfo {
+ sqlite3 *db;
+ const char *zDatabase;
+};
+
+/*
+** The first argument points to a nul-terminated string containing a
+** list of space separated integers. Read the first nOut of these into
+** the array aOut[].
+*/
+static void decodeIntArray(
+ char *zIntArray, /* String containing int array to decode */
+ int nOut, /* Number of slots in aOut[] */
+ tRowcnt *aOut, /* Store integers here */
+ LogEst *aLog, /* Or, if aOut==0, here */
+ Index *pIndex /* Handle extra flags for this index, if not NULL */
+){
+ char *z = zIntArray;
+ int c;
+ int i;
+ tRowcnt v;
+
+#ifdef SQLITE_ENABLE_STAT4
+ if( z==0 ) z = "";
+#else
+ assert( z!=0 );
+#endif
+ for(i=0; *z && i<nOut; i++){
+ v = 0;
+ while( (c=z[0])>='0' && c<='9' ){
+ v = v*10 + c - '0';
+ z++;
+ }
+#ifdef SQLITE_ENABLE_STAT4
+ if( aOut ) aOut[i] = v;
+ if( aLog ) aLog[i] = sqlite3LogEst(v);
+#else
+ assert( aOut==0 );
+ UNUSED_PARAMETER(aOut);
+ assert( aLog!=0 );
+ aLog[i] = sqlite3LogEst(v);
+#endif
+ if( *z==' ' ) z++;
+ }
+#ifndef SQLITE_ENABLE_STAT4
+ assert( pIndex!=0 ); {
+#else
+ if( pIndex ){
+#endif
+ pIndex->bUnordered = 0;
+ pIndex->noSkipScan = 0;
+ while( z[0] ){
+ if( sqlite3_strglob("unordered*", z)==0 ){
+ pIndex->bUnordered = 1;
+ }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
+ int sz = sqlite3Atoi(z+3);
+ if( sz<2 ) sz = 2;
+ pIndex->szIdxRow = sqlite3LogEst(sz);
+ }else if( sqlite3_strglob("noskipscan*", z)==0 ){
+ pIndex->noSkipScan = 1;
+ }
+#ifdef SQLITE_ENABLE_COSTMULT
+ else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
+ pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
+ }
+#endif
+ while( z[0]!=0 && z[0]!=' ' ) z++;
+ while( z[0]==' ' ) z++;
+ }
+ }
+}
+
+/*
+** This callback is invoked once for each index when reading the
+** sqlite_stat1 table.
+**
+** argv[0] = name of the table
+** argv[1] = name of the index (might be NULL)
+** argv[2] = results of analysis - on integer for each column
+**
+** Entries for which argv[1]==NULL simply record the number of rows in
+** the table.
+*/
+static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
+ analysisInfo *pInfo = (analysisInfo*)pData;
+ Index *pIndex;
+ Table *pTable;
+ const char *z;
+
+ assert( argc==3 );
+ UNUSED_PARAMETER2(NotUsed, argc);
+
+ if( argv==0 || argv[0]==0 || argv[2]==0 ){
+ return 0;
+ }
+ pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
+ if( pTable==0 ){
+ return 0;
+ }
+ if( argv[1]==0 ){
+ pIndex = 0;
+ }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
+ pIndex = sqlite3PrimaryKeyIndex(pTable);
+ }else{
+ pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
+ }
+ z = argv[2];
+
+ if( pIndex ){
+ tRowcnt *aiRowEst = 0;
+ int nCol = pIndex->nKeyCol+1;
+#ifdef SQLITE_ENABLE_STAT4
+ /* Index.aiRowEst may already be set here if there are duplicate
+ ** sqlite_stat1 entries for this index. In that case just clobber
+ ** the old data with the new instead of allocating a new array. */
+ if( pIndex->aiRowEst==0 ){
+ pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
+ if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
+ }
+ aiRowEst = pIndex->aiRowEst;
+#endif
+ pIndex->bUnordered = 0;
+ decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
+ pIndex->hasStat1 = 1;
+ if( pIndex->pPartIdxWhere==0 ){
+ pTable->nRowLogEst = pIndex->aiRowLogEst[0];
+ pTable->tabFlags |= TF_HasStat1;
+ }
+ }else{
+ Index fakeIdx;
+ fakeIdx.szIdxRow = pTable->szTabRow;
+#ifdef SQLITE_ENABLE_COSTMULT
+ fakeIdx.pTable = pTable;
+#endif
+ decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
+ pTable->szTabRow = fakeIdx.szIdxRow;
+ pTable->tabFlags |= TF_HasStat1;
+ }
+
+ return 0;
+}
+
+/*
+** If the Index.aSample variable is not NULL, delete the aSample[] array
+** and its contents.
+*/
+SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
+#ifdef SQLITE_ENABLE_STAT4
+ if( pIdx->aSample ){
+ int j;
+ for(j=0; j<pIdx->nSample; j++){
+ IndexSample *p = &pIdx->aSample[j];
+ sqlite3DbFree(db, p->p);
+ }
+ sqlite3DbFree(db, pIdx->aSample);
+ }
+ if( db && db->pnBytesFreed==0 ){
+ pIdx->nSample = 0;
+ pIdx->aSample = 0;
+ }
+#else
+ UNUSED_PARAMETER(db);
+ UNUSED_PARAMETER(pIdx);
+#endif /* SQLITE_ENABLE_STAT4 */
+}
+
+#ifdef SQLITE_ENABLE_STAT4
+/*
+** Populate the pIdx->aAvgEq[] array based on the samples currently
+** stored in pIdx->aSample[].
+*/
+static void initAvgEq(Index *pIdx){
+ if( pIdx ){
+ IndexSample *aSample = pIdx->aSample;
+ IndexSample *pFinal = &aSample[pIdx->nSample-1];
+ int iCol;
+ int nCol = 1;
+ if( pIdx->nSampleCol>1 ){
+ /* If this is stat4 data, then calculate aAvgEq[] values for all
+ ** sample columns except the last. The last is always set to 1, as
+ ** once the trailing PK fields are considered all index keys are
+ ** unique. */
+ nCol = pIdx->nSampleCol-1;
+ pIdx->aAvgEq[nCol] = 1;
+ }
+ for(iCol=0; iCol<nCol; iCol++){
+ int nSample = pIdx->nSample;
+ int i; /* Used to iterate through samples */
+ tRowcnt sumEq = 0; /* Sum of the nEq values */
+ tRowcnt avgEq = 0;
+ tRowcnt nRow; /* Number of rows in index */
+ i64 nSum100 = 0; /* Number of terms contributing to sumEq */
+ i64 nDist100; /* Number of distinct values in index */
+
+ if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
+ nRow = pFinal->anLt[iCol];
+ nDist100 = (i64)100 * pFinal->anDLt[iCol];
+ nSample--;
+ }else{
+ nRow = pIdx->aiRowEst[0];
+ nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
+ }
+ pIdx->nRowEst0 = nRow;
+
+ /* Set nSum to the number of distinct (iCol+1) field prefixes that
+ ** occur in the stat4 table for this index. Set sumEq to the sum of
+ ** the nEq values for column iCol for the same set (adding the value
+ ** only once where there exist duplicate prefixes). */
+ for(i=0; i<nSample; i++){
+ if( i==(pIdx->nSample-1)
+ || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
+ ){
+ sumEq += aSample[i].anEq[iCol];
+ nSum100 += 100;
+ }
+ }
+
+ if( nDist100>nSum100 && sumEq<nRow ){
+ avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
+ }
+ if( avgEq==0 ) avgEq = 1;
+ pIdx->aAvgEq[iCol] = avgEq;
+ }
+ }
+}
+
+/*
+** Look up an index by name. Or, if the name of a WITHOUT ROWID table
+** is supplied instead, find the PRIMARY KEY index for that table.
+*/
+static Index *findIndexOrPrimaryKey(
+ sqlite3 *db,
+ const char *zName,
+ const char *zDb
+){
+ Index *pIdx = sqlite3FindIndex(db, zName, zDb);
+ if( pIdx==0 ){
+ Table *pTab = sqlite3FindTable(db, zName, zDb);
+ if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
+ }
+ return pIdx;
+}
+
+/*
+** Load the content from either the sqlite_stat4
+** into the relevant Index.aSample[] arrays.
+**
+** Arguments zSql1 and zSql2 must point to SQL statements that return
+** data equivalent to the following:
+**
+** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
+** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
+**
+** where %Q is replaced with the database name before the SQL is executed.
+*/
+static int loadStatTbl(
+ sqlite3 *db, /* Database handle */
+ const char *zSql1, /* SQL statement 1 (see above) */
+ const char *zSql2, /* SQL statement 2 (see above) */
+ const char *zDb /* Database name (e.g. "main") */
+){
+ int rc; /* Result codes from subroutines */
+ sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
+ char *zSql; /* Text of the SQL statement */
+ Index *pPrevIdx = 0; /* Previous index in the loop */
+ IndexSample *pSample; /* A slot in pIdx->aSample[] */
+
+ assert( db->lookaside.bDisable );
+ zSql = sqlite3MPrintf(db, zSql1, zDb);
+ if( !zSql ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
+ sqlite3DbFree(db, zSql);
+ if( rc ) return rc;
+
+ while( sqlite3_step(pStmt)==SQLITE_ROW ){
+ int nIdxCol = 1; /* Number of columns in stat4 records */
+
+ char *zIndex; /* Index name */
+ Index *pIdx; /* Pointer to the index object */
+ int nSample; /* Number of samples */
+ int nByte; /* Bytes of space required */
+ int i; /* Bytes of space required */
+ tRowcnt *pSpace;
+
+ zIndex = (char *)sqlite3_column_text(pStmt, 0);
+ if( zIndex==0 ) continue;
+ nSample = sqlite3_column_int(pStmt, 1);
+ pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
+ assert( pIdx==0 || pIdx->nSample==0 );
+ if( pIdx==0 ) continue;
+ assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
+ if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
+ nIdxCol = pIdx->nKeyCol;
+ }else{
+ nIdxCol = pIdx->nColumn;
+ }
+ pIdx->nSampleCol = nIdxCol;
+ nByte = sizeof(IndexSample) * nSample;
+ nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
+ nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
+
+ pIdx->aSample = sqlite3DbMallocZero(db, nByte);
+ if( pIdx->aSample==0 ){
+ sqlite3_finalize(pStmt);
+ return SQLITE_NOMEM_BKPT;
+ }
+ pSpace = (tRowcnt*)&pIdx->aSample[nSample];
+ pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
+ for(i=0; i<nSample; i++){
+ pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
+ pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
+ pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
+ }
+ assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
+ }
+ rc = sqlite3_finalize(pStmt);
+ if( rc ) return rc;
+
+ zSql = sqlite3MPrintf(db, zSql2, zDb);
+ if( !zSql ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
+ sqlite3DbFree(db, zSql);
+ if( rc ) return rc;
+
+ while( sqlite3_step(pStmt)==SQLITE_ROW ){
+ char *zIndex; /* Index name */
+ Index *pIdx; /* Pointer to the index object */
+ int nCol = 1; /* Number of columns in index */
+
+ zIndex = (char *)sqlite3_column_text(pStmt, 0);
+ if( zIndex==0 ) continue;
+ pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
+ if( pIdx==0 ) continue;
+ /* This next condition is true if data has already been loaded from
+ ** the sqlite_stat4 table. */
+ nCol = pIdx->nSampleCol;
+ if( pIdx!=pPrevIdx ){
+ initAvgEq(pPrevIdx);
+ pPrevIdx = pIdx;
+ }
+ pSample = &pIdx->aSample[pIdx->nSample];
+ decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
+ decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
+ decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
+
+ /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
+ ** This is in case the sample record is corrupted. In that case, the
+ ** sqlite3VdbeRecordCompare() may read up to two varints past the
+ ** end of the allocated buffer before it realizes it is dealing with
+ ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
+ ** a buffer overread. */
+ pSample->n = sqlite3_column_bytes(pStmt, 4);
+ pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
+ if( pSample->p==0 ){
+ sqlite3_finalize(pStmt);
+ return SQLITE_NOMEM_BKPT;
+ }
+ if( pSample->n ){
+ memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
+ }
+ pIdx->nSample++;
+ }
+ rc = sqlite3_finalize(pStmt);
+ if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
+ return rc;
+}
+
+/*
+** Load content from the sqlite_stat4 table into
+** the Index.aSample[] arrays of all indices.
+*/
+static int loadStat4(sqlite3 *db, const char *zDb){
+ int rc = SQLITE_OK; /* Result codes from subroutines */
+
+ assert( db->lookaside.bDisable );
+ if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
+ rc = loadStatTbl(db,
+ "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
+ "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
+ zDb
+ );
+ }
+ return rc;
+}
+#endif /* SQLITE_ENABLE_STAT4 */
+
+/*
+** Load the content of the sqlite_stat1 and sqlite_stat4 tables. The
+** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
+** arrays. The contents of sqlite_stat4 are used to populate the
+** Index.aSample[] arrays.
+**
+** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
+** is returned. In this case, even if SQLITE_ENABLE_STAT4 was defined
+** during compilation and the sqlite_stat4 table is present, no data is
+** read from it.
+**
+** If SQLITE_ENABLE_STAT4 was defined during compilation and the
+** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
+** returned. However, in this case, data is read from the sqlite_stat1
+** table (if it is present) before returning.
+**
+** If an OOM error occurs, this function always sets db->mallocFailed.
+** This means if the caller does not care about other errors, the return
+** code may be ignored.
+*/
+SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
+ analysisInfo sInfo;
+ HashElem *i;
+ char *zSql;
+ int rc = SQLITE_OK;
+ Schema *pSchema = db->aDb[iDb].pSchema;
+
+ assert( iDb>=0 && iDb<db->nDb );
+ assert( db->aDb[iDb].pBt!=0 );
+
+ /* Clear any prior statistics */
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
+ Table *pTab = sqliteHashData(i);
+ pTab->tabFlags &= ~TF_HasStat1;
+ }
+ for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
+ Index *pIdx = sqliteHashData(i);
+ pIdx->hasStat1 = 0;
+#ifdef SQLITE_ENABLE_STAT4
+ sqlite3DeleteIndexSamples(db, pIdx);
+ pIdx->aSample = 0;
+#endif
+ }
+
+ /* Load new statistics out of the sqlite_stat1 table */
+ sInfo.db = db;
+ sInfo.zDatabase = db->aDb[iDb].zDbSName;
+ if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
+ zSql = sqlite3MPrintf(db,
+ "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
+ if( zSql==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ }else{
+ rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
+ sqlite3DbFree(db, zSql);
+ }
+ }
+
+ /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
+ Index *pIdx = sqliteHashData(i);
+ if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
+ }
+
+ /* Load the statistics from the sqlite_stat4 table. */
+#ifdef SQLITE_ENABLE_STAT4
+ if( rc==SQLITE_OK ){
+ DisableLookaside;
+ rc = loadStat4(db, sInfo.zDatabase);
+ EnableLookaside;
+ }
+ for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
+ Index *pIdx = sqliteHashData(i);
+ sqlite3_free(pIdx->aiRowEst);
+ pIdx->aiRowEst = 0;
+ }
+#endif
+
+ if( rc==SQLITE_NOMEM ){
+ sqlite3OomFault(db);
+ }
+ return rc;
+}
+
+
+#endif /* SQLITE_OMIT_ANALYZE */
+
+/************** End of analyze.c *********************************************/
+/************** Begin file attach.c ******************************************/
+/*
+** 2003 April 6
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code used to implement the ATTACH and DETACH commands.
+*/
+/* #include "sqliteInt.h" */
+
+#ifndef SQLITE_OMIT_ATTACH
+/*
+** Resolve an expression that was part of an ATTACH or DETACH statement. This
+** is slightly different from resolving a normal SQL expression, because simple
+** identifiers are treated as strings, not possible column names or aliases.
+**
+** i.e. if the parser sees:
+**
+** ATTACH DATABASE abc AS def
+**
+** it treats the two expressions as literal strings 'abc' and 'def' instead of
+** looking for columns of the same name.
+**
+** This only applies to the root node of pExpr, so the statement:
+**
+** ATTACH DATABASE abc||def AS 'db2'
+**
+** will fail because neither abc or def can be resolved.
+*/
+static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
+{
+ int rc = SQLITE_OK;
+ if( pExpr ){
+ if( pExpr->op!=TK_ID ){
+ rc = sqlite3ResolveExprNames(pName, pExpr);
+ }else{
+ pExpr->op = TK_STRING;
+ }
+ }
+ return rc;
+}
+
+/*
+** Return true if zName points to a name that may be used to refer to
+** database iDb attached to handle db.
+*/
+SQLITE_PRIVATE int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName){
+ return (
+ sqlite3StrICmp(db->aDb[iDb].zDbSName, zName)==0
+ || (iDb==0 && sqlite3StrICmp("main", zName)==0)
+ );
+}
+
+/*
+** An SQL user-function registered to do the work of an ATTACH statement. The
+** three arguments to the function come directly from an attach statement:
+**
+** ATTACH DATABASE x AS y KEY z
+**
+** SELECT sqlite_attach(x, y, z)
+**
+** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
+** third argument.
+**
+** If the db->init.reopenMemdb flags is set, then instead of attaching a
+** new database, close the database on db->init.iDb and reopen it as an
+** empty MemDB.
+*/
+static void attachFunc(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **argv
+){
+ int i;
+ int rc = 0;
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ const char *zName;
+ const char *zFile;
+ char *zPath = 0;
+ char *zErr = 0;
+ unsigned int flags;
+ Db *aNew; /* New array of Db pointers */
+ Db *pNew; /* Db object for the newly attached database */
+ char *zErrDyn = 0;
+ sqlite3_vfs *pVfs;
+
+ UNUSED_PARAMETER(NotUsed);
+ zFile = (const char *)sqlite3_value_text(argv[0]);
+ zName = (const char *)sqlite3_value_text(argv[1]);
+ if( zFile==0 ) zFile = "";
+ if( zName==0 ) zName = "";
+
+#ifdef SQLITE_ENABLE_DESERIALIZE
+# define REOPEN_AS_MEMDB(db) (db->init.reopenMemdb)
+#else
+# define REOPEN_AS_MEMDB(db) (0)
+#endif
+
+ if( REOPEN_AS_MEMDB(db) ){
+ /* This is not a real ATTACH. Instead, this routine is being called
+ ** from sqlite3_deserialize() to close database db->init.iDb and
+ ** reopen it as a MemDB */
+ pVfs = sqlite3_vfs_find("memdb");
+ if( pVfs==0 ) return;
+ pNew = &db->aDb[db->init.iDb];
+ if( pNew->pBt ) sqlite3BtreeClose(pNew->pBt);
+ pNew->pBt = 0;
+ pNew->pSchema = 0;
+ rc = sqlite3BtreeOpen(pVfs, "x\0", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB);
+ }else{
+ /* This is a real ATTACH
+ **
+ ** Check for the following errors:
+ **
+ ** * Too many attached databases,
+ ** * Transaction currently open
+ ** * Specified database name already being used.
+ */
+ if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
+ zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
+ db->aLimit[SQLITE_LIMIT_ATTACHED]
+ );
+ goto attach_error;
+ }
+ for(i=0; i<db->nDb; i++){
+ assert( zName );
+ if( sqlite3DbIsNamed(db, i, zName) ){
+ zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
+ goto attach_error;
+ }
+ }
+
+ /* Allocate the new entry in the db->aDb[] array and initialize the schema
+ ** hash tables.
+ */
+ if( db->aDb==db->aDbStatic ){
+ aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
+ if( aNew==0 ) return;
+ memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
+ }else{
+ aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
+ if( aNew==0 ) return;
+ }
+ db->aDb = aNew;
+ pNew = &db->aDb[db->nDb];
+ memset(pNew, 0, sizeof(*pNew));
+
+ /* Open the database file. If the btree is successfully opened, use
+ ** it to obtain the database schema. At this point the schema may
+ ** or may not be initialized.
+ */
+ flags = db->openFlags;
+ rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
+ if( rc!=SQLITE_OK ){
+ if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
+ sqlite3_result_error(context, zErr, -1);
+ sqlite3_free(zErr);
+ return;
+ }
+ assert( pVfs );
+ flags |= SQLITE_OPEN_MAIN_DB;
+ rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
+ db->nDb++;
+ pNew->zDbSName = sqlite3DbStrDup(db, zName);
+ }
+ db->noSharedCache = 0;
+ if( rc==SQLITE_CONSTRAINT ){
+ rc = SQLITE_ERROR;
+ zErrDyn = sqlite3MPrintf(db, "database is already attached");
+ }else if( rc==SQLITE_OK ){
+ Pager *pPager;
+ pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
+ if( !pNew->pSchema ){
+ rc = SQLITE_NOMEM_BKPT;
+ }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
+ zErrDyn = sqlite3MPrintf(db,
+ "attached databases must use the same text encoding as main database");
+ rc = SQLITE_ERROR;
+ }
+ sqlite3BtreeEnter(pNew->pBt);
+ pPager = sqlite3BtreePager(pNew->pBt);
+ sqlite3PagerLockingMode(pPager, db->dfltLockMode);
+ sqlite3BtreeSecureDelete(pNew->pBt,
+ sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
+#ifndef SQLITE_OMIT_PAGER_PRAGMAS
+ sqlite3BtreeSetPagerFlags(pNew->pBt,
+ PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
+#endif
+ sqlite3BtreeLeave(pNew->pBt);
+ }
+ pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
+ if( rc==SQLITE_OK && pNew->zDbSName==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ }
+ sqlite3_free_filename( zPath );
+
+ /* If the file was opened successfully, read the schema for the new database.
+ ** If this fails, or if opening the file failed, then close the file and
+ ** remove the entry from the db->aDb[] array. i.e. put everything back the
+ ** way we found it.
+ */
+ if( rc==SQLITE_OK ){
+ sqlite3BtreeEnterAll(db);
+ db->init.iDb = 0;
+ db->mDbFlags &= ~(DBFLAG_SchemaKnownOk);
+ if( !REOPEN_AS_MEMDB(db) ){
+ rc = sqlite3Init(db, &zErrDyn);
+ }
+ sqlite3BtreeLeaveAll(db);
+ assert( zErrDyn==0 || rc!=SQLITE_OK );
+ }
+#ifdef SQLITE_USER_AUTHENTICATION
+ if( rc==SQLITE_OK && !REOPEN_AS_MEMDB(db) ){
+ u8 newAuth = 0;
+ rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
+ if( newAuth<db->auth.authLevel ){
+ rc = SQLITE_AUTH_USER;
+ }
+ }
+#endif
+ if( rc ){
+ if( !REOPEN_AS_MEMDB(db) ){
+ int iDb = db->nDb - 1;
+ assert( iDb>=2 );
+ if( db->aDb[iDb].pBt ){
+ sqlite3BtreeClose(db->aDb[iDb].pBt);
+ db->aDb[iDb].pBt = 0;
+ db->aDb[iDb].pSchema = 0;
+ }
+ sqlite3ResetAllSchemasOfConnection(db);
+ db->nDb = iDb;
+ if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
+ sqlite3OomFault(db);
+ sqlite3DbFree(db, zErrDyn);
+ zErrDyn = sqlite3MPrintf(db, "out of memory");
+ }else if( zErrDyn==0 ){
+ zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
+ }
+ }
+ goto attach_error;
+ }
+
+ return;
+
+attach_error:
+ /* Return an error if we get here */
+ if( zErrDyn ){
+ sqlite3_result_error(context, zErrDyn, -1);
+ sqlite3DbFree(db, zErrDyn);
+ }
+ if( rc ) sqlite3_result_error_code(context, rc);
+}
+
+/*
+** An SQL user-function registered to do the work of an DETACH statement. The
+** three arguments to the function come directly from a detach statement:
+**
+** DETACH DATABASE x
+**
+** SELECT sqlite_detach(x)
+*/
+static void detachFunc(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **argv
+){
+ const char *zName = (const char *)sqlite3_value_text(argv[0]);
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ int i;
+ Db *pDb = 0;
+ HashElem *pEntry;
+ char zErr[128];
+
+ UNUSED_PARAMETER(NotUsed);
+
+ if( zName==0 ) zName = "";
+ for(i=0; i<db->nDb; i++){
+ pDb = &db->aDb[i];
+ if( pDb->pBt==0 ) continue;
+ if( sqlite3DbIsNamed(db, i, zName) ) break;
+ }
+
+ if( i>=db->nDb ){
+ sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
+ goto detach_error;
+ }
+ if( i<2 ){
+ sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
+ goto detach_error;
+ }
+ if( sqlite3BtreeTxnState(pDb->pBt)!=SQLITE_TXN_NONE
+ || sqlite3BtreeIsInBackup(pDb->pBt)
+ ){
+ sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
+ goto detach_error;
+ }
+
+ /* If any TEMP triggers reference the schema being detached, move those
+ ** triggers to reference the TEMP schema itself. */
+ assert( db->aDb[1].pSchema );
+ pEntry = sqliteHashFirst(&db->aDb[1].pSchema->trigHash);
+ while( pEntry ){
+ Trigger *pTrig = (Trigger*)sqliteHashData(pEntry);
+ if( pTrig->pTabSchema==pDb->pSchema ){
+ pTrig->pTabSchema = pTrig->pSchema;
+ }
+ pEntry = sqliteHashNext(pEntry);
+ }
+
+ sqlite3BtreeClose(pDb->pBt);
+ pDb->pBt = 0;
+ pDb->pSchema = 0;
+ sqlite3CollapseDatabaseArray(db);
+ return;
+
+detach_error:
+ sqlite3_result_error(context, zErr, -1);
+}
+
+/*
+** This procedure generates VDBE code for a single invocation of either the
+** sqlite_detach() or sqlite_attach() SQL user functions.
+*/
+static void codeAttach(
+ Parse *pParse, /* The parser context */
+ int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
+ FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
+ Expr *pAuthArg, /* Expression to pass to authorization callback */
+ Expr *pFilename, /* Name of database file */
+ Expr *pDbname, /* Name of the database to use internally */
+ Expr *pKey /* Database key for encryption extension */
+){
+ int rc;
+ NameContext sName;
+ Vdbe *v;
+ sqlite3* db = pParse->db;
+ int regArgs;
+
+ if( pParse->nErr ) goto attach_end;
+ memset(&sName, 0, sizeof(NameContext));
+ sName.pParse = pParse;
+
+ if(
+ SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
+ SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
+ SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
+ ){
+ goto attach_end;
+ }
+
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ if( pAuthArg ){
+ char *zAuthArg;
+ if( pAuthArg->op==TK_STRING ){
+ zAuthArg = pAuthArg->u.zToken;
+ }else{
+ zAuthArg = 0;
+ }
+ rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
+ if(rc!=SQLITE_OK ){
+ goto attach_end;
+ }
+ }
+#endif /* SQLITE_OMIT_AUTHORIZATION */
+
+
+ v = sqlite3GetVdbe(pParse);
+ regArgs = sqlite3GetTempRange(pParse, 4);
+ sqlite3ExprCode(pParse, pFilename, regArgs);
+ sqlite3ExprCode(pParse, pDbname, regArgs+1);
+ sqlite3ExprCode(pParse, pKey, regArgs+2);
+
+ assert( v || db->mallocFailed );
+ if( v ){
+ sqlite3VdbeAddFunctionCall(pParse, 0, regArgs+3-pFunc->nArg, regArgs+3,
+ pFunc->nArg, pFunc, 0);
+ /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
+ ** statement only). For DETACH, set it to false (expire all existing
+ ** statements).
+ */
+ sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
+ }
+
+attach_end:
+ sqlite3ExprDelete(db, pFilename);
+ sqlite3ExprDelete(db, pDbname);
+ sqlite3ExprDelete(db, pKey);
+}
+
+/*
+** Called by the parser to compile a DETACH statement.
+**
+** DETACH pDbname
+*/
+SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
+ static const FuncDef detach_func = {
+ 1, /* nArg */
+ SQLITE_UTF8, /* funcFlags */
+ 0, /* pUserData */
+ 0, /* pNext */
+ detachFunc, /* xSFunc */
+ 0, /* xFinalize */
+ 0, 0, /* xValue, xInverse */
+ "sqlite_detach", /* zName */
+ {0}
+ };
+ codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
+}
+
+/*
+** Called by the parser to compile an ATTACH statement.
+**
+** ATTACH p AS pDbname KEY pKey
+*/
+SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
+ static const FuncDef attach_func = {
+ 3, /* nArg */
+ SQLITE_UTF8, /* funcFlags */
+ 0, /* pUserData */
+ 0, /* pNext */
+ attachFunc, /* xSFunc */
+ 0, /* xFinalize */
+ 0, 0, /* xValue, xInverse */
+ "sqlite_attach", /* zName */
+ {0}
+ };
+ codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
+}
+#endif /* SQLITE_OMIT_ATTACH */
+
+/*
+** Initialize a DbFixer structure. This routine must be called prior
+** to passing the structure to one of the sqliteFixAAAA() routines below.
+*/
+SQLITE_PRIVATE void sqlite3FixInit(
+ DbFixer *pFix, /* The fixer to be initialized */
+ Parse *pParse, /* Error messages will be written here */
+ int iDb, /* This is the database that must be used */
+ const char *zType, /* "view", "trigger", or "index" */
+ const Token *pName /* Name of the view, trigger, or index */
+){
+ sqlite3 *db;
+
+ db = pParse->db;
+ assert( db->nDb>iDb );
+ pFix->pParse = pParse;
+ pFix->zDb = db->aDb[iDb].zDbSName;
+ pFix->pSchema = db->aDb[iDb].pSchema;
+ pFix->zType = zType;
+ pFix->pName = pName;
+ pFix->bTemp = (iDb==1);
+}
+
+/*
+** The following set of routines walk through the parse tree and assign
+** a specific database to all table references where the database name
+** was left unspecified in the original SQL statement. The pFix structure
+** must have been initialized by a prior call to sqlite3FixInit().
+**
+** These routines are used to make sure that an index, trigger, or
+** view in one database does not refer to objects in a different database.
+** (Exception: indices, triggers, and views in the TEMP database are
+** allowed to refer to anything.) If a reference is explicitly made
+** to an object in a different database, an error message is added to
+** pParse->zErrMsg and these routines return non-zero. If everything
+** checks out, these routines return 0.
+*/
+SQLITE_PRIVATE int sqlite3FixSrcList(
+ DbFixer *pFix, /* Context of the fixation */
+ SrcList *pList /* The Source list to check and modify */
+){
+ int i;
+ struct SrcList_item *pItem;
+ sqlite3 *db = pFix->pParse->db;
+ int iDb = sqlite3FindDbName(db, pFix->zDb);
+
+ if( NEVER(pList==0) ) return 0;
+
+ for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
+ if( pFix->bTemp==0 ){
+ if( pItem->zDatabase && iDb!=sqlite3FindDbName(db, pItem->zDatabase) ){
+ sqlite3ErrorMsg(pFix->pParse,
+ "%s %T cannot reference objects in database %s",
+ pFix->zType, pFix->pName, pItem->zDatabase);
+ return 1;
+ }
+ sqlite3DbFree(db, pItem->zDatabase);
+ pItem->zDatabase = 0;
+ pItem->pSchema = pFix->pSchema;
+ pItem->fg.fromDDL = 1;
+ }
+#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
+ if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
+ if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
+#endif
+ if( pItem->fg.isTabFunc && sqlite3FixExprList(pFix, pItem->u1.pFuncArg) ){
+ return 1;
+ }
+ }
+ return 0;
+}
+#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
+SQLITE_PRIVATE int sqlite3FixSelect(
+ DbFixer *pFix, /* Context of the fixation */
+ Select *pSelect /* The SELECT statement to be fixed to one database */
+){
+ while( pSelect ){
+ if( sqlite3FixExprList(pFix, pSelect->pEList) ){
+ return 1;
+ }
+ if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
+ return 1;
+ }
+ if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
+ return 1;
+ }
+ if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
+ return 1;
+ }
+ if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
+ return 1;
+ }
+ if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
+ return 1;
+ }
+ if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
+ return 1;
+ }
+ if( pSelect->pWith ){
+ int i;
+ for(i=0; i<pSelect->pWith->nCte; i++){
+ if( sqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){
+ return 1;
+ }
+ }
+ }
+ pSelect = pSelect->pPrior;
+ }
+ return 0;
+}
+SQLITE_PRIVATE int sqlite3FixExpr(
+ DbFixer *pFix, /* Context of the fixation */
+ Expr *pExpr /* The expression to be fixed to one database */
+){
+ while( pExpr ){
+ if( !pFix->bTemp ) ExprSetProperty(pExpr, EP_FromDDL);
+ if( pExpr->op==TK_VARIABLE ){
+ if( pFix->pParse->db->init.busy ){
+ pExpr->op = TK_NULL;
+ }else{
+ sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
+ return 1;
+ }
+ }
+ if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
+ if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+ if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
+ }else{
+ if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
+ }
+ if( sqlite3FixExpr(pFix, pExpr->pRight) ){
+ return 1;
+ }
+ pExpr = pExpr->pLeft;
+ }
+ return 0;
+}
+SQLITE_PRIVATE int sqlite3FixExprList(
+ DbFixer *pFix, /* Context of the fixation */
+ ExprList *pList /* The expression to be fixed to one database */
+){
+ int i;
+ struct ExprList_item *pItem;
+ if( pList==0 ) return 0;
+ for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
+ if( sqlite3FixExpr(pFix, pItem->pExpr) ){
+ return 1;
+ }
+ }
+ return 0;
+}
+#endif
+
+#ifndef SQLITE_OMIT_TRIGGER
+SQLITE_PRIVATE int sqlite3FixTriggerStep(
+ DbFixer *pFix, /* Context of the fixation */
+ TriggerStep *pStep /* The trigger step be fixed to one database */
+){
+ while( pStep ){
+ if( sqlite3FixSelect(pFix, pStep->pSelect) ){
+ return 1;
+ }
+ if( sqlite3FixExpr(pFix, pStep->pWhere) ){
+ return 1;
+ }
+ if( sqlite3FixExprList(pFix, pStep->pExprList) ){
+ return 1;
+ }
+ if( pStep->pFrom && sqlite3FixSrcList(pFix, pStep->pFrom) ){
+ return 1;
+ }
+#ifndef SQLITE_OMIT_UPSERT
+ if( pStep->pUpsert ){
+ Upsert *pUp = pStep->pUpsert;
+ if( sqlite3FixExprList(pFix, pUp->pUpsertTarget)
+ || sqlite3FixExpr(pFix, pUp->pUpsertTargetWhere)
+ || sqlite3FixExprList(pFix, pUp->pUpsertSet)
+ || sqlite3FixExpr(pFix, pUp->pUpsertWhere)
+ ){
+ return 1;
+ }
+ }
+#endif
+ pStep = pStep->pNext;
+ }
+ return 0;
+}
+#endif
+
+/************** End of attach.c **********************************************/
+/************** Begin file auth.c ********************************************/
+/*
+** 2003 January 11
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code used to implement the sqlite3_set_authorizer()
+** API. This facility is an optional feature of the library. Embedded
+** systems that do not need this facility may omit it by recompiling
+** the library with -DSQLITE_OMIT_AUTHORIZATION=1
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** All of the code in this file may be omitted by defining a single
+** macro.
+*/
+#ifndef SQLITE_OMIT_AUTHORIZATION
+
+/*
+** Set or clear the access authorization function.
+**
+** The access authorization function is be called during the compilation
+** phase to verify that the user has read and/or write access permission on
+** various fields of the database. The first argument to the auth function
+** is a copy of the 3rd argument to this routine. The second argument
+** to the auth function is one of these constants:
+**
+** SQLITE_CREATE_INDEX
+** SQLITE_CREATE_TABLE
+** SQLITE_CREATE_TEMP_INDEX
+** SQLITE_CREATE_TEMP_TABLE
+** SQLITE_CREATE_TEMP_TRIGGER
+** SQLITE_CREATE_TEMP_VIEW
+** SQLITE_CREATE_TRIGGER
+** SQLITE_CREATE_VIEW
+** SQLITE_DELETE
+** SQLITE_DROP_INDEX
+** SQLITE_DROP_TABLE
+** SQLITE_DROP_TEMP_INDEX
+** SQLITE_DROP_TEMP_TABLE
+** SQLITE_DROP_TEMP_TRIGGER
+** SQLITE_DROP_TEMP_VIEW
+** SQLITE_DROP_TRIGGER
+** SQLITE_DROP_VIEW
+** SQLITE_INSERT
+** SQLITE_PRAGMA
+** SQLITE_READ
+** SQLITE_SELECT
+** SQLITE_TRANSACTION
+** SQLITE_UPDATE
+**
+** The third and fourth arguments to the auth function are the name of
+** the table and the column that are being accessed. The auth function
+** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
+** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
+** means that the SQL statement will never-run - the sqlite3_exec() call
+** will return with an error. SQLITE_IGNORE means that the SQL statement
+** should run but attempts to read the specified column will return NULL
+** and attempts to write the column will be ignored.
+**
+** Setting the auth function to NULL disables this hook. The default
+** setting of the auth function is NULL.
+*/
+SQLITE_API int sqlite3_set_authorizer(
+ sqlite3 *db,
+ int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
+ void *pArg
+){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ db->xAuth = (sqlite3_xauth)xAuth;
+ db->pAuthArg = pArg;
+ if( db->xAuth ) sqlite3ExpirePreparedStatements(db, 1);
+ sqlite3_mutex_leave(db->mutex);
+ return SQLITE_OK;
+}
+
+/*
+** Write an error message into pParse->zErrMsg that explains that the
+** user-supplied authorization function returned an illegal value.
+*/
+static void sqliteAuthBadReturnCode(Parse *pParse){
+ sqlite3ErrorMsg(pParse, "authorizer malfunction");
+ pParse->rc = SQLITE_ERROR;
+}
+
+/*
+** Invoke the authorization callback for permission to read column zCol from
+** table zTab in database zDb. This function assumes that an authorization
+** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
+**
+** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
+** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
+** is treated as SQLITE_DENY. In this case an error is left in pParse.
+*/
+SQLITE_PRIVATE int sqlite3AuthReadCol(
+ Parse *pParse, /* The parser context */
+ const char *zTab, /* Table name */
+ const char *zCol, /* Column name */
+ int iDb /* Index of containing database. */
+){
+ sqlite3 *db = pParse->db; /* Database handle */
+ char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
+ int rc; /* Auth callback return code */
+
+ if( db->init.busy ) return SQLITE_OK;
+ rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
+#ifdef SQLITE_USER_AUTHENTICATION
+ ,db->auth.zAuthUser
+#endif
+ );
+ if( rc==SQLITE_DENY ){
+ char *z = sqlite3_mprintf("%s.%s", zTab, zCol);
+ if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
+ sqlite3ErrorMsg(pParse, "access to %z is prohibited", z);
+ pParse->rc = SQLITE_AUTH;
+ }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
+ sqliteAuthBadReturnCode(pParse);
+ }
+ return rc;
+}
+
+/*
+** The pExpr should be a TK_COLUMN expression. The table referred to
+** is in pTabList or else it is the NEW or OLD table of a trigger.
+** Check to see if it is OK to read this particular column.
+**
+** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
+** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
+** then generate an error.
+*/
+SQLITE_PRIVATE void sqlite3AuthRead(
+ Parse *pParse, /* The parser context */
+ Expr *pExpr, /* The expression to check authorization on */
+ Schema *pSchema, /* The schema of the expression */
+ SrcList *pTabList /* All table that pExpr might refer to */
+){
+ sqlite3 *db = pParse->db;
+ Table *pTab = 0; /* The table being read */
+ const char *zCol; /* Name of the column of the table */
+ int iSrc; /* Index in pTabList->a[] of table being read */
+ int iDb; /* The index of the database the expression refers to */
+ int iCol; /* Index of column in table */
+
+ assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
+ assert( !IN_RENAME_OBJECT || db->xAuth==0 );
+ if( db->xAuth==0 ) return;
+ iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
+ if( iDb<0 ){
+ /* An attempt to read a column out of a subquery or other
+ ** temporary table. */
+ return;
+ }
+
+ if( pExpr->op==TK_TRIGGER ){
+ pTab = pParse->pTriggerTab;
+ }else{
+ assert( pTabList );
+ for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
+ if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
+ pTab = pTabList->a[iSrc].pTab;
+ break;
+ }
+ }
+ }
+ iCol = pExpr->iColumn;
+ if( NEVER(pTab==0) ) return;
+
+ if( iCol>=0 ){
+ assert( iCol<pTab->nCol );
+ zCol = pTab->aCol[iCol].zName;
+ }else if( pTab->iPKey>=0 ){
+ assert( pTab->iPKey<pTab->nCol );
+ zCol = pTab->aCol[pTab->iPKey].zName;
+ }else{
+ zCol = "ROWID";
+ }
+ assert( iDb>=0 && iDb<db->nDb );
+ if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
+ pExpr->op = TK_NULL;
+ }
+}
+
+/*
+** Do an authorization check using the code and arguments given. Return
+** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
+** is returned, then the error count and error message in pParse are
+** modified appropriately.
+*/
+SQLITE_PRIVATE int sqlite3AuthCheck(
+ Parse *pParse,
+ int code,
+ const char *zArg1,
+ const char *zArg2,
+ const char *zArg3
+){
+ sqlite3 *db = pParse->db;
+ int rc;
+
+ /* Don't do any authorization checks if the database is initialising
+ ** or if the parser is being invoked from within sqlite3_declare_vtab.
+ */
+ assert( !IN_RENAME_OBJECT || db->xAuth==0 );
+ if( db->init.busy || IN_SPECIAL_PARSE ){
+ return SQLITE_OK;
+ }
+
+ if( db->xAuth==0 ){
+ return SQLITE_OK;
+ }
+
+ /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
+ ** callback are either NULL pointers or zero-terminated strings that
+ ** contain additional details about the action to be authorized.
+ **
+ ** The following testcase() macros show that any of the 3rd through 6th
+ ** parameters can be either NULL or a string. */
+ testcase( zArg1==0 );
+ testcase( zArg2==0 );
+ testcase( zArg3==0 );
+ testcase( pParse->zAuthContext==0 );
+
+ rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
+#ifdef SQLITE_USER_AUTHENTICATION
+ ,db->auth.zAuthUser
+#endif
+ );
+ if( rc==SQLITE_DENY ){
+ sqlite3ErrorMsg(pParse, "not authorized");
+ pParse->rc = SQLITE_AUTH;
+ }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
+ rc = SQLITE_DENY;
+ sqliteAuthBadReturnCode(pParse);
+ }
+ return rc;
+}
+
+/*
+** Push an authorization context. After this routine is called, the
+** zArg3 argument to authorization callbacks will be zContext until
+** popped. Or if pParse==0, this routine is a no-op.
+*/
+SQLITE_PRIVATE void sqlite3AuthContextPush(
+ Parse *pParse,
+ AuthContext *pContext,
+ const char *zContext
+){
+ assert( pParse );
+ pContext->pParse = pParse;
+ pContext->zAuthContext = pParse->zAuthContext;
+ pParse->zAuthContext = zContext;
+}
+
+/*
+** Pop an authorization context that was previously pushed
+** by sqlite3AuthContextPush
+*/
+SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
+ if( pContext->pParse ){
+ pContext->pParse->zAuthContext = pContext->zAuthContext;
+ pContext->pParse = 0;
+ }
+}
+
+#endif /* SQLITE_OMIT_AUTHORIZATION */
+
+/************** End of auth.c ************************************************/
+/************** Begin file build.c *******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains C code routines that are called by the SQLite parser
+** when syntax rules are reduced. The routines in this file handle the
+** following kinds of SQL syntax:
+**
+** CREATE TABLE
+** DROP TABLE
+** CREATE INDEX
+** DROP INDEX
+** creating ID lists
+** BEGIN TRANSACTION
+** COMMIT
+** ROLLBACK
+*/
+/* #include "sqliteInt.h" */
+
+#ifndef SQLITE_OMIT_SHARED_CACHE
+/*
+** The TableLock structure is only used by the sqlite3TableLock() and
+** codeTableLocks() functions.
+*/
+struct TableLock {
+ int iDb; /* The database containing the table to be locked */
+ Pgno iTab; /* The root page of the table to be locked */
+ u8 isWriteLock; /* True for write lock. False for a read lock */
+ const char *zLockName; /* Name of the table */
+};
+
+/*
+** Record the fact that we want to lock a table at run-time.
+**
+** The table to be locked has root page iTab and is found in database iDb.
+** A read or a write lock can be taken depending on isWritelock.
+**
+** This routine just records the fact that the lock is desired. The
+** code to make the lock occur is generated by a later call to
+** codeTableLocks() which occurs during sqlite3FinishCoding().
+*/
+SQLITE_PRIVATE void sqlite3TableLock(
+ Parse *pParse, /* Parsing context */
+ int iDb, /* Index of the database containing the table to lock */
+ Pgno iTab, /* Root page number of the table to be locked */
+ u8 isWriteLock, /* True for a write lock */
+ const char *zName /* Name of the table to be locked */
+){
+ Parse *pToplevel;
+ int i;
+ int nBytes;
+ TableLock *p;
+ assert( iDb>=0 );
+
+ if( iDb==1 ) return;
+ if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
+ pToplevel = sqlite3ParseToplevel(pParse);
+ for(i=0; i<pToplevel->nTableLock; i++){
+ p = &pToplevel->aTableLock[i];
+ if( p->iDb==iDb && p->iTab==iTab ){
+ p->isWriteLock = (p->isWriteLock || isWriteLock);
+ return;
+ }
+ }
+
+ nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
+ pToplevel->aTableLock =
+ sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
+ if( pToplevel->aTableLock ){
+ p = &pToplevel->aTableLock[pToplevel->nTableLock++];
+ p->iDb = iDb;
+ p->iTab = iTab;
+ p->isWriteLock = isWriteLock;
+ p->zLockName = zName;
+ }else{
+ pToplevel->nTableLock = 0;
+ sqlite3OomFault(pToplevel->db);
+ }
+}
+
+/*
+** Code an OP_TableLock instruction for each table locked by the
+** statement (configured by calls to sqlite3TableLock()).
+*/
+static void codeTableLocks(Parse *pParse){
+ int i;
+ Vdbe *pVdbe = pParse->pVdbe;
+ assert( pVdbe!=0 );
+
+ for(i=0; i<pParse->nTableLock; i++){
+ TableLock *p = &pParse->aTableLock[i];
+ int p1 = p->iDb;
+ sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
+ p->zLockName, P4_STATIC);
+ }
+}
+#else
+ #define codeTableLocks(x)
+#endif
+
+/*
+** Return TRUE if the given yDbMask object is empty - if it contains no
+** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
+** macros when SQLITE_MAX_ATTACHED is greater than 30.
+*/
+#if SQLITE_MAX_ATTACHED>30
+SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
+ int i;
+ for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
+ return 1;
+}
+#endif
+
+/*
+** This routine is called after a single SQL statement has been
+** parsed and a VDBE program to execute that statement has been
+** prepared. This routine puts the finishing touches on the
+** VDBE program and resets the pParse structure for the next
+** parse.
+**
+** Note that if an error occurred, it might be the case that
+** no VDBE code was generated.
+*/
+SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
+ sqlite3 *db;
+ Vdbe *v;
+
+ assert( pParse->pToplevel==0 );
+ db = pParse->db;
+ if( pParse->nested ) return;
+ if( db->mallocFailed || pParse->nErr ){
+ if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
+ return;
+ }
+
+ /* Begin by generating some termination code at the end of the
+ ** vdbe program
+ */
+ v = sqlite3GetVdbe(pParse);
+ assert( !pParse->isMultiWrite
+ || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
+ if( v ){
+ sqlite3VdbeAddOp0(v, OP_Halt);
+
+#if SQLITE_USER_AUTHENTICATION
+ if( pParse->nTableLock>0 && db->init.busy==0 ){
+ sqlite3UserAuthInit(db);
+ if( db->auth.authLevel<UAUTH_User ){
+ sqlite3ErrorMsg(pParse, "user not authenticated");
+ pParse->rc = SQLITE_AUTH_USER;
+ return;
+ }
+ }
+#endif
+
+ /* The cookie mask contains one bit for each database file open.
+ ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
+ ** set for each database that is used. Generate code to start a
+ ** transaction on each used database and to verify the schema cookie
+ ** on each used database.
+ */
+ if( db->mallocFailed==0
+ && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
+ ){
+ int iDb, i;
+ assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
+ sqlite3VdbeJumpHere(v, 0);
+ for(iDb=0; iDb<db->nDb; iDb++){
+ Schema *pSchema;
+ if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
+ sqlite3VdbeUsesBtree(v, iDb);
+ pSchema = db->aDb[iDb].pSchema;
+ sqlite3VdbeAddOp4Int(v,
+ OP_Transaction, /* Opcode */
+ iDb, /* P1 */
+ DbMaskTest(pParse->writeMask,iDb), /* P2 */
+ pSchema->schema_cookie, /* P3 */
+ pSchema->iGeneration /* P4 */
+ );
+ if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
+ VdbeComment((v,
+ "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
+ }
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ for(i=0; i<pParse->nVtabLock; i++){
+ char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
+ sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
+ }
+ pParse->nVtabLock = 0;
+#endif
+
+ /* Once all the cookies have been verified and transactions opened,
+ ** obtain the required table-locks. This is a no-op unless the
+ ** shared-cache feature is enabled.
+ */
+ codeTableLocks(pParse);
+
+ /* Initialize any AUTOINCREMENT data structures required.
+ */
+ sqlite3AutoincrementBegin(pParse);
+
+ /* Code constant expressions that where factored out of inner loops.
+ **
+ ** The pConstExpr list might also contain expressions that we simply
+ ** want to keep around until the Parse object is deleted. Such
+ ** expressions have iConstExprReg==0. Do not generate code for
+ ** those expressions, of course.
+ */
+ if( pParse->pConstExpr ){
+ ExprList *pEL = pParse->pConstExpr;
+ pParse->okConstFactor = 0;
+ for(i=0; i<pEL->nExpr; i++){
+ int iReg = pEL->a[i].u.iConstExprReg;
+ if( iReg>0 ){
+ sqlite3ExprCode(pParse, pEL->a[i].pExpr, iReg);
+ }
+ }
+ }
+
+ /* Finally, jump back to the beginning of the executable code. */
+ sqlite3VdbeGoto(v, 1);
+ }
+ }
+
+
+ /* Get the VDBE program ready for execution
+ */
+ if( v && pParse->nErr==0 && !db->mallocFailed ){
+ /* A minimum of one cursor is required if autoincrement is used
+ * See ticket [a696379c1f08866] */
+ assert( pParse->pAinc==0 || pParse->nTab>0 );
+ sqlite3VdbeMakeReady(v, pParse);
+ pParse->rc = SQLITE_DONE;
+ }else{
+ pParse->rc = SQLITE_ERROR;
+ }
+}
+
+/*
+** Run the parser and code generator recursively in order to generate
+** code for the SQL statement given onto the end of the pParse context
+** currently under construction. When the parser is run recursively
+** this way, the final OP_Halt is not appended and other initialization
+** and finalization steps are omitted because those are handling by the
+** outermost parser.
+**
+** Not everything is nestable. This facility is designed to permit
+** INSERT, UPDATE, and DELETE operations against the schema table. Use
+** care if you decide to try to use this routine for some other purposes.
+*/
+SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
+ va_list ap;
+ char *zSql;
+ char *zErrMsg = 0;
+ sqlite3 *db = pParse->db;
+ char saveBuf[PARSE_TAIL_SZ];
+
+ if( pParse->nErr ) return;
+ assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
+ va_start(ap, zFormat);
+ zSql = sqlite3VMPrintf(db, zFormat, ap);
+ va_end(ap);
+ if( zSql==0 ){
+ /* This can result either from an OOM or because the formatted string
+ ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set
+ ** an error */
+ if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
+ pParse->nErr++;
+ return;
+ }
+ pParse->nested++;
+ memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
+ memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
+ sqlite3RunParser(pParse, zSql, &zErrMsg);
+ sqlite3DbFree(db, zErrMsg);
+ sqlite3DbFree(db, zSql);
+ memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
+ pParse->nested--;
+}
+
+#if SQLITE_USER_AUTHENTICATION
+/*
+** Return TRUE if zTable is the name of the system table that stores the
+** list of users and their access credentials.
+*/
+SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
+ return sqlite3_stricmp(zTable, "sqlite_user")==0;
+}
+#endif
+
+/*
+** Locate the in-memory structure that describes a particular database
+** table given the name of that table and (optionally) the name of the
+** database containing the table. Return NULL if not found.
+**
+** If zDatabase is 0, all databases are searched for the table and the
+** first matching table is returned. (No checking for duplicate table
+** names is done.) The search order is TEMP first, then MAIN, then any
+** auxiliary databases added using the ATTACH command.
+**
+** See also sqlite3LocateTable().
+*/
+SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
+ Table *p = 0;
+ int i;
+
+ /* All mutexes are required for schema access. Make sure we hold them. */
+ assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
+#if SQLITE_USER_AUTHENTICATION
+ /* Only the admin user is allowed to know that the sqlite_user table
+ ** exists */
+ if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
+ return 0;
+ }
+#endif
+ if( zDatabase ){
+ for(i=0; i<db->nDb; i++){
+ if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break;
+ }
+ if( i>=db->nDb ){
+ /* No match against the official names. But always match "main"
+ ** to schema 0 as a legacy fallback. */
+ if( sqlite3StrICmp(zDatabase,"main")==0 ){
+ i = 0;
+ }else{
+ return 0;
+ }
+ }
+ p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
+ if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
+ if( i==1 ){
+ if( sqlite3StrICmp(zName+7, &ALT_TEMP_SCHEMA_TABLE[7])==0
+ || sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0
+ || sqlite3StrICmp(zName+7, &DFLT_SCHEMA_TABLE[7])==0
+ ){
+ p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
+ DFLT_TEMP_SCHEMA_TABLE);
+ }
+ }else{
+ if( sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 ){
+ p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash,
+ DFLT_SCHEMA_TABLE);
+ }
+ }
+ }
+ }else{
+ /* Match against TEMP first */
+ p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName);
+ if( p ) return p;
+ /* The main database is second */
+ p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName);
+ if( p ) return p;
+ /* Attached databases are in order of attachment */
+ for(i=2; i<db->nDb; i++){
+ assert( sqlite3SchemaMutexHeld(db, i, 0) );
+ p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
+ if( p ) break;
+ }
+ if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
+ if( sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 ){
+ p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, DFLT_SCHEMA_TABLE);
+ }else if( sqlite3StrICmp(zName+7, &ALT_TEMP_SCHEMA_TABLE[7])==0 ){
+ p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
+ DFLT_TEMP_SCHEMA_TABLE);
+ }
+ }
+ }
+ return p;
+}
+
+/*
+** Locate the in-memory structure that describes a particular database
+** table given the name of that table and (optionally) the name of the
+** database containing the table. Return NULL if not found. Also leave an
+** error message in pParse->zErrMsg.
+**
+** The difference between this routine and sqlite3FindTable() is that this
+** routine leaves an error message in pParse->zErrMsg where
+** sqlite3FindTable() does not.
+*/
+SQLITE_PRIVATE Table *sqlite3LocateTable(
+ Parse *pParse, /* context in which to report errors */
+ u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
+ const char *zName, /* Name of the table we are looking for */
+ const char *zDbase /* Name of the database. Might be NULL */
+){
+ Table *p;
+ sqlite3 *db = pParse->db;
+
+ /* Read the database schema. If an error occurs, leave an error message
+ ** and code in pParse and return NULL. */
+ if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
+ && SQLITE_OK!=sqlite3ReadSchema(pParse)
+ ){
+ return 0;
+ }
+
+ p = sqlite3FindTable(db, zName, zDbase);
+ if( p==0 ){
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ /* If zName is the not the name of a table in the schema created using
+ ** CREATE, then check to see if it is the name of an virtual table that
+ ** can be an eponymous virtual table. */
+ if( pParse->disableVtab==0 ){
+ Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
+ if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
+ pMod = sqlite3PragmaVtabRegister(db, zName);
+ }
+ if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
+ return pMod->pEpoTab;
+ }
+ }
+#endif
+ if( flags & LOCATE_NOERR ) return 0;
+ pParse->checkSchema = 1;
+ }else if( IsVirtual(p) && pParse->disableVtab ){
+ p = 0;
+ }
+
+ if( p==0 ){
+ const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
+ if( zDbase ){
+ sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
+ }else{
+ sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
+ }
+ }
+
+ return p;
+}
+
+/*
+** Locate the table identified by *p.
+**
+** This is a wrapper around sqlite3LocateTable(). The difference between
+** sqlite3LocateTable() and this function is that this function restricts
+** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
+** non-NULL if it is part of a view or trigger program definition. See
+** sqlite3FixSrcList() for details.
+*/
+SQLITE_PRIVATE Table *sqlite3LocateTableItem(
+ Parse *pParse,
+ u32 flags,
+ struct SrcList_item *p
+){
+ const char *zDb;
+ assert( p->pSchema==0 || p->zDatabase==0 );
+ if( p->pSchema ){
+ int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
+ zDb = pParse->db->aDb[iDb].zDbSName;
+ }else{
+ zDb = p->zDatabase;
+ }
+ return sqlite3LocateTable(pParse, flags, p->zName, zDb);
+}
+
+/*
+** Locate the in-memory structure that describes
+** a particular index given the name of that index
+** and the name of the database that contains the index.
+** Return NULL if not found.
+**
+** If zDatabase is 0, all databases are searched for the
+** table and the first matching index is returned. (No checking
+** for duplicate index names is done.) The search order is
+** TEMP first, then MAIN, then any auxiliary databases added
+** using the ATTACH command.
+*/
+SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
+ Index *p = 0;
+ int i;
+ /* All mutexes are required for schema access. Make sure we hold them. */
+ assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
+ for(i=OMIT_TEMPDB; i<db->nDb; i++){
+ int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
+ Schema *pSchema = db->aDb[j].pSchema;
+ assert( pSchema );
+ if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
+ assert( sqlite3SchemaMutexHeld(db, j, 0) );
+ p = sqlite3HashFind(&pSchema->idxHash, zName);
+ if( p ) break;
+ }
+ return p;
+}
+
+/*
+** Reclaim the memory used by an index
+*/
+SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3 *db, Index *p){
+#ifndef SQLITE_OMIT_ANALYZE
+ sqlite3DeleteIndexSamples(db, p);
+#endif
+ sqlite3ExprDelete(db, p->pPartIdxWhere);
+ sqlite3ExprListDelete(db, p->aColExpr);
+ sqlite3DbFree(db, p->zColAff);
+ if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
+#ifdef SQLITE_ENABLE_STAT4
+ sqlite3_free(p->aiRowEst);
+#endif
+ sqlite3DbFree(db, p);
+}
+
+/*
+** For the index called zIdxName which is found in the database iDb,
+** unlike that index from its Table then remove the index from
+** the index hash table and free all memory structures associated
+** with the index.
+*/
+SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
+ Index *pIndex;
+ Hash *pHash;
+
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ pHash = &db->aDb[iDb].pSchema->idxHash;
+ pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
+ if( ALWAYS(pIndex) ){
+ if( pIndex->pTable->pIndex==pIndex ){
+ pIndex->pTable->pIndex = pIndex->pNext;
+ }else{
+ Index *p;
+ /* Justification of ALWAYS(); The index must be on the list of
+ ** indices. */
+ p = pIndex->pTable->pIndex;
+ while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
+ if( ALWAYS(p && p->pNext==pIndex) ){
+ p->pNext = pIndex->pNext;
+ }
+ }
+ sqlite3FreeIndex(db, pIndex);
+ }
+ db->mDbFlags |= DBFLAG_SchemaChange;
+}
+
+/*
+** Look through the list of open database files in db->aDb[] and if
+** any have been closed, remove them from the list. Reallocate the
+** db->aDb[] structure to a smaller size, if possible.
+**
+** Entry 0 (the "main" database) and entry 1 (the "temp" database)
+** are never candidates for being collapsed.
+*/
+SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
+ int i, j;
+ for(i=j=2; i<db->nDb; i++){
+ struct Db *pDb = &db->aDb[i];
+ if( pDb->pBt==0 ){
+ sqlite3DbFree(db, pDb->zDbSName);
+ pDb->zDbSName = 0;
+ continue;
+ }
+ if( j<i ){
+ db->aDb[j] = db->aDb[i];
+ }
+ j++;
+ }
+ db->nDb = j;
+ if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
+ memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
+ sqlite3DbFree(db, db->aDb);
+ db->aDb = db->aDbStatic;
+ }
+}
+
+/*
+** Reset the schema for the database at index iDb. Also reset the
+** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
+** Deferred resets may be run by calling with iDb<0.
+*/
+SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
+ int i;
+ assert( iDb<db->nDb );
+
+ if( iDb>=0 ){
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ DbSetProperty(db, iDb, DB_ResetWanted);
+ DbSetProperty(db, 1, DB_ResetWanted);
+ db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
+ }
+
+ if( db->nSchemaLock==0 ){
+ for(i=0; i<db->nDb; i++){
+ if( DbHasProperty(db, i, DB_ResetWanted) ){
+ sqlite3SchemaClear(db->aDb[i].pSchema);
+ }
+ }
+ }
+}
+
+/*
+** Erase all schema information from all attached databases (including
+** "main" and "temp") for a single database connection.
+*/
+SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
+ int i;
+ sqlite3BtreeEnterAll(db);
+ for(i=0; i<db->nDb; i++){
+ Db *pDb = &db->aDb[i];
+ if( pDb->pSchema ){
+ if( db->nSchemaLock==0 ){
+ sqlite3SchemaClear(pDb->pSchema);
+ }else{
+ DbSetProperty(db, i, DB_ResetWanted);
+ }
+ }
+ }
+ db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
+ sqlite3VtabUnlockList(db);
+ sqlite3BtreeLeaveAll(db);
+ if( db->nSchemaLock==0 ){
+ sqlite3CollapseDatabaseArray(db);
+ }
+}
+
+/*
+** This routine is called when a commit occurs.
+*/
+SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
+ db->mDbFlags &= ~DBFLAG_SchemaChange;
+}
+
+/*
+** Delete memory allocated for the column names of a table or view (the
+** Table.aCol[] array).
+*/
+SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
+ int i;
+ Column *pCol;
+ assert( pTable!=0 );
+ if( (pCol = pTable->aCol)!=0 ){
+ for(i=0; i<pTable->nCol; i++, pCol++){
+ assert( pCol->zName==0 || pCol->hName==sqlite3StrIHash(pCol->zName) );
+ sqlite3DbFree(db, pCol->zName);
+ sqlite3ExprDelete(db, pCol->pDflt);
+ sqlite3DbFree(db, pCol->zColl);
+ }
+ sqlite3DbFree(db, pTable->aCol);
+ }
+}
+
+/*
+** Remove the memory data structures associated with the given
+** Table. No changes are made to disk by this routine.
+**
+** This routine just deletes the data structure. It does not unlink
+** the table data structure from the hash table. But it does destroy
+** memory structures of the indices and foreign keys associated with
+** the table.
+**
+** The db parameter is optional. It is needed if the Table object
+** contains lookaside memory. (Table objects in the schema do not use
+** lookaside memory, but some ephemeral Table objects do.) Or the
+** db parameter can be used with db->pnBytesFreed to measure the memory
+** used by the Table object.
+*/
+static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
+ Index *pIndex, *pNext;
+
+#ifdef SQLITE_DEBUG
+ /* Record the number of outstanding lookaside allocations in schema Tables
+ ** prior to doing any free() operations. Since schema Tables do not use
+ ** lookaside, this number should not change.
+ **
+ ** If malloc has already failed, it may be that it failed while allocating
+ ** a Table object that was going to be marked ephemeral. So do not check
+ ** that no lookaside memory is used in this case either. */
+ int nLookaside = 0;
+ if( db && !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
+ nLookaside = sqlite3LookasideUsed(db, 0);
+ }
+#endif
+
+ /* Delete all indices associated with this table. */
+ for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
+ pNext = pIndex->pNext;
+ assert( pIndex->pSchema==pTable->pSchema
+ || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
+ if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
+ char *zName = pIndex->zName;
+ TESTONLY ( Index *pOld = ) sqlite3HashInsert(
+ &pIndex->pSchema->idxHash, zName, 0
+ );
+ assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
+ assert( pOld==pIndex || pOld==0 );
+ }
+ sqlite3FreeIndex(db, pIndex);
+ }
+
+ /* Delete any foreign keys attached to this table. */
+ sqlite3FkDelete(db, pTable);
+
+ /* Delete the Table structure itself.
+ */
+ sqlite3DeleteColumnNames(db, pTable);
+ sqlite3DbFree(db, pTable->zName);
+ sqlite3DbFree(db, pTable->zColAff);
+ sqlite3SelectDelete(db, pTable->pSelect);
+ sqlite3ExprListDelete(db, pTable->pCheck);
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ sqlite3VtabClear(db, pTable);
+#endif
+ sqlite3DbFree(db, pTable);
+
+ /* Verify that no lookaside memory was used by schema tables */
+ assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
+}
+SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
+ /* Do not delete the table until the reference count reaches zero. */
+ if( !pTable ) return;
+ if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
+ deleteTable(db, pTable);
+}
+
+
+/*
+** Unlink the given table from the hash tables and the delete the
+** table structure with all its indices and foreign keys.
+*/
+SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
+ Table *p;
+ Db *pDb;
+
+ assert( db!=0 );
+ assert( iDb>=0 && iDb<db->nDb );
+ assert( zTabName );
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
+ pDb = &db->aDb[iDb];
+ p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
+ sqlite3DeleteTable(db, p);
+ db->mDbFlags |= DBFLAG_SchemaChange;
+}
+
+/*
+** Given a token, return a string that consists of the text of that
+** token. Space to hold the returned string
+** is obtained from sqliteMalloc() and must be freed by the calling
+** function.
+**
+** Any quotation marks (ex: "name", 'name', [name], or `name`) that
+** surround the body of the token are removed.
+**
+** Tokens are often just pointers into the original SQL text and so
+** are not \000 terminated and are not persistent. The returned string
+** is \000 terminated and is persistent.
+*/
+SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
+ char *zName;
+ if( pName ){
+ zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
+ sqlite3Dequote(zName);
+ }else{
+ zName = 0;
+ }
+ return zName;
+}
+
+/*
+** Open the sqlite_schema table stored in database number iDb for
+** writing. The table is opened using cursor 0.
+*/
+SQLITE_PRIVATE void sqlite3OpenSchemaTable(Parse *p, int iDb){
+ Vdbe *v = sqlite3GetVdbe(p);
+ sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, DFLT_SCHEMA_TABLE);
+ sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, SCHEMA_ROOT, iDb, 5);
+ if( p->nTab==0 ){
+ p->nTab = 1;
+ }
+}
+
+/*
+** Parameter zName points to a nul-terminated buffer containing the name
+** of a database ("main", "temp" or the name of an attached db). This
+** function returns the index of the named database in db->aDb[], or
+** -1 if the named db cannot be found.
+*/
+SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
+ int i = -1; /* Database number */
+ if( zName ){
+ Db *pDb;
+ for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
+ if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
+ /* "main" is always an acceptable alias for the primary database
+ ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
+ if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
+ }
+ }
+ return i;
+}
+
+/*
+** The token *pName contains the name of a database (either "main" or
+** "temp" or the name of an attached db). This routine returns the
+** index of the named database in db->aDb[], or -1 if the named db
+** does not exist.
+*/
+SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
+ int i; /* Database number */
+ char *zName; /* Name we are searching for */
+ zName = sqlite3NameFromToken(db, pName);
+ i = sqlite3FindDbName(db, zName);
+ sqlite3DbFree(db, zName);
+ return i;
+}
+
+/* The table or view or trigger name is passed to this routine via tokens
+** pName1 and pName2. If the table name was fully qualified, for example:
+**
+** CREATE TABLE xxx.yyy (...);
+**
+** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
+** the table name is not fully qualified, i.e.:
+**
+** CREATE TABLE yyy(...);
+**
+** Then pName1 is set to "yyy" and pName2 is "".
+**
+** This routine sets the *ppUnqual pointer to point at the token (pName1 or
+** pName2) that stores the unqualified table name. The index of the
+** database "xxx" is returned.
+*/
+SQLITE_PRIVATE int sqlite3TwoPartName(
+ Parse *pParse, /* Parsing and code generating context */
+ Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
+ Token *pName2, /* The "yyy" in the name "xxx.yyy" */
+ Token **pUnqual /* Write the unqualified object name here */
+){
+ int iDb; /* Database holding the object */
+ sqlite3 *db = pParse->db;
+
+ assert( pName2!=0 );
+ if( pName2->n>0 ){
+ if( db->init.busy ) {
+ sqlite3ErrorMsg(pParse, "corrupt database");
+ return -1;
+ }
+ *pUnqual = pName2;
+ iDb = sqlite3FindDb(db, pName1);
+ if( iDb<0 ){
+ sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
+ return -1;
+ }
+ }else{
+ assert( db->init.iDb==0 || db->init.busy || IN_RENAME_OBJECT
+ || (db->mDbFlags & DBFLAG_Vacuum)!=0);
+ iDb = db->init.iDb;
+ *pUnqual = pName1;
+ }
+ return iDb;
+}
+
+/*
+** True if PRAGMA writable_schema is ON
+*/
+SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3 *db){
+ testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
+ testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
+ SQLITE_WriteSchema );
+ testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
+ SQLITE_Defensive );
+ testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
+ (SQLITE_WriteSchema|SQLITE_Defensive) );
+ return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
+}
+
+/*
+** This routine is used to check if the UTF-8 string zName is a legal
+** unqualified name for a new schema object (table, index, view or
+** trigger). All names are legal except those that begin with the string
+** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
+** is reserved for internal use.
+**
+** When parsing the sqlite_schema table, this routine also checks to
+** make sure the "type", "name", and "tbl_name" columns are consistent
+** with the SQL.
+*/
+SQLITE_PRIVATE int sqlite3CheckObjectName(
+ Parse *pParse, /* Parsing context */
+ const char *zName, /* Name of the object to check */
+ const char *zType, /* Type of this object */
+ const char *zTblName /* Parent table name for triggers and indexes */
+){
+ sqlite3 *db = pParse->db;
+ if( sqlite3WritableSchema(db)
+ || db->init.imposterTable
+ || !sqlite3Config.bExtraSchemaChecks
+ ){
+ /* Skip these error checks for writable_schema=ON */
+ return SQLITE_OK;
+ }
+ if( db->init.busy ){
+ if( sqlite3_stricmp(zType, db->init.azInit[0])
+ || sqlite3_stricmp(zName, db->init.azInit[1])
+ || sqlite3_stricmp(zTblName, db->init.azInit[2])
+ ){
+ sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
+ return SQLITE_ERROR;
+ }
+ }else{
+ if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
+ || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
+ ){
+ sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
+ zName);
+ return SQLITE_ERROR;
+ }
+
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Return the PRIMARY KEY index of a table
+*/
+SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
+ Index *p;
+ for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
+ return p;
+}
+
+/*
+** Convert an table column number into a index column number. That is,
+** for the column iCol in the table (as defined by the CREATE TABLE statement)
+** find the (first) offset of that column in index pIdx. Or return -1
+** if column iCol is not used in index pIdx.
+*/
+SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){
+ int i;
+ for(i=0; i<pIdx->nColumn; i++){
+ if( iCol==pIdx->aiColumn[i] ) return i;
+ }
+ return -1;
+}
+
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+/* Convert a storage column number into a table column number.
+**
+** The storage column number (0,1,2,....) is the index of the value
+** as it appears in the record on disk. The true column number
+** is the index (0,1,2,...) of the column in the CREATE TABLE statement.
+**
+** The storage column number is less than the table column number if
+** and only there are VIRTUAL columns to the left.
+**
+** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
+*/
+SQLITE_PRIVATE i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){
+ if( pTab->tabFlags & TF_HasVirtual ){
+ int i;
+ for(i=0; i<=iCol; i++){
+ if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
+ }
+ }
+ return iCol;
+}
+#endif
+
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+/* Convert a table column number into a storage column number.
+**
+** The storage column number (0,1,2,....) is the index of the value
+** as it appears in the record on disk. Or, if the input column is
+** the N-th virtual column (zero-based) then the storage number is
+** the number of non-virtual columns in the table plus N.
+**
+** The true column number is the index (0,1,2,...) of the column in
+** the CREATE TABLE statement.
+**
+** If the input column is a VIRTUAL column, then it should not appear
+** in storage. But the value sometimes is cached in registers that
+** follow the range of registers used to construct storage. This
+** avoids computing the same VIRTUAL column multiple times, and provides
+** values for use by OP_Param opcodes in triggers. Hence, if the
+** input column is a VIRTUAL table, put it after all the other columns.
+**
+** In the following, N means "normal column", S means STORED, and
+** V means VIRTUAL. Suppose the CREATE TABLE has columns like this:
+**
+** CREATE TABLE ex(N,S,V,N,S,V,N,S,V);
+** -- 0 1 2 3 4 5 6 7 8
+**
+** Then the mapping from this function is as follows:
+**
+** INPUTS: 0 1 2 3 4 5 6 7 8
+** OUTPUTS: 0 1 6 2 3 7 4 5 8
+**
+** So, in other words, this routine shifts all the virtual columns to
+** the end.
+**
+** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and
+** this routine is a no-op macro. If the pTab does not have any virtual
+** columns, then this routine is no-op that always return iCol. If iCol
+** is negative (indicating the ROWID column) then this routine return iCol.
+*/
+SQLITE_PRIVATE i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){
+ int i;
+ i16 n;
+ assert( iCol<pTab->nCol );
+ if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
+ for(i=0, n=0; i<iCol; i++){
+ if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
+ }
+ if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
+ /* iCol is a virtual column itself */
+ return pTab->nNVCol + i - n;
+ }else{
+ /* iCol is a normal or stored column */
+ return n;
+ }
+}
+#endif
+
+/*
+** Begin constructing a new table representation in memory. This is
+** the first of several action routines that get called in response
+** to a CREATE TABLE statement. In particular, this routine is called
+** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
+** flag is true if the table should be stored in the auxiliary database
+** file instead of in the main database file. This is normally the case
+** when the "TEMP" or "TEMPORARY" keyword occurs in between
+** CREATE and TABLE.
+**
+** The new table record is initialized and put in pParse->pNewTable.
+** As more of the CREATE TABLE statement is parsed, additional action
+** routines will be called to add more information to this record.
+** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
+** is called to complete the construction of the new table record.
+*/
+SQLITE_PRIVATE void sqlite3StartTable(
+ Parse *pParse, /* Parser context */
+ Token *pName1, /* First part of the name of the table or view */
+ Token *pName2, /* Second part of the name of the table or view */
+ int isTemp, /* True if this is a TEMP table */
+ int isView, /* True if this is a VIEW */
+ int isVirtual, /* True if this is a VIRTUAL table */
+ int noErr /* Do nothing if table already exists */
+){
+ Table *pTable;
+ char *zName = 0; /* The name of the new table */
+ sqlite3 *db = pParse->db;
+ Vdbe *v;
+ int iDb; /* Database number to create the table in */
+ Token *pName; /* Unqualified name of the table to create */
+
+ if( db->init.busy && db->init.newTnum==1 ){
+ /* Special case: Parsing the sqlite_schema or sqlite_temp_schema schema */
+ iDb = db->init.iDb;
+ zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
+ pName = pName1;
+ }else{
+ /* The common case */
+ iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
+ if( iDb<0 ) return;
+ if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
+ /* If creating a temp table, the name may not be qualified. Unless
+ ** the database name is "temp" anyway. */
+ sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
+ return;
+ }
+ if( !OMIT_TEMPDB && isTemp ) iDb = 1;
+ zName = sqlite3NameFromToken(db, pName);
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameTokenMap(pParse, (void*)zName, pName);
+ }
+ }
+ pParse->sNameToken = *pName;
+ if( zName==0 ) return;
+ if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){
+ goto begin_table_error;
+ }
+ if( db->init.iDb==1 ) isTemp = 1;
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ assert( isTemp==0 || isTemp==1 );
+ assert( isView==0 || isView==1 );
+ {
+ static const u8 aCode[] = {
+ SQLITE_CREATE_TABLE,
+ SQLITE_CREATE_TEMP_TABLE,
+ SQLITE_CREATE_VIEW,
+ SQLITE_CREATE_TEMP_VIEW
+ };
+ char *zDb = db->aDb[iDb].zDbSName;
+ if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
+ goto begin_table_error;
+ }
+ if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
+ zName, 0, zDb) ){
+ goto begin_table_error;
+ }
+ }
+#endif
+
+ /* Make sure the new table name does not collide with an existing
+ ** index or table name in the same database. Issue an error message if
+ ** it does. The exception is if the statement being parsed was passed
+ ** to an sqlite3_declare_vtab() call. In that case only the column names
+ ** and types will be used, so there is no need to test for namespace
+ ** collisions.
+ */
+ if( !IN_SPECIAL_PARSE ){
+ char *zDb = db->aDb[iDb].zDbSName;
+ if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
+ goto begin_table_error;
+ }
+ pTable = sqlite3FindTable(db, zName, zDb);
+ if( pTable ){
+ if( !noErr ){
+ sqlite3ErrorMsg(pParse, "table %T already exists", pName);
+ }else{
+ assert( !db->init.busy || CORRUPT_DB );
+ sqlite3CodeVerifySchema(pParse, iDb);
+ }
+ goto begin_table_error;
+ }
+ if( sqlite3FindIndex(db, zName, zDb)!=0 ){
+ sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
+ goto begin_table_error;
+ }
+ }
+
+ pTable = sqlite3DbMallocZero(db, sizeof(Table));
+ if( pTable==0 ){
+ assert( db->mallocFailed );
+ pParse->rc = SQLITE_NOMEM_BKPT;
+ pParse->nErr++;
+ goto begin_table_error;
+ }
+ pTable->zName = zName;
+ pTable->iPKey = -1;
+ pTable->pSchema = db->aDb[iDb].pSchema;
+ pTable->nTabRef = 1;
+#ifdef SQLITE_DEFAULT_ROWEST
+ pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
+#else
+ pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
+#endif
+ assert( pParse->pNewTable==0 );
+ pParse->pNewTable = pTable;
+
+ /* If this is the magic sqlite_sequence table used by autoincrement,
+ ** then record a pointer to this table in the main database structure
+ ** so that INSERT can find the table easily.
+ */
+#ifndef SQLITE_OMIT_AUTOINCREMENT
+ if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ pTable->pSchema->pSeqTab = pTable;
+ }
+#endif
+
+ /* Begin generating the code that will insert the table record into
+ ** the schema table. Note in particular that we must go ahead
+ ** and allocate the record number for the table entry now. Before any
+ ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
+ ** indices to be created and the table record must come before the
+ ** indices. Hence, the record number for the table must be allocated
+ ** now.
+ */
+ if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
+ int addr1;
+ int fileFormat;
+ int reg1, reg2, reg3;
+ /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
+ static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
+ sqlite3BeginWriteOperation(pParse, 1, iDb);
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( isVirtual ){
+ sqlite3VdbeAddOp0(v, OP_VBegin);
+ }
+#endif
+
+ /* If the file format and encoding in the database have not been set,
+ ** set them now.
+ */
+ reg1 = pParse->regRowid = ++pParse->nMem;
+ reg2 = pParse->regRoot = ++pParse->nMem;
+ reg3 = ++pParse->nMem;
+ sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
+ sqlite3VdbeUsesBtree(v, iDb);
+ addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
+ fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
+ 1 : SQLITE_MAX_FILE_FORMAT;
+ sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
+ sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
+ sqlite3VdbeJumpHere(v, addr1);
+
+ /* This just creates a place-holder record in the sqlite_schema table.
+ ** The record created does not contain anything yet. It will be replaced
+ ** by the real entry in code generated at sqlite3EndTable().
+ **
+ ** The rowid for the new entry is left in register pParse->regRowid.
+ ** The root page number of the new table is left in reg pParse->regRoot.
+ ** The rowid and root page number values are needed by the code that
+ ** sqlite3EndTable will generate.
+ */
+#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
+ if( isView || isVirtual ){
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
+ }else
+#endif
+ {
+ pParse->addrCrTab =
+ sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
+ }
+ sqlite3OpenSchemaTable(pParse, iDb);
+ sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
+ sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
+ sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
+ sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
+ sqlite3VdbeAddOp0(v, OP_Close);
+ }
+
+ /* Normal (non-error) return. */
+ return;
+
+ /* If an error occurs, we jump here */
+begin_table_error:
+ sqlite3DbFree(db, zName);
+ return;
+}
+
+/* Set properties of a table column based on the (magical)
+** name of the column.
+*/
+#if SQLITE_ENABLE_HIDDEN_COLUMNS
+SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
+ if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
+ pCol->colFlags |= COLFLAG_HIDDEN;
+ }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
+ pTab->tabFlags |= TF_OOOHidden;
+ }
+}
+#endif
+
+
+/*
+** Add a new column to the table currently being constructed.
+**
+** The parser calls this routine once for each column declaration
+** in a CREATE TABLE statement. sqlite3StartTable() gets called
+** first to get things going. Then this routine is called for each
+** column.
+*/
+SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
+ Table *p;
+ int i;
+ char *z;
+ char *zType;
+ Column *pCol;
+ sqlite3 *db = pParse->db;
+ if( (p = pParse->pNewTable)==0 ) return;
+ if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
+ sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
+ return;
+ }
+ z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
+ if( z==0 ) return;
+ if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName);
+ memcpy(z, pName->z, pName->n);
+ z[pName->n] = 0;
+ sqlite3Dequote(z);
+ for(i=0; i<p->nCol; i++){
+ if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
+ sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
+ sqlite3DbFree(db, z);
+ return;
+ }
+ }
+ if( (p->nCol & 0x7)==0 ){
+ Column *aNew;
+ aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
+ if( aNew==0 ){
+ sqlite3DbFree(db, z);
+ return;
+ }
+ p->aCol = aNew;
+ }
+ pCol = &p->aCol[p->nCol];
+ memset(pCol, 0, sizeof(p->aCol[0]));
+ pCol->zName = z;
+ pCol->hName = sqlite3StrIHash(z);
+ sqlite3ColumnPropertiesFromName(p, pCol);
+
+ if( pType->n==0 ){
+ /* If there is no type specified, columns have the default affinity
+ ** 'BLOB' with a default size of 4 bytes. */
+ pCol->affinity = SQLITE_AFF_BLOB;
+ pCol->szEst = 1;
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ if( 4>=sqlite3GlobalConfig.szSorterRef ){
+ pCol->colFlags |= COLFLAG_SORTERREF;
+ }
+#endif
+ }else{
+ zType = z + sqlite3Strlen30(z) + 1;
+ memcpy(zType, pType->z, pType->n);
+ zType[pType->n] = 0;
+ sqlite3Dequote(zType);
+ pCol->affinity = sqlite3AffinityType(zType, pCol);
+ pCol->colFlags |= COLFLAG_HASTYPE;
+ }
+ p->nCol++;
+ p->nNVCol++;
+ pParse->constraintName.n = 0;
+}
+
+/*
+** This routine is called by the parser while in the middle of
+** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
+** been seen on a column. This routine sets the notNull flag on
+** the column currently under construction.
+*/
+SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
+ Table *p;
+ Column *pCol;
+ p = pParse->pNewTable;
+ if( p==0 || NEVER(p->nCol<1) ) return;
+ pCol = &p->aCol[p->nCol-1];
+ pCol->notNull = (u8)onError;
+ p->tabFlags |= TF_HasNotNull;
+
+ /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
+ ** on this column. */
+ if( pCol->colFlags & COLFLAG_UNIQUE ){
+ Index *pIdx;
+ for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
+ assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
+ if( pIdx->aiColumn[0]==p->nCol-1 ){
+ pIdx->uniqNotNull = 1;
+ }
+ }
+ }
+}
+
+/*
+** Scan the column type name zType (length nType) and return the
+** associated affinity type.
+**
+** This routine does a case-independent search of zType for the
+** substrings in the following table. If one of the substrings is
+** found, the corresponding affinity is returned. If zType contains
+** more than one of the substrings, entries toward the top of
+** the table take priority. For example, if zType is 'BLOBINT',
+** SQLITE_AFF_INTEGER is returned.
+**
+** Substring | Affinity
+** --------------------------------
+** 'INT' | SQLITE_AFF_INTEGER
+** 'CHAR' | SQLITE_AFF_TEXT
+** 'CLOB' | SQLITE_AFF_TEXT
+** 'TEXT' | SQLITE_AFF_TEXT
+** 'BLOB' | SQLITE_AFF_BLOB
+** 'REAL' | SQLITE_AFF_REAL
+** 'FLOA' | SQLITE_AFF_REAL
+** 'DOUB' | SQLITE_AFF_REAL
+**
+** If none of the substrings in the above table are found,
+** SQLITE_AFF_NUMERIC is returned.
+*/
+SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, Column *pCol){
+ u32 h = 0;
+ char aff = SQLITE_AFF_NUMERIC;
+ const char *zChar = 0;
+
+ assert( zIn!=0 );
+ while( zIn[0] ){
+ h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
+ zIn++;
+ if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
+ aff = SQLITE_AFF_TEXT;
+ zChar = zIn;
+ }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
+ aff = SQLITE_AFF_TEXT;
+ }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
+ aff = SQLITE_AFF_TEXT;
+ }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
+ && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
+ aff = SQLITE_AFF_BLOB;
+ if( zIn[0]=='(' ) zChar = zIn;
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
+ && aff==SQLITE_AFF_NUMERIC ){
+ aff = SQLITE_AFF_REAL;
+ }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
+ && aff==SQLITE_AFF_NUMERIC ){
+ aff = SQLITE_AFF_REAL;
+ }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
+ && aff==SQLITE_AFF_NUMERIC ){
+ aff = SQLITE_AFF_REAL;
+#endif
+ }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
+ aff = SQLITE_AFF_INTEGER;
+ break;
+ }
+ }
+
+ /* If pCol is not NULL, store an estimate of the field size. The
+ ** estimate is scaled so that the size of an integer is 1. */
+ if( pCol ){
+ int v = 0; /* default size is approx 4 bytes */
+ if( aff<SQLITE_AFF_NUMERIC ){
+ if( zChar ){
+ while( zChar[0] ){
+ if( sqlite3Isdigit(zChar[0]) ){
+ /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
+ sqlite3GetInt32(zChar, &v);
+ break;
+ }
+ zChar++;
+ }
+ }else{
+ v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
+ }
+ }
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ if( v>=sqlite3GlobalConfig.szSorterRef ){
+ pCol->colFlags |= COLFLAG_SORTERREF;
+ }
+#endif
+ v = v/4 + 1;
+ if( v>255 ) v = 255;
+ pCol->szEst = v;
+ }
+ return aff;
+}
+
+/*
+** The expression is the default value for the most recently added column
+** of the table currently under construction.
+**
+** Default value expressions must be constant. Raise an exception if this
+** is not the case.
+**
+** This routine is called by the parser while in the middle of
+** parsing a CREATE TABLE statement.
+*/
+SQLITE_PRIVATE void sqlite3AddDefaultValue(
+ Parse *pParse, /* Parsing context */
+ Expr *pExpr, /* The parsed expression of the default value */
+ const char *zStart, /* Start of the default value text */
+ const char *zEnd /* First character past end of defaut value text */
+){
+ Table *p;
+ Column *pCol;
+ sqlite3 *db = pParse->db;
+ p = pParse->pNewTable;
+ if( p!=0 ){
+ int isInit = db->init.busy && db->init.iDb!=1;
+ pCol = &(p->aCol[p->nCol-1]);
+ if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){
+ sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
+ pCol->zName);
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ }else if( pCol->colFlags & COLFLAG_GENERATED ){
+ testcase( pCol->colFlags & COLFLAG_VIRTUAL );
+ testcase( pCol->colFlags & COLFLAG_STORED );
+ sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
+#endif
+ }else{
+ /* A copy of pExpr is used instead of the original, as pExpr contains
+ ** tokens that point to volatile memory.
+ */
+ Expr x;
+ sqlite3ExprDelete(db, pCol->pDflt);
+ memset(&x, 0, sizeof(x));
+ x.op = TK_SPAN;
+ x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
+ x.pLeft = pExpr;
+ x.flags = EP_Skip;
+ pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
+ sqlite3DbFree(db, x.u.zToken);
+ }
+ }
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameExprUnmap(pParse, pExpr);
+ }
+ sqlite3ExprDelete(db, pExpr);
+}
+
+/*
+** Backwards Compatibility Hack:
+**
+** Historical versions of SQLite accepted strings as column names in
+** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
+**
+** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
+** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
+**
+** This is goofy. But to preserve backwards compatibility we continue to
+** accept it. This routine does the necessary conversion. It converts
+** the expression given in its argument from a TK_STRING into a TK_ID
+** if the expression is just a TK_STRING with an optional COLLATE clause.
+** If the expression is anything other than TK_STRING, the expression is
+** unchanged.
+*/
+static void sqlite3StringToId(Expr *p){
+ if( p->op==TK_STRING ){
+ p->op = TK_ID;
+ }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
+ p->pLeft->op = TK_ID;
+ }
+}
+
+/*
+** Tag the given column as being part of the PRIMARY KEY
+*/
+static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
+ pCol->colFlags |= COLFLAG_PRIMKEY;
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ if( pCol->colFlags & COLFLAG_GENERATED ){
+ testcase( pCol->colFlags & COLFLAG_VIRTUAL );
+ testcase( pCol->colFlags & COLFLAG_STORED );
+ sqlite3ErrorMsg(pParse,
+ "generated columns cannot be part of the PRIMARY KEY");
+ }
+#endif
+}
+
+/*
+** Designate the PRIMARY KEY for the table. pList is a list of names
+** of columns that form the primary key. If pList is NULL, then the
+** most recently added column of the table is the primary key.
+**
+** A table can have at most one primary key. If the table already has
+** a primary key (and this is the second primary key) then create an
+** error.
+**
+** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
+** then we will try to use that column as the rowid. Set the Table.iPKey
+** field of the table under construction to be the index of the
+** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
+** no INTEGER PRIMARY KEY.
+**
+** If the key is not an INTEGER PRIMARY KEY, then create a unique
+** index for the key. No index is created for INTEGER PRIMARY KEYs.
+*/
+SQLITE_PRIVATE void sqlite3AddPrimaryKey(
+ Parse *pParse, /* Parsing context */
+ ExprList *pList, /* List of field names to be indexed */
+ int onError, /* What to do with a uniqueness conflict */
+ int autoInc, /* True if the AUTOINCREMENT keyword is present */
+ int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
+){
+ Table *pTab = pParse->pNewTable;
+ Column *pCol = 0;
+ int iCol = -1, i;
+ int nTerm;
+ if( pTab==0 ) goto primary_key_exit;
+ if( pTab->tabFlags & TF_HasPrimaryKey ){
+ sqlite3ErrorMsg(pParse,
+ "table \"%s\" has more than one primary key", pTab->zName);
+ goto primary_key_exit;
+ }
+ pTab->tabFlags |= TF_HasPrimaryKey;
+ if( pList==0 ){
+ iCol = pTab->nCol - 1;
+ pCol = &pTab->aCol[iCol];
+ makeColumnPartOfPrimaryKey(pParse, pCol);
+ nTerm = 1;
+ }else{
+ nTerm = pList->nExpr;
+ for(i=0; i<nTerm; i++){
+ Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
+ assert( pCExpr!=0 );
+ sqlite3StringToId(pCExpr);
+ if( pCExpr->op==TK_ID ){
+ const char *zCName = pCExpr->u.zToken;
+ for(iCol=0; iCol<pTab->nCol; iCol++){
+ if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
+ pCol = &pTab->aCol[iCol];
+ makeColumnPartOfPrimaryKey(pParse, pCol);
+ break;
+ }
+ }
+ }
+ }
+ }
+ if( nTerm==1
+ && pCol
+ && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
+ && sortOrder!=SQLITE_SO_DESC
+ ){
+ if( IN_RENAME_OBJECT && pList ){
+ Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
+ sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
+ }
+ pTab->iPKey = iCol;
+ pTab->keyConf = (u8)onError;
+ assert( autoInc==0 || autoInc==1 );
+ pTab->tabFlags |= autoInc*TF_Autoincrement;
+ if( pList ) pParse->iPkSortOrder = pList->a[0].sortFlags;
+ (void)sqlite3HasExplicitNulls(pParse, pList);
+ }else if( autoInc ){
+#ifndef SQLITE_OMIT_AUTOINCREMENT
+ sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
+ "INTEGER PRIMARY KEY");
+#endif
+ }else{
+ sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
+ 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
+ pList = 0;
+ }
+
+primary_key_exit:
+ sqlite3ExprListDelete(pParse->db, pList);
+ return;
+}
+
+/*
+** Add a new CHECK constraint to the table currently under construction.
+*/
+SQLITE_PRIVATE void sqlite3AddCheckConstraint(
+ Parse *pParse, /* Parsing context */
+ Expr *pCheckExpr, /* The check expression */
+ const char *zStart, /* Opening "(" */
+ const char *zEnd /* Closing ")" */
+){
+#ifndef SQLITE_OMIT_CHECK
+ Table *pTab = pParse->pNewTable;
+ sqlite3 *db = pParse->db;
+ if( pTab && !IN_DECLARE_VTAB
+ && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
+ ){
+ pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
+ if( pParse->constraintName.n ){
+ sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
+ }else{
+ Token t;
+ for(zStart++; sqlite3Isspace(zStart[0]); zStart++){}
+ while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; }
+ t.z = zStart;
+ t.n = (int)(zEnd - t.z);
+ sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1);
+ }
+ }else
+#endif
+ {
+ sqlite3ExprDelete(pParse->db, pCheckExpr);
+ }
+}
+
+/*
+** Set the collation function of the most recently parsed table column
+** to the CollSeq given.
+*/
+SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
+ Table *p;
+ int i;
+ char *zColl; /* Dequoted name of collation sequence */
+ sqlite3 *db;
+
+ if( (p = pParse->pNewTable)==0 ) return;
+ i = p->nCol-1;
+ db = pParse->db;
+ zColl = sqlite3NameFromToken(db, pToken);
+ if( !zColl ) return;
+
+ if( sqlite3LocateCollSeq(pParse, zColl) ){
+ Index *pIdx;
+ sqlite3DbFree(db, p->aCol[i].zColl);
+ p->aCol[i].zColl = zColl;
+
+ /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
+ ** then an index may have been created on this column before the
+ ** collation type was added. Correct this if it is the case.
+ */
+ for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
+ assert( pIdx->nKeyCol==1 );
+ if( pIdx->aiColumn[0]==i ){
+ pIdx->azColl[0] = p->aCol[i].zColl;
+ }
+ }
+ }else{
+ sqlite3DbFree(db, zColl);
+ }
+}
+
+/* Change the most recently parsed column to be a GENERATED ALWAYS AS
+** column.
+*/
+SQLITE_PRIVATE void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ u8 eType = COLFLAG_VIRTUAL;
+ Table *pTab = pParse->pNewTable;
+ Column *pCol;
+ if( pTab==0 ){
+ /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
+ goto generated_done;
+ }
+ pCol = &(pTab->aCol[pTab->nCol-1]);
+ if( IN_DECLARE_VTAB ){
+ sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
+ goto generated_done;
+ }
+ if( pCol->pDflt ) goto generated_error;
+ if( pType ){
+ if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
+ /* no-op */
+ }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
+ eType = COLFLAG_STORED;
+ }else{
+ goto generated_error;
+ }
+ }
+ if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
+ pCol->colFlags |= eType;
+ assert( TF_HasVirtual==COLFLAG_VIRTUAL );
+ assert( TF_HasStored==COLFLAG_STORED );
+ pTab->tabFlags |= eType;
+ if( pCol->colFlags & COLFLAG_PRIMKEY ){
+ makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
+ }
+ pCol->pDflt = pExpr;
+ pExpr = 0;
+ goto generated_done;
+
+generated_error:
+ sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
+ pCol->zName);
+generated_done:
+ sqlite3ExprDelete(pParse->db, pExpr);
+#else
+ /* Throw and error for the GENERATED ALWAYS AS clause if the
+ ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
+ sqlite3ErrorMsg(pParse, "generated columns not supported");
+ sqlite3ExprDelete(pParse->db, pExpr);
+#endif
+}
+
+/*
+** Generate code that will increment the schema cookie.
+**
+** The schema cookie is used to determine when the schema for the
+** database changes. After each schema change, the cookie value
+** changes. When a process first reads the schema it records the
+** cookie. Thereafter, whenever it goes to access the database,
+** it checks the cookie to make sure the schema has not changed
+** since it was last read.
+**
+** This plan is not completely bullet-proof. It is possible for
+** the schema to change multiple times and for the cookie to be
+** set back to prior value. But schema changes are infrequent
+** and the probability of hitting the same cookie value is only
+** 1 chance in 2^32. So we're safe enough.
+**
+** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
+** the schema-version whenever the schema changes.
+*/
+SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
+ sqlite3 *db = pParse->db;
+ Vdbe *v = pParse->pVdbe;
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
+ (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
+}
+
+/*
+** Measure the number of characters needed to output the given
+** identifier. The number returned includes any quotes used
+** but does not include the null terminator.
+**
+** The estimate is conservative. It might be larger that what is
+** really needed.
+*/
+static int identLength(const char *z){
+ int n;
+ for(n=0; *z; n++, z++){
+ if( *z=='"' ){ n++; }
+ }
+ return n + 2;
+}
+
+/*
+** The first parameter is a pointer to an output buffer. The second
+** parameter is a pointer to an integer that contains the offset at
+** which to write into the output buffer. This function copies the
+** nul-terminated string pointed to by the third parameter, zSignedIdent,
+** to the specified offset in the buffer and updates *pIdx to refer
+** to the first byte after the last byte written before returning.
+**
+** If the string zSignedIdent consists entirely of alpha-numeric
+** characters, does not begin with a digit and is not an SQL keyword,
+** then it is copied to the output buffer exactly as it is. Otherwise,
+** it is quoted using double-quotes.
+*/
+static void identPut(char *z, int *pIdx, char *zSignedIdent){
+ unsigned char *zIdent = (unsigned char*)zSignedIdent;
+ int i, j, needQuote;
+ i = *pIdx;
+
+ for(j=0; zIdent[j]; j++){
+ if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
+ }
+ needQuote = sqlite3Isdigit(zIdent[0])
+ || sqlite3KeywordCode(zIdent, j)!=TK_ID
+ || zIdent[j]!=0
+ || j==0;
+
+ if( needQuote ) z[i++] = '"';
+ for(j=0; zIdent[j]; j++){
+ z[i++] = zIdent[j];
+ if( zIdent[j]=='"' ) z[i++] = '"';
+ }
+ if( needQuote ) z[i++] = '"';
+ z[i] = 0;
+ *pIdx = i;
+}
+
+/*
+** Generate a CREATE TABLE statement appropriate for the given
+** table. Memory to hold the text of the statement is obtained
+** from sqliteMalloc() and must be freed by the calling function.
+*/
+static char *createTableStmt(sqlite3 *db, Table *p){
+ int i, k, n;
+ char *zStmt;
+ char *zSep, *zSep2, *zEnd;
+ Column *pCol;
+ n = 0;
+ for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
+ n += identLength(pCol->zName) + 5;
+ }
+ n += identLength(p->zName);
+ if( n<50 ){
+ zSep = "";
+ zSep2 = ",";
+ zEnd = ")";
+ }else{
+ zSep = "\n ";
+ zSep2 = ",\n ";
+ zEnd = "\n)";
+ }
+ n += 35 + 6*p->nCol;
+ zStmt = sqlite3DbMallocRaw(0, n);
+ if( zStmt==0 ){
+ sqlite3OomFault(db);
+ return 0;
+ }
+ sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
+ k = sqlite3Strlen30(zStmt);
+ identPut(zStmt, &k, p->zName);
+ zStmt[k++] = '(';
+ for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
+ static const char * const azType[] = {
+ /* SQLITE_AFF_BLOB */ "",
+ /* SQLITE_AFF_TEXT */ " TEXT",
+ /* SQLITE_AFF_NUMERIC */ " NUM",
+ /* SQLITE_AFF_INTEGER */ " INT",
+ /* SQLITE_AFF_REAL */ " REAL"
+ };
+ int len;
+ const char *zType;
+
+ sqlite3_snprintf(n-k, &zStmt[k], zSep);
+ k += sqlite3Strlen30(&zStmt[k]);
+ zSep = zSep2;
+ identPut(zStmt, &k, pCol->zName);
+ assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
+ assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
+ testcase( pCol->affinity==SQLITE_AFF_BLOB );
+ testcase( pCol->affinity==SQLITE_AFF_TEXT );
+ testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
+ testcase( pCol->affinity==SQLITE_AFF_INTEGER );
+ testcase( pCol->affinity==SQLITE_AFF_REAL );
+
+ zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
+ len = sqlite3Strlen30(zType);
+ assert( pCol->affinity==SQLITE_AFF_BLOB
+ || pCol->affinity==sqlite3AffinityType(zType, 0) );
+ memcpy(&zStmt[k], zType, len);
+ k += len;
+ assert( k<=n );
+ }
+ sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
+ return zStmt;
+}
+
+/*
+** Resize an Index object to hold N columns total. Return SQLITE_OK
+** on success and SQLITE_NOMEM on an OOM error.
+*/
+static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
+ char *zExtra;
+ int nByte;
+ if( pIdx->nColumn>=N ) return SQLITE_OK;
+ assert( pIdx->isResized==0 );
+ nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*N;
+ zExtra = sqlite3DbMallocZero(db, nByte);
+ if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
+ memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
+ pIdx->azColl = (const char**)zExtra;
+ zExtra += sizeof(char*)*N;
+ memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1));
+ pIdx->aiRowLogEst = (LogEst*)zExtra;
+ zExtra += sizeof(LogEst)*N;
+ memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
+ pIdx->aiColumn = (i16*)zExtra;
+ zExtra += sizeof(i16)*N;
+ memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
+ pIdx->aSortOrder = (u8*)zExtra;
+ pIdx->nColumn = N;
+ pIdx->isResized = 1;
+ return SQLITE_OK;
+}
+
+/*
+** Estimate the total row width for a table.
+*/
+static void estimateTableWidth(Table *pTab){
+ unsigned wTable = 0;
+ const Column *pTabCol;
+ int i;
+ for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
+ wTable += pTabCol->szEst;
+ }
+ if( pTab->iPKey<0 ) wTable++;
+ pTab->szTabRow = sqlite3LogEst(wTable*4);
+}
+
+/*
+** Estimate the average size of a row for an index.
+*/
+static void estimateIndexWidth(Index *pIdx){
+ unsigned wIndex = 0;
+ int i;
+ const Column *aCol = pIdx->pTable->aCol;
+ for(i=0; i<pIdx->nColumn; i++){
+ i16 x = pIdx->aiColumn[i];
+ assert( x<pIdx->pTable->nCol );
+ wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
+ }
+ pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
+}
+
+/* Return true if column number x is any of the first nCol entries of aiCol[].
+** This is used to determine if the column number x appears in any of the
+** first nCol entries of an index.
+*/
+static int hasColumn(const i16 *aiCol, int nCol, int x){
+ while( nCol-- > 0 ){
+ assert( aiCol[0]>=0 );
+ if( x==*(aiCol++) ){
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/*
+** Return true if any of the first nKey entries of index pIdx exactly
+** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
+** PRIMARY KEY index. pIdx is an index on the same table. pIdx may
+** or may not be the same index as pPk.
+**
+** The first nKey entries of pIdx are guaranteed to be ordinary columns,
+** not a rowid or expression.
+**
+** This routine differs from hasColumn() in that both the column and the
+** collating sequence must match for this routine, but for hasColumn() only
+** the column name must match.
+*/
+static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
+ int i, j;
+ assert( nKey<=pIdx->nColumn );
+ assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
+ assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
+ assert( pPk->pTable->tabFlags & TF_WithoutRowid );
+ assert( pPk->pTable==pIdx->pTable );
+ testcase( pPk==pIdx );
+ j = pPk->aiColumn[iCol];
+ assert( j!=XN_ROWID && j!=XN_EXPR );
+ for(i=0; i<nKey; i++){
+ assert( pIdx->aiColumn[i]>=0 || j>=0 );
+ if( pIdx->aiColumn[i]==j
+ && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
+ ){
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/* Recompute the colNotIdxed field of the Index.
+**
+** colNotIdxed is a bitmask that has a 0 bit representing each indexed
+** columns that are within the first 63 columns of the table. The
+** high-order bit of colNotIdxed is always 1. All unindexed columns
+** of the table have a 1.
+**
+** 2019-10-24: For the purpose of this computation, virtual columns are
+** not considered to be covered by the index, even if they are in the
+** index, because we do not trust the logic in whereIndexExprTrans() to be
+** able to find all instances of a reference to the indexed table column
+** and convert them into references to the index. Hence we always want
+** the actual table at hand in order to recompute the virtual column, if
+** necessary.
+**
+** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
+** to determine if the index is covering index.
+*/
+static void recomputeColumnsNotIndexed(Index *pIdx){
+ Bitmask m = 0;
+ int j;
+ Table *pTab = pIdx->pTable;
+ for(j=pIdx->nColumn-1; j>=0; j--){
+ int x = pIdx->aiColumn[j];
+ if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
+ testcase( x==BMS-1 );
+ testcase( x==BMS-2 );
+ if( x<BMS-1 ) m |= MASKBIT(x);
+ }
+ }
+ pIdx->colNotIdxed = ~m;
+ assert( (pIdx->colNotIdxed>>63)==1 );
+}
+
+/*
+** This routine runs at the end of parsing a CREATE TABLE statement that
+** has a WITHOUT ROWID clause. The job of this routine is to convert both
+** internal schema data structures and the generated VDBE code so that they
+** are appropriate for a WITHOUT ROWID table instead of a rowid table.
+** Changes include:
+**
+** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
+** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
+** into BTREE_BLOBKEY.
+** (3) Bypass the creation of the sqlite_schema table entry
+** for the PRIMARY KEY as the primary key index is now
+** identified by the sqlite_schema table entry of the table itself.
+** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
+** schema to the rootpage from the main table.
+** (5) Add all table columns to the PRIMARY KEY Index object
+** so that the PRIMARY KEY is a covering index. The surplus
+** columns are part of KeyInfo.nAllField and are not used for
+** sorting or lookup or uniqueness checks.
+** (6) Replace the rowid tail on all automatically generated UNIQUE
+** indices with the PRIMARY KEY columns.
+**
+** For virtual tables, only (1) is performed.
+*/
+static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
+ Index *pIdx;
+ Index *pPk;
+ int nPk;
+ int nExtra;
+ int i, j;
+ sqlite3 *db = pParse->db;
+ Vdbe *v = pParse->pVdbe;
+
+ /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
+ */
+ if( !db->init.imposterTable ){
+ for(i=0; i<pTab->nCol; i++){
+ if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
+ pTab->aCol[i].notNull = OE_Abort;
+ }
+ }
+ pTab->tabFlags |= TF_HasNotNull;
+ }
+
+ /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
+ ** into BTREE_BLOBKEY.
+ */
+ if( pParse->addrCrTab ){
+ assert( v );
+ sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
+ }
+
+ /* Locate the PRIMARY KEY index. Or, if this table was originally
+ ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
+ */
+ if( pTab->iPKey>=0 ){
+ ExprList *pList;
+ Token ipkToken;
+ sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
+ pList = sqlite3ExprListAppend(pParse, 0,
+ sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
+ if( pList==0 ) return;
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
+ }
+ pList->a[0].sortFlags = pParse->iPkSortOrder;
+ assert( pParse->pNewTable==pTab );
+ pTab->iPKey = -1;
+ sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
+ SQLITE_IDXTYPE_PRIMARYKEY);
+ if( db->mallocFailed || pParse->nErr ) return;
+ pPk = sqlite3PrimaryKeyIndex(pTab);
+ assert( pPk->nKeyCol==1 );
+ }else{
+ pPk = sqlite3PrimaryKeyIndex(pTab);
+ assert( pPk!=0 );
+
+ /*
+ ** Remove all redundant columns from the PRIMARY KEY. For example, change
+ ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
+ ** code assumes the PRIMARY KEY contains no repeated columns.
+ */
+ for(i=j=1; i<pPk->nKeyCol; i++){
+ if( isDupColumn(pPk, j, pPk, i) ){
+ pPk->nColumn--;
+ }else{
+ testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
+ pPk->azColl[j] = pPk->azColl[i];
+ pPk->aSortOrder[j] = pPk->aSortOrder[i];
+ pPk->aiColumn[j++] = pPk->aiColumn[i];
+ }
+ }
+ pPk->nKeyCol = j;
+ }
+ assert( pPk!=0 );
+ pPk->isCovering = 1;
+ if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
+ nPk = pPk->nColumn = pPk->nKeyCol;
+
+ /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema
+ ** table entry. This is only required if currently generating VDBE
+ ** code for a CREATE TABLE (not when parsing one as part of reading
+ ** a database schema). */
+ if( v && pPk->tnum>0 ){
+ assert( db->init.busy==0 );
+ sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto);
+ }
+
+ /* The root page of the PRIMARY KEY is the table root page */
+ pPk->tnum = pTab->tnum;
+
+ /* Update the in-memory representation of all UNIQUE indices by converting
+ ** the final rowid column into one or more columns of the PRIMARY KEY.
+ */
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+ int n;
+ if( IsPrimaryKeyIndex(pIdx) ) continue;
+ for(i=n=0; i<nPk; i++){
+ if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
+ testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
+ n++;
+ }
+ }
+ if( n==0 ){
+ /* This index is a superset of the primary key */
+ pIdx->nColumn = pIdx->nKeyCol;
+ continue;
+ }
+ if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
+ for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
+ if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
+ testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
+ pIdx->aiColumn[j] = pPk->aiColumn[i];
+ pIdx->azColl[j] = pPk->azColl[i];
+ if( pPk->aSortOrder[i] ){
+ /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
+ pIdx->bAscKeyBug = 1;
+ }
+ j++;
+ }
+ }
+ assert( pIdx->nColumn>=pIdx->nKeyCol+n );
+ assert( pIdx->nColumn>=j );
+ }
+
+ /* Add all table columns to the PRIMARY KEY index
+ */
+ nExtra = 0;
+ for(i=0; i<pTab->nCol; i++){
+ if( !hasColumn(pPk->aiColumn, nPk, i)
+ && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
+ }
+ if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;
+ for(i=0, j=nPk; i<pTab->nCol; i++){
+ if( !hasColumn(pPk->aiColumn, j, i)
+ && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
+ ){
+ assert( j<pPk->nColumn );
+ pPk->aiColumn[j] = i;
+ pPk->azColl[j] = sqlite3StrBINARY;
+ j++;
+ }
+ }
+ assert( pPk->nColumn==j );
+ assert( pTab->nNVCol<=j );
+ recomputeColumnsNotIndexed(pPk);
+}
+
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/*
+** Return true if pTab is a virtual table and zName is a shadow table name
+** for that virtual table.
+*/
+SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){
+ int nName; /* Length of zName */
+ Module *pMod; /* Module for the virtual table */
+
+ if( !IsVirtual(pTab) ) return 0;
+ nName = sqlite3Strlen30(pTab->zName);
+ if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
+ if( zName[nName]!='_' ) return 0;
+ pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
+ if( pMod==0 ) return 0;
+ if( pMod->pModule->iVersion<3 ) return 0;
+ if( pMod->pModule->xShadowName==0 ) return 0;
+ return pMod->pModule->xShadowName(zName+nName+1);
+}
+#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/*
+** Return true if zName is a shadow table name in the current database
+** connection.
+**
+** zName is temporarily modified while this routine is running, but is
+** restored to its original value prior to this routine returning.
+*/
+SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
+ char *zTail; /* Pointer to the last "_" in zName */
+ Table *pTab; /* Table that zName is a shadow of */
+ zTail = strrchr(zName, '_');
+ if( zTail==0 ) return 0;
+ *zTail = 0;
+ pTab = sqlite3FindTable(db, zName, 0);
+ *zTail = '_';
+ if( pTab==0 ) return 0;
+ if( !IsVirtual(pTab) ) return 0;
+ return sqlite3IsShadowTableOf(db, pTab, zName);
+}
+#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
+
+
+#ifdef SQLITE_DEBUG
+/*
+** Mark all nodes of an expression as EP_Immutable, indicating that
+** they should not be changed. Expressions attached to a table or
+** index definition are tagged this way to help ensure that we do
+** not pass them into code generator routines by mistake.
+*/
+static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){
+ ExprSetVVAProperty(pExpr, EP_Immutable);
+ return WRC_Continue;
+}
+static void markExprListImmutable(ExprList *pList){
+ if( pList ){
+ Walker w;
+ memset(&w, 0, sizeof(w));
+ w.xExprCallback = markImmutableExprStep;
+ w.xSelectCallback = sqlite3SelectWalkNoop;
+ w.xSelectCallback2 = 0;
+ sqlite3WalkExprList(&w, pList);
+ }
+}
+#else
+#define markExprListImmutable(X) /* no-op */
+#endif /* SQLITE_DEBUG */
+
+
+/*
+** This routine is called to report the final ")" that terminates
+** a CREATE TABLE statement.
+**
+** The table structure that other action routines have been building
+** is added to the internal hash tables, assuming no errors have
+** occurred.
+**
+** An entry for the table is made in the schema table on disk, unless
+** this is a temporary table or db->init.busy==1. When db->init.busy==1
+** it means we are reading the sqlite_schema table because we just
+** connected to the database or because the sqlite_schema table has
+** recently changed, so the entry for this table already exists in
+** the sqlite_schema table. We do not want to create it again.
+**
+** If the pSelect argument is not NULL, it means that this routine
+** was called to create a table generated from a
+** "CREATE TABLE ... AS SELECT ..." statement. The column names of
+** the new table will match the result set of the SELECT.
+*/
+SQLITE_PRIVATE void sqlite3EndTable(
+ Parse *pParse, /* Parse context */
+ Token *pCons, /* The ',' token after the last column defn. */
+ Token *pEnd, /* The ')' before options in the CREATE TABLE */
+ u8 tabOpts, /* Extra table options. Usually 0. */
+ Select *pSelect /* Select from a "CREATE ... AS SELECT" */
+){
+ Table *p; /* The new table */
+ sqlite3 *db = pParse->db; /* The database connection */
+ int iDb; /* Database in which the table lives */
+ Index *pIdx; /* An implied index of the table */
+
+ if( pEnd==0 && pSelect==0 ){
+ return;
+ }
+ assert( !db->mallocFailed );
+ p = pParse->pNewTable;
+ if( p==0 ) return;
+
+ if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
+ p->tabFlags |= TF_Shadow;
+ }
+
+ /* If the db->init.busy is 1 it means we are reading the SQL off the
+ ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
+ ** So do not write to the disk again. Extract the root page number
+ ** for the table from the db->init.newTnum field. (The page number
+ ** should have been put there by the sqliteOpenCb routine.)
+ **
+ ** If the root page number is 1, that means this is the sqlite_schema
+ ** table itself. So mark it read-only.
+ */
+ if( db->init.busy ){
+ if( pSelect ){
+ sqlite3ErrorMsg(pParse, "");
+ return;
+ }
+ p->tnum = db->init.newTnum;
+ if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
+ }
+
+ assert( (p->tabFlags & TF_HasPrimaryKey)==0
+ || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
+ assert( (p->tabFlags & TF_HasPrimaryKey)!=0
+ || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
+
+ /* Special processing for WITHOUT ROWID Tables */
+ if( tabOpts & TF_WithoutRowid ){
+ if( (p->tabFlags & TF_Autoincrement) ){
+ sqlite3ErrorMsg(pParse,
+ "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
+ return;
+ }
+ if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
+ sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
+ return;
+ }
+ p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
+ convertToWithoutRowidTable(pParse, p);
+ }
+ iDb = sqlite3SchemaToIndex(db, p->pSchema);
+
+#ifndef SQLITE_OMIT_CHECK
+ /* Resolve names in all CHECK constraint expressions.
+ */
+ if( p->pCheck ){
+ sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
+ if( pParse->nErr ){
+ /* If errors are seen, delete the CHECK constraints now, else they might
+ ** actually be used if PRAGMA writable_schema=ON is set. */
+ sqlite3ExprListDelete(db, p->pCheck);
+ p->pCheck = 0;
+ }else{
+ markExprListImmutable(p->pCheck);
+ }
+ }
+#endif /* !defined(SQLITE_OMIT_CHECK) */
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ if( p->tabFlags & TF_HasGenerated ){
+ int ii, nNG = 0;
+ testcase( p->tabFlags & TF_HasVirtual );
+ testcase( p->tabFlags & TF_HasStored );
+ for(ii=0; ii<p->nCol; ii++){
+ u32 colFlags = p->aCol[ii].colFlags;
+ if( (colFlags & COLFLAG_GENERATED)!=0 ){
+ Expr *pX = p->aCol[ii].pDflt;
+ testcase( colFlags & COLFLAG_VIRTUAL );
+ testcase( colFlags & COLFLAG_STORED );
+ if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){
+ /* If there are errors in resolving the expression, change the
+ ** expression to a NULL. This prevents code generators that operate
+ ** on the expression from inserting extra parts into the expression
+ ** tree that have been allocated from lookaside memory, which is
+ ** illegal in a schema and will lead to errors or heap corruption
+ ** when the database connection closes. */
+ sqlite3ExprDelete(db, pX);
+ p->aCol[ii].pDflt = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
+ }
+ }else{
+ nNG++;
+ }
+ }
+ if( nNG==0 ){
+ sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
+ return;
+ }
+ }
+#endif
+
+ /* Estimate the average row size for the table and for all implied indices */
+ estimateTableWidth(p);
+ for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
+ estimateIndexWidth(pIdx);
+ }
+
+ /* If not initializing, then create a record for the new table
+ ** in the schema table of the database.
+ **
+ ** If this is a TEMPORARY table, write the entry into the auxiliary
+ ** file instead of into the main database file.
+ */
+ if( !db->init.busy ){
+ int n;
+ Vdbe *v;
+ char *zType; /* "view" or "table" */
+ char *zType2; /* "VIEW" or "TABLE" */
+ char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
+
+ v = sqlite3GetVdbe(pParse);
+ if( NEVER(v==0) ) return;
+
+ sqlite3VdbeAddOp1(v, OP_Close, 0);
+
+ /*
+ ** Initialize zType for the new view or table.
+ */
+ if( p->pSelect==0 ){
+ /* A regular table */
+ zType = "table";
+ zType2 = "TABLE";
+#ifndef SQLITE_OMIT_VIEW
+ }else{
+ /* A view */
+ zType = "view";
+ zType2 = "VIEW";
+#endif
+ }
+
+ /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
+ ** statement to populate the new table. The root-page number for the
+ ** new table is in register pParse->regRoot.
+ **
+ ** Once the SELECT has been coded by sqlite3Select(), it is in a
+ ** suitable state to query for the column names and types to be used
+ ** by the new table.
+ **
+ ** A shared-cache write-lock is not required to write to the new table,
+ ** as a schema-lock must have already been obtained to create it. Since
+ ** a schema-lock excludes all other database users, the write-lock would
+ ** be redundant.
+ */
+ if( pSelect ){
+ SelectDest dest; /* Where the SELECT should store results */
+ int regYield; /* Register holding co-routine entry-point */
+ int addrTop; /* Top of the co-routine */
+ int regRec; /* A record to be insert into the new table */
+ int regRowid; /* Rowid of the next row to insert */
+ int addrInsLoop; /* Top of the loop for inserting rows */
+ Table *pSelTab; /* A table that describes the SELECT results */
+
+ regYield = ++pParse->nMem;
+ regRec = ++pParse->nMem;
+ regRowid = ++pParse->nMem;
+ assert(pParse->nTab==1);
+ sqlite3MayAbort(pParse);
+ sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
+ sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
+ pParse->nTab = 2;
+ addrTop = sqlite3VdbeCurrentAddr(v) + 1;
+ sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
+ if( pParse->nErr ) return;
+ pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
+ if( pSelTab==0 ) return;
+ assert( p->aCol==0 );
+ p->nCol = p->nNVCol = pSelTab->nCol;
+ p->aCol = pSelTab->aCol;
+ pSelTab->nCol = 0;
+ pSelTab->aCol = 0;
+ sqlite3DeleteTable(db, pSelTab);
+ sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
+ sqlite3Select(pParse, pSelect, &dest);
+ if( pParse->nErr ) return;
+ sqlite3VdbeEndCoroutine(v, regYield);
+ sqlite3VdbeJumpHere(v, addrTop - 1);
+ addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
+ VdbeCoverage(v);
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
+ sqlite3TableAffinity(v, p, 0);
+ sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
+ sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
+ sqlite3VdbeGoto(v, addrInsLoop);
+ sqlite3VdbeJumpHere(v, addrInsLoop);
+ sqlite3VdbeAddOp1(v, OP_Close, 1);
+ }
+
+ /* Compute the complete text of the CREATE statement */
+ if( pSelect ){
+ zStmt = createTableStmt(db, p);
+ }else{
+ Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
+ n = (int)(pEnd2->z - pParse->sNameToken.z);
+ if( pEnd2->z[0]!=';' ) n += pEnd2->n;
+ zStmt = sqlite3MPrintf(db,
+ "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
+ );
+ }
+
+ /* A slot for the record has already been allocated in the
+ ** schema table. We just need to update that slot with all
+ ** the information we've collected.
+ */
+ sqlite3NestedParse(pParse,
+ "UPDATE %Q." DFLT_SCHEMA_TABLE
+ " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"
+ " WHERE rowid=#%d",
+ db->aDb[iDb].zDbSName,
+ zType,
+ p->zName,
+ p->zName,
+ pParse->regRoot,
+ zStmt,
+ pParse->regRowid
+ );
+ sqlite3DbFree(db, zStmt);
+ sqlite3ChangeCookie(pParse, iDb);
+
+#ifndef SQLITE_OMIT_AUTOINCREMENT
+ /* Check to see if we need to create an sqlite_sequence table for
+ ** keeping track of autoincrement keys.
+ */
+ if( (p->tabFlags & TF_Autoincrement)!=0 ){
+ Db *pDb = &db->aDb[iDb];
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ if( pDb->pSchema->pSeqTab==0 ){
+ sqlite3NestedParse(pParse,
+ "CREATE TABLE %Q.sqlite_sequence(name,seq)",
+ pDb->zDbSName
+ );
+ }
+ }
+#endif
+
+ /* Reparse everything to update our internal data structures */
+ sqlite3VdbeAddParseSchemaOp(v, iDb,
+ sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
+ }
+
+ /* Add the table to the in-memory representation of the database.
+ */
+ if( db->init.busy ){
+ Table *pOld;
+ Schema *pSchema = p->pSchema;
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
+ if( pOld ){
+ assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
+ sqlite3OomFault(db);
+ return;
+ }
+ pParse->pNewTable = 0;
+ db->mDbFlags |= DBFLAG_SchemaChange;
+
+#ifndef SQLITE_OMIT_ALTERTABLE
+ if( !p->pSelect ){
+ const char *zName = (const char *)pParse->sNameToken.z;
+ int nName;
+ assert( !pSelect && pCons && pEnd );
+ if( pCons->z==0 ){
+ pCons = pEnd;
+ }
+ nName = (int)((const char *)pCons->z - zName);
+ p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
+ }
+#endif
+ }
+}
+
+#ifndef SQLITE_OMIT_VIEW
+/*
+** The parser calls this routine in order to create a new VIEW
+*/
+SQLITE_PRIVATE void sqlite3CreateView(
+ Parse *pParse, /* The parsing context */
+ Token *pBegin, /* The CREATE token that begins the statement */
+ Token *pName1, /* The token that holds the name of the view */
+ Token *pName2, /* The token that holds the name of the view */
+ ExprList *pCNames, /* Optional list of view column names */
+ Select *pSelect, /* A SELECT statement that will become the new view */
+ int isTemp, /* TRUE for a TEMPORARY view */
+ int noErr /* Suppress error messages if VIEW already exists */
+){
+ Table *p;
+ int n;
+ const char *z;
+ Token sEnd;
+ DbFixer sFix;
+ Token *pName = 0;
+ int iDb;
+ sqlite3 *db = pParse->db;
+
+ if( pParse->nVar>0 ){
+ sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
+ goto create_view_fail;
+ }
+ sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
+ p = pParse->pNewTable;
+ if( p==0 || pParse->nErr ) goto create_view_fail;
+ sqlite3TwoPartName(pParse, pName1, pName2, &pName);
+ iDb = sqlite3SchemaToIndex(db, p->pSchema);
+ sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
+ if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
+
+ /* Make a copy of the entire SELECT statement that defines the view.
+ ** This will force all the Expr.token.z values to be dynamically
+ ** allocated rather than point to the input string - which means that
+ ** they will persist after the current sqlite3_exec() call returns.
+ */
+ pSelect->selFlags |= SF_View;
+ if( IN_RENAME_OBJECT ){
+ p->pSelect = pSelect;
+ pSelect = 0;
+ }else{
+ p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
+ }
+ p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
+ if( db->mallocFailed ) goto create_view_fail;
+
+ /* Locate the end of the CREATE VIEW statement. Make sEnd point to
+ ** the end.
+ */
+ sEnd = pParse->sLastToken;
+ assert( sEnd.z[0]!=0 || sEnd.n==0 );
+ if( sEnd.z[0]!=';' ){
+ sEnd.z += sEnd.n;
+ }
+ sEnd.n = 0;
+ n = (int)(sEnd.z - pBegin->z);
+ assert( n>0 );
+ z = pBegin->z;
+ while( sqlite3Isspace(z[n-1]) ){ n--; }
+ sEnd.z = &z[n-1];
+ sEnd.n = 1;
+
+ /* Use sqlite3EndTable() to add the view to the schema table */
+ sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
+
+create_view_fail:
+ sqlite3SelectDelete(db, pSelect);
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameExprlistUnmap(pParse, pCNames);
+ }
+ sqlite3ExprListDelete(db, pCNames);
+ return;
+}
+#endif /* SQLITE_OMIT_VIEW */
+
+#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
+/*
+** The Table structure pTable is really a VIEW. Fill in the names of
+** the columns of the view in the pTable structure. Return the number
+** of errors. If an error is seen leave an error message in pParse->zErrMsg.
+*/
+SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
+ Table *pSelTab; /* A fake table from which we get the result set */
+ Select *pSel; /* Copy of the SELECT that implements the view */
+ int nErr = 0; /* Number of errors encountered */
+ int n; /* Temporarily holds the number of cursors assigned */
+ sqlite3 *db = pParse->db; /* Database connection for malloc errors */
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ int rc;
+#endif
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ sqlite3_xauth xAuth; /* Saved xAuth pointer */
+#endif
+
+ assert( pTable );
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ db->nSchemaLock++;
+ rc = sqlite3VtabCallConnect(pParse, pTable);
+ db->nSchemaLock--;
+ if( rc ){
+ return 1;
+ }
+ if( IsVirtual(pTable) ) return 0;
+#endif
+
+#ifndef SQLITE_OMIT_VIEW
+ /* A positive nCol means the columns names for this view are
+ ** already known.
+ */
+ if( pTable->nCol>0 ) return 0;
+
+ /* A negative nCol is a special marker meaning that we are currently
+ ** trying to compute the column names. If we enter this routine with
+ ** a negative nCol, it means two or more views form a loop, like this:
+ **
+ ** CREATE VIEW one AS SELECT * FROM two;
+ ** CREATE VIEW two AS SELECT * FROM one;
+ **
+ ** Actually, the error above is now caught prior to reaching this point.
+ ** But the following test is still important as it does come up
+ ** in the following:
+ **
+ ** CREATE TABLE main.ex1(a);
+ ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
+ ** SELECT * FROM temp.ex1;
+ */
+ if( pTable->nCol<0 ){
+ sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
+ return 1;
+ }
+ assert( pTable->nCol>=0 );
+
+ /* If we get this far, it means we need to compute the table names.
+ ** Note that the call to sqlite3ResultSetOfSelect() will expand any
+ ** "*" elements in the results set of the view and will assign cursors
+ ** to the elements of the FROM clause. But we do not want these changes
+ ** to be permanent. So the computation is done on a copy of the SELECT
+ ** statement that defines the view.
+ */
+ assert( pTable->pSelect );
+ pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
+ if( pSel ){
+ u8 eParseMode = pParse->eParseMode;
+ pParse->eParseMode = PARSE_MODE_NORMAL;
+ n = pParse->nTab;
+ sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
+ pTable->nCol = -1;
+ DisableLookaside;
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ xAuth = db->xAuth;
+ db->xAuth = 0;
+ pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
+ db->xAuth = xAuth;
+#else
+ pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
+#endif
+ pParse->nTab = n;
+ if( pSelTab==0 ){
+ pTable->nCol = 0;
+ nErr++;
+ }else if( pTable->pCheck ){
+ /* CREATE VIEW name(arglist) AS ...
+ ** The names of the columns in the table are taken from
+ ** arglist which is stored in pTable->pCheck. The pCheck field
+ ** normally holds CHECK constraints on an ordinary table, but for
+ ** a VIEW it holds the list of column names.
+ */
+ sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
+ &pTable->nCol, &pTable->aCol);
+ if( db->mallocFailed==0
+ && pParse->nErr==0
+ && pTable->nCol==pSel->pEList->nExpr
+ ){
+ sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel,
+ SQLITE_AFF_NONE);
+ }
+ }else{
+ /* CREATE VIEW name AS... without an argument list. Construct
+ ** the column names from the SELECT statement that defines the view.
+ */
+ assert( pTable->aCol==0 );
+ pTable->nCol = pSelTab->nCol;
+ pTable->aCol = pSelTab->aCol;
+ pSelTab->nCol = 0;
+ pSelTab->aCol = 0;
+ assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
+ }
+ pTable->nNVCol = pTable->nCol;
+ sqlite3DeleteTable(db, pSelTab);
+ sqlite3SelectDelete(db, pSel);
+ EnableLookaside;
+ pParse->eParseMode = eParseMode;
+ } else {
+ nErr++;
+ }
+ pTable->pSchema->schemaFlags |= DB_UnresetViews;
+ if( db->mallocFailed ){
+ sqlite3DeleteColumnNames(db, pTable);
+ pTable->aCol = 0;
+ pTable->nCol = 0;
+ }
+#endif /* SQLITE_OMIT_VIEW */
+ return nErr;
+}
+#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
+
+#ifndef SQLITE_OMIT_VIEW
+/*
+** Clear the column names from every VIEW in database idx.
+*/
+static void sqliteViewResetAll(sqlite3 *db, int idx){
+ HashElem *i;
+ assert( sqlite3SchemaMutexHeld(db, idx, 0) );
+ if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
+ for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
+ Table *pTab = sqliteHashData(i);
+ if( pTab->pSelect ){
+ sqlite3DeleteColumnNames(db, pTab);
+ pTab->aCol = 0;
+ pTab->nCol = 0;
+ }
+ }
+ DbClearProperty(db, idx, DB_UnresetViews);
+}
+#else
+# define sqliteViewResetAll(A,B)
+#endif /* SQLITE_OMIT_VIEW */
+
+/*
+** This function is called by the VDBE to adjust the internal schema
+** used by SQLite when the btree layer moves a table root page. The
+** root-page of a table or index in database iDb has changed from iFrom
+** to iTo.
+**
+** Ticket #1728: The symbol table might still contain information
+** on tables and/or indices that are the process of being deleted.
+** If you are unlucky, one of those deleted indices or tables might
+** have the same rootpage number as the real table or index that is
+** being moved. So we cannot stop searching after the first match
+** because the first match might be for one of the deleted indices
+** or tables and not the table/index that is actually being moved.
+** We must continue looping until all tables and indices with
+** rootpage==iFrom have been converted to have a rootpage of iTo
+** in order to be certain that we got the right one.
+*/
+#ifndef SQLITE_OMIT_AUTOVACUUM
+SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){
+ HashElem *pElem;
+ Hash *pHash;
+ Db *pDb;
+
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ pDb = &db->aDb[iDb];
+ pHash = &pDb->pSchema->tblHash;
+ for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
+ Table *pTab = sqliteHashData(pElem);
+ if( pTab->tnum==iFrom ){
+ pTab->tnum = iTo;
+ }
+ }
+ pHash = &pDb->pSchema->idxHash;
+ for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
+ Index *pIdx = sqliteHashData(pElem);
+ if( pIdx->tnum==iFrom ){
+ pIdx->tnum = iTo;
+ }
+ }
+}
+#endif
+
+/*
+** Write code to erase the table with root-page iTable from database iDb.
+** Also write code to modify the sqlite_schema table and internal schema
+** if a root-page of another table is moved by the btree-layer whilst
+** erasing iTable (this can happen with an auto-vacuum database).
+*/
+static void destroyRootPage(Parse *pParse, int iTable, int iDb){
+ Vdbe *v = sqlite3GetVdbe(pParse);
+ int r1 = sqlite3GetTempReg(pParse);
+ if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
+ sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
+ sqlite3MayAbort(pParse);
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ /* OP_Destroy stores an in integer r1. If this integer
+ ** is non-zero, then it is the root page number of a table moved to
+ ** location iTable. The following code modifies the sqlite_schema table to
+ ** reflect this.
+ **
+ ** The "#NNN" in the SQL is a special constant that means whatever value
+ ** is in register NNN. See grammar rules associated with the TK_REGISTER
+ ** token for additional information.
+ */
+ sqlite3NestedParse(pParse,
+ "UPDATE %Q." DFLT_SCHEMA_TABLE
+ " SET rootpage=%d WHERE #%d AND rootpage=#%d",
+ pParse->db->aDb[iDb].zDbSName, iTable, r1, r1);
+#endif
+ sqlite3ReleaseTempReg(pParse, r1);
+}
+
+/*
+** Write VDBE code to erase table pTab and all associated indices on disk.
+** Code to update the sqlite_schema tables and internal schema definitions
+** in case a root-page belonging to another table is moved by the btree layer
+** is also added (this can happen with an auto-vacuum database).
+*/
+static void destroyTable(Parse *pParse, Table *pTab){
+ /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
+ ** is not defined), then it is important to call OP_Destroy on the
+ ** table and index root-pages in order, starting with the numerically
+ ** largest root-page number. This guarantees that none of the root-pages
+ ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
+ ** following were coded:
+ **
+ ** OP_Destroy 4 0
+ ** ...
+ ** OP_Destroy 5 0
+ **
+ ** and root page 5 happened to be the largest root-page number in the
+ ** database, then root page 5 would be moved to page 4 by the
+ ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
+ ** a free-list page.
+ */
+ Pgno iTab = pTab->tnum;
+ Pgno iDestroyed = 0;
+
+ while( 1 ){
+ Index *pIdx;
+ Pgno iLargest = 0;
+
+ if( iDestroyed==0 || iTab<iDestroyed ){
+ iLargest = iTab;
+ }
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+ Pgno iIdx = pIdx->tnum;
+ assert( pIdx->pSchema==pTab->pSchema );
+ if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
+ iLargest = iIdx;
+ }
+ }
+ if( iLargest==0 ){
+ return;
+ }else{
+ int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
+ assert( iDb>=0 && iDb<pParse->db->nDb );
+ destroyRootPage(pParse, iLargest, iDb);
+ iDestroyed = iLargest;
+ }
+ }
+}
+
+/*
+** Remove entries from the sqlite_statN tables (for N in (1,2,3))
+** after a DROP INDEX or DROP TABLE command.
+*/
+static void sqlite3ClearStatTables(
+ Parse *pParse, /* The parsing context */
+ int iDb, /* The database number */
+ const char *zType, /* "idx" or "tbl" */
+ const char *zName /* Name of index or table */
+){
+ int i;
+ const char *zDbName = pParse->db->aDb[iDb].zDbSName;
+ for(i=1; i<=4; i++){
+ char zTab[24];
+ sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
+ if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
+ sqlite3NestedParse(pParse,
+ "DELETE FROM %Q.%s WHERE %s=%Q",
+ zDbName, zTab, zType, zName
+ );
+ }
+ }
+}
+
+/*
+** Generate code to drop a table.
+*/
+SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
+ Vdbe *v;
+ sqlite3 *db = pParse->db;
+ Trigger *pTrigger;
+ Db *pDb = &db->aDb[iDb];
+
+ v = sqlite3GetVdbe(pParse);
+ assert( v!=0 );
+ sqlite3BeginWriteOperation(pParse, 1, iDb);
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( IsVirtual(pTab) ){
+ sqlite3VdbeAddOp0(v, OP_VBegin);
+ }
+#endif
+
+ /* Drop all triggers associated with the table being dropped. Code
+ ** is generated to remove entries from sqlite_schema and/or
+ ** sqlite_temp_schema if required.
+ */
+ pTrigger = sqlite3TriggerList(pParse, pTab);
+ while( pTrigger ){
+ assert( pTrigger->pSchema==pTab->pSchema ||
+ pTrigger->pSchema==db->aDb[1].pSchema );
+ sqlite3DropTriggerPtr(pParse, pTrigger);
+ pTrigger = pTrigger->pNext;
+ }
+
+#ifndef SQLITE_OMIT_AUTOINCREMENT
+ /* Remove any entries of the sqlite_sequence table associated with
+ ** the table being dropped. This is done before the table is dropped
+ ** at the btree level, in case the sqlite_sequence table needs to
+ ** move as a result of the drop (can happen in auto-vacuum mode).
+ */
+ if( pTab->tabFlags & TF_Autoincrement ){
+ sqlite3NestedParse(pParse,
+ "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
+ pDb->zDbSName, pTab->zName
+ );
+ }
+#endif
+
+ /* Drop all entries in the schema table that refer to the
+ ** table. The program name loops through the schema table and deletes
+ ** every row that refers to a table of the same name as the one being
+ ** dropped. Triggers are handled separately because a trigger can be
+ ** created in the temp database that refers to a table in another
+ ** database.
+ */
+ sqlite3NestedParse(pParse,
+ "DELETE FROM %Q." DFLT_SCHEMA_TABLE
+ " WHERE tbl_name=%Q and type!='trigger'",
+ pDb->zDbSName, pTab->zName);
+ if( !isView && !IsVirtual(pTab) ){
+ destroyTable(pParse, pTab);
+ }
+
+ /* Remove the table entry from SQLite's internal schema and modify
+ ** the schema cookie.
+ */
+ if( IsVirtual(pTab) ){
+ sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
+ sqlite3MayAbort(pParse);
+ }
+ sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
+ sqlite3ChangeCookie(pParse, iDb);
+ sqliteViewResetAll(db, iDb);
+}
+
+/*
+** Return TRUE if shadow tables should be read-only in the current
+** context.
+*/
+SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db){
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( (db->flags & SQLITE_Defensive)!=0
+ && db->pVtabCtx==0
+ && db->nVdbeExec==0
+ ){
+ return 1;
+ }
+#endif
+ return 0;
+}
+
+/*
+** Return true if it is not allowed to drop the given table
+*/
+static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
+ if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
+ if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
+ if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
+ return 1;
+ }
+ if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
+ return 1;
+ }
+ return 0;
+}
+
+/*
+** This routine is called to do the work of a DROP TABLE statement.
+** pName is the name of the table to be dropped.
+*/
+SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
+ Table *pTab;
+ Vdbe *v;
+ sqlite3 *db = pParse->db;
+ int iDb;
+
+ if( db->mallocFailed ){
+ goto exit_drop_table;
+ }
+ assert( pParse->nErr==0 );
+ assert( pName->nSrc==1 );
+ if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
+ if( noErr ) db->suppressErr++;
+ assert( isView==0 || isView==LOCATE_VIEW );
+ pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
+ if( noErr ) db->suppressErr--;
+
+ if( pTab==0 ){
+ if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
+ goto exit_drop_table;
+ }
+ iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ assert( iDb>=0 && iDb<db->nDb );
+
+ /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
+ ** it is initialized.
+ */
+ if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
+ goto exit_drop_table;
+ }
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ {
+ int code;
+ const char *zTab = SCHEMA_TABLE(iDb);
+ const char *zDb = db->aDb[iDb].zDbSName;
+ const char *zArg2 = 0;
+ if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
+ goto exit_drop_table;
+ }
+ if( isView ){
+ if( !OMIT_TEMPDB && iDb==1 ){
+ code = SQLITE_DROP_TEMP_VIEW;
+ }else{
+ code = SQLITE_DROP_VIEW;
+ }
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ }else if( IsVirtual(pTab) ){
+ code = SQLITE_DROP_VTABLE;
+ zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
+#endif
+ }else{
+ if( !OMIT_TEMPDB && iDb==1 ){
+ code = SQLITE_DROP_TEMP_TABLE;
+ }else{
+ code = SQLITE_DROP_TABLE;
+ }
+ }
+ if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
+ goto exit_drop_table;
+ }
+ if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
+ goto exit_drop_table;
+ }
+ }
+#endif
+ if( tableMayNotBeDropped(db, pTab) ){
+ sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
+ goto exit_drop_table;
+ }
+
+#ifndef SQLITE_OMIT_VIEW
+ /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
+ ** on a table.
+ */
+ if( isView && pTab->pSelect==0 ){
+ sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
+ goto exit_drop_table;
+ }
+ if( !isView && pTab->pSelect ){
+ sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
+ goto exit_drop_table;
+ }
+#endif
+
+ /* Generate code to remove the table from the schema table
+ ** on disk.
+ */
+ v = sqlite3GetVdbe(pParse);
+ if( v ){
+ sqlite3BeginWriteOperation(pParse, 1, iDb);
+ if( !isView ){
+ sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
+ sqlite3FkDropTable(pParse, pName, pTab);
+ }
+ sqlite3CodeDropTable(pParse, pTab, iDb, isView);
+ }
+
+exit_drop_table:
+ sqlite3SrcListDelete(db, pName);
+}
+
+/*
+** This routine is called to create a new foreign key on the table
+** currently under construction. pFromCol determines which columns
+** in the current table point to the foreign key. If pFromCol==0 then
+** connect the key to the last column inserted. pTo is the name of
+** the table referred to (a.k.a the "parent" table). pToCol is a list
+** of tables in the parent pTo table. flags contains all
+** information about the conflict resolution algorithms specified
+** in the ON DELETE, ON UPDATE and ON INSERT clauses.
+**
+** An FKey structure is created and added to the table currently
+** under construction in the pParse->pNewTable field.
+**
+** The foreign key is set for IMMEDIATE processing. A subsequent call
+** to sqlite3DeferForeignKey() might change this to DEFERRED.
+*/
+SQLITE_PRIVATE void sqlite3CreateForeignKey(
+ Parse *pParse, /* Parsing context */
+ ExprList *pFromCol, /* Columns in this table that point to other table */
+ Token *pTo, /* Name of the other table */
+ ExprList *pToCol, /* Columns in the other table */
+ int flags /* Conflict resolution algorithms. */
+){
+ sqlite3 *db = pParse->db;
+#ifndef SQLITE_OMIT_FOREIGN_KEY
+ FKey *pFKey = 0;
+ FKey *pNextTo;
+ Table *p = pParse->pNewTable;
+ int nByte;
+ int i;
+ int nCol;
+ char *z;
+
+ assert( pTo!=0 );
+ if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
+ if( pFromCol==0 ){
+ int iCol = p->nCol-1;
+ if( NEVER(iCol<0) ) goto fk_end;
+ if( pToCol && pToCol->nExpr!=1 ){
+ sqlite3ErrorMsg(pParse, "foreign key on %s"
+ " should reference only one column of table %T",
+ p->aCol[iCol].zName, pTo);
+ goto fk_end;
+ }
+ nCol = 1;
+ }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
+ sqlite3ErrorMsg(pParse,
+ "number of columns in foreign key does not match the number of "
+ "columns in the referenced table");
+ goto fk_end;
+ }else{
+ nCol = pFromCol->nExpr;
+ }
+ nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
+ if( pToCol ){
+ for(i=0; i<pToCol->nExpr; i++){
+ nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
+ }
+ }
+ pFKey = sqlite3DbMallocZero(db, nByte );
+ if( pFKey==0 ){
+ goto fk_end;
+ }
+ pFKey->pFrom = p;
+ pFKey->pNextFrom = p->pFKey;
+ z = (char*)&pFKey->aCol[nCol];
+ pFKey->zTo = z;
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameTokenMap(pParse, (void*)z, pTo);
+ }
+ memcpy(z, pTo->z, pTo->n);
+ z[pTo->n] = 0;
+ sqlite3Dequote(z);
+ z += pTo->n+1;
+ pFKey->nCol = nCol;
+ if( pFromCol==0 ){
+ pFKey->aCol[0].iFrom = p->nCol-1;
+ }else{
+ for(i=0; i<nCol; i++){
+ int j;
+ for(j=0; j<p->nCol; j++){
+ if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zEName)==0 ){
+ pFKey->aCol[i].iFrom = j;
+ break;
+ }
+ }
+ if( j>=p->nCol ){
+ sqlite3ErrorMsg(pParse,
+ "unknown column \"%s\" in foreign key definition",
+ pFromCol->a[i].zEName);
+ goto fk_end;
+ }
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
+ }
+ }
+ }
+ if( pToCol ){
+ for(i=0; i<nCol; i++){
+ int n = sqlite3Strlen30(pToCol->a[i].zEName);
+ pFKey->aCol[i].zCol = z;
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
+ }
+ memcpy(z, pToCol->a[i].zEName, n);
+ z[n] = 0;
+ z += n+1;
+ }
+ }
+ pFKey->isDeferred = 0;
+ pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
+ pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
+
+ assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
+ pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
+ pFKey->zTo, (void *)pFKey
+ );
+ if( pNextTo==pFKey ){
+ sqlite3OomFault(db);
+ goto fk_end;
+ }
+ if( pNextTo ){
+ assert( pNextTo->pPrevTo==0 );
+ pFKey->pNextTo = pNextTo;
+ pNextTo->pPrevTo = pFKey;
+ }
+
+ /* Link the foreign key to the table as the last step.
+ */
+ p->pFKey = pFKey;
+ pFKey = 0;
+
+fk_end:
+ sqlite3DbFree(db, pFKey);
+#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
+ sqlite3ExprListDelete(db, pFromCol);
+ sqlite3ExprListDelete(db, pToCol);
+}
+
+/*
+** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
+** clause is seen as part of a foreign key definition. The isDeferred
+** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
+** The behavior of the most recently created foreign key is adjusted
+** accordingly.
+*/
+SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
+#ifndef SQLITE_OMIT_FOREIGN_KEY
+ Table *pTab;
+ FKey *pFKey;
+ if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
+ assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
+ pFKey->isDeferred = (u8)isDeferred;
+#endif
+}
+
+/*
+** Generate code that will erase and refill index *pIdx. This is
+** used to initialize a newly created index or to recompute the
+** content of an index in response to a REINDEX command.
+**
+** if memRootPage is not negative, it means that the index is newly
+** created. The register specified by memRootPage contains the
+** root page number of the index. If memRootPage is negative, then
+** the index already exists and must be cleared before being refilled and
+** the root page number of the index is taken from pIndex->tnum.
+*/
+static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
+ Table *pTab = pIndex->pTable; /* The table that is indexed */
+ int iTab = pParse->nTab++; /* Btree cursor used for pTab */
+ int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
+ int iSorter; /* Cursor opened by OpenSorter (if in use) */
+ int addr1; /* Address of top of loop */
+ int addr2; /* Address to jump to for next iteration */
+ Pgno tnum; /* Root page of index */
+ int iPartIdxLabel; /* Jump to this label to skip a row */
+ Vdbe *v; /* Generate code into this virtual machine */
+ KeyInfo *pKey; /* KeyInfo for index */
+ int regRecord; /* Register holding assembled index record */
+ sqlite3 *db = pParse->db; /* The database connection */
+ int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
+
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
+ db->aDb[iDb].zDbSName ) ){
+ return;
+ }
+#endif
+
+ /* Require a write-lock on the table to perform this operation */
+ sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
+
+ v = sqlite3GetVdbe(pParse);
+ if( v==0 ) return;
+ if( memRootPage>=0 ){
+ tnum = (Pgno)memRootPage;
+ }else{
+ tnum = pIndex->tnum;
+ }
+ pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
+ assert( pKey!=0 || db->mallocFailed || pParse->nErr );
+
+ /* Open the sorter cursor if we are to use one. */
+ iSorter = pParse->nTab++;
+ sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
+ sqlite3KeyInfoRef(pKey), P4_KEYINFO);
+
+ /* Open the table. Loop through all rows of the table, inserting index
+ ** records into the sorter. */
+ sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
+ addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
+ regRecord = sqlite3GetTempReg(pParse);
+ sqlite3MultiWrite(pParse);
+
+ sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
+ sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
+ sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
+ sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
+ sqlite3VdbeJumpHere(v, addr1);
+ if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
+ sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb,
+ (char *)pKey, P4_KEYINFO);
+ sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
+
+ addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
+ if( IsUniqueIndex(pIndex) ){
+ int j2 = sqlite3VdbeGoto(v, 1);
+ addr2 = sqlite3VdbeCurrentAddr(v);
+ sqlite3VdbeVerifyAbortable(v, OE_Abort);
+ sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
+ pIndex->nKeyCol); VdbeCoverage(v);
+ sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
+ sqlite3VdbeJumpHere(v, j2);
+ }else{
+ /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
+ ** abort. The exception is if one of the indexed expressions contains a
+ ** user function that throws an exception when it is evaluated. But the
+ ** overhead of adding a statement journal to a CREATE INDEX statement is
+ ** very small (since most of the pages written do not contain content that
+ ** needs to be restored if the statement aborts), so we call
+ ** sqlite3MayAbort() for all CREATE INDEX statements. */
+ sqlite3MayAbort(pParse);
+ addr2 = sqlite3VdbeCurrentAddr(v);
+ }
+ sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
+ if( !pIndex->bAscKeyBug ){
+ /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
+ ** faster by avoiding unnecessary seeks. But the optimization does
+ ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
+ ** with DESC primary keys, since those indexes have there keys in
+ ** a different order from the main table.
+ ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
+ */
+ sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
+ }
+ sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
+ sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
+ sqlite3ReleaseTempReg(pParse, regRecord);
+ sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
+ sqlite3VdbeJumpHere(v, addr1);
+
+ sqlite3VdbeAddOp1(v, OP_Close, iTab);
+ sqlite3VdbeAddOp1(v, OP_Close, iIdx);
+ sqlite3VdbeAddOp1(v, OP_Close, iSorter);
+}
+
+/*
+** Allocate heap space to hold an Index object with nCol columns.
+**
+** Increase the allocation size to provide an extra nExtra bytes
+** of 8-byte aligned space after the Index object and return a
+** pointer to this extra space in *ppExtra.
+*/
+SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
+ sqlite3 *db, /* Database connection */
+ i16 nCol, /* Total number of columns in the index */
+ int nExtra, /* Number of bytes of extra space to alloc */
+ char **ppExtra /* Pointer to the "extra" space */
+){
+ Index *p; /* Allocated index object */
+ int nByte; /* Bytes of space for Index object + arrays */
+
+ nByte = ROUND8(sizeof(Index)) + /* Index structure */
+ ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
+ ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
+ sizeof(i16)*nCol + /* Index.aiColumn */
+ sizeof(u8)*nCol); /* Index.aSortOrder */
+ p = sqlite3DbMallocZero(db, nByte + nExtra);
+ if( p ){
+ char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
+ p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
+ p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
+ p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
+ p->aSortOrder = (u8*)pExtra;
+ p->nColumn = nCol;
+ p->nKeyCol = nCol - 1;
+ *ppExtra = ((char*)p) + nByte;
+ }
+ return p;
+}
+
+/*
+** If expression list pList contains an expression that was parsed with
+** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
+** pParse and return non-zero. Otherwise, return zero.
+*/
+SQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
+ if( pList ){
+ int i;
+ for(i=0; i<pList->nExpr; i++){
+ if( pList->a[i].bNulls ){
+ u8 sf = pList->a[i].sortFlags;
+ sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
+ (sf==0 || sf==3) ? "FIRST" : "LAST"
+ );
+ return 1;
+ }
+ }
+ }
+ return 0;
+}
+
+/*
+** Create a new index for an SQL table. pName1.pName2 is the name of the index
+** and pTblList is the name of the table that is to be indexed. Both will
+** be NULL for a primary key or an index that is created to satisfy a
+** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
+** as the table to be indexed. pParse->pNewTable is a table that is
+** currently being constructed by a CREATE TABLE statement.
+**
+** pList is a list of columns to be indexed. pList will be NULL if this
+** is a primary key or unique-constraint on the most recent column added
+** to the table currently under construction.
+*/
+SQLITE_PRIVATE void sqlite3CreateIndex(
+ Parse *pParse, /* All information about this parse */
+ Token *pName1, /* First part of index name. May be NULL */
+ Token *pName2, /* Second part of index name. May be NULL */
+ SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
+ ExprList *pList, /* A list of columns to be indexed */
+ int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
+ Token *pStart, /* The CREATE token that begins this statement */
+ Expr *pPIWhere, /* WHERE clause for partial indices */
+ int sortOrder, /* Sort order of primary key when pList==NULL */
+ int ifNotExist, /* Omit error if index already exists */
+ u8 idxType /* The index type */
+){
+ Table *pTab = 0; /* Table to be indexed */
+ Index *pIndex = 0; /* The index to be created */
+ char *zName = 0; /* Name of the index */
+ int nName; /* Number of characters in zName */
+ int i, j;
+ DbFixer sFix; /* For assigning database names to pTable */
+ int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
+ sqlite3 *db = pParse->db;
+ Db *pDb; /* The specific table containing the indexed database */
+ int iDb; /* Index of the database that is being written */
+ Token *pName = 0; /* Unqualified name of the index to create */
+ struct ExprList_item *pListItem; /* For looping over pList */
+ int nExtra = 0; /* Space allocated for zExtra[] */
+ int nExtraCol; /* Number of extra columns needed */
+ char *zExtra = 0; /* Extra space after the Index object */
+ Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
+
+ if( db->mallocFailed || pParse->nErr>0 ){
+ goto exit_create_index;
+ }
+ if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
+ goto exit_create_index;
+ }
+ if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
+ goto exit_create_index;
+ }
+ if( sqlite3HasExplicitNulls(pParse, pList) ){
+ goto exit_create_index;
+ }
+
+ /*
+ ** Find the table that is to be indexed. Return early if not found.
+ */
+ if( pTblName!=0 ){
+
+ /* Use the two-part index name to determine the database
+ ** to search for the table. 'Fix' the table name to this db
+ ** before looking up the table.
+ */
+ assert( pName1 && pName2 );
+ iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
+ if( iDb<0 ) goto exit_create_index;
+ assert( pName && pName->z );
+
+#ifndef SQLITE_OMIT_TEMPDB
+ /* If the index name was unqualified, check if the table
+ ** is a temp table. If so, set the database to 1. Do not do this
+ ** if initialising a database schema.
+ */
+ if( !db->init.busy ){
+ pTab = sqlite3SrcListLookup(pParse, pTblName);
+ if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
+ iDb = 1;
+ }
+ }
+#endif
+
+ sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
+ if( sqlite3FixSrcList(&sFix, pTblName) ){
+ /* Because the parser constructs pTblName from a single identifier,
+ ** sqlite3FixSrcList can never fail. */
+ assert(0);
+ }
+ pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
+ assert( db->mallocFailed==0 || pTab==0 );
+ if( pTab==0 ) goto exit_create_index;
+ if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
+ sqlite3ErrorMsg(pParse,
+ "cannot create a TEMP index on non-TEMP table \"%s\"",
+ pTab->zName);
+ goto exit_create_index;
+ }
+ if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
+ }else{
+ assert( pName==0 );
+ assert( pStart==0 );
+ pTab = pParse->pNewTable;
+ if( !pTab ) goto exit_create_index;
+ iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ }
+ pDb = &db->aDb[iDb];
+
+ assert( pTab!=0 );
+ assert( pParse->nErr==0 );
+ if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
+ && db->init.busy==0
+ && pTblName!=0
+#if SQLITE_USER_AUTHENTICATION
+ && sqlite3UserAuthTable(pTab->zName)==0
+#endif
+ ){
+ sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
+ goto exit_create_index;
+ }
+#ifndef SQLITE_OMIT_VIEW
+ if( pTab->pSelect ){
+ sqlite3ErrorMsg(pParse, "views may not be indexed");
+ goto exit_create_index;
+ }
+#endif
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( IsVirtual(pTab) ){
+ sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
+ goto exit_create_index;
+ }
+#endif
+
+ /*
+ ** Find the name of the index. Make sure there is not already another
+ ** index or table with the same name.
+ **
+ ** Exception: If we are reading the names of permanent indices from the
+ ** sqlite_schema table (because some other process changed the schema) and
+ ** one of the index names collides with the name of a temporary table or
+ ** index, then we will continue to process this index.
+ **
+ ** If pName==0 it means that we are
+ ** dealing with a primary key or UNIQUE constraint. We have to invent our
+ ** own name.
+ */
+ if( pName ){
+ zName = sqlite3NameFromToken(db, pName);
+ if( zName==0 ) goto exit_create_index;
+ assert( pName->z!=0 );
+ if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
+ goto exit_create_index;
+ }
+ if( !IN_RENAME_OBJECT ){
+ if( !db->init.busy ){
+ if( sqlite3FindTable(db, zName, 0)!=0 ){
+ sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
+ goto exit_create_index;
+ }
+ }
+ if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
+ if( !ifNotExist ){
+ sqlite3ErrorMsg(pParse, "index %s already exists", zName);
+ }else{
+ assert( !db->init.busy );
+ sqlite3CodeVerifySchema(pParse, iDb);
+ }
+ goto exit_create_index;
+ }
+ }
+ }else{
+ int n;
+ Index *pLoop;
+ for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
+ zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
+ if( zName==0 ){
+ goto exit_create_index;
+ }
+
+ /* Automatic index names generated from within sqlite3_declare_vtab()
+ ** must have names that are distinct from normal automatic index names.
+ ** The following statement converts "sqlite3_autoindex..." into
+ ** "sqlite3_butoindex..." in order to make the names distinct.
+ ** The "vtab_err.test" test demonstrates the need of this statement. */
+ if( IN_SPECIAL_PARSE ) zName[7]++;
+ }
+
+ /* Check for authorization to create an index.
+ */
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ if( !IN_RENAME_OBJECT ){
+ const char *zDb = pDb->zDbSName;
+ if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
+ goto exit_create_index;
+ }
+ i = SQLITE_CREATE_INDEX;
+ if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
+ if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
+ goto exit_create_index;
+ }
+ }
+#endif
+
+ /* If pList==0, it means this routine was called to make a primary
+ ** key out of the last column added to the table under construction.
+ ** So create a fake list to simulate this.
+ */
+ if( pList==0 ){
+ Token prevCol;
+ Column *pCol = &pTab->aCol[pTab->nCol-1];
+ pCol->colFlags |= COLFLAG_UNIQUE;
+ sqlite3TokenInit(&prevCol, pCol->zName);
+ pList = sqlite3ExprListAppend(pParse, 0,
+ sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
+ if( pList==0 ) goto exit_create_index;
+ assert( pList->nExpr==1 );
+ sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
+ }else{
+ sqlite3ExprListCheckLength(pParse, pList, "index");
+ if( pParse->nErr ) goto exit_create_index;
+ }
+
+ /* Figure out how many bytes of space are required to store explicitly
+ ** specified collation sequence names.
+ */
+ for(i=0; i<pList->nExpr; i++){
+ Expr *pExpr = pList->a[i].pExpr;
+ assert( pExpr!=0 );
+ if( pExpr->op==TK_COLLATE ){
+ nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
+ }
+ }
+
+ /*
+ ** Allocate the index structure.
+ */
+ nName = sqlite3Strlen30(zName);
+ nExtraCol = pPk ? pPk->nKeyCol : 1;
+ assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
+ pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
+ nName + nExtra + 1, &zExtra);
+ if( db->mallocFailed ){
+ goto exit_create_index;
+ }
+ assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
+ assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
+ pIndex->zName = zExtra;
+ zExtra += nName + 1;
+ memcpy(pIndex->zName, zName, nName+1);
+ pIndex->pTable = pTab;
+ pIndex->onError = (u8)onError;
+ pIndex->uniqNotNull = onError!=OE_None;
+ pIndex->idxType = idxType;
+ pIndex->pSchema = db->aDb[iDb].pSchema;
+ pIndex->nKeyCol = pList->nExpr;
+ if( pPIWhere ){
+ sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
+ pIndex->pPartIdxWhere = pPIWhere;
+ pPIWhere = 0;
+ }
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+
+ /* Check to see if we should honor DESC requests on index columns
+ */
+ if( pDb->pSchema->file_format>=4 ){
+ sortOrderMask = -1; /* Honor DESC */
+ }else{
+ sortOrderMask = 0; /* Ignore DESC */
+ }
+
+ /* Analyze the list of expressions that form the terms of the index and
+ ** report any errors. In the common case where the expression is exactly
+ ** a table column, store that column in aiColumn[]. For general expressions,
+ ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
+ **
+ ** TODO: Issue a warning if two or more columns of the index are identical.
+ ** TODO: Issue a warning if the table primary key is used as part of the
+ ** index key.
+ */
+ pListItem = pList->a;
+ if( IN_RENAME_OBJECT ){
+ pIndex->aColExpr = pList;
+ pList = 0;
+ }
+ for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
+ Expr *pCExpr; /* The i-th index expression */
+ int requestedSortOrder; /* ASC or DESC on the i-th expression */
+ const char *zColl; /* Collation sequence name */
+
+ sqlite3StringToId(pListItem->pExpr);
+ sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
+ if( pParse->nErr ) goto exit_create_index;
+ pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
+ if( pCExpr->op!=TK_COLUMN ){
+ if( pTab==pParse->pNewTable ){
+ sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
+ "UNIQUE constraints");
+ goto exit_create_index;
+ }
+ if( pIndex->aColExpr==0 ){
+ pIndex->aColExpr = pList;
+ pList = 0;
+ }
+ j = XN_EXPR;
+ pIndex->aiColumn[i] = XN_EXPR;
+ pIndex->uniqNotNull = 0;
+ }else{
+ j = pCExpr->iColumn;
+ assert( j<=0x7fff );
+ if( j<0 ){
+ j = pTab->iPKey;
+ }else{
+ if( pTab->aCol[j].notNull==0 ){
+ pIndex->uniqNotNull = 0;
+ }
+ if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
+ pIndex->bHasVCol = 1;
+ }
+ }
+ pIndex->aiColumn[i] = (i16)j;
+ }
+ zColl = 0;
+ if( pListItem->pExpr->op==TK_COLLATE ){
+ int nColl;
+ zColl = pListItem->pExpr->u.zToken;
+ nColl = sqlite3Strlen30(zColl) + 1;
+ assert( nExtra>=nColl );
+ memcpy(zExtra, zColl, nColl);
+ zColl = zExtra;
+ zExtra += nColl;
+ nExtra -= nColl;
+ }else if( j>=0 ){
+ zColl = pTab->aCol[j].zColl;
+ }
+ if( !zColl ) zColl = sqlite3StrBINARY;
+ if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
+ goto exit_create_index;
+ }
+ pIndex->azColl[i] = zColl;
+ requestedSortOrder = pListItem->sortFlags & sortOrderMask;
+ pIndex->aSortOrder[i] = (u8)requestedSortOrder;
+ }
+
+ /* Append the table key to the end of the index. For WITHOUT ROWID
+ ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
+ ** normal tables (when pPk==0) this will be the rowid.
+ */
+ if( pPk ){
+ for(j=0; j<pPk->nKeyCol; j++){
+ int x = pPk->aiColumn[j];
+ assert( x>=0 );
+ if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
+ pIndex->nColumn--;
+ }else{
+ testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
+ pIndex->aiColumn[i] = x;
+ pIndex->azColl[i] = pPk->azColl[j];
+ pIndex->aSortOrder[i] = pPk->aSortOrder[j];
+ i++;
+ }
+ }
+ assert( i==pIndex->nColumn );
+ }else{
+ pIndex->aiColumn[i] = XN_ROWID;
+ pIndex->azColl[i] = sqlite3StrBINARY;
+ }
+ sqlite3DefaultRowEst(pIndex);
+ if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
+
+ /* If this index contains every column of its table, then mark
+ ** it as a covering index */
+ assert( HasRowid(pTab)
+ || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
+ recomputeColumnsNotIndexed(pIndex);
+ if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
+ pIndex->isCovering = 1;
+ for(j=0; j<pTab->nCol; j++){
+ if( j==pTab->iPKey ) continue;
+ if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
+ pIndex->isCovering = 0;
+ break;
+ }
+ }
+
+ if( pTab==pParse->pNewTable ){
+ /* This routine has been called to create an automatic index as a
+ ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
+ ** a PRIMARY KEY or UNIQUE clause following the column definitions.
+ ** i.e. one of:
+ **
+ ** CREATE TABLE t(x PRIMARY KEY, y);
+ ** CREATE TABLE t(x, y, UNIQUE(x, y));
+ **
+ ** Either way, check to see if the table already has such an index. If
+ ** so, don't bother creating this one. This only applies to
+ ** automatically created indices. Users can do as they wish with
+ ** explicit indices.
+ **
+ ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
+ ** (and thus suppressing the second one) even if they have different
+ ** sort orders.
+ **
+ ** If there are different collating sequences or if the columns of
+ ** the constraint occur in different orders, then the constraints are
+ ** considered distinct and both result in separate indices.
+ */
+ Index *pIdx;
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+ int k;
+ assert( IsUniqueIndex(pIdx) );
+ assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
+ assert( IsUniqueIndex(pIndex) );
+
+ if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
+ for(k=0; k<pIdx->nKeyCol; k++){
+ const char *z1;
+ const char *z2;
+ assert( pIdx->aiColumn[k]>=0 );
+ if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
+ z1 = pIdx->azColl[k];
+ z2 = pIndex->azColl[k];
+ if( sqlite3StrICmp(z1, z2) ) break;
+ }
+ if( k==pIdx->nKeyCol ){
+ if( pIdx->onError!=pIndex->onError ){
+ /* This constraint creates the same index as a previous
+ ** constraint specified somewhere in the CREATE TABLE statement.
+ ** However the ON CONFLICT clauses are different. If both this
+ ** constraint and the previous equivalent constraint have explicit
+ ** ON CONFLICT clauses this is an error. Otherwise, use the
+ ** explicitly specified behavior for the index.
+ */
+ if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
+ sqlite3ErrorMsg(pParse,
+ "conflicting ON CONFLICT clauses specified", 0);
+ }
+ if( pIdx->onError==OE_Default ){
+ pIdx->onError = pIndex->onError;
+ }
+ }
+ if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
+ if( IN_RENAME_OBJECT ){
+ pIndex->pNext = pParse->pNewIndex;
+ pParse->pNewIndex = pIndex;
+ pIndex = 0;
+ }
+ goto exit_create_index;
+ }
+ }
+ }
+
+ if( !IN_RENAME_OBJECT ){
+
+ /* Link the new Index structure to its table and to the other
+ ** in-memory database structures.
+ */
+ assert( pParse->nErr==0 );
+ if( db->init.busy ){
+ Index *p;
+ assert( !IN_SPECIAL_PARSE );
+ assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
+ if( pTblName!=0 ){
+ pIndex->tnum = db->init.newTnum;
+ if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
+ sqlite3ErrorMsg(pParse, "invalid rootpage");
+ pParse->rc = SQLITE_CORRUPT_BKPT;
+ goto exit_create_index;
+ }
+ }
+ p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
+ pIndex->zName, pIndex);
+ if( p ){
+ assert( p==pIndex ); /* Malloc must have failed */
+ sqlite3OomFault(db);
+ goto exit_create_index;
+ }
+ db->mDbFlags |= DBFLAG_SchemaChange;
+ }
+
+ /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
+ ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
+ ** emit code to allocate the index rootpage on disk and make an entry for
+ ** the index in the sqlite_schema table and populate the index with
+ ** content. But, do not do this if we are simply reading the sqlite_schema
+ ** table to parse the schema, or if this index is the PRIMARY KEY index
+ ** of a WITHOUT ROWID table.
+ **
+ ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
+ ** or UNIQUE index in a CREATE TABLE statement. Since the table
+ ** has just been created, it contains no data and the index initialization
+ ** step can be skipped.
+ */
+ else if( HasRowid(pTab) || pTblName!=0 ){
+ Vdbe *v;
+ char *zStmt;
+ int iMem = ++pParse->nMem;
+
+ v = sqlite3GetVdbe(pParse);
+ if( v==0 ) goto exit_create_index;
+
+ sqlite3BeginWriteOperation(pParse, 1, iDb);
+
+ /* Create the rootpage for the index using CreateIndex. But before
+ ** doing so, code a Noop instruction and store its address in
+ ** Index.tnum. This is required in case this index is actually a
+ ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
+ ** that case the convertToWithoutRowidTable() routine will replace
+ ** the Noop with a Goto to jump over the VDBE code generated below. */
+ pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop);
+ sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
+
+ /* Gather the complete text of the CREATE INDEX statement into
+ ** the zStmt variable
+ */
+ assert( pName!=0 || pStart==0 );
+ if( pStart ){
+ int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
+ if( pName->z[n-1]==';' ) n--;
+ /* A named index with an explicit CREATE INDEX statement */
+ zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
+ onError==OE_None ? "" : " UNIQUE", n, pName->z);
+ }else{
+ /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
+ /* zStmt = sqlite3MPrintf(""); */
+ zStmt = 0;
+ }
+
+ /* Add an entry in sqlite_schema for this index
+ */
+ sqlite3NestedParse(pParse,
+ "INSERT INTO %Q." DFLT_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);",
+ db->aDb[iDb].zDbSName,
+ pIndex->zName,
+ pTab->zName,
+ iMem,
+ zStmt
+ );
+ sqlite3DbFree(db, zStmt);
+
+ /* Fill the index with data and reparse the schema. Code an OP_Expire
+ ** to invalidate all pre-compiled statements.
+ */
+ if( pTblName ){
+ sqlite3RefillIndex(pParse, pIndex, iMem);
+ sqlite3ChangeCookie(pParse, iDb);
+ sqlite3VdbeAddParseSchemaOp(v, iDb,
+ sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
+ sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
+ }
+
+ sqlite3VdbeJumpHere(v, (int)pIndex->tnum);
+ }
+ }
+ if( db->init.busy || pTblName==0 ){
+ pIndex->pNext = pTab->pIndex;
+ pTab->pIndex = pIndex;
+ pIndex = 0;
+ }
+ else if( IN_RENAME_OBJECT ){
+ assert( pParse->pNewIndex==0 );
+ pParse->pNewIndex = pIndex;
+ pIndex = 0;
+ }
+
+ /* Clean up before exiting */
+exit_create_index:
+ if( pIndex ) sqlite3FreeIndex(db, pIndex);
+ if( pTab ){ /* Ensure all REPLACE indexes are at the end of the list */
+ Index **ppFrom = &pTab->pIndex;
+ Index *pThis;
+ for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
+ Index *pNext;
+ if( pThis->onError!=OE_Replace ) continue;
+ while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
+ *ppFrom = pNext;
+ pThis->pNext = pNext->pNext;
+ pNext->pNext = pThis;
+ ppFrom = &pNext->pNext;
+ }
+ break;
+ }
+ }
+ sqlite3ExprDelete(db, pPIWhere);
+ sqlite3ExprListDelete(db, pList);
+ sqlite3SrcListDelete(db, pTblName);
+ sqlite3DbFree(db, zName);
+}
+
+/*
+** Fill the Index.aiRowEst[] array with default information - information
+** to be used when we have not run the ANALYZE command.
+**
+** aiRowEst[0] is supposed to contain the number of elements in the index.
+** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
+** number of rows in the table that match any particular value of the
+** first column of the index. aiRowEst[2] is an estimate of the number
+** of rows that match any particular combination of the first 2 columns
+** of the index. And so forth. It must always be the case that
+*
+** aiRowEst[N]<=aiRowEst[N-1]
+** aiRowEst[N]>=1
+**
+** Apart from that, we have little to go on besides intuition as to
+** how aiRowEst[] should be initialized. The numbers generated here
+** are based on typical values found in actual indices.
+*/
+SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
+ /* 10, 9, 8, 7, 6 */
+ static const LogEst aVal[] = { 33, 32, 30, 28, 26 };
+ LogEst *a = pIdx->aiRowLogEst;
+ LogEst x;
+ int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
+ int i;
+
+ /* Indexes with default row estimates should not have stat1 data */
+ assert( !pIdx->hasStat1 );
+
+ /* Set the first entry (number of rows in the index) to the estimated
+ ** number of rows in the table, or half the number of rows in the table
+ ** for a partial index.
+ **
+ ** 2020-05-27: If some of the stat data is coming from the sqlite_stat1
+ ** table but other parts we are having to guess at, then do not let the
+ ** estimated number of rows in the table be less than 1000 (LogEst 99).
+ ** Failure to do this can cause the indexes for which we do not have
+ ** stat1 data to be ignored by the query planner.
+ */
+ x = pIdx->pTable->nRowLogEst;
+ assert( 99==sqlite3LogEst(1000) );
+ if( x<99 ){
+ pIdx->pTable->nRowLogEst = x = 99;
+ }
+ if( pIdx->pPartIdxWhere!=0 ) x -= 10; assert( 10==sqlite3LogEst(2) );
+ a[0] = x;
+
+ /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
+ ** 6 and each subsequent value (if any) is 5. */
+ memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
+ for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
+ a[i] = 23; assert( 23==sqlite3LogEst(5) );
+ }
+
+ assert( 0==sqlite3LogEst(1) );
+ if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
+}
+
+/*
+** This routine will drop an existing named index. This routine
+** implements the DROP INDEX statement.
+*/
+SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
+ Index *pIndex;
+ Vdbe *v;
+ sqlite3 *db = pParse->db;
+ int iDb;
+
+ assert( pParse->nErr==0 ); /* Never called with prior errors */
+ if( db->mallocFailed ){
+ goto exit_drop_index;
+ }
+ assert( pName->nSrc==1 );
+ if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
+ goto exit_drop_index;
+ }
+ pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
+ if( pIndex==0 ){
+ if( !ifExists ){
+ sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
+ }else{
+ sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
+ }
+ pParse->checkSchema = 1;
+ goto exit_drop_index;
+ }
+ if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
+ sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
+ "or PRIMARY KEY constraint cannot be dropped", 0);
+ goto exit_drop_index;
+ }
+ iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ {
+ int code = SQLITE_DROP_INDEX;
+ Table *pTab = pIndex->pTable;
+ const char *zDb = db->aDb[iDb].zDbSName;
+ const char *zTab = SCHEMA_TABLE(iDb);
+ if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
+ goto exit_drop_index;
+ }
+ if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
+ if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
+ goto exit_drop_index;
+ }
+ }
+#endif
+
+ /* Generate code to remove the index and from the schema table */
+ v = sqlite3GetVdbe(pParse);
+ if( v ){
+ sqlite3BeginWriteOperation(pParse, 1, iDb);
+ sqlite3NestedParse(pParse,
+ "DELETE FROM %Q." DFLT_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
+ db->aDb[iDb].zDbSName, pIndex->zName
+ );
+ sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
+ sqlite3ChangeCookie(pParse, iDb);
+ destroyRootPage(pParse, pIndex->tnum, iDb);
+ sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
+ }
+
+exit_drop_index:
+ sqlite3SrcListDelete(db, pName);
+}
+
+/*
+** pArray is a pointer to an array of objects. Each object in the
+** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
+** to extend the array so that there is space for a new object at the end.
+**
+** When this function is called, *pnEntry contains the current size of
+** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
+** in total).
+**
+** If the realloc() is successful (i.e. if no OOM condition occurs), the
+** space allocated for the new object is zeroed, *pnEntry updated to
+** reflect the new size of the array and a pointer to the new allocation
+** returned. *pIdx is set to the index of the new array entry in this case.
+**
+** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
+** unchanged and a copy of pArray returned.
+*/
+SQLITE_PRIVATE void *sqlite3ArrayAllocate(
+ sqlite3 *db, /* Connection to notify of malloc failures */
+ void *pArray, /* Array of objects. Might be reallocated */
+ int szEntry, /* Size of each object in the array */
+ int *pnEntry, /* Number of objects currently in use */
+ int *pIdx /* Write the index of a new slot here */
+){
+ char *z;
+ sqlite3_int64 n = *pIdx = *pnEntry;
+ if( (n & (n-1))==0 ){
+ sqlite3_int64 sz = (n==0) ? 1 : 2*n;
+ void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
+ if( pNew==0 ){
+ *pIdx = -1;
+ return pArray;
+ }
+ pArray = pNew;
+ }
+ z = (char*)pArray;
+ memset(&z[n * szEntry], 0, szEntry);
+ ++*pnEntry;
+ return pArray;
+}
+
+/*
+** Append a new element to the given IdList. Create a new IdList if
+** need be.
+**
+** A new IdList is returned, or NULL if malloc() fails.
+*/
+SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
+ sqlite3 *db = pParse->db;
+ int i;
+ if( pList==0 ){
+ pList = sqlite3DbMallocZero(db, sizeof(IdList) );
+ if( pList==0 ) return 0;
+ }
+ pList->a = sqlite3ArrayAllocate(
+ db,
+ pList->a,
+ sizeof(pList->a[0]),
+ &pList->nId,
+ &i
+ );
+ if( i<0 ){
+ sqlite3IdListDelete(db, pList);
+ return 0;
+ }
+ pList->a[i].zName = sqlite3NameFromToken(db, pToken);
+ if( IN_RENAME_OBJECT && pList->a[i].zName ){
+ sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
+ }
+ return pList;
+}
+
+/*
+** Delete an IdList.
+*/
+SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
+ int i;
+ if( pList==0 ) return;
+ for(i=0; i<pList->nId; i++){
+ sqlite3DbFree(db, pList->a[i].zName);
+ }
+ sqlite3DbFree(db, pList->a);
+ sqlite3DbFreeNN(db, pList);
+}
+
+/*
+** Return the index in pList of the identifier named zId. Return -1
+** if not found.
+*/
+SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
+ int i;
+ if( pList==0 ) return -1;
+ for(i=0; i<pList->nId; i++){
+ if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
+ }
+ return -1;
+}
+
+/*
+** Maximum size of a SrcList object.
+** The SrcList object is used to represent the FROM clause of a
+** SELECT statement, and the query planner cannot deal with more
+** than 64 tables in a join. So any value larger than 64 here
+** is sufficient for most uses. Smaller values, like say 10, are
+** appropriate for small and memory-limited applications.
+*/
+#ifndef SQLITE_MAX_SRCLIST
+# define SQLITE_MAX_SRCLIST 200
+#endif
+
+/*
+** Expand the space allocated for the given SrcList object by
+** creating nExtra new slots beginning at iStart. iStart is zero based.
+** New slots are zeroed.
+**
+** For example, suppose a SrcList initially contains two entries: A,B.
+** To append 3 new entries onto the end, do this:
+**
+** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
+**
+** After the call above it would contain: A, B, nil, nil, nil.
+** If the iStart argument had been 1 instead of 2, then the result
+** would have been: A, nil, nil, nil, B. To prepend the new slots,
+** the iStart value would be 0. The result then would
+** be: nil, nil, nil, A, B.
+**
+** If a memory allocation fails or the SrcList becomes too large, leave
+** the original SrcList unchanged, return NULL, and leave an error message
+** in pParse.
+*/
+SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
+ Parse *pParse, /* Parsing context into which errors are reported */
+ SrcList *pSrc, /* The SrcList to be enlarged */
+ int nExtra, /* Number of new slots to add to pSrc->a[] */
+ int iStart /* Index in pSrc->a[] of first new slot */
+){
+ int i;
+
+ /* Sanity checking on calling parameters */
+ assert( iStart>=0 );
+ assert( nExtra>=1 );
+ assert( pSrc!=0 );
+ assert( iStart<=pSrc->nSrc );
+
+ /* Allocate additional space if needed */
+ if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
+ SrcList *pNew;
+ sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
+ sqlite3 *db = pParse->db;
+
+ if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
+ sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
+ SQLITE_MAX_SRCLIST);
+ return 0;
+ }
+ if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
+ pNew = sqlite3DbRealloc(db, pSrc,
+ sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
+ if( pNew==0 ){
+ assert( db->mallocFailed );
+ return 0;
+ }
+ pSrc = pNew;
+ pSrc->nAlloc = nAlloc;
+ }
+
+ /* Move existing slots that come after the newly inserted slots
+ ** out of the way */
+ for(i=pSrc->nSrc-1; i>=iStart; i--){
+ pSrc->a[i+nExtra] = pSrc->a[i];
+ }
+ pSrc->nSrc += nExtra;
+
+ /* Zero the newly allocated slots */
+ memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
+ for(i=iStart; i<iStart+nExtra; i++){
+ pSrc->a[i].iCursor = -1;
+ }
+
+ /* Return a pointer to the enlarged SrcList */
+ return pSrc;
+}
+
+
+/*
+** Append a new table name to the given SrcList. Create a new SrcList if
+** need be. A new entry is created in the SrcList even if pTable is NULL.
+**
+** A SrcList is returned, or NULL if there is an OOM error or if the
+** SrcList grows to large. The returned
+** SrcList might be the same as the SrcList that was input or it might be
+** a new one. If an OOM error does occurs, then the prior value of pList
+** that is input to this routine is automatically freed.
+**
+** If pDatabase is not null, it means that the table has an optional
+** database name prefix. Like this: "database.table". The pDatabase
+** points to the table name and the pTable points to the database name.
+** The SrcList.a[].zName field is filled with the table name which might
+** come from pTable (if pDatabase is NULL) or from pDatabase.
+** SrcList.a[].zDatabase is filled with the database name from pTable,
+** or with NULL if no database is specified.
+**
+** In other words, if call like this:
+**
+** sqlite3SrcListAppend(D,A,B,0);
+**
+** Then B is a table name and the database name is unspecified. If called
+** like this:
+**
+** sqlite3SrcListAppend(D,A,B,C);
+**
+** Then C is the table name and B is the database name. If C is defined
+** then so is B. In other words, we never have a case where:
+**
+** sqlite3SrcListAppend(D,A,0,C);
+**
+** Both pTable and pDatabase are assumed to be quoted. They are dequoted
+** before being added to the SrcList.
+*/
+SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
+ Parse *pParse, /* Parsing context, in which errors are reported */
+ SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
+ Token *pTable, /* Table to append */
+ Token *pDatabase /* Database of the table */
+){
+ struct SrcList_item *pItem;
+ sqlite3 *db;
+ assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
+ assert( pParse!=0 );
+ assert( pParse->db!=0 );
+ db = pParse->db;
+ if( pList==0 ){
+ pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
+ if( pList==0 ) return 0;
+ pList->nAlloc = 1;
+ pList->nSrc = 1;
+ memset(&pList->a[0], 0, sizeof(pList->a[0]));
+ pList->a[0].iCursor = -1;
+ }else{
+ SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
+ if( pNew==0 ){
+ sqlite3SrcListDelete(db, pList);
+ return 0;
+ }else{
+ pList = pNew;
+ }
+ }
+ pItem = &pList->a[pList->nSrc-1];
+ if( pDatabase && pDatabase->z==0 ){
+ pDatabase = 0;
+ }
+ if( pDatabase ){
+ pItem->zName = sqlite3NameFromToken(db, pDatabase);
+ pItem->zDatabase = sqlite3NameFromToken(db, pTable);
+ }else{
+ pItem->zName = sqlite3NameFromToken(db, pTable);
+ pItem->zDatabase = 0;
+ }
+ return pList;
+}
+
+/*
+** Assign VdbeCursor index numbers to all tables in a SrcList
+*/
+SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
+ int i;
+ struct SrcList_item *pItem;
+ assert(pList || pParse->db->mallocFailed );
+ if( pList ){
+ for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
+ if( pItem->iCursor>=0 ) break;
+ pItem->iCursor = pParse->nTab++;
+ if( pItem->pSelect ){
+ sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
+ }
+ }
+ }
+}
+
+/*
+** Delete an entire SrcList including all its substructure.
+*/
+SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
+ int i;
+ struct SrcList_item *pItem;
+ if( pList==0 ) return;
+ for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
+ if( pItem->zDatabase ) sqlite3DbFreeNN(db, pItem->zDatabase);
+ sqlite3DbFree(db, pItem->zName);
+ if( pItem->zAlias ) sqlite3DbFreeNN(db, pItem->zAlias);
+ if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
+ if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
+ sqlite3DeleteTable(db, pItem->pTab);
+ if( pItem->pSelect ) sqlite3SelectDelete(db, pItem->pSelect);
+ if( pItem->pOn ) sqlite3ExprDelete(db, pItem->pOn);
+ if( pItem->pUsing ) sqlite3IdListDelete(db, pItem->pUsing);
+ }
+ sqlite3DbFreeNN(db, pList);
+}
+
+/*
+** This routine is called by the parser to add a new term to the
+** end of a growing FROM clause. The "p" parameter is the part of
+** the FROM clause that has already been constructed. "p" is NULL
+** if this is the first term of the FROM clause. pTable and pDatabase
+** are the name of the table and database named in the FROM clause term.
+** pDatabase is NULL if the database name qualifier is missing - the
+** usual case. If the term has an alias, then pAlias points to the
+** alias token. If the term is a subquery, then pSubquery is the
+** SELECT statement that the subquery encodes. The pTable and
+** pDatabase parameters are NULL for subqueries. The pOn and pUsing
+** parameters are the content of the ON and USING clauses.
+**
+** Return a new SrcList which encodes is the FROM with the new
+** term added.
+*/
+SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
+ Parse *pParse, /* Parsing context */
+ SrcList *p, /* The left part of the FROM clause already seen */
+ Token *pTable, /* Name of the table to add to the FROM clause */
+ Token *pDatabase, /* Name of the database containing pTable */
+ Token *pAlias, /* The right-hand side of the AS subexpression */
+ Select *pSubquery, /* A subquery used in place of a table name */
+ Expr *pOn, /* The ON clause of a join */
+ IdList *pUsing /* The USING clause of a join */
+){
+ struct SrcList_item *pItem;
+ sqlite3 *db = pParse->db;
+ if( !p && (pOn || pUsing) ){
+ sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
+ (pOn ? "ON" : "USING")
+ );
+ goto append_from_error;
+ }
+ p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
+ if( p==0 ){
+ goto append_from_error;
+ }
+ assert( p->nSrc>0 );
+ pItem = &p->a[p->nSrc-1];
+ assert( (pTable==0)==(pDatabase==0) );
+ assert( pItem->zName==0 || pDatabase!=0 );
+ if( IN_RENAME_OBJECT && pItem->zName ){
+ Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
+ sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
+ }
+ assert( pAlias!=0 );
+ if( pAlias->n ){
+ pItem->zAlias = sqlite3NameFromToken(db, pAlias);
+ }
+ pItem->pSelect = pSubquery;
+ pItem->pOn = pOn;
+ pItem->pUsing = pUsing;
+ return p;
+
+ append_from_error:
+ assert( p==0 );
+ sqlite3ExprDelete(db, pOn);
+ sqlite3IdListDelete(db, pUsing);
+ sqlite3SelectDelete(db, pSubquery);
+ return 0;
+}
+
+/*
+** Add an INDEXED BY or NOT INDEXED clause to the most recently added
+** element of the source-list passed as the second argument.
+*/
+SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
+ assert( pIndexedBy!=0 );
+ if( p && pIndexedBy->n>0 ){
+ struct SrcList_item *pItem;
+ assert( p->nSrc>0 );
+ pItem = &p->a[p->nSrc-1];
+ assert( pItem->fg.notIndexed==0 );
+ assert( pItem->fg.isIndexedBy==0 );
+ assert( pItem->fg.isTabFunc==0 );
+ if( pIndexedBy->n==1 && !pIndexedBy->z ){
+ /* A "NOT INDEXED" clause was supplied. See parse.y
+ ** construct "indexed_opt" for details. */
+ pItem->fg.notIndexed = 1;
+ }else{
+ pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
+ pItem->fg.isIndexedBy = 1;
+ }
+ }
+}
+
+/*
+** Append the contents of SrcList p2 to SrcList p1 and return the resulting
+** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
+** are deleted by this function.
+*/
+SQLITE_PRIVATE SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){
+ assert( p1 && p1->nSrc==1 );
+ if( p2 ){
+ SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1);
+ if( pNew==0 ){
+ sqlite3SrcListDelete(pParse->db, p2);
+ }else{
+ p1 = pNew;
+ memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(struct SrcList_item));
+ sqlite3DbFree(pParse->db, p2);
+ }
+ }
+ return p1;
+}
+
+/*
+** Add the list of function arguments to the SrcList entry for a
+** table-valued-function.
+*/
+SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
+ if( p ){
+ struct SrcList_item *pItem = &p->a[p->nSrc-1];
+ assert( pItem->fg.notIndexed==0 );
+ assert( pItem->fg.isIndexedBy==0 );
+ assert( pItem->fg.isTabFunc==0 );
+ pItem->u1.pFuncArg = pList;
+ pItem->fg.isTabFunc = 1;
+ }else{
+ sqlite3ExprListDelete(pParse->db, pList);
+ }
+}
+
+/*
+** When building up a FROM clause in the parser, the join operator
+** is initially attached to the left operand. But the code generator
+** expects the join operator to be on the right operand. This routine
+** Shifts all join operators from left to right for an entire FROM
+** clause.
+**
+** Example: Suppose the join is like this:
+**
+** A natural cross join B
+**
+** The operator is "natural cross join". The A and B operands are stored
+** in p->a[0] and p->a[1], respectively. The parser initially stores the
+** operator with A. This routine shifts that operator over to B.
+*/
+SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
+ if( p ){
+ int i;
+ for(i=p->nSrc-1; i>0; i--){
+ p->a[i].fg.jointype = p->a[i-1].fg.jointype;
+ }
+ p->a[0].fg.jointype = 0;
+ }
+}
+
+/*
+** Generate VDBE code for a BEGIN statement.
+*/
+SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
+ sqlite3 *db;
+ Vdbe *v;
+ int i;
+
+ assert( pParse!=0 );
+ db = pParse->db;
+ assert( db!=0 );
+ if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
+ return;
+ }
+ v = sqlite3GetVdbe(pParse);
+ if( !v ) return;
+ if( type!=TK_DEFERRED ){
+ for(i=0; i<db->nDb; i++){
+ sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
+ sqlite3VdbeUsesBtree(v, i);
+ }
+ }
+ sqlite3VdbeAddOp0(v, OP_AutoCommit);
+}
+
+/*
+** Generate VDBE code for a COMMIT or ROLLBACK statement.
+** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
+** code is generated for a COMMIT.
+*/
+SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
+ Vdbe *v;
+ int isRollback;
+
+ assert( pParse!=0 );
+ assert( pParse->db!=0 );
+ assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
+ isRollback = eType==TK_ROLLBACK;
+ if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
+ isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
+ return;
+ }
+ v = sqlite3GetVdbe(pParse);
+ if( v ){
+ sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
+ }
+}
+
+/*
+** This function is called by the parser when it parses a command to create,
+** release or rollback an SQL savepoint.
+*/
+SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
+ char *zName = sqlite3NameFromToken(pParse->db, pName);
+ if( zName ){
+ Vdbe *v = sqlite3GetVdbe(pParse);
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
+ assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
+#endif
+ if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
+ sqlite3DbFree(pParse->db, zName);
+ return;
+ }
+ sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
+ }
+}
+
+/*
+** Make sure the TEMP database is open and available for use. Return
+** the number of errors. Leave any error messages in the pParse structure.
+*/
+SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
+ sqlite3 *db = pParse->db;
+ if( db->aDb[1].pBt==0 && !pParse->explain ){
+ int rc;
+ Btree *pBt;
+ static const int flags =
+ SQLITE_OPEN_READWRITE |
+ SQLITE_OPEN_CREATE |
+ SQLITE_OPEN_EXCLUSIVE |
+ SQLITE_OPEN_DELETEONCLOSE |
+ SQLITE_OPEN_TEMP_DB;
+
+ rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
+ if( rc!=SQLITE_OK ){
+ sqlite3ErrorMsg(pParse, "unable to open a temporary database "
+ "file for storing temporary tables");
+ pParse->rc = rc;
+ return 1;
+ }
+ db->aDb[1].pBt = pBt;
+ assert( db->aDb[1].pSchema );
+ if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
+ sqlite3OomFault(db);
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/*
+** Record the fact that the schema cookie will need to be verified
+** for database iDb. The code to actually verify the schema cookie
+** will occur at the end of the top-level VDBE and will be generated
+** later, by sqlite3FinishCoding().
+*/
+static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){
+ assert( iDb>=0 && iDb<pToplevel->db->nDb );
+ assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 );
+ assert( iDb<SQLITE_MAX_ATTACHED+2 );
+ assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) );
+ if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
+ DbMaskSet(pToplevel->cookieMask, iDb);
+ if( !OMIT_TEMPDB && iDb==1 ){
+ sqlite3OpenTempDatabase(pToplevel);
+ }
+ }
+}
+SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
+ sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse), iDb);
+}
+
+
+/*
+** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
+** attached database. Otherwise, invoke it for the database named zDb only.
+*/
+SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
+ sqlite3 *db = pParse->db;
+ int i;
+ for(i=0; i<db->nDb; i++){
+ Db *pDb = &db->aDb[i];
+ if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
+ sqlite3CodeVerifySchema(pParse, i);
+ }
+ }
+}
+
+/*
+** Generate VDBE code that prepares for doing an operation that
+** might change the database.
+**
+** This routine starts a new transaction if we are not already within
+** a transaction. If we are already within a transaction, then a checkpoint
+** is set if the setStatement parameter is true. A checkpoint should
+** be set for operations that might fail (due to a constraint) part of
+** the way through and which will need to undo some writes without having to
+** rollback the whole transaction. For operations where all constraints
+** can be checked before any changes are made to the database, it is never
+** necessary to undo a write and the checkpoint should not be set.
+*/
+SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
+ Parse *pToplevel = sqlite3ParseToplevel(pParse);
+ sqlite3CodeVerifySchemaAtToplevel(pToplevel, iDb);
+ DbMaskSet(pToplevel->writeMask, iDb);
+ pToplevel->isMultiWrite |= setStatement;
+}
+
+/*
+** Indicate that the statement currently under construction might write
+** more than one entry (example: deleting one row then inserting another,
+** inserting multiple rows in a table, or inserting a row and index entries.)
+** If an abort occurs after some of these writes have completed, then it will
+** be necessary to undo the completed writes.
+*/
+SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
+ Parse *pToplevel = sqlite3ParseToplevel(pParse);
+ pToplevel->isMultiWrite = 1;
+}
+
+/*
+** The code generator calls this routine if is discovers that it is
+** possible to abort a statement prior to completion. In order to
+** perform this abort without corrupting the database, we need to make
+** sure that the statement is protected by a statement transaction.
+**
+** Technically, we only need to set the mayAbort flag if the
+** isMultiWrite flag was previously set. There is a time dependency
+** such that the abort must occur after the multiwrite. This makes
+** some statements involving the REPLACE conflict resolution algorithm
+** go a little faster. But taking advantage of this time dependency
+** makes it more difficult to prove that the code is correct (in
+** particular, it prevents us from writing an effective
+** implementation of sqlite3AssertMayAbort()) and so we have chosen
+** to take the safe route and skip the optimization.
+*/
+SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
+ Parse *pToplevel = sqlite3ParseToplevel(pParse);
+ pToplevel->mayAbort = 1;
+}
+
+/*
+** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
+** error. The onError parameter determines which (if any) of the statement
+** and/or current transaction is rolled back.
+*/
+SQLITE_PRIVATE void sqlite3HaltConstraint(
+ Parse *pParse, /* Parsing context */
+ int errCode, /* extended error code */
+ int onError, /* Constraint type */
+ char *p4, /* Error message */
+ i8 p4type, /* P4_STATIC or P4_TRANSIENT */
+ u8 p5Errmsg /* P5_ErrMsg type */
+){
+ Vdbe *v;
+ assert( pParse->pVdbe!=0 );
+ v = sqlite3GetVdbe(pParse);
+ assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
+ if( onError==OE_Abort ){
+ sqlite3MayAbort(pParse);
+ }
+ sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
+ sqlite3VdbeChangeP5(v, p5Errmsg);
+}
+
+/*
+** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
+*/
+SQLITE_PRIVATE void sqlite3UniqueConstraint(
+ Parse *pParse, /* Parsing context */
+ int onError, /* Constraint type */
+ Index *pIdx /* The index that triggers the constraint */
+){
+ char *zErr;
+ int j;
+ StrAccum errMsg;
+ Table *pTab = pIdx->pTable;
+
+ sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
+ pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
+ if( pIdx->aColExpr ){
+ sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
+ }else{
+ for(j=0; j<pIdx->nKeyCol; j++){
+ char *zCol;
+ assert( pIdx->aiColumn[j]>=0 );
+ zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
+ if( j ) sqlite3_str_append(&errMsg, ", ", 2);
+ sqlite3_str_appendall(&errMsg, pTab->zName);
+ sqlite3_str_append(&errMsg, ".", 1);
+ sqlite3_str_appendall(&errMsg, zCol);
+ }
+ }
+ zErr = sqlite3StrAccumFinish(&errMsg);
+ sqlite3HaltConstraint(pParse,
+ IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
+ : SQLITE_CONSTRAINT_UNIQUE,
+ onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
+}
+
+
+/*
+** Code an OP_Halt due to non-unique rowid.
+*/
+SQLITE_PRIVATE void sqlite3RowidConstraint(
+ Parse *pParse, /* Parsing context */
+ int onError, /* Conflict resolution algorithm */
+ Table *pTab /* The table with the non-unique rowid */
+){
+ char *zMsg;
+ int rc;
+ if( pTab->iPKey>=0 ){
+ zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
+ pTab->aCol[pTab->iPKey].zName);
+ rc = SQLITE_CONSTRAINT_PRIMARYKEY;
+ }else{
+ zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
+ rc = SQLITE_CONSTRAINT_ROWID;
+ }
+ sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
+ P5_ConstraintUnique);
+}
+
+/*
+** Check to see if pIndex uses the collating sequence pColl. Return
+** true if it does and false if it does not.
+*/
+#ifndef SQLITE_OMIT_REINDEX
+static int collationMatch(const char *zColl, Index *pIndex){
+ int i;
+ assert( zColl!=0 );
+ for(i=0; i<pIndex->nColumn; i++){
+ const char *z = pIndex->azColl[i];
+ assert( z!=0 || pIndex->aiColumn[i]<0 );
+ if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
+ return 1;
+ }
+ }
+ return 0;
+}
+#endif
+
+/*
+** Recompute all indices of pTab that use the collating sequence pColl.
+** If pColl==0 then recompute all indices of pTab.
+*/
+#ifndef SQLITE_OMIT_REINDEX
+static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
+ if( !IsVirtual(pTab) ){
+ Index *pIndex; /* An index associated with pTab */
+
+ for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
+ if( zColl==0 || collationMatch(zColl, pIndex) ){
+ int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
+ sqlite3BeginWriteOperation(pParse, 0, iDb);
+ sqlite3RefillIndex(pParse, pIndex, -1);
+ }
+ }
+ }
+}
+#endif
+
+/*
+** Recompute all indices of all tables in all databases where the
+** indices use the collating sequence pColl. If pColl==0 then recompute
+** all indices everywhere.
+*/
+#ifndef SQLITE_OMIT_REINDEX
+static void reindexDatabases(Parse *pParse, char const *zColl){
+ Db *pDb; /* A single database */
+ int iDb; /* The database index number */
+ sqlite3 *db = pParse->db; /* The database connection */
+ HashElem *k; /* For looping over tables in pDb */
+ Table *pTab; /* A table in the database */
+
+ assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
+ for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
+ assert( pDb!=0 );
+ for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
+ pTab = (Table*)sqliteHashData(k);
+ reindexTable(pParse, pTab, zColl);
+ }
+ }
+}
+#endif
+
+/*
+** Generate code for the REINDEX command.
+**
+** REINDEX -- 1
+** REINDEX <collation> -- 2
+** REINDEX ?<database>.?<tablename> -- 3
+** REINDEX ?<database>.?<indexname> -- 4
+**
+** Form 1 causes all indices in all attached databases to be rebuilt.
+** Form 2 rebuilds all indices in all databases that use the named
+** collating function. Forms 3 and 4 rebuild the named index or all
+** indices associated with the named table.
+*/
+#ifndef SQLITE_OMIT_REINDEX
+SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
+ CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
+ char *z; /* Name of a table or index */
+ const char *zDb; /* Name of the database */
+ Table *pTab; /* A table in the database */
+ Index *pIndex; /* An index associated with pTab */
+ int iDb; /* The database index number */
+ sqlite3 *db = pParse->db; /* The database connection */
+ Token *pObjName; /* Name of the table or index to be reindexed */
+
+ /* Read the database schema. If an error occurs, leave an error message
+ ** and code in pParse and return NULL. */
+ if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
+ return;
+ }
+
+ if( pName1==0 ){
+ reindexDatabases(pParse, 0);
+ return;
+ }else if( NEVER(pName2==0) || pName2->z==0 ){
+ char *zColl;
+ assert( pName1->z );
+ zColl = sqlite3NameFromToken(pParse->db, pName1);
+ if( !zColl ) return;
+ pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
+ if( pColl ){
+ reindexDatabases(pParse, zColl);
+ sqlite3DbFree(db, zColl);
+ return;
+ }
+ sqlite3DbFree(db, zColl);
+ }
+ iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
+ if( iDb<0 ) return;
+ z = sqlite3NameFromToken(db, pObjName);
+ if( z==0 ) return;
+ zDb = db->aDb[iDb].zDbSName;
+ pTab = sqlite3FindTable(db, z, zDb);
+ if( pTab ){
+ reindexTable(pParse, pTab, 0);
+ sqlite3DbFree(db, z);
+ return;
+ }
+ pIndex = sqlite3FindIndex(db, z, zDb);
+ sqlite3DbFree(db, z);
+ if( pIndex ){
+ sqlite3BeginWriteOperation(pParse, 0, iDb);
+ sqlite3RefillIndex(pParse, pIndex, -1);
+ return;
+ }
+ sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
+}
+#endif
+
+/*
+** Return a KeyInfo structure that is appropriate for the given Index.
+**
+** The caller should invoke sqlite3KeyInfoUnref() on the returned object
+** when it has finished using it.
+*/
+SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
+ int i;
+ int nCol = pIdx->nColumn;
+ int nKey = pIdx->nKeyCol;
+ KeyInfo *pKey;
+ if( pParse->nErr ) return 0;
+ if( pIdx->uniqNotNull ){
+ pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
+ }else{
+ pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
+ }
+ if( pKey ){
+ assert( sqlite3KeyInfoIsWriteable(pKey) );
+ for(i=0; i<nCol; i++){
+ const char *zColl = pIdx->azColl[i];
+ pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
+ sqlite3LocateCollSeq(pParse, zColl);
+ pKey->aSortFlags[i] = pIdx->aSortOrder[i];
+ assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
+ }
+ if( pParse->nErr ){
+ assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
+ if( pIdx->bNoQuery==0 ){
+ /* Deactivate the index because it contains an unknown collating
+ ** sequence. The only way to reactive the index is to reload the
+ ** schema. Adding the missing collating sequence later does not
+ ** reactive the index. The application had the chance to register
+ ** the missing index using the collation-needed callback. For
+ ** simplicity, SQLite will not give the application a second chance.
+ */
+ pIdx->bNoQuery = 1;
+ pParse->rc = SQLITE_ERROR_RETRY;
+ }
+ sqlite3KeyInfoUnref(pKey);
+ pKey = 0;
+ }
+ }
+ return pKey;
+}
+
+#ifndef SQLITE_OMIT_CTE
+/*
+** This routine is invoked once per CTE by the parser while parsing a
+** WITH clause.
+*/
+SQLITE_PRIVATE With *sqlite3WithAdd(
+ Parse *pParse, /* Parsing context */
+ With *pWith, /* Existing WITH clause, or NULL */
+ Token *pName, /* Name of the common-table */
+ ExprList *pArglist, /* Optional column name list for the table */
+ Select *pQuery /* Query used to initialize the table */
+){
+ sqlite3 *db = pParse->db;
+ With *pNew;
+ char *zName;
+
+ /* Check that the CTE name is unique within this WITH clause. If
+ ** not, store an error in the Parse structure. */
+ zName = sqlite3NameFromToken(pParse->db, pName);
+ if( zName && pWith ){
+ int i;
+ for(i=0; i<pWith->nCte; i++){
+ if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
+ sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
+ }
+ }
+ }
+
+ if( pWith ){
+ sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
+ pNew = sqlite3DbRealloc(db, pWith, nByte);
+ }else{
+ pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
+ }
+ assert( (pNew!=0 && zName!=0) || db->mallocFailed );
+
+ if( db->mallocFailed ){
+ sqlite3ExprListDelete(db, pArglist);
+ sqlite3SelectDelete(db, pQuery);
+ sqlite3DbFree(db, zName);
+ pNew = pWith;
+ }else{
+ pNew->a[pNew->nCte].pSelect = pQuery;
+ pNew->a[pNew->nCte].pCols = pArglist;
+ pNew->a[pNew->nCte].zName = zName;
+ pNew->a[pNew->nCte].zCteErr = 0;
+ pNew->nCte++;
+ }
+
+ return pNew;
+}
+
+/*
+** Free the contents of the With object passed as the second argument.
+*/
+SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
+ if( pWith ){
+ int i;
+ for(i=0; i<pWith->nCte; i++){
+ struct Cte *pCte = &pWith->a[i];
+ sqlite3ExprListDelete(db, pCte->pCols);
+ sqlite3SelectDelete(db, pCte->pSelect);
+ sqlite3DbFree(db, pCte->zName);
+ }
+ sqlite3DbFree(db, pWith);
+ }
+}
+#endif /* !defined(SQLITE_OMIT_CTE) */
+
+/************** End of build.c ***********************************************/
+/************** Begin file callback.c ****************************************/
+/*
+** 2005 May 23
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains functions used to access the internal hash tables
+** of user defined functions and collation sequences.
+*/
+
+/* #include "sqliteInt.h" */
+
+/*
+** Invoke the 'collation needed' callback to request a collation sequence
+** in the encoding enc of name zName, length nName.
+*/
+static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
+ assert( !db->xCollNeeded || !db->xCollNeeded16 );
+ if( db->xCollNeeded ){
+ char *zExternal = sqlite3DbStrDup(db, zName);
+ if( !zExternal ) return;
+ db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
+ sqlite3DbFree(db, zExternal);
+ }
+#ifndef SQLITE_OMIT_UTF16
+ if( db->xCollNeeded16 ){
+ char const *zExternal;
+ sqlite3_value *pTmp = sqlite3ValueNew(db);
+ sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
+ zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
+ if( zExternal ){
+ db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
+ }
+ sqlite3ValueFree(pTmp);
+ }
+#endif
+}
+
+/*
+** This routine is called if the collation factory fails to deliver a
+** collation function in the best encoding but there may be other versions
+** of this collation function (for other text encodings) available. Use one
+** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
+** possible.
+*/
+static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
+ CollSeq *pColl2;
+ char *z = pColl->zName;
+ int i;
+ static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
+ for(i=0; i<3; i++){
+ pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
+ if( pColl2->xCmp!=0 ){
+ memcpy(pColl, pColl2, sizeof(CollSeq));
+ pColl->xDel = 0; /* Do not copy the destructor */
+ return SQLITE_OK;
+ }
+ }
+ return SQLITE_ERROR;
+}
+
+/*
+** This routine is called on a collation sequence before it is used to
+** check that it is defined. An undefined collation sequence exists when
+** a database is loaded that contains references to collation sequences
+** that have not been defined by sqlite3_create_collation() etc.
+**
+** If required, this routine calls the 'collation needed' callback to
+** request a definition of the collating sequence. If this doesn't work,
+** an equivalent collating sequence that uses a text encoding different
+** from the main database is substituted, if one is available.
+*/
+SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
+ if( pColl && pColl->xCmp==0 ){
+ const char *zName = pColl->zName;
+ sqlite3 *db = pParse->db;
+ CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
+ if( !p ){
+ return SQLITE_ERROR;
+ }
+ assert( p==pColl );
+ }
+ return SQLITE_OK;
+}
+
+
+
+/*
+** Locate and return an entry from the db.aCollSeq hash table. If the entry
+** specified by zName and nName is not found and parameter 'create' is
+** true, then create a new entry. Otherwise return NULL.
+**
+** Each pointer stored in the sqlite3.aCollSeq hash table contains an
+** array of three CollSeq structures. The first is the collation sequence
+** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
+**
+** Stored immediately after the three collation sequences is a copy of
+** the collation sequence name. A pointer to this string is stored in
+** each collation sequence structure.
+*/
+static CollSeq *findCollSeqEntry(
+ sqlite3 *db, /* Database connection */
+ const char *zName, /* Name of the collating sequence */
+ int create /* Create a new entry if true */
+){
+ CollSeq *pColl;
+ pColl = sqlite3HashFind(&db->aCollSeq, zName);
+
+ if( 0==pColl && create ){
+ int nName = sqlite3Strlen30(zName) + 1;
+ pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);
+ if( pColl ){
+ CollSeq *pDel = 0;
+ pColl[0].zName = (char*)&pColl[3];
+ pColl[0].enc = SQLITE_UTF8;
+ pColl[1].zName = (char*)&pColl[3];
+ pColl[1].enc = SQLITE_UTF16LE;
+ pColl[2].zName = (char*)&pColl[3];
+ pColl[2].enc = SQLITE_UTF16BE;
+ memcpy(pColl[0].zName, zName, nName);
+ pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
+
+ /* If a malloc() failure occurred in sqlite3HashInsert(), it will
+ ** return the pColl pointer to be deleted (because it wasn't added
+ ** to the hash table).
+ */
+ assert( pDel==0 || pDel==pColl );
+ if( pDel!=0 ){
+ sqlite3OomFault(db);
+ sqlite3DbFree(db, pDel);
+ pColl = 0;
+ }
+ }
+ }
+ return pColl;
+}
+
+/*
+** Parameter zName points to a UTF-8 encoded string nName bytes long.
+** Return the CollSeq* pointer for the collation sequence named zName
+** for the encoding 'enc' from the database 'db'.
+**
+** If the entry specified is not found and 'create' is true, then create a
+** new entry. Otherwise return NULL.
+**
+** A separate function sqlite3LocateCollSeq() is a wrapper around
+** this routine. sqlite3LocateCollSeq() invokes the collation factory
+** if necessary and generates an error message if the collating sequence
+** cannot be found.
+**
+** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
+*/
+SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
+ sqlite3 *db, /* Database connection to search */
+ u8 enc, /* Desired text encoding */
+ const char *zName, /* Name of the collating sequence. Might be NULL */
+ int create /* True to create CollSeq if doesn't already exist */
+){
+ CollSeq *pColl;
+ assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
+ assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
+ if( zName ){
+ pColl = findCollSeqEntry(db, zName, create);
+ if( pColl ) pColl += enc-1;
+ }else{
+ pColl = db->pDfltColl;
+ }
+ return pColl;
+}
+
+/*
+** Change the text encoding for a database connection. This means that
+** the pDfltColl must change as well.
+*/
+SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8 enc){
+ assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
+ db->enc = enc;
+ /* EVIDENCE-OF: R-08308-17224 The default collating function for all
+ ** strings is BINARY.
+ */
+ db->pDfltColl = sqlite3FindCollSeq(db, enc, sqlite3StrBINARY, 0);
+}
+
+/*
+** This function is responsible for invoking the collation factory callback
+** or substituting a collation sequence of a different encoding when the
+** requested collation sequence is not available in the desired encoding.
+**
+** If it is not NULL, then pColl must point to the database native encoding
+** collation sequence with name zName, length nName.
+**
+** The return value is either the collation sequence to be used in database
+** db for collation type name zName, length nName, or NULL, if no collation
+** sequence can be found. If no collation is found, leave an error message.
+**
+** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
+*/
+SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
+ Parse *pParse, /* Parsing context */
+ u8 enc, /* The desired encoding for the collating sequence */
+ CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
+ const char *zName /* Collating sequence name */
+){
+ CollSeq *p;
+ sqlite3 *db = pParse->db;
+
+ p = pColl;
+ if( !p ){
+ p = sqlite3FindCollSeq(db, enc, zName, 0);
+ }
+ if( !p || !p->xCmp ){
+ /* No collation sequence of this type for this encoding is registered.
+ ** Call the collation factory to see if it can supply us with one.
+ */
+ callCollNeeded(db, enc, zName);
+ p = sqlite3FindCollSeq(db, enc, zName, 0);
+ }
+ if( p && !p->xCmp && synthCollSeq(db, p) ){
+ p = 0;
+ }
+ assert( !p || p->xCmp );
+ if( p==0 ){
+ sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
+ pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;
+ }
+ return p;
+}
+
+/*
+** This function returns the collation sequence for database native text
+** encoding identified by the string zName.
+**
+** If the requested collation sequence is not available, or not available
+** in the database native encoding, the collation factory is invoked to
+** request it. If the collation factory does not supply such a sequence,
+** and the sequence is available in another text encoding, then that is
+** returned instead.
+**
+** If no versions of the requested collations sequence are available, or
+** another error occurs, NULL is returned and an error message written into
+** pParse.
+**
+** This routine is a wrapper around sqlite3FindCollSeq(). This routine
+** invokes the collation factory if the named collation cannot be found
+** and generates an error message.
+**
+** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
+*/
+SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
+ sqlite3 *db = pParse->db;
+ u8 enc = ENC(db);
+ u8 initbusy = db->init.busy;
+ CollSeq *pColl;
+
+ pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
+ if( !initbusy && (!pColl || !pColl->xCmp) ){
+ pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
+ }
+
+ return pColl;
+}
+
+/* During the search for the best function definition, this procedure
+** is called to test how well the function passed as the first argument
+** matches the request for a function with nArg arguments in a system
+** that uses encoding enc. The value returned indicates how well the
+** request is matched. A higher value indicates a better match.
+**
+** If nArg is -1 that means to only return a match (non-zero) if p->nArg
+** is also -1. In other words, we are searching for a function that
+** takes a variable number of arguments.
+**
+** If nArg is -2 that means that we are searching for any function
+** regardless of the number of arguments it uses, so return a positive
+** match score for any
+**
+** The returned value is always between 0 and 6, as follows:
+**
+** 0: Not a match.
+** 1: UTF8/16 conversion required and function takes any number of arguments.
+** 2: UTF16 byte order change required and function takes any number of args.
+** 3: encoding matches and function takes any number of arguments
+** 4: UTF8/16 conversion required - argument count matches exactly
+** 5: UTF16 byte order conversion required - argument count matches exactly
+** 6: Perfect match: encoding and argument count match exactly.
+**
+** If nArg==(-2) then any function with a non-null xSFunc is
+** a perfect match and any function with xSFunc NULL is
+** a non-match.
+*/
+#define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
+static int matchQuality(
+ FuncDef *p, /* The function we are evaluating for match quality */
+ int nArg, /* Desired number of arguments. (-1)==any */
+ u8 enc /* Desired text encoding */
+){
+ int match;
+ assert( p->nArg>=-1 );
+
+ /* Wrong number of arguments means "no match" */
+ if( p->nArg!=nArg ){
+ if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
+ if( p->nArg>=0 ) return 0;
+ }
+
+ /* Give a better score to a function with a specific number of arguments
+ ** than to function that accepts any number of arguments. */
+ if( p->nArg==nArg ){
+ match = 4;
+ }else{
+ match = 1;
+ }
+
+ /* Bonus points if the text encoding matches */
+ if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
+ match += 2; /* Exact encoding match */
+ }else if( (enc & p->funcFlags & 2)!=0 ){
+ match += 1; /* Both are UTF16, but with different byte orders */
+ }
+
+ return match;
+}
+
+/*
+** Search a FuncDefHash for a function with the given name. Return
+** a pointer to the matching FuncDef if found, or 0 if there is no match.
+*/
+SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(
+ int h, /* Hash of the name */
+ const char *zFunc /* Name of function */
+){
+ FuncDef *p;
+ for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
+ if( sqlite3StrICmp(p->zName, zFunc)==0 ){
+ return p;
+ }
+ }
+ return 0;
+}
+
+/*
+** Insert a new FuncDef into a FuncDefHash hash table.
+*/
+SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
+ FuncDef *aDef, /* List of global functions to be inserted */
+ int nDef /* Length of the apDef[] list */
+){
+ int i;
+ for(i=0; i<nDef; i++){
+ FuncDef *pOther;
+ const char *zName = aDef[i].zName;
+ int nName = sqlite3Strlen30(zName);
+ int h = SQLITE_FUNC_HASH(zName[0], nName);
+ assert( zName[0]>='a' && zName[0]<='z' );
+ pOther = sqlite3FunctionSearch(h, zName);
+ if( pOther ){
+ assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
+ aDef[i].pNext = pOther->pNext;
+ pOther->pNext = &aDef[i];
+ }else{
+ aDef[i].pNext = 0;
+ aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
+ sqlite3BuiltinFunctions.a[h] = &aDef[i];
+ }
+ }
+}
+
+
+
+/*
+** Locate a user function given a name, a number of arguments and a flag
+** indicating whether the function prefers UTF-16 over UTF-8. Return a
+** pointer to the FuncDef structure that defines that function, or return
+** NULL if the function does not exist.
+**
+** If the createFlag argument is true, then a new (blank) FuncDef
+** structure is created and liked into the "db" structure if a
+** no matching function previously existed.
+**
+** If nArg is -2, then the first valid function found is returned. A
+** function is valid if xSFunc is non-zero. The nArg==(-2)
+** case is used to see if zName is a valid function name for some number
+** of arguments. If nArg is -2, then createFlag must be 0.
+**
+** If createFlag is false, then a function with the required name and
+** number of arguments may be returned even if the eTextRep flag does not
+** match that requested.
+*/
+SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
+ sqlite3 *db, /* An open database */
+ const char *zName, /* Name of the function. zero-terminated */
+ int nArg, /* Number of arguments. -1 means any number */
+ u8 enc, /* Preferred text encoding */
+ u8 createFlag /* Create new entry if true and does not otherwise exist */
+){
+ FuncDef *p; /* Iterator variable */
+ FuncDef *pBest = 0; /* Best match found so far */
+ int bestScore = 0; /* Score of best match */
+ int h; /* Hash value */
+ int nName; /* Length of the name */
+
+ assert( nArg>=(-2) );
+ assert( nArg>=(-1) || createFlag==0 );
+ nName = sqlite3Strlen30(zName);
+
+ /* First search for a match amongst the application-defined functions.
+ */
+ p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
+ while( p ){
+ int score = matchQuality(p, nArg, enc);
+ if( score>bestScore ){
+ pBest = p;
+ bestScore = score;
+ }
+ p = p->pNext;
+ }
+
+ /* If no match is found, search the built-in functions.
+ **
+ ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
+ ** functions even if a prior app-defined function was found. And give
+ ** priority to built-in functions.
+ **
+ ** Except, if createFlag is true, that means that we are trying to
+ ** install a new function. Whatever FuncDef structure is returned it will
+ ** have fields overwritten with new information appropriate for the
+ ** new function. But the FuncDefs for built-in functions are read-only.
+ ** So we must not search for built-ins when creating a new function.
+ */
+ if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
+ bestScore = 0;
+ h = SQLITE_FUNC_HASH(sqlite3UpperToLower[(u8)zName[0]], nName);
+ p = sqlite3FunctionSearch(h, zName);
+ while( p ){
+ int score = matchQuality(p, nArg, enc);
+ if( score>bestScore ){
+ pBest = p;
+ bestScore = score;
+ }
+ p = p->pNext;
+ }
+ }
+
+ /* If the createFlag parameter is true and the search did not reveal an
+ ** exact match for the name, number of arguments and encoding, then add a
+ ** new entry to the hash table and return it.
+ */
+ if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
+ (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
+ FuncDef *pOther;
+ u8 *z;
+ pBest->zName = (const char*)&pBest[1];
+ pBest->nArg = (u16)nArg;
+ pBest->funcFlags = enc;
+ memcpy((char*)&pBest[1], zName, nName+1);
+ for(z=(u8*)pBest->zName; *z; z++) *z = sqlite3UpperToLower[*z];
+ pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
+ if( pOther==pBest ){
+ sqlite3DbFree(db, pBest);
+ sqlite3OomFault(db);
+ return 0;
+ }else{
+ pBest->pNext = pOther;
+ }
+ }
+
+ if( pBest && (pBest->xSFunc || createFlag) ){
+ return pBest;
+ }
+ return 0;
+}
+
+/*
+** Free all resources held by the schema structure. The void* argument points
+** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
+** pointer itself, it just cleans up subsidiary resources (i.e. the contents
+** of the schema hash tables).
+**
+** The Schema.cache_size variable is not cleared.
+*/
+SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
+ Hash temp1;
+ Hash temp2;
+ HashElem *pElem;
+ Schema *pSchema = (Schema *)p;
+
+ temp1 = pSchema->tblHash;
+ temp2 = pSchema->trigHash;
+ sqlite3HashInit(&pSchema->trigHash);
+ sqlite3HashClear(&pSchema->idxHash);
+ for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
+ sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
+ }
+ sqlite3HashClear(&temp2);
+ sqlite3HashInit(&pSchema->tblHash);
+ for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
+ Table *pTab = sqliteHashData(pElem);
+ sqlite3DeleteTable(0, pTab);
+ }
+ sqlite3HashClear(&temp1);
+ sqlite3HashClear(&pSchema->fkeyHash);
+ pSchema->pSeqTab = 0;
+ if( pSchema->schemaFlags & DB_SchemaLoaded ){
+ pSchema->iGeneration++;
+ }
+ pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
+}
+
+/*
+** Find and return the schema associated with a BTree. Create
+** a new one if necessary.
+*/
+SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
+ Schema * p;
+ if( pBt ){
+ p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
+ }else{
+ p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
+ }
+ if( !p ){
+ sqlite3OomFault(db);
+ }else if ( 0==p->file_format ){
+ sqlite3HashInit(&p->tblHash);
+ sqlite3HashInit(&p->idxHash);
+ sqlite3HashInit(&p->trigHash);
+ sqlite3HashInit(&p->fkeyHash);
+ p->enc = SQLITE_UTF8;
+ }
+ return p;
+}
+
+/************** End of callback.c ********************************************/
+/************** Begin file delete.c ******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains C code routines that are called by the parser
+** in order to generate code for DELETE FROM statements.
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** While a SrcList can in general represent multiple tables and subqueries
+** (as in the FROM clause of a SELECT statement) in this case it contains
+** the name of a single table, as one might find in an INSERT, DELETE,
+** or UPDATE statement. Look up that table in the symbol table and
+** return a pointer. Set an error message and return NULL if the table
+** name is not found or if any other error occurs.
+**
+** The following fields are initialized appropriate in pSrc:
+**
+** pSrc->a[0].pTab Pointer to the Table object
+** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
+**
+*/
+SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
+ struct SrcList_item *pItem = pSrc->a;
+ Table *pTab;
+ assert( pItem && pSrc->nSrc>=1 );
+ pTab = sqlite3LocateTableItem(pParse, 0, pItem);
+ sqlite3DeleteTable(pParse->db, pItem->pTab);
+ pItem->pTab = pTab;
+ if( pTab ){
+ pTab->nTabRef++;
+ }
+ if( sqlite3IndexedByLookup(pParse, pItem) ){
+ pTab = 0;
+ }
+ return pTab;
+}
+
+/* Return true if table pTab is read-only.
+**
+** A table is read-only if any of the following are true:
+**
+** 1) It is a virtual table and no implementation of the xUpdate method
+** has been provided
+**
+** 2) It is a system table (i.e. sqlite_schema), this call is not
+** part of a nested parse and writable_schema pragma has not
+** been specified
+**
+** 3) The table is a shadow table, the database connection is in
+** defensive mode, and the current sqlite3_prepare()
+** is for a top-level SQL statement.
+*/
+static int tabIsReadOnly(Parse *pParse, Table *pTab){
+ sqlite3 *db;
+ if( IsVirtual(pTab) ){
+ return sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0;
+ }
+ if( (pTab->tabFlags & (TF_Readonly|TF_Shadow))==0 ) return 0;
+ db = pParse->db;
+ if( (pTab->tabFlags & TF_Readonly)!=0 ){
+ return sqlite3WritableSchema(db)==0 && pParse->nested==0;
+ }
+ assert( pTab->tabFlags & TF_Shadow );
+ return sqlite3ReadOnlyShadowTables(db);
+}
+
+/*
+** Check to make sure the given table is writable. If it is not
+** writable, generate an error message and return 1. If it is
+** writable return 0;
+*/
+SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
+ if( tabIsReadOnly(pParse, pTab) ){
+ sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
+ return 1;
+ }
+#ifndef SQLITE_OMIT_VIEW
+ if( !viewOk && pTab->pSelect ){
+ sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
+ return 1;
+ }
+#endif
+ return 0;
+}
+
+
+#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
+/*
+** Evaluate a view and store its result in an ephemeral table. The
+** pWhere argument is an optional WHERE clause that restricts the
+** set of rows in the view that are to be added to the ephemeral table.
+*/
+SQLITE_PRIVATE void sqlite3MaterializeView(
+ Parse *pParse, /* Parsing context */
+ Table *pView, /* View definition */
+ Expr *pWhere, /* Optional WHERE clause to be added */
+ ExprList *pOrderBy, /* Optional ORDER BY clause */
+ Expr *pLimit, /* Optional LIMIT clause */
+ int iCur /* Cursor number for ephemeral table */
+){
+ SelectDest dest;
+ Select *pSel;
+ SrcList *pFrom;
+ sqlite3 *db = pParse->db;
+ int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
+ pWhere = sqlite3ExprDup(db, pWhere, 0);
+ pFrom = sqlite3SrcListAppend(pParse, 0, 0, 0);
+ if( pFrom ){
+ assert( pFrom->nSrc==1 );
+ pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
+ pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
+ assert( pFrom->a[0].pOn==0 );
+ assert( pFrom->a[0].pUsing==0 );
+ }
+ pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy,
+ SF_IncludeHidden, pLimit);
+ sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
+ sqlite3Select(pParse, pSel, &dest);
+ sqlite3SelectDelete(db, pSel);
+}
+#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
+
+#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
+/*
+** Generate an expression tree to implement the WHERE, ORDER BY,
+** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
+**
+** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
+** \__________________________/
+** pLimitWhere (pInClause)
+*/
+SQLITE_PRIVATE Expr *sqlite3LimitWhere(
+ Parse *pParse, /* The parser context */
+ SrcList *pSrc, /* the FROM clause -- which tables to scan */
+ Expr *pWhere, /* The WHERE clause. May be null */
+ ExprList *pOrderBy, /* The ORDER BY clause. May be null */
+ Expr *pLimit, /* The LIMIT clause. May be null */
+ char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
+){
+ sqlite3 *db = pParse->db;
+ Expr *pLhs = NULL; /* LHS of IN(SELECT...) operator */
+ Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
+ ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
+ SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
+ Select *pSelect = NULL; /* Complete SELECT tree */
+ Table *pTab;
+
+ /* Check that there isn't an ORDER BY without a LIMIT clause.
+ */
+ if( pOrderBy && pLimit==0 ) {
+ sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
+ sqlite3ExprDelete(pParse->db, pWhere);
+ sqlite3ExprListDelete(pParse->db, pOrderBy);
+ return 0;
+ }
+
+ /* We only need to generate a select expression if there
+ ** is a limit/offset term to enforce.
+ */
+ if( pLimit == 0 ) {
+ return pWhere;
+ }
+
+ /* Generate a select expression tree to enforce the limit/offset
+ ** term for the DELETE or UPDATE statement. For example:
+ ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
+ ** becomes:
+ ** DELETE FROM table_a WHERE rowid IN (
+ ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
+ ** );
+ */
+
+ pTab = pSrc->a[0].pTab;
+ if( HasRowid(pTab) ){
+ pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0);
+ pEList = sqlite3ExprListAppend(
+ pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0)
+ );
+ }else{
+ Index *pPk = sqlite3PrimaryKeyIndex(pTab);
+ if( pPk->nKeyCol==1 ){
+ const char *zName = pTab->aCol[pPk->aiColumn[0]].zName;
+ pLhs = sqlite3Expr(db, TK_ID, zName);
+ pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName));
+ }else{
+ int i;
+ for(i=0; i<pPk->nKeyCol; i++){
+ Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName);
+ pEList = sqlite3ExprListAppend(pParse, pEList, p);
+ }
+ pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
+ if( pLhs ){
+ pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);
+ }
+ }
+ }
+
+ /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
+ ** and the SELECT subtree. */
+ pSrc->a[0].pTab = 0;
+ pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
+ pSrc->a[0].pTab = pTab;
+ pSrc->a[0].pIBIndex = 0;
+
+ /* generate the SELECT expression tree. */
+ pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0,
+ pOrderBy,0,pLimit
+ );
+
+ /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
+ pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0);
+ sqlite3PExprAddSelect(pParse, pInClause, pSelect);
+ return pInClause;
+}
+#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
+ /* && !defined(SQLITE_OMIT_SUBQUERY) */
+
+/*
+** Generate code for a DELETE FROM statement.
+**
+** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
+** \________/ \________________/
+** pTabList pWhere
+*/
+SQLITE_PRIVATE void sqlite3DeleteFrom(
+ Parse *pParse, /* The parser context */
+ SrcList *pTabList, /* The table from which we should delete things */
+ Expr *pWhere, /* The WHERE clause. May be null */
+ ExprList *pOrderBy, /* ORDER BY clause. May be null */
+ Expr *pLimit /* LIMIT clause. May be null */
+){
+ Vdbe *v; /* The virtual database engine */
+ Table *pTab; /* The table from which records will be deleted */
+ int i; /* Loop counter */
+ WhereInfo *pWInfo; /* Information about the WHERE clause */
+ Index *pIdx; /* For looping over indices of the table */
+ int iTabCur; /* Cursor number for the table */
+ int iDataCur = 0; /* VDBE cursor for the canonical data source */
+ int iIdxCur = 0; /* Cursor number of the first index */
+ int nIdx; /* Number of indices */
+ sqlite3 *db; /* Main database structure */
+ AuthContext sContext; /* Authorization context */
+ NameContext sNC; /* Name context to resolve expressions in */
+ int iDb; /* Database number */
+ int memCnt = 0; /* Memory cell used for change counting */
+ int rcauth; /* Value returned by authorization callback */
+ int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
+ int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
+ u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
+ Index *pPk; /* The PRIMARY KEY index on the table */
+ int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
+ i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
+ int iKey; /* Memory cell holding key of row to be deleted */
+ i16 nKey; /* Number of memory cells in the row key */
+ int iEphCur = 0; /* Ephemeral table holding all primary key values */
+ int iRowSet = 0; /* Register for rowset of rows to delete */
+ int addrBypass = 0; /* Address of jump over the delete logic */
+ int addrLoop = 0; /* Top of the delete loop */
+ int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
+ int bComplex; /* True if there are triggers or FKs or
+ ** subqueries in the WHERE clause */
+
+#ifndef SQLITE_OMIT_TRIGGER
+ int isView; /* True if attempting to delete from a view */
+ Trigger *pTrigger; /* List of table triggers, if required */
+#endif
+
+ memset(&sContext, 0, sizeof(sContext));
+ db = pParse->db;
+ if( pParse->nErr || db->mallocFailed ){
+ goto delete_from_cleanup;
+ }
+ assert( pTabList->nSrc==1 );
+
+
+ /* Locate the table which we want to delete. This table has to be
+ ** put in an SrcList structure because some of the subroutines we
+ ** will be calling are designed to work with multiple tables and expect
+ ** an SrcList* parameter instead of just a Table* parameter.
+ */
+ pTab = sqlite3SrcListLookup(pParse, pTabList);
+ if( pTab==0 ) goto delete_from_cleanup;
+
+ /* Figure out if we have any triggers and if the table being
+ ** deleted from is a view
+ */
+#ifndef SQLITE_OMIT_TRIGGER
+ pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
+ isView = pTab->pSelect!=0;
+#else
+# define pTrigger 0
+# define isView 0
+#endif
+ bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
+#ifdef SQLITE_OMIT_VIEW
+# undef isView
+# define isView 0
+#endif
+
+#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
+ if( !isView ){
+ pWhere = sqlite3LimitWhere(
+ pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE"
+ );
+ pOrderBy = 0;
+ pLimit = 0;
+ }
+#endif
+
+ /* If pTab is really a view, make sure it has been initialized.
+ */
+ if( sqlite3ViewGetColumnNames(pParse, pTab) ){
+ goto delete_from_cleanup;
+ }
+
+ if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
+ goto delete_from_cleanup;
+ }
+ iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ assert( iDb<db->nDb );
+ rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
+ db->aDb[iDb].zDbSName);
+ assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
+ if( rcauth==SQLITE_DENY ){
+ goto delete_from_cleanup;
+ }
+ assert(!isView || pTrigger);
+
+ /* Assign cursor numbers to the table and all its indices.
+ */
+ assert( pTabList->nSrc==1 );
+ iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
+ for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
+ pParse->nTab++;
+ }
+
+ /* Start the view context
+ */
+ if( isView ){
+ sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
+ }
+
+ /* Begin generating code.
+ */
+ v = sqlite3GetVdbe(pParse);
+ if( v==0 ){
+ goto delete_from_cleanup;
+ }
+ if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
+ sqlite3BeginWriteOperation(pParse, bComplex, iDb);
+
+ /* If we are trying to delete from a view, realize that view into
+ ** an ephemeral table.
+ */
+#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
+ if( isView ){
+ sqlite3MaterializeView(pParse, pTab,
+ pWhere, pOrderBy, pLimit, iTabCur
+ );
+ iDataCur = iIdxCur = iTabCur;
+ pOrderBy = 0;
+ pLimit = 0;
+ }
+#endif
+
+ /* Resolve the column names in the WHERE clause.
+ */
+ memset(&sNC, 0, sizeof(sNC));
+ sNC.pParse = pParse;
+ sNC.pSrcList = pTabList;
+ if( sqlite3ResolveExprNames(&sNC, pWhere) ){
+ goto delete_from_cleanup;
+ }
+
+ /* Initialize the counter of the number of rows deleted, if
+ ** we are counting rows.
+ */
+ if( (db->flags & SQLITE_CountRows)!=0
+ && !pParse->nested
+ && !pParse->pTriggerTab
+ ){
+ memCnt = ++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
+ }
+
+#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
+ /* Special case: A DELETE without a WHERE clause deletes everything.
+ ** It is easier just to erase the whole table. Prior to version 3.6.5,
+ ** this optimization caused the row change count (the value returned by
+ ** API function sqlite3_count_changes) to be set incorrectly.
+ **
+ ** The "rcauth==SQLITE_OK" terms is the
+ ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
+ ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
+ ** the truncate optimization is disabled and all rows are deleted
+ ** individually.
+ */
+ if( rcauth==SQLITE_OK
+ && pWhere==0
+ && !bComplex
+ && !IsVirtual(pTab)
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+ && db->xPreUpdateCallback==0
+#endif
+ ){
+ assert( !isView );
+ sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
+ if( HasRowid(pTab) ){
+ sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1,
+ pTab->zName, P4_STATIC);
+ }
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+ assert( pIdx->pSchema==pTab->pSchema );
+ sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
+ }
+ }else
+#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
+ {
+ u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK;
+ if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
+ wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
+ if( HasRowid(pTab) ){
+ /* For a rowid table, initialize the RowSet to an empty set */
+ pPk = 0;
+ nPk = 1;
+ iRowSet = ++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
+ }else{
+ /* For a WITHOUT ROWID table, create an ephemeral table used to
+ ** hold all primary keys for rows to be deleted. */
+ pPk = sqlite3PrimaryKeyIndex(pTab);
+ assert( pPk!=0 );
+ nPk = pPk->nKeyCol;
+ iPk = pParse->nMem+1;
+ pParse->nMem += nPk;
+ iEphCur = pParse->nTab++;
+ addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
+ sqlite3VdbeSetP4KeyInfo(pParse, pPk);
+ }
+
+ /* Construct a query to find the rowid or primary key for every row
+ ** to be deleted, based on the WHERE clause. Set variable eOnePass
+ ** to indicate the strategy used to implement this delete:
+ **
+ ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
+ ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
+ ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
+ */
+ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
+ if( pWInfo==0 ) goto delete_from_cleanup;
+ eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
+ assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
+ assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
+ if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse);
+ if( sqlite3WhereUsesDeferredSeek(pWInfo) ){
+ sqlite3VdbeAddOp1(v, OP_FinishSeek, iTabCur);
+ }
+
+ /* Keep track of the number of rows to be deleted */
+ if( memCnt ){
+ sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
+ }
+
+ /* Extract the rowid or primary key for the current row */
+ if( pPk ){
+ for(i=0; i<nPk; i++){
+ assert( pPk->aiColumn[i]>=0 );
+ sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
+ pPk->aiColumn[i], iPk+i);
+ }
+ iKey = iPk;
+ }else{
+ iKey = ++pParse->nMem;
+ sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey);
+ }
+
+ if( eOnePass!=ONEPASS_OFF ){
+ /* For ONEPASS, no need to store the rowid/primary-key. There is only
+ ** one, so just keep it in its register(s) and fall through to the
+ ** delete code. */
+ nKey = nPk; /* OP_Found will use an unpacked key */
+ aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
+ if( aToOpen==0 ){
+ sqlite3WhereEnd(pWInfo);
+ goto delete_from_cleanup;
+ }
+ memset(aToOpen, 1, nIdx+1);
+ aToOpen[nIdx+1] = 0;
+ if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
+ if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
+ if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
+ addrBypass = sqlite3VdbeMakeLabel(pParse);
+ }else{
+ if( pPk ){
+ /* Add the PK key for this row to the temporary table */
+ iKey = ++pParse->nMem;
+ nKey = 0; /* Zero tells OP_Found to use a composite key */
+ sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
+ sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
+ }else{
+ /* Add the rowid of the row to be deleted to the RowSet */
+ nKey = 1; /* OP_DeferredSeek always uses a single rowid */
+ sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
+ }
+ sqlite3WhereEnd(pWInfo);
+ }
+
+ /* Unless this is a view, open cursors for the table we are
+ ** deleting from and all its indices. If this is a view, then the
+ ** only effect this statement has is to fire the INSTEAD OF
+ ** triggers.
+ */
+ if( !isView ){
+ int iAddrOnce = 0;
+ if( eOnePass==ONEPASS_MULTI ){
+ iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
+ }
+ testcase( IsVirtual(pTab) );
+ sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
+ iTabCur, aToOpen, &iDataCur, &iIdxCur);
+ assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
+ assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
+ if( eOnePass==ONEPASS_MULTI ){
+ sqlite3VdbeJumpHereOrPopInst(v, iAddrOnce);
+ }
+ }
+
+ /* Set up a loop over the rowids/primary-keys that were found in the
+ ** where-clause loop above.
+ */
+ if( eOnePass!=ONEPASS_OFF ){
+ assert( nKey==nPk ); /* OP_Found will use an unpacked key */
+ if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
+ assert( pPk!=0 || pTab->pSelect!=0 );
+ sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
+ VdbeCoverage(v);
+ }
+ }else if( pPk ){
+ addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
+ if( IsVirtual(pTab) ){
+ sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
+ }
+ assert( nKey==0 ); /* OP_Found will use a composite key */
+ }else{
+ addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
+ VdbeCoverage(v);
+ assert( nKey==1 );
+ }
+
+ /* Delete the row */
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( IsVirtual(pTab) ){
+ const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
+ sqlite3VtabMakeWritable(pParse, pTab);
+ assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
+ sqlite3MayAbort(pParse);
+ if( eOnePass==ONEPASS_SINGLE ){
+ sqlite3VdbeAddOp1(v, OP_Close, iTabCur);
+ if( sqlite3IsToplevel(pParse) ){
+ pParse->isMultiWrite = 0;
+ }
+ }
+ sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
+ sqlite3VdbeChangeP5(v, OE_Abort);
+ }else
+#endif
+ {
+ int count = (pParse->nested==0); /* True to count changes */
+ sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
+ iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
+ }
+
+ /* End of the loop over all rowids/primary-keys. */
+ if( eOnePass!=ONEPASS_OFF ){
+ sqlite3VdbeResolveLabel(v, addrBypass);
+ sqlite3WhereEnd(pWInfo);
+ }else if( pPk ){
+ sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
+ sqlite3VdbeJumpHere(v, addrLoop);
+ }else{
+ sqlite3VdbeGoto(v, addrLoop);
+ sqlite3VdbeJumpHere(v, addrLoop);
+ }
+ } /* End non-truncate path */
+
+ /* Update the sqlite_sequence table by storing the content of the
+ ** maximum rowid counter values recorded while inserting into
+ ** autoincrement tables.
+ */
+ if( pParse->nested==0 && pParse->pTriggerTab==0 ){
+ sqlite3AutoincrementEnd(pParse);
+ }
+
+ /* Return the number of rows that were deleted. If this routine is
+ ** generating code because of a call to sqlite3NestedParse(), do not
+ ** invoke the callback function.
+ */
+ if( memCnt ){
+ sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
+ sqlite3VdbeSetNumCols(v, 1);
+ sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
+ }
+
+delete_from_cleanup:
+ sqlite3AuthContextPop(&sContext);
+ sqlite3SrcListDelete(db, pTabList);
+ sqlite3ExprDelete(db, pWhere);
+#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
+ sqlite3ExprListDelete(db, pOrderBy);
+ sqlite3ExprDelete(db, pLimit);
+#endif
+ sqlite3DbFree(db, aToOpen);
+ return;
+}
+/* Make sure "isView" and other macros defined above are undefined. Otherwise
+** they may interfere with compilation of other functions in this file
+** (or in another file, if this file becomes part of the amalgamation). */
+#ifdef isView
+ #undef isView
+#endif
+#ifdef pTrigger
+ #undef pTrigger
+#endif
+
+/*
+** This routine generates VDBE code that causes a single row of a
+** single table to be deleted. Both the original table entry and
+** all indices are removed.
+**
+** Preconditions:
+**
+** 1. iDataCur is an open cursor on the btree that is the canonical data
+** store for the table. (This will be either the table itself,
+** in the case of a rowid table, or the PRIMARY KEY index in the case
+** of a WITHOUT ROWID table.)
+**
+** 2. Read/write cursors for all indices of pTab must be open as
+** cursor number iIdxCur+i for the i-th index.
+**
+** 3. The primary key for the row to be deleted must be stored in a
+** sequence of nPk memory cells starting at iPk. If nPk==0 that means
+** that a search record formed from OP_MakeRecord is contained in the
+** single memory location iPk.
+**
+** eMode:
+** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
+** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
+** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
+** then this function must seek iDataCur to the entry identified by iPk
+** and nPk before reading from it.
+**
+** If eMode is ONEPASS_MULTI, then this call is being made as part
+** of a ONEPASS delete that affects multiple rows. In this case, if
+** iIdxNoSeek is a valid cursor number (>=0) and is not the same as
+** iDataCur, then its position should be preserved following the delete
+** operation. Or, if iIdxNoSeek is not a valid cursor number, the
+** position of iDataCur should be preserved instead.
+**
+** iIdxNoSeek:
+** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
+** then it identifies an index cursor (from within array of cursors
+** starting at iIdxCur) that already points to the index entry to be deleted.
+** Except, this optimization is disabled if there are BEFORE triggers since
+** the trigger body might have moved the cursor.
+*/
+SQLITE_PRIVATE void sqlite3GenerateRowDelete(
+ Parse *pParse, /* Parsing context */
+ Table *pTab, /* Table containing the row to be deleted */
+ Trigger *pTrigger, /* List of triggers to (potentially) fire */
+ int iDataCur, /* Cursor from which column data is extracted */
+ int iIdxCur, /* First index cursor */
+ int iPk, /* First memory cell containing the PRIMARY KEY */
+ i16 nPk, /* Number of PRIMARY KEY memory cells */
+ u8 count, /* If non-zero, increment the row change counter */
+ u8 onconf, /* Default ON CONFLICT policy for triggers */
+ u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
+ int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
+){
+ Vdbe *v = pParse->pVdbe; /* Vdbe */
+ int iOld = 0; /* First register in OLD.* array */
+ int iLabel; /* Label resolved to end of generated code */
+ u8 opSeek; /* Seek opcode */
+
+ /* Vdbe is guaranteed to have been allocated by this stage. */
+ assert( v );
+ VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
+ iDataCur, iIdxCur, iPk, (int)nPk));
+
+ /* Seek cursor iCur to the row to delete. If this row no longer exists
+ ** (this can happen if a trigger program has already deleted it), do
+ ** not attempt to delete it or fire any DELETE triggers. */
+ iLabel = sqlite3VdbeMakeLabel(pParse);
+ opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
+ if( eMode==ONEPASS_OFF ){
+ sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
+ VdbeCoverageIf(v, opSeek==OP_NotExists);
+ VdbeCoverageIf(v, opSeek==OP_NotFound);
+ }
+
+ /* If there are any triggers to fire, allocate a range of registers to
+ ** use for the old.* references in the triggers. */
+ if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
+ u32 mask; /* Mask of OLD.* columns in use */
+ int iCol; /* Iterator used while populating OLD.* */
+ int addrStart; /* Start of BEFORE trigger programs */
+
+ /* TODO: Could use temporary registers here. Also could attempt to
+ ** avoid copying the contents of the rowid register. */
+ mask = sqlite3TriggerColmask(
+ pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
+ );
+ mask |= sqlite3FkOldmask(pParse, pTab);
+ iOld = pParse->nMem+1;
+ pParse->nMem += (1 + pTab->nCol);
+
+ /* Populate the OLD.* pseudo-table register array. These values will be
+ ** used by any BEFORE and AFTER triggers that exist. */
+ sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
+ for(iCol=0; iCol<pTab->nCol; iCol++){
+ testcase( mask!=0xffffffff && iCol==31 );
+ testcase( mask!=0xffffffff && iCol==32 );
+ if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
+ int kk = sqlite3TableColumnToStorage(pTab, iCol);
+ sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+kk+1);
+ }
+ }
+
+ /* Invoke BEFORE DELETE trigger programs. */
+ addrStart = sqlite3VdbeCurrentAddr(v);
+ sqlite3CodeRowTrigger(pParse, pTrigger,
+ TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
+ );
+
+ /* If any BEFORE triggers were coded, then seek the cursor to the
+ ** row to be deleted again. It may be that the BEFORE triggers moved
+ ** the cursor or already deleted the row that the cursor was
+ ** pointing to.
+ **
+ ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
+ ** may have moved that cursor.
+ */
+ if( addrStart<sqlite3VdbeCurrentAddr(v) ){
+ sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
+ VdbeCoverageIf(v, opSeek==OP_NotExists);
+ VdbeCoverageIf(v, opSeek==OP_NotFound);
+ testcase( iIdxNoSeek>=0 );
+ iIdxNoSeek = -1;
+ }
+
+ /* Do FK processing. This call checks that any FK constraints that
+ ** refer to this table (i.e. constraints attached to other tables)
+ ** are not violated by deleting this row. */
+ sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
+ }
+
+ /* Delete the index and table entries. Skip this step if pTab is really
+ ** a view (in which case the only effect of the DELETE statement is to
+ ** fire the INSTEAD OF triggers).
+ **
+ ** If variable 'count' is non-zero, then this OP_Delete instruction should
+ ** invoke the update-hook. The pre-update-hook, on the other hand should
+ ** be invoked unless table pTab is a system table. The difference is that
+ ** the update-hook is not invoked for rows removed by REPLACE, but the
+ ** pre-update-hook is.
+ */
+ if( pTab->pSelect==0 ){
+ u8 p5 = 0;
+ sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
+ sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
+ if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
+ sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
+ }
+ if( eMode!=ONEPASS_OFF ){
+ sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
+ }
+ if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
+ sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
+ }
+ if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
+ sqlite3VdbeChangeP5(v, p5);
+ }
+
+ /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
+ ** handle rows (possibly in other tables) that refer via a foreign key
+ ** to the row just deleted. */
+ sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
+
+ /* Invoke AFTER DELETE trigger programs. */
+ sqlite3CodeRowTrigger(pParse, pTrigger,
+ TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
+ );
+
+ /* Jump here if the row had already been deleted before any BEFORE
+ ** trigger programs were invoked. Or if a trigger program throws a
+ ** RAISE(IGNORE) exception. */
+ sqlite3VdbeResolveLabel(v, iLabel);
+ VdbeModuleComment((v, "END: GenRowDel()"));
+}
+
+/*
+** This routine generates VDBE code that causes the deletion of all
+** index entries associated with a single row of a single table, pTab
+**
+** Preconditions:
+**
+** 1. A read/write cursor "iDataCur" must be open on the canonical storage
+** btree for the table pTab. (This will be either the table itself
+** for rowid tables or to the primary key index for WITHOUT ROWID
+** tables.)
+**
+** 2. Read/write cursors for all indices of pTab must be open as
+** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
+** index is the 0-th index.)
+**
+** 3. The "iDataCur" cursor must be already be positioned on the row
+** that is to be deleted.
+*/
+SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
+ Parse *pParse, /* Parsing and code generating context */
+ Table *pTab, /* Table containing the row to be deleted */
+ int iDataCur, /* Cursor of table holding data. */
+ int iIdxCur, /* First index cursor */
+ int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
+ int iIdxNoSeek /* Do not delete from this cursor */
+){
+ int i; /* Index loop counter */
+ int r1 = -1; /* Register holding an index key */
+ int iPartIdxLabel; /* Jump destination for skipping partial index entries */
+ Index *pIdx; /* Current index */
+ Index *pPrior = 0; /* Prior index */
+ Vdbe *v; /* The prepared statement under construction */
+ Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
+
+ v = pParse->pVdbe;
+ pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
+ for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
+ assert( iIdxCur+i!=iDataCur || pPk==pIdx );
+ if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
+ if( pIdx==pPk ) continue;
+ if( iIdxCur+i==iIdxNoSeek ) continue;
+ VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
+ r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
+ &iPartIdxLabel, pPrior, r1);
+ sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
+ pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
+ sqlite3VdbeChangeP5(v, 1); /* Cause IdxDelete to error if no entry found */
+ sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
+ pPrior = pIdx;
+ }
+}
+
+/*
+** Generate code that will assemble an index key and stores it in register
+** regOut. The key with be for index pIdx which is an index on pTab.
+** iCur is the index of a cursor open on the pTab table and pointing to
+** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
+** iCur must be the cursor of the PRIMARY KEY index.
+**
+** Return a register number which is the first in a block of
+** registers that holds the elements of the index key. The
+** block of registers has already been deallocated by the time
+** this routine returns.
+**
+** If *piPartIdxLabel is not NULL, fill it in with a label and jump
+** to that label if pIdx is a partial index that should be skipped.
+** The label should be resolved using sqlite3ResolvePartIdxLabel().
+** A partial index should be skipped if its WHERE clause evaluates
+** to false or null. If pIdx is not a partial index, *piPartIdxLabel
+** will be set to zero which is an empty label that is ignored by
+** sqlite3ResolvePartIdxLabel().
+**
+** The pPrior and regPrior parameters are used to implement a cache to
+** avoid unnecessary register loads. If pPrior is not NULL, then it is
+** a pointer to a different index for which an index key has just been
+** computed into register regPrior. If the current pIdx index is generating
+** its key into the same sequence of registers and if pPrior and pIdx share
+** a column in common, then the register corresponding to that column already
+** holds the correct value and the loading of that register is skipped.
+** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
+** on a table with multiple indices, and especially with the ROWID or
+** PRIMARY KEY columns of the index.
+*/
+SQLITE_PRIVATE int sqlite3GenerateIndexKey(
+ Parse *pParse, /* Parsing context */
+ Index *pIdx, /* The index for which to generate a key */
+ int iDataCur, /* Cursor number from which to take column data */
+ int regOut, /* Put the new key into this register if not 0 */
+ int prefixOnly, /* Compute only a unique prefix of the key */
+ int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
+ Index *pPrior, /* Previously generated index key */
+ int regPrior /* Register holding previous generated key */
+){
+ Vdbe *v = pParse->pVdbe;
+ int j;
+ int regBase;
+ int nCol;
+
+ if( piPartIdxLabel ){
+ if( pIdx->pPartIdxWhere ){
+ *piPartIdxLabel = sqlite3VdbeMakeLabel(pParse);
+ pParse->iSelfTab = iDataCur + 1;
+ sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
+ SQLITE_JUMPIFNULL);
+ pParse->iSelfTab = 0;
+ pPrior = 0; /* Ticket a9efb42811fa41ee 2019-11-02;
+ ** pPartIdxWhere may have corrupted regPrior registers */
+ }else{
+ *piPartIdxLabel = 0;
+ }
+ }
+ nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
+ regBase = sqlite3GetTempRange(pParse, nCol);
+ if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
+ for(j=0; j<nCol; j++){
+ if( pPrior
+ && pPrior->aiColumn[j]==pIdx->aiColumn[j]
+ && pPrior->aiColumn[j]!=XN_EXPR
+ ){
+ /* This column was already computed by the previous index */
+ continue;
+ }
+ sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
+ /* If the column affinity is REAL but the number is an integer, then it
+ ** might be stored in the table as an integer (using a compact
+ ** representation) then converted to REAL by an OP_RealAffinity opcode.
+ ** But we are getting ready to store this value back into an index, where
+ ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
+ ** opcode if it is present */
+ sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
+ }
+ if( regOut ){
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
+ if( pIdx->pTable->pSelect ){
+ const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
+ sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
+ }
+ }
+ sqlite3ReleaseTempRange(pParse, regBase, nCol);
+ return regBase;
+}
+
+/*
+** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
+** because it was a partial index, then this routine should be called to
+** resolve that label.
+*/
+SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
+ if( iLabel ){
+ sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
+ }
+}
+
+/************** End of delete.c **********************************************/
+/************** Begin file func.c ********************************************/
+/*
+** 2002 February 23
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains the C-language implementations for many of the SQL
+** functions of SQLite. (Some function, and in particular the date and
+** time functions, are implemented separately.)
+*/
+/* #include "sqliteInt.h" */
+/* #include <stdlib.h> */
+/* #include <assert.h> */
+#ifndef SQLITE_OMIT_FLOATING_POINT
+/* #include <math.h> */
+#endif
+/* #include "vdbeInt.h" */
+
+/*
+** Return the collating function associated with a function.
+*/
+static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
+ VdbeOp *pOp;
+ assert( context->pVdbe!=0 );
+ pOp = &context->pVdbe->aOp[context->iOp-1];
+ assert( pOp->opcode==OP_CollSeq );
+ assert( pOp->p4type==P4_COLLSEQ );
+ return pOp->p4.pColl;
+}
+
+/*
+** Indicate that the accumulator load should be skipped on this
+** iteration of the aggregate loop.
+*/
+static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
+ assert( context->isError<=0 );
+ context->isError = -1;
+ context->skipFlag = 1;
+}
+
+/*
+** Implementation of the non-aggregate min() and max() functions
+*/
+static void minmaxFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ int i;
+ int mask; /* 0 for min() or 0xffffffff for max() */
+ int iBest;
+ CollSeq *pColl;
+
+ assert( argc>1 );
+ mask = sqlite3_user_data(context)==0 ? 0 : -1;
+ pColl = sqlite3GetFuncCollSeq(context);
+ assert( pColl );
+ assert( mask==-1 || mask==0 );
+ iBest = 0;
+ if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
+ for(i=1; i<argc; i++){
+ if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
+ if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
+ testcase( mask==0 );
+ iBest = i;
+ }
+ }
+ sqlite3_result_value(context, argv[iBest]);
+}
+
+/*
+** Return the type of the argument.
+*/
+static void typeofFunc(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **argv
+){
+ static const char *azType[] = { "integer", "real", "text", "blob", "null" };
+ int i = sqlite3_value_type(argv[0]) - 1;
+ UNUSED_PARAMETER(NotUsed);
+ assert( i>=0 && i<ArraySize(azType) );
+ assert( SQLITE_INTEGER==1 );
+ assert( SQLITE_FLOAT==2 );
+ assert( SQLITE_TEXT==3 );
+ assert( SQLITE_BLOB==4 );
+ assert( SQLITE_NULL==5 );
+ /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
+ ** the datatype code for the initial datatype of the sqlite3_value object
+ ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
+ ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
+ sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
+}
+
+
+/*
+** Implementation of the length() function
+*/
+static void lengthFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ assert( argc==1 );
+ UNUSED_PARAMETER(argc);
+ switch( sqlite3_value_type(argv[0]) ){
+ case SQLITE_BLOB:
+ case SQLITE_INTEGER:
+ case SQLITE_FLOAT: {
+ sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
+ break;
+ }
+ case SQLITE_TEXT: {
+ const unsigned char *z = sqlite3_value_text(argv[0]);
+ const unsigned char *z0;
+ unsigned char c;
+ if( z==0 ) return;
+ z0 = z;
+ while( (c = *z)!=0 ){
+ z++;
+ if( c>=0xc0 ){
+ while( (*z & 0xc0)==0x80 ){ z++; z0++; }
+ }
+ }
+ sqlite3_result_int(context, (int)(z-z0));
+ break;
+ }
+ default: {
+ sqlite3_result_null(context);
+ break;
+ }
+ }
+}
+
+/*
+** Implementation of the abs() function.
+**
+** IMP: R-23979-26855 The abs(X) function returns the absolute value of
+** the numeric argument X.
+*/
+static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
+ assert( argc==1 );
+ UNUSED_PARAMETER(argc);
+ switch( sqlite3_value_type(argv[0]) ){
+ case SQLITE_INTEGER: {
+ i64 iVal = sqlite3_value_int64(argv[0]);
+ if( iVal<0 ){
+ if( iVal==SMALLEST_INT64 ){
+ /* IMP: R-31676-45509 If X is the integer -9223372036854775808
+ ** then abs(X) throws an integer overflow error since there is no
+ ** equivalent positive 64-bit two complement value. */
+ sqlite3_result_error(context, "integer overflow", -1);
+ return;
+ }
+ iVal = -iVal;
+ }
+ sqlite3_result_int64(context, iVal);
+ break;
+ }
+ case SQLITE_NULL: {
+ /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
+ sqlite3_result_null(context);
+ break;
+ }
+ default: {
+ /* Because sqlite3_value_double() returns 0.0 if the argument is not
+ ** something that can be converted into a number, we have:
+ ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
+ ** that cannot be converted to a numeric value.
+ */
+ double rVal = sqlite3_value_double(argv[0]);
+ if( rVal<0 ) rVal = -rVal;
+ sqlite3_result_double(context, rVal);
+ break;
+ }
+ }
+}
+
+/*
+** Implementation of the instr() function.
+**
+** instr(haystack,needle) finds the first occurrence of needle
+** in haystack and returns the number of previous characters plus 1,
+** or 0 if needle does not occur within haystack.
+**
+** If both haystack and needle are BLOBs, then the result is one more than
+** the number of bytes in haystack prior to the first occurrence of needle,
+** or 0 if needle never occurs in haystack.
+*/
+static void instrFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ const unsigned char *zHaystack;
+ const unsigned char *zNeedle;
+ int nHaystack;
+ int nNeedle;
+ int typeHaystack, typeNeedle;
+ int N = 1;
+ int isText;
+ unsigned char firstChar;
+ sqlite3_value *pC1 = 0;
+ sqlite3_value *pC2 = 0;
+
+ UNUSED_PARAMETER(argc);
+ typeHaystack = sqlite3_value_type(argv[0]);
+ typeNeedle = sqlite3_value_type(argv[1]);
+ if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
+ nHaystack = sqlite3_value_bytes(argv[0]);
+ nNeedle = sqlite3_value_bytes(argv[1]);
+ if( nNeedle>0 ){
+ if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
+ zHaystack = sqlite3_value_blob(argv[0]);
+ zNeedle = sqlite3_value_blob(argv[1]);
+ isText = 0;
+ }else if( typeHaystack!=SQLITE_BLOB && typeNeedle!=SQLITE_BLOB ){
+ zHaystack = sqlite3_value_text(argv[0]);
+ zNeedle = sqlite3_value_text(argv[1]);
+ isText = 1;
+ }else{
+ pC1 = sqlite3_value_dup(argv[0]);
+ zHaystack = sqlite3_value_text(pC1);
+ if( zHaystack==0 ) goto endInstrOOM;
+ nHaystack = sqlite3_value_bytes(pC1);
+ pC2 = sqlite3_value_dup(argv[1]);
+ zNeedle = sqlite3_value_text(pC2);
+ if( zNeedle==0 ) goto endInstrOOM;
+ nNeedle = sqlite3_value_bytes(pC2);
+ isText = 1;
+ }
+ if( zNeedle==0 || (nHaystack && zHaystack==0) ) goto endInstrOOM;
+ firstChar = zNeedle[0];
+ while( nNeedle<=nHaystack
+ && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0)
+ ){
+ N++;
+ do{
+ nHaystack--;
+ zHaystack++;
+ }while( isText && (zHaystack[0]&0xc0)==0x80 );
+ }
+ if( nNeedle>nHaystack ) N = 0;
+ }
+ sqlite3_result_int(context, N);
+endInstr:
+ sqlite3_value_free(pC1);
+ sqlite3_value_free(pC2);
+ return;
+endInstrOOM:
+ sqlite3_result_error_nomem(context);
+ goto endInstr;
+}
+
+/*
+** Implementation of the printf() function.
+*/
+static void printfFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ PrintfArguments x;
+ StrAccum str;
+ const char *zFormat;
+ int n;
+ sqlite3 *db = sqlite3_context_db_handle(context);
+
+ if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
+ x.nArg = argc-1;
+ x.nUsed = 0;
+ x.apArg = argv+1;
+ sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
+ str.printfFlags = SQLITE_PRINTF_SQLFUNC;
+ sqlite3_str_appendf(&str, zFormat, &x);
+ n = str.nChar;
+ sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
+ SQLITE_DYNAMIC);
+ }
+}
+
+/*
+** Implementation of the substr() function.
+**
+** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
+** p1 is 1-indexed. So substr(x,1,1) returns the first character
+** of x. If x is text, then we actually count UTF-8 characters.
+** If x is a blob, then we count bytes.
+**
+** If p1 is negative, then we begin abs(p1) from the end of x[].
+**
+** If p2 is negative, return the p2 characters preceding p1.
+*/
+static void substrFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ const unsigned char *z;
+ const unsigned char *z2;
+ int len;
+ int p0type;
+ i64 p1, p2;
+ int negP2 = 0;
+
+ assert( argc==3 || argc==2 );
+ if( sqlite3_value_type(argv[1])==SQLITE_NULL
+ || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
+ ){
+ return;
+ }
+ p0type = sqlite3_value_type(argv[0]);
+ p1 = sqlite3_value_int(argv[1]);
+ if( p0type==SQLITE_BLOB ){
+ len = sqlite3_value_bytes(argv[0]);
+ z = sqlite3_value_blob(argv[0]);
+ if( z==0 ) return;
+ assert( len==sqlite3_value_bytes(argv[0]) );
+ }else{
+ z = sqlite3_value_text(argv[0]);
+ if( z==0 ) return;
+ len = 0;
+ if( p1<0 ){
+ for(z2=z; *z2; len++){
+ SQLITE_SKIP_UTF8(z2);
+ }
+ }
+ }
+#ifdef SQLITE_SUBSTR_COMPATIBILITY
+ /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
+ ** as substr(X,1,N) - it returns the first N characters of X. This
+ ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
+ ** from 2009-02-02 for compatibility of applications that exploited the
+ ** old buggy behavior. */
+ if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
+#endif
+ if( argc==3 ){
+ p2 = sqlite3_value_int(argv[2]);
+ if( p2<0 ){
+ p2 = -p2;
+ negP2 = 1;
+ }
+ }else{
+ p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
+ }
+ if( p1<0 ){
+ p1 += len;
+ if( p1<0 ){
+ p2 += p1;
+ if( p2<0 ) p2 = 0;
+ p1 = 0;
+ }
+ }else if( p1>0 ){
+ p1--;
+ }else if( p2>0 ){
+ p2--;
+ }
+ if( negP2 ){
+ p1 -= p2;
+ if( p1<0 ){
+ p2 += p1;
+ p1 = 0;
+ }
+ }
+ assert( p1>=0 && p2>=0 );
+ if( p0type!=SQLITE_BLOB ){
+ while( *z && p1 ){
+ SQLITE_SKIP_UTF8(z);
+ p1--;
+ }
+ for(z2=z; *z2 && p2; p2--){
+ SQLITE_SKIP_UTF8(z2);
+ }
+ sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
+ SQLITE_UTF8);
+ }else{
+ if( p1+p2>len ){
+ p2 = len-p1;
+ if( p2<0 ) p2 = 0;
+ }
+ sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
+ }
+}
+
+/*
+** Implementation of the round() function
+*/
+#ifndef SQLITE_OMIT_FLOATING_POINT
+static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
+ int n = 0;
+ double r;
+ char *zBuf;
+ assert( argc==1 || argc==2 );
+ if( argc==2 ){
+ if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
+ n = sqlite3_value_int(argv[1]);
+ if( n>30 ) n = 30;
+ if( n<0 ) n = 0;
+ }
+ if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
+ r = sqlite3_value_double(argv[0]);
+ /* If Y==0 and X will fit in a 64-bit int,
+ ** handle the rounding directly,
+ ** otherwise use printf.
+ */
+ if( r<-4503599627370496.0 || r>+4503599627370496.0 ){
+ /* The value has no fractional part so there is nothing to round */
+ }else if( n==0 ){
+ r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5)));
+ }else{
+ zBuf = sqlite3_mprintf("%.*f",n,r);
+ if( zBuf==0 ){
+ sqlite3_result_error_nomem(context);
+ return;
+ }
+ sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
+ sqlite3_free(zBuf);
+ }
+ sqlite3_result_double(context, r);
+}
+#endif
+
+/*
+** Allocate nByte bytes of space using sqlite3Malloc(). If the
+** allocation fails, call sqlite3_result_error_nomem() to notify
+** the database handle that malloc() has failed and return NULL.
+** If nByte is larger than the maximum string or blob length, then
+** raise an SQLITE_TOOBIG exception and return NULL.
+*/
+static void *contextMalloc(sqlite3_context *context, i64 nByte){
+ char *z;
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ assert( nByte>0 );
+ testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
+ testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
+ if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
+ sqlite3_result_error_toobig(context);
+ z = 0;
+ }else{
+ z = sqlite3Malloc(nByte);
+ if( !z ){
+ sqlite3_result_error_nomem(context);
+ }
+ }
+ return z;
+}
+
+/*
+** Implementation of the upper() and lower() SQL functions.
+*/
+static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
+ char *z1;
+ const char *z2;
+ int i, n;
+ UNUSED_PARAMETER(argc);
+ z2 = (char*)sqlite3_value_text(argv[0]);
+ n = sqlite3_value_bytes(argv[0]);
+ /* Verify that the call to _bytes() does not invalidate the _text() pointer */
+ assert( z2==(char*)sqlite3_value_text(argv[0]) );
+ if( z2 ){
+ z1 = contextMalloc(context, ((i64)n)+1);
+ if( z1 ){
+ for(i=0; i<n; i++){
+ z1[i] = (char)sqlite3Toupper(z2[i]);
+ }
+ sqlite3_result_text(context, z1, n, sqlite3_free);
+ }
+ }
+}
+static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
+ char *z1;
+ const char *z2;
+ int i, n;
+ UNUSED_PARAMETER(argc);
+ z2 = (char*)sqlite3_value_text(argv[0]);
+ n = sqlite3_value_bytes(argv[0]);
+ /* Verify that the call to _bytes() does not invalidate the _text() pointer */
+ assert( z2==(char*)sqlite3_value_text(argv[0]) );
+ if( z2 ){
+ z1 = contextMalloc(context, ((i64)n)+1);
+ if( z1 ){
+ for(i=0; i<n; i++){
+ z1[i] = sqlite3Tolower(z2[i]);
+ }
+ sqlite3_result_text(context, z1, n, sqlite3_free);
+ }
+ }
+}
+
+/*
+** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
+** as VDBE code so that unused argument values do not have to be computed.
+** However, we still need some kind of function implementation for this
+** routines in the function table. The noopFunc macro provides this.
+** noopFunc will never be called so it doesn't matter what the implementation
+** is. We might as well use the "version()" function as a substitute.
+*/
+#define noopFunc versionFunc /* Substitute function - never called */
+
+/*
+** Implementation of random(). Return a random integer.
+*/
+static void randomFunc(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **NotUsed2
+){
+ sqlite_int64 r;
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ sqlite3_randomness(sizeof(r), &r);
+ if( r<0 ){
+ /* We need to prevent a random number of 0x8000000000000000
+ ** (or -9223372036854775808) since when you do abs() of that
+ ** number of you get the same value back again. To do this
+ ** in a way that is testable, mask the sign bit off of negative
+ ** values, resulting in a positive value. Then take the
+ ** 2s complement of that positive value. The end result can
+ ** therefore be no less than -9223372036854775807.
+ */
+ r = -(r & LARGEST_INT64);
+ }
+ sqlite3_result_int64(context, r);
+}
+
+/*
+** Implementation of randomblob(N). Return a random blob
+** that is N bytes long.
+*/
+static void randomBlob(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ sqlite3_int64 n;
+ unsigned char *p;
+ assert( argc==1 );
+ UNUSED_PARAMETER(argc);
+ n = sqlite3_value_int64(argv[0]);
+ if( n<1 ){
+ n = 1;
+ }
+ p = contextMalloc(context, n);
+ if( p ){
+ sqlite3_randomness(n, p);
+ sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
+ }
+}
+
+/*
+** Implementation of the last_insert_rowid() SQL function. The return
+** value is the same as the sqlite3_last_insert_rowid() API function.
+*/
+static void last_insert_rowid(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **NotUsed2
+){
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
+ ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
+ ** function. */
+ sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
+}
+
+/*
+** Implementation of the changes() SQL function.
+**
+** IMP: R-62073-11209 The changes() SQL function is a wrapper
+** around the sqlite3_changes() C/C++ function and hence follows the same
+** rules for counting changes.
+*/
+static void changes(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **NotUsed2
+){
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ sqlite3_result_int(context, sqlite3_changes(db));
+}
+
+/*
+** Implementation of the total_changes() SQL function. The return value is
+** the same as the sqlite3_total_changes() API function.
+*/
+static void total_changes(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **NotUsed2
+){
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ /* IMP: R-52756-41993 This function is a wrapper around the
+ ** sqlite3_total_changes() C/C++ interface. */
+ sqlite3_result_int(context, sqlite3_total_changes(db));
+}
+
+/*
+** A structure defining how to do GLOB-style comparisons.
+*/
+struct compareInfo {
+ u8 matchAll; /* "*" or "%" */
+ u8 matchOne; /* "?" or "_" */
+ u8 matchSet; /* "[" or 0 */
+ u8 noCase; /* true to ignore case differences */
+};
+
+/*
+** For LIKE and GLOB matching on EBCDIC machines, assume that every
+** character is exactly one byte in size. Also, provde the Utf8Read()
+** macro for fast reading of the next character in the common case where
+** the next character is ASCII.
+*/
+#if defined(SQLITE_EBCDIC)
+# define sqlite3Utf8Read(A) (*((*A)++))
+# define Utf8Read(A) (*(A++))
+#else
+# define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
+#endif
+
+static const struct compareInfo globInfo = { '*', '?', '[', 0 };
+/* The correct SQL-92 behavior is for the LIKE operator to ignore
+** case. Thus 'a' LIKE 'A' would be true. */
+static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
+/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
+** is case sensitive causing 'a' LIKE 'A' to be false */
+static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
+
+/*
+** Possible error returns from patternMatch()
+*/
+#define SQLITE_MATCH 0
+#define SQLITE_NOMATCH 1
+#define SQLITE_NOWILDCARDMATCH 2
+
+/*
+** Compare two UTF-8 strings for equality where the first string is
+** a GLOB or LIKE expression. Return values:
+**
+** SQLITE_MATCH: Match
+** SQLITE_NOMATCH: No match
+** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards.
+**
+** Globbing rules:
+**
+** '*' Matches any sequence of zero or more characters.
+**
+** '?' Matches exactly one character.
+**
+** [...] Matches one character from the enclosed list of
+** characters.
+**
+** [^...] Matches one character not in the enclosed list.
+**
+** With the [...] and [^...] matching, a ']' character can be included
+** in the list by making it the first character after '[' or '^'. A
+** range of characters can be specified using '-'. Example:
+** "[a-z]" matches any single lower-case letter. To match a '-', make
+** it the last character in the list.
+**
+** Like matching rules:
+**
+** '%' Matches any sequence of zero or more characters
+**
+*** '_' Matches any one character
+**
+** Ec Where E is the "esc" character and c is any other
+** character, including '%', '_', and esc, match exactly c.
+**
+** The comments within this routine usually assume glob matching.
+**
+** This routine is usually quick, but can be N**2 in the worst case.
+*/
+static int patternCompare(
+ const u8 *zPattern, /* The glob pattern */
+ const u8 *zString, /* The string to compare against the glob */
+ const struct compareInfo *pInfo, /* Information about how to do the compare */
+ u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
+){
+ u32 c, c2; /* Next pattern and input string chars */
+ u32 matchOne = pInfo->matchOne; /* "?" or "_" */
+ u32 matchAll = pInfo->matchAll; /* "*" or "%" */
+ u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
+ const u8 *zEscaped = 0; /* One past the last escaped input char */
+
+ while( (c = Utf8Read(zPattern))!=0 ){
+ if( c==matchAll ){ /* Match "*" */
+ /* Skip over multiple "*" characters in the pattern. If there
+ ** are also "?" characters, skip those as well, but consume a
+ ** single character of the input string for each "?" skipped */
+ while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
+ if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
+ return SQLITE_NOWILDCARDMATCH;
+ }
+ }
+ if( c==0 ){
+ return SQLITE_MATCH; /* "*" at the end of the pattern matches */
+ }else if( c==matchOther ){
+ if( pInfo->matchSet==0 ){
+ c = sqlite3Utf8Read(&zPattern);
+ if( c==0 ) return SQLITE_NOWILDCARDMATCH;
+ }else{
+ /* "[...]" immediately follows the "*". We have to do a slow
+ ** recursive search in this case, but it is an unusual case. */
+ assert( matchOther<0x80 ); /* '[' is a single-byte character */
+ while( *zString ){
+ int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
+ if( bMatch!=SQLITE_NOMATCH ) return bMatch;
+ SQLITE_SKIP_UTF8(zString);
+ }
+ return SQLITE_NOWILDCARDMATCH;
+ }
+ }
+
+ /* At this point variable c contains the first character of the
+ ** pattern string past the "*". Search in the input string for the
+ ** first matching character and recursively continue the match from
+ ** that point.
+ **
+ ** For a case-insensitive search, set variable cx to be the same as
+ ** c but in the other case and search the input string for either
+ ** c or cx.
+ */
+ if( c<=0x80 ){
+ char zStop[3];
+ int bMatch;
+ if( noCase ){
+ zStop[0] = sqlite3Toupper(c);
+ zStop[1] = sqlite3Tolower(c);
+ zStop[2] = 0;
+ }else{
+ zStop[0] = c;
+ zStop[1] = 0;
+ }
+ while(1){
+ zString += strcspn((const char*)zString, zStop);
+ if( zString[0]==0 ) break;
+ zString++;
+ bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
+ if( bMatch!=SQLITE_NOMATCH ) return bMatch;
+ }
+ }else{
+ int bMatch;
+ while( (c2 = Utf8Read(zString))!=0 ){
+ if( c2!=c ) continue;
+ bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
+ if( bMatch!=SQLITE_NOMATCH ) return bMatch;
+ }
+ }
+ return SQLITE_NOWILDCARDMATCH;
+ }
+ if( c==matchOther ){
+ if( pInfo->matchSet==0 ){
+ c = sqlite3Utf8Read(&zPattern);
+ if( c==0 ) return SQLITE_NOMATCH;
+ zEscaped = zPattern;
+ }else{
+ u32 prior_c = 0;
+ int seen = 0;
+ int invert = 0;
+ c = sqlite3Utf8Read(&zString);
+ if( c==0 ) return SQLITE_NOMATCH;
+ c2 = sqlite3Utf8Read(&zPattern);
+ if( c2=='^' ){
+ invert = 1;
+ c2 = sqlite3Utf8Read(&zPattern);
+ }
+ if( c2==']' ){
+ if( c==']' ) seen = 1;
+ c2 = sqlite3Utf8Read(&zPattern);
+ }
+ while( c2 && c2!=']' ){
+ if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
+ c2 = sqlite3Utf8Read(&zPattern);
+ if( c>=prior_c && c<=c2 ) seen = 1;
+ prior_c = 0;
+ }else{
+ if( c==c2 ){
+ seen = 1;
+ }
+ prior_c = c2;
+ }
+ c2 = sqlite3Utf8Read(&zPattern);
+ }
+ if( c2==0 || (seen ^ invert)==0 ){
+ return SQLITE_NOMATCH;
+ }
+ continue;
+ }
+ }
+ c2 = Utf8Read(zString);
+ if( c==c2 ) continue;
+ if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
+ continue;
+ }
+ if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
+ return SQLITE_NOMATCH;
+ }
+ return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
+}
+
+/*
+** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and
+** non-zero if there is no match.
+*/
+SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
+ return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
+}
+
+/*
+** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
+** a miss - like strcmp().
+*/
+SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
+ return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
+}
+
+/*
+** Count the number of times that the LIKE operator (or GLOB which is
+** just a variation of LIKE) gets called. This is used for testing
+** only.
+*/
+#ifdef SQLITE_TEST
+SQLITE_API int sqlite3_like_count = 0;
+#endif
+
+
+/*
+** Implementation of the like() SQL function. This function implements
+** the build-in LIKE operator. The first argument to the function is the
+** pattern and the second argument is the string. So, the SQL statements:
+**
+** A LIKE B
+**
+** is implemented as like(B,A).
+**
+** This same function (with a different compareInfo structure) computes
+** the GLOB operator.
+*/
+static void likeFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ const unsigned char *zA, *zB;
+ u32 escape;
+ int nPat;
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ struct compareInfo *pInfo = sqlite3_user_data(context);
+ struct compareInfo backupInfo;
+
+#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
+ if( sqlite3_value_type(argv[0])==SQLITE_BLOB
+ || sqlite3_value_type(argv[1])==SQLITE_BLOB
+ ){
+#ifdef SQLITE_TEST
+ sqlite3_like_count++;
+#endif
+ sqlite3_result_int(context, 0);
+ return;
+ }
+#endif
+
+ /* Limit the length of the LIKE or GLOB pattern to avoid problems
+ ** of deep recursion and N*N behavior in patternCompare().
+ */
+ nPat = sqlite3_value_bytes(argv[0]);
+ testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
+ testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
+ if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
+ sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
+ return;
+ }
+ if( argc==3 ){
+ /* The escape character string must consist of a single UTF-8 character.
+ ** Otherwise, return an error.
+ */
+ const unsigned char *zEsc = sqlite3_value_text(argv[2]);
+ if( zEsc==0 ) return;
+ if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
+ sqlite3_result_error(context,
+ "ESCAPE expression must be a single character", -1);
+ return;
+ }
+ escape = sqlite3Utf8Read(&zEsc);
+ if( escape==pInfo->matchAll || escape==pInfo->matchOne ){
+ memcpy(&backupInfo, pInfo, sizeof(backupInfo));
+ pInfo = &backupInfo;
+ if( escape==pInfo->matchAll ) pInfo->matchAll = 0;
+ if( escape==pInfo->matchOne ) pInfo->matchOne = 0;
+ }
+ }else{
+ escape = pInfo->matchSet;
+ }
+ zB = sqlite3_value_text(argv[0]);
+ zA = sqlite3_value_text(argv[1]);
+ if( zA && zB ){
+#ifdef SQLITE_TEST
+ sqlite3_like_count++;
+#endif
+ sqlite3_result_int(context,
+ patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
+ }
+}
+
+/*
+** Implementation of the NULLIF(x,y) function. The result is the first
+** argument if the arguments are different. The result is NULL if the
+** arguments are equal to each other.
+*/
+static void nullifFunc(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **argv
+){
+ CollSeq *pColl = sqlite3GetFuncCollSeq(context);
+ UNUSED_PARAMETER(NotUsed);
+ if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
+ sqlite3_result_value(context, argv[0]);
+ }
+}
+
+/*
+** Implementation of the sqlite_version() function. The result is the version
+** of the SQLite library that is running.
+*/
+static void versionFunc(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **NotUsed2
+){
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ /* IMP: R-48699-48617 This function is an SQL wrapper around the
+ ** sqlite3_libversion() C-interface. */
+ sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
+}
+
+/*
+** Implementation of the sqlite_source_id() function. The result is a string
+** that identifies the particular version of the source code used to build
+** SQLite.
+*/
+static void sourceidFunc(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **NotUsed2
+){
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ /* IMP: R-24470-31136 This function is an SQL wrapper around the
+ ** sqlite3_sourceid() C interface. */
+ sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
+}
+
+/*
+** Implementation of the sqlite_log() function. This is a wrapper around
+** sqlite3_log(). The return value is NULL. The function exists purely for
+** its side-effects.
+*/
+static void errlogFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ UNUSED_PARAMETER(argc);
+ UNUSED_PARAMETER(context);
+ sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
+}
+
+/*
+** Implementation of the sqlite_compileoption_used() function.
+** The result is an integer that identifies if the compiler option
+** was used to build SQLite.
+*/
+#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
+static void compileoptionusedFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ const char *zOptName;
+ assert( argc==1 );
+ UNUSED_PARAMETER(argc);
+ /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
+ ** function is a wrapper around the sqlite3_compileoption_used() C/C++
+ ** function.
+ */
+ if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
+ sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
+ }
+}
+#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
+
+/*
+** Implementation of the sqlite_compileoption_get() function.
+** The result is a string that identifies the compiler options
+** used to build SQLite.
+*/
+#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
+static void compileoptiongetFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ int n;
+ assert( argc==1 );
+ UNUSED_PARAMETER(argc);
+ /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
+ ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
+ */
+ n = sqlite3_value_int(argv[0]);
+ sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
+}
+#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
+
+/* Array for converting from half-bytes (nybbles) into ASCII hex
+** digits. */
+static const char hexdigits[] = {
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
+};
+
+/*
+** Implementation of the QUOTE() function. This function takes a single
+** argument. If the argument is numeric, the return value is the same as
+** the argument. If the argument is NULL, the return value is the string
+** "NULL". Otherwise, the argument is enclosed in single quotes with
+** single-quote escapes.
+*/
+static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
+ assert( argc==1 );
+ UNUSED_PARAMETER(argc);
+ switch( sqlite3_value_type(argv[0]) ){
+ case SQLITE_FLOAT: {
+ double r1, r2;
+ char zBuf[50];
+ r1 = sqlite3_value_double(argv[0]);
+ sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
+ sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
+ if( r1!=r2 ){
+ sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
+ }
+ sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
+ break;
+ }
+ case SQLITE_INTEGER: {
+ sqlite3_result_value(context, argv[0]);
+ break;
+ }
+ case SQLITE_BLOB: {
+ char *zText = 0;
+ char const *zBlob = sqlite3_value_blob(argv[0]);
+ int nBlob = sqlite3_value_bytes(argv[0]);
+ assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
+ zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
+ if( zText ){
+ int i;
+ for(i=0; i<nBlob; i++){
+ zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
+ zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
+ }
+ zText[(nBlob*2)+2] = '\'';
+ zText[(nBlob*2)+3] = '\0';
+ zText[0] = 'X';
+ zText[1] = '\'';
+ sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
+ sqlite3_free(zText);
+ }
+ break;
+ }
+ case SQLITE_TEXT: {
+ int i,j;
+ u64 n;
+ const unsigned char *zArg = sqlite3_value_text(argv[0]);
+ char *z;
+
+ if( zArg==0 ) return;
+ for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
+ z = contextMalloc(context, ((i64)i)+((i64)n)+3);
+ if( z ){
+ z[0] = '\'';
+ for(i=0, j=1; zArg[i]; i++){
+ z[j++] = zArg[i];
+ if( zArg[i]=='\'' ){
+ z[j++] = '\'';
+ }
+ }
+ z[j++] = '\'';
+ z[j] = 0;
+ sqlite3_result_text(context, z, j, sqlite3_free);
+ }
+ break;
+ }
+ default: {
+ assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
+ sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
+ break;
+ }
+ }
+}
+
+/*
+** The unicode() function. Return the integer unicode code-point value
+** for the first character of the input string.
+*/
+static void unicodeFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ const unsigned char *z = sqlite3_value_text(argv[0]);
+ (void)argc;
+ if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
+}
+
+/*
+** The char() function takes zero or more arguments, each of which is
+** an integer. It constructs a string where each character of the string
+** is the unicode character for the corresponding integer argument.
+*/
+static void charFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ unsigned char *z, *zOut;
+ int i;
+ zOut = z = sqlite3_malloc64( argc*4+1 );
+ if( z==0 ){
+ sqlite3_result_error_nomem(context);
+ return;
+ }
+ for(i=0; i<argc; i++){
+ sqlite3_int64 x;
+ unsigned c;
+ x = sqlite3_value_int64(argv[i]);
+ if( x<0 || x>0x10ffff ) x = 0xfffd;
+ c = (unsigned)(x & 0x1fffff);
+ if( c<0x00080 ){
+ *zOut++ = (u8)(c&0xFF);
+ }else if( c<0x00800 ){
+ *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
+ *zOut++ = 0x80 + (u8)(c & 0x3F);
+ }else if( c<0x10000 ){
+ *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
+ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
+ *zOut++ = 0x80 + (u8)(c & 0x3F);
+ }else{
+ *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
+ *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
+ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
+ *zOut++ = 0x80 + (u8)(c & 0x3F);
+ } \
+ }
+ sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
+}
+
+/*
+** The hex() function. Interpret the argument as a blob. Return
+** a hexadecimal rendering as text.
+*/
+static void hexFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ int i, n;
+ const unsigned char *pBlob;
+ char *zHex, *z;
+ assert( argc==1 );
+ UNUSED_PARAMETER(argc);
+ pBlob = sqlite3_value_blob(argv[0]);
+ n = sqlite3_value_bytes(argv[0]);
+ assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
+ z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
+ if( zHex ){
+ for(i=0; i<n; i++, pBlob++){
+ unsigned char c = *pBlob;
+ *(z++) = hexdigits[(c>>4)&0xf];
+ *(z++) = hexdigits[c&0xf];
+ }
+ *z = 0;
+ sqlite3_result_text(context, zHex, n*2, sqlite3_free);
+ }
+}
+
+/*
+** The zeroblob(N) function returns a zero-filled blob of size N bytes.
+*/
+static void zeroblobFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ i64 n;
+ int rc;
+ assert( argc==1 );
+ UNUSED_PARAMETER(argc);
+ n = sqlite3_value_int64(argv[0]);
+ if( n<0 ) n = 0;
+ rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
+ if( rc ){
+ sqlite3_result_error_code(context, rc);
+ }
+}
+
+/*
+** The replace() function. Three arguments are all strings: call
+** them A, B, and C. The result is also a string which is derived
+** from A by replacing every occurrence of B with C. The match
+** must be exact. Collating sequences are not used.
+*/
+static void replaceFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ const unsigned char *zStr; /* The input string A */
+ const unsigned char *zPattern; /* The pattern string B */
+ const unsigned char *zRep; /* The replacement string C */
+ unsigned char *zOut; /* The output */
+ int nStr; /* Size of zStr */
+ int nPattern; /* Size of zPattern */
+ int nRep; /* Size of zRep */
+ i64 nOut; /* Maximum size of zOut */
+ int loopLimit; /* Last zStr[] that might match zPattern[] */
+ int i, j; /* Loop counters */
+ unsigned cntExpand; /* Number zOut expansions */
+ sqlite3 *db = sqlite3_context_db_handle(context);
+
+ assert( argc==3 );
+ UNUSED_PARAMETER(argc);
+ zStr = sqlite3_value_text(argv[0]);
+ if( zStr==0 ) return;
+ nStr = sqlite3_value_bytes(argv[0]);
+ assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
+ zPattern = sqlite3_value_text(argv[1]);
+ if( zPattern==0 ){
+ assert( sqlite3_value_type(argv[1])==SQLITE_NULL
+ || sqlite3_context_db_handle(context)->mallocFailed );
+ return;
+ }
+ if( zPattern[0]==0 ){
+ assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
+ sqlite3_result_value(context, argv[0]);
+ return;
+ }
+ nPattern = sqlite3_value_bytes(argv[1]);
+ assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
+ zRep = sqlite3_value_text(argv[2]);
+ if( zRep==0 ) return;
+ nRep = sqlite3_value_bytes(argv[2]);
+ assert( zRep==sqlite3_value_text(argv[2]) );
+ nOut = nStr + 1;
+ assert( nOut<SQLITE_MAX_LENGTH );
+ zOut = contextMalloc(context, (i64)nOut);
+ if( zOut==0 ){
+ return;
+ }
+ loopLimit = nStr - nPattern;
+ cntExpand = 0;
+ for(i=j=0; i<=loopLimit; i++){
+ if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
+ zOut[j++] = zStr[i];
+ }else{
+ if( nRep>nPattern ){
+ nOut += nRep - nPattern;
+ testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
+ testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
+ if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
+ sqlite3_result_error_toobig(context);
+ sqlite3_free(zOut);
+ return;
+ }
+ cntExpand++;
+ if( (cntExpand&(cntExpand-1))==0 ){
+ /* Grow the size of the output buffer only on substitutions
+ ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */
+ u8 *zOld;
+ zOld = zOut;
+ zOut = sqlite3Realloc(zOut, (int)nOut + (nOut - nStr - 1));
+ if( zOut==0 ){
+ sqlite3_result_error_nomem(context);
+ sqlite3_free(zOld);
+ return;
+ }
+ }
+ }
+ memcpy(&zOut[j], zRep, nRep);
+ j += nRep;
+ i += nPattern-1;
+ }
+ }
+ assert( j+nStr-i+1<=nOut );
+ memcpy(&zOut[j], &zStr[i], nStr-i);
+ j += nStr - i;
+ assert( j<=nOut );
+ zOut[j] = 0;
+ sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
+}
+
+/*
+** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
+** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
+*/
+static void trimFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ const unsigned char *zIn; /* Input string */
+ const unsigned char *zCharSet; /* Set of characters to trim */
+ int nIn; /* Number of bytes in input */
+ int flags; /* 1: trimleft 2: trimright 3: trim */
+ int i; /* Loop counter */
+ unsigned char *aLen = 0; /* Length of each character in zCharSet */
+ unsigned char **azChar = 0; /* Individual characters in zCharSet */
+ int nChar; /* Number of characters in zCharSet */
+
+ if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
+ return;
+ }
+ zIn = sqlite3_value_text(argv[0]);
+ if( zIn==0 ) return;
+ nIn = sqlite3_value_bytes(argv[0]);
+ assert( zIn==sqlite3_value_text(argv[0]) );
+ if( argc==1 ){
+ static const unsigned char lenOne[] = { 1 };
+ static unsigned char * const azOne[] = { (u8*)" " };
+ nChar = 1;
+ aLen = (u8*)lenOne;
+ azChar = (unsigned char **)azOne;
+ zCharSet = 0;
+ }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
+ return;
+ }else{
+ const unsigned char *z;
+ for(z=zCharSet, nChar=0; *z; nChar++){
+ SQLITE_SKIP_UTF8(z);
+ }
+ if( nChar>0 ){
+ azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
+ if( azChar==0 ){
+ return;
+ }
+ aLen = (unsigned char*)&azChar[nChar];
+ for(z=zCharSet, nChar=0; *z; nChar++){
+ azChar[nChar] = (unsigned char *)z;
+ SQLITE_SKIP_UTF8(z);
+ aLen[nChar] = (u8)(z - azChar[nChar]);
+ }
+ }
+ }
+ if( nChar>0 ){
+ flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
+ if( flags & 1 ){
+ while( nIn>0 ){
+ int len = 0;
+ for(i=0; i<nChar; i++){
+ len = aLen[i];
+ if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
+ }
+ if( i>=nChar ) break;
+ zIn += len;
+ nIn -= len;
+ }
+ }
+ if( flags & 2 ){
+ while( nIn>0 ){
+ int len = 0;
+ for(i=0; i<nChar; i++){
+ len = aLen[i];
+ if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
+ }
+ if( i>=nChar ) break;
+ nIn -= len;
+ }
+ }
+ if( zCharSet ){
+ sqlite3_free(azChar);
+ }
+ }
+ sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
+}
+
+
+#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
+/*
+** The "unknown" function is automatically substituted in place of
+** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
+** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
+** When the "sqlite3" command-line shell is built using this functionality,
+** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
+** involving application-defined functions to be examined in a generic
+** sqlite3 shell.
+*/
+static void unknownFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ /* no-op */
+}
+#endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
+
+
+/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
+** is only available if the SQLITE_SOUNDEX compile-time option is used
+** when SQLite is built.
+*/
+#ifdef SQLITE_SOUNDEX
+/*
+** Compute the soundex encoding of a word.
+**
+** IMP: R-59782-00072 The soundex(X) function returns a string that is the
+** soundex encoding of the string X.
+*/
+static void soundexFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ char zResult[8];
+ const u8 *zIn;
+ int i, j;
+ static const unsigned char iCode[] = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
+ 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
+ 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
+ 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
+ };
+ assert( argc==1 );
+ zIn = (u8*)sqlite3_value_text(argv[0]);
+ if( zIn==0 ) zIn = (u8*)"";
+ for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
+ if( zIn[i] ){
+ u8 prevcode = iCode[zIn[i]&0x7f];
+ zResult[0] = sqlite3Toupper(zIn[i]);
+ for(j=1; j<4 && zIn[i]; i++){
+ int code = iCode[zIn[i]&0x7f];
+ if( code>0 ){
+ if( code!=prevcode ){
+ prevcode = code;
+ zResult[j++] = code + '0';
+ }
+ }else{
+ prevcode = 0;
+ }
+ }
+ while( j<4 ){
+ zResult[j++] = '0';
+ }
+ zResult[j] = 0;
+ sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
+ }else{
+ /* IMP: R-64894-50321 The string "?000" is returned if the argument
+ ** is NULL or contains no ASCII alphabetic characters. */
+ sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
+ }
+}
+#endif /* SQLITE_SOUNDEX */
+
+#ifndef SQLITE_OMIT_LOAD_EXTENSION
+/*
+** A function that loads a shared-library extension then returns NULL.
+*/
+static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
+ const char *zFile = (const char *)sqlite3_value_text(argv[0]);
+ const char *zProc;
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ char *zErrMsg = 0;
+
+ /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
+ ** flag is set. See the sqlite3_enable_load_extension() API.
+ */
+ if( (db->flags & SQLITE_LoadExtFunc)==0 ){
+ sqlite3_result_error(context, "not authorized", -1);
+ return;
+ }
+
+ if( argc==2 ){
+ zProc = (const char *)sqlite3_value_text(argv[1]);
+ }else{
+ zProc = 0;
+ }
+ if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
+ sqlite3_result_error(context, zErrMsg, -1);
+ sqlite3_free(zErrMsg);
+ }
+}
+#endif
+
+
+/*
+** An instance of the following structure holds the context of a
+** sum() or avg() aggregate computation.
+*/
+typedef struct SumCtx SumCtx;
+struct SumCtx {
+ double rSum; /* Floating point sum */
+ i64 iSum; /* Integer sum */
+ i64 cnt; /* Number of elements summed */
+ u8 overflow; /* True if integer overflow seen */
+ u8 approx; /* True if non-integer value was input to the sum */
+};
+
+/*
+** Routines used to compute the sum, average, and total.
+**
+** The SUM() function follows the (broken) SQL standard which means
+** that it returns NULL if it sums over no inputs. TOTAL returns
+** 0.0 in that case. In addition, TOTAL always returns a float where
+** SUM might return an integer if it never encounters a floating point
+** value. TOTAL never fails, but SUM might through an exception if
+** it overflows an integer.
+*/
+static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
+ SumCtx *p;
+ int type;
+ assert( argc==1 );
+ UNUSED_PARAMETER(argc);
+ p = sqlite3_aggregate_context(context, sizeof(*p));
+ type = sqlite3_value_numeric_type(argv[0]);
+ if( p && type!=SQLITE_NULL ){
+ p->cnt++;
+ if( type==SQLITE_INTEGER ){
+ i64 v = sqlite3_value_int64(argv[0]);
+ p->rSum += v;
+ if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
+ p->approx = p->overflow = 1;
+ }
+ }else{
+ p->rSum += sqlite3_value_double(argv[0]);
+ p->approx = 1;
+ }
+ }
+}
+#ifndef SQLITE_OMIT_WINDOWFUNC
+static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){
+ SumCtx *p;
+ int type;
+ assert( argc==1 );
+ UNUSED_PARAMETER(argc);
+ p = sqlite3_aggregate_context(context, sizeof(*p));
+ type = sqlite3_value_numeric_type(argv[0]);
+ /* p is always non-NULL because sumStep() will have been called first
+ ** to initialize it */
+ if( ALWAYS(p) && type!=SQLITE_NULL ){
+ assert( p->cnt>0 );
+ p->cnt--;
+ assert( type==SQLITE_INTEGER || p->approx );
+ if( type==SQLITE_INTEGER && p->approx==0 ){
+ i64 v = sqlite3_value_int64(argv[0]);
+ p->rSum -= v;
+ p->iSum -= v;
+ }else{
+ p->rSum -= sqlite3_value_double(argv[0]);
+ }
+ }
+}
+#else
+# define sumInverse 0
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+static void sumFinalize(sqlite3_context *context){
+ SumCtx *p;
+ p = sqlite3_aggregate_context(context, 0);
+ if( p && p->cnt>0 ){
+ if( p->overflow ){
+ sqlite3_result_error(context,"integer overflow",-1);
+ }else if( p->approx ){
+ sqlite3_result_double(context, p->rSum);
+ }else{
+ sqlite3_result_int64(context, p->iSum);
+ }
+ }
+}
+static void avgFinalize(sqlite3_context *context){
+ SumCtx *p;
+ p = sqlite3_aggregate_context(context, 0);
+ if( p && p->cnt>0 ){
+ sqlite3_result_double(context, p->rSum/(double)p->cnt);
+ }
+}
+static void totalFinalize(sqlite3_context *context){
+ SumCtx *p;
+ p = sqlite3_aggregate_context(context, 0);
+ /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
+ sqlite3_result_double(context, p ? p->rSum : (double)0);
+}
+
+/*
+** The following structure keeps track of state information for the
+** count() aggregate function.
+*/
+typedef struct CountCtx CountCtx;
+struct CountCtx {
+ i64 n;
+#ifdef SQLITE_DEBUG
+ int bInverse; /* True if xInverse() ever called */
+#endif
+};
+
+/*
+** Routines to implement the count() aggregate function.
+*/
+static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
+ CountCtx *p;
+ p = sqlite3_aggregate_context(context, sizeof(*p));
+ if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
+ p->n++;
+ }
+
+#ifndef SQLITE_OMIT_DEPRECATED
+ /* The sqlite3_aggregate_count() function is deprecated. But just to make
+ ** sure it still operates correctly, verify that its count agrees with our
+ ** internal count when using count(*) and when the total count can be
+ ** expressed as a 32-bit integer. */
+ assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse
+ || p->n==sqlite3_aggregate_count(context) );
+#endif
+}
+static void countFinalize(sqlite3_context *context){
+ CountCtx *p;
+ p = sqlite3_aggregate_context(context, 0);
+ sqlite3_result_int64(context, p ? p->n : 0);
+}
+#ifndef SQLITE_OMIT_WINDOWFUNC
+static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){
+ CountCtx *p;
+ p = sqlite3_aggregate_context(ctx, sizeof(*p));
+ /* p is always non-NULL since countStep() will have been called first */
+ if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){
+ p->n--;
+#ifdef SQLITE_DEBUG
+ p->bInverse = 1;
+#endif
+ }
+}
+#else
+# define countInverse 0
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+
+/*
+** Routines to implement min() and max() aggregate functions.
+*/
+static void minmaxStep(
+ sqlite3_context *context,
+ int NotUsed,
+ sqlite3_value **argv
+){
+ Mem *pArg = (Mem *)argv[0];
+ Mem *pBest;
+ UNUSED_PARAMETER(NotUsed);
+
+ pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
+ if( !pBest ) return;
+
+ if( sqlite3_value_type(pArg)==SQLITE_NULL ){
+ if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
+ }else if( pBest->flags ){
+ int max;
+ int cmp;
+ CollSeq *pColl = sqlite3GetFuncCollSeq(context);
+ /* This step function is used for both the min() and max() aggregates,
+ ** the only difference between the two being that the sense of the
+ ** comparison is inverted. For the max() aggregate, the
+ ** sqlite3_user_data() function returns (void *)-1. For min() it
+ ** returns (void *)db, where db is the sqlite3* database pointer.
+ ** Therefore the next statement sets variable 'max' to 1 for the max()
+ ** aggregate, or 0 for min().
+ */
+ max = sqlite3_user_data(context)!=0;
+ cmp = sqlite3MemCompare(pBest, pArg, pColl);
+ if( (max && cmp<0) || (!max && cmp>0) ){
+ sqlite3VdbeMemCopy(pBest, pArg);
+ }else{
+ sqlite3SkipAccumulatorLoad(context);
+ }
+ }else{
+ pBest->db = sqlite3_context_db_handle(context);
+ sqlite3VdbeMemCopy(pBest, pArg);
+ }
+}
+static void minMaxValueFinalize(sqlite3_context *context, int bValue){
+ sqlite3_value *pRes;
+ pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
+ if( pRes ){
+ if( pRes->flags ){
+ sqlite3_result_value(context, pRes);
+ }
+ if( bValue==0 ) sqlite3VdbeMemRelease(pRes);
+ }
+}
+#ifndef SQLITE_OMIT_WINDOWFUNC
+static void minMaxValue(sqlite3_context *context){
+ minMaxValueFinalize(context, 1);
+}
+#else
+# define minMaxValue 0
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+static void minMaxFinalize(sqlite3_context *context){
+ minMaxValueFinalize(context, 0);
+}
+
+/*
+** group_concat(EXPR, ?SEPARATOR?)
+*/
+static void groupConcatStep(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ const char *zVal;
+ StrAccum *pAccum;
+ const char *zSep;
+ int nVal, nSep;
+ assert( argc==1 || argc==2 );
+ if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
+ pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
+
+ if( pAccum ){
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ int firstTerm = pAccum->mxAlloc==0;
+ pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
+ if( !firstTerm ){
+ if( argc==2 ){
+ zSep = (char*)sqlite3_value_text(argv[1]);
+ nSep = sqlite3_value_bytes(argv[1]);
+ }else{
+ zSep = ",";
+ nSep = 1;
+ }
+ if( zSep ) sqlite3_str_append(pAccum, zSep, nSep);
+ }
+ zVal = (char*)sqlite3_value_text(argv[0]);
+ nVal = sqlite3_value_bytes(argv[0]);
+ if( zVal ) sqlite3_str_append(pAccum, zVal, nVal);
+ }
+}
+#ifndef SQLITE_OMIT_WINDOWFUNC
+static void groupConcatInverse(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ int n;
+ StrAccum *pAccum;
+ assert( argc==1 || argc==2 );
+ if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
+ pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
+ /* pAccum is always non-NULL since groupConcatStep() will have always
+ ** run frist to initialize it */
+ if( ALWAYS(pAccum) ){
+ n = sqlite3_value_bytes(argv[0]);
+ if( argc==2 ){
+ n += sqlite3_value_bytes(argv[1]);
+ }else{
+ n++;
+ }
+ if( n>=(int)pAccum->nChar ){
+ pAccum->nChar = 0;
+ }else{
+ pAccum->nChar -= n;
+ memmove(pAccum->zText, &pAccum->zText[n], pAccum->nChar);
+ }
+ if( pAccum->nChar==0 ) pAccum->mxAlloc = 0;
+ }
+}
+#else
+# define groupConcatInverse 0
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+static void groupConcatFinalize(sqlite3_context *context){
+ StrAccum *pAccum;
+ pAccum = sqlite3_aggregate_context(context, 0);
+ if( pAccum ){
+ if( pAccum->accError==SQLITE_TOOBIG ){
+ sqlite3_result_error_toobig(context);
+ }else if( pAccum->accError==SQLITE_NOMEM ){
+ sqlite3_result_error_nomem(context);
+ }else{
+ sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
+ sqlite3_free);
+ }
+ }
+}
+#ifndef SQLITE_OMIT_WINDOWFUNC
+static void groupConcatValue(sqlite3_context *context){
+ sqlite3_str *pAccum;
+ pAccum = (sqlite3_str*)sqlite3_aggregate_context(context, 0);
+ if( pAccum ){
+ if( pAccum->accError==SQLITE_TOOBIG ){
+ sqlite3_result_error_toobig(context);
+ }else if( pAccum->accError==SQLITE_NOMEM ){
+ sqlite3_result_error_nomem(context);
+ }else{
+ const char *zText = sqlite3_str_value(pAccum);
+ sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
+ }
+ }
+}
+#else
+# define groupConcatValue 0
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+
+/*
+** This routine does per-connection function registration. Most
+** of the built-in functions above are part of the global function set.
+** This routine only deals with those that are not global.
+*/
+SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
+ int rc = sqlite3_overload_function(db, "MATCH", 2);
+ assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
+ if( rc==SQLITE_NOMEM ){
+ sqlite3OomFault(db);
+ }
+}
+
+/*
+** Re-register the built-in LIKE functions. The caseSensitive
+** parameter determines whether or not the LIKE operator is case
+** sensitive.
+*/
+SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
+ struct compareInfo *pInfo;
+ int flags;
+ if( caseSensitive ){
+ pInfo = (struct compareInfo*)&likeInfoAlt;
+ flags = SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE;
+ }else{
+ pInfo = (struct compareInfo*)&likeInfoNorm;
+ flags = SQLITE_FUNC_LIKE;
+ }
+ sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
+ sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
+ sqlite3FindFunction(db, "like", 2, SQLITE_UTF8, 0)->funcFlags |= flags;
+ sqlite3FindFunction(db, "like", 3, SQLITE_UTF8, 0)->funcFlags |= flags;
+}
+
+/*
+** pExpr points to an expression which implements a function. If
+** it is appropriate to apply the LIKE optimization to that function
+** then set aWc[0] through aWc[2] to the wildcard characters and the
+** escape character and then return TRUE. If the function is not a
+** LIKE-style function then return FALSE.
+**
+** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
+** operator if c is a string literal that is exactly one byte in length.
+** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is
+** no ESCAPE clause.
+**
+** *pIsNocase is set to true if uppercase and lowercase are equivalent for
+** the function (default for LIKE). If the function makes the distinction
+** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
+** false.
+*/
+SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
+ FuncDef *pDef;
+ int nExpr;
+ if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){
+ return 0;
+ }
+ assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
+ nExpr = pExpr->x.pList->nExpr;
+ pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
+#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
+ if( pDef==0 ) return 0;
+#endif
+ if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
+ return 0;
+ }
+
+ /* The memcpy() statement assumes that the wildcard characters are
+ ** the first three statements in the compareInfo structure. The
+ ** asserts() that follow verify that assumption
+ */
+ memcpy(aWc, pDef->pUserData, 3);
+ assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
+ assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
+ assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
+
+ if( nExpr<3 ){
+ aWc[3] = 0;
+ }else{
+ Expr *pEscape = pExpr->x.pList->a[2].pExpr;
+ char *zEscape;
+ if( pEscape->op!=TK_STRING ) return 0;
+ zEscape = pEscape->u.zToken;
+ if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
+ if( zEscape[0]==aWc[0] ) return 0;
+ if( zEscape[0]==aWc[1] ) return 0;
+ aWc[3] = zEscape[0];
+ }
+
+ *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
+ return 1;
+}
+
+/*
+** All of the FuncDef structures in the aBuiltinFunc[] array above
+** to the global function hash table. This occurs at start-time (as
+** a consequence of calling sqlite3_initialize()).
+**
+** After this routine runs
+*/
+SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
+ /*
+ ** The following array holds FuncDef structures for all of the functions
+ ** defined in this file.
+ **
+ ** The array cannot be constant since changes are made to the
+ ** FuncDef.pHash elements at start-time. The elements of this array
+ ** are read-only after initialization is complete.
+ **
+ ** For peak efficiency, put the most frequently used function last.
+ */
+ static FuncDef aBuiltinFunc[] = {
+/***** Functions only available with SQLITE_TESTCTRL_INTERNAL_FUNCTIONS *****/
+ TEST_FUNC(implies_nonnull_row, 2, INLINEFUNC_implies_nonnull_row, 0),
+ TEST_FUNC(expr_compare, 2, INLINEFUNC_expr_compare, 0),
+ TEST_FUNC(expr_implies_expr, 2, INLINEFUNC_expr_implies_expr, 0),
+#ifdef SQLITE_DEBUG
+ TEST_FUNC(affinity, 1, INLINEFUNC_affinity, 0),
+#endif
+/***** Regular functions *****/
+#ifdef SQLITE_SOUNDEX
+ FUNCTION(soundex, 1, 0, 0, soundexFunc ),
+#endif
+#ifndef SQLITE_OMIT_LOAD_EXTENSION
+ SFUNCTION(load_extension, 1, 0, 0, loadExt ),
+ SFUNCTION(load_extension, 2, 0, 0, loadExt ),
+#endif
+#if SQLITE_USER_AUTHENTICATION
+ FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
+#endif
+#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
+ DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
+ DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
+#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
+ INLINE_FUNC(unlikely, 1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
+ INLINE_FUNC(likelihood, 2, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
+ INLINE_FUNC(likely, 1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
+#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
+ FUNCTION2(sqlite_offset, 1, 0, 0, noopFunc, SQLITE_FUNC_OFFSET|
+ SQLITE_FUNC_TYPEOF),
+#endif
+ FUNCTION(ltrim, 1, 1, 0, trimFunc ),
+ FUNCTION(ltrim, 2, 1, 0, trimFunc ),
+ FUNCTION(rtrim, 1, 2, 0, trimFunc ),
+ FUNCTION(rtrim, 2, 2, 0, trimFunc ),
+ FUNCTION(trim, 1, 3, 0, trimFunc ),
+ FUNCTION(trim, 2, 3, 0, trimFunc ),
+ FUNCTION(min, -1, 0, 1, minmaxFunc ),
+ FUNCTION(min, 0, 0, 1, 0 ),
+ WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
+ SQLITE_FUNC_MINMAX ),
+ FUNCTION(max, -1, 1, 1, minmaxFunc ),
+ FUNCTION(max, 0, 1, 1, 0 ),
+ WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
+ SQLITE_FUNC_MINMAX ),
+ FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
+ FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
+ FUNCTION(instr, 2, 0, 0, instrFunc ),
+ FUNCTION(printf, -1, 0, 0, printfFunc ),
+ FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
+ FUNCTION(char, -1, 0, 0, charFunc ),
+ FUNCTION(abs, 1, 0, 0, absFunc ),
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ FUNCTION(round, 1, 0, 0, roundFunc ),
+ FUNCTION(round, 2, 0, 0, roundFunc ),
+#endif
+ FUNCTION(upper, 1, 0, 0, upperFunc ),
+ FUNCTION(lower, 1, 0, 0, lowerFunc ),
+ FUNCTION(hex, 1, 0, 0, hexFunc ),
+ INLINE_FUNC(ifnull, 2, INLINEFUNC_coalesce, 0 ),
+ VFUNCTION(random, 0, 0, 0, randomFunc ),
+ VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
+ FUNCTION(nullif, 2, 0, 1, nullifFunc ),
+ DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
+ DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
+ FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
+ FUNCTION(quote, 1, 0, 0, quoteFunc ),
+ VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
+ VFUNCTION(changes, 0, 0, 0, changes ),
+ VFUNCTION(total_changes, 0, 0, 0, total_changes ),
+ FUNCTION(replace, 3, 0, 0, replaceFunc ),
+ FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
+ FUNCTION(substr, 2, 0, 0, substrFunc ),
+ FUNCTION(substr, 3, 0, 0, substrFunc ),
+ WAGGREGATE(sum, 1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0),
+ WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0),
+ WAGGREGATE(avg, 1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0),
+ WAGGREGATE(count, 0,0,0, countStep,
+ countFinalize, countFinalize, countInverse, SQLITE_FUNC_COUNT ),
+ WAGGREGATE(count, 1,0,0, countStep,
+ countFinalize, countFinalize, countInverse, 0 ),
+ WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep,
+ groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
+ WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep,
+ groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
+
+ LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
+#ifdef SQLITE_CASE_SENSITIVE_LIKE
+ LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
+ LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
+#else
+ LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
+ LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
+#endif
+#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
+ FUNCTION(unknown, -1, 0, 0, unknownFunc ),
+#endif
+ FUNCTION(coalesce, 1, 0, 0, 0 ),
+ FUNCTION(coalesce, 0, 0, 0, 0 ),
+ INLINE_FUNC(coalesce, -1, INLINEFUNC_coalesce, 0 ),
+ INLINE_FUNC(iif, 3, INLINEFUNC_iif, 0 ),
+ };
+#ifndef SQLITE_OMIT_ALTERTABLE
+ sqlite3AlterFunctions();
+#endif
+ sqlite3WindowFunctions();
+ sqlite3RegisterDateTimeFunctions();
+ sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
+
+#if 0 /* Enable to print out how the built-in functions are hashed */
+ {
+ int i;
+ FuncDef *p;
+ for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
+ printf("FUNC-HASH %02d:", i);
+ for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
+ int n = sqlite3Strlen30(p->zName);
+ int h = p->zName[0] + n;
+ printf(" %s(%d)", p->zName, h);
+ }
+ printf("\n");
+ }
+ }
+#endif
+}
+
+/************** End of func.c ************************************************/
+/************** Begin file fkey.c ********************************************/
+/*
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code used by the compiler to add foreign key
+** support to compiled SQL statements.
+*/
+/* #include "sqliteInt.h" */
+
+#ifndef SQLITE_OMIT_FOREIGN_KEY
+#ifndef SQLITE_OMIT_TRIGGER
+
+/*
+** Deferred and Immediate FKs
+** --------------------------
+**
+** Foreign keys in SQLite come in two flavours: deferred and immediate.
+** If an immediate foreign key constraint is violated,
+** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
+** statement transaction rolled back. If a
+** deferred foreign key constraint is violated, no action is taken
+** immediately. However if the application attempts to commit the
+** transaction before fixing the constraint violation, the attempt fails.
+**
+** Deferred constraints are implemented using a simple counter associated
+** with the database handle. The counter is set to zero each time a
+** database transaction is opened. Each time a statement is executed
+** that causes a foreign key violation, the counter is incremented. Each
+** time a statement is executed that removes an existing violation from
+** the database, the counter is decremented. When the transaction is
+** committed, the commit fails if the current value of the counter is
+** greater than zero. This scheme has two big drawbacks:
+**
+** * When a commit fails due to a deferred foreign key constraint,
+** there is no way to tell which foreign constraint is not satisfied,
+** or which row it is not satisfied for.
+**
+** * If the database contains foreign key violations when the
+** transaction is opened, this may cause the mechanism to malfunction.
+**
+** Despite these problems, this approach is adopted as it seems simpler
+** than the alternatives.
+**
+** INSERT operations:
+**
+** I.1) For each FK for which the table is the child table, search
+** the parent table for a match. If none is found increment the
+** constraint counter.
+**
+** I.2) For each FK for which the table is the parent table,
+** search the child table for rows that correspond to the new
+** row in the parent table. Decrement the counter for each row
+** found (as the constraint is now satisfied).
+**
+** DELETE operations:
+**
+** D.1) For each FK for which the table is the child table,
+** search the parent table for a row that corresponds to the
+** deleted row in the child table. If such a row is not found,
+** decrement the counter.
+**
+** D.2) For each FK for which the table is the parent table, search
+** the child table for rows that correspond to the deleted row
+** in the parent table. For each found increment the counter.
+**
+** UPDATE operations:
+**
+** An UPDATE command requires that all 4 steps above are taken, but only
+** for FK constraints for which the affected columns are actually
+** modified (values must be compared at runtime).
+**
+** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
+** This simplifies the implementation a bit.
+**
+** For the purposes of immediate FK constraints, the OR REPLACE conflict
+** resolution is considered to delete rows before the new row is inserted.
+** If a delete caused by OR REPLACE violates an FK constraint, an exception
+** is thrown, even if the FK constraint would be satisfied after the new
+** row is inserted.
+**
+** Immediate constraints are usually handled similarly. The only difference
+** is that the counter used is stored as part of each individual statement
+** object (struct Vdbe). If, after the statement has run, its immediate
+** constraint counter is greater than zero,
+** it returns SQLITE_CONSTRAINT_FOREIGNKEY
+** and the statement transaction is rolled back. An exception is an INSERT
+** statement that inserts a single row only (no triggers). In this case,
+** instead of using a counter, an exception is thrown immediately if the
+** INSERT violates a foreign key constraint. This is necessary as such
+** an INSERT does not open a statement transaction.
+**
+** TODO: How should dropping a table be handled? How should renaming a
+** table be handled?
+**
+**
+** Query API Notes
+** ---------------
+**
+** Before coding an UPDATE or DELETE row operation, the code-generator
+** for those two operations needs to know whether or not the operation
+** requires any FK processing and, if so, which columns of the original
+** row are required by the FK processing VDBE code (i.e. if FKs were
+** implemented using triggers, which of the old.* columns would be
+** accessed). No information is required by the code-generator before
+** coding an INSERT operation. The functions used by the UPDATE/DELETE
+** generation code to query for this information are:
+**
+** sqlite3FkRequired() - Test to see if FK processing is required.
+** sqlite3FkOldmask() - Query for the set of required old.* columns.
+**
+**
+** Externally accessible module functions
+** --------------------------------------
+**
+** sqlite3FkCheck() - Check for foreign key violations.
+** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
+** sqlite3FkDelete() - Delete an FKey structure.
+*/
+
+/*
+** VDBE Calling Convention
+** -----------------------
+**
+** Example:
+**
+** For the following INSERT statement:
+**
+** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
+** INSERT INTO t1 VALUES(1, 2, 3.1);
+**
+** Register (x): 2 (type integer)
+** Register (x+1): 1 (type integer)
+** Register (x+2): NULL (type NULL)
+** Register (x+3): 3.1 (type real)
+*/
+
+/*
+** A foreign key constraint requires that the key columns in the parent
+** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
+** Given that pParent is the parent table for foreign key constraint pFKey,
+** search the schema for a unique index on the parent key columns.
+**
+** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
+** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
+** is set to point to the unique index.
+**
+** If the parent key consists of a single column (the foreign key constraint
+** is not a composite foreign key), output variable *paiCol is set to NULL.
+** Otherwise, it is set to point to an allocated array of size N, where
+** N is the number of columns in the parent key. The first element of the
+** array is the index of the child table column that is mapped by the FK
+** constraint to the parent table column stored in the left-most column
+** of index *ppIdx. The second element of the array is the index of the
+** child table column that corresponds to the second left-most column of
+** *ppIdx, and so on.
+**
+** If the required index cannot be found, either because:
+**
+** 1) The named parent key columns do not exist, or
+**
+** 2) The named parent key columns do exist, but are not subject to a
+** UNIQUE or PRIMARY KEY constraint, or
+**
+** 3) No parent key columns were provided explicitly as part of the
+** foreign key definition, and the parent table does not have a
+** PRIMARY KEY, or
+**
+** 4) No parent key columns were provided explicitly as part of the
+** foreign key definition, and the PRIMARY KEY of the parent table
+** consists of a different number of columns to the child key in
+** the child table.
+**
+** then non-zero is returned, and a "foreign key mismatch" error loaded
+** into pParse. If an OOM error occurs, non-zero is returned and the
+** pParse->db->mallocFailed flag is set.
+*/
+SQLITE_PRIVATE int sqlite3FkLocateIndex(
+ Parse *pParse, /* Parse context to store any error in */
+ Table *pParent, /* Parent table of FK constraint pFKey */
+ FKey *pFKey, /* Foreign key to find index for */
+ Index **ppIdx, /* OUT: Unique index on parent table */
+ int **paiCol /* OUT: Map of index columns in pFKey */
+){
+ Index *pIdx = 0; /* Value to return via *ppIdx */
+ int *aiCol = 0; /* Value to return via *paiCol */
+ int nCol = pFKey->nCol; /* Number of columns in parent key */
+ char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
+
+ /* The caller is responsible for zeroing output parameters. */
+ assert( ppIdx && *ppIdx==0 );
+ assert( !paiCol || *paiCol==0 );
+ assert( pParse );
+
+ /* If this is a non-composite (single column) foreign key, check if it
+ ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
+ ** and *paiCol set to zero and return early.
+ **
+ ** Otherwise, for a composite foreign key (more than one column), allocate
+ ** space for the aiCol array (returned via output parameter *paiCol).
+ ** Non-composite foreign keys do not require the aiCol array.
+ */
+ if( nCol==1 ){
+ /* The FK maps to the IPK if any of the following are true:
+ **
+ ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
+ ** mapped to the primary key of table pParent, or
+ ** 2) The FK is explicitly mapped to a column declared as INTEGER
+ ** PRIMARY KEY.
+ */
+ if( pParent->iPKey>=0 ){
+ if( !zKey ) return 0;
+ if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
+ }
+ }else if( paiCol ){
+ assert( nCol>1 );
+ aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
+ if( !aiCol ) return 1;
+ *paiCol = aiCol;
+ }
+
+ for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
+ if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
+ /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
+ ** of columns. If each indexed column corresponds to a foreign key
+ ** column of pFKey, then this index is a winner. */
+
+ if( zKey==0 ){
+ /* If zKey is NULL, then this foreign key is implicitly mapped to
+ ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
+ ** identified by the test. */
+ if( IsPrimaryKeyIndex(pIdx) ){
+ if( aiCol ){
+ int i;
+ for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
+ }
+ break;
+ }
+ }else{
+ /* If zKey is non-NULL, then this foreign key was declared to
+ ** map to an explicit list of columns in table pParent. Check if this
+ ** index matches those columns. Also, check that the index uses
+ ** the default collation sequences for each column. */
+ int i, j;
+ for(i=0; i<nCol; i++){
+ i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
+ const char *zDfltColl; /* Def. collation for column */
+ char *zIdxCol; /* Name of indexed column */
+
+ if( iCol<0 ) break; /* No foreign keys against expression indexes */
+
+ /* If the index uses a collation sequence that is different from
+ ** the default collation sequence for the column, this index is
+ ** unusable. Bail out early in this case. */
+ zDfltColl = pParent->aCol[iCol].zColl;
+ if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
+ if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
+
+ zIdxCol = pParent->aCol[iCol].zName;
+ for(j=0; j<nCol; j++){
+ if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
+ if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
+ break;
+ }
+ }
+ if( j==nCol ) break;
+ }
+ if( i==nCol ) break; /* pIdx is usable */
+ }
+ }
+ }
+
+ if( !pIdx ){
+ if( !pParse->disableTriggers ){
+ sqlite3ErrorMsg(pParse,
+ "foreign key mismatch - \"%w\" referencing \"%w\"",
+ pFKey->pFrom->zName, pFKey->zTo);
+ }
+ sqlite3DbFree(pParse->db, aiCol);
+ return 1;
+ }
+
+ *ppIdx = pIdx;
+ return 0;
+}
+
+/*
+** This function is called when a row is inserted into or deleted from the
+** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
+** on the child table of pFKey, this function is invoked twice for each row
+** affected - once to "delete" the old row, and then again to "insert" the
+** new row.
+**
+** Each time it is called, this function generates VDBE code to locate the
+** row in the parent table that corresponds to the row being inserted into
+** or deleted from the child table. If the parent row can be found, no
+** special action is taken. Otherwise, if the parent row can *not* be
+** found in the parent table:
+**
+** Operation | FK type | Action taken
+** --------------------------------------------------------------------------
+** INSERT immediate Increment the "immediate constraint counter".
+**
+** DELETE immediate Decrement the "immediate constraint counter".
+**
+** INSERT deferred Increment the "deferred constraint counter".
+**
+** DELETE deferred Decrement the "deferred constraint counter".
+**
+** These operations are identified in the comment at the top of this file
+** (fkey.c) as "I.1" and "D.1".
+*/
+static void fkLookupParent(
+ Parse *pParse, /* Parse context */
+ int iDb, /* Index of database housing pTab */
+ Table *pTab, /* Parent table of FK pFKey */
+ Index *pIdx, /* Unique index on parent key columns in pTab */
+ FKey *pFKey, /* Foreign key constraint */
+ int *aiCol, /* Map from parent key columns to child table columns */
+ int regData, /* Address of array containing child table row */
+ int nIncr, /* Increment constraint counter by this */
+ int isIgnore /* If true, pretend pTab contains all NULL values */
+){
+ int i; /* Iterator variable */
+ Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
+ int iCur = pParse->nTab - 1; /* Cursor number to use */
+ int iOk = sqlite3VdbeMakeLabel(pParse); /* jump here if parent key found */
+
+ sqlite3VdbeVerifyAbortable(v,
+ (!pFKey->isDeferred
+ && !(pParse->db->flags & SQLITE_DeferFKs)
+ && !pParse->pToplevel
+ && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore);
+
+ /* If nIncr is less than zero, then check at runtime if there are any
+ ** outstanding constraints to resolve. If there are not, there is no need
+ ** to check if deleting this row resolves any outstanding violations.
+ **
+ ** Check if any of the key columns in the child table row are NULL. If
+ ** any are, then the constraint is considered satisfied. No need to
+ ** search for a matching row in the parent table. */
+ if( nIncr<0 ){
+ sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
+ VdbeCoverage(v);
+ }
+ for(i=0; i<pFKey->nCol; i++){
+ int iReg = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i]) + regData + 1;
+ sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
+ }
+
+ if( isIgnore==0 ){
+ if( pIdx==0 ){
+ /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
+ ** column of the parent table (table pTab). */
+ int iMustBeInt; /* Address of MustBeInt instruction */
+ int regTemp = sqlite3GetTempReg(pParse);
+
+ /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
+ ** apply the affinity of the parent key). If this fails, then there
+ ** is no matching parent key. Before using MustBeInt, make a copy of
+ ** the value. Otherwise, the value inserted into the child key column
+ ** will have INTEGER affinity applied to it, which may not be correct. */
+ sqlite3VdbeAddOp2(v, OP_SCopy,
+ sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[0])+1+regData, regTemp);
+ iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
+ VdbeCoverage(v);
+
+ /* If the parent table is the same as the child table, and we are about
+ ** to increment the constraint-counter (i.e. this is an INSERT operation),
+ ** then check if the row being inserted matches itself. If so, do not
+ ** increment the constraint-counter. */
+ if( pTab==pFKey->pFrom && nIncr==1 ){
+ sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
+ sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
+ }
+
+ sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
+ sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
+ sqlite3VdbeGoto(v, iOk);
+ sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
+ sqlite3VdbeJumpHere(v, iMustBeInt);
+ sqlite3ReleaseTempReg(pParse, regTemp);
+ }else{
+ int nCol = pFKey->nCol;
+ int regTemp = sqlite3GetTempRange(pParse, nCol);
+ int regRec = sqlite3GetTempReg(pParse);
+
+ sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
+ sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
+ for(i=0; i<nCol; i++){
+ sqlite3VdbeAddOp2(v, OP_Copy,
+ sqlite3TableColumnToStorage(pFKey->pFrom, aiCol[i])+1+regData,
+ regTemp+i);
+ }
+
+ /* If the parent table is the same as the child table, and we are about
+ ** to increment the constraint-counter (i.e. this is an INSERT operation),
+ ** then check if the row being inserted matches itself. If so, do not
+ ** increment the constraint-counter.
+ **
+ ** If any of the parent-key values are NULL, then the row cannot match
+ ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
+ ** of the parent-key values are NULL (at this point it is known that
+ ** none of the child key values are).
+ */
+ if( pTab==pFKey->pFrom && nIncr==1 ){
+ int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
+ for(i=0; i<nCol; i++){
+ int iChild = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i])
+ +1+regData;
+ int iParent = 1+regData;
+ iParent += sqlite3TableColumnToStorage(pIdx->pTable,
+ pIdx->aiColumn[i]);
+ assert( pIdx->aiColumn[i]>=0 );
+ assert( aiCol[i]!=pTab->iPKey );
+ if( pIdx->aiColumn[i]==pTab->iPKey ){
+ /* The parent key is a composite key that includes the IPK column */
+ iParent = regData;
+ }
+ sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
+ sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
+ }
+ sqlite3VdbeGoto(v, iOk);
+ }
+
+ sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
+ sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
+ sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
+
+ sqlite3ReleaseTempReg(pParse, regRec);
+ sqlite3ReleaseTempRange(pParse, regTemp, nCol);
+ }
+ }
+
+ if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
+ && !pParse->pToplevel
+ && !pParse->isMultiWrite
+ ){
+ /* Special case: If this is an INSERT statement that will insert exactly
+ ** one row into the table, raise a constraint immediately instead of
+ ** incrementing a counter. This is necessary as the VM code is being
+ ** generated for will not open a statement transaction. */
+ assert( nIncr==1 );
+ sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
+ OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
+ }else{
+ if( nIncr>0 && pFKey->isDeferred==0 ){
+ sqlite3MayAbort(pParse);
+ }
+ sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
+ }
+
+ sqlite3VdbeResolveLabel(v, iOk);
+ sqlite3VdbeAddOp1(v, OP_Close, iCur);
+}
+
+
+/*
+** Return an Expr object that refers to a memory register corresponding
+** to column iCol of table pTab.
+**
+** regBase is the first of an array of register that contains the data
+** for pTab. regBase itself holds the rowid. regBase+1 holds the first
+** column. regBase+2 holds the second column, and so forth.
+*/
+static Expr *exprTableRegister(
+ Parse *pParse, /* Parsing and code generating context */
+ Table *pTab, /* The table whose content is at r[regBase]... */
+ int regBase, /* Contents of table pTab */
+ i16 iCol /* Which column of pTab is desired */
+){
+ Expr *pExpr;
+ Column *pCol;
+ const char *zColl;
+ sqlite3 *db = pParse->db;
+
+ pExpr = sqlite3Expr(db, TK_REGISTER, 0);
+ if( pExpr ){
+ if( iCol>=0 && iCol!=pTab->iPKey ){
+ pCol = &pTab->aCol[iCol];
+ pExpr->iTable = regBase + sqlite3TableColumnToStorage(pTab,iCol) + 1;
+ pExpr->affExpr = pCol->affinity;
+ zColl = pCol->zColl;
+ if( zColl==0 ) zColl = db->pDfltColl->zName;
+ pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
+ }else{
+ pExpr->iTable = regBase;
+ pExpr->affExpr = SQLITE_AFF_INTEGER;
+ }
+ }
+ return pExpr;
+}
+
+/*
+** Return an Expr object that refers to column iCol of table pTab which
+** has cursor iCur.
+*/
+static Expr *exprTableColumn(
+ sqlite3 *db, /* The database connection */
+ Table *pTab, /* The table whose column is desired */
+ int iCursor, /* The open cursor on the table */
+ i16 iCol /* The column that is wanted */
+){
+ Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
+ if( pExpr ){
+ pExpr->y.pTab = pTab;
+ pExpr->iTable = iCursor;
+ pExpr->iColumn = iCol;
+ }
+ return pExpr;
+}
+
+/*
+** This function is called to generate code executed when a row is deleted
+** from the parent table of foreign key constraint pFKey and, if pFKey is
+** deferred, when a row is inserted into the same table. When generating
+** code for an SQL UPDATE operation, this function may be called twice -
+** once to "delete" the old row and once to "insert" the new row.
+**
+** Parameter nIncr is passed -1 when inserting a row (as this may decrease
+** the number of FK violations in the db) or +1 when deleting one (as this
+** may increase the number of FK constraint problems).
+**
+** The code generated by this function scans through the rows in the child
+** table that correspond to the parent table row being deleted or inserted.
+** For each child row found, one of the following actions is taken:
+**
+** Operation | FK type | Action taken
+** --------------------------------------------------------------------------
+** DELETE immediate Increment the "immediate constraint counter".
+** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
+** throw a "FOREIGN KEY constraint failed" exception.
+**
+** INSERT immediate Decrement the "immediate constraint counter".
+**
+** DELETE deferred Increment the "deferred constraint counter".
+** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
+** throw a "FOREIGN KEY constraint failed" exception.
+**
+** INSERT deferred Decrement the "deferred constraint counter".
+**
+** These operations are identified in the comment at the top of this file
+** (fkey.c) as "I.2" and "D.2".
+*/
+static void fkScanChildren(
+ Parse *pParse, /* Parse context */
+ SrcList *pSrc, /* The child table to be scanned */
+ Table *pTab, /* The parent table */
+ Index *pIdx, /* Index on parent covering the foreign key */
+ FKey *pFKey, /* The foreign key linking pSrc to pTab */
+ int *aiCol, /* Map from pIdx cols to child table cols */
+ int regData, /* Parent row data starts here */
+ int nIncr /* Amount to increment deferred counter by */
+){
+ sqlite3 *db = pParse->db; /* Database handle */
+ int i; /* Iterator variable */
+ Expr *pWhere = 0; /* WHERE clause to scan with */
+ NameContext sNameContext; /* Context used to resolve WHERE clause */
+ WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
+ int iFkIfZero = 0; /* Address of OP_FkIfZero */
+ Vdbe *v = sqlite3GetVdbe(pParse);
+
+ assert( pIdx==0 || pIdx->pTable==pTab );
+ assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
+ assert( pIdx!=0 || pFKey->nCol==1 );
+ assert( pIdx!=0 || HasRowid(pTab) );
+
+ if( nIncr<0 ){
+ iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
+ VdbeCoverage(v);
+ }
+
+ /* Create an Expr object representing an SQL expression like:
+ **
+ ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
+ **
+ ** The collation sequence used for the comparison should be that of
+ ** the parent key columns. The affinity of the parent key column should
+ ** be applied to each child key value before the comparison takes place.
+ */
+ for(i=0; i<pFKey->nCol; i++){
+ Expr *pLeft; /* Value from parent table row */
+ Expr *pRight; /* Column ref to child table */
+ Expr *pEq; /* Expression (pLeft = pRight) */
+ i16 iCol; /* Index of column in child table */
+ const char *zCol; /* Name of column in child table */
+
+ iCol = pIdx ? pIdx->aiColumn[i] : -1;
+ pLeft = exprTableRegister(pParse, pTab, regData, iCol);
+ iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
+ assert( iCol>=0 );
+ zCol = pFKey->pFrom->aCol[iCol].zName;
+ pRight = sqlite3Expr(db, TK_ID, zCol);
+ pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
+ pWhere = sqlite3ExprAnd(pParse, pWhere, pEq);
+ }
+
+ /* If the child table is the same as the parent table, then add terms
+ ** to the WHERE clause that prevent this entry from being scanned.
+ ** The added WHERE clause terms are like this:
+ **
+ ** $current_rowid!=rowid
+ ** NOT( $current_a==a AND $current_b==b AND ... )
+ **
+ ** The first form is used for rowid tables. The second form is used
+ ** for WITHOUT ROWID tables. In the second form, the *parent* key is
+ ** (a,b,...). Either the parent or primary key could be used to
+ ** uniquely identify the current row, but the parent key is more convenient
+ ** as the required values have already been loaded into registers
+ ** by the caller.
+ */
+ if( pTab==pFKey->pFrom && nIncr>0 ){
+ Expr *pNe; /* Expression (pLeft != pRight) */
+ Expr *pLeft; /* Value from parent table row */
+ Expr *pRight; /* Column ref to child table */
+ if( HasRowid(pTab) ){
+ pLeft = exprTableRegister(pParse, pTab, regData, -1);
+ pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
+ pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
+ }else{
+ Expr *pEq, *pAll = 0;
+ assert( pIdx!=0 );
+ for(i=0; i<pIdx->nKeyCol; i++){
+ i16 iCol = pIdx->aiColumn[i];
+ assert( iCol>=0 );
+ pLeft = exprTableRegister(pParse, pTab, regData, iCol);
+ pRight = sqlite3Expr(db, TK_ID, pTab->aCol[iCol].zName);
+ pEq = sqlite3PExpr(pParse, TK_IS, pLeft, pRight);
+ pAll = sqlite3ExprAnd(pParse, pAll, pEq);
+ }
+ pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
+ }
+ pWhere = sqlite3ExprAnd(pParse, pWhere, pNe);
+ }
+
+ /* Resolve the references in the WHERE clause. */
+ memset(&sNameContext, 0, sizeof(NameContext));
+ sNameContext.pSrcList = pSrc;
+ sNameContext.pParse = pParse;
+ sqlite3ResolveExprNames(&sNameContext, pWhere);
+
+ /* Create VDBE to loop through the entries in pSrc that match the WHERE
+ ** clause. For each row found, increment either the deferred or immediate
+ ** foreign key constraint counter. */
+ if( pParse->nErr==0 ){
+ pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
+ sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
+ if( pWInfo ){
+ sqlite3WhereEnd(pWInfo);
+ }
+ }
+
+ /* Clean up the WHERE clause constructed above. */
+ sqlite3ExprDelete(db, pWhere);
+ if( iFkIfZero ){
+ sqlite3VdbeJumpHereOrPopInst(v, iFkIfZero);
+ }
+}
+
+/*
+** This function returns a linked list of FKey objects (connected by
+** FKey.pNextTo) holding all children of table pTab. For example,
+** given the following schema:
+**
+** CREATE TABLE t1(a PRIMARY KEY);
+** CREATE TABLE t2(b REFERENCES t1(a);
+**
+** Calling this function with table "t1" as an argument returns a pointer
+** to the FKey structure representing the foreign key constraint on table
+** "t2". Calling this function with "t2" as the argument would return a
+** NULL pointer (as there are no FK constraints for which t2 is the parent
+** table).
+*/
+SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
+ return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
+}
+
+/*
+** The second argument is a Trigger structure allocated by the
+** fkActionTrigger() routine. This function deletes the Trigger structure
+** and all of its sub-components.
+**
+** The Trigger structure or any of its sub-components may be allocated from
+** the lookaside buffer belonging to database handle dbMem.
+*/
+static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
+ if( p ){
+ TriggerStep *pStep = p->step_list;
+ sqlite3ExprDelete(dbMem, pStep->pWhere);
+ sqlite3ExprListDelete(dbMem, pStep->pExprList);
+ sqlite3SelectDelete(dbMem, pStep->pSelect);
+ sqlite3ExprDelete(dbMem, p->pWhen);
+ sqlite3DbFree(dbMem, p);
+ }
+}
+
+/*
+** This function is called to generate code that runs when table pTab is
+** being dropped from the database. The SrcList passed as the second argument
+** to this function contains a single entry guaranteed to resolve to
+** table pTab.
+**
+** Normally, no code is required. However, if either
+**
+** (a) The table is the parent table of a FK constraint, or
+** (b) The table is the child table of a deferred FK constraint and it is
+** determined at runtime that there are outstanding deferred FK
+** constraint violations in the database,
+**
+** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
+** the table from the database. Triggers are disabled while running this
+** DELETE, but foreign key actions are not.
+*/
+SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
+ sqlite3 *db = pParse->db;
+ if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) ){
+ int iSkip = 0;
+ Vdbe *v = sqlite3GetVdbe(pParse);
+
+ assert( v ); /* VDBE has already been allocated */
+ assert( pTab->pSelect==0 ); /* Not a view */
+ if( sqlite3FkReferences(pTab)==0 ){
+ /* Search for a deferred foreign key constraint for which this table
+ ** is the child table. If one cannot be found, return without
+ ** generating any VDBE code. If one can be found, then jump over
+ ** the entire DELETE if there are no outstanding deferred constraints
+ ** when this statement is run. */
+ FKey *p;
+ for(p=pTab->pFKey; p; p=p->pNextFrom){
+ if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
+ }
+ if( !p ) return;
+ iSkip = sqlite3VdbeMakeLabel(pParse);
+ sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
+ }
+
+ pParse->disableTriggers = 1;
+ sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0, 0, 0);
+ pParse->disableTriggers = 0;
+
+ /* If the DELETE has generated immediate foreign key constraint
+ ** violations, halt the VDBE and return an error at this point, before
+ ** any modifications to the schema are made. This is because statement
+ ** transactions are not able to rollback schema changes.
+ **
+ ** If the SQLITE_DeferFKs flag is set, then this is not required, as
+ ** the statement transaction will not be rolled back even if FK
+ ** constraints are violated.
+ */
+ if( (db->flags & SQLITE_DeferFKs)==0 ){
+ sqlite3VdbeVerifyAbortable(v, OE_Abort);
+ sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
+ VdbeCoverage(v);
+ sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
+ OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
+ }
+
+ if( iSkip ){
+ sqlite3VdbeResolveLabel(v, iSkip);
+ }
+ }
+}
+
+
+/*
+** The second argument points to an FKey object representing a foreign key
+** for which pTab is the child table. An UPDATE statement against pTab
+** is currently being processed. For each column of the table that is
+** actually updated, the corresponding element in the aChange[] array
+** is zero or greater (if a column is unmodified the corresponding element
+** is set to -1). If the rowid column is modified by the UPDATE statement
+** the bChngRowid argument is non-zero.
+**
+** This function returns true if any of the columns that are part of the
+** child key for FK constraint *p are modified.
+*/
+static int fkChildIsModified(
+ Table *pTab, /* Table being updated */
+ FKey *p, /* Foreign key for which pTab is the child */
+ int *aChange, /* Array indicating modified columns */
+ int bChngRowid /* True if rowid is modified by this update */
+){
+ int i;
+ for(i=0; i<p->nCol; i++){
+ int iChildKey = p->aCol[i].iFrom;
+ if( aChange[iChildKey]>=0 ) return 1;
+ if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
+ }
+ return 0;
+}
+
+/*
+** The second argument points to an FKey object representing a foreign key
+** for which pTab is the parent table. An UPDATE statement against pTab
+** is currently being processed. For each column of the table that is
+** actually updated, the corresponding element in the aChange[] array
+** is zero or greater (if a column is unmodified the corresponding element
+** is set to -1). If the rowid column is modified by the UPDATE statement
+** the bChngRowid argument is non-zero.
+**
+** This function returns true if any of the columns that are part of the
+** parent key for FK constraint *p are modified.
+*/
+static int fkParentIsModified(
+ Table *pTab,
+ FKey *p,
+ int *aChange,
+ int bChngRowid
+){
+ int i;
+ for(i=0; i<p->nCol; i++){
+ char *zKey = p->aCol[i].zCol;
+ int iKey;
+ for(iKey=0; iKey<pTab->nCol; iKey++){
+ if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
+ Column *pCol = &pTab->aCol[iKey];
+ if( zKey ){
+ if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
+ }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
+ return 1;
+ }
+ }
+ }
+ }
+ return 0;
+}
+
+/*
+** Return true if the parser passed as the first argument is being
+** used to code a trigger that is really a "SET NULL" action belonging
+** to trigger pFKey.
+*/
+static int isSetNullAction(Parse *pParse, FKey *pFKey){
+ Parse *pTop = sqlite3ParseToplevel(pParse);
+ if( pTop->pTriggerPrg ){
+ Trigger *p = pTop->pTriggerPrg->pTrigger;
+ if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
+ || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
+ ){
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/*
+** This function is called when inserting, deleting or updating a row of
+** table pTab to generate VDBE code to perform foreign key constraint
+** processing for the operation.
+**
+** For a DELETE operation, parameter regOld is passed the index of the
+** first register in an array of (pTab->nCol+1) registers containing the
+** rowid of the row being deleted, followed by each of the column values
+** of the row being deleted, from left to right. Parameter regNew is passed
+** zero in this case.
+**
+** For an INSERT operation, regOld is passed zero and regNew is passed the
+** first register of an array of (pTab->nCol+1) registers containing the new
+** row data.
+**
+** For an UPDATE operation, this function is called twice. Once before
+** the original record is deleted from the table using the calling convention
+** described for DELETE. Then again after the original record is deleted
+** but before the new record is inserted using the INSERT convention.
+*/
+SQLITE_PRIVATE void sqlite3FkCheck(
+ Parse *pParse, /* Parse context */
+ Table *pTab, /* Row is being deleted from this table */
+ int regOld, /* Previous row data is stored here */
+ int regNew, /* New row data is stored here */
+ int *aChange, /* Array indicating UPDATEd columns (or 0) */
+ int bChngRowid /* True if rowid is UPDATEd */
+){
+ sqlite3 *db = pParse->db; /* Database handle */
+ FKey *pFKey; /* Used to iterate through FKs */
+ int iDb; /* Index of database containing pTab */
+ const char *zDb; /* Name of database containing pTab */
+ int isIgnoreErrors = pParse->disableTriggers;
+
+ /* Exactly one of regOld and regNew should be non-zero. */
+ assert( (regOld==0)!=(regNew==0) );
+
+ /* If foreign-keys are disabled, this function is a no-op. */
+ if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
+
+ iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ zDb = db->aDb[iDb].zDbSName;
+
+ /* Loop through all the foreign key constraints for which pTab is the
+ ** child table (the table that the foreign key definition is part of). */
+ for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
+ Table *pTo; /* Parent table of foreign key pFKey */
+ Index *pIdx = 0; /* Index on key columns in pTo */
+ int *aiFree = 0;
+ int *aiCol;
+ int iCol;
+ int i;
+ int bIgnore = 0;
+
+ if( aChange
+ && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
+ && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
+ ){
+ continue;
+ }
+
+ /* Find the parent table of this foreign key. Also find a unique index
+ ** on the parent key columns in the parent table. If either of these
+ ** schema items cannot be located, set an error in pParse and return
+ ** early. */
+ if( pParse->disableTriggers ){
+ pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
+ }else{
+ pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
+ }
+ if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
+ assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
+ if( !isIgnoreErrors || db->mallocFailed ) return;
+ if( pTo==0 ){
+ /* If isIgnoreErrors is true, then a table is being dropped. In this
+ ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
+ ** before actually dropping it in order to check FK constraints.
+ ** If the parent table of an FK constraint on the current table is
+ ** missing, behave as if it is empty. i.e. decrement the relevant
+ ** FK counter for each row of the current table with non-NULL keys.
+ */
+ Vdbe *v = sqlite3GetVdbe(pParse);
+ int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
+ for(i=0; i<pFKey->nCol; i++){
+ int iFromCol, iReg;
+ iFromCol = pFKey->aCol[i].iFrom;
+ iReg = sqlite3TableColumnToStorage(pFKey->pFrom,iFromCol) + regOld+1;
+ sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
+ }
+ sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
+ }
+ continue;
+ }
+ assert( pFKey->nCol==1 || (aiFree && pIdx) );
+
+ if( aiFree ){
+ aiCol = aiFree;
+ }else{
+ iCol = pFKey->aCol[0].iFrom;
+ aiCol = &iCol;
+ }
+ for(i=0; i<pFKey->nCol; i++){
+ if( aiCol[i]==pTab->iPKey ){
+ aiCol[i] = -1;
+ }
+ assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ /* Request permission to read the parent key columns. If the
+ ** authorization callback returns SQLITE_IGNORE, behave as if any
+ ** values read from the parent table are NULL. */
+ if( db->xAuth ){
+ int rcauth;
+ char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
+ rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
+ bIgnore = (rcauth==SQLITE_IGNORE);
+ }
+#endif
+ }
+
+ /* Take a shared-cache advisory read-lock on the parent table. Allocate
+ ** a cursor to use to search the unique index on the parent key columns
+ ** in the parent table. */
+ sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
+ pParse->nTab++;
+
+ if( regOld!=0 ){
+ /* A row is being removed from the child table. Search for the parent.
+ ** If the parent does not exist, removing the child row resolves an
+ ** outstanding foreign key constraint violation. */
+ fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
+ }
+ if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
+ /* A row is being added to the child table. If a parent row cannot
+ ** be found, adding the child row has violated the FK constraint.
+ **
+ ** If this operation is being performed as part of a trigger program
+ ** that is actually a "SET NULL" action belonging to this very
+ ** foreign key, then omit this scan altogether. As all child key
+ ** values are guaranteed to be NULL, it is not possible for adding
+ ** this row to cause an FK violation. */
+ fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
+ }
+
+ sqlite3DbFree(db, aiFree);
+ }
+
+ /* Loop through all the foreign key constraints that refer to this table.
+ ** (the "child" constraints) */
+ for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
+ Index *pIdx = 0; /* Foreign key index for pFKey */
+ SrcList *pSrc;
+ int *aiCol = 0;
+
+ if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
+ continue;
+ }
+
+ if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
+ && !pParse->pToplevel && !pParse->isMultiWrite
+ ){
+ assert( regOld==0 && regNew!=0 );
+ /* Inserting a single row into a parent table cannot cause (or fix)
+ ** an immediate foreign key violation. So do nothing in this case. */
+ continue;
+ }
+
+ if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
+ if( !isIgnoreErrors || db->mallocFailed ) return;
+ continue;
+ }
+ assert( aiCol || pFKey->nCol==1 );
+
+ /* Create a SrcList structure containing the child table. We need the
+ ** child table as a SrcList for sqlite3WhereBegin() */
+ pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
+ if( pSrc ){
+ struct SrcList_item *pItem = pSrc->a;
+ pItem->pTab = pFKey->pFrom;
+ pItem->zName = pFKey->pFrom->zName;
+ pItem->pTab->nTabRef++;
+ pItem->iCursor = pParse->nTab++;
+
+ if( regNew!=0 ){
+ fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
+ }
+ if( regOld!=0 ){
+ int eAction = pFKey->aAction[aChange!=0];
+ fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
+ /* If this is a deferred FK constraint, or a CASCADE or SET NULL
+ ** action applies, then any foreign key violations caused by
+ ** removing the parent key will be rectified by the action trigger.
+ ** So do not set the "may-abort" flag in this case.
+ **
+ ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
+ ** may-abort flag will eventually be set on this statement anyway
+ ** (when this function is called as part of processing the UPDATE
+ ** within the action trigger).
+ **
+ ** Note 2: At first glance it may seem like SQLite could simply omit
+ ** all OP_FkCounter related scans when either CASCADE or SET NULL
+ ** applies. The trouble starts if the CASCADE or SET NULL action
+ ** trigger causes other triggers or action rules attached to the
+ ** child table to fire. In these cases the fk constraint counters
+ ** might be set incorrectly if any OP_FkCounter related scans are
+ ** omitted. */
+ if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
+ sqlite3MayAbort(pParse);
+ }
+ }
+ pItem->zName = 0;
+ sqlite3SrcListDelete(db, pSrc);
+ }
+ sqlite3DbFree(db, aiCol);
+ }
+}
+
+#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
+
+/*
+** This function is called before generating code to update or delete a
+** row contained in table pTab.
+*/
+SQLITE_PRIVATE u32 sqlite3FkOldmask(
+ Parse *pParse, /* Parse context */
+ Table *pTab /* Table being modified */
+){
+ u32 mask = 0;
+ if( pParse->db->flags&SQLITE_ForeignKeys ){
+ FKey *p;
+ int i;
+ for(p=pTab->pFKey; p; p=p->pNextFrom){
+ for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
+ }
+ for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
+ Index *pIdx = 0;
+ sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
+ if( pIdx ){
+ for(i=0; i<pIdx->nKeyCol; i++){
+ assert( pIdx->aiColumn[i]>=0 );
+ mask |= COLUMN_MASK(pIdx->aiColumn[i]);
+ }
+ }
+ }
+ }
+ return mask;
+}
+
+
+/*
+** This function is called before generating code to update or delete a
+** row contained in table pTab. If the operation is a DELETE, then
+** parameter aChange is passed a NULL value. For an UPDATE, aChange points
+** to an array of size N, where N is the number of columns in table pTab.
+** If the i'th column is not modified by the UPDATE, then the corresponding
+** entry in the aChange[] array is set to -1. If the column is modified,
+** the value is 0 or greater. Parameter chngRowid is set to true if the
+** UPDATE statement modifies the rowid fields of the table.
+**
+** If any foreign key processing will be required, this function returns
+** non-zero. If there is no foreign key related processing, this function
+** returns zero.
+**
+** For an UPDATE, this function returns 2 if:
+**
+** * There are any FKs for which pTab is the child and the parent table, or
+** * the UPDATE modifies one or more parent keys for which the action is
+** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
+**
+** Or, assuming some other foreign key processing is required, 1.
+*/
+SQLITE_PRIVATE int sqlite3FkRequired(
+ Parse *pParse, /* Parse context */
+ Table *pTab, /* Table being modified */
+ int *aChange, /* Non-NULL for UPDATE operations */
+ int chngRowid /* True for UPDATE that affects rowid */
+){
+ int eRet = 0;
+ if( pParse->db->flags&SQLITE_ForeignKeys ){
+ if( !aChange ){
+ /* A DELETE operation. Foreign key processing is required if the
+ ** table in question is either the child or parent table for any
+ ** foreign key constraint. */
+ eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
+ }else{
+ /* This is an UPDATE. Foreign key processing is only required if the
+ ** operation modifies one or more child or parent key columns. */
+ FKey *p;
+
+ /* Check if any child key columns are being modified. */
+ for(p=pTab->pFKey; p; p=p->pNextFrom){
+ if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
+ if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
+ eRet = 1;
+ }
+ }
+
+ /* Check if any parent key columns are being modified. */
+ for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
+ if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
+ if( p->aAction[1]!=OE_None ) return 2;
+ eRet = 1;
+ }
+ }
+ }
+ }
+ return eRet;
+}
+
+/*
+** This function is called when an UPDATE or DELETE operation is being
+** compiled on table pTab, which is the parent table of foreign-key pFKey.
+** If the current operation is an UPDATE, then the pChanges parameter is
+** passed a pointer to the list of columns being modified. If it is a
+** DELETE, pChanges is passed a NULL pointer.
+**
+** It returns a pointer to a Trigger structure containing a trigger
+** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
+** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
+** returned (these actions require no special handling by the triggers
+** sub-system, code for them is created by fkScanChildren()).
+**
+** For example, if pFKey is the foreign key and pTab is table "p" in
+** the following schema:
+**
+** CREATE TABLE p(pk PRIMARY KEY);
+** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
+**
+** then the returned trigger structure is equivalent to:
+**
+** CREATE TRIGGER ... DELETE ON p BEGIN
+** DELETE FROM c WHERE ck = old.pk;
+** END;
+**
+** The returned pointer is cached as part of the foreign key object. It
+** is eventually freed along with the rest of the foreign key object by
+** sqlite3FkDelete().
+*/
+static Trigger *fkActionTrigger(
+ Parse *pParse, /* Parse context */
+ Table *pTab, /* Table being updated or deleted from */
+ FKey *pFKey, /* Foreign key to get action for */
+ ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
+){
+ sqlite3 *db = pParse->db; /* Database handle */
+ int action; /* One of OE_None, OE_Cascade etc. */
+ Trigger *pTrigger; /* Trigger definition to return */
+ int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
+
+ action = pFKey->aAction[iAction];
+ if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
+ return 0;
+ }
+ pTrigger = pFKey->apTrigger[iAction];
+
+ if( action!=OE_None && !pTrigger ){
+ char const *zFrom; /* Name of child table */
+ int nFrom; /* Length in bytes of zFrom */
+ Index *pIdx = 0; /* Parent key index for this FK */
+ int *aiCol = 0; /* child table cols -> parent key cols */
+ TriggerStep *pStep = 0; /* First (only) step of trigger program */
+ Expr *pWhere = 0; /* WHERE clause of trigger step */
+ ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
+ Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
+ int i; /* Iterator variable */
+ Expr *pWhen = 0; /* WHEN clause for the trigger */
+
+ if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
+ assert( aiCol || pFKey->nCol==1 );
+
+ for(i=0; i<pFKey->nCol; i++){
+ Token tOld = { "old", 3 }; /* Literal "old" token */
+ Token tNew = { "new", 3 }; /* Literal "new" token */
+ Token tFromCol; /* Name of column in child table */
+ Token tToCol; /* Name of column in parent table */
+ int iFromCol; /* Idx of column in child table */
+ Expr *pEq; /* tFromCol = OLD.tToCol */
+
+ iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
+ assert( iFromCol>=0 );
+ assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
+ assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
+ sqlite3TokenInit(&tToCol,
+ pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
+ sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
+
+ /* Create the expression "OLD.zToCol = zFromCol". It is important
+ ** that the "OLD.zToCol" term is on the LHS of the = operator, so
+ ** that the affinity and collation sequence associated with the
+ ** parent table are used for the comparison. */
+ pEq = sqlite3PExpr(pParse, TK_EQ,
+ sqlite3PExpr(pParse, TK_DOT,
+ sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
+ sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
+ sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
+ );
+ pWhere = sqlite3ExprAnd(pParse, pWhere, pEq);
+
+ /* For ON UPDATE, construct the next term of the WHEN clause.
+ ** The final WHEN clause will be like this:
+ **
+ ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
+ */
+ if( pChanges ){
+ pEq = sqlite3PExpr(pParse, TK_IS,
+ sqlite3PExpr(pParse, TK_DOT,
+ sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
+ sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
+ sqlite3PExpr(pParse, TK_DOT,
+ sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
+ sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
+ );
+ pWhen = sqlite3ExprAnd(pParse, pWhen, pEq);
+ }
+
+ if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
+ Expr *pNew;
+ if( action==OE_Cascade ){
+ pNew = sqlite3PExpr(pParse, TK_DOT,
+ sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
+ sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
+ }else if( action==OE_SetDflt ){
+ Column *pCol = pFKey->pFrom->aCol + iFromCol;
+ Expr *pDflt;
+ if( pCol->colFlags & COLFLAG_GENERATED ){
+ testcase( pCol->colFlags & COLFLAG_VIRTUAL );
+ testcase( pCol->colFlags & COLFLAG_STORED );
+ pDflt = 0;
+ }else{
+ pDflt = pCol->pDflt;
+ }
+ if( pDflt ){
+ pNew = sqlite3ExprDup(db, pDflt, 0);
+ }else{
+ pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
+ }
+ }else{
+ pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
+ }
+ pList = sqlite3ExprListAppend(pParse, pList, pNew);
+ sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
+ }
+ }
+ sqlite3DbFree(db, aiCol);
+
+ zFrom = pFKey->pFrom->zName;
+ nFrom = sqlite3Strlen30(zFrom);
+
+ if( action==OE_Restrict ){
+ Token tFrom;
+ Expr *pRaise;
+
+ tFrom.z = zFrom;
+ tFrom.n = nFrom;
+ pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
+ if( pRaise ){
+ pRaise->affExpr = OE_Abort;
+ }
+ pSelect = sqlite3SelectNew(pParse,
+ sqlite3ExprListAppend(pParse, 0, pRaise),
+ sqlite3SrcListAppend(pParse, 0, &tFrom, 0),
+ pWhere,
+ 0, 0, 0, 0, 0
+ );
+ pWhere = 0;
+ }
+
+ /* Disable lookaside memory allocation */
+ DisableLookaside;
+
+ pTrigger = (Trigger *)sqlite3DbMallocZero(db,
+ sizeof(Trigger) + /* struct Trigger */
+ sizeof(TriggerStep) + /* Single step in trigger program */
+ nFrom + 1 /* Space for pStep->zTarget */
+ );
+ if( pTrigger ){
+ pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
+ pStep->zTarget = (char *)&pStep[1];
+ memcpy((char *)pStep->zTarget, zFrom, nFrom);
+
+ pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
+ pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
+ pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
+ if( pWhen ){
+ pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
+ pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
+ }
+ }
+
+ /* Re-enable the lookaside buffer, if it was disabled earlier. */
+ EnableLookaside;
+
+ sqlite3ExprDelete(db, pWhere);
+ sqlite3ExprDelete(db, pWhen);
+ sqlite3ExprListDelete(db, pList);
+ sqlite3SelectDelete(db, pSelect);
+ if( db->mallocFailed==1 ){
+ fkTriggerDelete(db, pTrigger);
+ return 0;
+ }
+ assert( pStep!=0 );
+ assert( pTrigger!=0 );
+
+ switch( action ){
+ case OE_Restrict:
+ pStep->op = TK_SELECT;
+ break;
+ case OE_Cascade:
+ if( !pChanges ){
+ pStep->op = TK_DELETE;
+ break;
+ }
+ /* no break */ deliberate_fall_through
+ default:
+ pStep->op = TK_UPDATE;
+ }
+ pStep->pTrig = pTrigger;
+ pTrigger->pSchema = pTab->pSchema;
+ pTrigger->pTabSchema = pTab->pSchema;
+ pFKey->apTrigger[iAction] = pTrigger;
+ pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
+ }
+
+ return pTrigger;
+}
+
+/*
+** This function is called when deleting or updating a row to implement
+** any required CASCADE, SET NULL or SET DEFAULT actions.
+*/
+SQLITE_PRIVATE void sqlite3FkActions(
+ Parse *pParse, /* Parse context */
+ Table *pTab, /* Table being updated or deleted from */
+ ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
+ int regOld, /* Address of array containing old row */
+ int *aChange, /* Array indicating UPDATEd columns (or 0) */
+ int bChngRowid /* True if rowid is UPDATEd */
+){
+ /* If foreign-key support is enabled, iterate through all FKs that
+ ** refer to table pTab. If there is an action associated with the FK
+ ** for this operation (either update or delete), invoke the associated
+ ** trigger sub-program. */
+ if( pParse->db->flags&SQLITE_ForeignKeys ){
+ FKey *pFKey; /* Iterator variable */
+ for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
+ if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
+ Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
+ if( pAct ){
+ sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
+ }
+ }
+ }
+ }
+}
+
+#endif /* ifndef SQLITE_OMIT_TRIGGER */
+
+/*
+** Free all memory associated with foreign key definitions attached to
+** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
+** hash table.
+*/
+SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
+ FKey *pFKey; /* Iterator variable */
+ FKey *pNext; /* Copy of pFKey->pNextFrom */
+
+ assert( db==0 || IsVirtual(pTab)
+ || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
+ for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
+
+ /* Remove the FK from the fkeyHash hash table. */
+ if( !db || db->pnBytesFreed==0 ){
+ if( pFKey->pPrevTo ){
+ pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
+ }else{
+ void *p = (void *)pFKey->pNextTo;
+ const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
+ sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
+ }
+ if( pFKey->pNextTo ){
+ pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
+ }
+ }
+
+ /* EV: R-30323-21917 Each foreign key constraint in SQLite is
+ ** classified as either immediate or deferred.
+ */
+ assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
+
+ /* Delete any triggers created to implement actions for this FK. */
+#ifndef SQLITE_OMIT_TRIGGER
+ fkTriggerDelete(db, pFKey->apTrigger[0]);
+ fkTriggerDelete(db, pFKey->apTrigger[1]);
+#endif
+
+ pNext = pFKey->pNextFrom;
+ sqlite3DbFree(db, pFKey);
+ }
+}
+#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
+
+/************** End of fkey.c ************************************************/
+/************** Begin file insert.c ******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains C code routines that are called by the parser
+** to handle INSERT statements in SQLite.
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** Generate code that will
+**
+** (1) acquire a lock for table pTab then
+** (2) open pTab as cursor iCur.
+**
+** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
+** for that table that is actually opened.
+*/
+SQLITE_PRIVATE void sqlite3OpenTable(
+ Parse *pParse, /* Generate code into this VDBE */
+ int iCur, /* The cursor number of the table */
+ int iDb, /* The database index in sqlite3.aDb[] */
+ Table *pTab, /* The table to be opened */
+ int opcode /* OP_OpenRead or OP_OpenWrite */
+){
+ Vdbe *v;
+ assert( !IsVirtual(pTab) );
+ assert( pParse->pVdbe!=0 );
+ v = pParse->pVdbe;
+ assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
+ sqlite3TableLock(pParse, iDb, pTab->tnum,
+ (opcode==OP_OpenWrite)?1:0, pTab->zName);
+ if( HasRowid(pTab) ){
+ sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);
+ VdbeComment((v, "%s", pTab->zName));
+ }else{
+ Index *pPk = sqlite3PrimaryKeyIndex(pTab);
+ assert( pPk!=0 );
+ assert( pPk->tnum==pTab->tnum );
+ sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
+ sqlite3VdbeSetP4KeyInfo(pParse, pPk);
+ VdbeComment((v, "%s", pTab->zName));
+ }
+}
+
+/*
+** Return a pointer to the column affinity string associated with index
+** pIdx. A column affinity string has one character for each column in
+** the table, according to the affinity of the column:
+**
+** Character Column affinity
+** ------------------------------
+** 'A' BLOB
+** 'B' TEXT
+** 'C' NUMERIC
+** 'D' INTEGER
+** 'F' REAL
+**
+** An extra 'D' is appended to the end of the string to cover the
+** rowid that appears as the last column in every index.
+**
+** Memory for the buffer containing the column index affinity string
+** is managed along with the rest of the Index structure. It will be
+** released when sqlite3DeleteIndex() is called.
+*/
+SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
+ if( !pIdx->zColAff ){
+ /* The first time a column affinity string for a particular index is
+ ** required, it is allocated and populated here. It is then stored as
+ ** a member of the Index structure for subsequent use.
+ **
+ ** The column affinity string will eventually be deleted by
+ ** sqliteDeleteIndex() when the Index structure itself is cleaned
+ ** up.
+ */
+ int n;
+ Table *pTab = pIdx->pTable;
+ pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
+ if( !pIdx->zColAff ){
+ sqlite3OomFault(db);
+ return 0;
+ }
+ for(n=0; n<pIdx->nColumn; n++){
+ i16 x = pIdx->aiColumn[n];
+ char aff;
+ if( x>=0 ){
+ aff = pTab->aCol[x].affinity;
+ }else if( x==XN_ROWID ){
+ aff = SQLITE_AFF_INTEGER;
+ }else{
+ assert( x==XN_EXPR );
+ assert( pIdx->aColExpr!=0 );
+ aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
+ }
+ if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;
+ if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;
+ pIdx->zColAff[n] = aff;
+ }
+ pIdx->zColAff[n] = 0;
+ }
+
+ return pIdx->zColAff;
+}
+
+/*
+** Compute the affinity string for table pTab, if it has not already been
+** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
+**
+** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
+** if iReg>0 then code an OP_Affinity opcode that will set the affinities
+** for register iReg and following. Or if affinities exists and iReg==0,
+** then just set the P4 operand of the previous opcode (which should be
+** an OP_MakeRecord) to the affinity string.
+**
+** A column affinity string has one character per column:
+**
+** Character Column affinity
+** ------------------------------
+** 'A' BLOB
+** 'B' TEXT
+** 'C' NUMERIC
+** 'D' INTEGER
+** 'E' REAL
+*/
+SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
+ int i, j;
+ char *zColAff = pTab->zColAff;
+ if( zColAff==0 ){
+ sqlite3 *db = sqlite3VdbeDb(v);
+ zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
+ if( !zColAff ){
+ sqlite3OomFault(db);
+ return;
+ }
+
+ for(i=j=0; i<pTab->nCol; i++){
+ assert( pTab->aCol[i].affinity!=0 );
+ if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
+ zColAff[j++] = pTab->aCol[i].affinity;
+ }
+ }
+ do{
+ zColAff[j--] = 0;
+ }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB );
+ pTab->zColAff = zColAff;
+ }
+ assert( zColAff!=0 );
+ i = sqlite3Strlen30NN(zColAff);
+ if( i ){
+ if( iReg ){
+ sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
+ }else{
+ sqlite3VdbeChangeP4(v, -1, zColAff, i);
+ }
+ }
+}
+
+/*
+** Return non-zero if the table pTab in database iDb or any of its indices
+** have been opened at any point in the VDBE program. This is used to see if
+** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
+** run without using a temporary table for the results of the SELECT.
+*/
+static int readsTable(Parse *p, int iDb, Table *pTab){
+ Vdbe *v = sqlite3GetVdbe(p);
+ int i;
+ int iEnd = sqlite3VdbeCurrentAddr(v);
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
+#endif
+
+ for(i=1; i<iEnd; i++){
+ VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
+ assert( pOp!=0 );
+ if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
+ Index *pIndex;
+ Pgno tnum = pOp->p2;
+ if( tnum==pTab->tnum ){
+ return 1;
+ }
+ for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
+ if( tnum==pIndex->tnum ){
+ return 1;
+ }
+ }
+ }
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
+ assert( pOp->p4.pVtab!=0 );
+ assert( pOp->p4type==P4_VTAB );
+ return 1;
+ }
+#endif
+ }
+ return 0;
+}
+
+/* This walker callback will compute the union of colFlags flags for all
+** referenced columns in a CHECK constraint or generated column expression.
+*/
+static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){
+ if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
+ assert( pExpr->iColumn < pWalker->u.pTab->nCol );
+ pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
+ }
+ return WRC_Continue;
+}
+
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+/*
+** All regular columns for table pTab have been puts into registers
+** starting with iRegStore. The registers that correspond to STORED
+** or VIRTUAL columns have not yet been initialized. This routine goes
+** back and computes the values for those columns based on the previously
+** computed normal columns.
+*/
+SQLITE_PRIVATE void sqlite3ComputeGeneratedColumns(
+ Parse *pParse, /* Parsing context */
+ int iRegStore, /* Register holding the first column */
+ Table *pTab /* The table */
+){
+ int i;
+ Walker w;
+ Column *pRedo;
+ int eProgress;
+ VdbeOp *pOp;
+
+ assert( pTab->tabFlags & TF_HasGenerated );
+ testcase( pTab->tabFlags & TF_HasVirtual );
+ testcase( pTab->tabFlags & TF_HasStored );
+
+ /* Before computing generated columns, first go through and make sure
+ ** that appropriate affinity has been applied to the regular columns
+ */
+ sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
+ if( (pTab->tabFlags & TF_HasStored)!=0
+ && (pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1))->opcode==OP_Affinity
+ ){
+ /* Change the OP_Affinity argument to '@' (NONE) for all stored
+ ** columns. '@' is the no-op affinity and those columns have not
+ ** yet been computed. */
+ int ii, jj;
+ char *zP4 = pOp->p4.z;
+ assert( zP4!=0 );
+ assert( pOp->p4type==P4_DYNAMIC );
+ for(ii=jj=0; zP4[jj]; ii++){
+ if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
+ continue;
+ }
+ if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
+ zP4[jj] = SQLITE_AFF_NONE;
+ }
+ jj++;
+ }
+ }
+
+ /* Because there can be multiple generated columns that refer to one another,
+ ** this is a two-pass algorithm. On the first pass, mark all generated
+ ** columns as "not available".
+ */
+ for(i=0; i<pTab->nCol; i++){
+ if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
+ testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
+ testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
+ pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
+ }
+ }
+
+ w.u.pTab = pTab;
+ w.xExprCallback = exprColumnFlagUnion;
+ w.xSelectCallback = 0;
+ w.xSelectCallback2 = 0;
+
+ /* On the second pass, compute the value of each NOT-AVAILABLE column.
+ ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will
+ ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as
+ ** they are needed.
+ */
+ pParse->iSelfTab = -iRegStore;
+ do{
+ eProgress = 0;
+ pRedo = 0;
+ for(i=0; i<pTab->nCol; i++){
+ Column *pCol = pTab->aCol + i;
+ if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){
+ int x;
+ pCol->colFlags |= COLFLAG_BUSY;
+ w.eCode = 0;
+ sqlite3WalkExpr(&w, pCol->pDflt);
+ pCol->colFlags &= ~COLFLAG_BUSY;
+ if( w.eCode & COLFLAG_NOTAVAIL ){
+ pRedo = pCol;
+ continue;
+ }
+ eProgress = 1;
+ assert( pCol->colFlags & COLFLAG_GENERATED );
+ x = sqlite3TableColumnToStorage(pTab, i) + iRegStore;
+ sqlite3ExprCodeGeneratedColumn(pParse, pCol, x);
+ pCol->colFlags &= ~COLFLAG_NOTAVAIL;
+ }
+ }
+ }while( pRedo && eProgress );
+ if( pRedo ){
+ sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zName);
+ }
+ pParse->iSelfTab = 0;
+}
+#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
+
+
+#ifndef SQLITE_OMIT_AUTOINCREMENT
+/*
+** Locate or create an AutoincInfo structure associated with table pTab
+** which is in database iDb. Return the register number for the register
+** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
+** table. (Also return zero when doing a VACUUM since we do not want to
+** update the AUTOINCREMENT counters during a VACUUM.)
+**
+** There is at most one AutoincInfo structure per table even if the
+** same table is autoincremented multiple times due to inserts within
+** triggers. A new AutoincInfo structure is created if this is the
+** first use of table pTab. On 2nd and subsequent uses, the original
+** AutoincInfo structure is used.
+**
+** Four consecutive registers are allocated:
+**
+** (1) The name of the pTab table.
+** (2) The maximum ROWID of pTab.
+** (3) The rowid in sqlite_sequence of pTab
+** (4) The original value of the max ROWID in pTab, or NULL if none
+**
+** The 2nd register is the one that is returned. That is all the
+** insert routine needs to know about.
+*/
+static int autoIncBegin(
+ Parse *pParse, /* Parsing context */
+ int iDb, /* Index of the database holding pTab */
+ Table *pTab /* The table we are writing to */
+){
+ int memId = 0; /* Register holding maximum rowid */
+ assert( pParse->db->aDb[iDb].pSchema!=0 );
+ if( (pTab->tabFlags & TF_Autoincrement)!=0
+ && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
+ ){
+ Parse *pToplevel = sqlite3ParseToplevel(pParse);
+ AutoincInfo *pInfo;
+ Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
+
+ /* Verify that the sqlite_sequence table exists and is an ordinary
+ ** rowid table with exactly two columns.
+ ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
+ if( pSeqTab==0
+ || !HasRowid(pSeqTab)
+ || IsVirtual(pSeqTab)
+ || pSeqTab->nCol!=2
+ ){
+ pParse->nErr++;
+ pParse->rc = SQLITE_CORRUPT_SEQUENCE;
+ return 0;
+ }
+
+ pInfo = pToplevel->pAinc;
+ while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
+ if( pInfo==0 ){
+ pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
+ if( pInfo==0 ) return 0;
+ pInfo->pNext = pToplevel->pAinc;
+ pToplevel->pAinc = pInfo;
+ pInfo->pTab = pTab;
+ pInfo->iDb = iDb;
+ pToplevel->nMem++; /* Register to hold name of table */
+ pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
+ pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
+ }
+ memId = pInfo->regCtr;
+ }
+ return memId;
+}
+
+/*
+** This routine generates code that will initialize all of the
+** register used by the autoincrement tracker.
+*/
+SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
+ AutoincInfo *p; /* Information about an AUTOINCREMENT */
+ sqlite3 *db = pParse->db; /* The database connection */
+ Db *pDb; /* Database only autoinc table */
+ int memId; /* Register holding max rowid */
+ Vdbe *v = pParse->pVdbe; /* VDBE under construction */
+
+ /* This routine is never called during trigger-generation. It is
+ ** only called from the top-level */
+ assert( pParse->pTriggerTab==0 );
+ assert( sqlite3IsToplevel(pParse) );
+
+ assert( v ); /* We failed long ago if this is not so */
+ for(p = pParse->pAinc; p; p = p->pNext){
+ static const int iLn = VDBE_OFFSET_LINENO(2);
+ static const VdbeOpList autoInc[] = {
+ /* 0 */ {OP_Null, 0, 0, 0},
+ /* 1 */ {OP_Rewind, 0, 10, 0},
+ /* 2 */ {OP_Column, 0, 0, 0},
+ /* 3 */ {OP_Ne, 0, 9, 0},
+ /* 4 */ {OP_Rowid, 0, 0, 0},
+ /* 5 */ {OP_Column, 0, 1, 0},
+ /* 6 */ {OP_AddImm, 0, 0, 0},
+ /* 7 */ {OP_Copy, 0, 0, 0},
+ /* 8 */ {OP_Goto, 0, 11, 0},
+ /* 9 */ {OP_Next, 0, 2, 0},
+ /* 10 */ {OP_Integer, 0, 0, 0},
+ /* 11 */ {OP_Close, 0, 0, 0}
+ };
+ VdbeOp *aOp;
+ pDb = &db->aDb[p->iDb];
+ memId = p->regCtr;
+ assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
+ sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
+ sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
+ aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
+ if( aOp==0 ) break;
+ aOp[0].p2 = memId;
+ aOp[0].p3 = memId+2;
+ aOp[2].p3 = memId;
+ aOp[3].p1 = memId-1;
+ aOp[3].p3 = memId;
+ aOp[3].p5 = SQLITE_JUMPIFNULL;
+ aOp[4].p2 = memId+1;
+ aOp[5].p3 = memId;
+ aOp[6].p1 = memId;
+ aOp[7].p2 = memId+2;
+ aOp[7].p1 = memId;
+ aOp[10].p2 = memId;
+ if( pParse->nTab==0 ) pParse->nTab = 1;
+ }
+}
+
+/*
+** Update the maximum rowid for an autoincrement calculation.
+**
+** This routine should be called when the regRowid register holds a
+** new rowid that is about to be inserted. If that new rowid is
+** larger than the maximum rowid in the memId memory cell, then the
+** memory cell is updated.
+*/
+static void autoIncStep(Parse *pParse, int memId, int regRowid){
+ if( memId>0 ){
+ sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
+ }
+}
+
+/*
+** This routine generates the code needed to write autoincrement
+** maximum rowid values back into the sqlite_sequence register.
+** Every statement that might do an INSERT into an autoincrement
+** table (either directly or through triggers) needs to call this
+** routine just before the "exit" code.
+*/
+static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
+ AutoincInfo *p;
+ Vdbe *v = pParse->pVdbe;
+ sqlite3 *db = pParse->db;
+
+ assert( v );
+ for(p = pParse->pAinc; p; p = p->pNext){
+ static const int iLn = VDBE_OFFSET_LINENO(2);
+ static const VdbeOpList autoIncEnd[] = {
+ /* 0 */ {OP_NotNull, 0, 2, 0},
+ /* 1 */ {OP_NewRowid, 0, 0, 0},
+ /* 2 */ {OP_MakeRecord, 0, 2, 0},
+ /* 3 */ {OP_Insert, 0, 0, 0},
+ /* 4 */ {OP_Close, 0, 0, 0}
+ };
+ VdbeOp *aOp;
+ Db *pDb = &db->aDb[p->iDb];
+ int iRec;
+ int memId = p->regCtr;
+
+ iRec = sqlite3GetTempReg(pParse);
+ assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
+ sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
+ VdbeCoverage(v);
+ sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
+ aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
+ if( aOp==0 ) break;
+ aOp[0].p1 = memId+1;
+ aOp[1].p2 = memId+1;
+ aOp[2].p1 = memId-1;
+ aOp[2].p3 = iRec;
+ aOp[3].p2 = iRec;
+ aOp[3].p3 = memId+1;
+ aOp[3].p5 = OPFLAG_APPEND;
+ sqlite3ReleaseTempReg(pParse, iRec);
+ }
+}
+SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
+ if( pParse->pAinc ) autoIncrementEnd(pParse);
+}
+#else
+/*
+** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
+** above are all no-ops
+*/
+# define autoIncBegin(A,B,C) (0)
+# define autoIncStep(A,B,C)
+#endif /* SQLITE_OMIT_AUTOINCREMENT */
+
+
+/* Forward declaration */
+static int xferOptimization(
+ Parse *pParse, /* Parser context */
+ Table *pDest, /* The table we are inserting into */
+ Select *pSelect, /* A SELECT statement to use as the data source */
+ int onError, /* How to handle constraint errors */
+ int iDbDest /* The database of pDest */
+);
+
+/*
+** This routine is called to handle SQL of the following forms:
+**
+** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
+** insert into TABLE (IDLIST) select
+** insert into TABLE (IDLIST) default values
+**
+** The IDLIST following the table name is always optional. If omitted,
+** then a list of all (non-hidden) columns for the table is substituted.
+** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
+** is omitted.
+**
+** For the pSelect parameter holds the values to be inserted for the
+** first two forms shown above. A VALUES clause is really just short-hand
+** for a SELECT statement that omits the FROM clause and everything else
+** that follows. If the pSelect parameter is NULL, that means that the
+** DEFAULT VALUES form of the INSERT statement is intended.
+**
+** The code generated follows one of four templates. For a simple
+** insert with data coming from a single-row VALUES clause, the code executes
+** once straight down through. Pseudo-code follows (we call this
+** the "1st template"):
+**
+** open write cursor to <table> and its indices
+** put VALUES clause expressions into registers
+** write the resulting record into <table>
+** cleanup
+**
+** The three remaining templates assume the statement is of the form
+**
+** INSERT INTO <table> SELECT ...
+**
+** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
+** in other words if the SELECT pulls all columns from a single table
+** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
+** if <table2> and <table1> are distinct tables but have identical
+** schemas, including all the same indices, then a special optimization
+** is invoked that copies raw records from <table2> over to <table1>.
+** See the xferOptimization() function for the implementation of this
+** template. This is the 2nd template.
+**
+** open a write cursor to <table>
+** open read cursor on <table2>
+** transfer all records in <table2> over to <table>
+** close cursors
+** foreach index on <table>
+** open a write cursor on the <table> index
+** open a read cursor on the corresponding <table2> index
+** transfer all records from the read to the write cursors
+** close cursors
+** end foreach
+**
+** The 3rd template is for when the second template does not apply
+** and the SELECT clause does not read from <table> at any time.
+** The generated code follows this template:
+**
+** X <- A
+** goto B
+** A: setup for the SELECT
+** loop over the rows in the SELECT
+** load values into registers R..R+n
+** yield X
+** end loop
+** cleanup after the SELECT
+** end-coroutine X
+** B: open write cursor to <table> and its indices
+** C: yield X, at EOF goto D
+** insert the select result into <table> from R..R+n
+** goto C
+** D: cleanup
+**
+** The 4th template is used if the insert statement takes its
+** values from a SELECT but the data is being inserted into a table
+** that is also read as part of the SELECT. In the third form,
+** we have to use an intermediate table to store the results of
+** the select. The template is like this:
+**
+** X <- A
+** goto B
+** A: setup for the SELECT
+** loop over the tables in the SELECT
+** load value into register R..R+n
+** yield X
+** end loop
+** cleanup after the SELECT
+** end co-routine R
+** B: open temp table
+** L: yield X, at EOF goto M
+** insert row from R..R+n into temp table
+** goto L
+** M: open write cursor to <table> and its indices
+** rewind temp table
+** C: loop over rows of intermediate table
+** transfer values form intermediate table into <table>
+** end loop
+** D: cleanup
+*/
+SQLITE_PRIVATE void sqlite3Insert(
+ Parse *pParse, /* Parser context */
+ SrcList *pTabList, /* Name of table into which we are inserting */
+ Select *pSelect, /* A SELECT statement to use as the data source */
+ IdList *pColumn, /* Column names corresponding to IDLIST, or NULL. */
+ int onError, /* How to handle constraint errors */
+ Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */
+){
+ sqlite3 *db; /* The main database structure */
+ Table *pTab; /* The table to insert into. aka TABLE */
+ int i, j; /* Loop counters */
+ Vdbe *v; /* Generate code into this virtual machine */
+ Index *pIdx; /* For looping over indices of the table */
+ int nColumn; /* Number of columns in the data */
+ int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
+ int iDataCur = 0; /* VDBE cursor that is the main data repository */
+ int iIdxCur = 0; /* First index cursor */
+ int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
+ int endOfLoop; /* Label for the end of the insertion loop */
+ int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
+ int addrInsTop = 0; /* Jump to label "D" */
+ int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
+ SelectDest dest; /* Destination for SELECT on rhs of INSERT */
+ int iDb; /* Index of database holding TABLE */
+ u8 useTempTable = 0; /* Store SELECT results in intermediate table */
+ u8 appendFlag = 0; /* True if the insert is likely to be an append */
+ u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
+ u8 bIdListInOrder; /* True if IDLIST is in table order */
+ ExprList *pList = 0; /* List of VALUES() to be inserted */
+ int iRegStore; /* Register in which to store next column */
+
+ /* Register allocations */
+ int regFromSelect = 0;/* Base register for data coming from SELECT */
+ int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
+ int regRowCount = 0; /* Memory cell used for the row counter */
+ int regIns; /* Block of regs holding rowid+data being inserted */
+ int regRowid; /* registers holding insert rowid */
+ int regData; /* register holding first column to insert */
+ int *aRegIdx = 0; /* One register allocated to each index */
+
+#ifndef SQLITE_OMIT_TRIGGER
+ int isView; /* True if attempting to insert into a view */
+ Trigger *pTrigger; /* List of triggers on pTab, if required */
+ int tmask; /* Mask of trigger times */
+#endif
+
+ db = pParse->db;
+ if( pParse->nErr || db->mallocFailed ){
+ goto insert_cleanup;
+ }
+ dest.iSDParm = 0; /* Suppress a harmless compiler warning */
+
+ /* If the Select object is really just a simple VALUES() list with a
+ ** single row (the common case) then keep that one row of values
+ ** and discard the other (unused) parts of the pSelect object
+ */
+ if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
+ pList = pSelect->pEList;
+ pSelect->pEList = 0;
+ sqlite3SelectDelete(db, pSelect);
+ pSelect = 0;
+ }
+
+ /* Locate the table into which we will be inserting new information.
+ */
+ assert( pTabList->nSrc==1 );
+ pTab = sqlite3SrcListLookup(pParse, pTabList);
+ if( pTab==0 ){
+ goto insert_cleanup;
+ }
+ iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ assert( iDb<db->nDb );
+ if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
+ db->aDb[iDb].zDbSName) ){
+ goto insert_cleanup;
+ }
+ withoutRowid = !HasRowid(pTab);
+
+ /* Figure out if we have any triggers and if the table being
+ ** inserted into is a view
+ */
+#ifndef SQLITE_OMIT_TRIGGER
+ pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
+ isView = pTab->pSelect!=0;
+#else
+# define pTrigger 0
+# define tmask 0
+# define isView 0
+#endif
+#ifdef SQLITE_OMIT_VIEW
+# undef isView
+# define isView 0
+#endif
+ assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
+
+ /* If pTab is really a view, make sure it has been initialized.
+ ** ViewGetColumnNames() is a no-op if pTab is not a view.
+ */
+ if( sqlite3ViewGetColumnNames(pParse, pTab) ){
+ goto insert_cleanup;
+ }
+
+ /* Cannot insert into a read-only table.
+ */
+ if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
+ goto insert_cleanup;
+ }
+
+ /* Allocate a VDBE
+ */
+ v = sqlite3GetVdbe(pParse);
+ if( v==0 ) goto insert_cleanup;
+ if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
+ sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
+
+#ifndef SQLITE_OMIT_XFER_OPT
+ /* If the statement is of the form
+ **
+ ** INSERT INTO <table1> SELECT * FROM <table2>;
+ **
+ ** Then special optimizations can be applied that make the transfer
+ ** very fast and which reduce fragmentation of indices.
+ **
+ ** This is the 2nd template.
+ */
+ if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
+ assert( !pTrigger );
+ assert( pList==0 );
+ goto insert_end;
+ }
+#endif /* SQLITE_OMIT_XFER_OPT */
+
+ /* If this is an AUTOINCREMENT table, look up the sequence number in the
+ ** sqlite_sequence table and store it in memory cell regAutoinc.
+ */
+ regAutoinc = autoIncBegin(pParse, iDb, pTab);
+
+ /* Allocate a block registers to hold the rowid and the values
+ ** for all columns of the new row.
+ */
+ regRowid = regIns = pParse->nMem+1;
+ pParse->nMem += pTab->nCol + 1;
+ if( IsVirtual(pTab) ){
+ regRowid++;
+ pParse->nMem++;
+ }
+ regData = regRowid+1;
+
+ /* If the INSERT statement included an IDLIST term, then make sure
+ ** all elements of the IDLIST really are columns of the table and
+ ** remember the column indices.
+ **
+ ** If the table has an INTEGER PRIMARY KEY column and that column
+ ** is named in the IDLIST, then record in the ipkColumn variable
+ ** the index into IDLIST of the primary key column. ipkColumn is
+ ** the index of the primary key as it appears in IDLIST, not as
+ ** is appears in the original table. (The index of the INTEGER
+ ** PRIMARY KEY in the original table is pTab->iPKey.) After this
+ ** loop, if ipkColumn==(-1), that means that integer primary key
+ ** is unspecified, and hence the table is either WITHOUT ROWID or
+ ** it will automatically generated an integer primary key.
+ **
+ ** bIdListInOrder is true if the columns in IDLIST are in storage
+ ** order. This enables an optimization that avoids shuffling the
+ ** columns into storage order. False negatives are harmless,
+ ** but false positives will cause database corruption.
+ */
+ bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
+ if( pColumn ){
+ for(i=0; i<pColumn->nId; i++){
+ pColumn->a[i].idx = -1;
+ }
+ for(i=0; i<pColumn->nId; i++){
+ for(j=0; j<pTab->nCol; j++){
+ if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
+ pColumn->a[i].idx = j;
+ if( i!=j ) bIdListInOrder = 0;
+ if( j==pTab->iPKey ){
+ ipkColumn = i; assert( !withoutRowid );
+ }
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
+ sqlite3ErrorMsg(pParse,
+ "cannot INSERT into generated column \"%s\"",
+ pTab->aCol[j].zName);
+ goto insert_cleanup;
+ }
+#endif
+ break;
+ }
+ }
+ if( j>=pTab->nCol ){
+ if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
+ ipkColumn = i;
+ bIdListInOrder = 0;
+ }else{
+ sqlite3ErrorMsg(pParse, "table %S has no column named %s",
+ pTabList, 0, pColumn->a[i].zName);
+ pParse->checkSchema = 1;
+ goto insert_cleanup;
+ }
+ }
+ }
+ }
+
+ /* Figure out how many columns of data are supplied. If the data
+ ** is coming from a SELECT statement, then generate a co-routine that
+ ** produces a single row of the SELECT on each invocation. The
+ ** co-routine is the common header to the 3rd and 4th templates.
+ */
+ if( pSelect ){
+ /* Data is coming from a SELECT or from a multi-row VALUES clause.
+ ** Generate a co-routine to run the SELECT. */
+ int regYield; /* Register holding co-routine entry-point */
+ int addrTop; /* Top of the co-routine */
+ int rc; /* Result code */
+
+ regYield = ++pParse->nMem;
+ addrTop = sqlite3VdbeCurrentAddr(v) + 1;
+ sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
+ sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
+ dest.iSdst = bIdListInOrder ? regData : 0;
+ dest.nSdst = pTab->nCol;
+ rc = sqlite3Select(pParse, pSelect, &dest);
+ regFromSelect = dest.iSdst;
+ if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
+ sqlite3VdbeEndCoroutine(v, regYield);
+ sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
+ assert( pSelect->pEList );
+ nColumn = pSelect->pEList->nExpr;
+
+ /* Set useTempTable to TRUE if the result of the SELECT statement
+ ** should be written into a temporary table (template 4). Set to
+ ** FALSE if each output row of the SELECT can be written directly into
+ ** the destination table (template 3).
+ **
+ ** A temp table must be used if the table being updated is also one
+ ** of the tables being read by the SELECT statement. Also use a
+ ** temp table in the case of row triggers.
+ */
+ if( pTrigger || readsTable(pParse, iDb, pTab) ){
+ useTempTable = 1;
+ }
+
+ if( useTempTable ){
+ /* Invoke the coroutine to extract information from the SELECT
+ ** and add it to a transient table srcTab. The code generated
+ ** here is from the 4th template:
+ **
+ ** B: open temp table
+ ** L: yield X, goto M at EOF
+ ** insert row from R..R+n into temp table
+ ** goto L
+ ** M: ...
+ */
+ int regRec; /* Register to hold packed record */
+ int regTempRowid; /* Register to hold temp table ROWID */
+ int addrL; /* Label "L" */
+
+ srcTab = pParse->nTab++;
+ regRec = sqlite3GetTempReg(pParse);
+ regTempRowid = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
+ addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
+ sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
+ sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
+ sqlite3VdbeGoto(v, addrL);
+ sqlite3VdbeJumpHere(v, addrL);
+ sqlite3ReleaseTempReg(pParse, regRec);
+ sqlite3ReleaseTempReg(pParse, regTempRowid);
+ }
+ }else{
+ /* This is the case if the data for the INSERT is coming from a
+ ** single-row VALUES clause
+ */
+ NameContext sNC;
+ memset(&sNC, 0, sizeof(sNC));
+ sNC.pParse = pParse;
+ srcTab = -1;
+ assert( useTempTable==0 );
+ if( pList ){
+ nColumn = pList->nExpr;
+ if( sqlite3ResolveExprListNames(&sNC, pList) ){
+ goto insert_cleanup;
+ }
+ }else{
+ nColumn = 0;
+ }
+ }
+
+ /* If there is no IDLIST term but the table has an integer primary
+ ** key, the set the ipkColumn variable to the integer primary key
+ ** column index in the original table definition.
+ */
+ if( pColumn==0 && nColumn>0 ){
+ ipkColumn = pTab->iPKey;
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
+ testcase( pTab->tabFlags & TF_HasVirtual );
+ testcase( pTab->tabFlags & TF_HasStored );
+ for(i=ipkColumn-1; i>=0; i--){
+ if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
+ testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
+ testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
+ ipkColumn--;
+ }
+ }
+ }
+#endif
+ }
+
+ /* Make sure the number of columns in the source data matches the number
+ ** of columns to be inserted into the table.
+ */
+ for(i=0; i<pTab->nCol; i++){
+ if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
+ }
+ if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
+ sqlite3ErrorMsg(pParse,
+ "table %S has %d columns but %d values were supplied",
+ pTabList, 0, pTab->nCol-nHidden, nColumn);
+ goto insert_cleanup;
+ }
+ if( pColumn!=0 && nColumn!=pColumn->nId ){
+ sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
+ goto insert_cleanup;
+ }
+
+ /* Initialize the count of rows to be inserted
+ */
+ if( (db->flags & SQLITE_CountRows)!=0
+ && !pParse->nested
+ && !pParse->pTriggerTab
+ ){
+ regRowCount = ++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
+ }
+
+ /* If this is not a view, open the table and and all indices */
+ if( !isView ){
+ int nIdx;
+ nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
+ &iDataCur, &iIdxCur);
+ aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
+ if( aRegIdx==0 ){
+ goto insert_cleanup;
+ }
+ for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
+ assert( pIdx );
+ aRegIdx[i] = ++pParse->nMem;
+ pParse->nMem += pIdx->nColumn;
+ }
+ aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */
+ }
+#ifndef SQLITE_OMIT_UPSERT
+ if( pUpsert ){
+ if( IsVirtual(pTab) ){
+ sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
+ pTab->zName);
+ goto insert_cleanup;
+ }
+ if( pTab->pSelect ){
+ sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
+ goto insert_cleanup;
+ }
+ if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
+ goto insert_cleanup;
+ }
+ pTabList->a[0].iCursor = iDataCur;
+ pUpsert->pUpsertSrc = pTabList;
+ pUpsert->regData = regData;
+ pUpsert->iDataCur = iDataCur;
+ pUpsert->iIdxCur = iIdxCur;
+ if( pUpsert->pUpsertTarget ){
+ sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert);
+ }
+ }
+#endif
+
+
+ /* This is the top of the main insertion loop */
+ if( useTempTable ){
+ /* This block codes the top of loop only. The complete loop is the
+ ** following pseudocode (template 4):
+ **
+ ** rewind temp table, if empty goto D
+ ** C: loop over rows of intermediate table
+ ** transfer values form intermediate table into <table>
+ ** end loop
+ ** D: ...
+ */
+ addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
+ addrCont = sqlite3VdbeCurrentAddr(v);
+ }else if( pSelect ){
+ /* This block codes the top of loop only. The complete loop is the
+ ** following pseudocode (template 3):
+ **
+ ** C: yield X, at EOF goto D
+ ** insert the select result into <table> from R..R+n
+ ** goto C
+ ** D: ...
+ */
+ sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
+ addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
+ VdbeCoverage(v);
+ if( ipkColumn>=0 ){
+ /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
+ ** SELECT, go ahead and copy the value into the rowid slot now, so that
+ ** the value does not get overwritten by a NULL at tag-20191021-002. */
+ sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
+ }
+ }
+
+ /* Compute data for ordinary columns of the new entry. Values
+ ** are written in storage order into registers starting with regData.
+ ** Only ordinary columns are computed in this loop. The rowid
+ ** (if there is one) is computed later and generated columns are
+ ** computed after the rowid since they might depend on the value
+ ** of the rowid.
+ */
+ nHidden = 0;
+ iRegStore = regData; assert( regData==regRowid+1 );
+ for(i=0; i<pTab->nCol; i++, iRegStore++){
+ int k;
+ u32 colFlags;
+ assert( i>=nHidden );
+ if( i==pTab->iPKey ){
+ /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
+ ** using the rowid. So put a NULL in the IPK slot of the record to avoid
+ ** using excess space. The file format definition requires this extra
+ ** NULL - we cannot optimize further by skipping the column completely */
+ sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
+ continue;
+ }
+ if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
+ nHidden++;
+ if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
+ /* Virtual columns do not participate in OP_MakeRecord. So back up
+ ** iRegStore by one slot to compensate for the iRegStore++ in the
+ ** outer for() loop */
+ iRegStore--;
+ continue;
+ }else if( (colFlags & COLFLAG_STORED)!=0 ){
+ /* Stored columns are computed later. But if there are BEFORE
+ ** triggers, the slots used for stored columns will be OP_Copy-ed
+ ** to a second block of registers, so the register needs to be
+ ** initialized to NULL to avoid an uninitialized register read */
+ if( tmask & TRIGGER_BEFORE ){
+ sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
+ }
+ continue;
+ }else if( pColumn==0 ){
+ /* Hidden columns that are not explicitly named in the INSERT
+ ** get there default value */
+ sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
+ continue;
+ }
+ }
+ if( pColumn ){
+ for(j=0; j<pColumn->nId && pColumn->a[j].idx!=i; j++){}
+ if( j>=pColumn->nId ){
+ /* A column not named in the insert column list gets its
+ ** default value */
+ sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
+ continue;
+ }
+ k = j;
+ }else if( nColumn==0 ){
+ /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */
+ sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
+ continue;
+ }else{
+ k = i - nHidden;
+ }
+
+ if( useTempTable ){
+ sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
+ }else if( pSelect ){
+ if( regFromSelect!=regData ){
+ sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
+ }
+ }else{
+ sqlite3ExprCode(pParse, pList->a[k].pExpr, iRegStore);
+ }
+ }
+
+
+ /* Run the BEFORE and INSTEAD OF triggers, if there are any
+ */
+ endOfLoop = sqlite3VdbeMakeLabel(pParse);
+ if( tmask & TRIGGER_BEFORE ){
+ int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
+
+ /* build the NEW.* reference row. Note that if there is an INTEGER
+ ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
+ ** translated into a unique ID for the row. But on a BEFORE trigger,
+ ** we do not know what the unique ID will be (because the insert has
+ ** not happened yet) so we substitute a rowid of -1
+ */
+ if( ipkColumn<0 ){
+ sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
+ }else{
+ int addr1;
+ assert( !withoutRowid );
+ if( useTempTable ){
+ sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
+ }else{
+ assert( pSelect==0 ); /* Otherwise useTempTable is true */
+ sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
+ }
+ addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
+ sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
+ sqlite3VdbeJumpHere(v, addr1);
+ sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
+ }
+
+ /* Cannot have triggers on a virtual table. If it were possible,
+ ** this block would have to account for hidden column.
+ */
+ assert( !IsVirtual(pTab) );
+
+ /* Copy the new data already generated. */
+ assert( pTab->nNVCol>0 );
+ sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
+
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ /* Compute the new value for generated columns after all other
+ ** columns have already been computed. This must be done after
+ ** computing the ROWID in case one of the generated columns
+ ** refers to the ROWID. */
+ if( pTab->tabFlags & TF_HasGenerated ){
+ testcase( pTab->tabFlags & TF_HasVirtual );
+ testcase( pTab->tabFlags & TF_HasStored );
+ sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
+ }
+#endif
+
+ /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
+ ** do not attempt any conversions before assembling the record.
+ ** If this is a real table, attempt conversions as required by the
+ ** table column affinities.
+ */
+ if( !isView ){
+ sqlite3TableAffinity(v, pTab, regCols+1);
+ }
+
+ /* Fire BEFORE or INSTEAD OF triggers */
+ sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
+ pTab, regCols-pTab->nCol-1, onError, endOfLoop);
+
+ sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
+ }
+
+ if( !isView ){
+ if( IsVirtual(pTab) ){
+ /* The row that the VUpdate opcode will delete: none */
+ sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
+ }
+ if( ipkColumn>=0 ){
+ /* Compute the new rowid */
+ if( useTempTable ){
+ sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
+ }else if( pSelect ){
+ /* Rowid already initialized at tag-20191021-001 */
+ }else{
+ Expr *pIpk = pList->a[ipkColumn].pExpr;
+ if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
+ sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
+ appendFlag = 1;
+ }else{
+ sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
+ }
+ }
+ /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
+ ** to generate a unique primary key value.
+ */
+ if( !appendFlag ){
+ int addr1;
+ if( !IsVirtual(pTab) ){
+ addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
+ sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
+ sqlite3VdbeJumpHere(v, addr1);
+ }else{
+ addr1 = sqlite3VdbeCurrentAddr(v);
+ sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
+ }
+ sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
+ }
+ }else if( IsVirtual(pTab) || withoutRowid ){
+ sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
+ }else{
+ sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
+ appendFlag = 1;
+ }
+ autoIncStep(pParse, regAutoinc, regRowid);
+
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ /* Compute the new value for generated columns after all other
+ ** columns have already been computed. This must be done after
+ ** computing the ROWID in case one of the generated columns
+ ** is derived from the INTEGER PRIMARY KEY. */
+ if( pTab->tabFlags & TF_HasGenerated ){
+ sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
+ }
+#endif
+
+ /* Generate code to check constraints and generate index keys and
+ ** do the insertion.
+ */
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( IsVirtual(pTab) ){
+ const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
+ sqlite3VtabMakeWritable(pParse, pTab);
+ sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
+ sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
+ sqlite3MayAbort(pParse);
+ }else
+#endif
+ {
+ int isReplace; /* Set to true if constraints may cause a replace */
+ int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
+ sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
+ regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
+ );
+ sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
+
+ /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
+ ** constraints or (b) there are no triggers and this table is not a
+ ** parent table in a foreign key constraint. It is safe to set the
+ ** flag in the second case as if any REPLACE constraint is hit, an
+ ** OP_Delete or OP_IdxDelete instruction will be executed on each
+ ** cursor that is disturbed. And these instructions both clear the
+ ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
+ ** functionality. */
+ bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
+ sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
+ regIns, aRegIdx, 0, appendFlag, bUseSeek
+ );
+ }
+ }
+
+ /* Update the count of rows that are inserted
+ */
+ if( regRowCount ){
+ sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
+ }
+
+ if( pTrigger ){
+ /* Code AFTER triggers */
+ sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
+ pTab, regData-2-pTab->nCol, onError, endOfLoop);
+ }
+
+ /* The bottom of the main insertion loop, if the data source
+ ** is a SELECT statement.
+ */
+ sqlite3VdbeResolveLabel(v, endOfLoop);
+ if( useTempTable ){
+ sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
+ sqlite3VdbeJumpHere(v, addrInsTop);
+ sqlite3VdbeAddOp1(v, OP_Close, srcTab);
+ }else if( pSelect ){
+ sqlite3VdbeGoto(v, addrCont);
+#ifdef SQLITE_DEBUG
+ /* If we are jumping back to an OP_Yield that is preceded by an
+ ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the
+ ** OP_ReleaseReg will be included in the loop. */
+ if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
+ assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
+ sqlite3VdbeChangeP5(v, 1);
+ }
+#endif
+ sqlite3VdbeJumpHere(v, addrInsTop);
+ }
+
+insert_end:
+ /* Update the sqlite_sequence table by storing the content of the
+ ** maximum rowid counter values recorded while inserting into
+ ** autoincrement tables.
+ */
+ if( pParse->nested==0 && pParse->pTriggerTab==0 ){
+ sqlite3AutoincrementEnd(pParse);
+ }
+
+ /*
+ ** Return the number of rows inserted. If this routine is
+ ** generating code because of a call to sqlite3NestedParse(), do not
+ ** invoke the callback function.
+ */
+ if( regRowCount ){
+ sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
+ sqlite3VdbeSetNumCols(v, 1);
+ sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
+ }
+
+insert_cleanup:
+ sqlite3SrcListDelete(db, pTabList);
+ sqlite3ExprListDelete(db, pList);
+ sqlite3UpsertDelete(db, pUpsert);
+ sqlite3SelectDelete(db, pSelect);
+ sqlite3IdListDelete(db, pColumn);
+ sqlite3DbFree(db, aRegIdx);
+}
+
+/* Make sure "isView" and other macros defined above are undefined. Otherwise
+** they may interfere with compilation of other functions in this file
+** (or in another file, if this file becomes part of the amalgamation). */
+#ifdef isView
+ #undef isView
+#endif
+#ifdef pTrigger
+ #undef pTrigger
+#endif
+#ifdef tmask
+ #undef tmask
+#endif
+
+/*
+** Meanings of bits in of pWalker->eCode for
+** sqlite3ExprReferencesUpdatedColumn()
+*/
+#define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
+#define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
+
+/* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
+* Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
+** expression node references any of the
+** columns that are being modifed by an UPDATE statement.
+*/
+static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
+ if( pExpr->op==TK_COLUMN ){
+ assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
+ if( pExpr->iColumn>=0 ){
+ if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
+ pWalker->eCode |= CKCNSTRNT_COLUMN;
+ }
+ }else{
+ pWalker->eCode |= CKCNSTRNT_ROWID;
+ }
+ }
+ return WRC_Continue;
+}
+
+/*
+** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
+** only columns that are modified by the UPDATE are those for which
+** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
+**
+** Return true if CHECK constraint pExpr uses any of the
+** changing columns (or the rowid if it is changing). In other words,
+** return true if this CHECK constraint must be validated for
+** the new row in the UPDATE statement.
+**
+** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
+** The operation of this routine is the same - return true if an only if
+** the expression uses one or more of columns identified by the second and
+** third arguments.
+*/
+SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(
+ Expr *pExpr, /* The expression to be checked */
+ int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */
+ int chngRowid /* True if UPDATE changes the rowid */
+){
+ Walker w;
+ memset(&w, 0, sizeof(w));
+ w.eCode = 0;
+ w.xExprCallback = checkConstraintExprNode;
+ w.u.aiCol = aiChng;
+ sqlite3WalkExpr(&w, pExpr);
+ if( !chngRowid ){
+ testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
+ w.eCode &= ~CKCNSTRNT_ROWID;
+ }
+ testcase( w.eCode==0 );
+ testcase( w.eCode==CKCNSTRNT_COLUMN );
+ testcase( w.eCode==CKCNSTRNT_ROWID );
+ testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
+ return w.eCode!=0;
+}
+
+/*
+** Generate code to do constraint checks prior to an INSERT or an UPDATE
+** on table pTab.
+**
+** The regNewData parameter is the first register in a range that contains
+** the data to be inserted or the data after the update. There will be
+** pTab->nCol+1 registers in this range. The first register (the one
+** that regNewData points to) will contain the new rowid, or NULL in the
+** case of a WITHOUT ROWID table. The second register in the range will
+** contain the content of the first table column. The third register will
+** contain the content of the second table column. And so forth.
+**
+** The regOldData parameter is similar to regNewData except that it contains
+** the data prior to an UPDATE rather than afterwards. regOldData is zero
+** for an INSERT. This routine can distinguish between UPDATE and INSERT by
+** checking regOldData for zero.
+**
+** For an UPDATE, the pkChng boolean is true if the true primary key (the
+** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
+** might be modified by the UPDATE. If pkChng is false, then the key of
+** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
+**
+** For an INSERT, the pkChng boolean indicates whether or not the rowid
+** was explicitly specified as part of the INSERT statement. If pkChng
+** is zero, it means that the either rowid is computed automatically or
+** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
+** pkChng will only be true if the INSERT statement provides an integer
+** value for either the rowid column or its INTEGER PRIMARY KEY alias.
+**
+** The code generated by this routine will store new index entries into
+** registers identified by aRegIdx[]. No index entry is created for
+** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
+** the same as the order of indices on the linked list of indices
+** at pTab->pIndex.
+**
+** (2019-05-07) The generated code also creates a new record for the
+** main table, if pTab is a rowid table, and stores that record in the
+** register identified by aRegIdx[nIdx] - in other words in the first
+** entry of aRegIdx[] past the last index. It is important that the
+** record be generated during constraint checks to avoid affinity changes
+** to the register content that occur after constraint checks but before
+** the new record is inserted.
+**
+** The caller must have already opened writeable cursors on the main
+** table and all applicable indices (that is to say, all indices for which
+** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
+** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
+** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
+** for the first index in the pTab->pIndex list. Cursors for other indices
+** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
+**
+** This routine also generates code to check constraints. NOT NULL,
+** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
+** then the appropriate action is performed. There are five possible
+** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
+**
+** Constraint type Action What Happens
+** --------------- ---------- ----------------------------------------
+** any ROLLBACK The current transaction is rolled back and
+** sqlite3_step() returns immediately with a
+** return code of SQLITE_CONSTRAINT.
+**
+** any ABORT Back out changes from the current command
+** only (do not do a complete rollback) then
+** cause sqlite3_step() to return immediately
+** with SQLITE_CONSTRAINT.
+**
+** any FAIL Sqlite3_step() returns immediately with a
+** return code of SQLITE_CONSTRAINT. The
+** transaction is not rolled back and any
+** changes to prior rows are retained.
+**
+** any IGNORE The attempt in insert or update the current
+** row is skipped, without throwing an error.
+** Processing continues with the next row.
+** (There is an immediate jump to ignoreDest.)
+**
+** NOT NULL REPLACE The NULL value is replace by the default
+** value for that column. If the default value
+** is NULL, the action is the same as ABORT.
+**
+** UNIQUE REPLACE The other row that conflicts with the row
+** being inserted is removed.
+**
+** CHECK REPLACE Illegal. The results in an exception.
+**
+** Which action to take is determined by the overrideError parameter.
+** Or if overrideError==OE_Default, then the pParse->onError parameter
+** is used. Or if pParse->onError==OE_Default then the onError value
+** for the constraint is used.
+*/
+SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
+ Parse *pParse, /* The parser context */
+ Table *pTab, /* The table being inserted or updated */
+ int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
+ int iDataCur, /* Canonical data cursor (main table or PK index) */
+ int iIdxCur, /* First index cursor */
+ int regNewData, /* First register in a range holding values to insert */
+ int regOldData, /* Previous content. 0 for INSERTs */
+ u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
+ u8 overrideError, /* Override onError to this if not OE_Default */
+ int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
+ int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
+ int *aiChng, /* column i is unchanged if aiChng[i]<0 */
+ Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */
+){
+ Vdbe *v; /* VDBE under constrution */
+ Index *pIdx; /* Pointer to one of the indices */
+ Index *pPk = 0; /* The PRIMARY KEY index */
+ sqlite3 *db; /* Database connection */
+ int i; /* loop counter */
+ int ix; /* Index loop counter */
+ int nCol; /* Number of columns */
+ int onError; /* Conflict resolution strategy */
+ int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
+ int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
+ Index *pUpIdx = 0; /* Index to which to apply the upsert */
+ u8 isUpdate; /* True if this is an UPDATE operation */
+ u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
+ int upsertBypass = 0; /* Address of Goto to bypass upsert subroutine */
+ int upsertJump = 0; /* Address of Goto that jumps into upsert subroutine */
+ int ipkTop = 0; /* Top of the IPK uniqueness check */
+ int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */
+ /* Variables associated with retesting uniqueness constraints after
+ ** replace triggers fire have run */
+ int regTrigCnt; /* Register used to count replace trigger invocations */
+ int addrRecheck = 0; /* Jump here to recheck all uniqueness constraints */
+ int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
+ Trigger *pTrigger; /* List of DELETE triggers on the table pTab */
+ int nReplaceTrig = 0; /* Number of replace triggers coded */
+
+ isUpdate = regOldData!=0;
+ db = pParse->db;
+ v = pParse->pVdbe;
+ assert( v!=0 );
+ assert( pTab->pSelect==0 ); /* This table is not a VIEW */
+ nCol = pTab->nCol;
+
+ /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
+ ** normal rowid tables. nPkField is the number of key fields in the
+ ** pPk index or 1 for a rowid table. In other words, nPkField is the
+ ** number of fields in the true primary key of the table. */
+ if( HasRowid(pTab) ){
+ pPk = 0;
+ nPkField = 1;
+ }else{
+ pPk = sqlite3PrimaryKeyIndex(pTab);
+ nPkField = pPk->nKeyCol;
+ }
+
+ /* Record that this module has started */
+ VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
+ iDataCur, iIdxCur, regNewData, regOldData, pkChng));
+
+ /* Test all NOT NULL constraints.
+ */
+ if( pTab->tabFlags & TF_HasNotNull ){
+ int b2ndPass = 0; /* True if currently running 2nd pass */
+ int nSeenReplace = 0; /* Number of ON CONFLICT REPLACE operations */
+ int nGenerated = 0; /* Number of generated columns with NOT NULL */
+ while(1){ /* Make 2 passes over columns. Exit loop via "break" */
+ for(i=0; i<nCol; i++){
+ int iReg; /* Register holding column value */
+ Column *pCol = &pTab->aCol[i]; /* The column to check for NOT NULL */
+ int isGenerated; /* non-zero if column is generated */
+ onError = pCol->notNull;
+ if( onError==OE_None ) continue; /* No NOT NULL on this column */
+ if( i==pTab->iPKey ){
+ continue; /* ROWID is never NULL */
+ }
+ isGenerated = pCol->colFlags & COLFLAG_GENERATED;
+ if( isGenerated && !b2ndPass ){
+ nGenerated++;
+ continue; /* Generated columns processed on 2nd pass */
+ }
+ if( aiChng && aiChng[i]<0 && !isGenerated ){
+ /* Do not check NOT NULL on columns that do not change */
+ continue;
+ }
+ if( overrideError!=OE_Default ){
+ onError = overrideError;
+ }else if( onError==OE_Default ){
+ onError = OE_Abort;
+ }
+ if( onError==OE_Replace ){
+ if( b2ndPass /* REPLACE becomes ABORT on the 2nd pass */
+ || pCol->pDflt==0 /* REPLACE is ABORT if no DEFAULT value */
+ ){
+ testcase( pCol->colFlags & COLFLAG_VIRTUAL );
+ testcase( pCol->colFlags & COLFLAG_STORED );
+ testcase( pCol->colFlags & COLFLAG_GENERATED );
+ onError = OE_Abort;
+ }else{
+ assert( !isGenerated );
+ }
+ }else if( b2ndPass && !isGenerated ){
+ continue;
+ }
+ assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
+ || onError==OE_Ignore || onError==OE_Replace );
+ testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
+ iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
+ switch( onError ){
+ case OE_Replace: {
+ int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);
+ VdbeCoverage(v);
+ assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
+ nSeenReplace++;
+ sqlite3ExprCodeCopy(pParse, pCol->pDflt, iReg);
+ sqlite3VdbeJumpHere(v, addr1);
+ break;
+ }
+ case OE_Abort:
+ sqlite3MayAbort(pParse);
+ /* no break */ deliberate_fall_through
+ case OE_Rollback:
+ case OE_Fail: {
+ char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
+ pCol->zName);
+ sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
+ onError, iReg);
+ sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
+ sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
+ VdbeCoverage(v);
+ break;
+ }
+ default: {
+ assert( onError==OE_Ignore );
+ sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
+ VdbeCoverage(v);
+ break;
+ }
+ } /* end switch(onError) */
+ } /* end loop i over columns */
+ if( nGenerated==0 && nSeenReplace==0 ){
+ /* If there are no generated columns with NOT NULL constraints
+ ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single
+ ** pass is sufficient */
+ break;
+ }
+ if( b2ndPass ) break; /* Never need more than 2 passes */
+ b2ndPass = 1;
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
+ /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the
+ ** first pass, recomputed values for all generated columns, as
+ ** those values might depend on columns affected by the REPLACE.
+ */
+ sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);
+ }
+#endif
+ } /* end of 2-pass loop */
+ } /* end if( has-not-null-constraints ) */
+
+ /* Test all CHECK constraints
+ */
+#ifndef SQLITE_OMIT_CHECK
+ if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
+ ExprList *pCheck = pTab->pCheck;
+ pParse->iSelfTab = -(regNewData+1);
+ onError = overrideError!=OE_Default ? overrideError : OE_Abort;
+ for(i=0; i<pCheck->nExpr; i++){
+ int allOk;
+ Expr *pCopy;
+ Expr *pExpr = pCheck->a[i].pExpr;
+ if( aiChng
+ && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
+ ){
+ /* The check constraints do not reference any of the columns being
+ ** updated so there is no point it verifying the check constraint */
+ continue;
+ }
+ if( bAffinityDone==0 ){
+ sqlite3TableAffinity(v, pTab, regNewData+1);
+ bAffinityDone = 1;
+ }
+ allOk = sqlite3VdbeMakeLabel(pParse);
+ sqlite3VdbeVerifyAbortable(v, onError);
+ pCopy = sqlite3ExprDup(db, pExpr, 0);
+ if( !db->mallocFailed ){
+ sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);
+ }
+ sqlite3ExprDelete(db, pCopy);
+ if( onError==OE_Ignore ){
+ sqlite3VdbeGoto(v, ignoreDest);
+ }else{
+ char *zName = pCheck->a[i].zEName;
+ assert( zName!=0 || pParse->db->mallocFailed );
+ if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
+ sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
+ onError, zName, P4_TRANSIENT,
+ P5_ConstraintCheck);
+ }
+ sqlite3VdbeResolveLabel(v, allOk);
+ }
+ pParse->iSelfTab = 0;
+ }
+#endif /* !defined(SQLITE_OMIT_CHECK) */
+
+ /* UNIQUE and PRIMARY KEY constraints should be handled in the following
+ ** order:
+ **
+ ** (1) OE_Update
+ ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
+ ** (3) OE_Replace
+ **
+ ** OE_Fail and OE_Ignore must happen before any changes are made.
+ ** OE_Update guarantees that only a single row will change, so it
+ ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback
+ ** could happen in any order, but they are grouped up front for
+ ** convenience.
+ **
+ ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
+ ** The order of constraints used to have OE_Update as (2) and OE_Abort
+ ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
+ ** constraint before any others, so it had to be moved.
+ **
+ ** Constraint checking code is generated in this order:
+ ** (A) The rowid constraint
+ ** (B) Unique index constraints that do not have OE_Replace as their
+ ** default conflict resolution strategy
+ ** (C) Unique index that do use OE_Replace by default.
+ **
+ ** The ordering of (2) and (3) is accomplished by making sure the linked
+ ** list of indexes attached to a table puts all OE_Replace indexes last
+ ** in the list. See sqlite3CreateIndex() for where that happens.
+ */
+
+ if( pUpsert ){
+ if( pUpsert->pUpsertTarget==0 ){
+ /* An ON CONFLICT DO NOTHING clause, without a constraint-target.
+ ** Make all unique constraint resolution be OE_Ignore */
+ assert( pUpsert->pUpsertSet==0 );
+ overrideError = OE_Ignore;
+ pUpsert = 0;
+ }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){
+ /* If the constraint-target uniqueness check must be run first.
+ ** Jump to that uniqueness check now */
+ upsertJump = sqlite3VdbeAddOp0(v, OP_Goto);
+ VdbeComment((v, "UPSERT constraint goes first"));
+ }
+ }
+
+ /* Determine if it is possible that triggers (either explicitly coded
+ ** triggers or FK resolution actions) might run as a result of deletes
+ ** that happen when OE_Replace conflict resolution occurs. (Call these
+ ** "replace triggers".) If any replace triggers run, we will need to
+ ** recheck all of the uniqueness constraints after they have all run.
+ ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
+ **
+ ** If replace triggers are a possibility, then
+ **
+ ** (1) Allocate register regTrigCnt and initialize it to zero.
+ ** That register will count the number of replace triggers that
+ ** fire. Constraint recheck only occurs if the number is positive.
+ ** (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
+ ** (3) Initialize addrRecheck and lblRecheckOk
+ **
+ ** The uniqueness rechecking code will create a series of tests to run
+ ** in a second pass. The addrRecheck and lblRecheckOk variables are
+ ** used to link together these tests which are separated from each other
+ ** in the generate bytecode.
+ */
+ if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
+ /* There are not DELETE triggers nor FK constraints. No constraint
+ ** rechecks are needed. */
+ pTrigger = 0;
+ regTrigCnt = 0;
+ }else{
+ if( db->flags&SQLITE_RecTriggers ){
+ pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
+ regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
+ }else{
+ pTrigger = 0;
+ regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
+ }
+ if( regTrigCnt ){
+ /* Replace triggers might exist. Allocate the counter and
+ ** initialize it to zero. */
+ regTrigCnt = ++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
+ VdbeComment((v, "trigger count"));
+ lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
+ addrRecheck = lblRecheckOk;
+ }
+ }
+
+ /* If rowid is changing, make sure the new rowid does not previously
+ ** exist in the table.
+ */
+ if( pkChng && pPk==0 ){
+ int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
+
+ /* Figure out what action to take in case of a rowid collision */
+ onError = pTab->keyConf;
+ if( overrideError!=OE_Default ){
+ onError = overrideError;
+ }else if( onError==OE_Default ){
+ onError = OE_Abort;
+ }
+
+ /* figure out whether or not upsert applies in this case */
+ if( pUpsert && pUpsert->pUpsertIdx==0 ){
+ if( pUpsert->pUpsertSet==0 ){
+ onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
+ }else{
+ onError = OE_Update; /* DO UPDATE */
+ }
+ }
+
+ /* If the response to a rowid conflict is REPLACE but the response
+ ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
+ ** to defer the running of the rowid conflict checking until after
+ ** the UNIQUE constraints have run.
+ */
+ if( onError==OE_Replace /* IPK rule is REPLACE */
+ && onError!=overrideError /* Rules for other contraints are different */
+ && pTab->pIndex /* There exist other constraints */
+ ){
+ ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
+ VdbeComment((v, "defer IPK REPLACE until last"));
+ }
+
+ if( isUpdate ){
+ /* pkChng!=0 does not mean that the rowid has changed, only that
+ ** it might have changed. Skip the conflict logic below if the rowid
+ ** is unchanged. */
+ sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
+ sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
+ VdbeCoverage(v);
+ }
+
+ /* Check to see if the new rowid already exists in the table. Skip
+ ** the following conflict logic if it does not. */
+ VdbeNoopComment((v, "uniqueness check for ROWID"));
+ sqlite3VdbeVerifyAbortable(v, onError);
+ sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
+ VdbeCoverage(v);
+
+ switch( onError ){
+ default: {
+ onError = OE_Abort;
+ /* no break */ deliberate_fall_through
+ }
+ case OE_Rollback:
+ case OE_Abort:
+ case OE_Fail: {
+ testcase( onError==OE_Rollback );
+ testcase( onError==OE_Abort );
+ testcase( onError==OE_Fail );
+ sqlite3RowidConstraint(pParse, onError, pTab);
+ break;
+ }
+ case OE_Replace: {
+ /* If there are DELETE triggers on this table and the
+ ** recursive-triggers flag is set, call GenerateRowDelete() to
+ ** remove the conflicting row from the table. This will fire
+ ** the triggers and remove both the table and index b-tree entries.
+ **
+ ** Otherwise, if there are no triggers or the recursive-triggers
+ ** flag is not set, but the table has one or more indexes, call
+ ** GenerateRowIndexDelete(). This removes the index b-tree entries
+ ** only. The table b-tree entry will be replaced by the new entry
+ ** when it is inserted.
+ **
+ ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
+ ** also invoke MultiWrite() to indicate that this VDBE may require
+ ** statement rollback (if the statement is aborted after the delete
+ ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
+ ** but being more selective here allows statements like:
+ **
+ ** REPLACE INTO t(rowid) VALUES($newrowid)
+ **
+ ** to run without a statement journal if there are no indexes on the
+ ** table.
+ */
+ if( regTrigCnt ){
+ sqlite3MultiWrite(pParse);
+ sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
+ regNewData, 1, 0, OE_Replace, 1, -1);
+ sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
+ nReplaceTrig++;
+ }else{
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+ assert( HasRowid(pTab) );
+ /* This OP_Delete opcode fires the pre-update-hook only. It does
+ ** not modify the b-tree. It is more efficient to let the coming
+ ** OP_Insert replace the existing entry than it is to delete the
+ ** existing entry and then insert a new one. */
+ sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
+ sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
+ if( pTab->pIndex ){
+ sqlite3MultiWrite(pParse);
+ sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
+ }
+ }
+ seenReplace = 1;
+ break;
+ }
+#ifndef SQLITE_OMIT_UPSERT
+ case OE_Update: {
+ sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
+ /* no break */ deliberate_fall_through
+ }
+#endif
+ case OE_Ignore: {
+ testcase( onError==OE_Ignore );
+ sqlite3VdbeGoto(v, ignoreDest);
+ break;
+ }
+ }
+ sqlite3VdbeResolveLabel(v, addrRowidOk);
+ if( ipkTop ){
+ ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
+ sqlite3VdbeJumpHere(v, ipkTop-1);
+ }
+ }
+
+ /* Test all UNIQUE constraints by creating entries for each UNIQUE
+ ** index and making sure that duplicate entries do not already exist.
+ ** Compute the revised record entries for indices as we go.
+ **
+ ** This loop also handles the case of the PRIMARY KEY index for a
+ ** WITHOUT ROWID table.
+ */
+ for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
+ int regIdx; /* Range of registers hold conent for pIdx */
+ int regR; /* Range of registers holding conflicting PK */
+ int iThisCur; /* Cursor for this UNIQUE index */
+ int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
+ int addrConflictCk; /* First opcode in the conflict check logic */
+
+ if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
+ if( pUpIdx==pIdx ){
+ addrUniqueOk = upsertJump+1;
+ upsertBypass = sqlite3VdbeGoto(v, 0);
+ VdbeComment((v, "Skip upsert subroutine"));
+ sqlite3VdbeJumpHere(v, upsertJump);
+ }else{
+ addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
+ }
+ if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){
+ sqlite3TableAffinity(v, pTab, regNewData+1);
+ bAffinityDone = 1;
+ }
+ VdbeNoopComment((v, "prep index %s", pIdx->zName));
+ iThisCur = iIdxCur+ix;
+
+
+ /* Skip partial indices for which the WHERE clause is not true */
+ if( pIdx->pPartIdxWhere ){
+ sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
+ pParse->iSelfTab = -(regNewData+1);
+ sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
+ SQLITE_JUMPIFNULL);
+ pParse->iSelfTab = 0;
+ }
+
+ /* Create a record for this index entry as it should appear after
+ ** the insert or update. Store that record in the aRegIdx[ix] register
+ */
+ regIdx = aRegIdx[ix]+1;
+ for(i=0; i<pIdx->nColumn; i++){
+ int iField = pIdx->aiColumn[i];
+ int x;
+ if( iField==XN_EXPR ){
+ pParse->iSelfTab = -(regNewData+1);
+ sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
+ pParse->iSelfTab = 0;
+ VdbeComment((v, "%s column %d", pIdx->zName, i));
+ }else if( iField==XN_ROWID || iField==pTab->iPKey ){
+ x = regNewData;
+ sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
+ VdbeComment((v, "rowid"));
+ }else{
+ testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
+ x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
+ sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
+ VdbeComment((v, "%s", pTab->aCol[iField].zName));
+ }
+ }
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
+ VdbeComment((v, "for %s", pIdx->zName));
+#ifdef SQLITE_ENABLE_NULL_TRIM
+ if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
+ sqlite3SetMakeRecordP5(v, pIdx->pTable);
+ }
+#endif
+ sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
+
+ /* In an UPDATE operation, if this index is the PRIMARY KEY index
+ ** of a WITHOUT ROWID table and there has been no change the
+ ** primary key, then no collision is possible. The collision detection
+ ** logic below can all be skipped. */
+ if( isUpdate && pPk==pIdx && pkChng==0 ){
+ sqlite3VdbeResolveLabel(v, addrUniqueOk);
+ continue;
+ }
+
+ /* Find out what action to take in case there is a uniqueness conflict */
+ onError = pIdx->onError;
+ if( onError==OE_None ){
+ sqlite3VdbeResolveLabel(v, addrUniqueOk);
+ continue; /* pIdx is not a UNIQUE index */
+ }
+ if( overrideError!=OE_Default ){
+ onError = overrideError;
+ }else if( onError==OE_Default ){
+ onError = OE_Abort;
+ }
+
+ /* Figure out if the upsert clause applies to this index */
+ if( pUpIdx==pIdx ){
+ if( pUpsert->pUpsertSet==0 ){
+ onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
+ }else{
+ onError = OE_Update; /* DO UPDATE */
+ }
+ }
+
+ /* Collision detection may be omitted if all of the following are true:
+ ** (1) The conflict resolution algorithm is REPLACE
+ ** (2) The table is a WITHOUT ROWID table
+ ** (3) There are no secondary indexes on the table
+ ** (4) No delete triggers need to be fired if there is a conflict
+ ** (5) No FK constraint counters need to be updated if a conflict occurs.
+ **
+ ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
+ ** must be explicitly deleted in order to ensure any pre-update hook
+ ** is invoked. */
+#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
+ if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
+ && pPk==pIdx /* Condition 2 */
+ && onError==OE_Replace /* Condition 1 */
+ && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
+ 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
+ && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
+ (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
+ ){
+ sqlite3VdbeResolveLabel(v, addrUniqueOk);
+ continue;
+ }
+#endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
+
+ /* Check to see if the new index entry will be unique */
+ sqlite3VdbeVerifyAbortable(v, onError);
+ addrConflictCk =
+ sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
+ regIdx, pIdx->nKeyCol); VdbeCoverage(v);
+
+ /* Generate code to handle collisions */
+ regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
+ if( isUpdate || onError==OE_Replace ){
+ if( HasRowid(pTab) ){
+ sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
+ /* Conflict only if the rowid of the existing index entry
+ ** is different from old-rowid */
+ if( isUpdate ){
+ sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
+ sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
+ VdbeCoverage(v);
+ }
+ }else{
+ int x;
+ /* Extract the PRIMARY KEY from the end of the index entry and
+ ** store it in registers regR..regR+nPk-1 */
+ if( pIdx!=pPk ){
+ for(i=0; i<pPk->nKeyCol; i++){
+ assert( pPk->aiColumn[i]>=0 );
+ x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
+ sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
+ VdbeComment((v, "%s.%s", pTab->zName,
+ pTab->aCol[pPk->aiColumn[i]].zName));
+ }
+ }
+ if( isUpdate ){
+ /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
+ ** table, only conflict if the new PRIMARY KEY values are actually
+ ** different from the old.
+ **
+ ** For a UNIQUE index, only conflict if the PRIMARY KEY values
+ ** of the matched index row are different from the original PRIMARY
+ ** KEY values of this row before the update. */
+ int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
+ int op = OP_Ne;
+ int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
+
+ for(i=0; i<pPk->nKeyCol; i++){
+ char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
+ x = pPk->aiColumn[i];
+ assert( x>=0 );
+ if( i==(pPk->nKeyCol-1) ){
+ addrJump = addrUniqueOk;
+ op = OP_Eq;
+ }
+ x = sqlite3TableColumnToStorage(pTab, x);
+ sqlite3VdbeAddOp4(v, op,
+ regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
+ );
+ sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
+ VdbeCoverageIf(v, op==OP_Eq);
+ VdbeCoverageIf(v, op==OP_Ne);
+ }
+ }
+ }
+ }
+
+ /* Generate code that executes if the new index entry is not unique */
+ assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
+ || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
+ switch( onError ){
+ case OE_Rollback:
+ case OE_Abort:
+ case OE_Fail: {
+ testcase( onError==OE_Rollback );
+ testcase( onError==OE_Abort );
+ testcase( onError==OE_Fail );
+ sqlite3UniqueConstraint(pParse, onError, pIdx);
+ break;
+ }
+#ifndef SQLITE_OMIT_UPSERT
+ case OE_Update: {
+ sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
+ /* no break */ deliberate_fall_through
+ }
+#endif
+ case OE_Ignore: {
+ testcase( onError==OE_Ignore );
+ sqlite3VdbeGoto(v, ignoreDest);
+ break;
+ }
+ default: {
+ int nConflictCk; /* Number of opcodes in conflict check logic */
+
+ assert( onError==OE_Replace );
+ nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
+ assert( nConflictCk>0 );
+ testcase( nConflictCk>1 );
+ if( regTrigCnt ){
+ sqlite3MultiWrite(pParse);
+ nReplaceTrig++;
+ }
+ if( pTrigger && isUpdate ){
+ sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);
+ }
+ sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
+ regR, nPkField, 0, OE_Replace,
+ (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
+ if( pTrigger && isUpdate ){
+ sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
+ }
+ if( regTrigCnt ){
+ int addrBypass; /* Jump destination to bypass recheck logic */
+
+ sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
+ addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */
+ VdbeComment((v, "bypass recheck"));
+
+ /* Here we insert code that will be invoked after all constraint
+ ** checks have run, if and only if one or more replace triggers
+ ** fired. */
+ sqlite3VdbeResolveLabel(v, lblRecheckOk);
+ lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
+ if( pIdx->pPartIdxWhere ){
+ /* Bypass the recheck if this partial index is not defined
+ ** for the current row */
+ sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
+ VdbeCoverage(v);
+ }
+ /* Copy the constraint check code from above, except change
+ ** the constraint-ok jump destination to be the address of
+ ** the next retest block */
+ while( nConflictCk>0 ){
+ VdbeOp x; /* Conflict check opcode to copy */
+ /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
+ ** Hence, make a complete copy of the opcode, rather than using
+ ** a pointer to the opcode. */
+ x = *sqlite3VdbeGetOp(v, addrConflictCk);
+ if( x.opcode!=OP_IdxRowid ){
+ int p2; /* New P2 value for copied conflict check opcode */
+ const char *zP4;
+ if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
+ p2 = lblRecheckOk;
+ }else{
+ p2 = x.p2;
+ }
+ zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
+ sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
+ sqlite3VdbeChangeP5(v, x.p5);
+ VdbeCoverageIf(v, p2!=x.p2);
+ }
+ nConflictCk--;
+ addrConflictCk++;
+ }
+ /* If the retest fails, issue an abort */
+ sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
+
+ sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
+ }
+ seenReplace = 1;
+ break;
+ }
+ }
+ if( pUpIdx==pIdx ){
+ sqlite3VdbeGoto(v, upsertJump+1);
+ sqlite3VdbeJumpHere(v, upsertBypass);
+ }else{
+ sqlite3VdbeResolveLabel(v, addrUniqueOk);
+ }
+ if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
+ }
+
+ /* If the IPK constraint is a REPLACE, run it last */
+ if( ipkTop ){
+ sqlite3VdbeGoto(v, ipkTop);
+ VdbeComment((v, "Do IPK REPLACE"));
+ sqlite3VdbeJumpHere(v, ipkBottom);
+ }
+
+ /* Recheck all uniqueness constraints after replace triggers have run */
+ testcase( regTrigCnt!=0 && nReplaceTrig==0 );
+ assert( regTrigCnt!=0 || nReplaceTrig==0 );
+ if( nReplaceTrig ){
+ sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
+ if( !pPk ){
+ if( isUpdate ){
+ sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
+ sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
+ VdbeCoverage(v);
+ }
+ sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
+ VdbeCoverage(v);
+ sqlite3RowidConstraint(pParse, OE_Abort, pTab);
+ }else{
+ sqlite3VdbeGoto(v, addrRecheck);
+ }
+ sqlite3VdbeResolveLabel(v, lblRecheckOk);
+ }
+
+ /* Generate the table record */
+ if( HasRowid(pTab) ){
+ int regRec = aRegIdx[ix];
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
+ sqlite3SetMakeRecordP5(v, pTab);
+ if( !bAffinityDone ){
+ sqlite3TableAffinity(v, pTab, 0);
+ }
+ }
+
+ *pbMayReplace = seenReplace;
+ VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
+}
+
+#ifdef SQLITE_ENABLE_NULL_TRIM
+/*
+** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
+** to be the number of columns in table pTab that must not be NULL-trimmed.
+**
+** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
+*/
+SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
+ u16 i;
+
+ /* Records with omitted columns are only allowed for schema format
+ ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
+ if( pTab->pSchema->file_format<2 ) return;
+
+ for(i=pTab->nCol-1; i>0; i--){
+ if( pTab->aCol[i].pDflt!=0 ) break;
+ if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
+ }
+ sqlite3VdbeChangeP5(v, i+1);
+}
+#endif
+
+/*
+** This routine generates code to finish the INSERT or UPDATE operation
+** that was started by a prior call to sqlite3GenerateConstraintChecks.
+** A consecutive range of registers starting at regNewData contains the
+** rowid and the content to be inserted.
+**
+** The arguments to this routine should be the same as the first six
+** arguments to sqlite3GenerateConstraintChecks.
+*/
+SQLITE_PRIVATE void sqlite3CompleteInsertion(
+ Parse *pParse, /* The parser context */
+ Table *pTab, /* the table into which we are inserting */
+ int iDataCur, /* Cursor of the canonical data source */
+ int iIdxCur, /* First index cursor */
+ int regNewData, /* Range of content */
+ int *aRegIdx, /* Register used by each index. 0 for unused indices */
+ int update_flags, /* True for UPDATE, False for INSERT */
+ int appendBias, /* True if this is likely to be an append */
+ int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
+){
+ Vdbe *v; /* Prepared statements under construction */
+ Index *pIdx; /* An index being inserted or updated */
+ u8 pik_flags; /* flag values passed to the btree insert */
+ int i; /* Loop counter */
+
+ assert( update_flags==0
+ || update_flags==OPFLAG_ISUPDATE
+ || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
+ );
+
+ v = pParse->pVdbe;
+ assert( v!=0 );
+ assert( pTab->pSelect==0 ); /* This table is not a VIEW */
+ for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
+ /* All REPLACE indexes are at the end of the list */
+ assert( pIdx->onError!=OE_Replace
+ || pIdx->pNext==0
+ || pIdx->pNext->onError==OE_Replace );
+ if( aRegIdx[i]==0 ) continue;
+ if( pIdx->pPartIdxWhere ){
+ sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
+ VdbeCoverage(v);
+ }
+ pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
+ if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
+ assert( pParse->nested==0 );
+ pik_flags |= OPFLAG_NCHANGE;
+ pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+ if( update_flags==0 ){
+ int r = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
+ sqlite3VdbeAddOp4(v, OP_Insert,
+ iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE
+ );
+ sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
+ sqlite3ReleaseTempReg(pParse, r);
+ }
+#endif
+ }
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
+ aRegIdx[i]+1,
+ pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
+ sqlite3VdbeChangeP5(v, pik_flags);
+ }
+ if( !HasRowid(pTab) ) return;
+ if( pParse->nested ){
+ pik_flags = 0;
+ }else{
+ pik_flags = OPFLAG_NCHANGE;
+ pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
+ }
+ if( appendBias ){
+ pik_flags |= OPFLAG_APPEND;
+ }
+ if( useSeekResult ){
+ pik_flags |= OPFLAG_USESEEKRESULT;
+ }
+ sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
+ if( !pParse->nested ){
+ sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
+ }
+ sqlite3VdbeChangeP5(v, pik_flags);
+}
+
+/*
+** Allocate cursors for the pTab table and all its indices and generate
+** code to open and initialized those cursors.
+**
+** The cursor for the object that contains the complete data (normally
+** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
+** ROWID table) is returned in *piDataCur. The first index cursor is
+** returned in *piIdxCur. The number of indices is returned.
+**
+** Use iBase as the first cursor (either the *piDataCur for rowid tables
+** or the first index for WITHOUT ROWID tables) if it is non-negative.
+** If iBase is negative, then allocate the next available cursor.
+**
+** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
+** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
+** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
+** pTab->pIndex list.
+**
+** If pTab is a virtual table, then this routine is a no-op and the
+** *piDataCur and *piIdxCur values are left uninitialized.
+*/
+SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
+ Parse *pParse, /* Parsing context */
+ Table *pTab, /* Table to be opened */
+ int op, /* OP_OpenRead or OP_OpenWrite */
+ u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
+ int iBase, /* Use this for the table cursor, if there is one */
+ u8 *aToOpen, /* If not NULL: boolean for each table and index */
+ int *piDataCur, /* Write the database source cursor number here */
+ int *piIdxCur /* Write the first index cursor number here */
+){
+ int i;
+ int iDb;
+ int iDataCur;
+ Index *pIdx;
+ Vdbe *v;
+
+ assert( op==OP_OpenRead || op==OP_OpenWrite );
+ assert( op==OP_OpenWrite || p5==0 );
+ if( IsVirtual(pTab) ){
+ /* This routine is a no-op for virtual tables. Leave the output
+ ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
+ ** can detect if they are used by mistake in the caller. */
+ return 0;
+ }
+ iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
+ v = pParse->pVdbe;
+ assert( v!=0 );
+ if( iBase<0 ) iBase = pParse->nTab;
+ iDataCur = iBase++;
+ if( piDataCur ) *piDataCur = iDataCur;
+ if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
+ sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
+ }else{
+ sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
+ }
+ if( piIdxCur ) *piIdxCur = iBase;
+ for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
+ int iIdxCur = iBase++;
+ assert( pIdx->pSchema==pTab->pSchema );
+ if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
+ if( piDataCur ) *piDataCur = iIdxCur;
+ p5 = 0;
+ }
+ if( aToOpen==0 || aToOpen[i+1] ){
+ sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
+ sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
+ sqlite3VdbeChangeP5(v, p5);
+ VdbeComment((v, "%s", pIdx->zName));
+ }
+ }
+ if( iBase>pParse->nTab ) pParse->nTab = iBase;
+ return i;
+}
+
+
+#ifdef SQLITE_TEST
+/*
+** The following global variable is incremented whenever the
+** transfer optimization is used. This is used for testing
+** purposes only - to make sure the transfer optimization really
+** is happening when it is supposed to.
+*/
+SQLITE_API int sqlite3_xferopt_count;
+#endif /* SQLITE_TEST */
+
+
+#ifndef SQLITE_OMIT_XFER_OPT
+/*
+** Check to see if index pSrc is compatible as a source of data
+** for index pDest in an insert transfer optimization. The rules
+** for a compatible index:
+**
+** * The index is over the same set of columns
+** * The same DESC and ASC markings occurs on all columns
+** * The same onError processing (OE_Abort, OE_Ignore, etc)
+** * The same collating sequence on each column
+** * The index has the exact same WHERE clause
+*/
+static int xferCompatibleIndex(Index *pDest, Index *pSrc){
+ int i;
+ assert( pDest && pSrc );
+ assert( pDest->pTable!=pSrc->pTable );
+ if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
+ return 0; /* Different number of columns */
+ }
+ if( pDest->onError!=pSrc->onError ){
+ return 0; /* Different conflict resolution strategies */
+ }
+ for(i=0; i<pSrc->nKeyCol; i++){
+ if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
+ return 0; /* Different columns indexed */
+ }
+ if( pSrc->aiColumn[i]==XN_EXPR ){
+ assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
+ if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
+ pDest->aColExpr->a[i].pExpr, -1)!=0 ){
+ return 0; /* Different expressions in the index */
+ }
+ }
+ if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
+ return 0; /* Different sort orders */
+ }
+ if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
+ return 0; /* Different collating sequences */
+ }
+ }
+ if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
+ return 0; /* Different WHERE clauses */
+ }
+
+ /* If no test above fails then the indices must be compatible */
+ return 1;
+}
+
+/*
+** Attempt the transfer optimization on INSERTs of the form
+**
+** INSERT INTO tab1 SELECT * FROM tab2;
+**
+** The xfer optimization transfers raw records from tab2 over to tab1.
+** Columns are not decoded and reassembled, which greatly improves
+** performance. Raw index records are transferred in the same way.
+**
+** The xfer optimization is only attempted if tab1 and tab2 are compatible.
+** There are lots of rules for determining compatibility - see comments
+** embedded in the code for details.
+**
+** This routine returns TRUE if the optimization is guaranteed to be used.
+** Sometimes the xfer optimization will only work if the destination table
+** is empty - a factor that can only be determined at run-time. In that
+** case, this routine generates code for the xfer optimization but also
+** does a test to see if the destination table is empty and jumps over the
+** xfer optimization code if the test fails. In that case, this routine
+** returns FALSE so that the caller will know to go ahead and generate
+** an unoptimized transfer. This routine also returns FALSE if there
+** is no chance that the xfer optimization can be applied.
+**
+** This optimization is particularly useful at making VACUUM run faster.
+*/
+static int xferOptimization(
+ Parse *pParse, /* Parser context */
+ Table *pDest, /* The table we are inserting into */
+ Select *pSelect, /* A SELECT statement to use as the data source */
+ int onError, /* How to handle constraint errors */
+ int iDbDest /* The database of pDest */
+){
+ sqlite3 *db = pParse->db;
+ ExprList *pEList; /* The result set of the SELECT */
+ Table *pSrc; /* The table in the FROM clause of SELECT */
+ Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
+ struct SrcList_item *pItem; /* An element of pSelect->pSrc */
+ int i; /* Loop counter */
+ int iDbSrc; /* The database of pSrc */
+ int iSrc, iDest; /* Cursors from source and destination */
+ int addr1, addr2; /* Loop addresses */
+ int emptyDestTest = 0; /* Address of test for empty pDest */
+ int emptySrcTest = 0; /* Address of test for empty pSrc */
+ Vdbe *v; /* The VDBE we are building */
+ int regAutoinc; /* Memory register used by AUTOINC */
+ int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
+ int regData, regRowid; /* Registers holding data and rowid */
+
+ if( pSelect==0 ){
+ return 0; /* Must be of the form INSERT INTO ... SELECT ... */
+ }
+ if( pParse->pWith || pSelect->pWith ){
+ /* Do not attempt to process this query if there are an WITH clauses
+ ** attached to it. Proceeding may generate a false "no such table: xxx"
+ ** error if pSelect reads from a CTE named "xxx". */
+ return 0;
+ }
+ if( sqlite3TriggerList(pParse, pDest) ){
+ return 0; /* tab1 must not have triggers */
+ }
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( IsVirtual(pDest) ){
+ return 0; /* tab1 must not be a virtual table */
+ }
+#endif
+ if( onError==OE_Default ){
+ if( pDest->iPKey>=0 ) onError = pDest->keyConf;
+ if( onError==OE_Default ) onError = OE_Abort;
+ }
+ assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
+ if( pSelect->pSrc->nSrc!=1 ){
+ return 0; /* FROM clause must have exactly one term */
+ }
+ if( pSelect->pSrc->a[0].pSelect ){
+ return 0; /* FROM clause cannot contain a subquery */
+ }
+ if( pSelect->pWhere ){
+ return 0; /* SELECT may not have a WHERE clause */
+ }
+ if( pSelect->pOrderBy ){
+ return 0; /* SELECT may not have an ORDER BY clause */
+ }
+ /* Do not need to test for a HAVING clause. If HAVING is present but
+ ** there is no ORDER BY, we will get an error. */
+ if( pSelect->pGroupBy ){
+ return 0; /* SELECT may not have a GROUP BY clause */
+ }
+ if( pSelect->pLimit ){
+ return 0; /* SELECT may not have a LIMIT clause */
+ }
+ if( pSelect->pPrior ){
+ return 0; /* SELECT may not be a compound query */
+ }
+ if( pSelect->selFlags & SF_Distinct ){
+ return 0; /* SELECT may not be DISTINCT */
+ }
+ pEList = pSelect->pEList;
+ assert( pEList!=0 );
+ if( pEList->nExpr!=1 ){
+ return 0; /* The result set must have exactly one column */
+ }
+ assert( pEList->a[0].pExpr );
+ if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
+ return 0; /* The result set must be the special operator "*" */
+ }
+
+ /* At this point we have established that the statement is of the
+ ** correct syntactic form to participate in this optimization. Now
+ ** we have to check the semantics.
+ */
+ pItem = pSelect->pSrc->a;
+ pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
+ if( pSrc==0 ){
+ return 0; /* FROM clause does not contain a real table */
+ }
+ if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
+ testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */
+ return 0; /* tab1 and tab2 may not be the same table */
+ }
+ if( HasRowid(pDest)!=HasRowid(pSrc) ){
+ return 0; /* source and destination must both be WITHOUT ROWID or not */
+ }
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( IsVirtual(pSrc) ){
+ return 0; /* tab2 must not be a virtual table */
+ }
+#endif
+ if( pSrc->pSelect ){
+ return 0; /* tab2 may not be a view */
+ }
+ if( pDest->nCol!=pSrc->nCol ){
+ return 0; /* Number of columns must be the same in tab1 and tab2 */
+ }
+ if( pDest->iPKey!=pSrc->iPKey ){
+ return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
+ }
+ for(i=0; i<pDest->nCol; i++){
+ Column *pDestCol = &pDest->aCol[i];
+ Column *pSrcCol = &pSrc->aCol[i];
+#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
+ if( (db->mDbFlags & DBFLAG_Vacuum)==0
+ && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
+ ){
+ return 0; /* Neither table may have __hidden__ columns */
+ }
+#endif
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ /* Even if tables t1 and t2 have identical schemas, if they contain
+ ** generated columns, then this statement is semantically incorrect:
+ **
+ ** INSERT INTO t2 SELECT * FROM t1;
+ **
+ ** The reason is that generated column values are returned by the
+ ** the SELECT statement on the right but the INSERT statement on the
+ ** left wants them to be omitted.
+ **
+ ** Nevertheless, this is a useful notational shorthand to tell SQLite
+ ** to do a bulk transfer all of the content from t1 over to t2.
+ **
+ ** We could, in theory, disable this (except for internal use by the
+ ** VACUUM command where it is actually needed). But why do that? It
+ ** seems harmless enough, and provides a useful service.
+ */
+ if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
+ (pSrcCol->colFlags & COLFLAG_GENERATED) ){
+ return 0; /* Both columns have the same generated-column type */
+ }
+ /* But the transfer is only allowed if both the source and destination
+ ** tables have the exact same expressions for generated columns.
+ ** This requirement could be relaxed for VIRTUAL columns, I suppose.
+ */
+ if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
+ if( sqlite3ExprCompare(0, pSrcCol->pDflt, pDestCol->pDflt, -1)!=0 ){
+ testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
+ testcase( pDestCol->colFlags & COLFLAG_STORED );
+ return 0; /* Different generator expressions */
+ }
+ }
+#endif
+ if( pDestCol->affinity!=pSrcCol->affinity ){
+ return 0; /* Affinity must be the same on all columns */
+ }
+ if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
+ return 0; /* Collating sequence must be the same on all columns */
+ }
+ if( pDestCol->notNull && !pSrcCol->notNull ){
+ return 0; /* tab2 must be NOT NULL if tab1 is */
+ }
+ /* Default values for second and subsequent columns need to match. */
+ if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
+ assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
+ assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
+ if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
+ || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
+ pSrcCol->pDflt->u.zToken)!=0)
+ ){
+ return 0; /* Default values must be the same for all columns */
+ }
+ }
+ }
+ for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
+ if( IsUniqueIndex(pDestIdx) ){
+ destHasUniqueIdx = 1;
+ }
+ for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
+ if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
+ }
+ if( pSrcIdx==0 ){
+ return 0; /* pDestIdx has no corresponding index in pSrc */
+ }
+ if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
+ && sqlite3FaultSim(411)==SQLITE_OK ){
+ /* The sqlite3FaultSim() call allows this corruption test to be
+ ** bypassed during testing, in order to exercise other corruption tests
+ ** further downstream. */
+ return 0; /* Corrupt schema - two indexes on the same btree */
+ }
+ }
+#ifndef SQLITE_OMIT_CHECK
+ if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
+ return 0; /* Tables have different CHECK constraints. Ticket #2252 */
+ }
+#endif
+#ifndef SQLITE_OMIT_FOREIGN_KEY
+ /* Disallow the transfer optimization if the destination table constains
+ ** any foreign key constraints. This is more restrictive than necessary.
+ ** But the main beneficiary of the transfer optimization is the VACUUM
+ ** command, and the VACUUM command disables foreign key constraints. So
+ ** the extra complication to make this rule less restrictive is probably
+ ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
+ */
+ if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
+ return 0;
+ }
+#endif
+ if( (db->flags & SQLITE_CountRows)!=0 ){
+ return 0; /* xfer opt does not play well with PRAGMA count_changes */
+ }
+
+ /* If we get this far, it means that the xfer optimization is at
+ ** least a possibility, though it might only work if the destination
+ ** table (tab1) is initially empty.
+ */
+#ifdef SQLITE_TEST
+ sqlite3_xferopt_count++;
+#endif
+ iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
+ v = sqlite3GetVdbe(pParse);
+ sqlite3CodeVerifySchema(pParse, iDbSrc);
+ iSrc = pParse->nTab++;
+ iDest = pParse->nTab++;
+ regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
+ regData = sqlite3GetTempReg(pParse);
+ regRowid = sqlite3GetTempReg(pParse);
+ sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
+ assert( HasRowid(pDest) || destHasUniqueIdx );
+ if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
+ (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
+ || destHasUniqueIdx /* (2) */
+ || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
+ )){
+ /* In some circumstances, we are able to run the xfer optimization
+ ** only if the destination table is initially empty. Unless the
+ ** DBFLAG_Vacuum flag is set, this block generates code to make
+ ** that determination. If DBFLAG_Vacuum is set, then the destination
+ ** table is always empty.
+ **
+ ** Conditions under which the destination must be empty:
+ **
+ ** (1) There is no INTEGER PRIMARY KEY but there are indices.
+ ** (If the destination is not initially empty, the rowid fields
+ ** of index entries might need to change.)
+ **
+ ** (2) The destination has a unique index. (The xfer optimization
+ ** is unable to test uniqueness.)
+ **
+ ** (3) onError is something other than OE_Abort and OE_Rollback.
+ */
+ addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
+ emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
+ sqlite3VdbeJumpHere(v, addr1);
+ }
+ if( HasRowid(pSrc) ){
+ u8 insFlags;
+ sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
+ emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
+ if( pDest->iPKey>=0 ){
+ addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
+ sqlite3VdbeVerifyAbortable(v, onError);
+ addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
+ VdbeCoverage(v);
+ sqlite3RowidConstraint(pParse, onError, pDest);
+ sqlite3VdbeJumpHere(v, addr2);
+ autoIncStep(pParse, regAutoinc, regRowid);
+ }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
+ addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
+ }else{
+ addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
+ assert( (pDest->tabFlags & TF_Autoincrement)==0 );
+ }
+ if( db->mDbFlags & DBFLAG_Vacuum ){
+ sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
+ insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
+ }else{
+ insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
+ }
+ sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
+ sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
+ (char*)pDest, P4_TABLE);
+ sqlite3VdbeChangeP5(v, insFlags);
+ sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
+ sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
+ sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
+ }else{
+ sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
+ sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
+ }
+ for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
+ u8 idxInsFlags = 0;
+ for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
+ if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
+ }
+ assert( pSrcIdx );
+ sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
+ sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
+ VdbeComment((v, "%s", pSrcIdx->zName));
+ sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
+ sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
+ sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
+ VdbeComment((v, "%s", pDestIdx->zName));
+ addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
+ if( db->mDbFlags & DBFLAG_Vacuum ){
+ /* This INSERT command is part of a VACUUM operation, which guarantees
+ ** that the destination table is empty. If all indexed columns use
+ ** collation sequence BINARY, then it can also be assumed that the
+ ** index will be populated by inserting keys in strictly sorted
+ ** order. In this case, instead of seeking within the b-tree as part
+ ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
+ ** OP_IdxInsert to seek to the point within the b-tree where each key
+ ** should be inserted. This is faster.
+ **
+ ** If any of the indexed columns use a collation sequence other than
+ ** BINARY, this optimization is disabled. This is because the user
+ ** might change the definition of a collation sequence and then run
+ ** a VACUUM command. In that case keys may not be written in strictly
+ ** sorted order. */
+ for(i=0; i<pSrcIdx->nColumn; i++){
+ const char *zColl = pSrcIdx->azColl[i];
+ if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
+ }
+ if( i==pSrcIdx->nColumn ){
+ idxInsFlags = OPFLAG_USESEEKRESULT;
+ sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
+ }
+ }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
+ idxInsFlags |= OPFLAG_NCHANGE;
+ }
+ sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
+ sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
+ sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
+ sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
+ sqlite3VdbeJumpHere(v, addr1);
+ sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
+ sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
+ }
+ if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
+ sqlite3ReleaseTempReg(pParse, regRowid);
+ sqlite3ReleaseTempReg(pParse, regData);
+ if( emptyDestTest ){
+ sqlite3AutoincrementEnd(pParse);
+ sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
+ sqlite3VdbeJumpHere(v, emptyDestTest);
+ sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
+ return 0;
+ }else{
+ return 1;
+ }
+}
+#endif /* SQLITE_OMIT_XFER_OPT */
+
+/************** End of insert.c **********************************************/
+/************** Begin file legacy.c ******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** Main file for the SQLite library. The routines in this file
+** implement the programmer interface to the library. Routines in
+** other files are for internal use by SQLite and should not be
+** accessed by users of the library.
+*/
+
+/* #include "sqliteInt.h" */
+
+/*
+** Execute SQL code. Return one of the SQLITE_ success/failure
+** codes. Also write an error message into memory obtained from
+** malloc() and make *pzErrMsg point to that message.
+**
+** If the SQL is a query, then for each row in the query result
+** the xCallback() function is called. pArg becomes the first
+** argument to xCallback(). If xCallback=NULL then no callback
+** is invoked, even for queries.
+*/
+SQLITE_API int sqlite3_exec(
+ sqlite3 *db, /* The database on which the SQL executes */
+ const char *zSql, /* The SQL to be executed */
+ sqlite3_callback xCallback, /* Invoke this callback routine */
+ void *pArg, /* First argument to xCallback() */
+ char **pzErrMsg /* Write error messages here */
+){
+ int rc = SQLITE_OK; /* Return code */
+ const char *zLeftover; /* Tail of unprocessed SQL */
+ sqlite3_stmt *pStmt = 0; /* The current SQL statement */
+ char **azCols = 0; /* Names of result columns */
+ int callbackIsInit; /* True if callback data is initialized */
+
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+ if( zSql==0 ) zSql = "";
+
+ sqlite3_mutex_enter(db->mutex);
+ sqlite3Error(db, SQLITE_OK);
+ while( rc==SQLITE_OK && zSql[0] ){
+ int nCol = 0;
+ char **azVals = 0;
+
+ pStmt = 0;
+ rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
+ assert( rc==SQLITE_OK || pStmt==0 );
+ if( rc!=SQLITE_OK ){
+ continue;
+ }
+ if( !pStmt ){
+ /* this happens for a comment or white-space */
+ zSql = zLeftover;
+ continue;
+ }
+ callbackIsInit = 0;
+
+ while( 1 ){
+ int i;
+ rc = sqlite3_step(pStmt);
+
+ /* Invoke the callback function if required */
+ if( xCallback && (SQLITE_ROW==rc ||
+ (SQLITE_DONE==rc && !callbackIsInit
+ && db->flags&SQLITE_NullCallback)) ){
+ if( !callbackIsInit ){
+ nCol = sqlite3_column_count(pStmt);
+ azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
+ if( azCols==0 ){
+ goto exec_out;
+ }
+ for(i=0; i<nCol; i++){
+ azCols[i] = (char *)sqlite3_column_name(pStmt, i);
+ /* sqlite3VdbeSetColName() installs column names as UTF8
+ ** strings so there is no way for sqlite3_column_name() to fail. */
+ assert( azCols[i]!=0 );
+ }
+ callbackIsInit = 1;
+ }
+ if( rc==SQLITE_ROW ){
+ azVals = &azCols[nCol];
+ for(i=0; i<nCol; i++){
+ azVals[i] = (char *)sqlite3_column_text(pStmt, i);
+ if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
+ sqlite3OomFault(db);
+ goto exec_out;
+ }
+ }
+ azVals[i] = 0;
+ }
+ if( xCallback(pArg, nCol, azVals, azCols) ){
+ /* EVIDENCE-OF: R-38229-40159 If the callback function to
+ ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
+ ** return SQLITE_ABORT. */
+ rc = SQLITE_ABORT;
+ sqlite3VdbeFinalize((Vdbe *)pStmt);
+ pStmt = 0;
+ sqlite3Error(db, SQLITE_ABORT);
+ goto exec_out;
+ }
+ }
+
+ if( rc!=SQLITE_ROW ){
+ rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
+ pStmt = 0;
+ zSql = zLeftover;
+ while( sqlite3Isspace(zSql[0]) ) zSql++;
+ break;
+ }
+ }
+
+ sqlite3DbFree(db, azCols);
+ azCols = 0;
+ }
+
+exec_out:
+ if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
+ sqlite3DbFree(db, azCols);
+
+ rc = sqlite3ApiExit(db, rc);
+ if( rc!=SQLITE_OK && pzErrMsg ){
+ *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));
+ if( *pzErrMsg==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ sqlite3Error(db, SQLITE_NOMEM);
+ }
+ }else if( pzErrMsg ){
+ *pzErrMsg = 0;
+ }
+
+ assert( (rc&db->errMask)==rc );
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+/************** End of legacy.c **********************************************/
+/************** Begin file loadext.c *****************************************/
+/*
+** 2006 June 7
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code used to dynamically load extensions into
+** the SQLite library.
+*/
+
+#ifndef SQLITE_CORE
+ #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
+#endif
+/************** Include sqlite3ext.h in the middle of loadext.c **************/
+/************** Begin file sqlite3ext.h **************************************/
+/*
+** 2006 June 7
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This header file defines the SQLite interface for use by
+** shared libraries that want to be imported as extensions into
+** an SQLite instance. Shared libraries that intend to be loaded
+** as extensions by SQLite should #include this file instead of
+** sqlite3.h.
+*/
+#ifndef SQLITE3EXT_H
+#define SQLITE3EXT_H
+/* #include "sqlite3.h" */
+
+/*
+** The following structure holds pointers to all of the SQLite API
+** routines.
+**
+** WARNING: In order to maintain backwards compatibility, add new
+** interfaces to the end of this structure only. If you insert new
+** interfaces in the middle of this structure, then older different
+** versions of SQLite will not be able to load each other's shared
+** libraries!
+*/
+struct sqlite3_api_routines {
+ void * (*aggregate_context)(sqlite3_context*,int nBytes);
+ int (*aggregate_count)(sqlite3_context*);
+ int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
+ int (*bind_double)(sqlite3_stmt*,int,double);
+ int (*bind_int)(sqlite3_stmt*,int,int);
+ int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
+ int (*bind_null)(sqlite3_stmt*,int);
+ int (*bind_parameter_count)(sqlite3_stmt*);
+ int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
+ const char * (*bind_parameter_name)(sqlite3_stmt*,int);
+ int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
+ int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
+ int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
+ int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
+ int (*busy_timeout)(sqlite3*,int ms);
+ int (*changes)(sqlite3*);
+ int (*close)(sqlite3*);
+ int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
+ int eTextRep,const char*));
+ int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
+ int eTextRep,const void*));
+ const void * (*column_blob)(sqlite3_stmt*,int iCol);
+ int (*column_bytes)(sqlite3_stmt*,int iCol);
+ int (*column_bytes16)(sqlite3_stmt*,int iCol);
+ int (*column_count)(sqlite3_stmt*pStmt);
+ const char * (*column_database_name)(sqlite3_stmt*,int);
+ const void * (*column_database_name16)(sqlite3_stmt*,int);
+ const char * (*column_decltype)(sqlite3_stmt*,int i);
+ const void * (*column_decltype16)(sqlite3_stmt*,int);
+ double (*column_double)(sqlite3_stmt*,int iCol);
+ int (*column_int)(sqlite3_stmt*,int iCol);
+ sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
+ const char * (*column_name)(sqlite3_stmt*,int);
+ const void * (*column_name16)(sqlite3_stmt*,int);
+ const char * (*column_origin_name)(sqlite3_stmt*,int);
+ const void * (*column_origin_name16)(sqlite3_stmt*,int);
+ const char * (*column_table_name)(sqlite3_stmt*,int);
+ const void * (*column_table_name16)(sqlite3_stmt*,int);
+ const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
+ const void * (*column_text16)(sqlite3_stmt*,int iCol);
+ int (*column_type)(sqlite3_stmt*,int iCol);
+ sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
+ void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
+ int (*complete)(const char*sql);
+ int (*complete16)(const void*sql);
+ int (*create_collation)(sqlite3*,const char*,int,void*,
+ int(*)(void*,int,const void*,int,const void*));
+ int (*create_collation16)(sqlite3*,const void*,int,void*,
+ int(*)(void*,int,const void*,int,const void*));
+ int (*create_function)(sqlite3*,const char*,int,int,void*,
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*));
+ int (*create_function16)(sqlite3*,const void*,int,int,void*,
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*));
+ int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
+ int (*data_count)(sqlite3_stmt*pStmt);
+ sqlite3 * (*db_handle)(sqlite3_stmt*);
+ int (*declare_vtab)(sqlite3*,const char*);
+ int (*enable_shared_cache)(int);
+ int (*errcode)(sqlite3*db);
+ const char * (*errmsg)(sqlite3*);
+ const void * (*errmsg16)(sqlite3*);
+ int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
+ int (*expired)(sqlite3_stmt*);
+ int (*finalize)(sqlite3_stmt*pStmt);
+ void (*free)(void*);
+ void (*free_table)(char**result);
+ int (*get_autocommit)(sqlite3*);
+ void * (*get_auxdata)(sqlite3_context*,int);
+ int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
+ int (*global_recover)(void);
+ void (*interruptx)(sqlite3*);
+ sqlite_int64 (*last_insert_rowid)(sqlite3*);
+ const char * (*libversion)(void);
+ int (*libversion_number)(void);
+ void *(*malloc)(int);
+ char * (*mprintf)(const char*,...);
+ int (*open)(const char*,sqlite3**);
+ int (*open16)(const void*,sqlite3**);
+ int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
+ int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
+ void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
+ void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
+ void *(*realloc)(void*,int);
+ int (*reset)(sqlite3_stmt*pStmt);
+ void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
+ void (*result_double)(sqlite3_context*,double);
+ void (*result_error)(sqlite3_context*,const char*,int);
+ void (*result_error16)(sqlite3_context*,const void*,int);
+ void (*result_int)(sqlite3_context*,int);
+ void (*result_int64)(sqlite3_context*,sqlite_int64);
+ void (*result_null)(sqlite3_context*);
+ void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
+ void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
+ void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
+ void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
+ void (*result_value)(sqlite3_context*,sqlite3_value*);
+ void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
+ int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
+ const char*,const char*),void*);
+ void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
+ char * (*xsnprintf)(int,char*,const char*,...);
+ int (*step)(sqlite3_stmt*);
+ int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
+ char const**,char const**,int*,int*,int*);
+ void (*thread_cleanup)(void);
+ int (*total_changes)(sqlite3*);
+ void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
+ int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
+ void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
+ sqlite_int64),void*);
+ void * (*user_data)(sqlite3_context*);
+ const void * (*value_blob)(sqlite3_value*);
+ int (*value_bytes)(sqlite3_value*);
+ int (*value_bytes16)(sqlite3_value*);
+ double (*value_double)(sqlite3_value*);
+ int (*value_int)(sqlite3_value*);
+ sqlite_int64 (*value_int64)(sqlite3_value*);
+ int (*value_numeric_type)(sqlite3_value*);
+ const unsigned char * (*value_text)(sqlite3_value*);
+ const void * (*value_text16)(sqlite3_value*);
+ const void * (*value_text16be)(sqlite3_value*);
+ const void * (*value_text16le)(sqlite3_value*);
+ int (*value_type)(sqlite3_value*);
+ char *(*vmprintf)(const char*,va_list);
+ /* Added ??? */
+ int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
+ /* Added by 3.3.13 */
+ int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
+ int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
+ int (*clear_bindings)(sqlite3_stmt*);
+ /* Added by 3.4.1 */
+ int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
+ void (*xDestroy)(void *));
+ /* Added by 3.5.0 */
+ int (*bind_zeroblob)(sqlite3_stmt*,int,int);
+ int (*blob_bytes)(sqlite3_blob*);
+ int (*blob_close)(sqlite3_blob*);
+ int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
+ int,sqlite3_blob**);
+ int (*blob_read)(sqlite3_blob*,void*,int,int);
+ int (*blob_write)(sqlite3_blob*,const void*,int,int);
+ int (*create_collation_v2)(sqlite3*,const char*,int,void*,
+ int(*)(void*,int,const void*,int,const void*),
+ void(*)(void*));
+ int (*file_control)(sqlite3*,const char*,int,void*);
+ sqlite3_int64 (*memory_highwater)(int);
+ sqlite3_int64 (*memory_used)(void);
+ sqlite3_mutex *(*mutex_alloc)(int);
+ void (*mutex_enter)(sqlite3_mutex*);
+ void (*mutex_free)(sqlite3_mutex*);
+ void (*mutex_leave)(sqlite3_mutex*);
+ int (*mutex_try)(sqlite3_mutex*);
+ int (*open_v2)(const char*,sqlite3**,int,const char*);
+ int (*release_memory)(int);
+ void (*result_error_nomem)(sqlite3_context*);
+ void (*result_error_toobig)(sqlite3_context*);
+ int (*sleep)(int);
+ void (*soft_heap_limit)(int);
+ sqlite3_vfs *(*vfs_find)(const char*);
+ int (*vfs_register)(sqlite3_vfs*,int);
+ int (*vfs_unregister)(sqlite3_vfs*);
+ int (*xthreadsafe)(void);
+ void (*result_zeroblob)(sqlite3_context*,int);
+ void (*result_error_code)(sqlite3_context*,int);
+ int (*test_control)(int, ...);
+ void (*randomness)(int,void*);
+ sqlite3 *(*context_db_handle)(sqlite3_context*);
+ int (*extended_result_codes)(sqlite3*,int);
+ int (*limit)(sqlite3*,int,int);
+ sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
+ const char *(*sql)(sqlite3_stmt*);
+ int (*status)(int,int*,int*,int);
+ int (*backup_finish)(sqlite3_backup*);
+ sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
+ int (*backup_pagecount)(sqlite3_backup*);
+ int (*backup_remaining)(sqlite3_backup*);
+ int (*backup_step)(sqlite3_backup*,int);
+ const char *(*compileoption_get)(int);
+ int (*compileoption_used)(const char*);
+ int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*),
+ void(*xDestroy)(void*));
+ int (*db_config)(sqlite3*,int,...);
+ sqlite3_mutex *(*db_mutex)(sqlite3*);
+ int (*db_status)(sqlite3*,int,int*,int*,int);
+ int (*extended_errcode)(sqlite3*);
+ void (*log)(int,const char*,...);
+ sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
+ const char *(*sourceid)(void);
+ int (*stmt_status)(sqlite3_stmt*,int,int);
+ int (*strnicmp)(const char*,const char*,int);
+ int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
+ int (*wal_autocheckpoint)(sqlite3*,int);
+ int (*wal_checkpoint)(sqlite3*,const char*);
+ void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
+ int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
+ int (*vtab_config)(sqlite3*,int op,...);
+ int (*vtab_on_conflict)(sqlite3*);
+ /* Version 3.7.16 and later */
+ int (*close_v2)(sqlite3*);
+ const char *(*db_filename)(sqlite3*,const char*);
+ int (*db_readonly)(sqlite3*,const char*);
+ int (*db_release_memory)(sqlite3*);
+ const char *(*errstr)(int);
+ int (*stmt_busy)(sqlite3_stmt*);
+ int (*stmt_readonly)(sqlite3_stmt*);
+ int (*stricmp)(const char*,const char*);
+ int (*uri_boolean)(const char*,const char*,int);
+ sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
+ const char *(*uri_parameter)(const char*,const char*);
+ char *(*xvsnprintf)(int,char*,const char*,va_list);
+ int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
+ /* Version 3.8.7 and later */
+ int (*auto_extension)(void(*)(void));
+ int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
+ void(*)(void*));
+ int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
+ void(*)(void*),unsigned char);
+ int (*cancel_auto_extension)(void(*)(void));
+ int (*load_extension)(sqlite3*,const char*,const char*,char**);
+ void *(*malloc64)(sqlite3_uint64);
+ sqlite3_uint64 (*msize)(void*);
+ void *(*realloc64)(void*,sqlite3_uint64);
+ void (*reset_auto_extension)(void);
+ void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
+ void(*)(void*));
+ void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
+ void(*)(void*), unsigned char);
+ int (*strglob)(const char*,const char*);
+ /* Version 3.8.11 and later */
+ sqlite3_value *(*value_dup)(const sqlite3_value*);
+ void (*value_free)(sqlite3_value*);
+ int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
+ int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
+ /* Version 3.9.0 and later */
+ unsigned int (*value_subtype)(sqlite3_value*);
+ void (*result_subtype)(sqlite3_context*,unsigned int);
+ /* Version 3.10.0 and later */
+ int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
+ int (*strlike)(const char*,const char*,unsigned int);
+ int (*db_cacheflush)(sqlite3*);
+ /* Version 3.12.0 and later */
+ int (*system_errno)(sqlite3*);
+ /* Version 3.14.0 and later */
+ int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
+ char *(*expanded_sql)(sqlite3_stmt*);
+ /* Version 3.18.0 and later */
+ void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
+ /* Version 3.20.0 and later */
+ int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
+ sqlite3_stmt**,const char**);
+ int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
+ sqlite3_stmt**,const void**);
+ int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
+ void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
+ void *(*value_pointer)(sqlite3_value*,const char*);
+ int (*vtab_nochange)(sqlite3_context*);
+ int (*value_nochange)(sqlite3_value*);
+ const char *(*vtab_collation)(sqlite3_index_info*,int);
+ /* Version 3.24.0 and later */
+ int (*keyword_count)(void);
+ int (*keyword_name)(int,const char**,int*);
+ int (*keyword_check)(const char*,int);
+ sqlite3_str *(*str_new)(sqlite3*);
+ char *(*str_finish)(sqlite3_str*);
+ void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);
+ void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);
+ void (*str_append)(sqlite3_str*, const char *zIn, int N);
+ void (*str_appendall)(sqlite3_str*, const char *zIn);
+ void (*str_appendchar)(sqlite3_str*, int N, char C);
+ void (*str_reset)(sqlite3_str*);
+ int (*str_errcode)(sqlite3_str*);
+ int (*str_length)(sqlite3_str*);
+ char *(*str_value)(sqlite3_str*);
+ /* Version 3.25.0 and later */
+ int (*create_window_function)(sqlite3*,const char*,int,int,void*,
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*),
+ void (*xValue)(sqlite3_context*),
+ void (*xInv)(sqlite3_context*,int,sqlite3_value**),
+ void(*xDestroy)(void*));
+ /* Version 3.26.0 and later */
+ const char *(*normalized_sql)(sqlite3_stmt*);
+ /* Version 3.28.0 and later */
+ int (*stmt_isexplain)(sqlite3_stmt*);
+ int (*value_frombind)(sqlite3_value*);
+ /* Version 3.30.0 and later */
+ int (*drop_modules)(sqlite3*,const char**);
+ /* Version 3.31.0 and later */
+ sqlite3_int64 (*hard_heap_limit64)(sqlite3_int64);
+ const char *(*uri_key)(const char*,int);
+ const char *(*filename_database)(const char*);
+ const char *(*filename_journal)(const char*);
+ const char *(*filename_wal)(const char*);
+ /* Version 3.32.0 and later */
+ char *(*create_filename)(const char*,const char*,const char*,
+ int,const char**);
+ void (*free_filename)(char*);
+ sqlite3_file *(*database_file_object)(const char*);
+};
+
+/*
+** This is the function signature used for all extension entry points. It
+** is also defined in the file "loadext.c".
+*/
+typedef int (*sqlite3_loadext_entry)(
+ sqlite3 *db, /* Handle to the database. */
+ char **pzErrMsg, /* Used to set error string on failure. */
+ const sqlite3_api_routines *pThunk /* Extension API function pointers. */
+);
+
+/*
+** The following macros redefine the API routines so that they are
+** redirected through the global sqlite3_api structure.
+**
+** This header file is also used by the loadext.c source file
+** (part of the main SQLite library - not an extension) so that
+** it can get access to the sqlite3_api_routines structure
+** definition. But the main library does not want to redefine
+** the API. So the redefinition macros are only valid if the
+** SQLITE_CORE macros is undefined.
+*/
+#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
+#define sqlite3_aggregate_context sqlite3_api->aggregate_context
+#ifndef SQLITE_OMIT_DEPRECATED
+#define sqlite3_aggregate_count sqlite3_api->aggregate_count
+#endif
+#define sqlite3_bind_blob sqlite3_api->bind_blob
+#define sqlite3_bind_double sqlite3_api->bind_double
+#define sqlite3_bind_int sqlite3_api->bind_int
+#define sqlite3_bind_int64 sqlite3_api->bind_int64
+#define sqlite3_bind_null sqlite3_api->bind_null
+#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
+#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
+#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
+#define sqlite3_bind_text sqlite3_api->bind_text
+#define sqlite3_bind_text16 sqlite3_api->bind_text16
+#define sqlite3_bind_value sqlite3_api->bind_value
+#define sqlite3_busy_handler sqlite3_api->busy_handler
+#define sqlite3_busy_timeout sqlite3_api->busy_timeout
+#define sqlite3_changes sqlite3_api->changes
+#define sqlite3_close sqlite3_api->close
+#define sqlite3_collation_needed sqlite3_api->collation_needed
+#define sqlite3_collation_needed16 sqlite3_api->collation_needed16
+#define sqlite3_column_blob sqlite3_api->column_blob
+#define sqlite3_column_bytes sqlite3_api->column_bytes
+#define sqlite3_column_bytes16 sqlite3_api->column_bytes16
+#define sqlite3_column_count sqlite3_api->column_count
+#define sqlite3_column_database_name sqlite3_api->column_database_name
+#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
+#define sqlite3_column_decltype sqlite3_api->column_decltype
+#define sqlite3_column_decltype16 sqlite3_api->column_decltype16
+#define sqlite3_column_double sqlite3_api->column_double
+#define sqlite3_column_int sqlite3_api->column_int
+#define sqlite3_column_int64 sqlite3_api->column_int64
+#define sqlite3_column_name sqlite3_api->column_name
+#define sqlite3_column_name16 sqlite3_api->column_name16
+#define sqlite3_column_origin_name sqlite3_api->column_origin_name
+#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
+#define sqlite3_column_table_name sqlite3_api->column_table_name
+#define sqlite3_column_table_name16 sqlite3_api->column_table_name16
+#define sqlite3_column_text sqlite3_api->column_text
+#define sqlite3_column_text16 sqlite3_api->column_text16
+#define sqlite3_column_type sqlite3_api->column_type
+#define sqlite3_column_value sqlite3_api->column_value
+#define sqlite3_commit_hook sqlite3_api->commit_hook
+#define sqlite3_complete sqlite3_api->complete
+#define sqlite3_complete16 sqlite3_api->complete16
+#define sqlite3_create_collation sqlite3_api->create_collation
+#define sqlite3_create_collation16 sqlite3_api->create_collation16
+#define sqlite3_create_function sqlite3_api->create_function
+#define sqlite3_create_function16 sqlite3_api->create_function16
+#define sqlite3_create_module sqlite3_api->create_module
+#define sqlite3_create_module_v2 sqlite3_api->create_module_v2
+#define sqlite3_data_count sqlite3_api->data_count
+#define sqlite3_db_handle sqlite3_api->db_handle
+#define sqlite3_declare_vtab sqlite3_api->declare_vtab
+#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
+#define sqlite3_errcode sqlite3_api->errcode
+#define sqlite3_errmsg sqlite3_api->errmsg
+#define sqlite3_errmsg16 sqlite3_api->errmsg16
+#define sqlite3_exec sqlite3_api->exec
+#ifndef SQLITE_OMIT_DEPRECATED
+#define sqlite3_expired sqlite3_api->expired
+#endif
+#define sqlite3_finalize sqlite3_api->finalize
+#define sqlite3_free sqlite3_api->free
+#define sqlite3_free_table sqlite3_api->free_table
+#define sqlite3_get_autocommit sqlite3_api->get_autocommit
+#define sqlite3_get_auxdata sqlite3_api->get_auxdata
+#define sqlite3_get_table sqlite3_api->get_table
+#ifndef SQLITE_OMIT_DEPRECATED
+#define sqlite3_global_recover sqlite3_api->global_recover
+#endif
+#define sqlite3_interrupt sqlite3_api->interruptx
+#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
+#define sqlite3_libversion sqlite3_api->libversion
+#define sqlite3_libversion_number sqlite3_api->libversion_number
+#define sqlite3_malloc sqlite3_api->malloc
+#define sqlite3_mprintf sqlite3_api->mprintf
+#define sqlite3_open sqlite3_api->open
+#define sqlite3_open16 sqlite3_api->open16
+#define sqlite3_prepare sqlite3_api->prepare
+#define sqlite3_prepare16 sqlite3_api->prepare16
+#define sqlite3_prepare_v2 sqlite3_api->prepare_v2
+#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
+#define sqlite3_profile sqlite3_api->profile
+#define sqlite3_progress_handler sqlite3_api->progress_handler
+#define sqlite3_realloc sqlite3_api->realloc
+#define sqlite3_reset sqlite3_api->reset
+#define sqlite3_result_blob sqlite3_api->result_blob
+#define sqlite3_result_double sqlite3_api->result_double
+#define sqlite3_result_error sqlite3_api->result_error
+#define sqlite3_result_error16 sqlite3_api->result_error16
+#define sqlite3_result_int sqlite3_api->result_int
+#define sqlite3_result_int64 sqlite3_api->result_int64
+#define sqlite3_result_null sqlite3_api->result_null
+#define sqlite3_result_text sqlite3_api->result_text
+#define sqlite3_result_text16 sqlite3_api->result_text16
+#define sqlite3_result_text16be sqlite3_api->result_text16be
+#define sqlite3_result_text16le sqlite3_api->result_text16le
+#define sqlite3_result_value sqlite3_api->result_value
+#define sqlite3_rollback_hook sqlite3_api->rollback_hook
+#define sqlite3_set_authorizer sqlite3_api->set_authorizer
+#define sqlite3_set_auxdata sqlite3_api->set_auxdata
+#define sqlite3_snprintf sqlite3_api->xsnprintf
+#define sqlite3_step sqlite3_api->step
+#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
+#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
+#define sqlite3_total_changes sqlite3_api->total_changes
+#define sqlite3_trace sqlite3_api->trace
+#ifndef SQLITE_OMIT_DEPRECATED
+#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
+#endif
+#define sqlite3_update_hook sqlite3_api->update_hook
+#define sqlite3_user_data sqlite3_api->user_data
+#define sqlite3_value_blob sqlite3_api->value_blob
+#define sqlite3_value_bytes sqlite3_api->value_bytes
+#define sqlite3_value_bytes16 sqlite3_api->value_bytes16
+#define sqlite3_value_double sqlite3_api->value_double
+#define sqlite3_value_int sqlite3_api->value_int
+#define sqlite3_value_int64 sqlite3_api->value_int64
+#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
+#define sqlite3_value_text sqlite3_api->value_text
+#define sqlite3_value_text16 sqlite3_api->value_text16
+#define sqlite3_value_text16be sqlite3_api->value_text16be
+#define sqlite3_value_text16le sqlite3_api->value_text16le
+#define sqlite3_value_type sqlite3_api->value_type
+#define sqlite3_vmprintf sqlite3_api->vmprintf
+#define sqlite3_vsnprintf sqlite3_api->xvsnprintf
+#define sqlite3_overload_function sqlite3_api->overload_function
+#define sqlite3_prepare_v2 sqlite3_api->prepare_v2
+#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
+#define sqlite3_clear_bindings sqlite3_api->clear_bindings
+#define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
+#define sqlite3_blob_bytes sqlite3_api->blob_bytes
+#define sqlite3_blob_close sqlite3_api->blob_close
+#define sqlite3_blob_open sqlite3_api->blob_open
+#define sqlite3_blob_read sqlite3_api->blob_read
+#define sqlite3_blob_write sqlite3_api->blob_write
+#define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
+#define sqlite3_file_control sqlite3_api->file_control
+#define sqlite3_memory_highwater sqlite3_api->memory_highwater
+#define sqlite3_memory_used sqlite3_api->memory_used
+#define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
+#define sqlite3_mutex_enter sqlite3_api->mutex_enter
+#define sqlite3_mutex_free sqlite3_api->mutex_free
+#define sqlite3_mutex_leave sqlite3_api->mutex_leave
+#define sqlite3_mutex_try sqlite3_api->mutex_try
+#define sqlite3_open_v2 sqlite3_api->open_v2
+#define sqlite3_release_memory sqlite3_api->release_memory
+#define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
+#define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
+#define sqlite3_sleep sqlite3_api->sleep
+#define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
+#define sqlite3_vfs_find sqlite3_api->vfs_find
+#define sqlite3_vfs_register sqlite3_api->vfs_register
+#define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
+#define sqlite3_threadsafe sqlite3_api->xthreadsafe
+#define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
+#define sqlite3_result_error_code sqlite3_api->result_error_code
+#define sqlite3_test_control sqlite3_api->test_control
+#define sqlite3_randomness sqlite3_api->randomness
+#define sqlite3_context_db_handle sqlite3_api->context_db_handle
+#define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
+#define sqlite3_limit sqlite3_api->limit
+#define sqlite3_next_stmt sqlite3_api->next_stmt
+#define sqlite3_sql sqlite3_api->sql
+#define sqlite3_status sqlite3_api->status
+#define sqlite3_backup_finish sqlite3_api->backup_finish
+#define sqlite3_backup_init sqlite3_api->backup_init
+#define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
+#define sqlite3_backup_remaining sqlite3_api->backup_remaining
+#define sqlite3_backup_step sqlite3_api->backup_step
+#define sqlite3_compileoption_get sqlite3_api->compileoption_get
+#define sqlite3_compileoption_used sqlite3_api->compileoption_used
+#define sqlite3_create_function_v2 sqlite3_api->create_function_v2
+#define sqlite3_db_config sqlite3_api->db_config
+#define sqlite3_db_mutex sqlite3_api->db_mutex
+#define sqlite3_db_status sqlite3_api->db_status
+#define sqlite3_extended_errcode sqlite3_api->extended_errcode
+#define sqlite3_log sqlite3_api->log
+#define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
+#define sqlite3_sourceid sqlite3_api->sourceid
+#define sqlite3_stmt_status sqlite3_api->stmt_status
+#define sqlite3_strnicmp sqlite3_api->strnicmp
+#define sqlite3_unlock_notify sqlite3_api->unlock_notify
+#define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
+#define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
+#define sqlite3_wal_hook sqlite3_api->wal_hook
+#define sqlite3_blob_reopen sqlite3_api->blob_reopen
+#define sqlite3_vtab_config sqlite3_api->vtab_config
+#define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
+/* Version 3.7.16 and later */
+#define sqlite3_close_v2 sqlite3_api->close_v2
+#define sqlite3_db_filename sqlite3_api->db_filename
+#define sqlite3_db_readonly sqlite3_api->db_readonly
+#define sqlite3_db_release_memory sqlite3_api->db_release_memory
+#define sqlite3_errstr sqlite3_api->errstr
+#define sqlite3_stmt_busy sqlite3_api->stmt_busy
+#define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
+#define sqlite3_stricmp sqlite3_api->stricmp
+#define sqlite3_uri_boolean sqlite3_api->uri_boolean
+#define sqlite3_uri_int64 sqlite3_api->uri_int64
+#define sqlite3_uri_parameter sqlite3_api->uri_parameter
+#define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf
+#define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
+/* Version 3.8.7 and later */
+#define sqlite3_auto_extension sqlite3_api->auto_extension
+#define sqlite3_bind_blob64 sqlite3_api->bind_blob64
+#define sqlite3_bind_text64 sqlite3_api->bind_text64
+#define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
+#define sqlite3_load_extension sqlite3_api->load_extension
+#define sqlite3_malloc64 sqlite3_api->malloc64
+#define sqlite3_msize sqlite3_api->msize
+#define sqlite3_realloc64 sqlite3_api->realloc64
+#define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
+#define sqlite3_result_blob64 sqlite3_api->result_blob64
+#define sqlite3_result_text64 sqlite3_api->result_text64
+#define sqlite3_strglob sqlite3_api->strglob
+/* Version 3.8.11 and later */
+#define sqlite3_value_dup sqlite3_api->value_dup
+#define sqlite3_value_free sqlite3_api->value_free
+#define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
+#define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
+/* Version 3.9.0 and later */
+#define sqlite3_value_subtype sqlite3_api->value_subtype
+#define sqlite3_result_subtype sqlite3_api->result_subtype
+/* Version 3.10.0 and later */
+#define sqlite3_status64 sqlite3_api->status64
+#define sqlite3_strlike sqlite3_api->strlike
+#define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
+/* Version 3.12.0 and later */
+#define sqlite3_system_errno sqlite3_api->system_errno
+/* Version 3.14.0 and later */
+#define sqlite3_trace_v2 sqlite3_api->trace_v2
+#define sqlite3_expanded_sql sqlite3_api->expanded_sql
+/* Version 3.18.0 and later */
+#define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
+/* Version 3.20.0 and later */
+#define sqlite3_prepare_v3 sqlite3_api->prepare_v3
+#define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3
+#define sqlite3_bind_pointer sqlite3_api->bind_pointer
+#define sqlite3_result_pointer sqlite3_api->result_pointer
+#define sqlite3_value_pointer sqlite3_api->value_pointer
+/* Version 3.22.0 and later */
+#define sqlite3_vtab_nochange sqlite3_api->vtab_nochange
+#define sqlite3_value_nochange sqlite3_api->value_nochange
+#define sqlite3_vtab_collation sqlite3_api->vtab_collation
+/* Version 3.24.0 and later */
+#define sqlite3_keyword_count sqlite3_api->keyword_count
+#define sqlite3_keyword_name sqlite3_api->keyword_name
+#define sqlite3_keyword_check sqlite3_api->keyword_check
+#define sqlite3_str_new sqlite3_api->str_new
+#define sqlite3_str_finish sqlite3_api->str_finish
+#define sqlite3_str_appendf sqlite3_api->str_appendf
+#define sqlite3_str_vappendf sqlite3_api->str_vappendf
+#define sqlite3_str_append sqlite3_api->str_append
+#define sqlite3_str_appendall sqlite3_api->str_appendall
+#define sqlite3_str_appendchar sqlite3_api->str_appendchar
+#define sqlite3_str_reset sqlite3_api->str_reset
+#define sqlite3_str_errcode sqlite3_api->str_errcode
+#define sqlite3_str_length sqlite3_api->str_length
+#define sqlite3_str_value sqlite3_api->str_value
+/* Version 3.25.0 and later */
+#define sqlite3_create_window_function sqlite3_api->create_window_function
+/* Version 3.26.0 and later */
+#define sqlite3_normalized_sql sqlite3_api->normalized_sql
+/* Version 3.28.0 and later */
+#define sqlite3_stmt_isexplain sqlite3_api->stmt_isexplain
+#define sqlite3_value_frombind sqlite3_api->value_frombind
+/* Version 3.30.0 and later */
+#define sqlite3_drop_modules sqlite3_api->drop_modules
+/* Version 3.31.0 and later */
+#define sqlite3_hard_heap_limit64 sqlite3_api->hard_heap_limit64
+#define sqlite3_uri_key sqlite3_api->uri_key
+#define sqlite3_filename_database sqlite3_api->filename_database
+#define sqlite3_filename_journal sqlite3_api->filename_journal
+#define sqlite3_filename_wal sqlite3_api->filename_wal
+/* Version 3.32.0 and later */
+#define sqlite3_create_filename sqlite3_api->create_filename
+#define sqlite3_free_filename sqlite3_api->free_filename
+#define sqlite3_database_file_object sqlite3_api->database_file_object
+#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
+
+#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
+ /* This case when the file really is being compiled as a loadable
+ ** extension */
+# define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
+# define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
+# define SQLITE_EXTENSION_INIT3 \
+ extern const sqlite3_api_routines *sqlite3_api;
+#else
+ /* This case when the file is being statically linked into the
+ ** application */
+# define SQLITE_EXTENSION_INIT1 /*no-op*/
+# define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
+# define SQLITE_EXTENSION_INIT3 /*no-op*/
+#endif
+
+#endif /* SQLITE3EXT_H */
+
+/************** End of sqlite3ext.h ******************************************/
+/************** Continuing where we left off in loadext.c ********************/
+/* #include "sqliteInt.h" */
+
+#ifndef SQLITE_OMIT_LOAD_EXTENSION
+/*
+** Some API routines are omitted when various features are
+** excluded from a build of SQLite. Substitute a NULL pointer
+** for any missing APIs.
+*/
+#ifndef SQLITE_ENABLE_COLUMN_METADATA
+# define sqlite3_column_database_name 0
+# define sqlite3_column_database_name16 0
+# define sqlite3_column_table_name 0
+# define sqlite3_column_table_name16 0
+# define sqlite3_column_origin_name 0
+# define sqlite3_column_origin_name16 0
+#endif
+
+#ifdef SQLITE_OMIT_AUTHORIZATION
+# define sqlite3_set_authorizer 0
+#endif
+
+#ifdef SQLITE_OMIT_UTF16
+# define sqlite3_bind_text16 0
+# define sqlite3_collation_needed16 0
+# define sqlite3_column_decltype16 0
+# define sqlite3_column_name16 0
+# define sqlite3_column_text16 0
+# define sqlite3_complete16 0
+# define sqlite3_create_collation16 0
+# define sqlite3_create_function16 0
+# define sqlite3_errmsg16 0
+# define sqlite3_open16 0
+# define sqlite3_prepare16 0
+# define sqlite3_prepare16_v2 0
+# define sqlite3_prepare16_v3 0
+# define sqlite3_result_error16 0
+# define sqlite3_result_text16 0
+# define sqlite3_result_text16be 0
+# define sqlite3_result_text16le 0
+# define sqlite3_value_text16 0
+# define sqlite3_value_text16be 0
+# define sqlite3_value_text16le 0
+# define sqlite3_column_database_name16 0
+# define sqlite3_column_table_name16 0
+# define sqlite3_column_origin_name16 0
+#endif
+
+#ifdef SQLITE_OMIT_COMPLETE
+# define sqlite3_complete 0
+# define sqlite3_complete16 0
+#endif
+
+#ifdef SQLITE_OMIT_DECLTYPE
+# define sqlite3_column_decltype16 0
+# define sqlite3_column_decltype 0
+#endif
+
+#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
+# define sqlite3_progress_handler 0
+#endif
+
+#ifdef SQLITE_OMIT_VIRTUALTABLE
+# define sqlite3_create_module 0
+# define sqlite3_create_module_v2 0
+# define sqlite3_declare_vtab 0
+# define sqlite3_vtab_config 0
+# define sqlite3_vtab_on_conflict 0
+# define sqlite3_vtab_collation 0
+#endif
+
+#ifdef SQLITE_OMIT_SHARED_CACHE
+# define sqlite3_enable_shared_cache 0
+#endif
+
+#if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
+# define sqlite3_profile 0
+# define sqlite3_trace 0
+#endif
+
+#ifdef SQLITE_OMIT_GET_TABLE
+# define sqlite3_free_table 0
+# define sqlite3_get_table 0
+#endif
+
+#ifdef SQLITE_OMIT_INCRBLOB
+#define sqlite3_bind_zeroblob 0
+#define sqlite3_blob_bytes 0
+#define sqlite3_blob_close 0
+#define sqlite3_blob_open 0
+#define sqlite3_blob_read 0
+#define sqlite3_blob_write 0
+#define sqlite3_blob_reopen 0
+#endif
+
+#if defined(SQLITE_OMIT_TRACE)
+# define sqlite3_trace_v2 0
+#endif
+
+/*
+** The following structure contains pointers to all SQLite API routines.
+** A pointer to this structure is passed into extensions when they are
+** loaded so that the extension can make calls back into the SQLite
+** library.
+**
+** When adding new APIs, add them to the bottom of this structure
+** in order to preserve backwards compatibility.
+**
+** Extensions that use newer APIs should first call the
+** sqlite3_libversion_number() to make sure that the API they
+** intend to use is supported by the library. Extensions should
+** also check to make sure that the pointer to the function is
+** not NULL before calling it.
+*/
+static const sqlite3_api_routines sqlite3Apis = {
+ sqlite3_aggregate_context,
+#ifndef SQLITE_OMIT_DEPRECATED
+ sqlite3_aggregate_count,
+#else
+ 0,
+#endif
+ sqlite3_bind_blob,
+ sqlite3_bind_double,
+ sqlite3_bind_int,
+ sqlite3_bind_int64,
+ sqlite3_bind_null,
+ sqlite3_bind_parameter_count,
+ sqlite3_bind_parameter_index,
+ sqlite3_bind_parameter_name,
+ sqlite3_bind_text,
+ sqlite3_bind_text16,
+ sqlite3_bind_value,
+ sqlite3_busy_handler,
+ sqlite3_busy_timeout,
+ sqlite3_changes,
+ sqlite3_close,
+ sqlite3_collation_needed,
+ sqlite3_collation_needed16,
+ sqlite3_column_blob,
+ sqlite3_column_bytes,
+ sqlite3_column_bytes16,
+ sqlite3_column_count,
+ sqlite3_column_database_name,
+ sqlite3_column_database_name16,
+ sqlite3_column_decltype,
+ sqlite3_column_decltype16,
+ sqlite3_column_double,
+ sqlite3_column_int,
+ sqlite3_column_int64,
+ sqlite3_column_name,
+ sqlite3_column_name16,
+ sqlite3_column_origin_name,
+ sqlite3_column_origin_name16,
+ sqlite3_column_table_name,
+ sqlite3_column_table_name16,
+ sqlite3_column_text,
+ sqlite3_column_text16,
+ sqlite3_column_type,
+ sqlite3_column_value,
+ sqlite3_commit_hook,
+ sqlite3_complete,
+ sqlite3_complete16,
+ sqlite3_create_collation,
+ sqlite3_create_collation16,
+ sqlite3_create_function,
+ sqlite3_create_function16,
+ sqlite3_create_module,
+ sqlite3_data_count,
+ sqlite3_db_handle,
+ sqlite3_declare_vtab,
+ sqlite3_enable_shared_cache,
+ sqlite3_errcode,
+ sqlite3_errmsg,
+ sqlite3_errmsg16,
+ sqlite3_exec,
+#ifndef SQLITE_OMIT_DEPRECATED
+ sqlite3_expired,
+#else
+ 0,
+#endif
+ sqlite3_finalize,
+ sqlite3_free,
+ sqlite3_free_table,
+ sqlite3_get_autocommit,
+ sqlite3_get_auxdata,
+ sqlite3_get_table,
+ 0, /* Was sqlite3_global_recover(), but that function is deprecated */
+ sqlite3_interrupt,
+ sqlite3_last_insert_rowid,
+ sqlite3_libversion,
+ sqlite3_libversion_number,
+ sqlite3_malloc,
+ sqlite3_mprintf,
+ sqlite3_open,
+ sqlite3_open16,
+ sqlite3_prepare,
+ sqlite3_prepare16,
+ sqlite3_profile,
+ sqlite3_progress_handler,
+ sqlite3_realloc,
+ sqlite3_reset,
+ sqlite3_result_blob,
+ sqlite3_result_double,
+ sqlite3_result_error,
+ sqlite3_result_error16,
+ sqlite3_result_int,
+ sqlite3_result_int64,
+ sqlite3_result_null,
+ sqlite3_result_text,
+ sqlite3_result_text16,
+ sqlite3_result_text16be,
+ sqlite3_result_text16le,
+ sqlite3_result_value,
+ sqlite3_rollback_hook,
+ sqlite3_set_authorizer,
+ sqlite3_set_auxdata,
+ sqlite3_snprintf,
+ sqlite3_step,
+ sqlite3_table_column_metadata,
+#ifndef SQLITE_OMIT_DEPRECATED
+ sqlite3_thread_cleanup,
+#else
+ 0,
+#endif
+ sqlite3_total_changes,
+ sqlite3_trace,
+#ifndef SQLITE_OMIT_DEPRECATED
+ sqlite3_transfer_bindings,
+#else
+ 0,
+#endif
+ sqlite3_update_hook,
+ sqlite3_user_data,
+ sqlite3_value_blob,
+ sqlite3_value_bytes,
+ sqlite3_value_bytes16,
+ sqlite3_value_double,
+ sqlite3_value_int,
+ sqlite3_value_int64,
+ sqlite3_value_numeric_type,
+ sqlite3_value_text,
+ sqlite3_value_text16,
+ sqlite3_value_text16be,
+ sqlite3_value_text16le,
+ sqlite3_value_type,
+ sqlite3_vmprintf,
+ /*
+ ** The original API set ends here. All extensions can call any
+ ** of the APIs above provided that the pointer is not NULL. But
+ ** before calling APIs that follow, extension should check the
+ ** sqlite3_libversion_number() to make sure they are dealing with
+ ** a library that is new enough to support that API.
+ *************************************************************************
+ */
+ sqlite3_overload_function,
+
+ /*
+ ** Added after 3.3.13
+ */
+ sqlite3_prepare_v2,
+ sqlite3_prepare16_v2,
+ sqlite3_clear_bindings,
+
+ /*
+ ** Added for 3.4.1
+ */
+ sqlite3_create_module_v2,
+
+ /*
+ ** Added for 3.5.0
+ */
+ sqlite3_bind_zeroblob,
+ sqlite3_blob_bytes,
+ sqlite3_blob_close,
+ sqlite3_blob_open,
+ sqlite3_blob_read,
+ sqlite3_blob_write,
+ sqlite3_create_collation_v2,
+ sqlite3_file_control,
+ sqlite3_memory_highwater,
+ sqlite3_memory_used,
+#ifdef SQLITE_MUTEX_OMIT
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+#else
+ sqlite3_mutex_alloc,
+ sqlite3_mutex_enter,
+ sqlite3_mutex_free,
+ sqlite3_mutex_leave,
+ sqlite3_mutex_try,
+#endif
+ sqlite3_open_v2,
+ sqlite3_release_memory,
+ sqlite3_result_error_nomem,
+ sqlite3_result_error_toobig,
+ sqlite3_sleep,
+ sqlite3_soft_heap_limit,
+ sqlite3_vfs_find,
+ sqlite3_vfs_register,
+ sqlite3_vfs_unregister,
+
+ /*
+ ** Added for 3.5.8
+ */
+ sqlite3_threadsafe,
+ sqlite3_result_zeroblob,
+ sqlite3_result_error_code,
+ sqlite3_test_control,
+ sqlite3_randomness,
+ sqlite3_context_db_handle,
+
+ /*
+ ** Added for 3.6.0
+ */
+ sqlite3_extended_result_codes,
+ sqlite3_limit,
+ sqlite3_next_stmt,
+ sqlite3_sql,
+ sqlite3_status,
+
+ /*
+ ** Added for 3.7.4
+ */
+ sqlite3_backup_finish,
+ sqlite3_backup_init,
+ sqlite3_backup_pagecount,
+ sqlite3_backup_remaining,
+ sqlite3_backup_step,
+#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
+ sqlite3_compileoption_get,
+ sqlite3_compileoption_used,
+#else
+ 0,
+ 0,
+#endif
+ sqlite3_create_function_v2,
+ sqlite3_db_config,
+ sqlite3_db_mutex,
+ sqlite3_db_status,
+ sqlite3_extended_errcode,
+ sqlite3_log,
+ sqlite3_soft_heap_limit64,
+ sqlite3_sourceid,
+ sqlite3_stmt_status,
+ sqlite3_strnicmp,
+#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
+ sqlite3_unlock_notify,
+#else
+ 0,
+#endif
+#ifndef SQLITE_OMIT_WAL
+ sqlite3_wal_autocheckpoint,
+ sqlite3_wal_checkpoint,
+ sqlite3_wal_hook,
+#else
+ 0,
+ 0,
+ 0,
+#endif
+ sqlite3_blob_reopen,
+ sqlite3_vtab_config,
+ sqlite3_vtab_on_conflict,
+ sqlite3_close_v2,
+ sqlite3_db_filename,
+ sqlite3_db_readonly,
+ sqlite3_db_release_memory,
+ sqlite3_errstr,
+ sqlite3_stmt_busy,
+ sqlite3_stmt_readonly,
+ sqlite3_stricmp,
+ sqlite3_uri_boolean,
+ sqlite3_uri_int64,
+ sqlite3_uri_parameter,
+ sqlite3_vsnprintf,
+ sqlite3_wal_checkpoint_v2,
+ /* Version 3.8.7 and later */
+ sqlite3_auto_extension,
+ sqlite3_bind_blob64,
+ sqlite3_bind_text64,
+ sqlite3_cancel_auto_extension,
+ sqlite3_load_extension,
+ sqlite3_malloc64,
+ sqlite3_msize,
+ sqlite3_realloc64,
+ sqlite3_reset_auto_extension,
+ sqlite3_result_blob64,
+ sqlite3_result_text64,
+ sqlite3_strglob,
+ /* Version 3.8.11 and later */
+ (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
+ sqlite3_value_free,
+ sqlite3_result_zeroblob64,
+ sqlite3_bind_zeroblob64,
+ /* Version 3.9.0 and later */
+ sqlite3_value_subtype,
+ sqlite3_result_subtype,
+ /* Version 3.10.0 and later */
+ sqlite3_status64,
+ sqlite3_strlike,
+ sqlite3_db_cacheflush,
+ /* Version 3.12.0 and later */
+ sqlite3_system_errno,
+ /* Version 3.14.0 and later */
+ sqlite3_trace_v2,
+ sqlite3_expanded_sql,
+ /* Version 3.18.0 and later */
+ sqlite3_set_last_insert_rowid,
+ /* Version 3.20.0 and later */
+ sqlite3_prepare_v3,
+ sqlite3_prepare16_v3,
+ sqlite3_bind_pointer,
+ sqlite3_result_pointer,
+ sqlite3_value_pointer,
+ /* Version 3.22.0 and later */
+ sqlite3_vtab_nochange,
+ sqlite3_value_nochange,
+ sqlite3_vtab_collation,
+ /* Version 3.24.0 and later */
+ sqlite3_keyword_count,
+ sqlite3_keyword_name,
+ sqlite3_keyword_check,
+ sqlite3_str_new,
+ sqlite3_str_finish,
+ sqlite3_str_appendf,
+ sqlite3_str_vappendf,
+ sqlite3_str_append,
+ sqlite3_str_appendall,
+ sqlite3_str_appendchar,
+ sqlite3_str_reset,
+ sqlite3_str_errcode,
+ sqlite3_str_length,
+ sqlite3_str_value,
+ /* Version 3.25.0 and later */
+ sqlite3_create_window_function,
+ /* Version 3.26.0 and later */
+#ifdef SQLITE_ENABLE_NORMALIZE
+ sqlite3_normalized_sql,
+#else
+ 0,
+#endif
+ /* Version 3.28.0 and later */
+ sqlite3_stmt_isexplain,
+ sqlite3_value_frombind,
+ /* Version 3.30.0 and later */
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ sqlite3_drop_modules,
+#else
+ 0,
+#endif
+ /* Version 3.31.0 and later */
+ sqlite3_hard_heap_limit64,
+ sqlite3_uri_key,
+ sqlite3_filename_database,
+ sqlite3_filename_journal,
+ sqlite3_filename_wal,
+ /* Version 3.32.0 and later */
+ sqlite3_create_filename,
+ sqlite3_free_filename,
+ sqlite3_database_file_object,
+};
+
+/* True if x is the directory separator character
+*/
+#if SQLITE_OS_WIN
+# define DirSep(X) ((X)=='/'||(X)=='\\')
+#else
+# define DirSep(X) ((X)=='/')
+#endif
+
+/*
+** Attempt to load an SQLite extension library contained in the file
+** zFile. The entry point is zProc. zProc may be 0 in which case a
+** default entry point name (sqlite3_extension_init) is used. Use
+** of the default name is recommended.
+**
+** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
+**
+** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
+** error message text. The calling function should free this memory
+** by calling sqlite3DbFree(db, ).
+*/
+static int sqlite3LoadExtension(
+ sqlite3 *db, /* Load the extension into this database connection */
+ const char *zFile, /* Name of the shared library containing extension */
+ const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
+ char **pzErrMsg /* Put error message here if not 0 */
+){
+ sqlite3_vfs *pVfs = db->pVfs;
+ void *handle;
+ sqlite3_loadext_entry xInit;
+ char *zErrmsg = 0;
+ const char *zEntry;
+ char *zAltEntry = 0;
+ void **aHandle;
+ u64 nMsg = 300 + sqlite3Strlen30(zFile);
+ int ii;
+ int rc;
+
+ /* Shared library endings to try if zFile cannot be loaded as written */
+ static const char *azEndings[] = {
+#if SQLITE_OS_WIN
+ "dll"
+#elif defined(__APPLE__)
+ "dylib"
+#else
+ "so"
+#endif
+ };
+
+
+ if( pzErrMsg ) *pzErrMsg = 0;
+
+ /* Ticket #1863. To avoid a creating security problems for older
+ ** applications that relink against newer versions of SQLite, the
+ ** ability to run load_extension is turned off by default. One
+ ** must call either sqlite3_enable_load_extension(db) or
+ ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
+ ** to turn on extension loading.
+ */
+ if( (db->flags & SQLITE_LoadExtension)==0 ){
+ if( pzErrMsg ){
+ *pzErrMsg = sqlite3_mprintf("not authorized");
+ }
+ return SQLITE_ERROR;
+ }
+
+ zEntry = zProc ? zProc : "sqlite3_extension_init";
+
+ handle = sqlite3OsDlOpen(pVfs, zFile);
+#if SQLITE_OS_UNIX || SQLITE_OS_WIN
+ for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
+ char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
+ if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
+ handle = sqlite3OsDlOpen(pVfs, zAltFile);
+ sqlite3_free(zAltFile);
+ }
+#endif
+ if( handle==0 ){
+ if( pzErrMsg ){
+ *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
+ if( zErrmsg ){
+ sqlite3_snprintf(nMsg, zErrmsg,
+ "unable to open shared library [%s]", zFile);
+ sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
+ }
+ }
+ return SQLITE_ERROR;
+ }
+ xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
+
+ /* If no entry point was specified and the default legacy
+ ** entry point name "sqlite3_extension_init" was not found, then
+ ** construct an entry point name "sqlite3_X_init" where the X is
+ ** replaced by the lowercase value of every ASCII alphabetic
+ ** character in the filename after the last "/" upto the first ".",
+ ** and eliding the first three characters if they are "lib".
+ ** Examples:
+ **
+ ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
+ ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
+ */
+ if( xInit==0 && zProc==0 ){
+ int iFile, iEntry, c;
+ int ncFile = sqlite3Strlen30(zFile);
+ zAltEntry = sqlite3_malloc64(ncFile+30);
+ if( zAltEntry==0 ){
+ sqlite3OsDlClose(pVfs, handle);
+ return SQLITE_NOMEM_BKPT;
+ }
+ memcpy(zAltEntry, "sqlite3_", 8);
+ for(iFile=ncFile-1; iFile>=0 && !DirSep(zFile[iFile]); iFile--){}
+ iFile++;
+ if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
+ for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
+ if( sqlite3Isalpha(c) ){
+ zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
+ }
+ }
+ memcpy(zAltEntry+iEntry, "_init", 6);
+ zEntry = zAltEntry;
+ xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
+ }
+ if( xInit==0 ){
+ if( pzErrMsg ){
+ nMsg += sqlite3Strlen30(zEntry);
+ *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
+ if( zErrmsg ){
+ sqlite3_snprintf(nMsg, zErrmsg,
+ "no entry point [%s] in shared library [%s]", zEntry, zFile);
+ sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
+ }
+ }
+ sqlite3OsDlClose(pVfs, handle);
+ sqlite3_free(zAltEntry);
+ return SQLITE_ERROR;
+ }
+ sqlite3_free(zAltEntry);
+ rc = xInit(db, &zErrmsg, &sqlite3Apis);
+ if( rc ){
+ if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
+ if( pzErrMsg ){
+ *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
+ }
+ sqlite3_free(zErrmsg);
+ sqlite3OsDlClose(pVfs, handle);
+ return SQLITE_ERROR;
+ }
+
+ /* Append the new shared library handle to the db->aExtension array. */
+ aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
+ if( aHandle==0 ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ if( db->nExtension>0 ){
+ memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
+ }
+ sqlite3DbFree(db, db->aExtension);
+ db->aExtension = aHandle;
+
+ db->aExtension[db->nExtension++] = handle;
+ return SQLITE_OK;
+}
+SQLITE_API int sqlite3_load_extension(
+ sqlite3 *db, /* Load the extension into this database connection */
+ const char *zFile, /* Name of the shared library containing extension */
+ const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
+ char **pzErrMsg /* Put error message here if not 0 */
+){
+ int rc;
+ sqlite3_mutex_enter(db->mutex);
+ rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
+ rc = sqlite3ApiExit(db, rc);
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+/*
+** Call this routine when the database connection is closing in order
+** to clean up loaded extensions
+*/
+SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
+ int i;
+ assert( sqlite3_mutex_held(db->mutex) );
+ for(i=0; i<db->nExtension; i++){
+ sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
+ }
+ sqlite3DbFree(db, db->aExtension);
+}
+
+/*
+** Enable or disable extension loading. Extension loading is disabled by
+** default so as not to open security holes in older applications.
+*/
+SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
+ sqlite3_mutex_enter(db->mutex);
+ if( onoff ){
+ db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
+ }else{
+ db->flags &= ~(u64)(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
+ }
+ sqlite3_mutex_leave(db->mutex);
+ return SQLITE_OK;
+}
+
+#endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
+
+/*
+** The following object holds the list of automatically loaded
+** extensions.
+**
+** This list is shared across threads. The SQLITE_MUTEX_STATIC_MAIN
+** mutex must be held while accessing this list.
+*/
+typedef struct sqlite3AutoExtList sqlite3AutoExtList;
+static SQLITE_WSD struct sqlite3AutoExtList {
+ u32 nExt; /* Number of entries in aExt[] */
+ void (**aExt)(void); /* Pointers to the extension init functions */
+} sqlite3Autoext = { 0, 0 };
+
+/* The "wsdAutoext" macro will resolve to the autoextension
+** state vector. If writable static data is unsupported on the target,
+** we have to locate the state vector at run-time. In the more common
+** case where writable static data is supported, wsdStat can refer directly
+** to the "sqlite3Autoext" state vector declared above.
+*/
+#ifdef SQLITE_OMIT_WSD
+# define wsdAutoextInit \
+ sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
+# define wsdAutoext x[0]
+#else
+# define wsdAutoextInit
+# define wsdAutoext sqlite3Autoext
+#endif
+
+
+/*
+** Register a statically linked extension that is automatically
+** loaded by every new database connection.
+*/
+SQLITE_API int sqlite3_auto_extension(
+ void (*xInit)(void)
+){
+ int rc = SQLITE_OK;
+#ifndef SQLITE_OMIT_AUTOINIT
+ rc = sqlite3_initialize();
+ if( rc ){
+ return rc;
+ }else
+#endif
+ {
+ u32 i;
+#if SQLITE_THREADSAFE
+ sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
+#endif
+ wsdAutoextInit;
+ sqlite3_mutex_enter(mutex);
+ for(i=0; i<wsdAutoext.nExt; i++){
+ if( wsdAutoext.aExt[i]==xInit ) break;
+ }
+ if( i==wsdAutoext.nExt ){
+ u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
+ void (**aNew)(void);
+ aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
+ if( aNew==0 ){
+ rc = SQLITE_NOMEM_BKPT;
+ }else{
+ wsdAutoext.aExt = aNew;
+ wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
+ wsdAutoext.nExt++;
+ }
+ }
+ sqlite3_mutex_leave(mutex);
+ assert( (rc&0xff)==rc );
+ return rc;
+ }
+}
+
+/*
+** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
+** set of routines that is invoked for each new database connection, if it
+** is currently on the list. If xInit is not on the list, then this
+** routine is a no-op.
+**
+** Return 1 if xInit was found on the list and removed. Return 0 if xInit
+** was not on the list.
+*/
+SQLITE_API int sqlite3_cancel_auto_extension(
+ void (*xInit)(void)
+){
+#if SQLITE_THREADSAFE
+ sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
+#endif
+ int i;
+ int n = 0;
+ wsdAutoextInit;
+ sqlite3_mutex_enter(mutex);
+ for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
+ if( wsdAutoext.aExt[i]==xInit ){
+ wsdAutoext.nExt--;
+ wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
+ n++;
+ break;
+ }
+ }
+ sqlite3_mutex_leave(mutex);
+ return n;
+}
+
+/*
+** Reset the automatic extension loading mechanism.
+*/
+SQLITE_API void sqlite3_reset_auto_extension(void){
+#ifndef SQLITE_OMIT_AUTOINIT
+ if( sqlite3_initialize()==SQLITE_OK )
+#endif
+ {
+#if SQLITE_THREADSAFE
+ sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
+#endif
+ wsdAutoextInit;
+ sqlite3_mutex_enter(mutex);
+ sqlite3_free(wsdAutoext.aExt);
+ wsdAutoext.aExt = 0;
+ wsdAutoext.nExt = 0;
+ sqlite3_mutex_leave(mutex);
+ }
+}
+
+/*
+** Load all automatic extensions.
+**
+** If anything goes wrong, set an error in the database connection.
+*/
+SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
+ u32 i;
+ int go = 1;
+ int rc;
+ sqlite3_loadext_entry xInit;
+
+ wsdAutoextInit;
+ if( wsdAutoext.nExt==0 ){
+ /* Common case: early out without every having to acquire a mutex */
+ return;
+ }
+ for(i=0; go; i++){
+ char *zErrmsg;
+#if SQLITE_THREADSAFE
+ sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
+#endif
+#ifdef SQLITE_OMIT_LOAD_EXTENSION
+ const sqlite3_api_routines *pThunk = 0;
+#else
+ const sqlite3_api_routines *pThunk = &sqlite3Apis;
+#endif
+ sqlite3_mutex_enter(mutex);
+ if( i>=wsdAutoext.nExt ){
+ xInit = 0;
+ go = 0;
+ }else{
+ xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
+ }
+ sqlite3_mutex_leave(mutex);
+ zErrmsg = 0;
+ if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
+ sqlite3ErrorWithMsg(db, rc,
+ "automatic extension loading failed: %s", zErrmsg);
+ go = 0;
+ }
+ sqlite3_free(zErrmsg);
+ }
+}
+
+/************** End of loadext.c *********************************************/
+/************** Begin file pragma.c ******************************************/
+/*
+** 2003 April 6
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code used to implement the PRAGMA command.
+*/
+/* #include "sqliteInt.h" */
+
+#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
+# if defined(__APPLE__)
+# define SQLITE_ENABLE_LOCKING_STYLE 1
+# else
+# define SQLITE_ENABLE_LOCKING_STYLE 0
+# endif
+#endif
+
+/***************************************************************************
+** The "pragma.h" include file is an automatically generated file that
+** that includes the PragType_XXXX macro definitions and the aPragmaName[]
+** object. This ensures that the aPragmaName[] table is arranged in
+** lexicographical order to facility a binary search of the pragma name.
+** Do not edit pragma.h directly. Edit and rerun the script in at
+** ../tool/mkpragmatab.tcl. */
+/************** Include pragma.h in the middle of pragma.c *******************/
+/************** Begin file pragma.h ******************************************/
+/* DO NOT EDIT!
+** This file is automatically generated by the script at
+** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
+** that script and rerun it.
+*/
+
+/* The various pragma types */
+#define PragTyp_ACTIVATE_EXTENSIONS 0
+#define PragTyp_ANALYSIS_LIMIT 1
+#define PragTyp_HEADER_VALUE 2
+#define PragTyp_AUTO_VACUUM 3
+#define PragTyp_FLAG 4
+#define PragTyp_BUSY_TIMEOUT 5
+#define PragTyp_CACHE_SIZE 6
+#define PragTyp_CACHE_SPILL 7
+#define PragTyp_CASE_SENSITIVE_LIKE 8
+#define PragTyp_COLLATION_LIST 9
+#define PragTyp_COMPILE_OPTIONS 10
+#define PragTyp_DATA_STORE_DIRECTORY 11
+#define PragTyp_DATABASE_LIST 12
+#define PragTyp_DEFAULT_CACHE_SIZE 13
+#define PragTyp_ENCODING 14
+#define PragTyp_FOREIGN_KEY_CHECK 15
+#define PragTyp_FOREIGN_KEY_LIST 16
+#define PragTyp_FUNCTION_LIST 17
+#define PragTyp_HARD_HEAP_LIMIT 18
+#define PragTyp_INCREMENTAL_VACUUM 19
+#define PragTyp_INDEX_INFO 20
+#define PragTyp_INDEX_LIST 21
+#define PragTyp_INTEGRITY_CHECK 22
+#define PragTyp_JOURNAL_MODE 23
+#define PragTyp_JOURNAL_SIZE_LIMIT 24
+#define PragTyp_LOCK_PROXY_FILE 25
+#define PragTyp_LOCKING_MODE 26
+#define PragTyp_PAGE_COUNT 27
+#define PragTyp_MMAP_SIZE 28
+#define PragTyp_MODULE_LIST 29
+#define PragTyp_OPTIMIZE 30
+#define PragTyp_PAGE_SIZE 31
+#define PragTyp_PRAGMA_LIST 32
+#define PragTyp_SECURE_DELETE 33
+#define PragTyp_SHRINK_MEMORY 34
+#define PragTyp_SOFT_HEAP_LIMIT 35
+#define PragTyp_SYNCHRONOUS 36
+#define PragTyp_TABLE_INFO 37
+#define PragTyp_TEMP_STORE 38
+#define PragTyp_TEMP_STORE_DIRECTORY 39
+#define PragTyp_THREADS 40
+#define PragTyp_WAL_AUTOCHECKPOINT 41
+#define PragTyp_WAL_CHECKPOINT 42
+#define PragTyp_LOCK_STATUS 43
+#define PragTyp_STATS 44
+
+/* Property flags associated with various pragma. */
+#define PragFlg_NeedSchema 0x01 /* Force schema load before running */
+#define PragFlg_NoColumns 0x02 /* OP_ResultRow called with zero columns */
+#define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
+#define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */
+#define PragFlg_Result0 0x10 /* Acts as query when no argument */
+#define PragFlg_Result1 0x20 /* Acts as query when has one argument */
+#define PragFlg_SchemaOpt 0x40 /* Schema restricts name search if present */
+#define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */
+
+/* Names of columns for pragmas that return multi-column result
+** or that return single-column results where the name of the
+** result column is different from the name of the pragma
+*/
+static const char *const pragCName[] = {
+ /* 0 */ "id", /* Used by: foreign_key_list */
+ /* 1 */ "seq",
+ /* 2 */ "table",
+ /* 3 */ "from",
+ /* 4 */ "to",
+ /* 5 */ "on_update",
+ /* 6 */ "on_delete",
+ /* 7 */ "match",
+ /* 8 */ "cid", /* Used by: table_xinfo */
+ /* 9 */ "name",
+ /* 10 */ "type",
+ /* 11 */ "notnull",
+ /* 12 */ "dflt_value",
+ /* 13 */ "pk",
+ /* 14 */ "hidden",
+ /* table_info reuses 8 */
+ /* 15 */ "seqno", /* Used by: index_xinfo */
+ /* 16 */ "cid",
+ /* 17 */ "name",
+ /* 18 */ "desc",
+ /* 19 */ "coll",
+ /* 20 */ "key",
+ /* 21 */ "name", /* Used by: function_list */
+ /* 22 */ "builtin",
+ /* 23 */ "type",
+ /* 24 */ "enc",
+ /* 25 */ "narg",
+ /* 26 */ "flags",
+ /* 27 */ "tbl", /* Used by: stats */
+ /* 28 */ "idx",
+ /* 29 */ "wdth",
+ /* 30 */ "hght",
+ /* 31 */ "flgs",
+ /* 32 */ "seq", /* Used by: index_list */
+ /* 33 */ "name",
+ /* 34 */ "unique",
+ /* 35 */ "origin",
+ /* 36 */ "partial",
+ /* 37 */ "table", /* Used by: foreign_key_check */
+ /* 38 */ "rowid",
+ /* 39 */ "parent",
+ /* 40 */ "fkid",
+ /* index_info reuses 15 */
+ /* 41 */ "seq", /* Used by: database_list */
+ /* 42 */ "name",
+ /* 43 */ "file",
+ /* 44 */ "busy", /* Used by: wal_checkpoint */
+ /* 45 */ "log",
+ /* 46 */ "checkpointed",
+ /* collation_list reuses 32 */
+ /* 47 */ "database", /* Used by: lock_status */
+ /* 48 */ "status",
+ /* 49 */ "cache_size", /* Used by: default_cache_size */
+ /* module_list pragma_list reuses 9 */
+ /* 50 */ "timeout", /* Used by: busy_timeout */
+};
+
+/* Definitions of all built-in pragmas */
+typedef struct PragmaName {
+ const char *const zName; /* Name of pragma */
+ u8 ePragTyp; /* PragTyp_XXX value */
+ u8 mPragFlg; /* Zero or more PragFlg_XXX values */
+ u8 iPragCName; /* Start of column names in pragCName[] */
+ u8 nPragCName; /* Num of col names. 0 means use pragma name */
+ u64 iArg; /* Extra argument */
+} PragmaName;
+static const PragmaName aPragmaName[] = {
+#if defined(SQLITE_ENABLE_CEROD)
+ {/* zName: */ "activate_extensions",
+ /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
+ /* ePragFlg: */ 0,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+ {/* zName: */ "analysis_limit",
+ /* ePragTyp: */ PragTyp_ANALYSIS_LIMIT,
+ /* ePragFlg: */ PragFlg_Result0,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
+ {/* zName: */ "application_id",
+ /* ePragTyp: */ PragTyp_HEADER_VALUE,
+ /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ BTREE_APPLICATION_ID },
+#endif
+#if !defined(SQLITE_OMIT_AUTOVACUUM)
+ {/* zName: */ "auto_vacuum",
+ /* ePragTyp: */ PragTyp_AUTO_VACUUM,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
+ {/* zName: */ "automatic_index",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_AutoIndex },
+#endif
+#endif
+ {/* zName: */ "busy_timeout",
+ /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
+ /* ePragFlg: */ PragFlg_Result0,
+ /* ColNames: */ 50, 1,
+ /* iArg: */ 0 },
+#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
+ {/* zName: */ "cache_size",
+ /* ePragTyp: */ PragTyp_CACHE_SIZE,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+ {/* zName: */ "cache_spill",
+ /* ePragTyp: */ PragTyp_CACHE_SPILL,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA)
+ {/* zName: */ "case_sensitive_like",
+ /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
+ /* ePragFlg: */ PragFlg_NoColumns,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+ {/* zName: */ "cell_size_check",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_CellSizeCk },
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+ {/* zName: */ "checkpoint_fullfsync",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_CkptFullFSync },
+#endif
+#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
+ {/* zName: */ "collation_list",
+ /* ePragTyp: */ PragTyp_COLLATION_LIST,
+ /* ePragFlg: */ PragFlg_Result0,
+ /* ColNames: */ 32, 2,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
+ {/* zName: */ "compile_options",
+ /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
+ /* ePragFlg: */ PragFlg_Result0,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+ {/* zName: */ "count_changes",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_CountRows },
+#endif
+#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
+ {/* zName: */ "data_store_directory",
+ /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
+ /* ePragFlg: */ PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
+ {/* zName: */ "data_version",
+ /* ePragTyp: */ PragTyp_HEADER_VALUE,
+ /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ BTREE_DATA_VERSION },
+#endif
+#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
+ {/* zName: */ "database_list",
+ /* ePragTyp: */ PragTyp_DATABASE_LIST,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
+ /* ColNames: */ 41, 3,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
+ {/* zName: */ "default_cache_size",
+ /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
+ /* ColNames: */ 49, 1,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
+ {/* zName: */ "defer_foreign_keys",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_DeferFKs },
+#endif
+#endif
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+ {/* zName: */ "empty_result_callbacks",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_NullCallback },
+#endif
+#if !defined(SQLITE_OMIT_UTF16)
+ {/* zName: */ "encoding",
+ /* ePragTyp: */ PragTyp_ENCODING,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
+ {/* zName: */ "foreign_key_check",
+ /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1|PragFlg_SchemaOpt,
+ /* ColNames: */ 37, 4,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_FOREIGN_KEY)
+ {/* zName: */ "foreign_key_list",
+ /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
+ /* ColNames: */ 0, 8,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
+ {/* zName: */ "foreign_keys",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_ForeignKeys },
+#endif
+#endif
+#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
+ {/* zName: */ "freelist_count",
+ /* ePragTyp: */ PragTyp_HEADER_VALUE,
+ /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ BTREE_FREE_PAGE_COUNT },
+#endif
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+ {/* zName: */ "full_column_names",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_FullColNames },
+ {/* zName: */ "fullfsync",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_FullFSync },
+#endif
+#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
+#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
+ {/* zName: */ "function_list",
+ /* ePragTyp: */ PragTyp_FUNCTION_LIST,
+ /* ePragFlg: */ PragFlg_Result0,
+ /* ColNames: */ 21, 6,
+ /* iArg: */ 0 },
+#endif
+#endif
+ {/* zName: */ "hard_heap_limit",
+ /* ePragTyp: */ PragTyp_HARD_HEAP_LIMIT,
+ /* ePragFlg: */ PragFlg_Result0,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+#if !defined(SQLITE_OMIT_CHECK)
+ {/* zName: */ "ignore_check_constraints",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_IgnoreChecks },
+#endif
+#endif
+#if !defined(SQLITE_OMIT_AUTOVACUUM)
+ {/* zName: */ "incremental_vacuum",
+ /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_NoColumns,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
+ {/* zName: */ "index_info",
+ /* ePragTyp: */ PragTyp_INDEX_INFO,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
+ /* ColNames: */ 15, 3,
+ /* iArg: */ 0 },
+ {/* zName: */ "index_list",
+ /* ePragTyp: */ PragTyp_INDEX_LIST,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
+ /* ColNames: */ 32, 5,
+ /* iArg: */ 0 },
+ {/* zName: */ "index_xinfo",
+ /* ePragTyp: */ PragTyp_INDEX_INFO,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
+ /* ColNames: */ 15, 6,
+ /* iArg: */ 1 },
+#endif
+#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
+ {/* zName: */ "integrity_check",
+ /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
+ {/* zName: */ "journal_mode",
+ /* ePragTyp: */ PragTyp_JOURNAL_MODE,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+ {/* zName: */ "journal_size_limit",
+ /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+ {/* zName: */ "legacy_alter_table",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_LegacyAlter },
+#endif
+#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
+ {/* zName: */ "lock_proxy_file",
+ /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
+ /* ePragFlg: */ PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+ {/* zName: */ "lock_status",
+ /* ePragTyp: */ PragTyp_LOCK_STATUS,
+ /* ePragFlg: */ PragFlg_Result0,
+ /* ColNames: */ 47, 2,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
+ {/* zName: */ "locking_mode",
+ /* ePragTyp: */ PragTyp_LOCKING_MODE,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+ {/* zName: */ "max_page_count",
+ /* ePragTyp: */ PragTyp_PAGE_COUNT,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+ {/* zName: */ "mmap_size",
+ /* ePragTyp: */ PragTyp_MMAP_SIZE,
+ /* ePragFlg: */ 0,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
+#if !defined(SQLITE_OMIT_VIRTUALTABLE)
+#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
+ {/* zName: */ "module_list",
+ /* ePragTyp: */ PragTyp_MODULE_LIST,
+ /* ePragFlg: */ PragFlg_Result0,
+ /* ColNames: */ 9, 1,
+ /* iArg: */ 0 },
+#endif
+#endif
+#endif
+ {/* zName: */ "optimize",
+ /* ePragTyp: */ PragTyp_OPTIMIZE,
+ /* ePragFlg: */ PragFlg_Result1|PragFlg_NeedSchema,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
+ {/* zName: */ "page_count",
+ /* ePragTyp: */ PragTyp_PAGE_COUNT,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+ {/* zName: */ "page_size",
+ /* ePragTyp: */ PragTyp_PAGE_SIZE,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+#if defined(SQLITE_DEBUG)
+ {/* zName: */ "parser_trace",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_ParserTrace },
+#endif
+#endif
+#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
+ {/* zName: */ "pragma_list",
+ /* ePragTyp: */ PragTyp_PRAGMA_LIST,
+ /* ePragFlg: */ PragFlg_Result0,
+ /* ColNames: */ 9, 1,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+ {/* zName: */ "query_only",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_QueryOnly },
+#endif
+#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
+ {/* zName: */ "quick_check",
+ /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+ {/* zName: */ "read_uncommitted",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_ReadUncommit },
+ {/* zName: */ "recursive_triggers",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_RecTriggers },
+ {/* zName: */ "reverse_unordered_selects",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_ReverseOrder },
+#endif
+#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
+ {/* zName: */ "schema_version",
+ /* ePragTyp: */ PragTyp_HEADER_VALUE,
+ /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ BTREE_SCHEMA_VERSION },
+#endif
+#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
+ {/* zName: */ "secure_delete",
+ /* ePragTyp: */ PragTyp_SECURE_DELETE,
+ /* ePragFlg: */ PragFlg_Result0,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+ {/* zName: */ "short_column_names",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_ShortColNames },
+#endif
+ {/* zName: */ "shrink_memory",
+ /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
+ /* ePragFlg: */ PragFlg_NoColumns,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+ {/* zName: */ "soft_heap_limit",
+ /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
+ /* ePragFlg: */ PragFlg_Result0,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+#if defined(SQLITE_DEBUG)
+ {/* zName: */ "sql_trace",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_SqlTrace },
+#endif
+#endif
+#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
+ {/* zName: */ "stats",
+ /* ePragTyp: */ PragTyp_STATS,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
+ /* ColNames: */ 27, 5,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
+ {/* zName: */ "synchronous",
+ /* ePragTyp: */ PragTyp_SYNCHRONOUS,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
+ {/* zName: */ "table_info",
+ /* ePragTyp: */ PragTyp_TABLE_INFO,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
+ /* ColNames: */ 8, 6,
+ /* iArg: */ 0 },
+ {/* zName: */ "table_xinfo",
+ /* ePragTyp: */ PragTyp_TABLE_INFO,
+ /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
+ /* ColNames: */ 8, 7,
+ /* iArg: */ 1 },
+#endif
+#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
+ {/* zName: */ "temp_store",
+ /* ePragTyp: */ PragTyp_TEMP_STORE,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+ {/* zName: */ "temp_store_directory",
+ /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
+ /* ePragFlg: */ PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#endif
+ {/* zName: */ "threads",
+ /* ePragTyp: */ PragTyp_THREADS,
+ /* ePragFlg: */ PragFlg_Result0,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+ {/* zName: */ "trusted_schema",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_TrustedSchema },
+#endif
+#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
+ {/* zName: */ "user_version",
+ /* ePragTyp: */ PragTyp_HEADER_VALUE,
+ /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ BTREE_USER_VERSION },
+#endif
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+#if defined(SQLITE_DEBUG)
+ {/* zName: */ "vdbe_addoptrace",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_VdbeAddopTrace },
+ {/* zName: */ "vdbe_debug",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
+ {/* zName: */ "vdbe_eqp",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_VdbeEQP },
+ {/* zName: */ "vdbe_listing",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_VdbeListing },
+ {/* zName: */ "vdbe_trace",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_VdbeTrace },
+#endif
+#endif
+#if !defined(SQLITE_OMIT_WAL)
+ {/* zName: */ "wal_autocheckpoint",
+ /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
+ /* ePragFlg: */ 0,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ 0 },
+ {/* zName: */ "wal_checkpoint",
+ /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
+ /* ePragFlg: */ PragFlg_NeedSchema,
+ /* ColNames: */ 44, 3,
+ /* iArg: */ 0 },
+#endif
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+ {/* zName: */ "writable_schema",
+ /* ePragTyp: */ PragTyp_FLAG,
+ /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
+ /* ColNames: */ 0, 0,
+ /* iArg: */ SQLITE_WriteSchema|SQLITE_NoSchemaError },
+#endif
+};
+/* Number of pragmas: 67 on by default, 77 total. */
+
+/************** End of pragma.h **********************************************/
+/************** Continuing where we left off in pragma.c *********************/
+
+/*
+** Interpret the given string as a safety level. Return 0 for OFF,
+** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
+** unrecognized string argument. The FULL and EXTRA option is disallowed
+** if the omitFull parameter it 1.
+**
+** Note that the values returned are one less that the values that
+** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
+** to support legacy SQL code. The safety level used to be boolean
+** and older scripts may have used numbers 0 for OFF and 1 for ON.
+*/
+static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
+ /* 123456789 123456789 123 */
+ static const char zText[] = "onoffalseyestruextrafull";
+ static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
+ static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
+ static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
+ /* on no off false yes true extra full */
+ int i, n;
+ if( sqlite3Isdigit(*z) ){
+ return (u8)sqlite3Atoi(z);
+ }
+ n = sqlite3Strlen30(z);
+ for(i=0; i<ArraySize(iLength); i++){
+ if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
+ && (!omitFull || iValue[i]<=1)
+ ){
+ return iValue[i];
+ }
+ }
+ return dflt;
+}
+
+/*
+** Interpret the given string as a boolean value.
+*/
+SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
+ return getSafetyLevel(z,1,dflt)!=0;
+}
+
+/* The sqlite3GetBoolean() function is used by other modules but the
+** remainder of this file is specific to PRAGMA processing. So omit
+** the rest of the file if PRAGMAs are omitted from the build.
+*/
+#if !defined(SQLITE_OMIT_PRAGMA)
+
+/*
+** Interpret the given string as a locking mode value.
+*/
+static int getLockingMode(const char *z){
+ if( z ){
+ if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
+ if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
+ }
+ return PAGER_LOCKINGMODE_QUERY;
+}
+
+#ifndef SQLITE_OMIT_AUTOVACUUM
+/*
+** Interpret the given string as an auto-vacuum mode value.
+**
+** The following strings, "none", "full" and "incremental" are
+** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
+*/
+static int getAutoVacuum(const char *z){
+ int i;
+ if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
+ if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
+ if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
+ i = sqlite3Atoi(z);
+ return (u8)((i>=0&&i<=2)?i:0);
+}
+#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
+
+#ifndef SQLITE_OMIT_PAGER_PRAGMAS
+/*
+** Interpret the given string as a temp db location. Return 1 for file
+** backed temporary databases, 2 for the Red-Black tree in memory database
+** and 0 to use the compile-time default.
+*/
+static int getTempStore(const char *z){
+ if( z[0]>='0' && z[0]<='2' ){
+ return z[0] - '0';
+ }else if( sqlite3StrICmp(z, "file")==0 ){
+ return 1;
+ }else if( sqlite3StrICmp(z, "memory")==0 ){
+ return 2;
+ }else{
+ return 0;
+ }
+}
+#endif /* SQLITE_PAGER_PRAGMAS */
+
+#ifndef SQLITE_OMIT_PAGER_PRAGMAS
+/*
+** Invalidate temp storage, either when the temp storage is changed
+** from default, or when 'file' and the temp_store_directory has changed
+*/
+static int invalidateTempStorage(Parse *pParse){
+ sqlite3 *db = pParse->db;
+ if( db->aDb[1].pBt!=0 ){
+ if( !db->autoCommit
+ || sqlite3BtreeTxnState(db->aDb[1].pBt)!=SQLITE_TXN_NONE
+ ){
+ sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
+ "from within a transaction");
+ return SQLITE_ERROR;
+ }
+ sqlite3BtreeClose(db->aDb[1].pBt);
+ db->aDb[1].pBt = 0;
+ sqlite3ResetAllSchemasOfConnection(db);
+ }
+ return SQLITE_OK;
+}
+#endif /* SQLITE_PAGER_PRAGMAS */
+
+#ifndef SQLITE_OMIT_PAGER_PRAGMAS
+/*
+** If the TEMP database is open, close it and mark the database schema
+** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
+** or DEFAULT_TEMP_STORE pragmas.
+*/
+static int changeTempStorage(Parse *pParse, const char *zStorageType){
+ int ts = getTempStore(zStorageType);
+ sqlite3 *db = pParse->db;
+ if( db->temp_store==ts ) return SQLITE_OK;
+ if( invalidateTempStorage( pParse ) != SQLITE_OK ){
+ return SQLITE_ERROR;
+ }
+ db->temp_store = (u8)ts;
+ return SQLITE_OK;
+}
+#endif /* SQLITE_PAGER_PRAGMAS */
+
+/*
+** Set result column names for a pragma.
+*/
+static void setPragmaResultColumnNames(
+ Vdbe *v, /* The query under construction */
+ const PragmaName *pPragma /* The pragma */
+){
+ u8 n = pPragma->nPragCName;
+ sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
+ if( n==0 ){
+ sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
+ }else{
+ int i, j;
+ for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
+ sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
+ }
+ }
+}
+
+/*
+** Generate code to return a single integer value.
+*/
+static void returnSingleInt(Vdbe *v, i64 value){
+ sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
+ sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
+}
+
+/*
+** Generate code to return a single text value.
+*/
+static void returnSingleText(
+ Vdbe *v, /* Prepared statement under construction */
+ const char *zValue /* Value to be returned */
+){
+ if( zValue ){
+ sqlite3VdbeLoadString(v, 1, (const char*)zValue);
+ sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
+ }
+}
+
+
+/*
+** Set the safety_level and pager flags for pager iDb. Or if iDb<0
+** set these values for all pagers.
+*/
+#ifndef SQLITE_OMIT_PAGER_PRAGMAS
+static void setAllPagerFlags(sqlite3 *db){
+ if( db->autoCommit ){
+ Db *pDb = db->aDb;
+ int n = db->nDb;
+ assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
+ assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
+ assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
+ assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
+ == PAGER_FLAGS_MASK );
+ assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
+ while( (n--) > 0 ){
+ if( pDb->pBt ){
+ sqlite3BtreeSetPagerFlags(pDb->pBt,
+ pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
+ }
+ pDb++;
+ }
+ }
+}
+#else
+# define setAllPagerFlags(X) /* no-op */
+#endif
+
+
+/*
+** Return a human-readable name for a constraint resolution action.
+*/
+#ifndef SQLITE_OMIT_FOREIGN_KEY
+static const char *actionName(u8 action){
+ const char *zName;
+ switch( action ){
+ case OE_SetNull: zName = "SET NULL"; break;
+ case OE_SetDflt: zName = "SET DEFAULT"; break;
+ case OE_Cascade: zName = "CASCADE"; break;
+ case OE_Restrict: zName = "RESTRICT"; break;
+ default: zName = "NO ACTION";
+ assert( action==OE_None ); break;
+ }
+ return zName;
+}
+#endif
+
+
+/*
+** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
+** defined in pager.h. This function returns the associated lowercase
+** journal-mode name.
+*/
+SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
+ static char * const azModeName[] = {
+ "delete", "persist", "off", "truncate", "memory"
+#ifndef SQLITE_OMIT_WAL
+ , "wal"
+#endif
+ };
+ assert( PAGER_JOURNALMODE_DELETE==0 );
+ assert( PAGER_JOURNALMODE_PERSIST==1 );
+ assert( PAGER_JOURNALMODE_OFF==2 );
+ assert( PAGER_JOURNALMODE_TRUNCATE==3 );
+ assert( PAGER_JOURNALMODE_MEMORY==4 );
+ assert( PAGER_JOURNALMODE_WAL==5 );
+ assert( eMode>=0 && eMode<=ArraySize(azModeName) );
+
+ if( eMode==ArraySize(azModeName) ) return 0;
+ return azModeName[eMode];
+}
+
+/*
+** Locate a pragma in the aPragmaName[] array.
+*/
+static const PragmaName *pragmaLocate(const char *zName){
+ int upr, lwr, mid = 0, rc;
+ lwr = 0;
+ upr = ArraySize(aPragmaName)-1;
+ while( lwr<=upr ){
+ mid = (lwr+upr)/2;
+ rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
+ if( rc==0 ) break;
+ if( rc<0 ){
+ upr = mid - 1;
+ }else{
+ lwr = mid + 1;
+ }
+ }
+ return lwr>upr ? 0 : &aPragmaName[mid];
+}
+
+/*
+** Create zero or more entries in the output for the SQL functions
+** defined by FuncDef p.
+*/
+static void pragmaFunclistLine(
+ Vdbe *v, /* The prepared statement being created */
+ FuncDef *p, /* A particular function definition */
+ int isBuiltin, /* True if this is a built-in function */
+ int showInternFuncs /* True if showing internal functions */
+){
+ for(; p; p=p->pNext){
+ const char *zType;
+ static const u32 mask =
+ SQLITE_DETERMINISTIC |
+ SQLITE_DIRECTONLY |
+ SQLITE_SUBTYPE |
+ SQLITE_INNOCUOUS |
+ SQLITE_FUNC_INTERNAL
+ ;
+ static const char *azEnc[] = { 0, "utf8", "utf16le", "utf16be" };
+
+ assert( SQLITE_FUNC_ENCMASK==0x3 );
+ assert( strcmp(azEnc[SQLITE_UTF8],"utf8")==0 );
+ assert( strcmp(azEnc[SQLITE_UTF16LE],"utf16le")==0 );
+ assert( strcmp(azEnc[SQLITE_UTF16BE],"utf16be")==0 );
+
+ if( p->xSFunc==0 ) continue;
+ if( (p->funcFlags & SQLITE_FUNC_INTERNAL)!=0
+ && showInternFuncs==0
+ ){
+ continue;
+ }
+ if( p->xValue!=0 ){
+ zType = "w";
+ }else if( p->xFinalize!=0 ){
+ zType = "a";
+ }else{
+ zType = "s";
+ }
+ sqlite3VdbeMultiLoad(v, 1, "sissii",
+ p->zName, isBuiltin,
+ zType, azEnc[p->funcFlags&SQLITE_FUNC_ENCMASK],
+ p->nArg,
+ (p->funcFlags & mask) ^ SQLITE_INNOCUOUS
+ );
+ }
+}
+
+
+/*
+** Helper subroutine for PRAGMA integrity_check:
+**
+** Generate code to output a single-column result row with a value of the
+** string held in register 3. Decrement the result count in register 1
+** and halt if the maximum number of result rows have been issued.
+*/
+static int integrityCheckResultRow(Vdbe *v){
+ int addr;
+ sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
+ addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
+ VdbeCoverage(v);
+ sqlite3VdbeAddOp0(v, OP_Halt);
+ return addr;
+}
+
+/*
+** Process a pragma statement.
+**
+** Pragmas are of this form:
+**
+** PRAGMA [schema.]id [= value]
+**
+** The identifier might also be a string. The value is a string, and
+** identifier, or a number. If minusFlag is true, then the value is
+** a number that was preceded by a minus sign.
+**
+** If the left side is "database.id" then pId1 is the database name
+** and pId2 is the id. If the left side is just "id" then pId1 is the
+** id and pId2 is any empty string.
+*/
+SQLITE_PRIVATE void sqlite3Pragma(
+ Parse *pParse,
+ Token *pId1, /* First part of [schema.]id field */
+ Token *pId2, /* Second part of [schema.]id field, or NULL */
+ Token *pValue, /* Token for <value>, or NULL */
+ int minusFlag /* True if a '-' sign preceded <value> */
+){
+ char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
+ char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
+ const char *zDb = 0; /* The database name */
+ Token *pId; /* Pointer to <id> token */
+ char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
+ int iDb; /* Database index for <database> */
+ int rc; /* return value form SQLITE_FCNTL_PRAGMA */
+ sqlite3 *db = pParse->db; /* The database connection */
+ Db *pDb; /* The specific database being pragmaed */
+ Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
+ const PragmaName *pPragma; /* The pragma */
+
+ if( v==0 ) return;
+ sqlite3VdbeRunOnlyOnce(v);
+ pParse->nMem = 2;
+
+ /* Interpret the [schema.] part of the pragma statement. iDb is the
+ ** index of the database this pragma is being applied to in db.aDb[]. */
+ iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
+ if( iDb<0 ) return;
+ pDb = &db->aDb[iDb];
+
+ /* If the temp database has been explicitly named as part of the
+ ** pragma, make sure it is open.
+ */
+ if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
+ return;
+ }
+
+ zLeft = sqlite3NameFromToken(db, pId);
+ if( !zLeft ) return;
+ if( minusFlag ){
+ zRight = sqlite3MPrintf(db, "-%T", pValue);
+ }else{
+ zRight = sqlite3NameFromToken(db, pValue);
+ }
+
+ assert( pId2 );
+ zDb = pId2->n>0 ? pDb->zDbSName : 0;
+ if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
+ goto pragma_out;
+ }
+
+ /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
+ ** connection. If it returns SQLITE_OK, then assume that the VFS
+ ** handled the pragma and generate a no-op prepared statement.
+ **
+ ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
+ ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
+ ** object corresponding to the database file to which the pragma
+ ** statement refers.
+ **
+ ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
+ ** file control is an array of pointers to strings (char**) in which the
+ ** second element of the array is the name of the pragma and the third
+ ** element is the argument to the pragma or NULL if the pragma has no
+ ** argument.
+ */
+ aFcntl[0] = 0;
+ aFcntl[1] = zLeft;
+ aFcntl[2] = zRight;
+ aFcntl[3] = 0;
+ db->busyHandler.nBusy = 0;
+ rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
+ if( rc==SQLITE_OK ){
+ sqlite3VdbeSetNumCols(v, 1);
+ sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
+ returnSingleText(v, aFcntl[0]);
+ sqlite3_free(aFcntl[0]);
+ goto pragma_out;
+ }
+ if( rc!=SQLITE_NOTFOUND ){
+ if( aFcntl[0] ){
+ sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
+ sqlite3_free(aFcntl[0]);
+ }
+ pParse->nErr++;
+ pParse->rc = rc;
+ goto pragma_out;
+ }
+
+ /* Locate the pragma in the lookup table */
+ pPragma = pragmaLocate(zLeft);
+ if( pPragma==0 ) goto pragma_out;
+
+ /* Make sure the database schema is loaded if the pragma requires that */
+ if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
+ if( sqlite3ReadSchema(pParse) ) goto pragma_out;
+ }
+
+ /* Register the result column names for pragmas that return results */
+ if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
+ && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
+ ){
+ setPragmaResultColumnNames(v, pPragma);
+ }
+
+ /* Jump to the appropriate pragma handler */
+ switch( pPragma->ePragTyp ){
+
+#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
+ /*
+ ** PRAGMA [schema.]default_cache_size
+ ** PRAGMA [schema.]default_cache_size=N
+ **
+ ** The first form reports the current persistent setting for the
+ ** page cache size. The value returned is the maximum number of
+ ** pages in the page cache. The second form sets both the current
+ ** page cache size value and the persistent page cache size value
+ ** stored in the database file.
+ **
+ ** Older versions of SQLite would set the default cache size to a
+ ** negative number to indicate synchronous=OFF. These days, synchronous
+ ** is always on by default regardless of the sign of the default cache
+ ** size. But continue to take the absolute value of the default cache
+ ** size of historical compatibility.
+ */
+ case PragTyp_DEFAULT_CACHE_SIZE: {
+ static const int iLn = VDBE_OFFSET_LINENO(2);
+ static const VdbeOpList getCacheSize[] = {
+ { OP_Transaction, 0, 0, 0}, /* 0 */
+ { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
+ { OP_IfPos, 1, 8, 0},
+ { OP_Integer, 0, 2, 0},
+ { OP_Subtract, 1, 2, 1},
+ { OP_IfPos, 1, 8, 0},
+ { OP_Integer, 0, 1, 0}, /* 6 */
+ { OP_Noop, 0, 0, 0},
+ { OP_ResultRow, 1, 1, 0},
+ };
+ VdbeOp *aOp;
+ sqlite3VdbeUsesBtree(v, iDb);
+ if( !zRight ){
+ pParse->nMem += 2;
+ sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
+ aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
+ if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
+ aOp[0].p1 = iDb;
+ aOp[1].p1 = iDb;
+ aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
+ }else{
+ int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
+ sqlite3BeginWriteOperation(pParse, 0, iDb);
+ sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ pDb->pSchema->cache_size = size;
+ sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
+ }
+ break;
+ }
+#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
+
+#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
+ /*
+ ** PRAGMA [schema.]page_size
+ ** PRAGMA [schema.]page_size=N
+ **
+ ** The first form reports the current setting for the
+ ** database page size in bytes. The second form sets the
+ ** database page size value. The value can only be set if
+ ** the database has not yet been created.
+ */
+ case PragTyp_PAGE_SIZE: {
+ Btree *pBt = pDb->pBt;
+ assert( pBt!=0 );
+ if( !zRight ){
+ int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
+ returnSingleInt(v, size);
+ }else{
+ /* Malloc may fail when setting the page-size, as there is an internal
+ ** buffer that the pager module resizes using sqlite3_realloc().
+ */
+ db->nextPagesize = sqlite3Atoi(zRight);
+ if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,0,0) ){
+ sqlite3OomFault(db);
+ }
+ }
+ break;
+ }
+
+ /*
+ ** PRAGMA [schema.]secure_delete
+ ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
+ **
+ ** The first form reports the current setting for the
+ ** secure_delete flag. The second form changes the secure_delete
+ ** flag setting and reports the new value.
+ */
+ case PragTyp_SECURE_DELETE: {
+ Btree *pBt = pDb->pBt;
+ int b = -1;
+ assert( pBt!=0 );
+ if( zRight ){
+ if( sqlite3_stricmp(zRight, "fast")==0 ){
+ b = 2;
+ }else{
+ b = sqlite3GetBoolean(zRight, 0);
+ }
+ }
+ if( pId2->n==0 && b>=0 ){
+ int ii;
+ for(ii=0; ii<db->nDb; ii++){
+ sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
+ }
+ }
+ b = sqlite3BtreeSecureDelete(pBt, b);
+ returnSingleInt(v, b);
+ break;
+ }
+
+ /*
+ ** PRAGMA [schema.]max_page_count
+ ** PRAGMA [schema.]max_page_count=N
+ **
+ ** The first form reports the current setting for the
+ ** maximum number of pages in the database file. The
+ ** second form attempts to change this setting. Both
+ ** forms return the current setting.
+ **
+ ** The absolute value of N is used. This is undocumented and might
+ ** change. The only purpose is to provide an easy way to test
+ ** the sqlite3AbsInt32() function.
+ **
+ ** PRAGMA [schema.]page_count
+ **
+ ** Return the number of pages in the specified database.
+ */
+ case PragTyp_PAGE_COUNT: {
+ int iReg;
+ i64 x = 0;
+ sqlite3CodeVerifySchema(pParse, iDb);
+ iReg = ++pParse->nMem;
+ if( sqlite3Tolower(zLeft[0])=='p' ){
+ sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
+ }else{
+ if( zRight && sqlite3DecOrHexToI64(zRight,&x)==0 ){
+ if( x<0 ) x = 0;
+ else if( x>0xfffffffe ) x = 0xfffffffe;
+ }else{
+ x = 0;
+ }
+ sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, (int)x);
+ }
+ sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
+ break;
+ }
+
+ /*
+ ** PRAGMA [schema.]locking_mode
+ ** PRAGMA [schema.]locking_mode = (normal|exclusive)
+ */
+ case PragTyp_LOCKING_MODE: {
+ const char *zRet = "normal";
+ int eMode = getLockingMode(zRight);
+
+ if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
+ /* Simple "PRAGMA locking_mode;" statement. This is a query for
+ ** the current default locking mode (which may be different to
+ ** the locking-mode of the main database).
+ */
+ eMode = db->dfltLockMode;
+ }else{
+ Pager *pPager;
+ if( pId2->n==0 ){
+ /* This indicates that no database name was specified as part
+ ** of the PRAGMA command. In this case the locking-mode must be
+ ** set on all attached databases, as well as the main db file.
+ **
+ ** Also, the sqlite3.dfltLockMode variable is set so that
+ ** any subsequently attached databases also use the specified
+ ** locking mode.
+ */
+ int ii;
+ assert(pDb==&db->aDb[0]);
+ for(ii=2; ii<db->nDb; ii++){
+ pPager = sqlite3BtreePager(db->aDb[ii].pBt);
+ sqlite3PagerLockingMode(pPager, eMode);
+ }
+ db->dfltLockMode = (u8)eMode;
+ }
+ pPager = sqlite3BtreePager(pDb->pBt);
+ eMode = sqlite3PagerLockingMode(pPager, eMode);
+ }
+
+ assert( eMode==PAGER_LOCKINGMODE_NORMAL
+ || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
+ if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
+ zRet = "exclusive";
+ }
+ returnSingleText(v, zRet);
+ break;
+ }
+
+ /*
+ ** PRAGMA [schema.]journal_mode
+ ** PRAGMA [schema.]journal_mode =
+ ** (delete|persist|off|truncate|memory|wal|off)
+ */
+ case PragTyp_JOURNAL_MODE: {
+ int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
+ int ii; /* Loop counter */
+
+ if( zRight==0 ){
+ /* If there is no "=MODE" part of the pragma, do a query for the
+ ** current mode */
+ eMode = PAGER_JOURNALMODE_QUERY;
+ }else{
+ const char *zMode;
+ int n = sqlite3Strlen30(zRight);
+ for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
+ if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
+ }
+ if( !zMode ){
+ /* If the "=MODE" part does not match any known journal mode,
+ ** then do a query */
+ eMode = PAGER_JOURNALMODE_QUERY;
+ }
+ if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){
+ /* Do not allow journal-mode "OFF" in defensive since the database
+ ** can become corrupted using ordinary SQL when the journal is off */
+ eMode = PAGER_JOURNALMODE_QUERY;
+ }
+ }
+ if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
+ /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
+ iDb = 0;
+ pId2->n = 1;
+ }
+ for(ii=db->nDb-1; ii>=0; ii--){
+ if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
+ sqlite3VdbeUsesBtree(v, ii);
+ sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
+ }
+ }
+ sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
+ break;
+ }
+
+ /*
+ ** PRAGMA [schema.]journal_size_limit
+ ** PRAGMA [schema.]journal_size_limit=N
+ **
+ ** Get or set the size limit on rollback journal files.
+ */
+ case PragTyp_JOURNAL_SIZE_LIMIT: {
+ Pager *pPager = sqlite3BtreePager(pDb->pBt);
+ i64 iLimit = -2;
+ if( zRight ){
+ sqlite3DecOrHexToI64(zRight, &iLimit);
+ if( iLimit<-1 ) iLimit = -1;
+ }
+ iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
+ returnSingleInt(v, iLimit);
+ break;
+ }
+
+#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
+
+ /*
+ ** PRAGMA [schema.]auto_vacuum
+ ** PRAGMA [schema.]auto_vacuum=N
+ **
+ ** Get or set the value of the database 'auto-vacuum' parameter.
+ ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
+ */
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ case PragTyp_AUTO_VACUUM: {
+ Btree *pBt = pDb->pBt;
+ assert( pBt!=0 );
+ if( !zRight ){
+ returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
+ }else{
+ int eAuto = getAutoVacuum(zRight);
+ assert( eAuto>=0 && eAuto<=2 );
+ db->nextAutovac = (u8)eAuto;
+ /* Call SetAutoVacuum() to set initialize the internal auto and
+ ** incr-vacuum flags. This is required in case this connection
+ ** creates the database file. It is important that it is created
+ ** as an auto-vacuum capable db.
+ */
+ rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
+ if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
+ /* When setting the auto_vacuum mode to either "full" or
+ ** "incremental", write the value of meta[6] in the database
+ ** file. Before writing to meta[6], check that meta[3] indicates
+ ** that this really is an auto-vacuum capable database.
+ */
+ static const int iLn = VDBE_OFFSET_LINENO(2);
+ static const VdbeOpList setMeta6[] = {
+ { OP_Transaction, 0, 1, 0}, /* 0 */
+ { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
+ { OP_If, 1, 0, 0}, /* 2 */
+ { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
+ { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
+ };
+ VdbeOp *aOp;
+ int iAddr = sqlite3VdbeCurrentAddr(v);
+ sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
+ aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
+ if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
+ aOp[0].p1 = iDb;
+ aOp[1].p1 = iDb;
+ aOp[2].p2 = iAddr+4;
+ aOp[4].p1 = iDb;
+ aOp[4].p3 = eAuto - 1;
+ sqlite3VdbeUsesBtree(v, iDb);
+ }
+ }
+ break;
+ }
+#endif
+
+ /*
+ ** PRAGMA [schema.]incremental_vacuum(N)
+ **
+ ** Do N steps of incremental vacuuming on a database.
+ */
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ case PragTyp_INCREMENTAL_VACUUM: {
+ int iLimit, addr;
+ if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
+ iLimit = 0x7fffffff;
+ }
+ sqlite3BeginWriteOperation(pParse, 0, iDb);
+ sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
+ addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
+ sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
+ sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
+ sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
+ sqlite3VdbeJumpHere(v, addr);
+ break;
+ }
+#endif
+
+#ifndef SQLITE_OMIT_PAGER_PRAGMAS
+ /*
+ ** PRAGMA [schema.]cache_size
+ ** PRAGMA [schema.]cache_size=N
+ **
+ ** The first form reports the current local setting for the
+ ** page cache size. The second form sets the local
+ ** page cache size value. If N is positive then that is the
+ ** number of pages in the cache. If N is negative, then the
+ ** number of pages is adjusted so that the cache uses -N kibibytes
+ ** of memory.
+ */
+ case PragTyp_CACHE_SIZE: {
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ if( !zRight ){
+ returnSingleInt(v, pDb->pSchema->cache_size);
+ }else{
+ int size = sqlite3Atoi(zRight);
+ pDb->pSchema->cache_size = size;
+ sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
+ }
+ break;
+ }
+
+ /*
+ ** PRAGMA [schema.]cache_spill
+ ** PRAGMA cache_spill=BOOLEAN
+ ** PRAGMA [schema.]cache_spill=N
+ **
+ ** The first form reports the current local setting for the
+ ** page cache spill size. The second form turns cache spill on
+ ** or off. When turnning cache spill on, the size is set to the
+ ** current cache_size. The third form sets a spill size that
+ ** may be different form the cache size.
+ ** If N is positive then that is the
+ ** number of pages in the cache. If N is negative, then the
+ ** number of pages is adjusted so that the cache uses -N kibibytes
+ ** of memory.
+ **
+ ** If the number of cache_spill pages is less then the number of
+ ** cache_size pages, no spilling occurs until the page count exceeds
+ ** the number of cache_size pages.
+ **
+ ** The cache_spill=BOOLEAN setting applies to all attached schemas,
+ ** not just the schema specified.
+ */
+ case PragTyp_CACHE_SPILL: {
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ if( !zRight ){
+ returnSingleInt(v,
+ (db->flags & SQLITE_CacheSpill)==0 ? 0 :
+ sqlite3BtreeSetSpillSize(pDb->pBt,0));
+ }else{
+ int size = 1;
+ if( sqlite3GetInt32(zRight, &size) ){
+ sqlite3BtreeSetSpillSize(pDb->pBt, size);
+ }
+ if( sqlite3GetBoolean(zRight, size!=0) ){
+ db->flags |= SQLITE_CacheSpill;
+ }else{
+ db->flags &= ~(u64)SQLITE_CacheSpill;
+ }
+ setAllPagerFlags(db);
+ }
+ break;
+ }
+
+ /*
+ ** PRAGMA [schema.]mmap_size(N)
+ **
+ ** Used to set mapping size limit. The mapping size limit is
+ ** used to limit the aggregate size of all memory mapped regions of the
+ ** database file. If this parameter is set to zero, then memory mapping
+ ** is not used at all. If N is negative, then the default memory map
+ ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
+ ** The parameter N is measured in bytes.
+ **
+ ** This value is advisory. The underlying VFS is free to memory map
+ ** as little or as much as it wants. Except, if N is set to 0 then the
+ ** upper layers will never invoke the xFetch interfaces to the VFS.
+ */
+ case PragTyp_MMAP_SIZE: {
+ sqlite3_int64 sz;
+#if SQLITE_MAX_MMAP_SIZE>0
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ if( zRight ){
+ int ii;
+ sqlite3DecOrHexToI64(zRight, &sz);
+ if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
+ if( pId2->n==0 ) db->szMmap = sz;
+ for(ii=db->nDb-1; ii>=0; ii--){
+ if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
+ sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
+ }
+ }
+ }
+ sz = -1;
+ rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
+#else
+ sz = 0;
+ rc = SQLITE_OK;
+#endif
+ if( rc==SQLITE_OK ){
+ returnSingleInt(v, sz);
+ }else if( rc!=SQLITE_NOTFOUND ){
+ pParse->nErr++;
+ pParse->rc = rc;
+ }
+ break;
+ }
+
+ /*
+ ** PRAGMA temp_store
+ ** PRAGMA temp_store = "default"|"memory"|"file"
+ **
+ ** Return or set the local value of the temp_store flag. Changing
+ ** the local value does not make changes to the disk file and the default
+ ** value will be restored the next time the database is opened.
+ **
+ ** Note that it is possible for the library compile-time options to
+ ** override this setting
+ */
+ case PragTyp_TEMP_STORE: {
+ if( !zRight ){
+ returnSingleInt(v, db->temp_store);
+ }else{
+ changeTempStorage(pParse, zRight);
+ }
+ break;
+ }
+
+ /*
+ ** PRAGMA temp_store_directory
+ ** PRAGMA temp_store_directory = ""|"directory_name"
+ **
+ ** Return or set the local value of the temp_store_directory flag. Changing
+ ** the value sets a specific directory to be used for temporary files.
+ ** Setting to a null string reverts to the default temporary directory search.
+ ** If temporary directory is changed, then invalidateTempStorage.
+ **
+ */
+ case PragTyp_TEMP_STORE_DIRECTORY: {
+ if( !zRight ){
+ returnSingleText(v, sqlite3_temp_directory);
+ }else{
+#ifndef SQLITE_OMIT_WSD
+ if( zRight[0] ){
+ int res;
+ rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
+ if( rc!=SQLITE_OK || res==0 ){
+ sqlite3ErrorMsg(pParse, "not a writable directory");
+ goto pragma_out;
+ }
+ }
+ if( SQLITE_TEMP_STORE==0
+ || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
+ || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
+ ){
+ invalidateTempStorage(pParse);
+ }
+ sqlite3_free(sqlite3_temp_directory);
+ if( zRight[0] ){
+ sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
+ }else{
+ sqlite3_temp_directory = 0;
+ }
+#endif /* SQLITE_OMIT_WSD */
+ }
+ break;
+ }
+
+#if SQLITE_OS_WIN
+ /*
+ ** PRAGMA data_store_directory
+ ** PRAGMA data_store_directory = ""|"directory_name"
+ **
+ ** Return or set the local value of the data_store_directory flag. Changing
+ ** the value sets a specific directory to be used for database files that
+ ** were specified with a relative pathname. Setting to a null string reverts
+ ** to the default database directory, which for database files specified with
+ ** a relative path will probably be based on the current directory for the
+ ** process. Database file specified with an absolute path are not impacted
+ ** by this setting, regardless of its value.
+ **
+ */
+ case PragTyp_DATA_STORE_DIRECTORY: {
+ if( !zRight ){
+ returnSingleText(v, sqlite3_data_directory);
+ }else{
+#ifndef SQLITE_OMIT_WSD
+ if( zRight[0] ){
+ int res;
+ rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
+ if( rc!=SQLITE_OK || res==0 ){
+ sqlite3ErrorMsg(pParse, "not a writable directory");
+ goto pragma_out;
+ }
+ }
+ sqlite3_free(sqlite3_data_directory);
+ if( zRight[0] ){
+ sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
+ }else{
+ sqlite3_data_directory = 0;
+ }
+#endif /* SQLITE_OMIT_WSD */
+ }
+ break;
+ }
+#endif
+
+#if SQLITE_ENABLE_LOCKING_STYLE
+ /*
+ ** PRAGMA [schema.]lock_proxy_file
+ ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
+ **
+ ** Return or set the value of the lock_proxy_file flag. Changing
+ ** the value sets a specific file to be used for database access locks.
+ **
+ */
+ case PragTyp_LOCK_PROXY_FILE: {
+ if( !zRight ){
+ Pager *pPager = sqlite3BtreePager(pDb->pBt);
+ char *proxy_file_path = NULL;
+ sqlite3_file *pFile = sqlite3PagerFile(pPager);
+ sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
+ &proxy_file_path);
+ returnSingleText(v, proxy_file_path);
+ }else{
+ Pager *pPager = sqlite3BtreePager(pDb->pBt);
+ sqlite3_file *pFile = sqlite3PagerFile(pPager);
+ int res;
+ if( zRight[0] ){
+ res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
+ zRight);
+ } else {
+ res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
+ NULL);
+ }
+ if( res!=SQLITE_OK ){
+ sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
+ goto pragma_out;
+ }
+ }
+ break;
+ }
+#endif /* SQLITE_ENABLE_LOCKING_STYLE */
+
+ /*
+ ** PRAGMA [schema.]synchronous
+ ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
+ **
+ ** Return or set the local value of the synchronous flag. Changing
+ ** the local value does not make changes to the disk file and the
+ ** default value will be restored the next time the database is
+ ** opened.
+ */
+ case PragTyp_SYNCHRONOUS: {
+ if( !zRight ){
+ returnSingleInt(v, pDb->safety_level-1);
+ }else{
+ if( !db->autoCommit ){
+ sqlite3ErrorMsg(pParse,
+ "Safety level may not be changed inside a transaction");
+ }else if( iDb!=1 ){
+ int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
+ if( iLevel==0 ) iLevel = 1;
+ pDb->safety_level = iLevel;
+ pDb->bSyncSet = 1;
+ setAllPagerFlags(db);
+ }
+ }
+ break;
+ }
+#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
+
+#ifndef SQLITE_OMIT_FLAG_PRAGMAS
+ case PragTyp_FLAG: {
+ if( zRight==0 ){
+ setPragmaResultColumnNames(v, pPragma);
+ returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
+ }else{
+ u64 mask = pPragma->iArg; /* Mask of bits to set or clear. */
+ if( db->autoCommit==0 ){
+ /* Foreign key support may not be enabled or disabled while not
+ ** in auto-commit mode. */
+ mask &= ~(SQLITE_ForeignKeys);
+ }
+#if SQLITE_USER_AUTHENTICATION
+ if( db->auth.authLevel==UAUTH_User ){
+ /* Do not allow non-admin users to modify the schema arbitrarily */
+ mask &= ~(SQLITE_WriteSchema);
+ }
+#endif
+
+ if( sqlite3GetBoolean(zRight, 0) ){
+ db->flags |= mask;
+ }else{
+ db->flags &= ~mask;
+ if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
+ }
+
+ /* Many of the flag-pragmas modify the code generated by the SQL
+ ** compiler (eg. count_changes). So add an opcode to expire all
+ ** compiled SQL statements after modifying a pragma value.
+ */
+ sqlite3VdbeAddOp0(v, OP_Expire);
+ setAllPagerFlags(db);
+ }
+ break;
+ }
+#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
+
+#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
+ /*
+ ** PRAGMA table_info(<table>)
+ **
+ ** Return a single row for each column of the named table. The columns of
+ ** the returned data set are:
+ **
+ ** cid: Column id (numbered from left to right, starting at 0)
+ ** name: Column name
+ ** type: Column declaration type.
+ ** notnull: True if 'NOT NULL' is part of column declaration
+ ** dflt_value: The default value for the column, if any.
+ ** pk: Non-zero for PK fields.
+ */
+ case PragTyp_TABLE_INFO: if( zRight ){
+ Table *pTab;
+ sqlite3CodeVerifyNamedSchema(pParse, zDb);
+ pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
+ if( pTab ){
+ int i, k;
+ int nHidden = 0;
+ Column *pCol;
+ Index *pPk = sqlite3PrimaryKeyIndex(pTab);
+ pParse->nMem = 7;
+ sqlite3ViewGetColumnNames(pParse, pTab);
+ for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
+ int isHidden = 0;
+ if( pCol->colFlags & COLFLAG_NOINSERT ){
+ if( pPragma->iArg==0 ){
+ nHidden++;
+ continue;
+ }
+ if( pCol->colFlags & COLFLAG_VIRTUAL ){
+ isHidden = 2; /* GENERATED ALWAYS AS ... VIRTUAL */
+ }else if( pCol->colFlags & COLFLAG_STORED ){
+ isHidden = 3; /* GENERATED ALWAYS AS ... STORED */
+ }else{ assert( pCol->colFlags & COLFLAG_HIDDEN );
+ isHidden = 1; /* HIDDEN */
+ }
+ }
+ if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
+ k = 0;
+ }else if( pPk==0 ){
+ k = 1;
+ }else{
+ for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
+ }
+ assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN || isHidden>=2 );
+ sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
+ i-nHidden,
+ pCol->zName,
+ sqlite3ColumnType(pCol,""),
+ pCol->notNull ? 1 : 0,
+ pCol->pDflt && isHidden<2 ? pCol->pDflt->u.zToken : 0,
+ k,
+ isHidden);
+ }
+ }
+ }
+ break;
+
+#ifdef SQLITE_DEBUG
+ case PragTyp_STATS: {
+ Index *pIdx;
+ HashElem *i;
+ pParse->nMem = 5;
+ sqlite3CodeVerifySchema(pParse, iDb);
+ for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
+ Table *pTab = sqliteHashData(i);
+ sqlite3VdbeMultiLoad(v, 1, "ssiii",
+ pTab->zName,
+ 0,
+ pTab->szTabRow,
+ pTab->nRowLogEst,
+ pTab->tabFlags);
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+ sqlite3VdbeMultiLoad(v, 2, "siiiX",
+ pIdx->zName,
+ pIdx->szIdxRow,
+ pIdx->aiRowLogEst[0],
+ pIdx->hasStat1);
+ sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
+ }
+ }
+ }
+ break;
+#endif
+
+ case PragTyp_INDEX_INFO: if( zRight ){
+ Index *pIdx;
+ Table *pTab;
+ pIdx = sqlite3FindIndex(db, zRight, zDb);
+ if( pIdx==0 ){
+ /* If there is no index named zRight, check to see if there is a
+ ** WITHOUT ROWID table named zRight, and if there is, show the
+ ** structure of the PRIMARY KEY index for that table. */
+ pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
+ if( pTab && !HasRowid(pTab) ){
+ pIdx = sqlite3PrimaryKeyIndex(pTab);
+ }
+ }
+ if( pIdx ){
+ int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
+ int i;
+ int mx;
+ if( pPragma->iArg ){
+ /* PRAGMA index_xinfo (newer version with more rows and columns) */
+ mx = pIdx->nColumn;
+ pParse->nMem = 6;
+ }else{
+ /* PRAGMA index_info (legacy version) */
+ mx = pIdx->nKeyCol;
+ pParse->nMem = 3;
+ }
+ pTab = pIdx->pTable;
+ sqlite3CodeVerifySchema(pParse, iIdxDb);
+ assert( pParse->nMem<=pPragma->nPragCName );
+ for(i=0; i<mx; i++){
+ i16 cnum = pIdx->aiColumn[i];
+ sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
+ cnum<0 ? 0 : pTab->aCol[cnum].zName);
+ if( pPragma->iArg ){
+ sqlite3VdbeMultiLoad(v, 4, "isiX",
+ pIdx->aSortOrder[i],
+ pIdx->azColl[i],
+ i<pIdx->nKeyCol);
+ }
+ sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
+ }
+ }
+ }
+ break;
+
+ case PragTyp_INDEX_LIST: if( zRight ){
+ Index *pIdx;
+ Table *pTab;
+ int i;
+ pTab = sqlite3FindTable(db, zRight, zDb);
+ if( pTab ){
+ int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ pParse->nMem = 5;
+ sqlite3CodeVerifySchema(pParse, iTabDb);
+ for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
+ const char *azOrigin[] = { "c", "u", "pk" };
+ sqlite3VdbeMultiLoad(v, 1, "isisi",
+ i,
+ pIdx->zName,
+ IsUniqueIndex(pIdx),
+ azOrigin[pIdx->idxType],
+ pIdx->pPartIdxWhere!=0);
+ }
+ }
+ }
+ break;
+
+ case PragTyp_DATABASE_LIST: {
+ int i;
+ pParse->nMem = 3;
+ for(i=0; i<db->nDb; i++){
+ if( db->aDb[i].pBt==0 ) continue;
+ assert( db->aDb[i].zDbSName!=0 );
+ sqlite3VdbeMultiLoad(v, 1, "iss",
+ i,
+ db->aDb[i].zDbSName,
+ sqlite3BtreeGetFilename(db->aDb[i].pBt));
+ }
+ }
+ break;
+
+ case PragTyp_COLLATION_LIST: {
+ int i = 0;
+ HashElem *p;
+ pParse->nMem = 2;
+ for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
+ CollSeq *pColl = (CollSeq *)sqliteHashData(p);
+ sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
+ }
+ }
+ break;
+
+#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
+ case PragTyp_FUNCTION_LIST: {
+ int i;
+ HashElem *j;
+ FuncDef *p;
+ int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0;
+ pParse->nMem = 6;
+ for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
+ for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
+ pragmaFunclistLine(v, p, 1, showInternFunc);
+ }
+ }
+ for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
+ p = (FuncDef*)sqliteHashData(j);
+ pragmaFunclistLine(v, p, 0, showInternFunc);
+ }
+ }
+ break;
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ case PragTyp_MODULE_LIST: {
+ HashElem *j;
+ pParse->nMem = 1;
+ for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
+ Module *pMod = (Module*)sqliteHashData(j);
+ sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
+ }
+ }
+ break;
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+ case PragTyp_PRAGMA_LIST: {
+ int i;
+ for(i=0; i<ArraySize(aPragmaName); i++){
+ sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
+ }
+ }
+ break;
+#endif /* SQLITE_INTROSPECTION_PRAGMAS */
+
+#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
+
+#ifndef SQLITE_OMIT_FOREIGN_KEY
+ case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
+ FKey *pFK;
+ Table *pTab;
+ pTab = sqlite3FindTable(db, zRight, zDb);
+ if( pTab ){
+ pFK = pTab->pFKey;
+ if( pFK ){
+ int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ int i = 0;
+ pParse->nMem = 8;
+ sqlite3CodeVerifySchema(pParse, iTabDb);
+ while(pFK){
+ int j;
+ for(j=0; j<pFK->nCol; j++){
+ sqlite3VdbeMultiLoad(v, 1, "iissssss",
+ i,
+ j,
+ pFK->zTo,
+ pTab->aCol[pFK->aCol[j].iFrom].zName,
+ pFK->aCol[j].zCol,
+ actionName(pFK->aAction[1]), /* ON UPDATE */
+ actionName(pFK->aAction[0]), /* ON DELETE */
+ "NONE");
+ }
+ ++i;
+ pFK = pFK->pNextFrom;
+ }
+ }
+ }
+ }
+ break;
+#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
+
+#ifndef SQLITE_OMIT_FOREIGN_KEY
+#ifndef SQLITE_OMIT_TRIGGER
+ case PragTyp_FOREIGN_KEY_CHECK: {
+ FKey *pFK; /* A foreign key constraint */
+ Table *pTab; /* Child table contain "REFERENCES" keyword */
+ Table *pParent; /* Parent table that child points to */
+ Index *pIdx; /* Index in the parent table */
+ int i; /* Loop counter: Foreign key number for pTab */
+ int j; /* Loop counter: Field of the foreign key */
+ HashElem *k; /* Loop counter: Next table in schema */
+ int x; /* result variable */
+ int regResult; /* 3 registers to hold a result row */
+ int regKey; /* Register to hold key for checking the FK */
+ int regRow; /* Registers to hold a row from pTab */
+ int addrTop; /* Top of a loop checking foreign keys */
+ int addrOk; /* Jump here if the key is OK */
+ int *aiCols; /* child to parent column mapping */
+
+ regResult = pParse->nMem+1;
+ pParse->nMem += 4;
+ regKey = ++pParse->nMem;
+ regRow = ++pParse->nMem;
+ k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
+ while( k ){
+ if( zRight ){
+ pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
+ k = 0;
+ }else{
+ pTab = (Table*)sqliteHashData(k);
+ k = sqliteHashNext(k);
+ }
+ if( pTab==0 || pTab->pFKey==0 ) continue;
+ iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ zDb = db->aDb[iDb].zDbSName;
+ sqlite3CodeVerifySchema(pParse, iDb);
+ sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
+ if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
+ sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
+ sqlite3VdbeLoadString(v, regResult, pTab->zName);
+ for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
+ pParent = sqlite3FindTable(db, pFK->zTo, zDb);
+ if( pParent==0 ) continue;
+ pIdx = 0;
+ sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
+ x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
+ if( x==0 ){
+ if( pIdx==0 ){
+ sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
+ }else{
+ sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
+ sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
+ }
+ }else{
+ k = 0;
+ break;
+ }
+ }
+ assert( pParse->nErr>0 || pFK==0 );
+ if( pFK ) break;
+ if( pParse->nTab<i ) pParse->nTab = i;
+ addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
+ for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
+ pParent = sqlite3FindTable(db, pFK->zTo, zDb);
+ pIdx = 0;
+ aiCols = 0;
+ if( pParent ){
+ x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
+ assert( x==0 || db->mallocFailed );
+ }
+ addrOk = sqlite3VdbeMakeLabel(pParse);
+
+ /* Generate code to read the child key values into registers
+ ** regRow..regRow+n. If any of the child key values are NULL, this
+ ** row cannot cause an FK violation. Jump directly to addrOk in
+ ** this case. */
+ for(j=0; j<pFK->nCol; j++){
+ int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
+ sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
+ sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
+ }
+
+ /* Generate code to query the parent index for a matching parent
+ ** key. If a match is found, jump to addrOk. */
+ if( pIdx ){
+ sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
+ sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
+ sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
+ VdbeCoverage(v);
+ }else if( pParent ){
+ int jmp = sqlite3VdbeCurrentAddr(v)+2;
+ sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
+ sqlite3VdbeGoto(v, addrOk);
+ assert( pFK->nCol==1 || db->mallocFailed );
+ }
+
+ /* Generate code to report an FK violation to the caller. */
+ if( HasRowid(pTab) ){
+ sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
+ }
+ sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
+ sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
+ sqlite3VdbeResolveLabel(v, addrOk);
+ sqlite3DbFree(db, aiCols);
+ }
+ sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
+ sqlite3VdbeJumpHere(v, addrTop);
+ }
+ }
+ break;
+#endif /* !defined(SQLITE_OMIT_TRIGGER) */
+#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
+
+#ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA
+ /* Reinstall the LIKE and GLOB functions. The variant of LIKE
+ ** used will be case sensitive or not depending on the RHS.
+ */
+ case PragTyp_CASE_SENSITIVE_LIKE: {
+ if( zRight ){
+ sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
+ }
+ }
+ break;
+#endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */
+
+#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
+# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
+#endif
+
+#ifndef SQLITE_OMIT_INTEGRITY_CHECK
+ /* PRAGMA integrity_check
+ ** PRAGMA integrity_check(N)
+ ** PRAGMA quick_check
+ ** PRAGMA quick_check(N)
+ **
+ ** Verify the integrity of the database.
+ **
+ ** The "quick_check" is reduced version of
+ ** integrity_check designed to detect most database corruption
+ ** without the overhead of cross-checking indexes. Quick_check
+ ** is linear time wherease integrity_check is O(NlogN).
+ **
+ ** The maximum nubmer of errors is 100 by default. A different default
+ ** can be specified using a numeric parameter N.
+ **
+ ** Or, the parameter N can be the name of a table. In that case, only
+ ** the one table named is verified. The freelist is only verified if
+ ** the named table is "sqlite_schema" (or one of its aliases).
+ **
+ ** All schemas are checked by default. To check just a single
+ ** schema, use the form:
+ **
+ ** PRAGMA schema.integrity_check;
+ */
+ case PragTyp_INTEGRITY_CHECK: {
+ int i, j, addr, mxErr;
+ Table *pObjTab = 0; /* Check only this one table, if not NULL */
+
+ int isQuick = (sqlite3Tolower(zLeft[0])=='q');
+
+ /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
+ ** then iDb is set to the index of the database identified by <db>.
+ ** In this case, the integrity of database iDb only is verified by
+ ** the VDBE created below.
+ **
+ ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
+ ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
+ ** to -1 here, to indicate that the VDBE should verify the integrity
+ ** of all attached databases. */
+ assert( iDb>=0 );
+ assert( iDb==0 || pId2->z );
+ if( pId2->z==0 ) iDb = -1;
+
+ /* Initialize the VDBE program */
+ pParse->nMem = 6;
+
+ /* Set the maximum error count */
+ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
+ if( zRight ){
+ if( sqlite3GetInt32(zRight, &mxErr) ){
+ if( mxErr<=0 ){
+ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
+ }
+ }else{
+ pObjTab = sqlite3LocateTable(pParse, 0, zRight,
+ iDb>=0 ? db->aDb[iDb].zDbSName : 0);
+ }
+ }
+ sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
+
+ /* Do an integrity check on each database file */
+ for(i=0; i<db->nDb; i++){
+ HashElem *x; /* For looping over tables in the schema */
+ Hash *pTbls; /* Set of all tables in the schema */
+ int *aRoot; /* Array of root page numbers of all btrees */
+ int cnt = 0; /* Number of entries in aRoot[] */
+ int mxIdx = 0; /* Maximum number of indexes for any table */
+
+ if( OMIT_TEMPDB && i==1 ) continue;
+ if( iDb>=0 && i!=iDb ) continue;
+
+ sqlite3CodeVerifySchema(pParse, i);
+
+ /* Do an integrity check of the B-Tree
+ **
+ ** Begin by finding the root pages numbers
+ ** for all tables and indices in the database.
+ */
+ assert( sqlite3SchemaMutexHeld(db, i, 0) );
+ pTbls = &db->aDb[i].pSchema->tblHash;
+ for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
+ Table *pTab = sqliteHashData(x); /* Current table */
+ Index *pIdx; /* An index on pTab */
+ int nIdx; /* Number of indexes on pTab */
+ if( pObjTab && pObjTab!=pTab ) continue;
+ if( HasRowid(pTab) ) cnt++;
+ for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
+ if( nIdx>mxIdx ) mxIdx = nIdx;
+ }
+ if( cnt==0 ) continue;
+ if( pObjTab ) cnt++;
+ aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
+ if( aRoot==0 ) break;
+ cnt = 0;
+ if( pObjTab ) aRoot[++cnt] = 0;
+ for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
+ Table *pTab = sqliteHashData(x);
+ Index *pIdx;
+ if( pObjTab && pObjTab!=pTab ) continue;
+ if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+ aRoot[++cnt] = pIdx->tnum;
+ }
+ }
+ aRoot[0] = cnt;
+
+ /* Make sure sufficient number of registers have been allocated */
+ pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
+ sqlite3ClearTempRegCache(pParse);
+
+ /* Do the b-tree integrity checks */
+ sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
+ sqlite3VdbeChangeP5(v, (u8)i);
+ addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
+ sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
+ sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
+ P4_DYNAMIC);
+ sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
+ integrityCheckResultRow(v);
+ sqlite3VdbeJumpHere(v, addr);
+
+ /* Make sure all the indices are constructed correctly.
+ */
+ for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
+ Table *pTab = sqliteHashData(x);
+ Index *pIdx, *pPk;
+ Index *pPrior = 0;
+ int loopTop;
+ int iDataCur, iIdxCur;
+ int r1 = -1;
+
+ if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */
+ if( pObjTab && pObjTab!=pTab ) continue;
+ pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
+ sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
+ 1, 0, &iDataCur, &iIdxCur);
+ /* reg[7] counts the number of entries in the table.
+ ** reg[8+i] counts the number of entries in the i-th index
+ */
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
+ for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
+ }
+ assert( pParse->nMem>=8+j );
+ assert( sqlite3NoTempsInRange(pParse,1,7+j) );
+ sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
+ loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
+ if( !isQuick ){
+ /* Sanity check on record header decoding */
+ sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nNVCol-1,3);
+ sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
+ }
+ /* Verify that all NOT NULL columns really are NOT NULL */
+ for(j=0; j<pTab->nCol; j++){
+ char *zErr;
+ int jmp2;
+ if( j==pTab->iPKey ) continue;
+ if( pTab->aCol[j].notNull==0 ) continue;
+ sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
+ if( sqlite3VdbeGetOp(v,-1)->opcode==OP_Column ){
+ sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
+ }
+ jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
+ zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
+ pTab->aCol[j].zName);
+ sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
+ integrityCheckResultRow(v);
+ sqlite3VdbeJumpHere(v, jmp2);
+ }
+ /* Verify CHECK constraints */
+ if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
+ ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
+ if( db->mallocFailed==0 ){
+ int addrCkFault = sqlite3VdbeMakeLabel(pParse);
+ int addrCkOk = sqlite3VdbeMakeLabel(pParse);
+ char *zErr;
+ int k;
+ pParse->iSelfTab = iDataCur + 1;
+ for(k=pCheck->nExpr-1; k>0; k--){
+ sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
+ }
+ sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
+ SQLITE_JUMPIFNULL);
+ sqlite3VdbeResolveLabel(v, addrCkFault);
+ pParse->iSelfTab = 0;
+ zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
+ pTab->zName);
+ sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
+ integrityCheckResultRow(v);
+ sqlite3VdbeResolveLabel(v, addrCkOk);
+ }
+ sqlite3ExprListDelete(db, pCheck);
+ }
+ if( !isQuick ){ /* Omit the remaining tests for quick_check */
+ /* Validate index entries for the current row */
+ for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
+ int jmp2, jmp3, jmp4, jmp5;
+ int ckUniq = sqlite3VdbeMakeLabel(pParse);
+ if( pPk==pIdx ) continue;
+ r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
+ pPrior, r1);
+ pPrior = pIdx;
+ sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
+ /* Verify that an index entry exists for the current table row */
+ jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
+ pIdx->nColumn); VdbeCoverage(v);
+ sqlite3VdbeLoadString(v, 3, "row ");
+ sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
+ sqlite3VdbeLoadString(v, 4, " missing from index ");
+ sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
+ jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
+ sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
+ jmp4 = integrityCheckResultRow(v);
+ sqlite3VdbeJumpHere(v, jmp2);
+ /* For UNIQUE indexes, verify that only one entry exists with the
+ ** current key. The entry is unique if (1) any column is NULL
+ ** or (2) the next entry has a different key */
+ if( IsUniqueIndex(pIdx) ){
+ int uniqOk = sqlite3VdbeMakeLabel(pParse);
+ int jmp6;
+ int kk;
+ for(kk=0; kk<pIdx->nKeyCol; kk++){
+ int iCol = pIdx->aiColumn[kk];
+ assert( iCol!=XN_ROWID && iCol<pTab->nCol );
+ if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
+ sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
+ VdbeCoverage(v);
+ }
+ jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
+ sqlite3VdbeGoto(v, uniqOk);
+ sqlite3VdbeJumpHere(v, jmp6);
+ sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
+ pIdx->nKeyCol); VdbeCoverage(v);
+ sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
+ sqlite3VdbeGoto(v, jmp5);
+ sqlite3VdbeResolveLabel(v, uniqOk);
+ }
+ sqlite3VdbeJumpHere(v, jmp4);
+ sqlite3ResolvePartIdxLabel(pParse, jmp3);
+ }
+ }
+ sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
+ sqlite3VdbeJumpHere(v, loopTop-1);
+ if( !isQuick ){
+ sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
+ for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
+ if( pPk==pIdx ) continue;
+ sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
+ addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
+ sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
+ sqlite3VdbeLoadString(v, 4, pIdx->zName);
+ sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
+ integrityCheckResultRow(v);
+ sqlite3VdbeJumpHere(v, addr);
+ }
+ }
+ }
+ }
+ {
+ static const int iLn = VDBE_OFFSET_LINENO(2);
+ static const VdbeOpList endCode[] = {
+ { OP_AddImm, 1, 0, 0}, /* 0 */
+ { OP_IfNotZero, 1, 4, 0}, /* 1 */
+ { OP_String8, 0, 3, 0}, /* 2 */
+ { OP_ResultRow, 3, 1, 0}, /* 3 */
+ { OP_Halt, 0, 0, 0}, /* 4 */
+ { OP_String8, 0, 3, 0}, /* 5 */
+ { OP_Goto, 0, 3, 0}, /* 6 */
+ };
+ VdbeOp *aOp;
+
+ aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
+ if( aOp ){
+ aOp[0].p2 = 1-mxErr;
+ aOp[2].p4type = P4_STATIC;
+ aOp[2].p4.z = "ok";
+ aOp[5].p4type = P4_STATIC;
+ aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
+ }
+ sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
+ }
+ }
+ break;
+#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
+
+#ifndef SQLITE_OMIT_UTF16
+ /*
+ ** PRAGMA encoding
+ ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
+ **
+ ** In its first form, this pragma returns the encoding of the main
+ ** database. If the database is not initialized, it is initialized now.
+ **
+ ** The second form of this pragma is a no-op if the main database file
+ ** has not already been initialized. In this case it sets the default
+ ** encoding that will be used for the main database file if a new file
+ ** is created. If an existing main database file is opened, then the
+ ** default text encoding for the existing database is used.
+ **
+ ** In all cases new databases created using the ATTACH command are
+ ** created to use the same default text encoding as the main database. If
+ ** the main database has not been initialized and/or created when ATTACH
+ ** is executed, this is done before the ATTACH operation.
+ **
+ ** In the second form this pragma sets the text encoding to be used in
+ ** new database files created using this database handle. It is only
+ ** useful if invoked immediately after the main database i
+ */
+ case PragTyp_ENCODING: {
+ static const struct EncName {
+ char *zName;
+ u8 enc;
+ } encnames[] = {
+ { "UTF8", SQLITE_UTF8 },
+ { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
+ { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
+ { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
+ { "UTF16le", SQLITE_UTF16LE },
+ { "UTF16be", SQLITE_UTF16BE },
+ { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
+ { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
+ { 0, 0 }
+ };
+ const struct EncName *pEnc;
+ if( !zRight ){ /* "PRAGMA encoding" */
+ if( sqlite3ReadSchema(pParse) ) goto pragma_out;
+ assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
+ assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
+ assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
+ returnSingleText(v, encnames[ENC(pParse->db)].zName);
+ }else{ /* "PRAGMA encoding = XXX" */
+ /* Only change the value of sqlite.enc if the database handle is not
+ ** initialized. If the main database exists, the new sqlite.enc value
+ ** will be overwritten when the schema is next loaded. If it does not
+ ** already exists, it will be created to use the new encoding value.
+ */
+ if( (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
+ for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
+ if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
+ u8 enc = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
+ SCHEMA_ENC(db) = enc;
+ sqlite3SetTextEncoding(db, enc);
+ break;
+ }
+ }
+ if( !pEnc->zName ){
+ sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
+ }
+ }
+ }
+ }
+ break;
+#endif /* SQLITE_OMIT_UTF16 */
+
+#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
+ /*
+ ** PRAGMA [schema.]schema_version
+ ** PRAGMA [schema.]schema_version = <integer>
+ **
+ ** PRAGMA [schema.]user_version
+ ** PRAGMA [schema.]user_version = <integer>
+ **
+ ** PRAGMA [schema.]freelist_count
+ **
+ ** PRAGMA [schema.]data_version
+ **
+ ** PRAGMA [schema.]application_id
+ ** PRAGMA [schema.]application_id = <integer>
+ **
+ ** The pragma's schema_version and user_version are used to set or get
+ ** the value of the schema-version and user-version, respectively. Both
+ ** the schema-version and the user-version are 32-bit signed integers
+ ** stored in the database header.
+ **
+ ** The schema-cookie is usually only manipulated internally by SQLite. It
+ ** is incremented by SQLite whenever the database schema is modified (by
+ ** creating or dropping a table or index). The schema version is used by
+ ** SQLite each time a query is executed to ensure that the internal cache
+ ** of the schema used when compiling the SQL query matches the schema of
+ ** the database against which the compiled query is actually executed.
+ ** Subverting this mechanism by using "PRAGMA schema_version" to modify
+ ** the schema-version is potentially dangerous and may lead to program
+ ** crashes or database corruption. Use with caution!
+ **
+ ** The user-version is not used internally by SQLite. It may be used by
+ ** applications for any purpose.
+ */
+ case PragTyp_HEADER_VALUE: {
+ int iCookie = pPragma->iArg; /* Which cookie to read or write */
+ sqlite3VdbeUsesBtree(v, iDb);
+ if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
+ /* Write the specified cookie value */
+ static const VdbeOpList setCookie[] = {
+ { OP_Transaction, 0, 1, 0}, /* 0 */
+ { OP_SetCookie, 0, 0, 0}, /* 1 */
+ };
+ VdbeOp *aOp;
+ sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
+ aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
+ if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
+ aOp[0].p1 = iDb;
+ aOp[1].p1 = iDb;
+ aOp[1].p2 = iCookie;
+ aOp[1].p3 = sqlite3Atoi(zRight);
+ aOp[1].p5 = 1;
+ }else{
+ /* Read the specified cookie value */
+ static const VdbeOpList readCookie[] = {
+ { OP_Transaction, 0, 0, 0}, /* 0 */
+ { OP_ReadCookie, 0, 1, 0}, /* 1 */
+ { OP_ResultRow, 1, 1, 0}
+ };
+ VdbeOp *aOp;
+ sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
+ aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
+ if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
+ aOp[0].p1 = iDb;
+ aOp[1].p1 = iDb;
+ aOp[1].p3 = iCookie;
+ sqlite3VdbeReusable(v);
+ }
+ }
+ break;
+#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
+
+#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
+ /*
+ ** PRAGMA compile_options
+ **
+ ** Return the names of all compile-time options used in this build,
+ ** one option per row.
+ */
+ case PragTyp_COMPILE_OPTIONS: {
+ int i = 0;
+ const char *zOpt;
+ pParse->nMem = 1;
+ while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
+ sqlite3VdbeLoadString(v, 1, zOpt);
+ sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
+ }
+ sqlite3VdbeReusable(v);
+ }
+ break;
+#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
+
+#ifndef SQLITE_OMIT_WAL
+ /*
+ ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
+ **
+ ** Checkpoint the database.
+ */
+ case PragTyp_WAL_CHECKPOINT: {
+ int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
+ int eMode = SQLITE_CHECKPOINT_PASSIVE;
+ if( zRight ){
+ if( sqlite3StrICmp(zRight, "full")==0 ){
+ eMode = SQLITE_CHECKPOINT_FULL;
+ }else if( sqlite3StrICmp(zRight, "restart")==0 ){
+ eMode = SQLITE_CHECKPOINT_RESTART;
+ }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
+ eMode = SQLITE_CHECKPOINT_TRUNCATE;
+ }
+ }
+ pParse->nMem = 3;
+ sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
+ sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
+ }
+ break;
+
+ /*
+ ** PRAGMA wal_autocheckpoint
+ ** PRAGMA wal_autocheckpoint = N
+ **
+ ** Configure a database connection to automatically checkpoint a database
+ ** after accumulating N frames in the log. Or query for the current value
+ ** of N.
+ */
+ case PragTyp_WAL_AUTOCHECKPOINT: {
+ if( zRight ){
+ sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
+ }
+ returnSingleInt(v,
+ db->xWalCallback==sqlite3WalDefaultHook ?
+ SQLITE_PTR_TO_INT(db->pWalArg) : 0);
+ }
+ break;
+#endif
+
+ /*
+ ** PRAGMA shrink_memory
+ **
+ ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
+ ** connection on which it is invoked to free up as much memory as it
+ ** can, by calling sqlite3_db_release_memory().
+ */
+ case PragTyp_SHRINK_MEMORY: {
+ sqlite3_db_release_memory(db);
+ break;
+ }
+
+ /*
+ ** PRAGMA optimize
+ ** PRAGMA optimize(MASK)
+ ** PRAGMA schema.optimize
+ ** PRAGMA schema.optimize(MASK)
+ **
+ ** Attempt to optimize the database. All schemas are optimized in the first
+ ** two forms, and only the specified schema is optimized in the latter two.
+ **
+ ** The details of optimizations performed by this pragma are expected
+ ** to change and improve over time. Applications should anticipate that
+ ** this pragma will perform new optimizations in future releases.
+ **
+ ** The optional argument is a bitmask of optimizations to perform:
+ **
+ ** 0x0001 Debugging mode. Do not actually perform any optimizations
+ ** but instead return one line of text for each optimization
+ ** that would have been done. Off by default.
+ **
+ ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
+ ** See below for additional information.
+ **
+ ** 0x0004 (Not yet implemented) Record usage and performance
+ ** information from the current session in the
+ ** database file so that it will be available to "optimize"
+ ** pragmas run by future database connections.
+ **
+ ** 0x0008 (Not yet implemented) Create indexes that might have
+ ** been helpful to recent queries
+ **
+ ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all
+ ** of the optimizations listed above except Debug Mode, including new
+ ** optimizations that have not yet been invented. If new optimizations are
+ ** ever added that should be off by default, those off-by-default
+ ** optimizations will have bitmasks of 0x10000 or larger.
+ **
+ ** DETERMINATION OF WHEN TO RUN ANALYZE
+ **
+ ** In the current implementation, a table is analyzed if only if all of
+ ** the following are true:
+ **
+ ** (1) MASK bit 0x02 is set.
+ **
+ ** (2) The query planner used sqlite_stat1-style statistics for one or
+ ** more indexes of the table at some point during the lifetime of
+ ** the current connection.
+ **
+ ** (3) One or more indexes of the table are currently unanalyzed OR
+ ** the number of rows in the table has increased by 25 times or more
+ ** since the last time ANALYZE was run.
+ **
+ ** The rules for when tables are analyzed are likely to change in
+ ** future releases.
+ */
+ case PragTyp_OPTIMIZE: {
+ int iDbLast; /* Loop termination point for the schema loop */
+ int iTabCur; /* Cursor for a table whose size needs checking */
+ HashElem *k; /* Loop over tables of a schema */
+ Schema *pSchema; /* The current schema */
+ Table *pTab; /* A table in the schema */
+ Index *pIdx; /* An index of the table */
+ LogEst szThreshold; /* Size threshold above which reanalysis is needd */
+ char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
+ u32 opMask; /* Mask of operations to perform */
+
+ if( zRight ){
+ opMask = (u32)sqlite3Atoi(zRight);
+ if( (opMask & 0x02)==0 ) break;
+ }else{
+ opMask = 0xfffe;
+ }
+ iTabCur = pParse->nTab++;
+ for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
+ if( iDb==1 ) continue;
+ sqlite3CodeVerifySchema(pParse, iDb);
+ pSchema = db->aDb[iDb].pSchema;
+ for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
+ pTab = (Table*)sqliteHashData(k);
+
+ /* If table pTab has not been used in a way that would benefit from
+ ** having analysis statistics during the current session, then skip it.
+ ** This also has the effect of skipping virtual tables and views */
+ if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
+
+ /* Reanalyze if the table is 25 times larger than the last analysis */
+ szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+ if( !pIdx->hasStat1 ){
+ szThreshold = 0; /* Always analyze if any index lacks statistics */
+ break;
+ }
+ }
+ if( szThreshold ){
+ sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
+ sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
+ sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
+ VdbeCoverage(v);
+ }
+ zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
+ db->aDb[iDb].zDbSName, pTab->zName);
+ if( opMask & 0x01 ){
+ int r1 = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
+ sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
+ }else{
+ sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
+ }
+ }
+ }
+ sqlite3VdbeAddOp0(v, OP_Expire);
+ break;
+ }
+
+ /*
+ ** PRAGMA busy_timeout
+ ** PRAGMA busy_timeout = N
+ **
+ ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
+ ** if one is set. If no busy handler or a different busy handler is set
+ ** then 0 is returned. Setting the busy_timeout to 0 or negative
+ ** disables the timeout.
+ */
+ /*case PragTyp_BUSY_TIMEOUT*/ default: {
+ assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
+ if( zRight ){
+ sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
+ }
+ returnSingleInt(v, db->busyTimeout);
+ break;
+ }
+
+ /*
+ ** PRAGMA soft_heap_limit
+ ** PRAGMA soft_heap_limit = N
+ **
+ ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
+ ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
+ ** specified and is a non-negative integer.
+ ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
+ ** returns the same integer that would be returned by the
+ ** sqlite3_soft_heap_limit64(-1) C-language function.
+ */
+ case PragTyp_SOFT_HEAP_LIMIT: {
+ sqlite3_int64 N;
+ if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
+ sqlite3_soft_heap_limit64(N);
+ }
+ returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
+ break;
+ }
+
+ /*
+ ** PRAGMA hard_heap_limit
+ ** PRAGMA hard_heap_limit = N
+ **
+ ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap
+ ** limit. The hard heap limit can be activated or lowered by this
+ ** pragma, but not raised or deactivated. Only the
+ ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
+ ** the hard heap limit. This allows an application to set a heap limit
+ ** constraint that cannot be relaxed by an untrusted SQL script.
+ */
+ case PragTyp_HARD_HEAP_LIMIT: {
+ sqlite3_int64 N;
+ if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
+ sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1);
+ if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N);
+ }
+ returnSingleInt(v, sqlite3_hard_heap_limit64(-1));
+ break;
+ }
+
+ /*
+ ** PRAGMA threads
+ ** PRAGMA threads = N
+ **
+ ** Configure the maximum number of worker threads. Return the new
+ ** maximum, which might be less than requested.
+ */
+ case PragTyp_THREADS: {
+ sqlite3_int64 N;
+ if( zRight
+ && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
+ && N>=0
+ ){
+ sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
+ }
+ returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
+ break;
+ }
+
+ /*
+ ** PRAGMA analysis_limit
+ ** PRAGMA analysis_limit = N
+ **
+ ** Configure the maximum number of rows that ANALYZE will examine
+ ** in each index that it looks at. Return the new limit.
+ */
+ case PragTyp_ANALYSIS_LIMIT: {
+ sqlite3_int64 N;
+ if( zRight
+ && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
+ && N>=0
+ ){
+ db->nAnalysisLimit = (int)(N&0x7fffffff);
+ }
+ returnSingleInt(v, db->nAnalysisLimit);
+ break;
+ }
+
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+ /*
+ ** Report the current state of file logs for all databases
+ */
+ case PragTyp_LOCK_STATUS: {
+ static const char *const azLockName[] = {
+ "unlocked", "shared", "reserved", "pending", "exclusive"
+ };
+ int i;
+ pParse->nMem = 2;
+ for(i=0; i<db->nDb; i++){
+ Btree *pBt;
+ const char *zState = "unknown";
+ int j;
+ if( db->aDb[i].zDbSName==0 ) continue;
+ pBt = db->aDb[i].pBt;
+ if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
+ zState = "closed";
+ }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
+ SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
+ zState = azLockName[j];
+ }
+ sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
+ }
+ break;
+ }
+#endif
+
+#if defined(SQLITE_ENABLE_CEROD)
+ case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
+ if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
+ sqlite3_activate_cerod(&zRight[6]);
+ }
+ }
+ break;
+#endif
+
+ } /* End of the PRAGMA switch */
+
+ /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
+ ** purpose is to execute assert() statements to verify that if the
+ ** PragFlg_NoColumns1 flag is set and the caller specified an argument
+ ** to the PRAGMA, the implementation has not added any OP_ResultRow
+ ** instructions to the VM. */
+ if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
+ sqlite3VdbeVerifyNoResultRow(v);
+ }
+
+pragma_out:
+ sqlite3DbFree(db, zLeft);
+ sqlite3DbFree(db, zRight);
+}
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/*****************************************************************************
+** Implementation of an eponymous virtual table that runs a pragma.
+**
+*/
+typedef struct PragmaVtab PragmaVtab;
+typedef struct PragmaVtabCursor PragmaVtabCursor;
+struct PragmaVtab {
+ sqlite3_vtab base; /* Base class. Must be first */
+ sqlite3 *db; /* The database connection to which it belongs */
+ const PragmaName *pName; /* Name of the pragma */
+ u8 nHidden; /* Number of hidden columns */
+ u8 iHidden; /* Index of the first hidden column */
+};
+struct PragmaVtabCursor {
+ sqlite3_vtab_cursor base; /* Base class. Must be first */
+ sqlite3_stmt *pPragma; /* The pragma statement to run */
+ sqlite_int64 iRowid; /* Current rowid */
+ char *azArg[2]; /* Value of the argument and schema */
+};
+
+/*
+** Pragma virtual table module xConnect method.
+*/
+static int pragmaVtabConnect(
+ sqlite3 *db,
+ void *pAux,
+ int argc, const char *const*argv,
+ sqlite3_vtab **ppVtab,
+ char **pzErr
+){
+ const PragmaName *pPragma = (const PragmaName*)pAux;
+ PragmaVtab *pTab = 0;
+ int rc;
+ int i, j;
+ char cSep = '(';
+ StrAccum acc;
+ char zBuf[200];
+
+ UNUSED_PARAMETER(argc);
+ UNUSED_PARAMETER(argv);
+ sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
+ sqlite3_str_appendall(&acc, "CREATE TABLE x");
+ for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
+ sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
+ cSep = ',';
+ }
+ if( i==0 ){
+ sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
+ i++;
+ }
+ j = 0;
+ if( pPragma->mPragFlg & PragFlg_Result1 ){
+ sqlite3_str_appendall(&acc, ",arg HIDDEN");
+ j++;
+ }
+ if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
+ sqlite3_str_appendall(&acc, ",schema HIDDEN");
+ j++;
+ }
+ sqlite3_str_append(&acc, ")", 1);
+ sqlite3StrAccumFinish(&acc);
+ assert( strlen(zBuf) < sizeof(zBuf)-1 );
+ rc = sqlite3_declare_vtab(db, zBuf);
+ if( rc==SQLITE_OK ){
+ pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
+ if( pTab==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memset(pTab, 0, sizeof(PragmaVtab));
+ pTab->pName = pPragma;
+ pTab->db = db;
+ pTab->iHidden = i;
+ pTab->nHidden = j;
+ }
+ }else{
+ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
+ }
+
+ *ppVtab = (sqlite3_vtab*)pTab;
+ return rc;
+}
+
+/*
+** Pragma virtual table module xDisconnect method.
+*/
+static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
+ PragmaVtab *pTab = (PragmaVtab*)pVtab;
+ sqlite3_free(pTab);
+ return SQLITE_OK;
+}
+
+/* Figure out the best index to use to search a pragma virtual table.
+**
+** There are not really any index choices. But we want to encourage the
+** query planner to give == constraints on as many hidden parameters as
+** possible, and especially on the first hidden parameter. So return a
+** high cost if hidden parameters are unconstrained.
+*/
+static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
+ PragmaVtab *pTab = (PragmaVtab*)tab;
+ const struct sqlite3_index_constraint *pConstraint;
+ int i, j;
+ int seen[2];
+
+ pIdxInfo->estimatedCost = (double)1;
+ if( pTab->nHidden==0 ){ return SQLITE_OK; }
+ pConstraint = pIdxInfo->aConstraint;
+ seen[0] = 0;
+ seen[1] = 0;
+ for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
+ if( pConstraint->usable==0 ) continue;
+ if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
+ if( pConstraint->iColumn < pTab->iHidden ) continue;
+ j = pConstraint->iColumn - pTab->iHidden;
+ assert( j < 2 );
+ seen[j] = i+1;
+ }
+ if( seen[0]==0 ){
+ pIdxInfo->estimatedCost = (double)2147483647;
+ pIdxInfo->estimatedRows = 2147483647;
+ return SQLITE_OK;
+ }
+ j = seen[0]-1;
+ pIdxInfo->aConstraintUsage[j].argvIndex = 1;
+ pIdxInfo->aConstraintUsage[j].omit = 1;
+ if( seen[1]==0 ) return SQLITE_OK;
+ pIdxInfo->estimatedCost = (double)20;
+ pIdxInfo->estimatedRows = 20;
+ j = seen[1]-1;
+ pIdxInfo->aConstraintUsage[j].argvIndex = 2;
+ pIdxInfo->aConstraintUsage[j].omit = 1;
+ return SQLITE_OK;
+}
+
+/* Create a new cursor for the pragma virtual table */
+static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
+ PragmaVtabCursor *pCsr;
+ pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
+ if( pCsr==0 ) return SQLITE_NOMEM;
+ memset(pCsr, 0, sizeof(PragmaVtabCursor));
+ pCsr->base.pVtab = pVtab;
+ *ppCursor = &pCsr->base;
+ return SQLITE_OK;
+}
+
+/* Clear all content from pragma virtual table cursor. */
+static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
+ int i;
+ sqlite3_finalize(pCsr->pPragma);
+ pCsr->pPragma = 0;
+ for(i=0; i<ArraySize(pCsr->azArg); i++){
+ sqlite3_free(pCsr->azArg[i]);
+ pCsr->azArg[i] = 0;
+ }
+}
+
+/* Close a pragma virtual table cursor */
+static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
+ PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
+ pragmaVtabCursorClear(pCsr);
+ sqlite3_free(pCsr);
+ return SQLITE_OK;
+}
+
+/* Advance the pragma virtual table cursor to the next row */
+static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
+ PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
+ int rc = SQLITE_OK;
+
+ /* Increment the xRowid value */
+ pCsr->iRowid++;
+ assert( pCsr->pPragma );
+ if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
+ rc = sqlite3_finalize(pCsr->pPragma);
+ pCsr->pPragma = 0;
+ pragmaVtabCursorClear(pCsr);
+ }
+ return rc;
+}
+
+/*
+** Pragma virtual table module xFilter method.
+*/
+static int pragmaVtabFilter(
+ sqlite3_vtab_cursor *pVtabCursor,
+ int idxNum, const char *idxStr,
+ int argc, sqlite3_value **argv
+){
+ PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
+ PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
+ int rc;
+ int i, j;
+ StrAccum acc;
+ char *zSql;
+
+ UNUSED_PARAMETER(idxNum);
+ UNUSED_PARAMETER(idxStr);
+ pragmaVtabCursorClear(pCsr);
+ j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
+ for(i=0; i<argc; i++, j++){
+ const char *zText = (const char*)sqlite3_value_text(argv[i]);
+ assert( j<ArraySize(pCsr->azArg) );
+ assert( pCsr->azArg[j]==0 );
+ if( zText ){
+ pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
+ if( pCsr->azArg[j]==0 ){
+ return SQLITE_NOMEM;
+ }
+ }
+ }
+ sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
+ sqlite3_str_appendall(&acc, "PRAGMA ");
+ if( pCsr->azArg[1] ){
+ sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
+ }
+ sqlite3_str_appendall(&acc, pTab->pName->zName);
+ if( pCsr->azArg[0] ){
+ sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
+ }
+ zSql = sqlite3StrAccumFinish(&acc);
+ if( zSql==0 ) return SQLITE_NOMEM;
+ rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
+ sqlite3_free(zSql);
+ if( rc!=SQLITE_OK ){
+ pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
+ return rc;
+ }
+ return pragmaVtabNext(pVtabCursor);
+}
+
+/*
+** Pragma virtual table module xEof method.
+*/
+static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
+ PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
+ return (pCsr->pPragma==0);
+}
+
+/* The xColumn method simply returns the corresponding column from
+** the PRAGMA.
+*/
+static int pragmaVtabColumn(
+ sqlite3_vtab_cursor *pVtabCursor,
+ sqlite3_context *ctx,
+ int i
+){
+ PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
+ PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
+ if( i<pTab->iHidden ){
+ sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
+ }else{
+ sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Pragma virtual table module xRowid method.
+*/
+static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
+ PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
+ *p = pCsr->iRowid;
+ return SQLITE_OK;
+}
+
+/* The pragma virtual table object */
+static const sqlite3_module pragmaVtabModule = {
+ 0, /* iVersion */
+ 0, /* xCreate - create a table */
+ pragmaVtabConnect, /* xConnect - connect to an existing table */
+ pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
+ pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
+ 0, /* xDestroy - Drop a table */
+ pragmaVtabOpen, /* xOpen - open a cursor */
+ pragmaVtabClose, /* xClose - close a cursor */
+ pragmaVtabFilter, /* xFilter - configure scan constraints */
+ pragmaVtabNext, /* xNext - advance a cursor */
+ pragmaVtabEof, /* xEof */
+ pragmaVtabColumn, /* xColumn - read data */
+ pragmaVtabRowid, /* xRowid - read data */
+ 0, /* xUpdate - write data */
+ 0, /* xBegin - begin transaction */
+ 0, /* xSync - sync transaction */
+ 0, /* xCommit - commit transaction */
+ 0, /* xRollback - rollback transaction */
+ 0, /* xFindFunction - function overloading */
+ 0, /* xRename - rename the table */
+ 0, /* xSavepoint */
+ 0, /* xRelease */
+ 0, /* xRollbackTo */
+ 0 /* xShadowName */
+};
+
+/*
+** Check to see if zTabName is really the name of a pragma. If it is,
+** then register an eponymous virtual table for that pragma and return
+** a pointer to the Module object for the new virtual table.
+*/
+SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
+ const PragmaName *pName;
+ assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
+ pName = pragmaLocate(zName+7);
+ if( pName==0 ) return 0;
+ if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
+ assert( sqlite3HashFind(&db->aModule, zName)==0 );
+ return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
+}
+
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+#endif /* SQLITE_OMIT_PRAGMA */
+
+/************** End of pragma.c **********************************************/
+/************** Begin file prepare.c *****************************************/
+/*
+** 2005 May 25
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains the implementation of the sqlite3_prepare()
+** interface, and routines that contribute to loading the database schema
+** from disk.
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** Fill the InitData structure with an error message that indicates
+** that the database is corrupt.
+*/
+static void corruptSchema(
+ InitData *pData, /* Initialization context */
+ const char *zObj, /* Object being parsed at the point of error */
+ const char *zExtra /* Error information */
+){
+ sqlite3 *db = pData->db;
+ if( db->mallocFailed ){
+ pData->rc = SQLITE_NOMEM_BKPT;
+ }else if( pData->pzErrMsg[0]!=0 ){
+ /* A error message has already been generated. Do not overwrite it */
+ }else if( pData->mInitFlags & INITFLAG_AlterTable ){
+ *pData->pzErrMsg = sqlite3DbStrDup(db, zExtra);
+ pData->rc = SQLITE_ERROR;
+ }else if( db->flags & SQLITE_WriteSchema ){
+ pData->rc = SQLITE_CORRUPT_BKPT;
+ }else{
+ char *z;
+ if( zObj==0 ) zObj = "?";
+ z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
+ if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
+ *pData->pzErrMsg = z;
+ pData->rc = SQLITE_CORRUPT_BKPT;
+ }
+}
+
+/*
+** Check to see if any sibling index (another index on the same table)
+** of pIndex has the same root page number, and if it does, return true.
+** This would indicate a corrupt schema.
+*/
+SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index *pIndex){
+ Index *p;
+ for(p=pIndex->pTable->pIndex; p; p=p->pNext){
+ if( p->tnum==pIndex->tnum && p!=pIndex ) return 1;
+ }
+ return 0;
+}
+
+/* forward declaration */
+static int sqlite3Prepare(
+ sqlite3 *db, /* Database handle. */
+ const char *zSql, /* UTF-8 encoded SQL statement. */
+ int nBytes, /* Length of zSql in bytes. */
+ u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
+ Vdbe *pReprepare, /* VM being reprepared */
+ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
+ const char **pzTail /* OUT: End of parsed string */
+);
+
+
+/*
+** This is the callback routine for the code that initializes the
+** database. See sqlite3Init() below for additional information.
+** This routine is also called from the OP_ParseSchema opcode of the VDBE.
+**
+** Each callback contains the following information:
+**
+** argv[0] = type of object: "table", "index", "trigger", or "view".
+** argv[1] = name of thing being created
+** argv[2] = associated table if an index or trigger
+** argv[3] = root page number for table or index. 0 for trigger or view.
+** argv[4] = SQL text for the CREATE statement.
+**
+*/
+SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
+ InitData *pData = (InitData*)pInit;
+ sqlite3 *db = pData->db;
+ int iDb = pData->iDb;
+
+ assert( argc==5 );
+ UNUSED_PARAMETER2(NotUsed, argc);
+ assert( sqlite3_mutex_held(db->mutex) );
+ db->mDbFlags |= DBFLAG_EncodingFixed;
+ pData->nInitRow++;
+ if( db->mallocFailed ){
+ corruptSchema(pData, argv[1], 0);
+ return 1;
+ }
+
+ assert( iDb>=0 && iDb<db->nDb );
+ if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
+ if( argv[3]==0 ){
+ corruptSchema(pData, argv[1], 0);
+ }else if( sqlite3_strnicmp(argv[4],"create ",7)==0 ){
+ /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
+ ** But because db->init.busy is set to 1, no VDBE code is generated
+ ** or executed. All the parser does is build the internal data
+ ** structures that describe the table, index, or view.
+ */
+ int rc;
+ u8 saved_iDb = db->init.iDb;
+ sqlite3_stmt *pStmt;
+ TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
+
+ assert( db->init.busy );
+ db->init.iDb = iDb;
+ if( sqlite3GetUInt32(argv[3], &db->init.newTnum)==0
+ || (db->init.newTnum>pData->mxPage && pData->mxPage>0)
+ ){
+ if( sqlite3Config.bExtraSchemaChecks ){
+ corruptSchema(pData, argv[1], "invalid rootpage");
+ }
+ }
+ db->init.orphanTrigger = 0;
+ db->init.azInit = argv;
+ pStmt = 0;
+ TESTONLY(rcp = ) sqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, 0);
+ rc = db->errCode;
+ assert( (rc&0xFF)==(rcp&0xFF) );
+ db->init.iDb = saved_iDb;
+ /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */
+ if( SQLITE_OK!=rc ){
+ if( db->init.orphanTrigger ){
+ assert( iDb==1 );
+ }else{
+ if( rc > pData->rc ) pData->rc = rc;
+ if( rc==SQLITE_NOMEM ){
+ sqlite3OomFault(db);
+ }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
+ corruptSchema(pData, argv[1], sqlite3_errmsg(db));
+ }
+ }
+ }
+ sqlite3_finalize(pStmt);
+ }else if( argv[1]==0 || (argv[4]!=0 && argv[4][0]!=0) ){
+ corruptSchema(pData, argv[1], 0);
+ }else{
+ /* If the SQL column is blank it means this is an index that
+ ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
+ ** constraint for a CREATE TABLE. The index should have already
+ ** been created when we processed the CREATE TABLE. All we have
+ ** to do here is record the root page number for that index.
+ */
+ Index *pIndex;
+ pIndex = sqlite3FindIndex(db, argv[1], db->aDb[iDb].zDbSName);
+ if( pIndex==0 ){
+ corruptSchema(pData, argv[1], "orphan index");
+ }else
+ if( sqlite3GetUInt32(argv[3],&pIndex->tnum)==0
+ || pIndex->tnum<2
+ || pIndex->tnum>pData->mxPage
+ || sqlite3IndexHasDuplicateRootPage(pIndex)
+ ){
+ if( sqlite3Config.bExtraSchemaChecks ){
+ corruptSchema(pData, argv[1], "invalid rootpage");
+ }
+ }
+ }
+ return 0;
+}
+
+/*
+** Attempt to read the database schema and initialize internal
+** data structures for a single database file. The index of the
+** database file is given by iDb. iDb==0 is used for the main
+** database. iDb==1 should never be used. iDb>=2 is used for
+** auxiliary databases. Return one of the SQLITE_ error codes to
+** indicate success or failure.
+*/
+SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){
+ int rc;
+ int i;
+#ifndef SQLITE_OMIT_DEPRECATED
+ int size;
+#endif
+ Db *pDb;
+ char const *azArg[6];
+ int meta[5];
+ InitData initData;
+ const char *zSchemaTabName;
+ int openedTransaction = 0;
+ int mask = ((db->mDbFlags & DBFLAG_EncodingFixed) | ~DBFLAG_EncodingFixed);
+
+ assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
+ assert( iDb>=0 && iDb<db->nDb );
+ assert( db->aDb[iDb].pSchema );
+ assert( sqlite3_mutex_held(db->mutex) );
+ assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
+
+ db->init.busy = 1;
+
+ /* Construct the in-memory representation schema tables (sqlite_schema or
+ ** sqlite_temp_schema) by invoking the parser directly. The appropriate
+ ** table name will be inserted automatically by the parser so we can just
+ ** use the abbreviation "x" here. The parser will also automatically tag
+ ** the schema table as read-only. */
+ azArg[0] = "table";
+ azArg[1] = zSchemaTabName = SCHEMA_TABLE(iDb);
+ azArg[2] = azArg[1];
+ azArg[3] = "1";
+ azArg[4] = "CREATE TABLE x(type text,name text,tbl_name text,"
+ "rootpage int,sql text)";
+ azArg[5] = 0;
+ initData.db = db;
+ initData.iDb = iDb;
+ initData.rc = SQLITE_OK;
+ initData.pzErrMsg = pzErrMsg;
+ initData.mInitFlags = mFlags;
+ initData.nInitRow = 0;
+ initData.mxPage = 0;
+ sqlite3InitCallback(&initData, 5, (char **)azArg, 0);
+ db->mDbFlags &= mask;
+ if( initData.rc ){
+ rc = initData.rc;
+ goto error_out;
+ }
+
+ /* Create a cursor to hold the database open
+ */
+ pDb = &db->aDb[iDb];
+ if( pDb->pBt==0 ){
+ assert( iDb==1 );
+ DbSetProperty(db, 1, DB_SchemaLoaded);
+ rc = SQLITE_OK;
+ goto error_out;
+ }
+
+ /* If there is not already a read-only (or read-write) transaction opened
+ ** on the b-tree database, open one now. If a transaction is opened, it
+ ** will be closed before this function returns. */
+ sqlite3BtreeEnter(pDb->pBt);
+ if( sqlite3BtreeTxnState(pDb->pBt)==SQLITE_TXN_NONE ){
+ rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);
+ if( rc!=SQLITE_OK ){
+ sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
+ goto initone_error_out;
+ }
+ openedTransaction = 1;
+ }
+
+ /* Get the database meta information.
+ **
+ ** Meta values are as follows:
+ ** meta[0] Schema cookie. Changes with each schema change.
+ ** meta[1] File format of schema layer.
+ ** meta[2] Size of the page cache.
+ ** meta[3] Largest rootpage (auto/incr_vacuum mode)
+ ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
+ ** meta[5] User version
+ ** meta[6] Incremental vacuum mode
+ ** meta[7] unused
+ ** meta[8] unused
+ ** meta[9] unused
+ **
+ ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
+ ** the possible values of meta[4].
+ */
+ for(i=0; i<ArraySize(meta); i++){
+ sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
+ }
+ if( (db->flags & SQLITE_ResetDatabase)!=0 ){
+ memset(meta, 0, sizeof(meta));
+ }
+ pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
+
+ /* If opening a non-empty database, check the text encoding. For the
+ ** main database, set sqlite3.enc to the encoding of the main database.
+ ** For an attached db, it is an error if the encoding is not the same
+ ** as sqlite3.enc.
+ */
+ if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
+ if( iDb==0 && (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
+ u8 encoding;
+#ifndef SQLITE_OMIT_UTF16
+ /* If opening the main database, set ENC(db). */
+ encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
+ if( encoding==0 ) encoding = SQLITE_UTF8;
+#else
+ encoding = SQLITE_UTF8;
+#endif
+ sqlite3SetTextEncoding(db, encoding);
+ }else{
+ /* If opening an attached database, the encoding much match ENC(db) */
+ if( (meta[BTREE_TEXT_ENCODING-1] & 3)!=ENC(db) ){
+ sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
+ " text encoding as main database");
+ rc = SQLITE_ERROR;
+ goto initone_error_out;
+ }
+ }
+ }
+ pDb->pSchema->enc = ENC(db);
+
+ if( pDb->pSchema->cache_size==0 ){
+#ifndef SQLITE_OMIT_DEPRECATED
+ size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
+ if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
+ pDb->pSchema->cache_size = size;
+#else
+ pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
+#endif
+ sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
+ }
+
+ /*
+ ** file_format==1 Version 3.0.0.
+ ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
+ ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
+ ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
+ */
+ pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
+ if( pDb->pSchema->file_format==0 ){
+ pDb->pSchema->file_format = 1;
+ }
+ if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
+ sqlite3SetString(pzErrMsg, db, "unsupported file format");
+ rc = SQLITE_ERROR;
+ goto initone_error_out;
+ }
+
+ /* Ticket #2804: When we open a database in the newer file format,
+ ** clear the legacy_file_format pragma flag so that a VACUUM will
+ ** not downgrade the database and thus invalidate any descending
+ ** indices that the user might have created.
+ */
+ if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
+ db->flags &= ~(u64)SQLITE_LegacyFileFmt;
+ }
+
+ /* Read the schema information out of the schema tables
+ */
+ assert( db->init.busy );
+ initData.mxPage = sqlite3BtreeLastPage(pDb->pBt);
+ {
+ char *zSql;
+ zSql = sqlite3MPrintf(db,
+ "SELECT*FROM\"%w\".%s ORDER BY rowid",
+ db->aDb[iDb].zDbSName, zSchemaTabName);
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ {
+ sqlite3_xauth xAuth;
+ xAuth = db->xAuth;
+ db->xAuth = 0;
+#endif
+ rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ db->xAuth = xAuth;
+ }
+#endif
+ if( rc==SQLITE_OK ) rc = initData.rc;
+ sqlite3DbFree(db, zSql);
+#ifndef SQLITE_OMIT_ANALYZE
+ if( rc==SQLITE_OK ){
+ sqlite3AnalysisLoad(db, iDb);
+ }
+#endif
+ }
+ if( db->mallocFailed ){
+ rc = SQLITE_NOMEM_BKPT;
+ sqlite3ResetAllSchemasOfConnection(db);
+ }
+ if( rc==SQLITE_OK || (db->flags&SQLITE_NoSchemaError)){
+ /* Black magic: If the SQLITE_NoSchemaError flag is set, then consider
+ ** the schema loaded, even if errors occurred. In this situation the
+ ** current sqlite3_prepare() operation will fail, but the following one
+ ** will attempt to compile the supplied statement against whatever subset
+ ** of the schema was loaded before the error occurred. The primary
+ ** purpose of this is to allow access to the sqlite_schema table
+ ** even when its contents have been corrupted.
+ */
+ DbSetProperty(db, iDb, DB_SchemaLoaded);
+ rc = SQLITE_OK;
+ }
+
+ /* Jump here for an error that occurs after successfully allocating
+ ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
+ ** before that point, jump to error_out.
+ */
+initone_error_out:
+ if( openedTransaction ){
+ sqlite3BtreeCommit(pDb->pBt);
+ }
+ sqlite3BtreeLeave(pDb->pBt);
+
+error_out:
+ if( rc ){
+ if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
+ sqlite3OomFault(db);
+ }
+ sqlite3ResetOneSchema(db, iDb);
+ }
+ db->init.busy = 0;
+ return rc;
+}
+
+/*
+** Initialize all database files - the main database file, the file
+** used to store temporary tables, and any additional database files
+** created using ATTACH statements. Return a success code. If an
+** error occurs, write an error message into *pzErrMsg.
+**
+** After a database is initialized, the DB_SchemaLoaded bit is set
+** bit is set in the flags field of the Db structure.
+*/
+SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
+ int i, rc;
+ int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
+
+ assert( sqlite3_mutex_held(db->mutex) );
+ assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
+ assert( db->init.busy==0 );
+ ENC(db) = SCHEMA_ENC(db);
+ assert( db->nDb>0 );
+ /* Do the main schema first */
+ if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
+ rc = sqlite3InitOne(db, 0, pzErrMsg, 0);
+ if( rc ) return rc;
+ }
+ /* All other schemas after the main schema. The "temp" schema must be last */
+ for(i=db->nDb-1; i>0; i--){
+ assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );
+ if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
+ rc = sqlite3InitOne(db, i, pzErrMsg, 0);
+ if( rc ) return rc;
+ }
+ }
+ if( commit_internal ){
+ sqlite3CommitInternalChanges(db);
+ }
+ return SQLITE_OK;
+}
+
+/*
+** This routine is a no-op if the database schema is already initialized.
+** Otherwise, the schema is loaded. An error code is returned.
+*/
+SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
+ int rc = SQLITE_OK;
+ sqlite3 *db = pParse->db;
+ assert( sqlite3_mutex_held(db->mutex) );
+ if( !db->init.busy ){
+ rc = sqlite3Init(db, &pParse->zErrMsg);
+ if( rc!=SQLITE_OK ){
+ pParse->rc = rc;
+ pParse->nErr++;
+ }else if( db->noSharedCache ){
+ db->mDbFlags |= DBFLAG_SchemaKnownOk;
+ }
+ }
+ return rc;
+}
+
+
+/*
+** Check schema cookies in all databases. If any cookie is out
+** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
+** make no changes to pParse->rc.
+*/
+static void schemaIsValid(Parse *pParse){
+ sqlite3 *db = pParse->db;
+ int iDb;
+ int rc;
+ int cookie;
+
+ assert( pParse->checkSchema );
+ assert( sqlite3_mutex_held(db->mutex) );
+ for(iDb=0; iDb<db->nDb; iDb++){
+ int openedTransaction = 0; /* True if a transaction is opened */
+ Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
+ if( pBt==0 ) continue;
+
+ /* If there is not already a read-only (or read-write) transaction opened
+ ** on the b-tree database, open one now. If a transaction is opened, it
+ ** will be closed immediately after reading the meta-value. */
+ if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_NONE ){
+ rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
+ if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
+ sqlite3OomFault(db);
+ }
+ if( rc!=SQLITE_OK ) return;
+ openedTransaction = 1;
+ }
+
+ /* Read the schema cookie from the database. If it does not match the
+ ** value stored as part of the in-memory schema representation,
+ ** set Parse.rc to SQLITE_SCHEMA. */
+ sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
+ sqlite3ResetOneSchema(db, iDb);
+ pParse->rc = SQLITE_SCHEMA;
+ }
+
+ /* Close the transaction, if one was opened. */
+ if( openedTransaction ){
+ sqlite3BtreeCommit(pBt);
+ }
+ }
+}
+
+/*
+** Convert a schema pointer into the iDb index that indicates
+** which database file in db->aDb[] the schema refers to.
+**
+** If the same database is attached more than once, the first
+** attached database is returned.
+*/
+SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
+ int i = -32768;
+
+ /* If pSchema is NULL, then return -32768. This happens when code in
+ ** expr.c is trying to resolve a reference to a transient table (i.e. one
+ ** created by a sub-select). In this case the return value of this
+ ** function should never be used.
+ **
+ ** We return -32768 instead of the more usual -1 simply because using
+ ** -32768 as the incorrect index into db->aDb[] is much
+ ** more likely to cause a segfault than -1 (of course there are assert()
+ ** statements too, but it never hurts to play the odds) and
+ ** -32768 will still fit into a 16-bit signed integer.
+ */
+ assert( sqlite3_mutex_held(db->mutex) );
+ if( pSchema ){
+ for(i=0; 1; i++){
+ assert( i<db->nDb );
+ if( db->aDb[i].pSchema==pSchema ){
+ break;
+ }
+ }
+ assert( i>=0 && i<db->nDb );
+ }
+ return i;
+}
+
+/*
+** Deallocate a single AggInfo object
+*/
+static void agginfoFree(sqlite3 *db, AggInfo *p){
+ sqlite3DbFree(db, p->aCol);
+ sqlite3DbFree(db, p->aFunc);
+ sqlite3DbFree(db, p);
+}
+
+/*
+** Free all memory allocations in the pParse object
+*/
+SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
+ sqlite3 *db = pParse->db;
+ AggInfo *pThis = pParse->pAggList;
+ while( pThis ){
+ AggInfo *pNext = pThis->pNext;
+ agginfoFree(db, pThis);
+ pThis = pNext;
+ }
+ sqlite3DbFree(db, pParse->aLabel);
+ sqlite3ExprListDelete(db, pParse->pConstExpr);
+ if( db ){
+ assert( db->lookaside.bDisable >= pParse->disableLookaside );
+ db->lookaside.bDisable -= pParse->disableLookaside;
+ db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue;
+ }
+ pParse->disableLookaside = 0;
+}
+
+/*
+** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
+*/
+static int sqlite3Prepare(
+ sqlite3 *db, /* Database handle. */
+ const char *zSql, /* UTF-8 encoded SQL statement. */
+ int nBytes, /* Length of zSql in bytes. */
+ u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
+ Vdbe *pReprepare, /* VM being reprepared */
+ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
+ const char **pzTail /* OUT: End of parsed string */
+){
+ char *zErrMsg = 0; /* Error message */
+ int rc = SQLITE_OK; /* Result code */
+ int i; /* Loop counter */
+ Parse sParse; /* Parsing context */
+
+ memset(&sParse, 0, PARSE_HDR_SZ);
+ memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
+ sParse.pReprepare = pReprepare;
+ assert( ppStmt && *ppStmt==0 );
+ /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
+ assert( sqlite3_mutex_held(db->mutex) );
+
+ /* For a long-term use prepared statement avoid the use of
+ ** lookaside memory.
+ */
+ if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
+ sParse.disableLookaside++;
+ DisableLookaside;
+ }
+ sParse.disableVtab = (prepFlags & SQLITE_PREPARE_NO_VTAB)!=0;
+
+ /* Check to verify that it is possible to get a read lock on all
+ ** database schemas. The inability to get a read lock indicates that
+ ** some other database connection is holding a write-lock, which in
+ ** turn means that the other connection has made uncommitted changes
+ ** to the schema.
+ **
+ ** Were we to proceed and prepare the statement against the uncommitted
+ ** schema changes and if those schema changes are subsequently rolled
+ ** back and different changes are made in their place, then when this
+ ** prepared statement goes to run the schema cookie would fail to detect
+ ** the schema change. Disaster would follow.
+ **
+ ** This thread is currently holding mutexes on all Btrees (because
+ ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
+ ** is not possible for another thread to start a new schema change
+ ** while this routine is running. Hence, we do not need to hold
+ ** locks on the schema, we just need to make sure nobody else is
+ ** holding them.
+ **
+ ** Note that setting READ_UNCOMMITTED overrides most lock detection,
+ ** but it does *not* override schema lock detection, so this all still
+ ** works even if READ_UNCOMMITTED is set.
+ */
+ if( !db->noSharedCache ){
+ for(i=0; i<db->nDb; i++) {
+ Btree *pBt = db->aDb[i].pBt;
+ if( pBt ){
+ assert( sqlite3BtreeHoldsMutex(pBt) );
+ rc = sqlite3BtreeSchemaLocked(pBt);
+ if( rc ){
+ const char *zDb = db->aDb[i].zDbSName;
+ sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
+ testcase( db->flags & SQLITE_ReadUncommit );
+ goto end_prepare;
+ }
+ }
+ }
+ }
+
+ sqlite3VtabUnlockList(db);
+
+ sParse.db = db;
+ if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
+ char *zSqlCopy;
+ int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
+ testcase( nBytes==mxLen );
+ testcase( nBytes==mxLen+1 );
+ if( nBytes>mxLen ){
+ sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
+ rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
+ goto end_prepare;
+ }
+ zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
+ if( zSqlCopy ){
+ sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
+ sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
+ sqlite3DbFree(db, zSqlCopy);
+ }else{
+ sParse.zTail = &zSql[nBytes];
+ }
+ }else{
+ sqlite3RunParser(&sParse, zSql, &zErrMsg);
+ }
+ assert( 0==sParse.nQueryLoop );
+
+ if( sParse.rc==SQLITE_DONE ){
+ sParse.rc = SQLITE_OK;
+ }
+ if( sParse.checkSchema ){
+ schemaIsValid(&sParse);
+ }
+ if( pzTail ){
+ *pzTail = sParse.zTail;
+ }
+
+ if( db->init.busy==0 ){
+ sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
+ }
+ if( db->mallocFailed ){
+ sParse.rc = SQLITE_NOMEM_BKPT;
+ }
+ rc = sParse.rc;
+ if( rc!=SQLITE_OK ){
+ if( sParse.pVdbe ) sqlite3VdbeFinalize(sParse.pVdbe);
+ assert(!(*ppStmt));
+ }else{
+ *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
+ }
+
+ if( zErrMsg ){
+ sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
+ sqlite3DbFree(db, zErrMsg);
+ }else{
+ sqlite3Error(db, rc);
+ }
+
+ /* Delete any TriggerPrg structures allocated while parsing this statement. */
+ while( sParse.pTriggerPrg ){
+ TriggerPrg *pT = sParse.pTriggerPrg;
+ sParse.pTriggerPrg = pT->pNext;
+ sqlite3DbFree(db, pT);
+ }
+
+end_prepare:
+
+ sqlite3ParserReset(&sParse);
+ return rc;
+}
+static int sqlite3LockAndPrepare(
+ sqlite3 *db, /* Database handle. */
+ const char *zSql, /* UTF-8 encoded SQL statement. */
+ int nBytes, /* Length of zSql in bytes. */
+ u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
+ Vdbe *pOld, /* VM being reprepared */
+ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
+ const char **pzTail /* OUT: End of parsed string */
+){
+ int rc;
+ int cnt = 0;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
+#endif
+ *ppStmt = 0;
+ if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
+ return SQLITE_MISUSE_BKPT;
+ }
+ sqlite3_mutex_enter(db->mutex);
+ sqlite3BtreeEnterAll(db);
+ do{
+ /* Make multiple attempts to compile the SQL, until it either succeeds
+ ** or encounters a permanent error. A schema problem after one schema
+ ** reset is considered a permanent error. */
+ rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
+ assert( rc==SQLITE_OK || *ppStmt==0 );
+ }while( rc==SQLITE_ERROR_RETRY
+ || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
+ sqlite3BtreeLeaveAll(db);
+ rc = sqlite3ApiExit(db, rc);
+ assert( (rc&db->errMask)==rc );
+ db->busyHandler.nBusy = 0;
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+
+/*
+** Rerun the compilation of a statement after a schema change.
+**
+** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
+** if the statement cannot be recompiled because another connection has
+** locked the sqlite3_schema table, return SQLITE_LOCKED. If any other error
+** occurs, return SQLITE_SCHEMA.
+*/
+SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
+ int rc;
+ sqlite3_stmt *pNew;
+ const char *zSql;
+ sqlite3 *db;
+ u8 prepFlags;
+
+ assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
+ zSql = sqlite3_sql((sqlite3_stmt *)p);
+ assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
+ db = sqlite3VdbeDb(p);
+ assert( sqlite3_mutex_held(db->mutex) );
+ prepFlags = sqlite3VdbePrepareFlags(p);
+ rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
+ if( rc ){
+ if( rc==SQLITE_NOMEM ){
+ sqlite3OomFault(db);
+ }
+ assert( pNew==0 );
+ return rc;
+ }else{
+ assert( pNew!=0 );
+ }
+ sqlite3VdbeSwap((Vdbe*)pNew, p);
+ sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
+ sqlite3VdbeResetStepResult((Vdbe*)pNew);
+ sqlite3VdbeFinalize((Vdbe*)pNew);
+ return SQLITE_OK;
+}
+
+
+/*
+** Two versions of the official API. Legacy and new use. In the legacy
+** version, the original SQL text is not saved in the prepared statement
+** and so if a schema change occurs, SQLITE_SCHEMA is returned by
+** sqlite3_step(). In the new version, the original SQL text is retained
+** and the statement is automatically recompiled if an schema change
+** occurs.
+*/
+SQLITE_API int sqlite3_prepare(
+ sqlite3 *db, /* Database handle. */
+ const char *zSql, /* UTF-8 encoded SQL statement. */
+ int nBytes, /* Length of zSql in bytes. */
+ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
+ const char **pzTail /* OUT: End of parsed string */
+){
+ int rc;
+ rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
+ assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
+ return rc;
+}
+SQLITE_API int sqlite3_prepare_v2(
+ sqlite3 *db, /* Database handle. */
+ const char *zSql, /* UTF-8 encoded SQL statement. */
+ int nBytes, /* Length of zSql in bytes. */
+ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
+ const char **pzTail /* OUT: End of parsed string */
+){
+ int rc;
+ /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
+ ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
+ ** parameter.
+ **
+ ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
+ rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
+ ppStmt,pzTail);
+ assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
+ return rc;
+}
+SQLITE_API int sqlite3_prepare_v3(
+ sqlite3 *db, /* Database handle. */
+ const char *zSql, /* UTF-8 encoded SQL statement. */
+ int nBytes, /* Length of zSql in bytes. */
+ unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
+ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
+ const char **pzTail /* OUT: End of parsed string */
+){
+ int rc;
+ /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
+ ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
+ ** which is a bit array consisting of zero or more of the
+ ** SQLITE_PREPARE_* flags.
+ **
+ ** Proof by comparison to the implementation of sqlite3_prepare_v2()
+ ** directly above. */
+ rc = sqlite3LockAndPrepare(db,zSql,nBytes,
+ SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
+ 0,ppStmt,pzTail);
+ assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
+ return rc;
+}
+
+
+#ifndef SQLITE_OMIT_UTF16
+/*
+** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
+*/
+static int sqlite3Prepare16(
+ sqlite3 *db, /* Database handle. */
+ const void *zSql, /* UTF-16 encoded SQL statement. */
+ int nBytes, /* Length of zSql in bytes. */
+ u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
+ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
+ const void **pzTail /* OUT: End of parsed string */
+){
+ /* This function currently works by first transforming the UTF-16
+ ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
+ ** tricky bit is figuring out the pointer to return in *pzTail.
+ */
+ char *zSql8;
+ const char *zTail8 = 0;
+ int rc = SQLITE_OK;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
+#endif
+ *ppStmt = 0;
+ if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
+ return SQLITE_MISUSE_BKPT;
+ }
+ if( nBytes>=0 ){
+ int sz;
+ const char *z = (const char*)zSql;
+ for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
+ nBytes = sz;
+ }
+ sqlite3_mutex_enter(db->mutex);
+ zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
+ if( zSql8 ){
+ rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
+ }
+
+ if( zTail8 && pzTail ){
+ /* If sqlite3_prepare returns a tail pointer, we calculate the
+ ** equivalent pointer into the UTF-16 string by counting the unicode
+ ** characters between zSql8 and zTail8, and then returning a pointer
+ ** the same number of characters into the UTF-16 string.
+ */
+ int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
+ *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
+ }
+ sqlite3DbFree(db, zSql8);
+ rc = sqlite3ApiExit(db, rc);
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+/*
+** Two versions of the official API. Legacy and new use. In the legacy
+** version, the original SQL text is not saved in the prepared statement
+** and so if a schema change occurs, SQLITE_SCHEMA is returned by
+** sqlite3_step(). In the new version, the original SQL text is retained
+** and the statement is automatically recompiled if an schema change
+** occurs.
+*/
+SQLITE_API int sqlite3_prepare16(
+ sqlite3 *db, /* Database handle. */
+ const void *zSql, /* UTF-16 encoded SQL statement. */
+ int nBytes, /* Length of zSql in bytes. */
+ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
+ const void **pzTail /* OUT: End of parsed string */
+){
+ int rc;
+ rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
+ assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
+ return rc;
+}
+SQLITE_API int sqlite3_prepare16_v2(
+ sqlite3 *db, /* Database handle. */
+ const void *zSql, /* UTF-16 encoded SQL statement. */
+ int nBytes, /* Length of zSql in bytes. */
+ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
+ const void **pzTail /* OUT: End of parsed string */
+){
+ int rc;
+ rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
+ assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
+ return rc;
+}
+SQLITE_API int sqlite3_prepare16_v3(
+ sqlite3 *db, /* Database handle. */
+ const void *zSql, /* UTF-16 encoded SQL statement. */
+ int nBytes, /* Length of zSql in bytes. */
+ unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
+ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
+ const void **pzTail /* OUT: End of parsed string */
+){
+ int rc;
+ rc = sqlite3Prepare16(db,zSql,nBytes,
+ SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
+ ppStmt,pzTail);
+ assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
+ return rc;
+}
+
+#endif /* SQLITE_OMIT_UTF16 */
+
+/************** End of prepare.c *********************************************/
+/************** Begin file select.c ******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains C code routines that are called by the parser
+** to handle SELECT statements in SQLite.
+*/
+/* #include "sqliteInt.h" */
+
+/*
+** An instance of the following object is used to record information about
+** how to process the DISTINCT keyword, to simplify passing that information
+** into the selectInnerLoop() routine.
+*/
+typedef struct DistinctCtx DistinctCtx;
+struct DistinctCtx {
+ u8 isTnct; /* True if the DISTINCT keyword is present */
+ u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
+ int tabTnct; /* Ephemeral table used for DISTINCT processing */
+ int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
+};
+
+/*
+** An instance of the following object is used to record information about
+** the ORDER BY (or GROUP BY) clause of query is being coded.
+**
+** The aDefer[] array is used by the sorter-references optimization. For
+** example, assuming there is no index that can be used for the ORDER BY,
+** for the query:
+**
+** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
+**
+** it may be more efficient to add just the "a" values to the sorter, and
+** retrieve the associated "bigblob" values directly from table t1 as the
+** 10 smallest "a" values are extracted from the sorter.
+**
+** When the sorter-reference optimization is used, there is one entry in the
+** aDefer[] array for each database table that may be read as values are
+** extracted from the sorter.
+*/
+typedef struct SortCtx SortCtx;
+struct SortCtx {
+ ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
+ int nOBSat; /* Number of ORDER BY terms satisfied by indices */
+ int iECursor; /* Cursor number for the sorter */
+ int regReturn; /* Register holding block-output return address */
+ int labelBkOut; /* Start label for the block-output subroutine */
+ int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
+ int labelDone; /* Jump here when done, ex: LIMIT reached */
+ int labelOBLopt; /* Jump here when sorter is full */
+ u8 sortFlags; /* Zero or more SORTFLAG_* bits */
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ u8 nDefer; /* Number of valid entries in aDefer[] */
+ struct DeferredCsr {
+ Table *pTab; /* Table definition */
+ int iCsr; /* Cursor number for table */
+ int nKey; /* Number of PK columns for table pTab (>=1) */
+ } aDefer[4];
+#endif
+ struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */
+};
+#define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
+
+/*
+** Delete all the content of a Select structure. Deallocate the structure
+** itself depending on the value of bFree
+**
+** If bFree==1, call sqlite3DbFree() on the p object.
+** If bFree==0, Leave the first Select object unfreed
+*/
+static void clearSelect(sqlite3 *db, Select *p, int bFree){
+ while( p ){
+ Select *pPrior = p->pPrior;
+ sqlite3ExprListDelete(db, p->pEList);
+ sqlite3SrcListDelete(db, p->pSrc);
+ sqlite3ExprDelete(db, p->pWhere);
+ sqlite3ExprListDelete(db, p->pGroupBy);
+ sqlite3ExprDelete(db, p->pHaving);
+ sqlite3ExprListDelete(db, p->pOrderBy);
+ sqlite3ExprDelete(db, p->pLimit);
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
+ sqlite3WindowListDelete(db, p->pWinDefn);
+ }
+#endif
+ if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
+ if( bFree ) sqlite3DbFreeNN(db, p);
+ p = pPrior;
+ bFree = 1;
+ }
+}
+
+/*
+** Initialize a SelectDest structure.
+*/
+SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
+ pDest->eDest = (u8)eDest;
+ pDest->iSDParm = iParm;
+ pDest->iSDParm2 = 0;
+ pDest->zAffSdst = 0;
+ pDest->iSdst = 0;
+ pDest->nSdst = 0;
+}
+
+
+/*
+** Allocate a new Select structure and return a pointer to that
+** structure.
+*/
+SQLITE_PRIVATE Select *sqlite3SelectNew(
+ Parse *pParse, /* Parsing context */
+ ExprList *pEList, /* which columns to include in the result */
+ SrcList *pSrc, /* the FROM clause -- which tables to scan */
+ Expr *pWhere, /* the WHERE clause */
+ ExprList *pGroupBy, /* the GROUP BY clause */
+ Expr *pHaving, /* the HAVING clause */
+ ExprList *pOrderBy, /* the ORDER BY clause */
+ u32 selFlags, /* Flag parameters, such as SF_Distinct */
+ Expr *pLimit /* LIMIT value. NULL means not used */
+){
+ Select *pNew, *pAllocated;
+ Select standin;
+ pAllocated = pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
+ if( pNew==0 ){
+ assert( pParse->db->mallocFailed );
+ pNew = &standin;
+ }
+ if( pEList==0 ){
+ pEList = sqlite3ExprListAppend(pParse, 0,
+ sqlite3Expr(pParse->db,TK_ASTERISK,0));
+ }
+ pNew->pEList = pEList;
+ pNew->op = TK_SELECT;
+ pNew->selFlags = selFlags;
+ pNew->iLimit = 0;
+ pNew->iOffset = 0;
+ pNew->selId = ++pParse->nSelect;
+ pNew->addrOpenEphm[0] = -1;
+ pNew->addrOpenEphm[1] = -1;
+ pNew->nSelectRow = 0;
+ if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
+ pNew->pSrc = pSrc;
+ pNew->pWhere = pWhere;
+ pNew->pGroupBy = pGroupBy;
+ pNew->pHaving = pHaving;
+ pNew->pOrderBy = pOrderBy;
+ pNew->pPrior = 0;
+ pNew->pNext = 0;
+ pNew->pLimit = pLimit;
+ pNew->pWith = 0;
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ pNew->pWin = 0;
+ pNew->pWinDefn = 0;
+#endif
+ if( pParse->db->mallocFailed ) {
+ clearSelect(pParse->db, pNew, pNew!=&standin);
+ pAllocated = 0;
+ }else{
+ assert( pNew->pSrc!=0 || pParse->nErr>0 );
+ }
+ return pAllocated;
+}
+
+
+/*
+** Delete the given Select structure and all of its substructures.
+*/
+SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
+ if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
+}
+
+/*
+** Return a pointer to the right-most SELECT statement in a compound.
+*/
+static Select *findRightmost(Select *p){
+ while( p->pNext ) p = p->pNext;
+ return p;
+}
+
+/*
+** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
+** type of join. Return an integer constant that expresses that type
+** in terms of the following bit values:
+**
+** JT_INNER
+** JT_CROSS
+** JT_OUTER
+** JT_NATURAL
+** JT_LEFT
+** JT_RIGHT
+**
+** A full outer join is the combination of JT_LEFT and JT_RIGHT.
+**
+** If an illegal or unsupported join type is seen, then still return
+** a join type, but put an error in the pParse structure.
+*/
+SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
+ int jointype = 0;
+ Token *apAll[3];
+ Token *p;
+ /* 0123456789 123456789 123456789 123 */
+ static const char zKeyText[] = "naturaleftouterightfullinnercross";
+ static const struct {
+ u8 i; /* Beginning of keyword text in zKeyText[] */
+ u8 nChar; /* Length of the keyword in characters */
+ u8 code; /* Join type mask */
+ } aKeyword[] = {
+ /* natural */ { 0, 7, JT_NATURAL },
+ /* left */ { 6, 4, JT_LEFT|JT_OUTER },
+ /* outer */ { 10, 5, JT_OUTER },
+ /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
+ /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
+ /* inner */ { 23, 5, JT_INNER },
+ /* cross */ { 28, 5, JT_INNER|JT_CROSS },
+ };
+ int i, j;
+ apAll[0] = pA;
+ apAll[1] = pB;
+ apAll[2] = pC;
+ for(i=0; i<3 && apAll[i]; i++){
+ p = apAll[i];
+ for(j=0; j<ArraySize(aKeyword); j++){
+ if( p->n==aKeyword[j].nChar
+ && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
+ jointype |= aKeyword[j].code;
+ break;
+ }
+ }
+ testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
+ if( j>=ArraySize(aKeyword) ){
+ jointype |= JT_ERROR;
+ break;
+ }
+ }
+ if(
+ (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
+ (jointype & JT_ERROR)!=0
+ ){
+ const char *zSp = " ";
+ assert( pB!=0 );
+ if( pC==0 ){ zSp++; }
+ sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
+ "%T %T%s%T", pA, pB, zSp, pC);
+ jointype = JT_INNER;
+ }else if( (jointype & JT_OUTER)!=0
+ && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
+ sqlite3ErrorMsg(pParse,
+ "RIGHT and FULL OUTER JOINs are not currently supported");
+ jointype = JT_INNER;
+ }
+ return jointype;
+}
+
+/*
+** Return the index of a column in a table. Return -1 if the column
+** is not contained in the table.
+*/
+static int columnIndex(Table *pTab, const char *zCol){
+ int i;
+ u8 h = sqlite3StrIHash(zCol);
+ Column *pCol;
+ for(pCol=pTab->aCol, i=0; i<pTab->nCol; pCol++, i++){
+ if( pCol->hName==h && sqlite3StrICmp(pCol->zName, zCol)==0 ) return i;
+ }
+ return -1;
+}
+
+/*
+** Search the first N tables in pSrc, from left to right, looking for a
+** table that has a column named zCol.
+**
+** When found, set *piTab and *piCol to the table index and column index
+** of the matching column and return TRUE.
+**
+** If not found, return FALSE.
+*/
+static int tableAndColumnIndex(
+ SrcList *pSrc, /* Array of tables to search */
+ int N, /* Number of tables in pSrc->a[] to search */
+ const char *zCol, /* Name of the column we are looking for */
+ int *piTab, /* Write index of pSrc->a[] here */
+ int *piCol, /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
+ int bIgnoreHidden /* True to ignore hidden columns */
+){
+ int i; /* For looping over tables in pSrc */
+ int iCol; /* Index of column matching zCol */
+
+ assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
+ for(i=0; i<N; i++){
+ iCol = columnIndex(pSrc->a[i].pTab, zCol);
+ if( iCol>=0
+ && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0)
+ ){
+ if( piTab ){
+ *piTab = i;
+ *piCol = iCol;
+ }
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/*
+** This function is used to add terms implied by JOIN syntax to the
+** WHERE clause expression of a SELECT statement. The new term, which
+** is ANDed with the existing WHERE clause, is of the form:
+**
+** (tab1.col1 = tab2.col2)
+**
+** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
+** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
+** column iColRight of tab2.
+*/
+static void addWhereTerm(
+ Parse *pParse, /* Parsing context */
+ SrcList *pSrc, /* List of tables in FROM clause */
+ int iLeft, /* Index of first table to join in pSrc */
+ int iColLeft, /* Index of column in first table */
+ int iRight, /* Index of second table in pSrc */
+ int iColRight, /* Index of column in second table */
+ int isOuterJoin, /* True if this is an OUTER join */
+ Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
+){
+ sqlite3 *db = pParse->db;
+ Expr *pE1;
+ Expr *pE2;
+ Expr *pEq;
+
+ assert( iLeft<iRight );
+ assert( pSrc->nSrc>iRight );
+ assert( pSrc->a[iLeft].pTab );
+ assert( pSrc->a[iRight].pTab );
+
+ pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
+ pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
+
+ pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
+ if( pEq && isOuterJoin ){
+ ExprSetProperty(pEq, EP_FromJoin);
+ assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
+ ExprSetVVAProperty(pEq, EP_NoReduce);
+ pEq->iRightJoinTable = (i16)pE2->iTable;
+ }
+ *ppWhere = sqlite3ExprAnd(pParse, *ppWhere, pEq);
+}
+
+/*
+** Set the EP_FromJoin property on all terms of the given expression.
+** And set the Expr.iRightJoinTable to iTable for every term in the
+** expression.
+**
+** The EP_FromJoin property is used on terms of an expression to tell
+** the LEFT OUTER JOIN processing logic that this term is part of the
+** join restriction specified in the ON or USING clause and not a part
+** of the more general WHERE clause. These terms are moved over to the
+** WHERE clause during join processing but we need to remember that they
+** originated in the ON or USING clause.
+**
+** The Expr.iRightJoinTable tells the WHERE clause processing that the
+** expression depends on table iRightJoinTable even if that table is not
+** explicitly mentioned in the expression. That information is needed
+** for cases like this:
+**
+** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
+**
+** The where clause needs to defer the handling of the t1.x=5
+** term until after the t2 loop of the join. In that way, a
+** NULL t2 row will be inserted whenever t1.x!=5. If we do not
+** defer the handling of t1.x=5, it will be processed immediately
+** after the t1 loop and rows with t1.x!=5 will never appear in
+** the output, which is incorrect.
+*/
+SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr *p, int iTable){
+ while( p ){
+ ExprSetProperty(p, EP_FromJoin);
+ assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
+ ExprSetVVAProperty(p, EP_NoReduce);
+ p->iRightJoinTable = (i16)iTable;
+ if( p->op==TK_FUNCTION && p->x.pList ){
+ int i;
+ for(i=0; i<p->x.pList->nExpr; i++){
+ sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable);
+ }
+ }
+ sqlite3SetJoinExpr(p->pLeft, iTable);
+ p = p->pRight;
+ }
+}
+
+/* Undo the work of sqlite3SetJoinExpr(). In the expression p, convert every
+** term that is marked with EP_FromJoin and iRightJoinTable==iTable into
+** an ordinary term that omits the EP_FromJoin mark.
+**
+** This happens when a LEFT JOIN is simplified into an ordinary JOIN.
+*/
+static void unsetJoinExpr(Expr *p, int iTable){
+ while( p ){
+ if( ExprHasProperty(p, EP_FromJoin)
+ && (iTable<0 || p->iRightJoinTable==iTable) ){
+ ExprClearProperty(p, EP_FromJoin);
+ }
+ if( p->op==TK_FUNCTION && p->x.pList ){
+ int i;
+ for(i=0; i<p->x.pList->nExpr; i++){
+ unsetJoinExpr(p->x.pList->a[i].pExpr, iTable);
+ }
+ }
+ unsetJoinExpr(p->pLeft, iTable);
+ p = p->pRight;
+ }
+}
+
+/*
+** This routine processes the join information for a SELECT statement.
+** ON and USING clauses are converted into extra terms of the WHERE clause.
+** NATURAL joins also create extra WHERE clause terms.
+**
+** The terms of a FROM clause are contained in the Select.pSrc structure.
+** The left most table is the first entry in Select.pSrc. The right-most
+** table is the last entry. The join operator is held in the entry to
+** the left. Thus entry 0 contains the join operator for the join between
+** entries 0 and 1. Any ON or USING clauses associated with the join are
+** also attached to the left entry.
+**
+** This routine returns the number of errors encountered.
+*/
+static int sqliteProcessJoin(Parse *pParse, Select *p){
+ SrcList *pSrc; /* All tables in the FROM clause */
+ int i, j; /* Loop counters */
+ struct SrcList_item *pLeft; /* Left table being joined */
+ struct SrcList_item *pRight; /* Right table being joined */
+
+ pSrc = p->pSrc;
+ pLeft = &pSrc->a[0];
+ pRight = &pLeft[1];
+ for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
+ Table *pRightTab = pRight->pTab;
+ int isOuter;
+
+ if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
+ isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
+
+ /* When the NATURAL keyword is present, add WHERE clause terms for
+ ** every column that the two tables have in common.
+ */
+ if( pRight->fg.jointype & JT_NATURAL ){
+ if( pRight->pOn || pRight->pUsing ){
+ sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
+ "an ON or USING clause", 0);
+ return 1;
+ }
+ for(j=0; j<pRightTab->nCol; j++){
+ char *zName; /* Name of column in the right table */
+ int iLeft; /* Matching left table */
+ int iLeftCol; /* Matching column in the left table */
+
+ if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue;
+ zName = pRightTab->aCol[j].zName;
+ if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 1) ){
+ addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
+ isOuter, &p->pWhere);
+ }
+ }
+ }
+
+ /* Disallow both ON and USING clauses in the same join
+ */
+ if( pRight->pOn && pRight->pUsing ){
+ sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
+ "clauses in the same join");
+ return 1;
+ }
+
+ /* Add the ON clause to the end of the WHERE clause, connected by
+ ** an AND operator.
+ */
+ if( pRight->pOn ){
+ if( isOuter ) sqlite3SetJoinExpr(pRight->pOn, pRight->iCursor);
+ p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->pOn);
+ pRight->pOn = 0;
+ }
+
+ /* Create extra terms on the WHERE clause for each column named
+ ** in the USING clause. Example: If the two tables to be joined are
+ ** A and B and the USING clause names X, Y, and Z, then add this
+ ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
+ ** Report an error if any column mentioned in the USING clause is
+ ** not contained in both tables to be joined.
+ */
+ if( pRight->pUsing ){
+ IdList *pList = pRight->pUsing;
+ for(j=0; j<pList->nId; j++){
+ char *zName; /* Name of the term in the USING clause */
+ int iLeft; /* Table on the left with matching column name */
+ int iLeftCol; /* Column number of matching column on the left */
+ int iRightCol; /* Column number of matching column on the right */
+
+ zName = pList->a[j].zName;
+ iRightCol = columnIndex(pRightTab, zName);
+ if( iRightCol<0
+ || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 0)
+ ){
+ sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
+ "not present in both tables", zName);
+ return 1;
+ }
+ addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
+ isOuter, &p->pWhere);
+ }
+ }
+ }
+ return 0;
+}
+
+/*
+** An instance of this object holds information (beyond pParse and pSelect)
+** needed to load the next result row that is to be added to the sorter.
+*/
+typedef struct RowLoadInfo RowLoadInfo;
+struct RowLoadInfo {
+ int regResult; /* Store results in array of registers here */
+ u8 ecelFlags; /* Flag argument to ExprCodeExprList() */
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ ExprList *pExtra; /* Extra columns needed by sorter refs */
+ int regExtraResult; /* Where to load the extra columns */
+#endif
+};
+
+/*
+** This routine does the work of loading query data into an array of
+** registers so that it can be added to the sorter.
+*/
+static void innerLoopLoadRow(
+ Parse *pParse, /* Statement under construction */
+ Select *pSelect, /* The query being coded */
+ RowLoadInfo *pInfo /* Info needed to complete the row load */
+){
+ sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
+ 0, pInfo->ecelFlags);
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ if( pInfo->pExtra ){
+ sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
+ sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
+ }
+#endif
+}
+
+/*
+** Code the OP_MakeRecord instruction that generates the entry to be
+** added into the sorter.
+**
+** Return the register in which the result is stored.
+*/
+static int makeSorterRecord(
+ Parse *pParse,
+ SortCtx *pSort,
+ Select *pSelect,
+ int regBase,
+ int nBase
+){
+ int nOBSat = pSort->nOBSat;
+ Vdbe *v = pParse->pVdbe;
+ int regOut = ++pParse->nMem;
+ if( pSort->pDeferredRowLoad ){
+ innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
+ }
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
+ return regOut;
+}
+
+/*
+** Generate code that will push the record in registers regData
+** through regData+nData-1 onto the sorter.
+*/
+static void pushOntoSorter(
+ Parse *pParse, /* Parser context */
+ SortCtx *pSort, /* Information about the ORDER BY clause */
+ Select *pSelect, /* The whole SELECT statement */
+ int regData, /* First register holding data to be sorted */
+ int regOrigData, /* First register holding data before packing */
+ int nData, /* Number of elements in the regData data array */
+ int nPrefixReg /* No. of reg prior to regData available for use */
+){
+ Vdbe *v = pParse->pVdbe; /* Stmt under construction */
+ int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
+ int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
+ int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
+ int regBase; /* Regs for sorter record */
+ int regRecord = 0; /* Assembled sorter record */
+ int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
+ int op; /* Opcode to add sorter record to sorter */
+ int iLimit; /* LIMIT counter */
+ int iSkip = 0; /* End of the sorter insert loop */
+
+ assert( bSeq==0 || bSeq==1 );
+
+ /* Three cases:
+ ** (1) The data to be sorted has already been packed into a Record
+ ** by a prior OP_MakeRecord. In this case nData==1 and regData
+ ** will be completely unrelated to regOrigData.
+ ** (2) All output columns are included in the sort record. In that
+ ** case regData==regOrigData.
+ ** (3) Some output columns are omitted from the sort record due to
+ ** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the
+ ** SQLITE_ECEL_OMITREF optimization, or due to the
+ ** SortCtx.pDeferredRowLoad optimiation. In any of these cases
+ ** regOrigData is 0 to prevent this routine from trying to copy
+ ** values that might not yet exist.
+ */
+ assert( nData==1 || regData==regOrigData || regOrigData==0 );
+
+ if( nPrefixReg ){
+ assert( nPrefixReg==nExpr+bSeq );
+ regBase = regData - nPrefixReg;
+ }else{
+ regBase = pParse->nMem + 1;
+ pParse->nMem += nBase;
+ }
+ assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
+ iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
+ pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
+ sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
+ SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
+ if( bSeq ){
+ sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
+ }
+ if( nPrefixReg==0 && nData>0 ){
+ sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
+ }
+ if( nOBSat>0 ){
+ int regPrevKey; /* The first nOBSat columns of the previous row */
+ int addrFirst; /* Address of the OP_IfNot opcode */
+ int addrJmp; /* Address of the OP_Jump opcode */
+ VdbeOp *pOp; /* Opcode that opens the sorter */
+ int nKey; /* Number of sorting key columns, including OP_Sequence */
+ KeyInfo *pKI; /* Original KeyInfo on the sorter table */
+
+ regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
+ regPrevKey = pParse->nMem+1;
+ pParse->nMem += pSort->nOBSat;
+ nKey = nExpr - pSort->nOBSat + bSeq;
+ if( bSeq ){
+ addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
+ }else{
+ addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
+ }
+ VdbeCoverage(v);
+ sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
+ pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
+ if( pParse->db->mallocFailed ) return;
+ pOp->p2 = nKey + nData;
+ pKI = pOp->p4.pKeyInfo;
+ memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */
+ sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
+ testcase( pKI->nAllField > pKI->nKeyField+2 );
+ pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
+ pKI->nAllField-pKI->nKeyField-1);
+ pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */
+ addrJmp = sqlite3VdbeCurrentAddr(v);
+ sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
+ pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
+ pSort->regReturn = ++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
+ sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
+ if( iLimit ){
+ sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
+ VdbeCoverage(v);
+ }
+ sqlite3VdbeJumpHere(v, addrFirst);
+ sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
+ sqlite3VdbeJumpHere(v, addrJmp);
+ }
+ if( iLimit ){
+ /* At this point the values for the new sorter entry are stored
+ ** in an array of registers. They need to be composed into a record
+ ** and inserted into the sorter if either (a) there are currently
+ ** less than LIMIT+OFFSET items or (b) the new record is smaller than
+ ** the largest record currently in the sorter. If (b) is true and there
+ ** are already LIMIT+OFFSET items in the sorter, delete the largest
+ ** entry before inserting the new one. This way there are never more
+ ** than LIMIT+OFFSET items in the sorter.
+ **
+ ** If the new record does not need to be inserted into the sorter,
+ ** jump to the next iteration of the loop. If the pSort->labelOBLopt
+ ** value is not zero, then it is a label of where to jump. Otherwise,
+ ** just bypass the row insert logic. See the header comment on the
+ ** sqlite3WhereOrderByLimitOptLabel() function for additional info.
+ */
+ int iCsr = pSort->iECursor;
+ sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
+ VdbeCoverage(v);
+ sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
+ iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
+ iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
+ VdbeCoverage(v);
+ sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
+ }
+ if( regRecord==0 ){
+ regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
+ }
+ if( pSort->sortFlags & SORTFLAG_UseSorter ){
+ op = OP_SorterInsert;
+ }else{
+ op = OP_IdxInsert;
+ }
+ sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
+ regBase+nOBSat, nBase-nOBSat);
+ if( iSkip ){
+ sqlite3VdbeChangeP2(v, iSkip,
+ pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
+ }
+}
+
+/*
+** Add code to implement the OFFSET
+*/
+static void codeOffset(
+ Vdbe *v, /* Generate code into this VM */
+ int iOffset, /* Register holding the offset counter */
+ int iContinue /* Jump here to skip the current record */
+){
+ if( iOffset>0 ){
+ sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
+ VdbeComment((v, "OFFSET"));
+ }
+}
+
+/*
+** Add code that will check to make sure the N registers starting at iMem
+** form a distinct entry. iTab is a sorting index that holds previously
+** seen combinations of the N values. A new entry is made in iTab
+** if the current N values are new.
+**
+** A jump to addrRepeat is made and the N+1 values are popped from the
+** stack if the top N elements are not distinct.
+*/
+static void codeDistinct(
+ Parse *pParse, /* Parsing and code generating context */
+ int iTab, /* A sorting index used to test for distinctness */
+ int addrRepeat, /* Jump to here if not distinct */
+ int N, /* Number of elements */
+ int iMem /* First element */
+){
+ Vdbe *v;
+ int r1;
+
+ v = pParse->pVdbe;
+ r1 = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
+ sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
+ sqlite3ReleaseTempReg(pParse, r1);
+}
+
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+/*
+** This function is called as part of inner-loop generation for a SELECT
+** statement with an ORDER BY that is not optimized by an index. It
+** determines the expressions, if any, that the sorter-reference
+** optimization should be used for. The sorter-reference optimization
+** is used for SELECT queries like:
+**
+** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
+**
+** If the optimization is used for expression "bigblob", then instead of
+** storing values read from that column in the sorter records, the PK of
+** the row from table t1 is stored instead. Then, as records are extracted from
+** the sorter to return to the user, the required value of bigblob is
+** retrieved directly from table t1. If the values are very large, this
+** can be more efficient than storing them directly in the sorter records.
+**
+** The ExprList_item.bSorterRef flag is set for each expression in pEList
+** for which the sorter-reference optimization should be enabled.
+** Additionally, the pSort->aDefer[] array is populated with entries
+** for all cursors required to evaluate all selected expressions. Finally.
+** output variable (*ppExtra) is set to an expression list containing
+** expressions for all extra PK values that should be stored in the
+** sorter records.
+*/
+static void selectExprDefer(
+ Parse *pParse, /* Leave any error here */
+ SortCtx *pSort, /* Sorter context */
+ ExprList *pEList, /* Expressions destined for sorter */
+ ExprList **ppExtra /* Expressions to append to sorter record */
+){
+ int i;
+ int nDefer = 0;
+ ExprList *pExtra = 0;
+ for(i=0; i<pEList->nExpr; i++){
+ struct ExprList_item *pItem = &pEList->a[i];
+ if( pItem->u.x.iOrderByCol==0 ){
+ Expr *pExpr = pItem->pExpr;
+ Table *pTab = pExpr->y.pTab;
+ if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab)
+ && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)
+ ){
+ int j;
+ for(j=0; j<nDefer; j++){
+ if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
+ }
+ if( j==nDefer ){
+ if( nDefer==ArraySize(pSort->aDefer) ){
+ continue;
+ }else{
+ int nKey = 1;
+ int k;
+ Index *pPk = 0;
+ if( !HasRowid(pTab) ){
+ pPk = sqlite3PrimaryKeyIndex(pTab);
+ nKey = pPk->nKeyCol;
+ }
+ for(k=0; k<nKey; k++){
+ Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
+ if( pNew ){
+ pNew->iTable = pExpr->iTable;
+ pNew->y.pTab = pExpr->y.pTab;
+ pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
+ pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
+ }
+ }
+ pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
+ pSort->aDefer[nDefer].iCsr = pExpr->iTable;
+ pSort->aDefer[nDefer].nKey = nKey;
+ nDefer++;
+ }
+ }
+ pItem->bSorterRef = 1;
+ }
+ }
+ }
+ pSort->nDefer = (u8)nDefer;
+ *ppExtra = pExtra;
+}
+#endif
+
+/*
+** This routine generates the code for the inside of the inner loop
+** of a SELECT.
+**
+** If srcTab is negative, then the p->pEList expressions
+** are evaluated in order to get the data for this row. If srcTab is
+** zero or more, then data is pulled from srcTab and p->pEList is used only
+** to get the number of columns and the collation sequence for each column.
+*/
+static void selectInnerLoop(
+ Parse *pParse, /* The parser context */
+ Select *p, /* The complete select statement being coded */
+ int srcTab, /* Pull data from this table if non-negative */
+ SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
+ DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
+ SelectDest *pDest, /* How to dispose of the results */
+ int iContinue, /* Jump here to continue with next row */
+ int iBreak /* Jump here to break out of the inner loop */
+){
+ Vdbe *v = pParse->pVdbe;
+ int i;
+ int hasDistinct; /* True if the DISTINCT keyword is present */
+ int eDest = pDest->eDest; /* How to dispose of results */
+ int iParm = pDest->iSDParm; /* First argument to disposal method */
+ int nResultCol; /* Number of result columns */
+ int nPrefixReg = 0; /* Number of extra registers before regResult */
+ RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */
+
+ /* Usually, regResult is the first cell in an array of memory cells
+ ** containing the current result row. In this case regOrig is set to the
+ ** same value. However, if the results are being sent to the sorter, the
+ ** values for any expressions that are also part of the sort-key are omitted
+ ** from this array. In this case regOrig is set to zero. */
+ int regResult; /* Start of memory holding current results */
+ int regOrig; /* Start of memory holding full result (or 0) */
+
+ assert( v );
+ assert( p->pEList!=0 );
+ hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
+ if( pSort && pSort->pOrderBy==0 ) pSort = 0;
+ if( pSort==0 && !hasDistinct ){
+ assert( iContinue!=0 );
+ codeOffset(v, p->iOffset, iContinue);
+ }
+
+ /* Pull the requested columns.
+ */
+ nResultCol = p->pEList->nExpr;
+
+ if( pDest->iSdst==0 ){
+ if( pSort ){
+ nPrefixReg = pSort->pOrderBy->nExpr;
+ if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
+ pParse->nMem += nPrefixReg;
+ }
+ pDest->iSdst = pParse->nMem+1;
+ pParse->nMem += nResultCol;
+ }else if( pDest->iSdst+nResultCol > pParse->nMem ){
+ /* This is an error condition that can result, for example, when a SELECT
+ ** on the right-hand side of an INSERT contains more result columns than
+ ** there are columns in the table on the left. The error will be caught
+ ** and reported later. But we need to make sure enough memory is allocated
+ ** to avoid other spurious errors in the meantime. */
+ pParse->nMem += nResultCol;
+ }
+ pDest->nSdst = nResultCol;
+ regOrig = regResult = pDest->iSdst;
+ if( srcTab>=0 ){
+ for(i=0; i<nResultCol; i++){
+ sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
+ VdbeComment((v, "%s", p->pEList->a[i].zEName));
+ }
+ }else if( eDest!=SRT_Exists ){
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ ExprList *pExtra = 0;
+#endif
+ /* If the destination is an EXISTS(...) expression, the actual
+ ** values returned by the SELECT are not required.
+ */
+ u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
+ ExprList *pEList;
+ if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
+ ecelFlags = SQLITE_ECEL_DUP;
+ }else{
+ ecelFlags = 0;
+ }
+ if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
+ /* For each expression in p->pEList that is a copy of an expression in
+ ** the ORDER BY clause (pSort->pOrderBy), set the associated
+ ** iOrderByCol value to one more than the index of the ORDER BY
+ ** expression within the sort-key that pushOntoSorter() will generate.
+ ** This allows the p->pEList field to be omitted from the sorted record,
+ ** saving space and CPU cycles. */
+ ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
+
+ for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
+ int j;
+ if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
+ p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
+ }
+ }
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ selectExprDefer(pParse, pSort, p->pEList, &pExtra);
+ if( pExtra && pParse->db->mallocFailed==0 ){
+ /* If there are any extra PK columns to add to the sorter records,
+ ** allocate extra memory cells and adjust the OpenEphemeral
+ ** instruction to account for the larger records. This is only
+ ** required if there are one or more WITHOUT ROWID tables with
+ ** composite primary keys in the SortCtx.aDefer[] array. */
+ VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
+ pOp->p2 += (pExtra->nExpr - pSort->nDefer);
+ pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
+ pParse->nMem += pExtra->nExpr;
+ }
+#endif
+
+ /* Adjust nResultCol to account for columns that are omitted
+ ** from the sorter by the optimizations in this branch */
+ pEList = p->pEList;
+ for(i=0; i<pEList->nExpr; i++){
+ if( pEList->a[i].u.x.iOrderByCol>0
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ || pEList->a[i].bSorterRef
+#endif
+ ){
+ nResultCol--;
+ regOrig = 0;
+ }
+ }
+
+ testcase( regOrig );
+ testcase( eDest==SRT_Set );
+ testcase( eDest==SRT_Mem );
+ testcase( eDest==SRT_Coroutine );
+ testcase( eDest==SRT_Output );
+ assert( eDest==SRT_Set || eDest==SRT_Mem
+ || eDest==SRT_Coroutine || eDest==SRT_Output
+ || eDest==SRT_Upfrom );
+ }
+ sRowLoadInfo.regResult = regResult;
+ sRowLoadInfo.ecelFlags = ecelFlags;
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ sRowLoadInfo.pExtra = pExtra;
+ sRowLoadInfo.regExtraResult = regResult + nResultCol;
+ if( pExtra ) nResultCol += pExtra->nExpr;
+#endif
+ if( p->iLimit
+ && (ecelFlags & SQLITE_ECEL_OMITREF)!=0
+ && nPrefixReg>0
+ ){
+ assert( pSort!=0 );
+ assert( hasDistinct==0 );
+ pSort->pDeferredRowLoad = &sRowLoadInfo;
+ regOrig = 0;
+ }else{
+ innerLoopLoadRow(pParse, p, &sRowLoadInfo);
+ }
+ }
+
+ /* If the DISTINCT keyword was present on the SELECT statement
+ ** and this row has been seen before, then do not make this row
+ ** part of the result.
+ */
+ if( hasDistinct ){
+ switch( pDistinct->eTnctType ){
+ case WHERE_DISTINCT_ORDERED: {
+ VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
+ int iJump; /* Jump destination */
+ int regPrev; /* Previous row content */
+
+ /* Allocate space for the previous row */
+ regPrev = pParse->nMem+1;
+ pParse->nMem += nResultCol;
+
+ /* Change the OP_OpenEphemeral coded earlier to an OP_Null
+ ** sets the MEM_Cleared bit on the first register of the
+ ** previous value. This will cause the OP_Ne below to always
+ ** fail on the first iteration of the loop even if the first
+ ** row is all NULLs.
+ */
+ sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
+ pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
+ pOp->opcode = OP_Null;
+ pOp->p1 = 1;
+ pOp->p2 = regPrev;
+ pOp = 0; /* Ensure pOp is not used after sqlite3VdbeAddOp() */
+
+ iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
+ for(i=0; i<nResultCol; i++){
+ CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
+ if( i<nResultCol-1 ){
+ sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
+ VdbeCoverage(v);
+ }else{
+ sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
+ VdbeCoverage(v);
+ }
+ sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
+ sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
+ }
+ assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
+ sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
+ break;
+ }
+
+ case WHERE_DISTINCT_UNIQUE: {
+ sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
+ break;
+ }
+
+ default: {
+ assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
+ codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
+ regResult);
+ break;
+ }
+ }
+ if( pSort==0 ){
+ codeOffset(v, p->iOffset, iContinue);
+ }
+ }
+
+ switch( eDest ){
+ /* In this mode, write each query result to the key of the temporary
+ ** table iParm.
+ */
+#ifndef SQLITE_OMIT_COMPOUND_SELECT
+ case SRT_Union: {
+ int r1;
+ r1 = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
+ sqlite3ReleaseTempReg(pParse, r1);
+ break;
+ }
+
+ /* Construct a record from the query result, but instead of
+ ** saving that record, use it as a key to delete elements from
+ ** the temporary table iParm.
+ */
+ case SRT_Except: {
+ sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
+ break;
+ }
+#endif /* SQLITE_OMIT_COMPOUND_SELECT */
+
+ /* Store the result as data using a unique key.
+ */
+ case SRT_Fifo:
+ case SRT_DistFifo:
+ case SRT_Table:
+ case SRT_EphemTab: {
+ int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
+ testcase( eDest==SRT_Table );
+ testcase( eDest==SRT_EphemTab );
+ testcase( eDest==SRT_Fifo );
+ testcase( eDest==SRT_DistFifo );
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
+#ifndef SQLITE_OMIT_CTE
+ if( eDest==SRT_DistFifo ){
+ /* If the destination is DistFifo, then cursor (iParm+1) is open
+ ** on an ephemeral index. If the current row is already present
+ ** in the index, do not write it to the output. If not, add the
+ ** current row to the index and proceed with writing it to the
+ ** output table as well. */
+ int addr = sqlite3VdbeCurrentAddr(v) + 4;
+ sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
+ VdbeCoverage(v);
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
+ assert( pSort==0 );
+ }
+#endif
+ if( pSort ){
+ assert( regResult==regOrig );
+ pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
+ }else{
+ int r2 = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
+ sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
+ sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
+ sqlite3ReleaseTempReg(pParse, r2);
+ }
+ sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
+ break;
+ }
+
+ case SRT_Upfrom: {
+ if( pSort ){
+ pushOntoSorter(
+ pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
+ }else{
+ int i2 = pDest->iSDParm2;
+ int r1 = sqlite3GetTempReg(pParse);
+
+ /* If the UPDATE FROM join is an aggregate that matches no rows, it
+ ** might still be trying to return one row, because that is what
+ ** aggregates do. Don't record that empty row in the output table. */
+ sqlite3VdbeAddOp2(v, OP_IsNull, regResult, iBreak); VdbeCoverage(v);
+
+ sqlite3VdbeAddOp3(v, OP_MakeRecord,
+ regResult+(i2<0), nResultCol-(i2<0), r1);
+ if( i2<0 ){
+ sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regResult);
+ }else{
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, i2);
+ }
+ }
+ break;
+ }
+
+#ifndef SQLITE_OMIT_SUBQUERY
+ /* If we are creating a set for an "expr IN (SELECT ...)" construct,
+ ** then there should be a single item on the stack. Write this
+ ** item into the set table with bogus data.
+ */
+ case SRT_Set: {
+ if( pSort ){
+ /* At first glance you would think we could optimize out the
+ ** ORDER BY in this case since the order of entries in the set
+ ** does not matter. But there might be a LIMIT clause, in which
+ ** case the order does matter */
+ pushOntoSorter(
+ pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
+ }else{
+ int r1 = sqlite3GetTempReg(pParse);
+ assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
+ sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
+ r1, pDest->zAffSdst, nResultCol);
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
+ sqlite3ReleaseTempReg(pParse, r1);
+ }
+ break;
+ }
+
+
+ /* If any row exist in the result set, record that fact and abort.
+ */
+ case SRT_Exists: {
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
+ /* The LIMIT clause will terminate the loop for us */
+ break;
+ }
+
+ /* If this is a scalar select that is part of an expression, then
+ ** store the results in the appropriate memory cell or array of
+ ** memory cells and break out of the scan loop.
+ */
+ case SRT_Mem: {
+ if( pSort ){
+ assert( nResultCol<=pDest->nSdst );
+ pushOntoSorter(
+ pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
+ }else{
+ assert( nResultCol==pDest->nSdst );
+ assert( regResult==iParm );
+ /* The LIMIT clause will jump out of the loop for us */
+ }
+ break;
+ }
+#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
+
+ case SRT_Coroutine: /* Send data to a co-routine */
+ case SRT_Output: { /* Return the results */
+ testcase( eDest==SRT_Coroutine );
+ testcase( eDest==SRT_Output );
+ if( pSort ){
+ pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
+ nPrefixReg);
+ }else if( eDest==SRT_Coroutine ){
+ sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
+ }
+ break;
+ }
+
+#ifndef SQLITE_OMIT_CTE
+ /* Write the results into a priority queue that is order according to
+ ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
+ ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
+ ** pSO->nExpr columns, then make sure all keys are unique by adding a
+ ** final OP_Sequence column. The last column is the record as a blob.
+ */
+ case SRT_DistQueue:
+ case SRT_Queue: {
+ int nKey;
+ int r1, r2, r3;
+ int addrTest = 0;
+ ExprList *pSO;
+ pSO = pDest->pOrderBy;
+ assert( pSO );
+ nKey = pSO->nExpr;
+ r1 = sqlite3GetTempReg(pParse);
+ r2 = sqlite3GetTempRange(pParse, nKey+2);
+ r3 = r2+nKey+1;
+ if( eDest==SRT_DistQueue ){
+ /* If the destination is DistQueue, then cursor (iParm+1) is open
+ ** on a second ephemeral index that holds all values every previously
+ ** added to the queue. */
+ addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
+ regResult, nResultCol);
+ VdbeCoverage(v);
+ }
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
+ if( eDest==SRT_DistQueue ){
+ sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
+ sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
+ }
+ for(i=0; i<nKey; i++){
+ sqlite3VdbeAddOp2(v, OP_SCopy,
+ regResult + pSO->a[i].u.x.iOrderByCol - 1,
+ r2+i);
+ }
+ sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
+ if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
+ sqlite3ReleaseTempReg(pParse, r1);
+ sqlite3ReleaseTempRange(pParse, r2, nKey+2);
+ break;
+ }
+#endif /* SQLITE_OMIT_CTE */
+
+
+
+#if !defined(SQLITE_OMIT_TRIGGER)
+ /* Discard the results. This is used for SELECT statements inside
+ ** the body of a TRIGGER. The purpose of such selects is to call
+ ** user-defined functions that have side effects. We do not care
+ ** about the actual results of the select.
+ */
+ default: {
+ assert( eDest==SRT_Discard );
+ break;
+ }
+#endif
+ }
+
+ /* Jump to the end of the loop if the LIMIT is reached. Except, if
+ ** there is a sorter, in which case the sorter has already limited
+ ** the output for us.
+ */
+ if( pSort==0 && p->iLimit ){
+ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
+ }
+}
+
+/*
+** Allocate a KeyInfo object sufficient for an index of N key columns and
+** X extra columns.
+*/
+SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
+ int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
+ KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
+ if( p ){
+ p->aSortFlags = (u8*)&p->aColl[N+X];
+ p->nKeyField = (u16)N;
+ p->nAllField = (u16)(N+X);
+ p->enc = ENC(db);
+ p->db = db;
+ p->nRef = 1;
+ memset(&p[1], 0, nExtra);
+ }else{
+ sqlite3OomFault(db);
+ }
+ return p;
+}
+
+/*
+** Deallocate a KeyInfo object
+*/
+SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
+ if( p ){
+ assert( p->nRef>0 );
+ p->nRef--;
+ if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
+ }
+}
+
+/*
+** Make a new pointer to a KeyInfo object
+*/
+SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
+ if( p ){
+ assert( p->nRef>0 );
+ p->nRef++;
+ }
+ return p;
+}
+
+#ifdef SQLITE_DEBUG
+/*
+** Return TRUE if a KeyInfo object can be change. The KeyInfo object
+** can only be changed if this is just a single reference to the object.
+**
+** This routine is used only inside of assert() statements.
+*/
+SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
+#endif /* SQLITE_DEBUG */
+
+/*
+** Given an expression list, generate a KeyInfo structure that records
+** the collating sequence for each expression in that expression list.
+**
+** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
+** KeyInfo structure is appropriate for initializing a virtual index to
+** implement that clause. If the ExprList is the result set of a SELECT
+** then the KeyInfo structure is appropriate for initializing a virtual
+** index to implement a DISTINCT test.
+**
+** Space to hold the KeyInfo structure is obtained from malloc. The calling
+** function is responsible for seeing that this structure is eventually
+** freed.
+*/
+SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(
+ Parse *pParse, /* Parsing context */
+ ExprList *pList, /* Form the KeyInfo object from this ExprList */
+ int iStart, /* Begin with this column of pList */
+ int nExtra /* Add this many extra columns to the end */
+){
+ int nExpr;
+ KeyInfo *pInfo;
+ struct ExprList_item *pItem;
+ sqlite3 *db = pParse->db;
+ int i;
+
+ nExpr = pList->nExpr;
+ pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
+ if( pInfo ){
+ assert( sqlite3KeyInfoIsWriteable(pInfo) );
+ for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
+ pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
+ pInfo->aSortFlags[i-iStart] = pItem->sortFlags;
+ }
+ }
+ return pInfo;
+}
+
+/*
+** Name of the connection operator, used for error messages.
+*/
+static const char *selectOpName(int id){
+ char *z;
+ switch( id ){
+ case TK_ALL: z = "UNION ALL"; break;
+ case TK_INTERSECT: z = "INTERSECT"; break;
+ case TK_EXCEPT: z = "EXCEPT"; break;
+ default: z = "UNION"; break;
+ }
+ return z;
+}
+
+#ifndef SQLITE_OMIT_EXPLAIN
+/*
+** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
+** is a no-op. Otherwise, it adds a single row of output to the EQP result,
+** where the caption is of the form:
+**
+** "USE TEMP B-TREE FOR xxx"
+**
+** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
+** is determined by the zUsage argument.
+*/
+static void explainTempTable(Parse *pParse, const char *zUsage){
+ ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
+}
+
+/*
+** Assign expression b to lvalue a. A second, no-op, version of this macro
+** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
+** in sqlite3Select() to assign values to structure member variables that
+** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
+** code with #ifndef directives.
+*/
+# define explainSetInteger(a, b) a = b
+
+#else
+/* No-op versions of the explainXXX() functions and macros. */
+# define explainTempTable(y,z)
+# define explainSetInteger(y,z)
+#endif
+
+
+/*
+** If the inner loop was generated using a non-null pOrderBy argument,
+** then the results were placed in a sorter. After the loop is terminated
+** we need to run the sorter and output the results. The following
+** routine generates the code needed to do that.
+*/
+static void generateSortTail(
+ Parse *pParse, /* Parsing context */
+ Select *p, /* The SELECT statement */
+ SortCtx *pSort, /* Information on the ORDER BY clause */
+ int nColumn, /* Number of columns of data */
+ SelectDest *pDest /* Write the sorted results here */
+){
+ Vdbe *v = pParse->pVdbe; /* The prepared statement */
+ int addrBreak = pSort->labelDone; /* Jump here to exit loop */
+ int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */
+ int addr; /* Top of output loop. Jump for Next. */
+ int addrOnce = 0;
+ int iTab;
+ ExprList *pOrderBy = pSort->pOrderBy;
+ int eDest = pDest->eDest;
+ int iParm = pDest->iSDParm;
+ int regRow;
+ int regRowid;
+ int iCol;
+ int nKey; /* Number of key columns in sorter record */
+ int iSortTab; /* Sorter cursor to read from */
+ int i;
+ int bSeq; /* True if sorter record includes seq. no. */
+ int nRefKey = 0;
+ struct ExprList_item *aOutEx = p->pEList->a;
+
+ assert( addrBreak<0 );
+ if( pSort->labelBkOut ){
+ sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
+ sqlite3VdbeGoto(v, addrBreak);
+ sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
+ }
+
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ /* Open any cursors needed for sorter-reference expressions */
+ for(i=0; i<pSort->nDefer; i++){
+ Table *pTab = pSort->aDefer[i].pTab;
+ int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
+ sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
+ nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
+ }
+#endif
+
+ iTab = pSort->iECursor;
+ if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
+ regRowid = 0;
+ regRow = pDest->iSdst;
+ }else{
+ regRowid = sqlite3GetTempReg(pParse);
+ if( eDest==SRT_EphemTab || eDest==SRT_Table ){
+ regRow = sqlite3GetTempReg(pParse);
+ nColumn = 0;
+ }else{
+ regRow = sqlite3GetTempRange(pParse, nColumn);
+ }
+ }
+ nKey = pOrderBy->nExpr - pSort->nOBSat;
+ if( pSort->sortFlags & SORTFLAG_UseSorter ){
+ int regSortOut = ++pParse->nMem;
+ iSortTab = pParse->nTab++;
+ if( pSort->labelBkOut ){
+ addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
+ }
+ sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
+ nKey+1+nColumn+nRefKey);
+ if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
+ addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
+ VdbeCoverage(v);
+ codeOffset(v, p->iOffset, addrContinue);
+ sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
+ bSeq = 0;
+ }else{
+ addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
+ codeOffset(v, p->iOffset, addrContinue);
+ iSortTab = iTab;
+ bSeq = 1;
+ }
+ for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ if( aOutEx[i].bSorterRef ) continue;
+#endif
+ if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
+ }
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ if( pSort->nDefer ){
+ int iKey = iCol+1;
+ int regKey = sqlite3GetTempRange(pParse, nRefKey);
+
+ for(i=0; i<pSort->nDefer; i++){
+ int iCsr = pSort->aDefer[i].iCsr;
+ Table *pTab = pSort->aDefer[i].pTab;
+ int nKey = pSort->aDefer[i].nKey;
+
+ sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
+ if( HasRowid(pTab) ){
+ sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
+ sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
+ sqlite3VdbeCurrentAddr(v)+1, regKey);
+ }else{
+ int k;
+ int iJmp;
+ assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
+ for(k=0; k<nKey; k++){
+ sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
+ }
+ iJmp = sqlite3VdbeCurrentAddr(v);
+ sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
+ sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
+ sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
+ }
+ }
+ sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
+ }
+#endif
+ for(i=nColumn-1; i>=0; i--){
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ if( aOutEx[i].bSorterRef ){
+ sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
+ }else
+#endif
+ {
+ int iRead;
+ if( aOutEx[i].u.x.iOrderByCol ){
+ iRead = aOutEx[i].u.x.iOrderByCol-1;
+ }else{
+ iRead = iCol--;
+ }
+ sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
+ VdbeComment((v, "%s", aOutEx[i].zEName));
+ }
+ }
+ switch( eDest ){
+ case SRT_Table:
+ case SRT_EphemTab: {
+ sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);
+ sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
+ sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
+ sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
+ break;
+ }
+#ifndef SQLITE_OMIT_SUBQUERY
+ case SRT_Set: {
+ assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
+ sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
+ pDest->zAffSdst, nColumn);
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
+ break;
+ }
+ case SRT_Mem: {
+ /* The LIMIT clause will terminate the loop for us */
+ break;
+ }
+#endif
+ case SRT_Upfrom: {
+ int i2 = pDest->iSDParm2;
+ int r1 = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp3(v, OP_MakeRecord,regRow+(i2<0),nColumn-(i2<0),r1);
+ if( i2<0 ){
+ sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regRow);
+ }else{
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regRow, i2);
+ }
+ break;
+ }
+ default: {
+ assert( eDest==SRT_Output || eDest==SRT_Coroutine );
+ testcase( eDest==SRT_Output );
+ testcase( eDest==SRT_Coroutine );
+ if( eDest==SRT_Output ){
+ sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
+ }else{
+ sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
+ }
+ break;
+ }
+ }
+ if( regRowid ){
+ if( eDest==SRT_Set ){
+ sqlite3ReleaseTempRange(pParse, regRow, nColumn);
+ }else{
+ sqlite3ReleaseTempReg(pParse, regRow);
+ }
+ sqlite3ReleaseTempReg(pParse, regRowid);
+ }
+ /* The bottom of the loop
+ */
+ sqlite3VdbeResolveLabel(v, addrContinue);
+ if( pSort->sortFlags & SORTFLAG_UseSorter ){
+ sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
+ }
+ if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
+ sqlite3VdbeResolveLabel(v, addrBreak);
+}
+
+/*
+** Return a pointer to a string containing the 'declaration type' of the
+** expression pExpr. The string may be treated as static by the caller.
+**
+** Also try to estimate the size of the returned value and return that
+** result in *pEstWidth.
+**
+** The declaration type is the exact datatype definition extracted from the
+** original CREATE TABLE statement if the expression is a column. The
+** declaration type for a ROWID field is INTEGER. Exactly when an expression
+** is considered a column can be complex in the presence of subqueries. The
+** result-set expression in all of the following SELECT statements is
+** considered a column by this function.
+**
+** SELECT col FROM tbl;
+** SELECT (SELECT col FROM tbl;
+** SELECT (SELECT col FROM tbl);
+** SELECT abc FROM (SELECT col AS abc FROM tbl);
+**
+** The declaration type for any expression other than a column is NULL.
+**
+** This routine has either 3 or 6 parameters depending on whether or not
+** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
+*/
+#ifdef SQLITE_ENABLE_COLUMN_METADATA
+# define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
+#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
+# define columnType(A,B,C,D,E) columnTypeImpl(A,B)
+#endif
+static const char *columnTypeImpl(
+ NameContext *pNC,
+#ifndef SQLITE_ENABLE_COLUMN_METADATA
+ Expr *pExpr
+#else
+ Expr *pExpr,
+ const char **pzOrigDb,
+ const char **pzOrigTab,
+ const char **pzOrigCol
+#endif
+){
+ char const *zType = 0;
+ int j;
+#ifdef SQLITE_ENABLE_COLUMN_METADATA
+ char const *zOrigDb = 0;
+ char const *zOrigTab = 0;
+ char const *zOrigCol = 0;
+#endif
+
+ assert( pExpr!=0 );
+ assert( pNC->pSrcList!=0 );
+ switch( pExpr->op ){
+ case TK_COLUMN: {
+ /* The expression is a column. Locate the table the column is being
+ ** extracted from in NameContext.pSrcList. This table may be real
+ ** database table or a subquery.
+ */
+ Table *pTab = 0; /* Table structure column is extracted from */
+ Select *pS = 0; /* Select the column is extracted from */
+ int iCol = pExpr->iColumn; /* Index of column in pTab */
+ while( pNC && !pTab ){
+ SrcList *pTabList = pNC->pSrcList;
+ for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
+ if( j<pTabList->nSrc ){
+ pTab = pTabList->a[j].pTab;
+ pS = pTabList->a[j].pSelect;
+ }else{
+ pNC = pNC->pNext;
+ }
+ }
+
+ if( pTab==0 ){
+ /* At one time, code such as "SELECT new.x" within a trigger would
+ ** cause this condition to run. Since then, we have restructured how
+ ** trigger code is generated and so this condition is no longer
+ ** possible. However, it can still be true for statements like
+ ** the following:
+ **
+ ** CREATE TABLE t1(col INTEGER);
+ ** SELECT (SELECT t1.col) FROM FROM t1;
+ **
+ ** when columnType() is called on the expression "t1.col" in the
+ ** sub-select. In this case, set the column type to NULL, even
+ ** though it should really be "INTEGER".
+ **
+ ** This is not a problem, as the column type of "t1.col" is never
+ ** used. When columnType() is called on the expression
+ ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
+ ** branch below. */
+ break;
+ }
+
+ assert( pTab && pExpr->y.pTab==pTab );
+ if( pS ){
+ /* The "table" is actually a sub-select or a view in the FROM clause
+ ** of the SELECT statement. Return the declaration type and origin
+ ** data for the result-set column of the sub-select.
+ */
+ if( iCol>=0 && iCol<pS->pEList->nExpr ){
+ /* If iCol is less than zero, then the expression requests the
+ ** rowid of the sub-select or view. This expression is legal (see
+ ** test case misc2.2.2) - it always evaluates to NULL.
+ */
+ NameContext sNC;
+ Expr *p = pS->pEList->a[iCol].pExpr;
+ sNC.pSrcList = pS->pSrc;
+ sNC.pNext = pNC;
+ sNC.pParse = pNC->pParse;
+ zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
+ }
+ }else{
+ /* A real table or a CTE table */
+ assert( !pS );
+#ifdef SQLITE_ENABLE_COLUMN_METADATA
+ if( iCol<0 ) iCol = pTab->iPKey;
+ assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
+ if( iCol<0 ){
+ zType = "INTEGER";
+ zOrigCol = "rowid";
+ }else{
+ zOrigCol = pTab->aCol[iCol].zName;
+ zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
+ }
+ zOrigTab = pTab->zName;
+ if( pNC->pParse && pTab->pSchema ){
+ int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
+ zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
+ }
+#else
+ assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
+ if( iCol<0 ){
+ zType = "INTEGER";
+ }else{
+ zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
+ }
+#endif
+ }
+ break;
+ }
+#ifndef SQLITE_OMIT_SUBQUERY
+ case TK_SELECT: {
+ /* The expression is a sub-select. Return the declaration type and
+ ** origin info for the single column in the result set of the SELECT
+ ** statement.
+ */
+ NameContext sNC;
+ Select *pS = pExpr->x.pSelect;
+ Expr *p = pS->pEList->a[0].pExpr;
+ assert( ExprHasProperty(pExpr, EP_xIsSelect) );
+ sNC.pSrcList = pS->pSrc;
+ sNC.pNext = pNC;
+ sNC.pParse = pNC->pParse;
+ zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
+ break;
+ }
+#endif
+ }
+
+#ifdef SQLITE_ENABLE_COLUMN_METADATA
+ if( pzOrigDb ){
+ assert( pzOrigTab && pzOrigCol );
+ *pzOrigDb = zOrigDb;
+ *pzOrigTab = zOrigTab;
+ *pzOrigCol = zOrigCol;
+ }
+#endif
+ return zType;
+}
+
+/*
+** Generate code that will tell the VDBE the declaration types of columns
+** in the result set.
+*/
+static void generateColumnTypes(
+ Parse *pParse, /* Parser context */
+ SrcList *pTabList, /* List of tables */
+ ExprList *pEList /* Expressions defining the result set */
+){
+#ifndef SQLITE_OMIT_DECLTYPE
+ Vdbe *v = pParse->pVdbe;
+ int i;
+ NameContext sNC;
+ sNC.pSrcList = pTabList;
+ sNC.pParse = pParse;
+ sNC.pNext = 0;
+ for(i=0; i<pEList->nExpr; i++){
+ Expr *p = pEList->a[i].pExpr;
+ const char *zType;
+#ifdef SQLITE_ENABLE_COLUMN_METADATA
+ const char *zOrigDb = 0;
+ const char *zOrigTab = 0;
+ const char *zOrigCol = 0;
+ zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
+
+ /* The vdbe must make its own copy of the column-type and other
+ ** column specific strings, in case the schema is reset before this
+ ** virtual machine is deleted.
+ */
+ sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
+ sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
+ sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
+#else
+ zType = columnType(&sNC, p, 0, 0, 0);
+#endif
+ sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
+ }
+#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
+}
+
+
+/*
+** Compute the column names for a SELECT statement.
+**
+** The only guarantee that SQLite makes about column names is that if the
+** column has an AS clause assigning it a name, that will be the name used.
+** That is the only documented guarantee. However, countless applications
+** developed over the years have made baseless assumptions about column names
+** and will break if those assumptions changes. Hence, use extreme caution
+** when modifying this routine to avoid breaking legacy.
+**
+** See Also: sqlite3ColumnsFromExprList()
+**
+** The PRAGMA short_column_names and PRAGMA full_column_names settings are
+** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
+** applications should operate this way. Nevertheless, we need to support the
+** other modes for legacy:
+**
+** short=OFF, full=OFF: Column name is the text of the expression has it
+** originally appears in the SELECT statement. In
+** other words, the zSpan of the result expression.
+**
+** short=ON, full=OFF: (This is the default setting). If the result
+** refers directly to a table column, then the
+** result column name is just the table column
+** name: COLUMN. Otherwise use zSpan.
+**
+** full=ON, short=ANY: If the result refers directly to a table column,
+** then the result column name with the table name
+** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
+*/
+static void generateColumnNames(
+ Parse *pParse, /* Parser context */
+ Select *pSelect /* Generate column names for this SELECT statement */
+){
+ Vdbe *v = pParse->pVdbe;
+ int i;
+ Table *pTab;
+ SrcList *pTabList;
+ ExprList *pEList;
+ sqlite3 *db = pParse->db;
+ int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
+ int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
+
+#ifndef SQLITE_OMIT_EXPLAIN
+ /* If this is an EXPLAIN, skip this step */
+ if( pParse->explain ){
+ return;
+ }
+#endif
+
+ if( pParse->colNamesSet ) return;
+ /* Column names are determined by the left-most term of a compound select */
+ while( pSelect->pPrior ) pSelect = pSelect->pPrior;
+ SELECTTRACE(1,pParse,pSelect,("generating column names\n"));
+ pTabList = pSelect->pSrc;
+ pEList = pSelect->pEList;
+ assert( v!=0 );
+ assert( pTabList!=0 );
+ pParse->colNamesSet = 1;
+ fullName = (db->flags & SQLITE_FullColNames)!=0;
+ srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
+ sqlite3VdbeSetNumCols(v, pEList->nExpr);
+ for(i=0; i<pEList->nExpr; i++){
+ Expr *p = pEList->a[i].pExpr;
+
+ assert( p!=0 );
+ assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
+ assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */
+ if( pEList->a[i].zEName && pEList->a[i].eEName==ENAME_NAME ){
+ /* An AS clause always takes first priority */
+ char *zName = pEList->a[i].zEName;
+ sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
+ }else if( srcName && p->op==TK_COLUMN ){
+ char *zCol;
+ int iCol = p->iColumn;
+ pTab = p->y.pTab;
+ assert( pTab!=0 );
+ if( iCol<0 ) iCol = pTab->iPKey;
+ assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
+ if( iCol<0 ){
+ zCol = "rowid";
+ }else{
+ zCol = pTab->aCol[iCol].zName;
+ }
+ if( fullName ){
+ char *zName = 0;
+ zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
+ sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
+ }else{
+ sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
+ }
+ }else{
+ const char *z = pEList->a[i].zEName;
+ z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
+ sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
+ }
+ }
+ generateColumnTypes(pParse, pTabList, pEList);
+}
+
+/*
+** Given an expression list (which is really the list of expressions
+** that form the result set of a SELECT statement) compute appropriate
+** column names for a table that would hold the expression list.
+**
+** All column names will be unique.
+**
+** Only the column names are computed. Column.zType, Column.zColl,
+** and other fields of Column are zeroed.
+**
+** Return SQLITE_OK on success. If a memory allocation error occurs,
+** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
+**
+** The only guarantee that SQLite makes about column names is that if the
+** column has an AS clause assigning it a name, that will be the name used.
+** That is the only documented guarantee. However, countless applications
+** developed over the years have made baseless assumptions about column names
+** and will break if those assumptions changes. Hence, use extreme caution
+** when modifying this routine to avoid breaking legacy.
+**
+** See Also: generateColumnNames()
+*/
+SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
+ Parse *pParse, /* Parsing context */
+ ExprList *pEList, /* Expr list from which to derive column names */
+ i16 *pnCol, /* Write the number of columns here */
+ Column **paCol /* Write the new column list here */
+){
+ sqlite3 *db = pParse->db; /* Database connection */
+ int i, j; /* Loop counters */
+ u32 cnt; /* Index added to make the name unique */
+ Column *aCol, *pCol; /* For looping over result columns */
+ int nCol; /* Number of columns in the result set */
+ char *zName; /* Column name */
+ int nName; /* Size of name in zName[] */
+ Hash ht; /* Hash table of column names */
+
+ sqlite3HashInit(&ht);
+ if( pEList ){
+ nCol = pEList->nExpr;
+ aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
+ testcase( aCol==0 );
+ if( nCol>32767 ) nCol = 32767;
+ }else{
+ nCol = 0;
+ aCol = 0;
+ }
+ assert( nCol==(i16)nCol );
+ *pnCol = nCol;
+ *paCol = aCol;
+
+ for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
+ /* Get an appropriate name for the column
+ */
+ if( (zName = pEList->a[i].zEName)!=0 && pEList->a[i].eEName==ENAME_NAME ){
+ /* If the column contains an "AS <name>" phrase, use <name> as the name */
+ }else{
+ Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pEList->a[i].pExpr);
+ while( pColExpr->op==TK_DOT ){
+ pColExpr = pColExpr->pRight;
+ assert( pColExpr!=0 );
+ }
+ if( pColExpr->op==TK_COLUMN ){
+ /* For columns use the column name name */
+ int iCol = pColExpr->iColumn;
+ Table *pTab = pColExpr->y.pTab;
+ assert( pTab!=0 );
+ if( iCol<0 ) iCol = pTab->iPKey;
+ zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
+ }else if( pColExpr->op==TK_ID ){
+ assert( !ExprHasProperty(pColExpr, EP_IntValue) );
+ zName = pColExpr->u.zToken;
+ }else{
+ /* Use the original text of the column expression as its name */
+ zName = pEList->a[i].zEName;
+ }
+ }
+ if( zName && !sqlite3IsTrueOrFalse(zName) ){
+ zName = sqlite3DbStrDup(db, zName);
+ }else{
+ zName = sqlite3MPrintf(db,"column%d",i+1);
+ }
+
+ /* Make sure the column name is unique. If the name is not unique,
+ ** append an integer to the name so that it becomes unique.
+ */
+ cnt = 0;
+ while( zName && sqlite3HashFind(&ht, zName)!=0 ){
+ nName = sqlite3Strlen30(zName);
+ if( nName>0 ){
+ for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
+ if( zName[j]==':' ) nName = j;
+ }
+ zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
+ if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
+ }
+ pCol->zName = zName;
+ pCol->hName = sqlite3StrIHash(zName);
+ sqlite3ColumnPropertiesFromName(0, pCol);
+ if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
+ sqlite3OomFault(db);
+ }
+ }
+ sqlite3HashClear(&ht);
+ if( db->mallocFailed ){
+ for(j=0; j<i; j++){
+ sqlite3DbFree(db, aCol[j].zName);
+ }
+ sqlite3DbFree(db, aCol);
+ *paCol = 0;
+ *pnCol = 0;
+ return SQLITE_NOMEM_BKPT;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Add type and collation information to a column list based on
+** a SELECT statement.
+**
+** The column list presumably came from selectColumnNamesFromExprList().
+** The column list has only names, not types or collations. This
+** routine goes through and adds the types and collations.
+**
+** This routine requires that all identifiers in the SELECT
+** statement be resolved.
+*/
+SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
+ Parse *pParse, /* Parsing contexts */
+ Table *pTab, /* Add column type information to this table */
+ Select *pSelect, /* SELECT used to determine types and collations */
+ char aff /* Default affinity for columns */
+){
+ sqlite3 *db = pParse->db;
+ NameContext sNC;
+ Column *pCol;
+ CollSeq *pColl;
+ int i;
+ Expr *p;
+ struct ExprList_item *a;
+
+ assert( pSelect!=0 );
+ assert( (pSelect->selFlags & SF_Resolved)!=0 );
+ assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
+ if( db->mallocFailed ) return;
+ memset(&sNC, 0, sizeof(sNC));
+ sNC.pSrcList = pSelect->pSrc;
+ a = pSelect->pEList->a;
+ for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
+ const char *zType;
+ int n, m;
+ p = a[i].pExpr;
+ zType = columnType(&sNC, p, 0, 0, 0);
+ /* pCol->szEst = ... // Column size est for SELECT tables never used */
+ pCol->affinity = sqlite3ExprAffinity(p);
+ if( zType ){
+ m = sqlite3Strlen30(zType);
+ n = sqlite3Strlen30(pCol->zName);
+ pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
+ if( pCol->zName ){
+ memcpy(&pCol->zName[n+1], zType, m+1);
+ pCol->colFlags |= COLFLAG_HASTYPE;
+ }
+ }
+ if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff;
+ pColl = sqlite3ExprCollSeq(pParse, p);
+ if( pColl && pCol->zColl==0 ){
+ pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
+ }
+ }
+ pTab->szTabRow = 1; /* Any non-zero value works */
+}
+
+/*
+** Given a SELECT statement, generate a Table structure that describes
+** the result set of that SELECT.
+*/
+SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){
+ Table *pTab;
+ sqlite3 *db = pParse->db;
+ u64 savedFlags;
+
+ savedFlags = db->flags;
+ db->flags &= ~(u64)SQLITE_FullColNames;
+ db->flags |= SQLITE_ShortColNames;
+ sqlite3SelectPrep(pParse, pSelect, 0);
+ db->flags = savedFlags;
+ if( pParse->nErr ) return 0;
+ while( pSelect->pPrior ) pSelect = pSelect->pPrior;
+ pTab = sqlite3DbMallocZero(db, sizeof(Table) );
+ if( pTab==0 ){
+ return 0;
+ }
+ pTab->nTabRef = 1;
+ pTab->zName = 0;
+ pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
+ sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
+ sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect, aff);
+ pTab->iPKey = -1;
+ if( db->mallocFailed ){
+ sqlite3DeleteTable(db, pTab);
+ return 0;
+ }
+ return pTab;
+}
+
+/*
+** Get a VDBE for the given parser context. Create a new one if necessary.
+** If an error occurs, return NULL and leave a message in pParse.
+*/
+SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
+ if( pParse->pVdbe ){
+ return pParse->pVdbe;
+ }
+ if( pParse->pToplevel==0
+ && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
+ ){
+ pParse->okConstFactor = 1;
+ }
+ return sqlite3VdbeCreate(pParse);
+}
+
+
+/*
+** Compute the iLimit and iOffset fields of the SELECT based on the
+** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
+** that appear in the original SQL statement after the LIMIT and OFFSET
+** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
+** are the integer memory register numbers for counters used to compute
+** the limit and offset. If there is no limit and/or offset, then
+** iLimit and iOffset are negative.
+**
+** This routine changes the values of iLimit and iOffset only if
+** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
+** and iOffset should have been preset to appropriate default values (zero)
+** prior to calling this routine.
+**
+** The iOffset register (if it exists) is initialized to the value
+** of the OFFSET. The iLimit register is initialized to LIMIT. Register
+** iOffset+1 is initialized to LIMIT+OFFSET.
+**
+** Only if pLimit->pLeft!=0 do the limit registers get
+** redefined. The UNION ALL operator uses this property to force
+** the reuse of the same limit and offset registers across multiple
+** SELECT statements.
+*/
+static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
+ Vdbe *v = 0;
+ int iLimit = 0;
+ int iOffset;
+ int n;
+ Expr *pLimit = p->pLimit;
+
+ if( p->iLimit ) return;
+
+ /*
+ ** "LIMIT -1" always shows all rows. There is some
+ ** controversy about what the correct behavior should be.
+ ** The current implementation interprets "LIMIT 0" to mean
+ ** no rows.
+ */
+ if( pLimit ){
+ assert( pLimit->op==TK_LIMIT );
+ assert( pLimit->pLeft!=0 );
+ p->iLimit = iLimit = ++pParse->nMem;
+ v = sqlite3GetVdbe(pParse);
+ assert( v!=0 );
+ if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
+ sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
+ VdbeComment((v, "LIMIT counter"));
+ if( n==0 ){
+ sqlite3VdbeGoto(v, iBreak);
+ }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
+ p->nSelectRow = sqlite3LogEst((u64)n);
+ p->selFlags |= SF_FixedLimit;
+ }
+ }else{
+ sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
+ sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
+ VdbeComment((v, "LIMIT counter"));
+ sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
+ }
+ if( pLimit->pRight ){
+ p->iOffset = iOffset = ++pParse->nMem;
+ pParse->nMem++; /* Allocate an extra register for limit+offset */
+ sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
+ sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
+ VdbeComment((v, "OFFSET counter"));
+ sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
+ VdbeComment((v, "LIMIT+OFFSET"));
+ }
+ }
+}
+
+#ifndef SQLITE_OMIT_COMPOUND_SELECT
+/*
+** Return the appropriate collating sequence for the iCol-th column of
+** the result set for the compound-select statement "p". Return NULL if
+** the column has no default collating sequence.
+**
+** The collating sequence for the compound select is taken from the
+** left-most term of the select that has a collating sequence.
+*/
+static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
+ CollSeq *pRet;
+ if( p->pPrior ){
+ pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
+ }else{
+ pRet = 0;
+ }
+ assert( iCol>=0 );
+ /* iCol must be less than p->pEList->nExpr. Otherwise an error would
+ ** have been thrown during name resolution and we would not have gotten
+ ** this far */
+ if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
+ pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
+ }
+ return pRet;
+}
+
+/*
+** The select statement passed as the second parameter is a compound SELECT
+** with an ORDER BY clause. This function allocates and returns a KeyInfo
+** structure suitable for implementing the ORDER BY.
+**
+** Space to hold the KeyInfo structure is obtained from malloc. The calling
+** function is responsible for ensuring that this structure is eventually
+** freed.
+*/
+static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
+ ExprList *pOrderBy = p->pOrderBy;
+ int nOrderBy = p->pOrderBy->nExpr;
+ sqlite3 *db = pParse->db;
+ KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
+ if( pRet ){
+ int i;
+ for(i=0; i<nOrderBy; i++){
+ struct ExprList_item *pItem = &pOrderBy->a[i];
+ Expr *pTerm = pItem->pExpr;
+ CollSeq *pColl;
+
+ if( pTerm->flags & EP_Collate ){
+ pColl = sqlite3ExprCollSeq(pParse, pTerm);
+ }else{
+ pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
+ if( pColl==0 ) pColl = db->pDfltColl;
+ pOrderBy->a[i].pExpr =
+ sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
+ }
+ assert( sqlite3KeyInfoIsWriteable(pRet) );
+ pRet->aColl[i] = pColl;
+ pRet->aSortFlags[i] = pOrderBy->a[i].sortFlags;
+ }
+ }
+
+ return pRet;
+}
+
+#ifndef SQLITE_OMIT_CTE
+/*
+** This routine generates VDBE code to compute the content of a WITH RECURSIVE
+** query of the form:
+**
+** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
+** \___________/ \_______________/
+** p->pPrior p
+**
+**
+** There is exactly one reference to the recursive-table in the FROM clause
+** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
+**
+** The setup-query runs once to generate an initial set of rows that go
+** into a Queue table. Rows are extracted from the Queue table one by
+** one. Each row extracted from Queue is output to pDest. Then the single
+** extracted row (now in the iCurrent table) becomes the content of the
+** recursive-table for a recursive-query run. The output of the recursive-query
+** is added back into the Queue table. Then another row is extracted from Queue
+** and the iteration continues until the Queue table is empty.
+**
+** If the compound query operator is UNION then no duplicate rows are ever
+** inserted into the Queue table. The iDistinct table keeps a copy of all rows
+** that have ever been inserted into Queue and causes duplicates to be
+** discarded. If the operator is UNION ALL, then duplicates are allowed.
+**
+** If the query has an ORDER BY, then entries in the Queue table are kept in
+** ORDER BY order and the first entry is extracted for each cycle. Without
+** an ORDER BY, the Queue table is just a FIFO.
+**
+** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
+** have been output to pDest. A LIMIT of zero means to output no rows and a
+** negative LIMIT means to output all rows. If there is also an OFFSET clause
+** with a positive value, then the first OFFSET outputs are discarded rather
+** than being sent to pDest. The LIMIT count does not begin until after OFFSET
+** rows have been skipped.
+*/
+static void generateWithRecursiveQuery(
+ Parse *pParse, /* Parsing context */
+ Select *p, /* The recursive SELECT to be coded */
+ SelectDest *pDest /* What to do with query results */
+){
+ SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
+ int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
+ Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
+ Select *pSetup = p->pPrior; /* The setup query */
+ int addrTop; /* Top of the loop */
+ int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
+ int iCurrent = 0; /* The Current table */
+ int regCurrent; /* Register holding Current table */
+ int iQueue; /* The Queue table */
+ int iDistinct = 0; /* To ensure unique results if UNION */
+ int eDest = SRT_Fifo; /* How to write to Queue */
+ SelectDest destQueue; /* SelectDest targetting the Queue table */
+ int i; /* Loop counter */
+ int rc; /* Result code */
+ ExprList *pOrderBy; /* The ORDER BY clause */
+ Expr *pLimit; /* Saved LIMIT and OFFSET */
+ int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( p->pWin ){
+ sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
+ return;
+ }
+#endif
+
+ /* Obtain authorization to do a recursive query */
+ if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
+
+ /* Process the LIMIT and OFFSET clauses, if they exist */
+ addrBreak = sqlite3VdbeMakeLabel(pParse);
+ p->nSelectRow = 320; /* 4 billion rows */
+ computeLimitRegisters(pParse, p, addrBreak);
+ pLimit = p->pLimit;
+ regLimit = p->iLimit;
+ regOffset = p->iOffset;
+ p->pLimit = 0;
+ p->iLimit = p->iOffset = 0;
+ pOrderBy = p->pOrderBy;
+
+ /* Locate the cursor number of the Current table */
+ for(i=0; ALWAYS(i<pSrc->nSrc); i++){
+ if( pSrc->a[i].fg.isRecursive ){
+ iCurrent = pSrc->a[i].iCursor;
+ break;
+ }
+ }
+
+ /* Allocate cursors numbers for Queue and Distinct. The cursor number for
+ ** the Distinct table must be exactly one greater than Queue in order
+ ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
+ iQueue = pParse->nTab++;
+ if( p->op==TK_UNION ){
+ eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
+ iDistinct = pParse->nTab++;
+ }else{
+ eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
+ }
+ sqlite3SelectDestInit(&destQueue, eDest, iQueue);
+
+ /* Allocate cursors for Current, Queue, and Distinct. */
+ regCurrent = ++pParse->nMem;
+ sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
+ if( pOrderBy ){
+ KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
+ sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
+ (char*)pKeyInfo, P4_KEYINFO);
+ destQueue.pOrderBy = pOrderBy;
+ }else{
+ sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
+ }
+ VdbeComment((v, "Queue table"));
+ if( iDistinct ){
+ p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
+ p->selFlags |= SF_UsesEphemeral;
+ }
+
+ /* Detach the ORDER BY clause from the compound SELECT */
+ p->pOrderBy = 0;
+
+ /* Store the results of the setup-query in Queue. */
+ pSetup->pNext = 0;
+ ExplainQueryPlan((pParse, 1, "SETUP"));
+ rc = sqlite3Select(pParse, pSetup, &destQueue);
+ pSetup->pNext = p;
+ if( rc ) goto end_of_recursive_query;
+
+ /* Find the next row in the Queue and output that row */
+ addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
+
+ /* Transfer the next row in Queue over to Current */
+ sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
+ if( pOrderBy ){
+ sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
+ }
+ sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
+
+ /* Output the single row in Current */
+ addrCont = sqlite3VdbeMakeLabel(pParse);
+ codeOffset(v, regOffset, addrCont);
+ selectInnerLoop(pParse, p, iCurrent,
+ 0, 0, pDest, addrCont, addrBreak);
+ if( regLimit ){
+ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
+ VdbeCoverage(v);
+ }
+ sqlite3VdbeResolveLabel(v, addrCont);
+
+ /* Execute the recursive SELECT taking the single row in Current as
+ ** the value for the recursive-table. Store the results in the Queue.
+ */
+ if( p->selFlags & SF_Aggregate ){
+ sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
+ }else{
+ p->pPrior = 0;
+ ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
+ sqlite3Select(pParse, p, &destQueue);
+ assert( p->pPrior==0 );
+ p->pPrior = pSetup;
+ }
+
+ /* Keep running the loop until the Queue is empty */
+ sqlite3VdbeGoto(v, addrTop);
+ sqlite3VdbeResolveLabel(v, addrBreak);
+
+end_of_recursive_query:
+ sqlite3ExprListDelete(pParse->db, p->pOrderBy);
+ p->pOrderBy = pOrderBy;
+ p->pLimit = pLimit;
+ return;
+}
+#endif /* SQLITE_OMIT_CTE */
+
+/* Forward references */
+static int multiSelectOrderBy(
+ Parse *pParse, /* Parsing context */
+ Select *p, /* The right-most of SELECTs to be coded */
+ SelectDest *pDest /* What to do with query results */
+);
+
+/*
+** Handle the special case of a compound-select that originates from a
+** VALUES clause. By handling this as a special case, we avoid deep
+** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
+** on a VALUES clause.
+**
+** Because the Select object originates from a VALUES clause:
+** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
+** (2) All terms are UNION ALL
+** (3) There is no ORDER BY clause
+**
+** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
+** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
+** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
+** Since the limit is exactly 1, we only need to evalutes the left-most VALUES.
+*/
+static int multiSelectValues(
+ Parse *pParse, /* Parsing context */
+ Select *p, /* The right-most of SELECTs to be coded */
+ SelectDest *pDest /* What to do with query results */
+){
+ int nRow = 1;
+ int rc = 0;
+ int bShowAll = p->pLimit==0;
+ assert( p->selFlags & SF_MultiValue );
+ do{
+ assert( p->selFlags & SF_Values );
+ assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
+ assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( p->pWin ) return -1;
+#endif
+ if( p->pPrior==0 ) break;
+ assert( p->pPrior->pNext==p );
+ p = p->pPrior;
+ nRow += bShowAll;
+ }while(1);
+ ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
+ nRow==1 ? "" : "S"));
+ while( p ){
+ selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
+ if( !bShowAll ) break;
+ p->nSelectRow = nRow;
+ p = p->pNext;
+ }
+ return rc;
+}
+
+/*
+** This routine is called to process a compound query form from
+** two or more separate queries using UNION, UNION ALL, EXCEPT, or
+** INTERSECT
+**
+** "p" points to the right-most of the two queries. the query on the
+** left is p->pPrior. The left query could also be a compound query
+** in which case this routine will be called recursively.
+**
+** The results of the total query are to be written into a destination
+** of type eDest with parameter iParm.
+**
+** Example 1: Consider a three-way compound SQL statement.
+**
+** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
+**
+** This statement is parsed up as follows:
+**
+** SELECT c FROM t3
+** |
+** `-----> SELECT b FROM t2
+** |
+** `------> SELECT a FROM t1
+**
+** The arrows in the diagram above represent the Select.pPrior pointer.
+** So if this routine is called with p equal to the t3 query, then
+** pPrior will be the t2 query. p->op will be TK_UNION in this case.
+**
+** Notice that because of the way SQLite parses compound SELECTs, the
+** individual selects always group from left to right.
+*/
+static int multiSelect(
+ Parse *pParse, /* Parsing context */
+ Select *p, /* The right-most of SELECTs to be coded */
+ SelectDest *pDest /* What to do with query results */
+){
+ int rc = SQLITE_OK; /* Success code from a subroutine */
+ Select *pPrior; /* Another SELECT immediately to our left */
+ Vdbe *v; /* Generate code to this VDBE */
+ SelectDest dest; /* Alternative data destination */
+ Select *pDelete = 0; /* Chain of simple selects to delete */
+ sqlite3 *db; /* Database connection */
+
+ /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
+ ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
+ */
+ assert( p && p->pPrior ); /* Calling function guarantees this much */
+ assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
+ assert( p->selFlags & SF_Compound );
+ db = pParse->db;
+ pPrior = p->pPrior;
+ dest = *pDest;
+ if( pPrior->pOrderBy || pPrior->pLimit ){
+ sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
+ pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
+ rc = 1;
+ goto multi_select_end;
+ }
+
+ v = sqlite3GetVdbe(pParse);
+ assert( v!=0 ); /* The VDBE already created by calling function */
+
+ /* Create the destination temporary table if necessary
+ */
+ if( dest.eDest==SRT_EphemTab ){
+ assert( p->pEList );
+ sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
+ dest.eDest = SRT_Table;
+ }
+
+ /* Special handling for a compound-select that originates as a VALUES clause.
+ */
+ if( p->selFlags & SF_MultiValue ){
+ rc = multiSelectValues(pParse, p, &dest);
+ if( rc>=0 ) goto multi_select_end;
+ rc = SQLITE_OK;
+ }
+
+ /* Make sure all SELECTs in the statement have the same number of elements
+ ** in their result sets.
+ */
+ assert( p->pEList && pPrior->pEList );
+ assert( p->pEList->nExpr==pPrior->pEList->nExpr );
+
+#ifndef SQLITE_OMIT_CTE
+ if( p->selFlags & SF_Recursive ){
+ generateWithRecursiveQuery(pParse, p, &dest);
+ }else
+#endif
+
+ /* Compound SELECTs that have an ORDER BY clause are handled separately.
+ */
+ if( p->pOrderBy ){
+ return multiSelectOrderBy(pParse, p, pDest);
+ }else{
+
+#ifndef SQLITE_OMIT_EXPLAIN
+ if( pPrior->pPrior==0 ){
+ ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
+ ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
+ }
+#endif
+
+ /* Generate code for the left and right SELECT statements.
+ */
+ switch( p->op ){
+ case TK_ALL: {
+ int addr = 0;
+ int nLimit;
+ assert( !pPrior->pLimit );
+ pPrior->iLimit = p->iLimit;
+ pPrior->iOffset = p->iOffset;
+ pPrior->pLimit = p->pLimit;
+ rc = sqlite3Select(pParse, pPrior, &dest);
+ p->pLimit = 0;
+ if( rc ){
+ goto multi_select_end;
+ }
+ p->pPrior = 0;
+ p->iLimit = pPrior->iLimit;
+ p->iOffset = pPrior->iOffset;
+ if( p->iLimit ){
+ addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
+ VdbeComment((v, "Jump ahead if LIMIT reached"));
+ if( p->iOffset ){
+ sqlite3VdbeAddOp3(v, OP_OffsetLimit,
+ p->iLimit, p->iOffset+1, p->iOffset);
+ }
+ }
+ ExplainQueryPlan((pParse, 1, "UNION ALL"));
+ rc = sqlite3Select(pParse, p, &dest);
+ testcase( rc!=SQLITE_OK );
+ pDelete = p->pPrior;
+ p->pPrior = pPrior;
+ p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
+ if( pPrior->pLimit
+ && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
+ && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
+ ){
+ p->nSelectRow = sqlite3LogEst((u64)nLimit);
+ }
+ if( addr ){
+ sqlite3VdbeJumpHere(v, addr);
+ }
+ break;
+ }
+ case TK_EXCEPT:
+ case TK_UNION: {
+ int unionTab; /* Cursor number of the temp table holding result */
+ u8 op = 0; /* One of the SRT_ operations to apply to self */
+ int priorOp; /* The SRT_ operation to apply to prior selects */
+ Expr *pLimit; /* Saved values of p->nLimit */
+ int addr;
+ SelectDest uniondest;
+
+ testcase( p->op==TK_EXCEPT );
+ testcase( p->op==TK_UNION );
+ priorOp = SRT_Union;
+ if( dest.eDest==priorOp ){
+ /* We can reuse a temporary table generated by a SELECT to our
+ ** right.
+ */
+ assert( p->pLimit==0 ); /* Not allowed on leftward elements */
+ unionTab = dest.iSDParm;
+ }else{
+ /* We will need to create our own temporary table to hold the
+ ** intermediate results.
+ */
+ unionTab = pParse->nTab++;
+ assert( p->pOrderBy==0 );
+ addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
+ assert( p->addrOpenEphm[0] == -1 );
+ p->addrOpenEphm[0] = addr;
+ findRightmost(p)->selFlags |= SF_UsesEphemeral;
+ assert( p->pEList );
+ }
+
+ /* Code the SELECT statements to our left
+ */
+ assert( !pPrior->pOrderBy );
+ sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
+ rc = sqlite3Select(pParse, pPrior, &uniondest);
+ if( rc ){
+ goto multi_select_end;
+ }
+
+ /* Code the current SELECT statement
+ */
+ if( p->op==TK_EXCEPT ){
+ op = SRT_Except;
+ }else{
+ assert( p->op==TK_UNION );
+ op = SRT_Union;
+ }
+ p->pPrior = 0;
+ pLimit = p->pLimit;
+ p->pLimit = 0;
+ uniondest.eDest = op;
+ ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
+ selectOpName(p->op)));
+ rc = sqlite3Select(pParse, p, &uniondest);
+ testcase( rc!=SQLITE_OK );
+ assert( p->pOrderBy==0 );
+ pDelete = p->pPrior;
+ p->pPrior = pPrior;
+ p->pOrderBy = 0;
+ if( p->op==TK_UNION ){
+ p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
+ }
+ sqlite3ExprDelete(db, p->pLimit);
+ p->pLimit = pLimit;
+ p->iLimit = 0;
+ p->iOffset = 0;
+
+ /* Convert the data in the temporary table into whatever form
+ ** it is that we currently need.
+ */
+ assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
+ assert( p->pEList || db->mallocFailed );
+ if( dest.eDest!=priorOp && db->mallocFailed==0 ){
+ int iCont, iBreak, iStart;
+ iBreak = sqlite3VdbeMakeLabel(pParse);
+ iCont = sqlite3VdbeMakeLabel(pParse);
+ computeLimitRegisters(pParse, p, iBreak);
+ sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
+ iStart = sqlite3VdbeCurrentAddr(v);
+ selectInnerLoop(pParse, p, unionTab,
+ 0, 0, &dest, iCont, iBreak);
+ sqlite3VdbeResolveLabel(v, iCont);
+ sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
+ sqlite3VdbeResolveLabel(v, iBreak);
+ sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
+ }
+ break;
+ }
+ default: assert( p->op==TK_INTERSECT ); {
+ int tab1, tab2;
+ int iCont, iBreak, iStart;
+ Expr *pLimit;
+ int addr;
+ SelectDest intersectdest;
+ int r1;
+
+ /* INTERSECT is different from the others since it requires
+ ** two temporary tables. Hence it has its own case. Begin
+ ** by allocating the tables we will need.
+ */
+ tab1 = pParse->nTab++;
+ tab2 = pParse->nTab++;
+ assert( p->pOrderBy==0 );
+
+ addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
+ assert( p->addrOpenEphm[0] == -1 );
+ p->addrOpenEphm[0] = addr;
+ findRightmost(p)->selFlags |= SF_UsesEphemeral;
+ assert( p->pEList );
+
+ /* Code the SELECTs to our left into temporary table "tab1".
+ */
+ sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
+ rc = sqlite3Select(pParse, pPrior, &intersectdest);
+ if( rc ){
+ goto multi_select_end;
+ }
+
+ /* Code the current SELECT into temporary table "tab2"
+ */
+ addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
+ assert( p->addrOpenEphm[1] == -1 );
+ p->addrOpenEphm[1] = addr;
+ p->pPrior = 0;
+ pLimit = p->pLimit;
+ p->pLimit = 0;
+ intersectdest.iSDParm = tab2;
+ ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
+ selectOpName(p->op)));
+ rc = sqlite3Select(pParse, p, &intersectdest);
+ testcase( rc!=SQLITE_OK );
+ pDelete = p->pPrior;
+ p->pPrior = pPrior;
+ if( p->nSelectRow>pPrior->nSelectRow ){
+ p->nSelectRow = pPrior->nSelectRow;
+ }
+ sqlite3ExprDelete(db, p->pLimit);
+ p->pLimit = pLimit;
+
+ /* Generate code to take the intersection of the two temporary
+ ** tables.
+ */
+ if( rc ) break;
+ assert( p->pEList );
+ iBreak = sqlite3VdbeMakeLabel(pParse);
+ iCont = sqlite3VdbeMakeLabel(pParse);
+ computeLimitRegisters(pParse, p, iBreak);
+ sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
+ r1 = sqlite3GetTempReg(pParse);
+ iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
+ sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
+ VdbeCoverage(v);
+ sqlite3ReleaseTempReg(pParse, r1);
+ selectInnerLoop(pParse, p, tab1,
+ 0, 0, &dest, iCont, iBreak);
+ sqlite3VdbeResolveLabel(v, iCont);
+ sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
+ sqlite3VdbeResolveLabel(v, iBreak);
+ sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
+ sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
+ break;
+ }
+ }
+
+ #ifndef SQLITE_OMIT_EXPLAIN
+ if( p->pNext==0 ){
+ ExplainQueryPlanPop(pParse);
+ }
+ #endif
+ }
+ if( pParse->nErr ) goto multi_select_end;
+
+ /* Compute collating sequences used by
+ ** temporary tables needed to implement the compound select.
+ ** Attach the KeyInfo structure to all temporary tables.
+ **
+ ** This section is run by the right-most SELECT statement only.
+ ** SELECT statements to the left always skip this part. The right-most
+ ** SELECT might also skip this part if it has no ORDER BY clause and
+ ** no temp tables are required.
+ */
+ if( p->selFlags & SF_UsesEphemeral ){
+ int i; /* Loop counter */
+ KeyInfo *pKeyInfo; /* Collating sequence for the result set */
+ Select *pLoop; /* For looping through SELECT statements */
+ CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
+ int nCol; /* Number of columns in result set */
+
+ assert( p->pNext==0 );
+ nCol = p->pEList->nExpr;
+ pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
+ if( !pKeyInfo ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto multi_select_end;
+ }
+ for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
+ *apColl = multiSelectCollSeq(pParse, p, i);
+ if( 0==*apColl ){
+ *apColl = db->pDfltColl;
+ }
+ }
+
+ for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
+ for(i=0; i<2; i++){
+ int addr = pLoop->addrOpenEphm[i];
+ if( addr<0 ){
+ /* If [0] is unused then [1] is also unused. So we can
+ ** always safely abort as soon as the first unused slot is found */
+ assert( pLoop->addrOpenEphm[1]<0 );
+ break;
+ }
+ sqlite3VdbeChangeP2(v, addr, nCol);
+ sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
+ P4_KEYINFO);
+ pLoop->addrOpenEphm[i] = -1;
+ }
+ }
+ sqlite3KeyInfoUnref(pKeyInfo);
+ }
+
+multi_select_end:
+ pDest->iSdst = dest.iSdst;
+ pDest->nSdst = dest.nSdst;
+ sqlite3SelectDelete(db, pDelete);
+ return rc;
+}
+#endif /* SQLITE_OMIT_COMPOUND_SELECT */
+
+/*
+** Error message for when two or more terms of a compound select have different
+** size result sets.
+*/
+SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
+ if( p->selFlags & SF_Values ){
+ sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
+ }else{
+ sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
+ " do not have the same number of result columns", selectOpName(p->op));
+ }
+}
+
+/*
+** Code an output subroutine for a coroutine implementation of a
+** SELECT statment.
+**
+** The data to be output is contained in pIn->iSdst. There are
+** pIn->nSdst columns to be output. pDest is where the output should
+** be sent.
+**
+** regReturn is the number of the register holding the subroutine
+** return address.
+**
+** If regPrev>0 then it is the first register in a vector that
+** records the previous output. mem[regPrev] is a flag that is false
+** if there has been no previous output. If regPrev>0 then code is
+** generated to suppress duplicates. pKeyInfo is used for comparing
+** keys.
+**
+** If the LIMIT found in p->iLimit is reached, jump immediately to
+** iBreak.
+*/
+static int generateOutputSubroutine(
+ Parse *pParse, /* Parsing context */
+ Select *p, /* The SELECT statement */
+ SelectDest *pIn, /* Coroutine supplying data */
+ SelectDest *pDest, /* Where to send the data */
+ int regReturn, /* The return address register */
+ int regPrev, /* Previous result register. No uniqueness if 0 */
+ KeyInfo *pKeyInfo, /* For comparing with previous entry */
+ int iBreak /* Jump here if we hit the LIMIT */
+){
+ Vdbe *v = pParse->pVdbe;
+ int iContinue;
+ int addr;
+
+ addr = sqlite3VdbeCurrentAddr(v);
+ iContinue = sqlite3VdbeMakeLabel(pParse);
+
+ /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
+ */
+ if( regPrev ){
+ int addr1, addr2;
+ addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
+ addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
+ (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
+ sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
+ sqlite3VdbeJumpHere(v, addr1);
+ sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
+ }
+ if( pParse->db->mallocFailed ) return 0;
+
+ /* Suppress the first OFFSET entries if there is an OFFSET clause
+ */
+ codeOffset(v, p->iOffset, iContinue);
+
+ assert( pDest->eDest!=SRT_Exists );
+ assert( pDest->eDest!=SRT_Table );
+ switch( pDest->eDest ){
+ /* Store the result as data using a unique key.
+ */
+ case SRT_EphemTab: {
+ int r1 = sqlite3GetTempReg(pParse);
+ int r2 = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
+ sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
+ sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
+ sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
+ sqlite3ReleaseTempReg(pParse, r2);
+ sqlite3ReleaseTempReg(pParse, r1);
+ break;
+ }
+
+#ifndef SQLITE_OMIT_SUBQUERY
+ /* If we are creating a set for an "expr IN (SELECT ...)".
+ */
+ case SRT_Set: {
+ int r1;
+ testcase( pIn->nSdst>1 );
+ r1 = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
+ r1, pDest->zAffSdst, pIn->nSdst);
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
+ pIn->iSdst, pIn->nSdst);
+ sqlite3ReleaseTempReg(pParse, r1);
+ break;
+ }
+
+ /* If this is a scalar select that is part of an expression, then
+ ** store the results in the appropriate memory cell and break out
+ ** of the scan loop. Note that the select might return multiple columns
+ ** if it is the RHS of a row-value IN operator.
+ */
+ case SRT_Mem: {
+ if( pParse->nErr==0 ){
+ testcase( pIn->nSdst>1 );
+ sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
+ }
+ /* The LIMIT clause will jump out of the loop for us */
+ break;
+ }
+#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
+
+ /* The results are stored in a sequence of registers
+ ** starting at pDest->iSdst. Then the co-routine yields.
+ */
+ case SRT_Coroutine: {
+ if( pDest->iSdst==0 ){
+ pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
+ pDest->nSdst = pIn->nSdst;
+ }
+ sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
+ sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
+ break;
+ }
+
+ /* If none of the above, then the result destination must be
+ ** SRT_Output. This routine is never called with any other
+ ** destination other than the ones handled above or SRT_Output.
+ **
+ ** For SRT_Output, results are stored in a sequence of registers.
+ ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
+ ** return the next row of result.
+ */
+ default: {
+ assert( pDest->eDest==SRT_Output );
+ sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
+ break;
+ }
+ }
+
+ /* Jump to the end of the loop if the LIMIT is reached.
+ */
+ if( p->iLimit ){
+ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
+ }
+
+ /* Generate the subroutine return
+ */
+ sqlite3VdbeResolveLabel(v, iContinue);
+ sqlite3VdbeAddOp1(v, OP_Return, regReturn);
+
+ return addr;
+}
+
+/*
+** Alternative compound select code generator for cases when there
+** is an ORDER BY clause.
+**
+** We assume a query of the following form:
+**
+** <selectA> <operator> <selectB> ORDER BY <orderbylist>
+**
+** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
+** is to code both <selectA> and <selectB> with the ORDER BY clause as
+** co-routines. Then run the co-routines in parallel and merge the results
+** into the output. In addition to the two coroutines (called selectA and
+** selectB) there are 7 subroutines:
+**
+** outA: Move the output of the selectA coroutine into the output
+** of the compound query.
+**
+** outB: Move the output of the selectB coroutine into the output
+** of the compound query. (Only generated for UNION and
+** UNION ALL. EXCEPT and INSERTSECT never output a row that
+** appears only in B.)
+**
+** AltB: Called when there is data from both coroutines and A<B.
+**
+** AeqB: Called when there is data from both coroutines and A==B.
+**
+** AgtB: Called when there is data from both coroutines and A>B.
+**
+** EofA: Called when data is exhausted from selectA.
+**
+** EofB: Called when data is exhausted from selectB.
+**
+** The implementation of the latter five subroutines depend on which
+** <operator> is used:
+**
+**
+** UNION ALL UNION EXCEPT INTERSECT
+** ------------- ----------------- -------------- -----------------
+** AltB: outA, nextA outA, nextA outA, nextA nextA
+**
+** AeqB: outA, nextA nextA nextA outA, nextA
+**
+** AgtB: outB, nextB outB, nextB nextB nextB
+**
+** EofA: outB, nextB outB, nextB halt halt
+**
+** EofB: outA, nextA outA, nextA outA, nextA halt
+**
+** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
+** causes an immediate jump to EofA and an EOF on B following nextB causes
+** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
+** following nextX causes a jump to the end of the select processing.
+**
+** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
+** within the output subroutine. The regPrev register set holds the previously
+** output value. A comparison is made against this value and the output
+** is skipped if the next results would be the same as the previous.
+**
+** The implementation plan is to implement the two coroutines and seven
+** subroutines first, then put the control logic at the bottom. Like this:
+**
+** goto Init
+** coA: coroutine for left query (A)
+** coB: coroutine for right query (B)
+** outA: output one row of A
+** outB: output one row of B (UNION and UNION ALL only)
+** EofA: ...
+** EofB: ...
+** AltB: ...
+** AeqB: ...
+** AgtB: ...
+** Init: initialize coroutine registers
+** yield coA
+** if eof(A) goto EofA
+** yield coB
+** if eof(B) goto EofB
+** Cmpr: Compare A, B
+** Jump AltB, AeqB, AgtB
+** End: ...
+**
+** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
+** actually called using Gosub and they do not Return. EofA and EofB loop
+** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
+** and AgtB jump to either L2 or to one of EofA or EofB.
+*/
+#ifndef SQLITE_OMIT_COMPOUND_SELECT
+static int multiSelectOrderBy(
+ Parse *pParse, /* Parsing context */
+ Select *p, /* The right-most of SELECTs to be coded */
+ SelectDest *pDest /* What to do with query results */
+){
+ int i, j; /* Loop counters */
+ Select *pPrior; /* Another SELECT immediately to our left */
+ Vdbe *v; /* Generate code to this VDBE */
+ SelectDest destA; /* Destination for coroutine A */
+ SelectDest destB; /* Destination for coroutine B */
+ int regAddrA; /* Address register for select-A coroutine */
+ int regAddrB; /* Address register for select-B coroutine */
+ int addrSelectA; /* Address of the select-A coroutine */
+ int addrSelectB; /* Address of the select-B coroutine */
+ int regOutA; /* Address register for the output-A subroutine */
+ int regOutB; /* Address register for the output-B subroutine */
+ int addrOutA; /* Address of the output-A subroutine */
+ int addrOutB = 0; /* Address of the output-B subroutine */
+ int addrEofA; /* Address of the select-A-exhausted subroutine */
+ int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
+ int addrEofB; /* Address of the select-B-exhausted subroutine */
+ int addrAltB; /* Address of the A<B subroutine */
+ int addrAeqB; /* Address of the A==B subroutine */
+ int addrAgtB; /* Address of the A>B subroutine */
+ int regLimitA; /* Limit register for select-A */
+ int regLimitB; /* Limit register for select-A */
+ int regPrev; /* A range of registers to hold previous output */
+ int savedLimit; /* Saved value of p->iLimit */
+ int savedOffset; /* Saved value of p->iOffset */
+ int labelCmpr; /* Label for the start of the merge algorithm */
+ int labelEnd; /* Label for the end of the overall SELECT stmt */
+ int addr1; /* Jump instructions that get retargetted */
+ int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
+ KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
+ KeyInfo *pKeyMerge; /* Comparison information for merging rows */
+ sqlite3 *db; /* Database connection */
+ ExprList *pOrderBy; /* The ORDER BY clause */
+ int nOrderBy; /* Number of terms in the ORDER BY clause */
+ u32 *aPermute; /* Mapping from ORDER BY terms to result set columns */
+
+ assert( p->pOrderBy!=0 );
+ assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
+ db = pParse->db;
+ v = pParse->pVdbe;
+ assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
+ labelEnd = sqlite3VdbeMakeLabel(pParse);
+ labelCmpr = sqlite3VdbeMakeLabel(pParse);
+
+
+ /* Patch up the ORDER BY clause
+ */
+ op = p->op;
+ pPrior = p->pPrior;
+ assert( pPrior->pOrderBy==0 );
+ pOrderBy = p->pOrderBy;
+ assert( pOrderBy );
+ nOrderBy = pOrderBy->nExpr;
+
+ /* For operators other than UNION ALL we have to make sure that
+ ** the ORDER BY clause covers every term of the result set. Add
+ ** terms to the ORDER BY clause as necessary.
+ */
+ if( op!=TK_ALL ){
+ for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
+ struct ExprList_item *pItem;
+ for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
+ assert( pItem->u.x.iOrderByCol>0 );
+ if( pItem->u.x.iOrderByCol==i ) break;
+ }
+ if( j==nOrderBy ){
+ Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
+ if( pNew==0 ) return SQLITE_NOMEM_BKPT;
+ pNew->flags |= EP_IntValue;
+ pNew->u.iValue = i;
+ p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
+ if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
+ }
+ }
+ }
+
+ /* Compute the comparison permutation and keyinfo that is used with
+ ** the permutation used to determine if the next
+ ** row of results comes from selectA or selectB. Also add explicit
+ ** collations to the ORDER BY clause terms so that when the subqueries
+ ** to the right and the left are evaluated, they use the correct
+ ** collation.
+ */
+ aPermute = sqlite3DbMallocRawNN(db, sizeof(u32)*(nOrderBy + 1));
+ if( aPermute ){
+ struct ExprList_item *pItem;
+ aPermute[0] = nOrderBy;
+ for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
+ assert( pItem->u.x.iOrderByCol>0 );
+ assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
+ aPermute[i] = pItem->u.x.iOrderByCol - 1;
+ }
+ pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
+ }else{
+ pKeyMerge = 0;
+ }
+
+ /* Reattach the ORDER BY clause to the query.
+ */
+ p->pOrderBy = pOrderBy;
+ pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
+
+ /* Allocate a range of temporary registers and the KeyInfo needed
+ ** for the logic that removes duplicate result rows when the
+ ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
+ */
+ if( op==TK_ALL ){
+ regPrev = 0;
+ }else{
+ int nExpr = p->pEList->nExpr;
+ assert( nOrderBy>=nExpr || db->mallocFailed );
+ regPrev = pParse->nMem+1;
+ pParse->nMem += nExpr+1;
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
+ pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
+ if( pKeyDup ){
+ assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
+ for(i=0; i<nExpr; i++){
+ pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
+ pKeyDup->aSortFlags[i] = 0;
+ }
+ }
+ }
+
+ /* Separate the left and the right query from one another
+ */
+ p->pPrior = 0;
+ pPrior->pNext = 0;
+ sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
+ if( pPrior->pPrior==0 ){
+ sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
+ }
+
+ /* Compute the limit registers */
+ computeLimitRegisters(pParse, p, labelEnd);
+ if( p->iLimit && op==TK_ALL ){
+ regLimitA = ++pParse->nMem;
+ regLimitB = ++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
+ regLimitA);
+ sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
+ }else{
+ regLimitA = regLimitB = 0;
+ }
+ sqlite3ExprDelete(db, p->pLimit);
+ p->pLimit = 0;
+
+ regAddrA = ++pParse->nMem;
+ regAddrB = ++pParse->nMem;
+ regOutA = ++pParse->nMem;
+ regOutB = ++pParse->nMem;
+ sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
+ sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
+
+ ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op)));
+
+ /* Generate a coroutine to evaluate the SELECT statement to the
+ ** left of the compound operator - the "A" select.
+ */
+ addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
+ addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
+ VdbeComment((v, "left SELECT"));
+ pPrior->iLimit = regLimitA;
+ ExplainQueryPlan((pParse, 1, "LEFT"));
+ sqlite3Select(pParse, pPrior, &destA);
+ sqlite3VdbeEndCoroutine(v, regAddrA);
+ sqlite3VdbeJumpHere(v, addr1);
+
+ /* Generate a coroutine to evaluate the SELECT statement on
+ ** the right - the "B" select
+ */
+ addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
+ addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
+ VdbeComment((v, "right SELECT"));
+ savedLimit = p->iLimit;
+ savedOffset = p->iOffset;
+ p->iLimit = regLimitB;
+ p->iOffset = 0;
+ ExplainQueryPlan((pParse, 1, "RIGHT"));
+ sqlite3Select(pParse, p, &destB);
+ p->iLimit = savedLimit;
+ p->iOffset = savedOffset;
+ sqlite3VdbeEndCoroutine(v, regAddrB);
+
+ /* Generate a subroutine that outputs the current row of the A
+ ** select as the next output row of the compound select.
+ */
+ VdbeNoopComment((v, "Output routine for A"));
+ addrOutA = generateOutputSubroutine(pParse,
+ p, &destA, pDest, regOutA,
+ regPrev, pKeyDup, labelEnd);
+
+ /* Generate a subroutine that outputs the current row of the B
+ ** select as the next output row of the compound select.
+ */
+ if( op==TK_ALL || op==TK_UNION ){
+ VdbeNoopComment((v, "Output routine for B"));
+ addrOutB = generateOutputSubroutine(pParse,
+ p, &destB, pDest, regOutB,
+ regPrev, pKeyDup, labelEnd);
+ }
+ sqlite3KeyInfoUnref(pKeyDup);
+
+ /* Generate a subroutine to run when the results from select A
+ ** are exhausted and only data in select B remains.
+ */
+ if( op==TK_EXCEPT || op==TK_INTERSECT ){
+ addrEofA_noB = addrEofA = labelEnd;
+ }else{
+ VdbeNoopComment((v, "eof-A subroutine"));
+ addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
+ addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
+ VdbeCoverage(v);
+ sqlite3VdbeGoto(v, addrEofA);
+ p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
+ }
+
+ /* Generate a subroutine to run when the results from select B
+ ** are exhausted and only data in select A remains.
+ */
+ if( op==TK_INTERSECT ){
+ addrEofB = addrEofA;
+ if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
+ }else{
+ VdbeNoopComment((v, "eof-B subroutine"));
+ addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
+ sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
+ sqlite3VdbeGoto(v, addrEofB);
+ }
+
+ /* Generate code to handle the case of A<B
+ */
+ VdbeNoopComment((v, "A-lt-B subroutine"));
+ addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
+ sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
+ sqlite3VdbeGoto(v, labelCmpr);
+
+ /* Generate code to handle the case of A==B
+ */
+ if( op==TK_ALL ){
+ addrAeqB = addrAltB;
+ }else if( op==TK_INTERSECT ){
+ addrAeqB = addrAltB;
+ addrAltB++;
+ }else{
+ VdbeNoopComment((v, "A-eq-B subroutine"));
+ addrAeqB =
+ sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
+ sqlite3VdbeGoto(v, labelCmpr);
+ }
+
+ /* Generate code to handle the case of A>B
+ */
+ VdbeNoopComment((v, "A-gt-B subroutine"));
+ addrAgtB = sqlite3VdbeCurrentAddr(v);
+ if( op==TK_ALL || op==TK_UNION ){
+ sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
+ }
+ sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
+ sqlite3VdbeGoto(v, labelCmpr);
+
+ /* This code runs once to initialize everything.
+ */
+ sqlite3VdbeJumpHere(v, addr1);
+ sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
+ sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
+
+ /* Implement the main merge loop
+ */
+ sqlite3VdbeResolveLabel(v, labelCmpr);
+ sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
+ sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
+ (char*)pKeyMerge, P4_KEYINFO);
+ sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
+ sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
+
+ /* Jump to the this point in order to terminate the query.
+ */
+ sqlite3VdbeResolveLabel(v, labelEnd);
+
+ /* Reassembly the compound query so that it will be freed correctly
+ ** by the calling function */
+ if( p->pPrior ){
+ sqlite3SelectDelete(db, p->pPrior);
+ }
+ p->pPrior = pPrior;
+ pPrior->pNext = p;
+
+ /*** TBD: Insert subroutine calls to close cursors on incomplete
+ **** subqueries ****/
+ ExplainQueryPlanPop(pParse);
+ return pParse->nErr!=0;
+}
+#endif
+
+#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
+
+/* An instance of the SubstContext object describes an substitution edit
+** to be performed on a parse tree.
+**
+** All references to columns in table iTable are to be replaced by corresponding
+** expressions in pEList.
+*/
+typedef struct SubstContext {
+ Parse *pParse; /* The parsing context */
+ int iTable; /* Replace references to this table */
+ int iNewTable; /* New table number */
+ int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
+ ExprList *pEList; /* Replacement expressions */
+} SubstContext;
+
+/* Forward Declarations */
+static void substExprList(SubstContext*, ExprList*);
+static void substSelect(SubstContext*, Select*, int);
+
+/*
+** Scan through the expression pExpr. Replace every reference to
+** a column in table number iTable with a copy of the iColumn-th
+** entry in pEList. (But leave references to the ROWID column
+** unchanged.)
+**
+** This routine is part of the flattening procedure. A subquery
+** whose result set is defined by pEList appears as entry in the
+** FROM clause of a SELECT such that the VDBE cursor assigned to that
+** FORM clause entry is iTable. This routine makes the necessary
+** changes to pExpr so that it refers directly to the source table
+** of the subquery rather the result set of the subquery.
+*/
+static Expr *substExpr(
+ SubstContext *pSubst, /* Description of the substitution */
+ Expr *pExpr /* Expr in which substitution occurs */
+){
+ if( pExpr==0 ) return 0;
+ if( ExprHasProperty(pExpr, EP_FromJoin)
+ && pExpr->iRightJoinTable==pSubst->iTable
+ ){
+ pExpr->iRightJoinTable = pSubst->iNewTable;
+ }
+ if( pExpr->op==TK_COLUMN
+ && pExpr->iTable==pSubst->iTable
+ && !ExprHasProperty(pExpr, EP_FixedCol)
+ ){
+ if( pExpr->iColumn<0 ){
+ pExpr->op = TK_NULL;
+ }else{
+ Expr *pNew;
+ Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
+ Expr ifNullRow;
+ assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
+ assert( pExpr->pRight==0 );
+ if( sqlite3ExprIsVector(pCopy) ){
+ sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
+ }else{
+ sqlite3 *db = pSubst->pParse->db;
+ if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
+ memset(&ifNullRow, 0, sizeof(ifNullRow));
+ ifNullRow.op = TK_IF_NULL_ROW;
+ ifNullRow.pLeft = pCopy;
+ ifNullRow.iTable = pSubst->iNewTable;
+ ifNullRow.flags = EP_IfNullRow;
+ pCopy = &ifNullRow;
+ }
+ testcase( ExprHasProperty(pCopy, EP_Subquery) );
+ pNew = sqlite3ExprDup(db, pCopy, 0);
+ if( pNew && pSubst->isLeftJoin ){
+ ExprSetProperty(pNew, EP_CanBeNull);
+ }
+ if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
+ sqlite3SetJoinExpr(pNew, pExpr->iRightJoinTable);
+ }
+ sqlite3ExprDelete(db, pExpr);
+ pExpr = pNew;
+
+ /* Ensure that the expression now has an implicit collation sequence,
+ ** just as it did when it was a column of a view or sub-query. */
+ if( pExpr ){
+ if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE ){
+ CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse, pExpr);
+ pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr,
+ (pColl ? pColl->zName : "BINARY")
+ );
+ }
+ ExprClearProperty(pExpr, EP_Collate);
+ }
+ }
+ }
+ }else{
+ if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
+ pExpr->iTable = pSubst->iNewTable;
+ }
+ pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
+ pExpr->pRight = substExpr(pSubst, pExpr->pRight);
+ if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+ substSelect(pSubst, pExpr->x.pSelect, 1);
+ }else{
+ substExprList(pSubst, pExpr->x.pList);
+ }
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( ExprHasProperty(pExpr, EP_WinFunc) ){
+ Window *pWin = pExpr->y.pWin;
+ pWin->pFilter = substExpr(pSubst, pWin->pFilter);
+ substExprList(pSubst, pWin->pPartition);
+ substExprList(pSubst, pWin->pOrderBy);
+ }
+#endif
+ }
+ return pExpr;
+}
+static void substExprList(
+ SubstContext *pSubst, /* Description of the substitution */
+ ExprList *pList /* List to scan and in which to make substitutes */
+){
+ int i;
+ if( pList==0 ) return;
+ for(i=0; i<pList->nExpr; i++){
+ pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
+ }
+}
+static void substSelect(
+ SubstContext *pSubst, /* Description of the substitution */
+ Select *p, /* SELECT statement in which to make substitutions */
+ int doPrior /* Do substitutes on p->pPrior too */
+){
+ SrcList *pSrc;
+ struct SrcList_item *pItem;
+ int i;
+ if( !p ) return;
+ do{
+ substExprList(pSubst, p->pEList);
+ substExprList(pSubst, p->pGroupBy);
+ substExprList(pSubst, p->pOrderBy);
+ p->pHaving = substExpr(pSubst, p->pHaving);
+ p->pWhere = substExpr(pSubst, p->pWhere);
+ pSrc = p->pSrc;
+ assert( pSrc!=0 );
+ for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
+ substSelect(pSubst, pItem->pSelect, 1);
+ if( pItem->fg.isTabFunc ){
+ substExprList(pSubst, pItem->u1.pFuncArg);
+ }
+ }
+ }while( doPrior && (p = p->pPrior)!=0 );
+}
+#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
+
+#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
+/*
+** pSelect is a SELECT statement and pSrcItem is one item in the FROM
+** clause of that SELECT.
+**
+** This routine scans the entire SELECT statement and recomputes the
+** pSrcItem->colUsed mask.
+*/
+static int recomputeColumnsUsedExpr(Walker *pWalker, Expr *pExpr){
+ struct SrcList_item *pItem;
+ if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
+ pItem = pWalker->u.pSrcItem;
+ if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue;
+ if( pExpr->iColumn<0 ) return WRC_Continue;
+ pItem->colUsed |= sqlite3ExprColUsed(pExpr);
+ return WRC_Continue;
+}
+static void recomputeColumnsUsed(
+ Select *pSelect, /* The complete SELECT statement */
+ struct SrcList_item *pSrcItem /* Which FROM clause item to recompute */
+){
+ Walker w;
+ if( NEVER(pSrcItem->pTab==0) ) return;
+ memset(&w, 0, sizeof(w));
+ w.xExprCallback = recomputeColumnsUsedExpr;
+ w.xSelectCallback = sqlite3SelectWalkNoop;
+ w.u.pSrcItem = pSrcItem;
+ pSrcItem->colUsed = 0;
+ sqlite3WalkSelect(&w, pSelect);
+}
+#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
+
+#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
+/*
+** This routine attempts to flatten subqueries as a performance optimization.
+** This routine returns 1 if it makes changes and 0 if no flattening occurs.
+**
+** To understand the concept of flattening, consider the following
+** query:
+**
+** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
+**
+** The default way of implementing this query is to execute the
+** subquery first and store the results in a temporary table, then
+** run the outer query on that temporary table. This requires two
+** passes over the data. Furthermore, because the temporary table
+** has no indices, the WHERE clause on the outer query cannot be
+** optimized.
+**
+** This routine attempts to rewrite queries such as the above into
+** a single flat select, like this:
+**
+** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
+**
+** The code generated for this simplification gives the same result
+** but only has to scan the data once. And because indices might
+** exist on the table t1, a complete scan of the data might be
+** avoided.
+**
+** Flattening is subject to the following constraints:
+**
+** (**) We no longer attempt to flatten aggregate subqueries. Was:
+** The subquery and the outer query cannot both be aggregates.
+**
+** (**) We no longer attempt to flatten aggregate subqueries. Was:
+** (2) If the subquery is an aggregate then
+** (2a) the outer query must not be a join and
+** (2b) the outer query must not use subqueries
+** other than the one FROM-clause subquery that is a candidate
+** for flattening. (This is due to ticket [2f7170d73bf9abf80]
+** from 2015-02-09.)
+**
+** (3) If the subquery is the right operand of a LEFT JOIN then
+** (3a) the subquery may not be a join and
+** (3b) the FROM clause of the subquery may not contain a virtual
+** table and
+** (3c) the outer query may not be an aggregate.
+** (3d) the outer query may not be DISTINCT.
+**
+** (4) The subquery can not be DISTINCT.
+**
+** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
+** sub-queries that were excluded from this optimization. Restriction
+** (4) has since been expanded to exclude all DISTINCT subqueries.
+**
+** (**) We no longer attempt to flatten aggregate subqueries. Was:
+** If the subquery is aggregate, the outer query may not be DISTINCT.
+**
+** (7) The subquery must have a FROM clause. TODO: For subqueries without
+** A FROM clause, consider adding a FROM clause with the special
+** table sqlite_once that consists of a single row containing a
+** single NULL.
+**
+** (8) If the subquery uses LIMIT then the outer query may not be a join.
+**
+** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
+**
+** (**) Restriction (10) was removed from the code on 2005-02-05 but we
+** accidently carried the comment forward until 2014-09-15. Original
+** constraint: "If the subquery is aggregate then the outer query
+** may not use LIMIT."
+**
+** (11) The subquery and the outer query may not both have ORDER BY clauses.
+**
+** (**) Not implemented. Subsumed into restriction (3). Was previously
+** a separate restriction deriving from ticket #350.
+**
+** (13) The subquery and outer query may not both use LIMIT.
+**
+** (14) The subquery may not use OFFSET.
+**
+** (15) If the outer query is part of a compound select, then the
+** subquery may not use LIMIT.
+** (See ticket #2339 and ticket [02a8e81d44]).
+**
+** (16) If the outer query is aggregate, then the subquery may not
+** use ORDER BY. (Ticket #2942) This used to not matter
+** until we introduced the group_concat() function.
+**
+** (17) If the subquery is a compound select, then
+** (17a) all compound operators must be a UNION ALL, and
+** (17b) no terms within the subquery compound may be aggregate
+** or DISTINCT, and
+** (17c) every term within the subquery compound must have a FROM clause
+** (17d) the outer query may not be
+** (17d1) aggregate, or
+** (17d2) DISTINCT, or
+** (17d3) a join.
+** (17e) the subquery may not contain window functions
+**
+** The parent and sub-query may contain WHERE clauses. Subject to
+** rules (11), (13) and (14), they may also contain ORDER BY,
+** LIMIT and OFFSET clauses. The subquery cannot use any compound
+** operator other than UNION ALL because all the other compound
+** operators have an implied DISTINCT which is disallowed by
+** restriction (4).
+**
+** Also, each component of the sub-query must return the same number
+** of result columns. This is actually a requirement for any compound
+** SELECT statement, but all the code here does is make sure that no
+** such (illegal) sub-query is flattened. The caller will detect the
+** syntax error and return a detailed message.
+**
+** (18) If the sub-query is a compound select, then all terms of the
+** ORDER BY clause of the parent must be simple references to
+** columns of the sub-query.
+**
+** (19) If the subquery uses LIMIT then the outer query may not
+** have a WHERE clause.
+**
+** (20) If the sub-query is a compound select, then it must not use
+** an ORDER BY clause. Ticket #3773. We could relax this constraint
+** somewhat by saying that the terms of the ORDER BY clause must
+** appear as unmodified result columns in the outer query. But we
+** have other optimizations in mind to deal with that case.
+**
+** (21) If the subquery uses LIMIT then the outer query may not be
+** DISTINCT. (See ticket [752e1646fc]).
+**
+** (22) The subquery may not be a recursive CTE.
+**
+** (**) Subsumed into restriction (17d3). Was: If the outer query is
+** a recursive CTE, then the sub-query may not be a compound query.
+** This restriction is because transforming the
+** parent to a compound query confuses the code that handles
+** recursive queries in multiSelect().
+**
+** (**) We no longer attempt to flatten aggregate subqueries. Was:
+** The subquery may not be an aggregate that uses the built-in min() or
+** or max() functions. (Without this restriction, a query like:
+** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
+** return the value X for which Y was maximal.)
+**
+** (25) If either the subquery or the parent query contains a window
+** function in the select list or ORDER BY clause, flattening
+** is not attempted.
+**
+**
+** In this routine, the "p" parameter is a pointer to the outer query.
+** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
+** uses aggregates.
+**
+** If flattening is not attempted, this routine is a no-op and returns 0.
+** If flattening is attempted this routine returns 1.
+**
+** All of the expression analysis must occur on both the outer query and
+** the subquery before this routine runs.
+*/
+static int flattenSubquery(
+ Parse *pParse, /* Parsing context */
+ Select *p, /* The parent or outer SELECT statement */
+ int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
+ int isAgg /* True if outer SELECT uses aggregate functions */
+){
+ const char *zSavedAuthContext = pParse->zAuthContext;
+ Select *pParent; /* Current UNION ALL term of the other query */
+ Select *pSub; /* The inner query or "subquery" */
+ Select *pSub1; /* Pointer to the rightmost select in sub-query */
+ SrcList *pSrc; /* The FROM clause of the outer query */
+ SrcList *pSubSrc; /* The FROM clause of the subquery */
+ int iParent; /* VDBE cursor number of the pSub result set temp table */
+ int iNewParent = -1;/* Replacement table for iParent */
+ int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
+ int i; /* Loop counter */
+ Expr *pWhere; /* The WHERE clause */
+ struct SrcList_item *pSubitem; /* The subquery */
+ sqlite3 *db = pParse->db;
+ Walker w; /* Walker to persist agginfo data */
+
+ /* Check to see if flattening is permitted. Return 0 if not.
+ */
+ assert( p!=0 );
+ assert( p->pPrior==0 );
+ if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
+ pSrc = p->pSrc;
+ assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
+ pSubitem = &pSrc->a[iFrom];
+ iParent = pSubitem->iCursor;
+ pSub = pSubitem->pSelect;
+ assert( pSub!=0 );
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
+#endif
+
+ pSubSrc = pSub->pSrc;
+ assert( pSubSrc );
+ /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
+ ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
+ ** because they could be computed at compile-time. But when LIMIT and OFFSET
+ ** became arbitrary expressions, we were forced to add restrictions (13)
+ ** and (14). */
+ if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
+ if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
+ if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
+ return 0; /* Restriction (15) */
+ }
+ if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
+ if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
+ if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
+ return 0; /* Restrictions (8)(9) */
+ }
+ if( p->pOrderBy && pSub->pOrderBy ){
+ return 0; /* Restriction (11) */
+ }
+ if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
+ if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
+ if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
+ return 0; /* Restriction (21) */
+ }
+ if( pSub->selFlags & (SF_Recursive) ){
+ return 0; /* Restrictions (22) */
+ }
+
+ /*
+ ** If the subquery is the right operand of a LEFT JOIN, then the
+ ** subquery may not be a join itself (3a). Example of why this is not
+ ** allowed:
+ **
+ ** t1 LEFT OUTER JOIN (t2 JOIN t3)
+ **
+ ** If we flatten the above, we would get
+ **
+ ** (t1 LEFT OUTER JOIN t2) JOIN t3
+ **
+ ** which is not at all the same thing.
+ **
+ ** If the subquery is the right operand of a LEFT JOIN, then the outer
+ ** query cannot be an aggregate. (3c) This is an artifact of the way
+ ** aggregates are processed - there is no mechanism to determine if
+ ** the LEFT JOIN table should be all-NULL.
+ **
+ ** See also tickets #306, #350, and #3300.
+ */
+ if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
+ isLeftJoin = 1;
+ if( pSubSrc->nSrc>1 /* (3a) */
+ || isAgg /* (3b) */
+ || IsVirtual(pSubSrc->a[0].pTab) /* (3c) */
+ || (p->selFlags & SF_Distinct)!=0 /* (3d) */
+ ){
+ return 0;
+ }
+ }
+#ifdef SQLITE_EXTRA_IFNULLROW
+ else if( iFrom>0 && !isAgg ){
+ /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
+ ** every reference to any result column from subquery in a join, even
+ ** though they are not necessary. This will stress-test the OP_IfNullRow
+ ** opcode. */
+ isLeftJoin = -1;
+ }
+#endif
+
+ /* Restriction (17): If the sub-query is a compound SELECT, then it must
+ ** use only the UNION ALL operator. And none of the simple select queries
+ ** that make up the compound SELECT are allowed to be aggregate or distinct
+ ** queries.
+ */
+ if( pSub->pPrior ){
+ if( pSub->pOrderBy ){
+ return 0; /* Restriction (20) */
+ }
+ if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
+ return 0; /* (17d1), (17d2), or (17d3) */
+ }
+ for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
+ testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
+ testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
+ assert( pSub->pSrc!=0 );
+ assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
+ if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
+ || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
+ || pSub1->pSrc->nSrc<1 /* (17c) */
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ || pSub1->pWin /* (17e) */
+#endif
+ ){
+ return 0;
+ }
+ testcase( pSub1->pSrc->nSrc>1 );
+ }
+
+ /* Restriction (18). */
+ if( p->pOrderBy ){
+ int ii;
+ for(ii=0; ii<p->pOrderBy->nExpr; ii++){
+ if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
+ }
+ }
+ }
+
+ /* Ex-restriction (23):
+ ** The only way that the recursive part of a CTE can contain a compound
+ ** subquery is for the subquery to be one term of a join. But if the
+ ** subquery is a join, then the flattening has already been stopped by
+ ** restriction (17d3)
+ */
+ assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
+
+ /***** If we reach this point, flattening is permitted. *****/
+ SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n",
+ pSub->selId, pSub, iFrom));
+
+ /* Authorize the subquery */
+ pParse->zAuthContext = pSubitem->zName;
+ TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
+ testcase( i==SQLITE_DENY );
+ pParse->zAuthContext = zSavedAuthContext;
+
+ /* If the sub-query is a compound SELECT statement, then (by restrictions
+ ** 17 and 18 above) it must be a UNION ALL and the parent query must
+ ** be of the form:
+ **
+ ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
+ **
+ ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
+ ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
+ ** OFFSET clauses and joins them to the left-hand-side of the original
+ ** using UNION ALL operators. In this case N is the number of simple
+ ** select statements in the compound sub-query.
+ **
+ ** Example:
+ **
+ ** SELECT a+1 FROM (
+ ** SELECT x FROM tab
+ ** UNION ALL
+ ** SELECT y FROM tab
+ ** UNION ALL
+ ** SELECT abs(z*2) FROM tab2
+ ** ) WHERE a!=5 ORDER BY 1
+ **
+ ** Transformed into:
+ **
+ ** SELECT x+1 FROM tab WHERE x+1!=5
+ ** UNION ALL
+ ** SELECT y+1 FROM tab WHERE y+1!=5
+ ** UNION ALL
+ ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
+ ** ORDER BY 1
+ **
+ ** We call this the "compound-subquery flattening".
+ */
+ for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
+ Select *pNew;
+ ExprList *pOrderBy = p->pOrderBy;
+ Expr *pLimit = p->pLimit;
+ Select *pPrior = p->pPrior;
+ p->pOrderBy = 0;
+ p->pSrc = 0;
+ p->pPrior = 0;
+ p->pLimit = 0;
+ pNew = sqlite3SelectDup(db, p, 0);
+ p->pLimit = pLimit;
+ p->pOrderBy = pOrderBy;
+ p->pSrc = pSrc;
+ p->op = TK_ALL;
+ if( pNew==0 ){
+ p->pPrior = pPrior;
+ }else{
+ pNew->pPrior = pPrior;
+ if( pPrior ) pPrior->pNext = pNew;
+ pNew->pNext = p;
+ p->pPrior = pNew;
+ SELECTTRACE(2,pParse,p,("compound-subquery flattener"
+ " creates %u as peer\n",pNew->selId));
+ }
+ if( db->mallocFailed ) return 1;
+ }
+
+ /* Begin flattening the iFrom-th entry of the FROM clause
+ ** in the outer query.
+ */
+ pSub = pSub1 = pSubitem->pSelect;
+
+ /* Delete the transient table structure associated with the
+ ** subquery
+ */
+ sqlite3DbFree(db, pSubitem->zDatabase);
+ sqlite3DbFree(db, pSubitem->zName);
+ sqlite3DbFree(db, pSubitem->zAlias);
+ pSubitem->zDatabase = 0;
+ pSubitem->zName = 0;
+ pSubitem->zAlias = 0;
+ pSubitem->pSelect = 0;
+
+ /* Defer deleting the Table object associated with the
+ ** subquery until code generation is
+ ** complete, since there may still exist Expr.pTab entries that
+ ** refer to the subquery even after flattening. Ticket #3346.
+ **
+ ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
+ */
+ if( ALWAYS(pSubitem->pTab!=0) ){
+ Table *pTabToDel = pSubitem->pTab;
+ if( pTabToDel->nTabRef==1 ){
+ Parse *pToplevel = sqlite3ParseToplevel(pParse);
+ pTabToDel->pNextZombie = pToplevel->pZombieTab;
+ pToplevel->pZombieTab = pTabToDel;
+ }else{
+ pTabToDel->nTabRef--;
+ }
+ pSubitem->pTab = 0;
+ }
+
+ /* The following loop runs once for each term in a compound-subquery
+ ** flattening (as described above). If we are doing a different kind
+ ** of flattening - a flattening other than a compound-subquery flattening -
+ ** then this loop only runs once.
+ **
+ ** This loop moves all of the FROM elements of the subquery into the
+ ** the FROM clause of the outer query. Before doing this, remember
+ ** the cursor number for the original outer query FROM element in
+ ** iParent. The iParent cursor will never be used. Subsequent code
+ ** will scan expressions looking for iParent references and replace
+ ** those references with expressions that resolve to the subquery FROM
+ ** elements we are now copying in.
+ */
+ for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
+ int nSubSrc;
+ u8 jointype = 0;
+ assert( pSub!=0 );
+ pSubSrc = pSub->pSrc; /* FROM clause of subquery */
+ nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
+ pSrc = pParent->pSrc; /* FROM clause of the outer query */
+
+ if( pSrc ){
+ assert( pParent==p ); /* First time through the loop */
+ jointype = pSubitem->fg.jointype;
+ }else{
+ assert( pParent!=p ); /* 2nd and subsequent times through the loop */
+ pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
+ if( pSrc==0 ) break;
+ pParent->pSrc = pSrc;
+ }
+
+ /* The subquery uses a single slot of the FROM clause of the outer
+ ** query. If the subquery has more than one element in its FROM clause,
+ ** then expand the outer query to make space for it to hold all elements
+ ** of the subquery.
+ **
+ ** Example:
+ **
+ ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
+ **
+ ** The outer query has 3 slots in its FROM clause. One slot of the
+ ** outer query (the middle slot) is used by the subquery. The next
+ ** block of code will expand the outer query FROM clause to 4 slots.
+ ** The middle slot is expanded to two slots in order to make space
+ ** for the two elements in the FROM clause of the subquery.
+ */
+ if( nSubSrc>1 ){
+ pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
+ if( pSrc==0 ) break;
+ pParent->pSrc = pSrc;
+ }
+
+ /* Transfer the FROM clause terms from the subquery into the
+ ** outer query.
+ */
+ for(i=0; i<nSubSrc; i++){
+ sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
+ assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
+ pSrc->a[i+iFrom] = pSubSrc->a[i];
+ iNewParent = pSubSrc->a[i].iCursor;
+ memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
+ }
+ pSrc->a[iFrom].fg.jointype = jointype;
+
+ /* Now begin substituting subquery result set expressions for
+ ** references to the iParent in the outer query.
+ **
+ ** Example:
+ **
+ ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
+ ** \ \_____________ subquery __________/ /
+ ** \_____________________ outer query ______________________________/
+ **
+ ** We look at every expression in the outer query and every place we see
+ ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
+ */
+ if( pSub->pOrderBy && (pParent->selFlags & SF_NoopOrderBy)==0 ){
+ /* At this point, any non-zero iOrderByCol values indicate that the
+ ** ORDER BY column expression is identical to the iOrderByCol'th
+ ** expression returned by SELECT statement pSub. Since these values
+ ** do not necessarily correspond to columns in SELECT statement pParent,
+ ** zero them before transfering the ORDER BY clause.
+ **
+ ** Not doing this may cause an error if a subsequent call to this
+ ** function attempts to flatten a compound sub-query into pParent
+ ** (the only way this can happen is if the compound sub-query is
+ ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
+ ExprList *pOrderBy = pSub->pOrderBy;
+ for(i=0; i<pOrderBy->nExpr; i++){
+ pOrderBy->a[i].u.x.iOrderByCol = 0;
+ }
+ assert( pParent->pOrderBy==0 );
+ pParent->pOrderBy = pOrderBy;
+ pSub->pOrderBy = 0;
+ }
+ pWhere = pSub->pWhere;
+ pSub->pWhere = 0;
+ if( isLeftJoin>0 ){
+ sqlite3SetJoinExpr(pWhere, iNewParent);
+ }
+ if( pWhere ){
+ if( pParent->pWhere ){
+ pParent->pWhere = sqlite3PExpr(pParse, TK_AND, pWhere, pParent->pWhere);
+ }else{
+ pParent->pWhere = pWhere;
+ }
+ }
+ if( db->mallocFailed==0 ){
+ SubstContext x;
+ x.pParse = pParse;
+ x.iTable = iParent;
+ x.iNewTable = iNewParent;
+ x.isLeftJoin = isLeftJoin;
+ x.pEList = pSub->pEList;
+ substSelect(&x, pParent, 0);
+ }
+
+ /* The flattened query is a compound if either the inner or the
+ ** outer query is a compound. */
+ pParent->selFlags |= pSub->selFlags & SF_Compound;
+ assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
+
+ /*
+ ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
+ **
+ ** One is tempted to try to add a and b to combine the limits. But this
+ ** does not work if either limit is negative.
+ */
+ if( pSub->pLimit ){
+ pParent->pLimit = pSub->pLimit;
+ pSub->pLimit = 0;
+ }
+
+ /* Recompute the SrcList_item.colUsed masks for the flattened
+ ** tables. */
+ for(i=0; i<nSubSrc; i++){
+ recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]);
+ }
+ }
+
+ /* Finially, delete what is left of the subquery and return
+ ** success.
+ */
+ sqlite3AggInfoPersistWalkerInit(&w, pParse);
+ sqlite3WalkSelect(&w,pSub1);
+ sqlite3SelectDelete(db, pSub1);
+
+#if SELECTTRACE_ENABLED
+ if( sqlite3_unsupported_selecttrace & 0x100 ){
+ SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
+ sqlite3TreeViewSelect(0, p, 0);
+ }
+#endif
+
+ return 1;
+}
+#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
+
+/*
+** A structure to keep track of all of the column values that are fixed to
+** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
+*/
+typedef struct WhereConst WhereConst;
+struct WhereConst {
+ Parse *pParse; /* Parsing context */
+ int nConst; /* Number for COLUMN=CONSTANT terms */
+ int nChng; /* Number of times a constant is propagated */
+ Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
+};
+
+/*
+** Add a new entry to the pConst object. Except, do not add duplicate
+** pColumn entires. Also, do not add if doing so would not be appropriate.
+**
+** The caller guarantees the pColumn is a column and pValue is a constant.
+** This routine has to do some additional checks before completing the
+** insert.
+*/
+static void constInsert(
+ WhereConst *pConst, /* The WhereConst into which we are inserting */
+ Expr *pColumn, /* The COLUMN part of the constraint */
+ Expr *pValue, /* The VALUE part of the constraint */
+ Expr *pExpr /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */
+){
+ int i;
+ assert( pColumn->op==TK_COLUMN );
+ assert( sqlite3ExprIsConstant(pValue) );
+
+ if( ExprHasProperty(pColumn, EP_FixedCol) ) return;
+ if( sqlite3ExprAffinity(pValue)!=0 ) return;
+ if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){
+ return;
+ }
+
+ /* 2018-10-25 ticket [cf5ed20f]
+ ** Make sure the same pColumn is not inserted more than once */
+ for(i=0; i<pConst->nConst; i++){
+ const Expr *pE2 = pConst->apExpr[i*2];
+ assert( pE2->op==TK_COLUMN );
+ if( pE2->iTable==pColumn->iTable
+ && pE2->iColumn==pColumn->iColumn
+ ){
+ return; /* Already present. Return without doing anything. */
+ }
+ }
+
+ pConst->nConst++;
+ pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
+ pConst->nConst*2*sizeof(Expr*));
+ if( pConst->apExpr==0 ){
+ pConst->nConst = 0;
+ }else{
+ pConst->apExpr[pConst->nConst*2-2] = pColumn;
+ pConst->apExpr[pConst->nConst*2-1] = pValue;
+ }
+}
+
+/*
+** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
+** is a constant expression and where the term must be true because it
+** is part of the AND-connected terms of the expression. For each term
+** found, add it to the pConst structure.
+*/
+static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
+ Expr *pRight, *pLeft;
+ if( pExpr==0 ) return;
+ if( ExprHasProperty(pExpr, EP_FromJoin) ) return;
+ if( pExpr->op==TK_AND ){
+ findConstInWhere(pConst, pExpr->pRight);
+ findConstInWhere(pConst, pExpr->pLeft);
+ return;
+ }
+ if( pExpr->op!=TK_EQ ) return;
+ pRight = pExpr->pRight;
+ pLeft = pExpr->pLeft;
+ assert( pRight!=0 );
+ assert( pLeft!=0 );
+ if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pLeft) ){
+ constInsert(pConst,pRight,pLeft,pExpr);
+ }
+ if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pRight) ){
+ constInsert(pConst,pLeft,pRight,pExpr);
+ }
+}
+
+/*
+** This is a Walker expression callback. pExpr is a candidate expression
+** to be replaced by a value. If pExpr is equivalent to one of the
+** columns named in pWalker->u.pConst, then overwrite it with its
+** corresponding value.
+*/
+static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
+ int i;
+ WhereConst *pConst;
+ if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
+ if( ExprHasProperty(pExpr, EP_FixedCol|EP_FromJoin) ){
+ testcase( ExprHasProperty(pExpr, EP_FixedCol) );
+ testcase( ExprHasProperty(pExpr, EP_FromJoin) );
+ return WRC_Continue;
+ }
+ pConst = pWalker->u.pConst;
+ for(i=0; i<pConst->nConst; i++){
+ Expr *pColumn = pConst->apExpr[i*2];
+ if( pColumn==pExpr ) continue;
+ if( pColumn->iTable!=pExpr->iTable ) continue;
+ if( pColumn->iColumn!=pExpr->iColumn ) continue;
+ /* A match is found. Add the EP_FixedCol property */
+ pConst->nChng++;
+ ExprClearProperty(pExpr, EP_Leaf);
+ ExprSetProperty(pExpr, EP_FixedCol);
+ assert( pExpr->pLeft==0 );
+ pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
+ break;
+ }
+ return WRC_Prune;
+}
+
+/*
+** The WHERE-clause constant propagation optimization.
+**
+** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
+** CONSTANT=COLUMN that are top-level AND-connected terms that are not
+** part of a ON clause from a LEFT JOIN, then throughout the query
+** replace all other occurrences of COLUMN with CONSTANT.
+**
+** For example, the query:
+**
+** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
+**
+** Is transformed into
+**
+** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
+**
+** Return true if any transformations where made and false if not.
+**
+** Implementation note: Constant propagation is tricky due to affinity
+** and collating sequence interactions. Consider this example:
+**
+** CREATE TABLE t1(a INT,b TEXT);
+** INSERT INTO t1 VALUES(123,'0123');
+** SELECT * FROM t1 WHERE a=123 AND b=a;
+** SELECT * FROM t1 WHERE a=123 AND b=123;
+**
+** The two SELECT statements above should return different answers. b=a
+** is alway true because the comparison uses numeric affinity, but b=123
+** is false because it uses text affinity and '0123' is not the same as '123'.
+** To work around this, the expression tree is not actually changed from
+** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
+** and the "123" value is hung off of the pLeft pointer. Code generator
+** routines know to generate the constant "123" instead of looking up the
+** column value. Also, to avoid collation problems, this optimization is
+** only attempted if the "a=123" term uses the default BINARY collation.
+*/
+static int propagateConstants(
+ Parse *pParse, /* The parsing context */
+ Select *p /* The query in which to propagate constants */
+){
+ WhereConst x;
+ Walker w;
+ int nChng = 0;
+ x.pParse = pParse;
+ do{
+ x.nConst = 0;
+ x.nChng = 0;
+ x.apExpr = 0;
+ findConstInWhere(&x, p->pWhere);
+ if( x.nConst ){
+ memset(&w, 0, sizeof(w));
+ w.pParse = pParse;
+ w.xExprCallback = propagateConstantExprRewrite;
+ w.xSelectCallback = sqlite3SelectWalkNoop;
+ w.xSelectCallback2 = 0;
+ w.walkerDepth = 0;
+ w.u.pConst = &x;
+ sqlite3WalkExpr(&w, p->pWhere);
+ sqlite3DbFree(x.pParse->db, x.apExpr);
+ nChng += x.nChng;
+ }
+ }while( x.nChng );
+ return nChng;
+}
+
+#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
+/*
+** Make copies of relevant WHERE clause terms of the outer query into
+** the WHERE clause of subquery. Example:
+**
+** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
+**
+** Transformed into:
+**
+** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
+** WHERE x=5 AND y=10;
+**
+** The hope is that the terms added to the inner query will make it more
+** efficient.
+**
+** Do not attempt this optimization if:
+**
+** (1) (** This restriction was removed on 2017-09-29. We used to
+** disallow this optimization for aggregate subqueries, but now
+** it is allowed by putting the extra terms on the HAVING clause.
+** The added HAVING clause is pointless if the subquery lacks
+** a GROUP BY clause. But such a HAVING clause is also harmless
+** so there does not appear to be any reason to add extra logic
+** to suppress it. **)
+**
+** (2) The inner query is the recursive part of a common table expression.
+**
+** (3) The inner query has a LIMIT clause (since the changes to the WHERE
+** clause would change the meaning of the LIMIT).
+**
+** (4) The inner query is the right operand of a LEFT JOIN and the
+** expression to be pushed down does not come from the ON clause
+** on that LEFT JOIN.
+**
+** (5) The WHERE clause expression originates in the ON or USING clause
+** of a LEFT JOIN where iCursor is not the right-hand table of that
+** left join. An example:
+**
+** SELECT *
+** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
+** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
+** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
+**
+** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9).
+** But if the (b2=2) term were to be pushed down into the bb subquery,
+** then the (1,1,NULL) row would be suppressed.
+**
+** (6) The inner query features one or more window-functions (since
+** changes to the WHERE clause of the inner query could change the
+** window over which window functions are calculated).
+**
+** Return 0 if no changes are made and non-zero if one or more WHERE clause
+** terms are duplicated into the subquery.
+*/
+static int pushDownWhereTerms(
+ Parse *pParse, /* Parse context (for malloc() and error reporting) */
+ Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
+ Expr *pWhere, /* The WHERE clause of the outer query */
+ int iCursor, /* Cursor number of the subquery */
+ int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */
+){
+ Expr *pNew;
+ int nChng = 0;
+ Select *pSel;
+ if( pWhere==0 ) return 0;
+ if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ for(pSel=pSubq; pSel; pSel=pSel->pPrior){
+ if( pSel->pWin ) return 0; /* restriction (6) */
+ }
+#endif
+
+#ifdef SQLITE_DEBUG
+ /* Only the first term of a compound can have a WITH clause. But make
+ ** sure no other terms are marked SF_Recursive in case something changes
+ ** in the future.
+ */
+ {
+ Select *pX;
+ for(pX=pSubq; pX; pX=pX->pPrior){
+ assert( (pX->selFlags & (SF_Recursive))==0 );
+ }
+ }
+#endif
+
+ if( pSubq->pLimit!=0 ){
+ return 0; /* restriction (3) */
+ }
+ while( pWhere->op==TK_AND ){
+ nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight,
+ iCursor, isLeftJoin);
+ pWhere = pWhere->pLeft;
+ }
+ if( isLeftJoin
+ && (ExprHasProperty(pWhere,EP_FromJoin)==0
+ || pWhere->iRightJoinTable!=iCursor)
+ ){
+ return 0; /* restriction (4) */
+ }
+ if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){
+ return 0; /* restriction (5) */
+ }
+ if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
+ nChng++;
+ while( pSubq ){
+ SubstContext x;
+ pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
+ unsetJoinExpr(pNew, -1);
+ x.pParse = pParse;
+ x.iTable = iCursor;
+ x.iNewTable = iCursor;
+ x.isLeftJoin = 0;
+ x.pEList = pSubq->pEList;
+ pNew = substExpr(&x, pNew);
+ if( pSubq->selFlags & SF_Aggregate ){
+ pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
+ }else{
+ pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
+ }
+ pSubq = pSubq->pPrior;
+ }
+ }
+ return nChng;
+}
+#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
+
+/*
+** The pFunc is the only aggregate function in the query. Check to see
+** if the query is a candidate for the min/max optimization.
+**
+** If the query is a candidate for the min/max optimization, then set
+** *ppMinMax to be an ORDER BY clause to be used for the optimization
+** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
+** whether pFunc is a min() or max() function.
+**
+** If the query is not a candidate for the min/max optimization, return
+** WHERE_ORDERBY_NORMAL (which must be zero).
+**
+** This routine must be called after aggregate functions have been
+** located but before their arguments have been subjected to aggregate
+** analysis.
+*/
+static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
+ int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
+ ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */
+ const char *zFunc; /* Name of aggregate function pFunc */
+ ExprList *pOrderBy;
+ u8 sortFlags = 0;
+
+ assert( *ppMinMax==0 );
+ assert( pFunc->op==TK_AGG_FUNCTION );
+ assert( !IsWindowFunc(pFunc) );
+ if( pEList==0 || pEList->nExpr!=1 || ExprHasProperty(pFunc, EP_WinFunc) ){
+ return eRet;
+ }
+ zFunc = pFunc->u.zToken;
+ if( sqlite3StrICmp(zFunc, "min")==0 ){
+ eRet = WHERE_ORDERBY_MIN;
+ if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){
+ sortFlags = KEYINFO_ORDER_BIGNULL;
+ }
+ }else if( sqlite3StrICmp(zFunc, "max")==0 ){
+ eRet = WHERE_ORDERBY_MAX;
+ sortFlags = KEYINFO_ORDER_DESC;
+ }else{
+ return eRet;
+ }
+ *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
+ assert( pOrderBy!=0 || db->mallocFailed );
+ if( pOrderBy ) pOrderBy->a[0].sortFlags = sortFlags;
+ return eRet;
+}
+
+/*
+** The select statement passed as the first argument is an aggregate query.
+** The second argument is the associated aggregate-info object. This
+** function tests if the SELECT is of the form:
+**
+** SELECT count(*) FROM <tbl>
+**
+** where table is a database table, not a sub-select or view. If the query
+** does match this pattern, then a pointer to the Table object representing
+** <tbl> is returned. Otherwise, 0 is returned.
+*/
+static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
+ Table *pTab;
+ Expr *pExpr;
+
+ assert( !p->pGroupBy );
+
+ if( p->pWhere || p->pEList->nExpr!=1
+ || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
+ ){
+ return 0;
+ }
+ pTab = p->pSrc->a[0].pTab;
+ pExpr = p->pEList->a[0].pExpr;
+ assert( pTab && !pTab->pSelect && pExpr );
+
+ if( IsVirtual(pTab) ) return 0;
+ if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
+ if( NEVER(pAggInfo->nFunc==0) ) return 0;
+ if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
+ if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0;
+
+ return pTab;
+}
+
+/*
+** If the source-list item passed as an argument was augmented with an
+** INDEXED BY clause, then try to locate the specified index. If there
+** was such a clause and the named index cannot be found, return
+** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
+** pFrom->pIndex and return SQLITE_OK.
+*/
+SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
+ if( pFrom->pTab && pFrom->fg.isIndexedBy ){
+ Table *pTab = pFrom->pTab;
+ char *zIndexedBy = pFrom->u1.zIndexedBy;
+ Index *pIdx;
+ for(pIdx=pTab->pIndex;
+ pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
+ pIdx=pIdx->pNext
+ );
+ if( !pIdx ){
+ sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
+ pParse->checkSchema = 1;
+ return SQLITE_ERROR;
+ }
+ pFrom->pIBIndex = pIdx;
+ }
+ return SQLITE_OK;
+}
+/*
+** Detect compound SELECT statements that use an ORDER BY clause with
+** an alternative collating sequence.
+**
+** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
+**
+** These are rewritten as a subquery:
+**
+** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
+** ORDER BY ... COLLATE ...
+**
+** This transformation is necessary because the multiSelectOrderBy() routine
+** above that generates the code for a compound SELECT with an ORDER BY clause
+** uses a merge algorithm that requires the same collating sequence on the
+** result columns as on the ORDER BY clause. See ticket
+** http://www.sqlite.org/src/info/6709574d2a
+**
+** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
+** The UNION ALL operator works fine with multiSelectOrderBy() even when
+** there are COLLATE terms in the ORDER BY.
+*/
+static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
+ int i;
+ Select *pNew;
+ Select *pX;
+ sqlite3 *db;
+ struct ExprList_item *a;
+ SrcList *pNewSrc;
+ Parse *pParse;
+ Token dummy;
+
+ if( p->pPrior==0 ) return WRC_Continue;
+ if( p->pOrderBy==0 ) return WRC_Continue;
+ for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
+ if( pX==0 ) return WRC_Continue;
+ a = p->pOrderBy->a;
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ /* If iOrderByCol is already non-zero, then it has already been matched
+ ** to a result column of the SELECT statement. This occurs when the
+ ** SELECT is rewritten for window-functions processing and then passed
+ ** to sqlite3SelectPrep() and similar a second time. The rewriting done
+ ** by this function is not required in this case. */
+ if( a[0].u.x.iOrderByCol ) return WRC_Continue;
+#endif
+ for(i=p->pOrderBy->nExpr-1; i>=0; i--){
+ if( a[i].pExpr->flags & EP_Collate ) break;
+ }
+ if( i<0 ) return WRC_Continue;
+
+ /* If we reach this point, that means the transformation is required. */
+
+ pParse = pWalker->pParse;
+ db = pParse->db;
+ pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
+ if( pNew==0 ) return WRC_Abort;
+ memset(&dummy, 0, sizeof(dummy));
+ pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
+ if( pNewSrc==0 ) return WRC_Abort;
+ *pNew = *p;
+ p->pSrc = pNewSrc;
+ p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
+ p->op = TK_SELECT;
+ p->pWhere = 0;
+ pNew->pGroupBy = 0;
+ pNew->pHaving = 0;
+ pNew->pOrderBy = 0;
+ p->pPrior = 0;
+ p->pNext = 0;
+ p->pWith = 0;
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ p->pWinDefn = 0;
+#endif
+ p->selFlags &= ~SF_Compound;
+ assert( (p->selFlags & SF_Converted)==0 );
+ p->selFlags |= SF_Converted;
+ assert( pNew->pPrior!=0 );
+ pNew->pPrior->pNext = pNew;
+ pNew->pLimit = 0;
+ return WRC_Continue;
+}
+
+/*
+** Check to see if the FROM clause term pFrom has table-valued function
+** arguments. If it does, leave an error message in pParse and return
+** non-zero, since pFrom is not allowed to be a table-valued function.
+*/
+static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
+ if( pFrom->fg.isTabFunc ){
+ sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
+ return 1;
+ }
+ return 0;
+}
+
+#ifndef SQLITE_OMIT_CTE
+/*
+** Argument pWith (which may be NULL) points to a linked list of nested
+** WITH contexts, from inner to outermost. If the table identified by
+** FROM clause element pItem is really a common-table-expression (CTE)
+** then return a pointer to the CTE definition for that table. Otherwise
+** return NULL.
+**
+** If a non-NULL value is returned, set *ppContext to point to the With
+** object that the returned CTE belongs to.
+*/
+static struct Cte *searchWith(
+ With *pWith, /* Current innermost WITH clause */
+ struct SrcList_item *pItem, /* FROM clause element to resolve */
+ With **ppContext /* OUT: WITH clause return value belongs to */
+){
+ const char *zName;
+ if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
+ With *p;
+ for(p=pWith; p; p=p->pOuter){
+ int i;
+ for(i=0; i<p->nCte; i++){
+ if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
+ *ppContext = p;
+ return &p->a[i];
+ }
+ }
+ }
+ }
+ return 0;
+}
+
+/* The code generator maintains a stack of active WITH clauses
+** with the inner-most WITH clause being at the top of the stack.
+**
+** This routine pushes the WITH clause passed as the second argument
+** onto the top of the stack. If argument bFree is true, then this
+** WITH clause will never be popped from the stack. In this case it
+** should be freed along with the Parse object. In other cases, when
+** bFree==0, the With object will be freed along with the SELECT
+** statement with which it is associated.
+*/
+SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
+ assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
+ if( pWith ){
+ assert( pParse->pWith!=pWith );
+ pWith->pOuter = pParse->pWith;
+ pParse->pWith = pWith;
+ if( bFree ) pParse->pWithToFree = pWith;
+ }
+}
+
+/*
+** This function checks if argument pFrom refers to a CTE declared by
+** a WITH clause on the stack currently maintained by the parser. And,
+** if currently processing a CTE expression, if it is a recursive
+** reference to the current CTE.
+**
+** If pFrom falls into either of the two categories above, pFrom->pTab
+** and other fields are populated accordingly. The caller should check
+** (pFrom->pTab!=0) to determine whether or not a successful match
+** was found.
+**
+** Whether or not a match is found, SQLITE_OK is returned if no error
+** occurs. If an error does occur, an error message is stored in the
+** parser and some error code other than SQLITE_OK returned.
+*/
+static int withExpand(
+ Walker *pWalker,
+ struct SrcList_item *pFrom
+){
+ Parse *pParse = pWalker->pParse;
+ sqlite3 *db = pParse->db;
+ struct Cte *pCte; /* Matched CTE (or NULL if no match) */
+ With *pWith; /* WITH clause that pCte belongs to */
+
+ assert( pFrom->pTab==0 );
+ if( pParse->nErr ){
+ return SQLITE_ERROR;
+ }
+
+ pCte = searchWith(pParse->pWith, pFrom, &pWith);
+ if( pCte ){
+ Table *pTab;
+ ExprList *pEList;
+ Select *pSel;
+ Select *pLeft; /* Left-most SELECT statement */
+ int bMayRecursive; /* True if compound joined by UNION [ALL] */
+ With *pSavedWith; /* Initial value of pParse->pWith */
+
+ /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
+ ** recursive reference to CTE pCte. Leave an error in pParse and return
+ ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
+ ** In this case, proceed. */
+ if( pCte->zCteErr ){
+ sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
+ return SQLITE_ERROR;
+ }
+ if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
+
+ assert( pFrom->pTab==0 );
+ pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
+ if( pTab==0 ) return WRC_Abort;
+ pTab->nTabRef = 1;
+ pTab->zName = sqlite3DbStrDup(db, pCte->zName);
+ pTab->iPKey = -1;
+ pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
+ pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
+ pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
+ if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
+ assert( pFrom->pSelect );
+
+ /* Check if this is a recursive CTE. */
+ pSel = pFrom->pSelect;
+ bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
+ if( bMayRecursive ){
+ int i;
+ SrcList *pSrc = pFrom->pSelect->pSrc;
+ for(i=0; i<pSrc->nSrc; i++){
+ struct SrcList_item *pItem = &pSrc->a[i];
+ if( pItem->zDatabase==0
+ && pItem->zName!=0
+ && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
+ ){
+ pItem->pTab = pTab;
+ pItem->fg.isRecursive = 1;
+ pTab->nTabRef++;
+ pSel->selFlags |= SF_Recursive;
+ }
+ }
+ }
+
+ /* Only one recursive reference is permitted. */
+ if( pTab->nTabRef>2 ){
+ sqlite3ErrorMsg(
+ pParse, "multiple references to recursive table: %s", pCte->zName
+ );
+ return SQLITE_ERROR;
+ }
+ assert( pTab->nTabRef==1 ||
+ ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
+
+ pCte->zCteErr = "circular reference: %s";
+ pSavedWith = pParse->pWith;
+ pParse->pWith = pWith;
+ if( bMayRecursive ){
+ Select *pPrior = pSel->pPrior;
+ assert( pPrior->pWith==0 );
+ pPrior->pWith = pSel->pWith;
+ sqlite3WalkSelect(pWalker, pPrior);
+ pPrior->pWith = 0;
+ }else{
+ sqlite3WalkSelect(pWalker, pSel);
+ }
+ pParse->pWith = pWith;
+
+ for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
+ pEList = pLeft->pEList;
+ if( pCte->pCols ){
+ if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
+ sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
+ pCte->zName, pEList->nExpr, pCte->pCols->nExpr
+ );
+ pParse->pWith = pSavedWith;
+ return SQLITE_ERROR;
+ }
+ pEList = pCte->pCols;
+ }
+
+ sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
+ if( bMayRecursive ){
+ if( pSel->selFlags & SF_Recursive ){
+ pCte->zCteErr = "multiple recursive references: %s";
+ }else{
+ pCte->zCteErr = "recursive reference in a subquery: %s";
+ }
+ sqlite3WalkSelect(pWalker, pSel);
+ }
+ pCte->zCteErr = 0;
+ pParse->pWith = pSavedWith;
+ }
+
+ return SQLITE_OK;
+}
+#endif
+
+#ifndef SQLITE_OMIT_CTE
+/*
+** If the SELECT passed as the second argument has an associated WITH
+** clause, pop it from the stack stored as part of the Parse object.
+**
+** This function is used as the xSelectCallback2() callback by
+** sqlite3SelectExpand() when walking a SELECT tree to resolve table
+** names and other FROM clause elements.
+*/
+static void selectPopWith(Walker *pWalker, Select *p){
+ Parse *pParse = pWalker->pParse;
+ if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
+ With *pWith = findRightmost(p)->pWith;
+ if( pWith!=0 ){
+ assert( pParse->pWith==pWith || pParse->nErr );
+ pParse->pWith = pWith->pOuter;
+ }
+ }
+}
+#else
+#define selectPopWith 0
+#endif
+
+/*
+** The SrcList_item structure passed as the second argument represents a
+** sub-query in the FROM clause of a SELECT statement. This function
+** allocates and populates the SrcList_item.pTab object. If successful,
+** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
+** SQLITE_NOMEM.
+*/
+SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){
+ Select *pSel = pFrom->pSelect;
+ Table *pTab;
+
+ assert( pSel );
+ pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
+ if( pTab==0 ) return SQLITE_NOMEM;
+ pTab->nTabRef = 1;
+ if( pFrom->zAlias ){
+ pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
+ }else{
+ pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId);
+ }
+ while( pSel->pPrior ){ pSel = pSel->pPrior; }
+ sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
+ pTab->iPKey = -1;
+ pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
+ pTab->tabFlags |= TF_Ephemeral;
+
+ return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
+}
+
+/*
+** This routine is a Walker callback for "expanding" a SELECT statement.
+** "Expanding" means to do the following:
+**
+** (1) Make sure VDBE cursor numbers have been assigned to every
+** element of the FROM clause.
+**
+** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
+** defines FROM clause. When views appear in the FROM clause,
+** fill pTabList->a[].pSelect with a copy of the SELECT statement
+** that implements the view. A copy is made of the view's SELECT
+** statement so that we can freely modify or delete that statement
+** without worrying about messing up the persistent representation
+** of the view.
+**
+** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
+** on joins and the ON and USING clause of joins.
+**
+** (4) Scan the list of columns in the result set (pEList) looking
+** for instances of the "*" operator or the TABLE.* operator.
+** If found, expand each "*" to be every column in every table
+** and TABLE.* to be every column in TABLE.
+**
+*/
+static int selectExpander(Walker *pWalker, Select *p){
+ Parse *pParse = pWalker->pParse;
+ int i, j, k;
+ SrcList *pTabList;
+ ExprList *pEList;
+ struct SrcList_item *pFrom;
+ sqlite3 *db = pParse->db;
+ Expr *pE, *pRight, *pExpr;
+ u16 selFlags = p->selFlags;
+ u32 elistFlags = 0;
+
+ p->selFlags |= SF_Expanded;
+ if( db->mallocFailed ){
+ return WRC_Abort;
+ }
+ assert( p->pSrc!=0 );
+ if( (selFlags & SF_Expanded)!=0 ){
+ return WRC_Prune;
+ }
+ if( pWalker->eCode ){
+ /* Renumber selId because it has been copied from a view */
+ p->selId = ++pParse->nSelect;
+ }
+ pTabList = p->pSrc;
+ pEList = p->pEList;
+ sqlite3WithPush(pParse, p->pWith, 0);
+
+ /* Make sure cursor numbers have been assigned to all entries in
+ ** the FROM clause of the SELECT statement.
+ */
+ sqlite3SrcListAssignCursors(pParse, pTabList);
+
+ /* Look up every table named in the FROM clause of the select. If
+ ** an entry of the FROM clause is a subquery instead of a table or view,
+ ** then create a transient table structure to describe the subquery.
+ */
+ for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
+ Table *pTab;
+ assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
+ if( pFrom->pTab ) continue;
+ assert( pFrom->fg.isRecursive==0 );
+#ifndef SQLITE_OMIT_CTE
+ if( withExpand(pWalker, pFrom) ) return WRC_Abort;
+ if( pFrom->pTab ) {} else
+#endif
+ if( pFrom->zName==0 ){
+#ifndef SQLITE_OMIT_SUBQUERY
+ Select *pSel = pFrom->pSelect;
+ /* A sub-query in the FROM clause of a SELECT */
+ assert( pSel!=0 );
+ assert( pFrom->pTab==0 );
+ if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
+ if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
+#endif
+ }else{
+ /* An ordinary table or view name in the FROM clause */
+ assert( pFrom->pTab==0 );
+ pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
+ if( pTab==0 ) return WRC_Abort;
+ if( pTab->nTabRef>=0xffff ){
+ sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
+ pTab->zName);
+ pFrom->pTab = 0;
+ return WRC_Abort;
+ }
+ pTab->nTabRef++;
+ if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
+ return WRC_Abort;
+ }
+#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
+ if( IsVirtual(pTab) || pTab->pSelect ){
+ i16 nCol;
+ u8 eCodeOrig = pWalker->eCode;
+ if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
+ assert( pFrom->pSelect==0 );
+ if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){
+ sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
+ pTab->zName);
+ }
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( IsVirtual(pTab)
+ && pFrom->fg.fromDDL
+ && ALWAYS(pTab->pVTable!=0)
+ && pTab->pVTable->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)
+ ){
+ sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"",
+ pTab->zName);
+ }
+#endif
+ pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
+ nCol = pTab->nCol;
+ pTab->nCol = -1;
+ pWalker->eCode = 1; /* Turn on Select.selId renumbering */
+ sqlite3WalkSelect(pWalker, pFrom->pSelect);
+ pWalker->eCode = eCodeOrig;
+ pTab->nCol = nCol;
+ }
+#endif
+ }
+
+ /* Locate the index named by the INDEXED BY clause, if any. */
+ if( sqlite3IndexedByLookup(pParse, pFrom) ){
+ return WRC_Abort;
+ }
+ }
+
+ /* Process NATURAL keywords, and ON and USING clauses of joins.
+ */
+ if( pParse->nErr || db->mallocFailed || sqliteProcessJoin(pParse, p) ){
+ return WRC_Abort;
+ }
+
+ /* For every "*" that occurs in the column list, insert the names of
+ ** all columns in all tables. And for every TABLE.* insert the names
+ ** of all columns in TABLE. The parser inserted a special expression
+ ** with the TK_ASTERISK operator for each "*" that it found in the column
+ ** list. The following code just has to locate the TK_ASTERISK
+ ** expressions and expand each one to the list of all columns in
+ ** all tables.
+ **
+ ** The first loop just checks to see if there are any "*" operators
+ ** that need expanding.
+ */
+ for(k=0; k<pEList->nExpr; k++){
+ pE = pEList->a[k].pExpr;
+ if( pE->op==TK_ASTERISK ) break;
+ assert( pE->op!=TK_DOT || pE->pRight!=0 );
+ assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
+ if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
+ elistFlags |= pE->flags;
+ }
+ if( k<pEList->nExpr ){
+ /*
+ ** If we get here it means the result set contains one or more "*"
+ ** operators that need to be expanded. Loop through each expression
+ ** in the result set and expand them one by one.
+ */
+ struct ExprList_item *a = pEList->a;
+ ExprList *pNew = 0;
+ int flags = pParse->db->flags;
+ int longNames = (flags & SQLITE_FullColNames)!=0
+ && (flags & SQLITE_ShortColNames)==0;
+
+ for(k=0; k<pEList->nExpr; k++){
+ pE = a[k].pExpr;
+ elistFlags |= pE->flags;
+ pRight = pE->pRight;
+ assert( pE->op!=TK_DOT || pRight!=0 );
+ if( pE->op!=TK_ASTERISK
+ && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
+ ){
+ /* This particular expression does not need to be expanded.
+ */
+ pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
+ if( pNew ){
+ pNew->a[pNew->nExpr-1].zEName = a[k].zEName;
+ pNew->a[pNew->nExpr-1].eEName = a[k].eEName;
+ a[k].zEName = 0;
+ }
+ a[k].pExpr = 0;
+ }else{
+ /* This expression is a "*" or a "TABLE.*" and needs to be
+ ** expanded. */
+ int tableSeen = 0; /* Set to 1 when TABLE matches */
+ char *zTName = 0; /* text of name of TABLE */
+ if( pE->op==TK_DOT ){
+ assert( pE->pLeft!=0 );
+ assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
+ zTName = pE->pLeft->u.zToken;
+ }
+ for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
+ Table *pTab = pFrom->pTab;
+ Select *pSub = pFrom->pSelect;
+ char *zTabName = pFrom->zAlias;
+ const char *zSchemaName = 0;
+ int iDb;
+ if( zTabName==0 ){
+ zTabName = pTab->zName;
+ }
+ if( db->mallocFailed ) break;
+ if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
+ pSub = 0;
+ if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
+ continue;
+ }
+ iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
+ }
+ for(j=0; j<pTab->nCol; j++){
+ char *zName = pTab->aCol[j].zName;
+ char *zColname; /* The computed column name */
+ char *zToFree; /* Malloced string that needs to be freed */
+ Token sColname; /* Computed column name as a token */
+
+ assert( zName );
+ if( zTName && pSub
+ && sqlite3MatchEName(&pSub->pEList->a[j], 0, zTName, 0)==0
+ ){
+ continue;
+ }
+
+ /* If a column is marked as 'hidden', omit it from the expanded
+ ** result-set list unless the SELECT has the SF_IncludeHidden
+ ** bit set.
+ */
+ if( (p->selFlags & SF_IncludeHidden)==0
+ && IsHiddenColumn(&pTab->aCol[j])
+ ){
+ continue;
+ }
+ tableSeen = 1;
+
+ if( i>0 && zTName==0 ){
+ if( (pFrom->fg.jointype & JT_NATURAL)!=0
+ && tableAndColumnIndex(pTabList, i, zName, 0, 0, 1)
+ ){
+ /* In a NATURAL join, omit the join columns from the
+ ** table to the right of the join */
+ continue;
+ }
+ if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
+ /* In a join with a USING clause, omit columns in the
+ ** using clause from the table on the right. */
+ continue;
+ }
+ }
+ pRight = sqlite3Expr(db, TK_ID, zName);
+ zColname = zName;
+ zToFree = 0;
+ if( longNames || pTabList->nSrc>1 ){
+ Expr *pLeft;
+ pLeft = sqlite3Expr(db, TK_ID, zTabName);
+ pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
+ if( zSchemaName ){
+ pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
+ pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
+ }
+ if( longNames ){
+ zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
+ zToFree = zColname;
+ }
+ }else{
+ pExpr = pRight;
+ }
+ pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
+ sqlite3TokenInit(&sColname, zColname);
+ sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
+ if( pNew && (p->selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){
+ struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
+ sqlite3DbFree(db, pX->zEName);
+ if( pSub ){
+ pX->zEName = sqlite3DbStrDup(db, pSub->pEList->a[j].zEName);
+ testcase( pX->zEName==0 );
+ }else{
+ pX->zEName = sqlite3MPrintf(db, "%s.%s.%s",
+ zSchemaName, zTabName, zColname);
+ testcase( pX->zEName==0 );
+ }
+ pX->eEName = ENAME_TAB;
+ }
+ sqlite3DbFree(db, zToFree);
+ }
+ }
+ if( !tableSeen ){
+ if( zTName ){
+ sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
+ }else{
+ sqlite3ErrorMsg(pParse, "no tables specified");
+ }
+ }
+ }
+ }
+ sqlite3ExprListDelete(db, pEList);
+ p->pEList = pNew;
+ }
+ if( p->pEList ){
+ if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
+ sqlite3ErrorMsg(pParse, "too many columns in result set");
+ return WRC_Abort;
+ }
+ if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
+ p->selFlags |= SF_ComplexResult;
+ }
+ }
+ return WRC_Continue;
+}
+
+#if SQLITE_DEBUG
+/*
+** Always assert. This xSelectCallback2 implementation proves that the
+** xSelectCallback2 is never invoked.
+*/
+SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ assert( 0 );
+}
+#endif
+/*
+** This routine "expands" a SELECT statement and all of its subqueries.
+** For additional information on what it means to "expand" a SELECT
+** statement, see the comment on the selectExpand worker callback above.
+**
+** Expanding a SELECT statement is the first step in processing a
+** SELECT statement. The SELECT statement must be expanded before
+** name resolution is performed.
+**
+** If anything goes wrong, an error message is written into pParse.
+** The calling function can detect the problem by looking at pParse->nErr
+** and/or pParse->db->mallocFailed.
+*/
+static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
+ Walker w;
+ w.xExprCallback = sqlite3ExprWalkNoop;
+ w.pParse = pParse;
+ if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
+ w.xSelectCallback = convertCompoundSelectToSubquery;
+ w.xSelectCallback2 = 0;
+ sqlite3WalkSelect(&w, pSelect);
+ }
+ w.xSelectCallback = selectExpander;
+ w.xSelectCallback2 = selectPopWith;
+ w.eCode = 0;
+ sqlite3WalkSelect(&w, pSelect);
+}
+
+
+#ifndef SQLITE_OMIT_SUBQUERY
+/*
+** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
+** interface.
+**
+** For each FROM-clause subquery, add Column.zType and Column.zColl
+** information to the Table structure that represents the result set
+** of that subquery.
+**
+** The Table structure that represents the result set was constructed
+** by selectExpander() but the type and collation information was omitted
+** at that point because identifiers had not yet been resolved. This
+** routine is called after identifier resolution.
+*/
+static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
+ Parse *pParse;
+ int i;
+ SrcList *pTabList;
+ struct SrcList_item *pFrom;
+
+ assert( p->selFlags & SF_Resolved );
+ if( p->selFlags & SF_HasTypeInfo ) return;
+ p->selFlags |= SF_HasTypeInfo;
+ pParse = pWalker->pParse;
+ pTabList = p->pSrc;
+ for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
+ Table *pTab = pFrom->pTab;
+ assert( pTab!=0 );
+ if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
+ /* A sub-query in the FROM clause of a SELECT */
+ Select *pSel = pFrom->pSelect;
+ if( pSel ){
+ while( pSel->pPrior ) pSel = pSel->pPrior;
+ sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel,
+ SQLITE_AFF_NONE);
+ }
+ }
+ }
+}
+#endif
+
+
+/*
+** This routine adds datatype and collating sequence information to
+** the Table structures of all FROM-clause subqueries in a
+** SELECT statement.
+**
+** Use this routine after name resolution.
+*/
+static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
+#ifndef SQLITE_OMIT_SUBQUERY
+ Walker w;
+ w.xSelectCallback = sqlite3SelectWalkNoop;
+ w.xSelectCallback2 = selectAddSubqueryTypeInfo;
+ w.xExprCallback = sqlite3ExprWalkNoop;
+ w.pParse = pParse;
+ sqlite3WalkSelect(&w, pSelect);
+#endif
+}
+
+
+/*
+** This routine sets up a SELECT statement for processing. The
+** following is accomplished:
+**
+** * VDBE Cursor numbers are assigned to all FROM-clause terms.
+** * Ephemeral Table objects are created for all FROM-clause subqueries.
+** * ON and USING clauses are shifted into WHERE statements
+** * Wildcards "*" and "TABLE.*" in result sets are expanded.
+** * Identifiers in expression are matched to tables.
+**
+** This routine acts recursively on all subqueries within the SELECT.
+*/
+SQLITE_PRIVATE void sqlite3SelectPrep(
+ Parse *pParse, /* The parser context */
+ Select *p, /* The SELECT statement being coded. */
+ NameContext *pOuterNC /* Name context for container */
+){
+ assert( p!=0 || pParse->db->mallocFailed );
+ if( pParse->db->mallocFailed ) return;
+ if( p->selFlags & SF_HasTypeInfo ) return;
+ sqlite3SelectExpand(pParse, p);
+ if( pParse->nErr || pParse->db->mallocFailed ) return;
+ sqlite3ResolveSelectNames(pParse, p, pOuterNC);
+ if( pParse->nErr || pParse->db->mallocFailed ) return;
+ sqlite3SelectAddTypeInfo(pParse, p);
+}
+
+/*
+** Reset the aggregate accumulator.
+**
+** The aggregate accumulator is a set of memory cells that hold
+** intermediate results while calculating an aggregate. This
+** routine generates code that stores NULLs in all of those memory
+** cells.
+*/
+static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
+ Vdbe *v = pParse->pVdbe;
+ int i;
+ struct AggInfo_func *pFunc;
+ int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
+ if( nReg==0 ) return;
+ if( pParse->nErr || pParse->db->mallocFailed ) return;
+#ifdef SQLITE_DEBUG
+ /* Verify that all AggInfo registers are within the range specified by
+ ** AggInfo.mnReg..AggInfo.mxReg */
+ assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
+ for(i=0; i<pAggInfo->nColumn; i++){
+ assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
+ && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
+ }
+ for(i=0; i<pAggInfo->nFunc; i++){
+ assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
+ && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
+ }
+#endif
+ sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
+ for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
+ if( pFunc->iDistinct>=0 ){
+ Expr *pE = pFunc->pFExpr;
+ assert( !ExprHasProperty(pE, EP_xIsSelect) );
+ if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
+ sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
+ "argument");
+ pFunc->iDistinct = -1;
+ }else{
+ KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
+ sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
+ (char*)pKeyInfo, P4_KEYINFO);
+ }
+ }
+ }
+}
+
+/*
+** Invoke the OP_AggFinalize opcode for every aggregate function
+** in the AggInfo structure.
+*/
+static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
+ Vdbe *v = pParse->pVdbe;
+ int i;
+ struct AggInfo_func *pF;
+ for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
+ ExprList *pList = pF->pFExpr->x.pList;
+ assert( !ExprHasProperty(pF->pFExpr, EP_xIsSelect) );
+ sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
+ sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
+ }
+}
+
+
+/*
+** Update the accumulator memory cells for an aggregate based on
+** the current cursor position.
+**
+** If regAcc is non-zero and there are no min() or max() aggregates
+** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
+** registers if register regAcc contains 0. The caller will take care
+** of setting and clearing regAcc.
+*/
+static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
+ Vdbe *v = pParse->pVdbe;
+ int i;
+ int regHit = 0;
+ int addrHitTest = 0;
+ struct AggInfo_func *pF;
+ struct AggInfo_col *pC;
+
+ pAggInfo->directMode = 1;
+ for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
+ int nArg;
+ int addrNext = 0;
+ int regAgg;
+ ExprList *pList = pF->pFExpr->x.pList;
+ assert( !ExprHasProperty(pF->pFExpr, EP_xIsSelect) );
+ assert( !IsWindowFunc(pF->pFExpr) );
+ if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){
+ Expr *pFilter = pF->pFExpr->y.pWin->pFilter;
+ if( pAggInfo->nAccumulator
+ && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
+ && regAcc
+ ){
+ /* If regAcc==0, there there exists some min() or max() function
+ ** without a FILTER clause that will ensure the magnet registers
+ ** are populated. */
+ if( regHit==0 ) regHit = ++pParse->nMem;
+ /* If this is the first row of the group (regAcc contains 0), clear the
+ ** "magnet" register regHit so that the accumulator registers
+ ** are populated if the FILTER clause jumps over the the
+ ** invocation of min() or max() altogether. Or, if this is not
+ ** the first row (regAcc contains 1), set the magnet register so that
+ ** the accumulators are not populated unless the min()/max() is invoked
+ ** and indicates that they should be. */
+ sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit);
+ }
+ addrNext = sqlite3VdbeMakeLabel(pParse);
+ sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL);
+ }
+ if( pList ){
+ nArg = pList->nExpr;
+ regAgg = sqlite3GetTempRange(pParse, nArg);
+ sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
+ }else{
+ nArg = 0;
+ regAgg = 0;
+ }
+ if( pF->iDistinct>=0 ){
+ if( addrNext==0 ){
+ addrNext = sqlite3VdbeMakeLabel(pParse);
+ }
+ testcase( nArg==0 ); /* Error condition */
+ testcase( nArg>1 ); /* Also an error */
+ codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
+ }
+ if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
+ CollSeq *pColl = 0;
+ struct ExprList_item *pItem;
+ int j;
+ assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
+ for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
+ pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
+ }
+ if( !pColl ){
+ pColl = pParse->db->pDfltColl;
+ }
+ if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
+ sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
+ }
+ sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem);
+ sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
+ sqlite3VdbeChangeP5(v, (u8)nArg);
+ sqlite3ReleaseTempRange(pParse, regAgg, nArg);
+ if( addrNext ){
+ sqlite3VdbeResolveLabel(v, addrNext);
+ }
+ }
+ if( regHit==0 && pAggInfo->nAccumulator ){
+ regHit = regAcc;
+ }
+ if( regHit ){
+ addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
+ }
+ for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
+ sqlite3ExprCode(pParse, pC->pCExpr, pC->iMem);
+ }
+
+ pAggInfo->directMode = 0;
+ if( addrHitTest ){
+ sqlite3VdbeJumpHereOrPopInst(v, addrHitTest);
+ }
+}
+
+/*
+** Add a single OP_Explain instruction to the VDBE to explain a simple
+** count(*) query ("SELECT count(*) FROM pTab").
+*/
+#ifndef SQLITE_OMIT_EXPLAIN
+static void explainSimpleCount(
+ Parse *pParse, /* Parse context */
+ Table *pTab, /* Table being queried */
+ Index *pIdx /* Index used to optimize scan, or NULL */
+){
+ if( pParse->explain==2 ){
+ int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
+ sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s",
+ pTab->zName,
+ bCover ? " USING COVERING INDEX " : "",
+ bCover ? pIdx->zName : ""
+ );
+ }
+}
+#else
+# define explainSimpleCount(a,b,c)
+#endif
+
+/*
+** sqlite3WalkExpr() callback used by havingToWhere().
+**
+** If the node passed to the callback is a TK_AND node, return
+** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
+**
+** Otherwise, return WRC_Prune. In this case, also check if the
+** sub-expression matches the criteria for being moved to the WHERE
+** clause. If so, add it to the WHERE clause and replace the sub-expression
+** within the HAVING expression with a constant "1".
+*/
+static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
+ if( pExpr->op!=TK_AND ){
+ Select *pS = pWalker->u.pSelect;
+ if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){
+ sqlite3 *db = pWalker->pParse->db;
+ Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1");
+ if( pNew ){
+ Expr *pWhere = pS->pWhere;
+ SWAP(Expr, *pNew, *pExpr);
+ pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
+ pS->pWhere = pNew;
+ pWalker->eCode = 1;
+ }
+ }
+ return WRC_Prune;
+ }
+ return WRC_Continue;
+}
+
+/*
+** Transfer eligible terms from the HAVING clause of a query, which is
+** processed after grouping, to the WHERE clause, which is processed before
+** grouping. For example, the query:
+**
+** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
+**
+** can be rewritten as:
+**
+** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
+**
+** A term of the HAVING expression is eligible for transfer if it consists
+** entirely of constants and expressions that are also GROUP BY terms that
+** use the "BINARY" collation sequence.
+*/
+static void havingToWhere(Parse *pParse, Select *p){
+ Walker sWalker;
+ memset(&sWalker, 0, sizeof(sWalker));
+ sWalker.pParse = pParse;
+ sWalker.xExprCallback = havingToWhereExprCb;
+ sWalker.u.pSelect = p;
+ sqlite3WalkExpr(&sWalker, p->pHaving);
+#if SELECTTRACE_ENABLED
+ if( sWalker.eCode && (sqlite3_unsupported_selecttrace & 0x100)!=0 ){
+ SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
+ sqlite3TreeViewSelect(0, p, 0);
+ }
+#endif
+}
+
+/*
+** Check to see if the pThis entry of pTabList is a self-join of a prior view.
+** If it is, then return the SrcList_item for the prior view. If it is not,
+** then return 0.
+*/
+static struct SrcList_item *isSelfJoinView(
+ SrcList *pTabList, /* Search for self-joins in this FROM clause */
+ struct SrcList_item *pThis /* Search for prior reference to this subquery */
+){
+ struct SrcList_item *pItem;
+ for(pItem = pTabList->a; pItem<pThis; pItem++){
+ Select *pS1;
+ if( pItem->pSelect==0 ) continue;
+ if( pItem->fg.viaCoroutine ) continue;
+ if( pItem->zName==0 ) continue;
+ assert( pItem->pTab!=0 );
+ assert( pThis->pTab!=0 );
+ if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue;
+ if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
+ pS1 = pItem->pSelect;
+ if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){
+ /* The query flattener left two different CTE tables with identical
+ ** names in the same FROM clause. */
+ continue;
+ }
+ if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1)
+ || sqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1)
+ ){
+ /* The view was modified by some other optimization such as
+ ** pushDownWhereTerms() */
+ continue;
+ }
+ return pItem;
+ }
+ return 0;
+}
+
+#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
+/*
+** Attempt to transform a query of the form
+**
+** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
+**
+** Into this:
+**
+** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
+**
+** The transformation only works if all of the following are true:
+**
+** * The subquery is a UNION ALL of two or more terms
+** * The subquery does not have a LIMIT clause
+** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
+** * The outer query is a simple count(*) with no WHERE clause or other
+** extraneous syntax.
+**
+** Return TRUE if the optimization is undertaken.
+*/
+static int countOfViewOptimization(Parse *pParse, Select *p){
+ Select *pSub, *pPrior;
+ Expr *pExpr;
+ Expr *pCount;
+ sqlite3 *db;
+ if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
+ if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
+ if( p->pWhere ) return 0;
+ if( p->pGroupBy ) return 0;
+ pExpr = p->pEList->a[0].pExpr;
+ if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
+ if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
+ if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
+ if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
+ pSub = p->pSrc->a[0].pSelect;
+ if( pSub==0 ) return 0; /* The FROM is a subquery */
+ if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */
+ do{
+ if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
+ if( pSub->pWhere ) return 0; /* No WHERE clause */
+ if( pSub->pLimit ) return 0; /* No LIMIT clause */
+ if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
+ pSub = pSub->pPrior; /* Repeat over compound */
+ }while( pSub );
+
+ /* If we reach this point then it is OK to perform the transformation */
+
+ db = pParse->db;
+ pCount = pExpr;
+ pExpr = 0;
+ pSub = p->pSrc->a[0].pSelect;
+ p->pSrc->a[0].pSelect = 0;
+ sqlite3SrcListDelete(db, p->pSrc);
+ p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
+ while( pSub ){
+ Expr *pTerm;
+ pPrior = pSub->pPrior;
+ pSub->pPrior = 0;
+ pSub->pNext = 0;
+ pSub->selFlags |= SF_Aggregate;
+ pSub->selFlags &= ~SF_Compound;
+ pSub->nSelectRow = 0;
+ sqlite3ExprListDelete(db, pSub->pEList);
+ pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
+ pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
+ pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
+ sqlite3PExprAddSelect(pParse, pTerm, pSub);
+ if( pExpr==0 ){
+ pExpr = pTerm;
+ }else{
+ pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
+ }
+ pSub = pPrior;
+ }
+ p->pEList->a[0].pExpr = pExpr;
+ p->selFlags &= ~SF_Aggregate;
+
+#if SELECTTRACE_ENABLED
+ if( sqlite3_unsupported_selecttrace & 0x400 ){
+ SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
+ sqlite3TreeViewSelect(0, p, 0);
+ }
+#endif
+ return 1;
+}
+#endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
+
+/*
+** Generate code for the SELECT statement given in the p argument.
+**
+** The results are returned according to the SelectDest structure.
+** See comments in sqliteInt.h for further information.
+**
+** This routine returns the number of errors. If any errors are
+** encountered, then an appropriate error message is left in
+** pParse->zErrMsg.
+**
+** This routine does NOT free the Select structure passed in. The
+** calling function needs to do that.
+*/
+SQLITE_PRIVATE int sqlite3Select(
+ Parse *pParse, /* The parser context */
+ Select *p, /* The SELECT statement being coded. */
+ SelectDest *pDest /* What to do with the query results */
+){
+ int i, j; /* Loop counters */
+ WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
+ Vdbe *v; /* The virtual machine under construction */
+ int isAgg; /* True for select lists like "count(*)" */
+ ExprList *pEList = 0; /* List of columns to extract. */
+ SrcList *pTabList; /* List of tables to select from */
+ Expr *pWhere; /* The WHERE clause. May be NULL */
+ ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
+ Expr *pHaving; /* The HAVING clause. May be NULL */
+ AggInfo *pAggInfo = 0; /* Aggregate information */
+ int rc = 1; /* Value to return from this function */
+ DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
+ SortCtx sSort; /* Info on how to code the ORDER BY clause */
+ int iEnd; /* Address of the end of the query */
+ sqlite3 *db; /* The database connection */
+ ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */
+ u8 minMaxFlag; /* Flag for min/max queries */
+
+ db = pParse->db;
+ v = sqlite3GetVdbe(pParse);
+ if( p==0 || db->mallocFailed || pParse->nErr ){
+ return 1;
+ }
+ if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
+#if SELECTTRACE_ENABLED
+ SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
+ if( sqlite3_unsupported_selecttrace & 0x100 ){
+ sqlite3TreeViewSelect(0, p, 0);
+ }
+#endif
+
+ assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
+ assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
+ assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
+ assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
+ if( IgnorableDistinct(pDest) ){
+ assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
+ pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
+ pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_DistFifo );
+ /* All of these destinations are also able to ignore the ORDER BY clause */
+ sqlite3ExprListDelete(db, p->pOrderBy);
+ p->pOrderBy = 0;
+ p->selFlags &= ~SF_Distinct;
+ p->selFlags |= SF_NoopOrderBy;
+ }
+ sqlite3SelectPrep(pParse, p, 0);
+ if( pParse->nErr || db->mallocFailed ){
+ goto select_end;
+ }
+ assert( p->pEList!=0 );
+#if SELECTTRACE_ENABLED
+ if( sqlite3_unsupported_selecttrace & 0x104 ){
+ SELECTTRACE(0x104,pParse,p, ("after name resolution:\n"));
+ sqlite3TreeViewSelect(0, p, 0);
+ }
+#endif
+
+ /* If the SF_UpdateFrom flag is set, then this function is being called
+ ** as part of populating the temp table for an UPDATE...FROM statement.
+ ** In this case, it is an error if the target object (pSrc->a[0]) name
+ ** or alias is duplicated within FROM clause (pSrc->a[1..n]). */
+ if( p->selFlags & SF_UpdateFrom ){
+ struct SrcList_item *p0 = &p->pSrc->a[0];
+ for(i=1; i<p->pSrc->nSrc; i++){
+ struct SrcList_item *p1 = &p->pSrc->a[i];
+ if( p0->pTab==p1->pTab && 0==sqlite3_stricmp(p0->zAlias, p1->zAlias) ){
+ sqlite3ErrorMsg(pParse,
+ "target object/alias may not appear in FROM clause: %s",
+ p0->zAlias ? p0->zAlias : p0->pTab->zName
+ );
+ goto select_end;
+ }
+ }
+ }
+
+ if( pDest->eDest==SRT_Output ){
+ generateColumnNames(pParse, p);
+ }
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ rc = sqlite3WindowRewrite(pParse, p);
+ if( rc ){
+ assert( db->mallocFailed || pParse->nErr>0 );
+ goto select_end;
+ }
+#if SELECTTRACE_ENABLED
+ if( p->pWin && (sqlite3_unsupported_selecttrace & 0x108)!=0 ){
+ SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n"));
+ sqlite3TreeViewSelect(0, p, 0);
+ }
+#endif
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+ pTabList = p->pSrc;
+ isAgg = (p->selFlags & SF_Aggregate)!=0;
+ memset(&sSort, 0, sizeof(sSort));
+ sSort.pOrderBy = p->pOrderBy;
+
+ /* Try to do various optimizations (flattening subqueries, and strength
+ ** reduction of join operators) in the FROM clause up into the main query
+ */
+#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
+ for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
+ struct SrcList_item *pItem = &pTabList->a[i];
+ Select *pSub = pItem->pSelect;
+ Table *pTab = pItem->pTab;
+
+ /* The expander should have already created transient Table objects
+ ** even for FROM clause elements such as subqueries that do not correspond
+ ** to a real table */
+ assert( pTab!=0 );
+
+ /* Convert LEFT JOIN into JOIN if there are terms of the right table
+ ** of the LEFT JOIN used in the WHERE clause.
+ */
+ if( (pItem->fg.jointype & JT_LEFT)!=0
+ && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
+ && OptimizationEnabled(db, SQLITE_SimplifyJoin)
+ ){
+ SELECTTRACE(0x100,pParse,p,
+ ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
+ pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
+ unsetJoinExpr(p->pWhere, pItem->iCursor);
+ }
+
+ /* No futher action if this term of the FROM clause is no a subquery */
+ if( pSub==0 ) continue;
+
+ /* Catch mismatch in the declared columns of a view and the number of
+ ** columns in the SELECT on the RHS */
+ if( pTab->nCol!=pSub->pEList->nExpr ){
+ sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
+ pTab->nCol, pTab->zName, pSub->pEList->nExpr);
+ goto select_end;
+ }
+
+ /* Do not try to flatten an aggregate subquery.
+ **
+ ** Flattening an aggregate subquery is only possible if the outer query
+ ** is not a join. But if the outer query is not a join, then the subquery
+ ** will be implemented as a co-routine and there is no advantage to
+ ** flattening in that case.
+ */
+ if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
+ assert( pSub->pGroupBy==0 );
+
+ /* If the outer query contains a "complex" result set (that is,
+ ** if the result set of the outer query uses functions or subqueries)
+ ** and if the subquery contains an ORDER BY clause and if
+ ** it will be implemented as a co-routine, then do not flatten. This
+ ** restriction allows SQL constructs like this:
+ **
+ ** SELECT expensive_function(x)
+ ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
+ **
+ ** The expensive_function() is only computed on the 10 rows that
+ ** are output, rather than every row of the table.
+ **
+ ** The requirement that the outer query have a complex result set
+ ** means that flattening does occur on simpler SQL constraints without
+ ** the expensive_function() like:
+ **
+ ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
+ */
+ if( pSub->pOrderBy!=0
+ && i==0
+ && (p->selFlags & SF_ComplexResult)!=0
+ && (pTabList->nSrc==1
+ || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
+ ){
+ continue;
+ }
+
+ if( flattenSubquery(pParse, p, i, isAgg) ){
+ if( pParse->nErr ) goto select_end;
+ /* This subquery can be absorbed into its parent. */
+ i = -1;
+ }
+ pTabList = p->pSrc;
+ if( db->mallocFailed ) goto select_end;
+ if( !IgnorableOrderby(pDest) ){
+ sSort.pOrderBy = p->pOrderBy;
+ }
+ }
+#endif
+
+#ifndef SQLITE_OMIT_COMPOUND_SELECT
+ /* Handle compound SELECT statements using the separate multiSelect()
+ ** procedure.
+ */
+ if( p->pPrior ){
+ rc = multiSelect(pParse, p, pDest);
+#if SELECTTRACE_ENABLED
+ SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
+ if( (sqlite3_unsupported_selecttrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
+ sqlite3TreeViewSelect(0, p, 0);
+ }
+#endif
+ if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
+ return rc;
+ }
+#endif
+
+ /* Do the WHERE-clause constant propagation optimization if this is
+ ** a join. No need to speed time on this operation for non-join queries
+ ** as the equivalent optimization will be handled by query planner in
+ ** sqlite3WhereBegin().
+ */
+ if( pTabList->nSrc>1
+ && OptimizationEnabled(db, SQLITE_PropagateConst)
+ && propagateConstants(pParse, p)
+ ){
+#if SELECTTRACE_ENABLED
+ if( sqlite3_unsupported_selecttrace & 0x100 ){
+ SELECTTRACE(0x100,pParse,p,("After constant propagation:\n"));
+ sqlite3TreeViewSelect(0, p, 0);
+ }
+#endif
+ }else{
+ SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n"));
+ }
+
+#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
+ if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
+ && countOfViewOptimization(pParse, p)
+ ){
+ if( db->mallocFailed ) goto select_end;
+ pEList = p->pEList;
+ pTabList = p->pSrc;
+ }
+#endif
+
+ /* For each term in the FROM clause, do two things:
+ ** (1) Authorized unreferenced tables
+ ** (2) Generate code for all sub-queries
+ */
+ for(i=0; i<pTabList->nSrc; i++){
+ struct SrcList_item *pItem = &pTabList->a[i];
+ SelectDest dest;
+ Select *pSub;
+#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
+ const char *zSavedAuthContext;
+#endif
+
+ /* Issue SQLITE_READ authorizations with a fake column name for any
+ ** tables that are referenced but from which no values are extracted.
+ ** Examples of where these kinds of null SQLITE_READ authorizations
+ ** would occur:
+ **
+ ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
+ ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
+ **
+ ** The fake column name is an empty string. It is possible for a table to
+ ** have a column named by the empty string, in which case there is no way to
+ ** distinguish between an unreferenced table and an actual reference to the
+ ** "" column. The original design was for the fake column name to be a NULL,
+ ** which would be unambiguous. But legacy authorization callbacks might
+ ** assume the column name is non-NULL and segfault. The use of an empty
+ ** string for the fake column name seems safer.
+ */
+ if( pItem->colUsed==0 && pItem->zName!=0 ){
+ sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
+ }
+
+#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
+ /* Generate code for all sub-queries in the FROM clause
+ */
+ pSub = pItem->pSelect;
+ if( pSub==0 ) continue;
+
+ /* The code for a subquery should only be generated once, though it is
+ ** technically harmless for it to be generated multiple times. The
+ ** following assert() will detect if something changes to cause
+ ** the same subquery to be coded multiple times, as a signal to the
+ ** developers to try to optimize the situation.
+ **
+ ** Update 2019-07-24:
+ ** See ticket https://sqlite.org/src/tktview/c52b09c7f38903b1311cec40.
+ ** The dbsqlfuzz fuzzer found a case where the same subquery gets
+ ** coded twice. So this assert() now becomes a testcase(). It should
+ ** be very rare, though.
+ */
+ testcase( pItem->addrFillSub!=0 );
+
+ /* Increment Parse.nHeight by the height of the largest expression
+ ** tree referred to by this, the parent select. The child select
+ ** may contain expression trees of at most
+ ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
+ ** more conservative than necessary, but much easier than enforcing
+ ** an exact limit.
+ */
+ pParse->nHeight += sqlite3SelectExprHeight(p);
+
+ /* Make copies of constant WHERE-clause terms in the outer query down
+ ** inside the subquery. This can help the subquery to run more efficiently.
+ */
+ if( OptimizationEnabled(db, SQLITE_PushDown)
+ && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor,
+ (pItem->fg.jointype & JT_OUTER)!=0)
+ ){
+#if SELECTTRACE_ENABLED
+ if( sqlite3_unsupported_selecttrace & 0x100 ){
+ SELECTTRACE(0x100,pParse,p,
+ ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
+ sqlite3TreeViewSelect(0, p, 0);
+ }
+#endif
+ }else{
+ SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
+ }
+
+ zSavedAuthContext = pParse->zAuthContext;
+ pParse->zAuthContext = pItem->zName;
+
+ /* Generate code to implement the subquery
+ **
+ ** The subquery is implemented as a co-routine if the subquery is
+ ** guaranteed to be the outer loop (so that it does not need to be
+ ** computed more than once)
+ **
+ ** TODO: Are there other reasons beside (1) to use a co-routine
+ ** implementation?
+ */
+ if( i==0
+ && (pTabList->nSrc==1
+ || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
+ ){
+ /* Implement a co-routine that will return a single row of the result
+ ** set on each invocation.
+ */
+ int addrTop = sqlite3VdbeCurrentAddr(v)+1;
+
+ pItem->regReturn = ++pParse->nMem;
+ sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
+ VdbeComment((v, "%s", pItem->pTab->zName));
+ pItem->addrFillSub = addrTop;
+ sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
+ ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId));
+ sqlite3Select(pParse, pSub, &dest);
+ pItem->pTab->nRowLogEst = pSub->nSelectRow;
+ pItem->fg.viaCoroutine = 1;
+ pItem->regResult = dest.iSdst;
+ sqlite3VdbeEndCoroutine(v, pItem->regReturn);
+ sqlite3VdbeJumpHere(v, addrTop-1);
+ sqlite3ClearTempRegCache(pParse);
+ }else{
+ /* Generate a subroutine that will fill an ephemeral table with
+ ** the content of this subquery. pItem->addrFillSub will point
+ ** to the address of the generated subroutine. pItem->regReturn
+ ** is a register allocated to hold the subroutine return address
+ */
+ int topAddr;
+ int onceAddr = 0;
+ int retAddr;
+ struct SrcList_item *pPrior;
+
+ testcase( pItem->addrFillSub==0 ); /* Ticket c52b09c7f38903b1311 */
+ pItem->regReturn = ++pParse->nMem;
+ topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
+ pItem->addrFillSub = topAddr+1;
+ if( pItem->fg.isCorrelated==0 ){
+ /* If the subquery is not correlated and if we are not inside of
+ ** a trigger, then we only need to compute the value of the subquery
+ ** once. */
+ onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
+ VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
+ }else{
+ VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
+ }
+ pPrior = isSelfJoinView(pTabList, pItem);
+ if( pPrior ){
+ sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
+ assert( pPrior->pSelect!=0 );
+ pSub->nSelectRow = pPrior->pSelect->nSelectRow;
+ }else{
+ sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
+ ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId));
+ sqlite3Select(pParse, pSub, &dest);
+ }
+ pItem->pTab->nRowLogEst = pSub->nSelectRow;
+ if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
+ retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
+ VdbeComment((v, "end %s", pItem->pTab->zName));
+ sqlite3VdbeChangeP1(v, topAddr, retAddr);
+ sqlite3ClearTempRegCache(pParse);
+ }
+ if( db->mallocFailed ) goto select_end;
+ pParse->nHeight -= sqlite3SelectExprHeight(p);
+ pParse->zAuthContext = zSavedAuthContext;
+#endif
+ }
+
+ /* Various elements of the SELECT copied into local variables for
+ ** convenience */
+ pEList = p->pEList;
+ pWhere = p->pWhere;
+ pGroupBy = p->pGroupBy;
+ pHaving = p->pHaving;
+ sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
+
+#if SELECTTRACE_ENABLED
+ if( sqlite3_unsupported_selecttrace & 0x400 ){
+ SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
+ sqlite3TreeViewSelect(0, p, 0);
+ }
+#endif
+
+ /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
+ ** if the select-list is the same as the ORDER BY list, then this query
+ ** can be rewritten as a GROUP BY. In other words, this:
+ **
+ ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
+ **
+ ** is transformed to:
+ **
+ ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
+ **
+ ** The second form is preferred as a single index (or temp-table) may be
+ ** used for both the ORDER BY and DISTINCT processing. As originally
+ ** written the query must use a temp-table for at least one of the ORDER
+ ** BY and DISTINCT, and an index or separate temp-table for the other.
+ */
+ if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
+ && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ && p->pWin==0
+#endif
+ ){
+ p->selFlags &= ~SF_Distinct;
+ pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
+ p->selFlags |= SF_Aggregate;
+ /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
+ ** the sDistinct.isTnct is still set. Hence, isTnct represents the
+ ** original setting of the SF_Distinct flag, not the current setting */
+ assert( sDistinct.isTnct );
+
+#if SELECTTRACE_ENABLED
+ if( sqlite3_unsupported_selecttrace & 0x400 ){
+ SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
+ sqlite3TreeViewSelect(0, p, 0);
+ }
+#endif
+ }
+
+ /* If there is an ORDER BY clause, then create an ephemeral index to
+ ** do the sorting. But this sorting ephemeral index might end up
+ ** being unused if the data can be extracted in pre-sorted order.
+ ** If that is the case, then the OP_OpenEphemeral instruction will be
+ ** changed to an OP_Noop once we figure out that the sorting index is
+ ** not needed. The sSort.addrSortIndex variable is used to facilitate
+ ** that change.
+ */
+ if( sSort.pOrderBy ){
+ KeyInfo *pKeyInfo;
+ pKeyInfo = sqlite3KeyInfoFromExprList(
+ pParse, sSort.pOrderBy, 0, pEList->nExpr);
+ sSort.iECursor = pParse->nTab++;
+ sSort.addrSortIndex =
+ sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
+ sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
+ (char*)pKeyInfo, P4_KEYINFO
+ );
+ }else{
+ sSort.addrSortIndex = -1;
+ }
+
+ /* If the output is destined for a temporary table, open that table.
+ */
+ if( pDest->eDest==SRT_EphemTab ){
+ sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
+ }
+
+ /* Set the limiter.
+ */
+ iEnd = sqlite3VdbeMakeLabel(pParse);
+ if( (p->selFlags & SF_FixedLimit)==0 ){
+ p->nSelectRow = 320; /* 4 billion rows */
+ }
+ computeLimitRegisters(pParse, p, iEnd);
+ if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
+ sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
+ sSort.sortFlags |= SORTFLAG_UseSorter;
+ }
+
+ /* Open an ephemeral index to use for the distinct set.
+ */
+ if( p->selFlags & SF_Distinct ){
+ sDistinct.tabTnct = pParse->nTab++;
+ sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
+ sDistinct.tabTnct, 0, 0,
+ (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
+ P4_KEYINFO);
+ sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
+ sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
+ }else{
+ sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
+ }
+
+ if( !isAgg && pGroupBy==0 ){
+ /* No aggregate functions and no GROUP BY clause */
+ u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
+ | (p->selFlags & SF_FixedLimit);
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ Window *pWin = p->pWin; /* Main window object (or NULL) */
+ if( pWin ){
+ sqlite3WindowCodeInit(pParse, p);
+ }
+#endif
+ assert( WHERE_USE_LIMIT==SF_FixedLimit );
+
+
+ /* Begin the database scan. */
+ SELECTTRACE(1,pParse,p,("WhereBegin\n"));
+ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
+ p->pEList, wctrlFlags, p->nSelectRow);
+ if( pWInfo==0 ) goto select_end;
+ if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
+ p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
+ }
+ if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
+ sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
+ }
+ if( sSort.pOrderBy ){
+ sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
+ sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
+ if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
+ sSort.pOrderBy = 0;
+ }
+ }
+
+ /* If sorting index that was created by a prior OP_OpenEphemeral
+ ** instruction ended up not being needed, then change the OP_OpenEphemeral
+ ** into an OP_Noop.
+ */
+ if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
+ sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
+ }
+
+ assert( p->pEList==pEList );
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( pWin ){
+ int addrGosub = sqlite3VdbeMakeLabel(pParse);
+ int iCont = sqlite3VdbeMakeLabel(pParse);
+ int iBreak = sqlite3VdbeMakeLabel(pParse);
+ int regGosub = ++pParse->nMem;
+
+ sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
+
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
+ sqlite3VdbeResolveLabel(v, addrGosub);
+ VdbeNoopComment((v, "inner-loop subroutine"));
+ sSort.labelOBLopt = 0;
+ selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
+ sqlite3VdbeResolveLabel(v, iCont);
+ sqlite3VdbeAddOp1(v, OP_Return, regGosub);
+ VdbeComment((v, "end inner-loop subroutine"));
+ sqlite3VdbeResolveLabel(v, iBreak);
+ }else
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+ {
+ /* Use the standard inner loop. */
+ selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
+ sqlite3WhereContinueLabel(pWInfo),
+ sqlite3WhereBreakLabel(pWInfo));
+
+ /* End the database scan loop.
+ */
+ sqlite3WhereEnd(pWInfo);
+ }
+ }else{
+ /* This case when there exist aggregate functions or a GROUP BY clause
+ ** or both */
+ NameContext sNC; /* Name context for processing aggregate information */
+ int iAMem; /* First Mem address for storing current GROUP BY */
+ int iBMem; /* First Mem address for previous GROUP BY */
+ int iUseFlag; /* Mem address holding flag indicating that at least
+ ** one row of the input to the aggregator has been
+ ** processed */
+ int iAbortFlag; /* Mem address which causes query abort if positive */
+ int groupBySort; /* Rows come from source in GROUP BY order */
+ int addrEnd; /* End of processing for this SELECT */
+ int sortPTab = 0; /* Pseudotable used to decode sorting results */
+ int sortOut = 0; /* Output register from the sorter */
+ int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
+
+ /* Remove any and all aliases between the result set and the
+ ** GROUP BY clause.
+ */
+ if( pGroupBy ){
+ int k; /* Loop counter */
+ struct ExprList_item *pItem; /* For looping over expression in a list */
+
+ for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
+ pItem->u.x.iAlias = 0;
+ }
+ for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
+ pItem->u.x.iAlias = 0;
+ }
+ assert( 66==sqlite3LogEst(100) );
+ if( p->nSelectRow>66 ) p->nSelectRow = 66;
+
+ /* If there is both a GROUP BY and an ORDER BY clause and they are
+ ** identical, then it may be possible to disable the ORDER BY clause
+ ** on the grounds that the GROUP BY will cause elements to come out
+ ** in the correct order. It also may not - the GROUP BY might use a
+ ** database index that causes rows to be grouped together as required
+ ** but not actually sorted. Either way, record the fact that the
+ ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
+ ** variable. */
+ if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){
+ int ii;
+ /* The GROUP BY processing doesn't care whether rows are delivered in
+ ** ASC or DESC order - only that each group is returned contiguously.
+ ** So set the ASC/DESC flags in the GROUP BY to match those in the
+ ** ORDER BY to maximize the chances of rows being delivered in an
+ ** order that makes the ORDER BY redundant. */
+ for(ii=0; ii<pGroupBy->nExpr; ii++){
+ u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC;
+ pGroupBy->a[ii].sortFlags = sortFlags;
+ }
+ if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
+ orderByGrp = 1;
+ }
+ }
+ }else{
+ assert( 0==sqlite3LogEst(1) );
+ p->nSelectRow = 0;
+ }
+
+ /* Create a label to jump to when we want to abort the query */
+ addrEnd = sqlite3VdbeMakeLabel(pParse);
+
+ /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
+ ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
+ ** SELECT statement.
+ */
+ pAggInfo = sqlite3DbMallocZero(db, sizeof(*pAggInfo) );
+ if( pAggInfo==0 ){
+ goto select_end;
+ }
+ pAggInfo->pNext = pParse->pAggList;
+ pParse->pAggList = pAggInfo;
+ pAggInfo->selId = p->selId;
+ memset(&sNC, 0, sizeof(sNC));
+ sNC.pParse = pParse;
+ sNC.pSrcList = pTabList;
+ sNC.uNC.pAggInfo = pAggInfo;
+ VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
+ pAggInfo->mnReg = pParse->nMem+1;
+ pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
+ pAggInfo->pGroupBy = pGroupBy;
+ sqlite3ExprAnalyzeAggList(&sNC, pEList);
+ sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
+ if( pHaving ){
+ if( pGroupBy ){
+ assert( pWhere==p->pWhere );
+ assert( pHaving==p->pHaving );
+ assert( pGroupBy==p->pGroupBy );
+ havingToWhere(pParse, p);
+ pWhere = p->pWhere;
+ }
+ sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
+ }
+ pAggInfo->nAccumulator = pAggInfo->nColumn;
+ if( p->pGroupBy==0 && p->pHaving==0 && pAggInfo->nFunc==1 ){
+ minMaxFlag = minMaxQuery(db, pAggInfo->aFunc[0].pFExpr, &pMinMaxOrderBy);
+ }else{
+ minMaxFlag = WHERE_ORDERBY_NORMAL;
+ }
+ for(i=0; i<pAggInfo->nFunc; i++){
+ Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
+ assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
+ sNC.ncFlags |= NC_InAggFunc;
+ sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList);
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ assert( !IsWindowFunc(pExpr) );
+ if( ExprHasProperty(pExpr, EP_WinFunc) ){
+ sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter);
+ }
+#endif
+ sNC.ncFlags &= ~NC_InAggFunc;
+ }
+ pAggInfo->mxReg = pParse->nMem;
+ if( db->mallocFailed ) goto select_end;
+#if SELECTTRACE_ENABLED
+ if( sqlite3_unsupported_selecttrace & 0x400 ){
+ int ii;
+ SELECTTRACE(0x400,pParse,p,("After aggregate analysis %p:\n", pAggInfo));
+ sqlite3TreeViewSelect(0, p, 0);
+ for(ii=0; ii<pAggInfo->nColumn; ii++){
+ sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
+ ii, pAggInfo->aCol[ii].iMem);
+ sqlite3TreeViewExpr(0, pAggInfo->aCol[ii].pCExpr, 0);
+ }
+ for(ii=0; ii<pAggInfo->nFunc; ii++){
+ sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
+ ii, pAggInfo->aFunc[ii].iMem);
+ sqlite3TreeViewExpr(0, pAggInfo->aFunc[ii].pFExpr, 0);
+ }
+ }
+#endif
+
+
+ /* Processing for aggregates with GROUP BY is very different and
+ ** much more complex than aggregates without a GROUP BY.
+ */
+ if( pGroupBy ){
+ KeyInfo *pKeyInfo; /* Keying information for the group by clause */
+ int addr1; /* A-vs-B comparision jump */
+ int addrOutputRow; /* Start of subroutine that outputs a result row */
+ int regOutputRow; /* Return address register for output subroutine */
+ int addrSetAbort; /* Set the abort flag and return */
+ int addrTopOfLoop; /* Top of the input loop */
+ int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
+ int addrReset; /* Subroutine for resetting the accumulator */
+ int regReset; /* Return address register for reset subroutine */
+
+ /* If there is a GROUP BY clause we might need a sorting index to
+ ** implement it. Allocate that sorting index now. If it turns out
+ ** that we do not need it after all, the OP_SorterOpen instruction
+ ** will be converted into a Noop.
+ */
+ pAggInfo->sortingIdx = pParse->nTab++;
+ pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pGroupBy,
+ 0, pAggInfo->nColumn);
+ addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
+ pAggInfo->sortingIdx, pAggInfo->nSortingColumn,
+ 0, (char*)pKeyInfo, P4_KEYINFO);
+
+ /* Initialize memory locations used by GROUP BY aggregate processing
+ */
+ iUseFlag = ++pParse->nMem;
+ iAbortFlag = ++pParse->nMem;
+ regOutputRow = ++pParse->nMem;
+ addrOutputRow = sqlite3VdbeMakeLabel(pParse);
+ regReset = ++pParse->nMem;
+ addrReset = sqlite3VdbeMakeLabel(pParse);
+ iAMem = pParse->nMem + 1;
+ pParse->nMem += pGroupBy->nExpr;
+ iBMem = pParse->nMem + 1;
+ pParse->nMem += pGroupBy->nExpr;
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
+ VdbeComment((v, "clear abort flag"));
+ sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
+
+ /* Begin a loop that will extract all source rows in GROUP BY order.
+ ** This might involve two separate loops with an OP_Sort in between, or
+ ** it might be a single loop that uses an index to extract information
+ ** in the right order to begin with.
+ */
+ sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
+ SELECTTRACE(1,pParse,p,("WhereBegin\n"));
+ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
+ WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
+ );
+ if( pWInfo==0 ) goto select_end;
+ if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
+ /* The optimizer is able to deliver rows in group by order so
+ ** we do not have to sort. The OP_OpenEphemeral table will be
+ ** cancelled later because we still need to use the pKeyInfo
+ */
+ groupBySort = 0;
+ }else{
+ /* Rows are coming out in undetermined order. We have to push
+ ** each row into a sorting index, terminate the first loop,
+ ** then loop over the sorting index in order to get the output
+ ** in sorted order
+ */
+ int regBase;
+ int regRecord;
+ int nCol;
+ int nGroupBy;
+
+ explainTempTable(pParse,
+ (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
+ "DISTINCT" : "GROUP BY");
+
+ groupBySort = 1;
+ nGroupBy = pGroupBy->nExpr;
+ nCol = nGroupBy;
+ j = nGroupBy;
+ for(i=0; i<pAggInfo->nColumn; i++){
+ if( pAggInfo->aCol[i].iSorterColumn>=j ){
+ nCol++;
+ j++;
+ }
+ }
+ regBase = sqlite3GetTempRange(pParse, nCol);
+ sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
+ j = nGroupBy;
+ for(i=0; i<pAggInfo->nColumn; i++){
+ struct AggInfo_col *pCol = &pAggInfo->aCol[i];
+ if( pCol->iSorterColumn>=j ){
+ int r1 = j + regBase;
+ sqlite3ExprCodeGetColumnOfTable(v,
+ pCol->pTab, pCol->iTable, pCol->iColumn, r1);
+ j++;
+ }
+ }
+ regRecord = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
+ sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord);
+ sqlite3ReleaseTempReg(pParse, regRecord);
+ sqlite3ReleaseTempRange(pParse, regBase, nCol);
+ sqlite3WhereEnd(pWInfo);
+ pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++;
+ sortOut = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
+ sqlite3VdbeAddOp2(v, OP_SorterSort, pAggInfo->sortingIdx, addrEnd);
+ VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
+ pAggInfo->useSortingIdx = 1;
+ }
+
+ /* If the index or temporary table used by the GROUP BY sort
+ ** will naturally deliver rows in the order required by the ORDER BY
+ ** clause, cancel the ephemeral table open coded earlier.
+ **
+ ** This is an optimization - the correct answer should result regardless.
+ ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
+ ** disable this optimization for testing purposes. */
+ if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
+ && (groupBySort || sqlite3WhereIsSorted(pWInfo))
+ ){
+ sSort.pOrderBy = 0;
+ sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
+ }
+
+ /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
+ ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
+ ** Then compare the current GROUP BY terms against the GROUP BY terms
+ ** from the previous row currently stored in a0, a1, a2...
+ */
+ addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
+ if( groupBySort ){
+ sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx,
+ sortOut, sortPTab);
+ }
+ for(j=0; j<pGroupBy->nExpr; j++){
+ if( groupBySort ){
+ sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
+ }else{
+ pAggInfo->directMode = 1;
+ sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
+ }
+ }
+ sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
+ (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
+ addr1 = sqlite3VdbeCurrentAddr(v);
+ sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
+
+ /* Generate code that runs whenever the GROUP BY changes.
+ ** Changes in the GROUP BY are detected by the previous code
+ ** block. If there were no changes, this block is skipped.
+ **
+ ** This code copies current group by terms in b0,b1,b2,...
+ ** over to a0,a1,a2. It then calls the output subroutine
+ ** and resets the aggregate accumulator registers in preparation
+ ** for the next GROUP BY batch.
+ */
+ sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
+ sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
+ VdbeComment((v, "output one row"));
+ sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
+ VdbeComment((v, "check abort flag"));
+ sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
+ VdbeComment((v, "reset accumulator"));
+
+ /* Update the aggregate accumulators based on the content of
+ ** the current row
+ */
+ sqlite3VdbeJumpHere(v, addr1);
+ updateAccumulator(pParse, iUseFlag, pAggInfo);
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
+ VdbeComment((v, "indicate data in accumulator"));
+
+ /* End of the loop
+ */
+ if( groupBySort ){
+ sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx, addrTopOfLoop);
+ VdbeCoverage(v);
+ }else{
+ sqlite3WhereEnd(pWInfo);
+ sqlite3VdbeChangeToNoop(v, addrSortingIdx);
+ }
+
+ /* Output the final row of result
+ */
+ sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
+ VdbeComment((v, "output final row"));
+
+ /* Jump over the subroutines
+ */
+ sqlite3VdbeGoto(v, addrEnd);
+
+ /* Generate a subroutine that outputs a single row of the result
+ ** set. This subroutine first looks at the iUseFlag. If iUseFlag
+ ** is less than or equal to zero, the subroutine is a no-op. If
+ ** the processing calls for the query to abort, this subroutine
+ ** increments the iAbortFlag memory location before returning in
+ ** order to signal the caller to abort.
+ */
+ addrSetAbort = sqlite3VdbeCurrentAddr(v);
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
+ VdbeComment((v, "set abort flag"));
+ sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
+ sqlite3VdbeResolveLabel(v, addrOutputRow);
+ addrOutputRow = sqlite3VdbeCurrentAddr(v);
+ sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
+ VdbeCoverage(v);
+ VdbeComment((v, "Groupby result generator entry point"));
+ sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
+ finalizeAggFunctions(pParse, pAggInfo);
+ sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
+ selectInnerLoop(pParse, p, -1, &sSort,
+ &sDistinct, pDest,
+ addrOutputRow+1, addrSetAbort);
+ sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
+ VdbeComment((v, "end groupby result generator"));
+
+ /* Generate a subroutine that will reset the group-by accumulator
+ */
+ sqlite3VdbeResolveLabel(v, addrReset);
+ resetAccumulator(pParse, pAggInfo);
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
+ VdbeComment((v, "indicate accumulator empty"));
+ sqlite3VdbeAddOp1(v, OP_Return, regReset);
+
+ } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
+ else {
+ Table *pTab;
+ if( (pTab = isSimpleCount(p, pAggInfo))!=0 ){
+ /* If isSimpleCount() returns a pointer to a Table structure, then
+ ** the SQL statement is of the form:
+ **
+ ** SELECT count(*) FROM <tbl>
+ **
+ ** where the Table structure returned represents table <tbl>.
+ **
+ ** This statement is so common that it is optimized specially. The
+ ** OP_Count instruction is executed either on the intkey table that
+ ** contains the data for table <tbl> or on one of its indexes. It
+ ** is better to execute the op on an index, as indexes are almost
+ ** always spread across less pages than their corresponding tables.
+ */
+ const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
+ const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
+ Index *pIdx; /* Iterator variable */
+ KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
+ Index *pBest = 0; /* Best index found so far */
+ Pgno iRoot = pTab->tnum; /* Root page of scanned b-tree */
+
+ sqlite3CodeVerifySchema(pParse, iDb);
+ sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
+
+ /* Search for the index that has the lowest scan cost.
+ **
+ ** (2011-04-15) Do not do a full scan of an unordered index.
+ **
+ ** (2013-10-03) Do not count the entries in a partial index.
+ **
+ ** In practice the KeyInfo structure will not be used. It is only
+ ** passed to keep OP_OpenRead happy.
+ */
+ if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
+ if( !p->pSrc->a[0].fg.notIndexed ){
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+ if( pIdx->bUnordered==0
+ && pIdx->szIdxRow<pTab->szTabRow
+ && pIdx->pPartIdxWhere==0
+ && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
+ ){
+ pBest = pIdx;
+ }
+ }
+ }
+ if( pBest ){
+ iRoot = pBest->tnum;
+ pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
+ }
+
+ /* Open a read-only cursor, execute the OP_Count, close the cursor. */
+ sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, (int)iRoot, iDb, 1);
+ if( pKeyInfo ){
+ sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
+ }
+ sqlite3VdbeAddOp2(v, OP_Count, iCsr, pAggInfo->aFunc[0].iMem);
+ sqlite3VdbeAddOp1(v, OP_Close, iCsr);
+ explainSimpleCount(pParse, pTab, pBest);
+ }else{
+ int regAcc = 0; /* "populate accumulators" flag */
+ int addrSkip;
+
+ /* If there are accumulator registers but no min() or max() functions
+ ** without FILTER clauses, allocate register regAcc. Register regAcc
+ ** will contain 0 the first time the inner loop runs, and 1 thereafter.
+ ** The code generated by updateAccumulator() uses this to ensure
+ ** that the accumulator registers are (a) updated only once if
+ ** there are no min() or max functions or (b) always updated for the
+ ** first row visited by the aggregate, so that they are updated at
+ ** least once even if the FILTER clause means the min() or max()
+ ** function visits zero rows. */
+ if( pAggInfo->nAccumulator ){
+ for(i=0; i<pAggInfo->nFunc; i++){
+ if( ExprHasProperty(pAggInfo->aFunc[i].pFExpr, EP_WinFunc) ){
+ continue;
+ }
+ if( pAggInfo->aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ){
+ break;
+ }
+ }
+ if( i==pAggInfo->nFunc ){
+ regAcc = ++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
+ }
+ }
+
+ /* This case runs if the aggregate has no GROUP BY clause. The
+ ** processing is much simpler since there is only a single row
+ ** of output.
+ */
+ assert( p->pGroupBy==0 );
+ resetAccumulator(pParse, pAggInfo);
+
+ /* If this query is a candidate for the min/max optimization, then
+ ** minMaxFlag will have been previously set to either
+ ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
+ ** be an appropriate ORDER BY expression for the optimization.
+ */
+ assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
+ assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
+
+ SELECTTRACE(1,pParse,p,("WhereBegin\n"));
+ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
+ 0, minMaxFlag, 0);
+ if( pWInfo==0 ){
+ goto select_end;
+ }
+ updateAccumulator(pParse, regAcc, pAggInfo);
+ if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
+ addrSkip = sqlite3WhereOrderByLimitOptLabel(pWInfo);
+ if( addrSkip!=sqlite3WhereContinueLabel(pWInfo) ){
+ sqlite3VdbeGoto(v, addrSkip);
+ }
+ sqlite3WhereEnd(pWInfo);
+ finalizeAggFunctions(pParse, pAggInfo);
+ }
+
+ sSort.pOrderBy = 0;
+ sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
+ selectInnerLoop(pParse, p, -1, 0, 0,
+ pDest, addrEnd, addrEnd);
+ }
+ sqlite3VdbeResolveLabel(v, addrEnd);
+
+ } /* endif aggregate query */
+
+ if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
+ explainTempTable(pParse, "DISTINCT");
+ }
+
+ /* If there is an ORDER BY clause, then we need to sort the results
+ ** and send them to the callback one by one.
+ */
+ if( sSort.pOrderBy ){
+ explainTempTable(pParse,
+ sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
+ assert( p->pEList==pEList );
+ generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
+ }
+
+ /* Jump here to skip this query
+ */
+ sqlite3VdbeResolveLabel(v, iEnd);
+
+ /* The SELECT has been coded. If there is an error in the Parse structure,
+ ** set the return code to 1. Otherwise 0. */
+ rc = (pParse->nErr>0);
+
+ /* Control jumps to here if an error is encountered above, or upon
+ ** successful coding of the SELECT.
+ */
+select_end:
+ sqlite3ExprListDelete(db, pMinMaxOrderBy);
+#ifdef SQLITE_DEBUG
+ if( pAggInfo && !db->mallocFailed ){
+ for(i=0; i<pAggInfo->nColumn; i++){
+ Expr *pExpr = pAggInfo->aCol[i].pCExpr;
+ assert( pExpr!=0 || db->mallocFailed );
+ if( pExpr==0 ) continue;
+ assert( pExpr->pAggInfo==pAggInfo );
+ assert( pExpr->iAgg==i );
+ }
+ for(i=0; i<pAggInfo->nFunc; i++){
+ Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
+ assert( pExpr!=0 || db->mallocFailed );
+ if( pExpr==0 ) continue;
+ assert( pExpr->pAggInfo==pAggInfo );
+ assert( pExpr->iAgg==i );
+ }
+ }
+#endif
+
+#if SELECTTRACE_ENABLED
+ SELECTTRACE(0x1,pParse,p,("end processing\n"));
+ if( (sqlite3_unsupported_selecttrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
+ sqlite3TreeViewSelect(0, p, 0);
+ }
+#endif
+ ExplainQueryPlanPop(pParse);
+ return rc;
+}
+
+/************** End of select.c **********************************************/
+/************** Begin file table.c *******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains the sqlite3_get_table() and sqlite3_free_table()
+** interface routines. These are just wrappers around the main
+** interface routine of sqlite3_exec().
+**
+** These routines are in a separate files so that they will not be linked
+** if they are not used.
+*/
+/* #include "sqliteInt.h" */
+
+#ifndef SQLITE_OMIT_GET_TABLE
+
+/*
+** This structure is used to pass data from sqlite3_get_table() through
+** to the callback function is uses to build the result.
+*/
+typedef struct TabResult {
+ char **azResult; /* Accumulated output */
+ char *zErrMsg; /* Error message text, if an error occurs */
+ u32 nAlloc; /* Slots allocated for azResult[] */
+ u32 nRow; /* Number of rows in the result */
+ u32 nColumn; /* Number of columns in the result */
+ u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
+ int rc; /* Return code from sqlite3_exec() */
+} TabResult;
+
+/*
+** This routine is called once for each row in the result table. Its job
+** is to fill in the TabResult structure appropriately, allocating new
+** memory as necessary.
+*/
+static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
+ TabResult *p = (TabResult*)pArg; /* Result accumulator */
+ int need; /* Slots needed in p->azResult[] */
+ int i; /* Loop counter */
+ char *z; /* A single column of result */
+
+ /* Make sure there is enough space in p->azResult to hold everything
+ ** we need to remember from this invocation of the callback.
+ */
+ if( p->nRow==0 && argv!=0 ){
+ need = nCol*2;
+ }else{
+ need = nCol;
+ }
+ if( p->nData + need > p->nAlloc ){
+ char **azNew;
+ p->nAlloc = p->nAlloc*2 + need;
+ azNew = sqlite3Realloc( p->azResult, sizeof(char*)*p->nAlloc );
+ if( azNew==0 ) goto malloc_failed;
+ p->azResult = azNew;
+ }
+
+ /* If this is the first row, then generate an extra row containing
+ ** the names of all columns.
+ */
+ if( p->nRow==0 ){
+ p->nColumn = nCol;
+ for(i=0; i<nCol; i++){
+ z = sqlite3_mprintf("%s", colv[i]);
+ if( z==0 ) goto malloc_failed;
+ p->azResult[p->nData++] = z;
+ }
+ }else if( (int)p->nColumn!=nCol ){
+ sqlite3_free(p->zErrMsg);
+ p->zErrMsg = sqlite3_mprintf(
+ "sqlite3_get_table() called with two or more incompatible queries"
+ );
+ p->rc = SQLITE_ERROR;
+ return 1;
+ }
+
+ /* Copy over the row data
+ */
+ if( argv!=0 ){
+ for(i=0; i<nCol; i++){
+ if( argv[i]==0 ){
+ z = 0;
+ }else{
+ int n = sqlite3Strlen30(argv[i])+1;
+ z = sqlite3_malloc64( n );
+ if( z==0 ) goto malloc_failed;
+ memcpy(z, argv[i], n);
+ }
+ p->azResult[p->nData++] = z;
+ }
+ p->nRow++;
+ }
+ return 0;
+
+malloc_failed:
+ p->rc = SQLITE_NOMEM_BKPT;
+ return 1;
+}
+
+/*
+** Query the database. But instead of invoking a callback for each row,
+** malloc() for space to hold the result and return the entire results
+** at the conclusion of the call.
+**
+** The result that is written to ***pazResult is held in memory obtained
+** from malloc(). But the caller cannot free this memory directly.
+** Instead, the entire table should be passed to sqlite3_free_table() when
+** the calling procedure is finished using it.
+*/
+SQLITE_API int sqlite3_get_table(
+ sqlite3 *db, /* The database on which the SQL executes */
+ const char *zSql, /* The SQL to be executed */
+ char ***pazResult, /* Write the result table here */
+ int *pnRow, /* Write the number of rows in the result here */
+ int *pnColumn, /* Write the number of columns of result here */
+ char **pzErrMsg /* Write error messages here */
+){
+ int rc;
+ TabResult res;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
+#endif
+ *pazResult = 0;
+ if( pnColumn ) *pnColumn = 0;
+ if( pnRow ) *pnRow = 0;
+ if( pzErrMsg ) *pzErrMsg = 0;
+ res.zErrMsg = 0;
+ res.nRow = 0;
+ res.nColumn = 0;
+ res.nData = 1;
+ res.nAlloc = 20;
+ res.rc = SQLITE_OK;
+ res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
+ if( res.azResult==0 ){
+ db->errCode = SQLITE_NOMEM;
+ return SQLITE_NOMEM_BKPT;
+ }
+ res.azResult[0] = 0;
+ rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
+ assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
+ res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
+ if( (rc&0xff)==SQLITE_ABORT ){
+ sqlite3_free_table(&res.azResult[1]);
+ if( res.zErrMsg ){
+ if( pzErrMsg ){
+ sqlite3_free(*pzErrMsg);
+ *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
+ }
+ sqlite3_free(res.zErrMsg);
+ }
+ db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
+ return res.rc;
+ }
+ sqlite3_free(res.zErrMsg);
+ if( rc!=SQLITE_OK ){
+ sqlite3_free_table(&res.azResult[1]);
+ return rc;
+ }
+ if( res.nAlloc>res.nData ){
+ char **azNew;
+ azNew = sqlite3Realloc( res.azResult, sizeof(char*)*res.nData );
+ if( azNew==0 ){
+ sqlite3_free_table(&res.azResult[1]);
+ db->errCode = SQLITE_NOMEM;
+ return SQLITE_NOMEM_BKPT;
+ }
+ res.azResult = azNew;
+ }
+ *pazResult = &res.azResult[1];
+ if( pnColumn ) *pnColumn = res.nColumn;
+ if( pnRow ) *pnRow = res.nRow;
+ return rc;
+}
+
+/*
+** This routine frees the space the sqlite3_get_table() malloced.
+*/
+SQLITE_API void sqlite3_free_table(
+ char **azResult /* Result returned from sqlite3_get_table() */
+){
+ if( azResult ){
+ int i, n;
+ azResult--;
+ assert( azResult!=0 );
+ n = SQLITE_PTR_TO_INT(azResult[0]);
+ for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
+ sqlite3_free(azResult);
+ }
+}
+
+#endif /* SQLITE_OMIT_GET_TABLE */
+
+/************** End of table.c ***********************************************/
+/************** Begin file trigger.c *****************************************/
+/*
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains the implementation for TRIGGERs
+*/
+/* #include "sqliteInt.h" */
+
+#ifndef SQLITE_OMIT_TRIGGER
+/*
+** Delete a linked list of TriggerStep structures.
+*/
+SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
+ while( pTriggerStep ){
+ TriggerStep * pTmp = pTriggerStep;
+ pTriggerStep = pTriggerStep->pNext;
+
+ sqlite3ExprDelete(db, pTmp->pWhere);
+ sqlite3ExprListDelete(db, pTmp->pExprList);
+ sqlite3SelectDelete(db, pTmp->pSelect);
+ sqlite3IdListDelete(db, pTmp->pIdList);
+ sqlite3UpsertDelete(db, pTmp->pUpsert);
+ sqlite3SrcListDelete(db, pTmp->pFrom);
+ sqlite3DbFree(db, pTmp->zSpan);
+
+ sqlite3DbFree(db, pTmp);
+ }
+}
+
+/*
+** Given table pTab, return a list of all the triggers attached to
+** the table. The list is connected by Trigger.pNext pointers.
+**
+** All of the triggers on pTab that are in the same database as pTab
+** are already attached to pTab->pTrigger. But there might be additional
+** triggers on pTab in the TEMP schema. This routine prepends all
+** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
+** and returns the combined list.
+**
+** To state it another way: This routine returns a list of all triggers
+** that fire off of pTab. The list will include any TEMP triggers on
+** pTab as well as the triggers lised in pTab->pTrigger.
+*/
+SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
+ Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
+ Trigger *pList = 0; /* List of triggers to return */
+
+ if( pParse->disableTriggers ){
+ return 0;
+ }
+
+ if( pTmpSchema!=pTab->pSchema ){
+ HashElem *p;
+ assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
+ for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
+ Trigger *pTrig = (Trigger *)sqliteHashData(p);
+ if( pTrig->pTabSchema==pTab->pSchema
+ && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
+ ){
+ pTrig->pNext = (pList ? pList : pTab->pTrigger);
+ pList = pTrig;
+ }
+ }
+ }
+
+ return (pList ? pList : pTab->pTrigger);
+}
+
+/*
+** This is called by the parser when it sees a CREATE TRIGGER statement
+** up to the point of the BEGIN before the trigger actions. A Trigger
+** structure is generated based on the information available and stored
+** in pParse->pNewTrigger. After the trigger actions have been parsed, the
+** sqlite3FinishTrigger() function is called to complete the trigger
+** construction process.
+*/
+SQLITE_PRIVATE void sqlite3BeginTrigger(
+ Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
+ Token *pName1, /* The name of the trigger */
+ Token *pName2, /* The name of the trigger */
+ int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
+ int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
+ IdList *pColumns, /* column list if this is an UPDATE OF trigger */
+ SrcList *pTableName,/* The name of the table/view the trigger applies to */
+ Expr *pWhen, /* WHEN clause */
+ int isTemp, /* True if the TEMPORARY keyword is present */
+ int noErr /* Suppress errors if the trigger already exists */
+){
+ Trigger *pTrigger = 0; /* The new trigger */
+ Table *pTab; /* Table that the trigger fires off of */
+ char *zName = 0; /* Name of the trigger */
+ sqlite3 *db = pParse->db; /* The database connection */
+ int iDb; /* The database to store the trigger in */
+ Token *pName; /* The unqualified db name */
+ DbFixer sFix; /* State vector for the DB fixer */
+
+ assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
+ assert( pName2!=0 );
+ assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
+ assert( op>0 && op<0xff );
+ if( isTemp ){
+ /* If TEMP was specified, then the trigger name may not be qualified. */
+ if( pName2->n>0 ){
+ sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
+ goto trigger_cleanup;
+ }
+ iDb = 1;
+ pName = pName1;
+ }else{
+ /* Figure out the db that the trigger will be created in */
+ iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
+ if( iDb<0 ){
+ goto trigger_cleanup;
+ }
+ }
+ if( !pTableName || db->mallocFailed ){
+ goto trigger_cleanup;
+ }
+
+ /* A long-standing parser bug is that this syntax was allowed:
+ **
+ ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
+ ** ^^^^^^^^
+ **
+ ** To maintain backwards compatibility, ignore the database
+ ** name on pTableName if we are reparsing out of the schema table
+ */
+ if( db->init.busy && iDb!=1 ){
+ sqlite3DbFree(db, pTableName->a[0].zDatabase);
+ pTableName->a[0].zDatabase = 0;
+ }
+
+ /* If the trigger name was unqualified, and the table is a temp table,
+ ** then set iDb to 1 to create the trigger in the temporary database.
+ ** If sqlite3SrcListLookup() returns 0, indicating the table does not
+ ** exist, the error is caught by the block below.
+ */
+ pTab = sqlite3SrcListLookup(pParse, pTableName);
+ if( db->init.busy==0 && pName2->n==0 && pTab
+ && pTab->pSchema==db->aDb[1].pSchema ){
+ iDb = 1;
+ }
+
+ /* Ensure the table name matches database name and that the table exists */
+ if( db->mallocFailed ) goto trigger_cleanup;
+ assert( pTableName->nSrc==1 );
+ sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
+ if( sqlite3FixSrcList(&sFix, pTableName) ){
+ goto trigger_cleanup;
+ }
+ pTab = sqlite3SrcListLookup(pParse, pTableName);
+ if( !pTab ){
+ /* The table does not exist. */
+ if( db->init.iDb==1 ){
+ /* Ticket #3810.
+ ** Normally, whenever a table is dropped, all associated triggers are
+ ** dropped too. But if a TEMP trigger is created on a non-TEMP table
+ ** and the table is dropped by a different database connection, the
+ ** trigger is not visible to the database connection that does the
+ ** drop so the trigger cannot be dropped. This results in an
+ ** "orphaned trigger" - a trigger whose associated table is missing.
+ */
+ db->init.orphanTrigger = 1;
+ }
+ goto trigger_cleanup;
+ }
+ if( IsVirtual(pTab) ){
+ sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
+ goto trigger_cleanup;
+ }
+
+ /* Check that the trigger name is not reserved and that no trigger of the
+ ** specified name exists */
+ zName = sqlite3NameFromToken(db, pName);
+ if( zName==0 ){
+ assert( db->mallocFailed );
+ goto trigger_cleanup;
+ }
+ if( sqlite3CheckObjectName(pParse, zName, "trigger", pTab->zName) ){
+ goto trigger_cleanup;
+ }
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ if( !IN_RENAME_OBJECT ){
+ if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
+ if( !noErr ){
+ sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
+ }else{
+ assert( !db->init.busy );
+ sqlite3CodeVerifySchema(pParse, iDb);
+ }
+ goto trigger_cleanup;
+ }
+ }
+
+ /* Do not create a trigger on a system table */
+ if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
+ sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
+ goto trigger_cleanup;
+ }
+
+ /* INSTEAD of triggers are only for views and views only support INSTEAD
+ ** of triggers.
+ */
+ if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
+ sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
+ (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
+ goto trigger_cleanup;
+ }
+ if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
+ sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
+ " trigger on table: %S", pTableName, 0);
+ goto trigger_cleanup;
+ }
+
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ if( !IN_RENAME_OBJECT ){
+ int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ int code = SQLITE_CREATE_TRIGGER;
+ const char *zDb = db->aDb[iTabDb].zDbSName;
+ const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
+ if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
+ if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
+ goto trigger_cleanup;
+ }
+ if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
+ goto trigger_cleanup;
+ }
+ }
+#endif
+
+ /* INSTEAD OF triggers can only appear on views and BEFORE triggers
+ ** cannot appear on views. So we might as well translate every
+ ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
+ ** elsewhere.
+ */
+ if (tr_tm == TK_INSTEAD){
+ tr_tm = TK_BEFORE;
+ }
+
+ /* Build the Trigger object */
+ pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
+ if( pTrigger==0 ) goto trigger_cleanup;
+ pTrigger->zName = zName;
+ zName = 0;
+ pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
+ pTrigger->pSchema = db->aDb[iDb].pSchema;
+ pTrigger->pTabSchema = pTab->pSchema;
+ pTrigger->op = (u8)op;
+ pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameTokenRemap(pParse, pTrigger->table, pTableName->a[0].zName);
+ pTrigger->pWhen = pWhen;
+ pWhen = 0;
+ }else{
+ pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
+ }
+ pTrigger->pColumns = pColumns;
+ pColumns = 0;
+ assert( pParse->pNewTrigger==0 );
+ pParse->pNewTrigger = pTrigger;
+
+trigger_cleanup:
+ sqlite3DbFree(db, zName);
+ sqlite3SrcListDelete(db, pTableName);
+ sqlite3IdListDelete(db, pColumns);
+ sqlite3ExprDelete(db, pWhen);
+ if( !pParse->pNewTrigger ){
+ sqlite3DeleteTrigger(db, pTrigger);
+ }else{
+ assert( pParse->pNewTrigger==pTrigger );
+ }
+}
+
+/*
+** This routine is called after all of the trigger actions have been parsed
+** in order to complete the process of building the trigger.
+*/
+SQLITE_PRIVATE void sqlite3FinishTrigger(
+ Parse *pParse, /* Parser context */
+ TriggerStep *pStepList, /* The triggered program */
+ Token *pAll /* Token that describes the complete CREATE TRIGGER */
+){
+ Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
+ char *zName; /* Name of trigger */
+ sqlite3 *db = pParse->db; /* The database */
+ DbFixer sFix; /* Fixer object */
+ int iDb; /* Database containing the trigger */
+ Token nameToken; /* Trigger name for error reporting */
+
+ pParse->pNewTrigger = 0;
+ if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
+ zName = pTrig->zName;
+ iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
+ pTrig->step_list = pStepList;
+ while( pStepList ){
+ pStepList->pTrig = pTrig;
+ pStepList = pStepList->pNext;
+ }
+ sqlite3TokenInit(&nameToken, pTrig->zName);
+ sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
+ if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
+ || sqlite3FixExpr(&sFix, pTrig->pWhen)
+ ){
+ goto triggerfinish_cleanup;
+ }
+
+#ifndef SQLITE_OMIT_ALTERTABLE
+ if( IN_RENAME_OBJECT ){
+ assert( !db->init.busy );
+ pParse->pNewTrigger = pTrig;
+ pTrig = 0;
+ }else
+#endif
+
+ /* if we are not initializing,
+ ** build the sqlite_schema entry
+ */
+ if( !db->init.busy ){
+ Vdbe *v;
+ char *z;
+
+ /* Make an entry in the sqlite_schema table */
+ v = sqlite3GetVdbe(pParse);
+ if( v==0 ) goto triggerfinish_cleanup;
+ sqlite3BeginWriteOperation(pParse, 0, iDb);
+ z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
+ testcase( z==0 );
+ sqlite3NestedParse(pParse,
+ "INSERT INTO %Q." DFLT_SCHEMA_TABLE
+ " VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
+ db->aDb[iDb].zDbSName, zName,
+ pTrig->table, z);
+ sqlite3DbFree(db, z);
+ sqlite3ChangeCookie(pParse, iDb);
+ sqlite3VdbeAddParseSchemaOp(v, iDb,
+ sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
+ }
+
+ if( db->init.busy ){
+ Trigger *pLink = pTrig;
+ Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ assert( pLink!=0 );
+ pTrig = sqlite3HashInsert(pHash, zName, pTrig);
+ if( pTrig ){
+ sqlite3OomFault(db);
+ }else if( pLink->pSchema==pLink->pTabSchema ){
+ Table *pTab;
+ pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
+ assert( pTab!=0 );
+ pLink->pNext = pTab->pTrigger;
+ pTab->pTrigger = pLink;
+ }
+ }
+
+triggerfinish_cleanup:
+ sqlite3DeleteTrigger(db, pTrig);
+ assert( IN_RENAME_OBJECT || !pParse->pNewTrigger );
+ sqlite3DeleteTriggerStep(db, pStepList);
+}
+
+/*
+** Duplicate a range of text from an SQL statement, then convert all
+** whitespace characters into ordinary space characters.
+*/
+static char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
+ char *z = sqlite3DbSpanDup(db, zStart, zEnd);
+ int i;
+ if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' ';
+ return z;
+}
+
+/*
+** Turn a SELECT statement (that the pSelect parameter points to) into
+** a trigger step. Return a pointer to a TriggerStep structure.
+**
+** The parser calls this routine when it finds a SELECT statement in
+** body of a TRIGGER.
+*/
+SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(
+ sqlite3 *db, /* Database connection */
+ Select *pSelect, /* The SELECT statement */
+ const char *zStart, /* Start of SQL text */
+ const char *zEnd /* End of SQL text */
+){
+ TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
+ if( pTriggerStep==0 ) {
+ sqlite3SelectDelete(db, pSelect);
+ return 0;
+ }
+ pTriggerStep->op = TK_SELECT;
+ pTriggerStep->pSelect = pSelect;
+ pTriggerStep->orconf = OE_Default;
+ pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
+ return pTriggerStep;
+}
+
+/*
+** Allocate space to hold a new trigger step. The allocated space
+** holds both the TriggerStep object and the TriggerStep.target.z string.
+**
+** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
+*/
+static TriggerStep *triggerStepAllocate(
+ Parse *pParse, /* Parser context */
+ u8 op, /* Trigger opcode */
+ Token *pName, /* The target name */
+ const char *zStart, /* Start of SQL text */
+ const char *zEnd /* End of SQL text */
+){
+ sqlite3 *db = pParse->db;
+ TriggerStep *pTriggerStep;
+
+ pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
+ if( pTriggerStep ){
+ char *z = (char*)&pTriggerStep[1];
+ memcpy(z, pName->z, pName->n);
+ sqlite3Dequote(z);
+ pTriggerStep->zTarget = z;
+ pTriggerStep->op = op;
+ pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName);
+ }
+ }
+ return pTriggerStep;
+}
+
+/*
+** Build a trigger step out of an INSERT statement. Return a pointer
+** to the new trigger step.
+**
+** The parser calls this routine when it sees an INSERT inside the
+** body of a trigger.
+*/
+SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
+ Parse *pParse, /* Parser */
+ Token *pTableName, /* Name of the table into which we insert */
+ IdList *pColumn, /* List of columns in pTableName to insert into */
+ Select *pSelect, /* A SELECT statement that supplies values */
+ u8 orconf, /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
+ Upsert *pUpsert, /* ON CONFLICT clauses for upsert */
+ const char *zStart, /* Start of SQL text */
+ const char *zEnd /* End of SQL text */
+){
+ sqlite3 *db = pParse->db;
+ TriggerStep *pTriggerStep;
+
+ assert(pSelect != 0 || db->mallocFailed);
+
+ pTriggerStep = triggerStepAllocate(pParse, TK_INSERT, pTableName,zStart,zEnd);
+ if( pTriggerStep ){
+ if( IN_RENAME_OBJECT ){
+ pTriggerStep->pSelect = pSelect;
+ pSelect = 0;
+ }else{
+ pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
+ }
+ pTriggerStep->pIdList = pColumn;
+ pTriggerStep->pUpsert = pUpsert;
+ pTriggerStep->orconf = orconf;
+ if( pUpsert ){
+ sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget);
+ }
+ }else{
+ testcase( pColumn );
+ sqlite3IdListDelete(db, pColumn);
+ testcase( pUpsert );
+ sqlite3UpsertDelete(db, pUpsert);
+ }
+ sqlite3SelectDelete(db, pSelect);
+
+ return pTriggerStep;
+}
+
+/*
+** Construct a trigger step that implements an UPDATE statement and return
+** a pointer to that trigger step. The parser calls this routine when it
+** sees an UPDATE statement inside the body of a CREATE TRIGGER.
+*/
+SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
+ Parse *pParse, /* Parser */
+ Token *pTableName, /* Name of the table to be updated */
+ SrcList *pFrom,
+ ExprList *pEList, /* The SET clause: list of column and new values */
+ Expr *pWhere, /* The WHERE clause */
+ u8 orconf, /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
+ const char *zStart, /* Start of SQL text */
+ const char *zEnd /* End of SQL text */
+){
+ sqlite3 *db = pParse->db;
+ TriggerStep *pTriggerStep;
+
+ pTriggerStep = triggerStepAllocate(pParse, TK_UPDATE, pTableName,zStart,zEnd);
+ if( pTriggerStep ){
+ if( IN_RENAME_OBJECT ){
+ pTriggerStep->pExprList = pEList;
+ pTriggerStep->pWhere = pWhere;
+ pTriggerStep->pFrom = pFrom;
+ pEList = 0;
+ pWhere = 0;
+ pFrom = 0;
+ }else{
+ pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
+ pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
+ pTriggerStep->pFrom = sqlite3SrcListDup(db, pFrom, EXPRDUP_REDUCE);
+ }
+ pTriggerStep->orconf = orconf;
+ }
+ sqlite3ExprListDelete(db, pEList);
+ sqlite3ExprDelete(db, pWhere);
+ sqlite3SrcListDelete(db, pFrom);
+ return pTriggerStep;
+}
+
+/*
+** Construct a trigger step that implements a DELETE statement and return
+** a pointer to that trigger step. The parser calls this routine when it
+** sees a DELETE statement inside the body of a CREATE TRIGGER.
+*/
+SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
+ Parse *pParse, /* Parser */
+ Token *pTableName, /* The table from which rows are deleted */
+ Expr *pWhere, /* The WHERE clause */
+ const char *zStart, /* Start of SQL text */
+ const char *zEnd /* End of SQL text */
+){
+ sqlite3 *db = pParse->db;
+ TriggerStep *pTriggerStep;
+
+ pTriggerStep = triggerStepAllocate(pParse, TK_DELETE, pTableName,zStart,zEnd);
+ if( pTriggerStep ){
+ if( IN_RENAME_OBJECT ){
+ pTriggerStep->pWhere = pWhere;
+ pWhere = 0;
+ }else{
+ pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
+ }
+ pTriggerStep->orconf = OE_Default;
+ }
+ sqlite3ExprDelete(db, pWhere);
+ return pTriggerStep;
+}
+
+/*
+** Recursively delete a Trigger structure
+*/
+SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
+ if( pTrigger==0 ) return;
+ sqlite3DeleteTriggerStep(db, pTrigger->step_list);
+ sqlite3DbFree(db, pTrigger->zName);
+ sqlite3DbFree(db, pTrigger->table);
+ sqlite3ExprDelete(db, pTrigger->pWhen);
+ sqlite3IdListDelete(db, pTrigger->pColumns);
+ sqlite3DbFree(db, pTrigger);
+}
+
+/*
+** This function is called to drop a trigger from the database schema.
+**
+** This may be called directly from the parser and therefore identifies
+** the trigger by name. The sqlite3DropTriggerPtr() routine does the
+** same job as this routine except it takes a pointer to the trigger
+** instead of the trigger name.
+**/
+SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
+ Trigger *pTrigger = 0;
+ int i;
+ const char *zDb;
+ const char *zName;
+ sqlite3 *db = pParse->db;
+
+ if( db->mallocFailed ) goto drop_trigger_cleanup;
+ if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
+ goto drop_trigger_cleanup;
+ }
+
+ assert( pName->nSrc==1 );
+ zDb = pName->a[0].zDatabase;
+ zName = pName->a[0].zName;
+ assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
+ for(i=OMIT_TEMPDB; i<db->nDb; i++){
+ int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
+ if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
+ assert( sqlite3SchemaMutexHeld(db, j, 0) );
+ pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
+ if( pTrigger ) break;
+ }
+ if( !pTrigger ){
+ if( !noErr ){
+ sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
+ }else{
+ sqlite3CodeVerifyNamedSchema(pParse, zDb);
+ }
+ pParse->checkSchema = 1;
+ goto drop_trigger_cleanup;
+ }
+ sqlite3DropTriggerPtr(pParse, pTrigger);
+
+drop_trigger_cleanup:
+ sqlite3SrcListDelete(db, pName);
+}
+
+/*
+** Return a pointer to the Table structure for the table that a trigger
+** is set on.
+*/
+static Table *tableOfTrigger(Trigger *pTrigger){
+ return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
+}
+
+
+/*
+** Drop a trigger given a pointer to that trigger.
+*/
+SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
+ Table *pTable;
+ Vdbe *v;
+ sqlite3 *db = pParse->db;
+ int iDb;
+
+ iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
+ assert( iDb>=0 && iDb<db->nDb );
+ pTable = tableOfTrigger(pTrigger);
+ assert( (pTable && pTable->pSchema==pTrigger->pSchema) || iDb==1 );
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ if( pTable ){
+ int code = SQLITE_DROP_TRIGGER;
+ const char *zDb = db->aDb[iDb].zDbSName;
+ const char *zTab = SCHEMA_TABLE(iDb);
+ if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
+ if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
+ sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
+ return;
+ }
+ }
+#endif
+
+ /* Generate code to destroy the database record of the trigger.
+ */
+ if( (v = sqlite3GetVdbe(pParse))!=0 ){
+ sqlite3NestedParse(pParse,
+ "DELETE FROM %Q." DFLT_SCHEMA_TABLE " WHERE name=%Q AND type='trigger'",
+ db->aDb[iDb].zDbSName, pTrigger->zName
+ );
+ sqlite3ChangeCookie(pParse, iDb);
+ sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
+ }
+}
+
+/*
+** Remove a trigger from the hash tables of the sqlite* pointer.
+*/
+SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
+ Trigger *pTrigger;
+ Hash *pHash;
+
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+ pHash = &(db->aDb[iDb].pSchema->trigHash);
+ pTrigger = sqlite3HashInsert(pHash, zName, 0);
+ if( ALWAYS(pTrigger) ){
+ if( pTrigger->pSchema==pTrigger->pTabSchema ){
+ Table *pTab = tableOfTrigger(pTrigger);
+ if( pTab ){
+ Trigger **pp;
+ for(pp=&pTab->pTrigger; *pp; pp=&((*pp)->pNext)){
+ if( *pp==pTrigger ){
+ *pp = (*pp)->pNext;
+ break;
+ }
+ }
+ }
+ }
+ sqlite3DeleteTrigger(db, pTrigger);
+ db->mDbFlags |= DBFLAG_SchemaChange;
+ }
+}
+
+/*
+** pEList is the SET clause of an UPDATE statement. Each entry
+** in pEList is of the format <id>=<expr>. If any of the entries
+** in pEList have an <id> which matches an identifier in pIdList,
+** then return TRUE. If pIdList==NULL, then it is considered a
+** wildcard that matches anything. Likewise if pEList==NULL then
+** it matches anything so always return true. Return false only
+** if there is no match.
+*/
+static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
+ int e;
+ if( pIdList==0 || NEVER(pEList==0) ) return 1;
+ for(e=0; e<pEList->nExpr; e++){
+ if( sqlite3IdListIndex(pIdList, pEList->a[e].zEName)>=0 ) return 1;
+ }
+ return 0;
+}
+
+/*
+** Return a list of all triggers on table pTab if there exists at least
+** one trigger that must be fired when an operation of type 'op' is
+** performed on the table, and, if that operation is an UPDATE, if at
+** least one of the columns in pChanges is being modified.
+*/
+SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
+ Parse *pParse, /* Parse context */
+ Table *pTab, /* The table the contains the triggers */
+ int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
+ ExprList *pChanges, /* Columns that change in an UPDATE statement */
+ int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
+){
+ int mask = 0;
+ Trigger *pList = 0;
+ Trigger *p;
+
+ if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
+ pList = sqlite3TriggerList(pParse, pTab);
+ }
+ assert( pList==0 || IsVirtual(pTab)==0 );
+ for(p=pList; p; p=p->pNext){
+ if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
+ mask |= p->tr_tm;
+ }
+ }
+ if( pMask ){
+ *pMask = mask;
+ }
+ return (mask ? pList : 0);
+}
+
+/*
+** Convert the pStep->zTarget string into a SrcList and return a pointer
+** to that SrcList.
+**
+** This routine adds a specific database name, if needed, to the target when
+** forming the SrcList. This prevents a trigger in one database from
+** referring to a target in another database. An exception is when the
+** trigger is in TEMP in which case it can refer to any other database it
+** wants.
+*/
+SQLITE_PRIVATE SrcList *sqlite3TriggerStepSrc(
+ Parse *pParse, /* The parsing context */
+ TriggerStep *pStep /* The trigger containing the target token */
+){
+ sqlite3 *db = pParse->db;
+ SrcList *pSrc; /* SrcList to be returned */
+ char *zName = sqlite3DbStrDup(db, pStep->zTarget);
+ pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
+ assert( pSrc==0 || pSrc->nSrc==1 );
+ assert( zName || pSrc==0 );
+ if( pSrc ){
+ Schema *pSchema = pStep->pTrig->pSchema;
+ pSrc->a[0].zName = zName;
+ if( pSchema!=db->aDb[1].pSchema ){
+ pSrc->a[0].pSchema = pSchema;
+ }
+ if( pStep->pFrom ){
+ SrcList *pDup = sqlite3SrcListDup(db, pStep->pFrom, 0);
+ pSrc = sqlite3SrcListAppendList(pParse, pSrc, pDup);
+ }
+ }else{
+ sqlite3DbFree(db, zName);
+ }
+ return pSrc;
+}
+
+/*
+** Generate VDBE code for the statements inside the body of a single
+** trigger.
+*/
+static int codeTriggerProgram(
+ Parse *pParse, /* The parser context */
+ TriggerStep *pStepList, /* List of statements inside the trigger body */
+ int orconf /* Conflict algorithm. (OE_Abort, etc) */
+){
+ TriggerStep *pStep;
+ Vdbe *v = pParse->pVdbe;
+ sqlite3 *db = pParse->db;
+
+ assert( pParse->pTriggerTab && pParse->pToplevel );
+ assert( pStepList );
+ assert( v!=0 );
+ for(pStep=pStepList; pStep; pStep=pStep->pNext){
+ /* Figure out the ON CONFLICT policy that will be used for this step
+ ** of the trigger program. If the statement that caused this trigger
+ ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
+ ** the ON CONFLICT policy that was specified as part of the trigger
+ ** step statement. Example:
+ **
+ ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
+ ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
+ ** END;
+ **
+ ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
+ ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
+ */
+ pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
+ assert( pParse->okConstFactor==0 );
+
+#ifndef SQLITE_OMIT_TRACE
+ if( pStep->zSpan ){
+ sqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0,
+ sqlite3MPrintf(db, "-- %s", pStep->zSpan),
+ P4_DYNAMIC);
+ }
+#endif
+
+ switch( pStep->op ){
+ case TK_UPDATE: {
+ sqlite3Update(pParse,
+ sqlite3TriggerStepSrc(pParse, pStep),
+ sqlite3ExprListDup(db, pStep->pExprList, 0),
+ sqlite3ExprDup(db, pStep->pWhere, 0),
+ pParse->eOrconf, 0, 0, 0
+ );
+ break;
+ }
+ case TK_INSERT: {
+ sqlite3Insert(pParse,
+ sqlite3TriggerStepSrc(pParse, pStep),
+ sqlite3SelectDup(db, pStep->pSelect, 0),
+ sqlite3IdListDup(db, pStep->pIdList),
+ pParse->eOrconf,
+ sqlite3UpsertDup(db, pStep->pUpsert)
+ );
+ break;
+ }
+ case TK_DELETE: {
+ sqlite3DeleteFrom(pParse,
+ sqlite3TriggerStepSrc(pParse, pStep),
+ sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
+ );
+ break;
+ }
+ default: assert( pStep->op==TK_SELECT ); {
+ SelectDest sDest;
+ Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
+ sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
+ sqlite3Select(pParse, pSelect, &sDest);
+ sqlite3SelectDelete(db, pSelect);
+ break;
+ }
+ }
+ if( pStep->op!=TK_SELECT ){
+ sqlite3VdbeAddOp0(v, OP_ResetCount);
+ }
+ }
+
+ return 0;
+}
+
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+/*
+** This function is used to add VdbeComment() annotations to a VDBE
+** program. It is not used in production code, only for debugging.
+*/
+static const char *onErrorText(int onError){
+ switch( onError ){
+ case OE_Abort: return "abort";
+ case OE_Rollback: return "rollback";
+ case OE_Fail: return "fail";
+ case OE_Replace: return "replace";
+ case OE_Ignore: return "ignore";
+ case OE_Default: return "default";
+ }
+ return "n/a";
+}
+#endif
+
+/*
+** Parse context structure pFrom has just been used to create a sub-vdbe
+** (trigger program). If an error has occurred, transfer error information
+** from pFrom to pTo.
+*/
+static void transferParseError(Parse *pTo, Parse *pFrom){
+ assert( pFrom->zErrMsg==0 || pFrom->nErr );
+ assert( pTo->zErrMsg==0 || pTo->nErr );
+ if( pTo->nErr==0 ){
+ pTo->zErrMsg = pFrom->zErrMsg;
+ pTo->nErr = pFrom->nErr;
+ pTo->rc = pFrom->rc;
+ }else{
+ sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
+ }
+}
+
+/*
+** Create and populate a new TriggerPrg object with a sub-program
+** implementing trigger pTrigger with ON CONFLICT policy orconf.
+*/
+static TriggerPrg *codeRowTrigger(
+ Parse *pParse, /* Current parse context */
+ Trigger *pTrigger, /* Trigger to code */
+ Table *pTab, /* The table pTrigger is attached to */
+ int orconf /* ON CONFLICT policy to code trigger program with */
+){
+ Parse *pTop = sqlite3ParseToplevel(pParse);
+ sqlite3 *db = pParse->db; /* Database handle */
+ TriggerPrg *pPrg; /* Value to return */
+ Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
+ Vdbe *v; /* Temporary VM */
+ NameContext sNC; /* Name context for sub-vdbe */
+ SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
+ Parse *pSubParse; /* Parse context for sub-vdbe */
+ int iEndTrigger = 0; /* Label to jump to if WHEN is false */
+
+ assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
+ assert( pTop->pVdbe );
+
+ /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
+ ** are freed if an error occurs, link them into the Parse.pTriggerPrg
+ ** list of the top-level Parse object sooner rather than later. */
+ pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
+ if( !pPrg ) return 0;
+ pPrg->pNext = pTop->pTriggerPrg;
+ pTop->pTriggerPrg = pPrg;
+ pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
+ if( !pProgram ) return 0;
+ sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
+ pPrg->pTrigger = pTrigger;
+ pPrg->orconf = orconf;
+ pPrg->aColmask[0] = 0xffffffff;
+ pPrg->aColmask[1] = 0xffffffff;
+
+ /* Allocate and populate a new Parse context to use for coding the
+ ** trigger sub-program. */
+ pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
+ if( !pSubParse ) return 0;
+ memset(&sNC, 0, sizeof(sNC));
+ sNC.pParse = pSubParse;
+ pSubParse->db = db;
+ pSubParse->pTriggerTab = pTab;
+ pSubParse->pToplevel = pTop;
+ pSubParse->zAuthContext = pTrigger->zName;
+ pSubParse->eTriggerOp = pTrigger->op;
+ pSubParse->nQueryLoop = pParse->nQueryLoop;
+ pSubParse->disableVtab = pParse->disableVtab;
+
+ v = sqlite3GetVdbe(pSubParse);
+ if( v ){
+ VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
+ pTrigger->zName, onErrorText(orconf),
+ (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
+ (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
+ (pTrigger->op==TK_INSERT ? "INSERT" : ""),
+ (pTrigger->op==TK_DELETE ? "DELETE" : ""),
+ pTab->zName
+ ));
+#ifndef SQLITE_OMIT_TRACE
+ if( pTrigger->zName ){
+ sqlite3VdbeChangeP4(v, -1,
+ sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
+ );
+ }
+#endif
+
+ /* If one was specified, code the WHEN clause. If it evaluates to false
+ ** (or NULL) the sub-vdbe is immediately halted by jumping to the
+ ** OP_Halt inserted at the end of the program. */
+ if( pTrigger->pWhen ){
+ pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
+ if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
+ && db->mallocFailed==0
+ ){
+ iEndTrigger = sqlite3VdbeMakeLabel(pSubParse);
+ sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
+ }
+ sqlite3ExprDelete(db, pWhen);
+ }
+
+ /* Code the trigger program into the sub-vdbe. */
+ codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
+
+ /* Insert an OP_Halt at the end of the sub-program. */
+ if( iEndTrigger ){
+ sqlite3VdbeResolveLabel(v, iEndTrigger);
+ }
+ sqlite3VdbeAddOp0(v, OP_Halt);
+ VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
+
+ transferParseError(pParse, pSubParse);
+ if( db->mallocFailed==0 && pParse->nErr==0 ){
+ pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
+ }
+ pProgram->nMem = pSubParse->nMem;
+ pProgram->nCsr = pSubParse->nTab;
+ pProgram->token = (void *)pTrigger;
+ pPrg->aColmask[0] = pSubParse->oldmask;
+ pPrg->aColmask[1] = pSubParse->newmask;
+ sqlite3VdbeDelete(v);
+ }
+
+ assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
+ assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
+ sqlite3ParserReset(pSubParse);
+ sqlite3StackFree(db, pSubParse);
+
+ return pPrg;
+}
+
+/*
+** Return a pointer to a TriggerPrg object containing the sub-program for
+** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
+** TriggerPrg object exists, a new object is allocated and populated before
+** being returned.
+*/
+static TriggerPrg *getRowTrigger(
+ Parse *pParse, /* Current parse context */
+ Trigger *pTrigger, /* Trigger to code */
+ Table *pTab, /* The table trigger pTrigger is attached to */
+ int orconf /* ON CONFLICT algorithm. */
+){
+ Parse *pRoot = sqlite3ParseToplevel(pParse);
+ TriggerPrg *pPrg;
+
+ assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
+
+ /* It may be that this trigger has already been coded (or is in the
+ ** process of being coded). If this is the case, then an entry with
+ ** a matching TriggerPrg.pTrigger field will be present somewhere
+ ** in the Parse.pTriggerPrg list. Search for such an entry. */
+ for(pPrg=pRoot->pTriggerPrg;
+ pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
+ pPrg=pPrg->pNext
+ );
+
+ /* If an existing TriggerPrg could not be located, create a new one. */
+ if( !pPrg ){
+ pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
+ }
+
+ return pPrg;
+}
+
+/*
+** Generate code for the trigger program associated with trigger p on
+** table pTab. The reg, orconf and ignoreJump parameters passed to this
+** function are the same as those described in the header function for
+** sqlite3CodeRowTrigger()
+*/
+SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
+ Parse *pParse, /* Parse context */
+ Trigger *p, /* Trigger to code */
+ Table *pTab, /* The table to code triggers from */
+ int reg, /* Reg array containing OLD.* and NEW.* values */
+ int orconf, /* ON CONFLICT policy */
+ int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
+){
+ Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
+ TriggerPrg *pPrg;
+ pPrg = getRowTrigger(pParse, p, pTab, orconf);
+ assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
+
+ /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
+ ** is a pointer to the sub-vdbe containing the trigger program. */
+ if( pPrg ){
+ int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
+
+ sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
+ (const char *)pPrg->pProgram, P4_SUBPROGRAM);
+ VdbeComment(
+ (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
+
+ /* Set the P5 operand of the OP_Program instruction to non-zero if
+ ** recursive invocation of this trigger program is disallowed. Recursive
+ ** invocation is disallowed if (a) the sub-program is really a trigger,
+ ** not a foreign key action, and (b) the flag to enable recursive triggers
+ ** is clear. */
+ sqlite3VdbeChangeP5(v, (u8)bRecursive);
+ }
+}
+
+/*
+** This is called to code the required FOR EACH ROW triggers for an operation
+** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
+** is given by the op parameter. The tr_tm parameter determines whether the
+** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
+** parameter pChanges is passed the list of columns being modified.
+**
+** If there are no triggers that fire at the specified time for the specified
+** operation on pTab, this function is a no-op.
+**
+** The reg argument is the address of the first in an array of registers
+** that contain the values substituted for the new.* and old.* references
+** in the trigger program. If N is the number of columns in table pTab
+** (a copy of pTab->nCol), then registers are populated as follows:
+**
+** Register Contains
+** ------------------------------------------------------
+** reg+0 OLD.rowid
+** reg+1 OLD.* value of left-most column of pTab
+** ... ...
+** reg+N OLD.* value of right-most column of pTab
+** reg+N+1 NEW.rowid
+** reg+N+2 OLD.* value of left-most column of pTab
+** ... ...
+** reg+N+N+1 NEW.* value of right-most column of pTab
+**
+** For ON DELETE triggers, the registers containing the NEW.* values will
+** never be accessed by the trigger program, so they are not allocated or
+** populated by the caller (there is no data to populate them with anyway).
+** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
+** are never accessed, and so are not allocated by the caller. So, for an
+** ON INSERT trigger, the value passed to this function as parameter reg
+** is not a readable register, although registers (reg+N) through
+** (reg+N+N+1) are.
+**
+** Parameter orconf is the default conflict resolution algorithm for the
+** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
+** is the instruction that control should jump to if a trigger program
+** raises an IGNORE exception.
+*/
+SQLITE_PRIVATE void sqlite3CodeRowTrigger(
+ Parse *pParse, /* Parse context */
+ Trigger *pTrigger, /* List of triggers on table pTab */
+ int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
+ ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
+ int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
+ Table *pTab, /* The table to code triggers from */
+ int reg, /* The first in an array of registers (see above) */
+ int orconf, /* ON CONFLICT policy */
+ int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
+){
+ Trigger *p; /* Used to iterate through pTrigger list */
+
+ assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
+ assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
+ assert( (op==TK_UPDATE)==(pChanges!=0) );
+
+ for(p=pTrigger; p; p=p->pNext){
+
+ /* Sanity checking: The schema for the trigger and for the table are
+ ** always defined. The trigger must be in the same schema as the table
+ ** or else it must be a TEMP trigger. */
+ assert( p->pSchema!=0 );
+ assert( p->pTabSchema!=0 );
+ assert( p->pSchema==p->pTabSchema
+ || p->pSchema==pParse->db->aDb[1].pSchema );
+
+ /* Determine whether we should code this trigger */
+ if( p->op==op
+ && p->tr_tm==tr_tm
+ && checkColumnOverlap(p->pColumns, pChanges)
+ ){
+ sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
+ }
+ }
+}
+
+/*
+** Triggers may access values stored in the old.* or new.* pseudo-table.
+** This function returns a 32-bit bitmask indicating which columns of the
+** old.* or new.* tables actually are used by triggers. This information
+** may be used by the caller, for example, to avoid having to load the entire
+** old.* record into memory when executing an UPDATE or DELETE command.
+**
+** Bit 0 of the returned mask is set if the left-most column of the
+** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
+** the second leftmost column value is required, and so on. If there
+** are more than 32 columns in the table, and at least one of the columns
+** with an index greater than 32 may be accessed, 0xffffffff is returned.
+**
+** It is not possible to determine if the old.rowid or new.rowid column is
+** accessed by triggers. The caller must always assume that it is.
+**
+** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
+** applies to the old.* table. If 1, the new.* table.
+**
+** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
+** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
+** included in the returned mask if the TRIGGER_BEFORE bit is set in the
+** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
+** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
+*/
+SQLITE_PRIVATE u32 sqlite3TriggerColmask(
+ Parse *pParse, /* Parse context */
+ Trigger *pTrigger, /* List of triggers on table pTab */
+ ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
+ int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
+ int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
+ Table *pTab, /* The table to code triggers from */
+ int orconf /* Default ON CONFLICT policy for trigger steps */
+){
+ const int op = pChanges ? TK_UPDATE : TK_DELETE;
+ u32 mask = 0;
+ Trigger *p;
+
+ assert( isNew==1 || isNew==0 );
+ for(p=pTrigger; p; p=p->pNext){
+ if( p->op==op && (tr_tm&p->tr_tm)
+ && checkColumnOverlap(p->pColumns,pChanges)
+ ){
+ TriggerPrg *pPrg;
+ pPrg = getRowTrigger(pParse, p, pTab, orconf);
+ if( pPrg ){
+ mask |= pPrg->aColmask[isNew];
+ }
+ }
+ }
+
+ return mask;
+}
+
+#endif /* !defined(SQLITE_OMIT_TRIGGER) */
+
+/************** End of trigger.c *********************************************/
+/************** Begin file update.c ******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains C code routines that are called by the parser
+** to handle UPDATE statements.
+*/
+/* #include "sqliteInt.h" */
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/* Forward declaration */
+static void updateVirtualTable(
+ Parse *pParse, /* The parsing context */
+ SrcList *pSrc, /* The virtual table to be modified */
+ Table *pTab, /* The virtual table */
+ ExprList *pChanges, /* The columns to change in the UPDATE statement */
+ Expr *pRowidExpr, /* Expression used to recompute the rowid */
+ int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
+ Expr *pWhere, /* WHERE clause of the UPDATE statement */
+ int onError /* ON CONFLICT strategy */
+);
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+/*
+** The most recently coded instruction was an OP_Column to retrieve the
+** i-th column of table pTab. This routine sets the P4 parameter of the
+** OP_Column to the default value, if any.
+**
+** The default value of a column is specified by a DEFAULT clause in the
+** column definition. This was either supplied by the user when the table
+** was created, or added later to the table definition by an ALTER TABLE
+** command. If the latter, then the row-records in the table btree on disk
+** may not contain a value for the column and the default value, taken
+** from the P4 parameter of the OP_Column instruction, is returned instead.
+** If the former, then all row-records are guaranteed to include a value
+** for the column and the P4 value is not required.
+**
+** Column definitions created by an ALTER TABLE command may only have
+** literal default values specified: a number, null or a string. (If a more
+** complicated default expression value was provided, it is evaluated
+** when the ALTER TABLE is executed and one of the literal values written
+** into the sqlite_schema table.)
+**
+** Therefore, the P4 parameter is only required if the default value for
+** the column is a literal number, string or null. The sqlite3ValueFromExpr()
+** function is capable of transforming these types of expressions into
+** sqlite3_value objects.
+**
+** If column as REAL affinity and the table is an ordinary b-tree table
+** (not a virtual table) then the value might have been stored as an
+** integer. In that case, add an OP_RealAffinity opcode to make sure
+** it has been converted into REAL.
+*/
+SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
+ assert( pTab!=0 );
+ if( !pTab->pSelect ){
+ sqlite3_value *pValue = 0;
+ u8 enc = ENC(sqlite3VdbeDb(v));
+ Column *pCol = &pTab->aCol[i];
+ VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
+ assert( i<pTab->nCol );
+ sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
+ pCol->affinity, &pValue);
+ if( pValue ){
+ sqlite3VdbeAppendP4(v, pValue, P4_MEM);
+ }
+ }
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ if( pTab->aCol[i].affinity==SQLITE_AFF_REAL && !IsVirtual(pTab) ){
+ sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
+ }
+#endif
+}
+
+/*
+** Check to see if column iCol of index pIdx references any of the
+** columns defined by aXRef and chngRowid. Return true if it does
+** and false if not. This is an optimization. False-positives are a
+** performance degradation, but false-negatives can result in a corrupt
+** index and incorrect answers.
+**
+** aXRef[j] will be non-negative if column j of the original table is
+** being updated. chngRowid will be true if the rowid of the table is
+** being updated.
+*/
+static int indexColumnIsBeingUpdated(
+ Index *pIdx, /* The index to check */
+ int iCol, /* Which column of the index to check */
+ int *aXRef, /* aXRef[j]>=0 if column j is being updated */
+ int chngRowid /* true if the rowid is being updated */
+){
+ i16 iIdxCol = pIdx->aiColumn[iCol];
+ assert( iIdxCol!=XN_ROWID ); /* Cannot index rowid */
+ if( iIdxCol>=0 ){
+ return aXRef[iIdxCol]>=0;
+ }
+ assert( iIdxCol==XN_EXPR );
+ assert( pIdx->aColExpr!=0 );
+ assert( pIdx->aColExpr->a[iCol].pExpr!=0 );
+ return sqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr,
+ aXRef,chngRowid);
+}
+
+/*
+** Check to see if index pIdx is a partial index whose conditional
+** expression might change values due to an UPDATE. Return true if
+** the index is subject to change and false if the index is guaranteed
+** to be unchanged. This is an optimization. False-positives are a
+** performance degradation, but false-negatives can result in a corrupt
+** index and incorrect answers.
+**
+** aXRef[j] will be non-negative if column j of the original table is
+** being updated. chngRowid will be true if the rowid of the table is
+** being updated.
+*/
+static int indexWhereClauseMightChange(
+ Index *pIdx, /* The index to check */
+ int *aXRef, /* aXRef[j]>=0 if column j is being updated */
+ int chngRowid /* true if the rowid is being updated */
+){
+ if( pIdx->pPartIdxWhere==0 ) return 0;
+ return sqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere,
+ aXRef, chngRowid);
+}
+
+/*
+** Allocate and return a pointer to an expression of type TK_ROW with
+** Expr.iColumn set to value (iCol+1). The resolver will modify the
+** expression to be a TK_COLUMN reading column iCol of the first
+** table in the source-list (pSrc->a[0]).
+*/
+static Expr *exprRowColumn(Parse *pParse, int iCol){
+ Expr *pRet = sqlite3PExpr(pParse, TK_ROW, 0, 0);
+ if( pRet ) pRet->iColumn = iCol+1;
+ return pRet;
+}
+
+/*
+** Assuming both the pLimit and pOrderBy parameters are NULL, this function
+** generates VM code to run the query:
+**
+** SELECT <other-columns>, pChanges FROM pTabList WHERE pWhere
+**
+** and write the results to the ephemeral table already opened as cursor
+** iEph. None of pChanges, pTabList or pWhere are modified or consumed by
+** this function, they must be deleted by the caller.
+**
+** Or, if pLimit and pOrderBy are not NULL, and pTab is not a view:
+**
+** SELECT <other-columns>, pChanges FROM pTabList
+** WHERE pWhere
+** GROUP BY <other-columns>
+** ORDER BY pOrderBy LIMIT pLimit
+**
+** If pTab is a view, the GROUP BY clause is omitted.
+**
+** Exactly how results are written to table iEph, and exactly what
+** the <other-columns> in the query above are is determined by the type
+** of table pTabList->a[0].pTab.
+**
+** If the table is a WITHOUT ROWID table, then argument pPk must be its
+** PRIMARY KEY. In this case <other-columns> are the primary key columns
+** of the table, in order. The results of the query are written to ephemeral
+** table iEph as index keys, using OP_IdxInsert.
+**
+** If the table is actually a view, then <other-columns> are all columns of
+** the view. The results are written to the ephemeral table iEph as records
+** with automatically assigned integer keys.
+**
+** If the table is a virtual or ordinary intkey table, then <other-columns>
+** is its rowid. For a virtual table, the results are written to iEph as
+** records with automatically assigned integer keys For intkey tables, the
+** rowid value in <other-columns> is used as the integer key, and the
+** remaining fields make up the table record.
+*/
+static void updateFromSelect(
+ Parse *pParse, /* Parse context */
+ int iEph, /* Cursor for open eph. table */
+ Index *pPk, /* PK if table 0 is WITHOUT ROWID */
+ ExprList *pChanges, /* List of expressions to return */
+ SrcList *pTabList, /* List of tables to select from */
+ Expr *pWhere, /* WHERE clause for query */
+ ExprList *pOrderBy, /* ORDER BY clause */
+ Expr *pLimit /* LIMIT clause */
+){
+ int i;
+ SelectDest dest;
+ Select *pSelect = 0;
+ ExprList *pList = 0;
+ ExprList *pGrp = 0;
+ Expr *pLimit2 = 0;
+ ExprList *pOrderBy2 = 0;
+ sqlite3 *db = pParse->db;
+ Table *pTab = pTabList->a[0].pTab;
+ SrcList *pSrc;
+ Expr *pWhere2;
+ int eDest;
+
+#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
+ if( pOrderBy && pLimit==0 ) {
+ sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on UPDATE");
+ return;
+ }
+ pOrderBy2 = sqlite3ExprListDup(db, pOrderBy, 0);
+ pLimit2 = sqlite3ExprDup(db, pLimit, 0);
+#else
+ UNUSED_PARAMETER(pOrderBy);
+ UNUSED_PARAMETER(pLimit);
+#endif
+
+ pSrc = sqlite3SrcListDup(db, pTabList, 0);
+ pWhere2 = sqlite3ExprDup(db, pWhere, 0);
+
+ assert( pTabList->nSrc>1 );
+ if( pSrc ){
+ pSrc->a[0].iCursor = -1;
+ pSrc->a[0].pTab->nTabRef--;
+ pSrc->a[0].pTab = 0;
+ }
+ if( pPk ){
+ for(i=0; i<pPk->nKeyCol; i++){
+ Expr *pNew = exprRowColumn(pParse, pPk->aiColumn[i]);
+#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
+ if( pLimit ){
+ pGrp = sqlite3ExprListAppend(pParse, pGrp, sqlite3ExprDup(db, pNew, 0));
+ }
+#endif
+ pList = sqlite3ExprListAppend(pParse, pList, pNew);
+ }
+ eDest = SRT_Upfrom;
+ }else if( pTab->pSelect ){
+ for(i=0; i<pTab->nCol; i++){
+ pList = sqlite3ExprListAppend(pParse, pList, exprRowColumn(pParse, i));
+ }
+ eDest = SRT_Table;
+ }else{
+ eDest = IsVirtual(pTab) ? SRT_Table : SRT_Upfrom;
+ pList = sqlite3ExprListAppend(pParse, 0, sqlite3PExpr(pParse,TK_ROW,0,0));
+#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
+ if( pLimit ){
+ pGrp = sqlite3ExprListAppend(pParse, 0, sqlite3PExpr(pParse,TK_ROW,0,0));
+ }
+#endif
+ }
+ if( ALWAYS(pChanges) ){
+ for(i=0; i<pChanges->nExpr; i++){
+ pList = sqlite3ExprListAppend(pParse, pList,
+ sqlite3ExprDup(db, pChanges->a[i].pExpr, 0)
+ );
+ }
+ }
+ pSelect = sqlite3SelectNew(pParse, pList,
+ pSrc, pWhere2, pGrp, 0, pOrderBy2, SF_UpdateFrom|SF_IncludeHidden, pLimit2
+ );
+ sqlite3SelectDestInit(&dest, eDest, iEph);
+ dest.iSDParm2 = (pPk ? pPk->nKeyCol : -1);
+ sqlite3Select(pParse, pSelect, &dest);
+ sqlite3SelectDelete(db, pSelect);
+}
+
+/*
+** Process an UPDATE statement.
+**
+** UPDATE OR IGNORE tbl SET a=b, c=d FROM tbl2... WHERE e<5 AND f NOT NULL;
+** \_______/ \_/ \______/ \_____/ \________________/
+** onError | pChanges | pWhere
+** \_______________________/
+** pTabList
+*/
+SQLITE_PRIVATE void sqlite3Update(
+ Parse *pParse, /* The parser context */
+ SrcList *pTabList, /* The table in which we should change things */
+ ExprList *pChanges, /* Things to be changed */
+ Expr *pWhere, /* The WHERE clause. May be null */
+ int onError, /* How to handle constraint errors */
+ ExprList *pOrderBy, /* ORDER BY clause. May be null */
+ Expr *pLimit, /* LIMIT clause. May be null */
+ Upsert *pUpsert /* ON CONFLICT clause, or null */
+){
+ int i, j, k; /* Loop counters */
+ Table *pTab; /* The table to be updated */
+ int addrTop = 0; /* VDBE instruction address of the start of the loop */
+ WhereInfo *pWInfo = 0; /* Information about the WHERE clause */
+ Vdbe *v; /* The virtual database engine */
+ Index *pIdx; /* For looping over indices */
+ Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
+ int nIdx; /* Number of indices that need updating */
+ int nAllIdx; /* Total number of indexes */
+ int iBaseCur; /* Base cursor number */
+ int iDataCur; /* Cursor for the canonical data btree */
+ int iIdxCur; /* Cursor for the first index */
+ sqlite3 *db; /* The database structure */
+ int *aRegIdx = 0; /* Registers for to each index and the main table */
+ int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
+ ** an expression for the i-th column of the table.
+ ** aXRef[i]==-1 if the i-th column is not changed. */
+ u8 *aToOpen; /* 1 for tables and indices to be opened */
+ u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
+ u8 chngRowid; /* Rowid changed in a normal table */
+ u8 chngKey; /* Either chngPk or chngRowid */
+ Expr *pRowidExpr = 0; /* Expression defining the new record number */
+ int iRowidExpr = -1; /* Index of "rowid=" (or IPK) assignment in pChanges */
+ AuthContext sContext; /* The authorization context */
+ NameContext sNC; /* The name-context to resolve expressions in */
+ int iDb; /* Database containing the table being updated */
+ int eOnePass; /* ONEPASS_XXX value from where.c */
+ int hasFK; /* True if foreign key processing is required */
+ int labelBreak; /* Jump here to break out of UPDATE loop */
+ int labelContinue; /* Jump here to continue next step of UPDATE loop */
+ int flags; /* Flags for sqlite3WhereBegin() */
+
+#ifndef SQLITE_OMIT_TRIGGER
+ int isView; /* True when updating a view (INSTEAD OF trigger) */
+ Trigger *pTrigger; /* List of triggers on pTab, if required */
+ int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
+#endif
+ int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
+ int iEph = 0; /* Ephemeral table holding all primary key values */
+ int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
+ int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
+ int addrOpen = 0; /* Address of OP_OpenEphemeral */
+ int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */
+ i16 nPk = 0; /* Number of components of the PRIMARY KEY */
+ int bReplace = 0; /* True if REPLACE conflict resolution might happen */
+ int bFinishSeek = 1; /* The OP_FinishSeek opcode is needed */
+ int nChangeFrom = 0; /* If there is a FROM, pChanges->nExpr, else 0 */
+
+ /* Register Allocations */
+ int regRowCount = 0; /* A count of rows changed */
+ int regOldRowid = 0; /* The old rowid */
+ int regNewRowid = 0; /* The new rowid */
+ int regNew = 0; /* Content of the NEW.* table in triggers */
+ int regOld = 0; /* Content of OLD.* table in triggers */
+ int regRowSet = 0; /* Rowset of rows to be updated */
+ int regKey = 0; /* composite PRIMARY KEY value */
+
+ memset(&sContext, 0, sizeof(sContext));
+ db = pParse->db;
+ if( pParse->nErr || db->mallocFailed ){
+ goto update_cleanup;
+ }
+
+ /* Locate the table which we want to update.
+ */
+ pTab = sqlite3SrcListLookup(pParse, pTabList);
+ if( pTab==0 ) goto update_cleanup;
+ iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
+
+ /* Figure out if we have any triggers and if the table being
+ ** updated is a view.
+ */
+#ifndef SQLITE_OMIT_TRIGGER
+ pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
+ isView = pTab->pSelect!=0;
+ assert( pTrigger || tmask==0 );
+#else
+# define pTrigger 0
+# define isView 0
+# define tmask 0
+#endif
+#ifdef SQLITE_OMIT_VIEW
+# undef isView
+# define isView 0
+#endif
+
+ /* If there was a FROM clause, set nChangeFrom to the number of expressions
+ ** in the change-list. Otherwise, set it to 0. There cannot be a FROM
+ ** clause if this function is being called to generate code for part of
+ ** an UPSERT statement. */
+ nChangeFrom = (pTabList->nSrc>1) ? pChanges->nExpr : 0;
+ assert( nChangeFrom==0 || pUpsert==0 );
+
+#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
+ if( !isView && nChangeFrom==0 ){
+ pWhere = sqlite3LimitWhere(
+ pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
+ );
+ pOrderBy = 0;
+ pLimit = 0;
+ }
+#endif
+
+ if( sqlite3ViewGetColumnNames(pParse, pTab) ){
+ goto update_cleanup;
+ }
+ if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
+ goto update_cleanup;
+ }
+
+ /* Allocate a cursors for the main database table and for all indices.
+ ** The index cursors might not be used, but if they are used they
+ ** need to occur right after the database cursor. So go ahead and
+ ** allocate enough space, just in case.
+ */
+ iBaseCur = iDataCur = pParse->nTab++;
+ iIdxCur = iDataCur+1;
+ pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
+ testcase( pPk!=0 && pPk!=pTab->pIndex );
+ for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
+ if( pPk==pIdx ){
+ iDataCur = pParse->nTab;
+ }
+ pParse->nTab++;
+ }
+ if( pUpsert ){
+ /* On an UPSERT, reuse the same cursors already opened by INSERT */
+ iDataCur = pUpsert->iDataCur;
+ iIdxCur = pUpsert->iIdxCur;
+ pParse->nTab = iBaseCur;
+ }
+ pTabList->a[0].iCursor = iDataCur;
+
+ /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
+ ** Initialize aXRef[] and aToOpen[] to their default values.
+ */
+ aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx+1) + nIdx+2 );
+ if( aXRef==0 ) goto update_cleanup;
+ aRegIdx = aXRef+pTab->nCol;
+ aToOpen = (u8*)(aRegIdx+nIdx+1);
+ memset(aToOpen, 1, nIdx+1);
+ aToOpen[nIdx+1] = 0;
+ for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
+
+ /* Initialize the name-context */
+ memset(&sNC, 0, sizeof(sNC));
+ sNC.pParse = pParse;
+ sNC.pSrcList = pTabList;
+ sNC.uNC.pUpsert = pUpsert;
+ sNC.ncFlags = NC_UUpsert;
+
+ /* Begin generating code. */
+ v = sqlite3GetVdbe(pParse);
+ if( v==0 ) goto update_cleanup;
+
+ /* Resolve the column names in all the expressions of the
+ ** of the UPDATE statement. Also find the column index
+ ** for each column to be updated in the pChanges array. For each
+ ** column to be updated, make sure we have authorization to change
+ ** that column.
+ */
+ chngRowid = chngPk = 0;
+ for(i=0; i<pChanges->nExpr; i++){
+ /* If this is an UPDATE with a FROM clause, do not resolve expressions
+ ** here. The call to sqlite3Select() below will do that. */
+ if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
+ goto update_cleanup;
+ }
+ for(j=0; j<pTab->nCol; j++){
+ if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zEName)==0 ){
+ if( j==pTab->iPKey ){
+ chngRowid = 1;
+ pRowidExpr = pChanges->a[i].pExpr;
+ iRowidExpr = i;
+ }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
+ chngPk = 1;
+ }
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){
+ testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL );
+ testcase( pTab->aCol[j].colFlags & COLFLAG_STORED );
+ sqlite3ErrorMsg(pParse,
+ "cannot UPDATE generated column \"%s\"",
+ pTab->aCol[j].zName);
+ goto update_cleanup;
+ }
+#endif
+ aXRef[j] = i;
+ break;
+ }
+ }
+ if( j>=pTab->nCol ){
+ if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zEName) ){
+ j = -1;
+ chngRowid = 1;
+ pRowidExpr = pChanges->a[i].pExpr;
+ iRowidExpr = i;
+ }else{
+ sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zEName);
+ pParse->checkSchema = 1;
+ goto update_cleanup;
+ }
+ }
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ {
+ int rc;
+ rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
+ j<0 ? "ROWID" : pTab->aCol[j].zName,
+ db->aDb[iDb].zDbSName);
+ if( rc==SQLITE_DENY ){
+ goto update_cleanup;
+ }else if( rc==SQLITE_IGNORE ){
+ aXRef[j] = -1;
+ }
+ }
+#endif
+ }
+ assert( (chngRowid & chngPk)==0 );
+ assert( chngRowid==0 || chngRowid==1 );
+ assert( chngPk==0 || chngPk==1 );
+ chngKey = chngRowid + chngPk;
+
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ /* Mark generated columns as changing if their generator expressions
+ ** reference any changing column. The actual aXRef[] value for
+ ** generated expressions is not used, other than to check to see that it
+ ** is non-negative, so the value of aXRef[] for generated columns can be
+ ** set to any non-negative number. We use 99999 so that the value is
+ ** obvious when looking at aXRef[] in a symbolic debugger.
+ */
+ if( pTab->tabFlags & TF_HasGenerated ){
+ int bProgress;
+ testcase( pTab->tabFlags & TF_HasVirtual );
+ testcase( pTab->tabFlags & TF_HasStored );
+ do{
+ bProgress = 0;
+ for(i=0; i<pTab->nCol; i++){
+ if( aXRef[i]>=0 ) continue;
+ if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ) continue;
+ if( sqlite3ExprReferencesUpdatedColumn(pTab->aCol[i].pDflt,
+ aXRef, chngRowid) ){
+ aXRef[i] = 99999;
+ bProgress = 1;
+ }
+ }
+ }while( bProgress );
+ }
+#endif
+
+ /* The SET expressions are not actually used inside the WHERE loop.
+ ** So reset the colUsed mask. Unless this is a virtual table. In that
+ ** case, set all bits of the colUsed mask (to ensure that the virtual
+ ** table implementation makes all columns available).
+ */
+ pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
+
+ hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
+
+ /* There is one entry in the aRegIdx[] array for each index on the table
+ ** being updated. Fill in aRegIdx[] with a register number that will hold
+ ** the key for accessing each index.
+ */
+ if( onError==OE_Replace ) bReplace = 1;
+ for(nAllIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nAllIdx++){
+ int reg;
+ if( chngKey || hasFK>1 || pIdx==pPk
+ || indexWhereClauseMightChange(pIdx,aXRef,chngRowid)
+ ){
+ reg = ++pParse->nMem;
+ pParse->nMem += pIdx->nColumn;
+ }else{
+ reg = 0;
+ for(i=0; i<pIdx->nKeyCol; i++){
+ if( indexColumnIsBeingUpdated(pIdx, i, aXRef, chngRowid) ){
+ reg = ++pParse->nMem;
+ pParse->nMem += pIdx->nColumn;
+ if( onError==OE_Default && pIdx->onError==OE_Replace ){
+ bReplace = 1;
+ }
+ break;
+ }
+ }
+ }
+ if( reg==0 ) aToOpen[nAllIdx+1] = 0;
+ aRegIdx[nAllIdx] = reg;
+ }
+ aRegIdx[nAllIdx] = ++pParse->nMem; /* Register storing the table record */
+ if( bReplace ){
+ /* If REPLACE conflict resolution might be invoked, open cursors on all
+ ** indexes in case they are needed to delete records. */
+ memset(aToOpen, 1, nIdx+1);
+ }
+
+ if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
+ sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb);
+
+ /* Allocate required registers. */
+ if( !IsVirtual(pTab) ){
+ /* For now, regRowSet and aRegIdx[nAllIdx] share the same register.
+ ** If regRowSet turns out to be needed, then aRegIdx[nAllIdx] will be
+ ** reallocated. aRegIdx[nAllIdx] is the register in which the main
+ ** table record is written. regRowSet holds the RowSet for the
+ ** two-pass update algorithm. */
+ assert( aRegIdx[nAllIdx]==pParse->nMem );
+ regRowSet = aRegIdx[nAllIdx];
+ regOldRowid = regNewRowid = ++pParse->nMem;
+ if( chngPk || pTrigger || hasFK ){
+ regOld = pParse->nMem + 1;
+ pParse->nMem += pTab->nCol;
+ }
+ if( chngKey || pTrigger || hasFK ){
+ regNewRowid = ++pParse->nMem;
+ }
+ regNew = pParse->nMem + 1;
+ pParse->nMem += pTab->nCol;
+ }
+
+ /* Start the view context. */
+ if( isView ){
+ sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
+ }
+
+ /* If we are trying to update a view, realize that view into
+ ** an ephemeral table.
+ */
+#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
+ if( nChangeFrom==0 && isView ){
+ sqlite3MaterializeView(pParse, pTab,
+ pWhere, pOrderBy, pLimit, iDataCur
+ );
+ pOrderBy = 0;
+ pLimit = 0;
+ }
+#endif
+
+ /* Resolve the column names in all the expressions in the
+ ** WHERE clause.
+ */
+ if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pWhere) ){
+ goto update_cleanup;
+ }
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ /* Virtual tables must be handled separately */
+ if( IsVirtual(pTab) ){
+ updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
+ pWhere, onError);
+ goto update_cleanup;
+ }
+#endif
+
+ /* Jump to labelBreak to abandon further processing of this UPDATE */
+ labelContinue = labelBreak = sqlite3VdbeMakeLabel(pParse);
+
+ /* Not an UPSERT. Normal processing. Begin by
+ ** initialize the count of updated rows */
+ if( (db->flags&SQLITE_CountRows)!=0
+ && !pParse->pTriggerTab
+ && !pParse->nested
+ && pUpsert==0
+ ){
+ regRowCount = ++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
+ }
+
+ if( nChangeFrom==0 && HasRowid(pTab) ){
+ sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
+ }else{
+ assert( pPk!=0 || HasRowid(pTab) );
+ nPk = pPk ? pPk->nKeyCol : 0;
+ iPk = pParse->nMem+1;
+ pParse->nMem += nPk;
+ pParse->nMem += nChangeFrom;
+ regKey = ++pParse->nMem;
+ if( pUpsert==0 ){
+ int nEphCol = nPk + nChangeFrom + (isView ? pTab->nCol : 0);
+ iEph = pParse->nTab++;
+ if( pPk ) sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
+ addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nEphCol);
+ if( pPk ){
+ KeyInfo *pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pPk);
+ if( pKeyInfo ){
+ pKeyInfo->nAllField = nEphCol;
+ sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
+ }
+ }
+ if( nChangeFrom ){
+ updateFromSelect(
+ pParse, iEph, pPk, pChanges, pTabList, pWhere, pOrderBy, pLimit
+ );
+#ifndef SQLITE_OMIT_SUBQUERY
+ if( isView ) iDataCur = iEph;
+#endif
+ }
+ }
+ }
+
+ if( nChangeFrom ){
+ sqlite3MultiWrite(pParse);
+ eOnePass = ONEPASS_OFF;
+ nKey = nPk;
+ regKey = iPk;
+ }else{
+ if( pUpsert ){
+ /* If this is an UPSERT, then all cursors have already been opened by
+ ** the outer INSERT and the data cursor should be pointing at the row
+ ** that is to be updated. So bypass the code that searches for the
+ ** row(s) to be updated.
+ */
+ pWInfo = 0;
+ eOnePass = ONEPASS_SINGLE;
+ sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
+ bFinishSeek = 0;
+ }else{
+ /* Begin the database scan.
+ **
+ ** Do not consider a single-pass strategy for a multi-row update if
+ ** there are any triggers or foreign keys to process, or rows may
+ ** be deleted as a result of REPLACE conflict handling. Any of these
+ ** things might disturb a cursor being used to scan through the table
+ ** or index, causing a single-pass approach to malfunction. */
+ flags = WHERE_ONEPASS_DESIRED;
+ if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
+ flags |= WHERE_ONEPASS_MULTIROW;
+ }
+ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags,iIdxCur);
+ if( pWInfo==0 ) goto update_cleanup;
+
+ /* A one-pass strategy that might update more than one row may not
+ ** be used if any column of the index used for the scan is being
+ ** updated. Otherwise, if there is an index on "b", statements like
+ ** the following could create an infinite loop:
+ **
+ ** UPDATE t1 SET b=b+1 WHERE b>?
+ **
+ ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
+ ** strategy that uses an index for which one or more columns are being
+ ** updated. */
+ eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
+ bFinishSeek = sqlite3WhereUsesDeferredSeek(pWInfo);
+ if( eOnePass!=ONEPASS_SINGLE ){
+ sqlite3MultiWrite(pParse);
+ if( eOnePass==ONEPASS_MULTI ){
+ int iCur = aiCurOnePass[1];
+ if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
+ eOnePass = ONEPASS_OFF;
+ }
+ assert( iCur!=iDataCur || !HasRowid(pTab) );
+ }
+ }
+ }
+
+ if( HasRowid(pTab) ){
+ /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
+ ** mode, write the rowid into the FIFO. In either of the one-pass modes,
+ ** leave it in register regOldRowid. */
+ sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
+ if( eOnePass==ONEPASS_OFF ){
+ /* We need to use regRowSet, so reallocate aRegIdx[nAllIdx] */
+ aRegIdx[nAllIdx] = ++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
+ }
+ }else{
+ /* Read the PK of the current row into an array of registers. In
+ ** ONEPASS_OFF mode, serialize the array into a record and store it in
+ ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
+ ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
+ ** is not required) and leave the PK fields in the array of registers. */
+ for(i=0; i<nPk; i++){
+ assert( pPk->aiColumn[i]>=0 );
+ sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,
+ pPk->aiColumn[i], iPk+i);
+ }
+ if( eOnePass ){
+ if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen);
+ nKey = nPk;
+ regKey = iPk;
+ }else{
+ sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
+ sqlite3IndexAffinityStr(db, pPk), nPk);
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
+ }
+ }
+ }
+
+ if( pUpsert==0 ){
+ if( nChangeFrom==0 && eOnePass!=ONEPASS_MULTI ){
+ sqlite3WhereEnd(pWInfo);
+ }
+
+ if( !isView ){
+ int addrOnce = 0;
+
+ /* Open every index that needs updating. */
+ if( eOnePass!=ONEPASS_OFF ){
+ if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
+ if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
+ }
+
+ if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
+ addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
+ }
+ sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur,
+ aToOpen, 0, 0);
+ if( addrOnce ){
+ sqlite3VdbeJumpHereOrPopInst(v, addrOnce);
+ }
+ }
+
+ /* Top of the update loop */
+ if( eOnePass!=ONEPASS_OFF ){
+ if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
+ assert( pPk );
+ sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey);
+ VdbeCoverage(v);
+ }
+ if( eOnePass!=ONEPASS_SINGLE ){
+ labelContinue = sqlite3VdbeMakeLabel(pParse);
+ }
+ sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
+ VdbeCoverageIf(v, pPk==0);
+ VdbeCoverageIf(v, pPk!=0);
+ }else if( pPk || nChangeFrom ){
+ labelContinue = sqlite3VdbeMakeLabel(pParse);
+ sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
+ addrTop = sqlite3VdbeCurrentAddr(v);
+ if( nChangeFrom ){
+ if( !isView ){
+ if( pPk ){
+ for(i=0; i<nPk; i++){
+ sqlite3VdbeAddOp3(v, OP_Column, iEph, i, iPk+i);
+ }
+ sqlite3VdbeAddOp4Int(
+ v, OP_NotFound, iDataCur, labelContinue, iPk, nPk
+ ); VdbeCoverage(v);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Rowid, iEph, regOldRowid);
+ sqlite3VdbeAddOp3(
+ v, OP_NotExists, iDataCur, labelContinue, regOldRowid
+ ); VdbeCoverage(v);
+ }
+ }
+ }else{
+ sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
+ sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey,0);
+ VdbeCoverage(v);
+ }
+ }else{
+ labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet,labelBreak,
+ regOldRowid);
+ VdbeCoverage(v);
+ sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
+ VdbeCoverage(v);
+ }
+ }
+
+ /* If the rowid value will change, set register regNewRowid to
+ ** contain the new value. If the rowid is not being modified,
+ ** then regNewRowid is the same register as regOldRowid, which is
+ ** already populated. */
+ assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
+ if( chngRowid ){
+ assert( iRowidExpr>=0 );
+ if( nChangeFrom==0 ){
+ sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
+ }else{
+ sqlite3VdbeAddOp3(v, OP_Column, iEph, iRowidExpr, regNewRowid);
+ }
+ sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
+ }
+
+ /* Compute the old pre-UPDATE content of the row being changed, if that
+ ** information is needed */
+ if( chngPk || hasFK || pTrigger ){
+ u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
+ oldmask |= sqlite3TriggerColmask(pParse,
+ pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
+ );
+ for(i=0; i<pTab->nCol; i++){
+ u32 colFlags = pTab->aCol[i].colFlags;
+ k = sqlite3TableColumnToStorage(pTab, i) + regOld;
+ if( oldmask==0xffffffff
+ || (i<32 && (oldmask & MASKBIT32(i))!=0)
+ || (colFlags & COLFLAG_PRIMKEY)!=0
+ ){
+ testcase( oldmask!=0xffffffff && i==31 );
+ sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Null, 0, k);
+ }
+ }
+ if( chngRowid==0 && pPk==0 ){
+ sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
+ }
+ }
+
+ /* Populate the array of registers beginning at regNew with the new
+ ** row data. This array is used to check constants, create the new
+ ** table and index records, and as the values for any new.* references
+ ** made by triggers.
+ **
+ ** If there are one or more BEFORE triggers, then do not populate the
+ ** registers associated with columns that are (a) not modified by
+ ** this UPDATE statement and (b) not accessed by new.* references. The
+ ** values for registers not modified by the UPDATE must be reloaded from
+ ** the database after the BEFORE triggers are fired anyway (as the trigger
+ ** may have modified them). So not loading those that are not going to
+ ** be used eliminates some redundant opcodes.
+ */
+ newmask = sqlite3TriggerColmask(
+ pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
+ );
+ for(i=0, k=regNew; i<pTab->nCol; i++, k++){
+ if( i==pTab->iPKey ){
+ sqlite3VdbeAddOp2(v, OP_Null, 0, k);
+ }else if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)!=0 ){
+ if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
+ }else{
+ j = aXRef[i];
+ if( j>=0 ){
+ if( nChangeFrom ){
+ int nOff = (isView ? pTab->nCol : nPk);
+ assert( eOnePass==ONEPASS_OFF );
+ sqlite3VdbeAddOp3(v, OP_Column, iEph, nOff+j, k);
+ }else{
+ sqlite3ExprCode(pParse, pChanges->a[j].pExpr, k);
+ }
+ }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
+ /* This branch loads the value of a column that will not be changed
+ ** into a register. This is done if there are no BEFORE triggers, or
+ ** if there are one or more BEFORE triggers that use this value via
+ ** a new.* reference in a trigger program.
+ */
+ testcase( i==31 );
+ testcase( i==32 );
+ sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
+ bFinishSeek = 0;
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Null, 0, k);
+ }
+ }
+ }
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ if( pTab->tabFlags & TF_HasGenerated ){
+ testcase( pTab->tabFlags & TF_HasVirtual );
+ testcase( pTab->tabFlags & TF_HasStored );
+ sqlite3ComputeGeneratedColumns(pParse, regNew, pTab);
+ }
+#endif
+
+ /* Fire any BEFORE UPDATE triggers. This happens before constraints are
+ ** verified. One could argue that this is wrong.
+ */
+ if( tmask&TRIGGER_BEFORE ){
+ sqlite3TableAffinity(v, pTab, regNew);
+ sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
+ TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
+
+ if( !isView ){
+ /* The row-trigger may have deleted the row being updated. In this
+ ** case, jump to the next row. No updates or AFTER triggers are
+ ** required. This behavior - what happens when the row being updated
+ ** is deleted or renamed by a BEFORE trigger - is left undefined in the
+ ** documentation.
+ */
+ if( pPk ){
+ sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey);
+ VdbeCoverage(v);
+ }else{
+ sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid);
+ VdbeCoverage(v);
+ }
+
+ /* After-BEFORE-trigger-reload-loop:
+ ** If it did not delete it, the BEFORE trigger may still have modified
+ ** some of the columns of the row being updated. Load the values for
+ ** all columns not modified by the update statement into their registers
+ ** in case this has happened. Only unmodified columns are reloaded.
+ ** The values computed for modified columns use the values before the
+ ** BEFORE trigger runs. See test case trigger1-18.0 (added 2018-04-26)
+ ** for an example.
+ */
+ for(i=0, k=regNew; i<pTab->nCol; i++, k++){
+ if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
+ if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
+ }else if( aXRef[i]<0 && i!=pTab->iPKey ){
+ sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
+ }
+ }
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ if( pTab->tabFlags & TF_HasGenerated ){
+ testcase( pTab->tabFlags & TF_HasVirtual );
+ testcase( pTab->tabFlags & TF_HasStored );
+ sqlite3ComputeGeneratedColumns(pParse, regNew, pTab);
+ }
+#endif
+ }
+ }
+
+ if( !isView ){
+ /* Do constraint checks. */
+ assert( regOldRowid>0 );
+ sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
+ regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
+ aXRef, 0);
+
+ /* If REPLACE conflict handling may have been used, or if the PK of the
+ ** row is changing, then the GenerateConstraintChecks() above may have
+ ** moved cursor iDataCur. Reseek it. */
+ if( bReplace || chngKey ){
+ if( pPk ){
+ sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey);
+ }else{
+ sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid);
+ }
+ VdbeCoverageNeverTaken(v);
+ }
+
+ /* Do FK constraint checks. */
+ if( hasFK ){
+ sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
+ }
+
+ /* Delete the index entries associated with the current record. */
+ sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
+
+ /* We must run the OP_FinishSeek opcode to resolve a prior
+ ** OP_DeferredSeek if there is any possibility that there have been
+ ** no OP_Column opcodes since the OP_DeferredSeek was issued. But
+ ** we want to avoid the OP_FinishSeek if possible, as running it
+ ** costs CPU cycles. */
+ if( bFinishSeek ){
+ sqlite3VdbeAddOp1(v, OP_FinishSeek, iDataCur);
+ }
+
+ /* If changing the rowid value, or if there are foreign key constraints
+ ** to process, delete the old record. Otherwise, add a noop OP_Delete
+ ** to invoke the pre-update hook.
+ **
+ ** That (regNew==regnewRowid+1) is true is also important for the
+ ** pre-update hook. If the caller invokes preupdate_new(), the returned
+ ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
+ ** is the column index supplied by the user.
+ */
+ assert( regNew==regNewRowid+1 );
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+ sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
+ OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
+ regNewRowid
+ );
+ if( eOnePass==ONEPASS_MULTI ){
+ assert( hasFK==0 && chngKey==0 );
+ sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
+ }
+ if( !pParse->nested ){
+ sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
+ }
+#else
+ if( hasFK>1 || chngKey ){
+ sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
+ }
+#endif
+
+ if( hasFK ){
+ sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
+ }
+
+ /* Insert the new index entries and the new record. */
+ sqlite3CompleteInsertion(
+ pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
+ OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
+ 0, 0
+ );
+
+ /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
+ ** handle rows (possibly in other tables) that refer via a foreign key
+ ** to the row just updated. */
+ if( hasFK ){
+ sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
+ }
+ }
+
+ /* Increment the row counter
+ */
+ if( regRowCount ){
+ sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
+ }
+
+ sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
+ TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
+
+ /* Repeat the above with the next record to be updated, until
+ ** all record selected by the WHERE clause have been updated.
+ */
+ if( eOnePass==ONEPASS_SINGLE ){
+ /* Nothing to do at end-of-loop for a single-pass */
+ }else if( eOnePass==ONEPASS_MULTI ){
+ sqlite3VdbeResolveLabel(v, labelContinue);
+ sqlite3WhereEnd(pWInfo);
+ }else if( pPk || nChangeFrom ){
+ sqlite3VdbeResolveLabel(v, labelContinue);
+ sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
+ }else{
+ sqlite3VdbeGoto(v, labelContinue);
+ }
+ sqlite3VdbeResolveLabel(v, labelBreak);
+
+ /* Update the sqlite_sequence table by storing the content of the
+ ** maximum rowid counter values recorded while inserting into
+ ** autoincrement tables.
+ */
+ if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){
+ sqlite3AutoincrementEnd(pParse);
+ }
+
+ /*
+ ** Return the number of rows that were changed, if we are tracking
+ ** that information.
+ */
+ if( regRowCount ){
+ sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
+ sqlite3VdbeSetNumCols(v, 1);
+ sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
+ }
+
+update_cleanup:
+ sqlite3AuthContextPop(&sContext);
+ sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
+ sqlite3SrcListDelete(db, pTabList);
+ sqlite3ExprListDelete(db, pChanges);
+ sqlite3ExprDelete(db, pWhere);
+#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
+ sqlite3ExprListDelete(db, pOrderBy);
+ sqlite3ExprDelete(db, pLimit);
+#endif
+ return;
+}
+/* Make sure "isView" and other macros defined above are undefined. Otherwise
+** they may interfere with compilation of other functions in this file
+** (or in another file, if this file becomes part of the amalgamation). */
+#ifdef isView
+ #undef isView
+#endif
+#ifdef pTrigger
+ #undef pTrigger
+#endif
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/*
+** Generate code for an UPDATE of a virtual table.
+**
+** There are two possible strategies - the default and the special
+** "onepass" strategy. Onepass is only used if the virtual table
+** implementation indicates that pWhere may match at most one row.
+**
+** The default strategy is to create an ephemeral table that contains
+** for each row to be changed:
+**
+** (A) The original rowid of that row.
+** (B) The revised rowid for the row.
+** (C) The content of every column in the row.
+**
+** Then loop through the contents of this ephemeral table executing a
+** VUpdate for each row. When finished, drop the ephemeral table.
+**
+** The "onepass" strategy does not use an ephemeral table. Instead, it
+** stores the same values (A, B and C above) in a register array and
+** makes a single invocation of VUpdate.
+*/
+static void updateVirtualTable(
+ Parse *pParse, /* The parsing context */
+ SrcList *pSrc, /* The virtual table to be modified */
+ Table *pTab, /* The virtual table */
+ ExprList *pChanges, /* The columns to change in the UPDATE statement */
+ Expr *pRowid, /* Expression used to recompute the rowid */
+ int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
+ Expr *pWhere, /* WHERE clause of the UPDATE statement */
+ int onError /* ON CONFLICT strategy */
+){
+ Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
+ int ephemTab; /* Table holding the result of the SELECT */
+ int i; /* Loop counter */
+ sqlite3 *db = pParse->db; /* Database connection */
+ const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
+ WhereInfo *pWInfo = 0;
+ int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
+ int regArg; /* First register in VUpdate arg array */
+ int regRec; /* Register in which to assemble record */
+ int regRowid; /* Register for ephem table rowid */
+ int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
+ int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
+ int eOnePass; /* True to use onepass strategy */
+ int addr; /* Address of OP_OpenEphemeral */
+
+ /* Allocate nArg registers in which to gather the arguments for VUpdate. Then
+ ** create and open the ephemeral table in which the records created from
+ ** these arguments will be temporarily stored. */
+ assert( v );
+ ephemTab = pParse->nTab++;
+ addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
+ regArg = pParse->nMem + 1;
+ pParse->nMem += nArg;
+ if( pSrc->nSrc>1 ){
+ Expr *pRow;
+ ExprList *pList;
+ if( pRowid ){
+ pRow = sqlite3ExprDup(db, pRowid, 0);
+ }else{
+ pRow = sqlite3PExpr(pParse, TK_ROW, 0, 0);
+ }
+ pList = sqlite3ExprListAppend(pParse, 0, pRow);
+
+ for(i=0; i<pTab->nCol; i++){
+ if( aXRef[i]>=0 ){
+ pList = sqlite3ExprListAppend(pParse, pList,
+ sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0)
+ );
+ }else{
+ pList = sqlite3ExprListAppend(pParse, pList, exprRowColumn(pParse, i));
+ }
+ }
+
+ updateFromSelect(pParse, ephemTab, 0, pList, pSrc, pWhere, 0, 0);
+ sqlite3ExprListDelete(db, pList);
+ eOnePass = ONEPASS_OFF;
+ }else{
+ regRec = ++pParse->nMem;
+ regRowid = ++pParse->nMem;
+
+ /* Start scanning the virtual table */
+ pWInfo = sqlite3WhereBegin(pParse, pSrc,pWhere,0,0,WHERE_ONEPASS_DESIRED,0);
+ if( pWInfo==0 ) return;
+
+ /* Populate the argument registers. */
+ for(i=0; i<pTab->nCol; i++){
+ assert( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 );
+ if( aXRef[i]>=0 ){
+ sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
+ }else{
+ sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
+ sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* For sqlite3_vtab_nochange() */
+ }
+ }
+ if( HasRowid(pTab) ){
+ sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
+ if( pRowid ){
+ sqlite3ExprCode(pParse, pRowid, regArg+1);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
+ }
+ }else{
+ Index *pPk; /* PRIMARY KEY index */
+ i16 iPk; /* PRIMARY KEY column */
+ pPk = sqlite3PrimaryKeyIndex(pTab);
+ assert( pPk!=0 );
+ assert( pPk->nKeyCol==1 );
+ iPk = pPk->aiColumn[0];
+ sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
+ sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
+ }
+
+ eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
+
+ /* There is no ONEPASS_MULTI on virtual tables */
+ assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
+
+ if( eOnePass ){
+ /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
+ ** above. */
+ sqlite3VdbeChangeToNoop(v, addr);
+ sqlite3VdbeAddOp1(v, OP_Close, iCsr);
+ }else{
+ /* Create a record from the argument register contents and insert it into
+ ** the ephemeral table. */
+ sqlite3MultiWrite(pParse);
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
+#if defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_NULL_TRIM)
+ /* Signal an assert() within OP_MakeRecord that it is allowed to
+ ** accept no-change records with serial_type 10 */
+ sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
+#endif
+ sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
+ sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
+ }
+ }
+
+
+ if( eOnePass==ONEPASS_OFF ){
+ /* End the virtual table scan */
+ if( pSrc->nSrc==1 ){
+ sqlite3WhereEnd(pWInfo);
+ }
+
+ /* Begin scannning through the ephemeral table. */
+ addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
+
+ /* Extract arguments from the current row of the ephemeral table and
+ ** invoke the VUpdate method. */
+ for(i=0; i<nArg; i++){
+ sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
+ }
+ }
+ sqlite3VtabMakeWritable(pParse, pTab);
+ sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
+ sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
+ sqlite3MayAbort(pParse);
+
+ /* End of the ephemeral table scan. Or, if using the onepass strategy,
+ ** jump to here if the scan visited zero rows. */
+ if( eOnePass==ONEPASS_OFF ){
+ sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
+ sqlite3VdbeJumpHere(v, addr);
+ sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
+ }else{
+ sqlite3WhereEnd(pWInfo);
+ }
+}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+/************** End of update.c **********************************************/
+/************** Begin file upsert.c ******************************************/
+/*
+** 2018-04-12
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code to implement various aspects of UPSERT
+** processing and handling of the Upsert object.
+*/
+/* #include "sqliteInt.h" */
+
+#ifndef SQLITE_OMIT_UPSERT
+/*
+** Free a list of Upsert objects
+*/
+SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3 *db, Upsert *p){
+ if( p ){
+ sqlite3ExprListDelete(db, p->pUpsertTarget);
+ sqlite3ExprDelete(db, p->pUpsertTargetWhere);
+ sqlite3ExprListDelete(db, p->pUpsertSet);
+ sqlite3ExprDelete(db, p->pUpsertWhere);
+ sqlite3DbFree(db, p);
+ }
+}
+
+/*
+** Duplicate an Upsert object.
+*/
+SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3 *db, Upsert *p){
+ if( p==0 ) return 0;
+ return sqlite3UpsertNew(db,
+ sqlite3ExprListDup(db, p->pUpsertTarget, 0),
+ sqlite3ExprDup(db, p->pUpsertTargetWhere, 0),
+ sqlite3ExprListDup(db, p->pUpsertSet, 0),
+ sqlite3ExprDup(db, p->pUpsertWhere, 0)
+ );
+}
+
+/*
+** Create a new Upsert object.
+*/
+SQLITE_PRIVATE Upsert *sqlite3UpsertNew(
+ sqlite3 *db, /* Determines which memory allocator to use */
+ ExprList *pTarget, /* Target argument to ON CONFLICT, or NULL */
+ Expr *pTargetWhere, /* Optional WHERE clause on the target */
+ ExprList *pSet, /* UPDATE columns, or NULL for a DO NOTHING */
+ Expr *pWhere /* WHERE clause for the ON CONFLICT UPDATE */
+){
+ Upsert *pNew;
+ pNew = sqlite3DbMallocRaw(db, sizeof(Upsert));
+ if( pNew==0 ){
+ sqlite3ExprListDelete(db, pTarget);
+ sqlite3ExprDelete(db, pTargetWhere);
+ sqlite3ExprListDelete(db, pSet);
+ sqlite3ExprDelete(db, pWhere);
+ return 0;
+ }else{
+ pNew->pUpsertTarget = pTarget;
+ pNew->pUpsertTargetWhere = pTargetWhere;
+ pNew->pUpsertSet = pSet;
+ pNew->pUpsertWhere = pWhere;
+ pNew->pUpsertIdx = 0;
+ }
+ return pNew;
+}
+
+/*
+** Analyze the ON CONFLICT clause described by pUpsert. Resolve all
+** symbols in the conflict-target.
+**
+** Return SQLITE_OK if everything works, or an error code is something
+** is wrong.
+*/
+SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(
+ Parse *pParse, /* The parsing context */
+ SrcList *pTabList, /* Table into which we are inserting */
+ Upsert *pUpsert /* The ON CONFLICT clauses */
+){
+ Table *pTab; /* That table into which we are inserting */
+ int rc; /* Result code */
+ int iCursor; /* Cursor used by pTab */
+ Index *pIdx; /* One of the indexes of pTab */
+ ExprList *pTarget; /* The conflict-target clause */
+ Expr *pTerm; /* One term of the conflict-target clause */
+ NameContext sNC; /* Context for resolving symbolic names */
+ Expr sCol[2]; /* Index column converted into an Expr */
+
+ assert( pTabList->nSrc==1 );
+ assert( pTabList->a[0].pTab!=0 );
+ assert( pUpsert!=0 );
+ assert( pUpsert->pUpsertTarget!=0 );
+
+ /* Resolve all symbolic names in the conflict-target clause, which
+ ** includes both the list of columns and the optional partial-index
+ ** WHERE clause.
+ */
+ memset(&sNC, 0, sizeof(sNC));
+ sNC.pParse = pParse;
+ sNC.pSrcList = pTabList;
+ rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
+ if( rc ) return rc;
+ rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
+ if( rc ) return rc;
+
+ /* Check to see if the conflict target matches the rowid. */
+ pTab = pTabList->a[0].pTab;
+ pTarget = pUpsert->pUpsertTarget;
+ iCursor = pTabList->a[0].iCursor;
+ if( HasRowid(pTab)
+ && pTarget->nExpr==1
+ && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN
+ && pTerm->iColumn==XN_ROWID
+ ){
+ /* The conflict-target is the rowid of the primary table */
+ assert( pUpsert->pUpsertIdx==0 );
+ return SQLITE_OK;
+ }
+
+ /* Initialize sCol[0..1] to be an expression parse tree for a
+ ** single column of an index. The sCol[0] node will be the TK_COLLATE
+ ** operator and sCol[1] will be the TK_COLUMN operator. Code below
+ ** will populate the specific collation and column number values
+ ** prior to comparing against the conflict-target expression.
+ */
+ memset(sCol, 0, sizeof(sCol));
+ sCol[0].op = TK_COLLATE;
+ sCol[0].pLeft = &sCol[1];
+ sCol[1].op = TK_COLUMN;
+ sCol[1].iTable = pTabList->a[0].iCursor;
+
+ /* Check for matches against other indexes */
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+ int ii, jj, nn;
+ if( !IsUniqueIndex(pIdx) ) continue;
+ if( pTarget->nExpr!=pIdx->nKeyCol ) continue;
+ if( pIdx->pPartIdxWhere ){
+ if( pUpsert->pUpsertTargetWhere==0 ) continue;
+ if( sqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere,
+ pIdx->pPartIdxWhere, iCursor)!=0 ){
+ continue;
+ }
+ }
+ nn = pIdx->nKeyCol;
+ for(ii=0; ii<nn; ii++){
+ Expr *pExpr;
+ sCol[0].u.zToken = (char*)pIdx->azColl[ii];
+ if( pIdx->aiColumn[ii]==XN_EXPR ){
+ assert( pIdx->aColExpr!=0 );
+ assert( pIdx->aColExpr->nExpr>ii );
+ pExpr = pIdx->aColExpr->a[ii].pExpr;
+ if( pExpr->op!=TK_COLLATE ){
+ sCol[0].pLeft = pExpr;
+ pExpr = &sCol[0];
+ }
+ }else{
+ sCol[0].pLeft = &sCol[1];
+ sCol[1].iColumn = pIdx->aiColumn[ii];
+ pExpr = &sCol[0];
+ }
+ for(jj=0; jj<nn; jj++){
+ if( sqlite3ExprCompare(pParse, pTarget->a[jj].pExpr, pExpr,iCursor)<2 ){
+ break; /* Column ii of the index matches column jj of target */
+ }
+ }
+ if( jj>=nn ){
+ /* The target contains no match for column jj of the index */
+ break;
+ }
+ }
+ if( ii<nn ){
+ /* Column ii of the index did not match any term of the conflict target.
+ ** Continue the search with the next index. */
+ continue;
+ }
+ pUpsert->pUpsertIdx = pIdx;
+ return SQLITE_OK;
+ }
+ sqlite3ErrorMsg(pParse, "ON CONFLICT clause does not match any "
+ "PRIMARY KEY or UNIQUE constraint");
+ return SQLITE_ERROR;
+}
+
+/*
+** Generate bytecode that does an UPDATE as part of an upsert.
+**
+** If pIdx is NULL, then the UNIQUE constraint that failed was the IPK.
+** In this case parameter iCur is a cursor open on the table b-tree that
+** currently points to the conflicting table row. Otherwise, if pIdx
+** is not NULL, then pIdx is the constraint that failed and iCur is a
+** cursor points to the conflicting row.
+*/
+SQLITE_PRIVATE void sqlite3UpsertDoUpdate(
+ Parse *pParse, /* The parsing and code-generating context */
+ Upsert *pUpsert, /* The ON CONFLICT clause for the upsert */
+ Table *pTab, /* The table being updated */
+ Index *pIdx, /* The UNIQUE constraint that failed */
+ int iCur /* Cursor for pIdx (or pTab if pIdx==NULL) */
+){
+ Vdbe *v = pParse->pVdbe;
+ sqlite3 *db = pParse->db;
+ SrcList *pSrc; /* FROM clause for the UPDATE */
+ int iDataCur;
+ int i;
+
+ assert( v!=0 );
+ assert( pUpsert!=0 );
+ VdbeNoopComment((v, "Begin DO UPDATE of UPSERT"));
+ iDataCur = pUpsert->iDataCur;
+ if( pIdx && iCur!=iDataCur ){
+ if( HasRowid(pTab) ){
+ int regRowid = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp2(v, OP_IdxRowid, iCur, regRowid);
+ sqlite3VdbeAddOp3(v, OP_SeekRowid, iDataCur, 0, regRowid);
+ VdbeCoverage(v);
+ sqlite3ReleaseTempReg(pParse, regRowid);
+ }else{
+ Index *pPk = sqlite3PrimaryKeyIndex(pTab);
+ int nPk = pPk->nKeyCol;
+ int iPk = pParse->nMem+1;
+ pParse->nMem += nPk;
+ for(i=0; i<nPk; i++){
+ int k;
+ assert( pPk->aiColumn[i]>=0 );
+ k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
+ sqlite3VdbeAddOp3(v, OP_Column, iCur, k, iPk+i);
+ VdbeComment((v, "%s.%s", pIdx->zName,
+ pTab->aCol[pPk->aiColumn[i]].zName));
+ }
+ sqlite3VdbeVerifyAbortable(v, OE_Abort);
+ i = sqlite3VdbeAddOp4Int(v, OP_Found, iDataCur, 0, iPk, nPk);
+ VdbeCoverage(v);
+ sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CORRUPT, OE_Abort, 0,
+ "corrupt database", P4_STATIC);
+ sqlite3MayAbort(pParse);
+ sqlite3VdbeJumpHere(v, i);
+ }
+ }
+ /* pUpsert does not own pUpsertSrc - the outer INSERT statement does. So
+ ** we have to make a copy before passing it down into sqlite3Update() */
+ pSrc = sqlite3SrcListDup(db, pUpsert->pUpsertSrc, 0);
+ /* excluded.* columns of type REAL need to be converted to a hard real */
+ for(i=0; i<pTab->nCol; i++){
+ if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
+ sqlite3VdbeAddOp1(v, OP_RealAffinity, pUpsert->regData+i);
+ }
+ }
+ sqlite3Update(pParse, pSrc, pUpsert->pUpsertSet,
+ pUpsert->pUpsertWhere, OE_Abort, 0, 0, pUpsert);
+ pUpsert->pUpsertSet = 0; /* Will have been deleted by sqlite3Update() */
+ pUpsert->pUpsertWhere = 0; /* Will have been deleted by sqlite3Update() */
+ VdbeNoopComment((v, "End DO UPDATE of UPSERT"));
+}
+
+#endif /* SQLITE_OMIT_UPSERT */
+
+/************** End of upsert.c **********************************************/
+/************** Begin file vacuum.c ******************************************/
+/*
+** 2003 April 6
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code used to implement the VACUUM command.
+**
+** Most of the code in this file may be omitted by defining the
+** SQLITE_OMIT_VACUUM macro.
+*/
+/* #include "sqliteInt.h" */
+/* #include "vdbeInt.h" */
+
+#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
+
+/*
+** Execute zSql on database db.
+**
+** If zSql returns rows, then each row will have exactly one
+** column. (This will only happen if zSql begins with "SELECT".)
+** Take each row of result and call execSql() again recursively.
+**
+** The execSqlF() routine does the same thing, except it accepts
+** a format string as its third argument
+*/
+static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
+ sqlite3_stmt *pStmt;
+ int rc;
+
+ /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
+ rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
+ if( rc!=SQLITE_OK ) return rc;
+ while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
+ const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
+ assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
+ /* The secondary SQL must be one of CREATE TABLE, CREATE INDEX,
+ ** or INSERT. Historically there have been attacks that first
+ ** corrupt the sqlite_schema.sql field with other kinds of statements
+ ** then run VACUUM to get those statements to execute at inappropriate
+ ** times. */
+ if( zSubSql
+ && (strncmp(zSubSql,"CRE",3)==0 || strncmp(zSubSql,"INS",3)==0)
+ ){
+ rc = execSql(db, pzErrMsg, zSubSql);
+ if( rc!=SQLITE_OK ) break;
+ }
+ }
+ assert( rc!=SQLITE_ROW );
+ if( rc==SQLITE_DONE ) rc = SQLITE_OK;
+ if( rc ){
+ sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
+ }
+ (void)sqlite3_finalize(pStmt);
+ return rc;
+}
+static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
+ char *z;
+ va_list ap;
+ int rc;
+ va_start(ap, zSql);
+ z = sqlite3VMPrintf(db, zSql, ap);
+ va_end(ap);
+ if( z==0 ) return SQLITE_NOMEM;
+ rc = execSql(db, pzErrMsg, z);
+ sqlite3DbFree(db, z);
+ return rc;
+}
+
+/*
+** The VACUUM command is used to clean up the database,
+** collapse free space, etc. It is modelled after the VACUUM command
+** in PostgreSQL. The VACUUM command works as follows:
+**
+** (1) Create a new transient database file
+** (2) Copy all content from the database being vacuumed into
+** the new transient database file
+** (3) Copy content from the transient database back into the
+** original database.
+**
+** The transient database requires temporary disk space approximately
+** equal to the size of the original database. The copy operation of
+** step (3) requires additional temporary disk space approximately equal
+** to the size of the original database for the rollback journal.
+** Hence, temporary disk space that is approximately 2x the size of the
+** original database is required. Every page of the database is written
+** approximately 3 times: Once for step (2) and twice for step (3).
+** Two writes per page are required in step (3) because the original
+** database content must be written into the rollback journal prior to
+** overwriting the database with the vacuumed content.
+**
+** Only 1x temporary space and only 1x writes would be required if
+** the copy of step (3) were replaced by deleting the original database
+** and renaming the transient database as the original. But that will
+** not work if other processes are attached to the original database.
+** And a power loss in between deleting the original and renaming the
+** transient would cause the database file to appear to be deleted
+** following reboot.
+*/
+SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm, Expr *pInto){
+ Vdbe *v = sqlite3GetVdbe(pParse);
+ int iDb = 0;
+ if( v==0 ) goto build_vacuum_end;
+ if( pParse->nErr ) goto build_vacuum_end;
+ if( pNm ){
+#ifndef SQLITE_BUG_COMPATIBLE_20160819
+ /* Default behavior: Report an error if the argument to VACUUM is
+ ** not recognized */
+ iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
+ if( iDb<0 ) goto build_vacuum_end;
+#else
+ /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
+ ** to VACUUM are silently ignored. This is a back-out of a bug fix that
+ ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
+ ** The buggy behavior is required for binary compatibility with some
+ ** legacy applications. */
+ iDb = sqlite3FindDb(pParse->db, pNm);
+ if( iDb<0 ) iDb = 0;
+#endif
+ }
+ if( iDb!=1 ){
+ int iIntoReg = 0;
+ if( pInto && sqlite3ResolveSelfReference(pParse,0,0,pInto,0)==0 ){
+ iIntoReg = ++pParse->nMem;
+ sqlite3ExprCode(pParse, pInto, iIntoReg);
+ }
+ sqlite3VdbeAddOp2(v, OP_Vacuum, iDb, iIntoReg);
+ sqlite3VdbeUsesBtree(v, iDb);
+ }
+build_vacuum_end:
+ sqlite3ExprDelete(pParse->db, pInto);
+ return;
+}
+
+/*
+** This routine implements the OP_Vacuum opcode of the VDBE.
+*/
+SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(
+ char **pzErrMsg, /* Write error message here */
+ sqlite3 *db, /* Database connection */
+ int iDb, /* Which attached DB to vacuum */
+ sqlite3_value *pOut /* Write results here, if not NULL. VACUUM INTO */
+){
+ int rc = SQLITE_OK; /* Return code from service routines */
+ Btree *pMain; /* The database being vacuumed */
+ Btree *pTemp; /* The temporary database we vacuum into */
+ u32 saved_mDbFlags; /* Saved value of db->mDbFlags */
+ u64 saved_flags; /* Saved value of db->flags */
+ int saved_nChange; /* Saved value of db->nChange */
+ int saved_nTotalChange; /* Saved value of db->nTotalChange */
+ u32 saved_openFlags; /* Saved value of db->openFlags */
+ u8 saved_mTrace; /* Saved trace settings */
+ Db *pDb = 0; /* Database to detach at end of vacuum */
+ int isMemDb; /* True if vacuuming a :memory: database */
+ int nRes; /* Bytes of reserved space at the end of each page */
+ int nDb; /* Number of attached databases */
+ const char *zDbMain; /* Schema name of database to vacuum */
+ const char *zOut; /* Name of output file */
+
+ if( !db->autoCommit ){
+ sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
+ return SQLITE_ERROR; /* IMP: R-12218-18073 */
+ }
+ if( db->nVdbeActive>1 ){
+ sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
+ return SQLITE_ERROR; /* IMP: R-15610-35227 */
+ }
+ saved_openFlags = db->openFlags;
+ if( pOut ){
+ if( sqlite3_value_type(pOut)!=SQLITE_TEXT ){
+ sqlite3SetString(pzErrMsg, db, "non-text filename");
+ return SQLITE_ERROR;
+ }
+ zOut = (const char*)sqlite3_value_text(pOut);
+ db->openFlags &= ~SQLITE_OPEN_READONLY;
+ db->openFlags |= SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
+ }else{
+ zOut = "";
+ }
+
+ /* Save the current value of the database flags so that it can be
+ ** restored before returning. Then set the writable-schema flag, and
+ ** disable CHECK and foreign key constraints. */
+ saved_flags = db->flags;
+ saved_mDbFlags = db->mDbFlags;
+ saved_nChange = db->nChange;
+ saved_nTotalChange = db->nTotalChange;
+ saved_mTrace = db->mTrace;
+ db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
+ db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
+ db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder
+ | SQLITE_Defensive | SQLITE_CountRows);
+ db->mTrace = 0;
+
+ zDbMain = db->aDb[iDb].zDbSName;
+ pMain = db->aDb[iDb].pBt;
+ isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
+
+ /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
+ ** can be set to 'off' for this file, as it is not recovered if a crash
+ ** occurs anyway. The integrity of the database is maintained by a
+ ** (possibly synchronous) transaction opened on the main database before
+ ** sqlite3BtreeCopyFile() is called.
+ **
+ ** An optimisation would be to use a non-journaled pager.
+ ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
+ ** that actually made the VACUUM run slower. Very little journalling
+ ** actually occurs when doing a vacuum since the vacuum_db is initially
+ ** empty. Only the journal header is written. Apparently it takes more
+ ** time to parse and run the PRAGMA to turn journalling off than it does
+ ** to write the journal header file.
+ */
+ nDb = db->nDb;
+ rc = execSqlF(db, pzErrMsg, "ATTACH %Q AS vacuum_db", zOut);
+ db->openFlags = saved_openFlags;
+ if( rc!=SQLITE_OK ) goto end_of_vacuum;
+ assert( (db->nDb-1)==nDb );
+ pDb = &db->aDb[nDb];
+ assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
+ pTemp = pDb->pBt;
+ if( pOut ){
+ sqlite3_file *id = sqlite3PagerFile(sqlite3BtreePager(pTemp));
+ i64 sz = 0;
+ if( id->pMethods!=0 && (sqlite3OsFileSize(id, &sz)!=SQLITE_OK || sz>0) ){
+ rc = SQLITE_ERROR;
+ sqlite3SetString(pzErrMsg, db, "output file already exists");
+ goto end_of_vacuum;
+ }
+ db->mDbFlags |= DBFLAG_VacuumInto;
+ }
+ nRes = sqlite3BtreeGetRequestedReserve(pMain);
+
+ sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
+ sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
+ sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
+
+ /* Begin a transaction and take an exclusive lock on the main database
+ ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
+ ** to ensure that we do not try to change the page-size on a WAL database.
+ */
+ rc = execSql(db, pzErrMsg, "BEGIN");
+ if( rc!=SQLITE_OK ) goto end_of_vacuum;
+ rc = sqlite3BtreeBeginTrans(pMain, pOut==0 ? 2 : 0, 0);
+ if( rc!=SQLITE_OK ) goto end_of_vacuum;
+
+ /* Do not attempt to change the page size for a WAL database */
+ if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
+ ==PAGER_JOURNALMODE_WAL ){
+ db->nextPagesize = 0;
+ }
+
+ if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
+ || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
+ || NEVER(db->mallocFailed)
+ ){
+ rc = SQLITE_NOMEM_BKPT;
+ goto end_of_vacuum;
+ }
+
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
+ sqlite3BtreeGetAutoVacuum(pMain));
+#endif
+
+ /* Query the schema of the main database. Create a mirror schema
+ ** in the temporary database.
+ */
+ db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
+ rc = execSqlF(db, pzErrMsg,
+ "SELECT sql FROM \"%w\".sqlite_schema"
+ " WHERE type='table'AND name<>'sqlite_sequence'"
+ " AND coalesce(rootpage,1)>0",
+ zDbMain
+ );
+ if( rc!=SQLITE_OK ) goto end_of_vacuum;
+ rc = execSqlF(db, pzErrMsg,
+ "SELECT sql FROM \"%w\".sqlite_schema"
+ " WHERE type='index'",
+ zDbMain
+ );
+ if( rc!=SQLITE_OK ) goto end_of_vacuum;
+ db->init.iDb = 0;
+
+ /* Loop through the tables in the main database. For each, do
+ ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
+ ** the contents to the temporary database.
+ */
+ rc = execSqlF(db, pzErrMsg,
+ "SELECT'INSERT INTO vacuum_db.'||quote(name)"
+ "||' SELECT*FROM\"%w\".'||quote(name)"
+ "FROM vacuum_db.sqlite_schema "
+ "WHERE type='table'AND coalesce(rootpage,1)>0",
+ zDbMain
+ );
+ assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
+ db->mDbFlags &= ~DBFLAG_Vacuum;
+ if( rc!=SQLITE_OK ) goto end_of_vacuum;
+
+ /* Copy the triggers, views, and virtual tables from the main database
+ ** over to the temporary database. None of these objects has any
+ ** associated storage, so all we have to do is copy their entries
+ ** from the schema table.
+ */
+ rc = execSqlF(db, pzErrMsg,
+ "INSERT INTO vacuum_db.sqlite_schema"
+ " SELECT*FROM \"%w\".sqlite_schema"
+ " WHERE type IN('view','trigger')"
+ " OR(type='table'AND rootpage=0)",
+ zDbMain
+ );
+ if( rc ) goto end_of_vacuum;
+
+ /* At this point, there is a write transaction open on both the
+ ** vacuum database and the main database. Assuming no error occurs,
+ ** both transactions are closed by this block - the main database
+ ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
+ ** call to sqlite3BtreeCommit().
+ */
+ {
+ u32 meta;
+ int i;
+
+ /* This array determines which meta meta values are preserved in the
+ ** vacuum. Even entries are the meta value number and odd entries
+ ** are an increment to apply to the meta value after the vacuum.
+ ** The increment is used to increase the schema cookie so that other
+ ** connections to the same database will know to reread the schema.
+ */
+ static const unsigned char aCopy[] = {
+ BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
+ BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
+ BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
+ BTREE_USER_VERSION, 0, /* Preserve the user version */
+ BTREE_APPLICATION_ID, 0, /* Preserve the application id */
+ };
+
+ assert( SQLITE_TXN_WRITE==sqlite3BtreeTxnState(pTemp) );
+ assert( pOut!=0 || SQLITE_TXN_WRITE==sqlite3BtreeTxnState(pMain) );
+
+ /* Copy Btree meta values */
+ for(i=0; i<ArraySize(aCopy); i+=2){
+ /* GetMeta() and UpdateMeta() cannot fail in this context because
+ ** we already have page 1 loaded into cache and marked dirty. */
+ sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
+ rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
+ if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
+ }
+
+ if( pOut==0 ){
+ rc = sqlite3BtreeCopyFile(pMain, pTemp);
+ }
+ if( rc!=SQLITE_OK ) goto end_of_vacuum;
+ rc = sqlite3BtreeCommit(pTemp);
+ if( rc!=SQLITE_OK ) goto end_of_vacuum;
+#ifndef SQLITE_OMIT_AUTOVACUUM
+ if( pOut==0 ){
+ sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
+ }
+#endif
+ }
+
+ assert( rc==SQLITE_OK );
+ if( pOut==0 ){
+ rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
+ }
+
+end_of_vacuum:
+ /* Restore the original value of db->flags */
+ db->init.iDb = 0;
+ db->mDbFlags = saved_mDbFlags;
+ db->flags = saved_flags;
+ db->nChange = saved_nChange;
+ db->nTotalChange = saved_nTotalChange;
+ db->mTrace = saved_mTrace;
+ sqlite3BtreeSetPageSize(pMain, -1, 0, 1);
+
+ /* Currently there is an SQL level transaction open on the vacuum
+ ** database. No locks are held on any other files (since the main file
+ ** was committed at the btree level). So it safe to end the transaction
+ ** by manually setting the autoCommit flag to true and detaching the
+ ** vacuum database. The vacuum_db journal file is deleted when the pager
+ ** is closed by the DETACH.
+ */
+ db->autoCommit = 1;
+
+ if( pDb ){
+ sqlite3BtreeClose(pDb->pBt);
+ pDb->pBt = 0;
+ pDb->pSchema = 0;
+ }
+
+ /* This both clears the schemas and reduces the size of the db->aDb[]
+ ** array. */
+ sqlite3ResetAllSchemasOfConnection(db);
+
+ return rc;
+}
+
+#endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
+
+/************** End of vacuum.c **********************************************/
+/************** Begin file vtab.c ********************************************/
+/*
+** 2006 June 10
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code used to help implement virtual tables.
+*/
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/* #include "sqliteInt.h" */
+
+/*
+** Before a virtual table xCreate() or xConnect() method is invoked, the
+** sqlite3.pVtabCtx member variable is set to point to an instance of
+** this struct allocated on the stack. It is used by the implementation of
+** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
+** are invoked only from within xCreate and xConnect methods.
+*/
+struct VtabCtx {
+ VTable *pVTable; /* The virtual table being constructed */
+ Table *pTab; /* The Table object to which the virtual table belongs */
+ VtabCtx *pPrior; /* Parent context (if any) */
+ int bDeclared; /* True after sqlite3_declare_vtab() is called */
+};
+
+/*
+** Construct and install a Module object for a virtual table. When this
+** routine is called, it is guaranteed that all appropriate locks are held
+** and the module is not already part of the connection.
+**
+** If there already exists a module with zName, replace it with the new one.
+** If pModule==0, then delete the module zName if it exists.
+*/
+SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
+ sqlite3 *db, /* Database in which module is registered */
+ const char *zName, /* Name assigned to this module */
+ const sqlite3_module *pModule, /* The definition of the module */
+ void *pAux, /* Context pointer for xCreate/xConnect */
+ void (*xDestroy)(void *) /* Module destructor function */
+){
+ Module *pMod;
+ Module *pDel;
+ char *zCopy;
+ if( pModule==0 ){
+ zCopy = (char*)zName;
+ pMod = 0;
+ }else{
+ int nName = sqlite3Strlen30(zName);
+ pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1);
+ if( pMod==0 ){
+ sqlite3OomFault(db);
+ return 0;
+ }
+ zCopy = (char *)(&pMod[1]);
+ memcpy(zCopy, zName, nName+1);
+ pMod->zName = zCopy;
+ pMod->pModule = pModule;
+ pMod->pAux = pAux;
+ pMod->xDestroy = xDestroy;
+ pMod->pEpoTab = 0;
+ pMod->nRefModule = 1;
+ }
+ pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
+ if( pDel ){
+ if( pDel==pMod ){
+ sqlite3OomFault(db);
+ sqlite3DbFree(db, pDel);
+ pMod = 0;
+ }else{
+ sqlite3VtabEponymousTableClear(db, pDel);
+ sqlite3VtabModuleUnref(db, pDel);
+ }
+ }
+ return pMod;
+}
+
+/*
+** The actual function that does the work of creating a new module.
+** This function implements the sqlite3_create_module() and
+** sqlite3_create_module_v2() interfaces.
+*/
+static int createModule(
+ sqlite3 *db, /* Database in which module is registered */
+ const char *zName, /* Name assigned to this module */
+ const sqlite3_module *pModule, /* The definition of the module */
+ void *pAux, /* Context pointer for xCreate/xConnect */
+ void (*xDestroy)(void *) /* Module destructor function */
+){
+ int rc = SQLITE_OK;
+
+ sqlite3_mutex_enter(db->mutex);
+ (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
+ rc = sqlite3ApiExit(db, rc);
+ if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+
+/*
+** External API function used to create a new virtual-table module.
+*/
+SQLITE_API int sqlite3_create_module(
+ sqlite3 *db, /* Database in which module is registered */
+ const char *zName, /* Name assigned to this module */
+ const sqlite3_module *pModule, /* The definition of the module */
+ void *pAux /* Context pointer for xCreate/xConnect */
+){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
+#endif
+ return createModule(db, zName, pModule, pAux, 0);
+}
+
+/*
+** External API function used to create a new virtual-table module.
+*/
+SQLITE_API int sqlite3_create_module_v2(
+ sqlite3 *db, /* Database in which module is registered */
+ const char *zName, /* Name assigned to this module */
+ const sqlite3_module *pModule, /* The definition of the module */
+ void *pAux, /* Context pointer for xCreate/xConnect */
+ void (*xDestroy)(void *) /* Module destructor function */
+){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
+#endif
+ return createModule(db, zName, pModule, pAux, xDestroy);
+}
+
+/*
+** External API to drop all virtual-table modules, except those named
+** on the azNames list.
+*/
+SQLITE_API int sqlite3_drop_modules(sqlite3 *db, const char** azNames){
+ HashElem *pThis, *pNext;
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+#endif
+ for(pThis=sqliteHashFirst(&db->aModule); pThis; pThis=pNext){
+ Module *pMod = (Module*)sqliteHashData(pThis);
+ pNext = sqliteHashNext(pThis);
+ if( azNames ){
+ int ii;
+ for(ii=0; azNames[ii]!=0 && strcmp(azNames[ii],pMod->zName)!=0; ii++){}
+ if( azNames[ii]!=0 ) continue;
+ }
+ createModule(db, pMod->zName, 0, 0, 0);
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Decrement the reference count on a Module object. Destroy the
+** module when the reference count reaches zero.
+*/
+SQLITE_PRIVATE void sqlite3VtabModuleUnref(sqlite3 *db, Module *pMod){
+ assert( pMod->nRefModule>0 );
+ pMod->nRefModule--;
+ if( pMod->nRefModule==0 ){
+ if( pMod->xDestroy ){
+ pMod->xDestroy(pMod->pAux);
+ }
+ assert( pMod->pEpoTab==0 );
+ sqlite3DbFree(db, pMod);
+ }
+}
+
+/*
+** Lock the virtual table so that it cannot be disconnected.
+** Locks nest. Every lock should have a corresponding unlock.
+** If an unlock is omitted, resources leaks will occur.
+**
+** If a disconnect is attempted while a virtual table is locked,
+** the disconnect is deferred until all locks have been removed.
+*/
+SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
+ pVTab->nRef++;
+}
+
+
+/*
+** pTab is a pointer to a Table structure representing a virtual-table.
+** Return a pointer to the VTable object used by connection db to access
+** this virtual-table, if one has been created, or NULL otherwise.
+*/
+SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
+ VTable *pVtab;
+ assert( IsVirtual(pTab) );
+ for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
+ return pVtab;
+}
+
+/*
+** Decrement the ref-count on a virtual table object. When the ref-count
+** reaches zero, call the xDisconnect() method to delete the object.
+*/
+SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
+ sqlite3 *db = pVTab->db;
+
+ assert( db );
+ assert( pVTab->nRef>0 );
+ assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
+
+ pVTab->nRef--;
+ if( pVTab->nRef==0 ){
+ sqlite3_vtab *p = pVTab->pVtab;
+ sqlite3VtabModuleUnref(pVTab->db, pVTab->pMod);
+ if( p ){
+ p->pModule->xDisconnect(p);
+ }
+ sqlite3DbFree(db, pVTab);
+ }
+}
+
+/*
+** Table p is a virtual table. This function moves all elements in the
+** p->pVTable list to the sqlite3.pDisconnect lists of their associated
+** database connections to be disconnected at the next opportunity.
+** Except, if argument db is not NULL, then the entry associated with
+** connection db is left in the p->pVTable list.
+*/
+static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
+ VTable *pRet = 0;
+ VTable *pVTable = p->pVTable;
+ p->pVTable = 0;
+
+ /* Assert that the mutex (if any) associated with the BtShared database
+ ** that contains table p is held by the caller. See header comments
+ ** above function sqlite3VtabUnlockList() for an explanation of why
+ ** this makes it safe to access the sqlite3.pDisconnect list of any
+ ** database connection that may have an entry in the p->pVTable list.
+ */
+ assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
+
+ while( pVTable ){
+ sqlite3 *db2 = pVTable->db;
+ VTable *pNext = pVTable->pNext;
+ assert( db2 );
+ if( db2==db ){
+ pRet = pVTable;
+ p->pVTable = pRet;
+ pRet->pNext = 0;
+ }else{
+ pVTable->pNext = db2->pDisconnect;
+ db2->pDisconnect = pVTable;
+ }
+ pVTable = pNext;
+ }
+
+ assert( !db || pRet );
+ return pRet;
+}
+
+/*
+** Table *p is a virtual table. This function removes the VTable object
+** for table *p associated with database connection db from the linked
+** list in p->pVTab. It also decrements the VTable ref count. This is
+** used when closing database connection db to free all of its VTable
+** objects without disturbing the rest of the Schema object (which may
+** be being used by other shared-cache connections).
+*/
+SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
+ VTable **ppVTab;
+
+ assert( IsVirtual(p) );
+ assert( sqlite3BtreeHoldsAllMutexes(db) );
+ assert( sqlite3_mutex_held(db->mutex) );
+
+ for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
+ if( (*ppVTab)->db==db ){
+ VTable *pVTab = *ppVTab;
+ *ppVTab = pVTab->pNext;
+ sqlite3VtabUnlock(pVTab);
+ break;
+ }
+ }
+}
+
+
+/*
+** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
+**
+** This function may only be called when the mutexes associated with all
+** shared b-tree databases opened using connection db are held by the
+** caller. This is done to protect the sqlite3.pDisconnect list. The
+** sqlite3.pDisconnect list is accessed only as follows:
+**
+** 1) By this function. In this case, all BtShared mutexes and the mutex
+** associated with the database handle itself must be held.
+**
+** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
+** the sqlite3.pDisconnect list. In this case either the BtShared mutex
+** associated with the database the virtual table is stored in is held
+** or, if the virtual table is stored in a non-sharable database, then
+** the database handle mutex is held.
+**
+** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
+** by multiple threads. It is thread-safe.
+*/
+SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
+ VTable *p = db->pDisconnect;
+
+ assert( sqlite3BtreeHoldsAllMutexes(db) );
+ assert( sqlite3_mutex_held(db->mutex) );
+
+ if( p ){
+ db->pDisconnect = 0;
+ sqlite3ExpirePreparedStatements(db, 0);
+ do {
+ VTable *pNext = p->pNext;
+ sqlite3VtabUnlock(p);
+ p = pNext;
+ }while( p );
+ }
+}
+
+/*
+** Clear any and all virtual-table information from the Table record.
+** This routine is called, for example, just before deleting the Table
+** record.
+**
+** Since it is a virtual-table, the Table structure contains a pointer
+** to the head of a linked list of VTable structures. Each VTable
+** structure is associated with a single sqlite3* user of the schema.
+** The reference count of the VTable structure associated with database
+** connection db is decremented immediately (which may lead to the
+** structure being xDisconnected and free). Any other VTable structures
+** in the list are moved to the sqlite3.pDisconnect list of the associated
+** database connection.
+*/
+SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
+ if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
+ if( p->azModuleArg ){
+ int i;
+ for(i=0; i<p->nModuleArg; i++){
+ if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
+ }
+ sqlite3DbFree(db, p->azModuleArg);
+ }
+}
+
+/*
+** Add a new module argument to pTable->azModuleArg[].
+** The string is not copied - the pointer is stored. The
+** string will be freed automatically when the table is
+** deleted.
+*/
+static void addModuleArgument(Parse *pParse, Table *pTable, char *zArg){
+ sqlite3_int64 nBytes = sizeof(char *)*(2+pTable->nModuleArg);
+ char **azModuleArg;
+ sqlite3 *db = pParse->db;
+ if( pTable->nModuleArg+3>=db->aLimit[SQLITE_LIMIT_COLUMN] ){
+ sqlite3ErrorMsg(pParse, "too many columns on %s", pTable->zName);
+ }
+ azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
+ if( azModuleArg==0 ){
+ sqlite3DbFree(db, zArg);
+ }else{
+ int i = pTable->nModuleArg++;
+ azModuleArg[i] = zArg;
+ azModuleArg[i+1] = 0;
+ pTable->azModuleArg = azModuleArg;
+ }
+}
+
+/*
+** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
+** statement. The module name has been parsed, but the optional list
+** of parameters that follow the module name are still pending.
+*/
+SQLITE_PRIVATE void sqlite3VtabBeginParse(
+ Parse *pParse, /* Parsing context */
+ Token *pName1, /* Name of new table, or database name */
+ Token *pName2, /* Name of new table or NULL */
+ Token *pModuleName, /* Name of the module for the virtual table */
+ int ifNotExists /* No error if the table already exists */
+){
+ Table *pTable; /* The new virtual table */
+ sqlite3 *db; /* Database connection */
+
+ sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
+ pTable = pParse->pNewTable;
+ if( pTable==0 ) return;
+ assert( 0==pTable->pIndex );
+
+ db = pParse->db;
+
+ assert( pTable->nModuleArg==0 );
+ addModuleArgument(pParse, pTable, sqlite3NameFromToken(db, pModuleName));
+ addModuleArgument(pParse, pTable, 0);
+ addModuleArgument(pParse, pTable, sqlite3DbStrDup(db, pTable->zName));
+ assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
+ || (pParse->sNameToken.z==pName1->z && pName2->z==0)
+ );
+ pParse->sNameToken.n = (int)(
+ &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
+ );
+
+#ifndef SQLITE_OMIT_AUTHORIZATION
+ /* Creating a virtual table invokes the authorization callback twice.
+ ** The first invocation, to obtain permission to INSERT a row into the
+ ** sqlite_schema table, has already been made by sqlite3StartTable().
+ ** The second call, to obtain permission to create the table, is made now.
+ */
+ if( pTable->azModuleArg ){
+ int iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
+ assert( iDb>=0 ); /* The database the table is being created in */
+ sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
+ pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
+ }
+#endif
+}
+
+/*
+** This routine takes the module argument that has been accumulating
+** in pParse->zArg[] and appends it to the list of arguments on the
+** virtual table currently under construction in pParse->pTable.
+*/
+static void addArgumentToVtab(Parse *pParse){
+ if( pParse->sArg.z && pParse->pNewTable ){
+ const char *z = (const char*)pParse->sArg.z;
+ int n = pParse->sArg.n;
+ sqlite3 *db = pParse->db;
+ addModuleArgument(pParse, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
+ }
+}
+
+/*
+** The parser calls this routine after the CREATE VIRTUAL TABLE statement
+** has been completely parsed.
+*/
+SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
+ Table *pTab = pParse->pNewTable; /* The table being constructed */
+ sqlite3 *db = pParse->db; /* The database connection */
+
+ if( pTab==0 ) return;
+ addArgumentToVtab(pParse);
+ pParse->sArg.z = 0;
+ if( pTab->nModuleArg<1 ) return;
+
+ /* If the CREATE VIRTUAL TABLE statement is being entered for the
+ ** first time (in other words if the virtual table is actually being
+ ** created now instead of just being read out of sqlite_schema) then
+ ** do additional initialization work and store the statement text
+ ** in the sqlite_schema table.
+ */
+ if( !db->init.busy ){
+ char *zStmt;
+ char *zWhere;
+ int iDb;
+ int iReg;
+ Vdbe *v;
+
+ sqlite3MayAbort(pParse);
+
+ /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
+ if( pEnd ){
+ pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
+ }
+ zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
+
+ /* A slot for the record has already been allocated in the
+ ** schema table. We just need to update that slot with all
+ ** the information we've collected.
+ **
+ ** The VM register number pParse->regRowid holds the rowid of an
+ ** entry in the sqlite_schema table tht was created for this vtab
+ ** by sqlite3StartTable().
+ */
+ iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ sqlite3NestedParse(pParse,
+ "UPDATE %Q." DFLT_SCHEMA_TABLE " "
+ "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
+ "WHERE rowid=#%d",
+ db->aDb[iDb].zDbSName,
+ pTab->zName,
+ pTab->zName,
+ zStmt,
+ pParse->regRowid
+ );
+ v = sqlite3GetVdbe(pParse);
+ sqlite3ChangeCookie(pParse, iDb);
+
+ sqlite3VdbeAddOp0(v, OP_Expire);
+ zWhere = sqlite3MPrintf(db, "name=%Q AND sql=%Q", pTab->zName, zStmt);
+ sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
+ sqlite3DbFree(db, zStmt);
+
+ iReg = ++pParse->nMem;
+ sqlite3VdbeLoadString(v, iReg, pTab->zName);
+ sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
+ }
+
+ /* If we are rereading the sqlite_schema table create the in-memory
+ ** record of the table. The xConnect() method is not called until
+ ** the first time the virtual table is used in an SQL statement. This
+ ** allows a schema that contains virtual tables to be loaded before
+ ** the required virtual table implementations are registered. */
+ else {
+ Table *pOld;
+ Schema *pSchema = pTab->pSchema;
+ const char *zName = pTab->zName;
+ assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
+ pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
+ if( pOld ){
+ sqlite3OomFault(db);
+ assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
+ return;
+ }
+ pParse->pNewTable = 0;
+ }
+}
+
+/*
+** The parser calls this routine when it sees the first token
+** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
+*/
+SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
+ addArgumentToVtab(pParse);
+ pParse->sArg.z = 0;
+ pParse->sArg.n = 0;
+}
+
+/*
+** The parser calls this routine for each token after the first token
+** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
+*/
+SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
+ Token *pArg = &pParse->sArg;
+ if( pArg->z==0 ){
+ pArg->z = p->z;
+ pArg->n = p->n;
+ }else{
+ assert(pArg->z <= p->z);
+ pArg->n = (int)(&p->z[p->n] - pArg->z);
+ }
+}
+
+/*
+** Invoke a virtual table constructor (either xCreate or xConnect). The
+** pointer to the function to invoke is passed as the fourth parameter
+** to this procedure.
+*/
+static int vtabCallConstructor(
+ sqlite3 *db,
+ Table *pTab,
+ Module *pMod,
+ int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
+ char **pzErr
+){
+ VtabCtx sCtx;
+ VTable *pVTable;
+ int rc;
+ const char *const*azArg = (const char *const*)pTab->azModuleArg;
+ int nArg = pTab->nModuleArg;
+ char *zErr = 0;
+ char *zModuleName;
+ int iDb;
+ VtabCtx *pCtx;
+
+ /* Check that the virtual-table is not already being initialized */
+ for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
+ if( pCtx->pTab==pTab ){
+ *pzErr = sqlite3MPrintf(db,
+ "vtable constructor called recursively: %s", pTab->zName
+ );
+ return SQLITE_LOCKED;
+ }
+ }
+
+ zModuleName = sqlite3DbStrDup(db, pTab->zName);
+ if( !zModuleName ){
+ return SQLITE_NOMEM_BKPT;
+ }
+
+ pVTable = sqlite3MallocZero(sizeof(VTable));
+ if( !pVTable ){
+ sqlite3OomFault(db);
+ sqlite3DbFree(db, zModuleName);
+ return SQLITE_NOMEM_BKPT;
+ }
+ pVTable->db = db;
+ pVTable->pMod = pMod;
+ pVTable->eVtabRisk = SQLITE_VTABRISK_Normal;
+
+ iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
+
+ /* Invoke the virtual table constructor */
+ assert( &db->pVtabCtx );
+ assert( xConstruct );
+ sCtx.pTab = pTab;
+ sCtx.pVTable = pVTable;
+ sCtx.pPrior = db->pVtabCtx;
+ sCtx.bDeclared = 0;
+ db->pVtabCtx = &sCtx;
+ rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
+ db->pVtabCtx = sCtx.pPrior;
+ if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
+ assert( sCtx.pTab==pTab );
+
+ if( SQLITE_OK!=rc ){
+ if( zErr==0 ){
+ *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
+ }else {
+ *pzErr = sqlite3MPrintf(db, "%s", zErr);
+ sqlite3_free(zErr);
+ }
+ sqlite3DbFree(db, pVTable);
+ }else if( ALWAYS(pVTable->pVtab) ){
+ /* Justification of ALWAYS(): A correct vtab constructor must allocate
+ ** the sqlite3_vtab object if successful. */
+ memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
+ pVTable->pVtab->pModule = pMod->pModule;
+ pMod->nRefModule++;
+ pVTable->nRef = 1;
+ if( sCtx.bDeclared==0 ){
+ const char *zFormat = "vtable constructor did not declare schema: %s";
+ *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
+ sqlite3VtabUnlock(pVTable);
+ rc = SQLITE_ERROR;
+ }else{
+ int iCol;
+ u16 oooHidden = 0;
+ /* If everything went according to plan, link the new VTable structure
+ ** into the linked list headed by pTab->pVTable. Then loop through the
+ ** columns of the table to see if any of them contain the token "hidden".
+ ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
+ ** the type string. */
+ pVTable->pNext = pTab->pVTable;
+ pTab->pVTable = pVTable;
+
+ for(iCol=0; iCol<pTab->nCol; iCol++){
+ char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
+ int nType;
+ int i = 0;
+ nType = sqlite3Strlen30(zType);
+ for(i=0; i<nType; i++){
+ if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
+ && (i==0 || zType[i-1]==' ')
+ && (zType[i+6]=='\0' || zType[i+6]==' ')
+ ){
+ break;
+ }
+ }
+ if( i<nType ){
+ int j;
+ int nDel = 6 + (zType[i+6] ? 1 : 0);
+ for(j=i; (j+nDel)<=nType; j++){
+ zType[j] = zType[j+nDel];
+ }
+ if( zType[i]=='\0' && i>0 ){
+ assert(zType[i-1]==' ');
+ zType[i-1] = '\0';
+ }
+ pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
+ oooHidden = TF_OOOHidden;
+ }else{
+ pTab->tabFlags |= oooHidden;
+ }
+ }
+ }
+ }
+
+ sqlite3DbFree(db, zModuleName);
+ return rc;
+}
+
+/*
+** This function is invoked by the parser to call the xConnect() method
+** of the virtual table pTab. If an error occurs, an error code is returned
+** and an error left in pParse.
+**
+** This call is a no-op if table pTab is not a virtual table.
+*/
+SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
+ sqlite3 *db = pParse->db;
+ const char *zMod;
+ Module *pMod;
+ int rc;
+
+ assert( pTab );
+ if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
+ return SQLITE_OK;
+ }
+
+ /* Locate the required virtual table module */
+ zMod = pTab->azModuleArg[0];
+ pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
+
+ if( !pMod ){
+ const char *zModule = pTab->azModuleArg[0];
+ sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
+ rc = SQLITE_ERROR;
+ }else{
+ char *zErr = 0;
+ rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
+ if( rc!=SQLITE_OK ){
+ sqlite3ErrorMsg(pParse, "%s", zErr);
+ pParse->rc = rc;
+ }
+ sqlite3DbFree(db, zErr);
+ }
+
+ return rc;
+}
+/*
+** Grow the db->aVTrans[] array so that there is room for at least one
+** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
+*/
+static int growVTrans(sqlite3 *db){
+ const int ARRAY_INCR = 5;
+
+ /* Grow the sqlite3.aVTrans array if required */
+ if( (db->nVTrans%ARRAY_INCR)==0 ){
+ VTable **aVTrans;
+ sqlite3_int64 nBytes = sizeof(sqlite3_vtab*)*
+ ((sqlite3_int64)db->nVTrans + ARRAY_INCR);
+ aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
+ if( !aVTrans ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
+ db->aVTrans = aVTrans;
+ }
+
+ return SQLITE_OK;
+}
+
+/*
+** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
+** have already been reserved using growVTrans().
+*/
+static void addToVTrans(sqlite3 *db, VTable *pVTab){
+ /* Add pVtab to the end of sqlite3.aVTrans */
+ db->aVTrans[db->nVTrans++] = pVTab;
+ sqlite3VtabLock(pVTab);
+}
+
+/*
+** This function is invoked by the vdbe to call the xCreate method
+** of the virtual table named zTab in database iDb.
+**
+** If an error occurs, *pzErr is set to point to an English language
+** description of the error and an SQLITE_XXX error code is returned.
+** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
+*/
+SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
+ int rc = SQLITE_OK;
+ Table *pTab;
+ Module *pMod;
+ const char *zMod;
+
+ pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
+ assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
+
+ /* Locate the required virtual table module */
+ zMod = pTab->azModuleArg[0];
+ pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
+
+ /* If the module has been registered and includes a Create method,
+ ** invoke it now. If the module has not been registered, return an
+ ** error. Otherwise, do nothing.
+ */
+ if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
+ *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
+ rc = SQLITE_ERROR;
+ }else{
+ rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
+ }
+
+ /* Justification of ALWAYS(): The xConstructor method is required to
+ ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
+ if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
+ rc = growVTrans(db);
+ if( rc==SQLITE_OK ){
+ addToVTrans(db, sqlite3GetVTable(db, pTab));
+ }
+ }
+
+ return rc;
+}
+
+/*
+** This function is used to set the schema of a virtual table. It is only
+** valid to call this function from within the xCreate() or xConnect() of a
+** virtual table module.
+*/
+SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
+ VtabCtx *pCtx;
+ int rc = SQLITE_OK;
+ Table *pTab;
+ char *zErr = 0;
+ Parse sParse;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
+ return SQLITE_MISUSE_BKPT;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ pCtx = db->pVtabCtx;
+ if( !pCtx || pCtx->bDeclared ){
+ sqlite3Error(db, SQLITE_MISUSE);
+ sqlite3_mutex_leave(db->mutex);
+ return SQLITE_MISUSE_BKPT;
+ }
+ pTab = pCtx->pTab;
+ assert( IsVirtual(pTab) );
+
+ memset(&sParse, 0, sizeof(sParse));
+ sParse.eParseMode = PARSE_MODE_DECLARE_VTAB;
+ sParse.db = db;
+ sParse.nQueryLoop = 1;
+ if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr)
+ && sParse.pNewTable
+ && !db->mallocFailed
+ && !sParse.pNewTable->pSelect
+ && !IsVirtual(sParse.pNewTable)
+ ){
+ if( !pTab->aCol ){
+ Table *pNew = sParse.pNewTable;
+ Index *pIdx;
+ pTab->aCol = pNew->aCol;
+ pTab->nCol = pNew->nCol;
+ pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
+ pNew->nCol = 0;
+ pNew->aCol = 0;
+ assert( pTab->pIndex==0 );
+ assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 );
+ if( !HasRowid(pNew)
+ && pCtx->pVTable->pMod->pModule->xUpdate!=0
+ && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
+ ){
+ /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
+ ** or else must have a single-column PRIMARY KEY */
+ rc = SQLITE_ERROR;
+ }
+ pIdx = pNew->pIndex;
+ if( pIdx ){
+ assert( pIdx->pNext==0 );
+ pTab->pIndex = pIdx;
+ pNew->pIndex = 0;
+ pIdx->pTable = pTab;
+ }
+ }
+ pCtx->bDeclared = 1;
+ }else{
+ sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
+ sqlite3DbFree(db, zErr);
+ rc = SQLITE_ERROR;
+ }
+ sParse.eParseMode = PARSE_MODE_NORMAL;
+
+ if( sParse.pVdbe ){
+ sqlite3VdbeFinalize(sParse.pVdbe);
+ }
+ sqlite3DeleteTable(db, sParse.pNewTable);
+ sqlite3ParserReset(&sParse);
+
+ assert( (rc&0xff)==rc );
+ rc = sqlite3ApiExit(db, rc);
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+/*
+** This function is invoked by the vdbe to call the xDestroy method
+** of the virtual table named zTab in database iDb. This occurs
+** when a DROP TABLE is mentioned.
+**
+** This call is a no-op if zTab is not a virtual table.
+*/
+SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
+ int rc = SQLITE_OK;
+ Table *pTab;
+
+ pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
+ if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
+ VTable *p;
+ int (*xDestroy)(sqlite3_vtab *);
+ for(p=pTab->pVTable; p; p=p->pNext){
+ assert( p->pVtab );
+ if( p->pVtab->nRef>0 ){
+ return SQLITE_LOCKED;
+ }
+ }
+ p = vtabDisconnectAll(db, pTab);
+ xDestroy = p->pMod->pModule->xDestroy;
+ if( xDestroy==0 ) xDestroy = p->pMod->pModule->xDisconnect;
+ assert( xDestroy!=0 );
+ pTab->nTabRef++;
+ rc = xDestroy(p->pVtab);
+ /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
+ if( rc==SQLITE_OK ){
+ assert( pTab->pVTable==p && p->pNext==0 );
+ p->pVtab = 0;
+ pTab->pVTable = 0;
+ sqlite3VtabUnlock(p);
+ }
+ sqlite3DeleteTable(db, pTab);
+ }
+
+ return rc;
+}
+
+/*
+** This function invokes either the xRollback or xCommit method
+** of each of the virtual tables in the sqlite3.aVTrans array. The method
+** called is identified by the second argument, "offset", which is
+** the offset of the method to call in the sqlite3_module structure.
+**
+** The array is cleared after invoking the callbacks.
+*/
+static void callFinaliser(sqlite3 *db, int offset){
+ int i;
+ if( db->aVTrans ){
+ VTable **aVTrans = db->aVTrans;
+ db->aVTrans = 0;
+ for(i=0; i<db->nVTrans; i++){
+ VTable *pVTab = aVTrans[i];
+ sqlite3_vtab *p = pVTab->pVtab;
+ if( p ){
+ int (*x)(sqlite3_vtab *);
+ x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
+ if( x ) x(p);
+ }
+ pVTab->iSavepoint = 0;
+ sqlite3VtabUnlock(pVTab);
+ }
+ sqlite3DbFree(db, aVTrans);
+ db->nVTrans = 0;
+ }
+}
+
+/*
+** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
+** array. Return the error code for the first error that occurs, or
+** SQLITE_OK if all xSync operations are successful.
+**
+** If an error message is available, leave it in p->zErrMsg.
+*/
+SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
+ int i;
+ int rc = SQLITE_OK;
+ VTable **aVTrans = db->aVTrans;
+
+ db->aVTrans = 0;
+ for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
+ int (*x)(sqlite3_vtab *);
+ sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
+ if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
+ rc = x(pVtab);
+ sqlite3VtabImportErrmsg(p, pVtab);
+ }
+ }
+ db->aVTrans = aVTrans;
+ return rc;
+}
+
+/*
+** Invoke the xRollback method of all virtual tables in the
+** sqlite3.aVTrans array. Then clear the array itself.
+*/
+SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
+ callFinaliser(db, offsetof(sqlite3_module,xRollback));
+ return SQLITE_OK;
+}
+
+/*
+** Invoke the xCommit method of all virtual tables in the
+** sqlite3.aVTrans array. Then clear the array itself.
+*/
+SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
+ callFinaliser(db, offsetof(sqlite3_module,xCommit));
+ return SQLITE_OK;
+}
+
+/*
+** If the virtual table pVtab supports the transaction interface
+** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
+** not currently open, invoke the xBegin method now.
+**
+** If the xBegin call is successful, place the sqlite3_vtab pointer
+** in the sqlite3.aVTrans array.
+*/
+SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
+ int rc = SQLITE_OK;
+ const sqlite3_module *pModule;
+
+ /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
+ ** than zero, then this function is being called from within a
+ ** virtual module xSync() callback. It is illegal to write to
+ ** virtual module tables in this case, so return SQLITE_LOCKED.
+ */
+ if( sqlite3VtabInSync(db) ){
+ return SQLITE_LOCKED;
+ }
+ if( !pVTab ){
+ return SQLITE_OK;
+ }
+ pModule = pVTab->pVtab->pModule;
+
+ if( pModule->xBegin ){
+ int i;
+
+ /* If pVtab is already in the aVTrans array, return early */
+ for(i=0; i<db->nVTrans; i++){
+ if( db->aVTrans[i]==pVTab ){
+ return SQLITE_OK;
+ }
+ }
+
+ /* Invoke the xBegin method. If successful, add the vtab to the
+ ** sqlite3.aVTrans[] array. */
+ rc = growVTrans(db);
+ if( rc==SQLITE_OK ){
+ rc = pModule->xBegin(pVTab->pVtab);
+ if( rc==SQLITE_OK ){
+ int iSvpt = db->nStatement + db->nSavepoint;
+ addToVTrans(db, pVTab);
+ if( iSvpt && pModule->xSavepoint ){
+ pVTab->iSavepoint = iSvpt;
+ rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
+ }
+ }
+ }
+ }
+ return rc;
+}
+
+/*
+** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
+** virtual tables that currently have an open transaction. Pass iSavepoint
+** as the second argument to the virtual table method invoked.
+**
+** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
+** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
+** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
+** an open transaction is invoked.
+**
+** If any virtual table method returns an error code other than SQLITE_OK,
+** processing is abandoned and the error returned to the caller of this
+** function immediately. If all calls to virtual table methods are successful,
+** SQLITE_OK is returned.
+*/
+SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
+ int rc = SQLITE_OK;
+
+ assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
+ assert( iSavepoint>=-1 );
+ if( db->aVTrans ){
+ int i;
+ for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
+ VTable *pVTab = db->aVTrans[i];
+ const sqlite3_module *pMod = pVTab->pMod->pModule;
+ if( pVTab->pVtab && pMod->iVersion>=2 ){
+ int (*xMethod)(sqlite3_vtab *, int);
+ sqlite3VtabLock(pVTab);
+ switch( op ){
+ case SAVEPOINT_BEGIN:
+ xMethod = pMod->xSavepoint;
+ pVTab->iSavepoint = iSavepoint+1;
+ break;
+ case SAVEPOINT_ROLLBACK:
+ xMethod = pMod->xRollbackTo;
+ break;
+ default:
+ xMethod = pMod->xRelease;
+ break;
+ }
+ if( xMethod && pVTab->iSavepoint>iSavepoint ){
+ rc = xMethod(pVTab->pVtab, iSavepoint);
+ }
+ sqlite3VtabUnlock(pVTab);
+ }
+ }
+ }
+ return rc;
+}
+
+/*
+** The first parameter (pDef) is a function implementation. The
+** second parameter (pExpr) is the first argument to this function.
+** If pExpr is a column in a virtual table, then let the virtual
+** table implementation have an opportunity to overload the function.
+**
+** This routine is used to allow virtual table implementations to
+** overload MATCH, LIKE, GLOB, and REGEXP operators.
+**
+** Return either the pDef argument (indicating no change) or a
+** new FuncDef structure that is marked as ephemeral using the
+** SQLITE_FUNC_EPHEM flag.
+*/
+SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
+ sqlite3 *db, /* Database connection for reporting malloc problems */
+ FuncDef *pDef, /* Function to possibly overload */
+ int nArg, /* Number of arguments to the function */
+ Expr *pExpr /* First argument to the function */
+){
+ Table *pTab;
+ sqlite3_vtab *pVtab;
+ sqlite3_module *pMod;
+ void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
+ void *pArg = 0;
+ FuncDef *pNew;
+ int rc = 0;
+
+ /* Check to see the left operand is a column in a virtual table */
+ if( NEVER(pExpr==0) ) return pDef;
+ if( pExpr->op!=TK_COLUMN ) return pDef;
+ pTab = pExpr->y.pTab;
+ if( pTab==0 ) return pDef;
+ if( !IsVirtual(pTab) ) return pDef;
+ pVtab = sqlite3GetVTable(db, pTab)->pVtab;
+ assert( pVtab!=0 );
+ assert( pVtab->pModule!=0 );
+ pMod = (sqlite3_module *)pVtab->pModule;
+ if( pMod->xFindFunction==0 ) return pDef;
+
+ /* Call the xFindFunction method on the virtual table implementation
+ ** to see if the implementation wants to overload this function.
+ **
+ ** Though undocumented, we have historically always invoked xFindFunction
+ ** with an all lower-case function name. Continue in this tradition to
+ ** avoid any chance of an incompatibility.
+ */
+#ifdef SQLITE_DEBUG
+ {
+ int i;
+ for(i=0; pDef->zName[i]; i++){
+ unsigned char x = (unsigned char)pDef->zName[i];
+ assert( x==sqlite3UpperToLower[x] );
+ }
+ }
+#endif
+ rc = pMod->xFindFunction(pVtab, nArg, pDef->zName, &xSFunc, &pArg);
+ if( rc==0 ){
+ return pDef;
+ }
+
+ /* Create a new ephemeral function definition for the overloaded
+ ** function */
+ pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
+ + sqlite3Strlen30(pDef->zName) + 1);
+ if( pNew==0 ){
+ return pDef;
+ }
+ *pNew = *pDef;
+ pNew->zName = (const char*)&pNew[1];
+ memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
+ pNew->xSFunc = xSFunc;
+ pNew->pUserData = pArg;
+ pNew->funcFlags |= SQLITE_FUNC_EPHEM;
+ return pNew;
+}
+
+/*
+** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
+** array so that an OP_VBegin will get generated for it. Add pTab to the
+** array if it is missing. If pTab is already in the array, this routine
+** is a no-op.
+*/
+SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
+ Parse *pToplevel = sqlite3ParseToplevel(pParse);
+ int i, n;
+ Table **apVtabLock;
+
+ assert( IsVirtual(pTab) );
+ for(i=0; i<pToplevel->nVtabLock; i++){
+ if( pTab==pToplevel->apVtabLock[i] ) return;
+ }
+ n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
+ apVtabLock = sqlite3Realloc(pToplevel->apVtabLock, n);
+ if( apVtabLock ){
+ pToplevel->apVtabLock = apVtabLock;
+ pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
+ }else{
+ sqlite3OomFault(pToplevel->db);
+ }
+}
+
+/*
+** Check to see if virtual table module pMod can be have an eponymous
+** virtual table instance. If it can, create one if one does not already
+** exist. Return non-zero if the eponymous virtual table instance exists
+** when this routine returns, and return zero if it does not exist.
+**
+** An eponymous virtual table instance is one that is named after its
+** module, and more importantly, does not require a CREATE VIRTUAL TABLE
+** statement in order to come into existance. Eponymous virtual table
+** instances always exist. They cannot be DROP-ed.
+**
+** Any virtual table module for which xConnect and xCreate are the same
+** method can have an eponymous virtual table instance.
+*/
+SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
+ const sqlite3_module *pModule = pMod->pModule;
+ Table *pTab;
+ char *zErr = 0;
+ int rc;
+ sqlite3 *db = pParse->db;
+ if( pMod->pEpoTab ) return 1;
+ if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
+ pTab = sqlite3DbMallocZero(db, sizeof(Table));
+ if( pTab==0 ) return 0;
+ pTab->zName = sqlite3DbStrDup(db, pMod->zName);
+ if( pTab->zName==0 ){
+ sqlite3DbFree(db, pTab);
+ return 0;
+ }
+ pMod->pEpoTab = pTab;
+ pTab->nTabRef = 1;
+ pTab->pSchema = db->aDb[0].pSchema;
+ assert( pTab->nModuleArg==0 );
+ pTab->iPKey = -1;
+ addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
+ addModuleArgument(pParse, pTab, 0);
+ addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
+ rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
+ if( rc ){
+ sqlite3ErrorMsg(pParse, "%s", zErr);
+ sqlite3DbFree(db, zErr);
+ sqlite3VtabEponymousTableClear(db, pMod);
+ return 0;
+ }
+ return 1;
+}
+
+/*
+** Erase the eponymous virtual table instance associated with
+** virtual table module pMod, if it exists.
+*/
+SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
+ Table *pTab = pMod->pEpoTab;
+ if( pTab!=0 ){
+ /* Mark the table as Ephemeral prior to deleting it, so that the
+ ** sqlite3DeleteTable() routine will know that it is not stored in
+ ** the schema. */
+ pTab->tabFlags |= TF_Ephemeral;
+ sqlite3DeleteTable(db, pTab);
+ pMod->pEpoTab = 0;
+ }
+}
+
+/*
+** Return the ON CONFLICT resolution mode in effect for the virtual
+** table update operation currently in progress.
+**
+** The results of this routine are undefined unless it is called from
+** within an xUpdate method.
+*/
+SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
+ static const unsigned char aMap[] = {
+ SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
+ };
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+#endif
+ assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
+ assert( OE_Ignore==4 && OE_Replace==5 );
+ assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
+ return (int)aMap[db->vtabOnConflict-1];
+}
+
+/*
+** Call from within the xCreate() or xConnect() methods to provide
+** the SQLite core with additional information about the behavior
+** of the virtual table being implemented.
+*/
+SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
+ va_list ap;
+ int rc = SQLITE_OK;
+ VtabCtx *p;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ p = db->pVtabCtx;
+ if( !p ){
+ rc = SQLITE_MISUSE_BKPT;
+ }else{
+ assert( p->pTab==0 || IsVirtual(p->pTab) );
+ va_start(ap, op);
+ switch( op ){
+ case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
+ p->pVTable->bConstraint = (u8)va_arg(ap, int);
+ break;
+ }
+ case SQLITE_VTAB_INNOCUOUS: {
+ p->pVTable->eVtabRisk = SQLITE_VTABRISK_Low;
+ break;
+ }
+ case SQLITE_VTAB_DIRECTONLY: {
+ p->pVTable->eVtabRisk = SQLITE_VTABRISK_High;
+ break;
+ }
+ default: {
+ rc = SQLITE_MISUSE_BKPT;
+ break;
+ }
+ }
+ va_end(ap);
+ }
+
+ if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+/************** End of vtab.c ************************************************/
+/************** Begin file wherecode.c ***************************************/
+/*
+** 2015-06-06
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This module contains C code that generates VDBE code used to process
+** the WHERE clause of SQL statements.
+**
+** This file was split off from where.c on 2015-06-06 in order to reduce the
+** size of where.c and make it easier to edit. This file contains the routines
+** that actually generate the bulk of the WHERE loop code. The original where.c
+** file retains the code that does query planning and analysis.
+*/
+/* #include "sqliteInt.h" */
+/************** Include whereInt.h in the middle of wherecode.c **************/
+/************** Begin file whereInt.h ****************************************/
+/*
+** 2013-11-12
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains structure and macro definitions for the query
+** planner logic in "where.c". These definitions are broken out into
+** a separate source file for easier editing.
+*/
+#ifndef SQLITE_WHEREINT_H
+#define SQLITE_WHEREINT_H
+
+/*
+** Trace output macros
+*/
+#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
+/***/ extern int sqlite3WhereTrace;
+#endif
+#if defined(SQLITE_DEBUG) \
+ && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
+# define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
+# define WHERETRACE_ENABLED 1
+#else
+# define WHERETRACE(K,X)
+#endif
+
+/* Forward references
+*/
+typedef struct WhereClause WhereClause;
+typedef struct WhereMaskSet WhereMaskSet;
+typedef struct WhereOrInfo WhereOrInfo;
+typedef struct WhereAndInfo WhereAndInfo;
+typedef struct WhereLevel WhereLevel;
+typedef struct WhereLoop WhereLoop;
+typedef struct WherePath WherePath;
+typedef struct WhereTerm WhereTerm;
+typedef struct WhereLoopBuilder WhereLoopBuilder;
+typedef struct WhereScan WhereScan;
+typedef struct WhereOrCost WhereOrCost;
+typedef struct WhereOrSet WhereOrSet;
+
+/*
+** This object contains information needed to implement a single nested
+** loop in WHERE clause.
+**
+** Contrast this object with WhereLoop. This object describes the
+** implementation of the loop. WhereLoop describes the algorithm.
+** This object contains a pointer to the WhereLoop algorithm as one of
+** its elements.
+**
+** The WhereInfo object contains a single instance of this object for
+** each term in the FROM clause (which is to say, for each of the
+** nested loops as implemented). The order of WhereLevel objects determines
+** the loop nested order, with WhereInfo.a[0] being the outer loop and
+** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
+*/
+struct WhereLevel {
+ int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
+ int iTabCur; /* The VDBE cursor used to access the table */
+ int iIdxCur; /* The VDBE cursor used to access pIdx */
+ int addrBrk; /* Jump here to break out of the loop */
+ int addrNxt; /* Jump here to start the next IN combination */
+ int addrSkip; /* Jump here for next iteration of skip-scan */
+ int addrCont; /* Jump here to continue with the next loop cycle */
+ int addrFirst; /* First instruction of interior of the loop */
+ int addrBody; /* Beginning of the body of this loop */
+ int regBignull; /* big-null flag reg. True if a NULL-scan is needed */
+ int addrBignull; /* Jump here for next part of big-null scan */
+#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
+ u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
+ int addrLikeRep; /* LIKE range processing address */
+#endif
+ u8 iFrom; /* Which entry in the FROM clause */
+ u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
+ int p1, p2; /* Operands of the opcode used to end the loop */
+ union { /* Information that depends on pWLoop->wsFlags */
+ struct {
+ int nIn; /* Number of entries in aInLoop[] */
+ struct InLoop {
+ int iCur; /* The VDBE cursor used by this IN operator */
+ int addrInTop; /* Top of the IN loop */
+ int iBase; /* Base register of multi-key index record */
+ int nPrefix; /* Number of prior entires in the key */
+ u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
+ } *aInLoop; /* Information about each nested IN operator */
+ } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
+ Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
+ } u;
+ struct WhereLoop *pWLoop; /* The selected WhereLoop object */
+ Bitmask notReady; /* FROM entries not usable at this level */
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+ int addrVisit; /* Address at which row is visited */
+#endif
+};
+
+/*
+** Each instance of this object represents an algorithm for evaluating one
+** term of a join. Every term of the FROM clause will have at least
+** one corresponding WhereLoop object (unless INDEXED BY constraints
+** prevent a query solution - which is an error) and many terms of the
+** FROM clause will have multiple WhereLoop objects, each describing a
+** potential way of implementing that FROM-clause term, together with
+** dependencies and cost estimates for using the chosen algorithm.
+**
+** Query planning consists of building up a collection of these WhereLoop
+** objects, then computing a particular sequence of WhereLoop objects, with
+** one WhereLoop object per FROM clause term, that satisfy all dependencies
+** and that minimize the overall cost.
+*/
+struct WhereLoop {
+ Bitmask prereq; /* Bitmask of other loops that must run first */
+ Bitmask maskSelf; /* Bitmask identifying table iTab */
+#ifdef SQLITE_DEBUG
+ char cId; /* Symbolic ID of this loop for debugging use */
+#endif
+ u8 iTab; /* Position in FROM clause of table for this loop */
+ u8 iSortIdx; /* Sorting index number. 0==None */
+ LogEst rSetup; /* One-time setup cost (ex: create transient index) */
+ LogEst rRun; /* Cost of running each loop */
+ LogEst nOut; /* Estimated number of output rows */
+ union {
+ struct { /* Information for internal btree tables */
+ u16 nEq; /* Number of equality constraints */
+ u16 nBtm; /* Size of BTM vector */
+ u16 nTop; /* Size of TOP vector */
+ u16 nDistinctCol; /* Index columns used to sort for DISTINCT */
+ Index *pIndex; /* Index used, or NULL */
+ } btree;
+ struct { /* Information for virtual tables */
+ int idxNum; /* Index number */
+ u8 needFree; /* True if sqlite3_free(idxStr) is needed */
+ i8 isOrdered; /* True if satisfies ORDER BY */
+ u16 omitMask; /* Terms that may be omitted */
+ char *idxStr; /* Index identifier string */
+ } vtab;
+ } u;
+ u32 wsFlags; /* WHERE_* flags describing the plan */
+ u16 nLTerm; /* Number of entries in aLTerm[] */
+ u16 nSkip; /* Number of NULL aLTerm[] entries */
+ /**** whereLoopXfer() copies fields above ***********************/
+# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
+ u16 nLSlot; /* Number of slots allocated for aLTerm[] */
+ WhereTerm **aLTerm; /* WhereTerms used */
+ WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
+ WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
+};
+
+/* This object holds the prerequisites and the cost of running a
+** subquery on one operand of an OR operator in the WHERE clause.
+** See WhereOrSet for additional information
+*/
+struct WhereOrCost {
+ Bitmask prereq; /* Prerequisites */
+ LogEst rRun; /* Cost of running this subquery */
+ LogEst nOut; /* Number of outputs for this subquery */
+};
+
+/* The WhereOrSet object holds a set of possible WhereOrCosts that
+** correspond to the subquery(s) of OR-clause processing. Only the
+** best N_OR_COST elements are retained.
+*/
+#define N_OR_COST 3
+struct WhereOrSet {
+ u16 n; /* Number of valid a[] entries */
+ WhereOrCost a[N_OR_COST]; /* Set of best costs */
+};
+
+/*
+** Each instance of this object holds a sequence of WhereLoop objects
+** that implement some or all of a query plan.
+**
+** Think of each WhereLoop object as a node in a graph with arcs
+** showing dependencies and costs for travelling between nodes. (That is
+** not a completely accurate description because WhereLoop costs are a
+** vector, not a scalar, and because dependencies are many-to-one, not
+** one-to-one as are graph nodes. But it is a useful visualization aid.)
+** Then a WherePath object is a path through the graph that visits some
+** or all of the WhereLoop objects once.
+**
+** The "solver" works by creating the N best WherePath objects of length
+** 1. Then using those as a basis to compute the N best WherePath objects
+** of length 2. And so forth until the length of WherePaths equals the
+** number of nodes in the FROM clause. The best (lowest cost) WherePath
+** at the end is the chosen query plan.
+*/
+struct WherePath {
+ Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
+ Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
+ LogEst nRow; /* Estimated number of rows generated by this path */
+ LogEst rCost; /* Total cost of this path */
+ LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
+ i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
+ WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
+};
+
+/*
+** The query generator uses an array of instances of this structure to
+** help it analyze the subexpressions of the WHERE clause. Each WHERE
+** clause subexpression is separated from the others by AND operators,
+** usually, or sometimes subexpressions separated by OR.
+**
+** All WhereTerms are collected into a single WhereClause structure.
+** The following identity holds:
+**
+** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
+**
+** When a term is of the form:
+**
+** X <op> <expr>
+**
+** where X is a column name and <op> is one of certain operators,
+** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
+** cursor number and column number for X. WhereTerm.eOperator records
+** the <op> using a bitmask encoding defined by WO_xxx below. The
+** use of a bitmask encoding for the operator allows us to search
+** quickly for terms that match any of several different operators.
+**
+** A WhereTerm might also be two or more subterms connected by OR:
+**
+** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
+**
+** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
+** and the WhereTerm.u.pOrInfo field points to auxiliary information that
+** is collected about the OR clause.
+**
+** If a term in the WHERE clause does not match either of the two previous
+** categories, then eOperator==0. The WhereTerm.pExpr field is still set
+** to the original subexpression content and wtFlags is set up appropriately
+** but no other fields in the WhereTerm object are meaningful.
+**
+** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
+** but they do so indirectly. A single WhereMaskSet structure translates
+** cursor number into bits and the translated bit is stored in the prereq
+** fields. The translation is used in order to maximize the number of
+** bits that will fit in a Bitmask. The VDBE cursor numbers might be
+** spread out over the non-negative integers. For example, the cursor
+** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
+** translates these sparse cursor numbers into consecutive integers
+** beginning with 0 in order to make the best possible use of the available
+** bits in the Bitmask. So, in the example above, the cursor numbers
+** would be mapped into integers 0 through 7.
+**
+** The number of terms in a join is limited by the number of bits
+** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
+** is only able to process joins with 64 or fewer tables.
+*/
+struct WhereTerm {
+ Expr *pExpr; /* Pointer to the subexpression that is this term */
+ WhereClause *pWC; /* The clause this term is part of */
+ LogEst truthProb; /* Probability of truth for this expression */
+ u16 wtFlags; /* TERM_xxx bit flags. See below */
+ u16 eOperator; /* A WO_xx value describing <op> */
+ u8 nChild; /* Number of children that must disable us */
+ u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
+ int iParent; /* Disable pWC->a[iParent] when this term disabled */
+ int leftCursor; /* Cursor number of X in "X <op> <expr>" */
+ union {
+ struct {
+ int leftColumn; /* Column number of X in "X <op> <expr>" */
+ int iField; /* Field in (?,?,?) IN (SELECT...) vector */
+ } x; /* Opcode other than OP_OR or OP_AND */
+ WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
+ WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
+ } u;
+ Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
+ Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
+};
+
+/*
+** Allowed values of WhereTerm.wtFlags
+*/
+#define TERM_DYNAMIC 0x0001 /* Need to call sqlite3ExprDelete(db, pExpr) */
+#define TERM_VIRTUAL 0x0002 /* Added by the optimizer. Do not code */
+#define TERM_CODED 0x0004 /* This term is already coded */
+#define TERM_COPIED 0x0008 /* Has a child */
+#define TERM_ORINFO 0x0010 /* Need to free the WhereTerm.u.pOrInfo object */
+#define TERM_ANDINFO 0x0020 /* Need to free the WhereTerm.u.pAndInfo obj */
+#define TERM_OR_OK 0x0040 /* Used during OR-clause processing */
+#ifdef SQLITE_ENABLE_STAT4
+# define TERM_VNULL 0x0080 /* Manufactured x>NULL or x<=NULL term */
+#else
+# define TERM_VNULL 0x0000 /* Disabled if not using stat4 */
+#endif
+#define TERM_LIKEOPT 0x0100 /* Virtual terms from the LIKE optimization */
+#define TERM_LIKECOND 0x0200 /* Conditionally this LIKE operator term */
+#define TERM_LIKE 0x0400 /* The original LIKE operator */
+#define TERM_IS 0x0800 /* Term.pExpr is an IS operator */
+#define TERM_VARSELECT 0x1000 /* Term.pExpr contains a correlated sub-query */
+#define TERM_HEURTRUTH 0x2000 /* Heuristic truthProb used */
+#ifdef SQLITE_ENABLE_STAT4
+# define TERM_HIGHTRUTH 0x4000 /* Term excludes few rows */
+#else
+# define TERM_HIGHTRUTH 0 /* Only used with STAT4 */
+#endif
+
+/*
+** An instance of the WhereScan object is used as an iterator for locating
+** terms in the WHERE clause that are useful to the query planner.
+*/
+struct WhereScan {
+ WhereClause *pOrigWC; /* Original, innermost WhereClause */
+ WhereClause *pWC; /* WhereClause currently being scanned */
+ const char *zCollName; /* Required collating sequence, if not NULL */
+ Expr *pIdxExpr; /* Search for this index expression */
+ char idxaff; /* Must match this affinity, if zCollName!=NULL */
+ unsigned char nEquiv; /* Number of entries in aEquiv[] */
+ unsigned char iEquiv; /* Next unused slot in aEquiv[] */
+ u32 opMask; /* Acceptable operators */
+ int k; /* Resume scanning at this->pWC->a[this->k] */
+ int aiCur[11]; /* Cursors in the equivalence class */
+ i16 aiColumn[11]; /* Corresponding column number in the eq-class */
+};
+
+/*
+** An instance of the following structure holds all information about a
+** WHERE clause. Mostly this is a container for one or more WhereTerms.
+**
+** Explanation of pOuter: For a WHERE clause of the form
+**
+** a AND ((b AND c) OR (d AND e)) AND f
+**
+** There are separate WhereClause objects for the whole clause and for
+** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
+** subclauses points to the WhereClause object for the whole clause.
+*/
+struct WhereClause {
+ WhereInfo *pWInfo; /* WHERE clause processing context */
+ WhereClause *pOuter; /* Outer conjunction */
+ u8 op; /* Split operator. TK_AND or TK_OR */
+ u8 hasOr; /* True if any a[].eOperator is WO_OR */
+ int nTerm; /* Number of terms */
+ int nSlot; /* Number of entries in a[] */
+ WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
+#if defined(SQLITE_SMALL_STACK)
+ WhereTerm aStatic[1]; /* Initial static space for a[] */
+#else
+ WhereTerm aStatic[8]; /* Initial static space for a[] */
+#endif
+};
+
+/*
+** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
+** a dynamically allocated instance of the following structure.
+*/
+struct WhereOrInfo {
+ WhereClause wc; /* Decomposition into subterms */
+ Bitmask indexable; /* Bitmask of all indexable tables in the clause */
+};
+
+/*
+** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
+** a dynamically allocated instance of the following structure.
+*/
+struct WhereAndInfo {
+ WhereClause wc; /* The subexpression broken out */
+};
+
+/*
+** An instance of the following structure keeps track of a mapping
+** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
+**
+** The VDBE cursor numbers are small integers contained in
+** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
+** clause, the cursor numbers might not begin with 0 and they might
+** contain gaps in the numbering sequence. But we want to make maximum
+** use of the bits in our bitmasks. This structure provides a mapping
+** from the sparse cursor numbers into consecutive integers beginning
+** with 0.
+**
+** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
+** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
+**
+** For example, if the WHERE clause expression used these VDBE
+** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
+** would map those cursor numbers into bits 0 through 5.
+**
+** Note that the mapping is not necessarily ordered. In the example
+** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
+** 57->5, 73->4. Or one of 719 other combinations might be used. It
+** does not really matter. What is important is that sparse cursor
+** numbers all get mapped into bit numbers that begin with 0 and contain
+** no gaps.
+*/
+struct WhereMaskSet {
+ int bVarSelect; /* Used by sqlite3WhereExprUsage() */
+ int n; /* Number of assigned cursor values */
+ int ix[BMS]; /* Cursor assigned to each bit */
+};
+
+/*
+** Initialize a WhereMaskSet object
+*/
+#define initMaskSet(P) (P)->n=0
+
+/*
+** This object is a convenience wrapper holding all information needed
+** to construct WhereLoop objects for a particular query.
+*/
+struct WhereLoopBuilder {
+ WhereInfo *pWInfo; /* Information about this WHERE */
+ WhereClause *pWC; /* WHERE clause terms */
+ ExprList *pOrderBy; /* ORDER BY clause */
+ WhereLoop *pNew; /* Template WhereLoop */
+ WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
+#ifdef SQLITE_ENABLE_STAT4
+ UnpackedRecord *pRec; /* Probe for stat4 (if required) */
+ int nRecValid; /* Number of valid fields currently in pRec */
+#endif
+ unsigned char bldFlags1; /* First set of SQLITE_BLDF_* flags */
+ unsigned char bldFlags2; /* Second set of SQLITE_BLDF_* flags */
+ unsigned int iPlanLimit; /* Search limiter */
+};
+
+/* Allowed values for WhereLoopBuider.bldFlags */
+#define SQLITE_BLDF1_INDEXED 0x0001 /* An index is used */
+#define SQLITE_BLDF1_UNIQUE 0x0002 /* All keys of a UNIQUE index used */
+
+#define SQLITE_BLDF2_2NDPASS 0x0004 /* Second builder pass needed */
+
+/* The WhereLoopBuilder.iPlanLimit is used to limit the number of
+** index+constraint combinations the query planner will consider for a
+** particular query. If this parameter is unlimited, then certain
+** pathological queries can spend excess time in the sqlite3WhereBegin()
+** routine. The limit is high enough that is should not impact real-world
+** queries.
+**
+** SQLITE_QUERY_PLANNER_LIMIT is the baseline limit. The limit is
+** increased by SQLITE_QUERY_PLANNER_LIMIT_INCR before each term of the FROM
+** clause is processed, so that every table in a join is guaranteed to be
+** able to propose a some index+constraint combinations even if the initial
+** baseline limit was exhausted by prior tables of the join.
+*/
+#ifndef SQLITE_QUERY_PLANNER_LIMIT
+# define SQLITE_QUERY_PLANNER_LIMIT 20000
+#endif
+#ifndef SQLITE_QUERY_PLANNER_LIMIT_INCR
+# define SQLITE_QUERY_PLANNER_LIMIT_INCR 1000
+#endif
+
+/*
+** Each instance of this object records a change to a single node
+** in an expression tree to cause that node to point to a column
+** of an index rather than an expression or a virtual column. All
+** such transformations need to be undone at the end of WHERE clause
+** processing.
+*/
+typedef struct WhereExprMod WhereExprMod;
+struct WhereExprMod {
+ WhereExprMod *pNext; /* Next translation on a list of them all */
+ Expr *pExpr; /* The Expr node that was transformed */
+ Expr orig; /* Original value of the Expr node */
+};
+
+/*
+** The WHERE clause processing routine has two halves. The
+** first part does the start of the WHERE loop and the second
+** half does the tail of the WHERE loop. An instance of
+** this structure is returned by the first half and passed
+** into the second half to give some continuity.
+**
+** An instance of this object holds the complete state of the query
+** planner.
+*/
+struct WhereInfo {
+ Parse *pParse; /* Parsing and code generating context */
+ SrcList *pTabList; /* List of tables in the join */
+ ExprList *pOrderBy; /* The ORDER BY clause or NULL */
+ ExprList *pResultSet; /* Result set of the query */
+ Expr *pWhere; /* The complete WHERE clause */
+ int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
+ int iContinue; /* Jump here to continue with next record */
+ int iBreak; /* Jump here to break out of the loop */
+ int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
+ u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
+ LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
+ u8 nLevel; /* Number of nested loop */
+ i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
+ u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
+ u8 eDistinct; /* One of the WHERE_DISTINCT_* values */
+ unsigned bDeferredSeek :1; /* Uses OP_DeferredSeek */
+ unsigned untestedTerms :1; /* Not all WHERE terms resolved by outer loop */
+ unsigned bOrderedInnerLoop:1;/* True if only the inner-most loop is ordered */
+ unsigned sorted :1; /* True if really sorted (not just grouped) */
+ LogEst nRowOut; /* Estimated number of output rows */
+ int iTop; /* The very beginning of the WHERE loop */
+ int iEndWhere; /* End of the WHERE clause itself */
+ WhereLoop *pLoops; /* List of all WhereLoop objects */
+ WhereExprMod *pExprMods; /* Expression modifications */
+ Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
+ WhereClause sWC; /* Decomposition of the WHERE clause */
+ WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
+ WhereLevel a[1]; /* Information about each nest loop in WHERE */
+};
+
+/*
+** Private interfaces - callable only by other where.c routines.
+**
+** where.c:
+*/
+SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
+#ifdef WHERETRACE_ENABLED
+SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
+SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm);
+SQLITE_PRIVATE void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC);
+#endif
+SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
+ WhereClause *pWC, /* The WHERE clause to be searched */
+ int iCur, /* Cursor number of LHS */
+ int iColumn, /* Column number of LHS */
+ Bitmask notReady, /* RHS must not overlap with this mask */
+ u32 op, /* Mask of WO_xx values describing operator */
+ Index *pIdx /* Must be compatible with this index, if not NULL */
+);
+
+/* wherecode.c: */
+#ifndef SQLITE_OMIT_EXPLAIN
+SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
+ Parse *pParse, /* Parse context */
+ SrcList *pTabList, /* Table list this loop refers to */
+ WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
+ u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
+);
+#else
+# define sqlite3WhereExplainOneScan(u,v,w,x) 0
+#endif /* SQLITE_OMIT_EXPLAIN */
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
+ Vdbe *v, /* Vdbe to add scanstatus entry to */
+ SrcList *pSrclist, /* FROM clause pLvl reads data from */
+ WhereLevel *pLvl, /* Level to add scanstatus() entry for */
+ int addrExplain /* Address of OP_Explain (or 0) */
+);
+#else
+# define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
+#endif
+SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
+ Parse *pParse, /* Parsing context */
+ Vdbe *v, /* Prepared statement under construction */
+ WhereInfo *pWInfo, /* Complete information about the WHERE clause */
+ int iLevel, /* Which level of pWInfo->a[] should be coded */
+ WhereLevel *pLevel, /* The current level pointer */
+ Bitmask notReady /* Which tables are currently available */
+);
+
+/* whereexpr.c: */
+SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
+SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
+SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
+SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
+SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*);
+SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
+SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
+SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
+
+
+
+
+
+/*
+** Bitmasks for the operators on WhereTerm objects. These are all
+** operators that are of interest to the query planner. An
+** OR-ed combination of these values can be used when searching for
+** particular WhereTerms within a WhereClause.
+**
+** Value constraints:
+** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
+** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
+** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
+** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
+** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
+*/
+#define WO_IN 0x0001
+#define WO_EQ 0x0002
+#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
+#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
+#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
+#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
+#define WO_AUX 0x0040 /* Op useful to virtual tables only */
+#define WO_IS 0x0080
+#define WO_ISNULL 0x0100
+#define WO_OR 0x0200 /* Two or more OR-connected terms */
+#define WO_AND 0x0400 /* Two or more AND-connected terms */
+#define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
+#define WO_NOOP 0x1000 /* This term does not restrict search space */
+
+#define WO_ALL 0x1fff /* Mask of all possible WO_* values */
+#define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
+
+/*
+** These are definitions of bits in the WhereLoop.wsFlags field.
+** The particular combination of bits in each WhereLoop help to
+** determine the algorithm that WhereLoop represents.
+*/
+#define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
+#define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
+#define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
+#define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
+#define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
+#define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
+#define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
+#define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
+#define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
+#define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
+#define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
+#define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
+#define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
+#define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
+#define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
+#define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
+#define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
+#define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
+#define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
+#define WHERE_IN_EARLYOUT 0x00040000 /* Perhaps quit IN loops early */
+#define WHERE_BIGNULL_SORT 0x00080000 /* Column nEq of index is BIGNULL */
+#define WHERE_IN_SEEKSCAN 0x00100000 /* Seek-scan optimization for IN */
+
+#endif /* !defined(SQLITE_WHEREINT_H) */
+
+/************** End of whereInt.h ********************************************/
+/************** Continuing where we left off in wherecode.c ******************/
+
+#ifndef SQLITE_OMIT_EXPLAIN
+
+/*
+** Return the name of the i-th column of the pIdx index.
+*/
+static const char *explainIndexColumnName(Index *pIdx, int i){
+ i = pIdx->aiColumn[i];
+ if( i==XN_EXPR ) return "<expr>";
+ if( i==XN_ROWID ) return "rowid";
+ return pIdx->pTable->aCol[i].zName;
+}
+
+/*
+** This routine is a helper for explainIndexRange() below
+**
+** pStr holds the text of an expression that we are building up one term
+** at a time. This routine adds a new term to the end of the expression.
+** Terms are separated by AND so add the "AND" text for second and subsequent
+** terms only.
+*/
+static void explainAppendTerm(
+ StrAccum *pStr, /* The text expression being built */
+ Index *pIdx, /* Index to read column names from */
+ int nTerm, /* Number of terms */
+ int iTerm, /* Zero-based index of first term. */
+ int bAnd, /* Non-zero to append " AND " */
+ const char *zOp /* Name of the operator */
+){
+ int i;
+
+ assert( nTerm>=1 );
+ if( bAnd ) sqlite3_str_append(pStr, " AND ", 5);
+
+ if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
+ for(i=0; i<nTerm; i++){
+ if( i ) sqlite3_str_append(pStr, ",", 1);
+ sqlite3_str_appendall(pStr, explainIndexColumnName(pIdx, iTerm+i));
+ }
+ if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
+
+ sqlite3_str_append(pStr, zOp, 1);
+
+ if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
+ for(i=0; i<nTerm; i++){
+ if( i ) sqlite3_str_append(pStr, ",", 1);
+ sqlite3_str_append(pStr, "?", 1);
+ }
+ if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
+}
+
+/*
+** Argument pLevel describes a strategy for scanning table pTab. This
+** function appends text to pStr that describes the subset of table
+** rows scanned by the strategy in the form of an SQL expression.
+**
+** For example, if the query:
+**
+** SELECT * FROM t1 WHERE a=1 AND b>2;
+**
+** is run and there is an index on (a, b), then this function returns a
+** string similar to:
+**
+** "a=? AND b>?"
+*/
+static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
+ Index *pIndex = pLoop->u.btree.pIndex;
+ u16 nEq = pLoop->u.btree.nEq;
+ u16 nSkip = pLoop->nSkip;
+ int i, j;
+
+ if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
+ sqlite3_str_append(pStr, " (", 2);
+ for(i=0; i<nEq; i++){
+ const char *z = explainIndexColumnName(pIndex, i);
+ if( i ) sqlite3_str_append(pStr, " AND ", 5);
+ sqlite3_str_appendf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
+ }
+
+ j = i;
+ if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
+ explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
+ i = 1;
+ }
+ if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
+ explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
+ }
+ sqlite3_str_append(pStr, ")", 1);
+}
+
+/*
+** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
+** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
+** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
+** is added to the output to describe the table scan strategy in pLevel.
+**
+** If an OP_Explain opcode is added to the VM, its address is returned.
+** Otherwise, if no OP_Explain is coded, zero is returned.
+*/
+SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
+ Parse *pParse, /* Parse context */
+ SrcList *pTabList, /* Table list this loop refers to */
+ WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
+ u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
+){
+ int ret = 0;
+#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
+ if( sqlite3ParseToplevel(pParse)->explain==2 )
+#endif
+ {
+ struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
+ Vdbe *v = pParse->pVdbe; /* VM being constructed */
+ sqlite3 *db = pParse->db; /* Database handle */
+ int isSearch; /* True for a SEARCH. False for SCAN. */
+ WhereLoop *pLoop; /* The controlling WhereLoop object */
+ u32 flags; /* Flags that describe this loop */
+ char *zMsg; /* Text to add to EQP output */
+ StrAccum str; /* EQP output string */
+ char zBuf[100]; /* Initial space for EQP output string */
+
+ pLoop = pLevel->pWLoop;
+ flags = pLoop->wsFlags;
+ if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
+
+ isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
+ || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
+ || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
+
+ sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
+ sqlite3_str_appendall(&str, isSearch ? "SEARCH" : "SCAN");
+ if( pItem->pSelect ){
+ sqlite3_str_appendf(&str, " SUBQUERY %u", pItem->pSelect->selId);
+ }else{
+ sqlite3_str_appendf(&str, " TABLE %s", pItem->zName);
+ }
+
+ if( pItem->zAlias ){
+ sqlite3_str_appendf(&str, " AS %s", pItem->zAlias);
+ }
+ if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
+ const char *zFmt = 0;
+ Index *pIdx;
+
+ assert( pLoop->u.btree.pIndex!=0 );
+ pIdx = pLoop->u.btree.pIndex;
+ assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
+ if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
+ if( isSearch ){
+ zFmt = "PRIMARY KEY";
+ }
+ }else if( flags & WHERE_PARTIALIDX ){
+ zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
+ }else if( flags & WHERE_AUTO_INDEX ){
+ zFmt = "AUTOMATIC COVERING INDEX";
+ }else if( flags & WHERE_IDX_ONLY ){
+ zFmt = "COVERING INDEX %s";
+ }else{
+ zFmt = "INDEX %s";
+ }
+ if( zFmt ){
+ sqlite3_str_append(&str, " USING ", 7);
+ sqlite3_str_appendf(&str, zFmt, pIdx->zName);
+ explainIndexRange(&str, pLoop);
+ }
+ }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
+ const char *zRangeOp;
+ if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
+ zRangeOp = "=";
+ }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
+ zRangeOp = ">? AND rowid<";
+ }else if( flags&WHERE_BTM_LIMIT ){
+ zRangeOp = ">";
+ }else{
+ assert( flags&WHERE_TOP_LIMIT);
+ zRangeOp = "<";
+ }
+ sqlite3_str_appendf(&str,
+ " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
+ }
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
+ sqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s",
+ pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
+ }
+#endif
+#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
+ if( pLoop->nOut>=10 ){
+ sqlite3_str_appendf(&str, " (~%llu rows)",
+ sqlite3LogEstToInt(pLoop->nOut));
+ }else{
+ sqlite3_str_append(&str, " (~1 row)", 9);
+ }
+#endif
+ zMsg = sqlite3StrAccumFinish(&str);
+ sqlite3ExplainBreakpoint("",zMsg);
+ ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
+ pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
+ }
+ return ret;
+}
+#endif /* SQLITE_OMIT_EXPLAIN */
+
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+/*
+** Configure the VM passed as the first argument with an
+** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
+** implement level pLvl. Argument pSrclist is a pointer to the FROM
+** clause that the scan reads data from.
+**
+** If argument addrExplain is not 0, it must be the address of an
+** OP_Explain instruction that describes the same loop.
+*/
+SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
+ Vdbe *v, /* Vdbe to add scanstatus entry to */
+ SrcList *pSrclist, /* FROM clause pLvl reads data from */
+ WhereLevel *pLvl, /* Level to add scanstatus() entry for */
+ int addrExplain /* Address of OP_Explain (or 0) */
+){
+ const char *zObj = 0;
+ WhereLoop *pLoop = pLvl->pWLoop;
+ if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
+ zObj = pLoop->u.btree.pIndex->zName;
+ }else{
+ zObj = pSrclist->a[pLvl->iFrom].zName;
+ }
+ sqlite3VdbeScanStatus(
+ v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
+ );
+}
+#endif
+
+
+/*
+** Disable a term in the WHERE clause. Except, do not disable the term
+** if it controls a LEFT OUTER JOIN and it did not originate in the ON
+** or USING clause of that join.
+**
+** Consider the term t2.z='ok' in the following queries:
+**
+** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
+** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
+** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
+**
+** The t2.z='ok' is disabled in the in (2) because it originates
+** in the ON clause. The term is disabled in (3) because it is not part
+** of a LEFT OUTER JOIN. In (1), the term is not disabled.
+**
+** Disabling a term causes that term to not be tested in the inner loop
+** of the join. Disabling is an optimization. When terms are satisfied
+** by indices, we disable them to prevent redundant tests in the inner
+** loop. We would get the correct results if nothing were ever disabled,
+** but joins might run a little slower. The trick is to disable as much
+** as we can without disabling too much. If we disabled in (1), we'd get
+** the wrong answer. See ticket #813.
+**
+** If all the children of a term are disabled, then that term is also
+** automatically disabled. In this way, terms get disabled if derived
+** virtual terms are tested first. For example:
+**
+** x GLOB 'abc*' AND x>='abc' AND x<'acd'
+** \___________/ \______/ \_____/
+** parent child1 child2
+**
+** Only the parent term was in the original WHERE clause. The child1
+** and child2 terms were added by the LIKE optimization. If both of
+** the virtual child terms are valid, then testing of the parent can be
+** skipped.
+**
+** Usually the parent term is marked as TERM_CODED. But if the parent
+** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
+** The TERM_LIKECOND marking indicates that the term should be coded inside
+** a conditional such that is only evaluated on the second pass of a
+** LIKE-optimization loop, when scanning BLOBs instead of strings.
+*/
+static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
+ int nLoop = 0;
+ assert( pTerm!=0 );
+ while( (pTerm->wtFlags & TERM_CODED)==0
+ && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
+ && (pLevel->notReady & pTerm->prereqAll)==0
+ ){
+ if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
+ pTerm->wtFlags |= TERM_LIKECOND;
+ }else{
+ pTerm->wtFlags |= TERM_CODED;
+ }
+ if( pTerm->iParent<0 ) break;
+ pTerm = &pTerm->pWC->a[pTerm->iParent];
+ assert( pTerm!=0 );
+ pTerm->nChild--;
+ if( pTerm->nChild!=0 ) break;
+ nLoop++;
+ }
+}
+
+/*
+** Code an OP_Affinity opcode to apply the column affinity string zAff
+** to the n registers starting at base.
+**
+** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which
+** are no-ops) at the beginning and end of zAff are ignored. If all entries
+** in zAff are SQLITE_AFF_BLOB or SQLITE_AFF_NONE, then no code gets generated.
+**
+** This routine makes its own copy of zAff so that the caller is free
+** to modify zAff after this routine returns.
+*/
+static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
+ Vdbe *v = pParse->pVdbe;
+ if( zAff==0 ){
+ assert( pParse->db->mallocFailed );
+ return;
+ }
+ assert( v!=0 );
+
+ /* Adjust base and n to skip over SQLITE_AFF_BLOB and SQLITE_AFF_NONE
+ ** entries at the beginning and end of the affinity string.
+ */
+ assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB );
+ while( n>0 && zAff[0]<=SQLITE_AFF_BLOB ){
+ n--;
+ base++;
+ zAff++;
+ }
+ while( n>1 && zAff[n-1]<=SQLITE_AFF_BLOB ){
+ n--;
+ }
+
+ /* Code the OP_Affinity opcode if there is anything left to do. */
+ if( n>0 ){
+ sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
+ }
+}
+
+/*
+** Expression pRight, which is the RHS of a comparison operation, is
+** either a vector of n elements or, if n==1, a scalar expression.
+** Before the comparison operation, affinity zAff is to be applied
+** to the pRight values. This function modifies characters within the
+** affinity string to SQLITE_AFF_BLOB if either:
+**
+** * the comparison will be performed with no affinity, or
+** * the affinity change in zAff is guaranteed not to change the value.
+*/
+static void updateRangeAffinityStr(
+ Expr *pRight, /* RHS of comparison */
+ int n, /* Number of vector elements in comparison */
+ char *zAff /* Affinity string to modify */
+){
+ int i;
+ for(i=0; i<n; i++){
+ Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
+ if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
+ || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
+ ){
+ zAff[i] = SQLITE_AFF_BLOB;
+ }
+ }
+}
+
+
+/*
+** pX is an expression of the form: (vector) IN (SELECT ...)
+** In other words, it is a vector IN operator with a SELECT clause on the
+** LHS. But not all terms in the vector are indexable and the terms might
+** not be in the correct order for indexing.
+**
+** This routine makes a copy of the input pX expression and then adjusts
+** the vector on the LHS with corresponding changes to the SELECT so that
+** the vector contains only index terms and those terms are in the correct
+** order. The modified IN expression is returned. The caller is responsible
+** for deleting the returned expression.
+**
+** Example:
+**
+** CREATE TABLE t1(a,b,c,d,e,f);
+** CREATE INDEX t1x1 ON t1(e,c);
+** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
+** \_______________________________________/
+** The pX expression
+**
+** Since only columns e and c can be used with the index, in that order,
+** the modified IN expression that is returned will be:
+**
+** (e,c) IN (SELECT z,x FROM t2)
+**
+** The reduced pX is different from the original (obviously) and thus is
+** only used for indexing, to improve performance. The original unaltered
+** IN expression must also be run on each output row for correctness.
+*/
+static Expr *removeUnindexableInClauseTerms(
+ Parse *pParse, /* The parsing context */
+ int iEq, /* Look at loop terms starting here */
+ WhereLoop *pLoop, /* The current loop */
+ Expr *pX /* The IN expression to be reduced */
+){
+ sqlite3 *db = pParse->db;
+ Expr *pNew;
+ pNew = sqlite3ExprDup(db, pX, 0);
+ if( db->mallocFailed==0 ){
+ ExprList *pOrigRhs = pNew->x.pSelect->pEList; /* Original unmodified RHS */
+ ExprList *pOrigLhs = pNew->pLeft->x.pList; /* Original unmodified LHS */
+ ExprList *pRhs = 0; /* New RHS after modifications */
+ ExprList *pLhs = 0; /* New LHS after mods */
+ int i; /* Loop counter */
+ Select *pSelect; /* Pointer to the SELECT on the RHS */
+
+ for(i=iEq; i<pLoop->nLTerm; i++){
+ if( pLoop->aLTerm[i]->pExpr==pX ){
+ int iField = pLoop->aLTerm[i]->u.x.iField - 1;
+ if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */
+ pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
+ pOrigRhs->a[iField].pExpr = 0;
+ assert( pOrigLhs->a[iField].pExpr!=0 );
+ pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr);
+ pOrigLhs->a[iField].pExpr = 0;
+ }
+ }
+ sqlite3ExprListDelete(db, pOrigRhs);
+ sqlite3ExprListDelete(db, pOrigLhs);
+ pNew->pLeft->x.pList = pLhs;
+ pNew->x.pSelect->pEList = pRhs;
+ if( pLhs && pLhs->nExpr==1 ){
+ /* Take care here not to generate a TK_VECTOR containing only a
+ ** single value. Since the parser never creates such a vector, some
+ ** of the subroutines do not handle this case. */
+ Expr *p = pLhs->a[0].pExpr;
+ pLhs->a[0].pExpr = 0;
+ sqlite3ExprDelete(db, pNew->pLeft);
+ pNew->pLeft = p;
+ }
+ pSelect = pNew->x.pSelect;
+ if( pSelect->pOrderBy ){
+ /* If the SELECT statement has an ORDER BY clause, zero the
+ ** iOrderByCol variables. These are set to non-zero when an
+ ** ORDER BY term exactly matches one of the terms of the
+ ** result-set. Since the result-set of the SELECT statement may
+ ** have been modified or reordered, these variables are no longer
+ ** set correctly. Since setting them is just an optimization,
+ ** it's easiest just to zero them here. */
+ ExprList *pOrderBy = pSelect->pOrderBy;
+ for(i=0; i<pOrderBy->nExpr; i++){
+ pOrderBy->a[i].u.x.iOrderByCol = 0;
+ }
+ }
+
+#if 0
+ printf("For indexing, change the IN expr:\n");
+ sqlite3TreeViewExpr(0, pX, 0);
+ printf("Into:\n");
+ sqlite3TreeViewExpr(0, pNew, 0);
+#endif
+ }
+ return pNew;
+}
+
+
+/*
+** Generate code for a single equality term of the WHERE clause. An equality
+** term can be either X=expr or X IN (...). pTerm is the term to be
+** coded.
+**
+** The current value for the constraint is left in a register, the index
+** of which is returned. An attempt is made store the result in iTarget but
+** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
+** constraint is a TK_EQ or TK_IS, then the current value might be left in
+** some other register and it is the caller's responsibility to compensate.
+**
+** For a constraint of the form X=expr, the expression is evaluated in
+** straight-line code. For constraints of the form X IN (...)
+** this routine sets up a loop that will iterate over all values of X.
+*/
+static int codeEqualityTerm(
+ Parse *pParse, /* The parsing context */
+ WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
+ WhereLevel *pLevel, /* The level of the FROM clause we are working on */
+ int iEq, /* Index of the equality term within this level */
+ int bRev, /* True for reverse-order IN operations */
+ int iTarget /* Attempt to leave results in this register */
+){
+ Expr *pX = pTerm->pExpr;
+ Vdbe *v = pParse->pVdbe;
+ int iReg; /* Register holding results */
+
+ assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
+ assert( iTarget>0 );
+ if( pX->op==TK_EQ || pX->op==TK_IS ){
+ iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
+ }else if( pX->op==TK_ISNULL ){
+ iReg = iTarget;
+ sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
+#ifndef SQLITE_OMIT_SUBQUERY
+ }else{
+ int eType = IN_INDEX_NOOP;
+ int iTab;
+ struct InLoop *pIn;
+ WhereLoop *pLoop = pLevel->pWLoop;
+ int i;
+ int nEq = 0;
+ int *aiMap = 0;
+
+ if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
+ && pLoop->u.btree.pIndex!=0
+ && pLoop->u.btree.pIndex->aSortOrder[iEq]
+ ){
+ testcase( iEq==0 );
+ testcase( bRev );
+ bRev = !bRev;
+ }
+ assert( pX->op==TK_IN );
+ iReg = iTarget;
+
+ for(i=0; i<iEq; i++){
+ if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
+ disableTerm(pLevel, pTerm);
+ return iTarget;
+ }
+ }
+ for(i=iEq;i<pLoop->nLTerm; i++){
+ assert( pLoop->aLTerm[i]!=0 );
+ if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
+ }
+
+ iTab = 0;
+ if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
+ eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab);
+ }else{
+ sqlite3 *db = pParse->db;
+ pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);
+
+ if( !db->mallocFailed ){
+ aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);
+ eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab);
+ pTerm->pExpr->iTable = iTab;
+ }
+ sqlite3ExprDelete(db, pX);
+ pX = pTerm->pExpr;
+ }
+
+ if( eType==IN_INDEX_INDEX_DESC ){
+ testcase( bRev );
+ bRev = !bRev;
+ }
+ sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
+ VdbeCoverageIf(v, bRev);
+ VdbeCoverageIf(v, !bRev);
+ assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
+
+ pLoop->wsFlags |= WHERE_IN_ABLE;
+ if( pLevel->u.in.nIn==0 ){
+ pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
+ }
+ if( iEq>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 ){
+ pLoop->wsFlags |= WHERE_IN_EARLYOUT;
+ }
+
+ i = pLevel->u.in.nIn;
+ pLevel->u.in.nIn += nEq;
+ pLevel->u.in.aInLoop =
+ sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
+ sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
+ pIn = pLevel->u.in.aInLoop;
+ if( pIn ){
+ int iMap = 0; /* Index in aiMap[] */
+ pIn += i;
+ for(i=iEq;i<pLoop->nLTerm; i++){
+ if( pLoop->aLTerm[i]->pExpr==pX ){
+ int iOut = iReg + i - iEq;
+ if( eType==IN_INDEX_ROWID ){
+ pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
+ }else{
+ int iCol = aiMap ? aiMap[iMap++] : 0;
+ pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
+ }
+ sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
+ if( i==iEq ){
+ pIn->iCur = iTab;
+ pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
+ if( iEq>0 ){
+ pIn->iBase = iReg - i;
+ pIn->nPrefix = i;
+ }else{
+ pIn->nPrefix = 0;
+ }
+ }else{
+ pIn->eEndLoopOp = OP_Noop;
+ }
+ pIn++;
+ }
+ }
+ testcase( iEq>0
+ && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
+ && (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 );
+ if( iEq>0
+ && (pLoop->wsFlags & (WHERE_IN_SEEKSCAN|WHERE_VIRTUALTABLE))==0
+ ){
+ sqlite3VdbeAddOp3(v, OP_SeekHit, pLevel->iIdxCur, 0, iEq);
+ }
+ }else{
+ pLevel->u.in.nIn = 0;
+ }
+ sqlite3DbFree(pParse->db, aiMap);
+#endif
+ }
+ disableTerm(pLevel, pTerm);
+ return iReg;
+}
+
+/*
+** Generate code that will evaluate all == and IN constraints for an
+** index scan.
+**
+** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
+** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
+** The index has as many as three equality constraints, but in this
+** example, the third "c" value is an inequality. So only two
+** constraints are coded. This routine will generate code to evaluate
+** a==5 and b IN (1,2,3). The current values for a and b will be stored
+** in consecutive registers and the index of the first register is returned.
+**
+** In the example above nEq==2. But this subroutine works for any value
+** of nEq including 0. If nEq==0, this routine is nearly a no-op.
+** The only thing it does is allocate the pLevel->iMem memory cell and
+** compute the affinity string.
+**
+** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
+** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
+** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
+** occurs after the nEq quality constraints.
+**
+** This routine allocates a range of nEq+nExtraReg memory cells and returns
+** the index of the first memory cell in that range. The code that
+** calls this routine will use that memory range to store keys for
+** start and termination conditions of the loop.
+** key value of the loop. If one or more IN operators appear, then
+** this routine allocates an additional nEq memory cells for internal
+** use.
+**
+** Before returning, *pzAff is set to point to a buffer containing a
+** copy of the column affinity string of the index allocated using
+** sqlite3DbMalloc(). Except, entries in the copy of the string associated
+** with equality constraints that use BLOB or NONE affinity are set to
+** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
+**
+** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
+** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
+**
+** In the example above, the index on t1(a) has TEXT affinity. But since
+** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
+** no conversion should be attempted before using a t2.b value as part of
+** a key to search the index. Hence the first byte in the returned affinity
+** string in this example would be set to SQLITE_AFF_BLOB.
+*/
+static int codeAllEqualityTerms(
+ Parse *pParse, /* Parsing context */
+ WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
+ int bRev, /* Reverse the order of IN operators */
+ int nExtraReg, /* Number of extra registers to allocate */
+ char **pzAff /* OUT: Set to point to affinity string */
+){
+ u16 nEq; /* The number of == or IN constraints to code */
+ u16 nSkip; /* Number of left-most columns to skip */
+ Vdbe *v = pParse->pVdbe; /* The vm under construction */
+ Index *pIdx; /* The index being used for this loop */
+ WhereTerm *pTerm; /* A single constraint term */
+ WhereLoop *pLoop; /* The WhereLoop object */
+ int j; /* Loop counter */
+ int regBase; /* Base register */
+ int nReg; /* Number of registers to allocate */
+ char *zAff; /* Affinity string to return */
+
+ /* This module is only called on query plans that use an index. */
+ pLoop = pLevel->pWLoop;
+ assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
+ nEq = pLoop->u.btree.nEq;
+ nSkip = pLoop->nSkip;
+ pIdx = pLoop->u.btree.pIndex;
+ assert( pIdx!=0 );
+
+ /* Figure out how many memory cells we will need then allocate them.
+ */
+ regBase = pParse->nMem + 1;
+ nReg = pLoop->u.btree.nEq + nExtraReg;
+ pParse->nMem += nReg;
+
+ zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
+ assert( zAff!=0 || pParse->db->mallocFailed );
+
+ if( nSkip ){
+ int iIdxCur = pLevel->iIdxCur;
+ sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
+ VdbeCoverageIf(v, bRev==0);
+ VdbeCoverageIf(v, bRev!=0);
+ VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
+ j = sqlite3VdbeAddOp0(v, OP_Goto);
+ pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
+ iIdxCur, 0, regBase, nSkip);
+ VdbeCoverageIf(v, bRev==0);
+ VdbeCoverageIf(v, bRev!=0);
+ sqlite3VdbeJumpHere(v, j);
+ for(j=0; j<nSkip; j++){
+ sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
+ testcase( pIdx->aiColumn[j]==XN_EXPR );
+ VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
+ }
+ }
+
+ /* Evaluate the equality constraints
+ */
+ assert( zAff==0 || (int)strlen(zAff)>=nEq );
+ for(j=nSkip; j<nEq; j++){
+ int r1;
+ pTerm = pLoop->aLTerm[j];
+ assert( pTerm!=0 );
+ /* The following testcase is true for indices with redundant columns.
+ ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
+ testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
+ testcase( pTerm->wtFlags & TERM_VIRTUAL );
+ r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
+ if( r1!=regBase+j ){
+ if( nReg==1 ){
+ sqlite3ReleaseTempReg(pParse, regBase);
+ regBase = r1;
+ }else{
+ sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
+ }
+ }
+ if( pTerm->eOperator & WO_IN ){
+ if( pTerm->pExpr->flags & EP_xIsSelect ){
+ /* No affinity ever needs to be (or should be) applied to a value
+ ** from the RHS of an "? IN (SELECT ...)" expression. The
+ ** sqlite3FindInIndex() routine has already ensured that the
+ ** affinity of the comparison has been applied to the value. */
+ if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
+ }
+ }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
+ Expr *pRight = pTerm->pExpr->pRight;
+ if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
+ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
+ VdbeCoverage(v);
+ }
+ if( zAff ){
+ if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
+ zAff[j] = SQLITE_AFF_BLOB;
+ }
+ if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
+ zAff[j] = SQLITE_AFF_BLOB;
+ }
+ }
+ }
+ }
+ *pzAff = zAff;
+ return regBase;
+}
+
+#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
+/*
+** If the most recently coded instruction is a constant range constraint
+** (a string literal) that originated from the LIKE optimization, then
+** set P3 and P5 on the OP_String opcode so that the string will be cast
+** to a BLOB at appropriate times.
+**
+** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
+** expression: "x>='ABC' AND x<'abd'". But this requires that the range
+** scan loop run twice, once for strings and a second time for BLOBs.
+** The OP_String opcodes on the second pass convert the upper and lower
+** bound string constants to blobs. This routine makes the necessary changes
+** to the OP_String opcodes for that to happen.
+**
+** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
+** only the one pass through the string space is required, so this routine
+** becomes a no-op.
+*/
+static void whereLikeOptimizationStringFixup(
+ Vdbe *v, /* prepared statement under construction */
+ WhereLevel *pLevel, /* The loop that contains the LIKE operator */
+ WhereTerm *pTerm /* The upper or lower bound just coded */
+){
+ if( pTerm->wtFlags & TERM_LIKEOPT ){
+ VdbeOp *pOp;
+ assert( pLevel->iLikeRepCntr>0 );
+ pOp = sqlite3VdbeGetOp(v, -1);
+ assert( pOp!=0 );
+ assert( pOp->opcode==OP_String8
+ || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
+ pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
+ pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
+ }
+}
+#else
+# define whereLikeOptimizationStringFixup(A,B,C)
+#endif
+
+#ifdef SQLITE_ENABLE_CURSOR_HINTS
+/*
+** Information is passed from codeCursorHint() down to individual nodes of
+** the expression tree (by sqlite3WalkExpr()) using an instance of this
+** structure.
+*/
+struct CCurHint {
+ int iTabCur; /* Cursor for the main table */
+ int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
+ Index *pIdx; /* The index used to access the table */
+};
+
+/*
+** This function is called for every node of an expression that is a candidate
+** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
+** the table CCurHint.iTabCur, verify that the same column can be
+** accessed through the index. If it cannot, then set pWalker->eCode to 1.
+*/
+static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
+ struct CCurHint *pHint = pWalker->u.pCCurHint;
+ assert( pHint->pIdx!=0 );
+ if( pExpr->op==TK_COLUMN
+ && pExpr->iTable==pHint->iTabCur
+ && sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn)<0
+ ){
+ pWalker->eCode = 1;
+ }
+ return WRC_Continue;
+}
+
+/*
+** Test whether or not expression pExpr, which was part of a WHERE clause,
+** should be included in the cursor-hint for a table that is on the rhs
+** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
+** expression is not suitable.
+**
+** An expression is unsuitable if it might evaluate to non NULL even if
+** a TK_COLUMN node that does affect the value of the expression is set
+** to NULL. For example:
+**
+** col IS NULL
+** col IS NOT NULL
+** coalesce(col, 1)
+** CASE WHEN col THEN 0 ELSE 1 END
+*/
+static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
+ if( pExpr->op==TK_IS
+ || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
+ || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
+ ){
+ pWalker->eCode = 1;
+ }else if( pExpr->op==TK_FUNCTION ){
+ int d1;
+ char d2[4];
+ if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
+ pWalker->eCode = 1;
+ }
+ }
+
+ return WRC_Continue;
+}
+
+
+/*
+** This function is called on every node of an expression tree used as an
+** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
+** that accesses any table other than the one identified by
+** CCurHint.iTabCur, then do the following:
+**
+** 1) allocate a register and code an OP_Column instruction to read
+** the specified column into the new register, and
+**
+** 2) transform the expression node to a TK_REGISTER node that reads
+** from the newly populated register.
+**
+** Also, if the node is a TK_COLUMN that does access the table idenified
+** by pCCurHint.iTabCur, and an index is being used (which we will
+** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
+** an access of the index rather than the original table.
+*/
+static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
+ int rc = WRC_Continue;
+ struct CCurHint *pHint = pWalker->u.pCCurHint;
+ if( pExpr->op==TK_COLUMN ){
+ if( pExpr->iTable!=pHint->iTabCur ){
+ int reg = ++pWalker->pParse->nMem; /* Register for column value */
+ sqlite3ExprCode(pWalker->pParse, pExpr, reg);
+ pExpr->op = TK_REGISTER;
+ pExpr->iTable = reg;
+ }else if( pHint->pIdx!=0 ){
+ pExpr->iTable = pHint->iIdxCur;
+ pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn);
+ assert( pExpr->iColumn>=0 );
+ }
+ }else if( pExpr->op==TK_AGG_FUNCTION ){
+ /* An aggregate function in the WHERE clause of a query means this must
+ ** be a correlated sub-query, and expression pExpr is an aggregate from
+ ** the parent context. Do not walk the function arguments in this case.
+ **
+ ** todo: It should be possible to replace this node with a TK_REGISTER
+ ** expression, as the result of the expression must be stored in a
+ ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
+ rc = WRC_Prune;
+ }
+ return rc;
+}
+
+/*
+** Insert an OP_CursorHint instruction if it is appropriate to do so.
+*/
+static void codeCursorHint(
+ struct SrcList_item *pTabItem, /* FROM clause item */
+ WhereInfo *pWInfo, /* The where clause */
+ WhereLevel *pLevel, /* Which loop to provide hints for */
+ WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
+){
+ Parse *pParse = pWInfo->pParse;
+ sqlite3 *db = pParse->db;
+ Vdbe *v = pParse->pVdbe;
+ Expr *pExpr = 0;
+ WhereLoop *pLoop = pLevel->pWLoop;
+ int iCur;
+ WhereClause *pWC;
+ WhereTerm *pTerm;
+ int i, j;
+ struct CCurHint sHint;
+ Walker sWalker;
+
+ if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
+ iCur = pLevel->iTabCur;
+ assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
+ sHint.iTabCur = iCur;
+ sHint.iIdxCur = pLevel->iIdxCur;
+ sHint.pIdx = pLoop->u.btree.pIndex;
+ memset(&sWalker, 0, sizeof(sWalker));
+ sWalker.pParse = pParse;
+ sWalker.u.pCCurHint = &sHint;
+ pWC = &pWInfo->sWC;
+ for(i=0; i<pWC->nTerm; i++){
+ pTerm = &pWC->a[i];
+ if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
+ if( pTerm->prereqAll & pLevel->notReady ) continue;
+
+ /* Any terms specified as part of the ON(...) clause for any LEFT
+ ** JOIN for which the current table is not the rhs are omitted
+ ** from the cursor-hint.
+ **
+ ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
+ ** that were specified as part of the WHERE clause must be excluded.
+ ** This is to address the following:
+ **
+ ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
+ **
+ ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
+ ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
+ ** pushed down to the cursor, this row is filtered out, causing
+ ** SQLite to synthesize a row of NULL values. Which does match the
+ ** WHERE clause, and so the query returns a row. Which is incorrect.
+ **
+ ** For the same reason, WHERE terms such as:
+ **
+ ** WHERE 1 = (t2.c IS NULL)
+ **
+ ** are also excluded. See codeCursorHintIsOrFunction() for details.
+ */
+ if( pTabItem->fg.jointype & JT_LEFT ){
+ Expr *pExpr = pTerm->pExpr;
+ if( !ExprHasProperty(pExpr, EP_FromJoin)
+ || pExpr->iRightJoinTable!=pTabItem->iCursor
+ ){
+ sWalker.eCode = 0;
+ sWalker.xExprCallback = codeCursorHintIsOrFunction;
+ sqlite3WalkExpr(&sWalker, pTerm->pExpr);
+ if( sWalker.eCode ) continue;
+ }
+ }else{
+ if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
+ }
+
+ /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
+ ** the cursor. These terms are not needed as hints for a pure range
+ ** scan (that has no == terms) so omit them. */
+ if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
+ for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
+ if( j<pLoop->nLTerm ) continue;
+ }
+
+ /* No subqueries or non-deterministic functions allowed */
+ if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
+
+ /* For an index scan, make sure referenced columns are actually in
+ ** the index. */
+ if( sHint.pIdx!=0 ){
+ sWalker.eCode = 0;
+ sWalker.xExprCallback = codeCursorHintCheckExpr;
+ sqlite3WalkExpr(&sWalker, pTerm->pExpr);
+ if( sWalker.eCode ) continue;
+ }
+
+ /* If we survive all prior tests, that means this term is worth hinting */
+ pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
+ }
+ if( pExpr!=0 ){
+ sWalker.xExprCallback = codeCursorHintFixExpr;
+ sqlite3WalkExpr(&sWalker, pExpr);
+ sqlite3VdbeAddOp4(v, OP_CursorHint,
+ (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
+ (const char*)pExpr, P4_EXPR);
+ }
+}
+#else
+# define codeCursorHint(A,B,C,D) /* No-op */
+#endif /* SQLITE_ENABLE_CURSOR_HINTS */
+
+/*
+** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
+** a rowid value just read from cursor iIdxCur, open on index pIdx. This
+** function generates code to do a deferred seek of cursor iCur to the
+** rowid stored in register iRowid.
+**
+** Normally, this is just:
+**
+** OP_DeferredSeek $iCur $iRowid
+**
+** However, if the scan currently being coded is a branch of an OR-loop and
+** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek
+** is set to iIdxCur and P4 is set to point to an array of integers
+** containing one entry for each column of the table cursor iCur is open
+** on. For each table column, if the column is the i'th column of the
+** index, then the corresponding array entry is set to (i+1). If the column
+** does not appear in the index at all, the array entry is set to 0.
+*/
+static void codeDeferredSeek(
+ WhereInfo *pWInfo, /* Where clause context */
+ Index *pIdx, /* Index scan is using */
+ int iCur, /* Cursor for IPK b-tree */
+ int iIdxCur /* Index cursor */
+){
+ Parse *pParse = pWInfo->pParse; /* Parse context */
+ Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
+
+ assert( iIdxCur>0 );
+ assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
+
+ pWInfo->bDeferredSeek = 1;
+ sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
+ if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
+ && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
+ ){
+ int i;
+ Table *pTab = pIdx->pTable;
+ u32 *ai = (u32*)sqlite3DbMallocZero(pParse->db, sizeof(u32)*(pTab->nCol+1));
+ if( ai ){
+ ai[0] = pTab->nCol;
+ for(i=0; i<pIdx->nColumn-1; i++){
+ int x1, x2;
+ assert( pIdx->aiColumn[i]<pTab->nCol );
+ x1 = pIdx->aiColumn[i];
+ x2 = sqlite3TableColumnToStorage(pTab, x1);
+ testcase( x1!=x2 );
+ if( x1>=0 ) ai[x2+1] = i+1;
+ }
+ sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
+ }
+ }
+}
+
+/*
+** If the expression passed as the second argument is a vector, generate
+** code to write the first nReg elements of the vector into an array
+** of registers starting with iReg.
+**
+** If the expression is not a vector, then nReg must be passed 1. In
+** this case, generate code to evaluate the expression and leave the
+** result in register iReg.
+*/
+static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
+ assert( nReg>0 );
+ if( p && sqlite3ExprIsVector(p) ){
+#ifndef SQLITE_OMIT_SUBQUERY
+ if( (p->flags & EP_xIsSelect) ){
+ Vdbe *v = pParse->pVdbe;
+ int iSelect;
+ assert( p->op==TK_SELECT );
+ iSelect = sqlite3CodeSubselect(pParse, p);
+ sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
+ }else
+#endif
+ {
+ int i;
+ ExprList *pList = p->x.pList;
+ assert( nReg<=pList->nExpr );
+ for(i=0; i<nReg; i++){
+ sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
+ }
+ }
+ }else{
+ assert( nReg==1 );
+ sqlite3ExprCode(pParse, p, iReg);
+ }
+}
+
+/* An instance of the IdxExprTrans object carries information about a
+** mapping from an expression on table columns into a column in an index
+** down through the Walker.
+*/
+typedef struct IdxExprTrans {
+ Expr *pIdxExpr; /* The index expression */
+ int iTabCur; /* The cursor of the corresponding table */
+ int iIdxCur; /* The cursor for the index */
+ int iIdxCol; /* The column for the index */
+ int iTabCol; /* The column for the table */
+ WhereInfo *pWInfo; /* Complete WHERE clause information */
+ sqlite3 *db; /* Database connection (for malloc()) */
+} IdxExprTrans;
+
+/*
+** Preserve pExpr on the WhereETrans list of the WhereInfo.
+*/
+static void preserveExpr(IdxExprTrans *pTrans, Expr *pExpr){
+ WhereExprMod *pNew;
+ pNew = sqlite3DbMallocRaw(pTrans->db, sizeof(*pNew));
+ if( pNew==0 ) return;
+ pNew->pNext = pTrans->pWInfo->pExprMods;
+ pTrans->pWInfo->pExprMods = pNew;
+ pNew->pExpr = pExpr;
+ memcpy(&pNew->orig, pExpr, sizeof(*pExpr));
+}
+
+/* The walker node callback used to transform matching expressions into
+** a reference to an index column for an index on an expression.
+**
+** If pExpr matches, then transform it into a reference to the index column
+** that contains the value of pExpr.
+*/
+static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
+ IdxExprTrans *pX = p->u.pIdxTrans;
+ if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
+ preserveExpr(pX, pExpr);
+ pExpr->affExpr = sqlite3ExprAffinity(pExpr);
+ pExpr->op = TK_COLUMN;
+ pExpr->iTable = pX->iIdxCur;
+ pExpr->iColumn = pX->iIdxCol;
+ pExpr->y.pTab = 0;
+ testcase( ExprHasProperty(pExpr, EP_Skip) );
+ testcase( ExprHasProperty(pExpr, EP_Unlikely) );
+ ExprClearProperty(pExpr, EP_Skip|EP_Unlikely);
+ return WRC_Prune;
+ }else{
+ return WRC_Continue;
+ }
+}
+
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+/* A walker node callback that translates a column reference to a table
+** into a corresponding column reference of an index.
+*/
+static int whereIndexExprTransColumn(Walker *p, Expr *pExpr){
+ if( pExpr->op==TK_COLUMN ){
+ IdxExprTrans *pX = p->u.pIdxTrans;
+ if( pExpr->iTable==pX->iTabCur && pExpr->iColumn==pX->iTabCol ){
+ assert( pExpr->y.pTab!=0 );
+ preserveExpr(pX, pExpr);
+ pExpr->affExpr = sqlite3TableColumnAffinity(pExpr->y.pTab,pExpr->iColumn);
+ pExpr->iTable = pX->iIdxCur;
+ pExpr->iColumn = pX->iIdxCol;
+ pExpr->y.pTab = 0;
+ }
+ }
+ return WRC_Continue;
+}
+#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
+
+/*
+** For an indexes on expression X, locate every instance of expression X
+** in pExpr and change that subexpression into a reference to the appropriate
+** column of the index.
+**
+** 2019-10-24: Updated to also translate references to a VIRTUAL column in
+** the table into references to the corresponding (stored) column of the
+** index.
+*/
+static void whereIndexExprTrans(
+ Index *pIdx, /* The Index */
+ int iTabCur, /* Cursor of the table that is being indexed */
+ int iIdxCur, /* Cursor of the index itself */
+ WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
+){
+ int iIdxCol; /* Column number of the index */
+ ExprList *aColExpr; /* Expressions that are indexed */
+ Table *pTab;
+ Walker w;
+ IdxExprTrans x;
+ aColExpr = pIdx->aColExpr;
+ if( aColExpr==0 && !pIdx->bHasVCol ){
+ /* The index does not reference any expressions or virtual columns
+ ** so no translations are needed. */
+ return;
+ }
+ pTab = pIdx->pTable;
+ memset(&w, 0, sizeof(w));
+ w.u.pIdxTrans = &x;
+ x.iTabCur = iTabCur;
+ x.iIdxCur = iIdxCur;
+ x.pWInfo = pWInfo;
+ x.db = pWInfo->pParse->db;
+ for(iIdxCol=0; iIdxCol<pIdx->nColumn; iIdxCol++){
+ i16 iRef = pIdx->aiColumn[iIdxCol];
+ if( iRef==XN_EXPR ){
+ assert( aColExpr->a[iIdxCol].pExpr!=0 );
+ x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
+ if( sqlite3ExprIsConstant(x.pIdxExpr) ) continue;
+ w.xExprCallback = whereIndexExprTransNode;
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+ }else if( iRef>=0
+ && (pTab->aCol[iRef].colFlags & COLFLAG_VIRTUAL)!=0
+ && (pTab->aCol[iRef].zColl==0
+ || sqlite3StrICmp(pTab->aCol[iRef].zColl, sqlite3StrBINARY)==0)
+ ){
+ /* Check to see if there are direct references to generated columns
+ ** that are contained in the index. Pulling the generated column
+ ** out of the index is an optimization only - the main table is always
+ ** available if the index cannot be used. To avoid unnecessary
+ ** complication, omit this optimization if the collating sequence for
+ ** the column is non-standard */
+ x.iTabCol = iRef;
+ w.xExprCallback = whereIndexExprTransColumn;
+#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
+ }else{
+ continue;
+ }
+ x.iIdxCol = iIdxCol;
+ sqlite3WalkExpr(&w, pWInfo->pWhere);
+ sqlite3WalkExprList(&w, pWInfo->pOrderBy);
+ sqlite3WalkExprList(&w, pWInfo->pResultSet);
+ }
+}
+
+/*
+** The pTruth expression is always true because it is the WHERE clause
+** a partial index that is driving a query loop. Look through all of the
+** WHERE clause terms on the query, and if any of those terms must be
+** true because pTruth is true, then mark those WHERE clause terms as
+** coded.
+*/
+static void whereApplyPartialIndexConstraints(
+ Expr *pTruth,
+ int iTabCur,
+ WhereClause *pWC
+){
+ int i;
+ WhereTerm *pTerm;
+ while( pTruth->op==TK_AND ){
+ whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC);
+ pTruth = pTruth->pRight;
+ }
+ for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
+ Expr *pExpr;
+ if( pTerm->wtFlags & TERM_CODED ) continue;
+ pExpr = pTerm->pExpr;
+ if( sqlite3ExprCompare(0, pExpr, pTruth, iTabCur)==0 ){
+ pTerm->wtFlags |= TERM_CODED;
+ }
+ }
+}
+
+/*
+** Generate code for the start of the iLevel-th loop in the WHERE clause
+** implementation described by pWInfo.
+*/
+SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
+ Parse *pParse, /* Parsing context */
+ Vdbe *v, /* Prepared statement under construction */
+ WhereInfo *pWInfo, /* Complete information about the WHERE clause */
+ int iLevel, /* Which level of pWInfo->a[] should be coded */
+ WhereLevel *pLevel, /* The current level pointer */
+ Bitmask notReady /* Which tables are currently available */
+){
+ int j, k; /* Loop counters */
+ int iCur; /* The VDBE cursor for the table */
+ int addrNxt; /* Where to jump to continue with the next IN case */
+ int bRev; /* True if we need to scan in reverse order */
+ WhereLoop *pLoop; /* The WhereLoop object being coded */
+ WhereClause *pWC; /* Decomposition of the entire WHERE clause */
+ WhereTerm *pTerm; /* A WHERE clause term */
+ sqlite3 *db; /* Database connection */
+ struct SrcList_item *pTabItem; /* FROM clause term being coded */
+ int addrBrk; /* Jump here to break out of the loop */
+ int addrHalt; /* addrBrk for the outermost loop */
+ int addrCont; /* Jump here to continue with next cycle */
+ int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
+ int iReleaseReg = 0; /* Temp register to free before returning */
+ Index *pIdx = 0; /* Index used by loop (if any) */
+ int iLoop; /* Iteration of constraint generator loop */
+
+ pWC = &pWInfo->sWC;
+ db = pParse->db;
+ pLoop = pLevel->pWLoop;
+ pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
+ iCur = pTabItem->iCursor;
+ pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
+ bRev = (pWInfo->revMask>>iLevel)&1;
+ VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
+#if WHERETRACE_ENABLED /* 0x20800 */
+ if( sqlite3WhereTrace & 0x800 ){
+ sqlite3DebugPrintf("Coding level %d of %d: notReady=%llx iFrom=%d\n",
+ iLevel, pWInfo->nLevel, (u64)notReady, pLevel->iFrom);
+ sqlite3WhereLoopPrint(pLoop, pWC);
+ }
+ if( sqlite3WhereTrace & 0x20000 ){
+ if( iLevel==0 ){
+ sqlite3DebugPrintf("WHERE clause being coded:\n");
+ sqlite3TreeViewExpr(0, pWInfo->pWhere, 0);
+ }
+ sqlite3DebugPrintf("All WHERE-clause terms before coding:\n");
+ sqlite3WhereClausePrint(pWC);
+ }
+#endif
+
+ /* Create labels for the "break" and "continue" instructions
+ ** for the current loop. Jump to addrBrk to break out of a loop.
+ ** Jump to cont to go immediately to the next iteration of the
+ ** loop.
+ **
+ ** When there is an IN operator, we also have a "addrNxt" label that
+ ** means to continue with the next IN value combination. When
+ ** there are no IN operators in the constraints, the "addrNxt" label
+ ** is the same as "addrBrk".
+ */
+ addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
+ addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse);
+
+ /* If this is the right table of a LEFT OUTER JOIN, allocate and
+ ** initialize a memory cell that records if this table matches any
+ ** row of the left table of the join.
+ */
+ assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
+ || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0
+ );
+ if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
+ pLevel->iLeftJoin = ++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
+ VdbeComment((v, "init LEFT JOIN no-match flag"));
+ }
+
+ /* Compute a safe address to jump to if we discover that the table for
+ ** this loop is empty and can never contribute content. */
+ for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
+ addrHalt = pWInfo->a[j].addrBrk;
+
+ /* Special case of a FROM clause subquery implemented as a co-routine */
+ if( pTabItem->fg.viaCoroutine ){
+ int regYield = pTabItem->regReturn;
+ sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
+ pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
+ VdbeCoverage(v);
+ VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
+ pLevel->op = OP_Goto;
+ }else
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
+ /* Case 1: The table is a virtual-table. Use the VFilter and VNext
+ ** to access the data.
+ */
+ int iReg; /* P3 Value for OP_VFilter */
+ int addrNotFound;
+ int nConstraint = pLoop->nLTerm;
+ int iIn; /* Counter for IN constraints */
+
+ iReg = sqlite3GetTempRange(pParse, nConstraint+2);
+ addrNotFound = pLevel->addrBrk;
+ for(j=0; j<nConstraint; j++){
+ int iTarget = iReg+j+2;
+ pTerm = pLoop->aLTerm[j];
+ if( NEVER(pTerm==0) ) continue;
+ if( pTerm->eOperator & WO_IN ){
+ codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
+ addrNotFound = pLevel->addrNxt;
+ }else{
+ Expr *pRight = pTerm->pExpr->pRight;
+ codeExprOrVector(pParse, pRight, iTarget, 1);
+ }
+ }
+ sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
+ sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
+ sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
+ pLoop->u.vtab.idxStr,
+ pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
+ VdbeCoverage(v);
+ pLoop->u.vtab.needFree = 0;
+ /* An OOM inside of AddOp4(OP_VFilter) instruction above might have freed
+ ** the u.vtab.idxStr. NULL it out to prevent a use-after-free */
+ if( db->mallocFailed ) pLoop->u.vtab.idxStr = 0;
+ pLevel->p1 = iCur;
+ pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
+ pLevel->p2 = sqlite3VdbeCurrentAddr(v);
+ iIn = pLevel->u.in.nIn;
+ for(j=nConstraint-1; j>=0; j--){
+ pTerm = pLoop->aLTerm[j];
+ if( (pTerm->eOperator & WO_IN)!=0 ) iIn--;
+ if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
+ disableTerm(pLevel, pTerm);
+ }else if( (pTerm->eOperator & WO_IN)!=0
+ && sqlite3ExprVectorSize(pTerm->pExpr->pLeft)==1
+ ){
+ Expr *pCompare; /* The comparison operator */
+ Expr *pRight; /* RHS of the comparison */
+ VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
+
+ /* Reload the constraint value into reg[iReg+j+2]. The same value
+ ** was loaded into the same register prior to the OP_VFilter, but
+ ** the xFilter implementation might have changed the datatype or
+ ** encoding of the value in the register, so it *must* be reloaded. */
+ assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
+ if( !db->mallocFailed ){
+ assert( iIn>=0 && iIn<pLevel->u.in.nIn );
+ pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop);
+ assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
+ assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
+ assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
+ testcase( pOp->opcode==OP_Rowid );
+ sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
+ }
+
+ /* Generate code that will continue to the next row if
+ ** the IN constraint is not satisfied */
+ pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
+ assert( pCompare!=0 || db->mallocFailed );
+ if( pCompare ){
+ pCompare->pLeft = pTerm->pExpr->pLeft;
+ pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
+ if( pRight ){
+ pRight->iTable = iReg+j+2;
+ sqlite3ExprIfFalse(
+ pParse, pCompare, pLevel->addrCont, SQLITE_JUMPIFNULL
+ );
+ }
+ pCompare->pLeft = 0;
+ sqlite3ExprDelete(db, pCompare);
+ }
+ }
+ }
+ assert( iIn==0 || db->mallocFailed );
+ /* These registers need to be preserved in case there is an IN operator
+ ** loop. So we could deallocate the registers here (and potentially
+ ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
+ ** simpler and safer to simply not reuse the registers.
+ **
+ ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
+ */
+ }else
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+ if( (pLoop->wsFlags & WHERE_IPK)!=0
+ && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
+ ){
+ /* Case 2: We can directly reference a single row using an
+ ** equality comparison against the ROWID field. Or
+ ** we reference multiple rows using a "rowid IN (...)"
+ ** construct.
+ */
+ assert( pLoop->u.btree.nEq==1 );
+ pTerm = pLoop->aLTerm[0];
+ assert( pTerm!=0 );
+ assert( pTerm->pExpr!=0 );
+ testcase( pTerm->wtFlags & TERM_VIRTUAL );
+ iReleaseReg = ++pParse->nMem;
+ iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
+ if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
+ addrNxt = pLevel->addrNxt;
+ sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
+ VdbeCoverage(v);
+ pLevel->op = OP_Noop;
+ if( (pTerm->prereqAll & pLevel->notReady)==0 ){
+ pTerm->wtFlags |= TERM_CODED;
+ }
+ }else if( (pLoop->wsFlags & WHERE_IPK)!=0
+ && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
+ ){
+ /* Case 3: We have an inequality comparison against the ROWID field.
+ */
+ int testOp = OP_Noop;
+ int start;
+ int memEndValue = 0;
+ WhereTerm *pStart, *pEnd;
+
+ j = 0;
+ pStart = pEnd = 0;
+ if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
+ if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
+ assert( pStart!=0 || pEnd!=0 );
+ if( bRev ){
+ pTerm = pStart;
+ pStart = pEnd;
+ pEnd = pTerm;
+ }
+ codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
+ if( pStart ){
+ Expr *pX; /* The expression that defines the start bound */
+ int r1, rTemp; /* Registers for holding the start boundary */
+ int op; /* Cursor seek operation */
+
+ /* The following constant maps TK_xx codes into corresponding
+ ** seek opcodes. It depends on a particular ordering of TK_xx
+ */
+ const u8 aMoveOp[] = {
+ /* TK_GT */ OP_SeekGT,
+ /* TK_LE */ OP_SeekLE,
+ /* TK_LT */ OP_SeekLT,
+ /* TK_GE */ OP_SeekGE
+ };
+ assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
+ assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
+ assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
+
+ assert( (pStart->wtFlags & TERM_VNULL)==0 );
+ testcase( pStart->wtFlags & TERM_VIRTUAL );
+ pX = pStart->pExpr;
+ assert( pX!=0 );
+ testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
+ if( sqlite3ExprIsVector(pX->pRight) ){
+ r1 = rTemp = sqlite3GetTempReg(pParse);
+ codeExprOrVector(pParse, pX->pRight, r1, 1);
+ testcase( pX->op==TK_GT );
+ testcase( pX->op==TK_GE );
+ testcase( pX->op==TK_LT );
+ testcase( pX->op==TK_LE );
+ op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1];
+ assert( pX->op!=TK_GT || op==OP_SeekGE );
+ assert( pX->op!=TK_GE || op==OP_SeekGE );
+ assert( pX->op!=TK_LT || op==OP_SeekLE );
+ assert( pX->op!=TK_LE || op==OP_SeekLE );
+ }else{
+ r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
+ disableTerm(pLevel, pStart);
+ op = aMoveOp[(pX->op - TK_GT)];
+ }
+ sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
+ VdbeComment((v, "pk"));
+ VdbeCoverageIf(v, pX->op==TK_GT);
+ VdbeCoverageIf(v, pX->op==TK_LE);
+ VdbeCoverageIf(v, pX->op==TK_LT);
+ VdbeCoverageIf(v, pX->op==TK_GE);
+ sqlite3ReleaseTempReg(pParse, rTemp);
+ }else{
+ sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
+ VdbeCoverageIf(v, bRev==0);
+ VdbeCoverageIf(v, bRev!=0);
+ }
+ if( pEnd ){
+ Expr *pX;
+ pX = pEnd->pExpr;
+ assert( pX!=0 );
+ assert( (pEnd->wtFlags & TERM_VNULL)==0 );
+ testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
+ testcase( pEnd->wtFlags & TERM_VIRTUAL );
+ memEndValue = ++pParse->nMem;
+ codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
+ if( 0==sqlite3ExprIsVector(pX->pRight)
+ && (pX->op==TK_LT || pX->op==TK_GT)
+ ){
+ testOp = bRev ? OP_Le : OP_Ge;
+ }else{
+ testOp = bRev ? OP_Lt : OP_Gt;
+ }
+ if( 0==sqlite3ExprIsVector(pX->pRight) ){
+ disableTerm(pLevel, pEnd);
+ }
+ }
+ start = sqlite3VdbeCurrentAddr(v);
+ pLevel->op = bRev ? OP_Prev : OP_Next;
+ pLevel->p1 = iCur;
+ pLevel->p2 = start;
+ assert( pLevel->p5==0 );
+ if( testOp!=OP_Noop ){
+ iRowidReg = ++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
+ sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
+ VdbeCoverageIf(v, testOp==OP_Le);
+ VdbeCoverageIf(v, testOp==OP_Lt);
+ VdbeCoverageIf(v, testOp==OP_Ge);
+ VdbeCoverageIf(v, testOp==OP_Gt);
+ sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
+ }
+ }else if( pLoop->wsFlags & WHERE_INDEXED ){
+ /* Case 4: A scan using an index.
+ **
+ ** The WHERE clause may contain zero or more equality
+ ** terms ("==" or "IN" operators) that refer to the N
+ ** left-most columns of the index. It may also contain
+ ** inequality constraints (>, <, >= or <=) on the indexed
+ ** column that immediately follows the N equalities. Only
+ ** the right-most column can be an inequality - the rest must
+ ** use the "==" and "IN" operators. For example, if the
+ ** index is on (x,y,z), then the following clauses are all
+ ** optimized:
+ **
+ ** x=5
+ ** x=5 AND y=10
+ ** x=5 AND y<10
+ ** x=5 AND y>5 AND y<10
+ ** x=5 AND y=5 AND z<=10
+ **
+ ** The z<10 term of the following cannot be used, only
+ ** the x=5 term:
+ **
+ ** x=5 AND z<10
+ **
+ ** N may be zero if there are inequality constraints.
+ ** If there are no inequality constraints, then N is at
+ ** least one.
+ **
+ ** This case is also used when there are no WHERE clause
+ ** constraints but an index is selected anyway, in order
+ ** to force the output order to conform to an ORDER BY.
+ */
+ static const u8 aStartOp[] = {
+ 0,
+ 0,
+ OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
+ OP_Last, /* 3: (!start_constraints && startEq && bRev) */
+ OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
+ OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
+ OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
+ OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
+ };
+ static const u8 aEndOp[] = {
+ OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
+ OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
+ OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
+ OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
+ };
+ u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
+ u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
+ u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
+ int regBase; /* Base register holding constraint values */
+ WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
+ WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
+ int startEq; /* True if range start uses ==, >= or <= */
+ int endEq; /* True if range end uses ==, >= or <= */
+ int start_constraints; /* Start of range is constrained */
+ int nConstraint; /* Number of constraint terms */
+ int iIdxCur; /* The VDBE cursor for the index */
+ int nExtraReg = 0; /* Number of extra registers needed */
+ int op; /* Instruction opcode */
+ char *zStartAff; /* Affinity for start of range constraint */
+ char *zEndAff = 0; /* Affinity for end of range constraint */
+ u8 bSeekPastNull = 0; /* True to seek past initial nulls */
+ u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
+ int omitTable; /* True if we use the index only */
+ int regBignull = 0; /* big-null flag register */
+ int addrSeekScan = 0; /* Opcode of the OP_SeekScan, if any */
+
+ pIdx = pLoop->u.btree.pIndex;
+ iIdxCur = pLevel->iIdxCur;
+ assert( nEq>=pLoop->nSkip );
+
+ /* Find any inequality constraint terms for the start and end
+ ** of the range.
+ */
+ j = nEq;
+ if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
+ pRangeStart = pLoop->aLTerm[j++];
+ nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
+ /* Like optimization range constraints always occur in pairs */
+ assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
+ (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
+ }
+ if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
+ pRangeEnd = pLoop->aLTerm[j++];
+ nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
+#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
+ if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
+ assert( pRangeStart!=0 ); /* LIKE opt constraints */
+ assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
+ pLevel->iLikeRepCntr = (u32)++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
+ VdbeComment((v, "LIKE loop counter"));
+ pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
+ /* iLikeRepCntr actually stores 2x the counter register number. The
+ ** bottom bit indicates whether the search order is ASC or DESC. */
+ testcase( bRev );
+ testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
+ assert( (bRev & ~1)==0 );
+ pLevel->iLikeRepCntr <<=1;
+ pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
+ }
+#endif
+ if( pRangeStart==0 ){
+ j = pIdx->aiColumn[nEq];
+ if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
+ bSeekPastNull = 1;
+ }
+ }
+ }
+ assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
+
+ /* If the WHERE_BIGNULL_SORT flag is set, then index column nEq uses
+ ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS
+ ** FIRST). In both cases separate ordered scans are made of those
+ ** index entries for which the column is null and for those for which
+ ** it is not. For an ASC sort, the non-NULL entries are scanned first.
+ ** For DESC, NULL entries are scanned first.
+ */
+ if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0
+ && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0
+ ){
+ assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 );
+ assert( pRangeEnd==0 && pRangeStart==0 );
+ testcase( pLoop->nSkip>0 );
+ nExtraReg = 1;
+ bSeekPastNull = 1;
+ pLevel->regBignull = regBignull = ++pParse->nMem;
+ if( pLevel->iLeftJoin ){
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, regBignull);
+ }
+ pLevel->addrBignull = sqlite3VdbeMakeLabel(pParse);
+ }
+
+ /* If we are doing a reverse order scan on an ascending index, or
+ ** a forward order scan on a descending index, interchange the
+ ** start and end terms (pRangeStart and pRangeEnd).
+ */
+ if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
+ || (bRev && pIdx->nKeyCol==nEq)
+ ){
+ SWAP(WhereTerm *, pRangeEnd, pRangeStart);
+ SWAP(u8, bSeekPastNull, bStopAtNull);
+ SWAP(u8, nBtm, nTop);
+ }
+
+ /* Generate code to evaluate all constraint terms using == or IN
+ ** and store the values of those terms in an array of registers
+ ** starting at regBase.
+ */
+ codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
+ regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
+ assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
+ if( zStartAff && nTop ){
+ zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
+ }
+ addrNxt = (regBignull ? pLevel->addrBignull : pLevel->addrNxt);
+
+ testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
+ testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
+ testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
+ testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
+ startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
+ endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
+ start_constraints = pRangeStart || nEq>0;
+
+ /* Seek the index cursor to the start of the range. */
+ nConstraint = nEq;
+ if( pRangeStart ){
+ Expr *pRight = pRangeStart->pExpr->pRight;
+ codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
+ whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
+ if( (pRangeStart->wtFlags & TERM_VNULL)==0
+ && sqlite3ExprCanBeNull(pRight)
+ ){
+ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
+ VdbeCoverage(v);
+ }
+ if( zStartAff ){
+ updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
+ }
+ nConstraint += nBtm;
+ testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
+ if( sqlite3ExprIsVector(pRight)==0 ){
+ disableTerm(pLevel, pRangeStart);
+ }else{
+ startEq = 1;
+ }
+ bSeekPastNull = 0;
+ }else if( bSeekPastNull ){
+ startEq = 0;
+ sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
+ start_constraints = 1;
+ nConstraint++;
+ }else if( regBignull ){
+ sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
+ start_constraints = 1;
+ nConstraint++;
+ }
+ codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
+ if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
+ /* The skip-scan logic inside the call to codeAllEqualityConstraints()
+ ** above has already left the cursor sitting on the correct row,
+ ** so no further seeking is needed */
+ }else{
+ if( regBignull ){
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull);
+ VdbeComment((v, "NULL-scan pass ctr"));
+ }
+
+ op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
+ assert( op!=0 );
+ if( (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 && op==OP_SeekGE ){
+ assert( regBignull==0 );
+ /* TUNING: The OP_SeekScan opcode seeks to reduce the number
+ ** of expensive seek operations by replacing a single seek with
+ ** 1 or more step operations. The question is, how many steps
+ ** should we try before giving up and going with a seek. The cost
+ ** of a seek is proportional to the logarithm of the of the number
+ ** of entries in the tree, so basing the number of steps to try
+ ** on the estimated number of rows in the btree seems like a good
+ ** guess. */
+ addrSeekScan = sqlite3VdbeAddOp1(v, OP_SeekScan,
+ (pIdx->aiRowLogEst[0]+9)/10);
+ VdbeCoverage(v);
+ }
+ sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
+ VdbeCoverage(v);
+ VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
+ VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
+ VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
+ VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
+ VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
+ VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
+
+ assert( bSeekPastNull==0 || bStopAtNull==0 );
+ if( regBignull ){
+ assert( bSeekPastNull==1 || bStopAtNull==1 );
+ assert( bSeekPastNull==!bStopAtNull );
+ assert( bStopAtNull==startEq );
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2);
+ op = aStartOp[(nConstraint>1)*4 + 2 + bRev];
+ sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase,
+ nConstraint-startEq);
+ VdbeCoverage(v);
+ VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
+ VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
+ VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
+ VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
+ assert( op==OP_Rewind || op==OP_Last || op==OP_SeekGE || op==OP_SeekLE);
+ }
+ }
+
+ /* Load the value for the inequality constraint at the end of the
+ ** range (if any).
+ */
+ nConstraint = nEq;
+ if( pRangeEnd ){
+ Expr *pRight = pRangeEnd->pExpr->pRight;
+ codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
+ whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
+ if( (pRangeEnd->wtFlags & TERM_VNULL)==0
+ && sqlite3ExprCanBeNull(pRight)
+ ){
+ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
+ VdbeCoverage(v);
+ }
+ if( zEndAff ){
+ updateRangeAffinityStr(pRight, nTop, zEndAff);
+ codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
+ }else{
+ assert( pParse->db->mallocFailed );
+ }
+ nConstraint += nTop;
+ testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
+
+ if( sqlite3ExprIsVector(pRight)==0 ){
+ disableTerm(pLevel, pRangeEnd);
+ }else{
+ endEq = 1;
+ }
+ }else if( bStopAtNull ){
+ if( regBignull==0 ){
+ sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
+ endEq = 0;
+ }
+ nConstraint++;
+ }
+ sqlite3DbFree(db, zStartAff);
+ sqlite3DbFree(db, zEndAff);
+
+ /* Top of the loop body */
+ pLevel->p2 = sqlite3VdbeCurrentAddr(v);
+
+ /* Check if the index cursor is past the end of the range. */
+ if( nConstraint ){
+ if( regBignull ){
+ /* Except, skip the end-of-range check while doing the NULL-scan */
+ sqlite3VdbeAddOp2(v, OP_IfNot, regBignull, sqlite3VdbeCurrentAddr(v)+3);
+ VdbeComment((v, "If NULL-scan 2nd pass"));
+ VdbeCoverage(v);
+ }
+ op = aEndOp[bRev*2 + endEq];
+ sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
+ testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
+ testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
+ testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
+ testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
+ if( addrSeekScan ) sqlite3VdbeJumpHere(v, addrSeekScan);
+ }
+ if( regBignull ){
+ /* During a NULL-scan, check to see if we have reached the end of
+ ** the NULLs */
+ assert( bSeekPastNull==!bStopAtNull );
+ assert( bSeekPastNull+bStopAtNull==1 );
+ assert( nConstraint+bSeekPastNull>0 );
+ sqlite3VdbeAddOp2(v, OP_If, regBignull, sqlite3VdbeCurrentAddr(v)+2);
+ VdbeComment((v, "If NULL-scan 1st pass"));
+ VdbeCoverage(v);
+ op = aEndOp[bRev*2 + bSeekPastNull];
+ sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase,
+ nConstraint+bSeekPastNull);
+ testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
+ testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
+ testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
+ testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
+ }
+
+ if( (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0 ){
+ sqlite3VdbeAddOp3(v, OP_SeekHit, iIdxCur, nEq, nEq);
+ }
+
+ /* Seek the table cursor, if required */
+ omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
+ && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
+ if( omitTable ){
+ /* pIdx is a covering index. No need to access the main table. */
+ }else if( HasRowid(pIdx->pTable) ){
+ codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
+ }else if( iCur!=iIdxCur ){
+ Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
+ iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
+ for(j=0; j<pPk->nKeyCol; j++){
+ k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
+ sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
+ }
+ sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
+ iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
+ }
+
+ if( pLevel->iLeftJoin==0 ){
+ /* If pIdx is an index on one or more expressions, then look through
+ ** all the expressions in pWInfo and try to transform matching expressions
+ ** into reference to index columns. Also attempt to translate references
+ ** to virtual columns in the table into references to (stored) columns
+ ** of the index.
+ **
+ ** Do not do this for the RHS of a LEFT JOIN. This is because the
+ ** expression may be evaluated after OP_NullRow has been executed on
+ ** the cursor. In this case it is important to do the full evaluation,
+ ** as the result of the expression may not be NULL, even if all table
+ ** column values are. https://www.sqlite.org/src/info/7fa8049685b50b5a
+ **
+ ** Also, do not do this when processing one index an a multi-index
+ ** OR clause, since the transformation will become invalid once we
+ ** move forward to the next index.
+ ** https://sqlite.org/src/info/4e8e4857d32d401f
+ */
+ if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
+ whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
+ }
+
+ /* If a partial index is driving the loop, try to eliminate WHERE clause
+ ** terms from the query that must be true due to the WHERE clause of
+ ** the partial index.
+ **
+ ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work
+ ** for a LEFT JOIN.
+ */
+ if( pIdx->pPartIdxWhere ){
+ whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC);
+ }
+ }else{
+ testcase( pIdx->pPartIdxWhere );
+ /* The following assert() is not a requirement, merely an observation:
+ ** The OR-optimization doesn't work for the right hand table of
+ ** a LEFT JOIN: */
+ assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 );
+ }
+
+ /* Record the instruction used to terminate the loop. */
+ if( pLoop->wsFlags & WHERE_ONEROW ){
+ pLevel->op = OP_Noop;
+ }else if( bRev ){
+ pLevel->op = OP_Prev;
+ }else{
+ pLevel->op = OP_Next;
+ }
+ pLevel->p1 = iIdxCur;
+ pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
+ if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
+ pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
+ }else{
+ assert( pLevel->p5==0 );
+ }
+ if( omitTable ) pIdx = 0;
+ }else
+
+#ifndef SQLITE_OMIT_OR_OPTIMIZATION
+ if( pLoop->wsFlags & WHERE_MULTI_OR ){
+ /* Case 5: Two or more separately indexed terms connected by OR
+ **
+ ** Example:
+ **
+ ** CREATE TABLE t1(a,b,c,d);
+ ** CREATE INDEX i1 ON t1(a);
+ ** CREATE INDEX i2 ON t1(b);
+ ** CREATE INDEX i3 ON t1(c);
+ **
+ ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
+ **
+ ** In the example, there are three indexed terms connected by OR.
+ ** The top of the loop looks like this:
+ **
+ ** Null 1 # Zero the rowset in reg 1
+ **
+ ** Then, for each indexed term, the following. The arguments to
+ ** RowSetTest are such that the rowid of the current row is inserted
+ ** into the RowSet. If it is already present, control skips the
+ ** Gosub opcode and jumps straight to the code generated by WhereEnd().
+ **
+ ** sqlite3WhereBegin(<term>)
+ ** RowSetTest # Insert rowid into rowset
+ ** Gosub 2 A
+ ** sqlite3WhereEnd()
+ **
+ ** Following the above, code to terminate the loop. Label A, the target
+ ** of the Gosub above, jumps to the instruction right after the Goto.
+ **
+ ** Null 1 # Zero the rowset in reg 1
+ ** Goto B # The loop is finished.
+ **
+ ** A: <loop body> # Return data, whatever.
+ **
+ ** Return 2 # Jump back to the Gosub
+ **
+ ** B: <after the loop>
+ **
+ ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
+ ** use an ephemeral index instead of a RowSet to record the primary
+ ** keys of the rows we have already seen.
+ **
+ */
+ WhereClause *pOrWc; /* The OR-clause broken out into subterms */
+ SrcList *pOrTab; /* Shortened table list or OR-clause generation */
+ Index *pCov = 0; /* Potential covering index (or NULL) */
+ int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
+
+ int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
+ int regRowset = 0; /* Register for RowSet object */
+ int regRowid = 0; /* Register holding rowid */
+ int iLoopBody = sqlite3VdbeMakeLabel(pParse);/* Start of loop body */
+ int iRetInit; /* Address of regReturn init */
+ int untestedTerms = 0; /* Some terms not completely tested */
+ int ii; /* Loop counter */
+ Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
+ Table *pTab = pTabItem->pTab;
+
+ pTerm = pLoop->aLTerm[0];
+ assert( pTerm!=0 );
+ assert( pTerm->eOperator & WO_OR );
+ assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
+ pOrWc = &pTerm->u.pOrInfo->wc;
+ pLevel->op = OP_Return;
+ pLevel->p1 = regReturn;
+
+ /* Set up a new SrcList in pOrTab containing the table being scanned
+ ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
+ ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
+ */
+ if( pWInfo->nLevel>1 ){
+ int nNotReady; /* The number of notReady tables */
+ struct SrcList_item *origSrc; /* Original list of tables */
+ nNotReady = pWInfo->nLevel - iLevel - 1;
+ pOrTab = sqlite3StackAllocRaw(db,
+ sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
+ if( pOrTab==0 ) return notReady;
+ pOrTab->nAlloc = (u8)(nNotReady + 1);
+ pOrTab->nSrc = pOrTab->nAlloc;
+ memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
+ origSrc = pWInfo->pTabList->a;
+ for(k=1; k<=nNotReady; k++){
+ memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
+ }
+ }else{
+ pOrTab = pWInfo->pTabList;
+ }
+
+ /* Initialize the rowset register to contain NULL. An SQL NULL is
+ ** equivalent to an empty rowset. Or, create an ephemeral index
+ ** capable of holding primary keys in the case of a WITHOUT ROWID.
+ **
+ ** Also initialize regReturn to contain the address of the instruction
+ ** immediately following the OP_Return at the bottom of the loop. This
+ ** is required in a few obscure LEFT JOIN cases where control jumps
+ ** over the top of the loop into the body of it. In this case the
+ ** correct response for the end-of-loop code (the OP_Return) is to
+ ** fall through to the next instruction, just as an OP_Next does if
+ ** called on an uninitialized cursor.
+ */
+ if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
+ if( HasRowid(pTab) ){
+ regRowset = ++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
+ }else{
+ Index *pPk = sqlite3PrimaryKeyIndex(pTab);
+ regRowset = pParse->nTab++;
+ sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
+ sqlite3VdbeSetP4KeyInfo(pParse, pPk);
+ }
+ regRowid = ++pParse->nMem;
+ }
+ iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
+
+ /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
+ ** Then for every term xN, evaluate as the subexpression: xN AND z
+ ** That way, terms in y that are factored into the disjunction will
+ ** be picked up by the recursive calls to sqlite3WhereBegin() below.
+ **
+ ** Actually, each subexpression is converted to "xN AND w" where w is
+ ** the "interesting" terms of z - terms that did not originate in the
+ ** ON or USING clause of a LEFT JOIN, and terms that are usable as
+ ** indices.
+ **
+ ** This optimization also only applies if the (x1 OR x2 OR ...) term
+ ** is not contained in the ON clause of a LEFT JOIN.
+ ** See ticket http://www.sqlite.org/src/info/f2369304e4
+ */
+ if( pWC->nTerm>1 ){
+ int iTerm;
+ for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
+ Expr *pExpr = pWC->a[iTerm].pExpr;
+ if( &pWC->a[iTerm] == pTerm ) continue;
+ testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
+ testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
+ if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
+ if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
+ testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
+ pExpr = sqlite3ExprDup(db, pExpr, 0);
+ pAndExpr = sqlite3ExprAnd(pParse, pAndExpr, pExpr);
+ }
+ if( pAndExpr ){
+ /* The extra 0x10000 bit on the opcode is masked off and does not
+ ** become part of the new Expr.op. However, it does make the
+ ** op==TK_AND comparison inside of sqlite3PExpr() false, and this
+ ** prevents sqlite3PExpr() from implementing AND short-circuit
+ ** optimization, which we do not want here. */
+ pAndExpr = sqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr);
+ }
+ }
+
+ /* Run a separate WHERE clause for each term of the OR clause. After
+ ** eliminating duplicates from other WHERE clauses, the action for each
+ ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
+ */
+ ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR"));
+ for(ii=0; ii<pOrWc->nTerm; ii++){
+ WhereTerm *pOrTerm = &pOrWc->a[ii];
+ if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
+ WhereInfo *pSubWInfo; /* Info for single OR-term scan */
+ Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
+ int jmp1 = 0; /* Address of jump operation */
+ testcase( (pTabItem[0].fg.jointype & JT_LEFT)!=0
+ && !ExprHasProperty(pOrExpr, EP_FromJoin)
+ ); /* See TH3 vtab25.400 and ticket 614b25314c766238 */
+ if( pAndExpr ){
+ pAndExpr->pLeft = pOrExpr;
+ pOrExpr = pAndExpr;
+ }
+ /* Loop through table entries that match term pOrTerm. */
+ ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1));
+ WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
+ pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
+ WHERE_OR_SUBCLAUSE, iCovCur);
+ assert( pSubWInfo || pParse->nErr || db->mallocFailed );
+ if( pSubWInfo ){
+ WhereLoop *pSubLoop;
+ int addrExplain = sqlite3WhereExplainOneScan(
+ pParse, pOrTab, &pSubWInfo->a[0], 0
+ );
+ sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
+
+ /* This is the sub-WHERE clause body. First skip over
+ ** duplicate rows from prior sub-WHERE clauses, and record the
+ ** rowid (or PRIMARY KEY) for the current row so that the same
+ ** row will be skipped in subsequent sub-WHERE clauses.
+ */
+ if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
+ int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
+ if( HasRowid(pTab) ){
+ sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid);
+ jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
+ regRowid, iSet);
+ VdbeCoverage(v);
+ }else{
+ Index *pPk = sqlite3PrimaryKeyIndex(pTab);
+ int nPk = pPk->nKeyCol;
+ int iPk;
+ int r;
+
+ /* Read the PK into an array of temp registers. */
+ r = sqlite3GetTempRange(pParse, nPk);
+ for(iPk=0; iPk<nPk; iPk++){
+ int iCol = pPk->aiColumn[iPk];
+ sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk);
+ }
+
+ /* Check if the temp table already contains this key. If so,
+ ** the row has already been included in the result set and
+ ** can be ignored (by jumping past the Gosub below). Otherwise,
+ ** insert the key into the temp table and proceed with processing
+ ** the row.
+ **
+ ** Use some of the same optimizations as OP_RowSetTest: If iSet
+ ** is zero, assume that the key cannot already be present in
+ ** the temp table. And if iSet is -1, assume that there is no
+ ** need to insert the key into the temp table, as it will never
+ ** be tested for. */
+ if( iSet ){
+ jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
+ VdbeCoverage(v);
+ }
+ if( iSet>=0 ){
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
+ r, nPk);
+ if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
+ }
+
+ /* Release the array of temp registers */
+ sqlite3ReleaseTempRange(pParse, r, nPk);
+ }
+ }
+
+ /* Invoke the main loop body as a subroutine */
+ sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
+
+ /* Jump here (skipping the main loop body subroutine) if the
+ ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
+ if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
+
+ /* The pSubWInfo->untestedTerms flag means that this OR term
+ ** contained one or more AND term from a notReady table. The
+ ** terms from the notReady table could not be tested and will
+ ** need to be tested later.
+ */
+ if( pSubWInfo->untestedTerms ) untestedTerms = 1;
+
+ /* If all of the OR-connected terms are optimized using the same
+ ** index, and the index is opened using the same cursor number
+ ** by each call to sqlite3WhereBegin() made by this loop, it may
+ ** be possible to use that index as a covering index.
+ **
+ ** If the call to sqlite3WhereBegin() above resulted in a scan that
+ ** uses an index, and this is either the first OR-connected term
+ ** processed or the index is the same as that used by all previous
+ ** terms, set pCov to the candidate covering index. Otherwise, set
+ ** pCov to NULL to indicate that no candidate covering index will
+ ** be available.
+ */
+ pSubLoop = pSubWInfo->a[0].pWLoop;
+ assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
+ if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
+ && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
+ && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
+ ){
+ assert( pSubWInfo->a[0].iIdxCur==iCovCur );
+ pCov = pSubLoop->u.btree.pIndex;
+ }else{
+ pCov = 0;
+ }
+ if( sqlite3WhereUsesDeferredSeek(pSubWInfo) ){
+ pWInfo->bDeferredSeek = 1;
+ }
+
+ /* Finish the loop through table entries that match term pOrTerm. */
+ sqlite3WhereEnd(pSubWInfo);
+ ExplainQueryPlanPop(pParse);
+ }
+ }
+ }
+ ExplainQueryPlanPop(pParse);
+ pLevel->u.pCovidx = pCov;
+ if( pCov ) pLevel->iIdxCur = iCovCur;
+ if( pAndExpr ){
+ pAndExpr->pLeft = 0;
+ sqlite3ExprDelete(db, pAndExpr);
+ }
+ sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
+ sqlite3VdbeGoto(v, pLevel->addrBrk);
+ sqlite3VdbeResolveLabel(v, iLoopBody);
+
+ if( pWInfo->nLevel>1 ){ sqlite3StackFree(db, pOrTab); }
+ if( !untestedTerms ) disableTerm(pLevel, pTerm);
+ }else
+#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
+
+ {
+ /* Case 6: There is no usable index. We must do a complete
+ ** scan of the entire table.
+ */
+ static const u8 aStep[] = { OP_Next, OP_Prev };
+ static const u8 aStart[] = { OP_Rewind, OP_Last };
+ assert( bRev==0 || bRev==1 );
+ if( pTabItem->fg.isRecursive ){
+ /* Tables marked isRecursive have only a single row that is stored in
+ ** a pseudo-cursor. No need to Rewind or Next such cursors. */
+ pLevel->op = OP_Noop;
+ }else{
+ codeCursorHint(pTabItem, pWInfo, pLevel, 0);
+ pLevel->op = aStep[bRev];
+ pLevel->p1 = iCur;
+ pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
+ VdbeCoverageIf(v, bRev==0);
+ VdbeCoverageIf(v, bRev!=0);
+ pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
+ }
+ }
+
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+ pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
+#endif
+
+ /* Insert code to test every subexpression that can be completely
+ ** computed using the current set of tables.
+ **
+ ** This loop may run between one and three times, depending on the
+ ** constraints to be generated. The value of stack variable iLoop
+ ** determines the constraints coded by each iteration, as follows:
+ **
+ ** iLoop==1: Code only expressions that are entirely covered by pIdx.
+ ** iLoop==2: Code remaining expressions that do not contain correlated
+ ** sub-queries.
+ ** iLoop==3: Code all remaining expressions.
+ **
+ ** An effort is made to skip unnecessary iterations of the loop.
+ */
+ iLoop = (pIdx ? 1 : 2);
+ do{
+ int iNext = 0; /* Next value for iLoop */
+ for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
+ Expr *pE;
+ int skipLikeAddr = 0;
+ testcase( pTerm->wtFlags & TERM_VIRTUAL );
+ testcase( pTerm->wtFlags & TERM_CODED );
+ if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
+ if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
+ testcase( pWInfo->untestedTerms==0
+ && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
+ pWInfo->untestedTerms = 1;
+ continue;
+ }
+ pE = pTerm->pExpr;
+ assert( pE!=0 );
+ if( (pTabItem->fg.jointype&JT_LEFT) && !ExprHasProperty(pE,EP_FromJoin) ){
+ continue;
+ }
+
+ if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
+ iNext = 2;
+ continue;
+ }
+ if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
+ if( iNext==0 ) iNext = 3;
+ continue;
+ }
+
+ if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){
+ /* If the TERM_LIKECOND flag is set, that means that the range search
+ ** is sufficient to guarantee that the LIKE operator is true, so we
+ ** can skip the call to the like(A,B) function. But this only works
+ ** for strings. So do not skip the call to the function on the pass
+ ** that compares BLOBs. */
+#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
+ continue;
+#else
+ u32 x = pLevel->iLikeRepCntr;
+ if( x>0 ){
+ skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1));
+ VdbeCoverageIf(v, (x&1)==1);
+ VdbeCoverageIf(v, (x&1)==0);
+ }
+#endif
+ }
+#ifdef WHERETRACE_ENABLED /* 0xffff */
+ if( sqlite3WhereTrace ){
+ VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
+ pWC->nTerm-j, pTerm, iLoop));
+ }
+ if( sqlite3WhereTrace & 0x800 ){
+ sqlite3DebugPrintf("Coding auxiliary constraint:\n");
+ sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
+ }
+#endif
+ sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
+ if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
+ pTerm->wtFlags |= TERM_CODED;
+ }
+ iLoop = iNext;
+ }while( iLoop>0 );
+
+ /* Insert code to test for implied constraints based on transitivity
+ ** of the "==" operator.
+ **
+ ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
+ ** and we are coding the t1 loop and the t2 loop has not yet coded,
+ ** then we cannot use the "t1.a=t2.b" constraint, but we can code
+ ** the implied "t1.a=123" constraint.
+ */
+ for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
+ Expr *pE, sEAlt;
+ WhereTerm *pAlt;
+ if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
+ if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
+ if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
+ if( pTerm->leftCursor!=iCur ) continue;
+ if( pTabItem->fg.jointype & JT_LEFT ) continue;
+ pE = pTerm->pExpr;
+#ifdef WHERETRACE_ENABLED /* 0x800 */
+ if( sqlite3WhereTrace & 0x800 ){
+ sqlite3DebugPrintf("Coding transitive constraint:\n");
+ sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
+ }
+#endif
+ assert( !ExprHasProperty(pE, EP_FromJoin) );
+ assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
+ pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.x.leftColumn, notReady,
+ WO_EQ|WO_IN|WO_IS, 0);
+ if( pAlt==0 ) continue;
+ if( pAlt->wtFlags & (TERM_CODED) ) continue;
+ if( (pAlt->eOperator & WO_IN)
+ && (pAlt->pExpr->flags & EP_xIsSelect)
+ && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
+ ){
+ continue;
+ }
+ testcase( pAlt->eOperator & WO_EQ );
+ testcase( pAlt->eOperator & WO_IS );
+ testcase( pAlt->eOperator & WO_IN );
+ VdbeModuleComment((v, "begin transitive constraint"));
+ sEAlt = *pAlt->pExpr;
+ sEAlt.pLeft = pE->pLeft;
+ sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
+ }
+
+ /* For a LEFT OUTER JOIN, generate code that will record the fact that
+ ** at least one row of the right table has matched the left table.
+ */
+ if( pLevel->iLeftJoin ){
+ pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
+ VdbeComment((v, "record LEFT JOIN hit"));
+ for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
+ testcase( pTerm->wtFlags & TERM_VIRTUAL );
+ testcase( pTerm->wtFlags & TERM_CODED );
+ if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
+ if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
+ assert( pWInfo->untestedTerms );
+ continue;
+ }
+ assert( pTerm->pExpr );
+ sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
+ pTerm->wtFlags |= TERM_CODED;
+ }
+ }
+
+#if WHERETRACE_ENABLED /* 0x20800 */
+ if( sqlite3WhereTrace & 0x20000 ){
+ sqlite3DebugPrintf("All WHERE-clause terms after coding level %d:\n",
+ iLevel);
+ sqlite3WhereClausePrint(pWC);
+ }
+ if( sqlite3WhereTrace & 0x800 ){
+ sqlite3DebugPrintf("End Coding level %d: notReady=%llx\n",
+ iLevel, (u64)pLevel->notReady);
+ }
+#endif
+ return pLevel->notReady;
+}
+
+/************** End of wherecode.c *******************************************/
+/************** Begin file whereexpr.c ***************************************/
+/*
+** 2015-06-08
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This module contains C code that generates VDBE code used to process
+** the WHERE clause of SQL statements.
+**
+** This file was originally part of where.c but was split out to improve
+** readability and editabiliity. This file contains utility routines for
+** analyzing Expr objects in the WHERE clause.
+*/
+/* #include "sqliteInt.h" */
+/* #include "whereInt.h" */
+
+/* Forward declarations */
+static void exprAnalyze(SrcList*, WhereClause*, int);
+
+/*
+** Deallocate all memory associated with a WhereOrInfo object.
+*/
+static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
+ sqlite3WhereClauseClear(&p->wc);
+ sqlite3DbFree(db, p);
+}
+
+/*
+** Deallocate all memory associated with a WhereAndInfo object.
+*/
+static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
+ sqlite3WhereClauseClear(&p->wc);
+ sqlite3DbFree(db, p);
+}
+
+/*
+** Add a single new WhereTerm entry to the WhereClause object pWC.
+** The new WhereTerm object is constructed from Expr p and with wtFlags.
+** The index in pWC->a[] of the new WhereTerm is returned on success.
+** 0 is returned if the new WhereTerm could not be added due to a memory
+** allocation error. The memory allocation failure will be recorded in
+** the db->mallocFailed flag so that higher-level functions can detect it.
+**
+** This routine will increase the size of the pWC->a[] array as necessary.
+**
+** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
+** for freeing the expression p is assumed by the WhereClause object pWC.
+** This is true even if this routine fails to allocate a new WhereTerm.
+**
+** WARNING: This routine might reallocate the space used to store
+** WhereTerms. All pointers to WhereTerms should be invalidated after
+** calling this routine. Such pointers may be reinitialized by referencing
+** the pWC->a[] array.
+*/
+static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
+ WhereTerm *pTerm;
+ int idx;
+ testcase( wtFlags & TERM_VIRTUAL );
+ if( pWC->nTerm>=pWC->nSlot ){
+ WhereTerm *pOld = pWC->a;
+ sqlite3 *db = pWC->pWInfo->pParse->db;
+ pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
+ if( pWC->a==0 ){
+ if( wtFlags & TERM_DYNAMIC ){
+ sqlite3ExprDelete(db, p);
+ }
+ pWC->a = pOld;
+ return 0;
+ }
+ memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
+ if( pOld!=pWC->aStatic ){
+ sqlite3DbFree(db, pOld);
+ }
+ pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
+ }
+ pTerm = &pWC->a[idx = pWC->nTerm++];
+ if( p && ExprHasProperty(p, EP_Unlikely) ){
+ pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
+ }else{
+ pTerm->truthProb = 1;
+ }
+ pTerm->pExpr = sqlite3ExprSkipCollateAndLikely(p);
+ pTerm->wtFlags = wtFlags;
+ pTerm->pWC = pWC;
+ pTerm->iParent = -1;
+ memset(&pTerm->eOperator, 0,
+ sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
+ return idx;
+}
+
+/*
+** Return TRUE if the given operator is one of the operators that is
+** allowed for an indexable WHERE clause term. The allowed operators are
+** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
+*/
+static int allowedOp(int op){
+ assert( TK_GT>TK_EQ && TK_GT<TK_GE );
+ assert( TK_LT>TK_EQ && TK_LT<TK_GE );
+ assert( TK_LE>TK_EQ && TK_LE<TK_GE );
+ assert( TK_GE==TK_EQ+4 );
+ return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
+}
+
+/*
+** Commute a comparison operator. Expressions of the form "X op Y"
+** are converted into "Y op X".
+*/
+static u16 exprCommute(Parse *pParse, Expr *pExpr){
+ if( pExpr->pLeft->op==TK_VECTOR
+ || pExpr->pRight->op==TK_VECTOR
+ || sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight) !=
+ sqlite3BinaryCompareCollSeq(pParse, pExpr->pRight, pExpr->pLeft)
+ ){
+ pExpr->flags ^= EP_Commuted;
+ }
+ SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
+ if( pExpr->op>=TK_GT ){
+ assert( TK_LT==TK_GT+2 );
+ assert( TK_GE==TK_LE+2 );
+ assert( TK_GT>TK_EQ );
+ assert( TK_GT<TK_LE );
+ assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
+ pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
+ }
+ return 0;
+}
+
+/*
+** Translate from TK_xx operator to WO_xx bitmask.
+*/
+static u16 operatorMask(int op){
+ u16 c;
+ assert( allowedOp(op) );
+ if( op==TK_IN ){
+ c = WO_IN;
+ }else if( op==TK_ISNULL ){
+ c = WO_ISNULL;
+ }else if( op==TK_IS ){
+ c = WO_IS;
+ }else{
+ assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
+ c = (u16)(WO_EQ<<(op-TK_EQ));
+ }
+ assert( op!=TK_ISNULL || c==WO_ISNULL );
+ assert( op!=TK_IN || c==WO_IN );
+ assert( op!=TK_EQ || c==WO_EQ );
+ assert( op!=TK_LT || c==WO_LT );
+ assert( op!=TK_LE || c==WO_LE );
+ assert( op!=TK_GT || c==WO_GT );
+ assert( op!=TK_GE || c==WO_GE );
+ assert( op!=TK_IS || c==WO_IS );
+ return c;
+}
+
+
+#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
+/*
+** Check to see if the given expression is a LIKE or GLOB operator that
+** can be optimized using inequality constraints. Return TRUE if it is
+** so and false if not.
+**
+** In order for the operator to be optimizible, the RHS must be a string
+** literal that does not begin with a wildcard. The LHS must be a column
+** that may only be NULL, a string, or a BLOB, never a number. (This means
+** that virtual tables cannot participate in the LIKE optimization.) The
+** collating sequence for the column on the LHS must be appropriate for
+** the operator.
+*/
+static int isLikeOrGlob(
+ Parse *pParse, /* Parsing and code generating context */
+ Expr *pExpr, /* Test this expression */
+ Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
+ int *pisComplete, /* True if the only wildcard is % in the last character */
+ int *pnoCase /* True if uppercase is equivalent to lowercase */
+){
+ const u8 *z = 0; /* String on RHS of LIKE operator */
+ Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
+ ExprList *pList; /* List of operands to the LIKE operator */
+ u8 c; /* One character in z[] */
+ int cnt; /* Number of non-wildcard prefix characters */
+ u8 wc[4]; /* Wildcard characters */
+ sqlite3 *db = pParse->db; /* Database connection */
+ sqlite3_value *pVal = 0;
+ int op; /* Opcode of pRight */
+ int rc; /* Result code to return */
+
+ if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){
+ return 0;
+ }
+#ifdef SQLITE_EBCDIC
+ if( *pnoCase ) return 0;
+#endif
+ pList = pExpr->x.pList;
+ pLeft = pList->a[1].pExpr;
+
+ pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
+ op = pRight->op;
+ if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
+ Vdbe *pReprepare = pParse->pReprepare;
+ int iCol = pRight->iColumn;
+ pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
+ if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
+ z = sqlite3_value_text(pVal);
+ }
+ sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
+ assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
+ }else if( op==TK_STRING ){
+ z = (u8*)pRight->u.zToken;
+ }
+ if( z ){
+
+ /* Count the number of prefix characters prior to the first wildcard */
+ cnt = 0;
+ while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
+ cnt++;
+ if( c==wc[3] && z[cnt]!=0 ) cnt++;
+ }
+
+ /* The optimization is possible only if (1) the pattern does not begin
+ ** with a wildcard and if (2) the non-wildcard prefix does not end with
+ ** an (illegal 0xff) character, or (3) the pattern does not consist of
+ ** a single escape character. The second condition is necessary so
+ ** that we can increment the prefix key to find an upper bound for the
+ ** range search. The third is because the caller assumes that the pattern
+ ** consists of at least one character after all escapes have been
+ ** removed. */
+ if( cnt!=0 && 255!=(u8)z[cnt-1] && (cnt>1 || z[0]!=wc[3]) ){
+ Expr *pPrefix;
+
+ /* A "complete" match if the pattern ends with "*" or "%" */
+ *pisComplete = c==wc[0] && z[cnt+1]==0;
+
+ /* Get the pattern prefix. Remove all escapes from the prefix. */
+ pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
+ if( pPrefix ){
+ int iFrom, iTo;
+ char *zNew = pPrefix->u.zToken;
+ zNew[cnt] = 0;
+ for(iFrom=iTo=0; iFrom<cnt; iFrom++){
+ if( zNew[iFrom]==wc[3] ) iFrom++;
+ zNew[iTo++] = zNew[iFrom];
+ }
+ zNew[iTo] = 0;
+ assert( iTo>0 );
+
+ /* If the LHS is not an ordinary column with TEXT affinity, then the
+ ** pattern prefix boundaries (both the start and end boundaries) must
+ ** not look like a number. Otherwise the pattern might be treated as
+ ** a number, which will invalidate the LIKE optimization.
+ **
+ ** Getting this right has been a persistent source of bugs in the
+ ** LIKE optimization. See, for example:
+ ** 2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1
+ ** 2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28
+ ** 2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07
+ ** 2019-06-14 https://sqlite.org/src/info/ce8717f0885af975
+ ** 2019-09-03 https://sqlite.org/src/info/0f0428096f17252a
+ */
+ if( pLeft->op!=TK_COLUMN
+ || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
+ || IsVirtual(pLeft->y.pTab) /* Value might be numeric */
+ ){
+ int isNum;
+ double rDummy;
+ isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);
+ if( isNum<=0 ){
+ if( iTo==1 && zNew[0]=='-' ){
+ isNum = +1;
+ }else{
+ zNew[iTo-1]++;
+ isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);
+ zNew[iTo-1]--;
+ }
+ }
+ if( isNum>0 ){
+ sqlite3ExprDelete(db, pPrefix);
+ sqlite3ValueFree(pVal);
+ return 0;
+ }
+ }
+ }
+ *ppPrefix = pPrefix;
+
+ /* If the RHS pattern is a bound parameter, make arrangements to
+ ** reprepare the statement when that parameter is rebound */
+ if( op==TK_VARIABLE ){
+ Vdbe *v = pParse->pVdbe;
+ sqlite3VdbeSetVarmask(v, pRight->iColumn);
+ if( *pisComplete && pRight->u.zToken[1] ){
+ /* If the rhs of the LIKE expression is a variable, and the current
+ ** value of the variable means there is no need to invoke the LIKE
+ ** function, then no OP_Variable will be added to the program.
+ ** This causes problems for the sqlite3_bind_parameter_name()
+ ** API. To work around them, add a dummy OP_Variable here.
+ */
+ int r1 = sqlite3GetTempReg(pParse);
+ sqlite3ExprCodeTarget(pParse, pRight, r1);
+ sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
+ sqlite3ReleaseTempReg(pParse, r1);
+ }
+ }
+ }else{
+ z = 0;
+ }
+ }
+
+ rc = (z!=0);
+ sqlite3ValueFree(pVal);
+ return rc;
+}
+#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
+
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/*
+** Check to see if the pExpr expression is a form that needs to be passed
+** to the xBestIndex method of virtual tables. Forms of interest include:
+**
+** Expression Virtual Table Operator
+** ----------------------- ---------------------------------
+** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH
+** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB
+** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE
+** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP
+** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE
+** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE
+** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT
+** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT
+** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL
+**
+** In every case, "column" must be a column of a virtual table. If there
+** is a match, set *ppLeft to the "column" expression, set *ppRight to the
+** "expr" expression (even though in forms (6) and (8) the column is on the
+** right and the expression is on the left). Also set *peOp2 to the
+** appropriate virtual table operator. The return value is 1 or 2 if there
+** is a match. The usual return is 1, but if the RHS is also a column
+** of virtual table in forms (5) or (7) then return 2.
+**
+** If the expression matches none of the patterns above, return 0.
+*/
+static int isAuxiliaryVtabOperator(
+ sqlite3 *db, /* Parsing context */
+ Expr *pExpr, /* Test this expression */
+ unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */
+ Expr **ppLeft, /* Column expression to left of MATCH/op2 */
+ Expr **ppRight /* Expression to left of MATCH/op2 */
+){
+ if( pExpr->op==TK_FUNCTION ){
+ static const struct Op2 {
+ const char *zOp;
+ unsigned char eOp2;
+ } aOp[] = {
+ { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
+ { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
+ { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
+ { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
+ };
+ ExprList *pList;
+ Expr *pCol; /* Column reference */
+ int i;
+
+ pList = pExpr->x.pList;
+ if( pList==0 || pList->nExpr!=2 ){
+ return 0;
+ }
+
+ /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a
+ ** virtual table on their second argument, which is the same as
+ ** the left-hand side operand in their in-fix form.
+ **
+ ** vtab_column MATCH expression
+ ** MATCH(expression,vtab_column)
+ */
+ pCol = pList->a[1].pExpr;
+ testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 );
+ if( ExprIsVtab(pCol) ){
+ for(i=0; i<ArraySize(aOp); i++){
+ if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
+ *peOp2 = aOp[i].eOp2;
+ *ppRight = pList->a[0].pExpr;
+ *ppLeft = pCol;
+ return 1;
+ }
+ }
+ }
+
+ /* We can also match against the first column of overloaded
+ ** functions where xFindFunction returns a value of at least
+ ** SQLITE_INDEX_CONSTRAINT_FUNCTION.
+ **
+ ** OVERLOADED(vtab_column,expression)
+ **
+ ** Historically, xFindFunction expected to see lower-case function
+ ** names. But for this use case, xFindFunction is expected to deal
+ ** with function names in an arbitrary case.
+ */
+ pCol = pList->a[0].pExpr;
+ testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 );
+ if( ExprIsVtab(pCol) ){
+ sqlite3_vtab *pVtab;
+ sqlite3_module *pMod;
+ void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);
+ void *pNotUsed;
+ pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab;
+ assert( pVtab!=0 );
+ assert( pVtab->pModule!=0 );
+ pMod = (sqlite3_module *)pVtab->pModule;
+ if( pMod->xFindFunction!=0 ){
+ i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
+ if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
+ *peOp2 = i;
+ *ppRight = pList->a[1].pExpr;
+ *ppLeft = pCol;
+ return 1;
+ }
+ }
+ }
+ }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
+ int res = 0;
+ Expr *pLeft = pExpr->pLeft;
+ Expr *pRight = pExpr->pRight;
+ testcase( pLeft->op==TK_COLUMN && pLeft->y.pTab==0 );
+ if( ExprIsVtab(pLeft) ){
+ res++;
+ }
+ testcase( pRight && pRight->op==TK_COLUMN && pRight->y.pTab==0 );
+ if( pRight && ExprIsVtab(pRight) ){
+ res++;
+ SWAP(Expr*, pLeft, pRight);
+ }
+ *ppLeft = pLeft;
+ *ppRight = pRight;
+ if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
+ if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
+ if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
+ return res;
+ }
+ return 0;
+}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+/*
+** If the pBase expression originated in the ON or USING clause of
+** a join, then transfer the appropriate markings over to derived.
+*/
+static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
+ if( pDerived ){
+ pDerived->flags |= pBase->flags & EP_FromJoin;
+ pDerived->iRightJoinTable = pBase->iRightJoinTable;
+ }
+}
+
+/*
+** Mark term iChild as being a child of term iParent
+*/
+static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
+ pWC->a[iChild].iParent = iParent;
+ pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
+ pWC->a[iParent].nChild++;
+}
+
+/*
+** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
+** a conjunction, then return just pTerm when N==0. If N is exceeds
+** the number of available subterms, return NULL.
+*/
+static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
+ if( pTerm->eOperator!=WO_AND ){
+ return N==0 ? pTerm : 0;
+ }
+ if( N<pTerm->u.pAndInfo->wc.nTerm ){
+ return &pTerm->u.pAndInfo->wc.a[N];
+ }
+ return 0;
+}
+
+/*
+** Subterms pOne and pTwo are contained within WHERE clause pWC. The
+** two subterms are in disjunction - they are OR-ed together.
+**
+** If these two terms are both of the form: "A op B" with the same
+** A and B values but different operators and if the operators are
+** compatible (if one is = and the other is <, for example) then
+** add a new virtual AND term to pWC that is the combination of the
+** two.
+**
+** Some examples:
+**
+** x<y OR x=y --> x<=y
+** x=y OR x=y --> x=y
+** x<=y OR x<y --> x<=y
+**
+** The following is NOT generated:
+**
+** x<y OR x>y --> x!=y
+*/
+static void whereCombineDisjuncts(
+ SrcList *pSrc, /* the FROM clause */
+ WhereClause *pWC, /* The complete WHERE clause */
+ WhereTerm *pOne, /* First disjunct */
+ WhereTerm *pTwo /* Second disjunct */
+){
+ u16 eOp = pOne->eOperator | pTwo->eOperator;
+ sqlite3 *db; /* Database connection (for malloc) */
+ Expr *pNew; /* New virtual expression */
+ int op; /* Operator for the combined expression */
+ int idxNew; /* Index in pWC of the next virtual term */
+
+ if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
+ if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
+ if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
+ && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
+ assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
+ assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
+ if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
+ if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
+ /* If we reach this point, it means the two subterms can be combined */
+ if( (eOp & (eOp-1))!=0 ){
+ if( eOp & (WO_LT|WO_LE) ){
+ eOp = WO_LE;
+ }else{
+ assert( eOp & (WO_GT|WO_GE) );
+ eOp = WO_GE;
+ }
+ }
+ db = pWC->pWInfo->pParse->db;
+ pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
+ if( pNew==0 ) return;
+ for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
+ pNew->op = op;
+ idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
+ exprAnalyze(pSrc, pWC, idxNew);
+}
+
+#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
+/*
+** Analyze a term that consists of two or more OR-connected
+** subterms. So in:
+**
+** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
+** ^^^^^^^^^^^^^^^^^^^^
+**
+** This routine analyzes terms such as the middle term in the above example.
+** A WhereOrTerm object is computed and attached to the term under
+** analysis, regardless of the outcome of the analysis. Hence:
+**
+** WhereTerm.wtFlags |= TERM_ORINFO
+** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
+**
+** The term being analyzed must have two or more of OR-connected subterms.
+** A single subterm might be a set of AND-connected sub-subterms.
+** Examples of terms under analysis:
+**
+** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
+** (B) x=expr1 OR expr2=x OR x=expr3
+** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
+** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
+** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
+** (F) x>A OR (x=A AND y>=B)
+**
+** CASE 1:
+**
+** If all subterms are of the form T.C=expr for some single column of C and
+** a single table T (as shown in example B above) then create a new virtual
+** term that is an equivalent IN expression. In other words, if the term
+** being analyzed is:
+**
+** x = expr1 OR expr2 = x OR x = expr3
+**
+** then create a new virtual term like this:
+**
+** x IN (expr1,expr2,expr3)
+**
+** CASE 2:
+**
+** If there are exactly two disjuncts and one side has x>A and the other side
+** has x=A (for the same x and A) then add a new virtual conjunct term to the
+** WHERE clause of the form "x>=A". Example:
+**
+** x>A OR (x=A AND y>B) adds: x>=A
+**
+** The added conjunct can sometimes be helpful in query planning.
+**
+** CASE 3:
+**
+** If all subterms are indexable by a single table T, then set
+**
+** WhereTerm.eOperator = WO_OR
+** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
+**
+** A subterm is "indexable" if it is of the form
+** "T.C <op> <expr>" where C is any column of table T and
+** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
+** A subterm is also indexable if it is an AND of two or more
+** subsubterms at least one of which is indexable. Indexable AND
+** subterms have their eOperator set to WO_AND and they have
+** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
+**
+** From another point of view, "indexable" means that the subterm could
+** potentially be used with an index if an appropriate index exists.
+** This analysis does not consider whether or not the index exists; that
+** is decided elsewhere. This analysis only looks at whether subterms
+** appropriate for indexing exist.
+**
+** All examples A through E above satisfy case 3. But if a term
+** also satisfies case 1 (such as B) we know that the optimizer will
+** always prefer case 1, so in that case we pretend that case 3 is not
+** satisfied.
+**
+** It might be the case that multiple tables are indexable. For example,
+** (E) above is indexable on tables P, Q, and R.
+**
+** Terms that satisfy case 3 are candidates for lookup by using
+** separate indices to find rowids for each subterm and composing
+** the union of all rowids using a RowSet object. This is similar
+** to "bitmap indices" in other database engines.
+**
+** OTHERWISE:
+**
+** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
+** zero. This term is not useful for search.
+*/
+static void exprAnalyzeOrTerm(
+ SrcList *pSrc, /* the FROM clause */
+ WhereClause *pWC, /* the complete WHERE clause */
+ int idxTerm /* Index of the OR-term to be analyzed */
+){
+ WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
+ Parse *pParse = pWInfo->pParse; /* Parser context */
+ sqlite3 *db = pParse->db; /* Database connection */
+ WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
+ Expr *pExpr = pTerm->pExpr; /* The expression of the term */
+ int i; /* Loop counters */
+ WhereClause *pOrWc; /* Breakup of pTerm into subterms */
+ WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
+ WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
+ Bitmask chngToIN; /* Tables that might satisfy case 1 */
+ Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
+
+ /*
+ ** Break the OR clause into its separate subterms. The subterms are
+ ** stored in a WhereClause structure containing within the WhereOrInfo
+ ** object that is attached to the original OR clause term.
+ */
+ assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
+ assert( pExpr->op==TK_OR );
+ pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
+ if( pOrInfo==0 ) return;
+ pTerm->wtFlags |= TERM_ORINFO;
+ pOrWc = &pOrInfo->wc;
+ memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
+ sqlite3WhereClauseInit(pOrWc, pWInfo);
+ sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
+ sqlite3WhereExprAnalyze(pSrc, pOrWc);
+ if( db->mallocFailed ) return;
+ assert( pOrWc->nTerm>=2 );
+
+ /*
+ ** Compute the set of tables that might satisfy cases 1 or 3.
+ */
+ indexable = ~(Bitmask)0;
+ chngToIN = ~(Bitmask)0;
+ for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
+ if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
+ WhereAndInfo *pAndInfo;
+ assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
+ chngToIN = 0;
+ pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
+ if( pAndInfo ){
+ WhereClause *pAndWC;
+ WhereTerm *pAndTerm;
+ int j;
+ Bitmask b = 0;
+ pOrTerm->u.pAndInfo = pAndInfo;
+ pOrTerm->wtFlags |= TERM_ANDINFO;
+ pOrTerm->eOperator = WO_AND;
+ pAndWC = &pAndInfo->wc;
+ memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
+ sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
+ sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
+ sqlite3WhereExprAnalyze(pSrc, pAndWC);
+ pAndWC->pOuter = pWC;
+ if( !db->mallocFailed ){
+ for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
+ assert( pAndTerm->pExpr );
+ if( allowedOp(pAndTerm->pExpr->op)
+ || pAndTerm->eOperator==WO_AUX
+ ){
+ b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
+ }
+ }
+ }
+ indexable &= b;
+ }
+ }else if( pOrTerm->wtFlags & TERM_COPIED ){
+ /* Skip this term for now. We revisit it when we process the
+ ** corresponding TERM_VIRTUAL term */
+ }else{
+ Bitmask b;
+ b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
+ if( pOrTerm->wtFlags & TERM_VIRTUAL ){
+ WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
+ b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
+ }
+ indexable &= b;
+ if( (pOrTerm->eOperator & WO_EQ)==0 ){
+ chngToIN = 0;
+ }else{
+ chngToIN &= b;
+ }
+ }
+ }
+
+ /*
+ ** Record the set of tables that satisfy case 3. The set might be
+ ** empty.
+ */
+ pOrInfo->indexable = indexable;
+ if( indexable ){
+ pTerm->eOperator = WO_OR;
+ pWC->hasOr = 1;
+ }else{
+ pTerm->eOperator = WO_OR;
+ }
+
+ /* For a two-way OR, attempt to implementation case 2.
+ */
+ if( indexable && pOrWc->nTerm==2 ){
+ int iOne = 0;
+ WhereTerm *pOne;
+ while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
+ int iTwo = 0;
+ WhereTerm *pTwo;
+ while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
+ whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
+ }
+ }
+ }
+
+ /*
+ ** chngToIN holds a set of tables that *might* satisfy case 1. But
+ ** we have to do some additional checking to see if case 1 really
+ ** is satisfied.
+ **
+ ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
+ ** that there is no possibility of transforming the OR clause into an
+ ** IN operator because one or more terms in the OR clause contain
+ ** something other than == on a column in the single table. The 1-bit
+ ** case means that every term of the OR clause is of the form
+ ** "table.column=expr" for some single table. The one bit that is set
+ ** will correspond to the common table. We still need to check to make
+ ** sure the same column is used on all terms. The 2-bit case is when
+ ** the all terms are of the form "table1.column=table2.column". It
+ ** might be possible to form an IN operator with either table1.column
+ ** or table2.column as the LHS if either is common to every term of
+ ** the OR clause.
+ **
+ ** Note that terms of the form "table.column1=table.column2" (the
+ ** same table on both sizes of the ==) cannot be optimized.
+ */
+ if( chngToIN ){
+ int okToChngToIN = 0; /* True if the conversion to IN is valid */
+ int iColumn = -1; /* Column index on lhs of IN operator */
+ int iCursor = -1; /* Table cursor common to all terms */
+ int j = 0; /* Loop counter */
+
+ /* Search for a table and column that appears on one side or the
+ ** other of the == operator in every subterm. That table and column
+ ** will be recorded in iCursor and iColumn. There might not be any
+ ** such table and column. Set okToChngToIN if an appropriate table
+ ** and column is found but leave okToChngToIN false if not found.
+ */
+ for(j=0; j<2 && !okToChngToIN; j++){
+ Expr *pLeft = 0;
+ pOrTerm = pOrWc->a;
+ for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
+ assert( pOrTerm->eOperator & WO_EQ );
+ pOrTerm->wtFlags &= ~TERM_OR_OK;
+ if( pOrTerm->leftCursor==iCursor ){
+ /* This is the 2-bit case and we are on the second iteration and
+ ** current term is from the first iteration. So skip this term. */
+ assert( j==1 );
+ continue;
+ }
+ if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
+ pOrTerm->leftCursor))==0 ){
+ /* This term must be of the form t1.a==t2.b where t2 is in the
+ ** chngToIN set but t1 is not. This term will be either preceded
+ ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
+ ** and use its inversion. */
+ testcase( pOrTerm->wtFlags & TERM_COPIED );
+ testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
+ assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
+ continue;
+ }
+ iColumn = pOrTerm->u.x.leftColumn;
+ iCursor = pOrTerm->leftCursor;
+ pLeft = pOrTerm->pExpr->pLeft;
+ break;
+ }
+ if( i<0 ){
+ /* No candidate table+column was found. This can only occur
+ ** on the second iteration */
+ assert( j==1 );
+ assert( IsPowerOfTwo(chngToIN) );
+ assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
+ break;
+ }
+ testcase( j==1 );
+
+ /* We have found a candidate table and column. Check to see if that
+ ** table and column is common to every term in the OR clause */
+ okToChngToIN = 1;
+ for(; i>=0 && okToChngToIN; i--, pOrTerm++){
+ assert( pOrTerm->eOperator & WO_EQ );
+ if( pOrTerm->leftCursor!=iCursor ){
+ pOrTerm->wtFlags &= ~TERM_OR_OK;
+ }else if( pOrTerm->u.x.leftColumn!=iColumn || (iColumn==XN_EXPR
+ && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1)
+ )){
+ okToChngToIN = 0;
+ }else{
+ int affLeft, affRight;
+ /* If the right-hand side is also a column, then the affinities
+ ** of both right and left sides must be such that no type
+ ** conversions are required on the right. (Ticket #2249)
+ */
+ affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
+ affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
+ if( affRight!=0 && affRight!=affLeft ){
+ okToChngToIN = 0;
+ }else{
+ pOrTerm->wtFlags |= TERM_OR_OK;
+ }
+ }
+ }
+ }
+
+ /* At this point, okToChngToIN is true if original pTerm satisfies
+ ** case 1. In that case, construct a new virtual term that is
+ ** pTerm converted into an IN operator.
+ */
+ if( okToChngToIN ){
+ Expr *pDup; /* A transient duplicate expression */
+ ExprList *pList = 0; /* The RHS of the IN operator */
+ Expr *pLeft = 0; /* The LHS of the IN operator */
+ Expr *pNew; /* The complete IN operator */
+
+ for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
+ if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
+ assert( pOrTerm->eOperator & WO_EQ );
+ assert( pOrTerm->leftCursor==iCursor );
+ assert( pOrTerm->u.x.leftColumn==iColumn );
+ pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
+ pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
+ pLeft = pOrTerm->pExpr->pLeft;
+ }
+ assert( pLeft!=0 );
+ pDup = sqlite3ExprDup(db, pLeft, 0);
+ pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
+ if( pNew ){
+ int idxNew;
+ transferJoinMarkings(pNew, pExpr);
+ assert( !ExprHasProperty(pNew, EP_xIsSelect) );
+ pNew->x.pList = pList;
+ idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
+ testcase( idxNew==0 );
+ exprAnalyze(pSrc, pWC, idxNew);
+ /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where used again */
+ markTermAsChild(pWC, idxNew, idxTerm);
+ }else{
+ sqlite3ExprListDelete(db, pList);
+ }
+ }
+ }
+}
+#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
+
+/*
+** We already know that pExpr is a binary operator where both operands are
+** column references. This routine checks to see if pExpr is an equivalence
+** relation:
+** 1. The SQLITE_Transitive optimization must be enabled
+** 2. Must be either an == or an IS operator
+** 3. Not originating in the ON clause of an OUTER JOIN
+** 4. The affinities of A and B must be compatible
+** 5a. Both operands use the same collating sequence OR
+** 5b. The overall collating sequence is BINARY
+** If this routine returns TRUE, that means that the RHS can be substituted
+** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
+** This is an optimization. No harm comes from returning 0. But if 1 is
+** returned when it should not be, then incorrect answers might result.
+*/
+static int termIsEquivalence(Parse *pParse, Expr *pExpr){
+ char aff1, aff2;
+ CollSeq *pColl;
+ if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
+ if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
+ if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
+ aff1 = sqlite3ExprAffinity(pExpr->pLeft);
+ aff2 = sqlite3ExprAffinity(pExpr->pRight);
+ if( aff1!=aff2
+ && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
+ ){
+ return 0;
+ }
+ pColl = sqlite3ExprCompareCollSeq(pParse, pExpr);
+ if( sqlite3IsBinary(pColl) ) return 1;
+ return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
+}
+
+/*
+** Recursively walk the expressions of a SELECT statement and generate
+** a bitmask indicating which tables are used in that expression
+** tree.
+*/
+static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
+ Bitmask mask = 0;
+ while( pS ){
+ SrcList *pSrc = pS->pSrc;
+ mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
+ mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
+ mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
+ mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
+ mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
+ if( ALWAYS(pSrc!=0) ){
+ int i;
+ for(i=0; i<pSrc->nSrc; i++){
+ mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
+ mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
+ if( pSrc->a[i].fg.isTabFunc ){
+ mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
+ }
+ }
+ }
+ pS = pS->pPrior;
+ }
+ return mask;
+}
+
+/*
+** Expression pExpr is one operand of a comparison operator that might
+** be useful for indexing. This routine checks to see if pExpr appears
+** in any index. Return TRUE (1) if pExpr is an indexed term and return
+** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
+** number of the table that is indexed and aiCurCol[1] to the column number
+** of the column that is indexed, or XN_EXPR (-2) if an expression is being
+** indexed.
+**
+** If pExpr is a TK_COLUMN column reference, then this routine always returns
+** true even if that particular column is not indexed, because the column
+** might be added to an automatic index later.
+*/
+static SQLITE_NOINLINE int exprMightBeIndexed2(
+ SrcList *pFrom, /* The FROM clause */
+ Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
+ int *aiCurCol, /* Write the referenced table cursor and column here */
+ Expr *pExpr /* An operand of a comparison operator */
+){
+ Index *pIdx;
+ int i;
+ int iCur;
+ for(i=0; mPrereq>1; i++, mPrereq>>=1){}
+ iCur = pFrom->a[i].iCursor;
+ for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+ if( pIdx->aColExpr==0 ) continue;
+ for(i=0; i<pIdx->nKeyCol; i++){
+ if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
+ if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
+ aiCurCol[0] = iCur;
+ aiCurCol[1] = XN_EXPR;
+ return 1;
+ }
+ }
+ }
+ return 0;
+}
+static int exprMightBeIndexed(
+ SrcList *pFrom, /* The FROM clause */
+ Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
+ int *aiCurCol, /* Write the referenced table cursor & column here */
+ Expr *pExpr, /* An operand of a comparison operator */
+ int op /* The specific comparison operator */
+){
+ /* If this expression is a vector to the left or right of a
+ ** inequality constraint (>, <, >= or <=), perform the processing
+ ** on the first element of the vector. */
+ assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
+ assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
+ assert( op<=TK_GE );
+ if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
+ pExpr = pExpr->x.pList->a[0].pExpr;
+ }
+
+ if( pExpr->op==TK_COLUMN ){
+ aiCurCol[0] = pExpr->iTable;
+ aiCurCol[1] = pExpr->iColumn;
+ return 1;
+ }
+ if( mPrereq==0 ) return 0; /* No table references */
+ if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
+ return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
+}
+
+/*
+** The input to this routine is an WhereTerm structure with only the
+** "pExpr" field filled in. The job of this routine is to analyze the
+** subexpression and populate all the other fields of the WhereTerm
+** structure.
+**
+** If the expression is of the form "<expr> <op> X" it gets commuted
+** to the standard form of "X <op> <expr>".
+**
+** If the expression is of the form "X <op> Y" where both X and Y are
+** columns, then the original expression is unchanged and a new virtual
+** term of the form "Y <op> X" is added to the WHERE clause and
+** analyzed separately. The original term is marked with TERM_COPIED
+** and the new term is marked with TERM_DYNAMIC (because it's pExpr
+** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
+** is a commuted copy of a prior term.) The original term has nChild=1
+** and the copy has idxParent set to the index of the original term.
+*/
+static void exprAnalyze(
+ SrcList *pSrc, /* the FROM clause */
+ WhereClause *pWC, /* the WHERE clause */
+ int idxTerm /* Index of the term to be analyzed */
+){
+ WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
+ WhereTerm *pTerm; /* The term to be analyzed */
+ WhereMaskSet *pMaskSet; /* Set of table index masks */
+ Expr *pExpr; /* The expression to be analyzed */
+ Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
+ Bitmask prereqAll; /* Prerequesites of pExpr */
+ Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
+ Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
+ int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
+ int noCase = 0; /* uppercase equivalent to lowercase */
+ int op; /* Top-level operator. pExpr->op */
+ Parse *pParse = pWInfo->pParse; /* Parsing context */
+ sqlite3 *db = pParse->db; /* Database connection */
+ unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */
+ int nLeft; /* Number of elements on left side vector */
+
+ if( db->mallocFailed ){
+ return;
+ }
+ pTerm = &pWC->a[idxTerm];
+ pMaskSet = &pWInfo->sMaskSet;
+ pExpr = pTerm->pExpr;
+ assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
+ prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
+ op = pExpr->op;
+ if( op==TK_IN ){
+ assert( pExpr->pRight==0 );
+ if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
+ if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+ pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
+ }else{
+ pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
+ }
+ }else if( op==TK_ISNULL ){
+ pTerm->prereqRight = 0;
+ }else{
+ pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
+ }
+ pMaskSet->bVarSelect = 0;
+ prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr);
+ if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
+ if( ExprHasProperty(pExpr, EP_FromJoin) ){
+ Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
+ prereqAll |= x;
+ extraRight = x-1; /* ON clause terms may not be used with an index
+ ** on left table of a LEFT JOIN. Ticket #3015 */
+ if( (prereqAll>>1)>=x ){
+ sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
+ return;
+ }
+ }
+ pTerm->prereqAll = prereqAll;
+ pTerm->leftCursor = -1;
+ pTerm->iParent = -1;
+ pTerm->eOperator = 0;
+ if( allowedOp(op) ){
+ int aiCurCol[2];
+ Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
+ Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
+ u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
+
+ if( pTerm->u.x.iField>0 ){
+ assert( op==TK_IN );
+ assert( pLeft->op==TK_VECTOR );
+ pLeft = pLeft->x.pList->a[pTerm->u.x.iField-1].pExpr;
+ }
+
+ if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
+ pTerm->leftCursor = aiCurCol[0];
+ pTerm->u.x.leftColumn = aiCurCol[1];
+ pTerm->eOperator = operatorMask(op) & opMask;
+ }
+ if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
+ if( pRight
+ && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
+ ){
+ WhereTerm *pNew;
+ Expr *pDup;
+ u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
+ assert( pTerm->u.x.iField==0 );
+ if( pTerm->leftCursor>=0 ){
+ int idxNew;
+ pDup = sqlite3ExprDup(db, pExpr, 0);
+ if( db->mallocFailed ){
+ sqlite3ExprDelete(db, pDup);
+ return;
+ }
+ idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
+ if( idxNew==0 ) return;
+ pNew = &pWC->a[idxNew];
+ markTermAsChild(pWC, idxNew, idxTerm);
+ if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
+ pTerm = &pWC->a[idxTerm];
+ pTerm->wtFlags |= TERM_COPIED;
+
+ if( termIsEquivalence(pParse, pDup) ){
+ pTerm->eOperator |= WO_EQUIV;
+ eExtraOp = WO_EQUIV;
+ }
+ }else{
+ pDup = pExpr;
+ pNew = pTerm;
+ }
+ pNew->wtFlags |= exprCommute(pParse, pDup);
+ pNew->leftCursor = aiCurCol[0];
+ pNew->u.x.leftColumn = aiCurCol[1];
+ testcase( (prereqLeft | extraRight) != prereqLeft );
+ pNew->prereqRight = prereqLeft | extraRight;
+ pNew->prereqAll = prereqAll;
+ pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
+ }
+ }
+
+#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
+ /* If a term is the BETWEEN operator, create two new virtual terms
+ ** that define the range that the BETWEEN implements. For example:
+ **
+ ** a BETWEEN b AND c
+ **
+ ** is converted into:
+ **
+ ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
+ **
+ ** The two new terms are added onto the end of the WhereClause object.
+ ** The new terms are "dynamic" and are children of the original BETWEEN
+ ** term. That means that if the BETWEEN term is coded, the children are
+ ** skipped. Or, if the children are satisfied by an index, the original
+ ** BETWEEN term is skipped.
+ */
+ else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
+ ExprList *pList = pExpr->x.pList;
+ int i;
+ static const u8 ops[] = {TK_GE, TK_LE};
+ assert( pList!=0 );
+ assert( pList->nExpr==2 );
+ for(i=0; i<2; i++){
+ Expr *pNewExpr;
+ int idxNew;
+ pNewExpr = sqlite3PExpr(pParse, ops[i],
+ sqlite3ExprDup(db, pExpr->pLeft, 0),
+ sqlite3ExprDup(db, pList->a[i].pExpr, 0));
+ transferJoinMarkings(pNewExpr, pExpr);
+ idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
+ testcase( idxNew==0 );
+ exprAnalyze(pSrc, pWC, idxNew);
+ pTerm = &pWC->a[idxTerm];
+ markTermAsChild(pWC, idxNew, idxTerm);
+ }
+ }
+#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
+
+#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
+ /* Analyze a term that is composed of two or more subterms connected by
+ ** an OR operator.
+ */
+ else if( pExpr->op==TK_OR ){
+ assert( pWC->op==TK_AND );
+ exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
+ pTerm = &pWC->a[idxTerm];
+ }
+#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
+
+#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
+ /* Add constraints to reduce the search space on a LIKE or GLOB
+ ** operator.
+ **
+ ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
+ **
+ ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
+ **
+ ** The last character of the prefix "abc" is incremented to form the
+ ** termination condition "abd". If case is not significant (the default
+ ** for LIKE) then the lower-bound is made all uppercase and the upper-
+ ** bound is made all lowercase so that the bounds also work when comparing
+ ** BLOBs.
+ */
+ if( pWC->op==TK_AND
+ && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
+ ){
+ Expr *pLeft; /* LHS of LIKE/GLOB operator */
+ Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
+ Expr *pNewExpr1;
+ Expr *pNewExpr2;
+ int idxNew1;
+ int idxNew2;
+ const char *zCollSeqName; /* Name of collating sequence */
+ const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
+
+ pLeft = pExpr->x.pList->a[1].pExpr;
+ pStr2 = sqlite3ExprDup(db, pStr1, 0);
+
+ /* Convert the lower bound to upper-case and the upper bound to
+ ** lower-case (upper-case is less than lower-case in ASCII) so that
+ ** the range constraints also work for BLOBs
+ */
+ if( noCase && !pParse->db->mallocFailed ){
+ int i;
+ char c;
+ pTerm->wtFlags |= TERM_LIKE;
+ for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
+ pStr1->u.zToken[i] = sqlite3Toupper(c);
+ pStr2->u.zToken[i] = sqlite3Tolower(c);
+ }
+ }
+
+ if( !db->mallocFailed ){
+ u8 c, *pC; /* Last character before the first wildcard */
+ pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
+ c = *pC;
+ if( noCase ){
+ /* The point is to increment the last character before the first
+ ** wildcard. But if we increment '@', that will push it into the
+ ** alphabetic range where case conversions will mess up the
+ ** inequality. To avoid this, make sure to also run the full
+ ** LIKE on all candidate expressions by clearing the isComplete flag
+ */
+ if( c=='A'-1 ) isComplete = 0;
+ c = sqlite3UpperToLower[c];
+ }
+ *pC = c + 1;
+ }
+ zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY;
+ pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
+ pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
+ sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
+ pStr1);
+ transferJoinMarkings(pNewExpr1, pExpr);
+ idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
+ testcase( idxNew1==0 );
+ exprAnalyze(pSrc, pWC, idxNew1);
+ pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
+ pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
+ sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
+ pStr2);
+ transferJoinMarkings(pNewExpr2, pExpr);
+ idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
+ testcase( idxNew2==0 );
+ exprAnalyze(pSrc, pWC, idxNew2);
+ pTerm = &pWC->a[idxTerm];
+ if( isComplete ){
+ markTermAsChild(pWC, idxNew1, idxTerm);
+ markTermAsChild(pWC, idxNew2, idxTerm);
+ }
+ }
+#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ /* Add a WO_AUX auxiliary term to the constraint set if the
+ ** current expression is of the form "column OP expr" where OP
+ ** is an operator that gets passed into virtual tables but which is
+ ** not normally optimized for ordinary tables. In other words, OP
+ ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
+ ** This information is used by the xBestIndex methods of
+ ** virtual tables. The native query optimizer does not attempt
+ ** to do anything with MATCH functions.
+ */
+ if( pWC->op==TK_AND ){
+ Expr *pRight = 0, *pLeft = 0;
+ int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight);
+ while( res-- > 0 ){
+ int idxNew;
+ WhereTerm *pNewTerm;
+ Bitmask prereqColumn, prereqExpr;
+
+ prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
+ prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
+ if( (prereqExpr & prereqColumn)==0 ){
+ Expr *pNewExpr;
+ pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
+ 0, sqlite3ExprDup(db, pRight, 0));
+ if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
+ ExprSetProperty(pNewExpr, EP_FromJoin);
+ pNewExpr->iRightJoinTable = pExpr->iRightJoinTable;
+ }
+ idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
+ testcase( idxNew==0 );
+ pNewTerm = &pWC->a[idxNew];
+ pNewTerm->prereqRight = prereqExpr;
+ pNewTerm->leftCursor = pLeft->iTable;
+ pNewTerm->u.x.leftColumn = pLeft->iColumn;
+ pNewTerm->eOperator = WO_AUX;
+ pNewTerm->eMatchOp = eOp2;
+ markTermAsChild(pWC, idxNew, idxTerm);
+ pTerm = &pWC->a[idxTerm];
+ pTerm->wtFlags |= TERM_COPIED;
+ pNewTerm->prereqAll = pTerm->prereqAll;
+ }
+ SWAP(Expr*, pLeft, pRight);
+ }
+ }
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+ /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
+ ** new terms for each component comparison - "a = ?" and "b = ?". The
+ ** new terms completely replace the original vector comparison, which is
+ ** no longer used.
+ **
+ ** This is only required if at least one side of the comparison operation
+ ** is not a sub-select. */
+ if( pWC->op==TK_AND
+ && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
+ && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
+ && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
+ && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
+ || (pExpr->pRight->flags & EP_xIsSelect)==0)
+ ){
+ int i;
+ for(i=0; i<nLeft; i++){
+ int idxNew;
+ Expr *pNew;
+ Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
+ Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
+
+ pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
+ transferJoinMarkings(pNew, pExpr);
+ idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
+ exprAnalyze(pSrc, pWC, idxNew);
+ }
+ pTerm = &pWC->a[idxTerm];
+ pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */
+ pTerm->eOperator = 0;
+ }
+
+ /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
+ ** a virtual term for each vector component. The expression object
+ ** used by each such virtual term is pExpr (the full vector IN(...)
+ ** expression). The WhereTerm.u.x.iField variable identifies the index within
+ ** the vector on the LHS that the virtual term represents.
+ **
+ ** This only works if the RHS is a simple SELECT (not a compound) that does
+ ** not use window functions.
+ */
+ if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->u.x.iField==0
+ && pExpr->pLeft->op==TK_VECTOR
+ && pExpr->x.pSelect->pPrior==0
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ && pExpr->x.pSelect->pWin==0
+#endif
+ ){
+ int i;
+ for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
+ int idxNew;
+ idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
+ pWC->a[idxNew].u.x.iField = i+1;
+ exprAnalyze(pSrc, pWC, idxNew);
+ markTermAsChild(pWC, idxNew, idxTerm);
+ }
+ }
+
+#ifdef SQLITE_ENABLE_STAT4
+ /* When sqlite_stat4 histogram data is available an operator of the
+ ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
+ ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
+ ** virtual term of that form.
+ **
+ ** Note that the virtual term must be tagged with TERM_VNULL.
+ */
+ if( pExpr->op==TK_NOTNULL
+ && pExpr->pLeft->op==TK_COLUMN
+ && pExpr->pLeft->iColumn>=0
+ && !ExprHasProperty(pExpr, EP_FromJoin)
+ && OptimizationEnabled(db, SQLITE_Stat4)
+ ){
+ Expr *pNewExpr;
+ Expr *pLeft = pExpr->pLeft;
+ int idxNew;
+ WhereTerm *pNewTerm;
+
+ pNewExpr = sqlite3PExpr(pParse, TK_GT,
+ sqlite3ExprDup(db, pLeft, 0),
+ sqlite3ExprAlloc(db, TK_NULL, 0, 0));
+
+ idxNew = whereClauseInsert(pWC, pNewExpr,
+ TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
+ if( idxNew ){
+ pNewTerm = &pWC->a[idxNew];
+ pNewTerm->prereqRight = 0;
+ pNewTerm->leftCursor = pLeft->iTable;
+ pNewTerm->u.x.leftColumn = pLeft->iColumn;
+ pNewTerm->eOperator = WO_GT;
+ markTermAsChild(pWC, idxNew, idxTerm);
+ pTerm = &pWC->a[idxTerm];
+ pTerm->wtFlags |= TERM_COPIED;
+ pNewTerm->prereqAll = pTerm->prereqAll;
+ }
+ }
+#endif /* SQLITE_ENABLE_STAT4 */
+
+ /* Prevent ON clause terms of a LEFT JOIN from being used to drive
+ ** an index for tables to the left of the join.
+ */
+ testcase( pTerm!=&pWC->a[idxTerm] );
+ pTerm = &pWC->a[idxTerm];
+ pTerm->prereqRight |= extraRight;
+}
+
+/***************************************************************************
+** Routines with file scope above. Interface to the rest of the where.c
+** subsystem follows.
+***************************************************************************/
+
+/*
+** This routine identifies subexpressions in the WHERE clause where
+** each subexpression is separated by the AND operator or some other
+** operator specified in the op parameter. The WhereClause structure
+** is filled with pointers to subexpressions. For example:
+**
+** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
+** \________/ \_______________/ \________________/
+** slot[0] slot[1] slot[2]
+**
+** The original WHERE clause in pExpr is unaltered. All this routine
+** does is make slot[] entries point to substructure within pExpr.
+**
+** In the previous sentence and in the diagram, "slot[]" refers to
+** the WhereClause.a[] array. The slot[] array grows as needed to contain
+** all terms of the WHERE clause.
+*/
+SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
+ Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pExpr);
+ pWC->op = op;
+ if( pE2==0 ) return;
+ if( pE2->op!=op ){
+ whereClauseInsert(pWC, pExpr, 0);
+ }else{
+ sqlite3WhereSplit(pWC, pE2->pLeft, op);
+ sqlite3WhereSplit(pWC, pE2->pRight, op);
+ }
+}
+
+/*
+** Initialize a preallocated WhereClause structure.
+*/
+SQLITE_PRIVATE void sqlite3WhereClauseInit(
+ WhereClause *pWC, /* The WhereClause to be initialized */
+ WhereInfo *pWInfo /* The WHERE processing context */
+){
+ pWC->pWInfo = pWInfo;
+ pWC->hasOr = 0;
+ pWC->pOuter = 0;
+ pWC->nTerm = 0;
+ pWC->nSlot = ArraySize(pWC->aStatic);
+ pWC->a = pWC->aStatic;
+}
+
+/*
+** Deallocate a WhereClause structure. The WhereClause structure
+** itself is not freed. This routine is the inverse of
+** sqlite3WhereClauseInit().
+*/
+SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
+ int i;
+ WhereTerm *a;
+ sqlite3 *db = pWC->pWInfo->pParse->db;
+ for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
+ if( a->wtFlags & TERM_DYNAMIC ){
+ sqlite3ExprDelete(db, a->pExpr);
+ }
+ if( a->wtFlags & TERM_ORINFO ){
+ whereOrInfoDelete(db, a->u.pOrInfo);
+ }else if( a->wtFlags & TERM_ANDINFO ){
+ whereAndInfoDelete(db, a->u.pAndInfo);
+ }
+ }
+ if( pWC->a!=pWC->aStatic ){
+ sqlite3DbFree(db, pWC->a);
+ }
+}
+
+
+/*
+** These routines walk (recursively) an expression tree and generate
+** a bitmask indicating which tables are used in that expression
+** tree.
+*/
+SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
+ Bitmask mask;
+ if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
+ return sqlite3WhereGetMask(pMaskSet, p->iTable);
+ }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
+ assert( p->op!=TK_IF_NULL_ROW );
+ return 0;
+ }
+ mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
+ if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft);
+ if( p->pRight ){
+ mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight);
+ assert( p->x.pList==0 );
+ }else if( ExprHasProperty(p, EP_xIsSelect) ){
+ if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
+ mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
+ }else if( p->x.pList ){
+ mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
+ }
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( (p->op==TK_FUNCTION || p->op==TK_AGG_FUNCTION) && p->y.pWin ){
+ mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition);
+ mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy);
+ mask |= sqlite3WhereExprUsage(pMaskSet, p->y.pWin->pFilter);
+ }
+#endif
+ return mask;
+}
+SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
+ return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0;
+}
+SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
+ int i;
+ Bitmask mask = 0;
+ if( pList ){
+ for(i=0; i<pList->nExpr; i++){
+ mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
+ }
+ }
+ return mask;
+}
+
+
+/*
+** Call exprAnalyze on all terms in a WHERE clause.
+**
+** Note that exprAnalyze() might add new virtual terms onto the
+** end of the WHERE clause. We do not want to analyze these new
+** virtual terms, so start analyzing at the end and work forward
+** so that the added virtual terms are never processed.
+*/
+SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
+ SrcList *pTabList, /* the FROM clause */
+ WhereClause *pWC /* the WHERE clause to be analyzed */
+){
+ int i;
+ for(i=pWC->nTerm-1; i>=0; i--){
+ exprAnalyze(pTabList, pWC, i);
+ }
+}
+
+/*
+** For table-valued-functions, transform the function arguments into
+** new WHERE clause terms.
+**
+** Each function argument translates into an equality constraint against
+** a HIDDEN column in the table.
+*/
+SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
+ Parse *pParse, /* Parsing context */
+ struct SrcList_item *pItem, /* The FROM clause term to process */
+ WhereClause *pWC /* Xfer function arguments to here */
+){
+ Table *pTab;
+ int j, k;
+ ExprList *pArgs;
+ Expr *pColRef;
+ Expr *pTerm;
+ if( pItem->fg.isTabFunc==0 ) return;
+ pTab = pItem->pTab;
+ assert( pTab!=0 );
+ pArgs = pItem->u1.pFuncArg;
+ if( pArgs==0 ) return;
+ for(j=k=0; j<pArgs->nExpr; j++){
+ Expr *pRhs;
+ while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
+ if( k>=pTab->nCol ){
+ sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
+ pTab->zName, j);
+ return;
+ }
+ pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
+ if( pColRef==0 ) return;
+ pColRef->iTable = pItem->iCursor;
+ pColRef->iColumn = k++;
+ pColRef->y.pTab = pTab;
+ pRhs = sqlite3PExpr(pParse, TK_UPLUS,
+ sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
+ pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
+ if( pItem->fg.jointype & JT_LEFT ){
+ sqlite3SetJoinExpr(pTerm, pItem->iCursor);
+ }
+ whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
+ }
+}
+
+/************** End of whereexpr.c *******************************************/
+/************** Begin file where.c *******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This module contains C code that generates VDBE code used to process
+** the WHERE clause of SQL statements. This module is responsible for
+** generating the code that loops through a table looking for applicable
+** rows. Indices are selected and used to speed the search when doing
+** so is applicable. Because this module is responsible for selecting
+** indices, you might also think of this module as the "query optimizer".
+*/
+/* #include "sqliteInt.h" */
+/* #include "whereInt.h" */
+
+/*
+** Extra information appended to the end of sqlite3_index_info but not
+** visible to the xBestIndex function, at least not directly. The
+** sqlite3_vtab_collation() interface knows how to reach it, however.
+**
+** This object is not an API and can be changed from one release to the
+** next. As long as allocateIndexInfo() and sqlite3_vtab_collation()
+** agree on the structure, all will be well.
+*/
+typedef struct HiddenIndexInfo HiddenIndexInfo;
+struct HiddenIndexInfo {
+ WhereClause *pWC; /* The Where clause being analyzed */
+ Parse *pParse; /* The parsing context */
+};
+
+/* Forward declaration of methods */
+static int whereLoopResize(sqlite3*, WhereLoop*, int);
+
+/* Test variable that can be set to enable WHERE tracing */
+#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
+/***/ int sqlite3WhereTrace = 0;
+#endif
+
+
+/*
+** Return the estimated number of output rows from a WHERE clause
+*/
+SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
+ return pWInfo->nRowOut;
+}
+
+/*
+** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
+** WHERE clause returns outputs for DISTINCT processing.
+*/
+SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
+ return pWInfo->eDistinct;
+}
+
+/*
+** Return the number of ORDER BY terms that are satisfied by the
+** WHERE clause. A return of 0 means that the output must be
+** completely sorted. A return equal to the number of ORDER BY
+** terms means that no sorting is needed at all. A return that
+** is positive but less than the number of ORDER BY terms means that
+** block sorting is required.
+*/
+SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
+ return pWInfo->nOBSat;
+}
+
+/*
+** In the ORDER BY LIMIT optimization, if the inner-most loop is known
+** to emit rows in increasing order, and if the last row emitted by the
+** inner-most loop did not fit within the sorter, then we can skip all
+** subsequent rows for the current iteration of the inner loop (because they
+** will not fit in the sorter either) and continue with the second inner
+** loop - the loop immediately outside the inner-most.
+**
+** When a row does not fit in the sorter (because the sorter already
+** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the
+** label returned by this function.
+**
+** If the ORDER BY LIMIT optimization applies, the jump destination should
+** be the continuation for the second-inner-most loop. If the ORDER BY
+** LIMIT optimization does not apply, then the jump destination should
+** be the continuation for the inner-most loop.
+**
+** It is always safe for this routine to return the continuation of the
+** inner-most loop, in the sense that a correct answer will result.
+** Returning the continuation the second inner loop is an optimization
+** that might make the code run a little faster, but should not change
+** the final answer.
+*/
+SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){
+ WhereLevel *pInner;
+ if( !pWInfo->bOrderedInnerLoop ){
+ /* The ORDER BY LIMIT optimization does not apply. Jump to the
+ ** continuation of the inner-most loop. */
+ return pWInfo->iContinue;
+ }
+ pInner = &pWInfo->a[pWInfo->nLevel-1];
+ assert( pInner->addrNxt!=0 );
+ return pInner->addrNxt;
+}
+
+/*
+** Return the VDBE address or label to jump to in order to continue
+** immediately with the next row of a WHERE clause.
+*/
+SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
+ assert( pWInfo->iContinue!=0 );
+ return pWInfo->iContinue;
+}
+
+/*
+** Return the VDBE address or label to jump to in order to break
+** out of a WHERE loop.
+*/
+SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
+ return pWInfo->iBreak;
+}
+
+/*
+** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
+** operate directly on the rowids returned by a WHERE clause. Return
+** ONEPASS_SINGLE (1) if the statement can operation directly because only
+** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
+** optimization can be used on multiple
+**
+** If the ONEPASS optimization is used (if this routine returns true)
+** then also write the indices of open cursors used by ONEPASS
+** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
+** table and iaCur[1] gets the cursor used by an auxiliary index.
+** Either value may be -1, indicating that cursor is not used.
+** Any cursors returned will have been opened for writing.
+**
+** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
+** unable to use the ONEPASS optimization.
+*/
+SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
+ memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
+#ifdef WHERETRACE_ENABLED
+ if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
+ sqlite3DebugPrintf("%s cursors: %d %d\n",
+ pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
+ aiCur[0], aiCur[1]);
+ }
+#endif
+ return pWInfo->eOnePass;
+}
+
+/*
+** Return TRUE if the WHERE loop uses the OP_DeferredSeek opcode to move
+** the data cursor to the row selected by the index cursor.
+*/
+SQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo *pWInfo){
+ return pWInfo->bDeferredSeek;
+}
+
+/*
+** Move the content of pSrc into pDest
+*/
+static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
+ pDest->n = pSrc->n;
+ memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
+}
+
+/*
+** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
+**
+** The new entry might overwrite an existing entry, or it might be
+** appended, or it might be discarded. Do whatever is the right thing
+** so that pSet keeps the N_OR_COST best entries seen so far.
+*/
+static int whereOrInsert(
+ WhereOrSet *pSet, /* The WhereOrSet to be updated */
+ Bitmask prereq, /* Prerequisites of the new entry */
+ LogEst rRun, /* Run-cost of the new entry */
+ LogEst nOut /* Number of outputs for the new entry */
+){
+ u16 i;
+ WhereOrCost *p;
+ for(i=pSet->n, p=pSet->a; i>0; i--, p++){
+ if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
+ goto whereOrInsert_done;
+ }
+ if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
+ return 0;
+ }
+ }
+ if( pSet->n<N_OR_COST ){
+ p = &pSet->a[pSet->n++];
+ p->nOut = nOut;
+ }else{
+ p = pSet->a;
+ for(i=1; i<pSet->n; i++){
+ if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
+ }
+ if( p->rRun<=rRun ) return 0;
+ }
+whereOrInsert_done:
+ p->prereq = prereq;
+ p->rRun = rRun;
+ if( p->nOut>nOut ) p->nOut = nOut;
+ return 1;
+}
+
+/*
+** Return the bitmask for the given cursor number. Return 0 if
+** iCursor is not in the set.
+*/
+SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
+ int i;
+ assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
+ for(i=0; i<pMaskSet->n; i++){
+ if( pMaskSet->ix[i]==iCursor ){
+ return MASKBIT(i);
+ }
+ }
+ return 0;
+}
+
+/*
+** Create a new mask for cursor iCursor.
+**
+** There is one cursor per table in the FROM clause. The number of
+** tables in the FROM clause is limited by a test early in the
+** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
+** array will never overflow.
+*/
+static void createMask(WhereMaskSet *pMaskSet, int iCursor){
+ assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
+ pMaskSet->ix[pMaskSet->n++] = iCursor;
+}
+
+/*
+** Advance to the next WhereTerm that matches according to the criteria
+** established when the pScan object was initialized by whereScanInit().
+** Return NULL if there are no more matching WhereTerms.
+*/
+static WhereTerm *whereScanNext(WhereScan *pScan){
+ int iCur; /* The cursor on the LHS of the term */
+ i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
+ Expr *pX; /* An expression being tested */
+ WhereClause *pWC; /* Shorthand for pScan->pWC */
+ WhereTerm *pTerm; /* The term being tested */
+ int k = pScan->k; /* Where to start scanning */
+
+ assert( pScan->iEquiv<=pScan->nEquiv );
+ pWC = pScan->pWC;
+ while(1){
+ iColumn = pScan->aiColumn[pScan->iEquiv-1];
+ iCur = pScan->aiCur[pScan->iEquiv-1];
+ assert( pWC!=0 );
+ do{
+ for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
+ if( pTerm->leftCursor==iCur
+ && pTerm->u.x.leftColumn==iColumn
+ && (iColumn!=XN_EXPR
+ || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
+ pScan->pIdxExpr,iCur)==0)
+ && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
+ ){
+ if( (pTerm->eOperator & WO_EQUIV)!=0
+ && pScan->nEquiv<ArraySize(pScan->aiCur)
+ && (pX = sqlite3ExprSkipCollateAndLikely(pTerm->pExpr->pRight))->op
+ ==TK_COLUMN
+ ){
+ int j;
+ for(j=0; j<pScan->nEquiv; j++){
+ if( pScan->aiCur[j]==pX->iTable
+ && pScan->aiColumn[j]==pX->iColumn ){
+ break;
+ }
+ }
+ if( j==pScan->nEquiv ){
+ pScan->aiCur[j] = pX->iTable;
+ pScan->aiColumn[j] = pX->iColumn;
+ pScan->nEquiv++;
+ }
+ }
+ if( (pTerm->eOperator & pScan->opMask)!=0 ){
+ /* Verify the affinity and collating sequence match */
+ if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
+ CollSeq *pColl;
+ Parse *pParse = pWC->pWInfo->pParse;
+ pX = pTerm->pExpr;
+ if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
+ continue;
+ }
+ assert(pX->pLeft);
+ pColl = sqlite3ExprCompareCollSeq(pParse, pX);
+ if( pColl==0 ) pColl = pParse->db->pDfltColl;
+ if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
+ continue;
+ }
+ }
+ if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
+ && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
+ && pX->iTable==pScan->aiCur[0]
+ && pX->iColumn==pScan->aiColumn[0]
+ ){
+ testcase( pTerm->eOperator & WO_IS );
+ continue;
+ }
+ pScan->pWC = pWC;
+ pScan->k = k+1;
+ return pTerm;
+ }
+ }
+ }
+ pWC = pWC->pOuter;
+ k = 0;
+ }while( pWC!=0 );
+ if( pScan->iEquiv>=pScan->nEquiv ) break;
+ pWC = pScan->pOrigWC;
+ k = 0;
+ pScan->iEquiv++;
+ }
+ return 0;
+}
+
+/*
+** This is whereScanInit() for the case of an index on an expression.
+** It is factored out into a separate tail-recursion subroutine so that
+** the normal whereScanInit() routine, which is a high-runner, does not
+** need to push registers onto the stack as part of its prologue.
+*/
+static SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){
+ pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr);
+ return whereScanNext(pScan);
+}
+
+/*
+** Initialize a WHERE clause scanner object. Return a pointer to the
+** first match. Return NULL if there are no matches.
+**
+** The scanner will be searching the WHERE clause pWC. It will look
+** for terms of the form "X <op> <expr>" where X is column iColumn of table
+** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
+** must be one of the indexes of table iCur.
+**
+** The <op> must be one of the operators described by opMask.
+**
+** If the search is for X and the WHERE clause contains terms of the
+** form X=Y then this routine might also return terms of the form
+** "Y <op> <expr>". The number of levels of transitivity is limited,
+** but is enough to handle most commonly occurring SQL statements.
+**
+** If X is not the INTEGER PRIMARY KEY then X must be compatible with
+** index pIdx.
+*/
+static WhereTerm *whereScanInit(
+ WhereScan *pScan, /* The WhereScan object being initialized */
+ WhereClause *pWC, /* The WHERE clause to be scanned */
+ int iCur, /* Cursor to scan for */
+ int iColumn, /* Column to scan for */
+ u32 opMask, /* Operator(s) to scan for */
+ Index *pIdx /* Must be compatible with this index */
+){
+ pScan->pOrigWC = pWC;
+ pScan->pWC = pWC;
+ pScan->pIdxExpr = 0;
+ pScan->idxaff = 0;
+ pScan->zCollName = 0;
+ pScan->opMask = opMask;
+ pScan->k = 0;
+ pScan->aiCur[0] = iCur;
+ pScan->nEquiv = 1;
+ pScan->iEquiv = 1;
+ if( pIdx ){
+ int j = iColumn;
+ iColumn = pIdx->aiColumn[j];
+ if( iColumn==XN_EXPR ){
+ pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
+ pScan->zCollName = pIdx->azColl[j];
+ pScan->aiColumn[0] = XN_EXPR;
+ return whereScanInitIndexExpr(pScan);
+ }else if( iColumn==pIdx->pTable->iPKey ){
+ iColumn = XN_ROWID;
+ }else if( iColumn>=0 ){
+ pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
+ pScan->zCollName = pIdx->azColl[j];
+ }
+ }else if( iColumn==XN_EXPR ){
+ return 0;
+ }
+ pScan->aiColumn[0] = iColumn;
+ return whereScanNext(pScan);
+}
+
+/*
+** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
+** where X is a reference to the iColumn of table iCur or of index pIdx
+** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
+** the op parameter. Return a pointer to the term. Return 0 if not found.
+**
+** If pIdx!=0 then it must be one of the indexes of table iCur.
+** Search for terms matching the iColumn-th column of pIdx
+** rather than the iColumn-th column of table iCur.
+**
+** The term returned might by Y=<expr> if there is another constraint in
+** the WHERE clause that specifies that X=Y. Any such constraints will be
+** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
+** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
+** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
+** other equivalent values. Hence a search for X will return <expr> if X=A1
+** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
+**
+** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
+** then try for the one with no dependencies on <expr> - in other words where
+** <expr> is a constant expression of some kind. Only return entries of
+** the form "X <op> Y" where Y is a column in another table if no terms of
+** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
+** exist, try to return a term that does not use WO_EQUIV.
+*/
+SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
+ WhereClause *pWC, /* The WHERE clause to be searched */
+ int iCur, /* Cursor number of LHS */
+ int iColumn, /* Column number of LHS */
+ Bitmask notReady, /* RHS must not overlap with this mask */
+ u32 op, /* Mask of WO_xx values describing operator */
+ Index *pIdx /* Must be compatible with this index, if not NULL */
+){
+ WhereTerm *pResult = 0;
+ WhereTerm *p;
+ WhereScan scan;
+
+ p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
+ op &= WO_EQ|WO_IS;
+ while( p ){
+ if( (p->prereqRight & notReady)==0 ){
+ if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
+ testcase( p->eOperator & WO_IS );
+ return p;
+ }
+ if( pResult==0 ) pResult = p;
+ }
+ p = whereScanNext(&scan);
+ }
+ return pResult;
+}
+
+/*
+** This function searches pList for an entry that matches the iCol-th column
+** of index pIdx.
+**
+** If such an expression is found, its index in pList->a[] is returned. If
+** no expression is found, -1 is returned.
+*/
+static int findIndexCol(
+ Parse *pParse, /* Parse context */
+ ExprList *pList, /* Expression list to search */
+ int iBase, /* Cursor for table associated with pIdx */
+ Index *pIdx, /* Index to match column of */
+ int iCol /* Column of index to match */
+){
+ int i;
+ const char *zColl = pIdx->azColl[iCol];
+
+ for(i=0; i<pList->nExpr; i++){
+ Expr *p = sqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr);
+ if( p->op==TK_COLUMN
+ && p->iColumn==pIdx->aiColumn[iCol]
+ && p->iTable==iBase
+ ){
+ CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
+ if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
+ return i;
+ }
+ }
+ }
+
+ return -1;
+}
+
+/*
+** Return TRUE if the iCol-th column of index pIdx is NOT NULL
+*/
+static int indexColumnNotNull(Index *pIdx, int iCol){
+ int j;
+ assert( pIdx!=0 );
+ assert( iCol>=0 && iCol<pIdx->nColumn );
+ j = pIdx->aiColumn[iCol];
+ if( j>=0 ){
+ return pIdx->pTable->aCol[j].notNull;
+ }else if( j==(-1) ){
+ return 1;
+ }else{
+ assert( j==(-2) );
+ return 0; /* Assume an indexed expression can always yield a NULL */
+
+ }
+}
+
+/*
+** Return true if the DISTINCT expression-list passed as the third argument
+** is redundant.
+**
+** A DISTINCT list is redundant if any subset of the columns in the
+** DISTINCT list are collectively unique and individually non-null.
+*/
+static int isDistinctRedundant(
+ Parse *pParse, /* Parsing context */
+ SrcList *pTabList, /* The FROM clause */
+ WhereClause *pWC, /* The WHERE clause */
+ ExprList *pDistinct /* The result set that needs to be DISTINCT */
+){
+ Table *pTab;
+ Index *pIdx;
+ int i;
+ int iBase;
+
+ /* If there is more than one table or sub-select in the FROM clause of
+ ** this query, then it will not be possible to show that the DISTINCT
+ ** clause is redundant. */
+ if( pTabList->nSrc!=1 ) return 0;
+ iBase = pTabList->a[0].iCursor;
+ pTab = pTabList->a[0].pTab;
+
+ /* If any of the expressions is an IPK column on table iBase, then return
+ ** true. Note: The (p->iTable==iBase) part of this test may be false if the
+ ** current SELECT is a correlated sub-query.
+ */
+ for(i=0; i<pDistinct->nExpr; i++){
+ Expr *p = sqlite3ExprSkipCollateAndLikely(pDistinct->a[i].pExpr);
+ if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
+ }
+
+ /* Loop through all indices on the table, checking each to see if it makes
+ ** the DISTINCT qualifier redundant. It does so if:
+ **
+ ** 1. The index is itself UNIQUE, and
+ **
+ ** 2. All of the columns in the index are either part of the pDistinct
+ ** list, or else the WHERE clause contains a term of the form "col=X",
+ ** where X is a constant value. The collation sequences of the
+ ** comparison and select-list expressions must match those of the index.
+ **
+ ** 3. All of those index columns for which the WHERE clause does not
+ ** contain a "col=X" term are subject to a NOT NULL constraint.
+ */
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+ if( !IsUniqueIndex(pIdx) ) continue;
+ for(i=0; i<pIdx->nKeyCol; i++){
+ if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
+ if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
+ if( indexColumnNotNull(pIdx, i)==0 ) break;
+ }
+ }
+ if( i==pIdx->nKeyCol ){
+ /* This index implies that the DISTINCT qualifier is redundant. */
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+
+/*
+** Estimate the logarithm of the input value to base 2.
+*/
+static LogEst estLog(LogEst N){
+ return N<=10 ? 0 : sqlite3LogEst(N) - 33;
+}
+
+/*
+** Convert OP_Column opcodes to OP_Copy in previously generated code.
+**
+** This routine runs over generated VDBE code and translates OP_Column
+** opcodes into OP_Copy when the table is being accessed via co-routine
+** instead of via table lookup.
+**
+** If the iAutoidxCur is not zero, then any OP_Rowid instructions on
+** cursor iTabCur are transformed into OP_Sequence opcode for the
+** iAutoidxCur cursor, in order to generate unique rowids for the
+** automatic index being generated.
+*/
+static void translateColumnToCopy(
+ Parse *pParse, /* Parsing context */
+ int iStart, /* Translate from this opcode to the end */
+ int iTabCur, /* OP_Column/OP_Rowid references to this table */
+ int iRegister, /* The first column is in this register */
+ int iAutoidxCur /* If non-zero, cursor of autoindex being generated */
+){
+ Vdbe *v = pParse->pVdbe;
+ VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
+ int iEnd = sqlite3VdbeCurrentAddr(v);
+ if( pParse->db->mallocFailed ) return;
+ for(; iStart<iEnd; iStart++, pOp++){
+ if( pOp->p1!=iTabCur ) continue;
+ if( pOp->opcode==OP_Column ){
+ pOp->opcode = OP_Copy;
+ pOp->p1 = pOp->p2 + iRegister;
+ pOp->p2 = pOp->p3;
+ pOp->p3 = 0;
+ }else if( pOp->opcode==OP_Rowid ){
+ if( iAutoidxCur ){
+ pOp->opcode = OP_Sequence;
+ pOp->p1 = iAutoidxCur;
+ }else{
+ pOp->opcode = OP_Null;
+ pOp->p1 = 0;
+ pOp->p3 = 0;
+ }
+ }
+ }
+}
+
+/*
+** Two routines for printing the content of an sqlite3_index_info
+** structure. Used for testing and debugging only. If neither
+** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
+** are no-ops.
+*/
+#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
+static void whereTraceIndexInfoInputs(sqlite3_index_info *p){
+ int i;
+ if( !sqlite3WhereTrace ) return;
+ for(i=0; i<p->nConstraint; i++){
+ sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
+ i,
+ p->aConstraint[i].iColumn,
+ p->aConstraint[i].iTermOffset,
+ p->aConstraint[i].op,
+ p->aConstraint[i].usable);
+ }
+ for(i=0; i<p->nOrderBy; i++){
+ sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
+ i,
+ p->aOrderBy[i].iColumn,
+ p->aOrderBy[i].desc);
+ }
+}
+static void whereTraceIndexInfoOutputs(sqlite3_index_info *p){
+ int i;
+ if( !sqlite3WhereTrace ) return;
+ for(i=0; i<p->nConstraint; i++){
+ sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
+ i,
+ p->aConstraintUsage[i].argvIndex,
+ p->aConstraintUsage[i].omit);
+ }
+ sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
+ sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
+ sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
+ sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
+ sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
+}
+#else
+#define whereTraceIndexInfoInputs(A)
+#define whereTraceIndexInfoOutputs(A)
+#endif
+
+#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
+/*
+** Return TRUE if the WHERE clause term pTerm is of a form where it
+** could be used with an index to access pSrc, assuming an appropriate
+** index existed.
+*/
+static int termCanDriveIndex(
+ WhereTerm *pTerm, /* WHERE clause term to check */
+ struct SrcList_item *pSrc, /* Table we are trying to access */
+ Bitmask notReady /* Tables in outer loops of the join */
+){
+ char aff;
+ if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
+ if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
+ if( (pSrc->fg.jointype & JT_LEFT)
+ && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
+ && (pTerm->eOperator & WO_IS)
+ ){
+ /* Cannot use an IS term from the WHERE clause as an index driver for
+ ** the RHS of a LEFT JOIN. Such a term can only be used if it is from
+ ** the ON clause. */
+ return 0;
+ }
+ if( (pTerm->prereqRight & notReady)!=0 ) return 0;
+ if( pTerm->u.x.leftColumn<0 ) return 0;
+ aff = pSrc->pTab->aCol[pTerm->u.x.leftColumn].affinity;
+ if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
+ testcase( pTerm->pExpr->op==TK_IS );
+ return 1;
+}
+#endif
+
+
+#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
+/*
+** Generate code to construct the Index object for an automatic index
+** and to set up the WhereLevel object pLevel so that the code generator
+** makes use of the automatic index.
+*/
+static void constructAutomaticIndex(
+ Parse *pParse, /* The parsing context */
+ WhereClause *pWC, /* The WHERE clause */
+ struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
+ Bitmask notReady, /* Mask of cursors that are not available */
+ WhereLevel *pLevel /* Write new index here */
+){
+ int nKeyCol; /* Number of columns in the constructed index */
+ WhereTerm *pTerm; /* A single term of the WHERE clause */
+ WhereTerm *pWCEnd; /* End of pWC->a[] */
+ Index *pIdx; /* Object describing the transient index */
+ Vdbe *v; /* Prepared statement under construction */
+ int addrInit; /* Address of the initialization bypass jump */
+ Table *pTable; /* The table being indexed */
+ int addrTop; /* Top of the index fill loop */
+ int regRecord; /* Register holding an index record */
+ int n; /* Column counter */
+ int i; /* Loop counter */
+ int mxBitCol; /* Maximum column in pSrc->colUsed */
+ CollSeq *pColl; /* Collating sequence to on a column */
+ WhereLoop *pLoop; /* The Loop object */
+ char *zNotUsed; /* Extra space on the end of pIdx */
+ Bitmask idxCols; /* Bitmap of columns used for indexing */
+ Bitmask extraCols; /* Bitmap of additional columns */
+ u8 sentWarning = 0; /* True if a warnning has been issued */
+ Expr *pPartial = 0; /* Partial Index Expression */
+ int iContinue = 0; /* Jump here to skip excluded rows */
+ struct SrcList_item *pTabItem; /* FROM clause term being indexed */
+ int addrCounter = 0; /* Address where integer counter is initialized */
+ int regBase; /* Array of registers where record is assembled */
+
+ /* Generate code to skip over the creation and initialization of the
+ ** transient index on 2nd and subsequent iterations of the loop. */
+ v = pParse->pVdbe;
+ assert( v!=0 );
+ addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
+
+ /* Count the number of columns that will be added to the index
+ ** and used to match WHERE clause constraints */
+ nKeyCol = 0;
+ pTable = pSrc->pTab;
+ pWCEnd = &pWC->a[pWC->nTerm];
+ pLoop = pLevel->pWLoop;
+ idxCols = 0;
+ for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
+ Expr *pExpr = pTerm->pExpr;
+ assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
+ || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
+ || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
+ if( pLoop->prereq==0
+ && (pTerm->wtFlags & TERM_VIRTUAL)==0
+ && !ExprHasProperty(pExpr, EP_FromJoin)
+ && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
+ pPartial = sqlite3ExprAnd(pParse, pPartial,
+ sqlite3ExprDup(pParse->db, pExpr, 0));
+ }
+ if( termCanDriveIndex(pTerm, pSrc, notReady) ){
+ int iCol = pTerm->u.x.leftColumn;
+ Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
+ testcase( iCol==BMS );
+ testcase( iCol==BMS-1 );
+ if( !sentWarning ){
+ sqlite3_log(SQLITE_WARNING_AUTOINDEX,
+ "automatic index on %s(%s)", pTable->zName,
+ pTable->aCol[iCol].zName);
+ sentWarning = 1;
+ }
+ if( (idxCols & cMask)==0 ){
+ if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
+ goto end_auto_index_create;
+ }
+ pLoop->aLTerm[nKeyCol++] = pTerm;
+ idxCols |= cMask;
+ }
+ }
+ }
+ assert( nKeyCol>0 );
+ pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
+ pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
+ | WHERE_AUTO_INDEX;
+
+ /* Count the number of additional columns needed to create a
+ ** covering index. A "covering index" is an index that contains all
+ ** columns that are needed by the query. With a covering index, the
+ ** original table never needs to be accessed. Automatic indices must
+ ** be a covering index because the index will not be updated if the
+ ** original table changes and the index and table cannot both be used
+ ** if they go out of sync.
+ */
+ extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
+ mxBitCol = MIN(BMS-1,pTable->nCol);
+ testcase( pTable->nCol==BMS-1 );
+ testcase( pTable->nCol==BMS-2 );
+ for(i=0; i<mxBitCol; i++){
+ if( extraCols & MASKBIT(i) ) nKeyCol++;
+ }
+ if( pSrc->colUsed & MASKBIT(BMS-1) ){
+ nKeyCol += pTable->nCol - BMS + 1;
+ }
+
+ /* Construct the Index object to describe this index */
+ pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
+ if( pIdx==0 ) goto end_auto_index_create;
+ pLoop->u.btree.pIndex = pIdx;
+ pIdx->zName = "auto-index";
+ pIdx->pTable = pTable;
+ n = 0;
+ idxCols = 0;
+ for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
+ if( termCanDriveIndex(pTerm, pSrc, notReady) ){
+ int iCol = pTerm->u.x.leftColumn;
+ Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
+ testcase( iCol==BMS-1 );
+ testcase( iCol==BMS );
+ if( (idxCols & cMask)==0 ){
+ Expr *pX = pTerm->pExpr;
+ idxCols |= cMask;
+ pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
+ pColl = sqlite3ExprCompareCollSeq(pParse, pX);
+ assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
+ pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
+ n++;
+ }
+ }
+ }
+ assert( (u32)n==pLoop->u.btree.nEq );
+
+ /* Add additional columns needed to make the automatic index into
+ ** a covering index */
+ for(i=0; i<mxBitCol; i++){
+ if( extraCols & MASKBIT(i) ){
+ pIdx->aiColumn[n] = i;
+ pIdx->azColl[n] = sqlite3StrBINARY;
+ n++;
+ }
+ }
+ if( pSrc->colUsed & MASKBIT(BMS-1) ){
+ for(i=BMS-1; i<pTable->nCol; i++){
+ pIdx->aiColumn[n] = i;
+ pIdx->azColl[n] = sqlite3StrBINARY;
+ n++;
+ }
+ }
+ assert( n==nKeyCol );
+ pIdx->aiColumn[n] = XN_ROWID;
+ pIdx->azColl[n] = sqlite3StrBINARY;
+
+ /* Create the automatic index */
+ assert( pLevel->iIdxCur>=0 );
+ pLevel->iIdxCur = pParse->nTab++;
+ sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
+ sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
+ VdbeComment((v, "for %s", pTable->zName));
+
+ /* Fill the automatic index with content */
+ pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
+ if( pTabItem->fg.viaCoroutine ){
+ int regYield = pTabItem->regReturn;
+ addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
+ sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
+ addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
+ VdbeCoverage(v);
+ VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
+ }else{
+ addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
+ }
+ if( pPartial ){
+ iContinue = sqlite3VdbeMakeLabel(pParse);
+ sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
+ pLoop->wsFlags |= WHERE_PARTIALIDX;
+ }
+ regRecord = sqlite3GetTempReg(pParse);
+ regBase = sqlite3GenerateIndexKey(
+ pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
+ );
+ sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
+ sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
+ if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
+ if( pTabItem->fg.viaCoroutine ){
+ sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
+ testcase( pParse->db->mallocFailed );
+ assert( pLevel->iIdxCur>0 );
+ translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
+ pTabItem->regResult, pLevel->iIdxCur);
+ sqlite3VdbeGoto(v, addrTop);
+ pTabItem->fg.viaCoroutine = 0;
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
+ sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
+ }
+ sqlite3VdbeJumpHere(v, addrTop);
+ sqlite3ReleaseTempReg(pParse, regRecord);
+
+ /* Jump here when skipping the initialization */
+ sqlite3VdbeJumpHere(v, addrInit);
+
+end_auto_index_create:
+ sqlite3ExprDelete(pParse->db, pPartial);
+}
+#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/*
+** Allocate and populate an sqlite3_index_info structure. It is the
+** responsibility of the caller to eventually release the structure
+** by passing the pointer returned by this function to sqlite3_free().
+*/
+static sqlite3_index_info *allocateIndexInfo(
+ Parse *pParse, /* The parsing context */
+ WhereClause *pWC, /* The WHERE clause being analyzed */
+ Bitmask mUnusable, /* Ignore terms with these prereqs */
+ struct SrcList_item *pSrc, /* The FROM clause term that is the vtab */
+ ExprList *pOrderBy, /* The ORDER BY clause */
+ u16 *pmNoOmit /* Mask of terms not to omit */
+){
+ int i, j;
+ int nTerm;
+ struct sqlite3_index_constraint *pIdxCons;
+ struct sqlite3_index_orderby *pIdxOrderBy;
+ struct sqlite3_index_constraint_usage *pUsage;
+ struct HiddenIndexInfo *pHidden;
+ WhereTerm *pTerm;
+ int nOrderBy;
+ sqlite3_index_info *pIdxInfo;
+ u16 mNoOmit = 0;
+
+ /* Count the number of possible WHERE clause constraints referring
+ ** to this virtual table */
+ for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
+ if( pTerm->leftCursor != pSrc->iCursor ) continue;
+ if( pTerm->prereqRight & mUnusable ) continue;
+ assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
+ testcase( pTerm->eOperator & WO_IN );
+ testcase( pTerm->eOperator & WO_ISNULL );
+ testcase( pTerm->eOperator & WO_IS );
+ testcase( pTerm->eOperator & WO_ALL );
+ if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
+ if( pTerm->wtFlags & TERM_VNULL ) continue;
+ assert( pTerm->u.x.leftColumn>=(-1) );
+ nTerm++;
+ }
+
+ /* If the ORDER BY clause contains only columns in the current
+ ** virtual table then allocate space for the aOrderBy part of
+ ** the sqlite3_index_info structure.
+ */
+ nOrderBy = 0;
+ if( pOrderBy ){
+ int n = pOrderBy->nExpr;
+ for(i=0; i<n; i++){
+ Expr *pExpr = pOrderBy->a[i].pExpr;
+ if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
+ if( pOrderBy->a[i].sortFlags & KEYINFO_ORDER_BIGNULL ) break;
+ }
+ if( i==n){
+ nOrderBy = n;
+ }
+ }
+
+ /* Allocate the sqlite3_index_info structure
+ */
+ pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
+ + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
+ + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) );
+ if( pIdxInfo==0 ){
+ sqlite3ErrorMsg(pParse, "out of memory");
+ return 0;
+ }
+ pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
+ pIdxCons = (struct sqlite3_index_constraint*)&pHidden[1];
+ pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
+ pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
+ pIdxInfo->nOrderBy = nOrderBy;
+ pIdxInfo->aConstraint = pIdxCons;
+ pIdxInfo->aOrderBy = pIdxOrderBy;
+ pIdxInfo->aConstraintUsage = pUsage;
+ pHidden->pWC = pWC;
+ pHidden->pParse = pParse;
+ for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
+ u16 op;
+ if( pTerm->leftCursor != pSrc->iCursor ) continue;
+ if( pTerm->prereqRight & mUnusable ) continue;
+ assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
+ testcase( pTerm->eOperator & WO_IN );
+ testcase( pTerm->eOperator & WO_IS );
+ testcase( pTerm->eOperator & WO_ISNULL );
+ testcase( pTerm->eOperator & WO_ALL );
+ if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
+ if( pTerm->wtFlags & TERM_VNULL ) continue;
+
+ /* tag-20191211-002: WHERE-clause constraints are not useful to the
+ ** right-hand table of a LEFT JOIN. See tag-20191211-001 for the
+ ** equivalent restriction for ordinary tables. */
+ if( (pSrc->fg.jointype & JT_LEFT)!=0
+ && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
+ ){
+ continue;
+ }
+ assert( pTerm->u.x.leftColumn>=(-1) );
+ pIdxCons[j].iColumn = pTerm->u.x.leftColumn;
+ pIdxCons[j].iTermOffset = i;
+ op = pTerm->eOperator & WO_ALL;
+ if( op==WO_IN ) op = WO_EQ;
+ if( op==WO_AUX ){
+ pIdxCons[j].op = pTerm->eMatchOp;
+ }else if( op & (WO_ISNULL|WO_IS) ){
+ if( op==WO_ISNULL ){
+ pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
+ }else{
+ pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
+ }
+ }else{
+ pIdxCons[j].op = (u8)op;
+ /* The direct assignment in the previous line is possible only because
+ ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
+ ** following asserts verify this fact. */
+ assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
+ assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
+ assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
+ assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
+ assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
+ assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
+
+ if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
+ && sqlite3ExprIsVector(pTerm->pExpr->pRight)
+ ){
+ testcase( j!=i );
+ if( j<16 ) mNoOmit |= (1 << j);
+ if( op==WO_LT ) pIdxCons[j].op = WO_LE;
+ if( op==WO_GT ) pIdxCons[j].op = WO_GE;
+ }
+ }
+
+ j++;
+ }
+ pIdxInfo->nConstraint = j;
+ for(i=0; i<nOrderBy; i++){
+ Expr *pExpr = pOrderBy->a[i].pExpr;
+ pIdxOrderBy[i].iColumn = pExpr->iColumn;
+ pIdxOrderBy[i].desc = pOrderBy->a[i].sortFlags & KEYINFO_ORDER_DESC;
+ }
+
+ *pmNoOmit = mNoOmit;
+ return pIdxInfo;
+}
+
+/*
+** The table object reference passed as the second argument to this function
+** must represent a virtual table. This function invokes the xBestIndex()
+** method of the virtual table with the sqlite3_index_info object that
+** comes in as the 3rd argument to this function.
+**
+** If an error occurs, pParse is populated with an error message and an
+** appropriate error code is returned. A return of SQLITE_CONSTRAINT from
+** xBestIndex is not considered an error. SQLITE_CONSTRAINT indicates that
+** the current configuration of "unusable" flags in sqlite3_index_info can
+** not result in a valid plan.
+**
+** Whether or not an error is returned, it is the responsibility of the
+** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
+** that this is required.
+*/
+static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
+ sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
+ int rc;
+
+ whereTraceIndexInfoInputs(p);
+ rc = pVtab->pModule->xBestIndex(pVtab, p);
+ whereTraceIndexInfoOutputs(p);
+
+ if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){
+ if( rc==SQLITE_NOMEM ){
+ sqlite3OomFault(pParse->db);
+ }else if( !pVtab->zErrMsg ){
+ sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
+ }else{
+ sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
+ }
+ }
+ sqlite3_free(pVtab->zErrMsg);
+ pVtab->zErrMsg = 0;
+ return rc;
+}
+#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
+
+#ifdef SQLITE_ENABLE_STAT4
+/*
+** Estimate the location of a particular key among all keys in an
+** index. Store the results in aStat as follows:
+**
+** aStat[0] Est. number of rows less than pRec
+** aStat[1] Est. number of rows equal to pRec
+**
+** Return the index of the sample that is the smallest sample that
+** is greater than or equal to pRec. Note that this index is not an index
+** into the aSample[] array - it is an index into a virtual set of samples
+** based on the contents of aSample[] and the number of fields in record
+** pRec.
+*/
+static int whereKeyStats(
+ Parse *pParse, /* Database connection */
+ Index *pIdx, /* Index to consider domain of */
+ UnpackedRecord *pRec, /* Vector of values to consider */
+ int roundUp, /* Round up if true. Round down if false */
+ tRowcnt *aStat /* OUT: stats written here */
+){
+ IndexSample *aSample = pIdx->aSample;
+ int iCol; /* Index of required stats in anEq[] etc. */
+ int i; /* Index of first sample >= pRec */
+ int iSample; /* Smallest sample larger than or equal to pRec */
+ int iMin = 0; /* Smallest sample not yet tested */
+ int iTest; /* Next sample to test */
+ int res; /* Result of comparison operation */
+ int nField; /* Number of fields in pRec */
+ tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
+
+#ifndef SQLITE_DEBUG
+ UNUSED_PARAMETER( pParse );
+#endif
+ assert( pRec!=0 );
+ assert( pIdx->nSample>0 );
+ assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
+
+ /* Do a binary search to find the first sample greater than or equal
+ ** to pRec. If pRec contains a single field, the set of samples to search
+ ** is simply the aSample[] array. If the samples in aSample[] contain more
+ ** than one fields, all fields following the first are ignored.
+ **
+ ** If pRec contains N fields, where N is more than one, then as well as the
+ ** samples in aSample[] (truncated to N fields), the search also has to
+ ** consider prefixes of those samples. For example, if the set of samples
+ ** in aSample is:
+ **
+ ** aSample[0] = (a, 5)
+ ** aSample[1] = (a, 10)
+ ** aSample[2] = (b, 5)
+ ** aSample[3] = (c, 100)
+ ** aSample[4] = (c, 105)
+ **
+ ** Then the search space should ideally be the samples above and the
+ ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
+ ** the code actually searches this set:
+ **
+ ** 0: (a)
+ ** 1: (a, 5)
+ ** 2: (a, 10)
+ ** 3: (a, 10)
+ ** 4: (b)
+ ** 5: (b, 5)
+ ** 6: (c)
+ ** 7: (c, 100)
+ ** 8: (c, 105)
+ ** 9: (c, 105)
+ **
+ ** For each sample in the aSample[] array, N samples are present in the
+ ** effective sample array. In the above, samples 0 and 1 are based on
+ ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
+ **
+ ** Often, sample i of each block of N effective samples has (i+1) fields.
+ ** Except, each sample may be extended to ensure that it is greater than or
+ ** equal to the previous sample in the array. For example, in the above,
+ ** sample 2 is the first sample of a block of N samples, so at first it
+ ** appears that it should be 1 field in size. However, that would make it
+ ** smaller than sample 1, so the binary search would not work. As a result,
+ ** it is extended to two fields. The duplicates that this creates do not
+ ** cause any problems.
+ */
+ nField = pRec->nField;
+ iCol = 0;
+ iSample = pIdx->nSample * nField;
+ do{
+ int iSamp; /* Index in aSample[] of test sample */
+ int n; /* Number of fields in test sample */
+
+ iTest = (iMin+iSample)/2;
+ iSamp = iTest / nField;
+ if( iSamp>0 ){
+ /* The proposed effective sample is a prefix of sample aSample[iSamp].
+ ** Specifically, the shortest prefix of at least (1 + iTest%nField)
+ ** fields that is greater than the previous effective sample. */
+ for(n=(iTest % nField) + 1; n<nField; n++){
+ if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
+ }
+ }else{
+ n = iTest + 1;
+ }
+
+ pRec->nField = n;
+ res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
+ if( res<0 ){
+ iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
+ iMin = iTest+1;
+ }else if( res==0 && n<nField ){
+ iLower = aSample[iSamp].anLt[n-1];
+ iMin = iTest+1;
+ res = -1;
+ }else{
+ iSample = iTest;
+ iCol = n-1;
+ }
+ }while( res && iMin<iSample );
+ i = iSample / nField;
+
+#ifdef SQLITE_DEBUG
+ /* The following assert statements check that the binary search code
+ ** above found the right answer. This block serves no purpose other
+ ** than to invoke the asserts. */
+ if( pParse->db->mallocFailed==0 ){
+ if( res==0 ){
+ /* If (res==0) is true, then pRec must be equal to sample i. */
+ assert( i<pIdx->nSample );
+ assert( iCol==nField-1 );
+ pRec->nField = nField;
+ assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
+ || pParse->db->mallocFailed
+ );
+ }else{
+ /* Unless i==pIdx->nSample, indicating that pRec is larger than
+ ** all samples in the aSample[] array, pRec must be smaller than the
+ ** (iCol+1) field prefix of sample i. */
+ assert( i<=pIdx->nSample && i>=0 );
+ pRec->nField = iCol+1;
+ assert( i==pIdx->nSample
+ || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
+ || pParse->db->mallocFailed );
+
+ /* if i==0 and iCol==0, then record pRec is smaller than all samples
+ ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
+ ** be greater than or equal to the (iCol) field prefix of sample i.
+ ** If (i>0), then pRec must also be greater than sample (i-1). */
+ if( iCol>0 ){
+ pRec->nField = iCol;
+ assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
+ || pParse->db->mallocFailed );
+ }
+ if( i>0 ){
+ pRec->nField = nField;
+ assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
+ || pParse->db->mallocFailed );
+ }
+ }
+ }
+#endif /* ifdef SQLITE_DEBUG */
+
+ if( res==0 ){
+ /* Record pRec is equal to sample i */
+ assert( iCol==nField-1 );
+ aStat[0] = aSample[i].anLt[iCol];
+ aStat[1] = aSample[i].anEq[iCol];
+ }else{
+ /* At this point, the (iCol+1) field prefix of aSample[i] is the first
+ ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
+ ** is larger than all samples in the array. */
+ tRowcnt iUpper, iGap;
+ if( i>=pIdx->nSample ){
+ iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
+ }else{
+ iUpper = aSample[i].anLt[iCol];
+ }
+
+ if( iLower>=iUpper ){
+ iGap = 0;
+ }else{
+ iGap = iUpper - iLower;
+ }
+ if( roundUp ){
+ iGap = (iGap*2)/3;
+ }else{
+ iGap = iGap/3;
+ }
+ aStat[0] = iLower + iGap;
+ aStat[1] = pIdx->aAvgEq[nField-1];
+ }
+
+ /* Restore the pRec->nField value before returning. */
+ pRec->nField = nField;
+ return i;
+}
+#endif /* SQLITE_ENABLE_STAT4 */
+
+/*
+** If it is not NULL, pTerm is a term that provides an upper or lower
+** bound on a range scan. Without considering pTerm, it is estimated
+** that the scan will visit nNew rows. This function returns the number
+** estimated to be visited after taking pTerm into account.
+**
+** If the user explicitly specified a likelihood() value for this term,
+** then the return value is the likelihood multiplied by the number of
+** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
+** has a likelihood of 0.50, and any other term a likelihood of 0.25.
+*/
+static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
+ LogEst nRet = nNew;
+ if( pTerm ){
+ if( pTerm->truthProb<=0 ){
+ nRet += pTerm->truthProb;
+ }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
+ nRet -= 20; assert( 20==sqlite3LogEst(4) );
+ }
+ }
+ return nRet;
+}
+
+
+#ifdef SQLITE_ENABLE_STAT4
+/*
+** Return the affinity for a single column of an index.
+*/
+SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
+ assert( iCol>=0 && iCol<pIdx->nColumn );
+ if( !pIdx->zColAff ){
+ if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
+ }
+ assert( pIdx->zColAff[iCol]!=0 );
+ return pIdx->zColAff[iCol];
+}
+#endif
+
+
+#ifdef SQLITE_ENABLE_STAT4
+/*
+** This function is called to estimate the number of rows visited by a
+** range-scan on a skip-scan index. For example:
+**
+** CREATE INDEX i1 ON t1(a, b, c);
+** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
+**
+** Value pLoop->nOut is currently set to the estimated number of rows
+** visited for scanning (a=? AND b=?). This function reduces that estimate
+** by some factor to account for the (c BETWEEN ? AND ?) expression based
+** on the stat4 data for the index. this scan will be peformed multiple
+** times (once for each (a,b) combination that matches a=?) is dealt with
+** by the caller.
+**
+** It does this by scanning through all stat4 samples, comparing values
+** extracted from pLower and pUpper with the corresponding column in each
+** sample. If L and U are the number of samples found to be less than or
+** equal to the values extracted from pLower and pUpper respectively, and
+** N is the total number of samples, the pLoop->nOut value is adjusted
+** as follows:
+**
+** nOut = nOut * ( min(U - L, 1) / N )
+**
+** If pLower is NULL, or a value cannot be extracted from the term, L is
+** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
+** U is set to N.
+**
+** Normally, this function sets *pbDone to 1 before returning. However,
+** if no value can be extracted from either pLower or pUpper (and so the
+** estimate of the number of rows delivered remains unchanged), *pbDone
+** is left as is.
+**
+** If an error occurs, an SQLite error code is returned. Otherwise,
+** SQLITE_OK.
+*/
+static int whereRangeSkipScanEst(
+ Parse *pParse, /* Parsing & code generating context */
+ WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
+ WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
+ WhereLoop *pLoop, /* Update the .nOut value of this loop */
+ int *pbDone /* Set to true if at least one expr. value extracted */
+){
+ Index *p = pLoop->u.btree.pIndex;
+ int nEq = pLoop->u.btree.nEq;
+ sqlite3 *db = pParse->db;
+ int nLower = -1;
+ int nUpper = p->nSample+1;
+ int rc = SQLITE_OK;
+ u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
+ CollSeq *pColl;
+
+ sqlite3_value *p1 = 0; /* Value extracted from pLower */
+ sqlite3_value *p2 = 0; /* Value extracted from pUpper */
+ sqlite3_value *pVal = 0; /* Value extracted from record */
+
+ pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
+ if( pLower ){
+ rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
+ nLower = 0;
+ }
+ if( pUpper && rc==SQLITE_OK ){
+ rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
+ nUpper = p2 ? 0 : p->nSample;
+ }
+
+ if( p1 || p2 ){
+ int i;
+ int nDiff;
+ for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
+ rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
+ if( rc==SQLITE_OK && p1 ){
+ int res = sqlite3MemCompare(p1, pVal, pColl);
+ if( res>=0 ) nLower++;
+ }
+ if( rc==SQLITE_OK && p2 ){
+ int res = sqlite3MemCompare(p2, pVal, pColl);
+ if( res>=0 ) nUpper++;
+ }
+ }
+ nDiff = (nUpper - nLower);
+ if( nDiff<=0 ) nDiff = 1;
+
+ /* If there is both an upper and lower bound specified, and the
+ ** comparisons indicate that they are close together, use the fallback
+ ** method (assume that the scan visits 1/64 of the rows) for estimating
+ ** the number of rows visited. Otherwise, estimate the number of rows
+ ** using the method described in the header comment for this function. */
+ if( nDiff!=1 || pUpper==0 || pLower==0 ){
+ int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
+ pLoop->nOut -= nAdjust;
+ *pbDone = 1;
+ WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
+ nLower, nUpper, nAdjust*-1, pLoop->nOut));
+ }
+
+ }else{
+ assert( *pbDone==0 );
+ }
+
+ sqlite3ValueFree(p1);
+ sqlite3ValueFree(p2);
+ sqlite3ValueFree(pVal);
+
+ return rc;
+}
+#endif /* SQLITE_ENABLE_STAT4 */
+
+/*
+** This function is used to estimate the number of rows that will be visited
+** by scanning an index for a range of values. The range may have an upper
+** bound, a lower bound, or both. The WHERE clause terms that set the upper
+** and lower bounds are represented by pLower and pUpper respectively. For
+** example, assuming that index p is on t1(a):
+**
+** ... FROM t1 WHERE a > ? AND a < ? ...
+** |_____| |_____|
+** | |
+** pLower pUpper
+**
+** If either of the upper or lower bound is not present, then NULL is passed in
+** place of the corresponding WhereTerm.
+**
+** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
+** column subject to the range constraint. Or, equivalently, the number of
+** equality constraints optimized by the proposed index scan. For example,
+** assuming index p is on t1(a, b), and the SQL query is:
+**
+** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
+**
+** then nEq is set to 1 (as the range restricted column, b, is the second
+** left-most column of the index). Or, if the query is:
+**
+** ... FROM t1 WHERE a > ? AND a < ? ...
+**
+** then nEq is set to 0.
+**
+** When this function is called, *pnOut is set to the sqlite3LogEst() of the
+** number of rows that the index scan is expected to visit without
+** considering the range constraints. If nEq is 0, then *pnOut is the number of
+** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
+** to account for the range constraints pLower and pUpper.
+**
+** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
+** used, a single range inequality reduces the search space by a factor of 4.
+** and a pair of constraints (x>? AND x<?) reduces the expected number of
+** rows visited by a factor of 64.
+*/
+static int whereRangeScanEst(
+ Parse *pParse, /* Parsing & code generating context */
+ WhereLoopBuilder *pBuilder,
+ WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
+ WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
+ WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
+){
+ int rc = SQLITE_OK;
+ int nOut = pLoop->nOut;
+ LogEst nNew;
+
+#ifdef SQLITE_ENABLE_STAT4
+ Index *p = pLoop->u.btree.pIndex;
+ int nEq = pLoop->u.btree.nEq;
+
+ if( p->nSample>0 && ALWAYS(nEq<p->nSampleCol)
+ && OptimizationEnabled(pParse->db, SQLITE_Stat4)
+ ){
+ if( nEq==pBuilder->nRecValid ){
+ UnpackedRecord *pRec = pBuilder->pRec;
+ tRowcnt a[2];
+ int nBtm = pLoop->u.btree.nBtm;
+ int nTop = pLoop->u.btree.nTop;
+
+ /* Variable iLower will be set to the estimate of the number of rows in
+ ** the index that are less than the lower bound of the range query. The
+ ** lower bound being the concatenation of $P and $L, where $P is the
+ ** key-prefix formed by the nEq values matched against the nEq left-most
+ ** columns of the index, and $L is the value in pLower.
+ **
+ ** Or, if pLower is NULL or $L cannot be extracted from it (because it
+ ** is not a simple variable or literal value), the lower bound of the
+ ** range is $P. Due to a quirk in the way whereKeyStats() works, even
+ ** if $L is available, whereKeyStats() is called for both ($P) and
+ ** ($P:$L) and the larger of the two returned values is used.
+ **
+ ** Similarly, iUpper is to be set to the estimate of the number of rows
+ ** less than the upper bound of the range query. Where the upper bound
+ ** is either ($P) or ($P:$U). Again, even if $U is available, both values
+ ** of iUpper are requested of whereKeyStats() and the smaller used.
+ **
+ ** The number of rows between the two bounds is then just iUpper-iLower.
+ */
+ tRowcnt iLower; /* Rows less than the lower bound */
+ tRowcnt iUpper; /* Rows less than the upper bound */
+ int iLwrIdx = -2; /* aSample[] for the lower bound */
+ int iUprIdx = -1; /* aSample[] for the upper bound */
+
+ if( pRec ){
+ testcase( pRec->nField!=pBuilder->nRecValid );
+ pRec->nField = pBuilder->nRecValid;
+ }
+ /* Determine iLower and iUpper using ($P) only. */
+ if( nEq==0 ){
+ iLower = 0;
+ iUpper = p->nRowEst0;
+ }else{
+ /* Note: this call could be optimized away - since the same values must
+ ** have been requested when testing key $P in whereEqualScanEst(). */
+ whereKeyStats(pParse, p, pRec, 0, a);
+ iLower = a[0];
+ iUpper = a[0] + a[1];
+ }
+
+ assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
+ assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
+ assert( p->aSortOrder!=0 );
+ if( p->aSortOrder[nEq] ){
+ /* The roles of pLower and pUpper are swapped for a DESC index */
+ SWAP(WhereTerm*, pLower, pUpper);
+ SWAP(int, nBtm, nTop);
+ }
+
+ /* If possible, improve on the iLower estimate using ($P:$L). */
+ if( pLower ){
+ int n; /* Values extracted from pExpr */
+ Expr *pExpr = pLower->pExpr->pRight;
+ rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
+ if( rc==SQLITE_OK && n ){
+ tRowcnt iNew;
+ u16 mask = WO_GT|WO_LE;
+ if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
+ iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
+ iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
+ if( iNew>iLower ) iLower = iNew;
+ nOut--;
+ pLower = 0;
+ }
+ }
+
+ /* If possible, improve on the iUpper estimate using ($P:$U). */
+ if( pUpper ){
+ int n; /* Values extracted from pExpr */
+ Expr *pExpr = pUpper->pExpr->pRight;
+ rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
+ if( rc==SQLITE_OK && n ){
+ tRowcnt iNew;
+ u16 mask = WO_GT|WO_LE;
+ if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
+ iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
+ iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
+ if( iNew<iUpper ) iUpper = iNew;
+ nOut--;
+ pUpper = 0;
+ }
+ }
+
+ pBuilder->pRec = pRec;
+ if( rc==SQLITE_OK ){
+ if( iUpper>iLower ){
+ nNew = sqlite3LogEst(iUpper - iLower);
+ /* TUNING: If both iUpper and iLower are derived from the same
+ ** sample, then assume they are 4x more selective. This brings
+ ** the estimated selectivity more in line with what it would be
+ ** if estimated without the use of STAT4 tables. */
+ if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
+ }else{
+ nNew = 10; assert( 10==sqlite3LogEst(2) );
+ }
+ if( nNew<nOut ){
+ nOut = nNew;
+ }
+ WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
+ (u32)iLower, (u32)iUpper, nOut));
+ }
+ }else{
+ int bDone = 0;
+ rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
+ if( bDone ) return rc;
+ }
+ }
+#else
+ UNUSED_PARAMETER(pParse);
+ UNUSED_PARAMETER(pBuilder);
+ assert( pLower || pUpper );
+#endif
+ assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
+ nNew = whereRangeAdjust(pLower, nOut);
+ nNew = whereRangeAdjust(pUpper, nNew);
+
+ /* TUNING: If there is both an upper and lower limit and neither limit
+ ** has an application-defined likelihood(), assume the range is
+ ** reduced by an additional 75%. This means that, by default, an open-ended
+ ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
+ ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
+ ** match 1/64 of the index. */
+ if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
+ nNew -= 20;
+ }
+
+ nOut -= (pLower!=0) + (pUpper!=0);
+ if( nNew<10 ) nNew = 10;
+ if( nNew<nOut ) nOut = nNew;
+#if defined(WHERETRACE_ENABLED)
+ if( pLoop->nOut>nOut ){
+ WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
+ pLoop->nOut, nOut));
+ }
+#endif
+ pLoop->nOut = (LogEst)nOut;
+ return rc;
+}
+
+#ifdef SQLITE_ENABLE_STAT4
+/*
+** Estimate the number of rows that will be returned based on
+** an equality constraint x=VALUE and where that VALUE occurs in
+** the histogram data. This only works when x is the left-most
+** column of an index and sqlite_stat4 histogram data is available
+** for that index. When pExpr==NULL that means the constraint is
+** "x IS NULL" instead of "x=VALUE".
+**
+** Write the estimated row count into *pnRow and return SQLITE_OK.
+** If unable to make an estimate, leave *pnRow unchanged and return
+** non-zero.
+**
+** This routine can fail if it is unable to load a collating sequence
+** required for string comparison, or if unable to allocate memory
+** for a UTF conversion required for comparison. The error is stored
+** in the pParse structure.
+*/
+static int whereEqualScanEst(
+ Parse *pParse, /* Parsing & code generating context */
+ WhereLoopBuilder *pBuilder,
+ Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
+ tRowcnt *pnRow /* Write the revised row estimate here */
+){
+ Index *p = pBuilder->pNew->u.btree.pIndex;
+ int nEq = pBuilder->pNew->u.btree.nEq;
+ UnpackedRecord *pRec = pBuilder->pRec;
+ int rc; /* Subfunction return code */
+ tRowcnt a[2]; /* Statistics */
+ int bOk;
+
+ assert( nEq>=1 );
+ assert( nEq<=p->nColumn );
+ assert( p->aSample!=0 );
+ assert( p->nSample>0 );
+ assert( pBuilder->nRecValid<nEq );
+
+ /* If values are not available for all fields of the index to the left
+ ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
+ if( pBuilder->nRecValid<(nEq-1) ){
+ return SQLITE_NOTFOUND;
+ }
+
+ /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
+ ** below would return the same value. */
+ if( nEq>=p->nColumn ){
+ *pnRow = 1;
+ return SQLITE_OK;
+ }
+
+ rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
+ pBuilder->pRec = pRec;
+ if( rc!=SQLITE_OK ) return rc;
+ if( bOk==0 ) return SQLITE_NOTFOUND;
+ pBuilder->nRecValid = nEq;
+
+ whereKeyStats(pParse, p, pRec, 0, a);
+ WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
+ p->zName, nEq-1, (int)a[1]));
+ *pnRow = a[1];
+
+ return rc;
+}
+#endif /* SQLITE_ENABLE_STAT4 */
+
+#ifdef SQLITE_ENABLE_STAT4
+/*
+** Estimate the number of rows that will be returned based on
+** an IN constraint where the right-hand side of the IN operator
+** is a list of values. Example:
+**
+** WHERE x IN (1,2,3,4)
+**
+** Write the estimated row count into *pnRow and return SQLITE_OK.
+** If unable to make an estimate, leave *pnRow unchanged and return
+** non-zero.
+**
+** This routine can fail if it is unable to load a collating sequence
+** required for string comparison, or if unable to allocate memory
+** for a UTF conversion required for comparison. The error is stored
+** in the pParse structure.
+*/
+static int whereInScanEst(
+ Parse *pParse, /* Parsing & code generating context */
+ WhereLoopBuilder *pBuilder,
+ ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
+ tRowcnt *pnRow /* Write the revised row estimate here */
+){
+ Index *p = pBuilder->pNew->u.btree.pIndex;
+ i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
+ int nRecValid = pBuilder->nRecValid;
+ int rc = SQLITE_OK; /* Subfunction return code */
+ tRowcnt nEst; /* Number of rows for a single term */
+ tRowcnt nRowEst = 0; /* New estimate of the number of rows */
+ int i; /* Loop counter */
+
+ assert( p->aSample!=0 );
+ for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
+ nEst = nRow0;
+ rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
+ nRowEst += nEst;
+ pBuilder->nRecValid = nRecValid;
+ }
+
+ if( rc==SQLITE_OK ){
+ if( nRowEst > nRow0 ) nRowEst = nRow0;
+ *pnRow = nRowEst;
+ WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
+ }
+ assert( pBuilder->nRecValid==nRecValid );
+ return rc;
+}
+#endif /* SQLITE_ENABLE_STAT4 */
+
+
+#ifdef WHERETRACE_ENABLED
+/*
+** Print the content of a WhereTerm object
+*/
+SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){
+ if( pTerm==0 ){
+ sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
+ }else{
+ char zType[8];
+ char zLeft[50];
+ memcpy(zType, "....", 5);
+ if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
+ if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
+ if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
+ if( pTerm->wtFlags & TERM_CODED ) zType[3] = 'C';
+ if( pTerm->eOperator & WO_SINGLE ){
+ sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
+ pTerm->leftCursor, pTerm->u.x.leftColumn);
+ }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
+ sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
+ pTerm->u.pOrInfo->indexable);
+ }else{
+ sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
+ }
+ sqlite3DebugPrintf(
+ "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x",
+ iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags);
+ /* The 0x10000 .wheretrace flag causes extra information to be
+ ** shown about each Term */
+ if( sqlite3WhereTrace & 0x10000 ){
+ sqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx",
+ pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight);
+ }
+ if( pTerm->u.x.iField ){
+ sqlite3DebugPrintf(" iField=%d", pTerm->u.x.iField);
+ }
+ if( pTerm->iParent>=0 ){
+ sqlite3DebugPrintf(" iParent=%d", pTerm->iParent);
+ }
+ sqlite3DebugPrintf("\n");
+ sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
+ }
+}
+#endif
+
+#ifdef WHERETRACE_ENABLED
+/*
+** Show the complete content of a WhereClause
+*/
+SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
+ int i;
+ for(i=0; i<pWC->nTerm; i++){
+ sqlite3WhereTermPrint(&pWC->a[i], i);
+ }
+}
+#endif
+
+#ifdef WHERETRACE_ENABLED
+/*
+** Print a WhereLoop object for debugging purposes
+*/
+SQLITE_PRIVATE void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC){
+ WhereInfo *pWInfo = pWC->pWInfo;
+ int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
+ struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
+ Table *pTab = pItem->pTab;
+ Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
+ sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
+ p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
+ sqlite3DebugPrintf(" %12s",
+ pItem->zAlias ? pItem->zAlias : pTab->zName);
+ if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
+ const char *zName;
+ if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
+ if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
+ int i = sqlite3Strlen30(zName) - 1;
+ while( zName[i]!='_' ) i--;
+ zName += i;
+ }
+ sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
+ }else{
+ sqlite3DebugPrintf("%20s","");
+ }
+ }else{
+ char *z;
+ if( p->u.vtab.idxStr ){
+ z = sqlite3_mprintf("(%d,\"%s\",%#x)",
+ p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
+ }else{
+ z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
+ }
+ sqlite3DebugPrintf(" %-19s", z);
+ sqlite3_free(z);
+ }
+ if( p->wsFlags & WHERE_SKIPSCAN ){
+ sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
+ }else{
+ sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
+ }
+ sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
+ if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
+ int i;
+ for(i=0; i<p->nLTerm; i++){
+ sqlite3WhereTermPrint(p->aLTerm[i], i);
+ }
+ }
+}
+#endif
+
+/*
+** Convert bulk memory into a valid WhereLoop that can be passed
+** to whereLoopClear harmlessly.
+*/
+static void whereLoopInit(WhereLoop *p){
+ p->aLTerm = p->aLTermSpace;
+ p->nLTerm = 0;
+ p->nLSlot = ArraySize(p->aLTermSpace);
+ p->wsFlags = 0;
+}
+
+/*
+** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
+*/
+static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
+ if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
+ if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
+ sqlite3_free(p->u.vtab.idxStr);
+ p->u.vtab.needFree = 0;
+ p->u.vtab.idxStr = 0;
+ }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
+ sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
+ sqlite3DbFreeNN(db, p->u.btree.pIndex);
+ p->u.btree.pIndex = 0;
+ }
+ }
+}
+
+/*
+** Deallocate internal memory used by a WhereLoop object
+*/
+static void whereLoopClear(sqlite3 *db, WhereLoop *p){
+ if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
+ whereLoopClearUnion(db, p);
+ whereLoopInit(p);
+}
+
+/*
+** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
+*/
+static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
+ WhereTerm **paNew;
+ if( p->nLSlot>=n ) return SQLITE_OK;
+ n = (n+7)&~7;
+ paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
+ if( paNew==0 ) return SQLITE_NOMEM_BKPT;
+ memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
+ if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
+ p->aLTerm = paNew;
+ p->nLSlot = n;
+ return SQLITE_OK;
+}
+
+/*
+** Transfer content from the second pLoop into the first.
+*/
+static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
+ whereLoopClearUnion(db, pTo);
+ if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
+ memset(&pTo->u, 0, sizeof(pTo->u));
+ return SQLITE_NOMEM_BKPT;
+ }
+ memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
+ memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
+ if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
+ pFrom->u.vtab.needFree = 0;
+ }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
+ pFrom->u.btree.pIndex = 0;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Delete a WhereLoop object
+*/
+static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
+ whereLoopClear(db, p);
+ sqlite3DbFreeNN(db, p);
+}
+
+/*
+** Free a WhereInfo structure
+*/
+static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
+ int i;
+ assert( pWInfo!=0 );
+ for(i=0; i<pWInfo->nLevel; i++){
+ WhereLevel *pLevel = &pWInfo->a[i];
+ if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
+ sqlite3DbFree(db, pLevel->u.in.aInLoop);
+ }
+ }
+ sqlite3WhereClauseClear(&pWInfo->sWC);
+ while( pWInfo->pLoops ){
+ WhereLoop *p = pWInfo->pLoops;
+ pWInfo->pLoops = p->pNextLoop;
+ whereLoopDelete(db, p);
+ }
+ assert( pWInfo->pExprMods==0 );
+ sqlite3DbFreeNN(db, pWInfo);
+}
+
+/*
+** Return TRUE if all of the following are true:
+**
+** (1) X has the same or lower cost that Y
+** (2) X uses fewer WHERE clause terms than Y
+** (3) Every WHERE clause term used by X is also used by Y
+** (4) X skips at least as many columns as Y
+** (5) If X is a covering index, than Y is too
+**
+** Conditions (2) and (3) mean that X is a "proper subset" of Y.
+** If X is a proper subset of Y then Y is a better choice and ought
+** to have a lower cost. This routine returns TRUE when that cost
+** relationship is inverted and needs to be adjusted. Constraint (4)
+** was added because if X uses skip-scan less than Y it still might
+** deserve a lower cost even if it is a proper subset of Y. Constraint (5)
+** was added because a covering index probably deserves to have a lower cost
+** than a non-covering index even if it is a proper subset.
+*/
+static int whereLoopCheaperProperSubset(
+ const WhereLoop *pX, /* First WhereLoop to compare */
+ const WhereLoop *pY /* Compare against this WhereLoop */
+){
+ int i, j;
+ if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
+ return 0; /* X is not a subset of Y */
+ }
+ if( pY->nSkip > pX->nSkip ) return 0;
+ if( pX->rRun >= pY->rRun ){
+ if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
+ if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
+ }
+ for(i=pX->nLTerm-1; i>=0; i--){
+ if( pX->aLTerm[i]==0 ) continue;
+ for(j=pY->nLTerm-1; j>=0; j--){
+ if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
+ }
+ if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
+ }
+ if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
+ && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
+ return 0; /* Constraint (5) */
+ }
+ return 1; /* All conditions meet */
+}
+
+/*
+** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
+** that:
+**
+** (1) pTemplate costs less than any other WhereLoops that are a proper
+** subset of pTemplate
+**
+** (2) pTemplate costs more than any other WhereLoops for which pTemplate
+** is a proper subset.
+**
+** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
+** WHERE clause terms than Y and that every WHERE clause term used by X is
+** also used by Y.
+*/
+static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
+ if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
+ for(; p; p=p->pNextLoop){
+ if( p->iTab!=pTemplate->iTab ) continue;
+ if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
+ if( whereLoopCheaperProperSubset(p, pTemplate) ){
+ /* Adjust pTemplate cost downward so that it is cheaper than its
+ ** subset p. */
+ WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
+ pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
+ pTemplate->rRun = p->rRun;
+ pTemplate->nOut = p->nOut - 1;
+ }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
+ /* Adjust pTemplate cost upward so that it is costlier than p since
+ ** pTemplate is a proper subset of p */
+ WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
+ pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
+ pTemplate->rRun = p->rRun;
+ pTemplate->nOut = p->nOut + 1;
+ }
+ }
+}
+
+/*
+** Search the list of WhereLoops in *ppPrev looking for one that can be
+** replaced by pTemplate.
+**
+** Return NULL if pTemplate does not belong on the WhereLoop list.
+** In other words if pTemplate ought to be dropped from further consideration.
+**
+** If pX is a WhereLoop that pTemplate can replace, then return the
+** link that points to pX.
+**
+** If pTemplate cannot replace any existing element of the list but needs
+** to be added to the list as a new entry, then return a pointer to the
+** tail of the list.
+*/
+static WhereLoop **whereLoopFindLesser(
+ WhereLoop **ppPrev,
+ const WhereLoop *pTemplate
+){
+ WhereLoop *p;
+ for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
+ if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
+ /* If either the iTab or iSortIdx values for two WhereLoop are different
+ ** then those WhereLoops need to be considered separately. Neither is
+ ** a candidate to replace the other. */
+ continue;
+ }
+ /* In the current implementation, the rSetup value is either zero
+ ** or the cost of building an automatic index (NlogN) and the NlogN
+ ** is the same for compatible WhereLoops. */
+ assert( p->rSetup==0 || pTemplate->rSetup==0
+ || p->rSetup==pTemplate->rSetup );
+
+ /* whereLoopAddBtree() always generates and inserts the automatic index
+ ** case first. Hence compatible candidate WhereLoops never have a larger
+ ** rSetup. Call this SETUP-INVARIANT */
+ assert( p->rSetup>=pTemplate->rSetup );
+
+ /* Any loop using an appliation-defined index (or PRIMARY KEY or
+ ** UNIQUE constraint) with one or more == constraints is better
+ ** than an automatic index. Unless it is a skip-scan. */
+ if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
+ && (pTemplate->nSkip)==0
+ && (pTemplate->wsFlags & WHERE_INDEXED)!=0
+ && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
+ && (p->prereq & pTemplate->prereq)==pTemplate->prereq
+ ){
+ break;
+ }
+
+ /* If existing WhereLoop p is better than pTemplate, pTemplate can be
+ ** discarded. WhereLoop p is better if:
+ ** (1) p has no more dependencies than pTemplate, and
+ ** (2) p has an equal or lower cost than pTemplate
+ */
+ if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
+ && p->rSetup<=pTemplate->rSetup /* (2a) */
+ && p->rRun<=pTemplate->rRun /* (2b) */
+ && p->nOut<=pTemplate->nOut /* (2c) */
+ ){
+ return 0; /* Discard pTemplate */
+ }
+
+ /* If pTemplate is always better than p, then cause p to be overwritten
+ ** with pTemplate. pTemplate is better than p if:
+ ** (1) pTemplate has no more dependences than p, and
+ ** (2) pTemplate has an equal or lower cost than p.
+ */
+ if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
+ && p->rRun>=pTemplate->rRun /* (2a) */
+ && p->nOut>=pTemplate->nOut /* (2b) */
+ ){
+ assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
+ break; /* Cause p to be overwritten by pTemplate */
+ }
+ }
+ return ppPrev;
+}
+
+/*
+** Insert or replace a WhereLoop entry using the template supplied.
+**
+** An existing WhereLoop entry might be overwritten if the new template
+** is better and has fewer dependencies. Or the template will be ignored
+** and no insert will occur if an existing WhereLoop is faster and has
+** fewer dependencies than the template. Otherwise a new WhereLoop is
+** added based on the template.
+**
+** If pBuilder->pOrSet is not NULL then we care about only the
+** prerequisites and rRun and nOut costs of the N best loops. That
+** information is gathered in the pBuilder->pOrSet object. This special
+** processing mode is used only for OR clause processing.
+**
+** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
+** still might overwrite similar loops with the new template if the
+** new template is better. Loops may be overwritten if the following
+** conditions are met:
+**
+** (1) They have the same iTab.
+** (2) They have the same iSortIdx.
+** (3) The template has same or fewer dependencies than the current loop
+** (4) The template has the same or lower cost than the current loop
+*/
+static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
+ WhereLoop **ppPrev, *p;
+ WhereInfo *pWInfo = pBuilder->pWInfo;
+ sqlite3 *db = pWInfo->pParse->db;
+ int rc;
+
+ /* Stop the search once we hit the query planner search limit */
+ if( pBuilder->iPlanLimit==0 ){
+ WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n"));
+ if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0;
+ return SQLITE_DONE;
+ }
+ pBuilder->iPlanLimit--;
+
+ whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
+
+ /* If pBuilder->pOrSet is defined, then only keep track of the costs
+ ** and prereqs.
+ */
+ if( pBuilder->pOrSet!=0 ){
+ if( pTemplate->nLTerm ){
+#if WHERETRACE_ENABLED
+ u16 n = pBuilder->pOrSet->n;
+ int x =
+#endif
+ whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
+ pTemplate->nOut);
+#if WHERETRACE_ENABLED /* 0x8 */
+ if( sqlite3WhereTrace & 0x8 ){
+ sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
+ sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
+ }
+#endif
+ }
+ return SQLITE_OK;
+ }
+
+ /* Look for an existing WhereLoop to replace with pTemplate
+ */
+ ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
+
+ if( ppPrev==0 ){
+ /* There already exists a WhereLoop on the list that is better
+ ** than pTemplate, so just ignore pTemplate */
+#if WHERETRACE_ENABLED /* 0x8 */
+ if( sqlite3WhereTrace & 0x8 ){
+ sqlite3DebugPrintf(" skip: ");
+ sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
+ }
+#endif
+ return SQLITE_OK;
+ }else{
+ p = *ppPrev;
+ }
+
+ /* If we reach this point it means that either p[] should be overwritten
+ ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
+ ** WhereLoop and insert it.
+ */
+#if WHERETRACE_ENABLED /* 0x8 */
+ if( sqlite3WhereTrace & 0x8 ){
+ if( p!=0 ){
+ sqlite3DebugPrintf("replace: ");
+ sqlite3WhereLoopPrint(p, pBuilder->pWC);
+ sqlite3DebugPrintf(" with: ");
+ }else{
+ sqlite3DebugPrintf(" add: ");
+ }
+ sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
+ }
+#endif
+ if( p==0 ){
+ /* Allocate a new WhereLoop to add to the end of the list */
+ *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
+ if( p==0 ) return SQLITE_NOMEM_BKPT;
+ whereLoopInit(p);
+ p->pNextLoop = 0;
+ }else{
+ /* We will be overwriting WhereLoop p[]. But before we do, first
+ ** go through the rest of the list and delete any other entries besides
+ ** p[] that are also supplated by pTemplate */
+ WhereLoop **ppTail = &p->pNextLoop;
+ WhereLoop *pToDel;
+ while( *ppTail ){
+ ppTail = whereLoopFindLesser(ppTail, pTemplate);
+ if( ppTail==0 ) break;
+ pToDel = *ppTail;
+ if( pToDel==0 ) break;
+ *ppTail = pToDel->pNextLoop;
+#if WHERETRACE_ENABLED /* 0x8 */
+ if( sqlite3WhereTrace & 0x8 ){
+ sqlite3DebugPrintf(" delete: ");
+ sqlite3WhereLoopPrint(pToDel, pBuilder->pWC);
+ }
+#endif
+ whereLoopDelete(db, pToDel);
+ }
+ }
+ rc = whereLoopXfer(db, p, pTemplate);
+ if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
+ Index *pIndex = p->u.btree.pIndex;
+ if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){
+ p->u.btree.pIndex = 0;
+ }
+ }
+ return rc;
+}
+
+/*
+** Adjust the WhereLoop.nOut value downward to account for terms of the
+** WHERE clause that reference the loop but which are not used by an
+** index.
+*
+** For every WHERE clause term that is not used by the index
+** and which has a truth probability assigned by one of the likelihood(),
+** likely(), or unlikely() SQL functions, reduce the estimated number
+** of output rows by the probability specified.
+**
+** TUNING: For every WHERE clause term that is not used by the index
+** and which does not have an assigned truth probability, heuristics
+** described below are used to try to estimate the truth probability.
+** TODO --> Perhaps this is something that could be improved by better
+** table statistics.
+**
+** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
+** value corresponds to -1 in LogEst notation, so this means decrement
+** the WhereLoop.nOut field for every such WHERE clause term.
+**
+** Heuristic 2: If there exists one or more WHERE clause terms of the
+** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
+** final output row estimate is no greater than 1/4 of the total number
+** of rows in the table. In other words, assume that x==EXPR will filter
+** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
+** "x" column is boolean or else -1 or 0 or 1 is a common default value
+** on the "x" column and so in that case only cap the output row estimate
+** at 1/2 instead of 1/4.
+*/
+static void whereLoopOutputAdjust(
+ WhereClause *pWC, /* The WHERE clause */
+ WhereLoop *pLoop, /* The loop to adjust downward */
+ LogEst nRow /* Number of rows in the entire table */
+){
+ WhereTerm *pTerm, *pX;
+ Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
+ int i, j;
+ LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
+
+ assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
+ for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
+ assert( pTerm!=0 );
+ if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
+ if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
+ if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
+ for(j=pLoop->nLTerm-1; j>=0; j--){
+ pX = pLoop->aLTerm[j];
+ if( pX==0 ) continue;
+ if( pX==pTerm ) break;
+ if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
+ }
+ if( j<0 ){
+ if( pTerm->truthProb<=0 ){
+ /* If a truth probability is specified using the likelihood() hints,
+ ** then use the probability provided by the application. */
+ pLoop->nOut += pTerm->truthProb;
+ }else{
+ /* In the absence of explicit truth probabilities, use heuristics to
+ ** guess a reasonable truth probability. */
+ pLoop->nOut--;
+ if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0
+ && (pTerm->wtFlags & TERM_HIGHTRUTH)==0 /* tag-20200224-1 */
+ ){
+ Expr *pRight = pTerm->pExpr->pRight;
+ int k = 0;
+ testcase( pTerm->pExpr->op==TK_IS );
+ if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
+ k = 10;
+ }else{
+ k = 20;
+ }
+ if( iReduce<k ){
+ pTerm->wtFlags |= TERM_HEURTRUTH;
+ iReduce = k;
+ }
+ }
+ }
+ }
+ }
+ if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
+}
+
+/*
+** Term pTerm is a vector range comparison operation. The first comparison
+** in the vector can be optimized using column nEq of the index. This
+** function returns the total number of vector elements that can be used
+** as part of the range comparison.
+**
+** For example, if the query is:
+**
+** WHERE a = ? AND (b, c, d) > (?, ?, ?)
+**
+** and the index:
+**
+** CREATE INDEX ... ON (a, b, c, d, e)
+**
+** then this function would be invoked with nEq=1. The value returned in
+** this case is 3.
+*/
+static int whereRangeVectorLen(
+ Parse *pParse, /* Parsing context */
+ int iCur, /* Cursor open on pIdx */
+ Index *pIdx, /* The index to be used for a inequality constraint */
+ int nEq, /* Number of prior equality constraints on same index */
+ WhereTerm *pTerm /* The vector inequality constraint */
+){
+ int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
+ int i;
+
+ nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
+ for(i=1; i<nCmp; i++){
+ /* Test if comparison i of pTerm is compatible with column (i+nEq)
+ ** of the index. If not, exit the loop. */
+ char aff; /* Comparison affinity */
+ char idxaff = 0; /* Indexed columns affinity */
+ CollSeq *pColl; /* Comparison collation sequence */
+ Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
+ Expr *pRhs = pTerm->pExpr->pRight;
+ if( pRhs->flags & EP_xIsSelect ){
+ pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
+ }else{
+ pRhs = pRhs->x.pList->a[i].pExpr;
+ }
+
+ /* Check that the LHS of the comparison is a column reference to
+ ** the right column of the right source table. And that the sort
+ ** order of the index column is the same as the sort order of the
+ ** leftmost index column. */
+ if( pLhs->op!=TK_COLUMN
+ || pLhs->iTable!=iCur
+ || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
+ || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
+ ){
+ break;
+ }
+
+ testcase( pLhs->iColumn==XN_ROWID );
+ aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
+ idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
+ if( aff!=idxaff ) break;
+
+ pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
+ if( pColl==0 ) break;
+ if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
+ }
+ return i;
+}
+
+/*
+** Adjust the cost C by the costMult facter T. This only occurs if
+** compiled with -DSQLITE_ENABLE_COSTMULT
+*/
+#ifdef SQLITE_ENABLE_COSTMULT
+# define ApplyCostMultiplier(C,T) C += T
+#else
+# define ApplyCostMultiplier(C,T)
+#endif
+
+/*
+** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
+** index pIndex. Try to match one more.
+**
+** When this function is called, pBuilder->pNew->nOut contains the
+** number of rows expected to be visited by filtering using the nEq
+** terms only. If it is modified, this value is restored before this
+** function returns.
+**
+** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is
+** a fake index used for the INTEGER PRIMARY KEY.
+*/
+static int whereLoopAddBtreeIndex(
+ WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
+ struct SrcList_item *pSrc, /* FROM clause term being analyzed */
+ Index *pProbe, /* An index on pSrc */
+ LogEst nInMul /* log(Number of iterations due to IN) */
+){
+ WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
+ Parse *pParse = pWInfo->pParse; /* Parsing context */
+ sqlite3 *db = pParse->db; /* Database connection malloc context */
+ WhereLoop *pNew; /* Template WhereLoop under construction */
+ WhereTerm *pTerm; /* A WhereTerm under consideration */
+ int opMask; /* Valid operators for constraints */
+ WhereScan scan; /* Iterator for WHERE terms */
+ Bitmask saved_prereq; /* Original value of pNew->prereq */
+ u16 saved_nLTerm; /* Original value of pNew->nLTerm */
+ u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
+ u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
+ u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
+ u16 saved_nSkip; /* Original value of pNew->nSkip */
+ u32 saved_wsFlags; /* Original value of pNew->wsFlags */
+ LogEst saved_nOut; /* Original value of pNew->nOut */
+ int rc = SQLITE_OK; /* Return code */
+ LogEst rSize; /* Number of rows in the table */
+ LogEst rLogSize; /* Logarithm of table size */
+ WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
+
+ pNew = pBuilder->pNew;
+ if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
+ WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d, nSkip=%d\n",
+ pProbe->pTable->zName,pProbe->zName,
+ pNew->u.btree.nEq, pNew->nSkip));
+
+ assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
+ assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
+ if( pNew->wsFlags & WHERE_BTM_LIMIT ){
+ opMask = WO_LT|WO_LE;
+ }else{
+ assert( pNew->u.btree.nBtm==0 );
+ opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
+ }
+ if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
+
+ assert( pNew->u.btree.nEq<pProbe->nColumn );
+
+ saved_nEq = pNew->u.btree.nEq;
+ saved_nBtm = pNew->u.btree.nBtm;
+ saved_nTop = pNew->u.btree.nTop;
+ saved_nSkip = pNew->nSkip;
+ saved_nLTerm = pNew->nLTerm;
+ saved_wsFlags = pNew->wsFlags;
+ saved_prereq = pNew->prereq;
+ saved_nOut = pNew->nOut;
+ pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
+ opMask, pProbe);
+ pNew->rSetup = 0;
+ rSize = pProbe->aiRowLogEst[0];
+ rLogSize = estLog(rSize);
+ for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
+ u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
+ LogEst rCostIdx;
+ LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
+ int nIn = 0;
+#ifdef SQLITE_ENABLE_STAT4
+ int nRecValid = pBuilder->nRecValid;
+#endif
+ if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
+ && indexColumnNotNull(pProbe, saved_nEq)
+ ){
+ continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
+ }
+ if( pTerm->prereqRight & pNew->maskSelf ) continue;
+
+ /* Do not allow the upper bound of a LIKE optimization range constraint
+ ** to mix with a lower range bound from some other source */
+ if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
+
+ /* tag-20191211-001: Do not allow constraints from the WHERE clause to
+ ** be used by the right table of a LEFT JOIN. Only constraints in the
+ ** ON clause are allowed. See tag-20191211-002 for the vtab equivalent. */
+ if( (pSrc->fg.jointype & JT_LEFT)!=0
+ && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
+ ){
+ continue;
+ }
+
+ if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
+ pBuilder->bldFlags1 |= SQLITE_BLDF1_UNIQUE;
+ }else{
+ pBuilder->bldFlags1 |= SQLITE_BLDF1_INDEXED;
+ }
+ pNew->wsFlags = saved_wsFlags;
+ pNew->u.btree.nEq = saved_nEq;
+ pNew->u.btree.nBtm = saved_nBtm;
+ pNew->u.btree.nTop = saved_nTop;
+ pNew->nLTerm = saved_nLTerm;
+ if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
+ pNew->aLTerm[pNew->nLTerm++] = pTerm;
+ pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
+
+ assert( nInMul==0
+ || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
+ || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
+ || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
+ );
+
+ if( eOp & WO_IN ){
+ Expr *pExpr = pTerm->pExpr;
+ if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+ /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
+ int i;
+ nIn = 46; assert( 46==sqlite3LogEst(25) );
+
+ /* The expression may actually be of the form (x, y) IN (SELECT...).
+ ** In this case there is a separate term for each of (x) and (y).
+ ** However, the nIn multiplier should only be applied once, not once
+ ** for each such term. The following loop checks that pTerm is the
+ ** first such term in use, and sets nIn back to 0 if it is not. */
+ for(i=0; i<pNew->nLTerm-1; i++){
+ if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
+ }
+ }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
+ /* "x IN (value, value, ...)" */
+ nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
+ }
+ if( pProbe->hasStat1 && rLogSize>=10 ){
+ LogEst M, logK, safetyMargin;
+ /* Let:
+ ** N = the total number of rows in the table
+ ** K = the number of entries on the RHS of the IN operator
+ ** M = the number of rows in the table that match terms to the
+ ** to the left in the same index. If the IN operator is on
+ ** the left-most index column, M==N.
+ **
+ ** Given the definitions above, it is better to omit the IN operator
+ ** from the index lookup and instead do a scan of the M elements,
+ ** testing each scanned row against the IN operator separately, if:
+ **
+ ** M*log(K) < K*log(N)
+ **
+ ** Our estimates for M, K, and N might be inaccurate, so we build in
+ ** a safety margin of 2 (LogEst: 10) that favors using the IN operator
+ ** with the index, as using an index has better worst-case behavior.
+ ** If we do not have real sqlite_stat1 data, always prefer to use
+ ** the index. Do not bother with this optimization on very small
+ ** tables (less than 2 rows) as it is pointless in that case.
+ */
+ M = pProbe->aiRowLogEst[saved_nEq];
+ logK = estLog(nIn);
+ safetyMargin = 10; /* TUNING: extra weight for indexed IN */
+ if( M + logK + safetyMargin < nIn + rLogSize ){
+ WHERETRACE(0x40,
+ ("Scan preferred over IN operator on column %d of \"%s\" (%d<%d)\n",
+ saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
+ pNew->wsFlags |= WHERE_IN_SEEKSCAN;
+ }else{
+ WHERETRACE(0x40,
+ ("IN operator preferred on column %d of \"%s\" (%d>=%d)\n",
+ saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
+ }
+ }
+ pNew->wsFlags |= WHERE_COLUMN_IN;
+ }else if( eOp & (WO_EQ|WO_IS) ){
+ int iCol = pProbe->aiColumn[saved_nEq];
+ pNew->wsFlags |= WHERE_COLUMN_EQ;
+ assert( saved_nEq==pNew->u.btree.nEq );
+ if( iCol==XN_ROWID
+ || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
+ ){
+ if( iCol==XN_ROWID || pProbe->uniqNotNull
+ || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
+ ){
+ pNew->wsFlags |= WHERE_ONEROW;
+ }else{
+ pNew->wsFlags |= WHERE_UNQ_WANTED;
+ }
+ }
+ }else if( eOp & WO_ISNULL ){
+ pNew->wsFlags |= WHERE_COLUMN_NULL;
+ }else if( eOp & (WO_GT|WO_GE) ){
+ testcase( eOp & WO_GT );
+ testcase( eOp & WO_GE );
+ pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
+ pNew->u.btree.nBtm = whereRangeVectorLen(
+ pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
+ );
+ pBtm = pTerm;
+ pTop = 0;
+ if( pTerm->wtFlags & TERM_LIKEOPT ){
+ /* Range contraints that come from the LIKE optimization are
+ ** always used in pairs. */
+ pTop = &pTerm[1];
+ assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
+ assert( pTop->wtFlags & TERM_LIKEOPT );
+ assert( pTop->eOperator==WO_LT );
+ if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
+ pNew->aLTerm[pNew->nLTerm++] = pTop;
+ pNew->wsFlags |= WHERE_TOP_LIMIT;
+ pNew->u.btree.nTop = 1;
+ }
+ }else{
+ assert( eOp & (WO_LT|WO_LE) );
+ testcase( eOp & WO_LT );
+ testcase( eOp & WO_LE );
+ pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
+ pNew->u.btree.nTop = whereRangeVectorLen(
+ pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
+ );
+ pTop = pTerm;
+ pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
+ pNew->aLTerm[pNew->nLTerm-2] : 0;
+ }
+
+ /* At this point pNew->nOut is set to the number of rows expected to
+ ** be visited by the index scan before considering term pTerm, or the
+ ** values of nIn and nInMul. In other words, assuming that all
+ ** "x IN(...)" terms are replaced with "x = ?". This block updates
+ ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
+ assert( pNew->nOut==saved_nOut );
+ if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
+ /* Adjust nOut using stat4 data. Or, if there is no stat4
+ ** data, using some other estimate. */
+ whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
+ }else{
+ int nEq = ++pNew->u.btree.nEq;
+ assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
+
+ assert( pNew->nOut==saved_nOut );
+ if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
+ assert( (eOp & WO_IN) || nIn==0 );
+ testcase( eOp & WO_IN );
+ pNew->nOut += pTerm->truthProb;
+ pNew->nOut -= nIn;
+ }else{
+#ifdef SQLITE_ENABLE_STAT4
+ tRowcnt nOut = 0;
+ if( nInMul==0
+ && pProbe->nSample
+ && pNew->u.btree.nEq<=pProbe->nSampleCol
+ && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
+ && OptimizationEnabled(db, SQLITE_Stat4)
+ ){
+ Expr *pExpr = pTerm->pExpr;
+ if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
+ testcase( eOp & WO_EQ );
+ testcase( eOp & WO_IS );
+ testcase( eOp & WO_ISNULL );
+ rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
+ }else{
+ rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
+ }
+ if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
+ if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
+ if( nOut ){
+ pNew->nOut = sqlite3LogEst(nOut);
+ if( nEq==1
+ /* TUNING: Mark terms as "low selectivity" if they seem likely
+ ** to be true for half or more of the rows in the table.
+ ** See tag-202002240-1 */
+ && pNew->nOut+10 > pProbe->aiRowLogEst[0]
+ ){
+#if WHERETRACE_ENABLED /* 0x01 */
+ if( sqlite3WhereTrace & 0x01 ){
+ sqlite3DebugPrintf(
+ "STAT4 determines term has low selectivity:\n");
+ sqlite3WhereTermPrint(pTerm, 999);
+ }
+#endif
+ pTerm->wtFlags |= TERM_HIGHTRUTH;
+ if( pTerm->wtFlags & TERM_HEURTRUTH ){
+ /* If the term has previously been used with an assumption of
+ ** higher selectivity, then set the flag to rerun the
+ ** loop computations. */
+ pBuilder->bldFlags2 |= SQLITE_BLDF2_2NDPASS;
+ }
+ }
+ if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
+ pNew->nOut -= nIn;
+ }
+ }
+ if( nOut==0 )
+#endif
+ {
+ pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
+ if( eOp & WO_ISNULL ){
+ /* TUNING: If there is no likelihood() value, assume that a
+ ** "col IS NULL" expression matches twice as many rows
+ ** as (col=?). */
+ pNew->nOut += 10;
+ }
+ }
+ }
+ }
+
+ /* Set rCostIdx to the cost of visiting selected rows in index. Add
+ ** it to pNew->rRun, which is currently set to the cost of the index
+ ** seek only. Then, if this is a non-covering index, add the cost of
+ ** visiting the rows in the main table. */
+ assert( pSrc->pTab->szTabRow>0 );
+ rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
+ pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
+ if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
+ pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
+ }
+ ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
+
+ nOutUnadjusted = pNew->nOut;
+ pNew->rRun += nInMul + nIn;
+ pNew->nOut += nInMul + nIn;
+ whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
+ rc = whereLoopInsert(pBuilder, pNew);
+
+ if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
+ pNew->nOut = saved_nOut;
+ }else{
+ pNew->nOut = nOutUnadjusted;
+ }
+
+ if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
+ && pNew->u.btree.nEq<pProbe->nColumn
+ ){
+ whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
+ }
+ pNew->nOut = saved_nOut;
+#ifdef SQLITE_ENABLE_STAT4
+ pBuilder->nRecValid = nRecValid;
+#endif
+ }
+ pNew->prereq = saved_prereq;
+ pNew->u.btree.nEq = saved_nEq;
+ pNew->u.btree.nBtm = saved_nBtm;
+ pNew->u.btree.nTop = saved_nTop;
+ pNew->nSkip = saved_nSkip;
+ pNew->wsFlags = saved_wsFlags;
+ pNew->nOut = saved_nOut;
+ pNew->nLTerm = saved_nLTerm;
+
+ /* Consider using a skip-scan if there are no WHERE clause constraints
+ ** available for the left-most terms of the index, and if the average
+ ** number of repeats in the left-most terms is at least 18.
+ **
+ ** The magic number 18 is selected on the basis that scanning 17 rows
+ ** is almost always quicker than an index seek (even though if the index
+ ** contains fewer than 2^17 rows we assume otherwise in other parts of
+ ** the code). And, even if it is not, it should not be too much slower.
+ ** On the other hand, the extra seeks could end up being significantly
+ ** more expensive. */
+ assert( 42==sqlite3LogEst(18) );
+ if( saved_nEq==saved_nSkip
+ && saved_nEq+1<pProbe->nKeyCol
+ && saved_nEq==pNew->nLTerm
+ && pProbe->noSkipScan==0
+ && pProbe->hasStat1!=0
+ && OptimizationEnabled(db, SQLITE_SkipScan)
+ && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
+ && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
+ ){
+ LogEst nIter;
+ pNew->u.btree.nEq++;
+ pNew->nSkip++;
+ pNew->aLTerm[pNew->nLTerm++] = 0;
+ pNew->wsFlags |= WHERE_SKIPSCAN;
+ nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
+ pNew->nOut -= nIter;
+ /* TUNING: Because uncertainties in the estimates for skip-scan queries,
+ ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
+ nIter += 5;
+ whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
+ pNew->nOut = saved_nOut;
+ pNew->u.btree.nEq = saved_nEq;
+ pNew->nSkip = saved_nSkip;
+ pNew->wsFlags = saved_wsFlags;
+ }
+
+ WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n",
+ pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));
+ return rc;
+}
+
+/*
+** Return True if it is possible that pIndex might be useful in
+** implementing the ORDER BY clause in pBuilder.
+**
+** Return False if pBuilder does not contain an ORDER BY clause or
+** if there is no way for pIndex to be useful in implementing that
+** ORDER BY clause.
+*/
+static int indexMightHelpWithOrderBy(
+ WhereLoopBuilder *pBuilder,
+ Index *pIndex,
+ int iCursor
+){
+ ExprList *pOB;
+ ExprList *aColExpr;
+ int ii, jj;
+
+ if( pIndex->bUnordered ) return 0;
+ if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
+ for(ii=0; ii<pOB->nExpr; ii++){
+ Expr *pExpr = sqlite3ExprSkipCollateAndLikely(pOB->a[ii].pExpr);
+ if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
+ if( pExpr->iColumn<0 ) return 1;
+ for(jj=0; jj<pIndex->nKeyCol; jj++){
+ if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
+ }
+ }else if( (aColExpr = pIndex->aColExpr)!=0 ){
+ for(jj=0; jj<pIndex->nKeyCol; jj++){
+ if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
+ if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
+ return 1;
+ }
+ }
+ }
+ }
+ return 0;
+}
+
+/* Check to see if a partial index with pPartIndexWhere can be used
+** in the current query. Return true if it can be and false if not.
+*/
+static int whereUsablePartialIndex(
+ int iTab, /* The table for which we want an index */
+ int isLeft, /* True if iTab is the right table of a LEFT JOIN */
+ WhereClause *pWC, /* The WHERE clause of the query */
+ Expr *pWhere /* The WHERE clause from the partial index */
+){
+ int i;
+ WhereTerm *pTerm;
+ Parse *pParse = pWC->pWInfo->pParse;
+ while( pWhere->op==TK_AND ){
+ if( !whereUsablePartialIndex(iTab,isLeft,pWC,pWhere->pLeft) ) return 0;
+ pWhere = pWhere->pRight;
+ }
+ if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
+ for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
+ Expr *pExpr;
+ pExpr = pTerm->pExpr;
+ if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
+ && (isLeft==0 || ExprHasProperty(pExpr, EP_FromJoin))
+ && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
+ ){
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/*
+** Add all WhereLoop objects for a single table of the join where the table
+** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
+** a b-tree table, not a virtual table.
+**
+** The costs (WhereLoop.rRun) of the b-tree loops added by this function
+** are calculated as follows:
+**
+** For a full scan, assuming the table (or index) contains nRow rows:
+**
+** cost = nRow * 3.0 // full-table scan
+** cost = nRow * K // scan of covering index
+** cost = nRow * (K+3.0) // scan of non-covering index
+**
+** where K is a value between 1.1 and 3.0 set based on the relative
+** estimated average size of the index and table records.
+**
+** For an index scan, where nVisit is the number of index rows visited
+** by the scan, and nSeek is the number of seek operations required on
+** the index b-tree:
+**
+** cost = nSeek * (log(nRow) + K * nVisit) // covering index
+** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
+**
+** Normally, nSeek is 1. nSeek values greater than 1 come about if the
+** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
+** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
+**
+** The estimated values (nRow, nVisit, nSeek) often contain a large amount
+** of uncertainty. For this reason, scoring is designed to pick plans that
+** "do the least harm" if the estimates are inaccurate. For example, a
+** log(nRow) factor is omitted from a non-covering index scan in order to
+** bias the scoring in favor of using an index, since the worst-case
+** performance of using an index is far better than the worst-case performance
+** of a full table scan.
+*/
+static int whereLoopAddBtree(
+ WhereLoopBuilder *pBuilder, /* WHERE clause information */
+ Bitmask mPrereq /* Extra prerequesites for using this table */
+){
+ WhereInfo *pWInfo; /* WHERE analysis context */
+ Index *pProbe; /* An index we are evaluating */
+ Index sPk; /* A fake index object for the primary key */
+ LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
+ i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
+ SrcList *pTabList; /* The FROM clause */
+ struct SrcList_item *pSrc; /* The FROM clause btree term to add */
+ WhereLoop *pNew; /* Template WhereLoop object */
+ int rc = SQLITE_OK; /* Return code */
+ int iSortIdx = 1; /* Index number */
+ int b; /* A boolean value */
+ LogEst rSize; /* number of rows in the table */
+ LogEst rLogSize; /* Logarithm of the number of rows in the table */
+ WhereClause *pWC; /* The parsed WHERE clause */
+ Table *pTab; /* Table being queried */
+
+ pNew = pBuilder->pNew;
+ pWInfo = pBuilder->pWInfo;
+ pTabList = pWInfo->pTabList;
+ pSrc = pTabList->a + pNew->iTab;
+ pTab = pSrc->pTab;
+ pWC = pBuilder->pWC;
+ assert( !IsVirtual(pSrc->pTab) );
+
+ if( pSrc->pIBIndex ){
+ /* An INDEXED BY clause specifies a particular index to use */
+ pProbe = pSrc->pIBIndex;
+ }else if( !HasRowid(pTab) ){
+ pProbe = pTab->pIndex;
+ }else{
+ /* There is no INDEXED BY clause. Create a fake Index object in local
+ ** variable sPk to represent the rowid primary key index. Make this
+ ** fake index the first in a chain of Index objects with all of the real
+ ** indices to follow */
+ Index *pFirst; /* First of real indices on the table */
+ memset(&sPk, 0, sizeof(Index));
+ sPk.nKeyCol = 1;
+ sPk.nColumn = 1;
+ sPk.aiColumn = &aiColumnPk;
+ sPk.aiRowLogEst = aiRowEstPk;
+ sPk.onError = OE_Replace;
+ sPk.pTable = pTab;
+ sPk.szIdxRow = pTab->szTabRow;
+ sPk.idxType = SQLITE_IDXTYPE_IPK;
+ aiRowEstPk[0] = pTab->nRowLogEst;
+ aiRowEstPk[1] = 0;
+ pFirst = pSrc->pTab->pIndex;
+ if( pSrc->fg.notIndexed==0 ){
+ /* The real indices of the table are only considered if the
+ ** NOT INDEXED qualifier is omitted from the FROM clause */
+ sPk.pNext = pFirst;
+ }
+ pProbe = &sPk;
+ }
+ rSize = pTab->nRowLogEst;
+ rLogSize = estLog(rSize);
+
+#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
+ /* Automatic indexes */
+ if( !pBuilder->pOrSet /* Not part of an OR optimization */
+ && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
+ && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
+ && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
+ && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
+ && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
+ && !pSrc->fg.isCorrelated /* Not a correlated subquery */
+ && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
+ ){
+ /* Generate auto-index WhereLoops */
+ WhereTerm *pTerm;
+ WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
+ for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
+ if( pTerm->prereqRight & pNew->maskSelf ) continue;
+ if( termCanDriveIndex(pTerm, pSrc, 0) ){
+ pNew->u.btree.nEq = 1;
+ pNew->nSkip = 0;
+ pNew->u.btree.pIndex = 0;
+ pNew->nLTerm = 1;
+ pNew->aLTerm[0] = pTerm;
+ /* TUNING: One-time cost for computing the automatic index is
+ ** estimated to be X*N*log2(N) where N is the number of rows in
+ ** the table being indexed and where X is 7 (LogEst=28) for normal
+ ** tables or 0.5 (LogEst=-10) for views and subqueries. The value
+ ** of X is smaller for views and subqueries so that the query planner
+ ** will be more aggressive about generating automatic indexes for
+ ** those objects, since there is no opportunity to add schema
+ ** indexes on subqueries and views. */
+ pNew->rSetup = rLogSize + rSize;
+ if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
+ pNew->rSetup += 28;
+ }else{
+ pNew->rSetup -= 10;
+ }
+ ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
+ if( pNew->rSetup<0 ) pNew->rSetup = 0;
+ /* TUNING: Each index lookup yields 20 rows in the table. This
+ ** is more than the usual guess of 10 rows, since we have no way
+ ** of knowing how selective the index will ultimately be. It would
+ ** not be unreasonable to make this value much larger. */
+ pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
+ pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
+ pNew->wsFlags = WHERE_AUTO_INDEX;
+ pNew->prereq = mPrereq | pTerm->prereqRight;
+ rc = whereLoopInsert(pBuilder, pNew);
+ }
+ }
+ }
+#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
+
+ /* Loop over all indices. If there was an INDEXED BY clause, then only
+ ** consider index pProbe. */
+ for(; rc==SQLITE_OK && pProbe;
+ pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++
+ ){
+ int isLeft = (pSrc->fg.jointype & JT_OUTER)!=0;
+ if( pProbe->pPartIdxWhere!=0
+ && !whereUsablePartialIndex(pSrc->iCursor, isLeft, pWC,
+ pProbe->pPartIdxWhere)
+ ){
+ testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
+ continue; /* Partial index inappropriate for this query */
+ }
+ if( pProbe->bNoQuery ) continue;
+ rSize = pProbe->aiRowLogEst[0];
+ pNew->u.btree.nEq = 0;
+ pNew->u.btree.nBtm = 0;
+ pNew->u.btree.nTop = 0;
+ pNew->nSkip = 0;
+ pNew->nLTerm = 0;
+ pNew->iSortIdx = 0;
+ pNew->rSetup = 0;
+ pNew->prereq = mPrereq;
+ pNew->nOut = rSize;
+ pNew->u.btree.pIndex = pProbe;
+ b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
+
+ /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
+ assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
+ if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
+ /* Integer primary key index */
+ pNew->wsFlags = WHERE_IPK;
+
+ /* Full table scan */
+ pNew->iSortIdx = b ? iSortIdx : 0;
+ /* TUNING: Cost of full table scan is (N*3.0). */
+ pNew->rRun = rSize + 16;
+ ApplyCostMultiplier(pNew->rRun, pTab->costMult);
+ whereLoopOutputAdjust(pWC, pNew, rSize);
+ rc = whereLoopInsert(pBuilder, pNew);
+ pNew->nOut = rSize;
+ if( rc ) break;
+ }else{
+ Bitmask m;
+ if( pProbe->isCovering ){
+ pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
+ m = 0;
+ }else{
+ m = pSrc->colUsed & pProbe->colNotIdxed;
+ pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
+ }
+
+ /* Full scan via index */
+ if( b
+ || !HasRowid(pTab)
+ || pProbe->pPartIdxWhere!=0
+ || pSrc->fg.isIndexedBy
+ || ( m==0
+ && pProbe->bUnordered==0
+ && (pProbe->szIdxRow<pTab->szTabRow)
+ && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
+ && sqlite3GlobalConfig.bUseCis
+ && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
+ )
+ ){
+ pNew->iSortIdx = b ? iSortIdx : 0;
+
+ /* The cost of visiting the index rows is N*K, where K is
+ ** between 1.1 and 3.0, depending on the relative sizes of the
+ ** index and table rows. */
+ pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
+ if( m!=0 ){
+ /* If this is a non-covering index scan, add in the cost of
+ ** doing table lookups. The cost will be 3x the number of
+ ** lookups. Take into account WHERE clause terms that can be
+ ** satisfied using just the index, and that do not require a
+ ** table lookup. */
+ LogEst nLookup = rSize + 16; /* Base cost: N*3 */
+ int ii;
+ int iCur = pSrc->iCursor;
+ WhereClause *pWC2 = &pWInfo->sWC;
+ for(ii=0; ii<pWC2->nTerm; ii++){
+ WhereTerm *pTerm = &pWC2->a[ii];
+ if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
+ break;
+ }
+ /* pTerm can be evaluated using just the index. So reduce
+ ** the expected number of table lookups accordingly */
+ if( pTerm->truthProb<=0 ){
+ nLookup += pTerm->truthProb;
+ }else{
+ nLookup--;
+ if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
+ }
+ }
+
+ pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
+ }
+ ApplyCostMultiplier(pNew->rRun, pTab->costMult);
+ whereLoopOutputAdjust(pWC, pNew, rSize);
+ rc = whereLoopInsert(pBuilder, pNew);
+ pNew->nOut = rSize;
+ if( rc ) break;
+ }
+ }
+
+ pBuilder->bldFlags1 = 0;
+ rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
+ if( pBuilder->bldFlags1==SQLITE_BLDF1_INDEXED ){
+ /* If a non-unique index is used, or if a prefix of the key for
+ ** unique index is used (making the index functionally non-unique)
+ ** then the sqlite_stat1 data becomes important for scoring the
+ ** plan */
+ pTab->tabFlags |= TF_StatsUsed;
+ }
+#ifdef SQLITE_ENABLE_STAT4
+ sqlite3Stat4ProbeFree(pBuilder->pRec);
+ pBuilder->nRecValid = 0;
+ pBuilder->pRec = 0;
+#endif
+ }
+ return rc;
+}
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+
+/*
+** Argument pIdxInfo is already populated with all constraints that may
+** be used by the virtual table identified by pBuilder->pNew->iTab. This
+** function marks a subset of those constraints usable, invokes the
+** xBestIndex method and adds the returned plan to pBuilder.
+**
+** A constraint is marked usable if:
+**
+** * Argument mUsable indicates that its prerequisites are available, and
+**
+** * It is not one of the operators specified in the mExclude mask passed
+** as the fourth argument (which in practice is either WO_IN or 0).
+**
+** Argument mPrereq is a mask of tables that must be scanned before the
+** virtual table in question. These are added to the plans prerequisites
+** before it is added to pBuilder.
+**
+** Output parameter *pbIn is set to true if the plan added to pBuilder
+** uses one or more WO_IN terms, or false otherwise.
+*/
+static int whereLoopAddVirtualOne(
+ WhereLoopBuilder *pBuilder,
+ Bitmask mPrereq, /* Mask of tables that must be used. */
+ Bitmask mUsable, /* Mask of usable tables */
+ u16 mExclude, /* Exclude terms using these operators */
+ sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
+ u16 mNoOmit, /* Do not omit these constraints */
+ int *pbIn /* OUT: True if plan uses an IN(...) op */
+){
+ WhereClause *pWC = pBuilder->pWC;
+ struct sqlite3_index_constraint *pIdxCons;
+ struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
+ int i;
+ int mxTerm;
+ int rc = SQLITE_OK;
+ WhereLoop *pNew = pBuilder->pNew;
+ Parse *pParse = pBuilder->pWInfo->pParse;
+ struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
+ int nConstraint = pIdxInfo->nConstraint;
+
+ assert( (mUsable & mPrereq)==mPrereq );
+ *pbIn = 0;
+ pNew->prereq = mPrereq;
+
+ /* Set the usable flag on the subset of constraints identified by
+ ** arguments mUsable and mExclude. */
+ pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
+ for(i=0; i<nConstraint; i++, pIdxCons++){
+ WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
+ pIdxCons->usable = 0;
+ if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
+ && (pTerm->eOperator & mExclude)==0
+ ){
+ pIdxCons->usable = 1;
+ }
+ }
+
+ /* Initialize the output fields of the sqlite3_index_info structure */
+ memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
+ assert( pIdxInfo->needToFreeIdxStr==0 );
+ pIdxInfo->idxStr = 0;
+ pIdxInfo->idxNum = 0;
+ pIdxInfo->orderByConsumed = 0;
+ pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
+ pIdxInfo->estimatedRows = 25;
+ pIdxInfo->idxFlags = 0;
+ pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
+
+ /* Invoke the virtual table xBestIndex() method */
+ rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
+ if( rc ){
+ if( rc==SQLITE_CONSTRAINT ){
+ /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
+ ** that the particular combination of parameters provided is unusable.
+ ** Make no entries in the loop table.
+ */
+ WHERETRACE(0xffff, (" ^^^^--- non-viable plan rejected!\n"));
+ return SQLITE_OK;
+ }
+ return rc;
+ }
+
+ mxTerm = -1;
+ assert( pNew->nLSlot>=nConstraint );
+ for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
+ pNew->u.vtab.omitMask = 0;
+ pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
+ for(i=0; i<nConstraint; i++, pIdxCons++){
+ int iTerm;
+ if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
+ WhereTerm *pTerm;
+ int j = pIdxCons->iTermOffset;
+ if( iTerm>=nConstraint
+ || j<0
+ || j>=pWC->nTerm
+ || pNew->aLTerm[iTerm]!=0
+ || pIdxCons->usable==0
+ ){
+ sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
+ testcase( pIdxInfo->needToFreeIdxStr );
+ return SQLITE_ERROR;
+ }
+ testcase( iTerm==nConstraint-1 );
+ testcase( j==0 );
+ testcase( j==pWC->nTerm-1 );
+ pTerm = &pWC->a[j];
+ pNew->prereq |= pTerm->prereqRight;
+ assert( iTerm<pNew->nLSlot );
+ pNew->aLTerm[iTerm] = pTerm;
+ if( iTerm>mxTerm ) mxTerm = iTerm;
+ testcase( iTerm==15 );
+ testcase( iTerm==16 );
+ if( pUsage[i].omit ){
+ if( i<16 && ((1<<i)&mNoOmit)==0 ){
+ testcase( i!=iTerm );
+ pNew->u.vtab.omitMask |= 1<<iTerm;
+ }else{
+ testcase( i!=iTerm );
+ }
+ }
+ if( (pTerm->eOperator & WO_IN)!=0 ){
+ /* A virtual table that is constrained by an IN clause may not
+ ** consume the ORDER BY clause because (1) the order of IN terms
+ ** is not necessarily related to the order of output terms and
+ ** (2) Multiple outputs from a single IN value will not merge
+ ** together. */
+ pIdxInfo->orderByConsumed = 0;
+ pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
+ *pbIn = 1; assert( (mExclude & WO_IN)==0 );
+ }
+ }
+ }
+
+ pNew->nLTerm = mxTerm+1;
+ for(i=0; i<=mxTerm; i++){
+ if( pNew->aLTerm[i]==0 ){
+ /* The non-zero argvIdx values must be contiguous. Raise an
+ ** error if they are not */
+ sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
+ testcase( pIdxInfo->needToFreeIdxStr );
+ return SQLITE_ERROR;
+ }
+ }
+ assert( pNew->nLTerm<=pNew->nLSlot );
+ pNew->u.vtab.idxNum = pIdxInfo->idxNum;
+ pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
+ pIdxInfo->needToFreeIdxStr = 0;
+ pNew->u.vtab.idxStr = pIdxInfo->idxStr;
+ pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
+ pIdxInfo->nOrderBy : 0);
+ pNew->rSetup = 0;
+ pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
+ pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
+
+ /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
+ ** that the scan will visit at most one row. Clear it otherwise. */
+ if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
+ pNew->wsFlags |= WHERE_ONEROW;
+ }else{
+ pNew->wsFlags &= ~WHERE_ONEROW;
+ }
+ rc = whereLoopInsert(pBuilder, pNew);
+ if( pNew->u.vtab.needFree ){
+ sqlite3_free(pNew->u.vtab.idxStr);
+ pNew->u.vtab.needFree = 0;
+ }
+ WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
+ *pbIn, (sqlite3_uint64)mPrereq,
+ (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
+
+ return rc;
+}
+
+/*
+** If this function is invoked from within an xBestIndex() callback, it
+** returns a pointer to a buffer containing the name of the collation
+** sequence associated with element iCons of the sqlite3_index_info.aConstraint
+** array. Or, if iCons is out of range or there is no active xBestIndex
+** call, return NULL.
+*/
+SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
+ HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
+ const char *zRet = 0;
+ if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
+ CollSeq *pC = 0;
+ int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
+ Expr *pX = pHidden->pWC->a[iTerm].pExpr;
+ if( pX->pLeft ){
+ pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX);
+ }
+ zRet = (pC ? pC->zName : sqlite3StrBINARY);
+ }
+ return zRet;
+}
+
+/*
+** Add all WhereLoop objects for a table of the join identified by
+** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
+**
+** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
+** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
+** entries that occur before the virtual table in the FROM clause and are
+** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
+** mUnusable mask contains all FROM clause entries that occur after the
+** virtual table and are separated from it by at least one LEFT or
+** CROSS JOIN.
+**
+** For example, if the query were:
+**
+** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
+**
+** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
+**
+** All the tables in mPrereq must be scanned before the current virtual
+** table. So any terms for which all prerequisites are satisfied by
+** mPrereq may be specified as "usable" in all calls to xBestIndex.
+** Conversely, all tables in mUnusable must be scanned after the current
+** virtual table, so any terms for which the prerequisites overlap with
+** mUnusable should always be configured as "not-usable" for xBestIndex.
+*/
+static int whereLoopAddVirtual(
+ WhereLoopBuilder *pBuilder, /* WHERE clause information */
+ Bitmask mPrereq, /* Tables that must be scanned before this one */
+ Bitmask mUnusable /* Tables that must be scanned after this one */
+){
+ int rc = SQLITE_OK; /* Return code */
+ WhereInfo *pWInfo; /* WHERE analysis context */
+ Parse *pParse; /* The parsing context */
+ WhereClause *pWC; /* The WHERE clause */
+ struct SrcList_item *pSrc; /* The FROM clause term to search */
+ sqlite3_index_info *p; /* Object to pass to xBestIndex() */
+ int nConstraint; /* Number of constraints in p */
+ int bIn; /* True if plan uses IN(...) operator */
+ WhereLoop *pNew;
+ Bitmask mBest; /* Tables used by best possible plan */
+ u16 mNoOmit;
+
+ assert( (mPrereq & mUnusable)==0 );
+ pWInfo = pBuilder->pWInfo;
+ pParse = pWInfo->pParse;
+ pWC = pBuilder->pWC;
+ pNew = pBuilder->pNew;
+ pSrc = &pWInfo->pTabList->a[pNew->iTab];
+ assert( IsVirtual(pSrc->pTab) );
+ p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
+ &mNoOmit);
+ if( p==0 ) return SQLITE_NOMEM_BKPT;
+ pNew->rSetup = 0;
+ pNew->wsFlags = WHERE_VIRTUALTABLE;
+ pNew->nLTerm = 0;
+ pNew->u.vtab.needFree = 0;
+ nConstraint = p->nConstraint;
+ if( whereLoopResize(pParse->db, pNew, nConstraint) ){
+ sqlite3DbFree(pParse->db, p);
+ return SQLITE_NOMEM_BKPT;
+ }
+
+ /* First call xBestIndex() with all constraints usable. */
+ WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
+ WHERETRACE(0x40, (" VirtualOne: all usable\n"));
+ rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
+
+ /* If the call to xBestIndex() with all terms enabled produced a plan
+ ** that does not require any source tables (IOW: a plan with mBest==0)
+ ** and does not use an IN(...) operator, then there is no point in making
+ ** any further calls to xBestIndex() since they will all return the same
+ ** result (if the xBestIndex() implementation is sane). */
+ if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){
+ int seenZero = 0; /* True if a plan with no prereqs seen */
+ int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
+ Bitmask mPrev = 0;
+ Bitmask mBestNoIn = 0;
+
+ /* If the plan produced by the earlier call uses an IN(...) term, call
+ ** xBestIndex again, this time with IN(...) terms disabled. */
+ if( bIn ){
+ WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
+ rc = whereLoopAddVirtualOne(
+ pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
+ assert( bIn==0 );
+ mBestNoIn = pNew->prereq & ~mPrereq;
+ if( mBestNoIn==0 ){
+ seenZero = 1;
+ seenZeroNoIN = 1;
+ }
+ }
+
+ /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
+ ** in the set of terms that apply to the current virtual table. */
+ while( rc==SQLITE_OK ){
+ int i;
+ Bitmask mNext = ALLBITS;
+ assert( mNext>0 );
+ for(i=0; i<nConstraint; i++){
+ Bitmask mThis = (
+ pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
+ );
+ if( mThis>mPrev && mThis<mNext ) mNext = mThis;
+ }
+ mPrev = mNext;
+ if( mNext==ALLBITS ) break;
+ if( mNext==mBest || mNext==mBestNoIn ) continue;
+ WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
+ (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
+ rc = whereLoopAddVirtualOne(
+ pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
+ if( pNew->prereq==mPrereq ){
+ seenZero = 1;
+ if( bIn==0 ) seenZeroNoIN = 1;
+ }
+ }
+
+ /* If the calls to xBestIndex() in the above loop did not find a plan
+ ** that requires no source tables at all (i.e. one guaranteed to be
+ ** usable), make a call here with all source tables disabled */
+ if( rc==SQLITE_OK && seenZero==0 ){
+ WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
+ rc = whereLoopAddVirtualOne(
+ pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
+ if( bIn==0 ) seenZeroNoIN = 1;
+ }
+
+ /* If the calls to xBestIndex() have so far failed to find a plan
+ ** that requires no source tables at all and does not use an IN(...)
+ ** operator, make a final call to obtain one here. */
+ if( rc==SQLITE_OK && seenZeroNoIN==0 ){
+ WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
+ rc = whereLoopAddVirtualOne(
+ pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
+ }
+ }
+
+ if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
+ sqlite3DbFreeNN(pParse->db, p);
+ WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
+ return rc;
+}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+/*
+** Add WhereLoop entries to handle OR terms. This works for either
+** btrees or virtual tables.
+*/
+static int whereLoopAddOr(
+ WhereLoopBuilder *pBuilder,
+ Bitmask mPrereq,
+ Bitmask mUnusable
+){
+ WhereInfo *pWInfo = pBuilder->pWInfo;
+ WhereClause *pWC;
+ WhereLoop *pNew;
+ WhereTerm *pTerm, *pWCEnd;
+ int rc = SQLITE_OK;
+ int iCur;
+ WhereClause tempWC;
+ WhereLoopBuilder sSubBuild;
+ WhereOrSet sSum, sCur;
+ struct SrcList_item *pItem;
+
+ pWC = pBuilder->pWC;
+ pWCEnd = pWC->a + pWC->nTerm;
+ pNew = pBuilder->pNew;
+ memset(&sSum, 0, sizeof(sSum));
+ pItem = pWInfo->pTabList->a + pNew->iTab;
+ iCur = pItem->iCursor;
+
+ for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
+ if( (pTerm->eOperator & WO_OR)!=0
+ && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
+ ){
+ WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
+ WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
+ WhereTerm *pOrTerm;
+ int once = 1;
+ int i, j;
+
+ sSubBuild = *pBuilder;
+ sSubBuild.pOrderBy = 0;
+ sSubBuild.pOrSet = &sCur;
+
+ WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
+ for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
+ if( (pOrTerm->eOperator & WO_AND)!=0 ){
+ sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
+ }else if( pOrTerm->leftCursor==iCur ){
+ tempWC.pWInfo = pWC->pWInfo;
+ tempWC.pOuter = pWC;
+ tempWC.op = TK_AND;
+ tempWC.nTerm = 1;
+ tempWC.a = pOrTerm;
+ sSubBuild.pWC = &tempWC;
+ }else{
+ continue;
+ }
+ sCur.n = 0;
+#ifdef WHERETRACE_ENABLED
+ WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
+ (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
+ if( sqlite3WhereTrace & 0x400 ){
+ sqlite3WhereClausePrint(sSubBuild.pWC);
+ }
+#endif
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( IsVirtual(pItem->pTab) ){
+ rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
+ }else
+#endif
+ {
+ rc = whereLoopAddBtree(&sSubBuild, mPrereq);
+ }
+ if( rc==SQLITE_OK ){
+ rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
+ }
+ assert( rc==SQLITE_OK || rc==SQLITE_DONE || sCur.n==0 );
+ testcase( rc==SQLITE_DONE );
+ if( sCur.n==0 ){
+ sSum.n = 0;
+ break;
+ }else if( once ){
+ whereOrMove(&sSum, &sCur);
+ once = 0;
+ }else{
+ WhereOrSet sPrev;
+ whereOrMove(&sPrev, &sSum);
+ sSum.n = 0;
+ for(i=0; i<sPrev.n; i++){
+ for(j=0; j<sCur.n; j++){
+ whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
+ sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
+ sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
+ }
+ }
+ }
+ }
+ pNew->nLTerm = 1;
+ pNew->aLTerm[0] = pTerm;
+ pNew->wsFlags = WHERE_MULTI_OR;
+ pNew->rSetup = 0;
+ pNew->iSortIdx = 0;
+ memset(&pNew->u, 0, sizeof(pNew->u));
+ for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
+ /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
+ ** of all sub-scans required by the OR-scan. However, due to rounding
+ ** errors, it may be that the cost of the OR-scan is equal to its
+ ** most expensive sub-scan. Add the smallest possible penalty
+ ** (equivalent to multiplying the cost by 1.07) to ensure that
+ ** this does not happen. Otherwise, for WHERE clauses such as the
+ ** following where there is an index on "y":
+ **
+ ** WHERE likelihood(x=?, 0.99) OR y=?
+ **
+ ** the planner may elect to "OR" together a full-table scan and an
+ ** index lookup. And other similarly odd results. */
+ pNew->rRun = sSum.a[i].rRun + 1;
+ pNew->nOut = sSum.a[i].nOut;
+ pNew->prereq = sSum.a[i].prereq;
+ rc = whereLoopInsert(pBuilder, pNew);
+ }
+ WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
+ }
+ }
+ return rc;
+}
+
+/*
+** Add all WhereLoop objects for all tables
+*/
+static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
+ WhereInfo *pWInfo = pBuilder->pWInfo;
+ Bitmask mPrereq = 0;
+ Bitmask mPrior = 0;
+ int iTab;
+ SrcList *pTabList = pWInfo->pTabList;
+ struct SrcList_item *pItem;
+ struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
+ sqlite3 *db = pWInfo->pParse->db;
+ int rc = SQLITE_OK;
+ WhereLoop *pNew;
+
+ /* Loop over the tables in the join, from left to right */
+ pNew = pBuilder->pNew;
+ whereLoopInit(pNew);
+ pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;
+ for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
+ Bitmask mUnusable = 0;
+ pNew->iTab = iTab;
+ pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
+ pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
+ if( (pItem->fg.jointype & (JT_LEFT|JT_CROSS))!=0 ){
+ /* This condition is true when pItem is the FROM clause term on the
+ ** right-hand-side of a LEFT or CROSS JOIN. */
+ mPrereq = mPrior;
+ }else{
+ mPrereq = 0;
+ }
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( IsVirtual(pItem->pTab) ){
+ struct SrcList_item *p;
+ for(p=&pItem[1]; p<pEnd; p++){
+ if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
+ mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
+ }
+ }
+ rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
+ }else
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+ {
+ rc = whereLoopAddBtree(pBuilder, mPrereq);
+ }
+ if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){
+ rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
+ }
+ mPrior |= pNew->maskSelf;
+ if( rc || db->mallocFailed ){
+ if( rc==SQLITE_DONE ){
+ /* We hit the query planner search limit set by iPlanLimit */
+ sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search");
+ rc = SQLITE_OK;
+ }else{
+ break;
+ }
+ }
+ }
+
+ whereLoopClear(db, pNew);
+ return rc;
+}
+
+/*
+** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
+** parameters) to see if it outputs rows in the requested ORDER BY
+** (or GROUP BY) without requiring a separate sort operation. Return N:
+**
+** N>0: N terms of the ORDER BY clause are satisfied
+** N==0: No terms of the ORDER BY clause are satisfied
+** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
+**
+** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
+** strict. With GROUP BY and DISTINCT the only requirement is that
+** equivalent rows appear immediately adjacent to one another. GROUP BY
+** and DISTINCT do not require rows to appear in any particular order as long
+** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
+** the pOrderBy terms can be matched in any order. With ORDER BY, the
+** pOrderBy terms must be matched in strict left-to-right order.
+*/
+static i8 wherePathSatisfiesOrderBy(
+ WhereInfo *pWInfo, /* The WHERE clause */
+ ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
+ WherePath *pPath, /* The WherePath to check */
+ u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
+ u16 nLoop, /* Number of entries in pPath->aLoop[] */
+ WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
+ Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
+){
+ u8 revSet; /* True if rev is known */
+ u8 rev; /* Composite sort order */
+ u8 revIdx; /* Index sort order */
+ u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
+ u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
+ u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
+ u16 eqOpMask; /* Allowed equality operators */
+ u16 nKeyCol; /* Number of key columns in pIndex */
+ u16 nColumn; /* Total number of ordered columns in the index */
+ u16 nOrderBy; /* Number terms in the ORDER BY clause */
+ int iLoop; /* Index of WhereLoop in pPath being processed */
+ int i, j; /* Loop counters */
+ int iCur; /* Cursor number for current WhereLoop */
+ int iColumn; /* A column number within table iCur */
+ WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
+ WhereTerm *pTerm; /* A single term of the WHERE clause */
+ Expr *pOBExpr; /* An expression from the ORDER BY clause */
+ CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
+ Index *pIndex; /* The index associated with pLoop */
+ sqlite3 *db = pWInfo->pParse->db; /* Database connection */
+ Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
+ Bitmask obDone; /* Mask of all ORDER BY terms */
+ Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
+ Bitmask ready; /* Mask of inner loops */
+
+ /*
+ ** We say the WhereLoop is "one-row" if it generates no more than one
+ ** row of output. A WhereLoop is one-row if all of the following are true:
+ ** (a) All index columns match with WHERE_COLUMN_EQ.
+ ** (b) The index is unique
+ ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
+ ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
+ **
+ ** We say the WhereLoop is "order-distinct" if the set of columns from
+ ** that WhereLoop that are in the ORDER BY clause are different for every
+ ** row of the WhereLoop. Every one-row WhereLoop is automatically
+ ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
+ ** is not order-distinct. To be order-distinct is not quite the same as being
+ ** UNIQUE since a UNIQUE column or index can have multiple rows that
+ ** are NULL and NULL values are equivalent for the purpose of order-distinct.
+ ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
+ **
+ ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
+ ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
+ ** automatically order-distinct.
+ */
+
+ assert( pOrderBy!=0 );
+ if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
+
+ nOrderBy = pOrderBy->nExpr;
+ testcase( nOrderBy==BMS-1 );
+ if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
+ isOrderDistinct = 1;
+ obDone = MASKBIT(nOrderBy)-1;
+ orderDistinctMask = 0;
+ ready = 0;
+ eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
+ if( wctrlFlags & (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MAX|WHERE_ORDERBY_MIN) ){
+ eqOpMask |= WO_IN;
+ }
+ for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
+ if( iLoop>0 ) ready |= pLoop->maskSelf;
+ if( iLoop<nLoop ){
+ pLoop = pPath->aLoop[iLoop];
+ if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
+ }else{
+ pLoop = pLast;
+ }
+ if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
+ if( pLoop->u.vtab.isOrdered && (wctrlFlags & WHERE_DISTINCTBY)==0 ){
+ obSat = obDone;
+ }
+ break;
+ }else if( wctrlFlags & WHERE_DISTINCTBY ){
+ pLoop->u.btree.nDistinctCol = 0;
+ }
+ iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
+
+ /* Mark off any ORDER BY term X that is a column in the table of
+ ** the current loop for which there is term in the WHERE
+ ** clause of the form X IS NULL or X=? that reference only outer
+ ** loops.
+ */
+ for(i=0; i<nOrderBy; i++){
+ if( MASKBIT(i) & obSat ) continue;
+ pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
+ if( pOBExpr->op!=TK_COLUMN ) continue;
+ if( pOBExpr->iTable!=iCur ) continue;
+ pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
+ ~ready, eqOpMask, 0);
+ if( pTerm==0 ) continue;
+ if( pTerm->eOperator==WO_IN ){
+ /* IN terms are only valid for sorting in the ORDER BY LIMIT
+ ** optimization, and then only if they are actually used
+ ** by the query plan */
+ assert( wctrlFlags &
+ (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) );
+ for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
+ if( j>=pLoop->nLTerm ) continue;
+ }
+ if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
+ Parse *pParse = pWInfo->pParse;
+ CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr);
+ CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr);
+ assert( pColl1 );
+ if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){
+ continue;
+ }
+ testcase( pTerm->pExpr->op==TK_IS );
+ }
+ obSat |= MASKBIT(i);
+ }
+
+ if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
+ if( pLoop->wsFlags & WHERE_IPK ){
+ pIndex = 0;
+ nKeyCol = 0;
+ nColumn = 1;
+ }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
+ return 0;
+ }else{
+ nKeyCol = pIndex->nKeyCol;
+ nColumn = pIndex->nColumn;
+ assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
+ assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
+ || !HasRowid(pIndex->pTable));
+ isOrderDistinct = IsUniqueIndex(pIndex)
+ && (pLoop->wsFlags & WHERE_SKIPSCAN)==0;
+ }
+
+ /* Loop through all columns of the index and deal with the ones
+ ** that are not constrained by == or IN.
+ */
+ rev = revSet = 0;
+ distinctColumns = 0;
+ for(j=0; j<nColumn; j++){
+ u8 bOnce = 1; /* True to run the ORDER BY search loop */
+
+ assert( j>=pLoop->u.btree.nEq
+ || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
+ );
+ if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
+ u16 eOp = pLoop->aLTerm[j]->eOperator;
+
+ /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
+ ** doing WHERE_ORDERBY_LIMIT processing). Except, IS and ISNULL
+ ** terms imply that the index is not UNIQUE NOT NULL in which case
+ ** the loop need to be marked as not order-distinct because it can
+ ** have repeated NULL rows.
+ **
+ ** If the current term is a column of an ((?,?) IN (SELECT...))
+ ** expression for which the SELECT returns more than one column,
+ ** check that it is the only column used by this loop. Otherwise,
+ ** if it is one of two or more, none of the columns can be
+ ** considered to match an ORDER BY term.
+ */
+ if( (eOp & eqOpMask)!=0 ){
+ if( eOp & (WO_ISNULL|WO_IS) ){
+ testcase( eOp & WO_ISNULL );
+ testcase( eOp & WO_IS );
+ testcase( isOrderDistinct );
+ isOrderDistinct = 0;
+ }
+ continue;
+ }else if( ALWAYS(eOp & WO_IN) ){
+ /* ALWAYS() justification: eOp is an equality operator due to the
+ ** j<pLoop->u.btree.nEq constraint above. Any equality other
+ ** than WO_IN is captured by the previous "if". So this one
+ ** always has to be WO_IN. */
+ Expr *pX = pLoop->aLTerm[j]->pExpr;
+ for(i=j+1; i<pLoop->u.btree.nEq; i++){
+ if( pLoop->aLTerm[i]->pExpr==pX ){
+ assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
+ bOnce = 0;
+ break;
+ }
+ }
+ }
+ }
+
+ /* Get the column number in the table (iColumn) and sort order
+ ** (revIdx) for the j-th column of the index.
+ */
+ if( pIndex ){
+ iColumn = pIndex->aiColumn[j];
+ revIdx = pIndex->aSortOrder[j] & KEYINFO_ORDER_DESC;
+ if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
+ }else{
+ iColumn = XN_ROWID;
+ revIdx = 0;
+ }
+
+ /* An unconstrained column that might be NULL means that this
+ ** WhereLoop is not well-ordered
+ */
+ if( isOrderDistinct
+ && iColumn>=0
+ && j>=pLoop->u.btree.nEq
+ && pIndex->pTable->aCol[iColumn].notNull==0
+ ){
+ isOrderDistinct = 0;
+ }
+
+ /* Find the ORDER BY term that corresponds to the j-th column
+ ** of the index and mark that ORDER BY term off
+ */
+ isMatch = 0;
+ for(i=0; bOnce && i<nOrderBy; i++){
+ if( MASKBIT(i) & obSat ) continue;
+ pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
+ testcase( wctrlFlags & WHERE_GROUPBY );
+ testcase( wctrlFlags & WHERE_DISTINCTBY );
+ if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
+ if( iColumn>=XN_ROWID ){
+ if( pOBExpr->op!=TK_COLUMN ) continue;
+ if( pOBExpr->iTable!=iCur ) continue;
+ if( pOBExpr->iColumn!=iColumn ) continue;
+ }else{
+ Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;
+ if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){
+ continue;
+ }
+ }
+ if( iColumn!=XN_ROWID ){
+ pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
+ if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
+ }
+ if( wctrlFlags & WHERE_DISTINCTBY ){
+ pLoop->u.btree.nDistinctCol = j+1;
+ }
+ isMatch = 1;
+ break;
+ }
+ if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
+ /* Make sure the sort order is compatible in an ORDER BY clause.
+ ** Sort order is irrelevant for a GROUP BY clause. */
+ if( revSet ){
+ if( (rev ^ revIdx)!=(pOrderBy->a[i].sortFlags&KEYINFO_ORDER_DESC) ){
+ isMatch = 0;
+ }
+ }else{
+ rev = revIdx ^ (pOrderBy->a[i].sortFlags & KEYINFO_ORDER_DESC);
+ if( rev ) *pRevMask |= MASKBIT(iLoop);
+ revSet = 1;
+ }
+ }
+ if( isMatch && (pOrderBy->a[i].sortFlags & KEYINFO_ORDER_BIGNULL) ){
+ if( j==pLoop->u.btree.nEq ){
+ pLoop->wsFlags |= WHERE_BIGNULL_SORT;
+ }else{
+ isMatch = 0;
+ }
+ }
+ if( isMatch ){
+ if( iColumn==XN_ROWID ){
+ testcase( distinctColumns==0 );
+ distinctColumns = 1;
+ }
+ obSat |= MASKBIT(i);
+ }else{
+ /* No match found */
+ if( j==0 || j<nKeyCol ){
+ testcase( isOrderDistinct!=0 );
+ isOrderDistinct = 0;
+ }
+ break;
+ }
+ } /* end Loop over all index columns */
+ if( distinctColumns ){
+ testcase( isOrderDistinct==0 );
+ isOrderDistinct = 1;
+ }
+ } /* end-if not one-row */
+
+ /* Mark off any other ORDER BY terms that reference pLoop */
+ if( isOrderDistinct ){
+ orderDistinctMask |= pLoop->maskSelf;
+ for(i=0; i<nOrderBy; i++){
+ Expr *p;
+ Bitmask mTerm;
+ if( MASKBIT(i) & obSat ) continue;
+ p = pOrderBy->a[i].pExpr;
+ mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
+ if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
+ if( (mTerm&~orderDistinctMask)==0 ){
+ obSat |= MASKBIT(i);
+ }
+ }
+ }
+ } /* End the loop over all WhereLoops from outer-most down to inner-most */
+ if( obSat==obDone ) return (i8)nOrderBy;
+ if( !isOrderDistinct ){
+ for(i=nOrderBy-1; i>0; i--){
+ Bitmask m = MASKBIT(i) - 1;
+ if( (obSat&m)==m ) return i;
+ }
+ return 0;
+ }
+ return -1;
+}
+
+
+/*
+** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
+** the planner assumes that the specified pOrderBy list is actually a GROUP
+** BY clause - and so any order that groups rows as required satisfies the
+** request.
+**
+** Normally, in this case it is not possible for the caller to determine
+** whether or not the rows are really being delivered in sorted order, or
+** just in some other order that provides the required grouping. However,
+** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
+** this function may be called on the returned WhereInfo object. It returns
+** true if the rows really will be sorted in the specified order, or false
+** otherwise.
+**
+** For example, assuming:
+**
+** CREATE INDEX i1 ON t1(x, Y);
+**
+** then
+**
+** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
+** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
+*/
+SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
+ assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
+ assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
+ return pWInfo->sorted;
+}
+
+#ifdef WHERETRACE_ENABLED
+/* For debugging use only: */
+static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
+ static char zName[65];
+ int i;
+ for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
+ if( pLast ) zName[i++] = pLast->cId;
+ zName[i] = 0;
+ return zName;
+}
+#endif
+
+/*
+** Return the cost of sorting nRow rows, assuming that the keys have
+** nOrderby columns and that the first nSorted columns are already in
+** order.
+*/
+static LogEst whereSortingCost(
+ WhereInfo *pWInfo,
+ LogEst nRow,
+ int nOrderBy,
+ int nSorted
+){
+ /* TUNING: Estimated cost of a full external sort, where N is
+ ** the number of rows to sort is:
+ **
+ ** cost = (3.0 * N * log(N)).
+ **
+ ** Or, if the order-by clause has X terms but only the last Y
+ ** terms are out of order, then block-sorting will reduce the
+ ** sorting cost to:
+ **
+ ** cost = (3.0 * N * log(N)) * (Y/X)
+ **
+ ** The (Y/X) term is implemented using stack variable rScale
+ ** below.
+ */
+ LogEst rScale, rSortCost;
+ assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
+ rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
+ rSortCost = nRow + rScale + 16;
+
+ /* Multiple by log(M) where M is the number of output rows.
+ ** Use the LIMIT for M if it is smaller. Or if this sort is for
+ ** a DISTINT operator, M will be the number of distinct output
+ ** rows, so fudge it downwards a bit.
+ */
+ if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
+ nRow = pWInfo->iLimit;
+ }else if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT) ){
+ /* TUNING: In the sort for a DISTINCT operator, assume that the DISTINCT
+ ** reduces the number of output rows by a factor of 2 */
+ if( nRow>10 ) nRow -= 10; assert( 10==sqlite3LogEst(2) );
+ }
+ rSortCost += estLog(nRow);
+ return rSortCost;
+}
+
+/*
+** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
+** attempts to find the lowest cost path that visits each WhereLoop
+** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
+**
+** Assume that the total number of output rows that will need to be sorted
+** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
+** costs if nRowEst==0.
+**
+** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
+** error occurs.
+*/
+static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
+ int mxChoice; /* Maximum number of simultaneous paths tracked */
+ int nLoop; /* Number of terms in the join */
+ Parse *pParse; /* Parsing context */
+ sqlite3 *db; /* The database connection */
+ int iLoop; /* Loop counter over the terms of the join */
+ int ii, jj; /* Loop counters */
+ int mxI = 0; /* Index of next entry to replace */
+ int nOrderBy; /* Number of ORDER BY clause terms */
+ LogEst mxCost = 0; /* Maximum cost of a set of paths */
+ LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
+ int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
+ WherePath *aFrom; /* All nFrom paths at the previous level */
+ WherePath *aTo; /* The nTo best paths at the current level */
+ WherePath *pFrom; /* An element of aFrom[] that we are working on */
+ WherePath *pTo; /* An element of aTo[] that we are working on */
+ WhereLoop *pWLoop; /* One of the WhereLoop objects */
+ WhereLoop **pX; /* Used to divy up the pSpace memory */
+ LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
+ char *pSpace; /* Temporary memory used by this routine */
+ int nSpace; /* Bytes of space allocated at pSpace */
+
+ pParse = pWInfo->pParse;
+ db = pParse->db;
+ nLoop = pWInfo->nLevel;
+ /* TUNING: For simple queries, only the best path is tracked.
+ ** For 2-way joins, the 5 best paths are followed.
+ ** For joins of 3 or more tables, track the 10 best paths */
+ mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
+ assert( nLoop<=pWInfo->pTabList->nSrc );
+ WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
+
+ /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
+ ** case the purpose of this call is to estimate the number of rows returned
+ ** by the overall query. Once this estimate has been obtained, the caller
+ ** will invoke this function a second time, passing the estimate as the
+ ** nRowEst parameter. */
+ if( pWInfo->pOrderBy==0 || nRowEst==0 ){
+ nOrderBy = 0;
+ }else{
+ nOrderBy = pWInfo->pOrderBy->nExpr;
+ }
+
+ /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
+ nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
+ nSpace += sizeof(LogEst) * nOrderBy;
+ pSpace = sqlite3DbMallocRawNN(db, nSpace);
+ if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
+ aTo = (WherePath*)pSpace;
+ aFrom = aTo+mxChoice;
+ memset(aFrom, 0, sizeof(aFrom[0]));
+ pX = (WhereLoop**)(aFrom+mxChoice);
+ for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
+ pFrom->aLoop = pX;
+ }
+ if( nOrderBy ){
+ /* If there is an ORDER BY clause and it is not being ignored, set up
+ ** space for the aSortCost[] array. Each element of the aSortCost array
+ ** is either zero - meaning it has not yet been initialized - or the
+ ** cost of sorting nRowEst rows of data where the first X terms of
+ ** the ORDER BY clause are already in order, where X is the array
+ ** index. */
+ aSortCost = (LogEst*)pX;
+ memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
+ }
+ assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
+ assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
+
+ /* Seed the search with a single WherePath containing zero WhereLoops.
+ **
+ ** TUNING: Do not let the number of iterations go above 28. If the cost
+ ** of computing an automatic index is not paid back within the first 28
+ ** rows, then do not use the automatic index. */
+ aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
+ nFrom = 1;
+ assert( aFrom[0].isOrdered==0 );
+ if( nOrderBy ){
+ /* If nLoop is zero, then there are no FROM terms in the query. Since
+ ** in this case the query may return a maximum of one row, the results
+ ** are already in the requested order. Set isOrdered to nOrderBy to
+ ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
+ ** -1, indicating that the result set may or may not be ordered,
+ ** depending on the loops added to the current plan. */
+ aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
+ }
+
+ /* Compute successively longer WherePaths using the previous generation
+ ** of WherePaths as the basis for the next. Keep track of the mxChoice
+ ** best paths at each generation */
+ for(iLoop=0; iLoop<nLoop; iLoop++){
+ nTo = 0;
+ for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
+ for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
+ LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
+ LogEst rCost; /* Cost of path (pFrom+pWLoop) */
+ LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
+ i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
+ Bitmask maskNew; /* Mask of src visited by (..) */
+ Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
+
+ if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
+ if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
+ if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
+ /* Do not use an automatic index if the this loop is expected
+ ** to run less than 1.25 times. It is tempting to also exclude
+ ** automatic index usage on an outer loop, but sometimes an automatic
+ ** index is useful in the outer loop of a correlated subquery. */
+ assert( 10==sqlite3LogEst(2) );
+ continue;
+ }
+
+ /* At this point, pWLoop is a candidate to be the next loop.
+ ** Compute its cost */
+ rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
+ rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
+ nOut = pFrom->nRow + pWLoop->nOut;
+ maskNew = pFrom->maskLoop | pWLoop->maskSelf;
+ if( isOrdered<0 ){
+ isOrdered = wherePathSatisfiesOrderBy(pWInfo,
+ pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
+ iLoop, pWLoop, &revMask);
+ }else{
+ revMask = pFrom->revLoop;
+ }
+ if( isOrdered>=0 && isOrdered<nOrderBy ){
+ if( aSortCost[isOrdered]==0 ){
+ aSortCost[isOrdered] = whereSortingCost(
+ pWInfo, nRowEst, nOrderBy, isOrdered
+ );
+ }
+ /* TUNING: Add a small extra penalty (5) to sorting as an
+ ** extra encouragment to the query planner to select a plan
+ ** where the rows emerge in the correct order without any sorting
+ ** required. */
+ rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 5;
+
+ WHERETRACE(0x002,
+ ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
+ aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
+ rUnsorted, rCost));
+ }else{
+ rCost = rUnsorted;
+ rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */
+ }
+
+ /* Check to see if pWLoop should be added to the set of
+ ** mxChoice best-so-far paths.
+ **
+ ** First look for an existing path among best-so-far paths
+ ** that covers the same set of loops and has the same isOrdered
+ ** setting as the current path candidate.
+ **
+ ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
+ ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
+ ** of legal values for isOrdered, -1..64.
+ */
+ for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
+ if( pTo->maskLoop==maskNew
+ && ((pTo->isOrdered^isOrdered)&0x80)==0
+ ){
+ testcase( jj==nTo-1 );
+ break;
+ }
+ }
+ if( jj>=nTo ){
+ /* None of the existing best-so-far paths match the candidate. */
+ if( nTo>=mxChoice
+ && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
+ ){
+ /* The current candidate is no better than any of the mxChoice
+ ** paths currently in the best-so-far buffer. So discard
+ ** this candidate as not viable. */
+#ifdef WHERETRACE_ENABLED /* 0x4 */
+ if( sqlite3WhereTrace&0x4 ){
+ sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
+ wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
+ isOrdered>=0 ? isOrdered+'0' : '?');
+ }
+#endif
+ continue;
+ }
+ /* If we reach this points it means that the new candidate path
+ ** needs to be added to the set of best-so-far paths. */
+ if( nTo<mxChoice ){
+ /* Increase the size of the aTo set by one */
+ jj = nTo++;
+ }else{
+ /* New path replaces the prior worst to keep count below mxChoice */
+ jj = mxI;
+ }
+ pTo = &aTo[jj];
+#ifdef WHERETRACE_ENABLED /* 0x4 */
+ if( sqlite3WhereTrace&0x4 ){
+ sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
+ wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
+ isOrdered>=0 ? isOrdered+'0' : '?');
+ }
+#endif
+ }else{
+ /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
+ ** same set of loops and has the same isOrdered setting as the
+ ** candidate path. Check to see if the candidate should replace
+ ** pTo or if the candidate should be skipped.
+ **
+ ** The conditional is an expanded vector comparison equivalent to:
+ ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
+ */
+ if( pTo->rCost<rCost
+ || (pTo->rCost==rCost
+ && (pTo->nRow<nOut
+ || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
+ )
+ )
+ ){
+#ifdef WHERETRACE_ENABLED /* 0x4 */
+ if( sqlite3WhereTrace&0x4 ){
+ sqlite3DebugPrintf(
+ "Skip %s cost=%-3d,%3d,%3d order=%c",
+ wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
+ isOrdered>=0 ? isOrdered+'0' : '?');
+ sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
+ wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
+ pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
+ }
+#endif
+ /* Discard the candidate path from further consideration */
+ testcase( pTo->rCost==rCost );
+ continue;
+ }
+ testcase( pTo->rCost==rCost+1 );
+ /* Control reaches here if the candidate path is better than the
+ ** pTo path. Replace pTo with the candidate. */
+#ifdef WHERETRACE_ENABLED /* 0x4 */
+ if( sqlite3WhereTrace&0x4 ){
+ sqlite3DebugPrintf(
+ "Update %s cost=%-3d,%3d,%3d order=%c",
+ wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
+ isOrdered>=0 ? isOrdered+'0' : '?');
+ sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
+ wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
+ pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
+ }
+#endif
+ }
+ /* pWLoop is a winner. Add it to the set of best so far */
+ pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
+ pTo->revLoop = revMask;
+ pTo->nRow = nOut;
+ pTo->rCost = rCost;
+ pTo->rUnsorted = rUnsorted;
+ pTo->isOrdered = isOrdered;
+ memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
+ pTo->aLoop[iLoop] = pWLoop;
+ if( nTo>=mxChoice ){
+ mxI = 0;
+ mxCost = aTo[0].rCost;
+ mxUnsorted = aTo[0].nRow;
+ for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
+ if( pTo->rCost>mxCost
+ || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
+ ){
+ mxCost = pTo->rCost;
+ mxUnsorted = pTo->rUnsorted;
+ mxI = jj;
+ }
+ }
+ }
+ }
+ }
+
+#ifdef WHERETRACE_ENABLED /* >=2 */
+ if( sqlite3WhereTrace & 0x02 ){
+ sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
+ for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
+ sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
+ wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
+ pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
+ if( pTo->isOrdered>0 ){
+ sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
+ }else{
+ sqlite3DebugPrintf("\n");
+ }
+ }
+ }
+#endif
+
+ /* Swap the roles of aFrom and aTo for the next generation */
+ pFrom = aTo;
+ aTo = aFrom;
+ aFrom = pFrom;
+ nFrom = nTo;
+ }
+
+ if( nFrom==0 ){
+ sqlite3ErrorMsg(pParse, "no query solution");
+ sqlite3DbFreeNN(db, pSpace);
+ return SQLITE_ERROR;
+ }
+
+ /* Find the lowest cost path. pFrom will be left pointing to that path */
+ pFrom = aFrom;
+ for(ii=1; ii<nFrom; ii++){
+ if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
+ }
+ assert( pWInfo->nLevel==nLoop );
+ /* Load the lowest cost path into pWInfo */
+ for(iLoop=0; iLoop<nLoop; iLoop++){
+ WhereLevel *pLevel = pWInfo->a + iLoop;
+ pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
+ pLevel->iFrom = pWLoop->iTab;
+ pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
+ }
+ if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
+ && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
+ && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
+ && nRowEst
+ ){
+ Bitmask notUsed;
+ int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
+ WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
+ if( rc==pWInfo->pResultSet->nExpr ){
+ pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
+ }
+ }
+ pWInfo->bOrderedInnerLoop = 0;
+ if( pWInfo->pOrderBy ){
+ if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
+ if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
+ pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
+ }
+ }else{
+ pWInfo->nOBSat = pFrom->isOrdered;
+ pWInfo->revMask = pFrom->revLoop;
+ if( pWInfo->nOBSat<=0 ){
+ pWInfo->nOBSat = 0;
+ if( nLoop>0 ){
+ u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
+ if( (wsFlags & WHERE_ONEROW)==0
+ && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
+ ){
+ Bitmask m = 0;
+ int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
+ WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
+ testcase( wsFlags & WHERE_IPK );
+ testcase( wsFlags & WHERE_COLUMN_IN );
+ if( rc==pWInfo->pOrderBy->nExpr ){
+ pWInfo->bOrderedInnerLoop = 1;
+ pWInfo->revMask = m;
+ }
+ }
+ }
+ }else if( nLoop
+ && pWInfo->nOBSat==1
+ && (pWInfo->wctrlFlags & (WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX))!=0
+ ){
+ pWInfo->bOrderedInnerLoop = 1;
+ }
+ }
+ if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
+ && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
+ ){
+ Bitmask revMask = 0;
+ int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
+ pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
+ );
+ assert( pWInfo->sorted==0 );
+ if( nOrder==pWInfo->pOrderBy->nExpr ){
+ pWInfo->sorted = 1;
+ pWInfo->revMask = revMask;
+ }
+ }
+ }
+
+
+ pWInfo->nRowOut = pFrom->nRow;
+
+ /* Free temporary memory and return success */
+ sqlite3DbFreeNN(db, pSpace);
+ return SQLITE_OK;
+}
+
+/*
+** Most queries use only a single table (they are not joins) and have
+** simple == constraints against indexed fields. This routine attempts
+** to plan those simple cases using much less ceremony than the
+** general-purpose query planner, and thereby yield faster sqlite3_prepare()
+** times for the common case.
+**
+** Return non-zero on success, if this query can be handled by this
+** no-frills query planner. Return zero if this query needs the
+** general-purpose query planner.
+*/
+static int whereShortCut(WhereLoopBuilder *pBuilder){
+ WhereInfo *pWInfo;
+ struct SrcList_item *pItem;
+ WhereClause *pWC;
+ WhereTerm *pTerm;
+ WhereLoop *pLoop;
+ int iCur;
+ int j;
+ Table *pTab;
+ Index *pIdx;
+
+ pWInfo = pBuilder->pWInfo;
+ if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
+ assert( pWInfo->pTabList->nSrc>=1 );
+ pItem = pWInfo->pTabList->a;
+ pTab = pItem->pTab;
+ if( IsVirtual(pTab) ) return 0;
+ if( pItem->fg.isIndexedBy ) return 0;
+ iCur = pItem->iCursor;
+ pWC = &pWInfo->sWC;
+ pLoop = pBuilder->pNew;
+ pLoop->wsFlags = 0;
+ pLoop->nSkip = 0;
+ pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
+ if( pTerm ){
+ testcase( pTerm->eOperator & WO_IS );
+ pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
+ pLoop->aLTerm[0] = pTerm;
+ pLoop->nLTerm = 1;
+ pLoop->u.btree.nEq = 1;
+ /* TUNING: Cost of a rowid lookup is 10 */
+ pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
+ }else{
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+ int opMask;
+ assert( pLoop->aLTermSpace==pLoop->aLTerm );
+ if( !IsUniqueIndex(pIdx)
+ || pIdx->pPartIdxWhere!=0
+ || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
+ ) continue;
+ opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
+ for(j=0; j<pIdx->nKeyCol; j++){
+ pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
+ if( pTerm==0 ) break;
+ testcase( pTerm->eOperator & WO_IS );
+ pLoop->aLTerm[j] = pTerm;
+ }
+ if( j!=pIdx->nKeyCol ) continue;
+ pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
+ if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){
+ pLoop->wsFlags |= WHERE_IDX_ONLY;
+ }
+ pLoop->nLTerm = j;
+ pLoop->u.btree.nEq = j;
+ pLoop->u.btree.pIndex = pIdx;
+ /* TUNING: Cost of a unique index lookup is 15 */
+ pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
+ break;
+ }
+ }
+ if( pLoop->wsFlags ){
+ pLoop->nOut = (LogEst)1;
+ pWInfo->a[0].pWLoop = pLoop;
+ assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
+ pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
+ pWInfo->a[0].iTabCur = iCur;
+ pWInfo->nRowOut = 1;
+ if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
+ if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
+ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
+ }
+#ifdef SQLITE_DEBUG
+ pLoop->cId = '0';
+#endif
+ return 1;
+ }
+ return 0;
+}
+
+/*
+** Helper function for exprIsDeterministic().
+*/
+static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
+ if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
+ pWalker->eCode = 0;
+ return WRC_Abort;
+ }
+ return WRC_Continue;
+}
+
+/*
+** Return true if the expression contains no non-deterministic SQL
+** functions. Do not consider non-deterministic SQL functions that are
+** part of sub-select statements.
+*/
+static int exprIsDeterministic(Expr *p){
+ Walker w;
+ memset(&w, 0, sizeof(w));
+ w.eCode = 1;
+ w.xExprCallback = exprNodeIsDeterministic;
+ w.xSelectCallback = sqlite3SelectWalkFail;
+ sqlite3WalkExpr(&w, p);
+ return w.eCode;
+}
+
+
+#ifdef WHERETRACE_ENABLED
+/*
+** Display all WhereLoops in pWInfo
+*/
+static void showAllWhereLoops(WhereInfo *pWInfo, WhereClause *pWC){
+ if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
+ WhereLoop *p;
+ int i;
+ static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
+ "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
+ for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
+ p->cId = zLabel[i%(sizeof(zLabel)-1)];
+ sqlite3WhereLoopPrint(p, pWC);
+ }
+ }
+}
+# define WHERETRACE_ALL_LOOPS(W,C) showAllWhereLoops(W,C)
+#else
+# define WHERETRACE_ALL_LOOPS(W,C)
+#endif
+
+/*
+** Generate the beginning of the loop used for WHERE clause processing.
+** The return value is a pointer to an opaque structure that contains
+** information needed to terminate the loop. Later, the calling routine
+** should invoke sqlite3WhereEnd() with the return value of this function
+** in order to complete the WHERE clause processing.
+**
+** If an error occurs, this routine returns NULL.
+**
+** The basic idea is to do a nested loop, one loop for each table in
+** the FROM clause of a select. (INSERT and UPDATE statements are the
+** same as a SELECT with only a single table in the FROM clause.) For
+** example, if the SQL is this:
+**
+** SELECT * FROM t1, t2, t3 WHERE ...;
+**
+** Then the code generated is conceptually like the following:
+**
+** foreach row1 in t1 do \ Code generated
+** foreach row2 in t2 do |-- by sqlite3WhereBegin()
+** foreach row3 in t3 do /
+** ...
+** end \ Code generated
+** end |-- by sqlite3WhereEnd()
+** end /
+**
+** Note that the loops might not be nested in the order in which they
+** appear in the FROM clause if a different order is better able to make
+** use of indices. Note also that when the IN operator appears in
+** the WHERE clause, it might result in additional nested loops for
+** scanning through all values on the right-hand side of the IN.
+**
+** There are Btree cursors associated with each table. t1 uses cursor
+** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
+** And so forth. This routine generates code to open those VDBE cursors
+** and sqlite3WhereEnd() generates the code to close them.
+**
+** The code that sqlite3WhereBegin() generates leaves the cursors named
+** in pTabList pointing at their appropriate entries. The [...] code
+** can use OP_Column and OP_Rowid opcodes on these cursors to extract
+** data from the various tables of the loop.
+**
+** If the WHERE clause is empty, the foreach loops must each scan their
+** entire tables. Thus a three-way join is an O(N^3) operation. But if
+** the tables have indices and there are terms in the WHERE clause that
+** refer to those indices, a complete table scan can be avoided and the
+** code will run much faster. Most of the work of this routine is checking
+** to see if there are indices that can be used to speed up the loop.
+**
+** Terms of the WHERE clause are also used to limit which rows actually
+** make it to the "..." in the middle of the loop. After each "foreach",
+** terms of the WHERE clause that use only terms in that loop and outer
+** loops are evaluated and if false a jump is made around all subsequent
+** inner loops (or around the "..." if the test occurs within the inner-
+** most loop)
+**
+** OUTER JOINS
+**
+** An outer join of tables t1 and t2 is conceptally coded as follows:
+**
+** foreach row1 in t1 do
+** flag = 0
+** foreach row2 in t2 do
+** start:
+** ...
+** flag = 1
+** end
+** if flag==0 then
+** move the row2 cursor to a null row
+** goto start
+** fi
+** end
+**
+** ORDER BY CLAUSE PROCESSING
+**
+** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
+** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
+** if there is one. If there is no ORDER BY clause or if this routine
+** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
+**
+** The iIdxCur parameter is the cursor number of an index. If
+** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
+** to use for OR clause processing. The WHERE clause should use this
+** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
+** the first cursor in an array of cursors for all indices. iIdxCur should
+** be used to compute the appropriate cursor depending on which index is
+** used.
+*/
+SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
+ Parse *pParse, /* The parser context */
+ SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
+ Expr *pWhere, /* The WHERE clause */
+ ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
+ ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
+ u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
+ int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
+ ** If WHERE_USE_LIMIT, then the limit amount */
+){
+ int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
+ int nTabList; /* Number of elements in pTabList */
+ WhereInfo *pWInfo; /* Will become the return value of this function */
+ Vdbe *v = pParse->pVdbe; /* The virtual database engine */
+ Bitmask notReady; /* Cursors that are not yet positioned */
+ WhereLoopBuilder sWLB; /* The WhereLoop builder */
+ WhereMaskSet *pMaskSet; /* The expression mask set */
+ WhereLevel *pLevel; /* A single level in pWInfo->a[] */
+ WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
+ int ii; /* Loop counter */
+ sqlite3 *db; /* Database connection */
+ int rc; /* Return code */
+ u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
+
+ assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
+ (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
+ && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
+ ));
+
+ /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
+ assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
+ || (wctrlFlags & WHERE_USE_LIMIT)==0 );
+
+ /* Variable initialization */
+ db = pParse->db;
+ memset(&sWLB, 0, sizeof(sWLB));
+
+ /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
+ testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
+ if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
+ sWLB.pOrderBy = pOrderBy;
+
+ /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
+ ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
+ if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
+ wctrlFlags &= ~WHERE_WANT_DISTINCT;
+ }
+
+ /* The number of tables in the FROM clause is limited by the number of
+ ** bits in a Bitmask
+ */
+ testcase( pTabList->nSrc==BMS );
+ if( pTabList->nSrc>BMS ){
+ sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
+ return 0;
+ }
+
+ /* This function normally generates a nested loop for all tables in
+ ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
+ ** only generate code for the first table in pTabList and assume that
+ ** any cursors associated with subsequent tables are uninitialized.
+ */
+ nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
+
+ /* Allocate and initialize the WhereInfo structure that will become the
+ ** return value. A single allocation is used to store the WhereInfo
+ ** struct, the contents of WhereInfo.a[], the WhereClause structure
+ ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
+ ** field (type Bitmask) it must be aligned on an 8-byte boundary on
+ ** some architectures. Hence the ROUND8() below.
+ */
+ nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
+ pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
+ if( db->mallocFailed ){
+ sqlite3DbFree(db, pWInfo);
+ pWInfo = 0;
+ goto whereBeginError;
+ }
+ pWInfo->pParse = pParse;
+ pWInfo->pTabList = pTabList;
+ pWInfo->pOrderBy = pOrderBy;
+ pWInfo->pWhere = pWhere;
+ pWInfo->pResultSet = pResultSet;
+ pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
+ pWInfo->nLevel = nTabList;
+ pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse);
+ pWInfo->wctrlFlags = wctrlFlags;
+ pWInfo->iLimit = iAuxArg;
+ pWInfo->savedNQueryLoop = pParse->nQueryLoop;
+ memset(&pWInfo->nOBSat, 0,
+ offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
+ memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
+ assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
+ pMaskSet = &pWInfo->sMaskSet;
+ sWLB.pWInfo = pWInfo;
+ sWLB.pWC = &pWInfo->sWC;
+ sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
+ assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
+ whereLoopInit(sWLB.pNew);
+#ifdef SQLITE_DEBUG
+ sWLB.pNew->cId = '*';
+#endif
+
+ /* Split the WHERE clause into separate subexpressions where each
+ ** subexpression is separated by an AND operator.
+ */
+ initMaskSet(pMaskSet);
+ sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
+ sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
+
+ /* Special case: No FROM clause
+ */
+ if( nTabList==0 ){
+ if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
+ if( wctrlFlags & WHERE_WANT_DISTINCT ){
+ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
+ }
+ ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
+ }else{
+ /* Assign a bit from the bitmask to every term in the FROM clause.
+ **
+ ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
+ **
+ ** The rule of the previous sentence ensures thta if X is the bitmask for
+ ** a table T, then X-1 is the bitmask for all other tables to the left of T.
+ ** Knowing the bitmask for all tables to the left of a left join is
+ ** important. Ticket #3015.
+ **
+ ** Note that bitmasks are created for all pTabList->nSrc tables in
+ ** pTabList, not just the first nTabList tables. nTabList is normally
+ ** equal to pTabList->nSrc but might be shortened to 1 if the
+ ** WHERE_OR_SUBCLAUSE flag is set.
+ */
+ ii = 0;
+ do{
+ createMask(pMaskSet, pTabList->a[ii].iCursor);
+ sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
+ }while( (++ii)<pTabList->nSrc );
+ #ifdef SQLITE_DEBUG
+ {
+ Bitmask mx = 0;
+ for(ii=0; ii<pTabList->nSrc; ii++){
+ Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
+ assert( m>=mx );
+ mx = m;
+ }
+ }
+ #endif
+ }
+
+ /* Analyze all of the subexpressions. */
+ sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
+ if( db->mallocFailed ) goto whereBeginError;
+
+ /* Special case: WHERE terms that do not refer to any tables in the join
+ ** (constant expressions). Evaluate each such term, and jump over all the
+ ** generated code if the result is not true.
+ **
+ ** Do not do this if the expression contains non-deterministic functions
+ ** that are not within a sub-select. This is not strictly required, but
+ ** preserves SQLite's legacy behaviour in the following two cases:
+ **
+ ** FROM ... WHERE random()>0; -- eval random() once per row
+ ** FROM ... WHERE (SELECT random())>0; -- eval random() once overall
+ */
+ for(ii=0; ii<sWLB.pWC->nTerm; ii++){
+ WhereTerm *pT = &sWLB.pWC->a[ii];
+ if( pT->wtFlags & TERM_VIRTUAL ) continue;
+ if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
+ sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
+ pT->wtFlags |= TERM_CODED;
+ }
+ }
+
+ if( wctrlFlags & WHERE_WANT_DISTINCT ){
+ if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
+ /* The DISTINCT marking is pointless. Ignore it. */
+ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
+ }else if( pOrderBy==0 ){
+ /* Try to ORDER BY the result set to make distinct processing easier */
+ pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
+ pWInfo->pOrderBy = pResultSet;
+ }
+ }
+
+ /* Construct the WhereLoop objects */
+#if defined(WHERETRACE_ENABLED)
+ if( sqlite3WhereTrace & 0xffff ){
+ sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
+ if( wctrlFlags & WHERE_USE_LIMIT ){
+ sqlite3DebugPrintf(", limit: %d", iAuxArg);
+ }
+ sqlite3DebugPrintf(")\n");
+ if( sqlite3WhereTrace & 0x100 ){
+ Select sSelect;
+ memset(&sSelect, 0, sizeof(sSelect));
+ sSelect.selFlags = SF_WhereBegin;
+ sSelect.pSrc = pTabList;
+ sSelect.pWhere = pWhere;
+ sSelect.pOrderBy = pOrderBy;
+ sSelect.pEList = pResultSet;
+ sqlite3TreeViewSelect(0, &sSelect, 0);
+ }
+ }
+ if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
+ sqlite3DebugPrintf("---- WHERE clause at start of analysis:\n");
+ sqlite3WhereClausePrint(sWLB.pWC);
+ }
+#endif
+
+ if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
+ rc = whereLoopAddAll(&sWLB);
+ if( rc ) goto whereBeginError;
+
+#ifdef SQLITE_ENABLE_STAT4
+ /* If one or more WhereTerm.truthProb values were used in estimating
+ ** loop parameters, but then those truthProb values were subsequently
+ ** changed based on STAT4 information while computing subsequent loops,
+ ** then we need to rerun the whole loop building process so that all
+ ** loops will be built using the revised truthProb values. */
+ if( sWLB.bldFlags2 & SQLITE_BLDF2_2NDPASS ){
+ WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
+ WHERETRACE(0xffff,
+ ("**** Redo all loop computations due to"
+ " TERM_HIGHTRUTH changes ****\n"));
+ while( pWInfo->pLoops ){
+ WhereLoop *p = pWInfo->pLoops;
+ pWInfo->pLoops = p->pNextLoop;
+ whereLoopDelete(db, p);
+ }
+ rc = whereLoopAddAll(&sWLB);
+ if( rc ) goto whereBeginError;
+ }
+#endif
+ WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
+
+ wherePathSolver(pWInfo, 0);
+ if( db->mallocFailed ) goto whereBeginError;
+ if( pWInfo->pOrderBy ){
+ wherePathSolver(pWInfo, pWInfo->nRowOut+1);
+ if( db->mallocFailed ) goto whereBeginError;
+ }
+ }
+ if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
+ pWInfo->revMask = ALLBITS;
+ }
+ if( pParse->nErr || NEVER(db->mallocFailed) ){
+ goto whereBeginError;
+ }
+#ifdef WHERETRACE_ENABLED
+ if( sqlite3WhereTrace ){
+ sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
+ if( pWInfo->nOBSat>0 ){
+ sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
+ }
+ switch( pWInfo->eDistinct ){
+ case WHERE_DISTINCT_UNIQUE: {
+ sqlite3DebugPrintf(" DISTINCT=unique");
+ break;
+ }
+ case WHERE_DISTINCT_ORDERED: {
+ sqlite3DebugPrintf(" DISTINCT=ordered");
+ break;
+ }
+ case WHERE_DISTINCT_UNORDERED: {
+ sqlite3DebugPrintf(" DISTINCT=unordered");
+ break;
+ }
+ }
+ sqlite3DebugPrintf("\n");
+ for(ii=0; ii<pWInfo->nLevel; ii++){
+ sqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
+ }
+ }
+#endif
+
+ /* Attempt to omit tables from the join that do not affect the result.
+ ** For a table to not affect the result, the following must be true:
+ **
+ ** 1) The query must not be an aggregate.
+ ** 2) The table must be the RHS of a LEFT JOIN.
+ ** 3) Either the query must be DISTINCT, or else the ON or USING clause
+ ** must contain a constraint that limits the scan of the table to
+ ** at most a single row.
+ ** 4) The table must not be referenced by any part of the query apart
+ ** from its own USING or ON clause.
+ **
+ ** For example, given:
+ **
+ ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
+ ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
+ ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
+ **
+ ** then table t2 can be omitted from the following:
+ **
+ ** SELECT v1, v3 FROM t1
+ ** LEFT JOIN t2 ON (t1.ipk=t2.ipk)
+ ** LEFT JOIN t3 ON (t1.ipk=t3.ipk)
+ **
+ ** or from:
+ **
+ ** SELECT DISTINCT v1, v3 FROM t1
+ ** LEFT JOIN t2
+ ** LEFT JOIN t3 ON (t1.ipk=t3.ipk)
+ */
+ notReady = ~(Bitmask)0;
+ if( pWInfo->nLevel>=2
+ && pResultSet!=0 /* guarantees condition (1) above */
+ && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
+ ){
+ int i;
+ Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
+ if( sWLB.pOrderBy ){
+ tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
+ }
+ for(i=pWInfo->nLevel-1; i>=1; i--){
+ WhereTerm *pTerm, *pEnd;
+ struct SrcList_item *pItem;
+ pLoop = pWInfo->a[i].pWLoop;
+ pItem = &pWInfo->pTabList->a[pLoop->iTab];
+ if( (pItem->fg.jointype & JT_LEFT)==0 ) continue;
+ if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
+ && (pLoop->wsFlags & WHERE_ONEROW)==0
+ ){
+ continue;
+ }
+ if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
+ pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
+ for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
+ if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
+ if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
+ || pTerm->pExpr->iRightJoinTable!=pItem->iCursor
+ ){
+ break;
+ }
+ }
+ }
+ if( pTerm<pEnd ) continue;
+ WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
+ notReady &= ~pLoop->maskSelf;
+ for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
+ if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
+ pTerm->wtFlags |= TERM_CODED;
+ }
+ }
+ if( i!=pWInfo->nLevel-1 ){
+ int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
+ memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
+ }
+ pWInfo->nLevel--;
+ nTabList--;
+ }
+ }
+#if defined(WHERETRACE_ENABLED)
+ if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
+ sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n");
+ sqlite3WhereClausePrint(sWLB.pWC);
+ }
+ WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
+#endif
+ pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
+
+ /* If the caller is an UPDATE or DELETE statement that is requesting
+ ** to use a one-pass algorithm, determine if this is appropriate.
+ **
+ ** A one-pass approach can be used if the caller has requested one
+ ** and either (a) the scan visits at most one row or (b) each
+ ** of the following are true:
+ **
+ ** * the caller has indicated that a one-pass approach can be used
+ ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
+ ** * the table is not a virtual table, and
+ ** * either the scan does not use the OR optimization or the caller
+ ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified
+ ** for DELETE).
+ **
+ ** The last qualification is because an UPDATE statement uses
+ ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
+ ** use a one-pass approach, and this is not set accurately for scans
+ ** that use the OR optimization.
+ */
+ assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
+ if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
+ int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
+ int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
+ assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) );
+ if( bOnerow || (
+ 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
+ && !IsVirtual(pTabList->a[0].pTab)
+ && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
+ )){
+ pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
+ if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
+ if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
+ bFordelete = OPFLAG_FORDELETE;
+ }
+ pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
+ }
+ }
+ }
+
+ /* Open all tables in the pTabList and any indices selected for
+ ** searching those tables.
+ */
+ for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
+ Table *pTab; /* Table to open */
+ int iDb; /* Index of database containing table/index */
+ struct SrcList_item *pTabItem;
+
+ pTabItem = &pTabList->a[pLevel->iFrom];
+ pTab = pTabItem->pTab;
+ iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+ pLoop = pLevel->pWLoop;
+ if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
+ /* Do nothing */
+ }else
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
+ const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
+ int iCur = pTabItem->iCursor;
+ sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
+ }else if( IsVirtual(pTab) ){
+ /* noop */
+ }else
+#endif
+ if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
+ && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
+ int op = OP_OpenRead;
+ if( pWInfo->eOnePass!=ONEPASS_OFF ){
+ op = OP_OpenWrite;
+ pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
+ };
+ sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
+ assert( pTabItem->iCursor==pLevel->iTabCur );
+ testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
+ testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
+ if( pWInfo->eOnePass==ONEPASS_OFF
+ && pTab->nCol<BMS
+ && (pTab->tabFlags & (TF_HasGenerated|TF_WithoutRowid))==0
+ ){
+ /* If we know that only a prefix of the record will be used,
+ ** it is advantageous to reduce the "column count" field in
+ ** the P4 operand of the OP_OpenRead/Write opcode. */
+ Bitmask b = pTabItem->colUsed;
+ int n = 0;
+ for(; b; b=b>>1, n++){}
+ sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
+ assert( n<=pTab->nCol );
+ }
+#ifdef SQLITE_ENABLE_CURSOR_HINTS
+ if( pLoop->u.btree.pIndex!=0 ){
+ sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
+ }else
+#endif
+ {
+ sqlite3VdbeChangeP5(v, bFordelete);
+ }
+#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
+ sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
+ (const u8*)&pTabItem->colUsed, P4_INT64);
+#endif
+ }else{
+ sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
+ }
+ if( pLoop->wsFlags & WHERE_INDEXED ){
+ Index *pIx = pLoop->u.btree.pIndex;
+ int iIndexCur;
+ int op = OP_OpenRead;
+ /* iAuxArg is always set to a positive value if ONEPASS is possible */
+ assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
+ if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
+ && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
+ ){
+ /* This is one term of an OR-optimization using the PRIMARY KEY of a
+ ** WITHOUT ROWID table. No need for a separate index */
+ iIndexCur = pLevel->iTabCur;
+ op = 0;
+ }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
+ Index *pJ = pTabItem->pTab->pIndex;
+ iIndexCur = iAuxArg;
+ assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
+ while( ALWAYS(pJ) && pJ!=pIx ){
+ iIndexCur++;
+ pJ = pJ->pNext;
+ }
+ op = OP_OpenWrite;
+ pWInfo->aiCurOnePass[1] = iIndexCur;
+ }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
+ iIndexCur = iAuxArg;
+ op = OP_ReopenIdx;
+ }else{
+ iIndexCur = pParse->nTab++;
+ }
+ pLevel->iIdxCur = iIndexCur;
+ assert( pIx->pSchema==pTab->pSchema );
+ assert( iIndexCur>=0 );
+ if( op ){
+ sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
+ sqlite3VdbeSetP4KeyInfo(pParse, pIx);
+ if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
+ && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
+ && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0
+ && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
+ && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
+ && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
+ ){
+ sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ);
+ }
+ VdbeComment((v, "%s", pIx->zName));
+#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
+ {
+ u64 colUsed = 0;
+ int ii, jj;
+ for(ii=0; ii<pIx->nColumn; ii++){
+ jj = pIx->aiColumn[ii];
+ if( jj<0 ) continue;
+ if( jj>63 ) jj = 63;
+ if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
+ colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
+ }
+ sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
+ (u8*)&colUsed, P4_INT64);
+ }
+#endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
+ }
+ }
+ if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
+ }
+ pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
+ if( db->mallocFailed ) goto whereBeginError;
+
+ /* Generate the code to do the search. Each iteration of the for
+ ** loop below generates code for a single nested loop of the VM
+ ** program.
+ */
+ for(ii=0; ii<nTabList; ii++){
+ int addrExplain;
+ int wsFlags;
+ pLevel = &pWInfo->a[ii];
+ wsFlags = pLevel->pWLoop->wsFlags;
+#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
+ if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
+ constructAutomaticIndex(pParse, &pWInfo->sWC,
+ &pTabList->a[pLevel->iFrom], notReady, pLevel);
+ if( db->mallocFailed ) goto whereBeginError;
+ }
+#endif
+ addrExplain = sqlite3WhereExplainOneScan(
+ pParse, pTabList, pLevel, wctrlFlags
+ );
+ pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
+ notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady);
+ pWInfo->iContinue = pLevel->addrCont;
+ if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
+ sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
+ }
+ }
+
+ /* Done. */
+ VdbeModuleComment((v, "Begin WHERE-core"));
+ pWInfo->iEndWhere = sqlite3VdbeCurrentAddr(v);
+ return pWInfo;
+
+ /* Jump here if malloc fails */
+whereBeginError:
+ if( pWInfo ){
+ pParse->nQueryLoop = pWInfo->savedNQueryLoop;
+ whereInfoFree(db, pWInfo);
+ }
+ return 0;
+}
+
+/*
+** Part of sqlite3WhereEnd() will rewrite opcodes to reference the
+** index rather than the main table. In SQLITE_DEBUG mode, we want
+** to trace those changes if PRAGMA vdbe_addoptrace=on. This routine
+** does that.
+*/
+#ifndef SQLITE_DEBUG
+# define OpcodeRewriteTrace(D,K,P) /* no-op */
+#else
+# define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P)
+ static void sqlite3WhereOpcodeRewriteTrace(
+ sqlite3 *db,
+ int pc,
+ VdbeOp *pOp
+ ){
+ if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return;
+ sqlite3VdbePrintOp(0, pc, pOp);
+ }
+#endif
+
+/*
+** Generate the end of the WHERE loop. See comments on
+** sqlite3WhereBegin() for additional information.
+*/
+SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
+ Parse *pParse = pWInfo->pParse;
+ Vdbe *v = pParse->pVdbe;
+ int i;
+ WhereLevel *pLevel;
+ WhereLoop *pLoop;
+ SrcList *pTabList = pWInfo->pTabList;
+ sqlite3 *db = pParse->db;
+ int iEnd = sqlite3VdbeCurrentAddr(v);
+
+ /* Generate loop termination code.
+ */
+ VdbeModuleComment((v, "End WHERE-core"));
+ for(i=pWInfo->nLevel-1; i>=0; i--){
+ int addr;
+ pLevel = &pWInfo->a[i];
+ pLoop = pLevel->pWLoop;
+ if( pLevel->op!=OP_Noop ){
+#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
+ int addrSeek = 0;
+ Index *pIdx;
+ int n;
+ if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
+ && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */
+ && (pLoop->wsFlags & WHERE_INDEXED)!=0
+ && (pIdx = pLoop->u.btree.pIndex)->hasStat1
+ && (n = pLoop->u.btree.nDistinctCol)>0
+ && pIdx->aiRowLogEst[n]>=36
+ ){
+ int r1 = pParse->nMem+1;
+ int j, op;
+ for(j=0; j<n; j++){
+ sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
+ }
+ pParse->nMem += n+1;
+ op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
+ addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
+ VdbeCoverageIf(v, op==OP_SeekLT);
+ VdbeCoverageIf(v, op==OP_SeekGT);
+ sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
+ }
+#endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
+ /* The common case: Advance to the next row */
+ sqlite3VdbeResolveLabel(v, pLevel->addrCont);
+ sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
+ sqlite3VdbeChangeP5(v, pLevel->p5);
+ VdbeCoverage(v);
+ VdbeCoverageIf(v, pLevel->op==OP_Next);
+ VdbeCoverageIf(v, pLevel->op==OP_Prev);
+ VdbeCoverageIf(v, pLevel->op==OP_VNext);
+ if( pLevel->regBignull ){
+ sqlite3VdbeResolveLabel(v, pLevel->addrBignull);
+ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1);
+ VdbeCoverage(v);
+ }
+#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
+ if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
+#endif
+ }else{
+ sqlite3VdbeResolveLabel(v, pLevel->addrCont);
+ }
+ if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
+ struct InLoop *pIn;
+ int j;
+ sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
+ for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
+ sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
+ if( pIn->eEndLoopOp!=OP_Noop ){
+ if( pIn->nPrefix ){
+ int bEarlyOut =
+ (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
+ && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0;
+ if( pLevel->iLeftJoin ){
+ /* For LEFT JOIN queries, cursor pIn->iCur may not have been
+ ** opened yet. This occurs for WHERE clauses such as
+ ** "a = ? AND b IN (...)", where the index is on (a, b). If
+ ** the RHS of the (a=?) is NULL, then the "b IN (...)" may
+ ** never have been coded, but the body of the loop run to
+ ** return the null-row. So, if the cursor is not open yet,
+ ** jump over the OP_Next or OP_Prev instruction about to
+ ** be coded. */
+ sqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur,
+ sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut);
+ VdbeCoverage(v);
+ }
+ if( bEarlyOut ){
+ sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
+ sqlite3VdbeCurrentAddr(v)+2,
+ pIn->iBase, pIn->nPrefix);
+ VdbeCoverage(v);
+ }
+ }
+ sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
+ VdbeCoverage(v);
+ VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
+ VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
+ }
+ sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
+ }
+ }
+ sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
+ if( pLevel->addrSkip ){
+ sqlite3VdbeGoto(v, pLevel->addrSkip);
+ VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
+ sqlite3VdbeJumpHere(v, pLevel->addrSkip);
+ sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
+ }
+#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
+ if( pLevel->addrLikeRep ){
+ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
+ pLevel->addrLikeRep);
+ VdbeCoverage(v);
+ }
+#endif
+ if( pLevel->iLeftJoin ){
+ int ws = pLoop->wsFlags;
+ addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
+ assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
+ if( (ws & WHERE_IDX_ONLY)==0 ){
+ assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
+ sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
+ }
+ if( (ws & WHERE_INDEXED)
+ || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
+ ){
+ sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
+ }
+ if( pLevel->op==OP_Return ){
+ sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
+ }else{
+ sqlite3VdbeGoto(v, pLevel->addrFirst);
+ }
+ sqlite3VdbeJumpHere(v, addr);
+ }
+ VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
+ pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
+ }
+
+ /* The "break" point is here, just past the end of the outer loop.
+ ** Set it.
+ */
+ sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
+
+ assert( pWInfo->nLevel<=pTabList->nSrc );
+ for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
+ int k, last;
+ VdbeOp *pOp, *pLastOp;
+ Index *pIdx = 0;
+ struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
+ Table *pTab = pTabItem->pTab;
+ assert( pTab!=0 );
+ pLoop = pLevel->pWLoop;
+
+ /* For a co-routine, change all OP_Column references to the table of
+ ** the co-routine into OP_Copy of result contained in a register.
+ ** OP_Rowid becomes OP_Null.
+ */
+ if( pTabItem->fg.viaCoroutine ){
+ testcase( pParse->db->mallocFailed );
+ translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
+ pTabItem->regResult, 0);
+ continue;
+ }
+
+#ifdef SQLITE_ENABLE_EARLY_CURSOR_CLOSE
+ /* Close all of the cursors that were opened by sqlite3WhereBegin.
+ ** Except, do not close cursors that will be reused by the OR optimization
+ ** (WHERE_OR_SUBCLAUSE). And do not close the OP_OpenWrite cursors
+ ** created for the ONEPASS optimization.
+ */
+ if( (pTab->tabFlags & TF_Ephemeral)==0
+ && pTab->pSelect==0
+ && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
+ ){
+ int ws = pLoop->wsFlags;
+ if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
+ sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
+ }
+ if( (ws & WHERE_INDEXED)!=0
+ && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
+ && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
+ ){
+ sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
+ }
+ }
+#endif
+
+ /* If this scan uses an index, make VDBE code substitutions to read data
+ ** from the index instead of from the table where possible. In some cases
+ ** this optimization prevents the table from ever being read, which can
+ ** yield a significant performance boost.
+ **
+ ** Calls to the code generator in between sqlite3WhereBegin and
+ ** sqlite3WhereEnd will have created code that references the table
+ ** directly. This loop scans all that code looking for opcodes
+ ** that reference the table and converts them into opcodes that
+ ** reference the index.
+ */
+ if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
+ pIdx = pLoop->u.btree.pIndex;
+ }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
+ pIdx = pLevel->u.pCovidx;
+ }
+ if( pIdx
+ && !db->mallocFailed
+ ){
+ if( pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable) ){
+ last = iEnd;
+ }else{
+ last = pWInfo->iEndWhere;
+ }
+ k = pLevel->addrBody + 1;
+#ifdef SQLITE_DEBUG
+ if( db->flags & SQLITE_VdbeAddopTrace ){
+ printf("TRANSLATE opcodes in range %d..%d\n", k, last-1);
+ }
+ /* Proof that the "+1" on the k value above is safe */
+ pOp = sqlite3VdbeGetOp(v, k - 1);
+ assert( pOp->opcode!=OP_Column || pOp->p1!=pLevel->iTabCur );
+ assert( pOp->opcode!=OP_Rowid || pOp->p1!=pLevel->iTabCur );
+ assert( pOp->opcode!=OP_IfNullRow || pOp->p1!=pLevel->iTabCur );
+#endif
+ pOp = sqlite3VdbeGetOp(v, k);
+ pLastOp = pOp + (last - k);
+ assert( pOp<pLastOp );
+ do{
+ if( pOp->p1!=pLevel->iTabCur ){
+ /* no-op */
+ }else if( pOp->opcode==OP_Column
+#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
+ || pOp->opcode==OP_Offset
+#endif
+ ){
+ int x = pOp->p2;
+ assert( pIdx->pTable==pTab );
+ if( !HasRowid(pTab) ){
+ Index *pPk = sqlite3PrimaryKeyIndex(pTab);
+ x = pPk->aiColumn[x];
+ assert( x>=0 );
+ }else{
+ testcase( x!=sqlite3StorageColumnToTable(pTab,x) );
+ x = sqlite3StorageColumnToTable(pTab,x);
+ }
+ x = sqlite3TableColumnToIndex(pIdx, x);
+ if( x>=0 ){
+ pOp->p2 = x;
+ pOp->p1 = pLevel->iIdxCur;
+ OpcodeRewriteTrace(db, k, pOp);
+ }
+ assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
+ || pWInfo->eOnePass );
+ }else if( pOp->opcode==OP_Rowid ){
+ pOp->p1 = pLevel->iIdxCur;
+ pOp->opcode = OP_IdxRowid;
+ OpcodeRewriteTrace(db, k, pOp);
+ }else if( pOp->opcode==OP_IfNullRow ){
+ pOp->p1 = pLevel->iIdxCur;
+ OpcodeRewriteTrace(db, k, pOp);
+ }
+#ifdef SQLITE_DEBUG
+ k++;
+#endif
+ }while( (++pOp)<pLastOp );
+#ifdef SQLITE_DEBUG
+ if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n");
+#endif
+ }
+ }
+
+ /* Undo all Expr node modifications */
+ while( pWInfo->pExprMods ){
+ WhereExprMod *p = pWInfo->pExprMods;
+ pWInfo->pExprMods = p->pNext;
+ memcpy(p->pExpr, &p->orig, sizeof(p->orig));
+ sqlite3DbFree(db, p);
+ }
+
+ /* Final cleanup
+ */
+ pParse->nQueryLoop = pWInfo->savedNQueryLoop;
+ whereInfoFree(db, pWInfo);
+ return;
+}
+
+/************** End of where.c ***********************************************/
+/************** Begin file window.c ******************************************/
+/*
+** 2018 May 08
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+*/
+/* #include "sqliteInt.h" */
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+
+/*
+** SELECT REWRITING
+**
+** Any SELECT statement that contains one or more window functions in
+** either the select list or ORDER BY clause (the only two places window
+** functions may be used) is transformed by function sqlite3WindowRewrite()
+** in order to support window function processing. For example, with the
+** schema:
+**
+** CREATE TABLE t1(a, b, c, d, e, f, g);
+**
+** the statement:
+**
+** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e;
+**
+** is transformed to:
+**
+** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM (
+** SELECT a, e, c, d, b FROM t1 ORDER BY c, d
+** ) ORDER BY e;
+**
+** The flattening optimization is disabled when processing this transformed
+** SELECT statement. This allows the implementation of the window function
+** (in this case max()) to process rows sorted in order of (c, d), which
+** makes things easier for obvious reasons. More generally:
+**
+** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to
+** the sub-query.
+**
+** * ORDER BY, LIMIT and OFFSET remain part of the parent query.
+**
+** * Terminals from each of the expression trees that make up the
+** select-list and ORDER BY expressions in the parent query are
+** selected by the sub-query. For the purposes of the transformation,
+** terminals are column references and aggregate functions.
+**
+** If there is more than one window function in the SELECT that uses
+** the same window declaration (the OVER bit), then a single scan may
+** be used to process more than one window function. For example:
+**
+** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
+** min(e) OVER (PARTITION BY c ORDER BY d)
+** FROM t1;
+**
+** is transformed in the same way as the example above. However:
+**
+** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
+** min(e) OVER (PARTITION BY a ORDER BY b)
+** FROM t1;
+**
+** Must be transformed to:
+**
+** SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM (
+** SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM
+** SELECT a, e, c, d, b FROM t1 ORDER BY a, b
+** ) ORDER BY c, d
+** ) ORDER BY e;
+**
+** so that both min() and max() may process rows in the order defined by
+** their respective window declarations.
+**
+** INTERFACE WITH SELECT.C
+**
+** When processing the rewritten SELECT statement, code in select.c calls
+** sqlite3WhereBegin() to begin iterating through the results of the
+** sub-query, which is always implemented as a co-routine. It then calls
+** sqlite3WindowCodeStep() to process rows and finish the scan by calling
+** sqlite3WhereEnd().
+**
+** sqlite3WindowCodeStep() generates VM code so that, for each row returned
+** by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked.
+** When the sub-routine is invoked:
+**
+** * The results of all window-functions for the row are stored
+** in the associated Window.regResult registers.
+**
+** * The required terminal values are stored in the current row of
+** temp table Window.iEphCsr.
+**
+** In some cases, depending on the window frame and the specific window
+** functions invoked, sqlite3WindowCodeStep() caches each entire partition
+** in a temp table before returning any rows. In other cases it does not.
+** This detail is encapsulated within this file, the code generated by
+** select.c is the same in either case.
+**
+** BUILT-IN WINDOW FUNCTIONS
+**
+** This implementation features the following built-in window functions:
+**
+** row_number()
+** rank()
+** dense_rank()
+** percent_rank()
+** cume_dist()
+** ntile(N)
+** lead(expr [, offset [, default]])
+** lag(expr [, offset [, default]])
+** first_value(expr)
+** last_value(expr)
+** nth_value(expr, N)
+**
+** These are the same built-in window functions supported by Postgres.
+** Although the behaviour of aggregate window functions (functions that
+** can be used as either aggregates or window funtions) allows them to
+** be implemented using an API, built-in window functions are much more
+** esoteric. Additionally, some window functions (e.g. nth_value())
+** may only be implemented by caching the entire partition in memory.
+** As such, some built-in window functions use the same API as aggregate
+** window functions and some are implemented directly using VDBE
+** instructions. Additionally, for those functions that use the API, the
+** window frame is sometimes modified before the SELECT statement is
+** rewritten. For example, regardless of the specified window frame, the
+** row_number() function always uses:
+**
+** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
+**
+** See sqlite3WindowUpdate() for details.
+**
+** As well as some of the built-in window functions, aggregate window
+** functions min() and max() are implemented using VDBE instructions if
+** the start of the window frame is declared as anything other than
+** UNBOUNDED PRECEDING.
+*/
+
+/*
+** Implementation of built-in window function row_number(). Assumes that the
+** window frame has been coerced to:
+**
+** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
+*/
+static void row_numberStepFunc(
+ sqlite3_context *pCtx,
+ int nArg,
+ sqlite3_value **apArg
+){
+ i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p ) (*p)++;
+ UNUSED_PARAMETER(nArg);
+ UNUSED_PARAMETER(apArg);
+}
+static void row_numberValueFunc(sqlite3_context *pCtx){
+ i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ sqlite3_result_int64(pCtx, (p ? *p : 0));
+}
+
+/*
+** Context object type used by rank(), dense_rank(), percent_rank() and
+** cume_dist().
+*/
+struct CallCount {
+ i64 nValue;
+ i64 nStep;
+ i64 nTotal;
+};
+
+/*
+** Implementation of built-in window function dense_rank(). Assumes that
+** the window frame has been set to:
+**
+** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
+*/
+static void dense_rankStepFunc(
+ sqlite3_context *pCtx,
+ int nArg,
+ sqlite3_value **apArg
+){
+ struct CallCount *p;
+ p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p ) p->nStep = 1;
+ UNUSED_PARAMETER(nArg);
+ UNUSED_PARAMETER(apArg);
+}
+static void dense_rankValueFunc(sqlite3_context *pCtx){
+ struct CallCount *p;
+ p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p ){
+ if( p->nStep ){
+ p->nValue++;
+ p->nStep = 0;
+ }
+ sqlite3_result_int64(pCtx, p->nValue);
+ }
+}
+
+/*
+** Implementation of built-in window function nth_value(). This
+** implementation is used in "slow mode" only - when the EXCLUDE clause
+** is not set to the default value "NO OTHERS".
+*/
+struct NthValueCtx {
+ i64 nStep;
+ sqlite3_value *pValue;
+};
+static void nth_valueStepFunc(
+ sqlite3_context *pCtx,
+ int nArg,
+ sqlite3_value **apArg
+){
+ struct NthValueCtx *p;
+ p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p ){
+ i64 iVal;
+ switch( sqlite3_value_numeric_type(apArg[1]) ){
+ case SQLITE_INTEGER:
+ iVal = sqlite3_value_int64(apArg[1]);
+ break;
+ case SQLITE_FLOAT: {
+ double fVal = sqlite3_value_double(apArg[1]);
+ if( ((i64)fVal)!=fVal ) goto error_out;
+ iVal = (i64)fVal;
+ break;
+ }
+ default:
+ goto error_out;
+ }
+ if( iVal<=0 ) goto error_out;
+
+ p->nStep++;
+ if( iVal==p->nStep ){
+ p->pValue = sqlite3_value_dup(apArg[0]);
+ if( !p->pValue ){
+ sqlite3_result_error_nomem(pCtx);
+ }
+ }
+ }
+ UNUSED_PARAMETER(nArg);
+ UNUSED_PARAMETER(apArg);
+ return;
+
+ error_out:
+ sqlite3_result_error(
+ pCtx, "second argument to nth_value must be a positive integer", -1
+ );
+}
+static void nth_valueFinalizeFunc(sqlite3_context *pCtx){
+ struct NthValueCtx *p;
+ p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0);
+ if( p && p->pValue ){
+ sqlite3_result_value(pCtx, p->pValue);
+ sqlite3_value_free(p->pValue);
+ p->pValue = 0;
+ }
+}
+#define nth_valueInvFunc noopStepFunc
+#define nth_valueValueFunc noopValueFunc
+
+static void first_valueStepFunc(
+ sqlite3_context *pCtx,
+ int nArg,
+ sqlite3_value **apArg
+){
+ struct NthValueCtx *p;
+ p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p && p->pValue==0 ){
+ p->pValue = sqlite3_value_dup(apArg[0]);
+ if( !p->pValue ){
+ sqlite3_result_error_nomem(pCtx);
+ }
+ }
+ UNUSED_PARAMETER(nArg);
+ UNUSED_PARAMETER(apArg);
+}
+static void first_valueFinalizeFunc(sqlite3_context *pCtx){
+ struct NthValueCtx *p;
+ p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p && p->pValue ){
+ sqlite3_result_value(pCtx, p->pValue);
+ sqlite3_value_free(p->pValue);
+ p->pValue = 0;
+ }
+}
+#define first_valueInvFunc noopStepFunc
+#define first_valueValueFunc noopValueFunc
+
+/*
+** Implementation of built-in window function rank(). Assumes that
+** the window frame has been set to:
+**
+** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
+*/
+static void rankStepFunc(
+ sqlite3_context *pCtx,
+ int nArg,
+ sqlite3_value **apArg
+){
+ struct CallCount *p;
+ p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p ){
+ p->nStep++;
+ if( p->nValue==0 ){
+ p->nValue = p->nStep;
+ }
+ }
+ UNUSED_PARAMETER(nArg);
+ UNUSED_PARAMETER(apArg);
+}
+static void rankValueFunc(sqlite3_context *pCtx){
+ struct CallCount *p;
+ p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p ){
+ sqlite3_result_int64(pCtx, p->nValue);
+ p->nValue = 0;
+ }
+}
+
+/*
+** Implementation of built-in window function percent_rank(). Assumes that
+** the window frame has been set to:
+**
+** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+*/
+static void percent_rankStepFunc(
+ sqlite3_context *pCtx,
+ int nArg,
+ sqlite3_value **apArg
+){
+ struct CallCount *p;
+ UNUSED_PARAMETER(nArg); assert( nArg==0 );
+ UNUSED_PARAMETER(apArg);
+ p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p ){
+ p->nTotal++;
+ }
+}
+static void percent_rankInvFunc(
+ sqlite3_context *pCtx,
+ int nArg,
+ sqlite3_value **apArg
+){
+ struct CallCount *p;
+ UNUSED_PARAMETER(nArg); assert( nArg==0 );
+ UNUSED_PARAMETER(apArg);
+ p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ p->nStep++;
+}
+static void percent_rankValueFunc(sqlite3_context *pCtx){
+ struct CallCount *p;
+ p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p ){
+ p->nValue = p->nStep;
+ if( p->nTotal>1 ){
+ double r = (double)p->nValue / (double)(p->nTotal-1);
+ sqlite3_result_double(pCtx, r);
+ }else{
+ sqlite3_result_double(pCtx, 0.0);
+ }
+ }
+}
+#define percent_rankFinalizeFunc percent_rankValueFunc
+
+/*
+** Implementation of built-in window function cume_dist(). Assumes that
+** the window frame has been set to:
+**
+** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
+*/
+static void cume_distStepFunc(
+ sqlite3_context *pCtx,
+ int nArg,
+ sqlite3_value **apArg
+){
+ struct CallCount *p;
+ UNUSED_PARAMETER(nArg); assert( nArg==0 );
+ UNUSED_PARAMETER(apArg);
+ p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p ){
+ p->nTotal++;
+ }
+}
+static void cume_distInvFunc(
+ sqlite3_context *pCtx,
+ int nArg,
+ sqlite3_value **apArg
+){
+ struct CallCount *p;
+ UNUSED_PARAMETER(nArg); assert( nArg==0 );
+ UNUSED_PARAMETER(apArg);
+ p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ p->nStep++;
+}
+static void cume_distValueFunc(sqlite3_context *pCtx){
+ struct CallCount *p;
+ p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0);
+ if( p ){
+ double r = (double)(p->nStep) / (double)(p->nTotal);
+ sqlite3_result_double(pCtx, r);
+ }
+}
+#define cume_distFinalizeFunc cume_distValueFunc
+
+/*
+** Context object for ntile() window function.
+*/
+struct NtileCtx {
+ i64 nTotal; /* Total rows in partition */
+ i64 nParam; /* Parameter passed to ntile(N) */
+ i64 iRow; /* Current row */
+};
+
+/*
+** Implementation of ntile(). This assumes that the window frame has
+** been coerced to:
+**
+** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
+*/
+static void ntileStepFunc(
+ sqlite3_context *pCtx,
+ int nArg,
+ sqlite3_value **apArg
+){
+ struct NtileCtx *p;
+ assert( nArg==1 ); UNUSED_PARAMETER(nArg);
+ p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p ){
+ if( p->nTotal==0 ){
+ p->nParam = sqlite3_value_int64(apArg[0]);
+ if( p->nParam<=0 ){
+ sqlite3_result_error(
+ pCtx, "argument of ntile must be a positive integer", -1
+ );
+ }
+ }
+ p->nTotal++;
+ }
+}
+static void ntileInvFunc(
+ sqlite3_context *pCtx,
+ int nArg,
+ sqlite3_value **apArg
+){
+ struct NtileCtx *p;
+ assert( nArg==1 ); UNUSED_PARAMETER(nArg);
+ UNUSED_PARAMETER(apArg);
+ p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ p->iRow++;
+}
+static void ntileValueFunc(sqlite3_context *pCtx){
+ struct NtileCtx *p;
+ p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p && p->nParam>0 ){
+ int nSize = (p->nTotal / p->nParam);
+ if( nSize==0 ){
+ sqlite3_result_int64(pCtx, p->iRow+1);
+ }else{
+ i64 nLarge = p->nTotal - p->nParam*nSize;
+ i64 iSmall = nLarge*(nSize+1);
+ i64 iRow = p->iRow;
+
+ assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
+
+ if( iRow<iSmall ){
+ sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
+ }else{
+ sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
+ }
+ }
+ }
+}
+#define ntileFinalizeFunc ntileValueFunc
+
+/*
+** Context object for last_value() window function.
+*/
+struct LastValueCtx {
+ sqlite3_value *pVal;
+ int nVal;
+};
+
+/*
+** Implementation of last_value().
+*/
+static void last_valueStepFunc(
+ sqlite3_context *pCtx,
+ int nArg,
+ sqlite3_value **apArg
+){
+ struct LastValueCtx *p;
+ UNUSED_PARAMETER(nArg);
+ p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p ){
+ sqlite3_value_free(p->pVal);
+ p->pVal = sqlite3_value_dup(apArg[0]);
+ if( p->pVal==0 ){
+ sqlite3_result_error_nomem(pCtx);
+ }else{
+ p->nVal++;
+ }
+ }
+}
+static void last_valueInvFunc(
+ sqlite3_context *pCtx,
+ int nArg,
+ sqlite3_value **apArg
+){
+ struct LastValueCtx *p;
+ UNUSED_PARAMETER(nArg);
+ UNUSED_PARAMETER(apArg);
+ p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( ALWAYS(p) ){
+ p->nVal--;
+ if( p->nVal==0 ){
+ sqlite3_value_free(p->pVal);
+ p->pVal = 0;
+ }
+ }
+}
+static void last_valueValueFunc(sqlite3_context *pCtx){
+ struct LastValueCtx *p;
+ p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0);
+ if( p && p->pVal ){
+ sqlite3_result_value(pCtx, p->pVal);
+ }
+}
+static void last_valueFinalizeFunc(sqlite3_context *pCtx){
+ struct LastValueCtx *p;
+ p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
+ if( p && p->pVal ){
+ sqlite3_result_value(pCtx, p->pVal);
+ sqlite3_value_free(p->pVal);
+ p->pVal = 0;
+ }
+}
+
+/*
+** Static names for the built-in window function names. These static
+** names are used, rather than string literals, so that FuncDef objects
+** can be associated with a particular window function by direct
+** comparison of the zName pointer. Example:
+**
+** if( pFuncDef->zName==row_valueName ){ ... }
+*/
+static const char row_numberName[] = "row_number";
+static const char dense_rankName[] = "dense_rank";
+static const char rankName[] = "rank";
+static const char percent_rankName[] = "percent_rank";
+static const char cume_distName[] = "cume_dist";
+static const char ntileName[] = "ntile";
+static const char last_valueName[] = "last_value";
+static const char nth_valueName[] = "nth_value";
+static const char first_valueName[] = "first_value";
+static const char leadName[] = "lead";
+static const char lagName[] = "lag";
+
+/*
+** No-op implementations of xStep() and xFinalize(). Used as place-holders
+** for built-in window functions that never call those interfaces.
+**
+** The noopValueFunc() is called but is expected to do nothing. The
+** noopStepFunc() is never called, and so it is marked with NO_TEST to
+** let the test coverage routine know not to expect this function to be
+** invoked.
+*/
+static void noopStepFunc( /*NO_TEST*/
+ sqlite3_context *p, /*NO_TEST*/
+ int n, /*NO_TEST*/
+ sqlite3_value **a /*NO_TEST*/
+){ /*NO_TEST*/
+ UNUSED_PARAMETER(p); /*NO_TEST*/
+ UNUSED_PARAMETER(n); /*NO_TEST*/
+ UNUSED_PARAMETER(a); /*NO_TEST*/
+ assert(0); /*NO_TEST*/
+} /*NO_TEST*/
+static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
+
+/* Window functions that use all window interfaces: xStep, xFinal,
+** xValue, and xInverse */
+#define WINDOWFUNCALL(name,nArg,extra) { \
+ nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
+ name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
+ name ## InvFunc, name ## Name, {0} \
+}
+
+/* Window functions that are implemented using bytecode and thus have
+** no-op routines for their methods */
+#define WINDOWFUNCNOOP(name,nArg,extra) { \
+ nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
+ noopStepFunc, noopValueFunc, noopValueFunc, \
+ noopStepFunc, name ## Name, {0} \
+}
+
+/* Window functions that use all window interfaces: xStep, the
+** same routine for xFinalize and xValue and which never call
+** xInverse. */
+#define WINDOWFUNCX(name,nArg,extra) { \
+ nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
+ name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
+ noopStepFunc, name ## Name, {0} \
+}
+
+
+/*
+** Register those built-in window functions that are not also aggregates.
+*/
+SQLITE_PRIVATE void sqlite3WindowFunctions(void){
+ static FuncDef aWindowFuncs[] = {
+ WINDOWFUNCX(row_number, 0, 0),
+ WINDOWFUNCX(dense_rank, 0, 0),
+ WINDOWFUNCX(rank, 0, 0),
+ WINDOWFUNCALL(percent_rank, 0, 0),
+ WINDOWFUNCALL(cume_dist, 0, 0),
+ WINDOWFUNCALL(ntile, 1, 0),
+ WINDOWFUNCALL(last_value, 1, 0),
+ WINDOWFUNCALL(nth_value, 2, 0),
+ WINDOWFUNCALL(first_value, 1, 0),
+ WINDOWFUNCNOOP(lead, 1, 0),
+ WINDOWFUNCNOOP(lead, 2, 0),
+ WINDOWFUNCNOOP(lead, 3, 0),
+ WINDOWFUNCNOOP(lag, 1, 0),
+ WINDOWFUNCNOOP(lag, 2, 0),
+ WINDOWFUNCNOOP(lag, 3, 0),
+ };
+ sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
+}
+
+static Window *windowFind(Parse *pParse, Window *pList, const char *zName){
+ Window *p;
+ for(p=pList; p; p=p->pNextWin){
+ if( sqlite3StrICmp(p->zName, zName)==0 ) break;
+ }
+ if( p==0 ){
+ sqlite3ErrorMsg(pParse, "no such window: %s", zName);
+ }
+ return p;
+}
+
+/*
+** This function is called immediately after resolving the function name
+** for a window function within a SELECT statement. Argument pList is a
+** linked list of WINDOW definitions for the current SELECT statement.
+** Argument pFunc is the function definition just resolved and pWin
+** is the Window object representing the associated OVER clause. This
+** function updates the contents of pWin as follows:
+**
+** * If the OVER clause refered to a named window (as in "max(x) OVER win"),
+** search list pList for a matching WINDOW definition, and update pWin
+** accordingly. If no such WINDOW clause can be found, leave an error
+** in pParse.
+**
+** * If the function is a built-in window function that requires the
+** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
+** of this file), pWin is updated here.
+*/
+SQLITE_PRIVATE void sqlite3WindowUpdate(
+ Parse *pParse,
+ Window *pList, /* List of named windows for this SELECT */
+ Window *pWin, /* Window frame to update */
+ FuncDef *pFunc /* Window function definition */
+){
+ if( pWin->zName && pWin->eFrmType==0 ){
+ Window *p = windowFind(pParse, pList, pWin->zName);
+ if( p==0 ) return;
+ pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
+ pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
+ pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
+ pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
+ pWin->eStart = p->eStart;
+ pWin->eEnd = p->eEnd;
+ pWin->eFrmType = p->eFrmType;
+ pWin->eExclude = p->eExclude;
+ }else{
+ sqlite3WindowChain(pParse, pWin, pList);
+ }
+ if( (pWin->eFrmType==TK_RANGE)
+ && (pWin->pStart || pWin->pEnd)
+ && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
+ ){
+ sqlite3ErrorMsg(pParse,
+ "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
+ );
+ }else
+ if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
+ sqlite3 *db = pParse->db;
+ if( pWin->pFilter ){
+ sqlite3ErrorMsg(pParse,
+ "FILTER clause may only be used with aggregate window functions"
+ );
+ }else{
+ struct WindowUpdate {
+ const char *zFunc;
+ int eFrmType;
+ int eStart;
+ int eEnd;
+ } aUp[] = {
+ { row_numberName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
+ { dense_rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
+ { rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
+ { percent_rankName, TK_GROUPS, TK_CURRENT, TK_UNBOUNDED },
+ { cume_distName, TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED },
+ { ntileName, TK_ROWS, TK_CURRENT, TK_UNBOUNDED },
+ { leadName, TK_ROWS, TK_UNBOUNDED, TK_UNBOUNDED },
+ { lagName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
+ };
+ int i;
+ for(i=0; i<ArraySize(aUp); i++){
+ if( pFunc->zName==aUp[i].zFunc ){
+ sqlite3ExprDelete(db, pWin->pStart);
+ sqlite3ExprDelete(db, pWin->pEnd);
+ pWin->pEnd = pWin->pStart = 0;
+ pWin->eFrmType = aUp[i].eFrmType;
+ pWin->eStart = aUp[i].eStart;
+ pWin->eEnd = aUp[i].eEnd;
+ pWin->eExclude = 0;
+ if( pWin->eStart==TK_FOLLOWING ){
+ pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1");
+ }
+ break;
+ }
+ }
+ }
+ }
+ pWin->pFunc = pFunc;
+}
+
+/*
+** Context object passed through sqlite3WalkExprList() to
+** selectWindowRewriteExprCb() by selectWindowRewriteEList().
+*/
+typedef struct WindowRewrite WindowRewrite;
+struct WindowRewrite {
+ Window *pWin;
+ SrcList *pSrc;
+ ExprList *pSub;
+ Table *pTab;
+ Select *pSubSelect; /* Current sub-select, if any */
+};
+
+/*
+** Callback function used by selectWindowRewriteEList(). If necessary,
+** this function appends to the output expression-list and updates
+** expression (*ppExpr) in place.
+*/
+static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
+ struct WindowRewrite *p = pWalker->u.pRewrite;
+ Parse *pParse = pWalker->pParse;
+ assert( p!=0 );
+ assert( p->pWin!=0 );
+
+ /* If this function is being called from within a scalar sub-select
+ ** that used by the SELECT statement being processed, only process
+ ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
+ ** not process aggregates or window functions at all, as they belong
+ ** to the scalar sub-select. */
+ if( p->pSubSelect ){
+ if( pExpr->op!=TK_COLUMN ){
+ return WRC_Continue;
+ }else{
+ int nSrc = p->pSrc->nSrc;
+ int i;
+ for(i=0; i<nSrc; i++){
+ if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
+ }
+ if( i==nSrc ) return WRC_Continue;
+ }
+ }
+
+ switch( pExpr->op ){
+
+ case TK_FUNCTION:
+ if( !ExprHasProperty(pExpr, EP_WinFunc) ){
+ break;
+ }else{
+ Window *pWin;
+ for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
+ if( pExpr->y.pWin==pWin ){
+ assert( pWin->pOwner==pExpr );
+ return WRC_Prune;
+ }
+ }
+ }
+ /* no break */ deliberate_fall_through
+
+ case TK_AGG_FUNCTION:
+ case TK_COLUMN: {
+ int iCol = -1;
+ if( p->pSub ){
+ int i;
+ for(i=0; i<p->pSub->nExpr; i++){
+ if( 0==sqlite3ExprCompare(0, p->pSub->a[i].pExpr, pExpr, -1) ){
+ iCol = i;
+ break;
+ }
+ }
+ }
+ if( iCol<0 ){
+ Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
+ if( pDup && pDup->op==TK_AGG_FUNCTION ) pDup->op = TK_FUNCTION;
+ p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
+ }
+ if( p->pSub ){
+ int f = pExpr->flags & EP_Collate;
+ assert( ExprHasProperty(pExpr, EP_Static)==0 );
+ ExprSetProperty(pExpr, EP_Static);
+ sqlite3ExprDelete(pParse->db, pExpr);
+ ExprClearProperty(pExpr, EP_Static);
+ memset(pExpr, 0, sizeof(Expr));
+
+ pExpr->op = TK_COLUMN;
+ pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol);
+ pExpr->iTable = p->pWin->iEphCsr;
+ pExpr->y.pTab = p->pTab;
+ pExpr->flags = f;
+ }
+ if( pParse->db->mallocFailed ) return WRC_Abort;
+ break;
+ }
+
+ default: /* no-op */
+ break;
+ }
+
+ return WRC_Continue;
+}
+static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
+ struct WindowRewrite *p = pWalker->u.pRewrite;
+ Select *pSave = p->pSubSelect;
+ if( pSave==pSelect ){
+ return WRC_Continue;
+ }else{
+ p->pSubSelect = pSelect;
+ sqlite3WalkSelect(pWalker, pSelect);
+ p->pSubSelect = pSave;
+ }
+ return WRC_Prune;
+}
+
+
+/*
+** Iterate through each expression in expression-list pEList. For each:
+**
+** * TK_COLUMN,
+** * aggregate function, or
+** * window function with a Window object that is not a member of the
+** Window list passed as the second argument (pWin).
+**
+** Append the node to output expression-list (*ppSub). And replace it
+** with a TK_COLUMN that reads the (N-1)th element of table
+** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
+** appending the new one.
+*/
+static void selectWindowRewriteEList(
+ Parse *pParse,
+ Window *pWin,
+ SrcList *pSrc,
+ ExprList *pEList, /* Rewrite expressions in this list */
+ Table *pTab,
+ ExprList **ppSub /* IN/OUT: Sub-select expression-list */
+){
+ Walker sWalker;
+ WindowRewrite sRewrite;
+
+ assert( pWin!=0 );
+ memset(&sWalker, 0, sizeof(Walker));
+ memset(&sRewrite, 0, sizeof(WindowRewrite));
+
+ sRewrite.pSub = *ppSub;
+ sRewrite.pWin = pWin;
+ sRewrite.pSrc = pSrc;
+ sRewrite.pTab = pTab;
+
+ sWalker.pParse = pParse;
+ sWalker.xExprCallback = selectWindowRewriteExprCb;
+ sWalker.xSelectCallback = selectWindowRewriteSelectCb;
+ sWalker.u.pRewrite = &sRewrite;
+
+ (void)sqlite3WalkExprList(&sWalker, pEList);
+
+ *ppSub = sRewrite.pSub;
+}
+
+/*
+** Append a copy of each expression in expression-list pAppend to
+** expression list pList. Return a pointer to the result list.
+*/
+static ExprList *exprListAppendList(
+ Parse *pParse, /* Parsing context */
+ ExprList *pList, /* List to which to append. Might be NULL */
+ ExprList *pAppend, /* List of values to append. Might be NULL */
+ int bIntToNull
+){
+ if( pAppend ){
+ int i;
+ int nInit = pList ? pList->nExpr : 0;
+ for(i=0; i<pAppend->nExpr; i++){
+ Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
+ assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );
+ if( bIntToNull && pDup ){
+ int iDummy;
+ Expr *pSub;
+ for(pSub=pDup; ExprHasProperty(pSub, EP_Skip); pSub=pSub->pLeft){
+ assert( pSub );
+ }
+ if( sqlite3ExprIsInteger(pSub, &iDummy) ){
+ pSub->op = TK_NULL;
+ pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
+ pSub->u.zToken = 0;
+ }
+ }
+ pList = sqlite3ExprListAppend(pParse, pList, pDup);
+ if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;
+ }
+ }
+ return pList;
+}
+
+/*
+** When rewriting a query, if the new subquery in the FROM clause
+** contains TK_AGG_FUNCTION nodes that refer to an outer query,
+** then we have to increase the Expr->op2 values of those nodes
+** due to the extra subquery layer that was added.
+**
+** See also the incrAggDepth() routine in resolve.c
+*/
+static int sqlite3WindowExtraAggFuncDepth(Walker *pWalker, Expr *pExpr){
+ if( pExpr->op==TK_AGG_FUNCTION
+ && pExpr->op2>=pWalker->walkerDepth
+ ){
+ pExpr->op2++;
+ }
+ return WRC_Continue;
+}
+
+/*
+** If the SELECT statement passed as the second argument does not invoke
+** any SQL window functions, this function is a no-op. Otherwise, it
+** rewrites the SELECT statement so that window function xStep functions
+** are invoked in the correct order as described under "SELECT REWRITING"
+** at the top of this file.
+*/
+SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
+ int rc = SQLITE_OK;
+ if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){
+ Vdbe *v = sqlite3GetVdbe(pParse);
+ sqlite3 *db = pParse->db;
+ Select *pSub = 0; /* The subquery */
+ SrcList *pSrc = p->pSrc;
+ Expr *pWhere = p->pWhere;
+ ExprList *pGroupBy = p->pGroupBy;
+ Expr *pHaving = p->pHaving;
+ ExprList *pSort = 0;
+
+ ExprList *pSublist = 0; /* Expression list for sub-query */
+ Window *pMWin = p->pWin; /* Main window object */
+ Window *pWin; /* Window object iterator */
+ Table *pTab;
+ Walker w;
+
+ u32 selFlags = p->selFlags;
+
+ pTab = sqlite3DbMallocZero(db, sizeof(Table));
+ if( pTab==0 ){
+ return sqlite3ErrorToParser(db, SQLITE_NOMEM);
+ }
+ sqlite3AggInfoPersistWalkerInit(&w, pParse);
+ sqlite3WalkSelect(&w, p);
+
+ p->pSrc = 0;
+ p->pWhere = 0;
+ p->pGroupBy = 0;
+ p->pHaving = 0;
+ p->selFlags &= ~SF_Aggregate;
+ p->selFlags |= SF_WinRewrite;
+
+ /* Create the ORDER BY clause for the sub-select. This is the concatenation
+ ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
+ ** redundant, remove the ORDER BY from the parent SELECT. */
+ pSort = exprListAppendList(pParse, 0, pMWin->pPartition, 1);
+ pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);
+ if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){
+ int nSave = pSort->nExpr;
+ pSort->nExpr = p->pOrderBy->nExpr;
+ if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
+ sqlite3ExprListDelete(db, p->pOrderBy);
+ p->pOrderBy = 0;
+ }
+ pSort->nExpr = nSave;
+ }
+
+ /* Assign a cursor number for the ephemeral table used to buffer rows.
+ ** The OpenEphemeral instruction is coded later, after it is known how
+ ** many columns the table will have. */
+ pMWin->iEphCsr = pParse->nTab++;
+ pParse->nTab += 3;
+
+ selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);
+ selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
+ pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
+
+ /* Append the PARTITION BY and ORDER BY expressions to the to the
+ ** sub-select expression list. They are required to figure out where
+ ** boundaries for partitions and sets of peer rows lie. */
+ pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
+ pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
+
+ /* Append the arguments passed to each window function to the
+ ** sub-select expression list. Also allocate two registers for each
+ ** window function - one for the accumulator, another for interim
+ ** results. */
+ for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
+ ExprList *pArgs = pWin->pOwner->x.pList;
+ if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){
+ selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);
+ pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
+ pWin->bExprArgs = 1;
+ }else{
+ pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
+ pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);
+ }
+ if( pWin->pFilter ){
+ Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
+ pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
+ }
+ pWin->regAccum = ++pParse->nMem;
+ pWin->regResult = ++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
+ }
+
+ /* If there is no ORDER BY or PARTITION BY clause, and the window
+ ** function accepts zero arguments, and there are no other columns
+ ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
+ ** that pSublist is still NULL here. Add a constant expression here to
+ ** keep everything legal in this case.
+ */
+ if( pSublist==0 ){
+ pSublist = sqlite3ExprListAppend(pParse, 0,
+ sqlite3Expr(db, TK_INTEGER, "0")
+ );
+ }
+
+ pSub = sqlite3SelectNew(
+ pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
+ );
+ SELECTTRACE(1,pParse,pSub,
+ ("New window-function subquery in FROM clause of (%u/%p)\n",
+ p->selId, p));
+ p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
+ if( p->pSrc ){
+ Table *pTab2;
+ p->pSrc->a[0].pSelect = pSub;
+ sqlite3SrcListAssignCursors(pParse, p->pSrc);
+ pSub->selFlags |= SF_Expanded;
+ pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);
+ pSub->selFlags |= (selFlags & SF_Aggregate);
+ if( pTab2==0 ){
+ /* Might actually be some other kind of error, but in that case
+ ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get
+ ** the correct error message regardless. */
+ rc = SQLITE_NOMEM;
+ }else{
+ memcpy(pTab, pTab2, sizeof(Table));
+ pTab->tabFlags |= TF_Ephemeral;
+ p->pSrc->a[0].pTab = pTab;
+ pTab = pTab2;
+ memset(&w, 0, sizeof(w));
+ w.xExprCallback = sqlite3WindowExtraAggFuncDepth;
+ w.xSelectCallback = sqlite3WalkerDepthIncrease;
+ w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
+ sqlite3WalkSelect(&w, pSub);
+ }
+ }else{
+ sqlite3SelectDelete(db, pSub);
+ }
+ if( db->mallocFailed ) rc = SQLITE_NOMEM;
+ sqlite3DbFree(db, pTab);
+ }
+
+ if( rc ){
+ if( pParse->nErr==0 ){
+ assert( pParse->db->mallocFailed );
+ sqlite3ErrorToParser(pParse->db, SQLITE_NOMEM);
+ }
+ }
+ return rc;
+}
+
+/*
+** Unlink the Window object from the Select to which it is attached,
+** if it is attached.
+*/
+SQLITE_PRIVATE void sqlite3WindowUnlinkFromSelect(Window *p){
+ if( p->ppThis ){
+ *p->ppThis = p->pNextWin;
+ if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis;
+ p->ppThis = 0;
+ }
+}
+
+/*
+** Free the Window object passed as the second argument.
+*/
+SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3 *db, Window *p){
+ if( p ){
+ sqlite3WindowUnlinkFromSelect(p);
+ sqlite3ExprDelete(db, p->pFilter);
+ sqlite3ExprListDelete(db, p->pPartition);
+ sqlite3ExprListDelete(db, p->pOrderBy);
+ sqlite3ExprDelete(db, p->pEnd);
+ sqlite3ExprDelete(db, p->pStart);
+ sqlite3DbFree(db, p->zName);
+ sqlite3DbFree(db, p->zBase);
+ sqlite3DbFree(db, p);
+ }
+}
+
+/*
+** Free the linked list of Window objects starting at the second argument.
+*/
+SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p){
+ while( p ){
+ Window *pNext = p->pNextWin;
+ sqlite3WindowDelete(db, p);
+ p = pNext;
+ }
+}
+
+/*
+** The argument expression is an PRECEDING or FOLLOWING offset. The
+** value should be a non-negative integer. If the value is not a
+** constant, change it to NULL. The fact that it is then a non-negative
+** integer will be caught later. But it is important not to leave
+** variable values in the expression tree.
+*/
+static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
+ if( 0==sqlite3ExprIsConstant(pExpr) ){
+ if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
+ sqlite3ExprDelete(pParse->db, pExpr);
+ pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
+ }
+ return pExpr;
+}
+
+/*
+** Allocate and return a new Window object describing a Window Definition.
+*/
+SQLITE_PRIVATE Window *sqlite3WindowAlloc(
+ Parse *pParse, /* Parsing context */
+ int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
+ int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
+ Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
+ int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
+ Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */
+ u8 eExclude /* EXCLUDE clause */
+){
+ Window *pWin = 0;
+ int bImplicitFrame = 0;
+
+ /* Parser assures the following: */
+ assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
+ assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
+ || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
+ assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
+ || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
+ assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
+ assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
+
+ if( eType==0 ){
+ bImplicitFrame = 1;
+ eType = TK_RANGE;
+ }
+
+ /* Additionally, the
+ ** starting boundary type may not occur earlier in the following list than
+ ** the ending boundary type:
+ **
+ ** UNBOUNDED PRECEDING
+ ** <expr> PRECEDING
+ ** CURRENT ROW
+ ** <expr> FOLLOWING
+ ** UNBOUNDED FOLLOWING
+ **
+ ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
+ ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
+ ** frame boundary.
+ */
+ if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
+ || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
+ ){
+ sqlite3ErrorMsg(pParse, "unsupported frame specification");
+ goto windowAllocErr;
+ }
+
+ pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
+ if( pWin==0 ) goto windowAllocErr;
+ pWin->eFrmType = eType;
+ pWin->eStart = eStart;
+ pWin->eEnd = eEnd;
+ if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
+ eExclude = TK_NO;
+ }
+ pWin->eExclude = eExclude;
+ pWin->bImplicitFrame = bImplicitFrame;
+ pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
+ pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
+ return pWin;
+
+windowAllocErr:
+ sqlite3ExprDelete(pParse->db, pEnd);
+ sqlite3ExprDelete(pParse->db, pStart);
+ return 0;
+}
+
+/*
+** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
+** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
+** equivalent nul-terminated string.
+*/
+SQLITE_PRIVATE Window *sqlite3WindowAssemble(
+ Parse *pParse,
+ Window *pWin,
+ ExprList *pPartition,
+ ExprList *pOrderBy,
+ Token *pBase
+){
+ if( pWin ){
+ pWin->pPartition = pPartition;
+ pWin->pOrderBy = pOrderBy;
+ if( pBase ){
+ pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
+ }
+ }else{
+ sqlite3ExprListDelete(pParse->db, pPartition);
+ sqlite3ExprListDelete(pParse->db, pOrderBy);
+ }
+ return pWin;
+}
+
+/*
+** Window *pWin has just been created from a WINDOW clause. Tokne pBase
+** is the base window. Earlier windows from the same WINDOW clause are
+** stored in the linked list starting at pWin->pNextWin. This function
+** either updates *pWin according to the base specification, or else
+** leaves an error in pParse.
+*/
+SQLITE_PRIVATE void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
+ if( pWin->zBase ){
+ sqlite3 *db = pParse->db;
+ Window *pExist = windowFind(pParse, pList, pWin->zBase);
+ if( pExist ){
+ const char *zErr = 0;
+ /* Check for errors */
+ if( pWin->pPartition ){
+ zErr = "PARTITION clause";
+ }else if( pExist->pOrderBy && pWin->pOrderBy ){
+ zErr = "ORDER BY clause";
+ }else if( pExist->bImplicitFrame==0 ){
+ zErr = "frame specification";
+ }
+ if( zErr ){
+ sqlite3ErrorMsg(pParse,
+ "cannot override %s of window: %s", zErr, pWin->zBase
+ );
+ }else{
+ pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
+ if( pExist->pOrderBy ){
+ assert( pWin->pOrderBy==0 );
+ pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
+ }
+ sqlite3DbFree(db, pWin->zBase);
+ pWin->zBase = 0;
+ }
+ }
+ }
+}
+
+/*
+** Attach window object pWin to expression p.
+*/
+SQLITE_PRIVATE void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
+ if( p ){
+ assert( p->op==TK_FUNCTION );
+ assert( pWin );
+ p->y.pWin = pWin;
+ ExprSetProperty(p, EP_WinFunc);
+ pWin->pOwner = p;
+ if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){
+ sqlite3ErrorMsg(pParse,
+ "DISTINCT is not supported for window functions"
+ );
+ }
+ }else{
+ sqlite3WindowDelete(pParse->db, pWin);
+ }
+}
+
+/*
+** Possibly link window pWin into the list at pSel->pWin (window functions
+** to be processed as part of SELECT statement pSel). The window is linked
+** in if either (a) there are no other windows already linked to this
+** SELECT, or (b) the windows already linked use a compatible window frame.
+*/
+SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin){
+ if( pSel!=0
+ && (0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0))
+ ){
+ pWin->pNextWin = pSel->pWin;
+ if( pSel->pWin ){
+ pSel->pWin->ppThis = &pWin->pNextWin;
+ }
+ pSel->pWin = pWin;
+ pWin->ppThis = &pSel->pWin;
+ }
+}
+
+/*
+** Return 0 if the two window objects are identical, 1 if they are
+** different, or 2 if it cannot be determined if the objects are identical
+** or not. Identical window objects can be processed in a single scan.
+*/
+SQLITE_PRIVATE int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){
+ int res;
+ if( NEVER(p1==0) || NEVER(p2==0) ) return 1;
+ if( p1->eFrmType!=p2->eFrmType ) return 1;
+ if( p1->eStart!=p2->eStart ) return 1;
+ if( p1->eEnd!=p2->eEnd ) return 1;
+ if( p1->eExclude!=p2->eExclude ) return 1;
+ if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
+ if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
+ if( (res = sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1)) ){
+ return res;
+ }
+ if( (res = sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1)) ){
+ return res;
+ }
+ if( bFilter ){
+ if( (res = sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1)) ){
+ return res;
+ }
+ }
+ return 0;
+}
+
+
+/*
+** This is called by code in select.c before it calls sqlite3WhereBegin()
+** to begin iterating through the sub-query results. It is used to allocate
+** and initialize registers and cursors used by sqlite3WindowCodeStep().
+*/
+SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse *pParse, Select *pSelect){
+ int nEphExpr = pSelect->pSrc->a[0].pSelect->pEList->nExpr;
+ Window *pMWin = pSelect->pWin;
+ Window *pWin;
+ Vdbe *v = sqlite3GetVdbe(pParse);
+
+ sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr);
+ sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
+ sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
+ sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
+
+ /* Allocate registers to use for PARTITION BY values, if any. Initialize
+ ** said registers to NULL. */
+ if( pMWin->pPartition ){
+ int nExpr = pMWin->pPartition->nExpr;
+ pMWin->regPart = pParse->nMem+1;
+ pParse->nMem += nExpr;
+ sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
+ }
+
+ pMWin->regOne = ++pParse->nMem;
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
+
+ if( pMWin->eExclude ){
+ pMWin->regStartRowid = ++pParse->nMem;
+ pMWin->regEndRowid = ++pParse->nMem;
+ pMWin->csrApp = pParse->nTab++;
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
+ sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
+ return;
+ }
+
+ for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
+ FuncDef *p = pWin->pFunc;
+ if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
+ /* The inline versions of min() and max() require a single ephemeral
+ ** table and 3 registers. The registers are used as follows:
+ **
+ ** regApp+0: slot to copy min()/max() argument to for MakeRecord
+ ** regApp+1: integer value used to ensure keys are unique
+ ** regApp+2: output of MakeRecord
+ */
+ ExprList *pList = pWin->pOwner->x.pList;
+ KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
+ pWin->csrApp = pParse->nTab++;
+ pWin->regApp = pParse->nMem+1;
+ pParse->nMem += 3;
+ if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
+ assert( pKeyInfo->aSortFlags[0]==0 );
+ pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC;
+ }
+ sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
+ sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
+ }
+ else if( p->zName==nth_valueName || p->zName==first_valueName ){
+ /* Allocate two registers at pWin->regApp. These will be used to
+ ** store the start and end index of the current frame. */
+ pWin->regApp = pParse->nMem+1;
+ pWin->csrApp = pParse->nTab++;
+ pParse->nMem += 2;
+ sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
+ }
+ else if( p->zName==leadName || p->zName==lagName ){
+ pWin->csrApp = pParse->nTab++;
+ sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
+ }
+ }
+}
+
+#define WINDOW_STARTING_INT 0
+#define WINDOW_ENDING_INT 1
+#define WINDOW_NTH_VALUE_INT 2
+#define WINDOW_STARTING_NUM 3
+#define WINDOW_ENDING_NUM 4
+
+/*
+** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
+** value of the second argument to nth_value() (eCond==2) has just been
+** evaluated and the result left in register reg. This function generates VM
+** code to check that the value is a non-negative integer and throws an
+** exception if it is not.
+*/
+static void windowCheckValue(Parse *pParse, int reg, int eCond){
+ static const char *azErr[] = {
+ "frame starting offset must be a non-negative integer",
+ "frame ending offset must be a non-negative integer",
+ "second argument to nth_value must be a positive integer",
+ "frame starting offset must be a non-negative number",
+ "frame ending offset must be a non-negative number",
+ };
+ static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
+ Vdbe *v = sqlite3GetVdbe(pParse);
+ int regZero = sqlite3GetTempReg(pParse);
+ assert( eCond>=0 && eCond<ArraySize(azErr) );
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
+ if( eCond>=WINDOW_STARTING_NUM ){
+ int regString = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
+ sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
+ sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
+ VdbeCoverage(v);
+ assert( eCond==3 || eCond==4 );
+ VdbeCoverageIf(v, eCond==3);
+ VdbeCoverageIf(v, eCond==4);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
+ VdbeCoverage(v);
+ assert( eCond==0 || eCond==1 || eCond==2 );
+ VdbeCoverageIf(v, eCond==0);
+ VdbeCoverageIf(v, eCond==1);
+ VdbeCoverageIf(v, eCond==2);
+ }
+ sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
+ VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
+ VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */
+ VdbeCoverageNeverNullIf(v, eCond==2);
+ VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
+ VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */
+ sqlite3MayAbort(pParse);
+ sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
+ sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
+ sqlite3ReleaseTempReg(pParse, regZero);
+}
+
+/*
+** Return the number of arguments passed to the window-function associated
+** with the object passed as the only argument to this function.
+*/
+static int windowArgCount(Window *pWin){
+ ExprList *pList = pWin->pOwner->x.pList;
+ return (pList ? pList->nExpr : 0);
+}
+
+typedef struct WindowCodeArg WindowCodeArg;
+typedef struct WindowCsrAndReg WindowCsrAndReg;
+
+/*
+** See comments above struct WindowCodeArg.
+*/
+struct WindowCsrAndReg {
+ int csr; /* Cursor number */
+ int reg; /* First in array of peer values */
+};
+
+/*
+** A single instance of this structure is allocated on the stack by
+** sqlite3WindowCodeStep() and a pointer to it passed to the various helper
+** routines. This is to reduce the number of arguments required by each
+** helper function.
+**
+** regArg:
+** Each window function requires an accumulator register (just as an
+** ordinary aggregate function does). This variable is set to the first
+** in an array of accumulator registers - one for each window function
+** in the WindowCodeArg.pMWin list.
+**
+** eDelete:
+** The window functions implementation sometimes caches the input rows
+** that it processes in a temporary table. If it is not zero, this
+** variable indicates when rows may be removed from the temp table (in
+** order to reduce memory requirements - it would always be safe just
+** to leave them there). Possible values for eDelete are:
+**
+** WINDOW_RETURN_ROW:
+** An input row can be discarded after it is returned to the caller.
+**
+** WINDOW_AGGINVERSE:
+** An input row can be discarded after the window functions xInverse()
+** callbacks have been invoked in it.
+**
+** WINDOW_AGGSTEP:
+** An input row can be discarded after the window functions xStep()
+** callbacks have been invoked in it.
+**
+** start,current,end
+** Consider a window-frame similar to the following:
+**
+** (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING)
+**
+** The windows functions implmentation caches the input rows in a temp
+** table, sorted by "a, b" (it actually populates the cache lazily, and
+** aggressively removes rows once they are no longer required, but that's
+** a mere detail). It keeps three cursors open on the temp table. One
+** (current) that points to the next row to return to the query engine
+** once its window function values have been calculated. Another (end)
+** points to the next row to call the xStep() method of each window function
+** on (so that it is 2 groups ahead of current). And a third (start) that
+** points to the next row to call the xInverse() method of each window
+** function on.
+**
+** Each cursor (start, current and end) consists of a VDBE cursor
+** (WindowCsrAndReg.csr) and an array of registers (starting at
+** WindowCodeArg.reg) that always contains a copy of the peer values
+** read from the corresponding cursor.
+**
+** Depending on the window-frame in question, all three cursors may not
+** be required. In this case both WindowCodeArg.csr and reg are set to
+** 0.
+*/
+struct WindowCodeArg {
+ Parse *pParse; /* Parse context */
+ Window *pMWin; /* First in list of functions being processed */
+ Vdbe *pVdbe; /* VDBE object */
+ int addrGosub; /* OP_Gosub to this address to return one row */
+ int regGosub; /* Register used with OP_Gosub(addrGosub) */
+ int regArg; /* First in array of accumulator registers */
+ int eDelete; /* See above */
+
+ WindowCsrAndReg start;
+ WindowCsrAndReg current;
+ WindowCsrAndReg end;
+};
+
+/*
+** Generate VM code to read the window frames peer values from cursor csr into
+** an array of registers starting at reg.
+*/
+static void windowReadPeerValues(
+ WindowCodeArg *p,
+ int csr,
+ int reg
+){
+ Window *pMWin = p->pMWin;
+ ExprList *pOrderBy = pMWin->pOrderBy;
+ if( pOrderBy ){
+ Vdbe *v = sqlite3GetVdbe(p->pParse);
+ ExprList *pPart = pMWin->pPartition;
+ int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
+ int i;
+ for(i=0; i<pOrderBy->nExpr; i++){
+ sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
+ }
+ }
+}
+
+/*
+** Generate VM code to invoke either xStep() (if bInverse is 0) or
+** xInverse (if bInverse is non-zero) for each window function in the
+** linked list starting at pMWin. Or, for built-in window functions
+** that do not use the standard function API, generate the required
+** inline VM code.
+**
+** If argument csr is greater than or equal to 0, then argument reg is
+** the first register in an array of registers guaranteed to be large
+** enough to hold the array of arguments for each function. In this case
+** the arguments are extracted from the current row of csr into the
+** array of registers before invoking OP_AggStep or OP_AggInverse
+**
+** Or, if csr is less than zero, then the array of registers at reg is
+** already populated with all columns from the current row of the sub-query.
+**
+** If argument regPartSize is non-zero, then it is a register containing the
+** number of rows in the current partition.
+*/
+static void windowAggStep(
+ WindowCodeArg *p,
+ Window *pMWin, /* Linked list of window functions */
+ int csr, /* Read arguments from this cursor */
+ int bInverse, /* True to invoke xInverse instead of xStep */
+ int reg /* Array of registers */
+){
+ Parse *pParse = p->pParse;
+ Vdbe *v = sqlite3GetVdbe(pParse);
+ Window *pWin;
+ for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
+ FuncDef *pFunc = pWin->pFunc;
+ int regArg;
+ int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin);
+ int i;
+
+ assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED );
+
+ /* All OVER clauses in the same window function aggregate step must
+ ** be the same. */
+ assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)!=1 );
+
+ for(i=0; i<nArg; i++){
+ if( i!=1 || pFunc->zName!=nth_valueName ){
+ sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
+ }else{
+ sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
+ }
+ }
+ regArg = reg;
+
+ if( pMWin->regStartRowid==0
+ && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
+ && (pWin->eStart!=TK_UNBOUNDED)
+ ){
+ int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
+ VdbeCoverage(v);
+ if( bInverse==0 ){
+ sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
+ sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
+ sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
+ }else{
+ sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
+ VdbeCoverageNeverTaken(v);
+ sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
+ sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
+ }
+ sqlite3VdbeJumpHere(v, addrIsNull);
+ }else if( pWin->regApp ){
+ assert( pFunc->zName==nth_valueName
+ || pFunc->zName==first_valueName
+ );
+ assert( bInverse==0 || bInverse==1 );
+ sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
+ }else if( pFunc->xSFunc!=noopStepFunc ){
+ int addrIf = 0;
+ if( pWin->pFilter ){
+ int regTmp;
+ assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr );
+ assert( pWin->bExprArgs || nArg ||pWin->pOwner->x.pList==0 );
+ regTmp = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
+ addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
+ VdbeCoverage(v);
+ sqlite3ReleaseTempReg(pParse, regTmp);
+ }
+
+ if( pWin->bExprArgs ){
+ int iStart = sqlite3VdbeCurrentAddr(v);
+ VdbeOp *pOp, *pEnd;
+
+ nArg = pWin->pOwner->x.pList->nExpr;
+ regArg = sqlite3GetTempRange(pParse, nArg);
+ sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0);
+
+ pEnd = sqlite3VdbeGetOp(v, -1);
+ for(pOp=sqlite3VdbeGetOp(v, iStart); pOp<=pEnd; pOp++){
+ if( pOp->opcode==OP_Column && pOp->p1==pWin->iEphCsr ){
+ pOp->p1 = csr;
+ }
+ }
+ }
+ if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
+ CollSeq *pColl;
+ assert( nArg>0 );
+ pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
+ sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
+ }
+ sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
+ bInverse, regArg, pWin->regAccum);
+ sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
+ sqlite3VdbeChangeP5(v, (u8)nArg);
+ if( pWin->bExprArgs ){
+ sqlite3ReleaseTempRange(pParse, regArg, nArg);
+ }
+ if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
+ }
+ }
+}
+
+/*
+** Values that may be passed as the second argument to windowCodeOp().
+*/
+#define WINDOW_RETURN_ROW 1
+#define WINDOW_AGGINVERSE 2
+#define WINDOW_AGGSTEP 3
+
+/*
+** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
+** (bFin==1) for each window function in the linked list starting at
+** pMWin. Or, for built-in window-functions that do not use the standard
+** API, generate the equivalent VM code.
+*/
+static void windowAggFinal(WindowCodeArg *p, int bFin){
+ Parse *pParse = p->pParse;
+ Window *pMWin = p->pMWin;
+ Vdbe *v = sqlite3GetVdbe(pParse);
+ Window *pWin;
+
+ for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
+ if( pMWin->regStartRowid==0
+ && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
+ && (pWin->eStart!=TK_UNBOUNDED)
+ ){
+ sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
+ sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
+ VdbeCoverage(v);
+ sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
+ sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
+ }else if( pWin->regApp ){
+ assert( pMWin->regStartRowid==0 );
+ }else{
+ int nArg = windowArgCount(pWin);
+ if( bFin ){
+ sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
+ sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
+ sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
+ sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
+ }else{
+ sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
+ sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
+ }
+ }
+ }
+}
+
+/*
+** Generate code to calculate the current values of all window functions in the
+** p->pMWin list by doing a full scan of the current window frame. Store the
+** results in the Window.regResult registers, ready to return the upper
+** layer.
+*/
+static void windowFullScan(WindowCodeArg *p){
+ Window *pWin;
+ Parse *pParse = p->pParse;
+ Window *pMWin = p->pMWin;
+ Vdbe *v = p->pVdbe;
+
+ int regCRowid = 0; /* Current rowid value */
+ int regCPeer = 0; /* Current peer values */
+ int regRowid = 0; /* AggStep rowid value */
+ int regPeer = 0; /* AggStep peer values */
+
+ int nPeer;
+ int lblNext;
+ int lblBrk;
+ int addrNext;
+ int csr;
+
+ VdbeModuleComment((v, "windowFullScan begin"));
+
+ assert( pMWin!=0 );
+ csr = pMWin->csrApp;
+ nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
+
+ lblNext = sqlite3VdbeMakeLabel(pParse);
+ lblBrk = sqlite3VdbeMakeLabel(pParse);
+
+ regCRowid = sqlite3GetTempReg(pParse);
+ regRowid = sqlite3GetTempReg(pParse);
+ if( nPeer ){
+ regCPeer = sqlite3GetTempRange(pParse, nPeer);
+ regPeer = sqlite3GetTempRange(pParse, nPeer);
+ }
+
+ sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
+ windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
+
+ for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
+ sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
+ }
+
+ sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
+ VdbeCoverage(v);
+ addrNext = sqlite3VdbeCurrentAddr(v);
+ sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
+ sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
+ VdbeCoverageNeverNull(v);
+
+ if( pMWin->eExclude==TK_CURRENT ){
+ sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
+ VdbeCoverageNeverNull(v);
+ }else if( pMWin->eExclude!=TK_NO ){
+ int addr;
+ int addrEq = 0;
+ KeyInfo *pKeyInfo = 0;
+
+ if( pMWin->pOrderBy ){
+ pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
+ }
+ if( pMWin->eExclude==TK_TIES ){
+ addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
+ VdbeCoverageNeverNull(v);
+ }
+ if( pKeyInfo ){
+ windowReadPeerValues(p, csr, regPeer);
+ sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
+ sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
+ addr = sqlite3VdbeCurrentAddr(v)+1;
+ sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
+ VdbeCoverageEqNe(v);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
+ }
+ if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
+ }
+
+ windowAggStep(p, pMWin, csr, 0, p->regArg);
+
+ sqlite3VdbeResolveLabel(v, lblNext);
+ sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
+ VdbeCoverage(v);
+ sqlite3VdbeJumpHere(v, addrNext-1);
+ sqlite3VdbeJumpHere(v, addrNext+1);
+ sqlite3ReleaseTempReg(pParse, regRowid);
+ sqlite3ReleaseTempReg(pParse, regCRowid);
+ if( nPeer ){
+ sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
+ sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
+ }
+
+ windowAggFinal(p, 1);
+ VdbeModuleComment((v, "windowFullScan end"));
+}
+
+/*
+** Invoke the sub-routine at regGosub (generated by code in select.c) to
+** return the current row of Window.iEphCsr. If all window functions are
+** aggregate window functions that use the standard API, a single
+** OP_Gosub instruction is all that this routine generates. Extra VM code
+** for per-row processing is only generated for the following built-in window
+** functions:
+**
+** nth_value()
+** first_value()
+** lag()
+** lead()
+*/
+static void windowReturnOneRow(WindowCodeArg *p){
+ Window *pMWin = p->pMWin;
+ Vdbe *v = p->pVdbe;
+
+ if( pMWin->regStartRowid ){
+ windowFullScan(p);
+ }else{
+ Parse *pParse = p->pParse;
+ Window *pWin;
+
+ for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
+ FuncDef *pFunc = pWin->pFunc;
+ if( pFunc->zName==nth_valueName
+ || pFunc->zName==first_valueName
+ ){
+ int csr = pWin->csrApp;
+ int lbl = sqlite3VdbeMakeLabel(pParse);
+ int tmpReg = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
+
+ if( pFunc->zName==nth_valueName ){
+ sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
+ windowCheckValue(pParse, tmpReg, 2);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
+ }
+ sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
+ sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
+ VdbeCoverageNeverNull(v);
+ sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
+ VdbeCoverageNeverTaken(v);
+ sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
+ sqlite3VdbeResolveLabel(v, lbl);
+ sqlite3ReleaseTempReg(pParse, tmpReg);
+ }
+ else if( pFunc->zName==leadName || pFunc->zName==lagName ){
+ int nArg = pWin->pOwner->x.pList->nExpr;
+ int csr = pWin->csrApp;
+ int lbl = sqlite3VdbeMakeLabel(pParse);
+ int tmpReg = sqlite3GetTempReg(pParse);
+ int iEph = pMWin->iEphCsr;
+
+ if( nArg<3 ){
+ sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
+ }else{
+ sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
+ }
+ sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
+ if( nArg<2 ){
+ int val = (pFunc->zName==leadName ? 1 : -1);
+ sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
+ }else{
+ int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
+ int tmpReg2 = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
+ sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
+ sqlite3ReleaseTempReg(pParse, tmpReg2);
+ }
+
+ sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
+ VdbeCoverage(v);
+ sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
+ sqlite3VdbeResolveLabel(v, lbl);
+ sqlite3ReleaseTempReg(pParse, tmpReg);
+ }
+ }
+ }
+ sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
+}
+
+/*
+** Generate code to set the accumulator register for each window function
+** in the linked list passed as the second argument to NULL. And perform
+** any equivalent initialization required by any built-in window functions
+** in the list.
+*/
+static int windowInitAccum(Parse *pParse, Window *pMWin){
+ Vdbe *v = sqlite3GetVdbe(pParse);
+ int regArg;
+ int nArg = 0;
+ Window *pWin;
+ for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
+ FuncDef *pFunc = pWin->pFunc;
+ assert( pWin->regAccum );
+ sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
+ nArg = MAX(nArg, windowArgCount(pWin));
+ if( pMWin->regStartRowid==0 ){
+ if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
+ }
+
+ if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
+ assert( pWin->eStart!=TK_UNBOUNDED );
+ sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
+ }
+ }
+ }
+ regArg = pParse->nMem+1;
+ pParse->nMem += nArg;
+ return regArg;
+}
+
+/*
+** Return true if the current frame should be cached in the ephemeral table,
+** even if there are no xInverse() calls required.
+*/
+static int windowCacheFrame(Window *pMWin){
+ Window *pWin;
+ if( pMWin->regStartRowid ) return 1;
+ for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
+ FuncDef *pFunc = pWin->pFunc;
+ if( (pFunc->zName==nth_valueName)
+ || (pFunc->zName==first_valueName)
+ || (pFunc->zName==leadName)
+ || (pFunc->zName==lagName)
+ ){
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/*
+** regOld and regNew are each the first register in an array of size
+** pOrderBy->nExpr. This function generates code to compare the two
+** arrays of registers using the collation sequences and other comparison
+** parameters specified by pOrderBy.
+**
+** If the two arrays are not equal, the contents of regNew is copied to
+** regOld and control falls through. Otherwise, if the contents of the arrays
+** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
+*/
+static void windowIfNewPeer(
+ Parse *pParse,
+ ExprList *pOrderBy,
+ int regNew, /* First in array of new values */
+ int regOld, /* First in array of old values */
+ int addr /* Jump here */
+){
+ Vdbe *v = sqlite3GetVdbe(pParse);
+ if( pOrderBy ){
+ int nVal = pOrderBy->nExpr;
+ KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
+ sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
+ sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
+ sqlite3VdbeAddOp3(v, OP_Jump,
+ sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
+ );
+ VdbeCoverageEqNe(v);
+ sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
+ }
+}
+
+/*
+** This function is called as part of generating VM programs for RANGE
+** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
+** the ORDER BY term in the window, and that argument op is OP_Ge, it generates
+** code equivalent to:
+**
+** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
+**
+** The value of parameter op may also be OP_Gt or OP_Le. In these cases the
+** operator in the above pseudo-code is replaced with ">" or "<=", respectively.
+**
+** If the sort-order for the ORDER BY term in the window is DESC, then the
+** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is
+** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
+** ">" becomes "<", and so on. So, with DESC sort order, if the argument op
+** is OP_Ge, the generated code is equivalent to:
+**
+** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
+**
+** A special type of arithmetic is used such that if csr1.peerVal is not
+** a numeric type (real or integer), then the result of the addition addition
+** or subtraction is a a copy of csr1.peerVal.
+*/
+static void windowCodeRangeTest(
+ WindowCodeArg *p,
+ int op, /* OP_Ge, OP_Gt, or OP_Le */
+ int csr1, /* Cursor number for cursor 1 */
+ int regVal, /* Register containing non-negative number */
+ int csr2, /* Cursor number for cursor 2 */
+ int lbl /* Jump destination if condition is true */
+){
+ Parse *pParse = p->pParse;
+ Vdbe *v = sqlite3GetVdbe(pParse);
+ ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */
+ int reg1 = sqlite3GetTempReg(pParse); /* Reg. for csr1.peerVal+regVal */
+ int reg2 = sqlite3GetTempReg(pParse); /* Reg. for csr2.peerVal */
+ int regString = ++pParse->nMem; /* Reg. for constant value '' */
+ int arith = OP_Add; /* OP_Add or OP_Subtract */
+ int addrGe; /* Jump destination */
+
+ assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
+ assert( pOrderBy && pOrderBy->nExpr==1 );
+ if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_DESC ){
+ switch( op ){
+ case OP_Ge: op = OP_Le; break;
+ case OP_Gt: op = OP_Lt; break;
+ default: assert( op==OP_Le ); op = OP_Ge; break;
+ }
+ arith = OP_Subtract;
+ }
+
+ /* Read the peer-value from each cursor into a register */
+ windowReadPeerValues(p, csr1, reg1);
+ windowReadPeerValues(p, csr2, reg2);
+
+ VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl",
+ reg1, (arith==OP_Add ? "+" : "-"), regVal,
+ ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2
+ ));
+
+ /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
+ ** This block adds (or subtracts for DESC) the numeric value in regVal
+ ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
+ ** then leave reg1 as it is. In pseudo-code, this is implemented as:
+ **
+ ** if( reg1>='' ) goto addrGe;
+ ** reg1 = reg1 +/- regVal
+ ** addrGe:
+ **
+ ** Since all strings and blobs are greater-than-or-equal-to an empty string,
+ ** the add/subtract is skipped for these, as required. If reg1 is a NULL,
+ ** then the arithmetic is performed, but since adding or subtracting from
+ ** NULL is always NULL anyway, this case is handled as required too. */
+ sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
+ addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
+ VdbeCoverage(v);
+ sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
+ sqlite3VdbeJumpHere(v, addrGe);
+
+ /* If the BIGNULL flag is set for the ORDER BY, then it is required to
+ ** consider NULL values to be larger than all other values, instead of
+ ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
+ ** (and adding that capability causes a performance regression), so
+ ** instead if the BIGNULL flag is set then cases where either reg1 or
+ ** reg2 are NULL are handled separately in the following block. The code
+ ** generated is equivalent to:
+ **
+ ** if( reg1 IS NULL ){
+ ** if( op==OP_Ge ) goto lbl;
+ ** if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl;
+ ** if( op==OP_Le && reg2 IS NULL ) goto lbl;
+ ** }else if( reg2 IS NULL ){
+ ** if( op==OP_Le ) goto lbl;
+ ** }
+ **
+ ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is
+ ** not taken, control jumps over the comparison operator coded below this
+ ** block. */
+ if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_BIGNULL ){
+ /* This block runs if reg1 contains a NULL. */
+ int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v);
+ switch( op ){
+ case OP_Ge:
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl);
+ break;
+ case OP_Gt:
+ sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl);
+ VdbeCoverage(v);
+ break;
+ case OP_Le:
+ sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl);
+ VdbeCoverage(v);
+ break;
+ default: assert( op==OP_Lt ); /* no-op */ break;
+ }
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
+
+ /* This block runs if reg1 is not NULL, but reg2 is. */
+ sqlite3VdbeJumpHere(v, addr);
+ sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); VdbeCoverage(v);
+ if( op==OP_Gt || op==OP_Ge ){
+ sqlite3VdbeChangeP2(v, -1, sqlite3VdbeCurrentAddr(v)+1);
+ }
+ }
+
+ /* Compare registers reg2 and reg1, taking the jump if required. Note that
+ ** control skips over this test if the BIGNULL flag is set and either
+ ** reg1 or reg2 contain a NULL value. */
+ sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
+ sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
+
+ assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
+ testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
+ testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
+ testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
+ testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
+ sqlite3ReleaseTempReg(pParse, reg1);
+ sqlite3ReleaseTempReg(pParse, reg2);
+
+ VdbeModuleComment((v, "CodeRangeTest: end"));
+}
+
+/*
+** Helper function for sqlite3WindowCodeStep(). Each call to this function
+** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
+** operation. Refer to the header comment for sqlite3WindowCodeStep() for
+** details.
+*/
+static int windowCodeOp(
+ WindowCodeArg *p, /* Context object */
+ int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
+ int regCountdown, /* Register for OP_IfPos countdown */
+ int jumpOnEof /* Jump here if stepped cursor reaches EOF */
+){
+ int csr, reg;
+ Parse *pParse = p->pParse;
+ Window *pMWin = p->pMWin;
+ int ret = 0;
+ Vdbe *v = p->pVdbe;
+ int addrContinue = 0;
+ int bPeer = (pMWin->eFrmType!=TK_ROWS);
+
+ int lblDone = sqlite3VdbeMakeLabel(pParse);
+ int addrNextRange = 0;
+
+ /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
+ ** starts with UNBOUNDED PRECEDING. */
+ if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
+ assert( regCountdown==0 && jumpOnEof==0 );
+ return 0;
+ }
+
+ if( regCountdown>0 ){
+ if( pMWin->eFrmType==TK_RANGE ){
+ addrNextRange = sqlite3VdbeCurrentAddr(v);
+ assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
+ if( op==WINDOW_AGGINVERSE ){
+ if( pMWin->eStart==TK_FOLLOWING ){
+ windowCodeRangeTest(
+ p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
+ );
+ }else{
+ windowCodeRangeTest(
+ p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
+ );
+ }
+ }else{
+ windowCodeRangeTest(
+ p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
+ );
+ }
+ }else{
+ sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1);
+ VdbeCoverage(v);
+ }
+ }
+
+ if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
+ windowAggFinal(p, 0);
+ }
+ addrContinue = sqlite3VdbeCurrentAddr(v);
+
+ /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or
+ ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the
+ ** start cursor does not advance past the end cursor within the
+ ** temporary table. It otherwise might, if (a>b). */
+ if( pMWin->eStart==pMWin->eEnd && regCountdown
+ && pMWin->eFrmType==TK_RANGE && op==WINDOW_AGGINVERSE
+ ){
+ int regRowid1 = sqlite3GetTempReg(pParse);
+ int regRowid2 = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1);
+ sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2);
+ sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1);
+ VdbeCoverage(v);
+ sqlite3ReleaseTempReg(pParse, regRowid1);
+ sqlite3ReleaseTempReg(pParse, regRowid2);
+ assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING );
+ }
+
+ switch( op ){
+ case WINDOW_RETURN_ROW:
+ csr = p->current.csr;
+ reg = p->current.reg;
+ windowReturnOneRow(p);
+ break;
+
+ case WINDOW_AGGINVERSE:
+ csr = p->start.csr;
+ reg = p->start.reg;
+ if( pMWin->regStartRowid ){
+ assert( pMWin->regEndRowid );
+ sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
+ }else{
+ windowAggStep(p, pMWin, csr, 1, p->regArg);
+ }
+ break;
+
+ default:
+ assert( op==WINDOW_AGGSTEP );
+ csr = p->end.csr;
+ reg = p->end.reg;
+ if( pMWin->regStartRowid ){
+ assert( pMWin->regEndRowid );
+ sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
+ }else{
+ windowAggStep(p, pMWin, csr, 0, p->regArg);
+ }
+ break;
+ }
+
+ if( op==p->eDelete ){
+ sqlite3VdbeAddOp1(v, OP_Delete, csr);
+ sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
+ }
+
+ if( jumpOnEof ){
+ sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
+ VdbeCoverage(v);
+ ret = sqlite3VdbeAddOp0(v, OP_Goto);
+ }else{
+ sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
+ VdbeCoverage(v);
+ if( bPeer ){
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone);
+ }
+ }
+
+ if( bPeer ){
+ int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
+ int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
+ windowReadPeerValues(p, csr, regTmp);
+ windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
+ sqlite3ReleaseTempRange(pParse, regTmp, nReg);
+ }
+
+ if( addrNextRange ){
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
+ }
+ sqlite3VdbeResolveLabel(v, lblDone);
+ return ret;
+}
+
+
+/*
+** Allocate and return a duplicate of the Window object indicated by the
+** third argument. Set the Window.pOwner field of the new object to
+** pOwner.
+*/
+SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
+ Window *pNew = 0;
+ if( ALWAYS(p) ){
+ pNew = sqlite3DbMallocZero(db, sizeof(Window));
+ if( pNew ){
+ pNew->zName = sqlite3DbStrDup(db, p->zName);
+ pNew->zBase = sqlite3DbStrDup(db, p->zBase);
+ pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
+ pNew->pFunc = p->pFunc;
+ pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
+ pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
+ pNew->eFrmType = p->eFrmType;
+ pNew->eEnd = p->eEnd;
+ pNew->eStart = p->eStart;
+ pNew->eExclude = p->eExclude;
+ pNew->regResult = p->regResult;
+ pNew->regAccum = p->regAccum;
+ pNew->iArgCol = p->iArgCol;
+ pNew->iEphCsr = p->iEphCsr;
+ pNew->bExprArgs = p->bExprArgs;
+ pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
+ pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
+ pNew->pOwner = pOwner;
+ pNew->bImplicitFrame = p->bImplicitFrame;
+ }
+ }
+ return pNew;
+}
+
+/*
+** Return a copy of the linked list of Window objects passed as the
+** second argument.
+*/
+SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
+ Window *pWin;
+ Window *pRet = 0;
+ Window **pp = &pRet;
+
+ for(pWin=p; pWin; pWin=pWin->pNextWin){
+ *pp = sqlite3WindowDup(db, 0, pWin);
+ if( *pp==0 ) break;
+ pp = &((*pp)->pNextWin);
+ }
+
+ return pRet;
+}
+
+/*
+** Return true if it can be determined at compile time that expression
+** pExpr evaluates to a value that, when cast to an integer, is greater
+** than zero. False otherwise.
+**
+** If an OOM error occurs, this function sets the Parse.db.mallocFailed
+** flag and returns zero.
+*/
+static int windowExprGtZero(Parse *pParse, Expr *pExpr){
+ int ret = 0;
+ sqlite3 *db = pParse->db;
+ sqlite3_value *pVal = 0;
+ sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
+ if( pVal && sqlite3_value_int(pVal)>0 ){
+ ret = 1;
+ }
+ sqlite3ValueFree(pVal);
+ return ret;
+}
+
+/*
+** sqlite3WhereBegin() has already been called for the SELECT statement
+** passed as the second argument when this function is invoked. It generates
+** code to populate the Window.regResult register for each window function
+** and invoke the sub-routine at instruction addrGosub once for each row.
+** sqlite3WhereEnd() is always called before returning.
+**
+** This function handles several different types of window frames, which
+** require slightly different processing. The following pseudo code is
+** used to implement window frames of the form:
+**
+** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
+**
+** Other window frame types use variants of the following:
+**
+** ... loop started by sqlite3WhereBegin() ...
+** if( new partition ){
+** Gosub flush
+** }
+** Insert new row into eph table.
+**
+** if( first row of partition ){
+** // Rewind three cursors, all open on the eph table.
+** Rewind(csrEnd);
+** Rewind(csrStart);
+** Rewind(csrCurrent);
+**
+** regEnd = <expr2> // FOLLOWING expression
+** regStart = <expr1> // PRECEDING expression
+** }else{
+** // First time this branch is taken, the eph table contains two
+** // rows. The first row in the partition, which all three cursors
+** // currently point to, and the following row.
+** AGGSTEP
+** if( (regEnd--)<=0 ){
+** RETURN_ROW
+** if( (regStart--)<=0 ){
+** AGGINVERSE
+** }
+** }
+** }
+** }
+** flush:
+** AGGSTEP
+** while( 1 ){
+** RETURN ROW
+** if( csrCurrent is EOF ) break;
+** if( (regStart--)<=0 ){
+** AggInverse(csrStart)
+** Next(csrStart)
+** }
+** }
+**
+** The pseudo-code above uses the following shorthand:
+**
+** AGGSTEP: invoke the aggregate xStep() function for each window function
+** with arguments read from the current row of cursor csrEnd, then
+** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
+**
+** RETURN_ROW: return a row to the caller based on the contents of the
+** current row of csrCurrent and the current state of all
+** aggregates. Then step cursor csrCurrent forward one row.
+**
+** AGGINVERSE: invoke the aggregate xInverse() function for each window
+** functions with arguments read from the current row of cursor
+** csrStart. Then step csrStart forward one row.
+**
+** There are two other ROWS window frames that are handled significantly
+** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
+** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
+** cases because they change the order in which the three cursors (csrStart,
+** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
+** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
+** three.
+**
+** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
+**
+** ... loop started by sqlite3WhereBegin() ...
+** if( new partition ){
+** Gosub flush
+** }
+** Insert new row into eph table.
+** if( first row of partition ){
+** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
+** regEnd = <expr2>
+** regStart = <expr1>
+** }else{
+** if( (regEnd--)<=0 ){
+** AGGSTEP
+** }
+** RETURN_ROW
+** if( (regStart--)<=0 ){
+** AGGINVERSE
+** }
+** }
+** }
+** flush:
+** if( (regEnd--)<=0 ){
+** AGGSTEP
+** }
+** RETURN_ROW
+**
+**
+** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
+**
+** ... loop started by sqlite3WhereBegin() ...
+** if( new partition ){
+** Gosub flush
+** }
+** Insert new row into eph table.
+** if( first row of partition ){
+** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
+** regEnd = <expr2>
+** regStart = regEnd - <expr1>
+** }else{
+** AGGSTEP
+** if( (regEnd--)<=0 ){
+** RETURN_ROW
+** }
+** if( (regStart--)<=0 ){
+** AGGINVERSE
+** }
+** }
+** }
+** flush:
+** AGGSTEP
+** while( 1 ){
+** if( (regEnd--)<=0 ){
+** RETURN_ROW
+** if( eof ) break;
+** }
+** if( (regStart--)<=0 ){
+** AGGINVERSE
+** if( eof ) break
+** }
+** }
+** while( !eof csrCurrent ){
+** RETURN_ROW
+** }
+**
+** For the most part, the patterns above are adapted to support UNBOUNDED by
+** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
+** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
+** This is optimized of course - branches that will never be taken and
+** conditions that are always true are omitted from the VM code. The only
+** exceptional case is:
+**
+** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
+**
+** ... loop started by sqlite3WhereBegin() ...
+** if( new partition ){
+** Gosub flush
+** }
+** Insert new row into eph table.
+** if( first row of partition ){
+** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
+** regStart = <expr1>
+** }else{
+** AGGSTEP
+** }
+** }
+** flush:
+** AGGSTEP
+** while( 1 ){
+** if( (regStart--)<=0 ){
+** AGGINVERSE
+** if( eof ) break
+** }
+** RETURN_ROW
+** }
+** while( !eof csrCurrent ){
+** RETURN_ROW
+** }
+**
+** Also requiring special handling are the cases:
+**
+** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
+** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
+**
+** when (expr1 < expr2). This is detected at runtime, not by this function.
+** To handle this case, the pseudo-code programs depicted above are modified
+** slightly to be:
+**
+** ... loop started by sqlite3WhereBegin() ...
+** if( new partition ){
+** Gosub flush
+** }
+** Insert new row into eph table.
+** if( first row of partition ){
+** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
+** regEnd = <expr2>
+** regStart = <expr1>
+** if( regEnd < regStart ){
+** RETURN_ROW
+** delete eph table contents
+** continue
+** }
+** ...
+**
+** The new "continue" statement in the above jumps to the next iteration
+** of the outer loop - the one started by sqlite3WhereBegin().
+**
+** The various GROUPS cases are implemented using the same patterns as
+** ROWS. The VM code is modified slightly so that:
+**
+** 1. The else branch in the main loop is only taken if the row just
+** added to the ephemeral table is the start of a new group. In
+** other words, it becomes:
+**
+** ... loop started by sqlite3WhereBegin() ...
+** if( new partition ){
+** Gosub flush
+** }
+** Insert new row into eph table.
+** if( first row of partition ){
+** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
+** regEnd = <expr2>
+** regStart = <expr1>
+** }else if( new group ){
+** ...
+** }
+** }
+**
+** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
+** AGGINVERSE step processes the current row of the relevant cursor and
+** all subsequent rows belonging to the same group.
+**
+** RANGE window frames are a little different again. As for GROUPS, the
+** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
+** deal in groups instead of rows. As for ROWS and GROUPS, there are three
+** basic cases:
+**
+** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
+**
+** ... loop started by sqlite3WhereBegin() ...
+** if( new partition ){
+** Gosub flush
+** }
+** Insert new row into eph table.
+** if( first row of partition ){
+** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
+** regEnd = <expr2>
+** regStart = <expr1>
+** }else{
+** AGGSTEP
+** while( (csrCurrent.key + regEnd) < csrEnd.key ){
+** RETURN_ROW
+** while( csrStart.key + regStart) < csrCurrent.key ){
+** AGGINVERSE
+** }
+** }
+** }
+** }
+** flush:
+** AGGSTEP
+** while( 1 ){
+** RETURN ROW
+** if( csrCurrent is EOF ) break;
+** while( csrStart.key + regStart) < csrCurrent.key ){
+** AGGINVERSE
+** }
+** }
+** }
+**
+** In the above notation, "csr.key" means the current value of the ORDER BY
+** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
+** or <expr PRECEDING) read from cursor csr.
+**
+** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
+**
+** ... loop started by sqlite3WhereBegin() ...
+** if( new partition ){
+** Gosub flush
+** }
+** Insert new row into eph table.
+** if( first row of partition ){
+** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
+** regEnd = <expr2>
+** regStart = <expr1>
+** }else{
+** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
+** AGGSTEP
+** }
+** while( (csrStart.key + regStart) < csrCurrent.key ){
+** AGGINVERSE
+** }
+** RETURN_ROW
+** }
+** }
+** flush:
+** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
+** AGGSTEP
+** }
+** while( (csrStart.key + regStart) < csrCurrent.key ){
+** AGGINVERSE
+** }
+** RETURN_ROW
+**
+** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
+**
+** ... loop started by sqlite3WhereBegin() ...
+** if( new partition ){
+** Gosub flush
+** }
+** Insert new row into eph table.
+** if( first row of partition ){
+** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
+** regEnd = <expr2>
+** regStart = <expr1>
+** }else{
+** AGGSTEP
+** while( (csrCurrent.key + regEnd) < csrEnd.key ){
+** while( (csrCurrent.key + regStart) > csrStart.key ){
+** AGGINVERSE
+** }
+** RETURN_ROW
+** }
+** }
+** }
+** flush:
+** AGGSTEP
+** while( 1 ){
+** while( (csrCurrent.key + regStart) > csrStart.key ){
+** AGGINVERSE
+** if( eof ) break "while( 1 )" loop.
+** }
+** RETURN_ROW
+** }
+** while( !eof csrCurrent ){
+** RETURN_ROW
+** }
+**
+** The text above leaves out many details. Refer to the code and comments
+** below for a more complete picture.
+*/
+SQLITE_PRIVATE void sqlite3WindowCodeStep(
+ Parse *pParse, /* Parse context */
+ Select *p, /* Rewritten SELECT statement */
+ WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
+ int regGosub, /* Register for OP_Gosub */
+ int addrGosub /* OP_Gosub here to return each row */
+){
+ Window *pMWin = p->pWin;
+ ExprList *pOrderBy = pMWin->pOrderBy;
+ Vdbe *v = sqlite3GetVdbe(pParse);
+ int csrWrite; /* Cursor used to write to eph. table */
+ int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */
+ int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */
+ int iInput; /* To iterate through sub cols */
+ int addrNe; /* Address of OP_Ne */
+ int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */
+ int addrInteger = 0; /* Address of OP_Integer */
+ int addrEmpty; /* Address of OP_Rewind in flush: */
+ int regNew; /* Array of registers holding new input row */
+ int regRecord; /* regNew array in record form */
+ int regRowid; /* Rowid for regRecord in eph table */
+ int regNewPeer = 0; /* Peer values for new row (part of regNew) */
+ int regPeer = 0; /* Peer values for current row */
+ int regFlushPart = 0; /* Register for "Gosub flush_partition" */
+ WindowCodeArg s; /* Context object for sub-routines */
+ int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */
+ int regStart = 0; /* Value of <expr> PRECEDING */
+ int regEnd = 0; /* Value of <expr> FOLLOWING */
+
+ assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
+ || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
+ );
+ assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
+ || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
+ );
+ assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
+ || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
+ || pMWin->eExclude==TK_NO
+ );
+
+ lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
+
+ /* Fill in the context object */
+ memset(&s, 0, sizeof(WindowCodeArg));
+ s.pParse = pParse;
+ s.pMWin = pMWin;
+ s.pVdbe = v;
+ s.regGosub = regGosub;
+ s.addrGosub = addrGosub;
+ s.current.csr = pMWin->iEphCsr;
+ csrWrite = s.current.csr+1;
+ s.start.csr = s.current.csr+2;
+ s.end.csr = s.current.csr+3;
+
+ /* Figure out when rows may be deleted from the ephemeral table. There
+ ** are four options - they may never be deleted (eDelete==0), they may
+ ** be deleted as soon as they are no longer part of the window frame
+ ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
+ ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
+ ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
+ switch( pMWin->eStart ){
+ case TK_FOLLOWING:
+ if( pMWin->eFrmType!=TK_RANGE
+ && windowExprGtZero(pParse, pMWin->pStart)
+ ){
+ s.eDelete = WINDOW_RETURN_ROW;
+ }
+ break;
+ case TK_UNBOUNDED:
+ if( windowCacheFrame(pMWin)==0 ){
+ if( pMWin->eEnd==TK_PRECEDING ){
+ if( pMWin->eFrmType!=TK_RANGE
+ && windowExprGtZero(pParse, pMWin->pEnd)
+ ){
+ s.eDelete = WINDOW_AGGSTEP;
+ }
+ }else{
+ s.eDelete = WINDOW_RETURN_ROW;
+ }
+ }
+ break;
+ default:
+ s.eDelete = WINDOW_AGGINVERSE;
+ break;
+ }
+
+ /* Allocate registers for the array of values from the sub-query, the
+ ** samve values in record form, and the rowid used to insert said record
+ ** into the ephemeral table. */
+ regNew = pParse->nMem+1;
+ pParse->nMem += nInput;
+ regRecord = ++pParse->nMem;
+ regRowid = ++pParse->nMem;
+
+ /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
+ ** clause, allocate registers to store the results of evaluating each
+ ** <expr>. */
+ if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
+ regStart = ++pParse->nMem;
+ }
+ if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
+ regEnd = ++pParse->nMem;
+ }
+
+ /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
+ ** registers to store copies of the ORDER BY expressions (peer values)
+ ** for the main loop, and for each cursor (start, current and end). */
+ if( pMWin->eFrmType!=TK_ROWS ){
+ int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
+ regNewPeer = regNew + pMWin->nBufferCol;
+ if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
+ regPeer = pParse->nMem+1; pParse->nMem += nPeer;
+ s.start.reg = pParse->nMem+1; pParse->nMem += nPeer;
+ s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
+ s.end.reg = pParse->nMem+1; pParse->nMem += nPeer;
+ }
+
+ /* Load the column values for the row returned by the sub-select
+ ** into an array of registers starting at regNew. Assemble them into
+ ** a record in register regRecord. */
+ for(iInput=0; iInput<nInput; iInput++){
+ sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
+ }
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
+
+ /* An input row has just been read into an array of registers starting
+ ** at regNew. If the window has a PARTITION clause, this block generates
+ ** VM code to check if the input row is the start of a new partition.
+ ** If so, it does an OP_Gosub to an address to be filled in later. The
+ ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
+ if( pMWin->pPartition ){
+ int addr;
+ ExprList *pPart = pMWin->pPartition;
+ int nPart = pPart->nExpr;
+ int regNewPart = regNew + pMWin->nBufferCol;
+ KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
+
+ regFlushPart = ++pParse->nMem;
+ addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
+ sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
+ sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
+ VdbeCoverageEqNe(v);
+ addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
+ VdbeComment((v, "call flush_partition"));
+ sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
+ }
+
+ /* Insert the new row into the ephemeral table */
+ sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);
+ sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);
+ addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid);
+ VdbeCoverageNeverNull(v);
+
+ /* This block is run for the first row of each partition */
+ s.regArg = windowInitAccum(pParse, pMWin);
+
+ if( regStart ){
+ sqlite3ExprCode(pParse, pMWin->pStart, regStart);
+ windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0));
+ }
+ if( regEnd ){
+ sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
+ windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0));
+ }
+
+ if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){
+ int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
+ int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
+ VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
+ VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */
+ windowAggFinal(&s, 0);
+ sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
+ VdbeCoverageNeverTaken(v);
+ windowReturnOneRow(&s);
+ sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
+ sqlite3VdbeJumpHere(v, addrGe);
+ }
+ if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
+ assert( pMWin->eEnd==TK_FOLLOWING );
+ sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
+ }
+
+ if( pMWin->eStart!=TK_UNBOUNDED ){
+ sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
+ VdbeCoverageNeverTaken(v);
+ }
+ sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
+ VdbeCoverageNeverTaken(v);
+ sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
+ VdbeCoverageNeverTaken(v);
+ if( regPeer && pOrderBy ){
+ sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
+ sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
+ sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
+ sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
+ }
+
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
+
+ sqlite3VdbeJumpHere(v, addrNe);
+
+ /* Beginning of the block executed for the second and subsequent rows. */
+ if( regPeer ){
+ windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
+ }
+ if( pMWin->eStart==TK_FOLLOWING ){
+ windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
+ if( pMWin->eEnd!=TK_UNBOUNDED ){
+ if( pMWin->eFrmType==TK_RANGE ){
+ int lbl = sqlite3VdbeMakeLabel(pParse);
+ int addrNext = sqlite3VdbeCurrentAddr(v);
+ windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
+ windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
+ windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
+ sqlite3VdbeResolveLabel(v, lbl);
+ }else{
+ windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
+ windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
+ }
+ }
+ }else
+ if( pMWin->eEnd==TK_PRECEDING ){
+ int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
+ windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
+ if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
+ windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
+ if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
+ }else{
+ int addr = 0;
+ windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
+ if( pMWin->eEnd!=TK_UNBOUNDED ){
+ if( pMWin->eFrmType==TK_RANGE ){
+ int lbl = 0;
+ addr = sqlite3VdbeCurrentAddr(v);
+ if( regEnd ){
+ lbl = sqlite3VdbeMakeLabel(pParse);
+ windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
+ }
+ windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
+ windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
+ if( regEnd ){
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
+ sqlite3VdbeResolveLabel(v, lbl);
+ }
+ }else{
+ if( regEnd ){
+ addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
+ VdbeCoverage(v);
+ }
+ windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
+ windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
+ if( regEnd ) sqlite3VdbeJumpHere(v, addr);
+ }
+ }
+ }
+
+ /* End of the main input loop */
+ sqlite3VdbeResolveLabel(v, lblWhereEnd);
+ sqlite3WhereEnd(pWInfo);
+
+ /* Fall through */
+ if( pMWin->pPartition ){
+ addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
+ sqlite3VdbeJumpHere(v, addrGosubFlush);
+ }
+
+ addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
+ VdbeCoverage(v);
+ if( pMWin->eEnd==TK_PRECEDING ){
+ int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
+ windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
+ if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
+ windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
+ }else if( pMWin->eStart==TK_FOLLOWING ){
+ int addrStart;
+ int addrBreak1;
+ int addrBreak2;
+ int addrBreak3;
+ windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
+ if( pMWin->eFrmType==TK_RANGE ){
+ addrStart = sqlite3VdbeCurrentAddr(v);
+ addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
+ addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
+ }else
+ if( pMWin->eEnd==TK_UNBOUNDED ){
+ addrStart = sqlite3VdbeCurrentAddr(v);
+ addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
+ addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
+ }else{
+ assert( pMWin->eEnd==TK_FOLLOWING );
+ addrStart = sqlite3VdbeCurrentAddr(v);
+ addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
+ addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
+ }
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
+ sqlite3VdbeJumpHere(v, addrBreak2);
+ addrStart = sqlite3VdbeCurrentAddr(v);
+ addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
+ sqlite3VdbeJumpHere(v, addrBreak1);
+ sqlite3VdbeJumpHere(v, addrBreak3);
+ }else{
+ int addrBreak;
+ int addrStart;
+ windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
+ addrStart = sqlite3VdbeCurrentAddr(v);
+ addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
+ windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
+ sqlite3VdbeJumpHere(v, addrBreak);
+ }
+ sqlite3VdbeJumpHere(v, addrEmpty);
+
+ sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
+ if( pMWin->pPartition ){
+ if( pMWin->regStartRowid ){
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
+ }
+ sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
+ sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
+ }
+}
+
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+
+/************** End of window.c **********************************************/
+/************** Begin file parse.c *******************************************/
+/* This file is automatically generated by Lemon from input grammar
+** source file "parse.y". */
+/*
+** 2001-09-15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains SQLite's SQL parser.
+**
+** The canonical source code to this file ("parse.y") is a Lemon grammar
+** file that specifies the input grammar and actions to take while parsing.
+** That input file is processed by Lemon to generate a C-language
+** implementation of a parser for the given grammer. You might be reading
+** this comment as part of the translated C-code. Edits should be made
+** to the original parse.y sources.
+*/
+
+/* #include "sqliteInt.h" */
+
+/*
+** Disable all error recovery processing in the parser push-down
+** automaton.
+*/
+#define YYNOERRORRECOVERY 1
+
+/*
+** Make yytestcase() the same as testcase()
+*/
+#define yytestcase(X) testcase(X)
+
+/*
+** Indicate that sqlite3ParserFree() will never be called with a null
+** pointer.
+*/
+#define YYPARSEFREENEVERNULL 1
+
+/*
+** In the amalgamation, the parse.c file generated by lemon and the
+** tokenize.c file are concatenated. In that case, sqlite3RunParser()
+** has access to the the size of the yyParser object and so the parser
+** engine can be allocated from stack. In that case, only the
+** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
+** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
+** omitted.
+*/
+#ifdef SQLITE_AMALGAMATION
+# define sqlite3Parser_ENGINEALWAYSONSTACK 1
+#endif
+
+/*
+** Alternative datatype for the argument to the malloc() routine passed
+** into sqlite3ParserAlloc(). The default is size_t.
+*/
+#define YYMALLOCARGTYPE u64
+
+/*
+** An instance of the following structure describes the event of a
+** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
+** TK_DELETE, or TK_INSTEAD. If the event is of the form
+**
+** UPDATE ON (a,b,c)
+**
+** Then the "b" IdList records the list "a,b,c".
+*/
+struct TrigEvent { int a; IdList * b; };
+
+struct FrameBound { int eType; Expr *pExpr; };
+
+/*
+** Disable lookaside memory allocation for objects that might be
+** shared across database connections.
+*/
+static void disableLookaside(Parse *pParse){
+ sqlite3 *db = pParse->db;
+ pParse->disableLookaside++;
+ DisableLookaside;
+}
+
+#if !defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) \
+ && defined(SQLITE_UDL_CAPABLE_PARSER)
+/*
+** Issue an error message if an ORDER BY or LIMIT clause occurs on an
+** UPDATE or DELETE statement.
+*/
+static void updateDeleteLimitError(
+ Parse *pParse,
+ ExprList *pOrderBy,
+ Expr *pLimit
+){
+ if( pOrderBy ){
+ sqlite3ErrorMsg(pParse, "syntax error near \"ORDER BY\"");
+ }else{
+ sqlite3ErrorMsg(pParse, "syntax error near \"LIMIT\"");
+ }
+ sqlite3ExprListDelete(pParse->db, pOrderBy);
+ sqlite3ExprDelete(pParse->db, pLimit);
+}
+#endif /* SQLITE_ENABLE_UPDATE_DELETE_LIMIT */
+
+
+ /*
+ ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
+ ** all elements in the list. And make sure list length does not exceed
+ ** SQLITE_LIMIT_COMPOUND_SELECT.
+ */
+ static void parserDoubleLinkSelect(Parse *pParse, Select *p){
+ assert( p!=0 );
+ if( p->pPrior ){
+ Select *pNext = 0, *pLoop;
+ int mxSelect, cnt = 0;
+ for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
+ pLoop->pNext = pNext;
+ pLoop->selFlags |= SF_Compound;
+ }
+ if( (p->selFlags & SF_MultiValue)==0 &&
+ (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
+ cnt>mxSelect
+ ){
+ sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
+ }
+ }
+ }
+
+
+ /* Construct a new Expr object from a single identifier. Use the
+ ** new Expr to populate pOut. Set the span of pOut to be the identifier
+ ** that created the expression.
+ */
+ static Expr *tokenExpr(Parse *pParse, int op, Token t){
+ Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
+ if( p ){
+ /* memset(p, 0, sizeof(Expr)); */
+ p->op = (u8)op;
+ p->affExpr = 0;
+ p->flags = EP_Leaf;
+ ExprClearVVAProperties(p);
+ p->iAgg = -1;
+ p->pLeft = p->pRight = 0;
+ p->x.pList = 0;
+ p->pAggInfo = 0;
+ p->y.pTab = 0;
+ p->op2 = 0;
+ p->iTable = 0;
+ p->iColumn = 0;
+ p->u.zToken = (char*)&p[1];
+ memcpy(p->u.zToken, t.z, t.n);
+ p->u.zToken[t.n] = 0;
+ if( sqlite3Isquote(p->u.zToken[0]) ){
+ sqlite3DequoteExpr(p);
+ }
+#if SQLITE_MAX_EXPR_DEPTH>0
+ p->nHeight = 1;
+#endif
+ if( IN_RENAME_OBJECT ){
+ return (Expr*)sqlite3RenameTokenMap(pParse, (void*)p, &t);
+ }
+ }
+ return p;
+ }
+
+
+ /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
+ ** unary TK_ISNULL or TK_NOTNULL expression. */
+ static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
+ sqlite3 *db = pParse->db;
+ if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){
+ pA->op = (u8)op;
+ sqlite3ExprDelete(db, pA->pRight);
+ pA->pRight = 0;
+ }
+ }
+
+ /* Add a single new term to an ExprList that is used to store a
+ ** list of identifiers. Report an error if the ID list contains
+ ** a COLLATE clause or an ASC or DESC keyword, except ignore the
+ ** error while parsing a legacy schema.
+ */
+ static ExprList *parserAddExprIdListTerm(
+ Parse *pParse,
+ ExprList *pPrior,
+ Token *pIdToken,
+ int hasCollate,
+ int sortOrder
+ ){
+ ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
+ if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
+ && pParse->db->init.busy==0
+ ){
+ sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
+ pIdToken->n, pIdToken->z);
+ }
+ sqlite3ExprListSetName(pParse, p, pIdToken, 1);
+ return p;
+ }
+
+#if TK_SPAN>255
+# error too many tokens in the grammar
+#endif
+/**************** End of %include directives **********************************/
+/* These constants specify the various numeric values for terminal symbols.
+***************** Begin token definitions *************************************/
+#ifndef TK_SEMI
+#define TK_SEMI 1
+#define TK_EXPLAIN 2
+#define TK_QUERY 3
+#define TK_PLAN 4
+#define TK_BEGIN 5
+#define TK_TRANSACTION 6
+#define TK_DEFERRED 7
+#define TK_IMMEDIATE 8
+#define TK_EXCLUSIVE 9
+#define TK_COMMIT 10
+#define TK_END 11
+#define TK_ROLLBACK 12
+#define TK_SAVEPOINT 13
+#define TK_RELEASE 14
+#define TK_TO 15
+#define TK_TABLE 16
+#define TK_CREATE 17
+#define TK_IF 18
+#define TK_NOT 19
+#define TK_EXISTS 20
+#define TK_TEMP 21
+#define TK_LP 22
+#define TK_RP 23
+#define TK_AS 24
+#define TK_WITHOUT 25
+#define TK_COMMA 26
+#define TK_ABORT 27
+#define TK_ACTION 28
+#define TK_AFTER 29
+#define TK_ANALYZE 30
+#define TK_ASC 31
+#define TK_ATTACH 32
+#define TK_BEFORE 33
+#define TK_BY 34
+#define TK_CASCADE 35
+#define TK_CAST 36
+#define TK_CONFLICT 37
+#define TK_DATABASE 38
+#define TK_DESC 39
+#define TK_DETACH 40
+#define TK_EACH 41
+#define TK_FAIL 42
+#define TK_OR 43
+#define TK_AND 44
+#define TK_IS 45
+#define TK_MATCH 46
+#define TK_LIKE_KW 47
+#define TK_BETWEEN 48
+#define TK_IN 49
+#define TK_ISNULL 50
+#define TK_NOTNULL 51
+#define TK_NE 52
+#define TK_EQ 53
+#define TK_GT 54
+#define TK_LE 55
+#define TK_LT 56
+#define TK_GE 57
+#define TK_ESCAPE 58
+#define TK_ID 59
+#define TK_COLUMNKW 60
+#define TK_DO 61
+#define TK_FOR 62
+#define TK_IGNORE 63
+#define TK_INITIALLY 64
+#define TK_INSTEAD 65
+#define TK_NO 66
+#define TK_KEY 67
+#define TK_OF 68
+#define TK_OFFSET 69
+#define TK_PRAGMA 70
+#define TK_RAISE 71
+#define TK_RECURSIVE 72
+#define TK_REPLACE 73
+#define TK_RESTRICT 74
+#define TK_ROW 75
+#define TK_ROWS 76
+#define TK_TRIGGER 77
+#define TK_VACUUM 78
+#define TK_VIEW 79
+#define TK_VIRTUAL 80
+#define TK_WITH 81
+#define TK_NULLS 82
+#define TK_FIRST 83
+#define TK_LAST 84
+#define TK_CURRENT 85
+#define TK_FOLLOWING 86
+#define TK_PARTITION 87
+#define TK_PRECEDING 88
+#define TK_RANGE 89
+#define TK_UNBOUNDED 90
+#define TK_EXCLUDE 91
+#define TK_GROUPS 92
+#define TK_OTHERS 93
+#define TK_TIES 94
+#define TK_GENERATED 95
+#define TK_ALWAYS 96
+#define TK_REINDEX 97
+#define TK_RENAME 98
+#define TK_CTIME_KW 99
+#define TK_ANY 100
+#define TK_BITAND 101
+#define TK_BITOR 102
+#define TK_LSHIFT 103
+#define TK_RSHIFT 104
+#define TK_PLUS 105
+#define TK_MINUS 106
+#define TK_STAR 107
+#define TK_SLASH 108
+#define TK_REM 109
+#define TK_CONCAT 110
+#define TK_COLLATE 111
+#define TK_BITNOT 112
+#define TK_ON 113
+#define TK_INDEXED 114
+#define TK_STRING 115
+#define TK_JOIN_KW 116
+#define TK_CONSTRAINT 117
+#define TK_DEFAULT 118
+#define TK_NULL 119
+#define TK_PRIMARY 120
+#define TK_UNIQUE 121
+#define TK_CHECK 122
+#define TK_REFERENCES 123
+#define TK_AUTOINCR 124
+#define TK_INSERT 125
+#define TK_DELETE 126
+#define TK_UPDATE 127
+#define TK_SET 128
+#define TK_DEFERRABLE 129
+#define TK_FOREIGN 130
+#define TK_DROP 131
+#define TK_UNION 132
+#define TK_ALL 133
+#define TK_EXCEPT 134
+#define TK_INTERSECT 135
+#define TK_SELECT 136
+#define TK_VALUES 137
+#define TK_DISTINCT 138
+#define TK_DOT 139
+#define TK_FROM 140
+#define TK_JOIN 141
+#define TK_USING 142
+#define TK_ORDER 143
+#define TK_GROUP 144
+#define TK_HAVING 145
+#define TK_LIMIT 146
+#define TK_WHERE 147
+#define TK_INTO 148
+#define TK_NOTHING 149
+#define TK_FLOAT 150
+#define TK_BLOB 151
+#define TK_INTEGER 152
+#define TK_VARIABLE 153
+#define TK_CASE 154
+#define TK_WHEN 155
+#define TK_THEN 156
+#define TK_ELSE 157
+#define TK_INDEX 158
+#define TK_ALTER 159
+#define TK_ADD 160
+#define TK_WINDOW 161
+#define TK_OVER 162
+#define TK_FILTER 163
+#define TK_COLUMN 164
+#define TK_AGG_FUNCTION 165
+#define TK_AGG_COLUMN 166
+#define TK_TRUEFALSE 167
+#define TK_ISNOT 168
+#define TK_FUNCTION 169
+#define TK_UMINUS 170
+#define TK_UPLUS 171
+#define TK_TRUTH 172
+#define TK_REGISTER 173
+#define TK_VECTOR 174
+#define TK_SELECT_COLUMN 175
+#define TK_IF_NULL_ROW 176
+#define TK_ASTERISK 177
+#define TK_SPAN 178
+#define TK_SPACE 179
+#define TK_ILLEGAL 180
+#endif
+/**************** End token definitions ***************************************/
+
+/* The next sections is a series of control #defines.
+** various aspects of the generated parser.
+** YYCODETYPE is the data type used to store the integer codes
+** that represent terminal and non-terminal symbols.
+** "unsigned char" is used if there are fewer than
+** 256 symbols. Larger types otherwise.
+** YYNOCODE is a number of type YYCODETYPE that is not used for
+** any terminal or nonterminal symbol.
+** YYFALLBACK If defined, this indicates that one or more tokens
+** (also known as: "terminal symbols") have fall-back
+** values which should be used if the original symbol
+** would not parse. This permits keywords to sometimes
+** be used as identifiers, for example.
+** YYACTIONTYPE is the data type used for "action codes" - numbers
+** that indicate what to do in response to the next
+** token.
+** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
+** symbols. Background: A "minor type" is a semantic
+** value associated with a terminal or non-terminal
+** symbols. For example, for an "ID" terminal symbol,
+** the minor type might be the name of the identifier.
+** Each non-terminal can have a different minor type.
+** Terminal symbols all have the same minor type, though.
+** This macros defines the minor type for terminal
+** symbols.
+** YYMINORTYPE is the data type used for all minor types.
+** This is typically a union of many types, one of
+** which is sqlite3ParserTOKENTYPE. The entry in the union
+** for terminal symbols is called "yy0".
+** YYSTACKDEPTH is the maximum depth of the parser's stack. If
+** zero the stack is dynamically sized using realloc()
+** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
+** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
+** sqlite3ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter
+** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
+** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
+** sqlite3ParserCTX_* As sqlite3ParserARG_ except for %extra_context
+** YYERRORSYMBOL is the code number of the error symbol. If not
+** defined, then do no error processing.
+** YYNSTATE the combined number of states.
+** YYNRULE the number of rules in the grammar
+** YYNTOKEN Number of terminal symbols
+** YY_MAX_SHIFT Maximum value for shift actions
+** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
+** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
+** YY_ERROR_ACTION The yy_action[] code for syntax error
+** YY_ACCEPT_ACTION The yy_action[] code for accept
+** YY_NO_ACTION The yy_action[] code for no-op
+** YY_MIN_REDUCE Minimum value for reduce actions
+** YY_MAX_REDUCE Maximum value for reduce actions
+*/
+#ifndef INTERFACE
+# define INTERFACE 1
+#endif
+/************* Begin control #defines *****************************************/
+#define YYCODETYPE unsigned short int
+#define YYNOCODE 310
+#define YYACTIONTYPE unsigned short int
+#define YYWILDCARD 100
+#define sqlite3ParserTOKENTYPE Token
+typedef union {
+ int yyinit;
+ sqlite3ParserTOKENTYPE yy0;
+ SrcList* yy47;
+ u8 yy58;
+ struct FrameBound yy77;
+ With* yy131;
+ int yy192;
+ Expr* yy202;
+ struct {int value; int mask;} yy207;
+ struct TrigEvent yy230;
+ ExprList* yy242;
+ Window* yy303;
+ Upsert* yy318;
+ const char* yy436;
+ TriggerStep* yy447;
+ Select* yy539;
+ IdList* yy600;
+} YYMINORTYPE;
+#ifndef YYSTACKDEPTH
+#define YYSTACKDEPTH 100
+#endif
+#define sqlite3ParserARG_SDECL
+#define sqlite3ParserARG_PDECL
+#define sqlite3ParserARG_PARAM
+#define sqlite3ParserARG_FETCH
+#define sqlite3ParserARG_STORE
+#define sqlite3ParserCTX_SDECL Parse *pParse;
+#define sqlite3ParserCTX_PDECL ,Parse *pParse
+#define sqlite3ParserCTX_PARAM ,pParse
+#define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
+#define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
+#define YYFALLBACK 1
+#define YYNSTATE 553
+#define YYNRULE 385
+#define YYNRULE_WITH_ACTION 325
+#define YYNTOKEN 181
+#define YY_MAX_SHIFT 552
+#define YY_MIN_SHIFTREDUCE 803
+#define YY_MAX_SHIFTREDUCE 1187
+#define YY_ERROR_ACTION 1188
+#define YY_ACCEPT_ACTION 1189
+#define YY_NO_ACTION 1190
+#define YY_MIN_REDUCE 1191
+#define YY_MAX_REDUCE 1575
+/************* End control #defines *******************************************/
+#define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])))
+
+/* Define the yytestcase() macro to be a no-op if is not already defined
+** otherwise.
+**
+** Applications can choose to define yytestcase() in the %include section
+** to a macro that can assist in verifying code coverage. For production
+** code the yytestcase() macro should be turned off. But it is useful
+** for testing.
+*/
+#ifndef yytestcase
+# define yytestcase(X)
+#endif
+
+
+/* Next are the tables used to determine what action to take based on the
+** current state and lookahead token. These tables are used to implement
+** functions that take a state number and lookahead value and return an
+** action integer.
+**
+** Suppose the action integer is N. Then the action is determined as
+** follows
+**
+** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
+** token onto the stack and goto state N.
+**
+** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
+** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
+**
+** N == YY_ERROR_ACTION A syntax error has occurred.
+**
+** N == YY_ACCEPT_ACTION The parser accepts its input.
+**
+** N == YY_NO_ACTION No such action. Denotes unused
+** slots in the yy_action[] table.
+**
+** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
+** and YY_MAX_REDUCE
+**
+** The action table is constructed as a single large table named yy_action[].
+** Given state S and lookahead X, the action is computed as either:
+**
+** (A) N = yy_action[ yy_shift_ofst[S] + X ]
+** (B) N = yy_default[S]
+**
+** The (A) formula is preferred. The B formula is used instead if
+** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X.
+**
+** The formulas above are for computing the action when the lookahead is
+** a terminal symbol. If the lookahead is a non-terminal (as occurs after
+** a reduce action) then the yy_reduce_ofst[] array is used in place of
+** the yy_shift_ofst[] array.
+**
+** The following are the tables generated in this section:
+**
+** yy_action[] A single table containing all actions.
+** yy_lookahead[] A table containing the lookahead for each entry in
+** yy_action. Used to detect hash collisions.
+** yy_shift_ofst[] For each state, the offset into yy_action for
+** shifting terminals.
+** yy_reduce_ofst[] For each state, the offset into yy_action for
+** shifting non-terminals after a reduce.
+** yy_default[] Default action for each state.
+**
+*********** Begin parsing tables **********************************************/
+#define YY_ACTTAB_COUNT (1962)
+static const YYACTIONTYPE yy_action[] = {
+ /* 0 */ 546, 1222, 546, 451, 1260, 546, 1239, 546, 114, 111,
+ /* 10 */ 211, 546, 1537, 546, 1260, 523, 114, 111, 211, 392,
+ /* 20 */ 1232, 344, 42, 42, 42, 42, 1225, 42, 42, 71,
+ /* 30 */ 71, 937, 1224, 71, 71, 71, 71, 1462, 1493, 938,
+ /* 40 */ 820, 453, 6, 121, 122, 112, 1165, 1165, 1006, 1009,
+ /* 50 */ 999, 999, 119, 119, 120, 120, 120, 120, 1543, 392,
+ /* 60 */ 1358, 1517, 552, 2, 1193, 194, 528, 436, 143, 291,
+ /* 70 */ 528, 136, 528, 371, 261, 504, 272, 385, 1273, 527,
+ /* 80 */ 503, 493, 164, 121, 122, 112, 1165, 1165, 1006, 1009,
+ /* 90 */ 999, 999, 119, 119, 120, 120, 120, 120, 1358, 442,
+ /* 100 */ 1514, 118, 118, 118, 118, 117, 117, 116, 116, 116,
+ /* 110 */ 115, 424, 266, 266, 266, 266, 1498, 358, 1500, 435,
+ /* 120 */ 357, 1498, 517, 524, 1485, 543, 1114, 543, 1114, 392,
+ /* 130 */ 405, 241, 208, 114, 111, 211, 98, 290, 537, 221,
+ /* 140 */ 1029, 118, 118, 118, 118, 117, 117, 116, 116, 116,
+ /* 150 */ 115, 424, 1142, 121, 122, 112, 1165, 1165, 1006, 1009,
+ /* 160 */ 999, 999, 119, 119, 120, 120, 120, 120, 406, 428,
+ /* 170 */ 117, 117, 116, 116, 116, 115, 424, 1418, 468, 123,
+ /* 180 */ 118, 118, 118, 118, 117, 117, 116, 116, 116, 115,
+ /* 190 */ 424, 116, 116, 116, 115, 424, 540, 540, 540, 392,
+ /* 200 */ 505, 120, 120, 120, 120, 113, 1051, 1142, 1143, 1144,
+ /* 210 */ 1051, 118, 118, 118, 118, 117, 117, 116, 116, 116,
+ /* 220 */ 115, 424, 1461, 121, 122, 112, 1165, 1165, 1006, 1009,
+ /* 230 */ 999, 999, 119, 119, 120, 120, 120, 120, 392, 444,
+ /* 240 */ 316, 83, 463, 81, 359, 382, 1142, 80, 118, 118,
+ /* 250 */ 118, 118, 117, 117, 116, 116, 116, 115, 424, 179,
+ /* 260 */ 434, 424, 121, 122, 112, 1165, 1165, 1006, 1009, 999,
+ /* 270 */ 999, 119, 119, 120, 120, 120, 120, 434, 433, 266,
+ /* 280 */ 266, 118, 118, 118, 118, 117, 117, 116, 116, 116,
+ /* 290 */ 115, 424, 543, 1109, 903, 506, 1142, 114, 111, 211,
+ /* 300 */ 1431, 1142, 1143, 1144, 206, 491, 1109, 392, 449, 1109,
+ /* 310 */ 545, 330, 120, 120, 120, 120, 298, 1431, 1433, 17,
+ /* 320 */ 118, 118, 118, 118, 117, 117, 116, 116, 116, 115,
+ /* 330 */ 424, 121, 122, 112, 1165, 1165, 1006, 1009, 999, 999,
+ /* 340 */ 119, 119, 120, 120, 120, 120, 392, 1358, 434, 1142,
+ /* 350 */ 482, 1142, 1143, 1144, 996, 996, 1007, 1010, 445, 118,
+ /* 360 */ 118, 118, 118, 117, 117, 116, 116, 116, 115, 424,
+ /* 370 */ 121, 122, 112, 1165, 1165, 1006, 1009, 999, 999, 119,
+ /* 380 */ 119, 120, 120, 120, 120, 1054, 1054, 465, 1431, 118,
+ /* 390 */ 118, 118, 118, 117, 117, 116, 116, 116, 115, 424,
+ /* 400 */ 1142, 451, 546, 1426, 1142, 1143, 1144, 233, 966, 1142,
+ /* 410 */ 481, 478, 477, 171, 360, 392, 164, 407, 414, 842,
+ /* 420 */ 476, 164, 185, 334, 71, 71, 1243, 1000, 118, 118,
+ /* 430 */ 118, 118, 117, 117, 116, 116, 116, 115, 424, 121,
+ /* 440 */ 122, 112, 1165, 1165, 1006, 1009, 999, 999, 119, 119,
+ /* 450 */ 120, 120, 120, 120, 392, 1142, 1143, 1144, 835, 12,
+ /* 460 */ 314, 509, 163, 356, 1142, 1143, 1144, 114, 111, 211,
+ /* 470 */ 508, 290, 537, 546, 276, 180, 290, 537, 121, 122,
+ /* 480 */ 112, 1165, 1165, 1006, 1009, 999, 999, 119, 119, 120,
+ /* 490 */ 120, 120, 120, 345, 484, 71, 71, 118, 118, 118,
+ /* 500 */ 118, 117, 117, 116, 116, 116, 115, 424, 1142, 209,
+ /* 510 */ 411, 523, 1142, 1109, 1571, 378, 252, 269, 342, 487,
+ /* 520 */ 337, 486, 238, 392, 513, 364, 1109, 1127, 333, 1109,
+ /* 530 */ 191, 409, 286, 32, 457, 443, 118, 118, 118, 118,
+ /* 540 */ 117, 117, 116, 116, 116, 115, 424, 121, 122, 112,
+ /* 550 */ 1165, 1165, 1006, 1009, 999, 999, 119, 119, 120, 120,
+ /* 560 */ 120, 120, 392, 1142, 1143, 1144, 987, 1142, 1143, 1144,
+ /* 570 */ 1142, 233, 492, 1492, 481, 478, 477, 6, 163, 546,
+ /* 580 */ 512, 546, 115, 424, 476, 5, 121, 122, 112, 1165,
+ /* 590 */ 1165, 1006, 1009, 999, 999, 119, 119, 120, 120, 120,
+ /* 600 */ 120, 13, 13, 13, 13, 118, 118, 118, 118, 117,
+ /* 610 */ 117, 116, 116, 116, 115, 424, 403, 502, 408, 546,
+ /* 620 */ 1486, 544, 1142, 892, 892, 1142, 1143, 1144, 1473, 1142,
+ /* 630 */ 275, 392, 808, 809, 810, 971, 422, 422, 422, 16,
+ /* 640 */ 16, 55, 55, 1242, 118, 118, 118, 118, 117, 117,
+ /* 650 */ 116, 116, 116, 115, 424, 121, 122, 112, 1165, 1165,
+ /* 660 */ 1006, 1009, 999, 999, 119, 119, 120, 120, 120, 120,
+ /* 670 */ 392, 1189, 1, 1, 552, 2, 1193, 1142, 1143, 1144,
+ /* 680 */ 194, 291, 898, 136, 1142, 1143, 1144, 897, 521, 1492,
+ /* 690 */ 1273, 3, 380, 6, 121, 122, 112, 1165, 1165, 1006,
+ /* 700 */ 1009, 999, 999, 119, 119, 120, 120, 120, 120, 858,
+ /* 710 */ 546, 924, 546, 118, 118, 118, 118, 117, 117, 116,
+ /* 720 */ 116, 116, 115, 424, 266, 266, 1092, 1569, 1142, 551,
+ /* 730 */ 1569, 1193, 13, 13, 13, 13, 291, 543, 136, 392,
+ /* 740 */ 485, 421, 420, 966, 344, 1273, 468, 410, 859, 279,
+ /* 750 */ 140, 221, 118, 118, 118, 118, 117, 117, 116, 116,
+ /* 760 */ 116, 115, 424, 121, 122, 112, 1165, 1165, 1006, 1009,
+ /* 770 */ 999, 999, 119, 119, 120, 120, 120, 120, 546, 266,
+ /* 780 */ 266, 428, 392, 1142, 1143, 1144, 1172, 830, 1172, 468,
+ /* 790 */ 431, 145, 543, 1146, 401, 314, 439, 302, 838, 1490,
+ /* 800 */ 71, 71, 412, 6, 1090, 473, 221, 100, 112, 1165,
+ /* 810 */ 1165, 1006, 1009, 999, 999, 119, 119, 120, 120, 120,
+ /* 820 */ 120, 118, 118, 118, 118, 117, 117, 116, 116, 116,
+ /* 830 */ 115, 424, 237, 1425, 546, 451, 428, 287, 986, 546,
+ /* 840 */ 236, 235, 234, 830, 97, 529, 429, 1265, 1265, 1146,
+ /* 850 */ 494, 307, 430, 838, 977, 546, 71, 71, 976, 1241,
+ /* 860 */ 546, 51, 51, 300, 118, 118, 118, 118, 117, 117,
+ /* 870 */ 116, 116, 116, 115, 424, 194, 103, 70, 70, 266,
+ /* 880 */ 266, 546, 71, 71, 266, 266, 30, 391, 344, 976,
+ /* 890 */ 976, 978, 543, 528, 1109, 328, 392, 543, 495, 397,
+ /* 900 */ 1470, 195, 530, 13, 13, 1358, 240, 1109, 277, 280,
+ /* 910 */ 1109, 280, 304, 457, 306, 333, 392, 31, 188, 419,
+ /* 920 */ 121, 122, 112, 1165, 1165, 1006, 1009, 999, 999, 119,
+ /* 930 */ 119, 120, 120, 120, 120, 142, 392, 365, 457, 986,
+ /* 940 */ 121, 122, 112, 1165, 1165, 1006, 1009, 999, 999, 119,
+ /* 950 */ 119, 120, 120, 120, 120, 977, 323, 1142, 326, 976,
+ /* 960 */ 121, 110, 112, 1165, 1165, 1006, 1009, 999, 999, 119,
+ /* 970 */ 119, 120, 120, 120, 120, 464, 377, 1185, 118, 118,
+ /* 980 */ 118, 118, 117, 117, 116, 116, 116, 115, 424, 1142,
+ /* 990 */ 976, 976, 978, 305, 9, 366, 244, 362, 118, 118,
+ /* 1000 */ 118, 118, 117, 117, 116, 116, 116, 115, 424, 313,
+ /* 1010 */ 546, 344, 1142, 1143, 1144, 299, 290, 537, 118, 118,
+ /* 1020 */ 118, 118, 117, 117, 116, 116, 116, 115, 424, 1263,
+ /* 1030 */ 1263, 1163, 13, 13, 278, 421, 420, 468, 392, 923,
+ /* 1040 */ 260, 260, 289, 1169, 1142, 1143, 1144, 189, 1171, 266,
+ /* 1050 */ 266, 468, 390, 543, 1186, 546, 1170, 263, 144, 489,
+ /* 1060 */ 922, 546, 543, 122, 112, 1165, 1165, 1006, 1009, 999,
+ /* 1070 */ 999, 119, 119, 120, 120, 120, 120, 71, 71, 1142,
+ /* 1080 */ 1172, 1272, 1172, 13, 13, 898, 1070, 1163, 546, 468,
+ /* 1090 */ 897, 107, 538, 1491, 4, 1268, 1109, 6, 525, 1049,
+ /* 1100 */ 12, 1071, 1092, 1570, 312, 455, 1570, 520, 541, 1109,
+ /* 1110 */ 56, 56, 1109, 1489, 423, 1358, 1072, 6, 345, 285,
+ /* 1120 */ 118, 118, 118, 118, 117, 117, 116, 116, 116, 115,
+ /* 1130 */ 424, 425, 1271, 321, 1142, 1143, 1144, 878, 266, 266,
+ /* 1140 */ 1277, 107, 538, 535, 4, 1488, 293, 879, 1211, 6,
+ /* 1150 */ 210, 543, 543, 164, 294, 496, 416, 204, 541, 267,
+ /* 1160 */ 267, 1214, 398, 511, 499, 204, 266, 266, 396, 531,
+ /* 1170 */ 8, 986, 543, 519, 546, 922, 458, 105, 105, 543,
+ /* 1180 */ 1090, 425, 266, 266, 106, 417, 425, 548, 547, 266,
+ /* 1190 */ 266, 976, 518, 535, 1373, 543, 15, 15, 266, 266,
+ /* 1200 */ 456, 1120, 543, 266, 266, 1070, 1372, 515, 290, 537,
+ /* 1210 */ 546, 543, 514, 97, 444, 316, 543, 546, 922, 125,
+ /* 1220 */ 1071, 986, 976, 976, 978, 979, 27, 105, 105, 401,
+ /* 1230 */ 343, 1511, 44, 44, 106, 1072, 425, 548, 547, 57,
+ /* 1240 */ 57, 976, 343, 1511, 107, 538, 546, 4, 462, 401,
+ /* 1250 */ 214, 1120, 459, 297, 377, 1091, 534, 1309, 546, 539,
+ /* 1260 */ 398, 541, 290, 537, 104, 244, 102, 526, 58, 58,
+ /* 1270 */ 546, 199, 976, 976, 978, 979, 27, 1516, 1131, 427,
+ /* 1280 */ 59, 59, 270, 237, 425, 138, 95, 375, 375, 374,
+ /* 1290 */ 255, 372, 60, 60, 817, 1180, 535, 546, 273, 546,
+ /* 1300 */ 1163, 1308, 389, 388, 546, 438, 546, 215, 210, 296,
+ /* 1310 */ 515, 849, 546, 265, 208, 516, 1476, 295, 274, 61,
+ /* 1320 */ 61, 62, 62, 308, 986, 109, 45, 45, 46, 46,
+ /* 1330 */ 105, 105, 1186, 922, 47, 47, 341, 106, 546, 425,
+ /* 1340 */ 548, 547, 1542, 546, 976, 867, 340, 217, 546, 937,
+ /* 1350 */ 397, 107, 538, 218, 4, 156, 1163, 938, 158, 546,
+ /* 1360 */ 49, 49, 1162, 546, 268, 50, 50, 546, 541, 1450,
+ /* 1370 */ 63, 63, 546, 1449, 216, 976, 976, 978, 979, 27,
+ /* 1380 */ 446, 64, 64, 546, 460, 65, 65, 546, 318, 14,
+ /* 1390 */ 14, 425, 1305, 546, 66, 66, 1087, 546, 141, 379,
+ /* 1400 */ 38, 546, 963, 535, 322, 127, 127, 546, 393, 67,
+ /* 1410 */ 67, 546, 325, 290, 537, 52, 52, 515, 546, 68,
+ /* 1420 */ 68, 845, 514, 69, 69, 399, 165, 857, 856, 53,
+ /* 1430 */ 53, 986, 311, 151, 151, 97, 432, 105, 105, 327,
+ /* 1440 */ 152, 152, 526, 1048, 106, 1048, 425, 548, 547, 1131,
+ /* 1450 */ 427, 976, 1032, 270, 968, 239, 329, 243, 375, 375,
+ /* 1460 */ 374, 255, 372, 940, 941, 817, 1296, 546, 220, 546,
+ /* 1470 */ 107, 538, 546, 4, 546, 1256, 199, 845, 215, 1036,
+ /* 1480 */ 296, 1530, 976, 976, 978, 979, 27, 541, 295, 76,
+ /* 1490 */ 76, 54, 54, 980, 72, 72, 128, 128, 864, 865,
+ /* 1500 */ 107, 538, 546, 4, 1047, 546, 1047, 533, 469, 546,
+ /* 1510 */ 425, 546, 450, 1240, 546, 243, 546, 541, 217, 546,
+ /* 1520 */ 452, 197, 535, 243, 73, 73, 156, 129, 129, 158,
+ /* 1530 */ 336, 130, 130, 126, 126, 1036, 150, 150, 149, 149,
+ /* 1540 */ 425, 134, 134, 317, 474, 216, 97, 239, 331, 980,
+ /* 1550 */ 986, 97, 535, 346, 347, 546, 105, 105, 902, 931,
+ /* 1560 */ 546, 895, 243, 106, 109, 425, 548, 547, 546, 1505,
+ /* 1570 */ 976, 828, 99, 538, 139, 4, 546, 133, 133, 393,
+ /* 1580 */ 986, 1317, 131, 131, 290, 537, 105, 105, 1357, 541,
+ /* 1590 */ 132, 132, 1292, 106, 1303, 425, 548, 547, 75, 75,
+ /* 1600 */ 976, 976, 976, 978, 979, 27, 546, 432, 896, 1289,
+ /* 1610 */ 532, 109, 425, 1363, 546, 1221, 1213, 1202, 258, 546,
+ /* 1620 */ 349, 546, 1201, 11, 535, 1203, 1524, 351, 77, 77,
+ /* 1630 */ 376, 976, 976, 978, 979, 27, 74, 74, 353, 213,
+ /* 1640 */ 301, 43, 43, 48, 48, 437, 310, 201, 303, 1350,
+ /* 1650 */ 315, 355, 986, 454, 479, 1239, 339, 192, 105, 105,
+ /* 1660 */ 1422, 1421, 193, 536, 205, 106, 1527, 425, 548, 547,
+ /* 1670 */ 1180, 167, 976, 270, 247, 1469, 1467, 1177, 375, 375,
+ /* 1680 */ 374, 255, 372, 200, 369, 817, 400, 83, 79, 82,
+ /* 1690 */ 1427, 448, 177, 95, 1342, 161, 169, 1339, 215, 440,
+ /* 1700 */ 296, 172, 173, 976, 976, 978, 979, 27, 295, 174,
+ /* 1710 */ 175, 441, 472, 223, 1347, 383, 35, 381, 36, 461,
+ /* 1720 */ 88, 1353, 181, 447, 384, 1416, 227, 467, 259, 229,
+ /* 1730 */ 186, 488, 470, 324, 1250, 230, 231, 320, 217, 1204,
+ /* 1740 */ 1438, 1259, 386, 1258, 413, 90, 156, 849, 1541, 158,
+ /* 1750 */ 206, 415, 1540, 507, 1300, 1257, 94, 348, 1229, 1301,
+ /* 1760 */ 387, 1510, 1228, 338, 1227, 216, 350, 1539, 498, 283,
+ /* 1770 */ 284, 1249, 501, 1299, 352, 245, 246, 418, 1298, 354,
+ /* 1780 */ 1496, 1495, 124, 10, 526, 363, 101, 1324, 253, 96,
+ /* 1790 */ 510, 1210, 34, 549, 1137, 254, 256, 257, 166, 393,
+ /* 1800 */ 550, 1199, 1282, 361, 290, 537, 1281, 196, 367, 368,
+ /* 1810 */ 1194, 153, 1454, 137, 281, 1323, 1455, 804, 154, 426,
+ /* 1820 */ 198, 155, 1453, 1452, 292, 212, 202, 432, 1402, 203,
+ /* 1830 */ 271, 135, 288, 78, 1046, 1044, 960, 168, 157, 881,
+ /* 1840 */ 170, 219, 309, 222, 1060, 176, 964, 159, 402, 84,
+ /* 1850 */ 178, 404, 85, 86, 87, 160, 1063, 224, 394, 395,
+ /* 1860 */ 225, 1059, 146, 18, 226, 319, 243, 1174, 466, 228,
+ /* 1870 */ 1052, 182, 183, 37, 819, 471, 340, 232, 332, 483,
+ /* 1880 */ 184, 89, 162, 19, 20, 475, 91, 480, 847, 335,
+ /* 1890 */ 147, 860, 282, 92, 490, 93, 1125, 148, 1012, 1095,
+ /* 1900 */ 39, 497, 1096, 40, 500, 262, 207, 264, 930, 187,
+ /* 1910 */ 925, 109, 1111, 1115, 1113, 7, 1099, 242, 33, 1119,
+ /* 1920 */ 21, 522, 22, 23, 24, 1118, 25, 190, 97, 26,
+ /* 1930 */ 1027, 1013, 1011, 1015, 1069, 1016, 1068, 249, 248, 28,
+ /* 1940 */ 41, 891, 981, 829, 108, 29, 250, 542, 251, 370,
+ /* 1950 */ 373, 1133, 1132, 1190, 1190, 1190, 1190, 1190, 1190, 1190,
+ /* 1960 */ 1532, 1531,
+};
+static const YYCODETYPE yy_lookahead[] = {
+ /* 0 */ 189, 211, 189, 189, 218, 189, 220, 189, 267, 268,
+ /* 10 */ 269, 189, 210, 189, 228, 189, 267, 268, 269, 19,
+ /* 20 */ 218, 189, 211, 212, 211, 212, 211, 211, 212, 211,
+ /* 30 */ 212, 31, 211, 211, 212, 211, 212, 288, 300, 39,
+ /* 40 */ 21, 189, 304, 43, 44, 45, 46, 47, 48, 49,
+ /* 50 */ 50, 51, 52, 53, 54, 55, 56, 57, 225, 19,
+ /* 60 */ 189, 183, 184, 185, 186, 189, 248, 263, 236, 191,
+ /* 70 */ 248, 193, 248, 197, 208, 257, 262, 201, 200, 257,
+ /* 80 */ 200, 257, 81, 43, 44, 45, 46, 47, 48, 49,
+ /* 90 */ 50, 51, 52, 53, 54, 55, 56, 57, 189, 80,
+ /* 100 */ 189, 101, 102, 103, 104, 105, 106, 107, 108, 109,
+ /* 110 */ 110, 111, 234, 235, 234, 235, 305, 306, 305, 118,
+ /* 120 */ 307, 305, 306, 297, 298, 247, 86, 247, 88, 19,
+ /* 130 */ 259, 251, 252, 267, 268, 269, 26, 136, 137, 261,
+ /* 140 */ 121, 101, 102, 103, 104, 105, 106, 107, 108, 109,
+ /* 150 */ 110, 111, 59, 43, 44, 45, 46, 47, 48, 49,
+ /* 160 */ 50, 51, 52, 53, 54, 55, 56, 57, 259, 291,
+ /* 170 */ 105, 106, 107, 108, 109, 110, 111, 158, 189, 69,
+ /* 180 */ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
+ /* 190 */ 111, 107, 108, 109, 110, 111, 205, 206, 207, 19,
+ /* 200 */ 19, 54, 55, 56, 57, 58, 29, 114, 115, 116,
+ /* 210 */ 33, 101, 102, 103, 104, 105, 106, 107, 108, 109,
+ /* 220 */ 110, 111, 233, 43, 44, 45, 46, 47, 48, 49,
+ /* 230 */ 50, 51, 52, 53, 54, 55, 56, 57, 19, 126,
+ /* 240 */ 127, 148, 65, 24, 214, 200, 59, 67, 101, 102,
+ /* 250 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 22,
+ /* 260 */ 189, 111, 43, 44, 45, 46, 47, 48, 49, 50,
+ /* 270 */ 51, 52, 53, 54, 55, 56, 57, 206, 207, 234,
+ /* 280 */ 235, 101, 102, 103, 104, 105, 106, 107, 108, 109,
+ /* 290 */ 110, 111, 247, 76, 107, 114, 59, 267, 268, 269,
+ /* 300 */ 189, 114, 115, 116, 162, 163, 89, 19, 263, 92,
+ /* 310 */ 189, 23, 54, 55, 56, 57, 189, 206, 207, 22,
+ /* 320 */ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
+ /* 330 */ 111, 43, 44, 45, 46, 47, 48, 49, 50, 51,
+ /* 340 */ 52, 53, 54, 55, 56, 57, 19, 189, 277, 59,
+ /* 350 */ 23, 114, 115, 116, 46, 47, 48, 49, 61, 101,
+ /* 360 */ 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
+ /* 370 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
+ /* 380 */ 53, 54, 55, 56, 57, 125, 126, 127, 277, 101,
+ /* 390 */ 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
+ /* 400 */ 59, 189, 189, 276, 114, 115, 116, 117, 73, 59,
+ /* 410 */ 120, 121, 122, 72, 214, 19, 81, 259, 19, 23,
+ /* 420 */ 130, 81, 72, 24, 211, 212, 221, 119, 101, 102,
+ /* 430 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 43,
+ /* 440 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
+ /* 450 */ 54, 55, 56, 57, 19, 114, 115, 116, 23, 208,
+ /* 460 */ 125, 248, 189, 189, 114, 115, 116, 267, 268, 269,
+ /* 470 */ 189, 136, 137, 189, 262, 22, 136, 137, 43, 44,
+ /* 480 */ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
+ /* 490 */ 55, 56, 57, 189, 95, 211, 212, 101, 102, 103,
+ /* 500 */ 104, 105, 106, 107, 108, 109, 110, 111, 59, 189,
+ /* 510 */ 111, 189, 59, 76, 294, 295, 117, 118, 119, 120,
+ /* 520 */ 121, 122, 123, 19, 87, 189, 89, 23, 129, 92,
+ /* 530 */ 279, 227, 248, 22, 189, 284, 101, 102, 103, 104,
+ /* 540 */ 105, 106, 107, 108, 109, 110, 111, 43, 44, 45,
+ /* 550 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
+ /* 560 */ 56, 57, 19, 114, 115, 116, 23, 114, 115, 116,
+ /* 570 */ 59, 117, 299, 300, 120, 121, 122, 304, 189, 189,
+ /* 580 */ 143, 189, 110, 111, 130, 22, 43, 44, 45, 46,
+ /* 590 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
+ /* 600 */ 57, 211, 212, 211, 212, 101, 102, 103, 104, 105,
+ /* 610 */ 106, 107, 108, 109, 110, 111, 226, 189, 226, 189,
+ /* 620 */ 298, 132, 59, 134, 135, 114, 115, 116, 189, 59,
+ /* 630 */ 285, 19, 7, 8, 9, 23, 205, 206, 207, 211,
+ /* 640 */ 212, 211, 212, 221, 101, 102, 103, 104, 105, 106,
+ /* 650 */ 107, 108, 109, 110, 111, 43, 44, 45, 46, 47,
+ /* 660 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
+ /* 670 */ 19, 181, 182, 183, 184, 185, 186, 114, 115, 116,
+ /* 680 */ 189, 191, 133, 193, 114, 115, 116, 138, 299, 300,
+ /* 690 */ 200, 22, 201, 304, 43, 44, 45, 46, 47, 48,
+ /* 700 */ 49, 50, 51, 52, 53, 54, 55, 56, 57, 35,
+ /* 710 */ 189, 141, 189, 101, 102, 103, 104, 105, 106, 107,
+ /* 720 */ 108, 109, 110, 111, 234, 235, 22, 23, 59, 184,
+ /* 730 */ 26, 186, 211, 212, 211, 212, 191, 247, 193, 19,
+ /* 740 */ 66, 105, 106, 73, 189, 200, 189, 226, 74, 226,
+ /* 750 */ 22, 261, 101, 102, 103, 104, 105, 106, 107, 108,
+ /* 760 */ 109, 110, 111, 43, 44, 45, 46, 47, 48, 49,
+ /* 770 */ 50, 51, 52, 53, 54, 55, 56, 57, 189, 234,
+ /* 780 */ 235, 291, 19, 114, 115, 116, 150, 59, 152, 189,
+ /* 790 */ 233, 236, 247, 59, 189, 125, 126, 127, 59, 300,
+ /* 800 */ 211, 212, 128, 304, 100, 19, 261, 156, 45, 46,
+ /* 810 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
+ /* 820 */ 57, 101, 102, 103, 104, 105, 106, 107, 108, 109,
+ /* 830 */ 110, 111, 46, 233, 189, 189, 291, 248, 99, 189,
+ /* 840 */ 125, 126, 127, 115, 26, 200, 289, 230, 231, 115,
+ /* 850 */ 200, 16, 189, 114, 115, 189, 211, 212, 119, 221,
+ /* 860 */ 189, 211, 212, 258, 101, 102, 103, 104, 105, 106,
+ /* 870 */ 107, 108, 109, 110, 111, 189, 156, 211, 212, 234,
+ /* 880 */ 235, 189, 211, 212, 234, 235, 22, 201, 189, 150,
+ /* 890 */ 151, 152, 247, 248, 76, 16, 19, 247, 248, 113,
+ /* 900 */ 189, 24, 257, 211, 212, 189, 26, 89, 262, 223,
+ /* 910 */ 92, 225, 77, 189, 79, 129, 19, 53, 226, 248,
+ /* 920 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
+ /* 930 */ 53, 54, 55, 56, 57, 236, 19, 271, 189, 99,
+ /* 940 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
+ /* 950 */ 53, 54, 55, 56, 57, 115, 77, 59, 79, 119,
+ /* 960 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
+ /* 970 */ 53, 54, 55, 56, 57, 259, 22, 23, 101, 102,
+ /* 980 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 59,
+ /* 990 */ 150, 151, 152, 158, 22, 244, 24, 246, 101, 102,
+ /* 1000 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 285,
+ /* 1010 */ 189, 189, 114, 115, 116, 200, 136, 137, 101, 102,
+ /* 1020 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 230,
+ /* 1030 */ 231, 59, 211, 212, 285, 105, 106, 189, 19, 141,
+ /* 1040 */ 234, 235, 239, 113, 114, 115, 116, 226, 118, 234,
+ /* 1050 */ 235, 189, 249, 247, 100, 189, 126, 23, 236, 107,
+ /* 1060 */ 26, 189, 247, 44, 45, 46, 47, 48, 49, 50,
+ /* 1070 */ 51, 52, 53, 54, 55, 56, 57, 211, 212, 59,
+ /* 1080 */ 150, 233, 152, 211, 212, 133, 12, 115, 189, 189,
+ /* 1090 */ 138, 19, 20, 300, 22, 233, 76, 304, 226, 11,
+ /* 1100 */ 208, 27, 22, 23, 200, 19, 26, 87, 36, 89,
+ /* 1110 */ 211, 212, 92, 300, 248, 189, 42, 304, 189, 250,
+ /* 1120 */ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
+ /* 1130 */ 111, 59, 200, 233, 114, 115, 116, 63, 234, 235,
+ /* 1140 */ 235, 19, 20, 71, 22, 300, 189, 73, 200, 304,
+ /* 1150 */ 116, 247, 247, 81, 189, 200, 227, 26, 36, 234,
+ /* 1160 */ 235, 203, 204, 143, 200, 26, 234, 235, 194, 200,
+ /* 1170 */ 48, 99, 247, 66, 189, 141, 284, 105, 106, 247,
+ /* 1180 */ 100, 59, 234, 235, 112, 259, 114, 115, 116, 234,
+ /* 1190 */ 235, 119, 85, 71, 266, 247, 211, 212, 234, 235,
+ /* 1200 */ 114, 94, 247, 234, 235, 12, 266, 85, 136, 137,
+ /* 1210 */ 189, 247, 90, 26, 126, 127, 247, 189, 26, 22,
+ /* 1220 */ 27, 99, 150, 151, 152, 153, 154, 105, 106, 189,
+ /* 1230 */ 302, 303, 211, 212, 112, 42, 114, 115, 116, 211,
+ /* 1240 */ 212, 119, 302, 303, 19, 20, 189, 22, 274, 189,
+ /* 1250 */ 15, 144, 278, 189, 22, 23, 63, 189, 189, 203,
+ /* 1260 */ 204, 36, 136, 137, 155, 24, 157, 143, 211, 212,
+ /* 1270 */ 189, 140, 150, 151, 152, 153, 154, 0, 1, 2,
+ /* 1280 */ 211, 212, 5, 46, 59, 161, 147, 10, 11, 12,
+ /* 1290 */ 13, 14, 211, 212, 17, 60, 71, 189, 258, 189,
+ /* 1300 */ 59, 189, 105, 106, 189, 189, 189, 30, 116, 32,
+ /* 1310 */ 85, 124, 189, 251, 252, 90, 189, 40, 258, 211,
+ /* 1320 */ 212, 211, 212, 189, 99, 26, 211, 212, 211, 212,
+ /* 1330 */ 105, 106, 100, 141, 211, 212, 119, 112, 189, 114,
+ /* 1340 */ 115, 116, 23, 189, 119, 26, 129, 70, 189, 31,
+ /* 1350 */ 113, 19, 20, 24, 22, 78, 115, 39, 81, 189,
+ /* 1360 */ 211, 212, 26, 189, 22, 211, 212, 189, 36, 189,
+ /* 1370 */ 211, 212, 189, 189, 97, 150, 151, 152, 153, 154,
+ /* 1380 */ 127, 211, 212, 189, 189, 211, 212, 189, 189, 211,
+ /* 1390 */ 212, 59, 189, 189, 211, 212, 23, 189, 22, 26,
+ /* 1400 */ 24, 189, 149, 71, 189, 211, 212, 189, 131, 211,
+ /* 1410 */ 212, 189, 189, 136, 137, 211, 212, 85, 189, 211,
+ /* 1420 */ 212, 59, 90, 211, 212, 292, 293, 118, 119, 211,
+ /* 1430 */ 212, 99, 23, 211, 212, 26, 159, 105, 106, 189,
+ /* 1440 */ 211, 212, 143, 150, 112, 152, 114, 115, 116, 1,
+ /* 1450 */ 2, 119, 23, 5, 23, 26, 189, 26, 10, 11,
+ /* 1460 */ 12, 13, 14, 83, 84, 17, 253, 189, 139, 189,
+ /* 1470 */ 19, 20, 189, 22, 189, 189, 140, 115, 30, 59,
+ /* 1480 */ 32, 139, 150, 151, 152, 153, 154, 36, 40, 211,
+ /* 1490 */ 212, 211, 212, 59, 211, 212, 211, 212, 7, 8,
+ /* 1500 */ 19, 20, 189, 22, 150, 189, 152, 231, 281, 189,
+ /* 1510 */ 59, 189, 23, 189, 189, 26, 189, 36, 70, 189,
+ /* 1520 */ 23, 237, 71, 26, 211, 212, 78, 211, 212, 81,
+ /* 1530 */ 189, 211, 212, 211, 212, 115, 211, 212, 211, 212,
+ /* 1540 */ 59, 211, 212, 23, 23, 97, 26, 26, 23, 115,
+ /* 1550 */ 99, 26, 71, 189, 189, 189, 105, 106, 107, 23,
+ /* 1560 */ 189, 23, 26, 112, 26, 114, 115, 116, 189, 309,
+ /* 1570 */ 119, 23, 19, 20, 26, 22, 189, 211, 212, 131,
+ /* 1580 */ 99, 189, 211, 212, 136, 137, 105, 106, 189, 36,
+ /* 1590 */ 211, 212, 189, 112, 189, 114, 115, 116, 211, 212,
+ /* 1600 */ 119, 150, 151, 152, 153, 154, 189, 159, 23, 250,
+ /* 1610 */ 189, 26, 59, 189, 189, 189, 189, 189, 280, 189,
+ /* 1620 */ 250, 189, 189, 238, 71, 189, 189, 250, 211, 212,
+ /* 1630 */ 187, 150, 151, 152, 153, 154, 211, 212, 250, 290,
+ /* 1640 */ 240, 211, 212, 211, 212, 254, 286, 209, 254, 241,
+ /* 1650 */ 240, 254, 99, 286, 215, 220, 214, 244, 105, 106,
+ /* 1660 */ 214, 214, 244, 273, 224, 112, 192, 114, 115, 116,
+ /* 1670 */ 60, 290, 119, 5, 139, 196, 196, 38, 10, 11,
+ /* 1680 */ 12, 13, 14, 238, 240, 17, 196, 148, 287, 287,
+ /* 1690 */ 276, 113, 22, 147, 241, 43, 229, 241, 30, 18,
+ /* 1700 */ 32, 232, 232, 150, 151, 152, 153, 154, 40, 232,
+ /* 1710 */ 232, 196, 18, 195, 265, 265, 264, 241, 264, 196,
+ /* 1720 */ 155, 229, 229, 241, 241, 241, 195, 62, 196, 195,
+ /* 1730 */ 22, 113, 216, 196, 222, 195, 195, 282, 70, 196,
+ /* 1740 */ 283, 213, 216, 213, 64, 22, 78, 124, 219, 81,
+ /* 1750 */ 162, 111, 219, 142, 256, 213, 113, 255, 213, 256,
+ /* 1760 */ 216, 303, 215, 213, 213, 97, 255, 213, 216, 275,
+ /* 1770 */ 275, 222, 216, 256, 255, 196, 91, 82, 256, 255,
+ /* 1780 */ 308, 308, 146, 22, 143, 196, 155, 260, 25, 145,
+ /* 1790 */ 144, 199, 26, 198, 13, 190, 190, 6, 293, 131,
+ /* 1800 */ 188, 188, 245, 244, 136, 137, 245, 243, 242, 241,
+ /* 1810 */ 188, 202, 208, 217, 217, 260, 208, 4, 202, 3,
+ /* 1820 */ 22, 202, 208, 208, 160, 15, 209, 159, 270, 209,
+ /* 1830 */ 98, 16, 272, 208, 23, 23, 137, 148, 128, 20,
+ /* 1840 */ 140, 24, 16, 142, 1, 140, 149, 128, 61, 53,
+ /* 1850 */ 148, 37, 53, 53, 53, 128, 114, 34, 296, 296,
+ /* 1860 */ 139, 1, 5, 22, 113, 158, 26, 75, 41, 139,
+ /* 1870 */ 68, 68, 113, 24, 20, 19, 129, 123, 23, 96,
+ /* 1880 */ 22, 22, 37, 22, 22, 67, 22, 67, 59, 24,
+ /* 1890 */ 23, 28, 67, 147, 22, 26, 23, 23, 23, 23,
+ /* 1900 */ 22, 24, 23, 22, 24, 23, 139, 23, 114, 22,
+ /* 1910 */ 141, 26, 88, 75, 86, 44, 23, 34, 22, 75,
+ /* 1920 */ 34, 24, 34, 34, 34, 93, 34, 26, 26, 34,
+ /* 1930 */ 23, 23, 23, 23, 23, 11, 23, 22, 26, 22,
+ /* 1940 */ 22, 133, 23, 23, 22, 22, 139, 26, 139, 23,
+ /* 1950 */ 15, 1, 1, 310, 310, 310, 310, 310, 310, 310,
+ /* 1960 */ 139, 139, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 1970 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 1980 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 1990 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2000 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2010 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2020 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2030 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2040 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2050 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2060 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2070 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2080 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2090 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2100 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2110 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2120 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2130 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
+ /* 2140 */ 310, 310, 310,
+};
+#define YY_SHIFT_COUNT (552)
+#define YY_SHIFT_MIN (0)
+#define YY_SHIFT_MAX (1951)
+static const unsigned short int yy_shift_ofst[] = {
+ /* 0 */ 1448, 1277, 1668, 1072, 1072, 340, 1122, 1225, 1332, 1481,
+ /* 10 */ 1481, 1481, 335, 0, 0, 180, 897, 1481, 1481, 1481,
+ /* 20 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
+ /* 30 */ 930, 930, 1020, 1020, 290, 1, 340, 340, 340, 340,
+ /* 40 */ 340, 340, 40, 110, 219, 288, 327, 396, 435, 504,
+ /* 50 */ 543, 612, 651, 720, 877, 897, 897, 897, 897, 897,
+ /* 60 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
+ /* 70 */ 897, 897, 897, 917, 897, 1019, 763, 763, 1451, 1481,
+ /* 80 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
+ /* 90 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
+ /* 100 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
+ /* 110 */ 1481, 1481, 1553, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
+ /* 120 */ 1481, 1481, 1481, 1481, 1481, 1481, 147, 258, 258, 258,
+ /* 130 */ 258, 258, 79, 65, 84, 449, 19, 786, 449, 636,
+ /* 140 */ 636, 449, 880, 880, 880, 880, 113, 142, 142, 472,
+ /* 150 */ 150, 1962, 1962, 399, 399, 399, 93, 237, 341, 237,
+ /* 160 */ 237, 1074, 1074, 437, 350, 704, 1080, 449, 449, 449,
+ /* 170 */ 449, 449, 449, 449, 449, 449, 449, 449, 449, 449,
+ /* 180 */ 449, 449, 449, 449, 449, 449, 449, 449, 818, 818,
+ /* 190 */ 449, 1088, 217, 217, 734, 734, 1124, 1126, 1962, 1962,
+ /* 200 */ 1962, 739, 840, 840, 453, 454, 511, 187, 563, 570,
+ /* 210 */ 898, 669, 449, 449, 449, 449, 449, 449, 449, 449,
+ /* 220 */ 449, 670, 449, 449, 449, 449, 449, 449, 449, 449,
+ /* 230 */ 449, 449, 449, 449, 674, 674, 674, 449, 449, 449,
+ /* 240 */ 449, 1034, 449, 449, 449, 972, 1107, 449, 449, 1193,
+ /* 250 */ 449, 449, 449, 449, 449, 449, 449, 449, 260, 177,
+ /* 260 */ 489, 1241, 1241, 1241, 1241, 1192, 489, 489, 952, 1197,
+ /* 270 */ 625, 1235, 1131, 181, 181, 1086, 1139, 1131, 1086, 1187,
+ /* 280 */ 1319, 1237, 1318, 1318, 1318, 181, 1299, 1299, 1109, 1336,
+ /* 290 */ 549, 1376, 1610, 1535, 1535, 1639, 1639, 1535, 1539, 1578,
+ /* 300 */ 1670, 1546, 1652, 1546, 1681, 1681, 1681, 1681, 1535, 1694,
+ /* 310 */ 1546, 1546, 1578, 1670, 1652, 1546, 1652, 1546, 1535, 1694,
+ /* 320 */ 1565, 1665, 1535, 1694, 1708, 1535, 1694, 1535, 1694, 1708,
+ /* 330 */ 1618, 1618, 1618, 1680, 1723, 1723, 1708, 1618, 1623, 1618,
+ /* 340 */ 1680, 1618, 1618, 1588, 1708, 1640, 1640, 1708, 1611, 1643,
+ /* 350 */ 1611, 1643, 1611, 1643, 1611, 1643, 1535, 1685, 1685, 1695,
+ /* 360 */ 1695, 1636, 1641, 1761, 1535, 1631, 1636, 1644, 1646, 1546,
+ /* 370 */ 1763, 1766, 1781, 1781, 1791, 1791, 1791, 1962, 1962, 1962,
+ /* 380 */ 1962, 1962, 1962, 1962, 1962, 1962, 1962, 1962, 1962, 1962,
+ /* 390 */ 1962, 1962, 308, 835, 954, 1232, 879, 715, 728, 1373,
+ /* 400 */ 864, 1329, 1253, 1409, 297, 1431, 1489, 1497, 1520, 1521,
+ /* 410 */ 1525, 1362, 1309, 1491, 1217, 1420, 1429, 1536, 1380, 1538,
+ /* 420 */ 1293, 1354, 1548, 1585, 1434, 1342, 1813, 1816, 1798, 1664,
+ /* 430 */ 1810, 1732, 1815, 1811, 1812, 1699, 1689, 1710, 1817, 1700,
+ /* 440 */ 1819, 1701, 1826, 1843, 1705, 1697, 1719, 1787, 1814, 1702,
+ /* 450 */ 1796, 1799, 1800, 1801, 1727, 1742, 1823, 1721, 1860, 1857,
+ /* 460 */ 1841, 1751, 1707, 1802, 1840, 1803, 1792, 1827, 1730, 1759,
+ /* 470 */ 1849, 1854, 1856, 1747, 1754, 1858, 1818, 1859, 1861, 1855,
+ /* 480 */ 1862, 1820, 1829, 1865, 1783, 1863, 1864, 1825, 1845, 1867,
+ /* 490 */ 1746, 1872, 1873, 1874, 1875, 1869, 1876, 1878, 1877, 1879,
+ /* 500 */ 1881, 1880, 1767, 1882, 1884, 1794, 1883, 1887, 1769, 1885,
+ /* 510 */ 1886, 1888, 1889, 1890, 1824, 1838, 1828, 1871, 1844, 1832,
+ /* 520 */ 1892, 1893, 1896, 1897, 1901, 1902, 1895, 1907, 1885, 1908,
+ /* 530 */ 1909, 1910, 1911, 1912, 1913, 1915, 1924, 1917, 1918, 1919,
+ /* 540 */ 1920, 1922, 1923, 1921, 1808, 1807, 1809, 1821, 1822, 1926,
+ /* 550 */ 1935, 1950, 1951,
+};
+#define YY_REDUCE_COUNT (391)
+#define YY_REDUCE_MIN (-262)
+#define YY_REDUCE_MAX (1625)
+static const short yy_reduce_ofst[] = {
+ /* 0 */ 490, -122, 545, 645, 650, -120, -189, -187, -184, -182,
+ /* 10 */ -178, -176, 45, 30, 200, -251, -134, 390, 392, 521,
+ /* 20 */ 523, 213, 692, 821, 284, 589, 872, 666, 671, 866,
+ /* 30 */ 71, 111, 273, 389, 686, 815, 904, 932, 948, 955,
+ /* 40 */ 964, 969, -259, -259, -259, -259, -259, -259, -259, -259,
+ /* 50 */ -259, -259, -259, -259, -259, -259, -259, -259, -259, -259,
+ /* 60 */ -259, -259, -259, -259, -259, -259, -259, -259, -259, -259,
+ /* 70 */ -259, -259, -259, -259, -259, -259, -259, -259, 428, 430,
+ /* 80 */ 899, 985, 1021, 1028, 1057, 1069, 1081, 1108, 1110, 1115,
+ /* 90 */ 1117, 1123, 1149, 1154, 1159, 1170, 1174, 1178, 1183, 1194,
+ /* 100 */ 1198, 1204, 1208, 1212, 1218, 1222, 1229, 1278, 1280, 1283,
+ /* 110 */ 1285, 1313, 1316, 1320, 1322, 1325, 1327, 1330, 1366, 1371,
+ /* 120 */ 1379, 1387, 1417, 1425, 1430, 1432, -259, -259, -259, -259,
+ /* 130 */ -259, -259, -259, -259, -259, 557, 974, -214, -174, -9,
+ /* 140 */ 431, -124, 806, 925, 806, 925, 251, 928, 940, -259,
+ /* 150 */ -259, -259, -259, -198, -198, -198, 127, -186, -168, 212,
+ /* 160 */ 646, 617, 799, -262, 555, 220, 220, 491, 605, 1040,
+ /* 170 */ 1060, 699, -11, 600, 848, 862, 345, -129, 724, -91,
+ /* 180 */ 158, 749, 716, 900, 304, 822, 929, 926, 499, 793,
+ /* 190 */ 322, 892, 813, 845, 958, 1056, 751, 905, 1133, 1062,
+ /* 200 */ 803, -210, -185, -179, -148, -167, -89, 121, 274, 281,
+ /* 210 */ 320, 336, 439, 663, 711, 957, 965, 1064, 1068, 1112,
+ /* 220 */ 1116, -196, 1127, 1134, 1180, 1184, 1195, 1199, 1203, 1215,
+ /* 230 */ 1223, 1250, 1267, 1286, 205, 422, 638, 1324, 1341, 1364,
+ /* 240 */ 1365, 1213, 1392, 1399, 1403, 869, 1260, 1405, 1421, 1276,
+ /* 250 */ 1424, 121, 1426, 1427, 1428, 1433, 1436, 1437, 1227, 1338,
+ /* 260 */ 1284, 1359, 1370, 1377, 1388, 1213, 1284, 1284, 1385, 1438,
+ /* 270 */ 1443, 1349, 1400, 1391, 1394, 1360, 1408, 1410, 1367, 1439,
+ /* 280 */ 1440, 1435, 1442, 1446, 1447, 1397, 1413, 1418, 1390, 1444,
+ /* 290 */ 1445, 1474, 1381, 1479, 1480, 1401, 1402, 1490, 1414, 1449,
+ /* 300 */ 1452, 1453, 1467, 1456, 1469, 1470, 1477, 1478, 1515, 1518,
+ /* 310 */ 1476, 1482, 1450, 1454, 1492, 1483, 1493, 1484, 1523, 1531,
+ /* 320 */ 1457, 1455, 1532, 1534, 1516, 1537, 1540, 1543, 1541, 1526,
+ /* 330 */ 1528, 1530, 1542, 1512, 1529, 1533, 1544, 1545, 1547, 1550,
+ /* 340 */ 1549, 1551, 1554, 1458, 1552, 1494, 1495, 1556, 1498, 1502,
+ /* 350 */ 1503, 1511, 1517, 1519, 1522, 1524, 1579, 1472, 1473, 1527,
+ /* 360 */ 1555, 1557, 1559, 1558, 1589, 1560, 1561, 1564, 1566, 1568,
+ /* 370 */ 1592, 1595, 1605, 1606, 1612, 1613, 1622, 1562, 1563, 1505,
+ /* 380 */ 1609, 1604, 1608, 1614, 1615, 1616, 1596, 1597, 1617, 1620,
+ /* 390 */ 1625, 1619,
+};
+static const YYACTIONTYPE yy_default[] = {
+ /* 0 */ 1575, 1575, 1575, 1411, 1188, 1297, 1188, 1188, 1188, 1411,
+ /* 10 */ 1411, 1411, 1188, 1327, 1327, 1464, 1219, 1188, 1188, 1188,
+ /* 20 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1410, 1188, 1188,
+ /* 30 */ 1188, 1188, 1494, 1494, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 40 */ 1188, 1188, 1188, 1336, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 50 */ 1412, 1413, 1188, 1188, 1188, 1463, 1465, 1428, 1346, 1345,
+ /* 60 */ 1344, 1343, 1446, 1314, 1341, 1334, 1338, 1406, 1407, 1405,
+ /* 70 */ 1409, 1413, 1412, 1188, 1337, 1377, 1391, 1376, 1188, 1188,
+ /* 80 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 90 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 100 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 110 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 120 */ 1188, 1188, 1188, 1188, 1188, 1188, 1385, 1390, 1396, 1389,
+ /* 130 */ 1386, 1379, 1378, 1380, 1381, 1188, 1209, 1261, 1188, 1188,
+ /* 140 */ 1188, 1188, 1482, 1481, 1188, 1188, 1219, 1371, 1370, 1382,
+ /* 150 */ 1383, 1393, 1392, 1471, 1529, 1528, 1429, 1188, 1188, 1188,
+ /* 160 */ 1188, 1188, 1188, 1494, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 170 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 180 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1494, 1494,
+ /* 190 */ 1188, 1219, 1494, 1494, 1215, 1215, 1321, 1188, 1477, 1297,
+ /* 200 */ 1288, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 210 */ 1188, 1188, 1188, 1188, 1188, 1468, 1466, 1188, 1188, 1188,
+ /* 220 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 230 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 240 */ 1188, 1188, 1188, 1188, 1188, 1293, 1188, 1188, 1188, 1188,
+ /* 250 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1523, 1188, 1441,
+ /* 260 */ 1275, 1293, 1293, 1293, 1293, 1295, 1276, 1274, 1287, 1220,
+ /* 270 */ 1195, 1567, 1294, 1316, 1316, 1564, 1340, 1294, 1564, 1236,
+ /* 280 */ 1545, 1231, 1327, 1327, 1327, 1316, 1321, 1321, 1408, 1294,
+ /* 290 */ 1287, 1188, 1567, 1302, 1302, 1566, 1566, 1302, 1429, 1349,
+ /* 300 */ 1355, 1340, 1264, 1340, 1270, 1270, 1270, 1270, 1302, 1206,
+ /* 310 */ 1340, 1340, 1349, 1355, 1264, 1340, 1264, 1340, 1302, 1206,
+ /* 320 */ 1445, 1561, 1302, 1206, 1419, 1302, 1206, 1302, 1206, 1419,
+ /* 330 */ 1262, 1262, 1262, 1251, 1188, 1188, 1419, 1262, 1236, 1262,
+ /* 340 */ 1251, 1262, 1262, 1512, 1419, 1423, 1423, 1419, 1320, 1315,
+ /* 350 */ 1320, 1315, 1320, 1315, 1320, 1315, 1302, 1504, 1504, 1330,
+ /* 360 */ 1330, 1335, 1321, 1414, 1302, 1188, 1335, 1333, 1331, 1340,
+ /* 370 */ 1212, 1254, 1526, 1526, 1522, 1522, 1522, 1572, 1572, 1477,
+ /* 380 */ 1538, 1219, 1219, 1219, 1219, 1538, 1238, 1238, 1220, 1220,
+ /* 390 */ 1219, 1538, 1188, 1188, 1188, 1188, 1188, 1188, 1533, 1188,
+ /* 400 */ 1430, 1306, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 410 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 420 */ 1188, 1188, 1188, 1188, 1188, 1360, 1188, 1191, 1474, 1188,
+ /* 430 */ 1188, 1472, 1188, 1188, 1188, 1188, 1188, 1188, 1307, 1188,
+ /* 440 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 450 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1563, 1188, 1188,
+ /* 460 */ 1188, 1188, 1188, 1188, 1444, 1443, 1188, 1188, 1304, 1188,
+ /* 470 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 480 */ 1188, 1188, 1234, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 490 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 500 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1332,
+ /* 510 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 520 */ 1188, 1188, 1188, 1188, 1509, 1322, 1188, 1188, 1554, 1188,
+ /* 530 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188,
+ /* 540 */ 1188, 1188, 1188, 1549, 1278, 1362, 1188, 1361, 1365, 1188,
+ /* 550 */ 1200, 1188, 1188,
+};
+/********** End of lemon-generated parsing tables *****************************/
+
+/* The next table maps tokens (terminal symbols) into fallback tokens.
+** If a construct like the following:
+**
+** %fallback ID X Y Z.
+**
+** appears in the grammar, then ID becomes a fallback token for X, Y,
+** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
+** but it does not parse, the type of the token is changed to ID and
+** the parse is retried before an error is thrown.
+**
+** This feature can be used, for example, to cause some keywords in a language
+** to revert to identifiers if they keyword does not apply in the context where
+** it appears.
+*/
+#ifdef YYFALLBACK
+static const YYCODETYPE yyFallback[] = {
+ 0, /* $ => nothing */
+ 0, /* SEMI => nothing */
+ 59, /* EXPLAIN => ID */
+ 59, /* QUERY => ID */
+ 59, /* PLAN => ID */
+ 59, /* BEGIN => ID */
+ 0, /* TRANSACTION => nothing */
+ 59, /* DEFERRED => ID */
+ 59, /* IMMEDIATE => ID */
+ 59, /* EXCLUSIVE => ID */
+ 0, /* COMMIT => nothing */
+ 59, /* END => ID */
+ 59, /* ROLLBACK => ID */
+ 59, /* SAVEPOINT => ID */
+ 59, /* RELEASE => ID */
+ 0, /* TO => nothing */
+ 0, /* TABLE => nothing */
+ 0, /* CREATE => nothing */
+ 59, /* IF => ID */
+ 0, /* NOT => nothing */
+ 0, /* EXISTS => nothing */
+ 59, /* TEMP => ID */
+ 0, /* LP => nothing */
+ 0, /* RP => nothing */
+ 0, /* AS => nothing */
+ 59, /* WITHOUT => ID */
+ 0, /* COMMA => nothing */
+ 59, /* ABORT => ID */
+ 59, /* ACTION => ID */
+ 59, /* AFTER => ID */
+ 59, /* ANALYZE => ID */
+ 59, /* ASC => ID */
+ 59, /* ATTACH => ID */
+ 59, /* BEFORE => ID */
+ 59, /* BY => ID */
+ 59, /* CASCADE => ID */
+ 59, /* CAST => ID */
+ 59, /* CONFLICT => ID */
+ 59, /* DATABASE => ID */
+ 59, /* DESC => ID */
+ 59, /* DETACH => ID */
+ 59, /* EACH => ID */
+ 59, /* FAIL => ID */
+ 0, /* OR => nothing */
+ 0, /* AND => nothing */
+ 0, /* IS => nothing */
+ 59, /* MATCH => ID */
+ 59, /* LIKE_KW => ID */
+ 0, /* BETWEEN => nothing */
+ 0, /* IN => nothing */
+ 0, /* ISNULL => nothing */
+ 0, /* NOTNULL => nothing */
+ 0, /* NE => nothing */
+ 0, /* EQ => nothing */
+ 0, /* GT => nothing */
+ 0, /* LE => nothing */
+ 0, /* LT => nothing */
+ 0, /* GE => nothing */
+ 0, /* ESCAPE => nothing */
+ 0, /* ID => nothing */
+ 59, /* COLUMNKW => ID */
+ 59, /* DO => ID */
+ 59, /* FOR => ID */
+ 59, /* IGNORE => ID */
+ 59, /* INITIALLY => ID */
+ 59, /* INSTEAD => ID */
+ 59, /* NO => ID */
+ 59, /* KEY => ID */
+ 59, /* OF => ID */
+ 59, /* OFFSET => ID */
+ 59, /* PRAGMA => ID */
+ 59, /* RAISE => ID */
+ 59, /* RECURSIVE => ID */
+ 59, /* REPLACE => ID */
+ 59, /* RESTRICT => ID */
+ 59, /* ROW => ID */
+ 59, /* ROWS => ID */
+ 59, /* TRIGGER => ID */
+ 59, /* VACUUM => ID */
+ 59, /* VIEW => ID */
+ 59, /* VIRTUAL => ID */
+ 59, /* WITH => ID */
+ 59, /* NULLS => ID */
+ 59, /* FIRST => ID */
+ 59, /* LAST => ID */
+ 59, /* CURRENT => ID */
+ 59, /* FOLLOWING => ID */
+ 59, /* PARTITION => ID */
+ 59, /* PRECEDING => ID */
+ 59, /* RANGE => ID */
+ 59, /* UNBOUNDED => ID */
+ 59, /* EXCLUDE => ID */
+ 59, /* GROUPS => ID */
+ 59, /* OTHERS => ID */
+ 59, /* TIES => ID */
+ 59, /* GENERATED => ID */
+ 59, /* ALWAYS => ID */
+ 59, /* REINDEX => ID */
+ 59, /* RENAME => ID */
+ 59, /* CTIME_KW => ID */
+ 0, /* ANY => nothing */
+ 0, /* BITAND => nothing */
+ 0, /* BITOR => nothing */
+ 0, /* LSHIFT => nothing */
+ 0, /* RSHIFT => nothing */
+ 0, /* PLUS => nothing */
+ 0, /* MINUS => nothing */
+ 0, /* STAR => nothing */
+ 0, /* SLASH => nothing */
+ 0, /* REM => nothing */
+ 0, /* CONCAT => nothing */
+ 0, /* COLLATE => nothing */
+ 0, /* BITNOT => nothing */
+ 0, /* ON => nothing */
+ 0, /* INDEXED => nothing */
+ 0, /* STRING => nothing */
+ 0, /* JOIN_KW => nothing */
+ 0, /* CONSTRAINT => nothing */
+ 0, /* DEFAULT => nothing */
+ 0, /* NULL => nothing */
+ 0, /* PRIMARY => nothing */
+ 0, /* UNIQUE => nothing */
+ 0, /* CHECK => nothing */
+ 0, /* REFERENCES => nothing */
+ 0, /* AUTOINCR => nothing */
+ 0, /* INSERT => nothing */
+ 0, /* DELETE => nothing */
+ 0, /* UPDATE => nothing */
+ 0, /* SET => nothing */
+ 0, /* DEFERRABLE => nothing */
+ 0, /* FOREIGN => nothing */
+ 0, /* DROP => nothing */
+ 0, /* UNION => nothing */
+ 0, /* ALL => nothing */
+ 0, /* EXCEPT => nothing */
+ 0, /* INTERSECT => nothing */
+ 0, /* SELECT => nothing */
+ 0, /* VALUES => nothing */
+ 0, /* DISTINCT => nothing */
+ 0, /* DOT => nothing */
+ 0, /* FROM => nothing */
+ 0, /* JOIN => nothing */
+ 0, /* USING => nothing */
+ 0, /* ORDER => nothing */
+ 0, /* GROUP => nothing */
+ 0, /* HAVING => nothing */
+ 0, /* LIMIT => nothing */
+ 0, /* WHERE => nothing */
+ 0, /* INTO => nothing */
+ 0, /* NOTHING => nothing */
+ 0, /* FLOAT => nothing */
+ 0, /* BLOB => nothing */
+ 0, /* INTEGER => nothing */
+ 0, /* VARIABLE => nothing */
+ 0, /* CASE => nothing */
+ 0, /* WHEN => nothing */
+ 0, /* THEN => nothing */
+ 0, /* ELSE => nothing */
+ 0, /* INDEX => nothing */
+ 0, /* ALTER => nothing */
+ 0, /* ADD => nothing */
+ 0, /* WINDOW => nothing */
+ 0, /* OVER => nothing */
+ 0, /* FILTER => nothing */
+ 0, /* COLUMN => nothing */
+ 0, /* AGG_FUNCTION => nothing */
+ 0, /* AGG_COLUMN => nothing */
+ 0, /* TRUEFALSE => nothing */
+ 0, /* ISNOT => nothing */
+ 0, /* FUNCTION => nothing */
+ 0, /* UMINUS => nothing */
+ 0, /* UPLUS => nothing */
+ 0, /* TRUTH => nothing */
+ 0, /* REGISTER => nothing */
+ 0, /* VECTOR => nothing */
+ 0, /* SELECT_COLUMN => nothing */
+ 0, /* IF_NULL_ROW => nothing */
+ 0, /* ASTERISK => nothing */
+ 0, /* SPAN => nothing */
+ 0, /* SPACE => nothing */
+ 0, /* ILLEGAL => nothing */
+};
+#endif /* YYFALLBACK */
+
+/* The following structure represents a single element of the
+** parser's stack. Information stored includes:
+**
+** + The state number for the parser at this level of the stack.
+**
+** + The value of the token stored at this level of the stack.
+** (In other words, the "major" token.)
+**
+** + The semantic value stored at this level of the stack. This is
+** the information used by the action routines in the grammar.
+** It is sometimes called the "minor" token.
+**
+** After the "shift" half of a SHIFTREDUCE action, the stateno field
+** actually contains the reduce action for the second half of the
+** SHIFTREDUCE.
+*/
+struct yyStackEntry {
+ YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
+ YYCODETYPE major; /* The major token value. This is the code
+ ** number for the token at this stack level */
+ YYMINORTYPE minor; /* The user-supplied minor token value. This
+ ** is the value of the token */
+};
+typedef struct yyStackEntry yyStackEntry;
+
+/* The state of the parser is completely contained in an instance of
+** the following structure */
+struct yyParser {
+ yyStackEntry *yytos; /* Pointer to top element of the stack */
+#ifdef YYTRACKMAXSTACKDEPTH
+ int yyhwm; /* High-water mark of the stack */
+#endif
+#ifndef YYNOERRORRECOVERY
+ int yyerrcnt; /* Shifts left before out of the error */
+#endif
+ sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
+ sqlite3ParserCTX_SDECL /* A place to hold %extra_context */
+#if YYSTACKDEPTH<=0
+ int yystksz; /* Current side of the stack */
+ yyStackEntry *yystack; /* The parser's stack */
+ yyStackEntry yystk0; /* First stack entry */
+#else
+ yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
+ yyStackEntry *yystackEnd; /* Last entry in the stack */
+#endif
+};
+typedef struct yyParser yyParser;
+
+#ifndef NDEBUG
+/* #include <stdio.h> */
+/* #include <assert.h> */
+static FILE *yyTraceFILE = 0;
+static char *yyTracePrompt = 0;
+#endif /* NDEBUG */
+
+#ifndef NDEBUG
+/*
+** Turn parser tracing on by giving a stream to which to write the trace
+** and a prompt to preface each trace message. Tracing is turned off
+** by making either argument NULL
+**
+** Inputs:
+** <ul>
+** <li> A FILE* to which trace output should be written.
+** If NULL, then tracing is turned off.
+** <li> A prefix string written at the beginning of every
+** line of trace output. If NULL, then tracing is
+** turned off.
+** </ul>
+**
+** Outputs:
+** None.
+*/
+SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
+ yyTraceFILE = TraceFILE;
+ yyTracePrompt = zTracePrompt;
+ if( yyTraceFILE==0 ) yyTracePrompt = 0;
+ else if( yyTracePrompt==0 ) yyTraceFILE = 0;
+}
+#endif /* NDEBUG */
+
+#if defined(YYCOVERAGE) || !defined(NDEBUG)
+/* For tracing shifts, the names of all terminals and nonterminals
+** are required. The following table supplies these names */
+static const char *const yyTokenName[] = {
+ /* 0 */ "$",
+ /* 1 */ "SEMI",
+ /* 2 */ "EXPLAIN",
+ /* 3 */ "QUERY",
+ /* 4 */ "PLAN",
+ /* 5 */ "BEGIN",
+ /* 6 */ "TRANSACTION",
+ /* 7 */ "DEFERRED",
+ /* 8 */ "IMMEDIATE",
+ /* 9 */ "EXCLUSIVE",
+ /* 10 */ "COMMIT",
+ /* 11 */ "END",
+ /* 12 */ "ROLLBACK",
+ /* 13 */ "SAVEPOINT",
+ /* 14 */ "RELEASE",
+ /* 15 */ "TO",
+ /* 16 */ "TABLE",
+ /* 17 */ "CREATE",
+ /* 18 */ "IF",
+ /* 19 */ "NOT",
+ /* 20 */ "EXISTS",
+ /* 21 */ "TEMP",
+ /* 22 */ "LP",
+ /* 23 */ "RP",
+ /* 24 */ "AS",
+ /* 25 */ "WITHOUT",
+ /* 26 */ "COMMA",
+ /* 27 */ "ABORT",
+ /* 28 */ "ACTION",
+ /* 29 */ "AFTER",
+ /* 30 */ "ANALYZE",
+ /* 31 */ "ASC",
+ /* 32 */ "ATTACH",
+ /* 33 */ "BEFORE",
+ /* 34 */ "BY",
+ /* 35 */ "CASCADE",
+ /* 36 */ "CAST",
+ /* 37 */ "CONFLICT",
+ /* 38 */ "DATABASE",
+ /* 39 */ "DESC",
+ /* 40 */ "DETACH",
+ /* 41 */ "EACH",
+ /* 42 */ "FAIL",
+ /* 43 */ "OR",
+ /* 44 */ "AND",
+ /* 45 */ "IS",
+ /* 46 */ "MATCH",
+ /* 47 */ "LIKE_KW",
+ /* 48 */ "BETWEEN",
+ /* 49 */ "IN",
+ /* 50 */ "ISNULL",
+ /* 51 */ "NOTNULL",
+ /* 52 */ "NE",
+ /* 53 */ "EQ",
+ /* 54 */ "GT",
+ /* 55 */ "LE",
+ /* 56 */ "LT",
+ /* 57 */ "GE",
+ /* 58 */ "ESCAPE",
+ /* 59 */ "ID",
+ /* 60 */ "COLUMNKW",
+ /* 61 */ "DO",
+ /* 62 */ "FOR",
+ /* 63 */ "IGNORE",
+ /* 64 */ "INITIALLY",
+ /* 65 */ "INSTEAD",
+ /* 66 */ "NO",
+ /* 67 */ "KEY",
+ /* 68 */ "OF",
+ /* 69 */ "OFFSET",
+ /* 70 */ "PRAGMA",
+ /* 71 */ "RAISE",
+ /* 72 */ "RECURSIVE",
+ /* 73 */ "REPLACE",
+ /* 74 */ "RESTRICT",
+ /* 75 */ "ROW",
+ /* 76 */ "ROWS",
+ /* 77 */ "TRIGGER",
+ /* 78 */ "VACUUM",
+ /* 79 */ "VIEW",
+ /* 80 */ "VIRTUAL",
+ /* 81 */ "WITH",
+ /* 82 */ "NULLS",
+ /* 83 */ "FIRST",
+ /* 84 */ "LAST",
+ /* 85 */ "CURRENT",
+ /* 86 */ "FOLLOWING",
+ /* 87 */ "PARTITION",
+ /* 88 */ "PRECEDING",
+ /* 89 */ "RANGE",
+ /* 90 */ "UNBOUNDED",
+ /* 91 */ "EXCLUDE",
+ /* 92 */ "GROUPS",
+ /* 93 */ "OTHERS",
+ /* 94 */ "TIES",
+ /* 95 */ "GENERATED",
+ /* 96 */ "ALWAYS",
+ /* 97 */ "REINDEX",
+ /* 98 */ "RENAME",
+ /* 99 */ "CTIME_KW",
+ /* 100 */ "ANY",
+ /* 101 */ "BITAND",
+ /* 102 */ "BITOR",
+ /* 103 */ "LSHIFT",
+ /* 104 */ "RSHIFT",
+ /* 105 */ "PLUS",
+ /* 106 */ "MINUS",
+ /* 107 */ "STAR",
+ /* 108 */ "SLASH",
+ /* 109 */ "REM",
+ /* 110 */ "CONCAT",
+ /* 111 */ "COLLATE",
+ /* 112 */ "BITNOT",
+ /* 113 */ "ON",
+ /* 114 */ "INDEXED",
+ /* 115 */ "STRING",
+ /* 116 */ "JOIN_KW",
+ /* 117 */ "CONSTRAINT",
+ /* 118 */ "DEFAULT",
+ /* 119 */ "NULL",
+ /* 120 */ "PRIMARY",
+ /* 121 */ "UNIQUE",
+ /* 122 */ "CHECK",
+ /* 123 */ "REFERENCES",
+ /* 124 */ "AUTOINCR",
+ /* 125 */ "INSERT",
+ /* 126 */ "DELETE",
+ /* 127 */ "UPDATE",
+ /* 128 */ "SET",
+ /* 129 */ "DEFERRABLE",
+ /* 130 */ "FOREIGN",
+ /* 131 */ "DROP",
+ /* 132 */ "UNION",
+ /* 133 */ "ALL",
+ /* 134 */ "EXCEPT",
+ /* 135 */ "INTERSECT",
+ /* 136 */ "SELECT",
+ /* 137 */ "VALUES",
+ /* 138 */ "DISTINCT",
+ /* 139 */ "DOT",
+ /* 140 */ "FROM",
+ /* 141 */ "JOIN",
+ /* 142 */ "USING",
+ /* 143 */ "ORDER",
+ /* 144 */ "GROUP",
+ /* 145 */ "HAVING",
+ /* 146 */ "LIMIT",
+ /* 147 */ "WHERE",
+ /* 148 */ "INTO",
+ /* 149 */ "NOTHING",
+ /* 150 */ "FLOAT",
+ /* 151 */ "BLOB",
+ /* 152 */ "INTEGER",
+ /* 153 */ "VARIABLE",
+ /* 154 */ "CASE",
+ /* 155 */ "WHEN",
+ /* 156 */ "THEN",
+ /* 157 */ "ELSE",
+ /* 158 */ "INDEX",
+ /* 159 */ "ALTER",
+ /* 160 */ "ADD",
+ /* 161 */ "WINDOW",
+ /* 162 */ "OVER",
+ /* 163 */ "FILTER",
+ /* 164 */ "COLUMN",
+ /* 165 */ "AGG_FUNCTION",
+ /* 166 */ "AGG_COLUMN",
+ /* 167 */ "TRUEFALSE",
+ /* 168 */ "ISNOT",
+ /* 169 */ "FUNCTION",
+ /* 170 */ "UMINUS",
+ /* 171 */ "UPLUS",
+ /* 172 */ "TRUTH",
+ /* 173 */ "REGISTER",
+ /* 174 */ "VECTOR",
+ /* 175 */ "SELECT_COLUMN",
+ /* 176 */ "IF_NULL_ROW",
+ /* 177 */ "ASTERISK",
+ /* 178 */ "SPAN",
+ /* 179 */ "SPACE",
+ /* 180 */ "ILLEGAL",
+ /* 181 */ "input",
+ /* 182 */ "cmdlist",
+ /* 183 */ "ecmd",
+ /* 184 */ "cmdx",
+ /* 185 */ "explain",
+ /* 186 */ "cmd",
+ /* 187 */ "transtype",
+ /* 188 */ "trans_opt",
+ /* 189 */ "nm",
+ /* 190 */ "savepoint_opt",
+ /* 191 */ "create_table",
+ /* 192 */ "create_table_args",
+ /* 193 */ "createkw",
+ /* 194 */ "temp",
+ /* 195 */ "ifnotexists",
+ /* 196 */ "dbnm",
+ /* 197 */ "columnlist",
+ /* 198 */ "conslist_opt",
+ /* 199 */ "table_options",
+ /* 200 */ "select",
+ /* 201 */ "columnname",
+ /* 202 */ "carglist",
+ /* 203 */ "typetoken",
+ /* 204 */ "typename",
+ /* 205 */ "signed",
+ /* 206 */ "plus_num",
+ /* 207 */ "minus_num",
+ /* 208 */ "scanpt",
+ /* 209 */ "scantok",
+ /* 210 */ "ccons",
+ /* 211 */ "term",
+ /* 212 */ "expr",
+ /* 213 */ "onconf",
+ /* 214 */ "sortorder",
+ /* 215 */ "autoinc",
+ /* 216 */ "eidlist_opt",
+ /* 217 */ "refargs",
+ /* 218 */ "defer_subclause",
+ /* 219 */ "generated",
+ /* 220 */ "refarg",
+ /* 221 */ "refact",
+ /* 222 */ "init_deferred_pred_opt",
+ /* 223 */ "conslist",
+ /* 224 */ "tconscomma",
+ /* 225 */ "tcons",
+ /* 226 */ "sortlist",
+ /* 227 */ "eidlist",
+ /* 228 */ "defer_subclause_opt",
+ /* 229 */ "orconf",
+ /* 230 */ "resolvetype",
+ /* 231 */ "raisetype",
+ /* 232 */ "ifexists",
+ /* 233 */ "fullname",
+ /* 234 */ "selectnowith",
+ /* 235 */ "oneselect",
+ /* 236 */ "wqlist",
+ /* 237 */ "multiselect_op",
+ /* 238 */ "distinct",
+ /* 239 */ "selcollist",
+ /* 240 */ "from",
+ /* 241 */ "where_opt",
+ /* 242 */ "groupby_opt",
+ /* 243 */ "having_opt",
+ /* 244 */ "orderby_opt",
+ /* 245 */ "limit_opt",
+ /* 246 */ "window_clause",
+ /* 247 */ "values",
+ /* 248 */ "nexprlist",
+ /* 249 */ "sclp",
+ /* 250 */ "as",
+ /* 251 */ "seltablist",
+ /* 252 */ "stl_prefix",
+ /* 253 */ "joinop",
+ /* 254 */ "indexed_opt",
+ /* 255 */ "on_opt",
+ /* 256 */ "using_opt",
+ /* 257 */ "exprlist",
+ /* 258 */ "xfullname",
+ /* 259 */ "idlist",
+ /* 260 */ "nulls",
+ /* 261 */ "with",
+ /* 262 */ "setlist",
+ /* 263 */ "insert_cmd",
+ /* 264 */ "idlist_opt",
+ /* 265 */ "upsert",
+ /* 266 */ "filter_over",
+ /* 267 */ "likeop",
+ /* 268 */ "between_op",
+ /* 269 */ "in_op",
+ /* 270 */ "paren_exprlist",
+ /* 271 */ "case_operand",
+ /* 272 */ "case_exprlist",
+ /* 273 */ "case_else",
+ /* 274 */ "uniqueflag",
+ /* 275 */ "collate",
+ /* 276 */ "vinto",
+ /* 277 */ "nmnum",
+ /* 278 */ "trigger_decl",
+ /* 279 */ "trigger_cmd_list",
+ /* 280 */ "trigger_time",
+ /* 281 */ "trigger_event",
+ /* 282 */ "foreach_clause",
+ /* 283 */ "when_clause",
+ /* 284 */ "trigger_cmd",
+ /* 285 */ "trnm",
+ /* 286 */ "tridxby",
+ /* 287 */ "database_kw_opt",
+ /* 288 */ "key_opt",
+ /* 289 */ "add_column_fullname",
+ /* 290 */ "kwcolumn_opt",
+ /* 291 */ "create_vtab",
+ /* 292 */ "vtabarglist",
+ /* 293 */ "vtabarg",
+ /* 294 */ "vtabargtoken",
+ /* 295 */ "lp",
+ /* 296 */ "anylist",
+ /* 297 */ "windowdefn_list",
+ /* 298 */ "windowdefn",
+ /* 299 */ "window",
+ /* 300 */ "frame_opt",
+ /* 301 */ "part_opt",
+ /* 302 */ "filter_clause",
+ /* 303 */ "over_clause",
+ /* 304 */ "range_or_rows",
+ /* 305 */ "frame_bound",
+ /* 306 */ "frame_bound_s",
+ /* 307 */ "frame_bound_e",
+ /* 308 */ "frame_exclude_opt",
+ /* 309 */ "frame_exclude",
+};
+#endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */
+
+#ifndef NDEBUG
+/* For tracing reduce actions, the names of all rules are required.
+*/
+static const char *const yyRuleName[] = {
+ /* 0 */ "explain ::= EXPLAIN",
+ /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
+ /* 2 */ "cmdx ::= cmd",
+ /* 3 */ "cmd ::= BEGIN transtype trans_opt",
+ /* 4 */ "transtype ::=",
+ /* 5 */ "transtype ::= DEFERRED",
+ /* 6 */ "transtype ::= IMMEDIATE",
+ /* 7 */ "transtype ::= EXCLUSIVE",
+ /* 8 */ "cmd ::= COMMIT|END trans_opt",
+ /* 9 */ "cmd ::= ROLLBACK trans_opt",
+ /* 10 */ "cmd ::= SAVEPOINT nm",
+ /* 11 */ "cmd ::= RELEASE savepoint_opt nm",
+ /* 12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
+ /* 13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
+ /* 14 */ "createkw ::= CREATE",
+ /* 15 */ "ifnotexists ::=",
+ /* 16 */ "ifnotexists ::= IF NOT EXISTS",
+ /* 17 */ "temp ::= TEMP",
+ /* 18 */ "temp ::=",
+ /* 19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
+ /* 20 */ "create_table_args ::= AS select",
+ /* 21 */ "table_options ::=",
+ /* 22 */ "table_options ::= WITHOUT nm",
+ /* 23 */ "columnname ::= nm typetoken",
+ /* 24 */ "typetoken ::=",
+ /* 25 */ "typetoken ::= typename LP signed RP",
+ /* 26 */ "typetoken ::= typename LP signed COMMA signed RP",
+ /* 27 */ "typename ::= typename ID|STRING",
+ /* 28 */ "scanpt ::=",
+ /* 29 */ "scantok ::=",
+ /* 30 */ "ccons ::= CONSTRAINT nm",
+ /* 31 */ "ccons ::= DEFAULT scantok term",
+ /* 32 */ "ccons ::= DEFAULT LP expr RP",
+ /* 33 */ "ccons ::= DEFAULT PLUS scantok term",
+ /* 34 */ "ccons ::= DEFAULT MINUS scantok term",
+ /* 35 */ "ccons ::= DEFAULT scantok ID|INDEXED",
+ /* 36 */ "ccons ::= NOT NULL onconf",
+ /* 37 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
+ /* 38 */ "ccons ::= UNIQUE onconf",
+ /* 39 */ "ccons ::= CHECK LP expr RP",
+ /* 40 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
+ /* 41 */ "ccons ::= defer_subclause",
+ /* 42 */ "ccons ::= COLLATE ID|STRING",
+ /* 43 */ "generated ::= LP expr RP",
+ /* 44 */ "generated ::= LP expr RP ID",
+ /* 45 */ "autoinc ::=",
+ /* 46 */ "autoinc ::= AUTOINCR",
+ /* 47 */ "refargs ::=",
+ /* 48 */ "refargs ::= refargs refarg",
+ /* 49 */ "refarg ::= MATCH nm",
+ /* 50 */ "refarg ::= ON INSERT refact",
+ /* 51 */ "refarg ::= ON DELETE refact",
+ /* 52 */ "refarg ::= ON UPDATE refact",
+ /* 53 */ "refact ::= SET NULL",
+ /* 54 */ "refact ::= SET DEFAULT",
+ /* 55 */ "refact ::= CASCADE",
+ /* 56 */ "refact ::= RESTRICT",
+ /* 57 */ "refact ::= NO ACTION",
+ /* 58 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
+ /* 59 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
+ /* 60 */ "init_deferred_pred_opt ::=",
+ /* 61 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
+ /* 62 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
+ /* 63 */ "conslist_opt ::=",
+ /* 64 */ "tconscomma ::= COMMA",
+ /* 65 */ "tcons ::= CONSTRAINT nm",
+ /* 66 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
+ /* 67 */ "tcons ::= UNIQUE LP sortlist RP onconf",
+ /* 68 */ "tcons ::= CHECK LP expr RP onconf",
+ /* 69 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
+ /* 70 */ "defer_subclause_opt ::=",
+ /* 71 */ "onconf ::=",
+ /* 72 */ "onconf ::= ON CONFLICT resolvetype",
+ /* 73 */ "orconf ::=",
+ /* 74 */ "orconf ::= OR resolvetype",
+ /* 75 */ "resolvetype ::= IGNORE",
+ /* 76 */ "resolvetype ::= REPLACE",
+ /* 77 */ "cmd ::= DROP TABLE ifexists fullname",
+ /* 78 */ "ifexists ::= IF EXISTS",
+ /* 79 */ "ifexists ::=",
+ /* 80 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
+ /* 81 */ "cmd ::= DROP VIEW ifexists fullname",
+ /* 82 */ "cmd ::= select",
+ /* 83 */ "select ::= WITH wqlist selectnowith",
+ /* 84 */ "select ::= WITH RECURSIVE wqlist selectnowith",
+ /* 85 */ "select ::= selectnowith",
+ /* 86 */ "selectnowith ::= selectnowith multiselect_op oneselect",
+ /* 87 */ "multiselect_op ::= UNION",
+ /* 88 */ "multiselect_op ::= UNION ALL",
+ /* 89 */ "multiselect_op ::= EXCEPT|INTERSECT",
+ /* 90 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
+ /* 91 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt",
+ /* 92 */ "values ::= VALUES LP nexprlist RP",
+ /* 93 */ "values ::= values COMMA LP nexprlist RP",
+ /* 94 */ "distinct ::= DISTINCT",
+ /* 95 */ "distinct ::= ALL",
+ /* 96 */ "distinct ::=",
+ /* 97 */ "sclp ::=",
+ /* 98 */ "selcollist ::= sclp scanpt expr scanpt as",
+ /* 99 */ "selcollist ::= sclp scanpt STAR",
+ /* 100 */ "selcollist ::= sclp scanpt nm DOT STAR",
+ /* 101 */ "as ::= AS nm",
+ /* 102 */ "as ::=",
+ /* 103 */ "from ::=",
+ /* 104 */ "from ::= FROM seltablist",
+ /* 105 */ "stl_prefix ::= seltablist joinop",
+ /* 106 */ "stl_prefix ::=",
+ /* 107 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
+ /* 108 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
+ /* 109 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
+ /* 110 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
+ /* 111 */ "dbnm ::=",
+ /* 112 */ "dbnm ::= DOT nm",
+ /* 113 */ "fullname ::= nm",
+ /* 114 */ "fullname ::= nm DOT nm",
+ /* 115 */ "xfullname ::= nm",
+ /* 116 */ "xfullname ::= nm DOT nm",
+ /* 117 */ "xfullname ::= nm DOT nm AS nm",
+ /* 118 */ "xfullname ::= nm AS nm",
+ /* 119 */ "joinop ::= COMMA|JOIN",
+ /* 120 */ "joinop ::= JOIN_KW JOIN",
+ /* 121 */ "joinop ::= JOIN_KW nm JOIN",
+ /* 122 */ "joinop ::= JOIN_KW nm nm JOIN",
+ /* 123 */ "on_opt ::= ON expr",
+ /* 124 */ "on_opt ::=",
+ /* 125 */ "indexed_opt ::=",
+ /* 126 */ "indexed_opt ::= INDEXED BY nm",
+ /* 127 */ "indexed_opt ::= NOT INDEXED",
+ /* 128 */ "using_opt ::= USING LP idlist RP",
+ /* 129 */ "using_opt ::=",
+ /* 130 */ "orderby_opt ::=",
+ /* 131 */ "orderby_opt ::= ORDER BY sortlist",
+ /* 132 */ "sortlist ::= sortlist COMMA expr sortorder nulls",
+ /* 133 */ "sortlist ::= expr sortorder nulls",
+ /* 134 */ "sortorder ::= ASC",
+ /* 135 */ "sortorder ::= DESC",
+ /* 136 */ "sortorder ::=",
+ /* 137 */ "nulls ::= NULLS FIRST",
+ /* 138 */ "nulls ::= NULLS LAST",
+ /* 139 */ "nulls ::=",
+ /* 140 */ "groupby_opt ::=",
+ /* 141 */ "groupby_opt ::= GROUP BY nexprlist",
+ /* 142 */ "having_opt ::=",
+ /* 143 */ "having_opt ::= HAVING expr",
+ /* 144 */ "limit_opt ::=",
+ /* 145 */ "limit_opt ::= LIMIT expr",
+ /* 146 */ "limit_opt ::= LIMIT expr OFFSET expr",
+ /* 147 */ "limit_opt ::= LIMIT expr COMMA expr",
+ /* 148 */ "cmd ::= with DELETE FROM xfullname indexed_opt where_opt",
+ /* 149 */ "where_opt ::=",
+ /* 150 */ "where_opt ::= WHERE expr",
+ /* 151 */ "cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt",
+ /* 152 */ "setlist ::= setlist COMMA nm EQ expr",
+ /* 153 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
+ /* 154 */ "setlist ::= nm EQ expr",
+ /* 155 */ "setlist ::= LP idlist RP EQ expr",
+ /* 156 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert",
+ /* 157 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES",
+ /* 158 */ "upsert ::=",
+ /* 159 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt",
+ /* 160 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING",
+ /* 161 */ "upsert ::= ON CONFLICT DO NOTHING",
+ /* 162 */ "insert_cmd ::= INSERT orconf",
+ /* 163 */ "insert_cmd ::= REPLACE",
+ /* 164 */ "idlist_opt ::=",
+ /* 165 */ "idlist_opt ::= LP idlist RP",
+ /* 166 */ "idlist ::= idlist COMMA nm",
+ /* 167 */ "idlist ::= nm",
+ /* 168 */ "expr ::= LP expr RP",
+ /* 169 */ "expr ::= ID|INDEXED",
+ /* 170 */ "expr ::= JOIN_KW",
+ /* 171 */ "expr ::= nm DOT nm",
+ /* 172 */ "expr ::= nm DOT nm DOT nm",
+ /* 173 */ "term ::= NULL|FLOAT|BLOB",
+ /* 174 */ "term ::= STRING",
+ /* 175 */ "term ::= INTEGER",
+ /* 176 */ "expr ::= VARIABLE",
+ /* 177 */ "expr ::= expr COLLATE ID|STRING",
+ /* 178 */ "expr ::= CAST LP expr AS typetoken RP",
+ /* 179 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
+ /* 180 */ "expr ::= ID|INDEXED LP STAR RP",
+ /* 181 */ "expr ::= ID|INDEXED LP distinct exprlist RP filter_over",
+ /* 182 */ "expr ::= ID|INDEXED LP STAR RP filter_over",
+ /* 183 */ "term ::= CTIME_KW",
+ /* 184 */ "expr ::= LP nexprlist COMMA expr RP",
+ /* 185 */ "expr ::= expr AND expr",
+ /* 186 */ "expr ::= expr OR expr",
+ /* 187 */ "expr ::= expr LT|GT|GE|LE expr",
+ /* 188 */ "expr ::= expr EQ|NE expr",
+ /* 189 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
+ /* 190 */ "expr ::= expr PLUS|MINUS expr",
+ /* 191 */ "expr ::= expr STAR|SLASH|REM expr",
+ /* 192 */ "expr ::= expr CONCAT expr",
+ /* 193 */ "likeop ::= NOT LIKE_KW|MATCH",
+ /* 194 */ "expr ::= expr likeop expr",
+ /* 195 */ "expr ::= expr likeop expr ESCAPE expr",
+ /* 196 */ "expr ::= expr ISNULL|NOTNULL",
+ /* 197 */ "expr ::= expr NOT NULL",
+ /* 198 */ "expr ::= expr IS expr",
+ /* 199 */ "expr ::= expr IS NOT expr",
+ /* 200 */ "expr ::= NOT expr",
+ /* 201 */ "expr ::= BITNOT expr",
+ /* 202 */ "expr ::= PLUS|MINUS expr",
+ /* 203 */ "between_op ::= BETWEEN",
+ /* 204 */ "between_op ::= NOT BETWEEN",
+ /* 205 */ "expr ::= expr between_op expr AND expr",
+ /* 206 */ "in_op ::= IN",
+ /* 207 */ "in_op ::= NOT IN",
+ /* 208 */ "expr ::= expr in_op LP exprlist RP",
+ /* 209 */ "expr ::= LP select RP",
+ /* 210 */ "expr ::= expr in_op LP select RP",
+ /* 211 */ "expr ::= expr in_op nm dbnm paren_exprlist",
+ /* 212 */ "expr ::= EXISTS LP select RP",
+ /* 213 */ "expr ::= CASE case_operand case_exprlist case_else END",
+ /* 214 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
+ /* 215 */ "case_exprlist ::= WHEN expr THEN expr",
+ /* 216 */ "case_else ::= ELSE expr",
+ /* 217 */ "case_else ::=",
+ /* 218 */ "case_operand ::= expr",
+ /* 219 */ "case_operand ::=",
+ /* 220 */ "exprlist ::=",
+ /* 221 */ "nexprlist ::= nexprlist COMMA expr",
+ /* 222 */ "nexprlist ::= expr",
+ /* 223 */ "paren_exprlist ::=",
+ /* 224 */ "paren_exprlist ::= LP exprlist RP",
+ /* 225 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
+ /* 226 */ "uniqueflag ::= UNIQUE",
+ /* 227 */ "uniqueflag ::=",
+ /* 228 */ "eidlist_opt ::=",
+ /* 229 */ "eidlist_opt ::= LP eidlist RP",
+ /* 230 */ "eidlist ::= eidlist COMMA nm collate sortorder",
+ /* 231 */ "eidlist ::= nm collate sortorder",
+ /* 232 */ "collate ::=",
+ /* 233 */ "collate ::= COLLATE ID|STRING",
+ /* 234 */ "cmd ::= DROP INDEX ifexists fullname",
+ /* 235 */ "cmd ::= VACUUM vinto",
+ /* 236 */ "cmd ::= VACUUM nm vinto",
+ /* 237 */ "vinto ::= INTO expr",
+ /* 238 */ "vinto ::=",
+ /* 239 */ "cmd ::= PRAGMA nm dbnm",
+ /* 240 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
+ /* 241 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
+ /* 242 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
+ /* 243 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
+ /* 244 */ "plus_num ::= PLUS INTEGER|FLOAT",
+ /* 245 */ "minus_num ::= MINUS INTEGER|FLOAT",
+ /* 246 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
+ /* 247 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
+ /* 248 */ "trigger_time ::= BEFORE|AFTER",
+ /* 249 */ "trigger_time ::= INSTEAD OF",
+ /* 250 */ "trigger_time ::=",
+ /* 251 */ "trigger_event ::= DELETE|INSERT",
+ /* 252 */ "trigger_event ::= UPDATE",
+ /* 253 */ "trigger_event ::= UPDATE OF idlist",
+ /* 254 */ "when_clause ::=",
+ /* 255 */ "when_clause ::= WHEN expr",
+ /* 256 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
+ /* 257 */ "trigger_cmd_list ::= trigger_cmd SEMI",
+ /* 258 */ "trnm ::= nm DOT nm",
+ /* 259 */ "tridxby ::= INDEXED BY nm",
+ /* 260 */ "tridxby ::= NOT INDEXED",
+ /* 261 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt",
+ /* 262 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
+ /* 263 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
+ /* 264 */ "trigger_cmd ::= scanpt select scanpt",
+ /* 265 */ "expr ::= RAISE LP IGNORE RP",
+ /* 266 */ "expr ::= RAISE LP raisetype COMMA nm RP",
+ /* 267 */ "raisetype ::= ROLLBACK",
+ /* 268 */ "raisetype ::= ABORT",
+ /* 269 */ "raisetype ::= FAIL",
+ /* 270 */ "cmd ::= DROP TRIGGER ifexists fullname",
+ /* 271 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
+ /* 272 */ "cmd ::= DETACH database_kw_opt expr",
+ /* 273 */ "key_opt ::=",
+ /* 274 */ "key_opt ::= KEY expr",
+ /* 275 */ "cmd ::= REINDEX",
+ /* 276 */ "cmd ::= REINDEX nm dbnm",
+ /* 277 */ "cmd ::= ANALYZE",
+ /* 278 */ "cmd ::= ANALYZE nm dbnm",
+ /* 279 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
+ /* 280 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
+ /* 281 */ "add_column_fullname ::= fullname",
+ /* 282 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
+ /* 283 */ "cmd ::= create_vtab",
+ /* 284 */ "cmd ::= create_vtab LP vtabarglist RP",
+ /* 285 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
+ /* 286 */ "vtabarg ::=",
+ /* 287 */ "vtabargtoken ::= ANY",
+ /* 288 */ "vtabargtoken ::= lp anylist RP",
+ /* 289 */ "lp ::= LP",
+ /* 290 */ "with ::= WITH wqlist",
+ /* 291 */ "with ::= WITH RECURSIVE wqlist",
+ /* 292 */ "wqlist ::= nm eidlist_opt AS LP select RP",
+ /* 293 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
+ /* 294 */ "windowdefn_list ::= windowdefn",
+ /* 295 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
+ /* 296 */ "windowdefn ::= nm AS LP window RP",
+ /* 297 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt",
+ /* 298 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt",
+ /* 299 */ "window ::= ORDER BY sortlist frame_opt",
+ /* 300 */ "window ::= nm ORDER BY sortlist frame_opt",
+ /* 301 */ "window ::= frame_opt",
+ /* 302 */ "window ::= nm frame_opt",
+ /* 303 */ "frame_opt ::=",
+ /* 304 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt",
+ /* 305 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt",
+ /* 306 */ "range_or_rows ::= RANGE|ROWS|GROUPS",
+ /* 307 */ "frame_bound_s ::= frame_bound",
+ /* 308 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
+ /* 309 */ "frame_bound_e ::= frame_bound",
+ /* 310 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
+ /* 311 */ "frame_bound ::= expr PRECEDING|FOLLOWING",
+ /* 312 */ "frame_bound ::= CURRENT ROW",
+ /* 313 */ "frame_exclude_opt ::=",
+ /* 314 */ "frame_exclude_opt ::= EXCLUDE frame_exclude",
+ /* 315 */ "frame_exclude ::= NO OTHERS",
+ /* 316 */ "frame_exclude ::= CURRENT ROW",
+ /* 317 */ "frame_exclude ::= GROUP|TIES",
+ /* 318 */ "window_clause ::= WINDOW windowdefn_list",
+ /* 319 */ "filter_over ::= filter_clause over_clause",
+ /* 320 */ "filter_over ::= over_clause",
+ /* 321 */ "filter_over ::= filter_clause",
+ /* 322 */ "over_clause ::= OVER LP window RP",
+ /* 323 */ "over_clause ::= OVER nm",
+ /* 324 */ "filter_clause ::= FILTER LP WHERE expr RP",
+ /* 325 */ "input ::= cmdlist",
+ /* 326 */ "cmdlist ::= cmdlist ecmd",
+ /* 327 */ "cmdlist ::= ecmd",
+ /* 328 */ "ecmd ::= SEMI",
+ /* 329 */ "ecmd ::= cmdx SEMI",
+ /* 330 */ "ecmd ::= explain cmdx SEMI",
+ /* 331 */ "trans_opt ::=",
+ /* 332 */ "trans_opt ::= TRANSACTION",
+ /* 333 */ "trans_opt ::= TRANSACTION nm",
+ /* 334 */ "savepoint_opt ::= SAVEPOINT",
+ /* 335 */ "savepoint_opt ::=",
+ /* 336 */ "cmd ::= create_table create_table_args",
+ /* 337 */ "columnlist ::= columnlist COMMA columnname carglist",
+ /* 338 */ "columnlist ::= columnname carglist",
+ /* 339 */ "nm ::= ID|INDEXED",
+ /* 340 */ "nm ::= STRING",
+ /* 341 */ "nm ::= JOIN_KW",
+ /* 342 */ "typetoken ::= typename",
+ /* 343 */ "typename ::= ID|STRING",
+ /* 344 */ "signed ::= plus_num",
+ /* 345 */ "signed ::= minus_num",
+ /* 346 */ "carglist ::= carglist ccons",
+ /* 347 */ "carglist ::=",
+ /* 348 */ "ccons ::= NULL onconf",
+ /* 349 */ "ccons ::= GENERATED ALWAYS AS generated",
+ /* 350 */ "ccons ::= AS generated",
+ /* 351 */ "conslist_opt ::= COMMA conslist",
+ /* 352 */ "conslist ::= conslist tconscomma tcons",
+ /* 353 */ "conslist ::= tcons",
+ /* 354 */ "tconscomma ::=",
+ /* 355 */ "defer_subclause_opt ::= defer_subclause",
+ /* 356 */ "resolvetype ::= raisetype",
+ /* 357 */ "selectnowith ::= oneselect",
+ /* 358 */ "oneselect ::= values",
+ /* 359 */ "sclp ::= selcollist COMMA",
+ /* 360 */ "as ::= ID|STRING",
+ /* 361 */ "expr ::= term",
+ /* 362 */ "likeop ::= LIKE_KW|MATCH",
+ /* 363 */ "exprlist ::= nexprlist",
+ /* 364 */ "nmnum ::= plus_num",
+ /* 365 */ "nmnum ::= nm",
+ /* 366 */ "nmnum ::= ON",
+ /* 367 */ "nmnum ::= DELETE",
+ /* 368 */ "nmnum ::= DEFAULT",
+ /* 369 */ "plus_num ::= INTEGER|FLOAT",
+ /* 370 */ "foreach_clause ::=",
+ /* 371 */ "foreach_clause ::= FOR EACH ROW",
+ /* 372 */ "trnm ::= nm",
+ /* 373 */ "tridxby ::=",
+ /* 374 */ "database_kw_opt ::= DATABASE",
+ /* 375 */ "database_kw_opt ::=",
+ /* 376 */ "kwcolumn_opt ::=",
+ /* 377 */ "kwcolumn_opt ::= COLUMNKW",
+ /* 378 */ "vtabarglist ::= vtabarg",
+ /* 379 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
+ /* 380 */ "vtabarg ::= vtabarg vtabargtoken",
+ /* 381 */ "anylist ::=",
+ /* 382 */ "anylist ::= anylist LP anylist RP",
+ /* 383 */ "anylist ::= anylist ANY",
+ /* 384 */ "with ::=",
+};
+#endif /* NDEBUG */
+
+
+#if YYSTACKDEPTH<=0
+/*
+** Try to increase the size of the parser stack. Return the number
+** of errors. Return 0 on success.
+*/
+static int yyGrowStack(yyParser *p){
+ int newSize;
+ int idx;
+ yyStackEntry *pNew;
+
+ newSize = p->yystksz*2 + 100;
+ idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
+ if( p->yystack==&p->yystk0 ){
+ pNew = malloc(newSize*sizeof(pNew[0]));
+ if( pNew ) pNew[0] = p->yystk0;
+ }else{
+ pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
+ }
+ if( pNew ){
+ p->yystack = pNew;
+ p->yytos = &p->yystack[idx];
+#ifndef NDEBUG
+ if( yyTraceFILE ){
+ fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
+ yyTracePrompt, p->yystksz, newSize);
+ }
+#endif
+ p->yystksz = newSize;
+ }
+ return pNew==0;
+}
+#endif
+
+/* Datatype of the argument to the memory allocated passed as the
+** second argument to sqlite3ParserAlloc() below. This can be changed by
+** putting an appropriate #define in the %include section of the input
+** grammar.
+*/
+#ifndef YYMALLOCARGTYPE
+# define YYMALLOCARGTYPE size_t
+#endif
+
+/* Initialize a new parser that has already been allocated.
+*/
+SQLITE_PRIVATE void sqlite3ParserInit(void *yypRawParser sqlite3ParserCTX_PDECL){
+ yyParser *yypParser = (yyParser*)yypRawParser;
+ sqlite3ParserCTX_STORE
+#ifdef YYTRACKMAXSTACKDEPTH
+ yypParser->yyhwm = 0;
+#endif
+#if YYSTACKDEPTH<=0
+ yypParser->yytos = NULL;
+ yypParser->yystack = NULL;
+ yypParser->yystksz = 0;
+ if( yyGrowStack(yypParser) ){
+ yypParser->yystack = &yypParser->yystk0;
+ yypParser->yystksz = 1;
+ }
+#endif
+#ifndef YYNOERRORRECOVERY
+ yypParser->yyerrcnt = -1;
+#endif
+ yypParser->yytos = yypParser->yystack;
+ yypParser->yystack[0].stateno = 0;
+ yypParser->yystack[0].major = 0;
+#if YYSTACKDEPTH>0
+ yypParser->yystackEnd = &yypParser->yystack[YYSTACKDEPTH-1];
+#endif
+}
+
+#ifndef sqlite3Parser_ENGINEALWAYSONSTACK
+/*
+** This function allocates a new parser.
+** The only argument is a pointer to a function which works like
+** malloc.
+**
+** Inputs:
+** A pointer to the function used to allocate memory.
+**
+** Outputs:
+** A pointer to a parser. This pointer is used in subsequent calls
+** to sqlite3Parser and sqlite3ParserFree.
+*/
+SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE) sqlite3ParserCTX_PDECL){
+ yyParser *yypParser;
+ yypParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
+ if( yypParser ){
+ sqlite3ParserCTX_STORE
+ sqlite3ParserInit(yypParser sqlite3ParserCTX_PARAM);
+ }
+ return (void*)yypParser;
+}
+#endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
+
+
+/* The following function deletes the "minor type" or semantic value
+** associated with a symbol. The symbol can be either a terminal
+** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
+** a pointer to the value to be deleted. The code used to do the
+** deletions is derived from the %destructor and/or %token_destructor
+** directives of the input grammar.
+*/
+static void yy_destructor(
+ yyParser *yypParser, /* The parser */
+ YYCODETYPE yymajor, /* Type code for object to destroy */
+ YYMINORTYPE *yypminor /* The object to be destroyed */
+){
+ sqlite3ParserARG_FETCH
+ sqlite3ParserCTX_FETCH
+ switch( yymajor ){
+ /* Here is inserted the actions which take place when a
+ ** terminal or non-terminal is destroyed. This can happen
+ ** when the symbol is popped from the stack during a
+ ** reduce or during error processing or when a parser is
+ ** being destroyed before it is finished parsing.
+ **
+ ** Note: during a reduce, the only symbols destroyed are those
+ ** which appear on the RHS of the rule, but which are *not* used
+ ** inside the C code.
+ */
+/********* Begin destructor definitions ***************************************/
+ case 200: /* select */
+ case 234: /* selectnowith */
+ case 235: /* oneselect */
+ case 247: /* values */
+{
+sqlite3SelectDelete(pParse->db, (yypminor->yy539));
+}
+ break;
+ case 211: /* term */
+ case 212: /* expr */
+ case 241: /* where_opt */
+ case 243: /* having_opt */
+ case 255: /* on_opt */
+ case 271: /* case_operand */
+ case 273: /* case_else */
+ case 276: /* vinto */
+ case 283: /* when_clause */
+ case 288: /* key_opt */
+ case 302: /* filter_clause */
+{
+sqlite3ExprDelete(pParse->db, (yypminor->yy202));
+}
+ break;
+ case 216: /* eidlist_opt */
+ case 226: /* sortlist */
+ case 227: /* eidlist */
+ case 239: /* selcollist */
+ case 242: /* groupby_opt */
+ case 244: /* orderby_opt */
+ case 248: /* nexprlist */
+ case 249: /* sclp */
+ case 257: /* exprlist */
+ case 262: /* setlist */
+ case 270: /* paren_exprlist */
+ case 272: /* case_exprlist */
+ case 301: /* part_opt */
+{
+sqlite3ExprListDelete(pParse->db, (yypminor->yy242));
+}
+ break;
+ case 233: /* fullname */
+ case 240: /* from */
+ case 251: /* seltablist */
+ case 252: /* stl_prefix */
+ case 258: /* xfullname */
+{
+sqlite3SrcListDelete(pParse->db, (yypminor->yy47));
+}
+ break;
+ case 236: /* wqlist */
+{
+sqlite3WithDelete(pParse->db, (yypminor->yy131));
+}
+ break;
+ case 246: /* window_clause */
+ case 297: /* windowdefn_list */
+{
+sqlite3WindowListDelete(pParse->db, (yypminor->yy303));
+}
+ break;
+ case 256: /* using_opt */
+ case 259: /* idlist */
+ case 264: /* idlist_opt */
+{
+sqlite3IdListDelete(pParse->db, (yypminor->yy600));
+}
+ break;
+ case 266: /* filter_over */
+ case 298: /* windowdefn */
+ case 299: /* window */
+ case 300: /* frame_opt */
+ case 303: /* over_clause */
+{
+sqlite3WindowDelete(pParse->db, (yypminor->yy303));
+}
+ break;
+ case 279: /* trigger_cmd_list */
+ case 284: /* trigger_cmd */
+{
+sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy447));
+}
+ break;
+ case 281: /* trigger_event */
+{
+sqlite3IdListDelete(pParse->db, (yypminor->yy230).b);
+}
+ break;
+ case 305: /* frame_bound */
+ case 306: /* frame_bound_s */
+ case 307: /* frame_bound_e */
+{
+sqlite3ExprDelete(pParse->db, (yypminor->yy77).pExpr);
+}
+ break;
+/********* End destructor definitions *****************************************/
+ default: break; /* If no destructor action specified: do nothing */
+ }
+}
+
+/*
+** Pop the parser's stack once.
+**
+** If there is a destructor routine associated with the token which
+** is popped from the stack, then call it.
+*/
+static void yy_pop_parser_stack(yyParser *pParser){
+ yyStackEntry *yytos;
+ assert( pParser->yytos!=0 );
+ assert( pParser->yytos > pParser->yystack );
+ yytos = pParser->yytos--;
+#ifndef NDEBUG
+ if( yyTraceFILE ){
+ fprintf(yyTraceFILE,"%sPopping %s\n",
+ yyTracePrompt,
+ yyTokenName[yytos->major]);
+ }
+#endif
+ yy_destructor(pParser, yytos->major, &yytos->minor);
+}
+
+/*
+** Clear all secondary memory allocations from the parser
+*/
+SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
+ yyParser *pParser = (yyParser*)p;
+ while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
+#if YYSTACKDEPTH<=0
+ if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
+#endif
+}
+
+#ifndef sqlite3Parser_ENGINEALWAYSONSTACK
+/*
+** Deallocate and destroy a parser. Destructors are called for
+** all stack elements before shutting the parser down.
+**
+** If the YYPARSEFREENEVERNULL macro exists (for example because it
+** is defined in a %include section of the input grammar) then it is
+** assumed that the input pointer is never NULL.
+*/
+SQLITE_PRIVATE void sqlite3ParserFree(
+ void *p, /* The parser to be deleted */
+ void (*freeProc)(void*) /* Function used to reclaim memory */
+){
+#ifndef YYPARSEFREENEVERNULL
+ if( p==0 ) return;
+#endif
+ sqlite3ParserFinalize(p);
+ (*freeProc)(p);
+}
+#endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
+
+/*
+** Return the peak depth of the stack for a parser.
+*/
+#ifdef YYTRACKMAXSTACKDEPTH
+SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
+ yyParser *pParser = (yyParser*)p;
+ return pParser->yyhwm;
+}
+#endif
+
+/* This array of booleans keeps track of the parser statement
+** coverage. The element yycoverage[X][Y] is set when the parser
+** is in state X and has a lookahead token Y. In a well-tested
+** systems, every element of this matrix should end up being set.
+*/
+#if defined(YYCOVERAGE)
+static unsigned char yycoverage[YYNSTATE][YYNTOKEN];
+#endif
+
+/*
+** Write into out a description of every state/lookahead combination that
+**
+** (1) has not been used by the parser, and
+** (2) is not a syntax error.
+**
+** Return the number of missed state/lookahead combinations.
+*/
+#if defined(YYCOVERAGE)
+SQLITE_PRIVATE int sqlite3ParserCoverage(FILE *out){
+ int stateno, iLookAhead, i;
+ int nMissed = 0;
+ for(stateno=0; stateno<YYNSTATE; stateno++){
+ i = yy_shift_ofst[stateno];
+ for(iLookAhead=0; iLookAhead<YYNTOKEN; iLookAhead++){
+ if( yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
+ if( yycoverage[stateno][iLookAhead]==0 ) nMissed++;
+ if( out ){
+ fprintf(out,"State %d lookahead %s %s\n", stateno,
+ yyTokenName[iLookAhead],
+ yycoverage[stateno][iLookAhead] ? "ok" : "missed");
+ }
+ }
+ }
+ return nMissed;
+}
+#endif
+
+/*
+** Find the appropriate action for a parser given the terminal
+** look-ahead token iLookAhead.
+*/
+static YYACTIONTYPE yy_find_shift_action(
+ YYCODETYPE iLookAhead, /* The look-ahead token */
+ YYACTIONTYPE stateno /* Current state number */
+){
+ int i;
+
+ if( stateno>YY_MAX_SHIFT ) return stateno;
+ assert( stateno <= YY_SHIFT_COUNT );
+#if defined(YYCOVERAGE)
+ yycoverage[stateno][iLookAhead] = 1;
+#endif
+ do{
+ i = yy_shift_ofst[stateno];
+ assert( i>=0 );
+ assert( i<=YY_ACTTAB_COUNT );
+ assert( i+YYNTOKEN<=(int)YY_NLOOKAHEAD );
+ assert( iLookAhead!=YYNOCODE );
+ assert( iLookAhead < YYNTOKEN );
+ i += iLookAhead;
+ assert( i<(int)YY_NLOOKAHEAD );
+ if( yy_lookahead[i]!=iLookAhead ){
+#ifdef YYFALLBACK
+ YYCODETYPE iFallback; /* Fallback token */
+ assert( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0]) );
+ iFallback = yyFallback[iLookAhead];
+ if( iFallback!=0 ){
+#ifndef NDEBUG
+ if( yyTraceFILE ){
+ fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
+ yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
+ }
+#endif
+ assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
+ iLookAhead = iFallback;
+ continue;
+ }
+#endif
+#ifdef YYWILDCARD
+ {
+ int j = i - iLookAhead + YYWILDCARD;
+ assert( j<(int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])) );
+ if( yy_lookahead[j]==YYWILDCARD && iLookAhead>0 ){
+#ifndef NDEBUG
+ if( yyTraceFILE ){
+ fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
+ yyTracePrompt, yyTokenName[iLookAhead],
+ yyTokenName[YYWILDCARD]);
+ }
+#endif /* NDEBUG */
+ return yy_action[j];
+ }
+ }
+#endif /* YYWILDCARD */
+ return yy_default[stateno];
+ }else{
+ assert( i>=0 && i<(int)(sizeof(yy_action)/sizeof(yy_action[0])) );
+ return yy_action[i];
+ }
+ }while(1);
+}
+
+/*
+** Find the appropriate action for a parser given the non-terminal
+** look-ahead token iLookAhead.
+*/
+static YYACTIONTYPE yy_find_reduce_action(
+ YYACTIONTYPE stateno, /* Current state number */
+ YYCODETYPE iLookAhead /* The look-ahead token */
+){
+ int i;
+#ifdef YYERRORSYMBOL
+ if( stateno>YY_REDUCE_COUNT ){
+ return yy_default[stateno];
+ }
+#else
+ assert( stateno<=YY_REDUCE_COUNT );
+#endif
+ i = yy_reduce_ofst[stateno];
+ assert( iLookAhead!=YYNOCODE );
+ i += iLookAhead;
+#ifdef YYERRORSYMBOL
+ if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
+ return yy_default[stateno];
+ }
+#else
+ assert( i>=0 && i<YY_ACTTAB_COUNT );
+ assert( yy_lookahead[i]==iLookAhead );
+#endif
+ return yy_action[i];
+}
+
+/*
+** The following routine is called if the stack overflows.
+*/
+static void yyStackOverflow(yyParser *yypParser){
+ sqlite3ParserARG_FETCH
+ sqlite3ParserCTX_FETCH
+#ifndef NDEBUG
+ if( yyTraceFILE ){
+ fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
+ }
+#endif
+ while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
+ /* Here code is inserted which will execute if the parser
+ ** stack every overflows */
+/******** Begin %stack_overflow code ******************************************/
+
+ sqlite3ErrorMsg(pParse, "parser stack overflow");
+/******** End %stack_overflow code ********************************************/
+ sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument var */
+ sqlite3ParserCTX_STORE
+}
+
+/*
+** Print tracing information for a SHIFT action
+*/
+#ifndef NDEBUG
+static void yyTraceShift(yyParser *yypParser, int yyNewState, const char *zTag){
+ if( yyTraceFILE ){
+ if( yyNewState<YYNSTATE ){
+ fprintf(yyTraceFILE,"%s%s '%s', go to state %d\n",
+ yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
+ yyNewState);
+ }else{
+ fprintf(yyTraceFILE,"%s%s '%s', pending reduce %d\n",
+ yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
+ yyNewState - YY_MIN_REDUCE);
+ }
+ }
+}
+#else
+# define yyTraceShift(X,Y,Z)
+#endif
+
+/*
+** Perform a shift action.
+*/
+static void yy_shift(
+ yyParser *yypParser, /* The parser to be shifted */
+ YYACTIONTYPE yyNewState, /* The new state to shift in */
+ YYCODETYPE yyMajor, /* The major token to shift in */
+ sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
+){
+ yyStackEntry *yytos;
+ yypParser->yytos++;
+#ifdef YYTRACKMAXSTACKDEPTH
+ if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
+ yypParser->yyhwm++;
+ assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
+ }
+#endif
+#if YYSTACKDEPTH>0
+ if( yypParser->yytos>yypParser->yystackEnd ){
+ yypParser->yytos--;
+ yyStackOverflow(yypParser);
+ return;
+ }
+#else
+ if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
+ if( yyGrowStack(yypParser) ){
+ yypParser->yytos--;
+ yyStackOverflow(yypParser);
+ return;
+ }
+ }
+#endif
+ if( yyNewState > YY_MAX_SHIFT ){
+ yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
+ }
+ yytos = yypParser->yytos;
+ yytos->stateno = yyNewState;
+ yytos->major = yyMajor;
+ yytos->minor.yy0 = yyMinor;
+ yyTraceShift(yypParser, yyNewState, "Shift");
+}
+
+/* For rule J, yyRuleInfoLhs[J] contains the symbol on the left-hand side
+** of that rule */
+static const YYCODETYPE yyRuleInfoLhs[] = {
+ 185, /* (0) explain ::= EXPLAIN */
+ 185, /* (1) explain ::= EXPLAIN QUERY PLAN */
+ 184, /* (2) cmdx ::= cmd */
+ 186, /* (3) cmd ::= BEGIN transtype trans_opt */
+ 187, /* (4) transtype ::= */
+ 187, /* (5) transtype ::= DEFERRED */
+ 187, /* (6) transtype ::= IMMEDIATE */
+ 187, /* (7) transtype ::= EXCLUSIVE */
+ 186, /* (8) cmd ::= COMMIT|END trans_opt */
+ 186, /* (9) cmd ::= ROLLBACK trans_opt */
+ 186, /* (10) cmd ::= SAVEPOINT nm */
+ 186, /* (11) cmd ::= RELEASE savepoint_opt nm */
+ 186, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
+ 191, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
+ 193, /* (14) createkw ::= CREATE */
+ 195, /* (15) ifnotexists ::= */
+ 195, /* (16) ifnotexists ::= IF NOT EXISTS */
+ 194, /* (17) temp ::= TEMP */
+ 194, /* (18) temp ::= */
+ 192, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
+ 192, /* (20) create_table_args ::= AS select */
+ 199, /* (21) table_options ::= */
+ 199, /* (22) table_options ::= WITHOUT nm */
+ 201, /* (23) columnname ::= nm typetoken */
+ 203, /* (24) typetoken ::= */
+ 203, /* (25) typetoken ::= typename LP signed RP */
+ 203, /* (26) typetoken ::= typename LP signed COMMA signed RP */
+ 204, /* (27) typename ::= typename ID|STRING */
+ 208, /* (28) scanpt ::= */
+ 209, /* (29) scantok ::= */
+ 210, /* (30) ccons ::= CONSTRAINT nm */
+ 210, /* (31) ccons ::= DEFAULT scantok term */
+ 210, /* (32) ccons ::= DEFAULT LP expr RP */
+ 210, /* (33) ccons ::= DEFAULT PLUS scantok term */
+ 210, /* (34) ccons ::= DEFAULT MINUS scantok term */
+ 210, /* (35) ccons ::= DEFAULT scantok ID|INDEXED */
+ 210, /* (36) ccons ::= NOT NULL onconf */
+ 210, /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */
+ 210, /* (38) ccons ::= UNIQUE onconf */
+ 210, /* (39) ccons ::= CHECK LP expr RP */
+ 210, /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */
+ 210, /* (41) ccons ::= defer_subclause */
+ 210, /* (42) ccons ::= COLLATE ID|STRING */
+ 219, /* (43) generated ::= LP expr RP */
+ 219, /* (44) generated ::= LP expr RP ID */
+ 215, /* (45) autoinc ::= */
+ 215, /* (46) autoinc ::= AUTOINCR */
+ 217, /* (47) refargs ::= */
+ 217, /* (48) refargs ::= refargs refarg */
+ 220, /* (49) refarg ::= MATCH nm */
+ 220, /* (50) refarg ::= ON INSERT refact */
+ 220, /* (51) refarg ::= ON DELETE refact */
+ 220, /* (52) refarg ::= ON UPDATE refact */
+ 221, /* (53) refact ::= SET NULL */
+ 221, /* (54) refact ::= SET DEFAULT */
+ 221, /* (55) refact ::= CASCADE */
+ 221, /* (56) refact ::= RESTRICT */
+ 221, /* (57) refact ::= NO ACTION */
+ 218, /* (58) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
+ 218, /* (59) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
+ 222, /* (60) init_deferred_pred_opt ::= */
+ 222, /* (61) init_deferred_pred_opt ::= INITIALLY DEFERRED */
+ 222, /* (62) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
+ 198, /* (63) conslist_opt ::= */
+ 224, /* (64) tconscomma ::= COMMA */
+ 225, /* (65) tcons ::= CONSTRAINT nm */
+ 225, /* (66) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
+ 225, /* (67) tcons ::= UNIQUE LP sortlist RP onconf */
+ 225, /* (68) tcons ::= CHECK LP expr RP onconf */
+ 225, /* (69) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
+ 228, /* (70) defer_subclause_opt ::= */
+ 213, /* (71) onconf ::= */
+ 213, /* (72) onconf ::= ON CONFLICT resolvetype */
+ 229, /* (73) orconf ::= */
+ 229, /* (74) orconf ::= OR resolvetype */
+ 230, /* (75) resolvetype ::= IGNORE */
+ 230, /* (76) resolvetype ::= REPLACE */
+ 186, /* (77) cmd ::= DROP TABLE ifexists fullname */
+ 232, /* (78) ifexists ::= IF EXISTS */
+ 232, /* (79) ifexists ::= */
+ 186, /* (80) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
+ 186, /* (81) cmd ::= DROP VIEW ifexists fullname */
+ 186, /* (82) cmd ::= select */
+ 200, /* (83) select ::= WITH wqlist selectnowith */
+ 200, /* (84) select ::= WITH RECURSIVE wqlist selectnowith */
+ 200, /* (85) select ::= selectnowith */
+ 234, /* (86) selectnowith ::= selectnowith multiselect_op oneselect */
+ 237, /* (87) multiselect_op ::= UNION */
+ 237, /* (88) multiselect_op ::= UNION ALL */
+ 237, /* (89) multiselect_op ::= EXCEPT|INTERSECT */
+ 235, /* (90) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
+ 235, /* (91) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
+ 247, /* (92) values ::= VALUES LP nexprlist RP */
+ 247, /* (93) values ::= values COMMA LP nexprlist RP */
+ 238, /* (94) distinct ::= DISTINCT */
+ 238, /* (95) distinct ::= ALL */
+ 238, /* (96) distinct ::= */
+ 249, /* (97) sclp ::= */
+ 239, /* (98) selcollist ::= sclp scanpt expr scanpt as */
+ 239, /* (99) selcollist ::= sclp scanpt STAR */
+ 239, /* (100) selcollist ::= sclp scanpt nm DOT STAR */
+ 250, /* (101) as ::= AS nm */
+ 250, /* (102) as ::= */
+ 240, /* (103) from ::= */
+ 240, /* (104) from ::= FROM seltablist */
+ 252, /* (105) stl_prefix ::= seltablist joinop */
+ 252, /* (106) stl_prefix ::= */
+ 251, /* (107) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
+ 251, /* (108) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
+ 251, /* (109) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
+ 251, /* (110) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
+ 196, /* (111) dbnm ::= */
+ 196, /* (112) dbnm ::= DOT nm */
+ 233, /* (113) fullname ::= nm */
+ 233, /* (114) fullname ::= nm DOT nm */
+ 258, /* (115) xfullname ::= nm */
+ 258, /* (116) xfullname ::= nm DOT nm */
+ 258, /* (117) xfullname ::= nm DOT nm AS nm */
+ 258, /* (118) xfullname ::= nm AS nm */
+ 253, /* (119) joinop ::= COMMA|JOIN */
+ 253, /* (120) joinop ::= JOIN_KW JOIN */
+ 253, /* (121) joinop ::= JOIN_KW nm JOIN */
+ 253, /* (122) joinop ::= JOIN_KW nm nm JOIN */
+ 255, /* (123) on_opt ::= ON expr */
+ 255, /* (124) on_opt ::= */
+ 254, /* (125) indexed_opt ::= */
+ 254, /* (126) indexed_opt ::= INDEXED BY nm */
+ 254, /* (127) indexed_opt ::= NOT INDEXED */
+ 256, /* (128) using_opt ::= USING LP idlist RP */
+ 256, /* (129) using_opt ::= */
+ 244, /* (130) orderby_opt ::= */
+ 244, /* (131) orderby_opt ::= ORDER BY sortlist */
+ 226, /* (132) sortlist ::= sortlist COMMA expr sortorder nulls */
+ 226, /* (133) sortlist ::= expr sortorder nulls */
+ 214, /* (134) sortorder ::= ASC */
+ 214, /* (135) sortorder ::= DESC */
+ 214, /* (136) sortorder ::= */
+ 260, /* (137) nulls ::= NULLS FIRST */
+ 260, /* (138) nulls ::= NULLS LAST */
+ 260, /* (139) nulls ::= */
+ 242, /* (140) groupby_opt ::= */
+ 242, /* (141) groupby_opt ::= GROUP BY nexprlist */
+ 243, /* (142) having_opt ::= */
+ 243, /* (143) having_opt ::= HAVING expr */
+ 245, /* (144) limit_opt ::= */
+ 245, /* (145) limit_opt ::= LIMIT expr */
+ 245, /* (146) limit_opt ::= LIMIT expr OFFSET expr */
+ 245, /* (147) limit_opt ::= LIMIT expr COMMA expr */
+ 186, /* (148) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
+ 241, /* (149) where_opt ::= */
+ 241, /* (150) where_opt ::= WHERE expr */
+ 186, /* (151) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt */
+ 262, /* (152) setlist ::= setlist COMMA nm EQ expr */
+ 262, /* (153) setlist ::= setlist COMMA LP idlist RP EQ expr */
+ 262, /* (154) setlist ::= nm EQ expr */
+ 262, /* (155) setlist ::= LP idlist RP EQ expr */
+ 186, /* (156) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
+ 186, /* (157) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
+ 265, /* (158) upsert ::= */
+ 265, /* (159) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
+ 265, /* (160) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
+ 265, /* (161) upsert ::= ON CONFLICT DO NOTHING */
+ 263, /* (162) insert_cmd ::= INSERT orconf */
+ 263, /* (163) insert_cmd ::= REPLACE */
+ 264, /* (164) idlist_opt ::= */
+ 264, /* (165) idlist_opt ::= LP idlist RP */
+ 259, /* (166) idlist ::= idlist COMMA nm */
+ 259, /* (167) idlist ::= nm */
+ 212, /* (168) expr ::= LP expr RP */
+ 212, /* (169) expr ::= ID|INDEXED */
+ 212, /* (170) expr ::= JOIN_KW */
+ 212, /* (171) expr ::= nm DOT nm */
+ 212, /* (172) expr ::= nm DOT nm DOT nm */
+ 211, /* (173) term ::= NULL|FLOAT|BLOB */
+ 211, /* (174) term ::= STRING */
+ 211, /* (175) term ::= INTEGER */
+ 212, /* (176) expr ::= VARIABLE */
+ 212, /* (177) expr ::= expr COLLATE ID|STRING */
+ 212, /* (178) expr ::= CAST LP expr AS typetoken RP */
+ 212, /* (179) expr ::= ID|INDEXED LP distinct exprlist RP */
+ 212, /* (180) expr ::= ID|INDEXED LP STAR RP */
+ 212, /* (181) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
+ 212, /* (182) expr ::= ID|INDEXED LP STAR RP filter_over */
+ 211, /* (183) term ::= CTIME_KW */
+ 212, /* (184) expr ::= LP nexprlist COMMA expr RP */
+ 212, /* (185) expr ::= expr AND expr */
+ 212, /* (186) expr ::= expr OR expr */
+ 212, /* (187) expr ::= expr LT|GT|GE|LE expr */
+ 212, /* (188) expr ::= expr EQ|NE expr */
+ 212, /* (189) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
+ 212, /* (190) expr ::= expr PLUS|MINUS expr */
+ 212, /* (191) expr ::= expr STAR|SLASH|REM expr */
+ 212, /* (192) expr ::= expr CONCAT expr */
+ 267, /* (193) likeop ::= NOT LIKE_KW|MATCH */
+ 212, /* (194) expr ::= expr likeop expr */
+ 212, /* (195) expr ::= expr likeop expr ESCAPE expr */
+ 212, /* (196) expr ::= expr ISNULL|NOTNULL */
+ 212, /* (197) expr ::= expr NOT NULL */
+ 212, /* (198) expr ::= expr IS expr */
+ 212, /* (199) expr ::= expr IS NOT expr */
+ 212, /* (200) expr ::= NOT expr */
+ 212, /* (201) expr ::= BITNOT expr */
+ 212, /* (202) expr ::= PLUS|MINUS expr */
+ 268, /* (203) between_op ::= BETWEEN */
+ 268, /* (204) between_op ::= NOT BETWEEN */
+ 212, /* (205) expr ::= expr between_op expr AND expr */
+ 269, /* (206) in_op ::= IN */
+ 269, /* (207) in_op ::= NOT IN */
+ 212, /* (208) expr ::= expr in_op LP exprlist RP */
+ 212, /* (209) expr ::= LP select RP */
+ 212, /* (210) expr ::= expr in_op LP select RP */
+ 212, /* (211) expr ::= expr in_op nm dbnm paren_exprlist */
+ 212, /* (212) expr ::= EXISTS LP select RP */
+ 212, /* (213) expr ::= CASE case_operand case_exprlist case_else END */
+ 272, /* (214) case_exprlist ::= case_exprlist WHEN expr THEN expr */
+ 272, /* (215) case_exprlist ::= WHEN expr THEN expr */
+ 273, /* (216) case_else ::= ELSE expr */
+ 273, /* (217) case_else ::= */
+ 271, /* (218) case_operand ::= expr */
+ 271, /* (219) case_operand ::= */
+ 257, /* (220) exprlist ::= */
+ 248, /* (221) nexprlist ::= nexprlist COMMA expr */
+ 248, /* (222) nexprlist ::= expr */
+ 270, /* (223) paren_exprlist ::= */
+ 270, /* (224) paren_exprlist ::= LP exprlist RP */
+ 186, /* (225) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
+ 274, /* (226) uniqueflag ::= UNIQUE */
+ 274, /* (227) uniqueflag ::= */
+ 216, /* (228) eidlist_opt ::= */
+ 216, /* (229) eidlist_opt ::= LP eidlist RP */
+ 227, /* (230) eidlist ::= eidlist COMMA nm collate sortorder */
+ 227, /* (231) eidlist ::= nm collate sortorder */
+ 275, /* (232) collate ::= */
+ 275, /* (233) collate ::= COLLATE ID|STRING */
+ 186, /* (234) cmd ::= DROP INDEX ifexists fullname */
+ 186, /* (235) cmd ::= VACUUM vinto */
+ 186, /* (236) cmd ::= VACUUM nm vinto */
+ 276, /* (237) vinto ::= INTO expr */
+ 276, /* (238) vinto ::= */
+ 186, /* (239) cmd ::= PRAGMA nm dbnm */
+ 186, /* (240) cmd ::= PRAGMA nm dbnm EQ nmnum */
+ 186, /* (241) cmd ::= PRAGMA nm dbnm LP nmnum RP */
+ 186, /* (242) cmd ::= PRAGMA nm dbnm EQ minus_num */
+ 186, /* (243) cmd ::= PRAGMA nm dbnm LP minus_num RP */
+ 206, /* (244) plus_num ::= PLUS INTEGER|FLOAT */
+ 207, /* (245) minus_num ::= MINUS INTEGER|FLOAT */
+ 186, /* (246) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
+ 278, /* (247) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
+ 280, /* (248) trigger_time ::= BEFORE|AFTER */
+ 280, /* (249) trigger_time ::= INSTEAD OF */
+ 280, /* (250) trigger_time ::= */
+ 281, /* (251) trigger_event ::= DELETE|INSERT */
+ 281, /* (252) trigger_event ::= UPDATE */
+ 281, /* (253) trigger_event ::= UPDATE OF idlist */
+ 283, /* (254) when_clause ::= */
+ 283, /* (255) when_clause ::= WHEN expr */
+ 279, /* (256) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
+ 279, /* (257) trigger_cmd_list ::= trigger_cmd SEMI */
+ 285, /* (258) trnm ::= nm DOT nm */
+ 286, /* (259) tridxby ::= INDEXED BY nm */
+ 286, /* (260) tridxby ::= NOT INDEXED */
+ 284, /* (261) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
+ 284, /* (262) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
+ 284, /* (263) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
+ 284, /* (264) trigger_cmd ::= scanpt select scanpt */
+ 212, /* (265) expr ::= RAISE LP IGNORE RP */
+ 212, /* (266) expr ::= RAISE LP raisetype COMMA nm RP */
+ 231, /* (267) raisetype ::= ROLLBACK */
+ 231, /* (268) raisetype ::= ABORT */
+ 231, /* (269) raisetype ::= FAIL */
+ 186, /* (270) cmd ::= DROP TRIGGER ifexists fullname */
+ 186, /* (271) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
+ 186, /* (272) cmd ::= DETACH database_kw_opt expr */
+ 288, /* (273) key_opt ::= */
+ 288, /* (274) key_opt ::= KEY expr */
+ 186, /* (275) cmd ::= REINDEX */
+ 186, /* (276) cmd ::= REINDEX nm dbnm */
+ 186, /* (277) cmd ::= ANALYZE */
+ 186, /* (278) cmd ::= ANALYZE nm dbnm */
+ 186, /* (279) cmd ::= ALTER TABLE fullname RENAME TO nm */
+ 186, /* (280) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
+ 289, /* (281) add_column_fullname ::= fullname */
+ 186, /* (282) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
+ 186, /* (283) cmd ::= create_vtab */
+ 186, /* (284) cmd ::= create_vtab LP vtabarglist RP */
+ 291, /* (285) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
+ 293, /* (286) vtabarg ::= */
+ 294, /* (287) vtabargtoken ::= ANY */
+ 294, /* (288) vtabargtoken ::= lp anylist RP */
+ 295, /* (289) lp ::= LP */
+ 261, /* (290) with ::= WITH wqlist */
+ 261, /* (291) with ::= WITH RECURSIVE wqlist */
+ 236, /* (292) wqlist ::= nm eidlist_opt AS LP select RP */
+ 236, /* (293) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
+ 297, /* (294) windowdefn_list ::= windowdefn */
+ 297, /* (295) windowdefn_list ::= windowdefn_list COMMA windowdefn */
+ 298, /* (296) windowdefn ::= nm AS LP window RP */
+ 299, /* (297) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
+ 299, /* (298) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
+ 299, /* (299) window ::= ORDER BY sortlist frame_opt */
+ 299, /* (300) window ::= nm ORDER BY sortlist frame_opt */
+ 299, /* (301) window ::= frame_opt */
+ 299, /* (302) window ::= nm frame_opt */
+ 300, /* (303) frame_opt ::= */
+ 300, /* (304) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
+ 300, /* (305) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
+ 304, /* (306) range_or_rows ::= RANGE|ROWS|GROUPS */
+ 306, /* (307) frame_bound_s ::= frame_bound */
+ 306, /* (308) frame_bound_s ::= UNBOUNDED PRECEDING */
+ 307, /* (309) frame_bound_e ::= frame_bound */
+ 307, /* (310) frame_bound_e ::= UNBOUNDED FOLLOWING */
+ 305, /* (311) frame_bound ::= expr PRECEDING|FOLLOWING */
+ 305, /* (312) frame_bound ::= CURRENT ROW */
+ 308, /* (313) frame_exclude_opt ::= */
+ 308, /* (314) frame_exclude_opt ::= EXCLUDE frame_exclude */
+ 309, /* (315) frame_exclude ::= NO OTHERS */
+ 309, /* (316) frame_exclude ::= CURRENT ROW */
+ 309, /* (317) frame_exclude ::= GROUP|TIES */
+ 246, /* (318) window_clause ::= WINDOW windowdefn_list */
+ 266, /* (319) filter_over ::= filter_clause over_clause */
+ 266, /* (320) filter_over ::= over_clause */
+ 266, /* (321) filter_over ::= filter_clause */
+ 303, /* (322) over_clause ::= OVER LP window RP */
+ 303, /* (323) over_clause ::= OVER nm */
+ 302, /* (324) filter_clause ::= FILTER LP WHERE expr RP */
+ 181, /* (325) input ::= cmdlist */
+ 182, /* (326) cmdlist ::= cmdlist ecmd */
+ 182, /* (327) cmdlist ::= ecmd */
+ 183, /* (328) ecmd ::= SEMI */
+ 183, /* (329) ecmd ::= cmdx SEMI */
+ 183, /* (330) ecmd ::= explain cmdx SEMI */
+ 188, /* (331) trans_opt ::= */
+ 188, /* (332) trans_opt ::= TRANSACTION */
+ 188, /* (333) trans_opt ::= TRANSACTION nm */
+ 190, /* (334) savepoint_opt ::= SAVEPOINT */
+ 190, /* (335) savepoint_opt ::= */
+ 186, /* (336) cmd ::= create_table create_table_args */
+ 197, /* (337) columnlist ::= columnlist COMMA columnname carglist */
+ 197, /* (338) columnlist ::= columnname carglist */
+ 189, /* (339) nm ::= ID|INDEXED */
+ 189, /* (340) nm ::= STRING */
+ 189, /* (341) nm ::= JOIN_KW */
+ 203, /* (342) typetoken ::= typename */
+ 204, /* (343) typename ::= ID|STRING */
+ 205, /* (344) signed ::= plus_num */
+ 205, /* (345) signed ::= minus_num */
+ 202, /* (346) carglist ::= carglist ccons */
+ 202, /* (347) carglist ::= */
+ 210, /* (348) ccons ::= NULL onconf */
+ 210, /* (349) ccons ::= GENERATED ALWAYS AS generated */
+ 210, /* (350) ccons ::= AS generated */
+ 198, /* (351) conslist_opt ::= COMMA conslist */
+ 223, /* (352) conslist ::= conslist tconscomma tcons */
+ 223, /* (353) conslist ::= tcons */
+ 224, /* (354) tconscomma ::= */
+ 228, /* (355) defer_subclause_opt ::= defer_subclause */
+ 230, /* (356) resolvetype ::= raisetype */
+ 234, /* (357) selectnowith ::= oneselect */
+ 235, /* (358) oneselect ::= values */
+ 249, /* (359) sclp ::= selcollist COMMA */
+ 250, /* (360) as ::= ID|STRING */
+ 212, /* (361) expr ::= term */
+ 267, /* (362) likeop ::= LIKE_KW|MATCH */
+ 257, /* (363) exprlist ::= nexprlist */
+ 277, /* (364) nmnum ::= plus_num */
+ 277, /* (365) nmnum ::= nm */
+ 277, /* (366) nmnum ::= ON */
+ 277, /* (367) nmnum ::= DELETE */
+ 277, /* (368) nmnum ::= DEFAULT */
+ 206, /* (369) plus_num ::= INTEGER|FLOAT */
+ 282, /* (370) foreach_clause ::= */
+ 282, /* (371) foreach_clause ::= FOR EACH ROW */
+ 285, /* (372) trnm ::= nm */
+ 286, /* (373) tridxby ::= */
+ 287, /* (374) database_kw_opt ::= DATABASE */
+ 287, /* (375) database_kw_opt ::= */
+ 290, /* (376) kwcolumn_opt ::= */
+ 290, /* (377) kwcolumn_opt ::= COLUMNKW */
+ 292, /* (378) vtabarglist ::= vtabarg */
+ 292, /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */
+ 293, /* (380) vtabarg ::= vtabarg vtabargtoken */
+ 296, /* (381) anylist ::= */
+ 296, /* (382) anylist ::= anylist LP anylist RP */
+ 296, /* (383) anylist ::= anylist ANY */
+ 261, /* (384) with ::= */
+};
+
+/* For rule J, yyRuleInfoNRhs[J] contains the negative of the number
+** of symbols on the right-hand side of that rule. */
+static const signed char yyRuleInfoNRhs[] = {
+ -1, /* (0) explain ::= EXPLAIN */
+ -3, /* (1) explain ::= EXPLAIN QUERY PLAN */
+ -1, /* (2) cmdx ::= cmd */
+ -3, /* (3) cmd ::= BEGIN transtype trans_opt */
+ 0, /* (4) transtype ::= */
+ -1, /* (5) transtype ::= DEFERRED */
+ -1, /* (6) transtype ::= IMMEDIATE */
+ -1, /* (7) transtype ::= EXCLUSIVE */
+ -2, /* (8) cmd ::= COMMIT|END trans_opt */
+ -2, /* (9) cmd ::= ROLLBACK trans_opt */
+ -2, /* (10) cmd ::= SAVEPOINT nm */
+ -3, /* (11) cmd ::= RELEASE savepoint_opt nm */
+ -5, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
+ -6, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
+ -1, /* (14) createkw ::= CREATE */
+ 0, /* (15) ifnotexists ::= */
+ -3, /* (16) ifnotexists ::= IF NOT EXISTS */
+ -1, /* (17) temp ::= TEMP */
+ 0, /* (18) temp ::= */
+ -5, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
+ -2, /* (20) create_table_args ::= AS select */
+ 0, /* (21) table_options ::= */
+ -2, /* (22) table_options ::= WITHOUT nm */
+ -2, /* (23) columnname ::= nm typetoken */
+ 0, /* (24) typetoken ::= */
+ -4, /* (25) typetoken ::= typename LP signed RP */
+ -6, /* (26) typetoken ::= typename LP signed COMMA signed RP */
+ -2, /* (27) typename ::= typename ID|STRING */
+ 0, /* (28) scanpt ::= */
+ 0, /* (29) scantok ::= */
+ -2, /* (30) ccons ::= CONSTRAINT nm */
+ -3, /* (31) ccons ::= DEFAULT scantok term */
+ -4, /* (32) ccons ::= DEFAULT LP expr RP */
+ -4, /* (33) ccons ::= DEFAULT PLUS scantok term */
+ -4, /* (34) ccons ::= DEFAULT MINUS scantok term */
+ -3, /* (35) ccons ::= DEFAULT scantok ID|INDEXED */
+ -3, /* (36) ccons ::= NOT NULL onconf */
+ -5, /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */
+ -2, /* (38) ccons ::= UNIQUE onconf */
+ -4, /* (39) ccons ::= CHECK LP expr RP */
+ -4, /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */
+ -1, /* (41) ccons ::= defer_subclause */
+ -2, /* (42) ccons ::= COLLATE ID|STRING */
+ -3, /* (43) generated ::= LP expr RP */
+ -4, /* (44) generated ::= LP expr RP ID */
+ 0, /* (45) autoinc ::= */
+ -1, /* (46) autoinc ::= AUTOINCR */
+ 0, /* (47) refargs ::= */
+ -2, /* (48) refargs ::= refargs refarg */
+ -2, /* (49) refarg ::= MATCH nm */
+ -3, /* (50) refarg ::= ON INSERT refact */
+ -3, /* (51) refarg ::= ON DELETE refact */
+ -3, /* (52) refarg ::= ON UPDATE refact */
+ -2, /* (53) refact ::= SET NULL */
+ -2, /* (54) refact ::= SET DEFAULT */
+ -1, /* (55) refact ::= CASCADE */
+ -1, /* (56) refact ::= RESTRICT */
+ -2, /* (57) refact ::= NO ACTION */
+ -3, /* (58) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
+ -2, /* (59) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
+ 0, /* (60) init_deferred_pred_opt ::= */
+ -2, /* (61) init_deferred_pred_opt ::= INITIALLY DEFERRED */
+ -2, /* (62) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
+ 0, /* (63) conslist_opt ::= */
+ -1, /* (64) tconscomma ::= COMMA */
+ -2, /* (65) tcons ::= CONSTRAINT nm */
+ -7, /* (66) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
+ -5, /* (67) tcons ::= UNIQUE LP sortlist RP onconf */
+ -5, /* (68) tcons ::= CHECK LP expr RP onconf */
+ -10, /* (69) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
+ 0, /* (70) defer_subclause_opt ::= */
+ 0, /* (71) onconf ::= */
+ -3, /* (72) onconf ::= ON CONFLICT resolvetype */
+ 0, /* (73) orconf ::= */
+ -2, /* (74) orconf ::= OR resolvetype */
+ -1, /* (75) resolvetype ::= IGNORE */
+ -1, /* (76) resolvetype ::= REPLACE */
+ -4, /* (77) cmd ::= DROP TABLE ifexists fullname */
+ -2, /* (78) ifexists ::= IF EXISTS */
+ 0, /* (79) ifexists ::= */
+ -9, /* (80) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
+ -4, /* (81) cmd ::= DROP VIEW ifexists fullname */
+ -1, /* (82) cmd ::= select */
+ -3, /* (83) select ::= WITH wqlist selectnowith */
+ -4, /* (84) select ::= WITH RECURSIVE wqlist selectnowith */
+ -1, /* (85) select ::= selectnowith */
+ -3, /* (86) selectnowith ::= selectnowith multiselect_op oneselect */
+ -1, /* (87) multiselect_op ::= UNION */
+ -2, /* (88) multiselect_op ::= UNION ALL */
+ -1, /* (89) multiselect_op ::= EXCEPT|INTERSECT */
+ -9, /* (90) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
+ -10, /* (91) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
+ -4, /* (92) values ::= VALUES LP nexprlist RP */
+ -5, /* (93) values ::= values COMMA LP nexprlist RP */
+ -1, /* (94) distinct ::= DISTINCT */
+ -1, /* (95) distinct ::= ALL */
+ 0, /* (96) distinct ::= */
+ 0, /* (97) sclp ::= */
+ -5, /* (98) selcollist ::= sclp scanpt expr scanpt as */
+ -3, /* (99) selcollist ::= sclp scanpt STAR */
+ -5, /* (100) selcollist ::= sclp scanpt nm DOT STAR */
+ -2, /* (101) as ::= AS nm */
+ 0, /* (102) as ::= */
+ 0, /* (103) from ::= */
+ -2, /* (104) from ::= FROM seltablist */
+ -2, /* (105) stl_prefix ::= seltablist joinop */
+ 0, /* (106) stl_prefix ::= */
+ -7, /* (107) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
+ -9, /* (108) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
+ -7, /* (109) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
+ -7, /* (110) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
+ 0, /* (111) dbnm ::= */
+ -2, /* (112) dbnm ::= DOT nm */
+ -1, /* (113) fullname ::= nm */
+ -3, /* (114) fullname ::= nm DOT nm */
+ -1, /* (115) xfullname ::= nm */
+ -3, /* (116) xfullname ::= nm DOT nm */
+ -5, /* (117) xfullname ::= nm DOT nm AS nm */
+ -3, /* (118) xfullname ::= nm AS nm */
+ -1, /* (119) joinop ::= COMMA|JOIN */
+ -2, /* (120) joinop ::= JOIN_KW JOIN */
+ -3, /* (121) joinop ::= JOIN_KW nm JOIN */
+ -4, /* (122) joinop ::= JOIN_KW nm nm JOIN */
+ -2, /* (123) on_opt ::= ON expr */
+ 0, /* (124) on_opt ::= */
+ 0, /* (125) indexed_opt ::= */
+ -3, /* (126) indexed_opt ::= INDEXED BY nm */
+ -2, /* (127) indexed_opt ::= NOT INDEXED */
+ -4, /* (128) using_opt ::= USING LP idlist RP */
+ 0, /* (129) using_opt ::= */
+ 0, /* (130) orderby_opt ::= */
+ -3, /* (131) orderby_opt ::= ORDER BY sortlist */
+ -5, /* (132) sortlist ::= sortlist COMMA expr sortorder nulls */
+ -3, /* (133) sortlist ::= expr sortorder nulls */
+ -1, /* (134) sortorder ::= ASC */
+ -1, /* (135) sortorder ::= DESC */
+ 0, /* (136) sortorder ::= */
+ -2, /* (137) nulls ::= NULLS FIRST */
+ -2, /* (138) nulls ::= NULLS LAST */
+ 0, /* (139) nulls ::= */
+ 0, /* (140) groupby_opt ::= */
+ -3, /* (141) groupby_opt ::= GROUP BY nexprlist */
+ 0, /* (142) having_opt ::= */
+ -2, /* (143) having_opt ::= HAVING expr */
+ 0, /* (144) limit_opt ::= */
+ -2, /* (145) limit_opt ::= LIMIT expr */
+ -4, /* (146) limit_opt ::= LIMIT expr OFFSET expr */
+ -4, /* (147) limit_opt ::= LIMIT expr COMMA expr */
+ -6, /* (148) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
+ 0, /* (149) where_opt ::= */
+ -2, /* (150) where_opt ::= WHERE expr */
+ -9, /* (151) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt */
+ -5, /* (152) setlist ::= setlist COMMA nm EQ expr */
+ -7, /* (153) setlist ::= setlist COMMA LP idlist RP EQ expr */
+ -3, /* (154) setlist ::= nm EQ expr */
+ -5, /* (155) setlist ::= LP idlist RP EQ expr */
+ -7, /* (156) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
+ -7, /* (157) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
+ 0, /* (158) upsert ::= */
+ -11, /* (159) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
+ -8, /* (160) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
+ -4, /* (161) upsert ::= ON CONFLICT DO NOTHING */
+ -2, /* (162) insert_cmd ::= INSERT orconf */
+ -1, /* (163) insert_cmd ::= REPLACE */
+ 0, /* (164) idlist_opt ::= */
+ -3, /* (165) idlist_opt ::= LP idlist RP */
+ -3, /* (166) idlist ::= idlist COMMA nm */
+ -1, /* (167) idlist ::= nm */
+ -3, /* (168) expr ::= LP expr RP */
+ -1, /* (169) expr ::= ID|INDEXED */
+ -1, /* (170) expr ::= JOIN_KW */
+ -3, /* (171) expr ::= nm DOT nm */
+ -5, /* (172) expr ::= nm DOT nm DOT nm */
+ -1, /* (173) term ::= NULL|FLOAT|BLOB */
+ -1, /* (174) term ::= STRING */
+ -1, /* (175) term ::= INTEGER */
+ -1, /* (176) expr ::= VARIABLE */
+ -3, /* (177) expr ::= expr COLLATE ID|STRING */
+ -6, /* (178) expr ::= CAST LP expr AS typetoken RP */
+ -5, /* (179) expr ::= ID|INDEXED LP distinct exprlist RP */
+ -4, /* (180) expr ::= ID|INDEXED LP STAR RP */
+ -6, /* (181) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
+ -5, /* (182) expr ::= ID|INDEXED LP STAR RP filter_over */
+ -1, /* (183) term ::= CTIME_KW */
+ -5, /* (184) expr ::= LP nexprlist COMMA expr RP */
+ -3, /* (185) expr ::= expr AND expr */
+ -3, /* (186) expr ::= expr OR expr */
+ -3, /* (187) expr ::= expr LT|GT|GE|LE expr */
+ -3, /* (188) expr ::= expr EQ|NE expr */
+ -3, /* (189) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
+ -3, /* (190) expr ::= expr PLUS|MINUS expr */
+ -3, /* (191) expr ::= expr STAR|SLASH|REM expr */
+ -3, /* (192) expr ::= expr CONCAT expr */
+ -2, /* (193) likeop ::= NOT LIKE_KW|MATCH */
+ -3, /* (194) expr ::= expr likeop expr */
+ -5, /* (195) expr ::= expr likeop expr ESCAPE expr */
+ -2, /* (196) expr ::= expr ISNULL|NOTNULL */
+ -3, /* (197) expr ::= expr NOT NULL */
+ -3, /* (198) expr ::= expr IS expr */
+ -4, /* (199) expr ::= expr IS NOT expr */
+ -2, /* (200) expr ::= NOT expr */
+ -2, /* (201) expr ::= BITNOT expr */
+ -2, /* (202) expr ::= PLUS|MINUS expr */
+ -1, /* (203) between_op ::= BETWEEN */
+ -2, /* (204) between_op ::= NOT BETWEEN */
+ -5, /* (205) expr ::= expr between_op expr AND expr */
+ -1, /* (206) in_op ::= IN */
+ -2, /* (207) in_op ::= NOT IN */
+ -5, /* (208) expr ::= expr in_op LP exprlist RP */
+ -3, /* (209) expr ::= LP select RP */
+ -5, /* (210) expr ::= expr in_op LP select RP */
+ -5, /* (211) expr ::= expr in_op nm dbnm paren_exprlist */
+ -4, /* (212) expr ::= EXISTS LP select RP */
+ -5, /* (213) expr ::= CASE case_operand case_exprlist case_else END */
+ -5, /* (214) case_exprlist ::= case_exprlist WHEN expr THEN expr */
+ -4, /* (215) case_exprlist ::= WHEN expr THEN expr */
+ -2, /* (216) case_else ::= ELSE expr */
+ 0, /* (217) case_else ::= */
+ -1, /* (218) case_operand ::= expr */
+ 0, /* (219) case_operand ::= */
+ 0, /* (220) exprlist ::= */
+ -3, /* (221) nexprlist ::= nexprlist COMMA expr */
+ -1, /* (222) nexprlist ::= expr */
+ 0, /* (223) paren_exprlist ::= */
+ -3, /* (224) paren_exprlist ::= LP exprlist RP */
+ -12, /* (225) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
+ -1, /* (226) uniqueflag ::= UNIQUE */
+ 0, /* (227) uniqueflag ::= */
+ 0, /* (228) eidlist_opt ::= */
+ -3, /* (229) eidlist_opt ::= LP eidlist RP */
+ -5, /* (230) eidlist ::= eidlist COMMA nm collate sortorder */
+ -3, /* (231) eidlist ::= nm collate sortorder */
+ 0, /* (232) collate ::= */
+ -2, /* (233) collate ::= COLLATE ID|STRING */
+ -4, /* (234) cmd ::= DROP INDEX ifexists fullname */
+ -2, /* (235) cmd ::= VACUUM vinto */
+ -3, /* (236) cmd ::= VACUUM nm vinto */
+ -2, /* (237) vinto ::= INTO expr */
+ 0, /* (238) vinto ::= */
+ -3, /* (239) cmd ::= PRAGMA nm dbnm */
+ -5, /* (240) cmd ::= PRAGMA nm dbnm EQ nmnum */
+ -6, /* (241) cmd ::= PRAGMA nm dbnm LP nmnum RP */
+ -5, /* (242) cmd ::= PRAGMA nm dbnm EQ minus_num */
+ -6, /* (243) cmd ::= PRAGMA nm dbnm LP minus_num RP */
+ -2, /* (244) plus_num ::= PLUS INTEGER|FLOAT */
+ -2, /* (245) minus_num ::= MINUS INTEGER|FLOAT */
+ -5, /* (246) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
+ -11, /* (247) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
+ -1, /* (248) trigger_time ::= BEFORE|AFTER */
+ -2, /* (249) trigger_time ::= INSTEAD OF */
+ 0, /* (250) trigger_time ::= */
+ -1, /* (251) trigger_event ::= DELETE|INSERT */
+ -1, /* (252) trigger_event ::= UPDATE */
+ -3, /* (253) trigger_event ::= UPDATE OF idlist */
+ 0, /* (254) when_clause ::= */
+ -2, /* (255) when_clause ::= WHEN expr */
+ -3, /* (256) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
+ -2, /* (257) trigger_cmd_list ::= trigger_cmd SEMI */
+ -3, /* (258) trnm ::= nm DOT nm */
+ -3, /* (259) tridxby ::= INDEXED BY nm */
+ -2, /* (260) tridxby ::= NOT INDEXED */
+ -9, /* (261) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
+ -8, /* (262) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
+ -6, /* (263) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
+ -3, /* (264) trigger_cmd ::= scanpt select scanpt */
+ -4, /* (265) expr ::= RAISE LP IGNORE RP */
+ -6, /* (266) expr ::= RAISE LP raisetype COMMA nm RP */
+ -1, /* (267) raisetype ::= ROLLBACK */
+ -1, /* (268) raisetype ::= ABORT */
+ -1, /* (269) raisetype ::= FAIL */
+ -4, /* (270) cmd ::= DROP TRIGGER ifexists fullname */
+ -6, /* (271) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
+ -3, /* (272) cmd ::= DETACH database_kw_opt expr */
+ 0, /* (273) key_opt ::= */
+ -2, /* (274) key_opt ::= KEY expr */
+ -1, /* (275) cmd ::= REINDEX */
+ -3, /* (276) cmd ::= REINDEX nm dbnm */
+ -1, /* (277) cmd ::= ANALYZE */
+ -3, /* (278) cmd ::= ANALYZE nm dbnm */
+ -6, /* (279) cmd ::= ALTER TABLE fullname RENAME TO nm */
+ -7, /* (280) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
+ -1, /* (281) add_column_fullname ::= fullname */
+ -8, /* (282) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
+ -1, /* (283) cmd ::= create_vtab */
+ -4, /* (284) cmd ::= create_vtab LP vtabarglist RP */
+ -8, /* (285) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
+ 0, /* (286) vtabarg ::= */
+ -1, /* (287) vtabargtoken ::= ANY */
+ -3, /* (288) vtabargtoken ::= lp anylist RP */
+ -1, /* (289) lp ::= LP */
+ -2, /* (290) with ::= WITH wqlist */
+ -3, /* (291) with ::= WITH RECURSIVE wqlist */
+ -6, /* (292) wqlist ::= nm eidlist_opt AS LP select RP */
+ -8, /* (293) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
+ -1, /* (294) windowdefn_list ::= windowdefn */
+ -3, /* (295) windowdefn_list ::= windowdefn_list COMMA windowdefn */
+ -5, /* (296) windowdefn ::= nm AS LP window RP */
+ -5, /* (297) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
+ -6, /* (298) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
+ -4, /* (299) window ::= ORDER BY sortlist frame_opt */
+ -5, /* (300) window ::= nm ORDER BY sortlist frame_opt */
+ -1, /* (301) window ::= frame_opt */
+ -2, /* (302) window ::= nm frame_opt */
+ 0, /* (303) frame_opt ::= */
+ -3, /* (304) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
+ -6, /* (305) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
+ -1, /* (306) range_or_rows ::= RANGE|ROWS|GROUPS */
+ -1, /* (307) frame_bound_s ::= frame_bound */
+ -2, /* (308) frame_bound_s ::= UNBOUNDED PRECEDING */
+ -1, /* (309) frame_bound_e ::= frame_bound */
+ -2, /* (310) frame_bound_e ::= UNBOUNDED FOLLOWING */
+ -2, /* (311) frame_bound ::= expr PRECEDING|FOLLOWING */
+ -2, /* (312) frame_bound ::= CURRENT ROW */
+ 0, /* (313) frame_exclude_opt ::= */
+ -2, /* (314) frame_exclude_opt ::= EXCLUDE frame_exclude */
+ -2, /* (315) frame_exclude ::= NO OTHERS */
+ -2, /* (316) frame_exclude ::= CURRENT ROW */
+ -1, /* (317) frame_exclude ::= GROUP|TIES */
+ -2, /* (318) window_clause ::= WINDOW windowdefn_list */
+ -2, /* (319) filter_over ::= filter_clause over_clause */
+ -1, /* (320) filter_over ::= over_clause */
+ -1, /* (321) filter_over ::= filter_clause */
+ -4, /* (322) over_clause ::= OVER LP window RP */
+ -2, /* (323) over_clause ::= OVER nm */
+ -5, /* (324) filter_clause ::= FILTER LP WHERE expr RP */
+ -1, /* (325) input ::= cmdlist */
+ -2, /* (326) cmdlist ::= cmdlist ecmd */
+ -1, /* (327) cmdlist ::= ecmd */
+ -1, /* (328) ecmd ::= SEMI */
+ -2, /* (329) ecmd ::= cmdx SEMI */
+ -3, /* (330) ecmd ::= explain cmdx SEMI */
+ 0, /* (331) trans_opt ::= */
+ -1, /* (332) trans_opt ::= TRANSACTION */
+ -2, /* (333) trans_opt ::= TRANSACTION nm */
+ -1, /* (334) savepoint_opt ::= SAVEPOINT */
+ 0, /* (335) savepoint_opt ::= */
+ -2, /* (336) cmd ::= create_table create_table_args */
+ -4, /* (337) columnlist ::= columnlist COMMA columnname carglist */
+ -2, /* (338) columnlist ::= columnname carglist */
+ -1, /* (339) nm ::= ID|INDEXED */
+ -1, /* (340) nm ::= STRING */
+ -1, /* (341) nm ::= JOIN_KW */
+ -1, /* (342) typetoken ::= typename */
+ -1, /* (343) typename ::= ID|STRING */
+ -1, /* (344) signed ::= plus_num */
+ -1, /* (345) signed ::= minus_num */
+ -2, /* (346) carglist ::= carglist ccons */
+ 0, /* (347) carglist ::= */
+ -2, /* (348) ccons ::= NULL onconf */
+ -4, /* (349) ccons ::= GENERATED ALWAYS AS generated */
+ -2, /* (350) ccons ::= AS generated */
+ -2, /* (351) conslist_opt ::= COMMA conslist */
+ -3, /* (352) conslist ::= conslist tconscomma tcons */
+ -1, /* (353) conslist ::= tcons */
+ 0, /* (354) tconscomma ::= */
+ -1, /* (355) defer_subclause_opt ::= defer_subclause */
+ -1, /* (356) resolvetype ::= raisetype */
+ -1, /* (357) selectnowith ::= oneselect */
+ -1, /* (358) oneselect ::= values */
+ -2, /* (359) sclp ::= selcollist COMMA */
+ -1, /* (360) as ::= ID|STRING */
+ -1, /* (361) expr ::= term */
+ -1, /* (362) likeop ::= LIKE_KW|MATCH */
+ -1, /* (363) exprlist ::= nexprlist */
+ -1, /* (364) nmnum ::= plus_num */
+ -1, /* (365) nmnum ::= nm */
+ -1, /* (366) nmnum ::= ON */
+ -1, /* (367) nmnum ::= DELETE */
+ -1, /* (368) nmnum ::= DEFAULT */
+ -1, /* (369) plus_num ::= INTEGER|FLOAT */
+ 0, /* (370) foreach_clause ::= */
+ -3, /* (371) foreach_clause ::= FOR EACH ROW */
+ -1, /* (372) trnm ::= nm */
+ 0, /* (373) tridxby ::= */
+ -1, /* (374) database_kw_opt ::= DATABASE */
+ 0, /* (375) database_kw_opt ::= */
+ 0, /* (376) kwcolumn_opt ::= */
+ -1, /* (377) kwcolumn_opt ::= COLUMNKW */
+ -1, /* (378) vtabarglist ::= vtabarg */
+ -3, /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */
+ -2, /* (380) vtabarg ::= vtabarg vtabargtoken */
+ 0, /* (381) anylist ::= */
+ -4, /* (382) anylist ::= anylist LP anylist RP */
+ -2, /* (383) anylist ::= anylist ANY */
+ 0, /* (384) with ::= */
+};
+
+static void yy_accept(yyParser*); /* Forward Declaration */
+
+/*
+** Perform a reduce action and the shift that must immediately
+** follow the reduce.
+**
+** The yyLookahead and yyLookaheadToken parameters provide reduce actions
+** access to the lookahead token (if any). The yyLookahead will be YYNOCODE
+** if the lookahead token has already been consumed. As this procedure is
+** only called from one place, optimizing compilers will in-line it, which
+** means that the extra parameters have no performance impact.
+*/
+static YYACTIONTYPE yy_reduce(
+ yyParser *yypParser, /* The parser */
+ unsigned int yyruleno, /* Number of the rule by which to reduce */
+ int yyLookahead, /* Lookahead token, or YYNOCODE if none */
+ sqlite3ParserTOKENTYPE yyLookaheadToken /* Value of the lookahead token */
+ sqlite3ParserCTX_PDECL /* %extra_context */
+){
+ int yygoto; /* The next state */
+ YYACTIONTYPE yyact; /* The next action */
+ yyStackEntry *yymsp; /* The top of the parser's stack */
+ int yysize; /* Amount to pop the stack */
+ sqlite3ParserARG_FETCH
+ (void)yyLookahead;
+ (void)yyLookaheadToken;
+ yymsp = yypParser->yytos;
+ assert( yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) );
+#ifndef NDEBUG
+ if( yyTraceFILE ){
+ yysize = yyRuleInfoNRhs[yyruleno];
+ if( yysize ){
+ fprintf(yyTraceFILE, "%sReduce %d [%s]%s, pop back to state %d.\n",
+ yyTracePrompt,
+ yyruleno, yyRuleName[yyruleno],
+ yyruleno<YYNRULE_WITH_ACTION ? "" : " without external action",
+ yymsp[yysize].stateno);
+ }else{
+ fprintf(yyTraceFILE, "%sReduce %d [%s]%s.\n",
+ yyTracePrompt, yyruleno, yyRuleName[yyruleno],
+ yyruleno<YYNRULE_WITH_ACTION ? "" : " without external action");
+ }
+ }
+#endif /* NDEBUG */
+
+ /* Check that the stack is large enough to grow by a single entry
+ ** if the RHS of the rule is empty. This ensures that there is room
+ ** enough on the stack to push the LHS value */
+ if( yyRuleInfoNRhs[yyruleno]==0 ){
+#ifdef YYTRACKMAXSTACKDEPTH
+ if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
+ yypParser->yyhwm++;
+ assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
+ }
+#endif
+#if YYSTACKDEPTH>0
+ if( yypParser->yytos>=yypParser->yystackEnd ){
+ yyStackOverflow(yypParser);
+ /* The call to yyStackOverflow() above pops the stack until it is
+ ** empty, causing the main parser loop to exit. So the return value
+ ** is never used and does not matter. */
+ return 0;
+ }
+#else
+ if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
+ if( yyGrowStack(yypParser) ){
+ yyStackOverflow(yypParser);
+ /* The call to yyStackOverflow() above pops the stack until it is
+ ** empty, causing the main parser loop to exit. So the return value
+ ** is never used and does not matter. */
+ return 0;
+ }
+ yymsp = yypParser->yytos;
+ }
+#endif
+ }
+
+ switch( yyruleno ){
+ /* Beginning here are the reduction cases. A typical example
+ ** follows:
+ ** case 0:
+ ** #line <lineno> <grammarfile>
+ ** { ... } // User supplied code
+ ** #line <lineno> <thisfile>
+ ** break;
+ */
+/********** Begin reduce actions **********************************************/
+ YYMINORTYPE yylhsminor;
+ case 0: /* explain ::= EXPLAIN */
+{ pParse->explain = 1; }
+ break;
+ case 1: /* explain ::= EXPLAIN QUERY PLAN */
+{ pParse->explain = 2; }
+ break;
+ case 2: /* cmdx ::= cmd */
+{ sqlite3FinishCoding(pParse); }
+ break;
+ case 3: /* cmd ::= BEGIN transtype trans_opt */
+{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy192);}
+ break;
+ case 4: /* transtype ::= */
+{yymsp[1].minor.yy192 = TK_DEFERRED;}
+ break;
+ case 5: /* transtype ::= DEFERRED */
+ case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
+ case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
+ case 306: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==306);
+{yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-X*/}
+ break;
+ case 8: /* cmd ::= COMMIT|END trans_opt */
+ case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
+{sqlite3EndTransaction(pParse,yymsp[-1].major);}
+ break;
+ case 10: /* cmd ::= SAVEPOINT nm */
+{
+ sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
+}
+ break;
+ case 11: /* cmd ::= RELEASE savepoint_opt nm */
+{
+ sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
+}
+ break;
+ case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
+{
+ sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
+}
+ break;
+ case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
+{
+ sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy192,0,0,yymsp[-2].minor.yy192);
+}
+ break;
+ case 14: /* createkw ::= CREATE */
+{disableLookaside(pParse);}
+ break;
+ case 15: /* ifnotexists ::= */
+ case 18: /* temp ::= */ yytestcase(yyruleno==18);
+ case 21: /* table_options ::= */ yytestcase(yyruleno==21);
+ case 45: /* autoinc ::= */ yytestcase(yyruleno==45);
+ case 60: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==60);
+ case 70: /* defer_subclause_opt ::= */ yytestcase(yyruleno==70);
+ case 79: /* ifexists ::= */ yytestcase(yyruleno==79);
+ case 96: /* distinct ::= */ yytestcase(yyruleno==96);
+ case 232: /* collate ::= */ yytestcase(yyruleno==232);
+{yymsp[1].minor.yy192 = 0;}
+ break;
+ case 16: /* ifnotexists ::= IF NOT EXISTS */
+{yymsp[-2].minor.yy192 = 1;}
+ break;
+ case 17: /* temp ::= TEMP */
+ case 46: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==46);
+{yymsp[0].minor.yy192 = 1;}
+ break;
+ case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
+{
+ sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy192,0);
+}
+ break;
+ case 20: /* create_table_args ::= AS select */
+{
+ sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy539);
+ sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy539);
+}
+ break;
+ case 22: /* table_options ::= WITHOUT nm */
+{
+ if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
+ yymsp[-1].minor.yy192 = TF_WithoutRowid | TF_NoVisibleRowid;
+ }else{
+ yymsp[-1].minor.yy192 = 0;
+ sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
+ }
+}
+ break;
+ case 23: /* columnname ::= nm typetoken */
+{sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
+ break;
+ case 24: /* typetoken ::= */
+ case 63: /* conslist_opt ::= */ yytestcase(yyruleno==63);
+ case 102: /* as ::= */ yytestcase(yyruleno==102);
+{yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
+ break;
+ case 25: /* typetoken ::= typename LP signed RP */
+{
+ yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
+}
+ break;
+ case 26: /* typetoken ::= typename LP signed COMMA signed RP */
+{
+ yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
+}
+ break;
+ case 27: /* typename ::= typename ID|STRING */
+{yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
+ break;
+ case 28: /* scanpt ::= */
+{
+ assert( yyLookahead!=YYNOCODE );
+ yymsp[1].minor.yy436 = yyLookaheadToken.z;
+}
+ break;
+ case 29: /* scantok ::= */
+{
+ assert( yyLookahead!=YYNOCODE );
+ yymsp[1].minor.yy0 = yyLookaheadToken;
+}
+ break;
+ case 30: /* ccons ::= CONSTRAINT nm */
+ case 65: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==65);
+{pParse->constraintName = yymsp[0].minor.yy0;}
+ break;
+ case 31: /* ccons ::= DEFAULT scantok term */
+{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy202,yymsp[-1].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
+ break;
+ case 32: /* ccons ::= DEFAULT LP expr RP */
+{sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy202,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
+ break;
+ case 33: /* ccons ::= DEFAULT PLUS scantok term */
+{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy202,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
+ break;
+ case 34: /* ccons ::= DEFAULT MINUS scantok term */
+{
+ Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy202, 0);
+ sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);
+}
+ break;
+ case 35: /* ccons ::= DEFAULT scantok ID|INDEXED */
+{
+ Expr *p = tokenExpr(pParse, TK_STRING, yymsp[0].minor.yy0);
+ if( p ){
+ sqlite3ExprIdToTrueFalse(p);
+ testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) );
+ }
+ sqlite3AddDefaultValue(pParse,p,yymsp[0].minor.yy0.z,yymsp[0].minor.yy0.z+yymsp[0].minor.yy0.n);
+}
+ break;
+ case 36: /* ccons ::= NOT NULL onconf */
+{sqlite3AddNotNull(pParse, yymsp[0].minor.yy192);}
+ break;
+ case 37: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
+{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy192,yymsp[0].minor.yy192,yymsp[-2].minor.yy192);}
+ break;
+ case 38: /* ccons ::= UNIQUE onconf */
+{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy192,0,0,0,0,
+ SQLITE_IDXTYPE_UNIQUE);}
+ break;
+ case 39: /* ccons ::= CHECK LP expr RP */
+{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy202,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy0.z);}
+ break;
+ case 40: /* ccons ::= REFERENCES nm eidlist_opt refargs */
+{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy242,yymsp[0].minor.yy192);}
+ break;
+ case 41: /* ccons ::= defer_subclause */
+{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy192);}
+ break;
+ case 42: /* ccons ::= COLLATE ID|STRING */
+{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
+ break;
+ case 43: /* generated ::= LP expr RP */
+{sqlite3AddGenerated(pParse,yymsp[-1].minor.yy202,0);}
+ break;
+ case 44: /* generated ::= LP expr RP ID */
+{sqlite3AddGenerated(pParse,yymsp[-2].minor.yy202,&yymsp[0].minor.yy0);}
+ break;
+ case 47: /* refargs ::= */
+{ yymsp[1].minor.yy192 = OE_None*0x0101; /* EV: R-19803-45884 */}
+ break;
+ case 48: /* refargs ::= refargs refarg */
+{ yymsp[-1].minor.yy192 = (yymsp[-1].minor.yy192 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
+ break;
+ case 49: /* refarg ::= MATCH nm */
+{ yymsp[-1].minor.yy207.value = 0; yymsp[-1].minor.yy207.mask = 0x000000; }
+ break;
+ case 50: /* refarg ::= ON INSERT refact */
+{ yymsp[-2].minor.yy207.value = 0; yymsp[-2].minor.yy207.mask = 0x000000; }
+ break;
+ case 51: /* refarg ::= ON DELETE refact */
+{ yymsp[-2].minor.yy207.value = yymsp[0].minor.yy192; yymsp[-2].minor.yy207.mask = 0x0000ff; }
+ break;
+ case 52: /* refarg ::= ON UPDATE refact */
+{ yymsp[-2].minor.yy207.value = yymsp[0].minor.yy192<<8; yymsp[-2].minor.yy207.mask = 0x00ff00; }
+ break;
+ case 53: /* refact ::= SET NULL */
+{ yymsp[-1].minor.yy192 = OE_SetNull; /* EV: R-33326-45252 */}
+ break;
+ case 54: /* refact ::= SET DEFAULT */
+{ yymsp[-1].minor.yy192 = OE_SetDflt; /* EV: R-33326-45252 */}
+ break;
+ case 55: /* refact ::= CASCADE */
+{ yymsp[0].minor.yy192 = OE_Cascade; /* EV: R-33326-45252 */}
+ break;
+ case 56: /* refact ::= RESTRICT */
+{ yymsp[0].minor.yy192 = OE_Restrict; /* EV: R-33326-45252 */}
+ break;
+ case 57: /* refact ::= NO ACTION */
+{ yymsp[-1].minor.yy192 = OE_None; /* EV: R-33326-45252 */}
+ break;
+ case 58: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
+{yymsp[-2].minor.yy192 = 0;}
+ break;
+ case 59: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
+ case 74: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==74);
+ case 162: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==162);
+{yymsp[-1].minor.yy192 = yymsp[0].minor.yy192;}
+ break;
+ case 61: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
+ case 78: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==78);
+ case 204: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==204);
+ case 207: /* in_op ::= NOT IN */ yytestcase(yyruleno==207);
+ case 233: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==233);
+{yymsp[-1].minor.yy192 = 1;}
+ break;
+ case 62: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
+{yymsp[-1].minor.yy192 = 0;}
+ break;
+ case 64: /* tconscomma ::= COMMA */
+{pParse->constraintName.n = 0;}
+ break;
+ case 66: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
+{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy242,yymsp[0].minor.yy192,yymsp[-2].minor.yy192,0);}
+ break;
+ case 67: /* tcons ::= UNIQUE LP sortlist RP onconf */
+{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy242,yymsp[0].minor.yy192,0,0,0,0,
+ SQLITE_IDXTYPE_UNIQUE);}
+ break;
+ case 68: /* tcons ::= CHECK LP expr RP onconf */
+{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy202,yymsp[-3].minor.yy0.z,yymsp[-1].minor.yy0.z);}
+ break;
+ case 69: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
+{
+ sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy242, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy242, yymsp[-1].minor.yy192);
+ sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy192);
+}
+ break;
+ case 71: /* onconf ::= */
+ case 73: /* orconf ::= */ yytestcase(yyruleno==73);
+{yymsp[1].minor.yy192 = OE_Default;}
+ break;
+ case 72: /* onconf ::= ON CONFLICT resolvetype */
+{yymsp[-2].minor.yy192 = yymsp[0].minor.yy192;}
+ break;
+ case 75: /* resolvetype ::= IGNORE */
+{yymsp[0].minor.yy192 = OE_Ignore;}
+ break;
+ case 76: /* resolvetype ::= REPLACE */
+ case 163: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==163);
+{yymsp[0].minor.yy192 = OE_Replace;}
+ break;
+ case 77: /* cmd ::= DROP TABLE ifexists fullname */
+{
+ sqlite3DropTable(pParse, yymsp[0].minor.yy47, 0, yymsp[-1].minor.yy192);
+}
+ break;
+ case 80: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
+{
+ sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy242, yymsp[0].minor.yy539, yymsp[-7].minor.yy192, yymsp[-5].minor.yy192);
+}
+ break;
+ case 81: /* cmd ::= DROP VIEW ifexists fullname */
+{
+ sqlite3DropTable(pParse, yymsp[0].minor.yy47, 1, yymsp[-1].minor.yy192);
+}
+ break;
+ case 82: /* cmd ::= select */
+{
+ SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0, 0};
+ sqlite3Select(pParse, yymsp[0].minor.yy539, &dest);
+ sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy539);
+}
+ break;
+ case 83: /* select ::= WITH wqlist selectnowith */
+{
+ Select *p = yymsp[0].minor.yy539;
+ if( p ){
+ p->pWith = yymsp[-1].minor.yy131;
+ parserDoubleLinkSelect(pParse, p);
+ }else{
+ sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy131);
+ }
+ yymsp[-2].minor.yy539 = p;
+}
+ break;
+ case 84: /* select ::= WITH RECURSIVE wqlist selectnowith */
+{
+ Select *p = yymsp[0].minor.yy539;
+ if( p ){
+ p->pWith = yymsp[-1].minor.yy131;
+ parserDoubleLinkSelect(pParse, p);
+ }else{
+ sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy131);
+ }
+ yymsp[-3].minor.yy539 = p;
+}
+ break;
+ case 85: /* select ::= selectnowith */
+{
+ Select *p = yymsp[0].minor.yy539;
+ if( p ){
+ parserDoubleLinkSelect(pParse, p);
+ }
+ yymsp[0].minor.yy539 = p; /*A-overwrites-X*/
+}
+ break;
+ case 86: /* selectnowith ::= selectnowith multiselect_op oneselect */
+{
+ Select *pRhs = yymsp[0].minor.yy539;
+ Select *pLhs = yymsp[-2].minor.yy539;
+ if( pRhs && pRhs->pPrior ){
+ SrcList *pFrom;
+ Token x;
+ x.n = 0;
+ parserDoubleLinkSelect(pParse, pRhs);
+ pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
+ pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
+ }
+ if( pRhs ){
+ pRhs->op = (u8)yymsp[-1].minor.yy192;
+ pRhs->pPrior = pLhs;
+ if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
+ pRhs->selFlags &= ~SF_MultiValue;
+ if( yymsp[-1].minor.yy192!=TK_ALL ) pParse->hasCompound = 1;
+ }else{
+ sqlite3SelectDelete(pParse->db, pLhs);
+ }
+ yymsp[-2].minor.yy539 = pRhs;
+}
+ break;
+ case 87: /* multiselect_op ::= UNION */
+ case 89: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==89);
+{yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-OP*/}
+ break;
+ case 88: /* multiselect_op ::= UNION ALL */
+{yymsp[-1].minor.yy192 = TK_ALL;}
+ break;
+ case 90: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
+{
+ yymsp[-8].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy242,yymsp[-5].minor.yy47,yymsp[-4].minor.yy202,yymsp[-3].minor.yy242,yymsp[-2].minor.yy202,yymsp[-1].minor.yy242,yymsp[-7].minor.yy192,yymsp[0].minor.yy202);
+}
+ break;
+ case 91: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
+{
+ yymsp[-9].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-7].minor.yy242,yymsp[-6].minor.yy47,yymsp[-5].minor.yy202,yymsp[-4].minor.yy242,yymsp[-3].minor.yy202,yymsp[-1].minor.yy242,yymsp[-8].minor.yy192,yymsp[0].minor.yy202);
+ if( yymsp[-9].minor.yy539 ){
+ yymsp[-9].minor.yy539->pWinDefn = yymsp[-2].minor.yy303;
+ }else{
+ sqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy303);
+ }
+}
+ break;
+ case 92: /* values ::= VALUES LP nexprlist RP */
+{
+ yymsp[-3].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy242,0,0,0,0,0,SF_Values,0);
+}
+ break;
+ case 93: /* values ::= values COMMA LP nexprlist RP */
+{
+ Select *pRight, *pLeft = yymsp[-4].minor.yy539;
+ pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy242,0,0,0,0,0,SF_Values|SF_MultiValue,0);
+ if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
+ if( pRight ){
+ pRight->op = TK_ALL;
+ pRight->pPrior = pLeft;
+ yymsp[-4].minor.yy539 = pRight;
+ }else{
+ yymsp[-4].minor.yy539 = pLeft;
+ }
+}
+ break;
+ case 94: /* distinct ::= DISTINCT */
+{yymsp[0].minor.yy192 = SF_Distinct;}
+ break;
+ case 95: /* distinct ::= ALL */
+{yymsp[0].minor.yy192 = SF_All;}
+ break;
+ case 97: /* sclp ::= */
+ case 130: /* orderby_opt ::= */ yytestcase(yyruleno==130);
+ case 140: /* groupby_opt ::= */ yytestcase(yyruleno==140);
+ case 220: /* exprlist ::= */ yytestcase(yyruleno==220);
+ case 223: /* paren_exprlist ::= */ yytestcase(yyruleno==223);
+ case 228: /* eidlist_opt ::= */ yytestcase(yyruleno==228);
+{yymsp[1].minor.yy242 = 0;}
+ break;
+ case 98: /* selcollist ::= sclp scanpt expr scanpt as */
+{
+ yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy242, yymsp[-2].minor.yy202);
+ if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy242, &yymsp[0].minor.yy0, 1);
+ sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy242,yymsp[-3].minor.yy436,yymsp[-1].minor.yy436);
+}
+ break;
+ case 99: /* selcollist ::= sclp scanpt STAR */
+{
+ Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
+ yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy242, p);
+}
+ break;
+ case 100: /* selcollist ::= sclp scanpt nm DOT STAR */
+{
+ Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
+ Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
+ Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
+ yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, pDot);
+}
+ break;
+ case 101: /* as ::= AS nm */
+ case 112: /* dbnm ::= DOT nm */ yytestcase(yyruleno==112);
+ case 244: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==244);
+ case 245: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==245);
+{yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
+ break;
+ case 103: /* from ::= */
+ case 106: /* stl_prefix ::= */ yytestcase(yyruleno==106);
+{yymsp[1].minor.yy47 = 0;}
+ break;
+ case 104: /* from ::= FROM seltablist */
+{
+ yymsp[-1].minor.yy47 = yymsp[0].minor.yy47;
+ sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy47);
+}
+ break;
+ case 105: /* stl_prefix ::= seltablist joinop */
+{
+ if( ALWAYS(yymsp[-1].minor.yy47 && yymsp[-1].minor.yy47->nSrc>0) ) yymsp[-1].minor.yy47->a[yymsp[-1].minor.yy47->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy192;
+}
+ break;
+ case 107: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
+{
+ yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
+ sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy47, &yymsp[-2].minor.yy0);
+}
+ break;
+ case 108: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
+{
+ yymsp[-8].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy47,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
+ sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy47, yymsp[-4].minor.yy242);
+}
+ break;
+ case 109: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
+{
+ yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy539,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
+ }
+ break;
+ case 110: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
+{
+ if( yymsp[-6].minor.yy47==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy202==0 && yymsp[0].minor.yy600==0 ){
+ yymsp[-6].minor.yy47 = yymsp[-4].minor.yy47;
+ }else if( yymsp[-4].minor.yy47->nSrc==1 ){
+ yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
+ if( yymsp[-6].minor.yy47 ){
+ struct SrcList_item *pNew = &yymsp[-6].minor.yy47->a[yymsp[-6].minor.yy47->nSrc-1];
+ struct SrcList_item *pOld = yymsp[-4].minor.yy47->a;
+ pNew->zName = pOld->zName;
+ pNew->zDatabase = pOld->zDatabase;
+ pNew->pSelect = pOld->pSelect;
+ if( pOld->fg.isTabFunc ){
+ pNew->u1.pFuncArg = pOld->u1.pFuncArg;
+ pOld->u1.pFuncArg = 0;
+ pOld->fg.isTabFunc = 0;
+ pNew->fg.isTabFunc = 1;
+ }
+ pOld->zName = pOld->zDatabase = 0;
+ pOld->pSelect = 0;
+ }
+ sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy47);
+ }else{
+ Select *pSubquery;
+ sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy47);
+ pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy47,0,0,0,0,SF_NestedFrom,0);
+ yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
+ }
+ }
+ break;
+ case 111: /* dbnm ::= */
+ case 125: /* indexed_opt ::= */ yytestcase(yyruleno==125);
+{yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
+ break;
+ case 113: /* fullname ::= nm */
+{
+ yylhsminor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0);
+ if( IN_RENAME_OBJECT && yylhsminor.yy47 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy47->a[0].zName, &yymsp[0].minor.yy0);
+}
+ yymsp[0].minor.yy47 = yylhsminor.yy47;
+ break;
+ case 114: /* fullname ::= nm DOT nm */
+{
+ yylhsminor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
+ if( IN_RENAME_OBJECT && yylhsminor.yy47 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy47->a[0].zName, &yymsp[0].minor.yy0);
+}
+ yymsp[-2].minor.yy47 = yylhsminor.yy47;
+ break;
+ case 115: /* xfullname ::= nm */
+{yymsp[0].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}
+ break;
+ case 116: /* xfullname ::= nm DOT nm */
+{yymsp[-2].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
+ break;
+ case 117: /* xfullname ::= nm DOT nm AS nm */
+{
+ yymsp[-4].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/
+ if( yymsp[-4].minor.yy47 ) yymsp[-4].minor.yy47->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
+}
+ break;
+ case 118: /* xfullname ::= nm AS nm */
+{
+ yymsp[-2].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/
+ if( yymsp[-2].minor.yy47 ) yymsp[-2].minor.yy47->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
+}
+ break;
+ case 119: /* joinop ::= COMMA|JOIN */
+{ yymsp[0].minor.yy192 = JT_INNER; }
+ break;
+ case 120: /* joinop ::= JOIN_KW JOIN */
+{yymsp[-1].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
+ break;
+ case 121: /* joinop ::= JOIN_KW nm JOIN */
+{yymsp[-2].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
+ break;
+ case 122: /* joinop ::= JOIN_KW nm nm JOIN */
+{yymsp[-3].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
+ break;
+ case 123: /* on_opt ::= ON expr */
+ case 143: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==143);
+ case 150: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==150);
+ case 216: /* case_else ::= ELSE expr */ yytestcase(yyruleno==216);
+ case 237: /* vinto ::= INTO expr */ yytestcase(yyruleno==237);
+{yymsp[-1].minor.yy202 = yymsp[0].minor.yy202;}
+ break;
+ case 124: /* on_opt ::= */
+ case 142: /* having_opt ::= */ yytestcase(yyruleno==142);
+ case 144: /* limit_opt ::= */ yytestcase(yyruleno==144);
+ case 149: /* where_opt ::= */ yytestcase(yyruleno==149);
+ case 217: /* case_else ::= */ yytestcase(yyruleno==217);
+ case 219: /* case_operand ::= */ yytestcase(yyruleno==219);
+ case 238: /* vinto ::= */ yytestcase(yyruleno==238);
+{yymsp[1].minor.yy202 = 0;}
+ break;
+ case 126: /* indexed_opt ::= INDEXED BY nm */
+{yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
+ break;
+ case 127: /* indexed_opt ::= NOT INDEXED */
+{yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
+ break;
+ case 128: /* using_opt ::= USING LP idlist RP */
+{yymsp[-3].minor.yy600 = yymsp[-1].minor.yy600;}
+ break;
+ case 129: /* using_opt ::= */
+ case 164: /* idlist_opt ::= */ yytestcase(yyruleno==164);
+{yymsp[1].minor.yy600 = 0;}
+ break;
+ case 131: /* orderby_opt ::= ORDER BY sortlist */
+ case 141: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==141);
+{yymsp[-2].minor.yy242 = yymsp[0].minor.yy242;}
+ break;
+ case 132: /* sortlist ::= sortlist COMMA expr sortorder nulls */
+{
+ yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242,yymsp[-2].minor.yy202);
+ sqlite3ExprListSetSortOrder(yymsp[-4].minor.yy242,yymsp[-1].minor.yy192,yymsp[0].minor.yy192);
+}
+ break;
+ case 133: /* sortlist ::= expr sortorder nulls */
+{
+ yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[-2].minor.yy202); /*A-overwrites-Y*/
+ sqlite3ExprListSetSortOrder(yymsp[-2].minor.yy242,yymsp[-1].minor.yy192,yymsp[0].minor.yy192);
+}
+ break;
+ case 134: /* sortorder ::= ASC */
+{yymsp[0].minor.yy192 = SQLITE_SO_ASC;}
+ break;
+ case 135: /* sortorder ::= DESC */
+{yymsp[0].minor.yy192 = SQLITE_SO_DESC;}
+ break;
+ case 136: /* sortorder ::= */
+ case 139: /* nulls ::= */ yytestcase(yyruleno==139);
+{yymsp[1].minor.yy192 = SQLITE_SO_UNDEFINED;}
+ break;
+ case 137: /* nulls ::= NULLS FIRST */
+{yymsp[-1].minor.yy192 = SQLITE_SO_ASC;}
+ break;
+ case 138: /* nulls ::= NULLS LAST */
+{yymsp[-1].minor.yy192 = SQLITE_SO_DESC;}
+ break;
+ case 145: /* limit_opt ::= LIMIT expr */
+{yymsp[-1].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy202,0);}
+ break;
+ case 146: /* limit_opt ::= LIMIT expr OFFSET expr */
+{yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);}
+ break;
+ case 147: /* limit_opt ::= LIMIT expr COMMA expr */
+{yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy202,yymsp[-2].minor.yy202);}
+ break;
+ case 148: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
+{
+ sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy47, &yymsp[-1].minor.yy0);
+ sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy47,yymsp[0].minor.yy202,0,0);
+}
+ break;
+ case 151: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt */
+{
+ sqlite3SrcListIndexedBy(pParse, yymsp[-5].minor.yy47, &yymsp[-4].minor.yy0);
+ sqlite3ExprListCheckLength(pParse,yymsp[-2].minor.yy242,"set list");
+ yymsp[-5].minor.yy47 = sqlite3SrcListAppendList(pParse, yymsp[-5].minor.yy47, yymsp[-1].minor.yy47);
+ sqlite3Update(pParse,yymsp[-5].minor.yy47,yymsp[-2].minor.yy242,yymsp[0].minor.yy202,yymsp[-6].minor.yy192,0,0,0);
+}
+ break;
+ case 152: /* setlist ::= setlist COMMA nm EQ expr */
+{
+ yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy242, yymsp[0].minor.yy202);
+ sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy242, &yymsp[-2].minor.yy0, 1);
+}
+ break;
+ case 153: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
+{
+ yymsp[-6].minor.yy242 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy242, yymsp[-3].minor.yy600, yymsp[0].minor.yy202);
+}
+ break;
+ case 154: /* setlist ::= nm EQ expr */
+{
+ yylhsminor.yy242 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy202);
+ sqlite3ExprListSetName(pParse, yylhsminor.yy242, &yymsp[-2].minor.yy0, 1);
+}
+ yymsp[-2].minor.yy242 = yylhsminor.yy242;
+ break;
+ case 155: /* setlist ::= LP idlist RP EQ expr */
+{
+ yymsp[-4].minor.yy242 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy600, yymsp[0].minor.yy202);
+}
+ break;
+ case 156: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
+{
+ sqlite3Insert(pParse, yymsp[-3].minor.yy47, yymsp[-1].minor.yy539, yymsp[-2].minor.yy600, yymsp[-5].minor.yy192, yymsp[0].minor.yy318);
+}
+ break;
+ case 157: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
+{
+ sqlite3Insert(pParse, yymsp[-3].minor.yy47, 0, yymsp[-2].minor.yy600, yymsp[-5].minor.yy192, 0);
+}
+ break;
+ case 158: /* upsert ::= */
+{ yymsp[1].minor.yy318 = 0; }
+ break;
+ case 159: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
+{ yymsp[-10].minor.yy318 = sqlite3UpsertNew(pParse->db,yymsp[-7].minor.yy242,yymsp[-5].minor.yy202,yymsp[-1].minor.yy242,yymsp[0].minor.yy202);}
+ break;
+ case 160: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
+{ yymsp[-7].minor.yy318 = sqlite3UpsertNew(pParse->db,yymsp[-4].minor.yy242,yymsp[-2].minor.yy202,0,0); }
+ break;
+ case 161: /* upsert ::= ON CONFLICT DO NOTHING */
+{ yymsp[-3].minor.yy318 = sqlite3UpsertNew(pParse->db,0,0,0,0); }
+ break;
+ case 165: /* idlist_opt ::= LP idlist RP */
+{yymsp[-2].minor.yy600 = yymsp[-1].minor.yy600;}
+ break;
+ case 166: /* idlist ::= idlist COMMA nm */
+{yymsp[-2].minor.yy600 = sqlite3IdListAppend(pParse,yymsp[-2].minor.yy600,&yymsp[0].minor.yy0);}
+ break;
+ case 167: /* idlist ::= nm */
+{yymsp[0].minor.yy600 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
+ break;
+ case 168: /* expr ::= LP expr RP */
+{yymsp[-2].minor.yy202 = yymsp[-1].minor.yy202;}
+ break;
+ case 169: /* expr ::= ID|INDEXED */
+ case 170: /* expr ::= JOIN_KW */ yytestcase(yyruleno==170);
+{yymsp[0].minor.yy202=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
+ break;
+ case 171: /* expr ::= nm DOT nm */
+{
+ Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
+ Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[0].minor.yy0);
+ sqlite3RenameTokenMap(pParse, (void*)temp1, &yymsp[-2].minor.yy0);
+ }
+ yylhsminor.yy202 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
+}
+ yymsp[-2].minor.yy202 = yylhsminor.yy202;
+ break;
+ case 172: /* expr ::= nm DOT nm DOT nm */
+{
+ Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
+ Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
+ Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
+ Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
+ if( IN_RENAME_OBJECT ){
+ sqlite3RenameTokenMap(pParse, (void*)temp3, &yymsp[0].minor.yy0);
+ sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[-2].minor.yy0);
+ }
+ yylhsminor.yy202 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
+}
+ yymsp[-4].minor.yy202 = yylhsminor.yy202;
+ break;
+ case 173: /* term ::= NULL|FLOAT|BLOB */
+ case 174: /* term ::= STRING */ yytestcase(yyruleno==174);
+{yymsp[0].minor.yy202=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
+ break;
+ case 175: /* term ::= INTEGER */
+{
+ yylhsminor.yy202 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
+}
+ yymsp[0].minor.yy202 = yylhsminor.yy202;
+ break;
+ case 176: /* expr ::= VARIABLE */
+{
+ if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
+ u32 n = yymsp[0].minor.yy0.n;
+ yymsp[0].minor.yy202 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
+ sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy202, n);
+ }else{
+ /* When doing a nested parse, one can include terms in an expression
+ ** that look like this: #1 #2 ... These terms refer to registers
+ ** in the virtual machine. #N is the N-th register. */
+ Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
+ assert( t.n>=2 );
+ if( pParse->nested==0 ){
+ sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
+ yymsp[0].minor.yy202 = 0;
+ }else{
+ yymsp[0].minor.yy202 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
+ if( yymsp[0].minor.yy202 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy202->iTable);
+ }
+ }
+}
+ break;
+ case 177: /* expr ::= expr COLLATE ID|STRING */
+{
+ yymsp[-2].minor.yy202 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy202, &yymsp[0].minor.yy0, 1);
+}
+ break;
+ case 178: /* expr ::= CAST LP expr AS typetoken RP */
+{
+ yymsp[-5].minor.yy202 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
+ sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy202, yymsp[-3].minor.yy202, 0);
+}
+ break;
+ case 179: /* expr ::= ID|INDEXED LP distinct exprlist RP */
+{
+ yylhsminor.yy202 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy242, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy192);
+}
+ yymsp[-4].minor.yy202 = yylhsminor.yy202;
+ break;
+ case 180: /* expr ::= ID|INDEXED LP STAR RP */
+{
+ yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
+}
+ yymsp[-3].minor.yy202 = yylhsminor.yy202;
+ break;
+ case 181: /* expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
+{
+ yylhsminor.yy202 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy242, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy192);
+ sqlite3WindowAttach(pParse, yylhsminor.yy202, yymsp[0].minor.yy303);
+}
+ yymsp[-5].minor.yy202 = yylhsminor.yy202;
+ break;
+ case 182: /* expr ::= ID|INDEXED LP STAR RP filter_over */
+{
+ yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
+ sqlite3WindowAttach(pParse, yylhsminor.yy202, yymsp[0].minor.yy303);
+}
+ yymsp[-4].minor.yy202 = yylhsminor.yy202;
+ break;
+ case 183: /* term ::= CTIME_KW */
+{
+ yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);
+}
+ yymsp[0].minor.yy202 = yylhsminor.yy202;
+ break;
+ case 184: /* expr ::= LP nexprlist COMMA expr RP */
+{
+ ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy242, yymsp[-1].minor.yy202);
+ yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
+ if( yymsp[-4].minor.yy202 ){
+ yymsp[-4].minor.yy202->x.pList = pList;
+ if( ALWAYS(pList->nExpr) ){
+ yymsp[-4].minor.yy202->flags |= pList->a[0].pExpr->flags & EP_Propagate;
+ }
+ }else{
+ sqlite3ExprListDelete(pParse->db, pList);
+ }
+}
+ break;
+ case 185: /* expr ::= expr AND expr */
+{yymsp[-2].minor.yy202=sqlite3ExprAnd(pParse,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);}
+ break;
+ case 186: /* expr ::= expr OR expr */
+ case 187: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==187);
+ case 188: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==188);
+ case 189: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==189);
+ case 190: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==190);
+ case 191: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==191);
+ case 192: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==192);
+{yymsp[-2].minor.yy202=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);}
+ break;
+ case 193: /* likeop ::= NOT LIKE_KW|MATCH */
+{yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
+ break;
+ case 194: /* expr ::= expr likeop expr */
+{
+ ExprList *pList;
+ int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
+ yymsp[-1].minor.yy0.n &= 0x7fffffff;
+ pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy202);
+ pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy202);
+ yymsp[-2].minor.yy202 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
+ if( bNot ) yymsp[-2].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy202, 0);
+ if( yymsp[-2].minor.yy202 ) yymsp[-2].minor.yy202->flags |= EP_InfixFunc;
+}
+ break;
+ case 195: /* expr ::= expr likeop expr ESCAPE expr */
+{
+ ExprList *pList;
+ int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
+ yymsp[-3].minor.yy0.n &= 0x7fffffff;
+ pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202);
+ pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy202);
+ pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy202);
+ yymsp[-4].minor.yy202 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);
+ if( bNot ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
+ if( yymsp[-4].minor.yy202 ) yymsp[-4].minor.yy202->flags |= EP_InfixFunc;
+}
+ break;
+ case 196: /* expr ::= expr ISNULL|NOTNULL */
+{yymsp[-1].minor.yy202 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy202,0);}
+ break;
+ case 197: /* expr ::= expr NOT NULL */
+{yymsp[-2].minor.yy202 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy202,0);}
+ break;
+ case 198: /* expr ::= expr IS expr */
+{
+ yymsp[-2].minor.yy202 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);
+ binaryToUnaryIfNull(pParse, yymsp[0].minor.yy202, yymsp[-2].minor.yy202, TK_ISNULL);
+}
+ break;
+ case 199: /* expr ::= expr IS NOT expr */
+{
+ yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy202,yymsp[0].minor.yy202);
+ binaryToUnaryIfNull(pParse, yymsp[0].minor.yy202, yymsp[-3].minor.yy202, TK_NOTNULL);
+}
+ break;
+ case 200: /* expr ::= NOT expr */
+ case 201: /* expr ::= BITNOT expr */ yytestcase(yyruleno==201);
+{yymsp[-1].minor.yy202 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy202, 0);/*A-overwrites-B*/}
+ break;
+ case 202: /* expr ::= PLUS|MINUS expr */
+{
+ yymsp[-1].minor.yy202 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy202, 0);
+ /*A-overwrites-B*/
+}
+ break;
+ case 203: /* between_op ::= BETWEEN */
+ case 206: /* in_op ::= IN */ yytestcase(yyruleno==206);
+{yymsp[0].minor.yy192 = 0;}
+ break;
+ case 205: /* expr ::= expr between_op expr AND expr */
+{
+ ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202);
+ pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy202);
+ yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy202, 0);
+ if( yymsp[-4].minor.yy202 ){
+ yymsp[-4].minor.yy202->x.pList = pList;
+ }else{
+ sqlite3ExprListDelete(pParse->db, pList);
+ }
+ if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
+}
+ break;
+ case 208: /* expr ::= expr in_op LP exprlist RP */
+{
+ if( yymsp[-1].minor.yy242==0 ){
+ /* Expressions of the form
+ **
+ ** expr1 IN ()
+ ** expr1 NOT IN ()
+ **
+ ** simplify to constants 0 (false) and 1 (true), respectively,
+ ** regardless of the value of expr1.
+ */
+ sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy202);
+ yymsp[-4].minor.yy202 = sqlite3Expr(pParse->db, TK_INTEGER, yymsp[-3].minor.yy192 ? "1" : "0");
+ }else if( yymsp[-1].minor.yy242->nExpr==1 && sqlite3ExprIsConstant(yymsp[-1].minor.yy242->a[0].pExpr) ){
+ Expr *pRHS = yymsp[-1].minor.yy242->a[0].pExpr;
+ yymsp[-1].minor.yy242->a[0].pExpr = 0;
+ sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy242);
+ pRHS = sqlite3PExpr(pParse, TK_UPLUS, pRHS, 0);
+ yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_EQ, yymsp[-4].minor.yy202, pRHS);
+ if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
+ }else{
+ yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0);
+ if( yymsp[-4].minor.yy202 ){
+ yymsp[-4].minor.yy202->x.pList = yymsp[-1].minor.yy242;
+ sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy202);
+ }else{
+ sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy242);
+ }
+ if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
+ }
+ }
+ break;
+ case 209: /* expr ::= LP select RP */
+{
+ yymsp[-2].minor.yy202 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
+ sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy202, yymsp[-1].minor.yy539);
+ }
+ break;
+ case 210: /* expr ::= expr in_op LP select RP */
+{
+ yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0);
+ sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy202, yymsp[-1].minor.yy539);
+ if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
+ }
+ break;
+ case 211: /* expr ::= expr in_op nm dbnm paren_exprlist */
+{
+ SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
+ Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
+ if( yymsp[0].minor.yy242 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy242);
+ yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0);
+ sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy202, pSelect);
+ if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
+ }
+ break;
+ case 212: /* expr ::= EXISTS LP select RP */
+{
+ Expr *p;
+ p = yymsp[-3].minor.yy202 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
+ sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy539);
+ }
+ break;
+ case 213: /* expr ::= CASE case_operand case_exprlist case_else END */
+{
+ yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy202, 0);
+ if( yymsp[-4].minor.yy202 ){
+ yymsp[-4].minor.yy202->x.pList = yymsp[-1].minor.yy202 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[-1].minor.yy202) : yymsp[-2].minor.yy242;
+ sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy202);
+ }else{
+ sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy242);
+ sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy202);
+ }
+}
+ break;
+ case 214: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
+{
+ yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, yymsp[-2].minor.yy202);
+ yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, yymsp[0].minor.yy202);
+}
+ break;
+ case 215: /* case_exprlist ::= WHEN expr THEN expr */
+{
+ yymsp[-3].minor.yy242 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202);
+ yymsp[-3].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy242, yymsp[0].minor.yy202);
+}
+ break;
+ case 218: /* case_operand ::= expr */
+{yymsp[0].minor.yy202 = yymsp[0].minor.yy202; /*A-overwrites-X*/}
+ break;
+ case 221: /* nexprlist ::= nexprlist COMMA expr */
+{yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[0].minor.yy202);}
+ break;
+ case 222: /* nexprlist ::= expr */
+{yymsp[0].minor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy202); /*A-overwrites-Y*/}
+ break;
+ case 224: /* paren_exprlist ::= LP exprlist RP */
+ case 229: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==229);
+{yymsp[-2].minor.yy242 = yymsp[-1].minor.yy242;}
+ break;
+ case 225: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
+{
+ sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
+ sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy242, yymsp[-10].minor.yy192,
+ &yymsp[-11].minor.yy0, yymsp[0].minor.yy202, SQLITE_SO_ASC, yymsp[-8].minor.yy192, SQLITE_IDXTYPE_APPDEF);
+ if( IN_RENAME_OBJECT && pParse->pNewIndex ){
+ sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0);
+ }
+}
+ break;
+ case 226: /* uniqueflag ::= UNIQUE */
+ case 268: /* raisetype ::= ABORT */ yytestcase(yyruleno==268);
+{yymsp[0].minor.yy192 = OE_Abort;}
+ break;
+ case 227: /* uniqueflag ::= */
+{yymsp[1].minor.yy192 = OE_None;}
+ break;
+ case 230: /* eidlist ::= eidlist COMMA nm collate sortorder */
+{
+ yymsp[-4].minor.yy242 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy242, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy192, yymsp[0].minor.yy192);
+}
+ break;
+ case 231: /* eidlist ::= nm collate sortorder */
+{
+ yymsp[-2].minor.yy242 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy192, yymsp[0].minor.yy192); /*A-overwrites-Y*/
+}
+ break;
+ case 234: /* cmd ::= DROP INDEX ifexists fullname */
+{sqlite3DropIndex(pParse, yymsp[0].minor.yy47, yymsp[-1].minor.yy192);}
+ break;
+ case 235: /* cmd ::= VACUUM vinto */
+{sqlite3Vacuum(pParse,0,yymsp[0].minor.yy202);}
+ break;
+ case 236: /* cmd ::= VACUUM nm vinto */
+{sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy202);}
+ break;
+ case 239: /* cmd ::= PRAGMA nm dbnm */
+{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
+ break;
+ case 240: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
+{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
+ break;
+ case 241: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
+{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
+ break;
+ case 242: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
+{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
+ break;
+ case 243: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
+{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
+ break;
+ case 246: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
+{
+ Token all;
+ all.z = yymsp[-3].minor.yy0.z;
+ all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
+ sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy447, &all);
+}
+ break;
+ case 247: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
+{
+ sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy192, yymsp[-4].minor.yy230.a, yymsp[-4].minor.yy230.b, yymsp[-2].minor.yy47, yymsp[0].minor.yy202, yymsp[-10].minor.yy192, yymsp[-8].minor.yy192);
+ yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
+}
+ break;
+ case 248: /* trigger_time ::= BEFORE|AFTER */
+{ yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-X*/ }
+ break;
+ case 249: /* trigger_time ::= INSTEAD OF */
+{ yymsp[-1].minor.yy192 = TK_INSTEAD;}
+ break;
+ case 250: /* trigger_time ::= */
+{ yymsp[1].minor.yy192 = TK_BEFORE; }
+ break;
+ case 251: /* trigger_event ::= DELETE|INSERT */
+ case 252: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==252);
+{yymsp[0].minor.yy230.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy230.b = 0;}
+ break;
+ case 253: /* trigger_event ::= UPDATE OF idlist */
+{yymsp[-2].minor.yy230.a = TK_UPDATE; yymsp[-2].minor.yy230.b = yymsp[0].minor.yy600;}
+ break;
+ case 254: /* when_clause ::= */
+ case 273: /* key_opt ::= */ yytestcase(yyruleno==273);
+{ yymsp[1].minor.yy202 = 0; }
+ break;
+ case 255: /* when_clause ::= WHEN expr */
+ case 274: /* key_opt ::= KEY expr */ yytestcase(yyruleno==274);
+{ yymsp[-1].minor.yy202 = yymsp[0].minor.yy202; }
+ break;
+ case 256: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
+{
+ assert( yymsp[-2].minor.yy447!=0 );
+ yymsp[-2].minor.yy447->pLast->pNext = yymsp[-1].minor.yy447;
+ yymsp[-2].minor.yy447->pLast = yymsp[-1].minor.yy447;
+}
+ break;
+ case 257: /* trigger_cmd_list ::= trigger_cmd SEMI */
+{
+ assert( yymsp[-1].minor.yy447!=0 );
+ yymsp[-1].minor.yy447->pLast = yymsp[-1].minor.yy447;
+}
+ break;
+ case 258: /* trnm ::= nm DOT nm */
+{
+ yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
+ sqlite3ErrorMsg(pParse,
+ "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
+ "statements within triggers");
+}
+ break;
+ case 259: /* tridxby ::= INDEXED BY nm */
+{
+ sqlite3ErrorMsg(pParse,
+ "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
+ "within triggers");
+}
+ break;
+ case 260: /* tridxby ::= NOT INDEXED */
+{
+ sqlite3ErrorMsg(pParse,
+ "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
+ "within triggers");
+}
+ break;
+ case 261: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
+{yylhsminor.yy447 = sqlite3TriggerUpdateStep(pParse, &yymsp[-6].minor.yy0, yymsp[-2].minor.yy47, yymsp[-3].minor.yy242, yymsp[-1].minor.yy202, yymsp[-7].minor.yy192, yymsp[-8].minor.yy0.z, yymsp[0].minor.yy436);}
+ yymsp[-8].minor.yy447 = yylhsminor.yy447;
+ break;
+ case 262: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
+{
+ yylhsminor.yy447 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy600,yymsp[-2].minor.yy539,yymsp[-6].minor.yy192,yymsp[-1].minor.yy318,yymsp[-7].minor.yy436,yymsp[0].minor.yy436);/*yylhsminor.yy447-overwrites-yymsp[-6].minor.yy192*/
+}
+ yymsp[-7].minor.yy447 = yylhsminor.yy447;
+ break;
+ case 263: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
+{yylhsminor.yy447 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy202, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy436);}
+ yymsp[-5].minor.yy447 = yylhsminor.yy447;
+ break;
+ case 264: /* trigger_cmd ::= scanpt select scanpt */
+{yylhsminor.yy447 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy539, yymsp[-2].minor.yy436, yymsp[0].minor.yy436); /*yylhsminor.yy447-overwrites-yymsp[-1].minor.yy539*/}
+ yymsp[-2].minor.yy447 = yylhsminor.yy447;
+ break;
+ case 265: /* expr ::= RAISE LP IGNORE RP */
+{
+ yymsp[-3].minor.yy202 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
+ if( yymsp[-3].minor.yy202 ){
+ yymsp[-3].minor.yy202->affExpr = OE_Ignore;
+ }
+}
+ break;
+ case 266: /* expr ::= RAISE LP raisetype COMMA nm RP */
+{
+ yymsp[-5].minor.yy202 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
+ if( yymsp[-5].minor.yy202 ) {
+ yymsp[-5].minor.yy202->affExpr = (char)yymsp[-3].minor.yy192;
+ }
+}
+ break;
+ case 267: /* raisetype ::= ROLLBACK */
+{yymsp[0].minor.yy192 = OE_Rollback;}
+ break;
+ case 269: /* raisetype ::= FAIL */
+{yymsp[0].minor.yy192 = OE_Fail;}
+ break;
+ case 270: /* cmd ::= DROP TRIGGER ifexists fullname */
+{
+ sqlite3DropTrigger(pParse,yymsp[0].minor.yy47,yymsp[-1].minor.yy192);
+}
+ break;
+ case 271: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
+{
+ sqlite3Attach(pParse, yymsp[-3].minor.yy202, yymsp[-1].minor.yy202, yymsp[0].minor.yy202);
+}
+ break;
+ case 272: /* cmd ::= DETACH database_kw_opt expr */
+{
+ sqlite3Detach(pParse, yymsp[0].minor.yy202);
+}
+ break;
+ case 275: /* cmd ::= REINDEX */
+{sqlite3Reindex(pParse, 0, 0);}
+ break;
+ case 276: /* cmd ::= REINDEX nm dbnm */
+{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
+ break;
+ case 277: /* cmd ::= ANALYZE */
+{sqlite3Analyze(pParse, 0, 0);}
+ break;
+ case 278: /* cmd ::= ANALYZE nm dbnm */
+{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
+ break;
+ case 279: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
+{
+ sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy47,&yymsp[0].minor.yy0);
+}
+ break;
+ case 280: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
+{
+ yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
+ sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
+}
+ break;
+ case 281: /* add_column_fullname ::= fullname */
+{
+ disableLookaside(pParse);
+ sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy47);
+}
+ break;
+ case 282: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
+{
+ sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy47, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
+}
+ break;
+ case 283: /* cmd ::= create_vtab */
+{sqlite3VtabFinishParse(pParse,0);}
+ break;
+ case 284: /* cmd ::= create_vtab LP vtabarglist RP */
+{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
+ break;
+ case 285: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
+{
+ sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy192);
+}
+ break;
+ case 286: /* vtabarg ::= */
+{sqlite3VtabArgInit(pParse);}
+ break;
+ case 287: /* vtabargtoken ::= ANY */
+ case 288: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==288);
+ case 289: /* lp ::= LP */ yytestcase(yyruleno==289);
+{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
+ break;
+ case 290: /* with ::= WITH wqlist */
+ case 291: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==291);
+{ sqlite3WithPush(pParse, yymsp[0].minor.yy131, 1); }
+ break;
+ case 292: /* wqlist ::= nm eidlist_opt AS LP select RP */
+{
+ yymsp[-5].minor.yy131 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy242, yymsp[-1].minor.yy539); /*A-overwrites-X*/
+}
+ break;
+ case 293: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
+{
+ yymsp[-7].minor.yy131 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy131, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy242, yymsp[-1].minor.yy539);
+}
+ break;
+ case 294: /* windowdefn_list ::= windowdefn */
+{ yylhsminor.yy303 = yymsp[0].minor.yy303; }
+ yymsp[0].minor.yy303 = yylhsminor.yy303;
+ break;
+ case 295: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
+{
+ assert( yymsp[0].minor.yy303!=0 );
+ sqlite3WindowChain(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy303);
+ yymsp[0].minor.yy303->pNextWin = yymsp[-2].minor.yy303;
+ yylhsminor.yy303 = yymsp[0].minor.yy303;
+}
+ yymsp[-2].minor.yy303 = yylhsminor.yy303;
+ break;
+ case 296: /* windowdefn ::= nm AS LP window RP */
+{
+ if( ALWAYS(yymsp[-1].minor.yy303) ){
+ yymsp[-1].minor.yy303->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n);
+ }
+ yylhsminor.yy303 = yymsp[-1].minor.yy303;
+}
+ yymsp[-4].minor.yy303 = yylhsminor.yy303;
+ break;
+ case 297: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */
+{
+ yymsp[-4].minor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy242, yymsp[-1].minor.yy242, 0);
+}
+ break;
+ case 298: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
+{
+ yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy242, yymsp[-1].minor.yy242, &yymsp[-5].minor.yy0);
+}
+ yymsp[-5].minor.yy303 = yylhsminor.yy303;
+ break;
+ case 299: /* window ::= ORDER BY sortlist frame_opt */
+{
+ yymsp[-3].minor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, yymsp[-1].minor.yy242, 0);
+}
+ break;
+ case 300: /* window ::= nm ORDER BY sortlist frame_opt */
+{
+ yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, yymsp[-1].minor.yy242, &yymsp[-4].minor.yy0);
+}
+ yymsp[-4].minor.yy303 = yylhsminor.yy303;
+ break;
+ case 301: /* window ::= frame_opt */
+ case 320: /* filter_over ::= over_clause */ yytestcase(yyruleno==320);
+{
+ yylhsminor.yy303 = yymsp[0].minor.yy303;
+}
+ yymsp[0].minor.yy303 = yylhsminor.yy303;
+ break;
+ case 302: /* window ::= nm frame_opt */
+{
+ yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, 0, &yymsp[-1].minor.yy0);
+}
+ yymsp[-1].minor.yy303 = yylhsminor.yy303;
+ break;
+ case 303: /* frame_opt ::= */
+{
+ yymsp[1].minor.yy303 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
+}
+ break;
+ case 304: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
+{
+ yylhsminor.yy303 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy192, yymsp[-1].minor.yy77.eType, yymsp[-1].minor.yy77.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy58);
+}
+ yymsp[-2].minor.yy303 = yylhsminor.yy303;
+ break;
+ case 305: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
+{
+ yylhsminor.yy303 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy192, yymsp[-3].minor.yy77.eType, yymsp[-3].minor.yy77.pExpr, yymsp[-1].minor.yy77.eType, yymsp[-1].minor.yy77.pExpr, yymsp[0].minor.yy58);
+}
+ yymsp[-5].minor.yy303 = yylhsminor.yy303;
+ break;
+ case 307: /* frame_bound_s ::= frame_bound */
+ case 309: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==309);
+{yylhsminor.yy77 = yymsp[0].minor.yy77;}
+ yymsp[0].minor.yy77 = yylhsminor.yy77;
+ break;
+ case 308: /* frame_bound_s ::= UNBOUNDED PRECEDING */
+ case 310: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==310);
+ case 312: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==312);
+{yylhsminor.yy77.eType = yymsp[-1].major; yylhsminor.yy77.pExpr = 0;}
+ yymsp[-1].minor.yy77 = yylhsminor.yy77;
+ break;
+ case 311: /* frame_bound ::= expr PRECEDING|FOLLOWING */
+{yylhsminor.yy77.eType = yymsp[0].major; yylhsminor.yy77.pExpr = yymsp[-1].minor.yy202;}
+ yymsp[-1].minor.yy77 = yylhsminor.yy77;
+ break;
+ case 313: /* frame_exclude_opt ::= */
+{yymsp[1].minor.yy58 = 0;}
+ break;
+ case 314: /* frame_exclude_opt ::= EXCLUDE frame_exclude */
+{yymsp[-1].minor.yy58 = yymsp[0].minor.yy58;}
+ break;
+ case 315: /* frame_exclude ::= NO OTHERS */
+ case 316: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==316);
+{yymsp[-1].minor.yy58 = yymsp[-1].major; /*A-overwrites-X*/}
+ break;
+ case 317: /* frame_exclude ::= GROUP|TIES */
+{yymsp[0].minor.yy58 = yymsp[0].major; /*A-overwrites-X*/}
+ break;
+ case 318: /* window_clause ::= WINDOW windowdefn_list */
+{ yymsp[-1].minor.yy303 = yymsp[0].minor.yy303; }
+ break;
+ case 319: /* filter_over ::= filter_clause over_clause */
+{
+ yymsp[0].minor.yy303->pFilter = yymsp[-1].minor.yy202;
+ yylhsminor.yy303 = yymsp[0].minor.yy303;
+}
+ yymsp[-1].minor.yy303 = yylhsminor.yy303;
+ break;
+ case 321: /* filter_over ::= filter_clause */
+{
+ yylhsminor.yy303 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
+ if( yylhsminor.yy303 ){
+ yylhsminor.yy303->eFrmType = TK_FILTER;
+ yylhsminor.yy303->pFilter = yymsp[0].minor.yy202;
+ }else{
+ sqlite3ExprDelete(pParse->db, yymsp[0].minor.yy202);
+ }
+}
+ yymsp[0].minor.yy303 = yylhsminor.yy303;
+ break;
+ case 322: /* over_clause ::= OVER LP window RP */
+{
+ yymsp[-3].minor.yy303 = yymsp[-1].minor.yy303;
+ assert( yymsp[-3].minor.yy303!=0 );
+}
+ break;
+ case 323: /* over_clause ::= OVER nm */
+{
+ yymsp[-1].minor.yy303 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
+ if( yymsp[-1].minor.yy303 ){
+ yymsp[-1].minor.yy303->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);
+ }
+}
+ break;
+ case 324: /* filter_clause ::= FILTER LP WHERE expr RP */
+{ yymsp[-4].minor.yy202 = yymsp[-1].minor.yy202; }
+ break;
+ default:
+ /* (325) input ::= cmdlist */ yytestcase(yyruleno==325);
+ /* (326) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==326);
+ /* (327) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=327);
+ /* (328) ecmd ::= SEMI */ yytestcase(yyruleno==328);
+ /* (329) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==329);
+ /* (330) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=330);
+ /* (331) trans_opt ::= */ yytestcase(yyruleno==331);
+ /* (332) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==332);
+ /* (333) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==333);
+ /* (334) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==334);
+ /* (335) savepoint_opt ::= */ yytestcase(yyruleno==335);
+ /* (336) cmd ::= create_table create_table_args */ yytestcase(yyruleno==336);
+ /* (337) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==337);
+ /* (338) columnlist ::= columnname carglist */ yytestcase(yyruleno==338);
+ /* (339) nm ::= ID|INDEXED */ yytestcase(yyruleno==339);
+ /* (340) nm ::= STRING */ yytestcase(yyruleno==340);
+ /* (341) nm ::= JOIN_KW */ yytestcase(yyruleno==341);
+ /* (342) typetoken ::= typename */ yytestcase(yyruleno==342);
+ /* (343) typename ::= ID|STRING */ yytestcase(yyruleno==343);
+ /* (344) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=344);
+ /* (345) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=345);
+ /* (346) carglist ::= carglist ccons */ yytestcase(yyruleno==346);
+ /* (347) carglist ::= */ yytestcase(yyruleno==347);
+ /* (348) ccons ::= NULL onconf */ yytestcase(yyruleno==348);
+ /* (349) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==349);
+ /* (350) ccons ::= AS generated */ yytestcase(yyruleno==350);
+ /* (351) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==351);
+ /* (352) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==352);
+ /* (353) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=353);
+ /* (354) tconscomma ::= */ yytestcase(yyruleno==354);
+ /* (355) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=355);
+ /* (356) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=356);
+ /* (357) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=357);
+ /* (358) oneselect ::= values */ yytestcase(yyruleno==358);
+ /* (359) sclp ::= selcollist COMMA */ yytestcase(yyruleno==359);
+ /* (360) as ::= ID|STRING */ yytestcase(yyruleno==360);
+ /* (361) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=361);
+ /* (362) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==362);
+ /* (363) exprlist ::= nexprlist */ yytestcase(yyruleno==363);
+ /* (364) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=364);
+ /* (365) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=365);
+ /* (366) nmnum ::= ON */ yytestcase(yyruleno==366);
+ /* (367) nmnum ::= DELETE */ yytestcase(yyruleno==367);
+ /* (368) nmnum ::= DEFAULT */ yytestcase(yyruleno==368);
+ /* (369) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==369);
+ /* (370) foreach_clause ::= */ yytestcase(yyruleno==370);
+ /* (371) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==371);
+ /* (372) trnm ::= nm */ yytestcase(yyruleno==372);
+ /* (373) tridxby ::= */ yytestcase(yyruleno==373);
+ /* (374) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==374);
+ /* (375) database_kw_opt ::= */ yytestcase(yyruleno==375);
+ /* (376) kwcolumn_opt ::= */ yytestcase(yyruleno==376);
+ /* (377) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==377);
+ /* (378) vtabarglist ::= vtabarg */ yytestcase(yyruleno==378);
+ /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==379);
+ /* (380) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==380);
+ /* (381) anylist ::= */ yytestcase(yyruleno==381);
+ /* (382) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==382);
+ /* (383) anylist ::= anylist ANY */ yytestcase(yyruleno==383);
+ /* (384) with ::= */ yytestcase(yyruleno==384);
+ break;
+/********** End reduce actions ************************************************/
+ };
+ assert( yyruleno<sizeof(yyRuleInfoLhs)/sizeof(yyRuleInfoLhs[0]) );
+ yygoto = yyRuleInfoLhs[yyruleno];
+ yysize = yyRuleInfoNRhs[yyruleno];
+ yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
+
+ /* There are no SHIFTREDUCE actions on nonterminals because the table
+ ** generator has simplified them to pure REDUCE actions. */
+ assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );
+
+ /* It is not possible for a REDUCE to be followed by an error */
+ assert( yyact!=YY_ERROR_ACTION );
+
+ yymsp += yysize+1;
+ yypParser->yytos = yymsp;
+ yymsp->stateno = (YYACTIONTYPE)yyact;
+ yymsp->major = (YYCODETYPE)yygoto;
+ yyTraceShift(yypParser, yyact, "... then shift");
+ return yyact;
+}
+
+/*
+** The following code executes when the parse fails
+*/
+#ifndef YYNOERRORRECOVERY
+static void yy_parse_failed(
+ yyParser *yypParser /* The parser */
+){
+ sqlite3ParserARG_FETCH
+ sqlite3ParserCTX_FETCH
+#ifndef NDEBUG
+ if( yyTraceFILE ){
+ fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
+ }
+#endif
+ while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
+ /* Here code is inserted which will be executed whenever the
+ ** parser fails */
+/************ Begin %parse_failure code ***************************************/
+/************ End %parse_failure code *****************************************/
+ sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
+ sqlite3ParserCTX_STORE
+}
+#endif /* YYNOERRORRECOVERY */
+
+/*
+** The following code executes when a syntax error first occurs.
+*/
+static void yy_syntax_error(
+ yyParser *yypParser, /* The parser */
+ int yymajor, /* The major type of the error token */
+ sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
+){
+ sqlite3ParserARG_FETCH
+ sqlite3ParserCTX_FETCH
+#define TOKEN yyminor
+/************ Begin %syntax_error code ****************************************/
+
+ UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
+ if( TOKEN.z[0] ){
+ sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
+ }else{
+ sqlite3ErrorMsg(pParse, "incomplete input");
+ }
+/************ End %syntax_error code ******************************************/
+ sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
+ sqlite3ParserCTX_STORE
+}
+
+/*
+** The following is executed when the parser accepts
+*/
+static void yy_accept(
+ yyParser *yypParser /* The parser */
+){
+ sqlite3ParserARG_FETCH
+ sqlite3ParserCTX_FETCH
+#ifndef NDEBUG
+ if( yyTraceFILE ){
+ fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
+ }
+#endif
+#ifndef YYNOERRORRECOVERY
+ yypParser->yyerrcnt = -1;
+#endif
+ assert( yypParser->yytos==yypParser->yystack );
+ /* Here code is inserted which will be executed whenever the
+ ** parser accepts */
+/*********** Begin %parse_accept code *****************************************/
+/*********** End %parse_accept code *******************************************/
+ sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
+ sqlite3ParserCTX_STORE
+}
+
+/* The main parser program.
+** The first argument is a pointer to a structure obtained from
+** "sqlite3ParserAlloc" which describes the current state of the parser.
+** The second argument is the major token number. The third is
+** the minor token. The fourth optional argument is whatever the
+** user wants (and specified in the grammar) and is available for
+** use by the action routines.
+**
+** Inputs:
+** <ul>
+** <li> A pointer to the parser (an opaque structure.)
+** <li> The major token number.
+** <li> The minor token number.
+** <li> An option argument of a grammar-specified type.
+** </ul>
+**
+** Outputs:
+** None.
+*/
+SQLITE_PRIVATE void sqlite3Parser(
+ void *yyp, /* The parser */
+ int yymajor, /* The major token code number */
+ sqlite3ParserTOKENTYPE yyminor /* The value for the token */
+ sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
+){
+ YYMINORTYPE yyminorunion;
+ YYACTIONTYPE yyact; /* The parser action. */
+#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
+ int yyendofinput; /* True if we are at the end of input */
+#endif
+#ifdef YYERRORSYMBOL
+ int yyerrorhit = 0; /* True if yymajor has invoked an error */
+#endif
+ yyParser *yypParser = (yyParser*)yyp; /* The parser */
+ sqlite3ParserCTX_FETCH
+ sqlite3ParserARG_STORE
+
+ assert( yypParser->yytos!=0 );
+#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
+ yyendofinput = (yymajor==0);
+#endif
+
+ yyact = yypParser->yytos->stateno;
+#ifndef NDEBUG
+ if( yyTraceFILE ){
+ if( yyact < YY_MIN_REDUCE ){
+ fprintf(yyTraceFILE,"%sInput '%s' in state %d\n",
+ yyTracePrompt,yyTokenName[yymajor],yyact);
+ }else{
+ fprintf(yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
+ yyTracePrompt,yyTokenName[yymajor],yyact-YY_MIN_REDUCE);
+ }
+ }
+#endif
+
+ do{
+ assert( yyact==yypParser->yytos->stateno );
+ yyact = yy_find_shift_action((YYCODETYPE)yymajor,yyact);
+ if( yyact >= YY_MIN_REDUCE ){
+ yyact = yy_reduce(yypParser,yyact-YY_MIN_REDUCE,yymajor,
+ yyminor sqlite3ParserCTX_PARAM);
+ }else if( yyact <= YY_MAX_SHIFTREDUCE ){
+ yy_shift(yypParser,yyact,(YYCODETYPE)yymajor,yyminor);
+#ifndef YYNOERRORRECOVERY
+ yypParser->yyerrcnt--;
+#endif
+ break;
+ }else if( yyact==YY_ACCEPT_ACTION ){
+ yypParser->yytos--;
+ yy_accept(yypParser);
+ return;
+ }else{
+ assert( yyact == YY_ERROR_ACTION );
+ yyminorunion.yy0 = yyminor;
+#ifdef YYERRORSYMBOL
+ int yymx;
+#endif
+#ifndef NDEBUG
+ if( yyTraceFILE ){
+ fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
+ }
+#endif
+#ifdef YYERRORSYMBOL
+ /* A syntax error has occurred.
+ ** The response to an error depends upon whether or not the
+ ** grammar defines an error token "ERROR".
+ **
+ ** This is what we do if the grammar does define ERROR:
+ **
+ ** * Call the %syntax_error function.
+ **
+ ** * Begin popping the stack until we enter a state where
+ ** it is legal to shift the error symbol, then shift
+ ** the error symbol.
+ **
+ ** * Set the error count to three.
+ **
+ ** * Begin accepting and shifting new tokens. No new error
+ ** processing will occur until three tokens have been
+ ** shifted successfully.
+ **
+ */
+ if( yypParser->yyerrcnt<0 ){
+ yy_syntax_error(yypParser,yymajor,yyminor);
+ }
+ yymx = yypParser->yytos->major;
+ if( yymx==YYERRORSYMBOL || yyerrorhit ){
+#ifndef NDEBUG
+ if( yyTraceFILE ){
+ fprintf(yyTraceFILE,"%sDiscard input token %s\n",
+ yyTracePrompt,yyTokenName[yymajor]);
+ }
+#endif
+ yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
+ yymajor = YYNOCODE;
+ }else{
+ while( yypParser->yytos >= yypParser->yystack
+ && (yyact = yy_find_reduce_action(
+ yypParser->yytos->stateno,
+ YYERRORSYMBOL)) > YY_MAX_SHIFTREDUCE
+ ){
+ yy_pop_parser_stack(yypParser);
+ }
+ if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
+ yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
+ yy_parse_failed(yypParser);
+#ifndef YYNOERRORRECOVERY
+ yypParser->yyerrcnt = -1;
+#endif
+ yymajor = YYNOCODE;
+ }else if( yymx!=YYERRORSYMBOL ){
+ yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
+ }
+ }
+ yypParser->yyerrcnt = 3;
+ yyerrorhit = 1;
+ if( yymajor==YYNOCODE ) break;
+ yyact = yypParser->yytos->stateno;
+#elif defined(YYNOERRORRECOVERY)
+ /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
+ ** do any kind of error recovery. Instead, simply invoke the syntax
+ ** error routine and continue going as if nothing had happened.
+ **
+ ** Applications can set this macro (for example inside %include) if
+ ** they intend to abandon the parse upon the first syntax error seen.
+ */
+ yy_syntax_error(yypParser,yymajor, yyminor);
+ yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
+ break;
+#else /* YYERRORSYMBOL is not defined */
+ /* This is what we do if the grammar does not define ERROR:
+ **
+ ** * Report an error message, and throw away the input token.
+ **
+ ** * If the input token is $, then fail the parse.
+ **
+ ** As before, subsequent error messages are suppressed until
+ ** three input tokens have been successfully shifted.
+ */
+ if( yypParser->yyerrcnt<=0 ){
+ yy_syntax_error(yypParser,yymajor, yyminor);
+ }
+ yypParser->yyerrcnt = 3;
+ yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
+ if( yyendofinput ){
+ yy_parse_failed(yypParser);
+#ifndef YYNOERRORRECOVERY
+ yypParser->yyerrcnt = -1;
+#endif
+ }
+ break;
+#endif
+ }
+ }while( yypParser->yytos>yypParser->yystack );
+#ifndef NDEBUG
+ if( yyTraceFILE ){
+ yyStackEntry *i;
+ char cDiv = '[';
+ fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
+ for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
+ fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
+ cDiv = ' ';
+ }
+ fprintf(yyTraceFILE,"]\n");
+ }
+#endif
+ return;
+}
+
+/*
+** Return the fallback token corresponding to canonical token iToken, or
+** 0 if iToken has no fallback.
+*/
+SQLITE_PRIVATE int sqlite3ParserFallback(int iToken){
+#ifdef YYFALLBACK
+ assert( iToken<(int)(sizeof(yyFallback)/sizeof(yyFallback[0])) );
+ return yyFallback[iToken];
+#else
+ (void)iToken;
+ return 0;
+#endif
+}
+
+/************** End of parse.c ***********************************************/
+/************** Begin file tokenize.c ****************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** An tokenizer for SQL
+**
+** This file contains C code that splits an SQL input string up into
+** individual tokens and sends those tokens one-by-one over to the
+** parser for analysis.
+*/
+/* #include "sqliteInt.h" */
+/* #include <stdlib.h> */
+
+/* Character classes for tokenizing
+**
+** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
+** using a lookup table, whereas a switch() directly on c uses a binary search.
+** The lookup table is much faster. To maximize speed, and to ensure that
+** a lookup table is used, all of the classes need to be small integers and
+** all of them need to be used within the switch.
+*/
+#define CC_X 0 /* The letter 'x', or start of BLOB literal */
+#define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
+#define CC_ID 2 /* unicode characters usable in IDs */
+#define CC_DIGIT 3 /* Digits */
+#define CC_DOLLAR 4 /* '$' */
+#define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
+#define CC_VARNUM 6 /* '?'. Numeric SQL variables */
+#define CC_SPACE 7 /* Space characters */
+#define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
+#define CC_QUOTE2 9 /* '['. [...] style quoted ids */
+#define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
+#define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
+#define CC_LT 12 /* '<'. Part of < or <= or <> */
+#define CC_GT 13 /* '>'. Part of > or >= */
+#define CC_EQ 14 /* '='. Part of = or == */
+#define CC_BANG 15 /* '!'. Part of != */
+#define CC_SLASH 16 /* '/'. / or c-style comment */
+#define CC_LP 17 /* '(' */
+#define CC_RP 18 /* ')' */
+#define CC_SEMI 19 /* ';' */
+#define CC_PLUS 20 /* '+' */
+#define CC_STAR 21 /* '*' */
+#define CC_PERCENT 22 /* '%' */
+#define CC_COMMA 23 /* ',' */
+#define CC_AND 24 /* '&' */
+#define CC_TILDA 25 /* '~' */
+#define CC_DOT 26 /* '.' */
+#define CC_ILLEGAL 27 /* Illegal character */
+#define CC_NUL 28 /* 0x00 */
+
+static const unsigned char aiClass[] = {
+#ifdef SQLITE_ASCII
+/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
+/* 0x */ 28, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
+/* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+/* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
+/* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
+/* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+/* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
+/* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+/* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
+/* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+/* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+/* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+/* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+/* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+/* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+/* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+/* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
+#endif
+#ifdef SQLITE_EBCDIC
+/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
+/* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
+/* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+/* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+/* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+/* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
+/* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
+/* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6,
+/* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
+/* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
+/* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
+/* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
+/* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
+/* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
+/* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
+/* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
+/* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
+#endif
+};
+
+/*
+** The charMap() macro maps alphabetic characters (only) into their
+** lower-case ASCII equivalent. On ASCII machines, this is just
+** an upper-to-lower case map. On EBCDIC machines we also need
+** to adjust the encoding. The mapping is only valid for alphabetics
+** which are the only characters for which this feature is used.
+**
+** Used by keywordhash.h
+*/
+#ifdef SQLITE_ASCII
+# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
+#endif
+#ifdef SQLITE_EBCDIC
+# define charMap(X) ebcdicToAscii[(unsigned char)X]
+const unsigned char ebcdicToAscii[] = {
+/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
+ 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
+ 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
+ 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
+ 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
+ 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
+ 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
+};
+#endif
+
+/*
+** The sqlite3KeywordCode function looks up an identifier to determine if
+** it is a keyword. If it is a keyword, the token code of that keyword is
+** returned. If the input is not a keyword, TK_ID is returned.
+**
+** The implementation of this routine was generated by a program,
+** mkkeywordhash.c, located in the tool subdirectory of the distribution.
+** The output of the mkkeywordhash.c program is written into a file
+** named keywordhash.h and then included into this source file by
+** the #include below.
+*/
+/************** Include keywordhash.h in the middle of tokenize.c ************/
+/************** Begin file keywordhash.h *************************************/
+/***** This file contains automatically generated code ******
+**
+** The code in this file has been automatically generated by
+**
+** sqlite/tool/mkkeywordhash.c
+**
+** The code in this file implements a function that determines whether
+** or not a given identifier is really an SQL keyword. The same thing
+** might be implemented more directly using a hand-written hash table.
+** But by using this automatically generated code, the size of the code
+** is substantially reduced. This is important for embedded applications
+** on platforms with limited memory.
+*/
+/* Hash score: 227 */
+/* zKWText[] encodes 984 bytes of keyword text in 648 bytes */
+/* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
+/* ABLEFTHENDEFERRABLELSEXCLUDELETEMPORARYISNULLSAVEPOINTERSECT */
+/* IESNOTNULLIKEXCEPTRANSACTIONATURALTERAISEXCLUSIVEXISTS */
+/* CONSTRAINTOFFSETRIGGERANGENERATEDETACHAVINGLOBEGINNEREFERENCES */
+/* UNIQUERYWITHOUTERELEASEATTACHBETWEENOTHINGROUPSCASCADEFAULT */
+/* CASECOLLATECREATECURRENT_DATEIMMEDIATEJOINSERTMATCHPLANALYZE */
+/* PRAGMABORTUPDATEVALUESVIRTUALWAYSWHENWHERECURSIVEAFTERENAMEAND */
+/* EFERREDISTINCTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
+/* CURRENT_TIMESTAMPARTITIONDROPRECEDINGFAILASTFILTEREPLACEFIRST */
+/* FOLLOWINGFROMFULLIMITIFORDERESTRICTOTHERSOVERIGHTROLLBACKROWS */
+/* UNBOUNDEDUNIONUSINGVACUUMVIEWINDOWBYINITIALLYPRIMARY */
+static const char zKWText[647] = {
+ 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
+ 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
+ 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
+ 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
+ 'E','R','R','A','B','L','E','L','S','E','X','C','L','U','D','E','L','E',
+ 'T','E','M','P','O','R','A','R','Y','I','S','N','U','L','L','S','A','V',
+ 'E','P','O','I','N','T','E','R','S','E','C','T','I','E','S','N','O','T',
+ 'N','U','L','L','I','K','E','X','C','E','P','T','R','A','N','S','A','C',
+ 'T','I','O','N','A','T','U','R','A','L','T','E','R','A','I','S','E','X',
+ 'C','L','U','S','I','V','E','X','I','S','T','S','C','O','N','S','T','R',
+ 'A','I','N','T','O','F','F','S','E','T','R','I','G','G','E','R','A','N',
+ 'G','E','N','E','R','A','T','E','D','E','T','A','C','H','A','V','I','N',
+ 'G','L','O','B','E','G','I','N','N','E','R','E','F','E','R','E','N','C',
+ 'E','S','U','N','I','Q','U','E','R','Y','W','I','T','H','O','U','T','E',
+ 'R','E','L','E','A','S','E','A','T','T','A','C','H','B','E','T','W','E',
+ 'E','N','O','T','H','I','N','G','R','O','U','P','S','C','A','S','C','A',
+ 'D','E','F','A','U','L','T','C','A','S','E','C','O','L','L','A','T','E',
+ 'C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A','T','E',
+ 'I','M','M','E','D','I','A','T','E','J','O','I','N','S','E','R','T','M',
+ 'A','T','C','H','P','L','A','N','A','L','Y','Z','E','P','R','A','G','M',
+ 'A','B','O','R','T','U','P','D','A','T','E','V','A','L','U','E','S','V',
+ 'I','R','T','U','A','L','W','A','Y','S','W','H','E','N','W','H','E','R',
+ 'E','C','U','R','S','I','V','E','A','F','T','E','R','E','N','A','M','E',
+ 'A','N','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','A',
+ 'U','T','O','I','N','C','R','E','M','E','N','T','C','A','S','T','C','O',
+ 'L','U','M','N','C','O','M','M','I','T','C','O','N','F','L','I','C','T',
+ 'C','R','O','S','S','C','U','R','R','E','N','T','_','T','I','M','E','S',
+ 'T','A','M','P','A','R','T','I','T','I','O','N','D','R','O','P','R','E',
+ 'C','E','D','I','N','G','F','A','I','L','A','S','T','F','I','L','T','E',
+ 'R','E','P','L','A','C','E','F','I','R','S','T','F','O','L','L','O','W',
+ 'I','N','G','F','R','O','M','F','U','L','L','I','M','I','T','I','F','O',
+ 'R','D','E','R','E','S','T','R','I','C','T','O','T','H','E','R','S','O',
+ 'V','E','R','I','G','H','T','R','O','L','L','B','A','C','K','R','O','W',
+ 'S','U','N','B','O','U','N','D','E','D','U','N','I','O','N','U','S','I',
+ 'N','G','V','A','C','U','U','M','V','I','E','W','I','N','D','O','W','B',
+ 'Y','I','N','I','T','I','A','L','L','Y','P','R','I','M','A','R','Y',
+};
+/* aKWHash[i] is the hash value for the i-th keyword */
+static const unsigned char aKWHash[127] = {
+ 84, 102, 132, 82, 114, 29, 0, 0, 91, 0, 85, 72, 0,
+ 53, 35, 86, 15, 0, 42, 94, 54, 126, 133, 19, 0, 0,
+ 138, 0, 40, 128, 0, 22, 104, 0, 9, 0, 0, 122, 80,
+ 0, 78, 6, 0, 65, 99, 145, 0, 134, 112, 0, 0, 48,
+ 0, 100, 24, 0, 17, 0, 27, 70, 23, 26, 5, 60, 140,
+ 107, 121, 0, 73, 101, 71, 143, 61, 119, 74, 0, 49, 0,
+ 11, 41, 0, 110, 0, 0, 0, 106, 10, 108, 113, 124, 14,
+ 50, 123, 0, 89, 0, 18, 120, 142, 56, 129, 137, 88, 83,
+ 37, 30, 125, 0, 0, 105, 51, 130, 127, 0, 34, 0, 0,
+ 44, 0, 95, 38, 39, 0, 20, 45, 116, 90,
+};
+/* aKWNext[] forms the hash collision chain. If aKWHash[i]==0
+** then the i-th keyword has no more hash collisions. Otherwise,
+** the next keyword with the same hash is aKWHash[i]-1. */
+static const unsigned char aKWNext[145] = {
+ 0, 0, 0, 0, 4, 0, 43, 0, 0, 103, 111, 0, 0,
+ 0, 2, 0, 0, 141, 0, 0, 0, 13, 0, 0, 0, 0,
+ 139, 0, 0, 118, 52, 0, 0, 135, 12, 0, 0, 62, 0,
+ 136, 0, 131, 0, 0, 36, 0, 0, 28, 77, 0, 0, 0,
+ 0, 59, 0, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 69, 0, 0, 0, 0, 0, 144, 3, 0, 58, 0, 1,
+ 75, 0, 0, 0, 31, 0, 0, 0, 0, 0, 0, 64, 66,
+ 63, 0, 0, 0, 0, 46, 0, 16, 0, 115, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 81, 97, 0, 8, 0, 109,
+ 21, 7, 67, 0, 79, 93, 117, 0, 0, 68, 0, 0, 96,
+ 0, 55, 0, 76, 0, 92, 32, 33, 57, 25, 0, 98, 0,
+ 0, 87,
+};
+/* aKWLen[i] is the length (in bytes) of the i-th keyword */
+static const unsigned char aKWLen[145] = {
+ 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
+ 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 7,
+ 6, 9, 4, 2, 6, 5, 9, 9, 4, 7, 3, 2, 4,
+ 4, 6, 11, 6, 2, 7, 5, 5, 9, 6, 10, 4, 6,
+ 2, 3, 7, 5, 9, 6, 6, 4, 5, 5, 10, 6, 5,
+ 7, 4, 5, 7, 6, 7, 7, 6, 5, 7, 3, 7, 4,
+ 7, 6, 12, 9, 4, 6, 5, 4, 7, 6, 5, 6, 6,
+ 7, 6, 4, 5, 9, 5, 6, 3, 8, 8, 2, 13, 2,
+ 2, 4, 6, 6, 8, 5, 17, 12, 7, 9, 4, 9, 4,
+ 4, 6, 7, 5, 9, 4, 4, 5, 2, 5, 8, 6, 4,
+ 5, 8, 4, 3, 9, 5, 5, 6, 4, 6, 2, 2, 9,
+ 3, 7,
+};
+/* aKWOffset[i] is the index into zKWText[] of the start of
+** the text for the i-th keyword. */
+static const unsigned short int aKWOffset[145] = {
+ 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
+ 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
+ 86, 90, 90, 94, 99, 101, 105, 111, 119, 123, 123, 123, 126,
+ 129, 132, 137, 142, 146, 147, 152, 156, 160, 168, 174, 181, 184,
+ 184, 187, 189, 195, 198, 206, 211, 216, 219, 222, 226, 236, 239,
+ 244, 244, 248, 252, 259, 265, 271, 277, 277, 283, 284, 288, 295,
+ 299, 306, 312, 324, 333, 335, 341, 346, 348, 355, 360, 365, 371,
+ 377, 382, 388, 392, 395, 404, 408, 414, 416, 423, 424, 431, 433,
+ 435, 444, 448, 454, 460, 468, 473, 473, 473, 489, 498, 501, 510,
+ 513, 517, 522, 529, 534, 543, 547, 550, 555, 557, 561, 569, 575,
+ 578, 583, 591, 591, 595, 604, 609, 614, 620, 623, 626, 629, 631,
+ 636, 640,
+};
+/* aKWCode[i] is the parser symbol code for the i-th keyword */
+static const unsigned char aKWCode[145] = {
+ TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
+ TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
+ TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
+ TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
+ TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
+ TK_EXCLUDE, TK_DELETE, TK_TEMP, TK_TEMP, TK_OR,
+ TK_ISNULL, TK_NULLS, TK_SAVEPOINT, TK_INTERSECT, TK_TIES,
+ TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
+ TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
+ TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_CONSTRAINT,
+ TK_INTO, TK_OFFSET, TK_OF, TK_SET, TK_TRIGGER,
+ TK_RANGE, TK_GENERATED, TK_DETACH, TK_HAVING, TK_LIKE_KW,
+ TK_BEGIN, TK_JOIN_KW, TK_REFERENCES, TK_UNIQUE, TK_QUERY,
+ TK_WITHOUT, TK_WITH, TK_JOIN_KW, TK_RELEASE, TK_ATTACH,
+ TK_BETWEEN, TK_NOTHING, TK_GROUPS, TK_GROUP, TK_CASCADE,
+ TK_ASC, TK_DEFAULT, TK_CASE, TK_COLLATE, TK_CREATE,
+ TK_CTIME_KW, TK_IMMEDIATE, TK_JOIN, TK_INSERT, TK_MATCH,
+ TK_PLAN, TK_ANALYZE, TK_PRAGMA, TK_ABORT, TK_UPDATE,
+ TK_VALUES, TK_VIRTUAL, TK_ALWAYS, TK_WHEN, TK_WHERE,
+ TK_RECURSIVE, TK_AFTER, TK_RENAME, TK_AND, TK_DEFERRED,
+ TK_DISTINCT, TK_IS, TK_AUTOINCR, TK_TO, TK_IN,
+ TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
+ TK_CTIME_KW, TK_CTIME_KW, TK_CURRENT, TK_PARTITION, TK_DROP,
+ TK_PRECEDING, TK_FAIL, TK_LAST, TK_FILTER, TK_REPLACE,
+ TK_FIRST, TK_FOLLOWING, TK_FROM, TK_JOIN_KW, TK_LIMIT,
+ TK_IF, TK_ORDER, TK_RESTRICT, TK_OTHERS, TK_OVER,
+ TK_JOIN_KW, TK_ROLLBACK, TK_ROWS, TK_ROW, TK_UNBOUNDED,
+ TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_WINDOW,
+ TK_DO, TK_BY, TK_INITIALLY, TK_ALL, TK_PRIMARY,
+};
+/* Hash table decoded:
+** 0: INSERT
+** 1: IS
+** 2: ROLLBACK TRIGGER
+** 3: IMMEDIATE
+** 4: PARTITION
+** 5: TEMP
+** 6:
+** 7:
+** 8: VALUES WITHOUT
+** 9:
+** 10: MATCH
+** 11: NOTHING
+** 12:
+** 13: OF
+** 14: TIES IGNORE
+** 15: PLAN
+** 16: INSTEAD INDEXED
+** 17:
+** 18: TRANSACTION RIGHT
+** 19: WHEN
+** 20: SET HAVING
+** 21: IF
+** 22: ROWS
+** 23: SELECT
+** 24:
+** 25:
+** 26: VACUUM SAVEPOINT
+** 27:
+** 28: LIKE UNION VIRTUAL REFERENCES
+** 29: RESTRICT
+** 30:
+** 31: THEN REGEXP
+** 32: TO
+** 33:
+** 34: BEFORE
+** 35:
+** 36:
+** 37: FOLLOWING COLLATE CASCADE
+** 38: CREATE
+** 39:
+** 40: CASE REINDEX
+** 41: EACH
+** 42:
+** 43: QUERY
+** 44: AND ADD
+** 45: PRIMARY ANALYZE
+** 46:
+** 47: ROW ASC DETACH
+** 48: CURRENT_TIME CURRENT_DATE
+** 49:
+** 50:
+** 51: EXCLUSIVE TEMPORARY
+** 52:
+** 53: DEFERRED
+** 54: DEFERRABLE
+** 55:
+** 56: DATABASE
+** 57:
+** 58: DELETE VIEW GENERATED
+** 59: ATTACH
+** 60: END
+** 61: EXCLUDE
+** 62: ESCAPE DESC
+** 63: GLOB
+** 64: WINDOW ELSE
+** 65: COLUMN
+** 66: FIRST
+** 67:
+** 68: GROUPS ALL
+** 69: DISTINCT DROP KEY
+** 70: BETWEEN
+** 71: INITIALLY
+** 72: BEGIN
+** 73: FILTER CHECK ACTION
+** 74: GROUP INDEX
+** 75:
+** 76: EXISTS DEFAULT
+** 77:
+** 78: FOR CURRENT_TIMESTAMP
+** 79: EXCEPT
+** 80:
+** 81: CROSS
+** 82:
+** 83:
+** 84:
+** 85: CAST
+** 86: FOREIGN AUTOINCREMENT
+** 87: COMMIT
+** 88: CURRENT AFTER ALTER
+** 89: FULL FAIL CONFLICT
+** 90: EXPLAIN
+** 91: CONSTRAINT
+** 92: FROM ALWAYS
+** 93:
+** 94: ABORT
+** 95:
+** 96: AS DO
+** 97: REPLACE WITH RELEASE
+** 98: BY RENAME
+** 99: RANGE RAISE
+** 100: OTHERS
+** 101: USING NULLS
+** 102: PRAGMA
+** 103: JOIN ISNULL OFFSET
+** 104: NOT
+** 105: OR LAST LEFT
+** 106: LIMIT
+** 107:
+** 108:
+** 109: IN
+** 110: INTO
+** 111: OVER RECURSIVE
+** 112: ORDER OUTER
+** 113:
+** 114: INTERSECT UNBOUNDED
+** 115:
+** 116:
+** 117: ON
+** 118:
+** 119: WHERE
+** 120: NO INNER
+** 121: NULL
+** 122:
+** 123: TABLE
+** 124: NATURAL NOTNULL
+** 125: PRECEDING
+** 126: UPDATE UNIQUE
+*/
+/* Check to see if z[0..n-1] is a keyword. If it is, write the
+** parser symbol code for that keyword into *pType. Always
+** return the integer n (the length of the token). */
+static int keywordCode(const char *z, int n, int *pType){
+ int i, j;
+ const char *zKW;
+ if( n>=2 ){
+ i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
+ for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
+ if( aKWLen[i]!=n ) continue;
+ zKW = &zKWText[aKWOffset[i]];
+#ifdef SQLITE_ASCII
+ if( (z[0]&~0x20)!=zKW[0] ) continue;
+ if( (z[1]&~0x20)!=zKW[1] ) continue;
+ j = 2;
+ while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
+#endif
+#ifdef SQLITE_EBCDIC
+ if( toupper(z[0])!=zKW[0] ) continue;
+ if( toupper(z[1])!=zKW[1] ) continue;
+ j = 2;
+ while( j<n && toupper(z[j])==zKW[j] ){ j++; }
+#endif
+ if( j<n ) continue;
+ testcase( i==0 ); /* REINDEX */
+ testcase( i==1 ); /* INDEXED */
+ testcase( i==2 ); /* INDEX */
+ testcase( i==3 ); /* DESC */
+ testcase( i==4 ); /* ESCAPE */
+ testcase( i==5 ); /* EACH */
+ testcase( i==6 ); /* CHECK */
+ testcase( i==7 ); /* KEY */
+ testcase( i==8 ); /* BEFORE */
+ testcase( i==9 ); /* FOREIGN */
+ testcase( i==10 ); /* FOR */
+ testcase( i==11 ); /* IGNORE */
+ testcase( i==12 ); /* REGEXP */
+ testcase( i==13 ); /* EXPLAIN */
+ testcase( i==14 ); /* INSTEAD */
+ testcase( i==15 ); /* ADD */
+ testcase( i==16 ); /* DATABASE */
+ testcase( i==17 ); /* AS */
+ testcase( i==18 ); /* SELECT */
+ testcase( i==19 ); /* TABLE */
+ testcase( i==20 ); /* LEFT */
+ testcase( i==21 ); /* THEN */
+ testcase( i==22 ); /* END */
+ testcase( i==23 ); /* DEFERRABLE */
+ testcase( i==24 ); /* ELSE */
+ testcase( i==25 ); /* EXCLUDE */
+ testcase( i==26 ); /* DELETE */
+ testcase( i==27 ); /* TEMPORARY */
+ testcase( i==28 ); /* TEMP */
+ testcase( i==29 ); /* OR */
+ testcase( i==30 ); /* ISNULL */
+ testcase( i==31 ); /* NULLS */
+ testcase( i==32 ); /* SAVEPOINT */
+ testcase( i==33 ); /* INTERSECT */
+ testcase( i==34 ); /* TIES */
+ testcase( i==35 ); /* NOTNULL */
+ testcase( i==36 ); /* NOT */
+ testcase( i==37 ); /* NO */
+ testcase( i==38 ); /* NULL */
+ testcase( i==39 ); /* LIKE */
+ testcase( i==40 ); /* EXCEPT */
+ testcase( i==41 ); /* TRANSACTION */
+ testcase( i==42 ); /* ACTION */
+ testcase( i==43 ); /* ON */
+ testcase( i==44 ); /* NATURAL */
+ testcase( i==45 ); /* ALTER */
+ testcase( i==46 ); /* RAISE */
+ testcase( i==47 ); /* EXCLUSIVE */
+ testcase( i==48 ); /* EXISTS */
+ testcase( i==49 ); /* CONSTRAINT */
+ testcase( i==50 ); /* INTO */
+ testcase( i==51 ); /* OFFSET */
+ testcase( i==52 ); /* OF */
+ testcase( i==53 ); /* SET */
+ testcase( i==54 ); /* TRIGGER */
+ testcase( i==55 ); /* RANGE */
+ testcase( i==56 ); /* GENERATED */
+ testcase( i==57 ); /* DETACH */
+ testcase( i==58 ); /* HAVING */
+ testcase( i==59 ); /* GLOB */
+ testcase( i==60 ); /* BEGIN */
+ testcase( i==61 ); /* INNER */
+ testcase( i==62 ); /* REFERENCES */
+ testcase( i==63 ); /* UNIQUE */
+ testcase( i==64 ); /* QUERY */
+ testcase( i==65 ); /* WITHOUT */
+ testcase( i==66 ); /* WITH */
+ testcase( i==67 ); /* OUTER */
+ testcase( i==68 ); /* RELEASE */
+ testcase( i==69 ); /* ATTACH */
+ testcase( i==70 ); /* BETWEEN */
+ testcase( i==71 ); /* NOTHING */
+ testcase( i==72 ); /* GROUPS */
+ testcase( i==73 ); /* GROUP */
+ testcase( i==74 ); /* CASCADE */
+ testcase( i==75 ); /* ASC */
+ testcase( i==76 ); /* DEFAULT */
+ testcase( i==77 ); /* CASE */
+ testcase( i==78 ); /* COLLATE */
+ testcase( i==79 ); /* CREATE */
+ testcase( i==80 ); /* CURRENT_DATE */
+ testcase( i==81 ); /* IMMEDIATE */
+ testcase( i==82 ); /* JOIN */
+ testcase( i==83 ); /* INSERT */
+ testcase( i==84 ); /* MATCH */
+ testcase( i==85 ); /* PLAN */
+ testcase( i==86 ); /* ANALYZE */
+ testcase( i==87 ); /* PRAGMA */
+ testcase( i==88 ); /* ABORT */
+ testcase( i==89 ); /* UPDATE */
+ testcase( i==90 ); /* VALUES */
+ testcase( i==91 ); /* VIRTUAL */
+ testcase( i==92 ); /* ALWAYS */
+ testcase( i==93 ); /* WHEN */
+ testcase( i==94 ); /* WHERE */
+ testcase( i==95 ); /* RECURSIVE */
+ testcase( i==96 ); /* AFTER */
+ testcase( i==97 ); /* RENAME */
+ testcase( i==98 ); /* AND */
+ testcase( i==99 ); /* DEFERRED */
+ testcase( i==100 ); /* DISTINCT */
+ testcase( i==101 ); /* IS */
+ testcase( i==102 ); /* AUTOINCREMENT */
+ testcase( i==103 ); /* TO */
+ testcase( i==104 ); /* IN */
+ testcase( i==105 ); /* CAST */
+ testcase( i==106 ); /* COLUMN */
+ testcase( i==107 ); /* COMMIT */
+ testcase( i==108 ); /* CONFLICT */
+ testcase( i==109 ); /* CROSS */
+ testcase( i==110 ); /* CURRENT_TIMESTAMP */
+ testcase( i==111 ); /* CURRENT_TIME */
+ testcase( i==112 ); /* CURRENT */
+ testcase( i==113 ); /* PARTITION */
+ testcase( i==114 ); /* DROP */
+ testcase( i==115 ); /* PRECEDING */
+ testcase( i==116 ); /* FAIL */
+ testcase( i==117 ); /* LAST */
+ testcase( i==118 ); /* FILTER */
+ testcase( i==119 ); /* REPLACE */
+ testcase( i==120 ); /* FIRST */
+ testcase( i==121 ); /* FOLLOWING */
+ testcase( i==122 ); /* FROM */
+ testcase( i==123 ); /* FULL */
+ testcase( i==124 ); /* LIMIT */
+ testcase( i==125 ); /* IF */
+ testcase( i==126 ); /* ORDER */
+ testcase( i==127 ); /* RESTRICT */
+ testcase( i==128 ); /* OTHERS */
+ testcase( i==129 ); /* OVER */
+ testcase( i==130 ); /* RIGHT */
+ testcase( i==131 ); /* ROLLBACK */
+ testcase( i==132 ); /* ROWS */
+ testcase( i==133 ); /* ROW */
+ testcase( i==134 ); /* UNBOUNDED */
+ testcase( i==135 ); /* UNION */
+ testcase( i==136 ); /* USING */
+ testcase( i==137 ); /* VACUUM */
+ testcase( i==138 ); /* VIEW */
+ testcase( i==139 ); /* WINDOW */
+ testcase( i==140 ); /* DO */
+ testcase( i==141 ); /* BY */
+ testcase( i==142 ); /* INITIALLY */
+ testcase( i==143 ); /* ALL */
+ testcase( i==144 ); /* PRIMARY */
+ *pType = aKWCode[i];
+ break;
+ }
+ }
+ return n;
+}
+SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
+ int id = TK_ID;
+ keywordCode((char*)z, n, &id);
+ return id;
+}
+#define SQLITE_N_KEYWORD 145
+SQLITE_API int sqlite3_keyword_name(int i,const char **pzName,int *pnName){
+ if( i<0 || i>=SQLITE_N_KEYWORD ) return SQLITE_ERROR;
+ *pzName = zKWText + aKWOffset[i];
+ *pnName = aKWLen[i];
+ return SQLITE_OK;
+}
+SQLITE_API int sqlite3_keyword_count(void){ return SQLITE_N_KEYWORD; }
+SQLITE_API int sqlite3_keyword_check(const char *zName, int nName){
+ return TK_ID!=sqlite3KeywordCode((const u8*)zName, nName);
+}
+
+/************** End of keywordhash.h *****************************************/
+/************** Continuing where we left off in tokenize.c *******************/
+
+
+/*
+** If X is a character that can be used in an identifier then
+** IdChar(X) will be true. Otherwise it is false.
+**
+** For ASCII, any character with the high-order bit set is
+** allowed in an identifier. For 7-bit characters,
+** sqlite3IsIdChar[X] must be 1.
+**
+** For EBCDIC, the rules are more complex but have the same
+** end result.
+**
+** Ticket #1066. the SQL standard does not allow '$' in the
+** middle of identifiers. But many SQL implementations do.
+** SQLite will allow '$' in identifiers for compatibility.
+** But the feature is undocumented.
+*/
+#ifdef SQLITE_ASCII
+#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
+#endif
+#ifdef SQLITE_EBCDIC
+SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
+/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
+ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
+ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
+ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
+ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
+};
+#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
+#endif
+
+/* Make the IdChar function accessible from ctime.c and alter.c */
+SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+/*
+** Return the id of the next token in string (*pz). Before returning, set
+** (*pz) to point to the byte following the parsed token.
+*/
+static int getToken(const unsigned char **pz){
+ const unsigned char *z = *pz;
+ int t; /* Token type to return */
+ do {
+ z += sqlite3GetToken(z, &t);
+ }while( t==TK_SPACE );
+ if( t==TK_ID
+ || t==TK_STRING
+ || t==TK_JOIN_KW
+ || t==TK_WINDOW
+ || t==TK_OVER
+ || sqlite3ParserFallback(t)==TK_ID
+ ){
+ t = TK_ID;
+ }
+ *pz = z;
+ return t;
+}
+
+/*
+** The following three functions are called immediately after the tokenizer
+** reads the keywords WINDOW, OVER and FILTER, respectively, to determine
+** whether the token should be treated as a keyword or an SQL identifier.
+** This cannot be handled by the usual lemon %fallback method, due to
+** the ambiguity in some constructions. e.g.
+**
+** SELECT sum(x) OVER ...
+**
+** In the above, "OVER" might be a keyword, or it might be an alias for the
+** sum(x) expression. If a "%fallback ID OVER" directive were added to
+** grammar, then SQLite would always treat "OVER" as an alias, making it
+** impossible to call a window-function without a FILTER clause.
+**
+** WINDOW is treated as a keyword if:
+**
+** * the following token is an identifier, or a keyword that can fallback
+** to being an identifier, and
+** * the token after than one is TK_AS.
+**
+** OVER is a keyword if:
+**
+** * the previous token was TK_RP, and
+** * the next token is either TK_LP or an identifier.
+**
+** FILTER is a keyword if:
+**
+** * the previous token was TK_RP, and
+** * the next token is TK_LP.
+*/
+static int analyzeWindowKeyword(const unsigned char *z){
+ int t;
+ t = getToken(&z);
+ if( t!=TK_ID ) return TK_ID;
+ t = getToken(&z);
+ if( t!=TK_AS ) return TK_ID;
+ return TK_WINDOW;
+}
+static int analyzeOverKeyword(const unsigned char *z, int lastToken){
+ if( lastToken==TK_RP ){
+ int t = getToken(&z);
+ if( t==TK_LP || t==TK_ID ) return TK_OVER;
+ }
+ return TK_ID;
+}
+static int analyzeFilterKeyword(const unsigned char *z, int lastToken){
+ if( lastToken==TK_RP && getToken(&z)==TK_LP ){
+ return TK_FILTER;
+ }
+ return TK_ID;
+}
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+
+/*
+** Return the length (in bytes) of the token that begins at z[0].
+** Store the token type in *tokenType before returning.
+*/
+SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
+ int i, c;
+ switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
+ ** of the token. See the comment on the CC_ defines
+ ** above. */
+ case CC_SPACE: {
+ testcase( z[0]==' ' );
+ testcase( z[0]=='\t' );
+ testcase( z[0]=='\n' );
+ testcase( z[0]=='\f' );
+ testcase( z[0]=='\r' );
+ for(i=1; sqlite3Isspace(z[i]); i++){}
+ *tokenType = TK_SPACE;
+ return i;
+ }
+ case CC_MINUS: {
+ if( z[1]=='-' ){
+ for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
+ *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
+ return i;
+ }
+ *tokenType = TK_MINUS;
+ return 1;
+ }
+ case CC_LP: {
+ *tokenType = TK_LP;
+ return 1;
+ }
+ case CC_RP: {
+ *tokenType = TK_RP;
+ return 1;
+ }
+ case CC_SEMI: {
+ *tokenType = TK_SEMI;
+ return 1;
+ }
+ case CC_PLUS: {
+ *tokenType = TK_PLUS;
+ return 1;
+ }
+ case CC_STAR: {
+ *tokenType = TK_STAR;
+ return 1;
+ }
+ case CC_SLASH: {
+ if( z[1]!='*' || z[2]==0 ){
+ *tokenType = TK_SLASH;
+ return 1;
+ }
+ for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
+ if( c ) i++;
+ *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
+ return i;
+ }
+ case CC_PERCENT: {
+ *tokenType = TK_REM;
+ return 1;
+ }
+ case CC_EQ: {
+ *tokenType = TK_EQ;
+ return 1 + (z[1]=='=');
+ }
+ case CC_LT: {
+ if( (c=z[1])=='=' ){
+ *tokenType = TK_LE;
+ return 2;
+ }else if( c=='>' ){
+ *tokenType = TK_NE;
+ return 2;
+ }else if( c=='<' ){
+ *tokenType = TK_LSHIFT;
+ return 2;
+ }else{
+ *tokenType = TK_LT;
+ return 1;
+ }
+ }
+ case CC_GT: {
+ if( (c=z[1])=='=' ){
+ *tokenType = TK_GE;
+ return 2;
+ }else if( c=='>' ){
+ *tokenType = TK_RSHIFT;
+ return 2;
+ }else{
+ *tokenType = TK_GT;
+ return 1;
+ }
+ }
+ case CC_BANG: {
+ if( z[1]!='=' ){
+ *tokenType = TK_ILLEGAL;
+ return 1;
+ }else{
+ *tokenType = TK_NE;
+ return 2;
+ }
+ }
+ case CC_PIPE: {
+ if( z[1]!='|' ){
+ *tokenType = TK_BITOR;
+ return 1;
+ }else{
+ *tokenType = TK_CONCAT;
+ return 2;
+ }
+ }
+ case CC_COMMA: {
+ *tokenType = TK_COMMA;
+ return 1;
+ }
+ case CC_AND: {
+ *tokenType = TK_BITAND;
+ return 1;
+ }
+ case CC_TILDA: {
+ *tokenType = TK_BITNOT;
+ return 1;
+ }
+ case CC_QUOTE: {
+ int delim = z[0];
+ testcase( delim=='`' );
+ testcase( delim=='\'' );
+ testcase( delim=='"' );
+ for(i=1; (c=z[i])!=0; i++){
+ if( c==delim ){
+ if( z[i+1]==delim ){
+ i++;
+ }else{
+ break;
+ }
+ }
+ }
+ if( c=='\'' ){
+ *tokenType = TK_STRING;
+ return i+1;
+ }else if( c!=0 ){
+ *tokenType = TK_ID;
+ return i+1;
+ }else{
+ *tokenType = TK_ILLEGAL;
+ return i;
+ }
+ }
+ case CC_DOT: {
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ if( !sqlite3Isdigit(z[1]) )
+#endif
+ {
+ *tokenType = TK_DOT;
+ return 1;
+ }
+ /* If the next character is a digit, this is a floating point
+ ** number that begins with ".". Fall thru into the next case */
+ /* no break */ deliberate_fall_through
+ }
+ case CC_DIGIT: {
+ testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
+ testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
+ testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
+ testcase( z[0]=='9' );
+ *tokenType = TK_INTEGER;
+#ifndef SQLITE_OMIT_HEX_INTEGER
+ if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
+ for(i=3; sqlite3Isxdigit(z[i]); i++){}
+ return i;
+ }
+#endif
+ for(i=0; sqlite3Isdigit(z[i]); i++){}
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ if( z[i]=='.' ){
+ i++;
+ while( sqlite3Isdigit(z[i]) ){ i++; }
+ *tokenType = TK_FLOAT;
+ }
+ if( (z[i]=='e' || z[i]=='E') &&
+ ( sqlite3Isdigit(z[i+1])
+ || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
+ )
+ ){
+ i += 2;
+ while( sqlite3Isdigit(z[i]) ){ i++; }
+ *tokenType = TK_FLOAT;
+ }
+#endif
+ while( IdChar(z[i]) ){
+ *tokenType = TK_ILLEGAL;
+ i++;
+ }
+ return i;
+ }
+ case CC_QUOTE2: {
+ for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
+ *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
+ return i;
+ }
+ case CC_VARNUM: {
+ *tokenType = TK_VARIABLE;
+ for(i=1; sqlite3Isdigit(z[i]); i++){}
+ return i;
+ }
+ case CC_DOLLAR:
+ case CC_VARALPHA: {
+ int n = 0;
+ testcase( z[0]=='$' ); testcase( z[0]=='@' );
+ testcase( z[0]==':' ); testcase( z[0]=='#' );
+ *tokenType = TK_VARIABLE;
+ for(i=1; (c=z[i])!=0; i++){
+ if( IdChar(c) ){
+ n++;
+#ifndef SQLITE_OMIT_TCL_VARIABLE
+ }else if( c=='(' && n>0 ){
+ do{
+ i++;
+ }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
+ if( c==')' ){
+ i++;
+ }else{
+ *tokenType = TK_ILLEGAL;
+ }
+ break;
+ }else if( c==':' && z[i+1]==':' ){
+ i++;
+#endif
+ }else{
+ break;
+ }
+ }
+ if( n==0 ) *tokenType = TK_ILLEGAL;
+ return i;
+ }
+ case CC_KYWD: {
+ for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
+ if( IdChar(z[i]) ){
+ /* This token started out using characters that can appear in keywords,
+ ** but z[i] is a character not allowed within keywords, so this must
+ ** be an identifier instead */
+ i++;
+ break;
+ }
+ *tokenType = TK_ID;
+ return keywordCode((char*)z, i, tokenType);
+ }
+ case CC_X: {
+#ifndef SQLITE_OMIT_BLOB_LITERAL
+ testcase( z[0]=='x' ); testcase( z[0]=='X' );
+ if( z[1]=='\'' ){
+ *tokenType = TK_BLOB;
+ for(i=2; sqlite3Isxdigit(z[i]); i++){}
+ if( z[i]!='\'' || i%2 ){
+ *tokenType = TK_ILLEGAL;
+ while( z[i] && z[i]!='\'' ){ i++; }
+ }
+ if( z[i] ) i++;
+ return i;
+ }
+#endif
+ /* If it is not a BLOB literal, then it must be an ID, since no
+ ** SQL keywords start with the letter 'x'. Fall through */
+ /* no break */ deliberate_fall_through
+ }
+ case CC_ID: {
+ i = 1;
+ break;
+ }
+ case CC_NUL: {
+ *tokenType = TK_ILLEGAL;
+ return 0;
+ }
+ default: {
+ *tokenType = TK_ILLEGAL;
+ return 1;
+ }
+ }
+ while( IdChar(z[i]) ){ i++; }
+ *tokenType = TK_ID;
+ return i;
+}
+
+/*
+** Run the parser on the given SQL string. The parser structure is
+** passed in. An SQLITE_ status code is returned. If an error occurs
+** then an and attempt is made to write an error message into
+** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
+** error message.
+*/
+SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
+ int nErr = 0; /* Number of errors encountered */
+ void *pEngine; /* The LEMON-generated LALR(1) parser */
+ int n = 0; /* Length of the next token token */
+ int tokenType; /* type of the next token */
+ int lastTokenParsed = -1; /* type of the previous token */
+ sqlite3 *db = pParse->db; /* The database connection */
+ int mxSqlLen; /* Max length of an SQL string */
+#ifdef sqlite3Parser_ENGINEALWAYSONSTACK
+ yyParser sEngine; /* Space to hold the Lemon-generated Parser object */
+#endif
+ VVA_ONLY( u8 startedWithOom = db->mallocFailed );
+
+ assert( zSql!=0 );
+ mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
+ if( db->nVdbeActive==0 ){
+ AtomicStore(&db->u1.isInterrupted, 0);
+ }
+ pParse->rc = SQLITE_OK;
+ pParse->zTail = zSql;
+ assert( pzErrMsg!=0 );
+#ifdef SQLITE_DEBUG
+ if( db->flags & SQLITE_ParserTrace ){
+ printf("parser: [[[%s]]]\n", zSql);
+ sqlite3ParserTrace(stdout, "parser: ");
+ }else{
+ sqlite3ParserTrace(0, 0);
+ }
+#endif
+#ifdef sqlite3Parser_ENGINEALWAYSONSTACK
+ pEngine = &sEngine;
+ sqlite3ParserInit(pEngine, pParse);
+#else
+ pEngine = sqlite3ParserAlloc(sqlite3Malloc, pParse);
+ if( pEngine==0 ){
+ sqlite3OomFault(db);
+ return SQLITE_NOMEM_BKPT;
+ }
+#endif
+ assert( pParse->pNewTable==0 );
+ assert( pParse->pNewTrigger==0 );
+ assert( pParse->nVar==0 );
+ assert( pParse->pVList==0 );
+ pParse->pParentParse = db->pParse;
+ db->pParse = pParse;
+ while( 1 ){
+ n = sqlite3GetToken((u8*)zSql, &tokenType);
+ mxSqlLen -= n;
+ if( mxSqlLen<0 ){
+ pParse->rc = SQLITE_TOOBIG;
+ break;
+ }
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ if( tokenType>=TK_WINDOW ){
+ assert( tokenType==TK_SPACE || tokenType==TK_OVER || tokenType==TK_FILTER
+ || tokenType==TK_ILLEGAL || tokenType==TK_WINDOW
+ );
+#else
+ if( tokenType>=TK_SPACE ){
+ assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+ if( AtomicLoad(&db->u1.isInterrupted) ){
+ pParse->rc = SQLITE_INTERRUPT;
+ break;
+ }
+ if( tokenType==TK_SPACE ){
+ zSql += n;
+ continue;
+ }
+ if( zSql[0]==0 ){
+ /* Upon reaching the end of input, call the parser two more times
+ ** with tokens TK_SEMI and 0, in that order. */
+ if( lastTokenParsed==TK_SEMI ){
+ tokenType = 0;
+ }else if( lastTokenParsed==0 ){
+ break;
+ }else{
+ tokenType = TK_SEMI;
+ }
+ n = 0;
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ }else if( tokenType==TK_WINDOW ){
+ assert( n==6 );
+ tokenType = analyzeWindowKeyword((const u8*)&zSql[6]);
+ }else if( tokenType==TK_OVER ){
+ assert( n==4 );
+ tokenType = analyzeOverKeyword((const u8*)&zSql[4], lastTokenParsed);
+ }else if( tokenType==TK_FILTER ){
+ assert( n==6 );
+ tokenType = analyzeFilterKeyword((const u8*)&zSql[6], lastTokenParsed);
+#endif /* SQLITE_OMIT_WINDOWFUNC */
+ }else{
+ sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
+ break;
+ }
+ }
+ pParse->sLastToken.z = zSql;
+ pParse->sLastToken.n = n;
+ sqlite3Parser(pEngine, tokenType, pParse->sLastToken);
+ lastTokenParsed = tokenType;
+ zSql += n;
+ assert( db->mallocFailed==0 || pParse->rc!=SQLITE_OK || startedWithOom );
+ if( pParse->rc!=SQLITE_OK ) break;
+ }
+ assert( nErr==0 );
+#ifdef YYTRACKMAXSTACKDEPTH
+ sqlite3_mutex_enter(sqlite3MallocMutex());
+ sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
+ sqlite3ParserStackPeak(pEngine)
+ );
+ sqlite3_mutex_leave(sqlite3MallocMutex());
+#endif /* YYDEBUG */
+#ifdef sqlite3Parser_ENGINEALWAYSONSTACK
+ sqlite3ParserFinalize(pEngine);
+#else
+ sqlite3ParserFree(pEngine, sqlite3_free);
+#endif
+ if( db->mallocFailed ){
+ pParse->rc = SQLITE_NOMEM_BKPT;
+ }
+ if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
+ pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
+ }
+ assert( pzErrMsg!=0 );
+ if( pParse->zErrMsg ){
+ *pzErrMsg = pParse->zErrMsg;
+ sqlite3_log(pParse->rc, "%s in \"%s\"",
+ *pzErrMsg, pParse->zTail);
+ pParse->zErrMsg = 0;
+ nErr++;
+ }
+ pParse->zTail = zSql;
+ if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
+ sqlite3VdbeDelete(pParse->pVdbe);
+ pParse->pVdbe = 0;
+ }
+#ifndef SQLITE_OMIT_SHARED_CACHE
+ if( pParse->nested==0 ){
+ sqlite3DbFree(db, pParse->aTableLock);
+ pParse->aTableLock = 0;
+ pParse->nTableLock = 0;
+ }
+#endif
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ sqlite3_free(pParse->apVtabLock);
+#endif
+
+ if( !IN_SPECIAL_PARSE ){
+ /* If the pParse->declareVtab flag is set, do not delete any table
+ ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
+ ** will take responsibility for freeing the Table structure.
+ */
+ sqlite3DeleteTable(db, pParse->pNewTable);
+ }
+ if( !IN_RENAME_OBJECT ){
+ sqlite3DeleteTrigger(db, pParse->pNewTrigger);
+ }
+
+ if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
+ sqlite3DbFree(db, pParse->pVList);
+ while( pParse->pAinc ){
+ AutoincInfo *p = pParse->pAinc;
+ pParse->pAinc = p->pNext;
+ sqlite3DbFreeNN(db, p);
+ }
+ while( pParse->pZombieTab ){
+ Table *p = pParse->pZombieTab;
+ pParse->pZombieTab = p->pNextZombie;
+ sqlite3DeleteTable(db, p);
+ }
+ db->pParse = pParse->pParentParse;
+ pParse->pParentParse = 0;
+ assert( nErr==0 || pParse->rc!=SQLITE_OK );
+ return nErr;
+}
+
+
+#ifdef SQLITE_ENABLE_NORMALIZE
+/*
+** Insert a single space character into pStr if the current string
+** ends with an identifier
+*/
+static void addSpaceSeparator(sqlite3_str *pStr){
+ if( pStr->nChar && sqlite3IsIdChar(pStr->zText[pStr->nChar-1]) ){
+ sqlite3_str_append(pStr, " ", 1);
+ }
+}
+
+/*
+** Compute a normalization of the SQL given by zSql[0..nSql-1]. Return
+** the normalization in space obtained from sqlite3DbMalloc(). Or return
+** NULL if anything goes wrong or if zSql is NULL.
+*/
+SQLITE_PRIVATE char *sqlite3Normalize(
+ Vdbe *pVdbe, /* VM being reprepared */
+ const char *zSql /* The original SQL string */
+){
+ sqlite3 *db; /* The database connection */
+ int i; /* Next unread byte of zSql[] */
+ int n; /* length of current token */
+ int tokenType; /* type of current token */
+ int prevType = 0; /* Previous non-whitespace token */
+ int nParen; /* Number of nested levels of parentheses */
+ int iStartIN; /* Start of RHS of IN operator in z[] */
+ int nParenAtIN; /* Value of nParent at start of RHS of IN operator */
+ u32 j; /* Bytes of normalized SQL generated so far */
+ sqlite3_str *pStr; /* The normalized SQL string under construction */
+
+ db = sqlite3VdbeDb(pVdbe);
+ tokenType = -1;
+ nParen = iStartIN = nParenAtIN = 0;
+ pStr = sqlite3_str_new(db);
+ assert( pStr!=0 ); /* sqlite3_str_new() never returns NULL */
+ for(i=0; zSql[i] && pStr->accError==0; i+=n){
+ if( tokenType!=TK_SPACE ){
+ prevType = tokenType;
+ }
+ n = sqlite3GetToken((unsigned char*)zSql+i, &tokenType);
+ if( NEVER(n<=0) ) break;
+ switch( tokenType ){
+ case TK_SPACE: {
+ break;
+ }
+ case TK_NULL: {
+ if( prevType==TK_IS || prevType==TK_NOT ){
+ sqlite3_str_append(pStr, " NULL", 5);
+ break;
+ }
+ /* Fall through */
+ }
+ case TK_STRING:
+ case TK_INTEGER:
+ case TK_FLOAT:
+ case TK_VARIABLE:
+ case TK_BLOB: {
+ sqlite3_str_append(pStr, "?", 1);
+ break;
+ }
+ case TK_LP: {
+ nParen++;
+ if( prevType==TK_IN ){
+ iStartIN = pStr->nChar;
+ nParenAtIN = nParen;
+ }
+ sqlite3_str_append(pStr, "(", 1);
+ break;
+ }
+ case TK_RP: {
+ if( iStartIN>0 && nParen==nParenAtIN ){
+ assert( pStr->nChar>=(u32)iStartIN );
+ pStr->nChar = iStartIN+1;
+ sqlite3_str_append(pStr, "?,?,?", 5);
+ iStartIN = 0;
+ }
+ nParen--;
+ sqlite3_str_append(pStr, ")", 1);
+ break;
+ }
+ case TK_ID: {
+ iStartIN = 0;
+ j = pStr->nChar;
+ if( sqlite3Isquote(zSql[i]) ){
+ char *zId = sqlite3DbStrNDup(db, zSql+i, n);
+ int nId;
+ int eType = 0;
+ if( zId==0 ) break;
+ sqlite3Dequote(zId);
+ if( zSql[i]=='"' && sqlite3VdbeUsesDoubleQuotedString(pVdbe, zId) ){
+ sqlite3_str_append(pStr, "?", 1);
+ sqlite3DbFree(db, zId);
+ break;
+ }
+ nId = sqlite3Strlen30(zId);
+ if( sqlite3GetToken((u8*)zId, &eType)==nId && eType==TK_ID ){
+ addSpaceSeparator(pStr);
+ sqlite3_str_append(pStr, zId, nId);
+ }else{
+ sqlite3_str_appendf(pStr, "\"%w\"", zId);
+ }
+ sqlite3DbFree(db, zId);
+ }else{
+ addSpaceSeparator(pStr);
+ sqlite3_str_append(pStr, zSql+i, n);
+ }
+ while( j<pStr->nChar ){
+ pStr->zText[j] = sqlite3Tolower(pStr->zText[j]);
+ j++;
+ }
+ break;
+ }
+ case TK_SELECT: {
+ iStartIN = 0;
+ /* fall through */
+ }
+ default: {
+ if( sqlite3IsIdChar(zSql[i]) ) addSpaceSeparator(pStr);
+ j = pStr->nChar;
+ sqlite3_str_append(pStr, zSql+i, n);
+ while( j<pStr->nChar ){
+ pStr->zText[j] = sqlite3Toupper(pStr->zText[j]);
+ j++;
+ }
+ break;
+ }
+ }
+ }
+ if( tokenType!=TK_SEMI ) sqlite3_str_append(pStr, ";", 1);
+ return sqlite3_str_finish(pStr);
+}
+#endif /* SQLITE_ENABLE_NORMALIZE */
+
+/************** End of tokenize.c ********************************************/
+/************** Begin file complete.c ****************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** An tokenizer for SQL
+**
+** This file contains C code that implements the sqlite3_complete() API.
+** This code used to be part of the tokenizer.c source file. But by
+** separating it out, the code will be automatically omitted from
+** static links that do not use it.
+*/
+/* #include "sqliteInt.h" */
+#ifndef SQLITE_OMIT_COMPLETE
+
+/*
+** This is defined in tokenize.c. We just have to import the definition.
+*/
+#ifndef SQLITE_AMALGAMATION
+#ifdef SQLITE_ASCII
+#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
+#endif
+#ifdef SQLITE_EBCDIC
+SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
+#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
+#endif
+#endif /* SQLITE_AMALGAMATION */
+
+
+/*
+** Token types used by the sqlite3_complete() routine. See the header
+** comments on that procedure for additional information.
+*/
+#define tkSEMI 0
+#define tkWS 1
+#define tkOTHER 2
+#ifndef SQLITE_OMIT_TRIGGER
+#define tkEXPLAIN 3
+#define tkCREATE 4
+#define tkTEMP 5
+#define tkTRIGGER 6
+#define tkEND 7
+#endif
+
+/*
+** Return TRUE if the given SQL string ends in a semicolon.
+**
+** Special handling is require for CREATE TRIGGER statements.
+** Whenever the CREATE TRIGGER keywords are seen, the statement
+** must end with ";END;".
+**
+** This implementation uses a state machine with 8 states:
+**
+** (0) INVALID We have not yet seen a non-whitespace character.
+**
+** (1) START At the beginning or end of an SQL statement. This routine
+** returns 1 if it ends in the START state and 0 if it ends
+** in any other state.
+**
+** (2) NORMAL We are in the middle of statement which ends with a single
+** semicolon.
+**
+** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
+** a statement.
+**
+** (4) CREATE The keyword CREATE has been seen at the beginning of a
+** statement, possibly preceded by EXPLAIN and/or followed by
+** TEMP or TEMPORARY
+**
+** (5) TRIGGER We are in the middle of a trigger definition that must be
+** ended by a semicolon, the keyword END, and another semicolon.
+**
+** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
+** the end of a trigger definition.
+**
+** (7) END We've seen the ";END" of the ";END;" that occurs at the end
+** of a trigger definition.
+**
+** Transitions between states above are determined by tokens extracted
+** from the input. The following tokens are significant:
+**
+** (0) tkSEMI A semicolon.
+** (1) tkWS Whitespace.
+** (2) tkOTHER Any other SQL token.
+** (3) tkEXPLAIN The "explain" keyword.
+** (4) tkCREATE The "create" keyword.
+** (5) tkTEMP The "temp" or "temporary" keyword.
+** (6) tkTRIGGER The "trigger" keyword.
+** (7) tkEND The "end" keyword.
+**
+** Whitespace never causes a state transition and is always ignored.
+** This means that a SQL string of all whitespace is invalid.
+**
+** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
+** to recognize the end of a trigger can be omitted. All we have to do
+** is look for a semicolon that is not part of an string or comment.
+*/
+SQLITE_API int sqlite3_complete(const char *zSql){
+ u8 state = 0; /* Current state, using numbers defined in header comment */
+ u8 token; /* Value of the next token */
+
+#ifndef SQLITE_OMIT_TRIGGER
+ /* A complex statement machine used to detect the end of a CREATE TRIGGER
+ ** statement. This is the normal case.
+ */
+ static const u8 trans[8][8] = {
+ /* Token: */
+ /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
+ /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
+ /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
+ /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
+ /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
+ /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
+ /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
+ /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
+ /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
+ };
+#else
+ /* If triggers are not supported by this compile then the statement machine
+ ** used to detect the end of a statement is much simpler
+ */
+ static const u8 trans[3][3] = {
+ /* Token: */
+ /* State: ** SEMI WS OTHER */
+ /* 0 INVALID: */ { 1, 0, 2, },
+ /* 1 START: */ { 1, 1, 2, },
+ /* 2 NORMAL: */ { 1, 2, 2, },
+ };
+#endif /* SQLITE_OMIT_TRIGGER */
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( zSql==0 ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+
+ while( *zSql ){
+ switch( *zSql ){
+ case ';': { /* A semicolon */
+ token = tkSEMI;
+ break;
+ }
+ case ' ':
+ case '\r':
+ case '\t':
+ case '\n':
+ case '\f': { /* White space is ignored */
+ token = tkWS;
+ break;
+ }
+ case '/': { /* C-style comments */
+ if( zSql[1]!='*' ){
+ token = tkOTHER;
+ break;
+ }
+ zSql += 2;
+ while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
+ if( zSql[0]==0 ) return 0;
+ zSql++;
+ token = tkWS;
+ break;
+ }
+ case '-': { /* SQL-style comments from "--" to end of line */
+ if( zSql[1]!='-' ){
+ token = tkOTHER;
+ break;
+ }
+ while( *zSql && *zSql!='\n' ){ zSql++; }
+ if( *zSql==0 ) return state==1;
+ token = tkWS;
+ break;
+ }
+ case '[': { /* Microsoft-style identifiers in [...] */
+ zSql++;
+ while( *zSql && *zSql!=']' ){ zSql++; }
+ if( *zSql==0 ) return 0;
+ token = tkOTHER;
+ break;
+ }
+ case '`': /* Grave-accent quoted symbols used by MySQL */
+ case '"': /* single- and double-quoted strings */
+ case '\'': {
+ int c = *zSql;
+ zSql++;
+ while( *zSql && *zSql!=c ){ zSql++; }
+ if( *zSql==0 ) return 0;
+ token = tkOTHER;
+ break;
+ }
+ default: {
+#ifdef SQLITE_EBCDIC
+ unsigned char c;
+#endif
+ if( IdChar((u8)*zSql) ){
+ /* Keywords and unquoted identifiers */
+ int nId;
+ for(nId=1; IdChar(zSql[nId]); nId++){}
+#ifdef SQLITE_OMIT_TRIGGER
+ token = tkOTHER;
+#else
+ switch( *zSql ){
+ case 'c': case 'C': {
+ if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
+ token = tkCREATE;
+ }else{
+ token = tkOTHER;
+ }
+ break;
+ }
+ case 't': case 'T': {
+ if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
+ token = tkTRIGGER;
+ }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
+ token = tkTEMP;
+ }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
+ token = tkTEMP;
+ }else{
+ token = tkOTHER;
+ }
+ break;
+ }
+ case 'e': case 'E': {
+ if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
+ token = tkEND;
+ }else
+#ifndef SQLITE_OMIT_EXPLAIN
+ if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
+ token = tkEXPLAIN;
+ }else
+#endif
+ {
+ token = tkOTHER;
+ }
+ break;
+ }
+ default: {
+ token = tkOTHER;
+ break;
+ }
+ }
+#endif /* SQLITE_OMIT_TRIGGER */
+ zSql += nId-1;
+ }else{
+ /* Operators and special symbols */
+ token = tkOTHER;
+ }
+ break;
+ }
+ }
+ state = trans[state][token];
+ zSql++;
+ }
+ return state==1;
+}
+
+#ifndef SQLITE_OMIT_UTF16
+/*
+** This routine is the same as the sqlite3_complete() routine described
+** above, except that the parameter is required to be UTF-16 encoded, not
+** UTF-8.
+*/
+SQLITE_API int sqlite3_complete16(const void *zSql){
+ sqlite3_value *pVal;
+ char const *zSql8;
+ int rc;
+
+#ifndef SQLITE_OMIT_AUTOINIT
+ rc = sqlite3_initialize();
+ if( rc ) return rc;
+#endif
+ pVal = sqlite3ValueNew(0);
+ sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
+ zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
+ if( zSql8 ){
+ rc = sqlite3_complete(zSql8);
+ }else{
+ rc = SQLITE_NOMEM_BKPT;
+ }
+ sqlite3ValueFree(pVal);
+ return rc & 0xff;
+}
+#endif /* SQLITE_OMIT_UTF16 */
+#endif /* SQLITE_OMIT_COMPLETE */
+
+/************** End of complete.c ********************************************/
+/************** Begin file main.c ********************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** Main file for the SQLite library. The routines in this file
+** implement the programmer interface to the library. Routines in
+** other files are for internal use by SQLite and should not be
+** accessed by users of the library.
+*/
+/* #include "sqliteInt.h" */
+
+#ifdef SQLITE_ENABLE_FTS3
+/************** Include fts3.h in the middle of main.c ***********************/
+/************** Begin file fts3.h ********************************************/
+/*
+** 2006 Oct 10
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This header file is used by programs that want to link against the
+** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
+*/
+/* #include "sqlite3.h" */
+
+#if 0
+extern "C" {
+#endif /* __cplusplus */
+
+SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
+
+#if 0
+} /* extern "C" */
+#endif /* __cplusplus */
+
+/************** End of fts3.h ************************************************/
+/************** Continuing where we left off in main.c ***********************/
+#endif
+#ifdef SQLITE_ENABLE_RTREE
+/************** Include rtree.h in the middle of main.c **********************/
+/************** Begin file rtree.h *******************************************/
+/*
+** 2008 May 26
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This header file is used by programs that want to link against the
+** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
+*/
+/* #include "sqlite3.h" */
+
+#ifdef SQLITE_OMIT_VIRTUALTABLE
+# undef SQLITE_ENABLE_RTREE
+#endif
+
+#if 0
+extern "C" {
+#endif /* __cplusplus */
+
+SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
+
+#if 0
+} /* extern "C" */
+#endif /* __cplusplus */
+
+/************** End of rtree.h ***********************************************/
+/************** Continuing where we left off in main.c ***********************/
+#endif
+#if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
+/************** Include sqliteicu.h in the middle of main.c ******************/
+/************** Begin file sqliteicu.h ***************************************/
+/*
+** 2008 May 26
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This header file is used by programs that want to link against the
+** ICU extension. All it does is declare the sqlite3IcuInit() interface.
+*/
+/* #include "sqlite3.h" */
+
+#if 0
+extern "C" {
+#endif /* __cplusplus */
+
+SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
+
+#if 0
+} /* extern "C" */
+#endif /* __cplusplus */
+
+/************** End of sqliteicu.h *******************************************/
+/************** Continuing where we left off in main.c ***********************/
+#endif
+
+/*
+** This is an extension initializer that is a no-op and always
+** succeeds, except that it fails if the fault-simulation is set
+** to 500.
+*/
+static int sqlite3TestExtInit(sqlite3 *db){
+ (void)db;
+ return sqlite3FaultSim(500);
+}
+
+
+/*
+** Forward declarations of external module initializer functions
+** for modules that need them.
+*/
+#ifdef SQLITE_ENABLE_FTS1
+SQLITE_PRIVATE int sqlite3Fts1Init(sqlite3*);
+#endif
+#ifdef SQLITE_ENABLE_FTS2
+SQLITE_PRIVATE int sqlite3Fts2Init(sqlite3*);
+#endif
+#ifdef SQLITE_ENABLE_FTS5
+SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
+#endif
+#ifdef SQLITE_ENABLE_JSON1
+SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
+#endif
+#ifdef SQLITE_ENABLE_STMTVTAB
+SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
+#endif
+
+/*
+** An array of pointers to extension initializer functions for
+** built-in extensions.
+*/
+static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = {
+#ifdef SQLITE_ENABLE_FTS1
+ sqlite3Fts1Init,
+#endif
+#ifdef SQLITE_ENABLE_FTS2
+ sqlite3Fts2Init,
+#endif
+#ifdef SQLITE_ENABLE_FTS3
+ sqlite3Fts3Init,
+#endif
+#ifdef SQLITE_ENABLE_FTS5
+ sqlite3Fts5Init,
+#endif
+#if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
+ sqlite3IcuInit,
+#endif
+#ifdef SQLITE_ENABLE_RTREE
+ sqlite3RtreeInit,
+#endif
+#ifdef SQLITE_ENABLE_DBPAGE_VTAB
+ sqlite3DbpageRegister,
+#endif
+#ifdef SQLITE_ENABLE_DBSTAT_VTAB
+ sqlite3DbstatRegister,
+#endif
+ sqlite3TestExtInit,
+#ifdef SQLITE_ENABLE_JSON1
+ sqlite3Json1Init,
+#endif
+#ifdef SQLITE_ENABLE_STMTVTAB
+ sqlite3StmtVtabInit,
+#endif
+#ifdef SQLITE_ENABLE_BYTECODE_VTAB
+ sqlite3VdbeBytecodeVtabInit,
+#endif
+};
+
+#ifndef SQLITE_AMALGAMATION
+/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
+** contains the text of SQLITE_VERSION macro.
+*/
+SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
+#endif
+
+/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
+** a pointer to the to the sqlite3_version[] string constant.
+*/
+SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
+
+/* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
+** pointer to a string constant whose value is the same as the
+** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
+** an edited copy of the amalgamation, then the last four characters of
+** the hash might be different from SQLITE_SOURCE_ID.
+*/
+/* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */
+
+/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
+** returns an integer equal to SQLITE_VERSION_NUMBER.
+*/
+SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
+
+/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
+** zero if and only if SQLite was compiled with mutexing code omitted due to
+** the SQLITE_THREADSAFE compile-time option being set to 0.
+*/
+SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
+
+/*
+** When compiling the test fixture or with debugging enabled (on Win32),
+** this variable being set to non-zero will cause OSTRACE macros to emit
+** extra diagnostic information.
+*/
+#ifdef SQLITE_HAVE_OS_TRACE
+# ifndef SQLITE_DEBUG_OS_TRACE
+# define SQLITE_DEBUG_OS_TRACE 0
+# endif
+ int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
+#endif
+
+#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
+/*
+** If the following function pointer is not NULL and if
+** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
+** I/O active are written using this function. These messages
+** are intended for debugging activity only.
+*/
+SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
+#endif
+
+/*
+** If the following global variable points to a string which is the
+** name of a directory, then that directory will be used to store
+** temporary files.
+**
+** See also the "PRAGMA temp_store_directory" SQL command.
+*/
+SQLITE_API char *sqlite3_temp_directory = 0;
+
+/*
+** If the following global variable points to a string which is the
+** name of a directory, then that directory will be used to store
+** all database files specified with a relative pathname.
+**
+** See also the "PRAGMA data_store_directory" SQL command.
+*/
+SQLITE_API char *sqlite3_data_directory = 0;
+
+/*
+** Initialize SQLite.
+**
+** This routine must be called to initialize the memory allocation,
+** VFS, and mutex subsystems prior to doing any serious work with
+** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
+** this routine will be called automatically by key routines such as
+** sqlite3_open().
+**
+** This routine is a no-op except on its very first call for the process,
+** or for the first call after a call to sqlite3_shutdown.
+**
+** The first thread to call this routine runs the initialization to
+** completion. If subsequent threads call this routine before the first
+** thread has finished the initialization process, then the subsequent
+** threads must block until the first thread finishes with the initialization.
+**
+** The first thread might call this routine recursively. Recursive
+** calls to this routine should not block, of course. Otherwise the
+** initialization process would never complete.
+**
+** Let X be the first thread to enter this routine. Let Y be some other
+** thread. Then while the initial invocation of this routine by X is
+** incomplete, it is required that:
+**
+** * Calls to this routine from Y must block until the outer-most
+** call by X completes.
+**
+** * Recursive calls to this routine from thread X return immediately
+** without blocking.
+*/
+SQLITE_API int sqlite3_initialize(void){
+ MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */
+ int rc; /* Result code */
+#ifdef SQLITE_EXTRA_INIT
+ int bRunExtraInit = 0; /* Extra initialization needed */
+#endif
+
+#ifdef SQLITE_OMIT_WSD
+ rc = sqlite3_wsd_init(4096, 24);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+#endif
+
+ /* If the following assert() fails on some obscure processor/compiler
+ ** combination, the work-around is to set the correct pointer
+ ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
+ assert( SQLITE_PTRSIZE==sizeof(char*) );
+
+ /* If SQLite is already completely initialized, then this call
+ ** to sqlite3_initialize() should be a no-op. But the initialization
+ ** must be complete. So isInit must not be set until the very end
+ ** of this routine.
+ */
+ if( sqlite3GlobalConfig.isInit ){
+ sqlite3MemoryBarrier();
+ return SQLITE_OK;
+ }
+
+ /* Make sure the mutex subsystem is initialized. If unable to
+ ** initialize the mutex subsystem, return early with the error.
+ ** If the system is so sick that we are unable to allocate a mutex,
+ ** there is not much SQLite is going to be able to do.
+ **
+ ** The mutex subsystem must take care of serializing its own
+ ** initialization.
+ */
+ rc = sqlite3MutexInit();
+ if( rc ) return rc;
+
+ /* Initialize the malloc() system and the recursive pInitMutex mutex.
+ ** This operation is protected by the STATIC_MAIN mutex. Note that
+ ** MutexAlloc() is called for a static mutex prior to initializing the
+ ** malloc subsystem - this implies that the allocation of a static
+ ** mutex must not require support from the malloc subsystem.
+ */
+ MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
+ sqlite3_mutex_enter(pMainMtx);
+ sqlite3GlobalConfig.isMutexInit = 1;
+ if( !sqlite3GlobalConfig.isMallocInit ){
+ rc = sqlite3MallocInit();
+ }
+ if( rc==SQLITE_OK ){
+ sqlite3GlobalConfig.isMallocInit = 1;
+ if( !sqlite3GlobalConfig.pInitMutex ){
+ sqlite3GlobalConfig.pInitMutex =
+ sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
+ if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
+ rc = SQLITE_NOMEM_BKPT;
+ }
+ }
+ }
+ if( rc==SQLITE_OK ){
+ sqlite3GlobalConfig.nRefInitMutex++;
+ }
+ sqlite3_mutex_leave(pMainMtx);
+
+ /* If rc is not SQLITE_OK at this point, then either the malloc
+ ** subsystem could not be initialized or the system failed to allocate
+ ** the pInitMutex mutex. Return an error in either case. */
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+
+ /* Do the rest of the initialization under the recursive mutex so
+ ** that we will be able to handle recursive calls into
+ ** sqlite3_initialize(). The recursive calls normally come through
+ ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
+ ** recursive calls might also be possible.
+ **
+ ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
+ ** to the xInit method, so the xInit method need not be threadsafe.
+ **
+ ** The following mutex is what serializes access to the appdef pcache xInit
+ ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
+ ** call to sqlite3PcacheInitialize().
+ */
+ sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
+ if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
+ sqlite3GlobalConfig.inProgress = 1;
+#ifdef SQLITE_ENABLE_SQLLOG
+ {
+ extern void sqlite3_init_sqllog(void);
+ sqlite3_init_sqllog();
+ }
+#endif
+ memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
+ sqlite3RegisterBuiltinFunctions();
+ if( sqlite3GlobalConfig.isPCacheInit==0 ){
+ rc = sqlite3PcacheInitialize();
+ }
+ if( rc==SQLITE_OK ){
+ sqlite3GlobalConfig.isPCacheInit = 1;
+ rc = sqlite3OsInit();
+ }
+#ifdef SQLITE_ENABLE_DESERIALIZE
+ if( rc==SQLITE_OK ){
+ rc = sqlite3MemdbInit();
+ }
+#endif
+ if( rc==SQLITE_OK ){
+ sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
+ sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
+ sqlite3MemoryBarrier();
+ sqlite3GlobalConfig.isInit = 1;
+#ifdef SQLITE_EXTRA_INIT
+ bRunExtraInit = 1;
+#endif
+ }
+ sqlite3GlobalConfig.inProgress = 0;
+ }
+ sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
+
+ /* Go back under the static mutex and clean up the recursive
+ ** mutex to prevent a resource leak.
+ */
+ sqlite3_mutex_enter(pMainMtx);
+ sqlite3GlobalConfig.nRefInitMutex--;
+ if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
+ assert( sqlite3GlobalConfig.nRefInitMutex==0 );
+ sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
+ sqlite3GlobalConfig.pInitMutex = 0;
+ }
+ sqlite3_mutex_leave(pMainMtx);
+
+ /* The following is just a sanity check to make sure SQLite has
+ ** been compiled correctly. It is important to run this code, but
+ ** we don't want to run it too often and soak up CPU cycles for no
+ ** reason. So we run it once during initialization.
+ */
+#ifndef NDEBUG
+#ifndef SQLITE_OMIT_FLOATING_POINT
+ /* This section of code's only "output" is via assert() statements. */
+ if( rc==SQLITE_OK ){
+ u64 x = (((u64)1)<<63)-1;
+ double y;
+ assert(sizeof(x)==8);
+ assert(sizeof(x)==sizeof(y));
+ memcpy(&y, &x, 8);
+ assert( sqlite3IsNaN(y) );
+ }
+#endif
+#endif
+
+ /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
+ ** compile-time option.
+ */
+#ifdef SQLITE_EXTRA_INIT
+ if( bRunExtraInit ){
+ int SQLITE_EXTRA_INIT(const char*);
+ rc = SQLITE_EXTRA_INIT(0);
+ }
+#endif
+
+ return rc;
+}
+
+/*
+** Undo the effects of sqlite3_initialize(). Must not be called while
+** there are outstanding database connections or memory allocations or
+** while any part of SQLite is otherwise in use in any thread. This
+** routine is not threadsafe. But it is safe to invoke this routine
+** on when SQLite is already shut down. If SQLite is already shut down
+** when this routine is invoked, then this routine is a harmless no-op.
+*/
+SQLITE_API int sqlite3_shutdown(void){
+#ifdef SQLITE_OMIT_WSD
+ int rc = sqlite3_wsd_init(4096, 24);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+#endif
+
+ if( sqlite3GlobalConfig.isInit ){
+#ifdef SQLITE_EXTRA_SHUTDOWN
+ void SQLITE_EXTRA_SHUTDOWN(void);
+ SQLITE_EXTRA_SHUTDOWN();
+#endif
+ sqlite3_os_end();
+ sqlite3_reset_auto_extension();
+ sqlite3GlobalConfig.isInit = 0;
+ }
+ if( sqlite3GlobalConfig.isPCacheInit ){
+ sqlite3PcacheShutdown();
+ sqlite3GlobalConfig.isPCacheInit = 0;
+ }
+ if( sqlite3GlobalConfig.isMallocInit ){
+ sqlite3MallocEnd();
+ sqlite3GlobalConfig.isMallocInit = 0;
+
+#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
+ /* The heap subsystem has now been shutdown and these values are supposed
+ ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
+ ** which would rely on that heap subsystem; therefore, make sure these
+ ** values cannot refer to heap memory that was just invalidated when the
+ ** heap subsystem was shutdown. This is only done if the current call to
+ ** this function resulted in the heap subsystem actually being shutdown.
+ */
+ sqlite3_data_directory = 0;
+ sqlite3_temp_directory = 0;
+#endif
+ }
+ if( sqlite3GlobalConfig.isMutexInit ){
+ sqlite3MutexEnd();
+ sqlite3GlobalConfig.isMutexInit = 0;
+ }
+
+ return SQLITE_OK;
+}
+
+/*
+** This API allows applications to modify the global configuration of
+** the SQLite library at run-time.
+**
+** This routine should only be called when there are no outstanding
+** database connections or memory allocations. This routine is not
+** threadsafe. Failure to heed these warnings can lead to unpredictable
+** behavior.
+*/
+SQLITE_API int sqlite3_config(int op, ...){
+ va_list ap;
+ int rc = SQLITE_OK;
+
+ /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
+ ** the SQLite library is in use. */
+ if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
+
+ va_start(ap, op);
+ switch( op ){
+
+ /* Mutex configuration options are only available in a threadsafe
+ ** compile.
+ */
+#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
+ case SQLITE_CONFIG_SINGLETHREAD: {
+ /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
+ ** Single-thread. */
+ sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
+ sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
+ break;
+ }
+#endif
+#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
+ case SQLITE_CONFIG_MULTITHREAD: {
+ /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
+ ** Multi-thread. */
+ sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
+ sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
+ break;
+ }
+#endif
+#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
+ case SQLITE_CONFIG_SERIALIZED: {
+ /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
+ ** Serialized. */
+ sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
+ sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
+ break;
+ }
+#endif
+#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
+ case SQLITE_CONFIG_MUTEX: {
+ /* Specify an alternative mutex implementation */
+ sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
+ break;
+ }
+#endif
+#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
+ case SQLITE_CONFIG_GETMUTEX: {
+ /* Retrieve the current mutex implementation */
+ *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
+ break;
+ }
+#endif
+
+ case SQLITE_CONFIG_MALLOC: {
+ /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
+ ** single argument which is a pointer to an instance of the
+ ** sqlite3_mem_methods structure. The argument specifies alternative
+ ** low-level memory allocation routines to be used in place of the memory
+ ** allocation routines built into SQLite. */
+ sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
+ break;
+ }
+ case SQLITE_CONFIG_GETMALLOC: {
+ /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
+ ** single argument which is a pointer to an instance of the
+ ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
+ ** filled with the currently defined memory allocation routines. */
+ if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
+ *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
+ break;
+ }
+ case SQLITE_CONFIG_MEMSTATUS: {
+ /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
+ ** single argument of type int, interpreted as a boolean, which enables
+ ** or disables the collection of memory allocation statistics. */
+ sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
+ break;
+ }
+ case SQLITE_CONFIG_SMALL_MALLOC: {
+ sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
+ break;
+ }
+ case SQLITE_CONFIG_PAGECACHE: {
+ /* EVIDENCE-OF: R-18761-36601 There are three arguments to
+ ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
+ ** the size of each page cache line (sz), and the number of cache lines
+ ** (N). */
+ sqlite3GlobalConfig.pPage = va_arg(ap, void*);
+ sqlite3GlobalConfig.szPage = va_arg(ap, int);
+ sqlite3GlobalConfig.nPage = va_arg(ap, int);
+ break;
+ }
+ case SQLITE_CONFIG_PCACHE_HDRSZ: {
+ /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
+ ** a single parameter which is a pointer to an integer and writes into
+ ** that integer the number of extra bytes per page required for each page
+ ** in SQLITE_CONFIG_PAGECACHE. */
+ *va_arg(ap, int*) =
+ sqlite3HeaderSizeBtree() +
+ sqlite3HeaderSizePcache() +
+ sqlite3HeaderSizePcache1();
+ break;
+ }
+
+ case SQLITE_CONFIG_PCACHE: {
+ /* no-op */
+ break;
+ }
+ case SQLITE_CONFIG_GETPCACHE: {
+ /* now an error */
+ rc = SQLITE_ERROR;
+ break;
+ }
+
+ case SQLITE_CONFIG_PCACHE2: {
+ /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
+ ** single argument which is a pointer to an sqlite3_pcache_methods2
+ ** object. This object specifies the interface to a custom page cache
+ ** implementation. */
+ sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
+ break;
+ }
+ case SQLITE_CONFIG_GETPCACHE2: {
+ /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
+ ** single argument which is a pointer to an sqlite3_pcache_methods2
+ ** object. SQLite copies of the current page cache implementation into
+ ** that object. */
+ if( sqlite3GlobalConfig.pcache2.xInit==0 ){
+ sqlite3PCacheSetDefault();
+ }
+ *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
+ break;
+ }
+
+/* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
+** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
+** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
+#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
+ case SQLITE_CONFIG_HEAP: {
+ /* EVIDENCE-OF: R-19854-42126 There are three arguments to
+ ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
+ ** number of bytes in the memory buffer, and the minimum allocation size.
+ */
+ sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
+ sqlite3GlobalConfig.nHeap = va_arg(ap, int);
+ sqlite3GlobalConfig.mnReq = va_arg(ap, int);
+
+ if( sqlite3GlobalConfig.mnReq<1 ){
+ sqlite3GlobalConfig.mnReq = 1;
+ }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
+ /* cap min request size at 2^12 */
+ sqlite3GlobalConfig.mnReq = (1<<12);
+ }
+
+ if( sqlite3GlobalConfig.pHeap==0 ){
+ /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
+ ** is NULL, then SQLite reverts to using its default memory allocator
+ ** (the system malloc() implementation), undoing any prior invocation of
+ ** SQLITE_CONFIG_MALLOC.
+ **
+ ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
+ ** revert to its default implementation when sqlite3_initialize() is run
+ */
+ memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
+ }else{
+ /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
+ ** alternative memory allocator is engaged to handle all of SQLites
+ ** memory allocation needs. */
+#ifdef SQLITE_ENABLE_MEMSYS3
+ sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
+#endif
+#ifdef SQLITE_ENABLE_MEMSYS5
+ sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
+#endif
+ }
+ break;
+ }
+#endif
+
+ case SQLITE_CONFIG_LOOKASIDE: {
+ sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
+ sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
+ break;
+ }
+
+ /* Record a pointer to the logger function and its first argument.
+ ** The default is NULL. Logging is disabled if the function pointer is
+ ** NULL.
+ */
+ case SQLITE_CONFIG_LOG: {
+ /* MSVC is picky about pulling func ptrs from va lists.
+ ** http://support.microsoft.com/kb/47961
+ ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
+ */
+ typedef void(*LOGFUNC_t)(void*,int,const char*);
+ sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
+ sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
+ break;
+ }
+
+ /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
+ ** can be changed at start-time using the
+ ** sqlite3_config(SQLITE_CONFIG_URI,1) or
+ ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
+ */
+ case SQLITE_CONFIG_URI: {
+ /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
+ ** argument of type int. If non-zero, then URI handling is globally
+ ** enabled. If the parameter is zero, then URI handling is globally
+ ** disabled. */
+ sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
+ break;
+ }
+
+ case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
+ /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
+ ** option takes a single integer argument which is interpreted as a
+ ** boolean in order to enable or disable the use of covering indices for
+ ** full table scans in the query optimizer. */
+ sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
+ break;
+ }
+
+#ifdef SQLITE_ENABLE_SQLLOG
+ case SQLITE_CONFIG_SQLLOG: {
+ typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
+ sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
+ sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
+ break;
+ }
+#endif
+
+ case SQLITE_CONFIG_MMAP_SIZE: {
+ /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
+ ** integer (sqlite3_int64) values that are the default mmap size limit
+ ** (the default setting for PRAGMA mmap_size) and the maximum allowed
+ ** mmap size limit. */
+ sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
+ sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
+ /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
+ ** negative, then that argument is changed to its compile-time default.
+ **
+ ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
+ ** silently truncated if necessary so that it does not exceed the
+ ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
+ ** compile-time option.
+ */
+ if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
+ mxMmap = SQLITE_MAX_MMAP_SIZE;
+ }
+ if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
+ if( szMmap>mxMmap) szMmap = mxMmap;
+ sqlite3GlobalConfig.mxMmap = mxMmap;
+ sqlite3GlobalConfig.szMmap = szMmap;
+ break;
+ }
+
+#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
+ case SQLITE_CONFIG_WIN32_HEAPSIZE: {
+ /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
+ ** unsigned integer value that specifies the maximum size of the created
+ ** heap. */
+ sqlite3GlobalConfig.nHeap = va_arg(ap, int);
+ break;
+ }
+#endif
+
+ case SQLITE_CONFIG_PMASZ: {
+ sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
+ break;
+ }
+
+ case SQLITE_CONFIG_STMTJRNL_SPILL: {
+ sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
+ break;
+ }
+
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+ case SQLITE_CONFIG_SORTERREF_SIZE: {
+ int iVal = va_arg(ap, int);
+ if( iVal<0 ){
+ iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
+ }
+ sqlite3GlobalConfig.szSorterRef = (u32)iVal;
+ break;
+ }
+#endif /* SQLITE_ENABLE_SORTER_REFERENCES */
+
+#ifdef SQLITE_ENABLE_DESERIALIZE
+ case SQLITE_CONFIG_MEMDB_MAXSIZE: {
+ sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);
+ break;
+ }
+#endif /* SQLITE_ENABLE_DESERIALIZE */
+
+ default: {
+ rc = SQLITE_ERROR;
+ break;
+ }
+ }
+ va_end(ap);
+ return rc;
+}
+
+/*
+** Set up the lookaside buffers for a database connection.
+** Return SQLITE_OK on success.
+** If lookaside is already active, return SQLITE_BUSY.
+**
+** The sz parameter is the number of bytes in each lookaside slot.
+** The cnt parameter is the number of slots. If pStart is NULL the
+** space for the lookaside memory is obtained from sqlite3_malloc().
+** If pStart is not NULL then it is sz*cnt bytes of memory to use for
+** the lookaside memory.
+*/
+static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
+#ifndef SQLITE_OMIT_LOOKASIDE
+ void *pStart;
+ sqlite3_int64 szAlloc = sz*(sqlite3_int64)cnt;
+ int nBig; /* Number of full-size slots */
+ int nSm; /* Number smaller LOOKASIDE_SMALL-byte slots */
+
+ if( sqlite3LookasideUsed(db,0)>0 ){
+ return SQLITE_BUSY;
+ }
+ /* Free any existing lookaside buffer for this handle before
+ ** allocating a new one so we don't have to have space for
+ ** both at the same time.
+ */
+ if( db->lookaside.bMalloced ){
+ sqlite3_free(db->lookaside.pStart);
+ }
+ /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
+ ** than a pointer to be useful.
+ */
+ sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
+ if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
+ if( cnt<0 ) cnt = 0;
+ if( sz==0 || cnt==0 ){
+ sz = 0;
+ pStart = 0;
+ }else if( pBuf==0 ){
+ sqlite3BeginBenignMalloc();
+ pStart = sqlite3Malloc( szAlloc ); /* IMP: R-61949-35727 */
+ sqlite3EndBenignMalloc();
+ if( pStart ) szAlloc = sqlite3MallocSize(pStart);
+ }else{
+ pStart = pBuf;
+ }
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+ if( sz>=LOOKASIDE_SMALL*3 ){
+ nBig = szAlloc/(3*LOOKASIDE_SMALL+sz);
+ nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
+ }else if( sz>=LOOKASIDE_SMALL*2 ){
+ nBig = szAlloc/(LOOKASIDE_SMALL+sz);
+ nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
+ }else
+#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
+ if( sz>0 ){
+ nBig = szAlloc/sz;
+ nSm = 0;
+ }else{
+ nBig = nSm = 0;
+ }
+ db->lookaside.pStart = pStart;
+ db->lookaside.pInit = 0;
+ db->lookaside.pFree = 0;
+ db->lookaside.sz = (u16)sz;
+ db->lookaside.szTrue = (u16)sz;
+ if( pStart ){
+ int i;
+ LookasideSlot *p;
+ assert( sz > (int)sizeof(LookasideSlot*) );
+ p = (LookasideSlot*)pStart;
+ for(i=0; i<nBig; i++){
+ p->pNext = db->lookaside.pInit;
+ db->lookaside.pInit = p;
+ p = (LookasideSlot*)&((u8*)p)[sz];
+ }
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+ db->lookaside.pSmallInit = 0;
+ db->lookaside.pSmallFree = 0;
+ db->lookaside.pMiddle = p;
+ for(i=0; i<nSm; i++){
+ p->pNext = db->lookaside.pSmallInit;
+ db->lookaside.pSmallInit = p;
+ p = (LookasideSlot*)&((u8*)p)[LOOKASIDE_SMALL];
+ }
+#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
+ assert( ((uptr)p)<=szAlloc + (uptr)pStart );
+ db->lookaside.pEnd = p;
+ db->lookaside.bDisable = 0;
+ db->lookaside.bMalloced = pBuf==0 ?1:0;
+ db->lookaside.nSlot = nBig+nSm;
+ }else{
+ db->lookaside.pStart = db;
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+ db->lookaside.pSmallInit = 0;
+ db->lookaside.pSmallFree = 0;
+ db->lookaside.pMiddle = db;
+#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
+ db->lookaside.pEnd = db;
+ db->lookaside.bDisable = 1;
+ db->lookaside.sz = 0;
+ db->lookaside.bMalloced = 0;
+ db->lookaside.nSlot = 0;
+ }
+ assert( sqlite3LookasideUsed(db,0)==0 );
+#endif /* SQLITE_OMIT_LOOKASIDE */
+ return SQLITE_OK;
+}
+
+/*
+** Return the mutex associated with a database connection.
+*/
+SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ return db->mutex;
+}
+
+/*
+** Free up as much memory as we can from the given database
+** connection.
+*/
+SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
+ int i;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ sqlite3BtreeEnterAll(db);
+ for(i=0; i<db->nDb; i++){
+ Btree *pBt = db->aDb[i].pBt;
+ if( pBt ){
+ Pager *pPager = sqlite3BtreePager(pBt);
+ sqlite3PagerShrink(pPager);
+ }
+ }
+ sqlite3BtreeLeaveAll(db);
+ sqlite3_mutex_leave(db->mutex);
+ return SQLITE_OK;
+}
+
+/*
+** Flush any dirty pages in the pager-cache for any attached database
+** to disk.
+*/
+SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
+ int i;
+ int rc = SQLITE_OK;
+ int bSeenBusy = 0;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ sqlite3BtreeEnterAll(db);
+ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
+ Btree *pBt = db->aDb[i].pBt;
+ if( pBt && sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
+ Pager *pPager = sqlite3BtreePager(pBt);
+ rc = sqlite3PagerFlush(pPager);
+ if( rc==SQLITE_BUSY ){
+ bSeenBusy = 1;
+ rc = SQLITE_OK;
+ }
+ }
+ }
+ sqlite3BtreeLeaveAll(db);
+ sqlite3_mutex_leave(db->mutex);
+ return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
+}
+
+/*
+** Configuration settings for an individual database connection
+*/
+SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
+ va_list ap;
+ int rc;
+ va_start(ap, op);
+ switch( op ){
+ case SQLITE_DBCONFIG_MAINDBNAME: {
+ /* IMP: R-06824-28531 */
+ /* IMP: R-36257-52125 */
+ db->aDb[0].zDbSName = va_arg(ap,char*);
+ rc = SQLITE_OK;
+ break;
+ }
+ case SQLITE_DBCONFIG_LOOKASIDE: {
+ void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
+ int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
+ int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
+ rc = setupLookaside(db, pBuf, sz, cnt);
+ break;
+ }
+ default: {
+ static const struct {
+ int op; /* The opcode */
+ u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
+ } aFlagOp[] = {
+ { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
+ { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
+ { SQLITE_DBCONFIG_ENABLE_VIEW, SQLITE_EnableView },
+ { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
+ { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
+ { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
+ { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG },
+ { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP },
+ { SQLITE_DBCONFIG_RESET_DATABASE, SQLITE_ResetDatabase },
+ { SQLITE_DBCONFIG_DEFENSIVE, SQLITE_Defensive },
+ { SQLITE_DBCONFIG_WRITABLE_SCHEMA, SQLITE_WriteSchema|
+ SQLITE_NoSchemaError },
+ { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, SQLITE_LegacyAlter },
+ { SQLITE_DBCONFIG_DQS_DDL, SQLITE_DqsDDL },
+ { SQLITE_DBCONFIG_DQS_DML, SQLITE_DqsDML },
+ { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT, SQLITE_LegacyFileFmt },
+ { SQLITE_DBCONFIG_TRUSTED_SCHEMA, SQLITE_TrustedSchema },
+ };
+ unsigned int i;
+ rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
+ for(i=0; i<ArraySize(aFlagOp); i++){
+ if( aFlagOp[i].op==op ){
+ int onoff = va_arg(ap, int);
+ int *pRes = va_arg(ap, int*);
+ u64 oldFlags = db->flags;
+ if( onoff>0 ){
+ db->flags |= aFlagOp[i].mask;
+ }else if( onoff==0 ){
+ db->flags &= ~(u64)aFlagOp[i].mask;
+ }
+ if( oldFlags!=db->flags ){
+ sqlite3ExpirePreparedStatements(db, 0);
+ }
+ if( pRes ){
+ *pRes = (db->flags & aFlagOp[i].mask)!=0;
+ }
+ rc = SQLITE_OK;
+ break;
+ }
+ }
+ break;
+ }
+ }
+ va_end(ap);
+ return rc;
+}
+
+/*
+** This is the default collating function named "BINARY" which is always
+** available.
+*/
+static int binCollFunc(
+ void *NotUsed,
+ int nKey1, const void *pKey1,
+ int nKey2, const void *pKey2
+){
+ int rc, n;
+ UNUSED_PARAMETER(NotUsed);
+ n = nKey1<nKey2 ? nKey1 : nKey2;
+ /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
+ ** strings byte by byte using the memcmp() function from the standard C
+ ** library. */
+ assert( pKey1 && pKey2 );
+ rc = memcmp(pKey1, pKey2, n);
+ if( rc==0 ){
+ rc = nKey1 - nKey2;
+ }
+ return rc;
+}
+
+/*
+** This is the collating function named "RTRIM" which is always
+** available. Ignore trailing spaces.
+*/
+static int rtrimCollFunc(
+ void *pUser,
+ int nKey1, const void *pKey1,
+ int nKey2, const void *pKey2
+){
+ const u8 *pK1 = (const u8*)pKey1;
+ const u8 *pK2 = (const u8*)pKey2;
+ while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--;
+ while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--;
+ return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2);
+}
+
+/*
+** Return true if CollSeq is the default built-in BINARY.
+*/
+SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq *p){
+ assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 );
+ return p==0 || p->xCmp==binCollFunc;
+}
+
+/*
+** Another built-in collating sequence: NOCASE.
+**
+** This collating sequence is intended to be used for "case independent
+** comparison". SQLite's knowledge of upper and lower case equivalents
+** extends only to the 26 characters used in the English language.
+**
+** At the moment there is only a UTF-8 implementation.
+*/
+static int nocaseCollatingFunc(
+ void *NotUsed,
+ int nKey1, const void *pKey1,
+ int nKey2, const void *pKey2
+){
+ int r = sqlite3StrNICmp(
+ (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
+ UNUSED_PARAMETER(NotUsed);
+ if( 0==r ){
+ r = nKey1-nKey2;
+ }
+ return r;
+}
+
+/*
+** Return the ROWID of the most recent insert
+*/
+SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ return db->lastRowid;
+}
+
+/*
+** Set the value returned by the sqlite3_last_insert_rowid() API function.
+*/
+SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ db->lastRowid = iRowid;
+ sqlite3_mutex_leave(db->mutex);
+}
+
+/*
+** Return the number of changes in the most recent call to sqlite3_exec().
+*/
+SQLITE_API int sqlite3_changes(sqlite3 *db){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ return db->nChange;
+}
+
+/*
+** Return the number of changes since the database handle was opened.
+*/
+SQLITE_API int sqlite3_total_changes(sqlite3 *db){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ return db->nTotalChange;
+}
+
+/*
+** Close all open savepoints. This function only manipulates fields of the
+** database handle object, it does not close any savepoints that may be open
+** at the b-tree/pager level.
+*/
+SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
+ while( db->pSavepoint ){
+ Savepoint *pTmp = db->pSavepoint;
+ db->pSavepoint = pTmp->pNext;
+ sqlite3DbFree(db, pTmp);
+ }
+ db->nSavepoint = 0;
+ db->nStatement = 0;
+ db->isTransactionSavepoint = 0;
+}
+
+/*
+** Invoke the destructor function associated with FuncDef p, if any. Except,
+** if this is not the last copy of the function, do not invoke it. Multiple
+** copies of a single function are created when create_function() is called
+** with SQLITE_ANY as the encoding.
+*/
+static void functionDestroy(sqlite3 *db, FuncDef *p){
+ FuncDestructor *pDestructor = p->u.pDestructor;
+ if( pDestructor ){
+ pDestructor->nRef--;
+ if( pDestructor->nRef==0 ){
+ pDestructor->xDestroy(pDestructor->pUserData);
+ sqlite3DbFree(db, pDestructor);
+ }
+ }
+}
+
+/*
+** Disconnect all sqlite3_vtab objects that belong to database connection
+** db. This is called when db is being closed.
+*/
+static void disconnectAllVtab(sqlite3 *db){
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ int i;
+ HashElem *p;
+ sqlite3BtreeEnterAll(db);
+ for(i=0; i<db->nDb; i++){
+ Schema *pSchema = db->aDb[i].pSchema;
+ if( pSchema ){
+ for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
+ Table *pTab = (Table *)sqliteHashData(p);
+ if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
+ }
+ }
+ }
+ for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
+ Module *pMod = (Module *)sqliteHashData(p);
+ if( pMod->pEpoTab ){
+ sqlite3VtabDisconnect(db, pMod->pEpoTab);
+ }
+ }
+ sqlite3VtabUnlockList(db);
+ sqlite3BtreeLeaveAll(db);
+#else
+ UNUSED_PARAMETER(db);
+#endif
+}
+
+/*
+** Return TRUE if database connection db has unfinalized prepared
+** statements or unfinished sqlite3_backup objects.
+*/
+static int connectionIsBusy(sqlite3 *db){
+ int j;
+ assert( sqlite3_mutex_held(db->mutex) );
+ if( db->pVdbe ) return 1;
+ for(j=0; j<db->nDb; j++){
+ Btree *pBt = db->aDb[j].pBt;
+ if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
+ }
+ return 0;
+}
+
+/*
+** Close an existing SQLite database
+*/
+static int sqlite3Close(sqlite3 *db, int forceZombie){
+ if( !db ){
+ /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
+ ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
+ return SQLITE_OK;
+ }
+ if( !sqlite3SafetyCheckSickOrOk(db) ){
+ return SQLITE_MISUSE_BKPT;
+ }
+ sqlite3_mutex_enter(db->mutex);
+ if( db->mTrace & SQLITE_TRACE_CLOSE ){
+ db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
+ }
+
+ /* Force xDisconnect calls on all virtual tables */
+ disconnectAllVtab(db);
+
+ /* If a transaction is open, the disconnectAllVtab() call above
+ ** will not have called the xDisconnect() method on any virtual
+ ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
+ ** call will do so. We need to do this before the check for active
+ ** SQL statements below, as the v-table implementation may be storing
+ ** some prepared statements internally.
+ */
+ sqlite3VtabRollback(db);
+
+ /* Legacy behavior (sqlite3_close() behavior) is to return
+ ** SQLITE_BUSY if the connection can not be closed immediately.
+ */
+ if( !forceZombie && connectionIsBusy(db) ){
+ sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
+ "statements or unfinished backups");
+ sqlite3_mutex_leave(db->mutex);
+ return SQLITE_BUSY;
+ }
+
+#ifdef SQLITE_ENABLE_SQLLOG
+ if( sqlite3GlobalConfig.xSqllog ){
+ /* Closing the handle. Fourth parameter is passed the value 2. */
+ sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
+ }
+#endif
+
+ /* Convert the connection into a zombie and then close it.
+ */
+ db->magic = SQLITE_MAGIC_ZOMBIE;
+ sqlite3LeaveMutexAndCloseZombie(db);
+ return SQLITE_OK;
+}
+
+/*
+** Return the transaction state for a single databse, or the maximum
+** transaction state over all attached databases if zSchema is null.
+*/
+SQLITE_API int sqlite3_txn_state(sqlite3 *db, const char *zSchema){
+ int iDb, nDb;
+ int iTxn = -1;
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return -1;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ if( zSchema ){
+ nDb = iDb = sqlite3FindDbName(db, zSchema);
+ if( iDb<0 ) nDb--;
+ }else{
+ iDb = 0;
+ nDb = db->nDb-1;
+ }
+ for(; iDb<=nDb; iDb++){
+ Btree *pBt = db->aDb[iDb].pBt;
+ int x = pBt!=0 ? sqlite3BtreeTxnState(pBt) : SQLITE_TXN_NONE;
+ if( x>iTxn ) iTxn = x;
+ }
+ sqlite3_mutex_leave(db->mutex);
+ return iTxn;
+}
+
+/*
+** Two variations on the public interface for closing a database
+** connection. The sqlite3_close() version returns SQLITE_BUSY and
+** leaves the connection option if there are unfinalized prepared
+** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
+** version forces the connection to become a zombie if there are
+** unclosed resources, and arranges for deallocation when the last
+** prepare statement or sqlite3_backup closes.
+*/
+SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
+SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
+
+
+/*
+** Close the mutex on database connection db.
+**
+** Furthermore, if database connection db is a zombie (meaning that there
+** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
+** every sqlite3_stmt has now been finalized and every sqlite3_backup has
+** finished, then free all resources.
+*/
+SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
+ HashElem *i; /* Hash table iterator */
+ int j;
+
+ /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
+ ** or if the connection has not yet been closed by sqlite3_close_v2(),
+ ** then just leave the mutex and return.
+ */
+ if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
+ sqlite3_mutex_leave(db->mutex);
+ return;
+ }
+
+ /* If we reach this point, it means that the database connection has
+ ** closed all sqlite3_stmt and sqlite3_backup objects and has been
+ ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
+ ** go ahead and free all resources.
+ */
+
+ /* If a transaction is open, roll it back. This also ensures that if
+ ** any database schemas have been modified by an uncommitted transaction
+ ** they are reset. And that the required b-tree mutex is held to make
+ ** the pager rollback and schema reset an atomic operation. */
+ sqlite3RollbackAll(db, SQLITE_OK);
+
+ /* Free any outstanding Savepoint structures. */
+ sqlite3CloseSavepoints(db);
+
+ /* Close all database connections */
+ for(j=0; j<db->nDb; j++){
+ struct Db *pDb = &db->aDb[j];
+ if( pDb->pBt ){
+ sqlite3BtreeClose(pDb->pBt);
+ pDb->pBt = 0;
+ if( j!=1 ){
+ pDb->pSchema = 0;
+ }
+ }
+ }
+ /* Clear the TEMP schema separately and last */
+ if( db->aDb[1].pSchema ){
+ sqlite3SchemaClear(db->aDb[1].pSchema);
+ }
+ sqlite3VtabUnlockList(db);
+
+ /* Free up the array of auxiliary databases */
+ sqlite3CollapseDatabaseArray(db);
+ assert( db->nDb<=2 );
+ assert( db->aDb==db->aDbStatic );
+
+ /* Tell the code in notify.c that the connection no longer holds any
+ ** locks and does not require any further unlock-notify callbacks.
+ */
+ sqlite3ConnectionClosed(db);
+
+ for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
+ FuncDef *pNext, *p;
+ p = sqliteHashData(i);
+ do{
+ functionDestroy(db, p);
+ pNext = p->pNext;
+ sqlite3DbFree(db, p);
+ p = pNext;
+ }while( p );
+ }
+ sqlite3HashClear(&db->aFunc);
+ for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
+ CollSeq *pColl = (CollSeq *)sqliteHashData(i);
+ /* Invoke any destructors registered for collation sequence user data. */
+ for(j=0; j<3; j++){
+ if( pColl[j].xDel ){
+ pColl[j].xDel(pColl[j].pUser);
+ }
+ }
+ sqlite3DbFree(db, pColl);
+ }
+ sqlite3HashClear(&db->aCollSeq);
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
+ Module *pMod = (Module *)sqliteHashData(i);
+ sqlite3VtabEponymousTableClear(db, pMod);
+ sqlite3VtabModuleUnref(db, pMod);
+ }
+ sqlite3HashClear(&db->aModule);
+#endif
+
+ sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
+ sqlite3ValueFree(db->pErr);
+ sqlite3CloseExtensions(db);
+#if SQLITE_USER_AUTHENTICATION
+ sqlite3_free(db->auth.zAuthUser);
+ sqlite3_free(db->auth.zAuthPW);
+#endif
+
+ db->magic = SQLITE_MAGIC_ERROR;
+
+ /* The temp-database schema is allocated differently from the other schema
+ ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
+ ** So it needs to be freed here. Todo: Why not roll the temp schema into
+ ** the same sqliteMalloc() as the one that allocates the database
+ ** structure?
+ */
+ sqlite3DbFree(db, db->aDb[1].pSchema);
+ sqlite3_mutex_leave(db->mutex);
+ db->magic = SQLITE_MAGIC_CLOSED;
+ sqlite3_mutex_free(db->mutex);
+ assert( sqlite3LookasideUsed(db,0)==0 );
+ if( db->lookaside.bMalloced ){
+ sqlite3_free(db->lookaside.pStart);
+ }
+ sqlite3_free(db);
+}
+
+/*
+** Rollback all database files. If tripCode is not SQLITE_OK, then
+** any write cursors are invalidated ("tripped" - as in "tripping a circuit
+** breaker") and made to return tripCode if there are any further
+** attempts to use that cursor. Read cursors remain open and valid
+** but are "saved" in case the table pages are moved around.
+*/
+SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
+ int i;
+ int inTrans = 0;
+ int schemaChange;
+ assert( sqlite3_mutex_held(db->mutex) );
+ sqlite3BeginBenignMalloc();
+
+ /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
+ ** This is important in case the transaction being rolled back has
+ ** modified the database schema. If the b-tree mutexes are not taken
+ ** here, then another shared-cache connection might sneak in between
+ ** the database rollback and schema reset, which can cause false
+ ** corruption reports in some cases. */
+ sqlite3BtreeEnterAll(db);
+ schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
+
+ for(i=0; i<db->nDb; i++){
+ Btree *p = db->aDb[i].pBt;
+ if( p ){
+ if( sqlite3BtreeTxnState(p)==SQLITE_TXN_WRITE ){
+ inTrans = 1;
+ }
+ sqlite3BtreeRollback(p, tripCode, !schemaChange);
+ }
+ }
+ sqlite3VtabRollback(db);
+ sqlite3EndBenignMalloc();
+
+ if( schemaChange ){
+ sqlite3ExpirePreparedStatements(db, 0);
+ sqlite3ResetAllSchemasOfConnection(db);
+ }
+ sqlite3BtreeLeaveAll(db);
+
+ /* Any deferred constraint violations have now been resolved. */
+ db->nDeferredCons = 0;
+ db->nDeferredImmCons = 0;
+ db->flags &= ~(u64)SQLITE_DeferFKs;
+
+ /* If one has been configured, invoke the rollback-hook callback */
+ if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
+ db->xRollbackCallback(db->pRollbackArg);
+ }
+}
+
+/*
+** Return a static string containing the name corresponding to the error code
+** specified in the argument.
+*/
+#if defined(SQLITE_NEED_ERR_NAME)
+SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
+ const char *zName = 0;
+ int i, origRc = rc;
+ for(i=0; i<2 && zName==0; i++, rc &= 0xff){
+ switch( rc ){
+ case SQLITE_OK: zName = "SQLITE_OK"; break;
+ case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
+ case SQLITE_ERROR_SNAPSHOT: zName = "SQLITE_ERROR_SNAPSHOT"; break;
+ case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
+ case SQLITE_PERM: zName = "SQLITE_PERM"; break;
+ case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
+ case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
+ case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
+ case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
+ case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
+ case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
+ case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
+ case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
+ case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
+ case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
+ case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break;
+ case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
+ case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
+ case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
+ case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
+ case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
+ case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
+ case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
+ case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
+ case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
+ case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
+ case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
+ case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
+ case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
+ case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
+ case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
+ case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
+ case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
+ case SQLITE_IOERR_CHECKRESERVEDLOCK:
+ zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
+ case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
+ case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
+ case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
+ case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
+ case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
+ case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
+ case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
+ case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
+ case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
+ case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
+ case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
+ case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
+ case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
+ case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
+ case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
+ case SQLITE_FULL: zName = "SQLITE_FULL"; break;
+ case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
+ case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
+ case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
+ case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
+ case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
+ case SQLITE_CANTOPEN_SYMLINK: zName = "SQLITE_CANTOPEN_SYMLINK"; break;
+ case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
+ case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
+ case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
+ case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
+ case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
+ case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
+ case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
+ case SQLITE_CONSTRAINT_FOREIGNKEY:
+ zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
+ case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
+ case SQLITE_CONSTRAINT_PRIMARYKEY:
+ zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
+ case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
+ case SQLITE_CONSTRAINT_COMMITHOOK:
+ zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
+ case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
+ case SQLITE_CONSTRAINT_FUNCTION:
+ zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
+ case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
+ case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
+ case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
+ case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
+ case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
+ case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
+ case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
+ case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
+ case SQLITE_ROW: zName = "SQLITE_ROW"; break;
+ case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
+ case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
+ case SQLITE_NOTICE_RECOVER_ROLLBACK:
+ zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
+ case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
+ case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
+ case SQLITE_DONE: zName = "SQLITE_DONE"; break;
+ }
+ }
+ if( zName==0 ){
+ static char zBuf[50];
+ sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
+ zName = zBuf;
+ }
+ return zName;
+}
+#endif
+
+/*
+** Return a static string that describes the kind of error specified in the
+** argument.
+*/
+SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
+ static const char* const aMsg[] = {
+ /* SQLITE_OK */ "not an error",
+ /* SQLITE_ERROR */ "SQL logic error",
+ /* SQLITE_INTERNAL */ 0,
+ /* SQLITE_PERM */ "access permission denied",
+ /* SQLITE_ABORT */ "query aborted",
+ /* SQLITE_BUSY */ "database is locked",
+ /* SQLITE_LOCKED */ "database table is locked",
+ /* SQLITE_NOMEM */ "out of memory",
+ /* SQLITE_READONLY */ "attempt to write a readonly database",
+ /* SQLITE_INTERRUPT */ "interrupted",
+ /* SQLITE_IOERR */ "disk I/O error",
+ /* SQLITE_CORRUPT */ "database disk image is malformed",
+ /* SQLITE_NOTFOUND */ "unknown operation",
+ /* SQLITE_FULL */ "database or disk is full",
+ /* SQLITE_CANTOPEN */ "unable to open database file",
+ /* SQLITE_PROTOCOL */ "locking protocol",
+ /* SQLITE_EMPTY */ 0,
+ /* SQLITE_SCHEMA */ "database schema has changed",
+ /* SQLITE_TOOBIG */ "string or blob too big",
+ /* SQLITE_CONSTRAINT */ "constraint failed",
+ /* SQLITE_MISMATCH */ "datatype mismatch",
+ /* SQLITE_MISUSE */ "bad parameter or other API misuse",
+#ifdef SQLITE_DISABLE_LFS
+ /* SQLITE_NOLFS */ "large file support is disabled",
+#else
+ /* SQLITE_NOLFS */ 0,
+#endif
+ /* SQLITE_AUTH */ "authorization denied",
+ /* SQLITE_FORMAT */ 0,
+ /* SQLITE_RANGE */ "column index out of range",
+ /* SQLITE_NOTADB */ "file is not a database",
+ /* SQLITE_NOTICE */ "notification message",
+ /* SQLITE_WARNING */ "warning message",
+ };
+ const char *zErr = "unknown error";
+ switch( rc ){
+ case SQLITE_ABORT_ROLLBACK: {
+ zErr = "abort due to ROLLBACK";
+ break;
+ }
+ case SQLITE_ROW: {
+ zErr = "another row available";
+ break;
+ }
+ case SQLITE_DONE: {
+ zErr = "no more rows available";
+ break;
+ }
+ default: {
+ rc &= 0xff;
+ if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
+ zErr = aMsg[rc];
+ }
+ break;
+ }
+ }
+ return zErr;
+}
+
+/*
+** This routine implements a busy callback that sleeps and tries
+** again until a timeout value is reached. The timeout value is
+** an integer number of milliseconds passed in as the first
+** argument.
+**
+** Return non-zero to retry the lock. Return zero to stop trying
+** and cause SQLite to return SQLITE_BUSY.
+*/
+static int sqliteDefaultBusyCallback(
+ void *ptr, /* Database connection */
+ int count /* Number of times table has been busy */
+){
+#if SQLITE_OS_WIN || HAVE_USLEEP
+ /* This case is for systems that have support for sleeping for fractions of
+ ** a second. Examples: All windows systems, unix systems with usleep() */
+ static const u8 delays[] =
+ { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
+ static const u8 totals[] =
+ { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
+# define NDELAY ArraySize(delays)
+ sqlite3 *db = (sqlite3 *)ptr;
+ int tmout = db->busyTimeout;
+ int delay, prior;
+
+ assert( count>=0 );
+ if( count < NDELAY ){
+ delay = delays[count];
+ prior = totals[count];
+ }else{
+ delay = delays[NDELAY-1];
+ prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
+ }
+ if( prior + delay > tmout ){
+ delay = tmout - prior;
+ if( delay<=0 ) return 0;
+ }
+ sqlite3OsSleep(db->pVfs, delay*1000);
+ return 1;
+#else
+ /* This case for unix systems that lack usleep() support. Sleeping
+ ** must be done in increments of whole seconds */
+ sqlite3 *db = (sqlite3 *)ptr;
+ int tmout = ((sqlite3 *)ptr)->busyTimeout;
+ if( (count+1)*1000 > tmout ){
+ return 0;
+ }
+ sqlite3OsSleep(db->pVfs, 1000000);
+ return 1;
+#endif
+}
+
+/*
+** Invoke the given busy handler.
+**
+** This routine is called when an operation failed to acquire a
+** lock on VFS file pFile.
+**
+** If this routine returns non-zero, the lock is retried. If it
+** returns 0, the operation aborts with an SQLITE_BUSY error.
+*/
+SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
+ int rc;
+ if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
+ rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
+ if( rc==0 ){
+ p->nBusy = -1;
+ }else{
+ p->nBusy++;
+ }
+ return rc;
+}
+
+/*
+** This routine sets the busy callback for an Sqlite database to the
+** given callback function with the given argument.
+*/
+SQLITE_API int sqlite3_busy_handler(
+ sqlite3 *db,
+ int (*xBusy)(void*,int),
+ void *pArg
+){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ db->busyHandler.xBusyHandler = xBusy;
+ db->busyHandler.pBusyArg = pArg;
+ db->busyHandler.nBusy = 0;
+ db->busyTimeout = 0;
+ sqlite3_mutex_leave(db->mutex);
+ return SQLITE_OK;
+}
+
+#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
+/*
+** This routine sets the progress callback for an Sqlite database to the
+** given callback function with the given argument. The progress callback will
+** be invoked every nOps opcodes.
+*/
+SQLITE_API void sqlite3_progress_handler(
+ sqlite3 *db,
+ int nOps,
+ int (*xProgress)(void*),
+ void *pArg
+){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ if( nOps>0 ){
+ db->xProgress = xProgress;
+ db->nProgressOps = (unsigned)nOps;
+ db->pProgressArg = pArg;
+ }else{
+ db->xProgress = 0;
+ db->nProgressOps = 0;
+ db->pProgressArg = 0;
+ }
+ sqlite3_mutex_leave(db->mutex);
+}
+#endif
+
+
+/*
+** This routine installs a default busy handler that waits for the
+** specified number of milliseconds before returning 0.
+*/
+SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+#endif
+ if( ms>0 ){
+ sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
+ (void*)db);
+ db->busyTimeout = ms;
+ }else{
+ sqlite3_busy_handler(db, 0, 0);
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Cause any pending operation to stop at its earliest opportunity.
+*/
+SQLITE_API void sqlite3_interrupt(sqlite3 *db){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return;
+ }
+#endif
+ AtomicStore(&db->u1.isInterrupted, 1);
+}
+
+
+/*
+** This function is exactly the same as sqlite3_create_function(), except
+** that it is designed to be called by internal code. The difference is
+** that if a malloc() fails in sqlite3_create_function(), an error code
+** is returned and the mallocFailed flag cleared.
+*/
+SQLITE_PRIVATE int sqlite3CreateFunc(
+ sqlite3 *db,
+ const char *zFunctionName,
+ int nArg,
+ int enc,
+ void *pUserData,
+ void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value **),
+ void (*xFinal)(sqlite3_context*),
+ void (*xValue)(sqlite3_context*),
+ void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
+ FuncDestructor *pDestructor
+){
+ FuncDef *p;
+ int nName;
+ int extraFlags;
+
+ assert( sqlite3_mutex_held(db->mutex) );
+ assert( xValue==0 || xSFunc==0 );
+ if( zFunctionName==0 /* Must have a valid name */
+ || (xSFunc!=0 && xFinal!=0) /* Not both xSFunc and xFinal */
+ || ((xFinal==0)!=(xStep==0)) /* Both or neither of xFinal and xStep */
+ || ((xValue==0)!=(xInverse==0)) /* Both or neither of xValue, xInverse */
+ || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
+ || (255<(nName = sqlite3Strlen30( zFunctionName)))
+ ){
+ return SQLITE_MISUSE_BKPT;
+ }
+
+ assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
+ assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY );
+ extraFlags = enc & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|
+ SQLITE_SUBTYPE|SQLITE_INNOCUOUS);
+ enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
+
+ /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE. But
+ ** the meaning is inverted. So flip the bit. */
+ assert( SQLITE_FUNC_UNSAFE==SQLITE_INNOCUOUS );
+ extraFlags ^= SQLITE_FUNC_UNSAFE;
+
+
+#ifndef SQLITE_OMIT_UTF16
+ /* If SQLITE_UTF16 is specified as the encoding type, transform this
+ ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
+ ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
+ **
+ ** If SQLITE_ANY is specified, add three versions of the function
+ ** to the hash table.
+ */
+ if( enc==SQLITE_UTF16 ){
+ enc = SQLITE_UTF16NATIVE;
+ }else if( enc==SQLITE_ANY ){
+ int rc;
+ rc = sqlite3CreateFunc(db, zFunctionName, nArg,
+ (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE,
+ pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3CreateFunc(db, zFunctionName, nArg,
+ (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE,
+ pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
+ }
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ enc = SQLITE_UTF16BE;
+ }
+#else
+ enc = SQLITE_UTF8;
+#endif
+
+ /* Check if an existing function is being overridden or deleted. If so,
+ ** and there are active VMs, then return SQLITE_BUSY. If a function
+ ** is being overridden/deleted but there are no active VMs, allow the
+ ** operation to continue but invalidate all precompiled statements.
+ */
+ p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
+ if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
+ if( db->nVdbeActive ){
+ sqlite3ErrorWithMsg(db, SQLITE_BUSY,
+ "unable to delete/modify user-function due to active statements");
+ assert( !db->mallocFailed );
+ return SQLITE_BUSY;
+ }else{
+ sqlite3ExpirePreparedStatements(db, 0);
+ }
+ }
+
+ p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
+ assert(p || db->mallocFailed);
+ if( !p ){
+ return SQLITE_NOMEM_BKPT;
+ }
+
+ /* If an older version of the function with a configured destructor is
+ ** being replaced invoke the destructor function here. */
+ functionDestroy(db, p);
+
+ if( pDestructor ){
+ pDestructor->nRef++;
+ }
+ p->u.pDestructor = pDestructor;
+ p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
+ testcase( p->funcFlags & SQLITE_DETERMINISTIC );
+ testcase( p->funcFlags & SQLITE_DIRECTONLY );
+ p->xSFunc = xSFunc ? xSFunc : xStep;
+ p->xFinalize = xFinal;
+ p->xValue = xValue;
+ p->xInverse = xInverse;
+ p->pUserData = pUserData;
+ p->nArg = (u16)nArg;
+ return SQLITE_OK;
+}
+
+/*
+** Worker function used by utf-8 APIs that create new functions:
+**
+** sqlite3_create_function()
+** sqlite3_create_function_v2()
+** sqlite3_create_window_function()
+*/
+static int createFunctionApi(
+ sqlite3 *db,
+ const char *zFunc,
+ int nArg,
+ int enc,
+ void *p,
+ void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*),
+ void (*xValue)(sqlite3_context*),
+ void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
+ void(*xDestroy)(void*)
+){
+ int rc = SQLITE_ERROR;
+ FuncDestructor *pArg = 0;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ return SQLITE_MISUSE_BKPT;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ if( xDestroy ){
+ pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
+ if( !pArg ){
+ sqlite3OomFault(db);
+ xDestroy(p);
+ goto out;
+ }
+ pArg->nRef = 0;
+ pArg->xDestroy = xDestroy;
+ pArg->pUserData = p;
+ }
+ rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p,
+ xSFunc, xStep, xFinal, xValue, xInverse, pArg
+ );
+ if( pArg && pArg->nRef==0 ){
+ assert( rc!=SQLITE_OK );
+ xDestroy(p);
+ sqlite3_free(pArg);
+ }
+
+ out:
+ rc = sqlite3ApiExit(db, rc);
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+/*
+** Create new user functions.
+*/
+SQLITE_API int sqlite3_create_function(
+ sqlite3 *db,
+ const char *zFunc,
+ int nArg,
+ int enc,
+ void *p,
+ void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value **),
+ void (*xFinal)(sqlite3_context*)
+){
+ return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
+ xFinal, 0, 0, 0);
+}
+SQLITE_API int sqlite3_create_function_v2(
+ sqlite3 *db,
+ const char *zFunc,
+ int nArg,
+ int enc,
+ void *p,
+ void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value **),
+ void (*xFinal)(sqlite3_context*),
+ void (*xDestroy)(void *)
+){
+ return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
+ xFinal, 0, 0, xDestroy);
+}
+SQLITE_API int sqlite3_create_window_function(
+ sqlite3 *db,
+ const char *zFunc,
+ int nArg,
+ int enc,
+ void *p,
+ void (*xStep)(sqlite3_context*,int,sqlite3_value **),
+ void (*xFinal)(sqlite3_context*),
+ void (*xValue)(sqlite3_context*),
+ void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
+ void (*xDestroy)(void *)
+){
+ return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
+ xFinal, xValue, xInverse, xDestroy);
+}
+
+#ifndef SQLITE_OMIT_UTF16
+SQLITE_API int sqlite3_create_function16(
+ sqlite3 *db,
+ const void *zFunctionName,
+ int nArg,
+ int eTextRep,
+ void *p,
+ void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*)
+){
+ int rc;
+ char *zFunc8;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ assert( !db->mallocFailed );
+ zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
+ rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
+ sqlite3DbFree(db, zFunc8);
+ rc = sqlite3ApiExit(db, rc);
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+#endif
+
+
+/*
+** The following is the implementation of an SQL function that always
+** fails with an error message stating that the function is used in the
+** wrong context. The sqlite3_overload_function() API might construct
+** SQL function that use this routine so that the functions will exist
+** for name resolution but are actually overloaded by the xFindFunction
+** method of virtual tables.
+*/
+static void sqlite3InvalidFunction(
+ sqlite3_context *context, /* The function calling context */
+ int NotUsed, /* Number of arguments to the function */
+ sqlite3_value **NotUsed2 /* Value of each argument */
+){
+ const char *zName = (const char*)sqlite3_user_data(context);
+ char *zErr;
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ zErr = sqlite3_mprintf(
+ "unable to use function %s in the requested context", zName);
+ sqlite3_result_error(context, zErr, -1);
+ sqlite3_free(zErr);
+}
+
+/*
+** Declare that a function has been overloaded by a virtual table.
+**
+** If the function already exists as a regular global function, then
+** this routine is a no-op. If the function does not exist, then create
+** a new one that always throws a run-time error.
+**
+** When virtual tables intend to provide an overloaded function, they
+** should call this routine to make sure the global function exists.
+** A global function must exist in order for name resolution to work
+** properly.
+*/
+SQLITE_API int sqlite3_overload_function(
+ sqlite3 *db,
+ const char *zName,
+ int nArg
+){
+ int rc;
+ char *zCopy;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
+ return SQLITE_MISUSE_BKPT;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
+ sqlite3_mutex_leave(db->mutex);
+ if( rc ) return SQLITE_OK;
+ zCopy = sqlite3_mprintf(zName);
+ if( zCopy==0 ) return SQLITE_NOMEM;
+ return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
+ zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
+}
+
+#ifndef SQLITE_OMIT_TRACE
+/*
+** Register a trace function. The pArg from the previously registered trace
+** is returned.
+**
+** A NULL trace function means that no tracing is executes. A non-NULL
+** trace is a pointer to a function that is invoked at the start of each
+** SQL statement.
+*/
+#ifndef SQLITE_OMIT_DEPRECATED
+SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
+ void *pOld;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ pOld = db->pTraceArg;
+ db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
+ db->trace.xLegacy = xTrace;
+ db->pTraceArg = pArg;
+ sqlite3_mutex_leave(db->mutex);
+ return pOld;
+}
+#endif /* SQLITE_OMIT_DEPRECATED */
+
+/* Register a trace callback using the version-2 interface.
+*/
+SQLITE_API int sqlite3_trace_v2(
+ sqlite3 *db, /* Trace this connection */
+ unsigned mTrace, /* Mask of events to be traced */
+ int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
+ void *pArg /* Context */
+){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ return SQLITE_MISUSE_BKPT;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ if( mTrace==0 ) xTrace = 0;
+ if( xTrace==0 ) mTrace = 0;
+ db->mTrace = mTrace;
+ db->trace.xV2 = xTrace;
+ db->pTraceArg = pArg;
+ sqlite3_mutex_leave(db->mutex);
+ return SQLITE_OK;
+}
+
+#ifndef SQLITE_OMIT_DEPRECATED
+/*
+** Register a profile function. The pArg from the previously registered
+** profile function is returned.
+**
+** A NULL profile function means that no profiling is executes. A non-NULL
+** profile is a pointer to a function that is invoked at the conclusion of
+** each SQL statement that is run.
+*/
+SQLITE_API void *sqlite3_profile(
+ sqlite3 *db,
+ void (*xProfile)(void*,const char*,sqlite_uint64),
+ void *pArg
+){
+ void *pOld;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ pOld = db->pProfileArg;
+ db->xProfile = xProfile;
+ db->pProfileArg = pArg;
+ db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;
+ if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;
+ sqlite3_mutex_leave(db->mutex);
+ return pOld;
+}
+#endif /* SQLITE_OMIT_DEPRECATED */
+#endif /* SQLITE_OMIT_TRACE */
+
+/*
+** Register a function to be invoked when a transaction commits.
+** If the invoked function returns non-zero, then the commit becomes a
+** rollback.
+*/
+SQLITE_API void *sqlite3_commit_hook(
+ sqlite3 *db, /* Attach the hook to this database */
+ int (*xCallback)(void*), /* Function to invoke on each commit */
+ void *pArg /* Argument to the function */
+){
+ void *pOld;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ pOld = db->pCommitArg;
+ db->xCommitCallback = xCallback;
+ db->pCommitArg = pArg;
+ sqlite3_mutex_leave(db->mutex);
+ return pOld;
+}
+
+/*
+** Register a callback to be invoked each time a row is updated,
+** inserted or deleted using this database connection.
+*/
+SQLITE_API void *sqlite3_update_hook(
+ sqlite3 *db, /* Attach the hook to this database */
+ void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
+ void *pArg /* Argument to the function */
+){
+ void *pRet;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ pRet = db->pUpdateArg;
+ db->xUpdateCallback = xCallback;
+ db->pUpdateArg = pArg;
+ sqlite3_mutex_leave(db->mutex);
+ return pRet;
+}
+
+/*
+** Register a callback to be invoked each time a transaction is rolled
+** back by this database connection.
+*/
+SQLITE_API void *sqlite3_rollback_hook(
+ sqlite3 *db, /* Attach the hook to this database */
+ void (*xCallback)(void*), /* Callback function */
+ void *pArg /* Argument to the function */
+){
+ void *pRet;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ pRet = db->pRollbackArg;
+ db->xRollbackCallback = xCallback;
+ db->pRollbackArg = pArg;
+ sqlite3_mutex_leave(db->mutex);
+ return pRet;
+}
+
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+/*
+** Register a callback to be invoked each time a row is updated,
+** inserted or deleted using this database connection.
+*/
+SQLITE_API void *sqlite3_preupdate_hook(
+ sqlite3 *db, /* Attach the hook to this database */
+ void(*xCallback)( /* Callback function */
+ void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
+ void *pArg /* First callback argument */
+){
+ void *pRet;
+ sqlite3_mutex_enter(db->mutex);
+ pRet = db->pPreUpdateArg;
+ db->xPreUpdateCallback = xCallback;
+ db->pPreUpdateArg = pArg;
+ sqlite3_mutex_leave(db->mutex);
+ return pRet;
+}
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
+
+#ifndef SQLITE_OMIT_WAL
+/*
+** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
+** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
+** is greater than sqlite3.pWalArg cast to an integer (the value configured by
+** wal_autocheckpoint()).
+*/
+SQLITE_PRIVATE int sqlite3WalDefaultHook(
+ void *pClientData, /* Argument */
+ sqlite3 *db, /* Connection */
+ const char *zDb, /* Database */
+ int nFrame /* Size of WAL */
+){
+ if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
+ sqlite3BeginBenignMalloc();
+ sqlite3_wal_checkpoint(db, zDb);
+ sqlite3EndBenignMalloc();
+ }
+ return SQLITE_OK;
+}
+#endif /* SQLITE_OMIT_WAL */
+
+/*
+** Configure an sqlite3_wal_hook() callback to automatically checkpoint
+** a database after committing a transaction if there are nFrame or
+** more frames in the log file. Passing zero or a negative value as the
+** nFrame parameter disables automatic checkpoints entirely.
+**
+** The callback registered by this function replaces any existing callback
+** registered using sqlite3_wal_hook(). Likewise, registering a callback
+** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
+** configured by this function.
+*/
+SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
+#ifdef SQLITE_OMIT_WAL
+ UNUSED_PARAMETER(db);
+ UNUSED_PARAMETER(nFrame);
+#else
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+#endif
+ if( nFrame>0 ){
+ sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
+ }else{
+ sqlite3_wal_hook(db, 0, 0);
+ }
+#endif
+ return SQLITE_OK;
+}
+
+/*
+** Register a callback to be invoked each time a transaction is written
+** into the write-ahead-log by this database connection.
+*/
+SQLITE_API void *sqlite3_wal_hook(
+ sqlite3 *db, /* Attach the hook to this db handle */
+ int(*xCallback)(void *, sqlite3*, const char*, int),
+ void *pArg /* First argument passed to xCallback() */
+){
+#ifndef SQLITE_OMIT_WAL
+ void *pRet;
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ pRet = db->pWalArg;
+ db->xWalCallback = xCallback;
+ db->pWalArg = pArg;
+ sqlite3_mutex_leave(db->mutex);
+ return pRet;
+#else
+ return 0;
+#endif
+}
+
+/*
+** Checkpoint database zDb.
+*/
+SQLITE_API int sqlite3_wal_checkpoint_v2(
+ sqlite3 *db, /* Database handle */
+ const char *zDb, /* Name of attached database (or NULL) */
+ int eMode, /* SQLITE_CHECKPOINT_* value */
+ int *pnLog, /* OUT: Size of WAL log in frames */
+ int *pnCkpt /* OUT: Total number of frames checkpointed */
+){
+#ifdef SQLITE_OMIT_WAL
+ return SQLITE_OK;
+#else
+ int rc; /* Return code */
+ int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+#endif
+
+ /* Initialize the output variables to -1 in case an error occurs. */
+ if( pnLog ) *pnLog = -1;
+ if( pnCkpt ) *pnCkpt = -1;
+
+ assert( SQLITE_CHECKPOINT_PASSIVE==0 );
+ assert( SQLITE_CHECKPOINT_FULL==1 );
+ assert( SQLITE_CHECKPOINT_RESTART==2 );
+ assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
+ if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
+ /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
+ ** mode: */
+ return SQLITE_MISUSE;
+ }
+
+ sqlite3_mutex_enter(db->mutex);
+ if( zDb && zDb[0] ){
+ iDb = sqlite3FindDbName(db, zDb);
+ }
+ if( iDb<0 ){
+ rc = SQLITE_ERROR;
+ sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
+ }else{
+ db->busyHandler.nBusy = 0;
+ rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
+ sqlite3Error(db, rc);
+ }
+ rc = sqlite3ApiExit(db, rc);
+
+ /* If there are no active statements, clear the interrupt flag at this
+ ** point. */
+ if( db->nVdbeActive==0 ){
+ AtomicStore(&db->u1.isInterrupted, 0);
+ }
+
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+#endif
+}
+
+
+/*
+** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
+** to contains a zero-length string, all attached databases are
+** checkpointed.
+*/
+SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
+ /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
+ ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
+ return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
+}
+
+#ifndef SQLITE_OMIT_WAL
+/*
+** Run a checkpoint on database iDb. This is a no-op if database iDb is
+** not currently open in WAL mode.
+**
+** If a transaction is open on the database being checkpointed, this
+** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
+** an error occurs while running the checkpoint, an SQLite error code is
+** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
+**
+** The mutex on database handle db should be held by the caller. The mutex
+** associated with the specific b-tree being checkpointed is taken by
+** this function while the checkpoint is running.
+**
+** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
+** checkpointed. If an error is encountered it is returned immediately -
+** no attempt is made to checkpoint any remaining databases.
+**
+** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
+** or TRUNCATE.
+*/
+SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
+ int rc = SQLITE_OK; /* Return code */
+ int i; /* Used to iterate through attached dbs */
+ int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
+
+ assert( sqlite3_mutex_held(db->mutex) );
+ assert( !pnLog || *pnLog==-1 );
+ assert( !pnCkpt || *pnCkpt==-1 );
+
+ for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
+ if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
+ rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
+ pnLog = 0;
+ pnCkpt = 0;
+ if( rc==SQLITE_BUSY ){
+ bBusy = 1;
+ rc = SQLITE_OK;
+ }
+ }
+ }
+
+ return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
+}
+#endif /* SQLITE_OMIT_WAL */
+
+/*
+** This function returns true if main-memory should be used instead of
+** a temporary file for transient pager files and statement journals.
+** The value returned depends on the value of db->temp_store (runtime
+** parameter) and the compile time value of SQLITE_TEMP_STORE. The
+** following table describes the relationship between these two values
+** and this functions return value.
+**
+** SQLITE_TEMP_STORE db->temp_store Location of temporary database
+** ----------------- -------------- ------------------------------
+** 0 any file (return 0)
+** 1 1 file (return 0)
+** 1 2 memory (return 1)
+** 1 0 file (return 0)
+** 2 1 file (return 0)
+** 2 2 memory (return 1)
+** 2 0 memory (return 1)
+** 3 any memory (return 1)
+*/
+SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
+#if SQLITE_TEMP_STORE==1
+ return ( db->temp_store==2 );
+#endif
+#if SQLITE_TEMP_STORE==2
+ return ( db->temp_store!=1 );
+#endif
+#if SQLITE_TEMP_STORE==3
+ UNUSED_PARAMETER(db);
+ return 1;
+#endif
+#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
+ UNUSED_PARAMETER(db);
+ return 0;
+#endif
+}
+
+/*
+** Return UTF-8 encoded English language explanation of the most recent
+** error.
+*/
+SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
+ const char *z;
+ if( !db ){
+ return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
+ }
+ if( !sqlite3SafetyCheckSickOrOk(db) ){
+ return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
+ }
+ sqlite3_mutex_enter(db->mutex);
+ if( db->mallocFailed ){
+ z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
+ }else{
+ testcase( db->pErr==0 );
+ z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;
+ assert( !db->mallocFailed );
+ if( z==0 ){
+ z = sqlite3ErrStr(db->errCode);
+ }
+ }
+ sqlite3_mutex_leave(db->mutex);
+ return z;
+}
+
+#ifndef SQLITE_OMIT_UTF16
+/*
+** Return UTF-16 encoded English language explanation of the most recent
+** error.
+*/
+SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
+ static const u16 outOfMem[] = {
+ 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
+ };
+ static const u16 misuse[] = {
+ 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
+ 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
+ 'm', 'i', 's', 'u', 's', 'e', 0
+ };
+
+ const void *z;
+ if( !db ){
+ return (void *)outOfMem;
+ }
+ if( !sqlite3SafetyCheckSickOrOk(db) ){
+ return (void *)misuse;
+ }
+ sqlite3_mutex_enter(db->mutex);
+ if( db->mallocFailed ){
+ z = (void *)outOfMem;
+ }else{
+ z = sqlite3_value_text16(db->pErr);
+ if( z==0 ){
+ sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
+ z = sqlite3_value_text16(db->pErr);
+ }
+ /* A malloc() may have failed within the call to sqlite3_value_text16()
+ ** above. If this is the case, then the db->mallocFailed flag needs to
+ ** be cleared before returning. Do this directly, instead of via
+ ** sqlite3ApiExit(), to avoid setting the database handle error message.
+ */
+ sqlite3OomClear(db);
+ }
+ sqlite3_mutex_leave(db->mutex);
+ return z;
+}
+#endif /* SQLITE_OMIT_UTF16 */
+
+/*
+** Return the most recent error code generated by an SQLite routine. If NULL is
+** passed to this function, we assume a malloc() failed during sqlite3_open().
+*/
+SQLITE_API int sqlite3_errcode(sqlite3 *db){
+ if( db && !sqlite3SafetyCheckSickOrOk(db) ){
+ return SQLITE_MISUSE_BKPT;
+ }
+ if( !db || db->mallocFailed ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ return db->errCode & db->errMask;
+}
+SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
+ if( db && !sqlite3SafetyCheckSickOrOk(db) ){
+ return SQLITE_MISUSE_BKPT;
+ }
+ if( !db || db->mallocFailed ){
+ return SQLITE_NOMEM_BKPT;
+ }
+ return db->errCode;
+}
+SQLITE_API int sqlite3_system_errno(sqlite3 *db){
+ return db ? db->iSysErrno : 0;
+}
+
+/*
+** Return a string that describes the kind of error specified in the
+** argument. For now, this simply calls the internal sqlite3ErrStr()
+** function.
+*/
+SQLITE_API const char *sqlite3_errstr(int rc){
+ return sqlite3ErrStr(rc);
+}
+
+/*
+** Create a new collating function for database "db". The name is zName
+** and the encoding is enc.
+*/
+static int createCollation(
+ sqlite3* db,
+ const char *zName,
+ u8 enc,
+ void* pCtx,
+ int(*xCompare)(void*,int,const void*,int,const void*),
+ void(*xDel)(void*)
+){
+ CollSeq *pColl;
+ int enc2;
+
+ assert( sqlite3_mutex_held(db->mutex) );
+
+ /* If SQLITE_UTF16 is specified as the encoding type, transform this
+ ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
+ ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
+ */
+ enc2 = enc;
+ testcase( enc2==SQLITE_UTF16 );
+ testcase( enc2==SQLITE_UTF16_ALIGNED );
+ if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
+ enc2 = SQLITE_UTF16NATIVE;
+ }
+ if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
+ return SQLITE_MISUSE_BKPT;
+ }
+
+ /* Check if this call is removing or replacing an existing collation
+ ** sequence. If so, and there are active VMs, return busy. If there
+ ** are no active VMs, invalidate any pre-compiled statements.
+ */
+ pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
+ if( pColl && pColl->xCmp ){
+ if( db->nVdbeActive ){
+ sqlite3ErrorWithMsg(db, SQLITE_BUSY,
+ "unable to delete/modify collation sequence due to active statements");
+ return SQLITE_BUSY;
+ }
+ sqlite3ExpirePreparedStatements(db, 0);
+
+ /* If collation sequence pColl was created directly by a call to
+ ** sqlite3_create_collation, and not generated by synthCollSeq(),
+ ** then any copies made by synthCollSeq() need to be invalidated.
+ ** Also, collation destructor - CollSeq.xDel() - function may need
+ ** to be called.
+ */
+ if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
+ CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
+ int j;
+ for(j=0; j<3; j++){
+ CollSeq *p = &aColl[j];
+ if( p->enc==pColl->enc ){
+ if( p->xDel ){
+ p->xDel(p->pUser);
+ }
+ p->xCmp = 0;
+ }
+ }
+ }
+ }
+
+ pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
+ if( pColl==0 ) return SQLITE_NOMEM_BKPT;
+ pColl->xCmp = xCompare;
+ pColl->pUser = pCtx;
+ pColl->xDel = xDel;
+ pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
+ sqlite3Error(db, SQLITE_OK);
+ return SQLITE_OK;
+}
+
+
+/*
+** This array defines hard upper bounds on limit values. The
+** initializer must be kept in sync with the SQLITE_LIMIT_*
+** #defines in sqlite3.h.
+*/
+static const int aHardLimit[] = {
+ SQLITE_MAX_LENGTH,
+ SQLITE_MAX_SQL_LENGTH,
+ SQLITE_MAX_COLUMN,
+ SQLITE_MAX_EXPR_DEPTH,
+ SQLITE_MAX_COMPOUND_SELECT,
+ SQLITE_MAX_VDBE_OP,
+ SQLITE_MAX_FUNCTION_ARG,
+ SQLITE_MAX_ATTACHED,
+ SQLITE_MAX_LIKE_PATTERN_LENGTH,
+ SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
+ SQLITE_MAX_TRIGGER_DEPTH,
+ SQLITE_MAX_WORKER_THREADS,
+};
+
+/*
+** Make sure the hard limits are set to reasonable values
+*/
+#if SQLITE_MAX_LENGTH<100
+# error SQLITE_MAX_LENGTH must be at least 100
+#endif
+#if SQLITE_MAX_SQL_LENGTH<100
+# error SQLITE_MAX_SQL_LENGTH must be at least 100
+#endif
+#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
+# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
+#endif
+#if SQLITE_MAX_COMPOUND_SELECT<2
+# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
+#endif
+#if SQLITE_MAX_VDBE_OP<40
+# error SQLITE_MAX_VDBE_OP must be at least 40
+#endif
+#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
+# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
+#endif
+#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
+# error SQLITE_MAX_ATTACHED must be between 0 and 125
+#endif
+#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
+# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
+#endif
+#if SQLITE_MAX_COLUMN>32767
+# error SQLITE_MAX_COLUMN must not exceed 32767
+#endif
+#if SQLITE_MAX_TRIGGER_DEPTH<1
+# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
+#endif
+#if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
+# error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
+#endif
+
+
+/*
+** Change the value of a limit. Report the old value.
+** If an invalid limit index is supplied, report -1.
+** Make no changes but still report the old value if the
+** new limit is negative.
+**
+** A new lower limit does not shrink existing constructs.
+** It merely prevents new constructs that exceed the limit
+** from forming.
+*/
+SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
+ int oldLimit;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return -1;
+ }
+#endif
+
+ /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
+ ** there is a hard upper bound set at compile-time by a C preprocessor
+ ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
+ ** "_MAX_".)
+ */
+ assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
+ assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
+ assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
+ assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
+ assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
+ assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
+ assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
+ assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
+ assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
+ SQLITE_MAX_LIKE_PATTERN_LENGTH );
+ assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
+ assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
+ assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
+ assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
+
+
+ if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
+ return -1;
+ }
+ oldLimit = db->aLimit[limitId];
+ if( newLimit>=0 ){ /* IMP: R-52476-28732 */
+ if( newLimit>aHardLimit[limitId] ){
+ newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
+ }
+ db->aLimit[limitId] = newLimit;
+ }
+ return oldLimit; /* IMP: R-53341-35419 */
+}
+
+/*
+** This function is used to parse both URIs and non-URI filenames passed by the
+** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
+** URIs specified as part of ATTACH statements.
+**
+** The first argument to this function is the name of the VFS to use (or
+** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
+** query parameter. The second argument contains the URI (or non-URI filename)
+** itself. When this function is called the *pFlags variable should contain
+** the default flags to open the database handle with. The value stored in
+** *pFlags may be updated before returning if the URI filename contains
+** "cache=xxx" or "mode=xxx" query parameters.
+**
+** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
+** the VFS that should be used to open the database file. *pzFile is set to
+** point to a buffer containing the name of the file to open. The value
+** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter()
+** and is in the same format as names created using sqlite3_create_filename().
+** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on
+** the value returned in *pzFile to avoid a memory leak.
+**
+** If an error occurs, then an SQLite error code is returned and *pzErrMsg
+** may be set to point to a buffer containing an English language error
+** message. It is the responsibility of the caller to eventually release
+** this buffer by calling sqlite3_free().
+*/
+SQLITE_PRIVATE int sqlite3ParseUri(
+ const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
+ const char *zUri, /* Nul-terminated URI to parse */
+ unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
+ sqlite3_vfs **ppVfs, /* OUT: VFS to use */
+ char **pzFile, /* OUT: Filename component of URI */
+ char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
+){
+ int rc = SQLITE_OK;
+ unsigned int flags = *pFlags;
+ const char *zVfs = zDefaultVfs;
+ char *zFile;
+ char c;
+ int nUri = sqlite3Strlen30(zUri);
+
+ assert( *pzErrMsg==0 );
+
+ if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
+ || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
+ && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
+ ){
+ char *zOpt;
+ int eState; /* Parser state when parsing URI */
+ int iIn; /* Input character index */
+ int iOut = 0; /* Output character index */
+ u64 nByte = nUri+8; /* Bytes of space to allocate */
+
+ /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
+ ** method that there may be extra parameters following the file-name. */
+ flags |= SQLITE_OPEN_URI;
+
+ for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
+ zFile = sqlite3_malloc64(nByte);
+ if( !zFile ) return SQLITE_NOMEM_BKPT;
+
+ memset(zFile, 0, 4); /* 4-byte of 0x00 is the start of DB name marker */
+ zFile += 4;
+
+ iIn = 5;
+#ifdef SQLITE_ALLOW_URI_AUTHORITY
+ if( strncmp(zUri+5, "///", 3)==0 ){
+ iIn = 7;
+ /* The following condition causes URIs with five leading / characters
+ ** like file://///host/path to be converted into UNCs like //host/path.
+ ** The correct URI for that UNC has only two or four leading / characters
+ ** file://host/path or file:////host/path. But 5 leading slashes is a
+ ** common error, we are told, so we handle it as a special case. */
+ if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
+ }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
+ iIn = 16;
+ }
+#else
+ /* Discard the scheme and authority segments of the URI. */
+ if( zUri[5]=='/' && zUri[6]=='/' ){
+ iIn = 7;
+ while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
+ if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
+ *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
+ iIn-7, &zUri[7]);
+ rc = SQLITE_ERROR;
+ goto parse_uri_out;
+ }
+ }
+#endif
+
+ /* Copy the filename and any query parameters into the zFile buffer.
+ ** Decode %HH escape codes along the way.
+ **
+ ** Within this loop, variable eState may be set to 0, 1 or 2, depending
+ ** on the parsing context. As follows:
+ **
+ ** 0: Parsing file-name.
+ ** 1: Parsing name section of a name=value query parameter.
+ ** 2: Parsing value section of a name=value query parameter.
+ */
+ eState = 0;
+ while( (c = zUri[iIn])!=0 && c!='#' ){
+ iIn++;
+ if( c=='%'
+ && sqlite3Isxdigit(zUri[iIn])
+ && sqlite3Isxdigit(zUri[iIn+1])
+ ){
+ int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
+ octet += sqlite3HexToInt(zUri[iIn++]);
+
+ assert( octet>=0 && octet<256 );
+ if( octet==0 ){
+#ifndef SQLITE_ENABLE_URI_00_ERROR
+ /* This branch is taken when "%00" appears within the URI. In this
+ ** case we ignore all text in the remainder of the path, name or
+ ** value currently being parsed. So ignore the current character
+ ** and skip to the next "?", "=" or "&", as appropriate. */
+ while( (c = zUri[iIn])!=0 && c!='#'
+ && (eState!=0 || c!='?')
+ && (eState!=1 || (c!='=' && c!='&'))
+ && (eState!=2 || c!='&')
+ ){
+ iIn++;
+ }
+ continue;
+#else
+ /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
+ *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
+ rc = SQLITE_ERROR;
+ goto parse_uri_out;
+#endif
+ }
+ c = octet;
+ }else if( eState==1 && (c=='&' || c=='=') ){
+ if( zFile[iOut-1]==0 ){
+ /* An empty option name. Ignore this option altogether. */
+ while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
+ continue;
+ }
+ if( c=='&' ){
+ zFile[iOut++] = '\0';
+ }else{
+ eState = 2;
+ }
+ c = 0;
+ }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
+ c = 0;
+ eState = 1;
+ }
+ zFile[iOut++] = c;
+ }
+ if( eState==1 ) zFile[iOut++] = '\0';
+ memset(zFile+iOut, 0, 4); /* end-of-options + empty journal filenames */
+
+ /* Check if there were any options specified that should be interpreted
+ ** here. Options that are interpreted here include "vfs" and those that
+ ** correspond to flags that may be passed to the sqlite3_open_v2()
+ ** method. */
+ zOpt = &zFile[sqlite3Strlen30(zFile)+1];
+ while( zOpt[0] ){
+ int nOpt = sqlite3Strlen30(zOpt);
+ char *zVal = &zOpt[nOpt+1];
+ int nVal = sqlite3Strlen30(zVal);
+
+ if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
+ zVfs = zVal;
+ }else{
+ struct OpenMode {
+ const char *z;
+ int mode;
+ } *aMode = 0;
+ char *zModeType = 0;
+ int mask = 0;
+ int limit = 0;
+
+ if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
+ static struct OpenMode aCacheMode[] = {
+ { "shared", SQLITE_OPEN_SHAREDCACHE },
+ { "private", SQLITE_OPEN_PRIVATECACHE },
+ { 0, 0 }
+ };
+
+ mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
+ aMode = aCacheMode;
+ limit = mask;
+ zModeType = "cache";
+ }
+ if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
+ static struct OpenMode aOpenMode[] = {
+ { "ro", SQLITE_OPEN_READONLY },
+ { "rw", SQLITE_OPEN_READWRITE },
+ { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
+ { "memory", SQLITE_OPEN_MEMORY },
+ { 0, 0 }
+ };
+
+ mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
+ | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
+ aMode = aOpenMode;
+ limit = mask & flags;
+ zModeType = "access";
+ }
+
+ if( aMode ){
+ int i;
+ int mode = 0;
+ for(i=0; aMode[i].z; i++){
+ const char *z = aMode[i].z;
+ if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
+ mode = aMode[i].mode;
+ break;
+ }
+ }
+ if( mode==0 ){
+ *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
+ rc = SQLITE_ERROR;
+ goto parse_uri_out;
+ }
+ if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
+ *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
+ zModeType, zVal);
+ rc = SQLITE_PERM;
+ goto parse_uri_out;
+ }
+ flags = (flags & ~mask) | mode;
+ }
+ }
+
+ zOpt = &zVal[nVal+1];
+ }
+
+ }else{
+ zFile = sqlite3_malloc64(nUri+8);
+ if( !zFile ) return SQLITE_NOMEM_BKPT;
+ memset(zFile, 0, 4);
+ zFile += 4;
+ if( nUri ){
+ memcpy(zFile, zUri, nUri);
+ }
+ memset(zFile+nUri, 0, 4);
+ flags &= ~SQLITE_OPEN_URI;
+ }
+
+ *ppVfs = sqlite3_vfs_find(zVfs);
+ if( *ppVfs==0 ){
+ *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
+ rc = SQLITE_ERROR;
+ }
+ parse_uri_out:
+ if( rc!=SQLITE_OK ){
+ sqlite3_free_filename(zFile);
+ zFile = 0;
+ }
+ *pFlags = flags;
+ *pzFile = zFile;
+ return rc;
+}
+
+/*
+** This routine does the core work of extracting URI parameters from a
+** database filename for the sqlite3_uri_parameter() interface.
+*/
+static const char *uriParameter(const char *zFilename, const char *zParam){
+ zFilename += sqlite3Strlen30(zFilename) + 1;
+ while( zFilename[0] ){
+ int x = strcmp(zFilename, zParam);
+ zFilename += sqlite3Strlen30(zFilename) + 1;
+ if( x==0 ) return zFilename;
+ zFilename += sqlite3Strlen30(zFilename) + 1;
+ }
+ return 0;
+}
+
+
+
+/*
+** This routine does the work of opening a database on behalf of
+** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
+** is UTF-8 encoded.
+*/
+static int openDatabase(
+ const char *zFilename, /* Database filename UTF-8 encoded */
+ sqlite3 **ppDb, /* OUT: Returned database handle */
+ unsigned int flags, /* Operational flags */
+ const char *zVfs /* Name of the VFS to use */
+){
+ sqlite3 *db; /* Store allocated handle here */
+ int rc; /* Return code */
+ int isThreadsafe; /* True for threadsafe connections */
+ char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
+ char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
+ int i; /* Loop counter */
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
+#endif
+ *ppDb = 0;
+#ifndef SQLITE_OMIT_AUTOINIT
+ rc = sqlite3_initialize();
+ if( rc ) return rc;
+#endif
+
+ if( sqlite3GlobalConfig.bCoreMutex==0 ){
+ isThreadsafe = 0;
+ }else if( flags & SQLITE_OPEN_NOMUTEX ){
+ isThreadsafe = 0;
+ }else if( flags & SQLITE_OPEN_FULLMUTEX ){
+ isThreadsafe = 1;
+ }else{
+ isThreadsafe = sqlite3GlobalConfig.bFullMutex;
+ }
+
+ if( flags & SQLITE_OPEN_PRIVATECACHE ){
+ flags &= ~SQLITE_OPEN_SHAREDCACHE;
+ }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
+ flags |= SQLITE_OPEN_SHAREDCACHE;
+ }
+
+ /* Remove harmful bits from the flags parameter
+ **
+ ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
+ ** dealt with in the previous code block. Besides these, the only
+ ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
+ ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
+ ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
+ ** off all other flags.
+ */
+ flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
+ SQLITE_OPEN_EXCLUSIVE |
+ SQLITE_OPEN_MAIN_DB |
+ SQLITE_OPEN_TEMP_DB |
+ SQLITE_OPEN_TRANSIENT_DB |
+ SQLITE_OPEN_MAIN_JOURNAL |
+ SQLITE_OPEN_TEMP_JOURNAL |
+ SQLITE_OPEN_SUBJOURNAL |
+ SQLITE_OPEN_SUPER_JOURNAL |
+ SQLITE_OPEN_NOMUTEX |
+ SQLITE_OPEN_FULLMUTEX |
+ SQLITE_OPEN_WAL
+ );
+
+ /* Allocate the sqlite data structure */
+ db = sqlite3MallocZero( sizeof(sqlite3) );
+ if( db==0 ) goto opendb_out;
+ if( isThreadsafe
+#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
+ || sqlite3GlobalConfig.bCoreMutex
+#endif
+ ){
+ db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
+ if( db->mutex==0 ){
+ sqlite3_free(db);
+ db = 0;
+ goto opendb_out;
+ }
+ if( isThreadsafe==0 ){
+ sqlite3MutexWarnOnContention(db->mutex);
+ }
+ }
+ sqlite3_mutex_enter(db->mutex);
+ db->errMask = 0xff;
+ db->nDb = 2;
+ db->magic = SQLITE_MAGIC_BUSY;
+ db->aDb = db->aDbStatic;
+ db->lookaside.bDisable = 1;
+ db->lookaside.sz = 0;
+
+ assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
+ memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
+ db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
+ db->autoCommit = 1;
+ db->nextAutovac = -1;
+ db->szMmap = sqlite3GlobalConfig.szMmap;
+ db->nextPagesize = 0;
+ db->nMaxSorterMmap = 0x7FFFFFFF;
+ db->flags |= SQLITE_ShortColNames
+ | SQLITE_EnableTrigger
+ | SQLITE_EnableView
+ | SQLITE_CacheSpill
+#if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
+ | SQLITE_TrustedSchema
+#endif
+/* The SQLITE_DQS compile-time option determines the default settings
+** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
+**
+** SQLITE_DQS SQLITE_DBCONFIG_DQS_DDL SQLITE_DBCONFIG_DQS_DML
+** ---------- ----------------------- -----------------------
+** undefined on on
+** 3 on on
+** 2 on off
+** 1 off on
+** 0 off off
+**
+** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
+** and so that is the default. But developers are encouranged to use
+** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
+*/
+#if !defined(SQLITE_DQS)
+# define SQLITE_DQS 3
+#endif
+#if (SQLITE_DQS&1)==1
+ | SQLITE_DqsDML
+#endif
+#if (SQLITE_DQS&2)==2
+ | SQLITE_DqsDDL
+#endif
+
+#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
+ | SQLITE_AutoIndex
+#endif
+#if SQLITE_DEFAULT_CKPTFULLFSYNC
+ | SQLITE_CkptFullFSync
+#endif
+#if SQLITE_DEFAULT_FILE_FORMAT<4
+ | SQLITE_LegacyFileFmt
+#endif
+#ifdef SQLITE_ENABLE_LOAD_EXTENSION
+ | SQLITE_LoadExtension
+#endif
+#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
+ | SQLITE_RecTriggers
+#endif
+#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
+ | SQLITE_ForeignKeys
+#endif
+#if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
+ | SQLITE_ReverseOrder
+#endif
+#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
+ | SQLITE_CellSizeCk
+#endif
+#if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
+ | SQLITE_Fts3Tokenizer
+#endif
+#if defined(SQLITE_ENABLE_QPSG)
+ | SQLITE_EnableQPSG
+#endif
+#if defined(SQLITE_DEFAULT_DEFENSIVE)
+ | SQLITE_Defensive
+#endif
+#if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
+ | SQLITE_LegacyAlter
+#endif
+ ;
+ sqlite3HashInit(&db->aCollSeq);
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ sqlite3HashInit(&db->aModule);
+#endif
+
+ /* Add the default collation sequence BINARY. BINARY works for both UTF-8
+ ** and UTF-16, so add a version for each to avoid any unnecessary
+ ** conversions. The only error that can occur here is a malloc() failure.
+ **
+ ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
+ ** functions:
+ */
+ createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
+ createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
+ createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
+ createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
+ createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0);
+ if( db->mallocFailed ){
+ goto opendb_out;
+ }
+
+ /* Parse the filename/URI argument
+ **
+ ** Only allow sensible combinations of bits in the flags argument.
+ ** Throw an error if any non-sense combination is used. If we
+ ** do not block illegal combinations here, it could trigger
+ ** assert() statements in deeper layers. Sensible combinations
+ ** are:
+ **
+ ** 1: SQLITE_OPEN_READONLY
+ ** 2: SQLITE_OPEN_READWRITE
+ ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
+ */
+ db->openFlags = flags;
+ assert( SQLITE_OPEN_READONLY == 0x01 );
+ assert( SQLITE_OPEN_READWRITE == 0x02 );
+ assert( SQLITE_OPEN_CREATE == 0x04 );
+ testcase( (1<<(flags&7))==0x02 ); /* READONLY */
+ testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
+ testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
+ if( ((1<<(flags&7)) & 0x46)==0 ){
+ rc = SQLITE_MISUSE_BKPT; /* IMP: R-18321-05872 */
+ }else{
+ rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
+ }
+ if( rc!=SQLITE_OK ){
+ if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
+ sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
+ sqlite3_free(zErrMsg);
+ goto opendb_out;
+ }
+
+ /* Open the backend database driver */
+ rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
+ flags | SQLITE_OPEN_MAIN_DB);
+ if( rc!=SQLITE_OK ){
+ if( rc==SQLITE_IOERR_NOMEM ){
+ rc = SQLITE_NOMEM_BKPT;
+ }
+ sqlite3Error(db, rc);
+ goto opendb_out;
+ }
+ sqlite3BtreeEnter(db->aDb[0].pBt);
+ db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
+ if( !db->mallocFailed ){
+ sqlite3SetTextEncoding(db, SCHEMA_ENC(db));
+ }
+ sqlite3BtreeLeave(db->aDb[0].pBt);
+ db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
+
+ /* The default safety_level for the main database is FULL; for the temp
+ ** database it is OFF. This matches the pager layer defaults.
+ */
+ db->aDb[0].zDbSName = "main";
+ db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
+ db->aDb[1].zDbSName = "temp";
+ db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
+
+ db->magic = SQLITE_MAGIC_OPEN;
+ if( db->mallocFailed ){
+ goto opendb_out;
+ }
+
+ /* Register all built-in functions, but do not attempt to read the
+ ** database schema yet. This is delayed until the first time the database
+ ** is accessed.
+ */
+ sqlite3Error(db, SQLITE_OK);
+ sqlite3RegisterPerConnectionBuiltinFunctions(db);
+ rc = sqlite3_errcode(db);
+
+
+ /* Load compiled-in extensions */
+ for(i=0; rc==SQLITE_OK && i<ArraySize(sqlite3BuiltinExtensions); i++){
+ rc = sqlite3BuiltinExtensions[i](db);
+ }
+
+ /* Load automatic extensions - extensions that have been registered
+ ** using the sqlite3_automatic_extension() API.
+ */
+ if( rc==SQLITE_OK ){
+ sqlite3AutoLoadExtensions(db);
+ rc = sqlite3_errcode(db);
+ if( rc!=SQLITE_OK ){
+ goto opendb_out;
+ }
+ }
+
+#ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
+ /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
+ ** option gives access to internal functions by default.
+ ** Testing use only!!! */
+ db->mDbFlags |= DBFLAG_InternalFunc;
+#endif
+
+ /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
+ ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
+ ** mode. Doing nothing at all also makes NORMAL the default.
+ */
+#ifdef SQLITE_DEFAULT_LOCKING_MODE
+ db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
+ sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
+ SQLITE_DEFAULT_LOCKING_MODE);
+#endif
+
+ if( rc ) sqlite3Error(db, rc);
+
+ /* Enable the lookaside-malloc subsystem */
+ setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
+ sqlite3GlobalConfig.nLookaside);
+
+ sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
+
+opendb_out:
+ if( db ){
+ assert( db->mutex!=0 || isThreadsafe==0
+ || sqlite3GlobalConfig.bFullMutex==0 );
+ sqlite3_mutex_leave(db->mutex);
+ }
+ rc = sqlite3_errcode(db);
+ assert( db!=0 || rc==SQLITE_NOMEM );
+ if( rc==SQLITE_NOMEM ){
+ sqlite3_close(db);
+ db = 0;
+ }else if( rc!=SQLITE_OK ){
+ db->magic = SQLITE_MAGIC_SICK;
+ }
+ *ppDb = db;
+#ifdef SQLITE_ENABLE_SQLLOG
+ if( sqlite3GlobalConfig.xSqllog ){
+ /* Opening a db handle. Fourth parameter is passed 0. */
+ void *pArg = sqlite3GlobalConfig.pSqllogArg;
+ sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
+ }
+#endif
+ sqlite3_free_filename(zOpen);
+ return rc & 0xff;
+}
+
+
+/*
+** Open a new database handle.
+*/
+SQLITE_API int sqlite3_open(
+ const char *zFilename,
+ sqlite3 **ppDb
+){
+ return openDatabase(zFilename, ppDb,
+ SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
+}
+SQLITE_API int sqlite3_open_v2(
+ const char *filename, /* Database filename (UTF-8) */
+ sqlite3 **ppDb, /* OUT: SQLite db handle */
+ int flags, /* Flags */
+ const char *zVfs /* Name of VFS module to use */
+){
+ return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
+}
+
+#ifndef SQLITE_OMIT_UTF16
+/*
+** Open a new database handle.
+*/
+SQLITE_API int sqlite3_open16(
+ const void *zFilename,
+ sqlite3 **ppDb
+){
+ char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
+ sqlite3_value *pVal;
+ int rc;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
+#endif
+ *ppDb = 0;
+#ifndef SQLITE_OMIT_AUTOINIT
+ rc = sqlite3_initialize();
+ if( rc ) return rc;
+#endif
+ if( zFilename==0 ) zFilename = "\000\000";
+ pVal = sqlite3ValueNew(0);
+ sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
+ zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
+ if( zFilename8 ){
+ rc = openDatabase(zFilename8, ppDb,
+ SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
+ assert( *ppDb || rc==SQLITE_NOMEM );
+ if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
+ SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
+ }
+ }else{
+ rc = SQLITE_NOMEM_BKPT;
+ }
+ sqlite3ValueFree(pVal);
+
+ return rc & 0xff;
+}
+#endif /* SQLITE_OMIT_UTF16 */
+
+/*
+** Register a new collation sequence with the database handle db.
+*/
+SQLITE_API int sqlite3_create_collation(
+ sqlite3* db,
+ const char *zName,
+ int enc,
+ void* pCtx,
+ int(*xCompare)(void*,int,const void*,int,const void*)
+){
+ return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
+}
+
+/*
+** Register a new collation sequence with the database handle db.
+*/
+SQLITE_API int sqlite3_create_collation_v2(
+ sqlite3* db,
+ const char *zName,
+ int enc,
+ void* pCtx,
+ int(*xCompare)(void*,int,const void*,int,const void*),
+ void(*xDel)(void*)
+){
+ int rc;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ assert( !db->mallocFailed );
+ rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
+ rc = sqlite3ApiExit(db, rc);
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+#ifndef SQLITE_OMIT_UTF16
+/*
+** Register a new collation sequence with the database handle db.
+*/
+SQLITE_API int sqlite3_create_collation16(
+ sqlite3* db,
+ const void *zName,
+ int enc,
+ void* pCtx,
+ int(*xCompare)(void*,int,const void*,int,const void*)
+){
+ int rc = SQLITE_OK;
+ char *zName8;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ assert( !db->mallocFailed );
+ zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
+ if( zName8 ){
+ rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
+ sqlite3DbFree(db, zName8);
+ }
+ rc = sqlite3ApiExit(db, rc);
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+#endif /* SQLITE_OMIT_UTF16 */
+
+/*
+** Register a collation sequence factory callback with the database handle
+** db. Replace any previously installed collation sequence factory.
+*/
+SQLITE_API int sqlite3_collation_needed(
+ sqlite3 *db,
+ void *pCollNeededArg,
+ void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
+){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ db->xCollNeeded = xCollNeeded;
+ db->xCollNeeded16 = 0;
+ db->pCollNeededArg = pCollNeededArg;
+ sqlite3_mutex_leave(db->mutex);
+ return SQLITE_OK;
+}
+
+#ifndef SQLITE_OMIT_UTF16
+/*
+** Register a collation sequence factory callback with the database handle
+** db. Replace any previously installed collation sequence factory.
+*/
+SQLITE_API int sqlite3_collation_needed16(
+ sqlite3 *db,
+ void *pCollNeededArg,
+ void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
+){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ db->xCollNeeded = 0;
+ db->xCollNeeded16 = xCollNeeded16;
+ db->pCollNeededArg = pCollNeededArg;
+ sqlite3_mutex_leave(db->mutex);
+ return SQLITE_OK;
+}
+#endif /* SQLITE_OMIT_UTF16 */
+
+#ifndef SQLITE_OMIT_DEPRECATED
+/*
+** This function is now an anachronism. It used to be used to recover from a
+** malloc() failure, but SQLite now does this automatically.
+*/
+SQLITE_API int sqlite3_global_recover(void){
+ return SQLITE_OK;
+}
+#endif
+
+/*
+** Test to see whether or not the database connection is in autocommit
+** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
+** by default. Autocommit is disabled by a BEGIN statement and reenabled
+** by the next COMMIT or ROLLBACK.
+*/
+SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ return db->autoCommit;
+}
+
+/*
+** The following routines are substitutes for constants SQLITE_CORRUPT,
+** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
+** constants. They serve two purposes:
+**
+** 1. Serve as a convenient place to set a breakpoint in a debugger
+** to detect when version error conditions occurs.
+**
+** 2. Invoke sqlite3_log() to provide the source code location where
+** a low-level error is first detected.
+*/
+SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType){
+ sqlite3_log(iErr, "%s at line %d of [%.10s]",
+ zType, lineno, 20+sqlite3_sourceid());
+ return iErr;
+}
+SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
+ testcase( sqlite3GlobalConfig.xLog!=0 );
+ return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
+}
+SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
+ testcase( sqlite3GlobalConfig.xLog!=0 );
+ return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
+}
+SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
+ testcase( sqlite3GlobalConfig.xLog!=0 );
+ return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
+}
+#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
+SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
+ char zMsg[100];
+ sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
+ testcase( sqlite3GlobalConfig.xLog!=0 );
+ return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
+}
+#endif
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE int sqlite3NomemError(int lineno){
+ testcase( sqlite3GlobalConfig.xLog!=0 );
+ return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
+}
+SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
+ testcase( sqlite3GlobalConfig.xLog!=0 );
+ return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
+}
+#endif
+
+#ifndef SQLITE_OMIT_DEPRECATED
+/*
+** This is a convenience routine that makes sure that all thread-specific
+** data for this thread has been deallocated.
+**
+** SQLite no longer uses thread-specific data so this routine is now a
+** no-op. It is retained for historical compatibility.
+*/
+SQLITE_API void sqlite3_thread_cleanup(void){
+}
+#endif
+
+/*
+** Return meta information about a specific column of a database table.
+** See comment in sqlite3.h (sqlite.h.in) for details.
+*/
+SQLITE_API int sqlite3_table_column_metadata(
+ sqlite3 *db, /* Connection handle */
+ const char *zDbName, /* Database name or NULL */
+ const char *zTableName, /* Table name */
+ const char *zColumnName, /* Column name */
+ char const **pzDataType, /* OUTPUT: Declared data type */
+ char const **pzCollSeq, /* OUTPUT: Collation sequence name */
+ int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
+ int *pPrimaryKey, /* OUTPUT: True if column part of PK */
+ int *pAutoinc /* OUTPUT: True if column is auto-increment */
+){
+ int rc;
+ char *zErrMsg = 0;
+ Table *pTab = 0;
+ Column *pCol = 0;
+ int iCol = 0;
+ char const *zDataType = 0;
+ char const *zCollSeq = 0;
+ int notnull = 0;
+ int primarykey = 0;
+ int autoinc = 0;
+
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
+ return SQLITE_MISUSE_BKPT;
+ }
+#endif
+
+ /* Ensure the database schema has been loaded */
+ sqlite3_mutex_enter(db->mutex);
+ sqlite3BtreeEnterAll(db);
+ rc = sqlite3Init(db, &zErrMsg);
+ if( SQLITE_OK!=rc ){
+ goto error_out;
+ }
+
+ /* Locate the table in question */
+ pTab = sqlite3FindTable(db, zTableName, zDbName);
+ if( !pTab || pTab->pSelect ){
+ pTab = 0;
+ goto error_out;
+ }
+
+ /* Find the column for which info is requested */
+ if( zColumnName==0 ){
+ /* Query for existance of table only */
+ }else{
+ for(iCol=0; iCol<pTab->nCol; iCol++){
+ pCol = &pTab->aCol[iCol];
+ if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
+ break;
+ }
+ }
+ if( iCol==pTab->nCol ){
+ if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
+ iCol = pTab->iPKey;
+ pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
+ }else{
+ pTab = 0;
+ goto error_out;
+ }
+ }
+ }
+
+ /* The following block stores the meta information that will be returned
+ ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
+ ** and autoinc. At this point there are two possibilities:
+ **
+ ** 1. The specified column name was rowid", "oid" or "_rowid_"
+ ** and there is no explicitly declared IPK column.
+ **
+ ** 2. The table is not a view and the column name identified an
+ ** explicitly declared column. Copy meta information from *pCol.
+ */
+ if( pCol ){
+ zDataType = sqlite3ColumnType(pCol,0);
+ zCollSeq = pCol->zColl;
+ notnull = pCol->notNull!=0;
+ primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
+ autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
+ }else{
+ zDataType = "INTEGER";
+ primarykey = 1;
+ }
+ if( !zCollSeq ){
+ zCollSeq = sqlite3StrBINARY;
+ }
+
+error_out:
+ sqlite3BtreeLeaveAll(db);
+
+ /* Whether the function call succeeded or failed, set the output parameters
+ ** to whatever their local counterparts contain. If an error did occur,
+ ** this has the effect of zeroing all output parameters.
+ */
+ if( pzDataType ) *pzDataType = zDataType;
+ if( pzCollSeq ) *pzCollSeq = zCollSeq;
+ if( pNotNull ) *pNotNull = notnull;
+ if( pPrimaryKey ) *pPrimaryKey = primarykey;
+ if( pAutoinc ) *pAutoinc = autoinc;
+
+ if( SQLITE_OK==rc && !pTab ){
+ sqlite3DbFree(db, zErrMsg);
+ zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
+ zColumnName);
+ rc = SQLITE_ERROR;
+ }
+ sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
+ sqlite3DbFree(db, zErrMsg);
+ rc = sqlite3ApiExit(db, rc);
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+/*
+** Sleep for a little while. Return the amount of time slept.
+*/
+SQLITE_API int sqlite3_sleep(int ms){
+ sqlite3_vfs *pVfs;
+ int rc;
+ pVfs = sqlite3_vfs_find(0);
+ if( pVfs==0 ) return 0;
+
+ /* This function works in milliseconds, but the underlying OsSleep()
+ ** API uses microseconds. Hence the 1000's.
+ */
+ rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
+ return rc;
+}
+
+/*
+** Enable or disable the extended result codes.
+*/
+SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ db->errMask = onoff ? 0xffffffff : 0xff;
+ sqlite3_mutex_leave(db->mutex);
+ return SQLITE_OK;
+}
+
+/*
+** Invoke the xFileControl method on a particular database.
+*/
+SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
+ int rc = SQLITE_ERROR;
+ Btree *pBtree;
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ pBtree = sqlite3DbNameToBtree(db, zDbName);
+ if( pBtree ){
+ Pager *pPager;
+ sqlite3_file *fd;
+ sqlite3BtreeEnter(pBtree);
+ pPager = sqlite3BtreePager(pBtree);
+ assert( pPager!=0 );
+ fd = sqlite3PagerFile(pPager);
+ assert( fd!=0 );
+ if( op==SQLITE_FCNTL_FILE_POINTER ){
+ *(sqlite3_file**)pArg = fd;
+ rc = SQLITE_OK;
+ }else if( op==SQLITE_FCNTL_VFS_POINTER ){
+ *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
+ rc = SQLITE_OK;
+ }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
+ *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
+ rc = SQLITE_OK;
+ }else if( op==SQLITE_FCNTL_DATA_VERSION ){
+ *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
+ rc = SQLITE_OK;
+ }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){
+ int iNew = *(int*)pArg;
+ *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree);
+ if( iNew>=0 && iNew<=255 ){
+ sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0);
+ }
+ rc = SQLITE_OK;
+ }else{
+ int nSave = db->busyHandler.nBusy;
+ rc = sqlite3OsFileControl(fd, op, pArg);
+ db->busyHandler.nBusy = nSave;
+ }
+ sqlite3BtreeLeave(pBtree);
+ }
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+/*
+** Interface to the testing logic.
+*/
+SQLITE_API int sqlite3_test_control(int op, ...){
+ int rc = 0;
+#ifdef SQLITE_UNTESTABLE
+ UNUSED_PARAMETER(op);
+#else
+ va_list ap;
+ va_start(ap, op);
+ switch( op ){
+
+ /*
+ ** Save the current state of the PRNG.
+ */
+ case SQLITE_TESTCTRL_PRNG_SAVE: {
+ sqlite3PrngSaveState();
+ break;
+ }
+
+ /*
+ ** Restore the state of the PRNG to the last state saved using
+ ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
+ ** this verb acts like PRNG_RESET.
+ */
+ case SQLITE_TESTCTRL_PRNG_RESTORE: {
+ sqlite3PrngRestoreState();
+ break;
+ }
+
+ /* sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);
+ **
+ ** Control the seed for the pseudo-random number generator (PRNG) that
+ ** is built into SQLite. Cases:
+ **
+ ** x!=0 && db!=0 Seed the PRNG to the current value of the
+ ** schema cookie in the main database for db, or
+ ** x if the schema cookie is zero. This case
+ ** is convenient to use with database fuzzers
+ ** as it allows the fuzzer some control over the
+ ** the PRNG seed.
+ **
+ ** x!=0 && db==0 Seed the PRNG to the value of x.
+ **
+ ** x==0 && db==0 Revert to default behavior of using the
+ ** xRandomness method on the primary VFS.
+ **
+ ** This test-control also resets the PRNG so that the new seed will
+ ** be used for the next call to sqlite3_randomness().
+ */
+#ifndef SQLITE_OMIT_WSD
+ case SQLITE_TESTCTRL_PRNG_SEED: {
+ int x = va_arg(ap, int);
+ int y;
+ sqlite3 *db = va_arg(ap, sqlite3*);
+ assert( db==0 || db->aDb[0].pSchema!=0 );
+ if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; }
+ sqlite3Config.iPrngSeed = x;
+ sqlite3_randomness(0,0);
+ break;
+ }
+#endif
+
+ /*
+ ** sqlite3_test_control(BITVEC_TEST, size, program)
+ **
+ ** Run a test against a Bitvec object of size. The program argument
+ ** is an array of integers that defines the test. Return -1 on a
+ ** memory allocation error, 0 on success, or non-zero for an error.
+ ** See the sqlite3BitvecBuiltinTest() for additional information.
+ */
+ case SQLITE_TESTCTRL_BITVEC_TEST: {
+ int sz = va_arg(ap, int);
+ int *aProg = va_arg(ap, int*);
+ rc = sqlite3BitvecBuiltinTest(sz, aProg);
+ break;
+ }
+
+ /*
+ ** sqlite3_test_control(FAULT_INSTALL, xCallback)
+ **
+ ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
+ ** if xCallback is not NULL.
+ **
+ ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
+ ** is called immediately after installing the new callback and the return
+ ** value from sqlite3FaultSim(0) becomes the return from
+ ** sqlite3_test_control().
+ */
+ case SQLITE_TESTCTRL_FAULT_INSTALL: {
+ /* MSVC is picky about pulling func ptrs from va lists.
+ ** http://support.microsoft.com/kb/47961
+ ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
+ */
+ typedef int(*TESTCALLBACKFUNC_t)(int);
+ sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
+ rc = sqlite3FaultSim(0);
+ break;
+ }
+
+ /*
+ ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
+ **
+ ** Register hooks to call to indicate which malloc() failures
+ ** are benign.
+ */
+ case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
+ typedef void (*void_function)(void);
+ void_function xBenignBegin;
+ void_function xBenignEnd;
+ xBenignBegin = va_arg(ap, void_function);
+ xBenignEnd = va_arg(ap, void_function);
+ sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
+ break;
+ }
+
+ /*
+ ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
+ **
+ ** Set the PENDING byte to the value in the argument, if X>0.
+ ** Make no changes if X==0. Return the value of the pending byte
+ ** as it existing before this routine was called.
+ **
+ ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
+ ** an incompatible database file format. Changing the PENDING byte
+ ** while any database connection is open results in undefined and
+ ** deleterious behavior.
+ */
+ case SQLITE_TESTCTRL_PENDING_BYTE: {
+ rc = PENDING_BYTE;
+#ifndef SQLITE_OMIT_WSD
+ {
+ unsigned int newVal = va_arg(ap, unsigned int);
+ if( newVal ) sqlite3PendingByte = newVal;
+ }
+#endif
+ break;
+ }
+
+ /*
+ ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
+ **
+ ** This action provides a run-time test to see whether or not
+ ** assert() was enabled at compile-time. If X is true and assert()
+ ** is enabled, then the return value is true. If X is true and
+ ** assert() is disabled, then the return value is zero. If X is
+ ** false and assert() is enabled, then the assertion fires and the
+ ** process aborts. If X is false and assert() is disabled, then the
+ ** return value is zero.
+ */
+ case SQLITE_TESTCTRL_ASSERT: {
+ volatile int x = 0;
+ assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
+ rc = x;
+ break;
+ }
+
+
+ /*
+ ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
+ **
+ ** This action provides a run-time test to see how the ALWAYS and
+ ** NEVER macros were defined at compile-time.
+ **
+ ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
+ **
+ ** The recommended test is X==2. If the return value is 2, that means
+ ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
+ ** default setting. If the return value is 1, then ALWAYS() is either
+ ** hard-coded to true or else it asserts if its argument is false.
+ ** The first behavior (hard-coded to true) is the case if
+ ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
+ ** behavior (assert if the argument to ALWAYS() is false) is the case if
+ ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
+ **
+ ** The run-time test procedure might look something like this:
+ **
+ ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
+ ** // ALWAYS() and NEVER() are no-op pass-through macros
+ ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
+ ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
+ ** }else{
+ ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
+ ** }
+ */
+ case SQLITE_TESTCTRL_ALWAYS: {
+ int x = va_arg(ap,int);
+ rc = x ? ALWAYS(x) : 0;
+ break;
+ }
+
+ /*
+ ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
+ **
+ ** The integer returned reveals the byte-order of the computer on which
+ ** SQLite is running:
+ **
+ ** 1 big-endian, determined at run-time
+ ** 10 little-endian, determined at run-time
+ ** 432101 big-endian, determined at compile-time
+ ** 123410 little-endian, determined at compile-time
+ */
+ case SQLITE_TESTCTRL_BYTEORDER: {
+ rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
+ break;
+ }
+
+ /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
+ **
+ ** Enable or disable various optimizations for testing purposes. The
+ ** argument N is a bitmask of optimizations to be disabled. For normal
+ ** operation N should be 0. The idea is that a test program (like the
+ ** SQL Logic Test or SLT test module) can run the same SQL multiple times
+ ** with various optimizations disabled to verify that the same answer
+ ** is obtained in every case.
+ */
+ case SQLITE_TESTCTRL_OPTIMIZATIONS: {
+ sqlite3 *db = va_arg(ap, sqlite3*);
+ db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
+ break;
+ }
+
+ /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
+ **
+ ** If parameter onoff is non-zero, subsequent calls to localtime()
+ ** and its variants fail. If onoff is zero, undo this setting.
+ */
+ case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
+ sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
+ break;
+ }
+
+ /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
+ **
+ ** Toggle the ability to use internal functions on or off for
+ ** the database connection given in the argument.
+ */
+ case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
+ sqlite3 *db = va_arg(ap, sqlite3*);
+ db->mDbFlags ^= DBFLAG_InternalFunc;
+ break;
+ }
+
+ /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
+ **
+ ** Set or clear a flag that indicates that the database file is always well-
+ ** formed and never corrupt. This flag is clear by default, indicating that
+ ** database files might have arbitrary corruption. Setting the flag during
+ ** testing causes certain assert() statements in the code to be activated
+ ** that demonstrat invariants on well-formed database files.
+ */
+ case SQLITE_TESTCTRL_NEVER_CORRUPT: {
+ sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
+ break;
+ }
+
+ /* sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
+ **
+ ** Set or clear a flag that causes SQLite to verify that type, name,
+ ** and tbl_name fields of the sqlite_schema table. This is normally
+ ** on, but it is sometimes useful to turn it off for testing.
+ **
+ ** 2020-07-22: Disabling EXTRA_SCHEMA_CHECKS also disables the
+ ** verification of rootpage numbers when parsing the schema. This
+ ** is useful to make it easier to reach strange internal error states
+ ** during testing. The EXTRA_SCHEMA_CHECKS setting is always enabled
+ ** in production.
+ */
+ case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: {
+ sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int);
+ break;
+ }
+
+ /* Set the threshold at which OP_Once counters reset back to zero.
+ ** By default this is 0x7ffffffe (over 2 billion), but that value is
+ ** too big to test in a reasonable amount of time, so this control is
+ ** provided to set a small and easily reachable reset value.
+ */
+ case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
+ sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
+ break;
+ }
+
+ /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
+ **
+ ** Set the VDBE coverage callback function to xCallback with context
+ ** pointer ptr.
+ */
+ case SQLITE_TESTCTRL_VDBE_COVERAGE: {
+#ifdef SQLITE_VDBE_COVERAGE
+ typedef void (*branch_callback)(void*,unsigned int,
+ unsigned char,unsigned char);
+ sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
+ sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
+#endif
+ break;
+ }
+
+ /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
+ case SQLITE_TESTCTRL_SORTER_MMAP: {
+ sqlite3 *db = va_arg(ap, sqlite3*);
+ db->nMaxSorterMmap = va_arg(ap, int);
+ break;
+ }
+
+ /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
+ **
+ ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
+ ** not.
+ */
+ case SQLITE_TESTCTRL_ISINIT: {
+ if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
+ break;
+ }
+
+ /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
+ **
+ ** This test control is used to create imposter tables. "db" is a pointer
+ ** to the database connection. dbName is the database name (ex: "main" or
+ ** "temp") which will receive the imposter. "onOff" turns imposter mode on
+ ** or off. "tnum" is the root page of the b-tree to which the imposter
+ ** table should connect.
+ **
+ ** Enable imposter mode only when the schema has already been parsed. Then
+ ** run a single CREATE TABLE statement to construct the imposter table in
+ ** the parsed schema. Then turn imposter mode back off again.
+ **
+ ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
+ ** the schema to be reparsed the next time it is needed. This has the
+ ** effect of erasing all imposter tables.
+ */
+ case SQLITE_TESTCTRL_IMPOSTER: {
+ sqlite3 *db = va_arg(ap, sqlite3*);
+ sqlite3_mutex_enter(db->mutex);
+ db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
+ db->init.busy = db->init.imposterTable = va_arg(ap,int);
+ db->init.newTnum = va_arg(ap,int);
+ if( db->init.busy==0 && db->init.newTnum>0 ){
+ sqlite3ResetAllSchemasOfConnection(db);
+ }
+ sqlite3_mutex_leave(db->mutex);
+ break;
+ }
+
+#if defined(YYCOVERAGE)
+ /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
+ **
+ ** This test control (only available when SQLite is compiled with
+ ** -DYYCOVERAGE) writes a report onto "out" that shows all
+ ** state/lookahead combinations in the parser state machine
+ ** which are never exercised. If any state is missed, make the
+ ** return code SQLITE_ERROR.
+ */
+ case SQLITE_TESTCTRL_PARSER_COVERAGE: {
+ FILE *out = va_arg(ap, FILE*);
+ if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
+ break;
+ }
+#endif /* defined(YYCOVERAGE) */
+
+ /* sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
+ **
+ ** This test-control causes the most recent sqlite3_result_int64() value
+ ** to be interpreted as a MEM_IntReal instead of as an MEM_Int. Normally,
+ ** MEM_IntReal values only arise during an INSERT operation of integer
+ ** values into a REAL column, so they can be challenging to test. This
+ ** test-control enables us to write an intreal() SQL function that can
+ ** inject an intreal() value at arbitrary places in an SQL statement,
+ ** for testing purposes.
+ */
+ case SQLITE_TESTCTRL_RESULT_INTREAL: {
+ sqlite3_context *pCtx = va_arg(ap, sqlite3_context*);
+ sqlite3ResultIntReal(pCtx);
+ break;
+ }
+
+ /* sqlite3_test_control(SQLITE_TESTCTRL_SEEK_COUNT,
+ ** sqlite3 *db, // Database connection
+ ** u64 *pnSeek // Write seek count here
+ ** );
+ **
+ ** This test-control queries the seek-counter on the "main" database
+ ** file. The seek-counter is written into *pnSeek and is then reset.
+ ** The seek-count is only available if compiled with SQLITE_DEBUG.
+ */
+ case SQLITE_TESTCTRL_SEEK_COUNT: {
+ sqlite3 *db = va_arg(ap, sqlite3*);
+ u64 *pn = va_arg(ap, sqlite3_uint64*);
+ *pn = sqlite3BtreeSeekCount(db->aDb->pBt);
+ (void)db; /* Silence harmless unused variable warning */
+ break;
+ }
+
+
+ }
+ va_end(ap);
+#endif /* SQLITE_UNTESTABLE */
+ return rc;
+}
+
+/*
+** The Pager stores the Database filename, Journal filename, and WAL filename
+** consecutively in memory, in that order. The database filename is prefixed
+** by four zero bytes. Locate the start of the database filename by searching
+** backwards for the first byte following four consecutive zero bytes.
+**
+** This only works if the filename passed in was obtained from the Pager.
+*/
+static const char *databaseName(const char *zName){
+ while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
+ zName--;
+ }
+ return zName;
+}
+
+/*
+** Append text z[] to the end of p[]. Return a pointer to the first
+** character after then zero terminator on the new text in p[].
+*/
+static char *appendText(char *p, const char *z){
+ size_t n = strlen(z);
+ memcpy(p, z, n+1);
+ return p+n+1;
+}
+
+/*
+** Allocate memory to hold names for a database, journal file, WAL file,
+** and query parameters. The pointer returned is valid for use by
+** sqlite3_filename_database() and sqlite3_uri_parameter() and related
+** functions.
+**
+** Memory layout must be compatible with that generated by the pager
+** and expected by sqlite3_uri_parameter() and databaseName().
+*/
+SQLITE_API char *sqlite3_create_filename(
+ const char *zDatabase,
+ const char *zJournal,
+ const char *zWal,
+ int nParam,
+ const char **azParam
+){
+ sqlite3_int64 nByte;
+ int i;
+ char *pResult, *p;
+ nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10;
+ for(i=0; i<nParam*2; i++){
+ nByte += strlen(azParam[i])+1;
+ }
+ pResult = p = sqlite3_malloc64( nByte );
+ if( p==0 ) return 0;
+ memset(p, 0, 4);
+ p += 4;
+ p = appendText(p, zDatabase);
+ for(i=0; i<nParam*2; i++){
+ p = appendText(p, azParam[i]);
+ }
+ *(p++) = 0;
+ p = appendText(p, zJournal);
+ p = appendText(p, zWal);
+ *(p++) = 0;
+ *(p++) = 0;
+ assert( (sqlite3_int64)(p - pResult)==nByte );
+ return pResult + 4;
+}
+
+/*
+** Free memory obtained from sqlite3_create_filename(). It is a severe
+** error to call this routine with any parameter other than a pointer
+** previously obtained from sqlite3_create_filename() or a NULL pointer.
+*/
+SQLITE_API void sqlite3_free_filename(char *p){
+ if( p==0 ) return;
+ p = (char*)databaseName(p);
+ sqlite3_free(p - 4);
+}
+
+
+/*
+** This is a utility routine, useful to VFS implementations, that checks
+** to see if a database file was a URI that contained a specific query
+** parameter, and if so obtains the value of the query parameter.
+**
+** The zFilename argument is the filename pointer passed into the xOpen()
+** method of a VFS implementation. The zParam argument is the name of the
+** query parameter we seek. This routine returns the value of the zParam
+** parameter if it exists. If the parameter does not exist, this routine
+** returns a NULL pointer.
+*/
+SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
+ if( zFilename==0 || zParam==0 ) return 0;
+ zFilename = databaseName(zFilename);
+ return uriParameter(zFilename, zParam);
+}
+
+/*
+** Return a pointer to the name of Nth query parameter of the filename.
+*/
+SQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N){
+ if( zFilename==0 || N<0 ) return 0;
+ zFilename = databaseName(zFilename);
+ zFilename += sqlite3Strlen30(zFilename) + 1;
+ while( zFilename[0] && (N--)>0 ){
+ zFilename += sqlite3Strlen30(zFilename) + 1;
+ zFilename += sqlite3Strlen30(zFilename) + 1;
+ }
+ return zFilename[0] ? zFilename : 0;
+}
+
+/*
+** Return a boolean value for a query parameter.
+*/
+SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
+ const char *z = sqlite3_uri_parameter(zFilename, zParam);
+ bDflt = bDflt!=0;
+ return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
+}
+
+/*
+** Return a 64-bit integer value for a query parameter.
+*/
+SQLITE_API sqlite3_int64 sqlite3_uri_int64(
+ const char *zFilename, /* Filename as passed to xOpen */
+ const char *zParam, /* URI parameter sought */
+ sqlite3_int64 bDflt /* return if parameter is missing */
+){
+ const char *z = sqlite3_uri_parameter(zFilename, zParam);
+ sqlite3_int64 v;
+ if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
+ bDflt = v;
+ }
+ return bDflt;
+}
+
+/*
+** Translate a filename that was handed to a VFS routine into the corresponding
+** database, journal, or WAL file.
+**
+** It is an error to pass this routine a filename string that was not
+** passed into the VFS from the SQLite core. Doing so is similar to
+** passing free() a pointer that was not obtained from malloc() - it is
+** an error that we cannot easily detect but that will likely cause memory
+** corruption.
+*/
+SQLITE_API const char *sqlite3_filename_database(const char *zFilename){
+ return databaseName(zFilename);
+}
+SQLITE_API const char *sqlite3_filename_journal(const char *zFilename){
+ zFilename = databaseName(zFilename);
+ zFilename += sqlite3Strlen30(zFilename) + 1;
+ while( zFilename[0] ){
+ zFilename += sqlite3Strlen30(zFilename) + 1;
+ zFilename += sqlite3Strlen30(zFilename) + 1;
+ }
+ return zFilename + 1;
+}
+SQLITE_API const char *sqlite3_filename_wal(const char *zFilename){
+#ifdef SQLITE_OMIT_WAL
+ return 0;
+#else
+ zFilename = sqlite3_filename_journal(zFilename);
+ zFilename += sqlite3Strlen30(zFilename) + 1;
+ return zFilename;
+#endif
+}
+
+/*
+** Return the Btree pointer identified by zDbName. Return NULL if not found.
+*/
+SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
+ int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
+ return iDb<0 ? 0 : db->aDb[iDb].pBt;
+}
+
+/*
+** Return the filename of the database associated with a database
+** connection.
+*/
+SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
+ Btree *pBt;
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+ pBt = sqlite3DbNameToBtree(db, zDbName);
+ return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
+}
+
+/*
+** Return 1 if database is read-only or 0 if read/write. Return -1 if
+** no such database exists.
+*/
+SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
+ Btree *pBt;
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ (void)SQLITE_MISUSE_BKPT;
+ return -1;
+ }
+#endif
+ pBt = sqlite3DbNameToBtree(db, zDbName);
+ return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
+}
+
+#ifdef SQLITE_ENABLE_SNAPSHOT
+/*
+** Obtain a snapshot handle for the snapshot of database zDb currently
+** being read by handle db.
+*/
+SQLITE_API int sqlite3_snapshot_get(
+ sqlite3 *db,
+ const char *zDb,
+ sqlite3_snapshot **ppSnapshot
+){
+ int rc = SQLITE_ERROR;
+#ifndef SQLITE_OMIT_WAL
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ return SQLITE_MISUSE_BKPT;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+
+ if( db->autoCommit==0 ){
+ int iDb = sqlite3FindDbName(db, zDb);
+ if( iDb==0 || iDb>1 ){
+ Btree *pBt = db->aDb[iDb].pBt;
+ if( SQLITE_TXN_WRITE!=sqlite3BtreeTxnState(pBt) ){
+ rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
+ }
+ }
+ }
+ }
+
+ sqlite3_mutex_leave(db->mutex);
+#endif /* SQLITE_OMIT_WAL */
+ return rc;
+}
+
+/*
+** Open a read-transaction on the snapshot idendified by pSnapshot.
+*/
+SQLITE_API int sqlite3_snapshot_open(
+ sqlite3 *db,
+ const char *zDb,
+ sqlite3_snapshot *pSnapshot
+){
+ int rc = SQLITE_ERROR;
+#ifndef SQLITE_OMIT_WAL
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ return SQLITE_MISUSE_BKPT;
+ }
+#endif
+ sqlite3_mutex_enter(db->mutex);
+ if( db->autoCommit==0 ){
+ int iDb;
+ iDb = sqlite3FindDbName(db, zDb);
+ if( iDb==0 || iDb>1 ){
+ Btree *pBt = db->aDb[iDb].pBt;
+ if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE ){
+ Pager *pPager = sqlite3BtreePager(pBt);
+ int bUnlock = 0;
+ if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_NONE ){
+ if( db->nVdbeActive==0 ){
+ rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
+ if( rc==SQLITE_OK ){
+ bUnlock = 1;
+ rc = sqlite3BtreeCommit(pBt);
+ }
+ }
+ }else{
+ rc = SQLITE_OK;
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
+ sqlite3PagerSnapshotOpen(pPager, 0);
+ }
+ if( bUnlock ){
+ sqlite3PagerSnapshotUnlock(pPager);
+ }
+ }
+ }
+ }
+
+ sqlite3_mutex_leave(db->mutex);
+#endif /* SQLITE_OMIT_WAL */
+ return rc;
+}
+
+/*
+** Recover as many snapshots as possible from the wal file associated with
+** schema zDb of database db.
+*/
+SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
+ int rc = SQLITE_ERROR;
+ int iDb;
+#ifndef SQLITE_OMIT_WAL
+
+#ifdef SQLITE_ENABLE_API_ARMOR
+ if( !sqlite3SafetyCheckOk(db) ){
+ return SQLITE_MISUSE_BKPT;
+ }
+#endif
+
+ sqlite3_mutex_enter(db->mutex);
+ iDb = sqlite3FindDbName(db, zDb);
+ if( iDb==0 || iDb>1 ){
+ Btree *pBt = db->aDb[iDb].pBt;
+ if( SQLITE_TXN_NONE==sqlite3BtreeTxnState(pBt) ){
+ rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
+ sqlite3BtreeCommit(pBt);
+ }
+ }
+ }
+ sqlite3_mutex_leave(db->mutex);
+#endif /* SQLITE_OMIT_WAL */
+ return rc;
+}
+
+/*
+** Free a snapshot handle obtained from sqlite3_snapshot_get().
+*/
+SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
+ sqlite3_free(pSnapshot);
+}
+#endif /* SQLITE_ENABLE_SNAPSHOT */
+
+#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
+/*
+** Given the name of a compile-time option, return true if that option
+** was used and false if not.
+**
+** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
+** is not required for a match.
+*/
+SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
+ int i, n;
+ int nOpt;
+ const char **azCompileOpt;
+
+#if SQLITE_ENABLE_API_ARMOR
+ if( zOptName==0 ){
+ (void)SQLITE_MISUSE_BKPT;
+ return 0;
+ }
+#endif
+
+ azCompileOpt = sqlite3CompileOptions(&nOpt);
+
+ if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
+ n = sqlite3Strlen30(zOptName);
+
+ /* Since nOpt is normally in single digits, a linear search is
+ ** adequate. No need for a binary search. */
+ for(i=0; i<nOpt; i++){
+ if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
+ && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
+ ){
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/*
+** Return the N-th compile-time option string. If N is out of range,
+** return a NULL pointer.
+*/
+SQLITE_API const char *sqlite3_compileoption_get(int N){
+ int nOpt;
+ const char **azCompileOpt;
+ azCompileOpt = sqlite3CompileOptions(&nOpt);
+ if( N>=0 && N<nOpt ){
+ return azCompileOpt[N];
+ }
+ return 0;
+}
+#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
+
+/************** End of main.c ************************************************/
+/************** Begin file notify.c ******************************************/
+/*
+** 2009 March 3
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains the implementation of the sqlite3_unlock_notify()
+** API method and its associated functionality.
+*/
+/* #include "sqliteInt.h" */
+/* #include "btreeInt.h" */
+
+/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
+#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
+
+/*
+** Public interfaces:
+**
+** sqlite3ConnectionBlocked()
+** sqlite3ConnectionUnlocked()
+** sqlite3ConnectionClosed()
+** sqlite3_unlock_notify()
+*/
+
+#define assertMutexHeld() \
+ assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN)) )
+
+/*
+** Head of a linked list of all sqlite3 objects created by this process
+** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
+** is not NULL. This variable may only accessed while the STATIC_MAIN
+** mutex is held.
+*/
+static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
+
+#ifndef NDEBUG
+/*
+** This function is a complex assert() that verifies the following
+** properties of the blocked connections list:
+**
+** 1) Each entry in the list has a non-NULL value for either
+** pUnlockConnection or pBlockingConnection, or both.
+**
+** 2) All entries in the list that share a common value for
+** xUnlockNotify are grouped together.
+**
+** 3) If the argument db is not NULL, then none of the entries in the
+** blocked connections list have pUnlockConnection or pBlockingConnection
+** set to db. This is used when closing connection db.
+*/
+static void checkListProperties(sqlite3 *db){
+ sqlite3 *p;
+ for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
+ int seen = 0;
+ sqlite3 *p2;
+
+ /* Verify property (1) */
+ assert( p->pUnlockConnection || p->pBlockingConnection );
+
+ /* Verify property (2) */
+ for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
+ if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
+ assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
+ assert( db==0 || p->pUnlockConnection!=db );
+ assert( db==0 || p->pBlockingConnection!=db );
+ }
+ }
+}
+#else
+# define checkListProperties(x)
+#endif
+
+/*
+** Remove connection db from the blocked connections list. If connection
+** db is not currently a part of the list, this function is a no-op.
+*/
+static void removeFromBlockedList(sqlite3 *db){
+ sqlite3 **pp;
+ assertMutexHeld();
+ for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
+ if( *pp==db ){
+ *pp = (*pp)->pNextBlocked;
+ break;
+ }
+ }
+}
+
+/*
+** Add connection db to the blocked connections list. It is assumed
+** that it is not already a part of the list.
+*/
+static void addToBlockedList(sqlite3 *db){
+ sqlite3 **pp;
+ assertMutexHeld();
+ for(
+ pp=&sqlite3BlockedList;
+ *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
+ pp=&(*pp)->pNextBlocked
+ );
+ db->pNextBlocked = *pp;
+ *pp = db;
+}
+
+/*
+** Obtain the STATIC_MAIN mutex.
+*/
+static void enterMutex(void){
+ sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
+ checkListProperties(0);
+}
+
+/*
+** Release the STATIC_MAIN mutex.
+*/
+static void leaveMutex(void){
+ assertMutexHeld();
+ checkListProperties(0);
+ sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
+}
+
+/*
+** Register an unlock-notify callback.
+**
+** This is called after connection "db" has attempted some operation
+** but has received an SQLITE_LOCKED error because another connection
+** (call it pOther) in the same process was busy using the same shared
+** cache. pOther is found by looking at db->pBlockingConnection.
+**
+** If there is no blocking connection, the callback is invoked immediately,
+** before this routine returns.
+**
+** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
+** a deadlock.
+**
+** Otherwise, make arrangements to invoke xNotify when pOther drops
+** its locks.
+**
+** Each call to this routine overrides any prior callbacks registered
+** on the same "db". If xNotify==0 then any prior callbacks are immediately
+** cancelled.
+*/
+SQLITE_API int sqlite3_unlock_notify(
+ sqlite3 *db,
+ void (*xNotify)(void **, int),
+ void *pArg
+){
+ int rc = SQLITE_OK;
+
+ sqlite3_mutex_enter(db->mutex);
+ enterMutex();
+
+ if( xNotify==0 ){
+ removeFromBlockedList(db);
+ db->pBlockingConnection = 0;
+ db->pUnlockConnection = 0;
+ db->xUnlockNotify = 0;
+ db->pUnlockArg = 0;
+ }else if( 0==db->pBlockingConnection ){
+ /* The blocking transaction has been concluded. Or there never was a
+ ** blocking transaction. In either case, invoke the notify callback
+ ** immediately.
+ */
+ xNotify(&pArg, 1);
+ }else{
+ sqlite3 *p;
+
+ for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
+ if( p ){
+ rc = SQLITE_LOCKED; /* Deadlock detected. */
+ }else{
+ db->pUnlockConnection = db->pBlockingConnection;
+ db->xUnlockNotify = xNotify;
+ db->pUnlockArg = pArg;
+ removeFromBlockedList(db);
+ addToBlockedList(db);
+ }
+ }
+
+ leaveMutex();
+ assert( !db->mallocFailed );
+ sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
+ sqlite3_mutex_leave(db->mutex);
+ return rc;
+}
+
+/*
+** This function is called while stepping or preparing a statement
+** associated with connection db. The operation will return SQLITE_LOCKED
+** to the user because it requires a lock that will not be available
+** until connection pBlocker concludes its current transaction.
+*/
+SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
+ enterMutex();
+ if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
+ addToBlockedList(db);
+ }
+ db->pBlockingConnection = pBlocker;
+ leaveMutex();
+}
+
+/*
+** This function is called when
+** the transaction opened by database db has just finished. Locks held
+** by database connection db have been released.
+**
+** This function loops through each entry in the blocked connections
+** list and does the following:
+**
+** 1) If the sqlite3.pBlockingConnection member of a list entry is
+** set to db, then set pBlockingConnection=0.
+**
+** 2) If the sqlite3.pUnlockConnection member of a list entry is
+** set to db, then invoke the configured unlock-notify callback and
+** set pUnlockConnection=0.
+**
+** 3) If the two steps above mean that pBlockingConnection==0 and
+** pUnlockConnection==0, remove the entry from the blocked connections
+** list.
+*/
+SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
+ void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
+ int nArg = 0; /* Number of entries in aArg[] */
+ sqlite3 **pp; /* Iterator variable */
+ void **aArg; /* Arguments to the unlock callback */
+ void **aDyn = 0; /* Dynamically allocated space for aArg[] */
+ void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
+
+ aArg = aStatic;
+ enterMutex(); /* Enter STATIC_MAIN mutex */
+
+ /* This loop runs once for each entry in the blocked-connections list. */
+ for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
+ sqlite3 *p = *pp;
+
+ /* Step 1. */
+ if( p->pBlockingConnection==db ){
+ p->pBlockingConnection = 0;
+ }
+
+ /* Step 2. */
+ if( p->pUnlockConnection==db ){
+ assert( p->xUnlockNotify );
+ if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
+ xUnlockNotify(aArg, nArg);
+ nArg = 0;
+ }
+
+ sqlite3BeginBenignMalloc();
+ assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
+ assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
+ if( (!aDyn && nArg==(int)ArraySize(aStatic))
+ || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
+ ){
+ /* The aArg[] array needs to grow. */
+ void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
+ if( pNew ){
+ memcpy(pNew, aArg, nArg*sizeof(void *));
+ sqlite3_free(aDyn);
+ aDyn = aArg = pNew;
+ }else{
+ /* This occurs when the array of context pointers that need to
+ ** be passed to the unlock-notify callback is larger than the
+ ** aStatic[] array allocated on the stack and the attempt to
+ ** allocate a larger array from the heap has failed.
+ **
+ ** This is a difficult situation to handle. Returning an error
+ ** code to the caller is insufficient, as even if an error code
+ ** is returned the transaction on connection db will still be
+ ** closed and the unlock-notify callbacks on blocked connections
+ ** will go unissued. This might cause the application to wait
+ ** indefinitely for an unlock-notify callback that will never
+ ** arrive.
+ **
+ ** Instead, invoke the unlock-notify callback with the context
+ ** array already accumulated. We can then clear the array and
+ ** begin accumulating any further context pointers without
+ ** requiring any dynamic allocation. This is sub-optimal because
+ ** it means that instead of one callback with a large array of
+ ** context pointers the application will receive two or more
+ ** callbacks with smaller arrays of context pointers, which will
+ ** reduce the applications ability to prioritize multiple
+ ** connections. But it is the best that can be done under the
+ ** circumstances.
+ */
+ xUnlockNotify(aArg, nArg);
+ nArg = 0;
+ }
+ }
+ sqlite3EndBenignMalloc();
+
+ aArg[nArg++] = p->pUnlockArg;
+ xUnlockNotify = p->xUnlockNotify;
+ p->pUnlockConnection = 0;
+ p->xUnlockNotify = 0;
+ p->pUnlockArg = 0;
+ }
+
+ /* Step 3. */
+ if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
+ /* Remove connection p from the blocked connections list. */
+ *pp = p->pNextBlocked;
+ p->pNextBlocked = 0;
+ }else{
+ pp = &p->pNextBlocked;
+ }
+ }
+
+ if( nArg!=0 ){
+ xUnlockNotify(aArg, nArg);
+ }
+ sqlite3_free(aDyn);
+ leaveMutex(); /* Leave STATIC_MAIN mutex */
+}
+
+/*
+** This is called when the database connection passed as an argument is
+** being closed. The connection is removed from the blocked list.
+*/
+SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
+ sqlite3ConnectionUnlocked(db);
+ enterMutex();
+ removeFromBlockedList(db);
+ checkListProperties(db);
+ leaveMutex();
+}
+#endif
+
+/************** End of notify.c **********************************************/
+/************** Begin file fts3.c ********************************************/
+/*
+** 2006 Oct 10
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This is an SQLite module implementing full-text search.
+*/
+
+/*
+** The code in this file is only compiled if:
+**
+** * The FTS3 module is being built as an extension
+** (in which case SQLITE_CORE is not defined), or
+**
+** * The FTS3 module is being built into the core of
+** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
+*/
+
+/* The full-text index is stored in a series of b+tree (-like)
+** structures called segments which map terms to doclists. The
+** structures are like b+trees in layout, but are constructed from the
+** bottom up in optimal fashion and are not updatable. Since trees
+** are built from the bottom up, things will be described from the
+** bottom up.
+**
+**
+**** Varints ****
+** The basic unit of encoding is a variable-length integer called a
+** varint. We encode variable-length integers in little-endian order
+** using seven bits * per byte as follows:
+**
+** KEY:
+** A = 0xxxxxxx 7 bits of data and one flag bit
+** B = 1xxxxxxx 7 bits of data and one flag bit
+**
+** 7 bits - A
+** 14 bits - BA
+** 21 bits - BBA
+** and so on.
+**
+** This is similar in concept to how sqlite encodes "varints" but
+** the encoding is not the same. SQLite varints are big-endian
+** are are limited to 9 bytes in length whereas FTS3 varints are
+** little-endian and can be up to 10 bytes in length (in theory).
+**
+** Example encodings:
+**
+** 1: 0x01
+** 127: 0x7f
+** 128: 0x81 0x00
+**
+**
+**** Document lists ****
+** A doclist (document list) holds a docid-sorted list of hits for a
+** given term. Doclists hold docids and associated token positions.
+** A docid is the unique integer identifier for a single document.
+** A position is the index of a word within the document. The first
+** word of the document has a position of 0.
+**
+** FTS3 used to optionally store character offsets using a compile-time
+** option. But that functionality is no longer supported.
+**
+** A doclist is stored like this:
+**
+** array {
+** varint docid; (delta from previous doclist)
+** array { (position list for column 0)
+** varint position; (2 more than the delta from previous position)
+** }
+** array {
+** varint POS_COLUMN; (marks start of position list for new column)
+** varint column; (index of new column)
+** array {
+** varint position; (2 more than the delta from previous position)
+** }
+** }
+** varint POS_END; (marks end of positions for this document.
+** }
+**
+** Here, array { X } means zero or more occurrences of X, adjacent in
+** memory. A "position" is an index of a token in the token stream
+** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
+** in the same logical place as the position element, and act as sentinals
+** ending a position list array. POS_END is 0. POS_COLUMN is 1.
+** The positions numbers are not stored literally but rather as two more
+** than the difference from the prior position, or the just the position plus
+** 2 for the first position. Example:
+**
+** label: A B C D E F G H I J K
+** value: 123 5 9 1 1 14 35 0 234 72 0
+**
+** The 123 value is the first docid. For column zero in this document
+** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
+** at D signals the start of a new column; the 1 at E indicates that the
+** new column is column number 1. There are two positions at 12 and 45
+** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
+** 234 at I is the delta to next docid (357). It has one position 70
+** (72-2) and then terminates with the 0 at K.
+**
+** A "position-list" is the list of positions for multiple columns for
+** a single docid. A "column-list" is the set of positions for a single
+** column. Hence, a position-list consists of one or more column-lists,
+** a document record consists of a docid followed by a position-list and
+** a doclist consists of one or more document records.
+**
+** A bare doclist omits the position information, becoming an
+** array of varint-encoded docids.
+**
+**** Segment leaf nodes ****
+** Segment leaf nodes store terms and doclists, ordered by term. Leaf
+** nodes are written using LeafWriter, and read using LeafReader (to
+** iterate through a single leaf node's data) and LeavesReader (to
+** iterate through a segment's entire leaf layer). Leaf nodes have
+** the format:
+**
+** varint iHeight; (height from leaf level, always 0)
+** varint nTerm; (length of first term)
+** char pTerm[nTerm]; (content of first term)
+** varint nDoclist; (length of term's associated doclist)
+** char pDoclist[nDoclist]; (content of doclist)
+** array {
+** (further terms are delta-encoded)
+** varint nPrefix; (length of prefix shared with previous term)
+** varint nSuffix; (length of unshared suffix)
+** char pTermSuffix[nSuffix];(unshared suffix of next term)
+** varint nDoclist; (length of term's associated doclist)
+** char pDoclist[nDoclist]; (content of doclist)
+** }
+**
+** Here, array { X } means zero or more occurrences of X, adjacent in
+** memory.
+**
+** Leaf nodes are broken into blocks which are stored contiguously in
+** the %_segments table in sorted order. This means that when the end
+** of a node is reached, the next term is in the node with the next
+** greater node id.
+**
+** New data is spilled to a new leaf node when the current node
+** exceeds LEAF_MAX bytes (default 2048). New data which itself is
+** larger than STANDALONE_MIN (default 1024) is placed in a standalone
+** node (a leaf node with a single term and doclist). The goal of
+** these settings is to pack together groups of small doclists while
+** making it efficient to directly access large doclists. The
+** assumption is that large doclists represent terms which are more
+** likely to be query targets.
+**
+** TODO(shess) It may be useful for blocking decisions to be more
+** dynamic. For instance, it may make more sense to have a 2.5k leaf
+** node rather than splitting into 2k and .5k nodes. My intuition is
+** that this might extend through 2x or 4x the pagesize.
+**
+**
+**** Segment interior nodes ****
+** Segment interior nodes store blockids for subtree nodes and terms
+** to describe what data is stored by the each subtree. Interior
+** nodes are written using InteriorWriter, and read using
+** InteriorReader. InteriorWriters are created as needed when
+** SegmentWriter creates new leaf nodes, or when an interior node
+** itself grows too big and must be split. The format of interior
+** nodes:
+**
+** varint iHeight; (height from leaf level, always >0)
+** varint iBlockid; (block id of node's leftmost subtree)
+** optional {
+** varint nTerm; (length of first term)
+** char pTerm[nTerm]; (content of first term)
+** array {
+** (further terms are delta-encoded)
+** varint nPrefix; (length of shared prefix with previous term)
+** varint nSuffix; (length of unshared suffix)
+** char pTermSuffix[nSuffix]; (unshared suffix of next term)
+** }
+** }
+**
+** Here, optional { X } means an optional element, while array { X }
+** means zero or more occurrences of X, adjacent in memory.
+**
+** An interior node encodes n terms separating n+1 subtrees. The
+** subtree blocks are contiguous, so only the first subtree's blockid
+** is encoded. The subtree at iBlockid will contain all terms less
+** than the first term encoded (or all terms if no term is encoded).
+** Otherwise, for terms greater than or equal to pTerm[i] but less
+** than pTerm[i+1], the subtree for that term will be rooted at
+** iBlockid+i. Interior nodes only store enough term data to
+** distinguish adjacent children (if the rightmost term of the left
+** child is "something", and the leftmost term of the right child is
+** "wicked", only "w" is stored).
+**
+** New data is spilled to a new interior node at the same height when
+** the current node exceeds INTERIOR_MAX bytes (default 2048).
+** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
+** interior nodes and making the tree too skinny. The interior nodes
+** at a given height are naturally tracked by interior nodes at
+** height+1, and so on.
+**
+**
+**** Segment directory ****
+** The segment directory in table %_segdir stores meta-information for
+** merging and deleting segments, and also the root node of the
+** segment's tree.
+**
+** The root node is the top node of the segment's tree after encoding
+** the entire segment, restricted to ROOT_MAX bytes (default 1024).
+** This could be either a leaf node or an interior node. If the top
+** node requires more than ROOT_MAX bytes, it is flushed to %_segments
+** and a new root interior node is generated (which should always fit
+** within ROOT_MAX because it only needs space for 2 varints, the
+** height and the blockid of the previous root).
+**
+** The meta-information in the segment directory is:
+** level - segment level (see below)
+** idx - index within level
+** - (level,idx uniquely identify a segment)
+** start_block - first leaf node
+** leaves_end_block - last leaf node
+** end_block - last block (including interior nodes)
+** root - contents of root node
+**
+** If the root node is a leaf node, then start_block,
+** leaves_end_block, and end_block are all 0.
+**
+**
+**** Segment merging ****
+** To amortize update costs, segments are grouped into levels and
+** merged in batches. Each increase in level represents exponentially
+** more documents.
+**
+** New documents (actually, document updates) are tokenized and
+** written individually (using LeafWriter) to a level 0 segment, with
+** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
+** level 0 segments are merged into a single level 1 segment. Level 1
+** is populated like level 0, and eventually MERGE_COUNT level 1
+** segments are merged to a single level 2 segment (representing
+** MERGE_COUNT^2 updates), and so on.
+**
+** A segment merge traverses all segments at a given level in
+** parallel, performing a straightforward sorted merge. Since segment
+** leaf nodes are written in to the %_segments table in order, this
+** merge traverses the underlying sqlite disk structures efficiently.
+** After the merge, all segment blocks from the merged level are
+** deleted.
+**
+** MERGE_COUNT controls how often we merge segments. 16 seems to be
+** somewhat of a sweet spot for insertion performance. 32 and 64 show
+** very similar performance numbers to 16 on insertion, though they're
+** a tiny bit slower (perhaps due to more overhead in merge-time
+** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
+** 16, 2 about 66% slower than 16.
+**
+** At query time, high MERGE_COUNT increases the number of segments
+** which need to be scanned and merged. For instance, with 100k docs
+** inserted:
+**
+** MERGE_COUNT segments
+** 16 25
+** 8 12
+** 4 10
+** 2 6
+**
+** This appears to have only a moderate impact on queries for very
+** frequent terms (which are somewhat dominated by segment merge
+** costs), and infrequent and non-existent terms still seem to be fast
+** even with many segments.
+**
+** TODO(shess) That said, it would be nice to have a better query-side
+** argument for MERGE_COUNT of 16. Also, it is possible/likely that
+** optimizations to things like doclist merging will swing the sweet
+** spot around.
+**
+**
+**
+**** Handling of deletions and updates ****
+** Since we're using a segmented structure, with no docid-oriented
+** index into the term index, we clearly cannot simply update the term
+** index when a document is deleted or updated. For deletions, we
+** write an empty doclist (varint(docid) varint(POS_END)), for updates
+** we simply write the new doclist. Segment merges overwrite older
+** data for a particular docid with newer data, so deletes or updates
+** will eventually overtake the earlier data and knock it out. The
+** query logic likewise merges doclists so that newer data knocks out
+** older data.
+*/
+
+/************** Include fts3Int.h in the middle of fts3.c ********************/
+/************** Begin file fts3Int.h *****************************************/
+/*
+** 2009 Nov 12
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+*/
+#ifndef _FTSINT_H
+#define _FTSINT_H
+
+#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
+# define NDEBUG 1
+#endif
+
+/* FTS3/FTS4 require virtual tables */
+#ifdef SQLITE_OMIT_VIRTUALTABLE
+# undef SQLITE_ENABLE_FTS3
+# undef SQLITE_ENABLE_FTS4
+#endif
+
+/*
+** FTS4 is really an extension for FTS3. It is enabled using the
+** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
+** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
+*/
+#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
+# define SQLITE_ENABLE_FTS3
+#endif
+
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
+
+/* If not building as part of the core, include sqlite3ext.h. */
+#ifndef SQLITE_CORE
+/* # include "sqlite3ext.h" */
+SQLITE_EXTENSION_INIT3
+#endif
+
+/* #include "sqlite3.h" */
+/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
+/************** Begin file fts3_tokenizer.h **********************************/
+/*
+** 2006 July 10
+**
+** The author disclaims copyright to this source code.
+**
+*************************************************************************
+** Defines the interface to tokenizers used by fulltext-search. There
+** are three basic components:
+**
+** sqlite3_tokenizer_module is a singleton defining the tokenizer
+** interface functions. This is essentially the class structure for
+** tokenizers.
+**
+** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
+** including customization information defined at creation time.
+**
+** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
+** tokens from a particular input.
+*/
+#ifndef _FTS3_TOKENIZER_H_
+#define _FTS3_TOKENIZER_H_
+
+/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
+** If tokenizers are to be allowed to call sqlite3_*() functions, then
+** we will need a way to register the API consistently.
+*/
+/* #include "sqlite3.h" */
+
+/*
+** Structures used by the tokenizer interface. When a new tokenizer
+** implementation is registered, the caller provides a pointer to
+** an sqlite3_tokenizer_module containing pointers to the callback
+** functions that make up an implementation.
+**
+** When an fts3 table is created, it passes any arguments passed to
+** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
+** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
+** implementation. The xCreate() function in turn returns an
+** sqlite3_tokenizer structure representing the specific tokenizer to
+** be used for the fts3 table (customized by the tokenizer clause arguments).
+**
+** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
+** method is called. It returns an sqlite3_tokenizer_cursor object
+** that may be used to tokenize a specific input buffer based on
+** the tokenization rules supplied by a specific sqlite3_tokenizer
+** object.
+*/
+typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
+typedef struct sqlite3_tokenizer sqlite3_tokenizer;
+typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
+
+struct sqlite3_tokenizer_module {
+
+ /*
+ ** Structure version. Should always be set to 0 or 1.
+ */
+ int iVersion;
+
+ /*
+ ** Create a new tokenizer. The values in the argv[] array are the
+ ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
+ ** TABLE statement that created the fts3 table. For example, if
+ ** the following SQL is executed:
+ **
+ ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
+ **
+ ** then argc is set to 2, and the argv[] array contains pointers
+ ** to the strings "arg1" and "arg2".
+ **
+ ** This method should return either SQLITE_OK (0), or an SQLite error
+ ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
+ ** to point at the newly created tokenizer structure. The generic
+ ** sqlite3_tokenizer.pModule variable should not be initialized by
+ ** this callback. The caller will do so.
+ */
+ int (*xCreate)(
+ int argc, /* Size of argv array */
+ const char *const*argv, /* Tokenizer argument strings */
+ sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
+ );
+
+ /*
+ ** Destroy an existing tokenizer. The fts3 module calls this method
+ ** exactly once for each successful call to xCreate().
+ */
+ int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
+
+ /*
+ ** Create a tokenizer cursor to tokenize an input buffer. The caller
+ ** is responsible for ensuring that the input buffer remains valid
+ ** until the cursor is closed (using the xClose() method).
+ */
+ int (*xOpen)(
+ sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
+ const char *pInput, int nBytes, /* Input buffer */
+ sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
+ );
+
+ /*
+ ** Destroy an existing tokenizer cursor. The fts3 module calls this
+ ** method exactly once for each successful call to xOpen().
+ */
+ int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
+
+ /*
+ ** Retrieve the next token from the tokenizer cursor pCursor. This
+ ** method should either return SQLITE_OK and set the values of the
+ ** "OUT" variables identified below, or SQLITE_DONE to indicate that
+ ** the end of the buffer has been reached, or an SQLite error code.
+ **
+ ** *ppToken should be set to point at a buffer containing the
+ ** normalized version of the token (i.e. after any case-folding and/or
+ ** stemming has been performed). *pnBytes should be set to the length
+ ** of this buffer in bytes. The input text that generated the token is
+ ** identified by the byte offsets returned in *piStartOffset and
+ ** *piEndOffset. *piStartOffset should be set to the index of the first
+ ** byte of the token in the input buffer. *piEndOffset should be set
+ ** to the index of the first byte just past the end of the token in
+ ** the input buffer.
+ **
+ ** The buffer *ppToken is set to point at is managed by the tokenizer
+ ** implementation. It is only required to be valid until the next call
+ ** to xNext() or xClose().
+ */
+ /* TODO(shess) current implementation requires pInput to be
+ ** nul-terminated. This should either be fixed, or pInput/nBytes
+ ** should be converted to zInput.
+ */
+ int (*xNext)(
+ sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
+ const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
+ int *piStartOffset, /* OUT: Byte offset of token in input buffer */
+ int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
+ int *piPosition /* OUT: Number of tokens returned before this one */
+ );
+
+ /***********************************************************************
+ ** Methods below this point are only available if iVersion>=1.
+ */
+
+ /*
+ ** Configure the language id of a tokenizer cursor.
+ */
+ int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
+};
+
+struct sqlite3_tokenizer {
+ const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
+ /* Tokenizer implementations will typically add additional fields */
+};
+
+struct sqlite3_tokenizer_cursor {
+ sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
+ /* Tokenizer implementations will typically add additional fields */
+};
+
+int fts3_global_term_cnt(int iTerm, int iCol);
+int fts3_term_cnt(int iTerm, int iCol);
+
+
+#endif /* _FTS3_TOKENIZER_H_ */
+
+/************** End of fts3_tokenizer.h **************************************/
+/************** Continuing where we left off in fts3Int.h ********************/
+/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
+/************** Begin file fts3_hash.h ***************************************/
+/*
+** 2001 September 22
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This is the header file for the generic hash-table implementation
+** used in SQLite. We've modified it slightly to serve as a standalone
+** hash table implementation for the full-text indexing module.
+**
+*/
+#ifndef _FTS3_HASH_H_
+#define _FTS3_HASH_H_
+
+/* Forward declarations of structures. */
+typedef struct Fts3Hash Fts3Hash;
+typedef struct Fts3HashElem Fts3HashElem;
+
+/* A complete hash table is an instance of the following structure.
+** The internals of this structure are intended to be opaque -- client
+** code should not attempt to access or modify the fields of this structure
+** directly. Change this structure only by using the routines below.
+** However, many of the "procedures" and "functions" for modifying and
+** accessing this structure are really macros, so we can't really make
+** this structure opaque.
+*/
+struct Fts3Hash {
+ char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
+ char copyKey; /* True if copy of key made on insert */
+ int count; /* Number of entries in this table */
+ Fts3HashElem *first; /* The first element of the array */
+ int htsize; /* Number of buckets in the hash table */
+ struct _fts3ht { /* the hash table */
+ int count; /* Number of entries with this hash */
+ Fts3HashElem *chain; /* Pointer to first entry with this hash */
+ } *ht;
+};
+
+/* Each element in the hash table is an instance of the following
+** structure. All elements are stored on a single doubly-linked list.
+**
+** Again, this structure is intended to be opaque, but it can't really
+** be opaque because it is used by macros.
+*/
+struct Fts3HashElem {
+ Fts3HashElem *next, *prev; /* Next and previous elements in the table */
+ void *data; /* Data associated with this element */
+ void *pKey; int nKey; /* Key associated with this element */
+};
+
+/*
+** There are 2 different modes of operation for a hash table:
+**
+** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
+** (including the null-terminator, if any). Case
+** is respected in comparisons.
+**
+** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
+** memcmp() is used to compare keys.
+**
+** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
+*/
+#define FTS3_HASH_STRING 1
+#define FTS3_HASH_BINARY 2
+
+/*
+** Access routines. To delete, insert a NULL pointer.
+*/
+SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
+SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
+SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
+SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
+SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
+
+/*
+** Shorthand for the functions above
+*/
+#define fts3HashInit sqlite3Fts3HashInit
+#define fts3HashInsert sqlite3Fts3HashInsert
+#define fts3HashFind sqlite3Fts3HashFind
+#define fts3HashClear sqlite3Fts3HashClear
+#define fts3HashFindElem sqlite3Fts3HashFindElem
+
+/*
+** Macros for looping over all elements of a hash table. The idiom is
+** like this:
+**
+** Fts3Hash h;
+** Fts3HashElem *p;
+** ...
+** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
+** SomeStructure *pData = fts3HashData(p);
+** // do something with pData
+** }
+*/
+#define fts3HashFirst(H) ((H)->first)
+#define fts3HashNext(E) ((E)->next)
+#define fts3HashData(E) ((E)->data)
+#define fts3HashKey(E) ((E)->pKey)
+#define fts3HashKeysize(E) ((E)->nKey)
+
+/*
+** Number of entries in a hash table
+*/
+#define fts3HashCount(H) ((H)->count)
+
+#endif /* _FTS3_HASH_H_ */
+
+/************** End of fts3_hash.h *******************************************/
+/************** Continuing where we left off in fts3Int.h ********************/
+
+/*
+** This constant determines the maximum depth of an FTS expression tree
+** that the library will create and use. FTS uses recursion to perform
+** various operations on the query tree, so the disadvantage of a large
+** limit is that it may allow very large queries to use large amounts
+** of stack space (perhaps causing a stack overflow).
+*/
+#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
+# define SQLITE_FTS3_MAX_EXPR_DEPTH 12
+#endif
+
+
+/*
+** This constant controls how often segments are merged. Once there are
+** FTS3_MERGE_COUNT segments of level N, they are merged into a single
+** segment of level N+1.
+*/
+#define FTS3_MERGE_COUNT 16
+
+/*
+** This is the maximum amount of data (in bytes) to store in the
+** Fts3Table.pendingTerms hash table. Normally, the hash table is
+** populated as documents are inserted/updated/deleted in a transaction
+** and used to create a new segment when the transaction is committed.
+** However if this limit is reached midway through a transaction, a new
+** segment is created and the hash table cleared immediately.
+*/
+#define FTS3_MAX_PENDING_DATA (1*1024*1024)
+
+/*
+** Macro to return the number of elements in an array. SQLite has a
+** similar macro called ArraySize(). Use a different name to avoid
+** a collision when building an amalgamation with built-in FTS3.
+*/
+#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
+
+
+#ifndef MIN
+# define MIN(x,y) ((x)<(y)?(x):(y))
+#endif
+#ifndef MAX
+# define MAX(x,y) ((x)>(y)?(x):(y))
+#endif
+
+/*
+** Maximum length of a varint encoded integer. The varint format is different
+** from that used by SQLite, so the maximum length is 10, not 9.
+*/
+#define FTS3_VARINT_MAX 10
+
+#define FTS3_BUFFER_PADDING 8
+
+/*
+** FTS4 virtual tables may maintain multiple indexes - one index of all terms
+** in the document set and zero or more prefix indexes. All indexes are stored
+** as one or more b+-trees in the %_segments and %_segdir tables.
+**
+** It is possible to determine which index a b+-tree belongs to based on the
+** value stored in the "%_segdir.level" column. Given this value L, the index
+** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
+** level values between 0 and 1023 (inclusive) belong to index 0, all levels
+** between 1024 and 2047 to index 1, and so on.
+**
+** It is considered impossible for an index to use more than 1024 levels. In
+** theory though this may happen, but only after at least
+** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
+*/
+#define FTS3_SEGDIR_MAXLEVEL 1024
+#define FTS3_SEGDIR_MAXLEVEL_STR "1024"
+
+/*
+** The testcase() macro is only used by the amalgamation. If undefined,
+** make it a no-op.
+*/
+#ifndef testcase
+# define testcase(X)
+#endif
+
+/*
+** Terminator values for position-lists and column-lists.
+*/
+#define POS_COLUMN (1) /* Column-list terminator */
+#define POS_END (0) /* Position-list terminator */
+
+/*
+** The assert_fts3_nc() macro is similar to the assert() macro, except that it
+** is used for assert() conditions that are true only if it can be
+** guranteed that the database is not corrupt.
+*/
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+SQLITE_API extern int sqlite3_fts3_may_be_corrupt;
+# define assert_fts3_nc(x) assert(sqlite3_fts3_may_be_corrupt || (x))
+#else
+# define assert_fts3_nc(x) assert(x)
+#endif
+
+/*
+** This section provides definitions to allow the
+** FTS3 extension to be compiled outside of the
+** amalgamation.
+*/
+#ifndef SQLITE_AMALGAMATION
+/*
+** Macros indicating that conditional expressions are always true or
+** false.
+*/
+#ifdef SQLITE_COVERAGE_TEST
+# define ALWAYS(x) (1)
+# define NEVER(X) (0)
+#elif defined(SQLITE_DEBUG)
+# define ALWAYS(x) sqlite3Fts3Always((x)!=0)
+# define NEVER(x) sqlite3Fts3Never((x)!=0)
+SQLITE_PRIVATE int sqlite3Fts3Always(int b);
+SQLITE_PRIVATE int sqlite3Fts3Never(int b);
+#else
+# define ALWAYS(x) (x)
+# define NEVER(x) (x)
+#endif
+
+/*
+** Internal types used by SQLite.
+*/
+typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
+typedef short int i16; /* 2-byte (or larger) signed integer */
+typedef unsigned int u32; /* 4-byte unsigned integer */
+typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
+typedef sqlite3_int64 i64; /* 8-byte signed integer */
+
+/*
+** Macro used to suppress compiler warnings for unused parameters.
+*/
+#define UNUSED_PARAMETER(x) (void)(x)
+
+/*
+** Activate assert() only if SQLITE_TEST is enabled.
+*/
+#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
+# define NDEBUG 1
+#endif
+
+/*
+** The TESTONLY macro is used to enclose variable declarations or
+** other bits of code that are needed to support the arguments
+** within testcase() and assert() macros.
+*/
+#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
+# define TESTONLY(X) X
+#else
+# define TESTONLY(X)
+#endif
+
+#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
+#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
+
+#define deliberate_fall_through
+
+#endif /* SQLITE_AMALGAMATION */
+
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
+# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
+#else
+# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
+#endif
+
+typedef struct Fts3Table Fts3Table;
+typedef struct Fts3Cursor Fts3Cursor;
+typedef struct Fts3Expr Fts3Expr;
+typedef struct Fts3Phrase Fts3Phrase;
+typedef struct Fts3PhraseToken Fts3PhraseToken;
+
+typedef struct Fts3Doclist Fts3Doclist;
+typedef struct Fts3SegFilter Fts3SegFilter;
+typedef struct Fts3DeferredToken Fts3DeferredToken;
+typedef struct Fts3SegReader Fts3SegReader;
+typedef struct Fts3MultiSegReader Fts3MultiSegReader;
+
+typedef struct MatchinfoBuffer MatchinfoBuffer;
+
+/*
+** A connection to a fulltext index is an instance of the following
+** structure. The xCreate and xConnect methods create an instance
+** of this structure and xDestroy and xDisconnect free that instance.
+** All other methods receive a pointer to the structure as one of their
+** arguments.
+*/
+struct Fts3Table {
+ sqlite3_vtab base; /* Base class used by SQLite core */
+ sqlite3 *db; /* The database connection */
+ const char *zDb; /* logical database name */
+ const char *zName; /* virtual table name */
+ int nColumn; /* number of named columns in virtual table */
+ char **azColumn; /* column names. malloced */
+ u8 *abNotindexed; /* True for 'notindexed' columns */
+ sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
+ char *zContentTbl; /* content=xxx option, or NULL */
+ char *zLanguageid; /* languageid=xxx option, or NULL */
+ int nAutoincrmerge; /* Value configured by 'automerge' */
+ u32 nLeafAdd; /* Number of leaf blocks added this trans */
+ int bLock; /* Used to prevent recursive content= tbls */
+
+ /* Precompiled statements used by the implementation. Each of these
+ ** statements is run and reset within a single virtual table API call.
+ */
+ sqlite3_stmt *aStmt[40];
+ sqlite3_stmt *pSeekStmt; /* Cache for fts3CursorSeekStmt() */
+
+ char *zReadExprlist;
+ char *zWriteExprlist;
+
+ int nNodeSize; /* Soft limit for node size */
+ u8 bFts4; /* True for FTS4, false for FTS3 */
+ u8 bHasStat; /* True if %_stat table exists (2==unknown) */
+ u8 bHasDocsize; /* True if %_docsize table exists */
+ u8 bDescIdx; /* True if doclists are in reverse order */
+ u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
+ int nPgsz; /* Page size for host database */
+ char *zSegmentsTbl; /* Name of %_segments table */
+ sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
+
+ /*
+ ** The following array of hash tables is used to buffer pending index
+ ** updates during transactions. All pending updates buffered at any one
+ ** time must share a common language-id (see the FTS4 langid= feature).
+ ** The current language id is stored in variable iPrevLangid.
+ **
+ ** A single FTS4 table may have multiple full-text indexes. For each index
+ ** there is an entry in the aIndex[] array. Index 0 is an index of all the
+ ** terms that appear in the document set. Each subsequent index in aIndex[]
+ ** is an index of prefixes of a specific length.
+ **
+ ** Variable nPendingData contains an estimate the memory consumed by the
+ ** pending data structures, including hash table overhead, but not including
+ ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
+ ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
+ ** recently inserted record.
+ */
+ int nIndex; /* Size of aIndex[] */
+ struct Fts3Index {
+ int nPrefix; /* Prefix length (0 for main terms index) */
+ Fts3Hash hPending; /* Pending terms table for this index */
+ } *aIndex;
+ int nMaxPendingData; /* Max pending data before flush to disk */
+ int nPendingData; /* Current bytes of pending data */
+ sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
+ int iPrevLangid; /* Langid of recently inserted document */
+ int bPrevDelete; /* True if last operation was a delete */
+
+#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
+ /* State variables used for validating that the transaction control
+ ** methods of the virtual table are called at appropriate times. These
+ ** values do not contribute to FTS functionality; they are used for
+ ** verifying the operation of the SQLite core.
+ */
+ int inTransaction; /* True after xBegin but before xCommit/xRollback */
+ int mxSavepoint; /* Largest valid xSavepoint integer */
+#endif
+
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+ /* True to disable the incremental doclist optimization. This is controled
+ ** by special insert command 'test-no-incr-doclist'. */
+ int bNoIncrDoclist;
+
+ /* Number of segments in a level */
+ int nMergeCount;
+#endif
+};
+
+/* Macro to find the number of segments to merge */
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+# define MergeCount(P) ((P)->nMergeCount)
+#else
+# define MergeCount(P) FTS3_MERGE_COUNT
+#endif
+
+/*
+** When the core wants to read from the virtual table, it creates a
+** virtual table cursor (an instance of the following structure) using
+** the xOpen method. Cursors are destroyed using the xClose method.
+*/
+struct Fts3Cursor {
+ sqlite3_vtab_cursor base; /* Base class used by SQLite core */
+ i16 eSearch; /* Search strategy (see below) */
+ u8 isEof; /* True if at End Of Results */
+ u8 isRequireSeek; /* True if must seek pStmt to %_content row */
+ u8 bSeekStmt; /* True if pStmt is a seek */
+ sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
+ Fts3Expr *pExpr; /* Parsed MATCH query string */
+ int iLangid; /* Language being queried for */
+ int nPhrase; /* Number of matchable phrases in query */
+ Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
+ sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
+ char *pNextId; /* Pointer into the body of aDoclist */
+ char *aDoclist; /* List of docids for full-text queries */
+ int nDoclist; /* Size of buffer at aDoclist */
+ u8 bDesc; /* True to sort in descending order */
+ int eEvalmode; /* An FTS3_EVAL_XX constant */
+ int nRowAvg; /* Average size of database rows, in pages */
+ sqlite3_int64 nDoc; /* Documents in table */
+ i64 iMinDocid; /* Minimum docid to return */
+ i64 iMaxDocid; /* Maximum docid to return */
+ int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
+ MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
+};
+
+#define FTS3_EVAL_FILTER 0
+#define FTS3_EVAL_NEXT 1
+#define FTS3_EVAL_MATCHINFO 2
+
+/*
+** The Fts3Cursor.eSearch member is always set to one of the following.
+** Actualy, Fts3Cursor.eSearch can be greater than or equal to
+** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
+** of the column to be searched. For example, in
+**
+** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
+** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
+**
+** Because the LHS of the MATCH operator is 2nd column "b",
+** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
+** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
+** indicating that all columns should be searched,
+** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
+*/
+#define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
+#define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
+#define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
+
+/*
+** The lower 16-bits of the sqlite3_index_info.idxNum value set by
+** the xBestIndex() method contains the Fts3Cursor.eSearch value described
+** above. The upper 16-bits contain a combination of the following
+** bits, used to describe extra constraints on full-text searches.
+*/
+#define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
+#define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
+#define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
+
+struct Fts3Doclist {
+ char *aAll; /* Array containing doclist (or NULL) */
+ int nAll; /* Size of a[] in bytes */
+ char *pNextDocid; /* Pointer to next docid */
+
+ sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
+ int bFreeList; /* True if pList should be sqlite3_free()d */
+ char *pList; /* Pointer to position list following iDocid */
+ int nList; /* Length of position list */
+};
+
+/*
+** A "phrase" is a sequence of one or more tokens that must match in
+** sequence. A single token is the base case and the most common case.
+** For a sequence of tokens contained in double-quotes (i.e. "one two three")
+** nToken will be the number of tokens in the string.
+*/
+struct Fts3PhraseToken {
+ char *z; /* Text of the token */
+ int n; /* Number of bytes in buffer z */
+ int isPrefix; /* True if token ends with a "*" character */
+ int bFirst; /* True if token must appear at position 0 */
+
+ /* Variables above this point are populated when the expression is
+ ** parsed (by code in fts3_expr.c). Below this point the variables are
+ ** used when evaluating the expression. */
+ Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
+ Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
+};
+
+struct Fts3Phrase {
+ /* Cache of doclist for this phrase. */
+ Fts3Doclist doclist;
+ int bIncr; /* True if doclist is loaded incrementally */
+ int iDoclistToken;
+
+ /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
+ ** OR condition. */
+ char *pOrPoslist;
+ i64 iOrDocid;
+
+ /* Variables below this point are populated by fts3_expr.c when parsing
+ ** a MATCH expression. Everything above is part of the evaluation phase.
+ */
+ int nToken; /* Number of tokens in the phrase */
+ int iColumn; /* Index of column this phrase must match */
+ Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
+};
+
+/*
+** A tree of these objects forms the RHS of a MATCH operator.
+**
+** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
+** points to a malloced buffer, size nDoclist bytes, containing the results
+** of this phrase query in FTS3 doclist format. As usual, the initial
+** "Length" field found in doclists stored on disk is omitted from this
+** buffer.
+**
+** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
+** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
+** where nCol is the number of columns in the queried FTS table. The array
+** is populated as follows:
+**
+** aMI[iCol*3 + 0] = Undefined
+** aMI[iCol*3 + 1] = Number of occurrences
+** aMI[iCol*3 + 2] = Number of rows containing at least one instance
+**
+** The aMI array is allocated using sqlite3_malloc(). It should be freed
+** when the expression node is.
+*/
+struct Fts3Expr {
+ int eType; /* One of the FTSQUERY_XXX values defined below */
+ int nNear; /* Valid if eType==FTSQUERY_NEAR */
+ Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
+ Fts3Expr *pLeft; /* Left operand */
+ Fts3Expr *pRight; /* Right operand */
+ Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
+
+ /* The following are used by the fts3_eval.c module. */
+ sqlite3_int64 iDocid; /* Current docid */
+ u8 bEof; /* True this expression is at EOF already */
+ u8 bStart; /* True if iDocid is valid */
+ u8 bDeferred; /* True if this expression is entirely deferred */
+
+ /* The following are used by the fts3_snippet.c module. */
+ int iPhrase; /* Index of this phrase in matchinfo() results */
+ u32 *aMI; /* See above */
+};
+
+/*
+** Candidate values for Fts3Query.eType. Note that the order of the first
+** four values is in order of precedence when parsing expressions. For
+** example, the following:
+**
+** "a OR b AND c NOT d NEAR e"
+**
+** is equivalent to:
+**
+** "a OR (b AND (c NOT (d NEAR e)))"
+*/
+#define FTSQUERY_NEAR 1
+#define FTSQUERY_NOT 2
+#define FTSQUERY_AND 3
+#define FTSQUERY_OR 4
+#define FTSQUERY_PHRASE 5
+
+
+/* fts3_write.c */
+SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
+SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
+SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
+SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
+SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
+ sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
+SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
+ Fts3Table*,int,const char*,int,int,Fts3SegReader**);
+SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
+SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
+SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
+
+SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
+SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
+
+#ifndef SQLITE_DISABLE_FTS4_DEFERRED
+SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
+SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
+SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
+SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
+SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
+#else
+# define sqlite3Fts3FreeDeferredTokens(x)
+# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
+# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
+# define sqlite3Fts3FreeDeferredDoclists(x)
+# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
+#endif
+
+SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
+SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
+
+/* Special values interpreted by sqlite3SegReaderCursor() */
+#define FTS3_SEGCURSOR_PENDING -1
+#define FTS3_SEGCURSOR_ALL -2
+
+SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
+SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
+SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
+
+SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
+ int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
+
+/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
+#define FTS3_SEGMENT_REQUIRE_POS 0x00000001
+#define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
+#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
+#define FTS3_SEGMENT_PREFIX 0x00000008
+#define FTS3_SEGMENT_SCAN 0x00000010
+#define FTS3_SEGMENT_FIRST 0x00000020
+
+/* Type passed as 4th argument to SegmentReaderIterate() */
+struct Fts3SegFilter {
+ const char *zTerm;
+ int nTerm;
+ int iCol;
+ int flags;
+};
+
+struct Fts3MultiSegReader {
+ /* Used internally by sqlite3Fts3SegReaderXXX() calls */
+ Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
+ int nSegment; /* Size of apSegment array */
+ int nAdvance; /* How many seg-readers to advance */
+ Fts3SegFilter *pFilter; /* Pointer to filter object */
+ char *aBuffer; /* Buffer to merge doclists in */
+ int nBuffer; /* Allocated size of aBuffer[] in bytes */
+
+ int iColFilter; /* If >=0, filter for this column */
+ int bRestart;
+
+ /* Used by fts3.c only. */
+ int nCost; /* Cost of running iterator */
+ int bLookup; /* True if a lookup of a single entry. */
+
+ /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
+ char *zTerm; /* Pointer to term buffer */
+ int nTerm; /* Size of zTerm in bytes */
+ char *aDoclist; /* Pointer to doclist buffer */
+ int nDoclist; /* Size of aDoclist[] in bytes */
+};
+
+SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
+
+#define fts3GetVarint32(p, piVal) ( \
+ (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
+)
+
+/* fts3.c */
+SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
+SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
+SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
+SQLITE_PRIVATE int sqlite3Fts3GetVarintU(const char *, sqlite_uint64 *);
+SQLITE_PRIVATE int sqlite3Fts3GetVarintBounded(const char*,const char*,sqlite3_int64*);
+SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
+SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
+SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
+SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
+SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
+SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
+SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
+SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
+SQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut);
+
+/* fts3_tokenizer.c */
+SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
+SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
+SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
+ sqlite3_tokenizer **, char **
+);
+SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
+
+/* fts3_snippet.c */
+SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
+SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
+ const char *, const char *, int, int
+);
+SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
+SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
+
+/* fts3_expr.c */
+SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
+ char **, int, int, int, const char *, int, Fts3Expr **, char **
+);
+SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
+#ifdef SQLITE_TEST
+SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash*);
+SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
+#endif
+
+SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
+ sqlite3_tokenizer_cursor **
+);
+
+/* fts3_aux.c */
+SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
+
+SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
+
+SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
+ Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
+SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
+ Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
+SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
+SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
+SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
+
+/* fts3_tokenize_vtab.c */
+SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
+
+/* fts3_unicode2.c (functions generated by parsing unicode text files) */
+#ifndef SQLITE_DISABLE_FTS3_UNICODE
+SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
+SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
+SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
+#endif
+
+#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
+#endif /* _FTSINT_H */
+
+/************** End of fts3Int.h *********************************************/
+/************** Continuing where we left off in fts3.c ***********************/
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
+
+#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
+# define SQLITE_CORE 1
+#endif
+
+/* #include <assert.h> */
+/* #include <stdlib.h> */
+/* #include <stddef.h> */
+/* #include <stdio.h> */
+/* #include <string.h> */
+/* #include <stdarg.h> */
+
+/* #include "fts3.h" */
+#ifndef SQLITE_CORE
+/* # include "sqlite3ext.h" */
+ SQLITE_EXTENSION_INIT1
+#endif
+
+static int fts3EvalNext(Fts3Cursor *pCsr);
+static int fts3EvalStart(Fts3Cursor *pCsr);
+static int fts3TermSegReaderCursor(
+ Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
+
+#ifndef SQLITE_AMALGAMATION
+# if defined(SQLITE_DEBUG)
+SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
+SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
+# endif
+#endif
+
+/*
+** This variable is set to false when running tests for which the on disk
+** structures should not be corrupt. Otherwise, true. If it is false, extra
+** assert() conditions in the fts3 code are activated - conditions that are
+** only true if it is guaranteed that the fts3 database is not corrupt.
+*/
+SQLITE_API int sqlite3_fts3_may_be_corrupt = 1;
+
+/*
+** Write a 64-bit variable-length integer to memory starting at p[0].
+** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
+** The number of bytes written is returned.
+*/
+SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
+ unsigned char *q = (unsigned char *) p;
+ sqlite_uint64 vu = v;
+ do{
+ *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
+ vu >>= 7;
+ }while( vu!=0 );
+ q[-1] &= 0x7f; /* turn off high bit in final byte */
+ assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
+ return (int) (q - (unsigned char *)p);
+}
+
+#define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
+ v = (v & mask1) | ( (*(const unsigned char*)(ptr++)) << shift ); \
+ if( (v & mask2)==0 ){ var = v; return ret; }
+#define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
+ v = (*ptr++); \
+ if( (v & mask2)==0 ){ var = v; return ret; }
+
+SQLITE_PRIVATE int sqlite3Fts3GetVarintU(const char *pBuf, sqlite_uint64 *v){
+ const unsigned char *p = (const unsigned char*)pBuf;
+ const unsigned char *pStart = p;
+ u32 a;
+ u64 b;
+ int shift;
+
+ GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
+ GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
+ GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
+ GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
+ b = (a & 0x0FFFFFFF );
+
+ for(shift=28; shift<=63; shift+=7){
+ u64 c = *p++;
+ b += (c&0x7F) << shift;
+ if( (c & 0x80)==0 ) break;
+ }
+ *v = b;
+ return (int)(p - pStart);
+}
+
+/*
+** Read a 64-bit variable-length integer from memory starting at p[0].
+** Return the number of bytes read, or 0 on error.
+** The value is stored in *v.
+*/
+SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
+ return sqlite3Fts3GetVarintU(pBuf, (sqlite3_uint64*)v);
+}
+
+/*
+** Read a 64-bit variable-length integer from memory starting at p[0] and
+** not extending past pEnd[-1].
+** Return the number of bytes read, or 0 on error.
+** The value is stored in *v.
+*/
+SQLITE_PRIVATE int sqlite3Fts3GetVarintBounded(
+ const char *pBuf,
+ const char *pEnd,
+ sqlite_int64 *v
+){
+ const unsigned char *p = (const unsigned char*)pBuf;
+ const unsigned char *pStart = p;
+ const unsigned char *pX = (const unsigned char*)pEnd;
+ u64 b = 0;
+ int shift;
+ for(shift=0; shift<=63; shift+=7){
+ u64 c = p<pX ? *p : 0;
+ p++;
+ b += (c&0x7F) << shift;
+ if( (c & 0x80)==0 ) break;
+ }
+ *v = b;
+ return (int)(p - pStart);
+}
+
+/*
+** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
+** a non-negative 32-bit integer before it is returned.
+*/
+SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
+ const unsigned char *ptr = (const unsigned char*)p;
+ u32 a;
+
+#ifndef fts3GetVarint32
+ GETVARINT_INIT(a, ptr, 0, 0x00, 0x80, *pi, 1);
+#else
+ a = (*ptr++);
+ assert( a & 0x80 );
+#endif
+
+ GETVARINT_STEP(a, ptr, 7, 0x7F, 0x4000, *pi, 2);
+ GETVARINT_STEP(a, ptr, 14, 0x3FFF, 0x200000, *pi, 3);
+ GETVARINT_STEP(a, ptr, 21, 0x1FFFFF, 0x10000000, *pi, 4);
+ a = (a & 0x0FFFFFFF );
+ *pi = (int)(a | ((u32)(*ptr & 0x07) << 28));
+ assert( 0==(a & 0x80000000) );
+ assert( *pi>=0 );
+ return 5;
+}
+
+/*
+** Return the number of bytes required to encode v as a varint
+*/
+SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
+ int i = 0;
+ do{
+ i++;
+ v >>= 7;
+ }while( v!=0 );
+ return i;
+}
+
+/*
+** Convert an SQL-style quoted string into a normal string by removing
+** the quote characters. The conversion is done in-place. If the
+** input does not begin with a quote character, then this routine
+** is a no-op.
+**
+** Examples:
+**
+** "abc" becomes abc
+** 'xyz' becomes xyz
+** [pqr] becomes pqr
+** `mno` becomes mno
+**
+*/
+SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
+ char quote; /* Quote character (if any ) */
+
+ quote = z[0];
+ if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
+ int iIn = 1; /* Index of next byte to read from input */
+ int iOut = 0; /* Index of next byte to write to output */
+
+ /* If the first byte was a '[', then the close-quote character is a ']' */
+ if( quote=='[' ) quote = ']';
+
+ while( z[iIn] ){
+ if( z[iIn]==quote ){
+ if( z[iIn+1]!=quote ) break;
+ z[iOut++] = quote;
+ iIn += 2;
+ }else{
+ z[iOut++] = z[iIn++];
+ }
+ }
+ z[iOut] = '\0';
+ }
+}
+
+/*
+** Read a single varint from the doclist at *pp and advance *pp to point
+** to the first byte past the end of the varint. Add the value of the varint
+** to *pVal.
+*/
+static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
+ sqlite3_int64 iVal;
+ *pp += sqlite3Fts3GetVarint(*pp, &iVal);
+ *pVal += iVal;
+}
+
+/*
+** When this function is called, *pp points to the first byte following a
+** varint that is part of a doclist (or position-list, or any other list
+** of varints). This function moves *pp to point to the start of that varint,
+** and sets *pVal by the varint value.
+**
+** Argument pStart points to the first byte of the doclist that the
+** varint is part of.
+*/
+static void fts3GetReverseVarint(
+ char **pp,
+ char *pStart,
+ sqlite3_int64 *pVal
+){
+ sqlite3_int64 iVal;
+ char *p;
+
+ /* Pointer p now points at the first byte past the varint we are
+ ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
+ ** clear on character p[-1]. */
+ for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
+ p++;
+ *pp = p;
+
+ sqlite3Fts3GetVarint(p, &iVal);
+ *pVal = iVal;
+}
+
+/*
+** The xDisconnect() virtual table method.
+*/
+static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
+ Fts3Table *p = (Fts3Table *)pVtab;
+ int i;
+
+ assert( p->nPendingData==0 );
+ assert( p->pSegments==0 );
+
+ /* Free any prepared statements held */
+ sqlite3_finalize(p->pSeekStmt);
+ for(i=0; i<SizeofArray(p->aStmt); i++){
+ sqlite3_finalize(p->aStmt[i]);
+ }
+ sqlite3_free(p->zSegmentsTbl);
+ sqlite3_free(p->zReadExprlist);
+ sqlite3_free(p->zWriteExprlist);
+ sqlite3_free(p->zContentTbl);
+ sqlite3_free(p->zLanguageid);
+
+ /* Invoke the tokenizer destructor to free the tokenizer. */
+ p->pTokenizer->pModule->xDestroy(p->pTokenizer);
+
+ sqlite3_free(p);
+ return SQLITE_OK;
+}
+
+/*
+** Write an error message into *pzErr
+*/
+SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
+ va_list ap;
+ sqlite3_free(*pzErr);
+ va_start(ap, zFormat);
+ *pzErr = sqlite3_vmprintf(zFormat, ap);
+ va_end(ap);
+}
+
+/*
+** Construct one or more SQL statements from the format string given
+** and then evaluate those statements. The success code is written
+** into *pRc.
+**
+** If *pRc is initially non-zero then this routine is a no-op.
+*/
+static void fts3DbExec(
+ int *pRc, /* Success code */
+ sqlite3 *db, /* Database in which to run SQL */
+ const char *zFormat, /* Format string for SQL */
+ ... /* Arguments to the format string */
+){
+ va_list ap;
+ char *zSql;
+ if( *pRc ) return;
+ va_start(ap, zFormat);
+ zSql = sqlite3_vmprintf(zFormat, ap);
+ va_end(ap);
+ if( zSql==0 ){
+ *pRc = SQLITE_NOMEM;
+ }else{
+ *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
+ sqlite3_free(zSql);
+ }
+}
+
+/*
+** The xDestroy() virtual table method.
+*/
+static int fts3DestroyMethod(sqlite3_vtab *pVtab){
+ Fts3Table *p = (Fts3Table *)pVtab;
+ int rc = SQLITE_OK; /* Return code */
+ const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
+ sqlite3 *db = p->db; /* Database handle */
+
+ /* Drop the shadow tables */
+ fts3DbExec(&rc, db,
+ "DROP TABLE IF EXISTS %Q.'%q_segments';"
+ "DROP TABLE IF EXISTS %Q.'%q_segdir';"
+ "DROP TABLE IF EXISTS %Q.'%q_docsize';"
+ "DROP TABLE IF EXISTS %Q.'%q_stat';"
+ "%s DROP TABLE IF EXISTS %Q.'%q_content';",
+ zDb, p->zName,
+ zDb, p->zName,
+ zDb, p->zName,
+ zDb, p->zName,
+ (p->zContentTbl ? "--" : ""), zDb,p->zName
+ );
+
+ /* If everything has worked, invoke fts3DisconnectMethod() to free the
+ ** memory associated with the Fts3Table structure and return SQLITE_OK.
+ ** Otherwise, return an SQLite error code.
+ */
+ return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
+}
+
+
+/*
+** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
+** passed as the first argument. This is done as part of the xConnect()
+** and xCreate() methods.
+**
+** If *pRc is non-zero when this function is called, it is a no-op.
+** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
+** before returning.
+*/
+static void fts3DeclareVtab(int *pRc, Fts3Table *p){
+ if( *pRc==SQLITE_OK ){
+ int i; /* Iterator variable */
+ int rc; /* Return code */
+ char *zSql; /* SQL statement passed to declare_vtab() */
+ char *zCols; /* List of user defined columns */
+ const char *zLanguageid;
+
+ zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
+ sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
+
+ /* Create a list of user columns for the virtual table */
+ zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
+ for(i=1; zCols && i<p->nColumn; i++){
+ zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
+ }
+
+ /* Create the whole "CREATE TABLE" statement to pass to SQLite */
+ zSql = sqlite3_mprintf(
+ "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
+ zCols, p->zName, zLanguageid
+ );
+ if( !zCols || !zSql ){
+ rc = SQLITE_NOMEM;
+ }else{
+ rc = sqlite3_declare_vtab(p->db, zSql);
+ }
+
+ sqlite3_free(zSql);
+ sqlite3_free(zCols);
+ *pRc = rc;
+ }
+}
+
+/*
+** Create the %_stat table if it does not already exist.
+*/
+SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
+ fts3DbExec(pRc, p->db,
+ "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
+ "(id INTEGER PRIMARY KEY, value BLOB);",
+ p->zDb, p->zName
+ );
+ if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
+}
+
+/*
+** Create the backing store tables (%_content, %_segments and %_segdir)
+** required by the FTS3 table passed as the only argument. This is done
+** as part of the vtab xCreate() method.
+**
+** If the p->bHasDocsize boolean is true (indicating that this is an
+** FTS4 table, not an FTS3 table) then also create the %_docsize and
+** %_stat tables required by FTS4.
+*/
+static int fts3CreateTables(Fts3Table *p){
+ int rc = SQLITE_OK; /* Return code */
+ int i; /* Iterator variable */
+ sqlite3 *db = p->db; /* The database connection */
+
+ if( p->zContentTbl==0 ){
+ const char *zLanguageid = p->zLanguageid;
+ char *zContentCols; /* Columns of %_content table */
+
+ /* Create a list of user columns for the content table */
+ zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
+ for(i=0; zContentCols && i<p->nColumn; i++){
+ char *z = p->azColumn[i];
+ zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
+ }
+ if( zLanguageid && zContentCols ){
+ zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
+ }
+ if( zContentCols==0 ) rc = SQLITE_NOMEM;
+
+ /* Create the content table */
+ fts3DbExec(&rc, db,
+ "CREATE TABLE %Q.'%q_content'(%s)",
+ p->zDb, p->zName, zContentCols
+ );
+ sqlite3_free(zContentCols);
+ }
+
+ /* Create other tables */
+ fts3DbExec(&rc, db,
+ "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
+ p->zDb, p->zName
+ );
+ fts3DbExec(&rc, db,
+ "CREATE TABLE %Q.'%q_segdir'("
+ "level INTEGER,"
+ "idx INTEGER,"
+ "start_block INTEGER,"
+ "leaves_end_block INTEGER,"
+ "end_block INTEGER,"
+ "root BLOB,"
+ "PRIMARY KEY(level, idx)"
+ ");",
+ p->zDb, p->zName
+ );
+ if( p->bHasDocsize ){
+ fts3DbExec(&rc, db,
+ "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
+ p->zDb, p->zName
+ );
+ }
+ assert( p->bHasStat==p->bFts4 );
+ if( p->bHasStat ){
+ sqlite3Fts3CreateStatTable(&rc, p);
+ }
+ return rc;
+}
+
+/*
+** Store the current database page-size in bytes in p->nPgsz.
+**
+** If *pRc is non-zero when this function is called, it is a no-op.
+** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
+** before returning.
+*/
+static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
+ if( *pRc==SQLITE_OK ){
+ int rc; /* Return code */
+ char *zSql; /* SQL text "PRAGMA %Q.page_size" */
+ sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
+
+ zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
+ if( !zSql ){
+ rc = SQLITE_NOMEM;
+ }else{
+ rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_step(pStmt);
+ p->nPgsz = sqlite3_column_int(pStmt, 0);
+ rc = sqlite3_finalize(pStmt);
+ }else if( rc==SQLITE_AUTH ){
+ p->nPgsz = 1024;
+ rc = SQLITE_OK;
+ }
+ }
+ assert( p->nPgsz>0 || rc!=SQLITE_OK );
+ sqlite3_free(zSql);
+ *pRc = rc;
+ }
+}
+
+/*
+** "Special" FTS4 arguments are column specifications of the following form:
+**
+** <key> = <value>
+**
+** There may not be whitespace surrounding the "=" character. The <value>
+** term may be quoted, but the <key> may not.
+*/
+static int fts3IsSpecialColumn(
+ const char *z,
+ int *pnKey,
+ char **pzValue
+){
+ char *zValue;
+ const char *zCsr = z;
+
+ while( *zCsr!='=' ){
+ if( *zCsr=='\0' ) return 0;
+ zCsr++;
+ }
+
+ *pnKey = (int)(zCsr-z);
+ zValue = sqlite3_mprintf("%s", &zCsr[1]);
+ if( zValue ){
+ sqlite3Fts3Dequote(zValue);
+ }
+ *pzValue = zValue;
+ return 1;
+}
+
+/*
+** Append the output of a printf() style formatting to an existing string.
+*/
+static void fts3Appendf(
+ int *pRc, /* IN/OUT: Error code */
+ char **pz, /* IN/OUT: Pointer to string buffer */
+ const char *zFormat, /* Printf format string to append */
+ ... /* Arguments for printf format string */
+){
+ if( *pRc==SQLITE_OK ){
+ va_list ap;
+ char *z;
+ va_start(ap, zFormat);
+ z = sqlite3_vmprintf(zFormat, ap);
+ va_end(ap);
+ if( z && *pz ){
+ char *z2 = sqlite3_mprintf("%s%s", *pz, z);
+ sqlite3_free(z);
+ z = z2;
+ }
+ if( z==0 ) *pRc = SQLITE_NOMEM;
+ sqlite3_free(*pz);
+ *pz = z;
+ }
+}
+
+/*
+** Return a copy of input string zInput enclosed in double-quotes (") and
+** with all double quote characters escaped. For example:
+**
+** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
+**
+** The pointer returned points to memory obtained from sqlite3_malloc(). It
+** is the callers responsibility to call sqlite3_free() to release this
+** memory.
+*/
+static char *fts3QuoteId(char const *zInput){
+ sqlite3_int64 nRet;
+ char *zRet;
+ nRet = 2 + (int)strlen(zInput)*2 + 1;
+ zRet = sqlite3_malloc64(nRet);
+ if( zRet ){
+ int i;
+ char *z = zRet;
+ *(z++) = '"';
+ for(i=0; zInput[i]; i++){
+ if( zInput[i]=='"' ) *(z++) = '"';
+ *(z++) = zInput[i];
+ }
+ *(z++) = '"';
+ *(z++) = '\0';
+ }
+ return zRet;
+}
+
+/*
+** Return a list of comma separated SQL expressions and a FROM clause that
+** could be used in a SELECT statement such as the following:
+**
+** SELECT <list of expressions> FROM %_content AS x ...
+**
+** to return the docid, followed by each column of text data in order
+** from left to write. If parameter zFunc is not NULL, then instead of
+** being returned directly each column of text data is passed to an SQL
+** function named zFunc first. For example, if zFunc is "unzip" and the
+** table has the three user-defined columns "a", "b", and "c", the following
+** string is returned:
+**
+** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
+**
+** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
+** is the responsibility of the caller to eventually free it.
+**
+** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
+** a NULL pointer is returned). Otherwise, if an OOM error is encountered
+** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
+** no error occurs, *pRc is left unmodified.
+*/
+static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
+ char *zRet = 0;
+ char *zFree = 0;
+ char *zFunction;
+ int i;
+
+ if( p->zContentTbl==0 ){
+ if( !zFunc ){
+ zFunction = "";
+ }else{
+ zFree = zFunction = fts3QuoteId(zFunc);
+ }
+ fts3Appendf(pRc, &zRet, "docid");
+ for(i=0; i<p->nColumn; i++){
+ fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
+ }
+ if( p->zLanguageid ){
+ fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
+ }
+ sqlite3_free(zFree);
+ }else{
+ fts3Appendf(pRc, &zRet, "rowid");
+ for(i=0; i<p->nColumn; i++){
+ fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
+ }
+ if( p->zLanguageid ){
+ fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
+ }
+ }
+ fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
+ p->zDb,
+ (p->zContentTbl ? p->zContentTbl : p->zName),
+ (p->zContentTbl ? "" : "_content")
+ );
+ return zRet;
+}
+
+/*
+** Return a list of N comma separated question marks, where N is the number
+** of columns in the %_content table (one for the docid plus one for each
+** user-defined text column).
+**
+** If argument zFunc is not NULL, then all but the first question mark
+** is preceded by zFunc and an open bracket, and followed by a closed
+** bracket. For example, if zFunc is "zip" and the FTS3 table has three
+** user-defined text columns, the following string is returned:
+**
+** "?, zip(?), zip(?), zip(?)"
+**
+** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
+** is the responsibility of the caller to eventually free it.
+**
+** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
+** a NULL pointer is returned). Otherwise, if an OOM error is encountered
+** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
+** no error occurs, *pRc is left unmodified.
+*/
+static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
+ char *zRet = 0;
+ char *zFree = 0;
+ char *zFunction;
+ int i;
+
+ if( !zFunc ){
+ zFunction = "";
+ }else{
+ zFree = zFunction = fts3QuoteId(zFunc);
+ }
+ fts3Appendf(pRc, &zRet, "?");
+ for(i=0; i<p->nColumn; i++){
+ fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
+ }
+ if( p->zLanguageid ){
+ fts3Appendf(pRc, &zRet, ", ?");
+ }
+ sqlite3_free(zFree);
+ return zRet;
+}
+
+/*
+** Buffer z contains a positive integer value encoded as utf-8 text.
+** Decode this value and store it in *pnOut, returning the number of bytes
+** consumed. If an overflow error occurs return a negative value.
+*/
+SQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut){
+ u64 iVal = 0;
+ int i;
+ for(i=0; z[i]>='0' && z[i]<='9'; i++){
+ iVal = iVal*10 + (z[i] - '0');
+ if( iVal>0x7FFFFFFF ) return -1;
+ }
+ *pnOut = (int)iVal;
+ return i;
+}
+
+/*
+** This function interprets the string at (*pp) as a non-negative integer
+** value. It reads the integer and sets *pnOut to the value read, then
+** sets *pp to point to the byte immediately following the last byte of
+** the integer value.
+**
+** Only decimal digits ('0'..'9') may be part of an integer value.
+**
+** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
+** the output value undefined. Otherwise SQLITE_OK is returned.
+**
+** This function is used when parsing the "prefix=" FTS4 parameter.
+*/
+static int fts3GobbleInt(const char **pp, int *pnOut){
+ const int MAX_NPREFIX = 10000000;
+ int nInt = 0; /* Output value */
+ int nByte;
+ nByte = sqlite3Fts3ReadInt(*pp, &nInt);
+ if( nInt>MAX_NPREFIX ){
+ nInt = 0;
+ }
+ if( nByte==0 ){
+ return SQLITE_ERROR;
+ }
+ *pnOut = nInt;
+ *pp += nByte;
+ return SQLITE_OK;
+}
+
+/*
+** This function is called to allocate an array of Fts3Index structures
+** representing the indexes maintained by the current FTS table. FTS tables
+** always maintain the main "terms" index, but may also maintain one or
+** more "prefix" indexes, depending on the value of the "prefix=" parameter
+** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
+**
+** Argument zParam is passed the value of the "prefix=" option if one was
+** specified, or NULL otherwise.
+**
+** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
+** the allocated array. *pnIndex is set to the number of elements in the
+** array. If an error does occur, an SQLite error code is returned.
+**
+** Regardless of whether or not an error is returned, it is the responsibility
+** of the caller to call sqlite3_free() on the output array to free it.
+*/
+static int fts3PrefixParameter(
+ const char *zParam, /* ABC in prefix=ABC parameter to parse */
+ int *pnIndex, /* OUT: size of *apIndex[] array */
+ struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
+){
+ struct Fts3Index *aIndex; /* Allocated array */
+ int nIndex = 1; /* Number of entries in array */
+
+ if( zParam && zParam[0] ){
+ const char *p;
+ nIndex++;
+ for(p=zParam; *p; p++){
+ if( *p==',' ) nIndex++;
+ }
+ }
+
+ aIndex = sqlite3_malloc64(sizeof(struct Fts3Index) * nIndex);
+ *apIndex = aIndex;
+ if( !aIndex ){
+ return SQLITE_NOMEM;
+ }
+
+ memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
+ if( zParam ){
+ const char *p = zParam;
+ int i;
+ for(i=1; i<nIndex; i++){
+ int nPrefix = 0;
+ if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
+ assert( nPrefix>=0 );
+ if( nPrefix==0 ){
+ nIndex--;
+ i--;
+ }else{
+ aIndex[i].nPrefix = nPrefix;
+ }
+ p++;
+ }
+ }
+
+ *pnIndex = nIndex;
+ return SQLITE_OK;
+}
+
+/*
+** This function is called when initializing an FTS4 table that uses the
+** content=xxx option. It determines the number of and names of the columns
+** of the new FTS4 table.
+**
+** The third argument passed to this function is the value passed to the
+** config=xxx option (i.e. "xxx"). This function queries the database for
+** a table of that name. If found, the output variables are populated
+** as follows:
+**
+** *pnCol: Set to the number of columns table xxx has,
+**
+** *pnStr: Set to the total amount of space required to store a copy
+** of each columns name, including the nul-terminator.
+**
+** *pazCol: Set to point to an array of *pnCol strings. Each string is
+** the name of the corresponding column in table xxx. The array
+** and its contents are allocated using a single allocation. It
+** is the responsibility of the caller to free this allocation
+** by eventually passing the *pazCol value to sqlite3_free().
+**
+** If the table cannot be found, an error code is returned and the output
+** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
+** returned (and the output variables are undefined).
+*/
+static int fts3ContentColumns(
+ sqlite3 *db, /* Database handle */
+ const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
+ const char *zTbl, /* Name of content table */
+ const char ***pazCol, /* OUT: Malloc'd array of column names */
+ int *pnCol, /* OUT: Size of array *pazCol */
+ int *pnStr, /* OUT: Bytes of string content */
+ char **pzErr /* OUT: error message */
+){
+ int rc = SQLITE_OK; /* Return code */
+ char *zSql; /* "SELECT *" statement on zTbl */
+ sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
+
+ zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
+ if( !zSql ){
+ rc = SQLITE_NOMEM;
+ }else{
+ rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
+ if( rc!=SQLITE_OK ){
+ sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
+ }
+ }
+ sqlite3_free(zSql);
+
+ if( rc==SQLITE_OK ){
+ const char **azCol; /* Output array */
+ sqlite3_int64 nStr = 0; /* Size of all column names (incl. 0x00) */
+ int nCol; /* Number of table columns */
+ int i; /* Used to iterate through columns */
+
+ /* Loop through the returned columns. Set nStr to the number of bytes of
+ ** space required to store a copy of each column name, including the
+ ** nul-terminator byte. */
+ nCol = sqlite3_column_count(pStmt);
+ for(i=0; i<nCol; i++){
+ const char *zCol = sqlite3_column_name(pStmt, i);
+ nStr += strlen(zCol) + 1;
+ }
+
+ /* Allocate and populate the array to return. */
+ azCol = (const char **)sqlite3_malloc64(sizeof(char *) * nCol + nStr);
+ if( azCol==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ char *p = (char *)&azCol[nCol];
+ for(i=0; i<nCol; i++){
+ const char *zCol = sqlite3_column_name(pStmt, i);
+ int n = (int)strlen(zCol)+1;
+ memcpy(p, zCol, n);
+ azCol[i] = p;
+ p += n;
+ }
+ }
+ sqlite3_finalize(pStmt);
+
+ /* Set the output variables. */
+ *pnCol = nCol;
+ *pnStr = nStr;
+ *pazCol = azCol;
+ }
+
+ return rc;
+}
+
+/*
+** This function is the implementation of both the xConnect and xCreate
+** methods of the FTS3 virtual table.
+**
+** The argv[] array contains the following:
+**
+** argv[0] -> module name ("fts3" or "fts4")
+** argv[1] -> database name
+** argv[2] -> table name
+** argv[...] -> "column name" and other module argument fields.
+*/
+static int fts3InitVtab(
+ int isCreate, /* True for xCreate, false for xConnect */
+ sqlite3 *db, /* The SQLite database connection */
+ void *pAux, /* Hash table containing tokenizers */
+ int argc, /* Number of elements in argv array */
+ const char * const *argv, /* xCreate/xConnect argument array */
+ sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
+ char **pzErr /* Write any error message here */
+){
+ Fts3Hash *pHash = (Fts3Hash *)pAux;
+ Fts3Table *p = 0; /* Pointer to allocated vtab */
+ int rc = SQLITE_OK; /* Return code */
+ int i; /* Iterator variable */
+ sqlite3_int64 nByte; /* Size of allocation used for *p */
+ int iCol; /* Column index */
+ int nString = 0; /* Bytes required to hold all column names */
+ int nCol = 0; /* Number of columns in the FTS table */
+ char *zCsr; /* Space for holding column names */
+ int nDb; /* Bytes required to hold database name */
+ int nName; /* Bytes required to hold table name */
+ int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
+ const char **aCol; /* Array of column names */
+ sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
+
+ int nIndex = 0; /* Size of aIndex[] array */
+ struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
+
+ /* The results of parsing supported FTS4 key=value options: */
+ int bNoDocsize = 0; /* True to omit %_docsize table */
+ int bDescIdx = 0; /* True to store descending indexes */
+ char *zPrefix = 0; /* Prefix parameter value (or NULL) */
+ char *zCompress = 0; /* compress=? parameter (or NULL) */
+ char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
+ char *zContent = 0; /* content=? parameter (or NULL) */
+ char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
+ char **azNotindexed = 0; /* The set of notindexed= columns */
+ int nNotindexed = 0; /* Size of azNotindexed[] array */
+
+ assert( strlen(argv[0])==4 );
+ assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
+ || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
+ );
+
+ nDb = (int)strlen(argv[1]) + 1;
+ nName = (int)strlen(argv[2]) + 1;
+
+ nByte = sizeof(const char *) * (argc-2);
+ aCol = (const char **)sqlite3_malloc64(nByte);
+ if( aCol ){
+ memset((void*)aCol, 0, nByte);
+ azNotindexed = (char **)sqlite3_malloc64(nByte);
+ }
+ if( azNotindexed ){
+ memset(azNotindexed, 0, nByte);
+ }
+ if( !aCol || !azNotindexed ){
+ rc = SQLITE_NOMEM;
+ goto fts3_init_out;
+ }
+
+ /* Loop through all of the arguments passed by the user to the FTS3/4
+ ** module (i.e. all the column names and special arguments). This loop
+ ** does the following:
+ **
+ ** + Figures out the number of columns the FTSX table will have, and
+ ** the number of bytes of space that must be allocated to store copies
+ ** of the column names.
+ **
+ ** + If there is a tokenizer specification included in the arguments,
+ ** initializes the tokenizer pTokenizer.
+ */
+ for(i=3; rc==SQLITE_OK && i<argc; i++){
+ char const *z = argv[i];
+ int nKey;
+ char *zVal;
+
+ /* Check if this is a tokenizer specification */
+ if( !pTokenizer
+ && strlen(z)>8
+ && 0==sqlite3_strnicmp(z, "tokenize", 8)
+ && 0==sqlite3Fts3IsIdChar(z[8])
+ ){
+ rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
+ }
+
+ /* Check if it is an FTS4 special argument. */
+ else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
+ struct Fts4Option {
+ const char *zOpt;
+ int nOpt;
+ } aFts4Opt[] = {
+ { "matchinfo", 9 }, /* 0 -> MATCHINFO */
+ { "prefix", 6 }, /* 1 -> PREFIX */
+ { "compress", 8 }, /* 2 -> COMPRESS */
+ { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
+ { "order", 5 }, /* 4 -> ORDER */
+ { "content", 7 }, /* 5 -> CONTENT */
+ { "languageid", 10 }, /* 6 -> LANGUAGEID */
+ { "notindexed", 10 } /* 7 -> NOTINDEXED */
+ };
+
+ int iOpt;
+ if( !zVal ){
+ rc = SQLITE_NOMEM;
+ }else{
+ for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
+ struct Fts4Option *pOp = &aFts4Opt[iOpt];
+ if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
+ break;
+ }
+ }
+ switch( iOpt ){
+ case 0: /* MATCHINFO */
+ if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
+ sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
+ rc = SQLITE_ERROR;
+ }
+ bNoDocsize = 1;
+ break;
+
+ case 1: /* PREFIX */
+ sqlite3_free(zPrefix);
+ zPrefix = zVal;
+ zVal = 0;
+ break;
+
+ case 2: /* COMPRESS */
+ sqlite3_free(zCompress);
+ zCompress = zVal;
+ zVal = 0;
+ break;
+
+ case 3: /* UNCOMPRESS */
+ sqlite3_free(zUncompress);
+ zUncompress = zVal;
+ zVal = 0;
+ break;
+
+ case 4: /* ORDER */
+ if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
+ && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
+ ){
+ sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
+ rc = SQLITE_ERROR;
+ }
+ bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
+ break;
+
+ case 5: /* CONTENT */
+ sqlite3_free(zContent);
+ zContent = zVal;
+ zVal = 0;
+ break;
+
+ case 6: /* LANGUAGEID */
+ assert( iOpt==6 );
+ sqlite3_free(zLanguageid);
+ zLanguageid = zVal;
+ zVal = 0;
+ break;
+
+ case 7: /* NOTINDEXED */
+ azNotindexed[nNotindexed++] = zVal;
+ zVal = 0;
+ break;
+
+ default:
+ assert( iOpt==SizeofArray(aFts4Opt) );
+ sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
+ rc = SQLITE_ERROR;
+ break;
+ }
+ sqlite3_free(zVal);
+ }
+ }
+
+ /* Otherwise, the argument is a column name. */
+ else {
+ nString += (int)(strlen(z) + 1);
+ aCol[nCol++] = z;
+ }
+ }
+
+ /* If a content=xxx option was specified, the following:
+ **
+ ** 1. Ignore any compress= and uncompress= options.
+ **
+ ** 2. If no column names were specified as part of the CREATE VIRTUAL
+ ** TABLE statement, use all columns from the content table.
+ */
+ if( rc==SQLITE_OK && zContent ){
+ sqlite3_free(zCompress);
+ sqlite3_free(zUncompress);
+ zCompress = 0;
+ zUncompress = 0;
+ if( nCol==0 ){
+ sqlite3_free((void*)aCol);
+ aCol = 0;
+ rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
+
+ /* If a languageid= option was specified, remove the language id
+ ** column from the aCol[] array. */
+ if( rc==SQLITE_OK && zLanguageid ){
+ int j;
+ for(j=0; j<nCol; j++){
+ if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
+ int k;
+ for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
+ nCol--;
+ break;
+ }
+ }
+ }
+ }
+ }
+ if( rc!=SQLITE_OK ) goto fts3_init_out;
+
+ if( nCol==0 ){
+ assert( nString==0 );
+ aCol[0] = "content";
+ nString = 8;
+ nCol = 1;
+ }
+
+ if( pTokenizer==0 ){
+ rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
+ if( rc!=SQLITE_OK ) goto fts3_init_out;
+ }
+ assert( pTokenizer );
+
+ rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
+ if( rc==SQLITE_ERROR ){
+ assert( zPrefix );
+ sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
+ }
+ if( rc!=SQLITE_OK ) goto fts3_init_out;
+
+ /* Allocate and populate the Fts3Table structure. */
+ nByte = sizeof(Fts3Table) + /* Fts3Table */
+ nCol * sizeof(char *) + /* azColumn */
+ nIndex * sizeof(struct Fts3Index) + /* aIndex */
+ nCol * sizeof(u8) + /* abNotindexed */
+ nName + /* zName */
+ nDb + /* zDb */
+ nString; /* Space for azColumn strings */
+ p = (Fts3Table*)sqlite3_malloc64(nByte);
+ if( p==0 ){
+ rc = SQLITE_NOMEM;
+ goto fts3_init_out;
+ }
+ memset(p, 0, nByte);
+ p->db = db;
+ p->nColumn = nCol;
+ p->nPendingData = 0;
+ p->azColumn = (char **)&p[1];
+ p->pTokenizer = pTokenizer;
+ p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
+ p->bHasDocsize = (isFts4 && bNoDocsize==0);
+ p->bHasStat = (u8)isFts4;
+ p->bFts4 = (u8)isFts4;
+ p->bDescIdx = (u8)bDescIdx;
+ p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
+ p->zContentTbl = zContent;
+ p->zLanguageid = zLanguageid;
+ zContent = 0;
+ zLanguageid = 0;
+ TESTONLY( p->inTransaction = -1 );
+ TESTONLY( p->mxSavepoint = -1 );
+
+ p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
+ memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
+ p->nIndex = nIndex;
+ for(i=0; i<nIndex; i++){
+ fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
+ }
+ p->abNotindexed = (u8 *)&p->aIndex[nIndex];
+
+ /* Fill in the zName and zDb fields of the vtab structure. */
+ zCsr = (char *)&p->abNotindexed[nCol];
+ p->zName = zCsr;
+ memcpy(zCsr, argv[2], nName);
+ zCsr += nName;
+ p->zDb = zCsr;
+ memcpy(zCsr, argv[1], nDb);
+ zCsr += nDb;
+
+ /* Fill in the azColumn array */
+ for(iCol=0; iCol<nCol; iCol++){
+ char *z;
+ int n = 0;
+ z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
+ if( n>0 ){
+ memcpy(zCsr, z, n);
+ }
+ zCsr[n] = '\0';
+ sqlite3Fts3Dequote(zCsr);
+ p->azColumn[iCol] = zCsr;
+ zCsr += n+1;
+ assert( zCsr <= &((char *)p)[nByte] );
+ }
+
+ /* Fill in the abNotindexed array */
+ for(iCol=0; iCol<nCol; iCol++){
+ int n = (int)strlen(p->azColumn[iCol]);
+ for(i=0; i<nNotindexed; i++){
+ char *zNot = azNotindexed[i];
+ if( zNot && n==(int)strlen(zNot)
+ && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
+ ){
+ p->abNotindexed[iCol] = 1;
+ sqlite3_free(zNot);
+ azNotindexed[i] = 0;
+ }
+ }
+ }
+ for(i=0; i<nNotindexed; i++){
+ if( azNotindexed[i] ){
+ sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
+ rc = SQLITE_ERROR;
+ }
+ }
+
+ if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
+ char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
+ rc = SQLITE_ERROR;
+ sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
+ }
+ p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
+ p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
+ if( rc!=SQLITE_OK ) goto fts3_init_out;
+
+ /* If this is an xCreate call, create the underlying tables in the
+ ** database. TODO: For xConnect(), it could verify that said tables exist.
+ */
+ if( isCreate ){
+ rc = fts3CreateTables(p);
+ }
+
+ /* Check to see if a legacy fts3 table has been "upgraded" by the
+ ** addition of a %_stat table so that it can use incremental merge.
+ */
+ if( !isFts4 && !isCreate ){
+ p->bHasStat = 2;
+ }
+
+ /* Figure out the page-size for the database. This is required in order to
+ ** estimate the cost of loading large doclists from the database. */
+ fts3DatabasePageSize(&rc, p);
+ p->nNodeSize = p->nPgsz-35;
+
+#if defined(SQLITE_DEBUG)||defined(SQLITE_TEST)
+ p->nMergeCount = FTS3_MERGE_COUNT;
+#endif
+
+ /* Declare the table schema to SQLite. */
+ fts3DeclareVtab(&rc, p);
+
+fts3_init_out:
+ sqlite3_free(zPrefix);
+ sqlite3_free(aIndex);
+ sqlite3_free(zCompress);
+ sqlite3_free(zUncompress);
+ sqlite3_free(zContent);
+ sqlite3_free(zLanguageid);
+ for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
+ sqlite3_free((void *)aCol);
+ sqlite3_free((void *)azNotindexed);
+ if( rc!=SQLITE_OK ){
+ if( p ){
+ fts3DisconnectMethod((sqlite3_vtab *)p);
+ }else if( pTokenizer ){
+ pTokenizer->pModule->xDestroy(pTokenizer);
+ }
+ }else{
+ assert( p->pSegments==0 );
+ *ppVTab = &p->base;
+ }
+ return rc;
+}
+
+/*
+** The xConnect() and xCreate() methods for the virtual table. All the
+** work is done in function fts3InitVtab().
+*/
+static int fts3ConnectMethod(
+ sqlite3 *db, /* Database connection */
+ void *pAux, /* Pointer to tokenizer hash table */
+ int argc, /* Number of elements in argv array */
+ const char * const *argv, /* xCreate/xConnect argument array */
+ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
+ char **pzErr /* OUT: sqlite3_malloc'd error message */
+){
+ return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
+}
+static int fts3CreateMethod(
+ sqlite3 *db, /* Database connection */
+ void *pAux, /* Pointer to tokenizer hash table */
+ int argc, /* Number of elements in argv array */
+ const char * const *argv, /* xCreate/xConnect argument array */
+ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
+ char **pzErr /* OUT: sqlite3_malloc'd error message */
+){
+ return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
+}
+
+/*
+** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
+** extension is currently being used by a version of SQLite too old to
+** support estimatedRows. In that case this function is a no-op.
+*/
+static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
+#if SQLITE_VERSION_NUMBER>=3008002
+ if( sqlite3_libversion_number()>=3008002 ){
+ pIdxInfo->estimatedRows = nRow;
+ }
+#endif
+}
+
+/*
+** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
+** extension is currently being used by a version of SQLite too old to
+** support index-info flags. In that case this function is a no-op.
+*/
+static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
+#if SQLITE_VERSION_NUMBER>=3008012
+ if( sqlite3_libversion_number()>=3008012 ){
+ pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
+ }
+#endif
+}
+
+/*
+** Implementation of the xBestIndex method for FTS3 tables. There
+** are three possible strategies, in order of preference:
+**
+** 1. Direct lookup by rowid or docid.
+** 2. Full-text search using a MATCH operator on a non-docid column.
+** 3. Linear scan of %_content table.
+*/
+static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
+ Fts3Table *p = (Fts3Table *)pVTab;
+ int i; /* Iterator variable */
+ int iCons = -1; /* Index of constraint to use */
+
+ int iLangidCons = -1; /* Index of langid=x constraint, if present */
+ int iDocidGe = -1; /* Index of docid>=x constraint, if present */
+ int iDocidLe = -1; /* Index of docid<=x constraint, if present */
+ int iIdx;
+
+ if( p->bLock ){
+ return SQLITE_ERROR;
+ }
+
+ /* By default use a full table scan. This is an expensive option,
+ ** so search through the constraints to see if a more efficient
+ ** strategy is possible.
+ */
+ pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
+ pInfo->estimatedCost = 5000000;
+ for(i=0; i<pInfo->nConstraint; i++){
+ int bDocid; /* True if this constraint is on docid */
+ struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
+ if( pCons->usable==0 ){
+ if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
+ /* There exists an unusable MATCH constraint. This means that if
+ ** the planner does elect to use the results of this call as part
+ ** of the overall query plan the user will see an "unable to use
+ ** function MATCH in the requested context" error. To discourage
+ ** this, return a very high cost here. */
+ pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
+ pInfo->estimatedCost = 1e50;
+ fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
+ return SQLITE_OK;
+ }
+ continue;
+ }
+
+ bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
+
+ /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
+ if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
+ pInfo->idxNum = FTS3_DOCID_SEARCH;
+ pInfo->estimatedCost = 1.0;
+ iCons = i;
+ }
+
+ /* A MATCH constraint. Use a full-text search.
+ **
+ ** If there is more than one MATCH constraint available, use the first
+ ** one encountered. If there is both a MATCH constraint and a direct
+ ** rowid/docid lookup, prefer the MATCH strategy. This is done even
+ ** though the rowid/docid lookup is faster than a MATCH query, selecting
+ ** it would lead to an "unable to use function MATCH in the requested
+ ** context" error.
+ */
+ if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
+ && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
+ ){
+ pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
+ pInfo->estimatedCost = 2.0;
+ iCons = i;
+ }
+
+ /* Equality constraint on the langid column */
+ if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
+ && pCons->iColumn==p->nColumn + 2
+ ){
+ iLangidCons = i;
+ }
+
+ if( bDocid ){
+ switch( pCons->op ){
+ case SQLITE_INDEX_CONSTRAINT_GE:
+ case SQLITE_INDEX_CONSTRAINT_GT:
+ iDocidGe = i;
+ break;
+
+ case SQLITE_INDEX_CONSTRAINT_LE:
+ case SQLITE_INDEX_CONSTRAINT_LT:
+ iDocidLe = i;
+ break;
+ }
+ }
+ }
+
+ /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
+ if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
+
+ iIdx = 1;
+ if( iCons>=0 ){
+ pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
+ pInfo->aConstraintUsage[iCons].omit = 1;
+ }
+ if( iLangidCons>=0 ){
+ pInfo->idxNum |= FTS3_HAVE_LANGID;
+ pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
+ }
+ if( iDocidGe>=0 ){
+ pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
+ pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
+ }
+ if( iDocidLe>=0 ){
+ pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
+ pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
+ }
+
+ /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
+ ** docid) order. Both ascending and descending are possible.
+ */
+ if( pInfo->nOrderBy==1 ){
+ struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
+ if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
+ if( pOrder->desc ){
+ pInfo->idxStr = "DESC";
+ }else{
+ pInfo->idxStr = "ASC";
+ }
+ pInfo->orderByConsumed = 1;
+ }
+ }
+
+ assert( p->pSegments==0 );
+ return SQLITE_OK;
+}
+
+/*
+** Implementation of xOpen method.
+*/
+static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
+ sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
+
+ UNUSED_PARAMETER(pVTab);
+
+ /* Allocate a buffer large enough for an Fts3Cursor structure. If the
+ ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
+ ** if the allocation fails, return SQLITE_NOMEM.
+ */
+ *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
+ if( !pCsr ){
+ return SQLITE_NOMEM;
+ }
+ memset(pCsr, 0, sizeof(Fts3Cursor));
+ return SQLITE_OK;
+}
+
+/*
+** Finalize the statement handle at pCsr->pStmt.
+**
+** Or, if that statement handle is one created by fts3CursorSeekStmt(),
+** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
+** pointer there instead of finalizing it.
+*/
+static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
+ if( pCsr->bSeekStmt ){
+ Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
+ if( p->pSeekStmt==0 ){
+ p->pSeekStmt = pCsr->pStmt;
+ sqlite3_reset(pCsr->pStmt);
+ pCsr->pStmt = 0;
+ }
+ pCsr->bSeekStmt = 0;
+ }
+ sqlite3_finalize(pCsr->pStmt);
+}
+
+/*
+** Free all resources currently held by the cursor passed as the only
+** argument.
+*/
+static void fts3ClearCursor(Fts3Cursor *pCsr){
+ fts3CursorFinalizeStmt(pCsr);
+ sqlite3Fts3FreeDeferredTokens(pCsr);
+ sqlite3_free(pCsr->aDoclist);
+ sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
+ sqlite3Fts3ExprFree(pCsr->pExpr);
+ memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
+}
+
+/*
+** Close the cursor. For additional information see the documentation
+** on the xClose method of the virtual table interface.
+*/
+static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
+ Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
+ assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
+ fts3ClearCursor(pCsr);
+ assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
+ sqlite3_free(pCsr);
+ return SQLITE_OK;
+}
+
+/*
+** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
+** compose and prepare an SQL statement of the form:
+**
+** "SELECT <columns> FROM %_content WHERE rowid = ?"
+**
+** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
+** it. If an error occurs, return an SQLite error code.
+*/
+static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
+ int rc = SQLITE_OK;
+ if( pCsr->pStmt==0 ){
+ Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
+ char *zSql;
+ if( p->pSeekStmt ){
+ pCsr->pStmt = p->pSeekStmt;
+ p->pSeekStmt = 0;
+ }else{
+ zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
+ if( !zSql ) return SQLITE_NOMEM;
+ p->bLock++;
+ rc = sqlite3_prepare_v3(
+ p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0
+ );
+ p->bLock--;
+ sqlite3_free(zSql);
+ }
+ if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
+ }
+ return rc;
+}
+
+/*
+** Position the pCsr->pStmt statement so that it is on the row
+** of the %_content table that contains the last match. Return
+** SQLITE_OK on success.
+*/
+static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
+ int rc = SQLITE_OK;
+ if( pCsr->isRequireSeek ){
+ rc = fts3CursorSeekStmt(pCsr);
+ if( rc==SQLITE_OK ){
+ Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab;
+ pTab->bLock++;
+ sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
+ pCsr->isRequireSeek = 0;
+ if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
+ pTab->bLock--;
+ return SQLITE_OK;
+ }else{
+ pTab->bLock--;
+ rc = sqlite3_reset(pCsr->pStmt);
+ if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
+ /* If no row was found and no error has occurred, then the %_content
+ ** table is missing a row that is present in the full-text index.
+ ** The data structures are corrupt. */
+ rc = FTS_CORRUPT_VTAB;
+ pCsr->isEof = 1;
+ }
+ }
+ }
+ }
+
+ if( rc!=SQLITE_OK && pContext ){
+ sqlite3_result_error_code(pContext, rc);
+ }
+ return rc;
+}
+
+/*
+** This function is used to process a single interior node when searching
+** a b-tree for a term or term prefix. The node data is passed to this
+** function via the zNode/nNode parameters. The term to search for is
+** passed in zTerm/nTerm.
+**
+** If piFirst is not NULL, then this function sets *piFirst to the blockid
+** of the child node that heads the sub-tree that may contain the term.
+**
+** If piLast is not NULL, then *piLast is set to the right-most child node
+** that heads a sub-tree that may contain a term for which zTerm/nTerm is
+** a prefix.
+**
+** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
+*/
+static int fts3ScanInteriorNode(
+ const char *zTerm, /* Term to select leaves for */
+ int nTerm, /* Size of term zTerm in bytes */
+ const char *zNode, /* Buffer containing segment interior node */
+ int nNode, /* Size of buffer at zNode */
+ sqlite3_int64 *piFirst, /* OUT: Selected child node */
+ sqlite3_int64 *piLast /* OUT: Selected child node */
+){
+ int rc = SQLITE_OK; /* Return code */
+ const char *zCsr = zNode; /* Cursor to iterate through node */
+ const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
+ char *zBuffer = 0; /* Buffer to load terms into */
+ i64 nAlloc = 0; /* Size of allocated buffer */
+ int isFirstTerm = 1; /* True when processing first term on page */
+ sqlite3_int64 iChild; /* Block id of child node to descend to */
+ int nBuffer = 0; /* Total term size */
+
+ /* Skip over the 'height' varint that occurs at the start of every
+ ** interior node. Then load the blockid of the left-child of the b-tree
+ ** node into variable iChild.
+ **
+ ** Even if the data structure on disk is corrupted, this (reading two
+ ** varints from the buffer) does not risk an overread. If zNode is a
+ ** root node, then the buffer comes from a SELECT statement. SQLite does
+ ** not make this guarantee explicitly, but in practice there are always
+ ** either more than 20 bytes of allocated space following the nNode bytes of
+ ** contents, or two zero bytes. Or, if the node is read from the %_segments
+ ** table, then there are always 20 bytes of zeroed padding following the
+ ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
+ */
+ zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
+ zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
+ if( zCsr>zEnd ){
+ return FTS_CORRUPT_VTAB;
+ }
+
+ while( zCsr<zEnd && (piFirst || piLast) ){
+ int cmp; /* memcmp() result */
+ int nSuffix; /* Size of term suffix */
+ int nPrefix = 0; /* Size of term prefix */
+
+ /* Load the next term on the node into zBuffer. Use realloc() to expand
+ ** the size of zBuffer if required. */
+ if( !isFirstTerm ){
+ zCsr += fts3GetVarint32(zCsr, &nPrefix);
+ if( nPrefix>nBuffer ){
+ rc = FTS_CORRUPT_VTAB;
+ goto finish_scan;
+ }
+ }
+ isFirstTerm = 0;
+ zCsr += fts3GetVarint32(zCsr, &nSuffix);
+
+ assert( nPrefix>=0 && nSuffix>=0 );
+ if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr || nSuffix==0 ){
+ rc = FTS_CORRUPT_VTAB;
+ goto finish_scan;
+ }
+ if( (i64)nPrefix+nSuffix>nAlloc ){
+ char *zNew;
+ nAlloc = ((i64)nPrefix+nSuffix) * 2;
+ zNew = (char *)sqlite3_realloc64(zBuffer, nAlloc);
+ if( !zNew ){
+ rc = SQLITE_NOMEM;
+ goto finish_scan;
+ }
+ zBuffer = zNew;
+ }
+ assert( zBuffer );
+ memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
+ nBuffer = nPrefix + nSuffix;
+ zCsr += nSuffix;
+
+ /* Compare the term we are searching for with the term just loaded from
+ ** the interior node. If the specified term is greater than or equal
+ ** to the term from the interior node, then all terms on the sub-tree
+ ** headed by node iChild are smaller than zTerm. No need to search
+ ** iChild.
+ **
+ ** If the interior node term is larger than the specified term, then
+ ** the tree headed by iChild may contain the specified term.
+ */
+ cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
+ if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
+ *piFirst = iChild;
+ piFirst = 0;
+ }
+
+ if( piLast && cmp<0 ){
+ *piLast = iChild;
+ piLast = 0;
+ }
+
+ iChild++;
+ };
+
+ if( piFirst ) *piFirst = iChild;
+ if( piLast ) *piLast = iChild;
+
+ finish_scan:
+ sqlite3_free(zBuffer);
+ return rc;
+}
+
+
+/*
+** The buffer pointed to by argument zNode (size nNode bytes) contains an
+** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
+** contains a term. This function searches the sub-tree headed by the zNode
+** node for the range of leaf nodes that may contain the specified term
+** or terms for which the specified term is a prefix.
+**
+** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
+** left-most leaf node in the tree that may contain the specified term.
+** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
+** right-most leaf node that may contain a term for which the specified
+** term is a prefix.
+**
+** It is possible that the range of returned leaf nodes does not contain
+** the specified term or any terms for which it is a prefix. However, if the
+** segment does contain any such terms, they are stored within the identified
+** range. Because this function only inspects interior segment nodes (and
+** never loads leaf nodes into memory), it is not possible to be sure.
+**
+** If an error occurs, an error code other than SQLITE_OK is returned.
+*/
+static int fts3SelectLeaf(
+ Fts3Table *p, /* Virtual table handle */
+ const char *zTerm, /* Term to select leaves for */
+ int nTerm, /* Size of term zTerm in bytes */
+ const char *zNode, /* Buffer containing segment interior node */
+ int nNode, /* Size of buffer at zNode */
+ sqlite3_int64 *piLeaf, /* Selected leaf node */
+ sqlite3_int64 *piLeaf2 /* Selected leaf node */
+){
+ int rc = SQLITE_OK; /* Return code */
+ int iHeight; /* Height of this node in tree */
+
+ assert( piLeaf || piLeaf2 );
+
+ fts3GetVarint32(zNode, &iHeight);
+ rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
+ assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
+
+ if( rc==SQLITE_OK && iHeight>1 ){
+ char *zBlob = 0; /* Blob read from %_segments table */
+ int nBlob = 0; /* Size of zBlob in bytes */
+
+ if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
+ rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
+ if( rc==SQLITE_OK ){
+ rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
+ }
+ sqlite3_free(zBlob);
+ piLeaf = 0;
+ zBlob = 0;
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
+ }
+ if( rc==SQLITE_OK ){
+ int iNewHeight = 0;
+ fts3GetVarint32(zBlob, &iNewHeight);
+ if( iNewHeight>=iHeight ){
+ rc = FTS_CORRUPT_VTAB;
+ }else{
+ rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
+ }
+ }
+ sqlite3_free(zBlob);
+ }
+
+ return rc;
+}
+
+/*
+** This function is used to create delta-encoded serialized lists of FTS3
+** varints. Each call to this function appends a single varint to a list.
+*/
+static void fts3PutDeltaVarint(
+ char **pp, /* IN/OUT: Output pointer */
+ sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
+ sqlite3_int64 iVal /* Write this value to the list */
+){
+ assert_fts3_nc( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
+ *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
+ *piPrev = iVal;
+}
+
+/*
+** When this function is called, *ppPoslist is assumed to point to the
+** start of a position-list. After it returns, *ppPoslist points to the
+** first byte after the position-list.
+**
+** A position list is list of positions (delta encoded) and columns for
+** a single document record of a doclist. So, in other words, this
+** routine advances *ppPoslist so that it points to the next docid in
+** the doclist, or to the first byte past the end of the doclist.
+**
+** If pp is not NULL, then the contents of the position list are copied
+** to *pp. *pp is set to point to the first byte past the last byte copied
+** before this function returns.
+*/
+static void fts3PoslistCopy(char **pp, char **ppPoslist){
+ char *pEnd = *ppPoslist;
+ char c = 0;
+
+ /* The end of a position list is marked by a zero encoded as an FTS3
+ ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
+ ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
+ ** of some other, multi-byte, value.
+ **
+ ** The following while-loop moves pEnd to point to the first byte that is not
+ ** immediately preceded by a byte with the 0x80 bit set. Then increments
+ ** pEnd once more so that it points to the byte immediately following the
+ ** last byte in the position-list.
+ */
+ while( *pEnd | c ){
+ c = *pEnd++ & 0x80;
+ testcase( c!=0 && (*pEnd)==0 );
+ }
+ pEnd++; /* Advance past the POS_END terminator byte */
+
+ if( pp ){
+ int n = (int)(pEnd - *ppPoslist);
+ char *p = *pp;
+ memcpy(p, *ppPoslist, n);
+ p += n;
+ *pp = p;
+ }
+ *ppPoslist = pEnd;
+}
+
+/*
+** When this function is called, *ppPoslist is assumed to point to the
+** start of a column-list. After it returns, *ppPoslist points to the
+** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
+**
+** A column-list is list of delta-encoded positions for a single column
+** within a single document within a doclist.
+**
+** The column-list is terminated either by a POS_COLUMN varint (1) or
+** a POS_END varint (0). This routine leaves *ppPoslist pointing to
+** the POS_COLUMN or POS_END that terminates the column-list.
+**
+** If pp is not NULL, then the contents of the column-list are copied
+** to *pp. *pp is set to point to the first byte past the last byte copied
+** before this function returns. The POS_COLUMN or POS_END terminator
+** is not copied into *pp.
+*/
+static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
+ char *pEnd = *ppPoslist;
+ char c = 0;
+
+ /* A column-list is terminated by either a 0x01 or 0x00 byte that is
+ ** not part of a multi-byte varint.
+ */
+ while( 0xFE & (*pEnd | c) ){
+ c = *pEnd++ & 0x80;
+ testcase( c!=0 && ((*pEnd)&0xfe)==0 );
+ }
+ if( pp ){
+ int n = (int)(pEnd - *ppPoslist);
+ char *p = *pp;
+ memcpy(p, *ppPoslist, n);
+ p += n;
+ *pp = p;
+ }
+ *ppPoslist = pEnd;
+}
+
+/*
+** Value used to signify the end of an position-list. This must be
+** as large or larger than any value that might appear on the
+** position-list, even a position list that has been corrupted.
+*/
+#define POSITION_LIST_END LARGEST_INT64
+
+/*
+** This function is used to help parse position-lists. When this function is
+** called, *pp may point to the start of the next varint in the position-list
+** being parsed, or it may point to 1 byte past the end of the position-list
+** (in which case **pp will be a terminator bytes POS_END (0) or
+** (1)).
+**
+** If *pp points past the end of the current position-list, set *pi to
+** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
+** increment the current value of *pi by the value read, and set *pp to
+** point to the next value before returning.
+**
+** Before calling this routine *pi must be initialized to the value of
+** the previous position, or zero if we are reading the first position
+** in the position-list. Because positions are delta-encoded, the value
+** of the previous position is needed in order to compute the value of
+** the next position.
+*/
+static void fts3ReadNextPos(
+ char **pp, /* IN/OUT: Pointer into position-list buffer */
+ sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
+){
+ if( (**pp)&0xFE ){
+ int iVal;
+ *pp += fts3GetVarint32((*pp), &iVal);
+ *pi += iVal;
+ *pi -= 2;
+ }else{
+ *pi = POSITION_LIST_END;
+ }
+}
+
+/*
+** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
+** the value of iCol encoded as a varint to *pp. This will start a new
+** column list.
+**
+** Set *pp to point to the byte just after the last byte written before
+** returning (do not modify it if iCol==0). Return the total number of bytes
+** written (0 if iCol==0).
+*/
+static int fts3PutColNumber(char **pp, int iCol){
+ int n = 0; /* Number of bytes written */
+ if( iCol ){
+ char *p = *pp; /* Output pointer */
+ n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
+ *p = 0x01;
+ *pp = &p[n];
+ }
+ return n;
+}
+
+/*
+** Compute the union of two position lists. The output written
+** into *pp contains all positions of both *pp1 and *pp2 in sorted
+** order and with any duplicates removed. All pointers are
+** updated appropriately. The caller is responsible for insuring
+** that there is enough space in *pp to hold the complete output.
+*/
+static int fts3PoslistMerge(
+ char **pp, /* Output buffer */
+ char **pp1, /* Left input list */
+ char **pp2 /* Right input list */
+){
+ char *p = *pp;
+ char *p1 = *pp1;
+ char *p2 = *pp2;
+
+ while( *p1 || *p2 ){
+ int iCol1; /* The current column index in pp1 */
+ int iCol2; /* The current column index in pp2 */
+
+ if( *p1==POS_COLUMN ){
+ fts3GetVarint32(&p1[1], &iCol1);
+ if( iCol1==0 ) return FTS_CORRUPT_VTAB;
+ }
+ else if( *p1==POS_END ) iCol1 = 0x7fffffff;
+ else iCol1 = 0;
+
+ if( *p2==POS_COLUMN ){
+ fts3GetVarint32(&p2[1], &iCol2);
+ if( iCol2==0 ) return FTS_CORRUPT_VTAB;
+ }
+ else if( *p2==POS_END ) iCol2 = 0x7fffffff;
+ else iCol2 = 0;
+
+ if( iCol1==iCol2 ){
+ sqlite3_int64 i1 = 0; /* Last position from pp1 */
+ sqlite3_int64 i2 = 0; /* Last position from pp2 */
+ sqlite3_int64 iPrev = 0;
+ int n = fts3PutColNumber(&p, iCol1);
+ p1 += n;
+ p2 += n;
+
+ /* At this point, both p1 and p2 point to the start of column-lists
+ ** for the same column (the column with index iCol1 and iCol2).
+ ** A column-list is a list of non-negative delta-encoded varints, each
+ ** incremented by 2 before being stored. Each list is terminated by a
+ ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
+ ** and writes the results to buffer p. p is left pointing to the byte
+ ** after the list written. No terminator (POS_END or POS_COLUMN) is
+ ** written to the output.
+ */
+ fts3GetDeltaVarint(&p1, &i1);
+ fts3GetDeltaVarint(&p2, &i2);
+ if( i1<2 || i2<2 ){
+ break;
+ }
+ do {
+ fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
+ iPrev -= 2;
+ if( i1==i2 ){
+ fts3ReadNextPos(&p1, &i1);
+ fts3ReadNextPos(&p2, &i2);
+ }else if( i1<i2 ){
+ fts3ReadNextPos(&p1, &i1);
+ }else{
+ fts3ReadNextPos(&p2, &i2);
+ }
+ }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
+ }else if( iCol1<iCol2 ){
+ p1 += fts3PutColNumber(&p, iCol1);
+ fts3ColumnlistCopy(&p, &p1);
+ }else{
+ p2 += fts3PutColNumber(&p, iCol2);
+ fts3ColumnlistCopy(&p, &p2);
+ }
+ }
+
+ *p++ = POS_END;
+ *pp = p;
+ *pp1 = p1 + 1;
+ *pp2 = p2 + 1;
+ return SQLITE_OK;
+}
+
+/*
+** This function is used to merge two position lists into one. When it is
+** called, *pp1 and *pp2 must both point to position lists. A position-list is
+** the part of a doclist that follows each document id. For example, if a row
+** contains:
+**
+** 'a b c'|'x y z'|'a b b a'
+**
+** Then the position list for this row for token 'b' would consist of:
+**
+** 0x02 0x01 0x02 0x03 0x03 0x00
+**
+** When this function returns, both *pp1 and *pp2 are left pointing to the
+** byte following the 0x00 terminator of their respective position lists.
+**
+** If isSaveLeft is 0, an entry is added to the output position list for
+** each position in *pp2 for which there exists one or more positions in
+** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
+** when the *pp1 token appears before the *pp2 token, but not more than nToken
+** slots before it.
+**
+** e.g. nToken==1 searches for adjacent positions.
+*/
+static int fts3PoslistPhraseMerge(
+ char **pp, /* IN/OUT: Preallocated output buffer */
+ int nToken, /* Maximum difference in token positions */
+ int isSaveLeft, /* Save the left position */
+ int isExact, /* If *pp1 is exactly nTokens before *pp2 */
+ char **pp1, /* IN/OUT: Left input list */
+ char **pp2 /* IN/OUT: Right input list */
+){
+ char *p = *pp;
+ char *p1 = *pp1;
+ char *p2 = *pp2;
+ int iCol1 = 0;
+ int iCol2 = 0;
+
+ /* Never set both isSaveLeft and isExact for the same invocation. */
+ assert( isSaveLeft==0 || isExact==0 );
+
+ assert_fts3_nc( p!=0 && *p1!=0 && *p2!=0 );
+ if( *p1==POS_COLUMN ){
+ p1++;
+ p1 += fts3GetVarint32(p1, &iCol1);
+ }
+ if( *p2==POS_COLUMN ){
+ p2++;
+ p2 += fts3GetVarint32(p2, &iCol2);
+ }
+
+ while( 1 ){
+ if( iCol1==iCol2 ){
+ char *pSave = p;
+ sqlite3_int64 iPrev = 0;
+ sqlite3_int64 iPos1 = 0;
+ sqlite3_int64 iPos2 = 0;
+
+ if( iCol1 ){
+ *p++ = POS_COLUMN;
+ p += sqlite3Fts3PutVarint(p, iCol1);
+ }
+
+ fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
+ fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
+ if( iPos1<0 || iPos2<0 ) break;
+
+ while( 1 ){
+ if( iPos2==iPos1+nToken
+ || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
+ ){
+ sqlite3_int64 iSave;
+ iSave = isSaveLeft ? iPos1 : iPos2;
+ fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
+ pSave = 0;
+ assert( p );
+ }
+ if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
+ if( (*p2&0xFE)==0 ) break;
+ fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
+ }else{
+ if( (*p1&0xFE)==0 ) break;
+ fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
+ }
+ }
+
+ if( pSave ){
+ assert( pp && p );
+ p = pSave;
+ }
+
+ fts3ColumnlistCopy(0, &p1);
+ fts3ColumnlistCopy(0, &p2);
+ assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
+ if( 0==*p1 || 0==*p2 ) break;
+
+ p1++;
+ p1 += fts3GetVarint32(p1, &iCol1);
+ p2++;
+ p2 += fts3GetVarint32(p2, &iCol2);
+ }
+
+ /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
+ ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
+ ** end of the position list, or the 0x01 that precedes the next
+ ** column-number in the position list.
+ */
+ else if( iCol1<iCol2 ){
+ fts3ColumnlistCopy(0, &p1);
+ if( 0==*p1 ) break;
+ p1++;
+ p1 += fts3GetVarint32(p1, &iCol1);
+ }else{
+ fts3ColumnlistCopy(0, &p2);
+ if( 0==*p2 ) break;
+ p2++;
+ p2 += fts3GetVarint32(p2, &iCol2);
+ }
+ }
+
+ fts3PoslistCopy(0, &p2);
+ fts3PoslistCopy(0, &p1);
+ *pp1 = p1;
+ *pp2 = p2;
+ if( *pp==p ){
+ return 0;
+ }
+ *p++ = 0x00;
+ *pp = p;
+ return 1;
+}
+
+/*
+** Merge two position-lists as required by the NEAR operator. The argument
+** position lists correspond to the left and right phrases of an expression
+** like:
+**
+** "phrase 1" NEAR "phrase number 2"
+**
+** Position list *pp1 corresponds to the left-hand side of the NEAR
+** expression and *pp2 to the right. As usual, the indexes in the position
+** lists are the offsets of the last token in each phrase (tokens "1" and "2"
+** in the example above).
+**
+** The output position list - written to *pp - is a copy of *pp2 with those
+** entries that are not sufficiently NEAR entries in *pp1 removed.
+*/
+static int fts3PoslistNearMerge(
+ char **pp, /* Output buffer */
+ char *aTmp, /* Temporary buffer space */
+ int nRight, /* Maximum difference in token positions */
+ int nLeft, /* Maximum difference in token positions */
+ char **pp1, /* IN/OUT: Left input list */
+ char **pp2 /* IN/OUT: Right input list */
+){
+ char *p1 = *pp1;
+ char *p2 = *pp2;
+
+ char *pTmp1 = aTmp;
+ char *pTmp2;
+ char *aTmp2;
+ int res = 1;
+
+ fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
+ aTmp2 = pTmp2 = pTmp1;
+ *pp1 = p1;
+ *pp2 = p2;
+ fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
+ if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
+ fts3PoslistMerge(pp, &aTmp, &aTmp2);
+ }else if( pTmp1!=aTmp ){
+ fts3PoslistCopy(pp, &aTmp);
+ }else if( pTmp2!=aTmp2 ){
+ fts3PoslistCopy(pp, &aTmp2);
+ }else{
+ res = 0;
+ }
+
+ return res;
+}
+
+/*
+** An instance of this function is used to merge together the (potentially
+** large number of) doclists for each term that matches a prefix query.
+** See function fts3TermSelectMerge() for details.
+*/
+typedef struct TermSelect TermSelect;
+struct TermSelect {
+ char *aaOutput[16]; /* Malloc'd output buffers */
+ int anOutput[16]; /* Size each output buffer in bytes */
+};
+
+/*
+** This function is used to read a single varint from a buffer. Parameter
+** pEnd points 1 byte past the end of the buffer. When this function is
+** called, if *pp points to pEnd or greater, then the end of the buffer
+** has been reached. In this case *pp is set to 0 and the function returns.
+**
+** If *pp does not point to or past pEnd, then a single varint is read
+** from *pp. *pp is then set to point 1 byte past the end of the read varint.
+**
+** If bDescIdx is false, the value read is added to *pVal before returning.
+** If it is true, the value read is subtracted from *pVal before this
+** function returns.
+*/
+static void fts3GetDeltaVarint3(
+ char **pp, /* IN/OUT: Point to read varint from */
+ char *pEnd, /* End of buffer */
+ int bDescIdx, /* True if docids are descending */
+ sqlite3_int64 *pVal /* IN/OUT: Integer value */
+){
+ if( *pp>=pEnd ){
+ *pp = 0;
+ }else{
+ u64 iVal;
+ *pp += sqlite3Fts3GetVarintU(*pp, &iVal);
+ if( bDescIdx ){
+ *pVal = (i64)((u64)*pVal - iVal);
+ }else{
+ *pVal = (i64)((u64)*pVal + iVal);
+ }
+ }
+}
+
+/*
+** This function is used to write a single varint to a buffer. The varint
+** is written to *pp. Before returning, *pp is set to point 1 byte past the
+** end of the value written.
+**
+** If *pbFirst is zero when this function is called, the value written to
+** the buffer is that of parameter iVal.
+**
+** If *pbFirst is non-zero when this function is called, then the value
+** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
+** (if bDescIdx is non-zero).
+**
+** Before returning, this function always sets *pbFirst to 1 and *piPrev
+** to the value of parameter iVal.
+*/
+static void fts3PutDeltaVarint3(
+ char **pp, /* IN/OUT: Output pointer */
+ int bDescIdx, /* True for descending docids */
+ sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
+ int *pbFirst, /* IN/OUT: True after first int written */
+ sqlite3_int64 iVal /* Write this value to the list */
+){
+ sqlite3_uint64 iWrite;
+ if( bDescIdx==0 || *pbFirst==0 ){
+ assert_fts3_nc( *pbFirst==0 || iVal>=*piPrev );
+ iWrite = (u64)iVal - (u64)*piPrev;
+ }else{
+ assert_fts3_nc( *piPrev>=iVal );
+ iWrite = (u64)*piPrev - (u64)iVal;
+ }
+ assert( *pbFirst || *piPrev==0 );
+ assert_fts3_nc( *pbFirst==0 || iWrite>0 );
+ *pp += sqlite3Fts3PutVarint(*pp, iWrite);
+ *piPrev = iVal;
+ *pbFirst = 1;
+}
+
+
+/*
+** This macro is used by various functions that merge doclists. The two
+** arguments are 64-bit docid values. If the value of the stack variable
+** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
+** Otherwise, (i2-i1).
+**
+** Using this makes it easier to write code that can merge doclists that are
+** sorted in either ascending or descending order.
+*/
+/* #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i64)((u64)i1-i2)) */
+#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1>i2?1:((i1==i2)?0:-1)))
+
+/*
+** This function does an "OR" merge of two doclists (output contains all
+** positions contained in either argument doclist). If the docids in the
+** input doclists are sorted in ascending order, parameter bDescDoclist
+** should be false. If they are sorted in ascending order, it should be
+** passed a non-zero value.
+**
+** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
+** containing the output doclist and SQLITE_OK is returned. In this case
+** *pnOut is set to the number of bytes in the output doclist.
+**
+** If an error occurs, an SQLite error code is returned. The output values
+** are undefined in this case.
+*/
+static int fts3DoclistOrMerge(
+ int bDescDoclist, /* True if arguments are desc */
+ char *a1, int n1, /* First doclist */
+ char *a2, int n2, /* Second doclist */
+ char **paOut, int *pnOut /* OUT: Malloc'd doclist */
+){
+ int rc = SQLITE_OK;
+ sqlite3_int64 i1 = 0;
+ sqlite3_int64 i2 = 0;
+ sqlite3_int64 iPrev = 0;
+ char *pEnd1 = &a1[n1];
+ char *pEnd2 = &a2[n2];
+ char *p1 = a1;
+ char *p2 = a2;
+ char *p;
+ char *aOut;
+ int bFirstOut = 0;
+
+ *paOut = 0;
+ *pnOut = 0;
+
+ /* Allocate space for the output. Both the input and output doclists
+ ** are delta encoded. If they are in ascending order (bDescDoclist==0),
+ ** then the first docid in each list is simply encoded as a varint. For
+ ** each subsequent docid, the varint stored is the difference between the
+ ** current and previous docid (a positive number - since the list is in
+ ** ascending order).
+ **
+ ** The first docid written to the output is therefore encoded using the
+ ** same number of bytes as it is in whichever of the input lists it is
+ ** read from. And each subsequent docid read from the same input list
+ ** consumes either the same or less bytes as it did in the input (since
+ ** the difference between it and the previous value in the output must
+ ** be a positive value less than or equal to the delta value read from
+ ** the input list). The same argument applies to all but the first docid
+ ** read from the 'other' list. And to the contents of all position lists
+ ** that will be copied and merged from the input to the output.
+ **
+ ** However, if the first docid copied to the output is a negative number,
+ ** then the encoding of the first docid from the 'other' input list may
+ ** be larger in the output than it was in the input (since the delta value
+ ** may be a larger positive integer than the actual docid).
+ **
+ ** The space required to store the output is therefore the sum of the
+ ** sizes of the two inputs, plus enough space for exactly one of the input
+ ** docids to grow.
+ **
+ ** A symetric argument may be made if the doclists are in descending
+ ** order.
+ */
+ aOut = sqlite3_malloc64((i64)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING);
+ if( !aOut ) return SQLITE_NOMEM;
+
+ p = aOut;
+ fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
+ fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
+ while( p1 || p2 ){
+ sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
+
+ if( p2 && p1 && iDiff==0 ){
+ fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
+ rc = fts3PoslistMerge(&p, &p1, &p2);
+ if( rc ) break;
+ fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
+ fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
+ }else if( !p2 || (p1 && iDiff<0) ){
+ fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
+ fts3PoslistCopy(&p, &p1);
+ fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
+ }else{
+ fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
+ fts3PoslistCopy(&p, &p2);
+ fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
+ }
+
+ assert( (p-aOut)<=((p1?(p1-a1):n1)+(p2?(p2-a2):n2)+FTS3_VARINT_MAX-1) );
+ }
+
+ if( rc!=SQLITE_OK ){
+ sqlite3_free(aOut);
+ p = aOut = 0;
+ }else{
+ assert( (p-aOut)<=n1+n2+FTS3_VARINT_MAX-1 );
+ memset(&aOut[(p-aOut)], 0, FTS3_BUFFER_PADDING);
+ }
+ *paOut = aOut;
+ *pnOut = (int)(p-aOut);
+ return rc;
+}
+
+/*
+** This function does a "phrase" merge of two doclists. In a phrase merge,
+** the output contains a copy of each position from the right-hand input
+** doclist for which there is a position in the left-hand input doclist
+** exactly nDist tokens before it.
+**
+** If the docids in the input doclists are sorted in ascending order,
+** parameter bDescDoclist should be false. If they are sorted in ascending
+** order, it should be passed a non-zero value.
+**
+** The right-hand input doclist is overwritten by this function.
+*/
+static int fts3DoclistPhraseMerge(
+ int bDescDoclist, /* True if arguments are desc */
+ int nDist, /* Distance from left to right (1=adjacent) */
+ char *aLeft, int nLeft, /* Left doclist */
+ char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
+){
+ sqlite3_int64 i1 = 0;
+ sqlite3_int64 i2 = 0;
+ sqlite3_int64 iPrev = 0;
+ char *aRight = *paRight;
+ char *pEnd1 = &aLeft[nLeft];
+ char *pEnd2 = &aRight[*pnRight];
+ char *p1 = aLeft;
+ char *p2 = aRight;
+ char *p;
+ int bFirstOut = 0;
+ char *aOut;
+
+ assert( nDist>0 );
+ if( bDescDoclist ){
+ aOut = sqlite3_malloc64((sqlite3_int64)*pnRight + FTS3_VARINT_MAX);
+ if( aOut==0 ) return SQLITE_NOMEM;
+ }else{
+ aOut = aRight;
+ }
+ p = aOut;
+
+ fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
+ fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
+
+ while( p1 && p2 ){
+ sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
+ if( iDiff==0 ){
+ char *pSave = p;
+ sqlite3_int64 iPrevSave = iPrev;
+ int bFirstOutSave = bFirstOut;
+
+ fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
+ if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
+ p = pSave;
+ iPrev = iPrevSave;
+ bFirstOut = bFirstOutSave;
+ }
+ fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
+ fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
+ }else if( iDiff<0 ){
+ fts3PoslistCopy(0, &p1);
+ fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
+ }else{
+ fts3PoslistCopy(0, &p2);
+ fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
+ }
+ }
+
+ *pnRight = (int)(p - aOut);
+ if( bDescDoclist ){
+ sqlite3_free(aRight);
+ *paRight = aOut;
+ }
+
+ return SQLITE_OK;
+}
+
+/*
+** Argument pList points to a position list nList bytes in size. This
+** function checks to see if the position list contains any entries for
+** a token in position 0 (of any column). If so, it writes argument iDelta
+** to the output buffer pOut, followed by a position list consisting only
+** of the entries from pList at position 0, and terminated by an 0x00 byte.
+** The value returned is the number of bytes written to pOut (if any).
+*/
+SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
+ sqlite3_int64 iDelta, /* Varint that may be written to pOut */
+ char *pList, /* Position list (no 0x00 term) */
+ int nList, /* Size of pList in bytes */
+ char *pOut /* Write output here */
+){
+ int nOut = 0;
+ int bWritten = 0; /* True once iDelta has been written */
+ char *p = pList;
+ char *pEnd = &pList[nList];
+
+ if( *p!=0x01 ){
+ if( *p==0x02 ){
+ nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
+ pOut[nOut++] = 0x02;
+ bWritten = 1;
+ }
+ fts3ColumnlistCopy(0, &p);
+ }
+
+ while( p<pEnd ){
+ sqlite3_int64 iCol;
+ p++;
+ p += sqlite3Fts3GetVarint(p, &iCol);
+ if( *p==0x02 ){
+ if( bWritten==0 ){
+ nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
+ bWritten = 1;
+ }
+ pOut[nOut++] = 0x01;
+ nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
+ pOut[nOut++] = 0x02;
+ }
+ fts3ColumnlistCopy(0, &p);
+ }
+ if( bWritten ){
+ pOut[nOut++] = 0x00;
+ }
+
+ return nOut;
+}
+
+
+/*
+** Merge all doclists in the TermSelect.aaOutput[] array into a single
+** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
+** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
+**
+** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
+** the responsibility of the caller to free any doclists left in the
+** TermSelect.aaOutput[] array.
+*/
+static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
+ char *aOut = 0;
+ int nOut = 0;
+ int i;
+
+ /* Loop through the doclists in the aaOutput[] array. Merge them all
+ ** into a single doclist.
+ */
+ for(i=0; i<SizeofArray(pTS->aaOutput); i++){
+ if( pTS->aaOutput[i] ){
+ if( !aOut ){
+ aOut = pTS->aaOutput[i];
+ nOut = pTS->anOutput[i];
+ pTS->aaOutput[i] = 0;
+ }else{
+ int nNew;
+ char *aNew;
+
+ int rc = fts3DoclistOrMerge(p->bDescIdx,
+ pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
+ );
+ if( rc!=SQLITE_OK ){
+ sqlite3_free(aOut);
+ return rc;
+ }
+
+ sqlite3_free(pTS->aaOutput[i]);
+ sqlite3_free(aOut);
+ pTS->aaOutput[i] = 0;
+ aOut = aNew;
+ nOut = nNew;
+ }
+ }
+ }
+
+ pTS->aaOutput[0] = aOut;
+ pTS->anOutput[0] = nOut;
+ return SQLITE_OK;
+}
+
+/*
+** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
+** as the first argument. The merge is an "OR" merge (see function
+** fts3DoclistOrMerge() for details).
+**
+** This function is called with the doclist for each term that matches
+** a queried prefix. It merges all these doclists into one, the doclist
+** for the specified prefix. Since there can be a very large number of
+** doclists to merge, the merging is done pair-wise using the TermSelect
+** object.
+**
+** This function returns SQLITE_OK if the merge is successful, or an
+** SQLite error code (SQLITE_NOMEM) if an error occurs.
+*/
+static int fts3TermSelectMerge(
+ Fts3Table *p, /* FTS table handle */
+ TermSelect *pTS, /* TermSelect object to merge into */
+ char *aDoclist, /* Pointer to doclist */
+ int nDoclist /* Size of aDoclist in bytes */
+){
+ if( pTS->aaOutput[0]==0 ){
+ /* If this is the first term selected, copy the doclist to the output
+ ** buffer using memcpy().
+ **
+ ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
+ ** allocation. This is so as to ensure that the buffer is big enough
+ ** to hold the current doclist AND'd with any other doclist. If the
+ ** doclists are stored in order=ASC order, this padding would not be
+ ** required (since the size of [doclistA AND doclistB] is always less
+ ** than or equal to the size of [doclistA] in that case). But this is
+ ** not true for order=DESC. For example, a doclist containing (1, -1)
+ ** may be smaller than (-1), as in the first example the -1 may be stored
+ ** as a single-byte delta, whereas in the second it must be stored as a
+ ** FTS3_VARINT_MAX byte varint.
+ **
+ ** Similar padding is added in the fts3DoclistOrMerge() function.
+ */
+ pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
+ pTS->anOutput[0] = nDoclist;
+ if( pTS->aaOutput[0] ){
+ memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
+ memset(&pTS->aaOutput[0][nDoclist], 0, FTS3_VARINT_MAX);
+ }else{
+ return SQLITE_NOMEM;
+ }
+ }else{
+ char *aMerge = aDoclist;
+ int nMerge = nDoclist;
+ int iOut;
+
+ for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
+ if( pTS->aaOutput[iOut]==0 ){
+ assert( iOut>0 );
+ pTS->aaOutput[iOut] = aMerge;
+ pTS->anOutput[iOut] = nMerge;
+ break;
+ }else{
+ char *aNew;
+ int nNew;
+
+ int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
+ pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
+ );
+ if( rc!=SQLITE_OK ){
+ if( aMerge!=aDoclist ) sqlite3_free(aMerge);
+ return rc;
+ }
+
+ if( aMerge!=aDoclist ) sqlite3_free(aMerge);
+ sqlite3_free(pTS->aaOutput[iOut]);
+ pTS->aaOutput[iOut] = 0;
+
+ aMerge = aNew;
+ nMerge = nNew;
+ if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
+ pTS->aaOutput[iOut] = aMerge;
+ pTS->anOutput[iOut] = nMerge;
+ }
+ }
+ }
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
+*/
+static int fts3SegReaderCursorAppend(
+ Fts3MultiSegReader *pCsr,
+ Fts3SegReader *pNew
+){
+ if( (pCsr->nSegment%16)==0 ){
+ Fts3SegReader **apNew;
+ sqlite3_int64 nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
+ apNew = (Fts3SegReader **)sqlite3_realloc64(pCsr->apSegment, nByte);
+ if( !apNew ){
+ sqlite3Fts3SegReaderFree(pNew);
+ return SQLITE_NOMEM;
+ }
+ pCsr->apSegment = apNew;
+ }
+ pCsr->apSegment[pCsr->nSegment++] = pNew;
+ return SQLITE_OK;
+}
+
+/*
+** Add seg-reader objects to the Fts3MultiSegReader object passed as the
+** 8th argument.
+**
+** This function returns SQLITE_OK if successful, or an SQLite error code
+** otherwise.
+*/
+static int fts3SegReaderCursor(
+ Fts3Table *p, /* FTS3 table handle */
+ int iLangid, /* Language id */
+ int iIndex, /* Index to search (from 0 to p->nIndex-1) */
+ int iLevel, /* Level of segments to scan */
+ const char *zTerm, /* Term to query for */
+ int nTerm, /* Size of zTerm in bytes */
+ int isPrefix, /* True for a prefix search */
+ int isScan, /* True to scan from zTerm to EOF */
+ Fts3MultiSegReader *pCsr /* Cursor object to populate */
+){
+ int rc = SQLITE_OK; /* Error code */
+ sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
+ int rc2; /* Result of sqlite3_reset() */
+
+ /* If iLevel is less than 0 and this is not a scan, include a seg-reader
+ ** for the pending-terms. If this is a scan, then this call must be being
+ ** made by an fts4aux module, not an FTS table. In this case calling
+ ** Fts3SegReaderPending might segfault, as the data structures used by
+ ** fts4aux are not completely populated. So it's easiest to filter these
+ ** calls out here. */
+ if( iLevel<0 && p->aIndex && p->iPrevLangid==iLangid ){
+ Fts3SegReader *pSeg = 0;
+ rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
+ if( rc==SQLITE_OK && pSeg ){
+ rc = fts3SegReaderCursorAppend(pCsr, pSeg);
+ }
+ }
+
+ if( iLevel!=FTS3_SEGCURSOR_PENDING ){
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
+ }
+
+ while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
+ Fts3SegReader *pSeg = 0;
+
+ /* Read the values returned by the SELECT into local variables. */
+ sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
+ sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
+ sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
+ int nRoot = sqlite3_column_bytes(pStmt, 4);
+ char const *zRoot = sqlite3_column_blob(pStmt, 4);
+
+ /* If zTerm is not NULL, and this segment is not stored entirely on its
+ ** root node, the range of leaves scanned can be reduced. Do this. */
+ if( iStartBlock && zTerm && zRoot ){
+ sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
+ rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
+ if( rc!=SQLITE_OK ) goto finished;
+ if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
+ }
+
+ rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
+ (isPrefix==0 && isScan==0),
+ iStartBlock, iLeavesEndBlock,
+ iEndBlock, zRoot, nRoot, &pSeg
+ );
+ if( rc!=SQLITE_OK ) goto finished;
+ rc = fts3SegReaderCursorAppend(pCsr, pSeg);
+ }
+ }
+
+ finished:
+ rc2 = sqlite3_reset(pStmt);
+ if( rc==SQLITE_DONE ) rc = rc2;
+
+ return rc;
+}
+
+/*
+** Set up a cursor object for iterating through a full-text index or a
+** single level therein.
+*/
+SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
+ Fts3Table *p, /* FTS3 table handle */
+ int iLangid, /* Language-id to search */
+ int iIndex, /* Index to search (from 0 to p->nIndex-1) */
+ int iLevel, /* Level of segments to scan */
+ const char *zTerm, /* Term to query for */
+ int nTerm, /* Size of zTerm in bytes */
+ int isPrefix, /* True for a prefix search */
+ int isScan, /* True to scan from zTerm to EOF */
+ Fts3MultiSegReader *pCsr /* Cursor object to populate */
+){
+ assert( iIndex>=0 && iIndex<p->nIndex );
+ assert( iLevel==FTS3_SEGCURSOR_ALL
+ || iLevel==FTS3_SEGCURSOR_PENDING
+ || iLevel>=0
+ );
+ assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
+ assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
+ assert( isPrefix==0 || isScan==0 );
+
+ memset(pCsr, 0, sizeof(Fts3MultiSegReader));
+ return fts3SegReaderCursor(
+ p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
+ );
+}
+
+/*
+** In addition to its current configuration, have the Fts3MultiSegReader
+** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
+**
+** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
+*/
+static int fts3SegReaderCursorAddZero(
+ Fts3Table *p, /* FTS virtual table handle */
+ int iLangid,
+ const char *zTerm, /* Term to scan doclist of */
+ int nTerm, /* Number of bytes in zTerm */
+ Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
+){
+ return fts3SegReaderCursor(p,
+ iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
+ );
+}
+
+/*
+** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
+** if isPrefix is true, to scan the doclist for all terms for which
+** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
+** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
+** an SQLite error code.
+**
+** It is the responsibility of the caller to free this object by eventually
+** passing it to fts3SegReaderCursorFree()
+**
+** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
+** Output parameter *ppSegcsr is set to 0 if an error occurs.
+*/
+static int fts3TermSegReaderCursor(
+ Fts3Cursor *pCsr, /* Virtual table cursor handle */
+ const char *zTerm, /* Term to query for */
+ int nTerm, /* Size of zTerm in bytes */
+ int isPrefix, /* True for a prefix search */
+ Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
+){
+ Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
+ int rc = SQLITE_NOMEM; /* Return code */
+
+ pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
+ if( pSegcsr ){
+ int i;
+ int bFound = 0; /* True once an index has been found */
+ Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
+
+ if( isPrefix ){
+ for(i=1; bFound==0 && i<p->nIndex; i++){
+ if( p->aIndex[i].nPrefix==nTerm ){
+ bFound = 1;
+ rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
+ i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
+ );
+ pSegcsr->bLookup = 1;
+ }
+ }
+
+ for(i=1; bFound==0 && i<p->nIndex; i++){
+ if( p->aIndex[i].nPrefix==nTerm+1 ){
+ bFound = 1;
+ rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
+ i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
+ );
+ if( rc==SQLITE_OK ){
+ rc = fts3SegReaderCursorAddZero(
+ p, pCsr->iLangid, zTerm, nTerm, pSegcsr
+ );
+ }
+ }
+ }
+ }
+
+ if( bFound==0 ){
+ rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
+ 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
+ );
+ pSegcsr->bLookup = !isPrefix;
+ }
+ }
+
+ *ppSegcsr = pSegcsr;
+ return rc;
+}
+
+/*
+** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
+*/
+static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
+ sqlite3Fts3SegReaderFinish(pSegcsr);
+ sqlite3_free(pSegcsr);
+}
+
+/*
+** This function retrieves the doclist for the specified term (or term
+** prefix) from the database.
+*/
+static int fts3TermSelect(
+ Fts3Table *p, /* Virtual table handle */
+ Fts3PhraseToken *pTok, /* Token to query for */
+ int iColumn, /* Column to query (or -ve for all columns) */
+ int *pnOut, /* OUT: Size of buffer at *ppOut */
+ char **ppOut /* OUT: Malloced result buffer */
+){
+ int rc; /* Return code */
+ Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
+ TermSelect tsc; /* Object for pair-wise doclist merging */
+ Fts3SegFilter filter; /* Segment term filter configuration */
+
+ pSegcsr = pTok->pSegcsr;
+ memset(&tsc, 0, sizeof(TermSelect));
+
+ filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
+ | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
+ | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
+ | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
+ filter.iCol = iColumn;
+ filter.zTerm = pTok->z;
+ filter.nTerm = pTok->n;
+
+ rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
+ while( SQLITE_OK==rc
+ && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
+ ){
+ rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = fts3TermSelectFinishMerge(p, &tsc);
+ }
+ if( rc==SQLITE_OK ){
+ *ppOut = tsc.aaOutput[0];
+ *pnOut = tsc.anOutput[0];
+ }else{
+ int i;
+ for(i=0; i<SizeofArray(tsc.aaOutput); i++){
+ sqlite3_free(tsc.aaOutput[i]);
+ }
+ }
+
+ fts3SegReaderCursorFree(pSegcsr);
+ pTok->pSegcsr = 0;
+ return rc;
+}
+
+/*
+** This function counts the total number of docids in the doclist stored
+** in buffer aList[], size nList bytes.
+**
+** If the isPoslist argument is true, then it is assumed that the doclist
+** contains a position-list following each docid. Otherwise, it is assumed
+** that the doclist is simply a list of docids stored as delta encoded
+** varints.
+*/
+static int fts3DoclistCountDocids(char *aList, int nList){
+ int nDoc = 0; /* Return value */
+ if( aList ){
+ char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
+ char *p = aList; /* Cursor */
+ while( p<aEnd ){
+ nDoc++;
+ while( (*p++)&0x80 ); /* Skip docid varint */
+ fts3PoslistCopy(0, &p); /* Skip over position list */
+ }
+ }
+
+ return nDoc;
+}
+
+/*
+** Advance the cursor to the next row in the %_content table that
+** matches the search criteria. For a MATCH search, this will be
+** the next row that matches. For a full-table scan, this will be
+** simply the next row in the %_content table. For a docid lookup,
+** this routine simply sets the EOF flag.
+**
+** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
+** even if we reach end-of-file. The fts3EofMethod() will be called
+** subsequently to determine whether or not an EOF was hit.
+*/
+static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
+ int rc;
+ Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
+ if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
+ Fts3Table *pTab = (Fts3Table*)pCursor->pVtab;
+ pTab->bLock++;
+ if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
+ pCsr->isEof = 1;
+ rc = sqlite3_reset(pCsr->pStmt);
+ }else{
+ pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
+ rc = SQLITE_OK;
+ }
+ pTab->bLock--;
+ }else{
+ rc = fts3EvalNext((Fts3Cursor *)pCursor);
+ }
+ assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
+ return rc;
+}
+
+/*
+** If the numeric type of argument pVal is "integer", then return it
+** converted to a 64-bit signed integer. Otherwise, return a copy of
+** the second parameter, iDefault.
+*/
+static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
+ if( pVal ){
+ int eType = sqlite3_value_numeric_type(pVal);
+ if( eType==SQLITE_INTEGER ){
+ return sqlite3_value_int64(pVal);
+ }
+ }
+ return iDefault;
+}
+
+/*
+** This is the xFilter interface for the virtual table. See
+** the virtual table xFilter method documentation for additional
+** information.
+**
+** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
+** the %_content table.
+**
+** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
+** in the %_content table.
+**
+** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
+** column on the left-hand side of the MATCH operator is column
+** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
+** side of the MATCH operator.
+*/
+static int fts3FilterMethod(
+ sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
+ int idxNum, /* Strategy index */
+ const char *idxStr, /* Unused */
+ int nVal, /* Number of elements in apVal */
+ sqlite3_value **apVal /* Arguments for the indexing scheme */
+){
+ int rc = SQLITE_OK;
+ char *zSql; /* SQL statement used to access %_content */
+ int eSearch;
+ Fts3Table *p = (Fts3Table *)pCursor->pVtab;
+ Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
+
+ sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
+ sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
+ sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
+ sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
+ int iIdx;
+
+ UNUSED_PARAMETER(idxStr);
+ UNUSED_PARAMETER(nVal);
+
+ if( p->bLock ){
+ return SQLITE_ERROR;
+ }
+
+ eSearch = (idxNum & 0x0000FFFF);
+ assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
+ assert( p->pSegments==0 );
+
+ /* Collect arguments into local variables */
+ iIdx = 0;
+ if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
+ if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
+ if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
+ if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
+ assert( iIdx==nVal );
+
+ /* In case the cursor has been used before, clear it now. */
+ fts3ClearCursor(pCsr);
+
+ /* Set the lower and upper bounds on docids to return */
+ pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
+ pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
+
+ if( idxStr ){
+ pCsr->bDesc = (idxStr[0]=='D');
+ }else{
+ pCsr->bDesc = p->bDescIdx;
+ }
+ pCsr->eSearch = (i16)eSearch;
+
+ if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
+ int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
+ const char *zQuery = (const char *)sqlite3_value_text(pCons);
+
+ if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
+ return SQLITE_NOMEM;
+ }
+
+ pCsr->iLangid = 0;
+ if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
+
+ assert( p->base.zErrMsg==0 );
+ rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
+ p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
+ &p->base.zErrMsg
+ );
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+
+ rc = fts3EvalStart(pCsr);
+ sqlite3Fts3SegmentsClose(p);
+ if( rc!=SQLITE_OK ) return rc;
+ pCsr->pNextId = pCsr->aDoclist;
+ pCsr->iPrevId = 0;
+ }
+
+ /* Compile a SELECT statement for this cursor. For a full-table-scan, the
+ ** statement loops through all rows of the %_content table. For a
+ ** full-text query or docid lookup, the statement retrieves a single
+ ** row by docid.
+ */
+ if( eSearch==FTS3_FULLSCAN_SEARCH ){
+ if( pDocidGe || pDocidLe ){
+ zSql = sqlite3_mprintf(
+ "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
+ p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
+ (pCsr->bDesc ? "DESC" : "ASC")
+ );
+ }else{
+ zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
+ p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
+ );
+ }
+ if( zSql ){
+ p->bLock++;
+ rc = sqlite3_prepare_v3(
+ p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0
+ );
+ p->bLock--;
+ sqlite3_free(zSql);
+ }else{
+ rc = SQLITE_NOMEM;
+ }
+ }else if( eSearch==FTS3_DOCID_SEARCH ){
+ rc = fts3CursorSeekStmt(pCsr);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
+ }
+ }
+ if( rc!=SQLITE_OK ) return rc;
+
+ return fts3NextMethod(pCursor);
+}
+
+/*
+** This is the xEof method of the virtual table. SQLite calls this
+** routine to find out if it has reached the end of a result set.
+*/
+static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
+ Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
+ if( pCsr->isEof ){
+ fts3ClearCursor(pCsr);
+ pCsr->isEof = 1;
+ }
+ return pCsr->isEof;
+}
+
+/*
+** This is the xRowid method. The SQLite core calls this routine to
+** retrieve the rowid for the current row of the result set. fts3
+** exposes %_content.docid as the rowid for the virtual table. The
+** rowid should be written to *pRowid.
+*/
+static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
+ Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
+ *pRowid = pCsr->iPrevId;
+ return SQLITE_OK;
+}
+
+/*
+** This is the xColumn method, called by SQLite to request a value from
+** the row that the supplied cursor currently points to.
+**
+** If:
+**
+** (iCol < p->nColumn) -> The value of the iCol'th user column.
+** (iCol == p->nColumn) -> Magic column with the same name as the table.
+** (iCol == p->nColumn+1) -> Docid column
+** (iCol == p->nColumn+2) -> Langid column
+*/
+static int fts3ColumnMethod(
+ sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
+ sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
+ int iCol /* Index of column to read value from */
+){
+ int rc = SQLITE_OK; /* Return Code */
+ Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
+ Fts3Table *p = (Fts3Table *)pCursor->pVtab;
+
+ /* The column value supplied by SQLite must be in range. */
+ assert( iCol>=0 && iCol<=p->nColumn+2 );
+
+ switch( iCol-p->nColumn ){
+ case 0:
+ /* The special 'table-name' column */
+ sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
+ break;
+
+ case 1:
+ /* The docid column */
+ sqlite3_result_int64(pCtx, pCsr->iPrevId);
+ break;
+
+ case 2:
+ if( pCsr->pExpr ){
+ sqlite3_result_int64(pCtx, pCsr->iLangid);
+ break;
+ }else if( p->zLanguageid==0 ){
+ sqlite3_result_int(pCtx, 0);
+ break;
+ }else{
+ iCol = p->nColumn;
+ /* no break */ deliberate_fall_through
+ }
+
+ default:
+ /* A user column. Or, if this is a full-table scan, possibly the
+ ** language-id column. Seek the cursor. */
+ rc = fts3CursorSeek(0, pCsr);
+ if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
+ sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
+ }
+ break;
+ }
+
+ assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
+ return rc;
+}
+
+/*
+** This function is the implementation of the xUpdate callback used by
+** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
+** inserted, updated or deleted.
+*/
+static int fts3UpdateMethod(
+ sqlite3_vtab *pVtab, /* Virtual table handle */
+ int nArg, /* Size of argument array */
+ sqlite3_value **apVal, /* Array of arguments */
+ sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
+){
+ return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
+}
+
+/*
+** Implementation of xSync() method. Flush the contents of the pending-terms
+** hash-table to the database.
+*/
+static int fts3SyncMethod(sqlite3_vtab *pVtab){
+
+ /* Following an incremental-merge operation, assuming that the input
+ ** segments are not completely consumed (the usual case), they are updated
+ ** in place to remove the entries that have already been merged. This
+ ** involves updating the leaf block that contains the smallest unmerged
+ ** entry and each block (if any) between the leaf and the root node. So
+ ** if the height of the input segment b-trees is N, and input segments
+ ** are merged eight at a time, updating the input segments at the end
+ ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
+ ** small - often between 0 and 2. So the overhead of the incremental
+ ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
+ ** dwarfing the actual productive work accomplished, the incremental merge
+ ** is only attempted if it will write at least 64 leaf blocks. Hence
+ ** nMinMerge.
+ **
+ ** Of course, updating the input segments also involves deleting a bunch
+ ** of blocks from the segments table. But this is not considered overhead
+ ** as it would also be required by a crisis-merge that used the same input
+ ** segments.
+ */
+ const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
+
+ Fts3Table *p = (Fts3Table*)pVtab;
+ int rc;
+ i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
+
+ rc = sqlite3Fts3PendingTermsFlush(p);
+ if( rc==SQLITE_OK
+ && p->nLeafAdd>(nMinMerge/16)
+ && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
+ ){
+ int mxLevel = 0; /* Maximum relative level value in db */
+ int A; /* Incr-merge parameter A */
+
+ rc = sqlite3Fts3MaxLevel(p, &mxLevel);
+ assert( rc==SQLITE_OK || mxLevel==0 );
+ A = p->nLeafAdd * mxLevel;
+ A += (A/2);
+ if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
+ }
+ sqlite3Fts3SegmentsClose(p);
+ sqlite3_set_last_insert_rowid(p->db, iLastRowid);
+ return rc;
+}
+
+/*
+** If it is currently unknown whether or not the FTS table has an %_stat
+** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
+** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
+** if an error occurs.
+*/
+static int fts3SetHasStat(Fts3Table *p){
+ int rc = SQLITE_OK;
+ if( p->bHasStat==2 ){
+ char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
+ if( zTbl ){
+ int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
+ sqlite3_free(zTbl);
+ p->bHasStat = (res==SQLITE_OK);
+ }else{
+ rc = SQLITE_NOMEM;
+ }
+ }
+ return rc;
+}
+
+/*
+** Implementation of xBegin() method.
+*/
+static int fts3BeginMethod(sqlite3_vtab *pVtab){
+ Fts3Table *p = (Fts3Table*)pVtab;
+ UNUSED_PARAMETER(pVtab);
+ assert( p->pSegments==0 );
+ assert( p->nPendingData==0 );
+ assert( p->inTransaction!=1 );
+ TESTONLY( p->inTransaction = 1 );
+ TESTONLY( p->mxSavepoint = -1; );
+ p->nLeafAdd = 0;
+ return fts3SetHasStat(p);
+}
+
+/*
+** Implementation of xCommit() method. This is a no-op. The contents of
+** the pending-terms hash-table have already been flushed into the database
+** by fts3SyncMethod().
+*/
+static int fts3CommitMethod(sqlite3_vtab *pVtab){
+ TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
+ UNUSED_PARAMETER(pVtab);
+ assert( p->nPendingData==0 );
+ assert( p->inTransaction!=0 );
+ assert( p->pSegments==0 );
+ TESTONLY( p->inTransaction = 0 );
+ TESTONLY( p->mxSavepoint = -1; );
+ return SQLITE_OK;
+}
+
+/*
+** Implementation of xRollback(). Discard the contents of the pending-terms
+** hash-table. Any changes made to the database are reverted by SQLite.
+*/
+static int fts3RollbackMethod(sqlite3_vtab *pVtab){
+ Fts3Table *p = (Fts3Table*)pVtab;
+ sqlite3Fts3PendingTermsClear(p);
+ assert( p->inTransaction!=0 );
+ TESTONLY( p->inTransaction = 0 );
+ TESTONLY( p->mxSavepoint = -1; );
+ return SQLITE_OK;
+}
+
+/*
+** When called, *ppPoslist must point to the byte immediately following the
+** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
+** moves *ppPoslist so that it instead points to the first byte of the
+** same position list.
+*/
+static void fts3ReversePoslist(char *pStart, char **ppPoslist){
+ char *p = &(*ppPoslist)[-2];
+ char c = 0;
+
+ /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
+ while( p>pStart && (c=*p--)==0 );
+
+ /* Search backwards for a varint with value zero (the end of the previous
+ ** poslist). This is an 0x00 byte preceded by some byte that does not
+ ** have the 0x80 bit set. */
+ while( p>pStart && (*p & 0x80) | c ){
+ c = *p--;
+ }
+ assert( p==pStart || c==0 );
+
+ /* At this point p points to that preceding byte without the 0x80 bit
+ ** set. So to find the start of the poslist, skip forward 2 bytes then
+ ** over a varint.
+ **
+ ** Normally. The other case is that p==pStart and the poslist to return
+ ** is the first in the doclist. In this case do not skip forward 2 bytes.
+ ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
+ ** is required for cases where the first byte of a doclist and the
+ ** doclist is empty. For example, if the first docid is 10, a doclist
+ ** that begins with:
+ **
+ ** 0x0A 0x00 <next docid delta varint>
+ */
+ if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
+ while( *p++&0x80 );
+ *ppPoslist = p;
+}
+
+/*
+** Helper function used by the implementation of the overloaded snippet(),
+** offsets() and optimize() SQL functions.
+**
+** If the value passed as the third argument is a blob of size
+** sizeof(Fts3Cursor*), then the blob contents are copied to the
+** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
+** message is written to context pContext and SQLITE_ERROR returned. The
+** string passed via zFunc is used as part of the error message.
+*/
+static int fts3FunctionArg(
+ sqlite3_context *pContext, /* SQL function call context */
+ const char *zFunc, /* Function name */
+ sqlite3_value *pVal, /* argv[0] passed to function */
+ Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
+){
+ int rc;
+ *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
+ if( (*ppCsr)!=0 ){
+ rc = SQLITE_OK;
+ }else{
+ char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
+ sqlite3_result_error(pContext, zErr, -1);
+ sqlite3_free(zErr);
+ rc = SQLITE_ERROR;
+ }
+ return rc;
+}
+
+/*
+** Implementation of the snippet() function for FTS3
+*/
+static void fts3SnippetFunc(
+ sqlite3_context *pContext, /* SQLite function call context */
+ int nVal, /* Size of apVal[] array */
+ sqlite3_value **apVal /* Array of arguments */
+){
+ Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
+ const char *zStart = "<b>";
+ const char *zEnd = "</b>";
+ const char *zEllipsis = "<b>...</b>";
+ int iCol = -1;
+ int nToken = 15; /* Default number of tokens in snippet */
+
+ /* There must be at least one argument passed to this function (otherwise
+ ** the non-overloaded version would have been called instead of this one).
+ */
+ assert( nVal>=1 );
+
+ if( nVal>6 ){
+ sqlite3_result_error(pContext,
+ "wrong number of arguments to function snippet()", -1);
+ return;
+ }
+ if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
+
+ switch( nVal ){
+ case 6: nToken = sqlite3_value_int(apVal[5]);
+ /* no break */ deliberate_fall_through
+ case 5: iCol = sqlite3_value_int(apVal[4]);
+ /* no break */ deliberate_fall_through
+ case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
+ /* no break */ deliberate_fall_through
+ case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
+ /* no break */ deliberate_fall_through
+ case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
+ }
+ if( !zEllipsis || !zEnd || !zStart ){
+ sqlite3_result_error_nomem(pContext);
+ }else if( nToken==0 ){
+ sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
+ }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
+ sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
+ }
+}
+
+/*
+** Implementation of the offsets() function for FTS3
+*/
+static void fts3OffsetsFunc(
+ sqlite3_context *pContext, /* SQLite function call context */
+ int nVal, /* Size of argument array */
+ sqlite3_value **apVal /* Array of arguments */
+){
+ Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
+
+ UNUSED_PARAMETER(nVal);
+
+ assert( nVal==1 );
+ if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
+ assert( pCsr );
+ if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
+ sqlite3Fts3Offsets(pContext, pCsr);
+ }
+}
+
+/*
+** Implementation of the special optimize() function for FTS3. This
+** function merges all segments in the database to a single segment.
+** Example usage is:
+**
+** SELECT optimize(t) FROM t LIMIT 1;
+**
+** where 't' is the name of an FTS3 table.
+*/
+static void fts3OptimizeFunc(
+ sqlite3_context *pContext, /* SQLite function call context */
+ int nVal, /* Size of argument array */
+ sqlite3_value **apVal /* Array of arguments */
+){
+ int rc; /* Return code */
+ Fts3Table *p; /* Virtual table handle */
+ Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
+
+ UNUSED_PARAMETER(nVal);
+
+ assert( nVal==1 );
+ if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
+ p = (Fts3Table *)pCursor->base.pVtab;
+ assert( p );
+
+ rc = sqlite3Fts3Optimize(p);
+
+ switch( rc ){
+ case SQLITE_OK:
+ sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
+ break;
+ case SQLITE_DONE:
+ sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
+ break;
+ default:
+ sqlite3_result_error_code(pContext, rc);
+ break;
+ }
+}
+
+/*
+** Implementation of the matchinfo() function for FTS3
+*/
+static void fts3MatchinfoFunc(
+ sqlite3_context *pContext, /* SQLite function call context */
+ int nVal, /* Size of argument array */
+ sqlite3_value **apVal /* Array of arguments */
+){
+ Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
+ assert( nVal==1 || nVal==2 );
+ if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
+ const char *zArg = 0;
+ if( nVal>1 ){
+ zArg = (const char *)sqlite3_value_text(apVal[1]);
+ }
+ sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
+ }
+}
+
+/*
+** This routine implements the xFindFunction method for the FTS3
+** virtual table.
+*/
+static int fts3FindFunctionMethod(
+ sqlite3_vtab *pVtab, /* Virtual table handle */
+ int nArg, /* Number of SQL function arguments */
+ const char *zName, /* Name of SQL function */
+ void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
+ void **ppArg /* Unused */
+){
+ struct Overloaded {
+ const char *zName;
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
+ } aOverload[] = {
+ { "snippet", fts3SnippetFunc },
+ { "offsets", fts3OffsetsFunc },
+ { "optimize", fts3OptimizeFunc },
+ { "matchinfo", fts3MatchinfoFunc },
+ };
+ int i; /* Iterator variable */
+
+ UNUSED_PARAMETER(pVtab);
+ UNUSED_PARAMETER(nArg);
+ UNUSED_PARAMETER(ppArg);
+
+ for(i=0; i<SizeofArray(aOverload); i++){
+ if( strcmp(zName, aOverload[i].zName)==0 ){
+ *pxFunc = aOverload[i].xFunc;
+ return 1;
+ }
+ }
+
+ /* No function of the specified name was found. Return 0. */
+ return 0;
+}
+
+/*
+** Implementation of FTS3 xRename method. Rename an fts3 table.
+*/
+static int fts3RenameMethod(
+ sqlite3_vtab *pVtab, /* Virtual table handle */
+ const char *zName /* New name of table */
+){
+ Fts3Table *p = (Fts3Table *)pVtab;
+ sqlite3 *db = p->db; /* Database connection */
+ int rc; /* Return Code */
+
+ /* At this point it must be known if the %_stat table exists or not.
+ ** So bHasStat may not be 2. */
+ rc = fts3SetHasStat(p);
+
+ /* As it happens, the pending terms table is always empty here. This is
+ ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
+ ** always opens a savepoint transaction. And the xSavepoint() method
+ ** flushes the pending terms table. But leave the (no-op) call to
+ ** PendingTermsFlush() in in case that changes.
+ */
+ assert( p->nPendingData==0 );
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts3PendingTermsFlush(p);
+ }
+
+ if( p->zContentTbl==0 ){
+ fts3DbExec(&rc, db,
+ "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
+ p->zDb, p->zName, zName
+ );
+ }
+
+ if( p->bHasDocsize ){
+ fts3DbExec(&rc, db,
+ "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
+ p->zDb, p->zName, zName
+ );
+ }
+ if( p->bHasStat ){
+ fts3DbExec(&rc, db,
+ "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
+ p->zDb, p->zName, zName
+ );
+ }
+ fts3DbExec(&rc, db,
+ "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
+ p->zDb, p->zName, zName
+ );
+ fts3DbExec(&rc, db,
+ "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
+ p->zDb, p->zName, zName
+ );
+ return rc;
+}
+
+/*
+** The xSavepoint() method.
+**
+** Flush the contents of the pending-terms table to disk.
+*/
+static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
+ int rc = SQLITE_OK;
+ UNUSED_PARAMETER(iSavepoint);
+ assert( ((Fts3Table *)pVtab)->inTransaction );
+ assert( ((Fts3Table *)pVtab)->mxSavepoint <= iSavepoint );
+ TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
+ if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
+ rc = fts3SyncMethod(pVtab);
+ }
+ return rc;
+}
+
+/*
+** The xRelease() method.
+**
+** This is a no-op.
+*/
+static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
+ TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
+ UNUSED_PARAMETER(iSavepoint);
+ UNUSED_PARAMETER(pVtab);
+ assert( p->inTransaction );
+ assert( p->mxSavepoint >= iSavepoint );
+ TESTONLY( p->mxSavepoint = iSavepoint-1 );
+ return SQLITE_OK;
+}
+
+/*
+** The xRollbackTo() method.
+**
+** Discard the contents of the pending terms table.
+*/
+static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
+ Fts3Table *p = (Fts3Table*)pVtab;
+ UNUSED_PARAMETER(iSavepoint);
+ assert( p->inTransaction );
+ TESTONLY( p->mxSavepoint = iSavepoint );
+ sqlite3Fts3PendingTermsClear(p);
+ return SQLITE_OK;
+}
+
+/*
+** Return true if zName is the extension on one of the shadow tables used
+** by this module.
+*/
+static int fts3ShadowName(const char *zName){
+ static const char *azName[] = {
+ "content", "docsize", "segdir", "segments", "stat",
+ };
+ unsigned int i;
+ for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
+ if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
+ }
+ return 0;
+}
+
+static const sqlite3_module fts3Module = {
+ /* iVersion */ 3,
+ /* xCreate */ fts3CreateMethod,
+ /* xConnect */ fts3ConnectMethod,
+ /* xBestIndex */ fts3BestIndexMethod,
+ /* xDisconnect */ fts3DisconnectMethod,
+ /* xDestroy */ fts3DestroyMethod,
+ /* xOpen */ fts3OpenMethod,
+ /* xClose */ fts3CloseMethod,
+ /* xFilter */ fts3FilterMethod,
+ /* xNext */ fts3NextMethod,
+ /* xEof */ fts3EofMethod,
+ /* xColumn */ fts3ColumnMethod,
+ /* xRowid */ fts3RowidMethod,
+ /* xUpdate */ fts3UpdateMethod,
+ /* xBegin */ fts3BeginMethod,
+ /* xSync */ fts3SyncMethod,
+ /* xCommit */ fts3CommitMethod,
+ /* xRollback */ fts3RollbackMethod,
+ /* xFindFunction */ fts3FindFunctionMethod,
+ /* xRename */ fts3RenameMethod,
+ /* xSavepoint */ fts3SavepointMethod,
+ /* xRelease */ fts3ReleaseMethod,
+ /* xRollbackTo */ fts3RollbackToMethod,
+ /* xShadowName */ fts3ShadowName,
+};
+
+/*
+** This function is registered as the module destructor (called when an
+** FTS3 enabled database connection is closed). It frees the memory
+** allocated for the tokenizer hash table.
+*/
+static void hashDestroy(void *p){
+ Fts3Hash *pHash = (Fts3Hash *)p;
+ sqlite3Fts3HashClear(pHash);
+ sqlite3_free(pHash);
+}
+
+/*
+** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
+** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
+** respectively. The following three forward declarations are for functions
+** declared in these files used to retrieve the respective implementations.
+**
+** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
+** to by the argument to point to the "simple" tokenizer implementation.
+** And so on.
+*/
+SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
+SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
+#ifndef SQLITE_DISABLE_FTS3_UNICODE
+SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
+#endif
+#ifdef SQLITE_ENABLE_ICU
+SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
+#endif
+
+/*
+** Initialize the fts3 extension. If this extension is built as part
+** of the sqlite library, then this function is called directly by
+** SQLite. If fts3 is built as a dynamically loadable extension, this
+** function is called by the sqlite3_extension_init() entry point.
+*/
+SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
+ int rc = SQLITE_OK;
+ Fts3Hash *pHash = 0;
+ const sqlite3_tokenizer_module *pSimple = 0;
+ const sqlite3_tokenizer_module *pPorter = 0;
+#ifndef SQLITE_DISABLE_FTS3_UNICODE
+ const sqlite3_tokenizer_module *pUnicode = 0;
+#endif
+
+#ifdef SQLITE_ENABLE_ICU
+ const sqlite3_tokenizer_module *pIcu = 0;
+ sqlite3Fts3IcuTokenizerModule(&pIcu);
+#endif
+
+#ifndef SQLITE_DISABLE_FTS3_UNICODE
+ sqlite3Fts3UnicodeTokenizer(&pUnicode);
+#endif
+
+#ifdef SQLITE_TEST
+ rc = sqlite3Fts3InitTerm(db);
+ if( rc!=SQLITE_OK ) return rc;
+#endif
+
+ rc = sqlite3Fts3InitAux(db);
+ if( rc!=SQLITE_OK ) return rc;
+
+ sqlite3Fts3SimpleTokenizerModule(&pSimple);
+ sqlite3Fts3PorterTokenizerModule(&pPorter);
+
+ /* Allocate and initialize the hash-table used to store tokenizers. */
+ pHash = sqlite3_malloc(sizeof(Fts3Hash));
+ if( !pHash ){
+ rc = SQLITE_NOMEM;
+ }else{
+ sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
+ }
+
+ /* Load the built-in tokenizers into the hash table */
+ if( rc==SQLITE_OK ){
+ if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
+ || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
+
+#ifndef SQLITE_DISABLE_FTS3_UNICODE
+ || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
+#endif
+#ifdef SQLITE_ENABLE_ICU
+ || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
+#endif
+ ){
+ rc = SQLITE_NOMEM;
+ }
+ }
+
+#ifdef SQLITE_TEST
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts3ExprInitTestInterface(db, pHash);
+ }
+#endif
+
+ /* Create the virtual table wrapper around the hash-table and overload
+ ** the four scalar functions. If this is successful, register the
+ ** module with sqlite.
+ */
+ if( SQLITE_OK==rc
+ && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
+ && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
+ && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
+ && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
+ && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
+ && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
+ ){
+ rc = sqlite3_create_module_v2(
+ db, "fts3", &fts3Module, (void *)pHash, hashDestroy
+ );
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_create_module_v2(
+ db, "fts4", &fts3Module, (void *)pHash, 0
+ );
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts3InitTok(db, (void *)pHash);
+ }
+ return rc;
+ }
+
+
+ /* An error has occurred. Delete the hash table and return the error code. */
+ assert( rc!=SQLITE_OK );
+ if( pHash ){
+ sqlite3Fts3HashClear(pHash);
+ sqlite3_free(pHash);
+ }
+ return rc;
+}
+
+/*
+** Allocate an Fts3MultiSegReader for each token in the expression headed
+** by pExpr.
+**
+** An Fts3SegReader object is a cursor that can seek or scan a range of
+** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
+** Fts3SegReader objects internally to provide an interface to seek or scan
+** within the union of all segments of a b-tree. Hence the name.
+**
+** If the allocated Fts3MultiSegReader just seeks to a single entry in a
+** segment b-tree (if the term is not a prefix or it is a prefix for which
+** there exists prefix b-tree of the right length) then it may be traversed
+** and merged incrementally. Otherwise, it has to be merged into an in-memory
+** doclist and then traversed.
+*/
+static void fts3EvalAllocateReaders(
+ Fts3Cursor *pCsr, /* FTS cursor handle */
+ Fts3Expr *pExpr, /* Allocate readers for this expression */
+ int *pnToken, /* OUT: Total number of tokens in phrase. */
+ int *pnOr, /* OUT: Total number of OR nodes in expr. */
+ int *pRc /* IN/OUT: Error code */
+){
+ if( pExpr && SQLITE_OK==*pRc ){
+ if( pExpr->eType==FTSQUERY_PHRASE ){
+ int i;
+ int nToken = pExpr->pPhrase->nToken;
+ *pnToken += nToken;
+ for(i=0; i<nToken; i++){
+ Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
+ int rc = fts3TermSegReaderCursor(pCsr,
+ pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
+ );
+ if( rc!=SQLITE_OK ){
+ *pRc = rc;
+ return;
+ }
+ }
+ assert( pExpr->pPhrase->iDoclistToken==0 );
+ pExpr->pPhrase->iDoclistToken = -1;
+ }else{
+ *pnOr += (pExpr->eType==FTSQUERY_OR);
+ fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
+ fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
+ }
+ }
+}
+
+/*
+** Arguments pList/nList contain the doclist for token iToken of phrase p.
+** It is merged into the main doclist stored in p->doclist.aAll/nAll.
+**
+** This function assumes that pList points to a buffer allocated using
+** sqlite3_malloc(). This function takes responsibility for eventually
+** freeing the buffer.
+**
+** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
+*/
+static int fts3EvalPhraseMergeToken(
+ Fts3Table *pTab, /* FTS Table pointer */
+ Fts3Phrase *p, /* Phrase to merge pList/nList into */
+ int iToken, /* Token pList/nList corresponds to */
+ char *pList, /* Pointer to doclist */
+ int nList /* Number of bytes in pList */
+){
+ int rc = SQLITE_OK;
+ assert( iToken!=p->iDoclistToken );
+
+ if( pList==0 ){
+ sqlite3_free(p->doclist.aAll);
+ p->doclist.aAll = 0;
+ p->doclist.nAll = 0;
+ }
+
+ else if( p->iDoclistToken<0 ){
+ p->doclist.aAll = pList;
+ p->doclist.nAll = nList;
+ }
+
+ else if( p->doclist.aAll==0 ){
+ sqlite3_free(pList);
+ }
+
+ else {
+ char *pLeft;
+ char *pRight;
+ int nLeft;
+ int nRight;
+ int nDiff;
+
+ if( p->iDoclistToken<iToken ){
+ pLeft = p->doclist.aAll;
+ nLeft = p->doclist.nAll;
+ pRight = pList;
+ nRight = nList;
+ nDiff = iToken - p->iDoclistToken;
+ }else{
+ pRight = p->doclist.aAll;
+ nRight = p->doclist.nAll;
+ pLeft = pList;
+ nLeft = nList;
+ nDiff = p->iDoclistToken - iToken;
+ }
+
+ rc = fts3DoclistPhraseMerge(
+ pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
+ );
+ sqlite3_free(pLeft);
+ p->doclist.aAll = pRight;
+ p->doclist.nAll = nRight;
+ }
+
+ if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
+ return rc;
+}
+
+/*
+** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
+** does not take deferred tokens into account.
+**
+** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
+*/
+static int fts3EvalPhraseLoad(
+ Fts3Cursor *pCsr, /* FTS Cursor handle */
+ Fts3Phrase *p /* Phrase object */
+){
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+ int iToken;
+ int rc = SQLITE_OK;
+
+ for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
+ Fts3PhraseToken *pToken = &p->aToken[iToken];
+ assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
+
+ if( pToken->pSegcsr ){
+ int nThis = 0;
+ char *pThis = 0;
+ rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
+ if( rc==SQLITE_OK ){
+ rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
+ }
+ }
+ assert( pToken->pSegcsr==0 );
+ }
+
+ return rc;
+}
+
+#ifndef SQLITE_DISABLE_FTS4_DEFERRED
+/*
+** This function is called on each phrase after the position lists for
+** any deferred tokens have been loaded into memory. It updates the phrases
+** current position list to include only those positions that are really
+** instances of the phrase (after considering deferred tokens). If this
+** means that the phrase does not appear in the current row, doclist.pList
+** and doclist.nList are both zeroed.
+**
+** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
+*/
+static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
+ int iToken; /* Used to iterate through phrase tokens */
+ char *aPoslist = 0; /* Position list for deferred tokens */
+ int nPoslist = 0; /* Number of bytes in aPoslist */
+ int iPrev = -1; /* Token number of previous deferred token */
+
+ assert( pPhrase->doclist.bFreeList==0 );
+
+ for(iToken=0; iToken<pPhrase->nToken; iToken++){
+ Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
+ Fts3DeferredToken *pDeferred = pToken->pDeferred;
+
+ if( pDeferred ){
+ char *pList;
+ int nList;
+ int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
+ if( rc!=SQLITE_OK ) return rc;
+
+ if( pList==0 ){
+ sqlite3_free(aPoslist);
+ pPhrase->doclist.pList = 0;
+ pPhrase->doclist.nList = 0;
+ return SQLITE_OK;
+
+ }else if( aPoslist==0 ){
+ aPoslist = pList;
+ nPoslist = nList;
+
+ }else{
+ char *aOut = pList;
+ char *p1 = aPoslist;
+ char *p2 = aOut;
+
+ assert( iPrev>=0 );
+ fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
+ sqlite3_free(aPoslist);
+ aPoslist = pList;
+ nPoslist = (int)(aOut - aPoslist);
+ if( nPoslist==0 ){
+ sqlite3_free(aPoslist);
+ pPhrase->doclist.pList = 0;
+ pPhrase->doclist.nList = 0;
+ return SQLITE_OK;
+ }
+ }
+ iPrev = iToken;
+ }
+ }
+
+ if( iPrev>=0 ){
+ int nMaxUndeferred = pPhrase->iDoclistToken;
+ if( nMaxUndeferred<0 ){
+ pPhrase->doclist.pList = aPoslist;
+ pPhrase->doclist.nList = nPoslist;
+ pPhrase->doclist.iDocid = pCsr->iPrevId;
+ pPhrase->doclist.bFreeList = 1;
+ }else{
+ int nDistance;
+ char *p1;
+ char *p2;
+ char *aOut;
+
+ if( nMaxUndeferred>iPrev ){
+ p1 = aPoslist;
+ p2 = pPhrase->doclist.pList;
+ nDistance = nMaxUndeferred - iPrev;
+ }else{
+ p1 = pPhrase->doclist.pList;
+ p2 = aPoslist;
+ nDistance = iPrev - nMaxUndeferred;
+ }
+
+ aOut = (char *)sqlite3_malloc(nPoslist+8);
+ if( !aOut ){
+ sqlite3_free(aPoslist);
+ return SQLITE_NOMEM;
+ }
+
+ pPhrase->doclist.pList = aOut;
+ if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
+ pPhrase->doclist.bFreeList = 1;
+ pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
+ }else{
+ sqlite3_free(aOut);
+ pPhrase->doclist.pList = 0;
+ pPhrase->doclist.nList = 0;
+ }
+ sqlite3_free(aPoslist);
+ }
+ }
+
+ return SQLITE_OK;
+}
+#endif /* SQLITE_DISABLE_FTS4_DEFERRED */
+
+/*
+** Maximum number of tokens a phrase may have to be considered for the
+** incremental doclists strategy.
+*/
+#define MAX_INCR_PHRASE_TOKENS 4
+
+/*
+** This function is called for each Fts3Phrase in a full-text query
+** expression to initialize the mechanism for returning rows. Once this
+** function has been called successfully on an Fts3Phrase, it may be
+** used with fts3EvalPhraseNext() to iterate through the matching docids.
+**
+** If parameter bOptOk is true, then the phrase may (or may not) use the
+** incremental loading strategy. Otherwise, the entire doclist is loaded into
+** memory within this call.
+**
+** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
+*/
+static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+ int rc = SQLITE_OK; /* Error code */
+ int i;
+
+ /* Determine if doclists may be loaded from disk incrementally. This is
+ ** possible if the bOptOk argument is true, the FTS doclists will be
+ ** scanned in forward order, and the phrase consists of
+ ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
+ ** tokens or prefix tokens that cannot use a prefix-index. */
+ int bHaveIncr = 0;
+ int bIncrOk = (bOptOk
+ && pCsr->bDesc==pTab->bDescIdx
+ && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+ && pTab->bNoIncrDoclist==0
+#endif
+ );
+ for(i=0; bIncrOk==1 && i<p->nToken; i++){
+ Fts3PhraseToken *pToken = &p->aToken[i];
+ if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
+ bIncrOk = 0;
+ }
+ if( pToken->pSegcsr ) bHaveIncr = 1;
+ }
+
+ if( bIncrOk && bHaveIncr ){
+ /* Use the incremental approach. */
+ int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
+ for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
+ Fts3PhraseToken *pToken = &p->aToken[i];
+ Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
+ if( pSegcsr ){
+ rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
+ }
+ }
+ p->bIncr = 1;
+ }else{
+ /* Load the full doclist for the phrase into memory. */
+ rc = fts3EvalPhraseLoad(pCsr, p);
+ p->bIncr = 0;
+ }
+
+ assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
+ return rc;
+}
+
+/*
+** This function is used to iterate backwards (from the end to start)
+** through doclists. It is used by this module to iterate through phrase
+** doclists in reverse and by the fts3_write.c module to iterate through
+** pending-terms lists when writing to databases with "order=desc".
+**
+** The doclist may be sorted in ascending (parameter bDescIdx==0) or
+** descending (parameter bDescIdx==1) order of docid. Regardless, this
+** function iterates from the end of the doclist to the beginning.
+*/
+SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
+ int bDescIdx, /* True if the doclist is desc */
+ char *aDoclist, /* Pointer to entire doclist */
+ int nDoclist, /* Length of aDoclist in bytes */
+ char **ppIter, /* IN/OUT: Iterator pointer */
+ sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
+ int *pnList, /* OUT: List length pointer */
+ u8 *pbEof /* OUT: End-of-file flag */
+){
+ char *p = *ppIter;
+
+ assert( nDoclist>0 );
+ assert( *pbEof==0 );
+ assert( p || *piDocid==0 );
+ assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
+
+ if( p==0 ){
+ sqlite3_int64 iDocid = 0;
+ char *pNext = 0;
+ char *pDocid = aDoclist;
+ char *pEnd = &aDoclist[nDoclist];
+ int iMul = 1;
+
+ while( pDocid<pEnd ){
+ sqlite3_int64 iDelta;
+ pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
+ iDocid += (iMul * iDelta);
+ pNext = pDocid;
+ fts3PoslistCopy(0, &pDocid);
+ while( pDocid<pEnd && *pDocid==0 ) pDocid++;
+ iMul = (bDescIdx ? -1 : 1);
+ }
+
+ *pnList = (int)(pEnd - pNext);
+ *ppIter = pNext;
+ *piDocid = iDocid;
+ }else{
+ int iMul = (bDescIdx ? -1 : 1);
+ sqlite3_int64 iDelta;
+ fts3GetReverseVarint(&p, aDoclist, &iDelta);
+ *piDocid -= (iMul * iDelta);
+
+ if( p==aDoclist ){
+ *pbEof = 1;
+ }else{
+ char *pSave = p;
+ fts3ReversePoslist(aDoclist, &p);
+ *pnList = (int)(pSave - p);
+ }
+ *ppIter = p;
+ }
+}
+
+/*
+** Iterate forwards through a doclist.
+*/
+SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
+ int bDescIdx, /* True if the doclist is desc */
+ char *aDoclist, /* Pointer to entire doclist */
+ int nDoclist, /* Length of aDoclist in bytes */
+ char **ppIter, /* IN/OUT: Iterator pointer */
+ sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
+ u8 *pbEof /* OUT: End-of-file flag */
+){
+ char *p = *ppIter;
+
+ assert( nDoclist>0 );
+ assert( *pbEof==0 );
+ assert_fts3_nc( p || *piDocid==0 );
+ assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
+
+ if( p==0 ){
+ p = aDoclist;
+ p += sqlite3Fts3GetVarint(p, piDocid);
+ }else{
+ fts3PoslistCopy(0, &p);
+ while( p<&aDoclist[nDoclist] && *p==0 ) p++;
+ if( p>=&aDoclist[nDoclist] ){
+ *pbEof = 1;
+ }else{
+ sqlite3_int64 iVar;
+ p += sqlite3Fts3GetVarint(p, &iVar);
+ *piDocid += ((bDescIdx ? -1 : 1) * iVar);
+ }
+ }
+
+ *ppIter = p;
+}
+
+/*
+** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
+** to true if EOF is reached.
+*/
+static void fts3EvalDlPhraseNext(
+ Fts3Table *pTab,
+ Fts3Doclist *pDL,
+ u8 *pbEof
+){
+ char *pIter; /* Used to iterate through aAll */
+ char *pEnd; /* 1 byte past end of aAll */
+
+ if( pDL->pNextDocid ){
+ pIter = pDL->pNextDocid;
+ assert( pDL->aAll!=0 || pIter==0 );
+ }else{
+ pIter = pDL->aAll;
+ }
+
+ if( pIter==0 || pIter>=(pEnd = pDL->aAll + pDL->nAll) ){
+ /* We have already reached the end of this doclist. EOF. */
+ *pbEof = 1;
+ }else{
+ sqlite3_int64 iDelta;
+ pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
+ if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
+ pDL->iDocid += iDelta;
+ }else{
+ pDL->iDocid -= iDelta;
+ }
+ pDL->pList = pIter;
+ fts3PoslistCopy(0, &pIter);
+ pDL->nList = (int)(pIter - pDL->pList);
+
+ /* pIter now points just past the 0x00 that terminates the position-
+ ** list for document pDL->iDocid. However, if this position-list was
+ ** edited in place by fts3EvalNearTrim(), then pIter may not actually
+ ** point to the start of the next docid value. The following line deals
+ ** with this case by advancing pIter past the zero-padding added by
+ ** fts3EvalNearTrim(). */
+ while( pIter<pEnd && *pIter==0 ) pIter++;
+
+ pDL->pNextDocid = pIter;
+ assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
+ *pbEof = 0;
+ }
+}
+
+/*
+** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
+*/
+typedef struct TokenDoclist TokenDoclist;
+struct TokenDoclist {
+ int bIgnore;
+ sqlite3_int64 iDocid;
+ char *pList;
+ int nList;
+};
+
+/*
+** Token pToken is an incrementally loaded token that is part of a
+** multi-token phrase. Advance it to the next matching document in the
+** database and populate output variable *p with the details of the new
+** entry. Or, if the iterator has reached EOF, set *pbEof to true.
+**
+** If an error occurs, return an SQLite error code. Otherwise, return
+** SQLITE_OK.
+*/
+static int incrPhraseTokenNext(
+ Fts3Table *pTab, /* Virtual table handle */
+ Fts3Phrase *pPhrase, /* Phrase to advance token of */
+ int iToken, /* Specific token to advance */
+ TokenDoclist *p, /* OUT: Docid and doclist for new entry */
+ u8 *pbEof /* OUT: True if iterator is at EOF */
+){
+ int rc = SQLITE_OK;
+
+ if( pPhrase->iDoclistToken==iToken ){
+ assert( p->bIgnore==0 );
+ assert( pPhrase->aToken[iToken].pSegcsr==0 );
+ fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
+ p->pList = pPhrase->doclist.pList;
+ p->nList = pPhrase->doclist.nList;
+ p->iDocid = pPhrase->doclist.iDocid;
+ }else{
+ Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
+ assert( pToken->pDeferred==0 );
+ assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
+ if( pToken->pSegcsr ){
+ assert( p->bIgnore==0 );
+ rc = sqlite3Fts3MsrIncrNext(
+ pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
+ );
+ if( p->pList==0 ) *pbEof = 1;
+ }else{
+ p->bIgnore = 1;
+ }
+ }
+
+ return rc;
+}
+
+
+/*
+** The phrase iterator passed as the second argument:
+**
+** * features at least one token that uses an incremental doclist, and
+**
+** * does not contain any deferred tokens.
+**
+** Advance it to the next matching documnent in the database and populate
+** the Fts3Doclist.pList and nList fields.
+**
+** If there is no "next" entry and no error occurs, then *pbEof is set to
+** 1 before returning. Otherwise, if no error occurs and the iterator is
+** successfully advanced, *pbEof is set to 0.
+**
+** If an error occurs, return an SQLite error code. Otherwise, return
+** SQLITE_OK.
+*/
+static int fts3EvalIncrPhraseNext(
+ Fts3Cursor *pCsr, /* FTS Cursor handle */
+ Fts3Phrase *p, /* Phrase object to advance to next docid */
+ u8 *pbEof /* OUT: Set to 1 if EOF */
+){
+ int rc = SQLITE_OK;
+ Fts3Doclist *pDL = &p->doclist;
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+ u8 bEof = 0;
+
+ /* This is only called if it is guaranteed that the phrase has at least
+ ** one incremental token. In which case the bIncr flag is set. */
+ assert( p->bIncr==1 );
+
+ if( p->nToken==1 ){
+ rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
+ &pDL->iDocid, &pDL->pList, &pDL->nList
+ );
+ if( pDL->pList==0 ) bEof = 1;
+ }else{
+ int bDescDoclist = pCsr->bDesc;
+ struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
+
+ memset(a, 0, sizeof(a));
+ assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
+ assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
+
+ while( bEof==0 ){
+ int bMaxSet = 0;
+ sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
+ int i; /* Used to iterate through tokens */
+
+ /* Advance the iterator for each token in the phrase once. */
+ for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
+ rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
+ if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
+ iMax = a[i].iDocid;
+ bMaxSet = 1;
+ }
+ }
+ assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
+ assert( rc!=SQLITE_OK || bMaxSet );
+
+ /* Keep advancing iterators until they all point to the same document */
+ for(i=0; i<p->nToken; i++){
+ while( rc==SQLITE_OK && bEof==0
+ && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
+ ){
+ rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
+ if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
+ iMax = a[i].iDocid;
+ i = 0;
+ }
+ }
+ }
+
+ /* Check if the current entries really are a phrase match */
+ if( bEof==0 ){
+ int nList = 0;
+ int nByte = a[p->nToken-1].nList;
+ char *aDoclist = sqlite3_malloc(nByte+FTS3_BUFFER_PADDING);
+ if( !aDoclist ) return SQLITE_NOMEM;
+ memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
+ memset(&aDoclist[nByte], 0, FTS3_BUFFER_PADDING);
+
+ for(i=0; i<(p->nToken-1); i++){
+ if( a[i].bIgnore==0 ){
+ char *pL = a[i].pList;
+ char *pR = aDoclist;
+ char *pOut = aDoclist;
+ int nDist = p->nToken-1-i;
+ int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
+ if( res==0 ) break;
+ nList = (int)(pOut - aDoclist);
+ }
+ }
+ if( i==(p->nToken-1) ){
+ pDL->iDocid = iMax;
+ pDL->pList = aDoclist;
+ pDL->nList = nList;
+ pDL->bFreeList = 1;
+ break;
+ }
+ sqlite3_free(aDoclist);
+ }
+ }
+ }
+
+ *pbEof = bEof;
+ return rc;
+}
+
+/*
+** Attempt to move the phrase iterator to point to the next matching docid.
+** If an error occurs, return an SQLite error code. Otherwise, return
+** SQLITE_OK.
+**
+** If there is no "next" entry and no error occurs, then *pbEof is set to
+** 1 before returning. Otherwise, if no error occurs and the iterator is
+** successfully advanced, *pbEof is set to 0.
+*/
+static int fts3EvalPhraseNext(
+ Fts3Cursor *pCsr, /* FTS Cursor handle */
+ Fts3Phrase *p, /* Phrase object to advance to next docid */
+ u8 *pbEof /* OUT: Set to 1 if EOF */
+){
+ int rc = SQLITE_OK;
+ Fts3Doclist *pDL = &p->doclist;
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+
+ if( p->bIncr ){
+ rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
+ }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
+ sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
+ &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
+ );
+ pDL->pList = pDL->pNextDocid;
+ }else{
+ fts3EvalDlPhraseNext(pTab, pDL, pbEof);
+ }
+
+ return rc;
+}
+
+/*
+**
+** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
+** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
+** expression. Also the Fts3Expr.bDeferred variable is set to true for any
+** expressions for which all descendent tokens are deferred.
+**
+** If parameter bOptOk is zero, then it is guaranteed that the
+** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
+** each phrase in the expression (subject to deferred token processing).
+** Or, if bOptOk is non-zero, then one or more tokens within the expression
+** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
+**
+** If an error occurs within this function, *pRc is set to an SQLite error
+** code before returning.
+*/
+static void fts3EvalStartReaders(
+ Fts3Cursor *pCsr, /* FTS Cursor handle */
+ Fts3Expr *pExpr, /* Expression to initialize phrases in */
+ int *pRc /* IN/OUT: Error code */
+){
+ if( pExpr && SQLITE_OK==*pRc ){
+ if( pExpr->eType==FTSQUERY_PHRASE ){
+ int nToken = pExpr->pPhrase->nToken;
+ if( nToken ){
+ int i;
+ for(i=0; i<nToken; i++){
+ if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
+ }
+ pExpr->bDeferred = (i==nToken);
+ }
+ *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
+ }else{
+ fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
+ fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
+ pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
+ }
+ }
+}
+
+/*
+** An array of the following structures is assembled as part of the process
+** of selecting tokens to defer before the query starts executing (as part
+** of the xFilter() method). There is one element in the array for each
+** token in the FTS expression.
+**
+** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
+** to phrases that are connected only by AND and NEAR operators (not OR or
+** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
+** separately. The root of a tokens AND/NEAR cluster is stored in
+** Fts3TokenAndCost.pRoot.
+*/
+typedef struct Fts3TokenAndCost Fts3TokenAndCost;
+struct Fts3TokenAndCost {
+ Fts3Phrase *pPhrase; /* The phrase the token belongs to */
+ int iToken; /* Position of token in phrase */
+ Fts3PhraseToken *pToken; /* The token itself */
+ Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
+ int nOvfl; /* Number of overflow pages to load doclist */
+ int iCol; /* The column the token must match */
+};
+
+/*
+** This function is used to populate an allocated Fts3TokenAndCost array.
+**
+** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
+** Otherwise, if an error occurs during execution, *pRc is set to an
+** SQLite error code.
+*/
+static void fts3EvalTokenCosts(
+ Fts3Cursor *pCsr, /* FTS Cursor handle */
+ Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
+ Fts3Expr *pExpr, /* Expression to consider */
+ Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
+ Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
+ int *pRc /* IN/OUT: Error code */
+){
+ if( *pRc==SQLITE_OK ){
+ if( pExpr->eType==FTSQUERY_PHRASE ){
+ Fts3Phrase *pPhrase = pExpr->pPhrase;
+ int i;
+ for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
+ Fts3TokenAndCost *pTC = (*ppTC)++;
+ pTC->pPhrase = pPhrase;
+ pTC->iToken = i;
+ pTC->pRoot = pRoot;
+ pTC->pToken = &pPhrase->aToken[i];
+ pTC->iCol = pPhrase->iColumn;
+ *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
+ }
+ }else if( pExpr->eType!=FTSQUERY_NOT ){
+ assert( pExpr->eType==FTSQUERY_OR
+ || pExpr->eType==FTSQUERY_AND
+ || pExpr->eType==FTSQUERY_NEAR
+ );
+ assert( pExpr->pLeft && pExpr->pRight );
+ if( pExpr->eType==FTSQUERY_OR ){
+ pRoot = pExpr->pLeft;
+ **ppOr = pRoot;
+ (*ppOr)++;
+ }
+ fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
+ if( pExpr->eType==FTSQUERY_OR ){
+ pRoot = pExpr->pRight;
+ **ppOr = pRoot;
+ (*ppOr)++;
+ }
+ fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
+ }
+ }
+}
+
+/*
+** Determine the average document (row) size in pages. If successful,
+** write this value to *pnPage and return SQLITE_OK. Otherwise, return
+** an SQLite error code.
+**
+** The average document size in pages is calculated by first calculating
+** determining the average size in bytes, B. If B is less than the amount
+** of data that will fit on a single leaf page of an intkey table in
+** this database, then the average docsize is 1. Otherwise, it is 1 plus
+** the number of overflow pages consumed by a record B bytes in size.
+*/
+static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
+ int rc = SQLITE_OK;
+ if( pCsr->nRowAvg==0 ){
+ /* The average document size, which is required to calculate the cost
+ ** of each doclist, has not yet been determined. Read the required
+ ** data from the %_stat table to calculate it.
+ **
+ ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
+ ** varints, where nCol is the number of columns in the FTS3 table.
+ ** The first varint is the number of documents currently stored in
+ ** the table. The following nCol varints contain the total amount of
+ ** data stored in all rows of each column of the table, from left
+ ** to right.
+ */
+ Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
+ sqlite3_stmt *pStmt;
+ sqlite3_int64 nDoc = 0;
+ sqlite3_int64 nByte = 0;
+ const char *pEnd;
+ const char *a;
+
+ rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
+ if( rc!=SQLITE_OK ) return rc;
+ a = sqlite3_column_blob(pStmt, 0);
+ testcase( a==0 ); /* If %_stat.value set to X'' */
+ if( a ){
+ pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
+ a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc);
+ while( a<pEnd ){
+ a += sqlite3Fts3GetVarintBounded(a, pEnd, &nByte);
+ }
+ }
+ if( nDoc==0 || nByte==0 ){
+ sqlite3_reset(pStmt);
+ return FTS_CORRUPT_VTAB;
+ }
+
+ pCsr->nDoc = nDoc;
+ pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
+ assert( pCsr->nRowAvg>0 );
+ rc = sqlite3_reset(pStmt);
+ }
+
+ *pnPage = pCsr->nRowAvg;
+ return rc;
+}
+
+/*
+** This function is called to select the tokens (if any) that will be
+** deferred. The array aTC[] has already been populated when this is
+** called.
+**
+** This function is called once for each AND/NEAR cluster in the
+** expression. Each invocation determines which tokens to defer within
+** the cluster with root node pRoot. See comments above the definition
+** of struct Fts3TokenAndCost for more details.
+**
+** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
+** called on each token to defer. Otherwise, an SQLite error code is
+** returned.
+*/
+static int fts3EvalSelectDeferred(
+ Fts3Cursor *pCsr, /* FTS Cursor handle */
+ Fts3Expr *pRoot, /* Consider tokens with this root node */
+ Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
+ int nTC /* Number of entries in aTC[] */
+){
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+ int nDocSize = 0; /* Number of pages per doc loaded */
+ int rc = SQLITE_OK; /* Return code */
+ int ii; /* Iterator variable for various purposes */
+ int nOvfl = 0; /* Total overflow pages used by doclists */
+ int nToken = 0; /* Total number of tokens in cluster */
+
+ int nMinEst = 0; /* The minimum count for any phrase so far. */
+ int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
+
+ /* Tokens are never deferred for FTS tables created using the content=xxx
+ ** option. The reason being that it is not guaranteed that the content
+ ** table actually contains the same data as the index. To prevent this from
+ ** causing any problems, the deferred token optimization is completely
+ ** disabled for content=xxx tables. */
+ if( pTab->zContentTbl ){
+ return SQLITE_OK;
+ }
+
+ /* Count the tokens in this AND/NEAR cluster. If none of the doclists
+ ** associated with the tokens spill onto overflow pages, or if there is
+ ** only 1 token, exit early. No tokens to defer in this case. */
+ for(ii=0; ii<nTC; ii++){
+ if( aTC[ii].pRoot==pRoot ){
+ nOvfl += aTC[ii].nOvfl;
+ nToken++;
+ }
+ }
+ if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
+
+ /* Obtain the average docsize (in pages). */
+ rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
+ assert( rc!=SQLITE_OK || nDocSize>0 );
+
+
+ /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
+ ** of the number of overflow pages that will be loaded by the pager layer
+ ** to retrieve the entire doclist for the token from the full-text index.
+ ** Load the doclists for tokens that are either:
+ **
+ ** a. The cheapest token in the entire query (i.e. the one visited by the
+ ** first iteration of this loop), or
+ **
+ ** b. Part of a multi-token phrase.
+ **
+ ** After each token doclist is loaded, merge it with the others from the
+ ** same phrase and count the number of documents that the merged doclist
+ ** contains. Set variable "nMinEst" to the smallest number of documents in
+ ** any phrase doclist for which 1 or more token doclists have been loaded.
+ ** Let nOther be the number of other phrases for which it is certain that
+ ** one or more tokens will not be deferred.
+ **
+ ** Then, for each token, defer it if loading the doclist would result in
+ ** loading N or more overflow pages into memory, where N is computed as:
+ **
+ ** (nMinEst + 4^nOther - 1) / (4^nOther)
+ */
+ for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
+ int iTC; /* Used to iterate through aTC[] array. */
+ Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
+
+ /* Set pTC to point to the cheapest remaining token. */
+ for(iTC=0; iTC<nTC; iTC++){
+ if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
+ && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
+ ){
+ pTC = &aTC[iTC];
+ }
+ }
+ assert( pTC );
+
+ if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
+ /* The number of overflow pages to load for this (and therefore all
+ ** subsequent) tokens is greater than the estimated number of pages
+ ** that will be loaded if all subsequent tokens are deferred.
+ */
+ Fts3PhraseToken *pToken = pTC->pToken;
+ rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
+ fts3SegReaderCursorFree(pToken->pSegcsr);
+ pToken->pSegcsr = 0;
+ }else{
+ /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
+ ** for-loop. Except, limit the value to 2^24 to prevent it from
+ ** overflowing the 32-bit integer it is stored in. */
+ if( ii<12 ) nLoad4 = nLoad4*4;
+
+ if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
+ /* Either this is the cheapest token in the entire query, or it is
+ ** part of a multi-token phrase. Either way, the entire doclist will
+ ** (eventually) be loaded into memory. It may as well be now. */
+ Fts3PhraseToken *pToken = pTC->pToken;
+ int nList = 0;
+ char *pList = 0;
+ rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
+ assert( rc==SQLITE_OK || pList==0 );
+ if( rc==SQLITE_OK ){
+ rc = fts3EvalPhraseMergeToken(
+ pTab, pTC->pPhrase, pTC->iToken,pList,nList
+ );
+ }
+ if( rc==SQLITE_OK ){
+ int nCount;
+ nCount = fts3DoclistCountDocids(
+ pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
+ );
+ if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
+ }
+ }
+ }
+ pTC->pToken = 0;
+ }
+
+ return rc;
+}
+
+/*
+** This function is called from within the xFilter method. It initializes
+** the full-text query currently stored in pCsr->pExpr. To iterate through
+** the results of a query, the caller does:
+**
+** fts3EvalStart(pCsr);
+** while( 1 ){
+** fts3EvalNext(pCsr);
+** if( pCsr->bEof ) break;
+** ... return row pCsr->iPrevId to the caller ...
+** }
+*/
+static int fts3EvalStart(Fts3Cursor *pCsr){
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+ int rc = SQLITE_OK;
+ int nToken = 0;
+ int nOr = 0;
+
+ /* Allocate a MultiSegReader for each token in the expression. */
+ fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
+
+ /* Determine which, if any, tokens in the expression should be deferred. */
+#ifndef SQLITE_DISABLE_FTS4_DEFERRED
+ if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
+ Fts3TokenAndCost *aTC;
+ Fts3Expr **apOr;
+ aTC = (Fts3TokenAndCost *)sqlite3_malloc64(
+ sizeof(Fts3TokenAndCost) * nToken
+ + sizeof(Fts3Expr *) * nOr * 2
+ );
+ apOr = (Fts3Expr **)&aTC[nToken];
+
+ if( !aTC ){
+ rc = SQLITE_NOMEM;
+ }else{
+ int ii;
+ Fts3TokenAndCost *pTC = aTC;
+ Fts3Expr **ppOr = apOr;
+
+ fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
+ nToken = (int)(pTC-aTC);
+ nOr = (int)(ppOr-apOr);
+
+ if( rc==SQLITE_OK ){
+ rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
+ for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
+ rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
+ }
+ }
+
+ sqlite3_free(aTC);
+ }
+ }
+#endif
+
+ fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
+ return rc;
+}
+
+/*
+** Invalidate the current position list for phrase pPhrase.
+*/
+static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
+ if( pPhrase->doclist.bFreeList ){
+ sqlite3_free(pPhrase->doclist.pList);
+ }
+ pPhrase->doclist.pList = 0;
+ pPhrase->doclist.nList = 0;
+ pPhrase->doclist.bFreeList = 0;
+}
+
+/*
+** This function is called to edit the position list associated with
+** the phrase object passed as the fifth argument according to a NEAR
+** condition. For example:
+**
+** abc NEAR/5 "def ghi"
+**
+** Parameter nNear is passed the NEAR distance of the expression (5 in
+** the example above). When this function is called, *paPoslist points to
+** the position list, and *pnToken is the number of phrase tokens in the
+** phrase on the other side of the NEAR operator to pPhrase. For example,
+** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
+** the position list associated with phrase "abc".
+**
+** All positions in the pPhrase position list that are not sufficiently
+** close to a position in the *paPoslist position list are removed. If this
+** leaves 0 positions, zero is returned. Otherwise, non-zero.
+**
+** Before returning, *paPoslist is set to point to the position lsit
+** associated with pPhrase. And *pnToken is set to the number of tokens in
+** pPhrase.
+*/
+static int fts3EvalNearTrim(
+ int nNear, /* NEAR distance. As in "NEAR/nNear". */
+ char *aTmp, /* Temporary space to use */
+ char **paPoslist, /* IN/OUT: Position list */
+ int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
+ Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
+){
+ int nParam1 = nNear + pPhrase->nToken;
+ int nParam2 = nNear + *pnToken;
+ int nNew;
+ char *p2;
+ char *pOut;
+ int res;
+
+ assert( pPhrase->doclist.pList );
+
+ p2 = pOut = pPhrase->doclist.pList;
+ res = fts3PoslistNearMerge(
+ &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
+ );
+ if( res ){
+ nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
+ if( nNew>=0 ){
+ assert( pPhrase->doclist.pList[nNew]=='\0' );
+ assert( nNew<=pPhrase->doclist.nList && nNew>0 );
+ memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
+ pPhrase->doclist.nList = nNew;
+ }
+ *paPoslist = pPhrase->doclist.pList;
+ *pnToken = pPhrase->nToken;
+ }
+
+ return res;
+}
+
+/*
+** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
+** Otherwise, it advances the expression passed as the second argument to
+** point to the next matching row in the database. Expressions iterate through
+** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
+** or descending if it is non-zero.
+**
+** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
+** successful, the following variables in pExpr are set:
+**
+** Fts3Expr.bEof (non-zero if EOF - there is no next row)
+** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
+**
+** If the expression is of type FTSQUERY_PHRASE, and the expression is not
+** at EOF, then the following variables are populated with the position list
+** for the phrase for the visited row:
+**
+** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
+** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
+**
+** It says above that this function advances the expression to the next
+** matching row. This is usually true, but there are the following exceptions:
+**
+** 1. Deferred tokens are not taken into account. If a phrase consists
+** entirely of deferred tokens, it is assumed to match every row in
+** the db. In this case the position-list is not populated at all.
+**
+** Or, if a phrase contains one or more deferred tokens and one or
+** more non-deferred tokens, then the expression is advanced to the
+** next possible match, considering only non-deferred tokens. In other
+** words, if the phrase is "A B C", and "B" is deferred, the expression
+** is advanced to the next row that contains an instance of "A * C",
+** where "*" may match any single token. The position list in this case
+** is populated as for "A * C" before returning.
+**
+** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
+** advanced to point to the next row that matches "x AND y".
+**
+** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
+** really a match, taking into account deferred tokens and NEAR operators.
+*/
+static void fts3EvalNextRow(
+ Fts3Cursor *pCsr, /* FTS Cursor handle */
+ Fts3Expr *pExpr, /* Expr. to advance to next matching row */
+ int *pRc /* IN/OUT: Error code */
+){
+ if( *pRc==SQLITE_OK ){
+ int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
+ assert( pExpr->bEof==0 );
+ pExpr->bStart = 1;
+
+ switch( pExpr->eType ){
+ case FTSQUERY_NEAR:
+ case FTSQUERY_AND: {
+ Fts3Expr *pLeft = pExpr->pLeft;
+ Fts3Expr *pRight = pExpr->pRight;
+ assert( !pLeft->bDeferred || !pRight->bDeferred );
+
+ if( pLeft->bDeferred ){
+ /* LHS is entirely deferred. So we assume it matches every row.
+ ** Advance the RHS iterator to find the next row visited. */
+ fts3EvalNextRow(pCsr, pRight, pRc);
+ pExpr->iDocid = pRight->iDocid;
+ pExpr->bEof = pRight->bEof;
+ }else if( pRight->bDeferred ){
+ /* RHS is entirely deferred. So we assume it matches every row.
+ ** Advance the LHS iterator to find the next row visited. */
+ fts3EvalNextRow(pCsr, pLeft, pRc);
+ pExpr->iDocid = pLeft->iDocid;
+ pExpr->bEof = pLeft->bEof;
+ }else{
+ /* Neither the RHS or LHS are deferred. */
+ fts3EvalNextRow(pCsr, pLeft, pRc);
+ fts3EvalNextRow(pCsr, pRight, pRc);
+ while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
+ sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
+ if( iDiff==0 ) break;
+ if( iDiff<0 ){
+ fts3EvalNextRow(pCsr, pLeft, pRc);
+ }else{
+ fts3EvalNextRow(pCsr, pRight, pRc);
+ }
+ }
+ pExpr->iDocid = pLeft->iDocid;
+ pExpr->bEof = (pLeft->bEof || pRight->bEof);
+ if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
+ assert( pRight->eType==FTSQUERY_PHRASE );
+ if( pRight->pPhrase->doclist.aAll ){
+ Fts3Doclist *pDl = &pRight->pPhrase->doclist;
+ while( *pRc==SQLITE_OK && pRight->bEof==0 ){
+ memset(pDl->pList, 0, pDl->nList);
+ fts3EvalNextRow(pCsr, pRight, pRc);
+ }
+ }
+ if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
+ Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
+ while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
+ memset(pDl->pList, 0, pDl->nList);
+ fts3EvalNextRow(pCsr, pLeft, pRc);
+ }
+ }
+ pRight->bEof = pLeft->bEof = 1;
+ }
+ }
+ break;
+ }
+
+ case FTSQUERY_OR: {
+ Fts3Expr *pLeft = pExpr->pLeft;
+ Fts3Expr *pRight = pExpr->pRight;
+ sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
+
+ assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
+ assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
+
+ if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
+ fts3EvalNextRow(pCsr, pLeft, pRc);
+ }else if( pLeft->bEof || iCmp>0 ){
+ fts3EvalNextRow(pCsr, pRight, pRc);
+ }else{
+ fts3EvalNextRow(pCsr, pLeft, pRc);
+ fts3EvalNextRow(pCsr, pRight, pRc);
+ }
+
+ pExpr->bEof = (pLeft->bEof && pRight->bEof);
+ iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
+ if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
+ pExpr->iDocid = pLeft->iDocid;
+ }else{
+ pExpr->iDocid = pRight->iDocid;
+ }
+
+ break;
+ }
+
+ case FTSQUERY_NOT: {
+ Fts3Expr *pLeft = pExpr->pLeft;
+ Fts3Expr *pRight = pExpr->pRight;
+
+ if( pRight->bStart==0 ){
+ fts3EvalNextRow(pCsr, pRight, pRc);
+ assert( *pRc!=SQLITE_OK || pRight->bStart );
+ }
+
+ fts3EvalNextRow(pCsr, pLeft, pRc);
+ if( pLeft->bEof==0 ){
+ while( !*pRc
+ && !pRight->bEof
+ && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
+ ){
+ fts3EvalNextRow(pCsr, pRight, pRc);
+ }
+ }
+ pExpr->iDocid = pLeft->iDocid;
+ pExpr->bEof = pLeft->bEof;
+ break;
+ }
+
+ default: {
+ Fts3Phrase *pPhrase = pExpr->pPhrase;
+ fts3EvalInvalidatePoslist(pPhrase);
+ *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
+ pExpr->iDocid = pPhrase->doclist.iDocid;
+ break;
+ }
+ }
+ }
+}
+
+/*
+** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
+** cluster, then this function returns 1 immediately.
+**
+** Otherwise, it checks if the current row really does match the NEAR
+** expression, using the data currently stored in the position lists
+** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
+**
+** If the current row is a match, the position list associated with each
+** phrase in the NEAR expression is edited in place to contain only those
+** phrase instances sufficiently close to their peers to satisfy all NEAR
+** constraints. In this case it returns 1. If the NEAR expression does not
+** match the current row, 0 is returned. The position lists may or may not
+** be edited if 0 is returned.
+*/
+static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
+ int res = 1;
+
+ /* The following block runs if pExpr is the root of a NEAR query.
+ ** For example, the query:
+ **
+ ** "w" NEAR "x" NEAR "y" NEAR "z"
+ **
+ ** which is represented in tree form as:
+ **
+ ** |
+ ** +--NEAR--+ <-- root of NEAR query
+ ** | |
+ ** +--NEAR--+ "z"
+ ** | |
+ ** +--NEAR--+ "y"
+ ** | |
+ ** "w" "x"
+ **
+ ** The right-hand child of a NEAR node is always a phrase. The
+ ** left-hand child may be either a phrase or a NEAR node. There are
+ ** no exceptions to this - it's the way the parser in fts3_expr.c works.
+ */
+ if( *pRc==SQLITE_OK
+ && pExpr->eType==FTSQUERY_NEAR
+ && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
+ ){
+ Fts3Expr *p;
+ sqlite3_int64 nTmp = 0; /* Bytes of temp space */
+ char *aTmp; /* Temp space for PoslistNearMerge() */
+
+ /* Allocate temporary working space. */
+ for(p=pExpr; p->pLeft; p=p->pLeft){
+ assert( p->pRight->pPhrase->doclist.nList>0 );
+ nTmp += p->pRight->pPhrase->doclist.nList;
+ }
+ nTmp += p->pPhrase->doclist.nList;
+ aTmp = sqlite3_malloc64(nTmp*2);
+ if( !aTmp ){
+ *pRc = SQLITE_NOMEM;
+ res = 0;
+ }else{
+ char *aPoslist = p->pPhrase->doclist.pList;
+ int nToken = p->pPhrase->nToken;
+
+ for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
+ Fts3Phrase *pPhrase = p->pRight->pPhrase;
+ int nNear = p->nNear;
+ res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
+ }
+
+ aPoslist = pExpr->pRight->pPhrase->doclist.pList;
+ nToken = pExpr->pRight->pPhrase->nToken;
+ for(p=pExpr->pLeft; p && res; p=p->pLeft){
+ int nNear;
+ Fts3Phrase *pPhrase;
+ assert( p->pParent && p->pParent->pLeft==p );
+ nNear = p->pParent->nNear;
+ pPhrase = (
+ p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
+ );
+ res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
+ }
+ }
+
+ sqlite3_free(aTmp);
+ }
+
+ return res;
+}
+
+/*
+** This function is a helper function for sqlite3Fts3EvalTestDeferred().
+** Assuming no error occurs or has occurred, It returns non-zero if the
+** expression passed as the second argument matches the row that pCsr
+** currently points to, or zero if it does not.
+**
+** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
+** If an error occurs during execution of this function, *pRc is set to
+** the appropriate SQLite error code. In this case the returned value is
+** undefined.
+*/
+static int fts3EvalTestExpr(
+ Fts3Cursor *pCsr, /* FTS cursor handle */
+ Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
+ int *pRc /* IN/OUT: Error code */
+){
+ int bHit = 1; /* Return value */
+ if( *pRc==SQLITE_OK ){
+ switch( pExpr->eType ){
+ case FTSQUERY_NEAR:
+ case FTSQUERY_AND:
+ bHit = (
+ fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
+ && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
+ && fts3EvalNearTest(pExpr, pRc)
+ );
+
+ /* If the NEAR expression does not match any rows, zero the doclist for
+ ** all phrases involved in the NEAR. This is because the snippet(),
+ ** offsets() and matchinfo() functions are not supposed to recognize
+ ** any instances of phrases that are part of unmatched NEAR queries.
+ ** For example if this expression:
+ **
+ ** ... MATCH 'a OR (b NEAR c)'
+ **
+ ** is matched against a row containing:
+ **
+ ** 'a b d e'
+ **
+ ** then any snippet() should ony highlight the "a" term, not the "b"
+ ** (as "b" is part of a non-matching NEAR clause).
+ */
+ if( bHit==0
+ && pExpr->eType==FTSQUERY_NEAR
+ && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
+ ){
+ Fts3Expr *p;
+ for(p=pExpr; p->pPhrase==0; p=p->pLeft){
+ if( p->pRight->iDocid==pCsr->iPrevId ){
+ fts3EvalInvalidatePoslist(p->pRight->pPhrase);
+ }
+ }
+ if( p->iDocid==pCsr->iPrevId ){
+ fts3EvalInvalidatePoslist(p->pPhrase);
+ }
+ }
+
+ break;
+
+ case FTSQUERY_OR: {
+ int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
+ int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
+ bHit = bHit1 || bHit2;
+ break;
+ }
+
+ case FTSQUERY_NOT:
+ bHit = (
+ fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
+ && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
+ );
+ break;
+
+ default: {
+#ifndef SQLITE_DISABLE_FTS4_DEFERRED
+ if( pCsr->pDeferred
+ && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
+ ){
+ Fts3Phrase *pPhrase = pExpr->pPhrase;
+ assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
+ if( pExpr->bDeferred ){
+ fts3EvalInvalidatePoslist(pPhrase);
+ }
+ *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
+ bHit = (pPhrase->doclist.pList!=0);
+ pExpr->iDocid = pCsr->iPrevId;
+ }else
+#endif
+ {
+ bHit = (
+ pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId
+ && pExpr->pPhrase->doclist.nList>0
+ );
+ }
+ break;
+ }
+ }
+ }
+ return bHit;
+}
+
+/*
+** This function is called as the second part of each xNext operation when
+** iterating through the results of a full-text query. At this point the
+** cursor points to a row that matches the query expression, with the
+** following caveats:
+**
+** * Up until this point, "NEAR" operators in the expression have been
+** treated as "AND".
+**
+** * Deferred tokens have not yet been considered.
+**
+** If *pRc is not SQLITE_OK when this function is called, it immediately
+** returns 0. Otherwise, it tests whether or not after considering NEAR
+** operators and deferred tokens the current row is still a match for the
+** expression. It returns 1 if both of the following are true:
+**
+** 1. *pRc is SQLITE_OK when this function returns, and
+**
+** 2. After scanning the current FTS table row for the deferred tokens,
+** it is determined that the row does *not* match the query.
+**
+** Or, if no error occurs and it seems the current row does match the FTS
+** query, return 0.
+*/
+SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
+ int rc = *pRc;
+ int bMiss = 0;
+ if( rc==SQLITE_OK ){
+
+ /* If there are one or more deferred tokens, load the current row into
+ ** memory and scan it to determine the position list for each deferred
+ ** token. Then, see if this row is really a match, considering deferred
+ ** tokens and NEAR operators (neither of which were taken into account
+ ** earlier, by fts3EvalNextRow()).
+ */
+ if( pCsr->pDeferred ){
+ rc = fts3CursorSeek(0, pCsr);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
+ }
+ }
+ bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
+
+ /* Free the position-lists accumulated for each deferred token above. */
+ sqlite3Fts3FreeDeferredDoclists(pCsr);
+ *pRc = rc;
+ }
+ return (rc==SQLITE_OK && bMiss);
+}
+
+/*
+** Advance to the next document that matches the FTS expression in
+** Fts3Cursor.pExpr.
+*/
+static int fts3EvalNext(Fts3Cursor *pCsr){
+ int rc = SQLITE_OK; /* Return Code */
+ Fts3Expr *pExpr = pCsr->pExpr;
+ assert( pCsr->isEof==0 );
+ if( pExpr==0 ){
+ pCsr->isEof = 1;
+ }else{
+ do {
+ if( pCsr->isRequireSeek==0 ){
+ sqlite3_reset(pCsr->pStmt);
+ }
+ assert( sqlite3_data_count(pCsr->pStmt)==0 );
+ fts3EvalNextRow(pCsr, pExpr, &rc);
+ pCsr->isEof = pExpr->bEof;
+ pCsr->isRequireSeek = 1;
+ pCsr->isMatchinfoNeeded = 1;
+ pCsr->iPrevId = pExpr->iDocid;
+ }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
+ }
+
+ /* Check if the cursor is past the end of the docid range specified
+ ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
+ if( rc==SQLITE_OK && (
+ (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
+ || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
+ )){
+ pCsr->isEof = 1;
+ }
+
+ return rc;
+}
+
+/*
+** Restart interation for expression pExpr so that the next call to
+** fts3EvalNext() visits the first row. Do not allow incremental
+** loading or merging of phrase doclists for this iteration.
+**
+** If *pRc is other than SQLITE_OK when this function is called, it is
+** a no-op. If an error occurs within this function, *pRc is set to an
+** SQLite error code before returning.
+*/
+static void fts3EvalRestart(
+ Fts3Cursor *pCsr,
+ Fts3Expr *pExpr,
+ int *pRc
+){
+ if( pExpr && *pRc==SQLITE_OK ){
+ Fts3Phrase *pPhrase = pExpr->pPhrase;
+
+ if( pPhrase ){
+ fts3EvalInvalidatePoslist(pPhrase);
+ if( pPhrase->bIncr ){
+ int i;
+ for(i=0; i<pPhrase->nToken; i++){
+ Fts3PhraseToken *pToken = &pPhrase->aToken[i];
+ assert( pToken->pDeferred==0 );
+ if( pToken->pSegcsr ){
+ sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
+ }
+ }
+ *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
+ }
+ pPhrase->doclist.pNextDocid = 0;
+ pPhrase->doclist.iDocid = 0;
+ pPhrase->pOrPoslist = 0;
+ }
+
+ pExpr->iDocid = 0;
+ pExpr->bEof = 0;
+ pExpr->bStart = 0;
+
+ fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
+ fts3EvalRestart(pCsr, pExpr->pRight, pRc);
+ }
+}
+
+/*
+** After allocating the Fts3Expr.aMI[] array for each phrase in the
+** expression rooted at pExpr, the cursor iterates through all rows matched
+** by pExpr, calling this function for each row. This function increments
+** the values in Fts3Expr.aMI[] according to the position-list currently
+** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
+** expression nodes.
+*/
+static void fts3EvalUpdateCounts(Fts3Expr *pExpr, int nCol){
+ if( pExpr ){
+ Fts3Phrase *pPhrase = pExpr->pPhrase;
+ if( pPhrase && pPhrase->doclist.pList ){
+ int iCol = 0;
+ char *p = pPhrase->doclist.pList;
+
+ do{
+ u8 c = 0;
+ int iCnt = 0;
+ while( 0xFE & (*p | c) ){
+ if( (c&0x80)==0 ) iCnt++;
+ c = *p++ & 0x80;
+ }
+
+ /* aMI[iCol*3 + 1] = Number of occurrences
+ ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
+ */
+ pExpr->aMI[iCol*3 + 1] += iCnt;
+ pExpr->aMI[iCol*3 + 2] += (iCnt>0);
+ if( *p==0x00 ) break;
+ p++;
+ p += fts3GetVarint32(p, &iCol);
+ }while( iCol<nCol );
+ }
+
+ fts3EvalUpdateCounts(pExpr->pLeft, nCol);
+ fts3EvalUpdateCounts(pExpr->pRight, nCol);
+ }
+}
+
+/*
+** Expression pExpr must be of type FTSQUERY_PHRASE.
+**
+** If it is not already allocated and populated, this function allocates and
+** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
+** of a NEAR expression, then it also allocates and populates the same array
+** for all other phrases that are part of the NEAR expression.
+**
+** SQLITE_OK is returned if the aMI[] array is successfully allocated and
+** populated. Otherwise, if an error occurs, an SQLite error code is returned.
+*/
+static int fts3EvalGatherStats(
+ Fts3Cursor *pCsr, /* Cursor object */
+ Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
+){
+ int rc = SQLITE_OK; /* Return code */
+
+ assert( pExpr->eType==FTSQUERY_PHRASE );
+ if( pExpr->aMI==0 ){
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+ Fts3Expr *pRoot; /* Root of NEAR expression */
+ Fts3Expr *p; /* Iterator used for several purposes */
+
+ sqlite3_int64 iPrevId = pCsr->iPrevId;
+ sqlite3_int64 iDocid;
+ u8 bEof;
+
+ /* Find the root of the NEAR expression */
+ pRoot = pExpr;
+ while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
+ pRoot = pRoot->pParent;
+ }
+ iDocid = pRoot->iDocid;
+ bEof = pRoot->bEof;
+ assert( pRoot->bStart );
+
+ /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
+ for(p=pRoot; p; p=p->pLeft){
+ Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
+ assert( pE->aMI==0 );
+ pE->aMI = (u32 *)sqlite3_malloc64(pTab->nColumn * 3 * sizeof(u32));
+ if( !pE->aMI ) return SQLITE_NOMEM;
+ memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
+ }
+
+ fts3EvalRestart(pCsr, pRoot, &rc);
+
+ while( pCsr->isEof==0 && rc==SQLITE_OK ){
+
+ do {
+ /* Ensure the %_content statement is reset. */
+ if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
+ assert( sqlite3_data_count(pCsr->pStmt)==0 );
+
+ /* Advance to the next document */
+ fts3EvalNextRow(pCsr, pRoot, &rc);
+ pCsr->isEof = pRoot->bEof;
+ pCsr->isRequireSeek = 1;
+ pCsr->isMatchinfoNeeded = 1;
+ pCsr->iPrevId = pRoot->iDocid;
+ }while( pCsr->isEof==0
+ && pRoot->eType==FTSQUERY_NEAR
+ && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
+ );
+
+ if( rc==SQLITE_OK && pCsr->isEof==0 ){
+ fts3EvalUpdateCounts(pRoot, pTab->nColumn);
+ }
+ }
+
+ pCsr->isEof = 0;
+ pCsr->iPrevId = iPrevId;
+
+ if( bEof ){
+ pRoot->bEof = bEof;
+ }else{
+ /* Caution: pRoot may iterate through docids in ascending or descending
+ ** order. For this reason, even though it seems more defensive, the
+ ** do loop can not be written:
+ **
+ ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
+ */
+ fts3EvalRestart(pCsr, pRoot, &rc);
+ do {
+ fts3EvalNextRow(pCsr, pRoot, &rc);
+ assert_fts3_nc( pRoot->bEof==0 );
+ if( pRoot->bEof ) rc = FTS_CORRUPT_VTAB;
+ }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
+ }
+ }
+ return rc;
+}
+
+/*
+** This function is used by the matchinfo() module to query a phrase
+** expression node for the following information:
+**
+** 1. The total number of occurrences of the phrase in each column of
+** the FTS table (considering all rows), and
+**
+** 2. For each column, the number of rows in the table for which the
+** column contains at least one instance of the phrase.
+**
+** If no error occurs, SQLITE_OK is returned and the values for each column
+** written into the array aiOut as follows:
+**
+** aiOut[iCol*3 + 1] = Number of occurrences
+** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
+**
+** Caveats:
+**
+** * If a phrase consists entirely of deferred tokens, then all output
+** values are set to the number of documents in the table. In other
+** words we assume that very common tokens occur exactly once in each
+** column of each row of the table.
+**
+** * If a phrase contains some deferred tokens (and some non-deferred
+** tokens), count the potential occurrence identified by considering
+** the non-deferred tokens instead of actual phrase occurrences.
+**
+** * If the phrase is part of a NEAR expression, then only phrase instances
+** that meet the NEAR constraint are included in the counts.
+*/
+SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
+ Fts3Cursor *pCsr, /* FTS cursor handle */
+ Fts3Expr *pExpr, /* Phrase expression */
+ u32 *aiOut /* Array to write results into (see above) */
+){
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+ int rc = SQLITE_OK;
+ int iCol;
+
+ if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
+ assert( pCsr->nDoc>0 );
+ for(iCol=0; iCol<pTab->nColumn; iCol++){
+ aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
+ aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
+ }
+ }else{
+ rc = fts3EvalGatherStats(pCsr, pExpr);
+ if( rc==SQLITE_OK ){
+ assert( pExpr->aMI );
+ for(iCol=0; iCol<pTab->nColumn; iCol++){
+ aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
+ aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
+ }
+ }
+ }
+
+ return rc;
+}
+
+/*
+** The expression pExpr passed as the second argument to this function
+** must be of type FTSQUERY_PHRASE.
+**
+** The returned value is either NULL or a pointer to a buffer containing
+** a position-list indicating the occurrences of the phrase in column iCol
+** of the current row.
+**
+** More specifically, the returned buffer contains 1 varint for each
+** occurrence of the phrase in the column, stored using the normal (delta+2)
+** compression and is terminated by either an 0x01 or 0x00 byte. For example,
+** if the requested column contains "a b X c d X X" and the position-list
+** for 'X' is requested, the buffer returned may contain:
+**
+** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
+**
+** This function works regardless of whether or not the phrase is deferred,
+** incremental, or neither.
+*/
+SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
+ Fts3Cursor *pCsr, /* FTS3 cursor object */
+ Fts3Expr *pExpr, /* Phrase to return doclist for */
+ int iCol, /* Column to return position list for */
+ char **ppOut /* OUT: Pointer to position list */
+){
+ Fts3Phrase *pPhrase = pExpr->pPhrase;
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+ char *pIter;
+ int iThis;
+ sqlite3_int64 iDocid;
+
+ /* If this phrase is applies specifically to some column other than
+ ** column iCol, return a NULL pointer. */
+ *ppOut = 0;
+ assert( iCol>=0 && iCol<pTab->nColumn );
+ if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
+ return SQLITE_OK;
+ }
+
+ iDocid = pExpr->iDocid;
+ pIter = pPhrase->doclist.pList;
+ if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
+ int rc = SQLITE_OK;
+ int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
+ int bOr = 0;
+ u8 bTreeEof = 0;
+ Fts3Expr *p; /* Used to iterate from pExpr to root */
+ Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
+ int bMatch;
+
+ /* Check if this phrase descends from an OR expression node. If not,
+ ** return NULL. Otherwise, the entry that corresponds to docid
+ ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
+ ** tree that the node is part of has been marked as EOF, but the node
+ ** itself is not EOF, then it may point to an earlier entry. */
+ pNear = pExpr;
+ for(p=pExpr->pParent; p; p=p->pParent){
+ if( p->eType==FTSQUERY_OR ) bOr = 1;
+ if( p->eType==FTSQUERY_NEAR ) pNear = p;
+ if( p->bEof ) bTreeEof = 1;
+ }
+ if( bOr==0 ) return SQLITE_OK;
+
+ /* This is the descendent of an OR node. In this case we cannot use
+ ** an incremental phrase. Load the entire doclist for the phrase
+ ** into memory in this case. */
+ if( pPhrase->bIncr ){
+ int bEofSave = pNear->bEof;
+ fts3EvalRestart(pCsr, pNear, &rc);
+ while( rc==SQLITE_OK && !pNear->bEof ){
+ fts3EvalNextRow(pCsr, pNear, &rc);
+ if( bEofSave==0 && pNear->iDocid==iDocid ) break;
+ }
+ assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
+ }
+ if( bTreeEof ){
+ while( rc==SQLITE_OK && !pNear->bEof ){
+ fts3EvalNextRow(pCsr, pNear, &rc);
+ }
+ }
+ if( rc!=SQLITE_OK ) return rc;
+
+ bMatch = 1;
+ for(p=pNear; p; p=p->pLeft){
+ u8 bEof = 0;
+ Fts3Expr *pTest = p;
+ Fts3Phrase *pPh;
+ assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
+ if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
+ assert( pTest->eType==FTSQUERY_PHRASE );
+ pPh = pTest->pPhrase;
+
+ pIter = pPh->pOrPoslist;
+ iDocid = pPh->iOrDocid;
+ if( pCsr->bDesc==bDescDoclist ){
+ bEof = !pPh->doclist.nAll ||
+ (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
+ while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
+ sqlite3Fts3DoclistNext(
+ bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
+ &pIter, &iDocid, &bEof
+ );
+ }
+ }else{
+ bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
+ while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
+ int dummy;
+ sqlite3Fts3DoclistPrev(
+ bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
+ &pIter, &iDocid, &dummy, &bEof
+ );
+ }
+ }
+ pPh->pOrPoslist = pIter;
+ pPh->iOrDocid = iDocid;
+ if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
+ }
+
+ if( bMatch ){
+ pIter = pPhrase->pOrPoslist;
+ }else{
+ pIter = 0;
+ }
+ }
+ if( pIter==0 ) return SQLITE_OK;
+
+ if( *pIter==0x01 ){
+ pIter++;
+ pIter += fts3GetVarint32(pIter, &iThis);
+ }else{
+ iThis = 0;
+ }
+ while( iThis<iCol ){
+ fts3ColumnlistCopy(0, &pIter);
+ if( *pIter==0x00 ) return SQLITE_OK;
+ pIter++;
+ pIter += fts3GetVarint32(pIter, &iThis);
+ }
+ if( *pIter==0x00 ){
+ pIter = 0;
+ }
+
+ *ppOut = ((iCol==iThis)?pIter:0);
+ return SQLITE_OK;
+}
+
+/*
+** Free all components of the Fts3Phrase structure that were allocated by
+** the eval module. Specifically, this means to free:
+**
+** * the contents of pPhrase->doclist, and
+** * any Fts3MultiSegReader objects held by phrase tokens.
+*/
+SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
+ if( pPhrase ){
+ int i;
+ sqlite3_free(pPhrase->doclist.aAll);
+ fts3EvalInvalidatePoslist(pPhrase);
+ memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
+ for(i=0; i<pPhrase->nToken; i++){
+ fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
+ pPhrase->aToken[i].pSegcsr = 0;
+ }
+ }
+}
+
+
+/*
+** Return SQLITE_CORRUPT_VTAB.
+*/
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
+ return SQLITE_CORRUPT_VTAB;
+}
+#endif
+
+#if !SQLITE_CORE
+/*
+** Initialize API pointer table, if required.
+*/
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+SQLITE_API int sqlite3_fts3_init(
+ sqlite3 *db,
+ char **pzErrMsg,
+ const sqlite3_api_routines *pApi
+){
+ SQLITE_EXTENSION_INIT2(pApi)
+ return sqlite3Fts3Init(db);
+}
+#endif
+
+#endif
+
+/************** End of fts3.c ************************************************/
+/************** Begin file fts3_aux.c ****************************************/
+/*
+** 2011 Jan 27
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+*/
+/* #include "fts3Int.h" */
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
+
+/* #include <string.h> */
+/* #include <assert.h> */
+
+typedef struct Fts3auxTable Fts3auxTable;
+typedef struct Fts3auxCursor Fts3auxCursor;
+
+struct Fts3auxTable {
+ sqlite3_vtab base; /* Base class used by SQLite core */
+ Fts3Table *pFts3Tab;
+};
+
+struct Fts3auxCursor {
+ sqlite3_vtab_cursor base; /* Base class used by SQLite core */
+ Fts3MultiSegReader csr; /* Must be right after "base" */
+ Fts3SegFilter filter;
+ char *zStop;
+ int nStop; /* Byte-length of string zStop */
+ int iLangid; /* Language id to query */
+ int isEof; /* True if cursor is at EOF */
+ sqlite3_int64 iRowid; /* Current rowid */
+
+ int iCol; /* Current value of 'col' column */
+ int nStat; /* Size of aStat[] array */
+ struct Fts3auxColstats {
+ sqlite3_int64 nDoc; /* 'documents' values for current csr row */
+ sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
+ } *aStat;
+};
+
+/*
+** Schema of the terms table.
+*/
+#define FTS3_AUX_SCHEMA \
+ "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
+
+/*
+** This function does all the work for both the xConnect and xCreate methods.
+** These tables have no persistent representation of their own, so xConnect
+** and xCreate are identical operations.
+*/
+static int fts3auxConnectMethod(
+ sqlite3 *db, /* Database connection */
+ void *pUnused, /* Unused */
+ int argc, /* Number of elements in argv array */
+ const char * const *argv, /* xCreate/xConnect argument array */
+ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
+ char **pzErr /* OUT: sqlite3_malloc'd error message */
+){
+ char const *zDb; /* Name of database (e.g. "main") */
+ char const *zFts3; /* Name of fts3 table */
+ int nDb; /* Result of strlen(zDb) */
+ int nFts3; /* Result of strlen(zFts3) */
+ sqlite3_int64 nByte; /* Bytes of space to allocate here */
+ int rc; /* value returned by declare_vtab() */
+ Fts3auxTable *p; /* Virtual table object to return */
+
+ UNUSED_PARAMETER(pUnused);
+
+ /* The user should invoke this in one of two forms:
+ **
+ ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
+ ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
+ */
+ if( argc!=4 && argc!=5 ) goto bad_args;
+
+ zDb = argv[1];
+ nDb = (int)strlen(zDb);
+ if( argc==5 ){
+ if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
+ zDb = argv[3];
+ nDb = (int)strlen(zDb);
+ zFts3 = argv[4];
+ }else{
+ goto bad_args;
+ }
+ }else{
+ zFts3 = argv[3];
+ }
+ nFts3 = (int)strlen(zFts3);
+
+ rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
+ if( rc!=SQLITE_OK ) return rc;
+
+ nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
+ p = (Fts3auxTable *)sqlite3_malloc64(nByte);
+ if( !p ) return SQLITE_NOMEM;
+ memset(p, 0, nByte);
+
+ p->pFts3Tab = (Fts3Table *)&p[1];
+ p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
+ p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
+ p->pFts3Tab->db = db;
+ p->pFts3Tab->nIndex = 1;
+
+ memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
+ memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
+ sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
+
+ *ppVtab = (sqlite3_vtab *)p;
+ return SQLITE_OK;
+
+ bad_args:
+ sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
+ return SQLITE_ERROR;
+}
+
+/*
+** This function does the work for both the xDisconnect and xDestroy methods.
+** These tables have no persistent representation of their own, so xDisconnect
+** and xDestroy are identical operations.
+*/
+static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
+ Fts3auxTable *p = (Fts3auxTable *)pVtab;
+ Fts3Table *pFts3 = p->pFts3Tab;
+ int i;
+
+ /* Free any prepared statements held */
+ for(i=0; i<SizeofArray(pFts3->aStmt); i++){
+ sqlite3_finalize(pFts3->aStmt[i]);
+ }
+ sqlite3_free(pFts3->zSegmentsTbl);
+ sqlite3_free(p);
+ return SQLITE_OK;
+}
+
+#define FTS4AUX_EQ_CONSTRAINT 1
+#define FTS4AUX_GE_CONSTRAINT 2
+#define FTS4AUX_LE_CONSTRAINT 4
+
+/*
+** xBestIndex - Analyze a WHERE and ORDER BY clause.
+*/
+static int fts3auxBestIndexMethod(
+ sqlite3_vtab *pVTab,
+ sqlite3_index_info *pInfo
+){
+ int i;
+ int iEq = -1;
+ int iGe = -1;
+ int iLe = -1;
+ int iLangid = -1;
+ int iNext = 1; /* Next free argvIndex value */
+
+ UNUSED_PARAMETER(pVTab);
+
+ /* This vtab delivers always results in "ORDER BY term ASC" order. */
+ if( pInfo->nOrderBy==1
+ && pInfo->aOrderBy[0].iColumn==0
+ && pInfo->aOrderBy[0].desc==0
+ ){
+ pInfo->orderByConsumed = 1;
+ }
+
+ /* Search for equality and range constraints on the "term" column.
+ ** And equality constraints on the hidden "languageid" column. */
+ for(i=0; i<pInfo->nConstraint; i++){
+ if( pInfo->aConstraint[i].usable ){
+ int op = pInfo->aConstraint[i].op;
+ int iCol = pInfo->aConstraint[i].iColumn;
+
+ if( iCol==0 ){
+ if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
+ if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
+ if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
+ if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
+ if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
+ }
+ if( iCol==4 ){
+ if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
+ }
+ }
+ }
+
+ if( iEq>=0 ){
+ pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
+ pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
+ pInfo->estimatedCost = 5;
+ }else{
+ pInfo->idxNum = 0;
+ pInfo->estimatedCost = 20000;
+ if( iGe>=0 ){
+ pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
+ pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
+ pInfo->estimatedCost /= 2;
+ }
+ if( iLe>=0 ){
+ pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
+ pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
+ pInfo->estimatedCost /= 2;
+ }
+ }
+ if( iLangid>=0 ){
+ pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
+ pInfo->estimatedCost--;
+ }
+
+ return SQLITE_OK;
+}
+
+/*
+** xOpen - Open a cursor.
+*/
+static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
+ Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
+
+ UNUSED_PARAMETER(pVTab);
+
+ pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
+ if( !pCsr ) return SQLITE_NOMEM;
+ memset(pCsr, 0, sizeof(Fts3auxCursor));
+
+ *ppCsr = (sqlite3_vtab_cursor *)pCsr;
+ return SQLITE_OK;
+}
+
+/*
+** xClose - Close a cursor.
+*/
+static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
+ Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
+ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
+
+ sqlite3Fts3SegmentsClose(pFts3);
+ sqlite3Fts3SegReaderFinish(&pCsr->csr);
+ sqlite3_free((void *)pCsr->filter.zTerm);
+ sqlite3_free(pCsr->zStop);
+ sqlite3_free(pCsr->aStat);
+ sqlite3_free(pCsr);
+ return SQLITE_OK;
+}
+
+static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
+ if( nSize>pCsr->nStat ){
+ struct Fts3auxColstats *aNew;
+ aNew = (struct Fts3auxColstats *)sqlite3_realloc64(pCsr->aStat,
+ sizeof(struct Fts3auxColstats) * nSize
+ );
+ if( aNew==0 ) return SQLITE_NOMEM;
+ memset(&aNew[pCsr->nStat], 0,
+ sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
+ );
+ pCsr->aStat = aNew;
+ pCsr->nStat = nSize;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** xNext - Advance the cursor to the next row, if any.
+*/
+static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
+ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
+ Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
+ int rc;
+
+ /* Increment our pretend rowid value. */
+ pCsr->iRowid++;
+
+ for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
+ if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
+ }
+
+ rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
+ if( rc==SQLITE_ROW ){
+ int i = 0;
+ int nDoclist = pCsr->csr.nDoclist;
+ char *aDoclist = pCsr->csr.aDoclist;
+ int iCol;
+
+ int eState = 0;
+
+ if( pCsr->zStop ){
+ int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
+ int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
+ if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
+ pCsr->isEof = 1;
+ return SQLITE_OK;
+ }
+ }
+
+ if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
+ memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
+ iCol = 0;
+
+ while( i<nDoclist ){
+ sqlite3_int64 v = 0;
+
+ i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
+ switch( eState ){
+ /* State 0. In this state the integer just read was a docid. */
+ case 0:
+ pCsr->aStat[0].nDoc++;
+ eState = 1;
+ iCol = 0;
+ break;
+
+ /* State 1. In this state we are expecting either a 1, indicating
+ ** that the following integer will be a column number, or the
+ ** start of a position list for column 0.
+ **
+ ** The only difference between state 1 and state 2 is that if the
+ ** integer encountered in state 1 is not 0 or 1, then we need to
+ ** increment the column 0 "nDoc" count for this term.
+ */
+ case 1:
+ assert( iCol==0 );
+ if( v>1 ){
+ pCsr->aStat[1].nDoc++;
+ }
+ eState = 2;
+ /* fall through */
+
+ case 2:
+ if( v==0 ){ /* 0x00. Next integer will be a docid. */
+ eState = 0;
+ }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
+ eState = 3;
+ }else{ /* 2 or greater. A position. */
+ pCsr->aStat[iCol+1].nOcc++;
+ pCsr->aStat[0].nOcc++;
+ }
+ break;
+
+ /* State 3. The integer just read is a column number. */
+ default: assert( eState==3 );
+ iCol = (int)v;
+ if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
+ pCsr->aStat[iCol+1].nDoc++;
+ eState = 2;
+ break;
+ }
+ }
+
+ pCsr->iCol = 0;
+ rc = SQLITE_OK;
+ }else{
+ pCsr->isEof = 1;
+ }
+ return rc;
+}
+
+/*
+** xFilter - Initialize a cursor to point at the start of its data.
+*/
+static int fts3auxFilterMethod(
+ sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
+ int idxNum, /* Strategy index */
+ const char *idxStr, /* Unused */
+ int nVal, /* Number of elements in apVal */
+ sqlite3_value **apVal /* Arguments for the indexing scheme */
+){
+ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
+ Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
+ int rc;
+ int isScan = 0;
+ int iLangVal = 0; /* Language id to query */
+
+ int iEq = -1; /* Index of term=? value in apVal */
+ int iGe = -1; /* Index of term>=? value in apVal */
+ int iLe = -1; /* Index of term<=? value in apVal */
+ int iLangid = -1; /* Index of languageid=? value in apVal */
+ int iNext = 0;
+
+ UNUSED_PARAMETER(nVal);
+ UNUSED_PARAMETER(idxStr);
+
+ assert( idxStr==0 );
+ assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
+ || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
+ || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
+ );
+
+ if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
+ iEq = iNext++;
+ }else{
+ isScan = 1;
+ if( idxNum & FTS4AUX_GE_CONSTRAINT ){
+ iGe = iNext++;
+ }
+ if( idxNum & FTS4AUX_LE_CONSTRAINT ){
+ iLe = iNext++;
+ }
+ }
+ if( iNext<nVal ){
+ iLangid = iNext++;
+ }
+
+ /* In case this cursor is being reused, close and zero it. */
+ testcase(pCsr->filter.zTerm);
+ sqlite3Fts3SegReaderFinish(&pCsr->csr);
+ sqlite3_free((void *)pCsr->filter.zTerm);
+ sqlite3_free(pCsr->aStat);
+ memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
+
+ pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
+ if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
+
+ if( iEq>=0 || iGe>=0 ){
+ const unsigned char *zStr = sqlite3_value_text(apVal[0]);
+ assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
+ if( zStr ){
+ pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
+ if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
+ pCsr->filter.nTerm = (int)strlen(pCsr->filter.zTerm);
+ }
+ }
+
+ if( iLe>=0 ){
+ pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
+ if( pCsr->zStop==0 ) return SQLITE_NOMEM;
+ pCsr->nStop = (int)strlen(pCsr->zStop);
+ }
+
+ if( iLangid>=0 ){
+ iLangVal = sqlite3_value_int(apVal[iLangid]);
+
+ /* If the user specified a negative value for the languageid, use zero
+ ** instead. This works, as the "languageid=?" constraint will also
+ ** be tested by the VDBE layer. The test will always be false (since
+ ** this module will not return a row with a negative languageid), and
+ ** so the overall query will return zero rows. */
+ if( iLangVal<0 ) iLangVal = 0;
+ }
+ pCsr->iLangid = iLangVal;
+
+ rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
+ pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
+ );
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
+ }
+
+ if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
+ return rc;
+}
+
+/*
+** xEof - Return true if the cursor is at EOF, or false otherwise.
+*/
+static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
+ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
+ return pCsr->isEof;
+}
+
+/*
+** xColumn - Return a column value.
+*/
+static int fts3auxColumnMethod(
+ sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
+ sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
+ int iCol /* Index of column to read value from */
+){
+ Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
+
+ assert( p->isEof==0 );
+ switch( iCol ){
+ case 0: /* term */
+ sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
+ break;
+
+ case 1: /* col */
+ if( p->iCol ){
+ sqlite3_result_int(pCtx, p->iCol-1);
+ }else{
+ sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
+ }
+ break;
+
+ case 2: /* documents */
+ sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
+ break;
+
+ case 3: /* occurrences */
+ sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
+ break;
+
+ default: /* languageid */
+ assert( iCol==4 );
+ sqlite3_result_int(pCtx, p->iLangid);
+ break;
+ }
+
+ return SQLITE_OK;
+}
+
+/*
+** xRowid - Return the current rowid for the cursor.
+*/
+static int fts3auxRowidMethod(
+ sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
+ sqlite_int64 *pRowid /* OUT: Rowid value */
+){
+ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
+ *pRowid = pCsr->iRowid;
+ return SQLITE_OK;
+}
+
+/*
+** Register the fts3aux module with database connection db. Return SQLITE_OK
+** if successful or an error code if sqlite3_create_module() fails.
+*/
+SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
+ static const sqlite3_module fts3aux_module = {
+ 0, /* iVersion */
+ fts3auxConnectMethod, /* xCreate */
+ fts3auxConnectMethod, /* xConnect */
+ fts3auxBestIndexMethod, /* xBestIndex */
+ fts3auxDisconnectMethod, /* xDisconnect */
+ fts3auxDisconnectMethod, /* xDestroy */
+ fts3auxOpenMethod, /* xOpen */
+ fts3auxCloseMethod, /* xClose */
+ fts3auxFilterMethod, /* xFilter */
+ fts3auxNextMethod, /* xNext */
+ fts3auxEofMethod, /* xEof */
+ fts3auxColumnMethod, /* xColumn */
+ fts3auxRowidMethod, /* xRowid */
+ 0, /* xUpdate */
+ 0, /* xBegin */
+ 0, /* xSync */
+ 0, /* xCommit */
+ 0, /* xRollback */
+ 0, /* xFindFunction */
+ 0, /* xRename */
+ 0, /* xSavepoint */
+ 0, /* xRelease */
+ 0, /* xRollbackTo */
+ 0 /* xShadowName */
+ };
+ int rc; /* Return code */
+
+ rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
+ return rc;
+}
+
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
+
+/************** End of fts3_aux.c ********************************************/
+/************** Begin file fts3_expr.c ***************************************/
+/*
+** 2008 Nov 28
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This module contains code that implements a parser for fts3 query strings
+** (the right-hand argument to the MATCH operator). Because the supported
+** syntax is relatively simple, the whole tokenizer/parser system is
+** hand-coded.
+*/
+/* #include "fts3Int.h" */
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
+
+/*
+** By default, this module parses the legacy syntax that has been
+** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
+** is defined, then it uses the new syntax. The differences between
+** the new and the old syntaxes are:
+**
+** a) The new syntax supports parenthesis. The old does not.
+**
+** b) The new syntax supports the AND and NOT operators. The old does not.
+**
+** c) The old syntax supports the "-" token qualifier. This is not
+** supported by the new syntax (it is replaced by the NOT operator).
+**
+** d) When using the old syntax, the OR operator has a greater precedence
+** than an implicit AND. When using the new, both implicity and explicit
+** AND operators have a higher precedence than OR.
+**
+** If compiled with SQLITE_TEST defined, then this module exports the
+** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
+** to zero causes the module to use the old syntax. If it is set to
+** non-zero the new syntax is activated. This is so both syntaxes can
+** be tested using a single build of testfixture.
+**
+** The following describes the syntax supported by the fts3 MATCH
+** operator in a similar format to that used by the lemon parser
+** generator. This module does not use actually lemon, it uses a
+** custom parser.
+**
+** query ::= andexpr (OR andexpr)*.
+**
+** andexpr ::= notexpr (AND? notexpr)*.
+**
+** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
+** notexpr ::= LP query RP.
+**
+** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
+**
+** distance_opt ::= .
+** distance_opt ::= / INTEGER.
+**
+** phrase ::= TOKEN.
+** phrase ::= COLUMN:TOKEN.
+** phrase ::= "TOKEN TOKEN TOKEN...".
+*/
+
+#ifdef SQLITE_TEST
+SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
+#else
+# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
+# define sqlite3_fts3_enable_parentheses 1
+# else
+# define sqlite3_fts3_enable_parentheses 0
+# endif
+#endif
+
+/*
+** Default span for NEAR operators.
+*/
+#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
+
+/* #include <string.h> */
+/* #include <assert.h> */
+
+/*
+** isNot:
+** This variable is used by function getNextNode(). When getNextNode() is
+** called, it sets ParseContext.isNot to true if the 'next node' is a
+** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
+** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
+** zero.
+*/
+typedef struct ParseContext ParseContext;
+struct ParseContext {
+ sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
+ int iLangid; /* Language id used with tokenizer */
+ const char **azCol; /* Array of column names for fts3 table */
+ int bFts4; /* True to allow FTS4-only syntax */
+ int nCol; /* Number of entries in azCol[] */
+ int iDefaultCol; /* Default column to query */
+ int isNot; /* True if getNextNode() sees a unary - */
+ sqlite3_context *pCtx; /* Write error message here */
+ int nNest; /* Number of nested brackets */
+};
+
+/*
+** This function is equivalent to the standard isspace() function.
+**
+** The standard isspace() can be awkward to use safely, because although it
+** is defined to accept an argument of type int, its behavior when passed
+** an integer that falls outside of the range of the unsigned char type
+** is undefined (and sometimes, "undefined" means segfault). This wrapper
+** is defined to accept an argument of type char, and always returns 0 for
+** any values that fall outside of the range of the unsigned char type (i.e.
+** negative values).
+*/
+static int fts3isspace(char c){
+ return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
+}
+
+/*
+** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
+** zero the memory before returning a pointer to it. If unsuccessful,
+** return NULL.
+*/
+static void *fts3MallocZero(sqlite3_int64 nByte){
+ void *pRet = sqlite3_malloc64(nByte);
+ if( pRet ) memset(pRet, 0, nByte);
+ return pRet;
+}
+
+SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
+ sqlite3_tokenizer *pTokenizer,
+ int iLangid,
+ const char *z,
+ int n,
+ sqlite3_tokenizer_cursor **ppCsr
+){
+ sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
+ sqlite3_tokenizer_cursor *pCsr = 0;
+ int rc;
+
+ rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
+ assert( rc==SQLITE_OK || pCsr==0 );
+ if( rc==SQLITE_OK ){
+ pCsr->pTokenizer = pTokenizer;
+ if( pModule->iVersion>=1 ){
+ rc = pModule->xLanguageid(pCsr, iLangid);
+ if( rc!=SQLITE_OK ){
+ pModule->xClose(pCsr);
+ pCsr = 0;
+ }
+ }
+ }
+ *ppCsr = pCsr;
+ return rc;
+}
+
+/*
+** Function getNextNode(), which is called by fts3ExprParse(), may itself
+** call fts3ExprParse(). So this forward declaration is required.
+*/
+static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
+
+/*
+** Extract the next token from buffer z (length n) using the tokenizer
+** and other information (column names etc.) in pParse. Create an Fts3Expr
+** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
+** single token and set *ppExpr to point to it. If the end of the buffer is
+** reached before a token is found, set *ppExpr to zero. It is the
+** responsibility of the caller to eventually deallocate the allocated
+** Fts3Expr structure (if any) by passing it to sqlite3_free().
+**
+** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
+** fails.
+*/
+static int getNextToken(
+ ParseContext *pParse, /* fts3 query parse context */
+ int iCol, /* Value for Fts3Phrase.iColumn */
+ const char *z, int n, /* Input string */
+ Fts3Expr **ppExpr, /* OUT: expression */
+ int *pnConsumed /* OUT: Number of bytes consumed */
+){
+ sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
+ sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
+ int rc;
+ sqlite3_tokenizer_cursor *pCursor;
+ Fts3Expr *pRet = 0;
+ int i = 0;
+
+ /* Set variable i to the maximum number of bytes of input to tokenize. */
+ for(i=0; i<n; i++){
+ if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
+ if( z[i]=='"' ) break;
+ }
+
+ *pnConsumed = i;
+ rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
+ if( rc==SQLITE_OK ){
+ const char *zToken;
+ int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
+ sqlite3_int64 nByte; /* total space to allocate */
+
+ rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
+ if( rc==SQLITE_OK ){
+ nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
+ pRet = (Fts3Expr *)fts3MallocZero(nByte);
+ if( !pRet ){
+ rc = SQLITE_NOMEM;
+ }else{
+ pRet->eType = FTSQUERY_PHRASE;
+ pRet->pPhrase = (Fts3Phrase *)&pRet[1];
+ pRet->pPhrase->nToken = 1;
+ pRet->pPhrase->iColumn = iCol;
+ pRet->pPhrase->aToken[0].n = nToken;
+ pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
+ memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
+
+ if( iEnd<n && z[iEnd]=='*' ){
+ pRet->pPhrase->aToken[0].isPrefix = 1;
+ iEnd++;
+ }
+
+ while( 1 ){
+ if( !sqlite3_fts3_enable_parentheses
+ && iStart>0 && z[iStart-1]=='-'
+ ){
+ pParse->isNot = 1;
+ iStart--;
+ }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
+ pRet->pPhrase->aToken[0].bFirst = 1;
+ iStart--;
+ }else{
+ break;
+ }
+ }
+
+ }
+ *pnConsumed = iEnd;
+ }else if( i && rc==SQLITE_DONE ){
+ rc = SQLITE_OK;
+ }
+
+ pModule->xClose(pCursor);
+ }
+
+ *ppExpr = pRet;
+ return rc;
+}
+
+
+/*
+** Enlarge a memory allocation. If an out-of-memory allocation occurs,
+** then free the old allocation.
+*/
+static void *fts3ReallocOrFree(void *pOrig, sqlite3_int64 nNew){
+ void *pRet = sqlite3_realloc64(pOrig, nNew);
+ if( !pRet ){
+ sqlite3_free(pOrig);
+ }
+ return pRet;
+}
+
+/*
+** Buffer zInput, length nInput, contains the contents of a quoted string
+** that appeared as part of an fts3 query expression. Neither quote character
+** is included in the buffer. This function attempts to tokenize the entire
+** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
+** containing the results.
+**
+** If successful, SQLITE_OK is returned and *ppExpr set to point at the
+** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
+** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
+** to 0.
+*/
+static int getNextString(
+ ParseContext *pParse, /* fts3 query parse context */
+ const char *zInput, int nInput, /* Input string */
+ Fts3Expr **ppExpr /* OUT: expression */
+){
+ sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
+ sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
+ int rc;
+ Fts3Expr *p = 0;
+ sqlite3_tokenizer_cursor *pCursor = 0;
+ char *zTemp = 0;
+ int nTemp = 0;
+
+ const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
+ int nToken = 0;
+
+ /* The final Fts3Expr data structure, including the Fts3Phrase,
+ ** Fts3PhraseToken structures token buffers are all stored as a single
+ ** allocation so that the expression can be freed with a single call to
+ ** sqlite3_free(). Setting this up requires a two pass approach.
+ **
+ ** The first pass, in the block below, uses a tokenizer cursor to iterate
+ ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
+ ** to assemble data in two dynamic buffers:
+ **
+ ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
+ ** structure, followed by the array of Fts3PhraseToken
+ ** structures. This pass only populates the Fts3PhraseToken array.
+ **
+ ** Buffer zTemp: Contains copies of all tokens.
+ **
+ ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
+ ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
+ ** structures.
+ */
+ rc = sqlite3Fts3OpenTokenizer(
+ pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
+ if( rc==SQLITE_OK ){
+ int ii;
+ for(ii=0; rc==SQLITE_OK; ii++){
+ const char *zByte;
+ int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
+ rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
+ if( rc==SQLITE_OK ){
+ Fts3PhraseToken *pToken;
+
+ p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
+ if( !p ) goto no_mem;
+
+ zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
+ if( !zTemp ) goto no_mem;
+
+ assert( nToken==ii );
+ pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
+ memset(pToken, 0, sizeof(Fts3PhraseToken));
+
+ memcpy(&zTemp[nTemp], zByte, nByte);
+ nTemp += nByte;
+
+ pToken->n = nByte;
+ pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
+ pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
+ nToken = ii+1;
+ }
+ }
+
+ pModule->xClose(pCursor);
+ pCursor = 0;
+ }
+
+ if( rc==SQLITE_DONE ){
+ int jj;
+ char *zBuf = 0;
+
+ p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
+ if( !p ) goto no_mem;
+ memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
+ p->eType = FTSQUERY_PHRASE;
+ p->pPhrase = (Fts3Phrase *)&p[1];
+ p->pPhrase->iColumn = pParse->iDefaultCol;
+ p->pPhrase->nToken = nToken;
+
+ zBuf = (char *)&p->pPhrase->aToken[nToken];
+ if( zTemp ){
+ memcpy(zBuf, zTemp, nTemp);
+ sqlite3_free(zTemp);
+ }else{
+ assert( nTemp==0 );
+ }
+
+ for(jj=0; jj<p->pPhrase->nToken; jj++){
+ p->pPhrase->aToken[jj].z = zBuf;
+ zBuf += p->pPhrase->aToken[jj].n;
+ }
+ rc = SQLITE_OK;
+ }
+
+ *ppExpr = p;
+ return rc;
+no_mem:
+
+ if( pCursor ){
+ pModule->xClose(pCursor);
+ }
+ sqlite3_free(zTemp);
+ sqlite3_free(p);
+ *ppExpr = 0;
+ return SQLITE_NOMEM;
+}
+
+/*
+** The output variable *ppExpr is populated with an allocated Fts3Expr
+** structure, or set to 0 if the end of the input buffer is reached.
+**
+** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
+** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
+** If SQLITE_ERROR is returned, pContext is populated with an error message.
+*/
+static int getNextNode(
+ ParseContext *pParse, /* fts3 query parse context */
+ const char *z, int n, /* Input string */
+ Fts3Expr **ppExpr, /* OUT: expression */
+ int *pnConsumed /* OUT: Number of bytes consumed */
+){
+ static const struct Fts3Keyword {
+ char *z; /* Keyword text */
+ unsigned char n; /* Length of the keyword */
+ unsigned char parenOnly; /* Only valid in paren mode */
+ unsigned char eType; /* Keyword code */
+ } aKeyword[] = {
+ { "OR" , 2, 0, FTSQUERY_OR },
+ { "AND", 3, 1, FTSQUERY_AND },
+ { "NOT", 3, 1, FTSQUERY_NOT },
+ { "NEAR", 4, 0, FTSQUERY_NEAR }
+ };
+ int ii;
+ int iCol;
+ int iColLen;
+ int rc;
+ Fts3Expr *pRet = 0;
+
+ const char *zInput = z;
+ int nInput = n;
+
+ pParse->isNot = 0;
+
+ /* Skip over any whitespace before checking for a keyword, an open or
+ ** close bracket, or a quoted string.
+ */
+ while( nInput>0 && fts3isspace(*zInput) ){
+ nInput--;
+ zInput++;
+ }
+ if( nInput==0 ){
+ return SQLITE_DONE;
+ }
+
+ /* See if we are dealing with a keyword. */
+ for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
+ const struct Fts3Keyword *pKey = &aKeyword[ii];
+
+ if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
+ continue;
+ }
+
+ if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
+ int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
+ int nKey = pKey->n;
+ char cNext;
+
+ /* If this is a "NEAR" keyword, check for an explicit nearness. */
+ if( pKey->eType==FTSQUERY_NEAR ){
+ assert( nKey==4 );
+ if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
+ nKey += 1+sqlite3Fts3ReadInt(&zInput[nKey+1], &nNear);
+ }
+ }
+
+ /* At this point this is probably a keyword. But for that to be true,
+ ** the next byte must contain either whitespace, an open or close
+ ** parenthesis, a quote character, or EOF.
+ */
+ cNext = zInput[nKey];
+ if( fts3isspace(cNext)
+ || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
+ ){
+ pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
+ if( !pRet ){
+ return SQLITE_NOMEM;
+ }
+ pRet->eType = pKey->eType;
+ pRet->nNear = nNear;
+ *ppExpr = pRet;
+ *pnConsumed = (int)((zInput - z) + nKey);
+ return SQLITE_OK;
+ }
+
+ /* Turns out that wasn't a keyword after all. This happens if the
+ ** user has supplied a token such as "ORacle". Continue.
+ */
+ }
+ }
+
+ /* See if we are dealing with a quoted phrase. If this is the case, then
+ ** search for the closing quote and pass the whole string to getNextString()
+ ** for processing. This is easy to do, as fts3 has no syntax for escaping
+ ** a quote character embedded in a string.
+ */
+ if( *zInput=='"' ){
+ for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
+ *pnConsumed = (int)((zInput - z) + ii + 1);
+ if( ii==nInput ){
+ return SQLITE_ERROR;
+ }
+ return getNextString(pParse, &zInput[1], ii-1, ppExpr);
+ }
+
+ if( sqlite3_fts3_enable_parentheses ){
+ if( *zInput=='(' ){
+ int nConsumed = 0;
+ pParse->nNest++;
+ rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
+ *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
+ return rc;
+ }else if( *zInput==')' ){
+ pParse->nNest--;
+ *pnConsumed = (int)((zInput - z) + 1);
+ *ppExpr = 0;
+ return SQLITE_DONE;
+ }
+ }
+
+ /* If control flows to this point, this must be a regular token, or
+ ** the end of the input. Read a regular token using the sqlite3_tokenizer
+ ** interface. Before doing so, figure out if there is an explicit
+ ** column specifier for the token.
+ **
+ ** TODO: Strangely, it is not possible to associate a column specifier
+ ** with a quoted phrase, only with a single token. Not sure if this was
+ ** an implementation artifact or an intentional decision when fts3 was
+ ** first implemented. Whichever it was, this module duplicates the
+ ** limitation.
+ */
+ iCol = pParse->iDefaultCol;
+ iColLen = 0;
+ for(ii=0; ii<pParse->nCol; ii++){
+ const char *zStr = pParse->azCol[ii];
+ int nStr = (int)strlen(zStr);
+ if( nInput>nStr && zInput[nStr]==':'
+ && sqlite3_strnicmp(zStr, zInput, nStr)==0
+ ){
+ iCol = ii;
+ iColLen = (int)((zInput - z) + nStr + 1);
+ break;
+ }
+ }
+ rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
+ *pnConsumed += iColLen;
+ return rc;
+}
+
+/*
+** The argument is an Fts3Expr structure for a binary operator (any type
+** except an FTSQUERY_PHRASE). Return an integer value representing the
+** precedence of the operator. Lower values have a higher precedence (i.e.
+** group more tightly). For example, in the C language, the == operator
+** groups more tightly than ||, and would therefore have a higher precedence.
+**
+** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
+** is defined), the order of the operators in precedence from highest to
+** lowest is:
+**
+** NEAR
+** NOT
+** AND (including implicit ANDs)
+** OR
+**
+** Note that when using the old query syntax, the OR operator has a higher
+** precedence than the AND operator.
+*/
+static int opPrecedence(Fts3Expr *p){
+ assert( p->eType!=FTSQUERY_PHRASE );
+ if( sqlite3_fts3_enable_parentheses ){
+ return p->eType;
+ }else if( p->eType==FTSQUERY_NEAR ){
+ return 1;
+ }else if( p->eType==FTSQUERY_OR ){
+ return 2;
+ }
+ assert( p->eType==FTSQUERY_AND );
+ return 3;
+}
+
+/*
+** Argument ppHead contains a pointer to the current head of a query
+** expression tree being parsed. pPrev is the expression node most recently
+** inserted into the tree. This function adds pNew, which is always a binary
+** operator node, into the expression tree based on the relative precedence
+** of pNew and the existing nodes of the tree. This may result in the head
+** of the tree changing, in which case *ppHead is set to the new root node.
+*/
+static void insertBinaryOperator(
+ Fts3Expr **ppHead, /* Pointer to the root node of a tree */
+ Fts3Expr *pPrev, /* Node most recently inserted into the tree */
+ Fts3Expr *pNew /* New binary node to insert into expression tree */
+){
+ Fts3Expr *pSplit = pPrev;
+ while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
+ pSplit = pSplit->pParent;
+ }
+
+ if( pSplit->pParent ){
+ assert( pSplit->pParent->pRight==pSplit );
+ pSplit->pParent->pRight = pNew;
+ pNew->pParent = pSplit->pParent;
+ }else{
+ *ppHead = pNew;
+ }
+ pNew->pLeft = pSplit;
+ pSplit->pParent = pNew;
+}
+
+/*
+** Parse the fts3 query expression found in buffer z, length n. This function
+** returns either when the end of the buffer is reached or an unmatched
+** closing bracket - ')' - is encountered.
+**
+** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
+** parsed form of the expression and *pnConsumed is set to the number of
+** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
+** (out of memory error) or SQLITE_ERROR (parse error) is returned.
+*/
+static int fts3ExprParse(
+ ParseContext *pParse, /* fts3 query parse context */
+ const char *z, int n, /* Text of MATCH query */
+ Fts3Expr **ppExpr, /* OUT: Parsed query structure */
+ int *pnConsumed /* OUT: Number of bytes consumed */
+){
+ Fts3Expr *pRet = 0;
+ Fts3Expr *pPrev = 0;
+ Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
+ int nIn = n;
+ const char *zIn = z;
+ int rc = SQLITE_OK;
+ int isRequirePhrase = 1;
+
+ while( rc==SQLITE_OK ){
+ Fts3Expr *p = 0;
+ int nByte = 0;
+
+ rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
+ assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
+ if( rc==SQLITE_OK ){
+ if( p ){
+ int isPhrase;
+
+ if( !sqlite3_fts3_enable_parentheses
+ && p->eType==FTSQUERY_PHRASE && pParse->isNot
+ ){
+ /* Create an implicit NOT operator. */
+ Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
+ if( !pNot ){
+ sqlite3Fts3ExprFree(p);
+ rc = SQLITE_NOMEM;
+ goto exprparse_out;
+ }
+ pNot->eType = FTSQUERY_NOT;
+ pNot->pRight = p;
+ p->pParent = pNot;
+ if( pNotBranch ){
+ pNot->pLeft = pNotBranch;
+ pNotBranch->pParent = pNot;
+ }
+ pNotBranch = pNot;
+ p = pPrev;
+ }else{
+ int eType = p->eType;
+ isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
+
+ /* The isRequirePhrase variable is set to true if a phrase or
+ ** an expression contained in parenthesis is required. If a
+ ** binary operator (AND, OR, NOT or NEAR) is encounted when
+ ** isRequirePhrase is set, this is a syntax error.
+ */
+ if( !isPhrase && isRequirePhrase ){
+ sqlite3Fts3ExprFree(p);
+ rc = SQLITE_ERROR;
+ goto exprparse_out;
+ }
+
+ if( isPhrase && !isRequirePhrase ){
+ /* Insert an implicit AND operator. */
+ Fts3Expr *pAnd;
+ assert( pRet && pPrev );
+ pAnd = fts3MallocZero(sizeof(Fts3Expr));
+ if( !pAnd ){
+ sqlite3Fts3ExprFree(p);
+ rc = SQLITE_NOMEM;
+ goto exprparse_out;
+ }
+ pAnd->eType = FTSQUERY_AND;
+ insertBinaryOperator(&pRet, pPrev, pAnd);
+ pPrev = pAnd;
+ }
+
+ /* This test catches attempts to make either operand of a NEAR
+ ** operator something other than a phrase. For example, either of
+ ** the following:
+ **
+ ** (bracketed expression) NEAR phrase
+ ** phrase NEAR (bracketed expression)
+ **
+ ** Return an error in either case.
+ */
+ if( pPrev && (
+ (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
+ || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
+ )){
+ sqlite3Fts3ExprFree(p);
+ rc = SQLITE_ERROR;
+ goto exprparse_out;
+ }
+
+ if( isPhrase ){
+ if( pRet ){
+ assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
+ pPrev->pRight = p;
+ p->pParent = pPrev;
+ }else{
+ pRet = p;
+ }
+ }else{
+ insertBinaryOperator(&pRet, pPrev, p);
+ }
+ isRequirePhrase = !isPhrase;
+ }
+ pPrev = p;
+ }
+ assert( nByte>0 );
+ }
+ assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
+ nIn -= nByte;
+ zIn += nByte;
+ }
+
+ if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
+ rc = SQLITE_ERROR;
+ }
+
+ if( rc==SQLITE_DONE ){
+ rc = SQLITE_OK;
+ if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
+ if( !pRet ){
+ rc = SQLITE_ERROR;
+ }else{
+ Fts3Expr *pIter = pNotBranch;
+ while( pIter->pLeft ){
+ pIter = pIter->pLeft;
+ }
+ pIter->pLeft = pRet;
+ pRet->pParent = pIter;
+ pRet = pNotBranch;
+ }
+ }
+ }
+ *pnConsumed = n - nIn;
+
+exprparse_out:
+ if( rc!=SQLITE_OK ){
+ sqlite3Fts3ExprFree(pRet);
+ sqlite3Fts3ExprFree(pNotBranch);
+ pRet = 0;
+ }
+ *ppExpr = pRet;
+ return rc;
+}
+
+/*
+** Return SQLITE_ERROR if the maximum depth of the expression tree passed
+** as the only argument is more than nMaxDepth.
+*/
+static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
+ int rc = SQLITE_OK;
+ if( p ){
+ if( nMaxDepth<0 ){
+ rc = SQLITE_TOOBIG;
+ }else{
+ rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
+ if( rc==SQLITE_OK ){
+ rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
+ }
+ }
+ }
+ return rc;
+}
+
+/*
+** This function attempts to transform the expression tree at (*pp) to
+** an equivalent but more balanced form. The tree is modified in place.
+** If successful, SQLITE_OK is returned and (*pp) set to point to the
+** new root expression node.
+**
+** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
+**
+** Otherwise, if an error occurs, an SQLite error code is returned and
+** expression (*pp) freed.
+*/
+static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
+ int rc = SQLITE_OK; /* Return code */
+ Fts3Expr *pRoot = *pp; /* Initial root node */
+ Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
+ int eType = pRoot->eType; /* Type of node in this tree */
+
+ if( nMaxDepth==0 ){
+ rc = SQLITE_ERROR;
+ }
+
+ if( rc==SQLITE_OK ){
+ if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
+ Fts3Expr **apLeaf;
+ apLeaf = (Fts3Expr **)sqlite3_malloc64(sizeof(Fts3Expr *) * nMaxDepth);
+ if( 0==apLeaf ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
+ }
+
+ if( rc==SQLITE_OK ){
+ int i;
+ Fts3Expr *p;
+
+ /* Set $p to point to the left-most leaf in the tree of eType nodes. */
+ for(p=pRoot; p->eType==eType; p=p->pLeft){
+ assert( p->pParent==0 || p->pParent->pLeft==p );
+ assert( p->pLeft && p->pRight );
+ }
+
+ /* This loop runs once for each leaf in the tree of eType nodes. */
+ while( 1 ){
+ int iLvl;
+ Fts3Expr *pParent = p->pParent; /* Current parent of p */
+
+ assert( pParent==0 || pParent->pLeft==p );
+ p->pParent = 0;
+ if( pParent ){
+ pParent->pLeft = 0;
+ }else{
+ pRoot = 0;
+ }
+ rc = fts3ExprBalance(&p, nMaxDepth-1);
+ if( rc!=SQLITE_OK ) break;
+
+ for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
+ if( apLeaf[iLvl]==0 ){
+ apLeaf[iLvl] = p;
+ p = 0;
+ }else{
+ assert( pFree );
+ pFree->pLeft = apLeaf[iLvl];
+ pFree->pRight = p;
+ pFree->pLeft->pParent = pFree;
+ pFree->pRight->pParent = pFree;
+
+ p = pFree;
+ pFree = pFree->pParent;
+ p->pParent = 0;
+ apLeaf[iLvl] = 0;
+ }
+ }
+ if( p ){
+ sqlite3Fts3ExprFree(p);
+ rc = SQLITE_TOOBIG;
+ break;
+ }
+
+ /* If that was the last leaf node, break out of the loop */
+ if( pParent==0 ) break;
+
+ /* Set $p to point to the next leaf in the tree of eType nodes */
+ for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
+
+ /* Remove pParent from the original tree. */
+ assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
+ pParent->pRight->pParent = pParent->pParent;
+ if( pParent->pParent ){
+ pParent->pParent->pLeft = pParent->pRight;
+ }else{
+ assert( pParent==pRoot );
+ pRoot = pParent->pRight;
+ }
+
+ /* Link pParent into the free node list. It will be used as an
+ ** internal node of the new tree. */
+ pParent->pParent = pFree;
+ pFree = pParent;
+ }
+
+ if( rc==SQLITE_OK ){
+ p = 0;
+ for(i=0; i<nMaxDepth; i++){
+ if( apLeaf[i] ){
+ if( p==0 ){
+ p = apLeaf[i];
+ p->pParent = 0;
+ }else{
+ assert( pFree!=0 );
+ pFree->pRight = p;
+ pFree->pLeft = apLeaf[i];
+ pFree->pLeft->pParent = pFree;
+ pFree->pRight->pParent = pFree;
+
+ p = pFree;
+ pFree = pFree->pParent;
+ p->pParent = 0;
+ }
+ }
+ }
+ pRoot = p;
+ }else{
+ /* An error occurred. Delete the contents of the apLeaf[] array
+ ** and pFree list. Everything else is cleaned up by the call to
+ ** sqlite3Fts3ExprFree(pRoot) below. */
+ Fts3Expr *pDel;
+ for(i=0; i<nMaxDepth; i++){
+ sqlite3Fts3ExprFree(apLeaf[i]);
+ }
+ while( (pDel=pFree)!=0 ){
+ pFree = pDel->pParent;
+ sqlite3_free(pDel);
+ }
+ }
+
+ assert( pFree==0 );
+ sqlite3_free( apLeaf );
+ }
+ }else if( eType==FTSQUERY_NOT ){
+ Fts3Expr *pLeft = pRoot->pLeft;
+ Fts3Expr *pRight = pRoot->pRight;
+
+ pRoot->pLeft = 0;
+ pRoot->pRight = 0;
+ pLeft->pParent = 0;
+ pRight->pParent = 0;
+
+ rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
+ if( rc==SQLITE_OK ){
+ rc = fts3ExprBalance(&pRight, nMaxDepth-1);
+ }
+
+ if( rc!=SQLITE_OK ){
+ sqlite3Fts3ExprFree(pRight);
+ sqlite3Fts3ExprFree(pLeft);
+ }else{
+ assert( pLeft && pRight );
+ pRoot->pLeft = pLeft;
+ pLeft->pParent = pRoot;
+ pRoot->pRight = pRight;
+ pRight->pParent = pRoot;
+ }
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ sqlite3Fts3ExprFree(pRoot);
+ pRoot = 0;
+ }
+ *pp = pRoot;
+ return rc;
+}
+
+/*
+** This function is similar to sqlite3Fts3ExprParse(), with the following
+** differences:
+**
+** 1. It does not do expression rebalancing.
+** 2. It does not check that the expression does not exceed the
+** maximum allowable depth.
+** 3. Even if it fails, *ppExpr may still be set to point to an
+** expression tree. It should be deleted using sqlite3Fts3ExprFree()
+** in this case.
+*/
+static int fts3ExprParseUnbalanced(
+ sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
+ int iLangid, /* Language id for tokenizer */
+ char **azCol, /* Array of column names for fts3 table */
+ int bFts4, /* True to allow FTS4-only syntax */
+ int nCol, /* Number of entries in azCol[] */
+ int iDefaultCol, /* Default column to query */
+ const char *z, int n, /* Text of MATCH query */
+ Fts3Expr **ppExpr /* OUT: Parsed query structure */
+){
+ int nParsed;
+ int rc;
+ ParseContext sParse;
+
+ memset(&sParse, 0, sizeof(ParseContext));
+ sParse.pTokenizer = pTokenizer;
+ sParse.iLangid = iLangid;
+ sParse.azCol = (const char **)azCol;
+ sParse.nCol = nCol;
+ sParse.iDefaultCol = iDefaultCol;
+ sParse.bFts4 = bFts4;
+ if( z==0 ){
+ *ppExpr = 0;
+ return SQLITE_OK;
+ }
+ if( n<0 ){
+ n = (int)strlen(z);
+ }
+ rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
+ assert( rc==SQLITE_OK || *ppExpr==0 );
+
+ /* Check for mismatched parenthesis */
+ if( rc==SQLITE_OK && sParse.nNest ){
+ rc = SQLITE_ERROR;
+ }
+
+ return rc;
+}
+
+/*
+** Parameters z and n contain a pointer to and length of a buffer containing
+** an fts3 query expression, respectively. This function attempts to parse the
+** query expression and create a tree of Fts3Expr structures representing the
+** parsed expression. If successful, *ppExpr is set to point to the head
+** of the parsed expression tree and SQLITE_OK is returned. If an error
+** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
+** error) is returned and *ppExpr is set to 0.
+**
+** If parameter n is a negative number, then z is assumed to point to a
+** nul-terminated string and the length is determined using strlen().
+**
+** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
+** use to normalize query tokens while parsing the expression. The azCol[]
+** array, which is assumed to contain nCol entries, should contain the names
+** of each column in the target fts3 table, in order from left to right.
+** Column names must be nul-terminated strings.
+**
+** The iDefaultCol parameter should be passed the index of the table column
+** that appears on the left-hand-side of the MATCH operator (the default
+** column to match against for tokens for which a column name is not explicitly
+** specified as part of the query string), or -1 if tokens may by default
+** match any table column.
+*/
+SQLITE_PRIVATE int sqlite3Fts3ExprParse(
+ sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
+ int iLangid, /* Language id for tokenizer */
+ char **azCol, /* Array of column names for fts3 table */
+ int bFts4, /* True to allow FTS4-only syntax */
+ int nCol, /* Number of entries in azCol[] */
+ int iDefaultCol, /* Default column to query */
+ const char *z, int n, /* Text of MATCH query */
+ Fts3Expr **ppExpr, /* OUT: Parsed query structure */
+ char **pzErr /* OUT: Error message (sqlite3_malloc) */
+){
+ int rc = fts3ExprParseUnbalanced(
+ pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
+ );
+
+ /* Rebalance the expression. And check that its depth does not exceed
+ ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
+ if( rc==SQLITE_OK && *ppExpr ){
+ rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
+ if( rc==SQLITE_OK ){
+ rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ sqlite3Fts3ExprFree(*ppExpr);
+ *ppExpr = 0;
+ if( rc==SQLITE_TOOBIG ){
+ sqlite3Fts3ErrMsg(pzErr,
+ "FTS expression tree is too large (maximum depth %d)",
+ SQLITE_FTS3_MAX_EXPR_DEPTH
+ );
+ rc = SQLITE_ERROR;
+ }else if( rc==SQLITE_ERROR ){
+ sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Free a single node of an expression tree.
+*/
+static void fts3FreeExprNode(Fts3Expr *p){
+ assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
+ sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
+ sqlite3_free(p->aMI);
+ sqlite3_free(p);
+}
+
+/*
+** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
+**
+** This function would be simpler if it recursively called itself. But
+** that would mean passing a sufficiently large expression to ExprParse()
+** could cause a stack overflow.
+*/
+SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
+ Fts3Expr *p;
+ assert( pDel==0 || pDel->pParent==0 );
+ for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
+ assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
+ }
+ while( p ){
+ Fts3Expr *pParent = p->pParent;
+ fts3FreeExprNode(p);
+ if( pParent && p==pParent->pLeft && pParent->pRight ){
+ p = pParent->pRight;
+ while( p && (p->pLeft || p->pRight) ){
+ assert( p==p->pParent->pRight || p==p->pParent->pLeft );
+ p = (p->pLeft ? p->pLeft : p->pRight);
+ }
+ }else{
+ p = pParent;
+ }
+ }
+}
+
+/****************************************************************************
+*****************************************************************************
+** Everything after this point is just test code.
+*/
+
+#ifdef SQLITE_TEST
+
+/* #include <stdio.h> */
+
+/*
+** Return a pointer to a buffer containing a text representation of the
+** expression passed as the first argument. The buffer is obtained from
+** sqlite3_malloc(). It is the responsibility of the caller to use
+** sqlite3_free() to release the memory. If an OOM condition is encountered,
+** NULL is returned.
+**
+** If the second argument is not NULL, then its contents are prepended to
+** the returned expression text and then freed using sqlite3_free().
+*/
+static char *exprToString(Fts3Expr *pExpr, char *zBuf){
+ if( pExpr==0 ){
+ return sqlite3_mprintf("");
+ }
+ switch( pExpr->eType ){
+ case FTSQUERY_PHRASE: {
+ Fts3Phrase *pPhrase = pExpr->pPhrase;
+ int i;
+ zBuf = sqlite3_mprintf(
+ "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
+ for(i=0; zBuf && i<pPhrase->nToken; i++){
+ zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
+ pPhrase->aToken[i].n, pPhrase->aToken[i].z,
+ (pPhrase->aToken[i].isPrefix?"+":"")
+ );
+ }
+ return zBuf;
+ }
+
+ case FTSQUERY_NEAR:
+ zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
+ break;
+ case FTSQUERY_NOT:
+ zBuf = sqlite3_mprintf("%zNOT ", zBuf);
+ break;
+ case FTSQUERY_AND:
+ zBuf = sqlite3_mprintf("%zAND ", zBuf);
+ break;
+ case FTSQUERY_OR:
+ zBuf = sqlite3_mprintf("%zOR ", zBuf);
+ break;
+ }
+
+ if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
+ if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
+ if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
+
+ if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
+ if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
+
+ return zBuf;
+}
+
+/*
+** This is the implementation of a scalar SQL function used to test the
+** expression parser. It should be called as follows:
+**
+** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
+**
+** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
+** to parse the query expression (see README.tokenizers). The second argument
+** is the query expression to parse. Each subsequent argument is the name
+** of a column of the fts3 table that the query expression may refer to.
+** For example:
+**
+** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
+*/
+static void fts3ExprTestCommon(
+ int bRebalance,
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ sqlite3_tokenizer *pTokenizer = 0;
+ int rc;
+ char **azCol = 0;
+ const char *zExpr;
+ int nExpr;
+ int nCol;
+ int ii;
+ Fts3Expr *pExpr;
+ char *zBuf = 0;
+ Fts3Hash *pHash = (Fts3Hash*)sqlite3_user_data(context);
+ const char *zTokenizer = 0;
+ char *zErr = 0;
+
+ if( argc<3 ){
+ sqlite3_result_error(context,
+ "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
+ );
+ return;
+ }
+
+ zTokenizer = (const char*)sqlite3_value_text(argv[0]);
+ rc = sqlite3Fts3InitTokenizer(pHash, zTokenizer, &pTokenizer, &zErr);
+ if( rc!=SQLITE_OK ){
+ if( rc==SQLITE_NOMEM ){
+ sqlite3_result_error_nomem(context);
+ }else{
+ sqlite3_result_error(context, zErr, -1);
+ }
+ sqlite3_free(zErr);
+ return;
+ }
+
+ zExpr = (const char *)sqlite3_value_text(argv[1]);
+ nExpr = sqlite3_value_bytes(argv[1]);
+ nCol = argc-2;
+ azCol = (char **)sqlite3_malloc64(nCol*sizeof(char *));
+ if( !azCol ){
+ sqlite3_result_error_nomem(context);
+ goto exprtest_out;
+ }
+ for(ii=0; ii<nCol; ii++){
+ azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
+ }
+
+ if( bRebalance ){
+ char *zDummy = 0;
+ rc = sqlite3Fts3ExprParse(
+ pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
+ );
+ assert( rc==SQLITE_OK || pExpr==0 );
+ sqlite3_free(zDummy);
+ }else{
+ rc = fts3ExprParseUnbalanced(
+ pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
+ );
+ }
+
+ if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
+ sqlite3Fts3ExprFree(pExpr);
+ sqlite3_result_error(context, "Error parsing expression", -1);
+ }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
+ sqlite3_result_error_nomem(context);
+ }else{
+ sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
+ sqlite3_free(zBuf);
+ }
+
+ sqlite3Fts3ExprFree(pExpr);
+
+exprtest_out:
+ if( pTokenizer ){
+ rc = pTokenizer->pModule->xDestroy(pTokenizer);
+ }
+ sqlite3_free(azCol);
+}
+
+static void fts3ExprTest(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ fts3ExprTestCommon(0, context, argc, argv);
+}
+static void fts3ExprTestRebalance(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ fts3ExprTestCommon(1, context, argc, argv);
+}
+
+/*
+** Register the query expression parser test function fts3_exprtest()
+** with database connection db.
+*/
+SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){
+ int rc = sqlite3_create_function(
+ db, "fts3_exprtest", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0
+ );
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
+ -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0
+ );
+ }
+ return rc;
+}
+
+#endif
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
+
+/************** End of fts3_expr.c *******************************************/
+/************** Begin file fts3_hash.c ***************************************/
+/*
+** 2001 September 22
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This is the implementation of generic hash-tables used in SQLite.
+** We've modified it slightly to serve as a standalone hash table
+** implementation for the full-text indexing module.
+*/
+
+/*
+** The code in this file is only compiled if:
+**
+** * The FTS3 module is being built as an extension
+** (in which case SQLITE_CORE is not defined), or
+**
+** * The FTS3 module is being built into the core of
+** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
+*/
+/* #include "fts3Int.h" */
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
+
+/* #include <assert.h> */
+/* #include <stdlib.h> */
+/* #include <string.h> */
+
+/* #include "fts3_hash.h" */
+
+/*
+** Malloc and Free functions
+*/
+static void *fts3HashMalloc(sqlite3_int64 n){
+ void *p = sqlite3_malloc64(n);
+ if( p ){
+ memset(p, 0, n);
+ }
+ return p;
+}
+static void fts3HashFree(void *p){
+ sqlite3_free(p);
+}
+
+/* Turn bulk memory into a hash table object by initializing the
+** fields of the Hash structure.
+**
+** "pNew" is a pointer to the hash table that is to be initialized.
+** keyClass is one of the constants
+** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
+** determines what kind of key the hash table will use. "copyKey" is
+** true if the hash table should make its own private copy of keys and
+** false if it should just use the supplied pointer.
+*/
+SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
+ assert( pNew!=0 );
+ assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
+ pNew->keyClass = keyClass;
+ pNew->copyKey = copyKey;
+ pNew->first = 0;
+ pNew->count = 0;
+ pNew->htsize = 0;
+ pNew->ht = 0;
+}
+
+/* Remove all entries from a hash table. Reclaim all memory.
+** Call this routine to delete a hash table or to reset a hash table
+** to the empty state.
+*/
+SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
+ Fts3HashElem *elem; /* For looping over all elements of the table */
+
+ assert( pH!=0 );
+ elem = pH->first;
+ pH->first = 0;
+ fts3HashFree(pH->ht);
+ pH->ht = 0;
+ pH->htsize = 0;
+ while( elem ){
+ Fts3HashElem *next_elem = elem->next;
+ if( pH->copyKey && elem->pKey ){
+ fts3HashFree(elem->pKey);
+ }
+ fts3HashFree(elem);
+ elem = next_elem;
+ }
+ pH->count = 0;
+}
+
+/*
+** Hash and comparison functions when the mode is FTS3_HASH_STRING
+*/
+static int fts3StrHash(const void *pKey, int nKey){
+ const char *z = (const char *)pKey;
+ unsigned h = 0;
+ if( nKey<=0 ) nKey = (int) strlen(z);
+ while( nKey > 0 ){
+ h = (h<<3) ^ h ^ *z++;
+ nKey--;
+ }
+ return (int)(h & 0x7fffffff);
+}
+static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
+ if( n1!=n2 ) return 1;
+ return strncmp((const char*)pKey1,(const char*)pKey2,n1);
+}
+
+/*
+** Hash and comparison functions when the mode is FTS3_HASH_BINARY
+*/
+static int fts3BinHash(const void *pKey, int nKey){
+ int h = 0;
+ const char *z = (const char *)pKey;
+ while( nKey-- > 0 ){
+ h = (h<<3) ^ h ^ *(z++);
+ }
+ return h & 0x7fffffff;
+}
+static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
+ if( n1!=n2 ) return 1;
+ return memcmp(pKey1,pKey2,n1);
+}
+
+/*
+** Return a pointer to the appropriate hash function given the key class.
+**
+** The C syntax in this function definition may be unfamilar to some
+** programmers, so we provide the following additional explanation:
+**
+** The name of the function is "ftsHashFunction". The function takes a
+** single parameter "keyClass". The return value of ftsHashFunction()
+** is a pointer to another function. Specifically, the return value
+** of ftsHashFunction() is a pointer to a function that takes two parameters
+** with types "const void*" and "int" and returns an "int".
+*/
+static int (*ftsHashFunction(int keyClass))(const void*,int){
+ if( keyClass==FTS3_HASH_STRING ){
+ return &fts3StrHash;
+ }else{
+ assert( keyClass==FTS3_HASH_BINARY );
+ return &fts3BinHash;
+ }
+}
+
+/*
+** Return a pointer to the appropriate hash function given the key class.
+**
+** For help in interpreted the obscure C code in the function definition,
+** see the header comment on the previous function.
+*/
+static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
+ if( keyClass==FTS3_HASH_STRING ){
+ return &fts3StrCompare;
+ }else{
+ assert( keyClass==FTS3_HASH_BINARY );
+ return &fts3BinCompare;
+ }
+}
+
+/* Link an element into the hash table
+*/
+static void fts3HashInsertElement(
+ Fts3Hash *pH, /* The complete hash table */
+ struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
+ Fts3HashElem *pNew /* The element to be inserted */
+){
+ Fts3HashElem *pHead; /* First element already in pEntry */
+ pHead = pEntry->chain;
+ if( pHead ){
+ pNew->next = pHead;
+ pNew->prev = pHead->prev;
+ if( pHead->prev ){ pHead->prev->next = pNew; }
+ else { pH->first = pNew; }
+ pHead->prev = pNew;
+ }else{
+ pNew->next = pH->first;
+ if( pH->first ){ pH->first->prev = pNew; }
+ pNew->prev = 0;
+ pH->first = pNew;
+ }
+ pEntry->count++;
+ pEntry->chain = pNew;
+}
+
+
+/* Resize the hash table so that it cantains "new_size" buckets.
+** "new_size" must be a power of 2. The hash table might fail
+** to resize if sqliteMalloc() fails.
+**
+** Return non-zero if a memory allocation error occurs.
+*/
+static int fts3Rehash(Fts3Hash *pH, int new_size){
+ struct _fts3ht *new_ht; /* The new hash table */
+ Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
+ int (*xHash)(const void*,int); /* The hash function */
+
+ assert( (new_size & (new_size-1))==0 );
+ new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
+ if( new_ht==0 ) return 1;
+ fts3HashFree(pH->ht);
+ pH->ht = new_ht;
+ pH->htsize = new_size;
+ xHash = ftsHashFunction(pH->keyClass);
+ for(elem=pH->first, pH->first=0; elem; elem = next_elem){
+ int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
+ next_elem = elem->next;
+ fts3HashInsertElement(pH, &new_ht[h], elem);
+ }
+ return 0;
+}
+
+/* This function (for internal use only) locates an element in an
+** hash table that matches the given key. The hash for this key has
+** already been computed and is passed as the 4th parameter.
+*/
+static Fts3HashElem *fts3FindElementByHash(
+ const Fts3Hash *pH, /* The pH to be searched */
+ const void *pKey, /* The key we are searching for */
+ int nKey,
+ int h /* The hash for this key. */
+){
+ Fts3HashElem *elem; /* Used to loop thru the element list */
+ int count; /* Number of elements left to test */
+ int (*xCompare)(const void*,int,const void*,int); /* comparison function */
+
+ if( pH->ht ){
+ struct _fts3ht *pEntry = &pH->ht[h];
+ elem = pEntry->chain;
+ count = pEntry->count;
+ xCompare = ftsCompareFunction(pH->keyClass);
+ while( count-- && elem ){
+ if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
+ return elem;
+ }
+ elem = elem->next;
+ }
+ }
+ return 0;
+}
+
+/* Remove a single entry from the hash table given a pointer to that
+** element and a hash on the element's key.
+*/
+static void fts3RemoveElementByHash(
+ Fts3Hash *pH, /* The pH containing "elem" */
+ Fts3HashElem* elem, /* The element to be removed from the pH */
+ int h /* Hash value for the element */
+){
+ struct _fts3ht *pEntry;
+ if( elem->prev ){
+ elem->prev->next = elem->next;
+ }else{
+ pH->first = elem->next;
+ }
+ if( elem->next ){
+ elem->next->prev = elem->prev;
+ }
+ pEntry = &pH->ht[h];
+ if( pEntry->chain==elem ){
+ pEntry->chain = elem->next;
+ }
+ pEntry->count--;
+ if( pEntry->count<=0 ){
+ pEntry->chain = 0;
+ }
+ if( pH->copyKey && elem->pKey ){
+ fts3HashFree(elem->pKey);
+ }
+ fts3HashFree( elem );
+ pH->count--;
+ if( pH->count<=0 ){
+ assert( pH->first==0 );
+ assert( pH->count==0 );
+ fts3HashClear(pH);
+ }
+}
+
+SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
+ const Fts3Hash *pH,
+ const void *pKey,
+ int nKey
+){
+ int h; /* A hash on key */
+ int (*xHash)(const void*,int); /* The hash function */
+
+ if( pH==0 || pH->ht==0 ) return 0;
+ xHash = ftsHashFunction(pH->keyClass);
+ assert( xHash!=0 );
+ h = (*xHash)(pKey,nKey);
+ assert( (pH->htsize & (pH->htsize-1))==0 );
+ return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
+}
+
+/*
+** Attempt to locate an element of the hash table pH with a key
+** that matches pKey,nKey. Return the data for this element if it is
+** found, or NULL if there is no match.
+*/
+SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
+ Fts3HashElem *pElem; /* The element that matches key (if any) */
+
+ pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
+ return pElem ? pElem->data : 0;
+}
+
+/* Insert an element into the hash table pH. The key is pKey,nKey
+** and the data is "data".
+**
+** If no element exists with a matching key, then a new
+** element is created. A copy of the key is made if the copyKey
+** flag is set. NULL is returned.
+**
+** If another element already exists with the same key, then the
+** new data replaces the old data and the old data is returned.
+** The key is not copied in this instance. If a malloc fails, then
+** the new data is returned and the hash table is unchanged.
+**
+** If the "data" parameter to this function is NULL, then the
+** element corresponding to "key" is removed from the hash table.
+*/
+SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
+ Fts3Hash *pH, /* The hash table to insert into */
+ const void *pKey, /* The key */
+ int nKey, /* Number of bytes in the key */
+ void *data /* The data */
+){
+ int hraw; /* Raw hash value of the key */
+ int h; /* the hash of the key modulo hash table size */
+ Fts3HashElem *elem; /* Used to loop thru the element list */
+ Fts3HashElem *new_elem; /* New element added to the pH */
+ int (*xHash)(const void*,int); /* The hash function */
+
+ assert( pH!=0 );
+ xHash = ftsHashFunction(pH->keyClass);
+ assert( xHash!=0 );
+ hraw = (*xHash)(pKey, nKey);
+ assert( (pH->htsize & (pH->htsize-1))==0 );
+ h = hraw & (pH->htsize-1);
+ elem = fts3FindElementByHash(pH,pKey,nKey,h);
+ if( elem ){
+ void *old_data = elem->data;
+ if( data==0 ){
+ fts3RemoveElementByHash(pH,elem,h);
+ }else{
+ elem->data = data;
+ }
+ return old_data;
+ }
+ if( data==0 ) return 0;
+ if( (pH->htsize==0 && fts3Rehash(pH,8))
+ || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
+ ){
+ pH->count = 0;
+ return data;
+ }
+ assert( pH->htsize>0 );
+ new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
+ if( new_elem==0 ) return data;
+ if( pH->copyKey && pKey!=0 ){
+ new_elem->pKey = fts3HashMalloc( nKey );
+ if( new_elem->pKey==0 ){
+ fts3HashFree(new_elem);
+ return data;
+ }
+ memcpy((void*)new_elem->pKey, pKey, nKey);
+ }else{
+ new_elem->pKey = (void*)pKey;
+ }
+ new_elem->nKey = nKey;
+ pH->count++;
+ assert( pH->htsize>0 );
+ assert( (pH->htsize & (pH->htsize-1))==0 );
+ h = hraw & (pH->htsize-1);
+ fts3HashInsertElement(pH, &pH->ht[h], new_elem);
+ new_elem->data = data;
+ return 0;
+}
+
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
+
+/************** End of fts3_hash.c *******************************************/
+/************** Begin file fts3_porter.c *************************************/
+/*
+** 2006 September 30
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** Implementation of the full-text-search tokenizer that implements
+** a Porter stemmer.
+*/
+
+/*
+** The code in this file is only compiled if:
+**
+** * The FTS3 module is being built as an extension
+** (in which case SQLITE_CORE is not defined), or
+**
+** * The FTS3 module is being built into the core of
+** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
+*/
+/* #include "fts3Int.h" */
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
+
+/* #include <assert.h> */
+/* #include <stdlib.h> */
+/* #include <stdio.h> */
+/* #include <string.h> */
+
+/* #include "fts3_tokenizer.h" */
+
+/*
+** Class derived from sqlite3_tokenizer
+*/
+typedef struct porter_tokenizer {
+ sqlite3_tokenizer base; /* Base class */
+} porter_tokenizer;
+
+/*
+** Class derived from sqlite3_tokenizer_cursor
+*/
+typedef struct porter_tokenizer_cursor {
+ sqlite3_tokenizer_cursor base;
+ const char *zInput; /* input we are tokenizing */
+ int nInput; /* size of the input */
+ int iOffset; /* current position in zInput */
+ int iToken; /* index of next token to be returned */
+ char *zToken; /* storage for current token */
+ int nAllocated; /* space allocated to zToken buffer */
+} porter_tokenizer_cursor;
+
+
+/*
+** Create a new tokenizer instance.
+*/
+static int porterCreate(
+ int argc, const char * const *argv,
+ sqlite3_tokenizer **ppTokenizer
+){
+ porter_tokenizer *t;
+
+ UNUSED_PARAMETER(argc);
+ UNUSED_PARAMETER(argv);
+
+ t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
+ if( t==NULL ) return SQLITE_NOMEM;
+ memset(t, 0, sizeof(*t));
+ *ppTokenizer = &t->base;
+ return SQLITE_OK;
+}
+
+/*
+** Destroy a tokenizer
+*/
+static int porterDestroy(sqlite3_tokenizer *pTokenizer){
+ sqlite3_free(pTokenizer);
+ return SQLITE_OK;
+}
+
+/*
+** Prepare to begin tokenizing a particular string. The input
+** string to be tokenized is zInput[0..nInput-1]. A cursor
+** used to incrementally tokenize this string is returned in
+** *ppCursor.
+*/
+static int porterOpen(
+ sqlite3_tokenizer *pTokenizer, /* The tokenizer */
+ const char *zInput, int nInput, /* String to be tokenized */
+ sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
+){
+ porter_tokenizer_cursor *c;
+
+ UNUSED_PARAMETER(pTokenizer);
+
+ c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
+ if( c==NULL ) return SQLITE_NOMEM;
+
+ c->zInput = zInput;
+ if( zInput==0 ){
+ c->nInput = 0;
+ }else if( nInput<0 ){
+ c->nInput = (int)strlen(zInput);
+ }else{
+ c->nInput = nInput;
+ }
+ c->iOffset = 0; /* start tokenizing at the beginning */
+ c->iToken = 0;
+ c->zToken = NULL; /* no space allocated, yet. */
+ c->nAllocated = 0;
+
+ *ppCursor = &c->base;
+ return SQLITE_OK;
+}
+
+/*
+** Close a tokenization cursor previously opened by a call to
+** porterOpen() above.
+*/
+static int porterClose(sqlite3_tokenizer_cursor *pCursor){
+ porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
+ sqlite3_free(c->zToken);
+ sqlite3_free(c);
+ return SQLITE_OK;
+}
+/*
+** Vowel or consonant
+*/
+static const char cType[] = {
+ 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
+ 1, 1, 1, 2, 1
+};
+
+/*
+** isConsonant() and isVowel() determine if their first character in
+** the string they point to is a consonant or a vowel, according
+** to Porter ruls.
+**
+** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
+** 'Y' is a consonant unless it follows another consonant,
+** in which case it is a vowel.
+**
+** In these routine, the letters are in reverse order. So the 'y' rule
+** is that 'y' is a consonant unless it is followed by another
+** consonent.
+*/
+static int isVowel(const char*);
+static int isConsonant(const char *z){
+ int j;
+ char x = *z;
+ if( x==0 ) return 0;
+ assert( x>='a' && x<='z' );
+ j = cType[x-'a'];
+ if( j<2 ) return j;
+ return z[1]==0 || isVowel(z + 1);
+}
+static int isVowel(const char *z){
+ int j;
+ char x = *z;
+ if( x==0 ) return 0;
+ assert( x>='a' && x<='z' );
+ j = cType[x-'a'];
+ if( j<2 ) return 1-j;
+ return isConsonant(z + 1);
+}
+
+/*
+** Let any sequence of one or more vowels be represented by V and let
+** C be sequence of one or more consonants. Then every word can be
+** represented as:
+**
+** [C] (VC){m} [V]
+**
+** In prose: A word is an optional consonant followed by zero or
+** vowel-consonant pairs followed by an optional vowel. "m" is the
+** number of vowel consonant pairs. This routine computes the value
+** of m for the first i bytes of a word.
+**
+** Return true if the m-value for z is 1 or more. In other words,
+** return true if z contains at least one vowel that is followed
+** by a consonant.
+**
+** In this routine z[] is in reverse order. So we are really looking
+** for an instance of a consonant followed by a vowel.
+*/
+static int m_gt_0(const char *z){
+ while( isVowel(z) ){ z++; }
+ if( *z==0 ) return 0;
+ while( isConsonant(z) ){ z++; }
+ return *z!=0;
+}
+
+/* Like mgt0 above except we are looking for a value of m which is
+** exactly 1
+*/
+static int m_eq_1(const char *z){
+ while( isVowel(z) ){ z++; }
+ if( *z==0 ) return 0;
+ while( isConsonant(z) ){ z++; }
+ if( *z==0 ) return 0;
+ while( isVowel(z) ){ z++; }
+ if( *z==0 ) return 1;
+ while( isConsonant(z) ){ z++; }
+ return *z==0;
+}
+
+/* Like mgt0 above except we are looking for a value of m>1 instead
+** or m>0
+*/
+static int m_gt_1(const char *z){
+ while( isVowel(z) ){ z++; }
+ if( *z==0 ) return 0;
+ while( isConsonant(z) ){ z++; }
+ if( *z==0 ) return 0;
+ while( isVowel(z) ){ z++; }
+ if( *z==0 ) return 0;
+ while( isConsonant(z) ){ z++; }
+ return *z!=0;
+}
+
+/*
+** Return TRUE if there is a vowel anywhere within z[0..n-1]
+*/
+static int hasVowel(const char *z){
+ while( isConsonant(z) ){ z++; }
+ return *z!=0;
+}
+
+/*
+** Return TRUE if the word ends in a double consonant.
+**
+** The text is reversed here. So we are really looking at
+** the first two characters of z[].
+*/
+static int doubleConsonant(const char *z){
+ return isConsonant(z) && z[0]==z[1];
+}
+
+/*
+** Return TRUE if the word ends with three letters which
+** are consonant-vowel-consonent and where the final consonant
+** is not 'w', 'x', or 'y'.
+**
+** The word is reversed here. So we are really checking the
+** first three letters and the first one cannot be in [wxy].
+*/
+static int star_oh(const char *z){
+ return
+ isConsonant(z) &&
+ z[0]!='w' && z[0]!='x' && z[0]!='y' &&
+ isVowel(z+1) &&
+ isConsonant(z+2);
+}
+
+/*
+** If the word ends with zFrom and xCond() is true for the stem
+** of the word that preceeds the zFrom ending, then change the
+** ending to zTo.
+**
+** The input word *pz and zFrom are both in reverse order. zTo
+** is in normal order.
+**
+** Return TRUE if zFrom matches. Return FALSE if zFrom does not
+** match. Not that TRUE is returned even if xCond() fails and
+** no substitution occurs.
+*/
+static int stem(
+ char **pz, /* The word being stemmed (Reversed) */
+ const char *zFrom, /* If the ending matches this... (Reversed) */
+ const char *zTo, /* ... change the ending to this (not reversed) */
+ int (*xCond)(const char*) /* Condition that must be true */
+){
+ char *z = *pz;
+ while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
+ if( *zFrom!=0 ) return 0;
+ if( xCond && !xCond(z) ) return 1;
+ while( *zTo ){
+ *(--z) = *(zTo++);
+ }
+ *pz = z;
+ return 1;
+}
+
+/*
+** This is the fallback stemmer used when the porter stemmer is
+** inappropriate. The input word is copied into the output with
+** US-ASCII case folding. If the input word is too long (more
+** than 20 bytes if it contains no digits or more than 6 bytes if
+** it contains digits) then word is truncated to 20 or 6 bytes
+** by taking 10 or 3 bytes from the beginning and end.
+*/
+static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
+ int i, mx, j;
+ int hasDigit = 0;
+ for(i=0; i<nIn; i++){
+ char c = zIn[i];
+ if( c>='A' && c<='Z' ){
+ zOut[i] = c - 'A' + 'a';
+ }else{
+ if( c>='0' && c<='9' ) hasDigit = 1;
+ zOut[i] = c;
+ }
+ }
+ mx = hasDigit ? 3 : 10;
+ if( nIn>mx*2 ){
+ for(j=mx, i=nIn-mx; i<nIn; i++, j++){
+ zOut[j] = zOut[i];
+ }
+ i = j;
+ }
+ zOut[i] = 0;
+ *pnOut = i;
+}
+
+
+/*
+** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
+** zOut is at least big enough to hold nIn bytes. Write the actual
+** size of the output word (exclusive of the '\0' terminator) into *pnOut.
+**
+** Any upper-case characters in the US-ASCII character set ([A-Z])
+** are converted to lower case. Upper-case UTF characters are
+** unchanged.
+**
+** Words that are longer than about 20 bytes are stemmed by retaining
+** a few bytes from the beginning and the end of the word. If the
+** word contains digits, 3 bytes are taken from the beginning and
+** 3 bytes from the end. For long words without digits, 10 bytes
+** are taken from each end. US-ASCII case folding still applies.
+**
+** If the input word contains not digits but does characters not
+** in [a-zA-Z] then no stemming is attempted and this routine just
+** copies the input into the input into the output with US-ASCII
+** case folding.
+**
+** Stemming never increases the length of the word. So there is
+** no chance of overflowing the zOut buffer.
+*/
+static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
+ int i, j;
+ char zReverse[28];
+ char *z, *z2;
+ if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
+ /* The word is too big or too small for the porter stemmer.
+ ** Fallback to the copy stemmer */
+ copy_stemmer(zIn, nIn, zOut, pnOut);
+ return;
+ }
+ for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
+ char c = zIn[i];
+ if( c>='A' && c<='Z' ){
+ zReverse[j] = c + 'a' - 'A';
+ }else if( c>='a' && c<='z' ){
+ zReverse[j] = c;
+ }else{
+ /* The use of a character not in [a-zA-Z] means that we fallback
+ ** to the copy stemmer */
+ copy_stemmer(zIn, nIn, zOut, pnOut);
+ return;
+ }
+ }
+ memset(&zReverse[sizeof(zReverse)-5], 0, 5);
+ z = &zReverse[j+1];
+
+
+ /* Step 1a */
+ if( z[0]=='s' ){
+ if(
+ !stem(&z, "sess", "ss", 0) &&
+ !stem(&z, "sei", "i", 0) &&
+ !stem(&z, "ss", "ss", 0)
+ ){
+ z++;
+ }
+ }
+
+ /* Step 1b */
+ z2 = z;
+ if( stem(&z, "dee", "ee", m_gt_0) ){
+ /* Do nothing. The work was all in the test */
+ }else if(
+ (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
+ && z!=z2
+ ){
+ if( stem(&z, "ta", "ate", 0) ||
+ stem(&z, "lb", "ble", 0) ||
+ stem(&z, "zi", "ize", 0) ){
+ /* Do nothing. The work was all in the test */
+ }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
+ z++;
+ }else if( m_eq_1(z) && star_oh(z) ){
+ *(--z) = 'e';
+ }
+ }
+
+ /* Step 1c */
+ if( z[0]=='y' && hasVowel(z+1) ){
+ z[0] = 'i';
+ }
+
+ /* Step 2 */
+ switch( z[1] ){
+ case 'a':
+ if( !stem(&z, "lanoita", "ate", m_gt_0) ){
+ stem(&z, "lanoit", "tion", m_gt_0);
+ }
+ break;
+ case 'c':
+ if( !stem(&z, "icne", "ence", m_gt_0) ){
+ stem(&z, "icna", "ance", m_gt_0);
+ }
+ break;
+ case 'e':
+ stem(&z, "rezi", "ize", m_gt_0);
+ break;
+ case 'g':
+ stem(&z, "igol", "log", m_gt_0);
+ break;
+ case 'l':
+ if( !stem(&z, "ilb", "ble", m_gt_0)
+ && !stem(&z, "illa", "al", m_gt_0)
+ && !stem(&z, "iltne", "ent", m_gt_0)
+ && !stem(&z, "ile", "e", m_gt_0)
+ ){
+ stem(&z, "ilsuo", "ous", m_gt_0);
+ }
+ break;
+ case 'o':
+ if( !stem(&z, "noitazi", "ize", m_gt_0)
+ && !stem(&z, "noita", "ate", m_gt_0)
+ ){
+ stem(&z, "rota", "ate", m_gt_0);
+ }
+ break;
+ case 's':
+ if( !stem(&z, "msila", "al", m_gt_0)
+ && !stem(&z, "ssenevi", "ive", m_gt_0)
+ && !stem(&z, "ssenluf", "ful", m_gt_0)
+ ){
+ stem(&z, "ssensuo", "ous", m_gt_0);
+ }
+ break;
+ case 't':
+ if( !stem(&z, "itila", "al", m_gt_0)
+ && !stem(&z, "itivi", "ive", m_gt_0)
+ ){
+ stem(&z, "itilib", "ble", m_gt_0);
+ }
+ break;
+ }
+
+ /* Step 3 */
+ switch( z[0] ){
+ case 'e':
+ if( !stem(&z, "etaci", "ic", m_gt_0)
+ && !stem(&z, "evita", "", m_gt_0)
+ ){
+ stem(&z, "ezila", "al", m_gt_0);
+ }
+ break;
+ case 'i':
+ stem(&z, "itici", "ic", m_gt_0);
+ break;
+ case 'l':
+ if( !stem(&z, "laci", "ic", m_gt_0) ){
+ stem(&z, "luf", "", m_gt_0);
+ }
+ break;
+ case 's':
+ stem(&z, "ssen", "", m_gt_0);
+ break;
+ }
+
+ /* Step 4 */
+ switch( z[1] ){
+ case 'a':
+ if( z[0]=='l' && m_gt_1(z+2) ){
+ z += 2;
+ }
+ break;
+ case 'c':
+ if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
+ z += 4;
+ }
+ break;
+ case 'e':
+ if( z[0]=='r' && m_gt_1(z+2) ){
+ z += 2;
+ }
+ break;
+ case 'i':
+ if( z[0]=='c' && m_gt_1(z+2) ){
+ z += 2;
+ }
+ break;
+ case 'l':
+ if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
+ z += 4;
+ }
+ break;
+ case 'n':
+ if( z[0]=='t' ){
+ if( z[2]=='a' ){
+ if( m_gt_1(z+3) ){
+ z += 3;
+ }
+ }else if( z[2]=='e' ){
+ if( !stem(&z, "tneme", "", m_gt_1)
+ && !stem(&z, "tnem", "", m_gt_1)
+ ){
+ stem(&z, "tne", "", m_gt_1);
+ }
+ }
+ }
+ break;
+ case 'o':
+ if( z[0]=='u' ){
+ if( m_gt_1(z+2) ){
+ z += 2;
+ }
+ }else if( z[3]=='s' || z[3]=='t' ){
+ stem(&z, "noi", "", m_gt_1);
+ }
+ break;
+ case 's':
+ if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
+ z += 3;
+ }
+ break;
+ case 't':
+ if( !stem(&z, "eta", "", m_gt_1) ){
+ stem(&z, "iti", "", m_gt_1);
+ }
+ break;
+ case 'u':
+ if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
+ z += 3;
+ }
+ break;
+ case 'v':
+ case 'z':
+ if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
+ z += 3;
+ }
+ break;
+ }
+
+ /* Step 5a */
+ if( z[0]=='e' ){
+ if( m_gt_1(z+1) ){
+ z++;
+ }else if( m_eq_1(z+1) && !star_oh(z+1) ){
+ z++;
+ }
+ }
+
+ /* Step 5b */
+ if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
+ z++;
+ }
+
+ /* z[] is now the stemmed word in reverse order. Flip it back
+ ** around into forward order and return.
+ */
+ *pnOut = i = (int)strlen(z);
+ zOut[i] = 0;
+ while( *z ){
+ zOut[--i] = *(z++);
+ }
+}
+
+/*
+** Characters that can be part of a token. We assume any character
+** whose value is greater than 0x80 (any UTF character) can be
+** part of a token. In other words, delimiters all must have
+** values of 0x7f or lower.
+*/
+static const char porterIdChar[] = {
+/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
+};
+#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
+
+/*
+** Extract the next token from a tokenization cursor. The cursor must
+** have been opened by a prior call to porterOpen().
+*/
+static int porterNext(
+ sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
+ const char **pzToken, /* OUT: *pzToken is the token text */
+ int *pnBytes, /* OUT: Number of bytes in token */
+ int *piStartOffset, /* OUT: Starting offset of token */
+ int *piEndOffset, /* OUT: Ending offset of token */
+ int *piPosition /* OUT: Position integer of token */
+){
+ porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
+ const char *z = c->zInput;
+
+ while( c->iOffset<c->nInput ){
+ int iStartOffset, ch;
+
+ /* Scan past delimiter characters */
+ while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
+ c->iOffset++;
+ }
+
+ /* Count non-delimiter characters. */
+ iStartOffset = c->iOffset;
+ while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
+ c->iOffset++;
+ }
+
+ if( c->iOffset>iStartOffset ){
+ int n = c->iOffset-iStartOffset;
+ if( n>c->nAllocated ){
+ char *pNew;
+ c->nAllocated = n+20;
+ pNew = sqlite3_realloc(c->zToken, c->nAllocated);
+ if( !pNew ) return SQLITE_NOMEM;
+ c->zToken = pNew;
+ }
+ porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
+ *pzToken = c->zToken;
+ *piStartOffset = iStartOffset;
+ *piEndOffset = c->iOffset;
+ *piPosition = c->iToken++;
+ return SQLITE_OK;
+ }
+ }
+ return SQLITE_DONE;
+}
+
+/*
+** The set of routines that implement the porter-stemmer tokenizer
+*/
+static const sqlite3_tokenizer_module porterTokenizerModule = {
+ 0,
+ porterCreate,
+ porterDestroy,
+ porterOpen,
+ porterClose,
+ porterNext,
+ 0
+};
+
+/*
+** Allocate a new porter tokenizer. Return a pointer to the new
+** tokenizer in *ppModule
+*/
+SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
+ sqlite3_tokenizer_module const**ppModule
+){
+ *ppModule = &porterTokenizerModule;
+}
+
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
+
+/************** End of fts3_porter.c *****************************************/
+/************** Begin file fts3_tokenizer.c **********************************/
+/*
+** 2007 June 22
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This is part of an SQLite module implementing full-text search.
+** This particular file implements the generic tokenizer interface.
+*/
+
+/*
+** The code in this file is only compiled if:
+**
+** * The FTS3 module is being built as an extension
+** (in which case SQLITE_CORE is not defined), or
+**
+** * The FTS3 module is being built into the core of
+** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
+*/
+/* #include "fts3Int.h" */
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
+
+/* #include <assert.h> */
+/* #include <string.h> */
+
+/*
+** Return true if the two-argument version of fts3_tokenizer()
+** has been activated via a prior call to sqlite3_db_config(db,
+** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
+*/
+static int fts3TokenizerEnabled(sqlite3_context *context){
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ int isEnabled = 0;
+ sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
+ return isEnabled;
+}
+
+/*
+** Implementation of the SQL scalar function for accessing the underlying
+** hash table. This function may be called as follows:
+**
+** SELECT <function-name>(<key-name>);
+** SELECT <function-name>(<key-name>, <pointer>);
+**
+** where <function-name> is the name passed as the second argument
+** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
+**
+** If the <pointer> argument is specified, it must be a blob value
+** containing a pointer to be stored as the hash data corresponding
+** to the string <key-name>. If <pointer> is not specified, then
+** the string <key-name> must already exist in the has table. Otherwise,
+** an error is returned.
+**
+** Whether or not the <pointer> argument is specified, the value returned
+** is a blob containing the pointer stored as the hash data corresponding
+** to string <key-name> (after the hash-table is updated, if applicable).
+*/
+static void fts3TokenizerFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ Fts3Hash *pHash;
+ void *pPtr = 0;
+ const unsigned char *zName;
+ int nName;
+
+ assert( argc==1 || argc==2 );
+
+ pHash = (Fts3Hash *)sqlite3_user_data(context);
+
+ zName = sqlite3_value_text(argv[0]);
+ nName = sqlite3_value_bytes(argv[0])+1;
+
+ if( argc==2 ){
+ if( fts3TokenizerEnabled(context) || sqlite3_value_frombind(argv[1]) ){
+ void *pOld;
+ int n = sqlite3_value_bytes(argv[1]);
+ if( zName==0 || n!=sizeof(pPtr) ){
+ sqlite3_result_error(context, "argument type mismatch", -1);
+ return;
+ }
+ pPtr = *(void **)sqlite3_value_blob(argv[1]);
+ pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
+ if( pOld==pPtr ){
+ sqlite3_result_error(context, "out of memory", -1);
+ }
+ }else{
+ sqlite3_result_error(context, "fts3tokenize disabled", -1);
+ return;
+ }
+ }else{
+ if( zName ){
+ pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
+ }
+ if( !pPtr ){
+ char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
+ sqlite3_result_error(context, zErr, -1);
+ sqlite3_free(zErr);
+ return;
+ }
+ }
+ if( fts3TokenizerEnabled(context) || sqlite3_value_frombind(argv[0]) ){
+ sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
+ }
+}
+
+SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
+ static const char isFtsIdChar[] = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
+ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
+ };
+ return (c&0x80 || isFtsIdChar[(int)(c)]);
+}
+
+SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
+ const char *z1;
+ const char *z2 = 0;
+
+ /* Find the start of the next token. */
+ z1 = zStr;
+ while( z2==0 ){
+ char c = *z1;
+ switch( c ){
+ case '\0': return 0; /* No more tokens here */
+ case '\'':
+ case '"':
+ case '`': {
+ z2 = z1;
+ while( *++z2 && (*z2!=c || *++z2==c) );
+ break;
+ }
+ case '[':
+ z2 = &z1[1];
+ while( *z2 && z2[0]!=']' ) z2++;
+ if( *z2 ) z2++;
+ break;
+
+ default:
+ if( sqlite3Fts3IsIdChar(*z1) ){
+ z2 = &z1[1];
+ while( sqlite3Fts3IsIdChar(*z2) ) z2++;
+ }else{
+ z1++;
+ }
+ }
+ }
+
+ *pn = (int)(z2-z1);
+ return z1;
+}
+
+SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
+ Fts3Hash *pHash, /* Tokenizer hash table */
+ const char *zArg, /* Tokenizer name */
+ sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
+ char **pzErr /* OUT: Set to malloced error message */
+){
+ int rc;
+ char *z = (char *)zArg;
+ int n = 0;
+ char *zCopy;
+ char *zEnd; /* Pointer to nul-term of zCopy */
+ sqlite3_tokenizer_module *m;
+
+ zCopy = sqlite3_mprintf("%s", zArg);
+ if( !zCopy ) return SQLITE_NOMEM;
+ zEnd = &zCopy[strlen(zCopy)];
+
+ z = (char *)sqlite3Fts3NextToken(zCopy, &n);
+ if( z==0 ){
+ assert( n==0 );
+ z = zCopy;
+ }
+ z[n] = '\0';
+ sqlite3Fts3Dequote(z);
+
+ m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
+ if( !m ){
+ sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
+ rc = SQLITE_ERROR;
+ }else{
+ char const **aArg = 0;
+ int iArg = 0;
+ z = &z[n+1];
+ while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
+ sqlite3_int64 nNew = sizeof(char *)*(iArg+1);
+ char const **aNew = (const char **)sqlite3_realloc64((void *)aArg, nNew);
+ if( !aNew ){
+ sqlite3_free(zCopy);
+ sqlite3_free((void *)aArg);
+ return SQLITE_NOMEM;
+ }
+ aArg = aNew;
+ aArg[iArg++] = z;
+ z[n] = '\0';
+ sqlite3Fts3Dequote(z);
+ z = &z[n+1];
+ }
+ rc = m->xCreate(iArg, aArg, ppTok);
+ assert( rc!=SQLITE_OK || *ppTok );
+ if( rc!=SQLITE_OK ){
+ sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
+ }else{
+ (*ppTok)->pModule = m;
+ }
+ sqlite3_free((void *)aArg);
+ }
+
+ sqlite3_free(zCopy);
+ return rc;
+}
+
+
+#ifdef SQLITE_TEST
+
+#if defined(INCLUDE_SQLITE_TCL_H)
+# include "sqlite_tcl.h"
+#else
+# include "tcl.h"
+#endif
+/* #include <string.h> */
+
+/*
+** Implementation of a special SQL scalar function for testing tokenizers
+** designed to be used in concert with the Tcl testing framework. This
+** function must be called with two or more arguments:
+**
+** SELECT <function-name>(<key-name>, ..., <input-string>);
+**
+** where <function-name> is the name passed as the second argument
+** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
+** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
+**
+** The return value is a string that may be interpreted as a Tcl
+** list. For each token in the <input-string>, three elements are
+** added to the returned list. The first is the token position, the
+** second is the token text (folded, stemmed, etc.) and the third is the
+** substring of <input-string> associated with the token. For example,
+** using the built-in "simple" tokenizer:
+**
+** SELECT fts_tokenizer_test('simple', 'I don't see how');
+**
+** will return the string:
+**
+** "{0 i I 1 dont don't 2 see see 3 how how}"
+**
+*/
+static void testFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ Fts3Hash *pHash;
+ sqlite3_tokenizer_module *p;
+ sqlite3_tokenizer *pTokenizer = 0;
+ sqlite3_tokenizer_cursor *pCsr = 0;
+
+ const char *zErr = 0;
+
+ const char *zName;
+ int nName;
+ const char *zInput;
+ int nInput;
+
+ const char *azArg[64];
+
+ const char *zToken;
+ int nToken = 0;
+ int iStart = 0;
+ int iEnd = 0;
+ int iPos = 0;
+ int i;
+
+ Tcl_Obj *pRet;
+
+ if( argc<2 ){
+ sqlite3_result_error(context, "insufficient arguments", -1);
+ return;
+ }
+
+ nName = sqlite3_value_bytes(argv[0]);
+ zName = (const char *)sqlite3_value_text(argv[0]);
+ nInput = sqlite3_value_bytes(argv[argc-1]);
+ zInput = (const char *)sqlite3_value_text(argv[argc-1]);
+
+ pHash = (Fts3Hash *)sqlite3_user_data(context);
+ p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
+
+ if( !p ){
+ char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
+ sqlite3_result_error(context, zErr2, -1);
+ sqlite3_free(zErr2);
+ return;
+ }
+
+ pRet = Tcl_NewObj();
+ Tcl_IncrRefCount(pRet);
+
+ for(i=1; i<argc-1; i++){
+ azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
+ }
+
+ if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
+ zErr = "error in xCreate()";
+ goto finish;
+ }
+ pTokenizer->pModule = p;
+ if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
+ zErr = "error in xOpen()";
+ goto finish;
+ }
+
+ while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
+ Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
+ Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
+ zToken = &zInput[iStart];
+ nToken = iEnd-iStart;
+ Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
+ }
+
+ if( SQLITE_OK!=p->xClose(pCsr) ){
+ zErr = "error in xClose()";
+ goto finish;
+ }
+ if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
+ zErr = "error in xDestroy()";
+ goto finish;
+ }
+
+finish:
+ if( zErr ){
+ sqlite3_result_error(context, zErr, -1);
+ }else{
+ sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
+ }
+ Tcl_DecrRefCount(pRet);
+}
+
+static
+int registerTokenizer(
+ sqlite3 *db,
+ char *zName,
+ const sqlite3_tokenizer_module *p
+){
+ int rc;
+ sqlite3_stmt *pStmt;
+ const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
+
+ rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+
+ sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
+ sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
+ sqlite3_step(pStmt);
+
+ return sqlite3_finalize(pStmt);
+}
+
+
+static
+int queryTokenizer(
+ sqlite3 *db,
+ char *zName,
+ const sqlite3_tokenizer_module **pp
+){
+ int rc;
+ sqlite3_stmt *pStmt;
+ const char zSql[] = "SELECT fts3_tokenizer(?)";
+
+ *pp = 0;
+ rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+
+ sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
+ if( SQLITE_ROW==sqlite3_step(pStmt) ){
+ if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB
+ && sqlite3_column_bytes(pStmt, 0)==sizeof(*pp)
+ ){
+ memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
+ }
+ }
+
+ return sqlite3_finalize(pStmt);
+}
+
+SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
+
+/*
+** Implementation of the scalar function fts3_tokenizer_internal_test().
+** This function is used for testing only, it is not included in the
+** build unless SQLITE_TEST is defined.
+**
+** The purpose of this is to test that the fts3_tokenizer() function
+** can be used as designed by the C-code in the queryTokenizer and
+** registerTokenizer() functions above. These two functions are repeated
+** in the README.tokenizer file as an example, so it is important to
+** test them.
+**
+** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
+** function with no arguments. An assert() will fail if a problem is
+** detected. i.e.:
+**
+** SELECT fts3_tokenizer_internal_test();
+**
+*/
+static void intTestFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ int rc;
+ const sqlite3_tokenizer_module *p1;
+ const sqlite3_tokenizer_module *p2;
+ sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
+
+ UNUSED_PARAMETER(argc);
+ UNUSED_PARAMETER(argv);
+
+ /* Test the query function */
+ sqlite3Fts3SimpleTokenizerModule(&p1);
+ rc = queryTokenizer(db, "simple", &p2);
+ assert( rc==SQLITE_OK );
+ assert( p1==p2 );
+ rc = queryTokenizer(db, "nosuchtokenizer", &p2);
+ assert( rc==SQLITE_ERROR );
+ assert( p2==0 );
+ assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
+
+ /* Test the storage function */
+ if( fts3TokenizerEnabled(context) ){
+ rc = registerTokenizer(db, "nosuchtokenizer", p1);
+ assert( rc==SQLITE_OK );
+ rc = queryTokenizer(db, "nosuchtokenizer", &p2);
+ assert( rc==SQLITE_OK );
+ assert( p2==p1 );
+ }
+
+ sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
+}
+
+#endif
+
+/*
+** Set up SQL objects in database db used to access the contents of
+** the hash table pointed to by argument pHash. The hash table must
+** been initialized to use string keys, and to take a private copy
+** of the key when a value is inserted. i.e. by a call similar to:
+**
+** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
+**
+** This function adds a scalar function (see header comment above
+** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
+** defined at compilation time, a temporary virtual table (see header
+** comment above struct HashTableVtab) to the database schema. Both
+** provide read/write access to the contents of *pHash.
+**
+** The third argument to this function, zName, is used as the name
+** of both the scalar and, if created, the virtual table.
+*/
+SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
+ sqlite3 *db,
+ Fts3Hash *pHash,
+ const char *zName
+){
+ int rc = SQLITE_OK;
+ void *p = (void *)pHash;
+ const int any = SQLITE_UTF8|SQLITE_DIRECTONLY;
+
+#ifdef SQLITE_TEST
+ char *zTest = 0;
+ char *zTest2 = 0;
+ void *pdb = (void *)db;
+ zTest = sqlite3_mprintf("%s_test", zName);
+ zTest2 = sqlite3_mprintf("%s_internal_test", zName);
+ if( !zTest || !zTest2 ){
+ rc = SQLITE_NOMEM;
+ }
+#endif
+
+ if( SQLITE_OK==rc ){
+ rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
+ }
+ if( SQLITE_OK==rc ){
+ rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
+ }
+#ifdef SQLITE_TEST
+ if( SQLITE_OK==rc ){
+ rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
+ }
+ if( SQLITE_OK==rc ){
+ rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
+ }
+#endif
+
+#ifdef SQLITE_TEST
+ sqlite3_free(zTest);
+ sqlite3_free(zTest2);
+#endif
+
+ return rc;
+}
+
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
+
+/************** End of fts3_tokenizer.c **************************************/
+/************** Begin file fts3_tokenizer1.c *********************************/
+/*
+** 2006 Oct 10
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** Implementation of the "simple" full-text-search tokenizer.
+*/
+
+/*
+** The code in this file is only compiled if:
+**
+** * The FTS3 module is being built as an extension
+** (in which case SQLITE_CORE is not defined), or
+**
+** * The FTS3 module is being built into the core of
+** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
+*/
+/* #include "fts3Int.h" */
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
+
+/* #include <assert.h> */
+/* #include <stdlib.h> */
+/* #include <stdio.h> */
+/* #include <string.h> */
+
+/* #include "fts3_tokenizer.h" */
+
+typedef struct simple_tokenizer {
+ sqlite3_tokenizer base;
+ char delim[128]; /* flag ASCII delimiters */
+} simple_tokenizer;
+
+typedef struct simple_tokenizer_cursor {
+ sqlite3_tokenizer_cursor base;
+ const char *pInput; /* input we are tokenizing */
+ int nBytes; /* size of the input */
+ int iOffset; /* current position in pInput */
+ int iToken; /* index of next token to be returned */
+ char *pToken; /* storage for current token */
+ int nTokenAllocated; /* space allocated to zToken buffer */
+} simple_tokenizer_cursor;
+
+
+static int simpleDelim(simple_tokenizer *t, unsigned char c){
+ return c<0x80 && t->delim[c];
+}
+static int fts3_isalnum(int x){
+ return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
+}
+
+/*
+** Create a new tokenizer instance.
+*/
+static int simpleCreate(
+ int argc, const char * const *argv,
+ sqlite3_tokenizer **ppTokenizer
+){
+ simple_tokenizer *t;
+
+ t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
+ if( t==NULL ) return SQLITE_NOMEM;
+ memset(t, 0, sizeof(*t));
+
+ /* TODO(shess) Delimiters need to remain the same from run to run,
+ ** else we need to reindex. One solution would be a meta-table to
+ ** track such information in the database, then we'd only want this
+ ** information on the initial create.
+ */
+ if( argc>1 ){
+ int i, n = (int)strlen(argv[1]);
+ for(i=0; i<n; i++){
+ unsigned char ch = argv[1][i];
+ /* We explicitly don't support UTF-8 delimiters for now. */
+ if( ch>=0x80 ){
+ sqlite3_free(t);
+ return SQLITE_ERROR;
+ }
+ t->delim[ch] = 1;
+ }
+ } else {
+ /* Mark non-alphanumeric ASCII characters as delimiters */
+ int i;
+ for(i=1; i<0x80; i++){
+ t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
+ }
+ }
+
+ *ppTokenizer = &t->base;
+ return SQLITE_OK;
+}
+
+/*
+** Destroy a tokenizer
+*/
+static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
+ sqlite3_free(pTokenizer);
+ return SQLITE_OK;
+}
+
+/*
+** Prepare to begin tokenizing a particular string. The input
+** string to be tokenized is pInput[0..nBytes-1]. A cursor
+** used to incrementally tokenize this string is returned in
+** *ppCursor.
+*/
+static int simpleOpen(
+ sqlite3_tokenizer *pTokenizer, /* The tokenizer */
+ const char *pInput, int nBytes, /* String to be tokenized */
+ sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
+){
+ simple_tokenizer_cursor *c;
+
+ UNUSED_PARAMETER(pTokenizer);
+
+ c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
+ if( c==NULL ) return SQLITE_NOMEM;
+
+ c->pInput = pInput;
+ if( pInput==0 ){
+ c->nBytes = 0;
+ }else if( nBytes<0 ){
+ c->nBytes = (int)strlen(pInput);
+ }else{
+ c->nBytes = nBytes;
+ }
+ c->iOffset = 0; /* start tokenizing at the beginning */
+ c->iToken = 0;
+ c->pToken = NULL; /* no space allocated, yet. */
+ c->nTokenAllocated = 0;
+
+ *ppCursor = &c->base;
+ return SQLITE_OK;
+}
+
+/*
+** Close a tokenization cursor previously opened by a call to
+** simpleOpen() above.
+*/
+static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
+ simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
+ sqlite3_free(c->pToken);
+ sqlite3_free(c);
+ return SQLITE_OK;
+}
+
+/*
+** Extract the next token from a tokenization cursor. The cursor must
+** have been opened by a prior call to simpleOpen().
+*/
+static int simpleNext(
+ sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
+ const char **ppToken, /* OUT: *ppToken is the token text */
+ int *pnBytes, /* OUT: Number of bytes in token */
+ int *piStartOffset, /* OUT: Starting offset of token */
+ int *piEndOffset, /* OUT: Ending offset of token */
+ int *piPosition /* OUT: Position integer of token */
+){
+ simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
+ simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
+ unsigned char *p = (unsigned char *)c->pInput;
+
+ while( c->iOffset<c->nBytes ){
+ int iStartOffset;
+
+ /* Scan past delimiter characters */
+ while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
+ c->iOffset++;
+ }
+
+ /* Count non-delimiter characters. */
+ iStartOffset = c->iOffset;
+ while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
+ c->iOffset++;
+ }
+
+ if( c->iOffset>iStartOffset ){
+ int i, n = c->iOffset-iStartOffset;
+ if( n>c->nTokenAllocated ){
+ char *pNew;
+ c->nTokenAllocated = n+20;
+ pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
+ if( !pNew ) return SQLITE_NOMEM;
+ c->pToken = pNew;
+ }
+ for(i=0; i<n; i++){
+ /* TODO(shess) This needs expansion to handle UTF-8
+ ** case-insensitivity.
+ */
+ unsigned char ch = p[iStartOffset+i];
+ c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
+ }
+ *ppToken = c->pToken;
+ *pnBytes = n;
+ *piStartOffset = iStartOffset;
+ *piEndOffset = c->iOffset;
+ *piPosition = c->iToken++;
+
+ return SQLITE_OK;
+ }
+ }
+ return SQLITE_DONE;
+}
+
+/*
+** The set of routines that implement the simple tokenizer
+*/
+static const sqlite3_tokenizer_module simpleTokenizerModule = {
+ 0,
+ simpleCreate,
+ simpleDestroy,
+ simpleOpen,
+ simpleClose,
+ simpleNext,
+ 0,
+};
+
+/*
+** Allocate a new simple tokenizer. Return a pointer to the new
+** tokenizer in *ppModule
+*/
+SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
+ sqlite3_tokenizer_module const**ppModule
+){
+ *ppModule = &simpleTokenizerModule;
+}
+
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
+
+/************** End of fts3_tokenizer1.c *************************************/
+/************** Begin file fts3_tokenize_vtab.c ******************************/
+/*
+** 2013 Apr 22
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains code for the "fts3tokenize" virtual table module.
+** An fts3tokenize virtual table is created as follows:
+**
+** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
+** <tokenizer-name>, <arg-1>, ...
+** );
+**
+** The table created has the following schema:
+**
+** CREATE TABLE <tbl>(input, token, start, end, position)
+**
+** When queried, the query must include a WHERE clause of type:
+**
+** input = <string>
+**
+** The virtual table module tokenizes this <string>, using the FTS3
+** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
+** statement and returns one row for each token in the result. With
+** fields set as follows:
+**
+** input: Always set to a copy of <string>
+** token: A token from the input.
+** start: Byte offset of the token within the input <string>.
+** end: Byte offset of the byte immediately following the end of the
+** token within the input string.
+** pos: Token offset of token within input.
+**
+*/
+/* #include "fts3Int.h" */
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
+
+/* #include <string.h> */
+/* #include <assert.h> */
+
+typedef struct Fts3tokTable Fts3tokTable;
+typedef struct Fts3tokCursor Fts3tokCursor;
+
+/*
+** Virtual table structure.
+*/
+struct Fts3tokTable {
+ sqlite3_vtab base; /* Base class used by SQLite core */
+ const sqlite3_tokenizer_module *pMod;
+ sqlite3_tokenizer *pTok;
+};
+
+/*
+** Virtual table cursor structure.
+*/
+struct Fts3tokCursor {
+ sqlite3_vtab_cursor base; /* Base class used by SQLite core */
+ char *zInput; /* Input string */
+ sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
+ int iRowid; /* Current 'rowid' value */
+ const char *zToken; /* Current 'token' value */
+ int nToken; /* Size of zToken in bytes */
+ int iStart; /* Current 'start' value */
+ int iEnd; /* Current 'end' value */
+ int iPos; /* Current 'pos' value */
+};
+
+/*
+** Query FTS for the tokenizer implementation named zName.
+*/
+static int fts3tokQueryTokenizer(
+ Fts3Hash *pHash,
+ const char *zName,
+ const sqlite3_tokenizer_module **pp,
+ char **pzErr
+){
+ sqlite3_tokenizer_module *p;
+ int nName = (int)strlen(zName);
+
+ p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
+ if( !p ){
+ sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
+ return SQLITE_ERROR;
+ }
+
+ *pp = p;
+ return SQLITE_OK;
+}
+
+/*
+** The second argument, argv[], is an array of pointers to nul-terminated
+** strings. This function makes a copy of the array and strings into a
+** single block of memory. It then dequotes any of the strings that appear
+** to be quoted.
+**
+** If successful, output parameter *pazDequote is set to point at the
+** array of dequoted strings and SQLITE_OK is returned. The caller is
+** responsible for eventually calling sqlite3_free() to free the array
+** in this case. Or, if an error occurs, an SQLite error code is returned.
+** The final value of *pazDequote is undefined in this case.
+*/
+static int fts3tokDequoteArray(
+ int argc, /* Number of elements in argv[] */
+ const char * const *argv, /* Input array */
+ char ***pazDequote /* Output array */
+){
+ int rc = SQLITE_OK; /* Return code */
+ if( argc==0 ){
+ *pazDequote = 0;
+ }else{
+ int i;
+ int nByte = 0;
+ char **azDequote;
+
+ for(i=0; i<argc; i++){
+ nByte += (int)(strlen(argv[i]) + 1);
+ }
+
+ *pazDequote = azDequote = sqlite3_malloc64(sizeof(char *)*argc + nByte);
+ if( azDequote==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ char *pSpace = (char *)&azDequote[argc];
+ for(i=0; i<argc; i++){
+ int n = (int)strlen(argv[i]);
+ azDequote[i] = pSpace;
+ memcpy(pSpace, argv[i], n+1);
+ sqlite3Fts3Dequote(pSpace);
+ pSpace += (n+1);
+ }
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Schema of the tokenizer table.
+*/
+#define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
+
+/*
+** This function does all the work for both the xConnect and xCreate methods.
+** These tables have no persistent representation of their own, so xConnect
+** and xCreate are identical operations.
+**
+** argv[0]: module name
+** argv[1]: database name
+** argv[2]: table name
+** argv[3]: first argument (tokenizer name)
+*/
+static int fts3tokConnectMethod(
+ sqlite3 *db, /* Database connection */
+ void *pHash, /* Hash table of tokenizers */
+ int argc, /* Number of elements in argv array */
+ const char * const *argv, /* xCreate/xConnect argument array */
+ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
+ char **pzErr /* OUT: sqlite3_malloc'd error message */
+){
+ Fts3tokTable *pTab = 0;
+ const sqlite3_tokenizer_module *pMod = 0;
+ sqlite3_tokenizer *pTok = 0;
+ int rc;
+ char **azDequote = 0;
+ int nDequote;
+
+ rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
+ if( rc!=SQLITE_OK ) return rc;
+
+ nDequote = argc-3;
+ rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
+
+ if( rc==SQLITE_OK ){
+ const char *zModule;
+ if( nDequote<1 ){
+ zModule = "simple";
+ }else{
+ zModule = azDequote[0];
+ }
+ rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
+ }
+
+ assert( (rc==SQLITE_OK)==(pMod!=0) );
+ if( rc==SQLITE_OK ){
+ const char * const *azArg = 0;
+ if( nDequote>1 ) azArg = (const char * const *)&azDequote[1];
+ rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
+ }
+
+ if( rc==SQLITE_OK ){
+ pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
+ if( pTab==0 ){
+ rc = SQLITE_NOMEM;
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ memset(pTab, 0, sizeof(Fts3tokTable));
+ pTab->pMod = pMod;
+ pTab->pTok = pTok;
+ *ppVtab = &pTab->base;
+ }else{
+ if( pTok ){
+ pMod->xDestroy(pTok);
+ }
+ }
+
+ sqlite3_free(azDequote);
+ return rc;
+}
+
+/*
+** This function does the work for both the xDisconnect and xDestroy methods.
+** These tables have no persistent representation of their own, so xDisconnect
+** and xDestroy are identical operations.
+*/
+static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
+ Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
+
+ pTab->pMod->xDestroy(pTab->pTok);
+ sqlite3_free(pTab);
+ return SQLITE_OK;
+}
+
+/*
+** xBestIndex - Analyze a WHERE and ORDER BY clause.
+*/
+static int fts3tokBestIndexMethod(
+ sqlite3_vtab *pVTab,
+ sqlite3_index_info *pInfo
+){
+ int i;
+ UNUSED_PARAMETER(pVTab);
+
+ for(i=0; i<pInfo->nConstraint; i++){
+ if( pInfo->aConstraint[i].usable
+ && pInfo->aConstraint[i].iColumn==0
+ && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
+ ){
+ pInfo->idxNum = 1;
+ pInfo->aConstraintUsage[i].argvIndex = 1;
+ pInfo->aConstraintUsage[i].omit = 1;
+ pInfo->estimatedCost = 1;
+ return SQLITE_OK;
+ }
+ }
+
+ pInfo->idxNum = 0;
+ assert( pInfo->estimatedCost>1000000.0 );
+
+ return SQLITE_OK;
+}
+
+/*
+** xOpen - Open a cursor.
+*/
+static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
+ Fts3tokCursor *pCsr;
+ UNUSED_PARAMETER(pVTab);
+
+ pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
+ if( pCsr==0 ){
+ return SQLITE_NOMEM;
+ }
+ memset(pCsr, 0, sizeof(Fts3tokCursor));
+
+ *ppCsr = (sqlite3_vtab_cursor *)pCsr;
+ return SQLITE_OK;
+}
+
+/*
+** Reset the tokenizer cursor passed as the only argument. As if it had
+** just been returned by fts3tokOpenMethod().
+*/
+static void fts3tokResetCursor(Fts3tokCursor *pCsr){
+ if( pCsr->pCsr ){
+ Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
+ pTab->pMod->xClose(pCsr->pCsr);
+ pCsr->pCsr = 0;
+ }
+ sqlite3_free(pCsr->zInput);
+ pCsr->zInput = 0;
+ pCsr->zToken = 0;
+ pCsr->nToken = 0;
+ pCsr->iStart = 0;
+ pCsr->iEnd = 0;
+ pCsr->iPos = 0;
+ pCsr->iRowid = 0;
+}
+
+/*
+** xClose - Close a cursor.
+*/
+static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
+ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
+
+ fts3tokResetCursor(pCsr);
+ sqlite3_free(pCsr);
+ return SQLITE_OK;
+}
+
+/*
+** xNext - Advance the cursor to the next row, if any.
+*/
+static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
+ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
+ Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
+ int rc; /* Return code */
+
+ pCsr->iRowid++;
+ rc = pTab->pMod->xNext(pCsr->pCsr,
+ &pCsr->zToken, &pCsr->nToken,
+ &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
+ );
+
+ if( rc!=SQLITE_OK ){
+ fts3tokResetCursor(pCsr);
+ if( rc==SQLITE_DONE ) rc = SQLITE_OK;
+ }
+
+ return rc;
+}
+
+/*
+** xFilter - Initialize a cursor to point at the start of its data.
+*/
+static int fts3tokFilterMethod(
+ sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
+ int idxNum, /* Strategy index */
+ const char *idxStr, /* Unused */
+ int nVal, /* Number of elements in apVal */
+ sqlite3_value **apVal /* Arguments for the indexing scheme */
+){
+ int rc = SQLITE_ERROR;
+ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
+ Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
+ UNUSED_PARAMETER(idxStr);
+ UNUSED_PARAMETER(nVal);
+
+ fts3tokResetCursor(pCsr);
+ if( idxNum==1 ){
+ const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
+ int nByte = sqlite3_value_bytes(apVal[0]);
+ pCsr->zInput = sqlite3_malloc64(nByte+1);
+ if( pCsr->zInput==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ if( nByte>0 ) memcpy(pCsr->zInput, zByte, nByte);
+ pCsr->zInput[nByte] = 0;
+ rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
+ if( rc==SQLITE_OK ){
+ pCsr->pCsr->pTokenizer = pTab->pTok;
+ }
+ }
+ }
+
+ if( rc!=SQLITE_OK ) return rc;
+ return fts3tokNextMethod(pCursor);
+}
+
+/*
+** xEof - Return true if the cursor is at EOF, or false otherwise.
+*/
+static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
+ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
+ return (pCsr->zToken==0);
+}
+
+/*
+** xColumn - Return a column value.
+*/
+static int fts3tokColumnMethod(
+ sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
+ sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
+ int iCol /* Index of column to read value from */
+){
+ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
+
+ /* CREATE TABLE x(input, token, start, end, position) */
+ switch( iCol ){
+ case 0:
+ sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
+ break;
+ case 1:
+ sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
+ break;
+ case 2:
+ sqlite3_result_int(pCtx, pCsr->iStart);
+ break;
+ case 3:
+ sqlite3_result_int(pCtx, pCsr->iEnd);
+ break;
+ default:
+ assert( iCol==4 );
+ sqlite3_result_int(pCtx, pCsr->iPos);
+ break;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** xRowid - Return the current rowid for the cursor.
+*/
+static int fts3tokRowidMethod(
+ sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
+ sqlite_int64 *pRowid /* OUT: Rowid value */
+){
+ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
+ *pRowid = (sqlite3_int64)pCsr->iRowid;
+ return SQLITE_OK;
+}
+
+/*
+** Register the fts3tok module with database connection db. Return SQLITE_OK
+** if successful or an error code if sqlite3_create_module() fails.
+*/
+SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
+ static const sqlite3_module fts3tok_module = {
+ 0, /* iVersion */
+ fts3tokConnectMethod, /* xCreate */
+ fts3tokConnectMethod, /* xConnect */
+ fts3tokBestIndexMethod, /* xBestIndex */
+ fts3tokDisconnectMethod, /* xDisconnect */
+ fts3tokDisconnectMethod, /* xDestroy */
+ fts3tokOpenMethod, /* xOpen */
+ fts3tokCloseMethod, /* xClose */
+ fts3tokFilterMethod, /* xFilter */
+ fts3tokNextMethod, /* xNext */
+ fts3tokEofMethod, /* xEof */
+ fts3tokColumnMethod, /* xColumn */
+ fts3tokRowidMethod, /* xRowid */
+ 0, /* xUpdate */
+ 0, /* xBegin */
+ 0, /* xSync */
+ 0, /* xCommit */
+ 0, /* xRollback */
+ 0, /* xFindFunction */
+ 0, /* xRename */
+ 0, /* xSavepoint */
+ 0, /* xRelease */
+ 0, /* xRollbackTo */
+ 0 /* xShadowName */
+ };
+ int rc; /* Return code */
+
+ rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
+ return rc;
+}
+
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
+
+/************** End of fts3_tokenize_vtab.c **********************************/
+/************** Begin file fts3_write.c **************************************/
+/*
+** 2009 Oct 23
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file is part of the SQLite FTS3 extension module. Specifically,
+** this file contains code to insert, update and delete rows from FTS3
+** tables. It also contains code to merge FTS3 b-tree segments. Some
+** of the sub-routines used to merge segments are also used by the query
+** code in fts3.c.
+*/
+
+/* #include "fts3Int.h" */
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
+
+/* #include <string.h> */
+/* #include <assert.h> */
+/* #include <stdlib.h> */
+/* #include <stdio.h> */
+
+#define FTS_MAX_APPENDABLE_HEIGHT 16
+
+/*
+** When full-text index nodes are loaded from disk, the buffer that they
+** are loaded into has the following number of bytes of padding at the end
+** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
+** of 920 bytes is allocated for it.
+**
+** This means that if we have a pointer into a buffer containing node data,
+** it is always safe to read up to two varints from it without risking an
+** overread, even if the node data is corrupted.
+*/
+#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
+
+/*
+** Under certain circumstances, b-tree nodes (doclists) can be loaded into
+** memory incrementally instead of all at once. This can be a big performance
+** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
+** method before retrieving all query results (as may happen, for example,
+** if a query has a LIMIT clause).
+**
+** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
+** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
+** The code is written so that the hard lower-limit for each of these values
+** is 1. Clearly such small values would be inefficient, but can be useful
+** for testing purposes.
+**
+** If this module is built with SQLITE_TEST defined, these constants may
+** be overridden at runtime for testing purposes. File fts3_test.c contains
+** a Tcl interface to read and write the values.
+*/
+#ifdef SQLITE_TEST
+int test_fts3_node_chunksize = (4*1024);
+int test_fts3_node_chunk_threshold = (4*1024)*4;
+# define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
+# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
+#else
+# define FTS3_NODE_CHUNKSIZE (4*1024)
+# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
+#endif
+
+/*
+** The values that may be meaningfully bound to the :1 parameter in
+** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
+*/
+#define FTS_STAT_DOCTOTAL 0
+#define FTS_STAT_INCRMERGEHINT 1
+#define FTS_STAT_AUTOINCRMERGE 2
+
+/*
+** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
+** and incremental merge operation that takes place. This is used for
+** debugging FTS only, it should not usually be turned on in production
+** systems.
+*/
+#ifdef FTS3_LOG_MERGES
+static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
+ sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
+}
+#else
+#define fts3LogMerge(x, y)
+#endif
+
+
+typedef struct PendingList PendingList;
+typedef struct SegmentNode SegmentNode;
+typedef struct SegmentWriter SegmentWriter;
+
+/*
+** An instance of the following data structure is used to build doclists
+** incrementally. See function fts3PendingListAppend() for details.
+*/
+struct PendingList {
+ int nData;
+ char *aData;
+ int nSpace;
+ sqlite3_int64 iLastDocid;
+ sqlite3_int64 iLastCol;
+ sqlite3_int64 iLastPos;
+};
+
+
+/*
+** Each cursor has a (possibly empty) linked list of the following objects.
+*/
+struct Fts3DeferredToken {
+ Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
+ int iCol; /* Column token must occur in */
+ Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
+ PendingList *pList; /* Doclist is assembled here */
+};
+
+/*
+** An instance of this structure is used to iterate through the terms on
+** a contiguous set of segment b-tree leaf nodes. Although the details of
+** this structure are only manipulated by code in this file, opaque handles
+** of type Fts3SegReader* are also used by code in fts3.c to iterate through
+** terms when querying the full-text index. See functions:
+**
+** sqlite3Fts3SegReaderNew()
+** sqlite3Fts3SegReaderFree()
+** sqlite3Fts3SegReaderIterate()
+**
+** Methods used to manipulate Fts3SegReader structures:
+**
+** fts3SegReaderNext()
+** fts3SegReaderFirstDocid()
+** fts3SegReaderNextDocid()
+*/
+struct Fts3SegReader {
+ int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
+ u8 bLookup; /* True for a lookup only */
+ u8 rootOnly; /* True for a root-only reader */
+
+ sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
+ sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
+ sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
+ sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
+
+ char *aNode; /* Pointer to node data (or NULL) */
+ int nNode; /* Size of buffer at aNode (or 0) */
+ int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
+ sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
+
+ Fts3HashElem **ppNextElem;
+
+ /* Variables set by fts3SegReaderNext(). These may be read directly
+ ** by the caller. They are valid from the time SegmentReaderNew() returns
+ ** until SegmentReaderNext() returns something other than SQLITE_OK
+ ** (i.e. SQLITE_DONE).
+ */
+ int nTerm; /* Number of bytes in current term */
+ char *zTerm; /* Pointer to current term */
+ int nTermAlloc; /* Allocated size of zTerm buffer */
+ char *aDoclist; /* Pointer to doclist of current entry */
+ int nDoclist; /* Size of doclist in current entry */
+
+ /* The following variables are used by fts3SegReaderNextDocid() to iterate
+ ** through the current doclist (aDoclist/nDoclist).
+ */
+ char *pOffsetList;
+ int nOffsetList; /* For descending pending seg-readers only */
+ sqlite3_int64 iDocid;
+};
+
+#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
+#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
+
+/*
+** An instance of this structure is used to create a segment b-tree in the
+** database. The internal details of this type are only accessed by the
+** following functions:
+**
+** fts3SegWriterAdd()
+** fts3SegWriterFlush()
+** fts3SegWriterFree()
+*/
+struct SegmentWriter {
+ SegmentNode *pTree; /* Pointer to interior tree structure */
+ sqlite3_int64 iFirst; /* First slot in %_segments written */
+ sqlite3_int64 iFree; /* Next free slot in %_segments */
+ char *zTerm; /* Pointer to previous term buffer */
+ int nTerm; /* Number of bytes in zTerm */
+ int nMalloc; /* Size of malloc'd buffer at zMalloc */
+ char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
+ int nSize; /* Size of allocation at aData */
+ int nData; /* Bytes of data in aData */
+ char *aData; /* Pointer to block from malloc() */
+ i64 nLeafData; /* Number of bytes of leaf data written */
+};
+
+/*
+** Type SegmentNode is used by the following three functions to create
+** the interior part of the segment b+-tree structures (everything except
+** the leaf nodes). These functions and type are only ever used by code
+** within the fts3SegWriterXXX() family of functions described above.
+**
+** fts3NodeAddTerm()
+** fts3NodeWrite()
+** fts3NodeFree()
+**
+** When a b+tree is written to the database (either as a result of a merge
+** or the pending-terms table being flushed), leaves are written into the
+** database file as soon as they are completely populated. The interior of
+** the tree is assembled in memory and written out only once all leaves have
+** been populated and stored. This is Ok, as the b+-tree fanout is usually
+** very large, meaning that the interior of the tree consumes relatively
+** little memory.
+*/
+struct SegmentNode {
+ SegmentNode *pParent; /* Parent node (or NULL for root node) */
+ SegmentNode *pRight; /* Pointer to right-sibling */
+ SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
+ int nEntry; /* Number of terms written to node so far */
+ char *zTerm; /* Pointer to previous term buffer */
+ int nTerm; /* Number of bytes in zTerm */
+ int nMalloc; /* Size of malloc'd buffer at zMalloc */
+ char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
+ int nData; /* Bytes of valid data so far */
+ char *aData; /* Node data */
+};
+
+/*
+** Valid values for the second argument to fts3SqlStmt().
+*/
+#define SQL_DELETE_CONTENT 0
+#define SQL_IS_EMPTY 1
+#define SQL_DELETE_ALL_CONTENT 2
+#define SQL_DELETE_ALL_SEGMENTS 3
+#define SQL_DELETE_ALL_SEGDIR 4
+#define SQL_DELETE_ALL_DOCSIZE 5
+#define SQL_DELETE_ALL_STAT 6
+#define SQL_SELECT_CONTENT_BY_ROWID 7
+#define SQL_NEXT_SEGMENT_INDEX 8
+#define SQL_INSERT_SEGMENTS 9
+#define SQL_NEXT_SEGMENTS_ID 10
+#define SQL_INSERT_SEGDIR 11
+#define SQL_SELECT_LEVEL 12
+#define SQL_SELECT_LEVEL_RANGE 13
+#define SQL_SELECT_LEVEL_COUNT 14
+#define SQL_SELECT_SEGDIR_MAX_LEVEL 15
+#define SQL_DELETE_SEGDIR_LEVEL 16
+#define SQL_DELETE_SEGMENTS_RANGE 17
+#define SQL_CONTENT_INSERT 18
+#define SQL_DELETE_DOCSIZE 19
+#define SQL_REPLACE_DOCSIZE 20
+#define SQL_SELECT_DOCSIZE 21
+#define SQL_SELECT_STAT 22
+#define SQL_REPLACE_STAT 23
+
+#define SQL_SELECT_ALL_PREFIX_LEVEL 24
+#define SQL_DELETE_ALL_TERMS_SEGDIR 25
+#define SQL_DELETE_SEGDIR_RANGE 26
+#define SQL_SELECT_ALL_LANGID 27
+#define SQL_FIND_MERGE_LEVEL 28
+#define SQL_MAX_LEAF_NODE_ESTIMATE 29
+#define SQL_DELETE_SEGDIR_ENTRY 30
+#define SQL_SHIFT_SEGDIR_ENTRY 31
+#define SQL_SELECT_SEGDIR 32
+#define SQL_CHOMP_SEGDIR 33
+#define SQL_SEGMENT_IS_APPENDABLE 34
+#define SQL_SELECT_INDEXES 35
+#define SQL_SELECT_MXLEVEL 36
+
+#define SQL_SELECT_LEVEL_RANGE2 37
+#define SQL_UPDATE_LEVEL_IDX 38
+#define SQL_UPDATE_LEVEL 39
+
+/*
+** This function is used to obtain an SQLite prepared statement handle
+** for the statement identified by the second argument. If successful,
+** *pp is set to the requested statement handle and SQLITE_OK returned.
+** Otherwise, an SQLite error code is returned and *pp is set to 0.
+**
+** If argument apVal is not NULL, then it must point to an array with
+** at least as many entries as the requested statement has bound
+** parameters. The values are bound to the statements parameters before
+** returning.
+*/
+static int fts3SqlStmt(
+ Fts3Table *p, /* Virtual table handle */
+ int eStmt, /* One of the SQL_XXX constants above */
+ sqlite3_stmt **pp, /* OUT: Statement handle */
+ sqlite3_value **apVal /* Values to bind to statement */
+){
+ const char *azSql[] = {
+/* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
+/* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
+/* 2 */ "DELETE FROM %Q.'%q_content'",
+/* 3 */ "DELETE FROM %Q.'%q_segments'",
+/* 4 */ "DELETE FROM %Q.'%q_segdir'",
+/* 5 */ "DELETE FROM %Q.'%q_docsize'",
+/* 6 */ "DELETE FROM %Q.'%q_stat'",
+/* 7 */ "SELECT %s WHERE rowid=?",
+/* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
+/* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
+/* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
+/* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
+
+ /* Return segments in order from oldest to newest.*/
+/* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
+ "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
+/* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
+ "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
+ "ORDER BY level DESC, idx ASC",
+
+/* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
+/* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
+
+/* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
+/* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
+/* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
+/* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
+/* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
+/* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
+/* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
+/* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
+/* 24 */ "",
+/* 25 */ "",
+
+/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
+/* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
+
+/* This statement is used to determine which level to read the input from
+** when performing an incremental merge. It returns the absolute level number
+** of the oldest level in the db that contains at least ? segments. Or,
+** if no level in the FTS index contains more than ? segments, the statement
+** returns zero rows. */
+/* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
+ " GROUP BY level HAVING cnt>=?"
+ " ORDER BY (level %% 1024) ASC, 2 DESC LIMIT 1",
+
+/* Estimate the upper limit on the number of leaf nodes in a new segment
+** created by merging the oldest :2 segments from absolute level :1. See
+** function sqlite3Fts3Incrmerge() for details. */
+/* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
+ " FROM (SELECT * FROM %Q.'%q_segdir' "
+ " WHERE level = ? ORDER BY idx ASC LIMIT ?"
+ " )",
+
+/* SQL_DELETE_SEGDIR_ENTRY
+** Delete the %_segdir entry on absolute level :1 with index :2. */
+/* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
+
+/* SQL_SHIFT_SEGDIR_ENTRY
+** Modify the idx value for the segment with idx=:3 on absolute level :2
+** to :1. */
+/* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
+
+/* SQL_SELECT_SEGDIR
+** Read a single entry from the %_segdir table. The entry from absolute
+** level :1 with index value :2. */
+/* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
+ "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
+
+/* SQL_CHOMP_SEGDIR
+** Update the start_block (:1) and root (:2) fields of the %_segdir
+** entry located on absolute level :3 with index :4. */
+/* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
+ "WHERE level = ? AND idx = ?",
+
+/* SQL_SEGMENT_IS_APPENDABLE
+** Return a single row if the segment with end_block=? is appendable. Or
+** no rows otherwise. */
+/* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
+
+/* SQL_SELECT_INDEXES
+** Return the list of valid segment indexes for absolute level ? */
+/* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
+
+/* SQL_SELECT_MXLEVEL
+** Return the largest relative level in the FTS index or indexes. */
+/* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
+
+ /* Return segments in order from oldest to newest.*/
+/* 37 */ "SELECT level, idx, end_block "
+ "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
+ "ORDER BY level DESC, idx ASC",
+
+ /* Update statements used while promoting segments */
+/* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
+ "WHERE level=? AND idx=?",
+/* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
+
+ };
+ int rc = SQLITE_OK;
+ sqlite3_stmt *pStmt;
+
+ assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
+ assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
+
+ pStmt = p->aStmt[eStmt];
+ if( !pStmt ){
+ int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
+ char *zSql;
+ if( eStmt==SQL_CONTENT_INSERT ){
+ zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
+ }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
+ f &= ~SQLITE_PREPARE_NO_VTAB;
+ zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
+ }else{
+ zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
+ }
+ if( !zSql ){
+ rc = SQLITE_NOMEM;
+ }else{
+ rc = sqlite3_prepare_v3(p->db, zSql, -1, f, &pStmt, NULL);
+ sqlite3_free(zSql);
+ assert( rc==SQLITE_OK || pStmt==0 );
+ p->aStmt[eStmt] = pStmt;
+ }
+ }
+ if( apVal ){
+ int i;
+ int nParam = sqlite3_bind_parameter_count(pStmt);
+ for(i=0; rc==SQLITE_OK && i<nParam; i++){
+ rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
+ }
+ }
+ *pp = pStmt;
+ return rc;
+}
+
+
+static int fts3SelectDocsize(
+ Fts3Table *pTab, /* FTS3 table handle */
+ sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
+ sqlite3_stmt **ppStmt /* OUT: Statement handle */
+){
+ sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
+ int rc; /* Return code */
+
+ rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pStmt, 1, iDocid);
+ rc = sqlite3_step(pStmt);
+ if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
+ rc = sqlite3_reset(pStmt);
+ if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
+ pStmt = 0;
+ }else{
+ rc = SQLITE_OK;
+ }
+ }
+
+ *ppStmt = pStmt;
+ return rc;
+}
+
+SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
+ Fts3Table *pTab, /* Fts3 table handle */
+ sqlite3_stmt **ppStmt /* OUT: Statement handle */
+){
+ sqlite3_stmt *pStmt = 0;
+ int rc;
+ rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
+ if( sqlite3_step(pStmt)!=SQLITE_ROW
+ || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
+ ){
+ rc = sqlite3_reset(pStmt);
+ if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
+ pStmt = 0;
+ }
+ }
+ *ppStmt = pStmt;
+ return rc;
+}
+
+SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
+ Fts3Table *pTab, /* Fts3 table handle */
+ sqlite3_int64 iDocid, /* Docid to read size data for */
+ sqlite3_stmt **ppStmt /* OUT: Statement handle */
+){
+ return fts3SelectDocsize(pTab, iDocid, ppStmt);
+}
+
+/*
+** Similar to fts3SqlStmt(). Except, after binding the parameters in
+** array apVal[] to the SQL statement identified by eStmt, the statement
+** is executed.
+**
+** Returns SQLITE_OK if the statement is successfully executed, or an
+** SQLite error code otherwise.
+*/
+static void fts3SqlExec(
+ int *pRC, /* Result code */
+ Fts3Table *p, /* The FTS3 table */
+ int eStmt, /* Index of statement to evaluate */
+ sqlite3_value **apVal /* Parameters to bind */
+){
+ sqlite3_stmt *pStmt;
+ int rc;
+ if( *pRC ) return;
+ rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
+ if( rc==SQLITE_OK ){
+ sqlite3_step(pStmt);
+ rc = sqlite3_reset(pStmt);
+ }
+ *pRC = rc;
+}
+
+
+/*
+** This function ensures that the caller has obtained an exclusive
+** shared-cache table-lock on the %_segdir table. This is required before
+** writing data to the fts3 table. If this lock is not acquired first, then
+** the caller may end up attempting to take this lock as part of committing
+** a transaction, causing SQLite to return SQLITE_LOCKED or
+** LOCKED_SHAREDCACHEto a COMMIT command.
+**
+** It is best to avoid this because if FTS3 returns any error when
+** committing a transaction, the whole transaction will be rolled back.
+** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
+** It can still happen if the user locks the underlying tables directly
+** instead of accessing them via FTS.
+*/
+static int fts3Writelock(Fts3Table *p){
+ int rc = SQLITE_OK;
+
+ if( p->nPendingData==0 ){
+ sqlite3_stmt *pStmt;
+ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_null(pStmt, 1);
+ sqlite3_step(pStmt);
+ rc = sqlite3_reset(pStmt);
+ }
+ }
+
+ return rc;
+}
+
+/*
+** FTS maintains a separate indexes for each language-id (a 32-bit integer).
+** Within each language id, a separate index is maintained to store the
+** document terms, and each configured prefix size (configured the FTS
+** "prefix=" option). And each index consists of multiple levels ("relative
+** levels").
+**
+** All three of these values (the language id, the specific index and the
+** level within the index) are encoded in 64-bit integer values stored
+** in the %_segdir table on disk. This function is used to convert three
+** separate component values into the single 64-bit integer value that
+** can be used to query the %_segdir table.
+**
+** Specifically, each language-id/index combination is allocated 1024
+** 64-bit integer level values ("absolute levels"). The main terms index
+** for language-id 0 is allocate values 0-1023. The first prefix index
+** (if any) for language-id 0 is allocated values 1024-2047. And so on.
+** Language 1 indexes are allocated immediately following language 0.
+**
+** So, for a system with nPrefix prefix indexes configured, the block of
+** absolute levels that corresponds to language-id iLangid and index
+** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
+*/
+static sqlite3_int64 getAbsoluteLevel(
+ Fts3Table *p, /* FTS3 table handle */
+ int iLangid, /* Language id */
+ int iIndex, /* Index in p->aIndex[] */
+ int iLevel /* Level of segments */
+){
+ sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
+ assert_fts3_nc( iLangid>=0 );
+ assert( p->nIndex>0 );
+ assert( iIndex>=0 && iIndex<p->nIndex );
+
+ iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
+ return iBase + iLevel;
+}
+
+/*
+** Set *ppStmt to a statement handle that may be used to iterate through
+** all rows in the %_segdir table, from oldest to newest. If successful,
+** return SQLITE_OK. If an error occurs while preparing the statement,
+** return an SQLite error code.
+**
+** There is only ever one instance of this SQL statement compiled for
+** each FTS3 table.
+**
+** The statement returns the following columns from the %_segdir table:
+**
+** 0: idx
+** 1: start_block
+** 2: leaves_end_block
+** 3: end_block
+** 4: root
+*/
+SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
+ Fts3Table *p, /* FTS3 table */
+ int iLangid, /* Language being queried */
+ int iIndex, /* Index for p->aIndex[] */
+ int iLevel, /* Level to select (relative level) */
+ sqlite3_stmt **ppStmt /* OUT: Compiled statement */
+){
+ int rc;
+ sqlite3_stmt *pStmt = 0;
+
+ assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
+ assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
+ assert( iIndex>=0 && iIndex<p->nIndex );
+
+ if( iLevel<0 ){
+ /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
+ rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
+ sqlite3_bind_int64(pStmt, 2,
+ getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
+ );
+ }
+ }else{
+ /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
+ rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
+ }
+ }
+ *ppStmt = pStmt;
+ return rc;
+}
+
+
+/*
+** Append a single varint to a PendingList buffer. SQLITE_OK is returned
+** if successful, or an SQLite error code otherwise.
+**
+** This function also serves to allocate the PendingList structure itself.
+** For example, to create a new PendingList structure containing two
+** varints:
+**
+** PendingList *p = 0;
+** fts3PendingListAppendVarint(&p, 1);
+** fts3PendingListAppendVarint(&p, 2);
+*/
+static int fts3PendingListAppendVarint(
+ PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
+ sqlite3_int64 i /* Value to append to data */
+){
+ PendingList *p = *pp;
+
+ /* Allocate or grow the PendingList as required. */
+ if( !p ){
+ p = sqlite3_malloc(sizeof(*p) + 100);
+ if( !p ){
+ return SQLITE_NOMEM;
+ }
+ p->nSpace = 100;
+ p->aData = (char *)&p[1];
+ p->nData = 0;
+ }
+ else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
+ int nNew = p->nSpace * 2;
+ p = sqlite3_realloc(p, sizeof(*p) + nNew);
+ if( !p ){
+ sqlite3_free(*pp);
+ *pp = 0;
+ return SQLITE_NOMEM;
+ }
+ p->nSpace = nNew;
+ p->aData = (char *)&p[1];
+ }
+
+ /* Append the new serialized varint to the end of the list. */
+ p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
+ p->aData[p->nData] = '\0';
+ *pp = p;
+ return SQLITE_OK;
+}
+
+/*
+** Add a docid/column/position entry to a PendingList structure. Non-zero
+** is returned if the structure is sqlite3_realloced as part of adding
+** the entry. Otherwise, zero.
+**
+** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
+** Zero is always returned in this case. Otherwise, if no OOM error occurs,
+** it is set to SQLITE_OK.
+*/
+static int fts3PendingListAppend(
+ PendingList **pp, /* IN/OUT: PendingList structure */
+ sqlite3_int64 iDocid, /* Docid for entry to add */
+ sqlite3_int64 iCol, /* Column for entry to add */
+ sqlite3_int64 iPos, /* Position of term for entry to add */
+ int *pRc /* OUT: Return code */
+){
+ PendingList *p = *pp;
+ int rc = SQLITE_OK;
+
+ assert( !p || p->iLastDocid<=iDocid );
+
+ if( !p || p->iLastDocid!=iDocid ){
+ u64 iDelta = (u64)iDocid - (u64)(p ? p->iLastDocid : 0);
+ if( p ){
+ assert( p->nData<p->nSpace );
+ assert( p->aData[p->nData]==0 );
+ p->nData++;
+ }
+ if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
+ goto pendinglistappend_out;
+ }
+ p->iLastCol = -1;
+ p->iLastPos = 0;
+ p->iLastDocid = iDocid;
+ }
+ if( iCol>0 && p->iLastCol!=iCol ){
+ if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
+ || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
+ ){
+ goto pendinglistappend_out;
+ }
+ p->iLastCol = iCol;
+ p->iLastPos = 0;
+ }
+ if( iCol>=0 ){
+ assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
+ rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
+ if( rc==SQLITE_OK ){
+ p->iLastPos = iPos;
+ }
+ }
+
+ pendinglistappend_out:
+ *pRc = rc;
+ if( p!=*pp ){
+ *pp = p;
+ return 1;
+ }
+ return 0;
+}
+
+/*
+** Free a PendingList object allocated by fts3PendingListAppend().
+*/
+static void fts3PendingListDelete(PendingList *pList){
+ sqlite3_free(pList);
+}
+
+/*
+** Add an entry to one of the pending-terms hash tables.
+*/
+static int fts3PendingTermsAddOne(
+ Fts3Table *p,
+ int iCol,
+ int iPos,
+ Fts3Hash *pHash, /* Pending terms hash table to add entry to */
+ const char *zToken,
+ int nToken
+){
+ PendingList *pList;
+ int rc = SQLITE_OK;
+
+ pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
+ if( pList ){
+ p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
+ }
+ if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
+ if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
+ /* Malloc failed while inserting the new entry. This can only
+ ** happen if there was no previous entry for this token.
+ */
+ assert( 0==fts3HashFind(pHash, zToken, nToken) );
+ sqlite3_free(pList);
+ rc = SQLITE_NOMEM;
+ }
+ }
+ if( rc==SQLITE_OK ){
+ p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
+ }
+ return rc;
+}
+
+/*
+** Tokenize the nul-terminated string zText and add all tokens to the
+** pending-terms hash-table. The docid used is that currently stored in
+** p->iPrevDocid, and the column is specified by argument iCol.
+**
+** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
+*/
+static int fts3PendingTermsAdd(
+ Fts3Table *p, /* Table into which text will be inserted */
+ int iLangid, /* Language id to use */
+ const char *zText, /* Text of document to be inserted */
+ int iCol, /* Column into which text is being inserted */
+ u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
+){
+ int rc;
+ int iStart = 0;
+ int iEnd = 0;
+ int iPos = 0;
+ int nWord = 0;
+
+ char const *zToken;
+ int nToken = 0;
+
+ sqlite3_tokenizer *pTokenizer = p->pTokenizer;
+ sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
+ sqlite3_tokenizer_cursor *pCsr;
+ int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
+ const char**,int*,int*,int*,int*);
+
+ assert( pTokenizer && pModule );
+
+ /* If the user has inserted a NULL value, this function may be called with
+ ** zText==0. In this case, add zero token entries to the hash table and
+ ** return early. */
+ if( zText==0 ){
+ *pnWord = 0;
+ return SQLITE_OK;
+ }
+
+ rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+
+ xNext = pModule->xNext;
+ while( SQLITE_OK==rc
+ && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
+ ){
+ int i;
+ if( iPos>=nWord ) nWord = iPos+1;
+
+ /* Positions cannot be negative; we use -1 as a terminator internally.
+ ** Tokens must have a non-zero length.
+ */
+ if( iPos<0 || !zToken || nToken<=0 ){
+ rc = SQLITE_ERROR;
+ break;
+ }
+
+ /* Add the term to the terms index */
+ rc = fts3PendingTermsAddOne(
+ p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
+ );
+
+ /* Add the term to each of the prefix indexes that it is not too
+ ** short for. */
+ for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
+ struct Fts3Index *pIndex = &p->aIndex[i];
+ if( nToken<pIndex->nPrefix ) continue;
+ rc = fts3PendingTermsAddOne(
+ p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
+ );
+ }
+ }
+
+ pModule->xClose(pCsr);
+ *pnWord += nWord;
+ return (rc==SQLITE_DONE ? SQLITE_OK : rc);
+}
+
+/*
+** Calling this function indicates that subsequent calls to
+** fts3PendingTermsAdd() are to add term/position-list pairs for the
+** contents of the document with docid iDocid.
+*/
+static int fts3PendingTermsDocid(
+ Fts3Table *p, /* Full-text table handle */
+ int bDelete, /* True if this op is a delete */
+ int iLangid, /* Language id of row being written */
+ sqlite_int64 iDocid /* Docid of row being written */
+){
+ assert( iLangid>=0 );
+ assert( bDelete==1 || bDelete==0 );
+
+ /* TODO(shess) Explore whether partially flushing the buffer on
+ ** forced-flush would provide better performance. I suspect that if
+ ** we ordered the doclists by size and flushed the largest until the
+ ** buffer was half empty, that would let the less frequent terms
+ ** generate longer doclists.
+ */
+ if( iDocid<p->iPrevDocid
+ || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
+ || p->iPrevLangid!=iLangid
+ || p->nPendingData>p->nMaxPendingData
+ ){
+ int rc = sqlite3Fts3PendingTermsFlush(p);
+ if( rc!=SQLITE_OK ) return rc;
+ }
+ p->iPrevDocid = iDocid;
+ p->iPrevLangid = iLangid;
+ p->bPrevDelete = bDelete;
+ return SQLITE_OK;
+}
+
+/*
+** Discard the contents of the pending-terms hash tables.
+*/
+SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
+ int i;
+ for(i=0; i<p->nIndex; i++){
+ Fts3HashElem *pElem;
+ Fts3Hash *pHash = &p->aIndex[i].hPending;
+ for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
+ PendingList *pList = (PendingList *)fts3HashData(pElem);
+ fts3PendingListDelete(pList);
+ }
+ fts3HashClear(pHash);
+ }
+ p->nPendingData = 0;
+}
+
+/*
+** This function is called by the xUpdate() method as part of an INSERT
+** operation. It adds entries for each term in the new record to the
+** pendingTerms hash table.
+**
+** Argument apVal is the same as the similarly named argument passed to
+** fts3InsertData(). Parameter iDocid is the docid of the new row.
+*/
+static int fts3InsertTerms(
+ Fts3Table *p,
+ int iLangid,
+ sqlite3_value **apVal,
+ u32 *aSz
+){
+ int i; /* Iterator variable */
+ for(i=2; i<p->nColumn+2; i++){
+ int iCol = i-2;
+ if( p->abNotindexed[iCol]==0 ){
+ const char *zText = (const char *)sqlite3_value_text(apVal[i]);
+ int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
+ }
+ }
+ return SQLITE_OK;
+}
+
+/*
+** This function is called by the xUpdate() method for an INSERT operation.
+** The apVal parameter is passed a copy of the apVal argument passed by
+** SQLite to the xUpdate() method. i.e:
+**
+** apVal[0] Not used for INSERT.
+** apVal[1] rowid
+** apVal[2] Left-most user-defined column
+** ...
+** apVal[p->nColumn+1] Right-most user-defined column
+** apVal[p->nColumn+2] Hidden column with same name as table
+** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
+** apVal[p->nColumn+4] Hidden languageid column
+*/
+static int fts3InsertData(
+ Fts3Table *p, /* Full-text table */
+ sqlite3_value **apVal, /* Array of values to insert */
+ sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
+){
+ int rc; /* Return code */
+ sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
+
+ if( p->zContentTbl ){
+ sqlite3_value *pRowid = apVal[p->nColumn+3];
+ if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
+ pRowid = apVal[1];
+ }
+ if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
+ return SQLITE_CONSTRAINT;
+ }
+ *piDocid = sqlite3_value_int64(pRowid);
+ return SQLITE_OK;
+ }
+
+ /* Locate the statement handle used to insert data into the %_content
+ ** table. The SQL for this statement is:
+ **
+ ** INSERT INTO %_content VALUES(?, ?, ?, ...)
+ **
+ ** The statement features N '?' variables, where N is the number of user
+ ** defined columns in the FTS3 table, plus one for the docid field.
+ */
+ rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
+ if( rc==SQLITE_OK && p->zLanguageid ){
+ rc = sqlite3_bind_int(
+ pContentInsert, p->nColumn+2,
+ sqlite3_value_int(apVal[p->nColumn+4])
+ );
+ }
+ if( rc!=SQLITE_OK ) return rc;
+
+ /* There is a quirk here. The users INSERT statement may have specified
+ ** a value for the "rowid" field, for the "docid" field, or for both.
+ ** Which is a problem, since "rowid" and "docid" are aliases for the
+ ** same value. For example:
+ **
+ ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
+ **
+ ** In FTS3, this is an error. It is an error to specify non-NULL values
+ ** for both docid and some other rowid alias.
+ */
+ if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
+ if( SQLITE_NULL==sqlite3_value_type(apVal[0])
+ && SQLITE_NULL!=sqlite3_value_type(apVal[1])
+ ){
+ /* A rowid/docid conflict. */
+ return SQLITE_ERROR;
+ }
+ rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
+ if( rc!=SQLITE_OK ) return rc;
+ }
+
+ /* Execute the statement to insert the record. Set *piDocid to the
+ ** new docid value.
+ */
+ sqlite3_step(pContentInsert);
+ rc = sqlite3_reset(pContentInsert);
+
+ *piDocid = sqlite3_last_insert_rowid(p->db);
+ return rc;
+}
+
+
+
+/*
+** Remove all data from the FTS3 table. Clear the hash table containing
+** pending terms.
+*/
+static int fts3DeleteAll(Fts3Table *p, int bContent){
+ int rc = SQLITE_OK; /* Return code */
+
+ /* Discard the contents of the pending-terms hash table. */
+ sqlite3Fts3PendingTermsClear(p);
+
+ /* Delete everything from the shadow tables. Except, leave %_content as
+ ** is if bContent is false. */
+ assert( p->zContentTbl==0 || bContent==0 );
+ if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
+ fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
+ fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
+ if( p->bHasDocsize ){
+ fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
+ }
+ if( p->bHasStat ){
+ fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
+ }
+ return rc;
+}
+
+/*
+**
+*/
+static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
+ int iLangid = 0;
+ if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
+ return iLangid;
+}
+
+/*
+** The first element in the apVal[] array is assumed to contain the docid
+** (an integer) of a row about to be deleted. Remove all terms from the
+** full-text index.
+*/
+static void fts3DeleteTerms(
+ int *pRC, /* Result code */
+ Fts3Table *p, /* The FTS table to delete from */
+ sqlite3_value *pRowid, /* The docid to be deleted */
+ u32 *aSz, /* Sizes of deleted document written here */
+ int *pbFound /* OUT: Set to true if row really does exist */
+){
+ int rc;
+ sqlite3_stmt *pSelect;
+
+ assert( *pbFound==0 );
+ if( *pRC ) return;
+ rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
+ if( rc==SQLITE_OK ){
+ if( SQLITE_ROW==sqlite3_step(pSelect) ){
+ int i;
+ int iLangid = langidFromSelect(p, pSelect);
+ i64 iDocid = sqlite3_column_int64(pSelect, 0);
+ rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
+ for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
+ int iCol = i-1;
+ if( p->abNotindexed[iCol]==0 ){
+ const char *zText = (const char *)sqlite3_column_text(pSelect, i);
+ rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
+ aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
+ }
+ }
+ if( rc!=SQLITE_OK ){
+ sqlite3_reset(pSelect);
+ *pRC = rc;
+ return;
+ }
+ *pbFound = 1;
+ }
+ rc = sqlite3_reset(pSelect);
+ }else{
+ sqlite3_reset(pSelect);
+ }
+ *pRC = rc;
+}
+
+/*
+** Forward declaration to account for the circular dependency between
+** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
+*/
+static int fts3SegmentMerge(Fts3Table *, int, int, int);
+
+/*
+** This function allocates a new level iLevel index in the segdir table.
+** Usually, indexes are allocated within a level sequentially starting
+** with 0, so the allocated index is one greater than the value returned
+** by:
+**
+** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
+**
+** However, if there are already FTS3_MERGE_COUNT indexes at the requested
+** level, they are merged into a single level (iLevel+1) segment and the
+** allocated index is 0.
+**
+** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
+** returned. Otherwise, an SQLite error code is returned.
+*/
+static int fts3AllocateSegdirIdx(
+ Fts3Table *p,
+ int iLangid, /* Language id */
+ int iIndex, /* Index for p->aIndex */
+ int iLevel,
+ int *piIdx
+){
+ int rc; /* Return Code */
+ sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
+ int iNext = 0; /* Result of query pNextIdx */
+
+ assert( iLangid>=0 );
+ assert( p->nIndex>=1 );
+
+ /* Set variable iNext to the next available segdir index at level iLevel. */
+ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(
+ pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
+ );
+ if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
+ iNext = sqlite3_column_int(pNextIdx, 0);
+ }
+ rc = sqlite3_reset(pNextIdx);
+ }
+
+ if( rc==SQLITE_OK ){
+ /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
+ ** full, merge all segments in level iLevel into a single iLevel+1
+ ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
+ ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
+ */
+ if( iNext>=MergeCount(p) ){
+ fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
+ rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
+ *piIdx = 0;
+ }else{
+ *piIdx = iNext;
+ }
+ }
+
+ return rc;
+}
+
+/*
+** The %_segments table is declared as follows:
+**
+** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
+**
+** This function reads data from a single row of the %_segments table. The
+** specific row is identified by the iBlockid parameter. If paBlob is not
+** NULL, then a buffer is allocated using sqlite3_malloc() and populated
+** with the contents of the blob stored in the "block" column of the
+** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
+** to the size of the blob in bytes before returning.
+**
+** If an error occurs, or the table does not contain the specified row,
+** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
+** paBlob is non-NULL, then it is the responsibility of the caller to
+** eventually free the returned buffer.
+**
+** This function may leave an open sqlite3_blob* handle in the
+** Fts3Table.pSegments variable. This handle is reused by subsequent calls
+** to this function. The handle may be closed by calling the
+** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
+** performance improvement, but the blob handle should always be closed
+** before control is returned to the user (to prevent a lock being held
+** on the database file for longer than necessary). Thus, any virtual table
+** method (xFilter etc.) that may directly or indirectly call this function
+** must call sqlite3Fts3SegmentsClose() before returning.
+*/
+SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
+ Fts3Table *p, /* FTS3 table handle */
+ sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
+ char **paBlob, /* OUT: Blob data in malloc'd buffer */
+ int *pnBlob, /* OUT: Size of blob data */
+ int *pnLoad /* OUT: Bytes actually loaded */
+){
+ int rc; /* Return code */
+
+ /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
+ assert( pnBlob );
+
+ if( p->pSegments ){
+ rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
+ }else{
+ if( 0==p->zSegmentsTbl ){
+ p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
+ if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
+ }
+ rc = sqlite3_blob_open(
+ p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
+ );
+ }
+
+ if( rc==SQLITE_OK ){
+ int nByte = sqlite3_blob_bytes(p->pSegments);
+ *pnBlob = nByte;
+ if( paBlob ){
+ char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
+ if( !aByte ){
+ rc = SQLITE_NOMEM;
+ }else{
+ if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
+ nByte = FTS3_NODE_CHUNKSIZE;
+ *pnLoad = nByte;
+ }
+ rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
+ memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
+ if( rc!=SQLITE_OK ){
+ sqlite3_free(aByte);
+ aByte = 0;
+ }
+ }
+ *paBlob = aByte;
+ }
+ }else if( rc==SQLITE_ERROR ){
+ rc = FTS_CORRUPT_VTAB;
+ }
+
+ return rc;
+}
+
+/*
+** Close the blob handle at p->pSegments, if it is open. See comments above
+** the sqlite3Fts3ReadBlock() function for details.
+*/
+SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
+ sqlite3_blob_close(p->pSegments);
+ p->pSegments = 0;
+}
+
+static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
+ int nRead; /* Number of bytes to read */
+ int rc; /* Return code */
+
+ nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
+ rc = sqlite3_blob_read(
+ pReader->pBlob,
+ &pReader->aNode[pReader->nPopulate],
+ nRead,
+ pReader->nPopulate
+ );
+
+ if( rc==SQLITE_OK ){
+ pReader->nPopulate += nRead;
+ memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
+ if( pReader->nPopulate==pReader->nNode ){
+ sqlite3_blob_close(pReader->pBlob);
+ pReader->pBlob = 0;
+ pReader->nPopulate = 0;
+ }
+ }
+ return rc;
+}
+
+static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
+ int rc = SQLITE_OK;
+ assert( !pReader->pBlob
+ || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
+ );
+ while( pReader->pBlob && rc==SQLITE_OK
+ && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
+ ){
+ rc = fts3SegReaderIncrRead(pReader);
+ }
+ return rc;
+}
+
+/*
+** Set an Fts3SegReader cursor to point at EOF.
+*/
+static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
+ if( !fts3SegReaderIsRootOnly(pSeg) ){
+ sqlite3_free(pSeg->aNode);
+ sqlite3_blob_close(pSeg->pBlob);
+ pSeg->pBlob = 0;
+ }
+ pSeg->aNode = 0;
+}
+
+/*
+** Move the iterator passed as the first argument to the next term in the
+** segment. If successful, SQLITE_OK is returned. If there is no next term,
+** SQLITE_DONE. Otherwise, an SQLite error code.
+*/
+static int fts3SegReaderNext(
+ Fts3Table *p,
+ Fts3SegReader *pReader,
+ int bIncr
+){
+ int rc; /* Return code of various sub-routines */
+ char *pNext; /* Cursor variable */
+ int nPrefix; /* Number of bytes in term prefix */
+ int nSuffix; /* Number of bytes in term suffix */
+
+ if( !pReader->aDoclist ){
+ pNext = pReader->aNode;
+ }else{
+ pNext = &pReader->aDoclist[pReader->nDoclist];
+ }
+
+ if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
+
+ if( fts3SegReaderIsPending(pReader) ){
+ Fts3HashElem *pElem = *(pReader->ppNextElem);
+ sqlite3_free(pReader->aNode);
+ pReader->aNode = 0;
+ if( pElem ){
+ char *aCopy;
+ PendingList *pList = (PendingList *)fts3HashData(pElem);
+ int nCopy = pList->nData+1;
+ pReader->zTerm = (char *)fts3HashKey(pElem);
+ pReader->nTerm = fts3HashKeysize(pElem);
+ aCopy = (char*)sqlite3_malloc(nCopy);
+ if( !aCopy ) return SQLITE_NOMEM;
+ memcpy(aCopy, pList->aData, nCopy);
+ pReader->nNode = pReader->nDoclist = nCopy;
+ pReader->aNode = pReader->aDoclist = aCopy;
+ pReader->ppNextElem++;
+ assert( pReader->aNode );
+ }
+ return SQLITE_OK;
+ }
+
+ fts3SegReaderSetEof(pReader);
+
+ /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
+ ** blocks have already been traversed. */
+#ifdef CORRUPT_DB
+ assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock || CORRUPT_DB );
+#endif
+ if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
+ return SQLITE_OK;
+ }
+
+ rc = sqlite3Fts3ReadBlock(
+ p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
+ (bIncr ? &pReader->nPopulate : 0)
+ );
+ if( rc!=SQLITE_OK ) return rc;
+ assert( pReader->pBlob==0 );
+ if( bIncr && pReader->nPopulate<pReader->nNode ){
+ pReader->pBlob = p->pSegments;
+ p->pSegments = 0;
+ }
+ pNext = pReader->aNode;
+ }
+
+ assert( !fts3SegReaderIsPending(pReader) );
+
+ rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
+ if( rc!=SQLITE_OK ) return rc;
+
+ /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
+ ** safe (no risk of overread) even if the node data is corrupted. */
+ pNext += fts3GetVarint32(pNext, &nPrefix);
+ pNext += fts3GetVarint32(pNext, &nSuffix);
+ if( nSuffix<=0
+ || (&pReader->aNode[pReader->nNode] - pNext)<nSuffix
+ || nPrefix>pReader->nTerm
+ ){
+ return FTS_CORRUPT_VTAB;
+ }
+
+ /* Both nPrefix and nSuffix were read by fts3GetVarint32() and so are
+ ** between 0 and 0x7FFFFFFF. But the sum of the two may cause integer
+ ** overflow - hence the (i64) casts. */
+ if( (i64)nPrefix+nSuffix>(i64)pReader->nTermAlloc ){
+ i64 nNew = ((i64)nPrefix+nSuffix)*2;
+ char *zNew = sqlite3_realloc64(pReader->zTerm, nNew);
+ if( !zNew ){
+ return SQLITE_NOMEM;
+ }
+ pReader->zTerm = zNew;
+ pReader->nTermAlloc = nNew;
+ }
+
+ rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
+ if( rc!=SQLITE_OK ) return rc;
+
+ memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
+ pReader->nTerm = nPrefix+nSuffix;
+ pNext += nSuffix;
+ pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
+ pReader->aDoclist = pNext;
+ pReader->pOffsetList = 0;
+
+ /* Check that the doclist does not appear to extend past the end of the
+ ** b-tree node. And that the final byte of the doclist is 0x00. If either
+ ** of these statements is untrue, then the data structure is corrupt.
+ */
+ if( pReader->nDoclist > pReader->nNode-(pReader->aDoclist-pReader->aNode)
+ || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
+ || pReader->nDoclist==0
+ ){
+ return FTS_CORRUPT_VTAB;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Set the SegReader to point to the first docid in the doclist associated
+** with the current term.
+*/
+static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
+ int rc = SQLITE_OK;
+ assert( pReader->aDoclist );
+ assert( !pReader->pOffsetList );
+ if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
+ u8 bEof = 0;
+ pReader->iDocid = 0;
+ pReader->nOffsetList = 0;
+ sqlite3Fts3DoclistPrev(0,
+ pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
+ &pReader->iDocid, &pReader->nOffsetList, &bEof
+ );
+ }else{
+ rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
+ if( rc==SQLITE_OK ){
+ int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
+ pReader->pOffsetList = &pReader->aDoclist[n];
+ }
+ }
+ return rc;
+}
+
+/*
+** Advance the SegReader to point to the next docid in the doclist
+** associated with the current term.
+**
+** If arguments ppOffsetList and pnOffsetList are not NULL, then
+** *ppOffsetList is set to point to the first column-offset list
+** in the doclist entry (i.e. immediately past the docid varint).
+** *pnOffsetList is set to the length of the set of column-offset
+** lists, not including the nul-terminator byte. For example:
+*/
+static int fts3SegReaderNextDocid(
+ Fts3Table *pTab,
+ Fts3SegReader *pReader, /* Reader to advance to next docid */
+ char **ppOffsetList, /* OUT: Pointer to current position-list */
+ int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
+){
+ int rc = SQLITE_OK;
+ char *p = pReader->pOffsetList;
+ char c = 0;
+
+ assert( p );
+
+ if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
+ /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
+ ** Pending-terms doclists are always built up in ascending order, so
+ ** we have to iterate through them backwards here. */
+ u8 bEof = 0;
+ if( ppOffsetList ){
+ *ppOffsetList = pReader->pOffsetList;
+ *pnOffsetList = pReader->nOffsetList - 1;
+ }
+ sqlite3Fts3DoclistPrev(0,
+ pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
+ &pReader->nOffsetList, &bEof
+ );
+ if( bEof ){
+ pReader->pOffsetList = 0;
+ }else{
+ pReader->pOffsetList = p;
+ }
+ }else{
+ char *pEnd = &pReader->aDoclist[pReader->nDoclist];
+
+ /* Pointer p currently points at the first byte of an offset list. The
+ ** following block advances it to point one byte past the end of
+ ** the same offset list. */
+ while( 1 ){
+
+ /* The following line of code (and the "p++" below the while() loop) is
+ ** normally all that is required to move pointer p to the desired
+ ** position. The exception is if this node is being loaded from disk
+ ** incrementally and pointer "p" now points to the first byte past
+ ** the populated part of pReader->aNode[].
+ */
+ while( *p | c ) c = *p++ & 0x80;
+ assert( *p==0 );
+
+ if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
+ rc = fts3SegReaderIncrRead(pReader);
+ if( rc!=SQLITE_OK ) return rc;
+ }
+ p++;
+
+ /* If required, populate the output variables with a pointer to and the
+ ** size of the previous offset-list.
+ */
+ if( ppOffsetList ){
+ *ppOffsetList = pReader->pOffsetList;
+ *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
+ }
+
+ /* List may have been edited in place by fts3EvalNearTrim() */
+ while( p<pEnd && *p==0 ) p++;
+
+ /* If there are no more entries in the doclist, set pOffsetList to
+ ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
+ ** Fts3SegReader.pOffsetList to point to the next offset list before
+ ** returning.
+ */
+ if( p>=pEnd ){
+ pReader->pOffsetList = 0;
+ }else{
+ rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
+ if( rc==SQLITE_OK ){
+ u64 iDelta;
+ pReader->pOffsetList = p + sqlite3Fts3GetVarintU(p, &iDelta);
+ if( pTab->bDescIdx ){
+ pReader->iDocid = (i64)((u64)pReader->iDocid - iDelta);
+ }else{
+ pReader->iDocid = (i64)((u64)pReader->iDocid + iDelta);
+ }
+ }
+ }
+ }
+
+ return rc;
+}
+
+
+SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
+ Fts3Cursor *pCsr,
+ Fts3MultiSegReader *pMsr,
+ int *pnOvfl
+){
+ Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
+ int nOvfl = 0;
+ int ii;
+ int rc = SQLITE_OK;
+ int pgsz = p->nPgsz;
+
+ assert( p->bFts4 );
+ assert( pgsz>0 );
+
+ for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
+ Fts3SegReader *pReader = pMsr->apSegment[ii];
+ if( !fts3SegReaderIsPending(pReader)
+ && !fts3SegReaderIsRootOnly(pReader)
+ ){
+ sqlite3_int64 jj;
+ for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
+ int nBlob;
+ rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
+ if( rc!=SQLITE_OK ) break;
+ if( (nBlob+35)>pgsz ){
+ nOvfl += (nBlob + 34)/pgsz;
+ }
+ }
+ }
+ }
+ *pnOvfl = nOvfl;
+ return rc;
+}
+
+/*
+** Free all allocations associated with the iterator passed as the
+** second argument.
+*/
+SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
+ if( pReader ){
+ if( !fts3SegReaderIsPending(pReader) ){
+ sqlite3_free(pReader->zTerm);
+ }
+ if( !fts3SegReaderIsRootOnly(pReader) ){
+ sqlite3_free(pReader->aNode);
+ }
+ sqlite3_blob_close(pReader->pBlob);
+ }
+ sqlite3_free(pReader);
+}
+
+/*
+** Allocate a new SegReader object.
+*/
+SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
+ int iAge, /* Segment "age". */
+ int bLookup, /* True for a lookup only */
+ sqlite3_int64 iStartLeaf, /* First leaf to traverse */
+ sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
+ sqlite3_int64 iEndBlock, /* Final block of segment */
+ const char *zRoot, /* Buffer containing root node */
+ int nRoot, /* Size of buffer containing root node */
+ Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
+){
+ Fts3SegReader *pReader; /* Newly allocated SegReader object */
+ int nExtra = 0; /* Bytes to allocate segment root node */
+
+ assert( zRoot!=0 || nRoot==0 );
+#ifdef CORRUPT_DB
+ assert( zRoot!=0 || CORRUPT_DB );
+#endif
+
+ if( iStartLeaf==0 ){
+ if( iEndLeaf!=0 ) return FTS_CORRUPT_VTAB;
+ nExtra = nRoot + FTS3_NODE_PADDING;
+ }
+
+ pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
+ if( !pReader ){
+ return SQLITE_NOMEM;
+ }
+ memset(pReader, 0, sizeof(Fts3SegReader));
+ pReader->iIdx = iAge;
+ pReader->bLookup = bLookup!=0;
+ pReader->iStartBlock = iStartLeaf;
+ pReader->iLeafEndBlock = iEndLeaf;
+ pReader->iEndBlock = iEndBlock;
+
+ if( nExtra ){
+ /* The entire segment is stored in the root node. */
+ pReader->aNode = (char *)&pReader[1];
+ pReader->rootOnly = 1;
+ pReader->nNode = nRoot;
+ if( nRoot ) memcpy(pReader->aNode, zRoot, nRoot);
+ memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
+ }else{
+ pReader->iCurrentBlock = iStartLeaf-1;
+ }
+ *ppReader = pReader;
+ return SQLITE_OK;
+}
+
+/*
+** This is a comparison function used as a qsort() callback when sorting
+** an array of pending terms by term. This occurs as part of flushing
+** the contents of the pending-terms hash table to the database.
+*/
+static int SQLITE_CDECL fts3CompareElemByTerm(
+ const void *lhs,
+ const void *rhs
+){
+ char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
+ char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
+ int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
+ int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
+
+ int n = (n1<n2 ? n1 : n2);
+ int c = memcmp(z1, z2, n);
+ if( c==0 ){
+ c = n1 - n2;
+ }
+ return c;
+}
+
+/*
+** This function is used to allocate an Fts3SegReader that iterates through
+** a subset of the terms stored in the Fts3Table.pendingTerms array.
+**
+** If the isPrefixIter parameter is zero, then the returned SegReader iterates
+** through each term in the pending-terms table. Or, if isPrefixIter is
+** non-zero, it iterates through each term and its prefixes. For example, if
+** the pending terms hash table contains the terms "sqlite", "mysql" and
+** "firebird", then the iterator visits the following 'terms' (in the order
+** shown):
+**
+** f fi fir fire fireb firebi firebir firebird
+** m my mys mysq mysql
+** s sq sql sqli sqlit sqlite
+**
+** Whereas if isPrefixIter is zero, the terms visited are:
+**
+** firebird mysql sqlite
+*/
+SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
+ Fts3Table *p, /* Virtual table handle */
+ int iIndex, /* Index for p->aIndex */
+ const char *zTerm, /* Term to search for */
+ int nTerm, /* Size of buffer zTerm */
+ int bPrefix, /* True for a prefix iterator */
+ Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
+){
+ Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
+ Fts3HashElem *pE; /* Iterator variable */
+ Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
+ int nElem = 0; /* Size of array at aElem */
+ int rc = SQLITE_OK; /* Return Code */
+ Fts3Hash *pHash;
+
+ pHash = &p->aIndex[iIndex].hPending;
+ if( bPrefix ){
+ int nAlloc = 0; /* Size of allocated array at aElem */
+
+ for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
+ char *zKey = (char *)fts3HashKey(pE);
+ int nKey = fts3HashKeysize(pE);
+ if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
+ if( nElem==nAlloc ){
+ Fts3HashElem **aElem2;
+ nAlloc += 16;
+ aElem2 = (Fts3HashElem **)sqlite3_realloc(
+ aElem, nAlloc*sizeof(Fts3HashElem *)
+ );
+ if( !aElem2 ){
+ rc = SQLITE_NOMEM;
+ nElem = 0;
+ break;
+ }
+ aElem = aElem2;
+ }
+
+ aElem[nElem++] = pE;
+ }
+ }
+
+ /* If more than one term matches the prefix, sort the Fts3HashElem
+ ** objects in term order using qsort(). This uses the same comparison
+ ** callback as is used when flushing terms to disk.
+ */
+ if( nElem>1 ){
+ qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
+ }
+
+ }else{
+ /* The query is a simple term lookup that matches at most one term in
+ ** the index. All that is required is a straight hash-lookup.
+ **
+ ** Because the stack address of pE may be accessed via the aElem pointer
+ ** below, the "Fts3HashElem *pE" must be declared so that it is valid
+ ** within this entire function, not just this "else{...}" block.
+ */
+ pE = fts3HashFindElem(pHash, zTerm, nTerm);
+ if( pE ){
+ aElem = &pE;
+ nElem = 1;
+ }
+ }
+
+ if( nElem>0 ){
+ sqlite3_int64 nByte;
+ nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
+ pReader = (Fts3SegReader *)sqlite3_malloc64(nByte);
+ if( !pReader ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memset(pReader, 0, nByte);
+ pReader->iIdx = 0x7FFFFFFF;
+ pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
+ memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
+ }
+ }
+
+ if( bPrefix ){
+ sqlite3_free(aElem);
+ }
+ *ppReader = pReader;
+ return rc;
+}
+
+/*
+** Compare the entries pointed to by two Fts3SegReader structures.
+** Comparison is as follows:
+**
+** 1) EOF is greater than not EOF.
+**
+** 2) The current terms (if any) are compared using memcmp(). If one
+** term is a prefix of another, the longer term is considered the
+** larger.
+**
+** 3) By segment age. An older segment is considered larger.
+*/
+static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
+ int rc;
+ if( pLhs->aNode && pRhs->aNode ){
+ int rc2 = pLhs->nTerm - pRhs->nTerm;
+ if( rc2<0 ){
+ rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
+ }else{
+ rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
+ }
+ if( rc==0 ){
+ rc = rc2;
+ }
+ }else{
+ rc = (pLhs->aNode==0) - (pRhs->aNode==0);
+ }
+ if( rc==0 ){
+ rc = pRhs->iIdx - pLhs->iIdx;
+ }
+ assert( rc!=0 );
+ return rc;
+}
+
+/*
+** A different comparison function for SegReader structures. In this
+** version, it is assumed that each SegReader points to an entry in
+** a doclist for identical terms. Comparison is made as follows:
+**
+** 1) EOF (end of doclist in this case) is greater than not EOF.
+**
+** 2) By current docid.
+**
+** 3) By segment age. An older segment is considered larger.
+*/
+static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
+ int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
+ if( rc==0 ){
+ if( pLhs->iDocid==pRhs->iDocid ){
+ rc = pRhs->iIdx - pLhs->iIdx;
+ }else{
+ rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
+ }
+ }
+ assert( pLhs->aNode && pRhs->aNode );
+ return rc;
+}
+static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
+ int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
+ if( rc==0 ){
+ if( pLhs->iDocid==pRhs->iDocid ){
+ rc = pRhs->iIdx - pLhs->iIdx;
+ }else{
+ rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
+ }
+ }
+ assert( pLhs->aNode && pRhs->aNode );
+ return rc;
+}
+
+/*
+** Compare the term that the Fts3SegReader object passed as the first argument
+** points to with the term specified by arguments zTerm and nTerm.
+**
+** If the pSeg iterator is already at EOF, return 0. Otherwise, return
+** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
+** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
+*/
+static int fts3SegReaderTermCmp(
+ Fts3SegReader *pSeg, /* Segment reader object */
+ const char *zTerm, /* Term to compare to */
+ int nTerm /* Size of term zTerm in bytes */
+){
+ int res = 0;
+ if( pSeg->aNode ){
+ if( pSeg->nTerm>nTerm ){
+ res = memcmp(pSeg->zTerm, zTerm, nTerm);
+ }else{
+ res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
+ }
+ if( res==0 ){
+ res = pSeg->nTerm-nTerm;
+ }
+ }
+ return res;
+}
+
+/*
+** Argument apSegment is an array of nSegment elements. It is known that
+** the final (nSegment-nSuspect) members are already in sorted order
+** (according to the comparison function provided). This function shuffles
+** the array around until all entries are in sorted order.
+*/
+static void fts3SegReaderSort(
+ Fts3SegReader **apSegment, /* Array to sort entries of */
+ int nSegment, /* Size of apSegment array */
+ int nSuspect, /* Unsorted entry count */
+ int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
+){
+ int i; /* Iterator variable */
+
+ assert( nSuspect<=nSegment );
+
+ if( nSuspect==nSegment ) nSuspect--;
+ for(i=nSuspect-1; i>=0; i--){
+ int j;
+ for(j=i; j<(nSegment-1); j++){
+ Fts3SegReader *pTmp;
+ if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
+ pTmp = apSegment[j+1];
+ apSegment[j+1] = apSegment[j];
+ apSegment[j] = pTmp;
+ }
+ }
+
+#ifndef NDEBUG
+ /* Check that the list really is sorted now. */
+ for(i=0; i<(nSuspect-1); i++){
+ assert( xCmp(apSegment[i], apSegment[i+1])<0 );
+ }
+#endif
+}
+
+/*
+** Insert a record into the %_segments table.
+*/
+static int fts3WriteSegment(
+ Fts3Table *p, /* Virtual table handle */
+ sqlite3_int64 iBlock, /* Block id for new block */
+ char *z, /* Pointer to buffer containing block data */
+ int n /* Size of buffer z in bytes */
+){
+ sqlite3_stmt *pStmt;
+ int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pStmt, 1, iBlock);
+ sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
+ sqlite3_step(pStmt);
+ rc = sqlite3_reset(pStmt);
+ sqlite3_bind_null(pStmt, 2);
+ }
+ return rc;
+}
+
+/*
+** Find the largest relative level number in the table. If successful, set
+** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
+** set *pnMax to zero and return an SQLite error code.
+*/
+SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
+ int rc;
+ int mxLevel = 0;
+ sqlite3_stmt *pStmt = 0;
+
+ rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
+ if( rc==SQLITE_OK ){
+ if( SQLITE_ROW==sqlite3_step(pStmt) ){
+ mxLevel = sqlite3_column_int(pStmt, 0);
+ }
+ rc = sqlite3_reset(pStmt);
+ }
+ *pnMax = mxLevel;
+ return rc;
+}
+
+/*
+** Insert a record into the %_segdir table.
+*/
+static int fts3WriteSegdir(
+ Fts3Table *p, /* Virtual table handle */
+ sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
+ int iIdx, /* Value for "idx" field */
+ sqlite3_int64 iStartBlock, /* Value for "start_block" field */
+ sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
+ sqlite3_int64 iEndBlock, /* Value for "end_block" field */
+ sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
+ char *zRoot, /* Blob value for "root" field */
+ int nRoot /* Number of bytes in buffer zRoot */
+){
+ sqlite3_stmt *pStmt;
+ int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pStmt, 1, iLevel);
+ sqlite3_bind_int(pStmt, 2, iIdx);
+ sqlite3_bind_int64(pStmt, 3, iStartBlock);
+ sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
+ if( nLeafData==0 ){
+ sqlite3_bind_int64(pStmt, 5, iEndBlock);
+ }else{
+ char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
+ if( !zEnd ) return SQLITE_NOMEM;
+ sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
+ }
+ sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
+ sqlite3_step(pStmt);
+ rc = sqlite3_reset(pStmt);
+ sqlite3_bind_null(pStmt, 6);
+ }
+ return rc;
+}
+
+/*
+** Return the size of the common prefix (if any) shared by zPrev and
+** zNext, in bytes. For example,
+**
+** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
+** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
+** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
+*/
+static int fts3PrefixCompress(
+ const char *zPrev, /* Buffer containing previous term */
+ int nPrev, /* Size of buffer zPrev in bytes */
+ const char *zNext, /* Buffer containing next term */
+ int nNext /* Size of buffer zNext in bytes */
+){
+ int n;
+ UNUSED_PARAMETER(nNext);
+ for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
+ return n;
+}
+
+/*
+** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
+** (according to memcmp) than the previous term.
+*/
+static int fts3NodeAddTerm(
+ Fts3Table *p, /* Virtual table handle */
+ SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
+ int isCopyTerm, /* True if zTerm/nTerm is transient */
+ const char *zTerm, /* Pointer to buffer containing term */
+ int nTerm /* Size of term in bytes */
+){
+ SegmentNode *pTree = *ppTree;
+ int rc;
+ SegmentNode *pNew;
+
+ /* First try to append the term to the current node. Return early if
+ ** this is possible.
+ */
+ if( pTree ){
+ int nData = pTree->nData; /* Current size of node in bytes */
+ int nReq = nData; /* Required space after adding zTerm */
+ int nPrefix; /* Number of bytes of prefix compression */
+ int nSuffix; /* Suffix length */
+
+ nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
+ nSuffix = nTerm-nPrefix;
+
+ /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of
+ ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when
+ ** compared with BINARY collation. This indicates corruption. */
+ if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
+
+ nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
+ if( nReq<=p->nNodeSize || !pTree->zTerm ){
+
+ if( nReq>p->nNodeSize ){
+ /* An unusual case: this is the first term to be added to the node
+ ** and the static node buffer (p->nNodeSize bytes) is not large
+ ** enough. Use a separately malloced buffer instead This wastes
+ ** p->nNodeSize bytes, but since this scenario only comes about when
+ ** the database contain two terms that share a prefix of almost 2KB,
+ ** this is not expected to be a serious problem.
+ */
+ assert( pTree->aData==(char *)&pTree[1] );
+ pTree->aData = (char *)sqlite3_malloc(nReq);
+ if( !pTree->aData ){
+ return SQLITE_NOMEM;
+ }
+ }
+
+ if( pTree->zTerm ){
+ /* There is no prefix-length field for first term in a node */
+ nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
+ }
+
+ nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
+ memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
+ pTree->nData = nData + nSuffix;
+ pTree->nEntry++;
+
+ if( isCopyTerm ){
+ if( pTree->nMalloc<nTerm ){
+ char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
+ if( !zNew ){
+ return SQLITE_NOMEM;
+ }
+ pTree->nMalloc = nTerm*2;
+ pTree->zMalloc = zNew;
+ }
+ pTree->zTerm = pTree->zMalloc;
+ memcpy(pTree->zTerm, zTerm, nTerm);
+ pTree->nTerm = nTerm;
+ }else{
+ pTree->zTerm = (char *)zTerm;
+ pTree->nTerm = nTerm;
+ }
+ return SQLITE_OK;
+ }
+ }
+
+ /* If control flows to here, it was not possible to append zTerm to the
+ ** current node. Create a new node (a right-sibling of the current node).
+ ** If this is the first node in the tree, the term is added to it.
+ **
+ ** Otherwise, the term is not added to the new node, it is left empty for
+ ** now. Instead, the term is inserted into the parent of pTree. If pTree
+ ** has no parent, one is created here.
+ */
+ pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
+ if( !pNew ){
+ return SQLITE_NOMEM;
+ }
+ memset(pNew, 0, sizeof(SegmentNode));
+ pNew->nData = 1 + FTS3_VARINT_MAX;
+ pNew->aData = (char *)&pNew[1];
+
+ if( pTree ){
+ SegmentNode *pParent = pTree->pParent;
+ rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
+ if( pTree->pParent==0 ){
+ pTree->pParent = pParent;
+ }
+ pTree->pRight = pNew;
+ pNew->pLeftmost = pTree->pLeftmost;
+ pNew->pParent = pParent;
+ pNew->zMalloc = pTree->zMalloc;
+ pNew->nMalloc = pTree->nMalloc;
+ pTree->zMalloc = 0;
+ }else{
+ pNew->pLeftmost = pNew;
+ rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
+ }
+
+ *ppTree = pNew;
+ return rc;
+}
+
+/*
+** Helper function for fts3NodeWrite().
+*/
+static int fts3TreeFinishNode(
+ SegmentNode *pTree,
+ int iHeight,
+ sqlite3_int64 iLeftChild
+){
+ int nStart;
+ assert( iHeight>=1 && iHeight<128 );
+ nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
+ pTree->aData[nStart] = (char)iHeight;
+ sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
+ return nStart;
+}
+
+/*
+** Write the buffer for the segment node pTree and all of its peers to the
+** database. Then call this function recursively to write the parent of
+** pTree and its peers to the database.
+**
+** Except, if pTree is a root node, do not write it to the database. Instead,
+** set output variables *paRoot and *pnRoot to contain the root node.
+**
+** If successful, SQLITE_OK is returned and output variable *piLast is
+** set to the largest blockid written to the database (or zero if no
+** blocks were written to the db). Otherwise, an SQLite error code is
+** returned.
+*/
+static int fts3NodeWrite(
+ Fts3Table *p, /* Virtual table handle */
+ SegmentNode *pTree, /* SegmentNode handle */
+ int iHeight, /* Height of this node in tree */
+ sqlite3_int64 iLeaf, /* Block id of first leaf node */
+ sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
+ sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
+ char **paRoot, /* OUT: Data for root node */
+ int *pnRoot /* OUT: Size of root node in bytes */
+){
+ int rc = SQLITE_OK;
+
+ if( !pTree->pParent ){
+ /* Root node of the tree. */
+ int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
+ *piLast = iFree-1;
+ *pnRoot = pTree->nData - nStart;
+ *paRoot = &pTree->aData[nStart];
+ }else{
+ SegmentNode *pIter;
+ sqlite3_int64 iNextFree = iFree;
+ sqlite3_int64 iNextLeaf = iLeaf;
+ for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
+ int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
+ int nWrite = pIter->nData - nStart;
+
+ rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
+ iNextFree++;
+ iNextLeaf += (pIter->nEntry+1);
+ }
+ if( rc==SQLITE_OK ){
+ assert( iNextLeaf==iFree );
+ rc = fts3NodeWrite(
+ p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
+ );
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Free all memory allocations associated with the tree pTree.
+*/
+static void fts3NodeFree(SegmentNode *pTree){
+ if( pTree ){
+ SegmentNode *p = pTree->pLeftmost;
+ fts3NodeFree(p->pParent);
+ while( p ){
+ SegmentNode *pRight = p->pRight;
+ if( p->aData!=(char *)&p[1] ){
+ sqlite3_free(p->aData);
+ }
+ assert( pRight==0 || p->zMalloc==0 );
+ sqlite3_free(p->zMalloc);
+ sqlite3_free(p);
+ p = pRight;
+ }
+ }
+}
+
+/*
+** Add a term to the segment being constructed by the SegmentWriter object
+** *ppWriter. When adding the first term to a segment, *ppWriter should
+** be passed NULL. This function will allocate a new SegmentWriter object
+** and return it via the input/output variable *ppWriter in this case.
+**
+** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
+*/
+static int fts3SegWriterAdd(
+ Fts3Table *p, /* Virtual table handle */
+ SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
+ int isCopyTerm, /* True if buffer zTerm must be copied */
+ const char *zTerm, /* Pointer to buffer containing term */
+ int nTerm, /* Size of term in bytes */
+ const char *aDoclist, /* Pointer to buffer containing doclist */
+ int nDoclist /* Size of doclist in bytes */
+){
+ int nPrefix; /* Size of term prefix in bytes */
+ int nSuffix; /* Size of term suffix in bytes */
+ int nReq; /* Number of bytes required on leaf page */
+ int nData;
+ SegmentWriter *pWriter = *ppWriter;
+
+ if( !pWriter ){
+ int rc;
+ sqlite3_stmt *pStmt;
+
+ /* Allocate the SegmentWriter structure */
+ pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
+ if( !pWriter ) return SQLITE_NOMEM;
+ memset(pWriter, 0, sizeof(SegmentWriter));
+ *ppWriter = pWriter;
+
+ /* Allocate a buffer in which to accumulate data */
+ pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
+ if( !pWriter->aData ) return SQLITE_NOMEM;
+ pWriter->nSize = p->nNodeSize;
+
+ /* Find the next free blockid in the %_segments table */
+ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
+ if( rc!=SQLITE_OK ) return rc;
+ if( SQLITE_ROW==sqlite3_step(pStmt) ){
+ pWriter->iFree = sqlite3_column_int64(pStmt, 0);
+ pWriter->iFirst = pWriter->iFree;
+ }
+ rc = sqlite3_reset(pStmt);
+ if( rc!=SQLITE_OK ) return rc;
+ }
+ nData = pWriter->nData;
+
+ nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
+ nSuffix = nTerm-nPrefix;
+
+ /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of
+ ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when
+ ** compared with BINARY collation. This indicates corruption. */
+ if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
+
+ /* Figure out how many bytes are required by this new entry */
+ nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
+ sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
+ nSuffix + /* Term suffix */
+ sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
+ nDoclist; /* Doclist data */
+
+ if( nData>0 && nData+nReq>p->nNodeSize ){
+ int rc;
+
+ /* The current leaf node is full. Write it out to the database. */
+ if( pWriter->iFree==LARGEST_INT64 ) return FTS_CORRUPT_VTAB;
+ rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
+ if( rc!=SQLITE_OK ) return rc;
+ p->nLeafAdd++;
+
+ /* Add the current term to the interior node tree. The term added to
+ ** the interior tree must:
+ **
+ ** a) be greater than the largest term on the leaf node just written
+ ** to the database (still available in pWriter->zTerm), and
+ **
+ ** b) be less than or equal to the term about to be added to the new
+ ** leaf node (zTerm/nTerm).
+ **
+ ** In other words, it must be the prefix of zTerm 1 byte longer than
+ ** the common prefix (if any) of zTerm and pWriter->zTerm.
+ */
+ assert( nPrefix<nTerm );
+ rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
+ if( rc!=SQLITE_OK ) return rc;
+
+ nData = 0;
+ pWriter->nTerm = 0;
+
+ nPrefix = 0;
+ nSuffix = nTerm;
+ nReq = 1 + /* varint containing prefix size */
+ sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
+ nTerm + /* Term suffix */
+ sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
+ nDoclist; /* Doclist data */
+ }
+
+ /* Increase the total number of bytes written to account for the new entry. */
+ pWriter->nLeafData += nReq;
+
+ /* If the buffer currently allocated is too small for this entry, realloc
+ ** the buffer to make it large enough.
+ */
+ if( nReq>pWriter->nSize ){
+ char *aNew = sqlite3_realloc(pWriter->aData, nReq);
+ if( !aNew ) return SQLITE_NOMEM;
+ pWriter->aData = aNew;
+ pWriter->nSize = nReq;
+ }
+ assert( nData+nReq<=pWriter->nSize );
+
+ /* Append the prefix-compressed term and doclist to the buffer. */
+ nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
+ nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
+ assert( nSuffix>0 );
+ memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
+ nData += nSuffix;
+ nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
+ assert( nDoclist>0 );
+ memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
+ pWriter->nData = nData + nDoclist;
+
+ /* Save the current term so that it can be used to prefix-compress the next.
+ ** If the isCopyTerm parameter is true, then the buffer pointed to by
+ ** zTerm is transient, so take a copy of the term data. Otherwise, just
+ ** store a copy of the pointer.
+ */
+ if( isCopyTerm ){
+ if( nTerm>pWriter->nMalloc ){
+ char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
+ if( !zNew ){
+ return SQLITE_NOMEM;
+ }
+ pWriter->nMalloc = nTerm*2;
+ pWriter->zMalloc = zNew;
+ pWriter->zTerm = zNew;
+ }
+ assert( pWriter->zTerm==pWriter->zMalloc );
+ assert( nTerm>0 );
+ memcpy(pWriter->zTerm, zTerm, nTerm);
+ }else{
+ pWriter->zTerm = (char *)zTerm;
+ }
+ pWriter->nTerm = nTerm;
+
+ return SQLITE_OK;
+}
+
+/*
+** Flush all data associated with the SegmentWriter object pWriter to the
+** database. This function must be called after all terms have been added
+** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
+** returned. Otherwise, an SQLite error code.
+*/
+static int fts3SegWriterFlush(
+ Fts3Table *p, /* Virtual table handle */
+ SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
+ sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
+ int iIdx /* Value for 'idx' column of %_segdir */
+){
+ int rc; /* Return code */
+ if( pWriter->pTree ){
+ sqlite3_int64 iLast = 0; /* Largest block id written to database */
+ sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
+ char *zRoot = NULL; /* Pointer to buffer containing root node */
+ int nRoot = 0; /* Size of buffer zRoot */
+
+ iLastLeaf = pWriter->iFree;
+ rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
+ if( rc==SQLITE_OK ){
+ rc = fts3NodeWrite(p, pWriter->pTree, 1,
+ pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
+ }
+ if( rc==SQLITE_OK ){
+ rc = fts3WriteSegdir(p, iLevel, iIdx,
+ pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
+ }
+ }else{
+ /* The entire tree fits on the root node. Write it to the segdir table. */
+ rc = fts3WriteSegdir(p, iLevel, iIdx,
+ 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
+ }
+ p->nLeafAdd++;
+ return rc;
+}
+
+/*
+** Release all memory held by the SegmentWriter object passed as the
+** first argument.
+*/
+static void fts3SegWriterFree(SegmentWriter *pWriter){
+ if( pWriter ){
+ sqlite3_free(pWriter->aData);
+ sqlite3_free(pWriter->zMalloc);
+ fts3NodeFree(pWriter->pTree);
+ sqlite3_free(pWriter);
+ }
+}
+
+/*
+** The first value in the apVal[] array is assumed to contain an integer.
+** This function tests if there exist any documents with docid values that
+** are different from that integer. i.e. if deleting the document with docid
+** pRowid would mean the FTS3 table were empty.
+**
+** If successful, *pisEmpty is set to true if the table is empty except for
+** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
+** error occurs, an SQLite error code is returned.
+*/
+static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
+ sqlite3_stmt *pStmt;
+ int rc;
+ if( p->zContentTbl ){
+ /* If using the content=xxx option, assume the table is never empty */
+ *pisEmpty = 0;
+ rc = SQLITE_OK;
+ }else{
+ rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
+ if( rc==SQLITE_OK ){
+ if( SQLITE_ROW==sqlite3_step(pStmt) ){
+ *pisEmpty = sqlite3_column_int(pStmt, 0);
+ }
+ rc = sqlite3_reset(pStmt);
+ }
+ }
+ return rc;
+}
+
+/*
+** Set *pnMax to the largest segment level in the database for the index
+** iIndex.
+**
+** Segment levels are stored in the 'level' column of the %_segdir table.
+**
+** Return SQLITE_OK if successful, or an SQLite error code if not.
+*/
+static int fts3SegmentMaxLevel(
+ Fts3Table *p,
+ int iLangid,
+ int iIndex,
+ sqlite3_int64 *pnMax
+){
+ sqlite3_stmt *pStmt;
+ int rc;
+ assert( iIndex>=0 && iIndex<p->nIndex );
+
+ /* Set pStmt to the compiled version of:
+ **
+ ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
+ **
+ ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
+ */
+ rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
+ if( rc!=SQLITE_OK ) return rc;
+ sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
+ sqlite3_bind_int64(pStmt, 2,
+ getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
+ );
+ if( SQLITE_ROW==sqlite3_step(pStmt) ){
+ *pnMax = sqlite3_column_int64(pStmt, 0);
+ }
+ return sqlite3_reset(pStmt);
+}
+
+/*
+** iAbsLevel is an absolute level that may be assumed to exist within
+** the database. This function checks if it is the largest level number
+** within its index. Assuming no error occurs, *pbMax is set to 1 if
+** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
+** is returned. If an error occurs, an error code is returned and the
+** final value of *pbMax is undefined.
+*/
+static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
+
+ /* Set pStmt to the compiled version of:
+ **
+ ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
+ **
+ ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
+ */
+ sqlite3_stmt *pStmt;
+ int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
+ if( rc!=SQLITE_OK ) return rc;
+ sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
+ sqlite3_bind_int64(pStmt, 2,
+ (((u64)iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
+ );
+
+ *pbMax = 0;
+ if( SQLITE_ROW==sqlite3_step(pStmt) ){
+ *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
+ }
+ return sqlite3_reset(pStmt);
+}
+
+/*
+** Delete all entries in the %_segments table associated with the segment
+** opened with seg-reader pSeg. This function does not affect the contents
+** of the %_segdir table.
+*/
+static int fts3DeleteSegment(
+ Fts3Table *p, /* FTS table handle */
+ Fts3SegReader *pSeg /* Segment to delete */
+){
+ int rc = SQLITE_OK; /* Return code */
+ if( pSeg->iStartBlock ){
+ sqlite3_stmt *pDelete; /* SQL statement to delete rows */
+ rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
+ sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
+ sqlite3_step(pDelete);
+ rc = sqlite3_reset(pDelete);
+ }
+ }
+ return rc;
+}
+
+/*
+** This function is used after merging multiple segments into a single large
+** segment to delete the old, now redundant, segment b-trees. Specifically,
+** it:
+**
+** 1) Deletes all %_segments entries for the segments associated with
+** each of the SegReader objects in the array passed as the third
+** argument, and
+**
+** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
+** entries regardless of level if (iLevel<0).
+**
+** SQLITE_OK is returned if successful, otherwise an SQLite error code.
+*/
+static int fts3DeleteSegdir(
+ Fts3Table *p, /* Virtual table handle */
+ int iLangid, /* Language id */
+ int iIndex, /* Index for p->aIndex */
+ int iLevel, /* Level of %_segdir entries to delete */
+ Fts3SegReader **apSegment, /* Array of SegReader objects */
+ int nReader /* Size of array apSegment */
+){
+ int rc = SQLITE_OK; /* Return Code */
+ int i; /* Iterator variable */
+ sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
+
+ for(i=0; rc==SQLITE_OK && i<nReader; i++){
+ rc = fts3DeleteSegment(p, apSegment[i]);
+ }
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+
+ assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
+ if( iLevel==FTS3_SEGCURSOR_ALL ){
+ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
+ sqlite3_bind_int64(pDelete, 2,
+ getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
+ );
+ }
+ }else{
+ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(
+ pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
+ );
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ sqlite3_step(pDelete);
+ rc = sqlite3_reset(pDelete);
+ }
+
+ return rc;
+}
+
+/*
+** When this function is called, buffer *ppList (size *pnList bytes) contains
+** a position list that may (or may not) feature multiple columns. This
+** function adjusts the pointer *ppList and the length *pnList so that they
+** identify the subset of the position list that corresponds to column iCol.
+**
+** If there are no entries in the input position list for column iCol, then
+** *pnList is set to zero before returning.
+**
+** If parameter bZero is non-zero, then any part of the input list following
+** the end of the output list is zeroed before returning.
+*/
+static void fts3ColumnFilter(
+ int iCol, /* Column to filter on */
+ int bZero, /* Zero out anything following *ppList */
+ char **ppList, /* IN/OUT: Pointer to position list */
+ int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
+){
+ char *pList = *ppList;
+ int nList = *pnList;
+ char *pEnd = &pList[nList];
+ int iCurrent = 0;
+ char *p = pList;
+
+ assert( iCol>=0 );
+ while( 1 ){
+ char c = 0;
+ while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
+
+ if( iCol==iCurrent ){
+ nList = (int)(p - pList);
+ break;
+ }
+
+ nList -= (int)(p - pList);
+ pList = p;
+ if( nList<=0 ){
+ break;
+ }
+ p = &pList[1];
+ p += fts3GetVarint32(p, &iCurrent);
+ }
+
+ if( bZero && (pEnd - &pList[nList])>0){
+ memset(&pList[nList], 0, pEnd - &pList[nList]);
+ }
+ *ppList = pList;
+ *pnList = nList;
+}
+
+/*
+** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
+** existing data). Grow the buffer if required.
+**
+** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
+** trying to resize the buffer, return SQLITE_NOMEM.
+*/
+static int fts3MsrBufferData(
+ Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
+ char *pList,
+ int nList
+){
+ if( nList>pMsr->nBuffer ){
+ char *pNew;
+ pMsr->nBuffer = nList*2;
+ pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
+ if( !pNew ) return SQLITE_NOMEM;
+ pMsr->aBuffer = pNew;
+ }
+
+ assert( nList>0 );
+ memcpy(pMsr->aBuffer, pList, nList);
+ return SQLITE_OK;
+}
+
+SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
+ Fts3Table *p, /* Virtual table handle */
+ Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
+ sqlite3_int64 *piDocid, /* OUT: Docid value */
+ char **paPoslist, /* OUT: Pointer to position list */
+ int *pnPoslist /* OUT: Size of position list in bytes */
+){
+ int nMerge = pMsr->nAdvance;
+ Fts3SegReader **apSegment = pMsr->apSegment;
+ int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
+ p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
+ );
+
+ if( nMerge==0 ){
+ *paPoslist = 0;
+ return SQLITE_OK;
+ }
+
+ while( 1 ){
+ Fts3SegReader *pSeg;
+ pSeg = pMsr->apSegment[0];
+
+ if( pSeg->pOffsetList==0 ){
+ *paPoslist = 0;
+ break;
+ }else{
+ int rc;
+ char *pList;
+ int nList;
+ int j;
+ sqlite3_int64 iDocid = apSegment[0]->iDocid;
+
+ rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
+ j = 1;
+ while( rc==SQLITE_OK
+ && j<nMerge
+ && apSegment[j]->pOffsetList
+ && apSegment[j]->iDocid==iDocid
+ ){
+ rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
+ j++;
+ }
+ if( rc!=SQLITE_OK ) return rc;
+ fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
+
+ if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
+ rc = fts3MsrBufferData(pMsr, pList, nList+1);
+ if( rc!=SQLITE_OK ) return rc;
+ assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
+ pList = pMsr->aBuffer;
+ }
+
+ if( pMsr->iColFilter>=0 ){
+ fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
+ }
+
+ if( nList>0 ){
+ *paPoslist = pList;
+ *piDocid = iDocid;
+ *pnPoslist = nList;
+ break;
+ }
+ }
+ }
+
+ return SQLITE_OK;
+}
+
+static int fts3SegReaderStart(
+ Fts3Table *p, /* Virtual table handle */
+ Fts3MultiSegReader *pCsr, /* Cursor object */
+ const char *zTerm, /* Term searched for (or NULL) */
+ int nTerm /* Length of zTerm in bytes */
+){
+ int i;
+ int nSeg = pCsr->nSegment;
+
+ /* If the Fts3SegFilter defines a specific term (or term prefix) to search
+ ** for, then advance each segment iterator until it points to a term of
+ ** equal or greater value than the specified term. This prevents many
+ ** unnecessary merge/sort operations for the case where single segment
+ ** b-tree leaf nodes contain more than one term.
+ */
+ for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
+ int res = 0;
+ Fts3SegReader *pSeg = pCsr->apSegment[i];
+ do {
+ int rc = fts3SegReaderNext(p, pSeg, 0);
+ if( rc!=SQLITE_OK ) return rc;
+ }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
+
+ if( pSeg->bLookup && res!=0 ){
+ fts3SegReaderSetEof(pSeg);
+ }
+ }
+ fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
+
+ return SQLITE_OK;
+}
+
+SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
+ Fts3Table *p, /* Virtual table handle */
+ Fts3MultiSegReader *pCsr, /* Cursor object */
+ Fts3SegFilter *pFilter /* Restrictions on range of iteration */
+){
+ pCsr->pFilter = pFilter;
+ return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
+}
+
+SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
+ Fts3Table *p, /* Virtual table handle */
+ Fts3MultiSegReader *pCsr, /* Cursor object */
+ int iCol, /* Column to match on. */
+ const char *zTerm, /* Term to iterate through a doclist for */
+ int nTerm /* Number of bytes in zTerm */
+){
+ int i;
+ int rc;
+ int nSegment = pCsr->nSegment;
+ int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
+ p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
+ );
+
+ assert( pCsr->pFilter==0 );
+ assert( zTerm && nTerm>0 );
+
+ /* Advance each segment iterator until it points to the term zTerm/nTerm. */
+ rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
+ if( rc!=SQLITE_OK ) return rc;
+
+ /* Determine how many of the segments actually point to zTerm/nTerm. */
+ for(i=0; i<nSegment; i++){
+ Fts3SegReader *pSeg = pCsr->apSegment[i];
+ if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
+ break;
+ }
+ }
+ pCsr->nAdvance = i;
+
+ /* Advance each of the segments to point to the first docid. */
+ for(i=0; i<pCsr->nAdvance; i++){
+ rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
+ if( rc!=SQLITE_OK ) return rc;
+ }
+ fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
+
+ assert( iCol<0 || iCol<p->nColumn );
+ pCsr->iColFilter = iCol;
+
+ return SQLITE_OK;
+}
+
+/*
+** This function is called on a MultiSegReader that has been started using
+** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
+** have been made. Calling this function puts the MultiSegReader in such
+** a state that if the next two calls are:
+**
+** sqlite3Fts3SegReaderStart()
+** sqlite3Fts3SegReaderStep()
+**
+** then the entire doclist for the term is available in
+** MultiSegReader.aDoclist/nDoclist.
+*/
+SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
+ int i; /* Used to iterate through segment-readers */
+
+ assert( pCsr->zTerm==0 );
+ assert( pCsr->nTerm==0 );
+ assert( pCsr->aDoclist==0 );
+ assert( pCsr->nDoclist==0 );
+
+ pCsr->nAdvance = 0;
+ pCsr->bRestart = 1;
+ for(i=0; i<pCsr->nSegment; i++){
+ pCsr->apSegment[i]->pOffsetList = 0;
+ pCsr->apSegment[i]->nOffsetList = 0;
+ pCsr->apSegment[i]->iDocid = 0;
+ }
+
+ return SQLITE_OK;
+}
+
+static int fts3GrowSegReaderBuffer(Fts3MultiSegReader *pCsr, int nReq){
+ if( nReq>pCsr->nBuffer ){
+ char *aNew;
+ pCsr->nBuffer = nReq*2;
+ aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
+ if( !aNew ){
+ return SQLITE_NOMEM;
+ }
+ pCsr->aBuffer = aNew;
+ }
+ return SQLITE_OK;
+}
+
+
+SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
+ Fts3Table *p, /* Virtual table handle */
+ Fts3MultiSegReader *pCsr /* Cursor object */
+){
+ int rc = SQLITE_OK;
+
+ int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
+ int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
+ int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
+ int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
+ int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
+ int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
+
+ Fts3SegReader **apSegment = pCsr->apSegment;
+ int nSegment = pCsr->nSegment;
+ Fts3SegFilter *pFilter = pCsr->pFilter;
+ int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
+ p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
+ );
+
+ if( pCsr->nSegment==0 ) return SQLITE_OK;
+
+ do {
+ int nMerge;
+ int i;
+
+ /* Advance the first pCsr->nAdvance entries in the apSegment[] array
+ ** forward. Then sort the list in order of current term again.
+ */
+ for(i=0; i<pCsr->nAdvance; i++){
+ Fts3SegReader *pSeg = apSegment[i];
+ if( pSeg->bLookup ){
+ fts3SegReaderSetEof(pSeg);
+ }else{
+ rc = fts3SegReaderNext(p, pSeg, 0);
+ }
+ if( rc!=SQLITE_OK ) return rc;
+ }
+ fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
+ pCsr->nAdvance = 0;
+
+ /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
+ assert( rc==SQLITE_OK );
+ if( apSegment[0]->aNode==0 ) break;
+
+ pCsr->nTerm = apSegment[0]->nTerm;
+ pCsr->zTerm = apSegment[0]->zTerm;
+
+ /* If this is a prefix-search, and if the term that apSegment[0] points
+ ** to does not share a suffix with pFilter->zTerm/nTerm, then all
+ ** required callbacks have been made. In this case exit early.
+ **
+ ** Similarly, if this is a search for an exact match, and the first term
+ ** of segment apSegment[0] is not a match, exit early.
+ */
+ if( pFilter->zTerm && !isScan ){
+ if( pCsr->nTerm<pFilter->nTerm
+ || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
+ || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
+ ){
+ break;
+ }
+ }
+
+ nMerge = 1;
+ while( nMerge<nSegment
+ && apSegment[nMerge]->aNode
+ && apSegment[nMerge]->nTerm==pCsr->nTerm
+ && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
+ ){
+ nMerge++;
+ }
+
+ assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
+ if( nMerge==1
+ && !isIgnoreEmpty
+ && !isFirst
+ && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
+ ){
+ pCsr->nDoclist = apSegment[0]->nDoclist;
+ if( fts3SegReaderIsPending(apSegment[0]) ){
+ rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
+ pCsr->aDoclist = pCsr->aBuffer;
+ }else{
+ pCsr->aDoclist = apSegment[0]->aDoclist;
+ }
+ if( rc==SQLITE_OK ) rc = SQLITE_ROW;
+ }else{
+ int nDoclist = 0; /* Size of doclist */
+ sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
+
+ /* The current term of the first nMerge entries in the array
+ ** of Fts3SegReader objects is the same. The doclists must be merged
+ ** and a single term returned with the merged doclist.
+ */
+ for(i=0; i<nMerge; i++){
+ fts3SegReaderFirstDocid(p, apSegment[i]);
+ }
+ fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
+ while( apSegment[0]->pOffsetList ){
+ int j; /* Number of segments that share a docid */
+ char *pList = 0;
+ int nList = 0;
+ int nByte;
+ sqlite3_int64 iDocid = apSegment[0]->iDocid;
+ fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
+ j = 1;
+ while( j<nMerge
+ && apSegment[j]->pOffsetList
+ && apSegment[j]->iDocid==iDocid
+ ){
+ fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
+ j++;
+ }
+
+ if( isColFilter ){
+ fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
+ }
+
+ if( !isIgnoreEmpty || nList>0 ){
+
+ /* Calculate the 'docid' delta value to write into the merged
+ ** doclist. */
+ sqlite3_int64 iDelta;
+ if( p->bDescIdx && nDoclist>0 ){
+ if( iPrev<=iDocid ) return FTS_CORRUPT_VTAB;
+ iDelta = (i64)((u64)iPrev - (u64)iDocid);
+ }else{
+ if( nDoclist>0 && iPrev>=iDocid ) return FTS_CORRUPT_VTAB;
+ iDelta = (i64)((u64)iDocid - (u64)iPrev);
+ }
+
+ nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
+
+ rc = fts3GrowSegReaderBuffer(pCsr, nByte+nDoclist);
+ if( rc ) return rc;
+
+ if( isFirst ){
+ char *a = &pCsr->aBuffer[nDoclist];
+ int nWrite;
+
+ nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
+ if( nWrite ){
+ iPrev = iDocid;
+ nDoclist += nWrite;
+ }
+ }else{
+ nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
+ iPrev = iDocid;
+ if( isRequirePos ){
+ memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
+ nDoclist += nList;
+ pCsr->aBuffer[nDoclist++] = '\0';
+ }
+ }
+ }
+
+ fts3SegReaderSort(apSegment, nMerge, j, xCmp);
+ }
+ if( nDoclist>0 ){
+ rc = fts3GrowSegReaderBuffer(pCsr, nDoclist+FTS3_NODE_PADDING);
+ if( rc ) return rc;
+ memset(&pCsr->aBuffer[nDoclist], 0, FTS3_NODE_PADDING);
+ pCsr->aDoclist = pCsr->aBuffer;
+ pCsr->nDoclist = nDoclist;
+ rc = SQLITE_ROW;
+ }
+ }
+ pCsr->nAdvance = nMerge;
+ }while( rc==SQLITE_OK );
+
+ return rc;
+}
+
+
+SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
+ Fts3MultiSegReader *pCsr /* Cursor object */
+){
+ if( pCsr ){
+ int i;
+ for(i=0; i<pCsr->nSegment; i++){
+ sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
+ }
+ sqlite3_free(pCsr->apSegment);
+ sqlite3_free(pCsr->aBuffer);
+
+ pCsr->nSegment = 0;
+ pCsr->apSegment = 0;
+ pCsr->aBuffer = 0;
+ }
+}
+
+/*
+** Decode the "end_block" field, selected by column iCol of the SELECT
+** statement passed as the first argument.
+**
+** The "end_block" field may contain either an integer, or a text field
+** containing the text representation of two non-negative integers separated
+** by one or more space (0x20) characters. In the first case, set *piEndBlock
+** to the integer value and *pnByte to zero before returning. In the second,
+** set *piEndBlock to the first value and *pnByte to the second.
+*/
+static void fts3ReadEndBlockField(
+ sqlite3_stmt *pStmt,
+ int iCol,
+ i64 *piEndBlock,
+ i64 *pnByte
+){
+ const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
+ if( zText ){
+ int i;
+ int iMul = 1;
+ u64 iVal = 0;
+ for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
+ iVal = iVal*10 + (zText[i] - '0');
+ }
+ *piEndBlock = (i64)iVal;
+ while( zText[i]==' ' ) i++;
+ iVal = 0;
+ if( zText[i]=='-' ){
+ i++;
+ iMul = -1;
+ }
+ for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
+ iVal = iVal*10 + (zText[i] - '0');
+ }
+ *pnByte = ((i64)iVal * (i64)iMul);
+ }
+}
+
+
+/*
+** A segment of size nByte bytes has just been written to absolute level
+** iAbsLevel. Promote any segments that should be promoted as a result.
+*/
+static int fts3PromoteSegments(
+ Fts3Table *p, /* FTS table handle */
+ sqlite3_int64 iAbsLevel, /* Absolute level just updated */
+ sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
+){
+ int rc = SQLITE_OK;
+ sqlite3_stmt *pRange;
+
+ rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
+
+ if( rc==SQLITE_OK ){
+ int bOk = 0;
+ i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
+ i64 nLimit = (nByte*3)/2;
+
+ /* Loop through all entries in the %_segdir table corresponding to
+ ** segments in this index on levels greater than iAbsLevel. If there is
+ ** at least one such segment, and it is possible to determine that all
+ ** such segments are smaller than nLimit bytes in size, they will be
+ ** promoted to level iAbsLevel. */
+ sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
+ sqlite3_bind_int64(pRange, 2, iLast);
+ while( SQLITE_ROW==sqlite3_step(pRange) ){
+ i64 nSize = 0, dummy;
+ fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
+ if( nSize<=0 || nSize>nLimit ){
+ /* If nSize==0, then the %_segdir.end_block field does not not
+ ** contain a size value. This happens if it was written by an
+ ** old version of FTS. In this case it is not possible to determine
+ ** the size of the segment, and so segment promotion does not
+ ** take place. */
+ bOk = 0;
+ break;
+ }
+ bOk = 1;
+ }
+ rc = sqlite3_reset(pRange);
+
+ if( bOk ){
+ int iIdx = 0;
+ sqlite3_stmt *pUpdate1 = 0;
+ sqlite3_stmt *pUpdate2 = 0;
+
+ if( rc==SQLITE_OK ){
+ rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
+ }
+ if( rc==SQLITE_OK ){
+ rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
+ }
+
+ if( rc==SQLITE_OK ){
+
+ /* Loop through all %_segdir entries for segments in this index with
+ ** levels equal to or greater than iAbsLevel. As each entry is visited,
+ ** updated it to set (level = -1) and (idx = N), where N is 0 for the
+ ** oldest segment in the range, 1 for the next oldest, and so on.
+ **
+ ** In other words, move all segments being promoted to level -1,
+ ** setting the "idx" fields as appropriate to keep them in the same
+ ** order. The contents of level -1 (which is never used, except
+ ** transiently here), will be moved back to level iAbsLevel below. */
+ sqlite3_bind_int64(pRange, 1, iAbsLevel);
+ while( SQLITE_ROW==sqlite3_step(pRange) ){
+ sqlite3_bind_int(pUpdate1, 1, iIdx++);
+ sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
+ sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
+ sqlite3_step(pUpdate1);
+ rc = sqlite3_reset(pUpdate1);
+ if( rc!=SQLITE_OK ){
+ sqlite3_reset(pRange);
+ break;
+ }
+ }
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_reset(pRange);
+ }
+
+ /* Move level -1 to level iAbsLevel */
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
+ sqlite3_step(pUpdate2);
+ rc = sqlite3_reset(pUpdate2);
+ }
+ }
+ }
+
+
+ return rc;
+}
+
+/*
+** Merge all level iLevel segments in the database into a single
+** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
+** single segment with a level equal to the numerically largest level
+** currently present in the database.
+**
+** If this function is called with iLevel<0, but there is only one
+** segment in the database, SQLITE_DONE is returned immediately.
+** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
+** an SQLite error code is returned.
+*/
+static int fts3SegmentMerge(
+ Fts3Table *p,
+ int iLangid, /* Language id to merge */
+ int iIndex, /* Index in p->aIndex[] to merge */
+ int iLevel /* Level to merge */
+){
+ int rc; /* Return code */
+ int iIdx = 0; /* Index of new segment */
+ sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
+ SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
+ Fts3SegFilter filter; /* Segment term filter condition */
+ Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
+ int bIgnoreEmpty = 0; /* True to ignore empty segments */
+ i64 iMaxLevel = 0; /* Max level number for this index/langid */
+
+ assert( iLevel==FTS3_SEGCURSOR_ALL
+ || iLevel==FTS3_SEGCURSOR_PENDING
+ || iLevel>=0
+ );
+ assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
+ assert( iIndex>=0 && iIndex<p->nIndex );
+
+ rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
+ if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
+
+ if( iLevel!=FTS3_SEGCURSOR_PENDING ){
+ rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
+ if( rc!=SQLITE_OK ) goto finished;
+ }
+
+ if( iLevel==FTS3_SEGCURSOR_ALL ){
+ /* This call is to merge all segments in the database to a single
+ ** segment. The level of the new segment is equal to the numerically
+ ** greatest segment level currently present in the database for this
+ ** index. The idx of the new segment is always 0. */
+ if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
+ rc = SQLITE_DONE;
+ goto finished;
+ }
+ iNewLevel = iMaxLevel;
+ bIgnoreEmpty = 1;
+
+ }else{
+ /* This call is to merge all segments at level iLevel. find the next
+ ** available segment index at level iLevel+1. The call to
+ ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
+ ** a single iLevel+2 segment if necessary. */
+ assert( FTS3_SEGCURSOR_PENDING==-1 );
+ iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
+ rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
+ bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
+ }
+ if( rc!=SQLITE_OK ) goto finished;
+
+ assert( csr.nSegment>0 );
+ assert_fts3_nc( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
+ assert_fts3_nc(
+ iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL)
+ );
+
+ memset(&filter, 0, sizeof(Fts3SegFilter));
+ filter.flags = FTS3_SEGMENT_REQUIRE_POS;
+ filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
+
+ rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
+ while( SQLITE_OK==rc ){
+ rc = sqlite3Fts3SegReaderStep(p, &csr);
+ if( rc!=SQLITE_ROW ) break;
+ rc = fts3SegWriterAdd(p, &pWriter, 1,
+ csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
+ }
+ if( rc!=SQLITE_OK ) goto finished;
+ assert_fts3_nc( pWriter || bIgnoreEmpty );
+
+ if( iLevel!=FTS3_SEGCURSOR_PENDING ){
+ rc = fts3DeleteSegdir(
+ p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
+ );
+ if( rc!=SQLITE_OK ) goto finished;
+ }
+ if( pWriter ){
+ rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
+ if( rc==SQLITE_OK ){
+ if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
+ rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
+ }
+ }
+ }
+
+ finished:
+ fts3SegWriterFree(pWriter);
+ sqlite3Fts3SegReaderFinish(&csr);
+ return rc;
+}
+
+
+/*
+** Flush the contents of pendingTerms to level 0 segments.
+*/
+SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
+ int rc = SQLITE_OK;
+ int i;
+
+ for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
+ rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
+ if( rc==SQLITE_DONE ) rc = SQLITE_OK;
+ }
+ sqlite3Fts3PendingTermsClear(p);
+
+ /* Determine the auto-incr-merge setting if unknown. If enabled,
+ ** estimate the number of leaf blocks of content to be written
+ */
+ if( rc==SQLITE_OK && p->bHasStat
+ && p->nAutoincrmerge==0xff && p->nLeafAdd>0
+ ){
+ sqlite3_stmt *pStmt = 0;
+ rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
+ rc = sqlite3_step(pStmt);
+ if( rc==SQLITE_ROW ){
+ p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
+ if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
+ }else if( rc==SQLITE_DONE ){
+ p->nAutoincrmerge = 0;
+ }
+ rc = sqlite3_reset(pStmt);
+ }
+ }
+ return rc;
+}
+
+/*
+** Encode N integers as varints into a blob.
+*/
+static void fts3EncodeIntArray(
+ int N, /* The number of integers to encode */
+ u32 *a, /* The integer values */
+ char *zBuf, /* Write the BLOB here */
+ int *pNBuf /* Write number of bytes if zBuf[] used here */
+){
+ int i, j;
+ for(i=j=0; i<N; i++){
+ j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
+ }
+ *pNBuf = j;
+}
+
+/*
+** Decode a blob of varints into N integers
+*/
+static void fts3DecodeIntArray(
+ int N, /* The number of integers to decode */
+ u32 *a, /* Write the integer values */
+ const char *zBuf, /* The BLOB containing the varints */
+ int nBuf /* size of the BLOB */
+){
+ int i = 0;
+ if( nBuf && (zBuf[nBuf-1]&0x80)==0 ){
+ int j;
+ for(i=j=0; i<N && j<nBuf; i++){
+ sqlite3_int64 x;
+ j += sqlite3Fts3GetVarint(&zBuf[j], &x);
+ a[i] = (u32)(x & 0xffffffff);
+ }
+ }
+ while( i<N ) a[i++] = 0;
+}
+
+/*
+** Insert the sizes (in tokens) for each column of the document
+** with docid equal to p->iPrevDocid. The sizes are encoded as
+** a blob of varints.
+*/
+static void fts3InsertDocsize(
+ int *pRC, /* Result code */
+ Fts3Table *p, /* Table into which to insert */
+ u32 *aSz /* Sizes of each column, in tokens */
+){
+ char *pBlob; /* The BLOB encoding of the document size */
+ int nBlob; /* Number of bytes in the BLOB */
+ sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
+ int rc; /* Result code from subfunctions */
+
+ if( *pRC ) return;
+ pBlob = sqlite3_malloc64( 10*(sqlite3_int64)p->nColumn );
+ if( pBlob==0 ){
+ *pRC = SQLITE_NOMEM;
+ return;
+ }
+ fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
+ rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
+ if( rc ){
+ sqlite3_free(pBlob);
+ *pRC = rc;
+ return;
+ }
+ sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
+ sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
+ sqlite3_step(pStmt);
+ *pRC = sqlite3_reset(pStmt);
+}
+
+/*
+** Record 0 of the %_stat table contains a blob consisting of N varints,
+** where N is the number of user defined columns in the fts3 table plus
+** two. If nCol is the number of user defined columns, then values of the
+** varints are set as follows:
+**
+** Varint 0: Total number of rows in the table.
+**
+** Varint 1..nCol: For each column, the total number of tokens stored in
+** the column for all rows of the table.
+**
+** Varint 1+nCol: The total size, in bytes, of all text values in all
+** columns of all rows of the table.
+**
+*/
+static void fts3UpdateDocTotals(
+ int *pRC, /* The result code */
+ Fts3Table *p, /* Table being updated */
+ u32 *aSzIns, /* Size increases */
+ u32 *aSzDel, /* Size decreases */
+ int nChng /* Change in the number of documents */
+){
+ char *pBlob; /* Storage for BLOB written into %_stat */
+ int nBlob; /* Size of BLOB written into %_stat */
+ u32 *a; /* Array of integers that becomes the BLOB */
+ sqlite3_stmt *pStmt; /* Statement for reading and writing */
+ int i; /* Loop counter */
+ int rc; /* Result code from subfunctions */
+
+ const int nStat = p->nColumn+2;
+
+ if( *pRC ) return;
+ a = sqlite3_malloc64( (sizeof(u32)+10)*(sqlite3_int64)nStat );
+ if( a==0 ){
+ *pRC = SQLITE_NOMEM;
+ return;
+ }
+ pBlob = (char*)&a[nStat];
+ rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
+ if( rc ){
+ sqlite3_free(a);
+ *pRC = rc;
+ return;
+ }
+ sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
+ if( sqlite3_step(pStmt)==SQLITE_ROW ){
+ fts3DecodeIntArray(nStat, a,
+ sqlite3_column_blob(pStmt, 0),
+ sqlite3_column_bytes(pStmt, 0));
+ }else{
+ memset(a, 0, sizeof(u32)*(nStat) );
+ }
+ rc = sqlite3_reset(pStmt);
+ if( rc!=SQLITE_OK ){
+ sqlite3_free(a);
+ *pRC = rc;
+ return;
+ }
+ if( nChng<0 && a[0]<(u32)(-nChng) ){
+ a[0] = 0;
+ }else{
+ a[0] += nChng;
+ }
+ for(i=0; i<p->nColumn+1; i++){
+ u32 x = a[i+1];
+ if( x+aSzIns[i] < aSzDel[i] ){
+ x = 0;
+ }else{
+ x = x + aSzIns[i] - aSzDel[i];
+ }
+ a[i+1] = x;
+ }
+ fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
+ rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
+ if( rc ){
+ sqlite3_free(a);
+ *pRC = rc;
+ return;
+ }
+ sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
+ sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
+ sqlite3_step(pStmt);
+ *pRC = sqlite3_reset(pStmt);
+ sqlite3_bind_null(pStmt, 2);
+ sqlite3_free(a);
+}
+
+/*
+** Merge the entire database so that there is one segment for each
+** iIndex/iLangid combination.
+*/
+static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
+ int bSeenDone = 0;
+ int rc;
+ sqlite3_stmt *pAllLangid = 0;
+
+ rc = sqlite3Fts3PendingTermsFlush(p);
+ if( rc==SQLITE_OK ){
+ rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
+ }
+ if( rc==SQLITE_OK ){
+ int rc2;
+ sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
+ sqlite3_bind_int(pAllLangid, 2, p->nIndex);
+ while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
+ int i;
+ int iLangid = sqlite3_column_int(pAllLangid, 0);
+ for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
+ rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
+ if( rc==SQLITE_DONE ){
+ bSeenDone = 1;
+ rc = SQLITE_OK;
+ }
+ }
+ }
+ rc2 = sqlite3_reset(pAllLangid);
+ if( rc==SQLITE_OK ) rc = rc2;
+ }
+
+ sqlite3Fts3SegmentsClose(p);
+
+ return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
+}
+
+/*
+** This function is called when the user executes the following statement:
+**
+** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
+**
+** The entire FTS index is discarded and rebuilt. If the table is one
+** created using the content=xxx option, then the new index is based on
+** the current contents of the xxx table. Otherwise, it is rebuilt based
+** on the contents of the %_content table.
+*/
+static int fts3DoRebuild(Fts3Table *p){
+ int rc; /* Return Code */
+
+ rc = fts3DeleteAll(p, 0);
+ if( rc==SQLITE_OK ){
+ u32 *aSz = 0;
+ u32 *aSzIns = 0;
+ u32 *aSzDel = 0;
+ sqlite3_stmt *pStmt = 0;
+ int nEntry = 0;
+
+ /* Compose and prepare an SQL statement to loop through the content table */
+ char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
+ if( !zSql ){
+ rc = SQLITE_NOMEM;
+ }else{
+ rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
+ sqlite3_free(zSql);
+ }
+
+ if( rc==SQLITE_OK ){
+ sqlite3_int64 nByte = sizeof(u32) * ((sqlite3_int64)p->nColumn+1)*3;
+ aSz = (u32 *)sqlite3_malloc64(nByte);
+ if( aSz==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memset(aSz, 0, nByte);
+ aSzIns = &aSz[p->nColumn+1];
+ aSzDel = &aSzIns[p->nColumn+1];
+ }
+ }
+
+ while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
+ int iCol;
+ int iLangid = langidFromSelect(p, pStmt);
+ rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
+ memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
+ for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
+ if( p->abNotindexed[iCol]==0 ){
+ const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
+ rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
+ aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
+ }
+ }
+ if( p->bHasDocsize ){
+ fts3InsertDocsize(&rc, p, aSz);
+ }
+ if( rc!=SQLITE_OK ){
+ sqlite3_finalize(pStmt);
+ pStmt = 0;
+ }else{
+ nEntry++;
+ for(iCol=0; iCol<=p->nColumn; iCol++){
+ aSzIns[iCol] += aSz[iCol];
+ }
+ }
+ }
+ if( p->bFts4 ){
+ fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
+ }
+ sqlite3_free(aSz);
+
+ if( pStmt ){
+ int rc2 = sqlite3_finalize(pStmt);
+ if( rc==SQLITE_OK ){
+ rc = rc2;
+ }
+ }
+ }
+
+ return rc;
+}
+
+
+/*
+** This function opens a cursor used to read the input data for an
+** incremental merge operation. Specifically, it opens a cursor to scan
+** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
+** level iAbsLevel.
+*/
+static int fts3IncrmergeCsr(
+ Fts3Table *p, /* FTS3 table handle */
+ sqlite3_int64 iAbsLevel, /* Absolute level to open */
+ int nSeg, /* Number of segments to merge */
+ Fts3MultiSegReader *pCsr /* Cursor object to populate */
+){
+ int rc; /* Return Code */
+ sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
+ sqlite3_int64 nByte; /* Bytes allocated at pCsr->apSegment[] */
+
+ /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
+ memset(pCsr, 0, sizeof(*pCsr));
+ nByte = sizeof(Fts3SegReader *) * nSeg;
+ pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc64(nByte);
+
+ if( pCsr->apSegment==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memset(pCsr->apSegment, 0, nByte);
+ rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
+ }
+ if( rc==SQLITE_OK ){
+ int i;
+ int rc2;
+ sqlite3_bind_int64(pStmt, 1, iAbsLevel);
+ assert( pCsr->nSegment==0 );
+ for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
+ rc = sqlite3Fts3SegReaderNew(i, 0,
+ sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
+ sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
+ sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
+ sqlite3_column_blob(pStmt, 4), /* segdir.root */
+ sqlite3_column_bytes(pStmt, 4), /* segdir.root */
+ &pCsr->apSegment[i]
+ );
+ pCsr->nSegment++;
+ }
+ rc2 = sqlite3_reset(pStmt);
+ if( rc==SQLITE_OK ) rc = rc2;
+ }
+
+ return rc;
+}
+
+typedef struct IncrmergeWriter IncrmergeWriter;
+typedef struct NodeWriter NodeWriter;
+typedef struct Blob Blob;
+typedef struct NodeReader NodeReader;
+
+/*
+** An instance of the following structure is used as a dynamic buffer
+** to build up nodes or other blobs of data in.
+**
+** The function blobGrowBuffer() is used to extend the allocation.
+*/
+struct Blob {
+ char *a; /* Pointer to allocation */
+ int n; /* Number of valid bytes of data in a[] */
+ int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
+};
+
+/*
+** This structure is used to build up buffers containing segment b-tree
+** nodes (blocks).
+*/
+struct NodeWriter {
+ sqlite3_int64 iBlock; /* Current block id */
+ Blob key; /* Last key written to the current block */
+ Blob block; /* Current block image */
+};
+
+/*
+** An object of this type contains the state required to create or append
+** to an appendable b-tree segment.
+*/
+struct IncrmergeWriter {
+ int nLeafEst; /* Space allocated for leaf blocks */
+ int nWork; /* Number of leaf pages flushed */
+ sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
+ int iIdx; /* Index of *output* segment in iAbsLevel+1 */
+ sqlite3_int64 iStart; /* Block number of first allocated block */
+ sqlite3_int64 iEnd; /* Block number of last allocated block */
+ sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
+ u8 bNoLeafData; /* If true, store 0 for segment size */
+ NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
+};
+
+/*
+** An object of the following type is used to read data from a single
+** FTS segment node. See the following functions:
+**
+** nodeReaderInit()
+** nodeReaderNext()
+** nodeReaderRelease()
+*/
+struct NodeReader {
+ const char *aNode;
+ int nNode;
+ int iOff; /* Current offset within aNode[] */
+
+ /* Output variables. Containing the current node entry. */
+ sqlite3_int64 iChild; /* Pointer to child node */
+ Blob term; /* Current term */
+ const char *aDoclist; /* Pointer to doclist */
+ int nDoclist; /* Size of doclist in bytes */
+};
+
+/*
+** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
+** Otherwise, if the allocation at pBlob->a is not already at least nMin
+** bytes in size, extend (realloc) it to be so.
+**
+** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
+** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
+** to reflect the new size of the pBlob->a[] buffer.
+*/
+static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
+ if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
+ int nAlloc = nMin;
+ char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
+ if( a ){
+ pBlob->nAlloc = nAlloc;
+ pBlob->a = a;
+ }else{
+ *pRc = SQLITE_NOMEM;
+ }
+ }
+}
+
+/*
+** Attempt to advance the node-reader object passed as the first argument to
+** the next entry on the node.
+**
+** Return an error code if an error occurs (SQLITE_NOMEM is possible).
+** Otherwise return SQLITE_OK. If there is no next entry on the node
+** (e.g. because the current entry is the last) set NodeReader->aNode to
+** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
+** variables for the new entry.
+*/
+static int nodeReaderNext(NodeReader *p){
+ int bFirst = (p->term.n==0); /* True for first term on the node */
+ int nPrefix = 0; /* Bytes to copy from previous term */
+ int nSuffix = 0; /* Bytes to append to the prefix */
+ int rc = SQLITE_OK; /* Return code */
+
+ assert( p->aNode );
+ if( p->iChild && bFirst==0 ) p->iChild++;
+ if( p->iOff>=p->nNode ){
+ /* EOF */
+ p->aNode = 0;
+ }else{
+ if( bFirst==0 ){
+ p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
+ }
+ p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
+
+ if( nPrefix>p->term.n || nSuffix>p->nNode-p->iOff || nSuffix==0 ){
+ return FTS_CORRUPT_VTAB;
+ }
+ blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
+ if( rc==SQLITE_OK ){
+ memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
+ p->term.n = nPrefix+nSuffix;
+ p->iOff += nSuffix;
+ if( p->iChild==0 ){
+ p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
+ if( (p->nNode-p->iOff)<p->nDoclist ){
+ return FTS_CORRUPT_VTAB;
+ }
+ p->aDoclist = &p->aNode[p->iOff];
+ p->iOff += p->nDoclist;
+ }
+ }
+ }
+
+ assert_fts3_nc( p->iOff<=p->nNode );
+ return rc;
+}
+
+/*
+** Release all dynamic resources held by node-reader object *p.
+*/
+static void nodeReaderRelease(NodeReader *p){
+ sqlite3_free(p->term.a);
+}
+
+/*
+** Initialize a node-reader object to read the node in buffer aNode/nNode.
+**
+** If successful, SQLITE_OK is returned and the NodeReader object set to
+** point to the first entry on the node (if any). Otherwise, an SQLite
+** error code is returned.
+*/
+static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
+ memset(p, 0, sizeof(NodeReader));
+ p->aNode = aNode;
+ p->nNode = nNode;
+
+ /* Figure out if this is a leaf or an internal node. */
+ if( aNode && aNode[0] ){
+ /* An internal node. */
+ p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
+ }else{
+ p->iOff = 1;
+ }
+
+ return aNode ? nodeReaderNext(p) : SQLITE_OK;
+}
+
+/*
+** This function is called while writing an FTS segment each time a leaf o
+** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
+** to be greater than the largest key on the node just written, but smaller
+** than or equal to the first key that will be written to the next leaf
+** node.
+**
+** The block id of the leaf node just written to disk may be found in
+** (pWriter->aNodeWriter[0].iBlock) when this function is called.
+*/
+static int fts3IncrmergePush(
+ Fts3Table *p, /* Fts3 table handle */
+ IncrmergeWriter *pWriter, /* Writer object */
+ const char *zTerm, /* Term to write to internal node */
+ int nTerm /* Bytes at zTerm */
+){
+ sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
+ int iLayer;
+
+ assert( nTerm>0 );
+ for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
+ sqlite3_int64 iNextPtr = 0;
+ NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
+ int rc = SQLITE_OK;
+ int nPrefix;
+ int nSuffix;
+ int nSpace;
+
+ /* Figure out how much space the key will consume if it is written to
+ ** the current node of layer iLayer. Due to the prefix compression,
+ ** the space required changes depending on which node the key is to
+ ** be added to. */
+ nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
+ nSuffix = nTerm - nPrefix;
+ if(nSuffix<=0 ) return FTS_CORRUPT_VTAB;
+ nSpace = sqlite3Fts3VarintLen(nPrefix);
+ nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
+
+ if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
+ /* If the current node of layer iLayer contains zero keys, or if adding
+ ** the key to it will not cause it to grow to larger than nNodeSize
+ ** bytes in size, write the key here. */
+
+ Blob *pBlk = &pNode->block;
+ if( pBlk->n==0 ){
+ blobGrowBuffer(pBlk, p->nNodeSize, &rc);
+ if( rc==SQLITE_OK ){
+ pBlk->a[0] = (char)iLayer;
+ pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
+ }
+ }
+ blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
+ blobGrowBuffer(&pNode->key, nTerm, &rc);
+
+ if( rc==SQLITE_OK ){
+ if( pNode->key.n ){
+ pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
+ }
+ pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
+ memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
+ pBlk->n += nSuffix;
+
+ memcpy(pNode->key.a, zTerm, nTerm);
+ pNode->key.n = nTerm;
+ }
+ }else{
+ /* Otherwise, flush the current node of layer iLayer to disk.
+ ** Then allocate a new, empty sibling node. The key will be written
+ ** into the parent of this node. */
+ rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
+
+ assert( pNode->block.nAlloc>=p->nNodeSize );
+ pNode->block.a[0] = (char)iLayer;
+ pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
+
+ iNextPtr = pNode->iBlock;
+ pNode->iBlock++;
+ pNode->key.n = 0;
+ }
+
+ if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
+ iPtr = iNextPtr;
+ }
+
+ assert( 0 );
+ return 0;
+}
+
+/*
+** Append a term and (optionally) doclist to the FTS segment node currently
+** stored in blob *pNode. The node need not contain any terms, but the
+** header must be written before this function is called.
+**
+** A node header is a single 0x00 byte for a leaf node, or a height varint
+** followed by the left-hand-child varint for an internal node.
+**
+** The term to be appended is passed via arguments zTerm/nTerm. For a
+** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
+** node, both aDoclist and nDoclist must be passed 0.
+**
+** If the size of the value in blob pPrev is zero, then this is the first
+** term written to the node. Otherwise, pPrev contains a copy of the
+** previous term. Before this function returns, it is updated to contain a
+** copy of zTerm/nTerm.
+**
+** It is assumed that the buffer associated with pNode is already large
+** enough to accommodate the new entry. The buffer associated with pPrev
+** is extended by this function if requrired.
+**
+** If an error (i.e. OOM condition) occurs, an SQLite error code is
+** returned. Otherwise, SQLITE_OK.
+*/
+static int fts3AppendToNode(
+ Blob *pNode, /* Current node image to append to */
+ Blob *pPrev, /* Buffer containing previous term written */
+ const char *zTerm, /* New term to write */
+ int nTerm, /* Size of zTerm in bytes */
+ const char *aDoclist, /* Doclist (or NULL) to write */
+ int nDoclist /* Size of aDoclist in bytes */
+){
+ int rc = SQLITE_OK; /* Return code */
+ int bFirst = (pPrev->n==0); /* True if this is the first term written */
+ int nPrefix; /* Size of term prefix in bytes */
+ int nSuffix; /* Size of term suffix in bytes */
+
+ /* Node must have already been started. There must be a doclist for a
+ ** leaf node, and there must not be a doclist for an internal node. */
+ assert( pNode->n>0 );
+ assert_fts3_nc( (pNode->a[0]=='\0')==(aDoclist!=0) );
+
+ blobGrowBuffer(pPrev, nTerm, &rc);
+ if( rc!=SQLITE_OK ) return rc;
+
+ nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
+ nSuffix = nTerm - nPrefix;
+ if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
+ memcpy(pPrev->a, zTerm, nTerm);
+ pPrev->n = nTerm;
+
+ if( bFirst==0 ){
+ pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
+ }
+ pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
+ memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
+ pNode->n += nSuffix;
+
+ if( aDoclist ){
+ pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
+ memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
+ pNode->n += nDoclist;
+ }
+
+ assert( pNode->n<=pNode->nAlloc );
+
+ return SQLITE_OK;
+}
+
+/*
+** Append the current term and doclist pointed to by cursor pCsr to the
+** appendable b-tree segment opened for writing by pWriter.
+**
+** Return SQLITE_OK if successful, or an SQLite error code otherwise.
+*/
+static int fts3IncrmergeAppend(
+ Fts3Table *p, /* Fts3 table handle */
+ IncrmergeWriter *pWriter, /* Writer object */
+ Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
+){
+ const char *zTerm = pCsr->zTerm;
+ int nTerm = pCsr->nTerm;
+ const char *aDoclist = pCsr->aDoclist;
+ int nDoclist = pCsr->nDoclist;
+ int rc = SQLITE_OK; /* Return code */
+ int nSpace; /* Total space in bytes required on leaf */
+ int nPrefix; /* Size of prefix shared with previous term */
+ int nSuffix; /* Size of suffix (nTerm - nPrefix) */
+ NodeWriter *pLeaf; /* Object used to write leaf nodes */
+
+ pLeaf = &pWriter->aNodeWriter[0];
+ nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
+ nSuffix = nTerm - nPrefix;
+
+ nSpace = sqlite3Fts3VarintLen(nPrefix);
+ nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
+ nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
+
+ /* If the current block is not empty, and if adding this term/doclist
+ ** to the current block would make it larger than Fts3Table.nNodeSize
+ ** bytes, write this block out to the database. */
+ if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
+ rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
+ pWriter->nWork++;
+
+ /* Add the current term to the parent node. The term added to the
+ ** parent must:
+ **
+ ** a) be greater than the largest term on the leaf node just written
+ ** to the database (still available in pLeaf->key), and
+ **
+ ** b) be less than or equal to the term about to be added to the new
+ ** leaf node (zTerm/nTerm).
+ **
+ ** In other words, it must be the prefix of zTerm 1 byte longer than
+ ** the common prefix (if any) of zTerm and pWriter->zTerm.
+ */
+ if( rc==SQLITE_OK ){
+ rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
+ }
+
+ /* Advance to the next output block */
+ pLeaf->iBlock++;
+ pLeaf->key.n = 0;
+ pLeaf->block.n = 0;
+
+ nSuffix = nTerm;
+ nSpace = 1;
+ nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
+ nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
+ }
+
+ pWriter->nLeafData += nSpace;
+ blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
+ if( rc==SQLITE_OK ){
+ if( pLeaf->block.n==0 ){
+ pLeaf->block.n = 1;
+ pLeaf->block.a[0] = '\0';
+ }
+ rc = fts3AppendToNode(
+ &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
+ );
+ }
+
+ return rc;
+}
+
+/*
+** This function is called to release all dynamic resources held by the
+** merge-writer object pWriter, and if no error has occurred, to flush
+** all outstanding node buffers held by pWriter to disk.
+**
+** If *pRc is not SQLITE_OK when this function is called, then no attempt
+** is made to write any data to disk. Instead, this function serves only
+** to release outstanding resources.
+**
+** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
+** flushing buffers to disk, *pRc is set to an SQLite error code before
+** returning.
+*/
+static void fts3IncrmergeRelease(
+ Fts3Table *p, /* FTS3 table handle */
+ IncrmergeWriter *pWriter, /* Merge-writer object */
+ int *pRc /* IN/OUT: Error code */
+){
+ int i; /* Used to iterate through non-root layers */
+ int iRoot; /* Index of root in pWriter->aNodeWriter */
+ NodeWriter *pRoot; /* NodeWriter for root node */
+ int rc = *pRc; /* Error code */
+
+ /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
+ ** root node. If the segment fits entirely on a single leaf node, iRoot
+ ** will be set to 0. If the root node is the parent of the leaves, iRoot
+ ** will be 1. And so on. */
+ for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
+ NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
+ if( pNode->block.n>0 ) break;
+ assert( *pRc || pNode->block.nAlloc==0 );
+ assert( *pRc || pNode->key.nAlloc==0 );
+ sqlite3_free(pNode->block.a);
+ sqlite3_free(pNode->key.a);
+ }
+
+ /* Empty output segment. This is a no-op. */
+ if( iRoot<0 ) return;
+
+ /* The entire output segment fits on a single node. Normally, this means
+ ** the node would be stored as a blob in the "root" column of the %_segdir
+ ** table. However, this is not permitted in this case. The problem is that
+ ** space has already been reserved in the %_segments table, and so the
+ ** start_block and end_block fields of the %_segdir table must be populated.
+ ** And, by design or by accident, released versions of FTS cannot handle
+ ** segments that fit entirely on the root node with start_block!=0.
+ **
+ ** Instead, create a synthetic root node that contains nothing but a
+ ** pointer to the single content node. So that the segment consists of a
+ ** single leaf and a single interior (root) node.
+ **
+ ** Todo: Better might be to defer allocating space in the %_segments
+ ** table until we are sure it is needed.
+ */
+ if( iRoot==0 ){
+ Blob *pBlock = &pWriter->aNodeWriter[1].block;
+ blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
+ if( rc==SQLITE_OK ){
+ pBlock->a[0] = 0x01;
+ pBlock->n = 1 + sqlite3Fts3PutVarint(
+ &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
+ );
+ }
+ iRoot = 1;
+ }
+ pRoot = &pWriter->aNodeWriter[iRoot];
+
+ /* Flush all currently outstanding nodes to disk. */
+ for(i=0; i<iRoot; i++){
+ NodeWriter *pNode = &pWriter->aNodeWriter[i];
+ if( pNode->block.n>0 && rc==SQLITE_OK ){
+ rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
+ }
+ sqlite3_free(pNode->block.a);
+ sqlite3_free(pNode->key.a);
+ }
+
+ /* Write the %_segdir record. */
+ if( rc==SQLITE_OK ){
+ rc = fts3WriteSegdir(p,
+ pWriter->iAbsLevel+1, /* level */
+ pWriter->iIdx, /* idx */
+ pWriter->iStart, /* start_block */
+ pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
+ pWriter->iEnd, /* end_block */
+ (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
+ pRoot->block.a, pRoot->block.n /* root */
+ );
+ }
+ sqlite3_free(pRoot->block.a);
+ sqlite3_free(pRoot->key.a);
+
+ *pRc = rc;
+}
+
+/*
+** Compare the term in buffer zLhs (size in bytes nLhs) with that in
+** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
+** the other, it is considered to be smaller than the other.
+**
+** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
+** if it is greater.
+*/
+static int fts3TermCmp(
+ const char *zLhs, int nLhs, /* LHS of comparison */
+ const char *zRhs, int nRhs /* RHS of comparison */
+){
+ int nCmp = MIN(nLhs, nRhs);
+ int res;
+
+ res = (nCmp ? memcmp(zLhs, zRhs, nCmp) : 0);
+ if( res==0 ) res = nLhs - nRhs;
+
+ return res;
+}
+
+
+/*
+** Query to see if the entry in the %_segments table with blockid iEnd is
+** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
+** returning. Otherwise, set *pbRes to 0.
+**
+** Or, if an error occurs while querying the database, return an SQLite
+** error code. The final value of *pbRes is undefined in this case.
+**
+** This is used to test if a segment is an "appendable" segment. If it
+** is, then a NULL entry has been inserted into the %_segments table
+** with blockid %_segdir.end_block.
+*/
+static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
+ int bRes = 0; /* Result to set *pbRes to */
+ sqlite3_stmt *pCheck = 0; /* Statement to query database with */
+ int rc; /* Return code */
+
+ rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pCheck, 1, iEnd);
+ if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
+ rc = sqlite3_reset(pCheck);
+ }
+
+ *pbRes = bRes;
+ return rc;
+}
+
+/*
+** This function is called when initializing an incremental-merge operation.
+** It checks if the existing segment with index value iIdx at absolute level
+** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
+** merge-writer object *pWriter is initialized to write to it.
+**
+** An existing segment can be appended to by an incremental merge if:
+**
+** * It was initially created as an appendable segment (with all required
+** space pre-allocated), and
+**
+** * The first key read from the input (arguments zKey and nKey) is
+** greater than the largest key currently stored in the potential
+** output segment.
+*/
+static int fts3IncrmergeLoad(
+ Fts3Table *p, /* Fts3 table handle */
+ sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
+ int iIdx, /* Index of candidate output segment */
+ const char *zKey, /* First key to write */
+ int nKey, /* Number of bytes in nKey */
+ IncrmergeWriter *pWriter /* Populate this object */
+){
+ int rc; /* Return code */
+ sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
+
+ rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
+ sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
+ sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
+ const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
+ int nRoot = 0; /* Size of aRoot[] in bytes */
+ int rc2; /* Return code from sqlite3_reset() */
+ int bAppendable = 0; /* Set to true if segment is appendable */
+
+ /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
+ sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
+ sqlite3_bind_int(pSelect, 2, iIdx);
+ if( sqlite3_step(pSelect)==SQLITE_ROW ){
+ iStart = sqlite3_column_int64(pSelect, 1);
+ iLeafEnd = sqlite3_column_int64(pSelect, 2);
+ fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
+ if( pWriter->nLeafData<0 ){
+ pWriter->nLeafData = pWriter->nLeafData * -1;
+ }
+ pWriter->bNoLeafData = (pWriter->nLeafData==0);
+ nRoot = sqlite3_column_bytes(pSelect, 4);
+ aRoot = sqlite3_column_blob(pSelect, 4);
+ if( aRoot==0 ){
+ sqlite3_reset(pSelect);
+ return nRoot ? SQLITE_NOMEM : FTS_CORRUPT_VTAB;
+ }
+ }else{
+ return sqlite3_reset(pSelect);
+ }
+
+ /* Check for the zero-length marker in the %_segments table */
+ rc = fts3IsAppendable(p, iEnd, &bAppendable);
+
+ /* Check that zKey/nKey is larger than the largest key the candidate */
+ if( rc==SQLITE_OK && bAppendable ){
+ char *aLeaf = 0;
+ int nLeaf = 0;
+
+ rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
+ if( rc==SQLITE_OK ){
+ NodeReader reader;
+ for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
+ rc==SQLITE_OK && reader.aNode;
+ rc = nodeReaderNext(&reader)
+ ){
+ assert( reader.aNode );
+ }
+ if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
+ bAppendable = 0;
+ }
+ nodeReaderRelease(&reader);
+ }
+ sqlite3_free(aLeaf);
+ }
+
+ if( rc==SQLITE_OK && bAppendable ){
+ /* It is possible to append to this segment. Set up the IncrmergeWriter
+ ** object to do so. */
+ int i;
+ int nHeight = (int)aRoot[0];
+ NodeWriter *pNode;
+ if( nHeight<1 || nHeight>=FTS_MAX_APPENDABLE_HEIGHT ){
+ sqlite3_reset(pSelect);
+ return FTS_CORRUPT_VTAB;
+ }
+
+ pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
+ pWriter->iStart = iStart;
+ pWriter->iEnd = iEnd;
+ pWriter->iAbsLevel = iAbsLevel;
+ pWriter->iIdx = iIdx;
+
+ for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
+ pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
+ }
+
+ pNode = &pWriter->aNodeWriter[nHeight];
+ pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
+ blobGrowBuffer(&pNode->block,
+ MAX(nRoot, p->nNodeSize)+FTS3_NODE_PADDING, &rc
+ );
+ if( rc==SQLITE_OK ){
+ memcpy(pNode->block.a, aRoot, nRoot);
+ pNode->block.n = nRoot;
+ memset(&pNode->block.a[nRoot], 0, FTS3_NODE_PADDING);
+ }
+
+ for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
+ NodeReader reader;
+ pNode = &pWriter->aNodeWriter[i];
+
+ if( pNode->block.a){
+ rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
+ while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
+ blobGrowBuffer(&pNode->key, reader.term.n, &rc);
+ if( rc==SQLITE_OK ){
+ memcpy(pNode->key.a, reader.term.a, reader.term.n);
+ pNode->key.n = reader.term.n;
+ if( i>0 ){
+ char *aBlock = 0;
+ int nBlock = 0;
+ pNode = &pWriter->aNodeWriter[i-1];
+ pNode->iBlock = reader.iChild;
+ rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
+ blobGrowBuffer(&pNode->block,
+ MAX(nBlock, p->nNodeSize)+FTS3_NODE_PADDING, &rc
+ );
+ if( rc==SQLITE_OK ){
+ memcpy(pNode->block.a, aBlock, nBlock);
+ pNode->block.n = nBlock;
+ memset(&pNode->block.a[nBlock], 0, FTS3_NODE_PADDING);
+ }
+ sqlite3_free(aBlock);
+ }
+ }
+ }
+ nodeReaderRelease(&reader);
+ }
+ }
+
+ rc2 = sqlite3_reset(pSelect);
+ if( rc==SQLITE_OK ) rc = rc2;
+ }
+
+ return rc;
+}
+
+/*
+** Determine the largest segment index value that exists within absolute
+** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
+** one before returning SQLITE_OK. Or, if there are no segments at all
+** within level iAbsLevel, set *piIdx to zero.
+**
+** If an error occurs, return an SQLite error code. The final value of
+** *piIdx is undefined in this case.
+*/
+static int fts3IncrmergeOutputIdx(
+ Fts3Table *p, /* FTS Table handle */
+ sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
+ int *piIdx /* OUT: Next free index at iAbsLevel+1 */
+){
+ int rc;
+ sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
+
+ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
+ sqlite3_step(pOutputIdx);
+ *piIdx = sqlite3_column_int(pOutputIdx, 0);
+ rc = sqlite3_reset(pOutputIdx);
+ }
+
+ return rc;
+}
+
+/*
+** Allocate an appendable output segment on absolute level iAbsLevel+1
+** with idx value iIdx.
+**
+** In the %_segdir table, a segment is defined by the values in three
+** columns:
+**
+** start_block
+** leaves_end_block
+** end_block
+**
+** When an appendable segment is allocated, it is estimated that the
+** maximum number of leaf blocks that may be required is the sum of the
+** number of leaf blocks consumed by the input segments, plus the number
+** of input segments, multiplied by two. This value is stored in stack
+** variable nLeafEst.
+**
+** A total of 16*nLeafEst blocks are allocated when an appendable segment
+** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
+** array of leaf nodes starts at the first block allocated. The array
+** of interior nodes that are parents of the leaf nodes start at block
+** (start_block + (1 + end_block - start_block) / 16). And so on.
+**
+** In the actual code below, the value "16" is replaced with the
+** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
+*/
+static int fts3IncrmergeWriter(
+ Fts3Table *p, /* Fts3 table handle */
+ sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
+ int iIdx, /* Index of new output segment */
+ Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
+ IncrmergeWriter *pWriter /* Populate this object */
+){
+ int rc; /* Return Code */
+ int i; /* Iterator variable */
+ int nLeafEst = 0; /* Blocks allocated for leaf nodes */
+ sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
+ sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
+
+ /* Calculate nLeafEst. */
+ rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
+ sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
+ if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
+ nLeafEst = sqlite3_column_int(pLeafEst, 0);
+ }
+ rc = sqlite3_reset(pLeafEst);
+ }
+ if( rc!=SQLITE_OK ) return rc;
+
+ /* Calculate the first block to use in the output segment */
+ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
+ if( rc==SQLITE_OK ){
+ if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
+ pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
+ pWriter->iEnd = pWriter->iStart - 1;
+ pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
+ }
+ rc = sqlite3_reset(pFirstBlock);
+ }
+ if( rc!=SQLITE_OK ) return rc;
+
+ /* Insert the marker in the %_segments table to make sure nobody tries
+ ** to steal the space just allocated. This is also used to identify
+ ** appendable segments. */
+ rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
+ if( rc!=SQLITE_OK ) return rc;
+
+ pWriter->iAbsLevel = iAbsLevel;
+ pWriter->nLeafEst = nLeafEst;
+ pWriter->iIdx = iIdx;
+
+ /* Set up the array of NodeWriter objects */
+ for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
+ pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Remove an entry from the %_segdir table. This involves running the
+** following two statements:
+**
+** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
+** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
+**
+** The DELETE statement removes the specific %_segdir level. The UPDATE
+** statement ensures that the remaining segments have contiguously allocated
+** idx values.
+*/
+static int fts3RemoveSegdirEntry(
+ Fts3Table *p, /* FTS3 table handle */
+ sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
+ int iIdx /* Index of %_segdir entry to delete */
+){
+ int rc; /* Return code */
+ sqlite3_stmt *pDelete = 0; /* DELETE statement */
+
+ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pDelete, 1, iAbsLevel);
+ sqlite3_bind_int(pDelete, 2, iIdx);
+ sqlite3_step(pDelete);
+ rc = sqlite3_reset(pDelete);
+ }
+
+ return rc;
+}
+
+/*
+** One or more segments have just been removed from absolute level iAbsLevel.
+** Update the 'idx' values of the remaining segments in the level so that
+** the idx values are a contiguous sequence starting from 0.
+*/
+static int fts3RepackSegdirLevel(
+ Fts3Table *p, /* FTS3 table handle */
+ sqlite3_int64 iAbsLevel /* Absolute level to repack */
+){
+ int rc; /* Return code */
+ int *aIdx = 0; /* Array of remaining idx values */
+ int nIdx = 0; /* Valid entries in aIdx[] */
+ int nAlloc = 0; /* Allocated size of aIdx[] */
+ int i; /* Iterator variable */
+ sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
+ sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
+
+ rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
+ if( rc==SQLITE_OK ){
+ int rc2;
+ sqlite3_bind_int64(pSelect, 1, iAbsLevel);
+ while( SQLITE_ROW==sqlite3_step(pSelect) ){
+ if( nIdx>=nAlloc ){
+ int *aNew;
+ nAlloc += 16;
+ aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
+ if( !aNew ){
+ rc = SQLITE_NOMEM;
+ break;
+ }
+ aIdx = aNew;
+ }
+ aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
+ }
+ rc2 = sqlite3_reset(pSelect);
+ if( rc==SQLITE_OK ) rc = rc2;
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
+ }
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
+ }
+
+ assert( p->bIgnoreSavepoint==0 );
+ p->bIgnoreSavepoint = 1;
+ for(i=0; rc==SQLITE_OK && i<nIdx; i++){
+ if( aIdx[i]!=i ){
+ sqlite3_bind_int(pUpdate, 3, aIdx[i]);
+ sqlite3_bind_int(pUpdate, 1, i);
+ sqlite3_step(pUpdate);
+ rc = sqlite3_reset(pUpdate);
+ }
+ }
+ p->bIgnoreSavepoint = 0;
+
+ sqlite3_free(aIdx);
+ return rc;
+}
+
+static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
+ pNode->a[0] = (char)iHeight;
+ if( iChild ){
+ assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
+ pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
+ }else{
+ assert( pNode->nAlloc>=1 );
+ pNode->n = 1;
+ }
+}
+
+/*
+** The first two arguments are a pointer to and the size of a segment b-tree
+** node. The node may be a leaf or an internal node.
+**
+** This function creates a new node image in blob object *pNew by copying
+** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
+** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
+*/
+static int fts3TruncateNode(
+ const char *aNode, /* Current node image */
+ int nNode, /* Size of aNode in bytes */
+ Blob *pNew, /* OUT: Write new node image here */
+ const char *zTerm, /* Omit all terms smaller than this */
+ int nTerm, /* Size of zTerm in bytes */
+ sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
+){
+ NodeReader reader; /* Reader object */
+ Blob prev = {0, 0, 0}; /* Previous term written to new node */
+ int rc = SQLITE_OK; /* Return code */
+ int bLeaf; /* True for a leaf node */
+
+ if( nNode<1 ) return FTS_CORRUPT_VTAB;
+ bLeaf = aNode[0]=='\0';
+
+ /* Allocate required output space */
+ blobGrowBuffer(pNew, nNode, &rc);
+ if( rc!=SQLITE_OK ) return rc;
+ pNew->n = 0;
+
+ /* Populate new node buffer */
+ for(rc = nodeReaderInit(&reader, aNode, nNode);
+ rc==SQLITE_OK && reader.aNode;
+ rc = nodeReaderNext(&reader)
+ ){
+ if( pNew->n==0 ){
+ int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
+ if( res<0 || (bLeaf==0 && res==0) ) continue;
+ fts3StartNode(pNew, (int)aNode[0], reader.iChild);
+ *piBlock = reader.iChild;
+ }
+ rc = fts3AppendToNode(
+ pNew, &prev, reader.term.a, reader.term.n,
+ reader.aDoclist, reader.nDoclist
+ );
+ if( rc!=SQLITE_OK ) break;
+ }
+ if( pNew->n==0 ){
+ fts3StartNode(pNew, (int)aNode[0], reader.iChild);
+ *piBlock = reader.iChild;
+ }
+ assert( pNew->n<=pNew->nAlloc );
+
+ nodeReaderRelease(&reader);
+ sqlite3_free(prev.a);
+ return rc;
+}
+
+/*
+** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
+** level iAbsLevel. This may involve deleting entries from the %_segments
+** table, and modifying existing entries in both the %_segments and %_segdir
+** tables.
+**
+** SQLITE_OK is returned if the segment is updated successfully. Or an
+** SQLite error code otherwise.
+*/
+static int fts3TruncateSegment(
+ Fts3Table *p, /* FTS3 table handle */
+ sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
+ int iIdx, /* Index within level of segment to modify */
+ const char *zTerm, /* Remove terms smaller than this */
+ int nTerm /* Number of bytes in buffer zTerm */
+){
+ int rc = SQLITE_OK; /* Return code */
+ Blob root = {0,0,0}; /* New root page image */
+ Blob block = {0,0,0}; /* Buffer used for any other block */
+ sqlite3_int64 iBlock = 0; /* Block id */
+ sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
+ sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
+ sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
+
+ rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
+ if( rc==SQLITE_OK ){
+ int rc2; /* sqlite3_reset() return code */
+ sqlite3_bind_int64(pFetch, 1, iAbsLevel);
+ sqlite3_bind_int(pFetch, 2, iIdx);
+ if( SQLITE_ROW==sqlite3_step(pFetch) ){
+ const char *aRoot = sqlite3_column_blob(pFetch, 4);
+ int nRoot = sqlite3_column_bytes(pFetch, 4);
+ iOldStart = sqlite3_column_int64(pFetch, 1);
+ rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
+ }
+ rc2 = sqlite3_reset(pFetch);
+ if( rc==SQLITE_OK ) rc = rc2;
+ }
+
+ while( rc==SQLITE_OK && iBlock ){
+ char *aBlock = 0;
+ int nBlock = 0;
+ iNewStart = iBlock;
+
+ rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
+ if( rc==SQLITE_OK ){
+ rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
+ }
+ if( rc==SQLITE_OK ){
+ rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
+ }
+ sqlite3_free(aBlock);
+ }
+
+ /* Variable iNewStart now contains the first valid leaf node. */
+ if( rc==SQLITE_OK && iNewStart ){
+ sqlite3_stmt *pDel = 0;
+ rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pDel, 1, iOldStart);
+ sqlite3_bind_int64(pDel, 2, iNewStart-1);
+ sqlite3_step(pDel);
+ rc = sqlite3_reset(pDel);
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ sqlite3_stmt *pChomp = 0;
+ rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pChomp, 1, iNewStart);
+ sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
+ sqlite3_bind_int64(pChomp, 3, iAbsLevel);
+ sqlite3_bind_int(pChomp, 4, iIdx);
+ sqlite3_step(pChomp);
+ rc = sqlite3_reset(pChomp);
+ sqlite3_bind_null(pChomp, 2);
+ }
+ }
+
+ sqlite3_free(root.a);
+ sqlite3_free(block.a);
+ return rc;
+}
+
+/*
+** This function is called after an incrmental-merge operation has run to
+** merge (or partially merge) two or more segments from absolute level
+** iAbsLevel.
+**
+** Each input segment is either removed from the db completely (if all of
+** its data was copied to the output segment by the incrmerge operation)
+** or modified in place so that it no longer contains those entries that
+** have been duplicated in the output segment.
+*/
+static int fts3IncrmergeChomp(
+ Fts3Table *p, /* FTS table handle */
+ sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
+ Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
+ int *pnRem /* Number of segments not deleted */
+){
+ int i;
+ int nRem = 0;
+ int rc = SQLITE_OK;
+
+ for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
+ Fts3SegReader *pSeg = 0;
+ int j;
+
+ /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
+ ** somewhere in the pCsr->apSegment[] array. */
+ for(j=0; ALWAYS(j<pCsr->nSegment); j++){
+ pSeg = pCsr->apSegment[j];
+ if( pSeg->iIdx==i ) break;
+ }
+ assert( j<pCsr->nSegment && pSeg->iIdx==i );
+
+ if( pSeg->aNode==0 ){
+ /* Seg-reader is at EOF. Remove the entire input segment. */
+ rc = fts3DeleteSegment(p, pSeg);
+ if( rc==SQLITE_OK ){
+ rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
+ }
+ *pnRem = 0;
+ }else{
+ /* The incremental merge did not copy all the data from this
+ ** segment to the upper level. The segment is modified in place
+ ** so that it contains no keys smaller than zTerm/nTerm. */
+ const char *zTerm = pSeg->zTerm;
+ int nTerm = pSeg->nTerm;
+ rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
+ nRem++;
+ }
+ }
+
+ if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
+ rc = fts3RepackSegdirLevel(p, iAbsLevel);
+ }
+
+ *pnRem = nRem;
+ return rc;
+}
+
+/*
+** Store an incr-merge hint in the database.
+*/
+static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
+ sqlite3_stmt *pReplace = 0;
+ int rc; /* Return code */
+
+ rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
+ sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
+ sqlite3_step(pReplace);
+ rc = sqlite3_reset(pReplace);
+ sqlite3_bind_null(pReplace, 2);
+ }
+
+ return rc;
+}
+
+/*
+** Load an incr-merge hint from the database. The incr-merge hint, if one
+** exists, is stored in the rowid==1 row of the %_stat table.
+**
+** If successful, populate blob *pHint with the value read from the %_stat
+** table and return SQLITE_OK. Otherwise, if an error occurs, return an
+** SQLite error code.
+*/
+static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
+ sqlite3_stmt *pSelect = 0;
+ int rc;
+
+ pHint->n = 0;
+ rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
+ if( rc==SQLITE_OK ){
+ int rc2;
+ sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
+ if( SQLITE_ROW==sqlite3_step(pSelect) ){
+ const char *aHint = sqlite3_column_blob(pSelect, 0);
+ int nHint = sqlite3_column_bytes(pSelect, 0);
+ if( aHint ){
+ blobGrowBuffer(pHint, nHint, &rc);
+ if( rc==SQLITE_OK ){
+ memcpy(pHint->a, aHint, nHint);
+ pHint->n = nHint;
+ }
+ }
+ }
+ rc2 = sqlite3_reset(pSelect);
+ if( rc==SQLITE_OK ) rc = rc2;
+ }
+
+ return rc;
+}
+
+/*
+** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
+** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
+** consists of two varints, the absolute level number of the input segments
+** and the number of input segments.
+**
+** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
+** set *pRc to an SQLite error code before returning.
+*/
+static void fts3IncrmergeHintPush(
+ Blob *pHint, /* Hint blob to append to */
+ i64 iAbsLevel, /* First varint to store in hint */
+ int nInput, /* Second varint to store in hint */
+ int *pRc /* IN/OUT: Error code */
+){
+ blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
+ if( *pRc==SQLITE_OK ){
+ pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
+ pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
+ }
+}
+
+/*
+** Read the last entry (most recently pushed) from the hint blob *pHint
+** and then remove the entry. Write the two values read to *piAbsLevel and
+** *pnInput before returning.
+**
+** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
+** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
+*/
+static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
+ const int nHint = pHint->n;
+ int i;
+
+ i = pHint->n-1;
+ if( (pHint->a[i] & 0x80) ) return FTS_CORRUPT_VTAB;
+ while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
+ if( i==0 ) return FTS_CORRUPT_VTAB;
+ i--;
+ while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
+
+ pHint->n = i;
+ i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
+ i += fts3GetVarint32(&pHint->a[i], pnInput);
+ assert( i<=nHint );
+ if( i!=nHint ) return FTS_CORRUPT_VTAB;
+
+ return SQLITE_OK;
+}
+
+
+/*
+** Attempt an incremental merge that writes nMerge leaf blocks.
+**
+** Incremental merges happen nMin segments at a time. The segments
+** to be merged are the nMin oldest segments (the ones with the smallest
+** values for the _segdir.idx field) in the highest level that contains
+** at least nMin segments. Multiple merges might occur in an attempt to
+** write the quota of nMerge leaf blocks.
+*/
+SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
+ int rc; /* Return code */
+ int nRem = nMerge; /* Number of leaf pages yet to be written */
+ Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
+ Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
+ IncrmergeWriter *pWriter; /* Writer object */
+ int nSeg = 0; /* Number of input segments */
+ sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
+ Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
+ int bDirtyHint = 0; /* True if blob 'hint' has been modified */
+
+ /* Allocate space for the cursor, filter and writer objects */
+ const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
+ pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
+ if( !pWriter ) return SQLITE_NOMEM;
+ pFilter = (Fts3SegFilter *)&pWriter[1];
+ pCsr = (Fts3MultiSegReader *)&pFilter[1];
+
+ rc = fts3IncrmergeHintLoad(p, &hint);
+ while( rc==SQLITE_OK && nRem>0 ){
+ const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
+ sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
+ int bUseHint = 0; /* True if attempting to append */
+ int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
+
+ /* Search the %_segdir table for the absolute level with the smallest
+ ** relative level number that contains at least nMin segments, if any.
+ ** If one is found, set iAbsLevel to the absolute level number and
+ ** nSeg to nMin. If no level with at least nMin segments can be found,
+ ** set nSeg to -1.
+ */
+ rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
+ sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
+ if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
+ iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
+ nSeg = sqlite3_column_int(pFindLevel, 1);
+ assert( nSeg>=2 );
+ }else{
+ nSeg = -1;
+ }
+ rc = sqlite3_reset(pFindLevel);
+
+ /* If the hint read from the %_stat table is not empty, check if the
+ ** last entry in it specifies a relative level smaller than or equal
+ ** to the level identified by the block above (if any). If so, this
+ ** iteration of the loop will work on merging at the hinted level.
+ */
+ if( rc==SQLITE_OK && hint.n ){
+ int nHint = hint.n;
+ sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
+ int nHintSeg = 0; /* Hint number of segments */
+
+ rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
+ if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
+ /* Based on the scan in the block above, it is known that there
+ ** are no levels with a relative level smaller than that of
+ ** iAbsLevel with more than nSeg segments, or if nSeg is -1,
+ ** no levels with more than nMin segments. Use this to limit the
+ ** value of nHintSeg to avoid a large memory allocation in case the
+ ** merge-hint is corrupt*/
+ iAbsLevel = iHintAbsLevel;
+ nSeg = MIN(MAX(nMin,nSeg), nHintSeg);
+ bUseHint = 1;
+ bDirtyHint = 1;
+ }else{
+ /* This undoes the effect of the HintPop() above - so that no entry
+ ** is removed from the hint blob. */
+ hint.n = nHint;
+ }
+ }
+
+ /* If nSeg is less that zero, then there is no level with at least
+ ** nMin segments and no hint in the %_stat table. No work to do.
+ ** Exit early in this case. */
+ if( nSeg<=0 ) break;
+
+ assert( nMod<=0x7FFFFFFF );
+ if( iAbsLevel<0 || iAbsLevel>(nMod<<32) ){
+ rc = FTS_CORRUPT_VTAB;
+ break;
+ }
+
+ /* Open a cursor to iterate through the contents of the oldest nSeg
+ ** indexes of absolute level iAbsLevel. If this cursor is opened using
+ ** the 'hint' parameters, it is possible that there are less than nSeg
+ ** segments available in level iAbsLevel. In this case, no work is
+ ** done on iAbsLevel - fall through to the next iteration of the loop
+ ** to start work on some other level. */
+ memset(pWriter, 0, nAlloc);
+ pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
+
+ if( rc==SQLITE_OK ){
+ rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
+ assert( bUseHint==1 || bUseHint==0 );
+ if( iIdx==0 || (bUseHint && iIdx==1) ){
+ int bIgnore = 0;
+ rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
+ if( bIgnore ){
+ pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
+ }
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
+ }
+ if( SQLITE_OK==rc && pCsr->nSegment==nSeg
+ && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
+ ){
+ int bEmpty = 0;
+ rc = sqlite3Fts3SegReaderStep(p, pCsr);
+ if( rc==SQLITE_OK ){
+ bEmpty = 1;
+ }else if( rc!=SQLITE_ROW ){
+ sqlite3Fts3SegReaderFinish(pCsr);
+ break;
+ }
+ if( bUseHint && iIdx>0 ){
+ const char *zKey = pCsr->zTerm;
+ int nKey = pCsr->nTerm;
+ rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
+ }else{
+ rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
+ }
+
+ if( rc==SQLITE_OK && pWriter->nLeafEst ){
+ fts3LogMerge(nSeg, iAbsLevel);
+ if( bEmpty==0 ){
+ do {
+ rc = fts3IncrmergeAppend(p, pWriter, pCsr);
+ if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
+ if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
+ }while( rc==SQLITE_ROW );
+ }
+
+ /* Update or delete the input segments */
+ if( rc==SQLITE_OK ){
+ nRem -= (1 + pWriter->nWork);
+ rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
+ if( nSeg!=0 ){
+ bDirtyHint = 1;
+ fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
+ }
+ }
+ }
+
+ if( nSeg!=0 ){
+ pWriter->nLeafData = pWriter->nLeafData * -1;
+ }
+ fts3IncrmergeRelease(p, pWriter, &rc);
+ if( nSeg==0 && pWriter->bNoLeafData==0 ){
+ fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
+ }
+ }
+
+ sqlite3Fts3SegReaderFinish(pCsr);
+ }
+
+ /* Write the hint values into the %_stat table for the next incr-merger */
+ if( bDirtyHint && rc==SQLITE_OK ){
+ rc = fts3IncrmergeHintStore(p, &hint);
+ }
+
+ sqlite3_free(pWriter);
+ sqlite3_free(hint.a);
+ return rc;
+}
+
+/*
+** Convert the text beginning at *pz into an integer and return
+** its value. Advance *pz to point to the first character past
+** the integer.
+**
+** This function used for parameters to merge= and incrmerge=
+** commands.
+*/
+static int fts3Getint(const char **pz){
+ const char *z = *pz;
+ int i = 0;
+ while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
+ *pz = z;
+ return i;
+}
+
+/*
+** Process statements of the form:
+**
+** INSERT INTO table(table) VALUES('merge=A,B');
+**
+** A and B are integers that decode to be the number of leaf pages
+** written for the merge, and the minimum number of segments on a level
+** before it will be selected for a merge, respectively.
+*/
+static int fts3DoIncrmerge(
+ Fts3Table *p, /* FTS3 table handle */
+ const char *zParam /* Nul-terminated string containing "A,B" */
+){
+ int rc;
+ int nMin = (MergeCount(p) / 2);
+ int nMerge = 0;
+ const char *z = zParam;
+
+ /* Read the first integer value */
+ nMerge = fts3Getint(&z);
+
+ /* If the first integer value is followed by a ',', read the second
+ ** integer value. */
+ if( z[0]==',' && z[1]!='\0' ){
+ z++;
+ nMin = fts3Getint(&z);
+ }
+
+ if( z[0]!='\0' || nMin<2 ){
+ rc = SQLITE_ERROR;
+ }else{
+ rc = SQLITE_OK;
+ if( !p->bHasStat ){
+ assert( p->bFts4==0 );
+ sqlite3Fts3CreateStatTable(&rc, p);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
+ }
+ sqlite3Fts3SegmentsClose(p);
+ }
+ return rc;
+}
+
+/*
+** Process statements of the form:
+**
+** INSERT INTO table(table) VALUES('automerge=X');
+**
+** where X is an integer. X==0 means to turn automerge off. X!=0 means
+** turn it on. The setting is persistent.
+*/
+static int fts3DoAutoincrmerge(
+ Fts3Table *p, /* FTS3 table handle */
+ const char *zParam /* Nul-terminated string containing boolean */
+){
+ int rc = SQLITE_OK;
+ sqlite3_stmt *pStmt = 0;
+ p->nAutoincrmerge = fts3Getint(&zParam);
+ if( p->nAutoincrmerge==1 || p->nAutoincrmerge>MergeCount(p) ){
+ p->nAutoincrmerge = 8;
+ }
+ if( !p->bHasStat ){
+ assert( p->bFts4==0 );
+ sqlite3Fts3CreateStatTable(&rc, p);
+ if( rc ) return rc;
+ }
+ rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
+ if( rc ) return rc;
+ sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
+ sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
+ sqlite3_step(pStmt);
+ rc = sqlite3_reset(pStmt);
+ return rc;
+}
+
+/*
+** Return a 64-bit checksum for the FTS index entry specified by the
+** arguments to this function.
+*/
+static u64 fts3ChecksumEntry(
+ const char *zTerm, /* Pointer to buffer containing term */
+ int nTerm, /* Size of zTerm in bytes */
+ int iLangid, /* Language id for current row */
+ int iIndex, /* Index (0..Fts3Table.nIndex-1) */
+ i64 iDocid, /* Docid for current row. */
+ int iCol, /* Column number */
+ int iPos /* Position */
+){
+ int i;
+ u64 ret = (u64)iDocid;
+
+ ret += (ret<<3) + iLangid;
+ ret += (ret<<3) + iIndex;
+ ret += (ret<<3) + iCol;
+ ret += (ret<<3) + iPos;
+ for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
+
+ return ret;
+}
+
+/*
+** Return a checksum of all entries in the FTS index that correspond to
+** language id iLangid. The checksum is calculated by XORing the checksums
+** of each individual entry (see fts3ChecksumEntry()) together.
+**
+** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
+** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
+** return value is undefined in this case.
+*/
+static u64 fts3ChecksumIndex(
+ Fts3Table *p, /* FTS3 table handle */
+ int iLangid, /* Language id to return cksum for */
+ int iIndex, /* Index to cksum (0..p->nIndex-1) */
+ int *pRc /* OUT: Return code */
+){
+ Fts3SegFilter filter;
+ Fts3MultiSegReader csr;
+ int rc;
+ u64 cksum = 0;
+
+ assert( *pRc==SQLITE_OK );
+
+ memset(&filter, 0, sizeof(filter));
+ memset(&csr, 0, sizeof(csr));
+ filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
+ filter.flags |= FTS3_SEGMENT_SCAN;
+
+ rc = sqlite3Fts3SegReaderCursor(
+ p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
+ );
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
+ }
+
+ if( rc==SQLITE_OK ){
+ while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
+ char *pCsr = csr.aDoclist;
+ char *pEnd = &pCsr[csr.nDoclist];
+
+ i64 iDocid = 0;
+ i64 iCol = 0;
+ u64 iPos = 0;
+
+ pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
+ while( pCsr<pEnd ){
+ u64 iVal = 0;
+ pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal);
+ if( pCsr<pEnd ){
+ if( iVal==0 || iVal==1 ){
+ iCol = 0;
+ iPos = 0;
+ if( iVal ){
+ pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
+ }else{
+ pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal);
+ if( p->bDescIdx ){
+ iDocid = (i64)((u64)iDocid - iVal);
+ }else{
+ iDocid = (i64)((u64)iDocid + iVal);
+ }
+ }
+ }else{
+ iPos += (iVal - 2);
+ cksum = cksum ^ fts3ChecksumEntry(
+ csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
+ (int)iCol, (int)iPos
+ );
+ }
+ }
+ }
+ }
+ }
+ sqlite3Fts3SegReaderFinish(&csr);
+
+ *pRc = rc;
+ return cksum;
+}
+
+/*
+** Check if the contents of the FTS index match the current contents of the
+** content table. If no error occurs and the contents do match, set *pbOk
+** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
+** to false before returning.
+**
+** If an error occurs (e.g. an OOM or IO error), return an SQLite error
+** code. The final value of *pbOk is undefined in this case.
+*/
+static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
+ int rc = SQLITE_OK; /* Return code */
+ u64 cksum1 = 0; /* Checksum based on FTS index contents */
+ u64 cksum2 = 0; /* Checksum based on %_content contents */
+ sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
+
+ /* This block calculates the checksum according to the FTS index. */
+ rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
+ if( rc==SQLITE_OK ){
+ int rc2;
+ sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
+ sqlite3_bind_int(pAllLangid, 2, p->nIndex);
+ while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
+ int iLangid = sqlite3_column_int(pAllLangid, 0);
+ int i;
+ for(i=0; i<p->nIndex; i++){
+ cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
+ }
+ }
+ rc2 = sqlite3_reset(pAllLangid);
+ if( rc==SQLITE_OK ) rc = rc2;
+ }
+
+ /* This block calculates the checksum according to the %_content table */
+ if( rc==SQLITE_OK ){
+ sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
+ sqlite3_stmt *pStmt = 0;
+ char *zSql;
+
+ zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
+ if( !zSql ){
+ rc = SQLITE_NOMEM;
+ }else{
+ rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
+ sqlite3_free(zSql);
+ }
+
+ while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
+ i64 iDocid = sqlite3_column_int64(pStmt, 0);
+ int iLang = langidFromSelect(p, pStmt);
+ int iCol;
+
+ for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
+ if( p->abNotindexed[iCol]==0 ){
+ const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
+ sqlite3_tokenizer_cursor *pT = 0;
+
+ rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, -1, &pT);
+ while( rc==SQLITE_OK ){
+ char const *zToken; /* Buffer containing token */
+ int nToken = 0; /* Number of bytes in token */
+ int iDum1 = 0, iDum2 = 0; /* Dummy variables */
+ int iPos = 0; /* Position of token in zText */
+
+ rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
+ if( rc==SQLITE_OK ){
+ int i;
+ cksum2 = cksum2 ^ fts3ChecksumEntry(
+ zToken, nToken, iLang, 0, iDocid, iCol, iPos
+ );
+ for(i=1; i<p->nIndex; i++){
+ if( p->aIndex[i].nPrefix<=nToken ){
+ cksum2 = cksum2 ^ fts3ChecksumEntry(
+ zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
+ );
+ }
+ }
+ }
+ }
+ if( pT ) pModule->xClose(pT);
+ if( rc==SQLITE_DONE ) rc = SQLITE_OK;
+ }
+ }
+ }
+
+ sqlite3_finalize(pStmt);
+ }
+
+ *pbOk = (cksum1==cksum2);
+ return rc;
+}
+
+/*
+** Run the integrity-check. If no error occurs and the current contents of
+** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
+** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
+**
+** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
+** error code.
+**
+** The integrity-check works as follows. For each token and indexed token
+** prefix in the document set, a 64-bit checksum is calculated (by code
+** in fts3ChecksumEntry()) based on the following:
+**
+** + The index number (0 for the main index, 1 for the first prefix
+** index etc.),
+** + The token (or token prefix) text itself,
+** + The language-id of the row it appears in,
+** + The docid of the row it appears in,
+** + The column it appears in, and
+** + The tokens position within that column.
+**
+** The checksums for all entries in the index are XORed together to create
+** a single checksum for the entire index.
+**
+** The integrity-check code calculates the same checksum in two ways:
+**
+** 1. By scanning the contents of the FTS index, and
+** 2. By scanning and tokenizing the content table.
+**
+** If the two checksums are identical, the integrity-check is deemed to have
+** passed.
+*/
+static int fts3DoIntegrityCheck(
+ Fts3Table *p /* FTS3 table handle */
+){
+ int rc;
+ int bOk = 0;
+ rc = fts3IntegrityCheck(p, &bOk);
+ if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
+ return rc;
+}
+
+/*
+** Handle a 'special' INSERT of the form:
+**
+** "INSERT INTO tbl(tbl) VALUES(<expr>)"
+**
+** Argument pVal contains the result of <expr>. Currently the only
+** meaningful value to insert is the text 'optimize'.
+*/
+static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
+ int rc = SQLITE_ERROR; /* Return Code */
+ const char *zVal = (const char *)sqlite3_value_text(pVal);
+ int nVal = sqlite3_value_bytes(pVal);
+
+ if( !zVal ){
+ return SQLITE_NOMEM;
+ }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
+ rc = fts3DoOptimize(p, 0);
+ }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
+ rc = fts3DoRebuild(p);
+ }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
+ rc = fts3DoIntegrityCheck(p);
+ }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
+ rc = fts3DoIncrmerge(p, &zVal[6]);
+ }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
+ rc = fts3DoAutoincrmerge(p, &zVal[10]);
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+ }else{
+ int v;
+ if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
+ v = atoi(&zVal[9]);
+ if( v>=24 && v<=p->nPgsz-35 ) p->nNodeSize = v;
+ rc = SQLITE_OK;
+ }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
+ v = atoi(&zVal[11]);
+ if( v>=64 && v<=FTS3_MAX_PENDING_DATA ) p->nMaxPendingData = v;
+ rc = SQLITE_OK;
+ }else if( nVal>21 && 0==sqlite3_strnicmp(zVal,"test-no-incr-doclist=",21) ){
+ p->bNoIncrDoclist = atoi(&zVal[21]);
+ rc = SQLITE_OK;
+ }else if( nVal>11 && 0==sqlite3_strnicmp(zVal,"mergecount=",11) ){
+ v = atoi(&zVal[11]);
+ if( v>=4 && v<=FTS3_MERGE_COUNT && (v&1)==0 ) p->nMergeCount = v;
+ rc = SQLITE_OK;
+ }
+#endif
+ }
+ return rc;
+}
+
+#ifndef SQLITE_DISABLE_FTS4_DEFERRED
+/*
+** Delete all cached deferred doclists. Deferred doclists are cached
+** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
+*/
+SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
+ Fts3DeferredToken *pDef;
+ for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
+ fts3PendingListDelete(pDef->pList);
+ pDef->pList = 0;
+ }
+}
+
+/*
+** Free all entries in the pCsr->pDeffered list. Entries are added to
+** this list using sqlite3Fts3DeferToken().
+*/
+SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
+ Fts3DeferredToken *pDef;
+ Fts3DeferredToken *pNext;
+ for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
+ pNext = pDef->pNext;
+ fts3PendingListDelete(pDef->pList);
+ sqlite3_free(pDef);
+ }
+ pCsr->pDeferred = 0;
+}
+
+/*
+** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
+** based on the row that pCsr currently points to.
+**
+** A deferred-doclist is like any other doclist with position information
+** included, except that it only contains entries for a single row of the
+** table, not for all rows.
+*/
+SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
+ int rc = SQLITE_OK; /* Return code */
+ if( pCsr->pDeferred ){
+ int i; /* Used to iterate through table columns */
+ sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
+ Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
+
+ Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
+ sqlite3_tokenizer *pT = p->pTokenizer;
+ sqlite3_tokenizer_module const *pModule = pT->pModule;
+
+ assert( pCsr->isRequireSeek==0 );
+ iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
+
+ for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
+ if( p->abNotindexed[i]==0 ){
+ const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
+ sqlite3_tokenizer_cursor *pTC = 0;
+
+ rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
+ while( rc==SQLITE_OK ){
+ char const *zToken; /* Buffer containing token */
+ int nToken = 0; /* Number of bytes in token */
+ int iDum1 = 0, iDum2 = 0; /* Dummy variables */
+ int iPos = 0; /* Position of token in zText */
+
+ rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
+ for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
+ Fts3PhraseToken *pPT = pDef->pToken;
+ if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
+ && (pPT->bFirst==0 || iPos==0)
+ && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
+ && (0==memcmp(zToken, pPT->z, pPT->n))
+ ){
+ fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
+ }
+ }
+ }
+ if( pTC ) pModule->xClose(pTC);
+ if( rc==SQLITE_DONE ) rc = SQLITE_OK;
+ }
+ }
+
+ for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
+ if( pDef->pList ){
+ rc = fts3PendingListAppendVarint(&pDef->pList, 0);
+ }
+ }
+ }
+
+ return rc;
+}
+
+SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
+ Fts3DeferredToken *p,
+ char **ppData,
+ int *pnData
+){
+ char *pRet;
+ int nSkip;
+ sqlite3_int64 dummy;
+
+ *ppData = 0;
+ *pnData = 0;
+
+ if( p->pList==0 ){
+ return SQLITE_OK;
+ }
+
+ pRet = (char *)sqlite3_malloc(p->pList->nData);
+ if( !pRet ) return SQLITE_NOMEM;
+
+ nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
+ *pnData = p->pList->nData - nSkip;
+ *ppData = pRet;
+
+ memcpy(pRet, &p->pList->aData[nSkip], *pnData);
+ return SQLITE_OK;
+}
+
+/*
+** Add an entry for token pToken to the pCsr->pDeferred list.
+*/
+SQLITE_PRIVATE int sqlite3Fts3DeferToken(
+ Fts3Cursor *pCsr, /* Fts3 table cursor */
+ Fts3PhraseToken *pToken, /* Token to defer */
+ int iCol /* Column that token must appear in (or -1) */
+){
+ Fts3DeferredToken *pDeferred;
+ pDeferred = sqlite3_malloc(sizeof(*pDeferred));
+ if( !pDeferred ){
+ return SQLITE_NOMEM;
+ }
+ memset(pDeferred, 0, sizeof(*pDeferred));
+ pDeferred->pToken = pToken;
+ pDeferred->pNext = pCsr->pDeferred;
+ pDeferred->iCol = iCol;
+ pCsr->pDeferred = pDeferred;
+
+ assert( pToken->pDeferred==0 );
+ pToken->pDeferred = pDeferred;
+
+ return SQLITE_OK;
+}
+#endif
+
+/*
+** SQLite value pRowid contains the rowid of a row that may or may not be
+** present in the FTS3 table. If it is, delete it and adjust the contents
+** of subsiduary data structures accordingly.
+*/
+static int fts3DeleteByRowid(
+ Fts3Table *p,
+ sqlite3_value *pRowid,
+ int *pnChng, /* IN/OUT: Decrement if row is deleted */
+ u32 *aSzDel
+){
+ int rc = SQLITE_OK; /* Return code */
+ int bFound = 0; /* True if *pRowid really is in the table */
+
+ fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
+ if( bFound && rc==SQLITE_OK ){
+ int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
+ rc = fts3IsEmpty(p, pRowid, &isEmpty);
+ if( rc==SQLITE_OK ){
+ if( isEmpty ){
+ /* Deleting this row means the whole table is empty. In this case
+ ** delete the contents of all three tables and throw away any
+ ** data in the pendingTerms hash table. */
+ rc = fts3DeleteAll(p, 1);
+ *pnChng = 0;
+ memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
+ }else{
+ *pnChng = *pnChng - 1;
+ if( p->zContentTbl==0 ){
+ fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
+ }
+ if( p->bHasDocsize ){
+ fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
+ }
+ }
+ }
+ }
+
+ return rc;
+}
+
+/*
+** This function does the work for the xUpdate method of FTS3 virtual
+** tables. The schema of the virtual table being:
+**
+** CREATE TABLE <table name>(
+** <user columns>,
+** <table name> HIDDEN,
+** docid HIDDEN,
+** <langid> HIDDEN
+** );
+**
+**
+*/
+SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
+ sqlite3_vtab *pVtab, /* FTS3 vtab object */
+ int nArg, /* Size of argument array */
+ sqlite3_value **apVal, /* Array of arguments */
+ sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
+){
+ Fts3Table *p = (Fts3Table *)pVtab;
+ int rc = SQLITE_OK; /* Return Code */
+ u32 *aSzIns = 0; /* Sizes of inserted documents */
+ u32 *aSzDel = 0; /* Sizes of deleted documents */
+ int nChng = 0; /* Net change in number of documents */
+ int bInsertDone = 0;
+
+ /* At this point it must be known if the %_stat table exists or not.
+ ** So bHasStat may not be 2. */
+ assert( p->bHasStat==0 || p->bHasStat==1 );
+
+ assert( p->pSegments==0 );
+ assert(
+ nArg==1 /* DELETE operations */
+ || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
+ );
+
+ /* Check for a "special" INSERT operation. One of the form:
+ **
+ ** INSERT INTO xyz(xyz) VALUES('command');
+ */
+ if( nArg>1
+ && sqlite3_value_type(apVal[0])==SQLITE_NULL
+ && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
+ ){
+ rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
+ goto update_out;
+ }
+
+ if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
+ rc = SQLITE_CONSTRAINT;
+ goto update_out;
+ }
+
+ /* Allocate space to hold the change in document sizes */
+ aSzDel = sqlite3_malloc64(sizeof(aSzDel[0])*((sqlite3_int64)p->nColumn+1)*2);
+ if( aSzDel==0 ){
+ rc = SQLITE_NOMEM;
+ goto update_out;
+ }
+ aSzIns = &aSzDel[p->nColumn+1];
+ memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
+
+ rc = fts3Writelock(p);
+ if( rc!=SQLITE_OK ) goto update_out;
+
+ /* If this is an INSERT operation, or an UPDATE that modifies the rowid
+ ** value, then this operation requires constraint handling.
+ **
+ ** If the on-conflict mode is REPLACE, this means that the existing row
+ ** should be deleted from the database before inserting the new row. Or,
+ ** if the on-conflict mode is other than REPLACE, then this method must
+ ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
+ ** modify the database file.
+ */
+ if( nArg>1 && p->zContentTbl==0 ){
+ /* Find the value object that holds the new rowid value. */
+ sqlite3_value *pNewRowid = apVal[3+p->nColumn];
+ if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
+ pNewRowid = apVal[1];
+ }
+
+ if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
+ sqlite3_value_type(apVal[0])==SQLITE_NULL
+ || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
+ )){
+ /* The new rowid is not NULL (in this case the rowid will be
+ ** automatically assigned and there is no chance of a conflict), and
+ ** the statement is either an INSERT or an UPDATE that modifies the
+ ** rowid column. So if the conflict mode is REPLACE, then delete any
+ ** existing row with rowid=pNewRowid.
+ **
+ ** Or, if the conflict mode is not REPLACE, insert the new record into
+ ** the %_content table. If we hit the duplicate rowid constraint (or any
+ ** other error) while doing so, return immediately.
+ **
+ ** This branch may also run if pNewRowid contains a value that cannot
+ ** be losslessly converted to an integer. In this case, the eventual
+ ** call to fts3InsertData() (either just below or further on in this
+ ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
+ ** invoked, it will delete zero rows (since no row will have
+ ** docid=$pNewRowid if $pNewRowid is not an integer value).
+ */
+ if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
+ rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
+ }else{
+ rc = fts3InsertData(p, apVal, pRowid);
+ bInsertDone = 1;
+ }
+ }
+ }
+ if( rc!=SQLITE_OK ){
+ goto update_out;
+ }
+
+ /* If this is a DELETE or UPDATE operation, remove the old record. */
+ if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
+ assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
+ rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
+ }
+
+ /* If this is an INSERT or UPDATE operation, insert the new record. */
+ if( nArg>1 && rc==SQLITE_OK ){
+ int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
+ if( bInsertDone==0 ){
+ rc = fts3InsertData(p, apVal, pRowid);
+ if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
+ rc = FTS_CORRUPT_VTAB;
+ }
+ }
+ if( rc==SQLITE_OK ){
+ rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
+ }
+ if( rc==SQLITE_OK ){
+ assert( p->iPrevDocid==*pRowid );
+ rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
+ }
+ if( p->bHasDocsize ){
+ fts3InsertDocsize(&rc, p, aSzIns);
+ }
+ nChng++;
+ }
+
+ if( p->bFts4 ){
+ fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
+ }
+
+ update_out:
+ sqlite3_free(aSzDel);
+ sqlite3Fts3SegmentsClose(p);
+ return rc;
+}
+
+/*
+** Flush any data in the pending-terms hash table to disk. If successful,
+** merge all segments in the database (including the new segment, if
+** there was any data to flush) into a single segment.
+*/
+SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
+ int rc;
+ rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
+ if( rc==SQLITE_OK ){
+ rc = fts3DoOptimize(p, 1);
+ if( rc==SQLITE_OK || rc==SQLITE_DONE ){
+ int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
+ if( rc2!=SQLITE_OK ) rc = rc2;
+ }else{
+ sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
+ sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
+ }
+ }
+ sqlite3Fts3SegmentsClose(p);
+ return rc;
+}
+
+#endif
+
+/************** End of fts3_write.c ******************************************/
+/************** Begin file fts3_snippet.c ************************************/
+/*
+** 2009 Oct 23
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+*/
+
+/* #include "fts3Int.h" */
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
+
+/* #include <string.h> */
+/* #include <assert.h> */
+
+/*
+** Characters that may appear in the second argument to matchinfo().
+*/
+#define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
+#define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
+#define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
+#define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
+#define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
+#define FTS3_MATCHINFO_LCS 's' /* nCol values */
+#define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
+#define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
+#define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
+
+/*
+** The default value for the second argument to matchinfo().
+*/
+#define FTS3_MATCHINFO_DEFAULT "pcx"
+
+
+/*
+** Used as an fts3ExprIterate() context when loading phrase doclists to
+** Fts3Expr.aDoclist[]/nDoclist.
+*/
+typedef struct LoadDoclistCtx LoadDoclistCtx;
+struct LoadDoclistCtx {
+ Fts3Cursor *pCsr; /* FTS3 Cursor */
+ int nPhrase; /* Number of phrases seen so far */
+ int nToken; /* Number of tokens seen so far */
+};
+
+/*
+** The following types are used as part of the implementation of the
+** fts3BestSnippet() routine.
+*/
+typedef struct SnippetIter SnippetIter;
+typedef struct SnippetPhrase SnippetPhrase;
+typedef struct SnippetFragment SnippetFragment;
+
+struct SnippetIter {
+ Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
+ int iCol; /* Extract snippet from this column */
+ int nSnippet; /* Requested snippet length (in tokens) */
+ int nPhrase; /* Number of phrases in query */
+ SnippetPhrase *aPhrase; /* Array of size nPhrase */
+ int iCurrent; /* First token of current snippet */
+};
+
+struct SnippetPhrase {
+ int nToken; /* Number of tokens in phrase */
+ char *pList; /* Pointer to start of phrase position list */
+ int iHead; /* Next value in position list */
+ char *pHead; /* Position list data following iHead */
+ int iTail; /* Next value in trailing position list */
+ char *pTail; /* Position list data following iTail */
+};
+
+struct SnippetFragment {
+ int iCol; /* Column snippet is extracted from */
+ int iPos; /* Index of first token in snippet */
+ u64 covered; /* Mask of query phrases covered */
+ u64 hlmask; /* Mask of snippet terms to highlight */
+};
+
+/*
+** This type is used as an fts3ExprIterate() context object while
+** accumulating the data returned by the matchinfo() function.
+*/
+typedef struct MatchInfo MatchInfo;
+struct MatchInfo {
+ Fts3Cursor *pCursor; /* FTS3 Cursor */
+ int nCol; /* Number of columns in table */
+ int nPhrase; /* Number of matchable phrases in query */
+ sqlite3_int64 nDoc; /* Number of docs in database */
+ char flag;
+ u32 *aMatchinfo; /* Pre-allocated buffer */
+};
+
+/*
+** An instance of this structure is used to manage a pair of buffers, each
+** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
+** for details.
+*/
+struct MatchinfoBuffer {
+ u8 aRef[3];
+ int nElem;
+ int bGlobal; /* Set if global data is loaded */
+ char *zMatchinfo;
+ u32 aMatchinfo[1];
+};
+
+
+/*
+** The snippet() and offsets() functions both return text values. An instance
+** of the following structure is used to accumulate those values while the
+** functions are running. See fts3StringAppend() for details.
+*/
+typedef struct StrBuffer StrBuffer;
+struct StrBuffer {
+ char *z; /* Pointer to buffer containing string */
+ int n; /* Length of z in bytes (excl. nul-term) */
+ int nAlloc; /* Allocated size of buffer z in bytes */
+};
+
+
+/*************************************************************************
+** Start of MatchinfoBuffer code.
+*/
+
+/*
+** Allocate a two-slot MatchinfoBuffer object.
+*/
+static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){
+ MatchinfoBuffer *pRet;
+ sqlite3_int64 nByte = sizeof(u32) * (2*(sqlite3_int64)nElem + 1)
+ + sizeof(MatchinfoBuffer);
+ sqlite3_int64 nStr = strlen(zMatchinfo);
+
+ pRet = sqlite3_malloc64(nByte + nStr+1);
+ if( pRet ){
+ memset(pRet, 0, nByte);
+ pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
+ pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0]
+ + sizeof(u32)*((int)nElem+1);
+ pRet->nElem = (int)nElem;
+ pRet->zMatchinfo = ((char*)pRet) + nByte;
+ memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
+ pRet->aRef[0] = 1;
+ }
+
+ return pRet;
+}
+
+static void fts3MIBufferFree(void *p){
+ MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
+
+ assert( (u32*)p==&pBuf->aMatchinfo[1]
+ || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
+ );
+ if( (u32*)p==&pBuf->aMatchinfo[1] ){
+ pBuf->aRef[1] = 0;
+ }else{
+ pBuf->aRef[2] = 0;
+ }
+
+ if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
+ sqlite3_free(pBuf);
+ }
+}
+
+static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
+ void (*xRet)(void*) = 0;
+ u32 *aOut = 0;
+
+ if( p->aRef[1]==0 ){
+ p->aRef[1] = 1;
+ aOut = &p->aMatchinfo[1];
+ xRet = fts3MIBufferFree;
+ }
+ else if( p->aRef[2]==0 ){
+ p->aRef[2] = 1;
+ aOut = &p->aMatchinfo[p->nElem+2];
+ xRet = fts3MIBufferFree;
+ }else{
+ aOut = (u32*)sqlite3_malloc64(p->nElem * sizeof(u32));
+ if( aOut ){
+ xRet = sqlite3_free;
+ if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
+ }
+ }
+
+ *paOut = aOut;
+ return xRet;
+}
+
+static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
+ p->bGlobal = 1;
+ memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
+}
+
+/*
+** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
+*/
+SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
+ if( p ){
+ assert( p->aRef[0]==1 );
+ p->aRef[0] = 0;
+ if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
+ sqlite3_free(p);
+ }
+ }
+}
+
+/*
+** End of MatchinfoBuffer code.
+*************************************************************************/
+
+
+/*
+** This function is used to help iterate through a position-list. A position
+** list is a list of unique integers, sorted from smallest to largest. Each
+** element of the list is represented by an FTS3 varint that takes the value
+** of the difference between the current element and the previous one plus
+** two. For example, to store the position-list:
+**
+** 4 9 113
+**
+** the three varints:
+**
+** 6 7 106
+**
+** are encoded.
+**
+** When this function is called, *pp points to the start of an element of
+** the list. *piPos contains the value of the previous entry in the list.
+** After it returns, *piPos contains the value of the next element of the
+** list and *pp is advanced to the following varint.
+*/
+static void fts3GetDeltaPosition(char **pp, int *piPos){
+ int iVal;
+ *pp += fts3GetVarint32(*pp, &iVal);
+ *piPos += (iVal-2);
+}
+
+/*
+** Helper function for fts3ExprIterate() (see below).
+*/
+static int fts3ExprIterate2(
+ Fts3Expr *pExpr, /* Expression to iterate phrases of */
+ int *piPhrase, /* Pointer to phrase counter */
+ int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
+ void *pCtx /* Second argument to pass to callback */
+){
+ int rc; /* Return code */
+ int eType = pExpr->eType; /* Type of expression node pExpr */
+
+ if( eType!=FTSQUERY_PHRASE ){
+ assert( pExpr->pLeft && pExpr->pRight );
+ rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
+ if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
+ rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
+ }
+ }else{
+ rc = x(pExpr, *piPhrase, pCtx);
+ (*piPhrase)++;
+ }
+ return rc;
+}
+
+/*
+** Iterate through all phrase nodes in an FTS3 query, except those that
+** are part of a sub-tree that is the right-hand-side of a NOT operator.
+** For each phrase node found, the supplied callback function is invoked.
+**
+** If the callback function returns anything other than SQLITE_OK,
+** the iteration is abandoned and the error code returned immediately.
+** Otherwise, SQLITE_OK is returned after a callback has been made for
+** all eligible phrase nodes.
+*/
+static int fts3ExprIterate(
+ Fts3Expr *pExpr, /* Expression to iterate phrases of */
+ int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
+ void *pCtx /* Second argument to pass to callback */
+){
+ int iPhrase = 0; /* Variable used as the phrase counter */
+ return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
+}
+
+
+/*
+** This is an fts3ExprIterate() callback used while loading the doclists
+** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
+** fts3ExprLoadDoclists().
+*/
+static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
+ int rc = SQLITE_OK;
+ Fts3Phrase *pPhrase = pExpr->pPhrase;
+ LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
+
+ UNUSED_PARAMETER(iPhrase);
+
+ p->nPhrase++;
+ p->nToken += pPhrase->nToken;
+
+ return rc;
+}
+
+/*
+** Load the doclists for each phrase in the query associated with FTS3 cursor
+** pCsr.
+**
+** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
+** phrases in the expression (all phrases except those directly or
+** indirectly descended from the right-hand-side of a NOT operator). If
+** pnToken is not NULL, then it is set to the number of tokens in all
+** matchable phrases of the expression.
+*/
+static int fts3ExprLoadDoclists(
+ Fts3Cursor *pCsr, /* Fts3 cursor for current query */
+ int *pnPhrase, /* OUT: Number of phrases in query */
+ int *pnToken /* OUT: Number of tokens in query */
+){
+ int rc; /* Return Code */
+ LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
+ sCtx.pCsr = pCsr;
+ rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
+ if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
+ if( pnToken ) *pnToken = sCtx.nToken;
+ return rc;
+}
+
+static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
+ (*(int *)ctx)++;
+ pExpr->iPhrase = iPhrase;
+ return SQLITE_OK;
+}
+static int fts3ExprPhraseCount(Fts3Expr *pExpr){
+ int nPhrase = 0;
+ (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
+ return nPhrase;
+}
+
+/*
+** Advance the position list iterator specified by the first two
+** arguments so that it points to the first element with a value greater
+** than or equal to parameter iNext.
+*/
+static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
+ char *pIter = *ppIter;
+ if( pIter ){
+ int iIter = *piIter;
+
+ while( iIter<iNext ){
+ if( 0==(*pIter & 0xFE) ){
+ iIter = -1;
+ pIter = 0;
+ break;
+ }
+ fts3GetDeltaPosition(&pIter, &iIter);
+ }
+
+ *piIter = iIter;
+ *ppIter = pIter;
+ }
+}
+
+/*
+** Advance the snippet iterator to the next candidate snippet.
+*/
+static int fts3SnippetNextCandidate(SnippetIter *pIter){
+ int i; /* Loop counter */
+
+ if( pIter->iCurrent<0 ){
+ /* The SnippetIter object has just been initialized. The first snippet
+ ** candidate always starts at offset 0 (even if this candidate has a
+ ** score of 0.0).
+ */
+ pIter->iCurrent = 0;
+
+ /* Advance the 'head' iterator of each phrase to the first offset that
+ ** is greater than or equal to (iNext+nSnippet).
+ */
+ for(i=0; i<pIter->nPhrase; i++){
+ SnippetPhrase *pPhrase = &pIter->aPhrase[i];
+ fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
+ }
+ }else{
+ int iStart;
+ int iEnd = 0x7FFFFFFF;
+
+ for(i=0; i<pIter->nPhrase; i++){
+ SnippetPhrase *pPhrase = &pIter->aPhrase[i];
+ if( pPhrase->pHead && pPhrase->iHead<iEnd ){
+ iEnd = pPhrase->iHead;
+ }
+ }
+ if( iEnd==0x7FFFFFFF ){
+ return 1;
+ }
+
+ pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
+ for(i=0; i<pIter->nPhrase; i++){
+ SnippetPhrase *pPhrase = &pIter->aPhrase[i];
+ fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
+ fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
+ }
+ }
+
+ return 0;
+}
+
+/*
+** Retrieve information about the current candidate snippet of snippet
+** iterator pIter.
+*/
+static void fts3SnippetDetails(
+ SnippetIter *pIter, /* Snippet iterator */
+ u64 mCovered, /* Bitmask of phrases already covered */
+ int *piToken, /* OUT: First token of proposed snippet */
+ int *piScore, /* OUT: "Score" for this snippet */
+ u64 *pmCover, /* OUT: Bitmask of phrases covered */
+ u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
+){
+ int iStart = pIter->iCurrent; /* First token of snippet */
+ int iScore = 0; /* Score of this snippet */
+ int i; /* Loop counter */
+ u64 mCover = 0; /* Mask of phrases covered by this snippet */
+ u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
+
+ for(i=0; i<pIter->nPhrase; i++){
+ SnippetPhrase *pPhrase = &pIter->aPhrase[i];
+ if( pPhrase->pTail ){
+ char *pCsr = pPhrase->pTail;
+ int iCsr = pPhrase->iTail;
+
+ while( iCsr<(iStart+pIter->nSnippet) && iCsr>=iStart ){
+ int j;
+ u64 mPhrase = (u64)1 << (i%64);
+ u64 mPos = (u64)1 << (iCsr - iStart);
+ assert( iCsr>=iStart && (iCsr - iStart)<=64 );
+ assert( i>=0 );
+ if( (mCover|mCovered)&mPhrase ){
+ iScore++;
+ }else{
+ iScore += 1000;
+ }
+ mCover |= mPhrase;
+
+ for(j=0; j<pPhrase->nToken; j++){
+ mHighlight |= (mPos>>j);
+ }
+
+ if( 0==(*pCsr & 0x0FE) ) break;
+ fts3GetDeltaPosition(&pCsr, &iCsr);
+ }
+ }
+ }
+
+ /* Set the output variables before returning. */
+ *piToken = iStart;
+ *piScore = iScore;
+ *pmCover = mCover;
+ *pmHighlight = mHighlight;
+}
+
+/*
+** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
+** Each invocation populates an element of the SnippetIter.aPhrase[] array.
+*/
+static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
+ SnippetIter *p = (SnippetIter *)ctx;
+ SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
+ char *pCsr;
+ int rc;
+
+ pPhrase->nToken = pExpr->pPhrase->nToken;
+ rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
+ assert( rc==SQLITE_OK || pCsr==0 );
+ if( pCsr ){
+ int iFirst = 0;
+ pPhrase->pList = pCsr;
+ fts3GetDeltaPosition(&pCsr, &iFirst);
+ if( iFirst<0 ){
+ rc = FTS_CORRUPT_VTAB;
+ }else{
+ pPhrase->pHead = pCsr;
+ pPhrase->pTail = pCsr;
+ pPhrase->iHead = iFirst;
+ pPhrase->iTail = iFirst;
+ }
+ }else{
+ assert( rc!=SQLITE_OK || (
+ pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
+ ));
+ }
+
+ return rc;
+}
+
+/*
+** Select the fragment of text consisting of nFragment contiguous tokens
+** from column iCol that represent the "best" snippet. The best snippet
+** is the snippet with the highest score, where scores are calculated
+** by adding:
+**
+** (a) +1 point for each occurrence of a matchable phrase in the snippet.
+**
+** (b) +1000 points for the first occurrence of each matchable phrase in
+** the snippet for which the corresponding mCovered bit is not set.
+**
+** The selected snippet parameters are stored in structure *pFragment before
+** returning. The score of the selected snippet is stored in *piScore
+** before returning.
+*/
+static int fts3BestSnippet(
+ int nSnippet, /* Desired snippet length */
+ Fts3Cursor *pCsr, /* Cursor to create snippet for */
+ int iCol, /* Index of column to create snippet from */
+ u64 mCovered, /* Mask of phrases already covered */
+ u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
+ SnippetFragment *pFragment, /* OUT: Best snippet found */
+ int *piScore /* OUT: Score of snippet pFragment */
+){
+ int rc; /* Return Code */
+ int nList; /* Number of phrases in expression */
+ SnippetIter sIter; /* Iterates through snippet candidates */
+ sqlite3_int64 nByte; /* Number of bytes of space to allocate */
+ int iBestScore = -1; /* Best snippet score found so far */
+ int i; /* Loop counter */
+
+ memset(&sIter, 0, sizeof(sIter));
+
+ /* Iterate through the phrases in the expression to count them. The same
+ ** callback makes sure the doclists are loaded for each phrase.
+ */
+ rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+
+ /* Now that it is known how many phrases there are, allocate and zero
+ ** the required space using malloc().
+ */
+ nByte = sizeof(SnippetPhrase) * nList;
+ sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc64(nByte);
+ if( !sIter.aPhrase ){
+ return SQLITE_NOMEM;
+ }
+ memset(sIter.aPhrase, 0, nByte);
+
+ /* Initialize the contents of the SnippetIter object. Then iterate through
+ ** the set of phrases in the expression to populate the aPhrase[] array.
+ */
+ sIter.pCsr = pCsr;
+ sIter.iCol = iCol;
+ sIter.nSnippet = nSnippet;
+ sIter.nPhrase = nList;
+ sIter.iCurrent = -1;
+ rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
+ if( rc==SQLITE_OK ){
+
+ /* Set the *pmSeen output variable. */
+ for(i=0; i<nList; i++){
+ if( sIter.aPhrase[i].pHead ){
+ *pmSeen |= (u64)1 << (i%64);
+ }
+ }
+
+ /* Loop through all candidate snippets. Store the best snippet in
+ ** *pFragment. Store its associated 'score' in iBestScore.
+ */
+ pFragment->iCol = iCol;
+ while( !fts3SnippetNextCandidate(&sIter) ){
+ int iPos;
+ int iScore;
+ u64 mCover;
+ u64 mHighlite;
+ fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
+ assert( iScore>=0 );
+ if( iScore>iBestScore ){
+ pFragment->iPos = iPos;
+ pFragment->hlmask = mHighlite;
+ pFragment->covered = mCover;
+ iBestScore = iScore;
+ }
+ }
+
+ *piScore = iBestScore;
+ }
+ sqlite3_free(sIter.aPhrase);
+ return rc;
+}
+
+
+/*
+** Append a string to the string-buffer passed as the first argument.
+**
+** If nAppend is negative, then the length of the string zAppend is
+** determined using strlen().
+*/
+static int fts3StringAppend(
+ StrBuffer *pStr, /* Buffer to append to */
+ const char *zAppend, /* Pointer to data to append to buffer */
+ int nAppend /* Size of zAppend in bytes (or -1) */
+){
+ if( nAppend<0 ){
+ nAppend = (int)strlen(zAppend);
+ }
+
+ /* If there is insufficient space allocated at StrBuffer.z, use realloc()
+ ** to grow the buffer until so that it is big enough to accomadate the
+ ** appended data.
+ */
+ if( pStr->n+nAppend+1>=pStr->nAlloc ){
+ sqlite3_int64 nAlloc = pStr->nAlloc+(sqlite3_int64)nAppend+100;
+ char *zNew = sqlite3_realloc64(pStr->z, nAlloc);
+ if( !zNew ){
+ return SQLITE_NOMEM;
+ }
+ pStr->z = zNew;
+ pStr->nAlloc = nAlloc;
+ }
+ assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
+
+ /* Append the data to the string buffer. */
+ memcpy(&pStr->z[pStr->n], zAppend, nAppend);
+ pStr->n += nAppend;
+ pStr->z[pStr->n] = '\0';
+
+ return SQLITE_OK;
+}
+
+/*
+** The fts3BestSnippet() function often selects snippets that end with a
+** query term. That is, the final term of the snippet is always a term
+** that requires highlighting. For example, if 'X' is a highlighted term
+** and '.' is a non-highlighted term, BestSnippet() may select:
+**
+** ........X.....X
+**
+** This function "shifts" the beginning of the snippet forward in the
+** document so that there are approximately the same number of
+** non-highlighted terms to the right of the final highlighted term as there
+** are to the left of the first highlighted term. For example, to this:
+**
+** ....X.....X....
+**
+** This is done as part of extracting the snippet text, not when selecting
+** the snippet. Snippet selection is done based on doclists only, so there
+** is no way for fts3BestSnippet() to know whether or not the document
+** actually contains terms that follow the final highlighted term.
+*/
+static int fts3SnippetShift(
+ Fts3Table *pTab, /* FTS3 table snippet comes from */
+ int iLangid, /* Language id to use in tokenizing */
+ int nSnippet, /* Number of tokens desired for snippet */
+ const char *zDoc, /* Document text to extract snippet from */
+ int nDoc, /* Size of buffer zDoc in bytes */
+ int *piPos, /* IN/OUT: First token of snippet */
+ u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
+){
+ u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
+
+ if( hlmask ){
+ int nLeft; /* Tokens to the left of first highlight */
+ int nRight; /* Tokens to the right of last highlight */
+ int nDesired; /* Ideal number of tokens to shift forward */
+
+ for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
+ for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
+ assert( (nSnippet-1-nRight)<=63 && (nSnippet-1-nRight)>=0 );
+ nDesired = (nLeft-nRight)/2;
+
+ /* Ideally, the start of the snippet should be pushed forward in the
+ ** document nDesired tokens. This block checks if there are actually
+ ** nDesired tokens to the right of the snippet. If so, *piPos and
+ ** *pHlMask are updated to shift the snippet nDesired tokens to the
+ ** right. Otherwise, the snippet is shifted by the number of tokens
+ ** available.
+ */
+ if( nDesired>0 ){
+ int nShift; /* Number of tokens to shift snippet by */
+ int iCurrent = 0; /* Token counter */
+ int rc; /* Return Code */
+ sqlite3_tokenizer_module *pMod;
+ sqlite3_tokenizer_cursor *pC;
+ pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
+
+ /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
+ ** or more tokens in zDoc/nDoc.
+ */
+ rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
+ const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
+ rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
+ }
+ pMod->xClose(pC);
+ if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
+
+ nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
+ assert( nShift<=nDesired );
+ if( nShift>0 ){
+ *piPos += nShift;
+ *pHlmask = hlmask >> nShift;
+ }
+ }
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Extract the snippet text for fragment pFragment from cursor pCsr and
+** append it to string buffer pOut.
+*/
+static int fts3SnippetText(
+ Fts3Cursor *pCsr, /* FTS3 Cursor */
+ SnippetFragment *pFragment, /* Snippet to extract */
+ int iFragment, /* Fragment number */
+ int isLast, /* True for final fragment in snippet */
+ int nSnippet, /* Number of tokens in extracted snippet */
+ const char *zOpen, /* String inserted before highlighted term */
+ const char *zClose, /* String inserted after highlighted term */
+ const char *zEllipsis, /* String inserted between snippets */
+ StrBuffer *pOut /* Write output here */
+){
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+ int rc; /* Return code */
+ const char *zDoc; /* Document text to extract snippet from */
+ int nDoc; /* Size of zDoc in bytes */
+ int iCurrent = 0; /* Current token number of document */
+ int iEnd = 0; /* Byte offset of end of current token */
+ int isShiftDone = 0; /* True after snippet is shifted */
+ int iPos = pFragment->iPos; /* First token of snippet */
+ u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
+ int iCol = pFragment->iCol+1; /* Query column to extract text from */
+ sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
+ sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
+
+ zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
+ if( zDoc==0 ){
+ if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
+ return SQLITE_NOMEM;
+ }
+ return SQLITE_OK;
+ }
+ nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
+
+ /* Open a token cursor on the document. */
+ pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
+ rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+
+ while( rc==SQLITE_OK ){
+ const char *ZDUMMY; /* Dummy argument used with tokenizer */
+ int DUMMY1 = -1; /* Dummy argument used with tokenizer */
+ int iBegin = 0; /* Offset in zDoc of start of token */
+ int iFin = 0; /* Offset in zDoc of end of token */
+ int isHighlight = 0; /* True for highlighted terms */
+
+ /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
+ ** in the FTS code the variable that the third argument to xNext points to
+ ** is initialized to zero before the first (*but not necessarily
+ ** subsequent*) call to xNext(). This is done for a particular application
+ ** that needs to know whether or not the tokenizer is being used for
+ ** snippet generation or for some other purpose.
+ **
+ ** Extreme care is required when writing code to depend on this
+ ** initialization. It is not a documented part of the tokenizer interface.
+ ** If a tokenizer is used directly by any code outside of FTS, this
+ ** convention might not be respected. */
+ rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
+ if( rc!=SQLITE_OK ){
+ if( rc==SQLITE_DONE ){
+ /* Special case - the last token of the snippet is also the last token
+ ** of the column. Append any punctuation that occurred between the end
+ ** of the previous token and the end of the document to the output.
+ ** Then break out of the loop. */
+ rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
+ }
+ break;
+ }
+ if( iCurrent<iPos ){ continue; }
+
+ if( !isShiftDone ){
+ int n = nDoc - iBegin;
+ rc = fts3SnippetShift(
+ pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
+ );
+ isShiftDone = 1;
+
+ /* Now that the shift has been done, check if the initial "..." are
+ ** required. They are required if (a) this is not the first fragment,
+ ** or (b) this fragment does not begin at position 0 of its column.
+ */
+ if( rc==SQLITE_OK ){
+ if( iPos>0 || iFragment>0 ){
+ rc = fts3StringAppend(pOut, zEllipsis, -1);
+ }else if( iBegin ){
+ rc = fts3StringAppend(pOut, zDoc, iBegin);
+ }
+ }
+ if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
+ }
+
+ if( iCurrent>=(iPos+nSnippet) ){
+ if( isLast ){
+ rc = fts3StringAppend(pOut, zEllipsis, -1);
+ }
+ break;
+ }
+
+ /* Set isHighlight to true if this term should be highlighted. */
+ isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
+
+ if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
+ if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
+ if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
+ if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
+
+ iEnd = iFin;
+ }
+
+ pMod->xClose(pC);
+ return rc;
+}
+
+
+/*
+** This function is used to count the entries in a column-list (a
+** delta-encoded list of term offsets within a single column of a single
+** row). When this function is called, *ppCollist should point to the
+** beginning of the first varint in the column-list (the varint that
+** contains the position of the first matching term in the column data).
+** Before returning, *ppCollist is set to point to the first byte after
+** the last varint in the column-list (either the 0x00 signifying the end
+** of the position-list, or the 0x01 that precedes the column number of
+** the next column in the position-list).
+**
+** The number of elements in the column-list is returned.
+*/
+static int fts3ColumnlistCount(char **ppCollist){
+ char *pEnd = *ppCollist;
+ char c = 0;
+ int nEntry = 0;
+
+ /* A column-list is terminated by either a 0x01 or 0x00. */
+ while( 0xFE & (*pEnd | c) ){
+ c = *pEnd++ & 0x80;
+ if( !c ) nEntry++;
+ }
+
+ *ppCollist = pEnd;
+ return nEntry;
+}
+
+/*
+** This function gathers 'y' or 'b' data for a single phrase.
+*/
+static int fts3ExprLHits(
+ Fts3Expr *pExpr, /* Phrase expression node */
+ MatchInfo *p /* Matchinfo context */
+){
+ Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
+ int iStart;
+ Fts3Phrase *pPhrase = pExpr->pPhrase;
+ char *pIter = pPhrase->doclist.pList;
+ int iCol = 0;
+
+ assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
+ if( p->flag==FTS3_MATCHINFO_LHITS ){
+ iStart = pExpr->iPhrase * p->nCol;
+ }else{
+ iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
+ }
+
+ if( pIter ) while( 1 ){
+ int nHit = fts3ColumnlistCount(&pIter);
+ if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
+ if( p->flag==FTS3_MATCHINFO_LHITS ){
+ p->aMatchinfo[iStart + iCol] = (u32)nHit;
+ }else if( nHit ){
+ p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
+ }
+ }
+ assert( *pIter==0x00 || *pIter==0x01 );
+ if( *pIter!=0x01 ) break;
+ pIter++;
+ pIter += fts3GetVarint32(pIter, &iCol);
+ if( iCol>=p->nCol ) return FTS_CORRUPT_VTAB;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Gather the results for matchinfo directives 'y' and 'b'.
+*/
+static int fts3ExprLHitGather(
+ Fts3Expr *pExpr,
+ MatchInfo *p
+){
+ int rc = SQLITE_OK;
+ assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
+ if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
+ if( pExpr->pLeft ){
+ rc = fts3ExprLHitGather(pExpr->pLeft, p);
+ if( rc==SQLITE_OK ) rc = fts3ExprLHitGather(pExpr->pRight, p);
+ }else{
+ rc = fts3ExprLHits(pExpr, p);
+ }
+ }
+ return rc;
+}
+
+/*
+** fts3ExprIterate() callback used to collect the "global" matchinfo stats
+** for a single query.
+**
+** fts3ExprIterate() callback to load the 'global' elements of a
+** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
+** of the matchinfo array that are constant for all rows returned by the
+** current query.
+**
+** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
+** function populates Matchinfo.aMatchinfo[] as follows:
+**
+** for(iCol=0; iCol<nCol; iCol++){
+** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
+** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
+** }
+**
+** where X is the number of matches for phrase iPhrase is column iCol of all
+** rows of the table. Y is the number of rows for which column iCol contains
+** at least one instance of phrase iPhrase.
+**
+** If the phrase pExpr consists entirely of deferred tokens, then all X and
+** Y values are set to nDoc, where nDoc is the number of documents in the
+** file system. This is done because the full-text index doclist is required
+** to calculate these values properly, and the full-text index doclist is
+** not available for deferred tokens.
+*/
+static int fts3ExprGlobalHitsCb(
+ Fts3Expr *pExpr, /* Phrase expression node */
+ int iPhrase, /* Phrase number (numbered from zero) */
+ void *pCtx /* Pointer to MatchInfo structure */
+){
+ MatchInfo *p = (MatchInfo *)pCtx;
+ return sqlite3Fts3EvalPhraseStats(
+ p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
+ );
+}
+
+/*
+** fts3ExprIterate() callback used to collect the "local" part of the
+** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
+** array that are different for each row returned by the query.
+*/
+static int fts3ExprLocalHitsCb(
+ Fts3Expr *pExpr, /* Phrase expression node */
+ int iPhrase, /* Phrase number */
+ void *pCtx /* Pointer to MatchInfo structure */
+){
+ int rc = SQLITE_OK;
+ MatchInfo *p = (MatchInfo *)pCtx;
+ int iStart = iPhrase * p->nCol * 3;
+ int i;
+
+ for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
+ char *pCsr;
+ rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
+ if( pCsr ){
+ p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
+ }else{
+ p->aMatchinfo[iStart+i*3] = 0;
+ }
+ }
+
+ return rc;
+}
+
+static int fts3MatchinfoCheck(
+ Fts3Table *pTab,
+ char cArg,
+ char **pzErr
+){
+ if( (cArg==FTS3_MATCHINFO_NPHRASE)
+ || (cArg==FTS3_MATCHINFO_NCOL)
+ || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
+ || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
+ || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
+ || (cArg==FTS3_MATCHINFO_LCS)
+ || (cArg==FTS3_MATCHINFO_HITS)
+ || (cArg==FTS3_MATCHINFO_LHITS)
+ || (cArg==FTS3_MATCHINFO_LHITS_BM)
+ ){
+ return SQLITE_OK;
+ }
+ sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
+ return SQLITE_ERROR;
+}
+
+static size_t fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
+ size_t nVal; /* Number of integers output by cArg */
+
+ switch( cArg ){
+ case FTS3_MATCHINFO_NDOC:
+ case FTS3_MATCHINFO_NPHRASE:
+ case FTS3_MATCHINFO_NCOL:
+ nVal = 1;
+ break;
+
+ case FTS3_MATCHINFO_AVGLENGTH:
+ case FTS3_MATCHINFO_LENGTH:
+ case FTS3_MATCHINFO_LCS:
+ nVal = pInfo->nCol;
+ break;
+
+ case FTS3_MATCHINFO_LHITS:
+ nVal = pInfo->nCol * pInfo->nPhrase;
+ break;
+
+ case FTS3_MATCHINFO_LHITS_BM:
+ nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
+ break;
+
+ default:
+ assert( cArg==FTS3_MATCHINFO_HITS );
+ nVal = pInfo->nCol * pInfo->nPhrase * 3;
+ break;
+ }
+
+ return nVal;
+}
+
+static int fts3MatchinfoSelectDoctotal(
+ Fts3Table *pTab,
+ sqlite3_stmt **ppStmt,
+ sqlite3_int64 *pnDoc,
+ const char **paLen,
+ const char **ppEnd
+){
+ sqlite3_stmt *pStmt;
+ const char *a;
+ const char *pEnd;
+ sqlite3_int64 nDoc;
+ int n;
+
+
+ if( !*ppStmt ){
+ int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
+ if( rc!=SQLITE_OK ) return rc;
+ }
+ pStmt = *ppStmt;
+ assert( sqlite3_data_count(pStmt)==1 );
+
+ n = sqlite3_column_bytes(pStmt, 0);
+ a = sqlite3_column_blob(pStmt, 0);
+ if( a==0 ){
+ return FTS_CORRUPT_VTAB;
+ }
+ pEnd = a + n;
+ a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc);
+ if( nDoc<=0 || a>pEnd ){
+ return FTS_CORRUPT_VTAB;
+ }
+ *pnDoc = nDoc;
+
+ if( paLen ) *paLen = a;
+ if( ppEnd ) *ppEnd = pEnd;
+ return SQLITE_OK;
+}
+
+/*
+** An instance of the following structure is used to store state while
+** iterating through a multi-column position-list corresponding to the
+** hits for a single phrase on a single row in order to calculate the
+** values for a matchinfo() FTS3_MATCHINFO_LCS request.
+*/
+typedef struct LcsIterator LcsIterator;
+struct LcsIterator {
+ Fts3Expr *pExpr; /* Pointer to phrase expression */
+ int iPosOffset; /* Tokens count up to end of this phrase */
+ char *pRead; /* Cursor used to iterate through aDoclist */
+ int iPos; /* Current position */
+};
+
+/*
+** If LcsIterator.iCol is set to the following value, the iterator has
+** finished iterating through all offsets for all columns.
+*/
+#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
+
+static int fts3MatchinfoLcsCb(
+ Fts3Expr *pExpr, /* Phrase expression node */
+ int iPhrase, /* Phrase number (numbered from zero) */
+ void *pCtx /* Pointer to MatchInfo structure */
+){
+ LcsIterator *aIter = (LcsIterator *)pCtx;
+ aIter[iPhrase].pExpr = pExpr;
+ return SQLITE_OK;
+}
+
+/*
+** Advance the iterator passed as an argument to the next position. Return
+** 1 if the iterator is at EOF or if it now points to the start of the
+** position list for the next column.
+*/
+static int fts3LcsIteratorAdvance(LcsIterator *pIter){
+ char *pRead = pIter->pRead;
+ sqlite3_int64 iRead;
+ int rc = 0;
+
+ pRead += sqlite3Fts3GetVarint(pRead, &iRead);
+ if( iRead==0 || iRead==1 ){
+ pRead = 0;
+ rc = 1;
+ }else{
+ pIter->iPos += (int)(iRead-2);
+ }
+
+ pIter->pRead = pRead;
+ return rc;
+}
+
+/*
+** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
+**
+** If the call is successful, the longest-common-substring lengths for each
+** column are written into the first nCol elements of the pInfo->aMatchinfo[]
+** array before returning. SQLITE_OK is returned in this case.
+**
+** Otherwise, if an error occurs, an SQLite error code is returned and the
+** data written to the first nCol elements of pInfo->aMatchinfo[] is
+** undefined.
+*/
+static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
+ LcsIterator *aIter;
+ int i;
+ int iCol;
+ int nToken = 0;
+ int rc = SQLITE_OK;
+
+ /* Allocate and populate the array of LcsIterator objects. The array
+ ** contains one element for each matchable phrase in the query.
+ **/
+ aIter = sqlite3_malloc64(sizeof(LcsIterator) * pCsr->nPhrase);
+ if( !aIter ) return SQLITE_NOMEM;
+ memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
+ (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
+
+ for(i=0; i<pInfo->nPhrase; i++){
+ LcsIterator *pIter = &aIter[i];
+ nToken -= pIter->pExpr->pPhrase->nToken;
+ pIter->iPosOffset = nToken;
+ }
+
+ for(iCol=0; iCol<pInfo->nCol; iCol++){
+ int nLcs = 0; /* LCS value for this column */
+ int nLive = 0; /* Number of iterators in aIter not at EOF */
+
+ for(i=0; i<pInfo->nPhrase; i++){
+ LcsIterator *pIt = &aIter[i];
+ rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
+ if( rc!=SQLITE_OK ) goto matchinfo_lcs_out;
+ if( pIt->pRead ){
+ pIt->iPos = pIt->iPosOffset;
+ fts3LcsIteratorAdvance(pIt);
+ if( pIt->pRead==0 ){
+ rc = FTS_CORRUPT_VTAB;
+ goto matchinfo_lcs_out;
+ }
+ nLive++;
+ }
+ }
+
+ while( nLive>0 ){
+ LcsIterator *pAdv = 0; /* The iterator to advance by one position */
+ int nThisLcs = 0; /* LCS for the current iterator positions */
+
+ for(i=0; i<pInfo->nPhrase; i++){
+ LcsIterator *pIter = &aIter[i];
+ if( pIter->pRead==0 ){
+ /* This iterator is already at EOF for this column. */
+ nThisLcs = 0;
+ }else{
+ if( pAdv==0 || pIter->iPos<pAdv->iPos ){
+ pAdv = pIter;
+ }
+ if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
+ nThisLcs++;
+ }else{
+ nThisLcs = 1;
+ }
+ if( nThisLcs>nLcs ) nLcs = nThisLcs;
+ }
+ }
+ if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
+ }
+
+ pInfo->aMatchinfo[iCol] = nLcs;
+ }
+
+ matchinfo_lcs_out:
+ sqlite3_free(aIter);
+ return rc;
+}
+
+/*
+** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
+** be returned by the matchinfo() function. Argument zArg contains the
+** format string passed as the second argument to matchinfo (or the
+** default value "pcx" if no second argument was specified). The format
+** string has already been validated and the pInfo->aMatchinfo[] array
+** is guaranteed to be large enough for the output.
+**
+** If bGlobal is true, then populate all fields of the matchinfo() output.
+** If it is false, then assume that those fields that do not change between
+** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
+** have already been populated.
+**
+** Return SQLITE_OK if successful, or an SQLite error code if an error
+** occurs. If a value other than SQLITE_OK is returned, the state the
+** pInfo->aMatchinfo[] buffer is left in is undefined.
+*/
+static int fts3MatchinfoValues(
+ Fts3Cursor *pCsr, /* FTS3 cursor object */
+ int bGlobal, /* True to grab the global stats */
+ MatchInfo *pInfo, /* Matchinfo context object */
+ const char *zArg /* Matchinfo format string */
+){
+ int rc = SQLITE_OK;
+ int i;
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+ sqlite3_stmt *pSelect = 0;
+
+ for(i=0; rc==SQLITE_OK && zArg[i]; i++){
+ pInfo->flag = zArg[i];
+ switch( zArg[i] ){
+ case FTS3_MATCHINFO_NPHRASE:
+ if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
+ break;
+
+ case FTS3_MATCHINFO_NCOL:
+ if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
+ break;
+
+ case FTS3_MATCHINFO_NDOC:
+ if( bGlobal ){
+ sqlite3_int64 nDoc = 0;
+ rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0, 0);
+ pInfo->aMatchinfo[0] = (u32)nDoc;
+ }
+ break;
+
+ case FTS3_MATCHINFO_AVGLENGTH:
+ if( bGlobal ){
+ sqlite3_int64 nDoc; /* Number of rows in table */
+ const char *a; /* Aggregate column length array */
+ const char *pEnd; /* First byte past end of length array */
+
+ rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a, &pEnd);
+ if( rc==SQLITE_OK ){
+ int iCol;
+ for(iCol=0; iCol<pInfo->nCol; iCol++){
+ u32 iVal;
+ sqlite3_int64 nToken;
+ a += sqlite3Fts3GetVarint(a, &nToken);
+ if( a>pEnd ){
+ rc = SQLITE_CORRUPT_VTAB;
+ break;
+ }
+ iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
+ pInfo->aMatchinfo[iCol] = iVal;
+ }
+ }
+ }
+ break;
+
+ case FTS3_MATCHINFO_LENGTH: {
+ sqlite3_stmt *pSelectDocsize = 0;
+ rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
+ if( rc==SQLITE_OK ){
+ int iCol;
+ const char *a = sqlite3_column_blob(pSelectDocsize, 0);
+ const char *pEnd = a + sqlite3_column_bytes(pSelectDocsize, 0);
+ for(iCol=0; iCol<pInfo->nCol; iCol++){
+ sqlite3_int64 nToken;
+ a += sqlite3Fts3GetVarintBounded(a, pEnd, &nToken);
+ if( a>pEnd ){
+ rc = SQLITE_CORRUPT_VTAB;
+ break;
+ }
+ pInfo->aMatchinfo[iCol] = (u32)nToken;
+ }
+ }
+ sqlite3_reset(pSelectDocsize);
+ break;
+ }
+
+ case FTS3_MATCHINFO_LCS:
+ rc = fts3ExprLoadDoclists(pCsr, 0, 0);
+ if( rc==SQLITE_OK ){
+ rc = fts3MatchinfoLcs(pCsr, pInfo);
+ }
+ break;
+
+ case FTS3_MATCHINFO_LHITS_BM:
+ case FTS3_MATCHINFO_LHITS: {
+ size_t nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
+ memset(pInfo->aMatchinfo, 0, nZero);
+ rc = fts3ExprLHitGather(pCsr->pExpr, pInfo);
+ break;
+ }
+
+ default: {
+ Fts3Expr *pExpr;
+ assert( zArg[i]==FTS3_MATCHINFO_HITS );
+ pExpr = pCsr->pExpr;
+ rc = fts3ExprLoadDoclists(pCsr, 0, 0);
+ if( rc!=SQLITE_OK ) break;
+ if( bGlobal ){
+ if( pCsr->pDeferred ){
+ rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc,0,0);
+ if( rc!=SQLITE_OK ) break;
+ }
+ rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
+ sqlite3Fts3EvalTestDeferred(pCsr, &rc);
+ if( rc!=SQLITE_OK ) break;
+ }
+ (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
+ break;
+ }
+ }
+
+ pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
+ }
+
+ sqlite3_reset(pSelect);
+ return rc;
+}
+
+
+/*
+** Populate pCsr->aMatchinfo[] with data for the current row. The
+** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
+*/
+static void fts3GetMatchinfo(
+ sqlite3_context *pCtx, /* Return results here */
+ Fts3Cursor *pCsr, /* FTS3 Cursor object */
+ const char *zArg /* Second argument to matchinfo() function */
+){
+ MatchInfo sInfo;
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+ int rc = SQLITE_OK;
+ int bGlobal = 0; /* Collect 'global' stats as well as local */
+
+ u32 *aOut = 0;
+ void (*xDestroyOut)(void*) = 0;
+
+ memset(&sInfo, 0, sizeof(MatchInfo));
+ sInfo.pCursor = pCsr;
+ sInfo.nCol = pTab->nColumn;
+
+ /* If there is cached matchinfo() data, but the format string for the
+ ** cache does not match the format string for this request, discard
+ ** the cached data. */
+ if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
+ sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
+ pCsr->pMIBuffer = 0;
+ }
+
+ /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
+ ** matchinfo function has been called for this query. In this case
+ ** allocate the array used to accumulate the matchinfo data and
+ ** initialize those elements that are constant for every row.
+ */
+ if( pCsr->pMIBuffer==0 ){
+ size_t nMatchinfo = 0; /* Number of u32 elements in match-info */
+ int i; /* Used to iterate through zArg */
+
+ /* Determine the number of phrases in the query */
+ pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
+ sInfo.nPhrase = pCsr->nPhrase;
+
+ /* Determine the number of integers in the buffer returned by this call. */
+ for(i=0; zArg[i]; i++){
+ char *zErr = 0;
+ if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
+ sqlite3_result_error(pCtx, zErr, -1);
+ sqlite3_free(zErr);
+ return;
+ }
+ nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
+ }
+
+ /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
+ pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
+ if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
+
+ pCsr->isMatchinfoNeeded = 1;
+ bGlobal = 1;
+ }
+
+ if( rc==SQLITE_OK ){
+ xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
+ if( xDestroyOut==0 ){
+ rc = SQLITE_NOMEM;
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ sInfo.aMatchinfo = aOut;
+ sInfo.nPhrase = pCsr->nPhrase;
+ rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
+ if( bGlobal ){
+ fts3MIBufferSetGlobal(pCsr->pMIBuffer);
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ sqlite3_result_error_code(pCtx, rc);
+ if( xDestroyOut ) xDestroyOut(aOut);
+ }else{
+ int n = pCsr->pMIBuffer->nElem * sizeof(u32);
+ sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
+ }
+}
+
+/*
+** Implementation of snippet() function.
+*/
+SQLITE_PRIVATE void sqlite3Fts3Snippet(
+ sqlite3_context *pCtx, /* SQLite function call context */
+ Fts3Cursor *pCsr, /* Cursor object */
+ const char *zStart, /* Snippet start text - "<b>" */
+ const char *zEnd, /* Snippet end text - "</b>" */
+ const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
+ int iCol, /* Extract snippet from this column */
+ int nToken /* Approximate number of tokens in snippet */
+){
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+ int rc = SQLITE_OK;
+ int i;
+ StrBuffer res = {0, 0, 0};
+
+ /* The returned text includes up to four fragments of text extracted from
+ ** the data in the current row. The first iteration of the for(...) loop
+ ** below attempts to locate a single fragment of text nToken tokens in
+ ** size that contains at least one instance of all phrases in the query
+ ** expression that appear in the current row. If such a fragment of text
+ ** cannot be found, the second iteration of the loop attempts to locate
+ ** a pair of fragments, and so on.
+ */
+ int nSnippet = 0; /* Number of fragments in this snippet */
+ SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
+ int nFToken = -1; /* Number of tokens in each fragment */
+
+ if( !pCsr->pExpr ){
+ sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
+ return;
+ }
+
+ /* Limit the snippet length to 64 tokens. */
+ if( nToken<-64 ) nToken = -64;
+ if( nToken>+64 ) nToken = +64;
+
+ for(nSnippet=1; 1; nSnippet++){
+
+ int iSnip; /* Loop counter 0..nSnippet-1 */
+ u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
+ u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
+
+ if( nToken>=0 ){
+ nFToken = (nToken+nSnippet-1) / nSnippet;
+ }else{
+ nFToken = -1 * nToken;
+ }
+
+ for(iSnip=0; iSnip<nSnippet; iSnip++){
+ int iBestScore = -1; /* Best score of columns checked so far */
+ int iRead; /* Used to iterate through columns */
+ SnippetFragment *pFragment = &aSnippet[iSnip];
+
+ memset(pFragment, 0, sizeof(*pFragment));
+
+ /* Loop through all columns of the table being considered for snippets.
+ ** If the iCol argument to this function was negative, this means all
+ ** columns of the FTS3 table. Otherwise, only column iCol is considered.
+ */
+ for(iRead=0; iRead<pTab->nColumn; iRead++){
+ SnippetFragment sF = {0, 0, 0, 0};
+ int iS = 0;
+ if( iCol>=0 && iRead!=iCol ) continue;
+
+ /* Find the best snippet of nFToken tokens in column iRead. */
+ rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
+ if( rc!=SQLITE_OK ){
+ goto snippet_out;
+ }
+ if( iS>iBestScore ){
+ *pFragment = sF;
+ iBestScore = iS;
+ }
+ }
+
+ mCovered |= pFragment->covered;
+ }
+
+ /* If all query phrases seen by fts3BestSnippet() are present in at least
+ ** one of the nSnippet snippet fragments, break out of the loop.
+ */
+ assert( (mCovered&mSeen)==mCovered );
+ if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
+ }
+
+ assert( nFToken>0 );
+
+ for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
+ rc = fts3SnippetText(pCsr, &aSnippet[i],
+ i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
+ );
+ }
+
+ snippet_out:
+ sqlite3Fts3SegmentsClose(pTab);
+ if( rc!=SQLITE_OK ){
+ sqlite3_result_error_code(pCtx, rc);
+ sqlite3_free(res.z);
+ }else{
+ sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
+ }
+}
+
+
+typedef struct TermOffset TermOffset;
+typedef struct TermOffsetCtx TermOffsetCtx;
+
+struct TermOffset {
+ char *pList; /* Position-list */
+ int iPos; /* Position just read from pList */
+ int iOff; /* Offset of this term from read positions */
+};
+
+struct TermOffsetCtx {
+ Fts3Cursor *pCsr;
+ int iCol; /* Column of table to populate aTerm for */
+ int iTerm;
+ sqlite3_int64 iDocid;
+ TermOffset *aTerm;
+};
+
+/*
+** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
+*/
+static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
+ TermOffsetCtx *p = (TermOffsetCtx *)ctx;
+ int nTerm; /* Number of tokens in phrase */
+ int iTerm; /* For looping through nTerm phrase terms */
+ char *pList; /* Pointer to position list for phrase */
+ int iPos = 0; /* First position in position-list */
+ int rc;
+
+ UNUSED_PARAMETER(iPhrase);
+ rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
+ nTerm = pExpr->pPhrase->nToken;
+ if( pList ){
+ fts3GetDeltaPosition(&pList, &iPos);
+ assert_fts3_nc( iPos>=0 );
+ }
+
+ for(iTerm=0; iTerm<nTerm; iTerm++){
+ TermOffset *pT = &p->aTerm[p->iTerm++];
+ pT->iOff = nTerm-iTerm-1;
+ pT->pList = pList;
+ pT->iPos = iPos;
+ }
+
+ return rc;
+}
+
+/*
+** Implementation of offsets() function.
+*/
+SQLITE_PRIVATE void sqlite3Fts3Offsets(
+ sqlite3_context *pCtx, /* SQLite function call context */
+ Fts3Cursor *pCsr /* Cursor object */
+){
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+ sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
+ int rc; /* Return Code */
+ int nToken; /* Number of tokens in query */
+ int iCol; /* Column currently being processed */
+ StrBuffer res = {0, 0, 0}; /* Result string */
+ TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
+
+ if( !pCsr->pExpr ){
+ sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
+ return;
+ }
+
+ memset(&sCtx, 0, sizeof(sCtx));
+ assert( pCsr->isRequireSeek==0 );
+
+ /* Count the number of terms in the query */
+ rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
+ if( rc!=SQLITE_OK ) goto offsets_out;
+
+ /* Allocate the array of TermOffset iterators. */
+ sCtx.aTerm = (TermOffset *)sqlite3_malloc64(sizeof(TermOffset)*nToken);
+ if( 0==sCtx.aTerm ){
+ rc = SQLITE_NOMEM;
+ goto offsets_out;
+ }
+ sCtx.iDocid = pCsr->iPrevId;
+ sCtx.pCsr = pCsr;
+
+ /* Loop through the table columns, appending offset information to
+ ** string-buffer res for each column.
+ */
+ for(iCol=0; iCol<pTab->nColumn; iCol++){
+ sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
+ const char *ZDUMMY; /* Dummy argument used with xNext() */
+ int NDUMMY = 0; /* Dummy argument used with xNext() */
+ int iStart = 0;
+ int iEnd = 0;
+ int iCurrent = 0;
+ const char *zDoc;
+ int nDoc;
+
+ /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
+ ** no way that this operation can fail, so the return code from
+ ** fts3ExprIterate() can be discarded.
+ */
+ sCtx.iCol = iCol;
+ sCtx.iTerm = 0;
+ (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
+
+ /* Retreive the text stored in column iCol. If an SQL NULL is stored
+ ** in column iCol, jump immediately to the next iteration of the loop.
+ ** If an OOM occurs while retrieving the data (this can happen if SQLite
+ ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
+ ** to the caller.
+ */
+ zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
+ nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
+ if( zDoc==0 ){
+ if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
+ continue;
+ }
+ rc = SQLITE_NOMEM;
+ goto offsets_out;
+ }
+
+ /* Initialize a tokenizer iterator to iterate through column iCol. */
+ rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
+ zDoc, nDoc, &pC
+ );
+ if( rc!=SQLITE_OK ) goto offsets_out;
+
+ rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
+ while( rc==SQLITE_OK ){
+ int i; /* Used to loop through terms */
+ int iMinPos = 0x7FFFFFFF; /* Position of next token */
+ TermOffset *pTerm = 0; /* TermOffset associated with next token */
+
+ for(i=0; i<nToken; i++){
+ TermOffset *pT = &sCtx.aTerm[i];
+ if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
+ iMinPos = pT->iPos-pT->iOff;
+ pTerm = pT;
+ }
+ }
+
+ if( !pTerm ){
+ /* All offsets for this column have been gathered. */
+ rc = SQLITE_DONE;
+ }else{
+ assert_fts3_nc( iCurrent<=iMinPos );
+ if( 0==(0xFE&*pTerm->pList) ){
+ pTerm->pList = 0;
+ }else{
+ fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
+ }
+ while( rc==SQLITE_OK && iCurrent<iMinPos ){
+ rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
+ }
+ if( rc==SQLITE_OK ){
+ char aBuffer[64];
+ sqlite3_snprintf(sizeof(aBuffer), aBuffer,
+ "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
+ );
+ rc = fts3StringAppend(&res, aBuffer, -1);
+ }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
+ rc = FTS_CORRUPT_VTAB;
+ }
+ }
+ }
+ if( rc==SQLITE_DONE ){
+ rc = SQLITE_OK;
+ }
+
+ pMod->xClose(pC);
+ if( rc!=SQLITE_OK ) goto offsets_out;
+ }
+
+ offsets_out:
+ sqlite3_free(sCtx.aTerm);
+ assert( rc!=SQLITE_DONE );
+ sqlite3Fts3SegmentsClose(pTab);
+ if( rc!=SQLITE_OK ){
+ sqlite3_result_error_code(pCtx, rc);
+ sqlite3_free(res.z);
+ }else{
+ sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
+ }
+ return;
+}
+
+/*
+** Implementation of matchinfo() function.
+*/
+SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
+ sqlite3_context *pContext, /* Function call context */
+ Fts3Cursor *pCsr, /* FTS3 table cursor */
+ const char *zArg /* Second arg to matchinfo() function */
+){
+ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
+ const char *zFormat;
+
+ if( zArg ){
+ zFormat = zArg;
+ }else{
+ zFormat = FTS3_MATCHINFO_DEFAULT;
+ }
+
+ if( !pCsr->pExpr ){
+ sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
+ return;
+ }else{
+ /* Retrieve matchinfo() data. */
+ fts3GetMatchinfo(pContext, pCsr, zFormat);
+ sqlite3Fts3SegmentsClose(pTab);
+ }
+}
+
+#endif
+
+/************** End of fts3_snippet.c ****************************************/
+/************** Begin file fts3_unicode.c ************************************/
+/*
+** 2012 May 24
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** Implementation of the "unicode" full-text-search tokenizer.
+*/
+
+#ifndef SQLITE_DISABLE_FTS3_UNICODE
+
+/* #include "fts3Int.h" */
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
+
+/* #include <assert.h> */
+/* #include <stdlib.h> */
+/* #include <stdio.h> */
+/* #include <string.h> */
+
+/* #include "fts3_tokenizer.h" */
+
+/*
+** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
+** from the sqlite3 source file utf.c. If this file is compiled as part
+** of the amalgamation, they are not required.
+*/
+#ifndef SQLITE_AMALGAMATION
+
+static const unsigned char sqlite3Utf8Trans1[] = {
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
+ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
+};
+
+#define READ_UTF8(zIn, zTerm, c) \
+ c = *(zIn++); \
+ if( c>=0xc0 ){ \
+ c = sqlite3Utf8Trans1[c-0xc0]; \
+ while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
+ c = (c<<6) + (0x3f & *(zIn++)); \
+ } \
+ if( c<0x80 \
+ || (c&0xFFFFF800)==0xD800 \
+ || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
+ }
+
+#define WRITE_UTF8(zOut, c) { \
+ if( c<0x00080 ){ \
+ *zOut++ = (u8)(c&0xFF); \
+ } \
+ else if( c<0x00800 ){ \
+ *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
+ *zOut++ = 0x80 + (u8)(c & 0x3F); \
+ } \
+ else if( c<0x10000 ){ \
+ *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
+ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
+ *zOut++ = 0x80 + (u8)(c & 0x3F); \
+ }else{ \
+ *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
+ *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
+ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
+ *zOut++ = 0x80 + (u8)(c & 0x3F); \
+ } \
+}
+
+#endif /* ifndef SQLITE_AMALGAMATION */
+
+typedef struct unicode_tokenizer unicode_tokenizer;
+typedef struct unicode_cursor unicode_cursor;
+
+struct unicode_tokenizer {
+ sqlite3_tokenizer base;
+ int eRemoveDiacritic;
+ int nException;
+ int *aiException;
+};
+
+struct unicode_cursor {
+ sqlite3_tokenizer_cursor base;
+ const unsigned char *aInput; /* Input text being tokenized */
+ int nInput; /* Size of aInput[] in bytes */
+ int iOff; /* Current offset within aInput[] */
+ int iToken; /* Index of next token to be returned */
+ char *zToken; /* storage for current token */
+ int nAlloc; /* space allocated at zToken */
+};
+
+
+/*
+** Destroy a tokenizer allocated by unicodeCreate().
+*/
+static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
+ if( pTokenizer ){
+ unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
+ sqlite3_free(p->aiException);
+ sqlite3_free(p);
+ }
+ return SQLITE_OK;
+}
+
+/*
+** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
+** statement has specified that the tokenizer for this table shall consider
+** all characters in string zIn/nIn to be separators (if bAlnum==0) or
+** token characters (if bAlnum==1).
+**
+** For each codepoint in the zIn/nIn string, this function checks if the
+** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
+** If so, no action is taken. Otherwise, the codepoint is added to the
+** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
+** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
+** codepoints in the aiException[] array.
+**
+** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
+** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
+** It is not possible to change the behavior of the tokenizer with respect
+** to these codepoints.
+*/
+static int unicodeAddExceptions(
+ unicode_tokenizer *p, /* Tokenizer to add exceptions to */
+ int bAlnum, /* Replace Isalnum() return value with this */
+ const char *zIn, /* Array of characters to make exceptions */
+ int nIn /* Length of z in bytes */
+){
+ const unsigned char *z = (const unsigned char *)zIn;
+ const unsigned char *zTerm = &z[nIn];
+ unsigned int iCode;
+ int nEntry = 0;
+
+ assert( bAlnum==0 || bAlnum==1 );
+
+ while( z<zTerm ){
+ READ_UTF8(z, zTerm, iCode);
+ assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
+ if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
+ && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
+ ){
+ nEntry++;
+ }
+ }
+
+ if( nEntry ){
+ int *aNew; /* New aiException[] array */
+ int nNew; /* Number of valid entries in array aNew[] */
+
+ aNew = sqlite3_realloc64(p->aiException,(p->nException+nEntry)*sizeof(int));
+ if( aNew==0 ) return SQLITE_NOMEM;
+ nNew = p->nException;
+
+ z = (const unsigned char *)zIn;
+ while( z<zTerm ){
+ READ_UTF8(z, zTerm, iCode);
+ if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
+ && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
+ ){
+ int i, j;
+ for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
+ for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
+ aNew[i] = (int)iCode;
+ nNew++;
+ }
+ }
+ p->aiException = aNew;
+ p->nException = nNew;
+ }
+
+ return SQLITE_OK;
+}
+
+/*
+** Return true if the p->aiException[] array contains the value iCode.
+*/
+static int unicodeIsException(unicode_tokenizer *p, int iCode){
+ if( p->nException>0 ){
+ int *a = p->aiException;
+ int iLo = 0;
+ int iHi = p->nException-1;
+
+ while( iHi>=iLo ){
+ int iTest = (iHi + iLo) / 2;
+ if( iCode==a[iTest] ){
+ return 1;
+ }else if( iCode>a[iTest] ){
+ iLo = iTest+1;
+ }else{
+ iHi = iTest-1;
+ }
+ }
+ }
+
+ return 0;
+}
+
+/*
+** Return true if, for the purposes of tokenization, codepoint iCode is
+** considered a token character (not a separator).
+*/
+static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
+ assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
+ return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
+}
+
+/*
+** Create a new tokenizer instance.
+*/
+static int unicodeCreate(
+ int nArg, /* Size of array argv[] */
+ const char * const *azArg, /* Tokenizer creation arguments */
+ sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
+){
+ unicode_tokenizer *pNew; /* New tokenizer object */
+ int i;
+ int rc = SQLITE_OK;
+
+ pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
+ if( pNew==NULL ) return SQLITE_NOMEM;
+ memset(pNew, 0, sizeof(unicode_tokenizer));
+ pNew->eRemoveDiacritic = 1;
+
+ for(i=0; rc==SQLITE_OK && i<nArg; i++){
+ const char *z = azArg[i];
+ int n = (int)strlen(z);
+
+ if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
+ pNew->eRemoveDiacritic = 1;
+ }
+ else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
+ pNew->eRemoveDiacritic = 0;
+ }
+ else if( n==19 && memcmp("remove_diacritics=2", z, 19)==0 ){
+ pNew->eRemoveDiacritic = 2;
+ }
+ else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
+ rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
+ }
+ else if( n>=11 && memcmp("separators=", z, 11)==0 ){
+ rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
+ }
+ else{
+ /* Unrecognized argument */
+ rc = SQLITE_ERROR;
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ unicodeDestroy((sqlite3_tokenizer *)pNew);
+ pNew = 0;
+ }
+ *pp = (sqlite3_tokenizer *)pNew;
+ return rc;
+}
+
+/*
+** Prepare to begin tokenizing a particular string. The input
+** string to be tokenized is pInput[0..nBytes-1]. A cursor
+** used to incrementally tokenize this string is returned in
+** *ppCursor.
+*/
+static int unicodeOpen(
+ sqlite3_tokenizer *p, /* The tokenizer */
+ const char *aInput, /* Input string */
+ int nInput, /* Size of string aInput in bytes */
+ sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
+){
+ unicode_cursor *pCsr;
+
+ pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
+ if( pCsr==0 ){
+ return SQLITE_NOMEM;
+ }
+ memset(pCsr, 0, sizeof(unicode_cursor));
+
+ pCsr->aInput = (const unsigned char *)aInput;
+ if( aInput==0 ){
+ pCsr->nInput = 0;
+ }else if( nInput<0 ){
+ pCsr->nInput = (int)strlen(aInput);
+ }else{
+ pCsr->nInput = nInput;
+ }
+
+ *pp = &pCsr->base;
+ UNUSED_PARAMETER(p);
+ return SQLITE_OK;
+}
+
+/*
+** Close a tokenization cursor previously opened by a call to
+** simpleOpen() above.
+*/
+static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
+ unicode_cursor *pCsr = (unicode_cursor *) pCursor;
+ sqlite3_free(pCsr->zToken);
+ sqlite3_free(pCsr);
+ return SQLITE_OK;
+}
+
+/*
+** Extract the next token from a tokenization cursor. The cursor must
+** have been opened by a prior call to simpleOpen().
+*/
+static int unicodeNext(
+ sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
+ const char **paToken, /* OUT: Token text */
+ int *pnToken, /* OUT: Number of bytes at *paToken */
+ int *piStart, /* OUT: Starting offset of token */
+ int *piEnd, /* OUT: Ending offset of token */
+ int *piPos /* OUT: Position integer of token */
+){
+ unicode_cursor *pCsr = (unicode_cursor *)pC;
+ unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
+ unsigned int iCode = 0;
+ char *zOut;
+ const unsigned char *z = &pCsr->aInput[pCsr->iOff];
+ const unsigned char *zStart = z;
+ const unsigned char *zEnd;
+ const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
+
+ /* Scan past any delimiter characters before the start of the next token.
+ ** Return SQLITE_DONE early if this takes us all the way to the end of
+ ** the input. */
+ while( z<zTerm ){
+ READ_UTF8(z, zTerm, iCode);
+ if( unicodeIsAlnum(p, (int)iCode) ) break;
+ zStart = z;
+ }
+ if( zStart>=zTerm ) return SQLITE_DONE;
+
+ zOut = pCsr->zToken;
+ do {
+ int iOut;
+
+ /* Grow the output buffer if required. */
+ if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
+ char *zNew = sqlite3_realloc64(pCsr->zToken, pCsr->nAlloc+64);
+ if( !zNew ) return SQLITE_NOMEM;
+ zOut = &zNew[zOut - pCsr->zToken];
+ pCsr->zToken = zNew;
+ pCsr->nAlloc += 64;
+ }
+
+ /* Write the folded case of the last character read to the output */
+ zEnd = z;
+ iOut = sqlite3FtsUnicodeFold((int)iCode, p->eRemoveDiacritic);
+ if( iOut ){
+ WRITE_UTF8(zOut, iOut);
+ }
+
+ /* If the cursor is not at EOF, read the next character */
+ if( z>=zTerm ) break;
+ READ_UTF8(z, zTerm, iCode);
+ }while( unicodeIsAlnum(p, (int)iCode)
+ || sqlite3FtsUnicodeIsdiacritic((int)iCode)
+ );
+
+ /* Set the output variables and return. */
+ pCsr->iOff = (int)(z - pCsr->aInput);
+ *paToken = pCsr->zToken;
+ *pnToken = (int)(zOut - pCsr->zToken);
+ *piStart = (int)(zStart - pCsr->aInput);
+ *piEnd = (int)(zEnd - pCsr->aInput);
+ *piPos = pCsr->iToken++;
+ return SQLITE_OK;
+}
+
+/*
+** Set *ppModule to a pointer to the sqlite3_tokenizer_module
+** structure for the unicode tokenizer.
+*/
+SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
+ static const sqlite3_tokenizer_module module = {
+ 0,
+ unicodeCreate,
+ unicodeDestroy,
+ unicodeOpen,
+ unicodeClose,
+ unicodeNext,
+ 0,
+ };
+ *ppModule = &module;
+}
+
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
+#endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
+
+/************** End of fts3_unicode.c ****************************************/
+/************** Begin file fts3_unicode2.c ***********************************/
+/*
+** 2012-05-25
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+*/
+
+/*
+** DO NOT EDIT THIS MACHINE GENERATED FILE.
+*/
+
+#ifndef SQLITE_DISABLE_FTS3_UNICODE
+#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
+
+/* #include <assert.h> */
+
+/*
+** Return true if the argument corresponds to a unicode codepoint
+** classified as either a letter or a number. Otherwise false.
+**
+** The results are undefined if the value passed to this function
+** is less than zero.
+*/
+SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
+ /* Each unsigned integer in the following array corresponds to a contiguous
+ ** range of unicode codepoints that are not either letters or numbers (i.e.
+ ** codepoints for which this function should return 0).
+ **
+ ** The most significant 22 bits in each 32-bit value contain the first
+ ** codepoint in the range. The least significant 10 bits are used to store
+ ** the size of the range (always at least 1). In other words, the value
+ ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
+ ** C. It is not possible to represent a range larger than 1023 codepoints
+ ** using this format.
+ */
+ static const unsigned int aEntry[] = {
+ 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
+ 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
+ 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
+ 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
+ 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
+ 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
+ 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
+ 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
+ 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
+ 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
+ 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
+ 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
+ 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
+ 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
+ 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
+ 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
+ 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
+ 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
+ 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
+ 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
+ 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
+ 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
+ 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
+ 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
+ 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
+ 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
+ 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
+ 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
+ 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
+ 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
+ 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
+ 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
+ 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
+ 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
+ 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
+ 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
+ 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
+ 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
+ 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
+ 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
+ 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
+ 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
+ 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
+ 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
+ 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
+ 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
+ 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
+ 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
+ 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
+ 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
+ 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
+ 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
+ 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
+ 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
+ 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
+ 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
+ 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
+ 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
+ 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
+ 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
+ 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
+ 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
+ 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
+ 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
+ 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
+ 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
+ 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
+ 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
+ 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
+ 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
+ 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
+ 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
+ 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
+ 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
+ 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
+ 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
+ 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
+ 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
+ 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
+ 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
+ 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
+ 0x380400F0,
+ };
+ static const unsigned int aAscii[4] = {
+ 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
+ };
+
+ if( (unsigned int)c<128 ){
+ return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
+ }else if( (unsigned int)c<(1<<22) ){
+ unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
+ int iRes = 0;
+ int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
+ int iLo = 0;
+ while( iHi>=iLo ){
+ int iTest = (iHi + iLo) / 2;
+ if( key >= aEntry[iTest] ){
+ iRes = iTest;
+ iLo = iTest+1;
+ }else{
+ iHi = iTest-1;
+ }
+ }
+ assert( aEntry[0]<key );
+ assert( key>=aEntry[iRes] );
+ return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
+ }
+ return 1;
+}
+
+
+/*
+** If the argument is a codepoint corresponding to a lowercase letter
+** in the ASCII range with a diacritic added, return the codepoint
+** of the ASCII letter only. For example, if passed 235 - "LATIN
+** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
+** E"). The resuls of passing a codepoint that corresponds to an
+** uppercase letter are undefined.
+*/
+static int remove_diacritic(int c, int bComplex){
+ unsigned short aDia[] = {
+ 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
+ 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
+ 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
+ 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
+ 3456, 3696, 3712, 3728, 3744, 3766, 3832, 3896,
+ 3912, 3928, 3944, 3968, 4008, 4040, 4056, 4106,
+ 4138, 4170, 4202, 4234, 4266, 4296, 4312, 4344,
+ 4408, 4424, 4442, 4472, 4488, 4504, 6148, 6198,
+ 6264, 6280, 6360, 6429, 6505, 6529, 61448, 61468,
+ 61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704,
+ 61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914,
+ 61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218,
+ 62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554,
+ 62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766,
+ 62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118,
+ 63182, 63242, 63274, 63310, 63368, 63390,
+ };
+#define HIBIT ((unsigned char)0x80)
+ unsigned char aChar[] = {
+ '\0', 'a', 'c', 'e', 'i', 'n',
+ 'o', 'u', 'y', 'y', 'a', 'c',
+ 'd', 'e', 'e', 'g', 'h', 'i',
+ 'j', 'k', 'l', 'n', 'o', 'r',
+ 's', 't', 'u', 'u', 'w', 'y',
+ 'z', 'o', 'u', 'a', 'i', 'o',
+ 'u', 'u'|HIBIT, 'a'|HIBIT, 'g', 'k', 'o',
+ 'o'|HIBIT, 'j', 'g', 'n', 'a'|HIBIT, 'a',
+ 'e', 'i', 'o', 'r', 'u', 's',
+ 't', 'h', 'a', 'e', 'o'|HIBIT, 'o',
+ 'o'|HIBIT, 'y', '\0', '\0', '\0', '\0',
+ '\0', '\0', '\0', '\0', 'a', 'b',
+ 'c'|HIBIT, 'd', 'd', 'e'|HIBIT, 'e', 'e'|HIBIT,
+ 'f', 'g', 'h', 'h', 'i', 'i'|HIBIT,
+ 'k', 'l', 'l'|HIBIT, 'l', 'm', 'n',
+ 'o'|HIBIT, 'p', 'r', 'r'|HIBIT, 'r', 's',
+ 's'|HIBIT, 't', 'u', 'u'|HIBIT, 'v', 'w',
+ 'w', 'x', 'y', 'z', 'h', 't',
+ 'w', 'y', 'a', 'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT,
+ 'e', 'e'|HIBIT, 'e'|HIBIT, 'i', 'o', 'o'|HIBIT,
+ 'o'|HIBIT, 'o'|HIBIT, 'u', 'u'|HIBIT, 'u'|HIBIT, 'y',
+ };
+
+ unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
+ int iRes = 0;
+ int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
+ int iLo = 0;
+ while( iHi>=iLo ){
+ int iTest = (iHi + iLo) / 2;
+ if( key >= aDia[iTest] ){
+ iRes = iTest;
+ iLo = iTest+1;
+ }else{
+ iHi = iTest-1;
+ }
+ }
+ assert( key>=aDia[iRes] );
+ if( bComplex==0 && (aChar[iRes] & 0x80) ) return c;
+ return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F);
+}
+
+
+/*
+** Return true if the argument interpreted as a unicode codepoint
+** is a diacritical modifier character.
+*/
+SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
+ unsigned int mask0 = 0x08029FDF;
+ unsigned int mask1 = 0x000361F8;
+ if( c<768 || c>817 ) return 0;
+ return (c < 768+32) ?
+ (mask0 & ((unsigned int)1 << (c-768))) :
+ (mask1 & ((unsigned int)1 << (c-768-32)));
+}
+
+
+/*
+** Interpret the argument as a unicode codepoint. If the codepoint
+** is an upper case character that has a lower case equivalent,
+** return the codepoint corresponding to the lower case version.
+** Otherwise, return a copy of the argument.
+**
+** The results are undefined if the value passed to this function
+** is less than zero.
+*/
+SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){
+ /* Each entry in the following array defines a rule for folding a range
+ ** of codepoints to lower case. The rule applies to a range of nRange
+ ** codepoints starting at codepoint iCode.
+ **
+ ** If the least significant bit in flags is clear, then the rule applies
+ ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
+ ** need to be folded). Or, if it is set, then the rule only applies to
+ ** every second codepoint in the range, starting with codepoint C.
+ **
+ ** The 7 most significant bits in flags are an index into the aiOff[]
+ ** array. If a specific codepoint C does require folding, then its lower
+ ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
+ **
+ ** The contents of this array are generated by parsing the CaseFolding.txt
+ ** file distributed as part of the "Unicode Character Database". See
+ ** http://www.unicode.org for details.
+ */
+ static const struct TableEntry {
+ unsigned short iCode;
+ unsigned char flags;
+ unsigned char nRange;
+ } aEntry[] = {
+ {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
+ {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
+ {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
+ {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
+ {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
+ {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
+ {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
+ {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
+ {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
+ {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
+ {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
+ {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
+ {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
+ {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
+ {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
+ {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
+ {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
+ {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
+ {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
+ {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
+ {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
+ {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
+ {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
+ {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
+ {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
+ {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
+ {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
+ {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
+ {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
+ {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
+ {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
+ {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
+ {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
+ {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
+ {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
+ {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
+ {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
+ {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
+ {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
+ {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
+ {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
+ {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
+ {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
+ {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
+ {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
+ {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
+ {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
+ {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
+ {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
+ {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
+ {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
+ {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
+ {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
+ {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
+ {65313, 14, 26},
+ };
+ static const unsigned short aiOff[] = {
+ 1, 2, 8, 15, 16, 26, 28, 32,
+ 37, 38, 40, 48, 63, 64, 69, 71,
+ 79, 80, 116, 202, 203, 205, 206, 207,
+ 209, 210, 211, 213, 214, 217, 218, 219,
+ 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
+ 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
+ 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
+ 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
+ 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
+ 65514, 65521, 65527, 65528, 65529,
+ };
+
+ int ret = c;
+
+ assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
+
+ if( c<128 ){
+ if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
+ }else if( c<65536 ){
+ const struct TableEntry *p;
+ int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
+ int iLo = 0;
+ int iRes = -1;
+
+ assert( c>aEntry[0].iCode );
+ while( iHi>=iLo ){
+ int iTest = (iHi + iLo) / 2;
+ int cmp = (c - aEntry[iTest].iCode);
+ if( cmp>=0 ){
+ iRes = iTest;
+ iLo = iTest+1;
+ }else{
+ iHi = iTest-1;
+ }
+ }
+
+ assert( iRes>=0 && c>=aEntry[iRes].iCode );
+ p = &aEntry[iRes];
+ if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
+ ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
+ assert( ret>0 );
+ }
+
+ if( eRemoveDiacritic ){
+ ret = remove_diacritic(ret, eRemoveDiacritic==2);
+ }
+ }
+
+ else if( c>=66560 && c<66600 ){
+ ret = c + 40;
+ }
+
+ return ret;
+}
+#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
+#endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
+
+/************** End of fts3_unicode2.c ***************************************/
+/************** Begin file json1.c *******************************************/
+/*
+** 2015-08-12
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This SQLite extension implements JSON functions. The interface is
+** modeled after MySQL JSON functions:
+**
+** https://dev.mysql.com/doc/refman/5.7/en/json.html
+**
+** For the time being, all JSON is stored as pure text. (We might add
+** a JSONB type in the future which stores a binary encoding of JSON in
+** a BLOB, but there is no support for JSONB in the current implementation.
+** This implementation parses JSON text at 250 MB/s, so it is hard to see
+** how JSONB might improve on that.)
+*/
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
+#if !defined(SQLITEINT_H)
+/* #include "sqlite3ext.h" */
+#endif
+SQLITE_EXTENSION_INIT1
+/* #include <assert.h> */
+/* #include <string.h> */
+/* #include <stdlib.h> */
+/* #include <stdarg.h> */
+
+/* Mark a function parameter as unused, to suppress nuisance compiler
+** warnings. */
+#ifndef UNUSED_PARAM
+# define UNUSED_PARAM(X) (void)(X)
+#endif
+
+#ifndef LARGEST_INT64
+# define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
+# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
+#endif
+
+#ifndef deliberate_fall_through
+# define deliberate_fall_through
+#endif
+
+/*
+** Versions of isspace(), isalnum() and isdigit() to which it is safe
+** to pass signed char values.
+*/
+#ifdef sqlite3Isdigit
+ /* Use the SQLite core versions if this routine is part of the
+ ** SQLite amalgamation */
+# define safe_isdigit(x) sqlite3Isdigit(x)
+# define safe_isalnum(x) sqlite3Isalnum(x)
+# define safe_isxdigit(x) sqlite3Isxdigit(x)
+#else
+ /* Use the standard library for separate compilation */
+#include <ctype.h> /* amalgamator: keep */
+# define safe_isdigit(x) isdigit((unsigned char)(x))
+# define safe_isalnum(x) isalnum((unsigned char)(x))
+# define safe_isxdigit(x) isxdigit((unsigned char)(x))
+#endif
+
+/*
+** Growing our own isspace() routine this way is twice as fast as
+** the library isspace() function, resulting in a 7% overall performance
+** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
+*/
+static const char jsonIsSpace[] = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+};
+#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
+
+#ifndef SQLITE_AMALGAMATION
+ /* Unsigned integer types. These are already defined in the sqliteInt.h,
+ ** but the definitions need to be repeated for separate compilation. */
+ typedef sqlite3_uint64 u64;
+ typedef unsigned int u32;
+ typedef unsigned short int u16;
+ typedef unsigned char u8;
+#endif
+
+/* Objects */
+typedef struct JsonString JsonString;
+typedef struct JsonNode JsonNode;
+typedef struct JsonParse JsonParse;
+
+/* An instance of this object represents a JSON string
+** under construction. Really, this is a generic string accumulator
+** that can be and is used to create strings other than JSON.
+*/
+struct JsonString {
+ sqlite3_context *pCtx; /* Function context - put error messages here */
+ char *zBuf; /* Append JSON content here */
+ u64 nAlloc; /* Bytes of storage available in zBuf[] */
+ u64 nUsed; /* Bytes of zBuf[] currently used */
+ u8 bStatic; /* True if zBuf is static space */
+ u8 bErr; /* True if an error has been encountered */
+ char zSpace[100]; /* Initial static space */
+};
+
+/* JSON type values
+*/
+#define JSON_NULL 0
+#define JSON_TRUE 1
+#define JSON_FALSE 2
+#define JSON_INT 3
+#define JSON_REAL 4
+#define JSON_STRING 5
+#define JSON_ARRAY 6
+#define JSON_OBJECT 7
+
+/* The "subtype" set for JSON values */
+#define JSON_SUBTYPE 74 /* Ascii for "J" */
+
+/*
+** Names of the various JSON types:
+*/
+static const char * const jsonType[] = {
+ "null", "true", "false", "integer", "real", "text", "array", "object"
+};
+
+/* Bit values for the JsonNode.jnFlag field
+*/
+#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
+#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
+#define JNODE_REMOVE 0x04 /* Do not output */
+#define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
+#define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
+#define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
+#define JNODE_LABEL 0x40 /* Is a label of an object */
+
+
+/* A single node of parsed JSON
+*/
+struct JsonNode {
+ u8 eType; /* One of the JSON_ type values */
+ u8 jnFlags; /* JNODE flags */
+ u32 n; /* Bytes of content, or number of sub-nodes */
+ union {
+ const char *zJContent; /* Content for INT, REAL, and STRING */
+ u32 iAppend; /* More terms for ARRAY and OBJECT */
+ u32 iKey; /* Key for ARRAY objects in json_tree() */
+ u32 iReplace; /* Replacement content for JNODE_REPLACE */
+ JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
+ } u;
+};
+
+/* A completely parsed JSON string
+*/
+struct JsonParse {
+ u32 nNode; /* Number of slots of aNode[] used */
+ u32 nAlloc; /* Number of slots of aNode[] allocated */
+ JsonNode *aNode; /* Array of nodes containing the parse */
+ const char *zJson; /* Original JSON string */
+ u32 *aUp; /* Index of parent of each node */
+ u8 oom; /* Set to true if out of memory */
+ u8 nErr; /* Number of errors seen */
+ u16 iDepth; /* Nesting depth */
+ int nJson; /* Length of the zJson string in bytes */
+ u32 iHold; /* Replace cache line with the lowest iHold value */
+};
+
+/*
+** Maximum nesting depth of JSON for this implementation.
+**
+** This limit is needed to avoid a stack overflow in the recursive
+** descent parser. A depth of 2000 is far deeper than any sane JSON
+** should go.
+*/
+#define JSON_MAX_DEPTH 2000
+
+/**************************************************************************
+** Utility routines for dealing with JsonString objects
+**************************************************************************/
+
+/* Set the JsonString object to an empty string
+*/
+static void jsonZero(JsonString *p){
+ p->zBuf = p->zSpace;
+ p->nAlloc = sizeof(p->zSpace);
+ p->nUsed = 0;
+ p->bStatic = 1;
+}
+
+/* Initialize the JsonString object
+*/
+static void jsonInit(JsonString *p, sqlite3_context *pCtx){
+ p->pCtx = pCtx;
+ p->bErr = 0;
+ jsonZero(p);
+}
+
+
+/* Free all allocated memory and reset the JsonString object back to its
+** initial state.
+*/
+static void jsonReset(JsonString *p){
+ if( !p->bStatic ) sqlite3_free(p->zBuf);
+ jsonZero(p);
+}
+
+
+/* Report an out-of-memory (OOM) condition
+*/
+static void jsonOom(JsonString *p){
+ p->bErr = 1;
+ sqlite3_result_error_nomem(p->pCtx);
+ jsonReset(p);
+}
+
+/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
+** Return zero on success. Return non-zero on an OOM error
+*/
+static int jsonGrow(JsonString *p, u32 N){
+ u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
+ char *zNew;
+ if( p->bStatic ){
+ if( p->bErr ) return 1;
+ zNew = sqlite3_malloc64(nTotal);
+ if( zNew==0 ){
+ jsonOom(p);
+ return SQLITE_NOMEM;
+ }
+ memcpy(zNew, p->zBuf, (size_t)p->nUsed);
+ p->zBuf = zNew;
+ p->bStatic = 0;
+ }else{
+ zNew = sqlite3_realloc64(p->zBuf, nTotal);
+ if( zNew==0 ){
+ jsonOom(p);
+ return SQLITE_NOMEM;
+ }
+ p->zBuf = zNew;
+ }
+ p->nAlloc = nTotal;
+ return SQLITE_OK;
+}
+
+/* Append N bytes from zIn onto the end of the JsonString string.
+*/
+static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
+ if( N==0 ) return;
+ if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
+ memcpy(p->zBuf+p->nUsed, zIn, N);
+ p->nUsed += N;
+}
+
+/* Append formatted text (not to exceed N bytes) to the JsonString.
+*/
+static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
+ va_list ap;
+ if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
+ va_start(ap, zFormat);
+ sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
+ va_end(ap);
+ p->nUsed += (int)strlen(p->zBuf+p->nUsed);
+}
+
+/* Append a single character
+*/
+static void jsonAppendChar(JsonString *p, char c){
+ if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
+ p->zBuf[p->nUsed++] = c;
+}
+
+/* Append a comma separator to the output buffer, if the previous
+** character is not '[' or '{'.
+*/
+static void jsonAppendSeparator(JsonString *p){
+ char c;
+ if( p->nUsed==0 ) return;
+ c = p->zBuf[p->nUsed-1];
+ if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
+}
+
+/* Append the N-byte string in zIn to the end of the JsonString string
+** under construction. Enclose the string in "..." and escape
+** any double-quotes or backslash characters contained within the
+** string.
+*/
+static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
+ u32 i;
+ if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
+ p->zBuf[p->nUsed++] = '"';
+ for(i=0; i<N; i++){
+ unsigned char c = ((unsigned const char*)zIn)[i];
+ if( c=='"' || c=='\\' ){
+ json_simple_escape:
+ if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
+ p->zBuf[p->nUsed++] = '\\';
+ }else if( c<=0x1f ){
+ static const char aSpecial[] = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+ };
+ assert( sizeof(aSpecial)==32 );
+ assert( aSpecial['\b']=='b' );
+ assert( aSpecial['\f']=='f' );
+ assert( aSpecial['\n']=='n' );
+ assert( aSpecial['\r']=='r' );
+ assert( aSpecial['\t']=='t' );
+ if( aSpecial[c] ){
+ c = aSpecial[c];
+ goto json_simple_escape;
+ }
+ if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
+ p->zBuf[p->nUsed++] = '\\';
+ p->zBuf[p->nUsed++] = 'u';
+ p->zBuf[p->nUsed++] = '0';
+ p->zBuf[p->nUsed++] = '0';
+ p->zBuf[p->nUsed++] = '0' + (c>>4);
+ c = "0123456789abcdef"[c&0xf];
+ }
+ p->zBuf[p->nUsed++] = c;
+ }
+ p->zBuf[p->nUsed++] = '"';
+ assert( p->nUsed<p->nAlloc );
+}
+
+/*
+** Append a function parameter value to the JSON string under
+** construction.
+*/
+static void jsonAppendValue(
+ JsonString *p, /* Append to this JSON string */
+ sqlite3_value *pValue /* Value to append */
+){
+ switch( sqlite3_value_type(pValue) ){
+ case SQLITE_NULL: {
+ jsonAppendRaw(p, "null", 4);
+ break;
+ }
+ case SQLITE_INTEGER:
+ case SQLITE_FLOAT: {
+ const char *z = (const char*)sqlite3_value_text(pValue);
+ u32 n = (u32)sqlite3_value_bytes(pValue);
+ jsonAppendRaw(p, z, n);
+ break;
+ }
+ case SQLITE_TEXT: {
+ const char *z = (const char*)sqlite3_value_text(pValue);
+ u32 n = (u32)sqlite3_value_bytes(pValue);
+ if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
+ jsonAppendRaw(p, z, n);
+ }else{
+ jsonAppendString(p, z, n);
+ }
+ break;
+ }
+ default: {
+ if( p->bErr==0 ){
+ sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
+ p->bErr = 2;
+ jsonReset(p);
+ }
+ break;
+ }
+ }
+}
+
+
+/* Make the JSON in p the result of the SQL function.
+*/
+static void jsonResult(JsonString *p){
+ if( p->bErr==0 ){
+ sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
+ p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
+ SQLITE_UTF8);
+ jsonZero(p);
+ }
+ assert( p->bStatic );
+}
+
+/**************************************************************************
+** Utility routines for dealing with JsonNode and JsonParse objects
+**************************************************************************/
+
+/*
+** Return the number of consecutive JsonNode slots need to represent
+** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
+** OBJECT types, the number might be larger.
+**
+** Appended elements are not counted. The value returned is the number
+** by which the JsonNode counter should increment in order to go to the
+** next peer value.
+*/
+static u32 jsonNodeSize(JsonNode *pNode){
+ return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
+}
+
+/*
+** Reclaim all memory allocated by a JsonParse object. But do not
+** delete the JsonParse object itself.
+*/
+static void jsonParseReset(JsonParse *pParse){
+ sqlite3_free(pParse->aNode);
+ pParse->aNode = 0;
+ pParse->nNode = 0;
+ pParse->nAlloc = 0;
+ sqlite3_free(pParse->aUp);
+ pParse->aUp = 0;
+}
+
+/*
+** Free a JsonParse object that was obtained from sqlite3_malloc().
+*/
+static void jsonParseFree(JsonParse *pParse){
+ jsonParseReset(pParse);
+ sqlite3_free(pParse);
+}
+
+/*
+** Convert the JsonNode pNode into a pure JSON string and
+** append to pOut. Subsubstructure is also included. Return
+** the number of JsonNode objects that are encoded.
+*/
+static void jsonRenderNode(
+ JsonNode *pNode, /* The node to render */
+ JsonString *pOut, /* Write JSON here */
+ sqlite3_value **aReplace /* Replacement values */
+){
+ if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
+ if( pNode->jnFlags & JNODE_REPLACE ){
+ jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
+ return;
+ }
+ pNode = pNode->u.pPatch;
+ }
+ switch( pNode->eType ){
+ default: {
+ assert( pNode->eType==JSON_NULL );
+ jsonAppendRaw(pOut, "null", 4);
+ break;
+ }
+ case JSON_TRUE: {
+ jsonAppendRaw(pOut, "true", 4);
+ break;
+ }
+ case JSON_FALSE: {
+ jsonAppendRaw(pOut, "false", 5);
+ break;
+ }
+ case JSON_STRING: {
+ if( pNode->jnFlags & JNODE_RAW ){
+ jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
+ break;
+ }
+ /* no break */ deliberate_fall_through
+ }
+ case JSON_REAL:
+ case JSON_INT: {
+ jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
+ break;
+ }
+ case JSON_ARRAY: {
+ u32 j = 1;
+ jsonAppendChar(pOut, '[');
+ for(;;){
+ while( j<=pNode->n ){
+ if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
+ jsonAppendSeparator(pOut);
+ jsonRenderNode(&pNode[j], pOut, aReplace);
+ }
+ j += jsonNodeSize(&pNode[j]);
+ }
+ if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
+ pNode = &pNode[pNode->u.iAppend];
+ j = 1;
+ }
+ jsonAppendChar(pOut, ']');
+ break;
+ }
+ case JSON_OBJECT: {
+ u32 j = 1;
+ jsonAppendChar(pOut, '{');
+ for(;;){
+ while( j<=pNode->n ){
+ if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
+ jsonAppendSeparator(pOut);
+ jsonRenderNode(&pNode[j], pOut, aReplace);
+ jsonAppendChar(pOut, ':');
+ jsonRenderNode(&pNode[j+1], pOut, aReplace);
+ }
+ j += 1 + jsonNodeSize(&pNode[j+1]);
+ }
+ if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
+ pNode = &pNode[pNode->u.iAppend];
+ j = 1;
+ }
+ jsonAppendChar(pOut, '}');
+ break;
+ }
+ }
+}
+
+/*
+** Return a JsonNode and all its descendents as a JSON string.
+*/
+static void jsonReturnJson(
+ JsonNode *pNode, /* Node to return */
+ sqlite3_context *pCtx, /* Return value for this function */
+ sqlite3_value **aReplace /* Array of replacement values */
+){
+ JsonString s;
+ jsonInit(&s, pCtx);
+ jsonRenderNode(pNode, &s, aReplace);
+ jsonResult(&s);
+ sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
+}
+
+/*
+** Translate a single byte of Hex into an integer.
+** This routine only works if h really is a valid hexadecimal
+** character: 0..9a..fA..F
+*/
+static u8 jsonHexToInt(int h){
+ assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
+#ifdef SQLITE_EBCDIC
+ h += 9*(1&~(h>>4));
+#else
+ h += 9*(1&(h>>6));
+#endif
+ return (u8)(h & 0xf);
+}
+
+/*
+** Convert a 4-byte hex string into an integer
+*/
+static u32 jsonHexToInt4(const char *z){
+ u32 v;
+ assert( safe_isxdigit(z[0]) );
+ assert( safe_isxdigit(z[1]) );
+ assert( safe_isxdigit(z[2]) );
+ assert( safe_isxdigit(z[3]) );
+ v = (jsonHexToInt(z[0])<<12)
+ + (jsonHexToInt(z[1])<<8)
+ + (jsonHexToInt(z[2])<<4)
+ + jsonHexToInt(z[3]);
+ return v;
+}
+
+/*
+** Make the JsonNode the return value of the function.
+*/
+static void jsonReturn(
+ JsonNode *pNode, /* Node to return */
+ sqlite3_context *pCtx, /* Return value for this function */
+ sqlite3_value **aReplace /* Array of replacement values */
+){
+ switch( pNode->eType ){
+ default: {
+ assert( pNode->eType==JSON_NULL );
+ sqlite3_result_null(pCtx);
+ break;
+ }
+ case JSON_TRUE: {
+ sqlite3_result_int(pCtx, 1);
+ break;
+ }
+ case JSON_FALSE: {
+ sqlite3_result_int(pCtx, 0);
+ break;
+ }
+ case JSON_INT: {
+ sqlite3_int64 i = 0;
+ const char *z = pNode->u.zJContent;
+ if( z[0]=='-' ){ z++; }
+ while( z[0]>='0' && z[0]<='9' ){
+ unsigned v = *(z++) - '0';
+ if( i>=LARGEST_INT64/10 ){
+ if( i>LARGEST_INT64/10 ) goto int_as_real;
+ if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
+ if( v==9 ) goto int_as_real;
+ if( v==8 ){
+ if( pNode->u.zJContent[0]=='-' ){
+ sqlite3_result_int64(pCtx, SMALLEST_INT64);
+ goto int_done;
+ }else{
+ goto int_as_real;
+ }
+ }
+ }
+ i = i*10 + v;
+ }
+ if( pNode->u.zJContent[0]=='-' ){ i = -i; }
+ sqlite3_result_int64(pCtx, i);
+ int_done:
+ break;
+ int_as_real: i=0; /* no break */ deliberate_fall_through
+ }
+ case JSON_REAL: {
+ double r;
+#ifdef SQLITE_AMALGAMATION
+ const char *z = pNode->u.zJContent;
+ sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
+#else
+ r = strtod(pNode->u.zJContent, 0);
+#endif
+ sqlite3_result_double(pCtx, r);
+ break;
+ }
+ case JSON_STRING: {
+#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
+ ** json_insert() and json_replace() and those routines do not
+ ** call jsonReturn() */
+ if( pNode->jnFlags & JNODE_RAW ){
+ sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
+ SQLITE_TRANSIENT);
+ }else
+#endif
+ assert( (pNode->jnFlags & JNODE_RAW)==0 );
+ if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
+ /* JSON formatted without any backslash-escapes */
+ sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
+ SQLITE_TRANSIENT);
+ }else{
+ /* Translate JSON formatted string into raw text */
+ u32 i;
+ u32 n = pNode->n;
+ const char *z = pNode->u.zJContent;
+ char *zOut;
+ u32 j;
+ zOut = sqlite3_malloc( n+1 );
+ if( zOut==0 ){
+ sqlite3_result_error_nomem(pCtx);
+ break;
+ }
+ for(i=1, j=0; i<n-1; i++){
+ char c = z[i];
+ if( c!='\\' ){
+ zOut[j++] = c;
+ }else{
+ c = z[++i];
+ if( c=='u' ){
+ u32 v = jsonHexToInt4(z+i+1);
+ i += 4;
+ if( v==0 ) break;
+ if( v<=0x7f ){
+ zOut[j++] = (char)v;
+ }else if( v<=0x7ff ){
+ zOut[j++] = (char)(0xc0 | (v>>6));
+ zOut[j++] = 0x80 | (v&0x3f);
+ }else{
+ u32 vlo;
+ if( (v&0xfc00)==0xd800
+ && i<n-6
+ && z[i+1]=='\\'
+ && z[i+2]=='u'
+ && ((vlo = jsonHexToInt4(z+i+3))&0xfc00)==0xdc00
+ ){
+ /* We have a surrogate pair */
+ v = ((v&0x3ff)<<10) + (vlo&0x3ff) + 0x10000;
+ i += 6;
+ zOut[j++] = 0xf0 | (v>>18);
+ zOut[j++] = 0x80 | ((v>>12)&0x3f);
+ zOut[j++] = 0x80 | ((v>>6)&0x3f);
+ zOut[j++] = 0x80 | (v&0x3f);
+ }else{
+ zOut[j++] = 0xe0 | (v>>12);
+ zOut[j++] = 0x80 | ((v>>6)&0x3f);
+ zOut[j++] = 0x80 | (v&0x3f);
+ }
+ }
+ }else{
+ if( c=='b' ){
+ c = '\b';
+ }else if( c=='f' ){
+ c = '\f';
+ }else if( c=='n' ){
+ c = '\n';
+ }else if( c=='r' ){
+ c = '\r';
+ }else if( c=='t' ){
+ c = '\t';
+ }
+ zOut[j++] = c;
+ }
+ }
+ }
+ zOut[j] = 0;
+ sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
+ }
+ break;
+ }
+ case JSON_ARRAY:
+ case JSON_OBJECT: {
+ jsonReturnJson(pNode, pCtx, aReplace);
+ break;
+ }
+ }
+}
+
+/* Forward reference */
+static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
+
+/*
+** A macro to hint to the compiler that a function should not be
+** inlined.
+*/
+#if defined(__GNUC__)
+# define JSON_NOINLINE __attribute__((noinline))
+#elif defined(_MSC_VER) && _MSC_VER>=1310
+# define JSON_NOINLINE __declspec(noinline)
+#else
+# define JSON_NOINLINE
+#endif
+
+
+static JSON_NOINLINE int jsonParseAddNodeExpand(
+ JsonParse *pParse, /* Append the node to this object */
+ u32 eType, /* Node type */
+ u32 n, /* Content size or sub-node count */
+ const char *zContent /* Content */
+){
+ u32 nNew;
+ JsonNode *pNew;
+ assert( pParse->nNode>=pParse->nAlloc );
+ if( pParse->oom ) return -1;
+ nNew = pParse->nAlloc*2 + 10;
+ pNew = sqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew);
+ if( pNew==0 ){
+ pParse->oom = 1;
+ return -1;
+ }
+ pParse->nAlloc = nNew;
+ pParse->aNode = pNew;
+ assert( pParse->nNode<pParse->nAlloc );
+ return jsonParseAddNode(pParse, eType, n, zContent);
+}
+
+/*
+** Create a new JsonNode instance based on the arguments and append that
+** instance to the JsonParse. Return the index in pParse->aNode[] of the
+** new node, or -1 if a memory allocation fails.
+*/
+static int jsonParseAddNode(
+ JsonParse *pParse, /* Append the node to this object */
+ u32 eType, /* Node type */
+ u32 n, /* Content size or sub-node count */
+ const char *zContent /* Content */
+){
+ JsonNode *p;
+ if( pParse->nNode>=pParse->nAlloc ){
+ return jsonParseAddNodeExpand(pParse, eType, n, zContent);
+ }
+ p = &pParse->aNode[pParse->nNode];
+ p->eType = (u8)eType;
+ p->jnFlags = 0;
+ p->n = n;
+ p->u.zJContent = zContent;
+ return pParse->nNode++;
+}
+
+/*
+** Return true if z[] begins with 4 (or more) hexadecimal digits
+*/
+static int jsonIs4Hex(const char *z){
+ int i;
+ for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
+ return 1;
+}
+
+/*
+** Parse a single JSON value which begins at pParse->zJson[i]. Return the
+** index of the first character past the end of the value parsed.
+**
+** Return negative for a syntax error. Special cases: return -2 if the
+** first non-whitespace character is '}' and return -3 if the first
+** non-whitespace character is ']'.
+*/
+static int jsonParseValue(JsonParse *pParse, u32 i){
+ char c;
+ u32 j;
+ int iThis;
+ int x;
+ JsonNode *pNode;
+ const char *z = pParse->zJson;
+ while( safe_isspace(z[i]) ){ i++; }
+ if( (c = z[i])=='{' ){
+ /* Parse object */
+ iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
+ if( iThis<0 ) return -1;
+ for(j=i+1;;j++){
+ while( safe_isspace(z[j]) ){ j++; }
+ if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
+ x = jsonParseValue(pParse, j);
+ if( x<0 ){
+ pParse->iDepth--;
+ if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
+ return -1;
+ }
+ if( pParse->oom ) return -1;
+ pNode = &pParse->aNode[pParse->nNode-1];
+ if( pNode->eType!=JSON_STRING ) return -1;
+ pNode->jnFlags |= JNODE_LABEL;
+ j = x;
+ while( safe_isspace(z[j]) ){ j++; }
+ if( z[j]!=':' ) return -1;
+ j++;
+ x = jsonParseValue(pParse, j);
+ pParse->iDepth--;
+ if( x<0 ) return -1;
+ j = x;
+ while( safe_isspace(z[j]) ){ j++; }
+ c = z[j];
+ if( c==',' ) continue;
+ if( c!='}' ) return -1;
+ break;
+ }
+ pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
+ return j+1;
+ }else if( c=='[' ){
+ /* Parse array */
+ iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
+ if( iThis<0 ) return -1;
+ for(j=i+1;;j++){
+ while( safe_isspace(z[j]) ){ j++; }
+ if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
+ x = jsonParseValue(pParse, j);
+ pParse->iDepth--;
+ if( x<0 ){
+ if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
+ return -1;
+ }
+ j = x;
+ while( safe_isspace(z[j]) ){ j++; }
+ c = z[j];
+ if( c==',' ) continue;
+ if( c!=']' ) return -1;
+ break;
+ }
+ pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
+ return j+1;
+ }else if( c=='"' ){
+ /* Parse string */
+ u8 jnFlags = 0;
+ j = i+1;
+ for(;;){
+ c = z[j];
+ if( (c & ~0x1f)==0 ){
+ /* Control characters are not allowed in strings */
+ return -1;
+ }
+ if( c=='\\' ){
+ c = z[++j];
+ if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
+ || c=='n' || c=='r' || c=='t'
+ || (c=='u' && jsonIs4Hex(z+j+1)) ){
+ jnFlags = JNODE_ESCAPE;
+ }else{
+ return -1;
+ }
+ }else if( c=='"' ){
+ break;
+ }
+ j++;
+ }
+ jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
+ if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
+ return j+1;
+ }else if( c=='n'
+ && strncmp(z+i,"null",4)==0
+ && !safe_isalnum(z[i+4]) ){
+ jsonParseAddNode(pParse, JSON_NULL, 0, 0);
+ return i+4;
+ }else if( c=='t'
+ && strncmp(z+i,"true",4)==0
+ && !safe_isalnum(z[i+4]) ){
+ jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
+ return i+4;
+ }else if( c=='f'
+ && strncmp(z+i,"false",5)==0
+ && !safe_isalnum(z[i+5]) ){
+ jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
+ return i+5;
+ }else if( c=='-' || (c>='0' && c<='9') ){
+ /* Parse number */
+ u8 seenDP = 0;
+ u8 seenE = 0;
+ assert( '-' < '0' );
+ if( c<='0' ){
+ j = c=='-' ? i+1 : i;
+ if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
+ }
+ j = i+1;
+ for(;; j++){
+ c = z[j];
+ if( c>='0' && c<='9' ) continue;
+ if( c=='.' ){
+ if( z[j-1]=='-' ) return -1;
+ if( seenDP ) return -1;
+ seenDP = 1;
+ continue;
+ }
+ if( c=='e' || c=='E' ){
+ if( z[j-1]<'0' ) return -1;
+ if( seenE ) return -1;
+ seenDP = seenE = 1;
+ c = z[j+1];
+ if( c=='+' || c=='-' ){
+ j++;
+ c = z[j+1];
+ }
+ if( c<'0' || c>'9' ) return -1;
+ continue;
+ }
+ break;
+ }
+ if( z[j-1]<'0' ) return -1;
+ jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
+ j - i, &z[i]);
+ return j;
+ }else if( c=='}' ){
+ return -2; /* End of {...} */
+ }else if( c==']' ){
+ return -3; /* End of [...] */
+ }else if( c==0 ){
+ return 0; /* End of file */
+ }else{
+ return -1; /* Syntax error */
+ }
+}
+
+/*
+** Parse a complete JSON string. Return 0 on success or non-zero if there
+** are any errors. If an error occurs, free all memory associated with
+** pParse.
+**
+** pParse is uninitialized when this routine is called.
+*/
+static int jsonParse(
+ JsonParse *pParse, /* Initialize and fill this JsonParse object */
+ sqlite3_context *pCtx, /* Report errors here */
+ const char *zJson /* Input JSON text to be parsed */
+){
+ int i;
+ memset(pParse, 0, sizeof(*pParse));
+ if( zJson==0 ) return 1;
+ pParse->zJson = zJson;
+ i = jsonParseValue(pParse, 0);
+ if( pParse->oom ) i = -1;
+ if( i>0 ){
+ assert( pParse->iDepth==0 );
+ while( safe_isspace(zJson[i]) ) i++;
+ if( zJson[i] ) i = -1;
+ }
+ if( i<=0 ){
+ if( pCtx!=0 ){
+ if( pParse->oom ){
+ sqlite3_result_error_nomem(pCtx);
+ }else{
+ sqlite3_result_error(pCtx, "malformed JSON", -1);
+ }
+ }
+ jsonParseReset(pParse);
+ return 1;
+ }
+ return 0;
+}
+
+/* Mark node i of pParse as being a child of iParent. Call recursively
+** to fill in all the descendants of node i.
+*/
+static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
+ JsonNode *pNode = &pParse->aNode[i];
+ u32 j;
+ pParse->aUp[i] = iParent;
+ switch( pNode->eType ){
+ case JSON_ARRAY: {
+ for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
+ jsonParseFillInParentage(pParse, i+j, i);
+ }
+ break;
+ }
+ case JSON_OBJECT: {
+ for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
+ pParse->aUp[i+j] = i;
+ jsonParseFillInParentage(pParse, i+j+1, i);
+ }
+ break;
+ }
+ default: {
+ break;
+ }
+ }
+}
+
+/*
+** Compute the parentage of all nodes in a completed parse.
+*/
+static int jsonParseFindParents(JsonParse *pParse){
+ u32 *aUp;
+ assert( pParse->aUp==0 );
+ aUp = pParse->aUp = sqlite3_malloc64( sizeof(u32)*pParse->nNode );
+ if( aUp==0 ){
+ pParse->oom = 1;
+ return SQLITE_NOMEM;
+ }
+ jsonParseFillInParentage(pParse, 0, 0);
+ return SQLITE_OK;
+}
+
+/*
+** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
+*/
+#define JSON_CACHE_ID (-429938) /* First cache entry */
+#define JSON_CACHE_SZ 4 /* Max number of cache entries */
+
+/*
+** Obtain a complete parse of the JSON found in the first argument
+** of the argv array. Use the sqlite3_get_auxdata() cache for this
+** parse if it is available. If the cache is not available or if it
+** is no longer valid, parse the JSON again and return the new parse,
+** and also register the new parse so that it will be available for
+** future sqlite3_get_auxdata() calls.
+*/
+static JsonParse *jsonParseCached(
+ sqlite3_context *pCtx,
+ sqlite3_value **argv,
+ sqlite3_context *pErrCtx
+){
+ const char *zJson = (const char*)sqlite3_value_text(argv[0]);
+ int nJson = sqlite3_value_bytes(argv[0]);
+ JsonParse *p;
+ JsonParse *pMatch = 0;
+ int iKey;
+ int iMinKey = 0;
+ u32 iMinHold = 0xffffffff;
+ u32 iMaxHold = 0;
+ if( zJson==0 ) return 0;
+ for(iKey=0; iKey<JSON_CACHE_SZ; iKey++){
+ p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iKey);
+ if( p==0 ){
+ iMinKey = iKey;
+ break;
+ }
+ if( pMatch==0
+ && p->nJson==nJson
+ && memcmp(p->zJson,zJson,nJson)==0
+ ){
+ p->nErr = 0;
+ pMatch = p;
+ }else if( p->iHold<iMinHold ){
+ iMinHold = p->iHold;
+ iMinKey = iKey;
+ }
+ if( p->iHold>iMaxHold ){
+ iMaxHold = p->iHold;
+ }
+ }
+ if( pMatch ){
+ pMatch->nErr = 0;
+ pMatch->iHold = iMaxHold+1;
+ return pMatch;
+ }
+ p = sqlite3_malloc64( sizeof(*p) + nJson + 1 );
+ if( p==0 ){
+ sqlite3_result_error_nomem(pCtx);
+ return 0;
+ }
+ memset(p, 0, sizeof(*p));
+ p->zJson = (char*)&p[1];
+ memcpy((char*)p->zJson, zJson, nJson+1);
+ if( jsonParse(p, pErrCtx, p->zJson) ){
+ sqlite3_free(p);
+ return 0;
+ }
+ p->nJson = nJson;
+ p->iHold = iMaxHold+1;
+ sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,
+ (void(*)(void*))jsonParseFree);
+ return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);
+}
+
+/*
+** Compare the OBJECT label at pNode against zKey,nKey. Return true on
+** a match.
+*/
+static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
+ if( pNode->jnFlags & JNODE_RAW ){
+ if( pNode->n!=nKey ) return 0;
+ return strncmp(pNode->u.zJContent, zKey, nKey)==0;
+ }else{
+ if( pNode->n!=nKey+2 ) return 0;
+ return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
+ }
+}
+
+/* forward declaration */
+static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
+
+/*
+** Search along zPath to find the node specified. Return a pointer
+** to that node, or NULL if zPath is malformed or if there is no such
+** node.
+**
+** If pApnd!=0, then try to append new nodes to complete zPath if it is
+** possible to do so and if no existing node corresponds to zPath. If
+** new nodes are appended *pApnd is set to 1.
+*/
+static JsonNode *jsonLookupStep(
+ JsonParse *pParse, /* The JSON to search */
+ u32 iRoot, /* Begin the search at this node */
+ const char *zPath, /* The path to search */
+ int *pApnd, /* Append nodes to complete path if not NULL */
+ const char **pzErr /* Make *pzErr point to any syntax error in zPath */
+){
+ u32 i, j, nKey;
+ const char *zKey;
+ JsonNode *pRoot = &pParse->aNode[iRoot];
+ if( zPath[0]==0 ) return pRoot;
+ if( pRoot->jnFlags & JNODE_REPLACE ) return 0;
+ if( zPath[0]=='.' ){
+ if( pRoot->eType!=JSON_OBJECT ) return 0;
+ zPath++;
+ if( zPath[0]=='"' ){
+ zKey = zPath + 1;
+ for(i=1; zPath[i] && zPath[i]!='"'; i++){}
+ nKey = i-1;
+ if( zPath[i] ){
+ i++;
+ }else{
+ *pzErr = zPath;
+ return 0;
+ }
+ }else{
+ zKey = zPath;
+ for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
+ nKey = i;
+ }
+ if( nKey==0 ){
+ *pzErr = zPath;
+ return 0;
+ }
+ j = 1;
+ for(;;){
+ while( j<=pRoot->n ){
+ if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
+ return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
+ }
+ j++;
+ j += jsonNodeSize(&pRoot[j]);
+ }
+ if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
+ iRoot += pRoot->u.iAppend;
+ pRoot = &pParse->aNode[iRoot];
+ j = 1;
+ }
+ if( pApnd ){
+ u32 iStart, iLabel;
+ JsonNode *pNode;
+ iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
+ iLabel = jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
+ zPath += i;
+ pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
+ if( pParse->oom ) return 0;
+ if( pNode ){
+ pRoot = &pParse->aNode[iRoot];
+ pRoot->u.iAppend = iStart - iRoot;
+ pRoot->jnFlags |= JNODE_APPEND;
+ pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
+ }
+ return pNode;
+ }
+ }else if( zPath[0]=='[' ){
+ i = 0;
+ j = 1;
+ while( safe_isdigit(zPath[j]) ){
+ i = i*10 + zPath[j] - '0';
+ j++;
+ }
+ if( j<2 || zPath[j]!=']' ){
+ if( zPath[1]=='#' ){
+ JsonNode *pBase = pRoot;
+ int iBase = iRoot;
+ if( pRoot->eType!=JSON_ARRAY ) return 0;
+ for(;;){
+ while( j<=pBase->n ){
+ if( (pBase[j].jnFlags & JNODE_REMOVE)==0 ) i++;
+ j += jsonNodeSize(&pBase[j]);
+ }
+ if( (pBase->jnFlags & JNODE_APPEND)==0 ) break;
+ iBase += pBase->u.iAppend;
+ pBase = &pParse->aNode[iBase];
+ j = 1;
+ }
+ j = 2;
+ if( zPath[2]=='-' && safe_isdigit(zPath[3]) ){
+ unsigned int x = 0;
+ j = 3;
+ do{
+ x = x*10 + zPath[j] - '0';
+ j++;
+ }while( safe_isdigit(zPath[j]) );
+ if( x>i ) return 0;
+ i -= x;
+ }
+ if( zPath[j]!=']' ){
+ *pzErr = zPath;
+ return 0;
+ }
+ }else{
+ *pzErr = zPath;
+ return 0;
+ }
+ }
+ if( pRoot->eType!=JSON_ARRAY ) return 0;
+ zPath += j + 1;
+ j = 1;
+ for(;;){
+ while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
+ if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
+ j += jsonNodeSize(&pRoot[j]);
+ }
+ if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
+ iRoot += pRoot->u.iAppend;
+ pRoot = &pParse->aNode[iRoot];
+ j = 1;
+ }
+ if( j<=pRoot->n ){
+ return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
+ }
+ if( i==0 && pApnd ){
+ u32 iStart;
+ JsonNode *pNode;
+ iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
+ pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
+ if( pParse->oom ) return 0;
+ if( pNode ){
+ pRoot = &pParse->aNode[iRoot];
+ pRoot->u.iAppend = iStart - iRoot;
+ pRoot->jnFlags |= JNODE_APPEND;
+ }
+ return pNode;
+ }
+ }else{
+ *pzErr = zPath;
+ }
+ return 0;
+}
+
+/*
+** Append content to pParse that will complete zPath. Return a pointer
+** to the inserted node, or return NULL if the append fails.
+*/
+static JsonNode *jsonLookupAppend(
+ JsonParse *pParse, /* Append content to the JSON parse */
+ const char *zPath, /* Description of content to append */
+ int *pApnd, /* Set this flag to 1 */
+ const char **pzErr /* Make this point to any syntax error */
+){
+ *pApnd = 1;
+ if( zPath[0]==0 ){
+ jsonParseAddNode(pParse, JSON_NULL, 0, 0);
+ return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
+ }
+ if( zPath[0]=='.' ){
+ jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
+ }else if( strncmp(zPath,"[0]",3)==0 ){
+ jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
+ }else{
+ return 0;
+ }
+ if( pParse->oom ) return 0;
+ return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
+}
+
+/*
+** Return the text of a syntax error message on a JSON path. Space is
+** obtained from sqlite3_malloc().
+*/
+static char *jsonPathSyntaxError(const char *zErr){
+ return sqlite3_mprintf("JSON path error near '%q'", zErr);
+}
+
+/*
+** Do a node lookup using zPath. Return a pointer to the node on success.
+** Return NULL if not found or if there is an error.
+**
+** On an error, write an error message into pCtx and increment the
+** pParse->nErr counter.
+**
+** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
+** nodes are appended.
+*/
+static JsonNode *jsonLookup(
+ JsonParse *pParse, /* The JSON to search */
+ const char *zPath, /* The path to search */
+ int *pApnd, /* Append nodes to complete path if not NULL */
+ sqlite3_context *pCtx /* Report errors here, if not NULL */
+){
+ const char *zErr = 0;
+ JsonNode *pNode = 0;
+ char *zMsg;
+
+ if( zPath==0 ) return 0;
+ if( zPath[0]!='$' ){
+ zErr = zPath;
+ goto lookup_err;
+ }
+ zPath++;
+ pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
+ if( zErr==0 ) return pNode;
+
+lookup_err:
+ pParse->nErr++;
+ assert( zErr!=0 && pCtx!=0 );
+ zMsg = jsonPathSyntaxError(zErr);
+ if( zMsg ){
+ sqlite3_result_error(pCtx, zMsg, -1);
+ sqlite3_free(zMsg);
+ }else{
+ sqlite3_result_error_nomem(pCtx);
+ }
+ return 0;
+}
+
+
+/*
+** Report the wrong number of arguments for json_insert(), json_replace()
+** or json_set().
+*/
+static void jsonWrongNumArgs(
+ sqlite3_context *pCtx,
+ const char *zFuncName
+){
+ char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
+ zFuncName);
+ sqlite3_result_error(pCtx, zMsg, -1);
+ sqlite3_free(zMsg);
+}
+
+/*
+** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
+*/
+static void jsonRemoveAllNulls(JsonNode *pNode){
+ int i, n;
+ assert( pNode->eType==JSON_OBJECT );
+ n = pNode->n;
+ for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
+ switch( pNode[i].eType ){
+ case JSON_NULL:
+ pNode[i].jnFlags |= JNODE_REMOVE;
+ break;
+ case JSON_OBJECT:
+ jsonRemoveAllNulls(&pNode[i]);
+ break;
+ }
+ }
+}
+
+
+/****************************************************************************
+** SQL functions used for testing and debugging
+****************************************************************************/
+
+#ifdef SQLITE_DEBUG
+/*
+** The json_parse(JSON) function returns a string which describes
+** a parse of the JSON provided. Or it returns NULL if JSON is not
+** well-formed.
+*/
+static void jsonParseFunc(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ JsonString s; /* Output string - not real JSON */
+ JsonParse x; /* The parse */
+ u32 i;
+
+ assert( argc==1 );
+ if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
+ jsonParseFindParents(&x);
+ jsonInit(&s, ctx);
+ for(i=0; i<x.nNode; i++){
+ const char *zType;
+ if( x.aNode[i].jnFlags & JNODE_LABEL ){
+ assert( x.aNode[i].eType==JSON_STRING );
+ zType = "label";
+ }else{
+ zType = jsonType[x.aNode[i].eType];
+ }
+ jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
+ i, zType, x.aNode[i].n, x.aUp[i]);
+ if( x.aNode[i].u.zJContent!=0 ){
+ jsonAppendRaw(&s, " ", 1);
+ jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
+ }
+ jsonAppendRaw(&s, "\n", 1);
+ }
+ jsonParseReset(&x);
+ jsonResult(&s);
+}
+
+/*
+** The json_test1(JSON) function return true (1) if the input is JSON
+** text generated by another json function. It returns (0) if the input
+** is not known to be JSON.
+*/
+static void jsonTest1Func(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ UNUSED_PARAM(argc);
+ sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
+}
+#endif /* SQLITE_DEBUG */
+
+/****************************************************************************
+** Scalar SQL function implementations
+****************************************************************************/
+
+/*
+** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
+** corresponding to the SQL value input. Mostly this means putting
+** double-quotes around strings and returning the unquoted string "null"
+** when given a NULL input.
+*/
+static void jsonQuoteFunc(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ JsonString jx;
+ UNUSED_PARAM(argc);
+
+ jsonInit(&jx, ctx);
+ jsonAppendValue(&jx, argv[0]);
+ jsonResult(&jx);
+ sqlite3_result_subtype(ctx, JSON_SUBTYPE);
+}
+
+/*
+** Implementation of the json_array(VALUE,...) function. Return a JSON
+** array that contains all values given in arguments. Or if any argument
+** is a BLOB, throw an error.
+*/
+static void jsonArrayFunc(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ int i;
+ JsonString jx;
+
+ jsonInit(&jx, ctx);
+ jsonAppendChar(&jx, '[');
+ for(i=0; i<argc; i++){
+ jsonAppendSeparator(&jx);
+ jsonAppendValue(&jx, argv[i]);
+ }
+ jsonAppendChar(&jx, ']');
+ jsonResult(&jx);
+ sqlite3_result_subtype(ctx, JSON_SUBTYPE);
+}
+
+
+/*
+** json_array_length(JSON)
+** json_array_length(JSON, PATH)
+**
+** Return the number of elements in the top-level JSON array.
+** Return 0 if the input is not a well-formed JSON array.
+*/
+static void jsonArrayLengthFunc(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ JsonParse *p; /* The parse */
+ sqlite3_int64 n = 0;
+ u32 i;
+ JsonNode *pNode;
+
+ p = jsonParseCached(ctx, argv, ctx);
+ if( p==0 ) return;
+ assert( p->nNode );
+ if( argc==2 ){
+ const char *zPath = (const char*)sqlite3_value_text(argv[1]);
+ pNode = jsonLookup(p, zPath, 0, ctx);
+ }else{
+ pNode = p->aNode;
+ }
+ if( pNode==0 ){
+ return;
+ }
+ if( pNode->eType==JSON_ARRAY ){
+ assert( (pNode->jnFlags & JNODE_APPEND)==0 );
+ for(i=1; i<=pNode->n; n++){
+ i += jsonNodeSize(&pNode[i]);
+ }
+ }
+ sqlite3_result_int64(ctx, n);
+}
+
+/*
+** json_extract(JSON, PATH, ...)
+**
+** Return the element described by PATH. Return NULL if there is no
+** PATH element. If there are multiple PATHs, then return a JSON array
+** with the result from each path. Throw an error if the JSON or any PATH
+** is malformed.
+*/
+static void jsonExtractFunc(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ JsonParse *p; /* The parse */
+ JsonNode *pNode;
+ const char *zPath;
+ JsonString jx;
+ int i;
+
+ if( argc<2 ) return;
+ p = jsonParseCached(ctx, argv, ctx);
+ if( p==0 ) return;
+ jsonInit(&jx, ctx);
+ jsonAppendChar(&jx, '[');
+ for(i=1; i<argc; i++){
+ zPath = (const char*)sqlite3_value_text(argv[i]);
+ pNode = jsonLookup(p, zPath, 0, ctx);
+ if( p->nErr ) break;
+ if( argc>2 ){
+ jsonAppendSeparator(&jx);
+ if( pNode ){
+ jsonRenderNode(pNode, &jx, 0);
+ }else{
+ jsonAppendRaw(&jx, "null", 4);
+ }
+ }else if( pNode ){
+ jsonReturn(pNode, ctx, 0);
+ }
+ }
+ if( argc>2 && i==argc ){
+ jsonAppendChar(&jx, ']');
+ jsonResult(&jx);
+ sqlite3_result_subtype(ctx, JSON_SUBTYPE);
+ }
+ jsonReset(&jx);
+}
+
+/* This is the RFC 7396 MergePatch algorithm.
+*/
+static JsonNode *jsonMergePatch(
+ JsonParse *pParse, /* The JSON parser that contains the TARGET */
+ u32 iTarget, /* Node of the TARGET in pParse */
+ JsonNode *pPatch /* The PATCH */
+){
+ u32 i, j;
+ u32 iRoot;
+ JsonNode *pTarget;
+ if( pPatch->eType!=JSON_OBJECT ){
+ return pPatch;
+ }
+ assert( iTarget>=0 && iTarget<pParse->nNode );
+ pTarget = &pParse->aNode[iTarget];
+ assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
+ if( pTarget->eType!=JSON_OBJECT ){
+ jsonRemoveAllNulls(pPatch);
+ return pPatch;
+ }
+ iRoot = iTarget;
+ for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
+ u32 nKey;
+ const char *zKey;
+ assert( pPatch[i].eType==JSON_STRING );
+ assert( pPatch[i].jnFlags & JNODE_LABEL );
+ nKey = pPatch[i].n;
+ zKey = pPatch[i].u.zJContent;
+ assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
+ for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
+ assert( pTarget[j].eType==JSON_STRING );
+ assert( pTarget[j].jnFlags & JNODE_LABEL );
+ assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
+ if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
+ if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
+ if( pPatch[i+1].eType==JSON_NULL ){
+ pTarget[j+1].jnFlags |= JNODE_REMOVE;
+ }else{
+ JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
+ if( pNew==0 ) return 0;
+ pTarget = &pParse->aNode[iTarget];
+ if( pNew!=&pTarget[j+1] ){
+ pTarget[j+1].u.pPatch = pNew;
+ pTarget[j+1].jnFlags |= JNODE_PATCH;
+ }
+ }
+ break;
+ }
+ }
+ if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
+ int iStart, iPatch;
+ iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
+ jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
+ iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
+ if( pParse->oom ) return 0;
+ jsonRemoveAllNulls(pPatch);
+ pTarget = &pParse->aNode[iTarget];
+ pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
+ pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
+ iRoot = iStart;
+ pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
+ pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
+ }
+ }
+ return pTarget;
+}
+
+/*
+** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
+** object that is the result of running the RFC 7396 MergePatch() algorithm
+** on the two arguments.
+*/
+static void jsonPatchFunc(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ JsonParse x; /* The JSON that is being patched */
+ JsonParse y; /* The patch */
+ JsonNode *pResult; /* The result of the merge */
+
+ UNUSED_PARAM(argc);
+ if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
+ if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
+ jsonParseReset(&x);
+ return;
+ }
+ pResult = jsonMergePatch(&x, 0, y.aNode);
+ assert( pResult!=0 || x.oom );
+ if( pResult ){
+ jsonReturnJson(pResult, ctx, 0);
+ }else{
+ sqlite3_result_error_nomem(ctx);
+ }
+ jsonParseReset(&x);
+ jsonParseReset(&y);
+}
+
+
+/*
+** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
+** object that contains all name/value given in arguments. Or if any name
+** is not a string or if any value is a BLOB, throw an error.
+*/
+static void jsonObjectFunc(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ int i;
+ JsonString jx;
+ const char *z;
+ u32 n;
+
+ if( argc&1 ){
+ sqlite3_result_error(ctx, "json_object() requires an even number "
+ "of arguments", -1);
+ return;
+ }
+ jsonInit(&jx, ctx);
+ jsonAppendChar(&jx, '{');
+ for(i=0; i<argc; i+=2){
+ if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
+ sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
+ jsonReset(&jx);
+ return;
+ }
+ jsonAppendSeparator(&jx);
+ z = (const char*)sqlite3_value_text(argv[i]);
+ n = (u32)sqlite3_value_bytes(argv[i]);
+ jsonAppendString(&jx, z, n);
+ jsonAppendChar(&jx, ':');
+ jsonAppendValue(&jx, argv[i+1]);
+ }
+ jsonAppendChar(&jx, '}');
+ jsonResult(&jx);
+ sqlite3_result_subtype(ctx, JSON_SUBTYPE);
+}
+
+
+/*
+** json_remove(JSON, PATH, ...)
+**
+** Remove the named elements from JSON and return the result. malformed
+** JSON or PATH arguments result in an error.
+*/
+static void jsonRemoveFunc(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ JsonParse x; /* The parse */
+ JsonNode *pNode;
+ const char *zPath;
+ u32 i;
+
+ if( argc<1 ) return;
+ if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
+ assert( x.nNode );
+ for(i=1; i<(u32)argc; i++){
+ zPath = (const char*)sqlite3_value_text(argv[i]);
+ if( zPath==0 ) goto remove_done;
+ pNode = jsonLookup(&x, zPath, 0, ctx);
+ if( x.nErr ) goto remove_done;
+ if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
+ }
+ if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
+ jsonReturnJson(x.aNode, ctx, 0);
+ }
+remove_done:
+ jsonParseReset(&x);
+}
+
+/*
+** json_replace(JSON, PATH, VALUE, ...)
+**
+** Replace the value at PATH with VALUE. If PATH does not already exist,
+** this routine is a no-op. If JSON or PATH is malformed, throw an error.
+*/
+static void jsonReplaceFunc(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ JsonParse x; /* The parse */
+ JsonNode *pNode;
+ const char *zPath;
+ u32 i;
+
+ if( argc<1 ) return;
+ if( (argc&1)==0 ) {
+ jsonWrongNumArgs(ctx, "replace");
+ return;
+ }
+ if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
+ assert( x.nNode );
+ for(i=1; i<(u32)argc; i+=2){
+ zPath = (const char*)sqlite3_value_text(argv[i]);
+ pNode = jsonLookup(&x, zPath, 0, ctx);
+ if( x.nErr ) goto replace_err;
+ if( pNode ){
+ pNode->jnFlags |= (u8)JNODE_REPLACE;
+ pNode->u.iReplace = i + 1;
+ }
+ }
+ if( x.aNode[0].jnFlags & JNODE_REPLACE ){
+ sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
+ }else{
+ jsonReturnJson(x.aNode, ctx, argv);
+ }
+replace_err:
+ jsonParseReset(&x);
+}
+
+/*
+** json_set(JSON, PATH, VALUE, ...)
+**
+** Set the value at PATH to VALUE. Create the PATH if it does not already
+** exist. Overwrite existing values that do exist.
+** If JSON or PATH is malformed, throw an error.
+**
+** json_insert(JSON, PATH, VALUE, ...)
+**
+** Create PATH and initialize it to VALUE. If PATH already exists, this
+** routine is a no-op. If JSON or PATH is malformed, throw an error.
+*/
+static void jsonSetFunc(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ JsonParse x; /* The parse */
+ JsonNode *pNode;
+ const char *zPath;
+ u32 i;
+ int bApnd;
+ int bIsSet = *(int*)sqlite3_user_data(ctx);
+
+ if( argc<1 ) return;
+ if( (argc&1)==0 ) {
+ jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
+ return;
+ }
+ if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
+ assert( x.nNode );
+ for(i=1; i<(u32)argc; i+=2){
+ zPath = (const char*)sqlite3_value_text(argv[i]);
+ bApnd = 0;
+ pNode = jsonLookup(&x, zPath, &bApnd, ctx);
+ if( x.oom ){
+ sqlite3_result_error_nomem(ctx);
+ goto jsonSetDone;
+ }else if( x.nErr ){
+ goto jsonSetDone;
+ }else if( pNode && (bApnd || bIsSet) ){
+ pNode->jnFlags |= (u8)JNODE_REPLACE;
+ pNode->u.iReplace = i + 1;
+ }
+ }
+ if( x.aNode[0].jnFlags & JNODE_REPLACE ){
+ sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
+ }else{
+ jsonReturnJson(x.aNode, ctx, argv);
+ }
+jsonSetDone:
+ jsonParseReset(&x);
+}
+
+/*
+** json_type(JSON)
+** json_type(JSON, PATH)
+**
+** Return the top-level "type" of a JSON string. Throw an error if
+** either the JSON or PATH inputs are not well-formed.
+*/
+static void jsonTypeFunc(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ JsonParse *p; /* The parse */
+ const char *zPath;
+ JsonNode *pNode;
+
+ p = jsonParseCached(ctx, argv, ctx);
+ if( p==0 ) return;
+ if( argc==2 ){
+ zPath = (const char*)sqlite3_value_text(argv[1]);
+ pNode = jsonLookup(p, zPath, 0, ctx);
+ }else{
+ pNode = p->aNode;
+ }
+ if( pNode ){
+ sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
+ }
+}
+
+/*
+** json_valid(JSON)
+**
+** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
+** Return 0 otherwise.
+*/
+static void jsonValidFunc(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ JsonParse *p; /* The parse */
+ UNUSED_PARAM(argc);
+ p = jsonParseCached(ctx, argv, 0);
+ sqlite3_result_int(ctx, p!=0);
+}
+
+
+/****************************************************************************
+** Aggregate SQL function implementations
+****************************************************************************/
+/*
+** json_group_array(VALUE)
+**
+** Return a JSON array composed of all values in the aggregate.
+*/
+static void jsonArrayStep(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ JsonString *pStr;
+ UNUSED_PARAM(argc);
+ pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
+ if( pStr ){
+ if( pStr->zBuf==0 ){
+ jsonInit(pStr, ctx);
+ jsonAppendChar(pStr, '[');
+ }else if( pStr->nUsed>1 ){
+ jsonAppendChar(pStr, ',');
+ pStr->pCtx = ctx;
+ }
+ jsonAppendValue(pStr, argv[0]);
+ }
+}
+static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
+ JsonString *pStr;
+ pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
+ if( pStr ){
+ pStr->pCtx = ctx;
+ jsonAppendChar(pStr, ']');
+ if( pStr->bErr ){
+ if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
+ assert( pStr->bStatic );
+ }else if( isFinal ){
+ sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
+ pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
+ pStr->bStatic = 1;
+ }else{
+ sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
+ pStr->nUsed--;
+ }
+ }else{
+ sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
+ }
+ sqlite3_result_subtype(ctx, JSON_SUBTYPE);
+}
+static void jsonArrayValue(sqlite3_context *ctx){
+ jsonArrayCompute(ctx, 0);
+}
+static void jsonArrayFinal(sqlite3_context *ctx){
+ jsonArrayCompute(ctx, 1);
+}
+
+#ifndef SQLITE_OMIT_WINDOWFUNC
+/*
+** This method works for both json_group_array() and json_group_object().
+** It works by removing the first element of the group by searching forward
+** to the first comma (",") that is not within a string and deleting all
+** text through that comma.
+*/
+static void jsonGroupInverse(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ unsigned int i;
+ int inStr = 0;
+ int nNest = 0;
+ char *z;
+ char c;
+ JsonString *pStr;
+ UNUSED_PARAM(argc);
+ UNUSED_PARAM(argv);
+ pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
+#ifdef NEVER
+ /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
+ ** always have been called to initalize it */
+ if( NEVER(!pStr) ) return;
+#endif
+ z = pStr->zBuf;
+ for(i=1; (c = z[i])!=',' || inStr || nNest; i++){
+ if( i>=pStr->nUsed ){
+ pStr->nUsed = 1;
+ return;
+ }
+ if( c=='"' ){
+ inStr = !inStr;
+ }else if( c=='\\' ){
+ i++;
+ }else if( !inStr ){
+ if( c=='{' || c=='[' ) nNest++;
+ if( c=='}' || c==']' ) nNest--;
+ }
+ }
+ pStr->nUsed -= i;
+ memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
+}
+#else
+# define jsonGroupInverse 0
+#endif
+
+
+/*
+** json_group_obj(NAME,VALUE)
+**
+** Return a JSON object composed of all names and values in the aggregate.
+*/
+static void jsonObjectStep(
+ sqlite3_context *ctx,
+ int argc,
+ sqlite3_value **argv
+){
+ JsonString *pStr;
+ const char *z;
+ u32 n;
+ UNUSED_PARAM(argc);
+ pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
+ if( pStr ){
+ if( pStr->zBuf==0 ){
+ jsonInit(pStr, ctx);
+ jsonAppendChar(pStr, '{');
+ }else if( pStr->nUsed>1 ){
+ jsonAppendChar(pStr, ',');
+ pStr->pCtx = ctx;
+ }
+ z = (const char*)sqlite3_value_text(argv[0]);
+ n = (u32)sqlite3_value_bytes(argv[0]);
+ jsonAppendString(pStr, z, n);
+ jsonAppendChar(pStr, ':');
+ jsonAppendValue(pStr, argv[1]);
+ }
+}
+static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
+ JsonString *pStr;
+ pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
+ if( pStr ){
+ jsonAppendChar(pStr, '}');
+ if( pStr->bErr ){
+ if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
+ assert( pStr->bStatic );
+ }else if( isFinal ){
+ sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
+ pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
+ pStr->bStatic = 1;
+ }else{
+ sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
+ pStr->nUsed--;
+ }
+ }else{
+ sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
+ }
+ sqlite3_result_subtype(ctx, JSON_SUBTYPE);
+}
+static void jsonObjectValue(sqlite3_context *ctx){
+ jsonObjectCompute(ctx, 0);
+}
+static void jsonObjectFinal(sqlite3_context *ctx){
+ jsonObjectCompute(ctx, 1);
+}
+
+
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/****************************************************************************
+** The json_each virtual table
+****************************************************************************/
+typedef struct JsonEachCursor JsonEachCursor;
+struct JsonEachCursor {
+ sqlite3_vtab_cursor base; /* Base class - must be first */
+ u32 iRowid; /* The rowid */
+ u32 iBegin; /* The first node of the scan */
+ u32 i; /* Index in sParse.aNode[] of current row */
+ u32 iEnd; /* EOF when i equals or exceeds this value */
+ u8 eType; /* Type of top-level element */
+ u8 bRecursive; /* True for json_tree(). False for json_each() */
+ char *zJson; /* Input JSON */
+ char *zRoot; /* Path by which to filter zJson */
+ JsonParse sParse; /* Parse of the input JSON */
+};
+
+/* Constructor for the json_each virtual table */
+static int jsonEachConnect(
+ sqlite3 *db,
+ void *pAux,
+ int argc, const char *const*argv,
+ sqlite3_vtab **ppVtab,
+ char **pzErr
+){
+ sqlite3_vtab *pNew;
+ int rc;
+
+/* Column numbers */
+#define JEACH_KEY 0
+#define JEACH_VALUE 1
+#define JEACH_TYPE 2
+#define JEACH_ATOM 3
+#define JEACH_ID 4
+#define JEACH_PARENT 5
+#define JEACH_FULLKEY 6
+#define JEACH_PATH 7
+/* The xBestIndex method assumes that the JSON and ROOT columns are
+** the last two columns in the table. Should this ever changes, be
+** sure to update the xBestIndex method. */
+#define JEACH_JSON 8
+#define JEACH_ROOT 9
+
+ UNUSED_PARAM(pzErr);
+ UNUSED_PARAM(argv);
+ UNUSED_PARAM(argc);
+ UNUSED_PARAM(pAux);
+ rc = sqlite3_declare_vtab(db,
+ "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
+ "json HIDDEN,root HIDDEN)");
+ if( rc==SQLITE_OK ){
+ pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
+ if( pNew==0 ) return SQLITE_NOMEM;
+ memset(pNew, 0, sizeof(*pNew));
+ sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
+ }
+ return rc;
+}
+
+/* destructor for json_each virtual table */
+static int jsonEachDisconnect(sqlite3_vtab *pVtab){
+ sqlite3_free(pVtab);
+ return SQLITE_OK;
+}
+
+/* constructor for a JsonEachCursor object for json_each(). */
+static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
+ JsonEachCursor *pCur;
+
+ UNUSED_PARAM(p);
+ pCur = sqlite3_malloc( sizeof(*pCur) );
+ if( pCur==0 ) return SQLITE_NOMEM;
+ memset(pCur, 0, sizeof(*pCur));
+ *ppCursor = &pCur->base;
+ return SQLITE_OK;
+}
+
+/* constructor for a JsonEachCursor object for json_tree(). */
+static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
+ int rc = jsonEachOpenEach(p, ppCursor);
+ if( rc==SQLITE_OK ){
+ JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
+ pCur->bRecursive = 1;
+ }
+ return rc;
+}
+
+/* Reset a JsonEachCursor back to its original state. Free any memory
+** held. */
+static void jsonEachCursorReset(JsonEachCursor *p){
+ sqlite3_free(p->zJson);
+ sqlite3_free(p->zRoot);
+ jsonParseReset(&p->sParse);
+ p->iRowid = 0;
+ p->i = 0;
+ p->iEnd = 0;
+ p->eType = 0;
+ p->zJson = 0;
+ p->zRoot = 0;
+}
+
+/* Destructor for a jsonEachCursor object */
+static int jsonEachClose(sqlite3_vtab_cursor *cur){
+ JsonEachCursor *p = (JsonEachCursor*)cur;
+ jsonEachCursorReset(p);
+ sqlite3_free(cur);
+ return SQLITE_OK;
+}
+
+/* Return TRUE if the jsonEachCursor object has been advanced off the end
+** of the JSON object */
+static int jsonEachEof(sqlite3_vtab_cursor *cur){
+ JsonEachCursor *p = (JsonEachCursor*)cur;
+ return p->i >= p->iEnd;
+}
+
+/* Advance the cursor to the next element for json_tree() */
+static int jsonEachNext(sqlite3_vtab_cursor *cur){
+ JsonEachCursor *p = (JsonEachCursor*)cur;
+ if( p->bRecursive ){
+ if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
+ p->i++;
+ p->iRowid++;
+ if( p->i<p->iEnd ){
+ u32 iUp = p->sParse.aUp[p->i];
+ JsonNode *pUp = &p->sParse.aNode[iUp];
+ p->eType = pUp->eType;
+ if( pUp->eType==JSON_ARRAY ){
+ if( iUp==p->i-1 ){
+ pUp->u.iKey = 0;
+ }else{
+ pUp->u.iKey++;
+ }
+ }
+ }
+ }else{
+ switch( p->eType ){
+ case JSON_ARRAY: {
+ p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
+ p->iRowid++;
+ break;
+ }
+ case JSON_OBJECT: {
+ p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
+ p->iRowid++;
+ break;
+ }
+ default: {
+ p->i = p->iEnd;
+ break;
+ }
+ }
+ }
+ return SQLITE_OK;
+}
+
+/* Append the name of the path for element i to pStr
+*/
+static void jsonEachComputePath(
+ JsonEachCursor *p, /* The cursor */
+ JsonString *pStr, /* Write the path here */
+ u32 i /* Path to this element */
+){
+ JsonNode *pNode, *pUp;
+ u32 iUp;
+ if( i==0 ){
+ jsonAppendChar(pStr, '$');
+ return;
+ }
+ iUp = p->sParse.aUp[i];
+ jsonEachComputePath(p, pStr, iUp);
+ pNode = &p->sParse.aNode[i];
+ pUp = &p->sParse.aNode[iUp];
+ if( pUp->eType==JSON_ARRAY ){
+ jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
+ }else{
+ assert( pUp->eType==JSON_OBJECT );
+ if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
+ assert( pNode->eType==JSON_STRING );
+ assert( pNode->jnFlags & JNODE_LABEL );
+ jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
+ }
+}
+
+/* Return the value of a column */
+static int jsonEachColumn(
+ sqlite3_vtab_cursor *cur, /* The cursor */
+ sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
+ int i /* Which column to return */
+){
+ JsonEachCursor *p = (JsonEachCursor*)cur;
+ JsonNode *pThis = &p->sParse.aNode[p->i];
+ switch( i ){
+ case JEACH_KEY: {
+ if( p->i==0 ) break;
+ if( p->eType==JSON_OBJECT ){
+ jsonReturn(pThis, ctx, 0);
+ }else if( p->eType==JSON_ARRAY ){
+ u32 iKey;
+ if( p->bRecursive ){
+ if( p->iRowid==0 ) break;
+ iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
+ }else{
+ iKey = p->iRowid;
+ }
+ sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
+ }
+ break;
+ }
+ case JEACH_VALUE: {
+ if( pThis->jnFlags & JNODE_LABEL ) pThis++;
+ jsonReturn(pThis, ctx, 0);
+ break;
+ }
+ case JEACH_TYPE: {
+ if( pThis->jnFlags & JNODE_LABEL ) pThis++;
+ sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
+ break;
+ }
+ case JEACH_ATOM: {
+ if( pThis->jnFlags & JNODE_LABEL ) pThis++;
+ if( pThis->eType>=JSON_ARRAY ) break;
+ jsonReturn(pThis, ctx, 0);
+ break;
+ }
+ case JEACH_ID: {
+ sqlite3_result_int64(ctx,
+ (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
+ break;
+ }
+ case JEACH_PARENT: {
+ if( p->i>p->iBegin && p->bRecursive ){
+ sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
+ }
+ break;
+ }
+ case JEACH_FULLKEY: {
+ JsonString x;
+ jsonInit(&x, ctx);
+ if( p->bRecursive ){
+ jsonEachComputePath(p, &x, p->i);
+ }else{
+ if( p->zRoot ){
+ jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
+ }else{
+ jsonAppendChar(&x, '$');
+ }
+ if( p->eType==JSON_ARRAY ){
+ jsonPrintf(30, &x, "[%d]", p->iRowid);
+ }else if( p->eType==JSON_OBJECT ){
+ jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
+ }
+ }
+ jsonResult(&x);
+ break;
+ }
+ case JEACH_PATH: {
+ if( p->bRecursive ){
+ JsonString x;
+ jsonInit(&x, ctx);
+ jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
+ jsonResult(&x);
+ break;
+ }
+ /* For json_each() path and root are the same so fall through
+ ** into the root case */
+ /* no break */ deliberate_fall_through
+ }
+ default: {
+ const char *zRoot = p->zRoot;
+ if( zRoot==0 ) zRoot = "$";
+ sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
+ break;
+ }
+ case JEACH_JSON: {
+ assert( i==JEACH_JSON );
+ sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
+ break;
+ }
+ }
+ return SQLITE_OK;
+}
+
+/* Return the current rowid value */
+static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
+ JsonEachCursor *p = (JsonEachCursor*)cur;
+ *pRowid = p->iRowid;
+ return SQLITE_OK;
+}
+
+/* The query strategy is to look for an equality constraint on the json
+** column. Without such a constraint, the table cannot operate. idxNum is
+** 1 if the constraint is found, 3 if the constraint and zRoot are found,
+** and 0 otherwise.
+*/
+static int jsonEachBestIndex(
+ sqlite3_vtab *tab,
+ sqlite3_index_info *pIdxInfo
+){
+ int i; /* Loop counter or computed array index */
+ int aIdx[2]; /* Index of constraints for JSON and ROOT */
+ int unusableMask = 0; /* Mask of unusable JSON and ROOT constraints */
+ int idxMask = 0; /* Mask of usable == constraints JSON and ROOT */
+ const struct sqlite3_index_constraint *pConstraint;
+
+ /* This implementation assumes that JSON and ROOT are the last two
+ ** columns in the table */
+ assert( JEACH_ROOT == JEACH_JSON+1 );
+ UNUSED_PARAM(tab);
+ aIdx[0] = aIdx[1] = -1;
+ pConstraint = pIdxInfo->aConstraint;
+ for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
+ int iCol;
+ int iMask;
+ if( pConstraint->iColumn < JEACH_JSON ) continue;
+ iCol = pConstraint->iColumn - JEACH_JSON;
+ assert( iCol==0 || iCol==1 );
+ iMask = 1 << iCol;
+ if( pConstraint->usable==0 ){
+ unusableMask |= iMask;
+ }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
+ aIdx[iCol] = i;
+ idxMask |= iMask;
+ }
+ }
+ if( (unusableMask & ~idxMask)!=0 ){
+ /* If there are any unusable constraints on JSON or ROOT, then reject
+ ** this entire plan */
+ return SQLITE_CONSTRAINT;
+ }
+ if( aIdx[0]<0 ){
+ /* No JSON input. Leave estimatedCost at the huge value that it was
+ ** initialized to to discourage the query planner from selecting this
+ ** plan. */
+ pIdxInfo->idxNum = 0;
+ }else{
+ pIdxInfo->estimatedCost = 1.0;
+ i = aIdx[0];
+ pIdxInfo->aConstraintUsage[i].argvIndex = 1;
+ pIdxInfo->aConstraintUsage[i].omit = 1;
+ if( aIdx[1]<0 ){
+ pIdxInfo->idxNum = 1; /* Only JSON supplied. Plan 1 */
+ }else{
+ i = aIdx[1];
+ pIdxInfo->aConstraintUsage[i].argvIndex = 2;
+ pIdxInfo->aConstraintUsage[i].omit = 1;
+ pIdxInfo->idxNum = 3; /* Both JSON and ROOT are supplied. Plan 3 */
+ }
+ }
+ return SQLITE_OK;
+}
+
+/* Start a search on a new JSON string */
+static int jsonEachFilter(
+ sqlite3_vtab_cursor *cur,
+ int idxNum, const char *idxStr,
+ int argc, sqlite3_value **argv
+){
+ JsonEachCursor *p = (JsonEachCursor*)cur;
+ const char *z;
+ const char *zRoot = 0;
+ sqlite3_int64 n;
+
+ UNUSED_PARAM(idxStr);
+ UNUSED_PARAM(argc);
+ jsonEachCursorReset(p);
+ if( idxNum==0 ) return SQLITE_OK;
+ z = (const char*)sqlite3_value_text(argv[0]);
+ if( z==0 ) return SQLITE_OK;
+ n = sqlite3_value_bytes(argv[0]);
+ p->zJson = sqlite3_malloc64( n+1 );
+ if( p->zJson==0 ) return SQLITE_NOMEM;
+ memcpy(p->zJson, z, (size_t)n+1);
+ if( jsonParse(&p->sParse, 0, p->zJson) ){
+ int rc = SQLITE_NOMEM;
+ if( p->sParse.oom==0 ){
+ sqlite3_free(cur->pVtab->zErrMsg);
+ cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
+ if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
+ }
+ jsonEachCursorReset(p);
+ return rc;
+ }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
+ jsonEachCursorReset(p);
+ return SQLITE_NOMEM;
+ }else{
+ JsonNode *pNode = 0;
+ if( idxNum==3 ){
+ const char *zErr = 0;
+ zRoot = (const char*)sqlite3_value_text(argv[1]);
+ if( zRoot==0 ) return SQLITE_OK;
+ n = sqlite3_value_bytes(argv[1]);
+ p->zRoot = sqlite3_malloc64( n+1 );
+ if( p->zRoot==0 ) return SQLITE_NOMEM;
+ memcpy(p->zRoot, zRoot, (size_t)n+1);
+ if( zRoot[0]!='$' ){
+ zErr = zRoot;
+ }else{
+ pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
+ }
+ if( zErr ){
+ sqlite3_free(cur->pVtab->zErrMsg);
+ cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
+ jsonEachCursorReset(p);
+ return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
+ }else if( pNode==0 ){
+ return SQLITE_OK;
+ }
+ }else{
+ pNode = p->sParse.aNode;
+ }
+ p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
+ p->eType = pNode->eType;
+ if( p->eType>=JSON_ARRAY ){
+ pNode->u.iKey = 0;
+ p->iEnd = p->i + pNode->n + 1;
+ if( p->bRecursive ){
+ p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
+ if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
+ p->i--;
+ }
+ }else{
+ p->i++;
+ }
+ }else{
+ p->iEnd = p->i+1;
+ }
+ }
+ return SQLITE_OK;
+}
+
+/* The methods of the json_each virtual table */
+static sqlite3_module jsonEachModule = {
+ 0, /* iVersion */
+ 0, /* xCreate */
+ jsonEachConnect, /* xConnect */
+ jsonEachBestIndex, /* xBestIndex */
+ jsonEachDisconnect, /* xDisconnect */
+ 0, /* xDestroy */
+ jsonEachOpenEach, /* xOpen - open a cursor */
+ jsonEachClose, /* xClose - close a cursor */
+ jsonEachFilter, /* xFilter - configure scan constraints */
+ jsonEachNext, /* xNext - advance a cursor */
+ jsonEachEof, /* xEof - check for end of scan */
+ jsonEachColumn, /* xColumn - read data */
+ jsonEachRowid, /* xRowid - read data */
+ 0, /* xUpdate */
+ 0, /* xBegin */
+ 0, /* xSync */
+ 0, /* xCommit */
+ 0, /* xRollback */
+ 0, /* xFindMethod */
+ 0, /* xRename */
+ 0, /* xSavepoint */
+ 0, /* xRelease */
+ 0, /* xRollbackTo */
+ 0 /* xShadowName */
+};
+
+/* The methods of the json_tree virtual table. */
+static sqlite3_module jsonTreeModule = {
+ 0, /* iVersion */
+ 0, /* xCreate */
+ jsonEachConnect, /* xConnect */
+ jsonEachBestIndex, /* xBestIndex */
+ jsonEachDisconnect, /* xDisconnect */
+ 0, /* xDestroy */
+ jsonEachOpenTree, /* xOpen - open a cursor */
+ jsonEachClose, /* xClose - close a cursor */
+ jsonEachFilter, /* xFilter - configure scan constraints */
+ jsonEachNext, /* xNext - advance a cursor */
+ jsonEachEof, /* xEof - check for end of scan */
+ jsonEachColumn, /* xColumn - read data */
+ jsonEachRowid, /* xRowid - read data */
+ 0, /* xUpdate */
+ 0, /* xBegin */
+ 0, /* xSync */
+ 0, /* xCommit */
+ 0, /* xRollback */
+ 0, /* xFindMethod */
+ 0, /* xRename */
+ 0, /* xSavepoint */
+ 0, /* xRelease */
+ 0, /* xRollbackTo */
+ 0 /* xShadowName */
+};
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+/****************************************************************************
+** The following routines are the only publically visible identifiers in this
+** file. Call the following routines in order to register the various SQL
+** functions and the virtual table implemented by this file.
+****************************************************************************/
+
+SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
+ int rc = SQLITE_OK;
+ unsigned int i;
+ static const struct {
+ const char *zName;
+ int nArg;
+ int flag;
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
+ } aFunc[] = {
+ { "json", 1, 0, jsonRemoveFunc },
+ { "json_array", -1, 0, jsonArrayFunc },
+ { "json_array_length", 1, 0, jsonArrayLengthFunc },
+ { "json_array_length", 2, 0, jsonArrayLengthFunc },
+ { "json_extract", -1, 0, jsonExtractFunc },
+ { "json_insert", -1, 0, jsonSetFunc },
+ { "json_object", -1, 0, jsonObjectFunc },
+ { "json_patch", 2, 0, jsonPatchFunc },
+ { "json_quote", 1, 0, jsonQuoteFunc },
+ { "json_remove", -1, 0, jsonRemoveFunc },
+ { "json_replace", -1, 0, jsonReplaceFunc },
+ { "json_set", -1, 1, jsonSetFunc },
+ { "json_type", 1, 0, jsonTypeFunc },
+ { "json_type", 2, 0, jsonTypeFunc },
+ { "json_valid", 1, 0, jsonValidFunc },
+
+#if SQLITE_DEBUG
+ /* DEBUG and TESTING functions */
+ { "json_parse", 1, 0, jsonParseFunc },
+ { "json_test1", 1, 0, jsonTest1Func },
+#endif
+ };
+ static const struct {
+ const char *zName;
+ int nArg;
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**);
+ void (*xFinal)(sqlite3_context*);
+ void (*xValue)(sqlite3_context*);
+ } aAgg[] = {
+ { "json_group_array", 1,
+ jsonArrayStep, jsonArrayFinal, jsonArrayValue },
+ { "json_group_object", 2,
+ jsonObjectStep, jsonObjectFinal, jsonObjectValue },
+ };
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ static const struct {
+ const char *zName;
+ sqlite3_module *pModule;
+ } aMod[] = {
+ { "json_each", &jsonEachModule },
+ { "json_tree", &jsonTreeModule },
+ };
+#endif
+ static const int enc =
+ SQLITE_UTF8 |
+ SQLITE_DETERMINISTIC |
+ SQLITE_INNOCUOUS;
+ for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
+ rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg, enc,
+ (void*)&aFunc[i].flag,
+ aFunc[i].xFunc, 0, 0);
+ }
+#ifndef SQLITE_OMIT_WINDOWFUNC
+ for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
+ rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,
+ SQLITE_SUBTYPE | enc, 0,
+ aAgg[i].xStep, aAgg[i].xFinal,
+ aAgg[i].xValue, jsonGroupInverse, 0);
+ }
+#endif
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
+ rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
+ }
+#endif
+ return rc;
+}
+
+
+#ifndef SQLITE_CORE
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+SQLITE_API int sqlite3_json_init(
+ sqlite3 *db,
+ char **pzErrMsg,
+ const sqlite3_api_routines *pApi
+){
+ SQLITE_EXTENSION_INIT2(pApi);
+ (void)pzErrMsg; /* Unused parameter */
+ return sqlite3Json1Init(db);
+}
+#endif
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
+
+/************** End of json1.c ***********************************************/
+/************** Begin file rtree.c *******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code for implementations of the r-tree and r*-tree
+** algorithms packaged as an SQLite virtual table module.
+*/
+
+/*
+** Database Format of R-Tree Tables
+** --------------------------------
+**
+** The data structure for a single virtual r-tree table is stored in three
+** native SQLite tables declared as follows. In each case, the '%' character
+** in the table name is replaced with the user-supplied name of the r-tree
+** table.
+**
+** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
+** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
+** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
+**
+** The data for each node of the r-tree structure is stored in the %_node
+** table. For each node that is not the root node of the r-tree, there is
+** an entry in the %_parent table associating the node with its parent.
+** And for each row of data in the table, there is an entry in the %_rowid
+** table that maps from the entries rowid to the id of the node that it
+** is stored on. If the r-tree contains auxiliary columns, those are stored
+** on the end of the %_rowid table.
+**
+** The root node of an r-tree always exists, even if the r-tree table is
+** empty. The nodeno of the root node is always 1. All other nodes in the
+** table must be the same size as the root node. The content of each node
+** is formatted as follows:
+**
+** 1. If the node is the root node (node 1), then the first 2 bytes
+** of the node contain the tree depth as a big-endian integer.
+** For non-root nodes, the first 2 bytes are left unused.
+**
+** 2. The next 2 bytes contain the number of entries currently
+** stored in the node.
+**
+** 3. The remainder of the node contains the node entries. Each entry
+** consists of a single 8-byte integer followed by an even number
+** of 4-byte coordinates. For leaf nodes the integer is the rowid
+** of a record. For internal nodes it is the node number of a
+** child page.
+*/
+
+#if !defined(SQLITE_CORE) \
+ || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE))
+
+#ifndef SQLITE_CORE
+/* #include "sqlite3ext.h" */
+ SQLITE_EXTENSION_INIT1
+#else
+/* #include "sqlite3.h" */
+#endif
+SQLITE_PRIVATE int sqlite3GetToken(const unsigned char*,int*); /* In the SQLite core */
+
+#ifndef SQLITE_AMALGAMATION
+#include "sqlite3rtree.h"
+typedef sqlite3_int64 i64;
+typedef sqlite3_uint64 u64;
+typedef unsigned char u8;
+typedef unsigned short u16;
+typedef unsigned int u32;
+#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
+# define NDEBUG 1
+#endif
+#if defined(NDEBUG) && defined(SQLITE_DEBUG)
+# undef NDEBUG
+#endif
+#endif
+
+/* #include <string.h> */
+/* #include <stdio.h> */
+/* #include <assert.h> */
+/* #include <stdlib.h> */
+
+/* The following macro is used to suppress compiler warnings.
+*/
+#ifndef UNUSED_PARAMETER
+# define UNUSED_PARAMETER(x) (void)(x)
+#endif
+
+typedef struct Rtree Rtree;
+typedef struct RtreeCursor RtreeCursor;
+typedef struct RtreeNode RtreeNode;
+typedef struct RtreeCell RtreeCell;
+typedef struct RtreeConstraint RtreeConstraint;
+typedef struct RtreeMatchArg RtreeMatchArg;
+typedef struct RtreeGeomCallback RtreeGeomCallback;
+typedef union RtreeCoord RtreeCoord;
+typedef struct RtreeSearchPoint RtreeSearchPoint;
+
+/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
+#define RTREE_MAX_DIMENSIONS 5
+
+/* Maximum number of auxiliary columns */
+#define RTREE_MAX_AUX_COLUMN 100
+
+/* Size of hash table Rtree.aHash. This hash table is not expected to
+** ever contain very many entries, so a fixed number of buckets is
+** used.
+*/
+#define HASHSIZE 97
+
+/* The xBestIndex method of this virtual table requires an estimate of
+** the number of rows in the virtual table to calculate the costs of
+** various strategies. If possible, this estimate is loaded from the
+** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
+** Otherwise, if no sqlite_stat1 entry is available, use
+** RTREE_DEFAULT_ROWEST.
+*/
+#define RTREE_DEFAULT_ROWEST 1048576
+#define RTREE_MIN_ROWEST 100
+
+/*
+** An rtree virtual-table object.
+*/
+struct Rtree {
+ sqlite3_vtab base; /* Base class. Must be first */
+ sqlite3 *db; /* Host database connection */
+ int iNodeSize; /* Size in bytes of each node in the node table */
+ u8 nDim; /* Number of dimensions */
+ u8 nDim2; /* Twice the number of dimensions */
+ u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
+ u8 nBytesPerCell; /* Bytes consumed per cell */
+ u8 inWrTrans; /* True if inside write transaction */
+ u8 nAux; /* # of auxiliary columns in %_rowid */
+ u8 nAuxNotNull; /* Number of initial not-null aux columns */
+#ifdef SQLITE_DEBUG
+ u8 bCorrupt; /* Shadow table corruption detected */
+#endif
+ int iDepth; /* Current depth of the r-tree structure */
+ char *zDb; /* Name of database containing r-tree table */
+ char *zName; /* Name of r-tree table */
+ u32 nBusy; /* Current number of users of this structure */
+ i64 nRowEst; /* Estimated number of rows in this table */
+ u32 nCursor; /* Number of open cursors */
+ u32 nNodeRef; /* Number RtreeNodes with positive nRef */
+ char *zReadAuxSql; /* SQL for statement to read aux data */
+
+ /* List of nodes removed during a CondenseTree operation. List is
+ ** linked together via the pointer normally used for hash chains -
+ ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
+ ** headed by the node (leaf nodes have RtreeNode.iNode==0).
+ */
+ RtreeNode *pDeleted;
+ int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
+
+ /* Blob I/O on xxx_node */
+ sqlite3_blob *pNodeBlob;
+
+ /* Statements to read/write/delete a record from xxx_node */
+ sqlite3_stmt *pWriteNode;
+ sqlite3_stmt *pDeleteNode;
+
+ /* Statements to read/write/delete a record from xxx_rowid */
+ sqlite3_stmt *pReadRowid;
+ sqlite3_stmt *pWriteRowid;
+ sqlite3_stmt *pDeleteRowid;
+
+ /* Statements to read/write/delete a record from xxx_parent */
+ sqlite3_stmt *pReadParent;
+ sqlite3_stmt *pWriteParent;
+ sqlite3_stmt *pDeleteParent;
+
+ /* Statement for writing to the "aux:" fields, if there are any */
+ sqlite3_stmt *pWriteAux;
+
+ RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
+};
+
+/* Possible values for Rtree.eCoordType: */
+#define RTREE_COORD_REAL32 0
+#define RTREE_COORD_INT32 1
+
+/*
+** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
+** only deal with integer coordinates. No floating point operations
+** will be done.
+*/
+#ifdef SQLITE_RTREE_INT_ONLY
+ typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
+ typedef int RtreeValue; /* Low accuracy coordinate */
+# define RTREE_ZERO 0
+#else
+ typedef double RtreeDValue; /* High accuracy coordinate */
+ typedef float RtreeValue; /* Low accuracy coordinate */
+# define RTREE_ZERO 0.0
+#endif
+
+/*
+** Set the Rtree.bCorrupt flag
+*/
+#ifdef SQLITE_DEBUG
+# define RTREE_IS_CORRUPT(X) ((X)->bCorrupt = 1)
+#else
+# define RTREE_IS_CORRUPT(X)
+#endif
+
+/*
+** When doing a search of an r-tree, instances of the following structure
+** record intermediate results from the tree walk.
+**
+** The id is always a node-id. For iLevel>=1 the id is the node-id of
+** the node that the RtreeSearchPoint represents. When iLevel==0, however,
+** the id is of the parent node and the cell that RtreeSearchPoint
+** represents is the iCell-th entry in the parent node.
+*/
+struct RtreeSearchPoint {
+ RtreeDValue rScore; /* The score for this node. Smallest goes first. */
+ sqlite3_int64 id; /* Node ID */
+ u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
+ u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
+ u8 iCell; /* Cell index within the node */
+};
+
+/*
+** The minimum number of cells allowed for a node is a third of the
+** maximum. In Gutman's notation:
+**
+** m = M/3
+**
+** If an R*-tree "Reinsert" operation is required, the same number of
+** cells are removed from the overfull node and reinserted into the tree.
+*/
+#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
+#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
+#define RTREE_MAXCELLS 51
+
+/*
+** The smallest possible node-size is (512-64)==448 bytes. And the largest
+** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
+** Therefore all non-root nodes must contain at least 3 entries. Since
+** 3^40 is greater than 2^64, an r-tree structure always has a depth of
+** 40 or less.
+*/
+#define RTREE_MAX_DEPTH 40
+
+
+/*
+** Number of entries in the cursor RtreeNode cache. The first entry is
+** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
+** entries cache the RtreeNode for the first elements of the priority queue.
+*/
+#define RTREE_CACHE_SZ 5
+
+/*
+** An rtree cursor object.
+*/
+struct RtreeCursor {
+ sqlite3_vtab_cursor base; /* Base class. Must be first */
+ u8 atEOF; /* True if at end of search */
+ u8 bPoint; /* True if sPoint is valid */
+ u8 bAuxValid; /* True if pReadAux is valid */
+ int iStrategy; /* Copy of idxNum search parameter */
+ int nConstraint; /* Number of entries in aConstraint */
+ RtreeConstraint *aConstraint; /* Search constraints. */
+ int nPointAlloc; /* Number of slots allocated for aPoint[] */
+ int nPoint; /* Number of slots used in aPoint[] */
+ int mxLevel; /* iLevel value for root of the tree */
+ RtreeSearchPoint *aPoint; /* Priority queue for search points */
+ sqlite3_stmt *pReadAux; /* Statement to read aux-data */
+ RtreeSearchPoint sPoint; /* Cached next search point */
+ RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
+ u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
+};
+
+/* Return the Rtree of a RtreeCursor */
+#define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
+
+/*
+** A coordinate can be either a floating point number or a integer. All
+** coordinates within a single R-Tree are always of the same time.
+*/
+union RtreeCoord {
+ RtreeValue f; /* Floating point value */
+ int i; /* Integer value */
+ u32 u; /* Unsigned for byte-order conversions */
+};
+
+/*
+** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
+** formatted as a RtreeDValue (double or int64). This macro assumes that local
+** variable pRtree points to the Rtree structure associated with the
+** RtreeCoord.
+*/
+#ifdef SQLITE_RTREE_INT_ONLY
+# define DCOORD(coord) ((RtreeDValue)coord.i)
+#else
+# define DCOORD(coord) ( \
+ (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
+ ((double)coord.f) : \
+ ((double)coord.i) \
+ )
+#endif
+
+/*
+** A search constraint.
+*/
+struct RtreeConstraint {
+ int iCoord; /* Index of constrained coordinate */
+ int op; /* Constraining operation */
+ union {
+ RtreeDValue rValue; /* Constraint value. */
+ int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
+ int (*xQueryFunc)(sqlite3_rtree_query_info*);
+ } u;
+ sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
+};
+
+/* Possible values for RtreeConstraint.op */
+#define RTREE_EQ 0x41 /* A */
+#define RTREE_LE 0x42 /* B */
+#define RTREE_LT 0x43 /* C */
+#define RTREE_GE 0x44 /* D */
+#define RTREE_GT 0x45 /* E */
+#define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
+#define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
+
+/* Special operators available only on cursors. Needs to be consecutive
+** with the normal values above, but must be less than RTREE_MATCH. These
+** are used in the cursor for contraints such as x=NULL (RTREE_FALSE) or
+** x<'xyz' (RTREE_TRUE) */
+#define RTREE_TRUE 0x3f /* ? */
+#define RTREE_FALSE 0x40 /* @ */
+
+/*
+** An rtree structure node.
+*/
+struct RtreeNode {
+ RtreeNode *pParent; /* Parent node */
+ i64 iNode; /* The node number */
+ int nRef; /* Number of references to this node */
+ int isDirty; /* True if the node needs to be written to disk */
+ u8 *zData; /* Content of the node, as should be on disk */
+ RtreeNode *pNext; /* Next node in this hash collision chain */
+};
+
+/* Return the number of cells in a node */
+#define NCELL(pNode) readInt16(&(pNode)->zData[2])
+
+/*
+** A single cell from a node, deserialized
+*/
+struct RtreeCell {
+ i64 iRowid; /* Node or entry ID */
+ RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
+};
+
+
+/*
+** This object becomes the sqlite3_user_data() for the SQL functions
+** that are created by sqlite3_rtree_geometry_callback() and
+** sqlite3_rtree_query_callback() and which appear on the right of MATCH
+** operators in order to constrain a search.
+**
+** xGeom and xQueryFunc are the callback functions. Exactly one of
+** xGeom and xQueryFunc fields is non-NULL, depending on whether the
+** SQL function was created using sqlite3_rtree_geometry_callback() or
+** sqlite3_rtree_query_callback().
+**
+** This object is deleted automatically by the destructor mechanism in
+** sqlite3_create_function_v2().
+*/
+struct RtreeGeomCallback {
+ int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
+ int (*xQueryFunc)(sqlite3_rtree_query_info*);
+ void (*xDestructor)(void*);
+ void *pContext;
+};
+
+/*
+** An instance of this structure (in the form of a BLOB) is returned by
+** the SQL functions that sqlite3_rtree_geometry_callback() and
+** sqlite3_rtree_query_callback() create, and is read as the right-hand
+** operand to the MATCH operator of an R-Tree.
+*/
+struct RtreeMatchArg {
+ u32 iSize; /* Size of this object */
+ RtreeGeomCallback cb; /* Info about the callback functions */
+ int nParam; /* Number of parameters to the SQL function */
+ sqlite3_value **apSqlParam; /* Original SQL parameter values */
+ RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
+};
+
+#ifndef MAX
+# define MAX(x,y) ((x) < (y) ? (y) : (x))
+#endif
+#ifndef MIN
+# define MIN(x,y) ((x) > (y) ? (y) : (x))
+#endif
+
+/* What version of GCC is being used. 0 means GCC is not being used .
+** Note that the GCC_VERSION macro will also be set correctly when using
+** clang, since clang works hard to be gcc compatible. So the gcc
+** optimizations will also work when compiling with clang.
+*/
+#ifndef GCC_VERSION
+#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
+# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
+#else
+# define GCC_VERSION 0
+#endif
+#endif
+
+/* The testcase() macro should already be defined in the amalgamation. If
+** it is not, make it a no-op.
+*/
+#ifndef SQLITE_AMALGAMATION
+# define testcase(X)
+#endif
+
+/*
+** Make sure that the compiler intrinsics we desire are enabled when
+** compiling with an appropriate version of MSVC unless prevented by
+** the SQLITE_DISABLE_INTRINSIC define.
+*/
+#if !defined(SQLITE_DISABLE_INTRINSIC)
+# if defined(_MSC_VER) && _MSC_VER>=1400
+# if !defined(_WIN32_WCE)
+/* # include <intrin.h> */
+# pragma intrinsic(_byteswap_ulong)
+# pragma intrinsic(_byteswap_uint64)
+# else
+/* # include <cmnintrin.h> */
+# endif
+# endif
+#endif
+
+/*
+** Macros to determine whether the machine is big or little endian,
+** and whether or not that determination is run-time or compile-time.
+**
+** For best performance, an attempt is made to guess at the byte-order
+** using C-preprocessor macros. If that is unsuccessful, or if
+** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
+** at run-time.
+*/
+#ifndef SQLITE_BYTEORDER
+#if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
+ defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
+ defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
+ defined(__arm__)
+# define SQLITE_BYTEORDER 1234
+#elif defined(sparc) || defined(__ppc__)
+# define SQLITE_BYTEORDER 4321
+#else
+# define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
+#endif
+#endif
+
+
+/* What version of MSVC is being used. 0 means MSVC is not being used */
+#ifndef MSVC_VERSION
+#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
+# define MSVC_VERSION _MSC_VER
+#else
+# define MSVC_VERSION 0
+#endif
+#endif
+
+/*
+** Functions to deserialize a 16 bit integer, 32 bit real number and
+** 64 bit integer. The deserialized value is returned.
+*/
+static int readInt16(u8 *p){
+ return (p[0]<<8) + p[1];
+}
+static void readCoord(u8 *p, RtreeCoord *pCoord){
+ assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
+#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
+ pCoord->u = _byteswap_ulong(*(u32*)p);
+#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
+ pCoord->u = __builtin_bswap32(*(u32*)p);
+#elif SQLITE_BYTEORDER==4321
+ pCoord->u = *(u32*)p;
+#else
+ pCoord->u = (
+ (((u32)p[0]) << 24) +
+ (((u32)p[1]) << 16) +
+ (((u32)p[2]) << 8) +
+ (((u32)p[3]) << 0)
+ );
+#endif
+}
+static i64 readInt64(u8 *p){
+#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
+ u64 x;
+ memcpy(&x, p, 8);
+ return (i64)_byteswap_uint64(x);
+#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
+ u64 x;
+ memcpy(&x, p, 8);
+ return (i64)__builtin_bswap64(x);
+#elif SQLITE_BYTEORDER==4321
+ i64 x;
+ memcpy(&x, p, 8);
+ return x;
+#else
+ return (i64)(
+ (((u64)p[0]) << 56) +
+ (((u64)p[1]) << 48) +
+ (((u64)p[2]) << 40) +
+ (((u64)p[3]) << 32) +
+ (((u64)p[4]) << 24) +
+ (((u64)p[5]) << 16) +
+ (((u64)p[6]) << 8) +
+ (((u64)p[7]) << 0)
+ );
+#endif
+}
+
+/*
+** Functions to serialize a 16 bit integer, 32 bit real number and
+** 64 bit integer. The value returned is the number of bytes written
+** to the argument buffer (always 2, 4 and 8 respectively).
+*/
+static void writeInt16(u8 *p, int i){
+ p[0] = (i>> 8)&0xFF;
+ p[1] = (i>> 0)&0xFF;
+}
+static int writeCoord(u8 *p, RtreeCoord *pCoord){
+ u32 i;
+ assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
+ assert( sizeof(RtreeCoord)==4 );
+ assert( sizeof(u32)==4 );
+#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
+ i = __builtin_bswap32(pCoord->u);
+ memcpy(p, &i, 4);
+#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
+ i = _byteswap_ulong(pCoord->u);
+ memcpy(p, &i, 4);
+#elif SQLITE_BYTEORDER==4321
+ i = pCoord->u;
+ memcpy(p, &i, 4);
+#else
+ i = pCoord->u;
+ p[0] = (i>>24)&0xFF;
+ p[1] = (i>>16)&0xFF;
+ p[2] = (i>> 8)&0xFF;
+ p[3] = (i>> 0)&0xFF;
+#endif
+ return 4;
+}
+static int writeInt64(u8 *p, i64 i){
+#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
+ i = (i64)__builtin_bswap64((u64)i);
+ memcpy(p, &i, 8);
+#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
+ i = (i64)_byteswap_uint64((u64)i);
+ memcpy(p, &i, 8);
+#elif SQLITE_BYTEORDER==4321
+ memcpy(p, &i, 8);
+#else
+ p[0] = (i>>56)&0xFF;
+ p[1] = (i>>48)&0xFF;
+ p[2] = (i>>40)&0xFF;
+ p[3] = (i>>32)&0xFF;
+ p[4] = (i>>24)&0xFF;
+ p[5] = (i>>16)&0xFF;
+ p[6] = (i>> 8)&0xFF;
+ p[7] = (i>> 0)&0xFF;
+#endif
+ return 8;
+}
+
+/*
+** Increment the reference count of node p.
+*/
+static void nodeReference(RtreeNode *p){
+ if( p ){
+ assert( p->nRef>0 );
+ p->nRef++;
+ }
+}
+
+/*
+** Clear the content of node p (set all bytes to 0x00).
+*/
+static void nodeZero(Rtree *pRtree, RtreeNode *p){
+ memset(&p->zData[2], 0, pRtree->iNodeSize-2);
+ p->isDirty = 1;
+}
+
+/*
+** Given a node number iNode, return the corresponding key to use
+** in the Rtree.aHash table.
+*/
+static unsigned int nodeHash(i64 iNode){
+ return ((unsigned)iNode) % HASHSIZE;
+}
+
+/*
+** Search the node hash table for node iNode. If found, return a pointer
+** to it. Otherwise, return 0.
+*/
+static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
+ RtreeNode *p;
+ for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
+ return p;
+}
+
+/*
+** Add node pNode to the node hash table.
+*/
+static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
+ int iHash;
+ assert( pNode->pNext==0 );
+ iHash = nodeHash(pNode->iNode);
+ pNode->pNext = pRtree->aHash[iHash];
+ pRtree->aHash[iHash] = pNode;
+}
+
+/*
+** Remove node pNode from the node hash table.
+*/
+static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
+ RtreeNode **pp;
+ if( pNode->iNode!=0 ){
+ pp = &pRtree->aHash[nodeHash(pNode->iNode)];
+ for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
+ *pp = pNode->pNext;
+ pNode->pNext = 0;
+ }
+}
+
+/*
+** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
+** indicating that node has not yet been assigned a node number. It is
+** assigned a node number when nodeWrite() is called to write the
+** node contents out to the database.
+*/
+static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
+ RtreeNode *pNode;
+ pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode) + pRtree->iNodeSize);
+ if( pNode ){
+ memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
+ pNode->zData = (u8 *)&pNode[1];
+ pNode->nRef = 1;
+ pRtree->nNodeRef++;
+ pNode->pParent = pParent;
+ pNode->isDirty = 1;
+ nodeReference(pParent);
+ }
+ return pNode;
+}
+
+/*
+** Clear the Rtree.pNodeBlob object
+*/
+static void nodeBlobReset(Rtree *pRtree){
+ if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
+ sqlite3_blob *pBlob = pRtree->pNodeBlob;
+ pRtree->pNodeBlob = 0;
+ sqlite3_blob_close(pBlob);
+ }
+}
+
+/*
+** Check to see if pNode is the same as pParent or any of the parents
+** of pParent.
+*/
+static int nodeInParentChain(const RtreeNode *pNode, const RtreeNode *pParent){
+ do{
+ if( pNode==pParent ) return 1;
+ pParent = pParent->pParent;
+ }while( pParent );
+ return 0;
+}
+
+/*
+** Obtain a reference to an r-tree node.
+*/
+static int nodeAcquire(
+ Rtree *pRtree, /* R-tree structure */
+ i64 iNode, /* Node number to load */
+ RtreeNode *pParent, /* Either the parent node or NULL */
+ RtreeNode **ppNode /* OUT: Acquired node */
+){
+ int rc = SQLITE_OK;
+ RtreeNode *pNode = 0;
+
+ /* Check if the requested node is already in the hash table. If so,
+ ** increase its reference count and return it.
+ */
+ if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){
+ if( pParent && !pNode->pParent ){
+ if( nodeInParentChain(pNode, pParent) ){
+ RTREE_IS_CORRUPT(pRtree);
+ return SQLITE_CORRUPT_VTAB;
+ }
+ pParent->nRef++;
+ pNode->pParent = pParent;
+ }else if( pParent && pNode->pParent && pParent!=pNode->pParent ){
+ RTREE_IS_CORRUPT(pRtree);
+ return SQLITE_CORRUPT_VTAB;
+ }
+ pNode->nRef++;
+ *ppNode = pNode;
+ return SQLITE_OK;
+ }
+
+ if( pRtree->pNodeBlob ){
+ sqlite3_blob *pBlob = pRtree->pNodeBlob;
+ pRtree->pNodeBlob = 0;
+ rc = sqlite3_blob_reopen(pBlob, iNode);
+ pRtree->pNodeBlob = pBlob;
+ if( rc ){
+ nodeBlobReset(pRtree);
+ if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
+ }
+ }
+ if( pRtree->pNodeBlob==0 ){
+ char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
+ if( zTab==0 ) return SQLITE_NOMEM;
+ rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
+ &pRtree->pNodeBlob);
+ sqlite3_free(zTab);
+ }
+ if( rc ){
+ nodeBlobReset(pRtree);
+ *ppNode = 0;
+ /* If unable to open an sqlite3_blob on the desired row, that can only
+ ** be because the shadow tables hold erroneous data. */
+ if( rc==SQLITE_ERROR ){
+ rc = SQLITE_CORRUPT_VTAB;
+ RTREE_IS_CORRUPT(pRtree);
+ }
+ }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
+ pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize);
+ if( !pNode ){
+ rc = SQLITE_NOMEM;
+ }else{
+ pNode->pParent = pParent;
+ pNode->zData = (u8 *)&pNode[1];
+ pNode->nRef = 1;
+ pRtree->nNodeRef++;
+ pNode->iNode = iNode;
+ pNode->isDirty = 0;
+ pNode->pNext = 0;
+ rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
+ pRtree->iNodeSize, 0);
+ }
+ }
+
+ /* If the root node was just loaded, set pRtree->iDepth to the height
+ ** of the r-tree structure. A height of zero means all data is stored on
+ ** the root node. A height of one means the children of the root node
+ ** are the leaves, and so on. If the depth as specified on the root node
+ ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
+ */
+ if( pNode && rc==SQLITE_OK && iNode==1 ){
+ pRtree->iDepth = readInt16(pNode->zData);
+ if( pRtree->iDepth>RTREE_MAX_DEPTH ){
+ rc = SQLITE_CORRUPT_VTAB;
+ RTREE_IS_CORRUPT(pRtree);
+ }
+ }
+
+ /* If no error has occurred so far, check if the "number of entries"
+ ** field on the node is too large. If so, set the return code to
+ ** SQLITE_CORRUPT_VTAB.
+ */
+ if( pNode && rc==SQLITE_OK ){
+ if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
+ rc = SQLITE_CORRUPT_VTAB;
+ RTREE_IS_CORRUPT(pRtree);
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ if( pNode!=0 ){
+ nodeReference(pParent);
+ nodeHashInsert(pRtree, pNode);
+ }else{
+ rc = SQLITE_CORRUPT_VTAB;
+ RTREE_IS_CORRUPT(pRtree);
+ }
+ *ppNode = pNode;
+ }else{
+ if( pNode ){
+ pRtree->nNodeRef--;
+ sqlite3_free(pNode);
+ }
+ *ppNode = 0;
+ }
+
+ return rc;
+}
+
+/*
+** Overwrite cell iCell of node pNode with the contents of pCell.
+*/
+static void nodeOverwriteCell(
+ Rtree *pRtree, /* The overall R-Tree */
+ RtreeNode *pNode, /* The node into which the cell is to be written */
+ RtreeCell *pCell, /* The cell to write */
+ int iCell /* Index into pNode into which pCell is written */
+){
+ int ii;
+ u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
+ p += writeInt64(p, pCell->iRowid);
+ for(ii=0; ii<pRtree->nDim2; ii++){
+ p += writeCoord(p, &pCell->aCoord[ii]);
+ }
+ pNode->isDirty = 1;
+}
+
+/*
+** Remove the cell with index iCell from node pNode.
+*/
+static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
+ u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
+ u8 *pSrc = &pDst[pRtree->nBytesPerCell];
+ int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
+ memmove(pDst, pSrc, nByte);
+ writeInt16(&pNode->zData[2], NCELL(pNode)-1);
+ pNode->isDirty = 1;
+}
+
+/*
+** Insert the contents of cell pCell into node pNode. If the insert
+** is successful, return SQLITE_OK.
+**
+** If there is not enough free space in pNode, return SQLITE_FULL.
+*/
+static int nodeInsertCell(
+ Rtree *pRtree, /* The overall R-Tree */
+ RtreeNode *pNode, /* Write new cell into this node */
+ RtreeCell *pCell /* The cell to be inserted */
+){
+ int nCell; /* Current number of cells in pNode */
+ int nMaxCell; /* Maximum number of cells for pNode */
+
+ nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
+ nCell = NCELL(pNode);
+
+ assert( nCell<=nMaxCell );
+ if( nCell<nMaxCell ){
+ nodeOverwriteCell(pRtree, pNode, pCell, nCell);
+ writeInt16(&pNode->zData[2], nCell+1);
+ pNode->isDirty = 1;
+ }
+
+ return (nCell==nMaxCell);
+}
+
+/*
+** If the node is dirty, write it out to the database.
+*/
+static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
+ int rc = SQLITE_OK;
+ if( pNode->isDirty ){
+ sqlite3_stmt *p = pRtree->pWriteNode;
+ if( pNode->iNode ){
+ sqlite3_bind_int64(p, 1, pNode->iNode);
+ }else{
+ sqlite3_bind_null(p, 1);
+ }
+ sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
+ sqlite3_step(p);
+ pNode->isDirty = 0;
+ rc = sqlite3_reset(p);
+ sqlite3_bind_null(p, 2);
+ if( pNode->iNode==0 && rc==SQLITE_OK ){
+ pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
+ nodeHashInsert(pRtree, pNode);
+ }
+ }
+ return rc;
+}
+
+/*
+** Release a reference to a node. If the node is dirty and the reference
+** count drops to zero, the node data is written to the database.
+*/
+static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
+ int rc = SQLITE_OK;
+ if( pNode ){
+ assert( pNode->nRef>0 );
+ assert( pRtree->nNodeRef>0 );
+ pNode->nRef--;
+ if( pNode->nRef==0 ){
+ pRtree->nNodeRef--;
+ if( pNode->iNode==1 ){
+ pRtree->iDepth = -1;
+ }
+ if( pNode->pParent ){
+ rc = nodeRelease(pRtree, pNode->pParent);
+ }
+ if( rc==SQLITE_OK ){
+ rc = nodeWrite(pRtree, pNode);
+ }
+ nodeHashDelete(pRtree, pNode);
+ sqlite3_free(pNode);
+ }
+ }
+ return rc;
+}
+
+/*
+** Return the 64-bit integer value associated with cell iCell of
+** node pNode. If pNode is a leaf node, this is a rowid. If it is
+** an internal node, then the 64-bit integer is a child page number.
+*/
+static i64 nodeGetRowid(
+ Rtree *pRtree, /* The overall R-Tree */
+ RtreeNode *pNode, /* The node from which to extract the ID */
+ int iCell /* The cell index from which to extract the ID */
+){
+ assert( iCell<NCELL(pNode) );
+ return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
+}
+
+/*
+** Return coordinate iCoord from cell iCell in node pNode.
+*/
+static void nodeGetCoord(
+ Rtree *pRtree, /* The overall R-Tree */
+ RtreeNode *pNode, /* The node from which to extract a coordinate */
+ int iCell, /* The index of the cell within the node */
+ int iCoord, /* Which coordinate to extract */
+ RtreeCoord *pCoord /* OUT: Space to write result to */
+){
+ readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
+}
+
+/*
+** Deserialize cell iCell of node pNode. Populate the structure pointed
+** to by pCell with the results.
+*/
+static void nodeGetCell(
+ Rtree *pRtree, /* The overall R-Tree */
+ RtreeNode *pNode, /* The node containing the cell to be read */
+ int iCell, /* Index of the cell within the node */
+ RtreeCell *pCell /* OUT: Write the cell contents here */
+){
+ u8 *pData;
+ RtreeCoord *pCoord;
+ int ii = 0;
+ pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
+ pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
+ pCoord = pCell->aCoord;
+ do{
+ readCoord(pData, &pCoord[ii]);
+ readCoord(pData+4, &pCoord[ii+1]);
+ pData += 8;
+ ii += 2;
+ }while( ii<pRtree->nDim2 );
+}
+
+
+/* Forward declaration for the function that does the work of
+** the virtual table module xCreate() and xConnect() methods.
+*/
+static int rtreeInit(
+ sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
+);
+
+/*
+** Rtree virtual table module xCreate method.
+*/
+static int rtreeCreate(
+ sqlite3 *db,
+ void *pAux,
+ int argc, const char *const*argv,
+ sqlite3_vtab **ppVtab,
+ char **pzErr
+){
+ return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
+}
+
+/*
+** Rtree virtual table module xConnect method.
+*/
+static int rtreeConnect(
+ sqlite3 *db,
+ void *pAux,
+ int argc, const char *const*argv,
+ sqlite3_vtab **ppVtab,
+ char **pzErr
+){
+ return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
+}
+
+/*
+** Increment the r-tree reference count.
+*/
+static void rtreeReference(Rtree *pRtree){
+ pRtree->nBusy++;
+}
+
+/*
+** Decrement the r-tree reference count. When the reference count reaches
+** zero the structure is deleted.
+*/
+static void rtreeRelease(Rtree *pRtree){
+ pRtree->nBusy--;
+ if( pRtree->nBusy==0 ){
+ pRtree->inWrTrans = 0;
+ assert( pRtree->nCursor==0 );
+ nodeBlobReset(pRtree);
+ assert( pRtree->nNodeRef==0 || pRtree->bCorrupt );
+ sqlite3_finalize(pRtree->pWriteNode);
+ sqlite3_finalize(pRtree->pDeleteNode);
+ sqlite3_finalize(pRtree->pReadRowid);
+ sqlite3_finalize(pRtree->pWriteRowid);
+ sqlite3_finalize(pRtree->pDeleteRowid);
+ sqlite3_finalize(pRtree->pReadParent);
+ sqlite3_finalize(pRtree->pWriteParent);
+ sqlite3_finalize(pRtree->pDeleteParent);
+ sqlite3_finalize(pRtree->pWriteAux);
+ sqlite3_free(pRtree->zReadAuxSql);
+ sqlite3_free(pRtree);
+ }
+}
+
+/*
+** Rtree virtual table module xDisconnect method.
+*/
+static int rtreeDisconnect(sqlite3_vtab *pVtab){
+ rtreeRelease((Rtree *)pVtab);
+ return SQLITE_OK;
+}
+
+/*
+** Rtree virtual table module xDestroy method.
+*/
+static int rtreeDestroy(sqlite3_vtab *pVtab){
+ Rtree *pRtree = (Rtree *)pVtab;
+ int rc;
+ char *zCreate = sqlite3_mprintf(
+ "DROP TABLE '%q'.'%q_node';"
+ "DROP TABLE '%q'.'%q_rowid';"
+ "DROP TABLE '%q'.'%q_parent';",
+ pRtree->zDb, pRtree->zName,
+ pRtree->zDb, pRtree->zName,
+ pRtree->zDb, pRtree->zName
+ );
+ if( !zCreate ){
+ rc = SQLITE_NOMEM;
+ }else{
+ nodeBlobReset(pRtree);
+ rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
+ sqlite3_free(zCreate);
+ }
+ if( rc==SQLITE_OK ){
+ rtreeRelease(pRtree);
+ }
+
+ return rc;
+}
+
+/*
+** Rtree virtual table module xOpen method.
+*/
+static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
+ int rc = SQLITE_NOMEM;
+ Rtree *pRtree = (Rtree *)pVTab;
+ RtreeCursor *pCsr;
+
+ pCsr = (RtreeCursor *)sqlite3_malloc64(sizeof(RtreeCursor));
+ if( pCsr ){
+ memset(pCsr, 0, sizeof(RtreeCursor));
+ pCsr->base.pVtab = pVTab;
+ rc = SQLITE_OK;
+ pRtree->nCursor++;
+ }
+ *ppCursor = (sqlite3_vtab_cursor *)pCsr;
+
+ return rc;
+}
+
+
+/*
+** Reset a cursor back to its initial state.
+*/
+static void resetCursor(RtreeCursor *pCsr){
+ Rtree *pRtree = (Rtree *)(pCsr->base.pVtab);
+ int ii;
+ sqlite3_stmt *pStmt;
+ if( pCsr->aConstraint ){
+ int i; /* Used to iterate through constraint array */
+ for(i=0; i<pCsr->nConstraint; i++){
+ sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
+ if( pInfo ){
+ if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
+ sqlite3_free(pInfo);
+ }
+ }
+ sqlite3_free(pCsr->aConstraint);
+ pCsr->aConstraint = 0;
+ }
+ for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
+ sqlite3_free(pCsr->aPoint);
+ pStmt = pCsr->pReadAux;
+ memset(pCsr, 0, sizeof(RtreeCursor));
+ pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
+ pCsr->pReadAux = pStmt;
+
+}
+
+/*
+** Rtree virtual table module xClose method.
+*/
+static int rtreeClose(sqlite3_vtab_cursor *cur){
+ Rtree *pRtree = (Rtree *)(cur->pVtab);
+ RtreeCursor *pCsr = (RtreeCursor *)cur;
+ assert( pRtree->nCursor>0 );
+ resetCursor(pCsr);
+ sqlite3_finalize(pCsr->pReadAux);
+ sqlite3_free(pCsr);
+ pRtree->nCursor--;
+ nodeBlobReset(pRtree);
+ return SQLITE_OK;
+}
+
+/*
+** Rtree virtual table module xEof method.
+**
+** Return non-zero if the cursor does not currently point to a valid
+** record (i.e if the scan has finished), or zero otherwise.
+*/
+static int rtreeEof(sqlite3_vtab_cursor *cur){
+ RtreeCursor *pCsr = (RtreeCursor *)cur;
+ return pCsr->atEOF;
+}
+
+/*
+** Convert raw bits from the on-disk RTree record into a coordinate value.
+** The on-disk format is big-endian and needs to be converted for little-
+** endian platforms. The on-disk record stores integer coordinates if
+** eInt is true and it stores 32-bit floating point records if eInt is
+** false. a[] is the four bytes of the on-disk record to be decoded.
+** Store the results in "r".
+**
+** There are five versions of this macro. The last one is generic. The
+** other four are various architectures-specific optimizations.
+*/
+#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
+#define RTREE_DECODE_COORD(eInt, a, r) { \
+ RtreeCoord c; /* Coordinate decoded */ \
+ c.u = _byteswap_ulong(*(u32*)a); \
+ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
+}
+#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
+#define RTREE_DECODE_COORD(eInt, a, r) { \
+ RtreeCoord c; /* Coordinate decoded */ \
+ c.u = __builtin_bswap32(*(u32*)a); \
+ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
+}
+#elif SQLITE_BYTEORDER==1234
+#define RTREE_DECODE_COORD(eInt, a, r) { \
+ RtreeCoord c; /* Coordinate decoded */ \
+ memcpy(&c.u,a,4); \
+ c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
+ ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
+ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
+}
+#elif SQLITE_BYTEORDER==4321
+#define RTREE_DECODE_COORD(eInt, a, r) { \
+ RtreeCoord c; /* Coordinate decoded */ \
+ memcpy(&c.u,a,4); \
+ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
+}
+#else
+#define RTREE_DECODE_COORD(eInt, a, r) { \
+ RtreeCoord c; /* Coordinate decoded */ \
+ c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
+ +((u32)a[2]<<8) + a[3]; \
+ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
+}
+#endif
+
+/*
+** Check the RTree node or entry given by pCellData and p against the MATCH
+** constraint pConstraint.
+*/
+static int rtreeCallbackConstraint(
+ RtreeConstraint *pConstraint, /* The constraint to test */
+ int eInt, /* True if RTree holding integer coordinates */
+ u8 *pCellData, /* Raw cell content */
+ RtreeSearchPoint *pSearch, /* Container of this cell */
+ sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
+ int *peWithin /* OUT: visibility of the cell */
+){
+ sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
+ int nCoord = pInfo->nCoord; /* No. of coordinates */
+ int rc; /* Callback return code */
+ RtreeCoord c; /* Translator union */
+ sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
+
+ assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
+ assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
+
+ if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
+ pInfo->iRowid = readInt64(pCellData);
+ }
+ pCellData += 8;
+#ifndef SQLITE_RTREE_INT_ONLY
+ if( eInt==0 ){
+ switch( nCoord ){
+ case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f;
+ readCoord(pCellData+32, &c); aCoord[8] = c.f;
+ case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f;
+ readCoord(pCellData+24, &c); aCoord[6] = c.f;
+ case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f;
+ readCoord(pCellData+16, &c); aCoord[4] = c.f;
+ case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f;
+ readCoord(pCellData+8, &c); aCoord[2] = c.f;
+ default: readCoord(pCellData+4, &c); aCoord[1] = c.f;
+ readCoord(pCellData, &c); aCoord[0] = c.f;
+ }
+ }else
+#endif
+ {
+ switch( nCoord ){
+ case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i;
+ readCoord(pCellData+32, &c); aCoord[8] = c.i;
+ case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i;
+ readCoord(pCellData+24, &c); aCoord[6] = c.i;
+ case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i;
+ readCoord(pCellData+16, &c); aCoord[4] = c.i;
+ case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i;
+ readCoord(pCellData+8, &c); aCoord[2] = c.i;
+ default: readCoord(pCellData+4, &c); aCoord[1] = c.i;
+ readCoord(pCellData, &c); aCoord[0] = c.i;
+ }
+ }
+ if( pConstraint->op==RTREE_MATCH ){
+ int eWithin = 0;
+ rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
+ nCoord, aCoord, &eWithin);
+ if( eWithin==0 ) *peWithin = NOT_WITHIN;
+ *prScore = RTREE_ZERO;
+ }else{
+ pInfo->aCoord = aCoord;
+ pInfo->iLevel = pSearch->iLevel - 1;
+ pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
+ pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
+ rc = pConstraint->u.xQueryFunc(pInfo);
+ if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
+ if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
+ *prScore = pInfo->rScore;
+ }
+ }
+ return rc;
+}
+
+/*
+** Check the internal RTree node given by pCellData against constraint p.
+** If this constraint cannot be satisfied by any child within the node,
+** set *peWithin to NOT_WITHIN.
+*/
+static void rtreeNonleafConstraint(
+ RtreeConstraint *p, /* The constraint to test */
+ int eInt, /* True if RTree holds integer coordinates */
+ u8 *pCellData, /* Raw cell content as appears on disk */
+ int *peWithin /* Adjust downward, as appropriate */
+){
+ sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
+
+ /* p->iCoord might point to either a lower or upper bound coordinate
+ ** in a coordinate pair. But make pCellData point to the lower bound.
+ */
+ pCellData += 8 + 4*(p->iCoord&0xfe);
+
+ assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
+ || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
+ || p->op==RTREE_FALSE );
+ assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
+ switch( p->op ){
+ case RTREE_TRUE: return; /* Always satisfied */
+ case RTREE_FALSE: break; /* Never satisfied */
+ case RTREE_LE:
+ case RTREE_LT:
+ case RTREE_EQ:
+ RTREE_DECODE_COORD(eInt, pCellData, val);
+ /* val now holds the lower bound of the coordinate pair */
+ if( p->u.rValue>=val ) return;
+ if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
+ /* Fall through for the RTREE_EQ case */
+
+ default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
+ pCellData += 4;
+ RTREE_DECODE_COORD(eInt, pCellData, val);
+ /* val now holds the upper bound of the coordinate pair */
+ if( p->u.rValue<=val ) return;
+ }
+ *peWithin = NOT_WITHIN;
+}
+
+/*
+** Check the leaf RTree cell given by pCellData against constraint p.
+** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
+** If the constraint is satisfied, leave *peWithin unchanged.
+**
+** The constraint is of the form: xN op $val
+**
+** The op is given by p->op. The xN is p->iCoord-th coordinate in
+** pCellData. $val is given by p->u.rValue.
+*/
+static void rtreeLeafConstraint(
+ RtreeConstraint *p, /* The constraint to test */
+ int eInt, /* True if RTree holds integer coordinates */
+ u8 *pCellData, /* Raw cell content as appears on disk */
+ int *peWithin /* Adjust downward, as appropriate */
+){
+ RtreeDValue xN; /* Coordinate value converted to a double */
+
+ assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
+ || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
+ || p->op==RTREE_FALSE );
+ pCellData += 8 + p->iCoord*4;
+ assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
+ RTREE_DECODE_COORD(eInt, pCellData, xN);
+ switch( p->op ){
+ case RTREE_TRUE: return; /* Always satisfied */
+ case RTREE_FALSE: break; /* Never satisfied */
+ case RTREE_LE: if( xN <= p->u.rValue ) return; break;
+ case RTREE_LT: if( xN < p->u.rValue ) return; break;
+ case RTREE_GE: if( xN >= p->u.rValue ) return; break;
+ case RTREE_GT: if( xN > p->u.rValue ) return; break;
+ default: if( xN == p->u.rValue ) return; break;
+ }
+ *peWithin = NOT_WITHIN;
+}
+
+/*
+** One of the cells in node pNode is guaranteed to have a 64-bit
+** integer value equal to iRowid. Return the index of this cell.
+*/
+static int nodeRowidIndex(
+ Rtree *pRtree,
+ RtreeNode *pNode,
+ i64 iRowid,
+ int *piIndex
+){
+ int ii;
+ int nCell = NCELL(pNode);
+ assert( nCell<200 );
+ for(ii=0; ii<nCell; ii++){
+ if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
+ *piIndex = ii;
+ return SQLITE_OK;
+ }
+ }
+ RTREE_IS_CORRUPT(pRtree);
+ return SQLITE_CORRUPT_VTAB;
+}
+
+/*
+** Return the index of the cell containing a pointer to node pNode
+** in its parent. If pNode is the root node, return -1.
+*/
+static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
+ RtreeNode *pParent = pNode->pParent;
+ if( pParent ){
+ return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
+ }
+ *piIndex = -1;
+ return SQLITE_OK;
+}
+
+/*
+** Compare two search points. Return negative, zero, or positive if the first
+** is less than, equal to, or greater than the second.
+**
+** The rScore is the primary key. Smaller rScore values come first.
+** If the rScore is a tie, then use iLevel as the tie breaker with smaller
+** iLevel values coming first. In this way, if rScore is the same for all
+** SearchPoints, then iLevel becomes the deciding factor and the result
+** is a depth-first search, which is the desired default behavior.
+*/
+static int rtreeSearchPointCompare(
+ const RtreeSearchPoint *pA,
+ const RtreeSearchPoint *pB
+){
+ if( pA->rScore<pB->rScore ) return -1;
+ if( pA->rScore>pB->rScore ) return +1;
+ if( pA->iLevel<pB->iLevel ) return -1;
+ if( pA->iLevel>pB->iLevel ) return +1;
+ return 0;
+}
+
+/*
+** Interchange two search points in a cursor.
+*/
+static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
+ RtreeSearchPoint t = p->aPoint[i];
+ assert( i<j );
+ p->aPoint[i] = p->aPoint[j];
+ p->aPoint[j] = t;
+ i++; j++;
+ if( i<RTREE_CACHE_SZ ){
+ if( j>=RTREE_CACHE_SZ ){
+ nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
+ p->aNode[i] = 0;
+ }else{
+ RtreeNode *pTemp = p->aNode[i];
+ p->aNode[i] = p->aNode[j];
+ p->aNode[j] = pTemp;
+ }
+ }
+}
+
+/*
+** Return the search point with the lowest current score.
+*/
+static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
+ return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
+}
+
+/*
+** Get the RtreeNode for the search point with the lowest score.
+*/
+static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
+ sqlite3_int64 id;
+ int ii = 1 - pCur->bPoint;
+ assert( ii==0 || ii==1 );
+ assert( pCur->bPoint || pCur->nPoint );
+ if( pCur->aNode[ii]==0 ){
+ assert( pRC!=0 );
+ id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
+ *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
+ }
+ return pCur->aNode[ii];
+}
+
+/*
+** Push a new element onto the priority queue
+*/
+static RtreeSearchPoint *rtreeEnqueue(
+ RtreeCursor *pCur, /* The cursor */
+ RtreeDValue rScore, /* Score for the new search point */
+ u8 iLevel /* Level for the new search point */
+){
+ int i, j;
+ RtreeSearchPoint *pNew;
+ if( pCur->nPoint>=pCur->nPointAlloc ){
+ int nNew = pCur->nPointAlloc*2 + 8;
+ pNew = sqlite3_realloc64(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
+ if( pNew==0 ) return 0;
+ pCur->aPoint = pNew;
+ pCur->nPointAlloc = nNew;
+ }
+ i = pCur->nPoint++;
+ pNew = pCur->aPoint + i;
+ pNew->rScore = rScore;
+ pNew->iLevel = iLevel;
+ assert( iLevel<=RTREE_MAX_DEPTH );
+ while( i>0 ){
+ RtreeSearchPoint *pParent;
+ j = (i-1)/2;
+ pParent = pCur->aPoint + j;
+ if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
+ rtreeSearchPointSwap(pCur, j, i);
+ i = j;
+ pNew = pParent;
+ }
+ return pNew;
+}
+
+/*
+** Allocate a new RtreeSearchPoint and return a pointer to it. Return
+** NULL if malloc fails.
+*/
+static RtreeSearchPoint *rtreeSearchPointNew(
+ RtreeCursor *pCur, /* The cursor */
+ RtreeDValue rScore, /* Score for the new search point */
+ u8 iLevel /* Level for the new search point */
+){
+ RtreeSearchPoint *pNew, *pFirst;
+ pFirst = rtreeSearchPointFirst(pCur);
+ pCur->anQueue[iLevel]++;
+ if( pFirst==0
+ || pFirst->rScore>rScore
+ || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
+ ){
+ if( pCur->bPoint ){
+ int ii;
+ pNew = rtreeEnqueue(pCur, rScore, iLevel);
+ if( pNew==0 ) return 0;
+ ii = (int)(pNew - pCur->aPoint) + 1;
+ if( ii<RTREE_CACHE_SZ ){
+ assert( pCur->aNode[ii]==0 );
+ pCur->aNode[ii] = pCur->aNode[0];
+ }else{
+ nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
+ }
+ pCur->aNode[0] = 0;
+ *pNew = pCur->sPoint;
+ }
+ pCur->sPoint.rScore = rScore;
+ pCur->sPoint.iLevel = iLevel;
+ pCur->bPoint = 1;
+ return &pCur->sPoint;
+ }else{
+ return rtreeEnqueue(pCur, rScore, iLevel);
+ }
+}
+
+#if 0
+/* Tracing routines for the RtreeSearchPoint queue */
+static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
+ if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
+ printf(" %d.%05lld.%02d %g %d",
+ p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
+ );
+ idx++;
+ if( idx<RTREE_CACHE_SZ ){
+ printf(" %p\n", pCur->aNode[idx]);
+ }else{
+ printf("\n");
+ }
+}
+static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
+ int ii;
+ printf("=== %9s ", zPrefix);
+ if( pCur->bPoint ){
+ tracePoint(&pCur->sPoint, -1, pCur);
+ }
+ for(ii=0; ii<pCur->nPoint; ii++){
+ if( ii>0 || pCur->bPoint ) printf(" ");
+ tracePoint(&pCur->aPoint[ii], ii, pCur);
+ }
+}
+# define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
+#else
+# define RTREE_QUEUE_TRACE(A,B) /* no-op */
+#endif
+
+/* Remove the search point with the lowest current score.
+*/
+static void rtreeSearchPointPop(RtreeCursor *p){
+ int i, j, k, n;
+ i = 1 - p->bPoint;
+ assert( i==0 || i==1 );
+ if( p->aNode[i] ){
+ nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
+ p->aNode[i] = 0;
+ }
+ if( p->bPoint ){
+ p->anQueue[p->sPoint.iLevel]--;
+ p->bPoint = 0;
+ }else if( p->nPoint ){
+ p->anQueue[p->aPoint[0].iLevel]--;
+ n = --p->nPoint;
+ p->aPoint[0] = p->aPoint[n];
+ if( n<RTREE_CACHE_SZ-1 ){
+ p->aNode[1] = p->aNode[n+1];
+ p->aNode[n+1] = 0;
+ }
+ i = 0;
+ while( (j = i*2+1)<n ){
+ k = j+1;
+ if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
+ if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
+ rtreeSearchPointSwap(p, i, k);
+ i = k;
+ }else{
+ break;
+ }
+ }else{
+ if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
+ rtreeSearchPointSwap(p, i, j);
+ i = j;
+ }else{
+ break;
+ }
+ }
+ }
+ }
+}
+
+
+/*
+** Continue the search on cursor pCur until the front of the queue
+** contains an entry suitable for returning as a result-set row,
+** or until the RtreeSearchPoint queue is empty, indicating that the
+** query has completed.
+*/
+static int rtreeStepToLeaf(RtreeCursor *pCur){
+ RtreeSearchPoint *p;
+ Rtree *pRtree = RTREE_OF_CURSOR(pCur);
+ RtreeNode *pNode;
+ int eWithin;
+ int rc = SQLITE_OK;
+ int nCell;
+ int nConstraint = pCur->nConstraint;
+ int ii;
+ int eInt;
+ RtreeSearchPoint x;
+
+ eInt = pRtree->eCoordType==RTREE_COORD_INT32;
+ while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
+ u8 *pCellData;
+ pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
+ if( rc ) return rc;
+ nCell = NCELL(pNode);
+ assert( nCell<200 );
+ pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
+ while( p->iCell<nCell ){
+ sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
+ eWithin = FULLY_WITHIN;
+ for(ii=0; ii<nConstraint; ii++){
+ RtreeConstraint *pConstraint = pCur->aConstraint + ii;
+ if( pConstraint->op>=RTREE_MATCH ){
+ rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
+ &rScore, &eWithin);
+ if( rc ) return rc;
+ }else if( p->iLevel==1 ){
+ rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
+ }else{
+ rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
+ }
+ if( eWithin==NOT_WITHIN ){
+ p->iCell++;
+ pCellData += pRtree->nBytesPerCell;
+ break;
+ }
+ }
+ if( eWithin==NOT_WITHIN ) continue;
+ p->iCell++;
+ x.iLevel = p->iLevel - 1;
+ if( x.iLevel ){
+ x.id = readInt64(pCellData);
+ for(ii=0; ii<pCur->nPoint; ii++){
+ if( pCur->aPoint[ii].id==x.id ){
+ RTREE_IS_CORRUPT(pRtree);
+ return SQLITE_CORRUPT_VTAB;
+ }
+ }
+ x.iCell = 0;
+ }else{
+ x.id = p->id;
+ x.iCell = p->iCell - 1;
+ }
+ if( p->iCell>=nCell ){
+ RTREE_QUEUE_TRACE(pCur, "POP-S:");
+ rtreeSearchPointPop(pCur);
+ }
+ if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
+ p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
+ if( p==0 ) return SQLITE_NOMEM;
+ p->eWithin = (u8)eWithin;
+ p->id = x.id;
+ p->iCell = x.iCell;
+ RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
+ break;
+ }
+ if( p->iCell>=nCell ){
+ RTREE_QUEUE_TRACE(pCur, "POP-Se:");
+ rtreeSearchPointPop(pCur);
+ }
+ }
+ pCur->atEOF = p==0;
+ return SQLITE_OK;
+}
+
+/*
+** Rtree virtual table module xNext method.
+*/
+static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
+ RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
+ int rc = SQLITE_OK;
+
+ /* Move to the next entry that matches the configured constraints. */
+ RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
+ if( pCsr->bAuxValid ){
+ pCsr->bAuxValid = 0;
+ sqlite3_reset(pCsr->pReadAux);
+ }
+ rtreeSearchPointPop(pCsr);
+ rc = rtreeStepToLeaf(pCsr);
+ return rc;
+}
+
+/*
+** Rtree virtual table module xRowid method.
+*/
+static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
+ RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
+ RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
+ int rc = SQLITE_OK;
+ RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
+ if( rc==SQLITE_OK && p ){
+ *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
+ }
+ return rc;
+}
+
+/*
+** Rtree virtual table module xColumn method.
+*/
+static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
+ Rtree *pRtree = (Rtree *)cur->pVtab;
+ RtreeCursor *pCsr = (RtreeCursor *)cur;
+ RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
+ RtreeCoord c;
+ int rc = SQLITE_OK;
+ RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
+
+ if( rc ) return rc;
+ if( p==0 ) return SQLITE_OK;
+ if( i==0 ){
+ sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
+ }else if( i<=pRtree->nDim2 ){
+ nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
+#ifndef SQLITE_RTREE_INT_ONLY
+ if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
+ sqlite3_result_double(ctx, c.f);
+ }else
+#endif
+ {
+ assert( pRtree->eCoordType==RTREE_COORD_INT32 );
+ sqlite3_result_int(ctx, c.i);
+ }
+ }else{
+ if( !pCsr->bAuxValid ){
+ if( pCsr->pReadAux==0 ){
+ rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
+ &pCsr->pReadAux, 0);
+ if( rc ) return rc;
+ }
+ sqlite3_bind_int64(pCsr->pReadAux, 1,
+ nodeGetRowid(pRtree, pNode, p->iCell));
+ rc = sqlite3_step(pCsr->pReadAux);
+ if( rc==SQLITE_ROW ){
+ pCsr->bAuxValid = 1;
+ }else{
+ sqlite3_reset(pCsr->pReadAux);
+ if( rc==SQLITE_DONE ) rc = SQLITE_OK;
+ return rc;
+ }
+ }
+ sqlite3_result_value(ctx,
+ sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Use nodeAcquire() to obtain the leaf node containing the record with
+** rowid iRowid. If successful, set *ppLeaf to point to the node and
+** return SQLITE_OK. If there is no such record in the table, set
+** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
+** to zero and return an SQLite error code.
+*/
+static int findLeafNode(
+ Rtree *pRtree, /* RTree to search */
+ i64 iRowid, /* The rowid searching for */
+ RtreeNode **ppLeaf, /* Write the node here */
+ sqlite3_int64 *piNode /* Write the node-id here */
+){
+ int rc;
+ *ppLeaf = 0;
+ sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
+ if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
+ i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
+ if( piNode ) *piNode = iNode;
+ rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
+ sqlite3_reset(pRtree->pReadRowid);
+ }else{
+ rc = sqlite3_reset(pRtree->pReadRowid);
+ }
+ return rc;
+}
+
+/*
+** This function is called to configure the RtreeConstraint object passed
+** as the second argument for a MATCH constraint. The value passed as the
+** first argument to this function is the right-hand operand to the MATCH
+** operator.
+*/
+static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
+ RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */
+ sqlite3_rtree_query_info *pInfo; /* Callback information */
+
+ pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
+ if( pSrc==0 ) return SQLITE_ERROR;
+ pInfo = (sqlite3_rtree_query_info*)
+ sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
+ if( !pInfo ) return SQLITE_NOMEM;
+ memset(pInfo, 0, sizeof(*pInfo));
+ pBlob = (RtreeMatchArg*)&pInfo[1];
+ memcpy(pBlob, pSrc, pSrc->iSize);
+ pInfo->pContext = pBlob->cb.pContext;
+ pInfo->nParam = pBlob->nParam;
+ pInfo->aParam = pBlob->aParam;
+ pInfo->apSqlParam = pBlob->apSqlParam;
+
+ if( pBlob->cb.xGeom ){
+ pCons->u.xGeom = pBlob->cb.xGeom;
+ }else{
+ pCons->op = RTREE_QUERY;
+ pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
+ }
+ pCons->pInfo = pInfo;
+ return SQLITE_OK;
+}
+
+/*
+** Rtree virtual table module xFilter method.
+*/
+static int rtreeFilter(
+ sqlite3_vtab_cursor *pVtabCursor,
+ int idxNum, const char *idxStr,
+ int argc, sqlite3_value **argv
+){
+ Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
+ RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
+ RtreeNode *pRoot = 0;
+ int ii;
+ int rc = SQLITE_OK;
+ int iCell = 0;
+
+ rtreeReference(pRtree);
+
+ /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
+ resetCursor(pCsr);
+
+ pCsr->iStrategy = idxNum;
+ if( idxNum==1 ){
+ /* Special case - lookup by rowid. */
+ RtreeNode *pLeaf; /* Leaf on which the required cell resides */
+ RtreeSearchPoint *p; /* Search point for the leaf */
+ i64 iRowid = sqlite3_value_int64(argv[0]);
+ i64 iNode = 0;
+ int eType = sqlite3_value_numeric_type(argv[0]);
+ if( eType==SQLITE_INTEGER
+ || (eType==SQLITE_FLOAT && sqlite3_value_double(argv[0])==iRowid)
+ ){
+ rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
+ }else{
+ rc = SQLITE_OK;
+ pLeaf = 0;
+ }
+ if( rc==SQLITE_OK && pLeaf!=0 ){
+ p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
+ assert( p!=0 ); /* Always returns pCsr->sPoint */
+ pCsr->aNode[0] = pLeaf;
+ p->id = iNode;
+ p->eWithin = PARTLY_WITHIN;
+ rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
+ p->iCell = (u8)iCell;
+ RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
+ }else{
+ pCsr->atEOF = 1;
+ }
+ }else{
+ /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
+ ** with the configured constraints.
+ */
+ rc = nodeAcquire(pRtree, 1, 0, &pRoot);
+ if( rc==SQLITE_OK && argc>0 ){
+ pCsr->aConstraint = sqlite3_malloc64(sizeof(RtreeConstraint)*argc);
+ pCsr->nConstraint = argc;
+ if( !pCsr->aConstraint ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
+ memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
+ assert( (idxStr==0 && argc==0)
+ || (idxStr && (int)strlen(idxStr)==argc*2) );
+ for(ii=0; ii<argc; ii++){
+ RtreeConstraint *p = &pCsr->aConstraint[ii];
+ int eType = sqlite3_value_numeric_type(argv[ii]);
+ p->op = idxStr[ii*2];
+ p->iCoord = idxStr[ii*2+1]-'0';
+ if( p->op>=RTREE_MATCH ){
+ /* A MATCH operator. The right-hand-side must be a blob that
+ ** can be cast into an RtreeMatchArg object. One created using
+ ** an sqlite3_rtree_geometry_callback() SQL user function.
+ */
+ rc = deserializeGeometry(argv[ii], p);
+ if( rc!=SQLITE_OK ){
+ break;
+ }
+ p->pInfo->nCoord = pRtree->nDim2;
+ p->pInfo->anQueue = pCsr->anQueue;
+ p->pInfo->mxLevel = pRtree->iDepth + 1;
+ }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
+#ifdef SQLITE_RTREE_INT_ONLY
+ p->u.rValue = sqlite3_value_int64(argv[ii]);
+#else
+ p->u.rValue = sqlite3_value_double(argv[ii]);
+#endif
+ }else{
+ p->u.rValue = RTREE_ZERO;
+ if( eType==SQLITE_NULL ){
+ p->op = RTREE_FALSE;
+ }else if( p->op==RTREE_LT || p->op==RTREE_LE ){
+ p->op = RTREE_TRUE;
+ }else{
+ p->op = RTREE_FALSE;
+ }
+ }
+ }
+ }
+ }
+ if( rc==SQLITE_OK ){
+ RtreeSearchPoint *pNew;
+ pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
+ if( pNew==0 ) return SQLITE_NOMEM;
+ pNew->id = 1;
+ pNew->iCell = 0;
+ pNew->eWithin = PARTLY_WITHIN;
+ assert( pCsr->bPoint==1 );
+ pCsr->aNode[0] = pRoot;
+ pRoot = 0;
+ RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
+ rc = rtreeStepToLeaf(pCsr);
+ }
+ }
+
+ nodeRelease(pRtree, pRoot);
+ rtreeRelease(pRtree);
+ return rc;
+}
+
+/*
+** Rtree virtual table module xBestIndex method. There are three
+** table scan strategies to choose from (in order from most to
+** least desirable):
+**
+** idxNum idxStr Strategy
+** ------------------------------------------------
+** 1 Unused Direct lookup by rowid.
+** 2 See below R-tree query or full-table scan.
+** ------------------------------------------------
+**
+** If strategy 1 is used, then idxStr is not meaningful. If strategy
+** 2 is used, idxStr is formatted to contain 2 bytes for each
+** constraint used. The first two bytes of idxStr correspond to
+** the constraint in sqlite3_index_info.aConstraintUsage[] with
+** (argvIndex==1) etc.
+**
+** The first of each pair of bytes in idxStr identifies the constraint
+** operator as follows:
+**
+** Operator Byte Value
+** ----------------------
+** = 0x41 ('A')
+** <= 0x42 ('B')
+** < 0x43 ('C')
+** >= 0x44 ('D')
+** > 0x45 ('E')
+** MATCH 0x46 ('F')
+** ----------------------
+**
+** The second of each pair of bytes identifies the coordinate column
+** to which the constraint applies. The leftmost coordinate column
+** is 'a', the second from the left 'b' etc.
+*/
+static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
+ Rtree *pRtree = (Rtree*)tab;
+ int rc = SQLITE_OK;
+ int ii;
+ int bMatch = 0; /* True if there exists a MATCH constraint */
+ i64 nRow; /* Estimated rows returned by this scan */
+
+ int iIdx = 0;
+ char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
+ memset(zIdxStr, 0, sizeof(zIdxStr));
+
+ /* Check if there exists a MATCH constraint - even an unusable one. If there
+ ** is, do not consider the lookup-by-rowid plan as using such a plan would
+ ** require the VDBE to evaluate the MATCH constraint, which is not currently
+ ** possible. */
+ for(ii=0; ii<pIdxInfo->nConstraint; ii++){
+ if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
+ bMatch = 1;
+ }
+ }
+
+ assert( pIdxInfo->idxStr==0 );
+ for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
+ struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
+
+ if( bMatch==0 && p->usable
+ && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
+ ){
+ /* We have an equality constraint on the rowid. Use strategy 1. */
+ int jj;
+ for(jj=0; jj<ii; jj++){
+ pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
+ pIdxInfo->aConstraintUsage[jj].omit = 0;
+ }
+ pIdxInfo->idxNum = 1;
+ pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
+ pIdxInfo->aConstraintUsage[jj].omit = 1;
+
+ /* This strategy involves a two rowid lookups on an B-Tree structures
+ ** and then a linear search of an R-Tree node. This should be
+ ** considered almost as quick as a direct rowid lookup (for which
+ ** sqlite uses an internal cost of 0.0). It is expected to return
+ ** a single row.
+ */
+ pIdxInfo->estimatedCost = 30.0;
+ pIdxInfo->estimatedRows = 1;
+ pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
+ return SQLITE_OK;
+ }
+
+ if( p->usable
+ && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2)
+ || p->op==SQLITE_INDEX_CONSTRAINT_MATCH)
+ ){
+ u8 op;
+ switch( p->op ){
+ case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
+ case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
+ case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
+ case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
+ case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
+ case SQLITE_INDEX_CONSTRAINT_MATCH: op = RTREE_MATCH; break;
+ default: op = 0; break;
+ }
+ if( op ){
+ zIdxStr[iIdx++] = op;
+ zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
+ pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
+ pIdxInfo->aConstraintUsage[ii].omit = 1;
+ }
+ }
+ }
+
+ pIdxInfo->idxNum = 2;
+ pIdxInfo->needToFreeIdxStr = 1;
+ if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
+ return SQLITE_NOMEM;
+ }
+
+ nRow = pRtree->nRowEst >> (iIdx/2);
+ pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
+ pIdxInfo->estimatedRows = nRow;
+
+ return rc;
+}
+
+/*
+** Return the N-dimensional volumn of the cell stored in *p.
+*/
+static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
+ RtreeDValue area = (RtreeDValue)1;
+ assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
+#ifndef SQLITE_RTREE_INT_ONLY
+ if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
+ switch( pRtree->nDim ){
+ case 5: area = p->aCoord[9].f - p->aCoord[8].f;
+ case 4: area *= p->aCoord[7].f - p->aCoord[6].f;
+ case 3: area *= p->aCoord[5].f - p->aCoord[4].f;
+ case 2: area *= p->aCoord[3].f - p->aCoord[2].f;
+ default: area *= p->aCoord[1].f - p->aCoord[0].f;
+ }
+ }else
+#endif
+ {
+ switch( pRtree->nDim ){
+ case 5: area = (i64)p->aCoord[9].i - (i64)p->aCoord[8].i;
+ case 4: area *= (i64)p->aCoord[7].i - (i64)p->aCoord[6].i;
+ case 3: area *= (i64)p->aCoord[5].i - (i64)p->aCoord[4].i;
+ case 2: area *= (i64)p->aCoord[3].i - (i64)p->aCoord[2].i;
+ default: area *= (i64)p->aCoord[1].i - (i64)p->aCoord[0].i;
+ }
+ }
+ return area;
+}
+
+/*
+** Return the margin length of cell p. The margin length is the sum
+** of the objects size in each dimension.
+*/
+static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
+ RtreeDValue margin = 0;
+ int ii = pRtree->nDim2 - 2;
+ do{
+ margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
+ ii -= 2;
+ }while( ii>=0 );
+ return margin;
+}
+
+/*
+** Store the union of cells p1 and p2 in p1.
+*/
+static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
+ int ii = 0;
+ if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
+ do{
+ p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
+ p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
+ ii += 2;
+ }while( ii<pRtree->nDim2 );
+ }else{
+ do{
+ p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
+ p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
+ ii += 2;
+ }while( ii<pRtree->nDim2 );
+ }
+}
+
+/*
+** Return true if the area covered by p2 is a subset of the area covered
+** by p1. False otherwise.
+*/
+static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
+ int ii;
+ int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
+ for(ii=0; ii<pRtree->nDim2; ii+=2){
+ RtreeCoord *a1 = &p1->aCoord[ii];
+ RtreeCoord *a2 = &p2->aCoord[ii];
+ if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
+ || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
+ ){
+ return 0;
+ }
+ }
+ return 1;
+}
+
+/*
+** Return the amount cell p would grow by if it were unioned with pCell.
+*/
+static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
+ RtreeDValue area;
+ RtreeCell cell;
+ memcpy(&cell, p, sizeof(RtreeCell));
+ area = cellArea(pRtree, &cell);
+ cellUnion(pRtree, &cell, pCell);
+ return (cellArea(pRtree, &cell)-area);
+}
+
+static RtreeDValue cellOverlap(
+ Rtree *pRtree,
+ RtreeCell *p,
+ RtreeCell *aCell,
+ int nCell
+){
+ int ii;
+ RtreeDValue overlap = RTREE_ZERO;
+ for(ii=0; ii<nCell; ii++){
+ int jj;
+ RtreeDValue o = (RtreeDValue)1;
+ for(jj=0; jj<pRtree->nDim2; jj+=2){
+ RtreeDValue x1, x2;
+ x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
+ x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
+ if( x2<x1 ){
+ o = (RtreeDValue)0;
+ break;
+ }else{
+ o = o * (x2-x1);
+ }
+ }
+ overlap += o;
+ }
+ return overlap;
+}
+
+
+/*
+** This function implements the ChooseLeaf algorithm from Gutman[84].
+** ChooseSubTree in r*tree terminology.
+*/
+static int ChooseLeaf(
+ Rtree *pRtree, /* Rtree table */
+ RtreeCell *pCell, /* Cell to insert into rtree */
+ int iHeight, /* Height of sub-tree rooted at pCell */
+ RtreeNode **ppLeaf /* OUT: Selected leaf page */
+){
+ int rc;
+ int ii;
+ RtreeNode *pNode = 0;
+ rc = nodeAcquire(pRtree, 1, 0, &pNode);
+
+ for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
+ int iCell;
+ sqlite3_int64 iBest = 0;
+
+ RtreeDValue fMinGrowth = RTREE_ZERO;
+ RtreeDValue fMinArea = RTREE_ZERO;
+
+ int nCell = NCELL(pNode);
+ RtreeCell cell;
+ RtreeNode *pChild;
+
+ RtreeCell *aCell = 0;
+
+ /* Select the child node which will be enlarged the least if pCell
+ ** is inserted into it. Resolve ties by choosing the entry with
+ ** the smallest area.
+ */
+ for(iCell=0; iCell<nCell; iCell++){
+ int bBest = 0;
+ RtreeDValue growth;
+ RtreeDValue area;
+ nodeGetCell(pRtree, pNode, iCell, &cell);
+ growth = cellGrowth(pRtree, &cell, pCell);
+ area = cellArea(pRtree, &cell);
+ if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
+ bBest = 1;
+ }
+ if( bBest ){
+ fMinGrowth = growth;
+ fMinArea = area;
+ iBest = cell.iRowid;
+ }
+ }
+
+ sqlite3_free(aCell);
+ rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
+ nodeRelease(pRtree, pNode);
+ pNode = pChild;
+ }
+
+ *ppLeaf = pNode;
+ return rc;
+}
+
+/*
+** A cell with the same content as pCell has just been inserted into
+** the node pNode. This function updates the bounding box cells in
+** all ancestor elements.
+*/
+static int AdjustTree(
+ Rtree *pRtree, /* Rtree table */
+ RtreeNode *pNode, /* Adjust ancestry of this node. */
+ RtreeCell *pCell /* This cell was just inserted */
+){
+ RtreeNode *p = pNode;
+ int cnt = 0;
+ while( p->pParent ){
+ RtreeNode *pParent = p->pParent;
+ RtreeCell cell;
+ int iCell;
+
+ if( (++cnt)>1000 || nodeParentIndex(pRtree, p, &iCell) ){
+ RTREE_IS_CORRUPT(pRtree);
+ return SQLITE_CORRUPT_VTAB;
+ }
+
+ nodeGetCell(pRtree, pParent, iCell, &cell);
+ if( !cellContains(pRtree, &cell, pCell) ){
+ cellUnion(pRtree, &cell, pCell);
+ nodeOverwriteCell(pRtree, pParent, &cell, iCell);
+ }
+
+ p = pParent;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
+*/
+static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
+ sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
+ sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
+ sqlite3_step(pRtree->pWriteRowid);
+ return sqlite3_reset(pRtree->pWriteRowid);
+}
+
+/*
+** Write mapping (iNode->iPar) to the <rtree>_parent table.
+*/
+static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
+ sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
+ sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
+ sqlite3_step(pRtree->pWriteParent);
+ return sqlite3_reset(pRtree->pWriteParent);
+}
+
+static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
+
+
+/*
+** Arguments aIdx, aDistance and aSpare all point to arrays of size
+** nIdx. The aIdx array contains the set of integers from 0 to
+** (nIdx-1) in no particular order. This function sorts the values
+** in aIdx according to the indexed values in aDistance. For
+** example, assuming the inputs:
+**
+** aIdx = { 0, 1, 2, 3 }
+** aDistance = { 5.0, 2.0, 7.0, 6.0 }
+**
+** this function sets the aIdx array to contain:
+**
+** aIdx = { 0, 1, 2, 3 }
+**
+** The aSpare array is used as temporary working space by the
+** sorting algorithm.
+*/
+static void SortByDistance(
+ int *aIdx,
+ int nIdx,
+ RtreeDValue *aDistance,
+ int *aSpare
+){
+ if( nIdx>1 ){
+ int iLeft = 0;
+ int iRight = 0;
+
+ int nLeft = nIdx/2;
+ int nRight = nIdx-nLeft;
+ int *aLeft = aIdx;
+ int *aRight = &aIdx[nLeft];
+
+ SortByDistance(aLeft, nLeft, aDistance, aSpare);
+ SortByDistance(aRight, nRight, aDistance, aSpare);
+
+ memcpy(aSpare, aLeft, sizeof(int)*nLeft);
+ aLeft = aSpare;
+
+ while( iLeft<nLeft || iRight<nRight ){
+ if( iLeft==nLeft ){
+ aIdx[iLeft+iRight] = aRight[iRight];
+ iRight++;
+ }else if( iRight==nRight ){
+ aIdx[iLeft+iRight] = aLeft[iLeft];
+ iLeft++;
+ }else{
+ RtreeDValue fLeft = aDistance[aLeft[iLeft]];
+ RtreeDValue fRight = aDistance[aRight[iRight]];
+ if( fLeft<fRight ){
+ aIdx[iLeft+iRight] = aLeft[iLeft];
+ iLeft++;
+ }else{
+ aIdx[iLeft+iRight] = aRight[iRight];
+ iRight++;
+ }
+ }
+ }
+
+#if 0
+ /* Check that the sort worked */
+ {
+ int jj;
+ for(jj=1; jj<nIdx; jj++){
+ RtreeDValue left = aDistance[aIdx[jj-1]];
+ RtreeDValue right = aDistance[aIdx[jj]];
+ assert( left<=right );
+ }
+ }
+#endif
+ }
+}
+
+/*
+** Arguments aIdx, aCell and aSpare all point to arrays of size
+** nIdx. The aIdx array contains the set of integers from 0 to
+** (nIdx-1) in no particular order. This function sorts the values
+** in aIdx according to dimension iDim of the cells in aCell. The
+** minimum value of dimension iDim is considered first, the
+** maximum used to break ties.
+**
+** The aSpare array is used as temporary working space by the
+** sorting algorithm.
+*/
+static void SortByDimension(
+ Rtree *pRtree,
+ int *aIdx,
+ int nIdx,
+ int iDim,
+ RtreeCell *aCell,
+ int *aSpare
+){
+ if( nIdx>1 ){
+
+ int iLeft = 0;
+ int iRight = 0;
+
+ int nLeft = nIdx/2;
+ int nRight = nIdx-nLeft;
+ int *aLeft = aIdx;
+ int *aRight = &aIdx[nLeft];
+
+ SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
+ SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
+
+ memcpy(aSpare, aLeft, sizeof(int)*nLeft);
+ aLeft = aSpare;
+ while( iLeft<nLeft || iRight<nRight ){
+ RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
+ RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
+ RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
+ RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
+ if( (iLeft!=nLeft) && ((iRight==nRight)
+ || (xleft1<xright1)
+ || (xleft1==xright1 && xleft2<xright2)
+ )){
+ aIdx[iLeft+iRight] = aLeft[iLeft];
+ iLeft++;
+ }else{
+ aIdx[iLeft+iRight] = aRight[iRight];
+ iRight++;
+ }
+ }
+
+#if 0
+ /* Check that the sort worked */
+ {
+ int jj;
+ for(jj=1; jj<nIdx; jj++){
+ RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
+ RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
+ RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
+ RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
+ assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
+ }
+ }
+#endif
+ }
+}
+
+/*
+** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
+*/
+static int splitNodeStartree(
+ Rtree *pRtree,
+ RtreeCell *aCell,
+ int nCell,
+ RtreeNode *pLeft,
+ RtreeNode *pRight,
+ RtreeCell *pBboxLeft,
+ RtreeCell *pBboxRight
+){
+ int **aaSorted;
+ int *aSpare;
+ int ii;
+
+ int iBestDim = 0;
+ int iBestSplit = 0;
+ RtreeDValue fBestMargin = RTREE_ZERO;
+
+ sqlite3_int64 nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
+
+ aaSorted = (int **)sqlite3_malloc64(nByte);
+ if( !aaSorted ){
+ return SQLITE_NOMEM;
+ }
+
+ aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
+ memset(aaSorted, 0, nByte);
+ for(ii=0; ii<pRtree->nDim; ii++){
+ int jj;
+ aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
+ for(jj=0; jj<nCell; jj++){
+ aaSorted[ii][jj] = jj;
+ }
+ SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
+ }
+
+ for(ii=0; ii<pRtree->nDim; ii++){
+ RtreeDValue margin = RTREE_ZERO;
+ RtreeDValue fBestOverlap = RTREE_ZERO;
+ RtreeDValue fBestArea = RTREE_ZERO;
+ int iBestLeft = 0;
+ int nLeft;
+
+ for(
+ nLeft=RTREE_MINCELLS(pRtree);
+ nLeft<=(nCell-RTREE_MINCELLS(pRtree));
+ nLeft++
+ ){
+ RtreeCell left;
+ RtreeCell right;
+ int kk;
+ RtreeDValue overlap;
+ RtreeDValue area;
+
+ memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
+ memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
+ for(kk=1; kk<(nCell-1); kk++){
+ if( kk<nLeft ){
+ cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
+ }else{
+ cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
+ }
+ }
+ margin += cellMargin(pRtree, &left);
+ margin += cellMargin(pRtree, &right);
+ overlap = cellOverlap(pRtree, &left, &right, 1);
+ area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
+ if( (nLeft==RTREE_MINCELLS(pRtree))
+ || (overlap<fBestOverlap)
+ || (overlap==fBestOverlap && area<fBestArea)
+ ){
+ iBestLeft = nLeft;
+ fBestOverlap = overlap;
+ fBestArea = area;
+ }
+ }
+
+ if( ii==0 || margin<fBestMargin ){
+ iBestDim = ii;
+ fBestMargin = margin;
+ iBestSplit = iBestLeft;
+ }
+ }
+
+ memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
+ memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
+ for(ii=0; ii<nCell; ii++){
+ RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
+ RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
+ RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
+ nodeInsertCell(pRtree, pTarget, pCell);
+ cellUnion(pRtree, pBbox, pCell);
+ }
+
+ sqlite3_free(aaSorted);
+ return SQLITE_OK;
+}
+
+
+static int updateMapping(
+ Rtree *pRtree,
+ i64 iRowid,
+ RtreeNode *pNode,
+ int iHeight
+){
+ int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
+ xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
+ if( iHeight>0 ){
+ RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
+ if( pChild ){
+ nodeRelease(pRtree, pChild->pParent);
+ nodeReference(pNode);
+ pChild->pParent = pNode;
+ }
+ }
+ return xSetMapping(pRtree, iRowid, pNode->iNode);
+}
+
+static int SplitNode(
+ Rtree *pRtree,
+ RtreeNode *pNode,
+ RtreeCell *pCell,
+ int iHeight
+){
+ int i;
+ int newCellIsRight = 0;
+
+ int rc = SQLITE_OK;
+ int nCell = NCELL(pNode);
+ RtreeCell *aCell;
+ int *aiUsed;
+
+ RtreeNode *pLeft = 0;
+ RtreeNode *pRight = 0;
+
+ RtreeCell leftbbox;
+ RtreeCell rightbbox;
+
+ /* Allocate an array and populate it with a copy of pCell and
+ ** all cells from node pLeft. Then zero the original node.
+ */
+ aCell = sqlite3_malloc64((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
+ if( !aCell ){
+ rc = SQLITE_NOMEM;
+ goto splitnode_out;
+ }
+ aiUsed = (int *)&aCell[nCell+1];
+ memset(aiUsed, 0, sizeof(int)*(nCell+1));
+ for(i=0; i<nCell; i++){
+ nodeGetCell(pRtree, pNode, i, &aCell[i]);
+ }
+ nodeZero(pRtree, pNode);
+ memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
+ nCell++;
+
+ if( pNode->iNode==1 ){
+ pRight = nodeNew(pRtree, pNode);
+ pLeft = nodeNew(pRtree, pNode);
+ pRtree->iDepth++;
+ pNode->isDirty = 1;
+ writeInt16(pNode->zData, pRtree->iDepth);
+ }else{
+ pLeft = pNode;
+ pRight = nodeNew(pRtree, pLeft->pParent);
+ pLeft->nRef++;
+ }
+
+ if( !pLeft || !pRight ){
+ rc = SQLITE_NOMEM;
+ goto splitnode_out;
+ }
+
+ memset(pLeft->zData, 0, pRtree->iNodeSize);
+ memset(pRight->zData, 0, pRtree->iNodeSize);
+
+ rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
+ &leftbbox, &rightbbox);
+ if( rc!=SQLITE_OK ){
+ goto splitnode_out;
+ }
+
+ /* Ensure both child nodes have node numbers assigned to them by calling
+ ** nodeWrite(). Node pRight always needs a node number, as it was created
+ ** by nodeNew() above. But node pLeft sometimes already has a node number.
+ ** In this case avoid the all to nodeWrite().
+ */
+ if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
+ || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
+ ){
+ goto splitnode_out;
+ }
+
+ rightbbox.iRowid = pRight->iNode;
+ leftbbox.iRowid = pLeft->iNode;
+
+ if( pNode->iNode==1 ){
+ rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
+ if( rc!=SQLITE_OK ){
+ goto splitnode_out;
+ }
+ }else{
+ RtreeNode *pParent = pLeft->pParent;
+ int iCell;
+ rc = nodeParentIndex(pRtree, pLeft, &iCell);
+ if( rc==SQLITE_OK ){
+ nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
+ rc = AdjustTree(pRtree, pParent, &leftbbox);
+ }
+ if( rc!=SQLITE_OK ){
+ goto splitnode_out;
+ }
+ }
+ if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
+ goto splitnode_out;
+ }
+
+ for(i=0; i<NCELL(pRight); i++){
+ i64 iRowid = nodeGetRowid(pRtree, pRight, i);
+ rc = updateMapping(pRtree, iRowid, pRight, iHeight);
+ if( iRowid==pCell->iRowid ){
+ newCellIsRight = 1;
+ }
+ if( rc!=SQLITE_OK ){
+ goto splitnode_out;
+ }
+ }
+ if( pNode->iNode==1 ){
+ for(i=0; i<NCELL(pLeft); i++){
+ i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
+ rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
+ if( rc!=SQLITE_OK ){
+ goto splitnode_out;
+ }
+ }
+ }else if( newCellIsRight==0 ){
+ rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = nodeRelease(pRtree, pRight);
+ pRight = 0;
+ }
+ if( rc==SQLITE_OK ){
+ rc = nodeRelease(pRtree, pLeft);
+ pLeft = 0;
+ }
+
+splitnode_out:
+ nodeRelease(pRtree, pRight);
+ nodeRelease(pRtree, pLeft);
+ sqlite3_free(aCell);
+ return rc;
+}
+
+/*
+** If node pLeaf is not the root of the r-tree and its pParent pointer is
+** still NULL, load all ancestor nodes of pLeaf into memory and populate
+** the pLeaf->pParent chain all the way up to the root node.
+**
+** This operation is required when a row is deleted (or updated - an update
+** is implemented as a delete followed by an insert). SQLite provides the
+** rowid of the row to delete, which can be used to find the leaf on which
+** the entry resides (argument pLeaf). Once the leaf is located, this
+** function is called to determine its ancestry.
+*/
+static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
+ int rc = SQLITE_OK;
+ RtreeNode *pChild = pLeaf;
+ while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
+ int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
+ sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
+ rc = sqlite3_step(pRtree->pReadParent);
+ if( rc==SQLITE_ROW ){
+ RtreeNode *pTest; /* Used to test for reference loops */
+ i64 iNode; /* Node number of parent node */
+
+ /* Before setting pChild->pParent, test that we are not creating a
+ ** loop of references (as we would if, say, pChild==pParent). We don't
+ ** want to do this as it leads to a memory leak when trying to delete
+ ** the referenced counted node structures.
+ */
+ iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
+ for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
+ if( !pTest ){
+ rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
+ }
+ }
+ rc = sqlite3_reset(pRtree->pReadParent);
+ if( rc==SQLITE_OK ) rc = rc2;
+ if( rc==SQLITE_OK && !pChild->pParent ){
+ RTREE_IS_CORRUPT(pRtree);
+ rc = SQLITE_CORRUPT_VTAB;
+ }
+ pChild = pChild->pParent;
+ }
+ return rc;
+}
+
+static int deleteCell(Rtree *, RtreeNode *, int, int);
+
+static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
+ int rc;
+ int rc2;
+ RtreeNode *pParent = 0;
+ int iCell;
+
+ assert( pNode->nRef==1 );
+
+ /* Remove the entry in the parent cell. */
+ rc = nodeParentIndex(pRtree, pNode, &iCell);
+ if( rc==SQLITE_OK ){
+ pParent = pNode->pParent;
+ pNode->pParent = 0;
+ rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
+ }
+ rc2 = nodeRelease(pRtree, pParent);
+ if( rc==SQLITE_OK ){
+ rc = rc2;
+ }
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+
+ /* Remove the xxx_node entry. */
+ sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
+ sqlite3_step(pRtree->pDeleteNode);
+ if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
+ return rc;
+ }
+
+ /* Remove the xxx_parent entry. */
+ sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
+ sqlite3_step(pRtree->pDeleteParent);
+ if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
+ return rc;
+ }
+
+ /* Remove the node from the in-memory hash table and link it into
+ ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
+ */
+ nodeHashDelete(pRtree, pNode);
+ pNode->iNode = iHeight;
+ pNode->pNext = pRtree->pDeleted;
+ pNode->nRef++;
+ pRtree->pDeleted = pNode;
+
+ return SQLITE_OK;
+}
+
+static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
+ RtreeNode *pParent = pNode->pParent;
+ int rc = SQLITE_OK;
+ if( pParent ){
+ int ii;
+ int nCell = NCELL(pNode);
+ RtreeCell box; /* Bounding box for pNode */
+ nodeGetCell(pRtree, pNode, 0, &box);
+ for(ii=1; ii<nCell; ii++){
+ RtreeCell cell;
+ nodeGetCell(pRtree, pNode, ii, &cell);
+ cellUnion(pRtree, &box, &cell);
+ }
+ box.iRowid = pNode->iNode;
+ rc = nodeParentIndex(pRtree, pNode, &ii);
+ if( rc==SQLITE_OK ){
+ nodeOverwriteCell(pRtree, pParent, &box, ii);
+ rc = fixBoundingBox(pRtree, pParent);
+ }
+ }
+ return rc;
+}
+
+/*
+** Delete the cell at index iCell of node pNode. After removing the
+** cell, adjust the r-tree data structure if required.
+*/
+static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
+ RtreeNode *pParent;
+ int rc;
+
+ if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
+ return rc;
+ }
+
+ /* Remove the cell from the node. This call just moves bytes around
+ ** the in-memory node image, so it cannot fail.
+ */
+ nodeDeleteCell(pRtree, pNode, iCell);
+
+ /* If the node is not the tree root and now has less than the minimum
+ ** number of cells, remove it from the tree. Otherwise, update the
+ ** cell in the parent node so that it tightly contains the updated
+ ** node.
+ */
+ pParent = pNode->pParent;
+ assert( pParent || pNode->iNode==1 );
+ if( pParent ){
+ if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
+ rc = removeNode(pRtree, pNode, iHeight);
+ }else{
+ rc = fixBoundingBox(pRtree, pNode);
+ }
+ }
+
+ return rc;
+}
+
+static int Reinsert(
+ Rtree *pRtree,
+ RtreeNode *pNode,
+ RtreeCell *pCell,
+ int iHeight
+){
+ int *aOrder;
+ int *aSpare;
+ RtreeCell *aCell;
+ RtreeDValue *aDistance;
+ int nCell;
+ RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
+ int iDim;
+ int ii;
+ int rc = SQLITE_OK;
+ int n;
+
+ memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
+
+ nCell = NCELL(pNode)+1;
+ n = (nCell+1)&(~1);
+
+ /* Allocate the buffers used by this operation. The allocation is
+ ** relinquished before this function returns.
+ */
+ aCell = (RtreeCell *)sqlite3_malloc64(n * (
+ sizeof(RtreeCell) + /* aCell array */
+ sizeof(int) + /* aOrder array */
+ sizeof(int) + /* aSpare array */
+ sizeof(RtreeDValue) /* aDistance array */
+ ));
+ if( !aCell ){
+ return SQLITE_NOMEM;
+ }
+ aOrder = (int *)&aCell[n];
+ aSpare = (int *)&aOrder[n];
+ aDistance = (RtreeDValue *)&aSpare[n];
+
+ for(ii=0; ii<nCell; ii++){
+ if( ii==(nCell-1) ){
+ memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
+ }else{
+ nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
+ }
+ aOrder[ii] = ii;
+ for(iDim=0; iDim<pRtree->nDim; iDim++){
+ aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
+ aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
+ }
+ }
+ for(iDim=0; iDim<pRtree->nDim; iDim++){
+ aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
+ }
+
+ for(ii=0; ii<nCell; ii++){
+ aDistance[ii] = RTREE_ZERO;
+ for(iDim=0; iDim<pRtree->nDim; iDim++){
+ RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
+ DCOORD(aCell[ii].aCoord[iDim*2]));
+ aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
+ }
+ }
+
+ SortByDistance(aOrder, nCell, aDistance, aSpare);
+ nodeZero(pRtree, pNode);
+
+ for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
+ RtreeCell *p = &aCell[aOrder[ii]];
+ nodeInsertCell(pRtree, pNode, p);
+ if( p->iRowid==pCell->iRowid ){
+ if( iHeight==0 ){
+ rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
+ }else{
+ rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
+ }
+ }
+ }
+ if( rc==SQLITE_OK ){
+ rc = fixBoundingBox(pRtree, pNode);
+ }
+ for(; rc==SQLITE_OK && ii<nCell; ii++){
+ /* Find a node to store this cell in. pNode->iNode currently contains
+ ** the height of the sub-tree headed by the cell.
+ */
+ RtreeNode *pInsert;
+ RtreeCell *p = &aCell[aOrder[ii]];
+ rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
+ if( rc==SQLITE_OK ){
+ int rc2;
+ rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
+ rc2 = nodeRelease(pRtree, pInsert);
+ if( rc==SQLITE_OK ){
+ rc = rc2;
+ }
+ }
+ }
+
+ sqlite3_free(aCell);
+ return rc;
+}
+
+/*
+** Insert cell pCell into node pNode. Node pNode is the head of a
+** subtree iHeight high (leaf nodes have iHeight==0).
+*/
+static int rtreeInsertCell(
+ Rtree *pRtree,
+ RtreeNode *pNode,
+ RtreeCell *pCell,
+ int iHeight
+){
+ int rc = SQLITE_OK;
+ if( iHeight>0 ){
+ RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
+ if( pChild ){
+ nodeRelease(pRtree, pChild->pParent);
+ nodeReference(pNode);
+ pChild->pParent = pNode;
+ }
+ }
+ if( nodeInsertCell(pRtree, pNode, pCell) ){
+ if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
+ rc = SplitNode(pRtree, pNode, pCell, iHeight);
+ }else{
+ pRtree->iReinsertHeight = iHeight;
+ rc = Reinsert(pRtree, pNode, pCell, iHeight);
+ }
+ }else{
+ rc = AdjustTree(pRtree, pNode, pCell);
+ if( rc==SQLITE_OK ){
+ if( iHeight==0 ){
+ rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
+ }else{
+ rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
+ }
+ }
+ }
+ return rc;
+}
+
+static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
+ int ii;
+ int rc = SQLITE_OK;
+ int nCell = NCELL(pNode);
+
+ for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
+ RtreeNode *pInsert;
+ RtreeCell cell;
+ nodeGetCell(pRtree, pNode, ii, &cell);
+
+ /* Find a node to store this cell in. pNode->iNode currently contains
+ ** the height of the sub-tree headed by the cell.
+ */
+ rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
+ if( rc==SQLITE_OK ){
+ int rc2;
+ rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
+ rc2 = nodeRelease(pRtree, pInsert);
+ if( rc==SQLITE_OK ){
+ rc = rc2;
+ }
+ }
+ }
+ return rc;
+}
+
+/*
+** Select a currently unused rowid for a new r-tree record.
+*/
+static int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){
+ int rc;
+ sqlite3_bind_null(pRtree->pWriteRowid, 1);
+ sqlite3_bind_null(pRtree->pWriteRowid, 2);
+ sqlite3_step(pRtree->pWriteRowid);
+ rc = sqlite3_reset(pRtree->pWriteRowid);
+ *piRowid = sqlite3_last_insert_rowid(pRtree->db);
+ return rc;
+}
+
+/*
+** Remove the entry with rowid=iDelete from the r-tree structure.
+*/
+static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
+ int rc; /* Return code */
+ RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
+ int iCell; /* Index of iDelete cell in pLeaf */
+ RtreeNode *pRoot = 0; /* Root node of rtree structure */
+
+
+ /* Obtain a reference to the root node to initialize Rtree.iDepth */
+ rc = nodeAcquire(pRtree, 1, 0, &pRoot);
+
+ /* Obtain a reference to the leaf node that contains the entry
+ ** about to be deleted.
+ */
+ if( rc==SQLITE_OK ){
+ rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
+ }
+
+#ifdef CORRUPT_DB
+ assert( pLeaf!=0 || rc!=SQLITE_OK || CORRUPT_DB );
+#endif
+
+ /* Delete the cell in question from the leaf node. */
+ if( rc==SQLITE_OK && pLeaf ){
+ int rc2;
+ rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
+ if( rc==SQLITE_OK ){
+ rc = deleteCell(pRtree, pLeaf, iCell, 0);
+ }
+ rc2 = nodeRelease(pRtree, pLeaf);
+ if( rc==SQLITE_OK ){
+ rc = rc2;
+ }
+ }
+
+ /* Delete the corresponding entry in the <rtree>_rowid table. */
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
+ sqlite3_step(pRtree->pDeleteRowid);
+ rc = sqlite3_reset(pRtree->pDeleteRowid);
+ }
+
+ /* Check if the root node now has exactly one child. If so, remove
+ ** it, schedule the contents of the child for reinsertion and
+ ** reduce the tree height by one.
+ **
+ ** This is equivalent to copying the contents of the child into
+ ** the root node (the operation that Gutman's paper says to perform
+ ** in this scenario).
+ */
+ if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
+ int rc2;
+ RtreeNode *pChild = 0;
+ i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
+ rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
+ if( rc==SQLITE_OK ){
+ rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
+ }
+ rc2 = nodeRelease(pRtree, pChild);
+ if( rc==SQLITE_OK ) rc = rc2;
+ if( rc==SQLITE_OK ){
+ pRtree->iDepth--;
+ writeInt16(pRoot->zData, pRtree->iDepth);
+ pRoot->isDirty = 1;
+ }
+ }
+
+ /* Re-insert the contents of any underfull nodes removed from the tree. */
+ for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
+ if( rc==SQLITE_OK ){
+ rc = reinsertNodeContent(pRtree, pLeaf);
+ }
+ pRtree->pDeleted = pLeaf->pNext;
+ pRtree->nNodeRef--;
+ sqlite3_free(pLeaf);
+ }
+
+ /* Release the reference to the root node. */
+ if( rc==SQLITE_OK ){
+ rc = nodeRelease(pRtree, pRoot);
+ }else{
+ nodeRelease(pRtree, pRoot);
+ }
+
+ return rc;
+}
+
+/*
+** Rounding constants for float->double conversion.
+*/
+#define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
+#define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
+
+#if !defined(SQLITE_RTREE_INT_ONLY)
+/*
+** Convert an sqlite3_value into an RtreeValue (presumably a float)
+** while taking care to round toward negative or positive, respectively.
+*/
+static RtreeValue rtreeValueDown(sqlite3_value *v){
+ double d = sqlite3_value_double(v);
+ float f = (float)d;
+ if( f>d ){
+ f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
+ }
+ return f;
+}
+static RtreeValue rtreeValueUp(sqlite3_value *v){
+ double d = sqlite3_value_double(v);
+ float f = (float)d;
+ if( f<d ){
+ f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
+ }
+ return f;
+}
+#endif /* !defined(SQLITE_RTREE_INT_ONLY) */
+
+/*
+** A constraint has failed while inserting a row into an rtree table.
+** Assuming no OOM error occurs, this function sets the error message
+** (at pRtree->base.zErrMsg) to an appropriate value and returns
+** SQLITE_CONSTRAINT.
+**
+** Parameter iCol is the index of the leftmost column involved in the
+** constraint failure. If it is 0, then the constraint that failed is
+** the unique constraint on the id column. Otherwise, it is the rtree
+** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
+**
+** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
+*/
+static int rtreeConstraintError(Rtree *pRtree, int iCol){
+ sqlite3_stmt *pStmt = 0;
+ char *zSql;
+ int rc;
+
+ assert( iCol==0 || iCol%2 );
+ zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
+ if( zSql ){
+ rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
+ }else{
+ rc = SQLITE_NOMEM;
+ }
+ sqlite3_free(zSql);
+
+ if( rc==SQLITE_OK ){
+ if( iCol==0 ){
+ const char *zCol = sqlite3_column_name(pStmt, 0);
+ pRtree->base.zErrMsg = sqlite3_mprintf(
+ "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
+ );
+ }else{
+ const char *zCol1 = sqlite3_column_name(pStmt, iCol);
+ const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
+ pRtree->base.zErrMsg = sqlite3_mprintf(
+ "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
+ );
+ }
+ }
+
+ sqlite3_finalize(pStmt);
+ return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
+}
+
+
+
+/*
+** The xUpdate method for rtree module virtual tables.
+*/
+static int rtreeUpdate(
+ sqlite3_vtab *pVtab,
+ int nData,
+ sqlite3_value **aData,
+ sqlite_int64 *pRowid
+){
+ Rtree *pRtree = (Rtree *)pVtab;
+ int rc = SQLITE_OK;
+ RtreeCell cell; /* New cell to insert if nData>1 */
+ int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
+
+ if( pRtree->nNodeRef ){
+ /* Unable to write to the btree while another cursor is reading from it,
+ ** since the write might do a rebalance which would disrupt the read
+ ** cursor. */
+ return SQLITE_LOCKED_VTAB;
+ }
+ rtreeReference(pRtree);
+ assert(nData>=1);
+
+ cell.iRowid = 0; /* Used only to suppress a compiler warning */
+
+ /* Constraint handling. A write operation on an r-tree table may return
+ ** SQLITE_CONSTRAINT for two reasons:
+ **
+ ** 1. A duplicate rowid value, or
+ ** 2. The supplied data violates the "x2>=x1" constraint.
+ **
+ ** In the first case, if the conflict-handling mode is REPLACE, then
+ ** the conflicting row can be removed before proceeding. In the second
+ ** case, SQLITE_CONSTRAINT must be returned regardless of the
+ ** conflict-handling mode specified by the user.
+ */
+ if( nData>1 ){
+ int ii;
+ int nn = nData - 4;
+
+ if( nn > pRtree->nDim2 ) nn = pRtree->nDim2;
+ /* Populate the cell.aCoord[] array. The first coordinate is aData[3].
+ **
+ ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
+ ** with "column" that are interpreted as table constraints.
+ ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
+ ** This problem was discovered after years of use, so we silently ignore
+ ** these kinds of misdeclared tables to avoid breaking any legacy.
+ */
+
+#ifndef SQLITE_RTREE_INT_ONLY
+ if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
+ for(ii=0; ii<nn; ii+=2){
+ cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]);
+ cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]);
+ if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
+ rc = rtreeConstraintError(pRtree, ii+1);
+ goto constraint;
+ }
+ }
+ }else
+#endif
+ {
+ for(ii=0; ii<nn; ii+=2){
+ cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]);
+ cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]);
+ if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
+ rc = rtreeConstraintError(pRtree, ii+1);
+ goto constraint;
+ }
+ }
+ }
+
+ /* If a rowid value was supplied, check if it is already present in
+ ** the table. If so, the constraint has failed. */
+ if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){
+ cell.iRowid = sqlite3_value_int64(aData[2]);
+ if( sqlite3_value_type(aData[0])==SQLITE_NULL
+ || sqlite3_value_int64(aData[0])!=cell.iRowid
+ ){
+ int steprc;
+ sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
+ steprc = sqlite3_step(pRtree->pReadRowid);
+ rc = sqlite3_reset(pRtree->pReadRowid);
+ if( SQLITE_ROW==steprc ){
+ if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
+ rc = rtreeDeleteRowid(pRtree, cell.iRowid);
+ }else{
+ rc = rtreeConstraintError(pRtree, 0);
+ goto constraint;
+ }
+ }
+ }
+ bHaveRowid = 1;
+ }
+ }
+
+ /* If aData[0] is not an SQL NULL value, it is the rowid of a
+ ** record to delete from the r-tree table. The following block does
+ ** just that.
+ */
+ if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){
+ rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0]));
+ }
+
+ /* If the aData[] array contains more than one element, elements
+ ** (aData[2]..aData[argc-1]) contain a new record to insert into
+ ** the r-tree structure.
+ */
+ if( rc==SQLITE_OK && nData>1 ){
+ /* Insert the new record into the r-tree */
+ RtreeNode *pLeaf = 0;
+
+ /* Figure out the rowid of the new row. */
+ if( bHaveRowid==0 ){
+ rc = rtreeNewRowid(pRtree, &cell.iRowid);
+ }
+ *pRowid = cell.iRowid;
+
+ if( rc==SQLITE_OK ){
+ rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
+ }
+ if( rc==SQLITE_OK ){
+ int rc2;
+ pRtree->iReinsertHeight = -1;
+ rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
+ rc2 = nodeRelease(pRtree, pLeaf);
+ if( rc==SQLITE_OK ){
+ rc = rc2;
+ }
+ }
+ if( rc==SQLITE_OK && pRtree->nAux ){
+ sqlite3_stmt *pUp = pRtree->pWriteAux;
+ int jj;
+ sqlite3_bind_int64(pUp, 1, *pRowid);
+ for(jj=0; jj<pRtree->nAux; jj++){
+ sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]);
+ }
+ sqlite3_step(pUp);
+ rc = sqlite3_reset(pUp);
+ }
+ }
+
+constraint:
+ rtreeRelease(pRtree);
+ return rc;
+}
+
+/*
+** Called when a transaction starts.
+*/
+static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
+ Rtree *pRtree = (Rtree *)pVtab;
+ assert( pRtree->inWrTrans==0 );
+ pRtree->inWrTrans++;
+ return SQLITE_OK;
+}
+
+/*
+** Called when a transaction completes (either by COMMIT or ROLLBACK).
+** The sqlite3_blob object should be released at this point.
+*/
+static int rtreeEndTransaction(sqlite3_vtab *pVtab){
+ Rtree *pRtree = (Rtree *)pVtab;
+ pRtree->inWrTrans = 0;
+ nodeBlobReset(pRtree);
+ return SQLITE_OK;
+}
+
+/*
+** The xRename method for rtree module virtual tables.
+*/
+static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
+ Rtree *pRtree = (Rtree *)pVtab;
+ int rc = SQLITE_NOMEM;
+ char *zSql = sqlite3_mprintf(
+ "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
+ "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
+ "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
+ , pRtree->zDb, pRtree->zName, zNewName
+ , pRtree->zDb, pRtree->zName, zNewName
+ , pRtree->zDb, pRtree->zName, zNewName
+ );
+ if( zSql ){
+ nodeBlobReset(pRtree);
+ rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
+ sqlite3_free(zSql);
+ }
+ return rc;
+}
+
+/*
+** The xSavepoint method.
+**
+** This module does not need to do anything to support savepoints. However,
+** it uses this hook to close any open blob handle. This is done because a
+** DROP TABLE command - which fortunately always opens a savepoint - cannot
+** succeed if there are any open blob handles. i.e. if the blob handle were
+** not closed here, the following would fail:
+**
+** BEGIN;
+** INSERT INTO rtree...
+** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED
+** COMMIT;
+*/
+static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
+ Rtree *pRtree = (Rtree *)pVtab;
+ u8 iwt = pRtree->inWrTrans;
+ UNUSED_PARAMETER(iSavepoint);
+ pRtree->inWrTrans = 0;
+ nodeBlobReset(pRtree);
+ pRtree->inWrTrans = iwt;
+ return SQLITE_OK;
+}
+
+/*
+** This function populates the pRtree->nRowEst variable with an estimate
+** of the number of rows in the virtual table. If possible, this is based
+** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
+*/
+static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
+ const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
+ char *zSql;
+ sqlite3_stmt *p;
+ int rc;
+ i64 nRow = 0;
+
+ rc = sqlite3_table_column_metadata(
+ db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
+ );
+ if( rc!=SQLITE_OK ){
+ pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
+ return rc==SQLITE_ERROR ? SQLITE_OK : rc;
+ }
+ zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
+ if( zSql==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
+ if( rc==SQLITE_OK ){
+ if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
+ rc = sqlite3_finalize(p);
+ }else if( rc!=SQLITE_NOMEM ){
+ rc = SQLITE_OK;
+ }
+
+ if( rc==SQLITE_OK ){
+ if( nRow==0 ){
+ pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
+ }else{
+ pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
+ }
+ }
+ sqlite3_free(zSql);
+ }
+
+ return rc;
+}
+
+
+/*
+** Return true if zName is the extension on one of the shadow tables used
+** by this module.
+*/
+static int rtreeShadowName(const char *zName){
+ static const char *azName[] = {
+ "node", "parent", "rowid"
+ };
+ unsigned int i;
+ for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
+ if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
+ }
+ return 0;
+}
+
+static sqlite3_module rtreeModule = {
+ 3, /* iVersion */
+ rtreeCreate, /* xCreate - create a table */
+ rtreeConnect, /* xConnect - connect to an existing table */
+ rtreeBestIndex, /* xBestIndex - Determine search strategy */
+ rtreeDisconnect, /* xDisconnect - Disconnect from a table */
+ rtreeDestroy, /* xDestroy - Drop a table */
+ rtreeOpen, /* xOpen - open a cursor */
+ rtreeClose, /* xClose - close a cursor */
+ rtreeFilter, /* xFilter - configure scan constraints */
+ rtreeNext, /* xNext - advance a cursor */
+ rtreeEof, /* xEof */
+ rtreeColumn, /* xColumn - read data */
+ rtreeRowid, /* xRowid - read data */
+ rtreeUpdate, /* xUpdate - write data */
+ rtreeBeginTransaction, /* xBegin - begin transaction */
+ rtreeEndTransaction, /* xSync - sync transaction */
+ rtreeEndTransaction, /* xCommit - commit transaction */
+ rtreeEndTransaction, /* xRollback - rollback transaction */
+ 0, /* xFindFunction - function overloading */
+ rtreeRename, /* xRename - rename the table */
+ rtreeSavepoint, /* xSavepoint */
+ 0, /* xRelease */
+ 0, /* xRollbackTo */
+ rtreeShadowName /* xShadowName */
+};
+
+static int rtreeSqlInit(
+ Rtree *pRtree,
+ sqlite3 *db,
+ const char *zDb,
+ const char *zPrefix,
+ int isCreate
+){
+ int rc = SQLITE_OK;
+
+ #define N_STATEMENT 8
+ static const char *azSql[N_STATEMENT] = {
+ /* Write the xxx_node table */
+ "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)",
+ "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1",
+
+ /* Read and write the xxx_rowid table */
+ "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1",
+ "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)",
+ "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1",
+
+ /* Read and write the xxx_parent table */
+ "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1",
+ "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)",
+ "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1"
+ };
+ sqlite3_stmt **appStmt[N_STATEMENT];
+ int i;
+ const int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
+
+ pRtree->db = db;
+
+ if( isCreate ){
+ char *zCreate;
+ sqlite3_str *p = sqlite3_str_new(db);
+ int ii;
+ sqlite3_str_appendf(p,
+ "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno",
+ zDb, zPrefix);
+ for(ii=0; ii<pRtree->nAux; ii++){
+ sqlite3_str_appendf(p,",a%d",ii);
+ }
+ sqlite3_str_appendf(p,
+ ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);",
+ zDb, zPrefix);
+ sqlite3_str_appendf(p,
+ "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);",
+ zDb, zPrefix);
+ sqlite3_str_appendf(p,
+ "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))",
+ zDb, zPrefix, pRtree->iNodeSize);
+ zCreate = sqlite3_str_finish(p);
+ if( !zCreate ){
+ return SQLITE_NOMEM;
+ }
+ rc = sqlite3_exec(db, zCreate, 0, 0, 0);
+ sqlite3_free(zCreate);
+ if( rc!=SQLITE_OK ){
+ return rc;
+ }
+ }
+
+ appStmt[0] = &pRtree->pWriteNode;
+ appStmt[1] = &pRtree->pDeleteNode;
+ appStmt[2] = &pRtree->pReadRowid;
+ appStmt[3] = &pRtree->pWriteRowid;
+ appStmt[4] = &pRtree->pDeleteRowid;
+ appStmt[5] = &pRtree->pReadParent;
+ appStmt[6] = &pRtree->pWriteParent;
+ appStmt[7] = &pRtree->pDeleteParent;
+
+ rc = rtreeQueryStat1(db, pRtree);
+ for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
+ char *zSql;
+ const char *zFormat;
+ if( i!=3 || pRtree->nAux==0 ){
+ zFormat = azSql[i];
+ }else {
+ /* An UPSERT is very slightly slower than REPLACE, but it is needed
+ ** if there are auxiliary columns */
+ zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)"
+ "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno";
+ }
+ zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);
+ if( zSql ){
+ rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0);
+ }else{
+ rc = SQLITE_NOMEM;
+ }
+ sqlite3_free(zSql);
+ }
+ if( pRtree->nAux ){
+ pRtree->zReadAuxSql = sqlite3_mprintf(
+ "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1",
+ zDb, zPrefix);
+ if( pRtree->zReadAuxSql==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ sqlite3_str *p = sqlite3_str_new(db);
+ int ii;
+ char *zSql;
+ sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix);
+ for(ii=0; ii<pRtree->nAux; ii++){
+ if( ii ) sqlite3_str_append(p, ",", 1);
+ if( ii<pRtree->nAuxNotNull ){
+ sqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii);
+ }else{
+ sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2);
+ }
+ }
+ sqlite3_str_appendf(p, " WHERE rowid=?1");
+ zSql = sqlite3_str_finish(p);
+ if( zSql==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0);
+ sqlite3_free(zSql);
+ }
+ }
+ }
+
+ return rc;
+}
+
+/*
+** The second argument to this function contains the text of an SQL statement
+** that returns a single integer value. The statement is compiled and executed
+** using database connection db. If successful, the integer value returned
+** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
+** code is returned and the value of *piVal after returning is not defined.
+*/
+static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
+ int rc = SQLITE_NOMEM;
+ if( zSql ){
+ sqlite3_stmt *pStmt = 0;
+ rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
+ if( rc==SQLITE_OK ){
+ if( SQLITE_ROW==sqlite3_step(pStmt) ){
+ *piVal = sqlite3_column_int(pStmt, 0);
+ }
+ rc = sqlite3_finalize(pStmt);
+ }
+ }
+ return rc;
+}
+
+/*
+** This function is called from within the xConnect() or xCreate() method to
+** determine the node-size used by the rtree table being created or connected
+** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
+** Otherwise, an SQLite error code is returned.
+**
+** If this function is being called as part of an xConnect(), then the rtree
+** table already exists. In this case the node-size is determined by inspecting
+** the root node of the tree.
+**
+** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
+** This ensures that each node is stored on a single database page. If the
+** database page-size is so large that more than RTREE_MAXCELLS entries
+** would fit in a single node, use a smaller node-size.
+*/
+static int getNodeSize(
+ sqlite3 *db, /* Database handle */
+ Rtree *pRtree, /* Rtree handle */
+ int isCreate, /* True for xCreate, false for xConnect */
+ char **pzErr /* OUT: Error message, if any */
+){
+ int rc;
+ char *zSql;
+ if( isCreate ){
+ int iPageSize = 0;
+ zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
+ rc = getIntFromStmt(db, zSql, &iPageSize);
+ if( rc==SQLITE_OK ){
+ pRtree->iNodeSize = iPageSize-64;
+ if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
+ pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
+ }
+ }else{
+ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
+ }
+ }else{
+ zSql = sqlite3_mprintf(
+ "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
+ pRtree->zDb, pRtree->zName
+ );
+ rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
+ if( rc!=SQLITE_OK ){
+ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
+ }else if( pRtree->iNodeSize<(512-64) ){
+ rc = SQLITE_CORRUPT_VTAB;
+ RTREE_IS_CORRUPT(pRtree);
+ *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
+ pRtree->zName);
+ }
+ }
+
+ sqlite3_free(zSql);
+ return rc;
+}
+
+/*
+** Return the length of a token
+*/
+static int rtreeTokenLength(const char *z){
+ int dummy = 0;
+ return sqlite3GetToken((const unsigned char*)z,&dummy);
+}
+
+/*
+** This function is the implementation of both the xConnect and xCreate
+** methods of the r-tree virtual table.
+**
+** argv[0] -> module name
+** argv[1] -> database name
+** argv[2] -> table name
+** argv[...] -> column names...
+*/
+static int rtreeInit(
+ sqlite3 *db, /* Database connection */
+ void *pAux, /* One of the RTREE_COORD_* constants */
+ int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
+ sqlite3_vtab **ppVtab, /* OUT: New virtual table */
+ char **pzErr, /* OUT: Error message, if any */
+ int isCreate /* True for xCreate, false for xConnect */
+){
+ int rc = SQLITE_OK;
+ Rtree *pRtree;
+ int nDb; /* Length of string argv[1] */
+ int nName; /* Length of string argv[2] */
+ int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
+ sqlite3_str *pSql;
+ char *zSql;
+ int ii = 4;
+ int iErr;
+
+ const char *aErrMsg[] = {
+ 0, /* 0 */
+ "Wrong number of columns for an rtree table", /* 1 */
+ "Too few columns for an rtree table", /* 2 */
+ "Too many columns for an rtree table", /* 3 */
+ "Auxiliary rtree columns must be last" /* 4 */
+ };
+
+ assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */
+ if( argc<6 || argc>RTREE_MAX_AUX_COLUMN+3 ){
+ *pzErr = sqlite3_mprintf("%s", aErrMsg[2 + (argc>=6)]);
+ return SQLITE_ERROR;
+ }
+
+ sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
+
+ /* Allocate the sqlite3_vtab structure */
+ nDb = (int)strlen(argv[1]);
+ nName = (int)strlen(argv[2]);
+ pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);
+ if( !pRtree ){
+ return SQLITE_NOMEM;
+ }
+ memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
+ pRtree->nBusy = 1;
+ pRtree->base.pModule = &rtreeModule;
+ pRtree->zDb = (char *)&pRtree[1];
+ pRtree->zName = &pRtree->zDb[nDb+1];
+ pRtree->eCoordType = (u8)eCoordType;
+ memcpy(pRtree->zDb, argv[1], nDb);
+ memcpy(pRtree->zName, argv[2], nName);
+
+
+ /* Create/Connect to the underlying relational database schema. If
+ ** that is successful, call sqlite3_declare_vtab() to configure
+ ** the r-tree table schema.
+ */
+ pSql = sqlite3_str_new(db);
+ sqlite3_str_appendf(pSql, "CREATE TABLE x(%.*s INT",
+ rtreeTokenLength(argv[3]), argv[3]);
+ for(ii=4; ii<argc; ii++){
+ const char *zArg = argv[ii];
+ if( zArg[0]=='+' ){
+ pRtree->nAux++;
+ sqlite3_str_appendf(pSql, ",%.*s", rtreeTokenLength(zArg+1), zArg+1);
+ }else if( pRtree->nAux>0 ){
+ break;
+ }else{
+ static const char *azFormat[] = {",%.*s REAL", ",%.*s INT"};
+ pRtree->nDim2++;
+ sqlite3_str_appendf(pSql, azFormat[eCoordType],
+ rtreeTokenLength(zArg), zArg);
+ }
+ }
+ sqlite3_str_appendf(pSql, ");");
+ zSql = sqlite3_str_finish(pSql);
+ if( !zSql ){
+ rc = SQLITE_NOMEM;
+ }else if( ii<argc ){
+ *pzErr = sqlite3_mprintf("%s", aErrMsg[4]);
+ rc = SQLITE_ERROR;
+ }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
+ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
+ }
+ sqlite3_free(zSql);
+ if( rc ) goto rtreeInit_fail;
+ pRtree->nDim = pRtree->nDim2/2;
+ if( pRtree->nDim<1 ){
+ iErr = 2;
+ }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){
+ iErr = 3;
+ }else if( pRtree->nDim2 % 2 ){
+ iErr = 1;
+ }else{
+ iErr = 0;
+ }
+ if( iErr ){
+ *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
+ goto rtreeInit_fail;
+ }
+ pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
+
+ /* Figure out the node size to use. */
+ rc = getNodeSize(db, pRtree, isCreate, pzErr);
+ if( rc ) goto rtreeInit_fail;
+ rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
+ if( rc ){
+ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
+ goto rtreeInit_fail;
+ }
+
+ *ppVtab = (sqlite3_vtab *)pRtree;
+ return SQLITE_OK;
+
+rtreeInit_fail:
+ if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
+ assert( *ppVtab==0 );
+ assert( pRtree->nBusy==1 );
+ rtreeRelease(pRtree);
+ return rc;
+}
+
+
+/*
+** Implementation of a scalar function that decodes r-tree nodes to
+** human readable strings. This can be used for debugging and analysis.
+**
+** The scalar function takes two arguments: (1) the number of dimensions
+** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
+** an r-tree node. For a two-dimensional r-tree structure called "rt", to
+** deserialize all nodes, a statement like:
+**
+** SELECT rtreenode(2, data) FROM rt_node;
+**
+** The human readable string takes the form of a Tcl list with one
+** entry for each cell in the r-tree node. Each entry is itself a
+** list, containing the 8-byte rowid/pageno followed by the
+** <num-dimension>*2 coordinates.
+*/
+static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
+ RtreeNode node;
+ Rtree tree;
+ int ii;
+ int nData;
+ int errCode;
+ sqlite3_str *pOut;
+
+ UNUSED_PARAMETER(nArg);
+ memset(&node, 0, sizeof(RtreeNode));
+ memset(&tree, 0, sizeof(Rtree));
+ tree.nDim = (u8)sqlite3_value_int(apArg[0]);
+ if( tree.nDim<1 || tree.nDim>5 ) return;
+ tree.nDim2 = tree.nDim*2;
+ tree.nBytesPerCell = 8 + 8 * tree.nDim;
+ node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
+ nData = sqlite3_value_bytes(apArg[1]);
+ if( nData<4 ) return;
+ if( nData<NCELL(&node)*tree.nBytesPerCell ) return;
+
+ pOut = sqlite3_str_new(0);
+ for(ii=0; ii<NCELL(&node); ii++){
+ RtreeCell cell;
+ int jj;
+
+ nodeGetCell(&tree, &node, ii, &cell);
+ if( ii>0 ) sqlite3_str_append(pOut, " ", 1);
+ sqlite3_str_appendf(pOut, "{%lld", cell.iRowid);
+ for(jj=0; jj<tree.nDim2; jj++){
+#ifndef SQLITE_RTREE_INT_ONLY
+ sqlite3_str_appendf(pOut, " %g", (double)cell.aCoord[jj].f);
+#else
+ sqlite3_str_appendf(pOut, " %d", cell.aCoord[jj].i);
+#endif
+ }
+ sqlite3_str_append(pOut, "}", 1);
+ }
+ errCode = sqlite3_str_errcode(pOut);
+ sqlite3_result_text(ctx, sqlite3_str_finish(pOut), -1, sqlite3_free);
+ sqlite3_result_error_code(ctx, errCode);
+}
+
+/* This routine implements an SQL function that returns the "depth" parameter
+** from the front of a blob that is an r-tree node. For example:
+**
+** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
+**
+** The depth value is 0 for all nodes other than the root node, and the root
+** node always has nodeno=1, so the example above is the primary use for this
+** routine. This routine is intended for testing and analysis only.
+*/
+static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
+ UNUSED_PARAMETER(nArg);
+ if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
+ || sqlite3_value_bytes(apArg[0])<2
+ ){
+ sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
+ }else{
+ u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
+ sqlite3_result_int(ctx, readInt16(zBlob));
+ }
+}
+
+/*
+** Context object passed between the various routines that make up the
+** implementation of integrity-check function rtreecheck().
+*/
+typedef struct RtreeCheck RtreeCheck;
+struct RtreeCheck {
+ sqlite3 *db; /* Database handle */
+ const char *zDb; /* Database containing rtree table */
+ const char *zTab; /* Name of rtree table */
+ int bInt; /* True for rtree_i32 table */
+ int nDim; /* Number of dimensions for this rtree tbl */
+ sqlite3_stmt *pGetNode; /* Statement used to retrieve nodes */
+ sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
+ int nLeaf; /* Number of leaf cells in table */
+ int nNonLeaf; /* Number of non-leaf cells in table */
+ int rc; /* Return code */
+ char *zReport; /* Message to report */
+ int nErr; /* Number of lines in zReport */
+};
+
+#define RTREE_CHECK_MAX_ERROR 100
+
+/*
+** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
+** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
+*/
+static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
+ int rc = sqlite3_reset(pStmt);
+ if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
+}
+
+/*
+** The second and subsequent arguments to this function are a format string
+** and printf style arguments. This function formats the string and attempts
+** to compile it as an SQL statement.
+**
+** If successful, a pointer to the new SQL statement is returned. Otherwise,
+** NULL is returned and an error code left in RtreeCheck.rc.
+*/
+static sqlite3_stmt *rtreeCheckPrepare(
+ RtreeCheck *pCheck, /* RtreeCheck object */
+ const char *zFmt, ... /* Format string and trailing args */
+){
+ va_list ap;
+ char *z;
+ sqlite3_stmt *pRet = 0;
+
+ va_start(ap, zFmt);
+ z = sqlite3_vmprintf(zFmt, ap);
+
+ if( pCheck->rc==SQLITE_OK ){
+ if( z==0 ){
+ pCheck->rc = SQLITE_NOMEM;
+ }else{
+ pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
+ }
+ }
+
+ sqlite3_free(z);
+ va_end(ap);
+ return pRet;
+}
+
+/*
+** The second and subsequent arguments to this function are a printf()
+** style format string and arguments. This function formats the string and
+** appends it to the report being accumuated in pCheck.
+*/
+static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
+ va_list ap;
+ va_start(ap, zFmt);
+ if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
+ char *z = sqlite3_vmprintf(zFmt, ap);
+ if( z==0 ){
+ pCheck->rc = SQLITE_NOMEM;
+ }else{
+ pCheck->zReport = sqlite3_mprintf("%z%s%z",
+ pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
+ );
+ if( pCheck->zReport==0 ){
+ pCheck->rc = SQLITE_NOMEM;
+ }
+ }
+ pCheck->nErr++;
+ }
+ va_end(ap);
+}
+
+/*
+** This function is a no-op if there is already an error code stored
+** in the RtreeCheck object indicated by the first argument. NULL is
+** returned in this case.
+**
+** Otherwise, the contents of rtree table node iNode are loaded from
+** the database and copied into a buffer obtained from sqlite3_malloc().
+** If no error occurs, a pointer to the buffer is returned and (*pnNode)
+** is set to the size of the buffer in bytes.
+**
+** Or, if an error does occur, NULL is returned and an error code left
+** in the RtreeCheck object. The final value of *pnNode is undefined in
+** this case.
+*/
+static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
+ u8 *pRet = 0; /* Return value */
+
+ if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){
+ pCheck->pGetNode = rtreeCheckPrepare(pCheck,
+ "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
+ pCheck->zDb, pCheck->zTab
+ );
+ }
+
+ if( pCheck->rc==SQLITE_OK ){
+ sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
+ if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
+ int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
+ const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
+ pRet = sqlite3_malloc64(nNode);
+ if( pRet==0 ){
+ pCheck->rc = SQLITE_NOMEM;
+ }else{
+ memcpy(pRet, pNode, nNode);
+ *pnNode = nNode;
+ }
+ }
+ rtreeCheckReset(pCheck, pCheck->pGetNode);
+ if( pCheck->rc==SQLITE_OK && pRet==0 ){
+ rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
+ }
+ }
+
+ return pRet;
+}
+
+/*
+** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
+** (if bLeaf==1) table contains a specified entry. The schemas of the
+** two tables are:
+**
+** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
+** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
+**
+** In both cases, this function checks that there exists an entry with
+** IPK value iKey and the second column set to iVal.
+**
+*/
+static void rtreeCheckMapping(
+ RtreeCheck *pCheck, /* RtreeCheck object */
+ int bLeaf, /* True for a leaf cell, false for interior */
+ i64 iKey, /* Key for mapping */
+ i64 iVal /* Expected value for mapping */
+){
+ int rc;
+ sqlite3_stmt *pStmt;
+ const char *azSql[2] = {
+ "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1",
+ "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1"
+ };
+
+ assert( bLeaf==0 || bLeaf==1 );
+ if( pCheck->aCheckMapping[bLeaf]==0 ){
+ pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
+ azSql[bLeaf], pCheck->zDb, pCheck->zTab
+ );
+ }
+ if( pCheck->rc!=SQLITE_OK ) return;
+
+ pStmt = pCheck->aCheckMapping[bLeaf];
+ sqlite3_bind_int64(pStmt, 1, iKey);
+ rc = sqlite3_step(pStmt);
+ if( rc==SQLITE_DONE ){
+ rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
+ iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
+ );
+ }else if( rc==SQLITE_ROW ){
+ i64 ii = sqlite3_column_int64(pStmt, 0);
+ if( ii!=iVal ){
+ rtreeCheckAppendMsg(pCheck,
+ "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
+ iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
+ );
+ }
+ }
+ rtreeCheckReset(pCheck, pStmt);
+}
+
+/*
+** Argument pCell points to an array of coordinates stored on an rtree page.
+** This function checks that the coordinates are internally consistent (no
+** x1>x2 conditions) and adds an error message to the RtreeCheck object
+** if they are not.
+**
+** Additionally, if pParent is not NULL, then it is assumed to point to
+** the array of coordinates on the parent page that bound the page
+** containing pCell. In this case it is also verified that the two
+** sets of coordinates are mutually consistent and an error message added
+** to the RtreeCheck object if they are not.
+*/
+static void rtreeCheckCellCoord(
+ RtreeCheck *pCheck,
+ i64 iNode, /* Node id to use in error messages */
+ int iCell, /* Cell number to use in error messages */
+ u8 *pCell, /* Pointer to cell coordinates */
+ u8 *pParent /* Pointer to parent coordinates */
+){
+ RtreeCoord c1, c2;
+ RtreeCoord p1, p2;
+ int i;
+
+ for(i=0; i<pCheck->nDim; i++){
+ readCoord(&pCell[4*2*i], &c1);
+ readCoord(&pCell[4*(2*i + 1)], &c2);
+
+ /* printf("%e, %e\n", c1.u.f, c2.u.f); */
+ if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
+ rtreeCheckAppendMsg(pCheck,
+ "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
+ );
+ }
+
+ if( pParent ){
+ readCoord(&pParent[4*2*i], &p1);
+ readCoord(&pParent[4*(2*i + 1)], &p2);
+
+ if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
+ || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
+ ){
+ rtreeCheckAppendMsg(pCheck,
+ "Dimension %d of cell %d on node %lld is corrupt relative to parent"
+ , i, iCell, iNode
+ );
+ }
+ }
+ }
+}
+
+/*
+** Run rtreecheck() checks on node iNode, which is at depth iDepth within
+** the r-tree structure. Argument aParent points to the array of coordinates
+** that bound node iNode on the parent node.
+**
+** If any problems are discovered, an error message is appended to the
+** report accumulated in the RtreeCheck object.
+*/
+static void rtreeCheckNode(
+ RtreeCheck *pCheck,
+ int iDepth, /* Depth of iNode (0==leaf) */
+ u8 *aParent, /* Buffer containing parent coords */
+ i64 iNode /* Node to check */
+){
+ u8 *aNode = 0;
+ int nNode = 0;
+
+ assert( iNode==1 || aParent!=0 );
+ assert( pCheck->nDim>0 );
+
+ aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
+ if( aNode ){
+ if( nNode<4 ){
+ rtreeCheckAppendMsg(pCheck,
+ "Node %lld is too small (%d bytes)", iNode, nNode
+ );
+ }else{
+ int nCell; /* Number of cells on page */
+ int i; /* Used to iterate through cells */
+ if( aParent==0 ){
+ iDepth = readInt16(aNode);
+ if( iDepth>RTREE_MAX_DEPTH ){
+ rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
+ sqlite3_free(aNode);
+ return;
+ }
+ }
+ nCell = readInt16(&aNode[2]);
+ if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
+ rtreeCheckAppendMsg(pCheck,
+ "Node %lld is too small for cell count of %d (%d bytes)",
+ iNode, nCell, nNode
+ );
+ }else{
+ for(i=0; i<nCell; i++){
+ u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
+ i64 iVal = readInt64(pCell);
+ rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
+
+ if( iDepth>0 ){
+ rtreeCheckMapping(pCheck, 0, iVal, iNode);
+ rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
+ pCheck->nNonLeaf++;
+ }else{
+ rtreeCheckMapping(pCheck, 1, iVal, iNode);
+ pCheck->nLeaf++;
+ }
+ }
+ }
+ }
+ sqlite3_free(aNode);
+ }
+}
+
+/*
+** The second argument to this function must be either "_rowid" or
+** "_parent". This function checks that the number of entries in the
+** %_rowid or %_parent table is exactly nExpect. If not, it adds
+** an error message to the report in the RtreeCheck object indicated
+** by the first argument.
+*/
+static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
+ if( pCheck->rc==SQLITE_OK ){
+ sqlite3_stmt *pCount;
+ pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
+ pCheck->zDb, pCheck->zTab, zTbl
+ );
+ if( pCount ){
+ if( sqlite3_step(pCount)==SQLITE_ROW ){
+ i64 nActual = sqlite3_column_int64(pCount, 0);
+ if( nActual!=nExpect ){
+ rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
+ " - expected %lld, actual %lld" , zTbl, nExpect, nActual
+ );
+ }
+ }
+ pCheck->rc = sqlite3_finalize(pCount);
+ }
+ }
+}
+
+/*
+** This function does the bulk of the work for the rtree integrity-check.
+** It is called by rtreecheck(), which is the SQL function implementation.
+*/
+static int rtreeCheckTable(
+ sqlite3 *db, /* Database handle to access db through */
+ const char *zDb, /* Name of db ("main", "temp" etc.) */
+ const char *zTab, /* Name of rtree table to check */
+ char **pzReport /* OUT: sqlite3_malloc'd report text */
+){
+ RtreeCheck check; /* Common context for various routines */
+ sqlite3_stmt *pStmt = 0; /* Used to find column count of rtree table */
+ int bEnd = 0; /* True if transaction should be closed */
+ int nAux = 0; /* Number of extra columns. */
+
+ /* Initialize the context object */
+ memset(&check, 0, sizeof(check));
+ check.db = db;
+ check.zDb = zDb;
+ check.zTab = zTab;
+
+ /* If there is not already an open transaction, open one now. This is
+ ** to ensure that the queries run as part of this integrity-check operate
+ ** on a consistent snapshot. */
+ if( sqlite3_get_autocommit(db) ){
+ check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
+ bEnd = 1;
+ }
+
+ /* Find the number of auxiliary columns */
+ if( check.rc==SQLITE_OK ){
+ pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
+ if( pStmt ){
+ nAux = sqlite3_column_count(pStmt) - 2;
+ sqlite3_finalize(pStmt);
+ }
+ check.rc = SQLITE_OK;
+ }
+
+ /* Find number of dimensions in the rtree table. */
+ pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
+ if( pStmt ){
+ int rc;
+ check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;
+ if( check.nDim<1 ){
+ rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
+ }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
+ check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
+ }
+ rc = sqlite3_finalize(pStmt);
+ if( rc!=SQLITE_CORRUPT ) check.rc = rc;
+ }
+
+ /* Do the actual integrity-check */
+ if( check.nDim>=1 ){
+ if( check.rc==SQLITE_OK ){
+ rtreeCheckNode(&check, 0, 0, 1);
+ }
+ rtreeCheckCount(&check, "_rowid", check.nLeaf);
+ rtreeCheckCount(&check, "_parent", check.nNonLeaf);
+ }
+
+ /* Finalize SQL statements used by the integrity-check */
+ sqlite3_finalize(check.pGetNode);
+ sqlite3_finalize(check.aCheckMapping[0]);
+ sqlite3_finalize(check.aCheckMapping[1]);
+
+ /* If one was opened, close the transaction */
+ if( bEnd ){
+ int rc = sqlite3_exec(db, "END", 0, 0, 0);
+ if( check.rc==SQLITE_OK ) check.rc = rc;
+ }
+ *pzReport = check.zReport;
+ return check.rc;
+}
+
+/*
+** Usage:
+**
+** rtreecheck(<rtree-table>);
+** rtreecheck(<database>, <rtree-table>);
+**
+** Invoking this SQL function runs an integrity-check on the named rtree
+** table. The integrity-check verifies the following:
+**
+** 1. For each cell in the r-tree structure (%_node table), that:
+**
+** a) for each dimension, (coord1 <= coord2).
+**
+** b) unless the cell is on the root node, that the cell is bounded
+** by the parent cell on the parent node.
+**
+** c) for leaf nodes, that there is an entry in the %_rowid
+** table corresponding to the cell's rowid value that
+** points to the correct node.
+**
+** d) for cells on non-leaf nodes, that there is an entry in the
+** %_parent table mapping from the cell's child node to the
+** node that it resides on.
+**
+** 2. That there are the same number of entries in the %_rowid table
+** as there are leaf cells in the r-tree structure, and that there
+** is a leaf cell that corresponds to each entry in the %_rowid table.
+**
+** 3. That there are the same number of entries in the %_parent table
+** as there are non-leaf cells in the r-tree structure, and that
+** there is a non-leaf cell that corresponds to each entry in the
+** %_parent table.
+*/
+static void rtreecheck(
+ sqlite3_context *ctx,
+ int nArg,
+ sqlite3_value **apArg
+){
+ if( nArg!=1 && nArg!=2 ){
+ sqlite3_result_error(ctx,
+ "wrong number of arguments to function rtreecheck()", -1
+ );
+ }else{
+ int rc;
+ char *zReport = 0;
+ const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
+ const char *zTab;
+ if( nArg==1 ){
+ zTab = zDb;
+ zDb = "main";
+ }else{
+ zTab = (const char*)sqlite3_value_text(apArg[1]);
+ }
+ rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
+ if( rc==SQLITE_OK ){
+ sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
+ }else{
+ sqlite3_result_error_code(ctx, rc);
+ }
+ sqlite3_free(zReport);
+ }
+}
+
+/* Conditionally include the geopoly code */
+#ifdef SQLITE_ENABLE_GEOPOLY
+/************** Include geopoly.c in the middle of rtree.c *******************/
+/************** Begin file geopoly.c *****************************************/
+/*
+** 2018-05-25
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file implements an alternative R-Tree virtual table that
+** uses polygons to express the boundaries of 2-dimensional objects.
+**
+** This file is #include-ed onto the end of "rtree.c" so that it has
+** access to all of the R-Tree internals.
+*/
+/* #include <stdlib.h> */
+
+/* Enable -DGEOPOLY_ENABLE_DEBUG for debugging facilities */
+#ifdef GEOPOLY_ENABLE_DEBUG
+ static int geo_debug = 0;
+# define GEODEBUG(X) if(geo_debug)printf X
+#else
+# define GEODEBUG(X)
+#endif
+
+#ifndef JSON_NULL /* The following stuff repeats things found in json1 */
+/*
+** Versions of isspace(), isalnum() and isdigit() to which it is safe
+** to pass signed char values.
+*/
+#ifdef sqlite3Isdigit
+ /* Use the SQLite core versions if this routine is part of the
+ ** SQLite amalgamation */
+# define safe_isdigit(x) sqlite3Isdigit(x)
+# define safe_isalnum(x) sqlite3Isalnum(x)
+# define safe_isxdigit(x) sqlite3Isxdigit(x)
+#else
+ /* Use the standard library for separate compilation */
+#include <ctype.h> /* amalgamator: keep */
+# define safe_isdigit(x) isdigit((unsigned char)(x))
+# define safe_isalnum(x) isalnum((unsigned char)(x))
+# define safe_isxdigit(x) isxdigit((unsigned char)(x))
+#endif
+
+/*
+** Growing our own isspace() routine this way is twice as fast as
+** the library isspace() function.
+*/
+static const char geopolyIsSpace[] = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+};
+#define safe_isspace(x) (geopolyIsSpace[(unsigned char)x])
+#endif /* JSON NULL - back to original code */
+
+/* Compiler and version */
+#ifndef GCC_VERSION
+#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
+# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
+#else
+# define GCC_VERSION 0
+#endif
+#endif
+#ifndef MSVC_VERSION
+#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
+# define MSVC_VERSION _MSC_VER
+#else
+# define MSVC_VERSION 0
+#endif
+#endif
+
+/* Datatype for coordinates
+*/
+typedef float GeoCoord;
+
+/*
+** Internal representation of a polygon.
+**
+** The polygon consists of a sequence of vertexes. There is a line
+** segment between each pair of vertexes, and one final segment from
+** the last vertex back to the first. (This differs from the GeoJSON
+** standard in which the final vertex is a repeat of the first.)
+**
+** The polygon follows the right-hand rule. The area to the right of
+** each segment is "outside" and the area to the left is "inside".
+**
+** The on-disk representation consists of a 4-byte header followed by
+** the values. The 4-byte header is:
+**
+** encoding (1 byte) 0=big-endian, 1=little-endian
+** nvertex (3 bytes) Number of vertexes as a big-endian integer
+**
+** Enough space is allocated for 4 coordinates, to work around over-zealous
+** warnings coming from some compiler (notably, clang). In reality, the size
+** of each GeoPoly memory allocate is adjusted as necessary so that the
+** GeoPoly.a[] array at the end is the appropriate size.
+*/
+typedef struct GeoPoly GeoPoly;
+struct GeoPoly {
+ int nVertex; /* Number of vertexes */
+ unsigned char hdr[4]; /* Header for on-disk representation */
+ GeoCoord a[8]; /* 2*nVertex values. X (longitude) first, then Y */
+};
+
+/* The size of a memory allocation needed for a GeoPoly object sufficient
+** to hold N coordinate pairs.
+*/
+#define GEOPOLY_SZ(N) (sizeof(GeoPoly) + sizeof(GeoCoord)*2*((N)-4))
+
+/* Macros to access coordinates of a GeoPoly.
+** We have to use these macros, rather than just say p->a[i] in order
+** to silence (incorrect) UBSAN warnings if the array index is too large.
+*/
+#define GeoX(P,I) (((GeoCoord*)(P)->a)[(I)*2])
+#define GeoY(P,I) (((GeoCoord*)(P)->a)[(I)*2+1])
+
+
+/*
+** State of a parse of a GeoJSON input.
+*/
+typedef struct GeoParse GeoParse;
+struct GeoParse {
+ const unsigned char *z; /* Unparsed input */
+ int nVertex; /* Number of vertexes in a[] */
+ int nAlloc; /* Space allocated to a[] */
+ int nErr; /* Number of errors encountered */
+ GeoCoord *a; /* Array of vertexes. From sqlite3_malloc64() */
+};
+
+/* Do a 4-byte byte swap */
+static void geopolySwab32(unsigned char *a){
+ unsigned char t = a[0];
+ a[0] = a[3];
+ a[3] = t;
+ t = a[1];
+ a[1] = a[2];
+ a[2] = t;
+}
+
+/* Skip whitespace. Return the next non-whitespace character. */
+static char geopolySkipSpace(GeoParse *p){
+ while( safe_isspace(p->z[0]) ) p->z++;
+ return p->z[0];
+}
+
+/* Parse out a number. Write the value into *pVal if pVal!=0.
+** return non-zero on success and zero if the next token is not a number.
+*/
+static int geopolyParseNumber(GeoParse *p, GeoCoord *pVal){
+ char c = geopolySkipSpace(p);
+ const unsigned char *z = p->z;
+ int j = 0;
+ int seenDP = 0;
+ int seenE = 0;
+ if( c=='-' ){
+ j = 1;
+ c = z[j];
+ }
+ if( c=='0' && z[j+1]>='0' && z[j+1]<='9' ) return 0;
+ for(;; j++){
+ c = z[j];
+ if( safe_isdigit(c) ) continue;
+ if( c=='.' ){
+ if( z[j-1]=='-' ) return 0;
+ if( seenDP ) return 0;
+ seenDP = 1;
+ continue;
+ }
+ if( c=='e' || c=='E' ){
+ if( z[j-1]<'0' ) return 0;
+ if( seenE ) return -1;
+ seenDP = seenE = 1;
+ c = z[j+1];
+ if( c=='+' || c=='-' ){
+ j++;
+ c = z[j+1];
+ }
+ if( c<'0' || c>'9' ) return 0;
+ continue;
+ }
+ break;
+ }
+ if( z[j-1]<'0' ) return 0;
+ if( pVal ){
+#ifdef SQLITE_AMALGAMATION
+ /* The sqlite3AtoF() routine is much much faster than atof(), if it
+ ** is available */
+ double r;
+ (void)sqlite3AtoF((const char*)p->z, &r, j, SQLITE_UTF8);
+ *pVal = r;
+#else
+ *pVal = (GeoCoord)atof((const char*)p->z);
+#endif
+ }
+ p->z += j;
+ return 1;
+}
+
+/*
+** If the input is a well-formed JSON array of coordinates with at least
+** four coordinates and where each coordinate is itself a two-value array,
+** then convert the JSON into a GeoPoly object and return a pointer to
+** that object.
+**
+** If any error occurs, return NULL.
+*/
+static GeoPoly *geopolyParseJson(const unsigned char *z, int *pRc){
+ GeoParse s;
+ int rc = SQLITE_OK;
+ memset(&s, 0, sizeof(s));
+ s.z = z;
+ if( geopolySkipSpace(&s)=='[' ){
+ s.z++;
+ while( geopolySkipSpace(&s)=='[' ){
+ int ii = 0;
+ char c;
+ s.z++;
+ if( s.nVertex>=s.nAlloc ){
+ GeoCoord *aNew;
+ s.nAlloc = s.nAlloc*2 + 16;
+ aNew = sqlite3_realloc64(s.a, s.nAlloc*sizeof(GeoCoord)*2 );
+ if( aNew==0 ){
+ rc = SQLITE_NOMEM;
+ s.nErr++;
+ break;
+ }
+ s.a = aNew;
+ }
+ while( geopolyParseNumber(&s, ii<=1 ? &s.a[s.nVertex*2+ii] : 0) ){
+ ii++;
+ if( ii==2 ) s.nVertex++;
+ c = geopolySkipSpace(&s);
+ s.z++;
+ if( c==',' ) continue;
+ if( c==']' && ii>=2 ) break;
+ s.nErr++;
+ rc = SQLITE_ERROR;
+ goto parse_json_err;
+ }
+ if( geopolySkipSpace(&s)==',' ){
+ s.z++;
+ continue;
+ }
+ break;
+ }
+ if( geopolySkipSpace(&s)==']'
+ && s.nVertex>=4
+ && s.a[0]==s.a[s.nVertex*2-2]
+ && s.a[1]==s.a[s.nVertex*2-1]
+ && (s.z++, geopolySkipSpace(&s)==0)
+ ){
+ GeoPoly *pOut;
+ int x = 1;
+ s.nVertex--; /* Remove the redundant vertex at the end */
+ pOut = sqlite3_malloc64( GEOPOLY_SZ((sqlite3_int64)s.nVertex) );
+ x = 1;
+ if( pOut==0 ) goto parse_json_err;
+ pOut->nVertex = s.nVertex;
+ memcpy(pOut->a, s.a, s.nVertex*2*sizeof(GeoCoord));
+ pOut->hdr[0] = *(unsigned char*)&x;
+ pOut->hdr[1] = (s.nVertex>>16)&0xff;
+ pOut->hdr[2] = (s.nVertex>>8)&0xff;
+ pOut->hdr[3] = s.nVertex&0xff;
+ sqlite3_free(s.a);
+ if( pRc ) *pRc = SQLITE_OK;
+ return pOut;
+ }else{
+ s.nErr++;
+ rc = SQLITE_ERROR;
+ }
+ }
+parse_json_err:
+ if( pRc ) *pRc = rc;
+ sqlite3_free(s.a);
+ return 0;
+}
+
+/*
+** Given a function parameter, try to interpret it as a polygon, either
+** in the binary format or JSON text. Compute a GeoPoly object and
+** return a pointer to that object. Or if the input is not a well-formed
+** polygon, put an error message in sqlite3_context and return NULL.
+*/
+static GeoPoly *geopolyFuncParam(
+ sqlite3_context *pCtx, /* Context for error messages */
+ sqlite3_value *pVal, /* The value to decode */
+ int *pRc /* Write error here */
+){
+ GeoPoly *p = 0;
+ int nByte;
+ if( sqlite3_value_type(pVal)==SQLITE_BLOB
+ && (nByte = sqlite3_value_bytes(pVal))>=(4+6*sizeof(GeoCoord))
+ ){
+ const unsigned char *a = sqlite3_value_blob(pVal);
+ int nVertex;
+ nVertex = (a[1]<<16) + (a[2]<<8) + a[3];
+ if( (a[0]==0 || a[0]==1)
+ && (nVertex*2*sizeof(GeoCoord) + 4)==(unsigned int)nByte
+ ){
+ p = sqlite3_malloc64( sizeof(*p) + (nVertex-1)*2*sizeof(GeoCoord) );
+ if( p==0 ){
+ if( pRc ) *pRc = SQLITE_NOMEM;
+ if( pCtx ) sqlite3_result_error_nomem(pCtx);
+ }else{
+ int x = 1;
+ p->nVertex = nVertex;
+ memcpy(p->hdr, a, nByte);
+ if( a[0] != *(unsigned char*)&x ){
+ int ii;
+ for(ii=0; ii<nVertex; ii++){
+ geopolySwab32((unsigned char*)&GeoX(p,ii));
+ geopolySwab32((unsigned char*)&GeoY(p,ii));
+ }
+ p->hdr[0] ^= 1;
+ }
+ }
+ }
+ if( pRc ) *pRc = SQLITE_OK;
+ return p;
+ }else if( sqlite3_value_type(pVal)==SQLITE_TEXT ){
+ const unsigned char *zJson = sqlite3_value_text(pVal);
+ if( zJson==0 ){
+ if( pRc ) *pRc = SQLITE_NOMEM;
+ return 0;
+ }
+ return geopolyParseJson(zJson, pRc);
+ }else{
+ if( pRc ) *pRc = SQLITE_ERROR;
+ return 0;
+ }
+}
+
+/*
+** Implementation of the geopoly_blob(X) function.
+**
+** If the input is a well-formed Geopoly BLOB or JSON string
+** then return the BLOB representation of the polygon. Otherwise
+** return NULL.
+*/
+static void geopolyBlobFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
+ if( p ){
+ sqlite3_result_blob(context, p->hdr,
+ 4+8*p->nVertex, SQLITE_TRANSIENT);
+ sqlite3_free(p);
+ }
+}
+
+/*
+** SQL function: geopoly_json(X)
+**
+** Interpret X as a polygon and render it as a JSON array
+** of coordinates. Or, if X is not a valid polygon, return NULL.
+*/
+static void geopolyJsonFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
+ if( p ){
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ sqlite3_str *x = sqlite3_str_new(db);
+ int i;
+ sqlite3_str_append(x, "[", 1);
+ for(i=0; i<p->nVertex; i++){
+ sqlite3_str_appendf(x, "[%!g,%!g],", GeoX(p,i), GeoY(p,i));
+ }
+ sqlite3_str_appendf(x, "[%!g,%!g]]", GeoX(p,0), GeoY(p,0));
+ sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
+ sqlite3_free(p);
+ }
+}
+
+/*
+** SQL function: geopoly_svg(X, ....)
+**
+** Interpret X as a polygon and render it as a SVG <polyline>.
+** Additional arguments are added as attributes to the <polyline>.
+*/
+static void geopolySvgFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ GeoPoly *p;
+ if( argc<1 ) return;
+ p = geopolyFuncParam(context, argv[0], 0);
+ if( p ){
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ sqlite3_str *x = sqlite3_str_new(db);
+ int i;
+ char cSep = '\'';
+ sqlite3_str_appendf(x, "<polyline points=");
+ for(i=0; i<p->nVertex; i++){
+ sqlite3_str_appendf(x, "%c%g,%g", cSep, GeoX(p,i), GeoY(p,i));
+ cSep = ' ';
+ }
+ sqlite3_str_appendf(x, " %g,%g'", GeoX(p,0), GeoY(p,0));
+ for(i=1; i<argc; i++){
+ const char *z = (const char*)sqlite3_value_text(argv[i]);
+ if( z && z[0] ){
+ sqlite3_str_appendf(x, " %s", z);
+ }
+ }
+ sqlite3_str_appendf(x, "></polyline>");
+ sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
+ sqlite3_free(p);
+ }
+}
+
+/*
+** SQL Function: geopoly_xform(poly, A, B, C, D, E, F)
+**
+** Transform and/or translate a polygon as follows:
+**
+** x1 = A*x0 + B*y0 + E
+** y1 = C*x0 + D*y0 + F
+**
+** For a translation:
+**
+** geopoly_xform(poly, 1, 0, 0, 1, x-offset, y-offset)
+**
+** Rotate by R around the point (0,0):
+**
+** geopoly_xform(poly, cos(R), sin(R), -sin(R), cos(R), 0, 0)
+*/
+static void geopolyXformFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
+ double A = sqlite3_value_double(argv[1]);
+ double B = sqlite3_value_double(argv[2]);
+ double C = sqlite3_value_double(argv[3]);
+ double D = sqlite3_value_double(argv[4]);
+ double E = sqlite3_value_double(argv[5]);
+ double F = sqlite3_value_double(argv[6]);
+ GeoCoord x1, y1, x0, y0;
+ int ii;
+ if( p ){
+ for(ii=0; ii<p->nVertex; ii++){
+ x0 = GeoX(p,ii);
+ y0 = GeoY(p,ii);
+ x1 = (GeoCoord)(A*x0 + B*y0 + E);
+ y1 = (GeoCoord)(C*x0 + D*y0 + F);
+ GeoX(p,ii) = x1;
+ GeoY(p,ii) = y1;
+ }
+ sqlite3_result_blob(context, p->hdr,
+ 4+8*p->nVertex, SQLITE_TRANSIENT);
+ sqlite3_free(p);
+ }
+}
+
+/*
+** Compute the area enclosed by the polygon.
+**
+** This routine can also be used to detect polygons that rotate in
+** the wrong direction. Polygons are suppose to be counter-clockwise (CCW).
+** This routine returns a negative value for clockwise (CW) polygons.
+*/
+static double geopolyArea(GeoPoly *p){
+ double rArea = 0.0;
+ int ii;
+ for(ii=0; ii<p->nVertex-1; ii++){
+ rArea += (GeoX(p,ii) - GeoX(p,ii+1)) /* (x0 - x1) */
+ * (GeoY(p,ii) + GeoY(p,ii+1)) /* (y0 + y1) */
+ * 0.5;
+ }
+ rArea += (GeoX(p,ii) - GeoX(p,0)) /* (xN - x0) */
+ * (GeoY(p,ii) + GeoY(p,0)) /* (yN + y0) */
+ * 0.5;
+ return rArea;
+}
+
+/*
+** Implementation of the geopoly_area(X) function.
+**
+** If the input is a well-formed Geopoly BLOB then return the area
+** enclosed by the polygon. If the polygon circulates clockwise instead
+** of counterclockwise (as it should) then return the negative of the
+** enclosed area. Otherwise return NULL.
+*/
+static void geopolyAreaFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
+ if( p ){
+ sqlite3_result_double(context, geopolyArea(p));
+ sqlite3_free(p);
+ }
+}
+
+/*
+** Implementation of the geopoly_ccw(X) function.
+**
+** If the rotation of polygon X is clockwise (incorrect) instead of
+** counter-clockwise (the correct winding order according to RFC7946)
+** then reverse the order of the vertexes in polygon X.
+**
+** In other words, this routine returns a CCW polygon regardless of the
+** winding order of its input.
+**
+** Use this routine to sanitize historical inputs that that sometimes
+** contain polygons that wind in the wrong direction.
+*/
+static void geopolyCcwFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
+ if( p ){
+ if( geopolyArea(p)<0.0 ){
+ int ii, jj;
+ for(ii=1, jj=p->nVertex-1; ii<jj; ii++, jj--){
+ GeoCoord t = GeoX(p,ii);
+ GeoX(p,ii) = GeoX(p,jj);
+ GeoX(p,jj) = t;
+ t = GeoY(p,ii);
+ GeoY(p,ii) = GeoY(p,jj);
+ GeoY(p,jj) = t;
+ }
+ }
+ sqlite3_result_blob(context, p->hdr,
+ 4+8*p->nVertex, SQLITE_TRANSIENT);
+ sqlite3_free(p);
+ }
+}
+
+#define GEOPOLY_PI 3.1415926535897932385
+
+/* Fast approximation for sine(X) for X between -0.5*pi and 2*pi
+*/
+static double geopolySine(double r){
+ assert( r>=-0.5*GEOPOLY_PI && r<=2.0*GEOPOLY_PI );
+ if( r>=1.5*GEOPOLY_PI ){
+ r -= 2.0*GEOPOLY_PI;
+ }
+ if( r>=0.5*GEOPOLY_PI ){
+ return -geopolySine(r-GEOPOLY_PI);
+ }else{
+ double r2 = r*r;
+ double r3 = r2*r;
+ double r5 = r3*r2;
+ return 0.9996949*r - 0.1656700*r3 + 0.0075134*r5;
+ }
+}
+
+/*
+** Function: geopoly_regular(X,Y,R,N)
+**
+** Construct a simple, convex, regular polygon centered at X, Y
+** with circumradius R and with N sides.
+*/
+static void geopolyRegularFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ double x = sqlite3_value_double(argv[0]);
+ double y = sqlite3_value_double(argv[1]);
+ double r = sqlite3_value_double(argv[2]);
+ int n = sqlite3_value_int(argv[3]);
+ int i;
+ GeoPoly *p;
+
+ if( n<3 || r<=0.0 ) return;
+ if( n>1000 ) n = 1000;
+ p = sqlite3_malloc64( sizeof(*p) + (n-1)*2*sizeof(GeoCoord) );
+ if( p==0 ){
+ sqlite3_result_error_nomem(context);
+ return;
+ }
+ i = 1;
+ p->hdr[0] = *(unsigned char*)&i;
+ p->hdr[1] = 0;
+ p->hdr[2] = (n>>8)&0xff;
+ p->hdr[3] = n&0xff;
+ for(i=0; i<n; i++){
+ double rAngle = 2.0*GEOPOLY_PI*i/n;
+ GeoX(p,i) = x - r*geopolySine(rAngle-0.5*GEOPOLY_PI);
+ GeoY(p,i) = y + r*geopolySine(rAngle);
+ }
+ sqlite3_result_blob(context, p->hdr, 4+8*n, SQLITE_TRANSIENT);
+ sqlite3_free(p);
+}
+
+/*
+** If pPoly is a polygon, compute its bounding box. Then:
+**
+** (1) if aCoord!=0 store the bounding box in aCoord, returning NULL
+** (2) otherwise, compute a GeoPoly for the bounding box and return the
+** new GeoPoly
+**
+** If pPoly is NULL but aCoord is not NULL, then compute a new GeoPoly from
+** the bounding box in aCoord and return a pointer to that GeoPoly.
+*/
+static GeoPoly *geopolyBBox(
+ sqlite3_context *context, /* For recording the error */
+ sqlite3_value *pPoly, /* The polygon */
+ RtreeCoord *aCoord, /* Results here */
+ int *pRc /* Error code here */
+){
+ GeoPoly *pOut = 0;
+ GeoPoly *p;
+ float mnX, mxX, mnY, mxY;
+ if( pPoly==0 && aCoord!=0 ){
+ p = 0;
+ mnX = aCoord[0].f;
+ mxX = aCoord[1].f;
+ mnY = aCoord[2].f;
+ mxY = aCoord[3].f;
+ goto geopolyBboxFill;
+ }else{
+ p = geopolyFuncParam(context, pPoly, pRc);
+ }
+ if( p ){
+ int ii;
+ mnX = mxX = GeoX(p,0);
+ mnY = mxY = GeoY(p,0);
+ for(ii=1; ii<p->nVertex; ii++){
+ double r = GeoX(p,ii);
+ if( r<mnX ) mnX = (float)r;
+ else if( r>mxX ) mxX = (float)r;
+ r = GeoY(p,ii);
+ if( r<mnY ) mnY = (float)r;
+ else if( r>mxY ) mxY = (float)r;
+ }
+ if( pRc ) *pRc = SQLITE_OK;
+ if( aCoord==0 ){
+ geopolyBboxFill:
+ pOut = sqlite3_realloc64(p, GEOPOLY_SZ(4));
+ if( pOut==0 ){
+ sqlite3_free(p);
+ if( context ) sqlite3_result_error_nomem(context);
+ if( pRc ) *pRc = SQLITE_NOMEM;
+ return 0;
+ }
+ pOut->nVertex = 4;
+ ii = 1;
+ pOut->hdr[0] = *(unsigned char*)&ii;
+ pOut->hdr[1] = 0;
+ pOut->hdr[2] = 0;
+ pOut->hdr[3] = 4;
+ GeoX(pOut,0) = mnX;
+ GeoY(pOut,0) = mnY;
+ GeoX(pOut,1) = mxX;
+ GeoY(pOut,1) = mnY;
+ GeoX(pOut,2) = mxX;
+ GeoY(pOut,2) = mxY;
+ GeoX(pOut,3) = mnX;
+ GeoY(pOut,3) = mxY;
+ }else{
+ sqlite3_free(p);
+ aCoord[0].f = mnX;
+ aCoord[1].f = mxX;
+ aCoord[2].f = mnY;
+ aCoord[3].f = mxY;
+ }
+ }else{
+ memset(aCoord, 0, sizeof(RtreeCoord)*4);
+ }
+ return pOut;
+}
+
+/*
+** Implementation of the geopoly_bbox(X) SQL function.
+*/
+static void geopolyBBoxFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ GeoPoly *p = geopolyBBox(context, argv[0], 0, 0);
+ if( p ){
+ sqlite3_result_blob(context, p->hdr,
+ 4+8*p->nVertex, SQLITE_TRANSIENT);
+ sqlite3_free(p);
+ }
+}
+
+/*
+** State vector for the geopoly_group_bbox() aggregate function.
+*/
+typedef struct GeoBBox GeoBBox;
+struct GeoBBox {
+ int isInit;
+ RtreeCoord a[4];
+};
+
+
+/*
+** Implementation of the geopoly_group_bbox(X) aggregate SQL function.
+*/
+static void geopolyBBoxStep(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ RtreeCoord a[4];
+ int rc = SQLITE_OK;
+ (void)geopolyBBox(context, argv[0], a, &rc);
+ if( rc==SQLITE_OK ){
+ GeoBBox *pBBox;
+ pBBox = (GeoBBox*)sqlite3_aggregate_context(context, sizeof(*pBBox));
+ if( pBBox==0 ) return;
+ if( pBBox->isInit==0 ){
+ pBBox->isInit = 1;
+ memcpy(pBBox->a, a, sizeof(RtreeCoord)*4);
+ }else{
+ if( a[0].f < pBBox->a[0].f ) pBBox->a[0] = a[0];
+ if( a[1].f > pBBox->a[1].f ) pBBox->a[1] = a[1];
+ if( a[2].f < pBBox->a[2].f ) pBBox->a[2] = a[2];
+ if( a[3].f > pBBox->a[3].f ) pBBox->a[3] = a[3];
+ }
+ }
+}
+static void geopolyBBoxFinal(
+ sqlite3_context *context
+){
+ GeoPoly *p;
+ GeoBBox *pBBox;
+ pBBox = (GeoBBox*)sqlite3_aggregate_context(context, 0);
+ if( pBBox==0 ) return;
+ p = geopolyBBox(context, 0, pBBox->a, 0);
+ if( p ){
+ sqlite3_result_blob(context, p->hdr,
+ 4+8*p->nVertex, SQLITE_TRANSIENT);
+ sqlite3_free(p);
+ }
+}
+
+
+/*
+** Determine if point (x0,y0) is beneath line segment (x1,y1)->(x2,y2).
+** Returns:
+**
+** +2 x0,y0 is on the line segement
+**
+** +1 x0,y0 is beneath line segment
+**
+** 0 x0,y0 is not on or beneath the line segment or the line segment
+** is vertical and x0,y0 is not on the line segment
+**
+** The left-most coordinate min(x1,x2) is not considered to be part of
+** the line segment for the purposes of this analysis.
+*/
+static int pointBeneathLine(
+ double x0, double y0,
+ double x1, double y1,
+ double x2, double y2
+){
+ double y;
+ if( x0==x1 && y0==y1 ) return 2;
+ if( x1<x2 ){
+ if( x0<=x1 || x0>x2 ) return 0;
+ }else if( x1>x2 ){
+ if( x0<=x2 || x0>x1 ) return 0;
+ }else{
+ /* Vertical line segment */
+ if( x0!=x1 ) return 0;
+ if( y0<y1 && y0<y2 ) return 0;
+ if( y0>y1 && y0>y2 ) return 0;
+ return 2;
+ }
+ y = y1 + (y2-y1)*(x0-x1)/(x2-x1);
+ if( y0==y ) return 2;
+ if( y0<y ) return 1;
+ return 0;
+}
+
+/*
+** SQL function: geopoly_contains_point(P,X,Y)
+**
+** Return +2 if point X,Y is within polygon P.
+** Return +1 if point X,Y is on the polygon boundary.
+** Return 0 if point X,Y is outside the polygon
+*/
+static void geopolyContainsPointFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
+ double x0 = sqlite3_value_double(argv[1]);
+ double y0 = sqlite3_value_double(argv[2]);
+ int v = 0;
+ int cnt = 0;
+ int ii;
+ if( p1==0 ) return;
+ for(ii=0; ii<p1->nVertex-1; ii++){
+ v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii),
+ GeoX(p1,ii+1),GeoY(p1,ii+1));
+ if( v==2 ) break;
+ cnt += v;
+ }
+ if( v!=2 ){
+ v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii),
+ GeoX(p1,0), GeoY(p1,0));
+ }
+ if( v==2 ){
+ sqlite3_result_int(context, 1);
+ }else if( ((v+cnt)&1)==0 ){
+ sqlite3_result_int(context, 0);
+ }else{
+ sqlite3_result_int(context, 2);
+ }
+ sqlite3_free(p1);
+}
+
+/* Forward declaration */
+static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2);
+
+/*
+** SQL function: geopoly_within(P1,P2)
+**
+** Return +2 if P1 and P2 are the same polygon
+** Return +1 if P2 is contained within P1
+** Return 0 if any part of P2 is on the outside of P1
+**
+*/
+static void geopolyWithinFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
+ GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);
+ if( p1 && p2 ){
+ int x = geopolyOverlap(p1, p2);
+ if( x<0 ){
+ sqlite3_result_error_nomem(context);
+ }else{
+ sqlite3_result_int(context, x==2 ? 1 : x==4 ? 2 : 0);
+ }
+ }
+ sqlite3_free(p1);
+ sqlite3_free(p2);
+}
+
+/* Objects used by the overlap algorihm. */
+typedef struct GeoEvent GeoEvent;
+typedef struct GeoSegment GeoSegment;
+typedef struct GeoOverlap GeoOverlap;
+struct GeoEvent {
+ double x; /* X coordinate at which event occurs */
+ int eType; /* 0 for ADD, 1 for REMOVE */
+ GeoSegment *pSeg; /* The segment to be added or removed */
+ GeoEvent *pNext; /* Next event in the sorted list */
+};
+struct GeoSegment {
+ double C, B; /* y = C*x + B */
+ double y; /* Current y value */
+ float y0; /* Initial y value */
+ unsigned char side; /* 1 for p1, 2 for p2 */
+ unsigned int idx; /* Which segment within the side */
+ GeoSegment *pNext; /* Next segment in a list sorted by y */
+};
+struct GeoOverlap {
+ GeoEvent *aEvent; /* Array of all events */
+ GeoSegment *aSegment; /* Array of all segments */
+ int nEvent; /* Number of events */
+ int nSegment; /* Number of segments */
+};
+
+/*
+** Add a single segment and its associated events.
+*/
+static void geopolyAddOneSegment(
+ GeoOverlap *p,
+ GeoCoord x0,
+ GeoCoord y0,
+ GeoCoord x1,
+ GeoCoord y1,
+ unsigned char side,
+ unsigned int idx
+){
+ GeoSegment *pSeg;
+ GeoEvent *pEvent;
+ if( x0==x1 ) return; /* Ignore vertical segments */
+ if( x0>x1 ){
+ GeoCoord t = x0;
+ x0 = x1;
+ x1 = t;
+ t = y0;
+ y0 = y1;
+ y1 = t;
+ }
+ pSeg = p->aSegment + p->nSegment;
+ p->nSegment++;
+ pSeg->C = (y1-y0)/(x1-x0);
+ pSeg->B = y1 - x1*pSeg->C;
+ pSeg->y0 = y0;
+ pSeg->side = side;
+ pSeg->idx = idx;
+ pEvent = p->aEvent + p->nEvent;
+ p->nEvent++;
+ pEvent->x = x0;
+ pEvent->eType = 0;
+ pEvent->pSeg = pSeg;
+ pEvent = p->aEvent + p->nEvent;
+ p->nEvent++;
+ pEvent->x = x1;
+ pEvent->eType = 1;
+ pEvent->pSeg = pSeg;
+}
+
+
+
+/*
+** Insert all segments and events for polygon pPoly.
+*/
+static void geopolyAddSegments(
+ GeoOverlap *p, /* Add segments to this Overlap object */
+ GeoPoly *pPoly, /* Take all segments from this polygon */
+ unsigned char side /* The side of pPoly */
+){
+ unsigned int i;
+ GeoCoord *x;
+ for(i=0; i<(unsigned)pPoly->nVertex-1; i++){
+ x = &GeoX(pPoly,i);
+ geopolyAddOneSegment(p, x[0], x[1], x[2], x[3], side, i);
+ }
+ x = &GeoX(pPoly,i);
+ geopolyAddOneSegment(p, x[0], x[1], pPoly->a[0], pPoly->a[1], side, i);
+}
+
+/*
+** Merge two lists of sorted events by X coordinate
+*/
+static GeoEvent *geopolyEventMerge(GeoEvent *pLeft, GeoEvent *pRight){
+ GeoEvent head, *pLast;
+ head.pNext = 0;
+ pLast = &head;
+ while( pRight && pLeft ){
+ if( pRight->x <= pLeft->x ){
+ pLast->pNext = pRight;
+ pLast = pRight;
+ pRight = pRight->pNext;
+ }else{
+ pLast->pNext = pLeft;
+ pLast = pLeft;
+ pLeft = pLeft->pNext;
+ }
+ }
+ pLast->pNext = pRight ? pRight : pLeft;
+ return head.pNext;
+}
+
+/*
+** Sort an array of nEvent event objects into a list.
+*/
+static GeoEvent *geopolySortEventsByX(GeoEvent *aEvent, int nEvent){
+ int mx = 0;
+ int i, j;
+ GeoEvent *p;
+ GeoEvent *a[50];
+ for(i=0; i<nEvent; i++){
+ p = &aEvent[i];
+ p->pNext = 0;
+ for(j=0; j<mx && a[j]; j++){
+ p = geopolyEventMerge(a[j], p);
+ a[j] = 0;
+ }
+ a[j] = p;
+ if( j>=mx ) mx = j+1;
+ }
+ p = 0;
+ for(i=0; i<mx; i++){
+ p = geopolyEventMerge(a[i], p);
+ }
+ return p;
+}
+
+/*
+** Merge two lists of sorted segments by Y, and then by C.
+*/
+static GeoSegment *geopolySegmentMerge(GeoSegment *pLeft, GeoSegment *pRight){
+ GeoSegment head, *pLast;
+ head.pNext = 0;
+ pLast = &head;
+ while( pRight && pLeft ){
+ double r = pRight->y - pLeft->y;
+ if( r==0.0 ) r = pRight->C - pLeft->C;
+ if( r<0.0 ){
+ pLast->pNext = pRight;
+ pLast = pRight;
+ pRight = pRight->pNext;
+ }else{
+ pLast->pNext = pLeft;
+ pLast = pLeft;
+ pLeft = pLeft->pNext;
+ }
+ }
+ pLast->pNext = pRight ? pRight : pLeft;
+ return head.pNext;
+}
+
+/*
+** Sort a list of GeoSegments in order of increasing Y and in the event of
+** a tie, increasing C (slope).
+*/
+static GeoSegment *geopolySortSegmentsByYAndC(GeoSegment *pList){
+ int mx = 0;
+ int i;
+ GeoSegment *p;
+ GeoSegment *a[50];
+ while( pList ){
+ p = pList;
+ pList = pList->pNext;
+ p->pNext = 0;
+ for(i=0; i<mx && a[i]; i++){
+ p = geopolySegmentMerge(a[i], p);
+ a[i] = 0;
+ }
+ a[i] = p;
+ if( i>=mx ) mx = i+1;
+ }
+ p = 0;
+ for(i=0; i<mx; i++){
+ p = geopolySegmentMerge(a[i], p);
+ }
+ return p;
+}
+
+/*
+** Determine the overlap between two polygons
+*/
+static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){
+ sqlite3_int64 nVertex = p1->nVertex + p2->nVertex + 2;
+ GeoOverlap *p;
+ sqlite3_int64 nByte;
+ GeoEvent *pThisEvent;
+ double rX;
+ int rc = 0;
+ int needSort = 0;
+ GeoSegment *pActive = 0;
+ GeoSegment *pSeg;
+ unsigned char aOverlap[4];
+
+ nByte = sizeof(GeoEvent)*nVertex*2
+ + sizeof(GeoSegment)*nVertex
+ + sizeof(GeoOverlap);
+ p = sqlite3_malloc64( nByte );
+ if( p==0 ) return -1;
+ p->aEvent = (GeoEvent*)&p[1];
+ p->aSegment = (GeoSegment*)&p->aEvent[nVertex*2];
+ p->nEvent = p->nSegment = 0;
+ geopolyAddSegments(p, p1, 1);
+ geopolyAddSegments(p, p2, 2);
+ pThisEvent = geopolySortEventsByX(p->aEvent, p->nEvent);
+ rX = pThisEvent->x==0.0 ? -1.0 : 0.0;
+ memset(aOverlap, 0, sizeof(aOverlap));
+ while( pThisEvent ){
+ if( pThisEvent->x!=rX ){
+ GeoSegment *pPrev = 0;
+ int iMask = 0;
+ GEODEBUG(("Distinct X: %g\n", pThisEvent->x));
+ rX = pThisEvent->x;
+ if( needSort ){
+ GEODEBUG(("SORT\n"));
+ pActive = geopolySortSegmentsByYAndC(pActive);
+ needSort = 0;
+ }
+ for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
+ if( pPrev ){
+ if( pPrev->y!=pSeg->y ){
+ GEODEBUG(("MASK: %d\n", iMask));
+ aOverlap[iMask] = 1;
+ }
+ }
+ iMask ^= pSeg->side;
+ pPrev = pSeg;
+ }
+ pPrev = 0;
+ for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
+ double y = pSeg->C*rX + pSeg->B;
+ GEODEBUG(("Segment %d.%d %g->%g\n", pSeg->side, pSeg->idx, pSeg->y, y));
+ pSeg->y = y;
+ if( pPrev ){
+ if( pPrev->y>pSeg->y && pPrev->side!=pSeg->side ){
+ rc = 1;
+ GEODEBUG(("Crossing: %d.%d and %d.%d\n",
+ pPrev->side, pPrev->idx,
+ pSeg->side, pSeg->idx));
+ goto geopolyOverlapDone;
+ }else if( pPrev->y!=pSeg->y ){
+ GEODEBUG(("MASK: %d\n", iMask));
+ aOverlap[iMask] = 1;
+ }
+ }
+ iMask ^= pSeg->side;
+ pPrev = pSeg;
+ }
+ }
+ GEODEBUG(("%s %d.%d C=%g B=%g\n",
+ pThisEvent->eType ? "RM " : "ADD",
+ pThisEvent->pSeg->side, pThisEvent->pSeg->idx,
+ pThisEvent->pSeg->C,
+ pThisEvent->pSeg->B));
+ if( pThisEvent->eType==0 ){
+ /* Add a segment */
+ pSeg = pThisEvent->pSeg;
+ pSeg->y = pSeg->y0;
+ pSeg->pNext = pActive;
+ pActive = pSeg;
+ needSort = 1;
+ }else{
+ /* Remove a segment */
+ if( pActive==pThisEvent->pSeg ){
+ pActive = pActive->pNext;
+ }else{
+ for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
+ if( pSeg->pNext==pThisEvent->pSeg ){
+ pSeg->pNext = pSeg->pNext->pNext;
+ break;
+ }
+ }
+ }
+ }
+ pThisEvent = pThisEvent->pNext;
+ }
+ if( aOverlap[3]==0 ){
+ rc = 0;
+ }else if( aOverlap[1]!=0 && aOverlap[2]==0 ){
+ rc = 3;
+ }else if( aOverlap[1]==0 && aOverlap[2]!=0 ){
+ rc = 2;
+ }else if( aOverlap[1]==0 && aOverlap[2]==0 ){
+ rc = 4;
+ }else{
+ rc = 1;
+ }
+
+geopolyOverlapDone:
+ sqlite3_free(p);
+ return rc;
+}
+
+/*
+** SQL function: geopoly_overlap(P1,P2)
+**
+** Determine whether or not P1 and P2 overlap. Return value:
+**
+** 0 The two polygons are disjoint
+** 1 They overlap
+** 2 P1 is completely contained within P2
+** 3 P2 is completely contained within P1
+** 4 P1 and P2 are the same polygon
+** NULL Either P1 or P2 or both are not valid polygons
+*/
+static void geopolyOverlapFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
+ GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);
+ if( p1 && p2 ){
+ int x = geopolyOverlap(p1, p2);
+ if( x<0 ){
+ sqlite3_result_error_nomem(context);
+ }else{
+ sqlite3_result_int(context, x);
+ }
+ }
+ sqlite3_free(p1);
+ sqlite3_free(p2);
+}
+
+/*
+** Enable or disable debugging output
+*/
+static void geopolyDebugFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+#ifdef GEOPOLY_ENABLE_DEBUG
+ geo_debug = sqlite3_value_int(argv[0]);
+#endif
+}
+
+/*
+** This function is the implementation of both the xConnect and xCreate
+** methods of the geopoly virtual table.
+**
+** argv[0] -> module name
+** argv[1] -> database name
+** argv[2] -> table name
+** argv[...] -> column names...
+*/
+static int geopolyInit(
+ sqlite3 *db, /* Database connection */
+ void *pAux, /* One of the RTREE_COORD_* constants */
+ int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
+ sqlite3_vtab **ppVtab, /* OUT: New virtual table */
+ char **pzErr, /* OUT: Error message, if any */
+ int isCreate /* True for xCreate, false for xConnect */
+){
+ int rc = SQLITE_OK;
+ Rtree *pRtree;
+ sqlite3_int64 nDb; /* Length of string argv[1] */
+ sqlite3_int64 nName; /* Length of string argv[2] */
+ sqlite3_str *pSql;
+ char *zSql;
+ int ii;
+
+ sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
+
+ /* Allocate the sqlite3_vtab structure */
+ nDb = strlen(argv[1]);
+ nName = strlen(argv[2]);
+ pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);
+ if( !pRtree ){
+ return SQLITE_NOMEM;
+ }
+ memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
+ pRtree->nBusy = 1;
+ pRtree->base.pModule = &rtreeModule;
+ pRtree->zDb = (char *)&pRtree[1];
+ pRtree->zName = &pRtree->zDb[nDb+1];
+ pRtree->eCoordType = RTREE_COORD_REAL32;
+ pRtree->nDim = 2;
+ pRtree->nDim2 = 4;
+ memcpy(pRtree->zDb, argv[1], nDb);
+ memcpy(pRtree->zName, argv[2], nName);
+
+
+ /* Create/Connect to the underlying relational database schema. If
+ ** that is successful, call sqlite3_declare_vtab() to configure
+ ** the r-tree table schema.
+ */
+ pSql = sqlite3_str_new(db);
+ sqlite3_str_appendf(pSql, "CREATE TABLE x(_shape");
+ pRtree->nAux = 1; /* Add one for _shape */
+ pRtree->nAuxNotNull = 1; /* The _shape column is always not-null */
+ for(ii=3; ii<argc; ii++){
+ pRtree->nAux++;
+ sqlite3_str_appendf(pSql, ",%s", argv[ii]);
+ }
+ sqlite3_str_appendf(pSql, ");");
+ zSql = sqlite3_str_finish(pSql);
+ if( !zSql ){
+ rc = SQLITE_NOMEM;
+ }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
+ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
+ }
+ sqlite3_free(zSql);
+ if( rc ) goto geopolyInit_fail;
+ pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
+
+ /* Figure out the node size to use. */
+ rc = getNodeSize(db, pRtree, isCreate, pzErr);
+ if( rc ) goto geopolyInit_fail;
+ rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
+ if( rc ){
+ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
+ goto geopolyInit_fail;
+ }
+
+ *ppVtab = (sqlite3_vtab *)pRtree;
+ return SQLITE_OK;
+
+geopolyInit_fail:
+ if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
+ assert( *ppVtab==0 );
+ assert( pRtree->nBusy==1 );
+ rtreeRelease(pRtree);
+ return rc;
+}
+
+
+/*
+** GEOPOLY virtual table module xCreate method.
+*/
+static int geopolyCreate(
+ sqlite3 *db,
+ void *pAux,
+ int argc, const char *const*argv,
+ sqlite3_vtab **ppVtab,
+ char **pzErr
+){
+ return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
+}
+
+/*
+** GEOPOLY virtual table module xConnect method.
+*/
+static int geopolyConnect(
+ sqlite3 *db,
+ void *pAux,
+ int argc, const char *const*argv,
+ sqlite3_vtab **ppVtab,
+ char **pzErr
+){
+ return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
+}
+
+
+/*
+** GEOPOLY virtual table module xFilter method.
+**
+** Query plans:
+**
+** 1 rowid lookup
+** 2 search for objects overlapping the same bounding box
+** that contains polygon argv[0]
+** 3 search for objects overlapping the same bounding box
+** that contains polygon argv[0]
+** 4 full table scan
+*/
+static int geopolyFilter(
+ sqlite3_vtab_cursor *pVtabCursor, /* The cursor to initialize */
+ int idxNum, /* Query plan */
+ const char *idxStr, /* Not Used */
+ int argc, sqlite3_value **argv /* Parameters to the query plan */
+){
+ Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
+ RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
+ RtreeNode *pRoot = 0;
+ int rc = SQLITE_OK;
+ int iCell = 0;
+
+ rtreeReference(pRtree);
+
+ /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
+ resetCursor(pCsr);
+
+ pCsr->iStrategy = idxNum;
+ if( idxNum==1 ){
+ /* Special case - lookup by rowid. */
+ RtreeNode *pLeaf; /* Leaf on which the required cell resides */
+ RtreeSearchPoint *p; /* Search point for the leaf */
+ i64 iRowid = sqlite3_value_int64(argv[0]);
+ i64 iNode = 0;
+ rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
+ if( rc==SQLITE_OK && pLeaf!=0 ){
+ p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
+ assert( p!=0 ); /* Always returns pCsr->sPoint */
+ pCsr->aNode[0] = pLeaf;
+ p->id = iNode;
+ p->eWithin = PARTLY_WITHIN;
+ rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
+ p->iCell = (u8)iCell;
+ RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
+ }else{
+ pCsr->atEOF = 1;
+ }
+ }else{
+ /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
+ ** with the configured constraints.
+ */
+ rc = nodeAcquire(pRtree, 1, 0, &pRoot);
+ if( rc==SQLITE_OK && idxNum<=3 ){
+ RtreeCoord bbox[4];
+ RtreeConstraint *p;
+ assert( argc==1 );
+ geopolyBBox(0, argv[0], bbox, &rc);
+ if( rc ){
+ goto geopoly_filter_end;
+ }
+ pCsr->aConstraint = p = sqlite3_malloc(sizeof(RtreeConstraint)*4);
+ pCsr->nConstraint = 4;
+ if( p==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*4);
+ memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
+ if( idxNum==2 ){
+ /* Overlap query */
+ p->op = 'B';
+ p->iCoord = 0;
+ p->u.rValue = bbox[1].f;
+ p++;
+ p->op = 'D';
+ p->iCoord = 1;
+ p->u.rValue = bbox[0].f;
+ p++;
+ p->op = 'B';
+ p->iCoord = 2;
+ p->u.rValue = bbox[3].f;
+ p++;
+ p->op = 'D';
+ p->iCoord = 3;
+ p->u.rValue = bbox[2].f;
+ }else{
+ /* Within query */
+ p->op = 'D';
+ p->iCoord = 0;
+ p->u.rValue = bbox[0].f;
+ p++;
+ p->op = 'B';
+ p->iCoord = 1;
+ p->u.rValue = bbox[1].f;
+ p++;
+ p->op = 'D';
+ p->iCoord = 2;
+ p->u.rValue = bbox[2].f;
+ p++;
+ p->op = 'B';
+ p->iCoord = 3;
+ p->u.rValue = bbox[3].f;
+ }
+ }
+ }
+ if( rc==SQLITE_OK ){
+ RtreeSearchPoint *pNew;
+ pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
+ if( pNew==0 ){
+ rc = SQLITE_NOMEM;
+ goto geopoly_filter_end;
+ }
+ pNew->id = 1;
+ pNew->iCell = 0;
+ pNew->eWithin = PARTLY_WITHIN;
+ assert( pCsr->bPoint==1 );
+ pCsr->aNode[0] = pRoot;
+ pRoot = 0;
+ RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
+ rc = rtreeStepToLeaf(pCsr);
+ }
+ }
+
+geopoly_filter_end:
+ nodeRelease(pRtree, pRoot);
+ rtreeRelease(pRtree);
+ return rc;
+}
+
+/*
+** Rtree virtual table module xBestIndex method. There are three
+** table scan strategies to choose from (in order from most to
+** least desirable):
+**
+** idxNum idxStr Strategy
+** ------------------------------------------------
+** 1 "rowid" Direct lookup by rowid.
+** 2 "rtree" R-tree overlap query using geopoly_overlap()
+** 3 "rtree" R-tree within query using geopoly_within()
+** 4 "fullscan" full-table scan.
+** ------------------------------------------------
+*/
+static int geopolyBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
+ int ii;
+ int iRowidTerm = -1;
+ int iFuncTerm = -1;
+ int idxNum = 0;
+
+ for(ii=0; ii<pIdxInfo->nConstraint; ii++){
+ struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
+ if( !p->usable ) continue;
+ if( p->iColumn<0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
+ iRowidTerm = ii;
+ break;
+ }
+ if( p->iColumn==0 && p->op>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
+ /* p->op==SQLITE_INDEX_CONSTRAINT_FUNCTION for geopoly_overlap()
+ ** p->op==(SQLITE_INDEX_CONTRAINT_FUNCTION+1) for geopoly_within().
+ ** See geopolyFindFunction() */
+ iFuncTerm = ii;
+ idxNum = p->op - SQLITE_INDEX_CONSTRAINT_FUNCTION + 2;
+ }
+ }
+
+ if( iRowidTerm>=0 ){
+ pIdxInfo->idxNum = 1;
+ pIdxInfo->idxStr = "rowid";
+ pIdxInfo->aConstraintUsage[iRowidTerm].argvIndex = 1;
+ pIdxInfo->aConstraintUsage[iRowidTerm].omit = 1;
+ pIdxInfo->estimatedCost = 30.0;
+ pIdxInfo->estimatedRows = 1;
+ pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
+ return SQLITE_OK;
+ }
+ if( iFuncTerm>=0 ){
+ pIdxInfo->idxNum = idxNum;
+ pIdxInfo->idxStr = "rtree";
+ pIdxInfo->aConstraintUsage[iFuncTerm].argvIndex = 1;
+ pIdxInfo->aConstraintUsage[iFuncTerm].omit = 0;
+ pIdxInfo->estimatedCost = 300.0;
+ pIdxInfo->estimatedRows = 10;
+ return SQLITE_OK;
+ }
+ pIdxInfo->idxNum = 4;
+ pIdxInfo->idxStr = "fullscan";
+ pIdxInfo->estimatedCost = 3000000.0;
+ pIdxInfo->estimatedRows = 100000;
+ return SQLITE_OK;
+}
+
+
+/*
+** GEOPOLY virtual table module xColumn method.
+*/
+static int geopolyColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
+ Rtree *pRtree = (Rtree *)cur->pVtab;
+ RtreeCursor *pCsr = (RtreeCursor *)cur;
+ RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
+ int rc = SQLITE_OK;
+ RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
+
+ if( rc ) return rc;
+ if( p==0 ) return SQLITE_OK;
+ if( i==0 && sqlite3_vtab_nochange(ctx) ) return SQLITE_OK;
+ if( i<=pRtree->nAux ){
+ if( !pCsr->bAuxValid ){
+ if( pCsr->pReadAux==0 ){
+ rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
+ &pCsr->pReadAux, 0);
+ if( rc ) return rc;
+ }
+ sqlite3_bind_int64(pCsr->pReadAux, 1,
+ nodeGetRowid(pRtree, pNode, p->iCell));
+ rc = sqlite3_step(pCsr->pReadAux);
+ if( rc==SQLITE_ROW ){
+ pCsr->bAuxValid = 1;
+ }else{
+ sqlite3_reset(pCsr->pReadAux);
+ if( rc==SQLITE_DONE ) rc = SQLITE_OK;
+ return rc;
+ }
+ }
+ sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pReadAux, i+2));
+ }
+ return SQLITE_OK;
+}
+
+
+/*
+** The xUpdate method for GEOPOLY module virtual tables.
+**
+** For DELETE:
+**
+** argv[0] = the rowid to be deleted
+**
+** For INSERT:
+**
+** argv[0] = SQL NULL
+** argv[1] = rowid to insert, or an SQL NULL to select automatically
+** argv[2] = _shape column
+** argv[3] = first application-defined column....
+**
+** For UPDATE:
+**
+** argv[0] = rowid to modify. Never NULL
+** argv[1] = rowid after the change. Never NULL
+** argv[2] = new value for _shape
+** argv[3] = new value for first application-defined column....
+*/
+static int geopolyUpdate(
+ sqlite3_vtab *pVtab,
+ int nData,
+ sqlite3_value **aData,
+ sqlite_int64 *pRowid
+){
+ Rtree *pRtree = (Rtree *)pVtab;
+ int rc = SQLITE_OK;
+ RtreeCell cell; /* New cell to insert if nData>1 */
+ i64 oldRowid; /* The old rowid */
+ int oldRowidValid; /* True if oldRowid is valid */
+ i64 newRowid; /* The new rowid */
+ int newRowidValid; /* True if newRowid is valid */
+ int coordChange = 0; /* Change in coordinates */
+
+ if( pRtree->nNodeRef ){
+ /* Unable to write to the btree while another cursor is reading from it,
+ ** since the write might do a rebalance which would disrupt the read
+ ** cursor. */
+ return SQLITE_LOCKED_VTAB;
+ }
+ rtreeReference(pRtree);
+ assert(nData>=1);
+
+ oldRowidValid = sqlite3_value_type(aData[0])!=SQLITE_NULL;;
+ oldRowid = oldRowidValid ? sqlite3_value_int64(aData[0]) : 0;
+ newRowidValid = nData>1 && sqlite3_value_type(aData[1])!=SQLITE_NULL;
+ newRowid = newRowidValid ? sqlite3_value_int64(aData[1]) : 0;
+ cell.iRowid = newRowid;
+
+ if( nData>1 /* not a DELETE */
+ && (!oldRowidValid /* INSERT */
+ || !sqlite3_value_nochange(aData[2]) /* UPDATE _shape */
+ || oldRowid!=newRowid) /* Rowid change */
+ ){
+ geopolyBBox(0, aData[2], cell.aCoord, &rc);
+ if( rc ){
+ if( rc==SQLITE_ERROR ){
+ pVtab->zErrMsg =
+ sqlite3_mprintf("_shape does not contain a valid polygon");
+ }
+ goto geopoly_update_end;
+ }
+ coordChange = 1;
+
+ /* If a rowid value was supplied, check if it is already present in
+ ** the table. If so, the constraint has failed. */
+ if( newRowidValid && (!oldRowidValid || oldRowid!=newRowid) ){
+ int steprc;
+ sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
+ steprc = sqlite3_step(pRtree->pReadRowid);
+ rc = sqlite3_reset(pRtree->pReadRowid);
+ if( SQLITE_ROW==steprc ){
+ if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
+ rc = rtreeDeleteRowid(pRtree, cell.iRowid);
+ }else{
+ rc = rtreeConstraintError(pRtree, 0);
+ }
+ }
+ }
+ }
+
+ /* If aData[0] is not an SQL NULL value, it is the rowid of a
+ ** record to delete from the r-tree table. The following block does
+ ** just that.
+ */
+ if( rc==SQLITE_OK && (nData==1 || (coordChange && oldRowidValid)) ){
+ rc = rtreeDeleteRowid(pRtree, oldRowid);
+ }
+
+ /* If the aData[] array contains more than one element, elements
+ ** (aData[2]..aData[argc-1]) contain a new record to insert into
+ ** the r-tree structure.
+ */
+ if( rc==SQLITE_OK && nData>1 && coordChange ){
+ /* Insert the new record into the r-tree */
+ RtreeNode *pLeaf = 0;
+ if( !newRowidValid ){
+ rc = rtreeNewRowid(pRtree, &cell.iRowid);
+ }
+ *pRowid = cell.iRowid;
+ if( rc==SQLITE_OK ){
+ rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
+ }
+ if( rc==SQLITE_OK ){
+ int rc2;
+ pRtree->iReinsertHeight = -1;
+ rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
+ rc2 = nodeRelease(pRtree, pLeaf);
+ if( rc==SQLITE_OK ){
+ rc = rc2;
+ }
+ }
+ }
+
+ /* Change the data */
+ if( rc==SQLITE_OK && nData>1 ){
+ sqlite3_stmt *pUp = pRtree->pWriteAux;
+ int jj;
+ int nChange = 0;
+ sqlite3_bind_int64(pUp, 1, cell.iRowid);
+ assert( pRtree->nAux>=1 );
+ if( sqlite3_value_nochange(aData[2]) ){
+ sqlite3_bind_null(pUp, 2);
+ }else{
+ GeoPoly *p = 0;
+ if( sqlite3_value_type(aData[2])==SQLITE_TEXT
+ && (p = geopolyFuncParam(0, aData[2], &rc))!=0
+ && rc==SQLITE_OK
+ ){
+ sqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex, SQLITE_TRANSIENT);
+ }else{
+ sqlite3_bind_value(pUp, 2, aData[2]);
+ }
+ sqlite3_free(p);
+ nChange = 1;
+ }
+ for(jj=1; jj<pRtree->nAux; jj++){
+ nChange++;
+ sqlite3_bind_value(pUp, jj+2, aData[jj+2]);
+ }
+ if( nChange ){
+ sqlite3_step(pUp);
+ rc = sqlite3_reset(pUp);
+ }
+ }
+
+geopoly_update_end:
+ rtreeRelease(pRtree);
+ return rc;
+}
+
+/*
+** Report that geopoly_overlap() is an overloaded function suitable
+** for use in xBestIndex.
+*/
+static int geopolyFindFunction(
+ sqlite3_vtab *pVtab,
+ int nArg,
+ const char *zName,
+ void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
+ void **ppArg
+){
+ if( sqlite3_stricmp(zName, "geopoly_overlap")==0 ){
+ *pxFunc = geopolyOverlapFunc;
+ *ppArg = 0;
+ return SQLITE_INDEX_CONSTRAINT_FUNCTION;
+ }
+ if( sqlite3_stricmp(zName, "geopoly_within")==0 ){
+ *pxFunc = geopolyWithinFunc;
+ *ppArg = 0;
+ return SQLITE_INDEX_CONSTRAINT_FUNCTION+1;
+ }
+ return 0;
+}
+
+
+static sqlite3_module geopolyModule = {
+ 3, /* iVersion */
+ geopolyCreate, /* xCreate - create a table */
+ geopolyConnect, /* xConnect - connect to an existing table */
+ geopolyBestIndex, /* xBestIndex - Determine search strategy */
+ rtreeDisconnect, /* xDisconnect - Disconnect from a table */
+ rtreeDestroy, /* xDestroy - Drop a table */
+ rtreeOpen, /* xOpen - open a cursor */
+ rtreeClose, /* xClose - close a cursor */
+ geopolyFilter, /* xFilter - configure scan constraints */
+ rtreeNext, /* xNext - advance a cursor */
+ rtreeEof, /* xEof */
+ geopolyColumn, /* xColumn - read data */
+ rtreeRowid, /* xRowid - read data */
+ geopolyUpdate, /* xUpdate - write data */
+ rtreeBeginTransaction, /* xBegin - begin transaction */
+ rtreeEndTransaction, /* xSync - sync transaction */
+ rtreeEndTransaction, /* xCommit - commit transaction */
+ rtreeEndTransaction, /* xRollback - rollback transaction */
+ geopolyFindFunction, /* xFindFunction - function overloading */
+ rtreeRename, /* xRename - rename the table */
+ rtreeSavepoint, /* xSavepoint */
+ 0, /* xRelease */
+ 0, /* xRollbackTo */
+ rtreeShadowName /* xShadowName */
+};
+
+static int sqlite3_geopoly_init(sqlite3 *db){
+ int rc = SQLITE_OK;
+ static const struct {
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
+ signed char nArg;
+ unsigned char bPure;
+ const char *zName;
+ } aFunc[] = {
+ { geopolyAreaFunc, 1, 1, "geopoly_area" },
+ { geopolyBlobFunc, 1, 1, "geopoly_blob" },
+ { geopolyJsonFunc, 1, 1, "geopoly_json" },
+ { geopolySvgFunc, -1, 1, "geopoly_svg" },
+ { geopolyWithinFunc, 2, 1, "geopoly_within" },
+ { geopolyContainsPointFunc, 3, 1, "geopoly_contains_point" },
+ { geopolyOverlapFunc, 2, 1, "geopoly_overlap" },
+ { geopolyDebugFunc, 1, 0, "geopoly_debug" },
+ { geopolyBBoxFunc, 1, 1, "geopoly_bbox" },
+ { geopolyXformFunc, 7, 1, "geopoly_xform" },
+ { geopolyRegularFunc, 4, 1, "geopoly_regular" },
+ { geopolyCcwFunc, 1, 1, "geopoly_ccw" },
+ };
+ static const struct {
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**);
+ void (*xFinal)(sqlite3_context*);
+ const char *zName;
+ } aAgg[] = {
+ { geopolyBBoxStep, geopolyBBoxFinal, "geopoly_group_bbox" },
+ };
+ int i;
+ for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
+ int enc;
+ if( aFunc[i].bPure ){
+ enc = SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS;
+ }else{
+ enc = SQLITE_UTF8|SQLITE_DIRECTONLY;
+ }
+ rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
+ enc, 0,
+ aFunc[i].xFunc, 0, 0);
+ }
+ for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
+ rc = sqlite3_create_function(db, aAgg[i].zName, 1,
+ SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS, 0,
+ 0, aAgg[i].xStep, aAgg[i].xFinal);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_create_module_v2(db, "geopoly", &geopolyModule, 0, 0);
+ }
+ return rc;
+}
+
+/************** End of geopoly.c *********************************************/
+/************** Continuing where we left off in rtree.c **********************/
+#endif
+
+/*
+** Register the r-tree module with database handle db. This creates the
+** virtual table module "rtree" and the debugging/analysis scalar
+** function "rtreenode".
+*/
+SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
+ const int utf8 = SQLITE_UTF8;
+ int rc;
+
+ rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
+ }
+ if( rc==SQLITE_OK ){
+#ifdef SQLITE_RTREE_INT_ONLY
+ void *c = (void *)RTREE_COORD_INT32;
+#else
+ void *c = (void *)RTREE_COORD_REAL32;
+#endif
+ rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
+ }
+ if( rc==SQLITE_OK ){
+ void *c = (void *)RTREE_COORD_INT32;
+ rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
+ }
+#ifdef SQLITE_ENABLE_GEOPOLY
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_geopoly_init(db);
+ }
+#endif
+
+ return rc;
+}
+
+/*
+** This routine deletes the RtreeGeomCallback object that was attached
+** one of the SQL functions create by sqlite3_rtree_geometry_callback()
+** or sqlite3_rtree_query_callback(). In other words, this routine is the
+** destructor for an RtreeGeomCallback objecct. This routine is called when
+** the corresponding SQL function is deleted.
+*/
+static void rtreeFreeCallback(void *p){
+ RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
+ if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
+ sqlite3_free(p);
+}
+
+/*
+** This routine frees the BLOB that is returned by geomCallback().
+*/
+static void rtreeMatchArgFree(void *pArg){
+ int i;
+ RtreeMatchArg *p = (RtreeMatchArg*)pArg;
+ for(i=0; i<p->nParam; i++){
+ sqlite3_value_free(p->apSqlParam[i]);
+ }
+ sqlite3_free(p);
+}
+
+/*
+** Each call to sqlite3_rtree_geometry_callback() or
+** sqlite3_rtree_query_callback() creates an ordinary SQLite
+** scalar function that is implemented by this routine.
+**
+** All this function does is construct an RtreeMatchArg object that
+** contains the geometry-checking callback routines and a list of
+** parameters to this function, then return that RtreeMatchArg object
+** as a BLOB.
+**
+** The R-Tree MATCH operator will read the returned BLOB, deserialize
+** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
+** out which elements of the R-Tree should be returned by the query.
+*/
+static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
+ RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
+ RtreeMatchArg *pBlob;
+ sqlite3_int64 nBlob;
+ int memErr = 0;
+
+ nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
+ + nArg*sizeof(sqlite3_value*);
+ pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob);
+ if( !pBlob ){
+ sqlite3_result_error_nomem(ctx);
+ }else{
+ int i;
+ pBlob->iSize = nBlob;
+ pBlob->cb = pGeomCtx[0];
+ pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
+ pBlob->nParam = nArg;
+ for(i=0; i<nArg; i++){
+ pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
+ if( pBlob->apSqlParam[i]==0 ) memErr = 1;
+#ifdef SQLITE_RTREE_INT_ONLY
+ pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
+#else
+ pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
+#endif
+ }
+ if( memErr ){
+ sqlite3_result_error_nomem(ctx);
+ rtreeMatchArgFree(pBlob);
+ }else{
+ sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
+ }
+ }
+}
+
+/*
+** Register a new geometry function for use with the r-tree MATCH operator.
+*/
+SQLITE_API int sqlite3_rtree_geometry_callback(
+ sqlite3 *db, /* Register SQL function on this connection */
+ const char *zGeom, /* Name of the new SQL function */
+ int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
+ void *pContext /* Extra data associated with the callback */
+){
+ RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
+
+ /* Allocate and populate the context object. */
+ pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
+ if( !pGeomCtx ) return SQLITE_NOMEM;
+ pGeomCtx->xGeom = xGeom;
+ pGeomCtx->xQueryFunc = 0;
+ pGeomCtx->xDestructor = 0;
+ pGeomCtx->pContext = pContext;
+ return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
+ (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
+ );
+}
+
+/*
+** Register a new 2nd-generation geometry function for use with the
+** r-tree MATCH operator.
+*/
+SQLITE_API int sqlite3_rtree_query_callback(
+ sqlite3 *db, /* Register SQL function on this connection */
+ const char *zQueryFunc, /* Name of new SQL function */
+ int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
+ void *pContext, /* Extra data passed into the callback */
+ void (*xDestructor)(void*) /* Destructor for the extra data */
+){
+ RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
+
+ /* Allocate and populate the context object. */
+ pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
+ if( !pGeomCtx ) return SQLITE_NOMEM;
+ pGeomCtx->xGeom = 0;
+ pGeomCtx->xQueryFunc = xQueryFunc;
+ pGeomCtx->xDestructor = xDestructor;
+ pGeomCtx->pContext = pContext;
+ return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
+ (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
+ );
+}
+
+#if !SQLITE_CORE
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+SQLITE_API int sqlite3_rtree_init(
+ sqlite3 *db,
+ char **pzErrMsg,
+ const sqlite3_api_routines *pApi
+){
+ SQLITE_EXTENSION_INIT2(pApi)
+ return sqlite3RtreeInit(db);
+}
+#endif
+
+#endif
+
+/************** End of rtree.c ***********************************************/
+/************** Begin file icu.c *********************************************/
+/*
+** 2007 May 6
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
+**
+** This file implements an integration between the ICU library
+** ("International Components for Unicode", an open-source library
+** for handling unicode data) and SQLite. The integration uses
+** ICU to provide the following to SQLite:
+**
+** * An implementation of the SQL regexp() function (and hence REGEXP
+** operator) using the ICU uregex_XX() APIs.
+**
+** * Implementations of the SQL scalar upper() and lower() functions
+** for case mapping.
+**
+** * Integration of ICU and SQLite collation sequences.
+**
+** * An implementation of the LIKE operator that uses ICU to
+** provide case-independent matching.
+*/
+
+#if !defined(SQLITE_CORE) \
+ || defined(SQLITE_ENABLE_ICU) \
+ || defined(SQLITE_ENABLE_ICU_COLLATIONS)
+
+/* Include ICU headers */
+#include <unicode/utypes.h>
+#include <unicode/uregex.h>
+#include <unicode/ustring.h>
+#include <unicode/ucol.h>
+
+/* #include <assert.h> */
+
+#ifndef SQLITE_CORE
+/* #include "sqlite3ext.h" */
+ SQLITE_EXTENSION_INIT1
+#else
+/* #include "sqlite3.h" */
+#endif
+
+/*
+** This function is called when an ICU function called from within
+** the implementation of an SQL scalar function returns an error.
+**
+** The scalar function context passed as the first argument is
+** loaded with an error message based on the following two args.
+*/
+static void icuFunctionError(
+ sqlite3_context *pCtx, /* SQLite scalar function context */
+ const char *zName, /* Name of ICU function that failed */
+ UErrorCode e /* Error code returned by ICU function */
+){
+ char zBuf[128];
+ sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
+ zBuf[127] = '\0';
+ sqlite3_result_error(pCtx, zBuf, -1);
+}
+
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
+
+/*
+** Maximum length (in bytes) of the pattern in a LIKE or GLOB
+** operator.
+*/
+#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
+# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
+#endif
+
+/*
+** Version of sqlite3_free() that is always a function, never a macro.
+*/
+static void xFree(void *p){
+ sqlite3_free(p);
+}
+
+/*
+** This lookup table is used to help decode the first byte of
+** a multi-byte UTF8 character. It is copied here from SQLite source
+** code file utf8.c.
+*/
+static const unsigned char icuUtf8Trans1[] = {
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
+ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
+};
+
+#define SQLITE_ICU_READ_UTF8(zIn, c) \
+ c = *(zIn++); \
+ if( c>=0xc0 ){ \
+ c = icuUtf8Trans1[c-0xc0]; \
+ while( (*zIn & 0xc0)==0x80 ){ \
+ c = (c<<6) + (0x3f & *(zIn++)); \
+ } \
+ }
+
+#define SQLITE_ICU_SKIP_UTF8(zIn) \
+ assert( *zIn ); \
+ if( *(zIn++)>=0xc0 ){ \
+ while( (*zIn & 0xc0)==0x80 ){zIn++;} \
+ }
+
+
+/*
+** Compare two UTF-8 strings for equality where the first string is
+** a "LIKE" expression. Return true (1) if they are the same and
+** false (0) if they are different.
+*/
+static int icuLikeCompare(
+ const uint8_t *zPattern, /* LIKE pattern */
+ const uint8_t *zString, /* The UTF-8 string to compare against */
+ const UChar32 uEsc /* The escape character */
+){
+ static const uint32_t MATCH_ONE = (uint32_t)'_';
+ static const uint32_t MATCH_ALL = (uint32_t)'%';
+
+ int prevEscape = 0; /* True if the previous character was uEsc */
+
+ while( 1 ){
+
+ /* Read (and consume) the next character from the input pattern. */
+ uint32_t uPattern;
+ SQLITE_ICU_READ_UTF8(zPattern, uPattern);
+ if( uPattern==0 ) break;
+
+ /* There are now 4 possibilities:
+ **
+ ** 1. uPattern is an unescaped match-all character "%",
+ ** 2. uPattern is an unescaped match-one character "_",
+ ** 3. uPattern is an unescaped escape character, or
+ ** 4. uPattern is to be handled as an ordinary character
+ */
+ if( uPattern==MATCH_ALL && !prevEscape && uPattern!=(uint32_t)uEsc ){
+ /* Case 1. */
+ uint8_t c;
+
+ /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
+ ** MATCH_ALL. For each MATCH_ONE, skip one character in the
+ ** test string.
+ */
+ while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
+ if( c==MATCH_ONE ){
+ if( *zString==0 ) return 0;
+ SQLITE_ICU_SKIP_UTF8(zString);
+ }
+ zPattern++;
+ }
+
+ if( *zPattern==0 ) return 1;
+
+ while( *zString ){
+ if( icuLikeCompare(zPattern, zString, uEsc) ){
+ return 1;
+ }
+ SQLITE_ICU_SKIP_UTF8(zString);
+ }
+ return 0;
+
+ }else if( uPattern==MATCH_ONE && !prevEscape && uPattern!=(uint32_t)uEsc ){
+ /* Case 2. */
+ if( *zString==0 ) return 0;
+ SQLITE_ICU_SKIP_UTF8(zString);
+
+ }else if( uPattern==(uint32_t)uEsc && !prevEscape ){
+ /* Case 3. */
+ prevEscape = 1;
+
+ }else{
+ /* Case 4. */
+ uint32_t uString;
+ SQLITE_ICU_READ_UTF8(zString, uString);
+ uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);
+ uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);
+ if( uString!=uPattern ){
+ return 0;
+ }
+ prevEscape = 0;
+ }
+ }
+
+ return *zString==0;
+}
+
+/*
+** Implementation of the like() SQL function. This function implements
+** the build-in LIKE operator. The first argument to the function is the
+** pattern and the second argument is the string. So, the SQL statements:
+**
+** A LIKE B
+**
+** is implemented as like(B, A). If there is an escape character E,
+**
+** A LIKE B ESCAPE E
+**
+** is mapped to like(B, A, E).
+*/
+static void icuLikeFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ const unsigned char *zA = sqlite3_value_text(argv[0]);
+ const unsigned char *zB = sqlite3_value_text(argv[1]);
+ UChar32 uEsc = 0;
+
+ /* Limit the length of the LIKE or GLOB pattern to avoid problems
+ ** of deep recursion and N*N behavior in patternCompare().
+ */
+ if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
+ sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
+ return;
+ }
+
+
+ if( argc==3 ){
+ /* The escape character string must consist of a single UTF-8 character.
+ ** Otherwise, return an error.
+ */
+ int nE= sqlite3_value_bytes(argv[2]);
+ const unsigned char *zE = sqlite3_value_text(argv[2]);
+ int i = 0;
+ if( zE==0 ) return;
+ U8_NEXT(zE, i, nE, uEsc);
+ if( i!=nE){
+ sqlite3_result_error(context,
+ "ESCAPE expression must be a single character", -1);
+ return;
+ }
+ }
+
+ if( zA && zB ){
+ sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
+ }
+}
+
+/*
+** Function to delete compiled regexp objects. Registered as
+** a destructor function with sqlite3_set_auxdata().
+*/
+static void icuRegexpDelete(void *p){
+ URegularExpression *pExpr = (URegularExpression *)p;
+ uregex_close(pExpr);
+}
+
+/*
+** Implementation of SQLite REGEXP operator. This scalar function takes
+** two arguments. The first is a regular expression pattern to compile
+** the second is a string to match against that pattern. If either
+** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
+** is 1 if the string matches the pattern, or 0 otherwise.
+**
+** SQLite maps the regexp() function to the regexp() operator such
+** that the following two are equivalent:
+**
+** zString REGEXP zPattern
+** regexp(zPattern, zString)
+**
+** Uses the following ICU regexp APIs:
+**
+** uregex_open()
+** uregex_matches()
+** uregex_close()
+*/
+static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
+ UErrorCode status = U_ZERO_ERROR;
+ URegularExpression *pExpr;
+ UBool res;
+ const UChar *zString = sqlite3_value_text16(apArg[1]);
+
+ (void)nArg; /* Unused parameter */
+
+ /* If the left hand side of the regexp operator is NULL,
+ ** then the result is also NULL.
+ */
+ if( !zString ){
+ return;
+ }
+
+ pExpr = sqlite3_get_auxdata(p, 0);
+ if( !pExpr ){
+ const UChar *zPattern = sqlite3_value_text16(apArg[0]);
+ if( !zPattern ){
+ return;
+ }
+ pExpr = uregex_open(zPattern, -1, 0, 0, &status);
+
+ if( U_SUCCESS(status) ){
+ sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
+ }else{
+ assert(!pExpr);
+ icuFunctionError(p, "uregex_open", status);
+ return;
+ }
+ }
+
+ /* Configure the text that the regular expression operates on. */
+ uregex_setText(pExpr, zString, -1, &status);
+ if( !U_SUCCESS(status) ){
+ icuFunctionError(p, "uregex_setText", status);
+ return;
+ }
+
+ /* Attempt the match */
+ res = uregex_matches(pExpr, 0, &status);
+ if( !U_SUCCESS(status) ){
+ icuFunctionError(p, "uregex_matches", status);
+ return;
+ }
+
+ /* Set the text that the regular expression operates on to a NULL
+ ** pointer. This is not really necessary, but it is tidier than
+ ** leaving the regular expression object configured with an invalid
+ ** pointer after this function returns.
+ */
+ uregex_setText(pExpr, 0, 0, &status);
+
+ /* Return 1 or 0. */
+ sqlite3_result_int(p, res ? 1 : 0);
+}
+
+/*
+** Implementations of scalar functions for case mapping - upper() and
+** lower(). Function upper() converts its input to upper-case (ABC).
+** Function lower() converts to lower-case (abc).
+**
+** ICU provides two types of case mapping, "general" case mapping and
+** "language specific". Refer to ICU documentation for the differences
+** between the two.
+**
+** To utilise "general" case mapping, the upper() or lower() scalar
+** functions are invoked with one argument:
+**
+** upper('ABC') -> 'abc'
+** lower('abc') -> 'ABC'
+**
+** To access ICU "language specific" case mapping, upper() or lower()
+** should be invoked with two arguments. The second argument is the name
+** of the locale to use. Passing an empty string ("") or SQL NULL value
+** as the second argument is the same as invoking the 1 argument version
+** of upper() or lower().
+**
+** lower('I', 'en_us') -> 'i'
+** lower('I', 'tr_tr') -> '\u131' (small dotless i)
+**
+** http://www.icu-project.org/userguide/posix.html#case_mappings
+*/
+static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
+ const UChar *zInput; /* Pointer to input string */
+ UChar *zOutput = 0; /* Pointer to output buffer */
+ int nInput; /* Size of utf-16 input string in bytes */
+ int nOut; /* Size of output buffer in bytes */
+ int cnt;
+ int bToUpper; /* True for toupper(), false for tolower() */
+ UErrorCode status;
+ const char *zLocale = 0;
+
+ assert(nArg==1 || nArg==2);
+ bToUpper = (sqlite3_user_data(p)!=0);
+ if( nArg==2 ){
+ zLocale = (const char *)sqlite3_value_text(apArg[1]);
+ }
+
+ zInput = sqlite3_value_text16(apArg[0]);
+ if( !zInput ){
+ return;
+ }
+ nOut = nInput = sqlite3_value_bytes16(apArg[0]);
+ if( nOut==0 ){
+ sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
+ return;
+ }
+
+ for(cnt=0; cnt<2; cnt++){
+ UChar *zNew = sqlite3_realloc(zOutput, nOut);
+ if( zNew==0 ){
+ sqlite3_free(zOutput);
+ sqlite3_result_error_nomem(p);
+ return;
+ }
+ zOutput = zNew;
+ status = U_ZERO_ERROR;
+ if( bToUpper ){
+ nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
+ }else{
+ nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
+ }
+
+ if( U_SUCCESS(status) ){
+ sqlite3_result_text16(p, zOutput, nOut, xFree);
+ }else if( status==U_BUFFER_OVERFLOW_ERROR ){
+ assert( cnt==0 );
+ continue;
+ }else{
+ icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
+ }
+ return;
+ }
+ assert( 0 ); /* Unreachable */
+}
+
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
+
+/*
+** Collation sequence destructor function. The pCtx argument points to
+** a UCollator structure previously allocated using ucol_open().
+*/
+static void icuCollationDel(void *pCtx){
+ UCollator *p = (UCollator *)pCtx;
+ ucol_close(p);
+}
+
+/*
+** Collation sequence comparison function. The pCtx argument points to
+** a UCollator structure previously allocated using ucol_open().
+*/
+static int icuCollationColl(
+ void *pCtx,
+ int nLeft,
+ const void *zLeft,
+ int nRight,
+ const void *zRight
+){
+ UCollationResult res;
+ UCollator *p = (UCollator *)pCtx;
+ res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
+ switch( res ){
+ case UCOL_LESS: return -1;
+ case UCOL_GREATER: return +1;
+ case UCOL_EQUAL: return 0;
+ }
+ assert(!"Unexpected return value from ucol_strcoll()");
+ return 0;
+}
+
+/*
+** Implementation of the scalar function icu_load_collation().
+**
+** This scalar function is used to add ICU collation based collation
+** types to an SQLite database connection. It is intended to be called
+** as follows:
+**
+** SELECT icu_load_collation(<locale>, <collation-name>);
+**
+** Where <locale> is a string containing an ICU locale identifier (i.e.
+** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
+** collation sequence to create.
+*/
+static void icuLoadCollation(
+ sqlite3_context *p,
+ int nArg,
+ sqlite3_value **apArg
+){
+ sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
+ UErrorCode status = U_ZERO_ERROR;
+ const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
+ const char *zName; /* SQL Collation sequence name (eg. "japanese") */
+ UCollator *pUCollator; /* ICU library collation object */
+ int rc; /* Return code from sqlite3_create_collation_x() */
+
+ assert(nArg==2);
+ (void)nArg; /* Unused parameter */
+ zLocale = (const char *)sqlite3_value_text(apArg[0]);
+ zName = (const char *)sqlite3_value_text(apArg[1]);
+
+ if( !zLocale || !zName ){
+ return;
+ }
+
+ pUCollator = ucol_open(zLocale, &status);
+ if( !U_SUCCESS(status) ){
+ icuFunctionError(p, "ucol_open", status);
+ return;
+ }
+ assert(p);
+
+ rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
+ icuCollationColl, icuCollationDel
+ );
+ if( rc!=SQLITE_OK ){
+ ucol_close(pUCollator);
+ sqlite3_result_error(p, "Error registering collation function", -1);
+ }
+}
+
+/*
+** Register the ICU extension functions with database db.
+*/
+SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
+# define SQLITEICU_EXTRAFLAGS (SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS)
+ static const struct IcuScalar {
+ const char *zName; /* Function name */
+ unsigned char nArg; /* Number of arguments */
+ unsigned int enc; /* Optimal text encoding */
+ unsigned char iContext; /* sqlite3_user_data() context */
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
+ } scalars[] = {
+ {"icu_load_collation",2,SQLITE_UTF8|SQLITE_DIRECTONLY,1, icuLoadCollation},
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
+ {"regexp", 2, SQLITE_ANY|SQLITEICU_EXTRAFLAGS, 0, icuRegexpFunc},
+ {"lower", 1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16},
+ {"lower", 2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16},
+ {"upper", 1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16},
+ {"upper", 2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16},
+ {"lower", 1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16},
+ {"lower", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16},
+ {"upper", 1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16},
+ {"upper", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16},
+ {"like", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuLikeFunc},
+ {"like", 3, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuLikeFunc},
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
+ };
+ int rc = SQLITE_OK;
+ int i;
+
+ for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
+ const struct IcuScalar *p = &scalars[i];
+ rc = sqlite3_create_function(
+ db, p->zName, p->nArg, p->enc,
+ p->iContext ? (void*)db : (void*)0,
+ p->xFunc, 0, 0
+ );
+ }
+
+ return rc;
+}
+
+#if !SQLITE_CORE
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+SQLITE_API int sqlite3_icu_init(
+ sqlite3 *db,
+ char **pzErrMsg,
+ const sqlite3_api_routines *pApi
+){
+ SQLITE_EXTENSION_INIT2(pApi)
+ return sqlite3IcuInit(db);
+}
+#endif
+
+#endif
+
+/************** End of icu.c *************************************************/
+/************** Begin file fts3_icu.c ****************************************/
+/*
+** 2007 June 22
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file implements a tokenizer for fts3 based on the ICU library.
+*/
+/* #include "fts3Int.h" */
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
+#ifdef SQLITE_ENABLE_ICU
+
+/* #include <assert.h> */
+/* #include <string.h> */
+/* #include "fts3_tokenizer.h" */
+
+#include <unicode/ubrk.h>
+/* #include <unicode/ucol.h> */
+/* #include <unicode/ustring.h> */
+#include <unicode/utf16.h>
+
+typedef struct IcuTokenizer IcuTokenizer;
+typedef struct IcuCursor IcuCursor;
+
+struct IcuTokenizer {
+ sqlite3_tokenizer base;
+ char *zLocale;
+};
+
+struct IcuCursor {
+ sqlite3_tokenizer_cursor base;
+
+ UBreakIterator *pIter; /* ICU break-iterator object */
+ int nChar; /* Number of UChar elements in pInput */
+ UChar *aChar; /* Copy of input using utf-16 encoding */
+ int *aOffset; /* Offsets of each character in utf-8 input */
+
+ int nBuffer;
+ char *zBuffer;
+
+ int iToken;
+};
+
+/*
+** Create a new tokenizer instance.
+*/
+static int icuCreate(
+ int argc, /* Number of entries in argv[] */
+ const char * const *argv, /* Tokenizer creation arguments */
+ sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
+){
+ IcuTokenizer *p;
+ int n = 0;
+
+ if( argc>0 ){
+ n = strlen(argv[0])+1;
+ }
+ p = (IcuTokenizer *)sqlite3_malloc64(sizeof(IcuTokenizer)+n);
+ if( !p ){
+ return SQLITE_NOMEM;
+ }
+ memset(p, 0, sizeof(IcuTokenizer));
+
+ if( n ){
+ p->zLocale = (char *)&p[1];
+ memcpy(p->zLocale, argv[0], n);
+ }
+
+ *ppTokenizer = (sqlite3_tokenizer *)p;
+
+ return SQLITE_OK;
+}
+
+/*
+** Destroy a tokenizer
+*/
+static int icuDestroy(sqlite3_tokenizer *pTokenizer){
+ IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
+ sqlite3_free(p);
+ return SQLITE_OK;
+}
+
+/*
+** Prepare to begin tokenizing a particular string. The input
+** string to be tokenized is pInput[0..nBytes-1]. A cursor
+** used to incrementally tokenize this string is returned in
+** *ppCursor.
+*/
+static int icuOpen(
+ sqlite3_tokenizer *pTokenizer, /* The tokenizer */
+ const char *zInput, /* Input string */
+ int nInput, /* Length of zInput in bytes */
+ sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
+){
+ IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
+ IcuCursor *pCsr;
+
+ const int32_t opt = U_FOLD_CASE_DEFAULT;
+ UErrorCode status = U_ZERO_ERROR;
+ int nChar;
+
+ UChar32 c;
+ int iInput = 0;
+ int iOut = 0;
+
+ *ppCursor = 0;
+
+ if( zInput==0 ){
+ nInput = 0;
+ zInput = "";
+ }else if( nInput<0 ){
+ nInput = strlen(zInput);
+ }
+ nChar = nInput+1;
+ pCsr = (IcuCursor *)sqlite3_malloc64(
+ sizeof(IcuCursor) + /* IcuCursor */
+ ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
+ (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
+ );
+ if( !pCsr ){
+ return SQLITE_NOMEM;
+ }
+ memset(pCsr, 0, sizeof(IcuCursor));
+ pCsr->aChar = (UChar *)&pCsr[1];
+ pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
+
+ pCsr->aOffset[iOut] = iInput;
+ U8_NEXT(zInput, iInput, nInput, c);
+ while( c>0 ){
+ int isError = 0;
+ c = u_foldCase(c, opt);
+ U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
+ if( isError ){
+ sqlite3_free(pCsr);
+ return SQLITE_ERROR;
+ }
+ pCsr->aOffset[iOut] = iInput;
+
+ if( iInput<nInput ){
+ U8_NEXT(zInput, iInput, nInput, c);
+ }else{
+ c = 0;
+ }
+ }
+
+ pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
+ if( !U_SUCCESS(status) ){
+ sqlite3_free(pCsr);
+ return SQLITE_ERROR;
+ }
+ pCsr->nChar = iOut;
+
+ ubrk_first(pCsr->pIter);
+ *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
+ return SQLITE_OK;
+}
+
+/*
+** Close a tokenization cursor previously opened by a call to icuOpen().
+*/
+static int icuClose(sqlite3_tokenizer_cursor *pCursor){
+ IcuCursor *pCsr = (IcuCursor *)pCursor;
+ ubrk_close(pCsr->pIter);
+ sqlite3_free(pCsr->zBuffer);
+ sqlite3_free(pCsr);
+ return SQLITE_OK;
+}
+
+/*
+** Extract the next token from a tokenization cursor.
+*/
+static int icuNext(
+ sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
+ const char **ppToken, /* OUT: *ppToken is the token text */
+ int *pnBytes, /* OUT: Number of bytes in token */
+ int *piStartOffset, /* OUT: Starting offset of token */
+ int *piEndOffset, /* OUT: Ending offset of token */
+ int *piPosition /* OUT: Position integer of token */
+){
+ IcuCursor *pCsr = (IcuCursor *)pCursor;
+
+ int iStart = 0;
+ int iEnd = 0;
+ int nByte = 0;
+
+ while( iStart==iEnd ){
+ UChar32 c;
+
+ iStart = ubrk_current(pCsr->pIter);
+ iEnd = ubrk_next(pCsr->pIter);
+ if( iEnd==UBRK_DONE ){
+ return SQLITE_DONE;
+ }
+
+ while( iStart<iEnd ){
+ int iWhite = iStart;
+ U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
+ if( u_isspace(c) ){
+ iStart = iWhite;
+ }else{
+ break;
+ }
+ }
+ assert(iStart<=iEnd);
+ }
+
+ do {
+ UErrorCode status = U_ZERO_ERROR;
+ if( nByte ){
+ char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
+ if( !zNew ){
+ return SQLITE_NOMEM;
+ }
+ pCsr->zBuffer = zNew;
+ pCsr->nBuffer = nByte;
+ }
+
+ u_strToUTF8(
+ pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
+ &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
+ &status /* Output success/failure */
+ );
+ } while( nByte>pCsr->nBuffer );
+
+ *ppToken = pCsr->zBuffer;
+ *pnBytes = nByte;
+ *piStartOffset = pCsr->aOffset[iStart];
+ *piEndOffset = pCsr->aOffset[iEnd];
+ *piPosition = pCsr->iToken++;
+
+ return SQLITE_OK;
+}
+
+/*
+** The set of routines that implement the simple tokenizer
+*/
+static const sqlite3_tokenizer_module icuTokenizerModule = {
+ 0, /* iVersion */
+ icuCreate, /* xCreate */
+ icuDestroy, /* xCreate */
+ icuOpen, /* xOpen */
+ icuClose, /* xClose */
+ icuNext, /* xNext */
+ 0, /* xLanguageid */
+};
+
+/*
+** Set *ppModule to point at the implementation of the ICU tokenizer.
+*/
+SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
+ sqlite3_tokenizer_module const**ppModule
+){
+ *ppModule = &icuTokenizerModule;
+}
+
+#endif /* defined(SQLITE_ENABLE_ICU) */
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
+
+/************** End of fts3_icu.c ********************************************/
+/************** Begin file sqlite3rbu.c **************************************/
+/*
+** 2014 August 30
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+**
+** OVERVIEW
+**
+** The RBU extension requires that the RBU update be packaged as an
+** SQLite database. The tables it expects to find are described in
+** sqlite3rbu.h. Essentially, for each table xyz in the target database
+** that the user wishes to write to, a corresponding data_xyz table is
+** created in the RBU database and populated with one row for each row to
+** update, insert or delete from the target table.
+**
+** The update proceeds in three stages:
+**
+** 1) The database is updated. The modified database pages are written
+** to a *-oal file. A *-oal file is just like a *-wal file, except
+** that it is named "<database>-oal" instead of "<database>-wal".
+** Because regular SQLite clients do not look for file named
+** "<database>-oal", they go on using the original database in
+** rollback mode while the *-oal file is being generated.
+**
+** During this stage RBU does not update the database by writing
+** directly to the target tables. Instead it creates "imposter"
+** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
+** to update each b-tree individually. All updates required by each
+** b-tree are completed before moving on to the next, and all
+** updates are done in sorted key order.
+**
+** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
+** location using a call to rename(2). Before doing this the RBU
+** module takes an EXCLUSIVE lock on the database file, ensuring
+** that there are no other active readers.
+**
+** Once the EXCLUSIVE lock is released, any other database readers
+** detect the new *-wal file and read the database in wal mode. At
+** this point they see the new version of the database - including
+** the updates made as part of the RBU update.
+**
+** 3) The new *-wal file is checkpointed. This proceeds in the same way
+** as a regular database checkpoint, except that a single frame is
+** checkpointed each time sqlite3rbu_step() is called. If the RBU
+** handle is closed before the entire *-wal file is checkpointed,
+** the checkpoint progress is saved in the RBU database and the
+** checkpoint can be resumed by another RBU client at some point in
+** the future.
+**
+** POTENTIAL PROBLEMS
+**
+** The rename() call might not be portable. And RBU is not currently
+** syncing the directory after renaming the file.
+**
+** When state is saved, any commit to the *-oal file and the commit to
+** the RBU update database are not atomic. So if the power fails at the
+** wrong moment they might get out of sync. As the main database will be
+** committed before the RBU update database this will likely either just
+** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
+** constraint violations).
+**
+** If some client does modify the target database mid RBU update, or some
+** other error occurs, the RBU extension will keep throwing errors. It's
+** not really clear how to get out of this state. The system could just
+** by delete the RBU update database and *-oal file and have the device
+** download the update again and start over.
+**
+** At present, for an UPDATE, both the new.* and old.* records are
+** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
+** fields are collected. This means we're probably writing a lot more
+** data to disk when saving the state of an ongoing update to the RBU
+** update database than is strictly necessary.
+**
+*/
+
+/* #include <assert.h> */
+/* #include <string.h> */
+/* #include <stdio.h> */
+
+/* #include "sqlite3.h" */
+
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
+/************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
+/************** Begin file sqlite3rbu.h **************************************/
+/*
+** 2014 August 30
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file contains the public interface for the RBU extension.
+*/
+
+/*
+** SUMMARY
+**
+** Writing a transaction containing a large number of operations on
+** b-tree indexes that are collectively larger than the available cache
+** memory can be very inefficient.
+**
+** The problem is that in order to update a b-tree, the leaf page (at least)
+** containing the entry being inserted or deleted must be modified. If the
+** working set of leaves is larger than the available cache memory, then a
+** single leaf that is modified more than once as part of the transaction
+** may be loaded from or written to the persistent media multiple times.
+** Additionally, because the index updates are likely to be applied in
+** random order, access to pages within the database is also likely to be in
+** random order, which is itself quite inefficient.
+**
+** One way to improve the situation is to sort the operations on each index
+** by index key before applying them to the b-tree. This leads to an IO
+** pattern that resembles a single linear scan through the index b-tree,
+** and all but guarantees each modified leaf page is loaded and stored
+** exactly once. SQLite uses this trick to improve the performance of
+** CREATE INDEX commands. This extension allows it to be used to improve
+** the performance of large transactions on existing databases.
+**
+** Additionally, this extension allows the work involved in writing the
+** large transaction to be broken down into sub-transactions performed
+** sequentially by separate processes. This is useful if the system cannot
+** guarantee that a single update process will run for long enough to apply
+** the entire update, for example because the update is being applied on a
+** mobile device that is frequently rebooted. Even after the writer process
+** has committed one or more sub-transactions, other database clients continue
+** to read from the original database snapshot. In other words, partially
+** applied transactions are not visible to other clients.
+**
+** "RBU" stands for "Resumable Bulk Update". As in a large database update
+** transmitted via a wireless network to a mobile device. A transaction
+** applied using this extension is hence refered to as an "RBU update".
+**
+**
+** LIMITATIONS
+**
+** An "RBU update" transaction is subject to the following limitations:
+**
+** * The transaction must consist of INSERT, UPDATE and DELETE operations
+** only.
+**
+** * INSERT statements may not use any default values.
+**
+** * UPDATE and DELETE statements must identify their target rows by
+** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
+** KEY fields may not be updated or deleted. If the table being written
+** has no PRIMARY KEY, affected rows must be identified by rowid.
+**
+** * UPDATE statements may not modify PRIMARY KEY columns.
+**
+** * No triggers will be fired.
+**
+** * No foreign key violations are detected or reported.
+**
+** * CHECK constraints are not enforced.
+**
+** * No constraint handling mode except for "OR ROLLBACK" is supported.
+**
+**
+** PREPARATION
+**
+** An "RBU update" is stored as a separate SQLite database. A database
+** containing an RBU update is an "RBU database". For each table in the
+** target database to be updated, the RBU database should contain a table
+** named "data_<target name>" containing the same set of columns as the
+** target table, and one more - "rbu_control". The data_% table should
+** have no PRIMARY KEY or UNIQUE constraints, but each column should have
+** the same type as the corresponding column in the target database.
+** The "rbu_control" column should have no type at all. For example, if
+** the target database contains:
+**
+** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
+**
+** Then the RBU database should contain:
+**
+** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
+**
+** The order of the columns in the data_% table does not matter.
+**
+** Instead of a regular table, the RBU database may also contain virtual
+** tables or view named using the data_<target> naming scheme.
+**
+** Instead of the plain data_<target> naming scheme, RBU database tables
+** may also be named data<integer>_<target>, where <integer> is any sequence
+** of zero or more numeric characters (0-9). This can be significant because
+** tables within the RBU database are always processed in order sorted by
+** name. By judicious selection of the <integer> portion of the names
+** of the RBU tables the user can therefore control the order in which they
+** are processed. This can be useful, for example, to ensure that "external
+** content" FTS4 tables are updated before their underlying content tables.
+**
+** If the target database table is a virtual table or a table that has no
+** PRIMARY KEY declaration, the data_% table must also contain a column
+** named "rbu_rowid". This column is mapped to the tables implicit primary
+** key column - "rowid". Virtual tables for which the "rowid" column does
+** not function like a primary key value cannot be updated using RBU. For
+** example, if the target db contains either of the following:
+**
+** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
+** CREATE TABLE x1(a, b)
+**
+** then the RBU database should contain:
+**
+** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
+**
+** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
+** target table must be present in the input table. For virtual tables,
+** hidden columns are optional - they are updated by RBU if present in
+** the input table, or not otherwise. For example, to write to an fts4
+** table with a hidden languageid column such as:
+**
+** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
+**
+** Either of the following input table schemas may be used:
+**
+** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
+** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
+**
+** For each row to INSERT into the target database as part of the RBU
+** update, the corresponding data_% table should contain a single record
+** with the "rbu_control" column set to contain integer value 0. The
+** other columns should be set to the values that make up the new record
+** to insert.
+**
+** If the target database table has an INTEGER PRIMARY KEY, it is not
+** possible to insert a NULL value into the IPK column. Attempting to
+** do so results in an SQLITE_MISMATCH error.
+**
+** For each row to DELETE from the target database as part of the RBU
+** update, the corresponding data_% table should contain a single record
+** with the "rbu_control" column set to contain integer value 1. The
+** real primary key values of the row to delete should be stored in the
+** corresponding columns of the data_% table. The values stored in the
+** other columns are not used.
+**
+** For each row to UPDATE from the target database as part of the RBU
+** update, the corresponding data_% table should contain a single record
+** with the "rbu_control" column set to contain a value of type text.
+** The real primary key values identifying the row to update should be
+** stored in the corresponding columns of the data_% table row, as should
+** the new values of all columns being update. The text value in the
+** "rbu_control" column must contain the same number of characters as
+** there are columns in the target database table, and must consist entirely
+** of 'x' and '.' characters (or in some special cases 'd' - see below). For
+** each column that is being updated, the corresponding character is set to
+** 'x'. For those that remain as they are, the corresponding character of the
+** rbu_control value should be set to '.'. For example, given the tables
+** above, the update statement:
+**
+** UPDATE t1 SET c = 'usa' WHERE a = 4;
+**
+** is represented by the data_t1 row created by:
+**
+** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
+**
+** Instead of an 'x' character, characters of the rbu_control value specified
+** for UPDATEs may also be set to 'd'. In this case, instead of updating the
+** target table with the value stored in the corresponding data_% column, the
+** user-defined SQL function "rbu_delta()" is invoked and the result stored in
+** the target table column. rbu_delta() is invoked with two arguments - the
+** original value currently stored in the target table column and the
+** value specified in the data_xxx table.
+**
+** For example, this row:
+**
+** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
+**
+** is similar to an UPDATE statement such as:
+**
+** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
+**
+** Finally, if an 'f' character appears in place of a 'd' or 's' in an
+** ota_control string, the contents of the data_xxx table column is assumed
+** to be a "fossil delta" - a patch to be applied to a blob value in the
+** format used by the fossil source-code management system. In this case
+** the existing value within the target database table must be of type BLOB.
+** It is replaced by the result of applying the specified fossil delta to
+** itself.
+**
+** If the target database table is a virtual table or a table with no PRIMARY
+** KEY, the rbu_control value should not include a character corresponding
+** to the rbu_rowid value. For example, this:
+**
+** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
+** VALUES(NULL, 'usa', 12, '.x');
+**
+** causes a result similar to:
+**
+** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
+**
+** The data_xxx tables themselves should have no PRIMARY KEY declarations.
+** However, RBU is more efficient if reading the rows in from each data_xxx
+** table in "rowid" order is roughly the same as reading them sorted by
+** the PRIMARY KEY of the corresponding target database table. In other
+** words, rows should be sorted using the destination table PRIMARY KEY
+** fields before they are inserted into the data_xxx tables.
+**
+** USAGE
+**
+** The API declared below allows an application to apply an RBU update
+** stored on disk to an existing target database. Essentially, the
+** application:
+**
+** 1) Opens an RBU handle using the sqlite3rbu_open() function.
+**
+** 2) Registers any required virtual table modules with the database
+** handle returned by sqlite3rbu_db(). Also, if required, register
+** the rbu_delta() implementation.
+**
+** 3) Calls the sqlite3rbu_step() function one or more times on
+** the new handle. Each call to sqlite3rbu_step() performs a single
+** b-tree operation, so thousands of calls may be required to apply
+** a complete update.
+**
+** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
+** sqlite3rbu_step() has been called enough times to completely
+** apply the update to the target database, then the RBU database
+** is marked as fully applied. Otherwise, the state of the RBU
+** update application is saved in the RBU database for later
+** resumption.
+**
+** See comments below for more detail on APIs.
+**
+** If an update is only partially applied to the target database by the
+** time sqlite3rbu_close() is called, various state information is saved
+** within the RBU database. This allows subsequent processes to automatically
+** resume the RBU update from where it left off.
+**
+** To remove all RBU extension state information, returning an RBU database
+** to its original contents, it is sufficient to drop all tables that begin
+** with the prefix "rbu_"
+**
+** DATABASE LOCKING
+**
+** An RBU update may not be applied to a database in WAL mode. Attempting
+** to do so is an error (SQLITE_ERROR).
+**
+** While an RBU handle is open, a SHARED lock may be held on the target
+** database file. This means it is possible for other clients to read the
+** database, but not to write it.
+**
+** If an RBU update is started and then suspended before it is completed,
+** then an external client writes to the database, then attempting to resume
+** the suspended RBU update is also an error (SQLITE_BUSY).
+*/
+
+#ifndef _SQLITE3RBU_H
+#define _SQLITE3RBU_H
+
+/* #include "sqlite3.h" ** Required for error code definitions ** */
+
+#if 0
+extern "C" {
+#endif
+
+typedef struct sqlite3rbu sqlite3rbu;
+
+/*
+** Open an RBU handle.
+**
+** Argument zTarget is the path to the target database. Argument zRbu is
+** the path to the RBU database. Each call to this function must be matched
+** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
+** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
+** or zRbu begin with "file:", it will be interpreted as an SQLite
+** database URI, not a regular file name.
+**
+** If the zState argument is passed a NULL value, the RBU extension stores
+** the current state of the update (how many rows have been updated, which
+** indexes are yet to be updated etc.) within the RBU database itself. This
+** can be convenient, as it means that the RBU application does not need to
+** organize removing a separate state file after the update is concluded.
+** Or, if zState is non-NULL, it must be a path to a database file in which
+** the RBU extension can store the state of the update.
+**
+** When resuming an RBU update, the zState argument must be passed the same
+** value as when the RBU update was started.
+**
+** Once the RBU update is finished, the RBU extension does not
+** automatically remove any zState database file, even if it created it.
+**
+** By default, RBU uses the default VFS to access the files on disk. To
+** use a VFS other than the default, an SQLite "file:" URI containing a
+** "vfs=..." option may be passed as the zTarget option.
+**
+** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
+** SQLite's built-in VFSs, including the multiplexor VFS. However it does
+** not work out of the box with zipvfs. Refer to the comment describing
+** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
+*/
+SQLITE_API sqlite3rbu *sqlite3rbu_open(
+ const char *zTarget,
+ const char *zRbu,
+ const char *zState
+);
+
+/*
+** Open an RBU handle to perform an RBU vacuum on database file zTarget.
+** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
+** that it can be suspended and resumed like an RBU update.
+**
+** The second argument to this function identifies a database in which
+** to store the state of the RBU vacuum operation if it is suspended. The
+** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
+** operation, the state database should either not exist or be empty
+** (contain no tables). If an RBU vacuum is suspended by calling
+** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
+** returned SQLITE_DONE, the vacuum state is stored in the state database.
+** The vacuum can be resumed by calling this function to open a new RBU
+** handle specifying the same target and state databases.
+**
+** If the second argument passed to this function is NULL, then the
+** name of the state database is "<database>-vacuum", where <database>
+** is the name of the target database file. In this case, on UNIX, if the
+** state database is not already present in the file-system, it is created
+** with the same permissions as the target db is made.
+**
+** With an RBU vacuum, it is an SQLITE_MISUSE error if the name of the
+** state database ends with "-vactmp". This name is reserved for internal
+** use.
+**
+** This function does not delete the state database after an RBU vacuum
+** is completed, even if it created it. However, if the call to
+** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
+** of the state tables within the state database are zeroed. This way,
+** the next call to sqlite3rbu_vacuum() opens a handle that starts a
+** new RBU vacuum operation.
+**
+** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
+** describing the sqlite3rbu_create_vfs() API function below for
+** a description of the complications associated with using RBU with
+** zipvfs databases.
+*/
+SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
+ const char *zTarget,
+ const char *zState
+);
+
+/*
+** Configure a limit for the amount of temp space that may be used by
+** the RBU handle passed as the first argument. The new limit is specified
+** in bytes by the second parameter. If it is positive, the limit is updated.
+** If the second parameter to this function is passed zero, then the limit
+** is removed entirely. If the second parameter is negative, the limit is
+** not modified (this is useful for querying the current limit).
+**
+** In all cases the returned value is the current limit in bytes (zero
+** indicates unlimited).
+**
+** If the temp space limit is exceeded during operation, an SQLITE_FULL
+** error is returned.
+*/
+SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);
+
+/*
+** Return the current amount of temp file space, in bytes, currently used by
+** the RBU handle passed as the only argument.
+*/
+SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
+
+/*
+** Internally, each RBU connection uses a separate SQLite database
+** connection to access the target and rbu update databases. This
+** API allows the application direct access to these database handles.
+**
+** The first argument passed to this function must be a valid, open, RBU
+** handle. The second argument should be passed zero to access the target
+** database handle, or non-zero to access the rbu update database handle.
+** Accessing the underlying database handles may be useful in the
+** following scenarios:
+**
+** * If any target tables are virtual tables, it may be necessary to
+** call sqlite3_create_module() on the target database handle to
+** register the required virtual table implementations.
+**
+** * If the data_xxx tables in the RBU source database are virtual
+** tables, the application may need to call sqlite3_create_module() on
+** the rbu update db handle to any required virtual table
+** implementations.
+**
+** * If the application uses the "rbu_delta()" feature described above,
+** it must use sqlite3_create_function() or similar to register the
+** rbu_delta() implementation with the target database handle.
+**
+** If an error has occurred, either while opening or stepping the RBU object,
+** this function may return NULL. The error code and message may be collected
+** when sqlite3rbu_close() is called.
+**
+** Database handles returned by this function remain valid until the next
+** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
+*/
+SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
+
+/*
+** Do some work towards applying the RBU update to the target db.
+**
+** Return SQLITE_DONE if the update has been completely applied, or
+** SQLITE_OK if no error occurs but there remains work to do to apply
+** the RBU update. If an error does occur, some other error code is
+** returned.
+**
+** Once a call to sqlite3rbu_step() has returned a value other than
+** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
+** that immediately return the same value.
+*/
+SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
+
+/*
+** Force RBU to save its state to disk.
+**
+** If a power failure or application crash occurs during an update, following
+** system recovery RBU may resume the update from the point at which the state
+** was last saved. In other words, from the most recent successful call to
+** sqlite3rbu_close() or this function.
+**
+** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
+*/
+SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
+
+/*
+** Close an RBU handle.
+**
+** If the RBU update has been completely applied, mark the RBU database
+** as fully applied. Otherwise, assuming no error has occurred, save the
+** current state of the RBU update appliation to the RBU database.
+**
+** If an error has already occurred as part of an sqlite3rbu_step()
+** or sqlite3rbu_open() call, or if one occurs within this function, an
+** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,
+** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted
+** English language error message. It is the responsibility of the caller to
+** eventually free any such buffer using sqlite3_free().
+**
+** Otherwise, if no error occurs, this function returns SQLITE_OK if the
+** update has been partially applied, or SQLITE_DONE if it has been
+** completely applied.
+*/
+SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
+
+/*
+** Return the total number of key-value operations (inserts, deletes or
+** updates) that have been performed on the target database since the
+** current RBU update was started.
+*/
+SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
+
+/*
+** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
+** progress indications for the two stages of an RBU update. This API may
+** be useful for driving GUI progress indicators and similar.
+**
+** An RBU update is divided into two stages:
+**
+** * Stage 1, in which changes are accumulated in an oal/wal file, and
+** * Stage 2, in which the contents of the wal file are copied into the
+** main database.
+**
+** The update is visible to non-RBU clients during stage 2. During stage 1
+** non-RBU reader clients may see the original database.
+**
+** If this API is called during stage 2 of the update, output variable
+** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
+** to a value between 0 and 10000 to indicate the permyriadage progress of
+** stage 2. A value of 5000 indicates that stage 2 is half finished,
+** 9000 indicates that it is 90% finished, and so on.
+**
+** If this API is called during stage 1 of the update, output variable
+** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
+** value to which (*pnOne) is set depends on whether or not the RBU
+** database contains an "rbu_count" table. The rbu_count table, if it
+** exists, must contain the same columns as the following:
+**
+** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
+**
+** There must be one row in the table for each source (data_xxx) table within
+** the RBU database. The 'tbl' column should contain the name of the source
+** table. The 'cnt' column should contain the number of rows within the
+** source table.
+**
+** If the rbu_count table is present and populated correctly and this
+** API is called during stage 1, the *pnOne output variable is set to the
+** permyriadage progress of the same stage. If the rbu_count table does
+** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
+** table exists but is not correctly populated, the value of the *pnOne
+** output variable during stage 1 is undefined.
+*/
+SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);
+
+/*
+** Obtain an indication as to the current stage of an RBU update or vacuum.
+** This function always returns one of the SQLITE_RBU_STATE_XXX constants
+** defined in this file. Return values should be interpreted as follows:
+**
+** SQLITE_RBU_STATE_OAL:
+** RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
+** may either add further data to the *-oal file, or compute data that will
+** be added by a subsequent call.
+**
+** SQLITE_RBU_STATE_MOVE:
+** RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
+** will move the *-oal file to the equivalent *-wal path. If the current
+** operation is an RBU update, then the updated version of the database
+** file will become visible to ordinary SQLite clients following the next
+** call to sqlite3rbu_step().
+**
+** SQLITE_RBU_STATE_CHECKPOINT:
+** RBU is currently performing an incremental checkpoint. The next call to
+** sqlite3rbu_step() will copy a page of data from the *-wal file into
+** the target database file.
+**
+** SQLITE_RBU_STATE_DONE:
+** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
+** will immediately return SQLITE_DONE.
+**
+** SQLITE_RBU_STATE_ERROR:
+** An error has occurred. Any subsequent calls to sqlite3rbu_step() will
+** immediately return the SQLite error code associated with the error.
+*/
+#define SQLITE_RBU_STATE_OAL 1
+#define SQLITE_RBU_STATE_MOVE 2
+#define SQLITE_RBU_STATE_CHECKPOINT 3
+#define SQLITE_RBU_STATE_DONE 4
+#define SQLITE_RBU_STATE_ERROR 5
+
+SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
+
+/*
+** Create an RBU VFS named zName that accesses the underlying file-system
+** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
+** then the new RBU VFS uses the default system VFS to access the file-system.
+** The new object is registered as a non-default VFS with SQLite before
+** returning.
+**
+** Part of the RBU implementation uses a custom VFS object. Usually, this
+** object is created and deleted automatically by RBU.
+**
+** The exception is for applications that also use zipvfs. In this case,
+** the custom VFS must be explicitly created by the user before the RBU
+** handle is opened. The RBU VFS should be installed so that the zipvfs
+** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
+** (for example multiplexor) to access the file-system. For example,
+** to assemble an RBU enabled VFS stack that uses both zipvfs and
+** multiplexor (error checking omitted):
+**
+** // Create a VFS named "multiplex" (not the default).
+** sqlite3_multiplex_initialize(0, 0);
+**
+** // Create an rbu VFS named "rbu" that uses multiplexor. If the
+** // second argument were replaced with NULL, the "rbu" VFS would
+** // access the file-system via the system default VFS, bypassing the
+** // multiplexor.
+** sqlite3rbu_create_vfs("rbu", "multiplex");
+**
+** // Create a zipvfs VFS named "zipvfs" that uses rbu.
+** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
+**
+** // Make zipvfs the default VFS.
+** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
+**
+** Because the default VFS created above includes a RBU functionality, it
+** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
+** that does not include the RBU layer results in an error.
+**
+** The overhead of adding the "rbu" VFS to the system is negligible for
+** non-RBU users. There is no harm in an application accessing the
+** file-system via "rbu" all the time, even if it only uses RBU functionality
+** occasionally.
+*/
+SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
+
+/*
+** Deregister and destroy an RBU vfs created by an earlier call to
+** sqlite3rbu_create_vfs().
+**
+** VFS objects are not reference counted. If a VFS object is destroyed
+** before all database handles that use it have been closed, the results
+** are undefined.
+*/
+SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
+
+#if 0
+} /* end of the 'extern "C"' block */
+#endif
+
+#endif /* _SQLITE3RBU_H */
+
+/************** End of sqlite3rbu.h ******************************************/
+/************** Continuing where we left off in sqlite3rbu.c *****************/
+
+#if defined(_WIN32_WCE)
+/* #include "windows.h" */
+#endif
+
+/* Maximum number of prepared UPDATE statements held by this module */
+#define SQLITE_RBU_UPDATE_CACHESIZE 16
+
+/* Delta checksums disabled by default. Compile with -DRBU_ENABLE_DELTA_CKSUM
+** to enable checksum verification.
+*/
+#ifndef RBU_ENABLE_DELTA_CKSUM
+# define RBU_ENABLE_DELTA_CKSUM 0
+#endif
+
+/*
+** Swap two objects of type TYPE.
+*/
+#if !defined(SQLITE_AMALGAMATION)
+# define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
+#endif
+
+/*
+** The rbu_state table is used to save the state of a partially applied
+** update so that it can be resumed later. The table consists of integer
+** keys mapped to values as follows:
+**
+** RBU_STATE_STAGE:
+** May be set to integer values 1, 2, 4 or 5. As follows:
+** 1: the *-rbu file is currently under construction.
+** 2: the *-rbu file has been constructed, but not yet moved
+** to the *-wal path.
+** 4: the checkpoint is underway.
+** 5: the rbu update has been checkpointed.
+**
+** RBU_STATE_TBL:
+** Only valid if STAGE==1. The target database name of the table
+** currently being written.
+**
+** RBU_STATE_IDX:
+** Only valid if STAGE==1. The target database name of the index
+** currently being written, or NULL if the main table is currently being
+** updated.
+**
+** RBU_STATE_ROW:
+** Only valid if STAGE==1. Number of rows already processed for the current
+** table/index.
+**
+** RBU_STATE_PROGRESS:
+** Trbul number of sqlite3rbu_step() calls made so far as part of this
+** rbu update.
+**
+** RBU_STATE_CKPT:
+** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
+** header created by recovering the *-wal file. This is used to detect
+** cases when another client appends frames to the *-wal file in the
+** middle of an incremental checkpoint (an incremental checkpoint cannot
+** be continued if this happens).
+**
+** RBU_STATE_COOKIE:
+** Valid if STAGE==1. The current change-counter cookie value in the
+** target db file.
+**
+** RBU_STATE_OALSZ:
+** Valid if STAGE==1. The size in bytes of the *-oal file.
+**
+** RBU_STATE_DATATBL:
+** Only valid if STAGE==1. The RBU database name of the table
+** currently being read.
+*/
+#define RBU_STATE_STAGE 1
+#define RBU_STATE_TBL 2
+#define RBU_STATE_IDX 3
+#define RBU_STATE_ROW 4
+#define RBU_STATE_PROGRESS 5
+#define RBU_STATE_CKPT 6
+#define RBU_STATE_COOKIE 7
+#define RBU_STATE_OALSZ 8
+#define RBU_STATE_PHASEONESTEP 9
+#define RBU_STATE_DATATBL 10
+
+#define RBU_STAGE_OAL 1
+#define RBU_STAGE_MOVE 2
+#define RBU_STAGE_CAPTURE 3
+#define RBU_STAGE_CKPT 4
+#define RBU_STAGE_DONE 5
+
+
+#define RBU_CREATE_STATE \
+ "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
+
+typedef struct RbuFrame RbuFrame;
+typedef struct RbuObjIter RbuObjIter;
+typedef struct RbuState RbuState;
+typedef struct RbuSpan RbuSpan;
+typedef struct rbu_vfs rbu_vfs;
+typedef struct rbu_file rbu_file;
+typedef struct RbuUpdateStmt RbuUpdateStmt;
+
+#if !defined(SQLITE_AMALGAMATION)
+typedef unsigned int u32;
+typedef unsigned short u16;
+typedef unsigned char u8;
+typedef sqlite3_int64 i64;
+#endif
+
+/*
+** These values must match the values defined in wal.c for the equivalent
+** locks. These are not magic numbers as they are part of the SQLite file
+** format.
+*/
+#define WAL_LOCK_WRITE 0
+#define WAL_LOCK_CKPT 1
+#define WAL_LOCK_READ0 3
+
+#define SQLITE_FCNTL_RBUCNT 5149216
+
+/*
+** A structure to store values read from the rbu_state table in memory.
+*/
+struct RbuState {
+ int eStage;
+ char *zTbl;
+ char *zDataTbl;
+ char *zIdx;
+ i64 iWalCksum;
+ int nRow;
+ i64 nProgress;
+ u32 iCookie;
+ i64 iOalSz;
+ i64 nPhaseOneStep;
+};
+
+struct RbuUpdateStmt {
+ char *zMask; /* Copy of update mask used with pUpdate */
+ sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
+ RbuUpdateStmt *pNext;
+};
+
+struct RbuSpan {
+ const char *zSpan;
+ int nSpan;
+};
+
+/*
+** An iterator of this type is used to iterate through all objects in
+** the target database that require updating. For each such table, the
+** iterator visits, in order:
+**
+** * the table itself,
+** * each index of the table (zero or more points to visit), and
+** * a special "cleanup table" state.
+**
+** abIndexed:
+** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
+** it points to an array of flags nTblCol elements in size. The flag is
+** set for each column that is either a part of the PK or a part of an
+** index. Or clear otherwise.
+**
+** If there are one or more partial indexes on the table, all fields of
+** this array set set to 1. This is because in that case, the module has
+** no way to tell which fields will be required to add and remove entries
+** from the partial indexes.
+**
+*/
+struct RbuObjIter {
+ sqlite3_stmt *pTblIter; /* Iterate through tables */
+ sqlite3_stmt *pIdxIter; /* Index iterator */
+ int nTblCol; /* Size of azTblCol[] array */
+ char **azTblCol; /* Array of unquoted target column names */
+ char **azTblType; /* Array of target column types */
+ int *aiSrcOrder; /* src table col -> target table col */
+ u8 *abTblPk; /* Array of flags, set on target PK columns */
+ u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
+ u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
+ int eType; /* Table type - an RBU_PK_XXX value */
+
+ /* Output variables. zTbl==0 implies EOF. */
+ int bCleanup; /* True in "cleanup" state */
+ const char *zTbl; /* Name of target db table */
+ const char *zDataTbl; /* Name of rbu db table (or null) */
+ const char *zIdx; /* Name of target db index (or null) */
+ int iTnum; /* Root page of current object */
+ int iPkTnum; /* If eType==EXTERNAL, root of PK index */
+ int bUnique; /* Current index is unique */
+ int nIndex; /* Number of aux. indexes on table zTbl */
+
+ /* Statements created by rbuObjIterPrepareAll() */
+ int nCol; /* Number of columns in current object */
+ sqlite3_stmt *pSelect; /* Source data */
+ sqlite3_stmt *pInsert; /* Statement for INSERT operations */
+ sqlite3_stmt *pDelete; /* Statement for DELETE ops */
+ sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
+ int nIdxCol;
+ RbuSpan *aIdxCol;
+ char *zIdxSql;
+
+ /* Last UPDATE used (for PK b-tree updates only), or NULL. */
+ RbuUpdateStmt *pRbuUpdate;
+};
+
+/*
+** Values for RbuObjIter.eType
+**
+** 0: Table does not exist (error)
+** 1: Table has an implicit rowid.
+** 2: Table has an explicit IPK column.
+** 3: Table has an external PK index.
+** 4: Table is WITHOUT ROWID.
+** 5: Table is a virtual table.
+*/
+#define RBU_PK_NOTABLE 0
+#define RBU_PK_NONE 1
+#define RBU_PK_IPK 2
+#define RBU_PK_EXTERNAL 3
+#define RBU_PK_WITHOUT_ROWID 4
+#define RBU_PK_VTAB 5
+
+
+/*
+** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
+** one of the following operations.
+*/
+#define RBU_INSERT 1 /* Insert on a main table b-tree */
+#define RBU_DELETE 2 /* Delete a row from a main table b-tree */
+#define RBU_REPLACE 3 /* Delete and then insert a row */
+#define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
+#define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
+
+#define RBU_UPDATE 6 /* Update a row in a main table b-tree */
+
+/*
+** A single step of an incremental checkpoint - frame iWalFrame of the wal
+** file should be copied to page iDbPage of the database file.
+*/
+struct RbuFrame {
+ u32 iDbPage;
+ u32 iWalFrame;
+};
+
+/*
+** RBU handle.
+**
+** nPhaseOneStep:
+** If the RBU database contains an rbu_count table, this value is set to
+** a running estimate of the number of b-tree operations required to
+** finish populating the *-oal file. This allows the sqlite3_bp_progress()
+** API to calculate the permyriadage progress of populating the *-oal file
+** using the formula:
+**
+** permyriadage = (10000 * nProgress) / nPhaseOneStep
+**
+** nPhaseOneStep is initialized to the sum of:
+**
+** nRow * (nIndex + 1)
+**
+** for all source tables in the RBU database, where nRow is the number
+** of rows in the source table and nIndex the number of indexes on the
+** corresponding target database table.
+**
+** This estimate is accurate if the RBU update consists entirely of
+** INSERT operations. However, it is inaccurate if:
+**
+** * the RBU update contains any UPDATE operations. If the PK specified
+** for an UPDATE operation does not exist in the target table, then
+** no b-tree operations are required on index b-trees. Or if the
+** specified PK does exist, then (nIndex*2) such operations are
+** required (one delete and one insert on each index b-tree).
+**
+** * the RBU update contains any DELETE operations for which the specified
+** PK does not exist. In this case no operations are required on index
+** b-trees.
+**
+** * the RBU update contains REPLACE operations. These are similar to
+** UPDATE operations.
+**
+** nPhaseOneStep is updated to account for the conditions above during the
+** first pass of each source table. The updated nPhaseOneStep value is
+** stored in the rbu_state table if the RBU update is suspended.
+*/
+struct sqlite3rbu {
+ int eStage; /* Value of RBU_STATE_STAGE field */
+ sqlite3 *dbMain; /* target database handle */
+ sqlite3 *dbRbu; /* rbu database handle */
+ char *zTarget; /* Path to target db */
+ char *zRbu; /* Path to rbu db */
+ char *zState; /* Path to state db (or NULL if zRbu) */
+ char zStateDb[5]; /* Db name for state ("stat" or "main") */
+ int rc; /* Value returned by last rbu_step() call */
+ char *zErrmsg; /* Error message if rc!=SQLITE_OK */
+ int nStep; /* Rows processed for current object */
+ int nProgress; /* Rows processed for all objects */
+ RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
+ const char *zVfsName; /* Name of automatically created rbu vfs */
+ rbu_file *pTargetFd; /* File handle open on target db */
+ int nPagePerSector; /* Pages per sector for pTargetFd */
+ i64 iOalSz;
+ i64 nPhaseOneStep;
+
+ /* The following state variables are used as part of the incremental
+ ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
+ ** function rbuSetupCheckpoint() for details. */
+ u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
+ u32 mLock;
+ int nFrame; /* Entries in aFrame[] array */
+ int nFrameAlloc; /* Allocated size of aFrame[] array */
+ RbuFrame *aFrame;
+ int pgsz;
+ u8 *aBuf;
+ i64 iWalCksum;
+ i64 szTemp; /* Current size of all temp files in use */
+ i64 szTempLimit; /* Total size limit for temp files */
+
+ /* Used in RBU vacuum mode only */
+ int nRbu; /* Number of RBU VFS in the stack */
+ rbu_file *pRbuFd; /* Fd for main db of dbRbu */
+};
+
+/*
+** An rbu VFS is implemented using an instance of this structure.
+**
+** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
+** It is NULL for RBU VFS objects created explicitly using
+** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
+** space used by the RBU handle.
+*/
+struct rbu_vfs {
+ sqlite3_vfs base; /* rbu VFS shim methods */
+ sqlite3_vfs *pRealVfs; /* Underlying VFS */
+ sqlite3_mutex *mutex; /* Mutex to protect pMain */
+ sqlite3rbu *pRbu; /* Owner RBU object */
+ rbu_file *pMain; /* List of main db files */
+ rbu_file *pMainRbu; /* List of main db files with pRbu!=0 */
+};
+
+/*
+** Each file opened by an rbu VFS is represented by an instance of
+** the following structure.
+**
+** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
+** "sz" is set to the current size of the database file.
+*/
+struct rbu_file {
+ sqlite3_file base; /* sqlite3_file methods */
+ sqlite3_file *pReal; /* Underlying file handle */
+ rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
+ sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
+ i64 sz; /* Size of file in bytes (temp only) */
+
+ int openFlags; /* Flags this file was opened with */
+ u32 iCookie; /* Cookie value for main db files */
+ u8 iWriteVer; /* "write-version" value for main db files */
+ u8 bNolock; /* True to fail EXCLUSIVE locks */
+
+ int nShm; /* Number of entries in apShm[] array */
+ char **apShm; /* Array of mmap'd *-shm regions */
+ char *zDel; /* Delete this when closing file */
+
+ const char *zWal; /* Wal filename for this main db file */
+ rbu_file *pWalFd; /* Wal file descriptor for this main db */
+ rbu_file *pMainNext; /* Next MAIN_DB file */
+ rbu_file *pMainRbuNext; /* Next MAIN_DB file with pRbu!=0 */
+};
+
+/*
+** True for an RBU vacuum handle, or false otherwise.
+*/
+#define rbuIsVacuum(p) ((p)->zTarget==0)
+
+
+/*************************************************************************
+** The following three functions, found below:
+**
+** rbuDeltaGetInt()
+** rbuDeltaChecksum()
+** rbuDeltaApply()
+**
+** are lifted from the fossil source code (http://fossil-scm.org). They
+** are used to implement the scalar SQL function rbu_fossil_delta().
+*/
+
+/*
+** Read bytes from *pz and convert them into a positive integer. When
+** finished, leave *pz pointing to the first character past the end of
+** the integer. The *pLen parameter holds the length of the string
+** in *pz and is decremented once for each character in the integer.
+*/
+static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
+ static const signed char zValue[] = {
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
+ -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
+ 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
+ -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
+ };
+ unsigned int v = 0;
+ int c;
+ unsigned char *z = (unsigned char*)*pz;
+ unsigned char *zStart = z;
+ while( (c = zValue[0x7f&*(z++)])>=0 ){
+ v = (v<<6) + c;
+ }
+ z--;
+ *pLen -= z - zStart;
+ *pz = (char*)z;
+ return v;
+}
+
+#if RBU_ENABLE_DELTA_CKSUM
+/*
+** Compute a 32-bit checksum on the N-byte buffer. Return the result.
+*/
+static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
+ const unsigned char *z = (const unsigned char *)zIn;
+ unsigned sum0 = 0;
+ unsigned sum1 = 0;
+ unsigned sum2 = 0;
+ unsigned sum3 = 0;
+ while(N >= 16){
+ sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
+ sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
+ sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
+ sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
+ z += 16;
+ N -= 16;
+ }
+ while(N >= 4){
+ sum0 += z[0];
+ sum1 += z[1];
+ sum2 += z[2];
+ sum3 += z[3];
+ z += 4;
+ N -= 4;
+ }
+ sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
+ switch(N){
+ case 3: sum3 += (z[2] << 8);
+ case 2: sum3 += (z[1] << 16);
+ case 1: sum3 += (z[0] << 24);
+ default: ;
+ }
+ return sum3;
+}
+#endif
+
+/*
+** Apply a delta.
+**
+** The output buffer should be big enough to hold the whole output
+** file and a NUL terminator at the end. The delta_output_size()
+** routine will determine this size for you.
+**
+** The delta string should be null-terminated. But the delta string
+** may contain embedded NUL characters (if the input and output are
+** binary files) so we also have to pass in the length of the delta in
+** the lenDelta parameter.
+**
+** This function returns the size of the output file in bytes (excluding
+** the final NUL terminator character). Except, if the delta string is
+** malformed or intended for use with a source file other than zSrc,
+** then this routine returns -1.
+**
+** Refer to the delta_create() documentation above for a description
+** of the delta file format.
+*/
+static int rbuDeltaApply(
+ const char *zSrc, /* The source or pattern file */
+ int lenSrc, /* Length of the source file */
+ const char *zDelta, /* Delta to apply to the pattern */
+ int lenDelta, /* Length of the delta */
+ char *zOut /* Write the output into this preallocated buffer */
+){
+ unsigned int limit;
+ unsigned int total = 0;
+#if RBU_ENABLE_DELTA_CKSUM
+ char *zOrigOut = zOut;
+#endif
+
+ limit = rbuDeltaGetInt(&zDelta, &lenDelta);
+ if( *zDelta!='\n' ){
+ /* ERROR: size integer not terminated by "\n" */
+ return -1;
+ }
+ zDelta++; lenDelta--;
+ while( *zDelta && lenDelta>0 ){
+ unsigned int cnt, ofst;
+ cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
+ switch( zDelta[0] ){
+ case '@': {
+ zDelta++; lenDelta--;
+ ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
+ if( lenDelta>0 && zDelta[0]!=',' ){
+ /* ERROR: copy command not terminated by ',' */
+ return -1;
+ }
+ zDelta++; lenDelta--;
+ total += cnt;
+ if( total>limit ){
+ /* ERROR: copy exceeds output file size */
+ return -1;
+ }
+ if( (int)(ofst+cnt) > lenSrc ){
+ /* ERROR: copy extends past end of input */
+ return -1;
+ }
+ memcpy(zOut, &zSrc[ofst], cnt);
+ zOut += cnt;
+ break;
+ }
+ case ':': {
+ zDelta++; lenDelta--;
+ total += cnt;
+ if( total>limit ){
+ /* ERROR: insert command gives an output larger than predicted */
+ return -1;
+ }
+ if( (int)cnt>lenDelta ){
+ /* ERROR: insert count exceeds size of delta */
+ return -1;
+ }
+ memcpy(zOut, zDelta, cnt);
+ zOut += cnt;
+ zDelta += cnt;
+ lenDelta -= cnt;
+ break;
+ }
+ case ';': {
+ zDelta++; lenDelta--;
+ zOut[0] = 0;
+#if RBU_ENABLE_DELTA_CKSUM
+ if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
+ /* ERROR: bad checksum */
+ return -1;
+ }
+#endif
+ if( total!=limit ){
+ /* ERROR: generated size does not match predicted size */
+ return -1;
+ }
+ return total;
+ }
+ default: {
+ /* ERROR: unknown delta operator */
+ return -1;
+ }
+ }
+ }
+ /* ERROR: unterminated delta */
+ return -1;
+}
+
+static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
+ int size;
+ size = rbuDeltaGetInt(&zDelta, &lenDelta);
+ if( *zDelta!='\n' ){
+ /* ERROR: size integer not terminated by "\n" */
+ return -1;
+ }
+ return size;
+}
+
+/*
+** End of code taken from fossil.
+*************************************************************************/
+
+/*
+** Implementation of SQL scalar function rbu_fossil_delta().
+**
+** This function applies a fossil delta patch to a blob. Exactly two
+** arguments must be passed to this function. The first is the blob to
+** patch and the second the patch to apply. If no error occurs, this
+** function returns the patched blob.
+*/
+static void rbuFossilDeltaFunc(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ const char *aDelta;
+ int nDelta;
+ const char *aOrig;
+ int nOrig;
+
+ int nOut;
+ int nOut2;
+ char *aOut;
+
+ assert( argc==2 );
+
+ nOrig = sqlite3_value_bytes(argv[0]);
+ aOrig = (const char*)sqlite3_value_blob(argv[0]);
+ nDelta = sqlite3_value_bytes(argv[1]);
+ aDelta = (const char*)sqlite3_value_blob(argv[1]);
+
+ /* Figure out the size of the output */
+ nOut = rbuDeltaOutputSize(aDelta, nDelta);
+ if( nOut<0 ){
+ sqlite3_result_error(context, "corrupt fossil delta", -1);
+ return;
+ }
+
+ aOut = sqlite3_malloc(nOut+1);
+ if( aOut==0 ){
+ sqlite3_result_error_nomem(context);
+ }else{
+ nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
+ if( nOut2!=nOut ){
+ sqlite3_free(aOut);
+ sqlite3_result_error(context, "corrupt fossil delta", -1);
+ }else{
+ sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
+ }
+ }
+}
+
+
+/*
+** Prepare the SQL statement in buffer zSql against database handle db.
+** If successful, set *ppStmt to point to the new statement and return
+** SQLITE_OK.
+**
+** Otherwise, if an error does occur, set *ppStmt to NULL and return
+** an SQLite error code. Additionally, set output variable *pzErrmsg to
+** point to a buffer containing an error message. It is the responsibility
+** of the caller to (eventually) free this buffer using sqlite3_free().
+*/
+static int prepareAndCollectError(
+ sqlite3 *db,
+ sqlite3_stmt **ppStmt,
+ char **pzErrmsg,
+ const char *zSql
+){
+ int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
+ if( rc!=SQLITE_OK ){
+ *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
+ *ppStmt = 0;
+ }
+ return rc;
+}
+
+/*
+** Reset the SQL statement passed as the first argument. Return a copy
+** of the value returned by sqlite3_reset().
+**
+** If an error has occurred, then set *pzErrmsg to point to a buffer
+** containing an error message. It is the responsibility of the caller
+** to eventually free this buffer using sqlite3_free().
+*/
+static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
+ int rc = sqlite3_reset(pStmt);
+ if( rc!=SQLITE_OK ){
+ *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
+ }
+ return rc;
+}
+
+/*
+** Unless it is NULL, argument zSql points to a buffer allocated using
+** sqlite3_malloc containing an SQL statement. This function prepares the SQL
+** statement against database db and frees the buffer. If statement
+** compilation is successful, *ppStmt is set to point to the new statement
+** handle and SQLITE_OK is returned.
+**
+** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
+** returned. In this case, *pzErrmsg may also be set to point to an error
+** message. It is the responsibility of the caller to free this error message
+** buffer using sqlite3_free().
+**
+** If argument zSql is NULL, this function assumes that an OOM has occurred.
+** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
+*/
+static int prepareFreeAndCollectError(
+ sqlite3 *db,
+ sqlite3_stmt **ppStmt,
+ char **pzErrmsg,
+ char *zSql
+){
+ int rc;
+ assert( *pzErrmsg==0 );
+ if( zSql==0 ){
+ rc = SQLITE_NOMEM;
+ *ppStmt = 0;
+ }else{
+ rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
+ sqlite3_free(zSql);
+ }
+ return rc;
+}
+
+/*
+** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
+** by an earlier call to rbuObjIterCacheTableInfo().
+*/
+static void rbuObjIterFreeCols(RbuObjIter *pIter){
+ int i;
+ for(i=0; i<pIter->nTblCol; i++){
+ sqlite3_free(pIter->azTblCol[i]);
+ sqlite3_free(pIter->azTblType[i]);
+ }
+ sqlite3_free(pIter->azTblCol);
+ pIter->azTblCol = 0;
+ pIter->azTblType = 0;
+ pIter->aiSrcOrder = 0;
+ pIter->abTblPk = 0;
+ pIter->abNotNull = 0;
+ pIter->nTblCol = 0;
+ pIter->eType = 0; /* Invalid value */
+}
+
+/*
+** Finalize all statements and free all allocations that are specific to
+** the current object (table/index pair).
+*/
+static void rbuObjIterClearStatements(RbuObjIter *pIter){
+ RbuUpdateStmt *pUp;
+
+ sqlite3_finalize(pIter->pSelect);
+ sqlite3_finalize(pIter->pInsert);
+ sqlite3_finalize(pIter->pDelete);
+ sqlite3_finalize(pIter->pTmpInsert);
+ pUp = pIter->pRbuUpdate;
+ while( pUp ){
+ RbuUpdateStmt *pTmp = pUp->pNext;
+ sqlite3_finalize(pUp->pUpdate);
+ sqlite3_free(pUp);
+ pUp = pTmp;
+ }
+ sqlite3_free(pIter->aIdxCol);
+ sqlite3_free(pIter->zIdxSql);
+
+ pIter->pSelect = 0;
+ pIter->pInsert = 0;
+ pIter->pDelete = 0;
+ pIter->pRbuUpdate = 0;
+ pIter->pTmpInsert = 0;
+ pIter->nCol = 0;
+ pIter->nIdxCol = 0;
+ pIter->aIdxCol = 0;
+ pIter->zIdxSql = 0;
+}
+
+/*
+** Clean up any resources allocated as part of the iterator object passed
+** as the only argument.
+*/
+static void rbuObjIterFinalize(RbuObjIter *pIter){
+ rbuObjIterClearStatements(pIter);
+ sqlite3_finalize(pIter->pTblIter);
+ sqlite3_finalize(pIter->pIdxIter);
+ rbuObjIterFreeCols(pIter);
+ memset(pIter, 0, sizeof(RbuObjIter));
+}
+
+/*
+** Advance the iterator to the next position.
+**
+** If no error occurs, SQLITE_OK is returned and the iterator is left
+** pointing to the next entry. Otherwise, an error code and message is
+** left in the RBU handle passed as the first argument. A copy of the
+** error code is returned.
+*/
+static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
+ int rc = p->rc;
+ if( rc==SQLITE_OK ){
+
+ /* Free any SQLite statements used while processing the previous object */
+ rbuObjIterClearStatements(pIter);
+ if( pIter->zIdx==0 ){
+ rc = sqlite3_exec(p->dbMain,
+ "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
+ "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
+ "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
+ "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
+ , 0, 0, &p->zErrmsg
+ );
+ }
+
+ if( rc==SQLITE_OK ){
+ if( pIter->bCleanup ){
+ rbuObjIterFreeCols(pIter);
+ pIter->bCleanup = 0;
+ rc = sqlite3_step(pIter->pTblIter);
+ if( rc!=SQLITE_ROW ){
+ rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
+ pIter->zTbl = 0;
+ }else{
+ pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
+ pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
+ rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
+ }
+ }else{
+ if( pIter->zIdx==0 ){
+ sqlite3_stmt *pIdx = pIter->pIdxIter;
+ rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_step(pIter->pIdxIter);
+ if( rc!=SQLITE_ROW ){
+ rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
+ pIter->bCleanup = 1;
+ pIter->zIdx = 0;
+ }else{
+ pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
+ pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
+ pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
+ rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
+ }
+ }
+ }
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ rbuObjIterFinalize(pIter);
+ p->rc = rc;
+ }
+ return rc;
+}
+
+
+/*
+** The implementation of the rbu_target_name() SQL function. This function
+** accepts one or two arguments. The first argument is the name of a table -
+** the name of a table in the RBU database. The second, if it is present, is 1
+** for a view or 0 for a table.
+**
+** For a non-vacuum RBU handle, if the table name matches the pattern:
+**
+** data[0-9]_<name>
+**
+** where <name> is any sequence of 1 or more characters, <name> is returned.
+** Otherwise, if the only argument does not match the above pattern, an SQL
+** NULL is returned.
+**
+** "data_t1" -> "t1"
+** "data0123_t2" -> "t2"
+** "dataAB_t3" -> NULL
+**
+** For an rbu vacuum handle, a copy of the first argument is returned if
+** the second argument is either missing or 0 (not a view).
+*/
+static void rbuTargetNameFunc(
+ sqlite3_context *pCtx,
+ int argc,
+ sqlite3_value **argv
+){
+ sqlite3rbu *p = sqlite3_user_data(pCtx);
+ const char *zIn;
+ assert( argc==1 || argc==2 );
+
+ zIn = (const char*)sqlite3_value_text(argv[0]);
+ if( zIn ){
+ if( rbuIsVacuum(p) ){
+ assert( argc==2 || argc==1 );
+ if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
+ sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
+ }
+ }else{
+ if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
+ int i;
+ for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
+ if( zIn[i]=='_' && zIn[i+1] ){
+ sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
+ }
+ }
+ }
+ }
+}
+
+/*
+** Initialize the iterator structure passed as the second argument.
+**
+** If no error occurs, SQLITE_OK is returned and the iterator is left
+** pointing to the first entry. Otherwise, an error code and message is
+** left in the RBU handle passed as the first argument. A copy of the
+** error code is returned.
+*/
+static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
+ int rc;
+ memset(pIter, 0, sizeof(RbuObjIter));
+
+ rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
+ sqlite3_mprintf(
+ "SELECT rbu_target_name(name, type='view') AS target, name "
+ "FROM sqlite_schema "
+ "WHERE type IN ('table', 'view') AND target IS NOT NULL "
+ " %s "
+ "ORDER BY name"
+ , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
+
+ if( rc==SQLITE_OK ){
+ rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
+ "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
+ " FROM main.sqlite_schema "
+ " WHERE type='index' AND tbl_name = ?"
+ );
+ }
+
+ pIter->bCleanup = 1;
+ p->rc = rc;
+ return rbuObjIterNext(p, pIter);
+}
+
+/*
+** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
+** an error code is stored in the RBU handle passed as the first argument.
+**
+** If an error has already occurred (p->rc is already set to something other
+** than SQLITE_OK), then this function returns NULL without modifying the
+** stored error code. In this case it still calls sqlite3_free() on any
+** printf() parameters associated with %z conversions.
+*/
+static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
+ char *zSql = 0;
+ va_list ap;
+ va_start(ap, zFmt);
+ zSql = sqlite3_vmprintf(zFmt, ap);
+ if( p->rc==SQLITE_OK ){
+ if( zSql==0 ) p->rc = SQLITE_NOMEM;
+ }else{
+ sqlite3_free(zSql);
+ zSql = 0;
+ }
+ va_end(ap);
+ return zSql;
+}
+
+/*
+** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
+** arguments are the usual subsitution values. This function performs
+** the printf() style substitutions and executes the result as an SQL
+** statement on the RBU handles database.
+**
+** If an error occurs, an error code and error message is stored in the
+** RBU handle. If an error has already occurred when this function is
+** called, it is a no-op.
+*/
+static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
+ va_list ap;
+ char *zSql;
+ va_start(ap, zFmt);
+ zSql = sqlite3_vmprintf(zFmt, ap);
+ if( p->rc==SQLITE_OK ){
+ if( zSql==0 ){
+ p->rc = SQLITE_NOMEM;
+ }else{
+ p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
+ }
+ }
+ sqlite3_free(zSql);
+ va_end(ap);
+ return p->rc;
+}
+
+/*
+** Attempt to allocate and return a pointer to a zeroed block of nByte
+** bytes.
+**
+** If an error (i.e. an OOM condition) occurs, return NULL and leave an
+** error code in the rbu handle passed as the first argument. Or, if an
+** error has already occurred when this function is called, return NULL
+** immediately without attempting the allocation or modifying the stored
+** error code.
+*/
+static void *rbuMalloc(sqlite3rbu *p, sqlite3_int64 nByte){
+ void *pRet = 0;
+ if( p->rc==SQLITE_OK ){
+ assert( nByte>0 );
+ pRet = sqlite3_malloc64(nByte);
+ if( pRet==0 ){
+ p->rc = SQLITE_NOMEM;
+ }else{
+ memset(pRet, 0, nByte);
+ }
+ }
+ return pRet;
+}
+
+
+/*
+** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
+** there is room for at least nCol elements. If an OOM occurs, store an
+** error code in the RBU handle passed as the first argument.
+*/
+static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
+ sqlite3_int64 nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
+ char **azNew;
+
+ azNew = (char**)rbuMalloc(p, nByte);
+ if( azNew ){
+ pIter->azTblCol = azNew;
+ pIter->azTblType = &azNew[nCol];
+ pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
+ pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
+ pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
+ pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
+ }
+}
+
+/*
+** The first argument must be a nul-terminated string. This function
+** returns a copy of the string in memory obtained from sqlite3_malloc().
+** It is the responsibility of the caller to eventually free this memory
+** using sqlite3_free().
+**
+** If an OOM condition is encountered when attempting to allocate memory,
+** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
+** if the allocation succeeds, (*pRc) is left unchanged.
+*/
+static char *rbuStrndup(const char *zStr, int *pRc){
+ char *zRet = 0;
+
+ if( *pRc==SQLITE_OK ){
+ if( zStr ){
+ size_t nCopy = strlen(zStr) + 1;
+ zRet = (char*)sqlite3_malloc64(nCopy);
+ if( zRet ){
+ memcpy(zRet, zStr, nCopy);
+ }else{
+ *pRc = SQLITE_NOMEM;
+ }
+ }
+ }
+
+ return zRet;
+}
+
+/*
+** Finalize the statement passed as the second argument.
+**
+** If the sqlite3_finalize() call indicates that an error occurs, and the
+** rbu handle error code is not already set, set the error code and error
+** message accordingly.
+*/
+static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
+ sqlite3 *db = sqlite3_db_handle(pStmt);
+ int rc = sqlite3_finalize(pStmt);
+ if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
+ p->rc = rc;
+ p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
+ }
+}
+
+/* Determine the type of a table.
+**
+** peType is of type (int*), a pointer to an output parameter of type
+** (int). This call sets the output parameter as follows, depending
+** on the type of the table specified by parameters dbName and zTbl.
+**
+** RBU_PK_NOTABLE: No such table.
+** RBU_PK_NONE: Table has an implicit rowid.
+** RBU_PK_IPK: Table has an explicit IPK column.
+** RBU_PK_EXTERNAL: Table has an external PK index.
+** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
+** RBU_PK_VTAB: Table is a virtual table.
+**
+** Argument *piPk is also of type (int*), and also points to an output
+** parameter. Unless the table has an external primary key index
+** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
+** if the table does have an external primary key index, then *piPk
+** is set to the root page number of the primary key index before
+** returning.
+**
+** ALGORITHM:
+**
+** if( no entry exists in sqlite_schema ){
+** return RBU_PK_NOTABLE
+** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
+** return RBU_PK_VTAB
+** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
+** if( the index that is the pk exists in sqlite_schema ){
+** *piPK = rootpage of that index.
+** return RBU_PK_EXTERNAL
+** }else{
+** return RBU_PK_WITHOUT_ROWID
+** }
+** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
+** return RBU_PK_IPK
+** }else{
+** return RBU_PK_NONE
+** }
+*/
+static void rbuTableType(
+ sqlite3rbu *p,
+ const char *zTab,
+ int *peType,
+ int *piTnum,
+ int *piPk
+){
+ /*
+ ** 0) SELECT count(*) FROM sqlite_schema where name=%Q AND IsVirtual(%Q)
+ ** 1) PRAGMA index_list = ?
+ ** 2) SELECT count(*) FROM sqlite_schema where name=%Q
+ ** 3) PRAGMA table_info = ?
+ */
+ sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
+
+ *peType = RBU_PK_NOTABLE;
+ *piPk = 0;
+
+ assert( p->rc==SQLITE_OK );
+ p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
+ sqlite3_mprintf(
+ "SELECT (sql LIKE 'create virtual%%'), rootpage"
+ " FROM sqlite_schema"
+ " WHERE name=%Q", zTab
+ ));
+ if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
+ /* Either an error, or no such table. */
+ goto rbuTableType_end;
+ }
+ if( sqlite3_column_int(aStmt[0], 0) ){
+ *peType = RBU_PK_VTAB; /* virtual table */
+ goto rbuTableType_end;
+ }
+ *piTnum = sqlite3_column_int(aStmt[0], 1);
+
+ p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
+ sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
+ );
+ if( p->rc ) goto rbuTableType_end;
+ while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
+ const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
+ const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
+ if( zOrig && zIdx && zOrig[0]=='p' ){
+ p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
+ sqlite3_mprintf(
+ "SELECT rootpage FROM sqlite_schema WHERE name = %Q", zIdx
+ ));
+ if( p->rc==SQLITE_OK ){
+ if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
+ *piPk = sqlite3_column_int(aStmt[2], 0);
+ *peType = RBU_PK_EXTERNAL;
+ }else{
+ *peType = RBU_PK_WITHOUT_ROWID;
+ }
+ }
+ goto rbuTableType_end;
+ }
+ }
+
+ p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
+ sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
+ );
+ if( p->rc==SQLITE_OK ){
+ while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
+ if( sqlite3_column_int(aStmt[3],5)>0 ){
+ *peType = RBU_PK_IPK; /* explicit IPK column */
+ goto rbuTableType_end;
+ }
+ }
+ *peType = RBU_PK_NONE;
+ }
+
+rbuTableType_end: {
+ unsigned int i;
+ for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
+ rbuFinalize(p, aStmt[i]);
+ }
+ }
+}
+
+/*
+** This is a helper function for rbuObjIterCacheTableInfo(). It populates
+** the pIter->abIndexed[] array.
+*/
+static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
+ sqlite3_stmt *pList = 0;
+ int bIndex = 0;
+
+ if( p->rc==SQLITE_OK ){
+ memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
+ p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
+ sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
+ );
+ }
+
+ pIter->nIndex = 0;
+ while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
+ const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
+ int bPartial = sqlite3_column_int(pList, 4);
+ sqlite3_stmt *pXInfo = 0;
+ if( zIdx==0 ) break;
+ if( bPartial ){
+ memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol);
+ }
+ p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
+ sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
+ );
+ while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
+ int iCid = sqlite3_column_int(pXInfo, 1);
+ if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
+ if( iCid==-2 ){
+ memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol);
+ }
+ }
+ rbuFinalize(p, pXInfo);
+ bIndex = 1;
+ pIter->nIndex++;
+ }
+
+ if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
+ /* "PRAGMA index_list" includes the main PK b-tree */
+ pIter->nIndex--;
+ }
+
+ rbuFinalize(p, pList);
+ if( bIndex==0 ) pIter->abIndexed = 0;
+}
+
+
+/*
+** If they are not already populated, populate the pIter->azTblCol[],
+** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
+** the table (not index) that the iterator currently points to.
+**
+** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
+** an error does occur, an error code and error message are also left in
+** the RBU handle.
+*/
+static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
+ if( pIter->azTblCol==0 ){
+ sqlite3_stmt *pStmt = 0;
+ int nCol = 0;
+ int i; /* for() loop iterator variable */
+ int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
+ int iOrder = 0;
+ int iTnum = 0;
+
+ /* Figure out the type of table this step will deal with. */
+ assert( pIter->eType==0 );
+ rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
+ if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
+ p->rc = SQLITE_ERROR;
+ p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
+ }
+ if( p->rc ) return p->rc;
+ if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
+
+ assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
+ || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
+ || pIter->eType==RBU_PK_VTAB
+ );
+
+ /* Populate the azTblCol[] and nTblCol variables based on the columns
+ ** of the input table. Ignore any input table columns that begin with
+ ** "rbu_". */
+ p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
+ sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
+ );
+ if( p->rc==SQLITE_OK ){
+ nCol = sqlite3_column_count(pStmt);
+ rbuAllocateIterArrays(p, pIter, nCol);
+ }
+ for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
+ const char *zName = (const char*)sqlite3_column_name(pStmt, i);
+ if( sqlite3_strnicmp("rbu_", zName, 4) ){
+ char *zCopy = rbuStrndup(zName, &p->rc);
+ pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
+ pIter->azTblCol[pIter->nTblCol++] = zCopy;
+ }
+ else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
+ bRbuRowid = 1;
+ }
+ }
+ sqlite3_finalize(pStmt);
+ pStmt = 0;
+
+ if( p->rc==SQLITE_OK
+ && rbuIsVacuum(p)==0
+ && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
+ ){
+ p->rc = SQLITE_ERROR;
+ p->zErrmsg = sqlite3_mprintf(
+ "table %q %s rbu_rowid column", pIter->zDataTbl,
+ (bRbuRowid ? "may not have" : "requires")
+ );
+ }
+
+ /* Check that all non-HIDDEN columns in the destination table are also
+ ** present in the input table. Populate the abTblPk[], azTblType[] and
+ ** aiTblOrder[] arrays at the same time. */
+ if( p->rc==SQLITE_OK ){
+ p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
+ sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
+ );
+ }
+ while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
+ const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
+ if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
+ for(i=iOrder; i<pIter->nTblCol; i++){
+ if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
+ }
+ if( i==pIter->nTblCol ){
+ p->rc = SQLITE_ERROR;
+ p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
+ pIter->zDataTbl, zName
+ );
+ }else{
+ int iPk = sqlite3_column_int(pStmt, 5);
+ int bNotNull = sqlite3_column_int(pStmt, 3);
+ const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
+
+ if( i!=iOrder ){
+ SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
+ SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
+ }
+
+ pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
+ assert( iPk>=0 );
+ pIter->abTblPk[iOrder] = (u8)iPk;
+ pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
+ iOrder++;
+ }
+ }
+
+ rbuFinalize(p, pStmt);
+ rbuObjIterCacheIndexedCols(p, pIter);
+ assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
+ assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
+ }
+
+ return p->rc;
+}
+
+/*
+** This function constructs and returns a pointer to a nul-terminated
+** string containing some SQL clause or list based on one or more of the
+** column names currently stored in the pIter->azTblCol[] array.
+*/
+static char *rbuObjIterGetCollist(
+ sqlite3rbu *p, /* RBU object */
+ RbuObjIter *pIter /* Object iterator for column names */
+){
+ char *zList = 0;
+ const char *zSep = "";
+ int i;
+ for(i=0; i<pIter->nTblCol; i++){
+ const char *z = pIter->azTblCol[i];
+ zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
+ zSep = ", ";
+ }
+ return zList;
+}
+
+/*
+** Return a comma separated list of the quoted PRIMARY KEY column names,
+** in order, for the current table. Before each column name, add the text
+** zPre. After each column name, add the zPost text. Use zSeparator as
+** the separator text (usually ", ").
+*/
+static char *rbuObjIterGetPkList(
+ sqlite3rbu *p, /* RBU object */
+ RbuObjIter *pIter, /* Object iterator for column names */
+ const char *zPre, /* Before each quoted column name */
+ const char *zSeparator, /* Separator to use between columns */
+ const char *zPost /* After each quoted column name */
+){
+ int iPk = 1;
+ char *zRet = 0;
+ const char *zSep = "";
+ while( 1 ){
+ int i;
+ for(i=0; i<pIter->nTblCol; i++){
+ if( (int)pIter->abTblPk[i]==iPk ){
+ const char *zCol = pIter->azTblCol[i];
+ zRet = rbuMPrintf(p, "%z%s%s\"%w\"%s", zRet, zSep, zPre, zCol, zPost);
+ zSep = zSeparator;
+ break;
+ }
+ }
+ if( i==pIter->nTblCol ) break;
+ iPk++;
+ }
+ return zRet;
+}
+
+/*
+** This function is called as part of restarting an RBU vacuum within
+** stage 1 of the process (while the *-oal file is being built) while
+** updating a table (not an index). The table may be a rowid table or
+** a WITHOUT ROWID table. It queries the target database to find the
+** largest key that has already been written to the target table and
+** constructs a WHERE clause that can be used to extract the remaining
+** rows from the source table. For a rowid table, the WHERE clause
+** is of the form:
+**
+** "WHERE _rowid_ > ?"
+**
+** and for WITHOUT ROWID tables:
+**
+** "WHERE (key1, key2) > (?, ?)"
+**
+** Instead of "?" placeholders, the actual WHERE clauses created by
+** this function contain literal SQL values.
+*/
+static char *rbuVacuumTableStart(
+ sqlite3rbu *p, /* RBU handle */
+ RbuObjIter *pIter, /* RBU iterator object */
+ int bRowid, /* True for a rowid table */
+ const char *zWrite /* Target table name prefix */
+){
+ sqlite3_stmt *pMax = 0;
+ char *zRet = 0;
+ if( bRowid ){
+ p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg,
+ sqlite3_mprintf(
+ "SELECT max(_rowid_) FROM \"%s%w\"", zWrite, pIter->zTbl
+ )
+ );
+ if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
+ sqlite3_int64 iMax = sqlite3_column_int64(pMax, 0);
+ zRet = rbuMPrintf(p, " WHERE _rowid_ > %lld ", iMax);
+ }
+ rbuFinalize(p, pMax);
+ }else{
+ char *zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", " DESC");
+ char *zSelect = rbuObjIterGetPkList(p, pIter, "quote(", "||','||", ")");
+ char *zList = rbuObjIterGetPkList(p, pIter, "", ", ", "");
+
+ if( p->rc==SQLITE_OK ){
+ p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg,
+ sqlite3_mprintf(
+ "SELECT %s FROM \"%s%w\" ORDER BY %s LIMIT 1",
+ zSelect, zWrite, pIter->zTbl, zOrder
+ )
+ );
+ if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
+ const char *zVal = (const char*)sqlite3_column_text(pMax, 0);
+ zRet = rbuMPrintf(p, " WHERE (%s) > (%s) ", zList, zVal);
+ }
+ rbuFinalize(p, pMax);
+ }
+
+ sqlite3_free(zOrder);
+ sqlite3_free(zSelect);
+ sqlite3_free(zList);
+ }
+ return zRet;
+}
+
+/*
+** This function is called as part of restating an RBU vacuum when the
+** current operation is writing content to an index. If possible, it
+** queries the target index b-tree for the largest key already written to
+** it, then composes and returns an expression that can be used in a WHERE
+** clause to select the remaining required rows from the source table.
+** It is only possible to return such an expression if:
+**
+** * The index contains no DESC columns, and
+** * The last key written to the index before the operation was
+** suspended does not contain any NULL values.
+**
+** The expression is of the form:
+**
+** (index-field1, index-field2, ...) > (?, ?, ...)
+**
+** except that the "?" placeholders are replaced with literal values.
+**
+** If the expression cannot be created, NULL is returned. In this case,
+** the caller has to use an OFFSET clause to extract only the required
+** rows from the sourct table, just as it does for an RBU update operation.
+*/
+char *rbuVacuumIndexStart(
+ sqlite3rbu *p, /* RBU handle */
+ RbuObjIter *pIter /* RBU iterator object */
+){
+ char *zOrder = 0;
+ char *zLhs = 0;
+ char *zSelect = 0;
+ char *zVector = 0;
+ char *zRet = 0;
+ int bFailed = 0;
+ const char *zSep = "";
+ int iCol = 0;
+ sqlite3_stmt *pXInfo = 0;
+
+ p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
+ sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
+ );
+ while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
+ int iCid = sqlite3_column_int(pXInfo, 1);
+ const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
+ const char *zCol;
+ if( sqlite3_column_int(pXInfo, 3) ){
+ bFailed = 1;
+ break;
+ }
+
+ if( iCid<0 ){
+ if( pIter->eType==RBU_PK_IPK ){
+ int i;
+ for(i=0; pIter->abTblPk[i]==0; i++);
+ assert( i<pIter->nTblCol );
+ zCol = pIter->azTblCol[i];
+ }else{
+ zCol = "_rowid_";
+ }
+ }else{
+ zCol = pIter->azTblCol[iCid];
+ }
+
+ zLhs = rbuMPrintf(p, "%z%s \"%w\" COLLATE %Q",
+ zLhs, zSep, zCol, zCollate
+ );
+ zOrder = rbuMPrintf(p, "%z%s \"rbu_imp_%d%w\" COLLATE %Q DESC",
+ zOrder, zSep, iCol, zCol, zCollate
+ );
+ zSelect = rbuMPrintf(p, "%z%s quote(\"rbu_imp_%d%w\")",
+ zSelect, zSep, iCol, zCol
+ );
+ zSep = ", ";
+ iCol++;
+ }
+ rbuFinalize(p, pXInfo);
+ if( bFailed ) goto index_start_out;
+
+ if( p->rc==SQLITE_OK ){
+ sqlite3_stmt *pSel = 0;
+
+ p->rc = prepareFreeAndCollectError(p->dbMain, &pSel, &p->zErrmsg,
+ sqlite3_mprintf("SELECT %s FROM \"rbu_imp_%w\" ORDER BY %s LIMIT 1",
+ zSelect, pIter->zTbl, zOrder
+ )
+ );
+ if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSel) ){
+ zSep = "";
+ for(iCol=0; iCol<pIter->nCol; iCol++){
+ const char *zQuoted = (const char*)sqlite3_column_text(pSel, iCol);
+ if( zQuoted[0]=='N' ){
+ bFailed = 1;
+ break;
+ }
+ zVector = rbuMPrintf(p, "%z%s%s", zVector, zSep, zQuoted);
+ zSep = ", ";
+ }
+
+ if( !bFailed ){
+ zRet = rbuMPrintf(p, "(%s) > (%s)", zLhs, zVector);
+ }
+ }
+ rbuFinalize(p, pSel);
+ }
+
+ index_start_out:
+ sqlite3_free(zOrder);
+ sqlite3_free(zSelect);
+ sqlite3_free(zVector);
+ sqlite3_free(zLhs);
+ return zRet;
+}
+
+/*
+** This function is used to create a SELECT list (the list of SQL
+** expressions that follows a SELECT keyword) for a SELECT statement
+** used to read from an data_xxx or rbu_tmp_xxx table while updating the
+** index object currently indicated by the iterator object passed as the
+** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
+** to obtain the required information.
+**
+** If the index is of the following form:
+**
+** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
+**
+** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
+** "ipk", the returned string is:
+**
+** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
+**
+** As well as the returned string, three other malloc'd strings are
+** returned via output parameters. As follows:
+**
+** pzImposterCols: ...
+** pzImposterPk: ...
+** pzWhere: ...
+*/
+static char *rbuObjIterGetIndexCols(
+ sqlite3rbu *p, /* RBU object */
+ RbuObjIter *pIter, /* Object iterator for column names */
+ char **pzImposterCols, /* OUT: Columns for imposter table */
+ char **pzImposterPk, /* OUT: Imposter PK clause */
+ char **pzWhere, /* OUT: WHERE clause */
+ int *pnBind /* OUT: Trbul number of columns */
+){
+ int rc = p->rc; /* Error code */
+ int rc2; /* sqlite3_finalize() return code */
+ char *zRet = 0; /* String to return */
+ char *zImpCols = 0; /* String to return via *pzImposterCols */
+ char *zImpPK = 0; /* String to return via *pzImposterPK */
+ char *zWhere = 0; /* String to return via *pzWhere */
+ int nBind = 0; /* Value to return via *pnBind */
+ const char *zCom = ""; /* Set to ", " later on */
+ const char *zAnd = ""; /* Set to " AND " later on */
+ sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
+
+ if( rc==SQLITE_OK ){
+ assert( p->zErrmsg==0 );
+ rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
+ sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
+ );
+ }
+
+ while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
+ int iCid = sqlite3_column_int(pXInfo, 1);
+ int bDesc = sqlite3_column_int(pXInfo, 3);
+ const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
+ const char *zCol = 0;
+ const char *zType;
+
+ if( iCid==-2 ){
+ int iSeq = sqlite3_column_int(pXInfo, 0);
+ zRet = sqlite3_mprintf("%z%s(%.*s) COLLATE %Q", zRet, zCom,
+ pIter->aIdxCol[iSeq].nSpan, pIter->aIdxCol[iSeq].zSpan, zCollate
+ );
+ zType = "";
+ }else {
+ if( iCid<0 ){
+ /* An integer primary key. If the table has an explicit IPK, use
+ ** its name. Otherwise, use "rbu_rowid". */
+ if( pIter->eType==RBU_PK_IPK ){
+ int i;
+ for(i=0; pIter->abTblPk[i]==0; i++);
+ assert( i<pIter->nTblCol );
+ zCol = pIter->azTblCol[i];
+ }else if( rbuIsVacuum(p) ){
+ zCol = "_rowid_";
+ }else{
+ zCol = "rbu_rowid";
+ }
+ zType = "INTEGER";
+ }else{
+ zCol = pIter->azTblCol[iCid];
+ zType = pIter->azTblType[iCid];
+ }
+ zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom,zCol,zCollate);
+ }
+
+ if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
+ const char *zOrder = (bDesc ? " DESC" : "");
+ zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
+ zImpPK, zCom, nBind, zCol, zOrder
+ );
+ }
+ zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
+ zImpCols, zCom, nBind, zCol, zType, zCollate
+ );
+ zWhere = sqlite3_mprintf(
+ "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
+ );
+ if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
+ zCom = ", ";
+ zAnd = " AND ";
+ nBind++;
+ }
+
+ rc2 = sqlite3_finalize(pXInfo);
+ if( rc==SQLITE_OK ) rc = rc2;
+
+ if( rc!=SQLITE_OK ){
+ sqlite3_free(zRet);
+ sqlite3_free(zImpCols);
+ sqlite3_free(zImpPK);
+ sqlite3_free(zWhere);
+ zRet = 0;
+ zImpCols = 0;
+ zImpPK = 0;
+ zWhere = 0;
+ p->rc = rc;
+ }
+
+ *pzImposterCols = zImpCols;
+ *pzImposterPk = zImpPK;
+ *pzWhere = zWhere;
+ *pnBind = nBind;
+ return zRet;
+}
+
+/*
+** Assuming the current table columns are "a", "b" and "c", and the zObj
+** paramter is passed "old", return a string of the form:
+**
+** "old.a, old.b, old.b"
+**
+** With the column names escaped.
+**
+** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
+** the text ", old._rowid_" to the returned value.
+*/
+static char *rbuObjIterGetOldlist(
+ sqlite3rbu *p,
+ RbuObjIter *pIter,
+ const char *zObj
+){
+ char *zList = 0;
+ if( p->rc==SQLITE_OK && pIter->abIndexed ){
+ const char *zS = "";
+ int i;
+ for(i=0; i<pIter->nTblCol; i++){
+ if( pIter->abIndexed[i] ){
+ const char *zCol = pIter->azTblCol[i];
+ zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
+ }else{
+ zList = sqlite3_mprintf("%z%sNULL", zList, zS);
+ }
+ zS = ", ";
+ if( zList==0 ){
+ p->rc = SQLITE_NOMEM;
+ break;
+ }
+ }
+
+ /* For a table with implicit rowids, append "old._rowid_" to the list. */
+ if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
+ zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
+ }
+ }
+ return zList;
+}
+
+/*
+** Return an expression that can be used in a WHERE clause to match the
+** primary key of the current table. For example, if the table is:
+**
+** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
+**
+** Return the string:
+**
+** "b = ?1 AND c = ?2"
+*/
+static char *rbuObjIterGetWhere(
+ sqlite3rbu *p,
+ RbuObjIter *pIter
+){
+ char *zList = 0;
+ if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
+ zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
+ }else if( pIter->eType==RBU_PK_EXTERNAL ){
+ const char *zSep = "";
+ int i;
+ for(i=0; i<pIter->nTblCol; i++){
+ if( pIter->abTblPk[i] ){
+ zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
+ zSep = " AND ";
+ }
+ }
+ zList = rbuMPrintf(p,
+ "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
+ );
+
+ }else{
+ const char *zSep = "";
+ int i;
+ for(i=0; i<pIter->nTblCol; i++){
+ if( pIter->abTblPk[i] ){
+ const char *zCol = pIter->azTblCol[i];
+ zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
+ zSep = " AND ";
+ }
+ }
+ }
+ return zList;
+}
+
+/*
+** The SELECT statement iterating through the keys for the current object
+** (p->objiter.pSelect) currently points to a valid row. However, there
+** is something wrong with the rbu_control value in the rbu_control value
+** stored in the (p->nCol+1)'th column. Set the error code and error message
+** of the RBU handle to something reflecting this.
+*/
+static void rbuBadControlError(sqlite3rbu *p){
+ p->rc = SQLITE_ERROR;
+ p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
+}
+
+
+/*
+** Return a nul-terminated string containing the comma separated list of
+** assignments that should be included following the "SET" keyword of
+** an UPDATE statement used to update the table object that the iterator
+** passed as the second argument currently points to if the rbu_control
+** column of the data_xxx table entry is set to zMask.
+**
+** The memory for the returned string is obtained from sqlite3_malloc().
+** It is the responsibility of the caller to eventually free it using
+** sqlite3_free().
+**
+** If an OOM error is encountered when allocating space for the new
+** string, an error code is left in the rbu handle passed as the first
+** argument and NULL is returned. Or, if an error has already occurred
+** when this function is called, NULL is returned immediately, without
+** attempting the allocation or modifying the stored error code.
+*/
+static char *rbuObjIterGetSetlist(
+ sqlite3rbu *p,
+ RbuObjIter *pIter,
+ const char *zMask
+){
+ char *zList = 0;
+ if( p->rc==SQLITE_OK ){
+ int i;
+
+ if( (int)strlen(zMask)!=pIter->nTblCol ){
+ rbuBadControlError(p);
+ }else{
+ const char *zSep = "";
+ for(i=0; i<pIter->nTblCol; i++){
+ char c = zMask[pIter->aiSrcOrder[i]];
+ if( c=='x' ){
+ zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
+ zList, zSep, pIter->azTblCol[i], i+1
+ );
+ zSep = ", ";
+ }
+ else if( c=='d' ){
+ zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
+ zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
+ );
+ zSep = ", ";
+ }
+ else if( c=='f' ){
+ zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
+ zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
+ );
+ zSep = ", ";
+ }
+ }
+ }
+ }
+ return zList;
+}
+
+/*
+** Return a nul-terminated string consisting of nByte comma separated
+** "?" expressions. For example, if nByte is 3, return a pointer to
+** a buffer containing the string "?,?,?".
+**
+** The memory for the returned string is obtained from sqlite3_malloc().
+** It is the responsibility of the caller to eventually free it using
+** sqlite3_free().
+**
+** If an OOM error is encountered when allocating space for the new
+** string, an error code is left in the rbu handle passed as the first
+** argument and NULL is returned. Or, if an error has already occurred
+** when this function is called, NULL is returned immediately, without
+** attempting the allocation or modifying the stored error code.
+*/
+static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
+ char *zRet = 0;
+ sqlite3_int64 nByte = 2*(sqlite3_int64)nBind + 1;
+
+ zRet = (char*)rbuMalloc(p, nByte);
+ if( zRet ){
+ int i;
+ for(i=0; i<nBind; i++){
+ zRet[i*2] = '?';
+ zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
+ }
+ }
+ return zRet;
+}
+
+/*
+** The iterator currently points to a table (not index) of type
+** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
+** declaration for the corresponding imposter table. For example,
+** if the iterator points to a table created as:
+**
+** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
+**
+** this function returns:
+**
+** PRIMARY KEY("b", "a" DESC)
+*/
+static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
+ char *z = 0;
+ assert( pIter->zIdx==0 );
+ if( p->rc==SQLITE_OK ){
+ const char *zSep = "PRIMARY KEY(";
+ sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
+ sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
+
+ p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
+ sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
+ );
+ while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
+ const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
+ if( zOrig && strcmp(zOrig, "pk")==0 ){
+ const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
+ if( zIdx ){
+ p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
+ sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
+ );
+ }
+ break;
+ }
+ }
+ rbuFinalize(p, pXList);
+
+ while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
+ if( sqlite3_column_int(pXInfo, 5) ){
+ /* int iCid = sqlite3_column_int(pXInfo, 0); */
+ const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
+ const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
+ z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
+ zSep = ", ";
+ }
+ }
+ z = rbuMPrintf(p, "%z)", z);
+ rbuFinalize(p, pXInfo);
+ }
+ return z;
+}
+
+/*
+** This function creates the second imposter table used when writing to
+** a table b-tree where the table has an external primary key. If the
+** iterator passed as the second argument does not currently point to
+** a table (not index) with an external primary key, this function is a
+** no-op.
+**
+** Assuming the iterator does point to a table with an external PK, this
+** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
+** used to access that PK index. For example, if the target table is
+** declared as follows:
+**
+** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
+**
+** then the imposter table schema is:
+**
+** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
+**
+*/
+static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
+ if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
+ int tnum = pIter->iPkTnum; /* Root page of PK index */
+ sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
+ const char *zIdx = 0; /* Name of PK index */
+ sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
+ const char *zComma = "";
+ char *zCols = 0; /* Used to build up list of table cols */
+ char *zPk = 0; /* Used to build up table PK declaration */
+
+ /* Figure out the name of the primary key index for the current table.
+ ** This is needed for the argument to "PRAGMA index_xinfo". Set
+ ** zIdx to point to a nul-terminated string containing this name. */
+ p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
+ "SELECT name FROM sqlite_schema WHERE rootpage = ?"
+ );
+ if( p->rc==SQLITE_OK ){
+ sqlite3_bind_int(pQuery, 1, tnum);
+ if( SQLITE_ROW==sqlite3_step(pQuery) ){
+ zIdx = (const char*)sqlite3_column_text(pQuery, 0);
+ }
+ }
+ if( zIdx ){
+ p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
+ sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
+ );
+ }
+ rbuFinalize(p, pQuery);
+
+ while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
+ int bKey = sqlite3_column_int(pXInfo, 5);
+ if( bKey ){
+ int iCid = sqlite3_column_int(pXInfo, 1);
+ int bDesc = sqlite3_column_int(pXInfo, 3);
+ const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
+ zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma,
+ iCid, pIter->azTblType[iCid], zCollate
+ );
+ zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
+ zComma = ", ";
+ }
+ }
+ zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
+ rbuFinalize(p, pXInfo);
+
+ sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
+ rbuMPrintfExec(p, p->dbMain,
+ "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
+ zCols, zPk
+ );
+ sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
+ }
+}
+
+/*
+** If an error has already occurred when this function is called, it
+** immediately returns zero (without doing any work). Or, if an error
+** occurs during the execution of this function, it sets the error code
+** in the sqlite3rbu object indicated by the first argument and returns
+** zero.
+**
+** The iterator passed as the second argument is guaranteed to point to
+** a table (not an index) when this function is called. This function
+** attempts to create any imposter table required to write to the main
+** table b-tree of the table before returning. Non-zero is returned if
+** an imposter table are created, or zero otherwise.
+**
+** An imposter table is required in all cases except RBU_PK_VTAB. Only
+** virtual tables are written to directly. The imposter table has the
+** same schema as the actual target table (less any UNIQUE constraints).
+** More precisely, the "same schema" means the same columns, types,
+** collation sequences. For tables that do not have an external PRIMARY
+** KEY, it also means the same PRIMARY KEY declaration.
+*/
+static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
+ if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
+ int tnum = pIter->iTnum;
+ const char *zComma = "";
+ char *zSql = 0;
+ int iCol;
+ sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
+
+ for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
+ const char *zPk = "";
+ const char *zCol = pIter->azTblCol[iCol];
+ const char *zColl = 0;
+
+ p->rc = sqlite3_table_column_metadata(
+ p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
+ );
+
+ if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
+ /* If the target table column is an "INTEGER PRIMARY KEY", add
+ ** "PRIMARY KEY" to the imposter table column declaration. */
+ zPk = "PRIMARY KEY ";
+ }
+ zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s",
+ zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
+ (pIter->abNotNull[iCol] ? " NOT NULL" : "")
+ );
+ zComma = ", ";
+ }
+
+ if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
+ char *zPk = rbuWithoutRowidPK(p, pIter);
+ if( zPk ){
+ zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
+ }
+ }
+
+ sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
+ rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
+ pIter->zTbl, zSql,
+ (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
+ );
+ sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
+ }
+}
+
+/*
+** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
+** Specifically a statement of the form:
+**
+** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
+**
+** The number of bound variables is equal to the number of columns in
+** the target table, plus one (for the rbu_control column), plus one more
+** (for the rbu_rowid column) if the target table is an implicit IPK or
+** virtual table.
+*/
+static void rbuObjIterPrepareTmpInsert(
+ sqlite3rbu *p,
+ RbuObjIter *pIter,
+ const char *zCollist,
+ const char *zRbuRowid
+){
+ int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
+ char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
+ if( zBind ){
+ assert( pIter->pTmpInsert==0 );
+ p->rc = prepareFreeAndCollectError(
+ p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
+ "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
+ p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
+ ));
+ }
+}
+
+static void rbuTmpInsertFunc(
+ sqlite3_context *pCtx,
+ int nVal,
+ sqlite3_value **apVal
+){
+ sqlite3rbu *p = sqlite3_user_data(pCtx);
+ int rc = SQLITE_OK;
+ int i;
+
+ assert( sqlite3_value_int(apVal[0])!=0
+ || p->objiter.eType==RBU_PK_EXTERNAL
+ || p->objiter.eType==RBU_PK_NONE
+ );
+ if( sqlite3_value_int(apVal[0])!=0 ){
+ p->nPhaseOneStep += p->objiter.nIndex;
+ }
+
+ for(i=0; rc==SQLITE_OK && i<nVal; i++){
+ rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
+ }
+ if( rc==SQLITE_OK ){
+ sqlite3_step(p->objiter.pTmpInsert);
+ rc = sqlite3_reset(p->objiter.pTmpInsert);
+ }
+
+ if( rc!=SQLITE_OK ){
+ sqlite3_result_error_code(pCtx, rc);
+ }
+}
+
+static char *rbuObjIterGetIndexWhere(sqlite3rbu *p, RbuObjIter *pIter){
+ sqlite3_stmt *pStmt = 0;
+ int rc = p->rc;
+ char *zRet = 0;
+
+ assert( pIter->zIdxSql==0 && pIter->nIdxCol==0 && pIter->aIdxCol==0 );
+
+ if( rc==SQLITE_OK ){
+ rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
+ "SELECT trim(sql) FROM sqlite_schema WHERE type='index' AND name=?"
+ );
+ }
+ if( rc==SQLITE_OK ){
+ int rc2;
+ rc = sqlite3_bind_text(pStmt, 1, pIter->zIdx, -1, SQLITE_STATIC);
+ if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
+ char *zSql = (char*)sqlite3_column_text(pStmt, 0);
+ if( zSql ){
+ pIter->zIdxSql = zSql = rbuStrndup(zSql, &rc);
+ }
+ if( zSql ){
+ int nParen = 0; /* Number of open parenthesis */
+ int i;
+ int iIdxCol = 0;
+ int nIdxAlloc = 0;
+ for(i=0; zSql[i]; i++){
+ char c = zSql[i];
+
+ /* If necessary, grow the pIter->aIdxCol[] array */
+ if( iIdxCol==nIdxAlloc ){
+ RbuSpan *aIdxCol = (RbuSpan*)sqlite3_realloc(
+ pIter->aIdxCol, (nIdxAlloc+16)*sizeof(RbuSpan)
+ );
+ if( aIdxCol==0 ){
+ rc = SQLITE_NOMEM;
+ break;
+ }
+ pIter->aIdxCol = aIdxCol;
+ nIdxAlloc += 16;
+ }
+
+ if( c=='(' ){
+ if( nParen==0 ){
+ assert( iIdxCol==0 );
+ pIter->aIdxCol[0].zSpan = &zSql[i+1];
+ }
+ nParen++;
+ }
+ else if( c==')' ){
+ nParen--;
+ if( nParen==0 ){
+ int nSpan = &zSql[i] - pIter->aIdxCol[iIdxCol].zSpan;
+ pIter->aIdxCol[iIdxCol++].nSpan = nSpan;
+ i++;
+ break;
+ }
+ }else if( c==',' && nParen==1 ){
+ int nSpan = &zSql[i] - pIter->aIdxCol[iIdxCol].zSpan;
+ pIter->aIdxCol[iIdxCol++].nSpan = nSpan;
+ pIter->aIdxCol[iIdxCol].zSpan = &zSql[i+1];
+ }else if( c=='"' || c=='\'' || c=='`' ){
+ for(i++; 1; i++){
+ if( zSql[i]==c ){
+ if( zSql[i+1]!=c ) break;
+ i++;
+ }
+ }
+ }else if( c=='[' ){
+ for(i++; 1; i++){
+ if( zSql[i]==']' ) break;
+ }
+ }else if( c=='-' && zSql[i+1]=='-' ){
+ for(i=i+2; zSql[i] && zSql[i]!='\n'; i++);
+ if( zSql[i]=='\0' ) break;
+ }else if( c=='/' && zSql[i+1]=='*' ){
+ for(i=i+2; zSql[i] && (zSql[i]!='*' || zSql[i+1]!='/'); i++);
+ if( zSql[i]=='\0' ) break;
+ i++;
+ }
+ }
+ if( zSql[i] ){
+ zRet = rbuStrndup(&zSql[i], &rc);
+ }
+ pIter->nIdxCol = iIdxCol;
+ }
+ }
+
+ rc2 = sqlite3_finalize(pStmt);
+ if( rc==SQLITE_OK ) rc = rc2;
+ }
+
+ p->rc = rc;
+ return zRet;
+}
+
+/*
+** Ensure that the SQLite statement handles required to update the
+** target database object currently indicated by the iterator passed
+** as the second argument are available.
+*/
+static int rbuObjIterPrepareAll(
+ sqlite3rbu *p,
+ RbuObjIter *pIter,
+ int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
+){
+ assert( pIter->bCleanup==0 );
+ if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
+ const int tnum = pIter->iTnum;
+ char *zCollist = 0; /* List of indexed columns */
+ char **pz = &p->zErrmsg;
+ const char *zIdx = pIter->zIdx;
+ char *zLimit = 0;
+
+ if( nOffset ){
+ zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
+ if( !zLimit ) p->rc = SQLITE_NOMEM;
+ }
+
+ if( zIdx ){
+ const char *zTbl = pIter->zTbl;
+ char *zImposterCols = 0; /* Columns for imposter table */
+ char *zImposterPK = 0; /* Primary key declaration for imposter */
+ char *zWhere = 0; /* WHERE clause on PK columns */
+ char *zBind = 0;
+ char *zPart = 0;
+ int nBind = 0;
+
+ assert( pIter->eType!=RBU_PK_VTAB );
+ zPart = rbuObjIterGetIndexWhere(p, pIter);
+ zCollist = rbuObjIterGetIndexCols(
+ p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
+ );
+ zBind = rbuObjIterGetBindlist(p, nBind);
+
+ /* Create the imposter table used to write to this index. */
+ sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
+ sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
+ rbuMPrintfExec(p, p->dbMain,
+ "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
+ zTbl, zImposterCols, zImposterPK
+ );
+ sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
+
+ /* Create the statement to insert index entries */
+ pIter->nCol = nBind;
+ if( p->rc==SQLITE_OK ){
+ p->rc = prepareFreeAndCollectError(
+ p->dbMain, &pIter->pInsert, &p->zErrmsg,
+ sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
+ );
+ }
+
+ /* And to delete index entries */
+ if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
+ p->rc = prepareFreeAndCollectError(
+ p->dbMain, &pIter->pDelete, &p->zErrmsg,
+ sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
+ );
+ }
+
+ /* Create the SELECT statement to read keys in sorted order */
+ if( p->rc==SQLITE_OK ){
+ char *zSql;
+ if( rbuIsVacuum(p) ){
+ char *zStart = 0;
+ if( nOffset ){
+ zStart = rbuVacuumIndexStart(p, pIter);
+ if( zStart ){
+ sqlite3_free(zLimit);
+ zLimit = 0;
+ }
+ }
+
+ zSql = sqlite3_mprintf(
+ "SELECT %s, 0 AS rbu_control FROM '%q' %s %s %s ORDER BY %s%s",
+ zCollist,
+ pIter->zDataTbl,
+ zPart,
+ (zStart ? (zPart ? "AND" : "WHERE") : ""), zStart,
+ zCollist, zLimit
+ );
+ sqlite3_free(zStart);
+ }else
+
+ if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
+ zSql = sqlite3_mprintf(
+ "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s ORDER BY %s%s",
+ zCollist, p->zStateDb, pIter->zDataTbl,
+ zPart, zCollist, zLimit
+ );
+ }else{
+ zSql = sqlite3_mprintf(
+ "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s "
+ "UNION ALL "
+ "SELECT %s, rbu_control FROM '%q' "
+ "%s %s typeof(rbu_control)='integer' AND rbu_control!=1 "
+ "ORDER BY %s%s",
+ zCollist, p->zStateDb, pIter->zDataTbl, zPart,
+ zCollist, pIter->zDataTbl,
+ zPart,
+ (zPart ? "AND" : "WHERE"),
+ zCollist, zLimit
+ );
+ }
+ if( p->rc==SQLITE_OK ){
+ p->rc = prepareFreeAndCollectError(p->dbRbu,&pIter->pSelect,pz,zSql);
+ }else{
+ sqlite3_free(zSql);
+ }
+ }
+
+ sqlite3_free(zImposterCols);
+ sqlite3_free(zImposterPK);
+ sqlite3_free(zWhere);
+ sqlite3_free(zBind);
+ sqlite3_free(zPart);
+ }else{
+ int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
+ ||(pIter->eType==RBU_PK_NONE)
+ ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
+ const char *zTbl = pIter->zTbl; /* Table this step applies to */
+ const char *zWrite; /* Imposter table name */
+
+ char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
+ char *zWhere = rbuObjIterGetWhere(p, pIter);
+ char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
+ char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
+
+ zCollist = rbuObjIterGetCollist(p, pIter);
+ pIter->nCol = pIter->nTblCol;
+
+ /* Create the imposter table or tables (if required). */
+ rbuCreateImposterTable(p, pIter);
+ rbuCreateImposterTable2(p, pIter);
+ zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
+
+ /* Create the INSERT statement to write to the target PK b-tree */
+ if( p->rc==SQLITE_OK ){
+ p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
+ sqlite3_mprintf(
+ "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
+ zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
+ )
+ );
+ }
+
+ /* Create the DELETE statement to write to the target PK b-tree.
+ ** Because it only performs INSERT operations, this is not required for
+ ** an rbu vacuum handle. */
+ if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
+ p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
+ sqlite3_mprintf(
+ "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
+ )
+ );
+ }
+
+ if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
+ const char *zRbuRowid = "";
+ if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
+ zRbuRowid = ", rbu_rowid";
+ }
+
+ /* Create the rbu_tmp_xxx table and the triggers to populate it. */
+ rbuMPrintfExec(p, p->dbRbu,
+ "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
+ "SELECT *%s FROM '%q' WHERE 0;"
+ , p->zStateDb, pIter->zDataTbl
+ , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
+ , pIter->zDataTbl
+ );
+
+ rbuMPrintfExec(p, p->dbMain,
+ "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
+ "BEGIN "
+ " SELECT rbu_tmp_insert(3, %s);"
+ "END;"
+
+ "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
+ "BEGIN "
+ " SELECT rbu_tmp_insert(3, %s);"
+ "END;"
+
+ "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
+ "BEGIN "
+ " SELECT rbu_tmp_insert(4, %s);"
+ "END;",
+ zWrite, zTbl, zOldlist,
+ zWrite, zTbl, zOldlist,
+ zWrite, zTbl, zNewlist
+ );
+
+ if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
+ rbuMPrintfExec(p, p->dbMain,
+ "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
+ "BEGIN "
+ " SELECT rbu_tmp_insert(0, %s);"
+ "END;",
+ zWrite, zTbl, zNewlist
+ );
+ }
+
+ rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
+ }
+
+ /* Create the SELECT statement to read keys from data_xxx */
+ if( p->rc==SQLITE_OK ){
+ const char *zRbuRowid = "";
+ char *zStart = 0;
+ char *zOrder = 0;
+ if( bRbuRowid ){
+ zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
+ }
+
+ if( rbuIsVacuum(p) ){
+ if( nOffset ){
+ zStart = rbuVacuumTableStart(p, pIter, bRbuRowid, zWrite);
+ if( zStart ){
+ sqlite3_free(zLimit);
+ zLimit = 0;
+ }
+ }
+ if( bRbuRowid ){
+ zOrder = rbuMPrintf(p, "_rowid_");
+ }else{
+ zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", "");
+ }
+ }
+
+ if( p->rc==SQLITE_OK ){
+ p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
+ sqlite3_mprintf(
+ "SELECT %s,%s rbu_control%s FROM '%q'%s %s %s %s",
+ zCollist,
+ (rbuIsVacuum(p) ? "0 AS " : ""),
+ zRbuRowid,
+ pIter->zDataTbl, (zStart ? zStart : ""),
+ (zOrder ? "ORDER BY" : ""), zOrder,
+ zLimit
+ )
+ );
+ }
+ sqlite3_free(zStart);
+ sqlite3_free(zOrder);
+ }
+
+ sqlite3_free(zWhere);
+ sqlite3_free(zOldlist);
+ sqlite3_free(zNewlist);
+ sqlite3_free(zBindings);
+ }
+ sqlite3_free(zCollist);
+ sqlite3_free(zLimit);
+ }
+
+ return p->rc;
+}
+
+/*
+** Set output variable *ppStmt to point to an UPDATE statement that may
+** be used to update the imposter table for the main table b-tree of the
+** table object that pIter currently points to, assuming that the
+** rbu_control column of the data_xyz table contains zMask.
+**
+** If the zMask string does not specify any columns to update, then this
+** is not an error. Output variable *ppStmt is set to NULL in this case.
+*/
+static int rbuGetUpdateStmt(
+ sqlite3rbu *p, /* RBU handle */
+ RbuObjIter *pIter, /* Object iterator */
+ const char *zMask, /* rbu_control value ('x.x.') */
+ sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
+){
+ RbuUpdateStmt **pp;
+ RbuUpdateStmt *pUp = 0;
+ int nUp = 0;
+
+ /* In case an error occurs */
+ *ppStmt = 0;
+
+ /* Search for an existing statement. If one is found, shift it to the front
+ ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
+ ** to the number of statements currently in the cache and pUp to the
+ ** last object in the list. */
+ for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
+ pUp = *pp;
+ if( strcmp(pUp->zMask, zMask)==0 ){
+ *pp = pUp->pNext;
+ pUp->pNext = pIter->pRbuUpdate;
+ pIter->pRbuUpdate = pUp;
+ *ppStmt = pUp->pUpdate;
+ return SQLITE_OK;
+ }
+ nUp++;
+ }
+ assert( pUp==0 || pUp->pNext==0 );
+
+ if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
+ for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
+ *pp = 0;
+ sqlite3_finalize(pUp->pUpdate);
+ pUp->pUpdate = 0;
+ }else{
+ pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
+ }
+
+ if( pUp ){
+ char *zWhere = rbuObjIterGetWhere(p, pIter);
+ char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
+ char *zUpdate = 0;
+
+ pUp->zMask = (char*)&pUp[1];
+ memcpy(pUp->zMask, zMask, pIter->nTblCol);
+ pUp->pNext = pIter->pRbuUpdate;
+ pIter->pRbuUpdate = pUp;
+
+ if( zSet ){
+ const char *zPrefix = "";
+
+ if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
+ zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
+ zPrefix, pIter->zTbl, zSet, zWhere
+ );
+ p->rc = prepareFreeAndCollectError(
+ p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
+ );
+ *ppStmt = pUp->pUpdate;
+ }
+ sqlite3_free(zWhere);
+ sqlite3_free(zSet);
+ }
+
+ return p->rc;
+}
+
+static sqlite3 *rbuOpenDbhandle(
+ sqlite3rbu *p,
+ const char *zName,
+ int bUseVfs
+){
+ sqlite3 *db = 0;
+ if( p->rc==SQLITE_OK ){
+ const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
+ p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
+ if( p->rc ){
+ p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
+ sqlite3_close(db);
+ db = 0;
+ }
+ }
+ return db;
+}
+
+/*
+** Free an RbuState object allocated by rbuLoadState().
+*/
+static void rbuFreeState(RbuState *p){
+ if( p ){
+ sqlite3_free(p->zTbl);
+ sqlite3_free(p->zDataTbl);
+ sqlite3_free(p->zIdx);
+ sqlite3_free(p);
+ }
+}
+
+/*
+** Allocate an RbuState object and load the contents of the rbu_state
+** table into it. Return a pointer to the new object. It is the
+** responsibility of the caller to eventually free the object using
+** sqlite3_free().
+**
+** If an error occurs, leave an error code and message in the rbu handle
+** and return NULL.
+*/
+static RbuState *rbuLoadState(sqlite3rbu *p){
+ RbuState *pRet = 0;
+ sqlite3_stmt *pStmt = 0;
+ int rc;
+ int rc2;
+
+ pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
+ if( pRet==0 ) return 0;
+
+ rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
+ sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
+ );
+ while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
+ switch( sqlite3_column_int(pStmt, 0) ){
+ case RBU_STATE_STAGE:
+ pRet->eStage = sqlite3_column_int(pStmt, 1);
+ if( pRet->eStage!=RBU_STAGE_OAL
+ && pRet->eStage!=RBU_STAGE_MOVE
+ && pRet->eStage!=RBU_STAGE_CKPT
+ ){
+ p->rc = SQLITE_CORRUPT;
+ }
+ break;
+
+ case RBU_STATE_TBL:
+ pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
+ break;
+
+ case RBU_STATE_IDX:
+ pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
+ break;
+
+ case RBU_STATE_ROW:
+ pRet->nRow = sqlite3_column_int(pStmt, 1);
+ break;
+
+ case RBU_STATE_PROGRESS:
+ pRet->nProgress = sqlite3_column_int64(pStmt, 1);
+ break;
+
+ case RBU_STATE_CKPT:
+ pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
+ break;
+
+ case RBU_STATE_COOKIE:
+ pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
+ break;
+
+ case RBU_STATE_OALSZ:
+ pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
+ break;
+
+ case RBU_STATE_PHASEONESTEP:
+ pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
+ break;
+
+ case RBU_STATE_DATATBL:
+ pRet->zDataTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
+ break;
+
+ default:
+ rc = SQLITE_CORRUPT;
+ break;
+ }
+ }
+ rc2 = sqlite3_finalize(pStmt);
+ if( rc==SQLITE_OK ) rc = rc2;
+
+ p->rc = rc;
+ return pRet;
+}
+
+
+/*
+** Open the database handle and attach the RBU database as "rbu". If an
+** error occurs, leave an error code and message in the RBU handle.
+*/
+static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
+ assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
+ assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
+
+ /* Open the RBU database */
+ p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
+
+ if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
+ sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
+ if( p->zState==0 ){
+ const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
+ p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
+ }
+ }
+
+ /* If using separate RBU and state databases, attach the state database to
+ ** the RBU db handle now. */
+ if( p->zState ){
+ rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
+ memcpy(p->zStateDb, "stat", 4);
+ }else{
+ memcpy(p->zStateDb, "main", 4);
+ }
+
+#if 0
+ if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
+ p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
+ }
+#endif
+
+ /* If it has not already been created, create the rbu_state table */
+ rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
+
+#if 0
+ if( rbuIsVacuum(p) ){
+ if( p->rc==SQLITE_OK ){
+ int rc2;
+ int bOk = 0;
+ sqlite3_stmt *pCnt = 0;
+ p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
+ "SELECT count(*) FROM stat.sqlite_schema"
+ );
+ if( p->rc==SQLITE_OK
+ && sqlite3_step(pCnt)==SQLITE_ROW
+ && 1==sqlite3_column_int(pCnt, 0)
+ ){
+ bOk = 1;
+ }
+ rc2 = sqlite3_finalize(pCnt);
+ if( p->rc==SQLITE_OK ) p->rc = rc2;
+
+ if( p->rc==SQLITE_OK && bOk==0 ){
+ p->rc = SQLITE_ERROR;
+ p->zErrmsg = sqlite3_mprintf("invalid state database");
+ }
+
+ if( p->rc==SQLITE_OK ){
+ p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
+ }
+ }
+ }
+#endif
+
+ if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
+ int bOpen = 0;
+ int rc;
+ p->nRbu = 0;
+ p->pRbuFd = 0;
+ rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
+ if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
+ if( p->eStage>=RBU_STAGE_MOVE ){
+ bOpen = 1;
+ }else{
+ RbuState *pState = rbuLoadState(p);
+ if( pState ){
+ bOpen = (pState->eStage>=RBU_STAGE_MOVE);
+ rbuFreeState(pState);
+ }
+ }
+ if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
+ }
+
+ p->eStage = 0;
+ if( p->rc==SQLITE_OK && p->dbMain==0 ){
+ if( !rbuIsVacuum(p) ){
+ p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
+ }else if( p->pRbuFd->pWalFd ){
+ if( pbRetry ){
+ p->pRbuFd->bNolock = 0;
+ sqlite3_close(p->dbRbu);
+ sqlite3_close(p->dbMain);
+ p->dbMain = 0;
+ p->dbRbu = 0;
+ *pbRetry = 1;
+ return;
+ }
+ p->rc = SQLITE_ERROR;
+ p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
+ }else{
+ char *zTarget;
+ char *zExtra = 0;
+ if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
+ zExtra = &p->zRbu[5];
+ while( *zExtra ){
+ if( *zExtra++=='?' ) break;
+ }
+ if( *zExtra=='\0' ) zExtra = 0;
+ }
+
+ zTarget = sqlite3_mprintf("file:%s-vactmp?rbu_memory=1%s%s",
+ sqlite3_db_filename(p->dbRbu, "main"),
+ (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
+ );
+
+ if( zTarget==0 ){
+ p->rc = SQLITE_NOMEM;
+ return;
+ }
+ p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
+ sqlite3_free(zTarget);
+ }
+ }
+
+ if( p->rc==SQLITE_OK ){
+ p->rc = sqlite3_create_function(p->dbMain,
+ "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
+ );
+ }
+
+ if( p->rc==SQLITE_OK ){
+ p->rc = sqlite3_create_function(p->dbMain,
+ "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
+ );
+ }
+
+ if( p->rc==SQLITE_OK ){
+ p->rc = sqlite3_create_function(p->dbRbu,
+ "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
+ );
+ }
+
+ if( p->rc==SQLITE_OK ){
+ p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
+ }
+ rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_schema");
+
+ /* Mark the database file just opened as an RBU target database. If
+ ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
+ ** This is an error. */
+ if( p->rc==SQLITE_OK ){
+ p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
+ }
+
+ if( p->rc==SQLITE_NOTFOUND ){
+ p->rc = SQLITE_ERROR;
+ p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
+ }
+}
+
+/*
+** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
+** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
+**
+** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
+** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
+** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
+** three characters, then shorten the suffix on z[] to be the last three
+** characters of the original suffix.
+**
+** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
+** do the suffix shortening regardless of URI parameter.
+**
+** Examples:
+**
+** test.db-journal => test.nal
+** test.db-wal => test.wal
+** test.db-shm => test.shm
+** test.db-mj7f3319fa => test.9fa
+*/
+static void rbuFileSuffix3(const char *zBase, char *z){
+#ifdef SQLITE_ENABLE_8_3_NAMES
+#if SQLITE_ENABLE_8_3_NAMES<2
+ if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
+#endif
+ {
+ int i, sz;
+ sz = (int)strlen(z)&0xffffff;
+ for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
+ if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
+ }
+#endif
+}
+
+/*
+** Return the current wal-index header checksum for the target database
+** as a 64-bit integer.
+**
+** The checksum is store in the first page of xShmMap memory as an 8-byte
+** blob starting at byte offset 40.
+*/
+static i64 rbuShmChecksum(sqlite3rbu *p){
+ i64 iRet = 0;
+ if( p->rc==SQLITE_OK ){
+ sqlite3_file *pDb = p->pTargetFd->pReal;
+ u32 volatile *ptr;
+ p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
+ if( p->rc==SQLITE_OK ){
+ iRet = ((i64)ptr[10] << 32) + ptr[11];
+ }
+ }
+ return iRet;
+}
+
+/*
+** This function is called as part of initializing or reinitializing an
+** incremental checkpoint.
+**
+** It populates the sqlite3rbu.aFrame[] array with the set of
+** (wal frame -> db page) copy operations required to checkpoint the
+** current wal file, and obtains the set of shm locks required to safely
+** perform the copy operations directly on the file-system.
+**
+** If argument pState is not NULL, then the incremental checkpoint is
+** being resumed. In this case, if the checksum of the wal-index-header
+** following recovery is not the same as the checksum saved in the RbuState
+** object, then the rbu handle is set to DONE state. This occurs if some
+** other client appends a transaction to the wal file in the middle of
+** an incremental checkpoint.
+*/
+static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
+
+ /* If pState is NULL, then the wal file may not have been opened and
+ ** recovered. Running a read-statement here to ensure that doing so
+ ** does not interfere with the "capture" process below. */
+ if( pState==0 ){
+ p->eStage = 0;
+ if( p->rc==SQLITE_OK ){
+ p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_schema", 0, 0, 0);
+ }
+ }
+
+ /* Assuming no error has occurred, run a "restart" checkpoint with the
+ ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
+ ** special behaviour in the rbu VFS:
+ **
+ ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
+ ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
+ ** proceed with running a passive checkpoint instead of failing).
+ **
+ ** * Attempts to read from the *-wal file or write to the database file
+ ** do not perform any IO. Instead, the frame/page combinations that
+ ** would be read/written are recorded in the sqlite3rbu.aFrame[]
+ ** array.
+ **
+ ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
+ ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
+ ** no-ops. These locks will not be released until the connection
+ ** is closed.
+ **
+ ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
+ ** error.
+ **
+ ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
+ ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
+ ** array populated with a set of (frame -> page) mappings. Because the
+ ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
+ ** data from the wal file into the database file according to the
+ ** contents of aFrame[].
+ */
+ if( p->rc==SQLITE_OK ){
+ int rc2;
+ p->eStage = RBU_STAGE_CAPTURE;
+ rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
+ if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
+ }
+
+ if( p->rc==SQLITE_OK && p->nFrame>0 ){
+ p->eStage = RBU_STAGE_CKPT;
+ p->nStep = (pState ? pState->nRow : 0);
+ p->aBuf = rbuMalloc(p, p->pgsz);
+ p->iWalCksum = rbuShmChecksum(p);
+ }
+
+ if( p->rc==SQLITE_OK ){
+ if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
+ p->rc = SQLITE_DONE;
+ p->eStage = RBU_STAGE_DONE;
+ }else{
+ int nSectorSize;
+ sqlite3_file *pDb = p->pTargetFd->pReal;
+ sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
+ assert( p->nPagePerSector==0 );
+ nSectorSize = pDb->pMethods->xSectorSize(pDb);
+ if( nSectorSize>p->pgsz ){
+ p->nPagePerSector = nSectorSize / p->pgsz;
+ }else{
+ p->nPagePerSector = 1;
+ }
+
+ /* Call xSync() on the wal file. This causes SQLite to sync the
+ ** directory in which the target database and the wal file reside, in
+ ** case it has not been synced since the rename() call in
+ ** rbuMoveOalFile(). */
+ p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
+ }
+ }
+}
+
+/*
+** Called when iAmt bytes are read from offset iOff of the wal file while
+** the rbu object is in capture mode. Record the frame number of the frame
+** being read in the aFrame[] array.
+*/
+static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
+ const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
+ u32 iFrame;
+
+ if( pRbu->mLock!=mReq ){
+ pRbu->rc = SQLITE_BUSY;
+ return SQLITE_INTERNAL;
+ }
+
+ pRbu->pgsz = iAmt;
+ if( pRbu->nFrame==pRbu->nFrameAlloc ){
+ int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
+ RbuFrame *aNew;
+ aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
+ if( aNew==0 ) return SQLITE_NOMEM;
+ pRbu->aFrame = aNew;
+ pRbu->nFrameAlloc = nNew;
+ }
+
+ iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
+ if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
+ pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
+ pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
+ pRbu->nFrame++;
+ return SQLITE_OK;
+}
+
+/*
+** Called when a page of data is written to offset iOff of the database
+** file while the rbu handle is in capture mode. Record the page number
+** of the page being written in the aFrame[] array.
+*/
+static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
+ pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
+ return SQLITE_OK;
+}
+
+/*
+** This is called as part of an incremental checkpoint operation. Copy
+** a single frame of data from the wal file into the database file, as
+** indicated by the RbuFrame object.
+*/
+static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
+ sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
+ sqlite3_file *pDb = p->pTargetFd->pReal;
+ i64 iOff;
+
+ assert( p->rc==SQLITE_OK );
+ iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
+ p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
+ if( p->rc ) return;
+
+ iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
+ p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
+}
+
+
+/*
+** Take an EXCLUSIVE lock on the database file.
+*/
+static void rbuLockDatabase(sqlite3rbu *p){
+ sqlite3_file *pReal = p->pTargetFd->pReal;
+ assert( p->rc==SQLITE_OK );
+ p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
+ if( p->rc==SQLITE_OK ){
+ p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
+ }
+}
+
+#if defined(_WIN32_WCE)
+static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
+ int nChar;
+ LPWSTR zWideFilename;
+
+ nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
+ if( nChar==0 ){
+ return 0;
+ }
+ zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
+ if( zWideFilename==0 ){
+ return 0;
+ }
+ memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
+ nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
+ nChar);
+ if( nChar==0 ){
+ sqlite3_free(zWideFilename);
+ zWideFilename = 0;
+ }
+ return zWideFilename;
+}
+#endif
+
+/*
+** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
+** on the database file. This proc moves the *-oal file to the *-wal path,
+** then reopens the database file (this time in vanilla, non-oal, WAL mode).
+** If an error occurs, leave an error code and error message in the rbu
+** handle.
+*/
+static void rbuMoveOalFile(sqlite3rbu *p){
+ const char *zBase = sqlite3_db_filename(p->dbMain, "main");
+ const char *zMove = zBase;
+ char *zOal;
+ char *zWal;
+
+ if( rbuIsVacuum(p) ){
+ zMove = sqlite3_db_filename(p->dbRbu, "main");
+ }
+ zOal = sqlite3_mprintf("%s-oal", zMove);
+ zWal = sqlite3_mprintf("%s-wal", zMove);
+
+ assert( p->eStage==RBU_STAGE_MOVE );
+ assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
+ if( zWal==0 || zOal==0 ){
+ p->rc = SQLITE_NOMEM;
+ }else{
+ /* Move the *-oal file to *-wal. At this point connection p->db is
+ ** holding a SHARED lock on the target database file (because it is
+ ** in WAL mode). So no other connection may be writing the db.
+ **
+ ** In order to ensure that there are no database readers, an EXCLUSIVE
+ ** lock is obtained here before the *-oal is moved to *-wal.
+ */
+ rbuLockDatabase(p);
+ if( p->rc==SQLITE_OK ){
+ rbuFileSuffix3(zBase, zWal);
+ rbuFileSuffix3(zBase, zOal);
+
+ /* Re-open the databases. */
+ rbuObjIterFinalize(&p->objiter);
+ sqlite3_close(p->dbRbu);
+ sqlite3_close(p->dbMain);
+ p->dbMain = 0;
+ p->dbRbu = 0;
+
+#if defined(_WIN32_WCE)
+ {
+ LPWSTR zWideOal;
+ LPWSTR zWideWal;
+
+ zWideOal = rbuWinUtf8ToUnicode(zOal);
+ if( zWideOal ){
+ zWideWal = rbuWinUtf8ToUnicode(zWal);
+ if( zWideWal ){
+ if( MoveFileW(zWideOal, zWideWal) ){
+ p->rc = SQLITE_OK;
+ }else{
+ p->rc = SQLITE_IOERR;
+ }
+ sqlite3_free(zWideWal);
+ }else{
+ p->rc = SQLITE_IOERR_NOMEM;
+ }
+ sqlite3_free(zWideOal);
+ }else{
+ p->rc = SQLITE_IOERR_NOMEM;
+ }
+ }
+#else
+ p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
+#endif
+
+ if( p->rc==SQLITE_OK ){
+ rbuOpenDatabase(p, 0);
+ rbuSetupCheckpoint(p, 0);
+ }
+ }
+ }
+
+ sqlite3_free(zWal);
+ sqlite3_free(zOal);
+}
+
+/*
+** The SELECT statement iterating through the keys for the current object
+** (p->objiter.pSelect) currently points to a valid row. This function
+** determines the type of operation requested by this row and returns
+** one of the following values to indicate the result:
+**
+** * RBU_INSERT
+** * RBU_DELETE
+** * RBU_IDX_DELETE
+** * RBU_UPDATE
+**
+** If RBU_UPDATE is returned, then output variable *pzMask is set to
+** point to the text value indicating the columns to update.
+**
+** If the rbu_control field contains an invalid value, an error code and
+** message are left in the RBU handle and zero returned.
+*/
+static int rbuStepType(sqlite3rbu *p, const char **pzMask){
+ int iCol = p->objiter.nCol; /* Index of rbu_control column */
+ int res = 0; /* Return value */
+
+ switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
+ case SQLITE_INTEGER: {
+ int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
+ switch( iVal ){
+ case 0: res = RBU_INSERT; break;
+ case 1: res = RBU_DELETE; break;
+ case 2: res = RBU_REPLACE; break;
+ case 3: res = RBU_IDX_DELETE; break;
+ case 4: res = RBU_IDX_INSERT; break;
+ }
+ break;
+ }
+
+ case SQLITE_TEXT: {
+ const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
+ if( z==0 ){
+ p->rc = SQLITE_NOMEM;
+ }else{
+ *pzMask = (const char*)z;
+ }
+ res = RBU_UPDATE;
+
+ break;
+ }
+
+ default:
+ break;
+ }
+
+ if( res==0 ){
+ rbuBadControlError(p);
+ }
+ return res;
+}
+
+#ifdef SQLITE_DEBUG
+/*
+** Assert that column iCol of statement pStmt is named zName.
+*/
+static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
+ const char *zCol = sqlite3_column_name(pStmt, iCol);
+ assert( 0==sqlite3_stricmp(zName, zCol) );
+}
+#else
+# define assertColumnName(x,y,z)
+#endif
+
+/*
+** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
+** RBU_IDX_DELETE. This function performs the work of a single
+** sqlite3rbu_step() call for the type of operation specified by eType.
+*/
+static void rbuStepOneOp(sqlite3rbu *p, int eType){
+ RbuObjIter *pIter = &p->objiter;
+ sqlite3_value *pVal;
+ sqlite3_stmt *pWriter;
+ int i;
+
+ assert( p->rc==SQLITE_OK );
+ assert( eType!=RBU_DELETE || pIter->zIdx==0 );
+ assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
+ || eType==RBU_INSERT || eType==RBU_IDX_INSERT
+ );
+
+ /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
+ ** statement below does actually delete a row, nPhaseOneStep will be
+ ** incremented by the same amount when SQL function rbu_tmp_insert()
+ ** is invoked by the trigger. */
+ if( eType==RBU_DELETE ){
+ p->nPhaseOneStep -= p->objiter.nIndex;
+ }
+
+ if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
+ pWriter = pIter->pDelete;
+ }else{
+ pWriter = pIter->pInsert;
+ }
+
+ for(i=0; i<pIter->nCol; i++){
+ /* If this is an INSERT into a table b-tree and the table has an
+ ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
+ ** to write a NULL into the IPK column. That is not permitted. */
+ if( eType==RBU_INSERT
+ && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
+ && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
+ ){
+ p->rc = SQLITE_MISMATCH;
+ p->zErrmsg = sqlite3_mprintf("datatype mismatch");
+ return;
+ }
+
+ if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
+ continue;
+ }
+
+ pVal = sqlite3_column_value(pIter->pSelect, i);
+ p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
+ if( p->rc ) return;
+ }
+ if( pIter->zIdx==0 ){
+ if( pIter->eType==RBU_PK_VTAB
+ || pIter->eType==RBU_PK_NONE
+ || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
+ ){
+ /* For a virtual table, or a table with no primary key, the
+ ** SELECT statement is:
+ **
+ ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
+ **
+ ** Hence column_value(pIter->nCol+1).
+ */
+ assertColumnName(pIter->pSelect, pIter->nCol+1,
+ rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
+ );
+ pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
+ p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
+ }
+ }
+ if( p->rc==SQLITE_OK ){
+ sqlite3_step(pWriter);
+ p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
+ }
+}
+
+/*
+** This function does the work for an sqlite3rbu_step() call.
+**
+** The object-iterator (p->objiter) currently points to a valid object,
+** and the input cursor (p->objiter.pSelect) currently points to a valid
+** input row. Perform whatever processing is required and return.
+**
+** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
+** and message is left in the RBU handle and a copy of the error code
+** returned.
+*/
+static int rbuStep(sqlite3rbu *p){
+ RbuObjIter *pIter = &p->objiter;
+ const char *zMask = 0;
+ int eType = rbuStepType(p, &zMask);
+
+ if( eType ){
+ assert( eType==RBU_INSERT || eType==RBU_DELETE
+ || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
+ || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
+ );
+ assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
+
+ if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
+ rbuBadControlError(p);
+ }
+ else if( eType==RBU_REPLACE ){
+ if( pIter->zIdx==0 ){
+ p->nPhaseOneStep += p->objiter.nIndex;
+ rbuStepOneOp(p, RBU_DELETE);
+ }
+ if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
+ }
+ else if( eType!=RBU_UPDATE ){
+ rbuStepOneOp(p, eType);
+ }
+ else{
+ sqlite3_value *pVal;
+ sqlite3_stmt *pUpdate = 0;
+ assert( eType==RBU_UPDATE );
+ p->nPhaseOneStep -= p->objiter.nIndex;
+ rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
+ if( pUpdate ){
+ int i;
+ for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
+ char c = zMask[pIter->aiSrcOrder[i]];
+ pVal = sqlite3_column_value(pIter->pSelect, i);
+ if( pIter->abTblPk[i] || c!='.' ){
+ p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
+ }
+ }
+ if( p->rc==SQLITE_OK
+ && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
+ ){
+ /* Bind the rbu_rowid value to column _rowid_ */
+ assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
+ pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
+ p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
+ }
+ if( p->rc==SQLITE_OK ){
+ sqlite3_step(pUpdate);
+ p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
+ }
+ }
+ }
+ }
+ return p->rc;
+}
+
+/*
+** Increment the schema cookie of the main database opened by p->dbMain.
+**
+** Or, if this is an RBU vacuum, set the schema cookie of the main db
+** opened by p->dbMain to one more than the schema cookie of the main
+** db opened by p->dbRbu.
+*/
+static void rbuIncrSchemaCookie(sqlite3rbu *p){
+ if( p->rc==SQLITE_OK ){
+ sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
+ int iCookie = 1000000;
+ sqlite3_stmt *pStmt;
+
+ p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
+ "PRAGMA schema_version"
+ );
+ if( p->rc==SQLITE_OK ){
+ /* Coverage: it may be that this sqlite3_step() cannot fail. There
+ ** is already a transaction open, so the prepared statement cannot
+ ** throw an SQLITE_SCHEMA exception. The only database page the
+ ** statement reads is page 1, which is guaranteed to be in the cache.
+ ** And no memory allocations are required. */
+ if( SQLITE_ROW==sqlite3_step(pStmt) ){
+ iCookie = sqlite3_column_int(pStmt, 0);
+ }
+ rbuFinalize(p, pStmt);
+ }
+ if( p->rc==SQLITE_OK ){
+ rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
+ }
+ }
+}
+
+/*
+** Update the contents of the rbu_state table within the rbu database. The
+** value stored in the RBU_STATE_STAGE column is eStage. All other values
+** are determined by inspecting the rbu handle passed as the first argument.
+*/
+static void rbuSaveState(sqlite3rbu *p, int eStage){
+ if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
+ sqlite3_stmt *pInsert = 0;
+ rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
+ int rc;
+
+ assert( p->zErrmsg==0 );
+ rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
+ sqlite3_mprintf(
+ "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
+ "(%d, %d), "
+ "(%d, %Q), "
+ "(%d, %Q), "
+ "(%d, %d), "
+ "(%d, %d), "
+ "(%d, %lld), "
+ "(%d, %lld), "
+ "(%d, %lld), "
+ "(%d, %lld), "
+ "(%d, %Q) ",
+ p->zStateDb,
+ RBU_STATE_STAGE, eStage,
+ RBU_STATE_TBL, p->objiter.zTbl,
+ RBU_STATE_IDX, p->objiter.zIdx,
+ RBU_STATE_ROW, p->nStep,
+ RBU_STATE_PROGRESS, p->nProgress,
+ RBU_STATE_CKPT, p->iWalCksum,
+ RBU_STATE_COOKIE, (i64)pFd->iCookie,
+ RBU_STATE_OALSZ, p->iOalSz,
+ RBU_STATE_PHASEONESTEP, p->nPhaseOneStep,
+ RBU_STATE_DATATBL, p->objiter.zDataTbl
+ )
+ );
+ assert( pInsert==0 || rc==SQLITE_OK );
+
+ if( rc==SQLITE_OK ){
+ sqlite3_step(pInsert);
+ rc = sqlite3_finalize(pInsert);
+ }
+ if( rc!=SQLITE_OK ) p->rc = rc;
+ }
+}
+
+
+/*
+** The second argument passed to this function is the name of a PRAGMA
+** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
+** This function executes the following on sqlite3rbu.dbRbu:
+**
+** "PRAGMA main.$zPragma"
+**
+** where $zPragma is the string passed as the second argument, then
+** on sqlite3rbu.dbMain:
+**
+** "PRAGMA main.$zPragma = $val"
+**
+** where $val is the value returned by the first PRAGMA invocation.
+**
+** In short, it copies the value of the specified PRAGMA setting from
+** dbRbu to dbMain.
+*/
+static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
+ if( p->rc==SQLITE_OK ){
+ sqlite3_stmt *pPragma = 0;
+ p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
+ sqlite3_mprintf("PRAGMA main.%s", zPragma)
+ );
+ if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
+ p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
+ zPragma, sqlite3_column_int(pPragma, 0)
+ );
+ }
+ rbuFinalize(p, pPragma);
+ }
+}
+
+/*
+** The RBU handle passed as the only argument has just been opened and
+** the state database is empty. If this RBU handle was opened for an
+** RBU vacuum operation, create the schema in the target db.
+*/
+static void rbuCreateTargetSchema(sqlite3rbu *p){
+ sqlite3_stmt *pSql = 0;
+ sqlite3_stmt *pInsert = 0;
+
+ assert( rbuIsVacuum(p) );
+ p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
+ if( p->rc==SQLITE_OK ){
+ p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
+ "SELECT sql FROM sqlite_schema WHERE sql!='' AND rootpage!=0"
+ " AND name!='sqlite_sequence' "
+ " ORDER BY type DESC"
+ );
+ }
+
+ while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
+ const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
+ p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
+ }
+ rbuFinalize(p, pSql);
+ if( p->rc!=SQLITE_OK ) return;
+
+ if( p->rc==SQLITE_OK ){
+ p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
+ "SELECT * FROM sqlite_schema WHERE rootpage=0 OR rootpage IS NULL"
+ );
+ }
+
+ if( p->rc==SQLITE_OK ){
+ p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
+ "INSERT INTO sqlite_schema VALUES(?,?,?,?,?)"
+ );
+ }
+
+ while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
+ int i;
+ for(i=0; i<5; i++){
+ sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
+ }
+ sqlite3_step(pInsert);
+ p->rc = sqlite3_reset(pInsert);
+ }
+ if( p->rc==SQLITE_OK ){
+ p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
+ }
+
+ rbuFinalize(p, pSql);
+ rbuFinalize(p, pInsert);
+}
+
+/*
+** Step the RBU object.
+*/
+SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
+ if( p ){
+ switch( p->eStage ){
+ case RBU_STAGE_OAL: {
+ RbuObjIter *pIter = &p->objiter;
+
+ /* If this is an RBU vacuum operation and the state table was empty
+ ** when this handle was opened, create the target database schema. */
+ if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
+ rbuCreateTargetSchema(p);
+ rbuCopyPragma(p, "user_version");
+ rbuCopyPragma(p, "application_id");
+ }
+
+ while( p->rc==SQLITE_OK && pIter->zTbl ){
+
+ if( pIter->bCleanup ){
+ /* Clean up the rbu_tmp_xxx table for the previous table. It
+ ** cannot be dropped as there are currently active SQL statements.
+ ** But the contents can be deleted. */
+ if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
+ rbuMPrintfExec(p, p->dbRbu,
+ "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
+ );
+ }
+ }else{
+ rbuObjIterPrepareAll(p, pIter, 0);
+
+ /* Advance to the next row to process. */
+ if( p->rc==SQLITE_OK ){
+ int rc = sqlite3_step(pIter->pSelect);
+ if( rc==SQLITE_ROW ){
+ p->nProgress++;
+ p->nStep++;
+ return rbuStep(p);
+ }
+ p->rc = sqlite3_reset(pIter->pSelect);
+ p->nStep = 0;
+ }
+ }
+
+ rbuObjIterNext(p, pIter);
+ }
+
+ if( p->rc==SQLITE_OK ){
+ assert( pIter->zTbl==0 );
+ rbuSaveState(p, RBU_STAGE_MOVE);
+ rbuIncrSchemaCookie(p);
+ if( p->rc==SQLITE_OK ){
+ p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
+ }
+ if( p->rc==SQLITE_OK ){
+ p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
+ }
+ p->eStage = RBU_STAGE_MOVE;
+ }
+ break;
+ }
+
+ case RBU_STAGE_MOVE: {
+ if( p->rc==SQLITE_OK ){
+ rbuMoveOalFile(p);
+ p->nProgress++;
+ }
+ break;
+ }
+
+ case RBU_STAGE_CKPT: {
+ if( p->rc==SQLITE_OK ){
+ if( p->nStep>=p->nFrame ){
+ sqlite3_file *pDb = p->pTargetFd->pReal;
+
+ /* Sync the db file */
+ p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
+
+ /* Update nBackfill */
+ if( p->rc==SQLITE_OK ){
+ void volatile *ptr;
+ p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
+ if( p->rc==SQLITE_OK ){
+ ((u32 volatile*)ptr)[24] = p->iMaxFrame;
+ }
+ }
+
+ if( p->rc==SQLITE_OK ){
+ p->eStage = RBU_STAGE_DONE;
+ p->rc = SQLITE_DONE;
+ }
+ }else{
+ /* At one point the following block copied a single frame from the
+ ** wal file to the database file. So that one call to sqlite3rbu_step()
+ ** checkpointed a single frame.
+ **
+ ** However, if the sector-size is larger than the page-size, and the
+ ** application calls sqlite3rbu_savestate() or close() immediately
+ ** after this step, then rbu_step() again, then a power failure occurs,
+ ** then the database page written here may be damaged. Work around
+ ** this by checkpointing frames until the next page in the aFrame[]
+ ** lies on a different disk sector to the current one. */
+ u32 iSector;
+ do{
+ RbuFrame *pFrame = &p->aFrame[p->nStep];
+ iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
+ rbuCheckpointFrame(p, pFrame);
+ p->nStep++;
+ }while( p->nStep<p->nFrame
+ && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
+ && p->rc==SQLITE_OK
+ );
+ }
+ p->nProgress++;
+ }
+ break;
+ }
+
+ default:
+ break;
+ }
+ return p->rc;
+ }else{
+ return SQLITE_NOMEM;
+ }
+}
+
+/*
+** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
+** otherwise. Either or both argument may be NULL. Two NULL values are
+** considered equal, and NULL is considered distinct from all other values.
+*/
+static int rbuStrCompare(const char *z1, const char *z2){
+ if( z1==0 && z2==0 ) return 0;
+ if( z1==0 || z2==0 ) return 1;
+ return (sqlite3_stricmp(z1, z2)!=0);
+}
+
+/*
+** This function is called as part of sqlite3rbu_open() when initializing
+** an rbu handle in OAL stage. If the rbu update has not started (i.e.
+** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
+** things so that the next call to sqlite3rbu_step() continues on from
+** where the previous rbu handle left off.
+**
+** If an error occurs, an error code and error message are left in the
+** rbu handle passed as the first argument.
+*/
+static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
+ assert( p->rc==SQLITE_OK );
+ if( pState->zTbl ){
+ RbuObjIter *pIter = &p->objiter;
+ int rc = SQLITE_OK;
+
+ while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
+ || rbuStrCompare(pIter->zIdx, pState->zIdx)
+ || (pState->zDataTbl==0 && rbuStrCompare(pIter->zTbl, pState->zTbl))
+ || (pState->zDataTbl && rbuStrCompare(pIter->zDataTbl, pState->zDataTbl))
+ )){
+ rc = rbuObjIterNext(p, pIter);
+ }
+
+ if( rc==SQLITE_OK && !pIter->zTbl ){
+ rc = SQLITE_ERROR;
+ p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
+ }
+
+ if( rc==SQLITE_OK ){
+ p->nStep = pState->nRow;
+ rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
+ }
+
+ p->rc = rc;
+ }
+}
+
+/*
+** If there is a "*-oal" file in the file-system corresponding to the
+** target database in the file-system, delete it. If an error occurs,
+** leave an error code and error message in the rbu handle.
+*/
+static void rbuDeleteOalFile(sqlite3rbu *p){
+ char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
+ if( zOal ){
+ sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
+ assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
+ pVfs->xDelete(pVfs, zOal, 0);
+ sqlite3_free(zOal);
+ }
+}
+
+/*
+** Allocate a private rbu VFS for the rbu handle passed as the only
+** argument. This VFS will be used unless the call to sqlite3rbu_open()
+** specified a URI with a vfs=? option in place of a target database
+** file name.
+*/
+static void rbuCreateVfs(sqlite3rbu *p){
+ int rnd;
+ char zRnd[64];
+
+ assert( p->rc==SQLITE_OK );
+ sqlite3_randomness(sizeof(int), (void*)&rnd);
+ sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
+ p->rc = sqlite3rbu_create_vfs(zRnd, 0);
+ if( p->rc==SQLITE_OK ){
+ sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
+ assert( pVfs );
+ p->zVfsName = pVfs->zName;
+ ((rbu_vfs*)pVfs)->pRbu = p;
+ }
+}
+
+/*
+** Destroy the private VFS created for the rbu handle passed as the only
+** argument by an earlier call to rbuCreateVfs().
+*/
+static void rbuDeleteVfs(sqlite3rbu *p){
+ if( p->zVfsName ){
+ sqlite3rbu_destroy_vfs(p->zVfsName);
+ p->zVfsName = 0;
+ }
+}
+
+/*
+** This user-defined SQL function is invoked with a single argument - the
+** name of a table expected to appear in the target database. It returns
+** the number of auxilliary indexes on the table.
+*/
+static void rbuIndexCntFunc(
+ sqlite3_context *pCtx,
+ int nVal,
+ sqlite3_value **apVal
+){
+ sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
+ sqlite3_stmt *pStmt = 0;
+ char *zErrmsg = 0;
+ int rc;
+ sqlite3 *db = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
+
+ assert( nVal==1 );
+
+ rc = prepareFreeAndCollectError(db, &pStmt, &zErrmsg,
+ sqlite3_mprintf("SELECT count(*) FROM sqlite_schema "
+ "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
+ );
+ if( rc!=SQLITE_OK ){
+ sqlite3_result_error(pCtx, zErrmsg, -1);
+ }else{
+ int nIndex = 0;
+ if( SQLITE_ROW==sqlite3_step(pStmt) ){
+ nIndex = sqlite3_column_int(pStmt, 0);
+ }
+ rc = sqlite3_finalize(pStmt);
+ if( rc==SQLITE_OK ){
+ sqlite3_result_int(pCtx, nIndex);
+ }else{
+ sqlite3_result_error(pCtx, sqlite3_errmsg(db), -1);
+ }
+ }
+
+ sqlite3_free(zErrmsg);
+}
+
+/*
+** If the RBU database contains the rbu_count table, use it to initialize
+** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
+** is assumed to contain the same columns as:
+**
+** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
+**
+** There should be one row in the table for each data_xxx table in the
+** database. The 'tbl' column should contain the name of a data_xxx table,
+** and the cnt column the number of rows it contains.
+**
+** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
+** for all rows in the rbu_count table, where nIndex is the number of
+** indexes on the corresponding target database table.
+*/
+static void rbuInitPhaseOneSteps(sqlite3rbu *p){
+ if( p->rc==SQLITE_OK ){
+ sqlite3_stmt *pStmt = 0;
+ int bExists = 0; /* True if rbu_count exists */
+
+ p->nPhaseOneStep = -1;
+
+ p->rc = sqlite3_create_function(p->dbRbu,
+ "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
+ );
+
+ /* Check for the rbu_count table. If it does not exist, or if an error
+ ** occurs, nPhaseOneStep will be left set to -1. */
+ if( p->rc==SQLITE_OK ){
+ p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
+ "SELECT 1 FROM sqlite_schema WHERE tbl_name = 'rbu_count'"
+ );
+ }
+ if( p->rc==SQLITE_OK ){
+ if( SQLITE_ROW==sqlite3_step(pStmt) ){
+ bExists = 1;
+ }
+ p->rc = sqlite3_finalize(pStmt);
+ }
+
+ if( p->rc==SQLITE_OK && bExists ){
+ p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
+ "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
+ "FROM rbu_count"
+ );
+ if( p->rc==SQLITE_OK ){
+ if( SQLITE_ROW==sqlite3_step(pStmt) ){
+ p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
+ }
+ p->rc = sqlite3_finalize(pStmt);
+ }
+ }
+ }
+}
+
+
+static sqlite3rbu *openRbuHandle(
+ const char *zTarget,
+ const char *zRbu,
+ const char *zState
+){
+ sqlite3rbu *p;
+ size_t nTarget = zTarget ? strlen(zTarget) : 0;
+ size_t nRbu = strlen(zRbu);
+ size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
+
+ p = (sqlite3rbu*)sqlite3_malloc64(nByte);
+ if( p ){
+ RbuState *pState = 0;
+
+ /* Create the custom VFS. */
+ memset(p, 0, sizeof(sqlite3rbu));
+ rbuCreateVfs(p);
+
+ /* Open the target, RBU and state databases */
+ if( p->rc==SQLITE_OK ){
+ char *pCsr = (char*)&p[1];
+ int bRetry = 0;
+ if( zTarget ){
+ p->zTarget = pCsr;
+ memcpy(p->zTarget, zTarget, nTarget+1);
+ pCsr += nTarget+1;
+ }
+ p->zRbu = pCsr;
+ memcpy(p->zRbu, zRbu, nRbu+1);
+ pCsr += nRbu+1;
+ if( zState ){
+ p->zState = rbuMPrintf(p, "%s", zState);
+ }
+
+ /* If the first attempt to open the database file fails and the bRetry
+ ** flag it set, this means that the db was not opened because it seemed
+ ** to be a wal-mode db. But, this may have happened due to an earlier
+ ** RBU vacuum operation leaving an old wal file in the directory.
+ ** If this is the case, it will have been checkpointed and deleted
+ ** when the handle was closed and a second attempt to open the
+ ** database may succeed. */
+ rbuOpenDatabase(p, &bRetry);
+ if( bRetry ){
+ rbuOpenDatabase(p, 0);
+ }
+ }
+
+ if( p->rc==SQLITE_OK ){
+ pState = rbuLoadState(p);
+ assert( pState || p->rc!=SQLITE_OK );
+ if( p->rc==SQLITE_OK ){
+
+ if( pState->eStage==0 ){
+ rbuDeleteOalFile(p);
+ rbuInitPhaseOneSteps(p);
+ p->eStage = RBU_STAGE_OAL;
+ }else{
+ p->eStage = pState->eStage;
+ p->nPhaseOneStep = pState->nPhaseOneStep;
+ }
+ p->nProgress = pState->nProgress;
+ p->iOalSz = pState->iOalSz;
+ }
+ }
+ assert( p->rc!=SQLITE_OK || p->eStage!=0 );
+
+ if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
+ if( p->eStage==RBU_STAGE_OAL ){
+ p->rc = SQLITE_ERROR;
+ p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
+ }else if( p->eStage==RBU_STAGE_MOVE ){
+ p->eStage = RBU_STAGE_CKPT;
+ p->nStep = 0;
+ }
+ }
+
+ if( p->rc==SQLITE_OK
+ && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
+ && pState->eStage!=0
+ ){
+ rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
+ if( pFd->iCookie!=pState->iCookie ){
+ /* At this point (pTargetFd->iCookie) contains the value of the
+ ** change-counter cookie (the thing that gets incremented when a
+ ** transaction is committed in rollback mode) currently stored on
+ ** page 1 of the database file. */
+ p->rc = SQLITE_BUSY;
+ p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
+ (rbuIsVacuum(p) ? "vacuum" : "update")
+ );
+ }
+ }
+
+ if( p->rc==SQLITE_OK ){
+ if( p->eStage==RBU_STAGE_OAL ){
+ sqlite3 *db = p->dbMain;
+ p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
+
+ /* Point the object iterator at the first object */
+ if( p->rc==SQLITE_OK ){
+ p->rc = rbuObjIterFirst(p, &p->objiter);
+ }
+
+ /* If the RBU database contains no data_xxx tables, declare the RBU
+ ** update finished. */
+ if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
+ p->rc = SQLITE_DONE;
+ p->eStage = RBU_STAGE_DONE;
+ }else{
+ if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
+ rbuCopyPragma(p, "page_size");
+ rbuCopyPragma(p, "auto_vacuum");
+ }
+
+ /* Open transactions both databases. The *-oal file is opened or
+ ** created at this point. */
+ if( p->rc==SQLITE_OK ){
+ p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
+ }
+
+ /* Check if the main database is a zipvfs db. If it is, set the upper
+ ** level pager to use "journal_mode=off". This prevents it from
+ ** generating a large journal using a temp file. */
+ if( p->rc==SQLITE_OK ){
+ int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
+ if( frc==SQLITE_OK ){
+ p->rc = sqlite3_exec(
+ db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
+ }
+ }
+
+ if( p->rc==SQLITE_OK ){
+ rbuSetupOal(p, pState);
+ }
+ }
+ }else if( p->eStage==RBU_STAGE_MOVE ){
+ /* no-op */
+ }else if( p->eStage==RBU_STAGE_CKPT ){
+ rbuSetupCheckpoint(p, pState);
+ }else if( p->eStage==RBU_STAGE_DONE ){
+ p->rc = SQLITE_DONE;
+ }else{
+ p->rc = SQLITE_CORRUPT;
+ }
+ }
+
+ rbuFreeState(pState);
+ }
+
+ return p;
+}
+
+/*
+** Allocate and return an RBU handle with all fields zeroed except for the
+** error code, which is set to SQLITE_MISUSE.
+*/
+static sqlite3rbu *rbuMisuseError(void){
+ sqlite3rbu *pRet;
+ pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
+ if( pRet ){
+ memset(pRet, 0, sizeof(sqlite3rbu));
+ pRet->rc = SQLITE_MISUSE;
+ }
+ return pRet;
+}
+
+/*
+** Open and return a new RBU handle.
+*/
+SQLITE_API sqlite3rbu *sqlite3rbu_open(
+ const char *zTarget,
+ const char *zRbu,
+ const char *zState
+){
+ if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
+ /* TODO: Check that zTarget and zRbu are non-NULL */
+ return openRbuHandle(zTarget, zRbu, zState);
+}
+
+/*
+** Open a handle to begin or resume an RBU VACUUM operation.
+*/
+SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
+ const char *zTarget,
+ const char *zState
+){
+ if( zTarget==0 ){ return rbuMisuseError(); }
+ if( zState ){
+ int n = strlen(zState);
+ if( n>=7 && 0==memcmp("-vactmp", &zState[n-7], 7) ){
+ return rbuMisuseError();
+ }
+ }
+ /* TODO: Check that both arguments are non-NULL */
+ return openRbuHandle(0, zTarget, zState);
+}
+
+/*
+** Return the database handle used by pRbu.
+*/
+SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
+ sqlite3 *db = 0;
+ if( pRbu ){
+ db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
+ }
+ return db;
+}
+
+
+/*
+** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
+** then edit any error message string so as to remove all occurrences of
+** the pattern "rbu_imp_[0-9]*".
+*/
+static void rbuEditErrmsg(sqlite3rbu *p){
+ if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
+ unsigned int i;
+ size_t nErrmsg = strlen(p->zErrmsg);
+ for(i=0; i<(nErrmsg-8); i++){
+ if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
+ int nDel = 8;
+ while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
+ memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
+ nErrmsg -= nDel;
+ }
+ }
+ }
+}
+
+/*
+** Close the RBU handle.
+*/
+SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
+ int rc;
+ if( p ){
+
+ /* Commit the transaction to the *-oal file. */
+ if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
+ p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
+ }
+
+ /* Sync the db file if currently doing an incremental checkpoint */
+ if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
+ sqlite3_file *pDb = p->pTargetFd->pReal;
+ p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
+ }
+
+ rbuSaveState(p, p->eStage);
+
+ if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
+ p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
+ }
+
+ /* Close any open statement handles. */
+ rbuObjIterFinalize(&p->objiter);
+
+ /* If this is an RBU vacuum handle and the vacuum has either finished
+ ** successfully or encountered an error, delete the contents of the
+ ** state table. This causes the next call to sqlite3rbu_vacuum()
+ ** specifying the current target and state databases to start a new
+ ** vacuum from scratch. */
+ if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
+ int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
+ if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
+ }
+
+ /* Close the open database handle and VFS object. */
+ sqlite3_close(p->dbRbu);
+ sqlite3_close(p->dbMain);
+ assert( p->szTemp==0 );
+ rbuDeleteVfs(p);
+ sqlite3_free(p->aBuf);
+ sqlite3_free(p->aFrame);
+
+ rbuEditErrmsg(p);
+ rc = p->rc;
+ if( pzErrmsg ){
+ *pzErrmsg = p->zErrmsg;
+ }else{
+ sqlite3_free(p->zErrmsg);
+ }
+ sqlite3_free(p->zState);
+ sqlite3_free(p);
+ }else{
+ rc = SQLITE_NOMEM;
+ *pzErrmsg = 0;
+ }
+ return rc;
+}
+
+/*
+** Return the total number of key-value operations (inserts, deletes or
+** updates) that have been performed on the target database since the
+** current RBU update was started.
+*/
+SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
+ return pRbu->nProgress;
+}
+
+/*
+** Return permyriadage progress indications for the two main stages of
+** an RBU update.
+*/
+SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
+ const int MAX_PROGRESS = 10000;
+ switch( p->eStage ){
+ case RBU_STAGE_OAL:
+ if( p->nPhaseOneStep>0 ){
+ *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
+ }else{
+ *pnOne = -1;
+ }
+ *pnTwo = 0;
+ break;
+
+ case RBU_STAGE_MOVE:
+ *pnOne = MAX_PROGRESS;
+ *pnTwo = 0;
+ break;
+
+ case RBU_STAGE_CKPT:
+ *pnOne = MAX_PROGRESS;
+ *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
+ break;
+
+ case RBU_STAGE_DONE:
+ *pnOne = MAX_PROGRESS;
+ *pnTwo = MAX_PROGRESS;
+ break;
+
+ default:
+ assert( 0 );
+ }
+}
+
+/*
+** Return the current state of the RBU vacuum or update operation.
+*/
+SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
+ int aRes[] = {
+ 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
+ 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
+ };
+
+ assert( RBU_STAGE_OAL==1 );
+ assert( RBU_STAGE_MOVE==2 );
+ assert( RBU_STAGE_CKPT==4 );
+ assert( RBU_STAGE_DONE==5 );
+ assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
+ assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
+ assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
+ assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
+
+ if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
+ return SQLITE_RBU_STATE_ERROR;
+ }else{
+ assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
+ assert( p->eStage==RBU_STAGE_OAL
+ || p->eStage==RBU_STAGE_MOVE
+ || p->eStage==RBU_STAGE_CKPT
+ || p->eStage==RBU_STAGE_DONE
+ );
+ return aRes[p->eStage];
+ }
+}
+
+SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
+ int rc = p->rc;
+ if( rc==SQLITE_DONE ) return SQLITE_OK;
+
+ assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
+ if( p->eStage==RBU_STAGE_OAL ){
+ assert( rc!=SQLITE_DONE );
+ if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
+ }
+
+ /* Sync the db file */
+ if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
+ sqlite3_file *pDb = p->pTargetFd->pReal;
+ rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
+ }
+
+ p->rc = rc;
+ rbuSaveState(p, p->eStage);
+ rc = p->rc;
+
+ if( p->eStage==RBU_STAGE_OAL ){
+ assert( rc!=SQLITE_DONE );
+ if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
+ if( rc==SQLITE_OK ){
+ const char *zBegin = rbuIsVacuum(p) ? "BEGIN" : "BEGIN IMMEDIATE";
+ rc = sqlite3_exec(p->dbRbu, zBegin, 0, 0, 0);
+ }
+ if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
+ }
+
+ p->rc = rc;
+ return rc;
+}
+
+/**************************************************************************
+** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
+** of a standard VFS in the following ways:
+**
+** 1. Whenever the first page of a main database file is read or
+** written, the value of the change-counter cookie is stored in
+** rbu_file.iCookie. Similarly, the value of the "write-version"
+** database header field is stored in rbu_file.iWriteVer. This ensures
+** that the values are always trustworthy within an open transaction.
+**
+** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
+** member variable of the associated database file descriptor is set
+** to point to the new file. A mutex protected linked list of all main
+** db fds opened using a particular RBU VFS is maintained at
+** rbu_vfs.pMain to facilitate this.
+**
+** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
+** object can be marked as the target database of an RBU update. This
+** turns on the following extra special behaviour:
+**
+** 3a. If xAccess() is called to check if there exists a *-wal file
+** associated with an RBU target database currently in RBU_STAGE_OAL
+** stage (preparing the *-oal file), the following special handling
+** applies:
+**
+** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
+** target database may not be in wal mode already.
+**
+** * if the *-wal file does not exist, set the output parameter to
+** non-zero (to tell SQLite that it does exist) anyway.
+**
+** Then, when xOpen() is called to open the *-wal file associated with
+** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
+** file, the rbu vfs opens the corresponding *-oal file instead.
+**
+** 3b. The *-shm pages returned by xShmMap() for a target db file in
+** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
+** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
+** are no-ops on target database files in RBU_STAGE_OAL mode. This is
+** because assert() statements in some VFS implementations fail if
+** xShmLock() is called before xShmMap().
+**
+** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
+** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
+** fails with an SQLITE_BUSY error. This is to stop RBU connections
+** from automatically checkpointing a *-wal (or *-oal) file from within
+** sqlite3_close().
+**
+** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
+** all xWrite() calls on the target database file perform no IO.
+** Instead the frame and page numbers that would be read and written
+** are recorded. Additionally, successful attempts to obtain exclusive
+** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
+** database file are recorded. xShmLock() calls to unlock the same
+** locks are no-ops (so that once obtained, these locks are never
+** relinquished). Finally, calls to xSync() on the target database
+** file fail with SQLITE_INTERNAL errors.
+*/
+
+static void rbuUnlockShm(rbu_file *p){
+ assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
+ if( p->pRbu ){
+ int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
+ int i;
+ for(i=0; i<SQLITE_SHM_NLOCK;i++){
+ if( (1<<i) & p->pRbu->mLock ){
+ xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
+ }
+ }
+ p->pRbu->mLock = 0;
+ }
+}
+
+/*
+*/
+static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
+ sqlite3rbu *pRbu = pFd->pRbu;
+ i64 nDiff = nNew - pFd->sz;
+ pRbu->szTemp += nDiff;
+ pFd->sz = nNew;
+ assert( pRbu->szTemp>=0 );
+ if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
+ return SQLITE_OK;
+}
+
+/*
+** Add an item to the main-db lists, if it is not already present.
+**
+** There are two main-db lists. One for all file descriptors, and one
+** for all file descriptors with rbu_file.pDb!=0. If the argument has
+** rbu_file.pDb!=0, then it is assumed to already be present on the
+** main list and is only added to the pDb!=0 list.
+*/
+static void rbuMainlistAdd(rbu_file *p){
+ rbu_vfs *pRbuVfs = p->pRbuVfs;
+ rbu_file *pIter;
+ assert( (p->openFlags & SQLITE_OPEN_MAIN_DB) );
+ sqlite3_mutex_enter(pRbuVfs->mutex);
+ if( p->pRbu==0 ){
+ for(pIter=pRbuVfs->pMain; pIter; pIter=pIter->pMainNext);
+ p->pMainNext = pRbuVfs->pMain;
+ pRbuVfs->pMain = p;
+ }else{
+ for(pIter=pRbuVfs->pMainRbu; pIter && pIter!=p; pIter=pIter->pMainRbuNext){}
+ if( pIter==0 ){
+ p->pMainRbuNext = pRbuVfs->pMainRbu;
+ pRbuVfs->pMainRbu = p;
+ }
+ }
+ sqlite3_mutex_leave(pRbuVfs->mutex);
+}
+
+/*
+** Remove an item from the main-db lists.
+*/
+static void rbuMainlistRemove(rbu_file *p){
+ rbu_file **pp;
+ sqlite3_mutex_enter(p->pRbuVfs->mutex);
+ for(pp=&p->pRbuVfs->pMain; *pp && *pp!=p; pp=&((*pp)->pMainNext)){}
+ if( *pp ) *pp = p->pMainNext;
+ p->pMainNext = 0;
+ for(pp=&p->pRbuVfs->pMainRbu; *pp && *pp!=p; pp=&((*pp)->pMainRbuNext)){}
+ if( *pp ) *pp = p->pMainRbuNext;
+ p->pMainRbuNext = 0;
+ sqlite3_mutex_leave(p->pRbuVfs->mutex);
+}
+
+/*
+** Given that zWal points to a buffer containing a wal file name passed to
+** either the xOpen() or xAccess() VFS method, search the main-db list for
+** a file-handle opened by the same database connection on the corresponding
+** database file.
+**
+** If parameter bRbu is true, only search for file-descriptors with
+** rbu_file.pDb!=0.
+*/
+static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal, int bRbu){
+ rbu_file *pDb;
+ sqlite3_mutex_enter(pRbuVfs->mutex);
+ if( bRbu ){
+ for(pDb=pRbuVfs->pMainRbu; pDb && pDb->zWal!=zWal; pDb=pDb->pMainRbuNext){}
+ }else{
+ for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
+ }
+ sqlite3_mutex_leave(pRbuVfs->mutex);
+ return pDb;
+}
+
+/*
+** Close an rbu file.
+*/
+static int rbuVfsClose(sqlite3_file *pFile){
+ rbu_file *p = (rbu_file*)pFile;
+ int rc;
+ int i;
+
+ /* Free the contents of the apShm[] array. And the array itself. */
+ for(i=0; i<p->nShm; i++){
+ sqlite3_free(p->apShm[i]);
+ }
+ sqlite3_free(p->apShm);
+ p->apShm = 0;
+ sqlite3_free(p->zDel);
+
+ if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
+ rbuMainlistRemove(p);
+ rbuUnlockShm(p);
+ p->pReal->pMethods->xShmUnmap(p->pReal, 0);
+ }
+ else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
+ rbuUpdateTempSize(p, 0);
+ }
+ assert( p->pMainNext==0 && p->pRbuVfs->pMain!=p );
+
+ /* Close the underlying file handle */
+ rc = p->pReal->pMethods->xClose(p->pReal);
+ return rc;
+}
+
+
+/*
+** Read and return an unsigned 32-bit big-endian integer from the buffer
+** passed as the only argument.
+*/
+static u32 rbuGetU32(u8 *aBuf){
+ return ((u32)aBuf[0] << 24)
+ + ((u32)aBuf[1] << 16)
+ + ((u32)aBuf[2] << 8)
+ + ((u32)aBuf[3]);
+}
+
+/*
+** Write an unsigned 32-bit value in big-endian format to the supplied
+** buffer.
+*/
+static void rbuPutU32(u8 *aBuf, u32 iVal){
+ aBuf[0] = (iVal >> 24) & 0xFF;
+ aBuf[1] = (iVal >> 16) & 0xFF;
+ aBuf[2] = (iVal >> 8) & 0xFF;
+ aBuf[3] = (iVal >> 0) & 0xFF;
+}
+
+static void rbuPutU16(u8 *aBuf, u16 iVal){
+ aBuf[0] = (iVal >> 8) & 0xFF;
+ aBuf[1] = (iVal >> 0) & 0xFF;
+}
+
+/*
+** Read data from an rbuVfs-file.
+*/
+static int rbuVfsRead(
+ sqlite3_file *pFile,
+ void *zBuf,
+ int iAmt,
+ sqlite_int64 iOfst
+){
+ rbu_file *p = (rbu_file*)pFile;
+ sqlite3rbu *pRbu = p->pRbu;
+ int rc;
+
+ if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
+ assert( p->openFlags & SQLITE_OPEN_WAL );
+ rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
+ }else{
+ if( pRbu && pRbu->eStage==RBU_STAGE_OAL
+ && (p->openFlags & SQLITE_OPEN_WAL)
+ && iOfst>=pRbu->iOalSz
+ ){
+ rc = SQLITE_OK;
+ memset(zBuf, 0, iAmt);
+ }else{
+ rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
+#if 1
+ /* If this is being called to read the first page of the target
+ ** database as part of an rbu vacuum operation, synthesize the
+ ** contents of the first page if it does not yet exist. Otherwise,
+ ** SQLite will not check for a *-wal file. */
+ if( pRbu && rbuIsVacuum(pRbu)
+ && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
+ && (p->openFlags & SQLITE_OPEN_MAIN_DB)
+ && pRbu->rc==SQLITE_OK
+ ){
+ sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
+ rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
+ if( rc==SQLITE_OK ){
+ u8 *aBuf = (u8*)zBuf;
+ u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
+ rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
+ rbuPutU32(&aBuf[36], 0); /* number of free pages */
+ rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
+ rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
+ rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
+
+ if( iAmt>100 ){
+ memset(&aBuf[100], 0, iAmt-100);
+ rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
+ aBuf[100] = 0x0D;
+ }
+ }
+ }
+#endif
+ }
+ if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
+ /* These look like magic numbers. But they are stable, as they are part
+ ** of the definition of the SQLite file format, which may not change. */
+ u8 *pBuf = (u8*)zBuf;
+ p->iCookie = rbuGetU32(&pBuf[24]);
+ p->iWriteVer = pBuf[19];
+ }
+ }
+ return rc;
+}
+
+/*
+** Write data to an rbuVfs-file.
+*/
+static int rbuVfsWrite(
+ sqlite3_file *pFile,
+ const void *zBuf,
+ int iAmt,
+ sqlite_int64 iOfst
+){
+ rbu_file *p = (rbu_file*)pFile;
+ sqlite3rbu *pRbu = p->pRbu;
+ int rc;
+
+ if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
+ assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
+ rc = rbuCaptureDbWrite(p->pRbu, iOfst);
+ }else{
+ if( pRbu ){
+ if( pRbu->eStage==RBU_STAGE_OAL
+ && (p->openFlags & SQLITE_OPEN_WAL)
+ && iOfst>=pRbu->iOalSz
+ ){
+ pRbu->iOalSz = iAmt + iOfst;
+ }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
+ i64 szNew = iAmt+iOfst;
+ if( szNew>p->sz ){
+ rc = rbuUpdateTempSize(p, szNew);
+ if( rc!=SQLITE_OK ) return rc;
+ }
+ }
+ }
+ rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
+ if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
+ /* These look like magic numbers. But they are stable, as they are part
+ ** of the definition of the SQLite file format, which may not change. */
+ u8 *pBuf = (u8*)zBuf;
+ p->iCookie = rbuGetU32(&pBuf[24]);
+ p->iWriteVer = pBuf[19];
+ }
+ }
+ return rc;
+}
+
+/*
+** Truncate an rbuVfs-file.
+*/
+static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
+ rbu_file *p = (rbu_file*)pFile;
+ if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
+ int rc = rbuUpdateTempSize(p, size);
+ if( rc!=SQLITE_OK ) return rc;
+ }
+ return p->pReal->pMethods->xTruncate(p->pReal, size);
+}
+
+/*
+** Sync an rbuVfs-file.
+*/
+static int rbuVfsSync(sqlite3_file *pFile, int flags){
+ rbu_file *p = (rbu_file *)pFile;
+ if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
+ if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
+ return SQLITE_INTERNAL;
+ }
+ return SQLITE_OK;
+ }
+ return p->pReal->pMethods->xSync(p->pReal, flags);
+}
+
+/*
+** Return the current file-size of an rbuVfs-file.
+*/
+static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
+ rbu_file *p = (rbu_file *)pFile;
+ int rc;
+ rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
+
+ /* If this is an RBU vacuum operation and this is the target database,
+ ** pretend that it has at least one page. Otherwise, SQLite will not
+ ** check for the existance of a *-wal file. rbuVfsRead() contains
+ ** similar logic. */
+ if( rc==SQLITE_OK && *pSize==0
+ && p->pRbu && rbuIsVacuum(p->pRbu)
+ && (p->openFlags & SQLITE_OPEN_MAIN_DB)
+ ){
+ *pSize = 1024;
+ }
+ return rc;
+}
+
+/*
+** Lock an rbuVfs-file.
+*/
+static int rbuVfsLock(sqlite3_file *pFile, int eLock){
+ rbu_file *p = (rbu_file*)pFile;
+ sqlite3rbu *pRbu = p->pRbu;
+ int rc = SQLITE_OK;
+
+ assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
+ if( eLock==SQLITE_LOCK_EXCLUSIVE
+ && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
+ ){
+ /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
+ ** prevents it from checkpointing the database from sqlite3_close(). */
+ rc = SQLITE_BUSY;
+ }else{
+ rc = p->pReal->pMethods->xLock(p->pReal, eLock);
+ }
+
+ return rc;
+}
+
+/*
+** Unlock an rbuVfs-file.
+*/
+static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
+ rbu_file *p = (rbu_file *)pFile;
+ return p->pReal->pMethods->xUnlock(p->pReal, eLock);
+}
+
+/*
+** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
+*/
+static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
+ rbu_file *p = (rbu_file *)pFile;
+ return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
+}
+
+/*
+** File control method. For custom operations on an rbuVfs-file.
+*/
+static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
+ rbu_file *p = (rbu_file *)pFile;
+ int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
+ int rc;
+
+ assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
+ || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
+ );
+ if( op==SQLITE_FCNTL_RBU ){
+ sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
+
+ /* First try to find another RBU vfs lower down in the vfs stack. If
+ ** one is found, this vfs will operate in pass-through mode. The lower
+ ** level vfs will do the special RBU handling. */
+ rc = xControl(p->pReal, op, pArg);
+
+ if( rc==SQLITE_NOTFOUND ){
+ /* Now search for a zipvfs instance lower down in the VFS stack. If
+ ** one is found, this is an error. */
+ void *dummy = 0;
+ rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
+ if( rc==SQLITE_OK ){
+ rc = SQLITE_ERROR;
+ pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
+ }else if( rc==SQLITE_NOTFOUND ){
+ pRbu->pTargetFd = p;
+ p->pRbu = pRbu;
+ rbuMainlistAdd(p);
+ if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
+ rc = SQLITE_OK;
+ }
+ }
+ return rc;
+ }
+ else if( op==SQLITE_FCNTL_RBUCNT ){
+ sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
+ pRbu->nRbu++;
+ pRbu->pRbuFd = p;
+ p->bNolock = 1;
+ }
+
+ rc = xControl(p->pReal, op, pArg);
+ if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
+ rbu_vfs *pRbuVfs = p->pRbuVfs;
+ char *zIn = *(char**)pArg;
+ char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
+ *(char**)pArg = zOut;
+ if( zOut==0 ) rc = SQLITE_NOMEM;
+ }
+
+ return rc;
+}
+
+/*
+** Return the sector-size in bytes for an rbuVfs-file.
+*/
+static int rbuVfsSectorSize(sqlite3_file *pFile){
+ rbu_file *p = (rbu_file *)pFile;
+ return p->pReal->pMethods->xSectorSize(p->pReal);
+}
+
+/*
+** Return the device characteristic flags supported by an rbuVfs-file.
+*/
+static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
+ rbu_file *p = (rbu_file *)pFile;
+ return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
+}
+
+/*
+** Take or release a shared-memory lock.
+*/
+static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
+ rbu_file *p = (rbu_file*)pFile;
+ sqlite3rbu *pRbu = p->pRbu;
+ int rc = SQLITE_OK;
+
+#ifdef SQLITE_AMALGAMATION
+ assert( WAL_CKPT_LOCK==1 );
+#endif
+
+ assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
+ if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
+ /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
+ ** taking this lock also prevents any checkpoints from occurring.
+ ** todo: really, it's not clear why this might occur, as
+ ** wal_autocheckpoint ought to be turned off. */
+ if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
+ }else{
+ int bCapture = 0;
+ if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
+ bCapture = 1;
+ }
+
+ if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
+ rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
+ if( bCapture && rc==SQLITE_OK ){
+ pRbu->mLock |= (1 << ofst);
+ }
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
+*/
+static int rbuVfsShmMap(
+ sqlite3_file *pFile,
+ int iRegion,
+ int szRegion,
+ int isWrite,
+ void volatile **pp
+){
+ rbu_file *p = (rbu_file*)pFile;
+ int rc = SQLITE_OK;
+ int eStage = (p->pRbu ? p->pRbu->eStage : 0);
+
+ /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
+ ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
+ ** instead of a file on disk. */
+ assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
+ if( eStage==RBU_STAGE_OAL ){
+ sqlite3_int64 nByte = (iRegion+1) * sizeof(char*);
+ char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
+
+ /* This is an RBU connection that uses its own heap memory for the
+ ** pages of the *-shm file. Since no other process can have run
+ ** recovery, the connection must request *-shm pages in order
+ ** from start to finish. */
+ assert( iRegion==p->nShm );
+ if( apNew==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
+ p->apShm = apNew;
+ p->nShm = iRegion+1;
+ }
+
+ if( rc==SQLITE_OK ){
+ char *pNew = (char*)sqlite3_malloc64(szRegion);
+ if( pNew==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memset(pNew, 0, szRegion);
+ p->apShm[iRegion] = pNew;
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ *pp = p->apShm[iRegion];
+ }else{
+ *pp = 0;
+ }
+ }else{
+ assert( p->apShm==0 );
+ rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
+ }
+
+ return rc;
+}
+
+/*
+** Memory barrier.
+*/
+static void rbuVfsShmBarrier(sqlite3_file *pFile){
+ rbu_file *p = (rbu_file *)pFile;
+ p->pReal->pMethods->xShmBarrier(p->pReal);
+}
+
+/*
+** The xShmUnmap method.
+*/
+static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
+ rbu_file *p = (rbu_file*)pFile;
+ int rc = SQLITE_OK;
+ int eStage = (p->pRbu ? p->pRbu->eStage : 0);
+
+ assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
+ if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
+ /* no-op */
+ }else{
+ /* Release the checkpointer and writer locks */
+ rbuUnlockShm(p);
+ rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
+ }
+ return rc;
+}
+
+/*
+** Open an rbu file handle.
+*/
+static int rbuVfsOpen(
+ sqlite3_vfs *pVfs,
+ const char *zName,
+ sqlite3_file *pFile,
+ int flags,
+ int *pOutFlags
+){
+ static sqlite3_io_methods rbuvfs_io_methods = {
+ 2, /* iVersion */
+ rbuVfsClose, /* xClose */
+ rbuVfsRead, /* xRead */
+ rbuVfsWrite, /* xWrite */
+ rbuVfsTruncate, /* xTruncate */
+ rbuVfsSync, /* xSync */
+ rbuVfsFileSize, /* xFileSize */
+ rbuVfsLock, /* xLock */
+ rbuVfsUnlock, /* xUnlock */
+ rbuVfsCheckReservedLock, /* xCheckReservedLock */
+ rbuVfsFileControl, /* xFileControl */
+ rbuVfsSectorSize, /* xSectorSize */
+ rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
+ rbuVfsShmMap, /* xShmMap */
+ rbuVfsShmLock, /* xShmLock */
+ rbuVfsShmBarrier, /* xShmBarrier */
+ rbuVfsShmUnmap, /* xShmUnmap */
+ 0, 0 /* xFetch, xUnfetch */
+ };
+ rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
+ sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
+ rbu_file *pFd = (rbu_file *)pFile;
+ int rc = SQLITE_OK;
+ const char *zOpen = zName;
+ int oflags = flags;
+
+ memset(pFd, 0, sizeof(rbu_file));
+ pFd->pReal = (sqlite3_file*)&pFd[1];
+ pFd->pRbuVfs = pRbuVfs;
+ pFd->openFlags = flags;
+ if( zName ){
+ if( flags & SQLITE_OPEN_MAIN_DB ){
+ /* A main database has just been opened. The following block sets
+ ** (pFd->zWal) to point to a buffer owned by SQLite that contains
+ ** the name of the *-wal file this db connection will use. SQLite
+ ** happens to pass a pointer to this buffer when using xAccess()
+ ** or xOpen() to operate on the *-wal file. */
+ pFd->zWal = sqlite3_filename_wal(zName);
+ }
+ else if( flags & SQLITE_OPEN_WAL ){
+ rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName, 0);
+ if( pDb ){
+ if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
+ /* This call is to open a *-wal file. Intead, open the *-oal. This
+ ** code ensures that the string passed to xOpen() is terminated by a
+ ** pair of '\0' bytes in case the VFS attempts to extract a URI
+ ** parameter from it. */
+ const char *zBase = zName;
+ size_t nCopy;
+ char *zCopy;
+ if( rbuIsVacuum(pDb->pRbu) ){
+ zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
+ zBase = sqlite3_filename_wal(zBase);
+ }
+ nCopy = strlen(zBase);
+ zCopy = sqlite3_malloc64(nCopy+2);
+ if( zCopy ){
+ memcpy(zCopy, zBase, nCopy);
+ zCopy[nCopy-3] = 'o';
+ zCopy[nCopy] = '\0';
+ zCopy[nCopy+1] = '\0';
+ zOpen = (const char*)(pFd->zDel = zCopy);
+ }else{
+ rc = SQLITE_NOMEM;
+ }
+ pFd->pRbu = pDb->pRbu;
+ }
+ pDb->pWalFd = pFd;
+ }
+ }
+ }else{
+ pFd->pRbu = pRbuVfs->pRbu;
+ }
+
+ if( oflags & SQLITE_OPEN_MAIN_DB
+ && sqlite3_uri_boolean(zName, "rbu_memory", 0)
+ ){
+ assert( oflags & SQLITE_OPEN_MAIN_DB );
+ oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
+ SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
+ zOpen = 0;
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
+ }
+ if( pFd->pReal->pMethods ){
+ /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
+ ** pointer and, if the file is a main database file, link it into the
+ ** mutex protected linked list of all such files. */
+ pFile->pMethods = &rbuvfs_io_methods;
+ if( flags & SQLITE_OPEN_MAIN_DB ){
+ rbuMainlistAdd(pFd);
+ }
+ }else{
+ sqlite3_free(pFd->zDel);
+ }
+
+ return rc;
+}
+
+/*
+** Delete the file located at zPath.
+*/
+static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
+ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
+ return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
+}
+
+/*
+** Test for access permissions. Return true if the requested permission
+** is available, or false otherwise.
+*/
+static int rbuVfsAccess(
+ sqlite3_vfs *pVfs,
+ const char *zPath,
+ int flags,
+ int *pResOut
+){
+ rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
+ sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
+ int rc;
+
+ rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
+
+ /* If this call is to check if a *-wal file associated with an RBU target
+ ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
+ ** the following special handling is activated:
+ **
+ ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
+ ** ensures that the RBU extension never tries to update a database
+ ** in wal mode, even if the first page of the database file has
+ ** been damaged.
+ **
+ ** b) if the *-wal file does not exist, claim that it does anyway,
+ ** causing SQLite to call xOpen() to open it. This call will also
+ ** be intercepted (see the rbuVfsOpen() function) and the *-oal
+ ** file opened instead.
+ */
+ if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
+ rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath, 1);
+ if( pDb && pDb->pRbu->eStage==RBU_STAGE_OAL ){
+ assert( pDb->pRbu );
+ if( *pResOut ){
+ rc = SQLITE_CANTOPEN;
+ }else{
+ sqlite3_int64 sz = 0;
+ rc = rbuVfsFileSize(&pDb->base, &sz);
+ *pResOut = (sz>0);
+ }
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Populate buffer zOut with the full canonical pathname corresponding
+** to the pathname in zPath. zOut is guaranteed to point to a buffer
+** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
+*/
+static int rbuVfsFullPathname(
+ sqlite3_vfs *pVfs,
+ const char *zPath,
+ int nOut,
+ char *zOut
+){
+ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
+ return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
+}
+
+#ifndef SQLITE_OMIT_LOAD_EXTENSION
+/*
+** Open the dynamic library located at zPath and return a handle.
+*/
+static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
+ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
+ return pRealVfs->xDlOpen(pRealVfs, zPath);
+}
+
+/*
+** Populate the buffer zErrMsg (size nByte bytes) with a human readable
+** utf-8 string describing the most recent error encountered associated
+** with dynamic libraries.
+*/
+static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
+ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
+ pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
+}
+
+/*
+** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
+*/
+static void (*rbuVfsDlSym(
+ sqlite3_vfs *pVfs,
+ void *pArg,
+ const char *zSym
+))(void){
+ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
+ return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
+}
+
+/*
+** Close the dynamic library handle pHandle.
+*/
+static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
+ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
+ pRealVfs->xDlClose(pRealVfs, pHandle);
+}
+#endif /* SQLITE_OMIT_LOAD_EXTENSION */
+
+/*
+** Populate the buffer pointed to by zBufOut with nByte bytes of
+** random data.
+*/
+static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
+ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
+ return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
+}
+
+/*
+** Sleep for nMicro microseconds. Return the number of microseconds
+** actually slept.
+*/
+static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
+ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
+ return pRealVfs->xSleep(pRealVfs, nMicro);
+}
+
+/*
+** Return the current time as a Julian Day number in *pTimeOut.
+*/
+static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
+ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
+ return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
+}
+
+/*
+** No-op.
+*/
+static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
+ return 0;
+}
+
+/*
+** Deregister and destroy an RBU vfs created by an earlier call to
+** sqlite3rbu_create_vfs().
+*/
+SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
+ sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
+ if( pVfs && pVfs->xOpen==rbuVfsOpen ){
+ sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
+ sqlite3_vfs_unregister(pVfs);
+ sqlite3_free(pVfs);
+ }
+}
+
+/*
+** Create an RBU VFS named zName that accesses the underlying file-system
+** via existing VFS zParent. The new object is registered as a non-default
+** VFS with SQLite before returning.
+*/
+SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
+
+ /* Template for VFS */
+ static sqlite3_vfs vfs_template = {
+ 1, /* iVersion */
+ 0, /* szOsFile */
+ 0, /* mxPathname */
+ 0, /* pNext */
+ 0, /* zName */
+ 0, /* pAppData */
+ rbuVfsOpen, /* xOpen */
+ rbuVfsDelete, /* xDelete */
+ rbuVfsAccess, /* xAccess */
+ rbuVfsFullPathname, /* xFullPathname */
+
+#ifndef SQLITE_OMIT_LOAD_EXTENSION
+ rbuVfsDlOpen, /* xDlOpen */
+ rbuVfsDlError, /* xDlError */
+ rbuVfsDlSym, /* xDlSym */
+ rbuVfsDlClose, /* xDlClose */
+#else
+ 0, 0, 0, 0,
+#endif
+
+ rbuVfsRandomness, /* xRandomness */
+ rbuVfsSleep, /* xSleep */
+ rbuVfsCurrentTime, /* xCurrentTime */
+ rbuVfsGetLastError, /* xGetLastError */
+ 0, /* xCurrentTimeInt64 (version 2) */
+ 0, 0, 0 /* Unimplemented version 3 methods */
+ };
+
+ rbu_vfs *pNew = 0; /* Newly allocated VFS */
+ int rc = SQLITE_OK;
+ size_t nName;
+ size_t nByte;
+
+ nName = strlen(zName);
+ nByte = sizeof(rbu_vfs) + nName + 1;
+ pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
+ if( pNew==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ sqlite3_vfs *pParent; /* Parent VFS */
+ memset(pNew, 0, nByte);
+ pParent = sqlite3_vfs_find(zParent);
+ if( pParent==0 ){
+ rc = SQLITE_NOTFOUND;
+ }else{
+ char *zSpace;
+ memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
+ pNew->base.mxPathname = pParent->mxPathname;
+ pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
+ pNew->pRealVfs = pParent;
+ pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
+ memcpy(zSpace, zName, nName);
+
+ /* Allocate the mutex and register the new VFS (not as the default) */
+ pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
+ if( pNew->mutex==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ rc = sqlite3_vfs_register(&pNew->base, 0);
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ sqlite3_mutex_free(pNew->mutex);
+ sqlite3_free(pNew);
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Configure the aggregate temp file size limit for this RBU handle.
+*/
+SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
+ if( n>=0 ){
+ pRbu->szTempLimit = n;
+ }
+ return pRbu->szTempLimit;
+}
+
+SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
+ return pRbu->szTemp;
+}
+
+
+/**************************************************************************/
+
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
+
+/************** End of sqlite3rbu.c ******************************************/
+/************** Begin file dbstat.c ******************************************/
+/*
+** 2010 July 12
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains an implementation of the "dbstat" virtual table.
+**
+** The dbstat virtual table is used to extract low-level storage
+** information from an SQLite database in order to implement the
+** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
+** for an example implementation.
+**
+** Additional information is available on the "dbstat.html" page of the
+** official SQLite documentation.
+*/
+
+/* #include "sqliteInt.h" ** Requires access to internal data structures ** */
+#if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
+ && !defined(SQLITE_OMIT_VIRTUALTABLE)
+
+/*
+** Page paths:
+**
+** The value of the 'path' column describes the path taken from the
+** root-node of the b-tree structure to each page. The value of the
+** root-node path is '/'.
+**
+** The value of the path for the left-most child page of the root of
+** a b-tree is '/000/'. (Btrees store content ordered from left to right
+** so the pages to the left have smaller keys than the pages to the right.)
+** The next to left-most child of the root page is
+** '/001', and so on, each sibling page identified by a 3-digit hex
+** value. The children of the 451st left-most sibling have paths such
+** as '/1c2/000/, '/1c2/001/' etc.
+**
+** Overflow pages are specified by appending a '+' character and a
+** six-digit hexadecimal value to the path to the cell they are linked
+** from. For example, the three overflow pages in a chain linked from
+** the left-most cell of the 450th child of the root page are identified
+** by the paths:
+**
+** '/1c2/000+000000' // First page in overflow chain
+** '/1c2/000+000001' // Second page in overflow chain
+** '/1c2/000+000002' // Third page in overflow chain
+**
+** If the paths are sorted using the BINARY collation sequence, then
+** the overflow pages associated with a cell will appear earlier in the
+** sort-order than its child page:
+**
+** '/1c2/000/' // Left-most child of 451st child of root
+*/
+static const char zDbstatSchema[] =
+ "CREATE TABLE x("
+ " name TEXT," /* 0 Name of table or index */
+ " path TEXT," /* 1 Path to page from root (NULL for agg) */
+ " pageno INTEGER," /* 2 Page number (page count for aggregates) */
+ " pagetype TEXT," /* 3 'internal', 'leaf', 'overflow', or NULL */
+ " ncell INTEGER," /* 4 Cells on page (0 for overflow) */
+ " payload INTEGER," /* 5 Bytes of payload on this page */
+ " unused INTEGER," /* 6 Bytes of unused space on this page */
+ " mx_payload INTEGER," /* 7 Largest payload size of all cells */
+ " pgoffset INTEGER," /* 8 Offset of page in file (NULL for agg) */
+ " pgsize INTEGER," /* 9 Size of the page (sum for aggregate) */
+ " schema TEXT HIDDEN," /* 10 Database schema being analyzed */
+ " aggregate BOOLEAN HIDDEN" /* 11 aggregate info for each table */
+ ")"
+;
+
+/* Forward reference to data structured used in this module */
+typedef struct StatTable StatTable;
+typedef struct StatCursor StatCursor;
+typedef struct StatPage StatPage;
+typedef struct StatCell StatCell;
+
+/* Size information for a single cell within a btree page */
+struct StatCell {
+ int nLocal; /* Bytes of local payload */
+ u32 iChildPg; /* Child node (or 0 if this is a leaf) */
+ int nOvfl; /* Entries in aOvfl[] */
+ u32 *aOvfl; /* Array of overflow page numbers */
+ int nLastOvfl; /* Bytes of payload on final overflow page */
+ int iOvfl; /* Iterates through aOvfl[] */
+};
+
+/* Size information for a single btree page */
+struct StatPage {
+ u32 iPgno; /* Page number */
+ DbPage *pPg; /* Page content */
+ int iCell; /* Current cell */
+
+ char *zPath; /* Path to this page */
+
+ /* Variables populated by statDecodePage(): */
+ u8 flags; /* Copy of flags byte */
+ int nCell; /* Number of cells on page */
+ int nUnused; /* Number of unused bytes on page */
+ StatCell *aCell; /* Array of parsed cells */
+ u32 iRightChildPg; /* Right-child page number (or 0) */
+ int nMxPayload; /* Largest payload of any cell on the page */
+};
+
+/* The cursor for scanning the dbstat virtual table */
+struct StatCursor {
+ sqlite3_vtab_cursor base; /* base class. MUST BE FIRST! */
+ sqlite3_stmt *pStmt; /* Iterates through set of root pages */
+ u8 isEof; /* After pStmt has returned SQLITE_DONE */
+ u8 isAgg; /* Aggregate results for each table */
+ int iDb; /* Schema used for this query */
+
+ StatPage aPage[32]; /* Pages in path to current page */
+ int iPage; /* Current entry in aPage[] */
+
+ /* Values to return. */
+ u32 iPageno; /* Value of 'pageno' column */
+ char *zName; /* Value of 'name' column */
+ char *zPath; /* Value of 'path' column */
+ char *zPagetype; /* Value of 'pagetype' column */
+ int nPage; /* Number of pages in current btree */
+ int nCell; /* Value of 'ncell' column */
+ int nMxPayload; /* Value of 'mx_payload' column */
+ i64 nUnused; /* Value of 'unused' column */
+ i64 nPayload; /* Value of 'payload' column */
+ i64 iOffset; /* Value of 'pgOffset' column */
+ i64 szPage; /* Value of 'pgSize' column */
+};
+
+/* An instance of the DBSTAT virtual table */
+struct StatTable {
+ sqlite3_vtab base; /* base class. MUST BE FIRST! */
+ sqlite3 *db; /* Database connection that owns this vtab */
+ int iDb; /* Index of database to analyze */
+};
+
+#ifndef get2byte
+# define get2byte(x) ((x)[0]<<8 | (x)[1])
+#endif
+
+/*
+** Connect to or create a new DBSTAT virtual table.
+*/
+static int statConnect(
+ sqlite3 *db,
+ void *pAux,
+ int argc, const char *const*argv,
+ sqlite3_vtab **ppVtab,
+ char **pzErr
+){
+ StatTable *pTab = 0;
+ int rc = SQLITE_OK;
+ int iDb;
+
+ if( argc>=4 ){
+ Token nm;
+ sqlite3TokenInit(&nm, (char*)argv[3]);
+ iDb = sqlite3FindDb(db, &nm);
+ if( iDb<0 ){
+ *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
+ return SQLITE_ERROR;
+ }
+ }else{
+ iDb = 0;
+ }
+ sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
+ rc = sqlite3_declare_vtab(db, zDbstatSchema);
+ if( rc==SQLITE_OK ){
+ pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
+ if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
+ }
+
+ assert( rc==SQLITE_OK || pTab==0 );
+ if( rc==SQLITE_OK ){
+ memset(pTab, 0, sizeof(StatTable));
+ pTab->db = db;
+ pTab->iDb = iDb;
+ }
+
+ *ppVtab = (sqlite3_vtab*)pTab;
+ return rc;
+}
+
+/*
+** Disconnect from or destroy the DBSTAT virtual table.
+*/
+static int statDisconnect(sqlite3_vtab *pVtab){
+ sqlite3_free(pVtab);
+ return SQLITE_OK;
+}
+
+/*
+** Compute the best query strategy and return the result in idxNum.
+**
+** idxNum-Bit Meaning
+** ---------- ----------------------------------------------
+** 0x01 There is a schema=? term in the WHERE clause
+** 0x02 There is a name=? term in the WHERE clause
+** 0x04 There is an aggregate=? term in the WHERE clause
+** 0x08 Output should be ordered by name and path
+*/
+static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
+ int i;
+ int iSchema = -1;
+ int iName = -1;
+ int iAgg = -1;
+
+ /* Look for a valid schema=? constraint. If found, change the idxNum to
+ ** 1 and request the value of that constraint be sent to xFilter. And
+ ** lower the cost estimate to encourage the constrained version to be
+ ** used.
+ */
+ for(i=0; i<pIdxInfo->nConstraint; i++){
+ if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
+ if( pIdxInfo->aConstraint[i].usable==0 ){
+ /* Force DBSTAT table should always be the right-most table in a join */
+ return SQLITE_CONSTRAINT;
+ }
+ switch( pIdxInfo->aConstraint[i].iColumn ){
+ case 0: { /* name */
+ iName = i;
+ break;
+ }
+ case 10: { /* schema */
+ iSchema = i;
+ break;
+ }
+ case 11: { /* aggregate */
+ iAgg = i;
+ break;
+ }
+ }
+ }
+ i = 0;
+ if( iSchema>=0 ){
+ pIdxInfo->aConstraintUsage[iSchema].argvIndex = ++i;
+ pIdxInfo->aConstraintUsage[iSchema].omit = 1;
+ pIdxInfo->idxNum |= 0x01;
+ }
+ if( iName>=0 ){
+ pIdxInfo->aConstraintUsage[iName].argvIndex = ++i;
+ pIdxInfo->idxNum |= 0x02;
+ }
+ if( iAgg>=0 ){
+ pIdxInfo->aConstraintUsage[iAgg].argvIndex = ++i;
+ pIdxInfo->idxNum |= 0x04;
+ }
+ pIdxInfo->estimatedCost = 1.0;
+
+ /* Records are always returned in ascending order of (name, path).
+ ** If this will satisfy the client, set the orderByConsumed flag so that
+ ** SQLite does not do an external sort.
+ */
+ if( ( pIdxInfo->nOrderBy==1
+ && pIdxInfo->aOrderBy[0].iColumn==0
+ && pIdxInfo->aOrderBy[0].desc==0
+ ) ||
+ ( pIdxInfo->nOrderBy==2
+ && pIdxInfo->aOrderBy[0].iColumn==0
+ && pIdxInfo->aOrderBy[0].desc==0
+ && pIdxInfo->aOrderBy[1].iColumn==1
+ && pIdxInfo->aOrderBy[1].desc==0
+ )
+ ){
+ pIdxInfo->orderByConsumed = 1;
+ pIdxInfo->idxNum |= 0x08;
+ }
+
+ return SQLITE_OK;
+}
+
+/*
+** Open a new DBSTAT cursor.
+*/
+static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
+ StatTable *pTab = (StatTable *)pVTab;
+ StatCursor *pCsr;
+
+ pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
+ if( pCsr==0 ){
+ return SQLITE_NOMEM_BKPT;
+ }else{
+ memset(pCsr, 0, sizeof(StatCursor));
+ pCsr->base.pVtab = pVTab;
+ pCsr->iDb = pTab->iDb;
+ }
+
+ *ppCursor = (sqlite3_vtab_cursor *)pCsr;
+ return SQLITE_OK;
+}
+
+static void statClearCells(StatPage *p){
+ int i;
+ if( p->aCell ){
+ for(i=0; i<p->nCell; i++){
+ sqlite3_free(p->aCell[i].aOvfl);
+ }
+ sqlite3_free(p->aCell);
+ }
+ p->nCell = 0;
+ p->aCell = 0;
+}
+
+static void statClearPage(StatPage *p){
+ statClearCells(p);
+ sqlite3PagerUnref(p->pPg);
+ sqlite3_free(p->zPath);
+ memset(p, 0, sizeof(StatPage));
+}
+
+static void statResetCsr(StatCursor *pCsr){
+ int i;
+ sqlite3_reset(pCsr->pStmt);
+ for(i=0; i<ArraySize(pCsr->aPage); i++){
+ statClearPage(&pCsr->aPage[i]);
+ }
+ pCsr->iPage = 0;
+ sqlite3_free(pCsr->zPath);
+ pCsr->zPath = 0;
+ pCsr->isEof = 0;
+}
+
+/* Resize the space-used counters inside of the cursor */
+static void statResetCounts(StatCursor *pCsr){
+ pCsr->nCell = 0;
+ pCsr->nMxPayload = 0;
+ pCsr->nUnused = 0;
+ pCsr->nPayload = 0;
+ pCsr->szPage = 0;
+ pCsr->nPage = 0;
+}
+
+/*
+** Close a DBSTAT cursor.
+*/
+static int statClose(sqlite3_vtab_cursor *pCursor){
+ StatCursor *pCsr = (StatCursor *)pCursor;
+ statResetCsr(pCsr);
+ sqlite3_finalize(pCsr->pStmt);
+ sqlite3_free(pCsr);
+ return SQLITE_OK;
+}
+
+/*
+** For a single cell on a btree page, compute the number of bytes of
+** content (payload) stored on that page. That is to say, compute the
+** number of bytes of content not found on overflow pages.
+*/
+static int getLocalPayload(
+ int nUsable, /* Usable bytes per page */
+ u8 flags, /* Page flags */
+ int nTotal /* Total record (payload) size */
+){
+ int nLocal;
+ int nMinLocal;
+ int nMaxLocal;
+
+ if( flags==0x0D ){ /* Table leaf node */
+ nMinLocal = (nUsable - 12) * 32 / 255 - 23;
+ nMaxLocal = nUsable - 35;
+ }else{ /* Index interior and leaf nodes */
+ nMinLocal = (nUsable - 12) * 32 / 255 - 23;
+ nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
+ }
+
+ nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
+ if( nLocal>nMaxLocal ) nLocal = nMinLocal;
+ return nLocal;
+}
+
+/* Populate the StatPage object with information about the all
+** cells found on the page currently under analysis.
+*/
+static int statDecodePage(Btree *pBt, StatPage *p){
+ int nUnused;
+ int iOff;
+ int nHdr;
+ int isLeaf;
+ int szPage;
+
+ u8 *aData = sqlite3PagerGetData(p->pPg);
+ u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
+
+ p->flags = aHdr[0];
+ if( p->flags==0x0A || p->flags==0x0D ){
+ isLeaf = 1;
+ nHdr = 8;
+ }else if( p->flags==0x05 || p->flags==0x02 ){
+ isLeaf = 0;
+ nHdr = 12;
+ }else{
+ goto statPageIsCorrupt;
+ }
+ if( p->iPgno==1 ) nHdr += 100;
+ p->nCell = get2byte(&aHdr[3]);
+ p->nMxPayload = 0;
+ szPage = sqlite3BtreeGetPageSize(pBt);
+
+ nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
+ nUnused += (int)aHdr[7];
+ iOff = get2byte(&aHdr[1]);
+ while( iOff ){
+ int iNext;
+ if( iOff>=szPage ) goto statPageIsCorrupt;
+ nUnused += get2byte(&aData[iOff+2]);
+ iNext = get2byte(&aData[iOff]);
+ if( iNext<iOff+4 && iNext>0 ) goto statPageIsCorrupt;
+ iOff = iNext;
+ }
+ p->nUnused = nUnused;
+ p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
+
+ if( p->nCell ){
+ int i; /* Used to iterate through cells */
+ int nUsable; /* Usable bytes per page */
+
+ sqlite3BtreeEnter(pBt);
+ nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
+ sqlite3BtreeLeave(pBt);
+ p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
+ if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
+ memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
+
+ for(i=0; i<p->nCell; i++){
+ StatCell *pCell = &p->aCell[i];
+
+ iOff = get2byte(&aData[nHdr+i*2]);
+ if( iOff<nHdr || iOff>=szPage ) goto statPageIsCorrupt;
+ if( !isLeaf ){
+ pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
+ iOff += 4;
+ }
+ if( p->flags==0x05 ){
+ /* A table interior node. nPayload==0. */
+ }else{
+ u32 nPayload; /* Bytes of payload total (local+overflow) */
+ int nLocal; /* Bytes of payload stored locally */
+ iOff += getVarint32(&aData[iOff], nPayload);
+ if( p->flags==0x0D ){
+ u64 dummy;
+ iOff += sqlite3GetVarint(&aData[iOff], &dummy);
+ }
+ if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
+ nLocal = getLocalPayload(nUsable, p->flags, nPayload);
+ if( nLocal<0 ) goto statPageIsCorrupt;
+ pCell->nLocal = nLocal;
+ assert( nPayload>=(u32)nLocal );
+ assert( nLocal<=(nUsable-35) );
+ if( nPayload>(u32)nLocal ){
+ int j;
+ int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
+ if( iOff+nLocal>nUsable || nPayload>0x7fffffff ){
+ goto statPageIsCorrupt;
+ }
+ pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
+ pCell->nOvfl = nOvfl;
+ pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
+ if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
+ pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
+ for(j=1; j<nOvfl; j++){
+ int rc;
+ u32 iPrev = pCell->aOvfl[j-1];
+ DbPage *pPg = 0;
+ rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
+ if( rc!=SQLITE_OK ){
+ assert( pPg==0 );
+ return rc;
+ }
+ pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
+ sqlite3PagerUnref(pPg);
+ }
+ }
+ }
+ }
+ }
+
+ return SQLITE_OK;
+
+statPageIsCorrupt:
+ p->flags = 0;
+ statClearCells(p);
+ return SQLITE_OK;
+}
+
+/*
+** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
+** the current value of pCsr->iPageno.
+*/
+static void statSizeAndOffset(StatCursor *pCsr){
+ StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
+ Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
+ Pager *pPager = sqlite3BtreePager(pBt);
+ sqlite3_file *fd;
+ sqlite3_int64 x[2];
+
+ /* If connected to a ZIPVFS backend, find the page size and
+ ** offset from ZIPVFS.
+ */
+ fd = sqlite3PagerFile(pPager);
+ x[0] = pCsr->iPageno;
+ if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
+ pCsr->iOffset = x[0];
+ pCsr->szPage += x[1];
+ }else{
+ /* Not ZIPVFS: The default page size and offset */
+ pCsr->szPage += sqlite3BtreeGetPageSize(pBt);
+ pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
+ }
+}
+
+/*
+** Move a DBSTAT cursor to the next entry. Normally, the next
+** entry will be the next page, but in aggregated mode (pCsr->isAgg!=0),
+** the next entry is the next btree.
+*/
+static int statNext(sqlite3_vtab_cursor *pCursor){
+ int rc;
+ int nPayload;
+ char *z;
+ StatCursor *pCsr = (StatCursor *)pCursor;
+ StatTable *pTab = (StatTable *)pCursor->pVtab;
+ Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
+ Pager *pPager = sqlite3BtreePager(pBt);
+
+ sqlite3_free(pCsr->zPath);
+ pCsr->zPath = 0;
+
+statNextRestart:
+ if( pCsr->aPage[0].pPg==0 ){
+ /* Start measuring space on the next btree */
+ statResetCounts(pCsr);
+ rc = sqlite3_step(pCsr->pStmt);
+ if( rc==SQLITE_ROW ){
+ int nPage;
+ u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
+ sqlite3PagerPagecount(pPager, &nPage);
+ if( nPage==0 ){
+ pCsr->isEof = 1;
+ return sqlite3_reset(pCsr->pStmt);
+ }
+ rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
+ pCsr->aPage[0].iPgno = iRoot;
+ pCsr->aPage[0].iCell = 0;
+ if( !pCsr->isAgg ){
+ pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
+ if( z==0 ) rc = SQLITE_NOMEM_BKPT;
+ }
+ pCsr->iPage = 0;
+ pCsr->nPage = 1;
+ }else{
+ pCsr->isEof = 1;
+ return sqlite3_reset(pCsr->pStmt);
+ }
+ }else{
+ /* Continue analyzing the btree previously started */
+ StatPage *p = &pCsr->aPage[pCsr->iPage];
+ if( !pCsr->isAgg ) statResetCounts(pCsr);
+ while( p->iCell<p->nCell ){
+ StatCell *pCell = &p->aCell[p->iCell];
+ while( pCell->iOvfl<pCell->nOvfl ){
+ int nUsable, iOvfl;
+ sqlite3BtreeEnter(pBt);
+ nUsable = sqlite3BtreeGetPageSize(pBt) -
+ sqlite3BtreeGetReserveNoMutex(pBt);
+ sqlite3BtreeLeave(pBt);
+ pCsr->nPage++;
+ statSizeAndOffset(pCsr);
+ if( pCell->iOvfl<pCell->nOvfl-1 ){
+ pCsr->nPayload += nUsable - 4;
+ }else{
+ pCsr->nPayload += pCell->nLastOvfl;
+ pCsr->nUnused += nUsable - 4 - pCell->nLastOvfl;
+ }
+ iOvfl = pCell->iOvfl;
+ pCell->iOvfl++;
+ if( !pCsr->isAgg ){
+ pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
+ pCsr->iPageno = pCell->aOvfl[iOvfl];
+ pCsr->zPagetype = "overflow";
+ pCsr->zPath = z = sqlite3_mprintf(
+ "%s%.3x+%.6x", p->zPath, p->iCell, iOvfl
+ );
+ return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
+ }
+ }
+ if( p->iRightChildPg ) break;
+ p->iCell++;
+ }
+
+ if( !p->iRightChildPg || p->iCell>p->nCell ){
+ statClearPage(p);
+ if( pCsr->iPage>0 ){
+ pCsr->iPage--;
+ }else if( pCsr->isAgg ){
+ /* label-statNext-done: When computing aggregate space usage over
+ ** an entire btree, this is the exit point from this function */
+ return SQLITE_OK;
+ }
+ goto statNextRestart; /* Tail recursion */
+ }
+ pCsr->iPage++;
+ if( pCsr->iPage>=ArraySize(pCsr->aPage) ){
+ statResetCsr(pCsr);
+ return SQLITE_CORRUPT_BKPT;
+ }
+ assert( p==&pCsr->aPage[pCsr->iPage-1] );
+
+ if( p->iCell==p->nCell ){
+ p[1].iPgno = p->iRightChildPg;
+ }else{
+ p[1].iPgno = p->aCell[p->iCell].iChildPg;
+ }
+ rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
+ pCsr->nPage++;
+ p[1].iCell = 0;
+ if( !pCsr->isAgg ){
+ p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
+ if( z==0 ) rc = SQLITE_NOMEM_BKPT;
+ }
+ p->iCell++;
+ }
+
+
+ /* Populate the StatCursor fields with the values to be returned
+ ** by the xColumn() and xRowid() methods.
+ */
+ if( rc==SQLITE_OK ){
+ int i;
+ StatPage *p = &pCsr->aPage[pCsr->iPage];
+ pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
+ pCsr->iPageno = p->iPgno;
+
+ rc = statDecodePage(pBt, p);
+ if( rc==SQLITE_OK ){
+ statSizeAndOffset(pCsr);
+
+ switch( p->flags ){
+ case 0x05: /* table internal */
+ case 0x02: /* index internal */
+ pCsr->zPagetype = "internal";
+ break;
+ case 0x0D: /* table leaf */
+ case 0x0A: /* index leaf */
+ pCsr->zPagetype = "leaf";
+ break;
+ default:
+ pCsr->zPagetype = "corrupted";
+ break;
+ }
+ pCsr->nCell += p->nCell;
+ pCsr->nUnused += p->nUnused;
+ if( p->nMxPayload>pCsr->nMxPayload ) pCsr->nMxPayload = p->nMxPayload;
+ if( !pCsr->isAgg ){
+ pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
+ if( z==0 ) rc = SQLITE_NOMEM_BKPT;
+ }
+ nPayload = 0;
+ for(i=0; i<p->nCell; i++){
+ nPayload += p->aCell[i].nLocal;
+ }
+ pCsr->nPayload += nPayload;
+
+ /* If computing aggregate space usage by btree, continue with the
+ ** next page. The loop will exit via the return at label-statNext-done
+ */
+ if( pCsr->isAgg ) goto statNextRestart;
+ }
+ }
+
+ return rc;
+}
+
+static int statEof(sqlite3_vtab_cursor *pCursor){
+ StatCursor *pCsr = (StatCursor *)pCursor;
+ return pCsr->isEof;
+}
+
+/* Initialize a cursor according to the query plan idxNum using the
+** arguments in argv[0]. See statBestIndex() for a description of the
+** meaning of the bits in idxNum.
+*/
+static int statFilter(
+ sqlite3_vtab_cursor *pCursor,
+ int idxNum, const char *idxStr,
+ int argc, sqlite3_value **argv
+){
+ StatCursor *pCsr = (StatCursor *)pCursor;
+ StatTable *pTab = (StatTable*)(pCursor->pVtab);
+ sqlite3_str *pSql; /* Query of btrees to analyze */
+ char *zSql; /* String value of pSql */
+ int iArg = 0; /* Count of argv[] parameters used so far */
+ int rc = SQLITE_OK; /* Result of this operation */
+ const char *zName = 0; /* Only provide analysis of this table */
+
+ statResetCsr(pCsr);
+ sqlite3_finalize(pCsr->pStmt);
+ pCsr->pStmt = 0;
+ if( idxNum & 0x01 ){
+ /* schema=? constraint is present. Get its value */
+ const char *zDbase = (const char*)sqlite3_value_text(argv[iArg++]);
+ pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
+ if( pCsr->iDb<0 ){
+ pCsr->iDb = 0;
+ pCsr->isEof = 1;
+ return SQLITE_OK;
+ }
+ }else{
+ pCsr->iDb = pTab->iDb;
+ }
+ if( idxNum & 0x02 ){
+ /* name=? constraint is present */
+ zName = (const char*)sqlite3_value_text(argv[iArg++]);
+ }
+ if( idxNum & 0x04 ){
+ /* aggregate=? constraint is present */
+ pCsr->isAgg = sqlite3_value_double(argv[iArg++])!=0.0;
+ }else{
+ pCsr->isAgg = 0;
+ }
+ pSql = sqlite3_str_new(pTab->db);
+ sqlite3_str_appendf(pSql,
+ "SELECT * FROM ("
+ "SELECT 'sqlite_schema' AS name,1 AS rootpage,'table' AS type"
+ " UNION ALL "
+ "SELECT name,rootpage,type"
+ " FROM \"%w\".sqlite_schema WHERE rootpage!=0)",
+ pTab->db->aDb[pCsr->iDb].zDbSName);
+ if( zName ){
+ sqlite3_str_appendf(pSql, "WHERE name=%Q", zName);
+ }
+ if( idxNum & 0x08 ){
+ sqlite3_str_appendf(pSql, " ORDER BY name");
+ }
+ zSql = sqlite3_str_finish(pSql);
+ if( zSql==0 ){
+ return SQLITE_NOMEM_BKPT;
+ }else{
+ rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
+ sqlite3_free(zSql);
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = statNext(pCursor);
+ }
+ return rc;
+}
+
+static int statColumn(
+ sqlite3_vtab_cursor *pCursor,
+ sqlite3_context *ctx,
+ int i
+){
+ StatCursor *pCsr = (StatCursor *)pCursor;
+ switch( i ){
+ case 0: /* name */
+ sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
+ break;
+ case 1: /* path */
+ if( !pCsr->isAgg ){
+ sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
+ }
+ break;
+ case 2: /* pageno */
+ if( pCsr->isAgg ){
+ sqlite3_result_int64(ctx, pCsr->nPage);
+ }else{
+ sqlite3_result_int64(ctx, pCsr->iPageno);
+ }
+ break;
+ case 3: /* pagetype */
+ if( !pCsr->isAgg ){
+ sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
+ }
+ break;
+ case 4: /* ncell */
+ sqlite3_result_int(ctx, pCsr->nCell);
+ break;
+ case 5: /* payload */
+ sqlite3_result_int(ctx, pCsr->nPayload);
+ break;
+ case 6: /* unused */
+ sqlite3_result_int(ctx, pCsr->nUnused);
+ break;
+ case 7: /* mx_payload */
+ sqlite3_result_int(ctx, pCsr->nMxPayload);
+ break;
+ case 8: /* pgoffset */
+ if( !pCsr->isAgg ){
+ sqlite3_result_int64(ctx, pCsr->iOffset);
+ }
+ break;
+ case 9: /* pgsize */
+ sqlite3_result_int(ctx, pCsr->szPage);
+ break;
+ case 10: { /* schema */
+ sqlite3 *db = sqlite3_context_db_handle(ctx);
+ int iDb = pCsr->iDb;
+ sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
+ break;
+ }
+ default: { /* aggregate */
+ sqlite3_result_int(ctx, pCsr->isAgg);
+ break;
+ }
+ }
+ return SQLITE_OK;
+}
+
+static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
+ StatCursor *pCsr = (StatCursor *)pCursor;
+ *pRowid = pCsr->iPageno;
+ return SQLITE_OK;
+}
+
+/*
+** Invoke this routine to register the "dbstat" virtual table module
+*/
+SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
+ static sqlite3_module dbstat_module = {
+ 0, /* iVersion */
+ statConnect, /* xCreate */
+ statConnect, /* xConnect */
+ statBestIndex, /* xBestIndex */
+ statDisconnect, /* xDisconnect */
+ statDisconnect, /* xDestroy */
+ statOpen, /* xOpen - open a cursor */
+ statClose, /* xClose - close a cursor */
+ statFilter, /* xFilter - configure scan constraints */
+ statNext, /* xNext - advance a cursor */
+ statEof, /* xEof - check for end of scan */
+ statColumn, /* xColumn - read data */
+ statRowid, /* xRowid - read data */
+ 0, /* xUpdate */
+ 0, /* xBegin */
+ 0, /* xSync */
+ 0, /* xCommit */
+ 0, /* xRollback */
+ 0, /* xFindMethod */
+ 0, /* xRename */
+ 0, /* xSavepoint */
+ 0, /* xRelease */
+ 0, /* xRollbackTo */
+ 0 /* xShadowName */
+ };
+ return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
+}
+#elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
+SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
+#endif /* SQLITE_ENABLE_DBSTAT_VTAB */
+
+/************** End of dbstat.c **********************************************/
+/************** Begin file dbpage.c ******************************************/
+/*
+** 2017-10-11
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains an implementation of the "sqlite_dbpage" virtual table.
+**
+** The sqlite_dbpage virtual table is used to read or write whole raw
+** pages of the database file. The pager interface is used so that
+** uncommitted changes and changes recorded in the WAL file are correctly
+** retrieved.
+**
+** Usage example:
+**
+** SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123;
+**
+** This is an eponymous virtual table so it does not need to be created before
+** use. The optional argument to the sqlite_dbpage() table name is the
+** schema for the database file that is to be read. The default schema is
+** "main".
+**
+** The data field of sqlite_dbpage table can be updated. The new
+** value must be a BLOB which is the correct page size, otherwise the
+** update fails. Rows may not be deleted or inserted.
+*/
+
+/* #include "sqliteInt.h" ** Requires access to internal data structures ** */
+#if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
+ && !defined(SQLITE_OMIT_VIRTUALTABLE)
+
+typedef struct DbpageTable DbpageTable;
+typedef struct DbpageCursor DbpageCursor;
+
+struct DbpageCursor {
+ sqlite3_vtab_cursor base; /* Base class. Must be first */
+ int pgno; /* Current page number */
+ int mxPgno; /* Last page to visit on this scan */
+ Pager *pPager; /* Pager being read/written */
+ DbPage *pPage1; /* Page 1 of the database */
+ int iDb; /* Index of database to analyze */
+ int szPage; /* Size of each page in bytes */
+};
+
+struct DbpageTable {
+ sqlite3_vtab base; /* Base class. Must be first */
+ sqlite3 *db; /* The database */
+};
+
+/* Columns */
+#define DBPAGE_COLUMN_PGNO 0
+#define DBPAGE_COLUMN_DATA 1
+#define DBPAGE_COLUMN_SCHEMA 2
+
+
+
+/*
+** Connect to or create a dbpagevfs virtual table.
+*/
+static int dbpageConnect(
+ sqlite3 *db,
+ void *pAux,
+ int argc, const char *const*argv,
+ sqlite3_vtab **ppVtab,
+ char **pzErr
+){
+ DbpageTable *pTab = 0;
+ int rc = SQLITE_OK;
+
+ sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
+ rc = sqlite3_declare_vtab(db,
+ "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
+ if( rc==SQLITE_OK ){
+ pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
+ if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
+ }
+
+ assert( rc==SQLITE_OK || pTab==0 );
+ if( rc==SQLITE_OK ){
+ memset(pTab, 0, sizeof(DbpageTable));
+ pTab->db = db;
+ }
+
+ *ppVtab = (sqlite3_vtab*)pTab;
+ return rc;
+}
+
+/*
+** Disconnect from or destroy a dbpagevfs virtual table.
+*/
+static int dbpageDisconnect(sqlite3_vtab *pVtab){
+ sqlite3_free(pVtab);
+ return SQLITE_OK;
+}
+
+/*
+** idxNum:
+**
+** 0 schema=main, full table scan
+** 1 schema=main, pgno=?1
+** 2 schema=?1, full table scan
+** 3 schema=?1, pgno=?2
+*/
+static int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
+ int i;
+ int iPlan = 0;
+
+ /* If there is a schema= constraint, it must be honored. Report a
+ ** ridiculously large estimated cost if the schema= constraint is
+ ** unavailable
+ */
+ for(i=0; i<pIdxInfo->nConstraint; i++){
+ struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
+ if( p->iColumn!=DBPAGE_COLUMN_SCHEMA ) continue;
+ if( p->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
+ if( !p->usable ){
+ /* No solution. */
+ return SQLITE_CONSTRAINT;
+ }
+ iPlan = 2;
+ pIdxInfo->aConstraintUsage[i].argvIndex = 1;
+ pIdxInfo->aConstraintUsage[i].omit = 1;
+ break;
+ }
+
+ /* If we reach this point, it means that either there is no schema=
+ ** constraint (in which case we use the "main" schema) or else the
+ ** schema constraint was accepted. Lower the estimated cost accordingly
+ */
+ pIdxInfo->estimatedCost = 1.0e6;
+
+ /* Check for constraints against pgno */
+ for(i=0; i<pIdxInfo->nConstraint; i++){
+ struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
+ if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
+ pIdxInfo->estimatedRows = 1;
+ pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
+ pIdxInfo->estimatedCost = 1.0;
+ pIdxInfo->aConstraintUsage[i].argvIndex = iPlan ? 2 : 1;
+ pIdxInfo->aConstraintUsage[i].omit = 1;
+ iPlan |= 1;
+ break;
+ }
+ }
+ pIdxInfo->idxNum = iPlan;
+
+ if( pIdxInfo->nOrderBy>=1
+ && pIdxInfo->aOrderBy[0].iColumn<=0
+ && pIdxInfo->aOrderBy[0].desc==0
+ ){
+ pIdxInfo->orderByConsumed = 1;
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Open a new dbpagevfs cursor.
+*/
+static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
+ DbpageCursor *pCsr;
+
+ pCsr = (DbpageCursor *)sqlite3_malloc64(sizeof(DbpageCursor));
+ if( pCsr==0 ){
+ return SQLITE_NOMEM_BKPT;
+ }else{
+ memset(pCsr, 0, sizeof(DbpageCursor));
+ pCsr->base.pVtab = pVTab;
+ pCsr->pgno = -1;
+ }
+
+ *ppCursor = (sqlite3_vtab_cursor *)pCsr;
+ return SQLITE_OK;
+}
+
+/*
+** Close a dbpagevfs cursor.
+*/
+static int dbpageClose(sqlite3_vtab_cursor *pCursor){
+ DbpageCursor *pCsr = (DbpageCursor *)pCursor;
+ if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
+ sqlite3_free(pCsr);
+ return SQLITE_OK;
+}
+
+/*
+** Move a dbpagevfs cursor to the next entry in the file.
+*/
+static int dbpageNext(sqlite3_vtab_cursor *pCursor){
+ int rc = SQLITE_OK;
+ DbpageCursor *pCsr = (DbpageCursor *)pCursor;
+ pCsr->pgno++;
+ return rc;
+}
+
+static int dbpageEof(sqlite3_vtab_cursor *pCursor){
+ DbpageCursor *pCsr = (DbpageCursor *)pCursor;
+ return pCsr->pgno > pCsr->mxPgno;
+}
+
+/*
+** idxNum:
+**
+** 0 schema=main, full table scan
+** 1 schema=main, pgno=?1
+** 2 schema=?1, full table scan
+** 3 schema=?1, pgno=?2
+**
+** idxStr is not used
+*/
+static int dbpageFilter(
+ sqlite3_vtab_cursor *pCursor,
+ int idxNum, const char *idxStr,
+ int argc, sqlite3_value **argv
+){
+ DbpageCursor *pCsr = (DbpageCursor *)pCursor;
+ DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
+ int rc;
+ sqlite3 *db = pTab->db;
+ Btree *pBt;
+
+ /* Default setting is no rows of result */
+ pCsr->pgno = 1;
+ pCsr->mxPgno = 0;
+
+ if( idxNum & 2 ){
+ const char *zSchema;
+ assert( argc>=1 );
+ zSchema = (const char*)sqlite3_value_text(argv[0]);
+ pCsr->iDb = sqlite3FindDbName(db, zSchema);
+ if( pCsr->iDb<0 ) return SQLITE_OK;
+ }else{
+ pCsr->iDb = 0;
+ }
+ pBt = db->aDb[pCsr->iDb].pBt;
+ if( pBt==0 ) return SQLITE_OK;
+ pCsr->pPager = sqlite3BtreePager(pBt);
+ pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
+ pCsr->mxPgno = sqlite3BtreeLastPage(pBt);
+ if( idxNum & 1 ){
+ assert( argc>(idxNum>>1) );
+ pCsr->pgno = sqlite3_value_int(argv[idxNum>>1]);
+ if( pCsr->pgno<1 || pCsr->pgno>pCsr->mxPgno ){
+ pCsr->pgno = 1;
+ pCsr->mxPgno = 0;
+ }else{
+ pCsr->mxPgno = pCsr->pgno;
+ }
+ }else{
+ assert( pCsr->pgno==1 );
+ }
+ if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
+ rc = sqlite3PagerGet(pCsr->pPager, 1, &pCsr->pPage1, 0);
+ return rc;
+}
+
+static int dbpageColumn(
+ sqlite3_vtab_cursor *pCursor,
+ sqlite3_context *ctx,
+ int i
+){
+ DbpageCursor *pCsr = (DbpageCursor *)pCursor;
+ int rc = SQLITE_OK;
+ switch( i ){
+ case 0: { /* pgno */
+ sqlite3_result_int(ctx, pCsr->pgno);
+ break;
+ }
+ case 1: { /* data */
+ DbPage *pDbPage = 0;
+ rc = sqlite3PagerGet(pCsr->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pCsr->szPage,
+ SQLITE_TRANSIENT);
+ }
+ sqlite3PagerUnref(pDbPage);
+ break;
+ }
+ default: { /* schema */
+ sqlite3 *db = sqlite3_context_db_handle(ctx);
+ sqlite3_result_text(ctx, db->aDb[pCsr->iDb].zDbSName, -1, SQLITE_STATIC);
+ break;
+ }
+ }
+ return SQLITE_OK;
+}
+
+static int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
+ DbpageCursor *pCsr = (DbpageCursor *)pCursor;
+ *pRowid = pCsr->pgno;
+ return SQLITE_OK;
+}
+
+static int dbpageUpdate(
+ sqlite3_vtab *pVtab,
+ int argc,
+ sqlite3_value **argv,
+ sqlite_int64 *pRowid
+){
+ DbpageTable *pTab = (DbpageTable *)pVtab;
+ Pgno pgno;
+ DbPage *pDbPage = 0;
+ int rc = SQLITE_OK;
+ char *zErr = 0;
+ const char *zSchema;
+ int iDb;
+ Btree *pBt;
+ Pager *pPager;
+ int szPage;
+
+ if( pTab->db->flags & SQLITE_Defensive ){
+ zErr = "read-only";
+ goto update_fail;
+ }
+ if( argc==1 ){
+ zErr = "cannot delete";
+ goto update_fail;
+ }
+ pgno = sqlite3_value_int(argv[0]);
+ if( (Pgno)sqlite3_value_int(argv[1])!=pgno ){
+ zErr = "cannot insert";
+ goto update_fail;
+ }
+ zSchema = (const char*)sqlite3_value_text(argv[4]);
+ iDb = zSchema ? sqlite3FindDbName(pTab->db, zSchema) : -1;
+ if( iDb<0 ){
+ zErr = "no such schema";
+ goto update_fail;
+ }
+ pBt = pTab->db->aDb[iDb].pBt;
+ if( pgno<1 || pBt==0 || pgno>(int)sqlite3BtreeLastPage(pBt) ){
+ zErr = "bad page number";
+ goto update_fail;
+ }
+ szPage = sqlite3BtreeGetPageSize(pBt);
+ if( sqlite3_value_type(argv[3])!=SQLITE_BLOB
+ || sqlite3_value_bytes(argv[3])!=szPage
+ ){
+ zErr = "bad page value";
+ goto update_fail;
+ }
+ pPager = sqlite3BtreePager(pBt);
+ rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3PagerWrite(pDbPage);
+ if( rc==SQLITE_OK ){
+ memcpy(sqlite3PagerGetData(pDbPage),
+ sqlite3_value_blob(argv[3]),
+ szPage);
+ }
+ }
+ sqlite3PagerUnref(pDbPage);
+ return rc;
+
+update_fail:
+ sqlite3_free(pVtab->zErrMsg);
+ pVtab->zErrMsg = sqlite3_mprintf("%s", zErr);
+ return SQLITE_ERROR;
+}
+
+/* Since we do not know in advance which database files will be
+** written by the sqlite_dbpage virtual table, start a write transaction
+** on them all.
+*/
+static int dbpageBegin(sqlite3_vtab *pVtab){
+ DbpageTable *pTab = (DbpageTable *)pVtab;
+ sqlite3 *db = pTab->db;
+ int i;
+ for(i=0; i<db->nDb; i++){
+ Btree *pBt = db->aDb[i].pBt;
+ if( pBt ) sqlite3BtreeBeginTrans(pBt, 1, 0);
+ }
+ return SQLITE_OK;
+}
+
+
+/*
+** Invoke this routine to register the "dbpage" virtual table module
+*/
+SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
+ static sqlite3_module dbpage_module = {
+ 0, /* iVersion */
+ dbpageConnect, /* xCreate */
+ dbpageConnect, /* xConnect */
+ dbpageBestIndex, /* xBestIndex */
+ dbpageDisconnect, /* xDisconnect */
+ dbpageDisconnect, /* xDestroy */
+ dbpageOpen, /* xOpen - open a cursor */
+ dbpageClose, /* xClose - close a cursor */
+ dbpageFilter, /* xFilter - configure scan constraints */
+ dbpageNext, /* xNext - advance a cursor */
+ dbpageEof, /* xEof - check for end of scan */
+ dbpageColumn, /* xColumn - read data */
+ dbpageRowid, /* xRowid - read data */
+ dbpageUpdate, /* xUpdate */
+ dbpageBegin, /* xBegin */
+ 0, /* xSync */
+ 0, /* xCommit */
+ 0, /* xRollback */
+ 0, /* xFindMethod */
+ 0, /* xRename */
+ 0, /* xSavepoint */
+ 0, /* xRelease */
+ 0, /* xRollbackTo */
+ 0 /* xShadowName */
+ };
+ return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
+}
+#elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
+SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }
+#endif /* SQLITE_ENABLE_DBSTAT_VTAB */
+
+/************** End of dbpage.c **********************************************/
+/************** Begin file sqlite3session.c **********************************/
+
+#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
+/* #include "sqlite3session.h" */
+/* #include <assert.h> */
+/* #include <string.h> */
+
+#ifndef SQLITE_AMALGAMATION
+/* # include "sqliteInt.h" */
+/* # include "vdbeInt.h" */
+#endif
+
+typedef struct SessionTable SessionTable;
+typedef struct SessionChange SessionChange;
+typedef struct SessionBuffer SessionBuffer;
+typedef struct SessionInput SessionInput;
+
+/*
+** Minimum chunk size used by streaming versions of functions.
+*/
+#ifndef SESSIONS_STRM_CHUNK_SIZE
+# ifdef SQLITE_TEST
+# define SESSIONS_STRM_CHUNK_SIZE 64
+# else
+# define SESSIONS_STRM_CHUNK_SIZE 1024
+# endif
+#endif
+
+static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE;
+
+typedef struct SessionHook SessionHook;
+struct SessionHook {
+ void *pCtx;
+ int (*xOld)(void*,int,sqlite3_value**);
+ int (*xNew)(void*,int,sqlite3_value**);
+ int (*xCount)(void*);
+ int (*xDepth)(void*);
+};
+
+/*
+** Session handle structure.
+*/
+struct sqlite3_session {
+ sqlite3 *db; /* Database handle session is attached to */
+ char *zDb; /* Name of database session is attached to */
+ int bEnable; /* True if currently recording */
+ int bIndirect; /* True if all changes are indirect */
+ int bAutoAttach; /* True to auto-attach tables */
+ int rc; /* Non-zero if an error has occurred */
+ void *pFilterCtx; /* First argument to pass to xTableFilter */
+ int (*xTableFilter)(void *pCtx, const char *zTab);
+ sqlite3_value *pZeroBlob; /* Value containing X'' */
+ sqlite3_session *pNext; /* Next session object on same db. */
+ SessionTable *pTable; /* List of attached tables */
+ SessionHook hook; /* APIs to grab new and old data with */
+};
+
+/*
+** Instances of this structure are used to build strings or binary records.
+*/
+struct SessionBuffer {
+ u8 *aBuf; /* Pointer to changeset buffer */
+ int nBuf; /* Size of buffer aBuf */
+ int nAlloc; /* Size of allocation containing aBuf */
+};
+
+/*
+** An object of this type is used internally as an abstraction for
+** input data. Input data may be supplied either as a single large buffer
+** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
+** sqlite3changeset_start_strm()).
+*/
+struct SessionInput {
+ int bNoDiscard; /* If true, do not discard in InputBuffer() */
+ int iCurrent; /* Offset in aData[] of current change */
+ int iNext; /* Offset in aData[] of next change */
+ u8 *aData; /* Pointer to buffer containing changeset */
+ int nData; /* Number of bytes in aData */
+
+ SessionBuffer buf; /* Current read buffer */
+ int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
+ void *pIn; /* First argument to xInput */
+ int bEof; /* Set to true after xInput finished */
+};
+
+/*
+** Structure for changeset iterators.
+*/
+struct sqlite3_changeset_iter {
+ SessionInput in; /* Input buffer or stream */
+ SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
+ int bPatchset; /* True if this is a patchset */
+ int bInvert; /* True to invert changeset */
+ int rc; /* Iterator error code */
+ sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
+ char *zTab; /* Current table */
+ int nCol; /* Number of columns in zTab */
+ int op; /* Current operation */
+ int bIndirect; /* True if current change was indirect */
+ u8 *abPK; /* Primary key array */
+ sqlite3_value **apValue; /* old.* and new.* values */
+};
+
+/*
+** Each session object maintains a set of the following structures, one
+** for each table the session object is monitoring. The structures are
+** stored in a linked list starting at sqlite3_session.pTable.
+**
+** The keys of the SessionTable.aChange[] hash table are all rows that have
+** been modified in any way since the session object was attached to the
+** table.
+**
+** The data associated with each hash-table entry is a structure containing
+** a subset of the initial values that the modified row contained at the
+** start of the session. Or no initial values if the row was inserted.
+*/
+struct SessionTable {
+ SessionTable *pNext;
+ char *zName; /* Local name of table */
+ int nCol; /* Number of columns in table zName */
+ int bStat1; /* True if this is sqlite_stat1 */
+ const char **azCol; /* Column names */
+ u8 *abPK; /* Array of primary key flags */
+ int nEntry; /* Total number of entries in hash table */
+ int nChange; /* Size of apChange[] array */
+ SessionChange **apChange; /* Hash table buckets */
+};
+
+/*
+** RECORD FORMAT:
+**
+** The following record format is similar to (but not compatible with) that
+** used in SQLite database files. This format is used as part of the
+** change-set binary format, and so must be architecture independent.
+**
+** Unlike the SQLite database record format, each field is self-contained -
+** there is no separation of header and data. Each field begins with a
+** single byte describing its type, as follows:
+**
+** 0x00: Undefined value.
+** 0x01: Integer value.
+** 0x02: Real value.
+** 0x03: Text value.
+** 0x04: Blob value.
+** 0x05: SQL NULL value.
+**
+** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
+** and so on in sqlite3.h. For undefined and NULL values, the field consists
+** only of the single type byte. For other types of values, the type byte
+** is followed by:
+**
+** Text values:
+** A varint containing the number of bytes in the value (encoded using
+** UTF-8). Followed by a buffer containing the UTF-8 representation
+** of the text value. There is no nul terminator.
+**
+** Blob values:
+** A varint containing the number of bytes in the value, followed by
+** a buffer containing the value itself.
+**
+** Integer values:
+** An 8-byte big-endian integer value.
+**
+** Real values:
+** An 8-byte big-endian IEEE 754-2008 real value.
+**
+** Varint values are encoded in the same way as varints in the SQLite
+** record format.
+**
+** CHANGESET FORMAT:
+**
+** A changeset is a collection of DELETE, UPDATE and INSERT operations on
+** one or more tables. Operations on a single table are grouped together,
+** but may occur in any order (i.e. deletes, updates and inserts are all
+** mixed together).
+**
+** Each group of changes begins with a table header:
+**
+** 1 byte: Constant 0x54 (capital 'T')
+** Varint: Number of columns in the table.
+** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
+** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
+**
+** Followed by one or more changes to the table.
+**
+** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
+** 1 byte: The "indirect-change" flag.
+** old.* record: (delete and update only)
+** new.* record: (insert and update only)
+**
+** The "old.*" and "new.*" records, if present, are N field records in the
+** format described above under "RECORD FORMAT", where N is the number of
+** columns in the table. The i'th field of each record is associated with
+** the i'th column of the table, counting from left to right in the order
+** in which columns were declared in the CREATE TABLE statement.
+**
+** The new.* record that is part of each INSERT change contains the values
+** that make up the new row. Similarly, the old.* record that is part of each
+** DELETE change contains the values that made up the row that was deleted
+** from the database. In the changeset format, the records that are part
+** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
+** fields.
+**
+** Within the old.* record associated with an UPDATE change, all fields
+** associated with table columns that are not PRIMARY KEY columns and are
+** not modified by the UPDATE change are set to "undefined". Other fields
+** are set to the values that made up the row before the UPDATE that the
+** change records took place. Within the new.* record, fields associated
+** with table columns modified by the UPDATE change contain the new
+** values. Fields associated with table columns that are not modified
+** are set to "undefined".
+**
+** PATCHSET FORMAT:
+**
+** A patchset is also a collection of changes. It is similar to a changeset,
+** but leaves undefined those fields that are not useful if no conflict
+** resolution is required when applying the changeset.
+**
+** Each group of changes begins with a table header:
+**
+** 1 byte: Constant 0x50 (capital 'P')
+** Varint: Number of columns in the table.
+** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
+** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
+**
+** Followed by one or more changes to the table.
+**
+** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
+** 1 byte: The "indirect-change" flag.
+** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
+** full record for INSERT).
+**
+** As in the changeset format, each field of the single record that is part
+** of a patchset change is associated with the correspondingly positioned
+** table column, counting from left to right within the CREATE TABLE
+** statement.
+**
+** For a DELETE change, all fields within the record except those associated
+** with PRIMARY KEY columns are omitted. The PRIMARY KEY fields contain the
+** values identifying the row to delete.
+**
+** For an UPDATE change, all fields except those associated with PRIMARY KEY
+** columns and columns that are modified by the UPDATE are set to "undefined".
+** PRIMARY KEY fields contain the values identifying the table row to update,
+** and fields associated with modified columns contain the new column values.
+**
+** The records associated with INSERT changes are in the same format as for
+** changesets. It is not possible for a record associated with an INSERT
+** change to contain a field set to "undefined".
+**
+** REBASE BLOB FORMAT:
+**
+** A rebase blob may be output by sqlite3changeset_apply_v2() and its
+** streaming equivalent for use with the sqlite3_rebaser APIs to rebase
+** existing changesets. A rebase blob contains one entry for each conflict
+** resolved using either the OMIT or REPLACE strategies within the apply_v2()
+** call.
+**
+** The format used for a rebase blob is very similar to that used for
+** changesets. All entries related to a single table are grouped together.
+**
+** Each group of entries begins with a table header in changeset format:
+**
+** 1 byte: Constant 0x54 (capital 'T')
+** Varint: Number of columns in the table.
+** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
+** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
+**
+** Followed by one or more entries associated with the table.
+**
+** 1 byte: Either SQLITE_INSERT (0x12), DELETE (0x09).
+** 1 byte: Flag. 0x01 for REPLACE, 0x00 for OMIT.
+** record: (in the record format defined above).
+**
+** In a rebase blob, the first field is set to SQLITE_INSERT if the change
+** that caused the conflict was an INSERT or UPDATE, or to SQLITE_DELETE if
+** it was a DELETE. The second field is set to 0x01 if the conflict
+** resolution strategy was REPLACE, or 0x00 if it was OMIT.
+**
+** If the change that caused the conflict was a DELETE, then the single
+** record is a copy of the old.* record from the original changeset. If it
+** was an INSERT, then the single record is a copy of the new.* record. If
+** the conflicting change was an UPDATE, then the single record is a copy
+** of the new.* record with the PK fields filled in based on the original
+** old.* record.
+*/
+
+/*
+** For each row modified during a session, there exists a single instance of
+** this structure stored in a SessionTable.aChange[] hash table.
+*/
+struct SessionChange {
+ int op; /* One of UPDATE, DELETE, INSERT */
+ int bIndirect; /* True if this change is "indirect" */
+ int nRecord; /* Number of bytes in buffer aRecord[] */
+ u8 *aRecord; /* Buffer containing old.* record */
+ SessionChange *pNext; /* For hash-table collisions */
+};
+
+/*
+** Write a varint with value iVal into the buffer at aBuf. Return the
+** number of bytes written.
+*/
+static int sessionVarintPut(u8 *aBuf, int iVal){
+ return putVarint32(aBuf, iVal);
+}
+
+/*
+** Return the number of bytes required to store value iVal as a varint.
+*/
+static int sessionVarintLen(int iVal){
+ return sqlite3VarintLen(iVal);
+}
+
+/*
+** Read a varint value from aBuf[] into *piVal. Return the number of
+** bytes read.
+*/
+static int sessionVarintGet(u8 *aBuf, int *piVal){
+ return getVarint32(aBuf, *piVal);
+}
+
+/* Load an unaligned and unsigned 32-bit integer */
+#define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
+
+/*
+** Read a 64-bit big-endian integer value from buffer aRec[]. Return
+** the value read.
+*/
+static sqlite3_int64 sessionGetI64(u8 *aRec){
+ u64 x = SESSION_UINT32(aRec);
+ u32 y = SESSION_UINT32(aRec+4);
+ x = (x<<32) + y;
+ return (sqlite3_int64)x;
+}
+
+/*
+** Write a 64-bit big-endian integer value to the buffer aBuf[].
+*/
+static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
+ aBuf[0] = (i>>56) & 0xFF;
+ aBuf[1] = (i>>48) & 0xFF;
+ aBuf[2] = (i>>40) & 0xFF;
+ aBuf[3] = (i>>32) & 0xFF;
+ aBuf[4] = (i>>24) & 0xFF;
+ aBuf[5] = (i>>16) & 0xFF;
+ aBuf[6] = (i>> 8) & 0xFF;
+ aBuf[7] = (i>> 0) & 0xFF;
+}
+
+/*
+** This function is used to serialize the contents of value pValue (see
+** comment titled "RECORD FORMAT" above).
+**
+** If it is non-NULL, the serialized form of the value is written to
+** buffer aBuf. *pnWrite is set to the number of bytes written before
+** returning. Or, if aBuf is NULL, the only thing this function does is
+** set *pnWrite.
+**
+** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
+** within a call to sqlite3_value_text() (may fail if the db is utf-16))
+** SQLITE_NOMEM is returned.
+*/
+static int sessionSerializeValue(
+ u8 *aBuf, /* If non-NULL, write serialized value here */
+ sqlite3_value *pValue, /* Value to serialize */
+ sqlite3_int64 *pnWrite /* IN/OUT: Increment by bytes written */
+){
+ int nByte; /* Size of serialized value in bytes */
+
+ if( pValue ){
+ int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
+
+ eType = sqlite3_value_type(pValue);
+ if( aBuf ) aBuf[0] = eType;
+
+ switch( eType ){
+ case SQLITE_NULL:
+ nByte = 1;
+ break;
+
+ case SQLITE_INTEGER:
+ case SQLITE_FLOAT:
+ if( aBuf ){
+ /* TODO: SQLite does something special to deal with mixed-endian
+ ** floating point values (e.g. ARM7). This code probably should
+ ** too. */
+ u64 i;
+ if( eType==SQLITE_INTEGER ){
+ i = (u64)sqlite3_value_int64(pValue);
+ }else{
+ double r;
+ assert( sizeof(double)==8 && sizeof(u64)==8 );
+ r = sqlite3_value_double(pValue);
+ memcpy(&i, &r, 8);
+ }
+ sessionPutI64(&aBuf[1], i);
+ }
+ nByte = 9;
+ break;
+
+ default: {
+ u8 *z;
+ int n;
+ int nVarint;
+
+ assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
+ if( eType==SQLITE_TEXT ){
+ z = (u8 *)sqlite3_value_text(pValue);
+ }else{
+ z = (u8 *)sqlite3_value_blob(pValue);
+ }
+ n = sqlite3_value_bytes(pValue);
+ if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
+ nVarint = sessionVarintLen(n);
+
+ if( aBuf ){
+ sessionVarintPut(&aBuf[1], n);
+ if( n ) memcpy(&aBuf[nVarint + 1], z, n);
+ }
+
+ nByte = 1 + nVarint + n;
+ break;
+ }
+ }
+ }else{
+ nByte = 1;
+ if( aBuf ) aBuf[0] = '\0';
+ }
+
+ if( pnWrite ) *pnWrite += nByte;
+ return SQLITE_OK;
+}
+
+
+/*
+** This macro is used to calculate hash key values for data structures. In
+** order to use this macro, the entire data structure must be represented
+** as a series of unsigned integers. In order to calculate a hash-key value
+** for a data structure represented as three such integers, the macro may
+** then be used as follows:
+**
+** int hash_key_value;
+** hash_key_value = HASH_APPEND(0, <value 1>);
+** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
+** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
+**
+** In practice, the data structures this macro is used for are the primary
+** key values of modified rows.
+*/
+#define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
+
+/*
+** Append the hash of the 64-bit integer passed as the second argument to the
+** hash-key value passed as the first. Return the new hash-key value.
+*/
+static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
+ h = HASH_APPEND(h, i & 0xFFFFFFFF);
+ return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
+}
+
+/*
+** Append the hash of the blob passed via the second and third arguments to
+** the hash-key value passed as the first. Return the new hash-key value.
+*/
+static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
+ int i;
+ for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
+ return h;
+}
+
+/*
+** Append the hash of the data type passed as the second argument to the
+** hash-key value passed as the first. Return the new hash-key value.
+*/
+static unsigned int sessionHashAppendType(unsigned int h, int eType){
+ return HASH_APPEND(h, eType);
+}
+
+/*
+** This function may only be called from within a pre-update callback.
+** It calculates a hash based on the primary key values of the old.* or
+** new.* row currently available and, assuming no error occurs, writes it to
+** *piHash before returning. If the primary key contains one or more NULL
+** values, *pbNullPK is set to true before returning.
+**
+** If an error occurs, an SQLite error code is returned and the final values
+** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
+** and the output variables are set as described above.
+*/
+static int sessionPreupdateHash(
+ sqlite3_session *pSession, /* Session object that owns pTab */
+ SessionTable *pTab, /* Session table handle */
+ int bNew, /* True to hash the new.* PK */
+ int *piHash, /* OUT: Hash value */
+ int *pbNullPK /* OUT: True if there are NULL values in PK */
+){
+ unsigned int h = 0; /* Hash value to return */
+ int i; /* Used to iterate through columns */
+
+ assert( *pbNullPK==0 );
+ assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
+ for(i=0; i<pTab->nCol; i++){
+ if( pTab->abPK[i] ){
+ int rc;
+ int eType;
+ sqlite3_value *pVal;
+
+ if( bNew ){
+ rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
+ }else{
+ rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
+ }
+ if( rc!=SQLITE_OK ) return rc;
+
+ eType = sqlite3_value_type(pVal);
+ h = sessionHashAppendType(h, eType);
+ if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
+ i64 iVal;
+ if( eType==SQLITE_INTEGER ){
+ iVal = sqlite3_value_int64(pVal);
+ }else{
+ double rVal = sqlite3_value_double(pVal);
+ assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
+ memcpy(&iVal, &rVal, 8);
+ }
+ h = sessionHashAppendI64(h, iVal);
+ }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
+ const u8 *z;
+ int n;
+ if( eType==SQLITE_TEXT ){
+ z = (const u8 *)sqlite3_value_text(pVal);
+ }else{
+ z = (const u8 *)sqlite3_value_blob(pVal);
+ }
+ n = sqlite3_value_bytes(pVal);
+ if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
+ h = sessionHashAppendBlob(h, n, z);
+ }else{
+ assert( eType==SQLITE_NULL );
+ assert( pTab->bStat1==0 || i!=1 );
+ *pbNullPK = 1;
+ }
+ }
+ }
+
+ *piHash = (h % pTab->nChange);
+ return SQLITE_OK;
+}
+
+/*
+** The buffer that the argument points to contains a serialized SQL value.
+** Return the number of bytes of space occupied by the value (including
+** the type byte).
+*/
+static int sessionSerialLen(u8 *a){
+ int e = *a;
+ int n;
+ if( e==0 || e==0xFF ) return 1;
+ if( e==SQLITE_NULL ) return 1;
+ if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
+ return sessionVarintGet(&a[1], &n) + 1 + n;
+}
+
+/*
+** Based on the primary key values stored in change aRecord, calculate a
+** hash key. Assume the has table has nBucket buckets. The hash keys
+** calculated by this function are compatible with those calculated by
+** sessionPreupdateHash().
+**
+** The bPkOnly argument is non-zero if the record at aRecord[] is from
+** a patchset DELETE. In this case the non-PK fields are omitted entirely.
+*/
+static unsigned int sessionChangeHash(
+ SessionTable *pTab, /* Table handle */
+ int bPkOnly, /* Record consists of PK fields only */
+ u8 *aRecord, /* Change record */
+ int nBucket /* Assume this many buckets in hash table */
+){
+ unsigned int h = 0; /* Value to return */
+ int i; /* Used to iterate through columns */
+ u8 *a = aRecord; /* Used to iterate through change record */
+
+ for(i=0; i<pTab->nCol; i++){
+ int eType = *a;
+ int isPK = pTab->abPK[i];
+ if( bPkOnly && isPK==0 ) continue;
+
+ /* It is not possible for eType to be SQLITE_NULL here. The session
+ ** module does not record changes for rows with NULL values stored in
+ ** primary key columns. */
+ assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
+ || eType==SQLITE_TEXT || eType==SQLITE_BLOB
+ || eType==SQLITE_NULL || eType==0
+ );
+ assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
+
+ if( isPK ){
+ a++;
+ h = sessionHashAppendType(h, eType);
+ if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
+ h = sessionHashAppendI64(h, sessionGetI64(a));
+ a += 8;
+ }else{
+ int n;
+ a += sessionVarintGet(a, &n);
+ h = sessionHashAppendBlob(h, n, a);
+ a += n;
+ }
+ }else{
+ a += sessionSerialLen(a);
+ }
+ }
+ return (h % nBucket);
+}
+
+/*
+** Arguments aLeft and aRight are pointers to change records for table pTab.
+** This function returns true if the two records apply to the same row (i.e.
+** have the same values stored in the primary key columns), or false
+** otherwise.
+*/
+static int sessionChangeEqual(
+ SessionTable *pTab, /* Table used for PK definition */
+ int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
+ u8 *aLeft, /* Change record */
+ int bRightPkOnly, /* True if aRight[] contains PK fields only */
+ u8 *aRight /* Change record */
+){
+ u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
+ u8 *a2 = aRight; /* Cursor to iterate through aRight */
+ int iCol; /* Used to iterate through table columns */
+
+ for(iCol=0; iCol<pTab->nCol; iCol++){
+ if( pTab->abPK[iCol] ){
+ int n1 = sessionSerialLen(a1);
+ int n2 = sessionSerialLen(a2);
+
+ if( n1!=n2 || memcmp(a1, a2, n1) ){
+ return 0;
+ }
+ a1 += n1;
+ a2 += n2;
+ }else{
+ if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
+ if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
+ }
+ }
+
+ return 1;
+}
+
+/*
+** Arguments aLeft and aRight both point to buffers containing change
+** records with nCol columns. This function "merges" the two records into
+** a single records which is written to the buffer at *paOut. *paOut is
+** then set to point to one byte after the last byte written before
+** returning.
+**
+** The merging of records is done as follows: For each column, if the
+** aRight record contains a value for the column, copy the value from
+** their. Otherwise, if aLeft contains a value, copy it. If neither
+** record contains a value for a given column, then neither does the
+** output record.
+*/
+static void sessionMergeRecord(
+ u8 **paOut,
+ int nCol,
+ u8 *aLeft,
+ u8 *aRight
+){
+ u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
+ u8 *a2 = aRight; /* Cursor used to iterate through aRight */
+ u8 *aOut = *paOut; /* Output cursor */
+ int iCol; /* Used to iterate from 0 to nCol */
+
+ for(iCol=0; iCol<nCol; iCol++){
+ int n1 = sessionSerialLen(a1);
+ int n2 = sessionSerialLen(a2);
+ if( *a2 ){
+ memcpy(aOut, a2, n2);
+ aOut += n2;
+ }else{
+ memcpy(aOut, a1, n1);
+ aOut += n1;
+ }
+ a1 += n1;
+ a2 += n2;
+ }
+
+ *paOut = aOut;
+}
+
+/*
+** This is a helper function used by sessionMergeUpdate().
+**
+** When this function is called, both *paOne and *paTwo point to a value
+** within a change record. Before it returns, both have been advanced so
+** as to point to the next value in the record.
+**
+** If, when this function is called, *paTwo points to a valid value (i.e.
+** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
+** pointer is returned and *pnVal is set to the number of bytes in the
+** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
+** set to the number of bytes in the value at *paOne. If *paOne points
+** to the "no value" placeholder, *pnVal is set to 1. In other words:
+**
+** if( *paTwo is valid ) return *paTwo;
+** return *paOne;
+**
+*/
+static u8 *sessionMergeValue(
+ u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
+ u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
+ int *pnVal /* OUT: Bytes in returned value */
+){
+ u8 *a1 = *paOne;
+ u8 *a2 = *paTwo;
+ u8 *pRet = 0;
+ int n1;
+
+ assert( a1 );
+ if( a2 ){
+ int n2 = sessionSerialLen(a2);
+ if( *a2 ){
+ *pnVal = n2;
+ pRet = a2;
+ }
+ *paTwo = &a2[n2];
+ }
+
+ n1 = sessionSerialLen(a1);
+ if( pRet==0 ){
+ *pnVal = n1;
+ pRet = a1;
+ }
+ *paOne = &a1[n1];
+
+ return pRet;
+}
+
+/*
+** This function is used by changeset_concat() to merge two UPDATE changes
+** on the same row.
+*/
+static int sessionMergeUpdate(
+ u8 **paOut, /* IN/OUT: Pointer to output buffer */
+ SessionTable *pTab, /* Table change pertains to */
+ int bPatchset, /* True if records are patchset records */
+ u8 *aOldRecord1, /* old.* record for first change */
+ u8 *aOldRecord2, /* old.* record for second change */
+ u8 *aNewRecord1, /* new.* record for first change */
+ u8 *aNewRecord2 /* new.* record for second change */
+){
+ u8 *aOld1 = aOldRecord1;
+ u8 *aOld2 = aOldRecord2;
+ u8 *aNew1 = aNewRecord1;
+ u8 *aNew2 = aNewRecord2;
+
+ u8 *aOut = *paOut;
+ int i;
+
+ if( bPatchset==0 ){
+ int bRequired = 0;
+
+ assert( aOldRecord1 && aNewRecord1 );
+
+ /* Write the old.* vector first. */
+ for(i=0; i<pTab->nCol; i++){
+ int nOld;
+ u8 *aOld;
+ int nNew;
+ u8 *aNew;
+
+ aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
+ aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
+ if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
+ if( pTab->abPK[i]==0 ) bRequired = 1;
+ memcpy(aOut, aOld, nOld);
+ aOut += nOld;
+ }else{
+ *(aOut++) = '\0';
+ }
+ }
+
+ if( !bRequired ) return 0;
+ }
+
+ /* Write the new.* vector */
+ aOld1 = aOldRecord1;
+ aOld2 = aOldRecord2;
+ aNew1 = aNewRecord1;
+ aNew2 = aNewRecord2;
+ for(i=0; i<pTab->nCol; i++){
+ int nOld;
+ u8 *aOld;
+ int nNew;
+ u8 *aNew;
+
+ aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
+ aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
+ if( bPatchset==0
+ && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
+ ){
+ *(aOut++) = '\0';
+ }else{
+ memcpy(aOut, aNew, nNew);
+ aOut += nNew;
+ }
+ }
+
+ *paOut = aOut;
+ return 1;
+}
+
+/*
+** This function is only called from within a pre-update-hook callback.
+** It determines if the current pre-update-hook change affects the same row
+** as the change stored in argument pChange. If so, it returns true. Otherwise
+** if the pre-update-hook does not affect the same row as pChange, it returns
+** false.
+*/
+static int sessionPreupdateEqual(
+ sqlite3_session *pSession, /* Session object that owns SessionTable */
+ SessionTable *pTab, /* Table associated with change */
+ SessionChange *pChange, /* Change to compare to */
+ int op /* Current pre-update operation */
+){
+ int iCol; /* Used to iterate through columns */
+ u8 *a = pChange->aRecord; /* Cursor used to scan change record */
+
+ assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
+ for(iCol=0; iCol<pTab->nCol; iCol++){
+ if( !pTab->abPK[iCol] ){
+ a += sessionSerialLen(a);
+ }else{
+ sqlite3_value *pVal; /* Value returned by preupdate_new/old */
+ int rc; /* Error code from preupdate_new/old */
+ int eType = *a++; /* Type of value from change record */
+
+ /* The following calls to preupdate_new() and preupdate_old() can not
+ ** fail. This is because they cache their return values, and by the
+ ** time control flows to here they have already been called once from
+ ** within sessionPreupdateHash(). The first two asserts below verify
+ ** this (that the method has already been called). */
+ if( op==SQLITE_INSERT ){
+ /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
+ rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
+ }else{
+ /* assert( db->pPreUpdate->pUnpacked ); */
+ rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
+ }
+ assert( rc==SQLITE_OK );
+ if( sqlite3_value_type(pVal)!=eType ) return 0;
+
+ /* A SessionChange object never has a NULL value in a PK column */
+ assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
+ || eType==SQLITE_BLOB || eType==SQLITE_TEXT
+ );
+
+ if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
+ i64 iVal = sessionGetI64(a);
+ a += 8;
+ if( eType==SQLITE_INTEGER ){
+ if( sqlite3_value_int64(pVal)!=iVal ) return 0;
+ }else{
+ double rVal;
+ assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
+ memcpy(&rVal, &iVal, 8);
+ if( sqlite3_value_double(pVal)!=rVal ) return 0;
+ }
+ }else{
+ int n;
+ const u8 *z;
+ a += sessionVarintGet(a, &n);
+ if( sqlite3_value_bytes(pVal)!=n ) return 0;
+ if( eType==SQLITE_TEXT ){
+ z = sqlite3_value_text(pVal);
+ }else{
+ z = sqlite3_value_blob(pVal);
+ }
+ if( n>0 && memcmp(a, z, n) ) return 0;
+ a += n;
+ }
+ }
+ }
+
+ return 1;
+}
+
+/*
+** If required, grow the hash table used to store changes on table pTab
+** (part of the session pSession). If a fatal OOM error occurs, set the
+** session object to failed and return SQLITE_ERROR. Otherwise, return
+** SQLITE_OK.
+**
+** It is possible that a non-fatal OOM error occurs in this function. In
+** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
+** Growing the hash table in this case is a performance optimization only,
+** it is not required for correct operation.
+*/
+static int sessionGrowHash(int bPatchset, SessionTable *pTab){
+ if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
+ int i;
+ SessionChange **apNew;
+ sqlite3_int64 nNew = 2*(sqlite3_int64)(pTab->nChange ? pTab->nChange : 128);
+
+ apNew = (SessionChange **)sqlite3_malloc64(sizeof(SessionChange *) * nNew);
+ if( apNew==0 ){
+ if( pTab->nChange==0 ){
+ return SQLITE_ERROR;
+ }
+ return SQLITE_OK;
+ }
+ memset(apNew, 0, sizeof(SessionChange *) * nNew);
+
+ for(i=0; i<pTab->nChange; i++){
+ SessionChange *p;
+ SessionChange *pNext;
+ for(p=pTab->apChange[i]; p; p=pNext){
+ int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
+ int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
+ pNext = p->pNext;
+ p->pNext = apNew[iHash];
+ apNew[iHash] = p;
+ }
+ }
+
+ sqlite3_free(pTab->apChange);
+ pTab->nChange = nNew;
+ pTab->apChange = apNew;
+ }
+
+ return SQLITE_OK;
+}
+
+/*
+** This function queries the database for the names of the columns of table
+** zThis, in schema zDb.
+**
+** Otherwise, if they are not NULL, variable *pnCol is set to the number
+** of columns in the database table and variable *pzTab is set to point to a
+** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
+** point to an array of pointers to column names. And *pabPK (again, if not
+** NULL) is set to point to an array of booleans - true if the corresponding
+** column is part of the primary key.
+**
+** For example, if the table is declared as:
+**
+** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
+**
+** Then the four output variables are populated as follows:
+**
+** *pnCol = 4
+** *pzTab = "tbl1"
+** *pazCol = {"w", "x", "y", "z"}
+** *pabPK = {1, 0, 0, 1}
+**
+** All returned buffers are part of the same single allocation, which must
+** be freed using sqlite3_free() by the caller
+*/
+static int sessionTableInfo(
+ sqlite3 *db, /* Database connection */
+ const char *zDb, /* Name of attached database (e.g. "main") */
+ const char *zThis, /* Table name */
+ int *pnCol, /* OUT: number of columns */
+ const char **pzTab, /* OUT: Copy of zThis */
+ const char ***pazCol, /* OUT: Array of column names for table */
+ u8 **pabPK /* OUT: Array of booleans - true for PK col */
+){
+ char *zPragma;
+ sqlite3_stmt *pStmt;
+ int rc;
+ sqlite3_int64 nByte;
+ int nDbCol = 0;
+ int nThis;
+ int i;
+ u8 *pAlloc = 0;
+ char **azCol = 0;
+ u8 *abPK = 0;
+
+ assert( pazCol && pabPK );
+
+ nThis = sqlite3Strlen30(zThis);
+ if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
+ rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
+ if( rc==SQLITE_OK ){
+ /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */
+ zPragma = sqlite3_mprintf(
+ "SELECT 0, 'tbl', '', 0, '', 1 UNION ALL "
+ "SELECT 1, 'idx', '', 0, '', 2 UNION ALL "
+ "SELECT 2, 'stat', '', 0, '', 0"
+ );
+ }else if( rc==SQLITE_ERROR ){
+ zPragma = sqlite3_mprintf("");
+ }else{
+ return rc;
+ }
+ }else{
+ zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
+ }
+ if( !zPragma ) return SQLITE_NOMEM;
+
+ rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
+ sqlite3_free(zPragma);
+ if( rc!=SQLITE_OK ) return rc;
+
+ nByte = nThis + 1;
+ while( SQLITE_ROW==sqlite3_step(pStmt) ){
+ nByte += sqlite3_column_bytes(pStmt, 1);
+ nDbCol++;
+ }
+ rc = sqlite3_reset(pStmt);
+
+ if( rc==SQLITE_OK ){
+ nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
+ pAlloc = sqlite3_malloc64(nByte);
+ if( pAlloc==0 ){
+ rc = SQLITE_NOMEM;
+ }
+ }
+ if( rc==SQLITE_OK ){
+ azCol = (char **)pAlloc;
+ pAlloc = (u8 *)&azCol[nDbCol];
+ abPK = (u8 *)pAlloc;
+ pAlloc = &abPK[nDbCol];
+ if( pzTab ){
+ memcpy(pAlloc, zThis, nThis+1);
+ *pzTab = (char *)pAlloc;
+ pAlloc += nThis+1;
+ }
+
+ i = 0;
+ while( SQLITE_ROW==sqlite3_step(pStmt) ){
+ int nName = sqlite3_column_bytes(pStmt, 1);
+ const unsigned char *zName = sqlite3_column_text(pStmt, 1);
+ if( zName==0 ) break;
+ memcpy(pAlloc, zName, nName+1);
+ azCol[i] = (char *)pAlloc;
+ pAlloc += nName+1;
+ abPK[i] = sqlite3_column_int(pStmt, 5);
+ i++;
+ }
+ rc = sqlite3_reset(pStmt);
+
+ }
+
+ /* If successful, populate the output variables. Otherwise, zero them and
+ ** free any allocation made. An error code will be returned in this case.
+ */
+ if( rc==SQLITE_OK ){
+ *pazCol = (const char **)azCol;
+ *pabPK = abPK;
+ *pnCol = nDbCol;
+ }else{
+ *pazCol = 0;
+ *pabPK = 0;
+ *pnCol = 0;
+ if( pzTab ) *pzTab = 0;
+ sqlite3_free(azCol);
+ }
+ sqlite3_finalize(pStmt);
+ return rc;
+}
+
+/*
+** This function is only called from within a pre-update handler for a
+** write to table pTab, part of session pSession. If this is the first
+** write to this table, initalize the SessionTable.nCol, azCol[] and
+** abPK[] arrays accordingly.
+**
+** If an error occurs, an error code is stored in sqlite3_session.rc and
+** non-zero returned. Or, if no error occurs but the table has no primary
+** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
+** indicate that updates on this table should be ignored. SessionTable.abPK
+** is set to NULL in this case.
+*/
+static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
+ if( pTab->nCol==0 ){
+ u8 *abPK;
+ assert( pTab->azCol==0 || pTab->abPK==0 );
+ pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
+ pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
+ );
+ if( pSession->rc==SQLITE_OK ){
+ int i;
+ for(i=0; i<pTab->nCol; i++){
+ if( abPK[i] ){
+ pTab->abPK = abPK;
+ break;
+ }
+ }
+ if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){
+ pTab->bStat1 = 1;
+ }
+ }
+ }
+ return (pSession->rc || pTab->abPK==0);
+}
+
+/*
+** Versions of the four methods in object SessionHook for use with the
+** sqlite_stat1 table. The purpose of this is to substitute a zero-length
+** blob each time a NULL value is read from the "idx" column of the
+** sqlite_stat1 table.
+*/
+typedef struct SessionStat1Ctx SessionStat1Ctx;
+struct SessionStat1Ctx {
+ SessionHook hook;
+ sqlite3_session *pSession;
+};
+static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){
+ SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
+ sqlite3_value *pVal = 0;
+ int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal);
+ if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
+ pVal = p->pSession->pZeroBlob;
+ }
+ *ppVal = pVal;
+ return rc;
+}
+static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){
+ SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
+ sqlite3_value *pVal = 0;
+ int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal);
+ if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
+ pVal = p->pSession->pZeroBlob;
+ }
+ *ppVal = pVal;
+ return rc;
+}
+static int sessionStat1Count(void *pCtx){
+ SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
+ return p->hook.xCount(p->hook.pCtx);
+}
+static int sessionStat1Depth(void *pCtx){
+ SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
+ return p->hook.xDepth(p->hook.pCtx);
+}
+
+
+/*
+** This function is only called from with a pre-update-hook reporting a
+** change on table pTab (attached to session pSession). The type of change
+** (UPDATE, INSERT, DELETE) is specified by the first argument.
+**
+** Unless one is already present or an error occurs, an entry is added
+** to the changed-rows hash table associated with table pTab.
+*/
+static void sessionPreupdateOneChange(
+ int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
+ sqlite3_session *pSession, /* Session object pTab is attached to */
+ SessionTable *pTab /* Table that change applies to */
+){
+ int iHash;
+ int bNull = 0;
+ int rc = SQLITE_OK;
+ SessionStat1Ctx stat1 = {{0,0,0,0,0},0};
+
+ if( pSession->rc ) return;
+
+ /* Load table details if required */
+ if( sessionInitTable(pSession, pTab) ) return;
+
+ /* Check the number of columns in this xPreUpdate call matches the
+ ** number of columns in the table. */
+ if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
+ pSession->rc = SQLITE_SCHEMA;
+ return;
+ }
+
+ /* Grow the hash table if required */
+ if( sessionGrowHash(0, pTab) ){
+ pSession->rc = SQLITE_NOMEM;
+ return;
+ }
+
+ if( pTab->bStat1 ){
+ stat1.hook = pSession->hook;
+ stat1.pSession = pSession;
+ pSession->hook.pCtx = (void*)&stat1;
+ pSession->hook.xNew = sessionStat1New;
+ pSession->hook.xOld = sessionStat1Old;
+ pSession->hook.xCount = sessionStat1Count;
+ pSession->hook.xDepth = sessionStat1Depth;
+ if( pSession->pZeroBlob==0 ){
+ sqlite3_value *p = sqlite3ValueNew(0);
+ if( p==0 ){
+ rc = SQLITE_NOMEM;
+ goto error_out;
+ }
+ sqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC);
+ pSession->pZeroBlob = p;
+ }
+ }
+
+ /* Calculate the hash-key for this change. If the primary key of the row
+ ** includes a NULL value, exit early. Such changes are ignored by the
+ ** session module. */
+ rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
+ if( rc!=SQLITE_OK ) goto error_out;
+
+ if( bNull==0 ){
+ /* Search the hash table for an existing record for this row. */
+ SessionChange *pC;
+ for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
+ if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
+ }
+
+ if( pC==0 ){
+ /* Create a new change object containing all the old values (if
+ ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
+ ** values (if this is an INSERT). */
+ SessionChange *pChange; /* New change object */
+ sqlite3_int64 nByte; /* Number of bytes to allocate */
+ int i; /* Used to iterate through columns */
+
+ assert( rc==SQLITE_OK );
+ pTab->nEntry++;
+
+ /* Figure out how large an allocation is required */
+ nByte = sizeof(SessionChange);
+ for(i=0; i<pTab->nCol; i++){
+ sqlite3_value *p = 0;
+ if( op!=SQLITE_INSERT ){
+ TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
+ assert( trc==SQLITE_OK );
+ }else if( pTab->abPK[i] ){
+ TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
+ assert( trc==SQLITE_OK );
+ }
+
+ /* This may fail if SQLite value p contains a utf-16 string that must
+ ** be converted to utf-8 and an OOM error occurs while doing so. */
+ rc = sessionSerializeValue(0, p, &nByte);
+ if( rc!=SQLITE_OK ) goto error_out;
+ }
+
+ /* Allocate the change object */
+ pChange = (SessionChange *)sqlite3_malloc64(nByte);
+ if( !pChange ){
+ rc = SQLITE_NOMEM;
+ goto error_out;
+ }else{
+ memset(pChange, 0, sizeof(SessionChange));
+ pChange->aRecord = (u8 *)&pChange[1];
+ }
+
+ /* Populate the change object. None of the preupdate_old(),
+ ** preupdate_new() or SerializeValue() calls below may fail as all
+ ** required values and encodings have already been cached in memory.
+ ** It is not possible for an OOM to occur in this block. */
+ nByte = 0;
+ for(i=0; i<pTab->nCol; i++){
+ sqlite3_value *p = 0;
+ if( op!=SQLITE_INSERT ){
+ pSession->hook.xOld(pSession->hook.pCtx, i, &p);
+ }else if( pTab->abPK[i] ){
+ pSession->hook.xNew(pSession->hook.pCtx, i, &p);
+ }
+ sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
+ }
+
+ /* Add the change to the hash-table */
+ if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
+ pChange->bIndirect = 1;
+ }
+ pChange->nRecord = nByte;
+ pChange->op = op;
+ pChange->pNext = pTab->apChange[iHash];
+ pTab->apChange[iHash] = pChange;
+
+ }else if( pC->bIndirect ){
+ /* If the existing change is considered "indirect", but this current
+ ** change is "direct", mark the change object as direct. */
+ if( pSession->hook.xDepth(pSession->hook.pCtx)==0
+ && pSession->bIndirect==0
+ ){
+ pC->bIndirect = 0;
+ }
+ }
+ }
+
+ /* If an error has occurred, mark the session object as failed. */
+ error_out:
+ if( pTab->bStat1 ){
+ pSession->hook = stat1.hook;
+ }
+ if( rc!=SQLITE_OK ){
+ pSession->rc = rc;
+ }
+}
+
+static int sessionFindTable(
+ sqlite3_session *pSession,
+ const char *zName,
+ SessionTable **ppTab
+){
+ int rc = SQLITE_OK;
+ int nName = sqlite3Strlen30(zName);
+ SessionTable *pRet;
+
+ /* Search for an existing table */
+ for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
+ if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
+ }
+
+ if( pRet==0 && pSession->bAutoAttach ){
+ /* If there is a table-filter configured, invoke it. If it returns 0,
+ ** do not automatically add the new table. */
+ if( pSession->xTableFilter==0
+ || pSession->xTableFilter(pSession->pFilterCtx, zName)
+ ){
+ rc = sqlite3session_attach(pSession, zName);
+ if( rc==SQLITE_OK ){
+ for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
+ assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
+ }
+ }
+ }
+
+ assert( rc==SQLITE_OK || pRet==0 );
+ *ppTab = pRet;
+ return rc;
+}
+
+/*
+** The 'pre-update' hook registered by this module with SQLite databases.
+*/
+static void xPreUpdate(
+ void *pCtx, /* Copy of third arg to preupdate_hook() */
+ sqlite3 *db, /* Database handle */
+ int op, /* SQLITE_UPDATE, DELETE or INSERT */
+ char const *zDb, /* Database name */
+ char const *zName, /* Table name */
+ sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
+ sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
+){
+ sqlite3_session *pSession;
+ int nDb = sqlite3Strlen30(zDb);
+
+ assert( sqlite3_mutex_held(db->mutex) );
+
+ for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
+ SessionTable *pTab;
+
+ /* If this session is attached to a different database ("main", "temp"
+ ** etc.), or if it is not currently enabled, there is nothing to do. Skip
+ ** to the next session object attached to this database. */
+ if( pSession->bEnable==0 ) continue;
+ if( pSession->rc ) continue;
+ if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
+
+ pSession->rc = sessionFindTable(pSession, zName, &pTab);
+ if( pTab ){
+ assert( pSession->rc==SQLITE_OK );
+ sessionPreupdateOneChange(op, pSession, pTab);
+ if( op==SQLITE_UPDATE ){
+ sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
+ }
+ }
+ }
+}
+
+/*
+** The pre-update hook implementations.
+*/
+static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
+ return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
+}
+static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
+ return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
+}
+static int sessionPreupdateCount(void *pCtx){
+ return sqlite3_preupdate_count((sqlite3*)pCtx);
+}
+static int sessionPreupdateDepth(void *pCtx){
+ return sqlite3_preupdate_depth((sqlite3*)pCtx);
+}
+
+/*
+** Install the pre-update hooks on the session object passed as the only
+** argument.
+*/
+static void sessionPreupdateHooks(
+ sqlite3_session *pSession
+){
+ pSession->hook.pCtx = (void*)pSession->db;
+ pSession->hook.xOld = sessionPreupdateOld;
+ pSession->hook.xNew = sessionPreupdateNew;
+ pSession->hook.xCount = sessionPreupdateCount;
+ pSession->hook.xDepth = sessionPreupdateDepth;
+}
+
+typedef struct SessionDiffCtx SessionDiffCtx;
+struct SessionDiffCtx {
+ sqlite3_stmt *pStmt;
+ int nOldOff;
+};
+
+/*
+** The diff hook implementations.
+*/
+static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
+ SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
+ *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
+ return SQLITE_OK;
+}
+static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
+ SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
+ *ppVal = sqlite3_column_value(p->pStmt, iVal);
+ return SQLITE_OK;
+}
+static int sessionDiffCount(void *pCtx){
+ SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
+ return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
+}
+static int sessionDiffDepth(void *pCtx){
+ return 0;
+}
+
+/*
+** Install the diff hooks on the session object passed as the only
+** argument.
+*/
+static void sessionDiffHooks(
+ sqlite3_session *pSession,
+ SessionDiffCtx *pDiffCtx
+){
+ pSession->hook.pCtx = (void*)pDiffCtx;
+ pSession->hook.xOld = sessionDiffOld;
+ pSession->hook.xNew = sessionDiffNew;
+ pSession->hook.xCount = sessionDiffCount;
+ pSession->hook.xDepth = sessionDiffDepth;
+}
+
+static char *sessionExprComparePK(
+ int nCol,
+ const char *zDb1, const char *zDb2,
+ const char *zTab,
+ const char **azCol, u8 *abPK
+){
+ int i;
+ const char *zSep = "";
+ char *zRet = 0;
+
+ for(i=0; i<nCol; i++){
+ if( abPK[i] ){
+ zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
+ zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
+ );
+ zSep = " AND ";
+ if( zRet==0 ) break;
+ }
+ }
+
+ return zRet;
+}
+
+static char *sessionExprCompareOther(
+ int nCol,
+ const char *zDb1, const char *zDb2,
+ const char *zTab,
+ const char **azCol, u8 *abPK
+){
+ int i;
+ const char *zSep = "";
+ char *zRet = 0;
+ int bHave = 0;
+
+ for(i=0; i<nCol; i++){
+ if( abPK[i]==0 ){
+ bHave = 1;
+ zRet = sqlite3_mprintf(
+ "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
+ zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
+ );
+ zSep = " OR ";
+ if( zRet==0 ) break;
+ }
+ }
+
+ if( bHave==0 ){
+ assert( zRet==0 );
+ zRet = sqlite3_mprintf("0");
+ }
+
+ return zRet;
+}
+
+static char *sessionSelectFindNew(
+ int nCol,
+ const char *zDb1, /* Pick rows in this db only */
+ const char *zDb2, /* But not in this one */
+ const char *zTbl, /* Table name */
+ const char *zExpr
+){
+ char *zRet = sqlite3_mprintf(
+ "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
+ " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
+ ")",
+ zDb1, zTbl, zDb2, zTbl, zExpr
+ );
+ return zRet;
+}
+
+static int sessionDiffFindNew(
+ int op,
+ sqlite3_session *pSession,
+ SessionTable *pTab,
+ const char *zDb1,
+ const char *zDb2,
+ char *zExpr
+){
+ int rc = SQLITE_OK;
+ char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
+
+ if( zStmt==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ sqlite3_stmt *pStmt;
+ rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
+ if( rc==SQLITE_OK ){
+ SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
+ pDiffCtx->pStmt = pStmt;
+ pDiffCtx->nOldOff = 0;
+ while( SQLITE_ROW==sqlite3_step(pStmt) ){
+ sessionPreupdateOneChange(op, pSession, pTab);
+ }
+ rc = sqlite3_finalize(pStmt);
+ }
+ sqlite3_free(zStmt);
+ }
+
+ return rc;
+}
+
+static int sessionDiffFindModified(
+ sqlite3_session *pSession,
+ SessionTable *pTab,
+ const char *zFrom,
+ const char *zExpr
+){
+ int rc = SQLITE_OK;
+
+ char *zExpr2 = sessionExprCompareOther(pTab->nCol,
+ pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
+ );
+ if( zExpr2==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ char *zStmt = sqlite3_mprintf(
+ "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
+ pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
+ );
+ if( zStmt==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ sqlite3_stmt *pStmt;
+ rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
+
+ if( rc==SQLITE_OK ){
+ SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
+ pDiffCtx->pStmt = pStmt;
+ pDiffCtx->nOldOff = pTab->nCol;
+ while( SQLITE_ROW==sqlite3_step(pStmt) ){
+ sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
+ }
+ rc = sqlite3_finalize(pStmt);
+ }
+ sqlite3_free(zStmt);
+ }
+ }
+
+ return rc;
+}
+
+SQLITE_API int sqlite3session_diff(
+ sqlite3_session *pSession,
+ const char *zFrom,
+ const char *zTbl,
+ char **pzErrMsg
+){
+ const char *zDb = pSession->zDb;
+ int rc = pSession->rc;
+ SessionDiffCtx d;
+
+ memset(&d, 0, sizeof(d));
+ sessionDiffHooks(pSession, &d);
+
+ sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
+ if( pzErrMsg ) *pzErrMsg = 0;
+ if( rc==SQLITE_OK ){
+ char *zExpr = 0;
+ sqlite3 *db = pSession->db;
+ SessionTable *pTo; /* Table zTbl */
+
+ /* Locate and if necessary initialize the target table object */
+ rc = sessionFindTable(pSession, zTbl, &pTo);
+ if( pTo==0 ) goto diff_out;
+ if( sessionInitTable(pSession, pTo) ){
+ rc = pSession->rc;
+ goto diff_out;
+ }
+
+ /* Check the table schemas match */
+ if( rc==SQLITE_OK ){
+ int bHasPk = 0;
+ int bMismatch = 0;
+ int nCol; /* Columns in zFrom.zTbl */
+ u8 *abPK;
+ const char **azCol = 0;
+ rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
+ if( rc==SQLITE_OK ){
+ if( pTo->nCol!=nCol ){
+ bMismatch = 1;
+ }else{
+ int i;
+ for(i=0; i<nCol; i++){
+ if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
+ if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
+ if( abPK[i] ) bHasPk = 1;
+ }
+ }
+ }
+ sqlite3_free((char*)azCol);
+ if( bMismatch ){
+ if( pzErrMsg ){
+ *pzErrMsg = sqlite3_mprintf("table schemas do not match");
+ }
+ rc = SQLITE_SCHEMA;
+ }
+ if( bHasPk==0 ){
+ /* Ignore tables with no primary keys */
+ goto diff_out;
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ zExpr = sessionExprComparePK(pTo->nCol,
+ zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
+ );
+ }
+
+ /* Find new rows */
+ if( rc==SQLITE_OK ){
+ rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
+ }
+
+ /* Find old rows */
+ if( rc==SQLITE_OK ){
+ rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
+ }
+
+ /* Find modified rows */
+ if( rc==SQLITE_OK ){
+ rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
+ }
+
+ sqlite3_free(zExpr);
+ }
+
+ diff_out:
+ sessionPreupdateHooks(pSession);
+ sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
+ return rc;
+}
+
+/*
+** Create a session object. This session object will record changes to
+** database zDb attached to connection db.
+*/
+SQLITE_API int sqlite3session_create(
+ sqlite3 *db, /* Database handle */
+ const char *zDb, /* Name of db (e.g. "main") */
+ sqlite3_session **ppSession /* OUT: New session object */
+){
+ sqlite3_session *pNew; /* Newly allocated session object */
+ sqlite3_session *pOld; /* Session object already attached to db */
+ int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
+
+ /* Zero the output value in case an error occurs. */
+ *ppSession = 0;
+
+ /* Allocate and populate the new session object. */
+ pNew = (sqlite3_session *)sqlite3_malloc64(sizeof(sqlite3_session) + nDb + 1);
+ if( !pNew ) return SQLITE_NOMEM;
+ memset(pNew, 0, sizeof(sqlite3_session));
+ pNew->db = db;
+ pNew->zDb = (char *)&pNew[1];
+ pNew->bEnable = 1;
+ memcpy(pNew->zDb, zDb, nDb+1);
+ sessionPreupdateHooks(pNew);
+
+ /* Add the new session object to the linked list of session objects
+ ** attached to database handle $db. Do this under the cover of the db
+ ** handle mutex. */
+ sqlite3_mutex_enter(sqlite3_db_mutex(db));
+ pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
+ pNew->pNext = pOld;
+ sqlite3_mutex_leave(sqlite3_db_mutex(db));
+
+ *ppSession = pNew;
+ return SQLITE_OK;
+}
+
+/*
+** Free the list of table objects passed as the first argument. The contents
+** of the changed-rows hash tables are also deleted.
+*/
+static void sessionDeleteTable(SessionTable *pList){
+ SessionTable *pNext;
+ SessionTable *pTab;
+
+ for(pTab=pList; pTab; pTab=pNext){
+ int i;
+ pNext = pTab->pNext;
+ for(i=0; i<pTab->nChange; i++){
+ SessionChange *p;
+ SessionChange *pNextChange;
+ for(p=pTab->apChange[i]; p; p=pNextChange){
+ pNextChange = p->pNext;
+ sqlite3_free(p);
+ }
+ }
+ sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
+ sqlite3_free(pTab->apChange);
+ sqlite3_free(pTab);
+ }
+}
+
+/*
+** Delete a session object previously allocated using sqlite3session_create().
+*/
+SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
+ sqlite3 *db = pSession->db;
+ sqlite3_session *pHead;
+ sqlite3_session **pp;
+
+ /* Unlink the session from the linked list of sessions attached to the
+ ** database handle. Hold the db mutex while doing so. */
+ sqlite3_mutex_enter(sqlite3_db_mutex(db));
+ pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
+ for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
+ if( (*pp)==pSession ){
+ *pp = (*pp)->pNext;
+ if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
+ break;
+ }
+ }
+ sqlite3_mutex_leave(sqlite3_db_mutex(db));
+ sqlite3ValueFree(pSession->pZeroBlob);
+
+ /* Delete all attached table objects. And the contents of their
+ ** associated hash-tables. */
+ sessionDeleteTable(pSession->pTable);
+
+ /* Free the session object itself. */
+ sqlite3_free(pSession);
+}
+
+/*
+** Set a table filter on a Session Object.
+*/
+SQLITE_API void sqlite3session_table_filter(
+ sqlite3_session *pSession,
+ int(*xFilter)(void*, const char*),
+ void *pCtx /* First argument passed to xFilter */
+){
+ pSession->bAutoAttach = 1;
+ pSession->pFilterCtx = pCtx;
+ pSession->xTableFilter = xFilter;
+}
+
+/*
+** Attach a table to a session. All subsequent changes made to the table
+** while the session object is enabled will be recorded.
+**
+** Only tables that have a PRIMARY KEY defined may be attached. It does
+** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
+** or not.
+*/
+SQLITE_API int sqlite3session_attach(
+ sqlite3_session *pSession, /* Session object */
+ const char *zName /* Table name */
+){
+ int rc = SQLITE_OK;
+ sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
+
+ if( !zName ){
+ pSession->bAutoAttach = 1;
+ }else{
+ SessionTable *pTab; /* New table object (if required) */
+ int nName; /* Number of bytes in string zName */
+
+ /* First search for an existing entry. If one is found, this call is
+ ** a no-op. Return early. */
+ nName = sqlite3Strlen30(zName);
+ for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
+ if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
+ }
+
+ if( !pTab ){
+ /* Allocate new SessionTable object. */
+ pTab = (SessionTable *)sqlite3_malloc64(sizeof(SessionTable) + nName + 1);
+ if( !pTab ){
+ rc = SQLITE_NOMEM;
+ }else{
+ /* Populate the new SessionTable object and link it into the list.
+ ** The new object must be linked onto the end of the list, not
+ ** simply added to the start of it in order to ensure that tables
+ ** appear in the correct order when a changeset or patchset is
+ ** eventually generated. */
+ SessionTable **ppTab;
+ memset(pTab, 0, sizeof(SessionTable));
+ pTab->zName = (char *)&pTab[1];
+ memcpy(pTab->zName, zName, nName+1);
+ for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
+ *ppTab = pTab;
+ }
+ }
+ }
+
+ sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
+ return rc;
+}
+
+/*
+** Ensure that there is room in the buffer to append nByte bytes of data.
+** If not, use sqlite3_realloc() to grow the buffer so that there is.
+**
+** If successful, return zero. Otherwise, if an OOM condition is encountered,
+** set *pRc to SQLITE_NOMEM and return non-zero.
+*/
+static int sessionBufferGrow(SessionBuffer *p, size_t nByte, int *pRc){
+ if( *pRc==SQLITE_OK && (size_t)(p->nAlloc-p->nBuf)<nByte ){
+ u8 *aNew;
+ i64 nNew = p->nAlloc ? p->nAlloc : 128;
+ do {
+ nNew = nNew*2;
+ }while( (size_t)(nNew-p->nBuf)<nByte );
+
+ aNew = (u8 *)sqlite3_realloc64(p->aBuf, nNew);
+ if( 0==aNew ){
+ *pRc = SQLITE_NOMEM;
+ }else{
+ p->aBuf = aNew;
+ p->nAlloc = nNew;
+ }
+ }
+ return (*pRc!=SQLITE_OK);
+}
+
+/*
+** Append the value passed as the second argument to the buffer passed
+** as the first.
+**
+** This function is a no-op if *pRc is non-zero when it is called.
+** Otherwise, if an error occurs, *pRc is set to an SQLite error code
+** before returning.
+*/
+static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
+ int rc = *pRc;
+ if( rc==SQLITE_OK ){
+ sqlite3_int64 nByte = 0;
+ rc = sessionSerializeValue(0, pVal, &nByte);
+ sessionBufferGrow(p, nByte, &rc);
+ if( rc==SQLITE_OK ){
+ rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
+ p->nBuf += nByte;
+ }else{
+ *pRc = rc;
+ }
+ }
+}
+
+/*
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
+** called. Otherwise, append a single byte to the buffer.
+**
+** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
+** returning.
+*/
+static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
+ if( 0==sessionBufferGrow(p, 1, pRc) ){
+ p->aBuf[p->nBuf++] = v;
+ }
+}
+
+/*
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
+** called. Otherwise, append a single varint to the buffer.
+**
+** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
+** returning.
+*/
+static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
+ if( 0==sessionBufferGrow(p, 9, pRc) ){
+ p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
+ }
+}
+
+/*
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
+** called. Otherwise, append a blob of data to the buffer.
+**
+** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
+** returning.
+*/
+static void sessionAppendBlob(
+ SessionBuffer *p,
+ const u8 *aBlob,
+ int nBlob,
+ int *pRc
+){
+ if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
+ memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
+ p->nBuf += nBlob;
+ }
+}
+
+/*
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
+** called. Otherwise, append a string to the buffer. All bytes in the string
+** up to (but not including) the nul-terminator are written to the buffer.
+**
+** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
+** returning.
+*/
+static void sessionAppendStr(
+ SessionBuffer *p,
+ const char *zStr,
+ int *pRc
+){
+ int nStr = sqlite3Strlen30(zStr);
+ if( 0==sessionBufferGrow(p, nStr, pRc) ){
+ memcpy(&p->aBuf[p->nBuf], zStr, nStr);
+ p->nBuf += nStr;
+ }
+}
+
+/*
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
+** called. Otherwise, append the string representation of integer iVal
+** to the buffer. No nul-terminator is written.
+**
+** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
+** returning.
+*/
+static void sessionAppendInteger(
+ SessionBuffer *p, /* Buffer to append to */
+ int iVal, /* Value to write the string rep. of */
+ int *pRc /* IN/OUT: Error code */
+){
+ char aBuf[24];
+ sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
+ sessionAppendStr(p, aBuf, pRc);
+}
+
+/*
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
+** called. Otherwise, append the string zStr enclosed in quotes (") and
+** with any embedded quote characters escaped to the buffer. No
+** nul-terminator byte is written.
+**
+** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
+** returning.
+*/
+static void sessionAppendIdent(
+ SessionBuffer *p, /* Buffer to a append to */
+ const char *zStr, /* String to quote, escape and append */
+ int *pRc /* IN/OUT: Error code */
+){
+ int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
+ if( 0==sessionBufferGrow(p, nStr, pRc) ){
+ char *zOut = (char *)&p->aBuf[p->nBuf];
+ const char *zIn = zStr;
+ *zOut++ = '"';
+ while( *zIn ){
+ if( *zIn=='"' ) *zOut++ = '"';
+ *zOut++ = *(zIn++);
+ }
+ *zOut++ = '"';
+ p->nBuf = (int)((u8 *)zOut - p->aBuf);
+ }
+}
+
+/*
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
+** called. Otherwse, it appends the serialized version of the value stored
+** in column iCol of the row that SQL statement pStmt currently points
+** to to the buffer.
+*/
+static void sessionAppendCol(
+ SessionBuffer *p, /* Buffer to append to */
+ sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
+ int iCol, /* Column to read value from */
+ int *pRc /* IN/OUT: Error code */
+){
+ if( *pRc==SQLITE_OK ){
+ int eType = sqlite3_column_type(pStmt, iCol);
+ sessionAppendByte(p, (u8)eType, pRc);
+ if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
+ sqlite3_int64 i;
+ u8 aBuf[8];
+ if( eType==SQLITE_INTEGER ){
+ i = sqlite3_column_int64(pStmt, iCol);
+ }else{
+ double r = sqlite3_column_double(pStmt, iCol);
+ memcpy(&i, &r, 8);
+ }
+ sessionPutI64(aBuf, i);
+ sessionAppendBlob(p, aBuf, 8, pRc);
+ }
+ if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
+ u8 *z;
+ int nByte;
+ if( eType==SQLITE_BLOB ){
+ z = (u8 *)sqlite3_column_blob(pStmt, iCol);
+ }else{
+ z = (u8 *)sqlite3_column_text(pStmt, iCol);
+ }
+ nByte = sqlite3_column_bytes(pStmt, iCol);
+ if( z || (eType==SQLITE_BLOB && nByte==0) ){
+ sessionAppendVarint(p, nByte, pRc);
+ sessionAppendBlob(p, z, nByte, pRc);
+ }else{
+ *pRc = SQLITE_NOMEM;
+ }
+ }
+ }
+}
+
+/*
+**
+** This function appends an update change to the buffer (see the comments
+** under "CHANGESET FORMAT" at the top of the file). An update change
+** consists of:
+**
+** 1 byte: SQLITE_UPDATE (0x17)
+** n bytes: old.* record (see RECORD FORMAT)
+** m bytes: new.* record (see RECORD FORMAT)
+**
+** The SessionChange object passed as the third argument contains the
+** values that were stored in the row when the session began (the old.*
+** values). The statement handle passed as the second argument points
+** at the current version of the row (the new.* values).
+**
+** If all of the old.* values are equal to their corresponding new.* value
+** (i.e. nothing has changed), then no data at all is appended to the buffer.
+**
+** Otherwise, the old.* record contains all primary key values and the
+** original values of any fields that have been modified. The new.* record
+** contains the new values of only those fields that have been modified.
+*/
+static int sessionAppendUpdate(
+ SessionBuffer *pBuf, /* Buffer to append to */
+ int bPatchset, /* True for "patchset", 0 for "changeset" */
+ sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
+ SessionChange *p, /* Object containing old values */
+ u8 *abPK /* Boolean array - true for PK columns */
+){
+ int rc = SQLITE_OK;
+ SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
+ int bNoop = 1; /* Set to zero if any values are modified */
+ int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
+ int i; /* Used to iterate through columns */
+ u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
+
+ sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
+ sessionAppendByte(pBuf, p->bIndirect, &rc);
+ for(i=0; i<sqlite3_column_count(pStmt); i++){
+ int bChanged = 0;
+ int nAdvance;
+ int eType = *pCsr;
+ switch( eType ){
+ case SQLITE_NULL:
+ nAdvance = 1;
+ if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
+ bChanged = 1;
+ }
+ break;
+
+ case SQLITE_FLOAT:
+ case SQLITE_INTEGER: {
+ nAdvance = 9;
+ if( eType==sqlite3_column_type(pStmt, i) ){
+ sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
+ if( eType==SQLITE_INTEGER ){
+ if( iVal==sqlite3_column_int64(pStmt, i) ) break;
+ }else{
+ double dVal;
+ memcpy(&dVal, &iVal, 8);
+ if( dVal==sqlite3_column_double(pStmt, i) ) break;
+ }
+ }
+ bChanged = 1;
+ break;
+ }
+
+ default: {
+ int n;
+ int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
+ assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
+ nAdvance = nHdr + n;
+ if( eType==sqlite3_column_type(pStmt, i)
+ && n==sqlite3_column_bytes(pStmt, i)
+ && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
+ ){
+ break;
+ }
+ bChanged = 1;
+ }
+ }
+
+ /* If at least one field has been modified, this is not a no-op. */
+ if( bChanged ) bNoop = 0;
+
+ /* Add a field to the old.* record. This is omitted if this modules is
+ ** currently generating a patchset. */
+ if( bPatchset==0 ){
+ if( bChanged || abPK[i] ){
+ sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
+ }else{
+ sessionAppendByte(pBuf, 0, &rc);
+ }
+ }
+
+ /* Add a field to the new.* record. Or the only record if currently
+ ** generating a patchset. */
+ if( bChanged || (bPatchset && abPK[i]) ){
+ sessionAppendCol(&buf2, pStmt, i, &rc);
+ }else{
+ sessionAppendByte(&buf2, 0, &rc);
+ }
+
+ pCsr += nAdvance;
+ }
+
+ if( bNoop ){
+ pBuf->nBuf = nRewind;
+ }else{
+ sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
+ }
+ sqlite3_free(buf2.aBuf);
+
+ return rc;
+}
+
+/*
+** Append a DELETE change to the buffer passed as the first argument. Use
+** the changeset format if argument bPatchset is zero, or the patchset
+** format otherwise.
+*/
+static int sessionAppendDelete(
+ SessionBuffer *pBuf, /* Buffer to append to */
+ int bPatchset, /* True for "patchset", 0 for "changeset" */
+ SessionChange *p, /* Object containing old values */
+ int nCol, /* Number of columns in table */
+ u8 *abPK /* Boolean array - true for PK columns */
+){
+ int rc = SQLITE_OK;
+
+ sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
+ sessionAppendByte(pBuf, p->bIndirect, &rc);
+
+ if( bPatchset==0 ){
+ sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
+ }else{
+ int i;
+ u8 *a = p->aRecord;
+ for(i=0; i<nCol; i++){
+ u8 *pStart = a;
+ int eType = *a++;
+
+ switch( eType ){
+ case 0:
+ case SQLITE_NULL:
+ assert( abPK[i]==0 );
+ break;
+
+ case SQLITE_FLOAT:
+ case SQLITE_INTEGER:
+ a += 8;
+ break;
+
+ default: {
+ int n;
+ a += sessionVarintGet(a, &n);
+ a += n;
+ break;
+ }
+ }
+ if( abPK[i] ){
+ sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
+ }
+ }
+ assert( (a - p->aRecord)==p->nRecord );
+ }
+
+ return rc;
+}
+
+/*
+** Formulate and prepare a SELECT statement to retrieve a row from table
+** zTab in database zDb based on its primary key. i.e.
+**
+** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
+*/
+static int sessionSelectStmt(
+ sqlite3 *db, /* Database handle */
+ const char *zDb, /* Database name */
+ const char *zTab, /* Table name */
+ int nCol, /* Number of columns in table */
+ const char **azCol, /* Names of table columns */
+ u8 *abPK, /* PRIMARY KEY array */
+ sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
+){
+ int rc = SQLITE_OK;
+ char *zSql = 0;
+ int nSql = -1;
+
+ if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
+ zSql = sqlite3_mprintf(
+ "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
+ "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
+ );
+ if( zSql==0 ) rc = SQLITE_NOMEM;
+ }else{
+ int i;
+ const char *zSep = "";
+ SessionBuffer buf = {0, 0, 0};
+
+ sessionAppendStr(&buf, "SELECT * FROM ", &rc);
+ sessionAppendIdent(&buf, zDb, &rc);
+ sessionAppendStr(&buf, ".", &rc);
+ sessionAppendIdent(&buf, zTab, &rc);
+ sessionAppendStr(&buf, " WHERE ", &rc);
+ for(i=0; i<nCol; i++){
+ if( abPK[i] ){
+ sessionAppendStr(&buf, zSep, &rc);
+ sessionAppendIdent(&buf, azCol[i], &rc);
+ sessionAppendStr(&buf, " IS ?", &rc);
+ sessionAppendInteger(&buf, i+1, &rc);
+ zSep = " AND ";
+ }
+ }
+ zSql = (char*)buf.aBuf;
+ nSql = buf.nBuf;
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
+ }
+ sqlite3_free(zSql);
+ return rc;
+}
+
+/*
+** Bind the PRIMARY KEY values from the change passed in argument pChange
+** to the SELECT statement passed as the first argument. The SELECT statement
+** is as prepared by function sessionSelectStmt().
+**
+** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
+** error code (e.g. SQLITE_NOMEM) otherwise.
+*/
+static int sessionSelectBind(
+ sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
+ int nCol, /* Number of columns in table */
+ u8 *abPK, /* PRIMARY KEY array */
+ SessionChange *pChange /* Change structure */
+){
+ int i;
+ int rc = SQLITE_OK;
+ u8 *a = pChange->aRecord;
+
+ for(i=0; i<nCol && rc==SQLITE_OK; i++){
+ int eType = *a++;
+
+ switch( eType ){
+ case 0:
+ case SQLITE_NULL:
+ assert( abPK[i]==0 );
+ break;
+
+ case SQLITE_INTEGER: {
+ if( abPK[i] ){
+ i64 iVal = sessionGetI64(a);
+ rc = sqlite3_bind_int64(pSelect, i+1, iVal);
+ }
+ a += 8;
+ break;
+ }
+
+ case SQLITE_FLOAT: {
+ if( abPK[i] ){
+ double rVal;
+ i64 iVal = sessionGetI64(a);
+ memcpy(&rVal, &iVal, 8);
+ rc = sqlite3_bind_double(pSelect, i+1, rVal);
+ }
+ a += 8;
+ break;
+ }
+
+ case SQLITE_TEXT: {
+ int n;
+ a += sessionVarintGet(a, &n);
+ if( abPK[i] ){
+ rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
+ }
+ a += n;
+ break;
+ }
+
+ default: {
+ int n;
+ assert( eType==SQLITE_BLOB );
+ a += sessionVarintGet(a, &n);
+ if( abPK[i] ){
+ rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
+ }
+ a += n;
+ break;
+ }
+ }
+ }
+
+ return rc;
+}
+
+/*
+** This function is a no-op if *pRc is set to other than SQLITE_OK when it
+** is called. Otherwise, append a serialized table header (part of the binary
+** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
+** SQLite error code before returning.
+*/
+static void sessionAppendTableHdr(
+ SessionBuffer *pBuf, /* Append header to this buffer */
+ int bPatchset, /* Use the patchset format if true */
+ SessionTable *pTab, /* Table object to append header for */
+ int *pRc /* IN/OUT: Error code */
+){
+ /* Write a table header */
+ sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
+ sessionAppendVarint(pBuf, pTab->nCol, pRc);
+ sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
+ sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
+}
+
+/*
+** Generate either a changeset (if argument bPatchset is zero) or a patchset
+** (if it is non-zero) based on the current contents of the session object
+** passed as the first argument.
+**
+** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
+** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
+** occurs, an SQLite error code is returned and both output variables set
+** to 0.
+*/
+static int sessionGenerateChangeset(
+ sqlite3_session *pSession, /* Session object */
+ int bPatchset, /* True for patchset, false for changeset */
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut, /* First argument for xOutput */
+ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
+ void **ppChangeset /* OUT: Buffer containing changeset */
+){
+ sqlite3 *db = pSession->db; /* Source database handle */
+ SessionTable *pTab; /* Used to iterate through attached tables */
+ SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
+ int rc; /* Return code */
+
+ assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
+
+ /* Zero the output variables in case an error occurs. If this session
+ ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
+ ** this call will be a no-op. */
+ if( xOutput==0 ){
+ *pnChangeset = 0;
+ *ppChangeset = 0;
+ }
+
+ if( pSession->rc ) return pSession->rc;
+ rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
+ if( rc!=SQLITE_OK ) return rc;
+
+ sqlite3_mutex_enter(sqlite3_db_mutex(db));
+
+ for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
+ if( pTab->nEntry ){
+ const char *zName = pTab->zName;
+ int nCol; /* Number of columns in table */
+ u8 *abPK; /* Primary key array */
+ const char **azCol = 0; /* Table columns */
+ int i; /* Used to iterate through hash buckets */
+ sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
+ int nRewind = buf.nBuf; /* Initial size of write buffer */
+ int nNoop; /* Size of buffer after writing tbl header */
+
+ /* Check the table schema is still Ok. */
+ rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
+ if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
+ rc = SQLITE_SCHEMA;
+ }
+
+ /* Write a table header */
+ sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
+
+ /* Build and compile a statement to execute: */
+ if( rc==SQLITE_OK ){
+ rc = sessionSelectStmt(
+ db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
+ }
+
+ nNoop = buf.nBuf;
+ for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
+ SessionChange *p; /* Used to iterate through changes */
+
+ for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
+ rc = sessionSelectBind(pSel, nCol, abPK, p);
+ if( rc!=SQLITE_OK ) continue;
+ if( sqlite3_step(pSel)==SQLITE_ROW ){
+ if( p->op==SQLITE_INSERT ){
+ int iCol;
+ sessionAppendByte(&buf, SQLITE_INSERT, &rc);
+ sessionAppendByte(&buf, p->bIndirect, &rc);
+ for(iCol=0; iCol<nCol; iCol++){
+ sessionAppendCol(&buf, pSel, iCol, &rc);
+ }
+ }else{
+ rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
+ }
+ }else if( p->op!=SQLITE_INSERT ){
+ rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_reset(pSel);
+ }
+
+ /* If the buffer is now larger than sessions_strm_chunk_size, pass
+ ** its contents to the xOutput() callback. */
+ if( xOutput
+ && rc==SQLITE_OK
+ && buf.nBuf>nNoop
+ && buf.nBuf>sessions_strm_chunk_size
+ ){
+ rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
+ nNoop = -1;
+ buf.nBuf = 0;
+ }
+
+ }
+ }
+
+ sqlite3_finalize(pSel);
+ if( buf.nBuf==nNoop ){
+ buf.nBuf = nRewind;
+ }
+ sqlite3_free((char*)azCol); /* cast works around VC++ bug */
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ if( xOutput==0 ){
+ *pnChangeset = buf.nBuf;
+ *ppChangeset = buf.aBuf;
+ buf.aBuf = 0;
+ }else if( buf.nBuf>0 ){
+ rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
+ }
+ }
+
+ sqlite3_free(buf.aBuf);
+ sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
+ sqlite3_mutex_leave(sqlite3_db_mutex(db));
+ return rc;
+}
+
+/*
+** Obtain a changeset object containing all changes recorded by the
+** session object passed as the first argument.
+**
+** It is the responsibility of the caller to eventually free the buffer
+** using sqlite3_free().
+*/
+SQLITE_API int sqlite3session_changeset(
+ sqlite3_session *pSession, /* Session object */
+ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
+ void **ppChangeset /* OUT: Buffer containing changeset */
+){
+ return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
+}
+
+/*
+** Streaming version of sqlite3session_changeset().
+*/
+SQLITE_API int sqlite3session_changeset_strm(
+ sqlite3_session *pSession,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+){
+ return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
+}
+
+/*
+** Streaming version of sqlite3session_patchset().
+*/
+SQLITE_API int sqlite3session_patchset_strm(
+ sqlite3_session *pSession,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+){
+ return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
+}
+
+/*
+** Obtain a patchset object containing all changes recorded by the
+** session object passed as the first argument.
+**
+** It is the responsibility of the caller to eventually free the buffer
+** using sqlite3_free().
+*/
+SQLITE_API int sqlite3session_patchset(
+ sqlite3_session *pSession, /* Session object */
+ int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
+ void **ppPatchset /* OUT: Buffer containing changeset */
+){
+ return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
+}
+
+/*
+** Enable or disable the session object passed as the first argument.
+*/
+SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
+ int ret;
+ sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
+ if( bEnable>=0 ){
+ pSession->bEnable = bEnable;
+ }
+ ret = pSession->bEnable;
+ sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
+ return ret;
+}
+
+/*
+** Enable or disable the session object passed as the first argument.
+*/
+SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
+ int ret;
+ sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
+ if( bIndirect>=0 ){
+ pSession->bIndirect = bIndirect;
+ }
+ ret = pSession->bIndirect;
+ sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
+ return ret;
+}
+
+/*
+** Return true if there have been no changes to monitored tables recorded
+** by the session object passed as the only argument.
+*/
+SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
+ int ret = 0;
+ SessionTable *pTab;
+
+ sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
+ for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
+ ret = (pTab->nEntry>0);
+ }
+ sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
+
+ return (ret==0);
+}
+
+/*
+** Do the work for either sqlite3changeset_start() or start_strm().
+*/
+static int sessionChangesetStart(
+ sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn,
+ int nChangeset, /* Size of buffer pChangeset in bytes */
+ void *pChangeset, /* Pointer to buffer containing changeset */
+ int bInvert /* True to invert changeset */
+){
+ sqlite3_changeset_iter *pRet; /* Iterator to return */
+ int nByte; /* Number of bytes to allocate for iterator */
+
+ assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
+
+ /* Zero the output variable in case an error occurs. */
+ *pp = 0;
+
+ /* Allocate and initialize the iterator structure. */
+ nByte = sizeof(sqlite3_changeset_iter);
+ pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
+ if( !pRet ) return SQLITE_NOMEM;
+ memset(pRet, 0, sizeof(sqlite3_changeset_iter));
+ pRet->in.aData = (u8 *)pChangeset;
+ pRet->in.nData = nChangeset;
+ pRet->in.xInput = xInput;
+ pRet->in.pIn = pIn;
+ pRet->in.bEof = (xInput ? 0 : 1);
+ pRet->bInvert = bInvert;
+
+ /* Populate the output variable and return success. */
+ *pp = pRet;
+ return SQLITE_OK;
+}
+
+/*
+** Create an iterator used to iterate through the contents of a changeset.
+*/
+SQLITE_API int sqlite3changeset_start(
+ sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
+ int nChangeset, /* Size of buffer pChangeset in bytes */
+ void *pChangeset /* Pointer to buffer containing changeset */
+){
+ return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, 0);
+}
+SQLITE_API int sqlite3changeset_start_v2(
+ sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
+ int nChangeset, /* Size of buffer pChangeset in bytes */
+ void *pChangeset, /* Pointer to buffer containing changeset */
+ int flags
+){
+ int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
+ return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, bInvert);
+}
+
+/*
+** Streaming version of sqlite3changeset_start().
+*/
+SQLITE_API int sqlite3changeset_start_strm(
+ sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn
+){
+ return sessionChangesetStart(pp, xInput, pIn, 0, 0, 0);
+}
+SQLITE_API int sqlite3changeset_start_v2_strm(
+ sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn,
+ int flags
+){
+ int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
+ return sessionChangesetStart(pp, xInput, pIn, 0, 0, bInvert);
+}
+
+/*
+** If the SessionInput object passed as the only argument is a streaming
+** object and the buffer is full, discard some data to free up space.
+*/
+static void sessionDiscardData(SessionInput *pIn){
+ if( pIn->xInput && pIn->iNext>=sessions_strm_chunk_size ){
+ int nMove = pIn->buf.nBuf - pIn->iNext;
+ assert( nMove>=0 );
+ if( nMove>0 ){
+ memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
+ }
+ pIn->buf.nBuf -= pIn->iNext;
+ pIn->iNext = 0;
+ pIn->nData = pIn->buf.nBuf;
+ }
+}
+
+/*
+** Ensure that there are at least nByte bytes available in the buffer. Or,
+** if there are not nByte bytes remaining in the input, that all available
+** data is in the buffer.
+**
+** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
+*/
+static int sessionInputBuffer(SessionInput *pIn, int nByte){
+ int rc = SQLITE_OK;
+ if( pIn->xInput ){
+ while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
+ int nNew = sessions_strm_chunk_size;
+
+ if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
+ if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
+ rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
+ if( nNew==0 ){
+ pIn->bEof = 1;
+ }else{
+ pIn->buf.nBuf += nNew;
+ }
+ }
+
+ pIn->aData = pIn->buf.aBuf;
+ pIn->nData = pIn->buf.nBuf;
+ }
+ }
+ return rc;
+}
+
+/*
+** When this function is called, *ppRec points to the start of a record
+** that contains nCol values. This function advances the pointer *ppRec
+** until it points to the byte immediately following that record.
+*/
+static void sessionSkipRecord(
+ u8 **ppRec, /* IN/OUT: Record pointer */
+ int nCol /* Number of values in record */
+){
+ u8 *aRec = *ppRec;
+ int i;
+ for(i=0; i<nCol; i++){
+ int eType = *aRec++;
+ if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
+ int nByte;
+ aRec += sessionVarintGet((u8*)aRec, &nByte);
+ aRec += nByte;
+ }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
+ aRec += 8;
+ }
+ }
+
+ *ppRec = aRec;
+}
+
+/*
+** This function sets the value of the sqlite3_value object passed as the
+** first argument to a copy of the string or blob held in the aData[]
+** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
+** error occurs.
+*/
+static int sessionValueSetStr(
+ sqlite3_value *pVal, /* Set the value of this object */
+ u8 *aData, /* Buffer containing string or blob data */
+ int nData, /* Size of buffer aData[] in bytes */
+ u8 enc /* String encoding (0 for blobs) */
+){
+ /* In theory this code could just pass SQLITE_TRANSIENT as the final
+ ** argument to sqlite3ValueSetStr() and have the copy created
+ ** automatically. But doing so makes it difficult to detect any OOM
+ ** error. Hence the code to create the copy externally. */
+ u8 *aCopy = sqlite3_malloc64((sqlite3_int64)nData+1);
+ if( aCopy==0 ) return SQLITE_NOMEM;
+ memcpy(aCopy, aData, nData);
+ sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
+ return SQLITE_OK;
+}
+
+/*
+** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
+** for details.
+**
+** When this function is called, *paChange points to the start of the record
+** to deserialize. Assuming no error occurs, *paChange is set to point to
+** one byte after the end of the same record before this function returns.
+** If the argument abPK is NULL, then the record contains nCol values. Or,
+** if abPK is other than NULL, then the record contains only the PK fields
+** (in other words, it is a patchset DELETE record).
+**
+** If successful, each element of the apOut[] array (allocated by the caller)
+** is set to point to an sqlite3_value object containing the value read
+** from the corresponding position in the record. If that value is not
+** included in the record (i.e. because the record is part of an UPDATE change
+** and the field was not modified), the corresponding element of apOut[] is
+** set to NULL.
+**
+** It is the responsibility of the caller to free all sqlite_value structures
+** using sqlite3_free().
+**
+** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
+** The apOut[] array may have been partially populated in this case.
+*/
+static int sessionReadRecord(
+ SessionInput *pIn, /* Input data */
+ int nCol, /* Number of values in record */
+ u8 *abPK, /* Array of primary key flags, or NULL */
+ sqlite3_value **apOut /* Write values to this array */
+){
+ int i; /* Used to iterate through columns */
+ int rc = SQLITE_OK;
+
+ for(i=0; i<nCol && rc==SQLITE_OK; i++){
+ int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
+ if( abPK && abPK[i]==0 ) continue;
+ rc = sessionInputBuffer(pIn, 9);
+ if( rc==SQLITE_OK ){
+ if( pIn->iNext>=pIn->nData ){
+ rc = SQLITE_CORRUPT_BKPT;
+ }else{
+ eType = pIn->aData[pIn->iNext++];
+ assert( apOut[i]==0 );
+ if( eType ){
+ apOut[i] = sqlite3ValueNew(0);
+ if( !apOut[i] ) rc = SQLITE_NOMEM;
+ }
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ u8 *aVal = &pIn->aData[pIn->iNext];
+ if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
+ int nByte;
+ pIn->iNext += sessionVarintGet(aVal, &nByte);
+ rc = sessionInputBuffer(pIn, nByte);
+ if( rc==SQLITE_OK ){
+ if( nByte<0 || nByte>pIn->nData-pIn->iNext ){
+ rc = SQLITE_CORRUPT_BKPT;
+ }else{
+ u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
+ rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
+ pIn->iNext += nByte;
+ }
+ }
+ }
+ if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
+ sqlite3_int64 v = sessionGetI64(aVal);
+ if( eType==SQLITE_INTEGER ){
+ sqlite3VdbeMemSetInt64(apOut[i], v);
+ }else{
+ double d;
+ memcpy(&d, &v, 8);
+ sqlite3VdbeMemSetDouble(apOut[i], d);
+ }
+ pIn->iNext += 8;
+ }
+ }
+ }
+
+ return rc;
+}
+
+/*
+** The input pointer currently points to the second byte of a table-header.
+** Specifically, to the following:
+**
+** + number of columns in table (varint)
+** + array of PK flags (1 byte per column),
+** + table name (nul terminated).
+**
+** This function ensures that all of the above is present in the input
+** buffer (i.e. that it can be accessed without any calls to xInput()).
+** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
+** The input pointer is not moved.
+*/
+static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
+ int rc = SQLITE_OK;
+ int nCol = 0;
+ int nRead = 0;
+
+ rc = sessionInputBuffer(pIn, 9);
+ if( rc==SQLITE_OK ){
+ nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
+ /* The hard upper limit for the number of columns in an SQLite
+ ** database table is, according to sqliteLimit.h, 32676. So
+ ** consider any table-header that purports to have more than 65536
+ ** columns to be corrupt. This is convenient because otherwise,
+ ** if the (nCol>65536) condition below were omitted, a sufficiently
+ ** large value for nCol may cause nRead to wrap around and become
+ ** negative. Leading to a crash. */
+ if( nCol<0 || nCol>65536 ){
+ rc = SQLITE_CORRUPT_BKPT;
+ }else{
+ rc = sessionInputBuffer(pIn, nRead+nCol+100);
+ nRead += nCol;
+ }
+ }
+
+ while( rc==SQLITE_OK ){
+ while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
+ nRead++;
+ }
+ if( (pIn->iNext + nRead)<pIn->nData ) break;
+ rc = sessionInputBuffer(pIn, nRead + 100);
+ }
+ *pnByte = nRead+1;
+ return rc;
+}
+
+/*
+** The input pointer currently points to the first byte of the first field
+** of a record consisting of nCol columns. This function ensures the entire
+** record is buffered. It does not move the input pointer.
+**
+** If successful, SQLITE_OK is returned and *pnByte is set to the size of
+** the record in bytes. Otherwise, an SQLite error code is returned. The
+** final value of *pnByte is undefined in this case.
+*/
+static int sessionChangesetBufferRecord(
+ SessionInput *pIn, /* Input data */
+ int nCol, /* Number of columns in record */
+ int *pnByte /* OUT: Size of record in bytes */
+){
+ int rc = SQLITE_OK;
+ int nByte = 0;
+ int i;
+ for(i=0; rc==SQLITE_OK && i<nCol; i++){
+ int eType;
+ rc = sessionInputBuffer(pIn, nByte + 10);
+ if( rc==SQLITE_OK ){
+ eType = pIn->aData[pIn->iNext + nByte++];
+ if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
+ int n;
+ nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
+ nByte += n;
+ rc = sessionInputBuffer(pIn, nByte);
+ }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
+ nByte += 8;
+ }
+ }
+ }
+ *pnByte = nByte;
+ return rc;
+}
+
+/*
+** The input pointer currently points to the second byte of a table-header.
+** Specifically, to the following:
+**
+** + number of columns in table (varint)
+** + array of PK flags (1 byte per column),
+** + table name (nul terminated).
+**
+** This function decodes the table-header and populates the p->nCol,
+** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
+** also allocated or resized according to the new value of p->nCol. The
+** input pointer is left pointing to the byte following the table header.
+**
+** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
+** is returned and the final values of the various fields enumerated above
+** are undefined.
+*/
+static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
+ int rc;
+ int nCopy;
+ assert( p->rc==SQLITE_OK );
+
+ rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
+ if( rc==SQLITE_OK ){
+ int nByte;
+ int nVarint;
+ nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
+ if( p->nCol>0 ){
+ nCopy -= nVarint;
+ p->in.iNext += nVarint;
+ nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
+ p->tblhdr.nBuf = 0;
+ sessionBufferGrow(&p->tblhdr, nByte, &rc);
+ }else{
+ rc = SQLITE_CORRUPT_BKPT;
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ size_t iPK = sizeof(sqlite3_value*)*p->nCol*2;
+ memset(p->tblhdr.aBuf, 0, iPK);
+ memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
+ p->in.iNext += nCopy;
+ }
+
+ p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
+ if( p->apValue==0 ){
+ p->abPK = 0;
+ p->zTab = 0;
+ }else{
+ p->abPK = (u8*)&p->apValue[p->nCol*2];
+ p->zTab = p->abPK ? (char*)&p->abPK[p->nCol] : 0;
+ }
+ return (p->rc = rc);
+}
+
+/*
+** Advance the changeset iterator to the next change.
+**
+** If both paRec and pnRec are NULL, then this function works like the public
+** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
+** sqlite3changeset_new() and old() APIs may be used to query for values.
+**
+** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
+** record is written to *paRec before returning and the number of bytes in
+** the record to *pnRec.
+**
+** Either way, this function returns SQLITE_ROW if the iterator is
+** successfully advanced to the next change in the changeset, an SQLite
+** error code if an error occurs, or SQLITE_DONE if there are no further
+** changes in the changeset.
+*/
+static int sessionChangesetNext(
+ sqlite3_changeset_iter *p, /* Changeset iterator */
+ u8 **paRec, /* If non-NULL, store record pointer here */
+ int *pnRec, /* If non-NULL, store size of record here */
+ int *pbNew /* If non-NULL, true if new table */
+){
+ int i;
+ u8 op;
+
+ assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
+
+ /* If the iterator is in the error-state, return immediately. */
+ if( p->rc!=SQLITE_OK ) return p->rc;
+
+ /* Free the current contents of p->apValue[], if any. */
+ if( p->apValue ){
+ for(i=0; i<p->nCol*2; i++){
+ sqlite3ValueFree(p->apValue[i]);
+ }
+ memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
+ }
+
+ /* Make sure the buffer contains at least 10 bytes of input data, or all
+ ** remaining data if there are less than 10 bytes available. This is
+ ** sufficient either for the 'T' or 'P' byte and the varint that follows
+ ** it, or for the two single byte values otherwise. */
+ p->rc = sessionInputBuffer(&p->in, 2);
+ if( p->rc!=SQLITE_OK ) return p->rc;
+
+ /* If the iterator is already at the end of the changeset, return DONE. */
+ if( p->in.iNext>=p->in.nData ){
+ return SQLITE_DONE;
+ }
+
+ sessionDiscardData(&p->in);
+ p->in.iCurrent = p->in.iNext;
+
+ op = p->in.aData[p->in.iNext++];
+ while( op=='T' || op=='P' ){
+ if( pbNew ) *pbNew = 1;
+ p->bPatchset = (op=='P');
+ if( sessionChangesetReadTblhdr(p) ) return p->rc;
+ if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
+ p->in.iCurrent = p->in.iNext;
+ if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
+ op = p->in.aData[p->in.iNext++];
+ }
+
+ if( p->zTab==0 || (p->bPatchset && p->bInvert) ){
+ /* The first record in the changeset is not a table header. Must be a
+ ** corrupt changeset. */
+ assert( p->in.iNext==1 || p->zTab );
+ return (p->rc = SQLITE_CORRUPT_BKPT);
+ }
+
+ p->op = op;
+ p->bIndirect = p->in.aData[p->in.iNext++];
+ if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
+ return (p->rc = SQLITE_CORRUPT_BKPT);
+ }
+
+ if( paRec ){
+ int nVal; /* Number of values to buffer */
+ if( p->bPatchset==0 && op==SQLITE_UPDATE ){
+ nVal = p->nCol * 2;
+ }else if( p->bPatchset && op==SQLITE_DELETE ){
+ nVal = 0;
+ for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
+ }else{
+ nVal = p->nCol;
+ }
+ p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
+ if( p->rc!=SQLITE_OK ) return p->rc;
+ *paRec = &p->in.aData[p->in.iNext];
+ p->in.iNext += *pnRec;
+ }else{
+ sqlite3_value **apOld = (p->bInvert ? &p->apValue[p->nCol] : p->apValue);
+ sqlite3_value **apNew = (p->bInvert ? p->apValue : &p->apValue[p->nCol]);
+
+ /* If this is an UPDATE or DELETE, read the old.* record. */
+ if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
+ u8 *abPK = p->bPatchset ? p->abPK : 0;
+ p->rc = sessionReadRecord(&p->in, p->nCol, abPK, apOld);
+ if( p->rc!=SQLITE_OK ) return p->rc;
+ }
+
+ /* If this is an INSERT or UPDATE, read the new.* record. */
+ if( p->op!=SQLITE_DELETE ){
+ p->rc = sessionReadRecord(&p->in, p->nCol, 0, apNew);
+ if( p->rc!=SQLITE_OK ) return p->rc;
+ }
+
+ if( (p->bPatchset || p->bInvert) && p->op==SQLITE_UPDATE ){
+ /* If this is an UPDATE that is part of a patchset, then all PK and
+ ** modified fields are present in the new.* record. The old.* record
+ ** is currently completely empty. This block shifts the PK fields from
+ ** new.* to old.*, to accommodate the code that reads these arrays. */
+ for(i=0; i<p->nCol; i++){
+ assert( p->bPatchset==0 || p->apValue[i]==0 );
+ if( p->abPK[i] ){
+ assert( p->apValue[i]==0 );
+ p->apValue[i] = p->apValue[i+p->nCol];
+ if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT);
+ p->apValue[i+p->nCol] = 0;
+ }
+ }
+ }else if( p->bInvert ){
+ if( p->op==SQLITE_INSERT ) p->op = SQLITE_DELETE;
+ else if( p->op==SQLITE_DELETE ) p->op = SQLITE_INSERT;
+ }
+ }
+
+ return SQLITE_ROW;
+}
+
+/*
+** Advance an iterator created by sqlite3changeset_start() to the next
+** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
+** or SQLITE_CORRUPT.
+**
+** This function may not be called on iterators passed to a conflict handler
+** callback by changeset_apply().
+*/
+SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
+ return sessionChangesetNext(p, 0, 0, 0);
+}
+
+/*
+** The following function extracts information on the current change
+** from a changeset iterator. It may only be called after changeset_next()
+** has returned SQLITE_ROW.
+*/
+SQLITE_API int sqlite3changeset_op(
+ sqlite3_changeset_iter *pIter, /* Iterator handle */
+ const char **pzTab, /* OUT: Pointer to table name */
+ int *pnCol, /* OUT: Number of columns in table */
+ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
+ int *pbIndirect /* OUT: True if change is indirect */
+){
+ *pOp = pIter->op;
+ *pnCol = pIter->nCol;
+ *pzTab = pIter->zTab;
+ if( pbIndirect ) *pbIndirect = pIter->bIndirect;
+ return SQLITE_OK;
+}
+
+/*
+** Return information regarding the PRIMARY KEY and number of columns in
+** the database table affected by the change that pIter currently points
+** to. This function may only be called after changeset_next() returns
+** SQLITE_ROW.
+*/
+SQLITE_API int sqlite3changeset_pk(
+ sqlite3_changeset_iter *pIter, /* Iterator object */
+ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
+ int *pnCol /* OUT: Number of entries in output array */
+){
+ *pabPK = pIter->abPK;
+ if( pnCol ) *pnCol = pIter->nCol;
+ return SQLITE_OK;
+}
+
+/*
+** This function may only be called while the iterator is pointing to an
+** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
+** Otherwise, SQLITE_MISUSE is returned.
+**
+** It sets *ppValue to point to an sqlite3_value structure containing the
+** iVal'th value in the old.* record. Or, if that particular value is not
+** included in the record (because the change is an UPDATE and the field
+** was not modified and is not a PK column), set *ppValue to NULL.
+**
+** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
+** not modified. Otherwise, SQLITE_OK.
+*/
+SQLITE_API int sqlite3changeset_old(
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ int iVal, /* Index of old.* value to retrieve */
+ sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
+){
+ if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
+ return SQLITE_MISUSE;
+ }
+ if( iVal<0 || iVal>=pIter->nCol ){
+ return SQLITE_RANGE;
+ }
+ *ppValue = pIter->apValue[iVal];
+ return SQLITE_OK;
+}
+
+/*
+** This function may only be called while the iterator is pointing to an
+** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
+** Otherwise, SQLITE_MISUSE is returned.
+**
+** It sets *ppValue to point to an sqlite3_value structure containing the
+** iVal'th value in the new.* record. Or, if that particular value is not
+** included in the record (because the change is an UPDATE and the field
+** was not modified), set *ppValue to NULL.
+**
+** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
+** not modified. Otherwise, SQLITE_OK.
+*/
+SQLITE_API int sqlite3changeset_new(
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ int iVal, /* Index of new.* value to retrieve */
+ sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
+){
+ if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
+ return SQLITE_MISUSE;
+ }
+ if( iVal<0 || iVal>=pIter->nCol ){
+ return SQLITE_RANGE;
+ }
+ *ppValue = pIter->apValue[pIter->nCol+iVal];
+ return SQLITE_OK;
+}
+
+/*
+** The following two macros are used internally. They are similar to the
+** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
+** they omit all error checking and return a pointer to the requested value.
+*/
+#define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
+#define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
+
+/*
+** This function may only be called with a changeset iterator that has been
+** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
+** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
+**
+** If successful, *ppValue is set to point to an sqlite3_value structure
+** containing the iVal'th value of the conflicting record.
+**
+** If value iVal is out-of-range or some other error occurs, an SQLite error
+** code is returned. Otherwise, SQLITE_OK.
+*/
+SQLITE_API int sqlite3changeset_conflict(
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ int iVal, /* Index of conflict record value to fetch */
+ sqlite3_value **ppValue /* OUT: Value from conflicting row */
+){
+ if( !pIter->pConflict ){
+ return SQLITE_MISUSE;
+ }
+ if( iVal<0 || iVal>=pIter->nCol ){
+ return SQLITE_RANGE;
+ }
+ *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
+ return SQLITE_OK;
+}
+
+/*
+** This function may only be called with an iterator passed to an
+** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
+** it sets the output variable to the total number of known foreign key
+** violations in the destination database and returns SQLITE_OK.
+**
+** In all other cases this function returns SQLITE_MISUSE.
+*/
+SQLITE_API int sqlite3changeset_fk_conflicts(
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ int *pnOut /* OUT: Number of FK violations */
+){
+ if( pIter->pConflict || pIter->apValue ){
+ return SQLITE_MISUSE;
+ }
+ *pnOut = pIter->nCol;
+ return SQLITE_OK;
+}
+
+
+/*
+** Finalize an iterator allocated with sqlite3changeset_start().
+**
+** This function may not be called on iterators passed to a conflict handler
+** callback by changeset_apply().
+*/
+SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
+ int rc = SQLITE_OK;
+ if( p ){
+ int i; /* Used to iterate through p->apValue[] */
+ rc = p->rc;
+ if( p->apValue ){
+ for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
+ }
+ sqlite3_free(p->tblhdr.aBuf);
+ sqlite3_free(p->in.buf.aBuf);
+ sqlite3_free(p);
+ }
+ return rc;
+}
+
+static int sessionChangesetInvert(
+ SessionInput *pInput, /* Input changeset */
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut,
+ int *pnInverted, /* OUT: Number of bytes in output changeset */
+ void **ppInverted /* OUT: Inverse of pChangeset */
+){
+ int rc = SQLITE_OK; /* Return value */
+ SessionBuffer sOut; /* Output buffer */
+ int nCol = 0; /* Number of cols in current table */
+ u8 *abPK = 0; /* PK array for current table */
+ sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
+ SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
+
+ /* Initialize the output buffer */
+ memset(&sOut, 0, sizeof(SessionBuffer));
+
+ /* Zero the output variables in case an error occurs. */
+ if( ppInverted ){
+ *ppInverted = 0;
+ *pnInverted = 0;
+ }
+
+ while( 1 ){
+ u8 eType;
+
+ /* Test for EOF. */
+ if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
+ if( pInput->iNext>=pInput->nData ) break;
+ eType = pInput->aData[pInput->iNext];
+
+ switch( eType ){
+ case 'T': {
+ /* A 'table' record consists of:
+ **
+ ** * A constant 'T' character,
+ ** * Number of columns in said table (a varint),
+ ** * An array of nCol bytes (sPK),
+ ** * A nul-terminated table name.
+ */
+ int nByte;
+ int nVar;
+ pInput->iNext++;
+ if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
+ goto finished_invert;
+ }
+ nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
+ sPK.nBuf = 0;
+ sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
+ sessionAppendByte(&sOut, eType, &rc);
+ sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
+ if( rc ) goto finished_invert;
+
+ pInput->iNext += nByte;
+ sqlite3_free(apVal);
+ apVal = 0;
+ abPK = sPK.aBuf;
+ break;
+ }
+
+ case SQLITE_INSERT:
+ case SQLITE_DELETE: {
+ int nByte;
+ int bIndirect = pInput->aData[pInput->iNext+1];
+ int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
+ pInput->iNext += 2;
+ assert( rc==SQLITE_OK );
+ rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
+ sessionAppendByte(&sOut, eType2, &rc);
+ sessionAppendByte(&sOut, bIndirect, &rc);
+ sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
+ pInput->iNext += nByte;
+ if( rc ) goto finished_invert;
+ break;
+ }
+
+ case SQLITE_UPDATE: {
+ int iCol;
+
+ if( 0==apVal ){
+ apVal = (sqlite3_value **)sqlite3_malloc64(sizeof(apVal[0])*nCol*2);
+ if( 0==apVal ){
+ rc = SQLITE_NOMEM;
+ goto finished_invert;
+ }
+ memset(apVal, 0, sizeof(apVal[0])*nCol*2);
+ }
+
+ /* Write the header for the new UPDATE change. Same as the original. */
+ sessionAppendByte(&sOut, eType, &rc);
+ sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
+
+ /* Read the old.* and new.* records for the update change. */
+ pInput->iNext += 2;
+ rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
+ if( rc==SQLITE_OK ){
+ rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
+ }
+
+ /* Write the new old.* record. Consists of the PK columns from the
+ ** original old.* record, and the other values from the original
+ ** new.* record. */
+ for(iCol=0; iCol<nCol; iCol++){
+ sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
+ sessionAppendValue(&sOut, pVal, &rc);
+ }
+
+ /* Write the new new.* record. Consists of a copy of all values
+ ** from the original old.* record, except for the PK columns, which
+ ** are set to "undefined". */
+ for(iCol=0; iCol<nCol; iCol++){
+ sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
+ sessionAppendValue(&sOut, pVal, &rc);
+ }
+
+ for(iCol=0; iCol<nCol*2; iCol++){
+ sqlite3ValueFree(apVal[iCol]);
+ }
+ memset(apVal, 0, sizeof(apVal[0])*nCol*2);
+ if( rc!=SQLITE_OK ){
+ goto finished_invert;
+ }
+
+ break;
+ }
+
+ default:
+ rc = SQLITE_CORRUPT_BKPT;
+ goto finished_invert;
+ }
+
+ assert( rc==SQLITE_OK );
+ if( xOutput && sOut.nBuf>=sessions_strm_chunk_size ){
+ rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
+ sOut.nBuf = 0;
+ if( rc!=SQLITE_OK ) goto finished_invert;
+ }
+ }
+
+ assert( rc==SQLITE_OK );
+ if( pnInverted ){
+ *pnInverted = sOut.nBuf;
+ *ppInverted = sOut.aBuf;
+ sOut.aBuf = 0;
+ }else if( sOut.nBuf>0 ){
+ rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
+ }
+
+ finished_invert:
+ sqlite3_free(sOut.aBuf);
+ sqlite3_free(apVal);
+ sqlite3_free(sPK.aBuf);
+ return rc;
+}
+
+
+/*
+** Invert a changeset object.
+*/
+SQLITE_API int sqlite3changeset_invert(
+ int nChangeset, /* Number of bytes in input */
+ const void *pChangeset, /* Input changeset */
+ int *pnInverted, /* OUT: Number of bytes in output changeset */
+ void **ppInverted /* OUT: Inverse of pChangeset */
+){
+ SessionInput sInput;
+
+ /* Set up the input stream */
+ memset(&sInput, 0, sizeof(SessionInput));
+ sInput.nData = nChangeset;
+ sInput.aData = (u8*)pChangeset;
+
+ return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
+}
+
+/*
+** Streaming version of sqlite3changeset_invert().
+*/
+SQLITE_API int sqlite3changeset_invert_strm(
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+){
+ SessionInput sInput;
+ int rc;
+
+ /* Set up the input stream */
+ memset(&sInput, 0, sizeof(SessionInput));
+ sInput.xInput = xInput;
+ sInput.pIn = pIn;
+
+ rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
+ sqlite3_free(sInput.buf.aBuf);
+ return rc;
+}
+
+typedef struct SessionApplyCtx SessionApplyCtx;
+struct SessionApplyCtx {
+ sqlite3 *db;
+ sqlite3_stmt *pDelete; /* DELETE statement */
+ sqlite3_stmt *pUpdate; /* UPDATE statement */
+ sqlite3_stmt *pInsert; /* INSERT statement */
+ sqlite3_stmt *pSelect; /* SELECT statement */
+ int nCol; /* Size of azCol[] and abPK[] arrays */
+ const char **azCol; /* Array of column names */
+ u8 *abPK; /* Boolean array - true if column is in PK */
+ int bStat1; /* True if table is sqlite_stat1 */
+ int bDeferConstraints; /* True to defer constraints */
+ int bInvertConstraints; /* Invert when iterating constraints buffer */
+ SessionBuffer constraints; /* Deferred constraints are stored here */
+ SessionBuffer rebase; /* Rebase information (if any) here */
+ u8 bRebaseStarted; /* If table header is already in rebase */
+ u8 bRebase; /* True to collect rebase information */
+};
+
+/*
+** Formulate a statement to DELETE a row from database db. Assuming a table
+** structure like this:
+**
+** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
+**
+** The DELETE statement looks like this:
+**
+** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
+**
+** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
+** matching b and d values, or 1 otherwise. The second case comes up if the
+** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
+**
+** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
+** pointing to the prepared version of the SQL statement.
+*/
+static int sessionDeleteRow(
+ sqlite3 *db, /* Database handle */
+ const char *zTab, /* Table name */
+ SessionApplyCtx *p /* Session changeset-apply context */
+){
+ int i;
+ const char *zSep = "";
+ int rc = SQLITE_OK;
+ SessionBuffer buf = {0, 0, 0};
+ int nPk = 0;
+
+ sessionAppendStr(&buf, "DELETE FROM main.", &rc);
+ sessionAppendIdent(&buf, zTab, &rc);
+ sessionAppendStr(&buf, " WHERE ", &rc);
+
+ for(i=0; i<p->nCol; i++){
+ if( p->abPK[i] ){
+ nPk++;
+ sessionAppendStr(&buf, zSep, &rc);
+ sessionAppendIdent(&buf, p->azCol[i], &rc);
+ sessionAppendStr(&buf, " = ?", &rc);
+ sessionAppendInteger(&buf, i+1, &rc);
+ zSep = " AND ";
+ }
+ }
+
+ if( nPk<p->nCol ){
+ sessionAppendStr(&buf, " AND (?", &rc);
+ sessionAppendInteger(&buf, p->nCol+1, &rc);
+ sessionAppendStr(&buf, " OR ", &rc);
+
+ zSep = "";
+ for(i=0; i<p->nCol; i++){
+ if( !p->abPK[i] ){
+ sessionAppendStr(&buf, zSep, &rc);
+ sessionAppendIdent(&buf, p->azCol[i], &rc);
+ sessionAppendStr(&buf, " IS ?", &rc);
+ sessionAppendInteger(&buf, i+1, &rc);
+ zSep = "AND ";
+ }
+ }
+ sessionAppendStr(&buf, ")", &rc);
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
+ }
+ sqlite3_free(buf.aBuf);
+
+ return rc;
+}
+
+/*
+** Formulate and prepare a statement to UPDATE a row from database db.
+** Assuming a table structure like this:
+**
+** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
+**
+** The UPDATE statement looks like this:
+**
+** UPDATE x SET
+** a = CASE WHEN ?2 THEN ?3 ELSE a END,
+** b = CASE WHEN ?5 THEN ?6 ELSE b END,
+** c = CASE WHEN ?8 THEN ?9 ELSE c END,
+** d = CASE WHEN ?11 THEN ?12 ELSE d END
+** WHERE a = ?1 AND c = ?7 AND (?13 OR
+** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
+** )
+**
+** For each column in the table, there are three variables to bind:
+**
+** ?(i*3+1) The old.* value of the column, if any.
+** ?(i*3+2) A boolean flag indicating that the value is being modified.
+** ?(i*3+3) The new.* value of the column, if any.
+**
+** Also, a boolean flag that, if set to true, causes the statement to update
+** a row even if the non-PK values do not match. This is required if the
+** conflict-handler is invoked with CHANGESET_DATA and returns
+** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
+**
+** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
+** pointing to the prepared version of the SQL statement.
+*/
+static int sessionUpdateRow(
+ sqlite3 *db, /* Database handle */
+ const char *zTab, /* Table name */
+ SessionApplyCtx *p /* Session changeset-apply context */
+){
+ int rc = SQLITE_OK;
+ int i;
+ const char *zSep = "";
+ SessionBuffer buf = {0, 0, 0};
+
+ /* Append "UPDATE tbl SET " */
+ sessionAppendStr(&buf, "UPDATE main.", &rc);
+ sessionAppendIdent(&buf, zTab, &rc);
+ sessionAppendStr(&buf, " SET ", &rc);
+
+ /* Append the assignments */
+ for(i=0; i<p->nCol; i++){
+ sessionAppendStr(&buf, zSep, &rc);
+ sessionAppendIdent(&buf, p->azCol[i], &rc);
+ sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
+ sessionAppendInteger(&buf, i*3+2, &rc);
+ sessionAppendStr(&buf, " THEN ?", &rc);
+ sessionAppendInteger(&buf, i*3+3, &rc);
+ sessionAppendStr(&buf, " ELSE ", &rc);
+ sessionAppendIdent(&buf, p->azCol[i], &rc);
+ sessionAppendStr(&buf, " END", &rc);
+ zSep = ", ";
+ }
+
+ /* Append the PK part of the WHERE clause */
+ sessionAppendStr(&buf, " WHERE ", &rc);
+ for(i=0; i<p->nCol; i++){
+ if( p->abPK[i] ){
+ sessionAppendIdent(&buf, p->azCol[i], &rc);
+ sessionAppendStr(&buf, " = ?", &rc);
+ sessionAppendInteger(&buf, i*3+1, &rc);
+ sessionAppendStr(&buf, " AND ", &rc);
+ }
+ }
+
+ /* Append the non-PK part of the WHERE clause */
+ sessionAppendStr(&buf, " (?", &rc);
+ sessionAppendInteger(&buf, p->nCol*3+1, &rc);
+ sessionAppendStr(&buf, " OR 1", &rc);
+ for(i=0; i<p->nCol; i++){
+ if( !p->abPK[i] ){
+ sessionAppendStr(&buf, " AND (?", &rc);
+ sessionAppendInteger(&buf, i*3+2, &rc);
+ sessionAppendStr(&buf, "=0 OR ", &rc);
+ sessionAppendIdent(&buf, p->azCol[i], &rc);
+ sessionAppendStr(&buf, " IS ?", &rc);
+ sessionAppendInteger(&buf, i*3+1, &rc);
+ sessionAppendStr(&buf, ")", &rc);
+ }
+ }
+ sessionAppendStr(&buf, ")", &rc);
+
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
+ }
+ sqlite3_free(buf.aBuf);
+
+ return rc;
+}
+
+
+/*
+** Formulate and prepare an SQL statement to query table zTab by primary
+** key. Assuming the following table structure:
+**
+** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
+**
+** The SELECT statement looks like this:
+**
+** SELECT * FROM x WHERE a = ?1 AND c = ?3
+**
+** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
+** pointing to the prepared version of the SQL statement.
+*/
+static int sessionSelectRow(
+ sqlite3 *db, /* Database handle */
+ const char *zTab, /* Table name */
+ SessionApplyCtx *p /* Session changeset-apply context */
+){
+ return sessionSelectStmt(
+ db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
+}
+
+/*
+** Formulate and prepare an INSERT statement to add a record to table zTab.
+** For example:
+**
+** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
+**
+** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
+** pointing to the prepared version of the SQL statement.
+*/
+static int sessionInsertRow(
+ sqlite3 *db, /* Database handle */
+ const char *zTab, /* Table name */
+ SessionApplyCtx *p /* Session changeset-apply context */
+){
+ int rc = SQLITE_OK;
+ int i;
+ SessionBuffer buf = {0, 0, 0};
+
+ sessionAppendStr(&buf, "INSERT INTO main.", &rc);
+ sessionAppendIdent(&buf, zTab, &rc);
+ sessionAppendStr(&buf, "(", &rc);
+ for(i=0; i<p->nCol; i++){
+ if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
+ sessionAppendIdent(&buf, p->azCol[i], &rc);
+ }
+
+ sessionAppendStr(&buf, ") VALUES(?", &rc);
+ for(i=1; i<p->nCol; i++){
+ sessionAppendStr(&buf, ", ?", &rc);
+ }
+ sessionAppendStr(&buf, ")", &rc);
+
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
+ }
+ sqlite3_free(buf.aBuf);
+ return rc;
+}
+
+static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){
+ return sqlite3_prepare_v2(db, zSql, -1, pp, 0);
+}
+
+/*
+** Prepare statements for applying changes to the sqlite_stat1 table.
+** These are similar to those created by sessionSelectRow(),
+** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for
+** other tables.
+*/
+static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
+ int rc = sessionSelectRow(db, "sqlite_stat1", p);
+ if( rc==SQLITE_OK ){
+ rc = sessionPrepare(db, &p->pInsert,
+ "INSERT INTO main.sqlite_stat1 VALUES(?1, "
+ "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, "
+ "?3)"
+ );
+ }
+ if( rc==SQLITE_OK ){
+ rc = sessionPrepare(db, &p->pUpdate,
+ "UPDATE main.sqlite_stat1 SET "
+ "tbl = CASE WHEN ?2 THEN ?3 ELSE tbl END, "
+ "idx = CASE WHEN ?5 THEN ?6 ELSE idx END, "
+ "stat = CASE WHEN ?8 THEN ?9 ELSE stat END "
+ "WHERE tbl=?1 AND idx IS "
+ "CASE WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL ELSE ?4 END "
+ "AND (?10 OR ?8=0 OR stat IS ?7)"
+ );
+ }
+ if( rc==SQLITE_OK ){
+ rc = sessionPrepare(db, &p->pDelete,
+ "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS "
+ "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END "
+ "AND (?4 OR stat IS ?3)"
+ );
+ }
+ return rc;
+}
+
+/*
+** A wrapper around sqlite3_bind_value() that detects an extra problem.
+** See comments in the body of this function for details.
+*/
+static int sessionBindValue(
+ sqlite3_stmt *pStmt, /* Statement to bind value to */
+ int i, /* Parameter number to bind to */
+ sqlite3_value *pVal /* Value to bind */
+){
+ int eType = sqlite3_value_type(pVal);
+ /* COVERAGE: The (pVal->z==0) branch is never true using current versions
+ ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
+ ** the (pVal->z) variable remains as it was or the type of the value is
+ ** set to SQLITE_NULL. */
+ if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
+ /* This condition occurs when an earlier OOM in a call to
+ ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
+ ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
+ return SQLITE_NOMEM;
+ }
+ return sqlite3_bind_value(pStmt, i, pVal);
+}
+
+/*
+** Iterator pIter must point to an SQLITE_INSERT entry. This function
+** transfers new.* values from the current iterator entry to statement
+** pStmt. The table being inserted into has nCol columns.
+**
+** New.* value $i from the iterator is bound to variable ($i+1) of
+** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
+** are transfered to the statement. Otherwise, if abPK is not NULL, it points
+** to an array nCol elements in size. In this case only those values for
+** which abPK[$i] is true are read from the iterator and bound to the
+** statement.
+**
+** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
+*/
+static int sessionBindRow(
+ sqlite3_changeset_iter *pIter, /* Iterator to read values from */
+ int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
+ int nCol, /* Number of columns */
+ u8 *abPK, /* If not NULL, bind only if true */
+ sqlite3_stmt *pStmt /* Bind values to this statement */
+){
+ int i;
+ int rc = SQLITE_OK;
+
+ /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
+ ** argument iterator points to a suitable entry. Make sure that xValue
+ ** is one of these to guarantee that it is safe to ignore the return
+ ** in the code below. */
+ assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
+
+ for(i=0; rc==SQLITE_OK && i<nCol; i++){
+ if( !abPK || abPK[i] ){
+ sqlite3_value *pVal;
+ (void)xValue(pIter, i, &pVal);
+ if( pVal==0 ){
+ /* The value in the changeset was "undefined". This indicates a
+ ** corrupt changeset blob. */
+ rc = SQLITE_CORRUPT_BKPT;
+ }else{
+ rc = sessionBindValue(pStmt, i+1, pVal);
+ }
+ }
+ }
+ return rc;
+}
+
+/*
+** SQL statement pSelect is as generated by the sessionSelectRow() function.
+** This function binds the primary key values from the change that changeset
+** iterator pIter points to to the SELECT and attempts to seek to the table
+** entry. If a row is found, the SELECT statement left pointing at the row
+** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
+** has occured, the statement is reset and SQLITE_OK is returned. If an
+** error occurs, the statement is reset and an SQLite error code is returned.
+**
+** If this function returns SQLITE_ROW, the caller must eventually reset()
+** statement pSelect. If any other value is returned, the statement does
+** not require a reset().
+**
+** If the iterator currently points to an INSERT record, bind values from the
+** new.* record to the SELECT statement. Or, if it points to a DELETE or
+** UPDATE, bind values from the old.* record.
+*/
+static int sessionSeekToRow(
+ sqlite3 *db, /* Database handle */
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ u8 *abPK, /* Primary key flags array */
+ sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
+){
+ int rc; /* Return code */
+ int nCol; /* Number of columns in table */
+ int op; /* Changset operation (SQLITE_UPDATE etc.) */
+ const char *zDummy; /* Unused */
+
+ sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
+ rc = sessionBindRow(pIter,
+ op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
+ nCol, abPK, pSelect
+ );
+
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_step(pSelect);
+ if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
+ }
+
+ return rc;
+}
+
+/*
+** This function is called from within sqlite3changeset_apply_v2() when
+** a conflict is encountered and resolved using conflict resolution
+** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE)..
+** It adds a conflict resolution record to the buffer in
+** SessionApplyCtx.rebase, which will eventually be returned to the caller
+** of apply_v2() as the "rebase" buffer.
+**
+** Return SQLITE_OK if successful, or an SQLite error code otherwise.
+*/
+static int sessionRebaseAdd(
+ SessionApplyCtx *p, /* Apply context */
+ int eType, /* Conflict resolution (OMIT or REPLACE) */
+ sqlite3_changeset_iter *pIter /* Iterator pointing at current change */
+){
+ int rc = SQLITE_OK;
+ if( p->bRebase ){
+ int i;
+ int eOp = pIter->op;
+ if( p->bRebaseStarted==0 ){
+ /* Append a table-header to the rebase buffer */
+ const char *zTab = pIter->zTab;
+ sessionAppendByte(&p->rebase, 'T', &rc);
+ sessionAppendVarint(&p->rebase, p->nCol, &rc);
+ sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc);
+ sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc);
+ p->bRebaseStarted = 1;
+ }
+
+ assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT );
+ assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE );
+
+ sessionAppendByte(&p->rebase,
+ (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc
+ );
+ sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc);
+ for(i=0; i<p->nCol; i++){
+ sqlite3_value *pVal = 0;
+ if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){
+ sqlite3changeset_old(pIter, i, &pVal);
+ }else{
+ sqlite3changeset_new(pIter, i, &pVal);
+ }
+ sessionAppendValue(&p->rebase, pVal, &rc);
+ }
+ }
+ return rc;
+}
+
+/*
+** Invoke the conflict handler for the change that the changeset iterator
+** currently points to.
+**
+** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
+** If argument pbReplace is NULL, then the type of conflict handler invoked
+** depends solely on eType, as follows:
+**
+** eType value Value passed to xConflict
+** -------------------------------------------------
+** CHANGESET_DATA CHANGESET_NOTFOUND
+** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
+**
+** Or, if pbReplace is not NULL, then an attempt is made to find an existing
+** record with the same primary key as the record about to be deleted, updated
+** or inserted. If such a record can be found, it is available to the conflict
+** handler as the "conflicting" record. In this case the type of conflict
+** handler invoked is as follows:
+**
+** eType value PK Record found? Value passed to xConflict
+** ----------------------------------------------------------------
+** CHANGESET_DATA Yes CHANGESET_DATA
+** CHANGESET_DATA No CHANGESET_NOTFOUND
+** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
+** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
+**
+** If pbReplace is not NULL, and a record with a matching PK is found, and
+** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
+** is set to non-zero before returning SQLITE_OK.
+**
+** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
+** returned. Or, if the conflict handler returns an invalid value,
+** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
+** this function returns SQLITE_OK.
+*/
+static int sessionConflictHandler(
+ int eType, /* Either CHANGESET_DATA or CONFLICT */
+ SessionApplyCtx *p, /* changeset_apply() context */
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ int(*xConflict)(void *, int, sqlite3_changeset_iter*),
+ void *pCtx, /* First argument for conflict handler */
+ int *pbReplace /* OUT: Set to true if PK row is found */
+){
+ int res = 0; /* Value returned by conflict handler */
+ int rc;
+ int nCol;
+ int op;
+ const char *zDummy;
+
+ sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
+
+ assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
+ assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
+ assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
+
+ /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
+ if( pbReplace ){
+ rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
+ }else{
+ rc = SQLITE_OK;
+ }
+
+ if( rc==SQLITE_ROW ){
+ /* There exists another row with the new.* primary key. */
+ pIter->pConflict = p->pSelect;
+ res = xConflict(pCtx, eType, pIter);
+ pIter->pConflict = 0;
+ rc = sqlite3_reset(p->pSelect);
+ }else if( rc==SQLITE_OK ){
+ if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
+ /* Instead of invoking the conflict handler, append the change blob
+ ** to the SessionApplyCtx.constraints buffer. */
+ u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
+ int nBlob = pIter->in.iNext - pIter->in.iCurrent;
+ sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
+ return SQLITE_OK;
+ }else{
+ /* No other row with the new.* primary key. */
+ res = xConflict(pCtx, eType+1, pIter);
+ if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ switch( res ){
+ case SQLITE_CHANGESET_REPLACE:
+ assert( pbReplace );
+ *pbReplace = 1;
+ break;
+
+ case SQLITE_CHANGESET_OMIT:
+ break;
+
+ case SQLITE_CHANGESET_ABORT:
+ rc = SQLITE_ABORT;
+ break;
+
+ default:
+ rc = SQLITE_MISUSE;
+ break;
+ }
+ if( rc==SQLITE_OK ){
+ rc = sessionRebaseAdd(p, res, pIter);
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Attempt to apply the change that the iterator passed as the first argument
+** currently points to to the database. If a conflict is encountered, invoke
+** the conflict handler callback.
+**
+** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
+** one is encountered, update or delete the row with the matching primary key
+** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
+** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
+** to true before returning. In this case the caller will invoke this function
+** again, this time with pbRetry set to NULL.
+**
+** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
+** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
+** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
+** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
+** before retrying. In this case the caller attempts to remove the conflicting
+** row before invoking this function again, this time with pbReplace set
+** to NULL.
+**
+** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
+** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
+** returned.
+*/
+static int sessionApplyOneOp(
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ SessionApplyCtx *p, /* changeset_apply() context */
+ int(*xConflict)(void *, int, sqlite3_changeset_iter *),
+ void *pCtx, /* First argument for the conflict handler */
+ int *pbReplace, /* OUT: True to remove PK row and retry */
+ int *pbRetry /* OUT: True to retry. */
+){
+ const char *zDummy;
+ int op;
+ int nCol;
+ int rc = SQLITE_OK;
+
+ assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
+ assert( p->azCol && p->abPK );
+ assert( !pbReplace || *pbReplace==0 );
+
+ sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
+
+ if( op==SQLITE_DELETE ){
+
+ /* Bind values to the DELETE statement. If conflict handling is required,
+ ** bind values for all columns and set bound variable (nCol+1) to true.
+ ** Or, if conflict handling is not required, bind just the PK column
+ ** values and, if it exists, set (nCol+1) to false. Conflict handling
+ ** is not required if:
+ **
+ ** * this is a patchset, or
+ ** * (pbRetry==0), or
+ ** * all columns of the table are PK columns (in this case there is
+ ** no (nCol+1) variable to bind to).
+ */
+ u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
+ rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
+ if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
+ rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
+ }
+ if( rc!=SQLITE_OK ) return rc;
+
+ sqlite3_step(p->pDelete);
+ rc = sqlite3_reset(p->pDelete);
+ if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
+ rc = sessionConflictHandler(
+ SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
+ );
+ }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
+ rc = sessionConflictHandler(
+ SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
+ );
+ }
+
+ }else if( op==SQLITE_UPDATE ){
+ int i;
+
+ /* Bind values to the UPDATE statement. */
+ for(i=0; rc==SQLITE_OK && i<nCol; i++){
+ sqlite3_value *pOld = sessionChangesetOld(pIter, i);
+ sqlite3_value *pNew = sessionChangesetNew(pIter, i);
+
+ sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
+ if( pOld ){
+ rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
+ }
+ if( rc==SQLITE_OK && pNew ){
+ rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
+ }
+ }
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
+ }
+ if( rc!=SQLITE_OK ) return rc;
+
+ /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
+ ** the result will be SQLITE_OK with 0 rows modified. */
+ sqlite3_step(p->pUpdate);
+ rc = sqlite3_reset(p->pUpdate);
+
+ if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
+ /* A NOTFOUND or DATA error. Search the table to see if it contains
+ ** a row with a matching primary key. If so, this is a DATA conflict.
+ ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
+
+ rc = sessionConflictHandler(
+ SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
+ );
+
+ }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
+ /* This is always a CONSTRAINT conflict. */
+ rc = sessionConflictHandler(
+ SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
+ );
+ }
+
+ }else{
+ assert( op==SQLITE_INSERT );
+ if( p->bStat1 ){
+ /* Check if there is a conflicting row. For sqlite_stat1, this needs
+ ** to be done using a SELECT, as there is no PRIMARY KEY in the
+ ** database schema to throw an exception if a duplicate is inserted. */
+ rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
+ if( rc==SQLITE_ROW ){
+ rc = SQLITE_CONSTRAINT;
+ sqlite3_reset(p->pSelect);
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
+ if( rc!=SQLITE_OK ) return rc;
+
+ sqlite3_step(p->pInsert);
+ rc = sqlite3_reset(p->pInsert);
+ }
+
+ if( (rc&0xff)==SQLITE_CONSTRAINT ){
+ rc = sessionConflictHandler(
+ SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
+ );
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Attempt to apply the change that the iterator passed as the first argument
+** currently points to to the database. If a conflict is encountered, invoke
+** the conflict handler callback.
+**
+** The difference between this function and sessionApplyOne() is that this
+** function handles the case where the conflict-handler is invoked and
+** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
+** retried in some manner.
+*/
+static int sessionApplyOneWithRetry(
+ sqlite3 *db, /* Apply change to "main" db of this handle */
+ sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
+ SessionApplyCtx *pApply, /* Apply context */
+ int(*xConflict)(void*, int, sqlite3_changeset_iter*),
+ void *pCtx /* First argument passed to xConflict */
+){
+ int bReplace = 0;
+ int bRetry = 0;
+ int rc;
+
+ rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
+ if( rc==SQLITE_OK ){
+ /* If the bRetry flag is set, the change has not been applied due to an
+ ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
+ ** a row with the correct PK is present in the db, but one or more other
+ ** fields do not contain the expected values) and the conflict handler
+ ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
+ ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
+ ** the SQLITE_CHANGESET_DATA problem. */
+ if( bRetry ){
+ assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
+ rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
+ }
+
+ /* If the bReplace flag is set, the change is an INSERT that has not
+ ** been performed because the database already contains a row with the
+ ** specified primary key and the conflict handler returned
+ ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
+ ** before reattempting the INSERT. */
+ else if( bReplace ){
+ assert( pIter->op==SQLITE_INSERT );
+ rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
+ if( rc==SQLITE_OK ){
+ rc = sessionBindRow(pIter,
+ sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
+ sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
+ }
+ if( rc==SQLITE_OK ){
+ sqlite3_step(pApply->pDelete);
+ rc = sqlite3_reset(pApply->pDelete);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
+ }
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Retry the changes accumulated in the pApply->constraints buffer.
+*/
+static int sessionRetryConstraints(
+ sqlite3 *db,
+ int bPatchset,
+ const char *zTab,
+ SessionApplyCtx *pApply,
+ int(*xConflict)(void*, int, sqlite3_changeset_iter*),
+ void *pCtx /* First argument passed to xConflict */
+){
+ int rc = SQLITE_OK;
+
+ while( pApply->constraints.nBuf ){
+ sqlite3_changeset_iter *pIter2 = 0;
+ SessionBuffer cons = pApply->constraints;
+ memset(&pApply->constraints, 0, sizeof(SessionBuffer));
+
+ rc = sessionChangesetStart(
+ &pIter2, 0, 0, cons.nBuf, cons.aBuf, pApply->bInvertConstraints
+ );
+ if( rc==SQLITE_OK ){
+ size_t nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
+ int rc2;
+ pIter2->bPatchset = bPatchset;
+ pIter2->zTab = (char*)zTab;
+ pIter2->nCol = pApply->nCol;
+ pIter2->abPK = pApply->abPK;
+ sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
+ pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
+ if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
+
+ while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
+ rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
+ }
+
+ rc2 = sqlite3changeset_finalize(pIter2);
+ if( rc==SQLITE_OK ) rc = rc2;
+ }
+ assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
+
+ sqlite3_free(cons.aBuf);
+ if( rc!=SQLITE_OK ) break;
+ if( pApply->constraints.nBuf>=cons.nBuf ){
+ /* No progress was made on the last round. */
+ pApply->bDeferConstraints = 0;
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Argument pIter is a changeset iterator that has been initialized, but
+** not yet passed to sqlite3changeset_next(). This function applies the
+** changeset to the main database attached to handle "db". The supplied
+** conflict handler callback is invoked to resolve any conflicts encountered
+** while applying the change.
+*/
+static int sessionChangesetApply(
+ sqlite3 *db, /* Apply change to "main" db of this handle */
+ sqlite3_changeset_iter *pIter, /* Changeset to apply */
+ int(*xFilter)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ const char *zTab /* Table name */
+ ),
+ int(*xConflict)(
+ void *pCtx, /* Copy of fifth arg to _apply() */
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
+ ),
+ void *pCtx, /* First argument passed to xConflict */
+ void **ppRebase, int *pnRebase, /* OUT: Rebase information */
+ int flags /* SESSION_APPLY_XXX flags */
+){
+ int schemaMismatch = 0;
+ int rc = SQLITE_OK; /* Return code */
+ const char *zTab = 0; /* Name of current table */
+ int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
+ SessionApplyCtx sApply; /* changeset_apply() context object */
+ int bPatchset;
+
+ assert( xConflict!=0 );
+
+ pIter->in.bNoDiscard = 1;
+ memset(&sApply, 0, sizeof(sApply));
+ sApply.bRebase = (ppRebase && pnRebase);
+ sApply.bInvertConstraints = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
+ sqlite3_mutex_enter(sqlite3_db_mutex(db));
+ if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
+ rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
+ }
+ while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
+ int nCol;
+ int op;
+ const char *zNew;
+
+ sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
+
+ if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
+ u8 *abPK;
+
+ rc = sessionRetryConstraints(
+ db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
+ );
+ if( rc!=SQLITE_OK ) break;
+
+ sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
+ sqlite3_finalize(sApply.pDelete);
+ sqlite3_finalize(sApply.pUpdate);
+ sqlite3_finalize(sApply.pInsert);
+ sqlite3_finalize(sApply.pSelect);
+ sApply.db = db;
+ sApply.pDelete = 0;
+ sApply.pUpdate = 0;
+ sApply.pInsert = 0;
+ sApply.pSelect = 0;
+ sApply.nCol = 0;
+ sApply.azCol = 0;
+ sApply.abPK = 0;
+ sApply.bStat1 = 0;
+ sApply.bDeferConstraints = 1;
+ sApply.bRebaseStarted = 0;
+ memset(&sApply.constraints, 0, sizeof(SessionBuffer));
+
+ /* If an xFilter() callback was specified, invoke it now. If the
+ ** xFilter callback returns zero, skip this table. If it returns
+ ** non-zero, proceed. */
+ schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
+ if( schemaMismatch ){
+ zTab = sqlite3_mprintf("%s", zNew);
+ if( zTab==0 ){
+ rc = SQLITE_NOMEM;
+ break;
+ }
+ nTab = (int)strlen(zTab);
+ sApply.azCol = (const char **)zTab;
+ }else{
+ int nMinCol = 0;
+ int i;
+
+ sqlite3changeset_pk(pIter, &abPK, 0);
+ rc = sessionTableInfo(
+ db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
+ );
+ if( rc!=SQLITE_OK ) break;
+ for(i=0; i<sApply.nCol; i++){
+ if( sApply.abPK[i] ) nMinCol = i+1;
+ }
+
+ if( sApply.nCol==0 ){
+ schemaMismatch = 1;
+ sqlite3_log(SQLITE_SCHEMA,
+ "sqlite3changeset_apply(): no such table: %s", zTab
+ );
+ }
+ else if( sApply.nCol<nCol ){
+ schemaMismatch = 1;
+ sqlite3_log(SQLITE_SCHEMA,
+ "sqlite3changeset_apply(): table %s has %d columns, "
+ "expected %d or more",
+ zTab, sApply.nCol, nCol
+ );
+ }
+ else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
+ schemaMismatch = 1;
+ sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
+ "primary key mismatch for table %s", zTab
+ );
+ }
+ else{
+ sApply.nCol = nCol;
+ if( 0==sqlite3_stricmp(zTab, "sqlite_stat1") ){
+ if( (rc = sessionStat1Sql(db, &sApply) ) ){
+ break;
+ }
+ sApply.bStat1 = 1;
+ }else{
+ if((rc = sessionSelectRow(db, zTab, &sApply))
+ || (rc = sessionUpdateRow(db, zTab, &sApply))
+ || (rc = sessionDeleteRow(db, zTab, &sApply))
+ || (rc = sessionInsertRow(db, zTab, &sApply))
+ ){
+ break;
+ }
+ sApply.bStat1 = 0;
+ }
+ }
+ nTab = sqlite3Strlen30(zTab);
+ }
+ }
+
+ /* If there is a schema mismatch on the current table, proceed to the
+ ** next change. A log message has already been issued. */
+ if( schemaMismatch ) continue;
+
+ rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
+ }
+
+ bPatchset = pIter->bPatchset;
+ if( rc==SQLITE_OK ){
+ rc = sqlite3changeset_finalize(pIter);
+ }else{
+ sqlite3changeset_finalize(pIter);
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
+ }
+
+ if( rc==SQLITE_OK ){
+ int nFk, notUsed;
+ sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
+ if( nFk!=0 ){
+ int res = SQLITE_CHANGESET_ABORT;
+ sqlite3_changeset_iter sIter;
+ memset(&sIter, 0, sizeof(sIter));
+ sIter.nCol = nFk;
+ res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
+ if( res!=SQLITE_CHANGESET_OMIT ){
+ rc = SQLITE_CONSTRAINT;
+ }
+ }
+ }
+ sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
+
+ if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
+ }else{
+ sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
+ sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
+ }
+ }
+
+ assert( sApply.bRebase || sApply.rebase.nBuf==0 );
+ if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){
+ *ppRebase = (void*)sApply.rebase.aBuf;
+ *pnRebase = sApply.rebase.nBuf;
+ sApply.rebase.aBuf = 0;
+ }
+ sqlite3_finalize(sApply.pInsert);
+ sqlite3_finalize(sApply.pDelete);
+ sqlite3_finalize(sApply.pUpdate);
+ sqlite3_finalize(sApply.pSelect);
+ sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
+ sqlite3_free((char*)sApply.constraints.aBuf);
+ sqlite3_free((char*)sApply.rebase.aBuf);
+ sqlite3_mutex_leave(sqlite3_db_mutex(db));
+ return rc;
+}
+
+/*
+** Apply the changeset passed via pChangeset/nChangeset to the main
+** database attached to handle "db".
+*/
+SQLITE_API int sqlite3changeset_apply_v2(
+ sqlite3 *db, /* Apply change to "main" db of this handle */
+ int nChangeset, /* Size of changeset in bytes */
+ void *pChangeset, /* Changeset blob */
+ int(*xFilter)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ const char *zTab /* Table name */
+ ),
+ int(*xConflict)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
+ ),
+ void *pCtx, /* First argument passed to xConflict */
+ void **ppRebase, int *pnRebase,
+ int flags
+){
+ sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
+ int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
+ int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset,bInverse);
+ if( rc==SQLITE_OK ){
+ rc = sessionChangesetApply(
+ db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
+ );
+ }
+ return rc;
+}
+
+/*
+** Apply the changeset passed via pChangeset/nChangeset to the main database
+** attached to handle "db". Invoke the supplied conflict handler callback
+** to resolve any conflicts encountered while applying the change.
+*/
+SQLITE_API int sqlite3changeset_apply(
+ sqlite3 *db, /* Apply change to "main" db of this handle */
+ int nChangeset, /* Size of changeset in bytes */
+ void *pChangeset, /* Changeset blob */
+ int(*xFilter)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ const char *zTab /* Table name */
+ ),
+ int(*xConflict)(
+ void *pCtx, /* Copy of fifth arg to _apply() */
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
+ ),
+ void *pCtx /* First argument passed to xConflict */
+){
+ return sqlite3changeset_apply_v2(
+ db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0
+ );
+}
+
+/*
+** Apply the changeset passed via xInput/pIn to the main database
+** attached to handle "db". Invoke the supplied conflict handler callback
+** to resolve any conflicts encountered while applying the change.
+*/
+SQLITE_API int sqlite3changeset_apply_v2_strm(
+ sqlite3 *db, /* Apply change to "main" db of this handle */
+ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
+ void *pIn, /* First arg for xInput */
+ int(*xFilter)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ const char *zTab /* Table name */
+ ),
+ int(*xConflict)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
+ ),
+ void *pCtx, /* First argument passed to xConflict */
+ void **ppRebase, int *pnRebase,
+ int flags
+){
+ sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
+ int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
+ int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse);
+ if( rc==SQLITE_OK ){
+ rc = sessionChangesetApply(
+ db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
+ );
+ }
+ return rc;
+}
+SQLITE_API int sqlite3changeset_apply_strm(
+ sqlite3 *db, /* Apply change to "main" db of this handle */
+ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
+ void *pIn, /* First arg for xInput */
+ int(*xFilter)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ const char *zTab /* Table name */
+ ),
+ int(*xConflict)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
+ ),
+ void *pCtx /* First argument passed to xConflict */
+){
+ return sqlite3changeset_apply_v2_strm(
+ db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0
+ );
+}
+
+/*
+** sqlite3_changegroup handle.
+*/
+struct sqlite3_changegroup {
+ int rc; /* Error code */
+ int bPatch; /* True to accumulate patchsets */
+ SessionTable *pList; /* List of tables in current patch */
+};
+
+/*
+** This function is called to merge two changes to the same row together as
+** part of an sqlite3changeset_concat() operation. A new change object is
+** allocated and a pointer to it stored in *ppNew.
+*/
+static int sessionChangeMerge(
+ SessionTable *pTab, /* Table structure */
+ int bRebase, /* True for a rebase hash-table */
+ int bPatchset, /* True for patchsets */
+ SessionChange *pExist, /* Existing change */
+ int op2, /* Second change operation */
+ int bIndirect, /* True if second change is indirect */
+ u8 *aRec, /* Second change record */
+ int nRec, /* Number of bytes in aRec */
+ SessionChange **ppNew /* OUT: Merged change */
+){
+ SessionChange *pNew = 0;
+ int rc = SQLITE_OK;
+
+ if( !pExist ){
+ pNew = (SessionChange *)sqlite3_malloc64(sizeof(SessionChange) + nRec);
+ if( !pNew ){
+ return SQLITE_NOMEM;
+ }
+ memset(pNew, 0, sizeof(SessionChange));
+ pNew->op = op2;
+ pNew->bIndirect = bIndirect;
+ pNew->aRecord = (u8*)&pNew[1];
+ if( bIndirect==0 || bRebase==0 ){
+ pNew->nRecord = nRec;
+ memcpy(pNew->aRecord, aRec, nRec);
+ }else{
+ int i;
+ u8 *pIn = aRec;
+ u8 *pOut = pNew->aRecord;
+ for(i=0; i<pTab->nCol; i++){
+ int nIn = sessionSerialLen(pIn);
+ if( *pIn==0 ){
+ *pOut++ = 0;
+ }else if( pTab->abPK[i]==0 ){
+ *pOut++ = 0xFF;
+ }else{
+ memcpy(pOut, pIn, nIn);
+ pOut += nIn;
+ }
+ pIn += nIn;
+ }
+ pNew->nRecord = pOut - pNew->aRecord;
+ }
+ }else if( bRebase ){
+ if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){
+ *ppNew = pExist;
+ }else{
+ sqlite3_int64 nByte = nRec + pExist->nRecord + sizeof(SessionChange);
+ pNew = (SessionChange*)sqlite3_malloc64(nByte);
+ if( pNew==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ int i;
+ u8 *a1 = pExist->aRecord;
+ u8 *a2 = aRec;
+ u8 *pOut;
+
+ memset(pNew, 0, nByte);
+ pNew->bIndirect = bIndirect || pExist->bIndirect;
+ pNew->op = op2;
+ pOut = pNew->aRecord = (u8*)&pNew[1];
+
+ for(i=0; i<pTab->nCol; i++){
+ int n1 = sessionSerialLen(a1);
+ int n2 = sessionSerialLen(a2);
+ if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){
+ *pOut++ = 0xFF;
+ }else if( *a2==0 ){
+ memcpy(pOut, a1, n1);
+ pOut += n1;
+ }else{
+ memcpy(pOut, a2, n2);
+ pOut += n2;
+ }
+ a1 += n1;
+ a2 += n2;
+ }
+ pNew->nRecord = pOut - pNew->aRecord;
+ }
+ sqlite3_free(pExist);
+ }
+ }else{
+ int op1 = pExist->op;
+
+ /*
+ ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
+ ** op1=INSERT, op2=UPDATE -> INSERT.
+ ** op1=INSERT, op2=DELETE -> (none)
+ **
+ ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
+ ** op1=UPDATE, op2=UPDATE -> UPDATE.
+ ** op1=UPDATE, op2=DELETE -> DELETE.
+ **
+ ** op1=DELETE, op2=INSERT -> UPDATE.
+ ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
+ ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
+ */
+ if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
+ || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
+ || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
+ || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
+ ){
+ pNew = pExist;
+ }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
+ sqlite3_free(pExist);
+ assert( pNew==0 );
+ }else{
+ u8 *aExist = pExist->aRecord;
+ sqlite3_int64 nByte;
+ u8 *aCsr;
+
+ /* Allocate a new SessionChange object. Ensure that the aRecord[]
+ ** buffer of the new object is large enough to hold any record that
+ ** may be generated by combining the input records. */
+ nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
+ pNew = (SessionChange *)sqlite3_malloc64(nByte);
+ if( !pNew ){
+ sqlite3_free(pExist);
+ return SQLITE_NOMEM;
+ }
+ memset(pNew, 0, sizeof(SessionChange));
+ pNew->bIndirect = (bIndirect && pExist->bIndirect);
+ aCsr = pNew->aRecord = (u8 *)&pNew[1];
+
+ if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
+ u8 *a1 = aRec;
+ assert( op2==SQLITE_UPDATE );
+ pNew->op = SQLITE_INSERT;
+ if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
+ sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
+ }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
+ assert( op2==SQLITE_INSERT );
+ pNew->op = SQLITE_UPDATE;
+ if( bPatchset ){
+ memcpy(aCsr, aRec, nRec);
+ aCsr += nRec;
+ }else{
+ if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
+ sqlite3_free(pNew);
+ pNew = 0;
+ }
+ }
+ }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
+ u8 *a1 = aExist;
+ u8 *a2 = aRec;
+ assert( op1==SQLITE_UPDATE );
+ if( bPatchset==0 ){
+ sessionSkipRecord(&a1, pTab->nCol);
+ sessionSkipRecord(&a2, pTab->nCol);
+ }
+ pNew->op = SQLITE_UPDATE;
+ if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
+ sqlite3_free(pNew);
+ pNew = 0;
+ }
+ }else{ /* UPDATE + DELETE */
+ assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
+ pNew->op = SQLITE_DELETE;
+ if( bPatchset ){
+ memcpy(aCsr, aRec, nRec);
+ aCsr += nRec;
+ }else{
+ sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
+ }
+ }
+
+ if( pNew ){
+ pNew->nRecord = (int)(aCsr - pNew->aRecord);
+ }
+ sqlite3_free(pExist);
+ }
+ }
+
+ *ppNew = pNew;
+ return rc;
+}
+
+/*
+** Add all changes in the changeset traversed by the iterator passed as
+** the first argument to the changegroup hash tables.
+*/
+static int sessionChangesetToHash(
+ sqlite3_changeset_iter *pIter, /* Iterator to read from */
+ sqlite3_changegroup *pGrp, /* Changegroup object to add changeset to */
+ int bRebase /* True if hash table is for rebasing */
+){
+ u8 *aRec;
+ int nRec;
+ int rc = SQLITE_OK;
+ SessionTable *pTab = 0;
+
+ while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, 0) ){
+ const char *zNew;
+ int nCol;
+ int op;
+ int iHash;
+ int bIndirect;
+ SessionChange *pChange;
+ SessionChange *pExist = 0;
+ SessionChange **pp;
+
+ if( pGrp->pList==0 ){
+ pGrp->bPatch = pIter->bPatchset;
+ }else if( pIter->bPatchset!=pGrp->bPatch ){
+ rc = SQLITE_ERROR;
+ break;
+ }
+
+ sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
+ if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
+ /* Search the list for a matching table */
+ int nNew = (int)strlen(zNew);
+ u8 *abPK;
+
+ sqlite3changeset_pk(pIter, &abPK, 0);
+ for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
+ if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
+ }
+ if( !pTab ){
+ SessionTable **ppTab;
+
+ pTab = sqlite3_malloc64(sizeof(SessionTable) + nCol + nNew+1);
+ if( !pTab ){
+ rc = SQLITE_NOMEM;
+ break;
+ }
+ memset(pTab, 0, sizeof(SessionTable));
+ pTab->nCol = nCol;
+ pTab->abPK = (u8*)&pTab[1];
+ memcpy(pTab->abPK, abPK, nCol);
+ pTab->zName = (char*)&pTab->abPK[nCol];
+ memcpy(pTab->zName, zNew, nNew+1);
+
+ /* The new object must be linked on to the end of the list, not
+ ** simply added to the start of it. This is to ensure that the
+ ** tables within the output of sqlite3changegroup_output() are in
+ ** the right order. */
+ for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
+ *ppTab = pTab;
+ }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
+ rc = SQLITE_SCHEMA;
+ break;
+ }
+ }
+
+ if( sessionGrowHash(pIter->bPatchset, pTab) ){
+ rc = SQLITE_NOMEM;
+ break;
+ }
+ iHash = sessionChangeHash(
+ pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
+ );
+
+ /* Search for existing entry. If found, remove it from the hash table.
+ ** Code below may link it back in.
+ */
+ for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
+ int bPkOnly1 = 0;
+ int bPkOnly2 = 0;
+ if( pIter->bPatchset ){
+ bPkOnly1 = (*pp)->op==SQLITE_DELETE;
+ bPkOnly2 = op==SQLITE_DELETE;
+ }
+ if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
+ pExist = *pp;
+ *pp = (*pp)->pNext;
+ pTab->nEntry--;
+ break;
+ }
+ }
+
+ rc = sessionChangeMerge(pTab, bRebase,
+ pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
+ );
+ if( rc ) break;
+ if( pChange ){
+ pChange->pNext = pTab->apChange[iHash];
+ pTab->apChange[iHash] = pChange;
+ pTab->nEntry++;
+ }
+ }
+
+ if( rc==SQLITE_OK ) rc = pIter->rc;
+ return rc;
+}
+
+/*
+** Serialize a changeset (or patchset) based on all changesets (or patchsets)
+** added to the changegroup object passed as the first argument.
+**
+** If xOutput is not NULL, then the changeset/patchset is returned to the
+** user via one or more calls to xOutput, as with the other streaming
+** interfaces.
+**
+** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
+** buffer containing the output changeset before this function returns. In
+** this case (*pnOut) is set to the size of the output buffer in bytes. It
+** is the responsibility of the caller to free the output buffer using
+** sqlite3_free() when it is no longer required.
+**
+** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
+** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
+** are both set to 0 before returning.
+*/
+static int sessionChangegroupOutput(
+ sqlite3_changegroup *pGrp,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut,
+ int *pnOut,
+ void **ppOut
+){
+ int rc = SQLITE_OK;
+ SessionBuffer buf = {0, 0, 0};
+ SessionTable *pTab;
+ assert( xOutput==0 || (ppOut==0 && pnOut==0) );
+
+ /* Create the serialized output changeset based on the contents of the
+ ** hash tables attached to the SessionTable objects in list p->pList.
+ */
+ for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
+ int i;
+ if( pTab->nEntry==0 ) continue;
+
+ sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
+ for(i=0; i<pTab->nChange; i++){
+ SessionChange *p;
+ for(p=pTab->apChange[i]; p; p=p->pNext){
+ sessionAppendByte(&buf, p->op, &rc);
+ sessionAppendByte(&buf, p->bIndirect, &rc);
+ sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
+ if( rc==SQLITE_OK && xOutput && buf.nBuf>=sessions_strm_chunk_size ){
+ rc = xOutput(pOut, buf.aBuf, buf.nBuf);
+ buf.nBuf = 0;
+ }
+ }
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ if( xOutput ){
+ if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
+ }else{
+ *ppOut = buf.aBuf;
+ *pnOut = buf.nBuf;
+ buf.aBuf = 0;
+ }
+ }
+ sqlite3_free(buf.aBuf);
+
+ return rc;
+}
+
+/*
+** Allocate a new, empty, sqlite3_changegroup.
+*/
+SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
+ int rc = SQLITE_OK; /* Return code */
+ sqlite3_changegroup *p; /* New object */
+ p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
+ if( p==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memset(p, 0, sizeof(sqlite3_changegroup));
+ }
+ *pp = p;
+ return rc;
+}
+
+/*
+** Add the changeset currently stored in buffer pData, size nData bytes,
+** to changeset-group p.
+*/
+SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
+ sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
+ int rc; /* Return code */
+
+ rc = sqlite3changeset_start(&pIter, nData, pData);
+ if( rc==SQLITE_OK ){
+ rc = sessionChangesetToHash(pIter, pGrp, 0);
+ }
+ sqlite3changeset_finalize(pIter);
+ return rc;
+}
+
+/*
+** Obtain a buffer containing a changeset representing the concatenation
+** of all changesets added to the group so far.
+*/
+SQLITE_API int sqlite3changegroup_output(
+ sqlite3_changegroup *pGrp,
+ int *pnData,
+ void **ppData
+){
+ return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
+}
+
+/*
+** Streaming versions of changegroup_add().
+*/
+SQLITE_API int sqlite3changegroup_add_strm(
+ sqlite3_changegroup *pGrp,
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn
+){
+ sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
+ int rc; /* Return code */
+
+ rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
+ if( rc==SQLITE_OK ){
+ rc = sessionChangesetToHash(pIter, pGrp, 0);
+ }
+ sqlite3changeset_finalize(pIter);
+ return rc;
+}
+
+/*
+** Streaming versions of changegroup_output().
+*/
+SQLITE_API int sqlite3changegroup_output_strm(
+ sqlite3_changegroup *pGrp,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+){
+ return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
+}
+
+/*
+** Delete a changegroup object.
+*/
+SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
+ if( pGrp ){
+ sessionDeleteTable(pGrp->pList);
+ sqlite3_free(pGrp);
+ }
+}
+
+/*
+** Combine two changesets together.
+*/
+SQLITE_API int sqlite3changeset_concat(
+ int nLeft, /* Number of bytes in lhs input */
+ void *pLeft, /* Lhs input changeset */
+ int nRight /* Number of bytes in rhs input */,
+ void *pRight, /* Rhs input changeset */
+ int *pnOut, /* OUT: Number of bytes in output changeset */
+ void **ppOut /* OUT: changeset (left <concat> right) */
+){
+ sqlite3_changegroup *pGrp;
+ int rc;
+
+ rc = sqlite3changegroup_new(&pGrp);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3changegroup_add(pGrp, nRight, pRight);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
+ }
+ sqlite3changegroup_delete(pGrp);
+
+ return rc;
+}
+
+/*
+** Streaming version of sqlite3changeset_concat().
+*/
+SQLITE_API int sqlite3changeset_concat_strm(
+ int (*xInputA)(void *pIn, void *pData, int *pnData),
+ void *pInA,
+ int (*xInputB)(void *pIn, void *pData, int *pnData),
+ void *pInB,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+){
+ sqlite3_changegroup *pGrp;
+ int rc;
+
+ rc = sqlite3changegroup_new(&pGrp);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
+ }
+ sqlite3changegroup_delete(pGrp);
+
+ return rc;
+}
+
+/*
+** Changeset rebaser handle.
+*/
+struct sqlite3_rebaser {
+ sqlite3_changegroup grp; /* Hash table */
+};
+
+/*
+** Buffers a1 and a2 must both contain a sessions module record nCol
+** fields in size. This function appends an nCol sessions module
+** record to buffer pBuf that is a copy of a1, except that for
+** each field that is undefined in a1[], swap in the field from a2[].
+*/
+static void sessionAppendRecordMerge(
+ SessionBuffer *pBuf, /* Buffer to append to */
+ int nCol, /* Number of columns in each record */
+ u8 *a1, int n1, /* Record 1 */
+ u8 *a2, int n2, /* Record 2 */
+ int *pRc /* IN/OUT: error code */
+){
+ sessionBufferGrow(pBuf, n1+n2, pRc);
+ if( *pRc==SQLITE_OK ){
+ int i;
+ u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
+ for(i=0; i<nCol; i++){
+ int nn1 = sessionSerialLen(a1);
+ int nn2 = sessionSerialLen(a2);
+ if( *a1==0 || *a1==0xFF ){
+ memcpy(pOut, a2, nn2);
+ pOut += nn2;
+ }else{
+ memcpy(pOut, a1, nn1);
+ pOut += nn1;
+ }
+ a1 += nn1;
+ a2 += nn2;
+ }
+
+ pBuf->nBuf = pOut-pBuf->aBuf;
+ assert( pBuf->nBuf<=pBuf->nAlloc );
+ }
+}
+
+/*
+** This function is called when rebasing a local UPDATE change against one
+** or more remote UPDATE changes. The aRec/nRec buffer contains the current
+** old.* and new.* records for the change. The rebase buffer (a single
+** record) is in aChange/nChange. The rebased change is appended to buffer
+** pBuf.
+**
+** Rebasing the UPDATE involves:
+**
+** * Removing any changes to fields for which the corresponding field
+** in the rebase buffer is set to "replaced" (type 0xFF). If this
+** means the UPDATE change updates no fields, nothing is appended
+** to the output buffer.
+**
+** * For each field modified by the local change for which the
+** corresponding field in the rebase buffer is not "undefined" (0x00)
+** or "replaced" (0xFF), the old.* value is replaced by the value
+** in the rebase buffer.
+*/
+static void sessionAppendPartialUpdate(
+ SessionBuffer *pBuf, /* Append record here */
+ sqlite3_changeset_iter *pIter, /* Iterator pointed at local change */
+ u8 *aRec, int nRec, /* Local change */
+ u8 *aChange, int nChange, /* Record to rebase against */
+ int *pRc /* IN/OUT: Return Code */
+){
+ sessionBufferGrow(pBuf, 2+nRec+nChange, pRc);
+ if( *pRc==SQLITE_OK ){
+ int bData = 0;
+ u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
+ int i;
+ u8 *a1 = aRec;
+ u8 *a2 = aChange;
+
+ *pOut++ = SQLITE_UPDATE;
+ *pOut++ = pIter->bIndirect;
+ for(i=0; i<pIter->nCol; i++){
+ int n1 = sessionSerialLen(a1);
+ int n2 = sessionSerialLen(a2);
+ if( pIter->abPK[i] || a2[0]==0 ){
+ if( !pIter->abPK[i] ) bData = 1;
+ memcpy(pOut, a1, n1);
+ pOut += n1;
+ }else if( a2[0]!=0xFF ){
+ bData = 1;
+ memcpy(pOut, a2, n2);
+ pOut += n2;
+ }else{
+ *pOut++ = '\0';
+ }
+ a1 += n1;
+ a2 += n2;
+ }
+ if( bData ){
+ a2 = aChange;
+ for(i=0; i<pIter->nCol; i++){
+ int n1 = sessionSerialLen(a1);
+ int n2 = sessionSerialLen(a2);
+ if( pIter->abPK[i] || a2[0]!=0xFF ){
+ memcpy(pOut, a1, n1);
+ pOut += n1;
+ }else{
+ *pOut++ = '\0';
+ }
+ a1 += n1;
+ a2 += n2;
+ }
+ pBuf->nBuf = (pOut - pBuf->aBuf);
+ }
+ }
+}
+
+/*
+** pIter is configured to iterate through a changeset. This function rebases
+** that changeset according to the current configuration of the rebaser
+** object passed as the first argument. If no error occurs and argument xOutput
+** is not NULL, then the changeset is returned to the caller by invoking
+** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL,
+** then (*ppOut) is set to point to a buffer containing the rebased changeset
+** before this function returns. In this case (*pnOut) is set to the size of
+** the buffer in bytes. It is the responsibility of the caller to eventually
+** free the (*ppOut) buffer using sqlite3_free().
+**
+** If an error occurs, an SQLite error code is returned. If ppOut and
+** pnOut are not NULL, then the two output parameters are set to 0 before
+** returning.
+*/
+static int sessionRebase(
+ sqlite3_rebaser *p, /* Rebaser hash table */
+ sqlite3_changeset_iter *pIter, /* Input data */
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut, /* Context for xOutput callback */
+ int *pnOut, /* OUT: Number of bytes in output changeset */
+ void **ppOut /* OUT: Inverse of pChangeset */
+){
+ int rc = SQLITE_OK;
+ u8 *aRec = 0;
+ int nRec = 0;
+ int bNew = 0;
+ SessionTable *pTab = 0;
+ SessionBuffer sOut = {0,0,0};
+
+ while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){
+ SessionChange *pChange = 0;
+ int bDone = 0;
+
+ if( bNew ){
+ const char *zTab = pIter->zTab;
+ for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){
+ if( 0==sqlite3_stricmp(pTab->zName, zTab) ) break;
+ }
+ bNew = 0;
+
+ /* A patchset may not be rebased */
+ if( pIter->bPatchset ){
+ rc = SQLITE_ERROR;
+ }
+
+ /* Append a table header to the output for this new table */
+ sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc);
+ sessionAppendVarint(&sOut, pIter->nCol, &rc);
+ sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc);
+ sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc);
+ }
+
+ if( pTab && rc==SQLITE_OK ){
+ int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange);
+
+ for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){
+ if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){
+ break;
+ }
+ }
+ }
+
+ if( pChange ){
+ assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT );
+ switch( pIter->op ){
+ case SQLITE_INSERT:
+ if( pChange->op==SQLITE_INSERT ){
+ bDone = 1;
+ if( pChange->bIndirect==0 ){
+ sessionAppendByte(&sOut, SQLITE_UPDATE, &rc);
+ sessionAppendByte(&sOut, pIter->bIndirect, &rc);
+ sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc);
+ sessionAppendBlob(&sOut, aRec, nRec, &rc);
+ }
+ }
+ break;
+
+ case SQLITE_UPDATE:
+ bDone = 1;
+ if( pChange->op==SQLITE_DELETE ){
+ if( pChange->bIndirect==0 ){
+ u8 *pCsr = aRec;
+ sessionSkipRecord(&pCsr, pIter->nCol);
+ sessionAppendByte(&sOut, SQLITE_INSERT, &rc);
+ sessionAppendByte(&sOut, pIter->bIndirect, &rc);
+ sessionAppendRecordMerge(&sOut, pIter->nCol,
+ pCsr, nRec-(pCsr-aRec),
+ pChange->aRecord, pChange->nRecord, &rc
+ );
+ }
+ }else{
+ sessionAppendPartialUpdate(&sOut, pIter,
+ aRec, nRec, pChange->aRecord, pChange->nRecord, &rc
+ );
+ }
+ break;
+
+ default:
+ assert( pIter->op==SQLITE_DELETE );
+ bDone = 1;
+ if( pChange->op==SQLITE_INSERT ){
+ sessionAppendByte(&sOut, SQLITE_DELETE, &rc);
+ sessionAppendByte(&sOut, pIter->bIndirect, &rc);
+ sessionAppendRecordMerge(&sOut, pIter->nCol,
+ pChange->aRecord, pChange->nRecord, aRec, nRec, &rc
+ );
+ }
+ break;
+ }
+ }
+
+ if( bDone==0 ){
+ sessionAppendByte(&sOut, pIter->op, &rc);
+ sessionAppendByte(&sOut, pIter->bIndirect, &rc);
+ sessionAppendBlob(&sOut, aRec, nRec, &rc);
+ }
+ if( rc==SQLITE_OK && xOutput && sOut.nBuf>sessions_strm_chunk_size ){
+ rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
+ sOut.nBuf = 0;
+ }
+ if( rc ) break;
+ }
+
+ if( rc!=SQLITE_OK ){
+ sqlite3_free(sOut.aBuf);
+ memset(&sOut, 0, sizeof(sOut));
+ }
+
+ if( rc==SQLITE_OK ){
+ if( xOutput ){
+ if( sOut.nBuf>0 ){
+ rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
+ }
+ }else{
+ *ppOut = (void*)sOut.aBuf;
+ *pnOut = sOut.nBuf;
+ sOut.aBuf = 0;
+ }
+ }
+ sqlite3_free(sOut.aBuf);
+ return rc;
+}
+
+/*
+** Create a new rebaser object.
+*/
+SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew){
+ int rc = SQLITE_OK;
+ sqlite3_rebaser *pNew;
+
+ pNew = sqlite3_malloc(sizeof(sqlite3_rebaser));
+ if( pNew==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memset(pNew, 0, sizeof(sqlite3_rebaser));
+ }
+ *ppNew = pNew;
+ return rc;
+}
+
+/*
+** Call this one or more times to configure a rebaser.
+*/
+SQLITE_API int sqlite3rebaser_configure(
+ sqlite3_rebaser *p,
+ int nRebase, const void *pRebase
+){
+ sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */
+ int rc; /* Return code */
+ rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);
+ if( rc==SQLITE_OK ){
+ rc = sessionChangesetToHash(pIter, &p->grp, 1);
+ }
+ sqlite3changeset_finalize(pIter);
+ return rc;
+}
+
+/*
+** Rebase a changeset according to current rebaser configuration
+*/
+SQLITE_API int sqlite3rebaser_rebase(
+ sqlite3_rebaser *p,
+ int nIn, const void *pIn,
+ int *pnOut, void **ppOut
+){
+ sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
+ int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn);
+
+ if( rc==SQLITE_OK ){
+ rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut);
+ sqlite3changeset_finalize(pIter);
+ }
+
+ return rc;
+}
+
+/*
+** Rebase a changeset according to current rebaser configuration
+*/
+SQLITE_API int sqlite3rebaser_rebase_strm(
+ sqlite3_rebaser *p,
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+){
+ sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
+ int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
+
+ if( rc==SQLITE_OK ){
+ rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0);
+ sqlite3changeset_finalize(pIter);
+ }
+
+ return rc;
+}
+
+/*
+** Destroy a rebaser object
+*/
+SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p){
+ if( p ){
+ sessionDeleteTable(p->grp.pList);
+ sqlite3_free(p);
+ }
+}
+
+/*
+** Global configuration
+*/
+SQLITE_API int sqlite3session_config(int op, void *pArg){
+ int rc = SQLITE_OK;
+ switch( op ){
+ case SQLITE_SESSION_CONFIG_STRMSIZE: {
+ int *pInt = (int*)pArg;
+ if( *pInt>0 ){
+ sessions_strm_chunk_size = *pInt;
+ }
+ *pInt = sessions_strm_chunk_size;
+ break;
+ }
+ default:
+ rc = SQLITE_MISUSE;
+ break;
+ }
+ return rc;
+}
+
+#endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
+
+/************** End of sqlite3session.c **************************************/
+/************** Begin file fts5.c ********************************************/
+
+
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
+
+#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
+# define NDEBUG 1
+#endif
+#if defined(NDEBUG) && defined(SQLITE_DEBUG)
+# undef NDEBUG
+#endif
+
+/*
+** 2014 May 31
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** Interfaces to extend FTS5. Using the interfaces defined in this file,
+** FTS5 may be extended with:
+**
+** * custom tokenizers, and
+** * custom auxiliary functions.
+*/
+
+
+#ifndef _FTS5_H
+#define _FTS5_H
+
+/* #include "sqlite3.h" */
+
+#if 0
+extern "C" {
+#endif
+
+/*************************************************************************
+** CUSTOM AUXILIARY FUNCTIONS
+**
+** Virtual table implementations may overload SQL functions by implementing
+** the sqlite3_module.xFindFunction() method.
+*/
+
+typedef struct Fts5ExtensionApi Fts5ExtensionApi;
+typedef struct Fts5Context Fts5Context;
+typedef struct Fts5PhraseIter Fts5PhraseIter;
+
+typedef void (*fts5_extension_function)(
+ const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
+ Fts5Context *pFts, /* First arg to pass to pApi functions */
+ sqlite3_context *pCtx, /* Context for returning result/error */
+ int nVal, /* Number of values in apVal[] array */
+ sqlite3_value **apVal /* Array of trailing arguments */
+);
+
+struct Fts5PhraseIter {
+ const unsigned char *a;
+ const unsigned char *b;
+};
+
+/*
+** EXTENSION API FUNCTIONS
+**
+** xUserData(pFts):
+** Return a copy of the context pointer the extension function was
+** registered with.
+**
+** xColumnTotalSize(pFts, iCol, pnToken):
+** If parameter iCol is less than zero, set output variable *pnToken
+** to the total number of tokens in the FTS5 table. Or, if iCol is
+** non-negative but less than the number of columns in the table, return
+** the total number of tokens in column iCol, considering all rows in
+** the FTS5 table.
+**
+** If parameter iCol is greater than or equal to the number of columns
+** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
+** an OOM condition or IO error), an appropriate SQLite error code is
+** returned.
+**
+** xColumnCount(pFts):
+** Return the number of columns in the table.
+**
+** xColumnSize(pFts, iCol, pnToken):
+** If parameter iCol is less than zero, set output variable *pnToken
+** to the total number of tokens in the current row. Or, if iCol is
+** non-negative but less than the number of columns in the table, set
+** *pnToken to the number of tokens in column iCol of the current row.
+**
+** If parameter iCol is greater than or equal to the number of columns
+** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
+** an OOM condition or IO error), an appropriate SQLite error code is
+** returned.
+**
+** This function may be quite inefficient if used with an FTS5 table
+** created with the "columnsize=0" option.
+**
+** xColumnText:
+** This function attempts to retrieve the text of column iCol of the
+** current document. If successful, (*pz) is set to point to a buffer
+** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
+** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
+** if an error occurs, an SQLite error code is returned and the final values
+** of (*pz) and (*pn) are undefined.
+**
+** xPhraseCount:
+** Returns the number of phrases in the current query expression.
+**
+** xPhraseSize:
+** Returns the number of tokens in phrase iPhrase of the query. Phrases
+** are numbered starting from zero.
+**
+** xInstCount:
+** Set *pnInst to the total number of occurrences of all phrases within
+** the query within the current row. Return SQLITE_OK if successful, or
+** an error code (i.e. SQLITE_NOMEM) if an error occurs.
+**
+** This API can be quite slow if used with an FTS5 table created with the
+** "detail=none" or "detail=column" option. If the FTS5 table is created
+** with either "detail=none" or "detail=column" and "content=" option
+** (i.e. if it is a contentless table), then this API always returns 0.
+**
+** xInst:
+** Query for the details of phrase match iIdx within the current row.
+** Phrase matches are numbered starting from zero, so the iIdx argument
+** should be greater than or equal to zero and smaller than the value
+** output by xInstCount().
+**
+** Usually, output parameter *piPhrase is set to the phrase number, *piCol
+** to the column in which it occurs and *piOff the token offset of the
+** first token of the phrase. Returns SQLITE_OK if successful, or an error
+** code (i.e. SQLITE_NOMEM) if an error occurs.
+**
+** This API can be quite slow if used with an FTS5 table created with the
+** "detail=none" or "detail=column" option.
+**
+** xRowid:
+** Returns the rowid of the current row.
+**
+** xTokenize:
+** Tokenize text using the tokenizer belonging to the FTS5 table.
+**
+** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
+** This API function is used to query the FTS table for phrase iPhrase
+** of the current query. Specifically, a query equivalent to:
+**
+** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
+**
+** with $p set to a phrase equivalent to the phrase iPhrase of the
+** current query is executed. Any column filter that applies to
+** phrase iPhrase of the current query is included in $p. For each
+** row visited, the callback function passed as the fourth argument
+** is invoked. The context and API objects passed to the callback
+** function may be used to access the properties of each matched row.
+** Invoking Api.xUserData() returns a copy of the pointer passed as
+** the third argument to pUserData.
+**
+** If the callback function returns any value other than SQLITE_OK, the
+** query is abandoned and the xQueryPhrase function returns immediately.
+** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
+** Otherwise, the error code is propagated upwards.
+**
+** If the query runs to completion without incident, SQLITE_OK is returned.
+** Or, if some error occurs before the query completes or is aborted by
+** the callback, an SQLite error code is returned.
+**
+**
+** xSetAuxdata(pFts5, pAux, xDelete)
+**
+** Save the pointer passed as the second argument as the extension function's
+** "auxiliary data". The pointer may then be retrieved by the current or any
+** future invocation of the same fts5 extension function made as part of
+** the same MATCH query using the xGetAuxdata() API.
+**
+** Each extension function is allocated a single auxiliary data slot for
+** each FTS query (MATCH expression). If the extension function is invoked
+** more than once for a single FTS query, then all invocations share a
+** single auxiliary data context.
+**
+** If there is already an auxiliary data pointer when this function is
+** invoked, then it is replaced by the new pointer. If an xDelete callback
+** was specified along with the original pointer, it is invoked at this
+** point.
+**
+** The xDelete callback, if one is specified, is also invoked on the
+** auxiliary data pointer after the FTS5 query has finished.
+**
+** If an error (e.g. an OOM condition) occurs within this function,
+** the auxiliary data is set to NULL and an error code returned. If the
+** xDelete parameter was not NULL, it is invoked on the auxiliary data
+** pointer before returning.
+**
+**
+** xGetAuxdata(pFts5, bClear)
+**
+** Returns the current auxiliary data pointer for the fts5 extension
+** function. See the xSetAuxdata() method for details.
+**
+** If the bClear argument is non-zero, then the auxiliary data is cleared
+** (set to NULL) before this function returns. In this case the xDelete,
+** if any, is not invoked.
+**
+**
+** xRowCount(pFts5, pnRow)
+**
+** This function is used to retrieve the total number of rows in the table.
+** In other words, the same value that would be returned by:
+**
+** SELECT count(*) FROM ftstable;
+**
+** xPhraseFirst()
+** This function is used, along with type Fts5PhraseIter and the xPhraseNext
+** method, to iterate through all instances of a single query phrase within
+** the current row. This is the same information as is accessible via the
+** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
+** to use, this API may be faster under some circumstances. To iterate
+** through instances of phrase iPhrase, use the following code:
+**
+** Fts5PhraseIter iter;
+** int iCol, iOff;
+** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
+** iCol>=0;
+** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
+** ){
+** // An instance of phrase iPhrase at offset iOff of column iCol
+** }
+**
+** The Fts5PhraseIter structure is defined above. Applications should not
+** modify this structure directly - it should only be used as shown above
+** with the xPhraseFirst() and xPhraseNext() API methods (and by
+** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
+**
+** This API can be quite slow if used with an FTS5 table created with the
+** "detail=none" or "detail=column" option. If the FTS5 table is created
+** with either "detail=none" or "detail=column" and "content=" option
+** (i.e. if it is a contentless table), then this API always iterates
+** through an empty set (all calls to xPhraseFirst() set iCol to -1).
+**
+** xPhraseNext()
+** See xPhraseFirst above.
+**
+** xPhraseFirstColumn()
+** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
+** and xPhraseNext() APIs described above. The difference is that instead
+** of iterating through all instances of a phrase in the current row, these
+** APIs are used to iterate through the set of columns in the current row
+** that contain one or more instances of a specified phrase. For example:
+**
+** Fts5PhraseIter iter;
+** int iCol;
+** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
+** iCol>=0;
+** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
+** ){
+** // Column iCol contains at least one instance of phrase iPhrase
+** }
+**
+** This API can be quite slow if used with an FTS5 table created with the
+** "detail=none" option. If the FTS5 table is created with either
+** "detail=none" "content=" option (i.e. if it is a contentless table),
+** then this API always iterates through an empty set (all calls to
+** xPhraseFirstColumn() set iCol to -1).
+**
+** The information accessed using this API and its companion
+** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
+** (or xInst/xInstCount). The chief advantage of this API is that it is
+** significantly more efficient than those alternatives when used with
+** "detail=column" tables.
+**
+** xPhraseNextColumn()
+** See xPhraseFirstColumn above.
+*/
+struct Fts5ExtensionApi {
+ int iVersion; /* Currently always set to 3 */
+
+ void *(*xUserData)(Fts5Context*);
+
+ int (*xColumnCount)(Fts5Context*);
+ int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
+ int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
+
+ int (*xTokenize)(Fts5Context*,
+ const char *pText, int nText, /* Text to tokenize */
+ void *pCtx, /* Context passed to xToken() */
+ int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
+ );
+
+ int (*xPhraseCount)(Fts5Context*);
+ int (*xPhraseSize)(Fts5Context*, int iPhrase);
+
+ int (*xInstCount)(Fts5Context*, int *pnInst);
+ int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
+
+ sqlite3_int64 (*xRowid)(Fts5Context*);
+ int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
+ int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
+
+ int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
+ int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
+ );
+ int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
+ void *(*xGetAuxdata)(Fts5Context*, int bClear);
+
+ int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
+ void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
+
+ int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
+ void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
+};
+
+/*
+** CUSTOM AUXILIARY FUNCTIONS
+*************************************************************************/
+
+/*************************************************************************
+** CUSTOM TOKENIZERS
+**
+** Applications may also register custom tokenizer types. A tokenizer
+** is registered by providing fts5 with a populated instance of the
+** following structure. All structure methods must be defined, setting
+** any member of the fts5_tokenizer struct to NULL leads to undefined
+** behaviour. The structure methods are expected to function as follows:
+**
+** xCreate:
+** This function is used to allocate and initialize a tokenizer instance.
+** A tokenizer instance is required to actually tokenize text.
+**
+** The first argument passed to this function is a copy of the (void*)
+** pointer provided by the application when the fts5_tokenizer object
+** was registered with FTS5 (the third argument to xCreateTokenizer()).
+** The second and third arguments are an array of nul-terminated strings
+** containing the tokenizer arguments, if any, specified following the
+** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
+** to create the FTS5 table.
+**
+** The final argument is an output variable. If successful, (*ppOut)
+** should be set to point to the new tokenizer handle and SQLITE_OK
+** returned. If an error occurs, some value other than SQLITE_OK should
+** be returned. In this case, fts5 assumes that the final value of *ppOut
+** is undefined.
+**
+** xDelete:
+** This function is invoked to delete a tokenizer handle previously
+** allocated using xCreate(). Fts5 guarantees that this function will
+** be invoked exactly once for each successful call to xCreate().
+**
+** xTokenize:
+** This function is expected to tokenize the nText byte string indicated
+** by argument pText. pText may or may not be nul-terminated. The first
+** argument passed to this function is a pointer to an Fts5Tokenizer object
+** returned by an earlier call to xCreate().
+**
+** The second argument indicates the reason that FTS5 is requesting
+** tokenization of the supplied text. This is always one of the following
+** four values:
+**
+** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
+** or removed from the FTS table. The tokenizer is being invoked to
+** determine the set of tokens to add to (or delete from) the
+** FTS index.
+**
+** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
+** against the FTS index. The tokenizer is being called to tokenize
+** a bareword or quoted string specified as part of the query.
+**
+** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
+** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
+** followed by a "*" character, indicating that the last token
+** returned by the tokenizer will be treated as a token prefix.
+**
+** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
+** satisfy an fts5_api.xTokenize() request made by an auxiliary
+** function. Or an fts5_api.xColumnSize() request made by the same
+** on a columnsize=0 database.
+** </ul>
+**
+** For each token in the input string, the supplied callback xToken() must
+** be invoked. The first argument to it should be a copy of the pointer
+** passed as the second argument to xTokenize(). The third and fourth
+** arguments are a pointer to a buffer containing the token text, and the
+** size of the token in bytes. The 4th and 5th arguments are the byte offsets
+** of the first byte of and first byte immediately following the text from
+** which the token is derived within the input.
+**
+** The second argument passed to the xToken() callback ("tflags") should
+** normally be set to 0. The exception is if the tokenizer supports
+** synonyms. In this case see the discussion below for details.
+**
+** FTS5 assumes the xToken() callback is invoked for each token in the
+** order that they occur within the input text.
+**
+** If an xToken() callback returns any value other than SQLITE_OK, then
+** the tokenization should be abandoned and the xTokenize() method should
+** immediately return a copy of the xToken() return value. Or, if the
+** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
+** if an error occurs with the xTokenize() implementation itself, it
+** may abandon the tokenization and return any error code other than
+** SQLITE_OK or SQLITE_DONE.
+**
+** SYNONYM SUPPORT
+**
+** Custom tokenizers may also support synonyms. Consider a case in which a
+** user wishes to query for a phrase such as "first place". Using the
+** built-in tokenizers, the FTS5 query 'first + place' will match instances
+** of "first place" within the document set, but not alternative forms
+** such as "1st place". In some applications, it would be better to match
+** all instances of "first place" or "1st place" regardless of which form
+** the user specified in the MATCH query text.
+**
+** There are several ways to approach this in FTS5:
+**
+** <ol><li> By mapping all synonyms to a single token. In this case, using
+** the above example, this means that the tokenizer returns the
+** same token for inputs "first" and "1st". Say that token is in
+** fact "first", so that when the user inserts the document "I won
+** 1st place" entries are added to the index for tokens "i", "won",
+** "first" and "place". If the user then queries for '1st + place',
+** the tokenizer substitutes "first" for "1st" and the query works
+** as expected.
+**
+** <li> By querying the index for all synonyms of each query term
+** separately. In this case, when tokenizing query text, the
+** tokenizer may provide multiple synonyms for a single term
+** within the document. FTS5 then queries the index for each
+** synonym individually. For example, faced with the query:
+**
+** <codeblock>
+** ... MATCH 'first place'</codeblock>
+**
+** the tokenizer offers both "1st" and "first" as synonyms for the
+** first token in the MATCH query and FTS5 effectively runs a query
+** similar to:
+**
+** <codeblock>
+** ... MATCH '(first OR 1st) place'</codeblock>
+**
+** except that, for the purposes of auxiliary functions, the query
+** still appears to contain just two phrases - "(first OR 1st)"
+** being treated as a single phrase.
+**
+** <li> By adding multiple synonyms for a single term to the FTS index.
+** Using this method, when tokenizing document text, the tokenizer
+** provides multiple synonyms for each token. So that when a
+** document such as "I won first place" is tokenized, entries are
+** added to the FTS index for "i", "won", "first", "1st" and
+** "place".
+**
+** This way, even if the tokenizer does not provide synonyms
+** when tokenizing query text (it should not - to do so would be
+** inefficient), it doesn't matter if the user queries for
+** 'first + place' or '1st + place', as there are entries in the
+** FTS index corresponding to both forms of the first token.
+** </ol>
+**
+** Whether it is parsing document or query text, any call to xToken that
+** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
+** is considered to supply a synonym for the previous token. For example,
+** when parsing the document "I won first place", a tokenizer that supports
+** synonyms would call xToken() 5 times, as follows:
+**
+** <codeblock>
+** xToken(pCtx, 0, "i", 1, 0, 1);
+** xToken(pCtx, 0, "won", 3, 2, 5);
+** xToken(pCtx, 0, "first", 5, 6, 11);
+** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
+** xToken(pCtx, 0, "place", 5, 12, 17);
+**</codeblock>
+**
+** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
+** xToken() is called. Multiple synonyms may be specified for a single token
+** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
+** There is no limit to the number of synonyms that may be provided for a
+** single token.
+**
+** In many cases, method (1) above is the best approach. It does not add
+** extra data to the FTS index or require FTS5 to query for multiple terms,
+** so it is efficient in terms of disk space and query speed. However, it
+** does not support prefix queries very well. If, as suggested above, the
+** token "first" is substituted for "1st" by the tokenizer, then the query:
+**
+** <codeblock>
+** ... MATCH '1s*'</codeblock>
+**
+** will not match documents that contain the token "1st" (as the tokenizer
+** will probably not map "1s" to any prefix of "first").
+**
+** For full prefix support, method (3) may be preferred. In this case,
+** because the index contains entries for both "first" and "1st", prefix
+** queries such as 'fi*' or '1s*' will match correctly. However, because
+** extra entries are added to the FTS index, this method uses more space
+** within the database.
+**
+** Method (2) offers a midpoint between (1) and (3). Using this method,
+** a query such as '1s*' will match documents that contain the literal
+** token "1st", but not "first" (assuming the tokenizer is not able to
+** provide synonyms for prefixes). However, a non-prefix query like '1st'
+** will match against "1st" and "first". This method does not require
+** extra disk space, as no extra entries are added to the FTS index.
+** On the other hand, it may require more CPU cycles to run MATCH queries,
+** as separate queries of the FTS index are required for each synonym.
+**
+** When using methods (2) or (3), it is important that the tokenizer only
+** provide synonyms when tokenizing document text (method (2)) or query
+** text (method (3)), not both. Doing so will not cause any errors, but is
+** inefficient.
+*/
+typedef struct Fts5Tokenizer Fts5Tokenizer;
+typedef struct fts5_tokenizer fts5_tokenizer;
+struct fts5_tokenizer {
+ int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
+ void (*xDelete)(Fts5Tokenizer*);
+ int (*xTokenize)(Fts5Tokenizer*,
+ void *pCtx,
+ int flags, /* Mask of FTS5_TOKENIZE_* flags */
+ const char *pText, int nText,
+ int (*xToken)(
+ void *pCtx, /* Copy of 2nd argument to xTokenize() */
+ int tflags, /* Mask of FTS5_TOKEN_* flags */
+ const char *pToken, /* Pointer to buffer containing token */
+ int nToken, /* Size of token in bytes */
+ int iStart, /* Byte offset of token within input text */
+ int iEnd /* Byte offset of end of token within input text */
+ )
+ );
+};
+
+/* Flags that may be passed as the third argument to xTokenize() */
+#define FTS5_TOKENIZE_QUERY 0x0001
+#define FTS5_TOKENIZE_PREFIX 0x0002
+#define FTS5_TOKENIZE_DOCUMENT 0x0004
+#define FTS5_TOKENIZE_AUX 0x0008
+
+/* Flags that may be passed by the tokenizer implementation back to FTS5
+** as the third argument to the supplied xToken callback. */
+#define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
+
+/*
+** END OF CUSTOM TOKENIZERS
+*************************************************************************/
+
+/*************************************************************************
+** FTS5 EXTENSION REGISTRATION API
+*/
+typedef struct fts5_api fts5_api;
+struct fts5_api {
+ int iVersion; /* Currently always set to 2 */
+
+ /* Create a new tokenizer */
+ int (*xCreateTokenizer)(
+ fts5_api *pApi,
+ const char *zName,
+ void *pContext,
+ fts5_tokenizer *pTokenizer,
+ void (*xDestroy)(void*)
+ );
+
+ /* Find an existing tokenizer */
+ int (*xFindTokenizer)(
+ fts5_api *pApi,
+ const char *zName,
+ void **ppContext,
+ fts5_tokenizer *pTokenizer
+ );
+
+ /* Create a new auxiliary function */
+ int (*xCreateFunction)(
+ fts5_api *pApi,
+ const char *zName,
+ void *pContext,
+ fts5_extension_function xFunction,
+ void (*xDestroy)(void*)
+ );
+};
+
+/*
+** END OF REGISTRATION API
+*************************************************************************/
+
+#if 0
+} /* end of the 'extern "C"' block */
+#endif
+
+#endif /* _FTS5_H */
+
+/*
+** 2014 May 31
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+*/
+#ifndef _FTS5INT_H
+#define _FTS5INT_H
+
+/* #include "fts5.h" */
+/* #include "sqlite3ext.h" */
+SQLITE_EXTENSION_INIT1
+
+/* #include <string.h> */
+/* #include <assert.h> */
+
+#ifndef SQLITE_AMALGAMATION
+
+typedef unsigned char u8;
+typedef unsigned int u32;
+typedef unsigned short u16;
+typedef short i16;
+typedef sqlite3_int64 i64;
+typedef sqlite3_uint64 u64;
+
+#ifndef ArraySize
+# define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
+#endif
+
+#define testcase(x)
+#define ALWAYS(x) 1
+#define NEVER(x) 0
+
+#define MIN(x,y) (((x) < (y)) ? (x) : (y))
+#define MAX(x,y) (((x) > (y)) ? (x) : (y))
+
+/*
+** Constants for the largest and smallest possible 64-bit signed integers.
+*/
+# define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
+# define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
+
+#endif
+
+/* Truncate very long tokens to this many bytes. Hard limit is
+** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
+** field that occurs at the start of each leaf page (see fts5_index.c). */
+#define FTS5_MAX_TOKEN_SIZE 32768
+
+/*
+** Maximum number of prefix indexes on single FTS5 table. This must be
+** less than 32. If it is set to anything large than that, an #error
+** directive in fts5_index.c will cause the build to fail.
+*/
+#define FTS5_MAX_PREFIX_INDEXES 31
+
+/*
+** Maximum segments permitted in a single index
+*/
+#define FTS5_MAX_SEGMENT 2000
+
+#define FTS5_DEFAULT_NEARDIST 10
+#define FTS5_DEFAULT_RANK "bm25"
+
+/* Name of rank and rowid columns */
+#define FTS5_RANK_NAME "rank"
+#define FTS5_ROWID_NAME "rowid"
+
+#ifdef SQLITE_DEBUG
+# define FTS5_CORRUPT sqlite3Fts5Corrupt()
+static int sqlite3Fts5Corrupt(void);
+#else
+# define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
+#endif
+
+/*
+** The assert_nc() macro is similar to the assert() macro, except that it
+** is used for assert() conditions that are true only if it can be
+** guranteed that the database is not corrupt.
+*/
+#ifdef SQLITE_DEBUG
+SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
+# define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
+#else
+# define assert_nc(x) assert(x)
+#endif
+
+/*
+** A version of memcmp() that does not cause asan errors if one of the pointer
+** parameters is NULL and the number of bytes to compare is zero.
+*/
+#define fts5Memcmp(s1, s2, n) ((n)==0 ? 0 : memcmp((s1), (s2), (n)))
+
+/* Mark a function parameter as unused, to suppress nuisance compiler
+** warnings. */
+#ifndef UNUSED_PARAM
+# define UNUSED_PARAM(X) (void)(X)
+#endif
+
+#ifndef UNUSED_PARAM2
+# define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
+#endif
+
+typedef struct Fts5Global Fts5Global;
+typedef struct Fts5Colset Fts5Colset;
+
+/* If a NEAR() clump or phrase may only match a specific set of columns,
+** then an object of the following type is used to record the set of columns.
+** Each entry in the aiCol[] array is a column that may be matched.
+**
+** This object is used by fts5_expr.c and fts5_index.c.
+*/
+struct Fts5Colset {
+ int nCol;
+ int aiCol[1];
+};
+
+
+
+/**************************************************************************
+** Interface to code in fts5_config.c. fts5_config.c contains contains code
+** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
+*/
+
+typedef struct Fts5Config Fts5Config;
+
+/*
+** An instance of the following structure encodes all information that can
+** be gleaned from the CREATE VIRTUAL TABLE statement.
+**
+** And all information loaded from the %_config table.
+**
+** nAutomerge:
+** The minimum number of segments that an auto-merge operation should
+** attempt to merge together. A value of 1 sets the object to use the
+** compile time default. Zero disables auto-merge altogether.
+**
+** zContent:
+**
+** zContentRowid:
+** The value of the content_rowid= option, if one was specified. Or
+** the string "rowid" otherwise. This text is not quoted - if it is
+** used as part of an SQL statement it needs to be quoted appropriately.
+**
+** zContentExprlist:
+**
+** pzErrmsg:
+** This exists in order to allow the fts5_index.c module to return a
+** decent error message if it encounters a file-format version it does
+** not understand.
+**
+** bColumnsize:
+** True if the %_docsize table is created.
+**
+** bPrefixIndex:
+** This is only used for debugging. If set to false, any prefix indexes
+** are ignored. This value is configured using:
+**
+** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
+**
+*/
+struct Fts5Config {
+ sqlite3 *db; /* Database handle */
+ char *zDb; /* Database holding FTS index (e.g. "main") */
+ char *zName; /* Name of FTS index */
+ int nCol; /* Number of columns */
+ char **azCol; /* Column names */
+ u8 *abUnindexed; /* True for unindexed columns */
+ int nPrefix; /* Number of prefix indexes */
+ int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
+ int eContent; /* An FTS5_CONTENT value */
+ char *zContent; /* content table */
+ char *zContentRowid; /* "content_rowid=" option value */
+ int bColumnsize; /* "columnsize=" option value (dflt==1) */
+ int eDetail; /* FTS5_DETAIL_XXX value */
+ char *zContentExprlist;
+ Fts5Tokenizer *pTok;
+ fts5_tokenizer *pTokApi;
+ int bLock; /* True when table is preparing statement */
+ int ePattern; /* FTS_PATTERN_XXX constant */
+
+ /* Values loaded from the %_config table */
+ int iCookie; /* Incremented when %_config is modified */
+ int pgsz; /* Approximate page size used in %_data */
+ int nAutomerge; /* 'automerge' setting */
+ int nCrisisMerge; /* Maximum allowed segments per level */
+ int nUsermerge; /* 'usermerge' setting */
+ int nHashSize; /* Bytes of memory for in-memory hash */
+ char *zRank; /* Name of rank function */
+ char *zRankArgs; /* Arguments to rank function */
+
+ /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
+ char **pzErrmsg;
+
+#ifdef SQLITE_DEBUG
+ int bPrefixIndex; /* True to use prefix-indexes */
+#endif
+};
+
+/* Current expected value of %_config table 'version' field */
+#define FTS5_CURRENT_VERSION 4
+
+#define FTS5_CONTENT_NORMAL 0
+#define FTS5_CONTENT_NONE 1
+#define FTS5_CONTENT_EXTERNAL 2
+
+#define FTS5_DETAIL_FULL 0
+#define FTS5_DETAIL_NONE 1
+#define FTS5_DETAIL_COLUMNS 2
+
+#define FTS5_PATTERN_NONE 0
+#define FTS5_PATTERN_LIKE 65 /* matches SQLITE_INDEX_CONSTRAINT_LIKE */
+#define FTS5_PATTERN_GLOB 66 /* matches SQLITE_INDEX_CONSTRAINT_GLOB */
+
+static int sqlite3Fts5ConfigParse(
+ Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
+);
+static void sqlite3Fts5ConfigFree(Fts5Config*);
+
+static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
+
+static int sqlite3Fts5Tokenize(
+ Fts5Config *pConfig, /* FTS5 Configuration object */
+ int flags, /* FTS5_TOKENIZE_* flags */
+ const char *pText, int nText, /* Text to tokenize */
+ void *pCtx, /* Context passed to xToken() */
+ int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
+);
+
+static void sqlite3Fts5Dequote(char *z);
+
+/* Load the contents of the %_config table */
+static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
+
+/* Set the value of a single config attribute */
+static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
+
+static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
+
+/*
+** End of interface to code in fts5_config.c.
+**************************************************************************/
+
+/**************************************************************************
+** Interface to code in fts5_buffer.c.
+*/
+
+/*
+** Buffer object for the incremental building of string data.
+*/
+typedef struct Fts5Buffer Fts5Buffer;
+struct Fts5Buffer {
+ u8 *p;
+ int n;
+ int nSpace;
+};
+
+static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
+static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
+static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
+static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
+static void sqlite3Fts5BufferFree(Fts5Buffer*);
+static void sqlite3Fts5BufferZero(Fts5Buffer*);
+static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
+static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
+
+static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
+
+#define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
+#define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
+#define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
+#define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
+#define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
+
+#define fts5BufferGrow(pRc,pBuf,nn) ( \
+ (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
+ sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
+)
+
+/* Write and decode big-endian 32-bit integer values */
+static void sqlite3Fts5Put32(u8*, int);
+static int sqlite3Fts5Get32(const u8*);
+
+#define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
+#define FTS5_POS2OFFSET(iPos) (int)(iPos & 0x7FFFFFFF)
+
+typedef struct Fts5PoslistReader Fts5PoslistReader;
+struct Fts5PoslistReader {
+ /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
+ const u8 *a; /* Position list to iterate through */
+ int n; /* Size of buffer at a[] in bytes */
+ int i; /* Current offset in a[] */
+
+ u8 bFlag; /* For client use (any custom purpose) */
+
+ /* Output variables */
+ u8 bEof; /* Set to true at EOF */
+ i64 iPos; /* (iCol<<32) + iPos */
+};
+static int sqlite3Fts5PoslistReaderInit(
+ const u8 *a, int n, /* Poslist buffer to iterate through */
+ Fts5PoslistReader *pIter /* Iterator object to initialize */
+);
+static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
+
+typedef struct Fts5PoslistWriter Fts5PoslistWriter;
+struct Fts5PoslistWriter {
+ i64 iPrev;
+};
+static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
+static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
+
+static int sqlite3Fts5PoslistNext64(
+ const u8 *a, int n, /* Buffer containing poslist */
+ int *pi, /* IN/OUT: Offset within a[] */
+ i64 *piOff /* IN/OUT: Current offset */
+);
+
+/* Malloc utility */
+static void *sqlite3Fts5MallocZero(int *pRc, sqlite3_int64 nByte);
+static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
+
+/* Character set tests (like isspace(), isalpha() etc.) */
+static int sqlite3Fts5IsBareword(char t);
+
+
+/* Bucket of terms object used by the integrity-check in offsets=0 mode. */
+typedef struct Fts5Termset Fts5Termset;
+static int sqlite3Fts5TermsetNew(Fts5Termset**);
+static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
+static void sqlite3Fts5TermsetFree(Fts5Termset*);
+
+/*
+** End of interface to code in fts5_buffer.c.
+**************************************************************************/
+
+/**************************************************************************
+** Interface to code in fts5_index.c. fts5_index.c contains contains code
+** to access the data stored in the %_data table.
+*/
+
+typedef struct Fts5Index Fts5Index;
+typedef struct Fts5IndexIter Fts5IndexIter;
+
+struct Fts5IndexIter {
+ i64 iRowid;
+ const u8 *pData;
+ int nData;
+ u8 bEof;
+};
+
+#define sqlite3Fts5IterEof(x) ((x)->bEof)
+
+/*
+** Values used as part of the flags argument passed to IndexQuery().
+*/
+#define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
+#define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
+#define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
+#define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
+
+/* The following are used internally by the fts5_index.c module. They are
+** defined here only to make it easier to avoid clashes with the flags
+** above. */
+#define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
+#define FTS5INDEX_QUERY_NOOUTPUT 0x0020
+
+/*
+** Create/destroy an Fts5Index object.
+*/
+static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
+static int sqlite3Fts5IndexClose(Fts5Index *p);
+
+/*
+** Return a simple checksum value based on the arguments.
+*/
+static u64 sqlite3Fts5IndexEntryCksum(
+ i64 iRowid,
+ int iCol,
+ int iPos,
+ int iIdx,
+ const char *pTerm,
+ int nTerm
+);
+
+/*
+** Argument p points to a buffer containing utf-8 text that is n bytes in
+** size. Return the number of bytes in the nChar character prefix of the
+** buffer, or 0 if there are less than nChar characters in total.
+*/
+static int sqlite3Fts5IndexCharlenToBytelen(
+ const char *p,
+ int nByte,
+ int nChar
+);
+
+/*
+** Open a new iterator to iterate though all rowids that match the
+** specified token or token prefix.
+*/
+static int sqlite3Fts5IndexQuery(
+ Fts5Index *p, /* FTS index to query */
+ const char *pToken, int nToken, /* Token (or prefix) to query for */
+ int flags, /* Mask of FTS5INDEX_QUERY_X flags */
+ Fts5Colset *pColset, /* Match these columns only */
+ Fts5IndexIter **ppIter /* OUT: New iterator object */
+);
+
+/*
+** The various operations on open token or token prefix iterators opened
+** using sqlite3Fts5IndexQuery().
+*/
+static int sqlite3Fts5IterNext(Fts5IndexIter*);
+static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
+
+/*
+** Close an iterator opened by sqlite3Fts5IndexQuery().
+*/
+static void sqlite3Fts5IterClose(Fts5IndexIter*);
+
+/*
+** Close the reader blob handle, if it is open.
+*/
+static void sqlite3Fts5IndexCloseReader(Fts5Index*);
+
+/*
+** This interface is used by the fts5vocab module.
+*/
+static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
+static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
+
+
+/*
+** Insert or remove data to or from the index. Each time a document is
+** added to or removed from the index, this function is called one or more
+** times.
+**
+** For an insert, it must be called once for each token in the new document.
+** If the operation is a delete, it must be called (at least) once for each
+** unique token in the document with an iCol value less than zero. The iPos
+** argument is ignored for a delete.
+*/
+static int sqlite3Fts5IndexWrite(
+ Fts5Index *p, /* Index to write to */
+ int iCol, /* Column token appears in (-ve -> delete) */
+ int iPos, /* Position of token within column */
+ const char *pToken, int nToken /* Token to add or remove to or from index */
+);
+
+/*
+** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
+** document iDocid.
+*/
+static int sqlite3Fts5IndexBeginWrite(
+ Fts5Index *p, /* Index to write to */
+ int bDelete, /* True if current operation is a delete */
+ i64 iDocid /* Docid to add or remove data from */
+);
+
+/*
+** Flush any data stored in the in-memory hash tables to the database.
+** Also close any open blob handles.
+*/
+static int sqlite3Fts5IndexSync(Fts5Index *p);
+
+/*
+** Discard any data stored in the in-memory hash tables. Do not write it
+** to the database. Additionally, assume that the contents of the %_data
+** table may have changed on disk. So any in-memory caches of %_data
+** records must be invalidated.
+*/
+static int sqlite3Fts5IndexRollback(Fts5Index *p);
+
+/*
+** Get or set the "averages" values.
+*/
+static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
+static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
+
+/*
+** Functions called by the storage module as part of integrity-check.
+*/
+static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum, int bUseCksum);
+
+/*
+** Called during virtual module initialization to register UDF
+** fts5_decode() with SQLite
+*/
+static int sqlite3Fts5IndexInit(sqlite3*);
+
+static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
+
+/*
+** Return the total number of entries read from the %_data table by
+** this connection since it was created.
+*/
+static int sqlite3Fts5IndexReads(Fts5Index *p);
+
+static int sqlite3Fts5IndexReinit(Fts5Index *p);
+static int sqlite3Fts5IndexOptimize(Fts5Index *p);
+static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
+static int sqlite3Fts5IndexReset(Fts5Index *p);
+
+static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
+
+/*
+** End of interface to code in fts5_index.c.
+**************************************************************************/
+
+/**************************************************************************
+** Interface to code in fts5_varint.c.
+*/
+static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
+static int sqlite3Fts5GetVarintLen(u32 iVal);
+static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
+static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
+
+#define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
+#define fts5GetVarint sqlite3Fts5GetVarint
+
+#define fts5FastGetVarint32(a, iOff, nVal) { \
+ nVal = (a)[iOff++]; \
+ if( nVal & 0x80 ){ \
+ iOff--; \
+ iOff += fts5GetVarint32(&(a)[iOff], nVal); \
+ } \
+}
+
+
+/*
+** End of interface to code in fts5_varint.c.
+**************************************************************************/
+
+
+/**************************************************************************
+** Interface to code in fts5_main.c.
+*/
+
+/*
+** Virtual-table object.
+*/
+typedef struct Fts5Table Fts5Table;
+struct Fts5Table {
+ sqlite3_vtab base; /* Base class used by SQLite core */
+ Fts5Config *pConfig; /* Virtual table configuration */
+ Fts5Index *pIndex; /* Full-text index */
+};
+
+static int sqlite3Fts5GetTokenizer(
+ Fts5Global*,
+ const char **azArg,
+ int nArg,
+ Fts5Config*,
+ char **pzErr
+);
+
+static Fts5Table *sqlite3Fts5TableFromCsrid(Fts5Global*, i64);
+
+static int sqlite3Fts5FlushToDisk(Fts5Table*);
+
+/*
+** End of interface to code in fts5.c.
+**************************************************************************/
+
+/**************************************************************************
+** Interface to code in fts5_hash.c.
+*/
+typedef struct Fts5Hash Fts5Hash;
+
+/*
+** Create a hash table, free a hash table.
+*/
+static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
+static void sqlite3Fts5HashFree(Fts5Hash*);
+
+static int sqlite3Fts5HashWrite(
+ Fts5Hash*,
+ i64 iRowid, /* Rowid for this entry */
+ int iCol, /* Column token appears in (-ve -> delete) */
+ int iPos, /* Position of token within column */
+ char bByte,
+ const char *pToken, int nToken /* Token to add or remove to or from index */
+);
+
+/*
+** Empty (but do not delete) a hash table.
+*/
+static void sqlite3Fts5HashClear(Fts5Hash*);
+
+static int sqlite3Fts5HashQuery(
+ Fts5Hash*, /* Hash table to query */
+ int nPre,
+ const char *pTerm, int nTerm, /* Query term */
+ void **ppObj, /* OUT: Pointer to doclist for pTerm */
+ int *pnDoclist /* OUT: Size of doclist in bytes */
+);
+
+static int sqlite3Fts5HashScanInit(
+ Fts5Hash*, /* Hash table to query */
+ const char *pTerm, int nTerm /* Query prefix */
+);
+static void sqlite3Fts5HashScanNext(Fts5Hash*);
+static int sqlite3Fts5HashScanEof(Fts5Hash*);
+static void sqlite3Fts5HashScanEntry(Fts5Hash *,
+ const char **pzTerm, /* OUT: term (nul-terminated) */
+ const u8 **ppDoclist, /* OUT: pointer to doclist */
+ int *pnDoclist /* OUT: size of doclist in bytes */
+);
+
+
+/*
+** End of interface to code in fts5_hash.c.
+**************************************************************************/
+
+/**************************************************************************
+** Interface to code in fts5_storage.c. fts5_storage.c contains contains
+** code to access the data stored in the %_content and %_docsize tables.
+*/
+
+#define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
+#define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
+#define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
+
+typedef struct Fts5Storage Fts5Storage;
+
+static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
+static int sqlite3Fts5StorageClose(Fts5Storage *p);
+static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
+
+static int sqlite3Fts5DropAll(Fts5Config*);
+static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
+
+static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
+static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
+static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
+
+static int sqlite3Fts5StorageIntegrity(Fts5Storage *p, int iArg);
+
+static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
+static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
+
+static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
+static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
+static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
+
+static int sqlite3Fts5StorageSync(Fts5Storage *p);
+static int sqlite3Fts5StorageRollback(Fts5Storage *p);
+
+static int sqlite3Fts5StorageConfigValue(
+ Fts5Storage *p, const char*, sqlite3_value*, int
+);
+
+static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
+static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
+static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
+static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
+static int sqlite3Fts5StorageReset(Fts5Storage *p);
+
+/*
+** End of interface to code in fts5_storage.c.
+**************************************************************************/
+
+
+/**************************************************************************
+** Interface to code in fts5_expr.c.
+*/
+typedef struct Fts5Expr Fts5Expr;
+typedef struct Fts5ExprNode Fts5ExprNode;
+typedef struct Fts5Parse Fts5Parse;
+typedef struct Fts5Token Fts5Token;
+typedef struct Fts5ExprPhrase Fts5ExprPhrase;
+typedef struct Fts5ExprNearset Fts5ExprNearset;
+
+struct Fts5Token {
+ const char *p; /* Token text (not NULL terminated) */
+ int n; /* Size of buffer p in bytes */
+};
+
+/* Parse a MATCH expression. */
+static int sqlite3Fts5ExprNew(
+ Fts5Config *pConfig,
+ int iCol, /* Column on LHS of MATCH operator */
+ const char *zExpr,
+ Fts5Expr **ppNew,
+ char **pzErr
+);
+
+/*
+** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
+** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
+** rc = sqlite3Fts5ExprNext(pExpr)
+** ){
+** // The document with rowid iRowid matches the expression!
+** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
+** }
+*/
+static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
+static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
+static int sqlite3Fts5ExprEof(Fts5Expr*);
+static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
+
+static void sqlite3Fts5ExprFree(Fts5Expr*);
+static int sqlite3Fts5ExprAnd(Fts5Expr **pp1, Fts5Expr *p2);
+
+/* Called during startup to register a UDF with SQLite */
+static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
+
+static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
+static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
+static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
+
+typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
+static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
+static int sqlite3Fts5ExprPopulatePoslists(
+ Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
+);
+static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
+
+static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
+
+static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
+
+/*******************************************
+** The fts5_expr.c API above this point is used by the other hand-written
+** C code in this module. The interfaces below this point are called by
+** the parser code in fts5parse.y. */
+
+static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
+
+static Fts5ExprNode *sqlite3Fts5ParseNode(
+ Fts5Parse *pParse,
+ int eType,
+ Fts5ExprNode *pLeft,
+ Fts5ExprNode *pRight,
+ Fts5ExprNearset *pNear
+);
+
+static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
+ Fts5Parse *pParse,
+ Fts5ExprNode *pLeft,
+ Fts5ExprNode *pRight
+);
+
+static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
+ Fts5Parse *pParse,
+ Fts5ExprPhrase *pPhrase,
+ Fts5Token *pToken,
+ int bPrefix
+);
+
+static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase*);
+
+static Fts5ExprNearset *sqlite3Fts5ParseNearset(
+ Fts5Parse*,
+ Fts5ExprNearset*,
+ Fts5ExprPhrase*
+);
+
+static Fts5Colset *sqlite3Fts5ParseColset(
+ Fts5Parse*,
+ Fts5Colset*,
+ Fts5Token *
+);
+
+static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
+static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
+static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
+
+static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
+static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
+static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
+static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
+static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
+
+/*
+** End of interface to code in fts5_expr.c.
+**************************************************************************/
+
+
+
+/**************************************************************************
+** Interface to code in fts5_aux.c.
+*/
+
+static int sqlite3Fts5AuxInit(fts5_api*);
+/*
+** End of interface to code in fts5_aux.c.
+**************************************************************************/
+
+/**************************************************************************
+** Interface to code in fts5_tokenizer.c.
+*/
+
+static int sqlite3Fts5TokenizerInit(fts5_api*);
+static int sqlite3Fts5TokenizerPattern(
+ int (*xCreate)(void*, const char**, int, Fts5Tokenizer**),
+ Fts5Tokenizer *pTok
+);
+/*
+** End of interface to code in fts5_tokenizer.c.
+**************************************************************************/
+
+/**************************************************************************
+** Interface to code in fts5_vocab.c.
+*/
+
+static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
+
+/*
+** End of interface to code in fts5_vocab.c.
+**************************************************************************/
+
+
+/**************************************************************************
+** Interface to automatically generated code in fts5_unicode2.c.
+*/
+static int sqlite3Fts5UnicodeIsdiacritic(int c);
+static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
+
+static int sqlite3Fts5UnicodeCatParse(const char*, u8*);
+static int sqlite3Fts5UnicodeCategory(u32 iCode);
+static void sqlite3Fts5UnicodeAscii(u8*, u8*);
+/*
+** End of interface to code in fts5_unicode2.c.
+**************************************************************************/
+
+#endif
+
+#define FTS5_OR 1
+#define FTS5_AND 2
+#define FTS5_NOT 3
+#define FTS5_TERM 4
+#define FTS5_COLON 5
+#define FTS5_MINUS 6
+#define FTS5_LCP 7
+#define FTS5_RCP 8
+#define FTS5_STRING 9
+#define FTS5_LP 10
+#define FTS5_RP 11
+#define FTS5_CARET 12
+#define FTS5_COMMA 13
+#define FTS5_PLUS 14
+#define FTS5_STAR 15
+
+/* This file is automatically generated by Lemon from input grammar
+** source file "fts5parse.y". */
+/*
+** 2000-05-29
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** Driver template for the LEMON parser generator.
+**
+** The "lemon" program processes an LALR(1) input grammar file, then uses
+** this template to construct a parser. The "lemon" program inserts text
+** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
+** interstitial "-" characters) contained in this template is changed into
+** the value of the %name directive from the grammar. Otherwise, the content
+** of this template is copied straight through into the generate parser
+** source file.
+**
+** The following is the concatenation of all %include directives from the
+** input grammar file:
+*/
+/************ Begin %include sections from the grammar ************************/
+
+/* #include "fts5Int.h" */
+/* #include "fts5parse.h" */
+
+/*
+** Disable all error recovery processing in the parser push-down
+** automaton.
+*/
+#define fts5YYNOERRORRECOVERY 1
+
+/*
+** Make fts5yytestcase() the same as testcase()
+*/
+#define fts5yytestcase(X) testcase(X)
+
+/*
+** Indicate that sqlite3ParserFree() will never be called with a null
+** pointer.
+*/
+#define fts5YYPARSEFREENOTNULL 1
+
+/*
+** Alternative datatype for the argument to the malloc() routine passed
+** into sqlite3ParserAlloc(). The default is size_t.
+*/
+#define fts5YYMALLOCARGTYPE u64
+
+/**************** End of %include directives **********************************/
+/* These constants specify the various numeric values for terminal symbols.
+***************** Begin token definitions *************************************/
+#ifndef FTS5_OR
+#define FTS5_OR 1
+#define FTS5_AND 2
+#define FTS5_NOT 3
+#define FTS5_TERM 4
+#define FTS5_COLON 5
+#define FTS5_MINUS 6
+#define FTS5_LCP 7
+#define FTS5_RCP 8
+#define FTS5_STRING 9
+#define FTS5_LP 10
+#define FTS5_RP 11
+#define FTS5_CARET 12
+#define FTS5_COMMA 13
+#define FTS5_PLUS 14
+#define FTS5_STAR 15
+#endif
+/**************** End token definitions ***************************************/
+
+/* The next sections is a series of control #defines.
+** various aspects of the generated parser.
+** fts5YYCODETYPE is the data type used to store the integer codes
+** that represent terminal and non-terminal symbols.
+** "unsigned char" is used if there are fewer than
+** 256 symbols. Larger types otherwise.
+** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
+** any terminal or nonterminal symbol.
+** fts5YYFALLBACK If defined, this indicates that one or more tokens
+** (also known as: "terminal symbols") have fall-back
+** values which should be used if the original symbol
+** would not parse. This permits keywords to sometimes
+** be used as identifiers, for example.
+** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
+** that indicate what to do in response to the next
+** token.
+** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
+** symbols. Background: A "minor type" is a semantic
+** value associated with a terminal or non-terminal
+** symbols. For example, for an "ID" terminal symbol,
+** the minor type might be the name of the identifier.
+** Each non-terminal can have a different minor type.
+** Terminal symbols all have the same minor type, though.
+** This macros defines the minor type for terminal
+** symbols.
+** fts5YYMINORTYPE is the data type used for all minor types.
+** This is typically a union of many types, one of
+** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
+** for terminal symbols is called "fts5yy0".
+** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
+** zero the stack is dynamically sized using realloc()
+** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
+** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
+** sqlite3Fts5ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter
+** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
+** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
+** sqlite3Fts5ParserCTX_* As sqlite3Fts5ParserARG_ except for %extra_context
+** fts5YYERRORSYMBOL is the code number of the error symbol. If not
+** defined, then do no error processing.
+** fts5YYNSTATE the combined number of states.
+** fts5YYNRULE the number of rules in the grammar
+** fts5YYNFTS5TOKEN Number of terminal symbols
+** fts5YY_MAX_SHIFT Maximum value for shift actions
+** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
+** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
+** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
+** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
+** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
+** fts5YY_MIN_REDUCE Minimum value for reduce actions
+** fts5YY_MAX_REDUCE Maximum value for reduce actions
+*/
+#ifndef INTERFACE
+# define INTERFACE 1
+#endif
+/************* Begin control #defines *****************************************/
+#define fts5YYCODETYPE unsigned char
+#define fts5YYNOCODE 27
+#define fts5YYACTIONTYPE unsigned char
+#define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
+typedef union {
+ int fts5yyinit;
+ sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
+ int fts5yy4;
+ Fts5Colset* fts5yy11;
+ Fts5ExprNode* fts5yy24;
+ Fts5ExprNearset* fts5yy46;
+ Fts5ExprPhrase* fts5yy53;
+} fts5YYMINORTYPE;
+#ifndef fts5YYSTACKDEPTH
+#define fts5YYSTACKDEPTH 100
+#endif
+#define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
+#define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
+#define sqlite3Fts5ParserARG_PARAM ,pParse
+#define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse=fts5yypParser->pParse;
+#define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse=pParse;
+#define sqlite3Fts5ParserCTX_SDECL
+#define sqlite3Fts5ParserCTX_PDECL
+#define sqlite3Fts5ParserCTX_PARAM
+#define sqlite3Fts5ParserCTX_FETCH
+#define sqlite3Fts5ParserCTX_STORE
+#define fts5YYNSTATE 35
+#define fts5YYNRULE 28
+#define fts5YYNRULE_WITH_ACTION 28
+#define fts5YYNFTS5TOKEN 16
+#define fts5YY_MAX_SHIFT 34
+#define fts5YY_MIN_SHIFTREDUCE 52
+#define fts5YY_MAX_SHIFTREDUCE 79
+#define fts5YY_ERROR_ACTION 80
+#define fts5YY_ACCEPT_ACTION 81
+#define fts5YY_NO_ACTION 82
+#define fts5YY_MIN_REDUCE 83
+#define fts5YY_MAX_REDUCE 110
+/************* End control #defines *******************************************/
+#define fts5YY_NLOOKAHEAD ((int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])))
+
+/* Define the fts5yytestcase() macro to be a no-op if is not already defined
+** otherwise.
+**
+** Applications can choose to define fts5yytestcase() in the %include section
+** to a macro that can assist in verifying code coverage. For production
+** code the fts5yytestcase() macro should be turned off. But it is useful
+** for testing.
+*/
+#ifndef fts5yytestcase
+# define fts5yytestcase(X)
+#endif
+
+
+/* Next are the tables used to determine what action to take based on the
+** current state and lookahead token. These tables are used to implement
+** functions that take a state number and lookahead value and return an
+** action integer.
+**
+** Suppose the action integer is N. Then the action is determined as
+** follows
+**
+** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
+** token onto the stack and goto state N.
+**
+** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
+** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
+**
+** N == fts5YY_ERROR_ACTION A syntax error has occurred.
+**
+** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
+**
+** N == fts5YY_NO_ACTION No such action. Denotes unused
+** slots in the fts5yy_action[] table.
+**
+** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
+** and fts5YY_MAX_REDUCE
+**
+** The action table is constructed as a single large table named fts5yy_action[].
+** Given state S and lookahead X, the action is computed as either:
+**
+** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
+** (B) N = fts5yy_default[S]
+**
+** The (A) formula is preferred. The B formula is used instead if
+** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X.
+**
+** The formulas above are for computing the action when the lookahead is
+** a terminal symbol. If the lookahead is a non-terminal (as occurs after
+** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
+** the fts5yy_shift_ofst[] array.
+**
+** The following are the tables generated in this section:
+**
+** fts5yy_action[] A single table containing all actions.
+** fts5yy_lookahead[] A table containing the lookahead for each entry in
+** fts5yy_action. Used to detect hash collisions.
+** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
+** shifting terminals.
+** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
+** shifting non-terminals after a reduce.
+** fts5yy_default[] Default action for each state.
+**
+*********** Begin parsing tables **********************************************/
+#define fts5YY_ACTTAB_COUNT (105)
+static const fts5YYACTIONTYPE fts5yy_action[] = {
+ /* 0 */ 81, 20, 96, 6, 28, 99, 98, 26, 26, 18,
+ /* 10 */ 96, 6, 28, 17, 98, 56, 26, 19, 96, 6,
+ /* 20 */ 28, 14, 98, 14, 26, 31, 92, 96, 6, 28,
+ /* 30 */ 108, 98, 25, 26, 21, 96, 6, 28, 78, 98,
+ /* 40 */ 58, 26, 29, 96, 6, 28, 107, 98, 22, 26,
+ /* 50 */ 24, 16, 12, 11, 1, 13, 13, 24, 16, 23,
+ /* 60 */ 11, 33, 34, 13, 97, 8, 27, 32, 98, 7,
+ /* 70 */ 26, 3, 4, 5, 3, 4, 5, 3, 83, 4,
+ /* 80 */ 5, 3, 63, 5, 3, 62, 12, 2, 86, 13,
+ /* 90 */ 9, 30, 10, 10, 54, 57, 75, 78, 78, 53,
+ /* 100 */ 57, 15, 82, 82, 71,
+};
+static const fts5YYCODETYPE fts5yy_lookahead[] = {
+ /* 0 */ 16, 17, 18, 19, 20, 22, 22, 24, 24, 17,
+ /* 10 */ 18, 19, 20, 7, 22, 9, 24, 17, 18, 19,
+ /* 20 */ 20, 9, 22, 9, 24, 13, 17, 18, 19, 20,
+ /* 30 */ 26, 22, 24, 24, 17, 18, 19, 20, 15, 22,
+ /* 40 */ 9, 24, 17, 18, 19, 20, 26, 22, 21, 24,
+ /* 50 */ 6, 7, 9, 9, 10, 12, 12, 6, 7, 21,
+ /* 60 */ 9, 24, 25, 12, 18, 5, 20, 14, 22, 5,
+ /* 70 */ 24, 3, 1, 2, 3, 1, 2, 3, 0, 1,
+ /* 80 */ 2, 3, 11, 2, 3, 11, 9, 10, 5, 12,
+ /* 90 */ 23, 24, 10, 10, 8, 9, 9, 15, 15, 8,
+ /* 100 */ 9, 9, 27, 27, 11, 27, 27, 27, 27, 27,
+ /* 110 */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+ /* 120 */ 27,
+};
+#define fts5YY_SHIFT_COUNT (34)
+#define fts5YY_SHIFT_MIN (0)
+#define fts5YY_SHIFT_MAX (93)
+static const unsigned char fts5yy_shift_ofst[] = {
+ /* 0 */ 44, 44, 44, 44, 44, 44, 51, 77, 43, 12,
+ /* 10 */ 14, 83, 82, 14, 23, 23, 31, 31, 71, 74,
+ /* 20 */ 78, 81, 86, 91, 6, 53, 53, 60, 64, 68,
+ /* 30 */ 53, 87, 92, 53, 93,
+};
+#define fts5YY_REDUCE_COUNT (17)
+#define fts5YY_REDUCE_MIN (-17)
+#define fts5YY_REDUCE_MAX (67)
+static const signed char fts5yy_reduce_ofst[] = {
+ /* 0 */ -16, -8, 0, 9, 17, 25, 46, -17, -17, 37,
+ /* 10 */ 67, 4, 4, 8, 4, 20, 27, 38,
+};
+static const fts5YYACTIONTYPE fts5yy_default[] = {
+ /* 0 */ 80, 80, 80, 80, 80, 80, 95, 80, 80, 105,
+ /* 10 */ 80, 110, 110, 80, 110, 110, 80, 80, 80, 80,
+ /* 20 */ 80, 91, 80, 80, 80, 101, 100, 80, 80, 90,
+ /* 30 */ 103, 80, 80, 104, 80,
+};
+/********** End of lemon-generated parsing tables *****************************/
+
+/* The next table maps tokens (terminal symbols) into fallback tokens.
+** If a construct like the following:
+**
+** %fallback ID X Y Z.
+**
+** appears in the grammar, then ID becomes a fallback token for X, Y,
+** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
+** but it does not parse, the type of the token is changed to ID and
+** the parse is retried before an error is thrown.
+**
+** This feature can be used, for example, to cause some keywords in a language
+** to revert to identifiers if they keyword does not apply in the context where
+** it appears.
+*/
+#ifdef fts5YYFALLBACK
+static const fts5YYCODETYPE fts5yyFallback[] = {
+};
+#endif /* fts5YYFALLBACK */
+
+/* The following structure represents a single element of the
+** parser's stack. Information stored includes:
+**
+** + The state number for the parser at this level of the stack.
+**
+** + The value of the token stored at this level of the stack.
+** (In other words, the "major" token.)
+**
+** + The semantic value stored at this level of the stack. This is
+** the information used by the action routines in the grammar.
+** It is sometimes called the "minor" token.
+**
+** After the "shift" half of a SHIFTREDUCE action, the stateno field
+** actually contains the reduce action for the second half of the
+** SHIFTREDUCE.
+*/
+struct fts5yyStackEntry {
+ fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
+ fts5YYCODETYPE major; /* The major token value. This is the code
+ ** number for the token at this stack level */
+ fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
+ ** is the value of the token */
+};
+typedef struct fts5yyStackEntry fts5yyStackEntry;
+
+/* The state of the parser is completely contained in an instance of
+** the following structure */
+struct fts5yyParser {
+ fts5yyStackEntry *fts5yytos; /* Pointer to top element of the stack */
+#ifdef fts5YYTRACKMAXSTACKDEPTH
+ int fts5yyhwm; /* High-water mark of the stack */
+#endif
+#ifndef fts5YYNOERRORRECOVERY
+ int fts5yyerrcnt; /* Shifts left before out of the error */
+#endif
+ sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
+ sqlite3Fts5ParserCTX_SDECL /* A place to hold %extra_context */
+#if fts5YYSTACKDEPTH<=0
+ int fts5yystksz; /* Current side of the stack */
+ fts5yyStackEntry *fts5yystack; /* The parser's stack */
+ fts5yyStackEntry fts5yystk0; /* First stack entry */
+#else
+ fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
+ fts5yyStackEntry *fts5yystackEnd; /* Last entry in the stack */
+#endif
+};
+typedef struct fts5yyParser fts5yyParser;
+
+#ifndef NDEBUG
+/* #include <stdio.h> */
+/* #include <assert.h> */
+static FILE *fts5yyTraceFILE = 0;
+static char *fts5yyTracePrompt = 0;
+#endif /* NDEBUG */
+
+#ifndef NDEBUG
+/*
+** Turn parser tracing on by giving a stream to which to write the trace
+** and a prompt to preface each trace message. Tracing is turned off
+** by making either argument NULL
+**
+** Inputs:
+** <ul>
+** <li> A FILE* to which trace output should be written.
+** If NULL, then tracing is turned off.
+** <li> A prefix string written at the beginning of every
+** line of trace output. If NULL, then tracing is
+** turned off.
+** </ul>
+**
+** Outputs:
+** None.
+*/
+static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
+ fts5yyTraceFILE = TraceFILE;
+ fts5yyTracePrompt = zTracePrompt;
+ if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
+ else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
+}
+#endif /* NDEBUG */
+
+#if defined(fts5YYCOVERAGE) || !defined(NDEBUG)
+/* For tracing shifts, the names of all terminals and nonterminals
+** are required. The following table supplies these names */
+static const char *const fts5yyTokenName[] = {
+ /* 0 */ "$",
+ /* 1 */ "OR",
+ /* 2 */ "AND",
+ /* 3 */ "NOT",
+ /* 4 */ "TERM",
+ /* 5 */ "COLON",
+ /* 6 */ "MINUS",
+ /* 7 */ "LCP",
+ /* 8 */ "RCP",
+ /* 9 */ "STRING",
+ /* 10 */ "LP",
+ /* 11 */ "RP",
+ /* 12 */ "CARET",
+ /* 13 */ "COMMA",
+ /* 14 */ "PLUS",
+ /* 15 */ "STAR",
+ /* 16 */ "input",
+ /* 17 */ "expr",
+ /* 18 */ "cnearset",
+ /* 19 */ "exprlist",
+ /* 20 */ "colset",
+ /* 21 */ "colsetlist",
+ /* 22 */ "nearset",
+ /* 23 */ "nearphrases",
+ /* 24 */ "phrase",
+ /* 25 */ "neardist_opt",
+ /* 26 */ "star_opt",
+};
+#endif /* defined(fts5YYCOVERAGE) || !defined(NDEBUG) */
+
+#ifndef NDEBUG
+/* For tracing reduce actions, the names of all rules are required.
+*/
+static const char *const fts5yyRuleName[] = {
+ /* 0 */ "input ::= expr",
+ /* 1 */ "colset ::= MINUS LCP colsetlist RCP",
+ /* 2 */ "colset ::= LCP colsetlist RCP",
+ /* 3 */ "colset ::= STRING",
+ /* 4 */ "colset ::= MINUS STRING",
+ /* 5 */ "colsetlist ::= colsetlist STRING",
+ /* 6 */ "colsetlist ::= STRING",
+ /* 7 */ "expr ::= expr AND expr",
+ /* 8 */ "expr ::= expr OR expr",
+ /* 9 */ "expr ::= expr NOT expr",
+ /* 10 */ "expr ::= colset COLON LP expr RP",
+ /* 11 */ "expr ::= LP expr RP",
+ /* 12 */ "expr ::= exprlist",
+ /* 13 */ "exprlist ::= cnearset",
+ /* 14 */ "exprlist ::= exprlist cnearset",
+ /* 15 */ "cnearset ::= nearset",
+ /* 16 */ "cnearset ::= colset COLON nearset",
+ /* 17 */ "nearset ::= phrase",
+ /* 18 */ "nearset ::= CARET phrase",
+ /* 19 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
+ /* 20 */ "nearphrases ::= phrase",
+ /* 21 */ "nearphrases ::= nearphrases phrase",
+ /* 22 */ "neardist_opt ::=",
+ /* 23 */ "neardist_opt ::= COMMA STRING",
+ /* 24 */ "phrase ::= phrase PLUS STRING star_opt",
+ /* 25 */ "phrase ::= STRING star_opt",
+ /* 26 */ "star_opt ::= STAR",
+ /* 27 */ "star_opt ::=",
+};
+#endif /* NDEBUG */
+
+
+#if fts5YYSTACKDEPTH<=0
+/*
+** Try to increase the size of the parser stack. Return the number
+** of errors. Return 0 on success.
+*/
+static int fts5yyGrowStack(fts5yyParser *p){
+ int newSize;
+ int idx;
+ fts5yyStackEntry *pNew;
+
+ newSize = p->fts5yystksz*2 + 100;
+ idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
+ if( p->fts5yystack==&p->fts5yystk0 ){
+ pNew = malloc(newSize*sizeof(pNew[0]));
+ if( pNew ) pNew[0] = p->fts5yystk0;
+ }else{
+ pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
+ }
+ if( pNew ){
+ p->fts5yystack = pNew;
+ p->fts5yytos = &p->fts5yystack[idx];
+#ifndef NDEBUG
+ if( fts5yyTraceFILE ){
+ fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
+ fts5yyTracePrompt, p->fts5yystksz, newSize);
+ }
+#endif
+ p->fts5yystksz = newSize;
+ }
+ return pNew==0;
+}
+#endif
+
+/* Datatype of the argument to the memory allocated passed as the
+** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
+** putting an appropriate #define in the %include section of the input
+** grammar.
+*/
+#ifndef fts5YYMALLOCARGTYPE
+# define fts5YYMALLOCARGTYPE size_t
+#endif
+
+/* Initialize a new parser that has already been allocated.
+*/
+static void sqlite3Fts5ParserInit(void *fts5yypRawParser sqlite3Fts5ParserCTX_PDECL){
+ fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yypRawParser;
+ sqlite3Fts5ParserCTX_STORE
+#ifdef fts5YYTRACKMAXSTACKDEPTH
+ fts5yypParser->fts5yyhwm = 0;
+#endif
+#if fts5YYSTACKDEPTH<=0
+ fts5yypParser->fts5yytos = NULL;
+ fts5yypParser->fts5yystack = NULL;
+ fts5yypParser->fts5yystksz = 0;
+ if( fts5yyGrowStack(fts5yypParser) ){
+ fts5yypParser->fts5yystack = &fts5yypParser->fts5yystk0;
+ fts5yypParser->fts5yystksz = 1;
+ }
+#endif
+#ifndef fts5YYNOERRORRECOVERY
+ fts5yypParser->fts5yyerrcnt = -1;
+#endif
+ fts5yypParser->fts5yytos = fts5yypParser->fts5yystack;
+ fts5yypParser->fts5yystack[0].stateno = 0;
+ fts5yypParser->fts5yystack[0].major = 0;
+#if fts5YYSTACKDEPTH>0
+ fts5yypParser->fts5yystackEnd = &fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1];
+#endif
+}
+
+#ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
+/*
+** This function allocates a new parser.
+** The only argument is a pointer to a function which works like
+** malloc.
+**
+** Inputs:
+** A pointer to the function used to allocate memory.
+**
+** Outputs:
+** A pointer to a parser. This pointer is used in subsequent calls
+** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
+*/
+static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE) sqlite3Fts5ParserCTX_PDECL){
+ fts5yyParser *fts5yypParser;
+ fts5yypParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
+ if( fts5yypParser ){
+ sqlite3Fts5ParserCTX_STORE
+ sqlite3Fts5ParserInit(fts5yypParser sqlite3Fts5ParserCTX_PARAM);
+ }
+ return (void*)fts5yypParser;
+}
+#endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
+
+
+/* The following function deletes the "minor type" or semantic value
+** associated with a symbol. The symbol can be either a terminal
+** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
+** a pointer to the value to be deleted. The code used to do the
+** deletions is derived from the %destructor and/or %token_destructor
+** directives of the input grammar.
+*/
+static void fts5yy_destructor(
+ fts5yyParser *fts5yypParser, /* The parser */
+ fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
+ fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
+){
+ sqlite3Fts5ParserARG_FETCH
+ sqlite3Fts5ParserCTX_FETCH
+ switch( fts5yymajor ){
+ /* Here is inserted the actions which take place when a
+ ** terminal or non-terminal is destroyed. This can happen
+ ** when the symbol is popped from the stack during a
+ ** reduce or during error processing or when a parser is
+ ** being destroyed before it is finished parsing.
+ **
+ ** Note: during a reduce, the only symbols destroyed are those
+ ** which appear on the RHS of the rule, but which are *not* used
+ ** inside the C code.
+ */
+/********* Begin destructor definitions ***************************************/
+ case 16: /* input */
+{
+ (void)pParse;
+}
+ break;
+ case 17: /* expr */
+ case 18: /* cnearset */
+ case 19: /* exprlist */
+{
+ sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
+}
+ break;
+ case 20: /* colset */
+ case 21: /* colsetlist */
+{
+ sqlite3_free((fts5yypminor->fts5yy11));
+}
+ break;
+ case 22: /* nearset */
+ case 23: /* nearphrases */
+{
+ sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
+}
+ break;
+ case 24: /* phrase */
+{
+ sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
+}
+ break;
+/********* End destructor definitions *****************************************/
+ default: break; /* If no destructor action specified: do nothing */
+ }
+}
+
+/*
+** Pop the parser's stack once.
+**
+** If there is a destructor routine associated with the token which
+** is popped from the stack, then call it.
+*/
+static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
+ fts5yyStackEntry *fts5yytos;
+ assert( pParser->fts5yytos!=0 );
+ assert( pParser->fts5yytos > pParser->fts5yystack );
+ fts5yytos = pParser->fts5yytos--;
+#ifndef NDEBUG
+ if( fts5yyTraceFILE ){
+ fprintf(fts5yyTraceFILE,"%sPopping %s\n",
+ fts5yyTracePrompt,
+ fts5yyTokenName[fts5yytos->major]);
+ }
+#endif
+ fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
+}
+
+/*
+** Clear all secondary memory allocations from the parser
+*/
+static void sqlite3Fts5ParserFinalize(void *p){
+ fts5yyParser *pParser = (fts5yyParser*)p;
+ while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
+#if fts5YYSTACKDEPTH<=0
+ if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
+#endif
+}
+
+#ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
+/*
+** Deallocate and destroy a parser. Destructors are called for
+** all stack elements before shutting the parser down.
+**
+** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
+** is defined in a %include section of the input grammar) then it is
+** assumed that the input pointer is never NULL.
+*/
+static void sqlite3Fts5ParserFree(
+ void *p, /* The parser to be deleted */
+ void (*freeProc)(void*) /* Function used to reclaim memory */
+){
+#ifndef fts5YYPARSEFREENEVERNULL
+ if( p==0 ) return;
+#endif
+ sqlite3Fts5ParserFinalize(p);
+ (*freeProc)(p);
+}
+#endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
+
+/*
+** Return the peak depth of the stack for a parser.
+*/
+#ifdef fts5YYTRACKMAXSTACKDEPTH
+static int sqlite3Fts5ParserStackPeak(void *p){
+ fts5yyParser *pParser = (fts5yyParser*)p;
+ return pParser->fts5yyhwm;
+}
+#endif
+
+/* This array of booleans keeps track of the parser statement
+** coverage. The element fts5yycoverage[X][Y] is set when the parser
+** is in state X and has a lookahead token Y. In a well-tested
+** systems, every element of this matrix should end up being set.
+*/
+#if defined(fts5YYCOVERAGE)
+static unsigned char fts5yycoverage[fts5YYNSTATE][fts5YYNFTS5TOKEN];
+#endif
+
+/*
+** Write into out a description of every state/lookahead combination that
+**
+** (1) has not been used by the parser, and
+** (2) is not a syntax error.
+**
+** Return the number of missed state/lookahead combinations.
+*/
+#if defined(fts5YYCOVERAGE)
+static int sqlite3Fts5ParserCoverage(FILE *out){
+ int stateno, iLookAhead, i;
+ int nMissed = 0;
+ for(stateno=0; stateno<fts5YYNSTATE; stateno++){
+ i = fts5yy_shift_ofst[stateno];
+ for(iLookAhead=0; iLookAhead<fts5YYNFTS5TOKEN; iLookAhead++){
+ if( fts5yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
+ if( fts5yycoverage[stateno][iLookAhead]==0 ) nMissed++;
+ if( out ){
+ fprintf(out,"State %d lookahead %s %s\n", stateno,
+ fts5yyTokenName[iLookAhead],
+ fts5yycoverage[stateno][iLookAhead] ? "ok" : "missed");
+ }
+ }
+ }
+ return nMissed;
+}
+#endif
+
+/*
+** Find the appropriate action for a parser given the terminal
+** look-ahead token iLookAhead.
+*/
+static fts5YYACTIONTYPE fts5yy_find_shift_action(
+ fts5YYCODETYPE iLookAhead, /* The look-ahead token */
+ fts5YYACTIONTYPE stateno /* Current state number */
+){
+ int i;
+
+ if( stateno>fts5YY_MAX_SHIFT ) return stateno;
+ assert( stateno <= fts5YY_SHIFT_COUNT );
+#if defined(fts5YYCOVERAGE)
+ fts5yycoverage[stateno][iLookAhead] = 1;
+#endif
+ do{
+ i = fts5yy_shift_ofst[stateno];
+ assert( i>=0 );
+ assert( i<=fts5YY_ACTTAB_COUNT );
+ assert( i+fts5YYNFTS5TOKEN<=(int)fts5YY_NLOOKAHEAD );
+ assert( iLookAhead!=fts5YYNOCODE );
+ assert( iLookAhead < fts5YYNFTS5TOKEN );
+ i += iLookAhead;
+ assert( i<(int)fts5YY_NLOOKAHEAD );
+ if( fts5yy_lookahead[i]!=iLookAhead ){
+#ifdef fts5YYFALLBACK
+ fts5YYCODETYPE iFallback; /* Fallback token */
+ assert( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0]) );
+ iFallback = fts5yyFallback[iLookAhead];
+ if( iFallback!=0 ){
+#ifndef NDEBUG
+ if( fts5yyTraceFILE ){
+ fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
+ fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
+ }
+#endif
+ assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
+ iLookAhead = iFallback;
+ continue;
+ }
+#endif
+#ifdef fts5YYWILDCARD
+ {
+ int j = i - iLookAhead + fts5YYWILDCARD;
+ assert( j<(int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])) );
+ if( fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0 ){
+#ifndef NDEBUG
+ if( fts5yyTraceFILE ){
+ fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
+ fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
+ fts5yyTokenName[fts5YYWILDCARD]);
+ }
+#endif /* NDEBUG */
+ return fts5yy_action[j];
+ }
+ }
+#endif /* fts5YYWILDCARD */
+ return fts5yy_default[stateno];
+ }else{
+ assert( i>=0 && i<(int)(sizeof(fts5yy_action)/sizeof(fts5yy_action[0])) );
+ return fts5yy_action[i];
+ }
+ }while(1);
+}
+
+/*
+** Find the appropriate action for a parser given the non-terminal
+** look-ahead token iLookAhead.
+*/
+static fts5YYACTIONTYPE fts5yy_find_reduce_action(
+ fts5YYACTIONTYPE stateno, /* Current state number */
+ fts5YYCODETYPE iLookAhead /* The look-ahead token */
+){
+ int i;
+#ifdef fts5YYERRORSYMBOL
+ if( stateno>fts5YY_REDUCE_COUNT ){
+ return fts5yy_default[stateno];
+ }
+#else
+ assert( stateno<=fts5YY_REDUCE_COUNT );
+#endif
+ i = fts5yy_reduce_ofst[stateno];
+ assert( iLookAhead!=fts5YYNOCODE );
+ i += iLookAhead;
+#ifdef fts5YYERRORSYMBOL
+ if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
+ return fts5yy_default[stateno];
+ }
+#else
+ assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
+ assert( fts5yy_lookahead[i]==iLookAhead );
+#endif
+ return fts5yy_action[i];
+}
+
+/*
+** The following routine is called if the stack overflows.
+*/
+static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
+ sqlite3Fts5ParserARG_FETCH
+ sqlite3Fts5ParserCTX_FETCH
+#ifndef NDEBUG
+ if( fts5yyTraceFILE ){
+ fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
+ }
+#endif
+ while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
+ /* Here code is inserted which will execute if the parser
+ ** stack every overflows */
+/******** Begin %stack_overflow code ******************************************/
+
+ sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
+/******** End %stack_overflow code ********************************************/
+ sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument var */
+ sqlite3Fts5ParserCTX_STORE
+}
+
+/*
+** Print tracing information for a SHIFT action
+*/
+#ifndef NDEBUG
+static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState, const char *zTag){
+ if( fts5yyTraceFILE ){
+ if( fts5yyNewState<fts5YYNSTATE ){
+ fprintf(fts5yyTraceFILE,"%s%s '%s', go to state %d\n",
+ fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
+ fts5yyNewState);
+ }else{
+ fprintf(fts5yyTraceFILE,"%s%s '%s', pending reduce %d\n",
+ fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
+ fts5yyNewState - fts5YY_MIN_REDUCE);
+ }
+ }
+}
+#else
+# define fts5yyTraceShift(X,Y,Z)
+#endif
+
+/*
+** Perform a shift action.
+*/
+static void fts5yy_shift(
+ fts5yyParser *fts5yypParser, /* The parser to be shifted */
+ fts5YYACTIONTYPE fts5yyNewState, /* The new state to shift in */
+ fts5YYCODETYPE fts5yyMajor, /* The major token to shift in */
+ sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
+){
+ fts5yyStackEntry *fts5yytos;
+ fts5yypParser->fts5yytos++;
+#ifdef fts5YYTRACKMAXSTACKDEPTH
+ if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
+ fts5yypParser->fts5yyhwm++;
+ assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
+ }
+#endif
+#if fts5YYSTACKDEPTH>0
+ if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){
+ fts5yypParser->fts5yytos--;
+ fts5yyStackOverflow(fts5yypParser);
+ return;
+ }
+#else
+ if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
+ if( fts5yyGrowStack(fts5yypParser) ){
+ fts5yypParser->fts5yytos--;
+ fts5yyStackOverflow(fts5yypParser);
+ return;
+ }
+ }
+#endif
+ if( fts5yyNewState > fts5YY_MAX_SHIFT ){
+ fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
+ }
+ fts5yytos = fts5yypParser->fts5yytos;
+ fts5yytos->stateno = fts5yyNewState;
+ fts5yytos->major = fts5yyMajor;
+ fts5yytos->minor.fts5yy0 = fts5yyMinor;
+ fts5yyTraceShift(fts5yypParser, fts5yyNewState, "Shift");
+}
+
+/* For rule J, fts5yyRuleInfoLhs[J] contains the symbol on the left-hand side
+** of that rule */
+static const fts5YYCODETYPE fts5yyRuleInfoLhs[] = {
+ 16, /* (0) input ::= expr */
+ 20, /* (1) colset ::= MINUS LCP colsetlist RCP */
+ 20, /* (2) colset ::= LCP colsetlist RCP */
+ 20, /* (3) colset ::= STRING */
+ 20, /* (4) colset ::= MINUS STRING */
+ 21, /* (5) colsetlist ::= colsetlist STRING */
+ 21, /* (6) colsetlist ::= STRING */
+ 17, /* (7) expr ::= expr AND expr */
+ 17, /* (8) expr ::= expr OR expr */
+ 17, /* (9) expr ::= expr NOT expr */
+ 17, /* (10) expr ::= colset COLON LP expr RP */
+ 17, /* (11) expr ::= LP expr RP */
+ 17, /* (12) expr ::= exprlist */
+ 19, /* (13) exprlist ::= cnearset */
+ 19, /* (14) exprlist ::= exprlist cnearset */
+ 18, /* (15) cnearset ::= nearset */
+ 18, /* (16) cnearset ::= colset COLON nearset */
+ 22, /* (17) nearset ::= phrase */
+ 22, /* (18) nearset ::= CARET phrase */
+ 22, /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
+ 23, /* (20) nearphrases ::= phrase */
+ 23, /* (21) nearphrases ::= nearphrases phrase */
+ 25, /* (22) neardist_opt ::= */
+ 25, /* (23) neardist_opt ::= COMMA STRING */
+ 24, /* (24) phrase ::= phrase PLUS STRING star_opt */
+ 24, /* (25) phrase ::= STRING star_opt */
+ 26, /* (26) star_opt ::= STAR */
+ 26, /* (27) star_opt ::= */
+};
+
+/* For rule J, fts5yyRuleInfoNRhs[J] contains the negative of the number
+** of symbols on the right-hand side of that rule. */
+static const signed char fts5yyRuleInfoNRhs[] = {
+ -1, /* (0) input ::= expr */
+ -4, /* (1) colset ::= MINUS LCP colsetlist RCP */
+ -3, /* (2) colset ::= LCP colsetlist RCP */
+ -1, /* (3) colset ::= STRING */
+ -2, /* (4) colset ::= MINUS STRING */
+ -2, /* (5) colsetlist ::= colsetlist STRING */
+ -1, /* (6) colsetlist ::= STRING */
+ -3, /* (7) expr ::= expr AND expr */
+ -3, /* (8) expr ::= expr OR expr */
+ -3, /* (9) expr ::= expr NOT expr */
+ -5, /* (10) expr ::= colset COLON LP expr RP */
+ -3, /* (11) expr ::= LP expr RP */
+ -1, /* (12) expr ::= exprlist */
+ -1, /* (13) exprlist ::= cnearset */
+ -2, /* (14) exprlist ::= exprlist cnearset */
+ -1, /* (15) cnearset ::= nearset */
+ -3, /* (16) cnearset ::= colset COLON nearset */
+ -1, /* (17) nearset ::= phrase */
+ -2, /* (18) nearset ::= CARET phrase */
+ -5, /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
+ -1, /* (20) nearphrases ::= phrase */
+ -2, /* (21) nearphrases ::= nearphrases phrase */
+ 0, /* (22) neardist_opt ::= */
+ -2, /* (23) neardist_opt ::= COMMA STRING */
+ -4, /* (24) phrase ::= phrase PLUS STRING star_opt */
+ -2, /* (25) phrase ::= STRING star_opt */
+ -1, /* (26) star_opt ::= STAR */
+ 0, /* (27) star_opt ::= */
+};
+
+static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
+
+/*
+** Perform a reduce action and the shift that must immediately
+** follow the reduce.
+**
+** The fts5yyLookahead and fts5yyLookaheadToken parameters provide reduce actions
+** access to the lookahead token (if any). The fts5yyLookahead will be fts5YYNOCODE
+** if the lookahead token has already been consumed. As this procedure is
+** only called from one place, optimizing compilers will in-line it, which
+** means that the extra parameters have no performance impact.
+*/
+static fts5YYACTIONTYPE fts5yy_reduce(
+ fts5yyParser *fts5yypParser, /* The parser */
+ unsigned int fts5yyruleno, /* Number of the rule by which to reduce */
+ int fts5yyLookahead, /* Lookahead token, or fts5YYNOCODE if none */
+ sqlite3Fts5ParserFTS5TOKENTYPE fts5yyLookaheadToken /* Value of the lookahead token */
+ sqlite3Fts5ParserCTX_PDECL /* %extra_context */
+){
+ int fts5yygoto; /* The next state */
+ fts5YYACTIONTYPE fts5yyact; /* The next action */
+ fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
+ int fts5yysize; /* Amount to pop the stack */
+ sqlite3Fts5ParserARG_FETCH
+ (void)fts5yyLookahead;
+ (void)fts5yyLookaheadToken;
+ fts5yymsp = fts5yypParser->fts5yytos;
+ assert( fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) );
+#ifndef NDEBUG
+ if( fts5yyTraceFILE ){
+ fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];
+ if( fts5yysize ){
+ fprintf(fts5yyTraceFILE, "%sReduce %d [%s]%s, pop back to state %d.\n",
+ fts5yyTracePrompt,
+ fts5yyruleno, fts5yyRuleName[fts5yyruleno],
+ fts5yyruleno<fts5YYNRULE_WITH_ACTION ? "" : " without external action",
+ fts5yymsp[fts5yysize].stateno);
+ }else{
+ fprintf(fts5yyTraceFILE, "%sReduce %d [%s]%s.\n",
+ fts5yyTracePrompt, fts5yyruleno, fts5yyRuleName[fts5yyruleno],
+ fts5yyruleno<fts5YYNRULE_WITH_ACTION ? "" : " without external action");
+ }
+ }
+#endif /* NDEBUG */
+
+ /* Check that the stack is large enough to grow by a single entry
+ ** if the RHS of the rule is empty. This ensures that there is room
+ ** enough on the stack to push the LHS value */
+ if( fts5yyRuleInfoNRhs[fts5yyruleno]==0 ){
+#ifdef fts5YYTRACKMAXSTACKDEPTH
+ if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
+ fts5yypParser->fts5yyhwm++;
+ assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
+ }
+#endif
+#if fts5YYSTACKDEPTH>0
+ if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
+ fts5yyStackOverflow(fts5yypParser);
+ /* The call to fts5yyStackOverflow() above pops the stack until it is
+ ** empty, causing the main parser loop to exit. So the return value
+ ** is never used and does not matter. */
+ return 0;
+ }
+#else
+ if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
+ if( fts5yyGrowStack(fts5yypParser) ){
+ fts5yyStackOverflow(fts5yypParser);
+ /* The call to fts5yyStackOverflow() above pops the stack until it is
+ ** empty, causing the main parser loop to exit. So the return value
+ ** is never used and does not matter. */
+ return 0;
+ }
+ fts5yymsp = fts5yypParser->fts5yytos;
+ }
+#endif
+ }
+
+ switch( fts5yyruleno ){
+ /* Beginning here are the reduction cases. A typical example
+ ** follows:
+ ** case 0:
+ ** #line <lineno> <grammarfile>
+ ** { ... } // User supplied code
+ ** #line <lineno> <thisfile>
+ ** break;
+ */
+/********** Begin reduce actions **********************************************/
+ fts5YYMINORTYPE fts5yylhsminor;
+ case 0: /* input ::= expr */
+{ sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
+ break;
+ case 1: /* colset ::= MINUS LCP colsetlist RCP */
+{
+ fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
+}
+ break;
+ case 2: /* colset ::= LCP colsetlist RCP */
+{ fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
+ break;
+ case 3: /* colset ::= STRING */
+{
+ fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
+}
+ fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
+ break;
+ case 4: /* colset ::= MINUS STRING */
+{
+ fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
+ fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
+}
+ break;
+ case 5: /* colsetlist ::= colsetlist STRING */
+{
+ fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
+ fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
+ break;
+ case 6: /* colsetlist ::= STRING */
+{
+ fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
+}
+ fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
+ break;
+ case 7: /* expr ::= expr AND expr */
+{
+ fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
+}
+ fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
+ break;
+ case 8: /* expr ::= expr OR expr */
+{
+ fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
+}
+ fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
+ break;
+ case 9: /* expr ::= expr NOT expr */
+{
+ fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
+}
+ fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
+ break;
+ case 10: /* expr ::= colset COLON LP expr RP */
+{
+ sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);
+ fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;
+}
+ fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
+ break;
+ case 11: /* expr ::= LP expr RP */
+{fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
+ break;
+ case 12: /* expr ::= exprlist */
+ case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
+{fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
+ fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
+ break;
+ case 14: /* exprlist ::= exprlist cnearset */
+{
+ fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
+}
+ fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
+ break;
+ case 15: /* cnearset ::= nearset */
+{
+ fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
+}
+ fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
+ break;
+ case 16: /* cnearset ::= colset COLON nearset */
+{
+ fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
+ sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
+}
+ fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
+ break;
+ case 17: /* nearset ::= phrase */
+{ fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
+ fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
+ break;
+ case 18: /* nearset ::= CARET phrase */
+{
+ sqlite3Fts5ParseSetCaret(fts5yymsp[0].minor.fts5yy53);
+ fts5yymsp[-1].minor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
+}
+ break;
+ case 19: /* nearset ::= STRING LP nearphrases neardist_opt RP */
+{
+ sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
+ sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
+ fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
+}
+ fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
+ break;
+ case 20: /* nearphrases ::= phrase */
+{
+ fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
+}
+ fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
+ break;
+ case 21: /* nearphrases ::= nearphrases phrase */
+{
+ fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
+}
+ fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
+ break;
+ case 22: /* neardist_opt ::= */
+{ fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
+ break;
+ case 23: /* neardist_opt ::= COMMA STRING */
+{ fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
+ break;
+ case 24: /* phrase ::= phrase PLUS STRING star_opt */
+{
+ fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
+}
+ fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
+ break;
+ case 25: /* phrase ::= STRING star_opt */
+{
+ fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
+}
+ fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
+ break;
+ case 26: /* star_opt ::= STAR */
+{ fts5yymsp[0].minor.fts5yy4 = 1; }
+ break;
+ case 27: /* star_opt ::= */
+{ fts5yymsp[1].minor.fts5yy4 = 0; }
+ break;
+ default:
+ break;
+/********** End reduce actions ************************************************/
+ };
+ assert( fts5yyruleno<sizeof(fts5yyRuleInfoLhs)/sizeof(fts5yyRuleInfoLhs[0]) );
+ fts5yygoto = fts5yyRuleInfoLhs[fts5yyruleno];
+ fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];
+ fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
+
+ /* There are no SHIFTREDUCE actions on nonterminals because the table
+ ** generator has simplified them to pure REDUCE actions. */
+ assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );
+
+ /* It is not possible for a REDUCE to be followed by an error */
+ assert( fts5yyact!=fts5YY_ERROR_ACTION );
+
+ fts5yymsp += fts5yysize+1;
+ fts5yypParser->fts5yytos = fts5yymsp;
+ fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
+ fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
+ fts5yyTraceShift(fts5yypParser, fts5yyact, "... then shift");
+ return fts5yyact;
+}
+
+/*
+** The following code executes when the parse fails
+*/
+#ifndef fts5YYNOERRORRECOVERY
+static void fts5yy_parse_failed(
+ fts5yyParser *fts5yypParser /* The parser */
+){
+ sqlite3Fts5ParserARG_FETCH
+ sqlite3Fts5ParserCTX_FETCH
+#ifndef NDEBUG
+ if( fts5yyTraceFILE ){
+ fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
+ }
+#endif
+ while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
+ /* Here code is inserted which will be executed whenever the
+ ** parser fails */
+/************ Begin %parse_failure code ***************************************/
+/************ End %parse_failure code *****************************************/
+ sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
+ sqlite3Fts5ParserCTX_STORE
+}
+#endif /* fts5YYNOERRORRECOVERY */
+
+/*
+** The following code executes when a syntax error first occurs.
+*/
+static void fts5yy_syntax_error(
+ fts5yyParser *fts5yypParser, /* The parser */
+ int fts5yymajor, /* The major type of the error token */
+ sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
+){
+ sqlite3Fts5ParserARG_FETCH
+ sqlite3Fts5ParserCTX_FETCH
+#define FTS5TOKEN fts5yyminor
+/************ Begin %syntax_error code ****************************************/
+
+ UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
+ sqlite3Fts5ParseError(
+ pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
+ );
+/************ End %syntax_error code ******************************************/
+ sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
+ sqlite3Fts5ParserCTX_STORE
+}
+
+/*
+** The following is executed when the parser accepts
+*/
+static void fts5yy_accept(
+ fts5yyParser *fts5yypParser /* The parser */
+){
+ sqlite3Fts5ParserARG_FETCH
+ sqlite3Fts5ParserCTX_FETCH
+#ifndef NDEBUG
+ if( fts5yyTraceFILE ){
+ fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
+ }
+#endif
+#ifndef fts5YYNOERRORRECOVERY
+ fts5yypParser->fts5yyerrcnt = -1;
+#endif
+ assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
+ /* Here code is inserted which will be executed whenever the
+ ** parser accepts */
+/*********** Begin %parse_accept code *****************************************/
+/*********** End %parse_accept code *******************************************/
+ sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
+ sqlite3Fts5ParserCTX_STORE
+}
+
+/* The main parser program.
+** The first argument is a pointer to a structure obtained from
+** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
+** The second argument is the major token number. The third is
+** the minor token. The fourth optional argument is whatever the
+** user wants (and specified in the grammar) and is available for
+** use by the action routines.
+**
+** Inputs:
+** <ul>
+** <li> A pointer to the parser (an opaque structure.)
+** <li> The major token number.
+** <li> The minor token number.
+** <li> An option argument of a grammar-specified type.
+** </ul>
+**
+** Outputs:
+** None.
+*/
+static void sqlite3Fts5Parser(
+ void *fts5yyp, /* The parser */
+ int fts5yymajor, /* The major token code number */
+ sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
+ sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
+){
+ fts5YYMINORTYPE fts5yyminorunion;
+ fts5YYACTIONTYPE fts5yyact; /* The parser action. */
+#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
+ int fts5yyendofinput; /* True if we are at the end of input */
+#endif
+#ifdef fts5YYERRORSYMBOL
+ int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
+#endif
+ fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yyp; /* The parser */
+ sqlite3Fts5ParserCTX_FETCH
+ sqlite3Fts5ParserARG_STORE
+
+ assert( fts5yypParser->fts5yytos!=0 );
+#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
+ fts5yyendofinput = (fts5yymajor==0);
+#endif
+
+ fts5yyact = fts5yypParser->fts5yytos->stateno;
+#ifndef NDEBUG
+ if( fts5yyTraceFILE ){
+ if( fts5yyact < fts5YY_MIN_REDUCE ){
+ fprintf(fts5yyTraceFILE,"%sInput '%s' in state %d\n",
+ fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact);
+ }else{
+ fprintf(fts5yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
+ fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact-fts5YY_MIN_REDUCE);
+ }
+ }
+#endif
+
+ do{
+ assert( fts5yyact==fts5yypParser->fts5yytos->stateno );
+ fts5yyact = fts5yy_find_shift_action((fts5YYCODETYPE)fts5yymajor,fts5yyact);
+ if( fts5yyact >= fts5YY_MIN_REDUCE ){
+ fts5yyact = fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE,fts5yymajor,
+ fts5yyminor sqlite3Fts5ParserCTX_PARAM);
+ }else if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
+ fts5yy_shift(fts5yypParser,fts5yyact,(fts5YYCODETYPE)fts5yymajor,fts5yyminor);
+#ifndef fts5YYNOERRORRECOVERY
+ fts5yypParser->fts5yyerrcnt--;
+#endif
+ break;
+ }else if( fts5yyact==fts5YY_ACCEPT_ACTION ){
+ fts5yypParser->fts5yytos--;
+ fts5yy_accept(fts5yypParser);
+ return;
+ }else{
+ assert( fts5yyact == fts5YY_ERROR_ACTION );
+ fts5yyminorunion.fts5yy0 = fts5yyminor;
+#ifdef fts5YYERRORSYMBOL
+ int fts5yymx;
+#endif
+#ifndef NDEBUG
+ if( fts5yyTraceFILE ){
+ fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
+ }
+#endif
+#ifdef fts5YYERRORSYMBOL
+ /* A syntax error has occurred.
+ ** The response to an error depends upon whether or not the
+ ** grammar defines an error token "ERROR".
+ **
+ ** This is what we do if the grammar does define ERROR:
+ **
+ ** * Call the %syntax_error function.
+ **
+ ** * Begin popping the stack until we enter a state where
+ ** it is legal to shift the error symbol, then shift
+ ** the error symbol.
+ **
+ ** * Set the error count to three.
+ **
+ ** * Begin accepting and shifting new tokens. No new error
+ ** processing will occur until three tokens have been
+ ** shifted successfully.
+ **
+ */
+ if( fts5yypParser->fts5yyerrcnt<0 ){
+ fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
+ }
+ fts5yymx = fts5yypParser->fts5yytos->major;
+ if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
+#ifndef NDEBUG
+ if( fts5yyTraceFILE ){
+ fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
+ fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
+ }
+#endif
+ fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
+ fts5yymajor = fts5YYNOCODE;
+ }else{
+ while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
+ && (fts5yyact = fts5yy_find_reduce_action(
+ fts5yypParser->fts5yytos->stateno,
+ fts5YYERRORSYMBOL)) > fts5YY_MAX_SHIFTREDUCE
+ ){
+ fts5yy_pop_parser_stack(fts5yypParser);
+ }
+ if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
+ fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
+ fts5yy_parse_failed(fts5yypParser);
+#ifndef fts5YYNOERRORRECOVERY
+ fts5yypParser->fts5yyerrcnt = -1;
+#endif
+ fts5yymajor = fts5YYNOCODE;
+ }else if( fts5yymx!=fts5YYERRORSYMBOL ){
+ fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
+ }
+ }
+ fts5yypParser->fts5yyerrcnt = 3;
+ fts5yyerrorhit = 1;
+ if( fts5yymajor==fts5YYNOCODE ) break;
+ fts5yyact = fts5yypParser->fts5yytos->stateno;
+#elif defined(fts5YYNOERRORRECOVERY)
+ /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
+ ** do any kind of error recovery. Instead, simply invoke the syntax
+ ** error routine and continue going as if nothing had happened.
+ **
+ ** Applications can set this macro (for example inside %include) if
+ ** they intend to abandon the parse upon the first syntax error seen.
+ */
+ fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
+ fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
+ break;
+#else /* fts5YYERRORSYMBOL is not defined */
+ /* This is what we do if the grammar does not define ERROR:
+ **
+ ** * Report an error message, and throw away the input token.
+ **
+ ** * If the input token is $, then fail the parse.
+ **
+ ** As before, subsequent error messages are suppressed until
+ ** three input tokens have been successfully shifted.
+ */
+ if( fts5yypParser->fts5yyerrcnt<=0 ){
+ fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
+ }
+ fts5yypParser->fts5yyerrcnt = 3;
+ fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
+ if( fts5yyendofinput ){
+ fts5yy_parse_failed(fts5yypParser);
+#ifndef fts5YYNOERRORRECOVERY
+ fts5yypParser->fts5yyerrcnt = -1;
+#endif
+ }
+ break;
+#endif
+ }
+ }while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
+#ifndef NDEBUG
+ if( fts5yyTraceFILE ){
+ fts5yyStackEntry *i;
+ char cDiv = '[';
+ fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
+ for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
+ fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
+ cDiv = ' ';
+ }
+ fprintf(fts5yyTraceFILE,"]\n");
+ }
+#endif
+ return;
+}
+
+/*
+** Return the fallback token corresponding to canonical token iToken, or
+** 0 if iToken has no fallback.
+*/
+static int sqlite3Fts5ParserFallback(int iToken){
+#ifdef fts5YYFALLBACK
+ assert( iToken<(int)(sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])) );
+ return fts5yyFallback[iToken];
+#else
+ (void)iToken;
+ return 0;
+#endif
+}
+
+/*
+** 2014 May 31
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+*/
+
+
+/* #include "fts5Int.h" */
+#include <math.h> /* amalgamator: keep */
+
+/*
+** Object used to iterate through all "coalesced phrase instances" in
+** a single column of the current row. If the phrase instances in the
+** column being considered do not overlap, this object simply iterates
+** through them. Or, if they do overlap (share one or more tokens in
+** common), each set of overlapping instances is treated as a single
+** match. See documentation for the highlight() auxiliary function for
+** details.
+**
+** Usage is:
+**
+** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
+** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
+** rc = fts5CInstIterNext(&iter)
+** ){
+** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
+** }
+**
+*/
+typedef struct CInstIter CInstIter;
+struct CInstIter {
+ const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
+ Fts5Context *pFts; /* First arg to pass to pApi functions */
+ int iCol; /* Column to search */
+ int iInst; /* Next phrase instance index */
+ int nInst; /* Total number of phrase instances */
+
+ /* Output variables */
+ int iStart; /* First token in coalesced phrase instance */
+ int iEnd; /* Last token in coalesced phrase instance */
+};
+
+/*
+** Advance the iterator to the next coalesced phrase instance. Return
+** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
+*/
+static int fts5CInstIterNext(CInstIter *pIter){
+ int rc = SQLITE_OK;
+ pIter->iStart = -1;
+ pIter->iEnd = -1;
+
+ while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
+ int ip; int ic; int io;
+ rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
+ if( rc==SQLITE_OK ){
+ if( ic==pIter->iCol ){
+ int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
+ if( pIter->iStart<0 ){
+ pIter->iStart = io;
+ pIter->iEnd = iEnd;
+ }else if( io<=pIter->iEnd ){
+ if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
+ }else{
+ break;
+ }
+ }
+ pIter->iInst++;
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Initialize the iterator object indicated by the final parameter to
+** iterate through coalesced phrase instances in column iCol.
+*/
+static int fts5CInstIterInit(
+ const Fts5ExtensionApi *pApi,
+ Fts5Context *pFts,
+ int iCol,
+ CInstIter *pIter
+){
+ int rc;
+
+ memset(pIter, 0, sizeof(CInstIter));
+ pIter->pApi = pApi;
+ pIter->pFts = pFts;
+ pIter->iCol = iCol;
+ rc = pApi->xInstCount(pFts, &pIter->nInst);
+
+ if( rc==SQLITE_OK ){
+ rc = fts5CInstIterNext(pIter);
+ }
+
+ return rc;
+}
+
+
+
+/*************************************************************************
+** Start of highlight() implementation.
+*/
+typedef struct HighlightContext HighlightContext;
+struct HighlightContext {
+ CInstIter iter; /* Coalesced Instance Iterator */
+ int iPos; /* Current token offset in zIn[] */
+ int iRangeStart; /* First token to include */
+ int iRangeEnd; /* If non-zero, last token to include */
+ const char *zOpen; /* Opening highlight */
+ const char *zClose; /* Closing highlight */
+ const char *zIn; /* Input text */
+ int nIn; /* Size of input text in bytes */
+ int iOff; /* Current offset within zIn[] */
+ char *zOut; /* Output value */
+};
+
+/*
+** Append text to the HighlightContext output string - p->zOut. Argument
+** z points to a buffer containing n bytes of text to append. If n is
+** negative, everything up until the first '\0' is appended to the output.
+**
+** If *pRc is set to any value other than SQLITE_OK when this function is
+** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
+** *pRc is set to an error code before returning.
+*/
+static void fts5HighlightAppend(
+ int *pRc,
+ HighlightContext *p,
+ const char *z, int n
+){
+ if( *pRc==SQLITE_OK && z ){
+ if( n<0 ) n = (int)strlen(z);
+ p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
+ if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
+ }
+}
+
+/*
+** Tokenizer callback used by implementation of highlight() function.
+*/
+static int fts5HighlightCb(
+ void *pContext, /* Pointer to HighlightContext object */
+ int tflags, /* Mask of FTS5_TOKEN_* flags */
+ const char *pToken, /* Buffer containing token */
+ int nToken, /* Size of token in bytes */
+ int iStartOff, /* Start offset of token */
+ int iEndOff /* End offset of token */
+){
+ HighlightContext *p = (HighlightContext*)pContext;
+ int rc = SQLITE_OK;
+ int iPos;
+
+ UNUSED_PARAM2(pToken, nToken);
+
+ if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
+ iPos = p->iPos++;
+
+ if( p->iRangeEnd>0 ){
+ if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
+ if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
+ }
+
+ if( iPos==p->iter.iStart ){
+ fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
+ fts5HighlightAppend(&rc, p, p->zOpen, -1);
+ p->iOff = iStartOff;
+ }
+
+ if( iPos==p->iter.iEnd ){
+ if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
+ fts5HighlightAppend(&rc, p, p->zOpen, -1);
+ }
+ fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
+ fts5HighlightAppend(&rc, p, p->zClose, -1);
+ p->iOff = iEndOff;
+ if( rc==SQLITE_OK ){
+ rc = fts5CInstIterNext(&p->iter);
+ }
+ }
+
+ if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
+ fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
+ p->iOff = iEndOff;
+ if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
+ fts5HighlightAppend(&rc, p, p->zClose, -1);
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Implementation of highlight() function.
+*/
+static void fts5HighlightFunction(
+ const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
+ Fts5Context *pFts, /* First arg to pass to pApi functions */
+ sqlite3_context *pCtx, /* Context for returning result/error */
+ int nVal, /* Number of values in apVal[] array */
+ sqlite3_value **apVal /* Array of trailing arguments */
+){
+ HighlightContext ctx;
+ int rc;
+ int iCol;
+
+ if( nVal!=3 ){
+ const char *zErr = "wrong number of arguments to function highlight()";
+ sqlite3_result_error(pCtx, zErr, -1);
+ return;
+ }
+
+ iCol = sqlite3_value_int(apVal[0]);
+ memset(&ctx, 0, sizeof(HighlightContext));
+ ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
+ ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
+ rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
+
+ if( ctx.zIn ){
+ if( rc==SQLITE_OK ){
+ rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
+ }
+ fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
+
+ if( rc==SQLITE_OK ){
+ sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
+ }
+ sqlite3_free(ctx.zOut);
+ }
+ if( rc!=SQLITE_OK ){
+ sqlite3_result_error_code(pCtx, rc);
+ }
+}
+/*
+** End of highlight() implementation.
+**************************************************************************/
+
+/*
+** Context object passed to the fts5SentenceFinderCb() function.
+*/
+typedef struct Fts5SFinder Fts5SFinder;
+struct Fts5SFinder {
+ int iPos; /* Current token position */
+ int nFirstAlloc; /* Allocated size of aFirst[] */
+ int nFirst; /* Number of entries in aFirst[] */
+ int *aFirst; /* Array of first token in each sentence */
+ const char *zDoc; /* Document being tokenized */
+};
+
+/*
+** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
+** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
+** error occurs.
+*/
+static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
+ if( p->nFirstAlloc==p->nFirst ){
+ int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
+ int *aNew;
+
+ aNew = (int*)sqlite3_realloc64(p->aFirst, nNew*sizeof(int));
+ if( aNew==0 ) return SQLITE_NOMEM;
+ p->aFirst = aNew;
+ p->nFirstAlloc = nNew;
+ }
+ p->aFirst[p->nFirst++] = iAdd;
+ return SQLITE_OK;
+}
+
+/*
+** This function is an xTokenize() callback used by the auxiliary snippet()
+** function. Its job is to identify tokens that are the first in a sentence.
+** For each such token, an entry is added to the SFinder.aFirst[] array.
+*/
+static int fts5SentenceFinderCb(
+ void *pContext, /* Pointer to HighlightContext object */
+ int tflags, /* Mask of FTS5_TOKEN_* flags */
+ const char *pToken, /* Buffer containing token */
+ int nToken, /* Size of token in bytes */
+ int iStartOff, /* Start offset of token */
+ int iEndOff /* End offset of token */
+){
+ int rc = SQLITE_OK;
+
+ UNUSED_PARAM2(pToken, nToken);
+ UNUSED_PARAM(iEndOff);
+
+ if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
+ Fts5SFinder *p = (Fts5SFinder*)pContext;
+ if( p->iPos>0 ){
+ int i;
+ char c = 0;
+ for(i=iStartOff-1; i>=0; i--){
+ c = p->zDoc[i];
+ if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
+ }
+ if( i!=iStartOff-1 && (c=='.' || c==':') ){
+ rc = fts5SentenceFinderAdd(p, p->iPos);
+ }
+ }else{
+ rc = fts5SentenceFinderAdd(p, 0);
+ }
+ p->iPos++;
+ }
+ return rc;
+}
+
+static int fts5SnippetScore(
+ const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
+ Fts5Context *pFts, /* First arg to pass to pApi functions */
+ int nDocsize, /* Size of column in tokens */
+ unsigned char *aSeen, /* Array with one element per query phrase */
+ int iCol, /* Column to score */
+ int iPos, /* Starting offset to score */
+ int nToken, /* Max tokens per snippet */
+ int *pnScore, /* OUT: Score */
+ int *piPos /* OUT: Adjusted offset */
+){
+ int rc;
+ int i;
+ int ip = 0;
+ int ic = 0;
+ int iOff = 0;
+ int iFirst = -1;
+ int nInst;
+ int nScore = 0;
+ int iLast = 0;
+ sqlite3_int64 iEnd = (sqlite3_int64)iPos + nToken;
+
+ rc = pApi->xInstCount(pFts, &nInst);
+ for(i=0; i<nInst && rc==SQLITE_OK; i++){
+ rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
+ if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<iEnd ){
+ nScore += (aSeen[ip] ? 1 : 1000);
+ aSeen[ip] = 1;
+ if( iFirst<0 ) iFirst = iOff;
+ iLast = iOff + pApi->xPhraseSize(pFts, ip);
+ }
+ }
+
+ *pnScore = nScore;
+ if( piPos ){
+ sqlite3_int64 iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
+ if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
+ if( iAdj<0 ) iAdj = 0;
+ *piPos = (int)iAdj;
+ }
+
+ return rc;
+}
+
+/*
+** Return the value in pVal interpreted as utf-8 text. Except, if pVal
+** contains a NULL value, return a pointer to a static string zero
+** bytes in length instead of a NULL pointer.
+*/
+static const char *fts5ValueToText(sqlite3_value *pVal){
+ const char *zRet = (const char*)sqlite3_value_text(pVal);
+ return zRet ? zRet : "";
+}
+
+/*
+** Implementation of snippet() function.
+*/
+static void fts5SnippetFunction(
+ const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
+ Fts5Context *pFts, /* First arg to pass to pApi functions */
+ sqlite3_context *pCtx, /* Context for returning result/error */
+ int nVal, /* Number of values in apVal[] array */
+ sqlite3_value **apVal /* Array of trailing arguments */
+){
+ HighlightContext ctx;
+ int rc = SQLITE_OK; /* Return code */
+ int iCol; /* 1st argument to snippet() */
+ const char *zEllips; /* 4th argument to snippet() */
+ int nToken; /* 5th argument to snippet() */
+ int nInst = 0; /* Number of instance matches this row */
+ int i; /* Used to iterate through instances */
+ int nPhrase; /* Number of phrases in query */
+ unsigned char *aSeen; /* Array of "seen instance" flags */
+ int iBestCol; /* Column containing best snippet */
+ int iBestStart = 0; /* First token of best snippet */
+ int nBestScore = 0; /* Score of best snippet */
+ int nColSize = 0; /* Total size of iBestCol in tokens */
+ Fts5SFinder sFinder; /* Used to find the beginnings of sentences */
+ int nCol;
+
+ if( nVal!=5 ){
+ const char *zErr = "wrong number of arguments to function snippet()";
+ sqlite3_result_error(pCtx, zErr, -1);
+ return;
+ }
+
+ nCol = pApi->xColumnCount(pFts);
+ memset(&ctx, 0, sizeof(HighlightContext));
+ iCol = sqlite3_value_int(apVal[0]);
+ ctx.zOpen = fts5ValueToText(apVal[1]);
+ ctx.zClose = fts5ValueToText(apVal[2]);
+ zEllips = fts5ValueToText(apVal[3]);
+ nToken = sqlite3_value_int(apVal[4]);
+
+ iBestCol = (iCol>=0 ? iCol : 0);
+ nPhrase = pApi->xPhraseCount(pFts);
+ aSeen = sqlite3_malloc(nPhrase);
+ if( aSeen==0 ){
+ rc = SQLITE_NOMEM;
+ }
+ if( rc==SQLITE_OK ){
+ rc = pApi->xInstCount(pFts, &nInst);
+ }
+
+ memset(&sFinder, 0, sizeof(Fts5SFinder));
+ for(i=0; i<nCol; i++){
+ if( iCol<0 || iCol==i ){
+ int nDoc;
+ int nDocsize;
+ int ii;
+ sFinder.iPos = 0;
+ sFinder.nFirst = 0;
+ rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
+ if( rc!=SQLITE_OK ) break;
+ rc = pApi->xTokenize(pFts,
+ sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
+ );
+ if( rc!=SQLITE_OK ) break;
+ rc = pApi->xColumnSize(pFts, i, &nDocsize);
+ if( rc!=SQLITE_OK ) break;
+
+ for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
+ int ip, ic, io;
+ int iAdj;
+ int nScore;
+ int jj;
+
+ rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
+ if( ic!=i ) continue;
+ if( io>nDocsize ) rc = FTS5_CORRUPT;
+ if( rc!=SQLITE_OK ) continue;
+ memset(aSeen, 0, nPhrase);
+ rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
+ io, nToken, &nScore, &iAdj
+ );
+ if( rc==SQLITE_OK && nScore>nBestScore ){
+ nBestScore = nScore;
+ iBestCol = i;
+ iBestStart = iAdj;
+ nColSize = nDocsize;
+ }
+
+ if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
+ for(jj=0; jj<(sFinder.nFirst-1); jj++){
+ if( sFinder.aFirst[jj+1]>io ) break;
+ }
+
+ if( sFinder.aFirst[jj]<io ){
+ memset(aSeen, 0, nPhrase);
+ rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
+ sFinder.aFirst[jj], nToken, &nScore, 0
+ );
+
+ nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
+ if( rc==SQLITE_OK && nScore>nBestScore ){
+ nBestScore = nScore;
+ iBestCol = i;
+ iBestStart = sFinder.aFirst[jj];
+ nColSize = nDocsize;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
+ }
+ if( rc==SQLITE_OK && nColSize==0 ){
+ rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
+ }
+ if( ctx.zIn ){
+ if( rc==SQLITE_OK ){
+ rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
+ }
+
+ ctx.iRangeStart = iBestStart;
+ ctx.iRangeEnd = iBestStart + nToken - 1;
+
+ if( iBestStart>0 ){
+ fts5HighlightAppend(&rc, &ctx, zEllips, -1);
+ }
+
+ /* Advance iterator ctx.iter so that it points to the first coalesced
+ ** phrase instance at or following position iBestStart. */
+ while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
+ rc = fts5CInstIterNext(&ctx.iter);
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
+ }
+ if( ctx.iRangeEnd>=(nColSize-1) ){
+ fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
+ }else{
+ fts5HighlightAppend(&rc, &ctx, zEllips, -1);
+ }
+ }
+ if( rc==SQLITE_OK ){
+ sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
+ }else{
+ sqlite3_result_error_code(pCtx, rc);
+ }
+ sqlite3_free(ctx.zOut);
+ sqlite3_free(aSeen);
+ sqlite3_free(sFinder.aFirst);
+}
+
+/************************************************************************/
+
+/*
+** The first time the bm25() function is called for a query, an instance
+** of the following structure is allocated and populated.
+*/
+typedef struct Fts5Bm25Data Fts5Bm25Data;
+struct Fts5Bm25Data {
+ int nPhrase; /* Number of phrases in query */
+ double avgdl; /* Average number of tokens in each row */
+ double *aIDF; /* IDF for each phrase */
+ double *aFreq; /* Array used to calculate phrase freq. */
+};
+
+/*
+** Callback used by fts5Bm25GetData() to count the number of rows in the
+** table matched by each individual phrase within the query.
+*/
+static int fts5CountCb(
+ const Fts5ExtensionApi *pApi,
+ Fts5Context *pFts,
+ void *pUserData /* Pointer to sqlite3_int64 variable */
+){
+ sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
+ UNUSED_PARAM2(pApi, pFts);
+ (*pn)++;
+ return SQLITE_OK;
+}
+
+/*
+** Set *ppData to point to the Fts5Bm25Data object for the current query.
+** If the object has not already been allocated, allocate and populate it
+** now.
+*/
+static int fts5Bm25GetData(
+ const Fts5ExtensionApi *pApi,
+ Fts5Context *pFts,
+ Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
+){
+ int rc = SQLITE_OK; /* Return code */
+ Fts5Bm25Data *p; /* Object to return */
+
+ p = pApi->xGetAuxdata(pFts, 0);
+ if( p==0 ){
+ int nPhrase; /* Number of phrases in query */
+ sqlite3_int64 nRow = 0; /* Number of rows in table */
+ sqlite3_int64 nToken = 0; /* Number of tokens in table */
+ sqlite3_int64 nByte; /* Bytes of space to allocate */
+ int i;
+
+ /* Allocate the Fts5Bm25Data object */
+ nPhrase = pApi->xPhraseCount(pFts);
+ nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
+ p = (Fts5Bm25Data*)sqlite3_malloc64(nByte);
+ if( p==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memset(p, 0, (size_t)nByte);
+ p->nPhrase = nPhrase;
+ p->aIDF = (double*)&p[1];
+ p->aFreq = &p->aIDF[nPhrase];
+ }
+
+ /* Calculate the average document length for this FTS5 table */
+ if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
+ assert( rc!=SQLITE_OK || nRow>0 );
+ if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
+ if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
+
+ /* Calculate an IDF for each phrase in the query */
+ for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
+ sqlite3_int64 nHit = 0;
+ rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
+ if( rc==SQLITE_OK ){
+ /* Calculate the IDF (Inverse Document Frequency) for phrase i.
+ ** This is done using the standard BM25 formula as found on wikipedia:
+ **
+ ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
+ **
+ ** where "N" is the total number of documents in the set and nHit
+ ** is the number that contain at least one instance of the phrase
+ ** under consideration.
+ **
+ ** The problem with this is that if (N < 2*nHit), the IDF is
+ ** negative. Which is undesirable. So the mimimum allowable IDF is
+ ** (1e-6) - roughly the same as a term that appears in just over
+ ** half of set of 5,000,000 documents. */
+ double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
+ if( idf<=0.0 ) idf = 1e-6;
+ p->aIDF[i] = idf;
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ sqlite3_free(p);
+ }else{
+ rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
+ }
+ if( rc!=SQLITE_OK ) p = 0;
+ }
+ *ppData = p;
+ return rc;
+}
+
+/*
+** Implementation of bm25() function.
+*/
+static void fts5Bm25Function(
+ const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
+ Fts5Context *pFts, /* First arg to pass to pApi functions */
+ sqlite3_context *pCtx, /* Context for returning result/error */
+ int nVal, /* Number of values in apVal[] array */
+ sqlite3_value **apVal /* Array of trailing arguments */
+){
+ const double k1 = 1.2; /* Constant "k1" from BM25 formula */
+ const double b = 0.75; /* Constant "b" from BM25 formula */
+ int rc = SQLITE_OK; /* Error code */
+ double score = 0.0; /* SQL function return value */
+ Fts5Bm25Data *pData; /* Values allocated/calculated once only */
+ int i; /* Iterator variable */
+ int nInst = 0; /* Value returned by xInstCount() */
+ double D = 0.0; /* Total number of tokens in row */
+ double *aFreq = 0; /* Array of phrase freq. for current row */
+
+ /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
+ ** for each phrase in the query for the current row. */
+ rc = fts5Bm25GetData(pApi, pFts, &pData);
+ if( rc==SQLITE_OK ){
+ aFreq = pData->aFreq;
+ memset(aFreq, 0, sizeof(double) * pData->nPhrase);
+ rc = pApi->xInstCount(pFts, &nInst);
+ }
+ for(i=0; rc==SQLITE_OK && i<nInst; i++){
+ int ip; int ic; int io;
+ rc = pApi->xInst(pFts, i, &ip, &ic, &io);
+ if( rc==SQLITE_OK ){
+ double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
+ aFreq[ip] += w;
+ }
+ }
+
+ /* Figure out the total size of the current row in tokens. */
+ if( rc==SQLITE_OK ){
+ int nTok;
+ rc = pApi->xColumnSize(pFts, -1, &nTok);
+ D = (double)nTok;
+ }
+
+ /* Determine the BM25 score for the current row. */
+ for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
+ score += pData->aIDF[i] * (
+ ( aFreq[i] * (k1 + 1.0) ) /
+ ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
+ );
+ }
+
+ /* If no error has occurred, return the calculated score. Otherwise,
+ ** throw an SQL exception. */
+ if( rc==SQLITE_OK ){
+ sqlite3_result_double(pCtx, -1.0 * score);
+ }else{
+ sqlite3_result_error_code(pCtx, rc);
+ }
+}
+
+static int sqlite3Fts5AuxInit(fts5_api *pApi){
+ struct Builtin {
+ const char *zFunc; /* Function name (nul-terminated) */
+ void *pUserData; /* User-data pointer */
+ fts5_extension_function xFunc;/* Callback function */
+ void (*xDestroy)(void*); /* Destructor function */
+ } aBuiltin [] = {
+ { "snippet", 0, fts5SnippetFunction, 0 },
+ { "highlight", 0, fts5HighlightFunction, 0 },
+ { "bm25", 0, fts5Bm25Function, 0 },
+ };
+ int rc = SQLITE_OK; /* Return code */
+ int i; /* To iterate through builtin functions */
+
+ for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
+ rc = pApi->xCreateFunction(pApi,
+ aBuiltin[i].zFunc,
+ aBuiltin[i].pUserData,
+ aBuiltin[i].xFunc,
+ aBuiltin[i].xDestroy
+ );
+ }
+
+ return rc;
+}
+
+/*
+** 2014 May 31
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+*/
+
+
+
+/* #include "fts5Int.h" */
+
+static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
+ if( (u32)pBuf->nSpace<nByte ){
+ u64 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
+ u8 *pNew;
+ while( nNew<nByte ){
+ nNew = nNew * 2;
+ }
+ pNew = sqlite3_realloc64(pBuf->p, nNew);
+ if( pNew==0 ){
+ *pRc = SQLITE_NOMEM;
+ return 1;
+ }else{
+ pBuf->nSpace = (int)nNew;
+ pBuf->p = pNew;
+ }
+ }
+ return 0;
+}
+
+
+/*
+** Encode value iVal as an SQLite varint and append it to the buffer object
+** pBuf. If an OOM error occurs, set the error code in p.
+*/
+static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
+ if( fts5BufferGrow(pRc, pBuf, 9) ) return;
+ pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
+}
+
+static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
+ aBuf[0] = (iVal>>24) & 0x00FF;
+ aBuf[1] = (iVal>>16) & 0x00FF;
+ aBuf[2] = (iVal>> 8) & 0x00FF;
+ aBuf[3] = (iVal>> 0) & 0x00FF;
+}
+
+static int sqlite3Fts5Get32(const u8 *aBuf){
+ return (int)((((u32)aBuf[0])<<24) + (aBuf[1]<<16) + (aBuf[2]<<8) + aBuf[3]);
+}
+
+/*
+** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
+** the error code in p. If an error has already occurred when this function
+** is called, it is a no-op.
+*/
+static void sqlite3Fts5BufferAppendBlob(
+ int *pRc,
+ Fts5Buffer *pBuf,
+ u32 nData,
+ const u8 *pData
+){
+ assert_nc( *pRc || nData>=0 );
+ if( nData ){
+ if( fts5BufferGrow(pRc, pBuf, nData) ) return;
+ memcpy(&pBuf->p[pBuf->n], pData, nData);
+ pBuf->n += nData;
+ }
+}
+
+/*
+** Append the nul-terminated string zStr to the buffer pBuf. This function
+** ensures that the byte following the buffer data is set to 0x00, even
+** though this byte is not included in the pBuf->n count.
+*/
+static void sqlite3Fts5BufferAppendString(
+ int *pRc,
+ Fts5Buffer *pBuf,
+ const char *zStr
+){
+ int nStr = (int)strlen(zStr);
+ sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
+ pBuf->n--;
+}
+
+/*
+** Argument zFmt is a printf() style format string. This function performs
+** the printf() style processing, then appends the results to buffer pBuf.
+**
+** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
+** following the buffer data is set to 0x00, even though this byte is not
+** included in the pBuf->n count.
+*/
+static void sqlite3Fts5BufferAppendPrintf(
+ int *pRc,
+ Fts5Buffer *pBuf,
+ char *zFmt, ...
+){
+ if( *pRc==SQLITE_OK ){
+ char *zTmp;
+ va_list ap;
+ va_start(ap, zFmt);
+ zTmp = sqlite3_vmprintf(zFmt, ap);
+ va_end(ap);
+
+ if( zTmp==0 ){
+ *pRc = SQLITE_NOMEM;
+ }else{
+ sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
+ sqlite3_free(zTmp);
+ }
+ }
+}
+
+static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
+ char *zRet = 0;
+ if( *pRc==SQLITE_OK ){
+ va_list ap;
+ va_start(ap, zFmt);
+ zRet = sqlite3_vmprintf(zFmt, ap);
+ va_end(ap);
+ if( zRet==0 ){
+ *pRc = SQLITE_NOMEM;
+ }
+ }
+ return zRet;
+}
+
+
+/*
+** Free any buffer allocated by pBuf. Zero the structure before returning.
+*/
+static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
+ sqlite3_free(pBuf->p);
+ memset(pBuf, 0, sizeof(Fts5Buffer));
+}
+
+/*
+** Zero the contents of the buffer object. But do not free the associated
+** memory allocation.
+*/
+static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
+ pBuf->n = 0;
+}
+
+/*
+** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
+** the error code in p. If an error has already occurred when this function
+** is called, it is a no-op.
+*/
+static void sqlite3Fts5BufferSet(
+ int *pRc,
+ Fts5Buffer *pBuf,
+ int nData,
+ const u8 *pData
+){
+ pBuf->n = 0;
+ sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
+}
+
+static int sqlite3Fts5PoslistNext64(
+ const u8 *a, int n, /* Buffer containing poslist */
+ int *pi, /* IN/OUT: Offset within a[] */
+ i64 *piOff /* IN/OUT: Current offset */
+){
+ int i = *pi;
+ if( i>=n ){
+ /* EOF */
+ *piOff = -1;
+ return 1;
+ }else{
+ i64 iOff = *piOff;
+ int iVal;
+ fts5FastGetVarint32(a, i, iVal);
+ if( iVal<=1 ){
+ if( iVal==0 ){
+ *pi = i;
+ return 0;
+ }
+ fts5FastGetVarint32(a, i, iVal);
+ iOff = ((i64)iVal) << 32;
+ fts5FastGetVarint32(a, i, iVal);
+ if( iVal<2 ){
+ /* This is a corrupt record. So stop parsing it here. */
+ *piOff = -1;
+ return 1;
+ }
+ }
+ *piOff = iOff + ((iVal-2) & 0x7FFFFFFF);
+ *pi = i;
+ return 0;
+ }
+}
+
+
+/*
+** Advance the iterator object passed as the only argument. Return true
+** if the iterator reaches EOF, or false otherwise.
+*/
+static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
+ if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
+ pIter->bEof = 1;
+ }
+ return pIter->bEof;
+}
+
+static int sqlite3Fts5PoslistReaderInit(
+ const u8 *a, int n, /* Poslist buffer to iterate through */
+ Fts5PoslistReader *pIter /* Iterator object to initialize */
+){
+ memset(pIter, 0, sizeof(*pIter));
+ pIter->a = a;
+ pIter->n = n;
+ sqlite3Fts5PoslistReaderNext(pIter);
+ return pIter->bEof;
+}
+
+/*
+** Append position iPos to the position list being accumulated in buffer
+** pBuf, which must be already be large enough to hold the new data.
+** The previous position written to this list is *piPrev. *piPrev is set
+** to iPos before returning.
+*/
+static void sqlite3Fts5PoslistSafeAppend(
+ Fts5Buffer *pBuf,
+ i64 *piPrev,
+ i64 iPos
+){
+ static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
+ if( (iPos & colmask) != (*piPrev & colmask) ){
+ pBuf->p[pBuf->n++] = 1;
+ pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
+ *piPrev = (iPos & colmask);
+ }
+ pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
+ *piPrev = iPos;
+}
+
+static int sqlite3Fts5PoslistWriterAppend(
+ Fts5Buffer *pBuf,
+ Fts5PoslistWriter *pWriter,
+ i64 iPos
+){
+ int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
+ if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
+ sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
+ return SQLITE_OK;
+}
+
+static void *sqlite3Fts5MallocZero(int *pRc, sqlite3_int64 nByte){
+ void *pRet = 0;
+ if( *pRc==SQLITE_OK ){
+ pRet = sqlite3_malloc64(nByte);
+ if( pRet==0 ){
+ if( nByte>0 ) *pRc = SQLITE_NOMEM;
+ }else{
+ memset(pRet, 0, (size_t)nByte);
+ }
+ }
+ return pRet;
+}
+
+/*
+** Return a nul-terminated copy of the string indicated by pIn. If nIn
+** is non-negative, then it is the length of the string in bytes. Otherwise,
+** the length of the string is determined using strlen().
+**
+** It is the responsibility of the caller to eventually free the returned
+** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
+*/
+static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
+ char *zRet = 0;
+ if( *pRc==SQLITE_OK ){
+ if( nIn<0 ){
+ nIn = (int)strlen(pIn);
+ }
+ zRet = (char*)sqlite3_malloc(nIn+1);
+ if( zRet ){
+ memcpy(zRet, pIn, nIn);
+ zRet[nIn] = '\0';
+ }else{
+ *pRc = SQLITE_NOMEM;
+ }
+ }
+ return zRet;
+}
+
+
+/*
+** Return true if character 't' may be part of an FTS5 bareword, or false
+** otherwise. Characters that may be part of barewords:
+**
+** * All non-ASCII characters,
+** * The 52 upper and lower case ASCII characters, and
+** * The 10 integer ASCII characters.
+** * The underscore character "_" (0x5F).
+** * The unicode "subsitute" character (0x1A).
+*/
+static int sqlite3Fts5IsBareword(char t){
+ u8 aBareword[128] = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
+ };
+
+ return (t & 0x80) || aBareword[(int)t];
+}
+
+
+/*************************************************************************
+*/
+typedef struct Fts5TermsetEntry Fts5TermsetEntry;
+struct Fts5TermsetEntry {
+ char *pTerm;
+ int nTerm;
+ int iIdx; /* Index (main or aPrefix[] entry) */
+ Fts5TermsetEntry *pNext;
+};
+
+struct Fts5Termset {
+ Fts5TermsetEntry *apHash[512];
+};
+
+static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
+ int rc = SQLITE_OK;
+ *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
+ return rc;
+}
+
+static int sqlite3Fts5TermsetAdd(
+ Fts5Termset *p,
+ int iIdx,
+ const char *pTerm, int nTerm,
+ int *pbPresent
+){
+ int rc = SQLITE_OK;
+ *pbPresent = 0;
+ if( p ){
+ int i;
+ u32 hash = 13;
+ Fts5TermsetEntry *pEntry;
+
+ /* Calculate a hash value for this term. This is the same hash checksum
+ ** used by the fts5_hash.c module. This is not important for correct
+ ** operation of the module, but is necessary to ensure that some tests
+ ** designed to produce hash table collisions really do work. */
+ for(i=nTerm-1; i>=0; i--){
+ hash = (hash << 3) ^ hash ^ pTerm[i];
+ }
+ hash = (hash << 3) ^ hash ^ iIdx;
+ hash = hash % ArraySize(p->apHash);
+
+ for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
+ if( pEntry->iIdx==iIdx
+ && pEntry->nTerm==nTerm
+ && memcmp(pEntry->pTerm, pTerm, nTerm)==0
+ ){
+ *pbPresent = 1;
+ break;
+ }
+ }
+
+ if( pEntry==0 ){
+ pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
+ if( pEntry ){
+ pEntry->pTerm = (char*)&pEntry[1];
+ pEntry->nTerm = nTerm;
+ pEntry->iIdx = iIdx;
+ memcpy(pEntry->pTerm, pTerm, nTerm);
+ pEntry->pNext = p->apHash[hash];
+ p->apHash[hash] = pEntry;
+ }
+ }
+ }
+
+ return rc;
+}
+
+static void sqlite3Fts5TermsetFree(Fts5Termset *p){
+ if( p ){
+ u32 i;
+ for(i=0; i<ArraySize(p->apHash); i++){
+ Fts5TermsetEntry *pEntry = p->apHash[i];
+ while( pEntry ){
+ Fts5TermsetEntry *pDel = pEntry;
+ pEntry = pEntry->pNext;
+ sqlite3_free(pDel);
+ }
+ }
+ sqlite3_free(p);
+ }
+}
+
+/*
+** 2014 Jun 09
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This is an SQLite module implementing full-text search.
+*/
+
+
+/* #include "fts5Int.h" */
+
+#define FTS5_DEFAULT_PAGE_SIZE 4050
+#define FTS5_DEFAULT_AUTOMERGE 4
+#define FTS5_DEFAULT_USERMERGE 4
+#define FTS5_DEFAULT_CRISISMERGE 16
+#define FTS5_DEFAULT_HASHSIZE (1024*1024)
+
+/* Maximum allowed page size */
+#define FTS5_MAX_PAGE_SIZE (64*1024)
+
+static int fts5_iswhitespace(char x){
+ return (x==' ');
+}
+
+static int fts5_isopenquote(char x){
+ return (x=='"' || x=='\'' || x=='[' || x=='`');
+}
+
+/*
+** Argument pIn points to a character that is part of a nul-terminated
+** string. Return a pointer to the first character following *pIn in
+** the string that is not a white-space character.
+*/
+static const char *fts5ConfigSkipWhitespace(const char *pIn){
+ const char *p = pIn;
+ if( p ){
+ while( fts5_iswhitespace(*p) ){ p++; }
+ }
+ return p;
+}
+
+/*
+** Argument pIn points to a character that is part of a nul-terminated
+** string. Return a pointer to the first character following *pIn in
+** the string that is not a "bareword" character.
+*/
+static const char *fts5ConfigSkipBareword(const char *pIn){
+ const char *p = pIn;
+ while ( sqlite3Fts5IsBareword(*p) ) p++;
+ if( p==pIn ) p = 0;
+ return p;
+}
+
+static int fts5_isdigit(char a){
+ return (a>='0' && a<='9');
+}
+
+
+
+static const char *fts5ConfigSkipLiteral(const char *pIn){
+ const char *p = pIn;
+ switch( *p ){
+ case 'n': case 'N':
+ if( sqlite3_strnicmp("null", p, 4)==0 ){
+ p = &p[4];
+ }else{
+ p = 0;
+ }
+ break;
+
+ case 'x': case 'X':
+ p++;
+ if( *p=='\'' ){
+ p++;
+ while( (*p>='a' && *p<='f')
+ || (*p>='A' && *p<='F')
+ || (*p>='0' && *p<='9')
+ ){
+ p++;
+ }
+ if( *p=='\'' && 0==((p-pIn)%2) ){
+ p++;
+ }else{
+ p = 0;
+ }
+ }else{
+ p = 0;
+ }
+ break;
+
+ case '\'':
+ p++;
+ while( p ){
+ if( *p=='\'' ){
+ p++;
+ if( *p!='\'' ) break;
+ }
+ p++;
+ if( *p==0 ) p = 0;
+ }
+ break;
+
+ default:
+ /* maybe a number */
+ if( *p=='+' || *p=='-' ) p++;
+ while( fts5_isdigit(*p) ) p++;
+
+ /* At this point, if the literal was an integer, the parse is
+ ** finished. Or, if it is a floating point value, it may continue
+ ** with either a decimal point or an 'E' character. */
+ if( *p=='.' && fts5_isdigit(p[1]) ){
+ p += 2;
+ while( fts5_isdigit(*p) ) p++;
+ }
+ if( p==pIn ) p = 0;
+
+ break;
+ }
+
+ return p;
+}
+
+/*
+** The first character of the string pointed to by argument z is guaranteed
+** to be an open-quote character (see function fts5_isopenquote()).
+**
+** This function searches for the corresponding close-quote character within
+** the string and, if found, dequotes the string in place and adds a new
+** nul-terminator byte.
+**
+** If the close-quote is found, the value returned is the byte offset of
+** the character immediately following it. Or, if the close-quote is not
+** found, -1 is returned. If -1 is returned, the buffer is left in an
+** undefined state.
+*/
+static int fts5Dequote(char *z){
+ char q;
+ int iIn = 1;
+ int iOut = 0;
+ q = z[0];
+
+ /* Set stack variable q to the close-quote character */
+ assert( q=='[' || q=='\'' || q=='"' || q=='`' );
+ if( q=='[' ) q = ']';
+
+ while( z[iIn] ){
+ if( z[iIn]==q ){
+ if( z[iIn+1]!=q ){
+ /* Character iIn was the close quote. */
+ iIn++;
+ break;
+ }else{
+ /* Character iIn and iIn+1 form an escaped quote character. Skip
+ ** the input cursor past both and copy a single quote character
+ ** to the output buffer. */
+ iIn += 2;
+ z[iOut++] = q;
+ }
+ }else{
+ z[iOut++] = z[iIn++];
+ }
+ }
+
+ z[iOut] = '\0';
+ return iIn;
+}
+
+/*
+** Convert an SQL-style quoted string into a normal string by removing
+** the quote characters. The conversion is done in-place. If the
+** input does not begin with a quote character, then this routine
+** is a no-op.
+**
+** Examples:
+**
+** "abc" becomes abc
+** 'xyz' becomes xyz
+** [pqr] becomes pqr
+** `mno` becomes mno
+*/
+static void sqlite3Fts5Dequote(char *z){
+ char quote; /* Quote character (if any ) */
+
+ assert( 0==fts5_iswhitespace(z[0]) );
+ quote = z[0];
+ if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
+ fts5Dequote(z);
+ }
+}
+
+
+struct Fts5Enum {
+ const char *zName;
+ int eVal;
+};
+typedef struct Fts5Enum Fts5Enum;
+
+static int fts5ConfigSetEnum(
+ const Fts5Enum *aEnum,
+ const char *zEnum,
+ int *peVal
+){
+ int nEnum = (int)strlen(zEnum);
+ int i;
+ int iVal = -1;
+
+ for(i=0; aEnum[i].zName; i++){
+ if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
+ if( iVal>=0 ) return SQLITE_ERROR;
+ iVal = aEnum[i].eVal;
+ }
+ }
+
+ *peVal = iVal;
+ return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
+}
+
+/*
+** Parse a "special" CREATE VIRTUAL TABLE directive and update
+** configuration object pConfig as appropriate.
+**
+** If successful, object pConfig is updated and SQLITE_OK returned. If
+** an error occurs, an SQLite error code is returned and an error message
+** may be left in *pzErr. It is the responsibility of the caller to
+** eventually free any such error message using sqlite3_free().
+*/
+static int fts5ConfigParseSpecial(
+ Fts5Global *pGlobal,
+ Fts5Config *pConfig, /* Configuration object to update */
+ const char *zCmd, /* Special command to parse */
+ const char *zArg, /* Argument to parse */
+ char **pzErr /* OUT: Error message */
+){
+ int rc = SQLITE_OK;
+ int nCmd = (int)strlen(zCmd);
+ if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
+ const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
+ const char *p;
+ int bFirst = 1;
+ if( pConfig->aPrefix==0 ){
+ pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
+ if( rc ) return rc;
+ }
+
+ p = zArg;
+ while( 1 ){
+ int nPre = 0;
+
+ while( p[0]==' ' ) p++;
+ if( bFirst==0 && p[0]==',' ){
+ p++;
+ while( p[0]==' ' ) p++;
+ }else if( p[0]=='\0' ){
+ break;
+ }
+ if( p[0]<'0' || p[0]>'9' ){
+ *pzErr = sqlite3_mprintf("malformed prefix=... directive");
+ rc = SQLITE_ERROR;
+ break;
+ }
+
+ if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
+ *pzErr = sqlite3_mprintf(
+ "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
+ );
+ rc = SQLITE_ERROR;
+ break;
+ }
+
+ while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
+ nPre = nPre*10 + (p[0] - '0');
+ p++;
+ }
+
+ if( nPre<=0 || nPre>=1000 ){
+ *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
+ rc = SQLITE_ERROR;
+ break;
+ }
+
+ pConfig->aPrefix[pConfig->nPrefix] = nPre;
+ pConfig->nPrefix++;
+ bFirst = 0;
+ }
+ assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
+ return rc;
+ }
+
+ if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
+ const char *p = (const char*)zArg;
+ sqlite3_int64 nArg = strlen(zArg) + 1;
+ char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
+ char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
+ char *pSpace = pDel;
+
+ if( azArg && pSpace ){
+ if( pConfig->pTok ){
+ *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
+ rc = SQLITE_ERROR;
+ }else{
+ for(nArg=0; p && *p; nArg++){
+ const char *p2 = fts5ConfigSkipWhitespace(p);
+ if( *p2=='\'' ){
+ p = fts5ConfigSkipLiteral(p2);
+ }else{
+ p = fts5ConfigSkipBareword(p2);
+ }
+ if( p ){
+ memcpy(pSpace, p2, p-p2);
+ azArg[nArg] = pSpace;
+ sqlite3Fts5Dequote(pSpace);
+ pSpace += (p - p2) + 1;
+ p = fts5ConfigSkipWhitespace(p);
+ }
+ }
+ if( p==0 ){
+ *pzErr = sqlite3_mprintf("parse error in tokenize directive");
+ rc = SQLITE_ERROR;
+ }else{
+ rc = sqlite3Fts5GetTokenizer(pGlobal,
+ (const char**)azArg, (int)nArg, pConfig,
+ pzErr
+ );
+ }
+ }
+ }
+
+ sqlite3_free(azArg);
+ sqlite3_free(pDel);
+ return rc;
+ }
+
+ if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
+ if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
+ *pzErr = sqlite3_mprintf("multiple content=... directives");
+ rc = SQLITE_ERROR;
+ }else{
+ if( zArg[0] ){
+ pConfig->eContent = FTS5_CONTENT_EXTERNAL;
+ pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
+ }else{
+ pConfig->eContent = FTS5_CONTENT_NONE;
+ }
+ }
+ return rc;
+ }
+
+ if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
+ if( pConfig->zContentRowid ){
+ *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
+ rc = SQLITE_ERROR;
+ }else{
+ pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
+ }
+ return rc;
+ }
+
+ if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
+ if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
+ *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
+ rc = SQLITE_ERROR;
+ }else{
+ pConfig->bColumnsize = (zArg[0]=='1');
+ }
+ return rc;
+ }
+
+ if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
+ const Fts5Enum aDetail[] = {
+ { "none", FTS5_DETAIL_NONE },
+ { "full", FTS5_DETAIL_FULL },
+ { "columns", FTS5_DETAIL_COLUMNS },
+ { 0, 0 }
+ };
+
+ if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
+ *pzErr = sqlite3_mprintf("malformed detail=... directive");
+ }
+ return rc;
+ }
+
+ *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
+ return SQLITE_ERROR;
+}
+
+/*
+** Allocate an instance of the default tokenizer ("simple") at
+** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
+** code if an error occurs.
+*/
+static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
+ assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
+ return sqlite3Fts5GetTokenizer(pGlobal, 0, 0, pConfig, 0);
+}
+
+/*
+** Gobble up the first bareword or quoted word from the input buffer zIn.
+** Return a pointer to the character immediately following the last in
+** the gobbled word if successful, or a NULL pointer otherwise (failed
+** to find close-quote character).
+**
+** Before returning, set pzOut to point to a new buffer containing a
+** nul-terminated, dequoted copy of the gobbled word. If the word was
+** quoted, *pbQuoted is also set to 1 before returning.
+**
+** If *pRc is other than SQLITE_OK when this function is called, it is
+** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
+** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
+** set if a parse error (failed to find close quote) occurs.
+*/
+static const char *fts5ConfigGobbleWord(
+ int *pRc, /* IN/OUT: Error code */
+ const char *zIn, /* Buffer to gobble string/bareword from */
+ char **pzOut, /* OUT: malloc'd buffer containing str/bw */
+ int *pbQuoted /* OUT: Set to true if dequoting required */
+){
+ const char *zRet = 0;
+
+ sqlite3_int64 nIn = strlen(zIn);
+ char *zOut = sqlite3_malloc64(nIn+1);
+
+ assert( *pRc==SQLITE_OK );
+ *pbQuoted = 0;
+ *pzOut = 0;
+
+ if( zOut==0 ){
+ *pRc = SQLITE_NOMEM;
+ }else{
+ memcpy(zOut, zIn, (size_t)(nIn+1));
+ if( fts5_isopenquote(zOut[0]) ){
+ int ii = fts5Dequote(zOut);
+ zRet = &zIn[ii];
+ *pbQuoted = 1;
+ }else{
+ zRet = fts5ConfigSkipBareword(zIn);
+ if( zRet ){
+ zOut[zRet-zIn] = '\0';
+ }
+ }
+ }
+
+ if( zRet==0 ){
+ sqlite3_free(zOut);
+ }else{
+ *pzOut = zOut;
+ }
+
+ return zRet;
+}
+
+static int fts5ConfigParseColumn(
+ Fts5Config *p,
+ char *zCol,
+ char *zArg,
+ char **pzErr
+){
+ int rc = SQLITE_OK;
+ if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
+ || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
+ ){
+ *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
+ rc = SQLITE_ERROR;
+ }else if( zArg ){
+ if( 0==sqlite3_stricmp(zArg, "unindexed") ){
+ p->abUnindexed[p->nCol] = 1;
+ }else{
+ *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
+ rc = SQLITE_ERROR;
+ }
+ }
+
+ p->azCol[p->nCol++] = zCol;
+ return rc;
+}
+
+/*
+** Populate the Fts5Config.zContentExprlist string.
+*/
+static int fts5ConfigMakeExprlist(Fts5Config *p){
+ int i;
+ int rc = SQLITE_OK;
+ Fts5Buffer buf = {0, 0, 0};
+
+ sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
+ if( p->eContent!=FTS5_CONTENT_NONE ){
+ for(i=0; i<p->nCol; i++){
+ if( p->eContent==FTS5_CONTENT_EXTERNAL ){
+ sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
+ }else{
+ sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
+ }
+ }
+ }
+
+ assert( p->zContentExprlist==0 );
+ p->zContentExprlist = (char*)buf.p;
+ return rc;
+}
+
+/*
+** Arguments nArg/azArg contain the string arguments passed to the xCreate
+** or xConnect method of the virtual table. This function attempts to
+** allocate an instance of Fts5Config containing the results of parsing
+** those arguments.
+**
+** If successful, SQLITE_OK is returned and *ppOut is set to point to the
+** new Fts5Config object. If an error occurs, an SQLite error code is
+** returned, *ppOut is set to NULL and an error message may be left in
+** *pzErr. It is the responsibility of the caller to eventually free any
+** such error message using sqlite3_free().
+*/
+static int sqlite3Fts5ConfigParse(
+ Fts5Global *pGlobal,
+ sqlite3 *db,
+ int nArg, /* Number of arguments */
+ const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
+ Fts5Config **ppOut, /* OUT: Results of parse */
+ char **pzErr /* OUT: Error message */
+){
+ int rc = SQLITE_OK; /* Return code */
+ Fts5Config *pRet; /* New object to return */
+ int i;
+ sqlite3_int64 nByte;
+
+ *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
+ if( pRet==0 ) return SQLITE_NOMEM;
+ memset(pRet, 0, sizeof(Fts5Config));
+ pRet->db = db;
+ pRet->iCookie = -1;
+
+ nByte = nArg * (sizeof(char*) + sizeof(u8));
+ pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
+ pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
+ pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
+ pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
+ pRet->bColumnsize = 1;
+ pRet->eDetail = FTS5_DETAIL_FULL;
+#ifdef SQLITE_DEBUG
+ pRet->bPrefixIndex = 1;
+#endif
+ if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
+ *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
+ rc = SQLITE_ERROR;
+ }
+
+ for(i=3; rc==SQLITE_OK && i<nArg; i++){
+ const char *zOrig = azArg[i];
+ const char *z;
+ char *zOne = 0;
+ char *zTwo = 0;
+ int bOption = 0;
+ int bMustBeCol = 0;
+
+ z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
+ z = fts5ConfigSkipWhitespace(z);
+ if( z && *z=='=' ){
+ bOption = 1;
+ z++;
+ if( bMustBeCol ) z = 0;
+ }
+ z = fts5ConfigSkipWhitespace(z);
+ if( z && z[0] ){
+ int bDummy;
+ z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
+ if( z && z[0] ) z = 0;
+ }
+
+ if( rc==SQLITE_OK ){
+ if( z==0 ){
+ *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
+ rc = SQLITE_ERROR;
+ }else{
+ if( bOption ){
+ rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
+ }else{
+ rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
+ zOne = 0;
+ }
+ }
+ }
+
+ sqlite3_free(zOne);
+ sqlite3_free(zTwo);
+ }
+
+ /* If a tokenizer= option was successfully parsed, the tokenizer has
+ ** already been allocated. Otherwise, allocate an instance of the default
+ ** tokenizer (unicode61) now. */
+ if( rc==SQLITE_OK && pRet->pTok==0 ){
+ rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
+ }
+
+ /* If no zContent option was specified, fill in the default values. */
+ if( rc==SQLITE_OK && pRet->zContent==0 ){
+ const char *zTail = 0;
+ assert( pRet->eContent==FTS5_CONTENT_NORMAL
+ || pRet->eContent==FTS5_CONTENT_NONE
+ );
+ if( pRet->eContent==FTS5_CONTENT_NORMAL ){
+ zTail = "content";
+ }else if( pRet->bColumnsize ){
+ zTail = "docsize";
+ }
+
+ if( zTail ){
+ pRet->zContent = sqlite3Fts5Mprintf(
+ &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
+ );
+ }
+ }
+
+ if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
+ pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
+ }
+
+ /* Formulate the zContentExprlist text */
+ if( rc==SQLITE_OK ){
+ rc = fts5ConfigMakeExprlist(pRet);
+ }
+
+ if( rc!=SQLITE_OK ){
+ sqlite3Fts5ConfigFree(pRet);
+ *ppOut = 0;
+ }
+ return rc;
+}
+
+/*
+** Free the configuration object passed as the only argument.
+*/
+static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
+ if( pConfig ){
+ int i;
+ if( pConfig->pTok ){
+ pConfig->pTokApi->xDelete(pConfig->pTok);
+ }
+ sqlite3_free(pConfig->zDb);
+ sqlite3_free(pConfig->zName);
+ for(i=0; i<pConfig->nCol; i++){
+ sqlite3_free(pConfig->azCol[i]);
+ }
+ sqlite3_free(pConfig->azCol);
+ sqlite3_free(pConfig->aPrefix);
+ sqlite3_free(pConfig->zRank);
+ sqlite3_free(pConfig->zRankArgs);
+ sqlite3_free(pConfig->zContent);
+ sqlite3_free(pConfig->zContentRowid);
+ sqlite3_free(pConfig->zContentExprlist);
+ sqlite3_free(pConfig);
+ }
+}
+
+/*
+** Call sqlite3_declare_vtab() based on the contents of the configuration
+** object passed as the only argument. Return SQLITE_OK if successful, or
+** an SQLite error code if an error occurs.
+*/
+static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
+ int i;
+ int rc = SQLITE_OK;
+ char *zSql;
+
+ zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
+ for(i=0; zSql && i<pConfig->nCol; i++){
+ const char *zSep = (i==0?"":", ");
+ zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
+ }
+ zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
+ zSql, pConfig->zName, FTS5_RANK_NAME
+ );
+
+ assert( zSql || rc==SQLITE_NOMEM );
+ if( zSql ){
+ rc = sqlite3_declare_vtab(pConfig->db, zSql);
+ sqlite3_free(zSql);
+ }
+
+ return rc;
+}
+
+/*
+** Tokenize the text passed via the second and third arguments.
+**
+** The callback is invoked once for each token in the input text. The
+** arguments passed to it are, in order:
+**
+** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
+** const char *pToken // Pointer to buffer containing token
+** int nToken // Size of token in bytes
+** int iStart // Byte offset of start of token within input text
+** int iEnd // Byte offset of end of token within input text
+** int iPos // Position of token in input (first token is 0)
+**
+** If the callback returns a non-zero value the tokenization is abandoned
+** and no further callbacks are issued.
+**
+** This function returns SQLITE_OK if successful or an SQLite error code
+** if an error occurs. If the tokenization was abandoned early because
+** the callback returned SQLITE_DONE, this is not an error and this function
+** still returns SQLITE_OK. Or, if the tokenization was abandoned early
+** because the callback returned another non-zero value, it is assumed
+** to be an SQLite error code and returned to the caller.
+*/
+static int sqlite3Fts5Tokenize(
+ Fts5Config *pConfig, /* FTS5 Configuration object */
+ int flags, /* FTS5_TOKENIZE_* flags */
+ const char *pText, int nText, /* Text to tokenize */
+ void *pCtx, /* Context passed to xToken() */
+ int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
+){
+ if( pText==0 ) return SQLITE_OK;
+ return pConfig->pTokApi->xTokenize(
+ pConfig->pTok, pCtx, flags, pText, nText, xToken
+ );
+}
+
+/*
+** Argument pIn points to the first character in what is expected to be
+** a comma-separated list of SQL literals followed by a ')' character.
+** If it actually is this, return a pointer to the ')'. Otherwise, return
+** NULL to indicate a parse error.
+*/
+static const char *fts5ConfigSkipArgs(const char *pIn){
+ const char *p = pIn;
+
+ while( 1 ){
+ p = fts5ConfigSkipWhitespace(p);
+ p = fts5ConfigSkipLiteral(p);
+ p = fts5ConfigSkipWhitespace(p);
+ if( p==0 || *p==')' ) break;
+ if( *p!=',' ){
+ p = 0;
+ break;
+ }
+ p++;
+ }
+
+ return p;
+}
+
+/*
+** Parameter zIn contains a rank() function specification. The format of
+** this is:
+**
+** + Bareword (function name)
+** + Open parenthesis - "("
+** + Zero or more SQL literals in a comma separated list
+** + Close parenthesis - ")"
+*/
+static int sqlite3Fts5ConfigParseRank(
+ const char *zIn, /* Input string */
+ char **pzRank, /* OUT: Rank function name */
+ char **pzRankArgs /* OUT: Rank function arguments */
+){
+ const char *p = zIn;
+ const char *pRank;
+ char *zRank = 0;
+ char *zRankArgs = 0;
+ int rc = SQLITE_OK;
+
+ *pzRank = 0;
+ *pzRankArgs = 0;
+
+ if( p==0 ){
+ rc = SQLITE_ERROR;
+ }else{
+ p = fts5ConfigSkipWhitespace(p);
+ pRank = p;
+ p = fts5ConfigSkipBareword(p);
+
+ if( p ){
+ zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
+ if( zRank ) memcpy(zRank, pRank, p-pRank);
+ }else{
+ rc = SQLITE_ERROR;
+ }
+
+ if( rc==SQLITE_OK ){
+ p = fts5ConfigSkipWhitespace(p);
+ if( *p!='(' ) rc = SQLITE_ERROR;
+ p++;
+ }
+ if( rc==SQLITE_OK ){
+ const char *pArgs;
+ p = fts5ConfigSkipWhitespace(p);
+ pArgs = p;
+ if( *p!=')' ){
+ p = fts5ConfigSkipArgs(p);
+ if( p==0 ){
+ rc = SQLITE_ERROR;
+ }else{
+ zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
+ if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
+ }
+ }
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ sqlite3_free(zRank);
+ assert( zRankArgs==0 );
+ }else{
+ *pzRank = zRank;
+ *pzRankArgs = zRankArgs;
+ }
+ return rc;
+}
+
+static int sqlite3Fts5ConfigSetValue(
+ Fts5Config *pConfig,
+ const char *zKey,
+ sqlite3_value *pVal,
+ int *pbBadkey
+){
+ int rc = SQLITE_OK;
+
+ if( 0==sqlite3_stricmp(zKey, "pgsz") ){
+ int pgsz = 0;
+ if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
+ pgsz = sqlite3_value_int(pVal);
+ }
+ if( pgsz<32 || pgsz>FTS5_MAX_PAGE_SIZE ){
+ *pbBadkey = 1;
+ }else{
+ pConfig->pgsz = pgsz;
+ }
+ }
+
+ else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
+ int nHashSize = -1;
+ if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
+ nHashSize = sqlite3_value_int(pVal);
+ }
+ if( nHashSize<=0 ){
+ *pbBadkey = 1;
+ }else{
+ pConfig->nHashSize = nHashSize;
+ }
+ }
+
+ else if( 0==sqlite3_stricmp(zKey, "automerge") ){
+ int nAutomerge = -1;
+ if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
+ nAutomerge = sqlite3_value_int(pVal);
+ }
+ if( nAutomerge<0 || nAutomerge>64 ){
+ *pbBadkey = 1;
+ }else{
+ if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
+ pConfig->nAutomerge = nAutomerge;
+ }
+ }
+
+ else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
+ int nUsermerge = -1;
+ if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
+ nUsermerge = sqlite3_value_int(pVal);
+ }
+ if( nUsermerge<2 || nUsermerge>16 ){
+ *pbBadkey = 1;
+ }else{
+ pConfig->nUsermerge = nUsermerge;
+ }
+ }
+
+ else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
+ int nCrisisMerge = -1;
+ if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
+ nCrisisMerge = sqlite3_value_int(pVal);
+ }
+ if( nCrisisMerge<0 ){
+ *pbBadkey = 1;
+ }else{
+ if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
+ if( nCrisisMerge>=FTS5_MAX_SEGMENT ) nCrisisMerge = FTS5_MAX_SEGMENT-1;
+ pConfig->nCrisisMerge = nCrisisMerge;
+ }
+ }
+
+ else if( 0==sqlite3_stricmp(zKey, "rank") ){
+ const char *zIn = (const char*)sqlite3_value_text(pVal);
+ char *zRank;
+ char *zRankArgs;
+ rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
+ if( rc==SQLITE_OK ){
+ sqlite3_free(pConfig->zRank);
+ sqlite3_free(pConfig->zRankArgs);
+ pConfig->zRank = zRank;
+ pConfig->zRankArgs = zRankArgs;
+ }else if( rc==SQLITE_ERROR ){
+ rc = SQLITE_OK;
+ *pbBadkey = 1;
+ }
+ }else{
+ *pbBadkey = 1;
+ }
+ return rc;
+}
+
+/*
+** Load the contents of the %_config table into memory.
+*/
+static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
+ const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
+ char *zSql;
+ sqlite3_stmt *p = 0;
+ int rc = SQLITE_OK;
+ int iVersion = 0;
+
+ /* Set default values */
+ pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
+ pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
+ pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
+ pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
+ pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
+
+ zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
+ if( zSql ){
+ rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
+ sqlite3_free(zSql);
+ }
+
+ assert( rc==SQLITE_OK || p==0 );
+ if( rc==SQLITE_OK ){
+ while( SQLITE_ROW==sqlite3_step(p) ){
+ const char *zK = (const char*)sqlite3_column_text(p, 0);
+ sqlite3_value *pVal = sqlite3_column_value(p, 1);
+ if( 0==sqlite3_stricmp(zK, "version") ){
+ iVersion = sqlite3_value_int(pVal);
+ }else{
+ int bDummy = 0;
+ sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
+ }
+ }
+ rc = sqlite3_finalize(p);
+ }
+
+ if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
+ rc = SQLITE_ERROR;
+ if( pConfig->pzErrmsg ){
+ assert( 0==*pConfig->pzErrmsg );
+ *pConfig->pzErrmsg = sqlite3_mprintf(
+ "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
+ iVersion, FTS5_CURRENT_VERSION
+ );
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ pConfig->iCookie = iCookie;
+ }
+ return rc;
+}
+
+/*
+** 2014 May 31
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+*/
+
+
+
+/* #include "fts5Int.h" */
+/* #include "fts5parse.h" */
+
+/*
+** All token types in the generated fts5parse.h file are greater than 0.
+*/
+#define FTS5_EOF 0
+
+#define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
+
+typedef struct Fts5ExprTerm Fts5ExprTerm;
+
+/*
+** Functions generated by lemon from fts5parse.y.
+*/
+static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
+static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
+static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
+#ifndef NDEBUG
+/* #include <stdio.h> */
+static void sqlite3Fts5ParserTrace(FILE*, char*);
+#endif
+static int sqlite3Fts5ParserFallback(int);
+
+
+struct Fts5Expr {
+ Fts5Index *pIndex;
+ Fts5Config *pConfig;
+ Fts5ExprNode *pRoot;
+ int bDesc; /* Iterate in descending rowid order */
+ int nPhrase; /* Number of phrases in expression */
+ Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
+};
+
+/*
+** eType:
+** Expression node type. Always one of:
+**
+** FTS5_AND (nChild, apChild valid)
+** FTS5_OR (nChild, apChild valid)
+** FTS5_NOT (nChild, apChild valid)
+** FTS5_STRING (pNear valid)
+** FTS5_TERM (pNear valid)
+*/
+struct Fts5ExprNode {
+ int eType; /* Node type */
+ int bEof; /* True at EOF */
+ int bNomatch; /* True if entry is not a match */
+
+ /* Next method for this node. */
+ int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
+
+ i64 iRowid; /* Current rowid */
+ Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
+
+ /* Child nodes. For a NOT node, this array always contains 2 entries. For
+ ** AND or OR nodes, it contains 2 or more entries. */
+ int nChild; /* Number of child nodes */
+ Fts5ExprNode *apChild[1]; /* Array of child nodes */
+};
+
+#define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
+
+/*
+** Invoke the xNext method of an Fts5ExprNode object. This macro should be
+** used as if it has the same signature as the xNext() methods themselves.
+*/
+#define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
+
+/*
+** An instance of the following structure represents a single search term
+** or term prefix.
+*/
+struct Fts5ExprTerm {
+ u8 bPrefix; /* True for a prefix term */
+ u8 bFirst; /* True if token must be first in column */
+ char *zTerm; /* nul-terminated term */
+ Fts5IndexIter *pIter; /* Iterator for this term */
+ Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
+};
+
+/*
+** A phrase. One or more terms that must appear in a contiguous sequence
+** within a document for it to match.
+*/
+struct Fts5ExprPhrase {
+ Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
+ Fts5Buffer poslist; /* Current position list */
+ int nTerm; /* Number of entries in aTerm[] */
+ Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
+};
+
+/*
+** One or more phrases that must appear within a certain token distance of
+** each other within each matching document.
+*/
+struct Fts5ExprNearset {
+ int nNear; /* NEAR parameter */
+ Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
+ int nPhrase; /* Number of entries in aPhrase[] array */
+ Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
+};
+
+
+/*
+** Parse context.
+*/
+struct Fts5Parse {
+ Fts5Config *pConfig;
+ char *zErr;
+ int rc;
+ int nPhrase; /* Size of apPhrase array */
+ Fts5ExprPhrase **apPhrase; /* Array of all phrases */
+ Fts5ExprNode *pExpr; /* Result of a successful parse */
+};
+
+static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
+ va_list ap;
+ va_start(ap, zFmt);
+ if( pParse->rc==SQLITE_OK ){
+ pParse->zErr = sqlite3_vmprintf(zFmt, ap);
+ pParse->rc = SQLITE_ERROR;
+ }
+ va_end(ap);
+}
+
+static int fts5ExprIsspace(char t){
+ return t==' ' || t=='\t' || t=='\n' || t=='\r';
+}
+
+/*
+** Read the first token from the nul-terminated string at *pz.
+*/
+static int fts5ExprGetToken(
+ Fts5Parse *pParse,
+ const char **pz, /* IN/OUT: Pointer into buffer */
+ Fts5Token *pToken
+){
+ const char *z = *pz;
+ int tok;
+
+ /* Skip past any whitespace */
+ while( fts5ExprIsspace(*z) ) z++;
+
+ pToken->p = z;
+ pToken->n = 1;
+ switch( *z ){
+ case '(': tok = FTS5_LP; break;
+ case ')': tok = FTS5_RP; break;
+ case '{': tok = FTS5_LCP; break;
+ case '}': tok = FTS5_RCP; break;
+ case ':': tok = FTS5_COLON; break;
+ case ',': tok = FTS5_COMMA; break;
+ case '+': tok = FTS5_PLUS; break;
+ case '*': tok = FTS5_STAR; break;
+ case '-': tok = FTS5_MINUS; break;
+ case '^': tok = FTS5_CARET; break;
+ case '\0': tok = FTS5_EOF; break;
+
+ case '"': {
+ const char *z2;
+ tok = FTS5_STRING;
+
+ for(z2=&z[1]; 1; z2++){
+ if( z2[0]=='"' ){
+ z2++;
+ if( z2[0]!='"' ) break;
+ }
+ if( z2[0]=='\0' ){
+ sqlite3Fts5ParseError(pParse, "unterminated string");
+ return FTS5_EOF;
+ }
+ }
+ pToken->n = (z2 - z);
+ break;
+ }
+
+ default: {
+ const char *z2;
+ if( sqlite3Fts5IsBareword(z[0])==0 ){
+ sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
+ return FTS5_EOF;
+ }
+ tok = FTS5_STRING;
+ for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
+ pToken->n = (z2 - z);
+ if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
+ if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
+ if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
+ break;
+ }
+ }
+
+ *pz = &pToken->p[pToken->n];
+ return tok;
+}
+
+static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc64((sqlite3_int64)t);}
+static void fts5ParseFree(void *p){ sqlite3_free(p); }
+
+static int sqlite3Fts5ExprNew(
+ Fts5Config *pConfig, /* FTS5 Configuration */
+ int iCol,
+ const char *zExpr, /* Expression text */
+ Fts5Expr **ppNew,
+ char **pzErr
+){
+ Fts5Parse sParse;
+ Fts5Token token;
+ const char *z = zExpr;
+ int t; /* Next token type */
+ void *pEngine;
+ Fts5Expr *pNew;
+
+ *ppNew = 0;
+ *pzErr = 0;
+ memset(&sParse, 0, sizeof(sParse));
+ pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
+ if( pEngine==0 ){ return SQLITE_NOMEM; }
+ sParse.pConfig = pConfig;
+
+ do {
+ t = fts5ExprGetToken(&sParse, &z, &token);
+ sqlite3Fts5Parser(pEngine, t, token, &sParse);
+ }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
+ sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
+
+ /* If the LHS of the MATCH expression was a user column, apply the
+ ** implicit column-filter. */
+ if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
+ int n = sizeof(Fts5Colset);
+ Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
+ if( pColset ){
+ pColset->nCol = 1;
+ pColset->aiCol[0] = iCol;
+ sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
+ }
+ }
+
+ assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
+ if( sParse.rc==SQLITE_OK ){
+ *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
+ if( pNew==0 ){
+ sParse.rc = SQLITE_NOMEM;
+ sqlite3Fts5ParseNodeFree(sParse.pExpr);
+ }else{
+ if( !sParse.pExpr ){
+ const int nByte = sizeof(Fts5ExprNode);
+ pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
+ if( pNew->pRoot ){
+ pNew->pRoot->bEof = 1;
+ }
+ }else{
+ pNew->pRoot = sParse.pExpr;
+ }
+ pNew->pIndex = 0;
+ pNew->pConfig = pConfig;
+ pNew->apExprPhrase = sParse.apPhrase;
+ pNew->nPhrase = sParse.nPhrase;
+ sParse.apPhrase = 0;
+ }
+ }else{
+ sqlite3Fts5ParseNodeFree(sParse.pExpr);
+ }
+
+ sqlite3_free(sParse.apPhrase);
+ *pzErr = sParse.zErr;
+ return sParse.rc;
+}
+
+/*
+** This function is only called when using the special 'trigram' tokenizer.
+** Argument zText contains the text of a LIKE or GLOB pattern matched
+** against column iCol. This function creates and compiles an FTS5 MATCH
+** expression that will match a superset of the rows matched by the LIKE or
+** GLOB. If successful, SQLITE_OK is returned. Otherwise, an SQLite error
+** code.
+*/
+static int sqlite3Fts5ExprPattern(
+ Fts5Config *pConfig, int iCol, const char *zText, Fts5Expr **pp
+){
+ i64 nText = strlen(zText);
+ char *zExpr = (char*)sqlite3_malloc64(nText*4 + 1);
+ int rc = SQLITE_OK;
+
+ if( zExpr==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ char aSpec[3];
+ int iOut = 0;
+ int i = 0;
+ int iFirst = 0;
+
+ if( pConfig->ePattern==FTS5_PATTERN_LIKE ){
+ aSpec[0] = '_';
+ aSpec[1] = '%';
+ aSpec[2] = 0;
+ }else{
+ aSpec[0] = '*';
+ aSpec[1] = '?';
+ aSpec[2] = '[';
+ }
+
+ while( i<=nText ){
+ if( i==nText
+ || zText[i]==aSpec[0] || zText[i]==aSpec[1] || zText[i]==aSpec[2]
+ ){
+ if( i-iFirst>=3 ){
+ int jj;
+ zExpr[iOut++] = '"';
+ for(jj=iFirst; jj<i; jj++){
+ zExpr[iOut++] = zText[jj];
+ if( zText[jj]=='"' ) zExpr[iOut++] = '"';
+ }
+ zExpr[iOut++] = '"';
+ zExpr[iOut++] = ' ';
+ }
+ if( zText[i]==aSpec[2] ){
+ i += 2;
+ if( zText[i-1]=='^' ) i++;
+ while( i<nText && zText[i]!=']' ) i++;
+ }
+ iFirst = i+1;
+ }
+ i++;
+ }
+ if( iOut>0 ){
+ zExpr[iOut] = '\0';
+ rc = sqlite3Fts5ExprNew(pConfig, iCol, zExpr, pp, pConfig->pzErrmsg);
+ }else{
+ *pp = 0;
+ }
+ sqlite3_free(zExpr);
+ }
+
+ return rc;
+}
+
+/*
+** Free the expression node object passed as the only argument.
+*/
+static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
+ if( p ){
+ int i;
+ for(i=0; i<p->nChild; i++){
+ sqlite3Fts5ParseNodeFree(p->apChild[i]);
+ }
+ sqlite3Fts5ParseNearsetFree(p->pNear);
+ sqlite3_free(p);
+ }
+}
+
+/*
+** Free the expression object passed as the only argument.
+*/
+static void sqlite3Fts5ExprFree(Fts5Expr *p){
+ if( p ){
+ sqlite3Fts5ParseNodeFree(p->pRoot);
+ sqlite3_free(p->apExprPhrase);
+ sqlite3_free(p);
+ }
+}
+
+static int sqlite3Fts5ExprAnd(Fts5Expr **pp1, Fts5Expr *p2){
+ Fts5Parse sParse;
+ memset(&sParse, 0, sizeof(sParse));
+
+ if( *pp1 ){
+ Fts5Expr *p1 = *pp1;
+ int nPhrase = p1->nPhrase + p2->nPhrase;
+
+ p1->pRoot = sqlite3Fts5ParseNode(&sParse, FTS5_AND, p1->pRoot, p2->pRoot,0);
+ p2->pRoot = 0;
+
+ if( sParse.rc==SQLITE_OK ){
+ Fts5ExprPhrase **ap = (Fts5ExprPhrase**)sqlite3_realloc(
+ p1->apExprPhrase, nPhrase * sizeof(Fts5ExprPhrase*)
+ );
+ if( ap==0 ){
+ sParse.rc = SQLITE_NOMEM;
+ }else{
+ int i;
+ memmove(&ap[p2->nPhrase], ap, p1->nPhrase*sizeof(Fts5ExprPhrase*));
+ for(i=0; i<p2->nPhrase; i++){
+ ap[i] = p2->apExprPhrase[i];
+ }
+ p1->nPhrase = nPhrase;
+ p1->apExprPhrase = ap;
+ }
+ }
+ sqlite3_free(p2->apExprPhrase);
+ sqlite3_free(p2);
+ }else{
+ *pp1 = p2;
+ }
+
+ return sParse.rc;
+}
+
+/*
+** Argument pTerm must be a synonym iterator. Return the current rowid
+** that it points to.
+*/
+static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
+ i64 iRet = 0;
+ int bRetValid = 0;
+ Fts5ExprTerm *p;
+
+ assert( pTerm->pSynonym );
+ assert( bDesc==0 || bDesc==1 );
+ for(p=pTerm; p; p=p->pSynonym){
+ if( 0==sqlite3Fts5IterEof(p->pIter) ){
+ i64 iRowid = p->pIter->iRowid;
+ if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
+ iRet = iRowid;
+ bRetValid = 1;
+ }
+ }
+ }
+
+ if( pbEof && bRetValid==0 ) *pbEof = 1;
+ return iRet;
+}
+
+/*
+** Argument pTerm must be a synonym iterator.
+*/
+static int fts5ExprSynonymList(
+ Fts5ExprTerm *pTerm,
+ i64 iRowid,
+ Fts5Buffer *pBuf, /* Use this buffer for space if required */
+ u8 **pa, int *pn
+){
+ Fts5PoslistReader aStatic[4];
+ Fts5PoslistReader *aIter = aStatic;
+ int nIter = 0;
+ int nAlloc = 4;
+ int rc = SQLITE_OK;
+ Fts5ExprTerm *p;
+
+ assert( pTerm->pSynonym );
+ for(p=pTerm; p; p=p->pSynonym){
+ Fts5IndexIter *pIter = p->pIter;
+ if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
+ if( pIter->nData==0 ) continue;
+ if( nIter==nAlloc ){
+ sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
+ Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc64(nByte);
+ if( aNew==0 ){
+ rc = SQLITE_NOMEM;
+ goto synonym_poslist_out;
+ }
+ memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
+ nAlloc = nAlloc*2;
+ if( aIter!=aStatic ) sqlite3_free(aIter);
+ aIter = aNew;
+ }
+ sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
+ assert( aIter[nIter].bEof==0 );
+ nIter++;
+ }
+ }
+
+ if( nIter==1 ){
+ *pa = (u8*)aIter[0].a;
+ *pn = aIter[0].n;
+ }else{
+ Fts5PoslistWriter writer = {0};
+ i64 iPrev = -1;
+ fts5BufferZero(pBuf);
+ while( 1 ){
+ int i;
+ i64 iMin = FTS5_LARGEST_INT64;
+ for(i=0; i<nIter; i++){
+ if( aIter[i].bEof==0 ){
+ if( aIter[i].iPos==iPrev ){
+ if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
+ }
+ if( aIter[i].iPos<iMin ){
+ iMin = aIter[i].iPos;
+ }
+ }
+ }
+ if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
+ rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
+ iPrev = iMin;
+ }
+ if( rc==SQLITE_OK ){
+ *pa = pBuf->p;
+ *pn = pBuf->n;
+ }
+ }
+
+ synonym_poslist_out:
+ if( aIter!=aStatic ) sqlite3_free(aIter);
+ return rc;
+}
+
+
+/*
+** All individual term iterators in pPhrase are guaranteed to be valid and
+** pointing to the same rowid when this function is called. This function
+** checks if the current rowid really is a match, and if so populates
+** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
+** is set to true if this is really a match, or false otherwise.
+**
+** SQLITE_OK is returned if an error occurs, or an SQLite error code
+** otherwise. It is not considered an error code if the current rowid is
+** not a match.
+*/
+static int fts5ExprPhraseIsMatch(
+ Fts5ExprNode *pNode, /* Node pPhrase belongs to */
+ Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
+ int *pbMatch /* OUT: Set to true if really a match */
+){
+ Fts5PoslistWriter writer = {0};
+ Fts5PoslistReader aStatic[4];
+ Fts5PoslistReader *aIter = aStatic;
+ int i;
+ int rc = SQLITE_OK;
+ int bFirst = pPhrase->aTerm[0].bFirst;
+
+ fts5BufferZero(&pPhrase->poslist);
+
+ /* If the aStatic[] array is not large enough, allocate a large array
+ ** using sqlite3_malloc(). This approach could be improved upon. */
+ if( pPhrase->nTerm>ArraySize(aStatic) ){
+ sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
+ aIter = (Fts5PoslistReader*)sqlite3_malloc64(nByte);
+ if( !aIter ) return SQLITE_NOMEM;
+ }
+ memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
+
+ /* Initialize a term iterator for each term in the phrase */
+ for(i=0; i<pPhrase->nTerm; i++){
+ Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
+ int n = 0;
+ int bFlag = 0;
+ u8 *a = 0;
+ if( pTerm->pSynonym ){
+ Fts5Buffer buf = {0, 0, 0};
+ rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
+ if( rc ){
+ sqlite3_free(a);
+ goto ismatch_out;
+ }
+ if( a==buf.p ) bFlag = 1;
+ }else{
+ a = (u8*)pTerm->pIter->pData;
+ n = pTerm->pIter->nData;
+ }
+ sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
+ aIter[i].bFlag = (u8)bFlag;
+ if( aIter[i].bEof ) goto ismatch_out;
+ }
+
+ while( 1 ){
+ int bMatch;
+ i64 iPos = aIter[0].iPos;
+ do {
+ bMatch = 1;
+ for(i=0; i<pPhrase->nTerm; i++){
+ Fts5PoslistReader *pPos = &aIter[i];
+ i64 iAdj = iPos + i;
+ if( pPos->iPos!=iAdj ){
+ bMatch = 0;
+ while( pPos->iPos<iAdj ){
+ if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
+ }
+ if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
+ }
+ }
+ }while( bMatch==0 );
+
+ /* Append position iPos to the output */
+ if( bFirst==0 || FTS5_POS2OFFSET(iPos)==0 ){
+ rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
+ if( rc!=SQLITE_OK ) goto ismatch_out;
+ }
+
+ for(i=0; i<pPhrase->nTerm; i++){
+ if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
+ }
+ }
+
+ ismatch_out:
+ *pbMatch = (pPhrase->poslist.n>0);
+ for(i=0; i<pPhrase->nTerm; i++){
+ if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
+ }
+ if( aIter!=aStatic ) sqlite3_free(aIter);
+ return rc;
+}
+
+typedef struct Fts5LookaheadReader Fts5LookaheadReader;
+struct Fts5LookaheadReader {
+ const u8 *a; /* Buffer containing position list */
+ int n; /* Size of buffer a[] in bytes */
+ int i; /* Current offset in position list */
+ i64 iPos; /* Current position */
+ i64 iLookahead; /* Next position */
+};
+
+#define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
+
+static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
+ p->iPos = p->iLookahead;
+ if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
+ p->iLookahead = FTS5_LOOKAHEAD_EOF;
+ }
+ return (p->iPos==FTS5_LOOKAHEAD_EOF);
+}
+
+static int fts5LookaheadReaderInit(
+ const u8 *a, int n, /* Buffer to read position list from */
+ Fts5LookaheadReader *p /* Iterator object to initialize */
+){
+ memset(p, 0, sizeof(Fts5LookaheadReader));
+ p->a = a;
+ p->n = n;
+ fts5LookaheadReaderNext(p);
+ return fts5LookaheadReaderNext(p);
+}
+
+typedef struct Fts5NearTrimmer Fts5NearTrimmer;
+struct Fts5NearTrimmer {
+ Fts5LookaheadReader reader; /* Input iterator */
+ Fts5PoslistWriter writer; /* Writer context */
+ Fts5Buffer *pOut; /* Output poslist */
+};
+
+/*
+** The near-set object passed as the first argument contains more than
+** one phrase. All phrases currently point to the same row. The
+** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
+** tests if the current row contains instances of each phrase sufficiently
+** close together to meet the NEAR constraint. Non-zero is returned if it
+** does, or zero otherwise.
+**
+** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
+** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
+** occurs within this function (*pRc) is set accordingly before returning.
+** The return value is undefined in both these cases.
+**
+** If no error occurs and non-zero (a match) is returned, the position-list
+** of each phrase object is edited to contain only those entries that
+** meet the constraint before returning.
+*/
+static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
+ Fts5NearTrimmer aStatic[4];
+ Fts5NearTrimmer *a = aStatic;
+ Fts5ExprPhrase **apPhrase = pNear->apPhrase;
+
+ int i;
+ int rc = *pRc;
+ int bMatch;
+
+ assert( pNear->nPhrase>1 );
+
+ /* If the aStatic[] array is not large enough, allocate a large array
+ ** using sqlite3_malloc(). This approach could be improved upon. */
+ if( pNear->nPhrase>ArraySize(aStatic) ){
+ sqlite3_int64 nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
+ a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
+ }else{
+ memset(aStatic, 0, sizeof(aStatic));
+ }
+ if( rc!=SQLITE_OK ){
+ *pRc = rc;
+ return 0;
+ }
+
+ /* Initialize a lookahead iterator for each phrase. After passing the
+ ** buffer and buffer size to the lookaside-reader init function, zero
+ ** the phrase poslist buffer. The new poslist for the phrase (containing
+ ** the same entries as the original with some entries removed on account
+ ** of the NEAR constraint) is written over the original even as it is
+ ** being read. This is safe as the entries for the new poslist are a
+ ** subset of the old, so it is not possible for data yet to be read to
+ ** be overwritten. */
+ for(i=0; i<pNear->nPhrase; i++){
+ Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
+ fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
+ pPoslist->n = 0;
+ a[i].pOut = pPoslist;
+ }
+
+ while( 1 ){
+ int iAdv;
+ i64 iMin;
+ i64 iMax;
+
+ /* This block advances the phrase iterators until they point to a set of
+ ** entries that together comprise a match. */
+ iMax = a[0].reader.iPos;
+ do {
+ bMatch = 1;
+ for(i=0; i<pNear->nPhrase; i++){
+ Fts5LookaheadReader *pPos = &a[i].reader;
+ iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
+ if( pPos->iPos<iMin || pPos->iPos>iMax ){
+ bMatch = 0;
+ while( pPos->iPos<iMin ){
+ if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
+ }
+ if( pPos->iPos>iMax ) iMax = pPos->iPos;
+ }
+ }
+ }while( bMatch==0 );
+
+ /* Add an entry to each output position list */
+ for(i=0; i<pNear->nPhrase; i++){
+ i64 iPos = a[i].reader.iPos;
+ Fts5PoslistWriter *pWriter = &a[i].writer;
+ if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
+ sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
+ }
+ }
+
+ iAdv = 0;
+ iMin = a[0].reader.iLookahead;
+ for(i=0; i<pNear->nPhrase; i++){
+ if( a[i].reader.iLookahead < iMin ){
+ iMin = a[i].reader.iLookahead;
+ iAdv = i;
+ }
+ }
+ if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
+ }
+
+ ismatch_out: {
+ int bRet = a[0].pOut->n>0;
+ *pRc = rc;
+ if( a!=aStatic ) sqlite3_free(a);
+ return bRet;
+ }
+}
+
+/*
+** Advance iterator pIter until it points to a value equal to or laster
+** than the initial value of *piLast. If this means the iterator points
+** to a value laster than *piLast, update *piLast to the new lastest value.
+**
+** If the iterator reaches EOF, set *pbEof to true before returning. If
+** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
+** are set, return a non-zero value. Otherwise, return zero.
+*/
+static int fts5ExprAdvanceto(
+ Fts5IndexIter *pIter, /* Iterator to advance */
+ int bDesc, /* True if iterator is "rowid DESC" */
+ i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
+ int *pRc, /* OUT: Error code */
+ int *pbEof /* OUT: Set to true if EOF */
+){
+ i64 iLast = *piLast;
+ i64 iRowid;
+
+ iRowid = pIter->iRowid;
+ if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
+ int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
+ if( rc || sqlite3Fts5IterEof(pIter) ){
+ *pRc = rc;
+ *pbEof = 1;
+ return 1;
+ }
+ iRowid = pIter->iRowid;
+ assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
+ }
+ *piLast = iRowid;
+
+ return 0;
+}
+
+static int fts5ExprSynonymAdvanceto(
+ Fts5ExprTerm *pTerm, /* Term iterator to advance */
+ int bDesc, /* True if iterator is "rowid DESC" */
+ i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
+ int *pRc /* OUT: Error code */
+){
+ int rc = SQLITE_OK;
+ i64 iLast = *piLast;
+ Fts5ExprTerm *p;
+ int bEof = 0;
+
+ for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
+ if( sqlite3Fts5IterEof(p->pIter)==0 ){
+ i64 iRowid = p->pIter->iRowid;
+ if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
+ rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
+ }
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ *pRc = rc;
+ bEof = 1;
+ }else{
+ *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
+ }
+ return bEof;
+}
+
+
+static int fts5ExprNearTest(
+ int *pRc,
+ Fts5Expr *pExpr, /* Expression that pNear is a part of */
+ Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
+){
+ Fts5ExprNearset *pNear = pNode->pNear;
+ int rc = *pRc;
+
+ if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
+ Fts5ExprTerm *pTerm;
+ Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
+ pPhrase->poslist.n = 0;
+ for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
+ Fts5IndexIter *pIter = pTerm->pIter;
+ if( sqlite3Fts5IterEof(pIter)==0 ){
+ if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
+ pPhrase->poslist.n = 1;
+ }
+ }
+ }
+ return pPhrase->poslist.n;
+ }else{
+ int i;
+
+ /* Check that each phrase in the nearset matches the current row.
+ ** Populate the pPhrase->poslist buffers at the same time. If any
+ ** phrase is not a match, break out of the loop early. */
+ for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
+ Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
+ if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym
+ || pNear->pColset || pPhrase->aTerm[0].bFirst
+ ){
+ int bMatch = 0;
+ rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
+ if( bMatch==0 ) break;
+ }else{
+ Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
+ fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
+ }
+ }
+
+ *pRc = rc;
+ if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
+ return 1;
+ }
+ return 0;
+ }
+}
+
+
+/*
+** Initialize all term iterators in the pNear object. If any term is found
+** to match no documents at all, return immediately without initializing any
+** further iterators.
+**
+** If an error occurs, return an SQLite error code. Otherwise, return
+** SQLITE_OK. It is not considered an error if some term matches zero
+** documents.
+*/
+static int fts5ExprNearInitAll(
+ Fts5Expr *pExpr,
+ Fts5ExprNode *pNode
+){
+ Fts5ExprNearset *pNear = pNode->pNear;
+ int i;
+
+ assert( pNode->bNomatch==0 );
+ for(i=0; i<pNear->nPhrase; i++){
+ Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
+ if( pPhrase->nTerm==0 ){
+ pNode->bEof = 1;
+ return SQLITE_OK;
+ }else{
+ int j;
+ for(j=0; j<pPhrase->nTerm; j++){
+ Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
+ Fts5ExprTerm *p;
+ int bHit = 0;
+
+ for(p=pTerm; p; p=p->pSynonym){
+ int rc;
+ if( p->pIter ){
+ sqlite3Fts5IterClose(p->pIter);
+ p->pIter = 0;
+ }
+ rc = sqlite3Fts5IndexQuery(
+ pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
+ (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
+ (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
+ pNear->pColset,
+ &p->pIter
+ );
+ assert( (rc==SQLITE_OK)==(p->pIter!=0) );
+ if( rc!=SQLITE_OK ) return rc;
+ if( 0==sqlite3Fts5IterEof(p->pIter) ){
+ bHit = 1;
+ }
+ }
+
+ if( bHit==0 ){
+ pNode->bEof = 1;
+ return SQLITE_OK;
+ }
+ }
+ }
+ }
+
+ pNode->bEof = 0;
+ return SQLITE_OK;
+}
+
+/*
+** If pExpr is an ASC iterator, this function returns a value with the
+** same sign as:
+**
+** (iLhs - iRhs)
+**
+** Otherwise, if this is a DESC iterator, the opposite is returned:
+**
+** (iRhs - iLhs)
+*/
+static int fts5RowidCmp(
+ Fts5Expr *pExpr,
+ i64 iLhs,
+ i64 iRhs
+){
+ assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
+ if( pExpr->bDesc==0 ){
+ if( iLhs<iRhs ) return -1;
+ return (iLhs > iRhs);
+ }else{
+ if( iLhs>iRhs ) return -1;
+ return (iLhs < iRhs);
+ }
+}
+
+static void fts5ExprSetEof(Fts5ExprNode *pNode){
+ int i;
+ pNode->bEof = 1;
+ pNode->bNomatch = 0;
+ for(i=0; i<pNode->nChild; i++){
+ fts5ExprSetEof(pNode->apChild[i]);
+ }
+}
+
+static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
+ if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
+ Fts5ExprNearset *pNear = pNode->pNear;
+ int i;
+ for(i=0; i<pNear->nPhrase; i++){
+ Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
+ pPhrase->poslist.n = 0;
+ }
+ }else{
+ int i;
+ for(i=0; i<pNode->nChild; i++){
+ fts5ExprNodeZeroPoslist(pNode->apChild[i]);
+ }
+ }
+}
+
+
+
+/*
+** Compare the values currently indicated by the two nodes as follows:
+**
+** res = (*p1) - (*p2)
+**
+** Nodes that point to values that come later in the iteration order are
+** considered to be larger. Nodes at EOF are the largest of all.
+**
+** This means that if the iteration order is ASC, then numerically larger
+** rowids are considered larger. Or if it is the default DESC, numerically
+** smaller rowids are larger.
+*/
+static int fts5NodeCompare(
+ Fts5Expr *pExpr,
+ Fts5ExprNode *p1,
+ Fts5ExprNode *p2
+){
+ if( p2->bEof ) return -1;
+ if( p1->bEof ) return +1;
+ return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
+}
+
+/*
+** All individual term iterators in pNear are guaranteed to be valid when
+** this function is called. This function checks if all term iterators
+** point to the same rowid, and if not, advances them until they do.
+** If an EOF is reached before this happens, *pbEof is set to true before
+** returning.
+**
+** SQLITE_OK is returned if an error occurs, or an SQLite error code
+** otherwise. It is not considered an error code if an iterator reaches
+** EOF.
+*/
+static int fts5ExprNodeTest_STRING(
+ Fts5Expr *pExpr, /* Expression pPhrase belongs to */
+ Fts5ExprNode *pNode
+){
+ Fts5ExprNearset *pNear = pNode->pNear;
+ Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
+ int rc = SQLITE_OK;
+ i64 iLast; /* Lastest rowid any iterator points to */
+ int i, j; /* Phrase and token index, respectively */
+ int bMatch; /* True if all terms are at the same rowid */
+ const int bDesc = pExpr->bDesc;
+
+ /* Check that this node should not be FTS5_TERM */
+ assert( pNear->nPhrase>1
+ || pNear->apPhrase[0]->nTerm>1
+ || pNear->apPhrase[0]->aTerm[0].pSynonym
+ || pNear->apPhrase[0]->aTerm[0].bFirst
+ );
+
+ /* Initialize iLast, the "lastest" rowid any iterator points to. If the
+ ** iterator skips through rowids in the default ascending order, this means
+ ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
+ ** means the minimum rowid. */
+ if( pLeft->aTerm[0].pSynonym ){
+ iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
+ }else{
+ iLast = pLeft->aTerm[0].pIter->iRowid;
+ }
+
+ do {
+ bMatch = 1;
+ for(i=0; i<pNear->nPhrase; i++){
+ Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
+ for(j=0; j<pPhrase->nTerm; j++){
+ Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
+ if( pTerm->pSynonym ){
+ i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
+ if( iRowid==iLast ) continue;
+ bMatch = 0;
+ if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
+ pNode->bNomatch = 0;
+ pNode->bEof = 1;
+ return rc;
+ }
+ }else{
+ Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
+ if( pIter->iRowid==iLast || pIter->bEof ) continue;
+ bMatch = 0;
+ if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
+ return rc;
+ }
+ }
+ }
+ }
+ }while( bMatch==0 );
+
+ pNode->iRowid = iLast;
+ pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
+ assert( pNode->bEof==0 || pNode->bNomatch==0 );
+
+ return rc;
+}
+
+/*
+** Advance the first term iterator in the first phrase of pNear. Set output
+** variable *pbEof to true if it reaches EOF or if an error occurs.
+**
+** Return SQLITE_OK if successful, or an SQLite error code if an error
+** occurs.
+*/
+static int fts5ExprNodeNext_STRING(
+ Fts5Expr *pExpr, /* Expression pPhrase belongs to */
+ Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
+ int bFromValid,
+ i64 iFrom
+){
+ Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
+ int rc = SQLITE_OK;
+
+ pNode->bNomatch = 0;
+ if( pTerm->pSynonym ){
+ int bEof = 1;
+ Fts5ExprTerm *p;
+
+ /* Find the firstest rowid any synonym points to. */
+ i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
+
+ /* Advance each iterator that currently points to iRowid. Or, if iFrom
+ ** is valid - each iterator that points to a rowid before iFrom. */
+ for(p=pTerm; p; p=p->pSynonym){
+ if( sqlite3Fts5IterEof(p->pIter)==0 ){
+ i64 ii = p->pIter->iRowid;
+ if( ii==iRowid
+ || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
+ ){
+ if( bFromValid ){
+ rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
+ }else{
+ rc = sqlite3Fts5IterNext(p->pIter);
+ }
+ if( rc!=SQLITE_OK ) break;
+ if( sqlite3Fts5IterEof(p->pIter)==0 ){
+ bEof = 0;
+ }
+ }else{
+ bEof = 0;
+ }
+ }
+ }
+
+ /* Set the EOF flag if either all synonym iterators are at EOF or an
+ ** error has occurred. */
+ pNode->bEof = (rc || bEof);
+ }else{
+ Fts5IndexIter *pIter = pTerm->pIter;
+
+ assert( Fts5NodeIsString(pNode) );
+ if( bFromValid ){
+ rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
+ }else{
+ rc = sqlite3Fts5IterNext(pIter);
+ }
+
+ pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
+ }
+
+ if( pNode->bEof==0 ){
+ assert( rc==SQLITE_OK );
+ rc = fts5ExprNodeTest_STRING(pExpr, pNode);
+ }
+
+ return rc;
+}
+
+
+static int fts5ExprNodeTest_TERM(
+ Fts5Expr *pExpr, /* Expression that pNear is a part of */
+ Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
+){
+ /* As this "NEAR" object is actually a single phrase that consists
+ ** of a single term only, grab pointers into the poslist managed by the
+ ** fts5_index.c iterator object. This is much faster than synthesizing
+ ** a new poslist the way we have to for more complicated phrase or NEAR
+ ** expressions. */
+ Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
+ Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
+
+ assert( pNode->eType==FTS5_TERM );
+ assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
+ assert( pPhrase->aTerm[0].pSynonym==0 );
+
+ pPhrase->poslist.n = pIter->nData;
+ if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
+ pPhrase->poslist.p = (u8*)pIter->pData;
+ }
+ pNode->iRowid = pIter->iRowid;
+ pNode->bNomatch = (pPhrase->poslist.n==0);
+ return SQLITE_OK;
+}
+
+/*
+** xNext() method for a node of type FTS5_TERM.
+*/
+static int fts5ExprNodeNext_TERM(
+ Fts5Expr *pExpr,
+ Fts5ExprNode *pNode,
+ int bFromValid,
+ i64 iFrom
+){
+ int rc;
+ Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
+
+ assert( pNode->bEof==0 );
+ if( bFromValid ){
+ rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
+ }else{
+ rc = sqlite3Fts5IterNext(pIter);
+ }
+ if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
+ rc = fts5ExprNodeTest_TERM(pExpr, pNode);
+ }else{
+ pNode->bEof = 1;
+ pNode->bNomatch = 0;
+ }
+ return rc;
+}
+
+static void fts5ExprNodeTest_OR(
+ Fts5Expr *pExpr, /* Expression of which pNode is a part */
+ Fts5ExprNode *pNode /* Expression node to test */
+){
+ Fts5ExprNode *pNext = pNode->apChild[0];
+ int i;
+
+ for(i=1; i<pNode->nChild; i++){
+ Fts5ExprNode *pChild = pNode->apChild[i];
+ int cmp = fts5NodeCompare(pExpr, pNext, pChild);
+ if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
+ pNext = pChild;
+ }
+ }
+ pNode->iRowid = pNext->iRowid;
+ pNode->bEof = pNext->bEof;
+ pNode->bNomatch = pNext->bNomatch;
+}
+
+static int fts5ExprNodeNext_OR(
+ Fts5Expr *pExpr,
+ Fts5ExprNode *pNode,
+ int bFromValid,
+ i64 iFrom
+){
+ int i;
+ i64 iLast = pNode->iRowid;
+
+ for(i=0; i<pNode->nChild; i++){
+ Fts5ExprNode *p1 = pNode->apChild[i];
+ assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
+ if( p1->bEof==0 ){
+ if( (p1->iRowid==iLast)
+ || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
+ ){
+ int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
+ if( rc!=SQLITE_OK ){
+ pNode->bNomatch = 0;
+ return rc;
+ }
+ }
+ }
+ }
+
+ fts5ExprNodeTest_OR(pExpr, pNode);
+ return SQLITE_OK;
+}
+
+/*
+** Argument pNode is an FTS5_AND node.
+*/
+static int fts5ExprNodeTest_AND(
+ Fts5Expr *pExpr, /* Expression pPhrase belongs to */
+ Fts5ExprNode *pAnd /* FTS5_AND node to advance */
+){
+ int iChild;
+ i64 iLast = pAnd->iRowid;
+ int rc = SQLITE_OK;
+ int bMatch;
+
+ assert( pAnd->bEof==0 );
+ do {
+ pAnd->bNomatch = 0;
+ bMatch = 1;
+ for(iChild=0; iChild<pAnd->nChild; iChild++){
+ Fts5ExprNode *pChild = pAnd->apChild[iChild];
+ int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
+ if( cmp>0 ){
+ /* Advance pChild until it points to iLast or laster */
+ rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
+ if( rc!=SQLITE_OK ){
+ pAnd->bNomatch = 0;
+ return rc;
+ }
+ }
+
+ /* If the child node is now at EOF, so is the parent AND node. Otherwise,
+ ** the child node is guaranteed to have advanced at least as far as
+ ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
+ ** new lastest rowid seen so far. */
+ assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
+ if( pChild->bEof ){
+ fts5ExprSetEof(pAnd);
+ bMatch = 1;
+ break;
+ }else if( iLast!=pChild->iRowid ){
+ bMatch = 0;
+ iLast = pChild->iRowid;
+ }
+
+ if( pChild->bNomatch ){
+ pAnd->bNomatch = 1;
+ }
+ }
+ }while( bMatch==0 );
+
+ if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
+ fts5ExprNodeZeroPoslist(pAnd);
+ }
+ pAnd->iRowid = iLast;
+ return SQLITE_OK;
+}
+
+static int fts5ExprNodeNext_AND(
+ Fts5Expr *pExpr,
+ Fts5ExprNode *pNode,
+ int bFromValid,
+ i64 iFrom
+){
+ int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
+ if( rc==SQLITE_OK ){
+ rc = fts5ExprNodeTest_AND(pExpr, pNode);
+ }else{
+ pNode->bNomatch = 0;
+ }
+ return rc;
+}
+
+static int fts5ExprNodeTest_NOT(
+ Fts5Expr *pExpr, /* Expression pPhrase belongs to */
+ Fts5ExprNode *pNode /* FTS5_NOT node to advance */
+){
+ int rc = SQLITE_OK;
+ Fts5ExprNode *p1 = pNode->apChild[0];
+ Fts5ExprNode *p2 = pNode->apChild[1];
+ assert( pNode->nChild==2 );
+
+ while( rc==SQLITE_OK && p1->bEof==0 ){
+ int cmp = fts5NodeCompare(pExpr, p1, p2);
+ if( cmp>0 ){
+ rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
+ cmp = fts5NodeCompare(pExpr, p1, p2);
+ }
+ assert( rc!=SQLITE_OK || cmp<=0 );
+ if( cmp || p2->bNomatch ) break;
+ rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
+ }
+ pNode->bEof = p1->bEof;
+ pNode->bNomatch = p1->bNomatch;
+ pNode->iRowid = p1->iRowid;
+ if( p1->bEof ){
+ fts5ExprNodeZeroPoslist(p2);
+ }
+ return rc;
+}
+
+static int fts5ExprNodeNext_NOT(
+ Fts5Expr *pExpr,
+ Fts5ExprNode *pNode,
+ int bFromValid,
+ i64 iFrom
+){
+ int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
+ if( rc==SQLITE_OK ){
+ rc = fts5ExprNodeTest_NOT(pExpr, pNode);
+ }
+ if( rc!=SQLITE_OK ){
+ pNode->bNomatch = 0;
+ }
+ return rc;
+}
+
+/*
+** If pNode currently points to a match, this function returns SQLITE_OK
+** without modifying it. Otherwise, pNode is advanced until it does point
+** to a match or EOF is reached.
+*/
+static int fts5ExprNodeTest(
+ Fts5Expr *pExpr, /* Expression of which pNode is a part */
+ Fts5ExprNode *pNode /* Expression node to test */
+){
+ int rc = SQLITE_OK;
+ if( pNode->bEof==0 ){
+ switch( pNode->eType ){
+
+ case FTS5_STRING: {
+ rc = fts5ExprNodeTest_STRING(pExpr, pNode);
+ break;
+ }
+
+ case FTS5_TERM: {
+ rc = fts5ExprNodeTest_TERM(pExpr, pNode);
+ break;
+ }
+
+ case FTS5_AND: {
+ rc = fts5ExprNodeTest_AND(pExpr, pNode);
+ break;
+ }
+
+ case FTS5_OR: {
+ fts5ExprNodeTest_OR(pExpr, pNode);
+ break;
+ }
+
+ default: assert( pNode->eType==FTS5_NOT ); {
+ rc = fts5ExprNodeTest_NOT(pExpr, pNode);
+ break;
+ }
+ }
+ }
+ return rc;
+}
+
+
+/*
+** Set node pNode, which is part of expression pExpr, to point to the first
+** match. If there are no matches, set the Node.bEof flag to indicate EOF.
+**
+** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
+** It is not an error if there are no matches.
+*/
+static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
+ int rc = SQLITE_OK;
+ pNode->bEof = 0;
+ pNode->bNomatch = 0;
+
+ if( Fts5NodeIsString(pNode) ){
+ /* Initialize all term iterators in the NEAR object. */
+ rc = fts5ExprNearInitAll(pExpr, pNode);
+ }else if( pNode->xNext==0 ){
+ pNode->bEof = 1;
+ }else{
+ int i;
+ int nEof = 0;
+ for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
+ Fts5ExprNode *pChild = pNode->apChild[i];
+ rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
+ assert( pChild->bEof==0 || pChild->bEof==1 );
+ nEof += pChild->bEof;
+ }
+ pNode->iRowid = pNode->apChild[0]->iRowid;
+
+ switch( pNode->eType ){
+ case FTS5_AND:
+ if( nEof>0 ) fts5ExprSetEof(pNode);
+ break;
+
+ case FTS5_OR:
+ if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
+ break;
+
+ default:
+ assert( pNode->eType==FTS5_NOT );
+ pNode->bEof = pNode->apChild[0]->bEof;
+ break;
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = fts5ExprNodeTest(pExpr, pNode);
+ }
+ return rc;
+}
+
+
+/*
+** Begin iterating through the set of documents in index pIdx matched by
+** the MATCH expression passed as the first argument. If the "bDesc"
+** parameter is passed a non-zero value, iteration is in descending rowid
+** order. Or, if it is zero, in ascending order.
+**
+** If iterating in ascending rowid order (bDesc==0), the first document
+** visited is that with the smallest rowid that is larger than or equal
+** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
+** then the first document visited must have a rowid smaller than or
+** equal to iFirst.
+**
+** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
+** is not considered an error if the query does not match any documents.
+*/
+static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
+ Fts5ExprNode *pRoot = p->pRoot;
+ int rc; /* Return code */
+
+ p->pIndex = pIdx;
+ p->bDesc = bDesc;
+ rc = fts5ExprNodeFirst(p, pRoot);
+
+ /* If not at EOF but the current rowid occurs earlier than iFirst in
+ ** the iteration order, move to document iFirst or later. */
+ if( rc==SQLITE_OK
+ && 0==pRoot->bEof
+ && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
+ ){
+ rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
+ }
+
+ /* If the iterator is not at a real match, skip forward until it is. */
+ while( pRoot->bNomatch ){
+ assert( pRoot->bEof==0 && rc==SQLITE_OK );
+ rc = fts5ExprNodeNext(p, pRoot, 0, 0);
+ }
+ return rc;
+}
+
+/*
+** Move to the next document
+**
+** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
+** is not considered an error if the query does not match any documents.
+*/
+static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
+ int rc;
+ Fts5ExprNode *pRoot = p->pRoot;
+ assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
+ do {
+ rc = fts5ExprNodeNext(p, pRoot, 0, 0);
+ assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
+ }while( pRoot->bNomatch );
+ if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
+ pRoot->bEof = 1;
+ }
+ return rc;
+}
+
+static int sqlite3Fts5ExprEof(Fts5Expr *p){
+ return p->pRoot->bEof;
+}
+
+static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
+ return p->pRoot->iRowid;
+}
+
+static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
+ int rc = SQLITE_OK;
+ *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
+ return rc;
+}
+
+/*
+** Free the phrase object passed as the only argument.
+*/
+static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
+ if( pPhrase ){
+ int i;
+ for(i=0; i<pPhrase->nTerm; i++){
+ Fts5ExprTerm *pSyn;
+ Fts5ExprTerm *pNext;
+ Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
+ sqlite3_free(pTerm->zTerm);
+ sqlite3Fts5IterClose(pTerm->pIter);
+ for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
+ pNext = pSyn->pSynonym;
+ sqlite3Fts5IterClose(pSyn->pIter);
+ fts5BufferFree((Fts5Buffer*)&pSyn[1]);
+ sqlite3_free(pSyn);
+ }
+ }
+ if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
+ sqlite3_free(pPhrase);
+ }
+}
+
+/*
+** Set the "bFirst" flag on the first token of the phrase passed as the
+** only argument.
+*/
+static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase *pPhrase){
+ if( pPhrase && pPhrase->nTerm ){
+ pPhrase->aTerm[0].bFirst = 1;
+ }
+}
+
+/*
+** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
+** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
+** appended to it and the results returned.
+**
+** If an OOM error occurs, both the pNear and pPhrase objects are freed and
+** NULL returned.
+*/
+static Fts5ExprNearset *sqlite3Fts5ParseNearset(
+ Fts5Parse *pParse, /* Parse context */
+ Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
+ Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
+){
+ const int SZALLOC = 8;
+ Fts5ExprNearset *pRet = 0;
+
+ if( pParse->rc==SQLITE_OK ){
+ if( pPhrase==0 ){
+ return pNear;
+ }
+ if( pNear==0 ){
+ sqlite3_int64 nByte;
+ nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
+ pRet = sqlite3_malloc64(nByte);
+ if( pRet==0 ){
+ pParse->rc = SQLITE_NOMEM;
+ }else{
+ memset(pRet, 0, (size_t)nByte);
+ }
+ }else if( (pNear->nPhrase % SZALLOC)==0 ){
+ int nNew = pNear->nPhrase + SZALLOC;
+ sqlite3_int64 nByte;
+
+ nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
+ pRet = (Fts5ExprNearset*)sqlite3_realloc64(pNear, nByte);
+ if( pRet==0 ){
+ pParse->rc = SQLITE_NOMEM;
+ }
+ }else{
+ pRet = pNear;
+ }
+ }
+
+ if( pRet==0 ){
+ assert( pParse->rc!=SQLITE_OK );
+ sqlite3Fts5ParseNearsetFree(pNear);
+ sqlite3Fts5ParsePhraseFree(pPhrase);
+ }else{
+ if( pRet->nPhrase>0 ){
+ Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
+ assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
+ if( pPhrase->nTerm==0 ){
+ fts5ExprPhraseFree(pPhrase);
+ pRet->nPhrase--;
+ pParse->nPhrase--;
+ pPhrase = pLast;
+ }else if( pLast->nTerm==0 ){
+ fts5ExprPhraseFree(pLast);
+ pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
+ pParse->nPhrase--;
+ pRet->nPhrase--;
+ }
+ }
+ pRet->apPhrase[pRet->nPhrase++] = pPhrase;
+ }
+ return pRet;
+}
+
+typedef struct TokenCtx TokenCtx;
+struct TokenCtx {
+ Fts5ExprPhrase *pPhrase;
+ int rc;
+};
+
+/*
+** Callback for tokenizing terms used by ParseTerm().
+*/
+static int fts5ParseTokenize(
+ void *pContext, /* Pointer to Fts5InsertCtx object */
+ int tflags, /* Mask of FTS5_TOKEN_* flags */
+ const char *pToken, /* Buffer containing token */
+ int nToken, /* Size of token in bytes */
+ int iUnused1, /* Start offset of token */
+ int iUnused2 /* End offset of token */
+){
+ int rc = SQLITE_OK;
+ const int SZALLOC = 8;
+ TokenCtx *pCtx = (TokenCtx*)pContext;
+ Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
+
+ UNUSED_PARAM2(iUnused1, iUnused2);
+
+ /* If an error has already occurred, this is a no-op */
+ if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
+ if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
+
+ if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
+ Fts5ExprTerm *pSyn;
+ sqlite3_int64 nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
+ pSyn = (Fts5ExprTerm*)sqlite3_malloc64(nByte);
+ if( pSyn==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memset(pSyn, 0, (size_t)nByte);
+ pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
+ memcpy(pSyn->zTerm, pToken, nToken);
+ pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
+ pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
+ }
+ }else{
+ Fts5ExprTerm *pTerm;
+ if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
+ Fts5ExprPhrase *pNew;
+ int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
+
+ pNew = (Fts5ExprPhrase*)sqlite3_realloc64(pPhrase,
+ sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
+ );
+ if( pNew==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
+ pCtx->pPhrase = pPhrase = pNew;
+ pNew->nTerm = nNew - SZALLOC;
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
+ memset(pTerm, 0, sizeof(Fts5ExprTerm));
+ pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
+ }
+ }
+
+ pCtx->rc = rc;
+ return rc;
+}
+
+
+/*
+** Free the phrase object passed as the only argument.
+*/
+static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
+ fts5ExprPhraseFree(pPhrase);
+}
+
+/*
+** Free the phrase object passed as the second argument.
+*/
+static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
+ if( pNear ){
+ int i;
+ for(i=0; i<pNear->nPhrase; i++){
+ fts5ExprPhraseFree(pNear->apPhrase[i]);
+ }
+ sqlite3_free(pNear->pColset);
+ sqlite3_free(pNear);
+ }
+}
+
+static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
+ assert( pParse->pExpr==0 );
+ pParse->pExpr = p;
+}
+
+/*
+** This function is called by the parser to process a string token. The
+** string may or may not be quoted. In any case it is tokenized and a
+** phrase object consisting of all tokens returned.
+*/
+static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
+ Fts5Parse *pParse, /* Parse context */
+ Fts5ExprPhrase *pAppend, /* Phrase to append to */
+ Fts5Token *pToken, /* String to tokenize */
+ int bPrefix /* True if there is a trailing "*" */
+){
+ Fts5Config *pConfig = pParse->pConfig;
+ TokenCtx sCtx; /* Context object passed to callback */
+ int rc; /* Tokenize return code */
+ char *z = 0;
+
+ memset(&sCtx, 0, sizeof(TokenCtx));
+ sCtx.pPhrase = pAppend;
+
+ rc = fts5ParseStringFromToken(pToken, &z);
+ if( rc==SQLITE_OK ){
+ int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
+ int n;
+ sqlite3Fts5Dequote(z);
+ n = (int)strlen(z);
+ rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
+ }
+ sqlite3_free(z);
+ if( rc || (rc = sCtx.rc) ){
+ pParse->rc = rc;
+ fts5ExprPhraseFree(sCtx.pPhrase);
+ sCtx.pPhrase = 0;
+ }else{
+
+ if( pAppend==0 ){
+ if( (pParse->nPhrase % 8)==0 ){
+ sqlite3_int64 nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
+ Fts5ExprPhrase **apNew;
+ apNew = (Fts5ExprPhrase**)sqlite3_realloc64(pParse->apPhrase, nByte);
+ if( apNew==0 ){
+ pParse->rc = SQLITE_NOMEM;
+ fts5ExprPhraseFree(sCtx.pPhrase);
+ return 0;
+ }
+ pParse->apPhrase = apNew;
+ }
+ pParse->nPhrase++;
+ }
+
+ if( sCtx.pPhrase==0 ){
+ /* This happens when parsing a token or quoted phrase that contains
+ ** no token characters at all. (e.g ... MATCH '""'). */
+ sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
+ }else if( sCtx.pPhrase->nTerm ){
+ sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = (u8)bPrefix;
+ }
+ pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
+ }
+
+ return sCtx.pPhrase;
+}
+
+/*
+** Create a new FTS5 expression by cloning phrase iPhrase of the
+** expression passed as the second argument.
+*/
+static int sqlite3Fts5ExprClonePhrase(
+ Fts5Expr *pExpr,
+ int iPhrase,
+ Fts5Expr **ppNew
+){
+ int rc = SQLITE_OK; /* Return code */
+ Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
+ Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
+ TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
+
+ pOrig = pExpr->apExprPhrase[iPhrase];
+ pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
+ if( rc==SQLITE_OK ){
+ pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
+ sizeof(Fts5ExprPhrase*));
+ }
+ if( rc==SQLITE_OK ){
+ pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
+ sizeof(Fts5ExprNode));
+ }
+ if( rc==SQLITE_OK ){
+ pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
+ sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
+ }
+ if( rc==SQLITE_OK ){
+ Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
+ if( pColsetOrig ){
+ sqlite3_int64 nByte;
+ Fts5Colset *pColset;
+ nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
+ pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
+ if( pColset ){
+ memcpy(pColset, pColsetOrig, (size_t)nByte);
+ }
+ pNew->pRoot->pNear->pColset = pColset;
+ }
+ }
+
+ if( pOrig->nTerm ){
+ int i; /* Used to iterate through phrase terms */
+ for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
+ int tflags = 0;
+ Fts5ExprTerm *p;
+ for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
+ const char *zTerm = p->zTerm;
+ rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
+ 0, 0);
+ tflags = FTS5_TOKEN_COLOCATED;
+ }
+ if( rc==SQLITE_OK ){
+ sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
+ sCtx.pPhrase->aTerm[i].bFirst = pOrig->aTerm[i].bFirst;
+ }
+ }
+ }else{
+ /* This happens when parsing a token or quoted phrase that contains
+ ** no token characters at all. (e.g ... MATCH '""'). */
+ sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
+ }
+
+ if( rc==SQLITE_OK ){
+ /* All the allocations succeeded. Put the expression object together. */
+ pNew->pIndex = pExpr->pIndex;
+ pNew->pConfig = pExpr->pConfig;
+ pNew->nPhrase = 1;
+ pNew->apExprPhrase[0] = sCtx.pPhrase;
+ pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
+ pNew->pRoot->pNear->nPhrase = 1;
+ sCtx.pPhrase->pNode = pNew->pRoot;
+
+ if( pOrig->nTerm==1
+ && pOrig->aTerm[0].pSynonym==0
+ && pOrig->aTerm[0].bFirst==0
+ ){
+ pNew->pRoot->eType = FTS5_TERM;
+ pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
+ }else{
+ pNew->pRoot->eType = FTS5_STRING;
+ pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
+ }
+ }else{
+ sqlite3Fts5ExprFree(pNew);
+ fts5ExprPhraseFree(sCtx.pPhrase);
+ pNew = 0;
+ }
+
+ *ppNew = pNew;
+ return rc;
+}
+
+
+/*
+** Token pTok has appeared in a MATCH expression where the NEAR operator
+** is expected. If token pTok does not contain "NEAR", store an error
+** in the pParse object.
+*/
+static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
+ if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
+ sqlite3Fts5ParseError(
+ pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
+ );
+ }
+}
+
+static void sqlite3Fts5ParseSetDistance(
+ Fts5Parse *pParse,
+ Fts5ExprNearset *pNear,
+ Fts5Token *p
+){
+ if( pNear ){
+ int nNear = 0;
+ int i;
+ if( p->n ){
+ for(i=0; i<p->n; i++){
+ char c = (char)p->p[i];
+ if( c<'0' || c>'9' ){
+ sqlite3Fts5ParseError(
+ pParse, "expected integer, got \"%.*s\"", p->n, p->p
+ );
+ return;
+ }
+ nNear = nNear * 10 + (p->p[i] - '0');
+ }
+ }else{
+ nNear = FTS5_DEFAULT_NEARDIST;
+ }
+ pNear->nNear = nNear;
+ }
+}
+
+/*
+** The second argument passed to this function may be NULL, or it may be
+** an existing Fts5Colset object. This function returns a pointer to
+** a new colset object containing the contents of (p) with new value column
+** number iCol appended.
+**
+** If an OOM error occurs, store an error code in pParse and return NULL.
+** The old colset object (if any) is not freed in this case.
+*/
+static Fts5Colset *fts5ParseColset(
+ Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
+ Fts5Colset *p, /* Existing colset object */
+ int iCol /* New column to add to colset object */
+){
+ int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
+ Fts5Colset *pNew; /* New colset object to return */
+
+ assert( pParse->rc==SQLITE_OK );
+ assert( iCol>=0 && iCol<pParse->pConfig->nCol );
+
+ pNew = sqlite3_realloc64(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
+ if( pNew==0 ){
+ pParse->rc = SQLITE_NOMEM;
+ }else{
+ int *aiCol = pNew->aiCol;
+ int i, j;
+ for(i=0; i<nCol; i++){
+ if( aiCol[i]==iCol ) return pNew;
+ if( aiCol[i]>iCol ) break;
+ }
+ for(j=nCol; j>i; j--){
+ aiCol[j] = aiCol[j-1];
+ }
+ aiCol[i] = iCol;
+ pNew->nCol = nCol+1;
+
+#ifndef NDEBUG
+ /* Check that the array is in order and contains no duplicate entries. */
+ for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
+#endif
+ }
+
+ return pNew;
+}
+
+/*
+** Allocate and return an Fts5Colset object specifying the inverse of
+** the colset passed as the second argument. Free the colset passed
+** as the second argument before returning.
+*/
+static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
+ Fts5Colset *pRet;
+ int nCol = pParse->pConfig->nCol;
+
+ pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
+ sizeof(Fts5Colset) + sizeof(int)*nCol
+ );
+ if( pRet ){
+ int i;
+ int iOld = 0;
+ for(i=0; i<nCol; i++){
+ if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
+ pRet->aiCol[pRet->nCol++] = i;
+ }else{
+ iOld++;
+ }
+ }
+ }
+
+ sqlite3_free(p);
+ return pRet;
+}
+
+static Fts5Colset *sqlite3Fts5ParseColset(
+ Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
+ Fts5Colset *pColset, /* Existing colset object */
+ Fts5Token *p
+){
+ Fts5Colset *pRet = 0;
+ int iCol;
+ char *z; /* Dequoted copy of token p */
+
+ z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
+ if( pParse->rc==SQLITE_OK ){
+ Fts5Config *pConfig = pParse->pConfig;
+ sqlite3Fts5Dequote(z);
+ for(iCol=0; iCol<pConfig->nCol; iCol++){
+ if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
+ }
+ if( iCol==pConfig->nCol ){
+ sqlite3Fts5ParseError(pParse, "no such column: %s", z);
+ }else{
+ pRet = fts5ParseColset(pParse, pColset, iCol);
+ }
+ sqlite3_free(z);
+ }
+
+ if( pRet==0 ){
+ assert( pParse->rc!=SQLITE_OK );
+ sqlite3_free(pColset);
+ }
+
+ return pRet;
+}
+
+/*
+** If argument pOrig is NULL, or if (*pRc) is set to anything other than
+** SQLITE_OK when this function is called, NULL is returned.
+**
+** Otherwise, a copy of (*pOrig) is made into memory obtained from
+** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
+** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
+*/
+static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
+ Fts5Colset *pRet;
+ if( pOrig ){
+ sqlite3_int64 nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
+ pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
+ if( pRet ){
+ memcpy(pRet, pOrig, (size_t)nByte);
+ }
+ }else{
+ pRet = 0;
+ }
+ return pRet;
+}
+
+/*
+** Remove from colset pColset any columns that are not also in colset pMerge.
+*/
+static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
+ int iIn = 0; /* Next input in pColset */
+ int iMerge = 0; /* Next input in pMerge */
+ int iOut = 0; /* Next output slot in pColset */
+
+ while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
+ int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
+ if( iDiff==0 ){
+ pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
+ iMerge++;
+ iIn++;
+ }else if( iDiff>0 ){
+ iMerge++;
+ }else{
+ iIn++;
+ }
+ }
+ pColset->nCol = iOut;
+}
+
+/*
+** Recursively apply colset pColset to expression node pNode and all of
+** its decendents. If (*ppFree) is not NULL, it contains a spare copy
+** of pColset. This function may use the spare copy and set (*ppFree) to
+** zero, or it may create copies of pColset using fts5CloneColset().
+*/
+static void fts5ParseSetColset(
+ Fts5Parse *pParse,
+ Fts5ExprNode *pNode,
+ Fts5Colset *pColset,
+ Fts5Colset **ppFree
+){
+ if( pParse->rc==SQLITE_OK ){
+ assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
+ || pNode->eType==FTS5_AND || pNode->eType==FTS5_OR
+ || pNode->eType==FTS5_NOT || pNode->eType==FTS5_EOF
+ );
+ if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
+ Fts5ExprNearset *pNear = pNode->pNear;
+ if( pNear->pColset ){
+ fts5MergeColset(pNear->pColset, pColset);
+ if( pNear->pColset->nCol==0 ){
+ pNode->eType = FTS5_EOF;
+ pNode->xNext = 0;
+ }
+ }else if( *ppFree ){
+ pNear->pColset = pColset;
+ *ppFree = 0;
+ }else{
+ pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
+ }
+ }else{
+ int i;
+ assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
+ for(i=0; i<pNode->nChild; i++){
+ fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
+ }
+ }
+ }
+}
+
+/*
+** Apply colset pColset to expression node pExpr and all of its descendents.
+*/
+static void sqlite3Fts5ParseSetColset(
+ Fts5Parse *pParse,
+ Fts5ExprNode *pExpr,
+ Fts5Colset *pColset
+){
+ Fts5Colset *pFree = pColset;
+ if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
+ pParse->rc = SQLITE_ERROR;
+ pParse->zErr = sqlite3_mprintf(
+ "fts5: column queries are not supported (detail=none)"
+ );
+ }else{
+ fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
+ }
+ sqlite3_free(pFree);
+}
+
+static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
+ switch( pNode->eType ){
+ case FTS5_STRING: {
+ Fts5ExprNearset *pNear = pNode->pNear;
+ if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
+ && pNear->apPhrase[0]->aTerm[0].pSynonym==0
+ && pNear->apPhrase[0]->aTerm[0].bFirst==0
+ ){
+ pNode->eType = FTS5_TERM;
+ pNode->xNext = fts5ExprNodeNext_TERM;
+ }else{
+ pNode->xNext = fts5ExprNodeNext_STRING;
+ }
+ break;
+ };
+
+ case FTS5_OR: {
+ pNode->xNext = fts5ExprNodeNext_OR;
+ break;
+ };
+
+ case FTS5_AND: {
+ pNode->xNext = fts5ExprNodeNext_AND;
+ break;
+ };
+
+ default: assert( pNode->eType==FTS5_NOT ); {
+ pNode->xNext = fts5ExprNodeNext_NOT;
+ break;
+ };
+ }
+}
+
+static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
+ if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
+ int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
+ memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
+ p->nChild += pSub->nChild;
+ sqlite3_free(pSub);
+ }else{
+ p->apChild[p->nChild++] = pSub;
+ }
+}
+
+/*
+** Allocate and return a new expression object. If anything goes wrong (i.e.
+** OOM error), leave an error code in pParse and return NULL.
+*/
+static Fts5ExprNode *sqlite3Fts5ParseNode(
+ Fts5Parse *pParse, /* Parse context */
+ int eType, /* FTS5_STRING, AND, OR or NOT */
+ Fts5ExprNode *pLeft, /* Left hand child expression */
+ Fts5ExprNode *pRight, /* Right hand child expression */
+ Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
+){
+ Fts5ExprNode *pRet = 0;
+
+ if( pParse->rc==SQLITE_OK ){
+ int nChild = 0; /* Number of children of returned node */
+ sqlite3_int64 nByte; /* Bytes of space to allocate for this node */
+
+ assert( (eType!=FTS5_STRING && !pNear)
+ || (eType==FTS5_STRING && !pLeft && !pRight)
+ );
+ if( eType==FTS5_STRING && pNear==0 ) return 0;
+ if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
+ if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
+
+ if( eType==FTS5_NOT ){
+ nChild = 2;
+ }else if( eType==FTS5_AND || eType==FTS5_OR ){
+ nChild = 2;
+ if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
+ if( pRight->eType==eType ) nChild += pRight->nChild-1;
+ }
+
+ nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
+ pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
+
+ if( pRet ){
+ pRet->eType = eType;
+ pRet->pNear = pNear;
+ fts5ExprAssignXNext(pRet);
+ if( eType==FTS5_STRING ){
+ int iPhrase;
+ for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
+ pNear->apPhrase[iPhrase]->pNode = pRet;
+ if( pNear->apPhrase[iPhrase]->nTerm==0 ){
+ pRet->xNext = 0;
+ pRet->eType = FTS5_EOF;
+ }
+ }
+
+ if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){
+ Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
+ if( pNear->nPhrase!=1
+ || pPhrase->nTerm>1
+ || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)
+ ){
+ assert( pParse->rc==SQLITE_OK );
+ pParse->rc = SQLITE_ERROR;
+ assert( pParse->zErr==0 );
+ pParse->zErr = sqlite3_mprintf(
+ "fts5: %s queries are not supported (detail!=full)",
+ pNear->nPhrase==1 ? "phrase": "NEAR"
+ );
+ sqlite3_free(pRet);
+ pRet = 0;
+ }
+ }
+ }else{
+ fts5ExprAddChildren(pRet, pLeft);
+ fts5ExprAddChildren(pRet, pRight);
+ }
+ }
+ }
+
+ if( pRet==0 ){
+ assert( pParse->rc!=SQLITE_OK );
+ sqlite3Fts5ParseNodeFree(pLeft);
+ sqlite3Fts5ParseNodeFree(pRight);
+ sqlite3Fts5ParseNearsetFree(pNear);
+ }
+ return pRet;
+}
+
+static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
+ Fts5Parse *pParse, /* Parse context */
+ Fts5ExprNode *pLeft, /* Left hand child expression */
+ Fts5ExprNode *pRight /* Right hand child expression */
+){
+ Fts5ExprNode *pRet = 0;
+ Fts5ExprNode *pPrev;
+
+ if( pParse->rc ){
+ sqlite3Fts5ParseNodeFree(pLeft);
+ sqlite3Fts5ParseNodeFree(pRight);
+ }else{
+
+ assert( pLeft->eType==FTS5_STRING
+ || pLeft->eType==FTS5_TERM
+ || pLeft->eType==FTS5_EOF
+ || pLeft->eType==FTS5_AND
+ );
+ assert( pRight->eType==FTS5_STRING
+ || pRight->eType==FTS5_TERM
+ || pRight->eType==FTS5_EOF
+ );
+
+ if( pLeft->eType==FTS5_AND ){
+ pPrev = pLeft->apChild[pLeft->nChild-1];
+ }else{
+ pPrev = pLeft;
+ }
+ assert( pPrev->eType==FTS5_STRING
+ || pPrev->eType==FTS5_TERM
+ || pPrev->eType==FTS5_EOF
+ );
+
+ if( pRight->eType==FTS5_EOF ){
+ assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
+ sqlite3Fts5ParseNodeFree(pRight);
+ pRet = pLeft;
+ pParse->nPhrase--;
+ }
+ else if( pPrev->eType==FTS5_EOF ){
+ Fts5ExprPhrase **ap;
+
+ if( pPrev==pLeft ){
+ pRet = pRight;
+ }else{
+ pLeft->apChild[pLeft->nChild-1] = pRight;
+ pRet = pLeft;
+ }
+
+ ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
+ assert( ap[0]==pPrev->pNear->apPhrase[0] );
+ memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
+ pParse->nPhrase--;
+
+ sqlite3Fts5ParseNodeFree(pPrev);
+ }
+ else{
+ pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
+ }
+ }
+
+ return pRet;
+}
+
+static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
+ sqlite3_int64 nByte = 0;
+ Fts5ExprTerm *p;
+ char *zQuoted;
+
+ /* Determine the maximum amount of space required. */
+ for(p=pTerm; p; p=p->pSynonym){
+ nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
+ }
+ zQuoted = sqlite3_malloc64(nByte);
+
+ if( zQuoted ){
+ int i = 0;
+ for(p=pTerm; p; p=p->pSynonym){
+ char *zIn = p->zTerm;
+ zQuoted[i++] = '"';
+ while( *zIn ){
+ if( *zIn=='"' ) zQuoted[i++] = '"';
+ zQuoted[i++] = *zIn++;
+ }
+ zQuoted[i++] = '"';
+ if( p->pSynonym ) zQuoted[i++] = '|';
+ }
+ if( pTerm->bPrefix ){
+ zQuoted[i++] = ' ';
+ zQuoted[i++] = '*';
+ }
+ zQuoted[i++] = '\0';
+ }
+ return zQuoted;
+}
+
+static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
+ char *zNew;
+ va_list ap;
+ va_start(ap, zFmt);
+ zNew = sqlite3_vmprintf(zFmt, ap);
+ va_end(ap);
+ if( zApp && zNew ){
+ char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
+ sqlite3_free(zNew);
+ zNew = zNew2;
+ }
+ sqlite3_free(zApp);
+ return zNew;
+}
+
+/*
+** Compose a tcl-readable representation of expression pExpr. Return a
+** pointer to a buffer containing that representation. It is the
+** responsibility of the caller to at some point free the buffer using
+** sqlite3_free().
+*/
+static char *fts5ExprPrintTcl(
+ Fts5Config *pConfig,
+ const char *zNearsetCmd,
+ Fts5ExprNode *pExpr
+){
+ char *zRet = 0;
+ if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
+ Fts5ExprNearset *pNear = pExpr->pNear;
+ int i;
+ int iTerm;
+
+ zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
+ if( zRet==0 ) return 0;
+ if( pNear->pColset ){
+ int *aiCol = pNear->pColset->aiCol;
+ int nCol = pNear->pColset->nCol;
+ if( nCol==1 ){
+ zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
+ }else{
+ zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
+ for(i=1; i<pNear->pColset->nCol; i++){
+ zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
+ }
+ zRet = fts5PrintfAppend(zRet, "} ");
+ }
+ if( zRet==0 ) return 0;
+ }
+
+ if( pNear->nPhrase>1 ){
+ zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
+ if( zRet==0 ) return 0;
+ }
+
+ zRet = fts5PrintfAppend(zRet, "--");
+ if( zRet==0 ) return 0;
+
+ for(i=0; i<pNear->nPhrase; i++){
+ Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
+
+ zRet = fts5PrintfAppend(zRet, " {");
+ for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
+ char *zTerm = pPhrase->aTerm[iTerm].zTerm;
+ zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
+ if( pPhrase->aTerm[iTerm].bPrefix ){
+ zRet = fts5PrintfAppend(zRet, "*");
+ }
+ }
+
+ if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
+ if( zRet==0 ) return 0;
+ }
+
+ }else{
+ char const *zOp = 0;
+ int i;
+ switch( pExpr->eType ){
+ case FTS5_AND: zOp = "AND"; break;
+ case FTS5_NOT: zOp = "NOT"; break;
+ default:
+ assert( pExpr->eType==FTS5_OR );
+ zOp = "OR";
+ break;
+ }
+
+ zRet = sqlite3_mprintf("%s", zOp);
+ for(i=0; zRet && i<pExpr->nChild; i++){
+ char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
+ if( !z ){
+ sqlite3_free(zRet);
+ zRet = 0;
+ }else{
+ zRet = fts5PrintfAppend(zRet, " [%z]", z);
+ }
+ }
+ }
+
+ return zRet;
+}
+
+static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
+ char *zRet = 0;
+ if( pExpr->eType==0 ){
+ return sqlite3_mprintf("\"\"");
+ }else
+ if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
+ Fts5ExprNearset *pNear = pExpr->pNear;
+ int i;
+ int iTerm;
+
+ if( pNear->pColset ){
+ int ii;
+ Fts5Colset *pColset = pNear->pColset;
+ if( pColset->nCol>1 ) zRet = fts5PrintfAppend(zRet, "{");
+ for(ii=0; ii<pColset->nCol; ii++){
+ zRet = fts5PrintfAppend(zRet, "%s%s",
+ pConfig->azCol[pColset->aiCol[ii]], ii==pColset->nCol-1 ? "" : " "
+ );
+ }
+ if( zRet ){
+ zRet = fts5PrintfAppend(zRet, "%s : ", pColset->nCol>1 ? "}" : "");
+ }
+ if( zRet==0 ) return 0;
+ }
+
+ if( pNear->nPhrase>1 ){
+ zRet = fts5PrintfAppend(zRet, "NEAR(");
+ if( zRet==0 ) return 0;
+ }
+
+ for(i=0; i<pNear->nPhrase; i++){
+ Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
+ if( i!=0 ){
+ zRet = fts5PrintfAppend(zRet, " ");
+ if( zRet==0 ) return 0;
+ }
+ for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
+ char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
+ if( zTerm ){
+ zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
+ sqlite3_free(zTerm);
+ }
+ if( zTerm==0 || zRet==0 ){
+ sqlite3_free(zRet);
+ return 0;
+ }
+ }
+ }
+
+ if( pNear->nPhrase>1 ){
+ zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
+ if( zRet==0 ) return 0;
+ }
+
+ }else{
+ char const *zOp = 0;
+ int i;
+
+ switch( pExpr->eType ){
+ case FTS5_AND: zOp = " AND "; break;
+ case FTS5_NOT: zOp = " NOT "; break;
+ default:
+ assert( pExpr->eType==FTS5_OR );
+ zOp = " OR ";
+ break;
+ }
+
+ for(i=0; i<pExpr->nChild; i++){
+ char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
+ if( z==0 ){
+ sqlite3_free(zRet);
+ zRet = 0;
+ }else{
+ int e = pExpr->apChild[i]->eType;
+ int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
+ zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
+ (i==0 ? "" : zOp),
+ (b?"(":""), z, (b?")":"")
+ );
+ }
+ if( zRet==0 ) break;
+ }
+ }
+
+ return zRet;
+}
+
+/*
+** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
+** and fts5_expr_tcl() (bTcl!=0).
+*/
+static void fts5ExprFunction(
+ sqlite3_context *pCtx, /* Function call context */
+ int nArg, /* Number of args */
+ sqlite3_value **apVal, /* Function arguments */
+ int bTcl
+){
+ Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
+ sqlite3 *db = sqlite3_context_db_handle(pCtx);
+ const char *zExpr = 0;
+ char *zErr = 0;
+ Fts5Expr *pExpr = 0;
+ int rc;
+ int i;
+
+ const char **azConfig; /* Array of arguments for Fts5Config */
+ const char *zNearsetCmd = "nearset";
+ int nConfig; /* Size of azConfig[] */
+ Fts5Config *pConfig = 0;
+ int iArg = 1;
+
+ if( nArg<1 ){
+ zErr = sqlite3_mprintf("wrong number of arguments to function %s",
+ bTcl ? "fts5_expr_tcl" : "fts5_expr"
+ );
+ sqlite3_result_error(pCtx, zErr, -1);
+ sqlite3_free(zErr);
+ return;
+ }
+
+ if( bTcl && nArg>1 ){
+ zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
+ iArg = 2;
+ }
+
+ nConfig = 3 + (nArg-iArg);
+ azConfig = (const char**)sqlite3_malloc64(sizeof(char*) * nConfig);
+ if( azConfig==0 ){
+ sqlite3_result_error_nomem(pCtx);
+ return;
+ }
+ azConfig[0] = 0;
+ azConfig[1] = "main";
+ azConfig[2] = "tbl";
+ for(i=3; iArg<nArg; iArg++){
+ const char *z = (const char*)sqlite3_value_text(apVal[iArg]);
+ azConfig[i++] = (z ? z : "");
+ }
+
+ zExpr = (const char*)sqlite3_value_text(apVal[0]);
+ if( zExpr==0 ) zExpr = "";
+
+ rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
+ }
+ if( rc==SQLITE_OK ){
+ char *zText;
+ if( pExpr->pRoot->xNext==0 ){
+ zText = sqlite3_mprintf("");
+ }else if( bTcl ){
+ zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
+ }else{
+ zText = fts5ExprPrint(pConfig, pExpr->pRoot);
+ }
+ if( zText==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
+ sqlite3_free(zText);
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ if( zErr ){
+ sqlite3_result_error(pCtx, zErr, -1);
+ sqlite3_free(zErr);
+ }else{
+ sqlite3_result_error_code(pCtx, rc);
+ }
+ }
+ sqlite3_free((void *)azConfig);
+ sqlite3Fts5ConfigFree(pConfig);
+ sqlite3Fts5ExprFree(pExpr);
+}
+
+static void fts5ExprFunctionHr(
+ sqlite3_context *pCtx, /* Function call context */
+ int nArg, /* Number of args */
+ sqlite3_value **apVal /* Function arguments */
+){
+ fts5ExprFunction(pCtx, nArg, apVal, 0);
+}
+static void fts5ExprFunctionTcl(
+ sqlite3_context *pCtx, /* Function call context */
+ int nArg, /* Number of args */
+ sqlite3_value **apVal /* Function arguments */
+){
+ fts5ExprFunction(pCtx, nArg, apVal, 1);
+}
+
+/*
+** The implementation of an SQLite user-defined-function that accepts a
+** single integer as an argument. If the integer is an alpha-numeric
+** unicode code point, 1 is returned. Otherwise 0.
+*/
+static void fts5ExprIsAlnum(
+ sqlite3_context *pCtx, /* Function call context */
+ int nArg, /* Number of args */
+ sqlite3_value **apVal /* Function arguments */
+){
+ int iCode;
+ u8 aArr[32];
+ if( nArg!=1 ){
+ sqlite3_result_error(pCtx,
+ "wrong number of arguments to function fts5_isalnum", -1
+ );
+ return;
+ }
+ memset(aArr, 0, sizeof(aArr));
+ sqlite3Fts5UnicodeCatParse("L*", aArr);
+ sqlite3Fts5UnicodeCatParse("N*", aArr);
+ sqlite3Fts5UnicodeCatParse("Co", aArr);
+ iCode = sqlite3_value_int(apVal[0]);
+ sqlite3_result_int(pCtx, aArr[sqlite3Fts5UnicodeCategory((u32)iCode)]);
+}
+
+static void fts5ExprFold(
+ sqlite3_context *pCtx, /* Function call context */
+ int nArg, /* Number of args */
+ sqlite3_value **apVal /* Function arguments */
+){
+ if( nArg!=1 && nArg!=2 ){
+ sqlite3_result_error(pCtx,
+ "wrong number of arguments to function fts5_fold", -1
+ );
+ }else{
+ int iCode;
+ int bRemoveDiacritics = 0;
+ iCode = sqlite3_value_int(apVal[0]);
+ if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
+ sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
+ }
+}
+
+/*
+** This is called during initialization to register the fts5_expr() scalar
+** UDF with the SQLite handle passed as the only argument.
+*/
+static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
+ struct Fts5ExprFunc {
+ const char *z;
+ void (*x)(sqlite3_context*,int,sqlite3_value**);
+ } aFunc[] = {
+ { "fts5_expr", fts5ExprFunctionHr },
+ { "fts5_expr_tcl", fts5ExprFunctionTcl },
+ { "fts5_isalnum", fts5ExprIsAlnum },
+ { "fts5_fold", fts5ExprFold },
+ };
+ int i;
+ int rc = SQLITE_OK;
+ void *pCtx = (void*)pGlobal;
+
+ for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
+ struct Fts5ExprFunc *p = &aFunc[i];
+ rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
+ }
+
+ /* Avoid warnings indicating that sqlite3Fts5ParserTrace() and
+ ** sqlite3Fts5ParserFallback() are unused */
+#ifndef NDEBUG
+ (void)sqlite3Fts5ParserTrace;
+#endif
+ (void)sqlite3Fts5ParserFallback;
+
+ return rc;
+}
+
+/*
+** Return the number of phrases in expression pExpr.
+*/
+static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
+ return (pExpr ? pExpr->nPhrase : 0);
+}
+
+/*
+** Return the number of terms in the iPhrase'th phrase in pExpr.
+*/
+static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
+ if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
+ return pExpr->apExprPhrase[iPhrase]->nTerm;
+}
+
+/*
+** This function is used to access the current position list for phrase
+** iPhrase.
+*/
+static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
+ int nRet;
+ Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
+ Fts5ExprNode *pNode = pPhrase->pNode;
+ if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
+ *pa = pPhrase->poslist.p;
+ nRet = pPhrase->poslist.n;
+ }else{
+ *pa = 0;
+ nRet = 0;
+ }
+ return nRet;
+}
+
+struct Fts5PoslistPopulator {
+ Fts5PoslistWriter writer;
+ int bOk; /* True if ok to populate */
+ int bMiss;
+};
+
+static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
+ Fts5PoslistPopulator *pRet;
+ pRet = sqlite3_malloc64(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
+ if( pRet ){
+ int i;
+ memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
+ for(i=0; i<pExpr->nPhrase; i++){
+ Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
+ Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
+ assert( pExpr->apExprPhrase[i]->nTerm==1 );
+ if( bLive &&
+ (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
+ ){
+ pRet[i].bMiss = 1;
+ }else{
+ pBuf->n = 0;
+ }
+ }
+ }
+ return pRet;
+}
+
+struct Fts5ExprCtx {
+ Fts5Expr *pExpr;
+ Fts5PoslistPopulator *aPopulator;
+ i64 iOff;
+};
+typedef struct Fts5ExprCtx Fts5ExprCtx;
+
+/*
+** TODO: Make this more efficient!
+*/
+static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
+ int i;
+ for(i=0; i<pColset->nCol; i++){
+ if( pColset->aiCol[i]==iCol ) return 1;
+ }
+ return 0;
+}
+
+static int fts5ExprPopulatePoslistsCb(
+ void *pCtx, /* Copy of 2nd argument to xTokenize() */
+ int tflags, /* Mask of FTS5_TOKEN_* flags */
+ const char *pToken, /* Pointer to buffer containing token */
+ int nToken, /* Size of token in bytes */
+ int iUnused1, /* Byte offset of token within input text */
+ int iUnused2 /* Byte offset of end of token within input text */
+){
+ Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
+ Fts5Expr *pExpr = p->pExpr;
+ int i;
+
+ UNUSED_PARAM2(iUnused1, iUnused2);
+
+ if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
+ if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
+ for(i=0; i<pExpr->nPhrase; i++){
+ Fts5ExprTerm *pTerm;
+ if( p->aPopulator[i].bOk==0 ) continue;
+ for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
+ int nTerm = (int)strlen(pTerm->zTerm);
+ if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
+ && memcmp(pTerm->zTerm, pToken, nTerm)==0
+ ){
+ int rc = sqlite3Fts5PoslistWriterAppend(
+ &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
+ );
+ if( rc ) return rc;
+ break;
+ }
+ }
+ }
+ return SQLITE_OK;
+}
+
+static int sqlite3Fts5ExprPopulatePoslists(
+ Fts5Config *pConfig,
+ Fts5Expr *pExpr,
+ Fts5PoslistPopulator *aPopulator,
+ int iCol,
+ const char *z, int n
+){
+ int i;
+ Fts5ExprCtx sCtx;
+ sCtx.pExpr = pExpr;
+ sCtx.aPopulator = aPopulator;
+ sCtx.iOff = (((i64)iCol) << 32) - 1;
+
+ for(i=0; i<pExpr->nPhrase; i++){
+ Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
+ Fts5Colset *pColset = pNode->pNear->pColset;
+ if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
+ || aPopulator[i].bMiss
+ ){
+ aPopulator[i].bOk = 0;
+ }else{
+ aPopulator[i].bOk = 1;
+ }
+ }
+
+ return sqlite3Fts5Tokenize(pConfig,
+ FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
+ );
+}
+
+static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
+ if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
+ pNode->pNear->apPhrase[0]->poslist.n = 0;
+ }else{
+ int i;
+ for(i=0; i<pNode->nChild; i++){
+ fts5ExprClearPoslists(pNode->apChild[i]);
+ }
+ }
+}
+
+static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
+ pNode->iRowid = iRowid;
+ pNode->bEof = 0;
+ switch( pNode->eType ){
+ case FTS5_TERM:
+ case FTS5_STRING:
+ return (pNode->pNear->apPhrase[0]->poslist.n>0);
+
+ case FTS5_AND: {
+ int i;
+ for(i=0; i<pNode->nChild; i++){
+ if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
+ fts5ExprClearPoslists(pNode);
+ return 0;
+ }
+ }
+ break;
+ }
+
+ case FTS5_OR: {
+ int i;
+ int bRet = 0;
+ for(i=0; i<pNode->nChild; i++){
+ if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
+ bRet = 1;
+ }
+ }
+ return bRet;
+ }
+
+ default: {
+ assert( pNode->eType==FTS5_NOT );
+ if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
+ || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
+ ){
+ fts5ExprClearPoslists(pNode);
+ return 0;
+ }
+ break;
+ }
+ }
+ return 1;
+}
+
+static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
+ fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
+}
+
+/*
+** This function is only called for detail=columns tables.
+*/
+static int sqlite3Fts5ExprPhraseCollist(
+ Fts5Expr *pExpr,
+ int iPhrase,
+ const u8 **ppCollist,
+ int *pnCollist
+){
+ Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
+ Fts5ExprNode *pNode = pPhrase->pNode;
+ int rc = SQLITE_OK;
+
+ assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
+ assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
+
+ if( pNode->bEof==0
+ && pNode->iRowid==pExpr->pRoot->iRowid
+ && pPhrase->poslist.n>0
+ ){
+ Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
+ if( pTerm->pSynonym ){
+ Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
+ rc = fts5ExprSynonymList(
+ pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
+ );
+ }else{
+ *ppCollist = pPhrase->aTerm[0].pIter->pData;
+ *pnCollist = pPhrase->aTerm[0].pIter->nData;
+ }
+ }else{
+ *ppCollist = 0;
+ *pnCollist = 0;
+ }
+
+ return rc;
+}
+
+/*
+** 2014 August 11
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+*/
+
+
+
+/* #include "fts5Int.h" */
+
+typedef struct Fts5HashEntry Fts5HashEntry;
+
+/*
+** This file contains the implementation of an in-memory hash table used
+** to accumuluate "term -> doclist" content before it is flused to a level-0
+** segment.
+*/
+
+
+struct Fts5Hash {
+ int eDetail; /* Copy of Fts5Config.eDetail */
+ int *pnByte; /* Pointer to bytes counter */
+ int nEntry; /* Number of entries currently in hash */
+ int nSlot; /* Size of aSlot[] array */
+ Fts5HashEntry *pScan; /* Current ordered scan item */
+ Fts5HashEntry **aSlot; /* Array of hash slots */
+};
+
+/*
+** Each entry in the hash table is represented by an object of the
+** following type. Each object, its key (a nul-terminated string) and
+** its current data are stored in a single memory allocation. The
+** key immediately follows the object in memory. The position list
+** data immediately follows the key data in memory.
+**
+** The data that follows the key is in a similar, but not identical format
+** to the doclist data stored in the database. It is:
+**
+** * Rowid, as a varint
+** * Position list, without 0x00 terminator.
+** * Size of previous position list and rowid, as a 4 byte
+** big-endian integer.
+**
+** iRowidOff:
+** Offset of last rowid written to data area. Relative to first byte of
+** structure.
+**
+** nData:
+** Bytes of data written since iRowidOff.
+*/
+struct Fts5HashEntry {
+ Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
+ Fts5HashEntry *pScanNext; /* Next entry in sorted order */
+
+ int nAlloc; /* Total size of allocation */
+ int iSzPoslist; /* Offset of space for 4-byte poslist size */
+ int nData; /* Total bytes of data (incl. structure) */
+ int nKey; /* Length of key in bytes */
+ u8 bDel; /* Set delete-flag @ iSzPoslist */
+ u8 bContent; /* Set content-flag (detail=none mode) */
+ i16 iCol; /* Column of last value written */
+ int iPos; /* Position of last value written */
+ i64 iRowid; /* Rowid of last value written */
+};
+
+/*
+** Eqivalent to:
+**
+** char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
+*/
+#define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
+
+
+/*
+** Allocate a new hash table.
+*/
+static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
+ int rc = SQLITE_OK;
+ Fts5Hash *pNew;
+
+ *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
+ if( pNew==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ sqlite3_int64 nByte;
+ memset(pNew, 0, sizeof(Fts5Hash));
+ pNew->pnByte = pnByte;
+ pNew->eDetail = pConfig->eDetail;
+
+ pNew->nSlot = 1024;
+ nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
+ pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc64(nByte);
+ if( pNew->aSlot==0 ){
+ sqlite3_free(pNew);
+ *ppNew = 0;
+ rc = SQLITE_NOMEM;
+ }else{
+ memset(pNew->aSlot, 0, (size_t)nByte);
+ }
+ }
+ return rc;
+}
+
+/*
+** Free a hash table object.
+*/
+static void sqlite3Fts5HashFree(Fts5Hash *pHash){
+ if( pHash ){
+ sqlite3Fts5HashClear(pHash);
+ sqlite3_free(pHash->aSlot);
+ sqlite3_free(pHash);
+ }
+}
+
+/*
+** Empty (but do not delete) a hash table.
+*/
+static void sqlite3Fts5HashClear(Fts5Hash *pHash){
+ int i;
+ for(i=0; i<pHash->nSlot; i++){
+ Fts5HashEntry *pNext;
+ Fts5HashEntry *pSlot;
+ for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
+ pNext = pSlot->pHashNext;
+ sqlite3_free(pSlot);
+ }
+ }
+ memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
+ pHash->nEntry = 0;
+}
+
+static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
+ int i;
+ unsigned int h = 13;
+ for(i=n-1; i>=0; i--){
+ h = (h << 3) ^ h ^ p[i];
+ }
+ return (h % nSlot);
+}
+
+static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
+ int i;
+ unsigned int h = 13;
+ for(i=n-1; i>=0; i--){
+ h = (h << 3) ^ h ^ p[i];
+ }
+ h = (h << 3) ^ h ^ b;
+ return (h % nSlot);
+}
+
+/*
+** Resize the hash table by doubling the number of slots.
+*/
+static int fts5HashResize(Fts5Hash *pHash){
+ int nNew = pHash->nSlot*2;
+ int i;
+ Fts5HashEntry **apNew;
+ Fts5HashEntry **apOld = pHash->aSlot;
+
+ apNew = (Fts5HashEntry**)sqlite3_malloc64(nNew*sizeof(Fts5HashEntry*));
+ if( !apNew ) return SQLITE_NOMEM;
+ memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
+
+ for(i=0; i<pHash->nSlot; i++){
+ while( apOld[i] ){
+ unsigned int iHash;
+ Fts5HashEntry *p = apOld[i];
+ apOld[i] = p->pHashNext;
+ iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p),
+ (int)strlen(fts5EntryKey(p)));
+ p->pHashNext = apNew[iHash];
+ apNew[iHash] = p;
+ }
+ }
+
+ sqlite3_free(apOld);
+ pHash->nSlot = nNew;
+ pHash->aSlot = apNew;
+ return SQLITE_OK;
+}
+
+static int fts5HashAddPoslistSize(
+ Fts5Hash *pHash,
+ Fts5HashEntry *p,
+ Fts5HashEntry *p2
+){
+ int nRet = 0;
+ if( p->iSzPoslist ){
+ u8 *pPtr = p2 ? (u8*)p2 : (u8*)p;
+ int nData = p->nData;
+ if( pHash->eDetail==FTS5_DETAIL_NONE ){
+ assert( nData==p->iSzPoslist );
+ if( p->bDel ){
+ pPtr[nData++] = 0x00;
+ if( p->bContent ){
+ pPtr[nData++] = 0x00;
+ }
+ }
+ }else{
+ int nSz = (nData - p->iSzPoslist - 1); /* Size in bytes */
+ int nPos = nSz*2 + p->bDel; /* Value of nPos field */
+
+ assert( p->bDel==0 || p->bDel==1 );
+ if( nPos<=127 ){
+ pPtr[p->iSzPoslist] = (u8)nPos;
+ }else{
+ int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
+ memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
+ sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
+ nData += (nByte-1);
+ }
+ }
+
+ nRet = nData - p->nData;
+ if( p2==0 ){
+ p->iSzPoslist = 0;
+ p->bDel = 0;
+ p->bContent = 0;
+ p->nData = nData;
+ }
+ }
+ return nRet;
+}
+
+/*
+** Add an entry to the in-memory hash table. The key is the concatenation
+** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
+**
+** (bByte || pToken) -> (iRowid,iCol,iPos)
+**
+** Or, if iCol is negative, then the value is a delete marker.
+*/
+static int sqlite3Fts5HashWrite(
+ Fts5Hash *pHash,
+ i64 iRowid, /* Rowid for this entry */
+ int iCol, /* Column token appears in (-ve -> delete) */
+ int iPos, /* Position of token within column */
+ char bByte, /* First byte of token */
+ const char *pToken, int nToken /* Token to add or remove to or from index */
+){
+ unsigned int iHash;
+ Fts5HashEntry *p;
+ u8 *pPtr;
+ int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
+ int bNew; /* If non-delete entry should be written */
+
+ bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
+
+ /* Attempt to locate an existing hash entry */
+ iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
+ for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
+ char *zKey = fts5EntryKey(p);
+ if( zKey[0]==bByte
+ && p->nKey==nToken
+ && memcmp(&zKey[1], pToken, nToken)==0
+ ){
+ break;
+ }
+ }
+
+ /* If an existing hash entry cannot be found, create a new one. */
+ if( p==0 ){
+ /* Figure out how much space to allocate */
+ char *zKey;
+ sqlite3_int64 nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
+ if( nByte<128 ) nByte = 128;
+
+ /* Grow the Fts5Hash.aSlot[] array if necessary. */
+ if( (pHash->nEntry*2)>=pHash->nSlot ){
+ int rc = fts5HashResize(pHash);
+ if( rc!=SQLITE_OK ) return rc;
+ iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
+ }
+
+ /* Allocate new Fts5HashEntry and add it to the hash table. */
+ p = (Fts5HashEntry*)sqlite3_malloc64(nByte);
+ if( !p ) return SQLITE_NOMEM;
+ memset(p, 0, sizeof(Fts5HashEntry));
+ p->nAlloc = (int)nByte;
+ zKey = fts5EntryKey(p);
+ zKey[0] = bByte;
+ memcpy(&zKey[1], pToken, nToken);
+ assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
+ p->nKey = nToken;
+ zKey[nToken+1] = '\0';
+ p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
+ p->pHashNext = pHash->aSlot[iHash];
+ pHash->aSlot[iHash] = p;
+ pHash->nEntry++;
+
+ /* Add the first rowid field to the hash-entry */
+ p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
+ p->iRowid = iRowid;
+
+ p->iSzPoslist = p->nData;
+ if( pHash->eDetail!=FTS5_DETAIL_NONE ){
+ p->nData += 1;
+ p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
+ }
+
+ }else{
+
+ /* Appending to an existing hash-entry. Check that there is enough
+ ** space to append the largest possible new entry. Worst case scenario
+ ** is:
+ **
+ ** + 9 bytes for a new rowid,
+ ** + 4 byte reserved for the "poslist size" varint.
+ ** + 1 byte for a "new column" byte,
+ ** + 3 bytes for a new column number (16-bit max) as a varint,
+ ** + 5 bytes for the new position offset (32-bit max).
+ */
+ if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
+ sqlite3_int64 nNew = p->nAlloc * 2;
+ Fts5HashEntry *pNew;
+ Fts5HashEntry **pp;
+ pNew = (Fts5HashEntry*)sqlite3_realloc64(p, nNew);
+ if( pNew==0 ) return SQLITE_NOMEM;
+ pNew->nAlloc = (int)nNew;
+ for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
+ *pp = pNew;
+ p = pNew;
+ }
+ nIncr -= p->nData;
+ }
+ assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
+
+ pPtr = (u8*)p;
+
+ /* If this is a new rowid, append the 4-byte size field for the previous
+ ** entry, and the new rowid for this entry. */
+ if( iRowid!=p->iRowid ){
+ fts5HashAddPoslistSize(pHash, p, 0);
+ p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
+ p->iRowid = iRowid;
+ bNew = 1;
+ p->iSzPoslist = p->nData;
+ if( pHash->eDetail!=FTS5_DETAIL_NONE ){
+ p->nData += 1;
+ p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
+ p->iPos = 0;
+ }
+ }
+
+ if( iCol>=0 ){
+ if( pHash->eDetail==FTS5_DETAIL_NONE ){
+ p->bContent = 1;
+ }else{
+ /* Append a new column value, if necessary */
+ assert( iCol>=p->iCol );
+ if( iCol!=p->iCol ){
+ if( pHash->eDetail==FTS5_DETAIL_FULL ){
+ pPtr[p->nData++] = 0x01;
+ p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
+ p->iCol = (i16)iCol;
+ p->iPos = 0;
+ }else{
+ bNew = 1;
+ p->iCol = (i16)(iPos = iCol);
+ }
+ }
+
+ /* Append the new position offset, if necessary */
+ if( bNew ){
+ p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
+ p->iPos = iPos;
+ }
+ }
+ }else{
+ /* This is a delete. Set the delete flag. */
+ p->bDel = 1;
+ }
+
+ nIncr += p->nData;
+ *pHash->pnByte += nIncr;
+ return SQLITE_OK;
+}
+
+
+/*
+** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
+** each sorted in key order. This function merges the two lists into a
+** single list and returns a pointer to its first element.
+*/
+static Fts5HashEntry *fts5HashEntryMerge(
+ Fts5HashEntry *pLeft,
+ Fts5HashEntry *pRight
+){
+ Fts5HashEntry *p1 = pLeft;
+ Fts5HashEntry *p2 = pRight;
+ Fts5HashEntry *pRet = 0;
+ Fts5HashEntry **ppOut = &pRet;
+
+ while( p1 || p2 ){
+ if( p1==0 ){
+ *ppOut = p2;
+ p2 = 0;
+ }else if( p2==0 ){
+ *ppOut = p1;
+ p1 = 0;
+ }else{
+ int i = 0;
+ char *zKey1 = fts5EntryKey(p1);
+ char *zKey2 = fts5EntryKey(p2);
+ while( zKey1[i]==zKey2[i] ) i++;
+
+ if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
+ /* p2 is smaller */
+ *ppOut = p2;
+ ppOut = &p2->pScanNext;
+ p2 = p2->pScanNext;
+ }else{
+ /* p1 is smaller */
+ *ppOut = p1;
+ ppOut = &p1->pScanNext;
+ p1 = p1->pScanNext;
+ }
+ *ppOut = 0;
+ }
+ }
+
+ return pRet;
+}
+
+/*
+** Extract all tokens from hash table iHash and link them into a list
+** in sorted order. The hash table is cleared before returning. It is
+** the responsibility of the caller to free the elements of the returned
+** list.
+*/
+static int fts5HashEntrySort(
+ Fts5Hash *pHash,
+ const char *pTerm, int nTerm, /* Query prefix, if any */
+ Fts5HashEntry **ppSorted
+){
+ const int nMergeSlot = 32;
+ Fts5HashEntry **ap;
+ Fts5HashEntry *pList;
+ int iSlot;
+ int i;
+
+ *ppSorted = 0;
+ ap = sqlite3_malloc64(sizeof(Fts5HashEntry*) * nMergeSlot);
+ if( !ap ) return SQLITE_NOMEM;
+ memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
+
+ for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
+ Fts5HashEntry *pIter;
+ for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
+ if( pTerm==0
+ || (pIter->nKey+1>=nTerm && 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm))
+ ){
+ Fts5HashEntry *pEntry = pIter;
+ pEntry->pScanNext = 0;
+ for(i=0; ap[i]; i++){
+ pEntry = fts5HashEntryMerge(pEntry, ap[i]);
+ ap[i] = 0;
+ }
+ ap[i] = pEntry;
+ }
+ }
+ }
+
+ pList = 0;
+ for(i=0; i<nMergeSlot; i++){
+ pList = fts5HashEntryMerge(pList, ap[i]);
+ }
+
+ pHash->nEntry = 0;
+ sqlite3_free(ap);
+ *ppSorted = pList;
+ return SQLITE_OK;
+}
+
+/*
+** Query the hash table for a doclist associated with term pTerm/nTerm.
+*/
+static int sqlite3Fts5HashQuery(
+ Fts5Hash *pHash, /* Hash table to query */
+ int nPre,
+ const char *pTerm, int nTerm, /* Query term */
+ void **ppOut, /* OUT: Pointer to new object */
+ int *pnDoclist /* OUT: Size of doclist in bytes */
+){
+ unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
+ char *zKey = 0;
+ Fts5HashEntry *p;
+
+ for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
+ zKey = fts5EntryKey(p);
+ assert( p->nKey+1==(int)strlen(zKey) );
+ if( nTerm==p->nKey+1 && memcmp(zKey, pTerm, nTerm)==0 ) break;
+ }
+
+ if( p ){
+ int nHashPre = sizeof(Fts5HashEntry) + nTerm + 1;
+ int nList = p->nData - nHashPre;
+ u8 *pRet = (u8*)(*ppOut = sqlite3_malloc64(nPre + nList + 10));
+ if( pRet ){
+ Fts5HashEntry *pFaux = (Fts5HashEntry*)&pRet[nPre-nHashPre];
+ memcpy(&pRet[nPre], &((u8*)p)[nHashPre], nList);
+ nList += fts5HashAddPoslistSize(pHash, p, pFaux);
+ *pnDoclist = nList;
+ }else{
+ *pnDoclist = 0;
+ return SQLITE_NOMEM;
+ }
+ }else{
+ *ppOut = 0;
+ *pnDoclist = 0;
+ }
+
+ return SQLITE_OK;
+}
+
+static int sqlite3Fts5HashScanInit(
+ Fts5Hash *p, /* Hash table to query */
+ const char *pTerm, int nTerm /* Query prefix */
+){
+ return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
+}
+
+static void sqlite3Fts5HashScanNext(Fts5Hash *p){
+ assert( !sqlite3Fts5HashScanEof(p) );
+ p->pScan = p->pScan->pScanNext;
+}
+
+static int sqlite3Fts5HashScanEof(Fts5Hash *p){
+ return (p->pScan==0);
+}
+
+static void sqlite3Fts5HashScanEntry(
+ Fts5Hash *pHash,
+ const char **pzTerm, /* OUT: term (nul-terminated) */
+ const u8 **ppDoclist, /* OUT: pointer to doclist */
+ int *pnDoclist /* OUT: size of doclist in bytes */
+){
+ Fts5HashEntry *p;
+ if( (p = pHash->pScan) ){
+ char *zKey = fts5EntryKey(p);
+ int nTerm = (int)strlen(zKey);
+ fts5HashAddPoslistSize(pHash, p, 0);
+ *pzTerm = zKey;
+ *ppDoclist = (const u8*)&zKey[nTerm+1];
+ *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
+ }else{
+ *pzTerm = 0;
+ *ppDoclist = 0;
+ *pnDoclist = 0;
+ }
+}
+
+/*
+** 2014 May 31
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** Low level access to the FTS index stored in the database file. The
+** routines in this file file implement all read and write access to the
+** %_data table. Other parts of the system access this functionality via
+** the interface defined in fts5Int.h.
+*/
+
+
+/* #include "fts5Int.h" */
+
+/*
+** Overview:
+**
+** The %_data table contains all the FTS indexes for an FTS5 virtual table.
+** As well as the main term index, there may be up to 31 prefix indexes.
+** The format is similar to FTS3/4, except that:
+**
+** * all segment b-tree leaf data is stored in fixed size page records
+** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
+** taken to ensure it is possible to iterate in either direction through
+** the entries in a doclist, or to seek to a specific entry within a
+** doclist, without loading it into memory.
+**
+** * large doclists that span many pages have associated "doclist index"
+** records that contain a copy of the first rowid on each page spanned by
+** the doclist. This is used to speed up seek operations, and merges of
+** large doclists with very small doclists.
+**
+** * extra fields in the "structure record" record the state of ongoing
+** incremental merge operations.
+**
+*/
+
+
+#define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
+#define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
+
+#define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
+
+#define FTS5_MAIN_PREFIX '0'
+
+#if FTS5_MAX_PREFIX_INDEXES > 31
+# error "FTS5_MAX_PREFIX_INDEXES is too large"
+#endif
+
+/*
+** Details:
+**
+** The %_data table managed by this module,
+**
+** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
+**
+** , contains the following 5 types of records. See the comments surrounding
+** the FTS5_*_ROWID macros below for a description of how %_data rowids are
+** assigned to each fo them.
+**
+** 1. Structure Records:
+**
+** The set of segments that make up an index - the index structure - are
+** recorded in a single record within the %_data table. The record consists
+** of a single 32-bit configuration cookie value followed by a list of
+** SQLite varints. If the FTS table features more than one index (because
+** there are one or more prefix indexes), it is guaranteed that all share
+** the same cookie value.
+**
+** Immediately following the configuration cookie, the record begins with
+** three varints:
+**
+** + number of levels,
+** + total number of segments on all levels,
+** + value of write counter.
+**
+** Then, for each level from 0 to nMax:
+**
+** + number of input segments in ongoing merge.
+** + total number of segments in level.
+** + for each segment from oldest to newest:
+** + segment id (always > 0)
+** + first leaf page number (often 1, always greater than 0)
+** + final leaf page number
+**
+** 2. The Averages Record:
+**
+** A single record within the %_data table. The data is a list of varints.
+** The first value is the number of rows in the index. Then, for each column
+** from left to right, the total number of tokens in the column for all
+** rows of the table.
+**
+** 3. Segment leaves:
+**
+** TERM/DOCLIST FORMAT:
+**
+** Most of each segment leaf is taken up by term/doclist data. The
+** general format of term/doclist, starting with the first term
+** on the leaf page, is:
+**
+** varint : size of first term
+** blob: first term data
+** doclist: first doclist
+** zero-or-more {
+** varint: number of bytes in common with previous term
+** varint: number of bytes of new term data (nNew)
+** blob: nNew bytes of new term data
+** doclist: next doclist
+** }
+**
+** doclist format:
+**
+** varint: first rowid
+** poslist: first poslist
+** zero-or-more {
+** varint: rowid delta (always > 0)
+** poslist: next poslist
+** }
+**
+** poslist format:
+**
+** varint: size of poslist in bytes multiplied by 2, not including
+** this field. Plus 1 if this entry carries the "delete" flag.
+** collist: collist for column 0
+** zero-or-more {
+** 0x01 byte
+** varint: column number (I)
+** collist: collist for column I
+** }
+**
+** collist format:
+**
+** varint: first offset + 2
+** zero-or-more {
+** varint: offset delta + 2
+** }
+**
+** PAGE FORMAT
+**
+** Each leaf page begins with a 4-byte header containing 2 16-bit
+** unsigned integer fields in big-endian format. They are:
+**
+** * The byte offset of the first rowid on the page, if it exists
+** and occurs before the first term (otherwise 0).
+**
+** * The byte offset of the start of the page footer. If the page
+** footer is 0 bytes in size, then this field is the same as the
+** size of the leaf page in bytes.
+**
+** The page footer consists of a single varint for each term located
+** on the page. Each varint is the byte offset of the current term
+** within the page, delta-compressed against the previous value. In
+** other words, the first varint in the footer is the byte offset of
+** the first term, the second is the byte offset of the second less that
+** of the first, and so on.
+**
+** The term/doclist format described above is accurate if the entire
+** term/doclist data fits on a single leaf page. If this is not the case,
+** the format is changed in two ways:
+**
+** + if the first rowid on a page occurs before the first term, it
+** is stored as a literal value:
+**
+** varint: first rowid
+**
+** + the first term on each page is stored in the same way as the
+** very first term of the segment:
+**
+** varint : size of first term
+** blob: first term data
+**
+** 5. Segment doclist indexes:
+**
+** Doclist indexes are themselves b-trees, however they usually consist of
+** a single leaf record only. The format of each doclist index leaf page
+** is:
+**
+** * Flags byte. Bits are:
+** 0x01: Clear if leaf is also the root page, otherwise set.
+**
+** * Page number of fts index leaf page. As a varint.
+**
+** * First rowid on page indicated by previous field. As a varint.
+**
+** * A list of varints, one for each subsequent termless page. A
+** positive delta if the termless page contains at least one rowid,
+** or an 0x00 byte otherwise.
+**
+** Internal doclist index nodes are:
+**
+** * Flags byte. Bits are:
+** 0x01: Clear for root page, otherwise set.
+**
+** * Page number of first child page. As a varint.
+**
+** * Copy of first rowid on page indicated by previous field. As a varint.
+**
+** * A list of delta-encoded varints - the first rowid on each subsequent
+** child page.
+**
+*/
+
+/*
+** Rowids for the averages and structure records in the %_data table.
+*/
+#define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
+#define FTS5_STRUCTURE_ROWID 10 /* The structure record */
+
+/*
+** Macros determining the rowids used by segment leaves and dlidx leaves
+** and nodes. All nodes and leaves are stored in the %_data table with large
+** positive rowids.
+**
+** Each segment has a unique non-zero 16-bit id.
+**
+** The rowid for each segment leaf is found by passing the segment id and
+** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
+** sequentially starting from 1.
+*/
+#define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
+#define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
+#define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
+#define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
+
+#define fts5_dri(segid, dlidx, height, pgno) ( \
+ ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
+ ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
+ ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
+ ((i64)(pgno)) \
+)
+
+#define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
+#define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
+
+#ifdef SQLITE_DEBUG
+static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
+#endif
+
+
+/*
+** Each time a blob is read from the %_data table, it is padded with this
+** many zero bytes. This makes it easier to decode the various record formats
+** without overreading if the records are corrupt.
+*/
+#define FTS5_DATA_ZERO_PADDING 8
+#define FTS5_DATA_PADDING 20
+
+typedef struct Fts5Data Fts5Data;
+typedef struct Fts5DlidxIter Fts5DlidxIter;
+typedef struct Fts5DlidxLvl Fts5DlidxLvl;
+typedef struct Fts5DlidxWriter Fts5DlidxWriter;
+typedef struct Fts5Iter Fts5Iter;
+typedef struct Fts5PageWriter Fts5PageWriter;
+typedef struct Fts5SegIter Fts5SegIter;
+typedef struct Fts5DoclistIter Fts5DoclistIter;
+typedef struct Fts5SegWriter Fts5SegWriter;
+typedef struct Fts5Structure Fts5Structure;
+typedef struct Fts5StructureLevel Fts5StructureLevel;
+typedef struct Fts5StructureSegment Fts5StructureSegment;
+
+struct Fts5Data {
+ u8 *p; /* Pointer to buffer containing record */
+ int nn; /* Size of record in bytes */
+ int szLeaf; /* Size of leaf without page-index */
+};
+
+/*
+** One object per %_data table.
+*/
+struct Fts5Index {
+ Fts5Config *pConfig; /* Virtual table configuration */
+ char *zDataTbl; /* Name of %_data table */
+ int nWorkUnit; /* Leaf pages in a "unit" of work */
+
+ /*
+ ** Variables related to the accumulation of tokens and doclists within the
+ ** in-memory hash tables before they are flushed to disk.
+ */
+ Fts5Hash *pHash; /* Hash table for in-memory data */
+ int nPendingData; /* Current bytes of pending data */
+ i64 iWriteRowid; /* Rowid for current doc being written */
+ int bDelete; /* Current write is a delete */
+
+ /* Error state. */
+ int rc; /* Current error code */
+
+ /* State used by the fts5DataXXX() functions. */
+ sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
+ sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
+ sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
+ sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
+ sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
+ sqlite3_stmt *pIdxSelect;
+ int nRead; /* Total number of blocks read */
+
+ sqlite3_stmt *pDataVersion;
+ i64 iStructVersion; /* data_version when pStruct read */
+ Fts5Structure *pStruct; /* Current db structure (or NULL) */
+};
+
+struct Fts5DoclistIter {
+ u8 *aEof; /* Pointer to 1 byte past end of doclist */
+
+ /* Output variables. aPoslist==0 at EOF */
+ i64 iRowid;
+ u8 *aPoslist;
+ int nPoslist;
+ int nSize;
+};
+
+/*
+** The contents of the "structure" record for each index are represented
+** using an Fts5Structure record in memory. Which uses instances of the
+** other Fts5StructureXXX types as components.
+*/
+struct Fts5StructureSegment {
+ int iSegid; /* Segment id */
+ int pgnoFirst; /* First leaf page number in segment */
+ int pgnoLast; /* Last leaf page number in segment */
+};
+struct Fts5StructureLevel {
+ int nMerge; /* Number of segments in incr-merge */
+ int nSeg; /* Total number of segments on level */
+ Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
+};
+struct Fts5Structure {
+ int nRef; /* Object reference count */
+ u64 nWriteCounter; /* Total leaves written to level 0 */
+ int nSegment; /* Total segments in this structure */
+ int nLevel; /* Number of levels in this index */
+ Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
+};
+
+/*
+** An object of type Fts5SegWriter is used to write to segments.
+*/
+struct Fts5PageWriter {
+ int pgno; /* Page number for this page */
+ int iPrevPgidx; /* Previous value written into pgidx */
+ Fts5Buffer buf; /* Buffer containing leaf data */
+ Fts5Buffer pgidx; /* Buffer containing page-index */
+ Fts5Buffer term; /* Buffer containing previous term on page */
+};
+struct Fts5DlidxWriter {
+ int pgno; /* Page number for this page */
+ int bPrevValid; /* True if iPrev is valid */
+ i64 iPrev; /* Previous rowid value written to page */
+ Fts5Buffer buf; /* Buffer containing page data */
+};
+struct Fts5SegWriter {
+ int iSegid; /* Segid to write to */
+ Fts5PageWriter writer; /* PageWriter object */
+ i64 iPrevRowid; /* Previous rowid written to current leaf */
+ u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
+ u8 bFirstRowidInPage; /* True if next rowid is first in page */
+ /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
+ u8 bFirstTermInPage; /* True if next term will be first in leaf */
+ int nLeafWritten; /* Number of leaf pages written */
+ int nEmpty; /* Number of contiguous term-less nodes */
+
+ int nDlidx; /* Allocated size of aDlidx[] array */
+ Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
+
+ /* Values to insert into the %_idx table */
+ Fts5Buffer btterm; /* Next term to insert into %_idx table */
+ int iBtPage; /* Page number corresponding to btterm */
+};
+
+typedef struct Fts5CResult Fts5CResult;
+struct Fts5CResult {
+ u16 iFirst; /* aSeg[] index of firstest iterator */
+ u8 bTermEq; /* True if the terms are equal */
+};
+
+/*
+** Object for iterating through a single segment, visiting each term/rowid
+** pair in the segment.
+**
+** pSeg:
+** The segment to iterate through.
+**
+** iLeafPgno:
+** Current leaf page number within segment.
+**
+** iLeafOffset:
+** Byte offset within the current leaf that is the first byte of the
+** position list data (one byte passed the position-list size field).
+** rowid field of the current entry. Usually this is the size field of the
+** position list data. The exception is if the rowid for the current entry
+** is the last thing on the leaf page.
+**
+** pLeaf:
+** Buffer containing current leaf page data. Set to NULL at EOF.
+**
+** iTermLeafPgno, iTermLeafOffset:
+** Leaf page number containing the last term read from the segment. And
+** the offset immediately following the term data.
+**
+** flags:
+** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
+**
+** FTS5_SEGITER_ONETERM:
+** If set, set the iterator to point to EOF after the current doclist
+** has been exhausted. Do not proceed to the next term in the segment.
+**
+** FTS5_SEGITER_REVERSE:
+** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
+** it is set, iterate through rowid in descending order instead of the
+** default ascending order.
+**
+** iRowidOffset/nRowidOffset/aRowidOffset:
+** These are used if the FTS5_SEGITER_REVERSE flag is set.
+**
+** For each rowid on the page corresponding to the current term, the
+** corresponding aRowidOffset[] entry is set to the byte offset of the
+** start of the "position-list-size" field within the page.
+**
+** iTermIdx:
+** Index of current term on iTermLeafPgno.
+*/
+struct Fts5SegIter {
+ Fts5StructureSegment *pSeg; /* Segment to iterate through */
+ int flags; /* Mask of configuration flags */
+ int iLeafPgno; /* Current leaf page number */
+ Fts5Data *pLeaf; /* Current leaf data */
+ Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
+ int iLeafOffset; /* Byte offset within current leaf */
+
+ /* Next method */
+ void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
+
+ /* The page and offset from which the current term was read. The offset
+ ** is the offset of the first rowid in the current doclist. */
+ int iTermLeafPgno;
+ int iTermLeafOffset;
+
+ int iPgidxOff; /* Next offset in pgidx */
+ int iEndofDoclist;
+
+ /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
+ int iRowidOffset; /* Current entry in aRowidOffset[] */
+ int nRowidOffset; /* Allocated size of aRowidOffset[] array */
+ int *aRowidOffset; /* Array of offset to rowid fields */
+
+ Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
+
+ /* Variables populated based on current entry. */
+ Fts5Buffer term; /* Current term */
+ i64 iRowid; /* Current rowid */
+ int nPos; /* Number of bytes in current position list */
+ u8 bDel; /* True if the delete flag is set */
+};
+
+/*
+** Argument is a pointer to an Fts5Data structure that contains a
+** leaf page.
+*/
+#define ASSERT_SZLEAF_OK(x) assert( \
+ (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
+)
+
+#define FTS5_SEGITER_ONETERM 0x01
+#define FTS5_SEGITER_REVERSE 0x02
+
+/*
+** Argument is a pointer to an Fts5Data structure that contains a leaf
+** page. This macro evaluates to true if the leaf contains no terms, or
+** false if it contains at least one term.
+*/
+#define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
+
+#define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
+
+#define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
+
+/*
+** Object for iterating through the merged results of one or more segments,
+** visiting each term/rowid pair in the merged data.
+**
+** nSeg is always a power of two greater than or equal to the number of
+** segments that this object is merging data from. Both the aSeg[] and
+** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
+** with zeroed objects - these are handled as if they were iterators opened
+** on empty segments.
+**
+** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
+** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
+** comparison in this context is the index of the iterator that currently
+** points to the smaller term/rowid combination. Iterators at EOF are
+** considered to be greater than all other iterators.
+**
+** aFirst[1] contains the index in aSeg[] of the iterator that points to
+** the smallest key overall. aFirst[0] is unused.
+**
+** poslist:
+** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
+** There is no way to tell if this is populated or not.
+*/
+struct Fts5Iter {
+ Fts5IndexIter base; /* Base class containing output vars */
+
+ Fts5Index *pIndex; /* Index that owns this iterator */
+ Fts5Buffer poslist; /* Buffer containing current poslist */
+ Fts5Colset *pColset; /* Restrict matches to these columns */
+
+ /* Invoked to set output variables. */
+ void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
+
+ int nSeg; /* Size of aSeg[] array */
+ int bRev; /* True to iterate in reverse order */
+ u8 bSkipEmpty; /* True to skip deleted entries */
+
+ i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
+ Fts5CResult *aFirst; /* Current merge state (see above) */
+ Fts5SegIter aSeg[1]; /* Array of segment iterators */
+};
+
+
+/*
+** An instance of the following type is used to iterate through the contents
+** of a doclist-index record.
+**
+** pData:
+** Record containing the doclist-index data.
+**
+** bEof:
+** Set to true once iterator has reached EOF.
+**
+** iOff:
+** Set to the current offset within record pData.
+*/
+struct Fts5DlidxLvl {
+ Fts5Data *pData; /* Data for current page of this level */
+ int iOff; /* Current offset into pData */
+ int bEof; /* At EOF already */
+ int iFirstOff; /* Used by reverse iterators */
+
+ /* Output variables */
+ int iLeafPgno; /* Page number of current leaf page */
+ i64 iRowid; /* First rowid on leaf iLeafPgno */
+};
+struct Fts5DlidxIter {
+ int nLvl;
+ int iSegid;
+ Fts5DlidxLvl aLvl[1];
+};
+
+static void fts5PutU16(u8 *aOut, u16 iVal){
+ aOut[0] = (iVal>>8);
+ aOut[1] = (iVal&0xFF);
+}
+
+static u16 fts5GetU16(const u8 *aIn){
+ return ((u16)aIn[0] << 8) + aIn[1];
+}
+
+/*
+** Allocate and return a buffer at least nByte bytes in size.
+**
+** If an OOM error is encountered, return NULL and set the error code in
+** the Fts5Index handle passed as the first argument.
+*/
+static void *fts5IdxMalloc(Fts5Index *p, sqlite3_int64 nByte){
+ return sqlite3Fts5MallocZero(&p->rc, nByte);
+}
+
+/*
+** Compare the contents of the pLeft buffer with the pRight/nRight blob.
+**
+** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
+** +ve if pRight is smaller than pLeft. In other words:
+**
+** res = *pLeft - *pRight
+*/
+#ifdef SQLITE_DEBUG
+static int fts5BufferCompareBlob(
+ Fts5Buffer *pLeft, /* Left hand side of comparison */
+ const u8 *pRight, int nRight /* Right hand side of comparison */
+){
+ int nCmp = MIN(pLeft->n, nRight);
+ int res = memcmp(pLeft->p, pRight, nCmp);
+ return (res==0 ? (pLeft->n - nRight) : res);
+}
+#endif
+
+/*
+** Compare the contents of the two buffers using memcmp(). If one buffer
+** is a prefix of the other, it is considered the lesser.
+**
+** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
+** +ve if pRight is smaller than pLeft. In other words:
+**
+** res = *pLeft - *pRight
+*/
+static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
+ int nCmp = MIN(pLeft->n, pRight->n);
+ int res = fts5Memcmp(pLeft->p, pRight->p, nCmp);
+ return (res==0 ? (pLeft->n - pRight->n) : res);
+}
+
+static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
+ int ret;
+ fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
+ return ret;
+}
+
+/*
+** Close the read-only blob handle, if it is open.
+*/
+static void sqlite3Fts5IndexCloseReader(Fts5Index *p){
+ if( p->pReader ){
+ sqlite3_blob *pReader = p->pReader;
+ p->pReader = 0;
+ sqlite3_blob_close(pReader);
+ }
+}
+
+/*
+** Retrieve a record from the %_data table.
+**
+** If an error occurs, NULL is returned and an error left in the
+** Fts5Index object.
+*/
+static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
+ Fts5Data *pRet = 0;
+ if( p->rc==SQLITE_OK ){
+ int rc = SQLITE_OK;
+
+ if( p->pReader ){
+ /* This call may return SQLITE_ABORT if there has been a savepoint
+ ** rollback since it was last used. In this case a new blob handle
+ ** is required. */
+ sqlite3_blob *pBlob = p->pReader;
+ p->pReader = 0;
+ rc = sqlite3_blob_reopen(pBlob, iRowid);
+ assert( p->pReader==0 );
+ p->pReader = pBlob;
+ if( rc!=SQLITE_OK ){
+ sqlite3Fts5IndexCloseReader(p);
+ }
+ if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
+ }
+
+ /* If the blob handle is not open at this point, open it and seek
+ ** to the requested entry. */
+ if( p->pReader==0 && rc==SQLITE_OK ){
+ Fts5Config *pConfig = p->pConfig;
+ rc = sqlite3_blob_open(pConfig->db,
+ pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
+ );
+ }
+
+ /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
+ ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
+ ** All the reasons those functions might return SQLITE_ERROR - missing
+ ** table, missing row, non-blob/text in block column - indicate
+ ** backing store corruption. */
+ if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
+
+ if( rc==SQLITE_OK ){
+ u8 *aOut = 0; /* Read blob data into this buffer */
+ int nByte = sqlite3_blob_bytes(p->pReader);
+ sqlite3_int64 nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
+ pRet = (Fts5Data*)sqlite3_malloc64(nAlloc);
+ if( pRet ){
+ pRet->nn = nByte;
+ aOut = pRet->p = (u8*)&pRet[1];
+ }else{
+ rc = SQLITE_NOMEM;
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
+ }
+ if( rc!=SQLITE_OK ){
+ sqlite3_free(pRet);
+ pRet = 0;
+ }else{
+ /* TODO1: Fix this */
+ pRet->p[nByte] = 0x00;
+ pRet->p[nByte+1] = 0x00;
+ pRet->szLeaf = fts5GetU16(&pRet->p[2]);
+ }
+ }
+ p->rc = rc;
+ p->nRead++;
+ }
+
+ assert( (pRet==0)==(p->rc!=SQLITE_OK) );
+ return pRet;
+}
+
+/*
+** Release a reference to data record returned by an earlier call to
+** fts5DataRead().
+*/
+static void fts5DataRelease(Fts5Data *pData){
+ sqlite3_free(pData);
+}
+
+static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
+ Fts5Data *pRet = fts5DataRead(p, iRowid);
+ if( pRet ){
+ if( pRet->nn<4 || pRet->szLeaf>pRet->nn ){
+ p->rc = FTS5_CORRUPT;
+ fts5DataRelease(pRet);
+ pRet = 0;
+ }
+ }
+ return pRet;
+}
+
+static int fts5IndexPrepareStmt(
+ Fts5Index *p,
+ sqlite3_stmt **ppStmt,
+ char *zSql
+){
+ if( p->rc==SQLITE_OK ){
+ if( zSql ){
+ p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
+ SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB,
+ ppStmt, 0);
+ }else{
+ p->rc = SQLITE_NOMEM;
+ }
+ }
+ sqlite3_free(zSql);
+ return p->rc;
+}
+
+
+/*
+** INSERT OR REPLACE a record into the %_data table.
+*/
+static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
+ if( p->rc!=SQLITE_OK ) return;
+
+ if( p->pWriter==0 ){
+ Fts5Config *pConfig = p->pConfig;
+ fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
+ "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
+ pConfig->zDb, pConfig->zName
+ ));
+ if( p->rc ) return;
+ }
+
+ sqlite3_bind_int64(p->pWriter, 1, iRowid);
+ sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
+ sqlite3_step(p->pWriter);
+ p->rc = sqlite3_reset(p->pWriter);
+ sqlite3_bind_null(p->pWriter, 2);
+}
+
+/*
+** Execute the following SQL:
+**
+** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
+*/
+static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
+ if( p->rc!=SQLITE_OK ) return;
+
+ if( p->pDeleter==0 ){
+ Fts5Config *pConfig = p->pConfig;
+ char *zSql = sqlite3_mprintf(
+ "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
+ pConfig->zDb, pConfig->zName
+ );
+ if( fts5IndexPrepareStmt(p, &p->pDeleter, zSql) ) return;
+ }
+
+ sqlite3_bind_int64(p->pDeleter, 1, iFirst);
+ sqlite3_bind_int64(p->pDeleter, 2, iLast);
+ sqlite3_step(p->pDeleter);
+ p->rc = sqlite3_reset(p->pDeleter);
+}
+
+/*
+** Remove all records associated with segment iSegid.
+*/
+static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
+ i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
+ i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
+ fts5DataDelete(p, iFirst, iLast);
+ if( p->pIdxDeleter==0 ){
+ Fts5Config *pConfig = p->pConfig;
+ fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
+ "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
+ pConfig->zDb, pConfig->zName
+ ));
+ }
+ if( p->rc==SQLITE_OK ){
+ sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
+ sqlite3_step(p->pIdxDeleter);
+ p->rc = sqlite3_reset(p->pIdxDeleter);
+ }
+}
+
+/*
+** Release a reference to an Fts5Structure object returned by an earlier
+** call to fts5StructureRead() or fts5StructureDecode().
+*/
+static void fts5StructureRelease(Fts5Structure *pStruct){
+ if( pStruct && 0>=(--pStruct->nRef) ){
+ int i;
+ assert( pStruct->nRef==0 );
+ for(i=0; i<pStruct->nLevel; i++){
+ sqlite3_free(pStruct->aLevel[i].aSeg);
+ }
+ sqlite3_free(pStruct);
+ }
+}
+
+static void fts5StructureRef(Fts5Structure *pStruct){
+ pStruct->nRef++;
+}
+
+/*
+** Deserialize and return the structure record currently stored in serialized
+** form within buffer pData/nData.
+**
+** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
+** are over-allocated by one slot. This allows the structure contents
+** to be more easily edited.
+**
+** If an error occurs, *ppOut is set to NULL and an SQLite error code
+** returned. Otherwise, *ppOut is set to point to the new object and
+** SQLITE_OK returned.
+*/
+static int fts5StructureDecode(
+ const u8 *pData, /* Buffer containing serialized structure */
+ int nData, /* Size of buffer pData in bytes */
+ int *piCookie, /* Configuration cookie value */
+ Fts5Structure **ppOut /* OUT: Deserialized object */
+){
+ int rc = SQLITE_OK;
+ int i = 0;
+ int iLvl;
+ int nLevel = 0;
+ int nSegment = 0;
+ sqlite3_int64 nByte; /* Bytes of space to allocate at pRet */
+ Fts5Structure *pRet = 0; /* Structure object to return */
+
+ /* Grab the cookie value */
+ if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
+ i = 4;
+
+ /* Read the total number of levels and segments from the start of the
+ ** structure record. */
+ i += fts5GetVarint32(&pData[i], nLevel);
+ i += fts5GetVarint32(&pData[i], nSegment);
+ if( nLevel>FTS5_MAX_SEGMENT || nLevel<0
+ || nSegment>FTS5_MAX_SEGMENT || nSegment<0
+ ){
+ return FTS5_CORRUPT;
+ }
+ nByte = (
+ sizeof(Fts5Structure) + /* Main structure */
+ sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
+ );
+ pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
+
+ if( pRet ){
+ pRet->nRef = 1;
+ pRet->nLevel = nLevel;
+ pRet->nSegment = nSegment;
+ i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
+
+ for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
+ Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
+ int nTotal = 0;
+ int iSeg;
+
+ if( i>=nData ){
+ rc = FTS5_CORRUPT;
+ }else{
+ i += fts5GetVarint32(&pData[i], pLvl->nMerge);
+ i += fts5GetVarint32(&pData[i], nTotal);
+ if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT;
+ pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
+ nTotal * sizeof(Fts5StructureSegment)
+ );
+ nSegment -= nTotal;
+ }
+
+ if( rc==SQLITE_OK ){
+ pLvl->nSeg = nTotal;
+ for(iSeg=0; iSeg<nTotal; iSeg++){
+ Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
+ if( i>=nData ){
+ rc = FTS5_CORRUPT;
+ break;
+ }
+ i += fts5GetVarint32(&pData[i], pSeg->iSegid);
+ i += fts5GetVarint32(&pData[i], pSeg->pgnoFirst);
+ i += fts5GetVarint32(&pData[i], pSeg->pgnoLast);
+ if( pSeg->pgnoLast<pSeg->pgnoFirst ){
+ rc = FTS5_CORRUPT;
+ break;
+ }
+ }
+ if( iLvl>0 && pLvl[-1].nMerge && nTotal==0 ) rc = FTS5_CORRUPT;
+ if( iLvl==nLevel-1 && pLvl->nMerge ) rc = FTS5_CORRUPT;
+ }
+ }
+ if( nSegment!=0 && rc==SQLITE_OK ) rc = FTS5_CORRUPT;
+
+ if( rc!=SQLITE_OK ){
+ fts5StructureRelease(pRet);
+ pRet = 0;
+ }
+ }
+
+ *ppOut = pRet;
+ return rc;
+}
+
+/*
+**
+*/
+static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
+ if( *pRc==SQLITE_OK ){
+ Fts5Structure *pStruct = *ppStruct;
+ int nLevel = pStruct->nLevel;
+ sqlite3_int64 nByte = (
+ sizeof(Fts5Structure) + /* Main structure */
+ sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
+ );
+
+ pStruct = sqlite3_realloc64(pStruct, nByte);
+ if( pStruct ){
+ memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
+ pStruct->nLevel++;
+ *ppStruct = pStruct;
+ }else{
+ *pRc = SQLITE_NOMEM;
+ }
+ }
+}
+
+/*
+** Extend level iLvl so that there is room for at least nExtra more
+** segments.
+*/
+static void fts5StructureExtendLevel(
+ int *pRc,
+ Fts5Structure *pStruct,
+ int iLvl,
+ int nExtra,
+ int bInsert
+){
+ if( *pRc==SQLITE_OK ){
+ Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
+ Fts5StructureSegment *aNew;
+ sqlite3_int64 nByte;
+
+ nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
+ aNew = sqlite3_realloc64(pLvl->aSeg, nByte);
+ if( aNew ){
+ if( bInsert==0 ){
+ memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
+ }else{
+ int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
+ memmove(&aNew[nExtra], aNew, nMove);
+ memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
+ }
+ pLvl->aSeg = aNew;
+ }else{
+ *pRc = SQLITE_NOMEM;
+ }
+ }
+}
+
+static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
+ Fts5Structure *pRet = 0;
+ Fts5Config *pConfig = p->pConfig;
+ int iCookie; /* Configuration cookie */
+ Fts5Data *pData;
+
+ pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
+ if( p->rc==SQLITE_OK ){
+ /* TODO: Do we need this if the leaf-index is appended? Probably... */
+ memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
+ p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
+ if( p->rc==SQLITE_OK && (pConfig->pgsz==0 || pConfig->iCookie!=iCookie) ){
+ p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
+ }
+ fts5DataRelease(pData);
+ if( p->rc!=SQLITE_OK ){
+ fts5StructureRelease(pRet);
+ pRet = 0;
+ }
+ }
+
+ return pRet;
+}
+
+static i64 fts5IndexDataVersion(Fts5Index *p){
+ i64 iVersion = 0;
+
+ if( p->rc==SQLITE_OK ){
+ if( p->pDataVersion==0 ){
+ p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
+ sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
+ );
+ if( p->rc ) return 0;
+ }
+
+ if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
+ iVersion = sqlite3_column_int64(p->pDataVersion, 0);
+ }
+ p->rc = sqlite3_reset(p->pDataVersion);
+ }
+
+ return iVersion;
+}
+
+/*
+** Read, deserialize and return the structure record.
+**
+** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
+** are over-allocated as described for function fts5StructureDecode()
+** above.
+**
+** If an error occurs, NULL is returned and an error code left in the
+** Fts5Index handle. If an error has already occurred when this function
+** is called, it is a no-op.
+*/
+static Fts5Structure *fts5StructureRead(Fts5Index *p){
+
+ if( p->pStruct==0 ){
+ p->iStructVersion = fts5IndexDataVersion(p);
+ if( p->rc==SQLITE_OK ){
+ p->pStruct = fts5StructureReadUncached(p);
+ }
+ }
+
+#if 0
+ else{
+ Fts5Structure *pTest = fts5StructureReadUncached(p);
+ if( pTest ){
+ int i, j;
+ assert_nc( p->pStruct->nSegment==pTest->nSegment );
+ assert_nc( p->pStruct->nLevel==pTest->nLevel );
+ for(i=0; i<pTest->nLevel; i++){
+ assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
+ assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
+ for(j=0; j<pTest->aLevel[i].nSeg; j++){
+ Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
+ Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
+ assert_nc( p1->iSegid==p2->iSegid );
+ assert_nc( p1->pgnoFirst==p2->pgnoFirst );
+ assert_nc( p1->pgnoLast==p2->pgnoLast );
+ }
+ }
+ fts5StructureRelease(pTest);
+ }
+ }
+#endif
+
+ if( p->rc!=SQLITE_OK ) return 0;
+ assert( p->iStructVersion!=0 );
+ assert( p->pStruct!=0 );
+ fts5StructureRef(p->pStruct);
+ return p->pStruct;
+}
+
+static void fts5StructureInvalidate(Fts5Index *p){
+ if( p->pStruct ){
+ fts5StructureRelease(p->pStruct);
+ p->pStruct = 0;
+ }
+}
+
+/*
+** Return the total number of segments in index structure pStruct. This
+** function is only ever used as part of assert() conditions.
+*/
+#ifdef SQLITE_DEBUG
+static int fts5StructureCountSegments(Fts5Structure *pStruct){
+ int nSegment = 0; /* Total number of segments */
+ if( pStruct ){
+ int iLvl; /* Used to iterate through levels */
+ for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
+ nSegment += pStruct->aLevel[iLvl].nSeg;
+ }
+ }
+
+ return nSegment;
+}
+#endif
+
+#define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
+ assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
+ memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
+ (pBuf)->n += nBlob; \
+}
+
+#define fts5BufferSafeAppendVarint(pBuf, iVal) { \
+ (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
+ assert( (pBuf)->nSpace>=(pBuf)->n ); \
+}
+
+
+/*
+** Serialize and store the "structure" record.
+**
+** If an error occurs, leave an error code in the Fts5Index object. If an
+** error has already occurred, this function is a no-op.
+*/
+static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
+ if( p->rc==SQLITE_OK ){
+ Fts5Buffer buf; /* Buffer to serialize record into */
+ int iLvl; /* Used to iterate through levels */
+ int iCookie; /* Cookie value to store */
+
+ assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
+ memset(&buf, 0, sizeof(Fts5Buffer));
+
+ /* Append the current configuration cookie */
+ iCookie = p->pConfig->iCookie;
+ if( iCookie<0 ) iCookie = 0;
+
+ if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
+ sqlite3Fts5Put32(buf.p, iCookie);
+ buf.n = 4;
+ fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
+ fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
+ fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
+ }
+
+ for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
+ int iSeg; /* Used to iterate through segments */
+ Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
+ fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
+ fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
+ assert( pLvl->nMerge<=pLvl->nSeg );
+
+ for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
+ fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
+ fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
+ fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
+ }
+ }
+
+ fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
+ fts5BufferFree(&buf);
+ }
+}
+
+#if 0
+static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
+static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
+ int rc = SQLITE_OK;
+ Fts5Buffer buf;
+ memset(&buf, 0, sizeof(buf));
+ fts5DebugStructure(&rc, &buf, pStruct);
+ fprintf(stdout, "%s: %s\n", zCaption, buf.p);
+ fflush(stdout);
+ fts5BufferFree(&buf);
+}
+#else
+# define fts5PrintStructure(x,y)
+#endif
+
+static int fts5SegmentSize(Fts5StructureSegment *pSeg){
+ return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
+}
+
+/*
+** Return a copy of index structure pStruct. Except, promote as many
+** segments as possible to level iPromote. If an OOM occurs, NULL is
+** returned.
+*/
+static void fts5StructurePromoteTo(
+ Fts5Index *p,
+ int iPromote,
+ int szPromote,
+ Fts5Structure *pStruct
+){
+ int il, is;
+ Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
+
+ if( pOut->nMerge==0 ){
+ for(il=iPromote+1; il<pStruct->nLevel; il++){
+ Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
+ if( pLvl->nMerge ) return;
+ for(is=pLvl->nSeg-1; is>=0; is--){
+ int sz = fts5SegmentSize(&pLvl->aSeg[is]);
+ if( sz>szPromote ) return;
+ fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
+ if( p->rc ) return;
+ memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
+ pOut->nSeg++;
+ pLvl->nSeg--;
+ }
+ }
+ }
+}
+
+/*
+** A new segment has just been written to level iLvl of index structure
+** pStruct. This function determines if any segments should be promoted
+** as a result. Segments are promoted in two scenarios:
+**
+** a) If the segment just written is smaller than one or more segments
+** within the previous populated level, it is promoted to the previous
+** populated level.
+**
+** b) If the segment just written is larger than the newest segment on
+** the next populated level, then that segment, and any other adjacent
+** segments that are also smaller than the one just written, are
+** promoted.
+**
+** If one or more segments are promoted, the structure object is updated
+** to reflect this.
+*/
+static void fts5StructurePromote(
+ Fts5Index *p, /* FTS5 backend object */
+ int iLvl, /* Index level just updated */
+ Fts5Structure *pStruct /* Index structure */
+){
+ if( p->rc==SQLITE_OK ){
+ int iTst;
+ int iPromote = -1;
+ int szPromote = 0; /* Promote anything this size or smaller */
+ Fts5StructureSegment *pSeg; /* Segment just written */
+ int szSeg; /* Size of segment just written */
+ int nSeg = pStruct->aLevel[iLvl].nSeg;
+
+ if( nSeg==0 ) return;
+ pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
+ szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
+
+ /* Check for condition (a) */
+ for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
+ if( iTst>=0 ){
+ int i;
+ int szMax = 0;
+ Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
+ assert( pTst->nMerge==0 );
+ for(i=0; i<pTst->nSeg; i++){
+ int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
+ if( sz>szMax ) szMax = sz;
+ }
+ if( szMax>=szSeg ){
+ /* Condition (a) is true. Promote the newest segment on level
+ ** iLvl to level iTst. */
+ iPromote = iTst;
+ szPromote = szMax;
+ }
+ }
+
+ /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
+ ** is a no-op if it is not. */
+ if( iPromote<0 ){
+ iPromote = iLvl;
+ szPromote = szSeg;
+ }
+ fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
+ }
+}
+
+
+/*
+** Advance the iterator passed as the only argument. If the end of the
+** doclist-index page is reached, return non-zero.
+*/
+static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
+ Fts5Data *pData = pLvl->pData;
+
+ if( pLvl->iOff==0 ){
+ assert( pLvl->bEof==0 );
+ pLvl->iOff = 1;
+ pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
+ pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
+ pLvl->iFirstOff = pLvl->iOff;
+ }else{
+ int iOff;
+ for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
+ if( pData->p[iOff] ) break;
+ }
+
+ if( iOff<pData->nn ){
+ i64 iVal;
+ pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
+ iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
+ pLvl->iRowid += iVal;
+ pLvl->iOff = iOff;
+ }else{
+ pLvl->bEof = 1;
+ }
+ }
+
+ return pLvl->bEof;
+}
+
+/*
+** Advance the iterator passed as the only argument.
+*/
+static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
+ Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
+
+ assert( iLvl<pIter->nLvl );
+ if( fts5DlidxLvlNext(pLvl) ){
+ if( (iLvl+1) < pIter->nLvl ){
+ fts5DlidxIterNextR(p, pIter, iLvl+1);
+ if( pLvl[1].bEof==0 ){
+ fts5DataRelease(pLvl->pData);
+ memset(pLvl, 0, sizeof(Fts5DlidxLvl));
+ pLvl->pData = fts5DataRead(p,
+ FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
+ );
+ if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
+ }
+ }
+ }
+
+ return pIter->aLvl[0].bEof;
+}
+static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
+ return fts5DlidxIterNextR(p, pIter, 0);
+}
+
+/*
+** The iterator passed as the first argument has the following fields set
+** as follows. This function sets up the rest of the iterator so that it
+** points to the first rowid in the doclist-index.
+**
+** pData:
+** pointer to doclist-index record,
+**
+** When this function is called pIter->iLeafPgno is the page number the
+** doclist is associated with (the one featuring the term).
+*/
+static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
+ int i;
+ for(i=0; i<pIter->nLvl; i++){
+ fts5DlidxLvlNext(&pIter->aLvl[i]);
+ }
+ return pIter->aLvl[0].bEof;
+}
+
+
+static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
+ return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
+}
+
+static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
+ int i;
+
+ /* Advance each level to the last entry on the last page */
+ for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
+ Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
+ while( fts5DlidxLvlNext(pLvl)==0 );
+ pLvl->bEof = 0;
+
+ if( i>0 ){
+ Fts5DlidxLvl *pChild = &pLvl[-1];
+ fts5DataRelease(pChild->pData);
+ memset(pChild, 0, sizeof(Fts5DlidxLvl));
+ pChild->pData = fts5DataRead(p,
+ FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
+ );
+ }
+ }
+}
+
+/*
+** Move the iterator passed as the only argument to the previous entry.
+*/
+static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
+ int iOff = pLvl->iOff;
+
+ assert( pLvl->bEof==0 );
+ if( iOff<=pLvl->iFirstOff ){
+ pLvl->bEof = 1;
+ }else{
+ u8 *a = pLvl->pData->p;
+ i64 iVal;
+ int iLimit;
+ int ii;
+ int nZero = 0;
+
+ /* Currently iOff points to the first byte of a varint. This block
+ ** decrements iOff until it points to the first byte of the previous
+ ** varint. Taking care not to read any memory locations that occur
+ ** before the buffer in memory. */
+ iLimit = (iOff>9 ? iOff-9 : 0);
+ for(iOff--; iOff>iLimit; iOff--){
+ if( (a[iOff-1] & 0x80)==0 ) break;
+ }
+
+ fts5GetVarint(&a[iOff], (u64*)&iVal);
+ pLvl->iRowid -= iVal;
+ pLvl->iLeafPgno--;
+
+ /* Skip backwards past any 0x00 varints. */
+ for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
+ nZero++;
+ }
+ if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
+ /* The byte immediately before the last 0x00 byte has the 0x80 bit
+ ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
+ ** bytes before a[ii]. */
+ int bZero = 0; /* True if last 0x00 counts */
+ if( (ii-8)>=pLvl->iFirstOff ){
+ int j;
+ for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
+ bZero = (j>8);
+ }
+ if( bZero==0 ) nZero--;
+ }
+ pLvl->iLeafPgno -= nZero;
+ pLvl->iOff = iOff - nZero;
+ }
+
+ return pLvl->bEof;
+}
+
+static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
+ Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
+
+ assert( iLvl<pIter->nLvl );
+ if( fts5DlidxLvlPrev(pLvl) ){
+ if( (iLvl+1) < pIter->nLvl ){
+ fts5DlidxIterPrevR(p, pIter, iLvl+1);
+ if( pLvl[1].bEof==0 ){
+ fts5DataRelease(pLvl->pData);
+ memset(pLvl, 0, sizeof(Fts5DlidxLvl));
+ pLvl->pData = fts5DataRead(p,
+ FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
+ );
+ if( pLvl->pData ){
+ while( fts5DlidxLvlNext(pLvl)==0 );
+ pLvl->bEof = 0;
+ }
+ }
+ }
+ }
+
+ return pIter->aLvl[0].bEof;
+}
+static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
+ return fts5DlidxIterPrevR(p, pIter, 0);
+}
+
+/*
+** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
+*/
+static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
+ if( pIter ){
+ int i;
+ for(i=0; i<pIter->nLvl; i++){
+ fts5DataRelease(pIter->aLvl[i].pData);
+ }
+ sqlite3_free(pIter);
+ }
+}
+
+static Fts5DlidxIter *fts5DlidxIterInit(
+ Fts5Index *p, /* Fts5 Backend to iterate within */
+ int bRev, /* True for ORDER BY ASC */
+ int iSegid, /* Segment id */
+ int iLeafPg /* Leaf page number to load dlidx for */
+){
+ Fts5DlidxIter *pIter = 0;
+ int i;
+ int bDone = 0;
+
+ for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
+ sqlite3_int64 nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
+ Fts5DlidxIter *pNew;
+
+ pNew = (Fts5DlidxIter*)sqlite3_realloc64(pIter, nByte);
+ if( pNew==0 ){
+ p->rc = SQLITE_NOMEM;
+ }else{
+ i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
+ Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
+ pIter = pNew;
+ memset(pLvl, 0, sizeof(Fts5DlidxLvl));
+ pLvl->pData = fts5DataRead(p, iRowid);
+ if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
+ bDone = 1;
+ }
+ pIter->nLvl = i+1;
+ }
+ }
+
+ if( p->rc==SQLITE_OK ){
+ pIter->iSegid = iSegid;
+ if( bRev==0 ){
+ fts5DlidxIterFirst(pIter);
+ }else{
+ fts5DlidxIterLast(p, pIter);
+ }
+ }
+
+ if( p->rc!=SQLITE_OK ){
+ fts5DlidxIterFree(pIter);
+ pIter = 0;
+ }
+
+ return pIter;
+}
+
+static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
+ return pIter->aLvl[0].iRowid;
+}
+static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
+ return pIter->aLvl[0].iLeafPgno;
+}
+
+/*
+** Load the next leaf page into the segment iterator.
+*/
+static void fts5SegIterNextPage(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5SegIter *pIter /* Iterator to advance to next page */
+){
+ Fts5Data *pLeaf;
+ Fts5StructureSegment *pSeg = pIter->pSeg;
+ fts5DataRelease(pIter->pLeaf);
+ pIter->iLeafPgno++;
+ if( pIter->pNextLeaf ){
+ pIter->pLeaf = pIter->pNextLeaf;
+ pIter->pNextLeaf = 0;
+ }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
+ pIter->pLeaf = fts5LeafRead(p,
+ FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
+ );
+ }else{
+ pIter->pLeaf = 0;
+ }
+ pLeaf = pIter->pLeaf;
+
+ if( pLeaf ){
+ pIter->iPgidxOff = pLeaf->szLeaf;
+ if( fts5LeafIsTermless(pLeaf) ){
+ pIter->iEndofDoclist = pLeaf->nn+1;
+ }else{
+ pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
+ pIter->iEndofDoclist
+ );
+ }
+ }
+}
+
+/*
+** Argument p points to a buffer containing a varint to be interpreted as a
+** position list size field. Read the varint and return the number of bytes
+** read. Before returning, set *pnSz to the number of bytes in the position
+** list, and *pbDel to true if the delete flag is set, or false otherwise.
+*/
+static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
+ int nSz;
+ int n = 0;
+ fts5FastGetVarint32(p, n, nSz);
+ assert_nc( nSz>=0 );
+ *pnSz = nSz/2;
+ *pbDel = nSz & 0x0001;
+ return n;
+}
+
+/*
+** Fts5SegIter.iLeafOffset currently points to the first byte of a
+** position-list size field. Read the value of the field and store it
+** in the following variables:
+**
+** Fts5SegIter.nPos
+** Fts5SegIter.bDel
+**
+** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
+** position list content (if any).
+*/
+static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
+ if( p->rc==SQLITE_OK ){
+ int iOff = pIter->iLeafOffset; /* Offset to read at */
+ ASSERT_SZLEAF_OK(pIter->pLeaf);
+ if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
+ int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
+ pIter->bDel = 0;
+ pIter->nPos = 1;
+ if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
+ pIter->bDel = 1;
+ iOff++;
+ if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
+ pIter->nPos = 1;
+ iOff++;
+ }else{
+ pIter->nPos = 0;
+ }
+ }
+ }else{
+ int nSz;
+ fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
+ pIter->bDel = (nSz & 0x0001);
+ pIter->nPos = nSz>>1;
+ assert_nc( pIter->nPos>=0 );
+ }
+ pIter->iLeafOffset = iOff;
+ }
+}
+
+static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
+ u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
+ int iOff = pIter->iLeafOffset;
+
+ ASSERT_SZLEAF_OK(pIter->pLeaf);
+ if( iOff>=pIter->pLeaf->szLeaf ){
+ fts5SegIterNextPage(p, pIter);
+ if( pIter->pLeaf==0 ){
+ if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
+ return;
+ }
+ iOff = 4;
+ a = pIter->pLeaf->p;
+ }
+ iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
+ pIter->iLeafOffset = iOff;
+}
+
+/*
+** Fts5SegIter.iLeafOffset currently points to the first byte of the
+** "nSuffix" field of a term. Function parameter nKeep contains the value
+** of the "nPrefix" field (if there was one - it is passed 0 if this is
+** the first term in the segment).
+**
+** This function populates:
+**
+** Fts5SegIter.term
+** Fts5SegIter.rowid
+**
+** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
+** the first position list. The position list belonging to document
+** (Fts5SegIter.iRowid).
+*/
+static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
+ u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
+ int iOff = pIter->iLeafOffset; /* Offset to read at */
+ int nNew; /* Bytes of new data */
+
+ iOff += fts5GetVarint32(&a[iOff], nNew);
+ if( iOff+nNew>pIter->pLeaf->szLeaf || nKeep>pIter->term.n || nNew==0 ){
+ p->rc = FTS5_CORRUPT;
+ return;
+ }
+ pIter->term.n = nKeep;
+ fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
+ assert( pIter->term.n<=pIter->term.nSpace );
+ iOff += nNew;
+ pIter->iTermLeafOffset = iOff;
+ pIter->iTermLeafPgno = pIter->iLeafPgno;
+ pIter->iLeafOffset = iOff;
+
+ if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
+ pIter->iEndofDoclist = pIter->pLeaf->nn+1;
+ }else{
+ int nExtra;
+ pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
+ pIter->iEndofDoclist += nExtra;
+ }
+
+ fts5SegIterLoadRowid(p, pIter);
+}
+
+static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
+static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
+static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
+
+static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
+ if( pIter->flags & FTS5_SEGITER_REVERSE ){
+ pIter->xNext = fts5SegIterNext_Reverse;
+ }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
+ pIter->xNext = fts5SegIterNext_None;
+ }else{
+ pIter->xNext = fts5SegIterNext;
+ }
+}
+
+/*
+** Initialize the iterator object pIter to iterate through the entries in
+** segment pSeg. The iterator is left pointing to the first entry when
+** this function returns.
+**
+** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
+** an error has already occurred when this function is called, it is a no-op.
+*/
+static void fts5SegIterInit(
+ Fts5Index *p, /* FTS index object */
+ Fts5StructureSegment *pSeg, /* Description of segment */
+ Fts5SegIter *pIter /* Object to populate */
+){
+ if( pSeg->pgnoFirst==0 ){
+ /* This happens if the segment is being used as an input to an incremental
+ ** merge and all data has already been "trimmed". See function
+ ** fts5TrimSegments() for details. In this case leave the iterator empty.
+ ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
+ ** at EOF already. */
+ assert( pIter->pLeaf==0 );
+ return;
+ }
+
+ if( p->rc==SQLITE_OK ){
+ memset(pIter, 0, sizeof(*pIter));
+ fts5SegIterSetNext(p, pIter);
+ pIter->pSeg = pSeg;
+ pIter->iLeafPgno = pSeg->pgnoFirst-1;
+ fts5SegIterNextPage(p, pIter);
+ }
+
+ if( p->rc==SQLITE_OK ){
+ pIter->iLeafOffset = 4;
+ assert_nc( pIter->pLeaf->nn>4 );
+ assert_nc( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
+ pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
+ fts5SegIterLoadTerm(p, pIter, 0);
+ fts5SegIterLoadNPos(p, pIter);
+ }
+}
+
+/*
+** This function is only ever called on iterators created by calls to
+** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
+**
+** The iterator is in an unusual state when this function is called: the
+** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
+** the position-list size field for the first relevant rowid on the page.
+** Fts5SegIter.rowid is set, but nPos and bDel are not.
+**
+** This function advances the iterator so that it points to the last
+** relevant rowid on the page and, if necessary, initializes the
+** aRowidOffset[] and iRowidOffset variables. At this point the iterator
+** is in its regular state - Fts5SegIter.iLeafOffset points to the first
+** byte of the position list content associated with said rowid.
+*/
+static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
+ int eDetail = p->pConfig->eDetail;
+ int n = pIter->pLeaf->szLeaf;
+ int i = pIter->iLeafOffset;
+ u8 *a = pIter->pLeaf->p;
+ int iRowidOffset = 0;
+
+ if( n>pIter->iEndofDoclist ){
+ n = pIter->iEndofDoclist;
+ }
+
+ ASSERT_SZLEAF_OK(pIter->pLeaf);
+ while( 1 ){
+ i64 iDelta = 0;
+
+ if( eDetail==FTS5_DETAIL_NONE ){
+ /* todo */
+ if( i<n && a[i]==0 ){
+ i++;
+ if( i<n && a[i]==0 ) i++;
+ }
+ }else{
+ int nPos;
+ int bDummy;
+ i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
+ i += nPos;
+ }
+ if( i>=n ) break;
+ i += fts5GetVarint(&a[i], (u64*)&iDelta);
+ pIter->iRowid += iDelta;
+
+ /* If necessary, grow the pIter->aRowidOffset[] array. */
+ if( iRowidOffset>=pIter->nRowidOffset ){
+ int nNew = pIter->nRowidOffset + 8;
+ int *aNew = (int*)sqlite3_realloc64(pIter->aRowidOffset,nNew*sizeof(int));
+ if( aNew==0 ){
+ p->rc = SQLITE_NOMEM;
+ break;
+ }
+ pIter->aRowidOffset = aNew;
+ pIter->nRowidOffset = nNew;
+ }
+
+ pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
+ pIter->iLeafOffset = i;
+ }
+ pIter->iRowidOffset = iRowidOffset;
+ fts5SegIterLoadNPos(p, pIter);
+}
+
+/*
+**
+*/
+static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
+ assert( pIter->flags & FTS5_SEGITER_REVERSE );
+ assert( pIter->flags & FTS5_SEGITER_ONETERM );
+
+ fts5DataRelease(pIter->pLeaf);
+ pIter->pLeaf = 0;
+ while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
+ Fts5Data *pNew;
+ pIter->iLeafPgno--;
+ pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
+ pIter->pSeg->iSegid, pIter->iLeafPgno
+ ));
+ if( pNew ){
+ /* iTermLeafOffset may be equal to szLeaf if the term is the last
+ ** thing on the page - i.e. the first rowid is on the following page.
+ ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
+ if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
+ assert( pIter->pLeaf==0 );
+ if( pIter->iTermLeafOffset<pNew->szLeaf ){
+ pIter->pLeaf = pNew;
+ pIter->iLeafOffset = pIter->iTermLeafOffset;
+ }
+ }else{
+ int iRowidOff;
+ iRowidOff = fts5LeafFirstRowidOff(pNew);
+ if( iRowidOff ){
+ pIter->pLeaf = pNew;
+ pIter->iLeafOffset = iRowidOff;
+ }
+ }
+
+ if( pIter->pLeaf ){
+ u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
+ pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
+ break;
+ }else{
+ fts5DataRelease(pNew);
+ }
+ }
+ }
+
+ if( pIter->pLeaf ){
+ pIter->iEndofDoclist = pIter->pLeaf->nn+1;
+ fts5SegIterReverseInitPage(p, pIter);
+ }
+}
+
+/*
+** Return true if the iterator passed as the second argument currently
+** points to a delete marker. A delete marker is an entry with a 0 byte
+** position-list.
+*/
+static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
+ Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
+ return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
+}
+
+/*
+** Advance iterator pIter to the next entry.
+**
+** This version of fts5SegIterNext() is only used by reverse iterators.
+*/
+static void fts5SegIterNext_Reverse(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5SegIter *pIter, /* Iterator to advance */
+ int *pbUnused /* Unused */
+){
+ assert( pIter->flags & FTS5_SEGITER_REVERSE );
+ assert( pIter->pNextLeaf==0 );
+ UNUSED_PARAM(pbUnused);
+
+ if( pIter->iRowidOffset>0 ){
+ u8 *a = pIter->pLeaf->p;
+ int iOff;
+ i64 iDelta;
+
+ pIter->iRowidOffset--;
+ pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
+ fts5SegIterLoadNPos(p, pIter);
+ iOff = pIter->iLeafOffset;
+ if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
+ iOff += pIter->nPos;
+ }
+ fts5GetVarint(&a[iOff], (u64*)&iDelta);
+ pIter->iRowid -= iDelta;
+ }else{
+ fts5SegIterReverseNewPage(p, pIter);
+ }
+}
+
+/*
+** Advance iterator pIter to the next entry.
+**
+** This version of fts5SegIterNext() is only used if detail=none and the
+** iterator is not a reverse direction iterator.
+*/
+static void fts5SegIterNext_None(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5SegIter *pIter, /* Iterator to advance */
+ int *pbNewTerm /* OUT: Set for new term */
+){
+ int iOff;
+
+ assert( p->rc==SQLITE_OK );
+ assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
+ assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
+
+ ASSERT_SZLEAF_OK(pIter->pLeaf);
+ iOff = pIter->iLeafOffset;
+
+ /* Next entry is on the next page */
+ if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
+ fts5SegIterNextPage(p, pIter);
+ if( p->rc || pIter->pLeaf==0 ) return;
+ pIter->iRowid = 0;
+ iOff = 4;
+ }
+
+ if( iOff<pIter->iEndofDoclist ){
+ /* Next entry is on the current page */
+ i64 iDelta;
+ iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
+ pIter->iLeafOffset = iOff;
+ pIter->iRowid += iDelta;
+ }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
+ if( pIter->pSeg ){
+ int nKeep = 0;
+ if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
+ iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
+ }
+ pIter->iLeafOffset = iOff;
+ fts5SegIterLoadTerm(p, pIter, nKeep);
+ }else{
+ const u8 *pList = 0;
+ const char *zTerm = 0;
+ int nList;
+ sqlite3Fts5HashScanNext(p->pHash);
+ sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
+ if( pList==0 ) goto next_none_eof;
+ pIter->pLeaf->p = (u8*)pList;
+ pIter->pLeaf->nn = nList;
+ pIter->pLeaf->szLeaf = nList;
+ pIter->iEndofDoclist = nList;
+ sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
+ pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
+ }
+
+ if( pbNewTerm ) *pbNewTerm = 1;
+ }else{
+ goto next_none_eof;
+ }
+
+ fts5SegIterLoadNPos(p, pIter);
+
+ return;
+ next_none_eof:
+ fts5DataRelease(pIter->pLeaf);
+ pIter->pLeaf = 0;
+}
+
+
+/*
+** Advance iterator pIter to the next entry.
+**
+** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
+** is not considered an error if the iterator reaches EOF. If an error has
+** already occurred when this function is called, it is a no-op.
+*/
+static void fts5SegIterNext(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5SegIter *pIter, /* Iterator to advance */
+ int *pbNewTerm /* OUT: Set for new term */
+){
+ Fts5Data *pLeaf = pIter->pLeaf;
+ int iOff;
+ int bNewTerm = 0;
+ int nKeep = 0;
+ u8 *a;
+ int n;
+
+ assert( pbNewTerm==0 || *pbNewTerm==0 );
+ assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
+
+ /* Search for the end of the position list within the current page. */
+ a = pLeaf->p;
+ n = pLeaf->szLeaf;
+
+ ASSERT_SZLEAF_OK(pLeaf);
+ iOff = pIter->iLeafOffset + pIter->nPos;
+
+ if( iOff<n ){
+ /* The next entry is on the current page. */
+ assert_nc( iOff<=pIter->iEndofDoclist );
+ if( iOff>=pIter->iEndofDoclist ){
+ bNewTerm = 1;
+ if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
+ iOff += fts5GetVarint32(&a[iOff], nKeep);
+ }
+ }else{
+ u64 iDelta;
+ iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
+ pIter->iRowid += iDelta;
+ assert_nc( iDelta>0 );
+ }
+ pIter->iLeafOffset = iOff;
+
+ }else if( pIter->pSeg==0 ){
+ const u8 *pList = 0;
+ const char *zTerm = 0;
+ int nList = 0;
+ assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
+ if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
+ sqlite3Fts5HashScanNext(p->pHash);
+ sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
+ }
+ if( pList==0 ){
+ fts5DataRelease(pIter->pLeaf);
+ pIter->pLeaf = 0;
+ }else{
+ pIter->pLeaf->p = (u8*)pList;
+ pIter->pLeaf->nn = nList;
+ pIter->pLeaf->szLeaf = nList;
+ pIter->iEndofDoclist = nList+1;
+ sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
+ (u8*)zTerm);
+ pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
+ *pbNewTerm = 1;
+ }
+ }else{
+ iOff = 0;
+ /* Next entry is not on the current page */
+ while( iOff==0 ){
+ fts5SegIterNextPage(p, pIter);
+ pLeaf = pIter->pLeaf;
+ if( pLeaf==0 ) break;
+ ASSERT_SZLEAF_OK(pLeaf);
+ if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
+ iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
+ pIter->iLeafOffset = iOff;
+
+ if( pLeaf->nn>pLeaf->szLeaf ){
+ pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
+ &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
+ );
+ }
+ }
+ else if( pLeaf->nn>pLeaf->szLeaf ){
+ pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
+ &pLeaf->p[pLeaf->szLeaf], iOff
+ );
+ pIter->iLeafOffset = iOff;
+ pIter->iEndofDoclist = iOff;
+ bNewTerm = 1;
+ }
+ assert_nc( iOff<pLeaf->szLeaf );
+ if( iOff>pLeaf->szLeaf ){
+ p->rc = FTS5_CORRUPT;
+ return;
+ }
+ }
+ }
+
+ /* Check if the iterator is now at EOF. If so, return early. */
+ if( pIter->pLeaf ){
+ if( bNewTerm ){
+ if( pIter->flags & FTS5_SEGITER_ONETERM ){
+ fts5DataRelease(pIter->pLeaf);
+ pIter->pLeaf = 0;
+ }else{
+ fts5SegIterLoadTerm(p, pIter, nKeep);
+ fts5SegIterLoadNPos(p, pIter);
+ if( pbNewTerm ) *pbNewTerm = 1;
+ }
+ }else{
+ /* The following could be done by calling fts5SegIterLoadNPos(). But
+ ** this block is particularly performance critical, so equivalent
+ ** code is inlined.
+ **
+ ** Later: Switched back to fts5SegIterLoadNPos() because it supports
+ ** detail=none mode. Not ideal.
+ */
+ int nSz;
+ assert( p->rc==SQLITE_OK );
+ assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
+ fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
+ pIter->bDel = (nSz & 0x0001);
+ pIter->nPos = nSz>>1;
+ assert_nc( pIter->nPos>=0 );
+ }
+ }
+}
+
+#define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
+
+#define fts5IndexSkipVarint(a, iOff) { \
+ int iEnd = iOff+9; \
+ while( (a[iOff++] & 0x80) && iOff<iEnd ); \
+}
+
+/*
+** Iterator pIter currently points to the first rowid in a doclist. This
+** function sets the iterator up so that iterates in reverse order through
+** the doclist.
+*/
+static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
+ Fts5DlidxIter *pDlidx = pIter->pDlidx;
+ Fts5Data *pLast = 0;
+ int pgnoLast = 0;
+
+ if( pDlidx ){
+ int iSegid = pIter->pSeg->iSegid;
+ pgnoLast = fts5DlidxIterPgno(pDlidx);
+ pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
+ }else{
+ Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
+
+ /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
+ ** position-list content for the current rowid. Back it up so that it
+ ** points to the start of the position-list size field. */
+ int iPoslist;
+ if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
+ iPoslist = pIter->iTermLeafOffset;
+ }else{
+ iPoslist = 4;
+ }
+ fts5IndexSkipVarint(pLeaf->p, iPoslist);
+ pIter->iLeafOffset = iPoslist;
+
+ /* If this condition is true then the largest rowid for the current
+ ** term may not be stored on the current page. So search forward to
+ ** see where said rowid really is. */
+ if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
+ int pgno;
+ Fts5StructureSegment *pSeg = pIter->pSeg;
+
+ /* The last rowid in the doclist may not be on the current page. Search
+ ** forward to find the page containing the last rowid. */
+ for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
+ i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
+ Fts5Data *pNew = fts5DataRead(p, iAbs);
+ if( pNew ){
+ int iRowid, bTermless;
+ iRowid = fts5LeafFirstRowidOff(pNew);
+ bTermless = fts5LeafIsTermless(pNew);
+ if( iRowid ){
+ SWAPVAL(Fts5Data*, pNew, pLast);
+ pgnoLast = pgno;
+ }
+ fts5DataRelease(pNew);
+ if( bTermless==0 ) break;
+ }
+ }
+ }
+ }
+
+ /* If pLast is NULL at this point, then the last rowid for this doclist
+ ** lies on the page currently indicated by the iterator. In this case
+ ** pIter->iLeafOffset is already set to point to the position-list size
+ ** field associated with the first relevant rowid on the page.
+ **
+ ** Or, if pLast is non-NULL, then it is the page that contains the last
+ ** rowid. In this case configure the iterator so that it points to the
+ ** first rowid on this page.
+ */
+ if( pLast ){
+ int iOff;
+ fts5DataRelease(pIter->pLeaf);
+ pIter->pLeaf = pLast;
+ pIter->iLeafPgno = pgnoLast;
+ iOff = fts5LeafFirstRowidOff(pLast);
+ iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
+ pIter->iLeafOffset = iOff;
+
+ if( fts5LeafIsTermless(pLast) ){
+ pIter->iEndofDoclist = pLast->nn+1;
+ }else{
+ pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
+ }
+
+ }
+
+ fts5SegIterReverseInitPage(p, pIter);
+}
+
+/*
+** Iterator pIter currently points to the first rowid of a doclist.
+** There is a doclist-index associated with the final term on the current
+** page. If the current term is the last term on the page, load the
+** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
+*/
+static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
+ int iSeg = pIter->pSeg->iSegid;
+ int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
+ Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
+
+ assert( pIter->flags & FTS5_SEGITER_ONETERM );
+ assert( pIter->pDlidx==0 );
+
+ /* Check if the current doclist ends on this page. If it does, return
+ ** early without loading the doclist-index (as it belongs to a different
+ ** term. */
+ if( pIter->iTermLeafPgno==pIter->iLeafPgno
+ && pIter->iEndofDoclist<pLeaf->szLeaf
+ ){
+ return;
+ }
+
+ pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
+}
+
+/*
+** The iterator object passed as the second argument currently contains
+** no valid values except for the Fts5SegIter.pLeaf member variable. This
+** function searches the leaf page for a term matching (pTerm/nTerm).
+**
+** If the specified term is found on the page, then the iterator is left
+** pointing to it. If argument bGe is zero and the term is not found,
+** the iterator is left pointing at EOF.
+**
+** If bGe is non-zero and the specified term is not found, then the
+** iterator is left pointing to the smallest term in the segment that
+** is larger than the specified term, even if this term is not on the
+** current page.
+*/
+static void fts5LeafSeek(
+ Fts5Index *p, /* Leave any error code here */
+ int bGe, /* True for a >= search */
+ Fts5SegIter *pIter, /* Iterator to seek */
+ const u8 *pTerm, int nTerm /* Term to search for */
+){
+ int iOff;
+ const u8 *a = pIter->pLeaf->p;
+ int szLeaf = pIter->pLeaf->szLeaf;
+ int n = pIter->pLeaf->nn;
+
+ u32 nMatch = 0;
+ u32 nKeep = 0;
+ u32 nNew = 0;
+ u32 iTermOff;
+ int iPgidx; /* Current offset in pgidx */
+ int bEndOfPage = 0;
+
+ assert( p->rc==SQLITE_OK );
+
+ iPgidx = szLeaf;
+ iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
+ iOff = iTermOff;
+ if( iOff>n ){
+ p->rc = FTS5_CORRUPT;
+ return;
+ }
+
+ while( 1 ){
+
+ /* Figure out how many new bytes are in this term */
+ fts5FastGetVarint32(a, iOff, nNew);
+ if( nKeep<nMatch ){
+ goto search_failed;
+ }
+
+ assert( nKeep>=nMatch );
+ if( nKeep==nMatch ){
+ u32 nCmp;
+ u32 i;
+ nCmp = (u32)MIN(nNew, nTerm-nMatch);
+ for(i=0; i<nCmp; i++){
+ if( a[iOff+i]!=pTerm[nMatch+i] ) break;
+ }
+ nMatch += i;
+
+ if( (u32)nTerm==nMatch ){
+ if( i==nNew ){
+ goto search_success;
+ }else{
+ goto search_failed;
+ }
+ }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
+ goto search_failed;
+ }
+ }
+
+ if( iPgidx>=n ){
+ bEndOfPage = 1;
+ break;
+ }
+
+ iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
+ iTermOff += nKeep;
+ iOff = iTermOff;
+
+ if( iOff>=n ){
+ p->rc = FTS5_CORRUPT;
+ return;
+ }
+
+ /* Read the nKeep field of the next term. */
+ fts5FastGetVarint32(a, iOff, nKeep);
+ }
+
+ search_failed:
+ if( bGe==0 ){
+ fts5DataRelease(pIter->pLeaf);
+ pIter->pLeaf = 0;
+ return;
+ }else if( bEndOfPage ){
+ do {
+ fts5SegIterNextPage(p, pIter);
+ if( pIter->pLeaf==0 ) return;
+ a = pIter->pLeaf->p;
+ if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
+ iPgidx = pIter->pLeaf->szLeaf;
+ iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
+ if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
+ p->rc = FTS5_CORRUPT;
+ return;
+ }else{
+ nKeep = 0;
+ iTermOff = iOff;
+ n = pIter->pLeaf->nn;
+ iOff += fts5GetVarint32(&a[iOff], nNew);
+ break;
+ }
+ }
+ }while( 1 );
+ }
+
+ search_success:
+ if( (i64)iOff+nNew>n || nNew<1 ){
+ p->rc = FTS5_CORRUPT;
+ return;
+ }
+ pIter->iLeafOffset = iOff + nNew;
+ pIter->iTermLeafOffset = pIter->iLeafOffset;
+ pIter->iTermLeafPgno = pIter->iLeafPgno;
+
+ fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
+ fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
+
+ if( iPgidx>=n ){
+ pIter->iEndofDoclist = pIter->pLeaf->nn+1;
+ }else{
+ int nExtra;
+ iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
+ pIter->iEndofDoclist = iTermOff + nExtra;
+ }
+ pIter->iPgidxOff = iPgidx;
+
+ fts5SegIterLoadRowid(p, pIter);
+ fts5SegIterLoadNPos(p, pIter);
+}
+
+static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
+ if( p->pIdxSelect==0 ){
+ Fts5Config *pConfig = p->pConfig;
+ fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
+ "SELECT pgno FROM '%q'.'%q_idx' WHERE "
+ "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
+ pConfig->zDb, pConfig->zName
+ ));
+ }
+ return p->pIdxSelect;
+}
+
+/*
+** Initialize the object pIter to point to term pTerm/nTerm within segment
+** pSeg. If there is no such term in the index, the iterator is set to EOF.
+**
+** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
+** an error has already occurred when this function is called, it is a no-op.
+*/
+static void fts5SegIterSeekInit(
+ Fts5Index *p, /* FTS5 backend */
+ const u8 *pTerm, int nTerm, /* Term to seek to */
+ int flags, /* Mask of FTS5INDEX_XXX flags */
+ Fts5StructureSegment *pSeg, /* Description of segment */
+ Fts5SegIter *pIter /* Object to populate */
+){
+ int iPg = 1;
+ int bGe = (flags & FTS5INDEX_QUERY_SCAN);
+ int bDlidx = 0; /* True if there is a doclist-index */
+ sqlite3_stmt *pIdxSelect = 0;
+
+ assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
+ assert( pTerm && nTerm );
+ memset(pIter, 0, sizeof(*pIter));
+ pIter->pSeg = pSeg;
+
+ /* This block sets stack variable iPg to the leaf page number that may
+ ** contain term (pTerm/nTerm), if it is present in the segment. */
+ pIdxSelect = fts5IdxSelectStmt(p);
+ if( p->rc ) return;
+ sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
+ sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
+ if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
+ i64 val = sqlite3_column_int(pIdxSelect, 0);
+ iPg = (int)(val>>1);
+ bDlidx = (val & 0x0001);
+ }
+ p->rc = sqlite3_reset(pIdxSelect);
+ sqlite3_bind_null(pIdxSelect, 2);
+
+ if( iPg<pSeg->pgnoFirst ){
+ iPg = pSeg->pgnoFirst;
+ bDlidx = 0;
+ }
+
+ pIter->iLeafPgno = iPg - 1;
+ fts5SegIterNextPage(p, pIter);
+
+ if( pIter->pLeaf ){
+ fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
+ }
+
+ if( p->rc==SQLITE_OK && bGe==0 ){
+ pIter->flags |= FTS5_SEGITER_ONETERM;
+ if( pIter->pLeaf ){
+ if( flags & FTS5INDEX_QUERY_DESC ){
+ pIter->flags |= FTS5_SEGITER_REVERSE;
+ }
+ if( bDlidx ){
+ fts5SegIterLoadDlidx(p, pIter);
+ }
+ if( flags & FTS5INDEX_QUERY_DESC ){
+ fts5SegIterReverse(p, pIter);
+ }
+ }
+ }
+
+ fts5SegIterSetNext(p, pIter);
+
+ /* Either:
+ **
+ ** 1) an error has occurred, or
+ ** 2) the iterator points to EOF, or
+ ** 3) the iterator points to an entry with term (pTerm/nTerm), or
+ ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
+ ** to an entry with a term greater than or equal to (pTerm/nTerm).
+ */
+ assert_nc( p->rc!=SQLITE_OK /* 1 */
+ || pIter->pLeaf==0 /* 2 */
+ || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
+ || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
+ );
+}
+
+/*
+** Initialize the object pIter to point to term pTerm/nTerm within the
+** in-memory hash table. If there is no such term in the hash-table, the
+** iterator is set to EOF.
+**
+** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
+** an error has already occurred when this function is called, it is a no-op.
+*/
+static void fts5SegIterHashInit(
+ Fts5Index *p, /* FTS5 backend */
+ const u8 *pTerm, int nTerm, /* Term to seek to */
+ int flags, /* Mask of FTS5INDEX_XXX flags */
+ Fts5SegIter *pIter /* Object to populate */
+){
+ int nList = 0;
+ const u8 *z = 0;
+ int n = 0;
+ Fts5Data *pLeaf = 0;
+
+ assert( p->pHash );
+ assert( p->rc==SQLITE_OK );
+
+ if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
+ const u8 *pList = 0;
+
+ p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
+ sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
+ n = (z ? (int)strlen((const char*)z) : 0);
+ if( pList ){
+ pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
+ if( pLeaf ){
+ pLeaf->p = (u8*)pList;
+ }
+ }
+ }else{
+ p->rc = sqlite3Fts5HashQuery(p->pHash, sizeof(Fts5Data),
+ (const char*)pTerm, nTerm, (void**)&pLeaf, &nList
+ );
+ if( pLeaf ){
+ pLeaf->p = (u8*)&pLeaf[1];
+ }
+ z = pTerm;
+ n = nTerm;
+ pIter->flags |= FTS5_SEGITER_ONETERM;
+ }
+
+ if( pLeaf ){
+ sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
+ pLeaf->nn = pLeaf->szLeaf = nList;
+ pIter->pLeaf = pLeaf;
+ pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
+ pIter->iEndofDoclist = pLeaf->nn;
+
+ if( flags & FTS5INDEX_QUERY_DESC ){
+ pIter->flags |= FTS5_SEGITER_REVERSE;
+ fts5SegIterReverseInitPage(p, pIter);
+ }else{
+ fts5SegIterLoadNPos(p, pIter);
+ }
+ }
+
+ fts5SegIterSetNext(p, pIter);
+}
+
+/*
+** Zero the iterator passed as the only argument.
+*/
+static void fts5SegIterClear(Fts5SegIter *pIter){
+ fts5BufferFree(&pIter->term);
+ fts5DataRelease(pIter->pLeaf);
+ fts5DataRelease(pIter->pNextLeaf);
+ fts5DlidxIterFree(pIter->pDlidx);
+ sqlite3_free(pIter->aRowidOffset);
+ memset(pIter, 0, sizeof(Fts5SegIter));
+}
+
+#ifdef SQLITE_DEBUG
+
+/*
+** This function is used as part of the big assert() procedure implemented by
+** fts5AssertMultiIterSetup(). It ensures that the result currently stored
+** in *pRes is the correct result of comparing the current positions of the
+** two iterators.
+*/
+static void fts5AssertComparisonResult(
+ Fts5Iter *pIter,
+ Fts5SegIter *p1,
+ Fts5SegIter *p2,
+ Fts5CResult *pRes
+){
+ int i1 = p1 - pIter->aSeg;
+ int i2 = p2 - pIter->aSeg;
+
+ if( p1->pLeaf || p2->pLeaf ){
+ if( p1->pLeaf==0 ){
+ assert( pRes->iFirst==i2 );
+ }else if( p2->pLeaf==0 ){
+ assert( pRes->iFirst==i1 );
+ }else{
+ int nMin = MIN(p1->term.n, p2->term.n);
+ int res = fts5Memcmp(p1->term.p, p2->term.p, nMin);
+ if( res==0 ) res = p1->term.n - p2->term.n;
+
+ if( res==0 ){
+ assert( pRes->bTermEq==1 );
+ assert( p1->iRowid!=p2->iRowid );
+ res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
+ }else{
+ assert( pRes->bTermEq==0 );
+ }
+
+ if( res<0 ){
+ assert( pRes->iFirst==i1 );
+ }else{
+ assert( pRes->iFirst==i2 );
+ }
+ }
+ }
+}
+
+/*
+** This function is a no-op unless SQLITE_DEBUG is defined when this module
+** is compiled. In that case, this function is essentially an assert()
+** statement used to verify that the contents of the pIter->aFirst[] array
+** are correct.
+*/
+static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
+ if( p->rc==SQLITE_OK ){
+ Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
+ int i;
+
+ assert( (pFirst->pLeaf==0)==pIter->base.bEof );
+
+ /* Check that pIter->iSwitchRowid is set correctly. */
+ for(i=0; i<pIter->nSeg; i++){
+ Fts5SegIter *p1 = &pIter->aSeg[i];
+ assert( p1==pFirst
+ || p1->pLeaf==0
+ || fts5BufferCompare(&pFirst->term, &p1->term)
+ || p1->iRowid==pIter->iSwitchRowid
+ || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
+ );
+ }
+
+ for(i=0; i<pIter->nSeg; i+=2){
+ Fts5SegIter *p1 = &pIter->aSeg[i];
+ Fts5SegIter *p2 = &pIter->aSeg[i+1];
+ Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
+ fts5AssertComparisonResult(pIter, p1, p2, pRes);
+ }
+
+ for(i=1; i<(pIter->nSeg / 2); i+=2){
+ Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
+ Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
+ Fts5CResult *pRes = &pIter->aFirst[i];
+ fts5AssertComparisonResult(pIter, p1, p2, pRes);
+ }
+ }
+}
+#else
+# define fts5AssertMultiIterSetup(x,y)
+#endif
+
+/*
+** Do the comparison necessary to populate pIter->aFirst[iOut].
+**
+** If the returned value is non-zero, then it is the index of an entry
+** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
+** to a key that is a duplicate of another, higher priority,
+** segment-iterator in the pSeg->aSeg[] array.
+*/
+static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
+ int i1; /* Index of left-hand Fts5SegIter */
+ int i2; /* Index of right-hand Fts5SegIter */
+ int iRes;
+ Fts5SegIter *p1; /* Left-hand Fts5SegIter */
+ Fts5SegIter *p2; /* Right-hand Fts5SegIter */
+ Fts5CResult *pRes = &pIter->aFirst[iOut];
+
+ assert( iOut<pIter->nSeg && iOut>0 );
+ assert( pIter->bRev==0 || pIter->bRev==1 );
+
+ if( iOut>=(pIter->nSeg/2) ){
+ i1 = (iOut - pIter->nSeg/2) * 2;
+ i2 = i1 + 1;
+ }else{
+ i1 = pIter->aFirst[iOut*2].iFirst;
+ i2 = pIter->aFirst[iOut*2+1].iFirst;
+ }
+ p1 = &pIter->aSeg[i1];
+ p2 = &pIter->aSeg[i2];
+
+ pRes->bTermEq = 0;
+ if( p1->pLeaf==0 ){ /* If p1 is at EOF */
+ iRes = i2;
+ }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
+ iRes = i1;
+ }else{
+ int res = fts5BufferCompare(&p1->term, &p2->term);
+ if( res==0 ){
+ assert_nc( i2>i1 );
+ assert_nc( i2!=0 );
+ pRes->bTermEq = 1;
+ if( p1->iRowid==p2->iRowid ){
+ p1->bDel = p2->bDel;
+ return i2;
+ }
+ res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
+ }
+ assert( res!=0 );
+ if( res<0 ){
+ iRes = i1;
+ }else{
+ iRes = i2;
+ }
+ }
+
+ pRes->iFirst = (u16)iRes;
+ return 0;
+}
+
+/*
+** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
+** It is an error if leaf iLeafPgno does not exist or contains no rowids.
+*/
+static void fts5SegIterGotoPage(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5SegIter *pIter, /* Iterator to advance */
+ int iLeafPgno
+){
+ assert( iLeafPgno>pIter->iLeafPgno );
+
+ if( iLeafPgno>pIter->pSeg->pgnoLast ){
+ p->rc = FTS5_CORRUPT;
+ }else{
+ fts5DataRelease(pIter->pNextLeaf);
+ pIter->pNextLeaf = 0;
+ pIter->iLeafPgno = iLeafPgno-1;
+ fts5SegIterNextPage(p, pIter);
+ assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
+
+ if( p->rc==SQLITE_OK ){
+ int iOff;
+ u8 *a = pIter->pLeaf->p;
+ int n = pIter->pLeaf->szLeaf;
+
+ iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
+ if( iOff<4 || iOff>=n ){
+ p->rc = FTS5_CORRUPT;
+ }else{
+ iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
+ pIter->iLeafOffset = iOff;
+ fts5SegIterLoadNPos(p, pIter);
+ }
+ }
+ }
+}
+
+/*
+** Advance the iterator passed as the second argument until it is at or
+** past rowid iFrom. Regardless of the value of iFrom, the iterator is
+** always advanced at least once.
+*/
+static void fts5SegIterNextFrom(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5SegIter *pIter, /* Iterator to advance */
+ i64 iMatch /* Advance iterator at least this far */
+){
+ int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
+ Fts5DlidxIter *pDlidx = pIter->pDlidx;
+ int iLeafPgno = pIter->iLeafPgno;
+ int bMove = 1;
+
+ assert( pIter->flags & FTS5_SEGITER_ONETERM );
+ assert( pIter->pDlidx );
+ assert( pIter->pLeaf );
+
+ if( bRev==0 ){
+ while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
+ iLeafPgno = fts5DlidxIterPgno(pDlidx);
+ fts5DlidxIterNext(p, pDlidx);
+ }
+ assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
+ if( iLeafPgno>pIter->iLeafPgno ){
+ fts5SegIterGotoPage(p, pIter, iLeafPgno);
+ bMove = 0;
+ }
+ }else{
+ assert( pIter->pNextLeaf==0 );
+ assert( iMatch<pIter->iRowid );
+ while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
+ fts5DlidxIterPrev(p, pDlidx);
+ }
+ iLeafPgno = fts5DlidxIterPgno(pDlidx);
+
+ assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
+
+ if( iLeafPgno<pIter->iLeafPgno ){
+ pIter->iLeafPgno = iLeafPgno+1;
+ fts5SegIterReverseNewPage(p, pIter);
+ bMove = 0;
+ }
+ }
+
+ do{
+ if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
+ if( pIter->pLeaf==0 ) break;
+ if( bRev==0 && pIter->iRowid>=iMatch ) break;
+ if( bRev!=0 && pIter->iRowid<=iMatch ) break;
+ bMove = 1;
+ }while( p->rc==SQLITE_OK );
+}
+
+
+/*
+** Free the iterator object passed as the second argument.
+*/
+static void fts5MultiIterFree(Fts5Iter *pIter){
+ if( pIter ){
+ int i;
+ for(i=0; i<pIter->nSeg; i++){
+ fts5SegIterClear(&pIter->aSeg[i]);
+ }
+ fts5BufferFree(&pIter->poslist);
+ sqlite3_free(pIter);
+ }
+}
+
+static void fts5MultiIterAdvanced(
+ Fts5Index *p, /* FTS5 backend to iterate within */
+ Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
+ int iChanged, /* Index of sub-iterator just advanced */
+ int iMinset /* Minimum entry in aFirst[] to set */
+){
+ int i;
+ for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
+ int iEq;
+ if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
+ Fts5SegIter *pSeg = &pIter->aSeg[iEq];
+ assert( p->rc==SQLITE_OK );
+ pSeg->xNext(p, pSeg, 0);
+ i = pIter->nSeg + iEq;
+ }
+ }
+}
+
+/*
+** Sub-iterator iChanged of iterator pIter has just been advanced. It still
+** points to the same term though - just a different rowid. This function
+** attempts to update the contents of the pIter->aFirst[] accordingly.
+** If it does so successfully, 0 is returned. Otherwise 1.
+**
+** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
+** on the iterator instead. That function does the same as this one, except
+** that it deals with more complicated cases as well.
+*/
+static int fts5MultiIterAdvanceRowid(
+ Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
+ int iChanged, /* Index of sub-iterator just advanced */
+ Fts5SegIter **ppFirst
+){
+ Fts5SegIter *pNew = &pIter->aSeg[iChanged];
+
+ if( pNew->iRowid==pIter->iSwitchRowid
+ || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
+ ){
+ int i;
+ Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
+ pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
+ for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
+ Fts5CResult *pRes = &pIter->aFirst[i];
+
+ assert( pNew->pLeaf );
+ assert( pRes->bTermEq==0 || pOther->pLeaf );
+
+ if( pRes->bTermEq ){
+ if( pNew->iRowid==pOther->iRowid ){
+ return 1;
+ }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
+ pIter->iSwitchRowid = pOther->iRowid;
+ pNew = pOther;
+ }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
+ pIter->iSwitchRowid = pOther->iRowid;
+ }
+ }
+ pRes->iFirst = (u16)(pNew - pIter->aSeg);
+ if( i==1 ) break;
+
+ pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
+ }
+ }
+
+ *ppFirst = pNew;
+ return 0;
+}
+
+/*
+** Set the pIter->bEof variable based on the state of the sub-iterators.
+*/
+static void fts5MultiIterSetEof(Fts5Iter *pIter){
+ Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
+ pIter->base.bEof = pSeg->pLeaf==0;
+ pIter->iSwitchRowid = pSeg->iRowid;
+}
+
+/*
+** Move the iterator to the next entry.
+**
+** If an error occurs, an error code is left in Fts5Index.rc. It is not
+** considered an error if the iterator reaches EOF, or if it is already at
+** EOF when this function is called.
+*/
+static void fts5MultiIterNext(
+ Fts5Index *p,
+ Fts5Iter *pIter,
+ int bFrom, /* True if argument iFrom is valid */
+ i64 iFrom /* Advance at least as far as this */
+){
+ int bUseFrom = bFrom;
+ assert( pIter->base.bEof==0 );
+ while( p->rc==SQLITE_OK ){
+ int iFirst = pIter->aFirst[1].iFirst;
+ int bNewTerm = 0;
+ Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
+ assert( p->rc==SQLITE_OK );
+ if( bUseFrom && pSeg->pDlidx ){
+ fts5SegIterNextFrom(p, pSeg, iFrom);
+ }else{
+ pSeg->xNext(p, pSeg, &bNewTerm);
+ }
+
+ if( pSeg->pLeaf==0 || bNewTerm
+ || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
+ ){
+ fts5MultiIterAdvanced(p, pIter, iFirst, 1);
+ fts5MultiIterSetEof(pIter);
+ pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
+ if( pSeg->pLeaf==0 ) return;
+ }
+
+ fts5AssertMultiIterSetup(p, pIter);
+ assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
+ if( pIter->bSkipEmpty==0 || pSeg->nPos ){
+ pIter->xSetOutputs(pIter, pSeg);
+ return;
+ }
+ bUseFrom = 0;
+ }
+}
+
+static void fts5MultiIterNext2(
+ Fts5Index *p,
+ Fts5Iter *pIter,
+ int *pbNewTerm /* OUT: True if *might* be new term */
+){
+ assert( pIter->bSkipEmpty );
+ if( p->rc==SQLITE_OK ){
+ *pbNewTerm = 0;
+ do{
+ int iFirst = pIter->aFirst[1].iFirst;
+ Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
+ int bNewTerm = 0;
+
+ assert( p->rc==SQLITE_OK );
+ pSeg->xNext(p, pSeg, &bNewTerm);
+ if( pSeg->pLeaf==0 || bNewTerm
+ || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
+ ){
+ fts5MultiIterAdvanced(p, pIter, iFirst, 1);
+ fts5MultiIterSetEof(pIter);
+ *pbNewTerm = 1;
+ }
+ fts5AssertMultiIterSetup(p, pIter);
+
+ }while( fts5MultiIterIsEmpty(p, pIter) );
+ }
+}
+
+static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
+ UNUSED_PARAM2(pUnused1, pUnused2);
+}
+
+static Fts5Iter *fts5MultiIterAlloc(
+ Fts5Index *p, /* FTS5 backend to iterate within */
+ int nSeg
+){
+ Fts5Iter *pNew;
+ int nSlot; /* Power of two >= nSeg */
+
+ for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
+ pNew = fts5IdxMalloc(p,
+ sizeof(Fts5Iter) + /* pNew */
+ sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
+ sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
+ );
+ if( pNew ){
+ pNew->nSeg = nSlot;
+ pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
+ pNew->pIndex = p;
+ pNew->xSetOutputs = fts5IterSetOutputs_Noop;
+ }
+ return pNew;
+}
+
+static void fts5PoslistCallback(
+ Fts5Index *pUnused,
+ void *pContext,
+ const u8 *pChunk, int nChunk
+){
+ UNUSED_PARAM(pUnused);
+ assert_nc( nChunk>=0 );
+ if( nChunk>0 ){
+ fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
+ }
+}
+
+typedef struct PoslistCallbackCtx PoslistCallbackCtx;
+struct PoslistCallbackCtx {
+ Fts5Buffer *pBuf; /* Append to this buffer */
+ Fts5Colset *pColset; /* Restrict matches to this column */
+ int eState; /* See above */
+};
+
+typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
+struct PoslistOffsetsCtx {
+ Fts5Buffer *pBuf; /* Append to this buffer */
+ Fts5Colset *pColset; /* Restrict matches to this column */
+ int iRead;
+ int iWrite;
+};
+
+/*
+** TODO: Make this more efficient!
+*/
+static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
+ int i;
+ for(i=0; i<pColset->nCol; i++){
+ if( pColset->aiCol[i]==iCol ) return 1;
+ }
+ return 0;
+}
+
+static void fts5PoslistOffsetsCallback(
+ Fts5Index *pUnused,
+ void *pContext,
+ const u8 *pChunk, int nChunk
+){
+ PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
+ UNUSED_PARAM(pUnused);
+ assert_nc( nChunk>=0 );
+ if( nChunk>0 ){
+ int i = 0;
+ while( i<nChunk ){
+ int iVal;
+ i += fts5GetVarint32(&pChunk[i], iVal);
+ iVal += pCtx->iRead - 2;
+ pCtx->iRead = iVal;
+ if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
+ fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
+ pCtx->iWrite = iVal;
+ }
+ }
+ }
+}
+
+static void fts5PoslistFilterCallback(
+ Fts5Index *pUnused,
+ void *pContext,
+ const u8 *pChunk, int nChunk
+){
+ PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
+ UNUSED_PARAM(pUnused);
+ assert_nc( nChunk>=0 );
+ if( nChunk>0 ){
+ /* Search through to find the first varint with value 1. This is the
+ ** start of the next columns hits. */
+ int i = 0;
+ int iStart = 0;
+
+ if( pCtx->eState==2 ){
+ int iCol;
+ fts5FastGetVarint32(pChunk, i, iCol);
+ if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
+ pCtx->eState = 1;
+ fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
+ }else{
+ pCtx->eState = 0;
+ }
+ }
+
+ do {
+ while( i<nChunk && pChunk[i]!=0x01 ){
+ while( pChunk[i] & 0x80 ) i++;
+ i++;
+ }
+ if( pCtx->eState ){
+ fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
+ }
+ if( i<nChunk ){
+ int iCol;
+ iStart = i;
+ i++;
+ if( i>=nChunk ){
+ pCtx->eState = 2;
+ }else{
+ fts5FastGetVarint32(pChunk, i, iCol);
+ pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
+ if( pCtx->eState ){
+ fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
+ iStart = i;
+ }
+ }
+ }
+ }while( i<nChunk );
+ }
+}
+
+static void fts5ChunkIterate(
+ Fts5Index *p, /* Index object */
+ Fts5SegIter *pSeg, /* Poslist of this iterator */
+ void *pCtx, /* Context pointer for xChunk callback */
+ void (*xChunk)(Fts5Index*, void*, const u8*, int)
+){
+ int nRem = pSeg->nPos; /* Number of bytes still to come */
+ Fts5Data *pData = 0;
+ u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
+ int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
+ int pgno = pSeg->iLeafPgno;
+ int pgnoSave = 0;
+
+ /* This function does notmwork with detail=none databases. */
+ assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
+
+ if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
+ pgnoSave = pgno+1;
+ }
+
+ while( 1 ){
+ xChunk(p, pCtx, pChunk, nChunk);
+ nRem -= nChunk;
+ fts5DataRelease(pData);
+ if( nRem<=0 ){
+ break;
+ }else{
+ pgno++;
+ pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
+ if( pData==0 ) break;
+ pChunk = &pData->p[4];
+ nChunk = MIN(nRem, pData->szLeaf - 4);
+ if( pgno==pgnoSave ){
+ assert( pSeg->pNextLeaf==0 );
+ pSeg->pNextLeaf = pData;
+ pData = 0;
+ }
+ }
+ }
+}
+
+/*
+** Iterator pIter currently points to a valid entry (not EOF). This
+** function appends the position list data for the current entry to
+** buffer pBuf. It does not make a copy of the position-list size
+** field.
+*/
+static void fts5SegiterPoslist(
+ Fts5Index *p,
+ Fts5SegIter *pSeg,
+ Fts5Colset *pColset,
+ Fts5Buffer *pBuf
+){
+ if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+FTS5_DATA_ZERO_PADDING) ){
+ memset(&pBuf->p[pBuf->n+pSeg->nPos], 0, FTS5_DATA_ZERO_PADDING);
+ if( pColset==0 ){
+ fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
+ }else{
+ if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
+ PoslistCallbackCtx sCtx;
+ sCtx.pBuf = pBuf;
+ sCtx.pColset = pColset;
+ sCtx.eState = fts5IndexColsetTest(pColset, 0);
+ assert( sCtx.eState==0 || sCtx.eState==1 );
+ fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
+ }else{
+ PoslistOffsetsCtx sCtx;
+ memset(&sCtx, 0, sizeof(sCtx));
+ sCtx.pBuf = pBuf;
+ sCtx.pColset = pColset;
+ fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
+ }
+ }
+ }
+}
+
+/*
+** IN/OUT parameter (*pa) points to a position list n bytes in size. If
+** the position list contains entries for column iCol, then (*pa) is set
+** to point to the sub-position-list for that column and the number of
+** bytes in it returned. Or, if the argument position list does not
+** contain any entries for column iCol, return 0.
+*/
+static int fts5IndexExtractCol(
+ const u8 **pa, /* IN/OUT: Pointer to poslist */
+ int n, /* IN: Size of poslist in bytes */
+ int iCol /* Column to extract from poslist */
+){
+ int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
+ const u8 *p = *pa;
+ const u8 *pEnd = &p[n]; /* One byte past end of position list */
+
+ while( iCol>iCurrent ){
+ /* Advance pointer p until it points to pEnd or an 0x01 byte that is
+ ** not part of a varint. Note that it is not possible for a negative
+ ** or extremely large varint to occur within an uncorrupted position
+ ** list. So the last byte of each varint may be assumed to have a clear
+ ** 0x80 bit. */
+ while( *p!=0x01 ){
+ while( *p++ & 0x80 );
+ if( p>=pEnd ) return 0;
+ }
+ *pa = p++;
+ iCurrent = *p++;
+ if( iCurrent & 0x80 ){
+ p--;
+ p += fts5GetVarint32(p, iCurrent);
+ }
+ }
+ if( iCol!=iCurrent ) return 0;
+
+ /* Advance pointer p until it points to pEnd or an 0x01 byte that is
+ ** not part of a varint */
+ while( p<pEnd && *p!=0x01 ){
+ while( *p++ & 0x80 );
+ }
+
+ return p - (*pa);
+}
+
+static void fts5IndexExtractColset(
+ int *pRc,
+ Fts5Colset *pColset, /* Colset to filter on */
+ const u8 *pPos, int nPos, /* Position list */
+ Fts5Buffer *pBuf /* Output buffer */
+){
+ if( *pRc==SQLITE_OK ){
+ int i;
+ fts5BufferZero(pBuf);
+ for(i=0; i<pColset->nCol; i++){
+ const u8 *pSub = pPos;
+ int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
+ if( nSub ){
+ fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
+ }
+ }
+ }
+}
+
+/*
+** xSetOutputs callback used by detail=none tables.
+*/
+static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
+ assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
+ pIter->base.iRowid = pSeg->iRowid;
+ pIter->base.nData = pSeg->nPos;
+}
+
+/*
+** xSetOutputs callback used by detail=full and detail=col tables when no
+** column filters are specified.
+*/
+static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
+ pIter->base.iRowid = pSeg->iRowid;
+ pIter->base.nData = pSeg->nPos;
+
+ assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
+ assert( pIter->pColset==0 );
+
+ if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
+ /* All data is stored on the current page. Populate the output
+ ** variables to point into the body of the page object. */
+ pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
+ }else{
+ /* The data is distributed over two or more pages. Copy it into the
+ ** Fts5Iter.poslist buffer and then set the output pointer to point
+ ** to this buffer. */
+ fts5BufferZero(&pIter->poslist);
+ fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
+ pIter->base.pData = pIter->poslist.p;
+ }
+}
+
+/*
+** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
+** against no columns at all).
+*/
+static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
+ UNUSED_PARAM(pSeg);
+ pIter->base.nData = 0;
+}
+
+/*
+** xSetOutputs callback used by detail=col when there is a column filter
+** and there are 100 or more columns. Also called as a fallback from
+** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
+*/
+static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
+ fts5BufferZero(&pIter->poslist);
+ fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
+ pIter->base.iRowid = pSeg->iRowid;
+ pIter->base.pData = pIter->poslist.p;
+ pIter->base.nData = pIter->poslist.n;
+}
+
+/*
+** xSetOutputs callback used when:
+**
+** * detail=col,
+** * there is a column filter, and
+** * the table contains 100 or fewer columns.
+**
+** The last point is to ensure all column numbers are stored as
+** single-byte varints.
+*/
+static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
+
+ assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
+ assert( pIter->pColset );
+
+ if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
+ fts5IterSetOutputs_Col(pIter, pSeg);
+ }else{
+ u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
+ u8 *pEnd = (u8*)&a[pSeg->nPos];
+ int iPrev = 0;
+ int *aiCol = pIter->pColset->aiCol;
+ int *aiColEnd = &aiCol[pIter->pColset->nCol];
+
+ u8 *aOut = pIter->poslist.p;
+ int iPrevOut = 0;
+
+ pIter->base.iRowid = pSeg->iRowid;
+
+ while( a<pEnd ){
+ iPrev += (int)a++[0] - 2;
+ while( *aiCol<iPrev ){
+ aiCol++;
+ if( aiCol==aiColEnd ) goto setoutputs_col_out;
+ }
+ if( *aiCol==iPrev ){
+ *aOut++ = (u8)((iPrev - iPrevOut) + 2);
+ iPrevOut = iPrev;
+ }
+ }
+
+setoutputs_col_out:
+ pIter->base.pData = pIter->poslist.p;
+ pIter->base.nData = aOut - pIter->poslist.p;
+ }
+}
+
+/*
+** xSetOutputs callback used by detail=full when there is a column filter.
+*/
+static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
+ Fts5Colset *pColset = pIter->pColset;
+ pIter->base.iRowid = pSeg->iRowid;
+
+ assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
+ assert( pColset );
+
+ if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
+ /* All data is stored on the current page. Populate the output
+ ** variables to point into the body of the page object. */
+ const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
+ if( pColset->nCol==1 ){
+ pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
+ pIter->base.pData = a;
+ }else{
+ int *pRc = &pIter->pIndex->rc;
+ fts5BufferZero(&pIter->poslist);
+ fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
+ pIter->base.pData = pIter->poslist.p;
+ pIter->base.nData = pIter->poslist.n;
+ }
+ }else{
+ /* The data is distributed over two or more pages. Copy it into the
+ ** Fts5Iter.poslist buffer and then set the output pointer to point
+ ** to this buffer. */
+ fts5BufferZero(&pIter->poslist);
+ fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
+ pIter->base.pData = pIter->poslist.p;
+ pIter->base.nData = pIter->poslist.n;
+ }
+}
+
+static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
+ if( *pRc==SQLITE_OK ){
+ Fts5Config *pConfig = pIter->pIndex->pConfig;
+ if( pConfig->eDetail==FTS5_DETAIL_NONE ){
+ pIter->xSetOutputs = fts5IterSetOutputs_None;
+ }
+
+ else if( pIter->pColset==0 ){
+ pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
+ }
+
+ else if( pIter->pColset->nCol==0 ){
+ pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
+ }
+
+ else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
+ pIter->xSetOutputs = fts5IterSetOutputs_Full;
+ }
+
+ else{
+ assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
+ if( pConfig->nCol<=100 ){
+ pIter->xSetOutputs = fts5IterSetOutputs_Col100;
+ sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
+ }else{
+ pIter->xSetOutputs = fts5IterSetOutputs_Col;
+ }
+ }
+ }
+}
+
+
+/*
+** Allocate a new Fts5Iter object.
+**
+** The new object will be used to iterate through data in structure pStruct.
+** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
+** is zero or greater, data from the first nSegment segments on level iLevel
+** is merged.
+**
+** The iterator initially points to the first term/rowid entry in the
+** iterated data.
+*/
+static void fts5MultiIterNew(
+ Fts5Index *p, /* FTS5 backend to iterate within */
+ Fts5Structure *pStruct, /* Structure of specific index */
+ int flags, /* FTS5INDEX_QUERY_XXX flags */
+ Fts5Colset *pColset, /* Colset to filter on (or NULL) */
+ const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
+ int iLevel, /* Level to iterate (-1 for all) */
+ int nSegment, /* Number of segments to merge (iLevel>=0) */
+ Fts5Iter **ppOut /* New object */
+){
+ int nSeg = 0; /* Number of segment-iters in use */
+ int iIter = 0; /* */
+ int iSeg; /* Used to iterate through segments */
+ Fts5StructureLevel *pLvl;
+ Fts5Iter *pNew;
+
+ assert( (pTerm==0 && nTerm==0) || iLevel<0 );
+
+ /* Allocate space for the new multi-seg-iterator. */
+ if( p->rc==SQLITE_OK ){
+ if( iLevel<0 ){
+ assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
+ nSeg = pStruct->nSegment;
+ nSeg += (p->pHash ? 1 : 0);
+ }else{
+ nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
+ }
+ }
+ *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
+ if( pNew==0 ) return;
+ pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
+ pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
+ pNew->pColset = pColset;
+ if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
+ fts5IterSetOutputCb(&p->rc, pNew);
+ }
+
+ /* Initialize each of the component segment iterators. */
+ if( p->rc==SQLITE_OK ){
+ if( iLevel<0 ){
+ Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
+ if( p->pHash ){
+ /* Add a segment iterator for the current contents of the hash table. */
+ Fts5SegIter *pIter = &pNew->aSeg[iIter++];
+ fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
+ }
+ for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
+ for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
+ Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
+ Fts5SegIter *pIter = &pNew->aSeg[iIter++];
+ if( pTerm==0 ){
+ fts5SegIterInit(p, pSeg, pIter);
+ }else{
+ fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
+ }
+ }
+ }
+ }else{
+ pLvl = &pStruct->aLevel[iLevel];
+ for(iSeg=nSeg-1; iSeg>=0; iSeg--){
+ fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
+ }
+ }
+ assert( iIter==nSeg );
+ }
+
+ /* If the above was successful, each component iterators now points
+ ** to the first entry in its segment. In this case initialize the
+ ** aFirst[] array. Or, if an error has occurred, free the iterator
+ ** object and set the output variable to NULL. */
+ if( p->rc==SQLITE_OK ){
+ for(iIter=pNew->nSeg-1; iIter>0; iIter--){
+ int iEq;
+ if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
+ Fts5SegIter *pSeg = &pNew->aSeg[iEq];
+ if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
+ fts5MultiIterAdvanced(p, pNew, iEq, iIter);
+ }
+ }
+ fts5MultiIterSetEof(pNew);
+ fts5AssertMultiIterSetup(p, pNew);
+
+ if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
+ fts5MultiIterNext(p, pNew, 0, 0);
+ }else if( pNew->base.bEof==0 ){
+ Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
+ pNew->xSetOutputs(pNew, pSeg);
+ }
+
+ }else{
+ fts5MultiIterFree(pNew);
+ *ppOut = 0;
+ }
+}
+
+/*
+** Create an Fts5Iter that iterates through the doclist provided
+** as the second argument.
+*/
+static void fts5MultiIterNew2(
+ Fts5Index *p, /* FTS5 backend to iterate within */
+ Fts5Data *pData, /* Doclist to iterate through */
+ int bDesc, /* True for descending rowid order */
+ Fts5Iter **ppOut /* New object */
+){
+ Fts5Iter *pNew;
+ pNew = fts5MultiIterAlloc(p, 2);
+ if( pNew ){
+ Fts5SegIter *pIter = &pNew->aSeg[1];
+
+ pIter->flags = FTS5_SEGITER_ONETERM;
+ if( pData->szLeaf>0 ){
+ pIter->pLeaf = pData;
+ pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
+ pIter->iEndofDoclist = pData->nn;
+ pNew->aFirst[1].iFirst = 1;
+ if( bDesc ){
+ pNew->bRev = 1;
+ pIter->flags |= FTS5_SEGITER_REVERSE;
+ fts5SegIterReverseInitPage(p, pIter);
+ }else{
+ fts5SegIterLoadNPos(p, pIter);
+ }
+ pData = 0;
+ }else{
+ pNew->base.bEof = 1;
+ }
+ fts5SegIterSetNext(p, pIter);
+
+ *ppOut = pNew;
+ }
+
+ fts5DataRelease(pData);
+}
+
+/*
+** Return true if the iterator is at EOF or if an error has occurred.
+** False otherwise.
+*/
+static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
+ assert( p->rc
+ || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
+ );
+ return (p->rc || pIter->base.bEof);
+}
+
+/*
+** Return the rowid of the entry that the iterator currently points
+** to. If the iterator points to EOF when this function is called the
+** results are undefined.
+*/
+static i64 fts5MultiIterRowid(Fts5Iter *pIter){
+ assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
+ return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
+}
+
+/*
+** Move the iterator to the next entry at or following iMatch.
+*/
+static void fts5MultiIterNextFrom(
+ Fts5Index *p,
+ Fts5Iter *pIter,
+ i64 iMatch
+){
+ while( 1 ){
+ i64 iRowid;
+ fts5MultiIterNext(p, pIter, 1, iMatch);
+ if( fts5MultiIterEof(p, pIter) ) break;
+ iRowid = fts5MultiIterRowid(pIter);
+ if( pIter->bRev==0 && iRowid>=iMatch ) break;
+ if( pIter->bRev!=0 && iRowid<=iMatch ) break;
+ }
+}
+
+/*
+** Return a pointer to a buffer containing the term associated with the
+** entry that the iterator currently points to.
+*/
+static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
+ Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
+ *pn = p->term.n;
+ return p->term.p;
+}
+
+/*
+** Allocate a new segment-id for the structure pStruct. The new segment
+** id must be between 1 and 65335 inclusive, and must not be used by
+** any currently existing segment. If a free segment id cannot be found,
+** SQLITE_FULL is returned.
+**
+** If an error has already occurred, this function is a no-op. 0 is
+** returned in this case.
+*/
+static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
+ int iSegid = 0;
+
+ if( p->rc==SQLITE_OK ){
+ if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
+ p->rc = SQLITE_FULL;
+ }else{
+ /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
+ ** array is 63 elements, or 252 bytes, in size. */
+ u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
+ int iLvl, iSeg;
+ int i;
+ u32 mask;
+ memset(aUsed, 0, sizeof(aUsed));
+ for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
+ for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
+ int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
+ if( iId<=FTS5_MAX_SEGMENT && iId>0 ){
+ aUsed[(iId-1) / 32] |= (u32)1 << ((iId-1) % 32);
+ }
+ }
+ }
+
+ for(i=0; aUsed[i]==0xFFFFFFFF; i++);
+ mask = aUsed[i];
+ for(iSegid=0; mask & ((u32)1 << iSegid); iSegid++);
+ iSegid += 1 + i*32;
+
+#ifdef SQLITE_DEBUG
+ for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
+ for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
+ assert_nc( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
+ }
+ }
+ assert_nc( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
+
+ {
+ sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
+ if( p->rc==SQLITE_OK ){
+ u8 aBlob[2] = {0xff, 0xff};
+ sqlite3_bind_int(pIdxSelect, 1, iSegid);
+ sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
+ assert_nc( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
+ p->rc = sqlite3_reset(pIdxSelect);
+ sqlite3_bind_null(pIdxSelect, 2);
+ }
+ }
+#endif
+ }
+ }
+
+ return iSegid;
+}
+
+/*
+** Discard all data currently cached in the hash-tables.
+*/
+static void fts5IndexDiscardData(Fts5Index *p){
+ assert( p->pHash || p->nPendingData==0 );
+ if( p->pHash ){
+ sqlite3Fts5HashClear(p->pHash);
+ p->nPendingData = 0;
+ }
+}
+
+/*
+** Return the size of the prefix, in bytes, that buffer
+** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
+**
+** Buffer (pNew/<length-unknown>) is guaranteed to be greater
+** than buffer (pOld/nOld).
+*/
+static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
+ int i;
+ for(i=0; i<nOld; i++){
+ if( pOld[i]!=pNew[i] ) break;
+ }
+ return i;
+}
+
+static void fts5WriteDlidxClear(
+ Fts5Index *p,
+ Fts5SegWriter *pWriter,
+ int bFlush /* If true, write dlidx to disk */
+){
+ int i;
+ assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
+ for(i=0; i<pWriter->nDlidx; i++){
+ Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
+ if( pDlidx->buf.n==0 ) break;
+ if( bFlush ){
+ assert( pDlidx->pgno!=0 );
+ fts5DataWrite(p,
+ FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
+ pDlidx->buf.p, pDlidx->buf.n
+ );
+ }
+ sqlite3Fts5BufferZero(&pDlidx->buf);
+ pDlidx->bPrevValid = 0;
+ }
+}
+
+/*
+** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
+** Any new array elements are zeroed before returning.
+*/
+static int fts5WriteDlidxGrow(
+ Fts5Index *p,
+ Fts5SegWriter *pWriter,
+ int nLvl
+){
+ if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
+ Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc64(
+ pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
+ );
+ if( aDlidx==0 ){
+ p->rc = SQLITE_NOMEM;
+ }else{
+ size_t nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
+ memset(&aDlidx[pWriter->nDlidx], 0, nByte);
+ pWriter->aDlidx = aDlidx;
+ pWriter->nDlidx = nLvl;
+ }
+ }
+ return p->rc;
+}
+
+/*
+** If the current doclist-index accumulating in pWriter->aDlidx[] is large
+** enough, flush it to disk and return 1. Otherwise discard it and return
+** zero.
+*/
+static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
+ int bFlag = 0;
+
+ /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
+ ** to the database, also write the doclist-index to disk. */
+ if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
+ bFlag = 1;
+ }
+ fts5WriteDlidxClear(p, pWriter, bFlag);
+ pWriter->nEmpty = 0;
+ return bFlag;
+}
+
+/*
+** This function is called whenever processing of the doclist for the
+** last term on leaf page (pWriter->iBtPage) is completed.
+**
+** The doclist-index for that term is currently stored in-memory within the
+** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
+** writes it out to disk. Or, if it is too small to bother with, discards
+** it.
+**
+** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
+*/
+static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
+ int bFlag;
+
+ assert( pWriter->iBtPage || pWriter->nEmpty==0 );
+ if( pWriter->iBtPage==0 ) return;
+ bFlag = fts5WriteFlushDlidx(p, pWriter);
+
+ if( p->rc==SQLITE_OK ){
+ const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
+ /* The following was already done in fts5WriteInit(): */
+ /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
+ sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
+ sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
+ sqlite3_step(p->pIdxWriter);
+ p->rc = sqlite3_reset(p->pIdxWriter);
+ sqlite3_bind_null(p->pIdxWriter, 2);
+ }
+ pWriter->iBtPage = 0;
+}
+
+/*
+** This is called once for each leaf page except the first that contains
+** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
+** is larger than all terms written to earlier leaves, and equal to or
+** smaller than the first term on the new leaf.
+**
+** If an error occurs, an error code is left in Fts5Index.rc. If an error
+** has already occurred when this function is called, it is a no-op.
+*/
+static void fts5WriteBtreeTerm(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5SegWriter *pWriter, /* Writer object */
+ int nTerm, const u8 *pTerm /* First term on new page */
+){
+ fts5WriteFlushBtree(p, pWriter);
+ if( p->rc==SQLITE_OK ){
+ fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
+ pWriter->iBtPage = pWriter->writer.pgno;
+ }
+}
+
+/*
+** This function is called when flushing a leaf page that contains no
+** terms at all to disk.
+*/
+static void fts5WriteBtreeNoTerm(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5SegWriter *pWriter /* Writer object */
+){
+ /* If there were no rowids on the leaf page either and the doclist-index
+ ** has already been started, append an 0x00 byte to it. */
+ if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
+ Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
+ assert( pDlidx->bPrevValid );
+ sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
+ }
+
+ /* Increment the "number of sequential leaves without a term" counter. */
+ pWriter->nEmpty++;
+}
+
+static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
+ i64 iRowid;
+ int iOff;
+
+ iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
+ fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
+ return iRowid;
+}
+
+/*
+** Rowid iRowid has just been appended to the current leaf page. It is the
+** first on the page. This function appends an appropriate entry to the current
+** doclist-index.
+*/
+static void fts5WriteDlidxAppend(
+ Fts5Index *p,
+ Fts5SegWriter *pWriter,
+ i64 iRowid
+){
+ int i;
+ int bDone = 0;
+
+ for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
+ i64 iVal;
+ Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
+
+ if( pDlidx->buf.n>=p->pConfig->pgsz ){
+ /* The current doclist-index page is full. Write it to disk and push
+ ** a copy of iRowid (which will become the first rowid on the next
+ ** doclist-index leaf page) up into the next level of the b-tree
+ ** hierarchy. If the node being flushed is currently the root node,
+ ** also push its first rowid upwards. */
+ pDlidx->buf.p[0] = 0x01; /* Not the root node */
+ fts5DataWrite(p,
+ FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
+ pDlidx->buf.p, pDlidx->buf.n
+ );
+ fts5WriteDlidxGrow(p, pWriter, i+2);
+ pDlidx = &pWriter->aDlidx[i];
+ if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
+ i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
+
+ /* This was the root node. Push its first rowid up to the new root. */
+ pDlidx[1].pgno = pDlidx->pgno;
+ sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
+ sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
+ sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
+ pDlidx[1].bPrevValid = 1;
+ pDlidx[1].iPrev = iFirst;
+ }
+
+ sqlite3Fts5BufferZero(&pDlidx->buf);
+ pDlidx->bPrevValid = 0;
+ pDlidx->pgno++;
+ }else{
+ bDone = 1;
+ }
+
+ if( pDlidx->bPrevValid ){
+ iVal = iRowid - pDlidx->iPrev;
+ }else{
+ i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
+ assert( pDlidx->buf.n==0 );
+ sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
+ sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
+ iVal = iRowid;
+ }
+
+ sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
+ pDlidx->bPrevValid = 1;
+ pDlidx->iPrev = iRowid;
+ }
+}
+
+static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
+ static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
+ Fts5PageWriter *pPage = &pWriter->writer;
+ i64 iRowid;
+
+ assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
+
+ /* Set the szLeaf header field. */
+ assert( 0==fts5GetU16(&pPage->buf.p[2]) );
+ fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
+
+ if( pWriter->bFirstTermInPage ){
+ /* No term was written to this page. */
+ assert( pPage->pgidx.n==0 );
+ fts5WriteBtreeNoTerm(p, pWriter);
+ }else{
+ /* Append the pgidx to the page buffer. Set the szLeaf header field. */
+ fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
+ }
+
+ /* Write the page out to disk */
+ iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
+ fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
+
+ /* Initialize the next page. */
+ fts5BufferZero(&pPage->buf);
+ fts5BufferZero(&pPage->pgidx);
+ fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
+ pPage->iPrevPgidx = 0;
+ pPage->pgno++;
+
+ /* Increase the leaves written counter */
+ pWriter->nLeafWritten++;
+
+ /* The new leaf holds no terms or rowids */
+ pWriter->bFirstTermInPage = 1;
+ pWriter->bFirstRowidInPage = 1;
+}
+
+/*
+** Append term pTerm/nTerm to the segment being written by the writer passed
+** as the second argument.
+**
+** If an error occurs, set the Fts5Index.rc error code. If an error has
+** already occurred, this function is a no-op.
+*/
+static void fts5WriteAppendTerm(
+ Fts5Index *p,
+ Fts5SegWriter *pWriter,
+ int nTerm, const u8 *pTerm
+){
+ int nPrefix; /* Bytes of prefix compression for term */
+ Fts5PageWriter *pPage = &pWriter->writer;
+ Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
+ int nMin = MIN(pPage->term.n, nTerm);
+
+ assert( p->rc==SQLITE_OK );
+ assert( pPage->buf.n>=4 );
+ assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
+
+ /* If the current leaf page is full, flush it to disk. */
+ if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
+ if( pPage->buf.n>4 ){
+ fts5WriteFlushLeaf(p, pWriter);
+ if( p->rc!=SQLITE_OK ) return;
+ }
+ fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
+ }
+
+ /* TODO1: Updating pgidx here. */
+ pPgidx->n += sqlite3Fts5PutVarint(
+ &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
+ );
+ pPage->iPrevPgidx = pPage->buf.n;
+#if 0
+ fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
+ pPgidx->n += 2;
+#endif
+
+ if( pWriter->bFirstTermInPage ){
+ nPrefix = 0;
+ if( pPage->pgno!=1 ){
+ /* This is the first term on a leaf that is not the leftmost leaf in
+ ** the segment b-tree. In this case it is necessary to add a term to
+ ** the b-tree hierarchy that is (a) larger than the largest term
+ ** already written to the segment and (b) smaller than or equal to
+ ** this term. In other words, a prefix of (pTerm/nTerm) that is one
+ ** byte longer than the longest prefix (pTerm/nTerm) shares with the
+ ** previous term.
+ **
+ ** Usually, the previous term is available in pPage->term. The exception
+ ** is if this is the first term written in an incremental-merge step.
+ ** In this case the previous term is not available, so just write a
+ ** copy of (pTerm/nTerm) into the parent node. This is slightly
+ ** inefficient, but still correct. */
+ int n = nTerm;
+ if( pPage->term.n ){
+ n = 1 + fts5PrefixCompress(nMin, pPage->term.p, pTerm);
+ }
+ fts5WriteBtreeTerm(p, pWriter, n, pTerm);
+ if( p->rc!=SQLITE_OK ) return;
+ pPage = &pWriter->writer;
+ }
+ }else{
+ nPrefix = fts5PrefixCompress(nMin, pPage->term.p, pTerm);
+ fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
+ }
+
+ /* Append the number of bytes of new data, then the term data itself
+ ** to the page. */
+ fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
+ fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
+
+ /* Update the Fts5PageWriter.term field. */
+ fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
+ pWriter->bFirstTermInPage = 0;
+
+ pWriter->bFirstRowidInPage = 0;
+ pWriter->bFirstRowidInDoclist = 1;
+
+ assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
+ pWriter->aDlidx[0].pgno = pPage->pgno;
+}
+
+/*
+** Append a rowid and position-list size field to the writers output.
+*/
+static void fts5WriteAppendRowid(
+ Fts5Index *p,
+ Fts5SegWriter *pWriter,
+ i64 iRowid
+){
+ if( p->rc==SQLITE_OK ){
+ Fts5PageWriter *pPage = &pWriter->writer;
+
+ if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
+ fts5WriteFlushLeaf(p, pWriter);
+ }
+
+ /* If this is to be the first rowid written to the page, set the
+ ** rowid-pointer in the page-header. Also append a value to the dlidx
+ ** buffer, in case a doclist-index is required. */
+ if( pWriter->bFirstRowidInPage ){
+ fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
+ fts5WriteDlidxAppend(p, pWriter, iRowid);
+ }
+
+ /* Write the rowid. */
+ if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
+ fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
+ }else{
+ assert_nc( p->rc || iRowid>pWriter->iPrevRowid );
+ fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
+ }
+ pWriter->iPrevRowid = iRowid;
+ pWriter->bFirstRowidInDoclist = 0;
+ pWriter->bFirstRowidInPage = 0;
+ }
+}
+
+static void fts5WriteAppendPoslistData(
+ Fts5Index *p,
+ Fts5SegWriter *pWriter,
+ const u8 *aData,
+ int nData
+){
+ Fts5PageWriter *pPage = &pWriter->writer;
+ const u8 *a = aData;
+ int n = nData;
+
+ assert( p->pConfig->pgsz>0 );
+ while( p->rc==SQLITE_OK
+ && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
+ ){
+ int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
+ int nCopy = 0;
+ while( nCopy<nReq ){
+ i64 dummy;
+ nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
+ }
+ fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
+ a += nCopy;
+ n -= nCopy;
+ fts5WriteFlushLeaf(p, pWriter);
+ }
+ if( n>0 ){
+ fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
+ }
+}
+
+/*
+** Flush any data cached by the writer object to the database. Free any
+** allocations associated with the writer.
+*/
+static void fts5WriteFinish(
+ Fts5Index *p,
+ Fts5SegWriter *pWriter, /* Writer object */
+ int *pnLeaf /* OUT: Number of leaf pages in b-tree */
+){
+ int i;
+ Fts5PageWriter *pLeaf = &pWriter->writer;
+ if( p->rc==SQLITE_OK ){
+ assert( pLeaf->pgno>=1 );
+ if( pLeaf->buf.n>4 ){
+ fts5WriteFlushLeaf(p, pWriter);
+ }
+ *pnLeaf = pLeaf->pgno-1;
+ if( pLeaf->pgno>1 ){
+ fts5WriteFlushBtree(p, pWriter);
+ }
+ }
+ fts5BufferFree(&pLeaf->term);
+ fts5BufferFree(&pLeaf->buf);
+ fts5BufferFree(&pLeaf->pgidx);
+ fts5BufferFree(&pWriter->btterm);
+
+ for(i=0; i<pWriter->nDlidx; i++){
+ sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
+ }
+ sqlite3_free(pWriter->aDlidx);
+}
+
+static void fts5WriteInit(
+ Fts5Index *p,
+ Fts5SegWriter *pWriter,
+ int iSegid
+){
+ const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
+
+ memset(pWriter, 0, sizeof(Fts5SegWriter));
+ pWriter->iSegid = iSegid;
+
+ fts5WriteDlidxGrow(p, pWriter, 1);
+ pWriter->writer.pgno = 1;
+ pWriter->bFirstTermInPage = 1;
+ pWriter->iBtPage = 1;
+
+ assert( pWriter->writer.buf.n==0 );
+ assert( pWriter->writer.pgidx.n==0 );
+
+ /* Grow the two buffers to pgsz + padding bytes in size. */
+ sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
+ sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
+
+ if( p->pIdxWriter==0 ){
+ Fts5Config *pConfig = p->pConfig;
+ fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
+ "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
+ pConfig->zDb, pConfig->zName
+ ));
+ }
+
+ if( p->rc==SQLITE_OK ){
+ /* Initialize the 4-byte leaf-page header to 0x00. */
+ memset(pWriter->writer.buf.p, 0, 4);
+ pWriter->writer.buf.n = 4;
+
+ /* Bind the current output segment id to the index-writer. This is an
+ ** optimization over binding the same value over and over as rows are
+ ** inserted into %_idx by the current writer. */
+ sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
+ }
+}
+
+/*
+** Iterator pIter was used to iterate through the input segments of on an
+** incremental merge operation. This function is called if the incremental
+** merge step has finished but the input has not been completely exhausted.
+*/
+static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
+ int i;
+ Fts5Buffer buf;
+ memset(&buf, 0, sizeof(Fts5Buffer));
+ for(i=0; i<pIter->nSeg && p->rc==SQLITE_OK; i++){
+ Fts5SegIter *pSeg = &pIter->aSeg[i];
+ if( pSeg->pSeg==0 ){
+ /* no-op */
+ }else if( pSeg->pLeaf==0 ){
+ /* All keys from this input segment have been transfered to the output.
+ ** Set both the first and last page-numbers to 0 to indicate that the
+ ** segment is now empty. */
+ pSeg->pSeg->pgnoLast = 0;
+ pSeg->pSeg->pgnoFirst = 0;
+ }else{
+ int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
+ i64 iLeafRowid;
+ Fts5Data *pData;
+ int iId = pSeg->pSeg->iSegid;
+ u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
+
+ iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
+ pData = fts5LeafRead(p, iLeafRowid);
+ if( pData ){
+ if( iOff>pData->szLeaf ){
+ /* This can occur if the pages that the segments occupy overlap - if
+ ** a single page has been assigned to more than one segment. In
+ ** this case a prior iteration of this loop may have corrupted the
+ ** segment currently being trimmed. */
+ p->rc = FTS5_CORRUPT;
+ }else{
+ fts5BufferZero(&buf);
+ fts5BufferGrow(&p->rc, &buf, pData->nn);
+ fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
+ fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
+ fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
+ fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff,&pData->p[iOff]);
+ if( p->rc==SQLITE_OK ){
+ /* Set the szLeaf field */
+ fts5PutU16(&buf.p[2], (u16)buf.n);
+ }
+
+ /* Set up the new page-index array */
+ fts5BufferAppendVarint(&p->rc, &buf, 4);
+ if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
+ && pSeg->iEndofDoclist<pData->szLeaf
+ && pSeg->iPgidxOff<=pData->nn
+ ){
+ int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
+ fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
+ fts5BufferAppendBlob(&p->rc, &buf,
+ pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
+ );
+ }
+
+ pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
+ fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
+ fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
+ }
+ fts5DataRelease(pData);
+ }
+ }
+ }
+ fts5BufferFree(&buf);
+}
+
+static void fts5MergeChunkCallback(
+ Fts5Index *p,
+ void *pCtx,
+ const u8 *pChunk, int nChunk
+){
+ Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
+ fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
+}
+
+/*
+**
+*/
+static void fts5IndexMergeLevel(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
+ int iLvl, /* Level to read input from */
+ int *pnRem /* Write up to this many output leaves */
+){
+ Fts5Structure *pStruct = *ppStruct;
+ Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
+ Fts5StructureLevel *pLvlOut;
+ Fts5Iter *pIter = 0; /* Iterator to read input data */
+ int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
+ int nInput; /* Number of input segments */
+ Fts5SegWriter writer; /* Writer object */
+ Fts5StructureSegment *pSeg; /* Output segment */
+ Fts5Buffer term;
+ int bOldest; /* True if the output segment is the oldest */
+ int eDetail = p->pConfig->eDetail;
+ const int flags = FTS5INDEX_QUERY_NOOUTPUT;
+ int bTermWritten = 0; /* True if current term already output */
+
+ assert( iLvl<pStruct->nLevel );
+ assert( pLvl->nMerge<=pLvl->nSeg );
+
+ memset(&writer, 0, sizeof(Fts5SegWriter));
+ memset(&term, 0, sizeof(Fts5Buffer));
+ if( pLvl->nMerge ){
+ pLvlOut = &pStruct->aLevel[iLvl+1];
+ assert( pLvlOut->nSeg>0 );
+ nInput = pLvl->nMerge;
+ pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
+
+ fts5WriteInit(p, &writer, pSeg->iSegid);
+ writer.writer.pgno = pSeg->pgnoLast+1;
+ writer.iBtPage = 0;
+ }else{
+ int iSegid = fts5AllocateSegid(p, pStruct);
+
+ /* Extend the Fts5Structure object as required to ensure the output
+ ** segment exists. */
+ if( iLvl==pStruct->nLevel-1 ){
+ fts5StructureAddLevel(&p->rc, ppStruct);
+ pStruct = *ppStruct;
+ }
+ fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
+ if( p->rc ) return;
+ pLvl = &pStruct->aLevel[iLvl];
+ pLvlOut = &pStruct->aLevel[iLvl+1];
+
+ fts5WriteInit(p, &writer, iSegid);
+
+ /* Add the new segment to the output level */
+ pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
+ pLvlOut->nSeg++;
+ pSeg->pgnoFirst = 1;
+ pSeg->iSegid = iSegid;
+ pStruct->nSegment++;
+
+ /* Read input from all segments in the input level */
+ nInput = pLvl->nSeg;
+ }
+ bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
+
+ assert( iLvl>=0 );
+ for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
+ fts5MultiIterEof(p, pIter)==0;
+ fts5MultiIterNext(p, pIter, 0, 0)
+ ){
+ Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
+ int nPos; /* position-list size field value */
+ int nTerm;
+ const u8 *pTerm;
+
+ pTerm = fts5MultiIterTerm(pIter, &nTerm);
+ if( nTerm!=term.n || fts5Memcmp(pTerm, term.p, nTerm) ){
+ if( pnRem && writer.nLeafWritten>nRem ){
+ break;
+ }
+ fts5BufferSet(&p->rc, &term, nTerm, pTerm);
+ bTermWritten =0;
+ }
+
+ /* Check for key annihilation. */
+ if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
+
+ if( p->rc==SQLITE_OK && bTermWritten==0 ){
+ /* This is a new term. Append a term to the output segment. */
+ fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
+ bTermWritten = 1;
+ }
+
+ /* Append the rowid to the output */
+ /* WRITEPOSLISTSIZE */
+ fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
+
+ if( eDetail==FTS5_DETAIL_NONE ){
+ if( pSegIter->bDel ){
+ fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
+ if( pSegIter->nPos>0 ){
+ fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
+ }
+ }
+ }else{
+ /* Append the position-list data to the output */
+ nPos = pSegIter->nPos*2 + pSegIter->bDel;
+ fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
+ fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
+ }
+ }
+
+ /* Flush the last leaf page to disk. Set the output segment b-tree height
+ ** and last leaf page number at the same time. */
+ fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
+
+ if( fts5MultiIterEof(p, pIter) ){
+ int i;
+
+ /* Remove the redundant segments from the %_data table */
+ for(i=0; i<nInput; i++){
+ fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
+ }
+
+ /* Remove the redundant segments from the input level */
+ if( pLvl->nSeg!=nInput ){
+ int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
+ memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
+ }
+ pStruct->nSegment -= nInput;
+ pLvl->nSeg -= nInput;
+ pLvl->nMerge = 0;
+ if( pSeg->pgnoLast==0 ){
+ pLvlOut->nSeg--;
+ pStruct->nSegment--;
+ }
+ }else{
+ assert( pSeg->pgnoLast>0 );
+ fts5TrimSegments(p, pIter);
+ pLvl->nMerge = nInput;
+ }
+
+ fts5MultiIterFree(pIter);
+ fts5BufferFree(&term);
+ if( pnRem ) *pnRem -= writer.nLeafWritten;
+}
+
+/*
+** Do up to nPg pages of automerge work on the index.
+**
+** Return true if any changes were actually made, or false otherwise.
+*/
+static int fts5IndexMerge(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
+ int nPg, /* Pages of work to do */
+ int nMin /* Minimum number of segments to merge */
+){
+ int nRem = nPg;
+ int bRet = 0;
+ Fts5Structure *pStruct = *ppStruct;
+ while( nRem>0 && p->rc==SQLITE_OK ){
+ int iLvl; /* To iterate through levels */
+ int iBestLvl = 0; /* Level offering the most input segments */
+ int nBest = 0; /* Number of input segments on best level */
+
+ /* Set iBestLvl to the level to read input segments from. */
+ assert( pStruct->nLevel>0 );
+ for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
+ Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
+ if( pLvl->nMerge ){
+ if( pLvl->nMerge>nBest ){
+ iBestLvl = iLvl;
+ nBest = pLvl->nMerge;
+ }
+ break;
+ }
+ if( pLvl->nSeg>nBest ){
+ nBest = pLvl->nSeg;
+ iBestLvl = iLvl;
+ }
+ }
+
+ /* If nBest is still 0, then the index must be empty. */
+#ifdef SQLITE_DEBUG
+ for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
+ assert( pStruct->aLevel[iLvl].nSeg==0 );
+ }
+#endif
+
+ if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
+ break;
+ }
+ bRet = 1;
+ fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
+ if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
+ fts5StructurePromote(p, iBestLvl+1, pStruct);
+ }
+ }
+ *ppStruct = pStruct;
+ return bRet;
+}
+
+/*
+** A total of nLeaf leaf pages of data has just been flushed to a level-0
+** segment. This function updates the write-counter accordingly and, if
+** necessary, performs incremental merge work.
+**
+** If an error occurs, set the Fts5Index.rc error code. If an error has
+** already occurred, this function is a no-op.
+*/
+static void fts5IndexAutomerge(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
+ int nLeaf /* Number of output leaves just written */
+){
+ if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
+ Fts5Structure *pStruct = *ppStruct;
+ u64 nWrite; /* Initial value of write-counter */
+ int nWork; /* Number of work-quanta to perform */
+ int nRem; /* Number of leaf pages left to write */
+
+ /* Update the write-counter. While doing so, set nWork. */
+ nWrite = pStruct->nWriteCounter;
+ nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
+ pStruct->nWriteCounter += nLeaf;
+ nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
+
+ fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
+ }
+}
+
+static void fts5IndexCrisismerge(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
+){
+ const int nCrisis = p->pConfig->nCrisisMerge;
+ Fts5Structure *pStruct = *ppStruct;
+ int iLvl = 0;
+
+ assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
+ while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
+ fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
+ assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
+ fts5StructurePromote(p, iLvl+1, pStruct);
+ iLvl++;
+ }
+ *ppStruct = pStruct;
+}
+
+static int fts5IndexReturn(Fts5Index *p){
+ int rc = p->rc;
+ p->rc = SQLITE_OK;
+ return rc;
+}
+
+typedef struct Fts5FlushCtx Fts5FlushCtx;
+struct Fts5FlushCtx {
+ Fts5Index *pIdx;
+ Fts5SegWriter writer;
+};
+
+/*
+** Buffer aBuf[] contains a list of varints, all small enough to fit
+** in a 32-bit integer. Return the size of the largest prefix of this
+** list nMax bytes or less in size.
+*/
+static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
+ int ret;
+ u32 dummy;
+ ret = fts5GetVarint32(aBuf, dummy);
+ if( ret<nMax ){
+ while( 1 ){
+ int i = fts5GetVarint32(&aBuf[ret], dummy);
+ if( (ret + i) > nMax ) break;
+ ret += i;
+ }
+ }
+ return ret;
+}
+
+/*
+** Flush the contents of in-memory hash table iHash to a new level-0
+** segment on disk. Also update the corresponding structure record.
+**
+** If an error occurs, set the Fts5Index.rc error code. If an error has
+** already occurred, this function is a no-op.
+*/
+static void fts5FlushOneHash(Fts5Index *p){
+ Fts5Hash *pHash = p->pHash;
+ Fts5Structure *pStruct;
+ int iSegid;
+ int pgnoLast = 0; /* Last leaf page number in segment */
+
+ /* Obtain a reference to the index structure and allocate a new segment-id
+ ** for the new level-0 segment. */
+ pStruct = fts5StructureRead(p);
+ iSegid = fts5AllocateSegid(p, pStruct);
+ fts5StructureInvalidate(p);
+
+ if( iSegid ){
+ const int pgsz = p->pConfig->pgsz;
+ int eDetail = p->pConfig->eDetail;
+ Fts5StructureSegment *pSeg; /* New segment within pStruct */
+ Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
+ Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
+
+ Fts5SegWriter writer;
+ fts5WriteInit(p, &writer, iSegid);
+
+ pBuf = &writer.writer.buf;
+ pPgidx = &writer.writer.pgidx;
+
+ /* fts5WriteInit() should have initialized the buffers to (most likely)
+ ** the maximum space required. */
+ assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
+ assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
+
+ /* Begin scanning through hash table entries. This loop runs once for each
+ ** term/doclist currently stored within the hash table. */
+ if( p->rc==SQLITE_OK ){
+ p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
+ }
+ while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
+ const char *zTerm; /* Buffer containing term */
+ const u8 *pDoclist; /* Pointer to doclist for this term */
+ int nDoclist; /* Size of doclist in bytes */
+
+ /* Write the term for this entry to disk. */
+ sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
+ fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
+ if( p->rc!=SQLITE_OK ) break;
+
+ assert( writer.bFirstRowidInPage==0 );
+ if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
+ /* The entire doclist will fit on the current leaf. */
+ fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
+ }else{
+ i64 iRowid = 0;
+ i64 iDelta = 0;
+ int iOff = 0;
+
+ /* The entire doclist will not fit on this leaf. The following
+ ** loop iterates through the poslists that make up the current
+ ** doclist. */
+ while( p->rc==SQLITE_OK && iOff<nDoclist ){
+ iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
+ iRowid += iDelta;
+
+ if( writer.bFirstRowidInPage ){
+ fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
+ pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
+ writer.bFirstRowidInPage = 0;
+ fts5WriteDlidxAppend(p, &writer, iRowid);
+ if( p->rc!=SQLITE_OK ) break;
+ }else{
+ pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
+ }
+ assert( pBuf->n<=pBuf->nSpace );
+
+ if( eDetail==FTS5_DETAIL_NONE ){
+ if( iOff<nDoclist && pDoclist[iOff]==0 ){
+ pBuf->p[pBuf->n++] = 0;
+ iOff++;
+ if( iOff<nDoclist && pDoclist[iOff]==0 ){
+ pBuf->p[pBuf->n++] = 0;
+ iOff++;
+ }
+ }
+ if( (pBuf->n + pPgidx->n)>=pgsz ){
+ fts5WriteFlushLeaf(p, &writer);
+ }
+ }else{
+ int bDummy;
+ int nPos;
+ int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
+ nCopy += nPos;
+ if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
+ /* The entire poslist will fit on the current leaf. So copy
+ ** it in one go. */
+ fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
+ }else{
+ /* The entire poslist will not fit on this leaf. So it needs
+ ** to be broken into sections. The only qualification being
+ ** that each varint must be stored contiguously. */
+ const u8 *pPoslist = &pDoclist[iOff];
+ int iPos = 0;
+ while( p->rc==SQLITE_OK ){
+ int nSpace = pgsz - pBuf->n - pPgidx->n;
+ int n = 0;
+ if( (nCopy - iPos)<=nSpace ){
+ n = nCopy - iPos;
+ }else{
+ n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
+ }
+ assert( n>0 );
+ fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
+ iPos += n;
+ if( (pBuf->n + pPgidx->n)>=pgsz ){
+ fts5WriteFlushLeaf(p, &writer);
+ }
+ if( iPos>=nCopy ) break;
+ }
+ }
+ iOff += nCopy;
+ }
+ }
+ }
+
+ /* TODO2: Doclist terminator written here. */
+ /* pBuf->p[pBuf->n++] = '\0'; */
+ assert( pBuf->n<=pBuf->nSpace );
+ if( p->rc==SQLITE_OK ) sqlite3Fts5HashScanNext(pHash);
+ }
+ sqlite3Fts5HashClear(pHash);
+ fts5WriteFinish(p, &writer, &pgnoLast);
+
+ /* Update the Fts5Structure. It is written back to the database by the
+ ** fts5StructureRelease() call below. */
+ if( pStruct->nLevel==0 ){
+ fts5StructureAddLevel(&p->rc, &pStruct);
+ }
+ fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
+ if( p->rc==SQLITE_OK ){
+ pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
+ pSeg->iSegid = iSegid;
+ pSeg->pgnoFirst = 1;
+ pSeg->pgnoLast = pgnoLast;
+ pStruct->nSegment++;
+ }
+ fts5StructurePromote(p, 0, pStruct);
+ }
+
+ fts5IndexAutomerge(p, &pStruct, pgnoLast);
+ fts5IndexCrisismerge(p, &pStruct);
+ fts5StructureWrite(p, pStruct);
+ fts5StructureRelease(pStruct);
+}
+
+/*
+** Flush any data stored in the in-memory hash tables to the database.
+*/
+static void fts5IndexFlush(Fts5Index *p){
+ /* Unless it is empty, flush the hash table to disk */
+ if( p->nPendingData ){
+ assert( p->pHash );
+ p->nPendingData = 0;
+ fts5FlushOneHash(p);
+ }
+}
+
+static Fts5Structure *fts5IndexOptimizeStruct(
+ Fts5Index *p,
+ Fts5Structure *pStruct
+){
+ Fts5Structure *pNew = 0;
+ sqlite3_int64 nByte = sizeof(Fts5Structure);
+ int nSeg = pStruct->nSegment;
+ int i;
+
+ /* Figure out if this structure requires optimization. A structure does
+ ** not require optimization if either:
+ **
+ ** + it consists of fewer than two segments, or
+ ** + all segments are on the same level, or
+ ** + all segments except one are currently inputs to a merge operation.
+ **
+ ** In the first case, return NULL. In the second, increment the ref-count
+ ** on *pStruct and return a copy of the pointer to it.
+ */
+ if( nSeg<2 ) return 0;
+ for(i=0; i<pStruct->nLevel; i++){
+ int nThis = pStruct->aLevel[i].nSeg;
+ if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
+ fts5StructureRef(pStruct);
+ return pStruct;
+ }
+ assert( pStruct->aLevel[i].nMerge<=nThis );
+ }
+
+ nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
+ pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
+
+ if( pNew ){
+ Fts5StructureLevel *pLvl;
+ nByte = nSeg * sizeof(Fts5StructureSegment);
+ pNew->nLevel = pStruct->nLevel+1;
+ pNew->nRef = 1;
+ pNew->nWriteCounter = pStruct->nWriteCounter;
+ pLvl = &pNew->aLevel[pStruct->nLevel];
+ pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
+ if( pLvl->aSeg ){
+ int iLvl, iSeg;
+ int iSegOut = 0;
+ /* Iterate through all segments, from oldest to newest. Add them to
+ ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
+ ** segment in the data structure. */
+ for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
+ for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
+ pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
+ iSegOut++;
+ }
+ }
+ pNew->nSegment = pLvl->nSeg = nSeg;
+ }else{
+ sqlite3_free(pNew);
+ pNew = 0;
+ }
+ }
+
+ return pNew;
+}
+
+static int sqlite3Fts5IndexOptimize(Fts5Index *p){
+ Fts5Structure *pStruct;
+ Fts5Structure *pNew = 0;
+
+ assert( p->rc==SQLITE_OK );
+ fts5IndexFlush(p);
+ pStruct = fts5StructureRead(p);
+ fts5StructureInvalidate(p);
+
+ if( pStruct ){
+ pNew = fts5IndexOptimizeStruct(p, pStruct);
+ }
+ fts5StructureRelease(pStruct);
+
+ assert( pNew==0 || pNew->nSegment>0 );
+ if( pNew ){
+ int iLvl;
+ for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
+ while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
+ int nRem = FTS5_OPT_WORK_UNIT;
+ fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
+ }
+
+ fts5StructureWrite(p, pNew);
+ fts5StructureRelease(pNew);
+ }
+
+ return fts5IndexReturn(p);
+}
+
+/*
+** This is called to implement the special "VALUES('merge', $nMerge)"
+** INSERT command.
+*/
+static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
+ Fts5Structure *pStruct = fts5StructureRead(p);
+ if( pStruct ){
+ int nMin = p->pConfig->nUsermerge;
+ fts5StructureInvalidate(p);
+ if( nMerge<0 ){
+ Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
+ fts5StructureRelease(pStruct);
+ pStruct = pNew;
+ nMin = 2;
+ nMerge = nMerge*-1;
+ }
+ if( pStruct && pStruct->nLevel ){
+ if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
+ fts5StructureWrite(p, pStruct);
+ }
+ }
+ fts5StructureRelease(pStruct);
+ }
+ return fts5IndexReturn(p);
+}
+
+static void fts5AppendRowid(
+ Fts5Index *p,
+ i64 iDelta,
+ Fts5Iter *pUnused,
+ Fts5Buffer *pBuf
+){
+ UNUSED_PARAM(pUnused);
+ fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
+}
+
+static void fts5AppendPoslist(
+ Fts5Index *p,
+ i64 iDelta,
+ Fts5Iter *pMulti,
+ Fts5Buffer *pBuf
+){
+ int nData = pMulti->base.nData;
+ int nByte = nData + 9 + 9 + FTS5_DATA_ZERO_PADDING;
+ assert( nData>0 );
+ if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nByte) ){
+ fts5BufferSafeAppendVarint(pBuf, iDelta);
+ fts5BufferSafeAppendVarint(pBuf, nData*2);
+ fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
+ memset(&pBuf->p[pBuf->n], 0, FTS5_DATA_ZERO_PADDING);
+ }
+}
+
+
+static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
+ u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
+
+ assert( pIter->aPoslist );
+ if( p>=pIter->aEof ){
+ pIter->aPoslist = 0;
+ }else{
+ i64 iDelta;
+
+ p += fts5GetVarint(p, (u64*)&iDelta);
+ pIter->iRowid += iDelta;
+
+ /* Read position list size */
+ if( p[0] & 0x80 ){
+ int nPos;
+ pIter->nSize = fts5GetVarint32(p, nPos);
+ pIter->nPoslist = (nPos>>1);
+ }else{
+ pIter->nPoslist = ((int)(p[0])) >> 1;
+ pIter->nSize = 1;
+ }
+
+ pIter->aPoslist = p;
+ }
+}
+
+static void fts5DoclistIterInit(
+ Fts5Buffer *pBuf,
+ Fts5DoclistIter *pIter
+){
+ memset(pIter, 0, sizeof(*pIter));
+ pIter->aPoslist = pBuf->p;
+ pIter->aEof = &pBuf->p[pBuf->n];
+ fts5DoclistIterNext(pIter);
+}
+
+#if 0
+/*
+** Append a doclist to buffer pBuf.
+**
+** This function assumes that space within the buffer has already been
+** allocated.
+*/
+static void fts5MergeAppendDocid(
+ Fts5Buffer *pBuf, /* Buffer to write to */
+ i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
+ i64 iRowid /* Rowid to append */
+){
+ assert( pBuf->n!=0 || (*piLastRowid)==0 );
+ fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
+ *piLastRowid = iRowid;
+}
+#endif
+
+#define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
+ assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
+ fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
+ (iLastRowid) = (iRowid); \
+}
+
+/*
+** Swap the contents of buffer *p1 with that of *p2.
+*/
+static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
+ Fts5Buffer tmp = *p1;
+ *p1 = *p2;
+ *p2 = tmp;
+}
+
+static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
+ int i = *piOff;
+ if( i>=pBuf->n ){
+ *piOff = -1;
+ }else{
+ u64 iVal;
+ *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
+ *piRowid += iVal;
+ }
+}
+
+/*
+** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
+** In this case the buffers consist of a delta-encoded list of rowids only.
+*/
+static void fts5MergeRowidLists(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5Buffer *p1, /* First list to merge */
+ Fts5Buffer *p2 /* Second list to merge */
+){
+ int i1 = 0;
+ int i2 = 0;
+ i64 iRowid1 = 0;
+ i64 iRowid2 = 0;
+ i64 iOut = 0;
+
+ Fts5Buffer out;
+ memset(&out, 0, sizeof(out));
+ sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
+ if( p->rc ) return;
+
+ fts5NextRowid(p1, &i1, &iRowid1);
+ fts5NextRowid(p2, &i2, &iRowid2);
+ while( i1>=0 || i2>=0 ){
+ if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
+ assert( iOut==0 || iRowid1>iOut );
+ fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
+ iOut = iRowid1;
+ fts5NextRowid(p1, &i1, &iRowid1);
+ }else{
+ assert( iOut==0 || iRowid2>iOut );
+ fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
+ iOut = iRowid2;
+ if( i1>=0 && iRowid1==iRowid2 ){
+ fts5NextRowid(p1, &i1, &iRowid1);
+ }
+ fts5NextRowid(p2, &i2, &iRowid2);
+ }
+ }
+
+ fts5BufferSwap(&out, p1);
+ fts5BufferFree(&out);
+}
+
+/*
+** Buffers p1 and p2 contain doclists. This function merges the content
+** of the two doclists together and sets buffer p1 to the result before
+** returning.
+**
+** If an error occurs, an error code is left in p->rc. If an error has
+** already occurred, this function is a no-op.
+*/
+static void fts5MergePrefixLists(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5Buffer *p1, /* First list to merge */
+ Fts5Buffer *p2 /* Second list to merge */
+){
+ if( p2->n ){
+ i64 iLastRowid = 0;
+ Fts5DoclistIter i1;
+ Fts5DoclistIter i2;
+ Fts5Buffer out = {0, 0, 0};
+ Fts5Buffer tmp = {0, 0, 0};
+
+ /* The maximum size of the output is equal to the sum of the two
+ ** input sizes + 1 varint (9 bytes). The extra varint is because if the
+ ** first rowid in one input is a large negative number, and the first in
+ ** the other a non-negative number, the delta for the non-negative
+ ** number will be larger on disk than the literal integer value
+ ** was.
+ **
+ ** Or, if the input position-lists are corrupt, then the output might
+ ** include up to 2 extra 10-byte positions created by interpreting -1
+ ** (the value PoslistNext64() uses for EOF) as a position and appending
+ ** it to the output. This can happen at most once for each input
+ ** position-list, hence two 10 byte paddings. */
+ if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n + 9+10+10) ) return;
+ fts5DoclistIterInit(p1, &i1);
+ fts5DoclistIterInit(p2, &i2);
+
+ while( 1 ){
+ if( i1.iRowid<i2.iRowid ){
+ /* Copy entry from i1 */
+ fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
+ fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
+ fts5DoclistIterNext(&i1);
+ if( i1.aPoslist==0 ) break;
+ assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) );
+ }
+ else if( i2.iRowid!=i1.iRowid ){
+ /* Copy entry from i2 */
+ fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
+ fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
+ fts5DoclistIterNext(&i2);
+ if( i2.aPoslist==0 ) break;
+ assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) );
+ }
+ else{
+ /* Merge the two position lists. */
+ i64 iPos1 = 0;
+ i64 iPos2 = 0;
+ int iOff1 = 0;
+ int iOff2 = 0;
+ u8 *a1 = &i1.aPoslist[i1.nSize];
+ u8 *a2 = &i2.aPoslist[i2.nSize];
+ int nCopy;
+ u8 *aCopy;
+
+ i64 iPrev = 0;
+ Fts5PoslistWriter writer;
+ memset(&writer, 0, sizeof(writer));
+
+ /* See the earlier comment in this function for an explanation of why
+ ** corrupt input position lists might cause the output to consume
+ ** at most 20 bytes of unexpected space. */
+ fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
+ fts5BufferZero(&tmp);
+ sqlite3Fts5BufferSize(&p->rc, &tmp,
+ i1.nPoslist + i2.nPoslist + 10 + 10 + FTS5_DATA_ZERO_PADDING
+ );
+ if( p->rc ) break;
+
+ sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
+ sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
+ assert_nc( iPos1>=0 && iPos2>=0 );
+
+ if( iPos1<iPos2 ){
+ sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
+ sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
+ }else{
+ sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
+ sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
+ }
+ if( iPos1>=0 && iPos2>=0 ){
+ while( 1 ){
+ if( iPos1<iPos2 ){
+ if( iPos1!=iPrev ){
+ sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
+ }
+ sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
+ if( iPos1<0 ) break;
+ }else{
+ assert_nc( iPos2!=iPrev );
+ sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
+ sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
+ if( iPos2<0 ) break;
+ }
+ }
+ }
+
+ if( iPos1>=0 ){
+ if( iPos1!=iPrev ){
+ sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
+ }
+ aCopy = &a1[iOff1];
+ nCopy = i1.nPoslist - iOff1;
+ }else{
+ assert_nc( iPos2>=0 && iPos2!=iPrev );
+ sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
+ aCopy = &a2[iOff2];
+ nCopy = i2.nPoslist - iOff2;
+ }
+ if( nCopy>0 ){
+ fts5BufferSafeAppendBlob(&tmp, aCopy, nCopy);
+ }
+
+ /* WRITEPOSLISTSIZE */
+ assert_nc( tmp.n<=i1.nPoslist+i2.nPoslist );
+ assert( tmp.n<=i1.nPoslist+i2.nPoslist+10+10 );
+ if( tmp.n>i1.nPoslist+i2.nPoslist ){
+ if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
+ break;
+ }
+ fts5BufferSafeAppendVarint(&out, tmp.n * 2);
+ fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
+ fts5DoclistIterNext(&i1);
+ fts5DoclistIterNext(&i2);
+ assert_nc( out.n<=(p1->n+p2->n+9) );
+ if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
+ assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) );
+ }
+ }
+
+ if( i1.aPoslist ){
+ fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
+ fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
+ }
+ else if( i2.aPoslist ){
+ fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
+ fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
+ }
+ assert_nc( out.n<=(p1->n+p2->n+9) );
+
+ fts5BufferFree(p1);
+ fts5BufferFree(&tmp);
+ memset(&out.p[out.n], 0, FTS5_DATA_ZERO_PADDING);
+ *p1 = out;
+ }
+}
+
+static void fts5SetupPrefixIter(
+ Fts5Index *p, /* Index to read from */
+ int bDesc, /* True for "ORDER BY rowid DESC" */
+ const u8 *pToken, /* Buffer containing prefix to match */
+ int nToken, /* Size of buffer pToken in bytes */
+ Fts5Colset *pColset, /* Restrict matches to these columns */
+ Fts5Iter **ppIter /* OUT: New iterator */
+){
+ Fts5Structure *pStruct;
+ Fts5Buffer *aBuf;
+ const int nBuf = 32;
+
+ void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
+ void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
+ if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
+ xMerge = fts5MergeRowidLists;
+ xAppend = fts5AppendRowid;
+ }else{
+ xMerge = fts5MergePrefixLists;
+ xAppend = fts5AppendPoslist;
+ }
+
+ aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
+ pStruct = fts5StructureRead(p);
+
+ if( aBuf && pStruct ){
+ const int flags = FTS5INDEX_QUERY_SCAN
+ | FTS5INDEX_QUERY_SKIPEMPTY
+ | FTS5INDEX_QUERY_NOOUTPUT;
+ int i;
+ i64 iLastRowid = 0;
+ Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
+ Fts5Data *pData;
+ Fts5Buffer doclist;
+ int bNewTerm = 1;
+
+ memset(&doclist, 0, sizeof(doclist));
+ fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
+ fts5IterSetOutputCb(&p->rc, p1);
+ for( /* no-op */ ;
+ fts5MultiIterEof(p, p1)==0;
+ fts5MultiIterNext2(p, p1, &bNewTerm)
+ ){
+ Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
+ int nTerm = pSeg->term.n;
+ const u8 *pTerm = pSeg->term.p;
+ p1->xSetOutputs(p1, pSeg);
+
+ assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
+ if( bNewTerm ){
+ if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
+ }
+
+ if( p1->base.nData==0 ) continue;
+
+ if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
+ for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
+ assert( i<nBuf );
+ if( aBuf[i].n==0 ){
+ fts5BufferSwap(&doclist, &aBuf[i]);
+ fts5BufferZero(&doclist);
+ }else{
+ xMerge(p, &doclist, &aBuf[i]);
+ fts5BufferZero(&aBuf[i]);
+ }
+ }
+ iLastRowid = 0;
+ }
+
+ xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
+ iLastRowid = p1->base.iRowid;
+ }
+
+ for(i=0; i<nBuf; i++){
+ if( p->rc==SQLITE_OK ){
+ xMerge(p, &doclist, &aBuf[i]);
+ }
+ fts5BufferFree(&aBuf[i]);
+ }
+ fts5MultiIterFree(p1);
+
+ pData = fts5IdxMalloc(p, sizeof(Fts5Data)+doclist.n+FTS5_DATA_ZERO_PADDING);
+ if( pData ){
+ pData->p = (u8*)&pData[1];
+ pData->nn = pData->szLeaf = doclist.n;
+ if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
+ fts5MultiIterNew2(p, pData, bDesc, ppIter);
+ }
+ fts5BufferFree(&doclist);
+ }
+
+ fts5StructureRelease(pStruct);
+ sqlite3_free(aBuf);
+}
+
+
+/*
+** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
+** to the document with rowid iRowid.
+*/
+static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
+ assert( p->rc==SQLITE_OK );
+
+ /* Allocate the hash table if it has not already been allocated */
+ if( p->pHash==0 ){
+ p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
+ }
+
+ /* Flush the hash table to disk if required */
+ if( iRowid<p->iWriteRowid
+ || (iRowid==p->iWriteRowid && p->bDelete==0)
+ || (p->nPendingData > p->pConfig->nHashSize)
+ ){
+ fts5IndexFlush(p);
+ }
+
+ p->iWriteRowid = iRowid;
+ p->bDelete = bDelete;
+ return fts5IndexReturn(p);
+}
+
+/*
+** Commit data to disk.
+*/
+static int sqlite3Fts5IndexSync(Fts5Index *p){
+ assert( p->rc==SQLITE_OK );
+ fts5IndexFlush(p);
+ sqlite3Fts5IndexCloseReader(p);
+ return fts5IndexReturn(p);
+}
+
+/*
+** Discard any data stored in the in-memory hash tables. Do not write it
+** to the database. Additionally, assume that the contents of the %_data
+** table may have changed on disk. So any in-memory caches of %_data
+** records must be invalidated.
+*/
+static int sqlite3Fts5IndexRollback(Fts5Index *p){
+ sqlite3Fts5IndexCloseReader(p);
+ fts5IndexDiscardData(p);
+ fts5StructureInvalidate(p);
+ /* assert( p->rc==SQLITE_OK ); */
+ return SQLITE_OK;
+}
+
+/*
+** The %_data table is completely empty when this function is called. This
+** function populates it with the initial structure objects for each index,
+** and the initial version of the "averages" record (a zero-byte blob).
+*/
+static int sqlite3Fts5IndexReinit(Fts5Index *p){
+ Fts5Structure s;
+ fts5StructureInvalidate(p);
+ fts5IndexDiscardData(p);
+ memset(&s, 0, sizeof(Fts5Structure));
+ fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
+ fts5StructureWrite(p, &s);
+ return fts5IndexReturn(p);
+}
+
+/*
+** Open a new Fts5Index handle. If the bCreate argument is true, create
+** and initialize the underlying %_data table.
+**
+** If successful, set *pp to point to the new object and return SQLITE_OK.
+** Otherwise, set *pp to NULL and return an SQLite error code.
+*/
+static int sqlite3Fts5IndexOpen(
+ Fts5Config *pConfig,
+ int bCreate,
+ Fts5Index **pp,
+ char **pzErr
+){
+ int rc = SQLITE_OK;
+ Fts5Index *p; /* New object */
+
+ *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
+ if( rc==SQLITE_OK ){
+ p->pConfig = pConfig;
+ p->nWorkUnit = FTS5_WORK_UNIT;
+ p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
+ if( p->zDataTbl && bCreate ){
+ rc = sqlite3Fts5CreateTable(
+ pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
+ );
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5CreateTable(pConfig, "idx",
+ "segid, term, pgno, PRIMARY KEY(segid, term)",
+ 1, pzErr
+ );
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5IndexReinit(p);
+ }
+ }
+ }
+
+ assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
+ if( rc ){
+ sqlite3Fts5IndexClose(p);
+ *pp = 0;
+ }
+ return rc;
+}
+
+/*
+** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
+*/
+static int sqlite3Fts5IndexClose(Fts5Index *p){
+ int rc = SQLITE_OK;
+ if( p ){
+ assert( p->pReader==0 );
+ fts5StructureInvalidate(p);
+ sqlite3_finalize(p->pWriter);
+ sqlite3_finalize(p->pDeleter);
+ sqlite3_finalize(p->pIdxWriter);
+ sqlite3_finalize(p->pIdxDeleter);
+ sqlite3_finalize(p->pIdxSelect);
+ sqlite3_finalize(p->pDataVersion);
+ sqlite3Fts5HashFree(p->pHash);
+ sqlite3_free(p->zDataTbl);
+ sqlite3_free(p);
+ }
+ return rc;
+}
+
+/*
+** Argument p points to a buffer containing utf-8 text that is n bytes in
+** size. Return the number of bytes in the nChar character prefix of the
+** buffer, or 0 if there are less than nChar characters in total.
+*/
+static int sqlite3Fts5IndexCharlenToBytelen(
+ const char *p,
+ int nByte,
+ int nChar
+){
+ int n = 0;
+ int i;
+ for(i=0; i<nChar; i++){
+ if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
+ if( (unsigned char)p[n++]>=0xc0 ){
+ if( n>=nByte ) return 0;
+ while( (p[n] & 0xc0)==0x80 ){
+ n++;
+ if( n>=nByte ){
+ if( i+1==nChar ) break;
+ return 0;
+ }
+ }
+ }
+ }
+ return n;
+}
+
+/*
+** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
+** unicode characters in the string.
+*/
+static int fts5IndexCharlen(const char *pIn, int nIn){
+ int nChar = 0;
+ int i = 0;
+ while( i<nIn ){
+ if( (unsigned char)pIn[i++]>=0xc0 ){
+ while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
+ }
+ nChar++;
+ }
+ return nChar;
+}
+
+/*
+** Insert or remove data to or from the index. Each time a document is
+** added to or removed from the index, this function is called one or more
+** times.
+**
+** For an insert, it must be called once for each token in the new document.
+** If the operation is a delete, it must be called (at least) once for each
+** unique token in the document with an iCol value less than zero. The iPos
+** argument is ignored for a delete.
+*/
+static int sqlite3Fts5IndexWrite(
+ Fts5Index *p, /* Index to write to */
+ int iCol, /* Column token appears in (-ve -> delete) */
+ int iPos, /* Position of token within column */
+ const char *pToken, int nToken /* Token to add or remove to or from index */
+){
+ int i; /* Used to iterate through indexes */
+ int rc = SQLITE_OK; /* Return code */
+ Fts5Config *pConfig = p->pConfig;
+
+ assert( p->rc==SQLITE_OK );
+ assert( (iCol<0)==p->bDelete );
+
+ /* Add the entry to the main terms index. */
+ rc = sqlite3Fts5HashWrite(
+ p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
+ );
+
+ for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
+ const int nChar = pConfig->aPrefix[i];
+ int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
+ if( nByte ){
+ rc = sqlite3Fts5HashWrite(p->pHash,
+ p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
+ nByte
+ );
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Open a new iterator to iterate though all rowid that match the
+** specified token or token prefix.
+*/
+static int sqlite3Fts5IndexQuery(
+ Fts5Index *p, /* FTS index to query */
+ const char *pToken, int nToken, /* Token (or prefix) to query for */
+ int flags, /* Mask of FTS5INDEX_QUERY_X flags */
+ Fts5Colset *pColset, /* Match these columns only */
+ Fts5IndexIter **ppIter /* OUT: New iterator object */
+){
+ Fts5Config *pConfig = p->pConfig;
+ Fts5Iter *pRet = 0;
+ Fts5Buffer buf = {0, 0, 0};
+
+ /* If the QUERY_SCAN flag is set, all other flags must be clear. */
+ assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
+
+ if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
+ int iIdx = 0; /* Index to search */
+ if( nToken ) memcpy(&buf.p[1], pToken, nToken);
+
+ /* Figure out which index to search and set iIdx accordingly. If this
+ ** is a prefix query for which there is no prefix index, set iIdx to
+ ** greater than pConfig->nPrefix to indicate that the query will be
+ ** satisfied by scanning multiple terms in the main index.
+ **
+ ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
+ ** prefix-query. Instead of using a prefix-index (if one exists),
+ ** evaluate the prefix query using the main FTS index. This is used
+ ** for internal sanity checking by the integrity-check in debug
+ ** mode only. */
+#ifdef SQLITE_DEBUG
+ if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
+ assert( flags & FTS5INDEX_QUERY_PREFIX );
+ iIdx = 1+pConfig->nPrefix;
+ }else
+#endif
+ if( flags & FTS5INDEX_QUERY_PREFIX ){
+ int nChar = fts5IndexCharlen(pToken, nToken);
+ for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
+ if( pConfig->aPrefix[iIdx-1]==nChar ) break;
+ }
+ }
+
+ if( iIdx<=pConfig->nPrefix ){
+ /* Straight index lookup */
+ Fts5Structure *pStruct = fts5StructureRead(p);
+ buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
+ if( pStruct ){
+ fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
+ pColset, buf.p, nToken+1, -1, 0, &pRet
+ );
+ fts5StructureRelease(pStruct);
+ }
+ }else{
+ /* Scan multiple terms in the main index */
+ int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
+ buf.p[0] = FTS5_MAIN_PREFIX;
+ fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
+ assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
+ fts5IterSetOutputCb(&p->rc, pRet);
+ if( p->rc==SQLITE_OK ){
+ Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
+ if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
+ }
+ }
+
+ if( p->rc ){
+ sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
+ pRet = 0;
+ sqlite3Fts5IndexCloseReader(p);
+ }
+
+ *ppIter = (Fts5IndexIter*)pRet;
+ sqlite3Fts5BufferFree(&buf);
+ }
+ return fts5IndexReturn(p);
+}
+
+/*
+** Return true if the iterator passed as the only argument is at EOF.
+*/
+/*
+** Move to the next matching rowid.
+*/
+static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
+ Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
+ assert( pIter->pIndex->rc==SQLITE_OK );
+ fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
+ return fts5IndexReturn(pIter->pIndex);
+}
+
+/*
+** Move to the next matching term/rowid. Used by the fts5vocab module.
+*/
+static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
+ Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
+ Fts5Index *p = pIter->pIndex;
+
+ assert( pIter->pIndex->rc==SQLITE_OK );
+
+ fts5MultiIterNext(p, pIter, 0, 0);
+ if( p->rc==SQLITE_OK ){
+ Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
+ if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
+ fts5DataRelease(pSeg->pLeaf);
+ pSeg->pLeaf = 0;
+ pIter->base.bEof = 1;
+ }
+ }
+
+ return fts5IndexReturn(pIter->pIndex);
+}
+
+/*
+** Move to the next matching rowid that occurs at or after iMatch. The
+** definition of "at or after" depends on whether this iterator iterates
+** in ascending or descending rowid order.
+*/
+static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
+ Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
+ fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
+ return fts5IndexReturn(pIter->pIndex);
+}
+
+/*
+** Return the current term.
+*/
+static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
+ int n;
+ const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
+ *pn = n-1;
+ return &z[1];
+}
+
+/*
+** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
+*/
+static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
+ if( pIndexIter ){
+ Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
+ Fts5Index *pIndex = pIter->pIndex;
+ fts5MultiIterFree(pIter);
+ sqlite3Fts5IndexCloseReader(pIndex);
+ }
+}
+
+/*
+** Read and decode the "averages" record from the database.
+**
+** Parameter anSize must point to an array of size nCol, where nCol is
+** the number of user defined columns in the FTS table.
+*/
+static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
+ int nCol = p->pConfig->nCol;
+ Fts5Data *pData;
+
+ *pnRow = 0;
+ memset(anSize, 0, sizeof(i64) * nCol);
+ pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
+ if( p->rc==SQLITE_OK && pData->nn ){
+ int i = 0;
+ int iCol;
+ i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
+ for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
+ i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
+ }
+ }
+
+ fts5DataRelease(pData);
+ return fts5IndexReturn(p);
+}
+
+/*
+** Replace the current "averages" record with the contents of the buffer
+** supplied as the second argument.
+*/
+static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
+ assert( p->rc==SQLITE_OK );
+ fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
+ return fts5IndexReturn(p);
+}
+
+/*
+** Return the total number of blocks this module has read from the %_data
+** table since it was created.
+*/
+static int sqlite3Fts5IndexReads(Fts5Index *p){
+ return p->nRead;
+}
+
+/*
+** Set the 32-bit cookie value stored at the start of all structure
+** records to the value passed as the second argument.
+**
+** Return SQLITE_OK if successful, or an SQLite error code if an error
+** occurs.
+*/
+static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
+ int rc; /* Return code */
+ Fts5Config *pConfig = p->pConfig; /* Configuration object */
+ u8 aCookie[4]; /* Binary representation of iNew */
+ sqlite3_blob *pBlob = 0;
+
+ assert( p->rc==SQLITE_OK );
+ sqlite3Fts5Put32(aCookie, iNew);
+
+ rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
+ "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
+ );
+ if( rc==SQLITE_OK ){
+ sqlite3_blob_write(pBlob, aCookie, 4, 0);
+ rc = sqlite3_blob_close(pBlob);
+ }
+
+ return rc;
+}
+
+static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
+ Fts5Structure *pStruct;
+ pStruct = fts5StructureRead(p);
+ fts5StructureRelease(pStruct);
+ return fts5IndexReturn(p);
+}
+
+
+/*************************************************************************
+**************************************************************************
+** Below this point is the implementation of the integrity-check
+** functionality.
+*/
+
+/*
+** Return a simple checksum value based on the arguments.
+*/
+static u64 sqlite3Fts5IndexEntryCksum(
+ i64 iRowid,
+ int iCol,
+ int iPos,
+ int iIdx,
+ const char *pTerm,
+ int nTerm
+){
+ int i;
+ u64 ret = iRowid;
+ ret += (ret<<3) + iCol;
+ ret += (ret<<3) + iPos;
+ if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
+ for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
+ return ret;
+}
+
+#ifdef SQLITE_DEBUG
+/*
+** This function is purely an internal test. It does not contribute to
+** FTS functionality, or even the integrity-check, in any way.
+**
+** Instead, it tests that the same set of pgno/rowid combinations are
+** visited regardless of whether the doclist-index identified by parameters
+** iSegid/iLeaf is iterated in forwards or reverse order.
+*/
+static void fts5TestDlidxReverse(
+ Fts5Index *p,
+ int iSegid, /* Segment id to load from */
+ int iLeaf /* Load doclist-index for this leaf */
+){
+ Fts5DlidxIter *pDlidx = 0;
+ u64 cksum1 = 13;
+ u64 cksum2 = 13;
+
+ for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
+ fts5DlidxIterEof(p, pDlidx)==0;
+ fts5DlidxIterNext(p, pDlidx)
+ ){
+ i64 iRowid = fts5DlidxIterRowid(pDlidx);
+ int pgno = fts5DlidxIterPgno(pDlidx);
+ assert( pgno>iLeaf );
+ cksum1 += iRowid + ((i64)pgno<<32);
+ }
+ fts5DlidxIterFree(pDlidx);
+ pDlidx = 0;
+
+ for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
+ fts5DlidxIterEof(p, pDlidx)==0;
+ fts5DlidxIterPrev(p, pDlidx)
+ ){
+ i64 iRowid = fts5DlidxIterRowid(pDlidx);
+ int pgno = fts5DlidxIterPgno(pDlidx);
+ assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
+ cksum2 += iRowid + ((i64)pgno<<32);
+ }
+ fts5DlidxIterFree(pDlidx);
+ pDlidx = 0;
+
+ if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
+}
+
+static int fts5QueryCksum(
+ Fts5Index *p, /* Fts5 index object */
+ int iIdx,
+ const char *z, /* Index key to query for */
+ int n, /* Size of index key in bytes */
+ int flags, /* Flags for Fts5IndexQuery */
+ u64 *pCksum /* IN/OUT: Checksum value */
+){
+ int eDetail = p->pConfig->eDetail;
+ u64 cksum = *pCksum;
+ Fts5IndexIter *pIter = 0;
+ int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
+
+ while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
+ i64 rowid = pIter->iRowid;
+
+ if( eDetail==FTS5_DETAIL_NONE ){
+ cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
+ }else{
+ Fts5PoslistReader sReader;
+ for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
+ sReader.bEof==0;
+ sqlite3Fts5PoslistReaderNext(&sReader)
+ ){
+ int iCol = FTS5_POS2COLUMN(sReader.iPos);
+ int iOff = FTS5_POS2OFFSET(sReader.iPos);
+ cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
+ }
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5IterNext(pIter);
+ }
+ }
+ sqlite3Fts5IterClose(pIter);
+
+ *pCksum = cksum;
+ return rc;
+}
+
+/*
+** Check if buffer z[], size n bytes, contains as series of valid utf-8
+** encoded codepoints. If so, return 0. Otherwise, if the buffer does not
+** contain valid utf-8, return non-zero.
+*/
+static int fts5TestUtf8(const char *z, int n){
+ int i = 0;
+ assert_nc( n>0 );
+ while( i<n ){
+ if( (z[i] & 0x80)==0x00 ){
+ i++;
+ }else
+ if( (z[i] & 0xE0)==0xC0 ){
+ if( i+1>=n || (z[i+1] & 0xC0)!=0x80 ) return 1;
+ i += 2;
+ }else
+ if( (z[i] & 0xF0)==0xE0 ){
+ if( i+2>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1;
+ i += 3;
+ }else
+ if( (z[i] & 0xF8)==0xF0 ){
+ if( i+3>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1;
+ if( (z[i+2] & 0xC0)!=0x80 ) return 1;
+ i += 3;
+ }else{
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+/*
+** This function is also purely an internal test. It does not contribute to
+** FTS functionality, or even the integrity-check, in any way.
+*/
+static void fts5TestTerm(
+ Fts5Index *p,
+ Fts5Buffer *pPrev, /* Previous term */
+ const char *z, int n, /* Possibly new term to test */
+ u64 expected,
+ u64 *pCksum
+){
+ int rc = p->rc;
+ if( pPrev->n==0 ){
+ fts5BufferSet(&rc, pPrev, n, (const u8*)z);
+ }else
+ if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
+ u64 cksum3 = *pCksum;
+ const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
+ int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
+ int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
+ int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
+ u64 ck1 = 0;
+ u64 ck2 = 0;
+
+ /* Check that the results returned for ASC and DESC queries are
+ ** the same. If not, call this corruption. */
+ rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
+ if( rc==SQLITE_OK ){
+ int f = flags|FTS5INDEX_QUERY_DESC;
+ rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
+ }
+ if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
+
+ /* If this is a prefix query, check that the results returned if the
+ ** the index is disabled are the same. In both ASC and DESC order.
+ **
+ ** This check may only be performed if the hash table is empty. This
+ ** is because the hash table only supports a single scan query at
+ ** a time, and the multi-iter loop from which this function is called
+ ** is already performing such a scan.
+ **
+ ** Also only do this if buffer zTerm contains nTerm bytes of valid
+ ** utf-8. Otherwise, the last part of the buffer contents might contain
+ ** a non-utf-8 sequence that happens to be a prefix of a valid utf-8
+ ** character stored in the main fts index, which will cause the
+ ** test to fail. */
+ if( p->nPendingData==0 && 0==fts5TestUtf8(zTerm, nTerm) ){
+ if( iIdx>0 && rc==SQLITE_OK ){
+ int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
+ ck2 = 0;
+ rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
+ if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
+ }
+ if( iIdx>0 && rc==SQLITE_OK ){
+ int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
+ ck2 = 0;
+ rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
+ if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
+ }
+ }
+
+ cksum3 ^= ck1;
+ fts5BufferSet(&rc, pPrev, n, (const u8*)z);
+
+ if( rc==SQLITE_OK && cksum3!=expected ){
+ rc = FTS5_CORRUPT;
+ }
+ *pCksum = cksum3;
+ }
+ p->rc = rc;
+}
+
+#else
+# define fts5TestDlidxReverse(x,y,z)
+# define fts5TestTerm(u,v,w,x,y,z)
+#endif
+
+/*
+** Check that:
+**
+** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
+** contain zero terms.
+** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
+** contain zero rowids.
+*/
+static void fts5IndexIntegrityCheckEmpty(
+ Fts5Index *p,
+ Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
+ int iFirst,
+ int iNoRowid,
+ int iLast
+){
+ int i;
+
+ /* Now check that the iter.nEmpty leaves following the current leaf
+ ** (a) exist and (b) contain no terms. */
+ for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
+ Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
+ if( pLeaf ){
+ if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
+ if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
+ }
+ fts5DataRelease(pLeaf);
+ }
+}
+
+static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
+ int iTermOff = 0;
+ int ii;
+
+ Fts5Buffer buf1 = {0,0,0};
+ Fts5Buffer buf2 = {0,0,0};
+
+ ii = pLeaf->szLeaf;
+ while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
+ int res;
+ int iOff;
+ int nIncr;
+
+ ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
+ iTermOff += nIncr;
+ iOff = iTermOff;
+
+ if( iOff>=pLeaf->szLeaf ){
+ p->rc = FTS5_CORRUPT;
+ }else if( iTermOff==nIncr ){
+ int nByte;
+ iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
+ if( (iOff+nByte)>pLeaf->szLeaf ){
+ p->rc = FTS5_CORRUPT;
+ }else{
+ fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
+ }
+ }else{
+ int nKeep, nByte;
+ iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
+ iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
+ if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
+ p->rc = FTS5_CORRUPT;
+ }else{
+ buf1.n = nKeep;
+ fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
+ }
+
+ if( p->rc==SQLITE_OK ){
+ res = fts5BufferCompare(&buf1, &buf2);
+ if( res<=0 ) p->rc = FTS5_CORRUPT;
+ }
+ }
+ fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
+ }
+
+ fts5BufferFree(&buf1);
+ fts5BufferFree(&buf2);
+}
+
+static void fts5IndexIntegrityCheckSegment(
+ Fts5Index *p, /* FTS5 backend object */
+ Fts5StructureSegment *pSeg /* Segment to check internal consistency */
+){
+ Fts5Config *pConfig = p->pConfig;
+ sqlite3_stmt *pStmt = 0;
+ int rc2;
+ int iIdxPrevLeaf = pSeg->pgnoFirst-1;
+ int iDlidxPrevLeaf = pSeg->pgnoLast;
+
+ if( pSeg->pgnoFirst==0 ) return;
+
+ fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
+ "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d "
+ "ORDER BY 1, 2",
+ pConfig->zDb, pConfig->zName, pSeg->iSegid
+ ));
+
+ /* Iterate through the b-tree hierarchy. */
+ while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
+ i64 iRow; /* Rowid for this leaf */
+ Fts5Data *pLeaf; /* Data for this leaf */
+
+ const char *zIdxTerm = (const char*)sqlite3_column_blob(pStmt, 1);
+ int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
+ int iIdxLeaf = sqlite3_column_int(pStmt, 2);
+ int bIdxDlidx = sqlite3_column_int(pStmt, 3);
+
+ /* If the leaf in question has already been trimmed from the segment,
+ ** ignore this b-tree entry. Otherwise, load it into memory. */
+ if( iIdxLeaf<pSeg->pgnoFirst ) continue;
+ iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
+ pLeaf = fts5LeafRead(p, iRow);
+ if( pLeaf==0 ) break;
+
+ /* Check that the leaf contains at least one term, and that it is equal
+ ** to or larger than the split-key in zIdxTerm. Also check that if there
+ ** is also a rowid pointer within the leaf page header, it points to a
+ ** location before the term. */
+ if( pLeaf->nn<=pLeaf->szLeaf ){
+ p->rc = FTS5_CORRUPT;
+ }else{
+ int iOff; /* Offset of first term on leaf */
+ int iRowidOff; /* Offset of first rowid on leaf */
+ int nTerm; /* Size of term on leaf in bytes */
+ int res; /* Comparison of term and split-key */
+
+ iOff = fts5LeafFirstTermOff(pLeaf);
+ iRowidOff = fts5LeafFirstRowidOff(pLeaf);
+ if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){
+ p->rc = FTS5_CORRUPT;
+ }else{
+ iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
+ res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
+ if( res==0 ) res = nTerm - nIdxTerm;
+ if( res<0 ) p->rc = FTS5_CORRUPT;
+ }
+
+ fts5IntegrityCheckPgidx(p, pLeaf);
+ }
+ fts5DataRelease(pLeaf);
+ if( p->rc ) break;
+
+ /* Now check that the iter.nEmpty leaves following the current leaf
+ ** (a) exist and (b) contain no terms. */
+ fts5IndexIntegrityCheckEmpty(
+ p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
+ );
+ if( p->rc ) break;
+
+ /* If there is a doclist-index, check that it looks right. */
+ if( bIdxDlidx ){
+ Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
+ int iPrevLeaf = iIdxLeaf;
+ int iSegid = pSeg->iSegid;
+ int iPg = 0;
+ i64 iKey;
+
+ for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
+ fts5DlidxIterEof(p, pDlidx)==0;
+ fts5DlidxIterNext(p, pDlidx)
+ ){
+
+ /* Check any rowid-less pages that occur before the current leaf. */
+ for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
+ iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
+ pLeaf = fts5DataRead(p, iKey);
+ if( pLeaf ){
+ if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
+ fts5DataRelease(pLeaf);
+ }
+ }
+ iPrevLeaf = fts5DlidxIterPgno(pDlidx);
+
+ /* Check that the leaf page indicated by the iterator really does
+ ** contain the rowid suggested by the same. */
+ iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
+ pLeaf = fts5DataRead(p, iKey);
+ if( pLeaf ){
+ i64 iRowid;
+ int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
+ ASSERT_SZLEAF_OK(pLeaf);
+ if( iRowidOff>=pLeaf->szLeaf ){
+ p->rc = FTS5_CORRUPT;
+ }else{
+ fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
+ if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
+ }
+ fts5DataRelease(pLeaf);
+ }
+ }
+
+ iDlidxPrevLeaf = iPg;
+ fts5DlidxIterFree(pDlidx);
+ fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
+ }else{
+ iDlidxPrevLeaf = pSeg->pgnoLast;
+ /* TODO: Check there is no doclist index */
+ }
+
+ iIdxPrevLeaf = iIdxLeaf;
+ }
+
+ rc2 = sqlite3_finalize(pStmt);
+ if( p->rc==SQLITE_OK ) p->rc = rc2;
+
+ /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
+#if 0
+ if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
+ p->rc = FTS5_CORRUPT;
+ }
+#endif
+}
+
+
+/*
+** Run internal checks to ensure that the FTS index (a) is internally
+** consistent and (b) contains entries for which the XOR of the checksums
+** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
+**
+** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
+** checksum does not match. Return SQLITE_OK if all checks pass without
+** error, or some other SQLite error code if another error (e.g. OOM)
+** occurs.
+*/
+static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksum){
+ int eDetail = p->pConfig->eDetail;
+ u64 cksum2 = 0; /* Checksum based on contents of indexes */
+ Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
+ Fts5Iter *pIter; /* Used to iterate through entire index */
+ Fts5Structure *pStruct; /* Index structure */
+
+#ifdef SQLITE_DEBUG
+ /* Used by extra internal tests only run if NDEBUG is not defined */
+ u64 cksum3 = 0; /* Checksum based on contents of indexes */
+ Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
+#endif
+ const int flags = FTS5INDEX_QUERY_NOOUTPUT;
+
+ /* Load the FTS index structure */
+ pStruct = fts5StructureRead(p);
+
+ /* Check that the internal nodes of each segment match the leaves */
+ if( pStruct ){
+ int iLvl, iSeg;
+ for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
+ for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
+ Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
+ fts5IndexIntegrityCheckSegment(p, pSeg);
+ }
+ }
+ }
+
+ /* The cksum argument passed to this function is a checksum calculated
+ ** based on all expected entries in the FTS index (including prefix index
+ ** entries). This block checks that a checksum calculated based on the
+ ** actual contents of FTS index is identical.
+ **
+ ** Two versions of the same checksum are calculated. The first (stack
+ ** variable cksum2) based on entries extracted from the full-text index
+ ** while doing a linear scan of each individual index in turn.
+ **
+ ** As each term visited by the linear scans, a separate query for the
+ ** same term is performed. cksum3 is calculated based on the entries
+ ** extracted by these queries.
+ */
+ for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
+ fts5MultiIterEof(p, pIter)==0;
+ fts5MultiIterNext(p, pIter, 0, 0)
+ ){
+ int n; /* Size of term in bytes */
+ i64 iPos = 0; /* Position read from poslist */
+ int iOff = 0; /* Offset within poslist */
+ i64 iRowid = fts5MultiIterRowid(pIter);
+ char *z = (char*)fts5MultiIterTerm(pIter, &n);
+
+ /* If this is a new term, query for it. Update cksum3 with the results. */
+ fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
+
+ if( eDetail==FTS5_DETAIL_NONE ){
+ if( 0==fts5MultiIterIsEmpty(p, pIter) ){
+ cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
+ }
+ }else{
+ poslist.n = 0;
+ fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
+ while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
+ int iCol = FTS5_POS2COLUMN(iPos);
+ int iTokOff = FTS5_POS2OFFSET(iPos);
+ cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
+ }
+ }
+ }
+ fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
+
+ fts5MultiIterFree(pIter);
+ if( p->rc==SQLITE_OK && bUseCksum && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
+
+ fts5StructureRelease(pStruct);
+#ifdef SQLITE_DEBUG
+ fts5BufferFree(&term);
+#endif
+ fts5BufferFree(&poslist);
+ return fts5IndexReturn(p);
+}
+
+/*************************************************************************
+**************************************************************************
+** Below this point is the implementation of the fts5_decode() scalar
+** function only.
+*/
+
+/*
+** Decode a segment-data rowid from the %_data table. This function is
+** the opposite of macro FTS5_SEGMENT_ROWID().
+*/
+static void fts5DecodeRowid(
+ i64 iRowid, /* Rowid from %_data table */
+ int *piSegid, /* OUT: Segment id */
+ int *pbDlidx, /* OUT: Dlidx flag */
+ int *piHeight, /* OUT: Height */
+ int *piPgno /* OUT: Page number */
+){
+ *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
+ iRowid >>= FTS5_DATA_PAGE_B;
+
+ *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
+ iRowid >>= FTS5_DATA_HEIGHT_B;
+
+ *pbDlidx = (int)(iRowid & 0x0001);
+ iRowid >>= FTS5_DATA_DLI_B;
+
+ *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
+}
+
+static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
+ int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
+ fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
+
+ if( iSegid==0 ){
+ if( iKey==FTS5_AVERAGES_ROWID ){
+ sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
+ }else{
+ sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
+ }
+ }
+ else{
+ sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
+ bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
+ );
+ }
+}
+
+static void fts5DebugStructure(
+ int *pRc, /* IN/OUT: error code */
+ Fts5Buffer *pBuf,
+ Fts5Structure *p
+){
+ int iLvl, iSeg; /* Iterate through levels, segments */
+
+ for(iLvl=0; iLvl<p->nLevel; iLvl++){
+ Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
+ sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
+ " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
+ );
+ for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
+ Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
+ sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
+ pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
+ );
+ }
+ sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
+ }
+}
+
+/*
+** This is part of the fts5_decode() debugging aid.
+**
+** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
+** function appends a human-readable representation of the same object
+** to the buffer passed as the second argument.
+*/
+static void fts5DecodeStructure(
+ int *pRc, /* IN/OUT: error code */
+ Fts5Buffer *pBuf,
+ const u8 *pBlob, int nBlob
+){
+ int rc; /* Return code */
+ Fts5Structure *p = 0; /* Decoded structure object */
+
+ rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
+ if( rc!=SQLITE_OK ){
+ *pRc = rc;
+ return;
+ }
+
+ fts5DebugStructure(pRc, pBuf, p);
+ fts5StructureRelease(p);
+}
+
+/*
+** This is part of the fts5_decode() debugging aid.
+**
+** Arguments pBlob/nBlob contain an "averages" record. This function
+** appends a human-readable representation of record to the buffer passed
+** as the second argument.
+*/
+static void fts5DecodeAverages(
+ int *pRc, /* IN/OUT: error code */
+ Fts5Buffer *pBuf,
+ const u8 *pBlob, int nBlob
+){
+ int i = 0;
+ const char *zSpace = "";
+
+ while( i<nBlob ){
+ u64 iVal;
+ i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
+ sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
+ zSpace = " ";
+ }
+}
+
+/*
+** Buffer (a/n) is assumed to contain a list of serialized varints. Read
+** each varint and append its string representation to buffer pBuf. Return
+** after either the input buffer is exhausted or a 0 value is read.
+**
+** The return value is the number of bytes read from the input buffer.
+*/
+static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
+ int iOff = 0;
+ while( iOff<n ){
+ int iVal;
+ iOff += fts5GetVarint32(&a[iOff], iVal);
+ sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
+ }
+ return iOff;
+}
+
+/*
+** The start of buffer (a/n) contains the start of a doclist. The doclist
+** may or may not finish within the buffer. This function appends a text
+** representation of the part of the doclist that is present to buffer
+** pBuf.
+**
+** The return value is the number of bytes read from the input buffer.
+*/
+static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
+ i64 iDocid = 0;
+ int iOff = 0;
+
+ if( n>0 ){
+ iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
+ sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
+ }
+ while( iOff<n ){
+ int nPos;
+ int bDel;
+ iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
+ sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
+ iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
+ if( iOff<n ){
+ i64 iDelta;
+ iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
+ iDocid += iDelta;
+ sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
+ }
+ }
+
+ return iOff;
+}
+
+/*
+** This function is part of the fts5_decode() debugging function. It is
+** only ever used with detail=none tables.
+**
+** Buffer (pData/nData) contains a doclist in the format used by detail=none
+** tables. This function appends a human-readable version of that list to
+** buffer pBuf.
+**
+** If *pRc is other than SQLITE_OK when this function is called, it is a
+** no-op. If an OOM or other error occurs within this function, *pRc is
+** set to an SQLite error code before returning. The final state of buffer
+** pBuf is undefined in this case.
+*/
+static void fts5DecodeRowidList(
+ int *pRc, /* IN/OUT: Error code */
+ Fts5Buffer *pBuf, /* Buffer to append text to */
+ const u8 *pData, int nData /* Data to decode list-of-rowids from */
+){
+ int i = 0;
+ i64 iRowid = 0;
+
+ while( i<nData ){
+ const char *zApp = "";
+ u64 iVal;
+ i += sqlite3Fts5GetVarint(&pData[i], &iVal);
+ iRowid += iVal;
+
+ if( i<nData && pData[i]==0x00 ){
+ i++;
+ if( i<nData && pData[i]==0x00 ){
+ i++;
+ zApp = "+";
+ }else{
+ zApp = "*";
+ }
+ }
+
+ sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
+ }
+}
+
+/*
+** The implementation of user-defined scalar function fts5_decode().
+*/
+static void fts5DecodeFunction(
+ sqlite3_context *pCtx, /* Function call context */
+ int nArg, /* Number of args (always 2) */
+ sqlite3_value **apVal /* Function arguments */
+){
+ i64 iRowid; /* Rowid for record being decoded */
+ int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
+ const u8 *aBlob; int n; /* Record to decode */
+ u8 *a = 0;
+ Fts5Buffer s; /* Build up text to return here */
+ int rc = SQLITE_OK; /* Return code */
+ sqlite3_int64 nSpace = 0;
+ int eDetailNone = (sqlite3_user_data(pCtx)!=0);
+
+ assert( nArg==2 );
+ UNUSED_PARAM(nArg);
+ memset(&s, 0, sizeof(Fts5Buffer));
+ iRowid = sqlite3_value_int64(apVal[0]);
+
+ /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
+ ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
+ ** buffer overreads even if the record is corrupt. */
+ n = sqlite3_value_bytes(apVal[1]);
+ aBlob = sqlite3_value_blob(apVal[1]);
+ nSpace = n + FTS5_DATA_ZERO_PADDING;
+ a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
+ if( a==0 ) goto decode_out;
+ if( n>0 ) memcpy(a, aBlob, n);
+
+ fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
+
+ fts5DebugRowid(&rc, &s, iRowid);
+ if( bDlidx ){
+ Fts5Data dlidx;
+ Fts5DlidxLvl lvl;
+
+ dlidx.p = a;
+ dlidx.nn = n;
+
+ memset(&lvl, 0, sizeof(Fts5DlidxLvl));
+ lvl.pData = &dlidx;
+ lvl.iLeafPgno = iPgno;
+
+ for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
+ sqlite3Fts5BufferAppendPrintf(&rc, &s,
+ " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
+ );
+ }
+ }else if( iSegid==0 ){
+ if( iRowid==FTS5_AVERAGES_ROWID ){
+ fts5DecodeAverages(&rc, &s, a, n);
+ }else{
+ fts5DecodeStructure(&rc, &s, a, n);
+ }
+ }else if( eDetailNone ){
+ Fts5Buffer term; /* Current term read from page */
+ int szLeaf;
+ int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
+ int iTermOff;
+ int nKeep = 0;
+ int iOff;
+
+ memset(&term, 0, sizeof(Fts5Buffer));
+
+ /* Decode any entries that occur before the first term. */
+ if( szLeaf<n ){
+ iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
+ }else{
+ iTermOff = szLeaf;
+ }
+ fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
+
+ iOff = iTermOff;
+ while( iOff<szLeaf ){
+ int nAppend;
+
+ /* Read the term data for the next term*/
+ iOff += fts5GetVarint32(&a[iOff], nAppend);
+ term.n = nKeep;
+ fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
+ sqlite3Fts5BufferAppendPrintf(
+ &rc, &s, " term=%.*s", term.n, (const char*)term.p
+ );
+ iOff += nAppend;
+
+ /* Figure out where the doclist for this term ends */
+ if( iPgidxOff<n ){
+ int nIncr;
+ iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
+ iTermOff += nIncr;
+ }else{
+ iTermOff = szLeaf;
+ }
+
+ fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
+ iOff = iTermOff;
+ if( iOff<szLeaf ){
+ iOff += fts5GetVarint32(&a[iOff], nKeep);
+ }
+ }
+
+ fts5BufferFree(&term);
+ }else{
+ Fts5Buffer term; /* Current term read from page */
+ int szLeaf; /* Offset of pgidx in a[] */
+ int iPgidxOff;
+ int iPgidxPrev = 0; /* Previous value read from pgidx */
+ int iTermOff = 0;
+ int iRowidOff = 0;
+ int iOff;
+ int nDoclist;
+
+ memset(&term, 0, sizeof(Fts5Buffer));
+
+ if( n<4 ){
+ sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
+ goto decode_out;
+ }else{
+ iRowidOff = fts5GetU16(&a[0]);
+ iPgidxOff = szLeaf = fts5GetU16(&a[2]);
+ if( iPgidxOff<n ){
+ fts5GetVarint32(&a[iPgidxOff], iTermOff);
+ }else if( iPgidxOff>n ){
+ rc = FTS5_CORRUPT;
+ goto decode_out;
+ }
+ }
+
+ /* Decode the position list tail at the start of the page */
+ if( iRowidOff!=0 ){
+ iOff = iRowidOff;
+ }else if( iTermOff!=0 ){
+ iOff = iTermOff;
+ }else{
+ iOff = szLeaf;
+ }
+ if( iOff>n ){
+ rc = FTS5_CORRUPT;
+ goto decode_out;
+ }
+ fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
+
+ /* Decode any more doclist data that appears on the page before the
+ ** first term. */
+ nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
+ if( nDoclist+iOff>n ){
+ rc = FTS5_CORRUPT;
+ goto decode_out;
+ }
+ fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
+
+ while( iPgidxOff<n && rc==SQLITE_OK ){
+ int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
+ int nByte; /* Bytes of data */
+ int iEnd;
+
+ iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
+ iPgidxPrev += nByte;
+ iOff = iPgidxPrev;
+
+ if( iPgidxOff<n ){
+ fts5GetVarint32(&a[iPgidxOff], nByte);
+ iEnd = iPgidxPrev + nByte;
+ }else{
+ iEnd = szLeaf;
+ }
+ if( iEnd>szLeaf ){
+ rc = FTS5_CORRUPT;
+ break;
+ }
+
+ if( bFirst==0 ){
+ iOff += fts5GetVarint32(&a[iOff], nByte);
+ if( nByte>term.n ){
+ rc = FTS5_CORRUPT;
+ break;
+ }
+ term.n = nByte;
+ }
+ iOff += fts5GetVarint32(&a[iOff], nByte);
+ if( iOff+nByte>n ){
+ rc = FTS5_CORRUPT;
+ break;
+ }
+ fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
+ iOff += nByte;
+
+ sqlite3Fts5BufferAppendPrintf(
+ &rc, &s, " term=%.*s", term.n, (const char*)term.p
+ );
+ iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
+ }
+
+ fts5BufferFree(&term);
+ }
+
+ decode_out:
+ sqlite3_free(a);
+ if( rc==SQLITE_OK ){
+ sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
+ }else{
+ sqlite3_result_error_code(pCtx, rc);
+ }
+ fts5BufferFree(&s);
+}
+
+/*
+** The implementation of user-defined scalar function fts5_rowid().
+*/
+static void fts5RowidFunction(
+ sqlite3_context *pCtx, /* Function call context */
+ int nArg, /* Number of args (always 2) */
+ sqlite3_value **apVal /* Function arguments */
+){
+ const char *zArg;
+ if( nArg==0 ){
+ sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
+ }else{
+ zArg = (const char*)sqlite3_value_text(apVal[0]);
+ if( 0==sqlite3_stricmp(zArg, "segment") ){
+ i64 iRowid;
+ int segid, pgno;
+ if( nArg!=3 ){
+ sqlite3_result_error(pCtx,
+ "should be: fts5_rowid('segment', segid, pgno))", -1
+ );
+ }else{
+ segid = sqlite3_value_int(apVal[1]);
+ pgno = sqlite3_value_int(apVal[2]);
+ iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
+ sqlite3_result_int64(pCtx, iRowid);
+ }
+ }else{
+ sqlite3_result_error(pCtx,
+ "first arg to fts5_rowid() must be 'segment'" , -1
+ );
+ }
+ }
+}
+
+/*
+** This is called as part of registering the FTS5 module with database
+** connection db. It registers several user-defined scalar functions useful
+** with FTS5.
+**
+** If successful, SQLITE_OK is returned. If an error occurs, some other
+** SQLite error code is returned instead.
+*/
+static int sqlite3Fts5IndexInit(sqlite3 *db){
+ int rc = sqlite3_create_function(
+ db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
+ );
+
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_create_function(
+ db, "fts5_decode_none", 2,
+ SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
+ );
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_create_function(
+ db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
+ );
+ }
+ return rc;
+}
+
+
+static int sqlite3Fts5IndexReset(Fts5Index *p){
+ assert( p->pStruct==0 || p->iStructVersion!=0 );
+ if( fts5IndexDataVersion(p)!=p->iStructVersion ){
+ fts5StructureInvalidate(p);
+ }
+ return fts5IndexReturn(p);
+}
+
+/*
+** 2014 Jun 09
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This is an SQLite module implementing full-text search.
+*/
+
+
+/* #include "fts5Int.h" */
+
+/*
+** This variable is set to false when running tests for which the on disk
+** structures should not be corrupt. Otherwise, true. If it is false, extra
+** assert() conditions in the fts5 code are activated - conditions that are
+** only true if it is guaranteed that the fts5 database is not corrupt.
+*/
+SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
+
+
+typedef struct Fts5Auxdata Fts5Auxdata;
+typedef struct Fts5Auxiliary Fts5Auxiliary;
+typedef struct Fts5Cursor Fts5Cursor;
+typedef struct Fts5FullTable Fts5FullTable;
+typedef struct Fts5Sorter Fts5Sorter;
+typedef struct Fts5TokenizerModule Fts5TokenizerModule;
+
+/*
+** NOTES ON TRANSACTIONS:
+**
+** SQLite invokes the following virtual table methods as transactions are
+** opened and closed by the user:
+**
+** xBegin(): Start of a new transaction.
+** xSync(): Initial part of two-phase commit.
+** xCommit(): Final part of two-phase commit.
+** xRollback(): Rollback the transaction.
+**
+** Anything that is required as part of a commit that may fail is performed
+** in the xSync() callback. Current versions of SQLite ignore any errors
+** returned by xCommit().
+**
+** And as sub-transactions are opened/closed:
+**
+** xSavepoint(int S): Open savepoint S.
+** xRelease(int S): Commit and close savepoint S.
+** xRollbackTo(int S): Rollback to start of savepoint S.
+**
+** During a write-transaction the fts5_index.c module may cache some data
+** in-memory. It is flushed to disk whenever xSync(), xRelease() or
+** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
+** is called.
+**
+** Additionally, if SQLITE_DEBUG is defined, an instance of the following
+** structure is used to record the current transaction state. This information
+** is not required, but it is used in the assert() statements executed by
+** function fts5CheckTransactionState() (see below).
+*/
+struct Fts5TransactionState {
+ int eState; /* 0==closed, 1==open, 2==synced */
+ int iSavepoint; /* Number of open savepoints (0 -> none) */
+};
+
+/*
+** A single object of this type is allocated when the FTS5 module is
+** registered with a database handle. It is used to store pointers to
+** all registered FTS5 extensions - tokenizers and auxiliary functions.
+*/
+struct Fts5Global {
+ fts5_api api; /* User visible part of object (see fts5.h) */
+ sqlite3 *db; /* Associated database connection */
+ i64 iNextId; /* Used to allocate unique cursor ids */
+ Fts5Auxiliary *pAux; /* First in list of all aux. functions */
+ Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
+ Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
+ Fts5Cursor *pCsr; /* First in list of all open cursors */
+};
+
+/*
+** Each auxiliary function registered with the FTS5 module is represented
+** by an object of the following type. All such objects are stored as part
+** of the Fts5Global.pAux list.
+*/
+struct Fts5Auxiliary {
+ Fts5Global *pGlobal; /* Global context for this function */
+ char *zFunc; /* Function name (nul-terminated) */
+ void *pUserData; /* User-data pointer */
+ fts5_extension_function xFunc; /* Callback function */
+ void (*xDestroy)(void*); /* Destructor function */
+ Fts5Auxiliary *pNext; /* Next registered auxiliary function */
+};
+
+/*
+** Each tokenizer module registered with the FTS5 module is represented
+** by an object of the following type. All such objects are stored as part
+** of the Fts5Global.pTok list.
+*/
+struct Fts5TokenizerModule {
+ char *zName; /* Name of tokenizer */
+ void *pUserData; /* User pointer passed to xCreate() */
+ fts5_tokenizer x; /* Tokenizer functions */
+ void (*xDestroy)(void*); /* Destructor function */
+ Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
+};
+
+struct Fts5FullTable {
+ Fts5Table p; /* Public class members from fts5Int.h */
+ Fts5Storage *pStorage; /* Document store */
+ Fts5Global *pGlobal; /* Global (connection wide) data */
+ Fts5Cursor *pSortCsr; /* Sort data from this cursor */
+#ifdef SQLITE_DEBUG
+ struct Fts5TransactionState ts;
+#endif
+};
+
+struct Fts5MatchPhrase {
+ Fts5Buffer *pPoslist; /* Pointer to current poslist */
+ int nTerm; /* Size of phrase in terms */
+};
+
+/*
+** pStmt:
+** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
+**
+** aIdx[]:
+** There is one entry in the aIdx[] array for each phrase in the query,
+** the value of which is the offset within aPoslist[] following the last
+** byte of the position list for the corresponding phrase.
+*/
+struct Fts5Sorter {
+ sqlite3_stmt *pStmt;
+ i64 iRowid; /* Current rowid */
+ const u8 *aPoslist; /* Position lists for current row */
+ int nIdx; /* Number of entries in aIdx[] */
+ int aIdx[1]; /* Offsets into aPoslist for current row */
+};
+
+
+/*
+** Virtual-table cursor object.
+**
+** iSpecial:
+** If this is a 'special' query (refer to function fts5SpecialMatch()),
+** then this variable contains the result of the query.
+**
+** iFirstRowid, iLastRowid:
+** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
+** cursor iterates in ascending order of rowids, iFirstRowid is the lower
+** limit of rowids to return, and iLastRowid the upper. In other words, the
+** WHERE clause in the user's query might have been:
+**
+** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
+**
+** If the cursor iterates in descending order of rowid, iFirstRowid
+** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
+** the lower.
+*/
+struct Fts5Cursor {
+ sqlite3_vtab_cursor base; /* Base class used by SQLite core */
+ Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
+ int *aColumnSize; /* Values for xColumnSize() */
+ i64 iCsrId; /* Cursor id */
+
+ /* Zero from this point onwards on cursor reset */
+ int ePlan; /* FTS5_PLAN_XXX value */
+ int bDesc; /* True for "ORDER BY rowid DESC" queries */
+ i64 iFirstRowid; /* Return no rowids earlier than this */
+ i64 iLastRowid; /* Return no rowids later than this */
+ sqlite3_stmt *pStmt; /* Statement used to read %_content */
+ Fts5Expr *pExpr; /* Expression for MATCH queries */
+ Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
+ int csrflags; /* Mask of cursor flags (see below) */
+ i64 iSpecial; /* Result of special query */
+
+ /* "rank" function. Populated on demand from vtab.xColumn(). */
+ char *zRank; /* Custom rank function */
+ char *zRankArgs; /* Custom rank function args */
+ Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
+ int nRankArg; /* Number of trailing arguments for rank() */
+ sqlite3_value **apRankArg; /* Array of trailing arguments */
+ sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
+
+ /* Auxiliary data storage */
+ Fts5Auxiliary *pAux; /* Currently executing extension function */
+ Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
+
+ /* Cache used by auxiliary functions xInst() and xInstCount() */
+ Fts5PoslistReader *aInstIter; /* One for each phrase */
+ int nInstAlloc; /* Size of aInst[] array (entries / 3) */
+ int nInstCount; /* Number of phrase instances */
+ int *aInst; /* 3 integers per phrase instance */
+};
+
+/*
+** Bits that make up the "idxNum" parameter passed indirectly by
+** xBestIndex() to xFilter().
+*/
+#define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
+#define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
+#define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
+#define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
+#define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
+
+#define FTS5_BI_ORDER_RANK 0x0020
+#define FTS5_BI_ORDER_ROWID 0x0040
+#define FTS5_BI_ORDER_DESC 0x0080
+
+/*
+** Values for Fts5Cursor.csrflags
+*/
+#define FTS5CSR_EOF 0x01
+#define FTS5CSR_REQUIRE_CONTENT 0x02
+#define FTS5CSR_REQUIRE_DOCSIZE 0x04
+#define FTS5CSR_REQUIRE_INST 0x08
+#define FTS5CSR_FREE_ZRANK 0x10
+#define FTS5CSR_REQUIRE_RESEEK 0x20
+#define FTS5CSR_REQUIRE_POSLIST 0x40
+
+#define BitFlagAllTest(x,y) (((x) & (y))==(y))
+#define BitFlagTest(x,y) (((x) & (y))!=0)
+
+
+/*
+** Macros to Set(), Clear() and Test() cursor flags.
+*/
+#define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
+#define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
+#define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
+
+struct Fts5Auxdata {
+ Fts5Auxiliary *pAux; /* Extension to which this belongs */
+ void *pPtr; /* Pointer value */
+ void(*xDelete)(void*); /* Destructor */
+ Fts5Auxdata *pNext; /* Next object in linked list */
+};
+
+#ifdef SQLITE_DEBUG
+#define FTS5_BEGIN 1
+#define FTS5_SYNC 2
+#define FTS5_COMMIT 3
+#define FTS5_ROLLBACK 4
+#define FTS5_SAVEPOINT 5
+#define FTS5_RELEASE 6
+#define FTS5_ROLLBACKTO 7
+static void fts5CheckTransactionState(Fts5FullTable *p, int op, int iSavepoint){
+ switch( op ){
+ case FTS5_BEGIN:
+ assert( p->ts.eState==0 );
+ p->ts.eState = 1;
+ p->ts.iSavepoint = -1;
+ break;
+
+ case FTS5_SYNC:
+ assert( p->ts.eState==1 );
+ p->ts.eState = 2;
+ break;
+
+ case FTS5_COMMIT:
+ assert( p->ts.eState==2 );
+ p->ts.eState = 0;
+ break;
+
+ case FTS5_ROLLBACK:
+ assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
+ p->ts.eState = 0;
+ break;
+
+ case FTS5_SAVEPOINT:
+ assert( p->ts.eState==1 );
+ assert( iSavepoint>=0 );
+ assert( iSavepoint>=p->ts.iSavepoint );
+ p->ts.iSavepoint = iSavepoint;
+ break;
+
+ case FTS5_RELEASE:
+ assert( p->ts.eState==1 );
+ assert( iSavepoint>=0 );
+ assert( iSavepoint<=p->ts.iSavepoint );
+ p->ts.iSavepoint = iSavepoint-1;
+ break;
+
+ case FTS5_ROLLBACKTO:
+ assert( p->ts.eState==1 );
+ assert( iSavepoint>=-1 );
+ /* The following assert() can fail if another vtab strikes an error
+ ** within an xSavepoint() call then SQLite calls xRollbackTo() - without
+ ** having called xSavepoint() on this vtab. */
+ /* assert( iSavepoint<=p->ts.iSavepoint ); */
+ p->ts.iSavepoint = iSavepoint;
+ break;
+ }
+}
+#else
+# define fts5CheckTransactionState(x,y,z)
+#endif
+
+/*
+** Return true if pTab is a contentless table.
+*/
+static int fts5IsContentless(Fts5FullTable *pTab){
+ return pTab->p.pConfig->eContent==FTS5_CONTENT_NONE;
+}
+
+/*
+** Delete a virtual table handle allocated by fts5InitVtab().
+*/
+static void fts5FreeVtab(Fts5FullTable *pTab){
+ if( pTab ){
+ sqlite3Fts5IndexClose(pTab->p.pIndex);
+ sqlite3Fts5StorageClose(pTab->pStorage);
+ sqlite3Fts5ConfigFree(pTab->p.pConfig);
+ sqlite3_free(pTab);
+ }
+}
+
+/*
+** The xDisconnect() virtual table method.
+*/
+static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
+ fts5FreeVtab((Fts5FullTable*)pVtab);
+ return SQLITE_OK;
+}
+
+/*
+** The xDestroy() virtual table method.
+*/
+static int fts5DestroyMethod(sqlite3_vtab *pVtab){
+ Fts5Table *pTab = (Fts5Table*)pVtab;
+ int rc = sqlite3Fts5DropAll(pTab->pConfig);
+ if( rc==SQLITE_OK ){
+ fts5FreeVtab((Fts5FullTable*)pVtab);
+ }
+ return rc;
+}
+
+/*
+** This function is the implementation of both the xConnect and xCreate
+** methods of the FTS3 virtual table.
+**
+** The argv[] array contains the following:
+**
+** argv[0] -> module name ("fts5")
+** argv[1] -> database name
+** argv[2] -> table name
+** argv[...] -> "column name" and other module argument fields.
+*/
+static int fts5InitVtab(
+ int bCreate, /* True for xCreate, false for xConnect */
+ sqlite3 *db, /* The SQLite database connection */
+ void *pAux, /* Hash table containing tokenizers */
+ int argc, /* Number of elements in argv array */
+ const char * const *argv, /* xCreate/xConnect argument array */
+ sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
+ char **pzErr /* Write any error message here */
+){
+ Fts5Global *pGlobal = (Fts5Global*)pAux;
+ const char **azConfig = (const char**)argv;
+ int rc = SQLITE_OK; /* Return code */
+ Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
+ Fts5FullTable *pTab = 0; /* New virtual table object */
+
+ /* Allocate the new vtab object and parse the configuration */
+ pTab = (Fts5FullTable*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5FullTable));
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
+ assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
+ }
+ if( rc==SQLITE_OK ){
+ pTab->p.pConfig = pConfig;
+ pTab->pGlobal = pGlobal;
+ }
+
+ /* Open the index sub-system */
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->p.pIndex, pzErr);
+ }
+
+ /* Open the storage sub-system */
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5StorageOpen(
+ pConfig, pTab->p.pIndex, bCreate, &pTab->pStorage, pzErr
+ );
+ }
+
+ /* Call sqlite3_declare_vtab() */
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
+ }
+
+ /* Load the initial configuration */
+ if( rc==SQLITE_OK ){
+ assert( pConfig->pzErrmsg==0 );
+ pConfig->pzErrmsg = pzErr;
+ rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
+ sqlite3Fts5IndexRollback(pTab->p.pIndex);
+ pConfig->pzErrmsg = 0;
+ }
+
+ if( rc!=SQLITE_OK ){
+ fts5FreeVtab(pTab);
+ pTab = 0;
+ }else if( bCreate ){
+ fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
+ }
+ *ppVTab = (sqlite3_vtab*)pTab;
+ return rc;
+}
+
+/*
+** The xConnect() and xCreate() methods for the virtual table. All the
+** work is done in function fts5InitVtab().
+*/
+static int fts5ConnectMethod(
+ sqlite3 *db, /* Database connection */
+ void *pAux, /* Pointer to tokenizer hash table */
+ int argc, /* Number of elements in argv array */
+ const char * const *argv, /* xCreate/xConnect argument array */
+ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
+ char **pzErr /* OUT: sqlite3_malloc'd error message */
+){
+ return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
+}
+static int fts5CreateMethod(
+ sqlite3 *db, /* Database connection */
+ void *pAux, /* Pointer to tokenizer hash table */
+ int argc, /* Number of elements in argv array */
+ const char * const *argv, /* xCreate/xConnect argument array */
+ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
+ char **pzErr /* OUT: sqlite3_malloc'd error message */
+){
+ return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
+}
+
+/*
+** The different query plans.
+*/
+#define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
+#define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
+#define FTS5_PLAN_SPECIAL 3 /* An internal query */
+#define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
+#define FTS5_PLAN_SCAN 5 /* No usable constraint */
+#define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
+
+/*
+** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
+** extension is currently being used by a version of SQLite too old to
+** support index-info flags. In that case this function is a no-op.
+*/
+static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
+#if SQLITE_VERSION_NUMBER>=3008012
+#ifndef SQLITE_CORE
+ if( sqlite3_libversion_number()>=3008012 )
+#endif
+ {
+ pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
+ }
+#endif
+}
+
+/*
+** Implementation of the xBestIndex method for FTS5 tables. Within the
+** WHERE constraint, it searches for the following:
+**
+** 1. A MATCH constraint against the table column.
+** 2. A MATCH constraint against the "rank" column.
+** 3. A MATCH constraint against some other column.
+** 4. An == constraint against the rowid column.
+** 5. A < or <= constraint against the rowid column.
+** 6. A > or >= constraint against the rowid column.
+**
+** Within the ORDER BY, the following are supported:
+**
+** 5. ORDER BY rank [ASC|DESC]
+** 6. ORDER BY rowid [ASC|DESC]
+**
+** Information for the xFilter call is passed via both the idxNum and
+** idxStr variables. Specifically, idxNum is a bitmask of the following
+** flags used to encode the ORDER BY clause:
+**
+** FTS5_BI_ORDER_RANK
+** FTS5_BI_ORDER_ROWID
+** FTS5_BI_ORDER_DESC
+**
+** idxStr is used to encode data from the WHERE clause. For each argument
+** passed to the xFilter method, the following is appended to idxStr:
+**
+** Match against table column: "m"
+** Match against rank column: "r"
+** Match against other column: "M<column-number>"
+** LIKE against other column: "L<column-number>"
+** GLOB against other column: "G<column-number>"
+** Equality constraint against the rowid: "="
+** A < or <= against the rowid: "<"
+** A > or >= against the rowid: ">"
+**
+** This function ensures that there is at most one "r" or "=". And that if
+** there exists an "=" then there is no "<" or ">".
+**
+** Costs are assigned as follows:
+**
+** a) If an unusable MATCH operator is present in the WHERE clause, the
+** cost is unconditionally set to 1e50 (a really big number).
+**
+** a) If a MATCH operator is present, the cost depends on the other
+** constraints also present. As follows:
+**
+** * No other constraints: cost=1000.0
+** * One rowid range constraint: cost=750.0
+** * Both rowid range constraints: cost=500.0
+** * An == rowid constraint: cost=100.0
+**
+** b) Otherwise, if there is no MATCH:
+**
+** * No other constraints: cost=1000000.0
+** * One rowid range constraint: cost=750000.0
+** * Both rowid range constraints: cost=250000.0
+** * An == rowid constraint: cost=10.0
+**
+** Costs are not modified by the ORDER BY clause.
+*/
+static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
+ Fts5Table *pTab = (Fts5Table*)pVTab;
+ Fts5Config *pConfig = pTab->pConfig;
+ const int nCol = pConfig->nCol;
+ int idxFlags = 0; /* Parameter passed through to xFilter() */
+ int i;
+
+ char *idxStr;
+ int iIdxStr = 0;
+ int iCons = 0;
+
+ int bSeenEq = 0;
+ int bSeenGt = 0;
+ int bSeenLt = 0;
+ int bSeenMatch = 0;
+ int bSeenRank = 0;
+
+
+ assert( SQLITE_INDEX_CONSTRAINT_EQ<SQLITE_INDEX_CONSTRAINT_MATCH );
+ assert( SQLITE_INDEX_CONSTRAINT_GT<SQLITE_INDEX_CONSTRAINT_MATCH );
+ assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
+ assert( SQLITE_INDEX_CONSTRAINT_GE<SQLITE_INDEX_CONSTRAINT_MATCH );
+ assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
+
+ if( pConfig->bLock ){
+ pTab->base.zErrMsg = sqlite3_mprintf(
+ "recursively defined fts5 content table"
+ );
+ return SQLITE_ERROR;
+ }
+
+ idxStr = (char*)sqlite3_malloc(pInfo->nConstraint * 8 + 1);
+ if( idxStr==0 ) return SQLITE_NOMEM;
+ pInfo->idxStr = idxStr;
+ pInfo->needToFreeIdxStr = 1;
+
+ for(i=0; i<pInfo->nConstraint; i++){
+ struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
+ int iCol = p->iColumn;
+ if( p->op==SQLITE_INDEX_CONSTRAINT_MATCH
+ || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol>=nCol)
+ ){
+ /* A MATCH operator or equivalent */
+ if( p->usable==0 || iCol<0 ){
+ /* As there exists an unusable MATCH constraint this is an
+ ** unusable plan. Set a prohibitively high cost. */
+ pInfo->estimatedCost = 1e50;
+ assert( iIdxStr < pInfo->nConstraint*6 + 1 );
+ idxStr[iIdxStr] = 0;
+ return SQLITE_OK;
+ }else{
+ if( iCol==nCol+1 ){
+ if( bSeenRank ) continue;
+ idxStr[iIdxStr++] = 'r';
+ bSeenRank = 1;
+ }else if( iCol>=0 ){
+ bSeenMatch = 1;
+ idxStr[iIdxStr++] = 'M';
+ sqlite3_snprintf(6, &idxStr[iIdxStr], "%d", iCol);
+ idxStr += strlen(&idxStr[iIdxStr]);
+ assert( idxStr[iIdxStr]=='\0' );
+ }
+ pInfo->aConstraintUsage[i].argvIndex = ++iCons;
+ pInfo->aConstraintUsage[i].omit = 1;
+ }
+ }else if( p->usable ){
+ if( iCol>=0 && iCol<nCol && pConfig->ePattern==p->op ){
+ assert( p->op==FTS5_PATTERN_LIKE || p->op==FTS5_PATTERN_GLOB );
+ idxStr[iIdxStr++] = p->op==FTS5_PATTERN_LIKE ? 'L' : 'G';
+ sqlite3_snprintf(6, &idxStr[iIdxStr], "%d", iCol);
+ idxStr += strlen(&idxStr[iIdxStr]);
+ pInfo->aConstraintUsage[i].argvIndex = ++iCons;
+ assert( idxStr[iIdxStr]=='\0' );
+ }else if( bSeenEq==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol<0 ){
+ idxStr[iIdxStr++] = '=';
+ bSeenEq = 1;
+ pInfo->aConstraintUsage[i].argvIndex = ++iCons;
+ }
+ }
+ }
+
+ if( bSeenEq==0 ){
+ for(i=0; i<pInfo->nConstraint; i++){
+ struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
+ if( p->iColumn<0 && p->usable ){
+ int op = p->op;
+ if( op==SQLITE_INDEX_CONSTRAINT_LT || op==SQLITE_INDEX_CONSTRAINT_LE ){
+ if( bSeenLt ) continue;
+ idxStr[iIdxStr++] = '<';
+ pInfo->aConstraintUsage[i].argvIndex = ++iCons;
+ bSeenLt = 1;
+ }else
+ if( op==SQLITE_INDEX_CONSTRAINT_GT || op==SQLITE_INDEX_CONSTRAINT_GE ){
+ if( bSeenGt ) continue;
+ idxStr[iIdxStr++] = '>';
+ pInfo->aConstraintUsage[i].argvIndex = ++iCons;
+ bSeenGt = 1;
+ }
+ }
+ }
+ }
+ idxStr[iIdxStr] = '\0';
+
+ /* Set idxFlags flags for the ORDER BY clause */
+ if( pInfo->nOrderBy==1 ){
+ int iSort = pInfo->aOrderBy[0].iColumn;
+ if( iSort==(pConfig->nCol+1) && bSeenMatch ){
+ idxFlags |= FTS5_BI_ORDER_RANK;
+ }else if( iSort==-1 ){
+ idxFlags |= FTS5_BI_ORDER_ROWID;
+ }
+ if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
+ pInfo->orderByConsumed = 1;
+ if( pInfo->aOrderBy[0].desc ){
+ idxFlags |= FTS5_BI_ORDER_DESC;
+ }
+ }
+ }
+
+ /* Calculate the estimated cost based on the flags set in idxFlags. */
+ if( bSeenEq ){
+ pInfo->estimatedCost = bSeenMatch ? 100.0 : 10.0;
+ if( bSeenMatch==0 ) fts5SetUniqueFlag(pInfo);
+ }else if( bSeenLt && bSeenGt ){
+ pInfo->estimatedCost = bSeenMatch ? 500.0 : 250000.0;
+ }else if( bSeenLt || bSeenGt ){
+ pInfo->estimatedCost = bSeenMatch ? 750.0 : 750000.0;
+ }else{
+ pInfo->estimatedCost = bSeenMatch ? 1000.0 : 1000000.0;
+ }
+
+ pInfo->idxNum = idxFlags;
+ return SQLITE_OK;
+}
+
+static int fts5NewTransaction(Fts5FullTable *pTab){
+ Fts5Cursor *pCsr;
+ for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
+ if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
+ }
+ return sqlite3Fts5StorageReset(pTab->pStorage);
+}
+
+/*
+** Implementation of xOpen method.
+*/
+static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
+ Fts5FullTable *pTab = (Fts5FullTable*)pVTab;
+ Fts5Config *pConfig = pTab->p.pConfig;
+ Fts5Cursor *pCsr = 0; /* New cursor object */
+ sqlite3_int64 nByte; /* Bytes of space to allocate */
+ int rc; /* Return code */
+
+ rc = fts5NewTransaction(pTab);
+ if( rc==SQLITE_OK ){
+ nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
+ pCsr = (Fts5Cursor*)sqlite3_malloc64(nByte);
+ if( pCsr ){
+ Fts5Global *pGlobal = pTab->pGlobal;
+ memset(pCsr, 0, (size_t)nByte);
+ pCsr->aColumnSize = (int*)&pCsr[1];
+ pCsr->pNext = pGlobal->pCsr;
+ pGlobal->pCsr = pCsr;
+ pCsr->iCsrId = ++pGlobal->iNextId;
+ }else{
+ rc = SQLITE_NOMEM;
+ }
+ }
+ *ppCsr = (sqlite3_vtab_cursor*)pCsr;
+ return rc;
+}
+
+static int fts5StmtType(Fts5Cursor *pCsr){
+ if( pCsr->ePlan==FTS5_PLAN_SCAN ){
+ return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
+ }
+ return FTS5_STMT_LOOKUP;
+}
+
+/*
+** This function is called after the cursor passed as the only argument
+** is moved to point at a different row. It clears all cached data
+** specific to the previous row stored by the cursor object.
+*/
+static void fts5CsrNewrow(Fts5Cursor *pCsr){
+ CsrFlagSet(pCsr,
+ FTS5CSR_REQUIRE_CONTENT
+ | FTS5CSR_REQUIRE_DOCSIZE
+ | FTS5CSR_REQUIRE_INST
+ | FTS5CSR_REQUIRE_POSLIST
+ );
+}
+
+static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
+ Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
+ Fts5Auxdata *pData;
+ Fts5Auxdata *pNext;
+
+ sqlite3_free(pCsr->aInstIter);
+ sqlite3_free(pCsr->aInst);
+ if( pCsr->pStmt ){
+ int eStmt = fts5StmtType(pCsr);
+ sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
+ }
+ if( pCsr->pSorter ){
+ Fts5Sorter *pSorter = pCsr->pSorter;
+ sqlite3_finalize(pSorter->pStmt);
+ sqlite3_free(pSorter);
+ }
+
+ if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
+ sqlite3Fts5ExprFree(pCsr->pExpr);
+ }
+
+ for(pData=pCsr->pAuxdata; pData; pData=pNext){
+ pNext = pData->pNext;
+ if( pData->xDelete ) pData->xDelete(pData->pPtr);
+ sqlite3_free(pData);
+ }
+
+ sqlite3_finalize(pCsr->pRankArgStmt);
+ sqlite3_free(pCsr->apRankArg);
+
+ if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
+ sqlite3_free(pCsr->zRank);
+ sqlite3_free(pCsr->zRankArgs);
+ }
+
+ sqlite3Fts5IndexCloseReader(pTab->p.pIndex);
+ memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
+}
+
+
+/*
+** Close the cursor. For additional information see the documentation
+** on the xClose method of the virtual table interface.
+*/
+static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
+ if( pCursor ){
+ Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
+ Fts5Cursor **pp;
+
+ fts5FreeCursorComponents(pCsr);
+ /* Remove the cursor from the Fts5Global.pCsr list */
+ for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
+ *pp = pCsr->pNext;
+
+ sqlite3_free(pCsr);
+ }
+ return SQLITE_OK;
+}
+
+static int fts5SorterNext(Fts5Cursor *pCsr){
+ Fts5Sorter *pSorter = pCsr->pSorter;
+ int rc;
+
+ rc = sqlite3_step(pSorter->pStmt);
+ if( rc==SQLITE_DONE ){
+ rc = SQLITE_OK;
+ CsrFlagSet(pCsr, FTS5CSR_EOF);
+ }else if( rc==SQLITE_ROW ){
+ const u8 *a;
+ const u8 *aBlob;
+ int nBlob;
+ int i;
+ int iOff = 0;
+ rc = SQLITE_OK;
+
+ pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
+ nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
+ aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
+
+ /* nBlob==0 in detail=none mode. */
+ if( nBlob>0 ){
+ for(i=0; i<(pSorter->nIdx-1); i++){
+ int iVal;
+ a += fts5GetVarint32(a, iVal);
+ iOff += iVal;
+ pSorter->aIdx[i] = iOff;
+ }
+ pSorter->aIdx[i] = &aBlob[nBlob] - a;
+ pSorter->aPoslist = a;
+ }
+
+ fts5CsrNewrow(pCsr);
+ }
+
+ return rc;
+}
+
+
+/*
+** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
+** open on table pTab.
+*/
+static void fts5TripCursors(Fts5FullTable *pTab){
+ Fts5Cursor *pCsr;
+ for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
+ if( pCsr->ePlan==FTS5_PLAN_MATCH
+ && pCsr->base.pVtab==(sqlite3_vtab*)pTab
+ ){
+ CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
+ }
+ }
+}
+
+/*
+** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
+** argument, close and reopen all Fts5IndexIter iterators that the cursor
+** is using. Then attempt to move the cursor to a rowid equal to or laster
+** (in the cursors sort order - ASC or DESC) than the current rowid.
+**
+** If the new rowid is not equal to the old, set output parameter *pbSkip
+** to 1 before returning. Otherwise, leave it unchanged.
+**
+** Return SQLITE_OK if successful or if no reseek was required, or an
+** error code if an error occurred.
+*/
+static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
+ int rc = SQLITE_OK;
+ assert( *pbSkip==0 );
+ if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
+ Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
+ int bDesc = pCsr->bDesc;
+ i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
+
+ rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->p.pIndex, iRowid, bDesc);
+ if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
+ *pbSkip = 1;
+ }
+
+ CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
+ fts5CsrNewrow(pCsr);
+ if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
+ CsrFlagSet(pCsr, FTS5CSR_EOF);
+ *pbSkip = 1;
+ }
+ }
+ return rc;
+}
+
+
+/*
+** Advance the cursor to the next row in the table that matches the
+** search criteria.
+**
+** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
+** even if we reach end-of-file. The fts5EofMethod() will be called
+** subsequently to determine whether or not an EOF was hit.
+*/
+static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
+ int rc;
+
+ assert( (pCsr->ePlan<3)==
+ (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
+ );
+ assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
+
+ if( pCsr->ePlan<3 ){
+ int bSkip = 0;
+ if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
+ rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
+ CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
+ fts5CsrNewrow(pCsr);
+ }else{
+ switch( pCsr->ePlan ){
+ case FTS5_PLAN_SPECIAL: {
+ CsrFlagSet(pCsr, FTS5CSR_EOF);
+ rc = SQLITE_OK;
+ break;
+ }
+
+ case FTS5_PLAN_SORTED_MATCH: {
+ rc = fts5SorterNext(pCsr);
+ break;
+ }
+
+ default: {
+ Fts5Config *pConfig = ((Fts5Table*)pCursor->pVtab)->pConfig;
+ pConfig->bLock++;
+ rc = sqlite3_step(pCsr->pStmt);
+ pConfig->bLock--;
+ if( rc!=SQLITE_ROW ){
+ CsrFlagSet(pCsr, FTS5CSR_EOF);
+ rc = sqlite3_reset(pCsr->pStmt);
+ if( rc!=SQLITE_OK ){
+ pCursor->pVtab->zErrMsg = sqlite3_mprintf(
+ "%s", sqlite3_errmsg(pConfig->db)
+ );
+ }
+ }else{
+ rc = SQLITE_OK;
+ }
+ break;
+ }
+ }
+ }
+
+ return rc;
+}
+
+
+static int fts5PrepareStatement(
+ sqlite3_stmt **ppStmt,
+ Fts5Config *pConfig,
+ const char *zFmt,
+ ...
+){
+ sqlite3_stmt *pRet = 0;
+ int rc;
+ char *zSql;
+ va_list ap;
+
+ va_start(ap, zFmt);
+ zSql = sqlite3_vmprintf(zFmt, ap);
+ if( zSql==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
+ SQLITE_PREPARE_PERSISTENT, &pRet, 0);
+ if( rc!=SQLITE_OK ){
+ *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
+ }
+ sqlite3_free(zSql);
+ }
+
+ va_end(ap);
+ *ppStmt = pRet;
+ return rc;
+}
+
+static int fts5CursorFirstSorted(
+ Fts5FullTable *pTab,
+ Fts5Cursor *pCsr,
+ int bDesc
+){
+ Fts5Config *pConfig = pTab->p.pConfig;
+ Fts5Sorter *pSorter;
+ int nPhrase;
+ sqlite3_int64 nByte;
+ int rc;
+ const char *zRank = pCsr->zRank;
+ const char *zRankArgs = pCsr->zRankArgs;
+
+ nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
+ nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
+ pSorter = (Fts5Sorter*)sqlite3_malloc64(nByte);
+ if( pSorter==0 ) return SQLITE_NOMEM;
+ memset(pSorter, 0, (size_t)nByte);
+ pSorter->nIdx = nPhrase;
+
+ /* TODO: It would be better to have some system for reusing statement
+ ** handles here, rather than preparing a new one for each query. But that
+ ** is not possible as SQLite reference counts the virtual table objects.
+ ** And since the statement required here reads from this very virtual
+ ** table, saving it creates a circular reference.
+ **
+ ** If SQLite a built-in statement cache, this wouldn't be a problem. */
+ rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
+ "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(\"%w\"%s%s) %s",
+ pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
+ (zRankArgs ? ", " : ""),
+ (zRankArgs ? zRankArgs : ""),
+ bDesc ? "DESC" : "ASC"
+ );
+
+ pCsr->pSorter = pSorter;
+ if( rc==SQLITE_OK ){
+ assert( pTab->pSortCsr==0 );
+ pTab->pSortCsr = pCsr;
+ rc = fts5SorterNext(pCsr);
+ pTab->pSortCsr = 0;
+ }
+
+ if( rc!=SQLITE_OK ){
+ sqlite3_finalize(pSorter->pStmt);
+ sqlite3_free(pSorter);
+ pCsr->pSorter = 0;
+ }
+
+ return rc;
+}
+
+static int fts5CursorFirst(Fts5FullTable *pTab, Fts5Cursor *pCsr, int bDesc){
+ int rc;
+ Fts5Expr *pExpr = pCsr->pExpr;
+ rc = sqlite3Fts5ExprFirst(pExpr, pTab->p.pIndex, pCsr->iFirstRowid, bDesc);
+ if( sqlite3Fts5ExprEof(pExpr) ){
+ CsrFlagSet(pCsr, FTS5CSR_EOF);
+ }
+ fts5CsrNewrow(pCsr);
+ return rc;
+}
+
+/*
+** Process a "special" query. A special query is identified as one with a
+** MATCH expression that begins with a '*' character. The remainder of
+** the text passed to the MATCH operator are used as the special query
+** parameters.
+*/
+static int fts5SpecialMatch(
+ Fts5FullTable *pTab,
+ Fts5Cursor *pCsr,
+ const char *zQuery
+){
+ int rc = SQLITE_OK; /* Return code */
+ const char *z = zQuery; /* Special query text */
+ int n; /* Number of bytes in text at z */
+
+ while( z[0]==' ' ) z++;
+ for(n=0; z[n] && z[n]!=' '; n++);
+
+ assert( pTab->p.base.zErrMsg==0 );
+ pCsr->ePlan = FTS5_PLAN_SPECIAL;
+
+ if( n==5 && 0==sqlite3_strnicmp("reads", z, n) ){
+ pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->p.pIndex);
+ }
+ else if( n==2 && 0==sqlite3_strnicmp("id", z, n) ){
+ pCsr->iSpecial = pCsr->iCsrId;
+ }
+ else{
+ /* An unrecognized directive. Return an error message. */
+ pTab->p.base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
+ rc = SQLITE_ERROR;
+ }
+
+ return rc;
+}
+
+/*
+** Search for an auxiliary function named zName that can be used with table
+** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
+** structure. Otherwise, if no such function exists, return NULL.
+*/
+static Fts5Auxiliary *fts5FindAuxiliary(Fts5FullTable *pTab, const char *zName){
+ Fts5Auxiliary *pAux;
+
+ for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
+ if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
+ }
+
+ /* No function of the specified name was found. Return 0. */
+ return 0;
+}
+
+
+static int fts5FindRankFunction(Fts5Cursor *pCsr){
+ Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
+ Fts5Config *pConfig = pTab->p.pConfig;
+ int rc = SQLITE_OK;
+ Fts5Auxiliary *pAux = 0;
+ const char *zRank = pCsr->zRank;
+ const char *zRankArgs = pCsr->zRankArgs;
+
+ if( zRankArgs ){
+ char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
+ if( zSql ){
+ sqlite3_stmt *pStmt = 0;
+ rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
+ SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
+ sqlite3_free(zSql);
+ assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
+ if( rc==SQLITE_OK ){
+ if( SQLITE_ROW==sqlite3_step(pStmt) ){
+ sqlite3_int64 nByte;
+ pCsr->nRankArg = sqlite3_column_count(pStmt);
+ nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
+ pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
+ if( rc==SQLITE_OK ){
+ int i;
+ for(i=0; i<pCsr->nRankArg; i++){
+ pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
+ }
+ }
+ pCsr->pRankArgStmt = pStmt;
+ }else{
+ rc = sqlite3_finalize(pStmt);
+ assert( rc!=SQLITE_OK );
+ }
+ }
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ pAux = fts5FindAuxiliary(pTab, zRank);
+ if( pAux==0 ){
+ assert( pTab->p.base.zErrMsg==0 );
+ pTab->p.base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
+ rc = SQLITE_ERROR;
+ }
+ }
+
+ pCsr->pRank = pAux;
+ return rc;
+}
+
+
+static int fts5CursorParseRank(
+ Fts5Config *pConfig,
+ Fts5Cursor *pCsr,
+ sqlite3_value *pRank
+){
+ int rc = SQLITE_OK;
+ if( pRank ){
+ const char *z = (const char*)sqlite3_value_text(pRank);
+ char *zRank = 0;
+ char *zRankArgs = 0;
+
+ if( z==0 ){
+ if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
+ }else{
+ rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
+ }
+ if( rc==SQLITE_OK ){
+ pCsr->zRank = zRank;
+ pCsr->zRankArgs = zRankArgs;
+ CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
+ }else if( rc==SQLITE_ERROR ){
+ pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
+ "parse error in rank function: %s", z
+ );
+ }
+ }else{
+ if( pConfig->zRank ){
+ pCsr->zRank = (char*)pConfig->zRank;
+ pCsr->zRankArgs = (char*)pConfig->zRankArgs;
+ }else{
+ pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
+ pCsr->zRankArgs = 0;
+ }
+ }
+ return rc;
+}
+
+static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
+ if( pVal ){
+ int eType = sqlite3_value_numeric_type(pVal);
+ if( eType==SQLITE_INTEGER ){
+ return sqlite3_value_int64(pVal);
+ }
+ }
+ return iDefault;
+}
+
+/*
+** This is the xFilter interface for the virtual table. See
+** the virtual table xFilter method documentation for additional
+** information.
+**
+** There are three possible query strategies:
+**
+** 1. Full-text search using a MATCH operator.
+** 2. A by-rowid lookup.
+** 3. A full-table scan.
+*/
+static int fts5FilterMethod(
+ sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
+ int idxNum, /* Strategy index */
+ const char *idxStr, /* Unused */
+ int nVal, /* Number of elements in apVal */
+ sqlite3_value **apVal /* Arguments for the indexing scheme */
+){
+ Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
+ Fts5Config *pConfig = pTab->p.pConfig;
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
+ int rc = SQLITE_OK; /* Error code */
+ int bDesc; /* True if ORDER BY [rank|rowid] DESC */
+ int bOrderByRank; /* True if ORDER BY rank */
+ sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
+ sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
+ sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
+ sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
+ int iCol; /* Column on LHS of MATCH operator */
+ char **pzErrmsg = pConfig->pzErrmsg;
+ int i;
+ int iIdxStr = 0;
+ Fts5Expr *pExpr = 0;
+
+ if( pConfig->bLock ){
+ pTab->p.base.zErrMsg = sqlite3_mprintf(
+ "recursively defined fts5 content table"
+ );
+ return SQLITE_ERROR;
+ }
+
+ if( pCsr->ePlan ){
+ fts5FreeCursorComponents(pCsr);
+ memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
+ }
+
+ assert( pCsr->pStmt==0 );
+ assert( pCsr->pExpr==0 );
+ assert( pCsr->csrflags==0 );
+ assert( pCsr->pRank==0 );
+ assert( pCsr->zRank==0 );
+ assert( pCsr->zRankArgs==0 );
+ assert( pTab->pSortCsr==0 || nVal==0 );
+
+ assert( pzErrmsg==0 || pzErrmsg==&pTab->p.base.zErrMsg );
+ pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
+
+ /* Decode the arguments passed through to this function. */
+ for(i=0; i<nVal; i++){
+ switch( idxStr[iIdxStr++] ){
+ case 'r':
+ pRank = apVal[i];
+ break;
+ case 'M': {
+ const char *zText = (const char*)sqlite3_value_text(apVal[i]);
+ if( zText==0 ) zText = "";
+ iCol = 0;
+ do{
+ iCol = iCol*10 + (idxStr[iIdxStr]-'0');
+ iIdxStr++;
+ }while( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' );
+
+ if( zText[0]=='*' ){
+ /* The user has issued a query of the form "MATCH '*...'". This
+ ** indicates that the MATCH expression is not a full text query,
+ ** but a request for an internal parameter. */
+ rc = fts5SpecialMatch(pTab, pCsr, &zText[1]);
+ goto filter_out;
+ }else{
+ char **pzErr = &pTab->p.base.zErrMsg;
+ rc = sqlite3Fts5ExprNew(pConfig, iCol, zText, &pExpr, pzErr);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5ExprAnd(&pCsr->pExpr, pExpr);
+ pExpr = 0;
+ }
+ if( rc!=SQLITE_OK ) goto filter_out;
+ }
+
+ break;
+ }
+ case 'L':
+ case 'G': {
+ const char *zText = (const char*)sqlite3_value_text(apVal[i]);
+ iCol = 0;
+ do{
+ iCol = iCol*10 + (idxStr[iIdxStr]-'0');
+ iIdxStr++;
+ }while( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' );
+ rc = sqlite3Fts5ExprPattern(pConfig, iCol, zText, &pExpr);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5ExprAnd(&pCsr->pExpr, pExpr);
+ pExpr = 0;
+ }
+ if( rc!=SQLITE_OK ) goto filter_out;
+ break;
+ }
+ case '=':
+ pRowidEq = apVal[i];
+ break;
+ case '<':
+ pRowidLe = apVal[i];
+ break;
+ default: assert( idxStr[iIdxStr-1]=='>' );
+ pRowidGe = apVal[i];
+ break;
+ }
+ }
+ bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
+ pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
+
+ /* Set the cursor upper and lower rowid limits. Only some strategies
+ ** actually use them. This is ok, as the xBestIndex() method leaves the
+ ** sqlite3_index_constraint.omit flag clear for range constraints
+ ** on the rowid field. */
+ if( pRowidEq ){
+ pRowidLe = pRowidGe = pRowidEq;
+ }
+ if( bDesc ){
+ pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
+ pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
+ }else{
+ pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
+ pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
+ }
+
+ if( pTab->pSortCsr ){
+ /* If pSortCsr is non-NULL, then this call is being made as part of
+ ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
+ ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
+ ** return results to the user for this query. The current cursor
+ ** (pCursor) is used to execute the query issued by function
+ ** fts5CursorFirstSorted() above. */
+ assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
+ assert( nVal==0 && bOrderByRank==0 && bDesc==0 );
+ assert( pCsr->iLastRowid==LARGEST_INT64 );
+ assert( pCsr->iFirstRowid==SMALLEST_INT64 );
+ if( pTab->pSortCsr->bDesc ){
+ pCsr->iLastRowid = pTab->pSortCsr->iFirstRowid;
+ pCsr->iFirstRowid = pTab->pSortCsr->iLastRowid;
+ }else{
+ pCsr->iLastRowid = pTab->pSortCsr->iLastRowid;
+ pCsr->iFirstRowid = pTab->pSortCsr->iFirstRowid;
+ }
+ pCsr->ePlan = FTS5_PLAN_SOURCE;
+ pCsr->pExpr = pTab->pSortCsr->pExpr;
+ rc = fts5CursorFirst(pTab, pCsr, bDesc);
+ }else if( pCsr->pExpr ){
+ rc = fts5CursorParseRank(pConfig, pCsr, pRank);
+ if( rc==SQLITE_OK ){
+ if( bOrderByRank ){
+ pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
+ rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
+ }else{
+ pCsr->ePlan = FTS5_PLAN_MATCH;
+ rc = fts5CursorFirst(pTab, pCsr, bDesc);
+ }
+ }
+ }else if( pConfig->zContent==0 ){
+ *pConfig->pzErrmsg = sqlite3_mprintf(
+ "%s: table does not support scanning", pConfig->zName
+ );
+ rc = SQLITE_ERROR;
+ }else{
+ /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
+ ** by rowid (ePlan==FTS5_PLAN_ROWID). */
+ pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
+ rc = sqlite3Fts5StorageStmt(
+ pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->p.base.zErrMsg
+ );
+ if( rc==SQLITE_OK ){
+ if( pCsr->ePlan==FTS5_PLAN_ROWID ){
+ sqlite3_bind_value(pCsr->pStmt, 1, pRowidEq);
+ }else{
+ sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
+ sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
+ }
+ rc = fts5NextMethod(pCursor);
+ }
+ }
+
+ filter_out:
+ sqlite3Fts5ExprFree(pExpr);
+ pConfig->pzErrmsg = pzErrmsg;
+ return rc;
+}
+
+/*
+** This is the xEof method of the virtual table. SQLite calls this
+** routine to find out if it has reached the end of a result set.
+*/
+static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
+ return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
+}
+
+/*
+** Return the rowid that the cursor currently points to.
+*/
+static i64 fts5CursorRowid(Fts5Cursor *pCsr){
+ assert( pCsr->ePlan==FTS5_PLAN_MATCH
+ || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
+ || pCsr->ePlan==FTS5_PLAN_SOURCE
+ );
+ if( pCsr->pSorter ){
+ return pCsr->pSorter->iRowid;
+ }else{
+ return sqlite3Fts5ExprRowid(pCsr->pExpr);
+ }
+}
+
+/*
+** This is the xRowid method. The SQLite core calls this routine to
+** retrieve the rowid for the current row of the result set. fts5
+** exposes %_content.rowid as the rowid for the virtual table. The
+** rowid should be written to *pRowid.
+*/
+static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
+ int ePlan = pCsr->ePlan;
+
+ assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
+ switch( ePlan ){
+ case FTS5_PLAN_SPECIAL:
+ *pRowid = 0;
+ break;
+
+ case FTS5_PLAN_SOURCE:
+ case FTS5_PLAN_MATCH:
+ case FTS5_PLAN_SORTED_MATCH:
+ *pRowid = fts5CursorRowid(pCsr);
+ break;
+
+ default:
+ *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
+ break;
+ }
+
+ return SQLITE_OK;
+}
+
+/*
+** If the cursor requires seeking (bSeekRequired flag is set), seek it.
+** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
+**
+** If argument bErrormsg is true and an error occurs, an error message may
+** be left in sqlite3_vtab.zErrMsg.
+*/
+static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
+ int rc = SQLITE_OK;
+
+ /* If the cursor does not yet have a statement handle, obtain one now. */
+ if( pCsr->pStmt==0 ){
+ Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
+ int eStmt = fts5StmtType(pCsr);
+ rc = sqlite3Fts5StorageStmt(
+ pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->p.base.zErrMsg:0)
+ );
+ assert( rc!=SQLITE_OK || pTab->p.base.zErrMsg==0 );
+ assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
+ }
+
+ if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
+ Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
+ assert( pCsr->pExpr );
+ sqlite3_reset(pCsr->pStmt);
+ sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
+ pTab->pConfig->bLock++;
+ rc = sqlite3_step(pCsr->pStmt);
+ pTab->pConfig->bLock--;
+ if( rc==SQLITE_ROW ){
+ rc = SQLITE_OK;
+ CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
+ }else{
+ rc = sqlite3_reset(pCsr->pStmt);
+ if( rc==SQLITE_OK ){
+ rc = FTS5_CORRUPT;
+ }else if( pTab->pConfig->pzErrmsg ){
+ *pTab->pConfig->pzErrmsg = sqlite3_mprintf(
+ "%s", sqlite3_errmsg(pTab->pConfig->db)
+ );
+ }
+ }
+ }
+ return rc;
+}
+
+static void fts5SetVtabError(Fts5FullTable *p, const char *zFormat, ...){
+ va_list ap; /* ... printf arguments */
+ va_start(ap, zFormat);
+ assert( p->p.base.zErrMsg==0 );
+ p->p.base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
+ va_end(ap);
+}
+
+/*
+** This function is called to handle an FTS INSERT command. In other words,
+** an INSERT statement of the form:
+**
+** INSERT INTO fts(fts) VALUES($pCmd)
+** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
+**
+** Argument pVal is the value assigned to column "fts" by the INSERT
+** statement. This function returns SQLITE_OK if successful, or an SQLite
+** error code if an error occurs.
+**
+** The commands implemented by this function are documented in the "Special
+** INSERT Directives" section of the documentation. It should be updated if
+** more commands are added to this function.
+*/
+static int fts5SpecialInsert(
+ Fts5FullTable *pTab, /* Fts5 table object */
+ const char *zCmd, /* Text inserted into table-name column */
+ sqlite3_value *pVal /* Value inserted into rank column */
+){
+ Fts5Config *pConfig = pTab->p.pConfig;
+ int rc = SQLITE_OK;
+ int bError = 0;
+
+ if( 0==sqlite3_stricmp("delete-all", zCmd) ){
+ if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
+ fts5SetVtabError(pTab,
+ "'delete-all' may only be used with a "
+ "contentless or external content fts5 table"
+ );
+ rc = SQLITE_ERROR;
+ }else{
+ rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
+ }
+ }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
+ if( pConfig->eContent==FTS5_CONTENT_NONE ){
+ fts5SetVtabError(pTab,
+ "'rebuild' may not be used with a contentless fts5 table"
+ );
+ rc = SQLITE_ERROR;
+ }else{
+ rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
+ }
+ }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
+ rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
+ }else if( 0==sqlite3_stricmp("merge", zCmd) ){
+ int nMerge = sqlite3_value_int(pVal);
+ rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
+ }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
+ int iArg = sqlite3_value_int(pVal);
+ rc = sqlite3Fts5StorageIntegrity(pTab->pStorage, iArg);
+#ifdef SQLITE_DEBUG
+ }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
+ pConfig->bPrefixIndex = sqlite3_value_int(pVal);
+#endif
+ }else{
+ rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5ConfigSetValue(pTab->p.pConfig, zCmd, pVal, &bError);
+ }
+ if( rc==SQLITE_OK ){
+ if( bError ){
+ rc = SQLITE_ERROR;
+ }else{
+ rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
+ }
+ }
+ }
+ return rc;
+}
+
+static int fts5SpecialDelete(
+ Fts5FullTable *pTab,
+ sqlite3_value **apVal
+){
+ int rc = SQLITE_OK;
+ int eType1 = sqlite3_value_type(apVal[1]);
+ if( eType1==SQLITE_INTEGER ){
+ sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
+ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
+ }
+ return rc;
+}
+
+static void fts5StorageInsert(
+ int *pRc,
+ Fts5FullTable *pTab,
+ sqlite3_value **apVal,
+ i64 *piRowid
+){
+ int rc = *pRc;
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
+ }
+ *pRc = rc;
+}
+
+/*
+** This function is the implementation of the xUpdate callback used by
+** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
+** inserted, updated or deleted.
+**
+** A delete specifies a single argument - the rowid of the row to remove.
+**
+** Update and insert operations pass:
+**
+** 1. The "old" rowid, or NULL.
+** 2. The "new" rowid.
+** 3. Values for each of the nCol matchable columns.
+** 4. Values for the two hidden columns (<tablename> and "rank").
+*/
+static int fts5UpdateMethod(
+ sqlite3_vtab *pVtab, /* Virtual table handle */
+ int nArg, /* Size of argument array */
+ sqlite3_value **apVal, /* Array of arguments */
+ sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
+){
+ Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
+ Fts5Config *pConfig = pTab->p.pConfig;
+ int eType0; /* value_type() of apVal[0] */
+ int rc = SQLITE_OK; /* Return code */
+
+ /* A transaction must be open when this is called. */
+ assert( pTab->ts.eState==1 );
+
+ assert( pVtab->zErrMsg==0 );
+ assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
+ assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER
+ || sqlite3_value_type(apVal[0])==SQLITE_NULL
+ );
+ assert( pTab->p.pConfig->pzErrmsg==0 );
+ pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
+
+ /* Put any active cursors into REQUIRE_SEEK state. */
+ fts5TripCursors(pTab);
+
+ eType0 = sqlite3_value_type(apVal[0]);
+ if( eType0==SQLITE_NULL
+ && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
+ ){
+ /* A "special" INSERT op. These are handled separately. */
+ const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
+ if( pConfig->eContent!=FTS5_CONTENT_NORMAL
+ && 0==sqlite3_stricmp("delete", z)
+ ){
+ rc = fts5SpecialDelete(pTab, apVal);
+ }else{
+ rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
+ }
+ }else{
+ /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
+ ** any conflict on the rowid value must be detected before any
+ ** modifications are made to the database file. There are 4 cases:
+ **
+ ** 1) DELETE
+ ** 2) UPDATE (rowid not modified)
+ ** 3) UPDATE (rowid modified)
+ ** 4) INSERT
+ **
+ ** Cases 3 and 4 may violate the rowid constraint.
+ */
+ int eConflict = SQLITE_ABORT;
+ if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
+ eConflict = sqlite3_vtab_on_conflict(pConfig->db);
+ }
+
+ assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
+ assert( nArg!=1 || eType0==SQLITE_INTEGER );
+
+ /* Filter out attempts to run UPDATE or DELETE on contentless tables.
+ ** This is not suported. */
+ if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
+ pTab->p.base.zErrMsg = sqlite3_mprintf(
+ "cannot %s contentless fts5 table: %s",
+ (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
+ );
+ rc = SQLITE_ERROR;
+ }
+
+ /* DELETE */
+ else if( nArg==1 ){
+ i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
+ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
+ }
+
+ /* INSERT or UPDATE */
+ else{
+ int eType1 = sqlite3_value_numeric_type(apVal[1]);
+
+ if( eType1!=SQLITE_INTEGER && eType1!=SQLITE_NULL ){
+ rc = SQLITE_MISMATCH;
+ }
+
+ else if( eType0!=SQLITE_INTEGER ){
+ /* If this is a REPLACE, first remove the current entry (if any) */
+ if( eConflict==SQLITE_REPLACE && eType1==SQLITE_INTEGER ){
+ i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
+ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
+ }
+ fts5StorageInsert(&rc, pTab, apVal, pRowid);
+ }
+
+ /* UPDATE */
+ else{
+ i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
+ i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
+ if( eType1==SQLITE_INTEGER && iOld!=iNew ){
+ if( eConflict==SQLITE_REPLACE ){
+ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
+ }
+ fts5StorageInsert(&rc, pTab, apVal, pRowid);
+ }else{
+ rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal,*pRowid);
+ }
+ }
+ }else{
+ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
+ fts5StorageInsert(&rc, pTab, apVal, pRowid);
+ }
+ }
+ }
+ }
+
+ pTab->p.pConfig->pzErrmsg = 0;
+ return rc;
+}
+
+/*
+** Implementation of xSync() method.
+*/
+static int fts5SyncMethod(sqlite3_vtab *pVtab){
+ int rc;
+ Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
+ fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
+ pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
+ fts5TripCursors(pTab);
+ rc = sqlite3Fts5StorageSync(pTab->pStorage);
+ pTab->p.pConfig->pzErrmsg = 0;
+ return rc;
+}
+
+/*
+** Implementation of xBegin() method.
+*/
+static int fts5BeginMethod(sqlite3_vtab *pVtab){
+ fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_BEGIN, 0);
+ fts5NewTransaction((Fts5FullTable*)pVtab);
+ return SQLITE_OK;
+}
+
+/*
+** Implementation of xCommit() method. This is a no-op. The contents of
+** the pending-terms hash-table have already been flushed into the database
+** by fts5SyncMethod().
+*/
+static int fts5CommitMethod(sqlite3_vtab *pVtab){
+ UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
+ fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_COMMIT, 0);
+ return SQLITE_OK;
+}
+
+/*
+** Implementation of xRollback(). Discard the contents of the pending-terms
+** hash-table. Any changes made to the database are reverted by SQLite.
+*/
+static int fts5RollbackMethod(sqlite3_vtab *pVtab){
+ int rc;
+ Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
+ fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
+ rc = sqlite3Fts5StorageRollback(pTab->pStorage);
+ return rc;
+}
+
+static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
+
+static void *fts5ApiUserData(Fts5Context *pCtx){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ return pCsr->pAux->pUserData;
+}
+
+static int fts5ApiColumnCount(Fts5Context *pCtx){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
+}
+
+static int fts5ApiColumnTotalSize(
+ Fts5Context *pCtx,
+ int iCol,
+ sqlite3_int64 *pnToken
+){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
+ return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
+}
+
+static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
+ return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
+}
+
+static int fts5ApiTokenize(
+ Fts5Context *pCtx,
+ const char *pText, int nText,
+ void *pUserData,
+ int (*xToken)(void*, int, const char*, int, int, int)
+){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
+ return sqlite3Fts5Tokenize(
+ pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
+ );
+}
+
+static int fts5ApiPhraseCount(Fts5Context *pCtx){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
+}
+
+static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
+}
+
+static int fts5ApiColumnText(
+ Fts5Context *pCtx,
+ int iCol,
+ const char **pz,
+ int *pn
+){
+ int rc = SQLITE_OK;
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ if( fts5IsContentless((Fts5FullTable*)(pCsr->base.pVtab))
+ || pCsr->ePlan==FTS5_PLAN_SPECIAL
+ ){
+ *pz = 0;
+ *pn = 0;
+ }else{
+ rc = fts5SeekCursor(pCsr, 0);
+ if( rc==SQLITE_OK ){
+ *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
+ *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
+ }
+ }
+ return rc;
+}
+
+static int fts5CsrPoslist(
+ Fts5Cursor *pCsr,
+ int iPhrase,
+ const u8 **pa,
+ int *pn
+){
+ Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
+ int rc = SQLITE_OK;
+ int bLive = (pCsr->pSorter==0);
+
+ if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
+
+ if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
+ Fts5PoslistPopulator *aPopulator;
+ int i;
+ aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
+ if( aPopulator==0 ) rc = SQLITE_NOMEM;
+ for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
+ int n; const char *z;
+ rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5ExprPopulatePoslists(
+ pConfig, pCsr->pExpr, aPopulator, i, z, n
+ );
+ }
+ }
+ sqlite3_free(aPopulator);
+
+ if( pCsr->pSorter ){
+ sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
+ }
+ }
+ CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
+ }
+
+ if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
+ Fts5Sorter *pSorter = pCsr->pSorter;
+ int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
+ *pn = pSorter->aIdx[iPhrase] - i1;
+ *pa = &pSorter->aPoslist[i1];
+ }else{
+ *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
+ }
+
+ return rc;
+}
+
+/*
+** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
+** correctly for the current view. Return SQLITE_OK if successful, or an
+** SQLite error code otherwise.
+*/
+static int fts5CacheInstArray(Fts5Cursor *pCsr){
+ int rc = SQLITE_OK;
+ Fts5PoslistReader *aIter; /* One iterator for each phrase */
+ int nIter; /* Number of iterators/phrases */
+ int nCol = ((Fts5Table*)pCsr->base.pVtab)->pConfig->nCol;
+
+ nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
+ if( pCsr->aInstIter==0 ){
+ sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nIter;
+ pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
+ }
+ aIter = pCsr->aInstIter;
+
+ if( aIter ){
+ int nInst = 0; /* Number instances seen so far */
+ int i;
+
+ /* Initialize all iterators */
+ for(i=0; i<nIter && rc==SQLITE_OK; i++){
+ const u8 *a;
+ int n;
+ rc = fts5CsrPoslist(pCsr, i, &a, &n);
+ if( rc==SQLITE_OK ){
+ sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ while( 1 ){
+ int *aInst;
+ int iBest = -1;
+ for(i=0; i<nIter; i++){
+ if( (aIter[i].bEof==0)
+ && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
+ ){
+ iBest = i;
+ }
+ }
+ if( iBest<0 ) break;
+
+ nInst++;
+ if( nInst>=pCsr->nInstAlloc ){
+ pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
+ aInst = (int*)sqlite3_realloc64(
+ pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
+ );
+ if( aInst ){
+ pCsr->aInst = aInst;
+ }else{
+ rc = SQLITE_NOMEM;
+ break;
+ }
+ }
+
+ aInst = &pCsr->aInst[3 * (nInst-1)];
+ aInst[0] = iBest;
+ aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
+ aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
+ if( aInst[1]<0 || aInst[1]>=nCol ){
+ rc = FTS5_CORRUPT;
+ break;
+ }
+ sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
+ }
+ }
+
+ pCsr->nInstCount = nInst;
+ CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
+ }
+ return rc;
+}
+
+static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ int rc = SQLITE_OK;
+ if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
+ || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
+ *pnInst = pCsr->nInstCount;
+ }
+ return rc;
+}
+
+static int fts5ApiInst(
+ Fts5Context *pCtx,
+ int iIdx,
+ int *piPhrase,
+ int *piCol,
+ int *piOff
+){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ int rc = SQLITE_OK;
+ if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
+ || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
+ ){
+ if( iIdx<0 || iIdx>=pCsr->nInstCount ){
+ rc = SQLITE_RANGE;
+#if 0
+ }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
+ *piPhrase = pCsr->aInst[iIdx*3];
+ *piCol = pCsr->aInst[iIdx*3 + 2];
+ *piOff = -1;
+#endif
+ }else{
+ *piPhrase = pCsr->aInst[iIdx*3];
+ *piCol = pCsr->aInst[iIdx*3 + 1];
+ *piOff = pCsr->aInst[iIdx*3 + 2];
+ }
+ }
+ return rc;
+}
+
+static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
+ return fts5CursorRowid((Fts5Cursor*)pCtx);
+}
+
+static int fts5ColumnSizeCb(
+ void *pContext, /* Pointer to int */
+ int tflags,
+ const char *pUnused, /* Buffer containing token */
+ int nUnused, /* Size of token in bytes */
+ int iUnused1, /* Start offset of token */
+ int iUnused2 /* End offset of token */
+){
+ int *pCnt = (int*)pContext;
+ UNUSED_PARAM2(pUnused, nUnused);
+ UNUSED_PARAM2(iUnused1, iUnused2);
+ if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
+ (*pCnt)++;
+ }
+ return SQLITE_OK;
+}
+
+static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
+ Fts5Config *pConfig = pTab->p.pConfig;
+ int rc = SQLITE_OK;
+
+ if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
+ if( pConfig->bColumnsize ){
+ i64 iRowid = fts5CursorRowid(pCsr);
+ rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
+ }else if( pConfig->zContent==0 ){
+ int i;
+ for(i=0; i<pConfig->nCol; i++){
+ if( pConfig->abUnindexed[i]==0 ){
+ pCsr->aColumnSize[i] = -1;
+ }
+ }
+ }else{
+ int i;
+ for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
+ if( pConfig->abUnindexed[i]==0 ){
+ const char *z; int n;
+ void *p = (void*)(&pCsr->aColumnSize[i]);
+ pCsr->aColumnSize[i] = 0;
+ rc = fts5ApiColumnText(pCtx, i, &z, &n);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5Tokenize(
+ pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
+ );
+ }
+ }
+ }
+ }
+ CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
+ }
+ if( iCol<0 ){
+ int i;
+ *pnToken = 0;
+ for(i=0; i<pConfig->nCol; i++){
+ *pnToken += pCsr->aColumnSize[i];
+ }
+ }else if( iCol<pConfig->nCol ){
+ *pnToken = pCsr->aColumnSize[iCol];
+ }else{
+ *pnToken = 0;
+ rc = SQLITE_RANGE;
+ }
+ return rc;
+}
+
+/*
+** Implementation of the xSetAuxdata() method.
+*/
+static int fts5ApiSetAuxdata(
+ Fts5Context *pCtx, /* Fts5 context */
+ void *pPtr, /* Pointer to save as auxdata */
+ void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
+){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ Fts5Auxdata *pData;
+
+ /* Search through the cursors list of Fts5Auxdata objects for one that
+ ** corresponds to the currently executing auxiliary function. */
+ for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
+ if( pData->pAux==pCsr->pAux ) break;
+ }
+
+ if( pData ){
+ if( pData->xDelete ){
+ pData->xDelete(pData->pPtr);
+ }
+ }else{
+ int rc = SQLITE_OK;
+ pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
+ if( pData==0 ){
+ if( xDelete ) xDelete(pPtr);
+ return rc;
+ }
+ pData->pAux = pCsr->pAux;
+ pData->pNext = pCsr->pAuxdata;
+ pCsr->pAuxdata = pData;
+ }
+
+ pData->xDelete = xDelete;
+ pData->pPtr = pPtr;
+ return SQLITE_OK;
+}
+
+static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ Fts5Auxdata *pData;
+ void *pRet = 0;
+
+ for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
+ if( pData->pAux==pCsr->pAux ) break;
+ }
+
+ if( pData ){
+ pRet = pData->pPtr;
+ if( bClear ){
+ pData->pPtr = 0;
+ pData->xDelete = 0;
+ }
+ }
+
+ return pRet;
+}
+
+static void fts5ApiPhraseNext(
+ Fts5Context *pUnused,
+ Fts5PhraseIter *pIter,
+ int *piCol, int *piOff
+){
+ UNUSED_PARAM(pUnused);
+ if( pIter->a>=pIter->b ){
+ *piCol = -1;
+ *piOff = -1;
+ }else{
+ int iVal;
+ pIter->a += fts5GetVarint32(pIter->a, iVal);
+ if( iVal==1 ){
+ pIter->a += fts5GetVarint32(pIter->a, iVal);
+ *piCol = iVal;
+ *piOff = 0;
+ pIter->a += fts5GetVarint32(pIter->a, iVal);
+ }
+ *piOff += (iVal-2);
+ }
+}
+
+static int fts5ApiPhraseFirst(
+ Fts5Context *pCtx,
+ int iPhrase,
+ Fts5PhraseIter *pIter,
+ int *piCol, int *piOff
+){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ int n;
+ int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
+ if( rc==SQLITE_OK ){
+ pIter->b = &pIter->a[n];
+ *piCol = 0;
+ *piOff = 0;
+ fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
+ }
+ return rc;
+}
+
+static void fts5ApiPhraseNextColumn(
+ Fts5Context *pCtx,
+ Fts5PhraseIter *pIter,
+ int *piCol
+){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
+
+ if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
+ if( pIter->a>=pIter->b ){
+ *piCol = -1;
+ }else{
+ int iIncr;
+ pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
+ *piCol += (iIncr-2);
+ }
+ }else{
+ while( 1 ){
+ int dummy;
+ if( pIter->a>=pIter->b ){
+ *piCol = -1;
+ return;
+ }
+ if( pIter->a[0]==0x01 ) break;
+ pIter->a += fts5GetVarint32(pIter->a, dummy);
+ }
+ pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
+ }
+}
+
+static int fts5ApiPhraseFirstColumn(
+ Fts5Context *pCtx,
+ int iPhrase,
+ Fts5PhraseIter *pIter,
+ int *piCol
+){
+ int rc = SQLITE_OK;
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
+
+ if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
+ Fts5Sorter *pSorter = pCsr->pSorter;
+ int n;
+ if( pSorter ){
+ int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
+ n = pSorter->aIdx[iPhrase] - i1;
+ pIter->a = &pSorter->aPoslist[i1];
+ }else{
+ rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
+ }
+ if( rc==SQLITE_OK ){
+ pIter->b = &pIter->a[n];
+ *piCol = 0;
+ fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
+ }
+ }else{
+ int n;
+ rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
+ if( rc==SQLITE_OK ){
+ pIter->b = &pIter->a[n];
+ if( n<=0 ){
+ *piCol = -1;
+ }else if( pIter->a[0]==0x01 ){
+ pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
+ }else{
+ *piCol = 0;
+ }
+ }
+ }
+
+ return rc;
+}
+
+
+static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
+ int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
+);
+
+static const Fts5ExtensionApi sFts5Api = {
+ 2, /* iVersion */
+ fts5ApiUserData,
+ fts5ApiColumnCount,
+ fts5ApiRowCount,
+ fts5ApiColumnTotalSize,
+ fts5ApiTokenize,
+ fts5ApiPhraseCount,
+ fts5ApiPhraseSize,
+ fts5ApiInstCount,
+ fts5ApiInst,
+ fts5ApiRowid,
+ fts5ApiColumnText,
+ fts5ApiColumnSize,
+ fts5ApiQueryPhrase,
+ fts5ApiSetAuxdata,
+ fts5ApiGetAuxdata,
+ fts5ApiPhraseFirst,
+ fts5ApiPhraseNext,
+ fts5ApiPhraseFirstColumn,
+ fts5ApiPhraseNextColumn,
+};
+
+/*
+** Implementation of API function xQueryPhrase().
+*/
+static int fts5ApiQueryPhrase(
+ Fts5Context *pCtx,
+ int iPhrase,
+ void *pUserData,
+ int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
+){
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
+ Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
+ int rc;
+ Fts5Cursor *pNew = 0;
+
+ rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
+ if( rc==SQLITE_OK ){
+ pNew->ePlan = FTS5_PLAN_MATCH;
+ pNew->iFirstRowid = SMALLEST_INT64;
+ pNew->iLastRowid = LARGEST_INT64;
+ pNew->base.pVtab = (sqlite3_vtab*)pTab;
+ rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
+ }
+
+ if( rc==SQLITE_OK ){
+ for(rc = fts5CursorFirst(pTab, pNew, 0);
+ rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
+ rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
+ ){
+ rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
+ if( rc!=SQLITE_OK ){
+ if( rc==SQLITE_DONE ) rc = SQLITE_OK;
+ break;
+ }
+ }
+ }
+
+ fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
+ return rc;
+}
+
+static void fts5ApiInvoke(
+ Fts5Auxiliary *pAux,
+ Fts5Cursor *pCsr,
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+ assert( pCsr->pAux==0 );
+ pCsr->pAux = pAux;
+ pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
+ pCsr->pAux = 0;
+}
+
+static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
+ Fts5Cursor *pCsr;
+ for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
+ if( pCsr->iCsrId==iCsrId ) break;
+ }
+ return pCsr;
+}
+
+static void fts5ApiCallback(
+ sqlite3_context *context,
+ int argc,
+ sqlite3_value **argv
+){
+
+ Fts5Auxiliary *pAux;
+ Fts5Cursor *pCsr;
+ i64 iCsrId;
+
+ assert( argc>=1 );
+ pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
+ iCsrId = sqlite3_value_int64(argv[0]);
+
+ pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
+ if( pCsr==0 || pCsr->ePlan==0 ){
+ char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
+ sqlite3_result_error(context, zErr, -1);
+ sqlite3_free(zErr);
+ }else{
+ fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
+ }
+}
+
+
+/*
+** Given cursor id iId, return a pointer to the corresponding Fts5Table
+** object. Or NULL If the cursor id does not exist.
+*/
+static Fts5Table *sqlite3Fts5TableFromCsrid(
+ Fts5Global *pGlobal, /* FTS5 global context for db handle */
+ i64 iCsrId /* Id of cursor to find */
+){
+ Fts5Cursor *pCsr;
+ pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
+ if( pCsr ){
+ return (Fts5Table*)pCsr->base.pVtab;
+ }
+ return 0;
+}
+
+/*
+** Return a "position-list blob" corresponding to the current position of
+** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
+** the current position-list for each phrase in the query associated with
+** cursor pCsr.
+**
+** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
+** the number of phrases in the query. Following the varints are the
+** concatenated position lists for each phrase, in order.
+**
+** The first varint (if it exists) contains the size of the position list
+** for phrase 0. The second (same disclaimer) contains the size of position
+** list 1. And so on. There is no size field for the final position list,
+** as it can be derived from the total size of the blob.
+*/
+static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
+ int i;
+ int rc = SQLITE_OK;
+ int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
+ Fts5Buffer val;
+
+ memset(&val, 0, sizeof(Fts5Buffer));
+ switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
+ case FTS5_DETAIL_FULL:
+
+ /* Append the varints */
+ for(i=0; i<(nPhrase-1); i++){
+ const u8 *dummy;
+ int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
+ sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
+ }
+
+ /* Append the position lists */
+ for(i=0; i<nPhrase; i++){
+ const u8 *pPoslist;
+ int nPoslist;
+ nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
+ sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
+ }
+ break;
+
+ case FTS5_DETAIL_COLUMNS:
+
+ /* Append the varints */
+ for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
+ const u8 *dummy;
+ int nByte;
+ rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
+ sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
+ }
+
+ /* Append the position lists */
+ for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
+ const u8 *pPoslist;
+ int nPoslist;
+ rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
+ sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
+ return rc;
+}
+
+/*
+** This is the xColumn method, called by SQLite to request a value from
+** the row that the supplied cursor currently points to.
+*/
+static int fts5ColumnMethod(
+ sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
+ sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
+ int iCol /* Index of column to read value from */
+){
+ Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
+ Fts5Config *pConfig = pTab->p.pConfig;
+ Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
+ int rc = SQLITE_OK;
+
+ assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
+
+ if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
+ if( iCol==pConfig->nCol ){
+ sqlite3_result_int64(pCtx, pCsr->iSpecial);
+ }
+ }else
+
+ if( iCol==pConfig->nCol ){
+ /* User is requesting the value of the special column with the same name
+ ** as the table. Return the cursor integer id number. This value is only
+ ** useful in that it may be passed as the first argument to an FTS5
+ ** auxiliary function. */
+ sqlite3_result_int64(pCtx, pCsr->iCsrId);
+ }else if( iCol==pConfig->nCol+1 ){
+
+ /* The value of the "rank" column. */
+ if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
+ fts5PoslistBlob(pCtx, pCsr);
+ }else if(
+ pCsr->ePlan==FTS5_PLAN_MATCH
+ || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
+ ){
+ if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
+ fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
+ }
+ }
+ }else if( !fts5IsContentless(pTab) ){
+ pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
+ rc = fts5SeekCursor(pCsr, 1);
+ if( rc==SQLITE_OK ){
+ sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
+ }
+ pConfig->pzErrmsg = 0;
+ }
+ return rc;
+}
+
+
+/*
+** This routine implements the xFindFunction method for the FTS3
+** virtual table.
+*/
+static int fts5FindFunctionMethod(
+ sqlite3_vtab *pVtab, /* Virtual table handle */
+ int nUnused, /* Number of SQL function arguments */
+ const char *zName, /* Name of SQL function */
+ void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
+ void **ppArg /* OUT: User data for *pxFunc */
+){
+ Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
+ Fts5Auxiliary *pAux;
+
+ UNUSED_PARAM(nUnused);
+ pAux = fts5FindAuxiliary(pTab, zName);
+ if( pAux ){
+ *pxFunc = fts5ApiCallback;
+ *ppArg = (void*)pAux;
+ return 1;
+ }
+
+ /* No function of the specified name was found. Return 0. */
+ return 0;
+}
+
+/*
+** Implementation of FTS5 xRename method. Rename an fts5 table.
+*/
+static int fts5RenameMethod(
+ sqlite3_vtab *pVtab, /* Virtual table handle */
+ const char *zName /* New name of table */
+){
+ Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
+ return sqlite3Fts5StorageRename(pTab->pStorage, zName);
+}
+
+static int sqlite3Fts5FlushToDisk(Fts5Table *pTab){
+ fts5TripCursors((Fts5FullTable*)pTab);
+ return sqlite3Fts5StorageSync(((Fts5FullTable*)pTab)->pStorage);
+}
+
+/*
+** The xSavepoint() method.
+**
+** Flush the contents of the pending-terms table to disk.
+*/
+static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
+ UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
+ fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_SAVEPOINT, iSavepoint);
+ return sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);
+}
+
+/*
+** The xRelease() method.
+**
+** This is a no-op.
+*/
+static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
+ UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
+ fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_RELEASE, iSavepoint);
+ return sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);
+}
+
+/*
+** The xRollbackTo() method.
+**
+** Discard the contents of the pending terms table.
+*/
+static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
+ Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
+ UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
+ fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
+ fts5TripCursors(pTab);
+ return sqlite3Fts5StorageRollback(pTab->pStorage);
+}
+
+/*
+** Register a new auxiliary function with global context pGlobal.
+*/
+static int fts5CreateAux(
+ fts5_api *pApi, /* Global context (one per db handle) */
+ const char *zName, /* Name of new function */
+ void *pUserData, /* User data for aux. function */
+ fts5_extension_function xFunc, /* Aux. function implementation */
+ void(*xDestroy)(void*) /* Destructor for pUserData */
+){
+ Fts5Global *pGlobal = (Fts5Global*)pApi;
+ int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
+ if( rc==SQLITE_OK ){
+ Fts5Auxiliary *pAux;
+ sqlite3_int64 nName; /* Size of zName in bytes, including \0 */
+ sqlite3_int64 nByte; /* Bytes of space to allocate */
+
+ nName = strlen(zName) + 1;
+ nByte = sizeof(Fts5Auxiliary) + nName;
+ pAux = (Fts5Auxiliary*)sqlite3_malloc64(nByte);
+ if( pAux ){
+ memset(pAux, 0, (size_t)nByte);
+ pAux->zFunc = (char*)&pAux[1];
+ memcpy(pAux->zFunc, zName, nName);
+ pAux->pGlobal = pGlobal;
+ pAux->pUserData = pUserData;
+ pAux->xFunc = xFunc;
+ pAux->xDestroy = xDestroy;
+ pAux->pNext = pGlobal->pAux;
+ pGlobal->pAux = pAux;
+ }else{
+ rc = SQLITE_NOMEM;
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Register a new tokenizer. This is the implementation of the
+** fts5_api.xCreateTokenizer() method.
+*/
+static int fts5CreateTokenizer(
+ fts5_api *pApi, /* Global context (one per db handle) */
+ const char *zName, /* Name of new function */
+ void *pUserData, /* User data for aux. function */
+ fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
+ void(*xDestroy)(void*) /* Destructor for pUserData */
+){
+ Fts5Global *pGlobal = (Fts5Global*)pApi;
+ Fts5TokenizerModule *pNew;
+ sqlite3_int64 nName; /* Size of zName and its \0 terminator */
+ sqlite3_int64 nByte; /* Bytes of space to allocate */
+ int rc = SQLITE_OK;
+
+ nName = strlen(zName) + 1;
+ nByte = sizeof(Fts5TokenizerModule) + nName;
+ pNew = (Fts5TokenizerModule*)sqlite3_malloc64(nByte);
+ if( pNew ){
+ memset(pNew, 0, (size_t)nByte);
+ pNew->zName = (char*)&pNew[1];
+ memcpy(pNew->zName, zName, nName);
+ pNew->pUserData = pUserData;
+ pNew->x = *pTokenizer;
+ pNew->xDestroy = xDestroy;
+ pNew->pNext = pGlobal->pTok;
+ pGlobal->pTok = pNew;
+ if( pNew->pNext==0 ){
+ pGlobal->pDfltTok = pNew;
+ }
+ }else{
+ rc = SQLITE_NOMEM;
+ }
+
+ return rc;
+}
+
+static Fts5TokenizerModule *fts5LocateTokenizer(
+ Fts5Global *pGlobal,
+ const char *zName
+){
+ Fts5TokenizerModule *pMod = 0;
+
+ if( zName==0 ){
+ pMod = pGlobal->pDfltTok;
+ }else{
+ for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
+ if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
+ }
+ }
+
+ return pMod;
+}
+
+/*
+** Find a tokenizer. This is the implementation of the
+** fts5_api.xFindTokenizer() method.
+*/
+static int fts5FindTokenizer(
+ fts5_api *pApi, /* Global context (one per db handle) */
+ const char *zName, /* Name of new function */
+ void **ppUserData,
+ fts5_tokenizer *pTokenizer /* Populate this object */
+){
+ int rc = SQLITE_OK;
+ Fts5TokenizerModule *pMod;
+
+ pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
+ if( pMod ){
+ *pTokenizer = pMod->x;
+ *ppUserData = pMod->pUserData;
+ }else{
+ memset(pTokenizer, 0, sizeof(fts5_tokenizer));
+ rc = SQLITE_ERROR;
+ }
+
+ return rc;
+}
+
+static int sqlite3Fts5GetTokenizer(
+ Fts5Global *pGlobal,
+ const char **azArg,
+ int nArg,
+ Fts5Config *pConfig,
+ char **pzErr
+){
+ Fts5TokenizerModule *pMod;
+ int rc = SQLITE_OK;
+
+ pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
+ if( pMod==0 ){
+ assert( nArg>0 );
+ rc = SQLITE_ERROR;
+ *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
+ }else{
+ rc = pMod->x.xCreate(
+ pMod->pUserData, &azArg[1], (nArg?nArg-1:0), &pConfig->pTok
+ );
+ pConfig->pTokApi = &pMod->x;
+ if( rc!=SQLITE_OK ){
+ if( pzErr ) *pzErr = sqlite3_mprintf("error in tokenizer constructor");
+ }else{
+ pConfig->ePattern = sqlite3Fts5TokenizerPattern(
+ pMod->x.xCreate, pConfig->pTok
+ );
+ }
+ }
+
+ if( rc!=SQLITE_OK ){
+ pConfig->pTokApi = 0;
+ pConfig->pTok = 0;
+ }
+
+ return rc;
+}
+
+static void fts5ModuleDestroy(void *pCtx){
+ Fts5TokenizerModule *pTok, *pNextTok;
+ Fts5Auxiliary *pAux, *pNextAux;
+ Fts5Global *pGlobal = (Fts5Global*)pCtx;
+
+ for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
+ pNextAux = pAux->pNext;
+ if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
+ sqlite3_free(pAux);
+ }
+
+ for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
+ pNextTok = pTok->pNext;
+ if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
+ sqlite3_free(pTok);
+ }
+
+ sqlite3_free(pGlobal);
+}
+
+static void fts5Fts5Func(
+ sqlite3_context *pCtx, /* Function call context */
+ int nArg, /* Number of args */
+ sqlite3_value **apArg /* Function arguments */
+){
+ Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
+ fts5_api **ppApi;
+ UNUSED_PARAM(nArg);
+ assert( nArg==1 );
+ ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
+ if( ppApi ) *ppApi = &pGlobal->api;
+}
+
+/*
+** Implementation of fts5_source_id() function.
+*/
+static void fts5SourceIdFunc(
+ sqlite3_context *pCtx, /* Function call context */
+ int nArg, /* Number of args */
+ sqlite3_value **apUnused /* Function arguments */
+){
+ assert( nArg==0 );
+ UNUSED_PARAM2(nArg, apUnused);
+ sqlite3_result_text(pCtx, "fts5: 2020-10-02 13:48:57 ad5ab24ebd557e7af1d92ab3fbcb3747c04da5ad4ed779fb6391dc94042687dd", -1, SQLITE_TRANSIENT);
+}
+
+/*
+** Return true if zName is the extension on one of the shadow tables used
+** by this module.
+*/
+static int fts5ShadowName(const char *zName){
+ static const char *azName[] = {
+ "config", "content", "data", "docsize", "idx"
+ };
+ unsigned int i;
+ for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
+ if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
+ }
+ return 0;
+}
+
+static int fts5Init(sqlite3 *db){
+ static const sqlite3_module fts5Mod = {
+ /* iVersion */ 3,
+ /* xCreate */ fts5CreateMethod,
+ /* xConnect */ fts5ConnectMethod,
+ /* xBestIndex */ fts5BestIndexMethod,
+ /* xDisconnect */ fts5DisconnectMethod,
+ /* xDestroy */ fts5DestroyMethod,
+ /* xOpen */ fts5OpenMethod,
+ /* xClose */ fts5CloseMethod,
+ /* xFilter */ fts5FilterMethod,
+ /* xNext */ fts5NextMethod,
+ /* xEof */ fts5EofMethod,
+ /* xColumn */ fts5ColumnMethod,
+ /* xRowid */ fts5RowidMethod,
+ /* xUpdate */ fts5UpdateMethod,
+ /* xBegin */ fts5BeginMethod,
+ /* xSync */ fts5SyncMethod,
+ /* xCommit */ fts5CommitMethod,
+ /* xRollback */ fts5RollbackMethod,
+ /* xFindFunction */ fts5FindFunctionMethod,
+ /* xRename */ fts5RenameMethod,
+ /* xSavepoint */ fts5SavepointMethod,
+ /* xRelease */ fts5ReleaseMethod,
+ /* xRollbackTo */ fts5RollbackToMethod,
+ /* xShadowName */ fts5ShadowName
+ };
+
+ int rc;
+ Fts5Global *pGlobal = 0;
+
+ pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
+ if( pGlobal==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ void *p = (void*)pGlobal;
+ memset(pGlobal, 0, sizeof(Fts5Global));
+ pGlobal->db = db;
+ pGlobal->api.iVersion = 2;
+ pGlobal->api.xCreateFunction = fts5CreateAux;
+ pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
+ pGlobal->api.xFindTokenizer = fts5FindTokenizer;
+ rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
+ if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
+ if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
+ if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
+ if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
+ if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_create_function(
+ db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
+ );
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3_create_function(
+ db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
+ );
+ }
+ }
+
+ /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
+ ** fts5_test_mi.c is compiled and linked into the executable. And call
+ ** its entry point to enable the matchinfo() demo. */
+#ifdef SQLITE_FTS5_ENABLE_TEST_MI
+ if( rc==SQLITE_OK ){
+ extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
+ rc = sqlite3Fts5TestRegisterMatchinfo(db);
+ }
+#endif
+
+ return rc;
+}
+
+/*
+** The following functions are used to register the module with SQLite. If
+** this module is being built as part of the SQLite core (SQLITE_CORE is
+** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
+**
+** Or, if this module is being built as a loadable extension,
+** sqlite3Fts5Init() is omitted and the two standard entry points
+** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
+*/
+#ifndef SQLITE_CORE
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+SQLITE_API int sqlite3_fts_init(
+ sqlite3 *db,
+ char **pzErrMsg,
+ const sqlite3_api_routines *pApi
+){
+ SQLITE_EXTENSION_INIT2(pApi);
+ (void)pzErrMsg; /* Unused parameter */
+ return fts5Init(db);
+}
+
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+SQLITE_API int sqlite3_fts5_init(
+ sqlite3 *db,
+ char **pzErrMsg,
+ const sqlite3_api_routines *pApi
+){
+ SQLITE_EXTENSION_INIT2(pApi);
+ (void)pzErrMsg; /* Unused parameter */
+ return fts5Init(db);
+}
+#else
+SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
+ return fts5Init(db);
+}
+#endif
+
+/*
+** 2014 May 31
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+*/
+
+
+
+/* #include "fts5Int.h" */
+
+struct Fts5Storage {
+ Fts5Config *pConfig;
+ Fts5Index *pIndex;
+ int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
+ i64 nTotalRow; /* Total number of rows in FTS table */
+ i64 *aTotalSize; /* Total sizes of each column */
+ sqlite3_stmt *aStmt[11];
+};
+
+
+#if FTS5_STMT_SCAN_ASC!=0
+# error "FTS5_STMT_SCAN_ASC mismatch"
+#endif
+#if FTS5_STMT_SCAN_DESC!=1
+# error "FTS5_STMT_SCAN_DESC mismatch"
+#endif
+#if FTS5_STMT_LOOKUP!=2
+# error "FTS5_STMT_LOOKUP mismatch"
+#endif
+
+#define FTS5_STMT_INSERT_CONTENT 3
+#define FTS5_STMT_REPLACE_CONTENT 4
+#define FTS5_STMT_DELETE_CONTENT 5
+#define FTS5_STMT_REPLACE_DOCSIZE 6
+#define FTS5_STMT_DELETE_DOCSIZE 7
+#define FTS5_STMT_LOOKUP_DOCSIZE 8
+#define FTS5_STMT_REPLACE_CONFIG 9
+#define FTS5_STMT_SCAN 10
+
+/*
+** Prepare the two insert statements - Fts5Storage.pInsertContent and
+** Fts5Storage.pInsertDocsize - if they have not already been prepared.
+** Return SQLITE_OK if successful, or an SQLite error code if an error
+** occurs.
+*/
+static int fts5StorageGetStmt(
+ Fts5Storage *p, /* Storage handle */
+ int eStmt, /* FTS5_STMT_XXX constant */
+ sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
+ char **pzErrMsg /* OUT: Error message (if any) */
+){
+ int rc = SQLITE_OK;
+
+ /* If there is no %_docsize table, there should be no requests for
+ ** statements to operate on it. */
+ assert( p->pConfig->bColumnsize || (
+ eStmt!=FTS5_STMT_REPLACE_DOCSIZE
+ && eStmt!=FTS5_STMT_DELETE_DOCSIZE
+ && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
+ ));
+
+ assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
+ if( p->aStmt[eStmt]==0 ){
+ const char *azStmt[] = {
+ "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
+ "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
+ "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
+
+ "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
+ "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
+ "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
+ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
+ "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
+
+ "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
+
+ "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
+ "SELECT %s FROM %s AS T", /* SCAN */
+ };
+ Fts5Config *pC = p->pConfig;
+ char *zSql = 0;
+
+ switch( eStmt ){
+ case FTS5_STMT_SCAN:
+ zSql = sqlite3_mprintf(azStmt[eStmt],
+ pC->zContentExprlist, pC->zContent
+ );
+ break;
+
+ case FTS5_STMT_SCAN_ASC:
+ case FTS5_STMT_SCAN_DESC:
+ zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
+ pC->zContent, pC->zContentRowid, pC->zContentRowid,
+ pC->zContentRowid
+ );
+ break;
+
+ case FTS5_STMT_LOOKUP:
+ zSql = sqlite3_mprintf(azStmt[eStmt],
+ pC->zContentExprlist, pC->zContent, pC->zContentRowid
+ );
+ break;
+
+ case FTS5_STMT_INSERT_CONTENT:
+ case FTS5_STMT_REPLACE_CONTENT: {
+ int nCol = pC->nCol + 1;
+ char *zBind;
+ int i;
+
+ zBind = sqlite3_malloc64(1 + nCol*2);
+ if( zBind ){
+ for(i=0; i<nCol; i++){
+ zBind[i*2] = '?';
+ zBind[i*2 + 1] = ',';
+ }
+ zBind[i*2-1] = '\0';
+ zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
+ sqlite3_free(zBind);
+ }
+ break;
+ }
+
+ default:
+ zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
+ break;
+ }
+
+ if( zSql==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ int f = SQLITE_PREPARE_PERSISTENT;
+ if( eStmt>FTS5_STMT_LOOKUP ) f |= SQLITE_PREPARE_NO_VTAB;
+ p->pConfig->bLock++;
+ rc = sqlite3_prepare_v3(pC->db, zSql, -1, f, &p->aStmt[eStmt], 0);
+ p->pConfig->bLock--;
+ sqlite3_free(zSql);
+ if( rc!=SQLITE_OK && pzErrMsg ){
+ *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
+ }
+ }
+ }
+
+ *ppStmt = p->aStmt[eStmt];
+ sqlite3_reset(*ppStmt);
+ return rc;
+}
+
+
+static int fts5ExecPrintf(
+ sqlite3 *db,
+ char **pzErr,
+ const char *zFormat,
+ ...
+){
+ int rc;
+ va_list ap; /* ... printf arguments */
+ char *zSql;
+
+ va_start(ap, zFormat);
+ zSql = sqlite3_vmprintf(zFormat, ap);
+
+ if( zSql==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
+ sqlite3_free(zSql);
+ }
+
+ va_end(ap);
+ return rc;
+}
+
+/*
+** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
+** code otherwise.
+*/
+static int sqlite3Fts5DropAll(Fts5Config *pConfig){
+ int rc = fts5ExecPrintf(pConfig->db, 0,
+ "DROP TABLE IF EXISTS %Q.'%q_data';"
+ "DROP TABLE IF EXISTS %Q.'%q_idx';"
+ "DROP TABLE IF EXISTS %Q.'%q_config';",
+ pConfig->zDb, pConfig->zName,
+ pConfig->zDb, pConfig->zName,
+ pConfig->zDb, pConfig->zName
+ );
+ if( rc==SQLITE_OK && pConfig->bColumnsize ){
+ rc = fts5ExecPrintf(pConfig->db, 0,
+ "DROP TABLE IF EXISTS %Q.'%q_docsize';",
+ pConfig->zDb, pConfig->zName
+ );
+ }
+ if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
+ rc = fts5ExecPrintf(pConfig->db, 0,
+ "DROP TABLE IF EXISTS %Q.'%q_content';",
+ pConfig->zDb, pConfig->zName
+ );
+ }
+ return rc;
+}
+
+static void fts5StorageRenameOne(
+ Fts5Config *pConfig, /* Current FTS5 configuration */
+ int *pRc, /* IN/OUT: Error code */
+ const char *zTail, /* Tail of table name e.g. "data", "config" */
+ const char *zName /* New name of FTS5 table */
+){
+ if( *pRc==SQLITE_OK ){
+ *pRc = fts5ExecPrintf(pConfig->db, 0,
+ "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
+ pConfig->zDb, pConfig->zName, zTail, zName, zTail
+ );
+ }
+}
+
+static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
+ Fts5Config *pConfig = pStorage->pConfig;
+ int rc = sqlite3Fts5StorageSync(pStorage);
+
+ fts5StorageRenameOne(pConfig, &rc, "data", zName);
+ fts5StorageRenameOne(pConfig, &rc, "idx", zName);
+ fts5StorageRenameOne(pConfig, &rc, "config", zName);
+ if( pConfig->bColumnsize ){
+ fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
+ }
+ if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
+ fts5StorageRenameOne(pConfig, &rc, "content", zName);
+ }
+ return rc;
+}
+
+/*
+** Create the shadow table named zPost, with definition zDefn. Return
+** SQLITE_OK if successful, or an SQLite error code otherwise.
+*/
+static int sqlite3Fts5CreateTable(
+ Fts5Config *pConfig, /* FTS5 configuration */
+ const char *zPost, /* Shadow table to create (e.g. "content") */
+ const char *zDefn, /* Columns etc. for shadow table */
+ int bWithout, /* True for without rowid */
+ char **pzErr /* OUT: Error message */
+){
+ int rc;
+ char *zErr = 0;
+
+ rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
+ pConfig->zDb, pConfig->zName, zPost, zDefn,
+#ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
+ bWithout?" WITHOUT ROWID":
+#endif
+ ""
+ );
+ if( zErr ){
+ *pzErr = sqlite3_mprintf(
+ "fts5: error creating shadow table %q_%s: %s",
+ pConfig->zName, zPost, zErr
+ );
+ sqlite3_free(zErr);
+ }
+
+ return rc;
+}
+
+/*
+** Open a new Fts5Index handle. If the bCreate argument is true, create
+** and initialize the underlying tables
+**
+** If successful, set *pp to point to the new object and return SQLITE_OK.
+** Otherwise, set *pp to NULL and return an SQLite error code.
+*/
+static int sqlite3Fts5StorageOpen(
+ Fts5Config *pConfig,
+ Fts5Index *pIndex,
+ int bCreate,
+ Fts5Storage **pp,
+ char **pzErr /* OUT: Error message */
+){
+ int rc = SQLITE_OK;
+ Fts5Storage *p; /* New object */
+ sqlite3_int64 nByte; /* Bytes of space to allocate */
+
+ nByte = sizeof(Fts5Storage) /* Fts5Storage object */
+ + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
+ *pp = p = (Fts5Storage*)sqlite3_malloc64(nByte);
+ if( !p ) return SQLITE_NOMEM;
+
+ memset(p, 0, (size_t)nByte);
+ p->aTotalSize = (i64*)&p[1];
+ p->pConfig = pConfig;
+ p->pIndex = pIndex;
+
+ if( bCreate ){
+ if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
+ int nDefn = 32 + pConfig->nCol*10;
+ char *zDefn = sqlite3_malloc64(32 + (sqlite3_int64)pConfig->nCol * 10);
+ if( zDefn==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ int i;
+ int iOff;
+ sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
+ iOff = (int)strlen(zDefn);
+ for(i=0; i<pConfig->nCol; i++){
+ sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
+ iOff += (int)strlen(&zDefn[iOff]);
+ }
+ rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
+ }
+ sqlite3_free(zDefn);
+ }
+
+ if( rc==SQLITE_OK && pConfig->bColumnsize ){
+ rc = sqlite3Fts5CreateTable(
+ pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
+ );
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5CreateTable(
+ pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
+ );
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
+ }
+ }
+
+ if( rc ){
+ sqlite3Fts5StorageClose(p);
+ *pp = 0;
+ }
+ return rc;
+}
+
+/*
+** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
+*/
+static int sqlite3Fts5StorageClose(Fts5Storage *p){
+ int rc = SQLITE_OK;
+ if( p ){
+ int i;
+
+ /* Finalize all SQL statements */
+ for(i=0; i<ArraySize(p->aStmt); i++){
+ sqlite3_finalize(p->aStmt[i]);
+ }
+
+ sqlite3_free(p);
+ }
+ return rc;
+}
+
+typedef struct Fts5InsertCtx Fts5InsertCtx;
+struct Fts5InsertCtx {
+ Fts5Storage *pStorage;
+ int iCol;
+ int szCol; /* Size of column value in tokens */
+};
+
+/*
+** Tokenization callback used when inserting tokens into the FTS index.
+*/
+static int fts5StorageInsertCallback(
+ void *pContext, /* Pointer to Fts5InsertCtx object */
+ int tflags,
+ const char *pToken, /* Buffer containing token */
+ int nToken, /* Size of token in bytes */
+ int iUnused1, /* Start offset of token */
+ int iUnused2 /* End offset of token */
+){
+ Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
+ Fts5Index *pIdx = pCtx->pStorage->pIndex;
+ UNUSED_PARAM2(iUnused1, iUnused2);
+ if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
+ if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
+ pCtx->szCol++;
+ }
+ return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
+}
+
+/*
+** If a row with rowid iDel is present in the %_content table, add the
+** delete-markers to the FTS index necessary to delete it. Do not actually
+** remove the %_content row at this time though.
+*/
+static int fts5StorageDeleteFromIndex(
+ Fts5Storage *p,
+ i64 iDel,
+ sqlite3_value **apVal
+){
+ Fts5Config *pConfig = p->pConfig;
+ sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
+ int rc; /* Return code */
+ int rc2; /* sqlite3_reset() return code */
+ int iCol;
+ Fts5InsertCtx ctx;
+
+ if( apVal==0 ){
+ rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
+ if( rc!=SQLITE_OK ) return rc;
+ sqlite3_bind_int64(pSeek, 1, iDel);
+ if( sqlite3_step(pSeek)!=SQLITE_ROW ){
+ return sqlite3_reset(pSeek);
+ }
+ }
+
+ ctx.pStorage = p;
+ ctx.iCol = -1;
+ rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
+ for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
+ if( pConfig->abUnindexed[iCol-1]==0 ){
+ const char *zText;
+ int nText;
+ if( pSeek ){
+ zText = (const char*)sqlite3_column_text(pSeek, iCol);
+ nText = sqlite3_column_bytes(pSeek, iCol);
+ }else{
+ zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
+ nText = sqlite3_value_bytes(apVal[iCol-1]);
+ }
+ ctx.szCol = 0;
+ rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
+ zText, nText, (void*)&ctx, fts5StorageInsertCallback
+ );
+ p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
+ if( p->aTotalSize[iCol-1]<0 ){
+ rc = FTS5_CORRUPT;
+ }
+ }
+ }
+ if( rc==SQLITE_OK && p->nTotalRow<1 ){
+ rc = FTS5_CORRUPT;
+ }else{
+ p->nTotalRow--;
+ }
+
+ rc2 = sqlite3_reset(pSeek);
+ if( rc==SQLITE_OK ) rc = rc2;
+ return rc;
+}
+
+
+/*
+** Insert a record into the %_docsize table. Specifically, do:
+**
+** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
+**
+** If there is no %_docsize table (as happens if the columnsize=0 option
+** is specified when the FTS5 table is created), this function is a no-op.
+*/
+static int fts5StorageInsertDocsize(
+ Fts5Storage *p, /* Storage module to write to */
+ i64 iRowid, /* id value */
+ Fts5Buffer *pBuf /* sz value */
+){
+ int rc = SQLITE_OK;
+ if( p->pConfig->bColumnsize ){
+ sqlite3_stmt *pReplace = 0;
+ rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pReplace, 1, iRowid);
+ sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
+ sqlite3_step(pReplace);
+ rc = sqlite3_reset(pReplace);
+ sqlite3_bind_null(pReplace, 2);
+ }
+ }
+ return rc;
+}
+
+/*
+** Load the contents of the "averages" record from disk into the
+** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
+** argument bCache is true, set the p->bTotalsValid flag to indicate
+** that the contents of aTotalSize[] and nTotalRow are valid until
+** further notice.
+**
+** Return SQLITE_OK if successful, or an SQLite error code if an error
+** occurs.
+*/
+static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
+ int rc = SQLITE_OK;
+ if( p->bTotalsValid==0 ){
+ rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
+ p->bTotalsValid = bCache;
+ }
+ return rc;
+}
+
+/*
+** Store the current contents of the p->nTotalRow and p->aTotalSize[]
+** variables in the "averages" record on disk.
+**
+** Return SQLITE_OK if successful, or an SQLite error code if an error
+** occurs.
+*/
+static int fts5StorageSaveTotals(Fts5Storage *p){
+ int nCol = p->pConfig->nCol;
+ int i;
+ Fts5Buffer buf;
+ int rc = SQLITE_OK;
+ memset(&buf, 0, sizeof(buf));
+
+ sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
+ for(i=0; i<nCol; i++){
+ sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
+ }
+ sqlite3_free(buf.p);
+
+ return rc;
+}
+
+/*
+** Remove a row from the FTS table.
+*/
+static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
+ Fts5Config *pConfig = p->pConfig;
+ int rc;
+ sqlite3_stmt *pDel = 0;
+
+ assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
+ rc = fts5StorageLoadTotals(p, 1);
+
+ /* Delete the index records */
+ if( rc==SQLITE_OK ){
+ rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
+ }
+
+ /* Delete the %_docsize record */
+ if( rc==SQLITE_OK && pConfig->bColumnsize ){
+ rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pDel, 1, iDel);
+ sqlite3_step(pDel);
+ rc = sqlite3_reset(pDel);
+ }
+ }
+
+ /* Delete the %_content record */
+ if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
+ if( rc==SQLITE_OK ){
+ rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
+ }
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_int64(pDel, 1, iDel);
+ sqlite3_step(pDel);
+ rc = sqlite3_reset(pDel);
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Delete all entries in the FTS5 index.
+*/
+static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
+ Fts5Config *pConfig = p->pConfig;
+ int rc;
+
+ p->bTotalsValid = 0;
+
+ /* Delete the contents of the %_data and %_docsize tables. */
+ rc = fts5ExecPrintf(pConfig->db, 0,
+ "DELETE FROM %Q.'%q_data';"
+ "DELETE FROM %Q.'%q_idx';",
+ pConfig->zDb, pConfig->zName,
+ pConfig->zDb, pConfig->zName
+ );
+ if( rc==SQLITE_OK && pConfig->bColumnsize ){
+ rc = fts5ExecPrintf(pConfig->db, 0,
+ "DELETE FROM %Q.'%q_docsize';",
+ pConfig->zDb, pConfig->zName
+ );
+ }
+
+ /* Reinitialize the %_data table. This call creates the initial structure
+ ** and averages records. */
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5IndexReinit(p->pIndex);
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
+ }
+ return rc;
+}
+
+static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
+ Fts5Buffer buf = {0,0,0};
+ Fts5Config *pConfig = p->pConfig;
+ sqlite3_stmt *pScan = 0;
+ Fts5InsertCtx ctx;
+ int rc, rc2;
+
+ memset(&ctx, 0, sizeof(Fts5InsertCtx));
+ ctx.pStorage = p;
+ rc = sqlite3Fts5StorageDeleteAll(p);
+ if( rc==SQLITE_OK ){
+ rc = fts5StorageLoadTotals(p, 1);
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
+ }
+
+ while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
+ i64 iRowid = sqlite3_column_int64(pScan, 0);
+
+ sqlite3Fts5BufferZero(&buf);
+ rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
+ for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
+ ctx.szCol = 0;
+ if( pConfig->abUnindexed[ctx.iCol]==0 ){
+ const char *zText = (const char*)sqlite3_column_text(pScan, ctx.iCol+1);
+ int nText = sqlite3_column_bytes(pScan, ctx.iCol+1);
+ rc = sqlite3Fts5Tokenize(pConfig,
+ FTS5_TOKENIZE_DOCUMENT,
+ zText, nText,
+ (void*)&ctx,
+ fts5StorageInsertCallback
+ );
+ }
+ sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
+ p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
+ }
+ p->nTotalRow++;
+
+ if( rc==SQLITE_OK ){
+ rc = fts5StorageInsertDocsize(p, iRowid, &buf);
+ }
+ }
+ sqlite3_free(buf.p);
+ rc2 = sqlite3_reset(pScan);
+ if( rc==SQLITE_OK ) rc = rc2;
+
+ /* Write the averages record */
+ if( rc==SQLITE_OK ){
+ rc = fts5StorageSaveTotals(p);
+ }
+ return rc;
+}
+
+static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
+ return sqlite3Fts5IndexOptimize(p->pIndex);
+}
+
+static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
+ return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
+}
+
+static int sqlite3Fts5StorageReset(Fts5Storage *p){
+ return sqlite3Fts5IndexReset(p->pIndex);
+}
+
+/*
+** Allocate a new rowid. This is used for "external content" tables when
+** a NULL value is inserted into the rowid column. The new rowid is allocated
+** by inserting a dummy row into the %_docsize table. The dummy will be
+** overwritten later.
+**
+** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
+** this case the user is required to provide a rowid explicitly.
+*/
+static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
+ int rc = SQLITE_MISMATCH;
+ if( p->pConfig->bColumnsize ){
+ sqlite3_stmt *pReplace = 0;
+ rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_null(pReplace, 1);
+ sqlite3_bind_null(pReplace, 2);
+ sqlite3_step(pReplace);
+ rc = sqlite3_reset(pReplace);
+ }
+ if( rc==SQLITE_OK ){
+ *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
+ }
+ }
+ return rc;
+}
+
+/*
+** Insert a new row into the FTS content table.
+*/
+static int sqlite3Fts5StorageContentInsert(
+ Fts5Storage *p,
+ sqlite3_value **apVal,
+ i64 *piRowid
+){
+ Fts5Config *pConfig = p->pConfig;
+ int rc = SQLITE_OK;
+
+ /* Insert the new row into the %_content table. */
+ if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
+ if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
+ *piRowid = sqlite3_value_int64(apVal[1]);
+ }else{
+ rc = fts5StorageNewRowid(p, piRowid);
+ }
+ }else{
+ sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
+ int i; /* Counter variable */
+ rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
+ for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
+ rc = sqlite3_bind_value(pInsert, i, apVal[i]);
+ }
+ if( rc==SQLITE_OK ){
+ sqlite3_step(pInsert);
+ rc = sqlite3_reset(pInsert);
+ }
+ *piRowid = sqlite3_last_insert_rowid(pConfig->db);
+ }
+
+ return rc;
+}
+
+/*
+** Insert new entries into the FTS index and %_docsize table.
+*/
+static int sqlite3Fts5StorageIndexInsert(
+ Fts5Storage *p,
+ sqlite3_value **apVal,
+ i64 iRowid
+){
+ Fts5Config *pConfig = p->pConfig;
+ int rc = SQLITE_OK; /* Return code */
+ Fts5InsertCtx ctx; /* Tokenization callback context object */
+ Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
+
+ memset(&buf, 0, sizeof(Fts5Buffer));
+ ctx.pStorage = p;
+ rc = fts5StorageLoadTotals(p, 1);
+
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
+ }
+ for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
+ ctx.szCol = 0;
+ if( pConfig->abUnindexed[ctx.iCol]==0 ){
+ const char *zText = (const char*)sqlite3_value_text(apVal[ctx.iCol+2]);
+ int nText = sqlite3_value_bytes(apVal[ctx.iCol+2]);
+ rc = sqlite3Fts5Tokenize(pConfig,
+ FTS5_TOKENIZE_DOCUMENT,
+ zText, nText,
+ (void*)&ctx,
+ fts5StorageInsertCallback
+ );
+ }
+ sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
+ p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
+ }
+ p->nTotalRow++;
+
+ /* Write the %_docsize record */
+ if( rc==SQLITE_OK ){
+ rc = fts5StorageInsertDocsize(p, iRowid, &buf);
+ }
+ sqlite3_free(buf.p);
+
+ return rc;
+}
+
+static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
+ Fts5Config *pConfig = p->pConfig;
+ char *zSql;
+ int rc;
+
+ zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
+ pConfig->zDb, pConfig->zName, zSuffix
+ );
+ if( zSql==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ sqlite3_stmt *pCnt = 0;
+ rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
+ if( rc==SQLITE_OK ){
+ if( SQLITE_ROW==sqlite3_step(pCnt) ){
+ *pnRow = sqlite3_column_int64(pCnt, 0);
+ }
+ rc = sqlite3_finalize(pCnt);
+ }
+ }
+
+ sqlite3_free(zSql);
+ return rc;
+}
+
+/*
+** Context object used by sqlite3Fts5StorageIntegrity().
+*/
+typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
+struct Fts5IntegrityCtx {
+ i64 iRowid;
+ int iCol;
+ int szCol;
+ u64 cksum;
+ Fts5Termset *pTermset;
+ Fts5Config *pConfig;
+};
+
+
+/*
+** Tokenization callback used by integrity check.
+*/
+static int fts5StorageIntegrityCallback(
+ void *pContext, /* Pointer to Fts5IntegrityCtx object */
+ int tflags,
+ const char *pToken, /* Buffer containing token */
+ int nToken, /* Size of token in bytes */
+ int iUnused1, /* Start offset of token */
+ int iUnused2 /* End offset of token */
+){
+ Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
+ Fts5Termset *pTermset = pCtx->pTermset;
+ int bPresent;
+ int ii;
+ int rc = SQLITE_OK;
+ int iPos;
+ int iCol;
+
+ UNUSED_PARAM2(iUnused1, iUnused2);
+ if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
+
+ if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
+ pCtx->szCol++;
+ }
+
+ switch( pCtx->pConfig->eDetail ){
+ case FTS5_DETAIL_FULL:
+ iPos = pCtx->szCol-1;
+ iCol = pCtx->iCol;
+ break;
+
+ case FTS5_DETAIL_COLUMNS:
+ iPos = pCtx->iCol;
+ iCol = 0;
+ break;
+
+ default:
+ assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
+ iPos = 0;
+ iCol = 0;
+ break;
+ }
+
+ rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
+ if( rc==SQLITE_OK && bPresent==0 ){
+ pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
+ pCtx->iRowid, iCol, iPos, 0, pToken, nToken
+ );
+ }
+
+ for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
+ const int nChar = pCtx->pConfig->aPrefix[ii];
+ int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
+ if( nByte ){
+ rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
+ if( bPresent==0 ){
+ pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
+ pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
+ );
+ }
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Check that the contents of the FTS index match that of the %_content
+** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
+** some other SQLite error code if an error occurs while attempting to
+** determine this.
+*/
+static int sqlite3Fts5StorageIntegrity(Fts5Storage *p, int iArg){
+ Fts5Config *pConfig = p->pConfig;
+ int rc = SQLITE_OK; /* Return code */
+ int *aColSize; /* Array of size pConfig->nCol */
+ i64 *aTotalSize; /* Array of size pConfig->nCol */
+ Fts5IntegrityCtx ctx;
+ sqlite3_stmt *pScan;
+ int bUseCksum;
+
+ memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
+ ctx.pConfig = p->pConfig;
+ aTotalSize = (i64*)sqlite3_malloc64(pConfig->nCol*(sizeof(int)+sizeof(i64)));
+ if( !aTotalSize ) return SQLITE_NOMEM;
+ aColSize = (int*)&aTotalSize[pConfig->nCol];
+ memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
+
+ bUseCksum = (pConfig->eContent==FTS5_CONTENT_NORMAL
+ || (pConfig->eContent==FTS5_CONTENT_EXTERNAL && iArg)
+ );
+ if( bUseCksum ){
+ /* Generate the expected index checksum based on the contents of the
+ ** %_content table. This block stores the checksum in ctx.cksum. */
+ rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
+ if( rc==SQLITE_OK ){
+ int rc2;
+ while( SQLITE_ROW==sqlite3_step(pScan) ){
+ int i;
+ ctx.iRowid = sqlite3_column_int64(pScan, 0);
+ ctx.szCol = 0;
+ if( pConfig->bColumnsize ){
+ rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
+ }
+ if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
+ rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
+ }
+ for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
+ if( pConfig->abUnindexed[i] ) continue;
+ ctx.iCol = i;
+ ctx.szCol = 0;
+ if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
+ rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
+ }
+ if( rc==SQLITE_OK ){
+ const char *zText = (const char*)sqlite3_column_text(pScan, i+1);
+ int nText = sqlite3_column_bytes(pScan, i+1);
+ rc = sqlite3Fts5Tokenize(pConfig,
+ FTS5_TOKENIZE_DOCUMENT,
+ zText, nText,
+ (void*)&ctx,
+ fts5StorageIntegrityCallback
+ );
+ }
+ if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
+ rc = FTS5_CORRUPT;
+ }
+ aTotalSize[i] += ctx.szCol;
+ if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
+ sqlite3Fts5TermsetFree(ctx.pTermset);
+ ctx.pTermset = 0;
+ }
+ }
+ sqlite3Fts5TermsetFree(ctx.pTermset);
+ ctx.pTermset = 0;
+
+ if( rc!=SQLITE_OK ) break;
+ }
+ rc2 = sqlite3_reset(pScan);
+ if( rc==SQLITE_OK ) rc = rc2;
+ }
+
+ /* Test that the "totals" (sometimes called "averages") record looks Ok */
+ if( rc==SQLITE_OK ){
+ int i;
+ rc = fts5StorageLoadTotals(p, 0);
+ for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
+ if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
+ }
+ }
+
+ /* Check that the %_docsize and %_content tables contain the expected
+ ** number of rows. */
+ if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
+ i64 nRow = 0;
+ rc = fts5StorageCount(p, "content", &nRow);
+ if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
+ }
+ if( rc==SQLITE_OK && pConfig->bColumnsize ){
+ i64 nRow = 0;
+ rc = fts5StorageCount(p, "docsize", &nRow);
+ if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
+ }
+ }
+
+ /* Pass the expected checksum down to the FTS index module. It will
+ ** verify, amongst other things, that it matches the checksum generated by
+ ** inspecting the index itself. */
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum, bUseCksum);
+ }
+
+ sqlite3_free(aTotalSize);
+ return rc;
+}
+
+/*
+** Obtain an SQLite statement handle that may be used to read data from the
+** %_content table.
+*/
+static int sqlite3Fts5StorageStmt(
+ Fts5Storage *p,
+ int eStmt,
+ sqlite3_stmt **pp,
+ char **pzErrMsg
+){
+ int rc;
+ assert( eStmt==FTS5_STMT_SCAN_ASC
+ || eStmt==FTS5_STMT_SCAN_DESC
+ || eStmt==FTS5_STMT_LOOKUP
+ );
+ rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
+ if( rc==SQLITE_OK ){
+ assert( p->aStmt[eStmt]==*pp );
+ p->aStmt[eStmt] = 0;
+ }
+ return rc;
+}
+
+/*
+** Release an SQLite statement handle obtained via an earlier call to
+** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
+** must match that passed to the sqlite3Fts5StorageStmt() call.
+*/
+static void sqlite3Fts5StorageStmtRelease(
+ Fts5Storage *p,
+ int eStmt,
+ sqlite3_stmt *pStmt
+){
+ assert( eStmt==FTS5_STMT_SCAN_ASC
+ || eStmt==FTS5_STMT_SCAN_DESC
+ || eStmt==FTS5_STMT_LOOKUP
+ );
+ if( p->aStmt[eStmt]==0 ){
+ sqlite3_reset(pStmt);
+ p->aStmt[eStmt] = pStmt;
+ }else{
+ sqlite3_finalize(pStmt);
+ }
+}
+
+static int fts5StorageDecodeSizeArray(
+ int *aCol, int nCol, /* Array to populate */
+ const u8 *aBlob, int nBlob /* Record to read varints from */
+){
+ int i;
+ int iOff = 0;
+ for(i=0; i<nCol; i++){
+ if( iOff>=nBlob ) return 1;
+ iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
+ }
+ return (iOff!=nBlob);
+}
+
+/*
+** Argument aCol points to an array of integers containing one entry for
+** each table column. This function reads the %_docsize record for the
+** specified rowid and populates aCol[] with the results.
+**
+** An SQLite error code is returned if an error occurs, or SQLITE_OK
+** otherwise.
+*/
+static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
+ int nCol = p->pConfig->nCol; /* Number of user columns in table */
+ sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
+ int rc; /* Return Code */
+
+ assert( p->pConfig->bColumnsize );
+ rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
+ if( rc==SQLITE_OK ){
+ int bCorrupt = 1;
+ sqlite3_bind_int64(pLookup, 1, iRowid);
+ if( SQLITE_ROW==sqlite3_step(pLookup) ){
+ const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
+ int nBlob = sqlite3_column_bytes(pLookup, 0);
+ if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
+ bCorrupt = 0;
+ }
+ }
+ rc = sqlite3_reset(pLookup);
+ if( bCorrupt && rc==SQLITE_OK ){
+ rc = FTS5_CORRUPT;
+ }
+ }
+
+ return rc;
+}
+
+static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
+ int rc = fts5StorageLoadTotals(p, 0);
+ if( rc==SQLITE_OK ){
+ *pnToken = 0;
+ if( iCol<0 ){
+ int i;
+ for(i=0; i<p->pConfig->nCol; i++){
+ *pnToken += p->aTotalSize[i];
+ }
+ }else if( iCol<p->pConfig->nCol ){
+ *pnToken = p->aTotalSize[iCol];
+ }else{
+ rc = SQLITE_RANGE;
+ }
+ }
+ return rc;
+}
+
+static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
+ int rc = fts5StorageLoadTotals(p, 0);
+ if( rc==SQLITE_OK ){
+ /* nTotalRow being zero does not necessarily indicate a corrupt
+ ** database - it might be that the FTS5 table really does contain zero
+ ** rows. However this function is only called from the xRowCount() API,
+ ** and there is no way for that API to be invoked if the table contains
+ ** no rows. Hence the FTS5_CORRUPT return. */
+ *pnRow = p->nTotalRow;
+ if( p->nTotalRow<=0 ) rc = FTS5_CORRUPT;
+ }
+ return rc;
+}
+
+/*
+** Flush any data currently held in-memory to disk.
+*/
+static int sqlite3Fts5StorageSync(Fts5Storage *p){
+ int rc = SQLITE_OK;
+ i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
+ if( p->bTotalsValid ){
+ rc = fts5StorageSaveTotals(p);
+ p->bTotalsValid = 0;
+ }
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5IndexSync(p->pIndex);
+ }
+ sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
+ return rc;
+}
+
+static int sqlite3Fts5StorageRollback(Fts5Storage *p){
+ p->bTotalsValid = 0;
+ return sqlite3Fts5IndexRollback(p->pIndex);
+}
+
+static int sqlite3Fts5StorageConfigValue(
+ Fts5Storage *p,
+ const char *z,
+ sqlite3_value *pVal,
+ int iVal
+){
+ sqlite3_stmt *pReplace = 0;
+ int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
+ if( rc==SQLITE_OK ){
+ sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
+ if( pVal ){
+ sqlite3_bind_value(pReplace, 2, pVal);
+ }else{
+ sqlite3_bind_int(pReplace, 2, iVal);
+ }
+ sqlite3_step(pReplace);
+ rc = sqlite3_reset(pReplace);
+ sqlite3_bind_null(pReplace, 1);
+ }
+ if( rc==SQLITE_OK && pVal ){
+ int iNew = p->pConfig->iCookie + 1;
+ rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
+ if( rc==SQLITE_OK ){
+ p->pConfig->iCookie = iNew;
+ }
+ }
+ return rc;
+}
+
+/*
+** 2014 May 31
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+*/
+
+
+/* #include "fts5Int.h" */
+
+/**************************************************************************
+** Start of ascii tokenizer implementation.
+*/
+
+/*
+** For tokenizers with no "unicode" modifier, the set of token characters
+** is the same as the set of ASCII range alphanumeric characters.
+*/
+static unsigned char aAsciiTokenChar[128] = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
+};
+
+typedef struct AsciiTokenizer AsciiTokenizer;
+struct AsciiTokenizer {
+ unsigned char aTokenChar[128];
+};
+
+static void fts5AsciiAddExceptions(
+ AsciiTokenizer *p,
+ const char *zArg,
+ int bTokenChars
+){
+ int i;
+ for(i=0; zArg[i]; i++){
+ if( (zArg[i] & 0x80)==0 ){
+ p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
+ }
+ }
+}
+
+/*
+** Delete a "ascii" tokenizer.
+*/
+static void fts5AsciiDelete(Fts5Tokenizer *p){
+ sqlite3_free(p);
+}
+
+/*
+** Create an "ascii" tokenizer.
+*/
+static int fts5AsciiCreate(
+ void *pUnused,
+ const char **azArg, int nArg,
+ Fts5Tokenizer **ppOut
+){
+ int rc = SQLITE_OK;
+ AsciiTokenizer *p = 0;
+ UNUSED_PARAM(pUnused);
+ if( nArg%2 ){
+ rc = SQLITE_ERROR;
+ }else{
+ p = sqlite3_malloc(sizeof(AsciiTokenizer));
+ if( p==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ int i;
+ memset(p, 0, sizeof(AsciiTokenizer));
+ memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
+ for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
+ const char *zArg = azArg[i+1];
+ if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
+ fts5AsciiAddExceptions(p, zArg, 1);
+ }else
+ if( 0==sqlite3_stricmp(azArg[i], "separators") ){
+ fts5AsciiAddExceptions(p, zArg, 0);
+ }else{
+ rc = SQLITE_ERROR;
+ }
+ }
+ if( rc!=SQLITE_OK ){
+ fts5AsciiDelete((Fts5Tokenizer*)p);
+ p = 0;
+ }
+ }
+ }
+
+ *ppOut = (Fts5Tokenizer*)p;
+ return rc;
+}
+
+
+static void asciiFold(char *aOut, const char *aIn, int nByte){
+ int i;
+ for(i=0; i<nByte; i++){
+ char c = aIn[i];
+ if( c>='A' && c<='Z' ) c += 32;
+ aOut[i] = c;
+ }
+}
+
+/*
+** Tokenize some text using the ascii tokenizer.
+*/
+static int fts5AsciiTokenize(
+ Fts5Tokenizer *pTokenizer,
+ void *pCtx,
+ int iUnused,
+ const char *pText, int nText,
+ int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
+){
+ AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
+ int rc = SQLITE_OK;
+ int ie;
+ int is = 0;
+
+ char aFold[64];
+ int nFold = sizeof(aFold);
+ char *pFold = aFold;
+ unsigned char *a = p->aTokenChar;
+
+ UNUSED_PARAM(iUnused);
+
+ while( is<nText && rc==SQLITE_OK ){
+ int nByte;
+
+ /* Skip any leading divider characters. */
+ while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
+ is++;
+ }
+ if( is==nText ) break;
+
+ /* Count the token characters */
+ ie = is+1;
+ while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
+ ie++;
+ }
+
+ /* Fold to lower case */
+ nByte = ie-is;
+ if( nByte>nFold ){
+ if( pFold!=aFold ) sqlite3_free(pFold);
+ pFold = sqlite3_malloc64((sqlite3_int64)nByte*2);
+ if( pFold==0 ){
+ rc = SQLITE_NOMEM;
+ break;
+ }
+ nFold = nByte*2;
+ }
+ asciiFold(pFold, &pText[is], nByte);
+
+ /* Invoke the token callback */
+ rc = xToken(pCtx, 0, pFold, nByte, is, ie);
+ is = ie+1;
+ }
+
+ if( pFold!=aFold ) sqlite3_free(pFold);
+ if( rc==SQLITE_DONE ) rc = SQLITE_OK;
+ return rc;
+}
+
+/**************************************************************************
+** Start of unicode61 tokenizer implementation.
+*/
+
+
+/*
+** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
+** from the sqlite3 source file utf.c. If this file is compiled as part
+** of the amalgamation, they are not required.
+*/
+#ifndef SQLITE_AMALGAMATION
+
+static const unsigned char sqlite3Utf8Trans1[] = {
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
+ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
+};
+
+#define READ_UTF8(zIn, zTerm, c) \
+ c = *(zIn++); \
+ if( c>=0xc0 ){ \
+ c = sqlite3Utf8Trans1[c-0xc0]; \
+ while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
+ c = (c<<6) + (0x3f & *(zIn++)); \
+ } \
+ if( c<0x80 \
+ || (c&0xFFFFF800)==0xD800 \
+ || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
+ }
+
+
+#define WRITE_UTF8(zOut, c) { \
+ if( c<0x00080 ){ \
+ *zOut++ = (unsigned char)(c&0xFF); \
+ } \
+ else if( c<0x00800 ){ \
+ *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
+ *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
+ } \
+ else if( c<0x10000 ){ \
+ *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
+ *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
+ *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
+ }else{ \
+ *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
+ *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
+ *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
+ *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
+ } \
+}
+
+#endif /* ifndef SQLITE_AMALGAMATION */
+
+typedef struct Unicode61Tokenizer Unicode61Tokenizer;
+struct Unicode61Tokenizer {
+ unsigned char aTokenChar[128]; /* ASCII range token characters */
+ char *aFold; /* Buffer to fold text into */
+ int nFold; /* Size of aFold[] in bytes */
+ int eRemoveDiacritic; /* True if remove_diacritics=1 is set */
+ int nException;
+ int *aiException;
+
+ unsigned char aCategory[32]; /* True for token char categories */
+};
+
+/* Values for eRemoveDiacritic (must match internals of fts5_unicode2.c) */
+#define FTS5_REMOVE_DIACRITICS_NONE 0
+#define FTS5_REMOVE_DIACRITICS_SIMPLE 1
+#define FTS5_REMOVE_DIACRITICS_COMPLEX 2
+
+static int fts5UnicodeAddExceptions(
+ Unicode61Tokenizer *p, /* Tokenizer object */
+ const char *z, /* Characters to treat as exceptions */
+ int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
+){
+ int rc = SQLITE_OK;
+ int n = (int)strlen(z);
+ int *aNew;
+
+ if( n>0 ){
+ aNew = (int*)sqlite3_realloc64(p->aiException,
+ (n+p->nException)*sizeof(int));
+ if( aNew ){
+ int nNew = p->nException;
+ const unsigned char *zCsr = (const unsigned char*)z;
+ const unsigned char *zTerm = (const unsigned char*)&z[n];
+ while( zCsr<zTerm ){
+ u32 iCode;
+ int bToken;
+ READ_UTF8(zCsr, zTerm, iCode);
+ if( iCode<128 ){
+ p->aTokenChar[iCode] = (unsigned char)bTokenChars;
+ }else{
+ bToken = p->aCategory[sqlite3Fts5UnicodeCategory(iCode)];
+ assert( (bToken==0 || bToken==1) );
+ assert( (bTokenChars==0 || bTokenChars==1) );
+ if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
+ int i;
+ for(i=0; i<nNew; i++){
+ if( (u32)aNew[i]>iCode ) break;
+ }
+ memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
+ aNew[i] = iCode;
+ nNew++;
+ }
+ }
+ }
+ p->aiException = aNew;
+ p->nException = nNew;
+ }else{
+ rc = SQLITE_NOMEM;
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Return true if the p->aiException[] array contains the value iCode.
+*/
+static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
+ if( p->nException>0 ){
+ int *a = p->aiException;
+ int iLo = 0;
+ int iHi = p->nException-1;
+
+ while( iHi>=iLo ){
+ int iTest = (iHi + iLo) / 2;
+ if( iCode==a[iTest] ){
+ return 1;
+ }else if( iCode>a[iTest] ){
+ iLo = iTest+1;
+ }else{
+ iHi = iTest-1;
+ }
+ }
+ }
+
+ return 0;
+}
+
+/*
+** Delete a "unicode61" tokenizer.
+*/
+static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
+ if( pTok ){
+ Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
+ sqlite3_free(p->aiException);
+ sqlite3_free(p->aFold);
+ sqlite3_free(p);
+ }
+ return;
+}
+
+static int unicodeSetCategories(Unicode61Tokenizer *p, const char *zCat){
+ const char *z = zCat;
+
+ while( *z ){
+ while( *z==' ' || *z=='\t' ) z++;
+ if( *z && sqlite3Fts5UnicodeCatParse(z, p->aCategory) ){
+ return SQLITE_ERROR;
+ }
+ while( *z!=' ' && *z!='\t' && *z!='\0' ) z++;
+ }
+
+ sqlite3Fts5UnicodeAscii(p->aCategory, p->aTokenChar);
+ return SQLITE_OK;
+}
+
+/*
+** Create a "unicode61" tokenizer.
+*/
+static int fts5UnicodeCreate(
+ void *pUnused,
+ const char **azArg, int nArg,
+ Fts5Tokenizer **ppOut
+){
+ int rc = SQLITE_OK; /* Return code */
+ Unicode61Tokenizer *p = 0; /* New tokenizer object */
+
+ UNUSED_PARAM(pUnused);
+
+ if( nArg%2 ){
+ rc = SQLITE_ERROR;
+ }else{
+ p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
+ if( p ){
+ const char *zCat = "L* N* Co";
+ int i;
+ memset(p, 0, sizeof(Unicode61Tokenizer));
+
+ p->eRemoveDiacritic = FTS5_REMOVE_DIACRITICS_SIMPLE;
+ p->nFold = 64;
+ p->aFold = sqlite3_malloc64(p->nFold * sizeof(char));
+ if( p->aFold==0 ){
+ rc = SQLITE_NOMEM;
+ }
+
+ /* Search for a "categories" argument */
+ for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
+ if( 0==sqlite3_stricmp(azArg[i], "categories") ){
+ zCat = azArg[i+1];
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = unicodeSetCategories(p, zCat);
+ }
+
+ for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
+ const char *zArg = azArg[i+1];
+ if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
+ if( (zArg[0]!='0' && zArg[0]!='1' && zArg[0]!='2') || zArg[1] ){
+ rc = SQLITE_ERROR;
+ }else{
+ p->eRemoveDiacritic = (zArg[0] - '0');
+ assert( p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_NONE
+ || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_SIMPLE
+ || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_COMPLEX
+ );
+ }
+ }else
+ if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
+ rc = fts5UnicodeAddExceptions(p, zArg, 1);
+ }else
+ if( 0==sqlite3_stricmp(azArg[i], "separators") ){
+ rc = fts5UnicodeAddExceptions(p, zArg, 0);
+ }else
+ if( 0==sqlite3_stricmp(azArg[i], "categories") ){
+ /* no-op */
+ }else{
+ rc = SQLITE_ERROR;
+ }
+ }
+
+ }else{
+ rc = SQLITE_NOMEM;
+ }
+ if( rc!=SQLITE_OK ){
+ fts5UnicodeDelete((Fts5Tokenizer*)p);
+ p = 0;
+ }
+ *ppOut = (Fts5Tokenizer*)p;
+ }
+ return rc;
+}
+
+/*
+** Return true if, for the purposes of tokenizing with the tokenizer
+** passed as the first argument, codepoint iCode is considered a token
+** character (not a separator).
+*/
+static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
+ return (
+ p->aCategory[sqlite3Fts5UnicodeCategory((u32)iCode)]
+ ^ fts5UnicodeIsException(p, iCode)
+ );
+}
+
+static int fts5UnicodeTokenize(
+ Fts5Tokenizer *pTokenizer,
+ void *pCtx,
+ int iUnused,
+ const char *pText, int nText,
+ int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
+){
+ Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
+ int rc = SQLITE_OK;
+ unsigned char *a = p->aTokenChar;
+
+ unsigned char *zTerm = (unsigned char*)&pText[nText];
+ unsigned char *zCsr = (unsigned char *)pText;
+
+ /* Output buffer */
+ char *aFold = p->aFold;
+ int nFold = p->nFold;
+ const char *pEnd = &aFold[nFold-6];
+
+ UNUSED_PARAM(iUnused);
+
+ /* Each iteration of this loop gobbles up a contiguous run of separators,
+ ** then the next token. */
+ while( rc==SQLITE_OK ){
+ u32 iCode; /* non-ASCII codepoint read from input */
+ char *zOut = aFold;
+ int is;
+ int ie;
+
+ /* Skip any separator characters. */
+ while( 1 ){
+ if( zCsr>=zTerm ) goto tokenize_done;
+ if( *zCsr & 0x80 ) {
+ /* A character outside of the ascii range. Skip past it if it is
+ ** a separator character. Or break out of the loop if it is not. */
+ is = zCsr - (unsigned char*)pText;
+ READ_UTF8(zCsr, zTerm, iCode);
+ if( fts5UnicodeIsAlnum(p, iCode) ){
+ goto non_ascii_tokenchar;
+ }
+ }else{
+ if( a[*zCsr] ){
+ is = zCsr - (unsigned char*)pText;
+ goto ascii_tokenchar;
+ }
+ zCsr++;
+ }
+ }
+
+ /* Run through the tokenchars. Fold them into the output buffer along
+ ** the way. */
+ while( zCsr<zTerm ){
+
+ /* Grow the output buffer so that there is sufficient space to fit the
+ ** largest possible utf-8 character. */
+ if( zOut>pEnd ){
+ aFold = sqlite3_malloc64((sqlite3_int64)nFold*2);
+ if( aFold==0 ){
+ rc = SQLITE_NOMEM;
+ goto tokenize_done;
+ }
+ zOut = &aFold[zOut - p->aFold];
+ memcpy(aFold, p->aFold, nFold);
+ sqlite3_free(p->aFold);
+ p->aFold = aFold;
+ p->nFold = nFold = nFold*2;
+ pEnd = &aFold[nFold-6];
+ }
+
+ if( *zCsr & 0x80 ){
+ /* An non-ascii-range character. Fold it into the output buffer if
+ ** it is a token character, or break out of the loop if it is not. */
+ READ_UTF8(zCsr, zTerm, iCode);
+ if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
+ non_ascii_tokenchar:
+ iCode = sqlite3Fts5UnicodeFold(iCode, p->eRemoveDiacritic);
+ if( iCode ) WRITE_UTF8(zOut, iCode);
+ }else{
+ break;
+ }
+ }else if( a[*zCsr]==0 ){
+ /* An ascii-range separator character. End of token. */
+ break;
+ }else{
+ ascii_tokenchar:
+ if( *zCsr>='A' && *zCsr<='Z' ){
+ *zOut++ = *zCsr + 32;
+ }else{
+ *zOut++ = *zCsr;
+ }
+ zCsr++;
+ }
+ ie = zCsr - (unsigned char*)pText;
+ }
+
+ /* Invoke the token callback */
+ rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
+ }
+
+ tokenize_done:
+ if( rc==SQLITE_DONE ) rc = SQLITE_OK;
+ return rc;
+}
+
+/**************************************************************************
+** Start of porter stemmer implementation.
+*/
+
+/* Any tokens larger than this (in bytes) are passed through without
+** stemming. */
+#define FTS5_PORTER_MAX_TOKEN 64
+
+typedef struct PorterTokenizer PorterTokenizer;
+struct PorterTokenizer {
+ fts5_tokenizer tokenizer; /* Parent tokenizer module */
+ Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
+ char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
+};
+
+/*
+** Delete a "porter" tokenizer.
+*/
+static void fts5PorterDelete(Fts5Tokenizer *pTok){
+ if( pTok ){
+ PorterTokenizer *p = (PorterTokenizer*)pTok;
+ if( p->pTokenizer ){
+ p->tokenizer.xDelete(p->pTokenizer);
+ }
+ sqlite3_free(p);
+ }
+}
+
+/*
+** Create a "porter" tokenizer.
+*/
+static int fts5PorterCreate(
+ void *pCtx,
+ const char **azArg, int nArg,
+ Fts5Tokenizer **ppOut
+){
+ fts5_api *pApi = (fts5_api*)pCtx;
+ int rc = SQLITE_OK;
+ PorterTokenizer *pRet;
+ void *pUserdata = 0;
+ const char *zBase = "unicode61";
+
+ if( nArg>0 ){
+ zBase = azArg[0];
+ }
+
+ pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
+ if( pRet ){
+ memset(pRet, 0, sizeof(PorterTokenizer));
+ rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
+ }else{
+ rc = SQLITE_NOMEM;
+ }
+ if( rc==SQLITE_OK ){
+ int nArg2 = (nArg>0 ? nArg-1 : 0);
+ const char **azArg2 = (nArg2 ? &azArg[1] : 0);
+ rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
+ }
+
+ if( rc!=SQLITE_OK ){
+ fts5PorterDelete((Fts5Tokenizer*)pRet);
+ pRet = 0;
+ }
+ *ppOut = (Fts5Tokenizer*)pRet;
+ return rc;
+}
+
+typedef struct PorterContext PorterContext;
+struct PorterContext {
+ void *pCtx;
+ int (*xToken)(void*, int, const char*, int, int, int);
+ char *aBuf;
+};
+
+typedef struct PorterRule PorterRule;
+struct PorterRule {
+ const char *zSuffix;
+ int nSuffix;
+ int (*xCond)(char *zStem, int nStem);
+ const char *zOutput;
+ int nOutput;
+};
+
+#if 0
+static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
+ int ret = -1;
+ int nBuf = *pnBuf;
+ PorterRule *p;
+
+ for(p=aRule; p->zSuffix; p++){
+ assert( strlen(p->zSuffix)==p->nSuffix );
+ assert( strlen(p->zOutput)==p->nOutput );
+ if( nBuf<p->nSuffix ) continue;
+ if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
+ }
+
+ if( p->zSuffix ){
+ int nStem = nBuf - p->nSuffix;
+ if( p->xCond==0 || p->xCond(aBuf, nStem) ){
+ memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
+ *pnBuf = nStem + p->nOutput;
+ ret = p - aRule;
+ }
+ }
+
+ return ret;
+}
+#endif
+
+static int fts5PorterIsVowel(char c, int bYIsVowel){
+ return (
+ c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
+ );
+}
+
+static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
+ int i;
+ int bCons = bPrevCons;
+
+ /* Scan for a vowel */
+ for(i=0; i<nStem; i++){
+ if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
+ }
+
+ /* Scan for a consonent */
+ for(i++; i<nStem; i++){
+ if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
+ }
+ return 0;
+}
+
+/* porter rule condition: (m > 0) */
+static int fts5Porter_MGt0(char *zStem, int nStem){
+ return !!fts5PorterGobbleVC(zStem, nStem, 0);
+}
+
+/* porter rule condition: (m > 1) */
+static int fts5Porter_MGt1(char *zStem, int nStem){
+ int n;
+ n = fts5PorterGobbleVC(zStem, nStem, 0);
+ if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
+ return 1;
+ }
+ return 0;
+}
+
+/* porter rule condition: (m = 1) */
+static int fts5Porter_MEq1(char *zStem, int nStem){
+ int n;
+ n = fts5PorterGobbleVC(zStem, nStem, 0);
+ if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
+ return 1;
+ }
+ return 0;
+}
+
+/* porter rule condition: (*o) */
+static int fts5Porter_Ostar(char *zStem, int nStem){
+ if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
+ return 0;
+ }else{
+ int i;
+ int mask = 0;
+ int bCons = 0;
+ for(i=0; i<nStem; i++){
+ bCons = !fts5PorterIsVowel(zStem[i], bCons);
+ assert( bCons==0 || bCons==1 );
+ mask = (mask << 1) + bCons;
+ }
+ return ((mask & 0x0007)==0x0005);
+ }
+}
+
+/* porter rule condition: (m > 1 and (*S or *T)) */
+static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
+ assert( nStem>0 );
+ return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
+ && fts5Porter_MGt1(zStem, nStem);
+}
+
+/* porter rule condition: (*v*) */
+static int fts5Porter_Vowel(char *zStem, int nStem){
+ int i;
+ for(i=0; i<nStem; i++){
+ if( fts5PorterIsVowel(zStem[i], i>0) ){
+ return 1;
+ }
+ }
+ return 0;
+}
+
+
+/**************************************************************************
+***************************************************************************
+** GENERATED CODE STARTS HERE (mkportersteps.tcl)
+*/
+
+static int fts5PorterStep4(char *aBuf, int *pnBuf){
+ int ret = 0;
+ int nBuf = *pnBuf;
+ switch( aBuf[nBuf-2] ){
+
+ case 'a':
+ if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-2) ){
+ *pnBuf = nBuf - 2;
+ }
+ }
+ break;
+
+ case 'c':
+ if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-4) ){
+ *pnBuf = nBuf - 4;
+ }
+ }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-4) ){
+ *pnBuf = nBuf - 4;
+ }
+ }
+ break;
+
+ case 'e':
+ if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-2) ){
+ *pnBuf = nBuf - 2;
+ }
+ }
+ break;
+
+ case 'i':
+ if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-2) ){
+ *pnBuf = nBuf - 2;
+ }
+ }
+ break;
+
+ case 'l':
+ if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-4) ){
+ *pnBuf = nBuf - 4;
+ }
+ }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-4) ){
+ *pnBuf = nBuf - 4;
+ }
+ }
+ break;
+
+ case 'n':
+ if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-3) ){
+ *pnBuf = nBuf - 3;
+ }
+ }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-5) ){
+ *pnBuf = nBuf - 5;
+ }
+ }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-4) ){
+ *pnBuf = nBuf - 4;
+ }
+ }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-3) ){
+ *pnBuf = nBuf - 3;
+ }
+ }
+ break;
+
+ case 'o':
+ if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
+ if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
+ *pnBuf = nBuf - 3;
+ }
+ }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-2) ){
+ *pnBuf = nBuf - 2;
+ }
+ }
+ break;
+
+ case 's':
+ if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-3) ){
+ *pnBuf = nBuf - 3;
+ }
+ }
+ break;
+
+ case 't':
+ if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-3) ){
+ *pnBuf = nBuf - 3;
+ }
+ }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-3) ){
+ *pnBuf = nBuf - 3;
+ }
+ }
+ break;
+
+ case 'u':
+ if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-3) ){
+ *pnBuf = nBuf - 3;
+ }
+ }
+ break;
+
+ case 'v':
+ if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-3) ){
+ *pnBuf = nBuf - 3;
+ }
+ }
+ break;
+
+ case 'z':
+ if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
+ if( fts5Porter_MGt1(aBuf, nBuf-3) ){
+ *pnBuf = nBuf - 3;
+ }
+ }
+ break;
+
+ }
+ return ret;
+}
+
+
+static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
+ int ret = 0;
+ int nBuf = *pnBuf;
+ switch( aBuf[nBuf-2] ){
+
+ case 'a':
+ if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
+ memcpy(&aBuf[nBuf-2], "ate", 3);
+ *pnBuf = nBuf - 2 + 3;
+ ret = 1;
+ }
+ break;
+
+ case 'b':
+ if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
+ memcpy(&aBuf[nBuf-2], "ble", 3);
+ *pnBuf = nBuf - 2 + 3;
+ ret = 1;
+ }
+ break;
+
+ case 'i':
+ if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
+ memcpy(&aBuf[nBuf-2], "ize", 3);
+ *pnBuf = nBuf - 2 + 3;
+ ret = 1;
+ }
+ break;
+
+ }
+ return ret;
+}
+
+
+static int fts5PorterStep2(char *aBuf, int *pnBuf){
+ int ret = 0;
+ int nBuf = *pnBuf;
+ switch( aBuf[nBuf-2] ){
+
+ case 'a':
+ if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-7) ){
+ memcpy(&aBuf[nBuf-7], "ate", 3);
+ *pnBuf = nBuf - 7 + 3;
+ }
+ }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-6) ){
+ memcpy(&aBuf[nBuf-6], "tion", 4);
+ *pnBuf = nBuf - 6 + 4;
+ }
+ }
+ break;
+
+ case 'c':
+ if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-4) ){
+ memcpy(&aBuf[nBuf-4], "ence", 4);
+ *pnBuf = nBuf - 4 + 4;
+ }
+ }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-4) ){
+ memcpy(&aBuf[nBuf-4], "ance", 4);
+ *pnBuf = nBuf - 4 + 4;
+ }
+ }
+ break;
+
+ case 'e':
+ if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-4) ){
+ memcpy(&aBuf[nBuf-4], "ize", 3);
+ *pnBuf = nBuf - 4 + 3;
+ }
+ }
+ break;
+
+ case 'g':
+ if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-4) ){
+ memcpy(&aBuf[nBuf-4], "log", 3);
+ *pnBuf = nBuf - 4 + 3;
+ }
+ }
+ break;
+
+ case 'l':
+ if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-3) ){
+ memcpy(&aBuf[nBuf-3], "ble", 3);
+ *pnBuf = nBuf - 3 + 3;
+ }
+ }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-4) ){
+ memcpy(&aBuf[nBuf-4], "al", 2);
+ *pnBuf = nBuf - 4 + 2;
+ }
+ }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-5) ){
+ memcpy(&aBuf[nBuf-5], "ent", 3);
+ *pnBuf = nBuf - 5 + 3;
+ }
+ }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-3) ){
+ memcpy(&aBuf[nBuf-3], "e", 1);
+ *pnBuf = nBuf - 3 + 1;
+ }
+ }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-5) ){
+ memcpy(&aBuf[nBuf-5], "ous", 3);
+ *pnBuf = nBuf - 5 + 3;
+ }
+ }
+ break;
+
+ case 'o':
+ if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-7) ){
+ memcpy(&aBuf[nBuf-7], "ize", 3);
+ *pnBuf = nBuf - 7 + 3;
+ }
+ }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-5) ){
+ memcpy(&aBuf[nBuf-5], "ate", 3);
+ *pnBuf = nBuf - 5 + 3;
+ }
+ }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-4) ){
+ memcpy(&aBuf[nBuf-4], "ate", 3);
+ *pnBuf = nBuf - 4 + 3;
+ }
+ }
+ break;
+
+ case 's':
+ if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-5) ){
+ memcpy(&aBuf[nBuf-5], "al", 2);
+ *pnBuf = nBuf - 5 + 2;
+ }
+ }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-7) ){
+ memcpy(&aBuf[nBuf-7], "ive", 3);
+ *pnBuf = nBuf - 7 + 3;
+ }
+ }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-7) ){
+ memcpy(&aBuf[nBuf-7], "ful", 3);
+ *pnBuf = nBuf - 7 + 3;
+ }
+ }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-7) ){
+ memcpy(&aBuf[nBuf-7], "ous", 3);
+ *pnBuf = nBuf - 7 + 3;
+ }
+ }
+ break;
+
+ case 't':
+ if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-5) ){
+ memcpy(&aBuf[nBuf-5], "al", 2);
+ *pnBuf = nBuf - 5 + 2;
+ }
+ }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-5) ){
+ memcpy(&aBuf[nBuf-5], "ive", 3);
+ *pnBuf = nBuf - 5 + 3;
+ }
+ }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-6) ){
+ memcpy(&aBuf[nBuf-6], "ble", 3);
+ *pnBuf = nBuf - 6 + 3;
+ }
+ }
+ break;
+
+ }
+ return ret;
+}
+
+
+static int fts5PorterStep3(char *aBuf, int *pnBuf){
+ int ret = 0;
+ int nBuf = *pnBuf;
+ switch( aBuf[nBuf-2] ){
+
+ case 'a':
+ if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-4) ){
+ memcpy(&aBuf[nBuf-4], "ic", 2);
+ *pnBuf = nBuf - 4 + 2;
+ }
+ }
+ break;
+
+ case 's':
+ if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-4) ){
+ *pnBuf = nBuf - 4;
+ }
+ }
+ break;
+
+ case 't':
+ if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-5) ){
+ memcpy(&aBuf[nBuf-5], "ic", 2);
+ *pnBuf = nBuf - 5 + 2;
+ }
+ }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-5) ){
+ memcpy(&aBuf[nBuf-5], "ic", 2);
+ *pnBuf = nBuf - 5 + 2;
+ }
+ }
+ break;
+
+ case 'u':
+ if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-3) ){
+ *pnBuf = nBuf - 3;
+ }
+ }
+ break;
+
+ case 'v':
+ if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-5) ){
+ *pnBuf = nBuf - 5;
+ }
+ }
+ break;
+
+ case 'z':
+ if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-5) ){
+ memcpy(&aBuf[nBuf-5], "al", 2);
+ *pnBuf = nBuf - 5 + 2;
+ }
+ }
+ break;
+
+ }
+ return ret;
+}
+
+
+static int fts5PorterStep1B(char *aBuf, int *pnBuf){
+ int ret = 0;
+ int nBuf = *pnBuf;
+ switch( aBuf[nBuf-2] ){
+
+ case 'e':
+ if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
+ if( fts5Porter_MGt0(aBuf, nBuf-3) ){
+ memcpy(&aBuf[nBuf-3], "ee", 2);
+ *pnBuf = nBuf - 3 + 2;
+ }
+ }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
+ if( fts5Porter_Vowel(aBuf, nBuf-2) ){
+ *pnBuf = nBuf - 2;
+ ret = 1;
+ }
+ }
+ break;
+
+ case 'n':
+ if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
+ if( fts5Porter_Vowel(aBuf, nBuf-3) ){
+ *pnBuf = nBuf - 3;
+ ret = 1;
+ }
+ }
+ break;
+
+ }
+ return ret;
+}
+
+/*
+** GENERATED CODE ENDS HERE (mkportersteps.tcl)
+***************************************************************************
+**************************************************************************/
+
+static void fts5PorterStep1A(char *aBuf, int *pnBuf){
+ int nBuf = *pnBuf;
+ if( aBuf[nBuf-1]=='s' ){
+ if( aBuf[nBuf-2]=='e' ){
+ if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
+ || (nBuf>3 && aBuf[nBuf-3]=='i' )
+ ){
+ *pnBuf = nBuf-2;
+ }else{
+ *pnBuf = nBuf-1;
+ }
+ }
+ else if( aBuf[nBuf-2]!='s' ){
+ *pnBuf = nBuf-1;
+ }
+ }
+}
+
+static int fts5PorterCb(
+ void *pCtx,
+ int tflags,
+ const char *pToken,
+ int nToken,
+ int iStart,
+ int iEnd
+){
+ PorterContext *p = (PorterContext*)pCtx;
+
+ char *aBuf;
+ int nBuf;
+
+ if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
+ aBuf = p->aBuf;
+ nBuf = nToken;
+ memcpy(aBuf, pToken, nBuf);
+
+ /* Step 1. */
+ fts5PorterStep1A(aBuf, &nBuf);
+ if( fts5PorterStep1B(aBuf, &nBuf) ){
+ if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
+ char c = aBuf[nBuf-1];
+ if( fts5PorterIsVowel(c, 0)==0
+ && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
+ ){
+ nBuf--;
+ }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
+ aBuf[nBuf++] = 'e';
+ }
+ }
+ }
+
+ /* Step 1C. */
+ if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
+ aBuf[nBuf-1] = 'i';
+ }
+
+ /* Steps 2 through 4. */
+ fts5PorterStep2(aBuf, &nBuf);
+ fts5PorterStep3(aBuf, &nBuf);
+ fts5PorterStep4(aBuf, &nBuf);
+
+ /* Step 5a. */
+ assert( nBuf>0 );
+ if( aBuf[nBuf-1]=='e' ){
+ if( fts5Porter_MGt1(aBuf, nBuf-1)
+ || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
+ ){
+ nBuf--;
+ }
+ }
+
+ /* Step 5b. */
+ if( nBuf>1 && aBuf[nBuf-1]=='l'
+ && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
+ ){
+ nBuf--;
+ }
+
+ return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
+
+ pass_through:
+ return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
+}
+
+/*
+** Tokenize using the porter tokenizer.
+*/
+static int fts5PorterTokenize(
+ Fts5Tokenizer *pTokenizer,
+ void *pCtx,
+ int flags,
+ const char *pText, int nText,
+ int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
+){
+ PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
+ PorterContext sCtx;
+ sCtx.xToken = xToken;
+ sCtx.pCtx = pCtx;
+ sCtx.aBuf = p->aBuf;
+ return p->tokenizer.xTokenize(
+ p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
+ );
+}
+
+/**************************************************************************
+** Start of trigram implementation.
+*/
+typedef struct TrigramTokenizer TrigramTokenizer;
+struct TrigramTokenizer {
+ int bFold; /* True to fold to lower-case */
+};
+
+/*
+** Free a trigram tokenizer.
+*/
+static void fts5TriDelete(Fts5Tokenizer *p){
+ sqlite3_free(p);
+}
+
+/*
+** Allocate a trigram tokenizer.
+*/
+static int fts5TriCreate(
+ void *pCtx,
+ const char **azArg,
+ int nArg,
+ Fts5Tokenizer **ppOut
+){
+ int rc = SQLITE_OK;
+ TrigramTokenizer *pNew = (TrigramTokenizer*)sqlite3_malloc(sizeof(*pNew));
+ if( pNew==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ int i;
+ pNew->bFold = 1;
+ for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
+ const char *zArg = azArg[i+1];
+ if( 0==sqlite3_stricmp(azArg[i], "case_sensitive") ){
+ if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
+ rc = SQLITE_ERROR;
+ }else{
+ pNew->bFold = (zArg[0]=='0');
+ }
+ }else{
+ rc = SQLITE_ERROR;
+ }
+ }
+ if( rc!=SQLITE_OK ){
+ fts5TriDelete((Fts5Tokenizer*)pNew);
+ pNew = 0;
+ }
+ }
+ *ppOut = (Fts5Tokenizer*)pNew;
+ return rc;
+}
+
+/*
+** Trigram tokenizer tokenize routine.
+*/
+static int fts5TriTokenize(
+ Fts5Tokenizer *pTok,
+ void *pCtx,
+ int flags,
+ const char *pText, int nText,
+ int (*xToken)(void*, int, const char*, int, int, int)
+){
+ TrigramTokenizer *p = (TrigramTokenizer*)pTok;
+ int rc = SQLITE_OK;
+ char aBuf[32];
+ const unsigned char *zIn = (const unsigned char*)pText;
+ const unsigned char *zEof = &zIn[nText];
+ u32 iCode;
+
+ while( 1 ){
+ char *zOut = aBuf;
+ int iStart = zIn - (const unsigned char*)pText;
+ const unsigned char *zNext;
+
+ READ_UTF8(zIn, zEof, iCode);
+ zNext = zIn;
+ if( zIn<zEof ){
+ if( p->bFold ) iCode = sqlite3Fts5UnicodeFold(iCode, 0);
+ WRITE_UTF8(zOut, iCode);
+ READ_UTF8(zIn, zEof, iCode);
+ }else{
+ break;
+ }
+ if( zIn<zEof ){
+ if( p->bFold ) iCode = sqlite3Fts5UnicodeFold(iCode, 0);
+ WRITE_UTF8(zOut, iCode);
+ READ_UTF8(zIn, zEof, iCode);
+ if( p->bFold ) iCode = sqlite3Fts5UnicodeFold(iCode, 0);
+ WRITE_UTF8(zOut, iCode);
+ }else{
+ break;
+ }
+ rc = xToken(pCtx, 0, aBuf, zOut-aBuf, iStart, iStart + zOut-aBuf);
+ if( rc!=SQLITE_OK ) break;
+ zIn = zNext;
+ }
+
+ return rc;
+}
+
+/*
+** Argument xCreate is a pointer to a constructor function for a tokenizer.
+** pTok is a tokenizer previously created using the same method. This function
+** returns one of FTS5_PATTERN_NONE, FTS5_PATTERN_LIKE or FTS5_PATTERN_GLOB
+** indicating the style of pattern matching that the tokenizer can support.
+** In practice, this is:
+**
+** "trigram" tokenizer, case_sensitive=1 - FTS5_PATTERN_GLOB
+** "trigram" tokenizer, case_sensitive=0 (the default) - FTS5_PATTERN_LIKE
+** all other tokenizers - FTS5_PATTERN_NONE
+*/
+static int sqlite3Fts5TokenizerPattern(
+ int (*xCreate)(void*, const char**, int, Fts5Tokenizer**),
+ Fts5Tokenizer *pTok
+){
+ if( xCreate==fts5TriCreate ){
+ TrigramTokenizer *p = (TrigramTokenizer*)pTok;
+ return p->bFold ? FTS5_PATTERN_LIKE : FTS5_PATTERN_GLOB;
+ }
+ return FTS5_PATTERN_NONE;
+}
+
+/*
+** Register all built-in tokenizers with FTS5.
+*/
+static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
+ struct BuiltinTokenizer {
+ const char *zName;
+ fts5_tokenizer x;
+ } aBuiltin[] = {
+ { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
+ { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
+ { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
+ { "trigram", {fts5TriCreate, fts5TriDelete, fts5TriTokenize}},
+ };
+
+ int rc = SQLITE_OK; /* Return code */
+ int i; /* To iterate through builtin functions */
+
+ for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
+ rc = pApi->xCreateTokenizer(pApi,
+ aBuiltin[i].zName,
+ (void*)pApi,
+ &aBuiltin[i].x,
+ 0
+ );
+ }
+
+ return rc;
+}
+
+/*
+** 2012-05-25
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+*/
+
+/*
+** DO NOT EDIT THIS MACHINE GENERATED FILE.
+*/
+
+
+/* #include <assert.h> */
+
+
+
+/*
+** If the argument is a codepoint corresponding to a lowercase letter
+** in the ASCII range with a diacritic added, return the codepoint
+** of the ASCII letter only. For example, if passed 235 - "LATIN
+** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
+** E"). The resuls of passing a codepoint that corresponds to an
+** uppercase letter are undefined.
+*/
+static int fts5_remove_diacritic(int c, int bComplex){
+ unsigned short aDia[] = {
+ 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
+ 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
+ 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
+ 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
+ 3456, 3696, 3712, 3728, 3744, 3766, 3832, 3896,
+ 3912, 3928, 3944, 3968, 4008, 4040, 4056, 4106,
+ 4138, 4170, 4202, 4234, 4266, 4296, 4312, 4344,
+ 4408, 4424, 4442, 4472, 4488, 4504, 6148, 6198,
+ 6264, 6280, 6360, 6429, 6505, 6529, 61448, 61468,
+ 61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704,
+ 61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914,
+ 61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218,
+ 62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554,
+ 62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766,
+ 62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118,
+ 63182, 63242, 63274, 63310, 63368, 63390,
+ };
+#define HIBIT ((unsigned char)0x80)
+ unsigned char aChar[] = {
+ '\0', 'a', 'c', 'e', 'i', 'n',
+ 'o', 'u', 'y', 'y', 'a', 'c',
+ 'd', 'e', 'e', 'g', 'h', 'i',
+ 'j', 'k', 'l', 'n', 'o', 'r',
+ 's', 't', 'u', 'u', 'w', 'y',
+ 'z', 'o', 'u', 'a', 'i', 'o',
+ 'u', 'u'|HIBIT, 'a'|HIBIT, 'g', 'k', 'o',
+ 'o'|HIBIT, 'j', 'g', 'n', 'a'|HIBIT, 'a',
+ 'e', 'i', 'o', 'r', 'u', 's',
+ 't', 'h', 'a', 'e', 'o'|HIBIT, 'o',
+ 'o'|HIBIT, 'y', '\0', '\0', '\0', '\0',
+ '\0', '\0', '\0', '\0', 'a', 'b',
+ 'c'|HIBIT, 'd', 'd', 'e'|HIBIT, 'e', 'e'|HIBIT,
+ 'f', 'g', 'h', 'h', 'i', 'i'|HIBIT,
+ 'k', 'l', 'l'|HIBIT, 'l', 'm', 'n',
+ 'o'|HIBIT, 'p', 'r', 'r'|HIBIT, 'r', 's',
+ 's'|HIBIT, 't', 'u', 'u'|HIBIT, 'v', 'w',
+ 'w', 'x', 'y', 'z', 'h', 't',
+ 'w', 'y', 'a', 'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT,
+ 'e', 'e'|HIBIT, 'e'|HIBIT, 'i', 'o', 'o'|HIBIT,
+ 'o'|HIBIT, 'o'|HIBIT, 'u', 'u'|HIBIT, 'u'|HIBIT, 'y',
+ };
+
+ unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
+ int iRes = 0;
+ int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
+ int iLo = 0;
+ while( iHi>=iLo ){
+ int iTest = (iHi + iLo) / 2;
+ if( key >= aDia[iTest] ){
+ iRes = iTest;
+ iLo = iTest+1;
+ }else{
+ iHi = iTest-1;
+ }
+ }
+ assert( key>=aDia[iRes] );
+ if( bComplex==0 && (aChar[iRes] & 0x80) ) return c;
+ return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F);
+}
+
+
+/*
+** Return true if the argument interpreted as a unicode codepoint
+** is a diacritical modifier character.
+*/
+static int sqlite3Fts5UnicodeIsdiacritic(int c){
+ unsigned int mask0 = 0x08029FDF;
+ unsigned int mask1 = 0x000361F8;
+ if( c<768 || c>817 ) return 0;
+ return (c < 768+32) ?
+ (mask0 & ((unsigned int)1 << (c-768))) :
+ (mask1 & ((unsigned int)1 << (c-768-32)));
+}
+
+
+/*
+** Interpret the argument as a unicode codepoint. If the codepoint
+** is an upper case character that has a lower case equivalent,
+** return the codepoint corresponding to the lower case version.
+** Otherwise, return a copy of the argument.
+**
+** The results are undefined if the value passed to this function
+** is less than zero.
+*/
+static int sqlite3Fts5UnicodeFold(int c, int eRemoveDiacritic){
+ /* Each entry in the following array defines a rule for folding a range
+ ** of codepoints to lower case. The rule applies to a range of nRange
+ ** codepoints starting at codepoint iCode.
+ **
+ ** If the least significant bit in flags is clear, then the rule applies
+ ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
+ ** need to be folded). Or, if it is set, then the rule only applies to
+ ** every second codepoint in the range, starting with codepoint C.
+ **
+ ** The 7 most significant bits in flags are an index into the aiOff[]
+ ** array. If a specific codepoint C does require folding, then its lower
+ ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
+ **
+ ** The contents of this array are generated by parsing the CaseFolding.txt
+ ** file distributed as part of the "Unicode Character Database". See
+ ** http://www.unicode.org for details.
+ */
+ static const struct TableEntry {
+ unsigned short iCode;
+ unsigned char flags;
+ unsigned char nRange;
+ } aEntry[] = {
+ {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
+ {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
+ {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
+ {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
+ {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
+ {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
+ {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
+ {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
+ {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
+ {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
+ {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
+ {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
+ {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
+ {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
+ {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
+ {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
+ {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
+ {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
+ {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
+ {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
+ {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
+ {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
+ {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
+ {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
+ {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
+ {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
+ {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
+ {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
+ {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
+ {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
+ {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
+ {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
+ {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
+ {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
+ {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
+ {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
+ {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
+ {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
+ {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
+ {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
+ {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
+ {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
+ {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
+ {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
+ {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
+ {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
+ {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
+ {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
+ {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
+ {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
+ {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
+ {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
+ {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
+ {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
+ {65313, 14, 26},
+ };
+ static const unsigned short aiOff[] = {
+ 1, 2, 8, 15, 16, 26, 28, 32,
+ 37, 38, 40, 48, 63, 64, 69, 71,
+ 79, 80, 116, 202, 203, 205, 206, 207,
+ 209, 210, 211, 213, 214, 217, 218, 219,
+ 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
+ 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
+ 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
+ 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
+ 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
+ 65514, 65521, 65527, 65528, 65529,
+ };
+
+ int ret = c;
+
+ assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
+
+ if( c<128 ){
+ if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
+ }else if( c<65536 ){
+ const struct TableEntry *p;
+ int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
+ int iLo = 0;
+ int iRes = -1;
+
+ assert( c>aEntry[0].iCode );
+ while( iHi>=iLo ){
+ int iTest = (iHi + iLo) / 2;
+ int cmp = (c - aEntry[iTest].iCode);
+ if( cmp>=0 ){
+ iRes = iTest;
+ iLo = iTest+1;
+ }else{
+ iHi = iTest-1;
+ }
+ }
+
+ assert( iRes>=0 && c>=aEntry[iRes].iCode );
+ p = &aEntry[iRes];
+ if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
+ ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
+ assert( ret>0 );
+ }
+
+ if( eRemoveDiacritic ){
+ ret = fts5_remove_diacritic(ret, eRemoveDiacritic==2);
+ }
+ }
+
+ else if( c>=66560 && c<66600 ){
+ ret = c + 40;
+ }
+
+ return ret;
+}
+
+
+static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
+ aArray[0] = 1;
+ switch( zCat[0] ){
+ case 'C':
+ switch( zCat[1] ){
+ case 'c': aArray[1] = 1; break;
+ case 'f': aArray[2] = 1; break;
+ case 'n': aArray[3] = 1; break;
+ case 's': aArray[4] = 1; break;
+ case 'o': aArray[31] = 1; break;
+ case '*':
+ aArray[1] = 1;
+ aArray[2] = 1;
+ aArray[3] = 1;
+ aArray[4] = 1;
+ aArray[31] = 1;
+ break;
+ default: return 1; }
+ break;
+
+ case 'L':
+ switch( zCat[1] ){
+ case 'l': aArray[5] = 1; break;
+ case 'm': aArray[6] = 1; break;
+ case 'o': aArray[7] = 1; break;
+ case 't': aArray[8] = 1; break;
+ case 'u': aArray[9] = 1; break;
+ case 'C': aArray[30] = 1; break;
+ case '*':
+ aArray[5] = 1;
+ aArray[6] = 1;
+ aArray[7] = 1;
+ aArray[8] = 1;
+ aArray[9] = 1;
+ aArray[30] = 1;
+ break;
+ default: return 1; }
+ break;
+
+ case 'M':
+ switch( zCat[1] ){
+ case 'c': aArray[10] = 1; break;
+ case 'e': aArray[11] = 1; break;
+ case 'n': aArray[12] = 1; break;
+ case '*':
+ aArray[10] = 1;
+ aArray[11] = 1;
+ aArray[12] = 1;
+ break;
+ default: return 1; }
+ break;
+
+ case 'N':
+ switch( zCat[1] ){
+ case 'd': aArray[13] = 1; break;
+ case 'l': aArray[14] = 1; break;
+ case 'o': aArray[15] = 1; break;
+ case '*':
+ aArray[13] = 1;
+ aArray[14] = 1;
+ aArray[15] = 1;
+ break;
+ default: return 1; }
+ break;
+
+ case 'P':
+ switch( zCat[1] ){
+ case 'c': aArray[16] = 1; break;
+ case 'd': aArray[17] = 1; break;
+ case 'e': aArray[18] = 1; break;
+ case 'f': aArray[19] = 1; break;
+ case 'i': aArray[20] = 1; break;
+ case 'o': aArray[21] = 1; break;
+ case 's': aArray[22] = 1; break;
+ case '*':
+ aArray[16] = 1;
+ aArray[17] = 1;
+ aArray[18] = 1;
+ aArray[19] = 1;
+ aArray[20] = 1;
+ aArray[21] = 1;
+ aArray[22] = 1;
+ break;
+ default: return 1; }
+ break;
+
+ case 'S':
+ switch( zCat[1] ){
+ case 'c': aArray[23] = 1; break;
+ case 'k': aArray[24] = 1; break;
+ case 'm': aArray[25] = 1; break;
+ case 'o': aArray[26] = 1; break;
+ case '*':
+ aArray[23] = 1;
+ aArray[24] = 1;
+ aArray[25] = 1;
+ aArray[26] = 1;
+ break;
+ default: return 1; }
+ break;
+
+ case 'Z':
+ switch( zCat[1] ){
+ case 'l': aArray[27] = 1; break;
+ case 'p': aArray[28] = 1; break;
+ case 's': aArray[29] = 1; break;
+ case '*':
+ aArray[27] = 1;
+ aArray[28] = 1;
+ aArray[29] = 1;
+ break;
+ default: return 1; }
+ break;
+
+ }
+ return 0;
+}
+
+static u16 aFts5UnicodeBlock[] = {
+ 0, 1471, 1753, 1760, 1760, 1760, 1760, 1760, 1760, 1760,
+ 1760, 1760, 1760, 1760, 1760, 1763, 1765,
+ };
+static u16 aFts5UnicodeMap[] = {
+ 0, 32, 33, 36, 37, 40, 41, 42, 43, 44,
+ 45, 46, 48, 58, 60, 63, 65, 91, 92, 93,
+ 94, 95, 96, 97, 123, 124, 125, 126, 127, 160,
+ 161, 162, 166, 167, 168, 169, 170, 171, 172, 173,
+ 174, 175, 176, 177, 178, 180, 181, 182, 184, 185,
+ 186, 187, 188, 191, 192, 215, 216, 223, 247, 248,
+ 256, 312, 313, 329, 330, 377, 383, 385, 387, 388,
+ 391, 394, 396, 398, 402, 403, 405, 406, 409, 412,
+ 414, 415, 417, 418, 423, 427, 428, 431, 434, 436,
+ 437, 440, 442, 443, 444, 446, 448, 452, 453, 454,
+ 455, 456, 457, 458, 459, 460, 461, 477, 478, 496,
+ 497, 498, 499, 500, 503, 505, 506, 564, 570, 572,
+ 573, 575, 577, 580, 583, 584, 592, 660, 661, 688,
+ 706, 710, 722, 736, 741, 748, 749, 750, 751, 768,
+ 880, 884, 885, 886, 890, 891, 894, 900, 902, 903,
+ 904, 908, 910, 912, 913, 931, 940, 975, 977, 978,
+ 981, 984, 1008, 1012, 1014, 1015, 1018, 1020, 1021, 1072,
+ 1120, 1154, 1155, 1160, 1162, 1217, 1231, 1232, 1329, 1369,
+ 1370, 1377, 1417, 1418, 1423, 1425, 1470, 1471, 1472, 1473,
+ 1475, 1476, 1478, 1479, 1488, 1520, 1523, 1536, 1542, 1545,
+ 1547, 1548, 1550, 1552, 1563, 1566, 1568, 1600, 1601, 1611,
+ 1632, 1642, 1646, 1648, 1649, 1748, 1749, 1750, 1757, 1758,
+ 1759, 1765, 1767, 1769, 1770, 1774, 1776, 1786, 1789, 1791,
+ 1792, 1807, 1808, 1809, 1810, 1840, 1869, 1958, 1969, 1984,
+ 1994, 2027, 2036, 2038, 2039, 2042, 2048, 2070, 2074, 2075,
+ 2084, 2085, 2088, 2089, 2096, 2112, 2137, 2142, 2208, 2210,
+ 2276, 2304, 2307, 2308, 2362, 2363, 2364, 2365, 2366, 2369,
+ 2377, 2381, 2382, 2384, 2385, 2392, 2402, 2404, 2406, 2416,
+ 2417, 2418, 2425, 2433, 2434, 2437, 2447, 2451, 2474, 2482,
+ 2486, 2492, 2493, 2494, 2497, 2503, 2507, 2509, 2510, 2519,
+ 2524, 2527, 2530, 2534, 2544, 2546, 2548, 2554, 2555, 2561,
+ 2563, 2565, 2575, 2579, 2602, 2610, 2613, 2616, 2620, 2622,
+ 2625, 2631, 2635, 2641, 2649, 2654, 2662, 2672, 2674, 2677,
+ 2689, 2691, 2693, 2703, 2707, 2730, 2738, 2741, 2748, 2749,
+ 2750, 2753, 2759, 2761, 2763, 2765, 2768, 2784, 2786, 2790,
+ 2800, 2801, 2817, 2818, 2821, 2831, 2835, 2858, 2866, 2869,
+ 2876, 2877, 2878, 2879, 2880, 2881, 2887, 2891, 2893, 2902,
+ 2903, 2908, 2911, 2914, 2918, 2928, 2929, 2930, 2946, 2947,
+ 2949, 2958, 2962, 2969, 2972, 2974, 2979, 2984, 2990, 3006,
+ 3008, 3009, 3014, 3018, 3021, 3024, 3031, 3046, 3056, 3059,
+ 3065, 3066, 3073, 3077, 3086, 3090, 3114, 3125, 3133, 3134,
+ 3137, 3142, 3146, 3157, 3160, 3168, 3170, 3174, 3192, 3199,
+ 3202, 3205, 3214, 3218, 3242, 3253, 3260, 3261, 3262, 3263,
+ 3264, 3270, 3271, 3274, 3276, 3285, 3294, 3296, 3298, 3302,
+ 3313, 3330, 3333, 3342, 3346, 3389, 3390, 3393, 3398, 3402,
+ 3405, 3406, 3415, 3424, 3426, 3430, 3440, 3449, 3450, 3458,
+ 3461, 3482, 3507, 3517, 3520, 3530, 3535, 3538, 3542, 3544,
+ 3570, 3572, 3585, 3633, 3634, 3636, 3647, 3648, 3654, 3655,
+ 3663, 3664, 3674, 3713, 3716, 3719, 3722, 3725, 3732, 3737,
+ 3745, 3749, 3751, 3754, 3757, 3761, 3762, 3764, 3771, 3773,
+ 3776, 3782, 3784, 3792, 3804, 3840, 3841, 3844, 3859, 3860,
+ 3861, 3864, 3866, 3872, 3882, 3892, 3893, 3894, 3895, 3896,
+ 3897, 3898, 3899, 3900, 3901, 3902, 3904, 3913, 3953, 3967,
+ 3968, 3973, 3974, 3976, 3981, 3993, 4030, 4038, 4039, 4046,
+ 4048, 4053, 4057, 4096, 4139, 4141, 4145, 4146, 4152, 4153,
+ 4155, 4157, 4159, 4160, 4170, 4176, 4182, 4184, 4186, 4190,
+ 4193, 4194, 4197, 4199, 4206, 4209, 4213, 4226, 4227, 4229,
+ 4231, 4237, 4238, 4239, 4240, 4250, 4253, 4254, 4256, 4295,
+ 4301, 4304, 4347, 4348, 4349, 4682, 4688, 4696, 4698, 4704,
+ 4746, 4752, 4786, 4792, 4800, 4802, 4808, 4824, 4882, 4888,
+ 4957, 4960, 4969, 4992, 5008, 5024, 5120, 5121, 5741, 5743,
+ 5760, 5761, 5787, 5788, 5792, 5867, 5870, 5888, 5902, 5906,
+ 5920, 5938, 5941, 5952, 5970, 5984, 5998, 6002, 6016, 6068,
+ 6070, 6071, 6078, 6086, 6087, 6089, 6100, 6103, 6104, 6107,
+ 6108, 6109, 6112, 6128, 6144, 6150, 6151, 6155, 6158, 6160,
+ 6176, 6211, 6212, 6272, 6313, 6314, 6320, 6400, 6432, 6435,
+ 6439, 6441, 6448, 6450, 6451, 6457, 6464, 6468, 6470, 6480,
+ 6512, 6528, 6576, 6593, 6600, 6608, 6618, 6622, 6656, 6679,
+ 6681, 6686, 6688, 6741, 6742, 6743, 6744, 6752, 6753, 6754,
+ 6755, 6757, 6765, 6771, 6783, 6784, 6800, 6816, 6823, 6824,
+ 6912, 6916, 6917, 6964, 6965, 6966, 6971, 6972, 6973, 6978,
+ 6979, 6981, 6992, 7002, 7009, 7019, 7028, 7040, 7042, 7043,
+ 7073, 7074, 7078, 7080, 7082, 7083, 7084, 7086, 7088, 7098,
+ 7142, 7143, 7144, 7146, 7149, 7150, 7151, 7154, 7164, 7168,
+ 7204, 7212, 7220, 7222, 7227, 7232, 7245, 7248, 7258, 7288,
+ 7294, 7360, 7376, 7379, 7380, 7393, 7394, 7401, 7405, 7406,
+ 7410, 7412, 7413, 7424, 7468, 7531, 7544, 7545, 7579, 7616,
+ 7676, 7680, 7830, 7838, 7936, 7944, 7952, 7960, 7968, 7976,
+ 7984, 7992, 8000, 8008, 8016, 8025, 8027, 8029, 8031, 8033,
+ 8040, 8048, 8064, 8072, 8080, 8088, 8096, 8104, 8112, 8118,
+ 8120, 8124, 8125, 8126, 8127, 8130, 8134, 8136, 8140, 8141,
+ 8144, 8150, 8152, 8157, 8160, 8168, 8173, 8178, 8182, 8184,
+ 8188, 8189, 8192, 8203, 8208, 8214, 8216, 8217, 8218, 8219,
+ 8221, 8222, 8223, 8224, 8232, 8233, 8234, 8239, 8240, 8249,
+ 8250, 8251, 8255, 8257, 8260, 8261, 8262, 8263, 8274, 8275,
+ 8276, 8277, 8287, 8288, 8298, 8304, 8305, 8308, 8314, 8317,
+ 8318, 8319, 8320, 8330, 8333, 8334, 8336, 8352, 8400, 8413,
+ 8417, 8418, 8421, 8448, 8450, 8451, 8455, 8456, 8458, 8459,
+ 8462, 8464, 8467, 8468, 8469, 8470, 8472, 8473, 8478, 8484,
+ 8485, 8486, 8487, 8488, 8489, 8490, 8494, 8495, 8496, 8500,
+ 8501, 8505, 8506, 8508, 8510, 8512, 8517, 8519, 8522, 8523,
+ 8524, 8526, 8527, 8528, 8544, 8579, 8581, 8585, 8592, 8597,
+ 8602, 8604, 8608, 8609, 8611, 8612, 8614, 8615, 8622, 8623,
+ 8654, 8656, 8658, 8659, 8660, 8661, 8692, 8960, 8968, 8972,
+ 8992, 8994, 9001, 9002, 9003, 9084, 9085, 9115, 9140, 9180,
+ 9186, 9216, 9280, 9312, 9372, 9450, 9472, 9655, 9656, 9665,
+ 9666, 9720, 9728, 9839, 9840, 9985, 10088, 10089, 10090, 10091,
+ 10092, 10093, 10094, 10095, 10096, 10097, 10098, 10099, 10100, 10101,
+ 10102, 10132, 10176, 10181, 10182, 10183, 10214, 10215, 10216, 10217,
+ 10218, 10219, 10220, 10221, 10222, 10223, 10224, 10240, 10496, 10627,
+ 10628, 10629, 10630, 10631, 10632, 10633, 10634, 10635, 10636, 10637,
+ 10638, 10639, 10640, 10641, 10642, 10643, 10644, 10645, 10646, 10647,
+ 10648, 10649, 10712, 10713, 10714, 10715, 10716, 10748, 10749, 10750,
+ 11008, 11056, 11077, 11079, 11088, 11264, 11312, 11360, 11363, 11365,
+ 11367, 11374, 11377, 11378, 11380, 11381, 11383, 11388, 11390, 11393,
+ 11394, 11492, 11493, 11499, 11503, 11506, 11513, 11517, 11518, 11520,
+ 11559, 11565, 11568, 11631, 11632, 11647, 11648, 11680, 11688, 11696,
+ 11704, 11712, 11720, 11728, 11736, 11744, 11776, 11778, 11779, 11780,
+ 11781, 11782, 11785, 11786, 11787, 11788, 11789, 11790, 11799, 11800,
+ 11802, 11803, 11804, 11805, 11806, 11808, 11809, 11810, 11811, 11812,
+ 11813, 11814, 11815, 11816, 11817, 11818, 11823, 11824, 11834, 11904,
+ 11931, 12032, 12272, 12288, 12289, 12292, 12293, 12294, 12295, 12296,
+ 12297, 12298, 12299, 12300, 12301, 12302, 12303, 12304, 12305, 12306,
+ 12308, 12309, 12310, 12311, 12312, 12313, 12314, 12315, 12316, 12317,
+ 12318, 12320, 12321, 12330, 12334, 12336, 12337, 12342, 12344, 12347,
+ 12348, 12349, 12350, 12353, 12441, 12443, 12445, 12447, 12448, 12449,
+ 12539, 12540, 12543, 12549, 12593, 12688, 12690, 12694, 12704, 12736,
+ 12784, 12800, 12832, 12842, 12872, 12880, 12881, 12896, 12928, 12938,
+ 12977, 12992, 13056, 13312, 19893, 19904, 19968, 40908, 40960, 40981,
+ 40982, 42128, 42192, 42232, 42238, 42240, 42508, 42509, 42512, 42528,
+ 42538, 42560, 42606, 42607, 42608, 42611, 42612, 42622, 42623, 42624,
+ 42655, 42656, 42726, 42736, 42738, 42752, 42775, 42784, 42786, 42800,
+ 42802, 42864, 42865, 42873, 42878, 42888, 42889, 42891, 42896, 42912,
+ 43000, 43002, 43003, 43010, 43011, 43014, 43015, 43019, 43020, 43043,
+ 43045, 43047, 43048, 43056, 43062, 43064, 43065, 43072, 43124, 43136,
+ 43138, 43188, 43204, 43214, 43216, 43232, 43250, 43256, 43259, 43264,
+ 43274, 43302, 43310, 43312, 43335, 43346, 43359, 43360, 43392, 43395,
+ 43396, 43443, 43444, 43446, 43450, 43452, 43453, 43457, 43471, 43472,
+ 43486, 43520, 43561, 43567, 43569, 43571, 43573, 43584, 43587, 43588,
+ 43596, 43597, 43600, 43612, 43616, 43632, 43633, 43639, 43642, 43643,
+ 43648, 43696, 43697, 43698, 43701, 43703, 43705, 43710, 43712, 43713,
+ 43714, 43739, 43741, 43742, 43744, 43755, 43756, 43758, 43760, 43762,
+ 43763, 43765, 43766, 43777, 43785, 43793, 43808, 43816, 43968, 44003,
+ 44005, 44006, 44008, 44009, 44011, 44012, 44013, 44016, 44032, 55203,
+ 55216, 55243, 55296, 56191, 56319, 57343, 57344, 63743, 63744, 64112,
+ 64256, 64275, 64285, 64286, 64287, 64297, 64298, 64312, 64318, 64320,
+ 64323, 64326, 64434, 64467, 64830, 64831, 64848, 64914, 65008, 65020,
+ 65021, 65024, 65040, 65047, 65048, 65049, 65056, 65072, 65073, 65075,
+ 65077, 65078, 65079, 65080, 65081, 65082, 65083, 65084, 65085, 65086,
+ 65087, 65088, 65089, 65090, 65091, 65092, 65093, 65095, 65096, 65097,
+ 65101, 65104, 65108, 65112, 65113, 65114, 65115, 65116, 65117, 65118,
+ 65119, 65122, 65123, 65124, 65128, 65129, 65130, 65136, 65142, 65279,
+ 65281, 65284, 65285, 65288, 65289, 65290, 65291, 65292, 65293, 65294,
+ 65296, 65306, 65308, 65311, 65313, 65339, 65340, 65341, 65342, 65343,
+ 65344, 65345, 65371, 65372, 65373, 65374, 65375, 65376, 65377, 65378,
+ 65379, 65380, 65382, 65392, 65393, 65438, 65440, 65474, 65482, 65490,
+ 65498, 65504, 65506, 65507, 65508, 65509, 65512, 65513, 65517, 65529,
+ 65532, 0, 13, 40, 60, 63, 80, 128, 256, 263,
+ 311, 320, 373, 377, 394, 400, 464, 509, 640, 672,
+ 768, 800, 816, 833, 834, 842, 896, 927, 928, 968,
+ 976, 977, 1024, 1064, 1104, 1184, 2048, 2056, 2058, 2103,
+ 2108, 2111, 2135, 2136, 2304, 2326, 2335, 2336, 2367, 2432,
+ 2494, 2560, 2561, 2565, 2572, 2576, 2581, 2585, 2616, 2623,
+ 2624, 2640, 2656, 2685, 2687, 2816, 2873, 2880, 2904, 2912,
+ 2936, 3072, 3680, 4096, 4097, 4098, 4099, 4152, 4167, 4178,
+ 4198, 4224, 4226, 4227, 4272, 4275, 4279, 4281, 4283, 4285,
+ 4286, 4304, 4336, 4352, 4355, 4391, 4396, 4397, 4406, 4416,
+ 4480, 4482, 4483, 4531, 4534, 4543, 4545, 4549, 4560, 5760,
+ 5803, 5804, 5805, 5806, 5808, 5814, 5815, 5824, 8192, 9216,
+ 9328, 12288, 26624, 28416, 28496, 28497, 28559, 28563, 45056, 53248,
+ 53504, 53545, 53605, 53607, 53610, 53613, 53619, 53627, 53635, 53637,
+ 53644, 53674, 53678, 53760, 53826, 53829, 54016, 54112, 54272, 54298,
+ 54324, 54350, 54358, 54376, 54402, 54428, 54430, 54434, 54437, 54441,
+ 54446, 54454, 54459, 54461, 54469, 54480, 54506, 54532, 54535, 54541,
+ 54550, 54558, 54584, 54587, 54592, 54598, 54602, 54610, 54636, 54662,
+ 54688, 54714, 54740, 54766, 54792, 54818, 54844, 54870, 54896, 54922,
+ 54952, 54977, 54978, 55003, 55004, 55010, 55035, 55036, 55061, 55062,
+ 55068, 55093, 55094, 55119, 55120, 55126, 55151, 55152, 55177, 55178,
+ 55184, 55209, 55210, 55235, 55236, 55242, 55246, 60928, 60933, 60961,
+ 60964, 60967, 60969, 60980, 60985, 60987, 60994, 60999, 61001, 61003,
+ 61005, 61009, 61012, 61015, 61017, 61019, 61021, 61023, 61025, 61028,
+ 61031, 61036, 61044, 61049, 61054, 61056, 61067, 61089, 61093, 61099,
+ 61168, 61440, 61488, 61600, 61617, 61633, 61649, 61696, 61712, 61744,
+ 61808, 61926, 61968, 62016, 62032, 62208, 62256, 62263, 62336, 62368,
+ 62406, 62432, 62464, 62528, 62530, 62713, 62720, 62784, 62800, 62971,
+ 63045, 63104, 63232, 0, 42710, 42752, 46900, 46912, 47133, 63488,
+ 1, 32, 256, 0, 65533,
+ };
+static u16 aFts5UnicodeData[] = {
+ 1025, 61, 117, 55, 117, 54, 50, 53, 57, 53,
+ 49, 85, 333, 85, 121, 85, 841, 54, 53, 50,
+ 56, 48, 56, 837, 54, 57, 50, 57, 1057, 61,
+ 53, 151, 58, 53, 56, 58, 39, 52, 57, 34,
+ 58, 56, 58, 57, 79, 56, 37, 85, 56, 47,
+ 39, 51, 111, 53, 745, 57, 233, 773, 57, 261,
+ 1822, 37, 542, 37, 1534, 222, 69, 73, 37, 126,
+ 126, 73, 69, 137, 37, 73, 37, 105, 101, 73,
+ 37, 73, 37, 190, 158, 37, 126, 126, 73, 37,
+ 126, 94, 37, 39, 94, 69, 135, 41, 40, 37,
+ 41, 40, 37, 41, 40, 37, 542, 37, 606, 37,
+ 41, 40, 37, 126, 73, 37, 1886, 197, 73, 37,
+ 73, 69, 126, 105, 37, 286, 2181, 39, 869, 582,
+ 152, 390, 472, 166, 248, 38, 56, 38, 568, 3596,
+ 158, 38, 56, 94, 38, 101, 53, 88, 41, 53,
+ 105, 41, 73, 37, 553, 297, 1125, 94, 37, 105,
+ 101, 798, 133, 94, 57, 126, 94, 37, 1641, 1541,
+ 1118, 58, 172, 75, 1790, 478, 37, 2846, 1225, 38,
+ 213, 1253, 53, 49, 55, 1452, 49, 44, 53, 76,
+ 53, 76, 53, 44, 871, 103, 85, 162, 121, 85,
+ 55, 85, 90, 364, 53, 85, 1031, 38, 327, 684,
+ 333, 149, 71, 44, 3175, 53, 39, 236, 34, 58,
+ 204, 70, 76, 58, 140, 71, 333, 103, 90, 39,
+ 469, 34, 39, 44, 967, 876, 2855, 364, 39, 333,
+ 1063, 300, 70, 58, 117, 38, 711, 140, 38, 300,
+ 38, 108, 38, 172, 501, 807, 108, 53, 39, 359,
+ 876, 108, 42, 1735, 44, 42, 44, 39, 106, 268,
+ 138, 44, 74, 39, 236, 327, 76, 85, 333, 53,
+ 38, 199, 231, 44, 74, 263, 71, 711, 231, 39,
+ 135, 44, 39, 106, 140, 74, 74, 44, 39, 42,
+ 71, 103, 76, 333, 71, 87, 207, 58, 55, 76,
+ 42, 199, 71, 711, 231, 71, 71, 71, 44, 106,
+ 76, 76, 108, 44, 135, 39, 333, 76, 103, 44,
+ 76, 42, 295, 103, 711, 231, 71, 167, 44, 39,
+ 106, 172, 76, 42, 74, 44, 39, 71, 76, 333,
+ 53, 55, 44, 74, 263, 71, 711, 231, 71, 167,
+ 44, 39, 42, 44, 42, 140, 74, 74, 44, 44,
+ 42, 71, 103, 76, 333, 58, 39, 207, 44, 39,
+ 199, 103, 135, 71, 39, 71, 71, 103, 391, 74,
+ 44, 74, 106, 106, 44, 39, 42, 333, 111, 218,
+ 55, 58, 106, 263, 103, 743, 327, 167, 39, 108,
+ 138, 108, 140, 76, 71, 71, 76, 333, 239, 58,
+ 74, 263, 103, 743, 327, 167, 44, 39, 42, 44,
+ 170, 44, 74, 74, 76, 74, 39, 71, 76, 333,
+ 71, 74, 263, 103, 1319, 39, 106, 140, 106, 106,
+ 44, 39, 42, 71, 76, 333, 207, 58, 199, 74,
+ 583, 775, 295, 39, 231, 44, 106, 108, 44, 266,
+ 74, 53, 1543, 44, 71, 236, 55, 199, 38, 268,
+ 53, 333, 85, 71, 39, 71, 39, 39, 135, 231,
+ 103, 39, 39, 71, 135, 44, 71, 204, 76, 39,
+ 167, 38, 204, 333, 135, 39, 122, 501, 58, 53,
+ 122, 76, 218, 333, 335, 58, 44, 58, 44, 58,
+ 44, 54, 50, 54, 50, 74, 263, 1159, 460, 42,
+ 172, 53, 76, 167, 364, 1164, 282, 44, 218, 90,
+ 181, 154, 85, 1383, 74, 140, 42, 204, 42, 76,
+ 74, 76, 39, 333, 213, 199, 74, 76, 135, 108,
+ 39, 106, 71, 234, 103, 140, 423, 44, 74, 76,
+ 202, 44, 39, 42, 333, 106, 44, 90, 1225, 41,
+ 41, 1383, 53, 38, 10631, 135, 231, 39, 135, 1319,
+ 135, 1063, 135, 231, 39, 135, 487, 1831, 135, 2151,
+ 108, 309, 655, 519, 346, 2727, 49, 19847, 85, 551,
+ 61, 839, 54, 50, 2407, 117, 110, 423, 135, 108,
+ 583, 108, 85, 583, 76, 423, 103, 76, 1671, 76,
+ 42, 236, 266, 44, 74, 364, 117, 38, 117, 55,
+ 39, 44, 333, 335, 213, 49, 149, 108, 61, 333,
+ 1127, 38, 1671, 1319, 44, 39, 2247, 935, 108, 138,
+ 76, 106, 74, 44, 202, 108, 58, 85, 333, 967,
+ 167, 1415, 554, 231, 74, 333, 47, 1114, 743, 76,
+ 106, 85, 1703, 42, 44, 42, 236, 44, 42, 44,
+ 74, 268, 202, 332, 44, 333, 333, 245, 38, 213,
+ 140, 42, 1511, 44, 42, 172, 42, 44, 170, 44,
+ 74, 231, 333, 245, 346, 300, 314, 76, 42, 967,
+ 42, 140, 74, 76, 42, 44, 74, 71, 333, 1415,
+ 44, 42, 76, 106, 44, 42, 108, 74, 149, 1159,
+ 266, 268, 74, 76, 181, 333, 103, 333, 967, 198,
+ 85, 277, 108, 53, 428, 42, 236, 135, 44, 135,
+ 74, 44, 71, 1413, 2022, 421, 38, 1093, 1190, 1260,
+ 140, 4830, 261, 3166, 261, 265, 197, 201, 261, 265,
+ 261, 265, 197, 201, 261, 41, 41, 41, 94, 229,
+ 265, 453, 261, 264, 261, 264, 261, 264, 165, 69,
+ 137, 40, 56, 37, 120, 101, 69, 137, 40, 120,
+ 133, 69, 137, 120, 261, 169, 120, 101, 69, 137,
+ 40, 88, 381, 162, 209, 85, 52, 51, 54, 84,
+ 51, 54, 52, 277, 59, 60, 162, 61, 309, 52,
+ 51, 149, 80, 117, 57, 54, 50, 373, 57, 53,
+ 48, 341, 61, 162, 194, 47, 38, 207, 121, 54,
+ 50, 38, 335, 121, 54, 50, 422, 855, 428, 139,
+ 44, 107, 396, 90, 41, 154, 41, 90, 37, 105,
+ 69, 105, 37, 58, 41, 90, 57, 169, 218, 41,
+ 58, 41, 58, 41, 58, 137, 58, 37, 137, 37,
+ 135, 37, 90, 69, 73, 185, 94, 101, 58, 57,
+ 90, 37, 58, 527, 1134, 94, 142, 47, 185, 186,
+ 89, 154, 57, 90, 57, 90, 57, 250, 57, 1018,
+ 89, 90, 57, 58, 57, 1018, 8601, 282, 153, 666,
+ 89, 250, 54, 50, 2618, 57, 986, 825, 1306, 217,
+ 602, 1274, 378, 1935, 2522, 719, 5882, 57, 314, 57,
+ 1754, 281, 3578, 57, 4634, 3322, 54, 50, 54, 50,
+ 54, 50, 54, 50, 54, 50, 54, 50, 54, 50,
+ 975, 1434, 185, 54, 50, 1017, 54, 50, 54, 50,
+ 54, 50, 54, 50, 54, 50, 537, 8218, 4217, 54,
+ 50, 54, 50, 54, 50, 54, 50, 54, 50, 54,
+ 50, 54, 50, 54, 50, 54, 50, 54, 50, 54,
+ 50, 2041, 54, 50, 54, 50, 1049, 54, 50, 8281,
+ 1562, 697, 90, 217, 346, 1513, 1509, 126, 73, 69,
+ 254, 105, 37, 94, 37, 94, 165, 70, 105, 37,
+ 3166, 37, 218, 158, 108, 94, 149, 47, 85, 1221,
+ 37, 37, 1799, 38, 53, 44, 743, 231, 231, 231,
+ 231, 231, 231, 231, 231, 1036, 85, 52, 51, 52,
+ 51, 117, 52, 51, 53, 52, 51, 309, 49, 85,
+ 49, 53, 52, 51, 85, 52, 51, 54, 50, 54,
+ 50, 54, 50, 54, 50, 181, 38, 341, 81, 858,
+ 2874, 6874, 410, 61, 117, 58, 38, 39, 46, 54,
+ 50, 54, 50, 54, 50, 54, 50, 54, 50, 90,
+ 54, 50, 54, 50, 54, 50, 54, 50, 49, 54,
+ 82, 58, 302, 140, 74, 49, 166, 90, 110, 38,
+ 39, 53, 90, 2759, 76, 88, 70, 39, 49, 2887,
+ 53, 102, 39, 1319, 3015, 90, 143, 346, 871, 1178,
+ 519, 1018, 335, 986, 271, 58, 495, 1050, 335, 1274,
+ 495, 2042, 8218, 39, 39, 2074, 39, 39, 679, 38,
+ 36583, 1786, 1287, 198, 85, 8583, 38, 117, 519, 333,
+ 71, 1502, 39, 44, 107, 53, 332, 53, 38, 798,
+ 44, 2247, 334, 76, 213, 760, 294, 88, 478, 69,
+ 2014, 38, 261, 190, 350, 38, 88, 158, 158, 382,
+ 70, 37, 231, 44, 103, 44, 135, 44, 743, 74,
+ 76, 42, 154, 207, 90, 55, 58, 1671, 149, 74,
+ 1607, 522, 44, 85, 333, 588, 199, 117, 39, 333,
+ 903, 268, 85, 743, 364, 74, 53, 935, 108, 42,
+ 1511, 44, 74, 140, 74, 44, 138, 437, 38, 333,
+ 85, 1319, 204, 74, 76, 74, 76, 103, 44, 263,
+ 44, 42, 333, 149, 519, 38, 199, 122, 39, 42,
+ 1543, 44, 39, 108, 71, 76, 167, 76, 39, 44,
+ 39, 71, 38, 85, 359, 42, 76, 74, 85, 39,
+ 70, 42, 44, 199, 199, 199, 231, 231, 1127, 74,
+ 44, 74, 44, 74, 53, 42, 44, 333, 39, 39,
+ 743, 1575, 36, 68, 68, 36, 63, 63, 11719, 3399,
+ 229, 165, 39, 44, 327, 57, 423, 167, 39, 71,
+ 71, 3463, 536, 11623, 54, 50, 2055, 1735, 391, 55,
+ 58, 524, 245, 54, 50, 53, 236, 53, 81, 80,
+ 54, 50, 54, 50, 54, 50, 54, 50, 54, 50,
+ 54, 50, 54, 50, 54, 50, 85, 54, 50, 149,
+ 112, 117, 149, 49, 54, 50, 54, 50, 54, 50,
+ 117, 57, 49, 121, 53, 55, 85, 167, 4327, 34,
+ 117, 55, 117, 54, 50, 53, 57, 53, 49, 85,
+ 333, 85, 121, 85, 841, 54, 53, 50, 56, 48,
+ 56, 837, 54, 57, 50, 57, 54, 50, 53, 54,
+ 50, 85, 327, 38, 1447, 70, 999, 199, 199, 199,
+ 103, 87, 57, 56, 58, 87, 58, 153, 90, 98,
+ 90, 391, 839, 615, 71, 487, 455, 3943, 117, 1455,
+ 314, 1710, 143, 570, 47, 410, 1466, 44, 935, 1575,
+ 999, 143, 551, 46, 263, 46, 967, 53, 1159, 263,
+ 53, 174, 1289, 1285, 2503, 333, 199, 39, 1415, 71,
+ 39, 743, 53, 271, 711, 207, 53, 839, 53, 1799,
+ 71, 39, 108, 76, 140, 135, 103, 871, 108, 44,
+ 271, 309, 935, 79, 53, 1735, 245, 711, 271, 615,
+ 271, 2343, 1007, 42, 44, 42, 1703, 492, 245, 655,
+ 333, 76, 42, 1447, 106, 140, 74, 76, 85, 34,
+ 149, 807, 333, 108, 1159, 172, 42, 268, 333, 149,
+ 76, 42, 1543, 106, 300, 74, 135, 149, 333, 1383,
+ 44, 42, 44, 74, 204, 42, 44, 333, 28135, 3182,
+ 149, 34279, 18215, 2215, 39, 1482, 140, 422, 71, 7898,
+ 1274, 1946, 74, 108, 122, 202, 258, 268, 90, 236,
+ 986, 140, 1562, 2138, 108, 58, 2810, 591, 841, 837,
+ 841, 229, 581, 841, 837, 41, 73, 41, 73, 137,
+ 265, 133, 37, 229, 357, 841, 837, 73, 137, 265,
+ 233, 837, 73, 137, 169, 41, 233, 837, 841, 837,
+ 841, 837, 841, 837, 841, 837, 841, 837, 841, 901,
+ 809, 57, 805, 57, 197, 809, 57, 805, 57, 197,
+ 809, 57, 805, 57, 197, 809, 57, 805, 57, 197,
+ 809, 57, 805, 57, 197, 94, 1613, 135, 871, 71,
+ 39, 39, 327, 135, 39, 39, 39, 39, 39, 39,
+ 103, 71, 39, 39, 39, 39, 39, 39, 71, 39,
+ 135, 231, 135, 135, 39, 327, 551, 103, 167, 551,
+ 89, 1434, 3226, 506, 474, 506, 506, 367, 1018, 1946,
+ 1402, 954, 1402, 314, 90, 1082, 218, 2266, 666, 1210,
+ 186, 570, 2042, 58, 5850, 154, 2010, 154, 794, 2266,
+ 378, 2266, 3738, 39, 39, 39, 39, 39, 39, 17351,
+ 34, 3074, 7692, 63, 63,
+ };
+
+static int sqlite3Fts5UnicodeCategory(u32 iCode) {
+ int iRes = -1;
+ int iHi;
+ int iLo;
+ int ret;
+ u16 iKey;
+
+ if( iCode>=(1<<20) ){
+ return 0;
+ }
+ iLo = aFts5UnicodeBlock[(iCode>>16)];
+ iHi = aFts5UnicodeBlock[1+(iCode>>16)];
+ iKey = (iCode & 0xFFFF);
+ while( iHi>iLo ){
+ int iTest = (iHi + iLo) / 2;
+ assert( iTest>=iLo && iTest<iHi );
+ if( iKey>=aFts5UnicodeMap[iTest] ){
+ iRes = iTest;
+ iLo = iTest+1;
+ }else{
+ iHi = iTest;
+ }
+ }
+
+ if( iRes<0 ) return 0;
+ if( iKey>=(aFts5UnicodeMap[iRes]+(aFts5UnicodeData[iRes]>>5)) ) return 0;
+ ret = aFts5UnicodeData[iRes] & 0x1F;
+ if( ret!=30 ) return ret;
+ return ((iKey - aFts5UnicodeMap[iRes]) & 0x01) ? 5 : 9;
+}
+
+static void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){
+ int i = 0;
+ int iTbl = 0;
+ while( i<128 ){
+ int bToken = aArray[ aFts5UnicodeData[iTbl] & 0x1F ];
+ int n = (aFts5UnicodeData[iTbl] >> 5) + i;
+ for(; i<128 && i<n; i++){
+ aAscii[i] = (u8)bToken;
+ }
+ iTbl++;
+ }
+}
+
+/*
+** 2015 May 30
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** Routines for varint serialization and deserialization.
+*/
+
+
+/* #include "fts5Int.h" */
+
+/*
+** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
+** Except, this version does handle the single byte case that the core
+** version depends on being handled before its function is called.
+*/
+static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
+ u32 a,b;
+
+ /* The 1-byte case. Overwhelmingly the most common. */
+ a = *p;
+ /* a: p0 (unmasked) */
+ if (!(a&0x80))
+ {
+ /* Values between 0 and 127 */
+ *v = a;
+ return 1;
+ }
+
+ /* The 2-byte case */
+ p++;
+ b = *p;
+ /* b: p1 (unmasked) */
+ if (!(b&0x80))
+ {
+ /* Values between 128 and 16383 */
+ a &= 0x7f;
+ a = a<<7;
+ *v = a | b;
+ return 2;
+ }
+
+ /* The 3-byte case */
+ p++;
+ a = a<<14;
+ a |= *p;
+ /* a: p0<<14 | p2 (unmasked) */
+ if (!(a&0x80))
+ {
+ /* Values between 16384 and 2097151 */
+ a &= (0x7f<<14)|(0x7f);
+ b &= 0x7f;
+ b = b<<7;
+ *v = a | b;
+ return 3;
+ }
+
+ /* A 32-bit varint is used to store size information in btrees.
+ ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
+ ** A 3-byte varint is sufficient, for example, to record the size
+ ** of a 1048569-byte BLOB or string.
+ **
+ ** We only unroll the first 1-, 2-, and 3- byte cases. The very
+ ** rare larger cases can be handled by the slower 64-bit varint
+ ** routine.
+ */
+ {
+ u64 v64;
+ u8 n;
+ p -= 2;
+ n = sqlite3Fts5GetVarint(p, &v64);
+ *v = ((u32)v64) & 0x7FFFFFFF;
+ assert( n>3 && n<=9 );
+ return n;
+ }
+}
+
+
+/*
+** Bitmasks used by sqlite3GetVarint(). These precomputed constants
+** are defined here rather than simply putting the constant expressions
+** inline in order to work around bugs in the RVT compiler.
+**
+** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
+**
+** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
+*/
+#define SLOT_2_0 0x001fc07f
+#define SLOT_4_2_0 0xf01fc07f
+
+/*
+** Read a 64-bit variable-length integer from memory starting at p[0].
+** Return the number of bytes read. The value is stored in *v.
+*/
+static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
+ u32 a,b,s;
+
+ a = *p;
+ /* a: p0 (unmasked) */
+ if (!(a&0x80))
+ {
+ *v = a;
+ return 1;
+ }
+
+ p++;
+ b = *p;
+ /* b: p1 (unmasked) */
+ if (!(b&0x80))
+ {
+ a &= 0x7f;
+ a = a<<7;
+ a |= b;
+ *v = a;
+ return 2;
+ }
+
+ /* Verify that constants are precomputed correctly */
+ assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
+ assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
+
+ p++;
+ a = a<<14;
+ a |= *p;
+ /* a: p0<<14 | p2 (unmasked) */
+ if (!(a&0x80))
+ {
+ a &= SLOT_2_0;
+ b &= 0x7f;
+ b = b<<7;
+ a |= b;
+ *v = a;
+ return 3;
+ }
+
+ /* CSE1 from below */
+ a &= SLOT_2_0;
+ p++;
+ b = b<<14;
+ b |= *p;
+ /* b: p1<<14 | p3 (unmasked) */
+ if (!(b&0x80))
+ {
+ b &= SLOT_2_0;
+ /* moved CSE1 up */
+ /* a &= (0x7f<<14)|(0x7f); */
+ a = a<<7;
+ a |= b;
+ *v = a;
+ return 4;
+ }
+
+ /* a: p0<<14 | p2 (masked) */
+ /* b: p1<<14 | p3 (unmasked) */
+ /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
+ /* moved CSE1 up */
+ /* a &= (0x7f<<14)|(0x7f); */
+ b &= SLOT_2_0;
+ s = a;
+ /* s: p0<<14 | p2 (masked) */
+
+ p++;
+ a = a<<14;
+ a |= *p;
+ /* a: p0<<28 | p2<<14 | p4 (unmasked) */
+ if (!(a&0x80))
+ {
+ /* we can skip these cause they were (effectively) done above in calc'ing s */
+ /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
+ /* b &= (0x7f<<14)|(0x7f); */
+ b = b<<7;
+ a |= b;
+ s = s>>18;
+ *v = ((u64)s)<<32 | a;
+ return 5;
+ }
+
+ /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
+ s = s<<7;
+ s |= b;
+ /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
+
+ p++;
+ b = b<<14;
+ b |= *p;
+ /* b: p1<<28 | p3<<14 | p5 (unmasked) */
+ if (!(b&0x80))
+ {
+ /* we can skip this cause it was (effectively) done above in calc'ing s */
+ /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
+ a &= SLOT_2_0;
+ a = a<<7;
+ a |= b;
+ s = s>>18;
+ *v = ((u64)s)<<32 | a;
+ return 6;
+ }
+
+ p++;
+ a = a<<14;
+ a |= *p;
+ /* a: p2<<28 | p4<<14 | p6 (unmasked) */
+ if (!(a&0x80))
+ {
+ a &= SLOT_4_2_0;
+ b &= SLOT_2_0;
+ b = b<<7;
+ a |= b;
+ s = s>>11;
+ *v = ((u64)s)<<32 | a;
+ return 7;
+ }
+
+ /* CSE2 from below */
+ a &= SLOT_2_0;
+ p++;
+ b = b<<14;
+ b |= *p;
+ /* b: p3<<28 | p5<<14 | p7 (unmasked) */
+ if (!(b&0x80))
+ {
+ b &= SLOT_4_2_0;
+ /* moved CSE2 up */
+ /* a &= (0x7f<<14)|(0x7f); */
+ a = a<<7;
+ a |= b;
+ s = s>>4;
+ *v = ((u64)s)<<32 | a;
+ return 8;
+ }
+
+ p++;
+ a = a<<15;
+ a |= *p;
+ /* a: p4<<29 | p6<<15 | p8 (unmasked) */
+
+ /* moved CSE2 up */
+ /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
+ b &= SLOT_2_0;
+ b = b<<8;
+ a |= b;
+
+ s = s<<4;
+ b = p[-4];
+ b &= 0x7f;
+ b = b>>3;
+ s |= b;
+
+ *v = ((u64)s)<<32 | a;
+
+ return 9;
+}
+
+/*
+** The variable-length integer encoding is as follows:
+**
+** KEY:
+** A = 0xxxxxxx 7 bits of data and one flag bit
+** B = 1xxxxxxx 7 bits of data and one flag bit
+** C = xxxxxxxx 8 bits of data
+**
+** 7 bits - A
+** 14 bits - BA
+** 21 bits - BBA
+** 28 bits - BBBA
+** 35 bits - BBBBA
+** 42 bits - BBBBBA
+** 49 bits - BBBBBBA
+** 56 bits - BBBBBBBA
+** 64 bits - BBBBBBBBC
+*/
+
+#ifdef SQLITE_NOINLINE
+# define FTS5_NOINLINE SQLITE_NOINLINE
+#else
+# define FTS5_NOINLINE
+#endif
+
+/*
+** Write a 64-bit variable-length integer to memory starting at p[0].
+** The length of data write will be between 1 and 9 bytes. The number
+** of bytes written is returned.
+**
+** A variable-length integer consists of the lower 7 bits of each byte
+** for all bytes that have the 8th bit set and one byte with the 8th
+** bit clear. Except, if we get to the 9th byte, it stores the full
+** 8 bits and is the last byte.
+*/
+static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
+ int i, j, n;
+ u8 buf[10];
+ if( v & (((u64)0xff000000)<<32) ){
+ p[8] = (u8)v;
+ v >>= 8;
+ for(i=7; i>=0; i--){
+ p[i] = (u8)((v & 0x7f) | 0x80);
+ v >>= 7;
+ }
+ return 9;
+ }
+ n = 0;
+ do{
+ buf[n++] = (u8)((v & 0x7f) | 0x80);
+ v >>= 7;
+ }while( v!=0 );
+ buf[0] &= 0x7f;
+ assert( n<=9 );
+ for(i=0, j=n-1; j>=0; j--, i++){
+ p[i] = buf[j];
+ }
+ return n;
+}
+
+static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
+ if( v<=0x7f ){
+ p[0] = v&0x7f;
+ return 1;
+ }
+ if( v<=0x3fff ){
+ p[0] = ((v>>7)&0x7f)|0x80;
+ p[1] = v&0x7f;
+ return 2;
+ }
+ return fts5PutVarint64(p,v);
+}
+
+
+static int sqlite3Fts5GetVarintLen(u32 iVal){
+#if 0
+ if( iVal<(1 << 7 ) ) return 1;
+#endif
+ assert( iVal>=(1 << 7) );
+ if( iVal<(1 << 14) ) return 2;
+ if( iVal<(1 << 21) ) return 3;
+ if( iVal<(1 << 28) ) return 4;
+ return 5;
+}
+
+/*
+** 2015 May 08
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This is an SQLite virtual table module implementing direct access to an
+** existing FTS5 index. The module may create several different types of
+** tables:
+**
+** col:
+** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
+**
+** One row for each term/column combination. The value of $doc is set to
+** the number of fts5 rows that contain at least one instance of term
+** $term within column $col. Field $cnt is set to the total number of
+** instances of term $term in column $col (in any row of the fts5 table).
+**
+** row:
+** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
+**
+** One row for each term in the database. The value of $doc is set to
+** the number of fts5 rows that contain at least one instance of term
+** $term. Field $cnt is set to the total number of instances of term
+** $term in the database.
+**
+** instance:
+** CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));
+**
+** One row for each term instance in the database.
+*/
+
+
+/* #include "fts5Int.h" */
+
+
+typedef struct Fts5VocabTable Fts5VocabTable;
+typedef struct Fts5VocabCursor Fts5VocabCursor;
+
+struct Fts5VocabTable {
+ sqlite3_vtab base;
+ char *zFts5Tbl; /* Name of fts5 table */
+ char *zFts5Db; /* Db containing fts5 table */
+ sqlite3 *db; /* Database handle */
+ Fts5Global *pGlobal; /* FTS5 global object for this database */
+ int eType; /* FTS5_VOCAB_COL, ROW or INSTANCE */
+ unsigned bBusy; /* True if busy */
+};
+
+struct Fts5VocabCursor {
+ sqlite3_vtab_cursor base;
+ sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
+ Fts5Table *pFts5; /* Associated FTS5 table */
+
+ int bEof; /* True if this cursor is at EOF */
+ Fts5IndexIter *pIter; /* Term/rowid iterator object */
+
+ int nLeTerm; /* Size of zLeTerm in bytes */
+ char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
+
+ /* These are used by 'col' tables only */
+ int iCol;
+ i64 *aCnt;
+ i64 *aDoc;
+
+ /* Output values used by all tables. */
+ i64 rowid; /* This table's current rowid value */
+ Fts5Buffer term; /* Current value of 'term' column */
+
+ /* Output values Used by 'instance' tables only */
+ i64 iInstPos;
+ int iInstOff;
+};
+
+#define FTS5_VOCAB_COL 0
+#define FTS5_VOCAB_ROW 1
+#define FTS5_VOCAB_INSTANCE 2
+
+#define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
+#define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
+#define FTS5_VOCAB_INST_SCHEMA "term, doc, col, offset"
+
+/*
+** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
+*/
+#define FTS5_VOCAB_TERM_EQ 0x01
+#define FTS5_VOCAB_TERM_GE 0x02
+#define FTS5_VOCAB_TERM_LE 0x04
+
+
+/*
+** Translate a string containing an fts5vocab table type to an
+** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
+** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
+** and return SQLITE_ERROR.
+*/
+static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
+ int rc = SQLITE_OK;
+ char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
+ if( rc==SQLITE_OK ){
+ sqlite3Fts5Dequote(zCopy);
+ if( sqlite3_stricmp(zCopy, "col")==0 ){
+ *peType = FTS5_VOCAB_COL;
+ }else
+
+ if( sqlite3_stricmp(zCopy, "row")==0 ){
+ *peType = FTS5_VOCAB_ROW;
+ }else
+ if( sqlite3_stricmp(zCopy, "instance")==0 ){
+ *peType = FTS5_VOCAB_INSTANCE;
+ }else
+ {
+ *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
+ rc = SQLITE_ERROR;
+ }
+ sqlite3_free(zCopy);
+ }
+
+ return rc;
+}
+
+
+/*
+** The xDisconnect() virtual table method.
+*/
+static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
+ Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
+ sqlite3_free(pTab);
+ return SQLITE_OK;
+}
+
+/*
+** The xDestroy() virtual table method.
+*/
+static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
+ Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
+ sqlite3_free(pTab);
+ return SQLITE_OK;
+}
+
+/*
+** This function is the implementation of both the xConnect and xCreate
+** methods of the FTS3 virtual table.
+**
+** The argv[] array contains the following:
+**
+** argv[0] -> module name ("fts5vocab")
+** argv[1] -> database name
+** argv[2] -> table name
+**
+** then:
+**
+** argv[3] -> name of fts5 table
+** argv[4] -> type of fts5vocab table
+**
+** or, for tables in the TEMP schema only.
+**
+** argv[3] -> name of fts5 tables database
+** argv[4] -> name of fts5 table
+** argv[5] -> type of fts5vocab table
+*/
+static int fts5VocabInitVtab(
+ sqlite3 *db, /* The SQLite database connection */
+ void *pAux, /* Pointer to Fts5Global object */
+ int argc, /* Number of elements in argv array */
+ const char * const *argv, /* xCreate/xConnect argument array */
+ sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
+ char **pzErr /* Write any error message here */
+){
+ const char *azSchema[] = {
+ "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
+ "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")",
+ "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")"
+ };
+
+ Fts5VocabTable *pRet = 0;
+ int rc = SQLITE_OK; /* Return code */
+ int bDb;
+
+ bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
+
+ if( argc!=5 && bDb==0 ){
+ *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
+ rc = SQLITE_ERROR;
+ }else{
+ int nByte; /* Bytes of space to allocate */
+ const char *zDb = bDb ? argv[3] : argv[1];
+ const char *zTab = bDb ? argv[4] : argv[3];
+ const char *zType = bDb ? argv[5] : argv[4];
+ int nDb = (int)strlen(zDb)+1;
+ int nTab = (int)strlen(zTab)+1;
+ int eType = 0;
+
+ rc = fts5VocabTableType(zType, pzErr, &eType);
+ if( rc==SQLITE_OK ){
+ assert( eType>=0 && eType<ArraySize(azSchema) );
+ rc = sqlite3_declare_vtab(db, azSchema[eType]);
+ }
+
+ nByte = sizeof(Fts5VocabTable) + nDb + nTab;
+ pRet = sqlite3Fts5MallocZero(&rc, nByte);
+ if( pRet ){
+ pRet->pGlobal = (Fts5Global*)pAux;
+ pRet->eType = eType;
+ pRet->db = db;
+ pRet->zFts5Tbl = (char*)&pRet[1];
+ pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
+ memcpy(pRet->zFts5Tbl, zTab, nTab);
+ memcpy(pRet->zFts5Db, zDb, nDb);
+ sqlite3Fts5Dequote(pRet->zFts5Tbl);
+ sqlite3Fts5Dequote(pRet->zFts5Db);
+ }
+ }
+
+ *ppVTab = (sqlite3_vtab*)pRet;
+ return rc;
+}
+
+
+/*
+** The xConnect() and xCreate() methods for the virtual table. All the
+** work is done in function fts5VocabInitVtab().
+*/
+static int fts5VocabConnectMethod(
+ sqlite3 *db, /* Database connection */
+ void *pAux, /* Pointer to tokenizer hash table */
+ int argc, /* Number of elements in argv array */
+ const char * const *argv, /* xCreate/xConnect argument array */
+ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
+ char **pzErr /* OUT: sqlite3_malloc'd error message */
+){
+ return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
+}
+static int fts5VocabCreateMethod(
+ sqlite3 *db, /* Database connection */
+ void *pAux, /* Pointer to tokenizer hash table */
+ int argc, /* Number of elements in argv array */
+ const char * const *argv, /* xCreate/xConnect argument array */
+ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
+ char **pzErr /* OUT: sqlite3_malloc'd error message */
+){
+ return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
+}
+
+/*
+** Implementation of the xBestIndex method.
+**
+** Only constraints of the form:
+**
+** term <= ?
+** term == ?
+** term >= ?
+**
+** are interpreted. Less-than and less-than-or-equal are treated
+** identically, as are greater-than and greater-than-or-equal.
+*/
+static int fts5VocabBestIndexMethod(
+ sqlite3_vtab *pUnused,
+ sqlite3_index_info *pInfo
+){
+ int i;
+ int iTermEq = -1;
+ int iTermGe = -1;
+ int iTermLe = -1;
+ int idxNum = 0;
+ int nArg = 0;
+
+ UNUSED_PARAM(pUnused);
+
+ for(i=0; i<pInfo->nConstraint; i++){
+ struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
+ if( p->usable==0 ) continue;
+ if( p->iColumn==0 ){ /* term column */
+ if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
+ if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
+ if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
+ if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
+ if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
+ }
+ }
+
+ if( iTermEq>=0 ){
+ idxNum |= FTS5_VOCAB_TERM_EQ;
+ pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
+ pInfo->estimatedCost = 100;
+ }else{
+ pInfo->estimatedCost = 1000000;
+ if( iTermGe>=0 ){
+ idxNum |= FTS5_VOCAB_TERM_GE;
+ pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
+ pInfo->estimatedCost = pInfo->estimatedCost / 2;
+ }
+ if( iTermLe>=0 ){
+ idxNum |= FTS5_VOCAB_TERM_LE;
+ pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
+ pInfo->estimatedCost = pInfo->estimatedCost / 2;
+ }
+ }
+
+ /* This virtual table always delivers results in ascending order of
+ ** the "term" column (column 0). So if the user has requested this
+ ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
+ ** sqlite3_index_info.orderByConsumed flag to tell the core the results
+ ** are already in sorted order. */
+ if( pInfo->nOrderBy==1
+ && pInfo->aOrderBy[0].iColumn==0
+ && pInfo->aOrderBy[0].desc==0
+ ){
+ pInfo->orderByConsumed = 1;
+ }
+
+ pInfo->idxNum = idxNum;
+ return SQLITE_OK;
+}
+
+/*
+** Implementation of xOpen method.
+*/
+static int fts5VocabOpenMethod(
+ sqlite3_vtab *pVTab,
+ sqlite3_vtab_cursor **ppCsr
+){
+ Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
+ Fts5Table *pFts5 = 0;
+ Fts5VocabCursor *pCsr = 0;
+ int rc = SQLITE_OK;
+ sqlite3_stmt *pStmt = 0;
+ char *zSql = 0;
+
+ if( pTab->bBusy ){
+ pVTab->zErrMsg = sqlite3_mprintf(
+ "recursive definition for %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
+ );
+ return SQLITE_ERROR;
+ }
+ zSql = sqlite3Fts5Mprintf(&rc,
+ "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
+ pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
+ );
+ if( zSql ){
+ rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
+ }
+ sqlite3_free(zSql);
+ assert( rc==SQLITE_OK || pStmt==0 );
+ if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
+
+ pTab->bBusy = 1;
+ if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
+ i64 iId = sqlite3_column_int64(pStmt, 0);
+ pFts5 = sqlite3Fts5TableFromCsrid(pTab->pGlobal, iId);
+ }
+ pTab->bBusy = 0;
+
+ if( rc==SQLITE_OK ){
+ if( pFts5==0 ){
+ rc = sqlite3_finalize(pStmt);
+ pStmt = 0;
+ if( rc==SQLITE_OK ){
+ pVTab->zErrMsg = sqlite3_mprintf(
+ "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
+ );
+ rc = SQLITE_ERROR;
+ }
+ }else{
+ rc = sqlite3Fts5FlushToDisk(pFts5);
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ int nByte = pFts5->pConfig->nCol * sizeof(i64)*2 + sizeof(Fts5VocabCursor);
+ pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
+ }
+
+ if( pCsr ){
+ pCsr->pFts5 = pFts5;
+ pCsr->pStmt = pStmt;
+ pCsr->aCnt = (i64*)&pCsr[1];
+ pCsr->aDoc = &pCsr->aCnt[pFts5->pConfig->nCol];
+ }else{
+ sqlite3_finalize(pStmt);
+ }
+
+ *ppCsr = (sqlite3_vtab_cursor*)pCsr;
+ return rc;
+}
+
+static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
+ pCsr->rowid = 0;
+ sqlite3Fts5IterClose(pCsr->pIter);
+ pCsr->pIter = 0;
+ sqlite3_free(pCsr->zLeTerm);
+ pCsr->nLeTerm = -1;
+ pCsr->zLeTerm = 0;
+ pCsr->bEof = 0;
+}
+
+/*
+** Close the cursor. For additional information see the documentation
+** on the xClose method of the virtual table interface.
+*/
+static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
+ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
+ fts5VocabResetCursor(pCsr);
+ sqlite3Fts5BufferFree(&pCsr->term);
+ sqlite3_finalize(pCsr->pStmt);
+ sqlite3_free(pCsr);
+ return SQLITE_OK;
+}
+
+static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){
+ int rc = SQLITE_OK;
+
+ if( sqlite3Fts5IterEof(pCsr->pIter) ){
+ pCsr->bEof = 1;
+ }else{
+ const char *zTerm;
+ int nTerm;
+ zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
+ if( pCsr->nLeTerm>=0 ){
+ int nCmp = MIN(nTerm, pCsr->nLeTerm);
+ int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
+ if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
+ pCsr->bEof = 1;
+ }
+ }
+
+ sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
+ }
+ return rc;
+}
+
+static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
+ int eDetail = pCsr->pFts5->pConfig->eDetail;
+ int rc = SQLITE_OK;
+ Fts5IndexIter *pIter = pCsr->pIter;
+ i64 *pp = &pCsr->iInstPos;
+ int *po = &pCsr->iInstOff;
+
+ assert( sqlite3Fts5IterEof(pIter)==0 );
+ assert( pCsr->bEof==0 );
+ while( eDetail==FTS5_DETAIL_NONE
+ || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp)
+ ){
+ pCsr->iInstPos = 0;
+ pCsr->iInstOff = 0;
+
+ rc = sqlite3Fts5IterNextScan(pCsr->pIter);
+ if( rc==SQLITE_OK ){
+ rc = fts5VocabInstanceNewTerm(pCsr);
+ if( pCsr->bEof || eDetail==FTS5_DETAIL_NONE ) break;
+ }
+ if( rc ){
+ pCsr->bEof = 1;
+ break;
+ }
+ }
+
+ return rc;
+}
+
+/*
+** Advance the cursor to the next row in the table.
+*/
+static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
+ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
+ Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
+ int rc = SQLITE_OK;
+ int nCol = pCsr->pFts5->pConfig->nCol;
+
+ pCsr->rowid++;
+
+ if( pTab->eType==FTS5_VOCAB_INSTANCE ){
+ return fts5VocabInstanceNext(pCsr);
+ }
+
+ if( pTab->eType==FTS5_VOCAB_COL ){
+ for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
+ if( pCsr->aDoc[pCsr->iCol] ) break;
+ }
+ }
+
+ if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){
+ if( sqlite3Fts5IterEof(pCsr->pIter) ){
+ pCsr->bEof = 1;
+ }else{
+ const char *zTerm;
+ int nTerm;
+
+ zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
+ assert( nTerm>=0 );
+ if( pCsr->nLeTerm>=0 ){
+ int nCmp = MIN(nTerm, pCsr->nLeTerm);
+ int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
+ if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
+ pCsr->bEof = 1;
+ return SQLITE_OK;
+ }
+ }
+
+ sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
+ memset(pCsr->aCnt, 0, nCol * sizeof(i64));
+ memset(pCsr->aDoc, 0, nCol * sizeof(i64));
+ pCsr->iCol = 0;
+
+ assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
+ while( rc==SQLITE_OK ){
+ int eDetail = pCsr->pFts5->pConfig->eDetail;
+ const u8 *pPos; int nPos; /* Position list */
+ i64 iPos = 0; /* 64-bit position read from poslist */
+ int iOff = 0; /* Current offset within position list */
+
+ pPos = pCsr->pIter->pData;
+ nPos = pCsr->pIter->nData;
+
+ switch( pTab->eType ){
+ case FTS5_VOCAB_ROW:
+ if( eDetail==FTS5_DETAIL_FULL ){
+ while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
+ pCsr->aCnt[0]++;
+ }
+ }
+ pCsr->aDoc[0]++;
+ break;
+
+ case FTS5_VOCAB_COL:
+ if( eDetail==FTS5_DETAIL_FULL ){
+ int iCol = -1;
+ while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
+ int ii = FTS5_POS2COLUMN(iPos);
+ if( iCol!=ii ){
+ if( ii>=nCol ){
+ rc = FTS5_CORRUPT;
+ break;
+ }
+ pCsr->aDoc[ii]++;
+ iCol = ii;
+ }
+ pCsr->aCnt[ii]++;
+ }
+ }else if( eDetail==FTS5_DETAIL_COLUMNS ){
+ while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
+ assert_nc( iPos>=0 && iPos<nCol );
+ if( iPos>=nCol ){
+ rc = FTS5_CORRUPT;
+ break;
+ }
+ pCsr->aDoc[iPos]++;
+ }
+ }else{
+ assert( eDetail==FTS5_DETAIL_NONE );
+ pCsr->aDoc[0]++;
+ }
+ break;
+
+ default:
+ assert( pTab->eType==FTS5_VOCAB_INSTANCE );
+ break;
+ }
+
+ if( rc==SQLITE_OK ){
+ rc = sqlite3Fts5IterNextScan(pCsr->pIter);
+ }
+ if( pTab->eType==FTS5_VOCAB_INSTANCE ) break;
+
+ if( rc==SQLITE_OK ){
+ zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
+ if( nTerm!=pCsr->term.n
+ || (nTerm>0 && memcmp(zTerm, pCsr->term.p, nTerm))
+ ){
+ break;
+ }
+ if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
+ }
+ }
+ }
+ }
+
+ if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
+ for(/* noop */; pCsr->iCol<nCol && pCsr->aDoc[pCsr->iCol]==0; pCsr->iCol++);
+ if( pCsr->iCol==nCol ){
+ rc = FTS5_CORRUPT;
+ }
+ }
+ return rc;
+}
+
+/*
+** This is the xFilter implementation for the virtual table.
+*/
+static int fts5VocabFilterMethod(
+ sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
+ int idxNum, /* Strategy index */
+ const char *zUnused, /* Unused */
+ int nUnused, /* Number of elements in apVal */
+ sqlite3_value **apVal /* Arguments for the indexing scheme */
+){
+ Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
+ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
+ int eType = pTab->eType;
+ int rc = SQLITE_OK;
+
+ int iVal = 0;
+ int f = FTS5INDEX_QUERY_SCAN;
+ const char *zTerm = 0;
+ int nTerm = 0;
+
+ sqlite3_value *pEq = 0;
+ sqlite3_value *pGe = 0;
+ sqlite3_value *pLe = 0;
+
+ UNUSED_PARAM2(zUnused, nUnused);
+
+ fts5VocabResetCursor(pCsr);
+ if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
+ if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
+ if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
+
+ if( pEq ){
+ zTerm = (const char *)sqlite3_value_text(pEq);
+ nTerm = sqlite3_value_bytes(pEq);
+ f = 0;
+ }else{
+ if( pGe ){
+ zTerm = (const char *)sqlite3_value_text(pGe);
+ nTerm = sqlite3_value_bytes(pGe);
+ }
+ if( pLe ){
+ const char *zCopy = (const char *)sqlite3_value_text(pLe);
+ if( zCopy==0 ) zCopy = "";
+ pCsr->nLeTerm = sqlite3_value_bytes(pLe);
+ pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
+ if( pCsr->zLeTerm==0 ){
+ rc = SQLITE_NOMEM;
+ }else{
+ memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
+ }
+ }
+ }
+
+ if( rc==SQLITE_OK ){
+ Fts5Index *pIndex = pCsr->pFts5->pIndex;
+ rc = sqlite3Fts5IndexQuery(pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
+ }
+ if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
+ rc = fts5VocabInstanceNewTerm(pCsr);
+ }
+ if( rc==SQLITE_OK && !pCsr->bEof
+ && (eType!=FTS5_VOCAB_INSTANCE
+ || pCsr->pFts5->pConfig->eDetail!=FTS5_DETAIL_NONE)
+ ){
+ rc = fts5VocabNextMethod(pCursor);
+ }
+
+ return rc;
+}
+
+/*
+** This is the xEof method of the virtual table. SQLite calls this
+** routine to find out if it has reached the end of a result set.
+*/
+static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
+ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
+ return pCsr->bEof;
+}
+
+static int fts5VocabColumnMethod(
+ sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
+ sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
+ int iCol /* Index of column to read value from */
+){
+ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
+ int eDetail = pCsr->pFts5->pConfig->eDetail;
+ int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
+ i64 iVal = 0;
+
+ if( iCol==0 ){
+ sqlite3_result_text(
+ pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
+ );
+ }else if( eType==FTS5_VOCAB_COL ){
+ assert( iCol==1 || iCol==2 || iCol==3 );
+ if( iCol==1 ){
+ if( eDetail!=FTS5_DETAIL_NONE ){
+ const char *z = pCsr->pFts5->pConfig->azCol[pCsr->iCol];
+ sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
+ }
+ }else if( iCol==2 ){
+ iVal = pCsr->aDoc[pCsr->iCol];
+ }else{
+ iVal = pCsr->aCnt[pCsr->iCol];
+ }
+ }else if( eType==FTS5_VOCAB_ROW ){
+ assert( iCol==1 || iCol==2 );
+ if( iCol==1 ){
+ iVal = pCsr->aDoc[0];
+ }else{
+ iVal = pCsr->aCnt[0];
+ }
+ }else{
+ assert( eType==FTS5_VOCAB_INSTANCE );
+ switch( iCol ){
+ case 1:
+ sqlite3_result_int64(pCtx, pCsr->pIter->iRowid);
+ break;
+ case 2: {
+ int ii = -1;
+ if( eDetail==FTS5_DETAIL_FULL ){
+ ii = FTS5_POS2COLUMN(pCsr->iInstPos);
+ }else if( eDetail==FTS5_DETAIL_COLUMNS ){
+ ii = (int)pCsr->iInstPos;
+ }
+ if( ii>=0 && ii<pCsr->pFts5->pConfig->nCol ){
+ const char *z = pCsr->pFts5->pConfig->azCol[ii];
+ sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
+ }
+ break;
+ }
+ default: {
+ assert( iCol==3 );
+ if( eDetail==FTS5_DETAIL_FULL ){
+ int ii = FTS5_POS2OFFSET(pCsr->iInstPos);
+ sqlite3_result_int(pCtx, ii);
+ }
+ break;
+ }
+ }
+ }
+
+ if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
+ return SQLITE_OK;
+}
+
+/*
+** This is the xRowid method. The SQLite core calls this routine to
+** retrieve the rowid for the current row of the result set. The
+** rowid should be written to *pRowid.
+*/
+static int fts5VocabRowidMethod(
+ sqlite3_vtab_cursor *pCursor,
+ sqlite_int64 *pRowid
+){
+ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
+ *pRowid = pCsr->rowid;
+ return SQLITE_OK;
+}
+
+static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
+ static const sqlite3_module fts5Vocab = {
+ /* iVersion */ 2,
+ /* xCreate */ fts5VocabCreateMethod,
+ /* xConnect */ fts5VocabConnectMethod,
+ /* xBestIndex */ fts5VocabBestIndexMethod,
+ /* xDisconnect */ fts5VocabDisconnectMethod,
+ /* xDestroy */ fts5VocabDestroyMethod,
+ /* xOpen */ fts5VocabOpenMethod,
+ /* xClose */ fts5VocabCloseMethod,
+ /* xFilter */ fts5VocabFilterMethod,
+ /* xNext */ fts5VocabNextMethod,
+ /* xEof */ fts5VocabEofMethod,
+ /* xColumn */ fts5VocabColumnMethod,
+ /* xRowid */ fts5VocabRowidMethod,
+ /* xUpdate */ 0,
+ /* xBegin */ 0,
+ /* xSync */ 0,
+ /* xCommit */ 0,
+ /* xRollback */ 0,
+ /* xFindFunction */ 0,
+ /* xRename */ 0,
+ /* xSavepoint */ 0,
+ /* xRelease */ 0,
+ /* xRollbackTo */ 0,
+ /* xShadowName */ 0
+ };
+ void *p = (void*)pGlobal;
+
+ return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
+}
+
+
+
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
+
+/************** End of fts5.c ************************************************/
+/************** Begin file stmt.c ********************************************/
+/*
+** 2017-05-31
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file demonstrates an eponymous virtual table that returns information
+** about all prepared statements for the database connection.
+**
+** Usage example:
+**
+** .load ./stmt
+** .mode line
+** .header on
+** SELECT * FROM stmt;
+*/
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)
+#if !defined(SQLITEINT_H)
+/* #include "sqlite3ext.h" */
+#endif
+SQLITE_EXTENSION_INIT1
+/* #include <assert.h> */
+/* #include <string.h> */
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+
+/* stmt_vtab is a subclass of sqlite3_vtab which will
+** serve as the underlying representation of a stmt virtual table
+*/
+typedef struct stmt_vtab stmt_vtab;
+struct stmt_vtab {
+ sqlite3_vtab base; /* Base class - must be first */
+ sqlite3 *db; /* Database connection for this stmt vtab */
+};
+
+/* stmt_cursor is a subclass of sqlite3_vtab_cursor which will
+** serve as the underlying representation of a cursor that scans
+** over rows of the result
+*/
+typedef struct stmt_cursor stmt_cursor;
+struct stmt_cursor {
+ sqlite3_vtab_cursor base; /* Base class - must be first */
+ sqlite3 *db; /* Database connection for this cursor */
+ sqlite3_stmt *pStmt; /* Statement cursor is currently pointing at */
+ sqlite3_int64 iRowid; /* The rowid */
+};
+
+/*
+** The stmtConnect() method is invoked to create a new
+** stmt_vtab that describes the stmt virtual table.
+**
+** Think of this routine as the constructor for stmt_vtab objects.
+**
+** All this routine needs to do is:
+**
+** (1) Allocate the stmt_vtab object and initialize all fields.
+**
+** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
+** result set of queries against stmt will look like.
+*/
+static int stmtConnect(
+ sqlite3 *db,
+ void *pAux,
+ int argc, const char *const*argv,
+ sqlite3_vtab **ppVtab,
+ char **pzErr
+){
+ stmt_vtab *pNew;
+ int rc;
+
+/* Column numbers */
+#define STMT_COLUMN_SQL 0 /* SQL for the statement */
+#define STMT_COLUMN_NCOL 1 /* Number of result columns */
+#define STMT_COLUMN_RO 2 /* True if read-only */
+#define STMT_COLUMN_BUSY 3 /* True if currently busy */
+#define STMT_COLUMN_NSCAN 4 /* SQLITE_STMTSTATUS_FULLSCAN_STEP */
+#define STMT_COLUMN_NSORT 5 /* SQLITE_STMTSTATUS_SORT */
+#define STMT_COLUMN_NAIDX 6 /* SQLITE_STMTSTATUS_AUTOINDEX */
+#define STMT_COLUMN_NSTEP 7 /* SQLITE_STMTSTATUS_VM_STEP */
+#define STMT_COLUMN_REPREP 8 /* SQLITE_STMTSTATUS_REPREPARE */
+#define STMT_COLUMN_RUN 9 /* SQLITE_STMTSTATUS_RUN */
+#define STMT_COLUMN_MEM 10 /* SQLITE_STMTSTATUS_MEMUSED */
+
+
+ rc = sqlite3_declare_vtab(db,
+ "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
+ "reprep,run,mem)");
+ if( rc==SQLITE_OK ){
+ pNew = sqlite3_malloc( sizeof(*pNew) );
+ *ppVtab = (sqlite3_vtab*)pNew;
+ if( pNew==0 ) return SQLITE_NOMEM;
+ memset(pNew, 0, sizeof(*pNew));
+ pNew->db = db;
+ }
+ return rc;
+}
+
+/*
+** This method is the destructor for stmt_cursor objects.
+*/
+static int stmtDisconnect(sqlite3_vtab *pVtab){
+ sqlite3_free(pVtab);
+ return SQLITE_OK;
+}
+
+/*
+** Constructor for a new stmt_cursor object.
+*/
+static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
+ stmt_cursor *pCur;
+ pCur = sqlite3_malloc( sizeof(*pCur) );
+ if( pCur==0 ) return SQLITE_NOMEM;
+ memset(pCur, 0, sizeof(*pCur));
+ pCur->db = ((stmt_vtab*)p)->db;
+ *ppCursor = &pCur->base;
+ return SQLITE_OK;
+}
+
+/*
+** Destructor for a stmt_cursor.
+*/
+static int stmtClose(sqlite3_vtab_cursor *cur){
+ sqlite3_free(cur);
+ return SQLITE_OK;
+}
+
+
+/*
+** Advance a stmt_cursor to its next row of output.
+*/
+static int stmtNext(sqlite3_vtab_cursor *cur){
+ stmt_cursor *pCur = (stmt_cursor*)cur;
+ pCur->iRowid++;
+ pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);
+ return SQLITE_OK;
+}
+
+/*
+** Return values of columns for the row at which the stmt_cursor
+** is currently pointing.
+*/
+static int stmtColumn(
+ sqlite3_vtab_cursor *cur, /* The cursor */
+ sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
+ int i /* Which column to return */
+){
+ stmt_cursor *pCur = (stmt_cursor*)cur;
+ switch( i ){
+ case STMT_COLUMN_SQL: {
+ sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);
+ break;
+ }
+ case STMT_COLUMN_NCOL: {
+ sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));
+ break;
+ }
+ case STMT_COLUMN_RO: {
+ sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));
+ break;
+ }
+ case STMT_COLUMN_BUSY: {
+ sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
+ break;
+ }
+ default: {
+ assert( i==STMT_COLUMN_MEM );
+ i = SQLITE_STMTSTATUS_MEMUSED +
+ STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
+ /* Fall thru */
+ }
+ case STMT_COLUMN_NSCAN:
+ case STMT_COLUMN_NSORT:
+ case STMT_COLUMN_NAIDX:
+ case STMT_COLUMN_NSTEP:
+ case STMT_COLUMN_REPREP:
+ case STMT_COLUMN_RUN: {
+ sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,
+ i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));
+ break;
+ }
+ }
+ return SQLITE_OK;
+}
+
+/*
+** Return the rowid for the current row. In this implementation, the
+** rowid is the same as the output value.
+*/
+static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
+ stmt_cursor *pCur = (stmt_cursor*)cur;
+ *pRowid = pCur->iRowid;
+ return SQLITE_OK;
+}
+
+/*
+** Return TRUE if the cursor has been moved off of the last
+** row of output.
+*/
+static int stmtEof(sqlite3_vtab_cursor *cur){
+ stmt_cursor *pCur = (stmt_cursor*)cur;
+ return pCur->pStmt==0;
+}
+
+/*
+** This method is called to "rewind" the stmt_cursor object back
+** to the first row of output. This method is always called at least
+** once prior to any call to stmtColumn() or stmtRowid() or
+** stmtEof().
+*/
+static int stmtFilter(
+ sqlite3_vtab_cursor *pVtabCursor,
+ int idxNum, const char *idxStr,
+ int argc, sqlite3_value **argv
+){
+ stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
+ pCur->pStmt = 0;
+ pCur->iRowid = 0;
+ return stmtNext(pVtabCursor);
+}
+
+/*
+** SQLite will invoke this method one or more times while planning a query
+** that uses the stmt virtual table. This routine needs to create
+** a query plan for each invocation and compute an estimated cost for that
+** plan.
+*/
+static int stmtBestIndex(
+ sqlite3_vtab *tab,
+ sqlite3_index_info *pIdxInfo
+){
+ pIdxInfo->estimatedCost = (double)500;
+ pIdxInfo->estimatedRows = 500;
+ return SQLITE_OK;
+}
+
+/*
+** This following structure defines all the methods for the
+** stmt virtual table.
+*/
+static sqlite3_module stmtModule = {
+ 0, /* iVersion */
+ 0, /* xCreate */
+ stmtConnect, /* xConnect */
+ stmtBestIndex, /* xBestIndex */
+ stmtDisconnect, /* xDisconnect */
+ 0, /* xDestroy */
+ stmtOpen, /* xOpen - open a cursor */
+ stmtClose, /* xClose - close a cursor */
+ stmtFilter, /* xFilter - configure scan constraints */
+ stmtNext, /* xNext - advance a cursor */
+ stmtEof, /* xEof - check for end of scan */
+ stmtColumn, /* xColumn - read data */
+ stmtRowid, /* xRowid - read data */
+ 0, /* xUpdate */
+ 0, /* xBegin */
+ 0, /* xSync */
+ 0, /* xCommit */
+ 0, /* xRollback */
+ 0, /* xFindMethod */
+ 0, /* xRename */
+ 0, /* xSavepoint */
+ 0, /* xRelease */
+ 0, /* xRollbackTo */
+ 0, /* xShadowName */
+};
+
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
+ int rc = SQLITE_OK;
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ rc = sqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0);
+#endif
+ return rc;
+}
+
+#ifndef SQLITE_CORE
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+SQLITE_API int sqlite3_stmt_init(
+ sqlite3 *db,
+ char **pzErrMsg,
+ const sqlite3_api_routines *pApi
+){
+ int rc = SQLITE_OK;
+ SQLITE_EXTENSION_INIT2(pApi);
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+ rc = sqlite3StmtVtabInit(db);
+#endif
+ return rc;
+}
+#endif /* SQLITE_CORE */
+#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
+
+/************** End of stmt.c ************************************************/
+#if __LINE__!=231376
+#undef SQLITE_SOURCE_ID
+#define SQLITE_SOURCE_ID "2020-10-02 15:15:18 dd009cd7aec3598e930806907601f4f0f9b0021ea99fa6c5e29e88f12460alt2"
+#endif
+/* Return the source-id for this library */
+SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
+/************************** End of sqlite3.c ******************************/
diff --git a/third_party/heimdal/lib/sqlite/sqlite3.h b/third_party/heimdal/lib/sqlite/sqlite3.h
new file mode 100644
index 0000000..b32ee2a
--- /dev/null
+++ b/third_party/heimdal/lib/sqlite/sqlite3.h
@@ -0,0 +1,12229 @@
+/*
+** 2001-09-15
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This header file defines the interface that the SQLite library
+** presents to client programs. If a C-function, structure, datatype,
+** or constant definition does not appear in this file, then it is
+** not a published API of SQLite, is subject to change without
+** notice, and should not be referenced by programs that use SQLite.
+**
+** Some of the definitions that are in this file are marked as
+** "experimental". Experimental interfaces are normally new
+** features recently added to SQLite. We do not anticipate changes
+** to experimental interfaces but reserve the right to make minor changes
+** if experience from use "in the wild" suggest such changes are prudent.
+**
+** The official C-language API documentation for SQLite is derived
+** from comments in this file. This file is the authoritative source
+** on how SQLite interfaces are supposed to operate.
+**
+** The name of this file under configuration management is "sqlite.h.in".
+** The makefile makes some minor changes to this file (such as inserting
+** the version number) and changes its name to "sqlite3.h" as
+** part of the build process.
+*/
+#ifndef SQLITE3_H
+#define SQLITE3_H
+#include <stdarg.h> /* Needed for the definition of va_list */
+
+/*
+** Make sure we can call this stuff from C++.
+*/
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/*
+** Provide the ability to override linkage features of the interface.
+*/
+#ifndef SQLITE_EXTERN
+# define SQLITE_EXTERN extern
+#endif
+#ifndef SQLITE_API
+# define SQLITE_API
+#endif
+#ifndef SQLITE_CDECL
+# define SQLITE_CDECL
+#endif
+#ifndef SQLITE_APICALL
+# define SQLITE_APICALL
+#endif
+#ifndef SQLITE_STDCALL
+# define SQLITE_STDCALL SQLITE_APICALL
+#endif
+#ifndef SQLITE_CALLBACK
+# define SQLITE_CALLBACK
+#endif
+#ifndef SQLITE_SYSAPI
+# define SQLITE_SYSAPI
+#endif
+
+/*
+** These no-op macros are used in front of interfaces to mark those
+** interfaces as either deprecated or experimental. New applications
+** should not use deprecated interfaces - they are supported for backwards
+** compatibility only. Application writers should be aware that
+** experimental interfaces are subject to change in point releases.
+**
+** These macros used to resolve to various kinds of compiler magic that
+** would generate warning messages when they were used. But that
+** compiler magic ended up generating such a flurry of bug reports
+** that we have taken it all out and gone back to using simple
+** noop macros.
+*/
+#define SQLITE_DEPRECATED
+#define SQLITE_EXPERIMENTAL
+
+/*
+** Ensure these symbols were not defined by some previous header file.
+*/
+#ifdef SQLITE_VERSION
+# undef SQLITE_VERSION
+#endif
+#ifdef SQLITE_VERSION_NUMBER
+# undef SQLITE_VERSION_NUMBER
+#endif
+
+/*
+** CAPI3REF: Compile-Time Library Version Numbers
+**
+** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
+** evaluates to a string literal that is the SQLite version in the
+** format "X.Y.Z" where X is the major version number (always 3 for
+** SQLite3) and Y is the minor version number and Z is the release number.)^
+** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
+** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
+** numbers used in [SQLITE_VERSION].)^
+** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
+** be larger than the release from which it is derived. Either Y will
+** be held constant and Z will be incremented or else Y will be incremented
+** and Z will be reset to zero.
+**
+** Since [version 3.6.18] ([dateof:3.6.18]),
+** SQLite source code has been stored in the
+** <a href="http://www.fossil-scm.org/">Fossil configuration management
+** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
+** a string which identifies a particular check-in of SQLite
+** within its configuration management system. ^The SQLITE_SOURCE_ID
+** string contains the date and time of the check-in (UTC) and a SHA1
+** or SHA3-256 hash of the entire source tree. If the source code has
+** been edited in any way since it was last checked in, then the last
+** four hexadecimal digits of the hash may be modified.
+**
+** See also: [sqlite3_libversion()],
+** [sqlite3_libversion_number()], [sqlite3_sourceid()],
+** [sqlite_version()] and [sqlite_source_id()].
+*/
+#define SQLITE_VERSION "3.34.0"
+#define SQLITE_VERSION_NUMBER 3034000
+#define SQLITE_SOURCE_ID "2020-10-02 15:15:18 dd009cd7aec3598e930806907601f4f0f9b0021ea99fa6c5e29e88f1246066ed"
+
+/*
+** CAPI3REF: Run-Time Library Version Numbers
+** KEYWORDS: sqlite3_version sqlite3_sourceid
+**
+** These interfaces provide the same information as the [SQLITE_VERSION],
+** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
+** but are associated with the library instead of the header file. ^(Cautious
+** programmers might include assert() statements in their application to
+** verify that values returned by these interfaces match the macros in
+** the header, and thus ensure that the application is
+** compiled with matching library and header files.
+**
+** <blockquote><pre>
+** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
+** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
+** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
+** </pre></blockquote>)^
+**
+** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
+** macro. ^The sqlite3_libversion() function returns a pointer to the
+** to the sqlite3_version[] string constant. The sqlite3_libversion()
+** function is provided for use in DLLs since DLL users usually do not have
+** direct access to string constants within the DLL. ^The
+** sqlite3_libversion_number() function returns an integer equal to
+** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns
+** a pointer to a string constant whose value is the same as the
+** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built
+** using an edited copy of [the amalgamation], then the last four characters
+** of the hash might be different from [SQLITE_SOURCE_ID].)^
+**
+** See also: [sqlite_version()] and [sqlite_source_id()].
+*/
+SQLITE_API SQLITE_EXTERN const char sqlite3_version[];
+SQLITE_API const char *sqlite3_libversion(void);
+SQLITE_API const char *sqlite3_sourceid(void);
+SQLITE_API int sqlite3_libversion_number(void);
+
+/*
+** CAPI3REF: Run-Time Library Compilation Options Diagnostics
+**
+** ^The sqlite3_compileoption_used() function returns 0 or 1
+** indicating whether the specified option was defined at
+** compile time. ^The SQLITE_ prefix may be omitted from the
+** option name passed to sqlite3_compileoption_used().
+**
+** ^The sqlite3_compileoption_get() function allows iterating
+** over the list of options that were defined at compile time by
+** returning the N-th compile time option string. ^If N is out of range,
+** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
+** prefix is omitted from any strings returned by
+** sqlite3_compileoption_get().
+**
+** ^Support for the diagnostic functions sqlite3_compileoption_used()
+** and sqlite3_compileoption_get() may be omitted by specifying the
+** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
+**
+** See also: SQL functions [sqlite_compileoption_used()] and
+** [sqlite_compileoption_get()] and the [compile_options pragma].
+*/
+#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
+SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
+SQLITE_API const char *sqlite3_compileoption_get(int N);
+#else
+# define sqlite3_compileoption_used(X) 0
+# define sqlite3_compileoption_get(X) ((void*)0)
+#endif
+
+/*
+** CAPI3REF: Test To See If The Library Is Threadsafe
+**
+** ^The sqlite3_threadsafe() function returns zero if and only if
+** SQLite was compiled with mutexing code omitted due to the
+** [SQLITE_THREADSAFE] compile-time option being set to 0.
+**
+** SQLite can be compiled with or without mutexes. When
+** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
+** are enabled and SQLite is threadsafe. When the
+** [SQLITE_THREADSAFE] macro is 0,
+** the mutexes are omitted. Without the mutexes, it is not safe
+** to use SQLite concurrently from more than one thread.
+**
+** Enabling mutexes incurs a measurable performance penalty.
+** So if speed is of utmost importance, it makes sense to disable
+** the mutexes. But for maximum safety, mutexes should be enabled.
+** ^The default behavior is for mutexes to be enabled.
+**
+** This interface can be used by an application to make sure that the
+** version of SQLite that it is linking against was compiled with
+** the desired setting of the [SQLITE_THREADSAFE] macro.
+**
+** This interface only reports on the compile-time mutex setting
+** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
+** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
+** can be fully or partially disabled using a call to [sqlite3_config()]
+** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
+** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
+** sqlite3_threadsafe() function shows only the compile-time setting of
+** thread safety, not any run-time changes to that setting made by
+** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
+** is unchanged by calls to sqlite3_config().)^
+**
+** See the [threading mode] documentation for additional information.
+*/
+SQLITE_API int sqlite3_threadsafe(void);
+
+/*
+** CAPI3REF: Database Connection Handle
+** KEYWORDS: {database connection} {database connections}
+**
+** Each open SQLite database is represented by a pointer to an instance of
+** the opaque structure named "sqlite3". It is useful to think of an sqlite3
+** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
+** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
+** and [sqlite3_close_v2()] are its destructors. There are many other
+** interfaces (such as
+** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
+** [sqlite3_busy_timeout()] to name but three) that are methods on an
+** sqlite3 object.
+*/
+typedef struct sqlite3 sqlite3;
+
+/*
+** CAPI3REF: 64-Bit Integer Types
+** KEYWORDS: sqlite_int64 sqlite_uint64
+**
+** Because there is no cross-platform way to specify 64-bit integer types
+** SQLite includes typedefs for 64-bit signed and unsigned integers.
+**
+** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
+** The sqlite_int64 and sqlite_uint64 types are supported for backwards
+** compatibility only.
+**
+** ^The sqlite3_int64 and sqlite_int64 types can store integer values
+** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
+** sqlite3_uint64 and sqlite_uint64 types can store integer values
+** between 0 and +18446744073709551615 inclusive.
+*/
+#ifdef SQLITE_INT64_TYPE
+ typedef SQLITE_INT64_TYPE sqlite_int64;
+# ifdef SQLITE_UINT64_TYPE
+ typedef SQLITE_UINT64_TYPE sqlite_uint64;
+# else
+ typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
+# endif
+#elif defined(_MSC_VER) || defined(__BORLANDC__)
+ typedef __int64 sqlite_int64;
+ typedef unsigned __int64 sqlite_uint64;
+#else
+ typedef long long int sqlite_int64;
+ typedef unsigned long long int sqlite_uint64;
+#endif
+typedef sqlite_int64 sqlite3_int64;
+typedef sqlite_uint64 sqlite3_uint64;
+
+/*
+** If compiling for a processor that lacks floating point support,
+** substitute integer for floating-point.
+*/
+#ifdef SQLITE_OMIT_FLOATING_POINT
+# define double sqlite3_int64
+#endif
+
+/*
+** CAPI3REF: Closing A Database Connection
+** DESTRUCTOR: sqlite3
+**
+** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
+** for the [sqlite3] object.
+** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
+** the [sqlite3] object is successfully destroyed and all associated
+** resources are deallocated.
+**
+** Ideally, applications should [sqlite3_finalize | finalize] all
+** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and
+** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
+** with the [sqlite3] object prior to attempting to close the object.
+** ^If the database connection is associated with unfinalized prepared
+** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then
+** sqlite3_close() will leave the database connection open and return
+** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared
+** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups,
+** it returns [SQLITE_OK] regardless, but instead of deallocating the database
+** connection immediately, it marks the database connection as an unusable
+** "zombie" and makes arrangements to automatically deallocate the database
+** connection after all prepared statements are finalized, all BLOB handles
+** are closed, and all backups have finished. The sqlite3_close_v2() interface
+** is intended for use with host languages that are garbage collected, and
+** where the order in which destructors are called is arbitrary.
+**
+** ^If an [sqlite3] object is destroyed while a transaction is open,
+** the transaction is automatically rolled back.
+**
+** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
+** must be either a NULL
+** pointer or an [sqlite3] object pointer obtained
+** from [sqlite3_open()], [sqlite3_open16()], or
+** [sqlite3_open_v2()], and not previously closed.
+** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
+** argument is a harmless no-op.
+*/
+SQLITE_API int sqlite3_close(sqlite3*);
+SQLITE_API int sqlite3_close_v2(sqlite3*);
+
+/*
+** The type for a callback function.
+** This is legacy and deprecated. It is included for historical
+** compatibility and is not documented.
+*/
+typedef int (*sqlite3_callback)(void*,int,char**, char**);
+
+/*
+** CAPI3REF: One-Step Query Execution Interface
+** METHOD: sqlite3
+**
+** The sqlite3_exec() interface is a convenience wrapper around
+** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
+** that allows an application to run multiple statements of SQL
+** without having to use a lot of C code.
+**
+** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
+** semicolon-separate SQL statements passed into its 2nd argument,
+** in the context of the [database connection] passed in as its 1st
+** argument. ^If the callback function of the 3rd argument to
+** sqlite3_exec() is not NULL, then it is invoked for each result row
+** coming out of the evaluated SQL statements. ^The 4th argument to
+** sqlite3_exec() is relayed through to the 1st argument of each
+** callback invocation. ^If the callback pointer to sqlite3_exec()
+** is NULL, then no callback is ever invoked and result rows are
+** ignored.
+**
+** ^If an error occurs while evaluating the SQL statements passed into
+** sqlite3_exec(), then execution of the current statement stops and
+** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
+** is not NULL then any error message is written into memory obtained
+** from [sqlite3_malloc()] and passed back through the 5th parameter.
+** To avoid memory leaks, the application should invoke [sqlite3_free()]
+** on error message strings returned through the 5th parameter of
+** sqlite3_exec() after the error message string is no longer needed.
+** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
+** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
+** NULL before returning.
+**
+** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
+** routine returns SQLITE_ABORT without invoking the callback again and
+** without running any subsequent SQL statements.
+**
+** ^The 2nd argument to the sqlite3_exec() callback function is the
+** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
+** callback is an array of pointers to strings obtained as if from
+** [sqlite3_column_text()], one for each column. ^If an element of a
+** result row is NULL then the corresponding string pointer for the
+** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
+** sqlite3_exec() callback is an array of pointers to strings where each
+** entry represents the name of corresponding result column as obtained
+** from [sqlite3_column_name()].
+**
+** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
+** to an empty string, or a pointer that contains only whitespace and/or
+** SQL comments, then no SQL statements are evaluated and the database
+** is not changed.
+**
+** Restrictions:
+**
+** <ul>
+** <li> The application must ensure that the 1st parameter to sqlite3_exec()
+** is a valid and open [database connection].
+** <li> The application must not close the [database connection] specified by
+** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
+** <li> The application must not modify the SQL statement text passed into
+** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
+** </ul>
+*/
+SQLITE_API int sqlite3_exec(
+ sqlite3*, /* An open database */
+ const char *sql, /* SQL to be evaluated */
+ int (*callback)(void*,int,char**,char**), /* Callback function */
+ void *, /* 1st argument to callback */
+ char **errmsg /* Error msg written here */
+);
+
+/*
+** CAPI3REF: Result Codes
+** KEYWORDS: {result code definitions}
+**
+** Many SQLite functions return an integer result code from the set shown
+** here in order to indicate success or failure.
+**
+** New error codes may be added in future versions of SQLite.
+**
+** See also: [extended result code definitions]
+*/
+#define SQLITE_OK 0 /* Successful result */
+/* beginning-of-error-codes */
+#define SQLITE_ERROR 1 /* Generic error */
+#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
+#define SQLITE_PERM 3 /* Access permission denied */
+#define SQLITE_ABORT 4 /* Callback routine requested an abort */
+#define SQLITE_BUSY 5 /* The database file is locked */
+#define SQLITE_LOCKED 6 /* A table in the database is locked */
+#define SQLITE_NOMEM 7 /* A malloc() failed */
+#define SQLITE_READONLY 8 /* Attempt to write a readonly database */
+#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
+#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
+#define SQLITE_CORRUPT 11 /* The database disk image is malformed */
+#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
+#define SQLITE_FULL 13 /* Insertion failed because database is full */
+#define SQLITE_CANTOPEN 14 /* Unable to open the database file */
+#define SQLITE_PROTOCOL 15 /* Database lock protocol error */
+#define SQLITE_EMPTY 16 /* Internal use only */
+#define SQLITE_SCHEMA 17 /* The database schema changed */
+#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
+#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
+#define SQLITE_MISMATCH 20 /* Data type mismatch */
+#define SQLITE_MISUSE 21 /* Library used incorrectly */
+#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
+#define SQLITE_AUTH 23 /* Authorization denied */
+#define SQLITE_FORMAT 24 /* Not used */
+#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
+#define SQLITE_NOTADB 26 /* File opened that is not a database file */
+#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
+#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
+#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
+#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
+/* end-of-error-codes */
+
+/*
+** CAPI3REF: Extended Result Codes
+** KEYWORDS: {extended result code definitions}
+**
+** In its default configuration, SQLite API routines return one of 30 integer
+** [result codes]. However, experience has shown that many of
+** these result codes are too coarse-grained. They do not provide as
+** much information about problems as programmers might like. In an effort to
+** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
+** and later) include
+** support for additional result codes that provide more detailed information
+** about errors. These [extended result codes] are enabled or disabled
+** on a per database connection basis using the
+** [sqlite3_extended_result_codes()] API. Or, the extended code for
+** the most recent error can be obtained using
+** [sqlite3_extended_errcode()].
+*/
+#define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8))
+#define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8))
+#define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8))
+#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
+#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
+#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
+#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
+#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
+#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
+#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
+#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
+#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
+#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
+#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
+#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
+#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
+#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
+#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
+#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
+#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
+#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
+#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
+#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
+#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
+#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
+#define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
+#define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
+#define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
+#define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
+#define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
+#define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
+#define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
+#define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
+#define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
+#define SQLITE_IOERR_DATA (SQLITE_IOERR | (32<<8))
+#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
+#define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8))
+#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
+#define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
+#define SQLITE_BUSY_TIMEOUT (SQLITE_BUSY | (3<<8))
+#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
+#define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
+#define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
+#define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
+#define SQLITE_CANTOPEN_DIRTYWAL (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
+#define SQLITE_CANTOPEN_SYMLINK (SQLITE_CANTOPEN | (6<<8))
+#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
+#define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8))
+#define SQLITE_CORRUPT_INDEX (SQLITE_CORRUPT | (3<<8))
+#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
+#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
+#define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
+#define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
+#define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8))
+#define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8))
+#define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
+#define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
+#define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
+#define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
+#define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
+#define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
+#define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
+#define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
+#define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
+#define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
+#define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
+#define SQLITE_CONSTRAINT_PINNED (SQLITE_CONSTRAINT |(11<<8))
+#define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
+#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
+#define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
+#define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
+#define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
+#define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8))
+
+/*
+** CAPI3REF: Flags For File Open Operations
+**
+** These bit values are intended for use in the
+** 3rd parameter to the [sqlite3_open_v2()] interface and
+** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
+*/
+#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
+#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
+#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
+#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
+#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
+#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
+#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
+#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
+#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
+#define SQLITE_OPEN_SUPER_JOURNAL 0x00004000 /* VFS only */
+#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
+#define SQLITE_OPEN_NOFOLLOW 0x01000000 /* Ok for sqlite3_open_v2() */
+
+/* Reserved: 0x00F00000 */
+/* Legacy compatibility: */
+#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
+
+
+/*
+** CAPI3REF: Device Characteristics
+**
+** The xDeviceCharacteristics method of the [sqlite3_io_methods]
+** object returns an integer which is a vector of these
+** bit values expressing I/O characteristics of the mass storage
+** device that holds the file that the [sqlite3_io_methods]
+** refers to.
+**
+** The SQLITE_IOCAP_ATOMIC property means that all writes of
+** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
+** mean that writes of blocks that are nnn bytes in size and
+** are aligned to an address which is an integer multiple of
+** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
+** that when data is appended to a file, the data is appended
+** first then the size of the file is extended, never the other
+** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
+** information is written to disk in the same order as calls
+** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
+** after reboot following a crash or power loss, the only bytes in a
+** file that were written at the application level might have changed
+** and that adjacent bytes, even bytes within the same sector are
+** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
+** flag indicates that a file cannot be deleted when open. The
+** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
+** read-only media and cannot be changed even by processes with
+** elevated privileges.
+**
+** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
+** filesystem supports doing multiple write operations atomically when those
+** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
+** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
+*/
+#define SQLITE_IOCAP_ATOMIC 0x00000001
+#define SQLITE_IOCAP_ATOMIC512 0x00000002
+#define SQLITE_IOCAP_ATOMIC1K 0x00000004
+#define SQLITE_IOCAP_ATOMIC2K 0x00000008
+#define SQLITE_IOCAP_ATOMIC4K 0x00000010
+#define SQLITE_IOCAP_ATOMIC8K 0x00000020
+#define SQLITE_IOCAP_ATOMIC16K 0x00000040
+#define SQLITE_IOCAP_ATOMIC32K 0x00000080
+#define SQLITE_IOCAP_ATOMIC64K 0x00000100
+#define SQLITE_IOCAP_SAFE_APPEND 0x00000200
+#define SQLITE_IOCAP_SEQUENTIAL 0x00000400
+#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
+#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
+#define SQLITE_IOCAP_IMMUTABLE 0x00002000
+#define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
+
+/*
+** CAPI3REF: File Locking Levels
+**
+** SQLite uses one of these integer values as the second
+** argument to calls it makes to the xLock() and xUnlock() methods
+** of an [sqlite3_io_methods] object.
+*/
+#define SQLITE_LOCK_NONE 0
+#define SQLITE_LOCK_SHARED 1
+#define SQLITE_LOCK_RESERVED 2
+#define SQLITE_LOCK_PENDING 3
+#define SQLITE_LOCK_EXCLUSIVE 4
+
+/*
+** CAPI3REF: Synchronization Type Flags
+**
+** When SQLite invokes the xSync() method of an
+** [sqlite3_io_methods] object it uses a combination of
+** these integer values as the second argument.
+**
+** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
+** sync operation only needs to flush data to mass storage. Inode
+** information need not be flushed. If the lower four bits of the flag
+** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
+** If the lower four bits equal SQLITE_SYNC_FULL, that means
+** to use Mac OS X style fullsync instead of fsync().
+**
+** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
+** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
+** settings. The [synchronous pragma] determines when calls to the
+** xSync VFS method occur and applies uniformly across all platforms.
+** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
+** energetic or rigorous or forceful the sync operations are and
+** only make a difference on Mac OSX for the default SQLite code.
+** (Third-party VFS implementations might also make the distinction
+** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
+** operating systems natively supported by SQLite, only Mac OSX
+** cares about the difference.)
+*/
+#define SQLITE_SYNC_NORMAL 0x00002
+#define SQLITE_SYNC_FULL 0x00003
+#define SQLITE_SYNC_DATAONLY 0x00010
+
+/*
+** CAPI3REF: OS Interface Open File Handle
+**
+** An [sqlite3_file] object represents an open file in the
+** [sqlite3_vfs | OS interface layer]. Individual OS interface
+** implementations will
+** want to subclass this object by appending additional fields
+** for their own use. The pMethods entry is a pointer to an
+** [sqlite3_io_methods] object that defines methods for performing
+** I/O operations on the open file.
+*/
+typedef struct sqlite3_file sqlite3_file;
+struct sqlite3_file {
+ const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
+};
+
+/*
+** CAPI3REF: OS Interface File Virtual Methods Object
+**
+** Every file opened by the [sqlite3_vfs.xOpen] method populates an
+** [sqlite3_file] object (or, more commonly, a subclass of the
+** [sqlite3_file] object) with a pointer to an instance of this object.
+** This object defines the methods used to perform various operations
+** against the open file represented by the [sqlite3_file] object.
+**
+** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
+** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
+** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
+** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
+** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
+** to NULL.
+**
+** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
+** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
+** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
+** flag may be ORed in to indicate that only the data of the file
+** and not its inode needs to be synced.
+**
+** The integer values to xLock() and xUnlock() are one of
+** <ul>
+** <li> [SQLITE_LOCK_NONE],
+** <li> [SQLITE_LOCK_SHARED],
+** <li> [SQLITE_LOCK_RESERVED],
+** <li> [SQLITE_LOCK_PENDING], or
+** <li> [SQLITE_LOCK_EXCLUSIVE].
+** </ul>
+** xLock() increases the lock. xUnlock() decreases the lock.
+** The xCheckReservedLock() method checks whether any database connection,
+** either in this process or in some other process, is holding a RESERVED,
+** PENDING, or EXCLUSIVE lock on the file. It returns true
+** if such a lock exists and false otherwise.
+**
+** The xFileControl() method is a generic interface that allows custom
+** VFS implementations to directly control an open file using the
+** [sqlite3_file_control()] interface. The second "op" argument is an
+** integer opcode. The third argument is a generic pointer intended to
+** point to a structure that may contain arguments or space in which to
+** write return values. Potential uses for xFileControl() might be
+** functions to enable blocking locks with timeouts, to change the
+** locking strategy (for example to use dot-file locks), to inquire
+** about the status of a lock, or to break stale locks. The SQLite
+** core reserves all opcodes less than 100 for its own use.
+** A [file control opcodes | list of opcodes] less than 100 is available.
+** Applications that define a custom xFileControl method should use opcodes
+** greater than 100 to avoid conflicts. VFS implementations should
+** return [SQLITE_NOTFOUND] for file control opcodes that they do not
+** recognize.
+**
+** The xSectorSize() method returns the sector size of the
+** device that underlies the file. The sector size is the
+** minimum write that can be performed without disturbing
+** other bytes in the file. The xDeviceCharacteristics()
+** method returns a bit vector describing behaviors of the
+** underlying device:
+**
+** <ul>
+** <li> [SQLITE_IOCAP_ATOMIC]
+** <li> [SQLITE_IOCAP_ATOMIC512]
+** <li> [SQLITE_IOCAP_ATOMIC1K]
+** <li> [SQLITE_IOCAP_ATOMIC2K]
+** <li> [SQLITE_IOCAP_ATOMIC4K]
+** <li> [SQLITE_IOCAP_ATOMIC8K]
+** <li> [SQLITE_IOCAP_ATOMIC16K]
+** <li> [SQLITE_IOCAP_ATOMIC32K]
+** <li> [SQLITE_IOCAP_ATOMIC64K]
+** <li> [SQLITE_IOCAP_SAFE_APPEND]
+** <li> [SQLITE_IOCAP_SEQUENTIAL]
+** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
+** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
+** <li> [SQLITE_IOCAP_IMMUTABLE]
+** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
+** </ul>
+**
+** The SQLITE_IOCAP_ATOMIC property means that all writes of
+** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
+** mean that writes of blocks that are nnn bytes in size and
+** are aligned to an address which is an integer multiple of
+** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
+** that when data is appended to a file, the data is appended
+** first then the size of the file is extended, never the other
+** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
+** information is written to disk in the same order as calls
+** to xWrite().
+**
+** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
+** in the unread portions of the buffer with zeros. A VFS that
+** fails to zero-fill short reads might seem to work. However,
+** failure to zero-fill short reads will eventually lead to
+** database corruption.
+*/
+typedef struct sqlite3_io_methods sqlite3_io_methods;
+struct sqlite3_io_methods {
+ int iVersion;
+ int (*xClose)(sqlite3_file*);
+ int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
+ int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
+ int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
+ int (*xSync)(sqlite3_file*, int flags);
+ int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
+ int (*xLock)(sqlite3_file*, int);
+ int (*xUnlock)(sqlite3_file*, int);
+ int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
+ int (*xFileControl)(sqlite3_file*, int op, void *pArg);
+ int (*xSectorSize)(sqlite3_file*);
+ int (*xDeviceCharacteristics)(sqlite3_file*);
+ /* Methods above are valid for version 1 */
+ int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
+ int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
+ void (*xShmBarrier)(sqlite3_file*);
+ int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
+ /* Methods above are valid for version 2 */
+ int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
+ int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
+ /* Methods above are valid for version 3 */
+ /* Additional methods may be added in future releases */
+};
+
+/*
+** CAPI3REF: Standard File Control Opcodes
+** KEYWORDS: {file control opcodes} {file control opcode}
+**
+** These integer constants are opcodes for the xFileControl method
+** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
+** interface.
+**
+** <ul>
+** <li>[[SQLITE_FCNTL_LOCKSTATE]]
+** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
+** opcode causes the xFileControl method to write the current state of
+** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
+** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
+** into an integer that the pArg argument points to. This capability
+** is used during testing and is only available when the SQLITE_TEST
+** compile-time option is used.
+**
+** <li>[[SQLITE_FCNTL_SIZE_HINT]]
+** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
+** layer a hint of how large the database file will grow to be during the
+** current transaction. This hint is not guaranteed to be accurate but it
+** is often close. The underlying VFS might choose to preallocate database
+** file space based on this hint in order to help writes to the database
+** file run faster.
+**
+** <li>[[SQLITE_FCNTL_SIZE_LIMIT]]
+** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that
+** implements [sqlite3_deserialize()] to set an upper bound on the size
+** of the in-memory database. The argument is a pointer to a [sqlite3_int64].
+** If the integer pointed to is negative, then it is filled in with the
+** current limit. Otherwise the limit is set to the larger of the value
+** of the integer pointed to and the current database size. The integer
+** pointed to is set to the new limit.
+**
+** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
+** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
+** extends and truncates the database file in chunks of a size specified
+** by the user. The fourth argument to [sqlite3_file_control()] should
+** point to an integer (type int) containing the new chunk-size to use
+** for the nominated database. Allocating database file space in large
+** chunks (say 1MB at a time), may reduce file-system fragmentation and
+** improve performance on some systems.
+**
+** <li>[[SQLITE_FCNTL_FILE_POINTER]]
+** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
+** to the [sqlite3_file] object associated with a particular database
+** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
+**
+** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
+** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
+** to the [sqlite3_file] object associated with the journal file (either
+** the [rollback journal] or the [write-ahead log]) for a particular database
+** connection. See also [SQLITE_FCNTL_FILE_POINTER].
+**
+** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
+** No longer in use.
+**
+** <li>[[SQLITE_FCNTL_SYNC]]
+** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
+** sent to the VFS immediately before the xSync method is invoked on a
+** database file descriptor. Or, if the xSync method is not invoked
+** because the user has configured SQLite with
+** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
+** of the xSync method. In most cases, the pointer argument passed with
+** this file-control is NULL. However, if the database file is being synced
+** as part of a multi-database commit, the argument points to a nul-terminated
+** string containing the transactions super-journal file name. VFSes that
+** do not need this signal should silently ignore this opcode. Applications
+** should not call [sqlite3_file_control()] with this opcode as doing so may
+** disrupt the operation of the specialized VFSes that do require it.
+**
+** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
+** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
+** and sent to the VFS after a transaction has been committed immediately
+** but before the database is unlocked. VFSes that do not need this signal
+** should silently ignore this opcode. Applications should not call
+** [sqlite3_file_control()] with this opcode as doing so may disrupt the
+** operation of the specialized VFSes that do require it.
+**
+** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
+** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
+** retry counts and intervals for certain disk I/O operations for the
+** windows [VFS] in order to provide robustness in the presence of
+** anti-virus programs. By default, the windows VFS will retry file read,
+** file write, and file delete operations up to 10 times, with a delay
+** of 25 milliseconds before the first retry and with the delay increasing
+** by an additional 25 milliseconds with each subsequent retry. This
+** opcode allows these two values (10 retries and 25 milliseconds of delay)
+** to be adjusted. The values are changed for all database connections
+** within the same process. The argument is a pointer to an array of two
+** integers where the first integer is the new retry count and the second
+** integer is the delay. If either integer is negative, then the setting
+** is not changed but instead the prior value of that setting is written
+** into the array entry, allowing the current retry settings to be
+** interrogated. The zDbName parameter is ignored.
+**
+** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
+** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
+** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
+** write ahead log ([WAL file]) and shared memory
+** files used for transaction control
+** are automatically deleted when the latest connection to the database
+** closes. Setting persistent WAL mode causes those files to persist after
+** close. Persisting the files is useful when other processes that do not
+** have write permission on the directory containing the database file want
+** to read the database file, as the WAL and shared memory files must exist
+** in order for the database to be readable. The fourth parameter to
+** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
+** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
+** WAL mode. If the integer is -1, then it is overwritten with the current
+** WAL persistence setting.
+**
+** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
+** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
+** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
+** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
+** xDeviceCharacteristics methods. The fourth parameter to
+** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
+** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
+** mode. If the integer is -1, then it is overwritten with the current
+** zero-damage mode setting.
+**
+** <li>[[SQLITE_FCNTL_OVERWRITE]]
+** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
+** a write transaction to indicate that, unless it is rolled back for some
+** reason, the entire database file will be overwritten by the current
+** transaction. This is used by VACUUM operations.
+**
+** <li>[[SQLITE_FCNTL_VFSNAME]]
+** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
+** all [VFSes] in the VFS stack. The names are of all VFS shims and the
+** final bottom-level VFS are written into memory obtained from
+** [sqlite3_malloc()] and the result is stored in the char* variable
+** that the fourth parameter of [sqlite3_file_control()] points to.
+** The caller is responsible for freeing the memory when done. As with
+** all file-control actions, there is no guarantee that this will actually
+** do anything. Callers should initialize the char* variable to a NULL
+** pointer in case this file-control is not implemented. This file-control
+** is intended for diagnostic use only.
+**
+** <li>[[SQLITE_FCNTL_VFS_POINTER]]
+** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
+** [VFSes] currently in use. ^(The argument X in
+** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
+** of type "[sqlite3_vfs] **". This opcodes will set *X
+** to a pointer to the top-level VFS.)^
+** ^When there are multiple VFS shims in the stack, this opcode finds the
+** upper-most shim only.
+**
+** <li>[[SQLITE_FCNTL_PRAGMA]]
+** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
+** file control is sent to the open [sqlite3_file] object corresponding
+** to the database file to which the pragma statement refers. ^The argument
+** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
+** pointers to strings (char**) in which the second element of the array
+** is the name of the pragma and the third element is the argument to the
+** pragma or NULL if the pragma has no argument. ^The handler for an
+** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
+** of the char** argument point to a string obtained from [sqlite3_mprintf()]
+** or the equivalent and that string will become the result of the pragma or
+** the error message if the pragma fails. ^If the
+** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
+** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
+** file control returns [SQLITE_OK], then the parser assumes that the
+** VFS has handled the PRAGMA itself and the parser generates a no-op
+** prepared statement if result string is NULL, or that returns a copy
+** of the result string if the string is non-NULL.
+** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
+** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
+** that the VFS encountered an error while handling the [PRAGMA] and the
+** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
+** file control occurs at the beginning of pragma statement analysis and so
+** it is able to override built-in [PRAGMA] statements.
+**
+** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
+** ^The [SQLITE_FCNTL_BUSYHANDLER]
+** file-control may be invoked by SQLite on the database file handle
+** shortly after it is opened in order to provide a custom VFS with access
+** to the connection's busy-handler callback. The argument is of type (void**)
+** - an array of two (void *) values. The first (void *) actually points
+** to a function of type (int (*)(void *)). In order to invoke the connection's
+** busy-handler, this function should be invoked with the second (void *) in
+** the array as the only argument. If it returns non-zero, then the operation
+** should be retried. If it returns zero, the custom VFS should abandon the
+** current operation.
+**
+** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
+** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
+** to have SQLite generate a
+** temporary filename using the same algorithm that is followed to generate
+** temporary filenames for TEMP tables and other internal uses. The
+** argument should be a char** which will be filled with the filename
+** written into memory obtained from [sqlite3_malloc()]. The caller should
+** invoke [sqlite3_free()] on the result to avoid a memory leak.
+**
+** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
+** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
+** maximum number of bytes that will be used for memory-mapped I/O.
+** The argument is a pointer to a value of type sqlite3_int64 that
+** is an advisory maximum number of bytes in the file to memory map. The
+** pointer is overwritten with the old value. The limit is not changed if
+** the value originally pointed to is negative, and so the current limit
+** can be queried by passing in a pointer to a negative number. This
+** file-control is used internally to implement [PRAGMA mmap_size].
+**
+** <li>[[SQLITE_FCNTL_TRACE]]
+** The [SQLITE_FCNTL_TRACE] file control provides advisory information
+** to the VFS about what the higher layers of the SQLite stack are doing.
+** This file control is used by some VFS activity tracing [shims].
+** The argument is a zero-terminated string. Higher layers in the
+** SQLite stack may generate instances of this file control if
+** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
+**
+** <li>[[SQLITE_FCNTL_HAS_MOVED]]
+** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
+** pointer to an integer and it writes a boolean into that integer depending
+** on whether or not the file has been renamed, moved, or deleted since it
+** was first opened.
+**
+** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
+** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
+** underlying native file handle associated with a file handle. This file
+** control interprets its argument as a pointer to a native file handle and
+** writes the resulting value there.
+**
+** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
+** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
+** opcode causes the xFileControl method to swap the file handle with the one
+** pointed to by the pArg argument. This capability is used during testing
+** and only needs to be supported when SQLITE_TEST is defined.
+**
+** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
+** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
+** be advantageous to block on the next WAL lock if the lock is not immediately
+** available. The WAL subsystem issues this signal during rare
+** circumstances in order to fix a problem with priority inversion.
+** Applications should <em>not</em> use this file-control.
+**
+** <li>[[SQLITE_FCNTL_ZIPVFS]]
+** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
+** VFS should return SQLITE_NOTFOUND for this opcode.
+**
+** <li>[[SQLITE_FCNTL_RBU]]
+** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
+** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
+** this opcode.
+**
+** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
+** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
+** the file descriptor is placed in "batch write mode", which
+** means all subsequent write operations will be deferred and done
+** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
+** that do not support batch atomic writes will return SQLITE_NOTFOUND.
+** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
+** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
+** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
+** no VFS interface calls on the same [sqlite3_file] file descriptor
+** except for calls to the xWrite method and the xFileControl method
+** with [SQLITE_FCNTL_SIZE_HINT].
+**
+** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
+** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
+** operations since the previous successful call to
+** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
+** This file control returns [SQLITE_OK] if and only if the writes were
+** all performed successfully and have been committed to persistent storage.
+** ^Regardless of whether or not it is successful, this file control takes
+** the file descriptor out of batch write mode so that all subsequent
+** write operations are independent.
+** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
+** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
+**
+** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
+** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
+** operations since the previous successful call to
+** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
+** ^This file control takes the file descriptor out of batch write mode
+** so that all subsequent write operations are independent.
+** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
+** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
+**
+** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
+** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS
+** to block for up to M milliseconds before failing when attempting to
+** obtain a file lock using the xLock or xShmLock methods of the VFS.
+** The parameter is a pointer to a 32-bit signed integer that contains
+** the value that M is to be set to. Before returning, the 32-bit signed
+** integer is overwritten with the previous value of M.
+**
+** <li>[[SQLITE_FCNTL_DATA_VERSION]]
+** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
+** a database file. The argument is a pointer to a 32-bit unsigned integer.
+** The "data version" for the pager is written into the pointer. The
+** "data version" changes whenever any change occurs to the corresponding
+** database file, either through SQL statements on the same database
+** connection or through transactions committed by separate database
+** connections possibly in other processes. The [sqlite3_total_changes()]
+** interface can be used to find if any database on the connection has changed,
+** but that interface responds to changes on TEMP as well as MAIN and does
+** not provide a mechanism to detect changes to MAIN only. Also, the
+** [sqlite3_total_changes()] interface responds to internal changes only and
+** omits changes made by other database connections. The
+** [PRAGMA data_version] command provides a mechanism to detect changes to
+** a single attached database that occur due to other database connections,
+** but omits changes implemented by the database connection on which it is
+** called. This file control is the only mechanism to detect changes that
+** happen either internally or externally and that are associated with
+** a particular attached database.
+**
+** <li>[[SQLITE_FCNTL_CKPT_START]]
+** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint
+** in wal mode before the client starts to copy pages from the wal
+** file to the database file.
+**
+** <li>[[SQLITE_FCNTL_CKPT_DONE]]
+** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint
+** in wal mode after the client has finished copying pages from the wal
+** file to the database file, but before the *-shm file is updated to
+** record the fact that the pages have been checkpointed.
+** </ul>
+*/
+#define SQLITE_FCNTL_LOCKSTATE 1
+#define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
+#define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
+#define SQLITE_FCNTL_LAST_ERRNO 4
+#define SQLITE_FCNTL_SIZE_HINT 5
+#define SQLITE_FCNTL_CHUNK_SIZE 6
+#define SQLITE_FCNTL_FILE_POINTER 7
+#define SQLITE_FCNTL_SYNC_OMITTED 8
+#define SQLITE_FCNTL_WIN32_AV_RETRY 9
+#define SQLITE_FCNTL_PERSIST_WAL 10
+#define SQLITE_FCNTL_OVERWRITE 11
+#define SQLITE_FCNTL_VFSNAME 12
+#define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
+#define SQLITE_FCNTL_PRAGMA 14
+#define SQLITE_FCNTL_BUSYHANDLER 15
+#define SQLITE_FCNTL_TEMPFILENAME 16
+#define SQLITE_FCNTL_MMAP_SIZE 18
+#define SQLITE_FCNTL_TRACE 19
+#define SQLITE_FCNTL_HAS_MOVED 20
+#define SQLITE_FCNTL_SYNC 21
+#define SQLITE_FCNTL_COMMIT_PHASETWO 22
+#define SQLITE_FCNTL_WIN32_SET_HANDLE 23
+#define SQLITE_FCNTL_WAL_BLOCK 24
+#define SQLITE_FCNTL_ZIPVFS 25
+#define SQLITE_FCNTL_RBU 26
+#define SQLITE_FCNTL_VFS_POINTER 27
+#define SQLITE_FCNTL_JOURNAL_POINTER 28
+#define SQLITE_FCNTL_WIN32_GET_HANDLE 29
+#define SQLITE_FCNTL_PDB 30
+#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
+#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
+#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
+#define SQLITE_FCNTL_LOCK_TIMEOUT 34
+#define SQLITE_FCNTL_DATA_VERSION 35
+#define SQLITE_FCNTL_SIZE_LIMIT 36
+#define SQLITE_FCNTL_CKPT_DONE 37
+#define SQLITE_FCNTL_RESERVE_BYTES 38
+#define SQLITE_FCNTL_CKPT_START 39
+
+/* deprecated names */
+#define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
+#define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
+#define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
+
+
+/*
+** CAPI3REF: Mutex Handle
+**
+** The mutex module within SQLite defines [sqlite3_mutex] to be an
+** abstract type for a mutex object. The SQLite core never looks
+** at the internal representation of an [sqlite3_mutex]. It only
+** deals with pointers to the [sqlite3_mutex] object.
+**
+** Mutexes are created using [sqlite3_mutex_alloc()].
+*/
+typedef struct sqlite3_mutex sqlite3_mutex;
+
+/*
+** CAPI3REF: Loadable Extension Thunk
+**
+** A pointer to the opaque sqlite3_api_routines structure is passed as
+** the third parameter to entry points of [loadable extensions]. This
+** structure must be typedefed in order to work around compiler warnings
+** on some platforms.
+*/
+typedef struct sqlite3_api_routines sqlite3_api_routines;
+
+/*
+** CAPI3REF: OS Interface Object
+**
+** An instance of the sqlite3_vfs object defines the interface between
+** the SQLite core and the underlying operating system. The "vfs"
+** in the name of the object stands for "virtual file system". See
+** the [VFS | VFS documentation] for further information.
+**
+** The VFS interface is sometimes extended by adding new methods onto
+** the end. Each time such an extension occurs, the iVersion field
+** is incremented. The iVersion value started out as 1 in
+** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2
+** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased
+** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields
+** may be appended to the sqlite3_vfs object and the iVersion value
+** may increase again in future versions of SQLite.
+** Note that due to an oversight, the structure
+** of the sqlite3_vfs object changed in the transition from
+** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
+** and yet the iVersion field was not increased.
+**
+** The szOsFile field is the size of the subclassed [sqlite3_file]
+** structure used by this VFS. mxPathname is the maximum length of
+** a pathname in this VFS.
+**
+** Registered sqlite3_vfs objects are kept on a linked list formed by
+** the pNext pointer. The [sqlite3_vfs_register()]
+** and [sqlite3_vfs_unregister()] interfaces manage this list
+** in a thread-safe way. The [sqlite3_vfs_find()] interface
+** searches the list. Neither the application code nor the VFS
+** implementation should use the pNext pointer.
+**
+** The pNext field is the only field in the sqlite3_vfs
+** structure that SQLite will ever modify. SQLite will only access
+** or modify this field while holding a particular static mutex.
+** The application should never modify anything within the sqlite3_vfs
+** object once the object has been registered.
+**
+** The zName field holds the name of the VFS module. The name must
+** be unique across all VFS modules.
+**
+** [[sqlite3_vfs.xOpen]]
+** ^SQLite guarantees that the zFilename parameter to xOpen
+** is either a NULL pointer or string obtained
+** from xFullPathname() with an optional suffix added.
+** ^If a suffix is added to the zFilename parameter, it will
+** consist of a single "-" character followed by no more than
+** 11 alphanumeric and/or "-" characters.
+** ^SQLite further guarantees that
+** the string will be valid and unchanged until xClose() is
+** called. Because of the previous sentence,
+** the [sqlite3_file] can safely store a pointer to the
+** filename if it needs to remember the filename for some reason.
+** If the zFilename parameter to xOpen is a NULL pointer then xOpen
+** must invent its own temporary name for the file. ^Whenever the
+** xFilename parameter is NULL it will also be the case that the
+** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
+**
+** The flags argument to xOpen() includes all bits set in
+** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
+** or [sqlite3_open16()] is used, then flags includes at least
+** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
+** If xOpen() opens a file read-only then it sets *pOutFlags to
+** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
+**
+** ^(SQLite will also add one of the following flags to the xOpen()
+** call, depending on the object being opened:
+**
+** <ul>
+** <li> [SQLITE_OPEN_MAIN_DB]
+** <li> [SQLITE_OPEN_MAIN_JOURNAL]
+** <li> [SQLITE_OPEN_TEMP_DB]
+** <li> [SQLITE_OPEN_TEMP_JOURNAL]
+** <li> [SQLITE_OPEN_TRANSIENT_DB]
+** <li> [SQLITE_OPEN_SUBJOURNAL]
+** <li> [SQLITE_OPEN_SUPER_JOURNAL]
+** <li> [SQLITE_OPEN_WAL]
+** </ul>)^
+**
+** The file I/O implementation can use the object type flags to
+** change the way it deals with files. For example, an application
+** that does not care about crash recovery or rollback might make
+** the open of a journal file a no-op. Writes to this journal would
+** also be no-ops, and any attempt to read the journal would return
+** SQLITE_IOERR. Or the implementation might recognize that a database
+** file will be doing page-aligned sector reads and writes in a random
+** order and set up its I/O subsystem accordingly.
+**
+** SQLite might also add one of the following flags to the xOpen method:
+**
+** <ul>
+** <li> [SQLITE_OPEN_DELETEONCLOSE]
+** <li> [SQLITE_OPEN_EXCLUSIVE]
+** </ul>
+**
+** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
+** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
+** will be set for TEMP databases and their journals, transient
+** databases, and subjournals.
+**
+** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
+** with the [SQLITE_OPEN_CREATE] flag, which are both directly
+** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
+** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
+** SQLITE_OPEN_CREATE, is used to indicate that file should always
+** be created, and that it is an error if it already exists.
+** It is <i>not</i> used to indicate the file should be opened
+** for exclusive access.
+**
+** ^At least szOsFile bytes of memory are allocated by SQLite
+** to hold the [sqlite3_file] structure passed as the third
+** argument to xOpen. The xOpen method does not have to
+** allocate the structure; it should just fill it in. Note that
+** the xOpen method must set the sqlite3_file.pMethods to either
+** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
+** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
+** element will be valid after xOpen returns regardless of the success
+** or failure of the xOpen call.
+**
+** [[sqlite3_vfs.xAccess]]
+** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
+** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
+** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
+** to test whether a file is at least readable. The SQLITE_ACCESS_READ
+** flag is never actually used and is not implemented in the built-in
+** VFSes of SQLite. The file is named by the second argument and can be a
+** directory. The xAccess method returns [SQLITE_OK] on success or some
+** non-zero error code if there is an I/O error or if the name of
+** the file given in the second argument is illegal. If SQLITE_OK
+** is returned, then non-zero or zero is written into *pResOut to indicate
+** whether or not the file is accessible.
+**
+** ^SQLite will always allocate at least mxPathname+1 bytes for the
+** output buffer xFullPathname. The exact size of the output buffer
+** is also passed as a parameter to both methods. If the output buffer
+** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
+** handled as a fatal error by SQLite, vfs implementations should endeavor
+** to prevent this by setting mxPathname to a sufficiently large value.
+**
+** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
+** interfaces are not strictly a part of the filesystem, but they are
+** included in the VFS structure for completeness.
+** The xRandomness() function attempts to return nBytes bytes
+** of good-quality randomness into zOut. The return value is
+** the actual number of bytes of randomness obtained.
+** The xSleep() method causes the calling thread to sleep for at
+** least the number of microseconds given. ^The xCurrentTime()
+** method returns a Julian Day Number for the current date and time as
+** a floating point value.
+** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
+** Day Number multiplied by 86400000 (the number of milliseconds in
+** a 24-hour day).
+** ^SQLite will use the xCurrentTimeInt64() method to get the current
+** date and time if that method is available (if iVersion is 2 or
+** greater and the function pointer is not NULL) and will fall back
+** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
+**
+** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
+** are not used by the SQLite core. These optional interfaces are provided
+** by some VFSes to facilitate testing of the VFS code. By overriding
+** system calls with functions under its control, a test program can
+** simulate faults and error conditions that would otherwise be difficult
+** or impossible to induce. The set of system calls that can be overridden
+** varies from one VFS to another, and from one version of the same VFS to the
+** next. Applications that use these interfaces must be prepared for any
+** or all of these interfaces to be NULL or for their behavior to change
+** from one release to the next. Applications must not attempt to access
+** any of these methods if the iVersion of the VFS is less than 3.
+*/
+typedef struct sqlite3_vfs sqlite3_vfs;
+typedef void (*sqlite3_syscall_ptr)(void);
+struct sqlite3_vfs {
+ int iVersion; /* Structure version number (currently 3) */
+ int szOsFile; /* Size of subclassed sqlite3_file */
+ int mxPathname; /* Maximum file pathname length */
+ sqlite3_vfs *pNext; /* Next registered VFS */
+ const char *zName; /* Name of this virtual file system */
+ void *pAppData; /* Pointer to application-specific data */
+ int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
+ int flags, int *pOutFlags);
+ int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
+ int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
+ int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
+ void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
+ void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
+ void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
+ void (*xDlClose)(sqlite3_vfs*, void*);
+ int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
+ int (*xSleep)(sqlite3_vfs*, int microseconds);
+ int (*xCurrentTime)(sqlite3_vfs*, double*);
+ int (*xGetLastError)(sqlite3_vfs*, int, char *);
+ /*
+ ** The methods above are in version 1 of the sqlite_vfs object
+ ** definition. Those that follow are added in version 2 or later
+ */
+ int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
+ /*
+ ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
+ ** Those below are for version 3 and greater.
+ */
+ int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
+ sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
+ const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
+ /*
+ ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
+ ** New fields may be appended in future versions. The iVersion
+ ** value will increment whenever this happens.
+ */
+};
+
+/*
+** CAPI3REF: Flags for the xAccess VFS method
+**
+** These integer constants can be used as the third parameter to
+** the xAccess method of an [sqlite3_vfs] object. They determine
+** what kind of permissions the xAccess method is looking for.
+** With SQLITE_ACCESS_EXISTS, the xAccess method
+** simply checks whether the file exists.
+** With SQLITE_ACCESS_READWRITE, the xAccess method
+** checks whether the named directory is both readable and writable
+** (in other words, if files can be added, removed, and renamed within
+** the directory).
+** The SQLITE_ACCESS_READWRITE constant is currently used only by the
+** [temp_store_directory pragma], though this could change in a future
+** release of SQLite.
+** With SQLITE_ACCESS_READ, the xAccess method
+** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
+** currently unused, though it might be used in a future release of
+** SQLite.
+*/
+#define SQLITE_ACCESS_EXISTS 0
+#define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
+#define SQLITE_ACCESS_READ 2 /* Unused */
+
+/*
+** CAPI3REF: Flags for the xShmLock VFS method
+**
+** These integer constants define the various locking operations
+** allowed by the xShmLock method of [sqlite3_io_methods]. The
+** following are the only legal combinations of flags to the
+** xShmLock method:
+**
+** <ul>
+** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
+** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
+** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
+** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
+** </ul>
+**
+** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
+** was given on the corresponding lock.
+**
+** The xShmLock method can transition between unlocked and SHARED or
+** between unlocked and EXCLUSIVE. It cannot transition between SHARED
+** and EXCLUSIVE.
+*/
+#define SQLITE_SHM_UNLOCK 1
+#define SQLITE_SHM_LOCK 2
+#define SQLITE_SHM_SHARED 4
+#define SQLITE_SHM_EXCLUSIVE 8
+
+/*
+** CAPI3REF: Maximum xShmLock index
+**
+** The xShmLock method on [sqlite3_io_methods] may use values
+** between 0 and this upper bound as its "offset" argument.
+** The SQLite core will never attempt to acquire or release a
+** lock outside of this range
+*/
+#define SQLITE_SHM_NLOCK 8
+
+
+/*
+** CAPI3REF: Initialize The SQLite Library
+**
+** ^The sqlite3_initialize() routine initializes the
+** SQLite library. ^The sqlite3_shutdown() routine
+** deallocates any resources that were allocated by sqlite3_initialize().
+** These routines are designed to aid in process initialization and
+** shutdown on embedded systems. Workstation applications using
+** SQLite normally do not need to invoke either of these routines.
+**
+** A call to sqlite3_initialize() is an "effective" call if it is
+** the first time sqlite3_initialize() is invoked during the lifetime of
+** the process, or if it is the first time sqlite3_initialize() is invoked
+** following a call to sqlite3_shutdown(). ^(Only an effective call
+** of sqlite3_initialize() does any initialization. All other calls
+** are harmless no-ops.)^
+**
+** A call to sqlite3_shutdown() is an "effective" call if it is the first
+** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
+** an effective call to sqlite3_shutdown() does any deinitialization.
+** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
+**
+** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
+** is not. The sqlite3_shutdown() interface must only be called from a
+** single thread. All open [database connections] must be closed and all
+** other SQLite resources must be deallocated prior to invoking
+** sqlite3_shutdown().
+**
+** Among other things, ^sqlite3_initialize() will invoke
+** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
+** will invoke sqlite3_os_end().
+**
+** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
+** ^If for some reason, sqlite3_initialize() is unable to initialize
+** the library (perhaps it is unable to allocate a needed resource such
+** as a mutex) it returns an [error code] other than [SQLITE_OK].
+**
+** ^The sqlite3_initialize() routine is called internally by many other
+** SQLite interfaces so that an application usually does not need to
+** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
+** calls sqlite3_initialize() so the SQLite library will be automatically
+** initialized when [sqlite3_open()] is called if it has not be initialized
+** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
+** compile-time option, then the automatic calls to sqlite3_initialize()
+** are omitted and the application must call sqlite3_initialize() directly
+** prior to using any other SQLite interface. For maximum portability,
+** it is recommended that applications always invoke sqlite3_initialize()
+** directly prior to using any other SQLite interface. Future releases
+** of SQLite may require this. In other words, the behavior exhibited
+** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
+** default behavior in some future release of SQLite.
+**
+** The sqlite3_os_init() routine does operating-system specific
+** initialization of the SQLite library. The sqlite3_os_end()
+** routine undoes the effect of sqlite3_os_init(). Typical tasks
+** performed by these routines include allocation or deallocation
+** of static resources, initialization of global variables,
+** setting up a default [sqlite3_vfs] module, or setting up
+** a default configuration using [sqlite3_config()].
+**
+** The application should never invoke either sqlite3_os_init()
+** or sqlite3_os_end() directly. The application should only invoke
+** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
+** interface is called automatically by sqlite3_initialize() and
+** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
+** implementations for sqlite3_os_init() and sqlite3_os_end()
+** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
+** When [custom builds | built for other platforms]
+** (using the [SQLITE_OS_OTHER=1] compile-time
+** option) the application must supply a suitable implementation for
+** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
+** implementation of sqlite3_os_init() or sqlite3_os_end()
+** must return [SQLITE_OK] on success and some other [error code] upon
+** failure.
+*/
+SQLITE_API int sqlite3_initialize(void);
+SQLITE_API int sqlite3_shutdown(void);
+SQLITE_API int sqlite3_os_init(void);
+SQLITE_API int sqlite3_os_end(void);
+
+/*
+** CAPI3REF: Configuring The SQLite Library
+**
+** The sqlite3_config() interface is used to make global configuration
+** changes to SQLite in order to tune SQLite to the specific needs of
+** the application. The default configuration is recommended for most
+** applications and so this routine is usually not necessary. It is
+** provided to support rare applications with unusual needs.
+**
+** <b>The sqlite3_config() interface is not threadsafe. The application
+** must ensure that no other SQLite interfaces are invoked by other
+** threads while sqlite3_config() is running.</b>
+**
+** The sqlite3_config() interface
+** may only be invoked prior to library initialization using
+** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
+** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
+** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
+** Note, however, that ^sqlite3_config() can be called as part of the
+** implementation of an application-defined [sqlite3_os_init()].
+**
+** The first argument to sqlite3_config() is an integer
+** [configuration option] that determines
+** what property of SQLite is to be configured. Subsequent arguments
+** vary depending on the [configuration option]
+** in the first argument.
+**
+** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
+** ^If the option is unknown or SQLite is unable to set the option
+** then this routine returns a non-zero [error code].
+*/
+SQLITE_API int sqlite3_config(int, ...);
+
+/*
+** CAPI3REF: Configure database connections
+** METHOD: sqlite3
+**
+** The sqlite3_db_config() interface is used to make configuration
+** changes to a [database connection]. The interface is similar to
+** [sqlite3_config()] except that the changes apply to a single
+** [database connection] (specified in the first argument).
+**
+** The second argument to sqlite3_db_config(D,V,...) is the
+** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
+** that indicates what aspect of the [database connection] is being configured.
+** Subsequent arguments vary depending on the configuration verb.
+**
+** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
+** the call is considered successful.
+*/
+SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
+
+/*
+** CAPI3REF: Memory Allocation Routines
+**
+** An instance of this object defines the interface between SQLite
+** and low-level memory allocation routines.
+**
+** This object is used in only one place in the SQLite interface.
+** A pointer to an instance of this object is the argument to
+** [sqlite3_config()] when the configuration option is
+** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
+** By creating an instance of this object
+** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
+** during configuration, an application can specify an alternative
+** memory allocation subsystem for SQLite to use for all of its
+** dynamic memory needs.
+**
+** Note that SQLite comes with several [built-in memory allocators]
+** that are perfectly adequate for the overwhelming majority of applications
+** and that this object is only useful to a tiny minority of applications
+** with specialized memory allocation requirements. This object is
+** also used during testing of SQLite in order to specify an alternative
+** memory allocator that simulates memory out-of-memory conditions in
+** order to verify that SQLite recovers gracefully from such
+** conditions.
+**
+** The xMalloc, xRealloc, and xFree methods must work like the
+** malloc(), realloc() and free() functions from the standard C library.
+** ^SQLite guarantees that the second argument to
+** xRealloc is always a value returned by a prior call to xRoundup.
+**
+** xSize should return the allocated size of a memory allocation
+** previously obtained from xMalloc or xRealloc. The allocated size
+** is always at least as big as the requested size but may be larger.
+**
+** The xRoundup method returns what would be the allocated size of
+** a memory allocation given a particular requested size. Most memory
+** allocators round up memory allocations at least to the next multiple
+** of 8. Some allocators round up to a larger multiple or to a power of 2.
+** Every memory allocation request coming in through [sqlite3_malloc()]
+** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
+** that causes the corresponding memory allocation to fail.
+**
+** The xInit method initializes the memory allocator. For example,
+** it might allocate any required mutexes or initialize internal data
+** structures. The xShutdown method is invoked (indirectly) by
+** [sqlite3_shutdown()] and should deallocate any resources acquired
+** by xInit. The pAppData pointer is used as the only parameter to
+** xInit and xShutdown.
+**
+** SQLite holds the [SQLITE_MUTEX_STATIC_MAIN] mutex when it invokes
+** the xInit method, so the xInit method need not be threadsafe. The
+** xShutdown method is only called from [sqlite3_shutdown()] so it does
+** not need to be threadsafe either. For all other methods, SQLite
+** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
+** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
+** it is by default) and so the methods are automatically serialized.
+** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
+** methods must be threadsafe or else make their own arrangements for
+** serialization.
+**
+** SQLite will never invoke xInit() more than once without an intervening
+** call to xShutdown().
+*/
+typedef struct sqlite3_mem_methods sqlite3_mem_methods;
+struct sqlite3_mem_methods {
+ void *(*xMalloc)(int); /* Memory allocation function */
+ void (*xFree)(void*); /* Free a prior allocation */
+ void *(*xRealloc)(void*,int); /* Resize an allocation */
+ int (*xSize)(void*); /* Return the size of an allocation */
+ int (*xRoundup)(int); /* Round up request size to allocation size */
+ int (*xInit)(void*); /* Initialize the memory allocator */
+ void (*xShutdown)(void*); /* Deinitialize the memory allocator */
+ void *pAppData; /* Argument to xInit() and xShutdown() */
+};
+
+/*
+** CAPI3REF: Configuration Options
+** KEYWORDS: {configuration option}
+**
+** These constants are the available integer configuration options that
+** can be passed as the first argument to the [sqlite3_config()] interface.
+**
+** New configuration options may be added in future releases of SQLite.
+** Existing configuration options might be discontinued. Applications
+** should check the return code from [sqlite3_config()] to make sure that
+** the call worked. The [sqlite3_config()] interface will return a
+** non-zero [error code] if a discontinued or unsupported configuration option
+** is invoked.
+**
+** <dl>
+** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
+** <dd>There are no arguments to this option. ^This option sets the
+** [threading mode] to Single-thread. In other words, it disables
+** all mutexing and puts SQLite into a mode where it can only be used
+** by a single thread. ^If SQLite is compiled with
+** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
+** it is not possible to change the [threading mode] from its default
+** value of Single-thread and so [sqlite3_config()] will return
+** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
+** configuration option.</dd>
+**
+** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
+** <dd>There are no arguments to this option. ^This option sets the
+** [threading mode] to Multi-thread. In other words, it disables
+** mutexing on [database connection] and [prepared statement] objects.
+** The application is responsible for serializing access to
+** [database connections] and [prepared statements]. But other mutexes
+** are enabled so that SQLite will be safe to use in a multi-threaded
+** environment as long as no two threads attempt to use the same
+** [database connection] at the same time. ^If SQLite is compiled with
+** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
+** it is not possible to set the Multi-thread [threading mode] and
+** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
+** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
+**
+** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
+** <dd>There are no arguments to this option. ^This option sets the
+** [threading mode] to Serialized. In other words, this option enables
+** all mutexes including the recursive
+** mutexes on [database connection] and [prepared statement] objects.
+** In this mode (which is the default when SQLite is compiled with
+** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
+** to [database connections] and [prepared statements] so that the
+** application is free to use the same [database connection] or the
+** same [prepared statement] in different threads at the same time.
+** ^If SQLite is compiled with
+** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
+** it is not possible to set the Serialized [threading mode] and
+** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
+** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
+**
+** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
+** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
+** a pointer to an instance of the [sqlite3_mem_methods] structure.
+** The argument specifies
+** alternative low-level memory allocation routines to be used in place of
+** the memory allocation routines built into SQLite.)^ ^SQLite makes
+** its own private copy of the content of the [sqlite3_mem_methods] structure
+** before the [sqlite3_config()] call returns.</dd>
+**
+** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
+** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
+** is a pointer to an instance of the [sqlite3_mem_methods] structure.
+** The [sqlite3_mem_methods]
+** structure is filled with the currently defined memory allocation routines.)^
+** This option can be used to overload the default memory allocation
+** routines with a wrapper that simulations memory allocation failure or
+** tracks memory usage, for example. </dd>
+**
+** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
+** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
+** type int, interpreted as a boolean, which if true provides a hint to
+** SQLite that it should avoid large memory allocations if possible.
+** SQLite will run faster if it is free to make large memory allocations,
+** but some application might prefer to run slower in exchange for
+** guarantees about memory fragmentation that are possible if large
+** allocations are avoided. This hint is normally off.
+** </dd>
+**
+** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
+** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
+** interpreted as a boolean, which enables or disables the collection of
+** memory allocation statistics. ^(When memory allocation statistics are
+** disabled, the following SQLite interfaces become non-operational:
+** <ul>
+** <li> [sqlite3_hard_heap_limit64()]
+** <li> [sqlite3_memory_used()]
+** <li> [sqlite3_memory_highwater()]
+** <li> [sqlite3_soft_heap_limit64()]
+** <li> [sqlite3_status64()]
+** </ul>)^
+** ^Memory allocation statistics are enabled by default unless SQLite is
+** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
+** allocation statistics are disabled by default.
+** </dd>
+**
+** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
+** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
+** </dd>
+**
+** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
+** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
+** that SQLite can use for the database page cache with the default page
+** cache implementation.
+** This configuration option is a no-op if an application-defined page
+** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
+** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
+** 8-byte aligned memory (pMem), the size of each page cache line (sz),
+** and the number of cache lines (N).
+** The sz argument should be the size of the largest database page
+** (a power of two between 512 and 65536) plus some extra bytes for each
+** page header. ^The number of extra bytes needed by the page header
+** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
+** ^It is harmless, apart from the wasted memory,
+** for the sz parameter to be larger than necessary. The pMem
+** argument must be either a NULL pointer or a pointer to an 8-byte
+** aligned block of memory of at least sz*N bytes, otherwise
+** subsequent behavior is undefined.
+** ^When pMem is not NULL, SQLite will strive to use the memory provided
+** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
+** a page cache line is larger than sz bytes or if all of the pMem buffer
+** is exhausted.
+** ^If pMem is NULL and N is non-zero, then each database connection
+** does an initial bulk allocation for page cache memory
+** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
+** of -1024*N bytes if N is negative, . ^If additional
+** page cache memory is needed beyond what is provided by the initial
+** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
+** additional cache line. </dd>
+**
+** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
+** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
+** that SQLite will use for all of its dynamic memory allocation needs
+** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
+** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
+** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
+** [SQLITE_ERROR] if invoked otherwise.
+** ^There are three arguments to SQLITE_CONFIG_HEAP:
+** An 8-byte aligned pointer to the memory,
+** the number of bytes in the memory buffer, and the minimum allocation size.
+** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
+** to using its default memory allocator (the system malloc() implementation),
+** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
+** memory pointer is not NULL then the alternative memory
+** allocator is engaged to handle all of SQLites memory allocation needs.
+** The first pointer (the memory pointer) must be aligned to an 8-byte
+** boundary or subsequent behavior of SQLite will be undefined.
+** The minimum allocation size is capped at 2**12. Reasonable values
+** for the minimum allocation size are 2**5 through 2**8.</dd>
+**
+** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
+** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
+** pointer to an instance of the [sqlite3_mutex_methods] structure.
+** The argument specifies alternative low-level mutex routines to be used
+** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
+** the content of the [sqlite3_mutex_methods] structure before the call to
+** [sqlite3_config()] returns. ^If SQLite is compiled with
+** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
+** the entire mutexing subsystem is omitted from the build and hence calls to
+** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
+** return [SQLITE_ERROR].</dd>
+**
+** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
+** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
+** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
+** [sqlite3_mutex_methods]
+** structure is filled with the currently defined mutex routines.)^
+** This option can be used to overload the default mutex allocation
+** routines with a wrapper used to track mutex usage for performance
+** profiling or testing, for example. ^If SQLite is compiled with
+** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
+** the entire mutexing subsystem is omitted from the build and hence calls to
+** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
+** return [SQLITE_ERROR].</dd>
+**
+** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
+** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
+** the default size of lookaside memory on each [database connection].
+** The first argument is the
+** size of each lookaside buffer slot and the second is the number of
+** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
+** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
+** option to [sqlite3_db_config()] can be used to change the lookaside
+** configuration on individual connections.)^ </dd>
+**
+** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
+** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
+** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
+** the interface to a custom page cache implementation.)^
+** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
+**
+** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
+** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
+** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
+** the current page cache implementation into that object.)^ </dd>
+**
+** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
+** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
+** global [error log].
+** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
+** function with a call signature of void(*)(void*,int,const char*),
+** and a pointer to void. ^If the function pointer is not NULL, it is
+** invoked by [sqlite3_log()] to process each logging event. ^If the
+** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
+** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
+** passed through as the first parameter to the application-defined logger
+** function whenever that function is invoked. ^The second parameter to
+** the logger function is a copy of the first parameter to the corresponding
+** [sqlite3_log()] call and is intended to be a [result code] or an
+** [extended result code]. ^The third parameter passed to the logger is
+** log message after formatting via [sqlite3_snprintf()].
+** The SQLite logging interface is not reentrant; the logger function
+** supplied by the application must not invoke any SQLite interface.
+** In a multi-threaded application, the application-defined logger
+** function must be threadsafe. </dd>
+**
+** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
+** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
+** If non-zero, then URI handling is globally enabled. If the parameter is zero,
+** then URI handling is globally disabled.)^ ^If URI handling is globally
+** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
+** [sqlite3_open16()] or
+** specified as part of [ATTACH] commands are interpreted as URIs, regardless
+** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
+** connection is opened. ^If it is globally disabled, filenames are
+** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
+** database connection is opened. ^(By default, URI handling is globally
+** disabled. The default value may be changed by compiling with the
+** [SQLITE_USE_URI] symbol defined.)^
+**
+** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
+** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
+** argument which is interpreted as a boolean in order to enable or disable
+** the use of covering indices for full table scans in the query optimizer.
+** ^The default setting is determined
+** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
+** if that compile-time option is omitted.
+** The ability to disable the use of covering indices for full table scans
+** is because some incorrectly coded legacy applications might malfunction
+** when the optimization is enabled. Providing the ability to
+** disable the optimization allows the older, buggy application code to work
+** without change even with newer versions of SQLite.
+**
+** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
+** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
+** <dd> These options are obsolete and should not be used by new code.
+** They are retained for backwards compatibility but are now no-ops.
+** </dd>
+**
+** [[SQLITE_CONFIG_SQLLOG]]
+** <dt>SQLITE_CONFIG_SQLLOG
+** <dd>This option is only available if sqlite is compiled with the
+** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
+** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
+** The second should be of type (void*). The callback is invoked by the library
+** in three separate circumstances, identified by the value passed as the
+** fourth parameter. If the fourth parameter is 0, then the database connection
+** passed as the second argument has just been opened. The third argument
+** points to a buffer containing the name of the main database file. If the
+** fourth parameter is 1, then the SQL statement that the third parameter
+** points to has just been executed. Or, if the fourth parameter is 2, then
+** the connection being passed as the second parameter is being closed. The
+** third parameter is passed NULL In this case. An example of using this
+** configuration option can be seen in the "test_sqllog.c" source file in
+** the canonical SQLite source tree.</dd>
+**
+** [[SQLITE_CONFIG_MMAP_SIZE]]
+** <dt>SQLITE_CONFIG_MMAP_SIZE
+** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
+** that are the default mmap size limit (the default setting for
+** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
+** ^The default setting can be overridden by each database connection using
+** either the [PRAGMA mmap_size] command, or by using the
+** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
+** will be silently truncated if necessary so that it does not exceed the
+** compile-time maximum mmap size set by the
+** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
+** ^If either argument to this option is negative, then that argument is
+** changed to its compile-time default.
+**
+** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
+** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
+** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
+** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
+** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
+** that specifies the maximum size of the created heap.
+**
+** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
+** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
+** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
+** is a pointer to an integer and writes into that integer the number of extra
+** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
+** The amount of extra space required can change depending on the compiler,
+** target platform, and SQLite version.
+**
+** [[SQLITE_CONFIG_PMASZ]]
+** <dt>SQLITE_CONFIG_PMASZ
+** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
+** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
+** sorter to that integer. The default minimum PMA Size is set by the
+** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
+** to help with sort operations when multithreaded sorting
+** is enabled (using the [PRAGMA threads] command) and the amount of content
+** to be sorted exceeds the page size times the minimum of the
+** [PRAGMA cache_size] setting and this value.
+**
+** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
+** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
+** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
+** becomes the [statement journal] spill-to-disk threshold.
+** [Statement journals] are held in memory until their size (in bytes)
+** exceeds this threshold, at which point they are written to disk.
+** Or if the threshold is -1, statement journals are always held
+** exclusively in memory.
+** Since many statement journals never become large, setting the spill
+** threshold to a value such as 64KiB can greatly reduce the amount of
+** I/O required to support statement rollback.
+** The default value for this setting is controlled by the
+** [SQLITE_STMTJRNL_SPILL] compile-time option.
+**
+** [[SQLITE_CONFIG_SORTERREF_SIZE]]
+** <dt>SQLITE_CONFIG_SORTERREF_SIZE
+** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter
+** of type (int) - the new value of the sorter-reference size threshold.
+** Usually, when SQLite uses an external sort to order records according
+** to an ORDER BY clause, all fields required by the caller are present in the
+** sorted records. However, if SQLite determines based on the declared type
+** of a table column that its values are likely to be very large - larger
+** than the configured sorter-reference size threshold - then a reference
+** is stored in each sorted record and the required column values loaded
+** from the database as records are returned in sorted order. The default
+** value for this option is to never use this optimization. Specifying a
+** negative value for this option restores the default behaviour.
+** This option is only available if SQLite is compiled with the
+** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
+**
+** [[SQLITE_CONFIG_MEMDB_MAXSIZE]]
+** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE
+** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter
+** [sqlite3_int64] parameter which is the default maximum size for an in-memory
+** database created using [sqlite3_deserialize()]. This default maximum
+** size can be adjusted up or down for individual databases using the
+** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control]. If this
+** configuration setting is never used, then the default maximum is determined
+** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option. If that
+** compile-time option is not set, then the default maximum is 1073741824.
+** </dl>
+*/
+#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
+#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
+#define SQLITE_CONFIG_SERIALIZED 3 /* nil */
+#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
+#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
+#define SQLITE_CONFIG_SCRATCH 6 /* No longer used */
+#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
+#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
+#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
+#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
+#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
+/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
+#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
+#define SQLITE_CONFIG_PCACHE 14 /* no-op */
+#define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
+#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
+#define SQLITE_CONFIG_URI 17 /* int */
+#define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
+#define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
+#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
+#define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
+#define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
+#define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
+#define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
+#define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
+#define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
+#define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */
+#define SQLITE_CONFIG_SORTERREF_SIZE 28 /* int nByte */
+#define SQLITE_CONFIG_MEMDB_MAXSIZE 29 /* sqlite3_int64 */
+
+/*
+** CAPI3REF: Database Connection Configuration Options
+**
+** These constants are the available integer configuration options that
+** can be passed as the second argument to the [sqlite3_db_config()] interface.
+**
+** New configuration options may be added in future releases of SQLite.
+** Existing configuration options might be discontinued. Applications
+** should check the return code from [sqlite3_db_config()] to make sure that
+** the call worked. ^The [sqlite3_db_config()] interface will return a
+** non-zero [error code] if a discontinued or unsupported configuration option
+** is invoked.
+**
+** <dl>
+** [[SQLITE_DBCONFIG_LOOKASIDE]]
+** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
+** <dd> ^This option takes three additional arguments that determine the
+** [lookaside memory allocator] configuration for the [database connection].
+** ^The first argument (the third parameter to [sqlite3_db_config()] is a
+** pointer to a memory buffer to use for lookaside memory.
+** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
+** may be NULL in which case SQLite will allocate the
+** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
+** size of each lookaside buffer slot. ^The third argument is the number of
+** slots. The size of the buffer in the first argument must be greater than
+** or equal to the product of the second and third arguments. The buffer
+** must be aligned to an 8-byte boundary. ^If the second argument to
+** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
+** rounded down to the next smaller multiple of 8. ^(The lookaside memory
+** configuration for a database connection can only be changed when that
+** connection is not currently using lookaside memory, or in other words
+** when the "current value" returned by
+** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
+** Any attempt to change the lookaside memory configuration when lookaside
+** memory is in use leaves the configuration unchanged and returns
+** [SQLITE_BUSY].)^</dd>
+**
+** [[SQLITE_DBCONFIG_ENABLE_FKEY]]
+** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
+** <dd> ^This option is used to enable or disable the enforcement of
+** [foreign key constraints]. There should be two additional arguments.
+** The first argument is an integer which is 0 to disable FK enforcement,
+** positive to enable FK enforcement or negative to leave FK enforcement
+** unchanged. The second parameter is a pointer to an integer into which
+** is written 0 or 1 to indicate whether FK enforcement is off or on
+** following this call. The second parameter may be a NULL pointer, in
+** which case the FK enforcement setting is not reported back. </dd>
+**
+** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]]
+** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
+** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
+** There should be two additional arguments.
+** The first argument is an integer which is 0 to disable triggers,
+** positive to enable triggers or negative to leave the setting unchanged.
+** The second parameter is a pointer to an integer into which
+** is written 0 or 1 to indicate whether triggers are disabled or enabled
+** following this call. The second parameter may be a NULL pointer, in
+** which case the trigger setting is not reported back. </dd>
+**
+** [[SQLITE_DBCONFIG_ENABLE_VIEW]]
+** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt>
+** <dd> ^This option is used to enable or disable [CREATE VIEW | views].
+** There should be two additional arguments.
+** The first argument is an integer which is 0 to disable views,
+** positive to enable views or negative to leave the setting unchanged.
+** The second parameter is a pointer to an integer into which
+** is written 0 or 1 to indicate whether views are disabled or enabled
+** following this call. The second parameter may be a NULL pointer, in
+** which case the view setting is not reported back. </dd>
+**
+** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]
+** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
+** <dd> ^This option is used to enable or disable the
+** [fts3_tokenizer()] function which is part of the
+** [FTS3] full-text search engine extension.
+** There should be two additional arguments.
+** The first argument is an integer which is 0 to disable fts3_tokenizer() or
+** positive to enable fts3_tokenizer() or negative to leave the setting
+** unchanged.
+** The second parameter is a pointer to an integer into which
+** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
+** following this call. The second parameter may be a NULL pointer, in
+** which case the new setting is not reported back. </dd>
+**
+** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]
+** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
+** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
+** interface independently of the [load_extension()] SQL function.
+** The [sqlite3_enable_load_extension()] API enables or disables both the
+** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
+** There should be two additional arguments.
+** When the first argument to this interface is 1, then only the C-API is
+** enabled and the SQL function remains disabled. If the first argument to
+** this interface is 0, then both the C-API and the SQL function are disabled.
+** If the first argument is -1, then no changes are made to state of either the
+** C-API or the SQL function.
+** The second parameter is a pointer to an integer into which
+** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
+** is disabled or enabled following this call. The second parameter may
+** be a NULL pointer, in which case the new setting is not reported back.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
+** <dd> ^This option is used to change the name of the "main" database
+** schema. ^The sole argument is a pointer to a constant UTF8 string
+** which will become the new schema name in place of "main". ^SQLite
+** does not make a copy of the new main schema name string, so the application
+** must ensure that the argument passed into this DBCONFIG option is unchanged
+** until after the database connection closes.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]]
+** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
+** <dd> Usually, when a database in wal mode is closed or detached from a
+** database handle, SQLite checks if this will mean that there are now no
+** connections at all to the database. If so, it performs a checkpoint
+** operation before closing the connection. This option may be used to
+** override this behaviour. The first parameter passed to this operation
+** is an integer - positive to disable checkpoints-on-close, or zero (the
+** default) to enable them, and negative to leave the setting unchanged.
+** The second parameter is a pointer to an integer
+** into which is written 0 or 1 to indicate whether checkpoints-on-close
+** have been disabled - 0 if they are not disabled, 1 if they are.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
+** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
+** the [query planner stability guarantee] (QPSG). When the QPSG is active,
+** a single SQL query statement will always use the same algorithm regardless
+** of values of [bound parameters].)^ The QPSG disables some query optimizations
+** that look at the values of bound parameters, which can make some queries
+** slower. But the QPSG has the advantage of more predictable behavior. With
+** the QPSG active, SQLite will always use the same query plan in the field as
+** was used during testing in the lab.
+** The first argument to this setting is an integer which is 0 to disable
+** the QPSG, positive to enable QPSG, or negative to leave the setting
+** unchanged. The second parameter is a pointer to an integer into which
+** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
+** following this call.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
+** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not
+** include output for any operations performed by trigger programs. This
+** option is used to set or clear (the default) a flag that governs this
+** behavior. The first parameter passed to this operation is an integer -
+** positive to enable output for trigger programs, or zero to disable it,
+** or negative to leave the setting unchanged.
+** The second parameter is a pointer to an integer into which is written
+** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
+** it is not disabled, 1 if it is.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
+** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
+** [VACUUM] in order to reset a database back to an empty database
+** with no schema and no content. The following process works even for
+** a badly corrupted database file:
+** <ol>
+** <li> If the database connection is newly opened, make sure it has read the
+** database schema by preparing then discarding some query against the
+** database, or calling sqlite3_table_column_metadata(), ignoring any
+** errors. This step is only necessary if the application desires to keep
+** the database in WAL mode after the reset if it was in WAL mode before
+** the reset.
+** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
+** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
+** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
+** </ol>
+** Because resetting a database is destructive and irreversible, the
+** process requires the use of this obscure API and multiple steps to help
+** ensure that it does not happen by accident.
+**
+** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>
+** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
+** "defensive" flag for a database connection. When the defensive
+** flag is enabled, language features that allow ordinary SQL to
+** deliberately corrupt the database file are disabled. The disabled
+** features include but are not limited to the following:
+** <ul>
+** <li> The [PRAGMA writable_schema=ON] statement.
+** <li> The [PRAGMA journal_mode=OFF] statement.
+** <li> Writes to the [sqlite_dbpage] virtual table.
+** <li> Direct writes to [shadow tables].
+** </ul>
+** </dd>
+**
+** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] <dt>SQLITE_DBCONFIG_WRITABLE_SCHEMA</dt>
+** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the
+** "writable_schema" flag. This has the same effect and is logically equivalent
+** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF].
+** The first argument to this setting is an integer which is 0 to disable
+** the writable_schema, positive to enable writable_schema, or negative to
+** leave the setting unchanged. The second parameter is a pointer to an
+** integer into which is written 0 or 1 to indicate whether the writable_schema
+** is enabled or disabled following this call.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]]
+** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt>
+** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates
+** the legacy behavior of the [ALTER TABLE RENAME] command such it
+** behaves as it did prior to [version 3.24.0] (2018-06-04). See the
+** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for
+** additional information. This feature can also be turned on and off
+** using the [PRAGMA legacy_alter_table] statement.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_DQS_DML]]
+** <dt>SQLITE_DBCONFIG_DQS_DML</td>
+** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
+** the legacy [double-quoted string literal] misfeature for DML statements
+** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
+** default value of this setting is determined by the [-DSQLITE_DQS]
+** compile-time option.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_DQS_DDL]]
+** <dt>SQLITE_DBCONFIG_DQS_DDL</td>
+** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates
+** the legacy [double-quoted string literal] misfeature for DDL statements,
+** such as CREATE TABLE and CREATE INDEX. The
+** default value of this setting is determined by the [-DSQLITE_DQS]
+** compile-time option.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]
+** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</td>
+** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to
+** assume that database schemas are untainted by malicious content.
+** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite
+** takes additional defensive steps to protect the application from harm
+** including:
+** <ul>
+** <li> Prohibit the use of SQL functions inside triggers, views,
+** CHECK constraints, DEFAULT clauses, expression indexes,
+** partial indexes, or generated columns
+** unless those functions are tagged with [SQLITE_INNOCUOUS].
+** <li> Prohibit the use of virtual tables inside of triggers or views
+** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].
+** </ul>
+** This setting defaults to "on" for legacy compatibility, however
+** all applications are advised to turn it off if possible. This setting
+** can also be controlled using the [PRAGMA trusted_schema] statement.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]
+** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</td>
+** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates
+** the legacy file format flag. When activated, this flag causes all newly
+** created database file to have a schema format version number (the 4-byte
+** integer found at offset 44 into the database header) of 1. This in turn
+** means that the resulting database file will be readable and writable by
+** any SQLite version back to 3.0.0 ([dateof:3.0.0]). Without this setting,
+** newly created databases are generally not understandable by SQLite versions
+** prior to 3.3.0 ([dateof:3.3.0]). As these words are written, there
+** is now scarcely any need to generated database files that are compatible
+** all the way back to version 3.0.0, and so this setting is of little
+** practical use, but is provided so that SQLite can continue to claim the
+** ability to generate new database files that are compatible with version
+** 3.0.0.
+** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,
+** the [VACUUM] command will fail with an obscure error when attempting to
+** process a table with generated columns and a descending index. This is
+** not considered a bug since SQLite versions 3.3.0 and earlier do not support
+** either generated columns or decending indexes.
+** </dd>
+** </dl>
+*/
+#define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
+#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
+#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
+#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
+#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
+#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
+#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */
+#define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */
+#define SQLITE_DBCONFIG_TRIGGER_EQP 1008 /* int int* */
+#define SQLITE_DBCONFIG_RESET_DATABASE 1009 /* int int* */
+#define SQLITE_DBCONFIG_DEFENSIVE 1010 /* int int* */
+#define SQLITE_DBCONFIG_WRITABLE_SCHEMA 1011 /* int int* */
+#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE 1012 /* int int* */
+#define SQLITE_DBCONFIG_DQS_DML 1013 /* int int* */
+#define SQLITE_DBCONFIG_DQS_DDL 1014 /* int int* */
+#define SQLITE_DBCONFIG_ENABLE_VIEW 1015 /* int int* */
+#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT 1016 /* int int* */
+#define SQLITE_DBCONFIG_TRUSTED_SCHEMA 1017 /* int int* */
+#define SQLITE_DBCONFIG_MAX 1017 /* Largest DBCONFIG */
+
+/*
+** CAPI3REF: Enable Or Disable Extended Result Codes
+** METHOD: sqlite3
+**
+** ^The sqlite3_extended_result_codes() routine enables or disables the
+** [extended result codes] feature of SQLite. ^The extended result
+** codes are disabled by default for historical compatibility.
+*/
+SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
+
+/*
+** CAPI3REF: Last Insert Rowid
+** METHOD: sqlite3
+**
+** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
+** has a unique 64-bit signed
+** integer key called the [ROWID | "rowid"]. ^The rowid is always available
+** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
+** names are not also used by explicitly declared columns. ^If
+** the table has a column of type [INTEGER PRIMARY KEY] then that column
+** is another alias for the rowid.
+**
+** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
+** the most recent successful [INSERT] into a rowid table or [virtual table]
+** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
+** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
+** on the database connection D, then sqlite3_last_insert_rowid(D) returns
+** zero.
+**
+** As well as being set automatically as rows are inserted into database
+** tables, the value returned by this function may be set explicitly by
+** [sqlite3_set_last_insert_rowid()]
+**
+** Some virtual table implementations may INSERT rows into rowid tables as
+** part of committing a transaction (e.g. to flush data accumulated in memory
+** to disk). In this case subsequent calls to this function return the rowid
+** associated with these internal INSERT operations, which leads to
+** unintuitive results. Virtual table implementations that do write to rowid
+** tables in this way can avoid this problem by restoring the original
+** rowid value using [sqlite3_set_last_insert_rowid()] before returning
+** control to the user.
+**
+** ^(If an [INSERT] occurs within a trigger then this routine will
+** return the [rowid] of the inserted row as long as the trigger is
+** running. Once the trigger program ends, the value returned
+** by this routine reverts to what it was before the trigger was fired.)^
+**
+** ^An [INSERT] that fails due to a constraint violation is not a
+** successful [INSERT] and does not change the value returned by this
+** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
+** and INSERT OR ABORT make no changes to the return value of this
+** routine when their insertion fails. ^(When INSERT OR REPLACE
+** encounters a constraint violation, it does not fail. The
+** INSERT continues to completion after deleting rows that caused
+** the constraint problem so INSERT OR REPLACE will always change
+** the return value of this interface.)^
+**
+** ^For the purposes of this routine, an [INSERT] is considered to
+** be successful even if it is subsequently rolled back.
+**
+** This function is accessible to SQL statements via the
+** [last_insert_rowid() SQL function].
+**
+** If a separate thread performs a new [INSERT] on the same
+** database connection while the [sqlite3_last_insert_rowid()]
+** function is running and thus changes the last insert [rowid],
+** then the value returned by [sqlite3_last_insert_rowid()] is
+** unpredictable and might not equal either the old or the new
+** last insert [rowid].
+*/
+SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
+
+/*
+** CAPI3REF: Set the Last Insert Rowid value.
+** METHOD: sqlite3
+**
+** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
+** set the value returned by calling sqlite3_last_insert_rowid(D) to R
+** without inserting a row into the database.
+*/
+SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
+
+/*
+** CAPI3REF: Count The Number Of Rows Modified
+** METHOD: sqlite3
+**
+** ^This function returns the number of rows modified, inserted or
+** deleted by the most recently completed INSERT, UPDATE or DELETE
+** statement on the database connection specified by the only parameter.
+** ^Executing any other type of SQL statement does not modify the value
+** returned by this function.
+**
+** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
+** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
+** [foreign key actions] or [REPLACE] constraint resolution are not counted.
+**
+** Changes to a view that are intercepted by
+** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
+** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
+** DELETE statement run on a view is always zero. Only changes made to real
+** tables are counted.
+**
+** Things are more complicated if the sqlite3_changes() function is
+** executed while a trigger program is running. This may happen if the
+** program uses the [changes() SQL function], or if some other callback
+** function invokes sqlite3_changes() directly. Essentially:
+**
+** <ul>
+** <li> ^(Before entering a trigger program the value returned by
+** sqlite3_changes() function is saved. After the trigger program
+** has finished, the original value is restored.)^
+**
+** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
+** statement sets the value returned by sqlite3_changes()
+** upon completion as normal. Of course, this value will not include
+** any changes performed by sub-triggers, as the sqlite3_changes()
+** value will be saved and restored after each sub-trigger has run.)^
+** </ul>
+**
+** ^This means that if the changes() SQL function (or similar) is used
+** by the first INSERT, UPDATE or DELETE statement within a trigger, it
+** returns the value as set when the calling statement began executing.
+** ^If it is used by the second or subsequent such statement within a trigger
+** program, the value returned reflects the number of rows modified by the
+** previous INSERT, UPDATE or DELETE statement within the same trigger.
+**
+** If a separate thread makes changes on the same database connection
+** while [sqlite3_changes()] is running then the value returned
+** is unpredictable and not meaningful.
+**
+** See also:
+** <ul>
+** <li> the [sqlite3_total_changes()] interface
+** <li> the [count_changes pragma]
+** <li> the [changes() SQL function]
+** <li> the [data_version pragma]
+** </ul>
+*/
+SQLITE_API int sqlite3_changes(sqlite3*);
+
+/*
+** CAPI3REF: Total Number Of Rows Modified
+** METHOD: sqlite3
+**
+** ^This function returns the total number of rows inserted, modified or
+** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
+** since the database connection was opened, including those executed as
+** part of trigger programs. ^Executing any other type of SQL statement
+** does not affect the value returned by sqlite3_total_changes().
+**
+** ^Changes made as part of [foreign key actions] are included in the
+** count, but those made as part of REPLACE constraint resolution are
+** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
+** are not counted.
+**
+** The [sqlite3_total_changes(D)] interface only reports the number
+** of rows that changed due to SQL statement run against database
+** connection D. Any changes by other database connections are ignored.
+** To detect changes against a database file from other database
+** connections use the [PRAGMA data_version] command or the
+** [SQLITE_FCNTL_DATA_VERSION] [file control].
+**
+** If a separate thread makes changes on the same database connection
+** while [sqlite3_total_changes()] is running then the value
+** returned is unpredictable and not meaningful.
+**
+** See also:
+** <ul>
+** <li> the [sqlite3_changes()] interface
+** <li> the [count_changes pragma]
+** <li> the [changes() SQL function]
+** <li> the [data_version pragma]
+** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control]
+** </ul>
+*/
+SQLITE_API int sqlite3_total_changes(sqlite3*);
+
+/*
+** CAPI3REF: Interrupt A Long-Running Query
+** METHOD: sqlite3
+**
+** ^This function causes any pending database operation to abort and
+** return at its earliest opportunity. This routine is typically
+** called in response to a user action such as pressing "Cancel"
+** or Ctrl-C where the user wants a long query operation to halt
+** immediately.
+**
+** ^It is safe to call this routine from a thread different from the
+** thread that is currently running the database operation. But it
+** is not safe to call this routine with a [database connection] that
+** is closed or might close before sqlite3_interrupt() returns.
+**
+** ^If an SQL operation is very nearly finished at the time when
+** sqlite3_interrupt() is called, then it might not have an opportunity
+** to be interrupted and might continue to completion.
+**
+** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
+** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
+** that is inside an explicit transaction, then the entire transaction
+** will be rolled back automatically.
+**
+** ^The sqlite3_interrupt(D) call is in effect until all currently running
+** SQL statements on [database connection] D complete. ^Any new SQL statements
+** that are started after the sqlite3_interrupt() call and before the
+** running statement count reaches zero are interrupted as if they had been
+** running prior to the sqlite3_interrupt() call. ^New SQL statements
+** that are started after the running statement count reaches zero are
+** not effected by the sqlite3_interrupt().
+** ^A call to sqlite3_interrupt(D) that occurs when there are no running
+** SQL statements is a no-op and has no effect on SQL statements
+** that are started after the sqlite3_interrupt() call returns.
+*/
+SQLITE_API void sqlite3_interrupt(sqlite3*);
+
+/*
+** CAPI3REF: Determine If An SQL Statement Is Complete
+**
+** These routines are useful during command-line input to determine if the
+** currently entered text seems to form a complete SQL statement or
+** if additional input is needed before sending the text into
+** SQLite for parsing. ^These routines return 1 if the input string
+** appears to be a complete SQL statement. ^A statement is judged to be
+** complete if it ends with a semicolon token and is not a prefix of a
+** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
+** string literals or quoted identifier names or comments are not
+** independent tokens (they are part of the token in which they are
+** embedded) and thus do not count as a statement terminator. ^Whitespace
+** and comments that follow the final semicolon are ignored.
+**
+** ^These routines return 0 if the statement is incomplete. ^If a
+** memory allocation fails, then SQLITE_NOMEM is returned.
+**
+** ^These routines do not parse the SQL statements thus
+** will not detect syntactically incorrect SQL.
+**
+** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
+** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
+** automatically by sqlite3_complete16(). If that initialization fails,
+** then the return value from sqlite3_complete16() will be non-zero
+** regardless of whether or not the input SQL is complete.)^
+**
+** The input to [sqlite3_complete()] must be a zero-terminated
+** UTF-8 string.
+**
+** The input to [sqlite3_complete16()] must be a zero-terminated
+** UTF-16 string in native byte order.
+*/
+SQLITE_API int sqlite3_complete(const char *sql);
+SQLITE_API int sqlite3_complete16(const void *sql);
+
+/*
+** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
+** KEYWORDS: {busy-handler callback} {busy handler}
+** METHOD: sqlite3
+**
+** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
+** that might be invoked with argument P whenever
+** an attempt is made to access a database table associated with
+** [database connection] D when another thread
+** or process has the table locked.
+** The sqlite3_busy_handler() interface is used to implement
+** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
+**
+** ^If the busy callback is NULL, then [SQLITE_BUSY]
+** is returned immediately upon encountering the lock. ^If the busy callback
+** is not NULL, then the callback might be invoked with two arguments.
+**
+** ^The first argument to the busy handler is a copy of the void* pointer which
+** is the third argument to sqlite3_busy_handler(). ^The second argument to
+** the busy handler callback is the number of times that the busy handler has
+** been invoked previously for the same locking event. ^If the
+** busy callback returns 0, then no additional attempts are made to
+** access the database and [SQLITE_BUSY] is returned
+** to the application.
+** ^If the callback returns non-zero, then another attempt
+** is made to access the database and the cycle repeats.
+**
+** The presence of a busy handler does not guarantee that it will be invoked
+** when there is lock contention. ^If SQLite determines that invoking the busy
+** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
+** to the application instead of invoking the
+** busy handler.
+** Consider a scenario where one process is holding a read lock that
+** it is trying to promote to a reserved lock and
+** a second process is holding a reserved lock that it is trying
+** to promote to an exclusive lock. The first process cannot proceed
+** because it is blocked by the second and the second process cannot
+** proceed because it is blocked by the first. If both processes
+** invoke the busy handlers, neither will make any progress. Therefore,
+** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
+** will induce the first process to release its read lock and allow
+** the second process to proceed.
+**
+** ^The default busy callback is NULL.
+**
+** ^(There can only be a single busy handler defined for each
+** [database connection]. Setting a new busy handler clears any
+** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
+** or evaluating [PRAGMA busy_timeout=N] will change the
+** busy handler and thus clear any previously set busy handler.
+**
+** The busy callback should not take any actions which modify the
+** database connection that invoked the busy handler. In other words,
+** the busy handler is not reentrant. Any such actions
+** result in undefined behavior.
+**
+** A busy handler must not close the database connection
+** or [prepared statement] that invoked the busy handler.
+*/
+SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
+
+/*
+** CAPI3REF: Set A Busy Timeout
+** METHOD: sqlite3
+**
+** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
+** for a specified amount of time when a table is locked. ^The handler
+** will sleep multiple times until at least "ms" milliseconds of sleeping
+** have accumulated. ^After at least "ms" milliseconds of sleeping,
+** the handler returns 0 which causes [sqlite3_step()] to return
+** [SQLITE_BUSY].
+**
+** ^Calling this routine with an argument less than or equal to zero
+** turns off all busy handlers.
+**
+** ^(There can only be a single busy handler for a particular
+** [database connection] at any given moment. If another busy handler
+** was defined (using [sqlite3_busy_handler()]) prior to calling
+** this routine, that other busy handler is cleared.)^
+**
+** See also: [PRAGMA busy_timeout]
+*/
+SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
+
+/*
+** CAPI3REF: Convenience Routines For Running Queries
+** METHOD: sqlite3
+**
+** This is a legacy interface that is preserved for backwards compatibility.
+** Use of this interface is not recommended.
+**
+** Definition: A <b>result table</b> is memory data structure created by the
+** [sqlite3_get_table()] interface. A result table records the
+** complete query results from one or more queries.
+**
+** The table conceptually has a number of rows and columns. But
+** these numbers are not part of the result table itself. These
+** numbers are obtained separately. Let N be the number of rows
+** and M be the number of columns.
+**
+** A result table is an array of pointers to zero-terminated UTF-8 strings.
+** There are (N+1)*M elements in the array. The first M pointers point
+** to zero-terminated strings that contain the names of the columns.
+** The remaining entries all point to query results. NULL values result
+** in NULL pointers. All other values are in their UTF-8 zero-terminated
+** string representation as returned by [sqlite3_column_text()].
+**
+** A result table might consist of one or more memory allocations.
+** It is not safe to pass a result table directly to [sqlite3_free()].
+** A result table should be deallocated using [sqlite3_free_table()].
+**
+** ^(As an example of the result table format, suppose a query result
+** is as follows:
+**
+** <blockquote><pre>
+** Name | Age
+** -----------------------
+** Alice | 43
+** Bob | 28
+** Cindy | 21
+** </pre></blockquote>
+**
+** There are two columns (M==2) and three rows (N==3). Thus the
+** result table has 8 entries. Suppose the result table is stored
+** in an array named azResult. Then azResult holds this content:
+**
+** <blockquote><pre>
+** azResult&#91;0] = "Name";
+** azResult&#91;1] = "Age";
+** azResult&#91;2] = "Alice";
+** azResult&#91;3] = "43";
+** azResult&#91;4] = "Bob";
+** azResult&#91;5] = "28";
+** azResult&#91;6] = "Cindy";
+** azResult&#91;7] = "21";
+** </pre></blockquote>)^
+**
+** ^The sqlite3_get_table() function evaluates one or more
+** semicolon-separated SQL statements in the zero-terminated UTF-8
+** string of its 2nd parameter and returns a result table to the
+** pointer given in its 3rd parameter.
+**
+** After the application has finished with the result from sqlite3_get_table(),
+** it must pass the result table pointer to sqlite3_free_table() in order to
+** release the memory that was malloced. Because of the way the
+** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
+** function must not try to call [sqlite3_free()] directly. Only
+** [sqlite3_free_table()] is able to release the memory properly and safely.
+**
+** The sqlite3_get_table() interface is implemented as a wrapper around
+** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
+** to any internal data structures of SQLite. It uses only the public
+** interface defined here. As a consequence, errors that occur in the
+** wrapper layer outside of the internal [sqlite3_exec()] call are not
+** reflected in subsequent calls to [sqlite3_errcode()] or
+** [sqlite3_errmsg()].
+*/
+SQLITE_API int sqlite3_get_table(
+ sqlite3 *db, /* An open database */
+ const char *zSql, /* SQL to be evaluated */
+ char ***pazResult, /* Results of the query */
+ int *pnRow, /* Number of result rows written here */
+ int *pnColumn, /* Number of result columns written here */
+ char **pzErrmsg /* Error msg written here */
+);
+SQLITE_API void sqlite3_free_table(char **result);
+
+/*
+** CAPI3REF: Formatted String Printing Functions
+**
+** These routines are work-alikes of the "printf()" family of functions
+** from the standard C library.
+** These routines understand most of the common formatting options from
+** the standard library printf()
+** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
+** See the [built-in printf()] documentation for details.
+**
+** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
+** results into memory obtained from [sqlite3_malloc64()].
+** The strings returned by these two routines should be
+** released by [sqlite3_free()]. ^Both routines return a
+** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough
+** memory to hold the resulting string.
+**
+** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
+** the standard C library. The result is written into the
+** buffer supplied as the second parameter whose size is given by
+** the first parameter. Note that the order of the
+** first two parameters is reversed from snprintf().)^ This is an
+** historical accident that cannot be fixed without breaking
+** backwards compatibility. ^(Note also that sqlite3_snprintf()
+** returns a pointer to its buffer instead of the number of
+** characters actually written into the buffer.)^ We admit that
+** the number of characters written would be a more useful return
+** value but we cannot change the implementation of sqlite3_snprintf()
+** now without breaking compatibility.
+**
+** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
+** guarantees that the buffer is always zero-terminated. ^The first
+** parameter "n" is the total size of the buffer, including space for
+** the zero terminator. So the longest string that can be completely
+** written will be n-1 characters.
+**
+** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
+**
+** See also: [built-in printf()], [printf() SQL function]
+*/
+SQLITE_API char *sqlite3_mprintf(const char*,...);
+SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
+SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
+SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
+
+/*
+** CAPI3REF: Memory Allocation Subsystem
+**
+** The SQLite core uses these three routines for all of its own
+** internal memory allocation needs. "Core" in the previous sentence
+** does not include operating-system specific [VFS] implementation. The
+** Windows VFS uses native malloc() and free() for some operations.
+**
+** ^The sqlite3_malloc() routine returns a pointer to a block
+** of memory at least N bytes in length, where N is the parameter.
+** ^If sqlite3_malloc() is unable to obtain sufficient free
+** memory, it returns a NULL pointer. ^If the parameter N to
+** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
+** a NULL pointer.
+**
+** ^The sqlite3_malloc64(N) routine works just like
+** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
+** of a signed 32-bit integer.
+**
+** ^Calling sqlite3_free() with a pointer previously returned
+** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
+** that it might be reused. ^The sqlite3_free() routine is
+** a no-op if is called with a NULL pointer. Passing a NULL pointer
+** to sqlite3_free() is harmless. After being freed, memory
+** should neither be read nor written. Even reading previously freed
+** memory might result in a segmentation fault or other severe error.
+** Memory corruption, a segmentation fault, or other severe error
+** might result if sqlite3_free() is called with a non-NULL pointer that
+** was not obtained from sqlite3_malloc() or sqlite3_realloc().
+**
+** ^The sqlite3_realloc(X,N) interface attempts to resize a
+** prior memory allocation X to be at least N bytes.
+** ^If the X parameter to sqlite3_realloc(X,N)
+** is a NULL pointer then its behavior is identical to calling
+** sqlite3_malloc(N).
+** ^If the N parameter to sqlite3_realloc(X,N) is zero or
+** negative then the behavior is exactly the same as calling
+** sqlite3_free(X).
+** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
+** of at least N bytes in size or NULL if insufficient memory is available.
+** ^If M is the size of the prior allocation, then min(N,M) bytes
+** of the prior allocation are copied into the beginning of buffer returned
+** by sqlite3_realloc(X,N) and the prior allocation is freed.
+** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
+** prior allocation is not freed.
+**
+** ^The sqlite3_realloc64(X,N) interfaces works the same as
+** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
+** of a 32-bit signed integer.
+**
+** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
+** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
+** sqlite3_msize(X) returns the size of that memory allocation in bytes.
+** ^The value returned by sqlite3_msize(X) might be larger than the number
+** of bytes requested when X was allocated. ^If X is a NULL pointer then
+** sqlite3_msize(X) returns zero. If X points to something that is not
+** the beginning of memory allocation, or if it points to a formerly
+** valid memory allocation that has now been freed, then the behavior
+** of sqlite3_msize(X) is undefined and possibly harmful.
+**
+** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
+** sqlite3_malloc64(), and sqlite3_realloc64()
+** is always aligned to at least an 8 byte boundary, or to a
+** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
+** option is used.
+**
+** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
+** must be either NULL or else pointers obtained from a prior
+** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
+** not yet been released.
+**
+** The application must not read or write any part of
+** a block of memory after it has been released using
+** [sqlite3_free()] or [sqlite3_realloc()].
+*/
+SQLITE_API void *sqlite3_malloc(int);
+SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
+SQLITE_API void *sqlite3_realloc(void*, int);
+SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
+SQLITE_API void sqlite3_free(void*);
+SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
+
+/*
+** CAPI3REF: Memory Allocator Statistics
+**
+** SQLite provides these two interfaces for reporting on the status
+** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
+** routines, which form the built-in memory allocation subsystem.
+**
+** ^The [sqlite3_memory_used()] routine returns the number of bytes
+** of memory currently outstanding (malloced but not freed).
+** ^The [sqlite3_memory_highwater()] routine returns the maximum
+** value of [sqlite3_memory_used()] since the high-water mark
+** was last reset. ^The values returned by [sqlite3_memory_used()] and
+** [sqlite3_memory_highwater()] include any overhead
+** added by SQLite in its implementation of [sqlite3_malloc()],
+** but not overhead added by the any underlying system library
+** routines that [sqlite3_malloc()] may call.
+**
+** ^The memory high-water mark is reset to the current value of
+** [sqlite3_memory_used()] if and only if the parameter to
+** [sqlite3_memory_highwater()] is true. ^The value returned
+** by [sqlite3_memory_highwater(1)] is the high-water mark
+** prior to the reset.
+*/
+SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
+SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
+
+/*
+** CAPI3REF: Pseudo-Random Number Generator
+**
+** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
+** select random [ROWID | ROWIDs] when inserting new records into a table that
+** already uses the largest possible [ROWID]. The PRNG is also used for
+** the built-in random() and randomblob() SQL functions. This interface allows
+** applications to access the same PRNG for other purposes.
+**
+** ^A call to this routine stores N bytes of randomness into buffer P.
+** ^The P parameter can be a NULL pointer.
+**
+** ^If this routine has not been previously called or if the previous
+** call had N less than one or a NULL pointer for P, then the PRNG is
+** seeded using randomness obtained from the xRandomness method of
+** the default [sqlite3_vfs] object.
+** ^If the previous call to this routine had an N of 1 or more and a
+** non-NULL P then the pseudo-randomness is generated
+** internally and without recourse to the [sqlite3_vfs] xRandomness
+** method.
+*/
+SQLITE_API void sqlite3_randomness(int N, void *P);
+
+/*
+** CAPI3REF: Compile-Time Authorization Callbacks
+** METHOD: sqlite3
+** KEYWORDS: {authorizer callback}
+**
+** ^This routine registers an authorizer callback with a particular
+** [database connection], supplied in the first argument.
+** ^The authorizer callback is invoked as SQL statements are being compiled
+** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
+** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
+** and [sqlite3_prepare16_v3()]. ^At various
+** points during the compilation process, as logic is being created
+** to perform various actions, the authorizer callback is invoked to
+** see if those actions are allowed. ^The authorizer callback should
+** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
+** specific action but allow the SQL statement to continue to be
+** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
+** rejected with an error. ^If the authorizer callback returns
+** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
+** then the [sqlite3_prepare_v2()] or equivalent call that triggered
+** the authorizer will fail with an error message.
+**
+** When the callback returns [SQLITE_OK], that means the operation
+** requested is ok. ^When the callback returns [SQLITE_DENY], the
+** [sqlite3_prepare_v2()] or equivalent call that triggered the
+** authorizer will fail with an error message explaining that
+** access is denied.
+**
+** ^The first parameter to the authorizer callback is a copy of the third
+** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
+** to the callback is an integer [SQLITE_COPY | action code] that specifies
+** the particular action to be authorized. ^The third through sixth parameters
+** to the callback are either NULL pointers or zero-terminated strings
+** that contain additional details about the action to be authorized.
+** Applications must always be prepared to encounter a NULL pointer in any
+** of the third through the sixth parameters of the authorization callback.
+**
+** ^If the action code is [SQLITE_READ]
+** and the callback returns [SQLITE_IGNORE] then the
+** [prepared statement] statement is constructed to substitute
+** a NULL value in place of the table column that would have
+** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
+** return can be used to deny an untrusted user access to individual
+** columns of a table.
+** ^When a table is referenced by a [SELECT] but no column values are
+** extracted from that table (for example in a query like
+** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
+** is invoked once for that table with a column name that is an empty string.
+** ^If the action code is [SQLITE_DELETE] and the callback returns
+** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
+** [truncate optimization] is disabled and all rows are deleted individually.
+**
+** An authorizer is used when [sqlite3_prepare | preparing]
+** SQL statements from an untrusted source, to ensure that the SQL statements
+** do not try to access data they are not allowed to see, or that they do not
+** try to execute malicious statements that damage the database. For
+** example, an application may allow a user to enter arbitrary
+** SQL queries for evaluation by a database. But the application does
+** not want the user to be able to make arbitrary changes to the
+** database. An authorizer could then be put in place while the
+** user-entered SQL is being [sqlite3_prepare | prepared] that
+** disallows everything except [SELECT] statements.
+**
+** Applications that need to process SQL from untrusted sources
+** might also consider lowering resource limits using [sqlite3_limit()]
+** and limiting database size using the [max_page_count] [PRAGMA]
+** in addition to using an authorizer.
+**
+** ^(Only a single authorizer can be in place on a database connection
+** at a time. Each call to sqlite3_set_authorizer overrides the
+** previous call.)^ ^Disable the authorizer by installing a NULL callback.
+** The authorizer is disabled by default.
+**
+** The authorizer callback must not do anything that will modify
+** the database connection that invoked the authorizer callback.
+** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
+** database connections for the meaning of "modify" in this paragraph.
+**
+** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
+** statement might be re-prepared during [sqlite3_step()] due to a
+** schema change. Hence, the application should ensure that the
+** correct authorizer callback remains in place during the [sqlite3_step()].
+**
+** ^Note that the authorizer callback is invoked only during
+** [sqlite3_prepare()] or its variants. Authorization is not
+** performed during statement evaluation in [sqlite3_step()], unless
+** as stated in the previous paragraph, sqlite3_step() invokes
+** sqlite3_prepare_v2() to reprepare a statement after a schema change.
+*/
+SQLITE_API int sqlite3_set_authorizer(
+ sqlite3*,
+ int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
+ void *pUserData
+);
+
+/*
+** CAPI3REF: Authorizer Return Codes
+**
+** The [sqlite3_set_authorizer | authorizer callback function] must
+** return either [SQLITE_OK] or one of these two constants in order
+** to signal SQLite whether or not the action is permitted. See the
+** [sqlite3_set_authorizer | authorizer documentation] for additional
+** information.
+**
+** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
+** returned from the [sqlite3_vtab_on_conflict()] interface.
+*/
+#define SQLITE_DENY 1 /* Abort the SQL statement with an error */
+#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
+
+/*
+** CAPI3REF: Authorizer Action Codes
+**
+** The [sqlite3_set_authorizer()] interface registers a callback function
+** that is invoked to authorize certain SQL statement actions. The
+** second parameter to the callback is an integer code that specifies
+** what action is being authorized. These are the integer action codes that
+** the authorizer callback may be passed.
+**
+** These action code values signify what kind of operation is to be
+** authorized. The 3rd and 4th parameters to the authorization
+** callback function will be parameters or NULL depending on which of these
+** codes is used as the second parameter. ^(The 5th parameter to the
+** authorizer callback is the name of the database ("main", "temp",
+** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
+** is the name of the inner-most trigger or view that is responsible for
+** the access attempt or NULL if this access attempt is directly from
+** top-level SQL code.
+*/
+/******************************************* 3rd ************ 4th ***********/
+#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
+#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
+#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
+#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
+#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
+#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
+#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
+#define SQLITE_CREATE_VIEW 8 /* View Name NULL */
+#define SQLITE_DELETE 9 /* Table Name NULL */
+#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
+#define SQLITE_DROP_TABLE 11 /* Table Name NULL */
+#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
+#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
+#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
+#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
+#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
+#define SQLITE_DROP_VIEW 17 /* View Name NULL */
+#define SQLITE_INSERT 18 /* Table Name NULL */
+#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
+#define SQLITE_READ 20 /* Table Name Column Name */
+#define SQLITE_SELECT 21 /* NULL NULL */
+#define SQLITE_TRANSACTION 22 /* Operation NULL */
+#define SQLITE_UPDATE 23 /* Table Name Column Name */
+#define SQLITE_ATTACH 24 /* Filename NULL */
+#define SQLITE_DETACH 25 /* Database Name NULL */
+#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
+#define SQLITE_REINDEX 27 /* Index Name NULL */
+#define SQLITE_ANALYZE 28 /* Table Name NULL */
+#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
+#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
+#define SQLITE_FUNCTION 31 /* NULL Function Name */
+#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
+#define SQLITE_COPY 0 /* No longer used */
+#define SQLITE_RECURSIVE 33 /* NULL NULL */
+
+/*
+** CAPI3REF: Tracing And Profiling Functions
+** METHOD: sqlite3
+**
+** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
+** instead of the routines described here.
+**
+** These routines register callback functions that can be used for
+** tracing and profiling the execution of SQL statements.
+**
+** ^The callback function registered by sqlite3_trace() is invoked at
+** various times when an SQL statement is being run by [sqlite3_step()].
+** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
+** SQL statement text as the statement first begins executing.
+** ^(Additional sqlite3_trace() callbacks might occur
+** as each triggered subprogram is entered. The callbacks for triggers
+** contain a UTF-8 SQL comment that identifies the trigger.)^
+**
+** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
+** the length of [bound parameter] expansion in the output of sqlite3_trace().
+**
+** ^The callback function registered by sqlite3_profile() is invoked
+** as each SQL statement finishes. ^The profile callback contains
+** the original statement text and an estimate of wall-clock time
+** of how long that statement took to run. ^The profile callback
+** time is in units of nanoseconds, however the current implementation
+** is only capable of millisecond resolution so the six least significant
+** digits in the time are meaningless. Future versions of SQLite
+** might provide greater resolution on the profiler callback. Invoking
+** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the
+** profile callback.
+*/
+SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
+ void(*xTrace)(void*,const char*), void*);
+SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
+ void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
+
+/*
+** CAPI3REF: SQL Trace Event Codes
+** KEYWORDS: SQLITE_TRACE
+**
+** These constants identify classes of events that can be monitored
+** using the [sqlite3_trace_v2()] tracing logic. The M argument
+** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
+** the following constants. ^The first argument to the trace callback
+** is one of the following constants.
+**
+** New tracing constants may be added in future releases.
+**
+** ^A trace callback has four arguments: xCallback(T,C,P,X).
+** ^The T argument is one of the integer type codes above.
+** ^The C argument is a copy of the context pointer passed in as the
+** fourth argument to [sqlite3_trace_v2()].
+** The P and X arguments are pointers whose meanings depend on T.
+**
+** <dl>
+** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
+** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
+** first begins running and possibly at other times during the
+** execution of the prepared statement, such as at the start of each
+** trigger subprogram. ^The P argument is a pointer to the
+** [prepared statement]. ^The X argument is a pointer to a string which
+** is the unexpanded SQL text of the prepared statement or an SQL comment
+** that indicates the invocation of a trigger. ^The callback can compute
+** the same text that would have been returned by the legacy [sqlite3_trace()]
+** interface by using the X argument when X begins with "--" and invoking
+** [sqlite3_expanded_sql(P)] otherwise.
+**
+** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
+** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
+** information as is provided by the [sqlite3_profile()] callback.
+** ^The P argument is a pointer to the [prepared statement] and the
+** X argument points to a 64-bit integer which is the estimated of
+** the number of nanosecond that the prepared statement took to run.
+** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
+**
+** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
+** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
+** statement generates a single row of result.
+** ^The P argument is a pointer to the [prepared statement] and the
+** X argument is unused.
+**
+** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
+** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
+** connection closes.
+** ^The P argument is a pointer to the [database connection] object
+** and the X argument is unused.
+** </dl>
+*/
+#define SQLITE_TRACE_STMT 0x01
+#define SQLITE_TRACE_PROFILE 0x02
+#define SQLITE_TRACE_ROW 0x04
+#define SQLITE_TRACE_CLOSE 0x08
+
+/*
+** CAPI3REF: SQL Trace Hook
+** METHOD: sqlite3
+**
+** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
+** function X against [database connection] D, using property mask M
+** and context pointer P. ^If the X callback is
+** NULL or if the M mask is zero, then tracing is disabled. The
+** M argument should be the bitwise OR-ed combination of
+** zero or more [SQLITE_TRACE] constants.
+**
+** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
+** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
+**
+** ^The X callback is invoked whenever any of the events identified by
+** mask M occur. ^The integer return value from the callback is currently
+** ignored, though this may change in future releases. Callback
+** implementations should return zero to ensure future compatibility.
+**
+** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
+** ^The T argument is one of the [SQLITE_TRACE]
+** constants to indicate why the callback was invoked.
+** ^The C argument is a copy of the context pointer.
+** The P and X arguments are pointers whose meanings depend on T.
+**
+** The sqlite3_trace_v2() interface is intended to replace the legacy
+** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
+** are deprecated.
+*/
+SQLITE_API int sqlite3_trace_v2(
+ sqlite3*,
+ unsigned uMask,
+ int(*xCallback)(unsigned,void*,void*,void*),
+ void *pCtx
+);
+
+/*
+** CAPI3REF: Query Progress Callbacks
+** METHOD: sqlite3
+**
+** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
+** function X to be invoked periodically during long running calls to
+** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
+** database connection D. An example use for this
+** interface is to keep a GUI updated during a large query.
+**
+** ^The parameter P is passed through as the only parameter to the
+** callback function X. ^The parameter N is the approximate number of
+** [virtual machine instructions] that are evaluated between successive
+** invocations of the callback X. ^If N is less than one then the progress
+** handler is disabled.
+**
+** ^Only a single progress handler may be defined at one time per
+** [database connection]; setting a new progress handler cancels the
+** old one. ^Setting parameter X to NULL disables the progress handler.
+** ^The progress handler is also disabled by setting N to a value less
+** than 1.
+**
+** ^If the progress callback returns non-zero, the operation is
+** interrupted. This feature can be used to implement a
+** "Cancel" button on a GUI progress dialog box.
+**
+** The progress handler callback must not do anything that will modify
+** the database connection that invoked the progress handler.
+** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
+** database connections for the meaning of "modify" in this paragraph.
+**
+*/
+SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
+
+/*
+** CAPI3REF: Opening A New Database Connection
+** CONSTRUCTOR: sqlite3
+**
+** ^These routines open an SQLite database file as specified by the
+** filename argument. ^The filename argument is interpreted as UTF-8 for
+** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
+** order for sqlite3_open16(). ^(A [database connection] handle is usually
+** returned in *ppDb, even if an error occurs. The only exception is that
+** if SQLite is unable to allocate memory to hold the [sqlite3] object,
+** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
+** object.)^ ^(If the database is opened (and/or created) successfully, then
+** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
+** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
+** an English language description of the error following a failure of any
+** of the sqlite3_open() routines.
+**
+** ^The default encoding will be UTF-8 for databases created using
+** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
+** created using sqlite3_open16() will be UTF-16 in the native byte order.
+**
+** Whether or not an error occurs when it is opened, resources
+** associated with the [database connection] handle should be released by
+** passing it to [sqlite3_close()] when it is no longer required.
+**
+** The sqlite3_open_v2() interface works like sqlite3_open()
+** except that it accepts two additional parameters for additional control
+** over the new database connection. ^(The flags parameter to
+** sqlite3_open_v2() must include, at a minimum, one of the following
+** three flag combinations:)^
+**
+** <dl>
+** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
+** <dd>The database is opened in read-only mode. If the database does not
+** already exist, an error is returned.</dd>)^
+**
+** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
+** <dd>The database is opened for reading and writing if possible, or reading
+** only if the file is write protected by the operating system. In either
+** case the database must already exist, otherwise an error is returned.</dd>)^
+**
+** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
+** <dd>The database is opened for reading and writing, and is created if
+** it does not already exist. This is the behavior that is always used for
+** sqlite3_open() and sqlite3_open16().</dd>)^
+** </dl>
+**
+** In addition to the required flags, the following optional flags are
+** also supported:
+**
+** <dl>
+** ^(<dt>[SQLITE_OPEN_URI]</dt>
+** <dd>The filename can be interpreted as a URI if this flag is set.</dd>)^
+**
+** ^(<dt>[SQLITE_OPEN_MEMORY]</dt>
+** <dd>The database will be opened as an in-memory database. The database
+** is named by the "filename" argument for the purposes of cache-sharing,
+** if shared cache mode is enabled, but the "filename" is otherwise ignored.
+** </dd>)^
+**
+** ^(<dt>[SQLITE_OPEN_NOMUTEX]</dt>
+** <dd>The new database connection will use the "multi-thread"
+** [threading mode].)^ This means that separate threads are allowed
+** to use SQLite at the same time, as long as each thread is using
+** a different [database connection].
+**
+** ^(<dt>[SQLITE_OPEN_FULLMUTEX]</dt>
+** <dd>The new database connection will use the "serialized"
+** [threading mode].)^ This means the multiple threads can safely
+** attempt to use the same database connection at the same time.
+** (Mutexes will block any actual concurrency, but in this mode
+** there is no harm in trying.)
+**
+** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt>
+** <dd>The database is opened [shared cache] enabled, overriding
+** the default shared cache setting provided by
+** [sqlite3_enable_shared_cache()].)^
+**
+** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>
+** <dd>The database is opened [shared cache] disabled, overriding
+** the default shared cache setting provided by
+** [sqlite3_enable_shared_cache()].)^
+**
+** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
+** <dd>The database filename is not allowed to be a symbolic link</dd>
+** </dl>)^
+**
+** If the 3rd parameter to sqlite3_open_v2() is not one of the
+** required combinations shown above optionally combined with other
+** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
+** then the behavior is undefined.
+**
+** ^The fourth parameter to sqlite3_open_v2() is the name of the
+** [sqlite3_vfs] object that defines the operating system interface that
+** the new database connection should use. ^If the fourth parameter is
+** a NULL pointer then the default [sqlite3_vfs] object is used.
+**
+** ^If the filename is ":memory:", then a private, temporary in-memory database
+** is created for the connection. ^This in-memory database will vanish when
+** the database connection is closed. Future versions of SQLite might
+** make use of additional special filenames that begin with the ":" character.
+** It is recommended that when a database filename actually does begin with
+** a ":" character you should prefix the filename with a pathname such as
+** "./" to avoid ambiguity.
+**
+** ^If the filename is an empty string, then a private, temporary
+** on-disk database will be created. ^This private database will be
+** automatically deleted as soon as the database connection is closed.
+**
+** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
+**
+** ^If [URI filename] interpretation is enabled, and the filename argument
+** begins with "file:", then the filename is interpreted as a URI. ^URI
+** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
+** set in the third argument to sqlite3_open_v2(), or if it has
+** been enabled globally using the [SQLITE_CONFIG_URI] option with the
+** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
+** URI filename interpretation is turned off
+** by default, but future releases of SQLite might enable URI filename
+** interpretation by default. See "[URI filenames]" for additional
+** information.
+**
+** URI filenames are parsed according to RFC 3986. ^If the URI contains an
+** authority, then it must be either an empty string or the string
+** "localhost". ^If the authority is not an empty string or "localhost", an
+** error is returned to the caller. ^The fragment component of a URI, if
+** present, is ignored.
+**
+** ^SQLite uses the path component of the URI as the name of the disk file
+** which contains the database. ^If the path begins with a '/' character,
+** then it is interpreted as an absolute path. ^If the path does not begin
+** with a '/' (meaning that the authority section is omitted from the URI)
+** then the path is interpreted as a relative path.
+** ^(On windows, the first component of an absolute path
+** is a drive specification (e.g. "C:").)^
+**
+** [[core URI query parameters]]
+** The query component of a URI may contain parameters that are interpreted
+** either by SQLite itself, or by a [VFS | custom VFS implementation].
+** SQLite and its built-in [VFSes] interpret the
+** following query parameters:
+**
+** <ul>
+** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
+** a VFS object that provides the operating system interface that should
+** be used to access the database file on disk. ^If this option is set to
+** an empty string the default VFS object is used. ^Specifying an unknown
+** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
+** present, then the VFS specified by the option takes precedence over
+** the value passed as the fourth parameter to sqlite3_open_v2().
+**
+** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
+** "rwc", or "memory". Attempting to set it to any other value is
+** an error)^.
+** ^If "ro" is specified, then the database is opened for read-only
+** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
+** third argument to sqlite3_open_v2(). ^If the mode option is set to
+** "rw", then the database is opened for read-write (but not create)
+** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
+** been set. ^Value "rwc" is equivalent to setting both
+** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
+** set to "memory" then a pure [in-memory database] that never reads
+** or writes from disk is used. ^It is an error to specify a value for
+** the mode parameter that is less restrictive than that specified by
+** the flags passed in the third parameter to sqlite3_open_v2().
+**
+** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
+** "private". ^Setting it to "shared" is equivalent to setting the
+** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
+** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
+** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
+** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
+** a URI filename, its value overrides any behavior requested by setting
+** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
+**
+** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
+** [powersafe overwrite] property does or does not apply to the
+** storage media on which the database file resides.
+**
+** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
+** which if set disables file locking in rollback journal modes. This
+** is useful for accessing a database on a filesystem that does not
+** support locking. Caution: Database corruption might result if two
+** or more processes write to the same database and any one of those
+** processes uses nolock=1.
+**
+** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
+** parameter that indicates that the database file is stored on
+** read-only media. ^When immutable is set, SQLite assumes that the
+** database file cannot be changed, even by a process with higher
+** privilege, and so the database is opened read-only and all locking
+** and change detection is disabled. Caution: Setting the immutable
+** property on a database file that does in fact change can result
+** in incorrect query results and/or [SQLITE_CORRUPT] errors.
+** See also: [SQLITE_IOCAP_IMMUTABLE].
+**
+** </ul>
+**
+** ^Specifying an unknown parameter in the query component of a URI is not an
+** error. Future versions of SQLite might understand additional query
+** parameters. See "[query parameters with special meaning to SQLite]" for
+** additional information.
+**
+** [[URI filename examples]] <h3>URI filename examples</h3>
+**
+** <table border="1" align=center cellpadding=5>
+** <tr><th> URI filenames <th> Results
+** <tr><td> file:data.db <td>
+** Open the file "data.db" in the current directory.
+** <tr><td> file:/home/fred/data.db<br>
+** file:///home/fred/data.db <br>
+** file://localhost/home/fred/data.db <br> <td>
+** Open the database file "/home/fred/data.db".
+** <tr><td> file://darkstar/home/fred/data.db <td>
+** An error. "darkstar" is not a recognized authority.
+** <tr><td style="white-space:nowrap">
+** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
+** <td> Windows only: Open the file "data.db" on fred's desktop on drive
+** C:. Note that the %20 escaping in this example is not strictly
+** necessary - space characters can be used literally
+** in URI filenames.
+** <tr><td> file:data.db?mode=ro&cache=private <td>
+** Open file "data.db" in the current directory for read-only access.
+** Regardless of whether or not shared-cache mode is enabled by
+** default, use a private cache.
+** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
+** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
+** that uses dot-files in place of posix advisory locking.
+** <tr><td> file:data.db?mode=readonly <td>
+** An error. "readonly" is not a valid option for the "mode" parameter.
+** </table>
+**
+** ^URI hexadecimal escape sequences (%HH) are supported within the path and
+** query components of a URI. A hexadecimal escape sequence consists of a
+** percent sign - "%" - followed by exactly two hexadecimal digits
+** specifying an octet value. ^Before the path or query components of a
+** URI filename are interpreted, they are encoded using UTF-8 and all
+** hexadecimal escape sequences replaced by a single byte containing the
+** corresponding octet. If this process generates an invalid UTF-8 encoding,
+** the results are undefined.
+**
+** <b>Note to Windows users:</b> The encoding used for the filename argument
+** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
+** codepage is currently defined. Filenames containing international
+** characters must be converted to UTF-8 prior to passing them into
+** sqlite3_open() or sqlite3_open_v2().
+**
+** <b>Note to Windows Runtime users:</b> The temporary directory must be set
+** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
+** features that require the use of temporary files may fail.
+**
+** See also: [sqlite3_temp_directory]
+*/
+SQLITE_API int sqlite3_open(
+ const char *filename, /* Database filename (UTF-8) */
+ sqlite3 **ppDb /* OUT: SQLite db handle */
+);
+SQLITE_API int sqlite3_open16(
+ const void *filename, /* Database filename (UTF-16) */
+ sqlite3 **ppDb /* OUT: SQLite db handle */
+);
+SQLITE_API int sqlite3_open_v2(
+ const char *filename, /* Database filename (UTF-8) */
+ sqlite3 **ppDb, /* OUT: SQLite db handle */
+ int flags, /* Flags */
+ const char *zVfs /* Name of VFS module to use */
+);
+
+/*
+** CAPI3REF: Obtain Values For URI Parameters
+**
+** These are utility routines, useful to [VFS|custom VFS implementations],
+** that check if a database file was a URI that contained a specific query
+** parameter, and if so obtains the value of that query parameter.
+**
+** The first parameter to these interfaces (hereafter referred to
+** as F) must be one of:
+** <ul>
+** <li> A database filename pointer created by the SQLite core and
+** passed into the xOpen() method of a VFS implemention, or
+** <li> A filename obtained from [sqlite3_db_filename()], or
+** <li> A new filename constructed using [sqlite3_create_filename()].
+** </ul>
+** If the F parameter is not one of the above, then the behavior is
+** undefined and probably undesirable. Older versions of SQLite were
+** more tolerant of invalid F parameters than newer versions.
+**
+** If F is a suitable filename (as described in the previous paragraph)
+** and if P is the name of the query parameter, then
+** sqlite3_uri_parameter(F,P) returns the value of the P
+** parameter if it exists or a NULL pointer if P does not appear as a
+** query parameter on F. If P is a query parameter of F and it
+** has no explicit value, then sqlite3_uri_parameter(F,P) returns
+** a pointer to an empty string.
+**
+** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
+** parameter and returns true (1) or false (0) according to the value
+** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
+** value of query parameter P is one of "yes", "true", or "on" in any
+** case or if the value begins with a non-zero number. The
+** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
+** query parameter P is one of "no", "false", or "off" in any case or
+** if the value begins with a numeric zero. If P is not a query
+** parameter on F or if the value of P does not match any of the
+** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
+**
+** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
+** 64-bit signed integer and returns that integer, or D if P does not
+** exist. If the value of P is something other than an integer, then
+** zero is returned.
+**
+** The sqlite3_uri_key(F,N) returns a pointer to the name (not
+** the value) of the N-th query parameter for filename F, or a NULL
+** pointer if N is less than zero or greater than the number of query
+** parameters minus 1. The N value is zero-based so N should be 0 to obtain
+** the name of the first query parameter, 1 for the second parameter, and
+** so forth.
+**
+** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
+** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
+** is not a database file pathname pointer that the SQLite core passed
+** into the xOpen VFS method, then the behavior of this routine is undefined
+** and probably undesirable.
+**
+** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F
+** parameter can also be the name of a rollback journal file or WAL file
+** in addition to the main database file. Prior to version 3.31.0, these
+** routines would only work if F was the name of the main database file.
+** When the F parameter is the name of the rollback journal or WAL file,
+** it has access to all the same query parameters as were found on the
+** main database file.
+**
+** See the [URI filename] documentation for additional information.
+*/
+SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
+SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
+SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
+SQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N);
+
+/*
+** CAPI3REF: Translate filenames
+**
+** These routines are available to [VFS|custom VFS implementations] for
+** translating filenames between the main database file, the journal file,
+** and the WAL file.
+**
+** If F is the name of an sqlite database file, journal file, or WAL file
+** passed by the SQLite core into the VFS, then sqlite3_filename_database(F)
+** returns the name of the corresponding database file.
+**
+** If F is the name of an sqlite database file, journal file, or WAL file
+** passed by the SQLite core into the VFS, or if F is a database filename
+** obtained from [sqlite3_db_filename()], then sqlite3_filename_journal(F)
+** returns the name of the corresponding rollback journal file.
+**
+** If F is the name of an sqlite database file, journal file, or WAL file
+** that was passed by the SQLite core into the VFS, or if F is a database
+** filename obtained from [sqlite3_db_filename()], then
+** sqlite3_filename_wal(F) returns the name of the corresponding
+** WAL file.
+**
+** In all of the above, if F is not the name of a database, journal or WAL
+** filename passed into the VFS from the SQLite core and F is not the
+** return value from [sqlite3_db_filename()], then the result is
+** undefined and is likely a memory access violation.
+*/
+SQLITE_API const char *sqlite3_filename_database(const char*);
+SQLITE_API const char *sqlite3_filename_journal(const char*);
+SQLITE_API const char *sqlite3_filename_wal(const char*);
+
+/*
+** CAPI3REF: Database File Corresponding To A Journal
+**
+** ^If X is the name of a rollback or WAL-mode journal file that is
+** passed into the xOpen method of [sqlite3_vfs], then
+** sqlite3_database_file_object(X) returns a pointer to the [sqlite3_file]
+** object that represents the main database file.
+**
+** This routine is intended for use in custom [VFS] implementations
+** only. It is not a general-purpose interface.
+** The argument sqlite3_file_object(X) must be a filename pointer that
+** has been passed into [sqlite3_vfs].xOpen method where the
+** flags parameter to xOpen contains one of the bits
+** [SQLITE_OPEN_MAIN_JOURNAL] or [SQLITE_OPEN_WAL]. Any other use
+** of this routine results in undefined and probably undesirable
+** behavior.
+*/
+SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*);
+
+/*
+** CAPI3REF: Create and Destroy VFS Filenames
+**
+** These interfces are provided for use by [VFS shim] implementations and
+** are not useful outside of that context.
+**
+** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of
+** database filename D with corresponding journal file J and WAL file W and
+** with N URI parameters key/values pairs in the array P. The result from
+** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that
+** is safe to pass to routines like:
+** <ul>
+** <li> [sqlite3_uri_parameter()],
+** <li> [sqlite3_uri_boolean()],
+** <li> [sqlite3_uri_int64()],
+** <li> [sqlite3_uri_key()],
+** <li> [sqlite3_filename_database()],
+** <li> [sqlite3_filename_journal()], or
+** <li> [sqlite3_filename_wal()].
+** </ul>
+** If a memory allocation error occurs, sqlite3_create_filename() might
+** return a NULL pointer. The memory obtained from sqlite3_create_filename(X)
+** must be released by a corresponding call to sqlite3_free_filename(Y).
+**
+** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array
+** of 2*N pointers to strings. Each pair of pointers in this array corresponds
+** to a key and value for a query parameter. The P parameter may be a NULL
+** pointer if N is zero. None of the 2*N pointers in the P array may be
+** NULL pointers and key pointers should not be empty strings.
+** None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may
+** be NULL pointers, though they can be empty strings.
+**
+** The sqlite3_free_filename(Y) routine releases a memory allocation
+** previously obtained from sqlite3_create_filename(). Invoking
+** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op.
+**
+** If the Y parameter to sqlite3_free_filename(Y) is anything other
+** than a NULL pointer or a pointer previously acquired from
+** sqlite3_create_filename(), then bad things such as heap
+** corruption or segfaults may occur. The value Y should be
+** used again after sqlite3_free_filename(Y) has been called. This means
+** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y,
+** then the corresponding [sqlite3_module.xClose() method should also be
+** invoked prior to calling sqlite3_free_filename(Y).
+*/
+SQLITE_API char *sqlite3_create_filename(
+ const char *zDatabase,
+ const char *zJournal,
+ const char *zWal,
+ int nParam,
+ const char **azParam
+);
+SQLITE_API void sqlite3_free_filename(char*);
+
+/*
+** CAPI3REF: Error Codes And Messages
+** METHOD: sqlite3
+**
+** ^If the most recent sqlite3_* API call associated with
+** [database connection] D failed, then the sqlite3_errcode(D) interface
+** returns the numeric [result code] or [extended result code] for that
+** API call.
+** ^The sqlite3_extended_errcode()
+** interface is the same except that it always returns the
+** [extended result code] even when extended result codes are
+** disabled.
+**
+** The values returned by sqlite3_errcode() and/or
+** sqlite3_extended_errcode() might change with each API call.
+** Except, there are some interfaces that are guaranteed to never
+** change the value of the error code. The error-code preserving
+** interfaces are:
+**
+** <ul>
+** <li> sqlite3_errcode()
+** <li> sqlite3_extended_errcode()
+** <li> sqlite3_errmsg()
+** <li> sqlite3_errmsg16()
+** </ul>
+**
+** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
+** text that describes the error, as either UTF-8 or UTF-16 respectively.
+** ^(Memory to hold the error message string is managed internally.
+** The application does not need to worry about freeing the result.
+** However, the error string might be overwritten or deallocated by
+** subsequent calls to other SQLite interface functions.)^
+**
+** ^The sqlite3_errstr() interface returns the English-language text
+** that describes the [result code], as UTF-8.
+** ^(Memory to hold the error message string is managed internally
+** and must not be freed by the application)^.
+**
+** When the serialized [threading mode] is in use, it might be the
+** case that a second error occurs on a separate thread in between
+** the time of the first error and the call to these interfaces.
+** When that happens, the second error will be reported since these
+** interfaces always report the most recent result. To avoid
+** this, each thread can obtain exclusive use of the [database connection] D
+** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
+** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
+** all calls to the interfaces listed here are completed.
+**
+** If an interface fails with SQLITE_MISUSE, that means the interface
+** was invoked incorrectly by the application. In that case, the
+** error code and message may or may not be set.
+*/
+SQLITE_API int sqlite3_errcode(sqlite3 *db);
+SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
+SQLITE_API const char *sqlite3_errmsg(sqlite3*);
+SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
+SQLITE_API const char *sqlite3_errstr(int);
+
+/*
+** CAPI3REF: Prepared Statement Object
+** KEYWORDS: {prepared statement} {prepared statements}
+**
+** An instance of this object represents a single SQL statement that
+** has been compiled into binary form and is ready to be evaluated.
+**
+** Think of each SQL statement as a separate computer program. The
+** original SQL text is source code. A prepared statement object
+** is the compiled object code. All SQL must be converted into a
+** prepared statement before it can be run.
+**
+** The life-cycle of a prepared statement object usually goes like this:
+**
+** <ol>
+** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
+** <li> Bind values to [parameters] using the sqlite3_bind_*()
+** interfaces.
+** <li> Run the SQL by calling [sqlite3_step()] one or more times.
+** <li> Reset the prepared statement using [sqlite3_reset()] then go back
+** to step 2. Do this zero or more times.
+** <li> Destroy the object using [sqlite3_finalize()].
+** </ol>
+*/
+typedef struct sqlite3_stmt sqlite3_stmt;
+
+/*
+** CAPI3REF: Run-time Limits
+** METHOD: sqlite3
+**
+** ^(This interface allows the size of various constructs to be limited
+** on a connection by connection basis. The first parameter is the
+** [database connection] whose limit is to be set or queried. The
+** second parameter is one of the [limit categories] that define a
+** class of constructs to be size limited. The third parameter is the
+** new limit for that construct.)^
+**
+** ^If the new limit is a negative number, the limit is unchanged.
+** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
+** [limits | hard upper bound]
+** set at compile-time by a C preprocessor macro called
+** [limits | SQLITE_MAX_<i>NAME</i>].
+** (The "_LIMIT_" in the name is changed to "_MAX_".))^
+** ^Attempts to increase a limit above its hard upper bound are
+** silently truncated to the hard upper bound.
+**
+** ^Regardless of whether or not the limit was changed, the
+** [sqlite3_limit()] interface returns the prior value of the limit.
+** ^Hence, to find the current value of a limit without changing it,
+** simply invoke this interface with the third parameter set to -1.
+**
+** Run-time limits are intended for use in applications that manage
+** both their own internal database and also databases that are controlled
+** by untrusted external sources. An example application might be a
+** web browser that has its own databases for storing history and
+** separate databases controlled by JavaScript applications downloaded
+** off the Internet. The internal databases can be given the
+** large, default limits. Databases managed by external sources can
+** be given much smaller limits designed to prevent a denial of service
+** attack. Developers might also want to use the [sqlite3_set_authorizer()]
+** interface to further control untrusted SQL. The size of the database
+** created by an untrusted script can be contained using the
+** [max_page_count] [PRAGMA].
+**
+** New run-time limit categories may be added in future releases.
+*/
+SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
+
+/*
+** CAPI3REF: Run-Time Limit Categories
+** KEYWORDS: {limit category} {*limit categories}
+**
+** These constants define various performance limits
+** that can be lowered at run-time using [sqlite3_limit()].
+** The synopsis of the meanings of the various limits is shown below.
+** Additional information is available at [limits | Limits in SQLite].
+**
+** <dl>
+** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
+** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
+**
+** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
+** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
+**
+** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
+** <dd>The maximum number of columns in a table definition or in the
+** result set of a [SELECT] or the maximum number of columns in an index
+** or in an ORDER BY or GROUP BY clause.</dd>)^
+**
+** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
+** <dd>The maximum depth of the parse tree on any expression.</dd>)^
+**
+** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
+** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
+**
+** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
+** <dd>The maximum number of instructions in a virtual machine program
+** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
+** the equivalent tries to allocate space for more than this many opcodes
+** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
+**
+** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
+** <dd>The maximum number of arguments on a function.</dd>)^
+**
+** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
+** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
+**
+** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
+** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
+** <dd>The maximum length of the pattern argument to the [LIKE] or
+** [GLOB] operators.</dd>)^
+**
+** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
+** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
+** <dd>The maximum index number of any [parameter] in an SQL statement.)^
+**
+** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
+** <dd>The maximum depth of recursion for triggers.</dd>)^
+**
+** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
+** <dd>The maximum number of auxiliary worker threads that a single
+** [prepared statement] may start.</dd>)^
+** </dl>
+*/
+#define SQLITE_LIMIT_LENGTH 0
+#define SQLITE_LIMIT_SQL_LENGTH 1
+#define SQLITE_LIMIT_COLUMN 2
+#define SQLITE_LIMIT_EXPR_DEPTH 3
+#define SQLITE_LIMIT_COMPOUND_SELECT 4
+#define SQLITE_LIMIT_VDBE_OP 5
+#define SQLITE_LIMIT_FUNCTION_ARG 6
+#define SQLITE_LIMIT_ATTACHED 7
+#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
+#define SQLITE_LIMIT_VARIABLE_NUMBER 9
+#define SQLITE_LIMIT_TRIGGER_DEPTH 10
+#define SQLITE_LIMIT_WORKER_THREADS 11
+
+/*
+** CAPI3REF: Prepare Flags
+**
+** These constants define various flags that can be passed into
+** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
+** [sqlite3_prepare16_v3()] interfaces.
+**
+** New flags may be added in future releases of SQLite.
+**
+** <dl>
+** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
+** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
+** that the prepared statement will be retained for a long time and
+** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
+** and [sqlite3_prepare16_v3()] assume that the prepared statement will
+** be used just once or at most a few times and then destroyed using
+** [sqlite3_finalize()] relatively soon. The current implementation acts
+** on this hint by avoiding the use of [lookaside memory] so as not to
+** deplete the limited store of lookaside memory. Future versions of
+** SQLite may act on this hint differently.
+**
+** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt>
+** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used
+** to be required for any prepared statement that wanted to use the
+** [sqlite3_normalized_sql()] interface. However, the
+** [sqlite3_normalized_sql()] interface is now available to all
+** prepared statements, regardless of whether or not they use this
+** flag.
+**
+** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt>
+** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler
+** to return an error (error code SQLITE_ERROR) if the statement uses
+** any virtual tables.
+** </dl>
+*/
+#define SQLITE_PREPARE_PERSISTENT 0x01
+#define SQLITE_PREPARE_NORMALIZE 0x02
+#define SQLITE_PREPARE_NO_VTAB 0x04
+
+/*
+** CAPI3REF: Compiling An SQL Statement
+** KEYWORDS: {SQL statement compiler}
+** METHOD: sqlite3
+** CONSTRUCTOR: sqlite3_stmt
+**
+** To execute an SQL statement, it must first be compiled into a byte-code
+** program using one of these routines. Or, in other words, these routines
+** are constructors for the [prepared statement] object.
+**
+** The preferred routine to use is [sqlite3_prepare_v2()]. The
+** [sqlite3_prepare()] interface is legacy and should be avoided.
+** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
+** for special purposes.
+**
+** The use of the UTF-8 interfaces is preferred, as SQLite currently
+** does all parsing using UTF-8. The UTF-16 interfaces are provided
+** as a convenience. The UTF-16 interfaces work by converting the
+** input text into UTF-8, then invoking the corresponding UTF-8 interface.
+**
+** The first argument, "db", is a [database connection] obtained from a
+** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
+** [sqlite3_open16()]. The database connection must not have been closed.
+**
+** The second argument, "zSql", is the statement to be compiled, encoded
+** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(),
+** and sqlite3_prepare_v3()
+** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
+** and sqlite3_prepare16_v3() use UTF-16.
+**
+** ^If the nByte argument is negative, then zSql is read up to the
+** first zero terminator. ^If nByte is positive, then it is the
+** number of bytes read from zSql. ^If nByte is zero, then no prepared
+** statement is generated.
+** If the caller knows that the supplied string is nul-terminated, then
+** there is a small performance advantage to passing an nByte parameter that
+** is the number of bytes in the input string <i>including</i>
+** the nul-terminator.
+**
+** ^If pzTail is not NULL then *pzTail is made to point to the first byte
+** past the end of the first SQL statement in zSql. These routines only
+** compile the first statement in zSql, so *pzTail is left pointing to
+** what remains uncompiled.
+**
+** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
+** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
+** to NULL. ^If the input text contains no SQL (if the input is an empty
+** string or a comment) then *ppStmt is set to NULL.
+** The calling procedure is responsible for deleting the compiled
+** SQL statement using [sqlite3_finalize()] after it has finished with it.
+** ppStmt may not be NULL.
+**
+** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
+** otherwise an [error code] is returned.
+**
+** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
+** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
+** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
+** are retained for backwards compatibility, but their use is discouraged.
+** ^In the "vX" interfaces, the prepared statement
+** that is returned (the [sqlite3_stmt] object) contains a copy of the
+** original SQL text. This causes the [sqlite3_step()] interface to
+** behave differently in three ways:
+**
+** <ol>
+** <li>
+** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
+** always used to do, [sqlite3_step()] will automatically recompile the SQL
+** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
+** retries will occur before sqlite3_step() gives up and returns an error.
+** </li>
+**
+** <li>
+** ^When an error occurs, [sqlite3_step()] will return one of the detailed
+** [error codes] or [extended error codes]. ^The legacy behavior was that
+** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
+** and the application would have to make a second call to [sqlite3_reset()]
+** in order to find the underlying cause of the problem. With the "v2" prepare
+** interfaces, the underlying reason for the error is returned immediately.
+** </li>
+**
+** <li>
+** ^If the specific value bound to a [parameter | host parameter] in the
+** WHERE clause might influence the choice of query plan for a statement,
+** then the statement will be automatically recompiled, as if there had been
+** a schema change, on the first [sqlite3_step()] call following any change
+** to the [sqlite3_bind_text | bindings] of that [parameter].
+** ^The specific value of a WHERE-clause [parameter] might influence the
+** choice of query plan if the parameter is the left-hand side of a [LIKE]
+** or [GLOB] operator or if the parameter is compared to an indexed column
+** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled.
+** </li>
+** </ol>
+**
+** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
+** the extra prepFlags parameter, which is a bit array consisting of zero or
+** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The
+** sqlite3_prepare_v2() interface works exactly the same as
+** sqlite3_prepare_v3() with a zero prepFlags parameter.
+*/
+SQLITE_API int sqlite3_prepare(
+ sqlite3 *db, /* Database handle */
+ const char *zSql, /* SQL statement, UTF-8 encoded */
+ int nByte, /* Maximum length of zSql in bytes. */
+ sqlite3_stmt **ppStmt, /* OUT: Statement handle */
+ const char **pzTail /* OUT: Pointer to unused portion of zSql */
+);
+SQLITE_API int sqlite3_prepare_v2(
+ sqlite3 *db, /* Database handle */
+ const char *zSql, /* SQL statement, UTF-8 encoded */
+ int nByte, /* Maximum length of zSql in bytes. */
+ sqlite3_stmt **ppStmt, /* OUT: Statement handle */
+ const char **pzTail /* OUT: Pointer to unused portion of zSql */
+);
+SQLITE_API int sqlite3_prepare_v3(
+ sqlite3 *db, /* Database handle */
+ const char *zSql, /* SQL statement, UTF-8 encoded */
+ int nByte, /* Maximum length of zSql in bytes. */
+ unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
+ sqlite3_stmt **ppStmt, /* OUT: Statement handle */
+ const char **pzTail /* OUT: Pointer to unused portion of zSql */
+);
+SQLITE_API int sqlite3_prepare16(
+ sqlite3 *db, /* Database handle */
+ const void *zSql, /* SQL statement, UTF-16 encoded */
+ int nByte, /* Maximum length of zSql in bytes. */
+ sqlite3_stmt **ppStmt, /* OUT: Statement handle */
+ const void **pzTail /* OUT: Pointer to unused portion of zSql */
+);
+SQLITE_API int sqlite3_prepare16_v2(
+ sqlite3 *db, /* Database handle */
+ const void *zSql, /* SQL statement, UTF-16 encoded */
+ int nByte, /* Maximum length of zSql in bytes. */
+ sqlite3_stmt **ppStmt, /* OUT: Statement handle */
+ const void **pzTail /* OUT: Pointer to unused portion of zSql */
+);
+SQLITE_API int sqlite3_prepare16_v3(
+ sqlite3 *db, /* Database handle */
+ const void *zSql, /* SQL statement, UTF-16 encoded */
+ int nByte, /* Maximum length of zSql in bytes. */
+ unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
+ sqlite3_stmt **ppStmt, /* OUT: Statement handle */
+ const void **pzTail /* OUT: Pointer to unused portion of zSql */
+);
+
+/*
+** CAPI3REF: Retrieving Statement SQL
+** METHOD: sqlite3_stmt
+**
+** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
+** SQL text used to create [prepared statement] P if P was
+** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
+** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
+** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
+** string containing the SQL text of prepared statement P with
+** [bound parameters] expanded.
+** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8
+** string containing the normalized SQL text of prepared statement P. The
+** semantics used to normalize a SQL statement are unspecified and subject
+** to change. At a minimum, literal values will be replaced with suitable
+** placeholders.
+**
+** ^(For example, if a prepared statement is created using the SQL
+** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
+** and parameter :xyz is unbound, then sqlite3_sql() will return
+** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
+** will return "SELECT 2345,NULL".)^
+**
+** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
+** is available to hold the result, or if the result would exceed the
+** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
+**
+** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
+** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
+** option causes sqlite3_expanded_sql() to always return NULL.
+**
+** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)
+** are managed by SQLite and are automatically freed when the prepared
+** statement is finalized.
+** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
+** is obtained from [sqlite3_malloc()] and must be free by the application
+** by passing it to [sqlite3_free()].
+*/
+SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
+SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
+SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Determine If An SQL Statement Writes The Database
+** METHOD: sqlite3_stmt
+**
+** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
+** and only if the [prepared statement] X makes no direct changes to
+** the content of the database file.
+**
+** Note that [application-defined SQL functions] or
+** [virtual tables] might change the database indirectly as a side effect.
+** ^(For example, if an application defines a function "eval()" that
+** calls [sqlite3_exec()], then the following SQL statement would
+** change the database file through side-effects:
+**
+** <blockquote><pre>
+** SELECT eval('DELETE FROM t1') FROM t2;
+** </pre></blockquote>
+**
+** But because the [SELECT] statement does not change the database file
+** directly, sqlite3_stmt_readonly() would still return true.)^
+**
+** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
+** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
+** since the statements themselves do not actually modify the database but
+** rather they control the timing of when other statements modify the
+** database. ^The [ATTACH] and [DETACH] statements also cause
+** sqlite3_stmt_readonly() to return true since, while those statements
+** change the configuration of a database connection, they do not make
+** changes to the content of the database files on disk.
+** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
+** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
+** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
+** sqlite3_stmt_readonly() returns false for those commands.
+*/
+SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement
+** METHOD: sqlite3_stmt
+**
+** ^The sqlite3_stmt_isexplain(S) interface returns 1 if the
+** prepared statement S is an EXPLAIN statement, or 2 if the
+** statement S is an EXPLAIN QUERY PLAN.
+** ^The sqlite3_stmt_isexplain(S) interface returns 0 if S is
+** an ordinary statement or a NULL pointer.
+*/
+SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Determine If A Prepared Statement Has Been Reset
+** METHOD: sqlite3_stmt
+**
+** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
+** [prepared statement] S has been stepped at least once using
+** [sqlite3_step(S)] but has neither run to completion (returned
+** [SQLITE_DONE] from [sqlite3_step(S)]) nor
+** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
+** interface returns false if S is a NULL pointer. If S is not a
+** NULL pointer and is not a pointer to a valid [prepared statement]
+** object, then the behavior is undefined and probably undesirable.
+**
+** This interface can be used in combination [sqlite3_next_stmt()]
+** to locate all prepared statements associated with a database
+** connection that are in need of being reset. This can be used,
+** for example, in diagnostic routines to search for prepared
+** statements that are holding a transaction open.
+*/
+SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
+
+/*
+** CAPI3REF: Dynamically Typed Value Object
+** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
+**
+** SQLite uses the sqlite3_value object to represent all values
+** that can be stored in a database table. SQLite uses dynamic typing
+** for the values it stores. ^Values stored in sqlite3_value objects
+** can be integers, floating point values, strings, BLOBs, or NULL.
+**
+** An sqlite3_value object may be either "protected" or "unprotected".
+** Some interfaces require a protected sqlite3_value. Other interfaces
+** will accept either a protected or an unprotected sqlite3_value.
+** Every interface that accepts sqlite3_value arguments specifies
+** whether or not it requires a protected sqlite3_value. The
+** [sqlite3_value_dup()] interface can be used to construct a new
+** protected sqlite3_value from an unprotected sqlite3_value.
+**
+** The terms "protected" and "unprotected" refer to whether or not
+** a mutex is held. An internal mutex is held for a protected
+** sqlite3_value object but no mutex is held for an unprotected
+** sqlite3_value object. If SQLite is compiled to be single-threaded
+** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
+** or if SQLite is run in one of reduced mutex modes
+** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
+** then there is no distinction between protected and unprotected
+** sqlite3_value objects and they can be used interchangeably. However,
+** for maximum code portability it is recommended that applications
+** still make the distinction between protected and unprotected
+** sqlite3_value objects even when not strictly required.
+**
+** ^The sqlite3_value objects that are passed as parameters into the
+** implementation of [application-defined SQL functions] are protected.
+** ^The sqlite3_value object returned by
+** [sqlite3_column_value()] is unprotected.
+** Unprotected sqlite3_value objects may only be used as arguments
+** to [sqlite3_result_value()], [sqlite3_bind_value()], and
+** [sqlite3_value_dup()].
+** The [sqlite3_value_blob | sqlite3_value_type()] family of
+** interfaces require protected sqlite3_value objects.
+*/
+typedef struct sqlite3_value sqlite3_value;
+
+/*
+** CAPI3REF: SQL Function Context Object
+**
+** The context in which an SQL function executes is stored in an
+** sqlite3_context object. ^A pointer to an sqlite3_context object
+** is always first parameter to [application-defined SQL functions].
+** The application-defined SQL function implementation will pass this
+** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
+** [sqlite3_aggregate_context()], [sqlite3_user_data()],
+** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
+** and/or [sqlite3_set_auxdata()].
+*/
+typedef struct sqlite3_context sqlite3_context;
+
+/*
+** CAPI3REF: Binding Values To Prepared Statements
+** KEYWORDS: {host parameter} {host parameters} {host parameter name}
+** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
+** METHOD: sqlite3_stmt
+**
+** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
+** literals may be replaced by a [parameter] that matches one of following
+** templates:
+**
+** <ul>
+** <li> ?
+** <li> ?NNN
+** <li> :VVV
+** <li> @VVV
+** <li> $VVV
+** </ul>
+**
+** In the templates above, NNN represents an integer literal,
+** and VVV represents an alphanumeric identifier.)^ ^The values of these
+** parameters (also called "host parameter names" or "SQL parameters")
+** can be set using the sqlite3_bind_*() routines defined here.
+**
+** ^The first argument to the sqlite3_bind_*() routines is always
+** a pointer to the [sqlite3_stmt] object returned from
+** [sqlite3_prepare_v2()] or its variants.
+**
+** ^The second argument is the index of the SQL parameter to be set.
+** ^The leftmost SQL parameter has an index of 1. ^When the same named
+** SQL parameter is used more than once, second and subsequent
+** occurrences have the same index as the first occurrence.
+** ^The index for named parameters can be looked up using the
+** [sqlite3_bind_parameter_index()] API if desired. ^The index
+** for "?NNN" parameters is the value of NNN.
+** ^The NNN value must be between 1 and the [sqlite3_limit()]
+** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 32766).
+**
+** ^The third argument is the value to bind to the parameter.
+** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
+** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
+** is ignored and the end result is the same as sqlite3_bind_null().
+** ^If the third parameter to sqlite3_bind_text() is not NULL, then
+** it should be a pointer to well-formed UTF8 text.
+** ^If the third parameter to sqlite3_bind_text16() is not NULL, then
+** it should be a pointer to well-formed UTF16 text.
+** ^If the third parameter to sqlite3_bind_text64() is not NULL, then
+** it should be a pointer to a well-formed unicode string that is
+** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16
+** otherwise.
+**
+** [[byte-order determination rules]] ^The byte-order of
+** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)
+** found in first character, which is removed, or in the absence of a BOM
+** the byte order is the native byte order of the host
+** machine for sqlite3_bind_text16() or the byte order specified in
+** the 6th parameter for sqlite3_bind_text64().)^
+** ^If UTF16 input text contains invalid unicode
+** characters, then SQLite might change those invalid characters
+** into the unicode replacement character: U+FFFD.
+**
+** ^(In those routines that have a fourth argument, its value is the
+** number of bytes in the parameter. To be clear: the value is the
+** number of <u>bytes</u> in the value, not the number of characters.)^
+** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
+** is negative, then the length of the string is
+** the number of bytes up to the first zero terminator.
+** If the fourth parameter to sqlite3_bind_blob() is negative, then
+** the behavior is undefined.
+** If a non-negative fourth parameter is provided to sqlite3_bind_text()
+** or sqlite3_bind_text16() or sqlite3_bind_text64() then
+** that parameter must be the byte offset
+** where the NUL terminator would occur assuming the string were NUL
+** terminated. If any NUL characters occurs at byte offsets less than
+** the value of the fourth parameter then the resulting string value will
+** contain embedded NULs. The result of expressions involving strings
+** with embedded NULs is undefined.
+**
+** ^The fifth argument to the BLOB and string binding interfaces
+** is a destructor used to dispose of the BLOB or
+** string after SQLite has finished with it. ^The destructor is called
+** to dispose of the BLOB or string even if the call to the bind API fails,
+** except the destructor is not called if the third parameter is a NULL
+** pointer or the fourth parameter is negative.
+** ^If the fifth argument is
+** the special value [SQLITE_STATIC], then SQLite assumes that the
+** information is in static, unmanaged space and does not need to be freed.
+** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
+** SQLite makes its own private copy of the data immediately, before
+** the sqlite3_bind_*() routine returns.
+**
+** ^The sixth argument to sqlite3_bind_text64() must be one of
+** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
+** to specify the encoding of the text in the third parameter. If
+** the sixth argument to sqlite3_bind_text64() is not one of the
+** allowed values shown above, or if the text encoding is different
+** from the encoding specified by the sixth parameter, then the behavior
+** is undefined.
+**
+** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
+** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
+** (just an integer to hold its size) while it is being processed.
+** Zeroblobs are intended to serve as placeholders for BLOBs whose
+** content is later written using
+** [sqlite3_blob_open | incremental BLOB I/O] routines.
+** ^A negative value for the zeroblob results in a zero-length BLOB.
+**
+** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
+** [prepared statement] S to have an SQL value of NULL, but to also be
+** associated with the pointer P of type T. ^D is either a NULL pointer or
+** a pointer to a destructor function for P. ^SQLite will invoke the
+** destructor D with a single argument of P when it is finished using
+** P. The T parameter should be a static string, preferably a string
+** literal. The sqlite3_bind_pointer() routine is part of the
+** [pointer passing interface] added for SQLite 3.20.0.
+**
+** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
+** for the [prepared statement] or with a prepared statement for which
+** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
+** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
+** routine is passed a [prepared statement] that has been finalized, the
+** result is undefined and probably harmful.
+**
+** ^Bindings are not cleared by the [sqlite3_reset()] routine.
+** ^Unbound parameters are interpreted as NULL.
+**
+** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
+** [error code] if anything goes wrong.
+** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
+** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
+** [SQLITE_MAX_LENGTH].
+** ^[SQLITE_RANGE] is returned if the parameter
+** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
+**
+** See also: [sqlite3_bind_parameter_count()],
+** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
+*/
+SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
+SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
+ void(*)(void*));
+SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
+SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
+SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
+SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
+SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
+SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
+SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
+ void(*)(void*), unsigned char encoding);
+SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
+SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
+SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
+SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
+
+/*
+** CAPI3REF: Number Of SQL Parameters
+** METHOD: sqlite3_stmt
+**
+** ^This routine can be used to find the number of [SQL parameters]
+** in a [prepared statement]. SQL parameters are tokens of the
+** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
+** placeholders for values that are [sqlite3_bind_blob | bound]
+** to the parameters at a later time.
+**
+** ^(This routine actually returns the index of the largest (rightmost)
+** parameter. For all forms except ?NNN, this will correspond to the
+** number of unique parameters. If parameters of the ?NNN form are used,
+** there may be gaps in the list.)^
+**
+** See also: [sqlite3_bind_blob|sqlite3_bind()],
+** [sqlite3_bind_parameter_name()], and
+** [sqlite3_bind_parameter_index()].
+*/
+SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
+
+/*
+** CAPI3REF: Name Of A Host Parameter
+** METHOD: sqlite3_stmt
+**
+** ^The sqlite3_bind_parameter_name(P,N) interface returns
+** the name of the N-th [SQL parameter] in the [prepared statement] P.
+** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
+** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
+** respectively.
+** In other words, the initial ":" or "$" or "@" or "?"
+** is included as part of the name.)^
+** ^Parameters of the form "?" without a following integer have no name
+** and are referred to as "nameless" or "anonymous parameters".
+**
+** ^The first host parameter has an index of 1, not 0.
+**
+** ^If the value N is out of range or if the N-th parameter is
+** nameless, then NULL is returned. ^The returned string is
+** always in UTF-8 encoding even if the named parameter was
+** originally specified as UTF-16 in [sqlite3_prepare16()],
+** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
+**
+** See also: [sqlite3_bind_blob|sqlite3_bind()],
+** [sqlite3_bind_parameter_count()], and
+** [sqlite3_bind_parameter_index()].
+*/
+SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
+
+/*
+** CAPI3REF: Index Of A Parameter With A Given Name
+** METHOD: sqlite3_stmt
+**
+** ^Return the index of an SQL parameter given its name. ^The
+** index value returned is suitable for use as the second
+** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
+** is returned if no matching parameter is found. ^The parameter
+** name must be given in UTF-8 even if the original statement
+** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
+** [sqlite3_prepare16_v3()].
+**
+** See also: [sqlite3_bind_blob|sqlite3_bind()],
+** [sqlite3_bind_parameter_count()], and
+** [sqlite3_bind_parameter_name()].
+*/
+SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
+
+/*
+** CAPI3REF: Reset All Bindings On A Prepared Statement
+** METHOD: sqlite3_stmt
+**
+** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
+** the [sqlite3_bind_blob | bindings] on a [prepared statement].
+** ^Use this routine to reset all host parameters to NULL.
+*/
+SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
+
+/*
+** CAPI3REF: Number Of Columns In A Result Set
+** METHOD: sqlite3_stmt
+**
+** ^Return the number of columns in the result set returned by the
+** [prepared statement]. ^If this routine returns 0, that means the
+** [prepared statement] returns no data (for example an [UPDATE]).
+** ^However, just because this routine returns a positive number does not
+** mean that one or more rows of data will be returned. ^A SELECT statement
+** will always have a positive sqlite3_column_count() but depending on the
+** WHERE clause constraints and the table content, it might return no rows.
+**
+** See also: [sqlite3_data_count()]
+*/
+SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Column Names In A Result Set
+** METHOD: sqlite3_stmt
+**
+** ^These routines return the name assigned to a particular column
+** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
+** interface returns a pointer to a zero-terminated UTF-8 string
+** and sqlite3_column_name16() returns a pointer to a zero-terminated
+** UTF-16 string. ^The first parameter is the [prepared statement]
+** that implements the [SELECT] statement. ^The second parameter is the
+** column number. ^The leftmost column is number 0.
+**
+** ^The returned string pointer is valid until either the [prepared statement]
+** is destroyed by [sqlite3_finalize()] or until the statement is automatically
+** reprepared by the first call to [sqlite3_step()] for a particular run
+** or until the next call to
+** sqlite3_column_name() or sqlite3_column_name16() on the same column.
+**
+** ^If sqlite3_malloc() fails during the processing of either routine
+** (for example during a conversion from UTF-8 to UTF-16) then a
+** NULL pointer is returned.
+**
+** ^The name of a result column is the value of the "AS" clause for
+** that column, if there is an AS clause. If there is no AS clause
+** then the name of the column is unspecified and may change from
+** one release of SQLite to the next.
+*/
+SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
+SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
+
+/*
+** CAPI3REF: Source Of Data In A Query Result
+** METHOD: sqlite3_stmt
+**
+** ^These routines provide a means to determine the database, table, and
+** table column that is the origin of a particular result column in
+** [SELECT] statement.
+** ^The name of the database or table or column can be returned as
+** either a UTF-8 or UTF-16 string. ^The _database_ routines return
+** the database name, the _table_ routines return the table name, and
+** the origin_ routines return the column name.
+** ^The returned string is valid until the [prepared statement] is destroyed
+** using [sqlite3_finalize()] or until the statement is automatically
+** reprepared by the first call to [sqlite3_step()] for a particular run
+** or until the same information is requested
+** again in a different encoding.
+**
+** ^The names returned are the original un-aliased names of the
+** database, table, and column.
+**
+** ^The first argument to these interfaces is a [prepared statement].
+** ^These functions return information about the Nth result column returned by
+** the statement, where N is the second function argument.
+** ^The left-most column is column 0 for these routines.
+**
+** ^If the Nth column returned by the statement is an expression or
+** subquery and is not a column value, then all of these functions return
+** NULL. ^These routines might also return NULL if a memory allocation error
+** occurs. ^Otherwise, they return the name of the attached database, table,
+** or column that query result column was extracted from.
+**
+** ^As with all other SQLite APIs, those whose names end with "16" return
+** UTF-16 encoded strings and the other functions return UTF-8.
+**
+** ^These APIs are only available if the library was compiled with the
+** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
+**
+** If two or more threads call one or more
+** [sqlite3_column_database_name | column metadata interfaces]
+** for the same [prepared statement] and result column
+** at the same time then the results are undefined.
+*/
+SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
+SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
+SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
+SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
+SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
+SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
+
+/*
+** CAPI3REF: Declared Datatype Of A Query Result
+** METHOD: sqlite3_stmt
+**
+** ^(The first parameter is a [prepared statement].
+** If this statement is a [SELECT] statement and the Nth column of the
+** returned result set of that [SELECT] is a table column (not an
+** expression or subquery) then the declared type of the table
+** column is returned.)^ ^If the Nth column of the result set is an
+** expression or subquery, then a NULL pointer is returned.
+** ^The returned string is always UTF-8 encoded.
+**
+** ^(For example, given the database schema:
+**
+** CREATE TABLE t1(c1 VARIANT);
+**
+** and the following statement to be compiled:
+**
+** SELECT c1 + 1, c1 FROM t1;
+**
+** this routine would return the string "VARIANT" for the second result
+** column (i==1), and a NULL pointer for the first result column (i==0).)^
+**
+** ^SQLite uses dynamic run-time typing. ^So just because a column
+** is declared to contain a particular type does not mean that the
+** data stored in that column is of the declared type. SQLite is
+** strongly typed, but the typing is dynamic not static. ^Type
+** is associated with individual values, not with the containers
+** used to hold those values.
+*/
+SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
+SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
+
+/*
+** CAPI3REF: Evaluate An SQL Statement
+** METHOD: sqlite3_stmt
+**
+** After a [prepared statement] has been prepared using any of
+** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
+** or [sqlite3_prepare16_v3()] or one of the legacy
+** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
+** must be called one or more times to evaluate the statement.
+**
+** The details of the behavior of the sqlite3_step() interface depend
+** on whether the statement was prepared using the newer "vX" interfaces
+** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
+** [sqlite3_prepare16_v2()] or the older legacy
+** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
+** new "vX" interface is recommended for new applications but the legacy
+** interface will continue to be supported.
+**
+** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
+** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
+** ^With the "v2" interface, any of the other [result codes] or
+** [extended result codes] might be returned as well.
+**
+** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
+** database locks it needs to do its job. ^If the statement is a [COMMIT]
+** or occurs outside of an explicit transaction, then you can retry the
+** statement. If the statement is not a [COMMIT] and occurs within an
+** explicit transaction then you should rollback the transaction before
+** continuing.
+**
+** ^[SQLITE_DONE] means that the statement has finished executing
+** successfully. sqlite3_step() should not be called again on this virtual
+** machine without first calling [sqlite3_reset()] to reset the virtual
+** machine back to its initial state.
+**
+** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
+** is returned each time a new row of data is ready for processing by the
+** caller. The values may be accessed using the [column access functions].
+** sqlite3_step() is called again to retrieve the next row of data.
+**
+** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
+** violation) has occurred. sqlite3_step() should not be called again on
+** the VM. More information may be found by calling [sqlite3_errmsg()].
+** ^With the legacy interface, a more specific error code (for example,
+** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
+** can be obtained by calling [sqlite3_reset()] on the
+** [prepared statement]. ^In the "v2" interface,
+** the more specific error code is returned directly by sqlite3_step().
+**
+** [SQLITE_MISUSE] means that the this routine was called inappropriately.
+** Perhaps it was called on a [prepared statement] that has
+** already been [sqlite3_finalize | finalized] or on one that had
+** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
+** be the case that the same database connection is being used by two or
+** more threads at the same moment in time.
+**
+** For all versions of SQLite up to and including 3.6.23.1, a call to
+** [sqlite3_reset()] was required after sqlite3_step() returned anything
+** other than [SQLITE_ROW] before any subsequent invocation of
+** sqlite3_step(). Failure to reset the prepared statement using
+** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
+** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
+** sqlite3_step() began
+** calling [sqlite3_reset()] automatically in this circumstance rather
+** than returning [SQLITE_MISUSE]. This is not considered a compatibility
+** break because any application that ever receives an SQLITE_MISUSE error
+** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
+** can be used to restore the legacy behavior.
+**
+** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
+** API always returns a generic error code, [SQLITE_ERROR], following any
+** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
+** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
+** specific [error codes] that better describes the error.
+** We admit that this is a goofy design. The problem has been fixed
+** with the "v2" interface. If you prepare all of your SQL statements
+** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
+** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
+** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
+** then the more specific [error codes] are returned directly
+** by sqlite3_step(). The use of the "vX" interfaces is recommended.
+*/
+SQLITE_API int sqlite3_step(sqlite3_stmt*);
+
+/*
+** CAPI3REF: Number of columns in a result set
+** METHOD: sqlite3_stmt
+**
+** ^The sqlite3_data_count(P) interface returns the number of columns in the
+** current row of the result set of [prepared statement] P.
+** ^If prepared statement P does not have results ready to return
+** (via calls to the [sqlite3_column_int | sqlite3_column()] family of
+** interfaces) then sqlite3_data_count(P) returns 0.
+** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
+** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
+** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
+** will return non-zero if previous call to [sqlite3_step](P) returned
+** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
+** where it always returns zero since each step of that multi-step
+** pragma returns 0 columns of data.
+**
+** See also: [sqlite3_column_count()]
+*/
+SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Fundamental Datatypes
+** KEYWORDS: SQLITE_TEXT
+**
+** ^(Every value in SQLite has one of five fundamental datatypes:
+**
+** <ul>
+** <li> 64-bit signed integer
+** <li> 64-bit IEEE floating point number
+** <li> string
+** <li> BLOB
+** <li> NULL
+** </ul>)^
+**
+** These constants are codes for each of those types.
+**
+** Note that the SQLITE_TEXT constant was also used in SQLite version 2
+** for a completely different meaning. Software that links against both
+** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
+** SQLITE_TEXT.
+*/
+#define SQLITE_INTEGER 1
+#define SQLITE_FLOAT 2
+#define SQLITE_BLOB 4
+#define SQLITE_NULL 5
+#ifdef SQLITE_TEXT
+# undef SQLITE_TEXT
+#else
+# define SQLITE_TEXT 3
+#endif
+#define SQLITE3_TEXT 3
+
+/*
+** CAPI3REF: Result Values From A Query
+** KEYWORDS: {column access functions}
+** METHOD: sqlite3_stmt
+**
+** <b>Summary:</b>
+** <blockquote><table border=0 cellpadding=0 cellspacing=0>
+** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
+** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
+** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
+** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
+** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
+** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
+** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
+** [sqlite3_value|unprotected sqlite3_value] object.
+** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
+** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
+** or a UTF-8 TEXT result in bytes
+** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
+** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
+** TEXT in bytes
+** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
+** datatype of the result
+** </table></blockquote>
+**
+** <b>Details:</b>
+**
+** ^These routines return information about a single column of the current
+** result row of a query. ^In every case the first argument is a pointer
+** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
+** that was returned from [sqlite3_prepare_v2()] or one of its variants)
+** and the second argument is the index of the column for which information
+** should be returned. ^The leftmost column of the result set has the index 0.
+** ^The number of columns in the result can be determined using
+** [sqlite3_column_count()].
+**
+** If the SQL statement does not currently point to a valid row, or if the
+** column index is out of range, the result is undefined.
+** These routines may only be called when the most recent call to
+** [sqlite3_step()] has returned [SQLITE_ROW] and neither
+** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
+** If any of these routines are called after [sqlite3_reset()] or
+** [sqlite3_finalize()] or after [sqlite3_step()] has returned
+** something other than [SQLITE_ROW], the results are undefined.
+** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
+** are called from a different thread while any of these routines
+** are pending, then the results are undefined.
+**
+** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
+** each return the value of a result column in a specific data format. If
+** the result column is not initially in the requested format (for example,
+** if the query returns an integer but the sqlite3_column_text() interface
+** is used to extract the value) then an automatic type conversion is performed.
+**
+** ^The sqlite3_column_type() routine returns the
+** [SQLITE_INTEGER | datatype code] for the initial data type
+** of the result column. ^The returned value is one of [SQLITE_INTEGER],
+** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
+** The return value of sqlite3_column_type() can be used to decide which
+** of the first six interface should be used to extract the column value.
+** The value returned by sqlite3_column_type() is only meaningful if no
+** automatic type conversions have occurred for the value in question.
+** After a type conversion, the result of calling sqlite3_column_type()
+** is undefined, though harmless. Future
+** versions of SQLite may change the behavior of sqlite3_column_type()
+** following a type conversion.
+**
+** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
+** or sqlite3_column_bytes16() interfaces can be used to determine the size
+** of that BLOB or string.
+**
+** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
+** routine returns the number of bytes in that BLOB or string.
+** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
+** the string to UTF-8 and then returns the number of bytes.
+** ^If the result is a numeric value then sqlite3_column_bytes() uses
+** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
+** the number of bytes in that string.
+** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
+**
+** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
+** routine returns the number of bytes in that BLOB or string.
+** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
+** the string to UTF-16 and then returns the number of bytes.
+** ^If the result is a numeric value then sqlite3_column_bytes16() uses
+** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
+** the number of bytes in that string.
+** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
+**
+** ^The values returned by [sqlite3_column_bytes()] and
+** [sqlite3_column_bytes16()] do not include the zero terminators at the end
+** of the string. ^For clarity: the values returned by
+** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
+** bytes in the string, not the number of characters.
+**
+** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
+** even empty strings, are always zero-terminated. ^The return
+** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
+**
+** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
+** [unprotected sqlite3_value] object. In a multithreaded environment,
+** an unprotected sqlite3_value object may only be used safely with
+** [sqlite3_bind_value()] and [sqlite3_result_value()].
+** If the [unprotected sqlite3_value] object returned by
+** [sqlite3_column_value()] is used in any other way, including calls
+** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
+** or [sqlite3_value_bytes()], the behavior is not threadsafe.
+** Hence, the sqlite3_column_value() interface
+** is normally only useful within the implementation of
+** [application-defined SQL functions] or [virtual tables], not within
+** top-level application code.
+**
+** The these routines may attempt to convert the datatype of the result.
+** ^For example, if the internal representation is FLOAT and a text result
+** is requested, [sqlite3_snprintf()] is used internally to perform the
+** conversion automatically. ^(The following table details the conversions
+** that are applied:
+**
+** <blockquote>
+** <table border="1">
+** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
+**
+** <tr><td> NULL <td> INTEGER <td> Result is 0
+** <tr><td> NULL <td> FLOAT <td> Result is 0.0
+** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
+** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
+** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
+** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
+** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
+** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
+** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
+** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
+** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
+** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
+** <tr><td> TEXT <td> BLOB <td> No change
+** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
+** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
+** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
+** </table>
+** </blockquote>)^
+**
+** Note that when type conversions occur, pointers returned by prior
+** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
+** sqlite3_column_text16() may be invalidated.
+** Type conversions and pointer invalidations might occur
+** in the following cases:
+**
+** <ul>
+** <li> The initial content is a BLOB and sqlite3_column_text() or
+** sqlite3_column_text16() is called. A zero-terminator might
+** need to be added to the string.</li>
+** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
+** sqlite3_column_text16() is called. The content must be converted
+** to UTF-16.</li>
+** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
+** sqlite3_column_text() is called. The content must be converted
+** to UTF-8.</li>
+** </ul>
+**
+** ^Conversions between UTF-16be and UTF-16le are always done in place and do
+** not invalidate a prior pointer, though of course the content of the buffer
+** that the prior pointer references will have been modified. Other kinds
+** of conversion are done in place when it is possible, but sometimes they
+** are not possible and in those cases prior pointers are invalidated.
+**
+** The safest policy is to invoke these routines
+** in one of the following ways:
+**
+** <ul>
+** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
+** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
+** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
+** </ul>
+**
+** In other words, you should call sqlite3_column_text(),
+** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
+** into the desired format, then invoke sqlite3_column_bytes() or
+** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
+** to sqlite3_column_text() or sqlite3_column_blob() with calls to
+** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
+** with calls to sqlite3_column_bytes().
+**
+** ^The pointers returned are valid until a type conversion occurs as
+** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
+** [sqlite3_finalize()] is called. ^The memory space used to hold strings
+** and BLOBs is freed automatically. Do not pass the pointers returned
+** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
+** [sqlite3_free()].
+**
+** As long as the input parameters are correct, these routines will only
+** fail if an out-of-memory error occurs during a format conversion.
+** Only the following subset of interfaces are subject to out-of-memory
+** errors:
+**
+** <ul>
+** <li> sqlite3_column_blob()
+** <li> sqlite3_column_text()
+** <li> sqlite3_column_text16()
+** <li> sqlite3_column_bytes()
+** <li> sqlite3_column_bytes16()
+** </ul>
+**
+** If an out-of-memory error occurs, then the return value from these
+** routines is the same as if the column had contained an SQL NULL value.
+** Valid SQL NULL returns can be distinguished from out-of-memory errors
+** by invoking the [sqlite3_errcode()] immediately after the suspect
+** return value is obtained and before any
+** other SQLite interface is called on the same [database connection].
+*/
+SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
+SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
+SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
+SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
+SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
+SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
+SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
+SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
+SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
+SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
+
+/*
+** CAPI3REF: Destroy A Prepared Statement Object
+** DESTRUCTOR: sqlite3_stmt
+**
+** ^The sqlite3_finalize() function is called to delete a [prepared statement].
+** ^If the most recent evaluation of the statement encountered no errors
+** or if the statement is never been evaluated, then sqlite3_finalize() returns
+** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
+** sqlite3_finalize(S) returns the appropriate [error code] or
+** [extended error code].
+**
+** ^The sqlite3_finalize(S) routine can be called at any point during
+** the life cycle of [prepared statement] S:
+** before statement S is ever evaluated, after
+** one or more calls to [sqlite3_reset()], or after any call
+** to [sqlite3_step()] regardless of whether or not the statement has
+** completed execution.
+**
+** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
+**
+** The application must finalize every [prepared statement] in order to avoid
+** resource leaks. It is a grievous error for the application to try to use
+** a prepared statement after it has been finalized. Any use of a prepared
+** statement after it has been finalized can result in undefined and
+** undesirable behavior such as segfaults and heap corruption.
+*/
+SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Reset A Prepared Statement Object
+** METHOD: sqlite3_stmt
+**
+** The sqlite3_reset() function is called to reset a [prepared statement]
+** object back to its initial state, ready to be re-executed.
+** ^Any SQL statement variables that had values bound to them using
+** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
+** Use [sqlite3_clear_bindings()] to reset the bindings.
+**
+** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
+** back to the beginning of its program.
+**
+** ^If the most recent call to [sqlite3_step(S)] for the
+** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
+** or if [sqlite3_step(S)] has never before been called on S,
+** then [sqlite3_reset(S)] returns [SQLITE_OK].
+**
+** ^If the most recent call to [sqlite3_step(S)] for the
+** [prepared statement] S indicated an error, then
+** [sqlite3_reset(S)] returns an appropriate [error code].
+**
+** ^The [sqlite3_reset(S)] interface does not change the values
+** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
+*/
+SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Create Or Redefine SQL Functions
+** KEYWORDS: {function creation routines}
+** METHOD: sqlite3
+**
+** ^These functions (collectively known as "function creation routines")
+** are used to add SQL functions or aggregates or to redefine the behavior
+** of existing SQL functions or aggregates. The only differences between
+** the three "sqlite3_create_function*" routines are the text encoding
+** expected for the second parameter (the name of the function being
+** created) and the presence or absence of a destructor callback for
+** the application data pointer. Function sqlite3_create_window_function()
+** is similar, but allows the user to supply the extra callback functions
+** needed by [aggregate window functions].
+**
+** ^The first parameter is the [database connection] to which the SQL
+** function is to be added. ^If an application uses more than one database
+** connection then application-defined SQL functions must be added
+** to each database connection separately.
+**
+** ^The second parameter is the name of the SQL function to be created or
+** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
+** representation, exclusive of the zero-terminator. ^Note that the name
+** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
+** ^Any attempt to create a function with a longer name
+** will result in [SQLITE_MISUSE] being returned.
+**
+** ^The third parameter (nArg)
+** is the number of arguments that the SQL function or
+** aggregate takes. ^If this parameter is -1, then the SQL function or
+** aggregate may take any number of arguments between 0 and the limit
+** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
+** parameter is less than -1 or greater than 127 then the behavior is
+** undefined.
+**
+** ^The fourth parameter, eTextRep, specifies what
+** [SQLITE_UTF8 | text encoding] this SQL function prefers for
+** its parameters. The application should set this parameter to
+** [SQLITE_UTF16LE] if the function implementation invokes
+** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
+** implementation invokes [sqlite3_value_text16be()] on an input, or
+** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
+** otherwise. ^The same SQL function may be registered multiple times using
+** different preferred text encodings, with different implementations for
+** each encoding.
+** ^When multiple implementations of the same function are available, SQLite
+** will pick the one that involves the least amount of data conversion.
+**
+** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
+** to signal that the function will always return the same result given
+** the same inputs within a single SQL statement. Most SQL functions are
+** deterministic. The built-in [random()] SQL function is an example of a
+** function that is not deterministic. The SQLite query planner is able to
+** perform additional optimizations on deterministic functions, so use
+** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
+**
+** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY]
+** flag, which if present prevents the function from being invoked from
+** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,
+** index expressions, or the WHERE clause of partial indexes.
+**
+** <span style="background-color:#ffff90;">
+** For best security, the [SQLITE_DIRECTONLY] flag is recommended for
+** all application-defined SQL functions that do not need to be
+** used inside of triggers, view, CHECK constraints, or other elements of
+** the database schema. This flags is especially recommended for SQL
+** functions that have side effects or reveal internal application state.
+** Without this flag, an attacker might be able to modify the schema of
+** a database file to include invocations of the function with parameters
+** chosen by the attacker, which the application will then execute when
+** the database file is opened and read.
+** </span>
+**
+** ^(The fifth parameter is an arbitrary pointer. The implementation of the
+** function can gain access to this pointer using [sqlite3_user_data()].)^
+**
+** ^The sixth, seventh and eighth parameters passed to the three
+** "sqlite3_create_function*" functions, xFunc, xStep and xFinal, are
+** pointers to C-language functions that implement the SQL function or
+** aggregate. ^A scalar SQL function requires an implementation of the xFunc
+** callback only; NULL pointers must be passed as the xStep and xFinal
+** parameters. ^An aggregate SQL function requires an implementation of xStep
+** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
+** SQL function or aggregate, pass NULL pointers for all three function
+** callbacks.
+**
+** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue
+** and xInverse) passed to sqlite3_create_window_function are pointers to
+** C-language callbacks that implement the new function. xStep and xFinal
+** must both be non-NULL. xValue and xInverse may either both be NULL, in
+** which case a regular aggregate function is created, or must both be
+** non-NULL, in which case the new function may be used as either an aggregate
+** or aggregate window function. More details regarding the implementation
+** of aggregate window functions are
+** [user-defined window functions|available here].
+**
+** ^(If the final parameter to sqlite3_create_function_v2() or
+** sqlite3_create_window_function() is not NULL, then it is destructor for
+** the application data pointer. The destructor is invoked when the function
+** is deleted, either by being overloaded or when the database connection
+** closes.)^ ^The destructor is also invoked if the call to
+** sqlite3_create_function_v2() fails. ^When the destructor callback is
+** invoked, it is passed a single argument which is a copy of the application
+** data pointer which was the fifth parameter to sqlite3_create_function_v2().
+**
+** ^It is permitted to register multiple implementations of the same
+** functions with the same name but with either differing numbers of
+** arguments or differing preferred text encodings. ^SQLite will use
+** the implementation that most closely matches the way in which the
+** SQL function is used. ^A function implementation with a non-negative
+** nArg parameter is a better match than a function implementation with
+** a negative nArg. ^A function where the preferred text encoding
+** matches the database encoding is a better
+** match than a function where the encoding is different.
+** ^A function where the encoding difference is between UTF16le and UTF16be
+** is a closer match than a function where the encoding difference is
+** between UTF8 and UTF16.
+**
+** ^Built-in functions may be overloaded by new application-defined functions.
+**
+** ^An application-defined function is permitted to call other
+** SQLite interfaces. However, such calls must not
+** close the database connection nor finalize or reset the prepared
+** statement in which the function is running.
+*/
+SQLITE_API int sqlite3_create_function(
+ sqlite3 *db,
+ const char *zFunctionName,
+ int nArg,
+ int eTextRep,
+ void *pApp,
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*)
+);
+SQLITE_API int sqlite3_create_function16(
+ sqlite3 *db,
+ const void *zFunctionName,
+ int nArg,
+ int eTextRep,
+ void *pApp,
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*)
+);
+SQLITE_API int sqlite3_create_function_v2(
+ sqlite3 *db,
+ const char *zFunctionName,
+ int nArg,
+ int eTextRep,
+ void *pApp,
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*),
+ void(*xDestroy)(void*)
+);
+SQLITE_API int sqlite3_create_window_function(
+ sqlite3 *db,
+ const char *zFunctionName,
+ int nArg,
+ int eTextRep,
+ void *pApp,
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*),
+ void (*xValue)(sqlite3_context*),
+ void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
+ void(*xDestroy)(void*)
+);
+
+/*
+** CAPI3REF: Text Encodings
+**
+** These constant define integer codes that represent the various
+** text encodings supported by SQLite.
+*/
+#define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
+#define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
+#define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
+#define SQLITE_UTF16 4 /* Use native byte order */
+#define SQLITE_ANY 5 /* Deprecated */
+#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
+
+/*
+** CAPI3REF: Function Flags
+**
+** These constants may be ORed together with the
+** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
+** to [sqlite3_create_function()], [sqlite3_create_function16()], or
+** [sqlite3_create_function_v2()].
+**
+** <dl>
+** [[SQLITE_DETERMINISTIC]] <dt>SQLITE_DETERMINISTIC</dt><dd>
+** The SQLITE_DETERMINISTIC flag means that the new function always gives
+** the same output when the input parameters are the same.
+** The [abs|abs() function] is deterministic, for example, but
+** [randomblob|randomblob()] is not. Functions must
+** be deterministic in order to be used in certain contexts such as
+** with the WHERE clause of [partial indexes] or in [generated columns].
+** SQLite might also optimize deterministic functions by factoring them
+** out of inner loops.
+** </dd>
+**
+** [[SQLITE_DIRECTONLY]] <dt>SQLITE_DIRECTONLY</dt><dd>
+** The SQLITE_DIRECTONLY flag means that the function may only be invoked
+** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in
+** schema structures such as [CHECK constraints], [DEFAULT clauses],
+** [expression indexes], [partial indexes], or [generated columns].
+** The SQLITE_DIRECTONLY flags is a security feature which is recommended
+** for all [application-defined SQL functions], and especially for functions
+** that have side-effects or that could potentially leak sensitive
+** information.
+** </dd>
+**
+** [[SQLITE_INNOCUOUS]] <dt>SQLITE_INNOCUOUS</dt><dd>
+** The SQLITE_INNOCUOUS flag means that the function is unlikely
+** to cause problems even if misused. An innocuous function should have
+** no side effects and should not depend on any values other than its
+** input parameters. The [abs|abs() function] is an example of an
+** innocuous function.
+** The [load_extension() SQL function] is not innocuous because of its
+** side effects.
+** <p> SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not
+** exactly the same. The [random|random() function] is an example of a
+** function that is innocuous but not deterministic.
+** <p>Some heightened security settings
+** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF])
+** disable the use of SQL functions inside views and triggers and in
+** schema structures such as [CHECK constraints], [DEFAULT clauses],
+** [expression indexes], [partial indexes], and [generated columns] unless
+** the function is tagged with SQLITE_INNOCUOUS. Most built-in functions
+** are innocuous. Developers are advised to avoid using the
+** SQLITE_INNOCUOUS flag for application-defined functions unless the
+** function has been carefully audited and found to be free of potentially
+** security-adverse side-effects and information-leaks.
+** </dd>
+**
+** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>
+** The SQLITE_SUBTYPE flag indicates to SQLite that a function may call
+** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.
+** Specifying this flag makes no difference for scalar or aggregate user
+** functions. However, if it is not specified for a user-defined window
+** function, then any sub-types belonging to arguments passed to the window
+** function may be discarded before the window function is called (i.e.
+** sqlite3_value_subtype() will always return 0).
+** </dd>
+** </dl>
+*/
+#define SQLITE_DETERMINISTIC 0x000000800
+#define SQLITE_DIRECTONLY 0x000080000
+#define SQLITE_SUBTYPE 0x000100000
+#define SQLITE_INNOCUOUS 0x000200000
+
+/*
+** CAPI3REF: Deprecated Functions
+** DEPRECATED
+**
+** These functions are [deprecated]. In order to maintain
+** backwards compatibility with older code, these functions continue
+** to be supported. However, new applications should avoid
+** the use of these functions. To encourage programmers to avoid
+** these functions, we will not explain what they do.
+*/
+#ifndef SQLITE_OMIT_DEPRECATED
+SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
+SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
+SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
+SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
+SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
+SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
+ void*,sqlite3_int64);
+#endif
+
+/*
+** CAPI3REF: Obtaining SQL Values
+** METHOD: sqlite3_value
+**
+** <b>Summary:</b>
+** <blockquote><table border=0 cellpadding=0 cellspacing=0>
+** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
+** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
+** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
+** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
+** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
+** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
+** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
+** the native byteorder
+** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
+** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
+** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
+** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
+** or a UTF-8 TEXT in bytes
+** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
+** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
+** TEXT in bytes
+** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
+** datatype of the value
+** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
+** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
+** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>
+** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE
+** against a virtual table.
+** <tr><td><b>sqlite3_value_frombind&nbsp;&nbsp;</b>
+** <td>&rarr;&nbsp;&nbsp;<td>True if value originated from a [bound parameter]
+** </table></blockquote>
+**
+** <b>Details:</b>
+**
+** These routines extract type, size, and content information from
+** [protected sqlite3_value] objects. Protected sqlite3_value objects
+** are used to pass parameter information into the functions that
+** implement [application-defined SQL functions] and [virtual tables].
+**
+** These routines work only with [protected sqlite3_value] objects.
+** Any attempt to use these routines on an [unprotected sqlite3_value]
+** is not threadsafe.
+**
+** ^These routines work just like the corresponding [column access functions]
+** except that these routines take a single [protected sqlite3_value] object
+** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
+**
+** ^The sqlite3_value_text16() interface extracts a UTF-16 string
+** in the native byte-order of the host machine. ^The
+** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
+** extract UTF-16 strings as big-endian and little-endian respectively.
+**
+** ^If [sqlite3_value] object V was initialized
+** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
+** and if X and Y are strings that compare equal according to strcmp(X,Y),
+** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise,
+** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
+** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
+**
+** ^(The sqlite3_value_type(V) interface returns the
+** [SQLITE_INTEGER | datatype code] for the initial datatype of the
+** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
+** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
+** Other interfaces might change the datatype for an sqlite3_value object.
+** For example, if the datatype is initially SQLITE_INTEGER and
+** sqlite3_value_text(V) is called to extract a text value for that
+** integer, then subsequent calls to sqlite3_value_type(V) might return
+** SQLITE_TEXT. Whether or not a persistent internal datatype conversion
+** occurs is undefined and may change from one release of SQLite to the next.
+**
+** ^(The sqlite3_value_numeric_type() interface attempts to apply
+** numeric affinity to the value. This means that an attempt is
+** made to convert the value to an integer or floating point. If
+** such a conversion is possible without loss of information (in other
+** words, if the value is a string that looks like a number)
+** then the conversion is performed. Otherwise no conversion occurs.
+** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
+**
+** ^Within the [xUpdate] method of a [virtual table], the
+** sqlite3_value_nochange(X) interface returns true if and only if
+** the column corresponding to X is unchanged by the UPDATE operation
+** that the xUpdate method call was invoked to implement and if
+** and the prior [xColumn] method call that was invoked to extracted
+** the value for that column returned without setting a result (probably
+** because it queried [sqlite3_vtab_nochange()] and found that the column
+** was unchanging). ^Within an [xUpdate] method, any value for which
+** sqlite3_value_nochange(X) is true will in all other respects appear
+** to be a NULL value. If sqlite3_value_nochange(X) is invoked anywhere other
+** than within an [xUpdate] method call for an UPDATE statement, then
+** the return value is arbitrary and meaningless.
+**
+** ^The sqlite3_value_frombind(X) interface returns non-zero if the
+** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()]
+** interfaces. ^If X comes from an SQL literal value, or a table column,
+** or an expression, then sqlite3_value_frombind(X) returns zero.
+**
+** Please pay particular attention to the fact that the pointer returned
+** from [sqlite3_value_blob()], [sqlite3_value_text()], or
+** [sqlite3_value_text16()] can be invalidated by a subsequent call to
+** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
+** or [sqlite3_value_text16()].
+**
+** These routines must be called from the same thread as
+** the SQL function that supplied the [sqlite3_value*] parameters.
+**
+** As long as the input parameter is correct, these routines can only
+** fail if an out-of-memory error occurs during a format conversion.
+** Only the following subset of interfaces are subject to out-of-memory
+** errors:
+**
+** <ul>
+** <li> sqlite3_value_blob()
+** <li> sqlite3_value_text()
+** <li> sqlite3_value_text16()
+** <li> sqlite3_value_text16le()
+** <li> sqlite3_value_text16be()
+** <li> sqlite3_value_bytes()
+** <li> sqlite3_value_bytes16()
+** </ul>
+**
+** If an out-of-memory error occurs, then the return value from these
+** routines is the same as if the column had contained an SQL NULL value.
+** Valid SQL NULL returns can be distinguished from out-of-memory errors
+** by invoking the [sqlite3_errcode()] immediately after the suspect
+** return value is obtained and before any
+** other SQLite interface is called on the same [database connection].
+*/
+SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
+SQLITE_API double sqlite3_value_double(sqlite3_value*);
+SQLITE_API int sqlite3_value_int(sqlite3_value*);
+SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
+SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
+SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
+SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
+SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
+SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
+SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
+SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
+SQLITE_API int sqlite3_value_type(sqlite3_value*);
+SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
+SQLITE_API int sqlite3_value_nochange(sqlite3_value*);
+SQLITE_API int sqlite3_value_frombind(sqlite3_value*);
+
+/*
+** CAPI3REF: Finding The Subtype Of SQL Values
+** METHOD: sqlite3_value
+**
+** The sqlite3_value_subtype(V) function returns the subtype for
+** an [application-defined SQL function] argument V. The subtype
+** information can be used to pass a limited amount of context from
+** one SQL function to another. Use the [sqlite3_result_subtype()]
+** routine to set the subtype for the return value of an SQL function.
+*/
+SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
+
+/*
+** CAPI3REF: Copy And Free SQL Values
+** METHOD: sqlite3_value
+**
+** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
+** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
+** is a [protected sqlite3_value] object even if the input is not.
+** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
+** memory allocation fails.
+**
+** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
+** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
+** then sqlite3_value_free(V) is a harmless no-op.
+*/
+SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
+SQLITE_API void sqlite3_value_free(sqlite3_value*);
+
+/*
+** CAPI3REF: Obtain Aggregate Function Context
+** METHOD: sqlite3_context
+**
+** Implementations of aggregate SQL functions use this
+** routine to allocate memory for storing their state.
+**
+** ^The first time the sqlite3_aggregate_context(C,N) routine is called
+** for a particular aggregate function, SQLite allocates
+** N bytes of memory, zeroes out that memory, and returns a pointer
+** to the new memory. ^On second and subsequent calls to
+** sqlite3_aggregate_context() for the same aggregate function instance,
+** the same buffer is returned. Sqlite3_aggregate_context() is normally
+** called once for each invocation of the xStep callback and then one
+** last time when the xFinal callback is invoked. ^(When no rows match
+** an aggregate query, the xStep() callback of the aggregate function
+** implementation is never called and xFinal() is called exactly once.
+** In those cases, sqlite3_aggregate_context() might be called for the
+** first time from within xFinal().)^
+**
+** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
+** when first called if N is less than or equal to zero or if a memory
+** allocate error occurs.
+**
+** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
+** determined by the N parameter on first successful call. Changing the
+** value of N in any subsequent call to sqlite3_aggregate_context() within
+** the same aggregate function instance will not resize the memory
+** allocation.)^ Within the xFinal callback, it is customary to set
+** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
+** pointless memory allocations occur.
+**
+** ^SQLite automatically frees the memory allocated by
+** sqlite3_aggregate_context() when the aggregate query concludes.
+**
+** The first parameter must be a copy of the
+** [sqlite3_context | SQL function context] that is the first parameter
+** to the xStep or xFinal callback routine that implements the aggregate
+** function.
+**
+** This routine must be called from the same thread in which
+** the aggregate SQL function is running.
+*/
+SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
+
+/*
+** CAPI3REF: User Data For Functions
+** METHOD: sqlite3_context
+**
+** ^The sqlite3_user_data() interface returns a copy of
+** the pointer that was the pUserData parameter (the 5th parameter)
+** of the [sqlite3_create_function()]
+** and [sqlite3_create_function16()] routines that originally
+** registered the application defined function.
+**
+** This routine must be called from the same thread in which
+** the application-defined function is running.
+*/
+SQLITE_API void *sqlite3_user_data(sqlite3_context*);
+
+/*
+** CAPI3REF: Database Connection For Functions
+** METHOD: sqlite3_context
+**
+** ^The sqlite3_context_db_handle() interface returns a copy of
+** the pointer to the [database connection] (the 1st parameter)
+** of the [sqlite3_create_function()]
+** and [sqlite3_create_function16()] routines that originally
+** registered the application defined function.
+*/
+SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
+
+/*
+** CAPI3REF: Function Auxiliary Data
+** METHOD: sqlite3_context
+**
+** These functions may be used by (non-aggregate) SQL functions to
+** associate metadata with argument values. If the same value is passed to
+** multiple invocations of the same SQL function during query execution, under
+** some circumstances the associated metadata may be preserved. An example
+** of where this might be useful is in a regular-expression matching
+** function. The compiled version of the regular expression can be stored as
+** metadata associated with the pattern string.
+** Then as long as the pattern string remains the same,
+** the compiled regular expression can be reused on multiple
+** invocations of the same function.
+**
+** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
+** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
+** value to the application-defined function. ^N is zero for the left-most
+** function argument. ^If there is no metadata
+** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
+** returns a NULL pointer.
+**
+** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
+** argument of the application-defined function. ^Subsequent
+** calls to sqlite3_get_auxdata(C,N) return P from the most recent
+** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
+** NULL if the metadata has been discarded.
+** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
+** SQLite will invoke the destructor function X with parameter P exactly
+** once, when the metadata is discarded.
+** SQLite is free to discard the metadata at any time, including: <ul>
+** <li> ^(when the corresponding function parameter changes)^, or
+** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
+** SQL statement)^, or
+** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
+** parameter)^, or
+** <li> ^(during the original sqlite3_set_auxdata() call when a memory
+** allocation error occurs.)^ </ul>
+**
+** Note the last bullet in particular. The destructor X in
+** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
+** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
+** should be called near the end of the function implementation and the
+** function implementation should not make any use of P after
+** sqlite3_set_auxdata() has been called.
+**
+** ^(In practice, metadata is preserved between function calls for
+** function parameters that are compile-time constants, including literal
+** values and [parameters] and expressions composed from the same.)^
+**
+** The value of the N parameter to these interfaces should be non-negative.
+** Future enhancements may make use of negative N values to define new
+** kinds of function caching behavior.
+**
+** These routines must be called from the same thread in which
+** the SQL function is running.
+*/
+SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
+SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
+
+
+/*
+** CAPI3REF: Constants Defining Special Destructor Behavior
+**
+** These are special values for the destructor that is passed in as the
+** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
+** argument is SQLITE_STATIC, it means that the content pointer is constant
+** and will never change. It does not need to be destroyed. ^The
+** SQLITE_TRANSIENT value means that the content will likely change in
+** the near future and that SQLite should make its own private copy of
+** the content before returning.
+**
+** The typedef is necessary to work around problems in certain
+** C++ compilers.
+*/
+typedef void (*sqlite3_destructor_type)(void*);
+#define SQLITE_STATIC ((sqlite3_destructor_type)0)
+#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
+
+/*
+** CAPI3REF: Setting The Result Of An SQL Function
+** METHOD: sqlite3_context
+**
+** These routines are used by the xFunc or xFinal callbacks that
+** implement SQL functions and aggregates. See
+** [sqlite3_create_function()] and [sqlite3_create_function16()]
+** for additional information.
+**
+** These functions work very much like the [parameter binding] family of
+** functions used to bind values to host parameters in prepared statements.
+** Refer to the [SQL parameter] documentation for additional information.
+**
+** ^The sqlite3_result_blob() interface sets the result from
+** an application-defined function to be the BLOB whose content is pointed
+** to by the second parameter and which is N bytes long where N is the
+** third parameter.
+**
+** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
+** interfaces set the result of the application-defined function to be
+** a BLOB containing all zero bytes and N bytes in size.
+**
+** ^The sqlite3_result_double() interface sets the result from
+** an application-defined function to be a floating point value specified
+** by its 2nd argument.
+**
+** ^The sqlite3_result_error() and sqlite3_result_error16() functions
+** cause the implemented SQL function to throw an exception.
+** ^SQLite uses the string pointed to by the
+** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
+** as the text of an error message. ^SQLite interprets the error
+** message string from sqlite3_result_error() as UTF-8. ^SQLite
+** interprets the string from sqlite3_result_error16() as UTF-16 using
+** the same [byte-order determination rules] as [sqlite3_bind_text16()].
+** ^If the third parameter to sqlite3_result_error()
+** or sqlite3_result_error16() is negative then SQLite takes as the error
+** message all text up through the first zero character.
+** ^If the third parameter to sqlite3_result_error() or
+** sqlite3_result_error16() is non-negative then SQLite takes that many
+** bytes (not characters) from the 2nd parameter as the error message.
+** ^The sqlite3_result_error() and sqlite3_result_error16()
+** routines make a private copy of the error message text before
+** they return. Hence, the calling function can deallocate or
+** modify the text after they return without harm.
+** ^The sqlite3_result_error_code() function changes the error code
+** returned by SQLite as a result of an error in a function. ^By default,
+** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
+** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
+**
+** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
+** error indicating that a string or BLOB is too long to represent.
+**
+** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
+** error indicating that a memory allocation failed.
+**
+** ^The sqlite3_result_int() interface sets the return value
+** of the application-defined function to be the 32-bit signed integer
+** value given in the 2nd argument.
+** ^The sqlite3_result_int64() interface sets the return value
+** of the application-defined function to be the 64-bit signed integer
+** value given in the 2nd argument.
+**
+** ^The sqlite3_result_null() interface sets the return value
+** of the application-defined function to be NULL.
+**
+** ^The sqlite3_result_text(), sqlite3_result_text16(),
+** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
+** set the return value of the application-defined function to be
+** a text string which is represented as UTF-8, UTF-16 native byte order,
+** UTF-16 little endian, or UTF-16 big endian, respectively.
+** ^The sqlite3_result_text64() interface sets the return value of an
+** application-defined function to be a text string in an encoding
+** specified by the fifth (and last) parameter, which must be one
+** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
+** ^SQLite takes the text result from the application from
+** the 2nd parameter of the sqlite3_result_text* interfaces.
+** ^If the 3rd parameter to the sqlite3_result_text* interfaces
+** is negative, then SQLite takes result text from the 2nd parameter
+** through the first zero character.
+** ^If the 3rd parameter to the sqlite3_result_text* interfaces
+** is non-negative, then as many bytes (not characters) of the text
+** pointed to by the 2nd parameter are taken as the application-defined
+** function result. If the 3rd parameter is non-negative, then it
+** must be the byte offset into the string where the NUL terminator would
+** appear if the string where NUL terminated. If any NUL characters occur
+** in the string at a byte offset that is less than the value of the 3rd
+** parameter, then the resulting string will contain embedded NULs and the
+** result of expressions operating on strings with embedded NULs is undefined.
+** ^If the 4th parameter to the sqlite3_result_text* interfaces
+** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
+** function as the destructor on the text or BLOB result when it has
+** finished using that result.
+** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
+** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
+** assumes that the text or BLOB result is in constant space and does not
+** copy the content of the parameter nor call a destructor on the content
+** when it has finished using that result.
+** ^If the 4th parameter to the sqlite3_result_text* interfaces
+** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
+** then SQLite makes a copy of the result into space obtained
+** from [sqlite3_malloc()] before it returns.
+**
+** ^For the sqlite3_result_text16(), sqlite3_result_text16le(), and
+** sqlite3_result_text16be() routines, and for sqlite3_result_text64()
+** when the encoding is not UTF8, if the input UTF16 begins with a
+** byte-order mark (BOM, U+FEFF) then the BOM is removed from the
+** string and the rest of the string is interpreted according to the
+** byte-order specified by the BOM. ^The byte-order specified by
+** the BOM at the beginning of the text overrides the byte-order
+** specified by the interface procedure. ^So, for example, if
+** sqlite3_result_text16le() is invoked with text that begins
+** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the
+** first two bytes of input are skipped and the remaining input
+** is interpreted as UTF16BE text.
+**
+** ^For UTF16 input text to the sqlite3_result_text16(),
+** sqlite3_result_text16be(), sqlite3_result_text16le(), and
+** sqlite3_result_text64() routines, if the text contains invalid
+** UTF16 characters, the invalid characters might be converted
+** into the unicode replacement character, U+FFFD.
+**
+** ^The sqlite3_result_value() interface sets the result of
+** the application-defined function to be a copy of the
+** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
+** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
+** so that the [sqlite3_value] specified in the parameter may change or
+** be deallocated after sqlite3_result_value() returns without harm.
+** ^A [protected sqlite3_value] object may always be used where an
+** [unprotected sqlite3_value] object is required, so either
+** kind of [sqlite3_value] object can be used with this interface.
+**
+** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
+** SQL NULL value, just like [sqlite3_result_null(C)], except that it
+** also associates the host-language pointer P or type T with that
+** NULL value such that the pointer can be retrieved within an
+** [application-defined SQL function] using [sqlite3_value_pointer()].
+** ^If the D parameter is not NULL, then it is a pointer to a destructor
+** for the P parameter. ^SQLite invokes D with P as its only argument
+** when SQLite is finished with P. The T parameter should be a static
+** string and preferably a string literal. The sqlite3_result_pointer()
+** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
+**
+** If these routines are called from within the different thread
+** than the one containing the application-defined function that received
+** the [sqlite3_context] pointer, the results are undefined.
+*/
+SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
+SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
+ sqlite3_uint64,void(*)(void*));
+SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
+SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
+SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
+SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
+SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
+SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
+SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
+SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
+SQLITE_API void sqlite3_result_null(sqlite3_context*);
+SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
+SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
+ void(*)(void*), unsigned char encoding);
+SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
+SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
+SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
+SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
+SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
+SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
+SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
+
+
+/*
+** CAPI3REF: Setting The Subtype Of An SQL Function
+** METHOD: sqlite3_context
+**
+** The sqlite3_result_subtype(C,T) function causes the subtype of
+** the result from the [application-defined SQL function] with
+** [sqlite3_context] C to be the value T. Only the lower 8 bits
+** of the subtype T are preserved in current versions of SQLite;
+** higher order bits are discarded.
+** The number of subtype bytes preserved by SQLite might increase
+** in future releases of SQLite.
+*/
+SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
+
+/*
+** CAPI3REF: Define New Collating Sequences
+** METHOD: sqlite3
+**
+** ^These functions add, remove, or modify a [collation] associated
+** with the [database connection] specified as the first argument.
+**
+** ^The name of the collation is a UTF-8 string
+** for sqlite3_create_collation() and sqlite3_create_collation_v2()
+** and a UTF-16 string in native byte order for sqlite3_create_collation16().
+** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
+** considered to be the same name.
+**
+** ^(The third argument (eTextRep) must be one of the constants:
+** <ul>
+** <li> [SQLITE_UTF8],
+** <li> [SQLITE_UTF16LE],
+** <li> [SQLITE_UTF16BE],
+** <li> [SQLITE_UTF16], or
+** <li> [SQLITE_UTF16_ALIGNED].
+** </ul>)^
+** ^The eTextRep argument determines the encoding of strings passed
+** to the collating function callback, xCompare.
+** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
+** force strings to be UTF16 with native byte order.
+** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
+** on an even byte address.
+**
+** ^The fourth argument, pArg, is an application data pointer that is passed
+** through as the first argument to the collating function callback.
+**
+** ^The fifth argument, xCompare, is a pointer to the collating function.
+** ^Multiple collating functions can be registered using the same name but
+** with different eTextRep parameters and SQLite will use whichever
+** function requires the least amount of data transformation.
+** ^If the xCompare argument is NULL then the collating function is
+** deleted. ^When all collating functions having the same name are deleted,
+** that collation is no longer usable.
+**
+** ^The collating function callback is invoked with a copy of the pArg
+** application data pointer and with two strings in the encoding specified
+** by the eTextRep argument. The two integer parameters to the collating
+** function callback are the length of the two strings, in bytes. The collating
+** function must return an integer that is negative, zero, or positive
+** if the first string is less than, equal to, or greater than the second,
+** respectively. A collating function must always return the same answer
+** given the same inputs. If two or more collating functions are registered
+** to the same collation name (using different eTextRep values) then all
+** must give an equivalent answer when invoked with equivalent strings.
+** The collating function must obey the following properties for all
+** strings A, B, and C:
+**
+** <ol>
+** <li> If A==B then B==A.
+** <li> If A==B and B==C then A==C.
+** <li> If A&lt;B THEN B&gt;A.
+** <li> If A&lt;B and B&lt;C then A&lt;C.
+** </ol>
+**
+** If a collating function fails any of the above constraints and that
+** collating function is registered and used, then the behavior of SQLite
+** is undefined.
+**
+** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
+** with the addition that the xDestroy callback is invoked on pArg when
+** the collating function is deleted.
+** ^Collating functions are deleted when they are overridden by later
+** calls to the collation creation functions or when the
+** [database connection] is closed using [sqlite3_close()].
+**
+** ^The xDestroy callback is <u>not</u> called if the
+** sqlite3_create_collation_v2() function fails. Applications that invoke
+** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
+** check the return code and dispose of the application data pointer
+** themselves rather than expecting SQLite to deal with it for them.
+** This is different from every other SQLite interface. The inconsistency
+** is unfortunate but cannot be changed without breaking backwards
+** compatibility.
+**
+** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
+*/
+SQLITE_API int sqlite3_create_collation(
+ sqlite3*,
+ const char *zName,
+ int eTextRep,
+ void *pArg,
+ int(*xCompare)(void*,int,const void*,int,const void*)
+);
+SQLITE_API int sqlite3_create_collation_v2(
+ sqlite3*,
+ const char *zName,
+ int eTextRep,
+ void *pArg,
+ int(*xCompare)(void*,int,const void*,int,const void*),
+ void(*xDestroy)(void*)
+);
+SQLITE_API int sqlite3_create_collation16(
+ sqlite3*,
+ const void *zName,
+ int eTextRep,
+ void *pArg,
+ int(*xCompare)(void*,int,const void*,int,const void*)
+);
+
+/*
+** CAPI3REF: Collation Needed Callbacks
+** METHOD: sqlite3
+**
+** ^To avoid having to register all collation sequences before a database
+** can be used, a single callback function may be registered with the
+** [database connection] to be invoked whenever an undefined collation
+** sequence is required.
+**
+** ^If the function is registered using the sqlite3_collation_needed() API,
+** then it is passed the names of undefined collation sequences as strings
+** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
+** the names are passed as UTF-16 in machine native byte order.
+** ^A call to either function replaces the existing collation-needed callback.
+**
+** ^(When the callback is invoked, the first argument passed is a copy
+** of the second argument to sqlite3_collation_needed() or
+** sqlite3_collation_needed16(). The second argument is the database
+** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
+** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
+** sequence function required. The fourth parameter is the name of the
+** required collation sequence.)^
+**
+** The callback function should register the desired collation using
+** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
+** [sqlite3_create_collation_v2()].
+*/
+SQLITE_API int sqlite3_collation_needed(
+ sqlite3*,
+ void*,
+ void(*)(void*,sqlite3*,int eTextRep,const char*)
+);
+SQLITE_API int sqlite3_collation_needed16(
+ sqlite3*,
+ void*,
+ void(*)(void*,sqlite3*,int eTextRep,const void*)
+);
+
+#ifdef SQLITE_ENABLE_CEROD
+/*
+** Specify the activation key for a CEROD database. Unless
+** activated, none of the CEROD routines will work.
+*/
+SQLITE_API void sqlite3_activate_cerod(
+ const char *zPassPhrase /* Activation phrase */
+);
+#endif
+
+/*
+** CAPI3REF: Suspend Execution For A Short Time
+**
+** The sqlite3_sleep() function causes the current thread to suspend execution
+** for at least a number of milliseconds specified in its parameter.
+**
+** If the operating system does not support sleep requests with
+** millisecond time resolution, then the time will be rounded up to
+** the nearest second. The number of milliseconds of sleep actually
+** requested from the operating system is returned.
+**
+** ^SQLite implements this interface by calling the xSleep()
+** method of the default [sqlite3_vfs] object. If the xSleep() method
+** of the default VFS is not implemented correctly, or not implemented at
+** all, then the behavior of sqlite3_sleep() may deviate from the description
+** in the previous paragraphs.
+*/
+SQLITE_API int sqlite3_sleep(int);
+
+/*
+** CAPI3REF: Name Of The Folder Holding Temporary Files
+**
+** ^(If this global variable is made to point to a string which is
+** the name of a folder (a.k.a. directory), then all temporary files
+** created by SQLite when using a built-in [sqlite3_vfs | VFS]
+** will be placed in that directory.)^ ^If this variable
+** is a NULL pointer, then SQLite performs a search for an appropriate
+** temporary file directory.
+**
+** Applications are strongly discouraged from using this global variable.
+** It is required to set a temporary folder on Windows Runtime (WinRT).
+** But for all other platforms, it is highly recommended that applications
+** neither read nor write this variable. This global variable is a relic
+** that exists for backwards compatibility of legacy applications and should
+** be avoided in new projects.
+**
+** It is not safe to read or modify this variable in more than one
+** thread at a time. It is not safe to read or modify this variable
+** if a [database connection] is being used at the same time in a separate
+** thread.
+** It is intended that this variable be set once
+** as part of process initialization and before any SQLite interface
+** routines have been called and that this variable remain unchanged
+** thereafter.
+**
+** ^The [temp_store_directory pragma] may modify this variable and cause
+** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
+** the [temp_store_directory pragma] always assumes that any string
+** that this variable points to is held in memory obtained from
+** [sqlite3_malloc] and the pragma may attempt to free that memory
+** using [sqlite3_free].
+** Hence, if this variable is modified directly, either it should be
+** made NULL or made to point to memory obtained from [sqlite3_malloc]
+** or else the use of the [temp_store_directory pragma] should be avoided.
+** Except when requested by the [temp_store_directory pragma], SQLite
+** does not free the memory that sqlite3_temp_directory points to. If
+** the application wants that memory to be freed, it must do
+** so itself, taking care to only do so after all [database connection]
+** objects have been destroyed.
+**
+** <b>Note to Windows Runtime users:</b> The temporary directory must be set
+** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
+** features that require the use of temporary files may fail. Here is an
+** example of how to do this using C++ with the Windows Runtime:
+**
+** <blockquote><pre>
+** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
+** &nbsp; TemporaryFolder->Path->Data();
+** char zPathBuf&#91;MAX_PATH + 1&#93;;
+** memset(zPathBuf, 0, sizeof(zPathBuf));
+** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
+** &nbsp; NULL, NULL);
+** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
+** </pre></blockquote>
+*/
+SQLITE_API SQLITE_EXTERN char *sqlite3_temp_directory;
+
+/*
+** CAPI3REF: Name Of The Folder Holding Database Files
+**
+** ^(If this global variable is made to point to a string which is
+** the name of a folder (a.k.a. directory), then all database files
+** specified with a relative pathname and created or accessed by
+** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
+** to be relative to that directory.)^ ^If this variable is a NULL
+** pointer, then SQLite assumes that all database files specified
+** with a relative pathname are relative to the current directory
+** for the process. Only the windows VFS makes use of this global
+** variable; it is ignored by the unix VFS.
+**
+** Changing the value of this variable while a database connection is
+** open can result in a corrupt database.
+**
+** It is not safe to read or modify this variable in more than one
+** thread at a time. It is not safe to read or modify this variable
+** if a [database connection] is being used at the same time in a separate
+** thread.
+** It is intended that this variable be set once
+** as part of process initialization and before any SQLite interface
+** routines have been called and that this variable remain unchanged
+** thereafter.
+**
+** ^The [data_store_directory pragma] may modify this variable and cause
+** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
+** the [data_store_directory pragma] always assumes that any string
+** that this variable points to is held in memory obtained from
+** [sqlite3_malloc] and the pragma may attempt to free that memory
+** using [sqlite3_free].
+** Hence, if this variable is modified directly, either it should be
+** made NULL or made to point to memory obtained from [sqlite3_malloc]
+** or else the use of the [data_store_directory pragma] should be avoided.
+*/
+SQLITE_API SQLITE_EXTERN char *sqlite3_data_directory;
+
+/*
+** CAPI3REF: Win32 Specific Interface
+**
+** These interfaces are available only on Windows. The
+** [sqlite3_win32_set_directory] interface is used to set the value associated
+** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to
+** zValue, depending on the value of the type parameter. The zValue parameter
+** should be NULL to cause the previous value to be freed via [sqlite3_free];
+** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
+** prior to being used. The [sqlite3_win32_set_directory] interface returns
+** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,
+** or [SQLITE_NOMEM] if memory could not be allocated. The value of the
+** [sqlite3_data_directory] variable is intended to act as a replacement for
+** the current directory on the sub-platforms of Win32 where that concept is
+** not present, e.g. WinRT and UWP. The [sqlite3_win32_set_directory8] and
+** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the
+** sqlite3_win32_set_directory interface except the string parameter must be
+** UTF-8 or UTF-16, respectively.
+*/
+SQLITE_API int sqlite3_win32_set_directory(
+ unsigned long type, /* Identifier for directory being set or reset */
+ void *zValue /* New value for directory being set or reset */
+);
+SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);
+SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);
+
+/*
+** CAPI3REF: Win32 Directory Types
+**
+** These macros are only available on Windows. They define the allowed values
+** for the type argument to the [sqlite3_win32_set_directory] interface.
+*/
+#define SQLITE_WIN32_DATA_DIRECTORY_TYPE 1
+#define SQLITE_WIN32_TEMP_DIRECTORY_TYPE 2
+
+/*
+** CAPI3REF: Test For Auto-Commit Mode
+** KEYWORDS: {autocommit mode}
+** METHOD: sqlite3
+**
+** ^The sqlite3_get_autocommit() interface returns non-zero or
+** zero if the given database connection is or is not in autocommit mode,
+** respectively. ^Autocommit mode is on by default.
+** ^Autocommit mode is disabled by a [BEGIN] statement.
+** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
+**
+** If certain kinds of errors occur on a statement within a multi-statement
+** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
+** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
+** transaction might be rolled back automatically. The only way to
+** find out whether SQLite automatically rolled back the transaction after
+** an error is to use this function.
+**
+** If another thread changes the autocommit status of the database
+** connection while this routine is running, then the return value
+** is undefined.
+*/
+SQLITE_API int sqlite3_get_autocommit(sqlite3*);
+
+/*
+** CAPI3REF: Find The Database Handle Of A Prepared Statement
+** METHOD: sqlite3_stmt
+**
+** ^The sqlite3_db_handle interface returns the [database connection] handle
+** to which a [prepared statement] belongs. ^The [database connection]
+** returned by sqlite3_db_handle is the same [database connection]
+** that was the first argument
+** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
+** create the statement in the first place.
+*/
+SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
+
+/*
+** CAPI3REF: Return The Filename For A Database Connection
+** METHOD: sqlite3
+**
+** ^The sqlite3_db_filename(D,N) interface returns a pointer to the filename
+** associated with database N of connection D.
+** ^If there is no attached database N on the database
+** connection D, or if database N is a temporary or in-memory database, then
+** this function will return either a NULL pointer or an empty string.
+**
+** ^The string value returned by this routine is owned and managed by
+** the database connection. ^The value will be valid until the database N
+** is [DETACH]-ed or until the database connection closes.
+**
+** ^The filename returned by this function is the output of the
+** xFullPathname method of the [VFS]. ^In other words, the filename
+** will be an absolute pathname, even if the filename used
+** to open the database originally was a URI or relative pathname.
+**
+** If the filename pointer returned by this routine is not NULL, then it
+** can be used as the filename input parameter to these routines:
+** <ul>
+** <li> [sqlite3_uri_parameter()]
+** <li> [sqlite3_uri_boolean()]
+** <li> [sqlite3_uri_int64()]
+** <li> [sqlite3_filename_database()]
+** <li> [sqlite3_filename_journal()]
+** <li> [sqlite3_filename_wal()]
+** </ul>
+*/
+SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
+
+/*
+** CAPI3REF: Determine if a database is read-only
+** METHOD: sqlite3
+**
+** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
+** of connection D is read-only, 0 if it is read/write, or -1 if N is not
+** the name of a database on connection D.
+*/
+SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
+
+/*
+** CAPI3REF: Determine the transaction state of a database
+** METHOD: sqlite3
+**
+** ^The sqlite3_txn_state(D,S) interface returns the current
+** [transaction state] of schema S in database connection D. ^If S is NULL,
+** then the highest transaction state of any schema on databse connection D
+** is returned. Transaction states are (in order of lowest to highest):
+** <ol>
+** <li value="0"> SQLITE_TXN_NONE
+** <li value="1"> SQLITE_TXN_READ
+** <li value="2"> SQLITE_TXN_WRITE
+** </ol>
+** ^If the S argument to sqlite3_txn_state(D,S) is not the name of
+** a valid schema, then -1 is returned.
+*/
+SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema);
+
+/*
+** CAPI3REF: Allowed return values from [sqlite3_txn_state()]
+** KEYWORDS: {transaction state}
+**
+** These constants define the current transaction state of a database file.
+** ^The [sqlite3_txn_state(D,S)] interface returns one of these
+** constants in order to describe the transaction state of schema S
+** in [database connection] D.
+**
+** <dl>
+** [[SQLITE_TXN_NONE]] <dt>SQLITE_TXN_NONE</dt>
+** <dd>The SQLITE_TXN_NONE state means that no transaction is currently
+** pending.</dd>
+**
+** [[SQLITE_TXN_READ]] <dt>SQLITE_TXN_READ</dt>
+** <dd>The SQLITE_TXN_READ state means that the database is currently
+** in a read transaction. Content has been read from the database file
+** but nothing in the database file has changed. The transaction state
+** will advanced to SQLITE_TXN_WRITE if any changes occur and there are
+** no other conflicting concurrent write transactions. The transaction
+** state will revert to SQLITE_TXN_NONE following a [ROLLBACK] or
+** [COMMIT].</dd>
+**
+** [[SQLITE_TXN_WRITE]] <dt>SQLITE_TXN_WRITE</dt>
+** <dd>The SQLITE_TXN_WRITE state means that the database is currently
+** in a write transaction. Content has been written to the database file
+** but has not yet committed. The transaction state will change to
+** to SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd>
+*/
+#define SQLITE_TXN_NONE 0
+#define SQLITE_TXN_READ 1
+#define SQLITE_TXN_WRITE 2
+
+/*
+** CAPI3REF: Find the next prepared statement
+** METHOD: sqlite3
+**
+** ^This interface returns a pointer to the next [prepared statement] after
+** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
+** then this interface returns a pointer to the first prepared statement
+** associated with the database connection pDb. ^If no prepared statement
+** satisfies the conditions of this routine, it returns NULL.
+**
+** The [database connection] pointer D in a call to
+** [sqlite3_next_stmt(D,S)] must refer to an open database
+** connection and in particular must not be a NULL pointer.
+*/
+SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
+
+/*
+** CAPI3REF: Commit And Rollback Notification Callbacks
+** METHOD: sqlite3
+**
+** ^The sqlite3_commit_hook() interface registers a callback
+** function to be invoked whenever a transaction is [COMMIT | committed].
+** ^Any callback set by a previous call to sqlite3_commit_hook()
+** for the same database connection is overridden.
+** ^The sqlite3_rollback_hook() interface registers a callback
+** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
+** ^Any callback set by a previous call to sqlite3_rollback_hook()
+** for the same database connection is overridden.
+** ^The pArg argument is passed through to the callback.
+** ^If the callback on a commit hook function returns non-zero,
+** then the commit is converted into a rollback.
+**
+** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
+** return the P argument from the previous call of the same function
+** on the same [database connection] D, or NULL for
+** the first call for each function on D.
+**
+** The commit and rollback hook callbacks are not reentrant.
+** The callback implementation must not do anything that will modify
+** the database connection that invoked the callback. Any actions
+** to modify the database connection must be deferred until after the
+** completion of the [sqlite3_step()] call that triggered the commit
+** or rollback hook in the first place.
+** Note that running any other SQL statements, including SELECT statements,
+** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
+** the database connections for the meaning of "modify" in this paragraph.
+**
+** ^Registering a NULL function disables the callback.
+**
+** ^When the commit hook callback routine returns zero, the [COMMIT]
+** operation is allowed to continue normally. ^If the commit hook
+** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
+** ^The rollback hook is invoked on a rollback that results from a commit
+** hook returning non-zero, just as it would be with any other rollback.
+**
+** ^For the purposes of this API, a transaction is said to have been
+** rolled back if an explicit "ROLLBACK" statement is executed, or
+** an error or constraint causes an implicit rollback to occur.
+** ^The rollback callback is not invoked if a transaction is
+** automatically rolled back because the database connection is closed.
+**
+** See also the [sqlite3_update_hook()] interface.
+*/
+SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
+SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
+
+/*
+** CAPI3REF: Data Change Notification Callbacks
+** METHOD: sqlite3
+**
+** ^The sqlite3_update_hook() interface registers a callback function
+** with the [database connection] identified by the first argument
+** to be invoked whenever a row is updated, inserted or deleted in
+** a [rowid table].
+** ^Any callback set by a previous call to this function
+** for the same database connection is overridden.
+**
+** ^The second argument is a pointer to the function to invoke when a
+** row is updated, inserted or deleted in a rowid table.
+** ^The first argument to the callback is a copy of the third argument
+** to sqlite3_update_hook().
+** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
+** or [SQLITE_UPDATE], depending on the operation that caused the callback
+** to be invoked.
+** ^The third and fourth arguments to the callback contain pointers to the
+** database and table name containing the affected row.
+** ^The final callback parameter is the [rowid] of the row.
+** ^In the case of an update, this is the [rowid] after the update takes place.
+**
+** ^(The update hook is not invoked when internal system tables are
+** modified (i.e. sqlite_sequence).)^
+** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
+**
+** ^In the current implementation, the update hook
+** is not invoked when conflicting rows are deleted because of an
+** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
+** invoked when rows are deleted using the [truncate optimization].
+** The exceptions defined in this paragraph might change in a future
+** release of SQLite.
+**
+** The update hook implementation must not do anything that will modify
+** the database connection that invoked the update hook. Any actions
+** to modify the database connection must be deferred until after the
+** completion of the [sqlite3_step()] call that triggered the update hook.
+** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
+** database connections for the meaning of "modify" in this paragraph.
+**
+** ^The sqlite3_update_hook(D,C,P) function
+** returns the P argument from the previous call
+** on the same [database connection] D, or NULL for
+** the first call on D.
+**
+** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
+** and [sqlite3_preupdate_hook()] interfaces.
+*/
+SQLITE_API void *sqlite3_update_hook(
+ sqlite3*,
+ void(*)(void *,int ,char const *,char const *,sqlite3_int64),
+ void*
+);
+
+/*
+** CAPI3REF: Enable Or Disable Shared Pager Cache
+**
+** ^(This routine enables or disables the sharing of the database cache
+** and schema data structures between [database connection | connections]
+** to the same database. Sharing is enabled if the argument is true
+** and disabled if the argument is false.)^
+**
+** ^Cache sharing is enabled and disabled for an entire process.
+** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
+** In prior versions of SQLite,
+** sharing was enabled or disabled for each thread separately.
+**
+** ^(The cache sharing mode set by this interface effects all subsequent
+** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
+** Existing database connections continue to use the sharing mode
+** that was in effect at the time they were opened.)^
+**
+** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
+** successfully. An [error code] is returned otherwise.)^
+**
+** ^Shared cache is disabled by default. It is recommended that it stay
+** that way. In other words, do not use this routine. This interface
+** continues to be provided for historical compatibility, but its use is
+** discouraged. Any use of shared cache is discouraged. If shared cache
+** must be used, it is recommended that shared cache only be enabled for
+** individual database connections using the [sqlite3_open_v2()] interface
+** with the [SQLITE_OPEN_SHAREDCACHE] flag.
+**
+** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
+** and will always return SQLITE_MISUSE. On those systems,
+** shared cache mode should be enabled per-database connection via
+** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
+**
+** This interface is threadsafe on processors where writing a
+** 32-bit integer is atomic.
+**
+** See Also: [SQLite Shared-Cache Mode]
+*/
+SQLITE_API int sqlite3_enable_shared_cache(int);
+
+/*
+** CAPI3REF: Attempt To Free Heap Memory
+**
+** ^The sqlite3_release_memory() interface attempts to free N bytes
+** of heap memory by deallocating non-essential memory allocations
+** held by the database library. Memory used to cache database
+** pages to improve performance is an example of non-essential memory.
+** ^sqlite3_release_memory() returns the number of bytes actually freed,
+** which might be more or less than the amount requested.
+** ^The sqlite3_release_memory() routine is a no-op returning zero
+** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
+**
+** See also: [sqlite3_db_release_memory()]
+*/
+SQLITE_API int sqlite3_release_memory(int);
+
+/*
+** CAPI3REF: Free Memory Used By A Database Connection
+** METHOD: sqlite3
+**
+** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
+** memory as possible from database connection D. Unlike the
+** [sqlite3_release_memory()] interface, this interface is in effect even
+** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
+** omitted.
+**
+** See also: [sqlite3_release_memory()]
+*/
+SQLITE_API int sqlite3_db_release_memory(sqlite3*);
+
+/*
+** CAPI3REF: Impose A Limit On Heap Size
+**
+** These interfaces impose limits on the amount of heap memory that will be
+** by all database connections within a single process.
+**
+** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
+** soft limit on the amount of heap memory that may be allocated by SQLite.
+** ^SQLite strives to keep heap memory utilization below the soft heap
+** limit by reducing the number of pages held in the page cache
+** as heap memory usages approaches the limit.
+** ^The soft heap limit is "soft" because even though SQLite strives to stay
+** below the limit, it will exceed the limit rather than generate
+** an [SQLITE_NOMEM] error. In other words, the soft heap limit
+** is advisory only.
+**
+** ^The sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of
+** N bytes on the amount of memory that will be allocated. ^The
+** sqlite3_hard_heap_limit64(N) interface is similar to
+** sqlite3_soft_heap_limit64(N) except that memory allocations will fail
+** when the hard heap limit is reached.
+**
+** ^The return value from both sqlite3_soft_heap_limit64() and
+** sqlite3_hard_heap_limit64() is the size of
+** the heap limit prior to the call, or negative in the case of an
+** error. ^If the argument N is negative
+** then no change is made to the heap limit. Hence, the current
+** size of heap limits can be determined by invoking
+** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1).
+**
+** ^Setting the heap limits to zero disables the heap limiter mechanism.
+**
+** ^The soft heap limit may not be greater than the hard heap limit.
+** ^If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N)
+** is invoked with a value of N that is greater than the hard heap limit,
+** the the soft heap limit is set to the value of the hard heap limit.
+** ^The soft heap limit is automatically enabled whenever the hard heap
+** limit is enabled. ^When sqlite3_hard_heap_limit64(N) is invoked and
+** the soft heap limit is outside the range of 1..N, then the soft heap
+** limit is set to N. ^Invoking sqlite3_soft_heap_limit64(0) when the
+** hard heap limit is enabled makes the soft heap limit equal to the
+** hard heap limit.
+**
+** The memory allocation limits can also be adjusted using
+** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit].
+**
+** ^(The heap limits are not enforced in the current implementation
+** if one or more of following conditions are true:
+**
+** <ul>
+** <li> The limit value is set to zero.
+** <li> Memory accounting is disabled using a combination of the
+** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
+** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
+** <li> An alternative page cache implementation is specified using
+** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
+** <li> The page cache allocates from its own memory pool supplied
+** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
+** from the heap.
+** </ul>)^
+**
+** The circumstances under which SQLite will enforce the heap limits may
+** changes in future releases of SQLite.
+*/
+SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
+SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N);
+
+/*
+** CAPI3REF: Deprecated Soft Heap Limit Interface
+** DEPRECATED
+**
+** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
+** interface. This routine is provided for historical compatibility
+** only. All new applications should use the
+** [sqlite3_soft_heap_limit64()] interface rather than this one.
+*/
+SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
+
+
+/*
+** CAPI3REF: Extract Metadata About A Column Of A Table
+** METHOD: sqlite3
+**
+** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
+** information about column C of table T in database D
+** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
+** interface returns SQLITE_OK and fills in the non-NULL pointers in
+** the final five arguments with appropriate values if the specified
+** column exists. ^The sqlite3_table_column_metadata() interface returns
+** SQLITE_ERROR if the specified column does not exist.
+** ^If the column-name parameter to sqlite3_table_column_metadata() is a
+** NULL pointer, then this routine simply checks for the existence of the
+** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
+** does not. If the table name parameter T in a call to
+** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
+** undefined behavior.
+**
+** ^The column is identified by the second, third and fourth parameters to
+** this function. ^(The second parameter is either the name of the database
+** (i.e. "main", "temp", or an attached database) containing the specified
+** table or NULL.)^ ^If it is NULL, then all attached databases are searched
+** for the table using the same algorithm used by the database engine to
+** resolve unqualified table references.
+**
+** ^The third and fourth parameters to this function are the table and column
+** name of the desired column, respectively.
+**
+** ^Metadata is returned by writing to the memory locations passed as the 5th
+** and subsequent parameters to this function. ^Any of these arguments may be
+** NULL, in which case the corresponding element of metadata is omitted.
+**
+** ^(<blockquote>
+** <table border="1">
+** <tr><th> Parameter <th> Output<br>Type <th> Description
+**
+** <tr><td> 5th <td> const char* <td> Data type
+** <tr><td> 6th <td> const char* <td> Name of default collation sequence
+** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
+** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
+** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
+** </table>
+** </blockquote>)^
+**
+** ^The memory pointed to by the character pointers returned for the
+** declaration type and collation sequence is valid until the next
+** call to any SQLite API function.
+**
+** ^If the specified table is actually a view, an [error code] is returned.
+**
+** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
+** is not a [WITHOUT ROWID] table and an
+** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
+** parameters are set for the explicitly declared column. ^(If there is no
+** [INTEGER PRIMARY KEY] column, then the outputs
+** for the [rowid] are set as follows:
+**
+** <pre>
+** data type: "INTEGER"
+** collation sequence: "BINARY"
+** not null: 0
+** primary key: 1
+** auto increment: 0
+** </pre>)^
+**
+** ^This function causes all database schemas to be read from disk and
+** parsed, if that has not already been done, and returns an error if
+** any errors are encountered while loading the schema.
+*/
+SQLITE_API int sqlite3_table_column_metadata(
+ sqlite3 *db, /* Connection handle */
+ const char *zDbName, /* Database name or NULL */
+ const char *zTableName, /* Table name */
+ const char *zColumnName, /* Column name */
+ char const **pzDataType, /* OUTPUT: Declared data type */
+ char const **pzCollSeq, /* OUTPUT: Collation sequence name */
+ int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
+ int *pPrimaryKey, /* OUTPUT: True if column part of PK */
+ int *pAutoinc /* OUTPUT: True if column is auto-increment */
+);
+
+/*
+** CAPI3REF: Load An Extension
+** METHOD: sqlite3
+**
+** ^This interface loads an SQLite extension library from the named file.
+**
+** ^The sqlite3_load_extension() interface attempts to load an
+** [SQLite extension] library contained in the file zFile. If
+** the file cannot be loaded directly, attempts are made to load
+** with various operating-system specific extensions added.
+** So for example, if "samplelib" cannot be loaded, then names like
+** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
+** be tried also.
+**
+** ^The entry point is zProc.
+** ^(zProc may be 0, in which case SQLite will try to come up with an
+** entry point name on its own. It first tries "sqlite3_extension_init".
+** If that does not work, it constructs a name "sqlite3_X_init" where the
+** X is consists of the lower-case equivalent of all ASCII alphabetic
+** characters in the filename from the last "/" to the first following
+** "." and omitting any initial "lib".)^
+** ^The sqlite3_load_extension() interface returns
+** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
+** ^If an error occurs and pzErrMsg is not 0, then the
+** [sqlite3_load_extension()] interface shall attempt to
+** fill *pzErrMsg with error message text stored in memory
+** obtained from [sqlite3_malloc()]. The calling function
+** should free this memory by calling [sqlite3_free()].
+**
+** ^Extension loading must be enabled using
+** [sqlite3_enable_load_extension()] or
+** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
+** prior to calling this API,
+** otherwise an error will be returned.
+**
+** <b>Security warning:</b> It is recommended that the
+** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
+** interface. The use of the [sqlite3_enable_load_extension()] interface
+** should be avoided. This will keep the SQL function [load_extension()]
+** disabled and prevent SQL injections from giving attackers
+** access to extension loading capabilities.
+**
+** See also the [load_extension() SQL function].
+*/
+SQLITE_API int sqlite3_load_extension(
+ sqlite3 *db, /* Load the extension into this database connection */
+ const char *zFile, /* Name of the shared library containing extension */
+ const char *zProc, /* Entry point. Derived from zFile if 0 */
+ char **pzErrMsg /* Put error message here if not 0 */
+);
+
+/*
+** CAPI3REF: Enable Or Disable Extension Loading
+** METHOD: sqlite3
+**
+** ^So as not to open security holes in older applications that are
+** unprepared to deal with [extension loading], and as a means of disabling
+** [extension loading] while evaluating user-entered SQL, the following API
+** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
+**
+** ^Extension loading is off by default.
+** ^Call the sqlite3_enable_load_extension() routine with onoff==1
+** to turn extension loading on and call it with onoff==0 to turn
+** it back off again.
+**
+** ^This interface enables or disables both the C-API
+** [sqlite3_load_extension()] and the SQL function [load_extension()].
+** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
+** to enable or disable only the C-API.)^
+**
+** <b>Security warning:</b> It is recommended that extension loading
+** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
+** rather than this interface, so the [load_extension()] SQL function
+** remains disabled. This will prevent SQL injections from giving attackers
+** access to extension loading capabilities.
+*/
+SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
+
+/*
+** CAPI3REF: Automatically Load Statically Linked Extensions
+**
+** ^This interface causes the xEntryPoint() function to be invoked for
+** each new [database connection] that is created. The idea here is that
+** xEntryPoint() is the entry point for a statically linked [SQLite extension]
+** that is to be automatically loaded into all new database connections.
+**
+** ^(Even though the function prototype shows that xEntryPoint() takes
+** no arguments and returns void, SQLite invokes xEntryPoint() with three
+** arguments and expects an integer result as if the signature of the
+** entry point where as follows:
+**
+** <blockquote><pre>
+** &nbsp; int xEntryPoint(
+** &nbsp; sqlite3 *db,
+** &nbsp; const char **pzErrMsg,
+** &nbsp; const struct sqlite3_api_routines *pThunk
+** &nbsp; );
+** </pre></blockquote>)^
+**
+** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
+** point to an appropriate error message (obtained from [sqlite3_mprintf()])
+** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
+** is NULL before calling the xEntryPoint(). ^SQLite will invoke
+** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
+** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
+** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
+**
+** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
+** on the list of automatic extensions is a harmless no-op. ^No entry point
+** will be called more than once for each database connection that is opened.
+**
+** See also: [sqlite3_reset_auto_extension()]
+** and [sqlite3_cancel_auto_extension()]
+*/
+SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
+
+/*
+** CAPI3REF: Cancel Automatic Extension Loading
+**
+** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
+** initialization routine X that was registered using a prior call to
+** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
+** routine returns 1 if initialization routine X was successfully
+** unregistered and it returns 0 if X was not on the list of initialization
+** routines.
+*/
+SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
+
+/*
+** CAPI3REF: Reset Automatic Extension Loading
+**
+** ^This interface disables all automatic extensions previously
+** registered using [sqlite3_auto_extension()].
+*/
+SQLITE_API void sqlite3_reset_auto_extension(void);
+
+/*
+** The interface to the virtual-table mechanism is currently considered
+** to be experimental. The interface might change in incompatible ways.
+** If this is a problem for you, do not use the interface at this time.
+**
+** When the virtual-table mechanism stabilizes, we will declare the
+** interface fixed, support it indefinitely, and remove this comment.
+*/
+
+/*
+** Structures used by the virtual table interface
+*/
+typedef struct sqlite3_vtab sqlite3_vtab;
+typedef struct sqlite3_index_info sqlite3_index_info;
+typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
+typedef struct sqlite3_module sqlite3_module;
+
+/*
+** CAPI3REF: Virtual Table Object
+** KEYWORDS: sqlite3_module {virtual table module}
+**
+** This structure, sometimes called a "virtual table module",
+** defines the implementation of a [virtual table].
+** This structure consists mostly of methods for the module.
+**
+** ^A virtual table module is created by filling in a persistent
+** instance of this structure and passing a pointer to that instance
+** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
+** ^The registration remains valid until it is replaced by a different
+** module or until the [database connection] closes. The content
+** of this structure must not change while it is registered with
+** any database connection.
+*/
+struct sqlite3_module {
+ int iVersion;
+ int (*xCreate)(sqlite3*, void *pAux,
+ int argc, const char *const*argv,
+ sqlite3_vtab **ppVTab, char**);
+ int (*xConnect)(sqlite3*, void *pAux,
+ int argc, const char *const*argv,
+ sqlite3_vtab **ppVTab, char**);
+ int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
+ int (*xDisconnect)(sqlite3_vtab *pVTab);
+ int (*xDestroy)(sqlite3_vtab *pVTab);
+ int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
+ int (*xClose)(sqlite3_vtab_cursor*);
+ int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
+ int argc, sqlite3_value **argv);
+ int (*xNext)(sqlite3_vtab_cursor*);
+ int (*xEof)(sqlite3_vtab_cursor*);
+ int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
+ int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
+ int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
+ int (*xBegin)(sqlite3_vtab *pVTab);
+ int (*xSync)(sqlite3_vtab *pVTab);
+ int (*xCommit)(sqlite3_vtab *pVTab);
+ int (*xRollback)(sqlite3_vtab *pVTab);
+ int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
+ void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
+ void **ppArg);
+ int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
+ /* The methods above are in version 1 of the sqlite_module object. Those
+ ** below are for version 2 and greater. */
+ int (*xSavepoint)(sqlite3_vtab *pVTab, int);
+ int (*xRelease)(sqlite3_vtab *pVTab, int);
+ int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
+ /* The methods above are in versions 1 and 2 of the sqlite_module object.
+ ** Those below are for version 3 and greater. */
+ int (*xShadowName)(const char*);
+};
+
+/*
+** CAPI3REF: Virtual Table Indexing Information
+** KEYWORDS: sqlite3_index_info
+**
+** The sqlite3_index_info structure and its substructures is used as part
+** of the [virtual table] interface to
+** pass information into and receive the reply from the [xBestIndex]
+** method of a [virtual table module]. The fields under **Inputs** are the
+** inputs to xBestIndex and are read-only. xBestIndex inserts its
+** results into the **Outputs** fields.
+**
+** ^(The aConstraint[] array records WHERE clause constraints of the form:
+**
+** <blockquote>column OP expr</blockquote>
+**
+** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
+** stored in aConstraint[].op using one of the
+** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
+** ^(The index of the column is stored in
+** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
+** expr on the right-hand side can be evaluated (and thus the constraint
+** is usable) and false if it cannot.)^
+**
+** ^The optimizer automatically inverts terms of the form "expr OP column"
+** and makes other simplifications to the WHERE clause in an attempt to
+** get as many WHERE clause terms into the form shown above as possible.
+** ^The aConstraint[] array only reports WHERE clause terms that are
+** relevant to the particular virtual table being queried.
+**
+** ^Information about the ORDER BY clause is stored in aOrderBy[].
+** ^Each term of aOrderBy records a column of the ORDER BY clause.
+**
+** The colUsed field indicates which columns of the virtual table may be
+** required by the current scan. Virtual table columns are numbered from
+** zero in the order in which they appear within the CREATE TABLE statement
+** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
+** the corresponding bit is set within the colUsed mask if the column may be
+** required by SQLite. If the table has at least 64 columns and any column
+** to the right of the first 63 is required, then bit 63 of colUsed is also
+** set. In other words, column iCol may be required if the expression
+** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
+** non-zero.
+**
+** The [xBestIndex] method must fill aConstraintUsage[] with information
+** about what parameters to pass to xFilter. ^If argvIndex>0 then
+** the right-hand side of the corresponding aConstraint[] is evaluated
+** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
+** is true, then the constraint is assumed to be fully handled by the
+** virtual table and might not be checked again by the byte code.)^ ^(The
+** aConstraintUsage[].omit flag is an optimization hint. When the omit flag
+** is left in its default setting of false, the constraint will always be
+** checked separately in byte code. If the omit flag is change to true, then
+** the constraint may or may not be checked in byte code. In other words,
+** when the omit flag is true there is no guarantee that the constraint will
+** not be checked again using byte code.)^
+**
+** ^The idxNum and idxPtr values are recorded and passed into the
+** [xFilter] method.
+** ^[sqlite3_free()] is used to free idxPtr if and only if
+** needToFreeIdxPtr is true.
+**
+** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
+** the correct order to satisfy the ORDER BY clause so that no separate
+** sorting step is required.
+**
+** ^The estimatedCost value is an estimate of the cost of a particular
+** strategy. A cost of N indicates that the cost of the strategy is similar
+** to a linear scan of an SQLite table with N rows. A cost of log(N)
+** indicates that the expense of the operation is similar to that of a
+** binary search on a unique indexed field of an SQLite table with N rows.
+**
+** ^The estimatedRows value is an estimate of the number of rows that
+** will be returned by the strategy.
+**
+** The xBestIndex method may optionally populate the idxFlags field with a
+** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
+** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
+** assumes that the strategy may visit at most one row.
+**
+** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
+** SQLite also assumes that if a call to the xUpdate() method is made as
+** part of the same statement to delete or update a virtual table row and the
+** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
+** any database changes. In other words, if the xUpdate() returns
+** SQLITE_CONSTRAINT, the database contents must be exactly as they were
+** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
+** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
+** the xUpdate method are automatically rolled back by SQLite.
+**
+** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
+** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
+** If a virtual table extension is
+** used with an SQLite version earlier than 3.8.2, the results of attempting
+** to read or write the estimatedRows field are undefined (but are likely
+** to include crashing the application). The estimatedRows field should
+** therefore only be used if [sqlite3_libversion_number()] returns a
+** value greater than or equal to 3008002. Similarly, the idxFlags field
+** was added for [version 3.9.0] ([dateof:3.9.0]).
+** It may therefore only be used if
+** sqlite3_libversion_number() returns a value greater than or equal to
+** 3009000.
+*/
+struct sqlite3_index_info {
+ /* Inputs */
+ int nConstraint; /* Number of entries in aConstraint */
+ struct sqlite3_index_constraint {
+ int iColumn; /* Column constrained. -1 for ROWID */
+ unsigned char op; /* Constraint operator */
+ unsigned char usable; /* True if this constraint is usable */
+ int iTermOffset; /* Used internally - xBestIndex should ignore */
+ } *aConstraint; /* Table of WHERE clause constraints */
+ int nOrderBy; /* Number of terms in the ORDER BY clause */
+ struct sqlite3_index_orderby {
+ int iColumn; /* Column number */
+ unsigned char desc; /* True for DESC. False for ASC. */
+ } *aOrderBy; /* The ORDER BY clause */
+ /* Outputs */
+ struct sqlite3_index_constraint_usage {
+ int argvIndex; /* if >0, constraint is part of argv to xFilter */
+ unsigned char omit; /* Do not code a test for this constraint */
+ } *aConstraintUsage;
+ int idxNum; /* Number used to identify the index */
+ char *idxStr; /* String, possibly obtained from sqlite3_malloc */
+ int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
+ int orderByConsumed; /* True if output is already ordered */
+ double estimatedCost; /* Estimated cost of using this index */
+ /* Fields below are only available in SQLite 3.8.2 and later */
+ sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
+ /* Fields below are only available in SQLite 3.9.0 and later */
+ int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
+ /* Fields below are only available in SQLite 3.10.0 and later */
+ sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
+};
+
+/*
+** CAPI3REF: Virtual Table Scan Flags
+**
+** Virtual table implementations are allowed to set the
+** [sqlite3_index_info].idxFlags field to some combination of
+** these bits.
+*/
+#define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
+
+/*
+** CAPI3REF: Virtual Table Constraint Operator Codes
+**
+** These macros define the allowed values for the
+** [sqlite3_index_info].aConstraint[].op field. Each value represents
+** an operator that is part of a constraint term in the wHERE clause of
+** a query that uses a [virtual table].
+*/
+#define SQLITE_INDEX_CONSTRAINT_EQ 2
+#define SQLITE_INDEX_CONSTRAINT_GT 4
+#define SQLITE_INDEX_CONSTRAINT_LE 8
+#define SQLITE_INDEX_CONSTRAINT_LT 16
+#define SQLITE_INDEX_CONSTRAINT_GE 32
+#define SQLITE_INDEX_CONSTRAINT_MATCH 64
+#define SQLITE_INDEX_CONSTRAINT_LIKE 65
+#define SQLITE_INDEX_CONSTRAINT_GLOB 66
+#define SQLITE_INDEX_CONSTRAINT_REGEXP 67
+#define SQLITE_INDEX_CONSTRAINT_NE 68
+#define SQLITE_INDEX_CONSTRAINT_ISNOT 69
+#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
+#define SQLITE_INDEX_CONSTRAINT_ISNULL 71
+#define SQLITE_INDEX_CONSTRAINT_IS 72
+#define SQLITE_INDEX_CONSTRAINT_FUNCTION 150
+
+/*
+** CAPI3REF: Register A Virtual Table Implementation
+** METHOD: sqlite3
+**
+** ^These routines are used to register a new [virtual table module] name.
+** ^Module names must be registered before
+** creating a new [virtual table] using the module and before using a
+** preexisting [virtual table] for the module.
+**
+** ^The module name is registered on the [database connection] specified
+** by the first parameter. ^The name of the module is given by the
+** second parameter. ^The third parameter is a pointer to
+** the implementation of the [virtual table module]. ^The fourth
+** parameter is an arbitrary client data pointer that is passed through
+** into the [xCreate] and [xConnect] methods of the virtual table module
+** when a new virtual table is be being created or reinitialized.
+**
+** ^The sqlite3_create_module_v2() interface has a fifth parameter which
+** is a pointer to a destructor for the pClientData. ^SQLite will
+** invoke the destructor function (if it is not NULL) when SQLite
+** no longer needs the pClientData pointer. ^The destructor will also
+** be invoked if the call to sqlite3_create_module_v2() fails.
+** ^The sqlite3_create_module()
+** interface is equivalent to sqlite3_create_module_v2() with a NULL
+** destructor.
+**
+** ^If the third parameter (the pointer to the sqlite3_module object) is
+** NULL then no new module is create and any existing modules with the
+** same name are dropped.
+**
+** See also: [sqlite3_drop_modules()]
+*/
+SQLITE_API int sqlite3_create_module(
+ sqlite3 *db, /* SQLite connection to register module with */
+ const char *zName, /* Name of the module */
+ const sqlite3_module *p, /* Methods for the module */
+ void *pClientData /* Client data for xCreate/xConnect */
+);
+SQLITE_API int sqlite3_create_module_v2(
+ sqlite3 *db, /* SQLite connection to register module with */
+ const char *zName, /* Name of the module */
+ const sqlite3_module *p, /* Methods for the module */
+ void *pClientData, /* Client data for xCreate/xConnect */
+ void(*xDestroy)(void*) /* Module destructor function */
+);
+
+/*
+** CAPI3REF: Remove Unnecessary Virtual Table Implementations
+** METHOD: sqlite3
+**
+** ^The sqlite3_drop_modules(D,L) interface removes all virtual
+** table modules from database connection D except those named on list L.
+** The L parameter must be either NULL or a pointer to an array of pointers
+** to strings where the array is terminated by a single NULL pointer.
+** ^If the L parameter is NULL, then all virtual table modules are removed.
+**
+** See also: [sqlite3_create_module()]
+*/
+SQLITE_API int sqlite3_drop_modules(
+ sqlite3 *db, /* Remove modules from this connection */
+ const char **azKeep /* Except, do not remove the ones named here */
+);
+
+/*
+** CAPI3REF: Virtual Table Instance Object
+** KEYWORDS: sqlite3_vtab
+**
+** Every [virtual table module] implementation uses a subclass
+** of this object to describe a particular instance
+** of the [virtual table]. Each subclass will
+** be tailored to the specific needs of the module implementation.
+** The purpose of this superclass is to define certain fields that are
+** common to all module implementations.
+**
+** ^Virtual tables methods can set an error message by assigning a
+** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
+** take care that any prior string is freed by a call to [sqlite3_free()]
+** prior to assigning a new string to zErrMsg. ^After the error message
+** is delivered up to the client application, the string will be automatically
+** freed by sqlite3_free() and the zErrMsg field will be zeroed.
+*/
+struct sqlite3_vtab {
+ const sqlite3_module *pModule; /* The module for this virtual table */
+ int nRef; /* Number of open cursors */
+ char *zErrMsg; /* Error message from sqlite3_mprintf() */
+ /* Virtual table implementations will typically add additional fields */
+};
+
+/*
+** CAPI3REF: Virtual Table Cursor Object
+** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
+**
+** Every [virtual table module] implementation uses a subclass of the
+** following structure to describe cursors that point into the
+** [virtual table] and are used
+** to loop through the virtual table. Cursors are created using the
+** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
+** by the [sqlite3_module.xClose | xClose] method. Cursors are used
+** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
+** of the module. Each module implementation will define
+** the content of a cursor structure to suit its own needs.
+**
+** This superclass exists in order to define fields of the cursor that
+** are common to all implementations.
+*/
+struct sqlite3_vtab_cursor {
+ sqlite3_vtab *pVtab; /* Virtual table of this cursor */
+ /* Virtual table implementations will typically add additional fields */
+};
+
+/*
+** CAPI3REF: Declare The Schema Of A Virtual Table
+**
+** ^The [xCreate] and [xConnect] methods of a
+** [virtual table module] call this interface
+** to declare the format (the names and datatypes of the columns) of
+** the virtual tables they implement.
+*/
+SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
+
+/*
+** CAPI3REF: Overload A Function For A Virtual Table
+** METHOD: sqlite3
+**
+** ^(Virtual tables can provide alternative implementations of functions
+** using the [xFindFunction] method of the [virtual table module].
+** But global versions of those functions
+** must exist in order to be overloaded.)^
+**
+** ^(This API makes sure a global version of a function with a particular
+** name and number of parameters exists. If no such function exists
+** before this API is called, a new function is created.)^ ^The implementation
+** of the new function always causes an exception to be thrown. So
+** the new function is not good for anything by itself. Its only
+** purpose is to be a placeholder function that can be overloaded
+** by a [virtual table].
+*/
+SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
+
+/*
+** The interface to the virtual-table mechanism defined above (back up
+** to a comment remarkably similar to this one) is currently considered
+** to be experimental. The interface might change in incompatible ways.
+** If this is a problem for you, do not use the interface at this time.
+**
+** When the virtual-table mechanism stabilizes, we will declare the
+** interface fixed, support it indefinitely, and remove this comment.
+*/
+
+/*
+** CAPI3REF: A Handle To An Open BLOB
+** KEYWORDS: {BLOB handle} {BLOB handles}
+**
+** An instance of this object represents an open BLOB on which
+** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
+** ^Objects of this type are created by [sqlite3_blob_open()]
+** and destroyed by [sqlite3_blob_close()].
+** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
+** can be used to read or write small subsections of the BLOB.
+** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
+*/
+typedef struct sqlite3_blob sqlite3_blob;
+
+/*
+** CAPI3REF: Open A BLOB For Incremental I/O
+** METHOD: sqlite3
+** CONSTRUCTOR: sqlite3_blob
+**
+** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
+** in row iRow, column zColumn, table zTable in database zDb;
+** in other words, the same BLOB that would be selected by:
+**
+** <pre>
+** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
+** </pre>)^
+**
+** ^(Parameter zDb is not the filename that contains the database, but
+** rather the symbolic name of the database. For attached databases, this is
+** the name that appears after the AS keyword in the [ATTACH] statement.
+** For the main database file, the database name is "main". For TEMP
+** tables, the database name is "temp".)^
+**
+** ^If the flags parameter is non-zero, then the BLOB is opened for read
+** and write access. ^If the flags parameter is zero, the BLOB is opened for
+** read-only access.
+**
+** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
+** in *ppBlob. Otherwise an [error code] is returned and, unless the error
+** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
+** the API is not misused, it is always safe to call [sqlite3_blob_close()]
+** on *ppBlob after this function it returns.
+**
+** This function fails with SQLITE_ERROR if any of the following are true:
+** <ul>
+** <li> ^(Database zDb does not exist)^,
+** <li> ^(Table zTable does not exist within database zDb)^,
+** <li> ^(Table zTable is a WITHOUT ROWID table)^,
+** <li> ^(Column zColumn does not exist)^,
+** <li> ^(Row iRow is not present in the table)^,
+** <li> ^(The specified column of row iRow contains a value that is not
+** a TEXT or BLOB value)^,
+** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
+** constraint and the blob is being opened for read/write access)^,
+** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
+** column zColumn is part of a [child key] definition and the blob is
+** being opened for read/write access)^.
+** </ul>
+**
+** ^Unless it returns SQLITE_MISUSE, this function sets the
+** [database connection] error code and message accessible via
+** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
+**
+** A BLOB referenced by sqlite3_blob_open() may be read using the
+** [sqlite3_blob_read()] interface and modified by using
+** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
+** different row of the same table using the [sqlite3_blob_reopen()]
+** interface. However, the column, table, or database of a [BLOB handle]
+** cannot be changed after the [BLOB handle] is opened.
+**
+** ^(If the row that a BLOB handle points to is modified by an
+** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
+** then the BLOB handle is marked as "expired".
+** This is true if any column of the row is changed, even a column
+** other than the one the BLOB handle is open on.)^
+** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
+** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
+** ^(Changes written into a BLOB prior to the BLOB expiring are not
+** rolled back by the expiration of the BLOB. Such changes will eventually
+** commit if the transaction continues to completion.)^
+**
+** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
+** the opened blob. ^The size of a blob may not be changed by this
+** interface. Use the [UPDATE] SQL command to change the size of a
+** blob.
+**
+** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
+** and the built-in [zeroblob] SQL function may be used to create a
+** zero-filled blob to read or write using the incremental-blob interface.
+**
+** To avoid a resource leak, every open [BLOB handle] should eventually
+** be released by a call to [sqlite3_blob_close()].
+**
+** See also: [sqlite3_blob_close()],
+** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
+** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
+*/
+SQLITE_API int sqlite3_blob_open(
+ sqlite3*,
+ const char *zDb,
+ const char *zTable,
+ const char *zColumn,
+ sqlite3_int64 iRow,
+ int flags,
+ sqlite3_blob **ppBlob
+);
+
+/*
+** CAPI3REF: Move a BLOB Handle to a New Row
+** METHOD: sqlite3_blob
+**
+** ^This function is used to move an existing [BLOB handle] so that it points
+** to a different row of the same database table. ^The new row is identified
+** by the rowid value passed as the second argument. Only the row can be
+** changed. ^The database, table and column on which the blob handle is open
+** remain the same. Moving an existing [BLOB handle] to a new row is
+** faster than closing the existing handle and opening a new one.
+**
+** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
+** it must exist and there must be either a blob or text value stored in
+** the nominated column.)^ ^If the new row is not present in the table, or if
+** it does not contain a blob or text value, or if another error occurs, an
+** SQLite error code is returned and the blob handle is considered aborted.
+** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
+** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
+** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
+** always returns zero.
+**
+** ^This function sets the database handle error code and message.
+*/
+SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
+
+/*
+** CAPI3REF: Close A BLOB Handle
+** DESTRUCTOR: sqlite3_blob
+**
+** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
+** unconditionally. Even if this routine returns an error code, the
+** handle is still closed.)^
+**
+** ^If the blob handle being closed was opened for read-write access, and if
+** the database is in auto-commit mode and there are no other open read-write
+** blob handles or active write statements, the current transaction is
+** committed. ^If an error occurs while committing the transaction, an error
+** code is returned and the transaction rolled back.
+**
+** Calling this function with an argument that is not a NULL pointer or an
+** open blob handle results in undefined behaviour. ^Calling this routine
+** with a null pointer (such as would be returned by a failed call to
+** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
+** is passed a valid open blob handle, the values returned by the
+** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
+*/
+SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
+
+/*
+** CAPI3REF: Return The Size Of An Open BLOB
+** METHOD: sqlite3_blob
+**
+** ^Returns the size in bytes of the BLOB accessible via the
+** successfully opened [BLOB handle] in its only argument. ^The
+** incremental blob I/O routines can only read or overwriting existing
+** blob content; they cannot change the size of a blob.
+**
+** This routine only works on a [BLOB handle] which has been created
+** by a prior successful call to [sqlite3_blob_open()] and which has not
+** been closed by [sqlite3_blob_close()]. Passing any other pointer in
+** to this routine results in undefined and probably undesirable behavior.
+*/
+SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
+
+/*
+** CAPI3REF: Read Data From A BLOB Incrementally
+** METHOD: sqlite3_blob
+**
+** ^(This function is used to read data from an open [BLOB handle] into a
+** caller-supplied buffer. N bytes of data are copied into buffer Z
+** from the open BLOB, starting at offset iOffset.)^
+**
+** ^If offset iOffset is less than N bytes from the end of the BLOB,
+** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
+** less than zero, [SQLITE_ERROR] is returned and no data is read.
+** ^The size of the blob (and hence the maximum value of N+iOffset)
+** can be determined using the [sqlite3_blob_bytes()] interface.
+**
+** ^An attempt to read from an expired [BLOB handle] fails with an
+** error code of [SQLITE_ABORT].
+**
+** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
+** Otherwise, an [error code] or an [extended error code] is returned.)^
+**
+** This routine only works on a [BLOB handle] which has been created
+** by a prior successful call to [sqlite3_blob_open()] and which has not
+** been closed by [sqlite3_blob_close()]. Passing any other pointer in
+** to this routine results in undefined and probably undesirable behavior.
+**
+** See also: [sqlite3_blob_write()].
+*/
+SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
+
+/*
+** CAPI3REF: Write Data Into A BLOB Incrementally
+** METHOD: sqlite3_blob
+**
+** ^(This function is used to write data into an open [BLOB handle] from a
+** caller-supplied buffer. N bytes of data are copied from the buffer Z
+** into the open BLOB, starting at offset iOffset.)^
+**
+** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
+** Otherwise, an [error code] or an [extended error code] is returned.)^
+** ^Unless SQLITE_MISUSE is returned, this function sets the
+** [database connection] error code and message accessible via
+** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
+**
+** ^If the [BLOB handle] passed as the first argument was not opened for
+** writing (the flags parameter to [sqlite3_blob_open()] was zero),
+** this function returns [SQLITE_READONLY].
+**
+** This function may only modify the contents of the BLOB; it is
+** not possible to increase the size of a BLOB using this API.
+** ^If offset iOffset is less than N bytes from the end of the BLOB,
+** [SQLITE_ERROR] is returned and no data is written. The size of the
+** BLOB (and hence the maximum value of N+iOffset) can be determined
+** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
+** than zero [SQLITE_ERROR] is returned and no data is written.
+**
+** ^An attempt to write to an expired [BLOB handle] fails with an
+** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
+** before the [BLOB handle] expired are not rolled back by the
+** expiration of the handle, though of course those changes might
+** have been overwritten by the statement that expired the BLOB handle
+** or by other independent statements.
+**
+** This routine only works on a [BLOB handle] which has been created
+** by a prior successful call to [sqlite3_blob_open()] and which has not
+** been closed by [sqlite3_blob_close()]. Passing any other pointer in
+** to this routine results in undefined and probably undesirable behavior.
+**
+** See also: [sqlite3_blob_read()].
+*/
+SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
+
+/*
+** CAPI3REF: Virtual File System Objects
+**
+** A virtual filesystem (VFS) is an [sqlite3_vfs] object
+** that SQLite uses to interact
+** with the underlying operating system. Most SQLite builds come with a
+** single default VFS that is appropriate for the host computer.
+** New VFSes can be registered and existing VFSes can be unregistered.
+** The following interfaces are provided.
+**
+** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
+** ^Names are case sensitive.
+** ^Names are zero-terminated UTF-8 strings.
+** ^If there is no match, a NULL pointer is returned.
+** ^If zVfsName is NULL then the default VFS is returned.
+**
+** ^New VFSes are registered with sqlite3_vfs_register().
+** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
+** ^The same VFS can be registered multiple times without injury.
+** ^To make an existing VFS into the default VFS, register it again
+** with the makeDflt flag set. If two different VFSes with the
+** same name are registered, the behavior is undefined. If a
+** VFS is registered with a name that is NULL or an empty string,
+** then the behavior is undefined.
+**
+** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
+** ^(If the default VFS is unregistered, another VFS is chosen as
+** the default. The choice for the new VFS is arbitrary.)^
+*/
+SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
+SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
+SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
+
+/*
+** CAPI3REF: Mutexes
+**
+** The SQLite core uses these routines for thread
+** synchronization. Though they are intended for internal
+** use by SQLite, code that links against SQLite is
+** permitted to use any of these routines.
+**
+** The SQLite source code contains multiple implementations
+** of these mutex routines. An appropriate implementation
+** is selected automatically at compile-time. The following
+** implementations are available in the SQLite core:
+**
+** <ul>
+** <li> SQLITE_MUTEX_PTHREADS
+** <li> SQLITE_MUTEX_W32
+** <li> SQLITE_MUTEX_NOOP
+** </ul>
+**
+** The SQLITE_MUTEX_NOOP implementation is a set of routines
+** that does no real locking and is appropriate for use in
+** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
+** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
+** and Windows.
+**
+** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
+** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
+** implementation is included with the library. In this case the
+** application must supply a custom mutex implementation using the
+** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
+** before calling sqlite3_initialize() or any other public sqlite3_
+** function that calls sqlite3_initialize().
+**
+** ^The sqlite3_mutex_alloc() routine allocates a new
+** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
+** routine returns NULL if it is unable to allocate the requested
+** mutex. The argument to sqlite3_mutex_alloc() must one of these
+** integer constants:
+**
+** <ul>
+** <li> SQLITE_MUTEX_FAST
+** <li> SQLITE_MUTEX_RECURSIVE
+** <li> SQLITE_MUTEX_STATIC_MAIN
+** <li> SQLITE_MUTEX_STATIC_MEM
+** <li> SQLITE_MUTEX_STATIC_OPEN
+** <li> SQLITE_MUTEX_STATIC_PRNG
+** <li> SQLITE_MUTEX_STATIC_LRU
+** <li> SQLITE_MUTEX_STATIC_PMEM
+** <li> SQLITE_MUTEX_STATIC_APP1
+** <li> SQLITE_MUTEX_STATIC_APP2
+** <li> SQLITE_MUTEX_STATIC_APP3
+** <li> SQLITE_MUTEX_STATIC_VFS1
+** <li> SQLITE_MUTEX_STATIC_VFS2
+** <li> SQLITE_MUTEX_STATIC_VFS3
+** </ul>
+**
+** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
+** cause sqlite3_mutex_alloc() to create
+** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
+** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
+** The mutex implementation does not need to make a distinction
+** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
+** not want to. SQLite will only request a recursive mutex in
+** cases where it really needs one. If a faster non-recursive mutex
+** implementation is available on the host platform, the mutex subsystem
+** might return such a mutex in response to SQLITE_MUTEX_FAST.
+**
+** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
+** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
+** a pointer to a static preexisting mutex. ^Nine static mutexes are
+** used by the current version of SQLite. Future versions of SQLite
+** may add additional static mutexes. Static mutexes are for internal
+** use by SQLite only. Applications that use SQLite mutexes should
+** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
+** SQLITE_MUTEX_RECURSIVE.
+**
+** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
+** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
+** returns a different mutex on every call. ^For the static
+** mutex types, the same mutex is returned on every call that has
+** the same type number.
+**
+** ^The sqlite3_mutex_free() routine deallocates a previously
+** allocated dynamic mutex. Attempting to deallocate a static
+** mutex results in undefined behavior.
+**
+** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
+** to enter a mutex. ^If another thread is already within the mutex,
+** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
+** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
+** upon successful entry. ^(Mutexes created using
+** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
+** In such cases, the
+** mutex must be exited an equal number of times before another thread
+** can enter.)^ If the same thread tries to enter any mutex other
+** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
+**
+** ^(Some systems (for example, Windows 95) do not support the operation
+** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
+** will always return SQLITE_BUSY. The SQLite core only ever uses
+** sqlite3_mutex_try() as an optimization so this is acceptable
+** behavior.)^
+**
+** ^The sqlite3_mutex_leave() routine exits a mutex that was
+** previously entered by the same thread. The behavior
+** is undefined if the mutex is not currently entered by the
+** calling thread or is not currently allocated.
+**
+** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
+** sqlite3_mutex_leave() is a NULL pointer, then all three routines
+** behave as no-ops.
+**
+** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
+*/
+SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
+SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
+SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
+SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
+SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
+
+/*
+** CAPI3REF: Mutex Methods Object
+**
+** An instance of this structure defines the low-level routines
+** used to allocate and use mutexes.
+**
+** Usually, the default mutex implementations provided by SQLite are
+** sufficient, however the application has the option of substituting a custom
+** implementation for specialized deployments or systems for which SQLite
+** does not provide a suitable implementation. In this case, the application
+** creates and populates an instance of this structure to pass
+** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
+** Additionally, an instance of this structure can be used as an
+** output variable when querying the system for the current mutex
+** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
+**
+** ^The xMutexInit method defined by this structure is invoked as
+** part of system initialization by the sqlite3_initialize() function.
+** ^The xMutexInit routine is called by SQLite exactly once for each
+** effective call to [sqlite3_initialize()].
+**
+** ^The xMutexEnd method defined by this structure is invoked as
+** part of system shutdown by the sqlite3_shutdown() function. The
+** implementation of this method is expected to release all outstanding
+** resources obtained by the mutex methods implementation, especially
+** those obtained by the xMutexInit method. ^The xMutexEnd()
+** interface is invoked exactly once for each call to [sqlite3_shutdown()].
+**
+** ^(The remaining seven methods defined by this structure (xMutexAlloc,
+** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
+** xMutexNotheld) implement the following interfaces (respectively):
+**
+** <ul>
+** <li> [sqlite3_mutex_alloc()] </li>
+** <li> [sqlite3_mutex_free()] </li>
+** <li> [sqlite3_mutex_enter()] </li>
+** <li> [sqlite3_mutex_try()] </li>
+** <li> [sqlite3_mutex_leave()] </li>
+** <li> [sqlite3_mutex_held()] </li>
+** <li> [sqlite3_mutex_notheld()] </li>
+** </ul>)^
+**
+** The only difference is that the public sqlite3_XXX functions enumerated
+** above silently ignore any invocations that pass a NULL pointer instead
+** of a valid mutex handle. The implementations of the methods defined
+** by this structure are not required to handle this case. The results
+** of passing a NULL pointer instead of a valid mutex handle are undefined
+** (i.e. it is acceptable to provide an implementation that segfaults if
+** it is passed a NULL pointer).
+**
+** The xMutexInit() method must be threadsafe. It must be harmless to
+** invoke xMutexInit() multiple times within the same process and without
+** intervening calls to xMutexEnd(). Second and subsequent calls to
+** xMutexInit() must be no-ops.
+**
+** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
+** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
+** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
+** memory allocation for a fast or recursive mutex.
+**
+** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
+** called, but only if the prior call to xMutexInit returned SQLITE_OK.
+** If xMutexInit fails in any way, it is expected to clean up after itself
+** prior to returning.
+*/
+typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
+struct sqlite3_mutex_methods {
+ int (*xMutexInit)(void);
+ int (*xMutexEnd)(void);
+ sqlite3_mutex *(*xMutexAlloc)(int);
+ void (*xMutexFree)(sqlite3_mutex *);
+ void (*xMutexEnter)(sqlite3_mutex *);
+ int (*xMutexTry)(sqlite3_mutex *);
+ void (*xMutexLeave)(sqlite3_mutex *);
+ int (*xMutexHeld)(sqlite3_mutex *);
+ int (*xMutexNotheld)(sqlite3_mutex *);
+};
+
+/*
+** CAPI3REF: Mutex Verification Routines
+**
+** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
+** are intended for use inside assert() statements. The SQLite core
+** never uses these routines except inside an assert() and applications
+** are advised to follow the lead of the core. The SQLite core only
+** provides implementations for these routines when it is compiled
+** with the SQLITE_DEBUG flag. External mutex implementations
+** are only required to provide these routines if SQLITE_DEBUG is
+** defined and if NDEBUG is not defined.
+**
+** These routines should return true if the mutex in their argument
+** is held or not held, respectively, by the calling thread.
+**
+** The implementation is not required to provide versions of these
+** routines that actually work. If the implementation does not provide working
+** versions of these routines, it should at least provide stubs that always
+** return true so that one does not get spurious assertion failures.
+**
+** If the argument to sqlite3_mutex_held() is a NULL pointer then
+** the routine should return 1. This seems counter-intuitive since
+** clearly the mutex cannot be held if it does not exist. But
+** the reason the mutex does not exist is because the build is not
+** using mutexes. And we do not want the assert() containing the
+** call to sqlite3_mutex_held() to fail, so a non-zero return is
+** the appropriate thing to do. The sqlite3_mutex_notheld()
+** interface should also return 1 when given a NULL pointer.
+*/
+#ifndef NDEBUG
+SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
+SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
+#endif
+
+/*
+** CAPI3REF: Mutex Types
+**
+** The [sqlite3_mutex_alloc()] interface takes a single argument
+** which is one of these integer constants.
+**
+** The set of static mutexes may change from one SQLite release to the
+** next. Applications that override the built-in mutex logic must be
+** prepared to accommodate additional static mutexes.
+*/
+#define SQLITE_MUTEX_FAST 0
+#define SQLITE_MUTEX_RECURSIVE 1
+#define SQLITE_MUTEX_STATIC_MAIN 2
+#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
+#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
+#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
+#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
+#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
+#define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
+#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
+#define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
+#define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
+#define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
+#define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
+#define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
+#define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
+
+/* Legacy compatibility: */
+#define SQLITE_MUTEX_STATIC_MASTER 2
+
+
+/*
+** CAPI3REF: Retrieve the mutex for a database connection
+** METHOD: sqlite3
+**
+** ^This interface returns a pointer the [sqlite3_mutex] object that
+** serializes access to the [database connection] given in the argument
+** when the [threading mode] is Serialized.
+** ^If the [threading mode] is Single-thread or Multi-thread then this
+** routine returns a NULL pointer.
+*/
+SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
+
+/*
+** CAPI3REF: Low-Level Control Of Database Files
+** METHOD: sqlite3
+** KEYWORDS: {file control}
+**
+** ^The [sqlite3_file_control()] interface makes a direct call to the
+** xFileControl method for the [sqlite3_io_methods] object associated
+** with a particular database identified by the second argument. ^The
+** name of the database is "main" for the main database or "temp" for the
+** TEMP database, or the name that appears after the AS keyword for
+** databases that are added using the [ATTACH] SQL command.
+** ^A NULL pointer can be used in place of "main" to refer to the
+** main database file.
+** ^The third and fourth parameters to this routine
+** are passed directly through to the second and third parameters of
+** the xFileControl method. ^The return value of the xFileControl
+** method becomes the return value of this routine.
+**
+** A few opcodes for [sqlite3_file_control()] are handled directly
+** by the SQLite core and never invoke the
+** sqlite3_io_methods.xFileControl method.
+** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
+** a pointer to the underlying [sqlite3_file] object to be written into
+** the space pointed to by the 4th parameter. The
+** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns
+** the [sqlite3_file] object associated with the journal file instead of
+** the main database. The [SQLITE_FCNTL_VFS_POINTER] opcode returns
+** a pointer to the underlying [sqlite3_vfs] object for the file.
+** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter
+** from the pager.
+**
+** ^If the second parameter (zDbName) does not match the name of any
+** open database file, then SQLITE_ERROR is returned. ^This error
+** code is not remembered and will not be recalled by [sqlite3_errcode()]
+** or [sqlite3_errmsg()]. The underlying xFileControl method might
+** also return SQLITE_ERROR. There is no way to distinguish between
+** an incorrect zDbName and an SQLITE_ERROR return from the underlying
+** xFileControl method.
+**
+** See also: [file control opcodes]
+*/
+SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
+
+/*
+** CAPI3REF: Testing Interface
+**
+** ^The sqlite3_test_control() interface is used to read out internal
+** state of SQLite and to inject faults into SQLite for testing
+** purposes. ^The first parameter is an operation code that determines
+** the number, meaning, and operation of all subsequent parameters.
+**
+** This interface is not for use by applications. It exists solely
+** for verifying the correct operation of the SQLite library. Depending
+** on how the SQLite library is compiled, this interface might not exist.
+**
+** The details of the operation codes, their meanings, the parameters
+** they take, and what they do are all subject to change without notice.
+** Unlike most of the SQLite API, this function is not guaranteed to
+** operate consistently from one release to the next.
+*/
+SQLITE_API int sqlite3_test_control(int op, ...);
+
+/*
+** CAPI3REF: Testing Interface Operation Codes
+**
+** These constants are the valid operation code parameters used
+** as the first argument to [sqlite3_test_control()].
+**
+** These parameters and their meanings are subject to change
+** without notice. These values are for testing purposes only.
+** Applications should not use any of these parameters or the
+** [sqlite3_test_control()] interface.
+*/
+#define SQLITE_TESTCTRL_FIRST 5
+#define SQLITE_TESTCTRL_PRNG_SAVE 5
+#define SQLITE_TESTCTRL_PRNG_RESTORE 6
+#define SQLITE_TESTCTRL_PRNG_RESET 7 /* NOT USED */
+#define SQLITE_TESTCTRL_SEEK_COUNT 7
+#define SQLITE_TESTCTRL_BITVEC_TEST 8
+#define SQLITE_TESTCTRL_FAULT_INSTALL 9
+#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
+#define SQLITE_TESTCTRL_PENDING_BYTE 11
+#define SQLITE_TESTCTRL_ASSERT 12
+#define SQLITE_TESTCTRL_ALWAYS 13
+#define SQLITE_TESTCTRL_RESERVE 14 /* NOT USED */
+#define SQLITE_TESTCTRL_OPTIMIZATIONS 15
+#define SQLITE_TESTCTRL_ISKEYWORD 16 /* NOT USED */
+#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */
+#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 17
+#define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
+#define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
+#define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
+#define SQLITE_TESTCTRL_NEVER_CORRUPT 20
+#define SQLITE_TESTCTRL_VDBE_COVERAGE 21
+#define SQLITE_TESTCTRL_BYTEORDER 22
+#define SQLITE_TESTCTRL_ISINIT 23
+#define SQLITE_TESTCTRL_SORTER_MMAP 24
+#define SQLITE_TESTCTRL_IMPOSTER 25
+#define SQLITE_TESTCTRL_PARSER_COVERAGE 26
+#define SQLITE_TESTCTRL_RESULT_INTREAL 27
+#define SQLITE_TESTCTRL_PRNG_SEED 28
+#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS 29
+#define SQLITE_TESTCTRL_LAST 29 /* Largest TESTCTRL */
+
+/*
+** CAPI3REF: SQL Keyword Checking
+**
+** These routines provide access to the set of SQL language keywords
+** recognized by SQLite. Applications can uses these routines to determine
+** whether or not a specific identifier needs to be escaped (for example,
+** by enclosing in double-quotes) so as not to confuse the parser.
+**
+** The sqlite3_keyword_count() interface returns the number of distinct
+** keywords understood by SQLite.
+**
+** The sqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and
+** makes *Z point to that keyword expressed as UTF8 and writes the number
+** of bytes in the keyword into *L. The string that *Z points to is not
+** zero-terminated. The sqlite3_keyword_name(N,Z,L) routine returns
+** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z
+** or L are NULL or invalid pointers then calls to
+** sqlite3_keyword_name(N,Z,L) result in undefined behavior.
+**
+** The sqlite3_keyword_check(Z,L) interface checks to see whether or not
+** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
+** if it is and zero if not.
+**
+** The parser used by SQLite is forgiving. It is often possible to use
+** a keyword as an identifier as long as such use does not result in a
+** parsing ambiguity. For example, the statement
+** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
+** creates a new table named "BEGIN" with three columns named
+** "REPLACE", "PRAGMA", and "END". Nevertheless, best practice is to avoid
+** using keywords as identifiers. Common techniques used to avoid keyword
+** name collisions include:
+** <ul>
+** <li> Put all identifier names inside double-quotes. This is the official
+** SQL way to escape identifier names.
+** <li> Put identifier names inside &#91;...&#93;. This is not standard SQL,
+** but it is what SQL Server does and so lots of programmers use this
+** technique.
+** <li> Begin every identifier with the letter "Z" as no SQL keywords start
+** with "Z".
+** <li> Include a digit somewhere in every identifier name.
+** </ul>
+**
+** Note that the number of keywords understood by SQLite can depend on
+** compile-time options. For example, "VACUUM" is not a keyword if
+** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also,
+** new keywords may be added to future releases of SQLite.
+*/
+SQLITE_API int sqlite3_keyword_count(void);
+SQLITE_API int sqlite3_keyword_name(int,const char**,int*);
+SQLITE_API int sqlite3_keyword_check(const char*,int);
+
+/*
+** CAPI3REF: Dynamic String Object
+** KEYWORDS: {dynamic string}
+**
+** An instance of the sqlite3_str object contains a dynamically-sized
+** string under construction.
+**
+** The lifecycle of an sqlite3_str object is as follows:
+** <ol>
+** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
+** <li> ^Text is appended to the sqlite3_str object using various
+** methods, such as [sqlite3_str_appendf()].
+** <li> ^The sqlite3_str object is destroyed and the string it created
+** is returned using the [sqlite3_str_finish()] interface.
+** </ol>
+*/
+typedef struct sqlite3_str sqlite3_str;
+
+/*
+** CAPI3REF: Create A New Dynamic String Object
+** CONSTRUCTOR: sqlite3_str
+**
+** ^The [sqlite3_str_new(D)] interface allocates and initializes
+** a new [sqlite3_str] object. To avoid memory leaks, the object returned by
+** [sqlite3_str_new()] must be freed by a subsequent call to
+** [sqlite3_str_finish(X)].
+**
+** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
+** valid [sqlite3_str] object, though in the event of an out-of-memory
+** error the returned object might be a special singleton that will
+** silently reject new text, always return SQLITE_NOMEM from
+** [sqlite3_str_errcode()], always return 0 for
+** [sqlite3_str_length()], and always return NULL from
+** [sqlite3_str_finish(X)]. It is always safe to use the value
+** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
+** to any of the other [sqlite3_str] methods.
+**
+** The D parameter to [sqlite3_str_new(D)] may be NULL. If the
+** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum
+** length of the string contained in the [sqlite3_str] object will be
+** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead
+** of [SQLITE_MAX_LENGTH].
+*/
+SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);
+
+/*
+** CAPI3REF: Finalize A Dynamic String
+** DESTRUCTOR: sqlite3_str
+**
+** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X
+** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]
+** that contains the constructed string. The calling application should
+** pass the returned value to [sqlite3_free()] to avoid a memory leak.
+** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any
+** errors were encountered during construction of the string. ^The
+** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the
+** string in [sqlite3_str] object X is zero bytes long.
+*/
+SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
+
+/*
+** CAPI3REF: Add Content To A Dynamic String
+** METHOD: sqlite3_str
+**
+** These interfaces add content to an sqlite3_str object previously obtained
+** from [sqlite3_str_new()].
+**
+** ^The [sqlite3_str_appendf(X,F,...)] and
+** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
+** functionality of SQLite to append formatted text onto the end of
+** [sqlite3_str] object X.
+**
+** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
+** onto the end of the [sqlite3_str] object X. N must be non-negative.
+** S must contain at least N non-zero bytes of content. To append a
+** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
+** method instead.
+**
+** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of
+** zero-terminated string S onto the end of [sqlite3_str] object X.
+**
+** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the
+** single-byte character C onto the end of [sqlite3_str] object X.
+** ^This method can be used, for example, to add whitespace indentation.
+**
+** ^The [sqlite3_str_reset(X)] method resets the string under construction
+** inside [sqlite3_str] object X back to zero bytes in length.
+**
+** These methods do not return a result code. ^If an error occurs, that fact
+** is recorded in the [sqlite3_str] object and can be recovered by a
+** subsequent call to [sqlite3_str_errcode(X)].
+*/
+SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);
+SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);
+SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);
+SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);
+SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);
+SQLITE_API void sqlite3_str_reset(sqlite3_str*);
+
+/*
+** CAPI3REF: Status Of A Dynamic String
+** METHOD: sqlite3_str
+**
+** These interfaces return the current status of an [sqlite3_str] object.
+**
+** ^If any prior errors have occurred while constructing the dynamic string
+** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return
+** an appropriate error code. ^The [sqlite3_str_errcode(X)] method returns
+** [SQLITE_NOMEM] following any out-of-memory error, or
+** [SQLITE_TOOBIG] if the size of the dynamic string exceeds
+** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.
+**
+** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,
+** of the dynamic string under construction in [sqlite3_str] object X.
+** ^The length returned by [sqlite3_str_length(X)] does not include the
+** zero-termination byte.
+**
+** ^The [sqlite3_str_value(X)] method returns a pointer to the current
+** content of the dynamic string under construction in X. The value
+** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X
+** and might be freed or altered by any subsequent method on the same
+** [sqlite3_str] object. Applications must not used the pointer returned
+** [sqlite3_str_value(X)] after any subsequent method call on the same
+** object. ^Applications may change the content of the string returned
+** by [sqlite3_str_value(X)] as long as they do not write into any bytes
+** outside the range of 0 to [sqlite3_str_length(X)] and do not read or
+** write any byte after any subsequent sqlite3_str method call.
+*/
+SQLITE_API int sqlite3_str_errcode(sqlite3_str*);
+SQLITE_API int sqlite3_str_length(sqlite3_str*);
+SQLITE_API char *sqlite3_str_value(sqlite3_str*);
+
+/*
+** CAPI3REF: SQLite Runtime Status
+**
+** ^These interfaces are used to retrieve runtime status information
+** about the performance of SQLite, and optionally to reset various
+** highwater marks. ^The first argument is an integer code for
+** the specific parameter to measure. ^(Recognized integer codes
+** are of the form [status parameters | SQLITE_STATUS_...].)^
+** ^The current value of the parameter is returned into *pCurrent.
+** ^The highest recorded value is returned in *pHighwater. ^If the
+** resetFlag is true, then the highest record value is reset after
+** *pHighwater is written. ^(Some parameters do not record the highest
+** value. For those parameters
+** nothing is written into *pHighwater and the resetFlag is ignored.)^
+** ^(Other parameters record only the highwater mark and not the current
+** value. For these latter parameters nothing is written into *pCurrent.)^
+**
+** ^The sqlite3_status() and sqlite3_status64() routines return
+** SQLITE_OK on success and a non-zero [error code] on failure.
+**
+** If either the current value or the highwater mark is too large to
+** be represented by a 32-bit integer, then the values returned by
+** sqlite3_status() are undefined.
+**
+** See also: [sqlite3_db_status()]
+*/
+SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
+SQLITE_API int sqlite3_status64(
+ int op,
+ sqlite3_int64 *pCurrent,
+ sqlite3_int64 *pHighwater,
+ int resetFlag
+);
+
+
+/*
+** CAPI3REF: Status Parameters
+** KEYWORDS: {status parameters}
+**
+** These integer constants designate various run-time status parameters
+** that can be returned by [sqlite3_status()].
+**
+** <dl>
+** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
+** <dd>This parameter is the current amount of memory checked out
+** using [sqlite3_malloc()], either directly or indirectly. The
+** figure includes calls made to [sqlite3_malloc()] by the application
+** and internal memory usage by the SQLite library. Auxiliary page-cache
+** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
+** this parameter. The amount returned is the sum of the allocation
+** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
+**
+** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
+** <dd>This parameter records the largest memory allocation request
+** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
+** internal equivalents). Only the value returned in the
+** *pHighwater parameter to [sqlite3_status()] is of interest.
+** The value written into the *pCurrent parameter is undefined.</dd>)^
+**
+** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
+** <dd>This parameter records the number of separate memory allocations
+** currently checked out.</dd>)^
+**
+** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
+** <dd>This parameter returns the number of pages used out of the
+** [pagecache memory allocator] that was configured using
+** [SQLITE_CONFIG_PAGECACHE]. The
+** value returned is in pages, not in bytes.</dd>)^
+**
+** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
+** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
+** <dd>This parameter returns the number of bytes of page cache
+** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
+** buffer and where forced to overflow to [sqlite3_malloc()]. The
+** returned value includes allocations that overflowed because they
+** where too large (they were larger than the "sz" parameter to
+** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
+** no space was left in the page cache.</dd>)^
+**
+** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
+** <dd>This parameter records the largest memory allocation request
+** handed to the [pagecache memory allocator]. Only the value returned in the
+** *pHighwater parameter to [sqlite3_status()] is of interest.
+** The value written into the *pCurrent parameter is undefined.</dd>)^
+**
+** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
+** <dd>No longer used.</dd>
+**
+** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
+** <dd>No longer used.</dd>
+**
+** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
+** <dd>No longer used.</dd>
+**
+** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
+** <dd>The *pHighwater parameter records the deepest parser stack.
+** The *pCurrent value is undefined. The *pHighwater value is only
+** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
+** </dl>
+**
+** New status parameters may be added from time to time.
+*/
+#define SQLITE_STATUS_MEMORY_USED 0
+#define SQLITE_STATUS_PAGECACHE_USED 1
+#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
+#define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */
+#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */
+#define SQLITE_STATUS_MALLOC_SIZE 5
+#define SQLITE_STATUS_PARSER_STACK 6
+#define SQLITE_STATUS_PAGECACHE_SIZE 7
+#define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */
+#define SQLITE_STATUS_MALLOC_COUNT 9
+
+/*
+** CAPI3REF: Database Connection Status
+** METHOD: sqlite3
+**
+** ^This interface is used to retrieve runtime status information
+** about a single [database connection]. ^The first argument is the
+** database connection object to be interrogated. ^The second argument
+** is an integer constant, taken from the set of
+** [SQLITE_DBSTATUS options], that
+** determines the parameter to interrogate. The set of
+** [SQLITE_DBSTATUS options] is likely
+** to grow in future releases of SQLite.
+**
+** ^The current value of the requested parameter is written into *pCur
+** and the highest instantaneous value is written into *pHiwtr. ^If
+** the resetFlg is true, then the highest instantaneous value is
+** reset back down to the current value.
+**
+** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
+** non-zero [error code] on failure.
+**
+** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
+*/
+SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
+
+/*
+** CAPI3REF: Status Parameters for database connections
+** KEYWORDS: {SQLITE_DBSTATUS options}
+**
+** These constants are the available integer "verbs" that can be passed as
+** the second argument to the [sqlite3_db_status()] interface.
+**
+** New verbs may be added in future releases of SQLite. Existing verbs
+** might be discontinued. Applications should check the return code from
+** [sqlite3_db_status()] to make sure that the call worked.
+** The [sqlite3_db_status()] interface will return a non-zero error code
+** if a discontinued or unsupported verb is invoked.
+**
+** <dl>
+** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
+** <dd>This parameter returns the number of lookaside memory slots currently
+** checked out.</dd>)^
+**
+** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
+** <dd>This parameter returns the number of malloc attempts that were
+** satisfied using lookaside memory. Only the high-water value is meaningful;
+** the current value is always zero.)^
+**
+** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
+** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
+** <dd>This parameter returns the number malloc attempts that might have
+** been satisfied using lookaside memory but failed due to the amount of
+** memory requested being larger than the lookaside slot size.
+** Only the high-water value is meaningful;
+** the current value is always zero.)^
+**
+** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
+** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
+** <dd>This parameter returns the number malloc attempts that might have
+** been satisfied using lookaside memory but failed due to all lookaside
+** memory already being in use.
+** Only the high-water value is meaningful;
+** the current value is always zero.)^
+**
+** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
+** <dd>This parameter returns the approximate number of bytes of heap
+** memory used by all pager caches associated with the database connection.)^
+** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
+**
+** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
+** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
+** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
+** pager cache is shared between two or more connections the bytes of heap
+** memory used by that pager cache is divided evenly between the attached
+** connections.)^ In other words, if none of the pager caches associated
+** with the database connection are shared, this request returns the same
+** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
+** shared, the value returned by this call will be smaller than that returned
+** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
+** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
+**
+** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
+** <dd>This parameter returns the approximate number of bytes of heap
+** memory used to store the schema for all databases associated
+** with the connection - main, temp, and any [ATTACH]-ed databases.)^
+** ^The full amount of memory used by the schemas is reported, even if the
+** schema memory is shared with other database connections due to
+** [shared cache mode] being enabled.
+** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
+**
+** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
+** <dd>This parameter returns the approximate number of bytes of heap
+** and lookaside memory used by all prepared statements associated with
+** the database connection.)^
+** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
+** </dd>
+**
+** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
+** <dd>This parameter returns the number of pager cache hits that have
+** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
+** is always 0.
+** </dd>
+**
+** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
+** <dd>This parameter returns the number of pager cache misses that have
+** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
+** is always 0.
+** </dd>
+**
+** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
+** <dd>This parameter returns the number of dirty cache entries that have
+** been written to disk. Specifically, the number of pages written to the
+** wal file in wal mode databases, or the number of pages written to the
+** database file in rollback mode databases. Any pages written as part of
+** transaction rollback or database recovery operations are not included.
+** If an IO or other error occurs while writing a page to disk, the effect
+** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
+** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
+** </dd>
+**
+** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>
+** <dd>This parameter returns the number of dirty cache entries that have
+** been written to disk in the middle of a transaction due to the page
+** cache overflowing. Transactions are more efficient if they are written
+** to disk all at once. When pages spill mid-transaction, that introduces
+** additional overhead. This parameter can be used help identify
+** inefficiencies that can be resolved by increasing the cache size.
+** </dd>
+**
+** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
+** <dd>This parameter returns zero for the current value if and only if
+** all foreign key constraints (deferred or immediate) have been
+** resolved.)^ ^The highwater mark is always 0.
+** </dd>
+** </dl>
+*/
+#define SQLITE_DBSTATUS_LOOKASIDE_USED 0
+#define SQLITE_DBSTATUS_CACHE_USED 1
+#define SQLITE_DBSTATUS_SCHEMA_USED 2
+#define SQLITE_DBSTATUS_STMT_USED 3
+#define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
+#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
+#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
+#define SQLITE_DBSTATUS_CACHE_HIT 7
+#define SQLITE_DBSTATUS_CACHE_MISS 8
+#define SQLITE_DBSTATUS_CACHE_WRITE 9
+#define SQLITE_DBSTATUS_DEFERRED_FKS 10
+#define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
+#define SQLITE_DBSTATUS_CACHE_SPILL 12
+#define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */
+
+
+/*
+** CAPI3REF: Prepared Statement Status
+** METHOD: sqlite3_stmt
+**
+** ^(Each prepared statement maintains various
+** [SQLITE_STMTSTATUS counters] that measure the number
+** of times it has performed specific operations.)^ These counters can
+** be used to monitor the performance characteristics of the prepared
+** statements. For example, if the number of table steps greatly exceeds
+** the number of table searches or result rows, that would tend to indicate
+** that the prepared statement is using a full table scan rather than
+** an index.
+**
+** ^(This interface is used to retrieve and reset counter values from
+** a [prepared statement]. The first argument is the prepared statement
+** object to be interrogated. The second argument
+** is an integer code for a specific [SQLITE_STMTSTATUS counter]
+** to be interrogated.)^
+** ^The current value of the requested counter is returned.
+** ^If the resetFlg is true, then the counter is reset to zero after this
+** interface call returns.
+**
+** See also: [sqlite3_status()] and [sqlite3_db_status()].
+*/
+SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
+
+/*
+** CAPI3REF: Status Parameters for prepared statements
+** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
+**
+** These preprocessor macros define integer codes that name counter
+** values associated with the [sqlite3_stmt_status()] interface.
+** The meanings of the various counters are as follows:
+**
+** <dl>
+** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
+** <dd>^This is the number of times that SQLite has stepped forward in
+** a table as part of a full table scan. Large numbers for this counter
+** may indicate opportunities for performance improvement through
+** careful use of indices.</dd>
+**
+** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
+** <dd>^This is the number of sort operations that have occurred.
+** A non-zero value in this counter may indicate an opportunity to
+** improvement performance through careful use of indices.</dd>
+**
+** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
+** <dd>^This is the number of rows inserted into transient indices that
+** were created automatically in order to help joins run faster.
+** A non-zero value in this counter may indicate an opportunity to
+** improvement performance by adding permanent indices that do not
+** need to be reinitialized each time the statement is run.</dd>
+**
+** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
+** <dd>^This is the number of virtual machine operations executed
+** by the prepared statement if that number is less than or equal
+** to 2147483647. The number of virtual machine operations can be
+** used as a proxy for the total work done by the prepared statement.
+** If the number of virtual machine operations exceeds 2147483647
+** then the value returned by this statement status code is undefined.
+**
+** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
+** <dd>^This is the number of times that the prepare statement has been
+** automatically regenerated due to schema changes or changes to
+** [bound parameters] that might affect the query plan.
+**
+** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
+** <dd>^This is the number of times that the prepared statement has
+** been run. A single "run" for the purposes of this counter is one
+** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
+** The counter is incremented on the first [sqlite3_step()] call of each
+** cycle.
+**
+** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
+** <dd>^This is the approximate number of bytes of heap memory
+** used to store the prepared statement. ^This value is not actually
+** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
+** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
+** </dd>
+** </dl>
+*/
+#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
+#define SQLITE_STMTSTATUS_SORT 2
+#define SQLITE_STMTSTATUS_AUTOINDEX 3
+#define SQLITE_STMTSTATUS_VM_STEP 4
+#define SQLITE_STMTSTATUS_REPREPARE 5
+#define SQLITE_STMTSTATUS_RUN 6
+#define SQLITE_STMTSTATUS_MEMUSED 99
+
+/*
+** CAPI3REF: Custom Page Cache Object
+**
+** The sqlite3_pcache type is opaque. It is implemented by
+** the pluggable module. The SQLite core has no knowledge of
+** its size or internal structure and never deals with the
+** sqlite3_pcache object except by holding and passing pointers
+** to the object.
+**
+** See [sqlite3_pcache_methods2] for additional information.
+*/
+typedef struct sqlite3_pcache sqlite3_pcache;
+
+/*
+** CAPI3REF: Custom Page Cache Object
+**
+** The sqlite3_pcache_page object represents a single page in the
+** page cache. The page cache will allocate instances of this
+** object. Various methods of the page cache use pointers to instances
+** of this object as parameters or as their return value.
+**
+** See [sqlite3_pcache_methods2] for additional information.
+*/
+typedef struct sqlite3_pcache_page sqlite3_pcache_page;
+struct sqlite3_pcache_page {
+ void *pBuf; /* The content of the page */
+ void *pExtra; /* Extra information associated with the page */
+};
+
+/*
+** CAPI3REF: Application Defined Page Cache.
+** KEYWORDS: {page cache}
+**
+** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
+** register an alternative page cache implementation by passing in an
+** instance of the sqlite3_pcache_methods2 structure.)^
+** In many applications, most of the heap memory allocated by
+** SQLite is used for the page cache.
+** By implementing a
+** custom page cache using this API, an application can better control
+** the amount of memory consumed by SQLite, the way in which
+** that memory is allocated and released, and the policies used to
+** determine exactly which parts of a database file are cached and for
+** how long.
+**
+** The alternative page cache mechanism is an
+** extreme measure that is only needed by the most demanding applications.
+** The built-in page cache is recommended for most uses.
+**
+** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
+** internal buffer by SQLite within the call to [sqlite3_config]. Hence
+** the application may discard the parameter after the call to
+** [sqlite3_config()] returns.)^
+**
+** [[the xInit() page cache method]]
+** ^(The xInit() method is called once for each effective
+** call to [sqlite3_initialize()])^
+** (usually only once during the lifetime of the process). ^(The xInit()
+** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
+** The intent of the xInit() method is to set up global data structures
+** required by the custom page cache implementation.
+** ^(If the xInit() method is NULL, then the
+** built-in default page cache is used instead of the application defined
+** page cache.)^
+**
+** [[the xShutdown() page cache method]]
+** ^The xShutdown() method is called by [sqlite3_shutdown()].
+** It can be used to clean up
+** any outstanding resources before process shutdown, if required.
+** ^The xShutdown() method may be NULL.
+**
+** ^SQLite automatically serializes calls to the xInit method,
+** so the xInit method need not be threadsafe. ^The
+** xShutdown method is only called from [sqlite3_shutdown()] so it does
+** not need to be threadsafe either. All other methods must be threadsafe
+** in multithreaded applications.
+**
+** ^SQLite will never invoke xInit() more than once without an intervening
+** call to xShutdown().
+**
+** [[the xCreate() page cache methods]]
+** ^SQLite invokes the xCreate() method to construct a new cache instance.
+** SQLite will typically create one cache instance for each open database file,
+** though this is not guaranteed. ^The
+** first parameter, szPage, is the size in bytes of the pages that must
+** be allocated by the cache. ^szPage will always a power of two. ^The
+** second parameter szExtra is a number of bytes of extra storage
+** associated with each page cache entry. ^The szExtra parameter will
+** a number less than 250. SQLite will use the
+** extra szExtra bytes on each page to store metadata about the underlying
+** database page on disk. The value passed into szExtra depends
+** on the SQLite version, the target platform, and how SQLite was compiled.
+** ^The third argument to xCreate(), bPurgeable, is true if the cache being
+** created will be used to cache database pages of a file stored on disk, or
+** false if it is used for an in-memory database. The cache implementation
+** does not have to do anything special based with the value of bPurgeable;
+** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
+** never invoke xUnpin() except to deliberately delete a page.
+** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
+** false will always have the "discard" flag set to true.
+** ^Hence, a cache created with bPurgeable false will
+** never contain any unpinned pages.
+**
+** [[the xCachesize() page cache method]]
+** ^(The xCachesize() method may be called at any time by SQLite to set the
+** suggested maximum cache-size (number of pages stored by) the cache
+** instance passed as the first argument. This is the value configured using
+** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
+** parameter, the implementation is not required to do anything with this
+** value; it is advisory only.
+**
+** [[the xPagecount() page cache methods]]
+** The xPagecount() method must return the number of pages currently
+** stored in the cache, both pinned and unpinned.
+**
+** [[the xFetch() page cache methods]]
+** The xFetch() method locates a page in the cache and returns a pointer to
+** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
+** The pBuf element of the returned sqlite3_pcache_page object will be a
+** pointer to a buffer of szPage bytes used to store the content of a
+** single database page. The pExtra element of sqlite3_pcache_page will be
+** a pointer to the szExtra bytes of extra storage that SQLite has requested
+** for each entry in the page cache.
+**
+** The page to be fetched is determined by the key. ^The minimum key value
+** is 1. After it has been retrieved using xFetch, the page is considered
+** to be "pinned".
+**
+** If the requested page is already in the page cache, then the page cache
+** implementation must return a pointer to the page buffer with its content
+** intact. If the requested page is not already in the cache, then the
+** cache implementation should use the value of the createFlag
+** parameter to help it determined what action to take:
+**
+** <table border=1 width=85% align=center>
+** <tr><th> createFlag <th> Behavior when page is not already in cache
+** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
+** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
+** Otherwise return NULL.
+** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
+** NULL if allocating a new page is effectively impossible.
+** </table>
+**
+** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
+** will only use a createFlag of 2 after a prior call with a createFlag of 1
+** failed.)^ In between the xFetch() calls, SQLite may
+** attempt to unpin one or more cache pages by spilling the content of
+** pinned pages to disk and synching the operating system disk cache.
+**
+** [[the xUnpin() page cache method]]
+** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
+** as its second argument. If the third parameter, discard, is non-zero,
+** then the page must be evicted from the cache.
+** ^If the discard parameter is
+** zero, then the page may be discarded or retained at the discretion of
+** page cache implementation. ^The page cache implementation
+** may choose to evict unpinned pages at any time.
+**
+** The cache must not perform any reference counting. A single
+** call to xUnpin() unpins the page regardless of the number of prior calls
+** to xFetch().
+**
+** [[the xRekey() page cache methods]]
+** The xRekey() method is used to change the key value associated with the
+** page passed as the second argument. If the cache
+** previously contains an entry associated with newKey, it must be
+** discarded. ^Any prior cache entry associated with newKey is guaranteed not
+** to be pinned.
+**
+** When SQLite calls the xTruncate() method, the cache must discard all
+** existing cache entries with page numbers (keys) greater than or equal
+** to the value of the iLimit parameter passed to xTruncate(). If any
+** of these pages are pinned, they are implicitly unpinned, meaning that
+** they can be safely discarded.
+**
+** [[the xDestroy() page cache method]]
+** ^The xDestroy() method is used to delete a cache allocated by xCreate().
+** All resources associated with the specified cache should be freed. ^After
+** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
+** handle invalid, and will not use it with any other sqlite3_pcache_methods2
+** functions.
+**
+** [[the xShrink() page cache method]]
+** ^SQLite invokes the xShrink() method when it wants the page cache to
+** free up as much of heap memory as possible. The page cache implementation
+** is not obligated to free any memory, but well-behaved implementations should
+** do their best.
+*/
+typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
+struct sqlite3_pcache_methods2 {
+ int iVersion;
+ void *pArg;
+ int (*xInit)(void*);
+ void (*xShutdown)(void*);
+ sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
+ void (*xCachesize)(sqlite3_pcache*, int nCachesize);
+ int (*xPagecount)(sqlite3_pcache*);
+ sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
+ void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
+ void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
+ unsigned oldKey, unsigned newKey);
+ void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
+ void (*xDestroy)(sqlite3_pcache*);
+ void (*xShrink)(sqlite3_pcache*);
+};
+
+/*
+** This is the obsolete pcache_methods object that has now been replaced
+** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
+** retained in the header file for backwards compatibility only.
+*/
+typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
+struct sqlite3_pcache_methods {
+ void *pArg;
+ int (*xInit)(void*);
+ void (*xShutdown)(void*);
+ sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
+ void (*xCachesize)(sqlite3_pcache*, int nCachesize);
+ int (*xPagecount)(sqlite3_pcache*);
+ void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
+ void (*xUnpin)(sqlite3_pcache*, void*, int discard);
+ void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
+ void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
+ void (*xDestroy)(sqlite3_pcache*);
+};
+
+
+/*
+** CAPI3REF: Online Backup Object
+**
+** The sqlite3_backup object records state information about an ongoing
+** online backup operation. ^The sqlite3_backup object is created by
+** a call to [sqlite3_backup_init()] and is destroyed by a call to
+** [sqlite3_backup_finish()].
+**
+** See Also: [Using the SQLite Online Backup API]
+*/
+typedef struct sqlite3_backup sqlite3_backup;
+
+/*
+** CAPI3REF: Online Backup API.
+**
+** The backup API copies the content of one database into another.
+** It is useful either for creating backups of databases or
+** for copying in-memory databases to or from persistent files.
+**
+** See Also: [Using the SQLite Online Backup API]
+**
+** ^SQLite holds a write transaction open on the destination database file
+** for the duration of the backup operation.
+** ^The source database is read-locked only while it is being read;
+** it is not locked continuously for the entire backup operation.
+** ^Thus, the backup may be performed on a live source database without
+** preventing other database connections from
+** reading or writing to the source database while the backup is underway.
+**
+** ^(To perform a backup operation:
+** <ol>
+** <li><b>sqlite3_backup_init()</b> is called once to initialize the
+** backup,
+** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
+** the data between the two databases, and finally
+** <li><b>sqlite3_backup_finish()</b> is called to release all resources
+** associated with the backup operation.
+** </ol>)^
+** There should be exactly one call to sqlite3_backup_finish() for each
+** successful call to sqlite3_backup_init().
+**
+** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
+**
+** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
+** [database connection] associated with the destination database
+** and the database name, respectively.
+** ^The database name is "main" for the main database, "temp" for the
+** temporary database, or the name specified after the AS keyword in
+** an [ATTACH] statement for an attached database.
+** ^The S and M arguments passed to
+** sqlite3_backup_init(D,N,S,M) identify the [database connection]
+** and database name of the source database, respectively.
+** ^The source and destination [database connections] (parameters S and D)
+** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
+** an error.
+**
+** ^A call to sqlite3_backup_init() will fail, returning NULL, if
+** there is already a read or read-write transaction open on the
+** destination database.
+**
+** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
+** returned and an error code and error message are stored in the
+** destination [database connection] D.
+** ^The error code and message for the failed call to sqlite3_backup_init()
+** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
+** [sqlite3_errmsg16()] functions.
+** ^A successful call to sqlite3_backup_init() returns a pointer to an
+** [sqlite3_backup] object.
+** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
+** sqlite3_backup_finish() functions to perform the specified backup
+** operation.
+**
+** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
+**
+** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
+** the source and destination databases specified by [sqlite3_backup] object B.
+** ^If N is negative, all remaining source pages are copied.
+** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
+** are still more pages to be copied, then the function returns [SQLITE_OK].
+** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
+** from source to destination, then it returns [SQLITE_DONE].
+** ^If an error occurs while running sqlite3_backup_step(B,N),
+** then an [error code] is returned. ^As well as [SQLITE_OK] and
+** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
+** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
+** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
+**
+** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
+** <ol>
+** <li> the destination database was opened read-only, or
+** <li> the destination database is using write-ahead-log journaling
+** and the destination and source page sizes differ, or
+** <li> the destination database is an in-memory database and the
+** destination and source page sizes differ.
+** </ol>)^
+**
+** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
+** the [sqlite3_busy_handler | busy-handler function]
+** is invoked (if one is specified). ^If the
+** busy-handler returns non-zero before the lock is available, then
+** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
+** sqlite3_backup_step() can be retried later. ^If the source
+** [database connection]
+** is being used to write to the source database when sqlite3_backup_step()
+** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
+** case the call to sqlite3_backup_step() can be retried later on. ^(If
+** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
+** [SQLITE_READONLY] is returned, then
+** there is no point in retrying the call to sqlite3_backup_step(). These
+** errors are considered fatal.)^ The application must accept
+** that the backup operation has failed and pass the backup operation handle
+** to the sqlite3_backup_finish() to release associated resources.
+**
+** ^The first call to sqlite3_backup_step() obtains an exclusive lock
+** on the destination file. ^The exclusive lock is not released until either
+** sqlite3_backup_finish() is called or the backup operation is complete
+** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
+** sqlite3_backup_step() obtains a [shared lock] on the source database that
+** lasts for the duration of the sqlite3_backup_step() call.
+** ^Because the source database is not locked between calls to
+** sqlite3_backup_step(), the source database may be modified mid-way
+** through the backup process. ^If the source database is modified by an
+** external process or via a database connection other than the one being
+** used by the backup operation, then the backup will be automatically
+** restarted by the next call to sqlite3_backup_step(). ^If the source
+** database is modified by the using the same database connection as is used
+** by the backup operation, then the backup database is automatically
+** updated at the same time.
+**
+** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
+**
+** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
+** application wishes to abandon the backup operation, the application
+** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
+** ^The sqlite3_backup_finish() interfaces releases all
+** resources associated with the [sqlite3_backup] object.
+** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
+** active write-transaction on the destination database is rolled back.
+** The [sqlite3_backup] object is invalid
+** and may not be used following a call to sqlite3_backup_finish().
+**
+** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
+** sqlite3_backup_step() errors occurred, regardless or whether or not
+** sqlite3_backup_step() completed.
+** ^If an out-of-memory condition or IO error occurred during any prior
+** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
+** sqlite3_backup_finish() returns the corresponding [error code].
+**
+** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
+** is not a permanent error and does not affect the return value of
+** sqlite3_backup_finish().
+**
+** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
+** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
+**
+** ^The sqlite3_backup_remaining() routine returns the number of pages still
+** to be backed up at the conclusion of the most recent sqlite3_backup_step().
+** ^The sqlite3_backup_pagecount() routine returns the total number of pages
+** in the source database at the conclusion of the most recent
+** sqlite3_backup_step().
+** ^(The values returned by these functions are only updated by
+** sqlite3_backup_step(). If the source database is modified in a way that
+** changes the size of the source database or the number of pages remaining,
+** those changes are not reflected in the output of sqlite3_backup_pagecount()
+** and sqlite3_backup_remaining() until after the next
+** sqlite3_backup_step().)^
+**
+** <b>Concurrent Usage of Database Handles</b>
+**
+** ^The source [database connection] may be used by the application for other
+** purposes while a backup operation is underway or being initialized.
+** ^If SQLite is compiled and configured to support threadsafe database
+** connections, then the source database connection may be used concurrently
+** from within other threads.
+**
+** However, the application must guarantee that the destination
+** [database connection] is not passed to any other API (by any thread) after
+** sqlite3_backup_init() is called and before the corresponding call to
+** sqlite3_backup_finish(). SQLite does not currently check to see
+** if the application incorrectly accesses the destination [database connection]
+** and so no error code is reported, but the operations may malfunction
+** nevertheless. Use of the destination database connection while a
+** backup is in progress might also also cause a mutex deadlock.
+**
+** If running in [shared cache mode], the application must
+** guarantee that the shared cache used by the destination database
+** is not accessed while the backup is running. In practice this means
+** that the application must guarantee that the disk file being
+** backed up to is not accessed by any connection within the process,
+** not just the specific connection that was passed to sqlite3_backup_init().
+**
+** The [sqlite3_backup] object itself is partially threadsafe. Multiple
+** threads may safely make multiple concurrent calls to sqlite3_backup_step().
+** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
+** APIs are not strictly speaking threadsafe. If they are invoked at the
+** same time as another thread is invoking sqlite3_backup_step() it is
+** possible that they return invalid values.
+*/
+SQLITE_API sqlite3_backup *sqlite3_backup_init(
+ sqlite3 *pDest, /* Destination database handle */
+ const char *zDestName, /* Destination database name */
+ sqlite3 *pSource, /* Source database handle */
+ const char *zSourceName /* Source database name */
+);
+SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
+SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
+SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
+SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
+
+/*
+** CAPI3REF: Unlock Notification
+** METHOD: sqlite3
+**
+** ^When running in shared-cache mode, a database operation may fail with
+** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
+** individual tables within the shared-cache cannot be obtained. See
+** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
+** ^This API may be used to register a callback that SQLite will invoke
+** when the connection currently holding the required lock relinquishes it.
+** ^This API is only available if the library was compiled with the
+** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
+**
+** See Also: [Using the SQLite Unlock Notification Feature].
+**
+** ^Shared-cache locks are released when a database connection concludes
+** its current transaction, either by committing it or rolling it back.
+**
+** ^When a connection (known as the blocked connection) fails to obtain a
+** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
+** identity of the database connection (the blocking connection) that
+** has locked the required resource is stored internally. ^After an
+** application receives an SQLITE_LOCKED error, it may call the
+** sqlite3_unlock_notify() method with the blocked connection handle as
+** the first argument to register for a callback that will be invoked
+** when the blocking connections current transaction is concluded. ^The
+** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
+** call that concludes the blocking connection's transaction.
+**
+** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
+** there is a chance that the blocking connection will have already
+** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
+** If this happens, then the specified callback is invoked immediately,
+** from within the call to sqlite3_unlock_notify().)^
+**
+** ^If the blocked connection is attempting to obtain a write-lock on a
+** shared-cache table, and more than one other connection currently holds
+** a read-lock on the same table, then SQLite arbitrarily selects one of
+** the other connections to use as the blocking connection.
+**
+** ^(There may be at most one unlock-notify callback registered by a
+** blocked connection. If sqlite3_unlock_notify() is called when the
+** blocked connection already has a registered unlock-notify callback,
+** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
+** called with a NULL pointer as its second argument, then any existing
+** unlock-notify callback is canceled. ^The blocked connections
+** unlock-notify callback may also be canceled by closing the blocked
+** connection using [sqlite3_close()].
+**
+** The unlock-notify callback is not reentrant. If an application invokes
+** any sqlite3_xxx API functions from within an unlock-notify callback, a
+** crash or deadlock may be the result.
+**
+** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
+** returns SQLITE_OK.
+**
+** <b>Callback Invocation Details</b>
+**
+** When an unlock-notify callback is registered, the application provides a
+** single void* pointer that is passed to the callback when it is invoked.
+** However, the signature of the callback function allows SQLite to pass
+** it an array of void* context pointers. The first argument passed to
+** an unlock-notify callback is a pointer to an array of void* pointers,
+** and the second is the number of entries in the array.
+**
+** When a blocking connection's transaction is concluded, there may be
+** more than one blocked connection that has registered for an unlock-notify
+** callback. ^If two or more such blocked connections have specified the
+** same callback function, then instead of invoking the callback function
+** multiple times, it is invoked once with the set of void* context pointers
+** specified by the blocked connections bundled together into an array.
+** This gives the application an opportunity to prioritize any actions
+** related to the set of unblocked database connections.
+**
+** <b>Deadlock Detection</b>
+**
+** Assuming that after registering for an unlock-notify callback a
+** database waits for the callback to be issued before taking any further
+** action (a reasonable assumption), then using this API may cause the
+** application to deadlock. For example, if connection X is waiting for
+** connection Y's transaction to be concluded, and similarly connection
+** Y is waiting on connection X's transaction, then neither connection
+** will proceed and the system may remain deadlocked indefinitely.
+**
+** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
+** detection. ^If a given call to sqlite3_unlock_notify() would put the
+** system in a deadlocked state, then SQLITE_LOCKED is returned and no
+** unlock-notify callback is registered. The system is said to be in
+** a deadlocked state if connection A has registered for an unlock-notify
+** callback on the conclusion of connection B's transaction, and connection
+** B has itself registered for an unlock-notify callback when connection
+** A's transaction is concluded. ^Indirect deadlock is also detected, so
+** the system is also considered to be deadlocked if connection B has
+** registered for an unlock-notify callback on the conclusion of connection
+** C's transaction, where connection C is waiting on connection A. ^Any
+** number of levels of indirection are allowed.
+**
+** <b>The "DROP TABLE" Exception</b>
+**
+** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
+** always appropriate to call sqlite3_unlock_notify(). There is however,
+** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
+** SQLite checks if there are any currently executing SELECT statements
+** that belong to the same connection. If there are, SQLITE_LOCKED is
+** returned. In this case there is no "blocking connection", so invoking
+** sqlite3_unlock_notify() results in the unlock-notify callback being
+** invoked immediately. If the application then re-attempts the "DROP TABLE"
+** or "DROP INDEX" query, an infinite loop might be the result.
+**
+** One way around this problem is to check the extended error code returned
+** by an sqlite3_step() call. ^(If there is a blocking connection, then the
+** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
+** the special "DROP TABLE/INDEX" case, the extended error code is just
+** SQLITE_LOCKED.)^
+*/
+SQLITE_API int sqlite3_unlock_notify(
+ sqlite3 *pBlocked, /* Waiting connection */
+ void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
+ void *pNotifyArg /* Argument to pass to xNotify */
+);
+
+
+/*
+** CAPI3REF: String Comparison
+**
+** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
+** and extensions to compare the contents of two buffers containing UTF-8
+** strings in a case-independent fashion, using the same definition of "case
+** independence" that SQLite uses internally when comparing identifiers.
+*/
+SQLITE_API int sqlite3_stricmp(const char *, const char *);
+SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
+
+/*
+** CAPI3REF: String Globbing
+*
+** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
+** string X matches the [GLOB] pattern P.
+** ^The definition of [GLOB] pattern matching used in
+** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
+** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
+** is case sensitive.
+**
+** Note that this routine returns zero on a match and non-zero if the strings
+** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
+**
+** See also: [sqlite3_strlike()].
+*/
+SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
+
+/*
+** CAPI3REF: String LIKE Matching
+*
+** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
+** string X matches the [LIKE] pattern P with escape character E.
+** ^The definition of [LIKE] pattern matching used in
+** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
+** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
+** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
+** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
+** insensitive - equivalent upper and lower case ASCII characters match
+** one another.
+**
+** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
+** only ASCII characters are case folded.
+**
+** Note that this routine returns zero on a match and non-zero if the strings
+** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
+**
+** See also: [sqlite3_strglob()].
+*/
+SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
+
+/*
+** CAPI3REF: Error Logging Interface
+**
+** ^The [sqlite3_log()] interface writes a message into the [error log]
+** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
+** ^If logging is enabled, the zFormat string and subsequent arguments are
+** used with [sqlite3_snprintf()] to generate the final output string.
+**
+** The sqlite3_log() interface is intended for use by extensions such as
+** virtual tables, collating functions, and SQL functions. While there is
+** nothing to prevent an application from calling sqlite3_log(), doing so
+** is considered bad form.
+**
+** The zFormat string must not be NULL.
+**
+** To avoid deadlocks and other threading problems, the sqlite3_log() routine
+** will not use dynamically allocated memory. The log message is stored in
+** a fixed-length buffer on the stack. If the log message is longer than
+** a few hundred characters, it will be truncated to the length of the
+** buffer.
+*/
+SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
+
+/*
+** CAPI3REF: Write-Ahead Log Commit Hook
+** METHOD: sqlite3
+**
+** ^The [sqlite3_wal_hook()] function is used to register a callback that
+** is invoked each time data is committed to a database in wal mode.
+**
+** ^(The callback is invoked by SQLite after the commit has taken place and
+** the associated write-lock on the database released)^, so the implementation
+** may read, write or [checkpoint] the database as required.
+**
+** ^The first parameter passed to the callback function when it is invoked
+** is a copy of the third parameter passed to sqlite3_wal_hook() when
+** registering the callback. ^The second is a copy of the database handle.
+** ^The third parameter is the name of the database that was written to -
+** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
+** is the number of pages currently in the write-ahead log file,
+** including those that were just committed.
+**
+** The callback function should normally return [SQLITE_OK]. ^If an error
+** code is returned, that error will propagate back up through the
+** SQLite code base to cause the statement that provoked the callback
+** to report an error, though the commit will have still occurred. If the
+** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
+** that does not correspond to any valid SQLite error code, the results
+** are undefined.
+**
+** A single database handle may have at most a single write-ahead log callback
+** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
+** previously registered write-ahead log callback. ^Note that the
+** [sqlite3_wal_autocheckpoint()] interface and the
+** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
+** overwrite any prior [sqlite3_wal_hook()] settings.
+*/
+SQLITE_API void *sqlite3_wal_hook(
+ sqlite3*,
+ int(*)(void *,sqlite3*,const char*,int),
+ void*
+);
+
+/*
+** CAPI3REF: Configure an auto-checkpoint
+** METHOD: sqlite3
+**
+** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
+** [sqlite3_wal_hook()] that causes any database on [database connection] D
+** to automatically [checkpoint]
+** after committing a transaction if there are N or
+** more frames in the [write-ahead log] file. ^Passing zero or
+** a negative value as the nFrame parameter disables automatic
+** checkpoints entirely.
+**
+** ^The callback registered by this function replaces any existing callback
+** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
+** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
+** configured by this function.
+**
+** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
+** from SQL.
+**
+** ^Checkpoints initiated by this mechanism are
+** [sqlite3_wal_checkpoint_v2|PASSIVE].
+**
+** ^Every new [database connection] defaults to having the auto-checkpoint
+** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
+** pages. The use of this interface
+** is only necessary if the default setting is found to be suboptimal
+** for a particular application.
+*/
+SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
+
+/*
+** CAPI3REF: Checkpoint a database
+** METHOD: sqlite3
+**
+** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
+** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
+**
+** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
+** [write-ahead log] for database X on [database connection] D to be
+** transferred into the database file and for the write-ahead log to
+** be reset. See the [checkpointing] documentation for addition
+** information.
+**
+** This interface used to be the only way to cause a checkpoint to
+** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
+** interface was added. This interface is retained for backwards
+** compatibility and as a convenience for applications that need to manually
+** start a callback but which do not need the full power (and corresponding
+** complication) of [sqlite3_wal_checkpoint_v2()].
+*/
+SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
+
+/*
+** CAPI3REF: Checkpoint a database
+** METHOD: sqlite3
+**
+** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
+** operation on database X of [database connection] D in mode M. Status
+** information is written back into integers pointed to by L and C.)^
+** ^(The M parameter must be a valid [checkpoint mode]:)^
+**
+** <dl>
+** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
+** ^Checkpoint as many frames as possible without waiting for any database
+** readers or writers to finish, then sync the database file if all frames
+** in the log were checkpointed. ^The [busy-handler callback]
+** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
+** ^On the other hand, passive mode might leave the checkpoint unfinished
+** if there are concurrent readers or writers.
+**
+** <dt>SQLITE_CHECKPOINT_FULL<dd>
+** ^This mode blocks (it invokes the
+** [sqlite3_busy_handler|busy-handler callback]) until there is no
+** database writer and all readers are reading from the most recent database
+** snapshot. ^It then checkpoints all frames in the log file and syncs the
+** database file. ^This mode blocks new database writers while it is pending,
+** but new database readers are allowed to continue unimpeded.
+**
+** <dt>SQLITE_CHECKPOINT_RESTART<dd>
+** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
+** that after checkpointing the log file it blocks (calls the
+** [busy-handler callback])
+** until all readers are reading from the database file only. ^This ensures
+** that the next writer will restart the log file from the beginning.
+** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
+** database writer attempts while it is pending, but does not impede readers.
+**
+** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
+** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
+** addition that it also truncates the log file to zero bytes just prior
+** to a successful return.
+** </dl>
+**
+** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
+** the log file or to -1 if the checkpoint could not run because
+** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
+** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
+** log file (including any that were already checkpointed before the function
+** was called) or to -1 if the checkpoint could not run due to an error or
+** because the database is not in WAL mode. ^Note that upon successful
+** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
+** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
+**
+** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
+** any other process is running a checkpoint operation at the same time, the
+** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
+** busy-handler configured, it will not be invoked in this case.
+**
+** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
+** exclusive "writer" lock on the database file. ^If the writer lock cannot be
+** obtained immediately, and a busy-handler is configured, it is invoked and
+** the writer lock retried until either the busy-handler returns 0 or the lock
+** is successfully obtained. ^The busy-handler is also invoked while waiting for
+** database readers as described above. ^If the busy-handler returns 0 before
+** the writer lock is obtained or while waiting for database readers, the
+** checkpoint operation proceeds from that point in the same way as
+** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
+** without blocking any further. ^SQLITE_BUSY is returned in this case.
+**
+** ^If parameter zDb is NULL or points to a zero length string, then the
+** specified operation is attempted on all WAL databases [attached] to
+** [database connection] db. In this case the
+** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
+** an SQLITE_BUSY error is encountered when processing one or more of the
+** attached WAL databases, the operation is still attempted on any remaining
+** attached databases and SQLITE_BUSY is returned at the end. ^If any other
+** error occurs while processing an attached database, processing is abandoned
+** and the error code is returned to the caller immediately. ^If no error
+** (SQLITE_BUSY or otherwise) is encountered while processing the attached
+** databases, SQLITE_OK is returned.
+**
+** ^If database zDb is the name of an attached database that is not in WAL
+** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
+** zDb is not NULL (or a zero length string) and is not the name of any
+** attached database, SQLITE_ERROR is returned to the caller.
+**
+** ^Unless it returns SQLITE_MISUSE,
+** the sqlite3_wal_checkpoint_v2() interface
+** sets the error information that is queried by
+** [sqlite3_errcode()] and [sqlite3_errmsg()].
+**
+** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
+** from SQL.
+*/
+SQLITE_API int sqlite3_wal_checkpoint_v2(
+ sqlite3 *db, /* Database handle */
+ const char *zDb, /* Name of attached database (or NULL) */
+ int eMode, /* SQLITE_CHECKPOINT_* value */
+ int *pnLog, /* OUT: Size of WAL log in frames */
+ int *pnCkpt /* OUT: Total number of frames checkpointed */
+);
+
+/*
+** CAPI3REF: Checkpoint Mode Values
+** KEYWORDS: {checkpoint mode}
+**
+** These constants define all valid values for the "checkpoint mode" passed
+** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
+** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
+** meaning of each of these checkpoint modes.
+*/
+#define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
+#define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
+#define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
+#define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
+
+/*
+** CAPI3REF: Virtual Table Interface Configuration
+**
+** This function may be called by either the [xConnect] or [xCreate] method
+** of a [virtual table] implementation to configure
+** various facets of the virtual table interface.
+**
+** If this interface is invoked outside the context of an xConnect or
+** xCreate virtual table method then the behavior is undefined.
+**
+** In the call sqlite3_vtab_config(D,C,...) the D parameter is the
+** [database connection] in which the virtual table is being created and
+** which is passed in as the first argument to the [xConnect] or [xCreate]
+** method that is invoking sqlite3_vtab_config(). The C parameter is one
+** of the [virtual table configuration options]. The presence and meaning
+** of parameters after C depend on which [virtual table configuration option]
+** is used.
+*/
+SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
+
+/*
+** CAPI3REF: Virtual Table Configuration Options
+** KEYWORDS: {virtual table configuration options}
+** KEYWORDS: {virtual table configuration option}
+**
+** These macros define the various options to the
+** [sqlite3_vtab_config()] interface that [virtual table] implementations
+** can use to customize and optimize their behavior.
+**
+** <dl>
+** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]
+** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT</dt>
+** <dd>Calls of the form
+** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
+** where X is an integer. If X is zero, then the [virtual table] whose
+** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
+** support constraints. In this configuration (which is the default) if
+** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
+** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
+** specified as part of the users SQL statement, regardless of the actual
+** ON CONFLICT mode specified.
+**
+** If X is non-zero, then the virtual table implementation guarantees
+** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
+** any modifications to internal or persistent data structures have been made.
+** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
+** is able to roll back a statement or database transaction, and abandon
+** or continue processing the current SQL statement as appropriate.
+** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
+** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
+** had been ABORT.
+**
+** Virtual table implementations that are required to handle OR REPLACE
+** must do so within the [xUpdate] method. If a call to the
+** [sqlite3_vtab_on_conflict()] function indicates that the current ON
+** CONFLICT policy is REPLACE, the virtual table implementation should
+** silently replace the appropriate rows within the xUpdate callback and
+** return SQLITE_OK. Or, if this is not possible, it may return
+** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
+** constraint handling.
+** </dd>
+**
+** [[SQLITE_VTAB_DIRECTONLY]]<dt>SQLITE_VTAB_DIRECTONLY</dt>
+** <dd>Calls of the form
+** [sqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the
+** the [xConnect] or [xCreate] methods of a [virtual table] implmentation
+** prohibits that virtual table from being used from within triggers and
+** views.
+** </dd>
+**
+** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>
+** <dd>Calls of the form
+** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the
+** the [xConnect] or [xCreate] methods of a [virtual table] implmentation
+** identify that virtual table as being safe to use from within triggers
+** and views. Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the
+** virtual table can do no serious harm even if it is controlled by a
+** malicious hacker. Developers should avoid setting the SQLITE_VTAB_INNOCUOUS
+** flag unless absolutely necessary.
+** </dd>
+** </dl>
+*/
+#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
+#define SQLITE_VTAB_INNOCUOUS 2
+#define SQLITE_VTAB_DIRECTONLY 3
+
+/*
+** CAPI3REF: Determine The Virtual Table Conflict Policy
+**
+** This function may only be called from within a call to the [xUpdate] method
+** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
+** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
+** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
+** of the SQL statement that triggered the call to the [xUpdate] method of the
+** [virtual table].
+*/
+SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
+
+/*
+** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
+**
+** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
+** method of a [virtual table], then it returns true if and only if the
+** column is being fetched as part of an UPDATE operation during which the
+** column value will not change. Applications might use this to substitute
+** a return value that is less expensive to compute and that the corresponding
+** [xUpdate] method understands as a "no-change" value.
+**
+** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
+** the column is not changed by the UPDATE statement, then the xColumn
+** method can optionally return without setting a result, without calling
+** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
+** In that case, [sqlite3_value_nochange(X)] will return true for the
+** same column in the [xUpdate] method.
+*/
+SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
+
+/*
+** CAPI3REF: Determine The Collation For a Virtual Table Constraint
+**
+** This function may only be called from within a call to the [xBestIndex]
+** method of a [virtual table].
+**
+** The first argument must be the sqlite3_index_info object that is the
+** first parameter to the xBestIndex() method. The second argument must be
+** an index into the aConstraint[] array belonging to the sqlite3_index_info
+** structure passed to xBestIndex. This function returns a pointer to a buffer
+** containing the name of the collation sequence for the corresponding
+** constraint.
+*/
+SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
+
+/*
+** CAPI3REF: Conflict resolution modes
+** KEYWORDS: {conflict resolution mode}
+**
+** These constants are returned by [sqlite3_vtab_on_conflict()] to
+** inform a [virtual table] implementation what the [ON CONFLICT] mode
+** is for the SQL statement being evaluated.
+**
+** Note that the [SQLITE_IGNORE] constant is also used as a potential
+** return value from the [sqlite3_set_authorizer()] callback and that
+** [SQLITE_ABORT] is also a [result code].
+*/
+#define SQLITE_ROLLBACK 1
+/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
+#define SQLITE_FAIL 3
+/* #define SQLITE_ABORT 4 // Also an error code */
+#define SQLITE_REPLACE 5
+
+/*
+** CAPI3REF: Prepared Statement Scan Status Opcodes
+** KEYWORDS: {scanstatus options}
+**
+** The following constants can be used for the T parameter to the
+** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
+** different metric for sqlite3_stmt_scanstatus() to return.
+**
+** When the value returned to V is a string, space to hold that string is
+** managed by the prepared statement S and will be automatically freed when
+** S is finalized.
+**
+** <dl>
+** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
+** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be
+** set to the total number of times that the X-th loop has run.</dd>
+**
+** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
+** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be set
+** to the total number of rows examined by all iterations of the X-th loop.</dd>
+**
+** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
+** <dd>^The "double" variable pointed to by the V parameter will be set to the
+** query planner's estimate for the average number of rows output from each
+** iteration of the X-th loop. If the query planner's estimates was accurate,
+** then this value will approximate the quotient NVISIT/NLOOP and the
+** product of this value for all prior loops with the same SELECTID will
+** be the NLOOP value for the current loop.
+**
+** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
+** <dd>^The "const char *" variable pointed to by the V parameter will be set
+** to a zero-terminated UTF-8 string containing the name of the index or table
+** used for the X-th loop.
+**
+** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
+** <dd>^The "const char *" variable pointed to by the V parameter will be set
+** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
+** description for the X-th loop.
+**
+** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
+** <dd>^The "int" variable pointed to by the V parameter will be set to the
+** "select-id" for the X-th loop. The select-id identifies which query or
+** subquery the loop is part of. The main query has a select-id of zero.
+** The select-id is the same value as is output in the first column
+** of an [EXPLAIN QUERY PLAN] query.
+** </dl>
+*/
+#define SQLITE_SCANSTAT_NLOOP 0
+#define SQLITE_SCANSTAT_NVISIT 1
+#define SQLITE_SCANSTAT_EST 2
+#define SQLITE_SCANSTAT_NAME 3
+#define SQLITE_SCANSTAT_EXPLAIN 4
+#define SQLITE_SCANSTAT_SELECTID 5
+
+/*
+** CAPI3REF: Prepared Statement Scan Status
+** METHOD: sqlite3_stmt
+**
+** This interface returns information about the predicted and measured
+** performance for pStmt. Advanced applications can use this
+** interface to compare the predicted and the measured performance and
+** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
+**
+** Since this interface is expected to be rarely used, it is only
+** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
+** compile-time option.
+**
+** The "iScanStatusOp" parameter determines which status information to return.
+** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
+** of this interface is undefined.
+** ^The requested measurement is written into a variable pointed to by
+** the "pOut" parameter.
+** Parameter "idx" identifies the specific loop to retrieve statistics for.
+** Loops are numbered starting from zero. ^If idx is out of range - less than
+** zero or greater than or equal to the total number of loops used to implement
+** the statement - a non-zero value is returned and the variable that pOut
+** points to is unchanged.
+**
+** ^Statistics might not be available for all loops in all statements. ^In cases
+** where there exist loops with no available statistics, this function behaves
+** as if the loop did not exist - it returns non-zero and leave the variable
+** that pOut points to unchanged.
+**
+** See also: [sqlite3_stmt_scanstatus_reset()]
+*/
+SQLITE_API int sqlite3_stmt_scanstatus(
+ sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
+ int idx, /* Index of loop to report on */
+ int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
+ void *pOut /* Result written here */
+);
+
+/*
+** CAPI3REF: Zero Scan-Status Counters
+** METHOD: sqlite3_stmt
+**
+** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
+**
+** This API is only available if the library is built with pre-processor
+** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
+*/
+SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
+
+/*
+** CAPI3REF: Flush caches to disk mid-transaction
+** METHOD: sqlite3
+**
+** ^If a write-transaction is open on [database connection] D when the
+** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
+** pages in the pager-cache that are not currently in use are written out
+** to disk. A dirty page may be in use if a database cursor created by an
+** active SQL statement is reading from it, or if it is page 1 of a database
+** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
+** interface flushes caches for all schemas - "main", "temp", and
+** any [attached] databases.
+**
+** ^If this function needs to obtain extra database locks before dirty pages
+** can be flushed to disk, it does so. ^If those locks cannot be obtained
+** immediately and there is a busy-handler callback configured, it is invoked
+** in the usual manner. ^If the required lock still cannot be obtained, then
+** the database is skipped and an attempt made to flush any dirty pages
+** belonging to the next (if any) database. ^If any databases are skipped
+** because locks cannot be obtained, but no other error occurs, this
+** function returns SQLITE_BUSY.
+**
+** ^If any other error occurs while flushing dirty pages to disk (for
+** example an IO error or out-of-memory condition), then processing is
+** abandoned and an SQLite [error code] is returned to the caller immediately.
+**
+** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
+**
+** ^This function does not set the database handle error code or message
+** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
+*/
+SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
+
+/*
+** CAPI3REF: The pre-update hook.
+** METHOD: sqlite3
+**
+** ^These interfaces are only available if SQLite is compiled using the
+** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
+**
+** ^The [sqlite3_preupdate_hook()] interface registers a callback function
+** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
+** on a database table.
+** ^At most one preupdate hook may be registered at a time on a single
+** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
+** the previous setting.
+** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
+** with a NULL pointer as the second parameter.
+** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
+** the first parameter to callbacks.
+**
+** ^The preupdate hook only fires for changes to real database tables; the
+** preupdate hook is not invoked for changes to [virtual tables] or to
+** system tables like sqlite_sequence or sqlite_stat1.
+**
+** ^The second parameter to the preupdate callback is a pointer to
+** the [database connection] that registered the preupdate hook.
+** ^The third parameter to the preupdate callback is one of the constants
+** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
+** kind of update operation that is about to occur.
+** ^(The fourth parameter to the preupdate callback is the name of the
+** database within the database connection that is being modified. This
+** will be "main" for the main database or "temp" for TEMP tables or
+** the name given after the AS keyword in the [ATTACH] statement for attached
+** databases.)^
+** ^The fifth parameter to the preupdate callback is the name of the
+** table that is being modified.
+**
+** For an UPDATE or DELETE operation on a [rowid table], the sixth
+** parameter passed to the preupdate callback is the initial [rowid] of the
+** row being modified or deleted. For an INSERT operation on a rowid table,
+** or any operation on a WITHOUT ROWID table, the value of the sixth
+** parameter is undefined. For an INSERT or UPDATE on a rowid table the
+** seventh parameter is the final rowid value of the row being inserted
+** or updated. The value of the seventh parameter passed to the callback
+** function is not defined for operations on WITHOUT ROWID tables, or for
+** DELETE operations on rowid tables.
+**
+** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
+** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
+** provide additional information about a preupdate event. These routines
+** may only be called from within a preupdate callback. Invoking any of
+** these routines from outside of a preupdate callback or with a
+** [database connection] pointer that is different from the one supplied
+** to the preupdate callback results in undefined and probably undesirable
+** behavior.
+**
+** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
+** in the row that is being inserted, updated, or deleted.
+**
+** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
+** a [protected sqlite3_value] that contains the value of the Nth column of
+** the table row before it is updated. The N parameter must be between 0
+** and one less than the number of columns or the behavior will be
+** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
+** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
+** behavior is undefined. The [sqlite3_value] that P points to
+** will be destroyed when the preupdate callback returns.
+**
+** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
+** a [protected sqlite3_value] that contains the value of the Nth column of
+** the table row after it is updated. The N parameter must be between 0
+** and one less than the number of columns or the behavior will be
+** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
+** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
+** behavior is undefined. The [sqlite3_value] that P points to
+** will be destroyed when the preupdate callback returns.
+**
+** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
+** callback was invoked as a result of a direct insert, update, or delete
+** operation; or 1 for inserts, updates, or deletes invoked by top-level
+** triggers; or 2 for changes resulting from triggers called by top-level
+** triggers; and so forth.
+**
+** See also: [sqlite3_update_hook()]
+*/
+#if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
+SQLITE_API void *sqlite3_preupdate_hook(
+ sqlite3 *db,
+ void(*xPreUpdate)(
+ void *pCtx, /* Copy of third arg to preupdate_hook() */
+ sqlite3 *db, /* Database handle */
+ int op, /* SQLITE_UPDATE, DELETE or INSERT */
+ char const *zDb, /* Database name */
+ char const *zName, /* Table name */
+ sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
+ sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
+ ),
+ void*
+);
+SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
+SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
+SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
+SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
+#endif
+
+/*
+** CAPI3REF: Low-level system error code
+** METHOD: sqlite3
+**
+** ^Attempt to return the underlying operating system error code or error
+** number that caused the most recent I/O error or failure to open a file.
+** The return value is OS-dependent. For example, on unix systems, after
+** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
+** called to get back the underlying "errno" that caused the problem, such
+** as ENOSPC, EAUTH, EISDIR, and so forth.
+*/
+SQLITE_API int sqlite3_system_errno(sqlite3*);
+
+/*
+** CAPI3REF: Database Snapshot
+** KEYWORDS: {snapshot} {sqlite3_snapshot}
+**
+** An instance of the snapshot object records the state of a [WAL mode]
+** database for some specific point in history.
+**
+** In [WAL mode], multiple [database connections] that are open on the
+** same database file can each be reading a different historical version
+** of the database file. When a [database connection] begins a read
+** transaction, that connection sees an unchanging copy of the database
+** as it existed for the point in time when the transaction first started.
+** Subsequent changes to the database from other connections are not seen
+** by the reader until a new read transaction is started.
+**
+** The sqlite3_snapshot object records state information about an historical
+** version of the database file so that it is possible to later open a new read
+** transaction that sees that historical version of the database rather than
+** the most recent version.
+*/
+typedef struct sqlite3_snapshot {
+ unsigned char hidden[48];
+} sqlite3_snapshot;
+
+/*
+** CAPI3REF: Record A Database Snapshot
+** CONSTRUCTOR: sqlite3_snapshot
+**
+** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
+** new [sqlite3_snapshot] object that records the current state of
+** schema S in database connection D. ^On success, the
+** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
+** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
+** If there is not already a read-transaction open on schema S when
+** this function is called, one is opened automatically.
+**
+** The following must be true for this function to succeed. If any of
+** the following statements are false when sqlite3_snapshot_get() is
+** called, SQLITE_ERROR is returned. The final value of *P is undefined
+** in this case.
+**
+** <ul>
+** <li> The database handle must not be in [autocommit mode].
+**
+** <li> Schema S of [database connection] D must be a [WAL mode] database.
+**
+** <li> There must not be a write transaction open on schema S of database
+** connection D.
+**
+** <li> One or more transactions must have been written to the current wal
+** file since it was created on disk (by any connection). This means
+** that a snapshot cannot be taken on a wal mode database with no wal
+** file immediately after it is first opened. At least one transaction
+** must be written to it first.
+** </ul>
+**
+** This function may also return SQLITE_NOMEM. If it is called with the
+** database handle in autocommit mode but fails for some other reason,
+** whether or not a read transaction is opened on schema S is undefined.
+**
+** The [sqlite3_snapshot] object returned from a successful call to
+** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
+** to avoid a memory leak.
+**
+** The [sqlite3_snapshot_get()] interface is only available when the
+** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
+*/
+SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
+ sqlite3 *db,
+ const char *zSchema,
+ sqlite3_snapshot **ppSnapshot
+);
+
+/*
+** CAPI3REF: Start a read transaction on an historical snapshot
+** METHOD: sqlite3_snapshot
+**
+** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read
+** transaction or upgrades an existing one for schema S of
+** [database connection] D such that the read transaction refers to
+** historical [snapshot] P, rather than the most recent change to the
+** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK
+** on success or an appropriate [error code] if it fails.
+**
+** ^In order to succeed, the database connection must not be in
+** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there
+** is already a read transaction open on schema S, then the database handle
+** must have no active statements (SELECT statements that have been passed
+** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()).
+** SQLITE_ERROR is returned if either of these conditions is violated, or
+** if schema S does not exist, or if the snapshot object is invalid.
+**
+** ^A call to sqlite3_snapshot_open() will fail to open if the specified
+** snapshot has been overwritten by a [checkpoint]. In this case
+** SQLITE_ERROR_SNAPSHOT is returned.
+**
+** If there is already a read transaction open when this function is
+** invoked, then the same read transaction remains open (on the same
+** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT
+** is returned. If another error code - for example SQLITE_PROTOCOL or an
+** SQLITE_IOERR error code - is returned, then the final state of the
+** read transaction is undefined. If SQLITE_OK is returned, then the
+** read transaction is now open on database snapshot P.
+**
+** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
+** database connection D does not know that the database file for
+** schema S is in [WAL mode]. A database connection might not know
+** that the database file is in [WAL mode] if there has been no prior
+** I/O on that database connection, or if the database entered [WAL mode]
+** after the most recent I/O on the database connection.)^
+** (Hint: Run "[PRAGMA application_id]" against a newly opened
+** database connection in order to make it ready to use snapshots.)
+**
+** The [sqlite3_snapshot_open()] interface is only available when the
+** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
+*/
+SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
+ sqlite3 *db,
+ const char *zSchema,
+ sqlite3_snapshot *pSnapshot
+);
+
+/*
+** CAPI3REF: Destroy a snapshot
+** DESTRUCTOR: sqlite3_snapshot
+**
+** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
+** The application must eventually free every [sqlite3_snapshot] object
+** using this routine to avoid a memory leak.
+**
+** The [sqlite3_snapshot_free()] interface is only available when the
+** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
+*/
+SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
+
+/*
+** CAPI3REF: Compare the ages of two snapshot handles.
+** METHOD: sqlite3_snapshot
+**
+** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
+** of two valid snapshot handles.
+**
+** If the two snapshot handles are not associated with the same database
+** file, the result of the comparison is undefined.
+**
+** Additionally, the result of the comparison is only valid if both of the
+** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
+** last time the wal file was deleted. The wal file is deleted when the
+** database is changed back to rollback mode or when the number of database
+** clients drops to zero. If either snapshot handle was obtained before the
+** wal file was last deleted, the value returned by this function
+** is undefined.
+**
+** Otherwise, this API returns a negative value if P1 refers to an older
+** snapshot than P2, zero if the two handles refer to the same database
+** snapshot, and a positive value if P1 is a newer snapshot than P2.
+**
+** This interface is only available if SQLite is compiled with the
+** [SQLITE_ENABLE_SNAPSHOT] option.
+*/
+SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
+ sqlite3_snapshot *p1,
+ sqlite3_snapshot *p2
+);
+
+/*
+** CAPI3REF: Recover snapshots from a wal file
+** METHOD: sqlite3_snapshot
+**
+** If a [WAL file] remains on disk after all database connections close
+** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control]
+** or because the last process to have the database opened exited without
+** calling [sqlite3_close()]) and a new connection is subsequently opened
+** on that database and [WAL file], the [sqlite3_snapshot_open()] interface
+** will only be able to open the last transaction added to the WAL file
+** even though the WAL file contains other valid transactions.
+**
+** This function attempts to scan the WAL file associated with database zDb
+** of database handle db and make all valid snapshots available to
+** sqlite3_snapshot_open(). It is an error if there is already a read
+** transaction open on the database, or if the database is not a WAL mode
+** database.
+**
+** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
+**
+** This interface is only available if SQLite is compiled with the
+** [SQLITE_ENABLE_SNAPSHOT] option.
+*/
+SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
+
+/*
+** CAPI3REF: Serialize a database
+**
+** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory
+** that is a serialization of the S database on [database connection] D.
+** If P is not a NULL pointer, then the size of the database in bytes
+** is written into *P.
+**
+** For an ordinary on-disk database file, the serialization is just a
+** copy of the disk file. For an in-memory database or a "TEMP" database,
+** the serialization is the same sequence of bytes which would be written
+** to disk if that database where backed up to disk.
+**
+** The usual case is that sqlite3_serialize() copies the serialization of
+** the database into memory obtained from [sqlite3_malloc64()] and returns
+** a pointer to that memory. The caller is responsible for freeing the
+** returned value to avoid a memory leak. However, if the F argument
+** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations
+** are made, and the sqlite3_serialize() function will return a pointer
+** to the contiguous memory representation of the database that SQLite
+** is currently using for that database, or NULL if the no such contiguous
+** memory representation of the database exists. A contiguous memory
+** representation of the database will usually only exist if there has
+** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
+** values of D and S.
+** The size of the database is written into *P even if the
+** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
+** of the database exists.
+**
+** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
+** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
+** allocation error occurs.
+**
+** This interface is only available if SQLite is compiled with the
+** [SQLITE_ENABLE_DESERIALIZE] option.
+*/
+SQLITE_API unsigned char *sqlite3_serialize(
+ sqlite3 *db, /* The database connection */
+ const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */
+ sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */
+ unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */
+);
+
+/*
+** CAPI3REF: Flags for sqlite3_serialize
+**
+** Zero or more of the following constants can be OR-ed together for
+** the F argument to [sqlite3_serialize(D,S,P,F)].
+**
+** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return
+** a pointer to contiguous in-memory database that it is currently using,
+** without making a copy of the database. If SQLite is not currently using
+** a contiguous in-memory database, then this option causes
+** [sqlite3_serialize()] to return a NULL pointer. SQLite will only be
+** using a contiguous in-memory database if it has been initialized by a
+** prior call to [sqlite3_deserialize()].
+*/
+#define SQLITE_SERIALIZE_NOCOPY 0x001 /* Do no memory allocations */
+
+/*
+** CAPI3REF: Deserialize a database
+**
+** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
+** [database connection] D to disconnect from database S and then
+** reopen S as an in-memory database based on the serialization contained
+** in P. The serialized database P is N bytes in size. M is the size of
+** the buffer P, which might be larger than N. If M is larger than N, and
+** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is
+** permitted to add content to the in-memory database as long as the total
+** size does not exceed M bytes.
+**
+** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
+** invoke sqlite3_free() on the serialization buffer when the database
+** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
+** SQLite will try to increase the buffer size using sqlite3_realloc64()
+** if writes on the database cause it to grow larger than M bytes.
+**
+** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
+** database is currently in a read transaction or is involved in a backup
+** operation.
+**
+** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
+** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
+** [sqlite3_free()] is invoked on argument P prior to returning.
+**
+** This interface is only available if SQLite is compiled with the
+** [SQLITE_ENABLE_DESERIALIZE] option.
+*/
+SQLITE_API int sqlite3_deserialize(
+ sqlite3 *db, /* The database connection */
+ const char *zSchema, /* Which DB to reopen with the deserialization */
+ unsigned char *pData, /* The serialized database content */
+ sqlite3_int64 szDb, /* Number bytes in the deserialization */
+ sqlite3_int64 szBuf, /* Total size of buffer pData[] */
+ unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
+);
+
+/*
+** CAPI3REF: Flags for sqlite3_deserialize()
+**
+** The following are allowed values for 6th argument (the F argument) to
+** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.
+**
+** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization
+** in the P argument is held in memory obtained from [sqlite3_malloc64()]
+** and that SQLite should take ownership of this memory and automatically
+** free it when it has finished using it. Without this flag, the caller
+** is responsible for freeing any dynamically allocated memory.
+**
+** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to
+** grow the size of the database using calls to [sqlite3_realloc64()]. This
+** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.
+** Without this flag, the deserialized database cannot increase in size beyond
+** the number of bytes specified by the M parameter.
+**
+** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database
+** should be treated as read-only.
+*/
+#define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */
+#define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */
+#define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */
+
+/*
+** Undo the hack that converts floating point types to integer for
+** builds on processors without floating point support.
+*/
+#ifdef SQLITE_OMIT_FLOATING_POINT
+# undef double
+#endif
+
+#ifdef __cplusplus
+} /* End of the 'extern "C"' block */
+#endif
+#endif /* SQLITE3_H */
+
+/******** Begin file sqlite3rtree.h *********/
+/*
+** 2010 August 30
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+*/
+
+#ifndef _SQLITE3RTREE_H_
+#define _SQLITE3RTREE_H_
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
+typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
+
+/* The double-precision datatype used by RTree depends on the
+** SQLITE_RTREE_INT_ONLY compile-time option.
+*/
+#ifdef SQLITE_RTREE_INT_ONLY
+ typedef sqlite3_int64 sqlite3_rtree_dbl;
+#else
+ typedef double sqlite3_rtree_dbl;
+#endif
+
+/*
+** Register a geometry callback named zGeom that can be used as part of an
+** R-Tree geometry query as follows:
+**
+** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
+*/
+SQLITE_API int sqlite3_rtree_geometry_callback(
+ sqlite3 *db,
+ const char *zGeom,
+ int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
+ void *pContext
+);
+
+
+/*
+** A pointer to a structure of the following type is passed as the first
+** argument to callbacks registered using rtree_geometry_callback().
+*/
+struct sqlite3_rtree_geometry {
+ void *pContext; /* Copy of pContext passed to s_r_g_c() */
+ int nParam; /* Size of array aParam[] */
+ sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
+ void *pUser; /* Callback implementation user data */
+ void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
+};
+
+/*
+** Register a 2nd-generation geometry callback named zScore that can be
+** used as part of an R-Tree geometry query as follows:
+**
+** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
+*/
+SQLITE_API int sqlite3_rtree_query_callback(
+ sqlite3 *db,
+ const char *zQueryFunc,
+ int (*xQueryFunc)(sqlite3_rtree_query_info*),
+ void *pContext,
+ void (*xDestructor)(void*)
+);
+
+
+/*
+** A pointer to a structure of the following type is passed as the
+** argument to scored geometry callback registered using
+** sqlite3_rtree_query_callback().
+**
+** Note that the first 5 fields of this structure are identical to
+** sqlite3_rtree_geometry. This structure is a subclass of
+** sqlite3_rtree_geometry.
+*/
+struct sqlite3_rtree_query_info {
+ void *pContext; /* pContext from when function registered */
+ int nParam; /* Number of function parameters */
+ sqlite3_rtree_dbl *aParam; /* value of function parameters */
+ void *pUser; /* callback can use this, if desired */
+ void (*xDelUser)(void*); /* function to free pUser */
+ sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
+ unsigned int *anQueue; /* Number of pending entries in the queue */
+ int nCoord; /* Number of coordinates */
+ int iLevel; /* Level of current node or entry */
+ int mxLevel; /* The largest iLevel value in the tree */
+ sqlite3_int64 iRowid; /* Rowid for current entry */
+ sqlite3_rtree_dbl rParentScore; /* Score of parent node */
+ int eParentWithin; /* Visibility of parent node */
+ int eWithin; /* OUT: Visibility */
+ sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
+ /* The following fields are only available in 3.8.11 and later */
+ sqlite3_value **apSqlParam; /* Original SQL values of parameters */
+};
+
+/*
+** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
+*/
+#define NOT_WITHIN 0 /* Object completely outside of query region */
+#define PARTLY_WITHIN 1 /* Object partially overlaps query region */
+#define FULLY_WITHIN 2 /* Object fully contained within query region */
+
+
+#ifdef __cplusplus
+} /* end of the 'extern "C"' block */
+#endif
+
+#endif /* ifndef _SQLITE3RTREE_H_ */
+
+/******** End of sqlite3rtree.h *********/
+/******** Begin file sqlite3session.h *********/
+
+#if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
+#define __SQLITESESSION_H_ 1
+
+/*
+** Make sure we can call this stuff from C++.
+*/
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/*
+** CAPI3REF: Session Object Handle
+**
+** An instance of this object is a [session] that can be used to
+** record changes to a database.
+*/
+typedef struct sqlite3_session sqlite3_session;
+
+/*
+** CAPI3REF: Changeset Iterator Handle
+**
+** An instance of this object acts as a cursor for iterating
+** over the elements of a [changeset] or [patchset].
+*/
+typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
+
+/*
+** CAPI3REF: Create A New Session Object
+** CONSTRUCTOR: sqlite3_session
+**
+** Create a new session object attached to database handle db. If successful,
+** a pointer to the new object is written to *ppSession and SQLITE_OK is
+** returned. If an error occurs, *ppSession is set to NULL and an SQLite
+** error code (e.g. SQLITE_NOMEM) is returned.
+**
+** It is possible to create multiple session objects attached to a single
+** database handle.
+**
+** Session objects created using this function should be deleted using the
+** [sqlite3session_delete()] function before the database handle that they
+** are attached to is itself closed. If the database handle is closed before
+** the session object is deleted, then the results of calling any session
+** module function, including [sqlite3session_delete()] on the session object
+** are undefined.
+**
+** Because the session module uses the [sqlite3_preupdate_hook()] API, it
+** is not possible for an application to register a pre-update hook on a
+** database handle that has one or more session objects attached. Nor is
+** it possible to create a session object attached to a database handle for
+** which a pre-update hook is already defined. The results of attempting
+** either of these things are undefined.
+**
+** The session object will be used to create changesets for tables in
+** database zDb, where zDb is either "main", or "temp", or the name of an
+** attached database. It is not an error if database zDb is not attached
+** to the database when the session object is created.
+*/
+SQLITE_API int sqlite3session_create(
+ sqlite3 *db, /* Database handle */
+ const char *zDb, /* Name of db (e.g. "main") */
+ sqlite3_session **ppSession /* OUT: New session object */
+);
+
+/*
+** CAPI3REF: Delete A Session Object
+** DESTRUCTOR: sqlite3_session
+**
+** Delete a session object previously allocated using
+** [sqlite3session_create()]. Once a session object has been deleted, the
+** results of attempting to use pSession with any other session module
+** function are undefined.
+**
+** Session objects must be deleted before the database handle to which they
+** are attached is closed. Refer to the documentation for
+** [sqlite3session_create()] for details.
+*/
+SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
+
+
+/*
+** CAPI3REF: Enable Or Disable A Session Object
+** METHOD: sqlite3_session
+**
+** Enable or disable the recording of changes by a session object. When
+** enabled, a session object records changes made to the database. When
+** disabled - it does not. A newly created session object is enabled.
+** Refer to the documentation for [sqlite3session_changeset()] for further
+** details regarding how enabling and disabling a session object affects
+** the eventual changesets.
+**
+** Passing zero to this function disables the session. Passing a value
+** greater than zero enables it. Passing a value less than zero is a
+** no-op, and may be used to query the current state of the session.
+**
+** The return value indicates the final state of the session object: 0 if
+** the session is disabled, or 1 if it is enabled.
+*/
+SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
+
+/*
+** CAPI3REF: Set Or Clear the Indirect Change Flag
+** METHOD: sqlite3_session
+**
+** Each change recorded by a session object is marked as either direct or
+** indirect. A change is marked as indirect if either:
+**
+** <ul>
+** <li> The session object "indirect" flag is set when the change is
+** made, or
+** <li> The change is made by an SQL trigger or foreign key action
+** instead of directly as a result of a users SQL statement.
+** </ul>
+**
+** If a single row is affected by more than one operation within a session,
+** then the change is considered indirect if all operations meet the criteria
+** for an indirect change above, or direct otherwise.
+**
+** This function is used to set, clear or query the session object indirect
+** flag. If the second argument passed to this function is zero, then the
+** indirect flag is cleared. If it is greater than zero, the indirect flag
+** is set. Passing a value less than zero does not modify the current value
+** of the indirect flag, and may be used to query the current state of the
+** indirect flag for the specified session object.
+**
+** The return value indicates the final state of the indirect flag: 0 if
+** it is clear, or 1 if it is set.
+*/
+SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
+
+/*
+** CAPI3REF: Attach A Table To A Session Object
+** METHOD: sqlite3_session
+**
+** If argument zTab is not NULL, then it is the name of a table to attach
+** to the session object passed as the first argument. All subsequent changes
+** made to the table while the session object is enabled will be recorded. See
+** documentation for [sqlite3session_changeset()] for further details.
+**
+** Or, if argument zTab is NULL, then changes are recorded for all tables
+** in the database. If additional tables are added to the database (by
+** executing "CREATE TABLE" statements) after this call is made, changes for
+** the new tables are also recorded.
+**
+** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
+** defined as part of their CREATE TABLE statement. It does not matter if the
+** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
+** KEY may consist of a single column, or may be a composite key.
+**
+** It is not an error if the named table does not exist in the database. Nor
+** is it an error if the named table does not have a PRIMARY KEY. However,
+** no changes will be recorded in either of these scenarios.
+**
+** Changes are not recorded for individual rows that have NULL values stored
+** in one or more of their PRIMARY KEY columns.
+**
+** SQLITE_OK is returned if the call completes without error. Or, if an error
+** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
+**
+** <h3>Special sqlite_stat1 Handling</h3>
+**
+** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
+** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
+** <pre>
+** &nbsp; CREATE TABLE sqlite_stat1(tbl,idx,stat)
+** </pre>
+**
+** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
+** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
+** are recorded for rows for which (idx IS NULL) is true. However, for such
+** rows a zero-length blob (SQL value X'') is stored in the changeset or
+** patchset instead of a NULL value. This allows such changesets to be
+** manipulated by legacy implementations of sqlite3changeset_invert(),
+** concat() and similar.
+**
+** The sqlite3changeset_apply() function automatically converts the
+** zero-length blob back to a NULL value when updating the sqlite_stat1
+** table. However, if the application calls sqlite3changeset_new(),
+** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
+** iterator directly (including on a changeset iterator passed to a
+** conflict-handler callback) then the X'' value is returned. The application
+** must translate X'' to NULL itself if required.
+**
+** Legacy (older than 3.22.0) versions of the sessions module cannot capture
+** changes made to the sqlite_stat1 table. Legacy versions of the
+** sqlite3changeset_apply() function silently ignore any modifications to the
+** sqlite_stat1 table that are part of a changeset or patchset.
+*/
+SQLITE_API int sqlite3session_attach(
+ sqlite3_session *pSession, /* Session object */
+ const char *zTab /* Table name */
+);
+
+/*
+** CAPI3REF: Set a table filter on a Session Object.
+** METHOD: sqlite3_session
+**
+** The second argument (xFilter) is the "filter callback". For changes to rows
+** in tables that are not attached to the Session object, the filter is called
+** to determine whether changes to the table's rows should be tracked or not.
+** If xFilter returns 0, changes are not tracked. Note that once a table is
+** attached, xFilter will not be called again.
+*/
+SQLITE_API void sqlite3session_table_filter(
+ sqlite3_session *pSession, /* Session object */
+ int(*xFilter)(
+ void *pCtx, /* Copy of third arg to _filter_table() */
+ const char *zTab /* Table name */
+ ),
+ void *pCtx /* First argument passed to xFilter */
+);
+
+/*
+** CAPI3REF: Generate A Changeset From A Session Object
+** METHOD: sqlite3_session
+**
+** Obtain a changeset containing changes to the tables attached to the
+** session object passed as the first argument. If successful,
+** set *ppChangeset to point to a buffer containing the changeset
+** and *pnChangeset to the size of the changeset in bytes before returning
+** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
+** zero and return an SQLite error code.
+**
+** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
+** each representing a change to a single row of an attached table. An INSERT
+** change contains the values of each field of a new database row. A DELETE
+** contains the original values of each field of a deleted database row. An
+** UPDATE change contains the original values of each field of an updated
+** database row along with the updated values for each updated non-primary-key
+** column. It is not possible for an UPDATE change to represent a change that
+** modifies the values of primary key columns. If such a change is made, it
+** is represented in a changeset as a DELETE followed by an INSERT.
+**
+** Changes are not recorded for rows that have NULL values stored in one or
+** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
+** no corresponding change is present in the changesets returned by this
+** function. If an existing row with one or more NULL values stored in
+** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
+** only an INSERT is appears in the changeset. Similarly, if an existing row
+** with non-NULL PRIMARY KEY values is updated so that one or more of its
+** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
+** DELETE change only.
+**
+** The contents of a changeset may be traversed using an iterator created
+** using the [sqlite3changeset_start()] API. A changeset may be applied to
+** a database with a compatible schema using the [sqlite3changeset_apply()]
+** API.
+**
+** Within a changeset generated by this function, all changes related to a
+** single table are grouped together. In other words, when iterating through
+** a changeset or when applying a changeset to a database, all changes related
+** to a single table are processed before moving on to the next table. Tables
+** are sorted in the same order in which they were attached (or auto-attached)
+** to the sqlite3_session object. The order in which the changes related to
+** a single table are stored is undefined.
+**
+** Following a successful call to this function, it is the responsibility of
+** the caller to eventually free the buffer that *ppChangeset points to using
+** [sqlite3_free()].
+**
+** <h3>Changeset Generation</h3>
+**
+** Once a table has been attached to a session object, the session object
+** records the primary key values of all new rows inserted into the table.
+** It also records the original primary key and other column values of any
+** deleted or updated rows. For each unique primary key value, data is only
+** recorded once - the first time a row with said primary key is inserted,
+** updated or deleted in the lifetime of the session.
+**
+** There is one exception to the previous paragraph: when a row is inserted,
+** updated or deleted, if one or more of its primary key columns contain a
+** NULL value, no record of the change is made.
+**
+** The session object therefore accumulates two types of records - those
+** that consist of primary key values only (created when the user inserts
+** a new record) and those that consist of the primary key values and the
+** original values of other table columns (created when the users deletes
+** or updates a record).
+**
+** When this function is called, the requested changeset is created using
+** both the accumulated records and the current contents of the database
+** file. Specifically:
+**
+** <ul>
+** <li> For each record generated by an insert, the database is queried
+** for a row with a matching primary key. If one is found, an INSERT
+** change is added to the changeset. If no such row is found, no change
+** is added to the changeset.
+**
+** <li> For each record generated by an update or delete, the database is
+** queried for a row with a matching primary key. If such a row is
+** found and one or more of the non-primary key fields have been
+** modified from their original values, an UPDATE change is added to
+** the changeset. Or, if no such row is found in the table, a DELETE
+** change is added to the changeset. If there is a row with a matching
+** primary key in the database, but all fields contain their original
+** values, no change is added to the changeset.
+** </ul>
+**
+** This means, amongst other things, that if a row is inserted and then later
+** deleted while a session object is active, neither the insert nor the delete
+** will be present in the changeset. Or if a row is deleted and then later a
+** row with the same primary key values inserted while a session object is
+** active, the resulting changeset will contain an UPDATE change instead of
+** a DELETE and an INSERT.
+**
+** When a session object is disabled (see the [sqlite3session_enable()] API),
+** it does not accumulate records when rows are inserted, updated or deleted.
+** This may appear to have some counter-intuitive effects if a single row
+** is written to more than once during a session. For example, if a row
+** is inserted while a session object is enabled, then later deleted while
+** the same session object is disabled, no INSERT record will appear in the
+** changeset, even though the delete took place while the session was disabled.
+** Or, if one field of a row is updated while a session is disabled, and
+** another field of the same row is updated while the session is enabled, the
+** resulting changeset will contain an UPDATE change that updates both fields.
+*/
+SQLITE_API int sqlite3session_changeset(
+ sqlite3_session *pSession, /* Session object */
+ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
+ void **ppChangeset /* OUT: Buffer containing changeset */
+);
+
+/*
+** CAPI3REF: Load The Difference Between Tables Into A Session
+** METHOD: sqlite3_session
+**
+** If it is not already attached to the session object passed as the first
+** argument, this function attaches table zTbl in the same manner as the
+** [sqlite3session_attach()] function. If zTbl does not exist, or if it
+** does not have a primary key, this function is a no-op (but does not return
+** an error).
+**
+** Argument zFromDb must be the name of a database ("main", "temp" etc.)
+** attached to the same database handle as the session object that contains
+** a table compatible with the table attached to the session by this function.
+** A table is considered compatible if it:
+**
+** <ul>
+** <li> Has the same name,
+** <li> Has the same set of columns declared in the same order, and
+** <li> Has the same PRIMARY KEY definition.
+** </ul>
+**
+** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
+** are compatible but do not have any PRIMARY KEY columns, it is not an error
+** but no changes are added to the session object. As with other session
+** APIs, tables without PRIMARY KEYs are simply ignored.
+**
+** This function adds a set of changes to the session object that could be
+** used to update the table in database zFrom (call this the "from-table")
+** so that its content is the same as the table attached to the session
+** object (call this the "to-table"). Specifically:
+**
+** <ul>
+** <li> For each row (primary key) that exists in the to-table but not in
+** the from-table, an INSERT record is added to the session object.
+**
+** <li> For each row (primary key) that exists in the to-table but not in
+** the from-table, a DELETE record is added to the session object.
+**
+** <li> For each row (primary key) that exists in both tables, but features
+** different non-PK values in each, an UPDATE record is added to the
+** session.
+** </ul>
+**
+** To clarify, if this function is called and then a changeset constructed
+** using [sqlite3session_changeset()], then after applying that changeset to
+** database zFrom the contents of the two compatible tables would be
+** identical.
+**
+** It an error if database zFrom does not exist or does not contain the
+** required compatible table.
+**
+** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite
+** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
+** may be set to point to a buffer containing an English language error
+** message. It is the responsibility of the caller to free this buffer using
+** sqlite3_free().
+*/
+SQLITE_API int sqlite3session_diff(
+ sqlite3_session *pSession,
+ const char *zFromDb,
+ const char *zTbl,
+ char **pzErrMsg
+);
+
+
+/*
+** CAPI3REF: Generate A Patchset From A Session Object
+** METHOD: sqlite3_session
+**
+** The differences between a patchset and a changeset are that:
+**
+** <ul>
+** <li> DELETE records consist of the primary key fields only. The
+** original values of other fields are omitted.
+** <li> The original values of any modified fields are omitted from
+** UPDATE records.
+** </ul>
+**
+** A patchset blob may be used with up to date versions of all
+** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
+** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
+** attempting to use a patchset blob with old versions of the
+** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
+**
+** Because the non-primary key "old.*" fields are omitted, no
+** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
+** is passed to the sqlite3changeset_apply() API. Other conflict types work
+** in the same way as for changesets.
+**
+** Changes within a patchset are ordered in the same way as for changesets
+** generated by the sqlite3session_changeset() function (i.e. all changes for
+** a single table are grouped together, tables appear in the order in which
+** they were attached to the session object).
+*/
+SQLITE_API int sqlite3session_patchset(
+ sqlite3_session *pSession, /* Session object */
+ int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */
+ void **ppPatchset /* OUT: Buffer containing patchset */
+);
+
+/*
+** CAPI3REF: Test if a changeset has recorded any changes.
+**
+** Return non-zero if no changes to attached tables have been recorded by
+** the session object passed as the first argument. Otherwise, if one or
+** more changes have been recorded, return zero.
+**
+** Even if this function returns zero, it is possible that calling
+** [sqlite3session_changeset()] on the session handle may still return a
+** changeset that contains no changes. This can happen when a row in
+** an attached table is modified and then later on the original values
+** are restored. However, if this function returns non-zero, then it is
+** guaranteed that a call to sqlite3session_changeset() will return a
+** changeset containing zero changes.
+*/
+SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
+
+/*
+** CAPI3REF: Create An Iterator To Traverse A Changeset
+** CONSTRUCTOR: sqlite3_changeset_iter
+**
+** Create an iterator used to iterate through the contents of a changeset.
+** If successful, *pp is set to point to the iterator handle and SQLITE_OK
+** is returned. Otherwise, if an error occurs, *pp is set to zero and an
+** SQLite error code is returned.
+**
+** The following functions can be used to advance and query a changeset
+** iterator created by this function:
+**
+** <ul>
+** <li> [sqlite3changeset_next()]
+** <li> [sqlite3changeset_op()]
+** <li> [sqlite3changeset_new()]
+** <li> [sqlite3changeset_old()]
+** </ul>
+**
+** It is the responsibility of the caller to eventually destroy the iterator
+** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
+** changeset (pChangeset) must remain valid until after the iterator is
+** destroyed.
+**
+** Assuming the changeset blob was created by one of the
+** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
+** [sqlite3changeset_invert()] functions, all changes within the changeset
+** that apply to a single table are grouped together. This means that when
+** an application iterates through a changeset using an iterator created by
+** this function, all changes that relate to a single table are visited
+** consecutively. There is no chance that the iterator will visit a change
+** the applies to table X, then one for table Y, and then later on visit
+** another change for table X.
+**
+** The behavior of sqlite3changeset_start_v2() and its streaming equivalent
+** may be modified by passing a combination of
+** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.
+**
+** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b>
+** and therefore subject to change.
+*/
+SQLITE_API int sqlite3changeset_start(
+ sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
+ int nChangeset, /* Size of changeset blob in bytes */
+ void *pChangeset /* Pointer to blob containing changeset */
+);
+SQLITE_API int sqlite3changeset_start_v2(
+ sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
+ int nChangeset, /* Size of changeset blob in bytes */
+ void *pChangeset, /* Pointer to blob containing changeset */
+ int flags /* SESSION_CHANGESETSTART_* flags */
+);
+
+/*
+** CAPI3REF: Flags for sqlite3changeset_start_v2
+**
+** The following flags may passed via the 4th parameter to
+** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:
+**
+** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
+** Invert the changeset while iterating through it. This is equivalent to
+** inverting a changeset using sqlite3changeset_invert() before applying it.
+** It is an error to specify this flag with a patchset.
+*/
+#define SQLITE_CHANGESETSTART_INVERT 0x0002
+
+
+/*
+** CAPI3REF: Advance A Changeset Iterator
+** METHOD: sqlite3_changeset_iter
+**
+** This function may only be used with iterators created by the function
+** [sqlite3changeset_start()]. If it is called on an iterator passed to
+** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
+** is returned and the call has no effect.
+**
+** Immediately after an iterator is created by sqlite3changeset_start(), it
+** does not point to any change in the changeset. Assuming the changeset
+** is not empty, the first call to this function advances the iterator to
+** point to the first change in the changeset. Each subsequent call advances
+** the iterator to point to the next change in the changeset (if any). If
+** no error occurs and the iterator points to a valid change after a call
+** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
+** Otherwise, if all changes in the changeset have already been visited,
+** SQLITE_DONE is returned.
+**
+** If an error occurs, an SQLite error code is returned. Possible error
+** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
+** SQLITE_NOMEM.
+*/
+SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
+
+/*
+** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
+** METHOD: sqlite3_changeset_iter
+**
+** The pIter argument passed to this function may either be an iterator
+** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
+** created by [sqlite3changeset_start()]. In the latter case, the most recent
+** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
+** is not the case, this function returns [SQLITE_MISUSE].
+**
+** If argument pzTab is not NULL, then *pzTab is set to point to a
+** nul-terminated utf-8 encoded string containing the name of the table
+** affected by the current change. The buffer remains valid until either
+** sqlite3changeset_next() is called on the iterator or until the
+** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
+** set to the number of columns in the table affected by the change. If
+** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
+** is an indirect change, or false (0) otherwise. See the documentation for
+** [sqlite3session_indirect()] for a description of direct and indirect
+** changes. Finally, if pOp is not NULL, then *pOp is set to one of
+** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
+** type of change that the iterator currently points to.
+**
+** If no error occurs, SQLITE_OK is returned. If an error does occur, an
+** SQLite error code is returned. The values of the output variables may not
+** be trusted in this case.
+*/
+SQLITE_API int sqlite3changeset_op(
+ sqlite3_changeset_iter *pIter, /* Iterator object */
+ const char **pzTab, /* OUT: Pointer to table name */
+ int *pnCol, /* OUT: Number of columns in table */
+ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
+ int *pbIndirect /* OUT: True for an 'indirect' change */
+);
+
+/*
+** CAPI3REF: Obtain The Primary Key Definition Of A Table
+** METHOD: sqlite3_changeset_iter
+**
+** For each modified table, a changeset includes the following:
+**
+** <ul>
+** <li> The number of columns in the table, and
+** <li> Which of those columns make up the tables PRIMARY KEY.
+** </ul>
+**
+** This function is used to find which columns comprise the PRIMARY KEY of
+** the table modified by the change that iterator pIter currently points to.
+** If successful, *pabPK is set to point to an array of nCol entries, where
+** nCol is the number of columns in the table. Elements of *pabPK are set to
+** 0x01 if the corresponding column is part of the tables primary key, or
+** 0x00 if it is not.
+**
+** If argument pnCol is not NULL, then *pnCol is set to the number of columns
+** in the table.
+**
+** If this function is called when the iterator does not point to a valid
+** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
+** SQLITE_OK is returned and the output variables populated as described
+** above.
+*/
+SQLITE_API int sqlite3changeset_pk(
+ sqlite3_changeset_iter *pIter, /* Iterator object */
+ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
+ int *pnCol /* OUT: Number of entries in output array */
+);
+
+/*
+** CAPI3REF: Obtain old.* Values From A Changeset Iterator
+** METHOD: sqlite3_changeset_iter
+**
+** The pIter argument passed to this function may either be an iterator
+** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
+** created by [sqlite3changeset_start()]. In the latter case, the most recent
+** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
+** Furthermore, it may only be called if the type of change that the iterator
+** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
+** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
+**
+** Argument iVal must be greater than or equal to 0, and less than the number
+** of columns in the table affected by the current change. Otherwise,
+** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
+**
+** If successful, this function sets *ppValue to point to a protected
+** sqlite3_value object containing the iVal'th value from the vector of
+** original row values stored as part of the UPDATE or DELETE change and
+** returns SQLITE_OK. The name of the function comes from the fact that this
+** is similar to the "old.*" columns available to update or delete triggers.
+**
+** If some other error occurs (e.g. an OOM condition), an SQLite error code
+** is returned and *ppValue is set to NULL.
+*/
+SQLITE_API int sqlite3changeset_old(
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ int iVal, /* Column number */
+ sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
+);
+
+/*
+** CAPI3REF: Obtain new.* Values From A Changeset Iterator
+** METHOD: sqlite3_changeset_iter
+**
+** The pIter argument passed to this function may either be an iterator
+** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
+** created by [sqlite3changeset_start()]. In the latter case, the most recent
+** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
+** Furthermore, it may only be called if the type of change that the iterator
+** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
+** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
+**
+** Argument iVal must be greater than or equal to 0, and less than the number
+** of columns in the table affected by the current change. Otherwise,
+** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
+**
+** If successful, this function sets *ppValue to point to a protected
+** sqlite3_value object containing the iVal'th value from the vector of
+** new row values stored as part of the UPDATE or INSERT change and
+** returns SQLITE_OK. If the change is an UPDATE and does not include
+** a new value for the requested column, *ppValue is set to NULL and
+** SQLITE_OK returned. The name of the function comes from the fact that
+** this is similar to the "new.*" columns available to update or delete
+** triggers.
+**
+** If some other error occurs (e.g. an OOM condition), an SQLite error code
+** is returned and *ppValue is set to NULL.
+*/
+SQLITE_API int sqlite3changeset_new(
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ int iVal, /* Column number */
+ sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
+);
+
+/*
+** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
+** METHOD: sqlite3_changeset_iter
+**
+** This function should only be used with iterator objects passed to a
+** conflict-handler callback by [sqlite3changeset_apply()] with either
+** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
+** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
+** is set to NULL.
+**
+** Argument iVal must be greater than or equal to 0, and less than the number
+** of columns in the table affected by the current change. Otherwise,
+** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
+**
+** If successful, this function sets *ppValue to point to a protected
+** sqlite3_value object containing the iVal'th value from the
+** "conflicting row" associated with the current conflict-handler callback
+** and returns SQLITE_OK.
+**
+** If some other error occurs (e.g. an OOM condition), an SQLite error code
+** is returned and *ppValue is set to NULL.
+*/
+SQLITE_API int sqlite3changeset_conflict(
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ int iVal, /* Column number */
+ sqlite3_value **ppValue /* OUT: Value from conflicting row */
+);
+
+/*
+** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
+** METHOD: sqlite3_changeset_iter
+**
+** This function may only be called with an iterator passed to an
+** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
+** it sets the output variable to the total number of known foreign key
+** violations in the destination database and returns SQLITE_OK.
+**
+** In all other cases this function returns SQLITE_MISUSE.
+*/
+SQLITE_API int sqlite3changeset_fk_conflicts(
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
+ int *pnOut /* OUT: Number of FK violations */
+);
+
+
+/*
+** CAPI3REF: Finalize A Changeset Iterator
+** METHOD: sqlite3_changeset_iter
+**
+** This function is used to finalize an iterator allocated with
+** [sqlite3changeset_start()].
+**
+** This function should only be called on iterators created using the
+** [sqlite3changeset_start()] function. If an application calls this
+** function with an iterator passed to a conflict-handler by
+** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
+** call has no effect.
+**
+** If an error was encountered within a call to an sqlite3changeset_xxx()
+** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
+** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
+** to that error is returned by this function. Otherwise, SQLITE_OK is
+** returned. This is to allow the following pattern (pseudo-code):
+**
+** <pre>
+** sqlite3changeset_start();
+** while( SQLITE_ROW==sqlite3changeset_next() ){
+** // Do something with change.
+** }
+** rc = sqlite3changeset_finalize();
+** if( rc!=SQLITE_OK ){
+** // An error has occurred
+** }
+** </pre>
+*/
+SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
+
+/*
+** CAPI3REF: Invert A Changeset
+**
+** This function is used to "invert" a changeset object. Applying an inverted
+** changeset to a database reverses the effects of applying the uninverted
+** changeset. Specifically:
+**
+** <ul>
+** <li> Each DELETE change is changed to an INSERT, and
+** <li> Each INSERT change is changed to a DELETE, and
+** <li> For each UPDATE change, the old.* and new.* values are exchanged.
+** </ul>
+**
+** This function does not change the order in which changes appear within
+** the changeset. It merely reverses the sense of each individual change.
+**
+** If successful, a pointer to a buffer containing the inverted changeset
+** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
+** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
+** zeroed and an SQLite error code returned.
+**
+** It is the responsibility of the caller to eventually call sqlite3_free()
+** on the *ppOut pointer to free the buffer allocation following a successful
+** call to this function.
+**
+** WARNING/TODO: This function currently assumes that the input is a valid
+** changeset. If it is not, the results are undefined.
+*/
+SQLITE_API int sqlite3changeset_invert(
+ int nIn, const void *pIn, /* Input changeset */
+ int *pnOut, void **ppOut /* OUT: Inverse of input */
+);
+
+/*
+** CAPI3REF: Concatenate Two Changeset Objects
+**
+** This function is used to concatenate two changesets, A and B, into a
+** single changeset. The result is a changeset equivalent to applying
+** changeset A followed by changeset B.
+**
+** This function combines the two input changesets using an
+** sqlite3_changegroup object. Calling it produces similar results as the
+** following code fragment:
+**
+** <pre>
+** sqlite3_changegroup *pGrp;
+** rc = sqlite3_changegroup_new(&pGrp);
+** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
+** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
+** if( rc==SQLITE_OK ){
+** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
+** }else{
+** *ppOut = 0;
+** *pnOut = 0;
+** }
+** </pre>
+**
+** Refer to the sqlite3_changegroup documentation below for details.
+*/
+SQLITE_API int sqlite3changeset_concat(
+ int nA, /* Number of bytes in buffer pA */
+ void *pA, /* Pointer to buffer containing changeset A */
+ int nB, /* Number of bytes in buffer pB */
+ void *pB, /* Pointer to buffer containing changeset B */
+ int *pnOut, /* OUT: Number of bytes in output changeset */
+ void **ppOut /* OUT: Buffer containing output changeset */
+);
+
+
+/*
+** CAPI3REF: Changegroup Handle
+**
+** A changegroup is an object used to combine two or more
+** [changesets] or [patchsets]
+*/
+typedef struct sqlite3_changegroup sqlite3_changegroup;
+
+/*
+** CAPI3REF: Create A New Changegroup Object
+** CONSTRUCTOR: sqlite3_changegroup
+**
+** An sqlite3_changegroup object is used to combine two or more changesets
+** (or patchsets) into a single changeset (or patchset). A single changegroup
+** object may combine changesets or patchsets, but not both. The output is
+** always in the same format as the input.
+**
+** If successful, this function returns SQLITE_OK and populates (*pp) with
+** a pointer to a new sqlite3_changegroup object before returning. The caller
+** should eventually free the returned object using a call to
+** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
+** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
+**
+** The usual usage pattern for an sqlite3_changegroup object is as follows:
+**
+** <ul>
+** <li> It is created using a call to sqlite3changegroup_new().
+**
+** <li> Zero or more changesets (or patchsets) are added to the object
+** by calling sqlite3changegroup_add().
+**
+** <li> The result of combining all input changesets together is obtained
+** by the application via a call to sqlite3changegroup_output().
+**
+** <li> The object is deleted using a call to sqlite3changegroup_delete().
+** </ul>
+**
+** Any number of calls to add() and output() may be made between the calls to
+** new() and delete(), and in any order.
+**
+** As well as the regular sqlite3changegroup_add() and
+** sqlite3changegroup_output() functions, also available are the streaming
+** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
+*/
+SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
+
+/*
+** CAPI3REF: Add A Changeset To A Changegroup
+** METHOD: sqlite3_changegroup
+**
+** Add all changes within the changeset (or patchset) in buffer pData (size
+** nData bytes) to the changegroup.
+**
+** If the buffer contains a patchset, then all prior calls to this function
+** on the same changegroup object must also have specified patchsets. Or, if
+** the buffer contains a changeset, so must have the earlier calls to this
+** function. Otherwise, SQLITE_ERROR is returned and no changes are added
+** to the changegroup.
+**
+** Rows within the changeset and changegroup are identified by the values in
+** their PRIMARY KEY columns. A change in the changeset is considered to
+** apply to the same row as a change already present in the changegroup if
+** the two rows have the same primary key.
+**
+** Changes to rows that do not already appear in the changegroup are
+** simply copied into it. Or, if both the new changeset and the changegroup
+** contain changes that apply to a single row, the final contents of the
+** changegroup depends on the type of each change, as follows:
+**
+** <table border=1 style="margin-left:8ex;margin-right:8ex">
+** <tr><th style="white-space:pre">Existing Change </th>
+** <th style="white-space:pre">New Change </th>
+** <th>Output Change
+** <tr><td>INSERT <td>INSERT <td>
+** The new change is ignored. This case does not occur if the new
+** changeset was recorded immediately after the changesets already
+** added to the changegroup.
+** <tr><td>INSERT <td>UPDATE <td>
+** The INSERT change remains in the changegroup. The values in the
+** INSERT change are modified as if the row was inserted by the
+** existing change and then updated according to the new change.
+** <tr><td>INSERT <td>DELETE <td>
+** The existing INSERT is removed from the changegroup. The DELETE is
+** not added.
+** <tr><td>UPDATE <td>INSERT <td>
+** The new change is ignored. This case does not occur if the new
+** changeset was recorded immediately after the changesets already
+** added to the changegroup.
+** <tr><td>UPDATE <td>UPDATE <td>
+** The existing UPDATE remains within the changegroup. It is amended
+** so that the accompanying values are as if the row was updated once
+** by the existing change and then again by the new change.
+** <tr><td>UPDATE <td>DELETE <td>
+** The existing UPDATE is replaced by the new DELETE within the
+** changegroup.
+** <tr><td>DELETE <td>INSERT <td>
+** If one or more of the column values in the row inserted by the
+** new change differ from those in the row deleted by the existing
+** change, the existing DELETE is replaced by an UPDATE within the
+** changegroup. Otherwise, if the inserted row is exactly the same
+** as the deleted row, the existing DELETE is simply discarded.
+** <tr><td>DELETE <td>UPDATE <td>
+** The new change is ignored. This case does not occur if the new
+** changeset was recorded immediately after the changesets already
+** added to the changegroup.
+** <tr><td>DELETE <td>DELETE <td>
+** The new change is ignored. This case does not occur if the new
+** changeset was recorded immediately after the changesets already
+** added to the changegroup.
+** </table>
+**
+** If the new changeset contains changes to a table that is already present
+** in the changegroup, then the number of columns and the position of the
+** primary key columns for the table must be consistent. If this is not the
+** case, this function fails with SQLITE_SCHEMA. If the input changeset
+** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
+** returned. Or, if an out-of-memory condition occurs during processing, this
+** function returns SQLITE_NOMEM. In all cases, if an error occurs the state
+** of the final contents of the changegroup is undefined.
+**
+** If no error occurs, SQLITE_OK is returned.
+*/
+SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
+
+/*
+** CAPI3REF: Obtain A Composite Changeset From A Changegroup
+** METHOD: sqlite3_changegroup
+**
+** Obtain a buffer containing a changeset (or patchset) representing the
+** current contents of the changegroup. If the inputs to the changegroup
+** were themselves changesets, the output is a changeset. Or, if the
+** inputs were patchsets, the output is also a patchset.
+**
+** As with the output of the sqlite3session_changeset() and
+** sqlite3session_patchset() functions, all changes related to a single
+** table are grouped together in the output of this function. Tables appear
+** in the same order as for the very first changeset added to the changegroup.
+** If the second or subsequent changesets added to the changegroup contain
+** changes for tables that do not appear in the first changeset, they are
+** appended onto the end of the output changeset, again in the order in
+** which they are first encountered.
+**
+** If an error occurs, an SQLite error code is returned and the output
+** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
+** is returned and the output variables are set to the size of and a
+** pointer to the output buffer, respectively. In this case it is the
+** responsibility of the caller to eventually free the buffer using a
+** call to sqlite3_free().
+*/
+SQLITE_API int sqlite3changegroup_output(
+ sqlite3_changegroup*,
+ int *pnData, /* OUT: Size of output buffer in bytes */
+ void **ppData /* OUT: Pointer to output buffer */
+);
+
+/*
+** CAPI3REF: Delete A Changegroup Object
+** DESTRUCTOR: sqlite3_changegroup
+*/
+SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
+
+/*
+** CAPI3REF: Apply A Changeset To A Database
+**
+** Apply a changeset or patchset to a database. These functions attempt to
+** update the "main" database attached to handle db with the changes found in
+** the changeset passed via the second and third arguments.
+**
+** The fourth argument (xFilter) passed to these functions is the "filter
+** callback". If it is not NULL, then for each table affected by at least one
+** change in the changeset, the filter callback is invoked with
+** the table name as the second argument, and a copy of the context pointer
+** passed as the sixth argument as the first. If the "filter callback"
+** returns zero, then no attempt is made to apply any changes to the table.
+** Otherwise, if the return value is non-zero or the xFilter argument to
+** is NULL, all changes related to the table are attempted.
+**
+** For each table that is not excluded by the filter callback, this function
+** tests that the target database contains a compatible table. A table is
+** considered compatible if all of the following are true:
+**
+** <ul>
+** <li> The table has the same name as the name recorded in the
+** changeset, and
+** <li> The table has at least as many columns as recorded in the
+** changeset, and
+** <li> The table has primary key columns in the same position as
+** recorded in the changeset.
+** </ul>
+**
+** If there is no compatible table, it is not an error, but none of the
+** changes associated with the table are applied. A warning message is issued
+** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
+** one such warning is issued for each table in the changeset.
+**
+** For each change for which there is a compatible table, an attempt is made
+** to modify the table contents according to the UPDATE, INSERT or DELETE
+** change. If a change cannot be applied cleanly, the conflict handler
+** function passed as the fifth argument to sqlite3changeset_apply() may be
+** invoked. A description of exactly when the conflict handler is invoked for
+** each type of change is below.
+**
+** Unlike the xFilter argument, xConflict may not be passed NULL. The results
+** of passing anything other than a valid function pointer as the xConflict
+** argument are undefined.
+**
+** Each time the conflict handler function is invoked, it must return one
+** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
+** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
+** if the second argument passed to the conflict handler is either
+** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
+** returns an illegal value, any changes already made are rolled back and
+** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
+** actions are taken by sqlite3changeset_apply() depending on the value
+** returned by each invocation of the conflict-handler function. Refer to
+** the documentation for the three
+** [SQLITE_CHANGESET_OMIT|available return values] for details.
+**
+** <dl>
+** <dt>DELETE Changes<dd>
+** For each DELETE change, the function checks if the target database
+** contains a row with the same primary key value (or values) as the
+** original row values stored in the changeset. If it does, and the values
+** stored in all non-primary key columns also match the values stored in
+** the changeset the row is deleted from the target database.
+**
+** If a row with matching primary key values is found, but one or more of
+** the non-primary key fields contains a value different from the original
+** row value stored in the changeset, the conflict-handler function is
+** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
+** database table has more columns than are recorded in the changeset,
+** only the values of those non-primary key fields are compared against
+** the current database contents - any trailing database table columns
+** are ignored.
+**
+** If no row with matching primary key values is found in the database,
+** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
+** passed as the second argument.
+**
+** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
+** (which can only happen if a foreign key constraint is violated), the
+** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
+** passed as the second argument. This includes the case where the DELETE
+** operation is attempted because an earlier call to the conflict handler
+** function returned [SQLITE_CHANGESET_REPLACE].
+**
+** <dt>INSERT Changes<dd>
+** For each INSERT change, an attempt is made to insert the new row into
+** the database. If the changeset row contains fewer fields than the
+** database table, the trailing fields are populated with their default
+** values.
+**
+** If the attempt to insert the row fails because the database already
+** contains a row with the same primary key values, the conflict handler
+** function is invoked with the second argument set to
+** [SQLITE_CHANGESET_CONFLICT].
+**
+** If the attempt to insert the row fails because of some other constraint
+** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
+** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
+** This includes the case where the INSERT operation is re-attempted because
+** an earlier call to the conflict handler function returned
+** [SQLITE_CHANGESET_REPLACE].
+**
+** <dt>UPDATE Changes<dd>
+** For each UPDATE change, the function checks if the target database
+** contains a row with the same primary key value (or values) as the
+** original row values stored in the changeset. If it does, and the values
+** stored in all modified non-primary key columns also match the values
+** stored in the changeset the row is updated within the target database.
+**
+** If a row with matching primary key values is found, but one or more of
+** the modified non-primary key fields contains a value different from an
+** original row value stored in the changeset, the conflict-handler function
+** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
+** UPDATE changes only contain values for non-primary key fields that are
+** to be modified, only those fields need to match the original values to
+** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
+**
+** If no row with matching primary key values is found in the database,
+** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
+** passed as the second argument.
+**
+** If the UPDATE operation is attempted, but SQLite returns
+** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
+** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
+** This includes the case where the UPDATE operation is attempted after
+** an earlier call to the conflict handler function returned
+** [SQLITE_CHANGESET_REPLACE].
+** </dl>
+**
+** It is safe to execute SQL statements, including those that write to the
+** table that the callback related to, from within the xConflict callback.
+** This can be used to further customize the application's conflict
+** resolution strategy.
+**
+** All changes made by these functions are enclosed in a savepoint transaction.
+** If any other error (aside from a constraint failure when attempting to
+** write to the target database) occurs, then the savepoint transaction is
+** rolled back, restoring the target database to its original state, and an
+** SQLite error code returned.
+**
+** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
+** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
+** may set (*ppRebase) to point to a "rebase" that may be used with the
+** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
+** is set to the size of the buffer in bytes. It is the responsibility of the
+** caller to eventually free any such buffer using sqlite3_free(). The buffer
+** is only allocated and populated if one or more conflicts were encountered
+** while applying the patchset. See comments surrounding the sqlite3_rebaser
+** APIs for further details.
+**
+** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent
+** may be modified by passing a combination of
+** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.
+**
+** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>
+** and therefore subject to change.
+*/
+SQLITE_API int sqlite3changeset_apply(
+ sqlite3 *db, /* Apply change to "main" db of this handle */
+ int nChangeset, /* Size of changeset in bytes */
+ void *pChangeset, /* Changeset blob */
+ int(*xFilter)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ const char *zTab /* Table name */
+ ),
+ int(*xConflict)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
+ ),
+ void *pCtx /* First argument passed to xConflict */
+);
+SQLITE_API int sqlite3changeset_apply_v2(
+ sqlite3 *db, /* Apply change to "main" db of this handle */
+ int nChangeset, /* Size of changeset in bytes */
+ void *pChangeset, /* Changeset blob */
+ int(*xFilter)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ const char *zTab /* Table name */
+ ),
+ int(*xConflict)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
+ ),
+ void *pCtx, /* First argument passed to xConflict */
+ void **ppRebase, int *pnRebase, /* OUT: Rebase data */
+ int flags /* SESSION_CHANGESETAPPLY_* flags */
+);
+
+/*
+** CAPI3REF: Flags for sqlite3changeset_apply_v2
+**
+** The following flags may passed via the 9th parameter to
+** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:
+**
+** <dl>
+** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>
+** Usually, the sessions module encloses all operations performed by
+** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The
+** SAVEPOINT is committed if the changeset or patchset is successfully
+** applied, or rolled back if an error occurs. Specifying this flag
+** causes the sessions module to omit this savepoint. In this case, if the
+** caller has an open transaction or savepoint when apply_v2() is called,
+** it may revert the partially applied changeset by rolling it back.
+**
+** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
+** Invert the changeset before applying it. This is equivalent to inverting
+** a changeset using sqlite3changeset_invert() before applying it. It is
+** an error to specify this flag with a patchset.
+*/
+#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001
+#define SQLITE_CHANGESETAPPLY_INVERT 0x0002
+
+/*
+** CAPI3REF: Constants Passed To The Conflict Handler
+**
+** Values that may be passed as the second argument to a conflict-handler.
+**
+** <dl>
+** <dt>SQLITE_CHANGESET_DATA<dd>
+** The conflict handler is invoked with CHANGESET_DATA as the second argument
+** when processing a DELETE or UPDATE change if a row with the required
+** PRIMARY KEY fields is present in the database, but one or more other
+** (non primary-key) fields modified by the update do not contain the
+** expected "before" values.
+**
+** The conflicting row, in this case, is the database row with the matching
+** primary key.
+**
+** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
+** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
+** argument when processing a DELETE or UPDATE change if a row with the
+** required PRIMARY KEY fields is not present in the database.
+**
+** There is no conflicting row in this case. The results of invoking the
+** sqlite3changeset_conflict() API are undefined.
+**
+** <dt>SQLITE_CHANGESET_CONFLICT<dd>
+** CHANGESET_CONFLICT is passed as the second argument to the conflict
+** handler while processing an INSERT change if the operation would result
+** in duplicate primary key values.
+**
+** The conflicting row in this case is the database row with the matching
+** primary key.
+**
+** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
+** If foreign key handling is enabled, and applying a changeset leaves the
+** database in a state containing foreign key violations, the conflict
+** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
+** exactly once before the changeset is committed. If the conflict handler
+** returns CHANGESET_OMIT, the changes, including those that caused the
+** foreign key constraint violation, are committed. Or, if it returns
+** CHANGESET_ABORT, the changeset is rolled back.
+**
+** No current or conflicting row information is provided. The only function
+** it is possible to call on the supplied sqlite3_changeset_iter handle
+** is sqlite3changeset_fk_conflicts().
+**
+** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
+** If any other constraint violation occurs while applying a change (i.e.
+** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
+** invoked with CHANGESET_CONSTRAINT as the second argument.
+**
+** There is no conflicting row in this case. The results of invoking the
+** sqlite3changeset_conflict() API are undefined.
+**
+** </dl>
+*/
+#define SQLITE_CHANGESET_DATA 1
+#define SQLITE_CHANGESET_NOTFOUND 2
+#define SQLITE_CHANGESET_CONFLICT 3
+#define SQLITE_CHANGESET_CONSTRAINT 4
+#define SQLITE_CHANGESET_FOREIGN_KEY 5
+
+/*
+** CAPI3REF: Constants Returned By The Conflict Handler
+**
+** A conflict handler callback must return one of the following three values.
+**
+** <dl>
+** <dt>SQLITE_CHANGESET_OMIT<dd>
+** If a conflict handler returns this value no special action is taken. The
+** change that caused the conflict is not applied. The session module
+** continues to the next change in the changeset.
+**
+** <dt>SQLITE_CHANGESET_REPLACE<dd>
+** This value may only be returned if the second argument to the conflict
+** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
+** is not the case, any changes applied so far are rolled back and the
+** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
+**
+** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
+** handler, then the conflicting row is either updated or deleted, depending
+** on the type of change.
+**
+** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
+** handler, then the conflicting row is removed from the database and a
+** second attempt to apply the change is made. If this second attempt fails,
+** the original row is restored to the database before continuing.
+**
+** <dt>SQLITE_CHANGESET_ABORT<dd>
+** If this value is returned, any changes applied so far are rolled back
+** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
+** </dl>
+*/
+#define SQLITE_CHANGESET_OMIT 0
+#define SQLITE_CHANGESET_REPLACE 1
+#define SQLITE_CHANGESET_ABORT 2
+
+/*
+** CAPI3REF: Rebasing changesets
+** EXPERIMENTAL
+**
+** Suppose there is a site hosting a database in state S0. And that
+** modifications are made that move that database to state S1 and a
+** changeset recorded (the "local" changeset). Then, a changeset based
+** on S0 is received from another site (the "remote" changeset) and
+** applied to the database. The database is then in state
+** (S1+"remote"), where the exact state depends on any conflict
+** resolution decisions (OMIT or REPLACE) made while applying "remote".
+** Rebasing a changeset is to update it to take those conflict
+** resolution decisions into account, so that the same conflicts
+** do not have to be resolved elsewhere in the network.
+**
+** For example, if both the local and remote changesets contain an
+** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
+**
+** local: INSERT INTO t1 VALUES(1, 'v1');
+** remote: INSERT INTO t1 VALUES(1, 'v2');
+**
+** and the conflict resolution is REPLACE, then the INSERT change is
+** removed from the local changeset (it was overridden). Or, if the
+** conflict resolution was "OMIT", then the local changeset is modified
+** to instead contain:
+**
+** UPDATE t1 SET b = 'v2' WHERE a=1;
+**
+** Changes within the local changeset are rebased as follows:
+**
+** <dl>
+** <dt>Local INSERT<dd>
+** This may only conflict with a remote INSERT. If the conflict
+** resolution was OMIT, then add an UPDATE change to the rebased
+** changeset. Or, if the conflict resolution was REPLACE, add
+** nothing to the rebased changeset.
+**
+** <dt>Local DELETE<dd>
+** This may conflict with a remote UPDATE or DELETE. In both cases the
+** only possible resolution is OMIT. If the remote operation was a
+** DELETE, then add no change to the rebased changeset. If the remote
+** operation was an UPDATE, then the old.* fields of change are updated
+** to reflect the new.* values in the UPDATE.
+**
+** <dt>Local UPDATE<dd>
+** This may conflict with a remote UPDATE or DELETE. If it conflicts
+** with a DELETE, and the conflict resolution was OMIT, then the update
+** is changed into an INSERT. Any undefined values in the new.* record
+** from the update change are filled in using the old.* values from
+** the conflicting DELETE. Or, if the conflict resolution was REPLACE,
+** the UPDATE change is simply omitted from the rebased changeset.
+**
+** If conflict is with a remote UPDATE and the resolution is OMIT, then
+** the old.* values are rebased using the new.* values in the remote
+** change. Or, if the resolution is REPLACE, then the change is copied
+** into the rebased changeset with updates to columns also updated by
+** the conflicting remote UPDATE removed. If this means no columns would
+** be updated, the change is omitted.
+** </dl>
+**
+** A local change may be rebased against multiple remote changes
+** simultaneously. If a single key is modified by multiple remote
+** changesets, they are combined as follows before the local changeset
+** is rebased:
+**
+** <ul>
+** <li> If there has been one or more REPLACE resolutions on a
+** key, it is rebased according to a REPLACE.
+**
+** <li> If there have been no REPLACE resolutions on a key, then
+** the local changeset is rebased according to the most recent
+** of the OMIT resolutions.
+** </ul>
+**
+** Note that conflict resolutions from multiple remote changesets are
+** combined on a per-field basis, not per-row. This means that in the
+** case of multiple remote UPDATE operations, some fields of a single
+** local change may be rebased for REPLACE while others are rebased for
+** OMIT.
+**
+** In order to rebase a local changeset, the remote changeset must first
+** be applied to the local database using sqlite3changeset_apply_v2() and
+** the buffer of rebase information captured. Then:
+**
+** <ol>
+** <li> An sqlite3_rebaser object is created by calling
+** sqlite3rebaser_create().
+** <li> The new object is configured with the rebase buffer obtained from
+** sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
+** If the local changeset is to be rebased against multiple remote
+** changesets, then sqlite3rebaser_configure() should be called
+** multiple times, in the same order that the multiple
+** sqlite3changeset_apply_v2() calls were made.
+** <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().
+** <li> The sqlite3_rebaser object is deleted by calling
+** sqlite3rebaser_delete().
+** </ol>
+*/
+typedef struct sqlite3_rebaser sqlite3_rebaser;
+
+/*
+** CAPI3REF: Create a changeset rebaser object.
+** EXPERIMENTAL
+**
+** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
+** point to the new object and return SQLITE_OK. Otherwise, if an error
+** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
+** to NULL.
+*/
+SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
+
+/*
+** CAPI3REF: Configure a changeset rebaser object.
+** EXPERIMENTAL
+**
+** Configure the changeset rebaser object to rebase changesets according
+** to the conflict resolutions described by buffer pRebase (size nRebase
+** bytes), which must have been obtained from a previous call to
+** sqlite3changeset_apply_v2().
+*/
+SQLITE_API int sqlite3rebaser_configure(
+ sqlite3_rebaser*,
+ int nRebase, const void *pRebase
+);
+
+/*
+** CAPI3REF: Rebase a changeset
+** EXPERIMENTAL
+**
+** Argument pIn must point to a buffer containing a changeset nIn bytes
+** in size. This function allocates and populates a buffer with a copy
+** of the changeset rebased according to the configuration of the
+** rebaser object passed as the first argument. If successful, (*ppOut)
+** is set to point to the new buffer containing the rebased changeset and
+** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
+** responsibility of the caller to eventually free the new buffer using
+** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
+** are set to zero and an SQLite error code returned.
+*/
+SQLITE_API int sqlite3rebaser_rebase(
+ sqlite3_rebaser*,
+ int nIn, const void *pIn,
+ int *pnOut, void **ppOut
+);
+
+/*
+** CAPI3REF: Delete a changeset rebaser object.
+** EXPERIMENTAL
+**
+** Delete the changeset rebaser object and all associated resources. There
+** should be one call to this function for each successful invocation
+** of sqlite3rebaser_create().
+*/
+SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
+
+/*
+** CAPI3REF: Streaming Versions of API functions.
+**
+** The six streaming API xxx_strm() functions serve similar purposes to the
+** corresponding non-streaming API functions:
+**
+** <table border=1 style="margin-left:8ex;margin-right:8ex">
+** <tr><th>Streaming function<th>Non-streaming equivalent</th>
+** <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
+** <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2]
+** <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
+** <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
+** <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
+** <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
+** <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
+** </table>
+**
+** Non-streaming functions that accept changesets (or patchsets) as input
+** require that the entire changeset be stored in a single buffer in memory.
+** Similarly, those that return a changeset or patchset do so by returning
+** a pointer to a single large buffer allocated using sqlite3_malloc().
+** Normally this is convenient. However, if an application running in a
+** low-memory environment is required to handle very large changesets, the
+** large contiguous memory allocations required can become onerous.
+**
+** In order to avoid this problem, instead of a single large buffer, input
+** is passed to a streaming API functions by way of a callback function that
+** the sessions module invokes to incrementally request input data as it is
+** required. In all cases, a pair of API function parameters such as
+**
+** <pre>
+** &nbsp; int nChangeset,
+** &nbsp; void *pChangeset,
+** </pre>
+**
+** Is replaced by:
+**
+** <pre>
+** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
+** &nbsp; void *pIn,
+** </pre>
+**
+** Each time the xInput callback is invoked by the sessions module, the first
+** argument passed is a copy of the supplied pIn context pointer. The second
+** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
+** error occurs the xInput method should copy up to (*pnData) bytes of data
+** into the buffer and set (*pnData) to the actual number of bytes copied
+** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
+** should be set to zero to indicate this. Or, if an error occurs, an SQLite
+** error code should be returned. In all cases, if an xInput callback returns
+** an error, all processing is abandoned and the streaming API function
+** returns a copy of the error code to the caller.
+**
+** In the case of sqlite3changeset_start_strm(), the xInput callback may be
+** invoked by the sessions module at any point during the lifetime of the
+** iterator. If such an xInput callback returns an error, the iterator enters
+** an error state, whereby all subsequent calls to iterator functions
+** immediately fail with the same error code as returned by xInput.
+**
+** Similarly, streaming API functions that return changesets (or patchsets)
+** return them in chunks by way of a callback function instead of via a
+** pointer to a single large buffer. In this case, a pair of parameters such
+** as:
+**
+** <pre>
+** &nbsp; int *pnChangeset,
+** &nbsp; void **ppChangeset,
+** </pre>
+**
+** Is replaced by:
+**
+** <pre>
+** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
+** &nbsp; void *pOut
+** </pre>
+**
+** The xOutput callback is invoked zero or more times to return data to
+** the application. The first parameter passed to each call is a copy of the
+** pOut pointer supplied by the application. The second parameter, pData,
+** points to a buffer nData bytes in size containing the chunk of output
+** data being returned. If the xOutput callback successfully processes the
+** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
+** it should return some other SQLite error code. In this case processing
+** is immediately abandoned and the streaming API function returns a copy
+** of the xOutput error code to the application.
+**
+** The sessions module never invokes an xOutput callback with the third
+** parameter set to a value less than or equal to zero. Other than this,
+** no guarantees are made as to the size of the chunks of data returned.
+*/
+SQLITE_API int sqlite3changeset_apply_strm(
+ sqlite3 *db, /* Apply change to "main" db of this handle */
+ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
+ void *pIn, /* First arg for xInput */
+ int(*xFilter)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ const char *zTab /* Table name */
+ ),
+ int(*xConflict)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
+ ),
+ void *pCtx /* First argument passed to xConflict */
+);
+SQLITE_API int sqlite3changeset_apply_v2_strm(
+ sqlite3 *db, /* Apply change to "main" db of this handle */
+ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
+ void *pIn, /* First arg for xInput */
+ int(*xFilter)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ const char *zTab /* Table name */
+ ),
+ int(*xConflict)(
+ void *pCtx, /* Copy of sixth arg to _apply() */
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
+ ),
+ void *pCtx, /* First argument passed to xConflict */
+ void **ppRebase, int *pnRebase,
+ int flags
+);
+SQLITE_API int sqlite3changeset_concat_strm(
+ int (*xInputA)(void *pIn, void *pData, int *pnData),
+ void *pInA,
+ int (*xInputB)(void *pIn, void *pData, int *pnData),
+ void *pInB,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+);
+SQLITE_API int sqlite3changeset_invert_strm(
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+);
+SQLITE_API int sqlite3changeset_start_strm(
+ sqlite3_changeset_iter **pp,
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn
+);
+SQLITE_API int sqlite3changeset_start_v2_strm(
+ sqlite3_changeset_iter **pp,
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn,
+ int flags
+);
+SQLITE_API int sqlite3session_changeset_strm(
+ sqlite3_session *pSession,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+);
+SQLITE_API int sqlite3session_patchset_strm(
+ sqlite3_session *pSession,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+);
+SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn
+);
+SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+);
+SQLITE_API int sqlite3rebaser_rebase_strm(
+ sqlite3_rebaser *pRebaser,
+ int (*xInput)(void *pIn, void *pData, int *pnData),
+ void *pIn,
+ int (*xOutput)(void *pOut, const void *pData, int nData),
+ void *pOut
+);
+
+/*
+** CAPI3REF: Configure global parameters
+**
+** The sqlite3session_config() interface is used to make global configuration
+** changes to the sessions module in order to tune it to the specific needs
+** of the application.
+**
+** The sqlite3session_config() interface is not threadsafe. If it is invoked
+** while any other thread is inside any other sessions method then the
+** results are undefined. Furthermore, if it is invoked after any sessions
+** related objects have been created, the results are also undefined.
+**
+** The first argument to the sqlite3session_config() function must be one
+** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The
+** interpretation of the (void*) value passed as the second parameter and
+** the effect of calling this function depends on the value of the first
+** parameter.
+**
+** <dl>
+** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd>
+** By default, the sessions module streaming interfaces attempt to input
+** and output data in approximately 1 KiB chunks. This operand may be used
+** to set and query the value of this configuration setting. The pointer
+** passed as the second argument must point to a value of type (int).
+** If this value is greater than 0, it is used as the new streaming data
+** chunk size for both input and output. Before returning, the (int) value
+** pointed to by pArg is set to the final value of the streaming interface
+** chunk size.
+** </dl>
+**
+** This function returns SQLITE_OK if successful, or an SQLite error code
+** otherwise.
+*/
+SQLITE_API int sqlite3session_config(int op, void *pArg);
+
+/*
+** CAPI3REF: Values for sqlite3session_config().
+*/
+#define SQLITE_SESSION_CONFIG_STRMSIZE 1
+
+/*
+** Make sure we can call this stuff from C++.
+*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
+
+/******** End of sqlite3session.h *********/
+/******** Begin file fts5.h *********/
+/*
+** 2014 May 31
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** Interfaces to extend FTS5. Using the interfaces defined in this file,
+** FTS5 may be extended with:
+**
+** * custom tokenizers, and
+** * custom auxiliary functions.
+*/
+
+
+#ifndef _FTS5_H
+#define _FTS5_H
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*************************************************************************
+** CUSTOM AUXILIARY FUNCTIONS
+**
+** Virtual table implementations may overload SQL functions by implementing
+** the sqlite3_module.xFindFunction() method.
+*/
+
+typedef struct Fts5ExtensionApi Fts5ExtensionApi;
+typedef struct Fts5Context Fts5Context;
+typedef struct Fts5PhraseIter Fts5PhraseIter;
+
+typedef void (*fts5_extension_function)(
+ const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
+ Fts5Context *pFts, /* First arg to pass to pApi functions */
+ sqlite3_context *pCtx, /* Context for returning result/error */
+ int nVal, /* Number of values in apVal[] array */
+ sqlite3_value **apVal /* Array of trailing arguments */
+);
+
+struct Fts5PhraseIter {
+ const unsigned char *a;
+ const unsigned char *b;
+};
+
+/*
+** EXTENSION API FUNCTIONS
+**
+** xUserData(pFts):
+** Return a copy of the context pointer the extension function was
+** registered with.
+**
+** xColumnTotalSize(pFts, iCol, pnToken):
+** If parameter iCol is less than zero, set output variable *pnToken
+** to the total number of tokens in the FTS5 table. Or, if iCol is
+** non-negative but less than the number of columns in the table, return
+** the total number of tokens in column iCol, considering all rows in
+** the FTS5 table.
+**
+** If parameter iCol is greater than or equal to the number of columns
+** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
+** an OOM condition or IO error), an appropriate SQLite error code is
+** returned.
+**
+** xColumnCount(pFts):
+** Return the number of columns in the table.
+**
+** xColumnSize(pFts, iCol, pnToken):
+** If parameter iCol is less than zero, set output variable *pnToken
+** to the total number of tokens in the current row. Or, if iCol is
+** non-negative but less than the number of columns in the table, set
+** *pnToken to the number of tokens in column iCol of the current row.
+**
+** If parameter iCol is greater than or equal to the number of columns
+** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
+** an OOM condition or IO error), an appropriate SQLite error code is
+** returned.
+**
+** This function may be quite inefficient if used with an FTS5 table
+** created with the "columnsize=0" option.
+**
+** xColumnText:
+** This function attempts to retrieve the text of column iCol of the
+** current document. If successful, (*pz) is set to point to a buffer
+** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
+** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
+** if an error occurs, an SQLite error code is returned and the final values
+** of (*pz) and (*pn) are undefined.
+**
+** xPhraseCount:
+** Returns the number of phrases in the current query expression.
+**
+** xPhraseSize:
+** Returns the number of tokens in phrase iPhrase of the query. Phrases
+** are numbered starting from zero.
+**
+** xInstCount:
+** Set *pnInst to the total number of occurrences of all phrases within
+** the query within the current row. Return SQLITE_OK if successful, or
+** an error code (i.e. SQLITE_NOMEM) if an error occurs.
+**
+** This API can be quite slow if used with an FTS5 table created with the
+** "detail=none" or "detail=column" option. If the FTS5 table is created
+** with either "detail=none" or "detail=column" and "content=" option
+** (i.e. if it is a contentless table), then this API always returns 0.
+**
+** xInst:
+** Query for the details of phrase match iIdx within the current row.
+** Phrase matches are numbered starting from zero, so the iIdx argument
+** should be greater than or equal to zero and smaller than the value
+** output by xInstCount().
+**
+** Usually, output parameter *piPhrase is set to the phrase number, *piCol
+** to the column in which it occurs and *piOff the token offset of the
+** first token of the phrase. Returns SQLITE_OK if successful, or an error
+** code (i.e. SQLITE_NOMEM) if an error occurs.
+**
+** This API can be quite slow if used with an FTS5 table created with the
+** "detail=none" or "detail=column" option.
+**
+** xRowid:
+** Returns the rowid of the current row.
+**
+** xTokenize:
+** Tokenize text using the tokenizer belonging to the FTS5 table.
+**
+** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
+** This API function is used to query the FTS table for phrase iPhrase
+** of the current query. Specifically, a query equivalent to:
+**
+** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
+**
+** with $p set to a phrase equivalent to the phrase iPhrase of the
+** current query is executed. Any column filter that applies to
+** phrase iPhrase of the current query is included in $p. For each
+** row visited, the callback function passed as the fourth argument
+** is invoked. The context and API objects passed to the callback
+** function may be used to access the properties of each matched row.
+** Invoking Api.xUserData() returns a copy of the pointer passed as
+** the third argument to pUserData.
+**
+** If the callback function returns any value other than SQLITE_OK, the
+** query is abandoned and the xQueryPhrase function returns immediately.
+** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
+** Otherwise, the error code is propagated upwards.
+**
+** If the query runs to completion without incident, SQLITE_OK is returned.
+** Or, if some error occurs before the query completes or is aborted by
+** the callback, an SQLite error code is returned.
+**
+**
+** xSetAuxdata(pFts5, pAux, xDelete)
+**
+** Save the pointer passed as the second argument as the extension function's
+** "auxiliary data". The pointer may then be retrieved by the current or any
+** future invocation of the same fts5 extension function made as part of
+** the same MATCH query using the xGetAuxdata() API.
+**
+** Each extension function is allocated a single auxiliary data slot for
+** each FTS query (MATCH expression). If the extension function is invoked
+** more than once for a single FTS query, then all invocations share a
+** single auxiliary data context.
+**
+** If there is already an auxiliary data pointer when this function is
+** invoked, then it is replaced by the new pointer. If an xDelete callback
+** was specified along with the original pointer, it is invoked at this
+** point.
+**
+** The xDelete callback, if one is specified, is also invoked on the
+** auxiliary data pointer after the FTS5 query has finished.
+**
+** If an error (e.g. an OOM condition) occurs within this function,
+** the auxiliary data is set to NULL and an error code returned. If the
+** xDelete parameter was not NULL, it is invoked on the auxiliary data
+** pointer before returning.
+**
+**
+** xGetAuxdata(pFts5, bClear)
+**
+** Returns the current auxiliary data pointer for the fts5 extension
+** function. See the xSetAuxdata() method for details.
+**
+** If the bClear argument is non-zero, then the auxiliary data is cleared
+** (set to NULL) before this function returns. In this case the xDelete,
+** if any, is not invoked.
+**
+**
+** xRowCount(pFts5, pnRow)
+**
+** This function is used to retrieve the total number of rows in the table.
+** In other words, the same value that would be returned by:
+**
+** SELECT count(*) FROM ftstable;
+**
+** xPhraseFirst()
+** This function is used, along with type Fts5PhraseIter and the xPhraseNext
+** method, to iterate through all instances of a single query phrase within
+** the current row. This is the same information as is accessible via the
+** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
+** to use, this API may be faster under some circumstances. To iterate
+** through instances of phrase iPhrase, use the following code:
+**
+** Fts5PhraseIter iter;
+** int iCol, iOff;
+** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
+** iCol>=0;
+** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
+** ){
+** // An instance of phrase iPhrase at offset iOff of column iCol
+** }
+**
+** The Fts5PhraseIter structure is defined above. Applications should not
+** modify this structure directly - it should only be used as shown above
+** with the xPhraseFirst() and xPhraseNext() API methods (and by
+** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
+**
+** This API can be quite slow if used with an FTS5 table created with the
+** "detail=none" or "detail=column" option. If the FTS5 table is created
+** with either "detail=none" or "detail=column" and "content=" option
+** (i.e. if it is a contentless table), then this API always iterates
+** through an empty set (all calls to xPhraseFirst() set iCol to -1).
+**
+** xPhraseNext()
+** See xPhraseFirst above.
+**
+** xPhraseFirstColumn()
+** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
+** and xPhraseNext() APIs described above. The difference is that instead
+** of iterating through all instances of a phrase in the current row, these
+** APIs are used to iterate through the set of columns in the current row
+** that contain one or more instances of a specified phrase. For example:
+**
+** Fts5PhraseIter iter;
+** int iCol;
+** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
+** iCol>=0;
+** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
+** ){
+** // Column iCol contains at least one instance of phrase iPhrase
+** }
+**
+** This API can be quite slow if used with an FTS5 table created with the
+** "detail=none" option. If the FTS5 table is created with either
+** "detail=none" "content=" option (i.e. if it is a contentless table),
+** then this API always iterates through an empty set (all calls to
+** xPhraseFirstColumn() set iCol to -1).
+**
+** The information accessed using this API and its companion
+** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
+** (or xInst/xInstCount). The chief advantage of this API is that it is
+** significantly more efficient than those alternatives when used with
+** "detail=column" tables.
+**
+** xPhraseNextColumn()
+** See xPhraseFirstColumn above.
+*/
+struct Fts5ExtensionApi {
+ int iVersion; /* Currently always set to 3 */
+
+ void *(*xUserData)(Fts5Context*);
+
+ int (*xColumnCount)(Fts5Context*);
+ int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
+ int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
+
+ int (*xTokenize)(Fts5Context*,
+ const char *pText, int nText, /* Text to tokenize */
+ void *pCtx, /* Context passed to xToken() */
+ int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
+ );
+
+ int (*xPhraseCount)(Fts5Context*);
+ int (*xPhraseSize)(Fts5Context*, int iPhrase);
+
+ int (*xInstCount)(Fts5Context*, int *pnInst);
+ int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
+
+ sqlite3_int64 (*xRowid)(Fts5Context*);
+ int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
+ int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
+
+ int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
+ int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
+ );
+ int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
+ void *(*xGetAuxdata)(Fts5Context*, int bClear);
+
+ int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
+ void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
+
+ int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
+ void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
+};
+
+/*
+** CUSTOM AUXILIARY FUNCTIONS
+*************************************************************************/
+
+/*************************************************************************
+** CUSTOM TOKENIZERS
+**
+** Applications may also register custom tokenizer types. A tokenizer
+** is registered by providing fts5 with a populated instance of the
+** following structure. All structure methods must be defined, setting
+** any member of the fts5_tokenizer struct to NULL leads to undefined
+** behaviour. The structure methods are expected to function as follows:
+**
+** xCreate:
+** This function is used to allocate and initialize a tokenizer instance.
+** A tokenizer instance is required to actually tokenize text.
+**
+** The first argument passed to this function is a copy of the (void*)
+** pointer provided by the application when the fts5_tokenizer object
+** was registered with FTS5 (the third argument to xCreateTokenizer()).
+** The second and third arguments are an array of nul-terminated strings
+** containing the tokenizer arguments, if any, specified following the
+** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
+** to create the FTS5 table.
+**
+** The final argument is an output variable. If successful, (*ppOut)
+** should be set to point to the new tokenizer handle and SQLITE_OK
+** returned. If an error occurs, some value other than SQLITE_OK should
+** be returned. In this case, fts5 assumes that the final value of *ppOut
+** is undefined.
+**
+** xDelete:
+** This function is invoked to delete a tokenizer handle previously
+** allocated using xCreate(). Fts5 guarantees that this function will
+** be invoked exactly once for each successful call to xCreate().
+**
+** xTokenize:
+** This function is expected to tokenize the nText byte string indicated
+** by argument pText. pText may or may not be nul-terminated. The first
+** argument passed to this function is a pointer to an Fts5Tokenizer object
+** returned by an earlier call to xCreate().
+**
+** The second argument indicates the reason that FTS5 is requesting
+** tokenization of the supplied text. This is always one of the following
+** four values:
+**
+** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
+** or removed from the FTS table. The tokenizer is being invoked to
+** determine the set of tokens to add to (or delete from) the
+** FTS index.
+**
+** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
+** against the FTS index. The tokenizer is being called to tokenize
+** a bareword or quoted string specified as part of the query.
+**
+** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
+** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
+** followed by a "*" character, indicating that the last token
+** returned by the tokenizer will be treated as a token prefix.
+**
+** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
+** satisfy an fts5_api.xTokenize() request made by an auxiliary
+** function. Or an fts5_api.xColumnSize() request made by the same
+** on a columnsize=0 database.
+** </ul>
+**
+** For each token in the input string, the supplied callback xToken() must
+** be invoked. The first argument to it should be a copy of the pointer
+** passed as the second argument to xTokenize(). The third and fourth
+** arguments are a pointer to a buffer containing the token text, and the
+** size of the token in bytes. The 4th and 5th arguments are the byte offsets
+** of the first byte of and first byte immediately following the text from
+** which the token is derived within the input.
+**
+** The second argument passed to the xToken() callback ("tflags") should
+** normally be set to 0. The exception is if the tokenizer supports
+** synonyms. In this case see the discussion below for details.
+**
+** FTS5 assumes the xToken() callback is invoked for each token in the
+** order that they occur within the input text.
+**
+** If an xToken() callback returns any value other than SQLITE_OK, then
+** the tokenization should be abandoned and the xTokenize() method should
+** immediately return a copy of the xToken() return value. Or, if the
+** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
+** if an error occurs with the xTokenize() implementation itself, it
+** may abandon the tokenization and return any error code other than
+** SQLITE_OK or SQLITE_DONE.
+**
+** SYNONYM SUPPORT
+**
+** Custom tokenizers may also support synonyms. Consider a case in which a
+** user wishes to query for a phrase such as "first place". Using the
+** built-in tokenizers, the FTS5 query 'first + place' will match instances
+** of "first place" within the document set, but not alternative forms
+** such as "1st place". In some applications, it would be better to match
+** all instances of "first place" or "1st place" regardless of which form
+** the user specified in the MATCH query text.
+**
+** There are several ways to approach this in FTS5:
+**
+** <ol><li> By mapping all synonyms to a single token. In this case, using
+** the above example, this means that the tokenizer returns the
+** same token for inputs "first" and "1st". Say that token is in
+** fact "first", so that when the user inserts the document "I won
+** 1st place" entries are added to the index for tokens "i", "won",
+** "first" and "place". If the user then queries for '1st + place',
+** the tokenizer substitutes "first" for "1st" and the query works
+** as expected.
+**
+** <li> By querying the index for all synonyms of each query term
+** separately. In this case, when tokenizing query text, the
+** tokenizer may provide multiple synonyms for a single term
+** within the document. FTS5 then queries the index for each
+** synonym individually. For example, faced with the query:
+**
+** <codeblock>
+** ... MATCH 'first place'</codeblock>
+**
+** the tokenizer offers both "1st" and "first" as synonyms for the
+** first token in the MATCH query and FTS5 effectively runs a query
+** similar to:
+**
+** <codeblock>
+** ... MATCH '(first OR 1st) place'</codeblock>
+**
+** except that, for the purposes of auxiliary functions, the query
+** still appears to contain just two phrases - "(first OR 1st)"
+** being treated as a single phrase.
+**
+** <li> By adding multiple synonyms for a single term to the FTS index.
+** Using this method, when tokenizing document text, the tokenizer
+** provides multiple synonyms for each token. So that when a
+** document such as "I won first place" is tokenized, entries are
+** added to the FTS index for "i", "won", "first", "1st" and
+** "place".
+**
+** This way, even if the tokenizer does not provide synonyms
+** when tokenizing query text (it should not - to do so would be
+** inefficient), it doesn't matter if the user queries for
+** 'first + place' or '1st + place', as there are entries in the
+** FTS index corresponding to both forms of the first token.
+** </ol>
+**
+** Whether it is parsing document or query text, any call to xToken that
+** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
+** is considered to supply a synonym for the previous token. For example,
+** when parsing the document "I won first place", a tokenizer that supports
+** synonyms would call xToken() 5 times, as follows:
+**
+** <codeblock>
+** xToken(pCtx, 0, "i", 1, 0, 1);
+** xToken(pCtx, 0, "won", 3, 2, 5);
+** xToken(pCtx, 0, "first", 5, 6, 11);
+** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
+** xToken(pCtx, 0, "place", 5, 12, 17);
+**</codeblock>
+**
+** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
+** xToken() is called. Multiple synonyms may be specified for a single token
+** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
+** There is no limit to the number of synonyms that may be provided for a
+** single token.
+**
+** In many cases, method (1) above is the best approach. It does not add
+** extra data to the FTS index or require FTS5 to query for multiple terms,
+** so it is efficient in terms of disk space and query speed. However, it
+** does not support prefix queries very well. If, as suggested above, the
+** token "first" is substituted for "1st" by the tokenizer, then the query:
+**
+** <codeblock>
+** ... MATCH '1s*'</codeblock>
+**
+** will not match documents that contain the token "1st" (as the tokenizer
+** will probably not map "1s" to any prefix of "first").
+**
+** For full prefix support, method (3) may be preferred. In this case,
+** because the index contains entries for both "first" and "1st", prefix
+** queries such as 'fi*' or '1s*' will match correctly. However, because
+** extra entries are added to the FTS index, this method uses more space
+** within the database.
+**
+** Method (2) offers a midpoint between (1) and (3). Using this method,
+** a query such as '1s*' will match documents that contain the literal
+** token "1st", but not "first" (assuming the tokenizer is not able to
+** provide synonyms for prefixes). However, a non-prefix query like '1st'
+** will match against "1st" and "first". This method does not require
+** extra disk space, as no extra entries are added to the FTS index.
+** On the other hand, it may require more CPU cycles to run MATCH queries,
+** as separate queries of the FTS index are required for each synonym.
+**
+** When using methods (2) or (3), it is important that the tokenizer only
+** provide synonyms when tokenizing document text (method (2)) or query
+** text (method (3)), not both. Doing so will not cause any errors, but is
+** inefficient.
+*/
+typedef struct Fts5Tokenizer Fts5Tokenizer;
+typedef struct fts5_tokenizer fts5_tokenizer;
+struct fts5_tokenizer {
+ int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
+ void (*xDelete)(Fts5Tokenizer*);
+ int (*xTokenize)(Fts5Tokenizer*,
+ void *pCtx,
+ int flags, /* Mask of FTS5_TOKENIZE_* flags */
+ const char *pText, int nText,
+ int (*xToken)(
+ void *pCtx, /* Copy of 2nd argument to xTokenize() */
+ int tflags, /* Mask of FTS5_TOKEN_* flags */
+ const char *pToken, /* Pointer to buffer containing token */
+ int nToken, /* Size of token in bytes */
+ int iStart, /* Byte offset of token within input text */
+ int iEnd /* Byte offset of end of token within input text */
+ )
+ );
+};
+
+/* Flags that may be passed as the third argument to xTokenize() */
+#define FTS5_TOKENIZE_QUERY 0x0001
+#define FTS5_TOKENIZE_PREFIX 0x0002
+#define FTS5_TOKENIZE_DOCUMENT 0x0004
+#define FTS5_TOKENIZE_AUX 0x0008
+
+/* Flags that may be passed by the tokenizer implementation back to FTS5
+** as the third argument to the supplied xToken callback. */
+#define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
+
+/*
+** END OF CUSTOM TOKENIZERS
+*************************************************************************/
+
+/*************************************************************************
+** FTS5 EXTENSION REGISTRATION API
+*/
+typedef struct fts5_api fts5_api;
+struct fts5_api {
+ int iVersion; /* Currently always set to 2 */
+
+ /* Create a new tokenizer */
+ int (*xCreateTokenizer)(
+ fts5_api *pApi,
+ const char *zName,
+ void *pContext,
+ fts5_tokenizer *pTokenizer,
+ void (*xDestroy)(void*)
+ );
+
+ /* Find an existing tokenizer */
+ int (*xFindTokenizer)(
+ fts5_api *pApi,
+ const char *zName,
+ void **ppContext,
+ fts5_tokenizer *pTokenizer
+ );
+
+ /* Create a new auxiliary function */
+ int (*xCreateFunction)(
+ fts5_api *pApi,
+ const char *zName,
+ void *pContext,
+ fts5_extension_function xFunction,
+ void (*xDestroy)(void*)
+ );
+};
+
+/*
+** END OF REGISTRATION API
+*************************************************************************/
+
+#ifdef __cplusplus
+} /* end of the 'extern "C"' block */
+#endif
+
+#endif /* _FTS5_H */
+
+/******** End of fts5.h *********/
diff --git a/third_party/heimdal/lib/sqlite/sqlite3ext.h b/third_party/heimdal/lib/sqlite/sqlite3ext.h
new file mode 100644
index 0000000..78c19a0
--- /dev/null
+++ b/third_party/heimdal/lib/sqlite/sqlite3ext.h
@@ -0,0 +1,659 @@
+/*
+** 2006 June 7
+**
+** The author disclaims copyright to this source code. In place of
+** a legal notice, here is a blessing:
+**
+** May you do good and not evil.
+** May you find forgiveness for yourself and forgive others.
+** May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This header file defines the SQLite interface for use by
+** shared libraries that want to be imported as extensions into
+** an SQLite instance. Shared libraries that intend to be loaded
+** as extensions by SQLite should #include this file instead of
+** sqlite3.h.
+*/
+#ifndef SQLITE3EXT_H
+#define SQLITE3EXT_H
+#include "sqlite3.h"
+
+/*
+** The following structure holds pointers to all of the SQLite API
+** routines.
+**
+** WARNING: In order to maintain backwards compatibility, add new
+** interfaces to the end of this structure only. If you insert new
+** interfaces in the middle of this structure, then older different
+** versions of SQLite will not be able to load each other's shared
+** libraries!
+*/
+struct sqlite3_api_routines {
+ void * (*aggregate_context)(sqlite3_context*,int nBytes);
+ int (*aggregate_count)(sqlite3_context*);
+ int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
+ int (*bind_double)(sqlite3_stmt*,int,double);
+ int (*bind_int)(sqlite3_stmt*,int,int);
+ int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
+ int (*bind_null)(sqlite3_stmt*,int);
+ int (*bind_parameter_count)(sqlite3_stmt*);
+ int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
+ const char * (*bind_parameter_name)(sqlite3_stmt*,int);
+ int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
+ int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
+ int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
+ int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
+ int (*busy_timeout)(sqlite3*,int ms);
+ int (*changes)(sqlite3*);
+ int (*close)(sqlite3*);
+ int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
+ int eTextRep,const char*));
+ int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
+ int eTextRep,const void*));
+ const void * (*column_blob)(sqlite3_stmt*,int iCol);
+ int (*column_bytes)(sqlite3_stmt*,int iCol);
+ int (*column_bytes16)(sqlite3_stmt*,int iCol);
+ int (*column_count)(sqlite3_stmt*pStmt);
+ const char * (*column_database_name)(sqlite3_stmt*,int);
+ const void * (*column_database_name16)(sqlite3_stmt*,int);
+ const char * (*column_decltype)(sqlite3_stmt*,int i);
+ const void * (*column_decltype16)(sqlite3_stmt*,int);
+ double (*column_double)(sqlite3_stmt*,int iCol);
+ int (*column_int)(sqlite3_stmt*,int iCol);
+ sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
+ const char * (*column_name)(sqlite3_stmt*,int);
+ const void * (*column_name16)(sqlite3_stmt*,int);
+ const char * (*column_origin_name)(sqlite3_stmt*,int);
+ const void * (*column_origin_name16)(sqlite3_stmt*,int);
+ const char * (*column_table_name)(sqlite3_stmt*,int);
+ const void * (*column_table_name16)(sqlite3_stmt*,int);
+ const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
+ const void * (*column_text16)(sqlite3_stmt*,int iCol);
+ int (*column_type)(sqlite3_stmt*,int iCol);
+ sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
+ void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
+ int (*complete)(const char*sql);
+ int (*complete16)(const void*sql);
+ int (*create_collation)(sqlite3*,const char*,int,void*,
+ int(*)(void*,int,const void*,int,const void*));
+ int (*create_collation16)(sqlite3*,const void*,int,void*,
+ int(*)(void*,int,const void*,int,const void*));
+ int (*create_function)(sqlite3*,const char*,int,int,void*,
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*));
+ int (*create_function16)(sqlite3*,const void*,int,int,void*,
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*));
+ int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
+ int (*data_count)(sqlite3_stmt*pStmt);
+ sqlite3 * (*db_handle)(sqlite3_stmt*);
+ int (*declare_vtab)(sqlite3*,const char*);
+ int (*enable_shared_cache)(int);
+ int (*errcode)(sqlite3*db);
+ const char * (*errmsg)(sqlite3*);
+ const void * (*errmsg16)(sqlite3*);
+ int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
+ int (*expired)(sqlite3_stmt*);
+ int (*finalize)(sqlite3_stmt*pStmt);
+ void (*free)(void*);
+ void (*free_table)(char**result);
+ int (*get_autocommit)(sqlite3*);
+ void * (*get_auxdata)(sqlite3_context*,int);
+ int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
+ int (*global_recover)(void);
+ void (*interruptx)(sqlite3*);
+ sqlite_int64 (*last_insert_rowid)(sqlite3*);
+ const char * (*libversion)(void);
+ int (*libversion_number)(void);
+ void *(*malloc)(int);
+ char * (*mprintf)(const char*,...);
+ int (*open)(const char*,sqlite3**);
+ int (*open16)(const void*,sqlite3**);
+ int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
+ int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
+ void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
+ void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
+ void *(*realloc)(void*,int);
+ int (*reset)(sqlite3_stmt*pStmt);
+ void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
+ void (*result_double)(sqlite3_context*,double);
+ void (*result_error)(sqlite3_context*,const char*,int);
+ void (*result_error16)(sqlite3_context*,const void*,int);
+ void (*result_int)(sqlite3_context*,int);
+ void (*result_int64)(sqlite3_context*,sqlite_int64);
+ void (*result_null)(sqlite3_context*);
+ void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
+ void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
+ void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
+ void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
+ void (*result_value)(sqlite3_context*,sqlite3_value*);
+ void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
+ int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
+ const char*,const char*),void*);
+ void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
+ char * (*xsnprintf)(int,char*,const char*,...);
+ int (*step)(sqlite3_stmt*);
+ int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
+ char const**,char const**,int*,int*,int*);
+ void (*thread_cleanup)(void);
+ int (*total_changes)(sqlite3*);
+ void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
+ int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
+ void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
+ sqlite_int64),void*);
+ void * (*user_data)(sqlite3_context*);
+ const void * (*value_blob)(sqlite3_value*);
+ int (*value_bytes)(sqlite3_value*);
+ int (*value_bytes16)(sqlite3_value*);
+ double (*value_double)(sqlite3_value*);
+ int (*value_int)(sqlite3_value*);
+ sqlite_int64 (*value_int64)(sqlite3_value*);
+ int (*value_numeric_type)(sqlite3_value*);
+ const unsigned char * (*value_text)(sqlite3_value*);
+ const void * (*value_text16)(sqlite3_value*);
+ const void * (*value_text16be)(sqlite3_value*);
+ const void * (*value_text16le)(sqlite3_value*);
+ int (*value_type)(sqlite3_value*);
+ char *(*vmprintf)(const char*,va_list);
+ /* Added ??? */
+ int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
+ /* Added by 3.3.13 */
+ int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
+ int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
+ int (*clear_bindings)(sqlite3_stmt*);
+ /* Added by 3.4.1 */
+ int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
+ void (*xDestroy)(void *));
+ /* Added by 3.5.0 */
+ int (*bind_zeroblob)(sqlite3_stmt*,int,int);
+ int (*blob_bytes)(sqlite3_blob*);
+ int (*blob_close)(sqlite3_blob*);
+ int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
+ int,sqlite3_blob**);
+ int (*blob_read)(sqlite3_blob*,void*,int,int);
+ int (*blob_write)(sqlite3_blob*,const void*,int,int);
+ int (*create_collation_v2)(sqlite3*,const char*,int,void*,
+ int(*)(void*,int,const void*,int,const void*),
+ void(*)(void*));
+ int (*file_control)(sqlite3*,const char*,int,void*);
+ sqlite3_int64 (*memory_highwater)(int);
+ sqlite3_int64 (*memory_used)(void);
+ sqlite3_mutex *(*mutex_alloc)(int);
+ void (*mutex_enter)(sqlite3_mutex*);
+ void (*mutex_free)(sqlite3_mutex*);
+ void (*mutex_leave)(sqlite3_mutex*);
+ int (*mutex_try)(sqlite3_mutex*);
+ int (*open_v2)(const char*,sqlite3**,int,const char*);
+ int (*release_memory)(int);
+ void (*result_error_nomem)(sqlite3_context*);
+ void (*result_error_toobig)(sqlite3_context*);
+ int (*sleep)(int);
+ void (*soft_heap_limit)(int);
+ sqlite3_vfs *(*vfs_find)(const char*);
+ int (*vfs_register)(sqlite3_vfs*,int);
+ int (*vfs_unregister)(sqlite3_vfs*);
+ int (*xthreadsafe)(void);
+ void (*result_zeroblob)(sqlite3_context*,int);
+ void (*result_error_code)(sqlite3_context*,int);
+ int (*test_control)(int, ...);
+ void (*randomness)(int,void*);
+ sqlite3 *(*context_db_handle)(sqlite3_context*);
+ int (*extended_result_codes)(sqlite3*,int);
+ int (*limit)(sqlite3*,int,int);
+ sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
+ const char *(*sql)(sqlite3_stmt*);
+ int (*status)(int,int*,int*,int);
+ int (*backup_finish)(sqlite3_backup*);
+ sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
+ int (*backup_pagecount)(sqlite3_backup*);
+ int (*backup_remaining)(sqlite3_backup*);
+ int (*backup_step)(sqlite3_backup*,int);
+ const char *(*compileoption_get)(int);
+ int (*compileoption_used)(const char*);
+ int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*),
+ void(*xDestroy)(void*));
+ int (*db_config)(sqlite3*,int,...);
+ sqlite3_mutex *(*db_mutex)(sqlite3*);
+ int (*db_status)(sqlite3*,int,int*,int*,int);
+ int (*extended_errcode)(sqlite3*);
+ void (*log)(int,const char*,...);
+ sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
+ const char *(*sourceid)(void);
+ int (*stmt_status)(sqlite3_stmt*,int,int);
+ int (*strnicmp)(const char*,const char*,int);
+ int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
+ int (*wal_autocheckpoint)(sqlite3*,int);
+ int (*wal_checkpoint)(sqlite3*,const char*);
+ void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
+ int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
+ int (*vtab_config)(sqlite3*,int op,...);
+ int (*vtab_on_conflict)(sqlite3*);
+ /* Version 3.7.16 and later */
+ int (*close_v2)(sqlite3*);
+ const char *(*db_filename)(sqlite3*,const char*);
+ int (*db_readonly)(sqlite3*,const char*);
+ int (*db_release_memory)(sqlite3*);
+ const char *(*errstr)(int);
+ int (*stmt_busy)(sqlite3_stmt*);
+ int (*stmt_readonly)(sqlite3_stmt*);
+ int (*stricmp)(const char*,const char*);
+ int (*uri_boolean)(const char*,const char*,int);
+ sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
+ const char *(*uri_parameter)(const char*,const char*);
+ char *(*xvsnprintf)(int,char*,const char*,va_list);
+ int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
+ /* Version 3.8.7 and later */
+ int (*auto_extension)(void(*)(void));
+ int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
+ void(*)(void*));
+ int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
+ void(*)(void*),unsigned char);
+ int (*cancel_auto_extension)(void(*)(void));
+ int (*load_extension)(sqlite3*,const char*,const char*,char**);
+ void *(*malloc64)(sqlite3_uint64);
+ sqlite3_uint64 (*msize)(void*);
+ void *(*realloc64)(void*,sqlite3_uint64);
+ void (*reset_auto_extension)(void);
+ void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
+ void(*)(void*));
+ void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
+ void(*)(void*), unsigned char);
+ int (*strglob)(const char*,const char*);
+ /* Version 3.8.11 and later */
+ sqlite3_value *(*value_dup)(const sqlite3_value*);
+ void (*value_free)(sqlite3_value*);
+ int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
+ int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
+ /* Version 3.9.0 and later */
+ unsigned int (*value_subtype)(sqlite3_value*);
+ void (*result_subtype)(sqlite3_context*,unsigned int);
+ /* Version 3.10.0 and later */
+ int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
+ int (*strlike)(const char*,const char*,unsigned int);
+ int (*db_cacheflush)(sqlite3*);
+ /* Version 3.12.0 and later */
+ int (*system_errno)(sqlite3*);
+ /* Version 3.14.0 and later */
+ int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
+ char *(*expanded_sql)(sqlite3_stmt*);
+ /* Version 3.18.0 and later */
+ void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
+ /* Version 3.20.0 and later */
+ int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
+ sqlite3_stmt**,const char**);
+ int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
+ sqlite3_stmt**,const void**);
+ int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
+ void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
+ void *(*value_pointer)(sqlite3_value*,const char*);
+ int (*vtab_nochange)(sqlite3_context*);
+ int (*value_nochange)(sqlite3_value*);
+ const char *(*vtab_collation)(sqlite3_index_info*,int);
+ /* Version 3.24.0 and later */
+ int (*keyword_count)(void);
+ int (*keyword_name)(int,const char**,int*);
+ int (*keyword_check)(const char*,int);
+ sqlite3_str *(*str_new)(sqlite3*);
+ char *(*str_finish)(sqlite3_str*);
+ void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);
+ void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);
+ void (*str_append)(sqlite3_str*, const char *zIn, int N);
+ void (*str_appendall)(sqlite3_str*, const char *zIn);
+ void (*str_appendchar)(sqlite3_str*, int N, char C);
+ void (*str_reset)(sqlite3_str*);
+ int (*str_errcode)(sqlite3_str*);
+ int (*str_length)(sqlite3_str*);
+ char *(*str_value)(sqlite3_str*);
+ /* Version 3.25.0 and later */
+ int (*create_window_function)(sqlite3*,const char*,int,int,void*,
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
+ void (*xFinal)(sqlite3_context*),
+ void (*xValue)(sqlite3_context*),
+ void (*xInv)(sqlite3_context*,int,sqlite3_value**),
+ void(*xDestroy)(void*));
+ /* Version 3.26.0 and later */
+ const char *(*normalized_sql)(sqlite3_stmt*);
+ /* Version 3.28.0 and later */
+ int (*stmt_isexplain)(sqlite3_stmt*);
+ int (*value_frombind)(sqlite3_value*);
+ /* Version 3.30.0 and later */
+ int (*drop_modules)(sqlite3*,const char**);
+ /* Version 3.31.0 and later */
+ sqlite3_int64 (*hard_heap_limit64)(sqlite3_int64);
+ const char *(*uri_key)(const char*,int);
+ const char *(*filename_database)(const char*);
+ const char *(*filename_journal)(const char*);
+ const char *(*filename_wal)(const char*);
+ /* Version 3.32.0 and later */
+ char *(*create_filename)(const char*,const char*,const char*,
+ int,const char**);
+ void (*free_filename)(char*);
+ sqlite3_file *(*database_file_object)(const char*);
+};
+
+/*
+** This is the function signature used for all extension entry points. It
+** is also defined in the file "loadext.c".
+*/
+typedef int (*sqlite3_loadext_entry)(
+ sqlite3 *db, /* Handle to the database. */
+ char **pzErrMsg, /* Used to set error string on failure. */
+ const sqlite3_api_routines *pThunk /* Extension API function pointers. */
+);
+
+/*
+** The following macros redefine the API routines so that they are
+** redirected through the global sqlite3_api structure.
+**
+** This header file is also used by the loadext.c source file
+** (part of the main SQLite library - not an extension) so that
+** it can get access to the sqlite3_api_routines structure
+** definition. But the main library does not want to redefine
+** the API. So the redefinition macros are only valid if the
+** SQLITE_CORE macros is undefined.
+*/
+#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
+#define sqlite3_aggregate_context sqlite3_api->aggregate_context
+#ifndef SQLITE_OMIT_DEPRECATED
+#define sqlite3_aggregate_count sqlite3_api->aggregate_count
+#endif
+#define sqlite3_bind_blob sqlite3_api->bind_blob
+#define sqlite3_bind_double sqlite3_api->bind_double
+#define sqlite3_bind_int sqlite3_api->bind_int
+#define sqlite3_bind_int64 sqlite3_api->bind_int64
+#define sqlite3_bind_null sqlite3_api->bind_null
+#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
+#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
+#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
+#define sqlite3_bind_text sqlite3_api->bind_text
+#define sqlite3_bind_text16 sqlite3_api->bind_text16
+#define sqlite3_bind_value sqlite3_api->bind_value
+#define sqlite3_busy_handler sqlite3_api->busy_handler
+#define sqlite3_busy_timeout sqlite3_api->busy_timeout
+#define sqlite3_changes sqlite3_api->changes
+#define sqlite3_close sqlite3_api->close
+#define sqlite3_collation_needed sqlite3_api->collation_needed
+#define sqlite3_collation_needed16 sqlite3_api->collation_needed16
+#define sqlite3_column_blob sqlite3_api->column_blob
+#define sqlite3_column_bytes sqlite3_api->column_bytes
+#define sqlite3_column_bytes16 sqlite3_api->column_bytes16
+#define sqlite3_column_count sqlite3_api->column_count
+#define sqlite3_column_database_name sqlite3_api->column_database_name
+#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
+#define sqlite3_column_decltype sqlite3_api->column_decltype
+#define sqlite3_column_decltype16 sqlite3_api->column_decltype16
+#define sqlite3_column_double sqlite3_api->column_double
+#define sqlite3_column_int sqlite3_api->column_int
+#define sqlite3_column_int64 sqlite3_api->column_int64
+#define sqlite3_column_name sqlite3_api->column_name
+#define sqlite3_column_name16 sqlite3_api->column_name16
+#define sqlite3_column_origin_name sqlite3_api->column_origin_name
+#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
+#define sqlite3_column_table_name sqlite3_api->column_table_name
+#define sqlite3_column_table_name16 sqlite3_api->column_table_name16
+#define sqlite3_column_text sqlite3_api->column_text
+#define sqlite3_column_text16 sqlite3_api->column_text16
+#define sqlite3_column_type sqlite3_api->column_type
+#define sqlite3_column_value sqlite3_api->column_value
+#define sqlite3_commit_hook sqlite3_api->commit_hook
+#define sqlite3_complete sqlite3_api->complete
+#define sqlite3_complete16 sqlite3_api->complete16
+#define sqlite3_create_collation sqlite3_api->create_collation
+#define sqlite3_create_collation16 sqlite3_api->create_collation16
+#define sqlite3_create_function sqlite3_api->create_function
+#define sqlite3_create_function16 sqlite3_api->create_function16
+#define sqlite3_create_module sqlite3_api->create_module
+#define sqlite3_create_module_v2 sqlite3_api->create_module_v2
+#define sqlite3_data_count sqlite3_api->data_count
+#define sqlite3_db_handle sqlite3_api->db_handle
+#define sqlite3_declare_vtab sqlite3_api->declare_vtab
+#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
+#define sqlite3_errcode sqlite3_api->errcode
+#define sqlite3_errmsg sqlite3_api->errmsg
+#define sqlite3_errmsg16 sqlite3_api->errmsg16
+#define sqlite3_exec sqlite3_api->exec
+#ifndef SQLITE_OMIT_DEPRECATED
+#define sqlite3_expired sqlite3_api->expired
+#endif
+#define sqlite3_finalize sqlite3_api->finalize
+#define sqlite3_free sqlite3_api->free
+#define sqlite3_free_table sqlite3_api->free_table
+#define sqlite3_get_autocommit sqlite3_api->get_autocommit
+#define sqlite3_get_auxdata sqlite3_api->get_auxdata
+#define sqlite3_get_table sqlite3_api->get_table
+#ifndef SQLITE_OMIT_DEPRECATED
+#define sqlite3_global_recover sqlite3_api->global_recover
+#endif
+#define sqlite3_interrupt sqlite3_api->interruptx
+#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
+#define sqlite3_libversion sqlite3_api->libversion
+#define sqlite3_libversion_number sqlite3_api->libversion_number
+#define sqlite3_malloc sqlite3_api->malloc
+#define sqlite3_mprintf sqlite3_api->mprintf
+#define sqlite3_open sqlite3_api->open
+#define sqlite3_open16 sqlite3_api->open16
+#define sqlite3_prepare sqlite3_api->prepare
+#define sqlite3_prepare16 sqlite3_api->prepare16
+#define sqlite3_prepare_v2 sqlite3_api->prepare_v2
+#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
+#define sqlite3_profile sqlite3_api->profile
+#define sqlite3_progress_handler sqlite3_api->progress_handler
+#define sqlite3_realloc sqlite3_api->realloc
+#define sqlite3_reset sqlite3_api->reset
+#define sqlite3_result_blob sqlite3_api->result_blob
+#define sqlite3_result_double sqlite3_api->result_double
+#define sqlite3_result_error sqlite3_api->result_error
+#define sqlite3_result_error16 sqlite3_api->result_error16
+#define sqlite3_result_int sqlite3_api->result_int
+#define sqlite3_result_int64 sqlite3_api->result_int64
+#define sqlite3_result_null sqlite3_api->result_null
+#define sqlite3_result_text sqlite3_api->result_text
+#define sqlite3_result_text16 sqlite3_api->result_text16
+#define sqlite3_result_text16be sqlite3_api->result_text16be
+#define sqlite3_result_text16le sqlite3_api->result_text16le
+#define sqlite3_result_value sqlite3_api->result_value
+#define sqlite3_rollback_hook sqlite3_api->rollback_hook
+#define sqlite3_set_authorizer sqlite3_api->set_authorizer
+#define sqlite3_set_auxdata sqlite3_api->set_auxdata
+#define sqlite3_snprintf sqlite3_api->xsnprintf
+#define sqlite3_step sqlite3_api->step
+#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
+#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
+#define sqlite3_total_changes sqlite3_api->total_changes
+#define sqlite3_trace sqlite3_api->trace
+#ifndef SQLITE_OMIT_DEPRECATED
+#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
+#endif
+#define sqlite3_update_hook sqlite3_api->update_hook
+#define sqlite3_user_data sqlite3_api->user_data
+#define sqlite3_value_blob sqlite3_api->value_blob
+#define sqlite3_value_bytes sqlite3_api->value_bytes
+#define sqlite3_value_bytes16 sqlite3_api->value_bytes16
+#define sqlite3_value_double sqlite3_api->value_double
+#define sqlite3_value_int sqlite3_api->value_int
+#define sqlite3_value_int64 sqlite3_api->value_int64
+#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
+#define sqlite3_value_text sqlite3_api->value_text
+#define sqlite3_value_text16 sqlite3_api->value_text16
+#define sqlite3_value_text16be sqlite3_api->value_text16be
+#define sqlite3_value_text16le sqlite3_api->value_text16le
+#define sqlite3_value_type sqlite3_api->value_type
+#define sqlite3_vmprintf sqlite3_api->vmprintf
+#define sqlite3_vsnprintf sqlite3_api->xvsnprintf
+#define sqlite3_overload_function sqlite3_api->overload_function
+#define sqlite3_prepare_v2 sqlite3_api->prepare_v2
+#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
+#define sqlite3_clear_bindings sqlite3_api->clear_bindings
+#define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
+#define sqlite3_blob_bytes sqlite3_api->blob_bytes
+#define sqlite3_blob_close sqlite3_api->blob_close
+#define sqlite3_blob_open sqlite3_api->blob_open
+#define sqlite3_blob_read sqlite3_api->blob_read
+#define sqlite3_blob_write sqlite3_api->blob_write
+#define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
+#define sqlite3_file_control sqlite3_api->file_control
+#define sqlite3_memory_highwater sqlite3_api->memory_highwater
+#define sqlite3_memory_used sqlite3_api->memory_used
+#define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
+#define sqlite3_mutex_enter sqlite3_api->mutex_enter
+#define sqlite3_mutex_free sqlite3_api->mutex_free
+#define sqlite3_mutex_leave sqlite3_api->mutex_leave
+#define sqlite3_mutex_try sqlite3_api->mutex_try
+#define sqlite3_open_v2 sqlite3_api->open_v2
+#define sqlite3_release_memory sqlite3_api->release_memory
+#define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
+#define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
+#define sqlite3_sleep sqlite3_api->sleep
+#define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
+#define sqlite3_vfs_find sqlite3_api->vfs_find
+#define sqlite3_vfs_register sqlite3_api->vfs_register
+#define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
+#define sqlite3_threadsafe sqlite3_api->xthreadsafe
+#define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
+#define sqlite3_result_error_code sqlite3_api->result_error_code
+#define sqlite3_test_control sqlite3_api->test_control
+#define sqlite3_randomness sqlite3_api->randomness
+#define sqlite3_context_db_handle sqlite3_api->context_db_handle
+#define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
+#define sqlite3_limit sqlite3_api->limit
+#define sqlite3_next_stmt sqlite3_api->next_stmt
+#define sqlite3_sql sqlite3_api->sql
+#define sqlite3_status sqlite3_api->status
+#define sqlite3_backup_finish sqlite3_api->backup_finish
+#define sqlite3_backup_init sqlite3_api->backup_init
+#define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
+#define sqlite3_backup_remaining sqlite3_api->backup_remaining
+#define sqlite3_backup_step sqlite3_api->backup_step
+#define sqlite3_compileoption_get sqlite3_api->compileoption_get
+#define sqlite3_compileoption_used sqlite3_api->compileoption_used
+#define sqlite3_create_function_v2 sqlite3_api->create_function_v2
+#define sqlite3_db_config sqlite3_api->db_config
+#define sqlite3_db_mutex sqlite3_api->db_mutex
+#define sqlite3_db_status sqlite3_api->db_status
+#define sqlite3_extended_errcode sqlite3_api->extended_errcode
+#define sqlite3_log sqlite3_api->log
+#define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
+#define sqlite3_sourceid sqlite3_api->sourceid
+#define sqlite3_stmt_status sqlite3_api->stmt_status
+#define sqlite3_strnicmp sqlite3_api->strnicmp
+#define sqlite3_unlock_notify sqlite3_api->unlock_notify
+#define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
+#define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
+#define sqlite3_wal_hook sqlite3_api->wal_hook
+#define sqlite3_blob_reopen sqlite3_api->blob_reopen
+#define sqlite3_vtab_config sqlite3_api->vtab_config
+#define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
+/* Version 3.7.16 and later */
+#define sqlite3_close_v2 sqlite3_api->close_v2
+#define sqlite3_db_filename sqlite3_api->db_filename
+#define sqlite3_db_readonly sqlite3_api->db_readonly
+#define sqlite3_db_release_memory sqlite3_api->db_release_memory
+#define sqlite3_errstr sqlite3_api->errstr
+#define sqlite3_stmt_busy sqlite3_api->stmt_busy
+#define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
+#define sqlite3_stricmp sqlite3_api->stricmp
+#define sqlite3_uri_boolean sqlite3_api->uri_boolean
+#define sqlite3_uri_int64 sqlite3_api->uri_int64
+#define sqlite3_uri_parameter sqlite3_api->uri_parameter
+#define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf
+#define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
+/* Version 3.8.7 and later */
+#define sqlite3_auto_extension sqlite3_api->auto_extension
+#define sqlite3_bind_blob64 sqlite3_api->bind_blob64
+#define sqlite3_bind_text64 sqlite3_api->bind_text64
+#define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
+#define sqlite3_load_extension sqlite3_api->load_extension
+#define sqlite3_malloc64 sqlite3_api->malloc64
+#define sqlite3_msize sqlite3_api->msize
+#define sqlite3_realloc64 sqlite3_api->realloc64
+#define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
+#define sqlite3_result_blob64 sqlite3_api->result_blob64
+#define sqlite3_result_text64 sqlite3_api->result_text64
+#define sqlite3_strglob sqlite3_api->strglob
+/* Version 3.8.11 and later */
+#define sqlite3_value_dup sqlite3_api->value_dup
+#define sqlite3_value_free sqlite3_api->value_free
+#define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
+#define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
+/* Version 3.9.0 and later */
+#define sqlite3_value_subtype sqlite3_api->value_subtype
+#define sqlite3_result_subtype sqlite3_api->result_subtype
+/* Version 3.10.0 and later */
+#define sqlite3_status64 sqlite3_api->status64
+#define sqlite3_strlike sqlite3_api->strlike
+#define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
+/* Version 3.12.0 and later */
+#define sqlite3_system_errno sqlite3_api->system_errno
+/* Version 3.14.0 and later */
+#define sqlite3_trace_v2 sqlite3_api->trace_v2
+#define sqlite3_expanded_sql sqlite3_api->expanded_sql
+/* Version 3.18.0 and later */
+#define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
+/* Version 3.20.0 and later */
+#define sqlite3_prepare_v3 sqlite3_api->prepare_v3
+#define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3
+#define sqlite3_bind_pointer sqlite3_api->bind_pointer
+#define sqlite3_result_pointer sqlite3_api->result_pointer
+#define sqlite3_value_pointer sqlite3_api->value_pointer
+/* Version 3.22.0 and later */
+#define sqlite3_vtab_nochange sqlite3_api->vtab_nochange
+#define sqlite3_value_nochange sqlite3_api->value_nochange
+#define sqlite3_vtab_collation sqlite3_api->vtab_collation
+/* Version 3.24.0 and later */
+#define sqlite3_keyword_count sqlite3_api->keyword_count
+#define sqlite3_keyword_name sqlite3_api->keyword_name
+#define sqlite3_keyword_check sqlite3_api->keyword_check
+#define sqlite3_str_new sqlite3_api->str_new
+#define sqlite3_str_finish sqlite3_api->str_finish
+#define sqlite3_str_appendf sqlite3_api->str_appendf
+#define sqlite3_str_vappendf sqlite3_api->str_vappendf
+#define sqlite3_str_append sqlite3_api->str_append
+#define sqlite3_str_appendall sqlite3_api->str_appendall
+#define sqlite3_str_appendchar sqlite3_api->str_appendchar
+#define sqlite3_str_reset sqlite3_api->str_reset
+#define sqlite3_str_errcode sqlite3_api->str_errcode
+#define sqlite3_str_length sqlite3_api->str_length
+#define sqlite3_str_value sqlite3_api->str_value
+/* Version 3.25.0 and later */
+#define sqlite3_create_window_function sqlite3_api->create_window_function
+/* Version 3.26.0 and later */
+#define sqlite3_normalized_sql sqlite3_api->normalized_sql
+/* Version 3.28.0 and later */
+#define sqlite3_stmt_isexplain sqlite3_api->stmt_isexplain
+#define sqlite3_value_frombind sqlite3_api->value_frombind
+/* Version 3.30.0 and later */
+#define sqlite3_drop_modules sqlite3_api->drop_modules
+/* Version 3.31.0 and later */
+#define sqlite3_hard_heap_limit64 sqlite3_api->hard_heap_limit64
+#define sqlite3_uri_key sqlite3_api->uri_key
+#define sqlite3_filename_database sqlite3_api->filename_database
+#define sqlite3_filename_journal sqlite3_api->filename_journal
+#define sqlite3_filename_wal sqlite3_api->filename_wal
+/* Version 3.32.0 and later */
+#define sqlite3_create_filename sqlite3_api->create_filename
+#define sqlite3_free_filename sqlite3_api->free_filename
+#define sqlite3_database_file_object sqlite3_api->database_file_object
+#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
+
+#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
+ /* This case when the file really is being compiled as a loadable
+ ** extension */
+# define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
+# define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
+# define SQLITE_EXTENSION_INIT3 \
+ extern const sqlite3_api_routines *sqlite3_api;
+#else
+ /* This case when the file is being statically linked into the
+ ** application */
+# define SQLITE_EXTENSION_INIT1 /*no-op*/
+# define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
+# define SQLITE_EXTENSION_INIT3 /*no-op*/
+#endif
+
+#endif /* SQLITE3EXT_H */
diff --git a/third_party/heimdal/lib/vers/ChangeLog b/third_party/heimdal/lib/vers/ChangeLog
new file mode 100644
index 0000000..524728b
--- /dev/null
+++ b/third_party/heimdal/lib/vers/ChangeLog
@@ -0,0 +1,74 @@
+2007-10-16 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: don't run local checks.
+
+2006-12-29 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * print_version.c: Update (c).
+
+2006-10-21 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * make-print-version.c: include <string.h>
+
+2006-10-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * make-print-version.c: Avoid creating a file called --version.
+
+2006-10-19 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: fix spelling of build_HEADERZ
+
+2006-10-07 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add build_HEADERZ to EXTRA_DIST
+
+2005-01-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * print_version.c: Happy New Year
+
+2004-01-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * print_version.c: add year 2004
+
+2003-01-02 Johan Danielsson <joda@pdc.kth.se>
+
+ * print_version.c: considerable clean up
+
+ * make-print-version.c: make VERSIONLIST a string instead of an
+ array of strings
+
+2002-08-28 Assar Westerlund <assar@kth.se>
+
+ * Makefile.am (make_print_version_LDADD): do not hardcode -ldes,
+ use $(LIB_des)
+
+2002-08-19 Johan Danielsson <joda@pdc.kth.se>
+
+ * print_version.c: add bug-report message
+
+2002-05-20 Johan Danielsson <joda@pdc.kth.se>
+
+ * print_version.c: update year
+
+2001-08-24 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am (make_print_version_LDADD): use = instead of += (be
+ nice to current automake)
+
+2001-04-21 Johan Danielsson <joda@pdc.kth.se>
+
+ * print_version.c: 2001
+
+2001-01-31 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: remove -static turning this into a convenience
+ library
+
+2000-11-15 Assar Westerlund <assar@sics.se>
+
+ * Makefile.am: make the library static and don't install it
+
+2000-07-08 Assar Westerlund <assar@sics.se>
+
+ * make-print-version.c (heimdal_version, krb4_version): const-ize,
+ based on thorpej@netbsd.org's change to NetBSD
diff --git a/third_party/heimdal/lib/vers/Makefile.am b/third_party/heimdal/lib/vers/Makefile.am
new file mode 100644
index 0000000..b366227
--- /dev/null
+++ b/third_party/heimdal/lib/vers/Makefile.am
@@ -0,0 +1,13 @@
+# $Id$
+
+include $(top_srcdir)/Makefile.am.common
+
+noinst_LTLIBRARIES = libvers.la
+
+build_HEADERZ = vers.h
+
+CHECK_LOCAL = no-check-local
+
+libvers_la_SOURCES = print_version.c
+
+EXTRA_DIST = NTMakefile $(build_HEADERZ) make-print-version.c
diff --git a/third_party/heimdal/lib/vers/NTMakefile b/third_party/heimdal/lib/vers/NTMakefile
new file mode 100644
index 0000000..2ae27f7
--- /dev/null
+++ b/third_party/heimdal/lib/vers/NTMakefile
@@ -0,0 +1,56 @@
+########################################################################
+#
+# Copyright (c) 2009, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR = lib\vers
+
+!include ../../windows/NTMakefile.w32
+
+INCFILES=$(INCDIR)\vers.h
+
+$(LIBVERS): $(OBJ)\print_version.obj
+ $(LIBCON)
+
+$(OBJ)\print_version.obj: print_version.c
+ $(C2OBJ) -I$(OBJ)
+
+$(OBJ)\make-print-version.exe: $(OBJ)\make-print-version.obj
+ $(EXECONLINK)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\print_version.h: $(OBJ)\make-print-version.exe
+ $(OBJ)\make-print-version.exe $@
+
+all:: $(INCFILES) $(OBJ)\print_version.h $(LIBVERS)
+
+clean::
+ -$(RM) $(OBJ)\print_version.h $(LIBVERS)
+ -$(RM) $(OBJ)\make-print-version.exe
+ -$(RM) $(OBJ)\make-print-version.obj
diff --git a/third_party/heimdal/lib/vers/make-print-version.c b/third_party/heimdal/lib/vers/make-print-version.c
new file mode 100644
index 0000000..f0a61f6
--- /dev/null
+++ b/third_party/heimdal/lib/vers/make-print-version.c
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 1998 - 2003 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdio.h>
+#include <string.h>
+
+#ifdef KRB5
+extern const char *heimdal_version;
+#endif
+#include <version.h>
+
+int
+main(int argc, char **argv)
+{
+ FILE *f;
+ if(argc != 2)
+ return 1;
+ if (strcmp(argv[1], "--version") == 0) {
+ printf("some version");
+ return 0;
+ }
+ f = fopen(argv[1], "w");
+ if(f == NULL)
+ return 1;
+ fprintf(f, "#define VERSIONLIST \"");
+#ifdef KRB5
+ fprintf(f, "%s", heimdal_version);
+#endif
+ fprintf(f, "\"\n");
+ fclose(f);
+ return 0;
+}
diff --git a/third_party/heimdal/lib/vers/print_version.c b/third_party/heimdal/lib/vers/print_version.c
new file mode 100644
index 0000000..c62fe9e
--- /dev/null
+++ b/third_party/heimdal/lib/vers/print_version.c
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 1998 - 2006 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+
+#include <config.h>
+#include <krb5-types.h>
+
+#define VERSION_HIDDEN static HEIMDAL_UNUSED_ATTRIBUTE
+
+#include "roken.h"
+
+#include "version.h"
+
+void ROKEN_LIB_FUNCTION
+print_version(const char *progname)
+{
+ const char *package_list = heimdal_version;
+
+ if(progname == NULL)
+ progname = getprogname();
+
+ if(*package_list == '\0')
+ package_list = "no version information";
+ fprintf(stderr, "%s (%s)\n", progname, package_list);
+ fprintf(stderr, "Copyright 1995-2014 Kungliga Tekniska Högskolan\n");
+#ifdef PACKAGE_BUGREPORT
+ fprintf(stderr, "Send bug-reports to %s\n", PACKAGE_BUGREPORT);
+#endif
+}
diff --git a/third_party/heimdal/lib/vers/vers.h b/third_party/heimdal/lib/vers/vers.h
new file mode 100644
index 0000000..5bd23a0
--- /dev/null
+++ b/third_party/heimdal/lib/vers/vers.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 1995 - 2000 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef __VERS_H__
+#define __VERS_H__
+
+void print_version(const char *);
+
+#endif /* __VERS_H__ */
diff --git a/third_party/heimdal/lib/wind/ChangeLog b/third_party/heimdal/lib/wind/ChangeLog
new file mode 100644
index 0000000..0d8119d
--- /dev/null
+++ b/third_party/heimdal/lib/wind/ChangeLog
@@ -0,0 +1,136 @@
+2008-07-15 Love Hörnquist Åstrand <lha@kth.se>
+
+ * Makefile.am: Try to do depencies better.
+
+2008-07-15 Love Hörnquist Åstrand <lha@kth.se>
+
+ * Makefile.am: add punycode_examples.[ch] to built files.
+
+2008-06-01 Love Hörnquist Åstrand <lha@kth.se>
+
+ * Add utf8 <-> utf16 support.
+
+2008-05-31 Love Hörnquist Åstrand <lha@kth.se>
+
+ * generate files into the source tree
+
+2008-05-31 Love Hörnquist Åstrand <lha@kth.se>
+
+ * Support utf8 to utf16 conversion.
+
+2008-05-30 Love Hörnquist Åstrand <lha@kth.se>
+
+ * idn-lookup.c: Drop <stdint.h>
+
+ * wind.h: Use <krb5-types.h>
+
+2008-05-23 Love Hörnquist Åstrand <lha@kth.se>
+
+ * windlocl.h: Include <krb5-types.h> to get fixed int types.
+
+2008-04-20 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * stringprep.c: Use <string.h> instead of <strings.h>.
+
+2008-04-14 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * wind.h: Make wind_stringprep match prototype in .c file. pointed
+ out by David Rosenstrauch.
+
+2008-04-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test-normalize.c: include roken.h
+
+2008-02-26 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Add more built files so they are distributed.
+
+2008-02-24 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add LIB_com_err.
+
+2008-02-23 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Makefile.am: Add more built files.
+
+ * Makefile.am: Add unicode header files.
+
+ * punycode.c: make pass the test cases again.
+
+ * Makefile.am: add more missing .py files.
+
+ * Makefile.am: add generate.py
+
+ * test-ldap.c: Test ldap cases.
+
+ * Makefile.am: Drop com_err files from dist sources.
+
+ * ldap.c (_wind_ldap_case_exact_attribute): case exact matching.
+
+2008-02-12 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * rename wind_punycode_toascii to wind_punycode_label_toascii
+
+ * stringprep.c: Move else to make it work again.
+
+2008-02-11 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Add partial support for LDAP-prep Insignificant Character Handling
+
+ * normalize.c: use generated constant for length, check for
+ overruns, dont use gcc/c99 extentions
+
+ * gen-normalize.py, test-normalize.c: use generated constant for length
+
+2008-02-05 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * utf8.c: Make wind_utf8ucs4_length() work again.
+
+ * test-utf8.c: Test wind_utf8ucs4_length().
+
+2008-02-03 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * utf8.c: Fix overaggressive checks, fix comments.
+
+ * Add UCS-2 reading and writing functions
+
+2008-02-01 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * Add and use com_err error codes
+
+ * libwind from Assar. stringprep library supporting nameprep,
+ saslprep and ldapprep. Added libwind to Heimdal repository.
+
+2007-01-17 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test-utf8.c: spelling
+
+ * utf8.c: Add wind_ucs4toutf8
+
+2006-10-08 Love Hörnquist Åstrand <lha@it.su.se>
+
+ * test-utf8.c: Add test for wind_ucs4toutf8.
+
+ * wind.h (wind_ucs4toutf8): New function.
+
+ * utf8.c (wind_utf8toucs4): allow calculation of length by passing
+ in NULL as out buffer.
+ (wind_ucs4toutf8): new function.
+
+2004-12-20 Assar Westerlund <assar@kth.se>
+
+ * util.py:
+ * rfc3454.py:
+ * generate.py:
+ * gen-punycode-examples.py:
+ * gen-normalize.py:
+ * gen-map.py:
+ * gen-errorlist.py:
+ * gen-combining.py:
+ * gen-bidi.py:
+ * UnicodeData.py:
+ Add encoding.
+
+2004-12-20 Assar Westerlund <assar@kth.se>
+
+ * First version of stringprep library.
diff --git a/third_party/heimdal/lib/wind/CompositionExclusions-3.2.0.txt b/third_party/heimdal/lib/wind/CompositionExclusions-3.2.0.txt
new file mode 100644
index 0000000..07a60b8
--- /dev/null
+++ b/third_party/heimdal/lib/wind/CompositionExclusions-3.2.0.txt
@@ -0,0 +1,176 @@
+# CompositionExclusions-3.2.0.txt
+# Date: 2002-03-19,23:30:28 GMT [MD]
+#
+# This file lists the characters from the UAX #15 Composition Exclusion Table.
+#
+# The format of the comments in this file has been updated since the last version,
+# CompositionExclusions-3.txt. The only substantive change to this file between that
+# version and this one is the addition of U+2ADC FORKING.
+#
+# For more information, see
+# http://www.unicode.org/unicode/reports/tr15/#Primary Exclusion List Table
+# ================================================
+
+# (1) Script Specifics
+# This list of characters cannot be derived from the UnicodeData file.
+# ================================================
+
+0958 # DEVANAGARI LETTER QA
+0959 # DEVANAGARI LETTER KHHA
+095A # DEVANAGARI LETTER GHHA
+095B # DEVANAGARI LETTER ZA
+095C # DEVANAGARI LETTER DDDHA
+095D # DEVANAGARI LETTER RHA
+095E # DEVANAGARI LETTER FA
+095F # DEVANAGARI LETTER YYA
+09DC # BENGALI LETTER RRA
+09DD # BENGALI LETTER RHA
+09DF # BENGALI LETTER YYA
+0A33 # GURMUKHI LETTER LLA
+0A36 # GURMUKHI LETTER SHA
+0A59 # GURMUKHI LETTER KHHA
+0A5A # GURMUKHI LETTER GHHA
+0A5B # GURMUKHI LETTER ZA
+0A5E # GURMUKHI LETTER FA
+0B5C # ORIYA LETTER RRA
+0B5D # ORIYA LETTER RHA
+0F43 # TIBETAN LETTER GHA
+0F4D # TIBETAN LETTER DDHA
+0F52 # TIBETAN LETTER DHA
+0F57 # TIBETAN LETTER BHA
+0F5C # TIBETAN LETTER DZHA
+0F69 # TIBETAN LETTER KSSA
+0F76 # TIBETAN VOWEL SIGN VOCALIC R
+0F78 # TIBETAN VOWEL SIGN VOCALIC L
+0F93 # TIBETAN SUBJOINED LETTER GHA
+0F9D # TIBETAN SUBJOINED LETTER DDHA
+0FA2 # TIBETAN SUBJOINED LETTER DHA
+0FA7 # TIBETAN SUBJOINED LETTER BHA
+0FAC # TIBETAN SUBJOINED LETTER DZHA
+0FB9 # TIBETAN SUBJOINED LETTER KSSA
+FB1D # HEBREW LETTER YOD WITH HIRIQ
+FB1F # HEBREW LIGATURE YIDDISH YOD YOD PATAH
+FB2A # HEBREW LETTER SHIN WITH SHIN DOT
+FB2B # HEBREW LETTER SHIN WITH SIN DOT
+FB2C # HEBREW LETTER SHIN WITH DAGESH AND SHIN DOT
+FB2D # HEBREW LETTER SHIN WITH DAGESH AND SIN DOT
+FB2E # HEBREW LETTER ALEF WITH PATAH
+FB2F # HEBREW LETTER ALEF WITH QAMATS
+FB30 # HEBREW LETTER ALEF WITH MAPIQ
+FB31 # HEBREW LETTER BET WITH DAGESH
+FB32 # HEBREW LETTER GIMEL WITH DAGESH
+FB33 # HEBREW LETTER DALET WITH DAGESH
+FB34 # HEBREW LETTER HE WITH MAPIQ
+FB35 # HEBREW LETTER VAV WITH DAGESH
+FB36 # HEBREW LETTER ZAYIN WITH DAGESH
+FB38 # HEBREW LETTER TET WITH DAGESH
+FB39 # HEBREW LETTER YOD WITH DAGESH
+FB3A # HEBREW LETTER FINAL KAF WITH DAGESH
+FB3B # HEBREW LETTER KAF WITH DAGESH
+FB3C # HEBREW LETTER LAMED WITH DAGESH
+FB3E # HEBREW LETTER MEM WITH DAGESH
+FB40 # HEBREW LETTER NUN WITH DAGESH
+FB41 # HEBREW LETTER SAMEKH WITH DAGESH
+FB43 # HEBREW LETTER FINAL PE WITH DAGESH
+FB44 # HEBREW LETTER PE WITH DAGESH
+FB46 # HEBREW LETTER TSADI WITH DAGESH
+FB47 # HEBREW LETTER QOF WITH DAGESH
+FB48 # HEBREW LETTER RESH WITH DAGESH
+FB49 # HEBREW LETTER SHIN WITH DAGESH
+FB4A # HEBREW LETTER TAV WITH DAGESH
+FB4B # HEBREW LETTER VAV WITH HOLAM
+FB4C # HEBREW LETTER BET WITH RAFE
+FB4D # HEBREW LETTER KAF WITH RAFE
+FB4E # HEBREW LETTER PE WITH RAFE
+
+# Total code points: 67
+
+# ================================================
+# (2) Post Composition Version precomposed characters
+# These characters cannot be derived solely from the UnicodeData.txt file
+# in this version of Unicode.
+# ================================================
+
+2ADC # FORKING
+1D15E # MUSICAL SYMBOL HALF NOTE
+1D15F # MUSICAL SYMBOL QUARTER NOTE
+1D160 # MUSICAL SYMBOL EIGHTH NOTE
+1D161 # MUSICAL SYMBOL SIXTEENTH NOTE
+1D162 # MUSICAL SYMBOL THIRTY-SECOND NOTE
+1D163 # MUSICAL SYMBOL SIXTY-FOURTH NOTE
+1D164 # MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH NOTE
+1D1BB # MUSICAL SYMBOL MINIMA
+1D1BC # MUSICAL SYMBOL MINIMA BLACK
+1D1BD # MUSICAL SYMBOL SEMIMINIMA WHITE
+1D1BE # MUSICAL SYMBOL SEMIMINIMA BLACK
+1D1BF # MUSICAL SYMBOL FUSA WHITE
+1D1C0 # MUSICAL SYMBOL FUSA BLACK
+
+# Total code points: 14
+
+# ================================================
+# (3) Singleton Decompositions
+# These characters can be derived from the UnicodeData file
+# by including all characters whose canonical decomposition
+# consists of a single character.
+# These characters are simply quoted here for reference.
+# ================================================
+
+# 0340..0341 [2] COMBINING GRAVE TONE MARK..COMBINING ACUTE TONE MARK
+# 0343 COMBINING GREEK KORONIS
+# 0374 GREEK NUMERAL SIGN
+# 037E GREEK QUESTION MARK
+# 0387 GREEK ANO TELEIA
+# 1F71 GREEK SMALL LETTER ALPHA WITH OXIA
+# 1F73 GREEK SMALL LETTER EPSILON WITH OXIA
+# 1F75 GREEK SMALL LETTER ETA WITH OXIA
+# 1F77 GREEK SMALL LETTER IOTA WITH OXIA
+# 1F79 GREEK SMALL LETTER OMICRON WITH OXIA
+# 1F7B GREEK SMALL LETTER UPSILON WITH OXIA
+# 1F7D GREEK SMALL LETTER OMEGA WITH OXIA
+# 1FBB GREEK CAPITAL LETTER ALPHA WITH OXIA
+# 1FBE GREEK PROSGEGRAMMENI
+# 1FC9 GREEK CAPITAL LETTER EPSILON WITH OXIA
+# 1FCB GREEK CAPITAL LETTER ETA WITH OXIA
+# 1FD3 GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA
+# 1FDB GREEK CAPITAL LETTER IOTA WITH OXIA
+# 1FE3 GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA
+# 1FEB GREEK CAPITAL LETTER UPSILON WITH OXIA
+# 1FEE..1FEF [2] GREEK DIALYTIKA AND OXIA..GREEK VARIA
+# 1FF9 GREEK CAPITAL LETTER OMICRON WITH OXIA
+# 1FFB GREEK CAPITAL LETTER OMEGA WITH OXIA
+# 1FFD GREEK OXIA
+# 2000..2001 [2] EN QUAD..EM QUAD
+# 2126 OHM SIGN
+# 212A..212B [2] KELVIN SIGN..ANGSTROM SIGN
+# 2329 LEFT-POINTING ANGLE BRACKET
+# 232A RIGHT-POINTING ANGLE BRACKET
+# F900..FA0D [270] CJK COMPATIBILITY IDEOGRAPH-F900..CJK COMPATIBILITY IDEOGRAPH-FA0D
+# FA10 CJK COMPATIBILITY IDEOGRAPH-FA10
+# FA12 CJK COMPATIBILITY IDEOGRAPH-FA12
+# FA15..FA1E [10] CJK COMPATIBILITY IDEOGRAPH-FA15..CJK COMPATIBILITY IDEOGRAPH-FA1E
+# FA20 CJK COMPATIBILITY IDEOGRAPH-FA20
+# FA22 CJK COMPATIBILITY IDEOGRAPH-FA22
+# FA25..FA26 [2] CJK COMPATIBILITY IDEOGRAPH-FA25..CJK COMPATIBILITY IDEOGRAPH-FA26
+# FA2A..FA2D [4] CJK COMPATIBILITY IDEOGRAPH-FA2A..CJK COMPATIBILITY IDEOGRAPH-FA2D
+# FA30..FA6A [59] CJK COMPATIBILITY IDEOGRAPH-FA30..CJK COMPATIBILITY IDEOGRAPH-FA6A
+# 2F800..2FA1D [542] CJK COMPATIBILITY IDEOGRAPH-2F800..CJK COMPATIBILITY IDEOGRAPH-2FA1D
+
+# Total code points: 924
+
+# ================================================
+# (4) Non-Starter Decompositions
+# These characters can be derived from the UnicodeData file
+# by including all characters whose canonical decomposition consists
+# of a sequence of characters, the first of which has a non-zero
+# combining class.
+# These characters are simply quoted here for reference.
+# ================================================
+
+# 0344 COMBINING GREEK DIALYTIKA TONOS
+# 0F73 TIBETAN VOWEL SIGN II
+# 0F75 TIBETAN VOWEL SIGN UU
+# 0F81 TIBETAN VOWEL SIGN REVERSED II
+
+# Total code points: 4
+
diff --git a/third_party/heimdal/lib/wind/DerivedNormalizationProps.txt b/third_party/heimdal/lib/wind/DerivedNormalizationProps.txt
new file mode 100644
index 0000000..2d4f0a6
--- /dev/null
+++ b/third_party/heimdal/lib/wind/DerivedNormalizationProps.txt
@@ -0,0 +1,2574 @@
+# DerivedNormalizationProps-4.0.1.txt
+# Date: 2004-03-02, 02:42:17 GMT [MD]
+#
+# Unicode Character Database
+# Copyright (c) 1991-2004 Unicode, Inc.
+# For terms of use, see http://www.unicode.org/terms_of_use.html
+# For documentation, see UCD.html
+
+# ================================================
+
+# Derived Property: FC_NFKC_Closure
+# Generated from computing: b = NFKC(Fold(a)); c = NFKC(Fold(b));
+# Then if (c != b) add the mapping from a to c to the set of
+# mappings that constitute the FC_NFKC_Closure list
+# Uses the full case folding from CaseFolding.txt, without the T option.
+
+037A ; FC_NFKC; 0020 03B9 # Lm GREEK YPOGEGRAMMENI
+03D2 ; FC_NFKC; 03C5 # L& GREEK UPSILON WITH HOOK SYMBOL
+03D3 ; FC_NFKC; 03CD # L& GREEK UPSILON WITH ACUTE AND HOOK SYMBOL
+03D4 ; FC_NFKC; 03CB # L& GREEK UPSILON WITH DIAERESIS AND HOOK SYMBOL
+03F2 ; FC_NFKC; 03C3 # L& GREEK LUNATE SIGMA SYMBOL
+03F9 ; FC_NFKC; 03C3 # L& GREEK CAPITAL LUNATE SIGMA SYMBOL
+1D2C ; FC_NFKC; 0061 # Lm MODIFIER LETTER CAPITAL A
+1D2D ; FC_NFKC; 00E6 # Lm MODIFIER LETTER CAPITAL AE
+1D2E ; FC_NFKC; 0062 # Lm MODIFIER LETTER CAPITAL B
+1D30 ; FC_NFKC; 0064 # Lm MODIFIER LETTER CAPITAL D
+1D31 ; FC_NFKC; 0065 # Lm MODIFIER LETTER CAPITAL E
+1D32 ; FC_NFKC; 01DD # Lm MODIFIER LETTER CAPITAL REVERSED E
+1D33 ; FC_NFKC; 0067 # Lm MODIFIER LETTER CAPITAL G
+1D34 ; FC_NFKC; 0068 # Lm MODIFIER LETTER CAPITAL H
+1D35 ; FC_NFKC; 0069 # Lm MODIFIER LETTER CAPITAL I
+1D36 ; FC_NFKC; 006A # Lm MODIFIER LETTER CAPITAL J
+1D37 ; FC_NFKC; 006B # Lm MODIFIER LETTER CAPITAL K
+1D38 ; FC_NFKC; 006C # Lm MODIFIER LETTER CAPITAL L
+1D39 ; FC_NFKC; 006D # Lm MODIFIER LETTER CAPITAL M
+1D3A ; FC_NFKC; 006E # Lm MODIFIER LETTER CAPITAL N
+1D3C ; FC_NFKC; 006F # Lm MODIFIER LETTER CAPITAL O
+1D3D ; FC_NFKC; 0223 # Lm MODIFIER LETTER CAPITAL OU
+1D3E ; FC_NFKC; 0070 # Lm MODIFIER LETTER CAPITAL P
+1D3F ; FC_NFKC; 0072 # Lm MODIFIER LETTER CAPITAL R
+1D40 ; FC_NFKC; 0074 # Lm MODIFIER LETTER CAPITAL T
+1D41 ; FC_NFKC; 0075 # Lm MODIFIER LETTER CAPITAL U
+1D42 ; FC_NFKC; 0077 # Lm MODIFIER LETTER CAPITAL W
+20A8 ; FC_NFKC; 0072 0073 # Sc RUPEE SIGN
+2102 ; FC_NFKC; 0063 # L& DOUBLE-STRUCK CAPITAL C
+2103 ; FC_NFKC; 00B0 0063 # So DEGREE CELSIUS
+2107 ; FC_NFKC; 025B # L& EULER CONSTANT
+2109 ; FC_NFKC; 00B0 0066 # So DEGREE FAHRENHEIT
+210B ; FC_NFKC; 0068 # L& SCRIPT CAPITAL H
+210C ; FC_NFKC; 0068 # L& BLACK-LETTER CAPITAL H
+210D ; FC_NFKC; 0068 # L& DOUBLE-STRUCK CAPITAL H
+2110 ; FC_NFKC; 0069 # L& SCRIPT CAPITAL I
+2111 ; FC_NFKC; 0069 # L& BLACK-LETTER CAPITAL I
+2112 ; FC_NFKC; 006C # L& SCRIPT CAPITAL L
+2115 ; FC_NFKC; 006E # L& DOUBLE-STRUCK CAPITAL N
+2116 ; FC_NFKC; 006E 006F # So NUMERO SIGN
+2119 ; FC_NFKC; 0070 # L& DOUBLE-STRUCK CAPITAL P
+211A ; FC_NFKC; 0071 # L& DOUBLE-STRUCK CAPITAL Q
+211B ; FC_NFKC; 0072 # L& SCRIPT CAPITAL R
+211C ; FC_NFKC; 0072 # L& BLACK-LETTER CAPITAL R
+211D ; FC_NFKC; 0072 # L& DOUBLE-STRUCK CAPITAL R
+2120 ; FC_NFKC; 0073 006D # So SERVICE MARK
+2121 ; FC_NFKC; 0074 0065 006C # So TELEPHONE SIGN
+2122 ; FC_NFKC; 0074 006D # So TRADE MARK SIGN
+2124 ; FC_NFKC; 007A # L& DOUBLE-STRUCK CAPITAL Z
+2128 ; FC_NFKC; 007A # L& BLACK-LETTER CAPITAL Z
+212C ; FC_NFKC; 0062 # L& SCRIPT CAPITAL B
+212D ; FC_NFKC; 0063 # L& BLACK-LETTER CAPITAL C
+2130 ; FC_NFKC; 0065 # L& SCRIPT CAPITAL E
+2131 ; FC_NFKC; 0066 # L& SCRIPT CAPITAL F
+2133 ; FC_NFKC; 006D # L& SCRIPT CAPITAL M
+213B ; FC_NFKC; 0066 0061 0078 # So FACSIMILE SIGN
+213E ; FC_NFKC; 03B3 # L& DOUBLE-STRUCK CAPITAL GAMMA
+213F ; FC_NFKC; 03C0 # L& DOUBLE-STRUCK CAPITAL PI
+2145 ; FC_NFKC; 0064 # L& DOUBLE-STRUCK ITALIC CAPITAL D
+3250 ; FC_NFKC; 0070 0074 0065 # So PARTNERSHIP SIGN
+32CC ; FC_NFKC; 0068 0067 # So SQUARE HG
+32CE ; FC_NFKC; 0065 0076 # So SQUARE EV
+32CF ; FC_NFKC; 006C 0074 0064 # So LIMITED LIABILITY SIGN
+3371 ; FC_NFKC; 0068 0070 0061 # So SQUARE HPA
+3373 ; FC_NFKC; 0061 0075 # So SQUARE AU
+3375 ; FC_NFKC; 006F 0076 # So SQUARE OV
+337A ; FC_NFKC; 0069 0075 # So SQUARE IU
+3380 ; FC_NFKC; 0070 0061 # So SQUARE PA AMPS
+3381 ; FC_NFKC; 006E 0061 # So SQUARE NA
+3382 ; FC_NFKC; 03BC 0061 # So SQUARE MU A
+3383 ; FC_NFKC; 006D 0061 # So SQUARE MA
+3384 ; FC_NFKC; 006B 0061 # So SQUARE KA
+3385 ; FC_NFKC; 006B 0062 # So SQUARE KB
+3386 ; FC_NFKC; 006D 0062 # So SQUARE MB
+3387 ; FC_NFKC; 0067 0062 # So SQUARE GB
+338A ; FC_NFKC; 0070 0066 # So SQUARE PF
+338B ; FC_NFKC; 006E 0066 # So SQUARE NF
+338C ; FC_NFKC; 03BC 0066 # So SQUARE MU F
+3390 ; FC_NFKC; 0068 007A # So SQUARE HZ
+3391 ; FC_NFKC; 006B 0068 007A # So SQUARE KHZ
+3392 ; FC_NFKC; 006D 0068 007A # So SQUARE MHZ
+3393 ; FC_NFKC; 0067 0068 007A # So SQUARE GHZ
+3394 ; FC_NFKC; 0074 0068 007A # So SQUARE THZ
+33A9 ; FC_NFKC; 0070 0061 # So SQUARE PA
+33AA ; FC_NFKC; 006B 0070 0061 # So SQUARE KPA
+33AB ; FC_NFKC; 006D 0070 0061 # So SQUARE MPA
+33AC ; FC_NFKC; 0067 0070 0061 # So SQUARE GPA
+33B4 ; FC_NFKC; 0070 0076 # So SQUARE PV
+33B5 ; FC_NFKC; 006E 0076 # So SQUARE NV
+33B6 ; FC_NFKC; 03BC 0076 # So SQUARE MU V
+33B7 ; FC_NFKC; 006D 0076 # So SQUARE MV
+33B8 ; FC_NFKC; 006B 0076 # So SQUARE KV
+33B9 ; FC_NFKC; 006D 0076 # So SQUARE MV MEGA
+33BA ; FC_NFKC; 0070 0077 # So SQUARE PW
+33BB ; FC_NFKC; 006E 0077 # So SQUARE NW
+33BC ; FC_NFKC; 03BC 0077 # So SQUARE MU W
+33BD ; FC_NFKC; 006D 0077 # So SQUARE MW
+33BE ; FC_NFKC; 006B 0077 # So SQUARE KW
+33BF ; FC_NFKC; 006D 0077 # So SQUARE MW MEGA
+33C0 ; FC_NFKC; 006B 03C9 # So SQUARE K OHM
+33C1 ; FC_NFKC; 006D 03C9 # So SQUARE M OHM
+33C3 ; FC_NFKC; 0062 0071 # So SQUARE BQ
+33C6 ; FC_NFKC; 0063 2215 006B 0067 # So SQUARE C OVER KG
+33C7 ; FC_NFKC; 0063 006F 002E # So SQUARE CO
+33C8 ; FC_NFKC; 0064 0062 # So SQUARE DB
+33C9 ; FC_NFKC; 0067 0079 # So SQUARE GY
+33CB ; FC_NFKC; 0068 0070 # So SQUARE HP
+33CD ; FC_NFKC; 006B 006B # So SQUARE KK
+33CE ; FC_NFKC; 006B 006D # So SQUARE KM CAPITAL
+33D7 ; FC_NFKC; 0070 0068 # So SQUARE PH
+33D9 ; FC_NFKC; 0070 0070 006D # So SQUARE PPM
+33DA ; FC_NFKC; 0070 0072 # So SQUARE PR
+33DC ; FC_NFKC; 0073 0076 # So SQUARE SV
+33DD ; FC_NFKC; 0077 0062 # So SQUARE WB
+33DE ; FC_NFKC; 0076 2215 006D # So SQUARE V OVER M
+33DF ; FC_NFKC; 0061 2215 006D # So SQUARE A OVER M
+1D400 ; FC_NFKC; 0061 # L& MATHEMATICAL BOLD CAPITAL A
+1D401 ; FC_NFKC; 0062 # L& MATHEMATICAL BOLD CAPITAL B
+1D402 ; FC_NFKC; 0063 # L& MATHEMATICAL BOLD CAPITAL C
+1D403 ; FC_NFKC; 0064 # L& MATHEMATICAL BOLD CAPITAL D
+1D404 ; FC_NFKC; 0065 # L& MATHEMATICAL BOLD CAPITAL E
+1D405 ; FC_NFKC; 0066 # L& MATHEMATICAL BOLD CAPITAL F
+1D406 ; FC_NFKC; 0067 # L& MATHEMATICAL BOLD CAPITAL G
+1D407 ; FC_NFKC; 0068 # L& MATHEMATICAL BOLD CAPITAL H
+1D408 ; FC_NFKC; 0069 # L& MATHEMATICAL BOLD CAPITAL I
+1D409 ; FC_NFKC; 006A # L& MATHEMATICAL BOLD CAPITAL J
+1D40A ; FC_NFKC; 006B # L& MATHEMATICAL BOLD CAPITAL K
+1D40B ; FC_NFKC; 006C # L& MATHEMATICAL BOLD CAPITAL L
+1D40C ; FC_NFKC; 006D # L& MATHEMATICAL BOLD CAPITAL M
+1D40D ; FC_NFKC; 006E # L& MATHEMATICAL BOLD CAPITAL N
+1D40E ; FC_NFKC; 006F # L& MATHEMATICAL BOLD CAPITAL O
+1D40F ; FC_NFKC; 0070 # L& MATHEMATICAL BOLD CAPITAL P
+1D410 ; FC_NFKC; 0071 # L& MATHEMATICAL BOLD CAPITAL Q
+1D411 ; FC_NFKC; 0072 # L& MATHEMATICAL BOLD CAPITAL R
+1D412 ; FC_NFKC; 0073 # L& MATHEMATICAL BOLD CAPITAL S
+1D413 ; FC_NFKC; 0074 # L& MATHEMATICAL BOLD CAPITAL T
+1D414 ; FC_NFKC; 0075 # L& MATHEMATICAL BOLD CAPITAL U
+1D415 ; FC_NFKC; 0076 # L& MATHEMATICAL BOLD CAPITAL V
+1D416 ; FC_NFKC; 0077 # L& MATHEMATICAL BOLD CAPITAL W
+1D417 ; FC_NFKC; 0078 # L& MATHEMATICAL BOLD CAPITAL X
+1D418 ; FC_NFKC; 0079 # L& MATHEMATICAL BOLD CAPITAL Y
+1D419 ; FC_NFKC; 007A # L& MATHEMATICAL BOLD CAPITAL Z
+1D434 ; FC_NFKC; 0061 # L& MATHEMATICAL ITALIC CAPITAL A
+1D435 ; FC_NFKC; 0062 # L& MATHEMATICAL ITALIC CAPITAL B
+1D436 ; FC_NFKC; 0063 # L& MATHEMATICAL ITALIC CAPITAL C
+1D437 ; FC_NFKC; 0064 # L& MATHEMATICAL ITALIC CAPITAL D
+1D438 ; FC_NFKC; 0065 # L& MATHEMATICAL ITALIC CAPITAL E
+1D439 ; FC_NFKC; 0066 # L& MATHEMATICAL ITALIC CAPITAL F
+1D43A ; FC_NFKC; 0067 # L& MATHEMATICAL ITALIC CAPITAL G
+1D43B ; FC_NFKC; 0068 # L& MATHEMATICAL ITALIC CAPITAL H
+1D43C ; FC_NFKC; 0069 # L& MATHEMATICAL ITALIC CAPITAL I
+1D43D ; FC_NFKC; 006A # L& MATHEMATICAL ITALIC CAPITAL J
+1D43E ; FC_NFKC; 006B # L& MATHEMATICAL ITALIC CAPITAL K
+1D43F ; FC_NFKC; 006C # L& MATHEMATICAL ITALIC CAPITAL L
+1D440 ; FC_NFKC; 006D # L& MATHEMATICAL ITALIC CAPITAL M
+1D441 ; FC_NFKC; 006E # L& MATHEMATICAL ITALIC CAPITAL N
+1D442 ; FC_NFKC; 006F # L& MATHEMATICAL ITALIC CAPITAL O
+1D443 ; FC_NFKC; 0070 # L& MATHEMATICAL ITALIC CAPITAL P
+1D444 ; FC_NFKC; 0071 # L& MATHEMATICAL ITALIC CAPITAL Q
+1D445 ; FC_NFKC; 0072 # L& MATHEMATICAL ITALIC CAPITAL R
+1D446 ; FC_NFKC; 0073 # L& MATHEMATICAL ITALIC CAPITAL S
+1D447 ; FC_NFKC; 0074 # L& MATHEMATICAL ITALIC CAPITAL T
+1D448 ; FC_NFKC; 0075 # L& MATHEMATICAL ITALIC CAPITAL U
+1D449 ; FC_NFKC; 0076 # L& MATHEMATICAL ITALIC CAPITAL V
+1D44A ; FC_NFKC; 0077 # L& MATHEMATICAL ITALIC CAPITAL W
+1D44B ; FC_NFKC; 0078 # L& MATHEMATICAL ITALIC CAPITAL X
+1D44C ; FC_NFKC; 0079 # L& MATHEMATICAL ITALIC CAPITAL Y
+1D44D ; FC_NFKC; 007A # L& MATHEMATICAL ITALIC CAPITAL Z
+1D468 ; FC_NFKC; 0061 # L& MATHEMATICAL BOLD ITALIC CAPITAL A
+1D469 ; FC_NFKC; 0062 # L& MATHEMATICAL BOLD ITALIC CAPITAL B
+1D46A ; FC_NFKC; 0063 # L& MATHEMATICAL BOLD ITALIC CAPITAL C
+1D46B ; FC_NFKC; 0064 # L& MATHEMATICAL BOLD ITALIC CAPITAL D
+1D46C ; FC_NFKC; 0065 # L& MATHEMATICAL BOLD ITALIC CAPITAL E
+1D46D ; FC_NFKC; 0066 # L& MATHEMATICAL BOLD ITALIC CAPITAL F
+1D46E ; FC_NFKC; 0067 # L& MATHEMATICAL BOLD ITALIC CAPITAL G
+1D46F ; FC_NFKC; 0068 # L& MATHEMATICAL BOLD ITALIC CAPITAL H
+1D470 ; FC_NFKC; 0069 # L& MATHEMATICAL BOLD ITALIC CAPITAL I
+1D471 ; FC_NFKC; 006A # L& MATHEMATICAL BOLD ITALIC CAPITAL J
+1D472 ; FC_NFKC; 006B # L& MATHEMATICAL BOLD ITALIC CAPITAL K
+1D473 ; FC_NFKC; 006C # L& MATHEMATICAL BOLD ITALIC CAPITAL L
+1D474 ; FC_NFKC; 006D # L& MATHEMATICAL BOLD ITALIC CAPITAL M
+1D475 ; FC_NFKC; 006E # L& MATHEMATICAL BOLD ITALIC CAPITAL N
+1D476 ; FC_NFKC; 006F # L& MATHEMATICAL BOLD ITALIC CAPITAL O
+1D477 ; FC_NFKC; 0070 # L& MATHEMATICAL BOLD ITALIC CAPITAL P
+1D478 ; FC_NFKC; 0071 # L& MATHEMATICAL BOLD ITALIC CAPITAL Q
+1D479 ; FC_NFKC; 0072 # L& MATHEMATICAL BOLD ITALIC CAPITAL R
+1D47A ; FC_NFKC; 0073 # L& MATHEMATICAL BOLD ITALIC CAPITAL S
+1D47B ; FC_NFKC; 0074 # L& MATHEMATICAL BOLD ITALIC CAPITAL T
+1D47C ; FC_NFKC; 0075 # L& MATHEMATICAL BOLD ITALIC CAPITAL U
+1D47D ; FC_NFKC; 0076 # L& MATHEMATICAL BOLD ITALIC CAPITAL V
+1D47E ; FC_NFKC; 0077 # L& MATHEMATICAL BOLD ITALIC CAPITAL W
+1D47F ; FC_NFKC; 0078 # L& MATHEMATICAL BOLD ITALIC CAPITAL X
+1D480 ; FC_NFKC; 0079 # L& MATHEMATICAL BOLD ITALIC CAPITAL Y
+1D481 ; FC_NFKC; 007A # L& MATHEMATICAL BOLD ITALIC CAPITAL Z
+1D49C ; FC_NFKC; 0061 # L& MATHEMATICAL SCRIPT CAPITAL A
+1D49E ; FC_NFKC; 0063 # L& MATHEMATICAL SCRIPT CAPITAL C
+1D49F ; FC_NFKC; 0064 # L& MATHEMATICAL SCRIPT CAPITAL D
+1D4A2 ; FC_NFKC; 0067 # L& MATHEMATICAL SCRIPT CAPITAL G
+1D4A5 ; FC_NFKC; 006A # L& MATHEMATICAL SCRIPT CAPITAL J
+1D4A6 ; FC_NFKC; 006B # L& MATHEMATICAL SCRIPT CAPITAL K
+1D4A9 ; FC_NFKC; 006E # L& MATHEMATICAL SCRIPT CAPITAL N
+1D4AA ; FC_NFKC; 006F # L& MATHEMATICAL SCRIPT CAPITAL O
+1D4AB ; FC_NFKC; 0070 # L& MATHEMATICAL SCRIPT CAPITAL P
+1D4AC ; FC_NFKC; 0071 # L& MATHEMATICAL SCRIPT CAPITAL Q
+1D4AE ; FC_NFKC; 0073 # L& MATHEMATICAL SCRIPT CAPITAL S
+1D4AF ; FC_NFKC; 0074 # L& MATHEMATICAL SCRIPT CAPITAL T
+1D4B0 ; FC_NFKC; 0075 # L& MATHEMATICAL SCRIPT CAPITAL U
+1D4B1 ; FC_NFKC; 0076 # L& MATHEMATICAL SCRIPT CAPITAL V
+1D4B2 ; FC_NFKC; 0077 # L& MATHEMATICAL SCRIPT CAPITAL W
+1D4B3 ; FC_NFKC; 0078 # L& MATHEMATICAL SCRIPT CAPITAL X
+1D4B4 ; FC_NFKC; 0079 # L& MATHEMATICAL SCRIPT CAPITAL Y
+1D4B5 ; FC_NFKC; 007A # L& MATHEMATICAL SCRIPT CAPITAL Z
+1D4D0 ; FC_NFKC; 0061 # L& MATHEMATICAL BOLD SCRIPT CAPITAL A
+1D4D1 ; FC_NFKC; 0062 # L& MATHEMATICAL BOLD SCRIPT CAPITAL B
+1D4D2 ; FC_NFKC; 0063 # L& MATHEMATICAL BOLD SCRIPT CAPITAL C
+1D4D3 ; FC_NFKC; 0064 # L& MATHEMATICAL BOLD SCRIPT CAPITAL D
+1D4D4 ; FC_NFKC; 0065 # L& MATHEMATICAL BOLD SCRIPT CAPITAL E
+1D4D5 ; FC_NFKC; 0066 # L& MATHEMATICAL BOLD SCRIPT CAPITAL F
+1D4D6 ; FC_NFKC; 0067 # L& MATHEMATICAL BOLD SCRIPT CAPITAL G
+1D4D7 ; FC_NFKC; 0068 # L& MATHEMATICAL BOLD SCRIPT CAPITAL H
+1D4D8 ; FC_NFKC; 0069 # L& MATHEMATICAL BOLD SCRIPT CAPITAL I
+1D4D9 ; FC_NFKC; 006A # L& MATHEMATICAL BOLD SCRIPT CAPITAL J
+1D4DA ; FC_NFKC; 006B # L& MATHEMATICAL BOLD SCRIPT CAPITAL K
+1D4DB ; FC_NFKC; 006C # L& MATHEMATICAL BOLD SCRIPT CAPITAL L
+1D4DC ; FC_NFKC; 006D # L& MATHEMATICAL BOLD SCRIPT CAPITAL M
+1D4DD ; FC_NFKC; 006E # L& MATHEMATICAL BOLD SCRIPT CAPITAL N
+1D4DE ; FC_NFKC; 006F # L& MATHEMATICAL BOLD SCRIPT CAPITAL O
+1D4DF ; FC_NFKC; 0070 # L& MATHEMATICAL BOLD SCRIPT CAPITAL P
+1D4E0 ; FC_NFKC; 0071 # L& MATHEMATICAL BOLD SCRIPT CAPITAL Q
+1D4E1 ; FC_NFKC; 0072 # L& MATHEMATICAL BOLD SCRIPT CAPITAL R
+1D4E2 ; FC_NFKC; 0073 # L& MATHEMATICAL BOLD SCRIPT CAPITAL S
+1D4E3 ; FC_NFKC; 0074 # L& MATHEMATICAL BOLD SCRIPT CAPITAL T
+1D4E4 ; FC_NFKC; 0075 # L& MATHEMATICAL BOLD SCRIPT CAPITAL U
+1D4E5 ; FC_NFKC; 0076 # L& MATHEMATICAL BOLD SCRIPT CAPITAL V
+1D4E6 ; FC_NFKC; 0077 # L& MATHEMATICAL BOLD SCRIPT CAPITAL W
+1D4E7 ; FC_NFKC; 0078 # L& MATHEMATICAL BOLD SCRIPT CAPITAL X
+1D4E8 ; FC_NFKC; 0079 # L& MATHEMATICAL BOLD SCRIPT CAPITAL Y
+1D4E9 ; FC_NFKC; 007A # L& MATHEMATICAL BOLD SCRIPT CAPITAL Z
+1D504 ; FC_NFKC; 0061 # L& MATHEMATICAL FRAKTUR CAPITAL A
+1D505 ; FC_NFKC; 0062 # L& MATHEMATICAL FRAKTUR CAPITAL B
+1D507 ; FC_NFKC; 0064 # L& MATHEMATICAL FRAKTUR CAPITAL D
+1D508 ; FC_NFKC; 0065 # L& MATHEMATICAL FRAKTUR CAPITAL E
+1D509 ; FC_NFKC; 0066 # L& MATHEMATICAL FRAKTUR CAPITAL F
+1D50A ; FC_NFKC; 0067 # L& MATHEMATICAL FRAKTUR CAPITAL G
+1D50D ; FC_NFKC; 006A # L& MATHEMATICAL FRAKTUR CAPITAL J
+1D50E ; FC_NFKC; 006B # L& MATHEMATICAL FRAKTUR CAPITAL K
+1D50F ; FC_NFKC; 006C # L& MATHEMATICAL FRAKTUR CAPITAL L
+1D510 ; FC_NFKC; 006D # L& MATHEMATICAL FRAKTUR CAPITAL M
+1D511 ; FC_NFKC; 006E # L& MATHEMATICAL FRAKTUR CAPITAL N
+1D512 ; FC_NFKC; 006F # L& MATHEMATICAL FRAKTUR CAPITAL O
+1D513 ; FC_NFKC; 0070 # L& MATHEMATICAL FRAKTUR CAPITAL P
+1D514 ; FC_NFKC; 0071 # L& MATHEMATICAL FRAKTUR CAPITAL Q
+1D516 ; FC_NFKC; 0073 # L& MATHEMATICAL FRAKTUR CAPITAL S
+1D517 ; FC_NFKC; 0074 # L& MATHEMATICAL FRAKTUR CAPITAL T
+1D518 ; FC_NFKC; 0075 # L& MATHEMATICAL FRAKTUR CAPITAL U
+1D519 ; FC_NFKC; 0076 # L& MATHEMATICAL FRAKTUR CAPITAL V
+1D51A ; FC_NFKC; 0077 # L& MATHEMATICAL FRAKTUR CAPITAL W
+1D51B ; FC_NFKC; 0078 # L& MATHEMATICAL FRAKTUR CAPITAL X
+1D51C ; FC_NFKC; 0079 # L& MATHEMATICAL FRAKTUR CAPITAL Y
+1D538 ; FC_NFKC; 0061 # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL A
+1D539 ; FC_NFKC; 0062 # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL B
+1D53B ; FC_NFKC; 0064 # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL D
+1D53C ; FC_NFKC; 0065 # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL E
+1D53D ; FC_NFKC; 0066 # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL F
+1D53E ; FC_NFKC; 0067 # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL G
+1D540 ; FC_NFKC; 0069 # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL I
+1D541 ; FC_NFKC; 006A # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL J
+1D542 ; FC_NFKC; 006B # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL K
+1D543 ; FC_NFKC; 006C # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL L
+1D544 ; FC_NFKC; 006D # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL M
+1D546 ; FC_NFKC; 006F # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL O
+1D54A ; FC_NFKC; 0073 # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL S
+1D54B ; FC_NFKC; 0074 # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL T
+1D54C ; FC_NFKC; 0075 # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL U
+1D54D ; FC_NFKC; 0076 # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL V
+1D54E ; FC_NFKC; 0077 # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL W
+1D54F ; FC_NFKC; 0078 # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL X
+1D550 ; FC_NFKC; 0079 # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL Y
+1D56C ; FC_NFKC; 0061 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL A
+1D56D ; FC_NFKC; 0062 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL B
+1D56E ; FC_NFKC; 0063 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL C
+1D56F ; FC_NFKC; 0064 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL D
+1D570 ; FC_NFKC; 0065 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL E
+1D571 ; FC_NFKC; 0066 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL F
+1D572 ; FC_NFKC; 0067 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL G
+1D573 ; FC_NFKC; 0068 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL H
+1D574 ; FC_NFKC; 0069 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL I
+1D575 ; FC_NFKC; 006A # L& MATHEMATICAL BOLD FRAKTUR CAPITAL J
+1D576 ; FC_NFKC; 006B # L& MATHEMATICAL BOLD FRAKTUR CAPITAL K
+1D577 ; FC_NFKC; 006C # L& MATHEMATICAL BOLD FRAKTUR CAPITAL L
+1D578 ; FC_NFKC; 006D # L& MATHEMATICAL BOLD FRAKTUR CAPITAL M
+1D579 ; FC_NFKC; 006E # L& MATHEMATICAL BOLD FRAKTUR CAPITAL N
+1D57A ; FC_NFKC; 006F # L& MATHEMATICAL BOLD FRAKTUR CAPITAL O
+1D57B ; FC_NFKC; 0070 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL P
+1D57C ; FC_NFKC; 0071 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL Q
+1D57D ; FC_NFKC; 0072 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL R
+1D57E ; FC_NFKC; 0073 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL S
+1D57F ; FC_NFKC; 0074 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL T
+1D580 ; FC_NFKC; 0075 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL U
+1D581 ; FC_NFKC; 0076 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL V
+1D582 ; FC_NFKC; 0077 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL W
+1D583 ; FC_NFKC; 0078 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL X
+1D584 ; FC_NFKC; 0079 # L& MATHEMATICAL BOLD FRAKTUR CAPITAL Y
+1D585 ; FC_NFKC; 007A # L& MATHEMATICAL BOLD FRAKTUR CAPITAL Z
+1D5A0 ; FC_NFKC; 0061 # L& MATHEMATICAL SANS-SERIF CAPITAL A
+1D5A1 ; FC_NFKC; 0062 # L& MATHEMATICAL SANS-SERIF CAPITAL B
+1D5A2 ; FC_NFKC; 0063 # L& MATHEMATICAL SANS-SERIF CAPITAL C
+1D5A3 ; FC_NFKC; 0064 # L& MATHEMATICAL SANS-SERIF CAPITAL D
+1D5A4 ; FC_NFKC; 0065 # L& MATHEMATICAL SANS-SERIF CAPITAL E
+1D5A5 ; FC_NFKC; 0066 # L& MATHEMATICAL SANS-SERIF CAPITAL F
+1D5A6 ; FC_NFKC; 0067 # L& MATHEMATICAL SANS-SERIF CAPITAL G
+1D5A7 ; FC_NFKC; 0068 # L& MATHEMATICAL SANS-SERIF CAPITAL H
+1D5A8 ; FC_NFKC; 0069 # L& MATHEMATICAL SANS-SERIF CAPITAL I
+1D5A9 ; FC_NFKC; 006A # L& MATHEMATICAL SANS-SERIF CAPITAL J
+1D5AA ; FC_NFKC; 006B # L& MATHEMATICAL SANS-SERIF CAPITAL K
+1D5AB ; FC_NFKC; 006C # L& MATHEMATICAL SANS-SERIF CAPITAL L
+1D5AC ; FC_NFKC; 006D # L& MATHEMATICAL SANS-SERIF CAPITAL M
+1D5AD ; FC_NFKC; 006E # L& MATHEMATICAL SANS-SERIF CAPITAL N
+1D5AE ; FC_NFKC; 006F # L& MATHEMATICAL SANS-SERIF CAPITAL O
+1D5AF ; FC_NFKC; 0070 # L& MATHEMATICAL SANS-SERIF CAPITAL P
+1D5B0 ; FC_NFKC; 0071 # L& MATHEMATICAL SANS-SERIF CAPITAL Q
+1D5B1 ; FC_NFKC; 0072 # L& MATHEMATICAL SANS-SERIF CAPITAL R
+1D5B2 ; FC_NFKC; 0073 # L& MATHEMATICAL SANS-SERIF CAPITAL S
+1D5B3 ; FC_NFKC; 0074 # L& MATHEMATICAL SANS-SERIF CAPITAL T
+1D5B4 ; FC_NFKC; 0075 # L& MATHEMATICAL SANS-SERIF CAPITAL U
+1D5B5 ; FC_NFKC; 0076 # L& MATHEMATICAL SANS-SERIF CAPITAL V
+1D5B6 ; FC_NFKC; 0077 # L& MATHEMATICAL SANS-SERIF CAPITAL W
+1D5B7 ; FC_NFKC; 0078 # L& MATHEMATICAL SANS-SERIF CAPITAL X
+1D5B8 ; FC_NFKC; 0079 # L& MATHEMATICAL SANS-SERIF CAPITAL Y
+1D5B9 ; FC_NFKC; 007A # L& MATHEMATICAL SANS-SERIF CAPITAL Z
+1D5D4 ; FC_NFKC; 0061 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL A
+1D5D5 ; FC_NFKC; 0062 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL B
+1D5D6 ; FC_NFKC; 0063 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL C
+1D5D7 ; FC_NFKC; 0064 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL D
+1D5D8 ; FC_NFKC; 0065 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL E
+1D5D9 ; FC_NFKC; 0066 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL F
+1D5DA ; FC_NFKC; 0067 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL G
+1D5DB ; FC_NFKC; 0068 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL H
+1D5DC ; FC_NFKC; 0069 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL I
+1D5DD ; FC_NFKC; 006A # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL J
+1D5DE ; FC_NFKC; 006B # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL K
+1D5DF ; FC_NFKC; 006C # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL L
+1D5E0 ; FC_NFKC; 006D # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL M
+1D5E1 ; FC_NFKC; 006E # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL N
+1D5E2 ; FC_NFKC; 006F # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL O
+1D5E3 ; FC_NFKC; 0070 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL P
+1D5E4 ; FC_NFKC; 0071 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL Q
+1D5E5 ; FC_NFKC; 0072 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL R
+1D5E6 ; FC_NFKC; 0073 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL S
+1D5E7 ; FC_NFKC; 0074 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL T
+1D5E8 ; FC_NFKC; 0075 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL U
+1D5E9 ; FC_NFKC; 0076 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL V
+1D5EA ; FC_NFKC; 0077 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL W
+1D5EB ; FC_NFKC; 0078 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL X
+1D5EC ; FC_NFKC; 0079 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL Y
+1D5ED ; FC_NFKC; 007A # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL Z
+1D608 ; FC_NFKC; 0061 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL A
+1D609 ; FC_NFKC; 0062 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL B
+1D60A ; FC_NFKC; 0063 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL C
+1D60B ; FC_NFKC; 0064 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL D
+1D60C ; FC_NFKC; 0065 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL E
+1D60D ; FC_NFKC; 0066 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL F
+1D60E ; FC_NFKC; 0067 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL G
+1D60F ; FC_NFKC; 0068 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL H
+1D610 ; FC_NFKC; 0069 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL I
+1D611 ; FC_NFKC; 006A # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL J
+1D612 ; FC_NFKC; 006B # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL K
+1D613 ; FC_NFKC; 006C # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL L
+1D614 ; FC_NFKC; 006D # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL M
+1D615 ; FC_NFKC; 006E # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL N
+1D616 ; FC_NFKC; 006F # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL O
+1D617 ; FC_NFKC; 0070 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL P
+1D618 ; FC_NFKC; 0071 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL Q
+1D619 ; FC_NFKC; 0072 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL R
+1D61A ; FC_NFKC; 0073 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL S
+1D61B ; FC_NFKC; 0074 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL T
+1D61C ; FC_NFKC; 0075 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL U
+1D61D ; FC_NFKC; 0076 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL V
+1D61E ; FC_NFKC; 0077 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL W
+1D61F ; FC_NFKC; 0078 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL X
+1D620 ; FC_NFKC; 0079 # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL Y
+1D621 ; FC_NFKC; 007A # L& MATHEMATICAL SANS-SERIF ITALIC CAPITAL Z
+1D63C ; FC_NFKC; 0061 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL A
+1D63D ; FC_NFKC; 0062 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL B
+1D63E ; FC_NFKC; 0063 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL C
+1D63F ; FC_NFKC; 0064 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL D
+1D640 ; FC_NFKC; 0065 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL E
+1D641 ; FC_NFKC; 0066 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL F
+1D642 ; FC_NFKC; 0067 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL G
+1D643 ; FC_NFKC; 0068 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL H
+1D644 ; FC_NFKC; 0069 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL I
+1D645 ; FC_NFKC; 006A # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL J
+1D646 ; FC_NFKC; 006B # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL K
+1D647 ; FC_NFKC; 006C # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL L
+1D648 ; FC_NFKC; 006D # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL M
+1D649 ; FC_NFKC; 006E # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL N
+1D64A ; FC_NFKC; 006F # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL O
+1D64B ; FC_NFKC; 0070 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL P
+1D64C ; FC_NFKC; 0071 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL Q
+1D64D ; FC_NFKC; 0072 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL R
+1D64E ; FC_NFKC; 0073 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL S
+1D64F ; FC_NFKC; 0074 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL T
+1D650 ; FC_NFKC; 0075 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL U
+1D651 ; FC_NFKC; 0076 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL V
+1D652 ; FC_NFKC; 0077 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL W
+1D653 ; FC_NFKC; 0078 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL X
+1D654 ; FC_NFKC; 0079 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL Y
+1D655 ; FC_NFKC; 007A # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL Z
+1D670 ; FC_NFKC; 0061 # L& MATHEMATICAL MONOSPACE CAPITAL A
+1D671 ; FC_NFKC; 0062 # L& MATHEMATICAL MONOSPACE CAPITAL B
+1D672 ; FC_NFKC; 0063 # L& MATHEMATICAL MONOSPACE CAPITAL C
+1D673 ; FC_NFKC; 0064 # L& MATHEMATICAL MONOSPACE CAPITAL D
+1D674 ; FC_NFKC; 0065 # L& MATHEMATICAL MONOSPACE CAPITAL E
+1D675 ; FC_NFKC; 0066 # L& MATHEMATICAL MONOSPACE CAPITAL F
+1D676 ; FC_NFKC; 0067 # L& MATHEMATICAL MONOSPACE CAPITAL G
+1D677 ; FC_NFKC; 0068 # L& MATHEMATICAL MONOSPACE CAPITAL H
+1D678 ; FC_NFKC; 0069 # L& MATHEMATICAL MONOSPACE CAPITAL I
+1D679 ; FC_NFKC; 006A # L& MATHEMATICAL MONOSPACE CAPITAL J
+1D67A ; FC_NFKC; 006B # L& MATHEMATICAL MONOSPACE CAPITAL K
+1D67B ; FC_NFKC; 006C # L& MATHEMATICAL MONOSPACE CAPITAL L
+1D67C ; FC_NFKC; 006D # L& MATHEMATICAL MONOSPACE CAPITAL M
+1D67D ; FC_NFKC; 006E # L& MATHEMATICAL MONOSPACE CAPITAL N
+1D67E ; FC_NFKC; 006F # L& MATHEMATICAL MONOSPACE CAPITAL O
+1D67F ; FC_NFKC; 0070 # L& MATHEMATICAL MONOSPACE CAPITAL P
+1D680 ; FC_NFKC; 0071 # L& MATHEMATICAL MONOSPACE CAPITAL Q
+1D681 ; FC_NFKC; 0072 # L& MATHEMATICAL MONOSPACE CAPITAL R
+1D682 ; FC_NFKC; 0073 # L& MATHEMATICAL MONOSPACE CAPITAL S
+1D683 ; FC_NFKC; 0074 # L& MATHEMATICAL MONOSPACE CAPITAL T
+1D684 ; FC_NFKC; 0075 # L& MATHEMATICAL MONOSPACE CAPITAL U
+1D685 ; FC_NFKC; 0076 # L& MATHEMATICAL MONOSPACE CAPITAL V
+1D686 ; FC_NFKC; 0077 # L& MATHEMATICAL MONOSPACE CAPITAL W
+1D687 ; FC_NFKC; 0078 # L& MATHEMATICAL MONOSPACE CAPITAL X
+1D688 ; FC_NFKC; 0079 # L& MATHEMATICAL MONOSPACE CAPITAL Y
+1D689 ; FC_NFKC; 007A # L& MATHEMATICAL MONOSPACE CAPITAL Z
+1D6A8 ; FC_NFKC; 03B1 # L& MATHEMATICAL BOLD CAPITAL ALPHA
+1D6A9 ; FC_NFKC; 03B2 # L& MATHEMATICAL BOLD CAPITAL BETA
+1D6AA ; FC_NFKC; 03B3 # L& MATHEMATICAL BOLD CAPITAL GAMMA
+1D6AB ; FC_NFKC; 03B4 # L& MATHEMATICAL BOLD CAPITAL DELTA
+1D6AC ; FC_NFKC; 03B5 # L& MATHEMATICAL BOLD CAPITAL EPSILON
+1D6AD ; FC_NFKC; 03B6 # L& MATHEMATICAL BOLD CAPITAL ZETA
+1D6AE ; FC_NFKC; 03B7 # L& MATHEMATICAL BOLD CAPITAL ETA
+1D6AF ; FC_NFKC; 03B8 # L& MATHEMATICAL BOLD CAPITAL THETA
+1D6B0 ; FC_NFKC; 03B9 # L& MATHEMATICAL BOLD CAPITAL IOTA
+1D6B1 ; FC_NFKC; 03BA # L& MATHEMATICAL BOLD CAPITAL KAPPA
+1D6B2 ; FC_NFKC; 03BB # L& MATHEMATICAL BOLD CAPITAL LAMDA
+1D6B3 ; FC_NFKC; 03BC # L& MATHEMATICAL BOLD CAPITAL MU
+1D6B4 ; FC_NFKC; 03BD # L& MATHEMATICAL BOLD CAPITAL NU
+1D6B5 ; FC_NFKC; 03BE # L& MATHEMATICAL BOLD CAPITAL XI
+1D6B6 ; FC_NFKC; 03BF # L& MATHEMATICAL BOLD CAPITAL OMICRON
+1D6B7 ; FC_NFKC; 03C0 # L& MATHEMATICAL BOLD CAPITAL PI
+1D6B8 ; FC_NFKC; 03C1 # L& MATHEMATICAL BOLD CAPITAL RHO
+1D6B9 ; FC_NFKC; 03B8 # L& MATHEMATICAL BOLD CAPITAL THETA SYMBOL
+1D6BA ; FC_NFKC; 03C3 # L& MATHEMATICAL BOLD CAPITAL SIGMA
+1D6BB ; FC_NFKC; 03C4 # L& MATHEMATICAL BOLD CAPITAL TAU
+1D6BC ; FC_NFKC; 03C5 # L& MATHEMATICAL BOLD CAPITAL UPSILON
+1D6BD ; FC_NFKC; 03C6 # L& MATHEMATICAL BOLD CAPITAL PHI
+1D6BE ; FC_NFKC; 03C7 # L& MATHEMATICAL BOLD CAPITAL CHI
+1D6BF ; FC_NFKC; 03C8 # L& MATHEMATICAL BOLD CAPITAL PSI
+1D6C0 ; FC_NFKC; 03C9 # L& MATHEMATICAL BOLD CAPITAL OMEGA
+1D6D3 ; FC_NFKC; 03C3 # L& MATHEMATICAL BOLD SMALL FINAL SIGMA
+1D6E2 ; FC_NFKC; 03B1 # L& MATHEMATICAL ITALIC CAPITAL ALPHA
+1D6E3 ; FC_NFKC; 03B2 # L& MATHEMATICAL ITALIC CAPITAL BETA
+1D6E4 ; FC_NFKC; 03B3 # L& MATHEMATICAL ITALIC CAPITAL GAMMA
+1D6E5 ; FC_NFKC; 03B4 # L& MATHEMATICAL ITALIC CAPITAL DELTA
+1D6E6 ; FC_NFKC; 03B5 # L& MATHEMATICAL ITALIC CAPITAL EPSILON
+1D6E7 ; FC_NFKC; 03B6 # L& MATHEMATICAL ITALIC CAPITAL ZETA
+1D6E8 ; FC_NFKC; 03B7 # L& MATHEMATICAL ITALIC CAPITAL ETA
+1D6E9 ; FC_NFKC; 03B8 # L& MATHEMATICAL ITALIC CAPITAL THETA
+1D6EA ; FC_NFKC; 03B9 # L& MATHEMATICAL ITALIC CAPITAL IOTA
+1D6EB ; FC_NFKC; 03BA # L& MATHEMATICAL ITALIC CAPITAL KAPPA
+1D6EC ; FC_NFKC; 03BB # L& MATHEMATICAL ITALIC CAPITAL LAMDA
+1D6ED ; FC_NFKC; 03BC # L& MATHEMATICAL ITALIC CAPITAL MU
+1D6EE ; FC_NFKC; 03BD # L& MATHEMATICAL ITALIC CAPITAL NU
+1D6EF ; FC_NFKC; 03BE # L& MATHEMATICAL ITALIC CAPITAL XI
+1D6F0 ; FC_NFKC; 03BF # L& MATHEMATICAL ITALIC CAPITAL OMICRON
+1D6F1 ; FC_NFKC; 03C0 # L& MATHEMATICAL ITALIC CAPITAL PI
+1D6F2 ; FC_NFKC; 03C1 # L& MATHEMATICAL ITALIC CAPITAL RHO
+1D6F3 ; FC_NFKC; 03B8 # L& MATHEMATICAL ITALIC CAPITAL THETA SYMBOL
+1D6F4 ; FC_NFKC; 03C3 # L& MATHEMATICAL ITALIC CAPITAL SIGMA
+1D6F5 ; FC_NFKC; 03C4 # L& MATHEMATICAL ITALIC CAPITAL TAU
+1D6F6 ; FC_NFKC; 03C5 # L& MATHEMATICAL ITALIC CAPITAL UPSILON
+1D6F7 ; FC_NFKC; 03C6 # L& MATHEMATICAL ITALIC CAPITAL PHI
+1D6F8 ; FC_NFKC; 03C7 # L& MATHEMATICAL ITALIC CAPITAL CHI
+1D6F9 ; FC_NFKC; 03C8 # L& MATHEMATICAL ITALIC CAPITAL PSI
+1D6FA ; FC_NFKC; 03C9 # L& MATHEMATICAL ITALIC CAPITAL OMEGA
+1D70D ; FC_NFKC; 03C3 # L& MATHEMATICAL ITALIC SMALL FINAL SIGMA
+1D71C ; FC_NFKC; 03B1 # L& MATHEMATICAL BOLD ITALIC CAPITAL ALPHA
+1D71D ; FC_NFKC; 03B2 # L& MATHEMATICAL BOLD ITALIC CAPITAL BETA
+1D71E ; FC_NFKC; 03B3 # L& MATHEMATICAL BOLD ITALIC CAPITAL GAMMA
+1D71F ; FC_NFKC; 03B4 # L& MATHEMATICAL BOLD ITALIC CAPITAL DELTA
+1D720 ; FC_NFKC; 03B5 # L& MATHEMATICAL BOLD ITALIC CAPITAL EPSILON
+1D721 ; FC_NFKC; 03B6 # L& MATHEMATICAL BOLD ITALIC CAPITAL ZETA
+1D722 ; FC_NFKC; 03B7 # L& MATHEMATICAL BOLD ITALIC CAPITAL ETA
+1D723 ; FC_NFKC; 03B8 # L& MATHEMATICAL BOLD ITALIC CAPITAL THETA
+1D724 ; FC_NFKC; 03B9 # L& MATHEMATICAL BOLD ITALIC CAPITAL IOTA
+1D725 ; FC_NFKC; 03BA # L& MATHEMATICAL BOLD ITALIC CAPITAL KAPPA
+1D726 ; FC_NFKC; 03BB # L& MATHEMATICAL BOLD ITALIC CAPITAL LAMDA
+1D727 ; FC_NFKC; 03BC # L& MATHEMATICAL BOLD ITALIC CAPITAL MU
+1D728 ; FC_NFKC; 03BD # L& MATHEMATICAL BOLD ITALIC CAPITAL NU
+1D729 ; FC_NFKC; 03BE # L& MATHEMATICAL BOLD ITALIC CAPITAL XI
+1D72A ; FC_NFKC; 03BF # L& MATHEMATICAL BOLD ITALIC CAPITAL OMICRON
+1D72B ; FC_NFKC; 03C0 # L& MATHEMATICAL BOLD ITALIC CAPITAL PI
+1D72C ; FC_NFKC; 03C1 # L& MATHEMATICAL BOLD ITALIC CAPITAL RHO
+1D72D ; FC_NFKC; 03B8 # L& MATHEMATICAL BOLD ITALIC CAPITAL THETA SYMBOL
+1D72E ; FC_NFKC; 03C3 # L& MATHEMATICAL BOLD ITALIC CAPITAL SIGMA
+1D72F ; FC_NFKC; 03C4 # L& MATHEMATICAL BOLD ITALIC CAPITAL TAU
+1D730 ; FC_NFKC; 03C5 # L& MATHEMATICAL BOLD ITALIC CAPITAL UPSILON
+1D731 ; FC_NFKC; 03C6 # L& MATHEMATICAL BOLD ITALIC CAPITAL PHI
+1D732 ; FC_NFKC; 03C7 # L& MATHEMATICAL BOLD ITALIC CAPITAL CHI
+1D733 ; FC_NFKC; 03C8 # L& MATHEMATICAL BOLD ITALIC CAPITAL PSI
+1D734 ; FC_NFKC; 03C9 # L& MATHEMATICAL BOLD ITALIC CAPITAL OMEGA
+1D747 ; FC_NFKC; 03C3 # L& MATHEMATICAL BOLD ITALIC SMALL FINAL SIGMA
+1D756 ; FC_NFKC; 03B1 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL ALPHA
+1D757 ; FC_NFKC; 03B2 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL BETA
+1D758 ; FC_NFKC; 03B3 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL GAMMA
+1D759 ; FC_NFKC; 03B4 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL DELTA
+1D75A ; FC_NFKC; 03B5 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL EPSILON
+1D75B ; FC_NFKC; 03B6 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL ZETA
+1D75C ; FC_NFKC; 03B7 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL ETA
+1D75D ; FC_NFKC; 03B8 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL THETA
+1D75E ; FC_NFKC; 03B9 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL IOTA
+1D75F ; FC_NFKC; 03BA # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL KAPPA
+1D760 ; FC_NFKC; 03BB # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL LAMDA
+1D761 ; FC_NFKC; 03BC # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL MU
+1D762 ; FC_NFKC; 03BD # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL NU
+1D763 ; FC_NFKC; 03BE # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL XI
+1D764 ; FC_NFKC; 03BF # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL OMICRON
+1D765 ; FC_NFKC; 03C0 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL PI
+1D766 ; FC_NFKC; 03C1 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL RHO
+1D767 ; FC_NFKC; 03B8 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL THETA SYMBOL
+1D768 ; FC_NFKC; 03C3 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL SIGMA
+1D769 ; FC_NFKC; 03C4 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL TAU
+1D76A ; FC_NFKC; 03C5 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL UPSILON
+1D76B ; FC_NFKC; 03C6 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL PHI
+1D76C ; FC_NFKC; 03C7 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL CHI
+1D76D ; FC_NFKC; 03C8 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL PSI
+1D76E ; FC_NFKC; 03C9 # L& MATHEMATICAL SANS-SERIF BOLD CAPITAL OMEGA
+1D781 ; FC_NFKC; 03C3 # L& MATHEMATICAL SANS-SERIF BOLD SMALL FINAL SIGMA
+1D790 ; FC_NFKC; 03B1 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ALPHA
+1D791 ; FC_NFKC; 03B2 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL BETA
+1D792 ; FC_NFKC; 03B3 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL GAMMA
+1D793 ; FC_NFKC; 03B4 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL DELTA
+1D794 ; FC_NFKC; 03B5 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL EPSILON
+1D795 ; FC_NFKC; 03B6 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ZETA
+1D796 ; FC_NFKC; 03B7 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ETA
+1D797 ; FC_NFKC; 03B8 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL THETA
+1D798 ; FC_NFKC; 03B9 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL IOTA
+1D799 ; FC_NFKC; 03BA # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL KAPPA
+1D79A ; FC_NFKC; 03BB # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL LAMDA
+1D79B ; FC_NFKC; 03BC # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL MU
+1D79C ; FC_NFKC; 03BD # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL NU
+1D79D ; FC_NFKC; 03BE # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL XI
+1D79E ; FC_NFKC; 03BF # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL OMICRON
+1D79F ; FC_NFKC; 03C0 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PI
+1D7A0 ; FC_NFKC; 03C1 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL RHO
+1D7A1 ; FC_NFKC; 03B8 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL THETA SYMBOL
+1D7A2 ; FC_NFKC; 03C3 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL SIGMA
+1D7A3 ; FC_NFKC; 03C4 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL TAU
+1D7A4 ; FC_NFKC; 03C5 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL UPSILON
+1D7A5 ; FC_NFKC; 03C6 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PHI
+1D7A6 ; FC_NFKC; 03C7 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL CHI
+1D7A7 ; FC_NFKC; 03C8 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PSI
+1D7A8 ; FC_NFKC; 03C9 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL OMEGA
+1D7BB ; FC_NFKC; 03C3 # L& MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL FINAL SIGMA
+
+# Total code points: 564
+
+# ================================================
+
+# Derived Property: Full_Composition_Exclusion
+# Generated from: Composition Exclusions + Singletons + Non-Starter Decompositions
+
+0340..0341 ; Full_Composition_Exclusion # Mn [2] COMBINING GRAVE TONE MARK..COMBINING ACUTE TONE MARK
+0343..0344 ; Full_Composition_Exclusion # Mn [2] COMBINING GREEK KORONIS..COMBINING GREEK DIALYTIKA TONOS
+0374 ; Full_Composition_Exclusion # Sk GREEK NUMERAL SIGN
+037E ; Full_Composition_Exclusion # Po GREEK QUESTION MARK
+0387 ; Full_Composition_Exclusion # Po GREEK ANO TELEIA
+0958..095F ; Full_Composition_Exclusion # Lo [8] DEVANAGARI LETTER QA..DEVANAGARI LETTER YYA
+09DC..09DD ; Full_Composition_Exclusion # Lo [2] BENGALI LETTER RRA..BENGALI LETTER RHA
+09DF ; Full_Composition_Exclusion # Lo BENGALI LETTER YYA
+0A33 ; Full_Composition_Exclusion # Lo GURMUKHI LETTER LLA
+0A36 ; Full_Composition_Exclusion # Lo GURMUKHI LETTER SHA
+0A59..0A5B ; Full_Composition_Exclusion # Lo [3] GURMUKHI LETTER KHHA..GURMUKHI LETTER ZA
+0A5E ; Full_Composition_Exclusion # Lo GURMUKHI LETTER FA
+0B5C..0B5D ; Full_Composition_Exclusion # Lo [2] ORIYA LETTER RRA..ORIYA LETTER RHA
+0F43 ; Full_Composition_Exclusion # Lo TIBETAN LETTER GHA
+0F4D ; Full_Composition_Exclusion # Lo TIBETAN LETTER DDHA
+0F52 ; Full_Composition_Exclusion # Lo TIBETAN LETTER DHA
+0F57 ; Full_Composition_Exclusion # Lo TIBETAN LETTER BHA
+0F5C ; Full_Composition_Exclusion # Lo TIBETAN LETTER DZHA
+0F69 ; Full_Composition_Exclusion # Lo TIBETAN LETTER KSSA
+0F73 ; Full_Composition_Exclusion # Mn TIBETAN VOWEL SIGN II
+0F75..0F76 ; Full_Composition_Exclusion # Mn [2] TIBETAN VOWEL SIGN UU..TIBETAN VOWEL SIGN VOCALIC R
+0F78 ; Full_Composition_Exclusion # Mn TIBETAN VOWEL SIGN VOCALIC L
+0F81 ; Full_Composition_Exclusion # Mn TIBETAN VOWEL SIGN REVERSED II
+0F93 ; Full_Composition_Exclusion # Mn TIBETAN SUBJOINED LETTER GHA
+0F9D ; Full_Composition_Exclusion # Mn TIBETAN SUBJOINED LETTER DDHA
+0FA2 ; Full_Composition_Exclusion # Mn TIBETAN SUBJOINED LETTER DHA
+0FA7 ; Full_Composition_Exclusion # Mn TIBETAN SUBJOINED LETTER BHA
+0FAC ; Full_Composition_Exclusion # Mn TIBETAN SUBJOINED LETTER DZHA
+0FB9 ; Full_Composition_Exclusion # Mn TIBETAN SUBJOINED LETTER KSSA
+1F71 ; Full_Composition_Exclusion # L& GREEK SMALL LETTER ALPHA WITH OXIA
+1F73 ; Full_Composition_Exclusion # L& GREEK SMALL LETTER EPSILON WITH OXIA
+1F75 ; Full_Composition_Exclusion # L& GREEK SMALL LETTER ETA WITH OXIA
+1F77 ; Full_Composition_Exclusion # L& GREEK SMALL LETTER IOTA WITH OXIA
+1F79 ; Full_Composition_Exclusion # L& GREEK SMALL LETTER OMICRON WITH OXIA
+1F7B ; Full_Composition_Exclusion # L& GREEK SMALL LETTER UPSILON WITH OXIA
+1F7D ; Full_Composition_Exclusion # L& GREEK SMALL LETTER OMEGA WITH OXIA
+1FBB ; Full_Composition_Exclusion # L& GREEK CAPITAL LETTER ALPHA WITH OXIA
+1FBE ; Full_Composition_Exclusion # L& GREEK PROSGEGRAMMENI
+1FC9 ; Full_Composition_Exclusion # L& GREEK CAPITAL LETTER EPSILON WITH OXIA
+1FCB ; Full_Composition_Exclusion # L& GREEK CAPITAL LETTER ETA WITH OXIA
+1FD3 ; Full_Composition_Exclusion # L& GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA
+1FDB ; Full_Composition_Exclusion # L& GREEK CAPITAL LETTER IOTA WITH OXIA
+1FE3 ; Full_Composition_Exclusion # L& GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA
+1FEB ; Full_Composition_Exclusion # L& GREEK CAPITAL LETTER UPSILON WITH OXIA
+1FEE..1FEF ; Full_Composition_Exclusion # Sk [2] GREEK DIALYTIKA AND OXIA..GREEK VARIA
+1FF9 ; Full_Composition_Exclusion # L& GREEK CAPITAL LETTER OMICRON WITH OXIA
+1FFB ; Full_Composition_Exclusion # L& GREEK CAPITAL LETTER OMEGA WITH OXIA
+1FFD ; Full_Composition_Exclusion # Sk GREEK OXIA
+2000..2001 ; Full_Composition_Exclusion # Zs [2] EN QUAD..EM QUAD
+2126 ; Full_Composition_Exclusion # L& OHM SIGN
+212A..212B ; Full_Composition_Exclusion # L& [2] KELVIN SIGN..ANGSTROM SIGN
+2329 ; Full_Composition_Exclusion # Ps LEFT-POINTING ANGLE BRACKET
+232A ; Full_Composition_Exclusion # Pe RIGHT-POINTING ANGLE BRACKET
+2ADC ; Full_Composition_Exclusion # Sm FORKING
+F900..FA0D ; Full_Composition_Exclusion # Lo [270] CJK COMPATIBILITY IDEOGRAPH-F900..CJK COMPATIBILITY IDEOGRAPH-FA0D
+FA10 ; Full_Composition_Exclusion # Lo CJK COMPATIBILITY IDEOGRAPH-FA10
+FA12 ; Full_Composition_Exclusion # Lo CJK COMPATIBILITY IDEOGRAPH-FA12
+FA15..FA1E ; Full_Composition_Exclusion # Lo [10] CJK COMPATIBILITY IDEOGRAPH-FA15..CJK COMPATIBILITY IDEOGRAPH-FA1E
+FA20 ; Full_Composition_Exclusion # Lo CJK COMPATIBILITY IDEOGRAPH-FA20
+FA22 ; Full_Composition_Exclusion # Lo CJK COMPATIBILITY IDEOGRAPH-FA22
+FA25..FA26 ; Full_Composition_Exclusion # Lo [2] CJK COMPATIBILITY IDEOGRAPH-FA25..CJK COMPATIBILITY IDEOGRAPH-FA26
+FA2A..FA2D ; Full_Composition_Exclusion # Lo [4] CJK COMPATIBILITY IDEOGRAPH-FA2A..CJK COMPATIBILITY IDEOGRAPH-FA2D
+FA30..FA6A ; Full_Composition_Exclusion # Lo [59] CJK COMPATIBILITY IDEOGRAPH-FA30..CJK COMPATIBILITY IDEOGRAPH-FA6A
+FB1D ; Full_Composition_Exclusion # Lo HEBREW LETTER YOD WITH HIRIQ
+FB1F ; Full_Composition_Exclusion # Lo HEBREW LIGATURE YIDDISH YOD YOD PATAH
+FB2A..FB36 ; Full_Composition_Exclusion # Lo [13] HEBREW LETTER SHIN WITH SHIN DOT..HEBREW LETTER ZAYIN WITH DAGESH
+FB38..FB3C ; Full_Composition_Exclusion # Lo [5] HEBREW LETTER TET WITH DAGESH..HEBREW LETTER LAMED WITH DAGESH
+FB3E ; Full_Composition_Exclusion # Lo HEBREW LETTER MEM WITH DAGESH
+FB40..FB41 ; Full_Composition_Exclusion # Lo [2] HEBREW LETTER NUN WITH DAGESH..HEBREW LETTER SAMEKH WITH DAGESH
+FB43..FB44 ; Full_Composition_Exclusion # Lo [2] HEBREW LETTER FINAL PE WITH DAGESH..HEBREW LETTER PE WITH DAGESH
+FB46..FB4E ; Full_Composition_Exclusion # Lo [9] HEBREW LETTER TSADI WITH DAGESH..HEBREW LETTER PE WITH RAFE
+1D15E..1D164 ; Full_Composition_Exclusion # So [7] MUSICAL SYMBOL HALF NOTE..MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH NOTE
+1D1BB..1D1C0 ; Full_Composition_Exclusion # So [6] MUSICAL SYMBOL MINIMA..MUSICAL SYMBOL FUSA BLACK
+2F800..2FA1D ; Full_Composition_Exclusion # Lo [542] CJK COMPATIBILITY IDEOGRAPH-2F800..CJK COMPATIBILITY IDEOGRAPH-2FA1D
+
+# Total code points: 1009
+
+# ================================================
+
+# Property: NFD_Quick_Check
+
+# All code points not explicitly listed for NFD_Quick_Check
+# have the value Yes (Y).
+
+# ================================================
+
+# NFD_Quick_Check=No
+
+00C0..00C5 ; NFD_QC; N # L& [6] LATIN CAPITAL LETTER A WITH GRAVE..LATIN CAPITAL LETTER A WITH RING ABOVE
+00C7..00CF ; NFD_QC; N # L& [9] LATIN CAPITAL LETTER C WITH CEDILLA..LATIN CAPITAL LETTER I WITH DIAERESIS
+00D1..00D6 ; NFD_QC; N # L& [6] LATIN CAPITAL LETTER N WITH TILDE..LATIN CAPITAL LETTER O WITH DIAERESIS
+00D9..00DD ; NFD_QC; N # L& [5] LATIN CAPITAL LETTER U WITH GRAVE..LATIN CAPITAL LETTER Y WITH ACUTE
+00E0..00E5 ; NFD_QC; N # L& [6] LATIN SMALL LETTER A WITH GRAVE..LATIN SMALL LETTER A WITH RING ABOVE
+00E7..00EF ; NFD_QC; N # L& [9] LATIN SMALL LETTER C WITH CEDILLA..LATIN SMALL LETTER I WITH DIAERESIS
+00F1..00F6 ; NFD_QC; N # L& [6] LATIN SMALL LETTER N WITH TILDE..LATIN SMALL LETTER O WITH DIAERESIS
+00F9..00FD ; NFD_QC; N # L& [5] LATIN SMALL LETTER U WITH GRAVE..LATIN SMALL LETTER Y WITH ACUTE
+00FF..010F ; NFD_QC; N # L& [17] LATIN SMALL LETTER Y WITH DIAERESIS..LATIN SMALL LETTER D WITH CARON
+0112..0125 ; NFD_QC; N # L& [20] LATIN CAPITAL LETTER E WITH MACRON..LATIN SMALL LETTER H WITH CIRCUMFLEX
+0128..0130 ; NFD_QC; N # L& [9] LATIN CAPITAL LETTER I WITH TILDE..LATIN CAPITAL LETTER I WITH DOT ABOVE
+0134..0137 ; NFD_QC; N # L& [4] LATIN CAPITAL LETTER J WITH CIRCUMFLEX..LATIN SMALL LETTER K WITH CEDILLA
+0139..013E ; NFD_QC; N # L& [6] LATIN CAPITAL LETTER L WITH ACUTE..LATIN SMALL LETTER L WITH CARON
+0143..0148 ; NFD_QC; N # L& [6] LATIN CAPITAL LETTER N WITH ACUTE..LATIN SMALL LETTER N WITH CARON
+014C..0151 ; NFD_QC; N # L& [6] LATIN CAPITAL LETTER O WITH MACRON..LATIN SMALL LETTER O WITH DOUBLE ACUTE
+0154..0165 ; NFD_QC; N # L& [18] LATIN CAPITAL LETTER R WITH ACUTE..LATIN SMALL LETTER T WITH CARON
+0168..017E ; NFD_QC; N # L& [23] LATIN CAPITAL LETTER U WITH TILDE..LATIN SMALL LETTER Z WITH CARON
+01A0..01A1 ; NFD_QC; N # L& [2] LATIN CAPITAL LETTER O WITH HORN..LATIN SMALL LETTER O WITH HORN
+01AF..01B0 ; NFD_QC; N # L& [2] LATIN CAPITAL LETTER U WITH HORN..LATIN SMALL LETTER U WITH HORN
+01CD..01DC ; NFD_QC; N # L& [16] LATIN CAPITAL LETTER A WITH CARON..LATIN SMALL LETTER U WITH DIAERESIS AND GRAVE
+01DE..01E3 ; NFD_QC; N # L& [6] LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON..LATIN SMALL LETTER AE WITH MACRON
+01E6..01F0 ; NFD_QC; N # L& [11] LATIN CAPITAL LETTER G WITH CARON..LATIN SMALL LETTER J WITH CARON
+01F4..01F5 ; NFD_QC; N # L& [2] LATIN CAPITAL LETTER G WITH ACUTE..LATIN SMALL LETTER G WITH ACUTE
+01F8..021B ; NFD_QC; N # L& [36] LATIN CAPITAL LETTER N WITH GRAVE..LATIN SMALL LETTER T WITH COMMA BELOW
+021E..021F ; NFD_QC; N # L& [2] LATIN CAPITAL LETTER H WITH CARON..LATIN SMALL LETTER H WITH CARON
+0226..0233 ; NFD_QC; N # L& [14] LATIN CAPITAL LETTER A WITH DOT ABOVE..LATIN SMALL LETTER Y WITH MACRON
+0340..0341 ; NFD_QC; N # Mn [2] COMBINING GRAVE TONE MARK..COMBINING ACUTE TONE MARK
+0343..0344 ; NFD_QC; N # Mn [2] COMBINING GREEK KORONIS..COMBINING GREEK DIALYTIKA TONOS
+0374 ; NFD_QC; N # Sk GREEK NUMERAL SIGN
+037E ; NFD_QC; N # Po GREEK QUESTION MARK
+0385 ; NFD_QC; N # Sk GREEK DIALYTIKA TONOS
+0386 ; NFD_QC; N # L& GREEK CAPITAL LETTER ALPHA WITH TONOS
+0387 ; NFD_QC; N # Po GREEK ANO TELEIA
+0388..038A ; NFD_QC; N # L& [3] GREEK CAPITAL LETTER EPSILON WITH TONOS..GREEK CAPITAL LETTER IOTA WITH TONOS
+038C ; NFD_QC; N # L& GREEK CAPITAL LETTER OMICRON WITH TONOS
+038E..0390 ; NFD_QC; N # L& [3] GREEK CAPITAL LETTER UPSILON WITH TONOS..GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
+03AA..03B0 ; NFD_QC; N # L& [7] GREEK CAPITAL LETTER IOTA WITH DIALYTIKA..GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
+03CA..03CE ; NFD_QC; N # L& [5] GREEK SMALL LETTER IOTA WITH DIALYTIKA..GREEK SMALL LETTER OMEGA WITH TONOS
+03D3..03D4 ; NFD_QC; N # L& [2] GREEK UPSILON WITH ACUTE AND HOOK SYMBOL..GREEK UPSILON WITH DIAERESIS AND HOOK SYMBOL
+0400..0401 ; NFD_QC; N # L& [2] CYRILLIC CAPITAL LETTER IE WITH GRAVE..CYRILLIC CAPITAL LETTER IO
+0403 ; NFD_QC; N # L& CYRILLIC CAPITAL LETTER GJE
+0407 ; NFD_QC; N # L& CYRILLIC CAPITAL LETTER YI
+040C..040E ; NFD_QC; N # L& [3] CYRILLIC CAPITAL LETTER KJE..CYRILLIC CAPITAL LETTER SHORT U
+0419 ; NFD_QC; N # L& CYRILLIC CAPITAL LETTER SHORT I
+0439 ; NFD_QC; N # L& CYRILLIC SMALL LETTER SHORT I
+0450..0451 ; NFD_QC; N # L& [2] CYRILLIC SMALL LETTER IE WITH GRAVE..CYRILLIC SMALL LETTER IO
+0453 ; NFD_QC; N # L& CYRILLIC SMALL LETTER GJE
+0457 ; NFD_QC; N # L& CYRILLIC SMALL LETTER YI
+045C..045E ; NFD_QC; N # L& [3] CYRILLIC SMALL LETTER KJE..CYRILLIC SMALL LETTER SHORT U
+0476..0477 ; NFD_QC; N # L& [2] CYRILLIC CAPITAL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT..CYRILLIC SMALL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT
+04C1..04C2 ; NFD_QC; N # L& [2] CYRILLIC CAPITAL LETTER ZHE WITH BREVE..CYRILLIC SMALL LETTER ZHE WITH BREVE
+04D0..04D3 ; NFD_QC; N # L& [4] CYRILLIC CAPITAL LETTER A WITH BREVE..CYRILLIC SMALL LETTER A WITH DIAERESIS
+04D6..04D7 ; NFD_QC; N # L& [2] CYRILLIC CAPITAL LETTER IE WITH BREVE..CYRILLIC SMALL LETTER IE WITH BREVE
+04DA..04DF ; NFD_QC; N # L& [6] CYRILLIC CAPITAL LETTER SCHWA WITH DIAERESIS..CYRILLIC SMALL LETTER ZE WITH DIAERESIS
+04E2..04E7 ; NFD_QC; N # L& [6] CYRILLIC CAPITAL LETTER I WITH MACRON..CYRILLIC SMALL LETTER O WITH DIAERESIS
+04EA..04F5 ; NFD_QC; N # L& [12] CYRILLIC CAPITAL LETTER BARRED O WITH DIAERESIS..CYRILLIC SMALL LETTER CHE WITH DIAERESIS
+04F8..04F9 ; NFD_QC; N # L& [2] CYRILLIC CAPITAL LETTER YERU WITH DIAERESIS..CYRILLIC SMALL LETTER YERU WITH DIAERESIS
+0622..0626 ; NFD_QC; N # Lo [5] ARABIC LETTER ALEF WITH MADDA ABOVE..ARABIC LETTER YEH WITH HAMZA ABOVE
+06C0 ; NFD_QC; N # Lo ARABIC LETTER HEH WITH YEH ABOVE
+06C2 ; NFD_QC; N # Lo ARABIC LETTER HEH GOAL WITH HAMZA ABOVE
+06D3 ; NFD_QC; N # Lo ARABIC LETTER YEH BARREE WITH HAMZA ABOVE
+0929 ; NFD_QC; N # Lo DEVANAGARI LETTER NNNA
+0931 ; NFD_QC; N # Lo DEVANAGARI LETTER RRA
+0934 ; NFD_QC; N # Lo DEVANAGARI LETTER LLLA
+0958..095F ; NFD_QC; N # Lo [8] DEVANAGARI LETTER QA..DEVANAGARI LETTER YYA
+09CB..09CC ; NFD_QC; N # Mc [2] BENGALI VOWEL SIGN O..BENGALI VOWEL SIGN AU
+09DC..09DD ; NFD_QC; N # Lo [2] BENGALI LETTER RRA..BENGALI LETTER RHA
+09DF ; NFD_QC; N # Lo BENGALI LETTER YYA
+0A33 ; NFD_QC; N # Lo GURMUKHI LETTER LLA
+0A36 ; NFD_QC; N # Lo GURMUKHI LETTER SHA
+0A59..0A5B ; NFD_QC; N # Lo [3] GURMUKHI LETTER KHHA..GURMUKHI LETTER ZA
+0A5E ; NFD_QC; N # Lo GURMUKHI LETTER FA
+0B48 ; NFD_QC; N # Mc ORIYA VOWEL SIGN AI
+0B4B..0B4C ; NFD_QC; N # Mc [2] ORIYA VOWEL SIGN O..ORIYA VOWEL SIGN AU
+0B5C..0B5D ; NFD_QC; N # Lo [2] ORIYA LETTER RRA..ORIYA LETTER RHA
+0B94 ; NFD_QC; N # Lo TAMIL LETTER AU
+0BCA..0BCC ; NFD_QC; N # Mc [3] TAMIL VOWEL SIGN O..TAMIL VOWEL SIGN AU
+0C48 ; NFD_QC; N # Mn TELUGU VOWEL SIGN AI
+0CC0 ; NFD_QC; N # Mc KANNADA VOWEL SIGN II
+0CC7..0CC8 ; NFD_QC; N # Mc [2] KANNADA VOWEL SIGN EE..KANNADA VOWEL SIGN AI
+0CCA..0CCB ; NFD_QC; N # Mc [2] KANNADA VOWEL SIGN O..KANNADA VOWEL SIGN OO
+0D4A..0D4C ; NFD_QC; N # Mc [3] MALAYALAM VOWEL SIGN O..MALAYALAM VOWEL SIGN AU
+0DDA ; NFD_QC; N # Mc SINHALA VOWEL SIGN DIGA KOMBUVA
+0DDC..0DDE ; NFD_QC; N # Mc [3] SINHALA VOWEL SIGN KOMBUVA HAA AELA-PILLA..SINHALA VOWEL SIGN KOMBUVA HAA GAYANUKITTA
+0F43 ; NFD_QC; N # Lo TIBETAN LETTER GHA
+0F4D ; NFD_QC; N # Lo TIBETAN LETTER DDHA
+0F52 ; NFD_QC; N # Lo TIBETAN LETTER DHA
+0F57 ; NFD_QC; N # Lo TIBETAN LETTER BHA
+0F5C ; NFD_QC; N # Lo TIBETAN LETTER DZHA
+0F69 ; NFD_QC; N # Lo TIBETAN LETTER KSSA
+0F73 ; NFD_QC; N # Mn TIBETAN VOWEL SIGN II
+0F75..0F76 ; NFD_QC; N # Mn [2] TIBETAN VOWEL SIGN UU..TIBETAN VOWEL SIGN VOCALIC R
+0F78 ; NFD_QC; N # Mn TIBETAN VOWEL SIGN VOCALIC L
+0F81 ; NFD_QC; N # Mn TIBETAN VOWEL SIGN REVERSED II
+0F93 ; NFD_QC; N # Mn TIBETAN SUBJOINED LETTER GHA
+0F9D ; NFD_QC; N # Mn TIBETAN SUBJOINED LETTER DDHA
+0FA2 ; NFD_QC; N # Mn TIBETAN SUBJOINED LETTER DHA
+0FA7 ; NFD_QC; N # Mn TIBETAN SUBJOINED LETTER BHA
+0FAC ; NFD_QC; N # Mn TIBETAN SUBJOINED LETTER DZHA
+0FB9 ; NFD_QC; N # Mn TIBETAN SUBJOINED LETTER KSSA
+1026 ; NFD_QC; N # Lo MYANMAR LETTER UU
+1E00..1E99 ; NFD_QC; N # L& [154] LATIN CAPITAL LETTER A WITH RING BELOW..LATIN SMALL LETTER Y WITH RING ABOVE
+1E9B ; NFD_QC; N # L& LATIN SMALL LETTER LONG S WITH DOT ABOVE
+1EA0..1EF9 ; NFD_QC; N # L& [90] LATIN CAPITAL LETTER A WITH DOT BELOW..LATIN SMALL LETTER Y WITH TILDE
+1F00..1F15 ; NFD_QC; N # L& [22] GREEK SMALL LETTER ALPHA WITH PSILI..GREEK SMALL LETTER EPSILON WITH DASIA AND OXIA
+1F18..1F1D ; NFD_QC; N # L& [6] GREEK CAPITAL LETTER EPSILON WITH PSILI..GREEK CAPITAL LETTER EPSILON WITH DASIA AND OXIA
+1F20..1F45 ; NFD_QC; N # L& [38] GREEK SMALL LETTER ETA WITH PSILI..GREEK SMALL LETTER OMICRON WITH DASIA AND OXIA
+1F48..1F4D ; NFD_QC; N # L& [6] GREEK CAPITAL LETTER OMICRON WITH PSILI..GREEK CAPITAL LETTER OMICRON WITH DASIA AND OXIA
+1F50..1F57 ; NFD_QC; N # L& [8] GREEK SMALL LETTER UPSILON WITH PSILI..GREEK SMALL LETTER UPSILON WITH DASIA AND PERISPOMENI
+1F59 ; NFD_QC; N # L& GREEK CAPITAL LETTER UPSILON WITH DASIA
+1F5B ; NFD_QC; N # L& GREEK CAPITAL LETTER UPSILON WITH DASIA AND VARIA
+1F5D ; NFD_QC; N # L& GREEK CAPITAL LETTER UPSILON WITH DASIA AND OXIA
+1F5F..1F7D ; NFD_QC; N # L& [31] GREEK CAPITAL LETTER UPSILON WITH DASIA AND PERISPOMENI..GREEK SMALL LETTER OMEGA WITH OXIA
+1F80..1FB4 ; NFD_QC; N # L& [53] GREEK SMALL LETTER ALPHA WITH PSILI AND YPOGEGRAMMENI..GREEK SMALL LETTER ALPHA WITH OXIA AND YPOGEGRAMMENI
+1FB6..1FBC ; NFD_QC; N # L& [7] GREEK SMALL LETTER ALPHA WITH PERISPOMENI..GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI
+1FBE ; NFD_QC; N # L& GREEK PROSGEGRAMMENI
+1FC1 ; NFD_QC; N # Sk GREEK DIALYTIKA AND PERISPOMENI
+1FC2..1FC4 ; NFD_QC; N # L& [3] GREEK SMALL LETTER ETA WITH VARIA AND YPOGEGRAMMENI..GREEK SMALL LETTER ETA WITH OXIA AND YPOGEGRAMMENI
+1FC6..1FCC ; NFD_QC; N # L& [7] GREEK SMALL LETTER ETA WITH PERISPOMENI..GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI
+1FCD..1FCF ; NFD_QC; N # Sk [3] GREEK PSILI AND VARIA..GREEK PSILI AND PERISPOMENI
+1FD0..1FD3 ; NFD_QC; N # L& [4] GREEK SMALL LETTER IOTA WITH VRACHY..GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA
+1FD6..1FDB ; NFD_QC; N # L& [6] GREEK SMALL LETTER IOTA WITH PERISPOMENI..GREEK CAPITAL LETTER IOTA WITH OXIA
+1FDD..1FDF ; NFD_QC; N # Sk [3] GREEK DASIA AND VARIA..GREEK DASIA AND PERISPOMENI
+1FE0..1FEC ; NFD_QC; N # L& [13] GREEK SMALL LETTER UPSILON WITH VRACHY..GREEK CAPITAL LETTER RHO WITH DASIA
+1FED..1FEF ; NFD_QC; N # Sk [3] GREEK DIALYTIKA AND VARIA..GREEK VARIA
+1FF2..1FF4 ; NFD_QC; N # L& [3] GREEK SMALL LETTER OMEGA WITH VARIA AND YPOGEGRAMMENI..GREEK SMALL LETTER OMEGA WITH OXIA AND YPOGEGRAMMENI
+1FF6..1FFC ; NFD_QC; N # L& [7] GREEK SMALL LETTER OMEGA WITH PERISPOMENI..GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI
+1FFD ; NFD_QC; N # Sk GREEK OXIA
+2000..2001 ; NFD_QC; N # Zs [2] EN QUAD..EM QUAD
+2126 ; NFD_QC; N # L& OHM SIGN
+212A..212B ; NFD_QC; N # L& [2] KELVIN SIGN..ANGSTROM SIGN
+219A..219B ; NFD_QC; N # Sm [2] LEFTWARDS ARROW WITH STROKE..RIGHTWARDS ARROW WITH STROKE
+21AE ; NFD_QC; N # Sm LEFT RIGHT ARROW WITH STROKE
+21CD ; NFD_QC; N # So LEFTWARDS DOUBLE ARROW WITH STROKE
+21CE..21CF ; NFD_QC; N # Sm [2] LEFT RIGHT DOUBLE ARROW WITH STROKE..RIGHTWARDS DOUBLE ARROW WITH STROKE
+2204 ; NFD_QC; N # Sm THERE DOES NOT EXIST
+2209 ; NFD_QC; N # Sm NOT AN ELEMENT OF
+220C ; NFD_QC; N # Sm DOES NOT CONTAIN AS MEMBER
+2224 ; NFD_QC; N # Sm DOES NOT DIVIDE
+2226 ; NFD_QC; N # Sm NOT PARALLEL TO
+2241 ; NFD_QC; N # Sm NOT TILDE
+2244 ; NFD_QC; N # Sm NOT ASYMPTOTICALLY EQUAL TO
+2247 ; NFD_QC; N # Sm NEITHER APPROXIMATELY NOR ACTUALLY EQUAL TO
+2249 ; NFD_QC; N # Sm NOT ALMOST EQUAL TO
+2260 ; NFD_QC; N # Sm NOT EQUAL TO
+2262 ; NFD_QC; N # Sm NOT IDENTICAL TO
+226D..2271 ; NFD_QC; N # Sm [5] NOT EQUIVALENT TO..NEITHER GREATER-THAN NOR EQUAL TO
+2274..2275 ; NFD_QC; N # Sm [2] NEITHER LESS-THAN NOR EQUIVALENT TO..NEITHER GREATER-THAN NOR EQUIVALENT TO
+2278..2279 ; NFD_QC; N # Sm [2] NEITHER LESS-THAN NOR GREATER-THAN..NEITHER GREATER-THAN NOR LESS-THAN
+2280..2281 ; NFD_QC; N # Sm [2] DOES NOT PRECEDE..DOES NOT SUCCEED
+2284..2285 ; NFD_QC; N # Sm [2] NOT A SUBSET OF..NOT A SUPERSET OF
+2288..2289 ; NFD_QC; N # Sm [2] NEITHER A SUBSET OF NOR EQUAL TO..NEITHER A SUPERSET OF NOR EQUAL TO
+22AC..22AF ; NFD_QC; N # Sm [4] DOES NOT PROVE..NEGATED DOUBLE VERTICAL BAR DOUBLE RIGHT TURNSTILE
+22E0..22E3 ; NFD_QC; N # Sm [4] DOES NOT PRECEDE OR EQUAL..NOT SQUARE ORIGINAL OF OR EQUAL TO
+22EA..22ED ; NFD_QC; N # Sm [4] NOT NORMAL SUBGROUP OF..DOES NOT CONTAIN AS NORMAL SUBGROUP OR EQUAL
+2329 ; NFD_QC; N # Ps LEFT-POINTING ANGLE BRACKET
+232A ; NFD_QC; N # Pe RIGHT-POINTING ANGLE BRACKET
+2ADC ; NFD_QC; N # Sm FORKING
+304C ; NFD_QC; N # Lo HIRAGANA LETTER GA
+304E ; NFD_QC; N # Lo HIRAGANA LETTER GI
+3050 ; NFD_QC; N # Lo HIRAGANA LETTER GU
+3052 ; NFD_QC; N # Lo HIRAGANA LETTER GE
+3054 ; NFD_QC; N # Lo HIRAGANA LETTER GO
+3056 ; NFD_QC; N # Lo HIRAGANA LETTER ZA
+3058 ; NFD_QC; N # Lo HIRAGANA LETTER ZI
+305A ; NFD_QC; N # Lo HIRAGANA LETTER ZU
+305C ; NFD_QC; N # Lo HIRAGANA LETTER ZE
+305E ; NFD_QC; N # Lo HIRAGANA LETTER ZO
+3060 ; NFD_QC; N # Lo HIRAGANA LETTER DA
+3062 ; NFD_QC; N # Lo HIRAGANA LETTER DI
+3065 ; NFD_QC; N # Lo HIRAGANA LETTER DU
+3067 ; NFD_QC; N # Lo HIRAGANA LETTER DE
+3069 ; NFD_QC; N # Lo HIRAGANA LETTER DO
+3070..3071 ; NFD_QC; N # Lo [2] HIRAGANA LETTER BA..HIRAGANA LETTER PA
+3073..3074 ; NFD_QC; N # Lo [2] HIRAGANA LETTER BI..HIRAGANA LETTER PI
+3076..3077 ; NFD_QC; N # Lo [2] HIRAGANA LETTER BU..HIRAGANA LETTER PU
+3079..307A ; NFD_QC; N # Lo [2] HIRAGANA LETTER BE..HIRAGANA LETTER PE
+307C..307D ; NFD_QC; N # Lo [2] HIRAGANA LETTER BO..HIRAGANA LETTER PO
+3094 ; NFD_QC; N # Lo HIRAGANA LETTER VU
+309E ; NFD_QC; N # Lm HIRAGANA VOICED ITERATION MARK
+30AC ; NFD_QC; N # Lo KATAKANA LETTER GA
+30AE ; NFD_QC; N # Lo KATAKANA LETTER GI
+30B0 ; NFD_QC; N # Lo KATAKANA LETTER GU
+30B2 ; NFD_QC; N # Lo KATAKANA LETTER GE
+30B4 ; NFD_QC; N # Lo KATAKANA LETTER GO
+30B6 ; NFD_QC; N # Lo KATAKANA LETTER ZA
+30B8 ; NFD_QC; N # Lo KATAKANA LETTER ZI
+30BA ; NFD_QC; N # Lo KATAKANA LETTER ZU
+30BC ; NFD_QC; N # Lo KATAKANA LETTER ZE
+30BE ; NFD_QC; N # Lo KATAKANA LETTER ZO
+30C0 ; NFD_QC; N # Lo KATAKANA LETTER DA
+30C2 ; NFD_QC; N # Lo KATAKANA LETTER DI
+30C5 ; NFD_QC; N # Lo KATAKANA LETTER DU
+30C7 ; NFD_QC; N # Lo KATAKANA LETTER DE
+30C9 ; NFD_QC; N # Lo KATAKANA LETTER DO
+30D0..30D1 ; NFD_QC; N # Lo [2] KATAKANA LETTER BA..KATAKANA LETTER PA
+30D3..30D4 ; NFD_QC; N # Lo [2] KATAKANA LETTER BI..KATAKANA LETTER PI
+30D6..30D7 ; NFD_QC; N # Lo [2] KATAKANA LETTER BU..KATAKANA LETTER PU
+30D9..30DA ; NFD_QC; N # Lo [2] KATAKANA LETTER BE..KATAKANA LETTER PE
+30DC..30DD ; NFD_QC; N # Lo [2] KATAKANA LETTER BO..KATAKANA LETTER PO
+30F4 ; NFD_QC; N # Lo KATAKANA LETTER VU
+30F7..30FA ; NFD_QC; N # Lo [4] KATAKANA LETTER VA..KATAKANA LETTER VO
+30FE ; NFD_QC; N # Lm KATAKANA VOICED ITERATION MARK
+AC00..D7A3 ; NFD_QC; N # Lo [11172] HANGUL SYLLABLE GA..HANGUL SYLLABLE HIH
+F900..FA0D ; NFD_QC; N # Lo [270] CJK COMPATIBILITY IDEOGRAPH-F900..CJK COMPATIBILITY IDEOGRAPH-FA0D
+FA10 ; NFD_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA10
+FA12 ; NFD_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA12
+FA15..FA1E ; NFD_QC; N # Lo [10] CJK COMPATIBILITY IDEOGRAPH-FA15..CJK COMPATIBILITY IDEOGRAPH-FA1E
+FA20 ; NFD_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA20
+FA22 ; NFD_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA22
+FA25..FA26 ; NFD_QC; N # Lo [2] CJK COMPATIBILITY IDEOGRAPH-FA25..CJK COMPATIBILITY IDEOGRAPH-FA26
+FA2A..FA2D ; NFD_QC; N # Lo [4] CJK COMPATIBILITY IDEOGRAPH-FA2A..CJK COMPATIBILITY IDEOGRAPH-FA2D
+FA30..FA6A ; NFD_QC; N # Lo [59] CJK COMPATIBILITY IDEOGRAPH-FA30..CJK COMPATIBILITY IDEOGRAPH-FA6A
+FB1D ; NFD_QC; N # Lo HEBREW LETTER YOD WITH HIRIQ
+FB1F ; NFD_QC; N # Lo HEBREW LIGATURE YIDDISH YOD YOD PATAH
+FB2A..FB36 ; NFD_QC; N # Lo [13] HEBREW LETTER SHIN WITH SHIN DOT..HEBREW LETTER ZAYIN WITH DAGESH
+FB38..FB3C ; NFD_QC; N # Lo [5] HEBREW LETTER TET WITH DAGESH..HEBREW LETTER LAMED WITH DAGESH
+FB3E ; NFD_QC; N # Lo HEBREW LETTER MEM WITH DAGESH
+FB40..FB41 ; NFD_QC; N # Lo [2] HEBREW LETTER NUN WITH DAGESH..HEBREW LETTER SAMEKH WITH DAGESH
+FB43..FB44 ; NFD_QC; N # Lo [2] HEBREW LETTER FINAL PE WITH DAGESH..HEBREW LETTER PE WITH DAGESH
+FB46..FB4E ; NFD_QC; N # Lo [9] HEBREW LETTER TSADI WITH DAGESH..HEBREW LETTER PE WITH RAFE
+1D15E..1D164 ; NFD_QC; N # So [7] MUSICAL SYMBOL HALF NOTE..MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH NOTE
+1D1BB..1D1C0 ; NFD_QC; N # So [6] MUSICAL SYMBOL MINIMA..MUSICAL SYMBOL FUSA BLACK
+2F800..2FA1D ; NFD_QC; N # Lo [542] CJK COMPATIBILITY IDEOGRAPH-2F800..CJK COMPATIBILITY IDEOGRAPH-2FA1D
+
+# Total code points: 13098
+
+# ================================================
+
+# Property: NFC_Quick_Check
+
+# All code points not explicitly listed for NFC_Quick_Check
+# have the value Yes (Y).
+
+# ================================================
+
+# NFC_Quick_Check=No
+
+0340..0341 ; NFC_QC; N # Mn [2] COMBINING GRAVE TONE MARK..COMBINING ACUTE TONE MARK
+0343..0344 ; NFC_QC; N # Mn [2] COMBINING GREEK KORONIS..COMBINING GREEK DIALYTIKA TONOS
+0374 ; NFC_QC; N # Sk GREEK NUMERAL SIGN
+037E ; NFC_QC; N # Po GREEK QUESTION MARK
+0387 ; NFC_QC; N # Po GREEK ANO TELEIA
+0958..095F ; NFC_QC; N # Lo [8] DEVANAGARI LETTER QA..DEVANAGARI LETTER YYA
+09DC..09DD ; NFC_QC; N # Lo [2] BENGALI LETTER RRA..BENGALI LETTER RHA
+09DF ; NFC_QC; N # Lo BENGALI LETTER YYA
+0A33 ; NFC_QC; N # Lo GURMUKHI LETTER LLA
+0A36 ; NFC_QC; N # Lo GURMUKHI LETTER SHA
+0A59..0A5B ; NFC_QC; N # Lo [3] GURMUKHI LETTER KHHA..GURMUKHI LETTER ZA
+0A5E ; NFC_QC; N # Lo GURMUKHI LETTER FA
+0B5C..0B5D ; NFC_QC; N # Lo [2] ORIYA LETTER RRA..ORIYA LETTER RHA
+0F43 ; NFC_QC; N # Lo TIBETAN LETTER GHA
+0F4D ; NFC_QC; N # Lo TIBETAN LETTER DDHA
+0F52 ; NFC_QC; N # Lo TIBETAN LETTER DHA
+0F57 ; NFC_QC; N # Lo TIBETAN LETTER BHA
+0F5C ; NFC_QC; N # Lo TIBETAN LETTER DZHA
+0F69 ; NFC_QC; N # Lo TIBETAN LETTER KSSA
+0F73 ; NFC_QC; N # Mn TIBETAN VOWEL SIGN II
+0F75..0F76 ; NFC_QC; N # Mn [2] TIBETAN VOWEL SIGN UU..TIBETAN VOWEL SIGN VOCALIC R
+0F78 ; NFC_QC; N # Mn TIBETAN VOWEL SIGN VOCALIC L
+0F81 ; NFC_QC; N # Mn TIBETAN VOWEL SIGN REVERSED II
+0F93 ; NFC_QC; N # Mn TIBETAN SUBJOINED LETTER GHA
+0F9D ; NFC_QC; N # Mn TIBETAN SUBJOINED LETTER DDHA
+0FA2 ; NFC_QC; N # Mn TIBETAN SUBJOINED LETTER DHA
+0FA7 ; NFC_QC; N # Mn TIBETAN SUBJOINED LETTER BHA
+0FAC ; NFC_QC; N # Mn TIBETAN SUBJOINED LETTER DZHA
+0FB9 ; NFC_QC; N # Mn TIBETAN SUBJOINED LETTER KSSA
+1F71 ; NFC_QC; N # L& GREEK SMALL LETTER ALPHA WITH OXIA
+1F73 ; NFC_QC; N # L& GREEK SMALL LETTER EPSILON WITH OXIA
+1F75 ; NFC_QC; N # L& GREEK SMALL LETTER ETA WITH OXIA
+1F77 ; NFC_QC; N # L& GREEK SMALL LETTER IOTA WITH OXIA
+1F79 ; NFC_QC; N # L& GREEK SMALL LETTER OMICRON WITH OXIA
+1F7B ; NFC_QC; N # L& GREEK SMALL LETTER UPSILON WITH OXIA
+1F7D ; NFC_QC; N # L& GREEK SMALL LETTER OMEGA WITH OXIA
+1FBB ; NFC_QC; N # L& GREEK CAPITAL LETTER ALPHA WITH OXIA
+1FBE ; NFC_QC; N # L& GREEK PROSGEGRAMMENI
+1FC9 ; NFC_QC; N # L& GREEK CAPITAL LETTER EPSILON WITH OXIA
+1FCB ; NFC_QC; N # L& GREEK CAPITAL LETTER ETA WITH OXIA
+1FD3 ; NFC_QC; N # L& GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA
+1FDB ; NFC_QC; N # L& GREEK CAPITAL LETTER IOTA WITH OXIA
+1FE3 ; NFC_QC; N # L& GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA
+1FEB ; NFC_QC; N # L& GREEK CAPITAL LETTER UPSILON WITH OXIA
+1FEE..1FEF ; NFC_QC; N # Sk [2] GREEK DIALYTIKA AND OXIA..GREEK VARIA
+1FF9 ; NFC_QC; N # L& GREEK CAPITAL LETTER OMICRON WITH OXIA
+1FFB ; NFC_QC; N # L& GREEK CAPITAL LETTER OMEGA WITH OXIA
+1FFD ; NFC_QC; N # Sk GREEK OXIA
+2000..2001 ; NFC_QC; N # Zs [2] EN QUAD..EM QUAD
+2126 ; NFC_QC; N # L& OHM SIGN
+212A..212B ; NFC_QC; N # L& [2] KELVIN SIGN..ANGSTROM SIGN
+2329 ; NFC_QC; N # Ps LEFT-POINTING ANGLE BRACKET
+232A ; NFC_QC; N # Pe RIGHT-POINTING ANGLE BRACKET
+2ADC ; NFC_QC; N # Sm FORKING
+F900..FA0D ; NFC_QC; N # Lo [270] CJK COMPATIBILITY IDEOGRAPH-F900..CJK COMPATIBILITY IDEOGRAPH-FA0D
+FA10 ; NFC_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA10
+FA12 ; NFC_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA12
+FA15..FA1E ; NFC_QC; N # Lo [10] CJK COMPATIBILITY IDEOGRAPH-FA15..CJK COMPATIBILITY IDEOGRAPH-FA1E
+FA20 ; NFC_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA20
+FA22 ; NFC_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA22
+FA25..FA26 ; NFC_QC; N # Lo [2] CJK COMPATIBILITY IDEOGRAPH-FA25..CJK COMPATIBILITY IDEOGRAPH-FA26
+FA2A..FA2D ; NFC_QC; N # Lo [4] CJK COMPATIBILITY IDEOGRAPH-FA2A..CJK COMPATIBILITY IDEOGRAPH-FA2D
+FA30..FA6A ; NFC_QC; N # Lo [59] CJK COMPATIBILITY IDEOGRAPH-FA30..CJK COMPATIBILITY IDEOGRAPH-FA6A
+FB1D ; NFC_QC; N # Lo HEBREW LETTER YOD WITH HIRIQ
+FB1F ; NFC_QC; N # Lo HEBREW LIGATURE YIDDISH YOD YOD PATAH
+FB2A..FB36 ; NFC_QC; N # Lo [13] HEBREW LETTER SHIN WITH SHIN DOT..HEBREW LETTER ZAYIN WITH DAGESH
+FB38..FB3C ; NFC_QC; N # Lo [5] HEBREW LETTER TET WITH DAGESH..HEBREW LETTER LAMED WITH DAGESH
+FB3E ; NFC_QC; N # Lo HEBREW LETTER MEM WITH DAGESH
+FB40..FB41 ; NFC_QC; N # Lo [2] HEBREW LETTER NUN WITH DAGESH..HEBREW LETTER SAMEKH WITH DAGESH
+FB43..FB44 ; NFC_QC; N # Lo [2] HEBREW LETTER FINAL PE WITH DAGESH..HEBREW LETTER PE WITH DAGESH
+FB46..FB4E ; NFC_QC; N # Lo [9] HEBREW LETTER TSADI WITH DAGESH..HEBREW LETTER PE WITH RAFE
+1D15E..1D164 ; NFC_QC; N # So [7] MUSICAL SYMBOL HALF NOTE..MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH NOTE
+1D1BB..1D1C0 ; NFC_QC; N # So [6] MUSICAL SYMBOL MINIMA..MUSICAL SYMBOL FUSA BLACK
+2F800..2FA1D ; NFC_QC; N # Lo [542] CJK COMPATIBILITY IDEOGRAPH-2F800..CJK COMPATIBILITY IDEOGRAPH-2FA1D
+
+# Total code points: 1009
+
+# ================================================
+
+# NFC_Quick_Check=Maybe
+
+0300..0304 ; NFC_QC; M # Mn [5] COMBINING GRAVE ACCENT..COMBINING MACRON
+0306..030C ; NFC_QC; M # Mn [7] COMBINING BREVE..COMBINING CARON
+030F ; NFC_QC; M # Mn COMBINING DOUBLE GRAVE ACCENT
+0311 ; NFC_QC; M # Mn COMBINING INVERTED BREVE
+0313..0314 ; NFC_QC; M # Mn [2] COMBINING COMMA ABOVE..COMBINING REVERSED COMMA ABOVE
+031B ; NFC_QC; M # Mn COMBINING HORN
+0323..0328 ; NFC_QC; M # Mn [6] COMBINING DOT BELOW..COMBINING OGONEK
+032D..032E ; NFC_QC; M # Mn [2] COMBINING CIRCUMFLEX ACCENT BELOW..COMBINING BREVE BELOW
+0330..0331 ; NFC_QC; M # Mn [2] COMBINING TILDE BELOW..COMBINING MACRON BELOW
+0338 ; NFC_QC; M # Mn COMBINING LONG SOLIDUS OVERLAY
+0342 ; NFC_QC; M # Mn COMBINING GREEK PERISPOMENI
+0345 ; NFC_QC; M # Mn COMBINING GREEK YPOGEGRAMMENI
+0653..0655 ; NFC_QC; M # Mn [3] ARABIC MADDAH ABOVE..ARABIC HAMZA BELOW
+093C ; NFC_QC; M # Mn DEVANAGARI SIGN NUKTA
+09BE ; NFC_QC; M # Mc BENGALI VOWEL SIGN AA
+09D7 ; NFC_QC; M # Mc BENGALI AU LENGTH MARK
+0B3E ; NFC_QC; M # Mc ORIYA VOWEL SIGN AA
+0B56 ; NFC_QC; M # Mn ORIYA AI LENGTH MARK
+0B57 ; NFC_QC; M # Mc ORIYA AU LENGTH MARK
+0BBE ; NFC_QC; M # Mc TAMIL VOWEL SIGN AA
+0BD7 ; NFC_QC; M # Mc TAMIL AU LENGTH MARK
+0C56 ; NFC_QC; M # Mn TELUGU AI LENGTH MARK
+0CC2 ; NFC_QC; M # Mc KANNADA VOWEL SIGN UU
+0CD5..0CD6 ; NFC_QC; M # Mc [2] KANNADA LENGTH MARK..KANNADA AI LENGTH MARK
+0D3E ; NFC_QC; M # Mc MALAYALAM VOWEL SIGN AA
+0D57 ; NFC_QC; M # Mc MALAYALAM AU LENGTH MARK
+0DCA ; NFC_QC; M # Mn SINHALA SIGN AL-LAKUNA
+0DCF ; NFC_QC; M # Mc SINHALA VOWEL SIGN AELA-PILLA
+0DDF ; NFC_QC; M # Mc SINHALA VOWEL SIGN GAYANUKITTA
+102E ; NFC_QC; M # Mn MYANMAR VOWEL SIGN II
+1161..1175 ; NFC_QC; M # Lo [21] HANGUL JUNGSEONG A..HANGUL JUNGSEONG I
+11A8..11C2 ; NFC_QC; M # Lo [27] HANGUL JONGSEONG KIYEOK..HANGUL JONGSEONG HIEUH
+3099..309A ; NFC_QC; M # Mn [2] COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK..COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
+
+# Total code points: 101
+
+# ================================================
+
+# Property: NFKD_Quick_Check
+
+# All code points not explicitly listed for NFKD_Quick_Check
+# have the value Yes (Y).
+
+# ================================================
+
+# NFKD_Quick_Check=No
+
+00A0 ; NFKD_QC; N # Zs NO-BREAK SPACE
+00A8 ; NFKD_QC; N # Sk DIAERESIS
+00AA ; NFKD_QC; N # L& FEMININE ORDINAL INDICATOR
+00AF ; NFKD_QC; N # Sk MACRON
+00B2..00B3 ; NFKD_QC; N # No [2] SUPERSCRIPT TWO..SUPERSCRIPT THREE
+00B4 ; NFKD_QC; N # Sk ACUTE ACCENT
+00B5 ; NFKD_QC; N # L& MICRO SIGN
+00B8 ; NFKD_QC; N # Sk CEDILLA
+00B9 ; NFKD_QC; N # No SUPERSCRIPT ONE
+00BA ; NFKD_QC; N # L& MASCULINE ORDINAL INDICATOR
+00BC..00BE ; NFKD_QC; N # No [3] VULGAR FRACTION ONE QUARTER..VULGAR FRACTION THREE QUARTERS
+00C0..00C5 ; NFKD_QC; N # L& [6] LATIN CAPITAL LETTER A WITH GRAVE..LATIN CAPITAL LETTER A WITH RING ABOVE
+00C7..00CF ; NFKD_QC; N # L& [9] LATIN CAPITAL LETTER C WITH CEDILLA..LATIN CAPITAL LETTER I WITH DIAERESIS
+00D1..00D6 ; NFKD_QC; N # L& [6] LATIN CAPITAL LETTER N WITH TILDE..LATIN CAPITAL LETTER O WITH DIAERESIS
+00D9..00DD ; NFKD_QC; N # L& [5] LATIN CAPITAL LETTER U WITH GRAVE..LATIN CAPITAL LETTER Y WITH ACUTE
+00E0..00E5 ; NFKD_QC; N # L& [6] LATIN SMALL LETTER A WITH GRAVE..LATIN SMALL LETTER A WITH RING ABOVE
+00E7..00EF ; NFKD_QC; N # L& [9] LATIN SMALL LETTER C WITH CEDILLA..LATIN SMALL LETTER I WITH DIAERESIS
+00F1..00F6 ; NFKD_QC; N # L& [6] LATIN SMALL LETTER N WITH TILDE..LATIN SMALL LETTER O WITH DIAERESIS
+00F9..00FD ; NFKD_QC; N # L& [5] LATIN SMALL LETTER U WITH GRAVE..LATIN SMALL LETTER Y WITH ACUTE
+00FF..010F ; NFKD_QC; N # L& [17] LATIN SMALL LETTER Y WITH DIAERESIS..LATIN SMALL LETTER D WITH CARON
+0112..0125 ; NFKD_QC; N # L& [20] LATIN CAPITAL LETTER E WITH MACRON..LATIN SMALL LETTER H WITH CIRCUMFLEX
+0128..0130 ; NFKD_QC; N # L& [9] LATIN CAPITAL LETTER I WITH TILDE..LATIN CAPITAL LETTER I WITH DOT ABOVE
+0132..0137 ; NFKD_QC; N # L& [6] LATIN CAPITAL LIGATURE IJ..LATIN SMALL LETTER K WITH CEDILLA
+0139..0140 ; NFKD_QC; N # L& [8] LATIN CAPITAL LETTER L WITH ACUTE..LATIN SMALL LETTER L WITH MIDDLE DOT
+0143..0149 ; NFKD_QC; N # L& [7] LATIN CAPITAL LETTER N WITH ACUTE..LATIN SMALL LETTER N PRECEDED BY APOSTROPHE
+014C..0151 ; NFKD_QC; N # L& [6] LATIN CAPITAL LETTER O WITH MACRON..LATIN SMALL LETTER O WITH DOUBLE ACUTE
+0154..0165 ; NFKD_QC; N # L& [18] LATIN CAPITAL LETTER R WITH ACUTE..LATIN SMALL LETTER T WITH CARON
+0168..017F ; NFKD_QC; N # L& [24] LATIN CAPITAL LETTER U WITH TILDE..LATIN SMALL LETTER LONG S
+01A0..01A1 ; NFKD_QC; N # L& [2] LATIN CAPITAL LETTER O WITH HORN..LATIN SMALL LETTER O WITH HORN
+01AF..01B0 ; NFKD_QC; N # L& [2] LATIN CAPITAL LETTER U WITH HORN..LATIN SMALL LETTER U WITH HORN
+01C4..01DC ; NFKD_QC; N # L& [25] LATIN CAPITAL LETTER DZ WITH CARON..LATIN SMALL LETTER U WITH DIAERESIS AND GRAVE
+01DE..01E3 ; NFKD_QC; N # L& [6] LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON..LATIN SMALL LETTER AE WITH MACRON
+01E6..01F5 ; NFKD_QC; N # L& [16] LATIN CAPITAL LETTER G WITH CARON..LATIN SMALL LETTER G WITH ACUTE
+01F8..021B ; NFKD_QC; N # L& [36] LATIN CAPITAL LETTER N WITH GRAVE..LATIN SMALL LETTER T WITH COMMA BELOW
+021E..021F ; NFKD_QC; N # L& [2] LATIN CAPITAL LETTER H WITH CARON..LATIN SMALL LETTER H WITH CARON
+0226..0233 ; NFKD_QC; N # L& [14] LATIN CAPITAL LETTER A WITH DOT ABOVE..LATIN SMALL LETTER Y WITH MACRON
+02B0..02B8 ; NFKD_QC; N # Lm [9] MODIFIER LETTER SMALL H..MODIFIER LETTER SMALL Y
+02D8..02DD ; NFKD_QC; N # Sk [6] BREVE..DOUBLE ACUTE ACCENT
+02E0..02E4 ; NFKD_QC; N # Lm [5] MODIFIER LETTER SMALL GAMMA..MODIFIER LETTER SMALL REVERSED GLOTTAL STOP
+0340..0341 ; NFKD_QC; N # Mn [2] COMBINING GRAVE TONE MARK..COMBINING ACUTE TONE MARK
+0343..0344 ; NFKD_QC; N # Mn [2] COMBINING GREEK KORONIS..COMBINING GREEK DIALYTIKA TONOS
+0374 ; NFKD_QC; N # Sk GREEK NUMERAL SIGN
+037A ; NFKD_QC; N # Lm GREEK YPOGEGRAMMENI
+037E ; NFKD_QC; N # Po GREEK QUESTION MARK
+0384..0385 ; NFKD_QC; N # Sk [2] GREEK TONOS..GREEK DIALYTIKA TONOS
+0386 ; NFKD_QC; N # L& GREEK CAPITAL LETTER ALPHA WITH TONOS
+0387 ; NFKD_QC; N # Po GREEK ANO TELEIA
+0388..038A ; NFKD_QC; N # L& [3] GREEK CAPITAL LETTER EPSILON WITH TONOS..GREEK CAPITAL LETTER IOTA WITH TONOS
+038C ; NFKD_QC; N # L& GREEK CAPITAL LETTER OMICRON WITH TONOS
+038E..0390 ; NFKD_QC; N # L& [3] GREEK CAPITAL LETTER UPSILON WITH TONOS..GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
+03AA..03B0 ; NFKD_QC; N # L& [7] GREEK CAPITAL LETTER IOTA WITH DIALYTIKA..GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
+03CA..03CE ; NFKD_QC; N # L& [5] GREEK SMALL LETTER IOTA WITH DIALYTIKA..GREEK SMALL LETTER OMEGA WITH TONOS
+03D0..03D6 ; NFKD_QC; N # L& [7] GREEK BETA SYMBOL..GREEK PI SYMBOL
+03F0..03F2 ; NFKD_QC; N # L& [3] GREEK KAPPA SYMBOL..GREEK LUNATE SIGMA SYMBOL
+03F4..03F5 ; NFKD_QC; N # L& [2] GREEK CAPITAL THETA SYMBOL..GREEK LUNATE EPSILON SYMBOL
+03F9 ; NFKD_QC; N # L& GREEK CAPITAL LUNATE SIGMA SYMBOL
+0400..0401 ; NFKD_QC; N # L& [2] CYRILLIC CAPITAL LETTER IE WITH GRAVE..CYRILLIC CAPITAL LETTER IO
+0403 ; NFKD_QC; N # L& CYRILLIC CAPITAL LETTER GJE
+0407 ; NFKD_QC; N # L& CYRILLIC CAPITAL LETTER YI
+040C..040E ; NFKD_QC; N # L& [3] CYRILLIC CAPITAL LETTER KJE..CYRILLIC CAPITAL LETTER SHORT U
+0419 ; NFKD_QC; N # L& CYRILLIC CAPITAL LETTER SHORT I
+0439 ; NFKD_QC; N # L& CYRILLIC SMALL LETTER SHORT I
+0450..0451 ; NFKD_QC; N # L& [2] CYRILLIC SMALL LETTER IE WITH GRAVE..CYRILLIC SMALL LETTER IO
+0453 ; NFKD_QC; N # L& CYRILLIC SMALL LETTER GJE
+0457 ; NFKD_QC; N # L& CYRILLIC SMALL LETTER YI
+045C..045E ; NFKD_QC; N # L& [3] CYRILLIC SMALL LETTER KJE..CYRILLIC SMALL LETTER SHORT U
+0476..0477 ; NFKD_QC; N # L& [2] CYRILLIC CAPITAL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT..CYRILLIC SMALL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT
+04C1..04C2 ; NFKD_QC; N # L& [2] CYRILLIC CAPITAL LETTER ZHE WITH BREVE..CYRILLIC SMALL LETTER ZHE WITH BREVE
+04D0..04D3 ; NFKD_QC; N # L& [4] CYRILLIC CAPITAL LETTER A WITH BREVE..CYRILLIC SMALL LETTER A WITH DIAERESIS
+04D6..04D7 ; NFKD_QC; N # L& [2] CYRILLIC CAPITAL LETTER IE WITH BREVE..CYRILLIC SMALL LETTER IE WITH BREVE
+04DA..04DF ; NFKD_QC; N # L& [6] CYRILLIC CAPITAL LETTER SCHWA WITH DIAERESIS..CYRILLIC SMALL LETTER ZE WITH DIAERESIS
+04E2..04E7 ; NFKD_QC; N # L& [6] CYRILLIC CAPITAL LETTER I WITH MACRON..CYRILLIC SMALL LETTER O WITH DIAERESIS
+04EA..04F5 ; NFKD_QC; N # L& [12] CYRILLIC CAPITAL LETTER BARRED O WITH DIAERESIS..CYRILLIC SMALL LETTER CHE WITH DIAERESIS
+04F8..04F9 ; NFKD_QC; N # L& [2] CYRILLIC CAPITAL LETTER YERU WITH DIAERESIS..CYRILLIC SMALL LETTER YERU WITH DIAERESIS
+0587 ; NFKD_QC; N # L& ARMENIAN SMALL LIGATURE ECH YIWN
+0622..0626 ; NFKD_QC; N # Lo [5] ARABIC LETTER ALEF WITH MADDA ABOVE..ARABIC LETTER YEH WITH HAMZA ABOVE
+0675..0678 ; NFKD_QC; N # Lo [4] ARABIC LETTER HIGH HAMZA ALEF..ARABIC LETTER HIGH HAMZA YEH
+06C0 ; NFKD_QC; N # Lo ARABIC LETTER HEH WITH YEH ABOVE
+06C2 ; NFKD_QC; N # Lo ARABIC LETTER HEH GOAL WITH HAMZA ABOVE
+06D3 ; NFKD_QC; N # Lo ARABIC LETTER YEH BARREE WITH HAMZA ABOVE
+0929 ; NFKD_QC; N # Lo DEVANAGARI LETTER NNNA
+0931 ; NFKD_QC; N # Lo DEVANAGARI LETTER RRA
+0934 ; NFKD_QC; N # Lo DEVANAGARI LETTER LLLA
+0958..095F ; NFKD_QC; N # Lo [8] DEVANAGARI LETTER QA..DEVANAGARI LETTER YYA
+09CB..09CC ; NFKD_QC; N # Mc [2] BENGALI VOWEL SIGN O..BENGALI VOWEL SIGN AU
+09DC..09DD ; NFKD_QC; N # Lo [2] BENGALI LETTER RRA..BENGALI LETTER RHA
+09DF ; NFKD_QC; N # Lo BENGALI LETTER YYA
+0A33 ; NFKD_QC; N # Lo GURMUKHI LETTER LLA
+0A36 ; NFKD_QC; N # Lo GURMUKHI LETTER SHA
+0A59..0A5B ; NFKD_QC; N # Lo [3] GURMUKHI LETTER KHHA..GURMUKHI LETTER ZA
+0A5E ; NFKD_QC; N # Lo GURMUKHI LETTER FA
+0B48 ; NFKD_QC; N # Mc ORIYA VOWEL SIGN AI
+0B4B..0B4C ; NFKD_QC; N # Mc [2] ORIYA VOWEL SIGN O..ORIYA VOWEL SIGN AU
+0B5C..0B5D ; NFKD_QC; N # Lo [2] ORIYA LETTER RRA..ORIYA LETTER RHA
+0B94 ; NFKD_QC; N # Lo TAMIL LETTER AU
+0BCA..0BCC ; NFKD_QC; N # Mc [3] TAMIL VOWEL SIGN O..TAMIL VOWEL SIGN AU
+0C48 ; NFKD_QC; N # Mn TELUGU VOWEL SIGN AI
+0CC0 ; NFKD_QC; N # Mc KANNADA VOWEL SIGN II
+0CC7..0CC8 ; NFKD_QC; N # Mc [2] KANNADA VOWEL SIGN EE..KANNADA VOWEL SIGN AI
+0CCA..0CCB ; NFKD_QC; N # Mc [2] KANNADA VOWEL SIGN O..KANNADA VOWEL SIGN OO
+0D4A..0D4C ; NFKD_QC; N # Mc [3] MALAYALAM VOWEL SIGN O..MALAYALAM VOWEL SIGN AU
+0DDA ; NFKD_QC; N # Mc SINHALA VOWEL SIGN DIGA KOMBUVA
+0DDC..0DDE ; NFKD_QC; N # Mc [3] SINHALA VOWEL SIGN KOMBUVA HAA AELA-PILLA..SINHALA VOWEL SIGN KOMBUVA HAA GAYANUKITTA
+0E33 ; NFKD_QC; N # Lo THAI CHARACTER SARA AM
+0EB3 ; NFKD_QC; N # Lo LAO VOWEL SIGN AM
+0EDC..0EDD ; NFKD_QC; N # Lo [2] LAO HO NO..LAO HO MO
+0F0C ; NFKD_QC; N # Po TIBETAN MARK DELIMITER TSHEG BSTAR
+0F43 ; NFKD_QC; N # Lo TIBETAN LETTER GHA
+0F4D ; NFKD_QC; N # Lo TIBETAN LETTER DDHA
+0F52 ; NFKD_QC; N # Lo TIBETAN LETTER DHA
+0F57 ; NFKD_QC; N # Lo TIBETAN LETTER BHA
+0F5C ; NFKD_QC; N # Lo TIBETAN LETTER DZHA
+0F69 ; NFKD_QC; N # Lo TIBETAN LETTER KSSA
+0F73 ; NFKD_QC; N # Mn TIBETAN VOWEL SIGN II
+0F75..0F79 ; NFKD_QC; N # Mn [5] TIBETAN VOWEL SIGN UU..TIBETAN VOWEL SIGN VOCALIC LL
+0F81 ; NFKD_QC; N # Mn TIBETAN VOWEL SIGN REVERSED II
+0F93 ; NFKD_QC; N # Mn TIBETAN SUBJOINED LETTER GHA
+0F9D ; NFKD_QC; N # Mn TIBETAN SUBJOINED LETTER DDHA
+0FA2 ; NFKD_QC; N # Mn TIBETAN SUBJOINED LETTER DHA
+0FA7 ; NFKD_QC; N # Mn TIBETAN SUBJOINED LETTER BHA
+0FAC ; NFKD_QC; N # Mn TIBETAN SUBJOINED LETTER DZHA
+0FB9 ; NFKD_QC; N # Mn TIBETAN SUBJOINED LETTER KSSA
+1026 ; NFKD_QC; N # Lo MYANMAR LETTER UU
+1D2C..1D2E ; NFKD_QC; N # Lm [3] MODIFIER LETTER CAPITAL A..MODIFIER LETTER CAPITAL B
+1D30..1D3A ; NFKD_QC; N # Lm [11] MODIFIER LETTER CAPITAL D..MODIFIER LETTER CAPITAL N
+1D3C..1D4D ; NFKD_QC; N # Lm [18] MODIFIER LETTER CAPITAL O..MODIFIER LETTER SMALL G
+1D4F..1D61 ; NFKD_QC; N # Lm [19] MODIFIER LETTER SMALL K..MODIFIER LETTER SMALL CHI
+1D62..1D6A ; NFKD_QC; N # L& [9] LATIN SUBSCRIPT SMALL LETTER I..GREEK SUBSCRIPT SMALL LETTER CHI
+1E00..1E9B ; NFKD_QC; N # L& [156] LATIN CAPITAL LETTER A WITH RING BELOW..LATIN SMALL LETTER LONG S WITH DOT ABOVE
+1EA0..1EF9 ; NFKD_QC; N # L& [90] LATIN CAPITAL LETTER A WITH DOT BELOW..LATIN SMALL LETTER Y WITH TILDE
+1F00..1F15 ; NFKD_QC; N # L& [22] GREEK SMALL LETTER ALPHA WITH PSILI..GREEK SMALL LETTER EPSILON WITH DASIA AND OXIA
+1F18..1F1D ; NFKD_QC; N # L& [6] GREEK CAPITAL LETTER EPSILON WITH PSILI..GREEK CAPITAL LETTER EPSILON WITH DASIA AND OXIA
+1F20..1F45 ; NFKD_QC; N # L& [38] GREEK SMALL LETTER ETA WITH PSILI..GREEK SMALL LETTER OMICRON WITH DASIA AND OXIA
+1F48..1F4D ; NFKD_QC; N # L& [6] GREEK CAPITAL LETTER OMICRON WITH PSILI..GREEK CAPITAL LETTER OMICRON WITH DASIA AND OXIA
+1F50..1F57 ; NFKD_QC; N # L& [8] GREEK SMALL LETTER UPSILON WITH PSILI..GREEK SMALL LETTER UPSILON WITH DASIA AND PERISPOMENI
+1F59 ; NFKD_QC; N # L& GREEK CAPITAL LETTER UPSILON WITH DASIA
+1F5B ; NFKD_QC; N # L& GREEK CAPITAL LETTER UPSILON WITH DASIA AND VARIA
+1F5D ; NFKD_QC; N # L& GREEK CAPITAL LETTER UPSILON WITH DASIA AND OXIA
+1F5F..1F7D ; NFKD_QC; N # L& [31] GREEK CAPITAL LETTER UPSILON WITH DASIA AND PERISPOMENI..GREEK SMALL LETTER OMEGA WITH OXIA
+1F80..1FB4 ; NFKD_QC; N # L& [53] GREEK SMALL LETTER ALPHA WITH PSILI AND YPOGEGRAMMENI..GREEK SMALL LETTER ALPHA WITH OXIA AND YPOGEGRAMMENI
+1FB6..1FBC ; NFKD_QC; N # L& [7] GREEK SMALL LETTER ALPHA WITH PERISPOMENI..GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI
+1FBD ; NFKD_QC; N # Sk GREEK KORONIS
+1FBE ; NFKD_QC; N # L& GREEK PROSGEGRAMMENI
+1FBF..1FC1 ; NFKD_QC; N # Sk [3] GREEK PSILI..GREEK DIALYTIKA AND PERISPOMENI
+1FC2..1FC4 ; NFKD_QC; N # L& [3] GREEK SMALL LETTER ETA WITH VARIA AND YPOGEGRAMMENI..GREEK SMALL LETTER ETA WITH OXIA AND YPOGEGRAMMENI
+1FC6..1FCC ; NFKD_QC; N # L& [7] GREEK SMALL LETTER ETA WITH PERISPOMENI..GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI
+1FCD..1FCF ; NFKD_QC; N # Sk [3] GREEK PSILI AND VARIA..GREEK PSILI AND PERISPOMENI
+1FD0..1FD3 ; NFKD_QC; N # L& [4] GREEK SMALL LETTER IOTA WITH VRACHY..GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA
+1FD6..1FDB ; NFKD_QC; N # L& [6] GREEK SMALL LETTER IOTA WITH PERISPOMENI..GREEK CAPITAL LETTER IOTA WITH OXIA
+1FDD..1FDF ; NFKD_QC; N # Sk [3] GREEK DASIA AND VARIA..GREEK DASIA AND PERISPOMENI
+1FE0..1FEC ; NFKD_QC; N # L& [13] GREEK SMALL LETTER UPSILON WITH VRACHY..GREEK CAPITAL LETTER RHO WITH DASIA
+1FED..1FEF ; NFKD_QC; N # Sk [3] GREEK DIALYTIKA AND VARIA..GREEK VARIA
+1FF2..1FF4 ; NFKD_QC; N # L& [3] GREEK SMALL LETTER OMEGA WITH VARIA AND YPOGEGRAMMENI..GREEK SMALL LETTER OMEGA WITH OXIA AND YPOGEGRAMMENI
+1FF6..1FFC ; NFKD_QC; N # L& [7] GREEK SMALL LETTER OMEGA WITH PERISPOMENI..GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI
+1FFD..1FFE ; NFKD_QC; N # Sk [2] GREEK OXIA..GREEK DASIA
+2000..200A ; NFKD_QC; N # Zs [11] EN QUAD..HAIR SPACE
+2011 ; NFKD_QC; N # Pd NON-BREAKING HYPHEN
+2017 ; NFKD_QC; N # Po DOUBLE LOW LINE
+2024..2026 ; NFKD_QC; N # Po [3] ONE DOT LEADER..HORIZONTAL ELLIPSIS
+202F ; NFKD_QC; N # Zs NARROW NO-BREAK SPACE
+2033..2034 ; NFKD_QC; N # Po [2] DOUBLE PRIME..TRIPLE PRIME
+2036..2037 ; NFKD_QC; N # Po [2] REVERSED DOUBLE PRIME..REVERSED TRIPLE PRIME
+203C ; NFKD_QC; N # Po DOUBLE EXCLAMATION MARK
+203E ; NFKD_QC; N # Po OVERLINE
+2047..2049 ; NFKD_QC; N # Po [3] DOUBLE QUESTION MARK..EXCLAMATION QUESTION MARK
+2057 ; NFKD_QC; N # Po QUADRUPLE PRIME
+205F ; NFKD_QC; N # Zs MEDIUM MATHEMATICAL SPACE
+2070 ; NFKD_QC; N # No SUPERSCRIPT ZERO
+2071 ; NFKD_QC; N # L& SUPERSCRIPT LATIN SMALL LETTER I
+2074..2079 ; NFKD_QC; N # No [6] SUPERSCRIPT FOUR..SUPERSCRIPT NINE
+207A..207C ; NFKD_QC; N # Sm [3] SUPERSCRIPT PLUS SIGN..SUPERSCRIPT EQUALS SIGN
+207D ; NFKD_QC; N # Ps SUPERSCRIPT LEFT PARENTHESIS
+207E ; NFKD_QC; N # Pe SUPERSCRIPT RIGHT PARENTHESIS
+207F ; NFKD_QC; N # L& SUPERSCRIPT LATIN SMALL LETTER N
+2080..2089 ; NFKD_QC; N # No [10] SUBSCRIPT ZERO..SUBSCRIPT NINE
+208A..208C ; NFKD_QC; N # Sm [3] SUBSCRIPT PLUS SIGN..SUBSCRIPT EQUALS SIGN
+208D ; NFKD_QC; N # Ps SUBSCRIPT LEFT PARENTHESIS
+208E ; NFKD_QC; N # Pe SUBSCRIPT RIGHT PARENTHESIS
+20A8 ; NFKD_QC; N # Sc RUPEE SIGN
+2100..2101 ; NFKD_QC; N # So [2] ACCOUNT OF..ADDRESSED TO THE SUBJECT
+2102 ; NFKD_QC; N # L& DOUBLE-STRUCK CAPITAL C
+2103 ; NFKD_QC; N # So DEGREE CELSIUS
+2105..2106 ; NFKD_QC; N # So [2] CARE OF..CADA UNA
+2107 ; NFKD_QC; N # L& EULER CONSTANT
+2109 ; NFKD_QC; N # So DEGREE FAHRENHEIT
+210A..2113 ; NFKD_QC; N # L& [10] SCRIPT SMALL G..SCRIPT SMALL L
+2115 ; NFKD_QC; N # L& DOUBLE-STRUCK CAPITAL N
+2116 ; NFKD_QC; N # So NUMERO SIGN
+2119..211D ; NFKD_QC; N # L& [5] DOUBLE-STRUCK CAPITAL P..DOUBLE-STRUCK CAPITAL R
+2120..2122 ; NFKD_QC; N # So [3] SERVICE MARK..TRADE MARK SIGN
+2124 ; NFKD_QC; N # L& DOUBLE-STRUCK CAPITAL Z
+2126 ; NFKD_QC; N # L& OHM SIGN
+2128 ; NFKD_QC; N # L& BLACK-LETTER CAPITAL Z
+212A..212D ; NFKD_QC; N # L& [4] KELVIN SIGN..BLACK-LETTER CAPITAL C
+212F..2131 ; NFKD_QC; N # L& [3] SCRIPT SMALL E..SCRIPT CAPITAL F
+2133..2134 ; NFKD_QC; N # L& [2] SCRIPT CAPITAL M..SCRIPT SMALL O
+2135..2138 ; NFKD_QC; N # Lo [4] ALEF SYMBOL..DALET SYMBOL
+2139 ; NFKD_QC; N # L& INFORMATION SOURCE
+213B ; NFKD_QC; N # So FACSIMILE SIGN
+213D..213F ; NFKD_QC; N # L& [3] DOUBLE-STRUCK SMALL GAMMA..DOUBLE-STRUCK CAPITAL PI
+2140 ; NFKD_QC; N # Sm DOUBLE-STRUCK N-ARY SUMMATION
+2145..2149 ; NFKD_QC; N # L& [5] DOUBLE-STRUCK ITALIC CAPITAL D..DOUBLE-STRUCK ITALIC SMALL J
+2153..215F ; NFKD_QC; N # No [13] VULGAR FRACTION ONE THIRD..FRACTION NUMERATOR ONE
+2160..217F ; NFKD_QC; N # Nl [32] ROMAN NUMERAL ONE..SMALL ROMAN NUMERAL ONE THOUSAND
+219A..219B ; NFKD_QC; N # Sm [2] LEFTWARDS ARROW WITH STROKE..RIGHTWARDS ARROW WITH STROKE
+21AE ; NFKD_QC; N # Sm LEFT RIGHT ARROW WITH STROKE
+21CD ; NFKD_QC; N # So LEFTWARDS DOUBLE ARROW WITH STROKE
+21CE..21CF ; NFKD_QC; N # Sm [2] LEFT RIGHT DOUBLE ARROW WITH STROKE..RIGHTWARDS DOUBLE ARROW WITH STROKE
+2204 ; NFKD_QC; N # Sm THERE DOES NOT EXIST
+2209 ; NFKD_QC; N # Sm NOT AN ELEMENT OF
+220C ; NFKD_QC; N # Sm DOES NOT CONTAIN AS MEMBER
+2224 ; NFKD_QC; N # Sm DOES NOT DIVIDE
+2226 ; NFKD_QC; N # Sm NOT PARALLEL TO
+222C..222D ; NFKD_QC; N # Sm [2] DOUBLE INTEGRAL..TRIPLE INTEGRAL
+222F..2230 ; NFKD_QC; N # Sm [2] SURFACE INTEGRAL..VOLUME INTEGRAL
+2241 ; NFKD_QC; N # Sm NOT TILDE
+2244 ; NFKD_QC; N # Sm NOT ASYMPTOTICALLY EQUAL TO
+2247 ; NFKD_QC; N # Sm NEITHER APPROXIMATELY NOR ACTUALLY EQUAL TO
+2249 ; NFKD_QC; N # Sm NOT ALMOST EQUAL TO
+2260 ; NFKD_QC; N # Sm NOT EQUAL TO
+2262 ; NFKD_QC; N # Sm NOT IDENTICAL TO
+226D..2271 ; NFKD_QC; N # Sm [5] NOT EQUIVALENT TO..NEITHER GREATER-THAN NOR EQUAL TO
+2274..2275 ; NFKD_QC; N # Sm [2] NEITHER LESS-THAN NOR EQUIVALENT TO..NEITHER GREATER-THAN NOR EQUIVALENT TO
+2278..2279 ; NFKD_QC; N # Sm [2] NEITHER LESS-THAN NOR GREATER-THAN..NEITHER GREATER-THAN NOR LESS-THAN
+2280..2281 ; NFKD_QC; N # Sm [2] DOES NOT PRECEDE..DOES NOT SUCCEED
+2284..2285 ; NFKD_QC; N # Sm [2] NOT A SUBSET OF..NOT A SUPERSET OF
+2288..2289 ; NFKD_QC; N # Sm [2] NEITHER A SUBSET OF NOR EQUAL TO..NEITHER A SUPERSET OF NOR EQUAL TO
+22AC..22AF ; NFKD_QC; N # Sm [4] DOES NOT PROVE..NEGATED DOUBLE VERTICAL BAR DOUBLE RIGHT TURNSTILE
+22E0..22E3 ; NFKD_QC; N # Sm [4] DOES NOT PRECEDE OR EQUAL..NOT SQUARE ORIGINAL OF OR EQUAL TO
+22EA..22ED ; NFKD_QC; N # Sm [4] NOT NORMAL SUBGROUP OF..DOES NOT CONTAIN AS NORMAL SUBGROUP OR EQUAL
+2329 ; NFKD_QC; N # Ps LEFT-POINTING ANGLE BRACKET
+232A ; NFKD_QC; N # Pe RIGHT-POINTING ANGLE BRACKET
+2460..249B ; NFKD_QC; N # No [60] CIRCLED DIGIT ONE..NUMBER TWENTY FULL STOP
+249C..24E9 ; NFKD_QC; N # So [78] PARENTHESIZED LATIN SMALL LETTER A..CIRCLED LATIN SMALL LETTER Z
+24EA ; NFKD_QC; N # No CIRCLED DIGIT ZERO
+2A0C ; NFKD_QC; N # Sm QUADRUPLE INTEGRAL OPERATOR
+2A74..2A76 ; NFKD_QC; N # Sm [3] DOUBLE COLON EQUAL..THREE CONSECUTIVE EQUALS SIGNS
+2ADC ; NFKD_QC; N # Sm FORKING
+2E9F ; NFKD_QC; N # So CJK RADICAL MOTHER
+2EF3 ; NFKD_QC; N # So CJK RADICAL C-SIMPLIFIED TURTLE
+2F00..2FD5 ; NFKD_QC; N # So [214] KANGXI RADICAL ONE..KANGXI RADICAL FLUTE
+3000 ; NFKD_QC; N # Zs IDEOGRAPHIC SPACE
+3036 ; NFKD_QC; N # So CIRCLED POSTAL MARK
+3038..303A ; NFKD_QC; N # Nl [3] HANGZHOU NUMERAL TEN..HANGZHOU NUMERAL THIRTY
+304C ; NFKD_QC; N # Lo HIRAGANA LETTER GA
+304E ; NFKD_QC; N # Lo HIRAGANA LETTER GI
+3050 ; NFKD_QC; N # Lo HIRAGANA LETTER GU
+3052 ; NFKD_QC; N # Lo HIRAGANA LETTER GE
+3054 ; NFKD_QC; N # Lo HIRAGANA LETTER GO
+3056 ; NFKD_QC; N # Lo HIRAGANA LETTER ZA
+3058 ; NFKD_QC; N # Lo HIRAGANA LETTER ZI
+305A ; NFKD_QC; N # Lo HIRAGANA LETTER ZU
+305C ; NFKD_QC; N # Lo HIRAGANA LETTER ZE
+305E ; NFKD_QC; N # Lo HIRAGANA LETTER ZO
+3060 ; NFKD_QC; N # Lo HIRAGANA LETTER DA
+3062 ; NFKD_QC; N # Lo HIRAGANA LETTER DI
+3065 ; NFKD_QC; N # Lo HIRAGANA LETTER DU
+3067 ; NFKD_QC; N # Lo HIRAGANA LETTER DE
+3069 ; NFKD_QC; N # Lo HIRAGANA LETTER DO
+3070..3071 ; NFKD_QC; N # Lo [2] HIRAGANA LETTER BA..HIRAGANA LETTER PA
+3073..3074 ; NFKD_QC; N # Lo [2] HIRAGANA LETTER BI..HIRAGANA LETTER PI
+3076..3077 ; NFKD_QC; N # Lo [2] HIRAGANA LETTER BU..HIRAGANA LETTER PU
+3079..307A ; NFKD_QC; N # Lo [2] HIRAGANA LETTER BE..HIRAGANA LETTER PE
+307C..307D ; NFKD_QC; N # Lo [2] HIRAGANA LETTER BO..HIRAGANA LETTER PO
+3094 ; NFKD_QC; N # Lo HIRAGANA LETTER VU
+309B..309C ; NFKD_QC; N # Sk [2] KATAKANA-HIRAGANA VOICED SOUND MARK..KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
+309E ; NFKD_QC; N # Lm HIRAGANA VOICED ITERATION MARK
+309F ; NFKD_QC; N # Lo HIRAGANA DIGRAPH YORI
+30AC ; NFKD_QC; N # Lo KATAKANA LETTER GA
+30AE ; NFKD_QC; N # Lo KATAKANA LETTER GI
+30B0 ; NFKD_QC; N # Lo KATAKANA LETTER GU
+30B2 ; NFKD_QC; N # Lo KATAKANA LETTER GE
+30B4 ; NFKD_QC; N # Lo KATAKANA LETTER GO
+30B6 ; NFKD_QC; N # Lo KATAKANA LETTER ZA
+30B8 ; NFKD_QC; N # Lo KATAKANA LETTER ZI
+30BA ; NFKD_QC; N # Lo KATAKANA LETTER ZU
+30BC ; NFKD_QC; N # Lo KATAKANA LETTER ZE
+30BE ; NFKD_QC; N # Lo KATAKANA LETTER ZO
+30C0 ; NFKD_QC; N # Lo KATAKANA LETTER DA
+30C2 ; NFKD_QC; N # Lo KATAKANA LETTER DI
+30C5 ; NFKD_QC; N # Lo KATAKANA LETTER DU
+30C7 ; NFKD_QC; N # Lo KATAKANA LETTER DE
+30C9 ; NFKD_QC; N # Lo KATAKANA LETTER DO
+30D0..30D1 ; NFKD_QC; N # Lo [2] KATAKANA LETTER BA..KATAKANA LETTER PA
+30D3..30D4 ; NFKD_QC; N # Lo [2] KATAKANA LETTER BI..KATAKANA LETTER PI
+30D6..30D7 ; NFKD_QC; N # Lo [2] KATAKANA LETTER BU..KATAKANA LETTER PU
+30D9..30DA ; NFKD_QC; N # Lo [2] KATAKANA LETTER BE..KATAKANA LETTER PE
+30DC..30DD ; NFKD_QC; N # Lo [2] KATAKANA LETTER BO..KATAKANA LETTER PO
+30F4 ; NFKD_QC; N # Lo KATAKANA LETTER VU
+30F7..30FA ; NFKD_QC; N # Lo [4] KATAKANA LETTER VA..KATAKANA LETTER VO
+30FE ; NFKD_QC; N # Lm KATAKANA VOICED ITERATION MARK
+30FF ; NFKD_QC; N # Lo KATAKANA DIGRAPH KOTO
+3131..318E ; NFKD_QC; N # Lo [94] HANGUL LETTER KIYEOK..HANGUL LETTER ARAEAE
+3192..3195 ; NFKD_QC; N # No [4] IDEOGRAPHIC ANNOTATION ONE MARK..IDEOGRAPHIC ANNOTATION FOUR MARK
+3196..319F ; NFKD_QC; N # So [10] IDEOGRAPHIC ANNOTATION TOP MARK..IDEOGRAPHIC ANNOTATION MAN MARK
+3200..321E ; NFKD_QC; N # So [31] PARENTHESIZED HANGUL KIYEOK..PARENTHESIZED KOREAN CHARACTER O HU
+3220..3229 ; NFKD_QC; N # No [10] PARENTHESIZED IDEOGRAPH ONE..PARENTHESIZED IDEOGRAPH TEN
+322A..3243 ; NFKD_QC; N # So [26] PARENTHESIZED IDEOGRAPH MOON..PARENTHESIZED IDEOGRAPH REACH
+3250 ; NFKD_QC; N # So PARTNERSHIP SIGN
+3251..325F ; NFKD_QC; N # No [15] CIRCLED NUMBER TWENTY ONE..CIRCLED NUMBER THIRTY FIVE
+3260..327D ; NFKD_QC; N # So [30] CIRCLED HANGUL KIYEOK..CIRCLED KOREAN CHARACTER JUEUI
+3280..3289 ; NFKD_QC; N # No [10] CIRCLED IDEOGRAPH ONE..CIRCLED IDEOGRAPH TEN
+328A..32B0 ; NFKD_QC; N # So [39] CIRCLED IDEOGRAPH MOON..CIRCLED IDEOGRAPH NIGHT
+32B1..32BF ; NFKD_QC; N # No [15] CIRCLED NUMBER THIRTY SIX..CIRCLED NUMBER FIFTY
+32C0..32FE ; NFKD_QC; N # So [63] IDEOGRAPHIC TELEGRAPH SYMBOL FOR JANUARY..CIRCLED KATAKANA WO
+3300..33FF ; NFKD_QC; N # So [256] SQUARE APAATO..SQUARE GAL
+AC00..D7A3 ; NFKD_QC; N # Lo [11172] HANGUL SYLLABLE GA..HANGUL SYLLABLE HIH
+F900..FA0D ; NFKD_QC; N # Lo [270] CJK COMPATIBILITY IDEOGRAPH-F900..CJK COMPATIBILITY IDEOGRAPH-FA0D
+FA10 ; NFKD_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA10
+FA12 ; NFKD_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA12
+FA15..FA1E ; NFKD_QC; N # Lo [10] CJK COMPATIBILITY IDEOGRAPH-FA15..CJK COMPATIBILITY IDEOGRAPH-FA1E
+FA20 ; NFKD_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA20
+FA22 ; NFKD_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA22
+FA25..FA26 ; NFKD_QC; N # Lo [2] CJK COMPATIBILITY IDEOGRAPH-FA25..CJK COMPATIBILITY IDEOGRAPH-FA26
+FA2A..FA2D ; NFKD_QC; N # Lo [4] CJK COMPATIBILITY IDEOGRAPH-FA2A..CJK COMPATIBILITY IDEOGRAPH-FA2D
+FA30..FA6A ; NFKD_QC; N # Lo [59] CJK COMPATIBILITY IDEOGRAPH-FA30..CJK COMPATIBILITY IDEOGRAPH-FA6A
+FB00..FB06 ; NFKD_QC; N # L& [7] LATIN SMALL LIGATURE FF..LATIN SMALL LIGATURE ST
+FB13..FB17 ; NFKD_QC; N # L& [5] ARMENIAN SMALL LIGATURE MEN NOW..ARMENIAN SMALL LIGATURE MEN XEH
+FB1D ; NFKD_QC; N # Lo HEBREW LETTER YOD WITH HIRIQ
+FB1F..FB28 ; NFKD_QC; N # Lo [10] HEBREW LIGATURE YIDDISH YOD YOD PATAH..HEBREW LETTER WIDE TAV
+FB29 ; NFKD_QC; N # Sm HEBREW LETTER ALTERNATIVE PLUS SIGN
+FB2A..FB36 ; NFKD_QC; N # Lo [13] HEBREW LETTER SHIN WITH SHIN DOT..HEBREW LETTER ZAYIN WITH DAGESH
+FB38..FB3C ; NFKD_QC; N # Lo [5] HEBREW LETTER TET WITH DAGESH..HEBREW LETTER LAMED WITH DAGESH
+FB3E ; NFKD_QC; N # Lo HEBREW LETTER MEM WITH DAGESH
+FB40..FB41 ; NFKD_QC; N # Lo [2] HEBREW LETTER NUN WITH DAGESH..HEBREW LETTER SAMEKH WITH DAGESH
+FB43..FB44 ; NFKD_QC; N # Lo [2] HEBREW LETTER FINAL PE WITH DAGESH..HEBREW LETTER PE WITH DAGESH
+FB46..FBB1 ; NFKD_QC; N # Lo [108] HEBREW LETTER TSADI WITH DAGESH..ARABIC LETTER YEH BARREE WITH HAMZA ABOVE FINAL FORM
+FBD3..FD3D ; NFKD_QC; N # Lo [363] ARABIC LETTER NG ISOLATED FORM..ARABIC LIGATURE ALEF WITH FATHATAN ISOLATED FORM
+FD50..FD8F ; NFKD_QC; N # Lo [64] ARABIC LIGATURE TEH WITH JEEM WITH MEEM INITIAL FORM..ARABIC LIGATURE MEEM WITH KHAH WITH MEEM INITIAL FORM
+FD92..FDC7 ; NFKD_QC; N # Lo [54] ARABIC LIGATURE MEEM WITH JEEM WITH KHAH INITIAL FORM..ARABIC LIGATURE NOON WITH JEEM WITH YEH FINAL FORM
+FDF0..FDFB ; NFKD_QC; N # Lo [12] ARABIC LIGATURE SALLA USED AS KORANIC STOP SIGN ISOLATED FORM..ARABIC LIGATURE JALLAJALALOUHOU
+FDFC ; NFKD_QC; N # Sc RIAL SIGN
+FE30 ; NFKD_QC; N # Po PRESENTATION FORM FOR VERTICAL TWO DOT LEADER
+FE31..FE32 ; NFKD_QC; N # Pd [2] PRESENTATION FORM FOR VERTICAL EM DASH..PRESENTATION FORM FOR VERTICAL EN DASH
+FE33..FE34 ; NFKD_QC; N # Pc [2] PRESENTATION FORM FOR VERTICAL LOW LINE..PRESENTATION FORM FOR VERTICAL WAVY LOW LINE
+FE35 ; NFKD_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT PARENTHESIS
+FE36 ; NFKD_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT PARENTHESIS
+FE37 ; NFKD_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT CURLY BRACKET
+FE38 ; NFKD_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT CURLY BRACKET
+FE39 ; NFKD_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT TORTOISE SHELL BRACKET
+FE3A ; NFKD_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT TORTOISE SHELL BRACKET
+FE3B ; NFKD_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT BLACK LENTICULAR BRACKET
+FE3C ; NFKD_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT BLACK LENTICULAR BRACKET
+FE3D ; NFKD_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT DOUBLE ANGLE BRACKET
+FE3E ; NFKD_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT DOUBLE ANGLE BRACKET
+FE3F ; NFKD_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT ANGLE BRACKET
+FE40 ; NFKD_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT ANGLE BRACKET
+FE41 ; NFKD_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT CORNER BRACKET
+FE42 ; NFKD_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT CORNER BRACKET
+FE43 ; NFKD_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT WHITE CORNER BRACKET
+FE44 ; NFKD_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT WHITE CORNER BRACKET
+FE47 ; NFKD_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT SQUARE BRACKET
+FE48 ; NFKD_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT SQUARE BRACKET
+FE49..FE4C ; NFKD_QC; N # Po [4] DASHED OVERLINE..DOUBLE WAVY OVERLINE
+FE4D..FE4F ; NFKD_QC; N # Pc [3] DASHED LOW LINE..WAVY LOW LINE
+FE50..FE52 ; NFKD_QC; N # Po [3] SMALL COMMA..SMALL FULL STOP
+FE54..FE57 ; NFKD_QC; N # Po [4] SMALL SEMICOLON..SMALL EXCLAMATION MARK
+FE58 ; NFKD_QC; N # Pd SMALL EM DASH
+FE59 ; NFKD_QC; N # Ps SMALL LEFT PARENTHESIS
+FE5A ; NFKD_QC; N # Pe SMALL RIGHT PARENTHESIS
+FE5B ; NFKD_QC; N # Ps SMALL LEFT CURLY BRACKET
+FE5C ; NFKD_QC; N # Pe SMALL RIGHT CURLY BRACKET
+FE5D ; NFKD_QC; N # Ps SMALL LEFT TORTOISE SHELL BRACKET
+FE5E ; NFKD_QC; N # Pe SMALL RIGHT TORTOISE SHELL BRACKET
+FE5F..FE61 ; NFKD_QC; N # Po [3] SMALL NUMBER SIGN..SMALL ASTERISK
+FE62 ; NFKD_QC; N # Sm SMALL PLUS SIGN
+FE63 ; NFKD_QC; N # Pd SMALL HYPHEN-MINUS
+FE64..FE66 ; NFKD_QC; N # Sm [3] SMALL LESS-THAN SIGN..SMALL EQUALS SIGN
+FE68 ; NFKD_QC; N # Po SMALL REVERSE SOLIDUS
+FE69 ; NFKD_QC; N # Sc SMALL DOLLAR SIGN
+FE6A..FE6B ; NFKD_QC; N # Po [2] SMALL PERCENT SIGN..SMALL COMMERCIAL AT
+FE70..FE72 ; NFKD_QC; N # Lo [3] ARABIC FATHATAN ISOLATED FORM..ARABIC DAMMATAN ISOLATED FORM
+FE74 ; NFKD_QC; N # Lo ARABIC KASRATAN ISOLATED FORM
+FE76..FEFC ; NFKD_QC; N # Lo [135] ARABIC FATHA ISOLATED FORM..ARABIC LIGATURE LAM WITH ALEF FINAL FORM
+FF01..FF03 ; NFKD_QC; N # Po [3] FULLWIDTH EXCLAMATION MARK..FULLWIDTH NUMBER SIGN
+FF04 ; NFKD_QC; N # Sc FULLWIDTH DOLLAR SIGN
+FF05..FF07 ; NFKD_QC; N # Po [3] FULLWIDTH PERCENT SIGN..FULLWIDTH APOSTROPHE
+FF08 ; NFKD_QC; N # Ps FULLWIDTH LEFT PARENTHESIS
+FF09 ; NFKD_QC; N # Pe FULLWIDTH RIGHT PARENTHESIS
+FF0A ; NFKD_QC; N # Po FULLWIDTH ASTERISK
+FF0B ; NFKD_QC; N # Sm FULLWIDTH PLUS SIGN
+FF0C ; NFKD_QC; N # Po FULLWIDTH COMMA
+FF0D ; NFKD_QC; N # Pd FULLWIDTH HYPHEN-MINUS
+FF0E..FF0F ; NFKD_QC; N # Po [2] FULLWIDTH FULL STOP..FULLWIDTH SOLIDUS
+FF10..FF19 ; NFKD_QC; N # Nd [10] FULLWIDTH DIGIT ZERO..FULLWIDTH DIGIT NINE
+FF1A..FF1B ; NFKD_QC; N # Po [2] FULLWIDTH COLON..FULLWIDTH SEMICOLON
+FF1C..FF1E ; NFKD_QC; N # Sm [3] FULLWIDTH LESS-THAN SIGN..FULLWIDTH GREATER-THAN SIGN
+FF1F..FF20 ; NFKD_QC; N # Po [2] FULLWIDTH QUESTION MARK..FULLWIDTH COMMERCIAL AT
+FF21..FF3A ; NFKD_QC; N # L& [26] FULLWIDTH LATIN CAPITAL LETTER A..FULLWIDTH LATIN CAPITAL LETTER Z
+FF3B ; NFKD_QC; N # Ps FULLWIDTH LEFT SQUARE BRACKET
+FF3C ; NFKD_QC; N # Po FULLWIDTH REVERSE SOLIDUS
+FF3D ; NFKD_QC; N # Pe FULLWIDTH RIGHT SQUARE BRACKET
+FF3E ; NFKD_QC; N # Sk FULLWIDTH CIRCUMFLEX ACCENT
+FF3F ; NFKD_QC; N # Pc FULLWIDTH LOW LINE
+FF40 ; NFKD_QC; N # Sk FULLWIDTH GRAVE ACCENT
+FF41..FF5A ; NFKD_QC; N # L& [26] FULLWIDTH LATIN SMALL LETTER A..FULLWIDTH LATIN SMALL LETTER Z
+FF5B ; NFKD_QC; N # Ps FULLWIDTH LEFT CURLY BRACKET
+FF5C ; NFKD_QC; N # Sm FULLWIDTH VERTICAL LINE
+FF5D ; NFKD_QC; N # Pe FULLWIDTH RIGHT CURLY BRACKET
+FF5E ; NFKD_QC; N # Sm FULLWIDTH TILDE
+FF5F ; NFKD_QC; N # Ps FULLWIDTH LEFT WHITE PARENTHESIS
+FF60 ; NFKD_QC; N # Pe FULLWIDTH RIGHT WHITE PARENTHESIS
+FF61 ; NFKD_QC; N # Po HALFWIDTH IDEOGRAPHIC FULL STOP
+FF62 ; NFKD_QC; N # Ps HALFWIDTH LEFT CORNER BRACKET
+FF63 ; NFKD_QC; N # Pe HALFWIDTH RIGHT CORNER BRACKET
+FF64 ; NFKD_QC; N # Po HALFWIDTH IDEOGRAPHIC COMMA
+FF65 ; NFKD_QC; N # Pc HALFWIDTH KATAKANA MIDDLE DOT
+FF66..FF6F ; NFKD_QC; N # Lo [10] HALFWIDTH KATAKANA LETTER WO..HALFWIDTH KATAKANA LETTER SMALL TU
+FF70 ; NFKD_QC; N # Lm HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK
+FF71..FF9D ; NFKD_QC; N # Lo [45] HALFWIDTH KATAKANA LETTER A..HALFWIDTH KATAKANA LETTER N
+FF9E..FF9F ; NFKD_QC; N # Lm [2] HALFWIDTH KATAKANA VOICED SOUND MARK..HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK
+FFA0..FFBE ; NFKD_QC; N # Lo [31] HALFWIDTH HANGUL FILLER..HALFWIDTH HANGUL LETTER HIEUH
+FFC2..FFC7 ; NFKD_QC; N # Lo [6] HALFWIDTH HANGUL LETTER A..HALFWIDTH HANGUL LETTER E
+FFCA..FFCF ; NFKD_QC; N # Lo [6] HALFWIDTH HANGUL LETTER YEO..HALFWIDTH HANGUL LETTER OE
+FFD2..FFD7 ; NFKD_QC; N # Lo [6] HALFWIDTH HANGUL LETTER YO..HALFWIDTH HANGUL LETTER YU
+FFDA..FFDC ; NFKD_QC; N # Lo [3] HALFWIDTH HANGUL LETTER EU..HALFWIDTH HANGUL LETTER I
+FFE0..FFE1 ; NFKD_QC; N # Sc [2] FULLWIDTH CENT SIGN..FULLWIDTH POUND SIGN
+FFE2 ; NFKD_QC; N # Sm FULLWIDTH NOT SIGN
+FFE3 ; NFKD_QC; N # Sk FULLWIDTH MACRON
+FFE4 ; NFKD_QC; N # So FULLWIDTH BROKEN BAR
+FFE5..FFE6 ; NFKD_QC; N # Sc [2] FULLWIDTH YEN SIGN..FULLWIDTH WON SIGN
+FFE8 ; NFKD_QC; N # So HALFWIDTH FORMS LIGHT VERTICAL
+FFE9..FFEC ; NFKD_QC; N # Sm [4] HALFWIDTH LEFTWARDS ARROW..HALFWIDTH DOWNWARDS ARROW
+FFED..FFEE ; NFKD_QC; N # So [2] HALFWIDTH BLACK SQUARE..HALFWIDTH WHITE CIRCLE
+1D15E..1D164 ; NFKD_QC; N # So [7] MUSICAL SYMBOL HALF NOTE..MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH NOTE
+1D1BB..1D1C0 ; NFKD_QC; N # So [6] MUSICAL SYMBOL MINIMA..MUSICAL SYMBOL FUSA BLACK
+1D400..1D454 ; NFKD_QC; N # L& [85] MATHEMATICAL BOLD CAPITAL A..MATHEMATICAL ITALIC SMALL G
+1D456..1D49C ; NFKD_QC; N # L& [71] MATHEMATICAL ITALIC SMALL I..MATHEMATICAL SCRIPT CAPITAL A
+1D49E..1D49F ; NFKD_QC; N # L& [2] MATHEMATICAL SCRIPT CAPITAL C..MATHEMATICAL SCRIPT CAPITAL D
+1D4A2 ; NFKD_QC; N # L& MATHEMATICAL SCRIPT CAPITAL G
+1D4A5..1D4A6 ; NFKD_QC; N # L& [2] MATHEMATICAL SCRIPT CAPITAL J..MATHEMATICAL SCRIPT CAPITAL K
+1D4A9..1D4AC ; NFKD_QC; N # L& [4] MATHEMATICAL SCRIPT CAPITAL N..MATHEMATICAL SCRIPT CAPITAL Q
+1D4AE..1D4B9 ; NFKD_QC; N # L& [12] MATHEMATICAL SCRIPT CAPITAL S..MATHEMATICAL SCRIPT SMALL D
+1D4BB ; NFKD_QC; N # L& MATHEMATICAL SCRIPT SMALL F
+1D4BD..1D4C3 ; NFKD_QC; N # L& [7] MATHEMATICAL SCRIPT SMALL H..MATHEMATICAL SCRIPT SMALL N
+1D4C5..1D505 ; NFKD_QC; N # L& [65] MATHEMATICAL SCRIPT SMALL P..MATHEMATICAL FRAKTUR CAPITAL B
+1D507..1D50A ; NFKD_QC; N # L& [4] MATHEMATICAL FRAKTUR CAPITAL D..MATHEMATICAL FRAKTUR CAPITAL G
+1D50D..1D514 ; NFKD_QC; N # L& [8] MATHEMATICAL FRAKTUR CAPITAL J..MATHEMATICAL FRAKTUR CAPITAL Q
+1D516..1D51C ; NFKD_QC; N # L& [7] MATHEMATICAL FRAKTUR CAPITAL S..MATHEMATICAL FRAKTUR CAPITAL Y
+1D51E..1D539 ; NFKD_QC; N # L& [28] MATHEMATICAL FRAKTUR SMALL A..MATHEMATICAL DOUBLE-STRUCK CAPITAL B
+1D53B..1D53E ; NFKD_QC; N # L& [4] MATHEMATICAL DOUBLE-STRUCK CAPITAL D..MATHEMATICAL DOUBLE-STRUCK CAPITAL G
+1D540..1D544 ; NFKD_QC; N # L& [5] MATHEMATICAL DOUBLE-STRUCK CAPITAL I..MATHEMATICAL DOUBLE-STRUCK CAPITAL M
+1D546 ; NFKD_QC; N # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL O
+1D54A..1D550 ; NFKD_QC; N # L& [7] MATHEMATICAL DOUBLE-STRUCK CAPITAL S..MATHEMATICAL DOUBLE-STRUCK CAPITAL Y
+1D552..1D6A3 ; NFKD_QC; N # L& [338] MATHEMATICAL DOUBLE-STRUCK SMALL A..MATHEMATICAL MONOSPACE SMALL Z
+1D6A8..1D6C0 ; NFKD_QC; N # L& [25] MATHEMATICAL BOLD CAPITAL ALPHA..MATHEMATICAL BOLD CAPITAL OMEGA
+1D6C1 ; NFKD_QC; N # Sm MATHEMATICAL BOLD NABLA
+1D6C2..1D6DA ; NFKD_QC; N # L& [25] MATHEMATICAL BOLD SMALL ALPHA..MATHEMATICAL BOLD SMALL OMEGA
+1D6DB ; NFKD_QC; N # Sm MATHEMATICAL BOLD PARTIAL DIFFERENTIAL
+1D6DC..1D6FA ; NFKD_QC; N # L& [31] MATHEMATICAL BOLD EPSILON SYMBOL..MATHEMATICAL ITALIC CAPITAL OMEGA
+1D6FB ; NFKD_QC; N # Sm MATHEMATICAL ITALIC NABLA
+1D6FC..1D714 ; NFKD_QC; N # L& [25] MATHEMATICAL ITALIC SMALL ALPHA..MATHEMATICAL ITALIC SMALL OMEGA
+1D715 ; NFKD_QC; N # Sm MATHEMATICAL ITALIC PARTIAL DIFFERENTIAL
+1D716..1D734 ; NFKD_QC; N # L& [31] MATHEMATICAL ITALIC EPSILON SYMBOL..MATHEMATICAL BOLD ITALIC CAPITAL OMEGA
+1D735 ; NFKD_QC; N # Sm MATHEMATICAL BOLD ITALIC NABLA
+1D736..1D74E ; NFKD_QC; N # L& [25] MATHEMATICAL BOLD ITALIC SMALL ALPHA..MATHEMATICAL BOLD ITALIC SMALL OMEGA
+1D74F ; NFKD_QC; N # Sm MATHEMATICAL BOLD ITALIC PARTIAL DIFFERENTIAL
+1D750..1D76E ; NFKD_QC; N # L& [31] MATHEMATICAL BOLD ITALIC EPSILON SYMBOL..MATHEMATICAL SANS-SERIF BOLD CAPITAL OMEGA
+1D76F ; NFKD_QC; N # Sm MATHEMATICAL SANS-SERIF BOLD NABLA
+1D770..1D788 ; NFKD_QC; N # L& [25] MATHEMATICAL SANS-SERIF BOLD SMALL ALPHA..MATHEMATICAL SANS-SERIF BOLD SMALL OMEGA
+1D789 ; NFKD_QC; N # Sm MATHEMATICAL SANS-SERIF BOLD PARTIAL DIFFERENTIAL
+1D78A..1D7A8 ; NFKD_QC; N # L& [31] MATHEMATICAL SANS-SERIF BOLD EPSILON SYMBOL..MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL OMEGA
+1D7A9 ; NFKD_QC; N # Sm MATHEMATICAL SANS-SERIF BOLD ITALIC NABLA
+1D7AA..1D7C2 ; NFKD_QC; N # L& [25] MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ALPHA..MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL OMEGA
+1D7C3 ; NFKD_QC; N # Sm MATHEMATICAL SANS-SERIF BOLD ITALIC PARTIAL DIFFERENTIAL
+1D7C4..1D7C9 ; NFKD_QC; N # L& [6] MATHEMATICAL SANS-SERIF BOLD ITALIC EPSILON SYMBOL..MATHEMATICAL SANS-SERIF BOLD ITALIC PI SYMBOL
+1D7CE..1D7FF ; NFKD_QC; N # Nd [50] MATHEMATICAL BOLD DIGIT ZERO..MATHEMATICAL MONOSPACE DIGIT NINE
+2F800..2FA1D ; NFKD_QC; N # Lo [542] CJK COMPATIBILITY IDEOGRAPH-2F800..CJK COMPATIBILITY IDEOGRAPH-2FA1D
+
+# Total code points: 16396
+
+# ================================================
+
+# Property: NFKC_Quick_Check
+
+# All code points not explicitly listed for NFKC_Quick_Check
+# have the value Yes (Y).
+
+# ================================================
+
+# NFKC_Quick_Check=No
+
+00A0 ; NFKC_QC; N # Zs NO-BREAK SPACE
+00A8 ; NFKC_QC; N # Sk DIAERESIS
+00AA ; NFKC_QC; N # L& FEMININE ORDINAL INDICATOR
+00AF ; NFKC_QC; N # Sk MACRON
+00B2..00B3 ; NFKC_QC; N # No [2] SUPERSCRIPT TWO..SUPERSCRIPT THREE
+00B4 ; NFKC_QC; N # Sk ACUTE ACCENT
+00B5 ; NFKC_QC; N # L& MICRO SIGN
+00B8 ; NFKC_QC; N # Sk CEDILLA
+00B9 ; NFKC_QC; N # No SUPERSCRIPT ONE
+00BA ; NFKC_QC; N # L& MASCULINE ORDINAL INDICATOR
+00BC..00BE ; NFKC_QC; N # No [3] VULGAR FRACTION ONE QUARTER..VULGAR FRACTION THREE QUARTERS
+0132..0133 ; NFKC_QC; N # L& [2] LATIN CAPITAL LIGATURE IJ..LATIN SMALL LIGATURE IJ
+013F..0140 ; NFKC_QC; N # L& [2] LATIN CAPITAL LETTER L WITH MIDDLE DOT..LATIN SMALL LETTER L WITH MIDDLE DOT
+0149 ; NFKC_QC; N # L& LATIN SMALL LETTER N PRECEDED BY APOSTROPHE
+017F ; NFKC_QC; N # L& LATIN SMALL LETTER LONG S
+01C4..01CC ; NFKC_QC; N # L& [9] LATIN CAPITAL LETTER DZ WITH CARON..LATIN SMALL LETTER NJ
+01F1..01F3 ; NFKC_QC; N # L& [3] LATIN CAPITAL LETTER DZ..LATIN SMALL LETTER DZ
+02B0..02B8 ; NFKC_QC; N # Lm [9] MODIFIER LETTER SMALL H..MODIFIER LETTER SMALL Y
+02D8..02DD ; NFKC_QC; N # Sk [6] BREVE..DOUBLE ACUTE ACCENT
+02E0..02E4 ; NFKC_QC; N # Lm [5] MODIFIER LETTER SMALL GAMMA..MODIFIER LETTER SMALL REVERSED GLOTTAL STOP
+0340..0341 ; NFKC_QC; N # Mn [2] COMBINING GRAVE TONE MARK..COMBINING ACUTE TONE MARK
+0343..0344 ; NFKC_QC; N # Mn [2] COMBINING GREEK KORONIS..COMBINING GREEK DIALYTIKA TONOS
+0374 ; NFKC_QC; N # Sk GREEK NUMERAL SIGN
+037A ; NFKC_QC; N # Lm GREEK YPOGEGRAMMENI
+037E ; NFKC_QC; N # Po GREEK QUESTION MARK
+0384..0385 ; NFKC_QC; N # Sk [2] GREEK TONOS..GREEK DIALYTIKA TONOS
+0387 ; NFKC_QC; N # Po GREEK ANO TELEIA
+03D0..03D6 ; NFKC_QC; N # L& [7] GREEK BETA SYMBOL..GREEK PI SYMBOL
+03F0..03F2 ; NFKC_QC; N # L& [3] GREEK KAPPA SYMBOL..GREEK LUNATE SIGMA SYMBOL
+03F4..03F5 ; NFKC_QC; N # L& [2] GREEK CAPITAL THETA SYMBOL..GREEK LUNATE EPSILON SYMBOL
+03F9 ; NFKC_QC; N # L& GREEK CAPITAL LUNATE SIGMA SYMBOL
+0587 ; NFKC_QC; N # L& ARMENIAN SMALL LIGATURE ECH YIWN
+0675..0678 ; NFKC_QC; N # Lo [4] ARABIC LETTER HIGH HAMZA ALEF..ARABIC LETTER HIGH HAMZA YEH
+0958..095F ; NFKC_QC; N # Lo [8] DEVANAGARI LETTER QA..DEVANAGARI LETTER YYA
+09DC..09DD ; NFKC_QC; N # Lo [2] BENGALI LETTER RRA..BENGALI LETTER RHA
+09DF ; NFKC_QC; N # Lo BENGALI LETTER YYA
+0A33 ; NFKC_QC; N # Lo GURMUKHI LETTER LLA
+0A36 ; NFKC_QC; N # Lo GURMUKHI LETTER SHA
+0A59..0A5B ; NFKC_QC; N # Lo [3] GURMUKHI LETTER KHHA..GURMUKHI LETTER ZA
+0A5E ; NFKC_QC; N # Lo GURMUKHI LETTER FA
+0B5C..0B5D ; NFKC_QC; N # Lo [2] ORIYA LETTER RRA..ORIYA LETTER RHA
+0E33 ; NFKC_QC; N # Lo THAI CHARACTER SARA AM
+0EB3 ; NFKC_QC; N # Lo LAO VOWEL SIGN AM
+0EDC..0EDD ; NFKC_QC; N # Lo [2] LAO HO NO..LAO HO MO
+0F0C ; NFKC_QC; N # Po TIBETAN MARK DELIMITER TSHEG BSTAR
+0F43 ; NFKC_QC; N # Lo TIBETAN LETTER GHA
+0F4D ; NFKC_QC; N # Lo TIBETAN LETTER DDHA
+0F52 ; NFKC_QC; N # Lo TIBETAN LETTER DHA
+0F57 ; NFKC_QC; N # Lo TIBETAN LETTER BHA
+0F5C ; NFKC_QC; N # Lo TIBETAN LETTER DZHA
+0F69 ; NFKC_QC; N # Lo TIBETAN LETTER KSSA
+0F73 ; NFKC_QC; N # Mn TIBETAN VOWEL SIGN II
+0F75..0F79 ; NFKC_QC; N # Mn [5] TIBETAN VOWEL SIGN UU..TIBETAN VOWEL SIGN VOCALIC LL
+0F81 ; NFKC_QC; N # Mn TIBETAN VOWEL SIGN REVERSED II
+0F93 ; NFKC_QC; N # Mn TIBETAN SUBJOINED LETTER GHA
+0F9D ; NFKC_QC; N # Mn TIBETAN SUBJOINED LETTER DDHA
+0FA2 ; NFKC_QC; N # Mn TIBETAN SUBJOINED LETTER DHA
+0FA7 ; NFKC_QC; N # Mn TIBETAN SUBJOINED LETTER BHA
+0FAC ; NFKC_QC; N # Mn TIBETAN SUBJOINED LETTER DZHA
+0FB9 ; NFKC_QC; N # Mn TIBETAN SUBJOINED LETTER KSSA
+1D2C..1D2E ; NFKC_QC; N # Lm [3] MODIFIER LETTER CAPITAL A..MODIFIER LETTER CAPITAL B
+1D30..1D3A ; NFKC_QC; N # Lm [11] MODIFIER LETTER CAPITAL D..MODIFIER LETTER CAPITAL N
+1D3C..1D4D ; NFKC_QC; N # Lm [18] MODIFIER LETTER CAPITAL O..MODIFIER LETTER SMALL G
+1D4F..1D61 ; NFKC_QC; N # Lm [19] MODIFIER LETTER SMALL K..MODIFIER LETTER SMALL CHI
+1D62..1D6A ; NFKC_QC; N # L& [9] LATIN SUBSCRIPT SMALL LETTER I..GREEK SUBSCRIPT SMALL LETTER CHI
+1E9A..1E9B ; NFKC_QC; N # L& [2] LATIN SMALL LETTER A WITH RIGHT HALF RING..LATIN SMALL LETTER LONG S WITH DOT ABOVE
+1F71 ; NFKC_QC; N # L& GREEK SMALL LETTER ALPHA WITH OXIA
+1F73 ; NFKC_QC; N # L& GREEK SMALL LETTER EPSILON WITH OXIA
+1F75 ; NFKC_QC; N # L& GREEK SMALL LETTER ETA WITH OXIA
+1F77 ; NFKC_QC; N # L& GREEK SMALL LETTER IOTA WITH OXIA
+1F79 ; NFKC_QC; N # L& GREEK SMALL LETTER OMICRON WITH OXIA
+1F7B ; NFKC_QC; N # L& GREEK SMALL LETTER UPSILON WITH OXIA
+1F7D ; NFKC_QC; N # L& GREEK SMALL LETTER OMEGA WITH OXIA
+1FBB ; NFKC_QC; N # L& GREEK CAPITAL LETTER ALPHA WITH OXIA
+1FBD ; NFKC_QC; N # Sk GREEK KORONIS
+1FBE ; NFKC_QC; N # L& GREEK PROSGEGRAMMENI
+1FBF..1FC1 ; NFKC_QC; N # Sk [3] GREEK PSILI..GREEK DIALYTIKA AND PERISPOMENI
+1FC9 ; NFKC_QC; N # L& GREEK CAPITAL LETTER EPSILON WITH OXIA
+1FCB ; NFKC_QC; N # L& GREEK CAPITAL LETTER ETA WITH OXIA
+1FCD..1FCF ; NFKC_QC; N # Sk [3] GREEK PSILI AND VARIA..GREEK PSILI AND PERISPOMENI
+1FD3 ; NFKC_QC; N # L& GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA
+1FDB ; NFKC_QC; N # L& GREEK CAPITAL LETTER IOTA WITH OXIA
+1FDD..1FDF ; NFKC_QC; N # Sk [3] GREEK DASIA AND VARIA..GREEK DASIA AND PERISPOMENI
+1FE3 ; NFKC_QC; N # L& GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA
+1FEB ; NFKC_QC; N # L& GREEK CAPITAL LETTER UPSILON WITH OXIA
+1FED..1FEF ; NFKC_QC; N # Sk [3] GREEK DIALYTIKA AND VARIA..GREEK VARIA
+1FF9 ; NFKC_QC; N # L& GREEK CAPITAL LETTER OMICRON WITH OXIA
+1FFB ; NFKC_QC; N # L& GREEK CAPITAL LETTER OMEGA WITH OXIA
+1FFD..1FFE ; NFKC_QC; N # Sk [2] GREEK OXIA..GREEK DASIA
+2000..200A ; NFKC_QC; N # Zs [11] EN QUAD..HAIR SPACE
+2011 ; NFKC_QC; N # Pd NON-BREAKING HYPHEN
+2017 ; NFKC_QC; N # Po DOUBLE LOW LINE
+2024..2026 ; NFKC_QC; N # Po [3] ONE DOT LEADER..HORIZONTAL ELLIPSIS
+202F ; NFKC_QC; N # Zs NARROW NO-BREAK SPACE
+2033..2034 ; NFKC_QC; N # Po [2] DOUBLE PRIME..TRIPLE PRIME
+2036..2037 ; NFKC_QC; N # Po [2] REVERSED DOUBLE PRIME..REVERSED TRIPLE PRIME
+203C ; NFKC_QC; N # Po DOUBLE EXCLAMATION MARK
+203E ; NFKC_QC; N # Po OVERLINE
+2047..2049 ; NFKC_QC; N # Po [3] DOUBLE QUESTION MARK..EXCLAMATION QUESTION MARK
+2057 ; NFKC_QC; N # Po QUADRUPLE PRIME
+205F ; NFKC_QC; N # Zs MEDIUM MATHEMATICAL SPACE
+2070 ; NFKC_QC; N # No SUPERSCRIPT ZERO
+2071 ; NFKC_QC; N # L& SUPERSCRIPT LATIN SMALL LETTER I
+2074..2079 ; NFKC_QC; N # No [6] SUPERSCRIPT FOUR..SUPERSCRIPT NINE
+207A..207C ; NFKC_QC; N # Sm [3] SUPERSCRIPT PLUS SIGN..SUPERSCRIPT EQUALS SIGN
+207D ; NFKC_QC; N # Ps SUPERSCRIPT LEFT PARENTHESIS
+207E ; NFKC_QC; N # Pe SUPERSCRIPT RIGHT PARENTHESIS
+207F ; NFKC_QC; N # L& SUPERSCRIPT LATIN SMALL LETTER N
+2080..2089 ; NFKC_QC; N # No [10] SUBSCRIPT ZERO..SUBSCRIPT NINE
+208A..208C ; NFKC_QC; N # Sm [3] SUBSCRIPT PLUS SIGN..SUBSCRIPT EQUALS SIGN
+208D ; NFKC_QC; N # Ps SUBSCRIPT LEFT PARENTHESIS
+208E ; NFKC_QC; N # Pe SUBSCRIPT RIGHT PARENTHESIS
+20A8 ; NFKC_QC; N # Sc RUPEE SIGN
+2100..2101 ; NFKC_QC; N # So [2] ACCOUNT OF..ADDRESSED TO THE SUBJECT
+2102 ; NFKC_QC; N # L& DOUBLE-STRUCK CAPITAL C
+2103 ; NFKC_QC; N # So DEGREE CELSIUS
+2105..2106 ; NFKC_QC; N # So [2] CARE OF..CADA UNA
+2107 ; NFKC_QC; N # L& EULER CONSTANT
+2109 ; NFKC_QC; N # So DEGREE FAHRENHEIT
+210A..2113 ; NFKC_QC; N # L& [10] SCRIPT SMALL G..SCRIPT SMALL L
+2115 ; NFKC_QC; N # L& DOUBLE-STRUCK CAPITAL N
+2116 ; NFKC_QC; N # So NUMERO SIGN
+2119..211D ; NFKC_QC; N # L& [5] DOUBLE-STRUCK CAPITAL P..DOUBLE-STRUCK CAPITAL R
+2120..2122 ; NFKC_QC; N # So [3] SERVICE MARK..TRADE MARK SIGN
+2124 ; NFKC_QC; N # L& DOUBLE-STRUCK CAPITAL Z
+2126 ; NFKC_QC; N # L& OHM SIGN
+2128 ; NFKC_QC; N # L& BLACK-LETTER CAPITAL Z
+212A..212D ; NFKC_QC; N # L& [4] KELVIN SIGN..BLACK-LETTER CAPITAL C
+212F..2131 ; NFKC_QC; N # L& [3] SCRIPT SMALL E..SCRIPT CAPITAL F
+2133..2134 ; NFKC_QC; N # L& [2] SCRIPT CAPITAL M..SCRIPT SMALL O
+2135..2138 ; NFKC_QC; N # Lo [4] ALEF SYMBOL..DALET SYMBOL
+2139 ; NFKC_QC; N # L& INFORMATION SOURCE
+213B ; NFKC_QC; N # So FACSIMILE SIGN
+213D..213F ; NFKC_QC; N # L& [3] DOUBLE-STRUCK SMALL GAMMA..DOUBLE-STRUCK CAPITAL PI
+2140 ; NFKC_QC; N # Sm DOUBLE-STRUCK N-ARY SUMMATION
+2145..2149 ; NFKC_QC; N # L& [5] DOUBLE-STRUCK ITALIC CAPITAL D..DOUBLE-STRUCK ITALIC SMALL J
+2153..215F ; NFKC_QC; N # No [13] VULGAR FRACTION ONE THIRD..FRACTION NUMERATOR ONE
+2160..217F ; NFKC_QC; N # Nl [32] ROMAN NUMERAL ONE..SMALL ROMAN NUMERAL ONE THOUSAND
+222C..222D ; NFKC_QC; N # Sm [2] DOUBLE INTEGRAL..TRIPLE INTEGRAL
+222F..2230 ; NFKC_QC; N # Sm [2] SURFACE INTEGRAL..VOLUME INTEGRAL
+2329 ; NFKC_QC; N # Ps LEFT-POINTING ANGLE BRACKET
+232A ; NFKC_QC; N # Pe RIGHT-POINTING ANGLE BRACKET
+2460..249B ; NFKC_QC; N # No [60] CIRCLED DIGIT ONE..NUMBER TWENTY FULL STOP
+249C..24E9 ; NFKC_QC; N # So [78] PARENTHESIZED LATIN SMALL LETTER A..CIRCLED LATIN SMALL LETTER Z
+24EA ; NFKC_QC; N # No CIRCLED DIGIT ZERO
+2A0C ; NFKC_QC; N # Sm QUADRUPLE INTEGRAL OPERATOR
+2A74..2A76 ; NFKC_QC; N # Sm [3] DOUBLE COLON EQUAL..THREE CONSECUTIVE EQUALS SIGNS
+2ADC ; NFKC_QC; N # Sm FORKING
+2E9F ; NFKC_QC; N # So CJK RADICAL MOTHER
+2EF3 ; NFKC_QC; N # So CJK RADICAL C-SIMPLIFIED TURTLE
+2F00..2FD5 ; NFKC_QC; N # So [214] KANGXI RADICAL ONE..KANGXI RADICAL FLUTE
+3000 ; NFKC_QC; N # Zs IDEOGRAPHIC SPACE
+3036 ; NFKC_QC; N # So CIRCLED POSTAL MARK
+3038..303A ; NFKC_QC; N # Nl [3] HANGZHOU NUMERAL TEN..HANGZHOU NUMERAL THIRTY
+309B..309C ; NFKC_QC; N # Sk [2] KATAKANA-HIRAGANA VOICED SOUND MARK..KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
+309F ; NFKC_QC; N # Lo HIRAGANA DIGRAPH YORI
+30FF ; NFKC_QC; N # Lo KATAKANA DIGRAPH KOTO
+3131..318E ; NFKC_QC; N # Lo [94] HANGUL LETTER KIYEOK..HANGUL LETTER ARAEAE
+3192..3195 ; NFKC_QC; N # No [4] IDEOGRAPHIC ANNOTATION ONE MARK..IDEOGRAPHIC ANNOTATION FOUR MARK
+3196..319F ; NFKC_QC; N # So [10] IDEOGRAPHIC ANNOTATION TOP MARK..IDEOGRAPHIC ANNOTATION MAN MARK
+3200..321E ; NFKC_QC; N # So [31] PARENTHESIZED HANGUL KIYEOK..PARENTHESIZED KOREAN CHARACTER O HU
+3220..3229 ; NFKC_QC; N # No [10] PARENTHESIZED IDEOGRAPH ONE..PARENTHESIZED IDEOGRAPH TEN
+322A..3243 ; NFKC_QC; N # So [26] PARENTHESIZED IDEOGRAPH MOON..PARENTHESIZED IDEOGRAPH REACH
+3250 ; NFKC_QC; N # So PARTNERSHIP SIGN
+3251..325F ; NFKC_QC; N # No [15] CIRCLED NUMBER TWENTY ONE..CIRCLED NUMBER THIRTY FIVE
+3260..327D ; NFKC_QC; N # So [30] CIRCLED HANGUL KIYEOK..CIRCLED KOREAN CHARACTER JUEUI
+3280..3289 ; NFKC_QC; N # No [10] CIRCLED IDEOGRAPH ONE..CIRCLED IDEOGRAPH TEN
+328A..32B0 ; NFKC_QC; N # So [39] CIRCLED IDEOGRAPH MOON..CIRCLED IDEOGRAPH NIGHT
+32B1..32BF ; NFKC_QC; N # No [15] CIRCLED NUMBER THIRTY SIX..CIRCLED NUMBER FIFTY
+32C0..32FE ; NFKC_QC; N # So [63] IDEOGRAPHIC TELEGRAPH SYMBOL FOR JANUARY..CIRCLED KATAKANA WO
+3300..33FF ; NFKC_QC; N # So [256] SQUARE APAATO..SQUARE GAL
+F900..FA0D ; NFKC_QC; N # Lo [270] CJK COMPATIBILITY IDEOGRAPH-F900..CJK COMPATIBILITY IDEOGRAPH-FA0D
+FA10 ; NFKC_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA10
+FA12 ; NFKC_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA12
+FA15..FA1E ; NFKC_QC; N # Lo [10] CJK COMPATIBILITY IDEOGRAPH-FA15..CJK COMPATIBILITY IDEOGRAPH-FA1E
+FA20 ; NFKC_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA20
+FA22 ; NFKC_QC; N # Lo CJK COMPATIBILITY IDEOGRAPH-FA22
+FA25..FA26 ; NFKC_QC; N # Lo [2] CJK COMPATIBILITY IDEOGRAPH-FA25..CJK COMPATIBILITY IDEOGRAPH-FA26
+FA2A..FA2D ; NFKC_QC; N # Lo [4] CJK COMPATIBILITY IDEOGRAPH-FA2A..CJK COMPATIBILITY IDEOGRAPH-FA2D
+FA30..FA6A ; NFKC_QC; N # Lo [59] CJK COMPATIBILITY IDEOGRAPH-FA30..CJK COMPATIBILITY IDEOGRAPH-FA6A
+FB00..FB06 ; NFKC_QC; N # L& [7] LATIN SMALL LIGATURE FF..LATIN SMALL LIGATURE ST
+FB13..FB17 ; NFKC_QC; N # L& [5] ARMENIAN SMALL LIGATURE MEN NOW..ARMENIAN SMALL LIGATURE MEN XEH
+FB1D ; NFKC_QC; N # Lo HEBREW LETTER YOD WITH HIRIQ
+FB1F..FB28 ; NFKC_QC; N # Lo [10] HEBREW LIGATURE YIDDISH YOD YOD PATAH..HEBREW LETTER WIDE TAV
+FB29 ; NFKC_QC; N # Sm HEBREW LETTER ALTERNATIVE PLUS SIGN
+FB2A..FB36 ; NFKC_QC; N # Lo [13] HEBREW LETTER SHIN WITH SHIN DOT..HEBREW LETTER ZAYIN WITH DAGESH
+FB38..FB3C ; NFKC_QC; N # Lo [5] HEBREW LETTER TET WITH DAGESH..HEBREW LETTER LAMED WITH DAGESH
+FB3E ; NFKC_QC; N # Lo HEBREW LETTER MEM WITH DAGESH
+FB40..FB41 ; NFKC_QC; N # Lo [2] HEBREW LETTER NUN WITH DAGESH..HEBREW LETTER SAMEKH WITH DAGESH
+FB43..FB44 ; NFKC_QC; N # Lo [2] HEBREW LETTER FINAL PE WITH DAGESH..HEBREW LETTER PE WITH DAGESH
+FB46..FBB1 ; NFKC_QC; N # Lo [108] HEBREW LETTER TSADI WITH DAGESH..ARABIC LETTER YEH BARREE WITH HAMZA ABOVE FINAL FORM
+FBD3..FD3D ; NFKC_QC; N # Lo [363] ARABIC LETTER NG ISOLATED FORM..ARABIC LIGATURE ALEF WITH FATHATAN ISOLATED FORM
+FD50..FD8F ; NFKC_QC; N # Lo [64] ARABIC LIGATURE TEH WITH JEEM WITH MEEM INITIAL FORM..ARABIC LIGATURE MEEM WITH KHAH WITH MEEM INITIAL FORM
+FD92..FDC7 ; NFKC_QC; N # Lo [54] ARABIC LIGATURE MEEM WITH JEEM WITH KHAH INITIAL FORM..ARABIC LIGATURE NOON WITH JEEM WITH YEH FINAL FORM
+FDF0..FDFB ; NFKC_QC; N # Lo [12] ARABIC LIGATURE SALLA USED AS KORANIC STOP SIGN ISOLATED FORM..ARABIC LIGATURE JALLAJALALOUHOU
+FDFC ; NFKC_QC; N # Sc RIAL SIGN
+FE30 ; NFKC_QC; N # Po PRESENTATION FORM FOR VERTICAL TWO DOT LEADER
+FE31..FE32 ; NFKC_QC; N # Pd [2] PRESENTATION FORM FOR VERTICAL EM DASH..PRESENTATION FORM FOR VERTICAL EN DASH
+FE33..FE34 ; NFKC_QC; N # Pc [2] PRESENTATION FORM FOR VERTICAL LOW LINE..PRESENTATION FORM FOR VERTICAL WAVY LOW LINE
+FE35 ; NFKC_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT PARENTHESIS
+FE36 ; NFKC_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT PARENTHESIS
+FE37 ; NFKC_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT CURLY BRACKET
+FE38 ; NFKC_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT CURLY BRACKET
+FE39 ; NFKC_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT TORTOISE SHELL BRACKET
+FE3A ; NFKC_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT TORTOISE SHELL BRACKET
+FE3B ; NFKC_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT BLACK LENTICULAR BRACKET
+FE3C ; NFKC_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT BLACK LENTICULAR BRACKET
+FE3D ; NFKC_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT DOUBLE ANGLE BRACKET
+FE3E ; NFKC_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT DOUBLE ANGLE BRACKET
+FE3F ; NFKC_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT ANGLE BRACKET
+FE40 ; NFKC_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT ANGLE BRACKET
+FE41 ; NFKC_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT CORNER BRACKET
+FE42 ; NFKC_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT CORNER BRACKET
+FE43 ; NFKC_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT WHITE CORNER BRACKET
+FE44 ; NFKC_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT WHITE CORNER BRACKET
+FE47 ; NFKC_QC; N # Ps PRESENTATION FORM FOR VERTICAL LEFT SQUARE BRACKET
+FE48 ; NFKC_QC; N # Pe PRESENTATION FORM FOR VERTICAL RIGHT SQUARE BRACKET
+FE49..FE4C ; NFKC_QC; N # Po [4] DASHED OVERLINE..DOUBLE WAVY OVERLINE
+FE4D..FE4F ; NFKC_QC; N # Pc [3] DASHED LOW LINE..WAVY LOW LINE
+FE50..FE52 ; NFKC_QC; N # Po [3] SMALL COMMA..SMALL FULL STOP
+FE54..FE57 ; NFKC_QC; N # Po [4] SMALL SEMICOLON..SMALL EXCLAMATION MARK
+FE58 ; NFKC_QC; N # Pd SMALL EM DASH
+FE59 ; NFKC_QC; N # Ps SMALL LEFT PARENTHESIS
+FE5A ; NFKC_QC; N # Pe SMALL RIGHT PARENTHESIS
+FE5B ; NFKC_QC; N # Ps SMALL LEFT CURLY BRACKET
+FE5C ; NFKC_QC; N # Pe SMALL RIGHT CURLY BRACKET
+FE5D ; NFKC_QC; N # Ps SMALL LEFT TORTOISE SHELL BRACKET
+FE5E ; NFKC_QC; N # Pe SMALL RIGHT TORTOISE SHELL BRACKET
+FE5F..FE61 ; NFKC_QC; N # Po [3] SMALL NUMBER SIGN..SMALL ASTERISK
+FE62 ; NFKC_QC; N # Sm SMALL PLUS SIGN
+FE63 ; NFKC_QC; N # Pd SMALL HYPHEN-MINUS
+FE64..FE66 ; NFKC_QC; N # Sm [3] SMALL LESS-THAN SIGN..SMALL EQUALS SIGN
+FE68 ; NFKC_QC; N # Po SMALL REVERSE SOLIDUS
+FE69 ; NFKC_QC; N # Sc SMALL DOLLAR SIGN
+FE6A..FE6B ; NFKC_QC; N # Po [2] SMALL PERCENT SIGN..SMALL COMMERCIAL AT
+FE70..FE72 ; NFKC_QC; N # Lo [3] ARABIC FATHATAN ISOLATED FORM..ARABIC DAMMATAN ISOLATED FORM
+FE74 ; NFKC_QC; N # Lo ARABIC KASRATAN ISOLATED FORM
+FE76..FEFC ; NFKC_QC; N # Lo [135] ARABIC FATHA ISOLATED FORM..ARABIC LIGATURE LAM WITH ALEF FINAL FORM
+FF01..FF03 ; NFKC_QC; N # Po [3] FULLWIDTH EXCLAMATION MARK..FULLWIDTH NUMBER SIGN
+FF04 ; NFKC_QC; N # Sc FULLWIDTH DOLLAR SIGN
+FF05..FF07 ; NFKC_QC; N # Po [3] FULLWIDTH PERCENT SIGN..FULLWIDTH APOSTROPHE
+FF08 ; NFKC_QC; N # Ps FULLWIDTH LEFT PARENTHESIS
+FF09 ; NFKC_QC; N # Pe FULLWIDTH RIGHT PARENTHESIS
+FF0A ; NFKC_QC; N # Po FULLWIDTH ASTERISK
+FF0B ; NFKC_QC; N # Sm FULLWIDTH PLUS SIGN
+FF0C ; NFKC_QC; N # Po FULLWIDTH COMMA
+FF0D ; NFKC_QC; N # Pd FULLWIDTH HYPHEN-MINUS
+FF0E..FF0F ; NFKC_QC; N # Po [2] FULLWIDTH FULL STOP..FULLWIDTH SOLIDUS
+FF10..FF19 ; NFKC_QC; N # Nd [10] FULLWIDTH DIGIT ZERO..FULLWIDTH DIGIT NINE
+FF1A..FF1B ; NFKC_QC; N # Po [2] FULLWIDTH COLON..FULLWIDTH SEMICOLON
+FF1C..FF1E ; NFKC_QC; N # Sm [3] FULLWIDTH LESS-THAN SIGN..FULLWIDTH GREATER-THAN SIGN
+FF1F..FF20 ; NFKC_QC; N # Po [2] FULLWIDTH QUESTION MARK..FULLWIDTH COMMERCIAL AT
+FF21..FF3A ; NFKC_QC; N # L& [26] FULLWIDTH LATIN CAPITAL LETTER A..FULLWIDTH LATIN CAPITAL LETTER Z
+FF3B ; NFKC_QC; N # Ps FULLWIDTH LEFT SQUARE BRACKET
+FF3C ; NFKC_QC; N # Po FULLWIDTH REVERSE SOLIDUS
+FF3D ; NFKC_QC; N # Pe FULLWIDTH RIGHT SQUARE BRACKET
+FF3E ; NFKC_QC; N # Sk FULLWIDTH CIRCUMFLEX ACCENT
+FF3F ; NFKC_QC; N # Pc FULLWIDTH LOW LINE
+FF40 ; NFKC_QC; N # Sk FULLWIDTH GRAVE ACCENT
+FF41..FF5A ; NFKC_QC; N # L& [26] FULLWIDTH LATIN SMALL LETTER A..FULLWIDTH LATIN SMALL LETTER Z
+FF5B ; NFKC_QC; N # Ps FULLWIDTH LEFT CURLY BRACKET
+FF5C ; NFKC_QC; N # Sm FULLWIDTH VERTICAL LINE
+FF5D ; NFKC_QC; N # Pe FULLWIDTH RIGHT CURLY BRACKET
+FF5E ; NFKC_QC; N # Sm FULLWIDTH TILDE
+FF5F ; NFKC_QC; N # Ps FULLWIDTH LEFT WHITE PARENTHESIS
+FF60 ; NFKC_QC; N # Pe FULLWIDTH RIGHT WHITE PARENTHESIS
+FF61 ; NFKC_QC; N # Po HALFWIDTH IDEOGRAPHIC FULL STOP
+FF62 ; NFKC_QC; N # Ps HALFWIDTH LEFT CORNER BRACKET
+FF63 ; NFKC_QC; N # Pe HALFWIDTH RIGHT CORNER BRACKET
+FF64 ; NFKC_QC; N # Po HALFWIDTH IDEOGRAPHIC COMMA
+FF65 ; NFKC_QC; N # Pc HALFWIDTH KATAKANA MIDDLE DOT
+FF66..FF6F ; NFKC_QC; N # Lo [10] HALFWIDTH KATAKANA LETTER WO..HALFWIDTH KATAKANA LETTER SMALL TU
+FF70 ; NFKC_QC; N # Lm HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK
+FF71..FF9D ; NFKC_QC; N # Lo [45] HALFWIDTH KATAKANA LETTER A..HALFWIDTH KATAKANA LETTER N
+FF9E..FF9F ; NFKC_QC; N # Lm [2] HALFWIDTH KATAKANA VOICED SOUND MARK..HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK
+FFA0..FFBE ; NFKC_QC; N # Lo [31] HALFWIDTH HANGUL FILLER..HALFWIDTH HANGUL LETTER HIEUH
+FFC2..FFC7 ; NFKC_QC; N # Lo [6] HALFWIDTH HANGUL LETTER A..HALFWIDTH HANGUL LETTER E
+FFCA..FFCF ; NFKC_QC; N # Lo [6] HALFWIDTH HANGUL LETTER YEO..HALFWIDTH HANGUL LETTER OE
+FFD2..FFD7 ; NFKC_QC; N # Lo [6] HALFWIDTH HANGUL LETTER YO..HALFWIDTH HANGUL LETTER YU
+FFDA..FFDC ; NFKC_QC; N # Lo [3] HALFWIDTH HANGUL LETTER EU..HALFWIDTH HANGUL LETTER I
+FFE0..FFE1 ; NFKC_QC; N # Sc [2] FULLWIDTH CENT SIGN..FULLWIDTH POUND SIGN
+FFE2 ; NFKC_QC; N # Sm FULLWIDTH NOT SIGN
+FFE3 ; NFKC_QC; N # Sk FULLWIDTH MACRON
+FFE4 ; NFKC_QC; N # So FULLWIDTH BROKEN BAR
+FFE5..FFE6 ; NFKC_QC; N # Sc [2] FULLWIDTH YEN SIGN..FULLWIDTH WON SIGN
+FFE8 ; NFKC_QC; N # So HALFWIDTH FORMS LIGHT VERTICAL
+FFE9..FFEC ; NFKC_QC; N # Sm [4] HALFWIDTH LEFTWARDS ARROW..HALFWIDTH DOWNWARDS ARROW
+FFED..FFEE ; NFKC_QC; N # So [2] HALFWIDTH BLACK SQUARE..HALFWIDTH WHITE CIRCLE
+1D15E..1D164 ; NFKC_QC; N # So [7] MUSICAL SYMBOL HALF NOTE..MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH NOTE
+1D1BB..1D1C0 ; NFKC_QC; N # So [6] MUSICAL SYMBOL MINIMA..MUSICAL SYMBOL FUSA BLACK
+1D400..1D454 ; NFKC_QC; N # L& [85] MATHEMATICAL BOLD CAPITAL A..MATHEMATICAL ITALIC SMALL G
+1D456..1D49C ; NFKC_QC; N # L& [71] MATHEMATICAL ITALIC SMALL I..MATHEMATICAL SCRIPT CAPITAL A
+1D49E..1D49F ; NFKC_QC; N # L& [2] MATHEMATICAL SCRIPT CAPITAL C..MATHEMATICAL SCRIPT CAPITAL D
+1D4A2 ; NFKC_QC; N # L& MATHEMATICAL SCRIPT CAPITAL G
+1D4A5..1D4A6 ; NFKC_QC; N # L& [2] MATHEMATICAL SCRIPT CAPITAL J..MATHEMATICAL SCRIPT CAPITAL K
+1D4A9..1D4AC ; NFKC_QC; N # L& [4] MATHEMATICAL SCRIPT CAPITAL N..MATHEMATICAL SCRIPT CAPITAL Q
+1D4AE..1D4B9 ; NFKC_QC; N # L& [12] MATHEMATICAL SCRIPT CAPITAL S..MATHEMATICAL SCRIPT SMALL D
+1D4BB ; NFKC_QC; N # L& MATHEMATICAL SCRIPT SMALL F
+1D4BD..1D4C3 ; NFKC_QC; N # L& [7] MATHEMATICAL SCRIPT SMALL H..MATHEMATICAL SCRIPT SMALL N
+1D4C5..1D505 ; NFKC_QC; N # L& [65] MATHEMATICAL SCRIPT SMALL P..MATHEMATICAL FRAKTUR CAPITAL B
+1D507..1D50A ; NFKC_QC; N # L& [4] MATHEMATICAL FRAKTUR CAPITAL D..MATHEMATICAL FRAKTUR CAPITAL G
+1D50D..1D514 ; NFKC_QC; N # L& [8] MATHEMATICAL FRAKTUR CAPITAL J..MATHEMATICAL FRAKTUR CAPITAL Q
+1D516..1D51C ; NFKC_QC; N # L& [7] MATHEMATICAL FRAKTUR CAPITAL S..MATHEMATICAL FRAKTUR CAPITAL Y
+1D51E..1D539 ; NFKC_QC; N # L& [28] MATHEMATICAL FRAKTUR SMALL A..MATHEMATICAL DOUBLE-STRUCK CAPITAL B
+1D53B..1D53E ; NFKC_QC; N # L& [4] MATHEMATICAL DOUBLE-STRUCK CAPITAL D..MATHEMATICAL DOUBLE-STRUCK CAPITAL G
+1D540..1D544 ; NFKC_QC; N # L& [5] MATHEMATICAL DOUBLE-STRUCK CAPITAL I..MATHEMATICAL DOUBLE-STRUCK CAPITAL M
+1D546 ; NFKC_QC; N # L& MATHEMATICAL DOUBLE-STRUCK CAPITAL O
+1D54A..1D550 ; NFKC_QC; N # L& [7] MATHEMATICAL DOUBLE-STRUCK CAPITAL S..MATHEMATICAL DOUBLE-STRUCK CAPITAL Y
+1D552..1D6A3 ; NFKC_QC; N # L& [338] MATHEMATICAL DOUBLE-STRUCK SMALL A..MATHEMATICAL MONOSPACE SMALL Z
+1D6A8..1D6C0 ; NFKC_QC; N # L& [25] MATHEMATICAL BOLD CAPITAL ALPHA..MATHEMATICAL BOLD CAPITAL OMEGA
+1D6C1 ; NFKC_QC; N # Sm MATHEMATICAL BOLD NABLA
+1D6C2..1D6DA ; NFKC_QC; N # L& [25] MATHEMATICAL BOLD SMALL ALPHA..MATHEMATICAL BOLD SMALL OMEGA
+1D6DB ; NFKC_QC; N # Sm MATHEMATICAL BOLD PARTIAL DIFFERENTIAL
+1D6DC..1D6FA ; NFKC_QC; N # L& [31] MATHEMATICAL BOLD EPSILON SYMBOL..MATHEMATICAL ITALIC CAPITAL OMEGA
+1D6FB ; NFKC_QC; N # Sm MATHEMATICAL ITALIC NABLA
+1D6FC..1D714 ; NFKC_QC; N # L& [25] MATHEMATICAL ITALIC SMALL ALPHA..MATHEMATICAL ITALIC SMALL OMEGA
+1D715 ; NFKC_QC; N # Sm MATHEMATICAL ITALIC PARTIAL DIFFERENTIAL
+1D716..1D734 ; NFKC_QC; N # L& [31] MATHEMATICAL ITALIC EPSILON SYMBOL..MATHEMATICAL BOLD ITALIC CAPITAL OMEGA
+1D735 ; NFKC_QC; N # Sm MATHEMATICAL BOLD ITALIC NABLA
+1D736..1D74E ; NFKC_QC; N # L& [25] MATHEMATICAL BOLD ITALIC SMALL ALPHA..MATHEMATICAL BOLD ITALIC SMALL OMEGA
+1D74F ; NFKC_QC; N # Sm MATHEMATICAL BOLD ITALIC PARTIAL DIFFERENTIAL
+1D750..1D76E ; NFKC_QC; N # L& [31] MATHEMATICAL BOLD ITALIC EPSILON SYMBOL..MATHEMATICAL SANS-SERIF BOLD CAPITAL OMEGA
+1D76F ; NFKC_QC; N # Sm MATHEMATICAL SANS-SERIF BOLD NABLA
+1D770..1D788 ; NFKC_QC; N # L& [25] MATHEMATICAL SANS-SERIF BOLD SMALL ALPHA..MATHEMATICAL SANS-SERIF BOLD SMALL OMEGA
+1D789 ; NFKC_QC; N # Sm MATHEMATICAL SANS-SERIF BOLD PARTIAL DIFFERENTIAL
+1D78A..1D7A8 ; NFKC_QC; N # L& [31] MATHEMATICAL SANS-SERIF BOLD EPSILON SYMBOL..MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL OMEGA
+1D7A9 ; NFKC_QC; N # Sm MATHEMATICAL SANS-SERIF BOLD ITALIC NABLA
+1D7AA..1D7C2 ; NFKC_QC; N # L& [25] MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ALPHA..MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL OMEGA
+1D7C3 ; NFKC_QC; N # Sm MATHEMATICAL SANS-SERIF BOLD ITALIC PARTIAL DIFFERENTIAL
+1D7C4..1D7C9 ; NFKC_QC; N # L& [6] MATHEMATICAL SANS-SERIF BOLD ITALIC EPSILON SYMBOL..MATHEMATICAL SANS-SERIF BOLD ITALIC PI SYMBOL
+1D7CE..1D7FF ; NFKC_QC; N # Nd [50] MATHEMATICAL BOLD DIGIT ZERO..MATHEMATICAL MONOSPACE DIGIT NINE
+2F800..2FA1D ; NFKC_QC; N # Lo [542] CJK COMPATIBILITY IDEOGRAPH-2F800..CJK COMPATIBILITY IDEOGRAPH-2FA1D
+
+# Total code points: 4319
+
+# ================================================
+
+# NFKC_Quick_Check=Maybe
+
+0300..0304 ; NFKC_QC; M # Mn [5] COMBINING GRAVE ACCENT..COMBINING MACRON
+0306..030C ; NFKC_QC; M # Mn [7] COMBINING BREVE..COMBINING CARON
+030F ; NFKC_QC; M # Mn COMBINING DOUBLE GRAVE ACCENT
+0311 ; NFKC_QC; M # Mn COMBINING INVERTED BREVE
+0313..0314 ; NFKC_QC; M # Mn [2] COMBINING COMMA ABOVE..COMBINING REVERSED COMMA ABOVE
+031B ; NFKC_QC; M # Mn COMBINING HORN
+0323..0328 ; NFKC_QC; M # Mn [6] COMBINING DOT BELOW..COMBINING OGONEK
+032D..032E ; NFKC_QC; M # Mn [2] COMBINING CIRCUMFLEX ACCENT BELOW..COMBINING BREVE BELOW
+0330..0331 ; NFKC_QC; M # Mn [2] COMBINING TILDE BELOW..COMBINING MACRON BELOW
+0338 ; NFKC_QC; M # Mn COMBINING LONG SOLIDUS OVERLAY
+0342 ; NFKC_QC; M # Mn COMBINING GREEK PERISPOMENI
+0345 ; NFKC_QC; M # Mn COMBINING GREEK YPOGEGRAMMENI
+0653..0655 ; NFKC_QC; M # Mn [3] ARABIC MADDAH ABOVE..ARABIC HAMZA BELOW
+093C ; NFKC_QC; M # Mn DEVANAGARI SIGN NUKTA
+09BE ; NFKC_QC; M # Mc BENGALI VOWEL SIGN AA
+09D7 ; NFKC_QC; M # Mc BENGALI AU LENGTH MARK
+0B3E ; NFKC_QC; M # Mc ORIYA VOWEL SIGN AA
+0B56 ; NFKC_QC; M # Mn ORIYA AI LENGTH MARK
+0B57 ; NFKC_QC; M # Mc ORIYA AU LENGTH MARK
+0BBE ; NFKC_QC; M # Mc TAMIL VOWEL SIGN AA
+0BD7 ; NFKC_QC; M # Mc TAMIL AU LENGTH MARK
+0C56 ; NFKC_QC; M # Mn TELUGU AI LENGTH MARK
+0CC2 ; NFKC_QC; M # Mc KANNADA VOWEL SIGN UU
+0CD5..0CD6 ; NFKC_QC; M # Mc [2] KANNADA LENGTH MARK..KANNADA AI LENGTH MARK
+0D3E ; NFKC_QC; M # Mc MALAYALAM VOWEL SIGN AA
+0D57 ; NFKC_QC; M # Mc MALAYALAM AU LENGTH MARK
+0DCA ; NFKC_QC; M # Mn SINHALA SIGN AL-LAKUNA
+0DCF ; NFKC_QC; M # Mc SINHALA VOWEL SIGN AELA-PILLA
+0DDF ; NFKC_QC; M # Mc SINHALA VOWEL SIGN GAYANUKITTA
+102E ; NFKC_QC; M # Mn MYANMAR VOWEL SIGN II
+1161..1175 ; NFKC_QC; M # Lo [21] HANGUL JUNGSEONG A..HANGUL JUNGSEONG I
+11A8..11C2 ; NFKC_QC; M # Lo [27] HANGUL JONGSEONG KIYEOK..HANGUL JONGSEONG HIEUH
+3099..309A ; NFKC_QC; M # Mn [2] COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK..COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
+
+# Total code points: 101
+
+# ================================================
+
+# Derived Property: Expands_On_NFD
+# Generated according to UAX #15.
+# Characters whose normalized length is not one.
+# WARNING: Normalization of STRINGS must use the algorithm in UAX #15 because characters may interact.
+# The length of a normalized string is not necessarily the sum of the lengths of the normalized characters!
+
+00C0..00C5 ; Expands_On_NFD # L& [6] LATIN CAPITAL LETTER A WITH GRAVE..LATIN CAPITAL LETTER A WITH RING ABOVE
+00C7..00CF ; Expands_On_NFD # L& [9] LATIN CAPITAL LETTER C WITH CEDILLA..LATIN CAPITAL LETTER I WITH DIAERESIS
+00D1..00D6 ; Expands_On_NFD # L& [6] LATIN CAPITAL LETTER N WITH TILDE..LATIN CAPITAL LETTER O WITH DIAERESIS
+00D9..00DD ; Expands_On_NFD # L& [5] LATIN CAPITAL LETTER U WITH GRAVE..LATIN CAPITAL LETTER Y WITH ACUTE
+00E0..00E5 ; Expands_On_NFD # L& [6] LATIN SMALL LETTER A WITH GRAVE..LATIN SMALL LETTER A WITH RING ABOVE
+00E7..00EF ; Expands_On_NFD # L& [9] LATIN SMALL LETTER C WITH CEDILLA..LATIN SMALL LETTER I WITH DIAERESIS
+00F1..00F6 ; Expands_On_NFD # L& [6] LATIN SMALL LETTER N WITH TILDE..LATIN SMALL LETTER O WITH DIAERESIS
+00F9..00FD ; Expands_On_NFD # L& [5] LATIN SMALL LETTER U WITH GRAVE..LATIN SMALL LETTER Y WITH ACUTE
+00FF..010F ; Expands_On_NFD # L& [17] LATIN SMALL LETTER Y WITH DIAERESIS..LATIN SMALL LETTER D WITH CARON
+0112..0125 ; Expands_On_NFD # L& [20] LATIN CAPITAL LETTER E WITH MACRON..LATIN SMALL LETTER H WITH CIRCUMFLEX
+0128..0130 ; Expands_On_NFD # L& [9] LATIN CAPITAL LETTER I WITH TILDE..LATIN CAPITAL LETTER I WITH DOT ABOVE
+0134..0137 ; Expands_On_NFD # L& [4] LATIN CAPITAL LETTER J WITH CIRCUMFLEX..LATIN SMALL LETTER K WITH CEDILLA
+0139..013E ; Expands_On_NFD # L& [6] LATIN CAPITAL LETTER L WITH ACUTE..LATIN SMALL LETTER L WITH CARON
+0143..0148 ; Expands_On_NFD # L& [6] LATIN CAPITAL LETTER N WITH ACUTE..LATIN SMALL LETTER N WITH CARON
+014C..0151 ; Expands_On_NFD # L& [6] LATIN CAPITAL LETTER O WITH MACRON..LATIN SMALL LETTER O WITH DOUBLE ACUTE
+0154..0165 ; Expands_On_NFD # L& [18] LATIN CAPITAL LETTER R WITH ACUTE..LATIN SMALL LETTER T WITH CARON
+0168..017E ; Expands_On_NFD # L& [23] LATIN CAPITAL LETTER U WITH TILDE..LATIN SMALL LETTER Z WITH CARON
+01A0..01A1 ; Expands_On_NFD # L& [2] LATIN CAPITAL LETTER O WITH HORN..LATIN SMALL LETTER O WITH HORN
+01AF..01B0 ; Expands_On_NFD # L& [2] LATIN CAPITAL LETTER U WITH HORN..LATIN SMALL LETTER U WITH HORN
+01CD..01DC ; Expands_On_NFD # L& [16] LATIN CAPITAL LETTER A WITH CARON..LATIN SMALL LETTER U WITH DIAERESIS AND GRAVE
+01DE..01E3 ; Expands_On_NFD # L& [6] LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON..LATIN SMALL LETTER AE WITH MACRON
+01E6..01F0 ; Expands_On_NFD # L& [11] LATIN CAPITAL LETTER G WITH CARON..LATIN SMALL LETTER J WITH CARON
+01F4..01F5 ; Expands_On_NFD # L& [2] LATIN CAPITAL LETTER G WITH ACUTE..LATIN SMALL LETTER G WITH ACUTE
+01F8..021B ; Expands_On_NFD # L& [36] LATIN CAPITAL LETTER N WITH GRAVE..LATIN SMALL LETTER T WITH COMMA BELOW
+021E..021F ; Expands_On_NFD # L& [2] LATIN CAPITAL LETTER H WITH CARON..LATIN SMALL LETTER H WITH CARON
+0226..0233 ; Expands_On_NFD # L& [14] LATIN CAPITAL LETTER A WITH DOT ABOVE..LATIN SMALL LETTER Y WITH MACRON
+0344 ; Expands_On_NFD # Mn COMBINING GREEK DIALYTIKA TONOS
+0385 ; Expands_On_NFD # Sk GREEK DIALYTIKA TONOS
+0386 ; Expands_On_NFD # L& GREEK CAPITAL LETTER ALPHA WITH TONOS
+0388..038A ; Expands_On_NFD # L& [3] GREEK CAPITAL LETTER EPSILON WITH TONOS..GREEK CAPITAL LETTER IOTA WITH TONOS
+038C ; Expands_On_NFD # L& GREEK CAPITAL LETTER OMICRON WITH TONOS
+038E..0390 ; Expands_On_NFD # L& [3] GREEK CAPITAL LETTER UPSILON WITH TONOS..GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
+03AA..03B0 ; Expands_On_NFD # L& [7] GREEK CAPITAL LETTER IOTA WITH DIALYTIKA..GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
+03CA..03CE ; Expands_On_NFD # L& [5] GREEK SMALL LETTER IOTA WITH DIALYTIKA..GREEK SMALL LETTER OMEGA WITH TONOS
+03D3..03D4 ; Expands_On_NFD # L& [2] GREEK UPSILON WITH ACUTE AND HOOK SYMBOL..GREEK UPSILON WITH DIAERESIS AND HOOK SYMBOL
+0400..0401 ; Expands_On_NFD # L& [2] CYRILLIC CAPITAL LETTER IE WITH GRAVE..CYRILLIC CAPITAL LETTER IO
+0403 ; Expands_On_NFD # L& CYRILLIC CAPITAL LETTER GJE
+0407 ; Expands_On_NFD # L& CYRILLIC CAPITAL LETTER YI
+040C..040E ; Expands_On_NFD # L& [3] CYRILLIC CAPITAL LETTER KJE..CYRILLIC CAPITAL LETTER SHORT U
+0419 ; Expands_On_NFD # L& CYRILLIC CAPITAL LETTER SHORT I
+0439 ; Expands_On_NFD # L& CYRILLIC SMALL LETTER SHORT I
+0450..0451 ; Expands_On_NFD # L& [2] CYRILLIC SMALL LETTER IE WITH GRAVE..CYRILLIC SMALL LETTER IO
+0453 ; Expands_On_NFD # L& CYRILLIC SMALL LETTER GJE
+0457 ; Expands_On_NFD # L& CYRILLIC SMALL LETTER YI
+045C..045E ; Expands_On_NFD # L& [3] CYRILLIC SMALL LETTER KJE..CYRILLIC SMALL LETTER SHORT U
+0476..0477 ; Expands_On_NFD # L& [2] CYRILLIC CAPITAL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT..CYRILLIC SMALL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT
+04C1..04C2 ; Expands_On_NFD # L& [2] CYRILLIC CAPITAL LETTER ZHE WITH BREVE..CYRILLIC SMALL LETTER ZHE WITH BREVE
+04D0..04D3 ; Expands_On_NFD # L& [4] CYRILLIC CAPITAL LETTER A WITH BREVE..CYRILLIC SMALL LETTER A WITH DIAERESIS
+04D6..04D7 ; Expands_On_NFD # L& [2] CYRILLIC CAPITAL LETTER IE WITH BREVE..CYRILLIC SMALL LETTER IE WITH BREVE
+04DA..04DF ; Expands_On_NFD # L& [6] CYRILLIC CAPITAL LETTER SCHWA WITH DIAERESIS..CYRILLIC SMALL LETTER ZE WITH DIAERESIS
+04E2..04E7 ; Expands_On_NFD # L& [6] CYRILLIC CAPITAL LETTER I WITH MACRON..CYRILLIC SMALL LETTER O WITH DIAERESIS
+04EA..04F5 ; Expands_On_NFD # L& [12] CYRILLIC CAPITAL LETTER BARRED O WITH DIAERESIS..CYRILLIC SMALL LETTER CHE WITH DIAERESIS
+04F8..04F9 ; Expands_On_NFD # L& [2] CYRILLIC CAPITAL LETTER YERU WITH DIAERESIS..CYRILLIC SMALL LETTER YERU WITH DIAERESIS
+0622..0626 ; Expands_On_NFD # Lo [5] ARABIC LETTER ALEF WITH MADDA ABOVE..ARABIC LETTER YEH WITH HAMZA ABOVE
+06C0 ; Expands_On_NFD # Lo ARABIC LETTER HEH WITH YEH ABOVE
+06C2 ; Expands_On_NFD # Lo ARABIC LETTER HEH GOAL WITH HAMZA ABOVE
+06D3 ; Expands_On_NFD # Lo ARABIC LETTER YEH BARREE WITH HAMZA ABOVE
+0929 ; Expands_On_NFD # Lo DEVANAGARI LETTER NNNA
+0931 ; Expands_On_NFD # Lo DEVANAGARI LETTER RRA
+0934 ; Expands_On_NFD # Lo DEVANAGARI LETTER LLLA
+0958..095F ; Expands_On_NFD # Lo [8] DEVANAGARI LETTER QA..DEVANAGARI LETTER YYA
+09CB..09CC ; Expands_On_NFD # Mc [2] BENGALI VOWEL SIGN O..BENGALI VOWEL SIGN AU
+09DC..09DD ; Expands_On_NFD # Lo [2] BENGALI LETTER RRA..BENGALI LETTER RHA
+09DF ; Expands_On_NFD # Lo BENGALI LETTER YYA
+0A33 ; Expands_On_NFD # Lo GURMUKHI LETTER LLA
+0A36 ; Expands_On_NFD # Lo GURMUKHI LETTER SHA
+0A59..0A5B ; Expands_On_NFD # Lo [3] GURMUKHI LETTER KHHA..GURMUKHI LETTER ZA
+0A5E ; Expands_On_NFD # Lo GURMUKHI LETTER FA
+0B48 ; Expands_On_NFD # Mc ORIYA VOWEL SIGN AI
+0B4B..0B4C ; Expands_On_NFD # Mc [2] ORIYA VOWEL SIGN O..ORIYA VOWEL SIGN AU
+0B5C..0B5D ; Expands_On_NFD # Lo [2] ORIYA LETTER RRA..ORIYA LETTER RHA
+0B94 ; Expands_On_NFD # Lo TAMIL LETTER AU
+0BCA..0BCC ; Expands_On_NFD # Mc [3] TAMIL VOWEL SIGN O..TAMIL VOWEL SIGN AU
+0C48 ; Expands_On_NFD # Mn TELUGU VOWEL SIGN AI
+0CC0 ; Expands_On_NFD # Mc KANNADA VOWEL SIGN II
+0CC7..0CC8 ; Expands_On_NFD # Mc [2] KANNADA VOWEL SIGN EE..KANNADA VOWEL SIGN AI
+0CCA..0CCB ; Expands_On_NFD # Mc [2] KANNADA VOWEL SIGN O..KANNADA VOWEL SIGN OO
+0D4A..0D4C ; Expands_On_NFD # Mc [3] MALAYALAM VOWEL SIGN O..MALAYALAM VOWEL SIGN AU
+0DDA ; Expands_On_NFD # Mc SINHALA VOWEL SIGN DIGA KOMBUVA
+0DDC..0DDE ; Expands_On_NFD # Mc [3] SINHALA VOWEL SIGN KOMBUVA HAA AELA-PILLA..SINHALA VOWEL SIGN KOMBUVA HAA GAYANUKITTA
+0F43 ; Expands_On_NFD # Lo TIBETAN LETTER GHA
+0F4D ; Expands_On_NFD # Lo TIBETAN LETTER DDHA
+0F52 ; Expands_On_NFD # Lo TIBETAN LETTER DHA
+0F57 ; Expands_On_NFD # Lo TIBETAN LETTER BHA
+0F5C ; Expands_On_NFD # Lo TIBETAN LETTER DZHA
+0F69 ; Expands_On_NFD # Lo TIBETAN LETTER KSSA
+0F73 ; Expands_On_NFD # Mn TIBETAN VOWEL SIGN II
+0F75..0F76 ; Expands_On_NFD # Mn [2] TIBETAN VOWEL SIGN UU..TIBETAN VOWEL SIGN VOCALIC R
+0F78 ; Expands_On_NFD # Mn TIBETAN VOWEL SIGN VOCALIC L
+0F81 ; Expands_On_NFD # Mn TIBETAN VOWEL SIGN REVERSED II
+0F93 ; Expands_On_NFD # Mn TIBETAN SUBJOINED LETTER GHA
+0F9D ; Expands_On_NFD # Mn TIBETAN SUBJOINED LETTER DDHA
+0FA2 ; Expands_On_NFD # Mn TIBETAN SUBJOINED LETTER DHA
+0FA7 ; Expands_On_NFD # Mn TIBETAN SUBJOINED LETTER BHA
+0FAC ; Expands_On_NFD # Mn TIBETAN SUBJOINED LETTER DZHA
+0FB9 ; Expands_On_NFD # Mn TIBETAN SUBJOINED LETTER KSSA
+1026 ; Expands_On_NFD # Lo MYANMAR LETTER UU
+1E00..1E99 ; Expands_On_NFD # L& [154] LATIN CAPITAL LETTER A WITH RING BELOW..LATIN SMALL LETTER Y WITH RING ABOVE
+1E9B ; Expands_On_NFD # L& LATIN SMALL LETTER LONG S WITH DOT ABOVE
+1EA0..1EF9 ; Expands_On_NFD # L& [90] LATIN CAPITAL LETTER A WITH DOT BELOW..LATIN SMALL LETTER Y WITH TILDE
+1F00..1F15 ; Expands_On_NFD # L& [22] GREEK SMALL LETTER ALPHA WITH PSILI..GREEK SMALL LETTER EPSILON WITH DASIA AND OXIA
+1F18..1F1D ; Expands_On_NFD # L& [6] GREEK CAPITAL LETTER EPSILON WITH PSILI..GREEK CAPITAL LETTER EPSILON WITH DASIA AND OXIA
+1F20..1F45 ; Expands_On_NFD # L& [38] GREEK SMALL LETTER ETA WITH PSILI..GREEK SMALL LETTER OMICRON WITH DASIA AND OXIA
+1F48..1F4D ; Expands_On_NFD # L& [6] GREEK CAPITAL LETTER OMICRON WITH PSILI..GREEK CAPITAL LETTER OMICRON WITH DASIA AND OXIA
+1F50..1F57 ; Expands_On_NFD # L& [8] GREEK SMALL LETTER UPSILON WITH PSILI..GREEK SMALL LETTER UPSILON WITH DASIA AND PERISPOMENI
+1F59 ; Expands_On_NFD # L& GREEK CAPITAL LETTER UPSILON WITH DASIA
+1F5B ; Expands_On_NFD # L& GREEK CAPITAL LETTER UPSILON WITH DASIA AND VARIA
+1F5D ; Expands_On_NFD # L& GREEK CAPITAL LETTER UPSILON WITH DASIA AND OXIA
+1F5F..1F7D ; Expands_On_NFD # L& [31] GREEK CAPITAL LETTER UPSILON WITH DASIA AND PERISPOMENI..GREEK SMALL LETTER OMEGA WITH OXIA
+1F80..1FB4 ; Expands_On_NFD # L& [53] GREEK SMALL LETTER ALPHA WITH PSILI AND YPOGEGRAMMENI..GREEK SMALL LETTER ALPHA WITH OXIA AND YPOGEGRAMMENI
+1FB6..1FBC ; Expands_On_NFD # L& [7] GREEK SMALL LETTER ALPHA WITH PERISPOMENI..GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI
+1FC1 ; Expands_On_NFD # Sk GREEK DIALYTIKA AND PERISPOMENI
+1FC2..1FC4 ; Expands_On_NFD # L& [3] GREEK SMALL LETTER ETA WITH VARIA AND YPOGEGRAMMENI..GREEK SMALL LETTER ETA WITH OXIA AND YPOGEGRAMMENI
+1FC6..1FCC ; Expands_On_NFD # L& [7] GREEK SMALL LETTER ETA WITH PERISPOMENI..GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI
+1FCD..1FCF ; Expands_On_NFD # Sk [3] GREEK PSILI AND VARIA..GREEK PSILI AND PERISPOMENI
+1FD0..1FD3 ; Expands_On_NFD # L& [4] GREEK SMALL LETTER IOTA WITH VRACHY..GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA
+1FD6..1FDB ; Expands_On_NFD # L& [6] GREEK SMALL LETTER IOTA WITH PERISPOMENI..GREEK CAPITAL LETTER IOTA WITH OXIA
+1FDD..1FDF ; Expands_On_NFD # Sk [3] GREEK DASIA AND VARIA..GREEK DASIA AND PERISPOMENI
+1FE0..1FEC ; Expands_On_NFD # L& [13] GREEK SMALL LETTER UPSILON WITH VRACHY..GREEK CAPITAL LETTER RHO WITH DASIA
+1FED..1FEE ; Expands_On_NFD # Sk [2] GREEK DIALYTIKA AND VARIA..GREEK DIALYTIKA AND OXIA
+1FF2..1FF4 ; Expands_On_NFD # L& [3] GREEK SMALL LETTER OMEGA WITH VARIA AND YPOGEGRAMMENI..GREEK SMALL LETTER OMEGA WITH OXIA AND YPOGEGRAMMENI
+1FF6..1FFC ; Expands_On_NFD # L& [7] GREEK SMALL LETTER OMEGA WITH PERISPOMENI..GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI
+212B ; Expands_On_NFD # L& ANGSTROM SIGN
+219A..219B ; Expands_On_NFD # Sm [2] LEFTWARDS ARROW WITH STROKE..RIGHTWARDS ARROW WITH STROKE
+21AE ; Expands_On_NFD # Sm LEFT RIGHT ARROW WITH STROKE
+21CD ; Expands_On_NFD # So LEFTWARDS DOUBLE ARROW WITH STROKE
+21CE..21CF ; Expands_On_NFD # Sm [2] LEFT RIGHT DOUBLE ARROW WITH STROKE..RIGHTWARDS DOUBLE ARROW WITH STROKE
+2204 ; Expands_On_NFD # Sm THERE DOES NOT EXIST
+2209 ; Expands_On_NFD # Sm NOT AN ELEMENT OF
+220C ; Expands_On_NFD # Sm DOES NOT CONTAIN AS MEMBER
+2224 ; Expands_On_NFD # Sm DOES NOT DIVIDE
+2226 ; Expands_On_NFD # Sm NOT PARALLEL TO
+2241 ; Expands_On_NFD # Sm NOT TILDE
+2244 ; Expands_On_NFD # Sm NOT ASYMPTOTICALLY EQUAL TO
+2247 ; Expands_On_NFD # Sm NEITHER APPROXIMATELY NOR ACTUALLY EQUAL TO
+2249 ; Expands_On_NFD # Sm NOT ALMOST EQUAL TO
+2260 ; Expands_On_NFD # Sm NOT EQUAL TO
+2262 ; Expands_On_NFD # Sm NOT IDENTICAL TO
+226D..2271 ; Expands_On_NFD # Sm [5] NOT EQUIVALENT TO..NEITHER GREATER-THAN NOR EQUAL TO
+2274..2275 ; Expands_On_NFD # Sm [2] NEITHER LESS-THAN NOR EQUIVALENT TO..NEITHER GREATER-THAN NOR EQUIVALENT TO
+2278..2279 ; Expands_On_NFD # Sm [2] NEITHER LESS-THAN NOR GREATER-THAN..NEITHER GREATER-THAN NOR LESS-THAN
+2280..2281 ; Expands_On_NFD # Sm [2] DOES NOT PRECEDE..DOES NOT SUCCEED
+2284..2285 ; Expands_On_NFD # Sm [2] NOT A SUBSET OF..NOT A SUPERSET OF
+2288..2289 ; Expands_On_NFD # Sm [2] NEITHER A SUBSET OF NOR EQUAL TO..NEITHER A SUPERSET OF NOR EQUAL TO
+22AC..22AF ; Expands_On_NFD # Sm [4] DOES NOT PROVE..NEGATED DOUBLE VERTICAL BAR DOUBLE RIGHT TURNSTILE
+22E0..22E3 ; Expands_On_NFD # Sm [4] DOES NOT PRECEDE OR EQUAL..NOT SQUARE ORIGINAL OF OR EQUAL TO
+22EA..22ED ; Expands_On_NFD # Sm [4] NOT NORMAL SUBGROUP OF..DOES NOT CONTAIN AS NORMAL SUBGROUP OR EQUAL
+2ADC ; Expands_On_NFD # Sm FORKING
+304C ; Expands_On_NFD # Lo HIRAGANA LETTER GA
+304E ; Expands_On_NFD # Lo HIRAGANA LETTER GI
+3050 ; Expands_On_NFD # Lo HIRAGANA LETTER GU
+3052 ; Expands_On_NFD # Lo HIRAGANA LETTER GE
+3054 ; Expands_On_NFD # Lo HIRAGANA LETTER GO
+3056 ; Expands_On_NFD # Lo HIRAGANA LETTER ZA
+3058 ; Expands_On_NFD # Lo HIRAGANA LETTER ZI
+305A ; Expands_On_NFD # Lo HIRAGANA LETTER ZU
+305C ; Expands_On_NFD # Lo HIRAGANA LETTER ZE
+305E ; Expands_On_NFD # Lo HIRAGANA LETTER ZO
+3060 ; Expands_On_NFD # Lo HIRAGANA LETTER DA
+3062 ; Expands_On_NFD # Lo HIRAGANA LETTER DI
+3065 ; Expands_On_NFD # Lo HIRAGANA LETTER DU
+3067 ; Expands_On_NFD # Lo HIRAGANA LETTER DE
+3069 ; Expands_On_NFD # Lo HIRAGANA LETTER DO
+3070..3071 ; Expands_On_NFD # Lo [2] HIRAGANA LETTER BA..HIRAGANA LETTER PA
+3073..3074 ; Expands_On_NFD # Lo [2] HIRAGANA LETTER BI..HIRAGANA LETTER PI
+3076..3077 ; Expands_On_NFD # Lo [2] HIRAGANA LETTER BU..HIRAGANA LETTER PU
+3079..307A ; Expands_On_NFD # Lo [2] HIRAGANA LETTER BE..HIRAGANA LETTER PE
+307C..307D ; Expands_On_NFD # Lo [2] HIRAGANA LETTER BO..HIRAGANA LETTER PO
+3094 ; Expands_On_NFD # Lo HIRAGANA LETTER VU
+309E ; Expands_On_NFD # Lm HIRAGANA VOICED ITERATION MARK
+30AC ; Expands_On_NFD # Lo KATAKANA LETTER GA
+30AE ; Expands_On_NFD # Lo KATAKANA LETTER GI
+30B0 ; Expands_On_NFD # Lo KATAKANA LETTER GU
+30B2 ; Expands_On_NFD # Lo KATAKANA LETTER GE
+30B4 ; Expands_On_NFD # Lo KATAKANA LETTER GO
+30B6 ; Expands_On_NFD # Lo KATAKANA LETTER ZA
+30B8 ; Expands_On_NFD # Lo KATAKANA LETTER ZI
+30BA ; Expands_On_NFD # Lo KATAKANA LETTER ZU
+30BC ; Expands_On_NFD # Lo KATAKANA LETTER ZE
+30BE ; Expands_On_NFD # Lo KATAKANA LETTER ZO
+30C0 ; Expands_On_NFD # Lo KATAKANA LETTER DA
+30C2 ; Expands_On_NFD # Lo KATAKANA LETTER DI
+30C5 ; Expands_On_NFD # Lo KATAKANA LETTER DU
+30C7 ; Expands_On_NFD # Lo KATAKANA LETTER DE
+30C9 ; Expands_On_NFD # Lo KATAKANA LETTER DO
+30D0..30D1 ; Expands_On_NFD # Lo [2] KATAKANA LETTER BA..KATAKANA LETTER PA
+30D3..30D4 ; Expands_On_NFD # Lo [2] KATAKANA LETTER BI..KATAKANA LETTER PI
+30D6..30D7 ; Expands_On_NFD # Lo [2] KATAKANA LETTER BU..KATAKANA LETTER PU
+30D9..30DA ; Expands_On_NFD # Lo [2] KATAKANA LETTER BE..KATAKANA LETTER PE
+30DC..30DD ; Expands_On_NFD # Lo [2] KATAKANA LETTER BO..KATAKANA LETTER PO
+30F4 ; Expands_On_NFD # Lo KATAKANA LETTER VU
+30F7..30FA ; Expands_On_NFD # Lo [4] KATAKANA LETTER VA..KATAKANA LETTER VO
+30FE ; Expands_On_NFD # Lm KATAKANA VOICED ITERATION MARK
+AC00..D7A3 ; Expands_On_NFD # Lo [11172] HANGUL SYLLABLE GA..HANGUL SYLLABLE HIH
+FB1D ; Expands_On_NFD # Lo HEBREW LETTER YOD WITH HIRIQ
+FB1F ; Expands_On_NFD # Lo HEBREW LIGATURE YIDDISH YOD YOD PATAH
+FB2A..FB36 ; Expands_On_NFD # Lo [13] HEBREW LETTER SHIN WITH SHIN DOT..HEBREW LETTER ZAYIN WITH DAGESH
+FB38..FB3C ; Expands_On_NFD # Lo [5] HEBREW LETTER TET WITH DAGESH..HEBREW LETTER LAMED WITH DAGESH
+FB3E ; Expands_On_NFD # Lo HEBREW LETTER MEM WITH DAGESH
+FB40..FB41 ; Expands_On_NFD # Lo [2] HEBREW LETTER NUN WITH DAGESH..HEBREW LETTER SAMEKH WITH DAGESH
+FB43..FB44 ; Expands_On_NFD # Lo [2] HEBREW LETTER FINAL PE WITH DAGESH..HEBREW LETTER PE WITH DAGESH
+FB46..FB4E ; Expands_On_NFD # Lo [9] HEBREW LETTER TSADI WITH DAGESH..HEBREW LETTER PE WITH RAFE
+1D15E..1D164 ; Expands_On_NFD # So [7] MUSICAL SYMBOL HALF NOTE..MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH NOTE
+1D1BB..1D1C0 ; Expands_On_NFD # So [6] MUSICAL SYMBOL MINIMA..MUSICAL SYMBOL FUSA BLACK
+
+# Total code points: 12192
+
+# ================================================
+
+# Derived Property: Expands_On_NFC
+# Generated according to UAX #15.
+# Characters whose normalized length is not one.
+# WARNING: Normalization of STRINGS must use the algorithm in UAX #15 because characters may interact.
+# The length of a normalized string is not necessarily the sum of the lengths of the normalized characters!
+
+0344 ; Expands_On_NFC # Mn COMBINING GREEK DIALYTIKA TONOS
+0958..095F ; Expands_On_NFC # Lo [8] DEVANAGARI LETTER QA..DEVANAGARI LETTER YYA
+09DC..09DD ; Expands_On_NFC # Lo [2] BENGALI LETTER RRA..BENGALI LETTER RHA
+09DF ; Expands_On_NFC # Lo BENGALI LETTER YYA
+0A33 ; Expands_On_NFC # Lo GURMUKHI LETTER LLA
+0A36 ; Expands_On_NFC # Lo GURMUKHI LETTER SHA
+0A59..0A5B ; Expands_On_NFC # Lo [3] GURMUKHI LETTER KHHA..GURMUKHI LETTER ZA
+0A5E ; Expands_On_NFC # Lo GURMUKHI LETTER FA
+0B5C..0B5D ; Expands_On_NFC # Lo [2] ORIYA LETTER RRA..ORIYA LETTER RHA
+0F43 ; Expands_On_NFC # Lo TIBETAN LETTER GHA
+0F4D ; Expands_On_NFC # Lo TIBETAN LETTER DDHA
+0F52 ; Expands_On_NFC # Lo TIBETAN LETTER DHA
+0F57 ; Expands_On_NFC # Lo TIBETAN LETTER BHA
+0F5C ; Expands_On_NFC # Lo TIBETAN LETTER DZHA
+0F69 ; Expands_On_NFC # Lo TIBETAN LETTER KSSA
+0F73 ; Expands_On_NFC # Mn TIBETAN VOWEL SIGN II
+0F75..0F76 ; Expands_On_NFC # Mn [2] TIBETAN VOWEL SIGN UU..TIBETAN VOWEL SIGN VOCALIC R
+0F78 ; Expands_On_NFC # Mn TIBETAN VOWEL SIGN VOCALIC L
+0F81 ; Expands_On_NFC # Mn TIBETAN VOWEL SIGN REVERSED II
+0F93 ; Expands_On_NFC # Mn TIBETAN SUBJOINED LETTER GHA
+0F9D ; Expands_On_NFC # Mn TIBETAN SUBJOINED LETTER DDHA
+0FA2 ; Expands_On_NFC # Mn TIBETAN SUBJOINED LETTER DHA
+0FA7 ; Expands_On_NFC # Mn TIBETAN SUBJOINED LETTER BHA
+0FAC ; Expands_On_NFC # Mn TIBETAN SUBJOINED LETTER DZHA
+0FB9 ; Expands_On_NFC # Mn TIBETAN SUBJOINED LETTER KSSA
+2ADC ; Expands_On_NFC # Sm FORKING
+FB1D ; Expands_On_NFC # Lo HEBREW LETTER YOD WITH HIRIQ
+FB1F ; Expands_On_NFC # Lo HEBREW LIGATURE YIDDISH YOD YOD PATAH
+FB2A..FB36 ; Expands_On_NFC # Lo [13] HEBREW LETTER SHIN WITH SHIN DOT..HEBREW LETTER ZAYIN WITH DAGESH
+FB38..FB3C ; Expands_On_NFC # Lo [5] HEBREW LETTER TET WITH DAGESH..HEBREW LETTER LAMED WITH DAGESH
+FB3E ; Expands_On_NFC # Lo HEBREW LETTER MEM WITH DAGESH
+FB40..FB41 ; Expands_On_NFC # Lo [2] HEBREW LETTER NUN WITH DAGESH..HEBREW LETTER SAMEKH WITH DAGESH
+FB43..FB44 ; Expands_On_NFC # Lo [2] HEBREW LETTER FINAL PE WITH DAGESH..HEBREW LETTER PE WITH DAGESH
+FB46..FB4E ; Expands_On_NFC # Lo [9] HEBREW LETTER TSADI WITH DAGESH..HEBREW LETTER PE WITH RAFE
+1D15E..1D164 ; Expands_On_NFC # So [7] MUSICAL SYMBOL HALF NOTE..MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH NOTE
+1D1BB..1D1C0 ; Expands_On_NFC # So [6] MUSICAL SYMBOL MINIMA..MUSICAL SYMBOL FUSA BLACK
+
+# Total code points: 85
+
+# ================================================
+
+# Derived Property: Expands_On_NFKD
+# Generated according to UAX #15.
+# Characters whose normalized length is not one.
+# WARNING: Normalization of STRINGS must use the algorithm in UAX #15 because characters may interact.
+# The length of a normalized string is not necessarily the sum of the lengths of the normalized characters!
+
+00A8 ; Expands_On_NFKD # Sk DIAERESIS
+00AF ; Expands_On_NFKD # Sk MACRON
+00B4 ; Expands_On_NFKD # Sk ACUTE ACCENT
+00B8 ; Expands_On_NFKD # Sk CEDILLA
+00BC..00BE ; Expands_On_NFKD # No [3] VULGAR FRACTION ONE QUARTER..VULGAR FRACTION THREE QUARTERS
+00C0..00C5 ; Expands_On_NFKD # L& [6] LATIN CAPITAL LETTER A WITH GRAVE..LATIN CAPITAL LETTER A WITH RING ABOVE
+00C7..00CF ; Expands_On_NFKD # L& [9] LATIN CAPITAL LETTER C WITH CEDILLA..LATIN CAPITAL LETTER I WITH DIAERESIS
+00D1..00D6 ; Expands_On_NFKD # L& [6] LATIN CAPITAL LETTER N WITH TILDE..LATIN CAPITAL LETTER O WITH DIAERESIS
+00D9..00DD ; Expands_On_NFKD # L& [5] LATIN CAPITAL LETTER U WITH GRAVE..LATIN CAPITAL LETTER Y WITH ACUTE
+00E0..00E5 ; Expands_On_NFKD # L& [6] LATIN SMALL LETTER A WITH GRAVE..LATIN SMALL LETTER A WITH RING ABOVE
+00E7..00EF ; Expands_On_NFKD # L& [9] LATIN SMALL LETTER C WITH CEDILLA..LATIN SMALL LETTER I WITH DIAERESIS
+00F1..00F6 ; Expands_On_NFKD # L& [6] LATIN SMALL LETTER N WITH TILDE..LATIN SMALL LETTER O WITH DIAERESIS
+00F9..00FD ; Expands_On_NFKD # L& [5] LATIN SMALL LETTER U WITH GRAVE..LATIN SMALL LETTER Y WITH ACUTE
+00FF..010F ; Expands_On_NFKD # L& [17] LATIN SMALL LETTER Y WITH DIAERESIS..LATIN SMALL LETTER D WITH CARON
+0112..0125 ; Expands_On_NFKD # L& [20] LATIN CAPITAL LETTER E WITH MACRON..LATIN SMALL LETTER H WITH CIRCUMFLEX
+0128..0130 ; Expands_On_NFKD # L& [9] LATIN CAPITAL LETTER I WITH TILDE..LATIN CAPITAL LETTER I WITH DOT ABOVE
+0132..0137 ; Expands_On_NFKD # L& [6] LATIN CAPITAL LIGATURE IJ..LATIN SMALL LETTER K WITH CEDILLA
+0139..0140 ; Expands_On_NFKD # L& [8] LATIN CAPITAL LETTER L WITH ACUTE..LATIN SMALL LETTER L WITH MIDDLE DOT
+0143..0149 ; Expands_On_NFKD # L& [7] LATIN CAPITAL LETTER N WITH ACUTE..LATIN SMALL LETTER N PRECEDED BY APOSTROPHE
+014C..0151 ; Expands_On_NFKD # L& [6] LATIN CAPITAL LETTER O WITH MACRON..LATIN SMALL LETTER O WITH DOUBLE ACUTE
+0154..0165 ; Expands_On_NFKD # L& [18] LATIN CAPITAL LETTER R WITH ACUTE..LATIN SMALL LETTER T WITH CARON
+0168..017E ; Expands_On_NFKD # L& [23] LATIN CAPITAL LETTER U WITH TILDE..LATIN SMALL LETTER Z WITH CARON
+01A0..01A1 ; Expands_On_NFKD # L& [2] LATIN CAPITAL LETTER O WITH HORN..LATIN SMALL LETTER O WITH HORN
+01AF..01B0 ; Expands_On_NFKD # L& [2] LATIN CAPITAL LETTER U WITH HORN..LATIN SMALL LETTER U WITH HORN
+01C4..01DC ; Expands_On_NFKD # L& [25] LATIN CAPITAL LETTER DZ WITH CARON..LATIN SMALL LETTER U WITH DIAERESIS AND GRAVE
+01DE..01E3 ; Expands_On_NFKD # L& [6] LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON..LATIN SMALL LETTER AE WITH MACRON
+01E6..01F5 ; Expands_On_NFKD # L& [16] LATIN CAPITAL LETTER G WITH CARON..LATIN SMALL LETTER G WITH ACUTE
+01F8..021B ; Expands_On_NFKD # L& [36] LATIN CAPITAL LETTER N WITH GRAVE..LATIN SMALL LETTER T WITH COMMA BELOW
+021E..021F ; Expands_On_NFKD # L& [2] LATIN CAPITAL LETTER H WITH CARON..LATIN SMALL LETTER H WITH CARON
+0226..0233 ; Expands_On_NFKD # L& [14] LATIN CAPITAL LETTER A WITH DOT ABOVE..LATIN SMALL LETTER Y WITH MACRON
+02D8..02DD ; Expands_On_NFKD # Sk [6] BREVE..DOUBLE ACUTE ACCENT
+0344 ; Expands_On_NFKD # Mn COMBINING GREEK DIALYTIKA TONOS
+037A ; Expands_On_NFKD # Lm GREEK YPOGEGRAMMENI
+0384..0385 ; Expands_On_NFKD # Sk [2] GREEK TONOS..GREEK DIALYTIKA TONOS
+0386 ; Expands_On_NFKD # L& GREEK CAPITAL LETTER ALPHA WITH TONOS
+0388..038A ; Expands_On_NFKD # L& [3] GREEK CAPITAL LETTER EPSILON WITH TONOS..GREEK CAPITAL LETTER IOTA WITH TONOS
+038C ; Expands_On_NFKD # L& GREEK CAPITAL LETTER OMICRON WITH TONOS
+038E..0390 ; Expands_On_NFKD # L& [3] GREEK CAPITAL LETTER UPSILON WITH TONOS..GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
+03AA..03B0 ; Expands_On_NFKD # L& [7] GREEK CAPITAL LETTER IOTA WITH DIALYTIKA..GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
+03CA..03CE ; Expands_On_NFKD # L& [5] GREEK SMALL LETTER IOTA WITH DIALYTIKA..GREEK SMALL LETTER OMEGA WITH TONOS
+03D3..03D4 ; Expands_On_NFKD # L& [2] GREEK UPSILON WITH ACUTE AND HOOK SYMBOL..GREEK UPSILON WITH DIAERESIS AND HOOK SYMBOL
+0400..0401 ; Expands_On_NFKD # L& [2] CYRILLIC CAPITAL LETTER IE WITH GRAVE..CYRILLIC CAPITAL LETTER IO
+0403 ; Expands_On_NFKD # L& CYRILLIC CAPITAL LETTER GJE
+0407 ; Expands_On_NFKD # L& CYRILLIC CAPITAL LETTER YI
+040C..040E ; Expands_On_NFKD # L& [3] CYRILLIC CAPITAL LETTER KJE..CYRILLIC CAPITAL LETTER SHORT U
+0419 ; Expands_On_NFKD # L& CYRILLIC CAPITAL LETTER SHORT I
+0439 ; Expands_On_NFKD # L& CYRILLIC SMALL LETTER SHORT I
+0450..0451 ; Expands_On_NFKD # L& [2] CYRILLIC SMALL LETTER IE WITH GRAVE..CYRILLIC SMALL LETTER IO
+0453 ; Expands_On_NFKD # L& CYRILLIC SMALL LETTER GJE
+0457 ; Expands_On_NFKD # L& CYRILLIC SMALL LETTER YI
+045C..045E ; Expands_On_NFKD # L& [3] CYRILLIC SMALL LETTER KJE..CYRILLIC SMALL LETTER SHORT U
+0476..0477 ; Expands_On_NFKD # L& [2] CYRILLIC CAPITAL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT..CYRILLIC SMALL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT
+04C1..04C2 ; Expands_On_NFKD # L& [2] CYRILLIC CAPITAL LETTER ZHE WITH BREVE..CYRILLIC SMALL LETTER ZHE WITH BREVE
+04D0..04D3 ; Expands_On_NFKD # L& [4] CYRILLIC CAPITAL LETTER A WITH BREVE..CYRILLIC SMALL LETTER A WITH DIAERESIS
+04D6..04D7 ; Expands_On_NFKD # L& [2] CYRILLIC CAPITAL LETTER IE WITH BREVE..CYRILLIC SMALL LETTER IE WITH BREVE
+04DA..04DF ; Expands_On_NFKD # L& [6] CYRILLIC CAPITAL LETTER SCHWA WITH DIAERESIS..CYRILLIC SMALL LETTER ZE WITH DIAERESIS
+04E2..04E7 ; Expands_On_NFKD # L& [6] CYRILLIC CAPITAL LETTER I WITH MACRON..CYRILLIC SMALL LETTER O WITH DIAERESIS
+04EA..04F5 ; Expands_On_NFKD # L& [12] CYRILLIC CAPITAL LETTER BARRED O WITH DIAERESIS..CYRILLIC SMALL LETTER CHE WITH DIAERESIS
+04F8..04F9 ; Expands_On_NFKD # L& [2] CYRILLIC CAPITAL LETTER YERU WITH DIAERESIS..CYRILLIC SMALL LETTER YERU WITH DIAERESIS
+0587 ; Expands_On_NFKD # L& ARMENIAN SMALL LIGATURE ECH YIWN
+0622..0626 ; Expands_On_NFKD # Lo [5] ARABIC LETTER ALEF WITH MADDA ABOVE..ARABIC LETTER YEH WITH HAMZA ABOVE
+0675..0678 ; Expands_On_NFKD # Lo [4] ARABIC LETTER HIGH HAMZA ALEF..ARABIC LETTER HIGH HAMZA YEH
+06C0 ; Expands_On_NFKD # Lo ARABIC LETTER HEH WITH YEH ABOVE
+06C2 ; Expands_On_NFKD # Lo ARABIC LETTER HEH GOAL WITH HAMZA ABOVE
+06D3 ; Expands_On_NFKD # Lo ARABIC LETTER YEH BARREE WITH HAMZA ABOVE
+0929 ; Expands_On_NFKD # Lo DEVANAGARI LETTER NNNA
+0931 ; Expands_On_NFKD # Lo DEVANAGARI LETTER RRA
+0934 ; Expands_On_NFKD # Lo DEVANAGARI LETTER LLLA
+0958..095F ; Expands_On_NFKD # Lo [8] DEVANAGARI LETTER QA..DEVANAGARI LETTER YYA
+09CB..09CC ; Expands_On_NFKD # Mc [2] BENGALI VOWEL SIGN O..BENGALI VOWEL SIGN AU
+09DC..09DD ; Expands_On_NFKD # Lo [2] BENGALI LETTER RRA..BENGALI LETTER RHA
+09DF ; Expands_On_NFKD # Lo BENGALI LETTER YYA
+0A33 ; Expands_On_NFKD # Lo GURMUKHI LETTER LLA
+0A36 ; Expands_On_NFKD # Lo GURMUKHI LETTER SHA
+0A59..0A5B ; Expands_On_NFKD # Lo [3] GURMUKHI LETTER KHHA..GURMUKHI LETTER ZA
+0A5E ; Expands_On_NFKD # Lo GURMUKHI LETTER FA
+0B48 ; Expands_On_NFKD # Mc ORIYA VOWEL SIGN AI
+0B4B..0B4C ; Expands_On_NFKD # Mc [2] ORIYA VOWEL SIGN O..ORIYA VOWEL SIGN AU
+0B5C..0B5D ; Expands_On_NFKD # Lo [2] ORIYA LETTER RRA..ORIYA LETTER RHA
+0B94 ; Expands_On_NFKD # Lo TAMIL LETTER AU
+0BCA..0BCC ; Expands_On_NFKD # Mc [3] TAMIL VOWEL SIGN O..TAMIL VOWEL SIGN AU
+0C48 ; Expands_On_NFKD # Mn TELUGU VOWEL SIGN AI
+0CC0 ; Expands_On_NFKD # Mc KANNADA VOWEL SIGN II
+0CC7..0CC8 ; Expands_On_NFKD # Mc [2] KANNADA VOWEL SIGN EE..KANNADA VOWEL SIGN AI
+0CCA..0CCB ; Expands_On_NFKD # Mc [2] KANNADA VOWEL SIGN O..KANNADA VOWEL SIGN OO
+0D4A..0D4C ; Expands_On_NFKD # Mc [3] MALAYALAM VOWEL SIGN O..MALAYALAM VOWEL SIGN AU
+0DDA ; Expands_On_NFKD # Mc SINHALA VOWEL SIGN DIGA KOMBUVA
+0DDC..0DDE ; Expands_On_NFKD # Mc [3] SINHALA VOWEL SIGN KOMBUVA HAA AELA-PILLA..SINHALA VOWEL SIGN KOMBUVA HAA GAYANUKITTA
+0E33 ; Expands_On_NFKD # Lo THAI CHARACTER SARA AM
+0EB3 ; Expands_On_NFKD # Lo LAO VOWEL SIGN AM
+0EDC..0EDD ; Expands_On_NFKD # Lo [2] LAO HO NO..LAO HO MO
+0F43 ; Expands_On_NFKD # Lo TIBETAN LETTER GHA
+0F4D ; Expands_On_NFKD # Lo TIBETAN LETTER DDHA
+0F52 ; Expands_On_NFKD # Lo TIBETAN LETTER DHA
+0F57 ; Expands_On_NFKD # Lo TIBETAN LETTER BHA
+0F5C ; Expands_On_NFKD # Lo TIBETAN LETTER DZHA
+0F69 ; Expands_On_NFKD # Lo TIBETAN LETTER KSSA
+0F73 ; Expands_On_NFKD # Mn TIBETAN VOWEL SIGN II
+0F75..0F79 ; Expands_On_NFKD # Mn [5] TIBETAN VOWEL SIGN UU..TIBETAN VOWEL SIGN VOCALIC LL
+0F81 ; Expands_On_NFKD # Mn TIBETAN VOWEL SIGN REVERSED II
+0F93 ; Expands_On_NFKD # Mn TIBETAN SUBJOINED LETTER GHA
+0F9D ; Expands_On_NFKD # Mn TIBETAN SUBJOINED LETTER DDHA
+0FA2 ; Expands_On_NFKD # Mn TIBETAN SUBJOINED LETTER DHA
+0FA7 ; Expands_On_NFKD # Mn TIBETAN SUBJOINED LETTER BHA
+0FAC ; Expands_On_NFKD # Mn TIBETAN SUBJOINED LETTER DZHA
+0FB9 ; Expands_On_NFKD # Mn TIBETAN SUBJOINED LETTER KSSA
+1026 ; Expands_On_NFKD # Lo MYANMAR LETTER UU
+1E00..1E9B ; Expands_On_NFKD # L& [156] LATIN CAPITAL LETTER A WITH RING BELOW..LATIN SMALL LETTER LONG S WITH DOT ABOVE
+1EA0..1EF9 ; Expands_On_NFKD # L& [90] LATIN CAPITAL LETTER A WITH DOT BELOW..LATIN SMALL LETTER Y WITH TILDE
+1F00..1F15 ; Expands_On_NFKD # L& [22] GREEK SMALL LETTER ALPHA WITH PSILI..GREEK SMALL LETTER EPSILON WITH DASIA AND OXIA
+1F18..1F1D ; Expands_On_NFKD # L& [6] GREEK CAPITAL LETTER EPSILON WITH PSILI..GREEK CAPITAL LETTER EPSILON WITH DASIA AND OXIA
+1F20..1F45 ; Expands_On_NFKD # L& [38] GREEK SMALL LETTER ETA WITH PSILI..GREEK SMALL LETTER OMICRON WITH DASIA AND OXIA
+1F48..1F4D ; Expands_On_NFKD # L& [6] GREEK CAPITAL LETTER OMICRON WITH PSILI..GREEK CAPITAL LETTER OMICRON WITH DASIA AND OXIA
+1F50..1F57 ; Expands_On_NFKD # L& [8] GREEK SMALL LETTER UPSILON WITH PSILI..GREEK SMALL LETTER UPSILON WITH DASIA AND PERISPOMENI
+1F59 ; Expands_On_NFKD # L& GREEK CAPITAL LETTER UPSILON WITH DASIA
+1F5B ; Expands_On_NFKD # L& GREEK CAPITAL LETTER UPSILON WITH DASIA AND VARIA
+1F5D ; Expands_On_NFKD # L& GREEK CAPITAL LETTER UPSILON WITH DASIA AND OXIA
+1F5F..1F7D ; Expands_On_NFKD # L& [31] GREEK CAPITAL LETTER UPSILON WITH DASIA AND PERISPOMENI..GREEK SMALL LETTER OMEGA WITH OXIA
+1F80..1FB4 ; Expands_On_NFKD # L& [53] GREEK SMALL LETTER ALPHA WITH PSILI AND YPOGEGRAMMENI..GREEK SMALL LETTER ALPHA WITH OXIA AND YPOGEGRAMMENI
+1FB6..1FBC ; Expands_On_NFKD # L& [7] GREEK SMALL LETTER ALPHA WITH PERISPOMENI..GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI
+1FBD ; Expands_On_NFKD # Sk GREEK KORONIS
+1FBF..1FC1 ; Expands_On_NFKD # Sk [3] GREEK PSILI..GREEK DIALYTIKA AND PERISPOMENI
+1FC2..1FC4 ; Expands_On_NFKD # L& [3] GREEK SMALL LETTER ETA WITH VARIA AND YPOGEGRAMMENI..GREEK SMALL LETTER ETA WITH OXIA AND YPOGEGRAMMENI
+1FC6..1FCC ; Expands_On_NFKD # L& [7] GREEK SMALL LETTER ETA WITH PERISPOMENI..GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI
+1FCD..1FCF ; Expands_On_NFKD # Sk [3] GREEK PSILI AND VARIA..GREEK PSILI AND PERISPOMENI
+1FD0..1FD3 ; Expands_On_NFKD # L& [4] GREEK SMALL LETTER IOTA WITH VRACHY..GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA
+1FD6..1FDB ; Expands_On_NFKD # L& [6] GREEK SMALL LETTER IOTA WITH PERISPOMENI..GREEK CAPITAL LETTER IOTA WITH OXIA
+1FDD..1FDF ; Expands_On_NFKD # Sk [3] GREEK DASIA AND VARIA..GREEK DASIA AND PERISPOMENI
+1FE0..1FEC ; Expands_On_NFKD # L& [13] GREEK SMALL LETTER UPSILON WITH VRACHY..GREEK CAPITAL LETTER RHO WITH DASIA
+1FED..1FEE ; Expands_On_NFKD # Sk [2] GREEK DIALYTIKA AND VARIA..GREEK DIALYTIKA AND OXIA
+1FF2..1FF4 ; Expands_On_NFKD # L& [3] GREEK SMALL LETTER OMEGA WITH VARIA AND YPOGEGRAMMENI..GREEK SMALL LETTER OMEGA WITH OXIA AND YPOGEGRAMMENI
+1FF6..1FFC ; Expands_On_NFKD # L& [7] GREEK SMALL LETTER OMEGA WITH PERISPOMENI..GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI
+1FFD..1FFE ; Expands_On_NFKD # Sk [2] GREEK OXIA..GREEK DASIA
+2017 ; Expands_On_NFKD # Po DOUBLE LOW LINE
+2025..2026 ; Expands_On_NFKD # Po [2] TWO DOT LEADER..HORIZONTAL ELLIPSIS
+2033..2034 ; Expands_On_NFKD # Po [2] DOUBLE PRIME..TRIPLE PRIME
+2036..2037 ; Expands_On_NFKD # Po [2] REVERSED DOUBLE PRIME..REVERSED TRIPLE PRIME
+203C ; Expands_On_NFKD # Po DOUBLE EXCLAMATION MARK
+203E ; Expands_On_NFKD # Po OVERLINE
+2047..2049 ; Expands_On_NFKD # Po [3] DOUBLE QUESTION MARK..EXCLAMATION QUESTION MARK
+2057 ; Expands_On_NFKD # Po QUADRUPLE PRIME
+20A8 ; Expands_On_NFKD # Sc RUPEE SIGN
+2100..2101 ; Expands_On_NFKD # So [2] ACCOUNT OF..ADDRESSED TO THE SUBJECT
+2103 ; Expands_On_NFKD # So DEGREE CELSIUS
+2105..2106 ; Expands_On_NFKD # So [2] CARE OF..CADA UNA
+2109 ; Expands_On_NFKD # So DEGREE FAHRENHEIT
+2116 ; Expands_On_NFKD # So NUMERO SIGN
+2120..2122 ; Expands_On_NFKD # So [3] SERVICE MARK..TRADE MARK SIGN
+212B ; Expands_On_NFKD # L& ANGSTROM SIGN
+213B ; Expands_On_NFKD # So FACSIMILE SIGN
+2153..215F ; Expands_On_NFKD # No [13] VULGAR FRACTION ONE THIRD..FRACTION NUMERATOR ONE
+2161..2163 ; Expands_On_NFKD # Nl [3] ROMAN NUMERAL TWO..ROMAN NUMERAL FOUR
+2165..2168 ; Expands_On_NFKD # Nl [4] ROMAN NUMERAL SIX..ROMAN NUMERAL NINE
+216A..216B ; Expands_On_NFKD # Nl [2] ROMAN NUMERAL ELEVEN..ROMAN NUMERAL TWELVE
+2171..2173 ; Expands_On_NFKD # Nl [3] SMALL ROMAN NUMERAL TWO..SMALL ROMAN NUMERAL FOUR
+2175..2178 ; Expands_On_NFKD # Nl [4] SMALL ROMAN NUMERAL SIX..SMALL ROMAN NUMERAL NINE
+217A..217B ; Expands_On_NFKD # Nl [2] SMALL ROMAN NUMERAL ELEVEN..SMALL ROMAN NUMERAL TWELVE
+219A..219B ; Expands_On_NFKD # Sm [2] LEFTWARDS ARROW WITH STROKE..RIGHTWARDS ARROW WITH STROKE
+21AE ; Expands_On_NFKD # Sm LEFT RIGHT ARROW WITH STROKE
+21CD ; Expands_On_NFKD # So LEFTWARDS DOUBLE ARROW WITH STROKE
+21CE..21CF ; Expands_On_NFKD # Sm [2] LEFT RIGHT DOUBLE ARROW WITH STROKE..RIGHTWARDS DOUBLE ARROW WITH STROKE
+2204 ; Expands_On_NFKD # Sm THERE DOES NOT EXIST
+2209 ; Expands_On_NFKD # Sm NOT AN ELEMENT OF
+220C ; Expands_On_NFKD # Sm DOES NOT CONTAIN AS MEMBER
+2224 ; Expands_On_NFKD # Sm DOES NOT DIVIDE
+2226 ; Expands_On_NFKD # Sm NOT PARALLEL TO
+222C..222D ; Expands_On_NFKD # Sm [2] DOUBLE INTEGRAL..TRIPLE INTEGRAL
+222F..2230 ; Expands_On_NFKD # Sm [2] SURFACE INTEGRAL..VOLUME INTEGRAL
+2241 ; Expands_On_NFKD # Sm NOT TILDE
+2244 ; Expands_On_NFKD # Sm NOT ASYMPTOTICALLY EQUAL TO
+2247 ; Expands_On_NFKD # Sm NEITHER APPROXIMATELY NOR ACTUALLY EQUAL TO
+2249 ; Expands_On_NFKD # Sm NOT ALMOST EQUAL TO
+2260 ; Expands_On_NFKD # Sm NOT EQUAL TO
+2262 ; Expands_On_NFKD # Sm NOT IDENTICAL TO
+226D..2271 ; Expands_On_NFKD # Sm [5] NOT EQUIVALENT TO..NEITHER GREATER-THAN NOR EQUAL TO
+2274..2275 ; Expands_On_NFKD # Sm [2] NEITHER LESS-THAN NOR EQUIVALENT TO..NEITHER GREATER-THAN NOR EQUIVALENT TO
+2278..2279 ; Expands_On_NFKD # Sm [2] NEITHER LESS-THAN NOR GREATER-THAN..NEITHER GREATER-THAN NOR LESS-THAN
+2280..2281 ; Expands_On_NFKD # Sm [2] DOES NOT PRECEDE..DOES NOT SUCCEED
+2284..2285 ; Expands_On_NFKD # Sm [2] NOT A SUBSET OF..NOT A SUPERSET OF
+2288..2289 ; Expands_On_NFKD # Sm [2] NEITHER A SUBSET OF NOR EQUAL TO..NEITHER A SUPERSET OF NOR EQUAL TO
+22AC..22AF ; Expands_On_NFKD # Sm [4] DOES NOT PROVE..NEGATED DOUBLE VERTICAL BAR DOUBLE RIGHT TURNSTILE
+22E0..22E3 ; Expands_On_NFKD # Sm [4] DOES NOT PRECEDE OR EQUAL..NOT SQUARE ORIGINAL OF OR EQUAL TO
+22EA..22ED ; Expands_On_NFKD # Sm [4] NOT NORMAL SUBGROUP OF..DOES NOT CONTAIN AS NORMAL SUBGROUP OR EQUAL
+2469..249B ; Expands_On_NFKD # No [51] CIRCLED NUMBER TEN..NUMBER TWENTY FULL STOP
+249C..24B5 ; Expands_On_NFKD # So [26] PARENTHESIZED LATIN SMALL LETTER A..PARENTHESIZED LATIN SMALL LETTER Z
+2A0C ; Expands_On_NFKD # Sm QUADRUPLE INTEGRAL OPERATOR
+2A74..2A76 ; Expands_On_NFKD # Sm [3] DOUBLE COLON EQUAL..THREE CONSECUTIVE EQUALS SIGNS
+2ADC ; Expands_On_NFKD # Sm FORKING
+304C ; Expands_On_NFKD # Lo HIRAGANA LETTER GA
+304E ; Expands_On_NFKD # Lo HIRAGANA LETTER GI
+3050 ; Expands_On_NFKD # Lo HIRAGANA LETTER GU
+3052 ; Expands_On_NFKD # Lo HIRAGANA LETTER GE
+3054 ; Expands_On_NFKD # Lo HIRAGANA LETTER GO
+3056 ; Expands_On_NFKD # Lo HIRAGANA LETTER ZA
+3058 ; Expands_On_NFKD # Lo HIRAGANA LETTER ZI
+305A ; Expands_On_NFKD # Lo HIRAGANA LETTER ZU
+305C ; Expands_On_NFKD # Lo HIRAGANA LETTER ZE
+305E ; Expands_On_NFKD # Lo HIRAGANA LETTER ZO
+3060 ; Expands_On_NFKD # Lo HIRAGANA LETTER DA
+3062 ; Expands_On_NFKD # Lo HIRAGANA LETTER DI
+3065 ; Expands_On_NFKD # Lo HIRAGANA LETTER DU
+3067 ; Expands_On_NFKD # Lo HIRAGANA LETTER DE
+3069 ; Expands_On_NFKD # Lo HIRAGANA LETTER DO
+3070..3071 ; Expands_On_NFKD # Lo [2] HIRAGANA LETTER BA..HIRAGANA LETTER PA
+3073..3074 ; Expands_On_NFKD # Lo [2] HIRAGANA LETTER BI..HIRAGANA LETTER PI
+3076..3077 ; Expands_On_NFKD # Lo [2] HIRAGANA LETTER BU..HIRAGANA LETTER PU
+3079..307A ; Expands_On_NFKD # Lo [2] HIRAGANA LETTER BE..HIRAGANA LETTER PE
+307C..307D ; Expands_On_NFKD # Lo [2] HIRAGANA LETTER BO..HIRAGANA LETTER PO
+3094 ; Expands_On_NFKD # Lo HIRAGANA LETTER VU
+309B..309C ; Expands_On_NFKD # Sk [2] KATAKANA-HIRAGANA VOICED SOUND MARK..KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
+309E ; Expands_On_NFKD # Lm HIRAGANA VOICED ITERATION MARK
+309F ; Expands_On_NFKD # Lo HIRAGANA DIGRAPH YORI
+30AC ; Expands_On_NFKD # Lo KATAKANA LETTER GA
+30AE ; Expands_On_NFKD # Lo KATAKANA LETTER GI
+30B0 ; Expands_On_NFKD # Lo KATAKANA LETTER GU
+30B2 ; Expands_On_NFKD # Lo KATAKANA LETTER GE
+30B4 ; Expands_On_NFKD # Lo KATAKANA LETTER GO
+30B6 ; Expands_On_NFKD # Lo KATAKANA LETTER ZA
+30B8 ; Expands_On_NFKD # Lo KATAKANA LETTER ZI
+30BA ; Expands_On_NFKD # Lo KATAKANA LETTER ZU
+30BC ; Expands_On_NFKD # Lo KATAKANA LETTER ZE
+30BE ; Expands_On_NFKD # Lo KATAKANA LETTER ZO
+30C0 ; Expands_On_NFKD # Lo KATAKANA LETTER DA
+30C2 ; Expands_On_NFKD # Lo KATAKANA LETTER DI
+30C5 ; Expands_On_NFKD # Lo KATAKANA LETTER DU
+30C7 ; Expands_On_NFKD # Lo KATAKANA LETTER DE
+30C9 ; Expands_On_NFKD # Lo KATAKANA LETTER DO
+30D0..30D1 ; Expands_On_NFKD # Lo [2] KATAKANA LETTER BA..KATAKANA LETTER PA
+30D3..30D4 ; Expands_On_NFKD # Lo [2] KATAKANA LETTER BI..KATAKANA LETTER PI
+30D6..30D7 ; Expands_On_NFKD # Lo [2] KATAKANA LETTER BU..KATAKANA LETTER PU
+30D9..30DA ; Expands_On_NFKD # Lo [2] KATAKANA LETTER BE..KATAKANA LETTER PE
+30DC..30DD ; Expands_On_NFKD # Lo [2] KATAKANA LETTER BO..KATAKANA LETTER PO
+30F4 ; Expands_On_NFKD # Lo KATAKANA LETTER VU
+30F7..30FA ; Expands_On_NFKD # Lo [4] KATAKANA LETTER VA..KATAKANA LETTER VO
+30FE ; Expands_On_NFKD # Lm KATAKANA VOICED ITERATION MARK
+30FF ; Expands_On_NFKD # Lo KATAKANA DIGRAPH KOTO
+3200..321E ; Expands_On_NFKD # So [31] PARENTHESIZED HANGUL KIYEOK..PARENTHESIZED KOREAN CHARACTER O HU
+3220..3229 ; Expands_On_NFKD # No [10] PARENTHESIZED IDEOGRAPH ONE..PARENTHESIZED IDEOGRAPH TEN
+322A..3243 ; Expands_On_NFKD # So [26] PARENTHESIZED IDEOGRAPH MOON..PARENTHESIZED IDEOGRAPH REACH
+3250 ; Expands_On_NFKD # So PARTNERSHIP SIGN
+3251..325F ; Expands_On_NFKD # No [15] CIRCLED NUMBER TWENTY ONE..CIRCLED NUMBER THIRTY FIVE
+326E..327D ; Expands_On_NFKD # So [16] CIRCLED HANGUL KIYEOK A..CIRCLED KOREAN CHARACTER JUEUI
+32B1..32BF ; Expands_On_NFKD # No [15] CIRCLED NUMBER THIRTY SIX..CIRCLED NUMBER FIFTY
+32C0..32CF ; Expands_On_NFKD # So [16] IDEOGRAPHIC TELEGRAPH SYMBOL FOR JANUARY..LIMITED LIABILITY SIGN
+3300..33FF ; Expands_On_NFKD # So [256] SQUARE APAATO..SQUARE GAL
+AC00..D7A3 ; Expands_On_NFKD # Lo [11172] HANGUL SYLLABLE GA..HANGUL SYLLABLE HIH
+FB00..FB06 ; Expands_On_NFKD # L& [7] LATIN SMALL LIGATURE FF..LATIN SMALL LIGATURE ST
+FB13..FB17 ; Expands_On_NFKD # L& [5] ARMENIAN SMALL LIGATURE MEN NOW..ARMENIAN SMALL LIGATURE MEN XEH
+FB1D ; Expands_On_NFKD # Lo HEBREW LETTER YOD WITH HIRIQ
+FB1F ; Expands_On_NFKD # Lo HEBREW LIGATURE YIDDISH YOD YOD PATAH
+FB2A..FB36 ; Expands_On_NFKD # Lo [13] HEBREW LETTER SHIN WITH SHIN DOT..HEBREW LETTER ZAYIN WITH DAGESH
+FB38..FB3C ; Expands_On_NFKD # Lo [5] HEBREW LETTER TET WITH DAGESH..HEBREW LETTER LAMED WITH DAGESH
+FB3E ; Expands_On_NFKD # Lo HEBREW LETTER MEM WITH DAGESH
+FB40..FB41 ; Expands_On_NFKD # Lo [2] HEBREW LETTER NUN WITH DAGESH..HEBREW LETTER SAMEKH WITH DAGESH
+FB43..FB44 ; Expands_On_NFKD # Lo [2] HEBREW LETTER FINAL PE WITH DAGESH..HEBREW LETTER PE WITH DAGESH
+FB46..FB4F ; Expands_On_NFKD # Lo [10] HEBREW LETTER TSADI WITH DAGESH..HEBREW LIGATURE ALEF LAMED
+FBA4..FBA5 ; Expands_On_NFKD # Lo [2] ARABIC LETTER HEH WITH YEH ABOVE ISOLATED FORM..ARABIC LETTER HEH WITH YEH ABOVE FINAL FORM
+FBB0..FBB1 ; Expands_On_NFKD # Lo [2] ARABIC LETTER YEH BARREE WITH HAMZA ABOVE ISOLATED FORM..ARABIC LETTER YEH BARREE WITH HAMZA ABOVE FINAL FORM
+FBDD ; Expands_On_NFKD # Lo ARABIC LETTER U WITH HAMZA ABOVE ISOLATED FORM
+FBEA..FBFB ; Expands_On_NFKD # Lo [18] ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF ISOLATED FORM..ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH HAMZA ABOVE WITH ALEF MAKSURA INITIAL FORM
+FC00..FD3D ; Expands_On_NFKD # Lo [318] ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH JEEM ISOLATED FORM..ARABIC LIGATURE ALEF WITH FATHATAN ISOLATED FORM
+FD50..FD8F ; Expands_On_NFKD # Lo [64] ARABIC LIGATURE TEH WITH JEEM WITH MEEM INITIAL FORM..ARABIC LIGATURE MEEM WITH KHAH WITH MEEM INITIAL FORM
+FD92..FDC7 ; Expands_On_NFKD # Lo [54] ARABIC LIGATURE MEEM WITH JEEM WITH KHAH INITIAL FORM..ARABIC LIGATURE NOON WITH JEEM WITH YEH FINAL FORM
+FDF0..FDFB ; Expands_On_NFKD # Lo [12] ARABIC LIGATURE SALLA USED AS KORANIC STOP SIGN ISOLATED FORM..ARABIC LIGATURE JALLAJALALOUHOU
+FDFC ; Expands_On_NFKD # Sc RIAL SIGN
+FE30 ; Expands_On_NFKD # Po PRESENTATION FORM FOR VERTICAL TWO DOT LEADER
+FE49..FE4C ; Expands_On_NFKD # Po [4] DASHED OVERLINE..DOUBLE WAVY OVERLINE
+FE70..FE72 ; Expands_On_NFKD # Lo [3] ARABIC FATHATAN ISOLATED FORM..ARABIC DAMMATAN ISOLATED FORM
+FE74 ; Expands_On_NFKD # Lo ARABIC KASRATAN ISOLATED FORM
+FE76..FE7F ; Expands_On_NFKD # Lo [10] ARABIC FATHA ISOLATED FORM..ARABIC SUKUN MEDIAL FORM
+FE81..FE8C ; Expands_On_NFKD # Lo [12] ARABIC LETTER ALEF WITH MADDA ABOVE ISOLATED FORM..ARABIC LETTER YEH WITH HAMZA ABOVE MEDIAL FORM
+FEF5..FEFC ; Expands_On_NFKD # Lo [8] ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM..ARABIC LIGATURE LAM WITH ALEF FINAL FORM
+FFE3 ; Expands_On_NFKD # Sk FULLWIDTH MACRON
+1D15E..1D164 ; Expands_On_NFKD # So [7] MUSICAL SYMBOL HALF NOTE..MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH NOTE
+1D1BB..1D1C0 ; Expands_On_NFKD # So [6] MUSICAL SYMBOL MINIMA..MUSICAL SYMBOL FUSA BLACK
+
+# Total code points: 13297
+
+# ================================================
+
+# Derived Property: Expands_On_NFKC
+# Generated according to UAX #15.
+# Characters whose normalized length is not one.
+# WARNING: Normalization of STRINGS must use the algorithm in UAX #15 because characters may interact.
+# The length of a normalized string is not necessarily the sum of the lengths of the normalized characters!
+
+00A8 ; Expands_On_NFKC # Sk DIAERESIS
+00AF ; Expands_On_NFKC # Sk MACRON
+00B4 ; Expands_On_NFKC # Sk ACUTE ACCENT
+00B8 ; Expands_On_NFKC # Sk CEDILLA
+00BC..00BE ; Expands_On_NFKC # No [3] VULGAR FRACTION ONE QUARTER..VULGAR FRACTION THREE QUARTERS
+0132..0133 ; Expands_On_NFKC # L& [2] LATIN CAPITAL LIGATURE IJ..LATIN SMALL LIGATURE IJ
+013F..0140 ; Expands_On_NFKC # L& [2] LATIN CAPITAL LETTER L WITH MIDDLE DOT..LATIN SMALL LETTER L WITH MIDDLE DOT
+0149 ; Expands_On_NFKC # L& LATIN SMALL LETTER N PRECEDED BY APOSTROPHE
+01C4..01CC ; Expands_On_NFKC # L& [9] LATIN CAPITAL LETTER DZ WITH CARON..LATIN SMALL LETTER NJ
+01F1..01F3 ; Expands_On_NFKC # L& [3] LATIN CAPITAL LETTER DZ..LATIN SMALL LETTER DZ
+02D8..02DD ; Expands_On_NFKC # Sk [6] BREVE..DOUBLE ACUTE ACCENT
+0344 ; Expands_On_NFKC # Mn COMBINING GREEK DIALYTIKA TONOS
+037A ; Expands_On_NFKC # Lm GREEK YPOGEGRAMMENI
+0384..0385 ; Expands_On_NFKC # Sk [2] GREEK TONOS..GREEK DIALYTIKA TONOS
+0587 ; Expands_On_NFKC # L& ARMENIAN SMALL LIGATURE ECH YIWN
+0675..0678 ; Expands_On_NFKC # Lo [4] ARABIC LETTER HIGH HAMZA ALEF..ARABIC LETTER HIGH HAMZA YEH
+0958..095F ; Expands_On_NFKC # Lo [8] DEVANAGARI LETTER QA..DEVANAGARI LETTER YYA
+09DC..09DD ; Expands_On_NFKC # Lo [2] BENGALI LETTER RRA..BENGALI LETTER RHA
+09DF ; Expands_On_NFKC # Lo BENGALI LETTER YYA
+0A33 ; Expands_On_NFKC # Lo GURMUKHI LETTER LLA
+0A36 ; Expands_On_NFKC # Lo GURMUKHI LETTER SHA
+0A59..0A5B ; Expands_On_NFKC # Lo [3] GURMUKHI LETTER KHHA..GURMUKHI LETTER ZA
+0A5E ; Expands_On_NFKC # Lo GURMUKHI LETTER FA
+0B5C..0B5D ; Expands_On_NFKC # Lo [2] ORIYA LETTER RRA..ORIYA LETTER RHA
+0E33 ; Expands_On_NFKC # Lo THAI CHARACTER SARA AM
+0EB3 ; Expands_On_NFKC # Lo LAO VOWEL SIGN AM
+0EDC..0EDD ; Expands_On_NFKC # Lo [2] LAO HO NO..LAO HO MO
+0F43 ; Expands_On_NFKC # Lo TIBETAN LETTER GHA
+0F4D ; Expands_On_NFKC # Lo TIBETAN LETTER DDHA
+0F52 ; Expands_On_NFKC # Lo TIBETAN LETTER DHA
+0F57 ; Expands_On_NFKC # Lo TIBETAN LETTER BHA
+0F5C ; Expands_On_NFKC # Lo TIBETAN LETTER DZHA
+0F69 ; Expands_On_NFKC # Lo TIBETAN LETTER KSSA
+0F73 ; Expands_On_NFKC # Mn TIBETAN VOWEL SIGN II
+0F75..0F79 ; Expands_On_NFKC # Mn [5] TIBETAN VOWEL SIGN UU..TIBETAN VOWEL SIGN VOCALIC LL
+0F81 ; Expands_On_NFKC # Mn TIBETAN VOWEL SIGN REVERSED II
+0F93 ; Expands_On_NFKC # Mn TIBETAN SUBJOINED LETTER GHA
+0F9D ; Expands_On_NFKC # Mn TIBETAN SUBJOINED LETTER DDHA
+0FA2 ; Expands_On_NFKC # Mn TIBETAN SUBJOINED LETTER DHA
+0FA7 ; Expands_On_NFKC # Mn TIBETAN SUBJOINED LETTER BHA
+0FAC ; Expands_On_NFKC # Mn TIBETAN SUBJOINED LETTER DZHA
+0FB9 ; Expands_On_NFKC # Mn TIBETAN SUBJOINED LETTER KSSA
+1E9A ; Expands_On_NFKC # L& LATIN SMALL LETTER A WITH RIGHT HALF RING
+1FBD ; Expands_On_NFKC # Sk GREEK KORONIS
+1FBF..1FC1 ; Expands_On_NFKC # Sk [3] GREEK PSILI..GREEK DIALYTIKA AND PERISPOMENI
+1FCD..1FCF ; Expands_On_NFKC # Sk [3] GREEK PSILI AND VARIA..GREEK PSILI AND PERISPOMENI
+1FDD..1FDF ; Expands_On_NFKC # Sk [3] GREEK DASIA AND VARIA..GREEK DASIA AND PERISPOMENI
+1FED..1FEE ; Expands_On_NFKC # Sk [2] GREEK DIALYTIKA AND VARIA..GREEK DIALYTIKA AND OXIA
+1FFD..1FFE ; Expands_On_NFKC # Sk [2] GREEK OXIA..GREEK DASIA
+2017 ; Expands_On_NFKC # Po DOUBLE LOW LINE
+2025..2026 ; Expands_On_NFKC # Po [2] TWO DOT LEADER..HORIZONTAL ELLIPSIS
+2033..2034 ; Expands_On_NFKC # Po [2] DOUBLE PRIME..TRIPLE PRIME
+2036..2037 ; Expands_On_NFKC # Po [2] REVERSED DOUBLE PRIME..REVERSED TRIPLE PRIME
+203C ; Expands_On_NFKC # Po DOUBLE EXCLAMATION MARK
+203E ; Expands_On_NFKC # Po OVERLINE
+2047..2049 ; Expands_On_NFKC # Po [3] DOUBLE QUESTION MARK..EXCLAMATION QUESTION MARK
+2057 ; Expands_On_NFKC # Po QUADRUPLE PRIME
+20A8 ; Expands_On_NFKC # Sc RUPEE SIGN
+2100..2101 ; Expands_On_NFKC # So [2] ACCOUNT OF..ADDRESSED TO THE SUBJECT
+2103 ; Expands_On_NFKC # So DEGREE CELSIUS
+2105..2106 ; Expands_On_NFKC # So [2] CARE OF..CADA UNA
+2109 ; Expands_On_NFKC # So DEGREE FAHRENHEIT
+2116 ; Expands_On_NFKC # So NUMERO SIGN
+2120..2122 ; Expands_On_NFKC # So [3] SERVICE MARK..TRADE MARK SIGN
+213B ; Expands_On_NFKC # So FACSIMILE SIGN
+2153..215F ; Expands_On_NFKC # No [13] VULGAR FRACTION ONE THIRD..FRACTION NUMERATOR ONE
+2161..2163 ; Expands_On_NFKC # Nl [3] ROMAN NUMERAL TWO..ROMAN NUMERAL FOUR
+2165..2168 ; Expands_On_NFKC # Nl [4] ROMAN NUMERAL SIX..ROMAN NUMERAL NINE
+216A..216B ; Expands_On_NFKC # Nl [2] ROMAN NUMERAL ELEVEN..ROMAN NUMERAL TWELVE
+2171..2173 ; Expands_On_NFKC # Nl [3] SMALL ROMAN NUMERAL TWO..SMALL ROMAN NUMERAL FOUR
+2175..2178 ; Expands_On_NFKC # Nl [4] SMALL ROMAN NUMERAL SIX..SMALL ROMAN NUMERAL NINE
+217A..217B ; Expands_On_NFKC # Nl [2] SMALL ROMAN NUMERAL ELEVEN..SMALL ROMAN NUMERAL TWELVE
+222C..222D ; Expands_On_NFKC # Sm [2] DOUBLE INTEGRAL..TRIPLE INTEGRAL
+222F..2230 ; Expands_On_NFKC # Sm [2] SURFACE INTEGRAL..VOLUME INTEGRAL
+2469..249B ; Expands_On_NFKC # No [51] CIRCLED NUMBER TEN..NUMBER TWENTY FULL STOP
+249C..24B5 ; Expands_On_NFKC # So [26] PARENTHESIZED LATIN SMALL LETTER A..PARENTHESIZED LATIN SMALL LETTER Z
+2A0C ; Expands_On_NFKC # Sm QUADRUPLE INTEGRAL OPERATOR
+2A74..2A76 ; Expands_On_NFKC # Sm [3] DOUBLE COLON EQUAL..THREE CONSECUTIVE EQUALS SIGNS
+2ADC ; Expands_On_NFKC # Sm FORKING
+309B..309C ; Expands_On_NFKC # Sk [2] KATAKANA-HIRAGANA VOICED SOUND MARK..KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
+309F ; Expands_On_NFKC # Lo HIRAGANA DIGRAPH YORI
+30FF ; Expands_On_NFKC # Lo KATAKANA DIGRAPH KOTO
+3200..321E ; Expands_On_NFKC # So [31] PARENTHESIZED HANGUL KIYEOK..PARENTHESIZED KOREAN CHARACTER O HU
+3220..3229 ; Expands_On_NFKC # No [10] PARENTHESIZED IDEOGRAPH ONE..PARENTHESIZED IDEOGRAPH TEN
+322A..3243 ; Expands_On_NFKC # So [26] PARENTHESIZED IDEOGRAPH MOON..PARENTHESIZED IDEOGRAPH REACH
+3250 ; Expands_On_NFKC # So PARTNERSHIP SIGN
+3251..325F ; Expands_On_NFKC # No [15] CIRCLED NUMBER TWENTY ONE..CIRCLED NUMBER THIRTY FIVE
+327C..327D ; Expands_On_NFKC # So [2] CIRCLED KOREAN CHARACTER CHAMKO..CIRCLED KOREAN CHARACTER JUEUI
+32B1..32BF ; Expands_On_NFKC # No [15] CIRCLED NUMBER THIRTY SIX..CIRCLED NUMBER FIFTY
+32C0..32CF ; Expands_On_NFKC # So [16] IDEOGRAPHIC TELEGRAPH SYMBOL FOR JANUARY..LIMITED LIABILITY SIGN
+3300..33FF ; Expands_On_NFKC # So [256] SQUARE APAATO..SQUARE GAL
+FB00..FB06 ; Expands_On_NFKC # L& [7] LATIN SMALL LIGATURE FF..LATIN SMALL LIGATURE ST
+FB13..FB17 ; Expands_On_NFKC # L& [5] ARMENIAN SMALL LIGATURE MEN NOW..ARMENIAN SMALL LIGATURE MEN XEH
+FB1D ; Expands_On_NFKC # Lo HEBREW LETTER YOD WITH HIRIQ
+FB1F ; Expands_On_NFKC # Lo HEBREW LIGATURE YIDDISH YOD YOD PATAH
+FB2A..FB36 ; Expands_On_NFKC # Lo [13] HEBREW LETTER SHIN WITH SHIN DOT..HEBREW LETTER ZAYIN WITH DAGESH
+FB38..FB3C ; Expands_On_NFKC # Lo [5] HEBREW LETTER TET WITH DAGESH..HEBREW LETTER LAMED WITH DAGESH
+FB3E ; Expands_On_NFKC # Lo HEBREW LETTER MEM WITH DAGESH
+FB40..FB41 ; Expands_On_NFKC # Lo [2] HEBREW LETTER NUN WITH DAGESH..HEBREW LETTER SAMEKH WITH DAGESH
+FB43..FB44 ; Expands_On_NFKC # Lo [2] HEBREW LETTER FINAL PE WITH DAGESH..HEBREW LETTER PE WITH DAGESH
+FB46..FB4F ; Expands_On_NFKC # Lo [10] HEBREW LETTER TSADI WITH DAGESH..HEBREW LIGATURE ALEF LAMED
+FBDD ; Expands_On_NFKC # Lo ARABIC LETTER U WITH HAMZA ABOVE ISOLATED FORM
+FBEA..FBFB ; Expands_On_NFKC # Lo [18] ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF ISOLATED FORM..ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH HAMZA ABOVE WITH ALEF MAKSURA INITIAL FORM
+FC00..FD3D ; Expands_On_NFKC # Lo [318] ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH JEEM ISOLATED FORM..ARABIC LIGATURE ALEF WITH FATHATAN ISOLATED FORM
+FD50..FD8F ; Expands_On_NFKC # Lo [64] ARABIC LIGATURE TEH WITH JEEM WITH MEEM INITIAL FORM..ARABIC LIGATURE MEEM WITH KHAH WITH MEEM INITIAL FORM
+FD92..FDC7 ; Expands_On_NFKC # Lo [54] ARABIC LIGATURE MEEM WITH JEEM WITH KHAH INITIAL FORM..ARABIC LIGATURE NOON WITH JEEM WITH YEH FINAL FORM
+FDF0..FDFB ; Expands_On_NFKC # Lo [12] ARABIC LIGATURE SALLA USED AS KORANIC STOP SIGN ISOLATED FORM..ARABIC LIGATURE JALLAJALALOUHOU
+FDFC ; Expands_On_NFKC # Sc RIAL SIGN
+FE30 ; Expands_On_NFKC # Po PRESENTATION FORM FOR VERTICAL TWO DOT LEADER
+FE49..FE4C ; Expands_On_NFKC # Po [4] DASHED OVERLINE..DOUBLE WAVY OVERLINE
+FE70..FE72 ; Expands_On_NFKC # Lo [3] ARABIC FATHATAN ISOLATED FORM..ARABIC DAMMATAN ISOLATED FORM
+FE74 ; Expands_On_NFKC # Lo ARABIC KASRATAN ISOLATED FORM
+FE76..FE7F ; Expands_On_NFKC # Lo [10] ARABIC FATHA ISOLATED FORM..ARABIC SUKUN MEDIAL FORM
+FEF5..FEFC ; Expands_On_NFKC # Lo [8] ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM..ARABIC LIGATURE LAM WITH ALEF FINAL FORM
+FFE3 ; Expands_On_NFKC # Sk FULLWIDTH MACRON
+1D15E..1D164 ; Expands_On_NFKC # So [7] MUSICAL SYMBOL HALF NOTE..MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH NOTE
+1D1BB..1D1C0 ; Expands_On_NFKC # So [6] MUSICAL SYMBOL MINIMA..MUSICAL SYMBOL FUSA BLACK
+
+# Total code points: 1170
diff --git a/third_party/heimdal/lib/wind/Makefile.am b/third_party/heimdal/lib/wind/Makefile.am
new file mode 100644
index 0000000..4a34496
--- /dev/null
+++ b/third_party/heimdal/lib/wind/Makefile.am
@@ -0,0 +1,147 @@
+# $Id: Makefile.am,v 1.1 2004/12/20 08:31:45 assar Exp $
+
+include $(top_srcdir)/Makefile.am.common
+
+lib_LTLIBRARIES = libwind.la
+
+built = \
+ bidi_table.c \
+ bidi_table.h \
+ combining_table.c \
+ combining_table.h \
+ errorlist_table.c \
+ errorlist_table.h \
+ map_table.c \
+ map_table.h \
+ normalize_table.c \
+ normalize_table.h
+
+built_tests = \
+ punycode_examples.h \
+ punycode_examples.c
+
+
+MAINTAINERCLEANFILES = $(built) $(built_tests)
+
+code = \
+ bidi.c \
+ combining.c \
+ doxygen.c \
+ errorlist.c \
+ map.c \
+ ldap.c \
+ normalize.c \
+ punycode.c \
+ stringprep.c \
+ wind.h \
+ windlocl.h \
+ utf8.c
+
+$(code:.c=.lo): $(built)
+
+dist_libwind_la_SOURCES = $(code) $(built)
+nodist_libwind_la_SOURCES = wind_err.c wind_err.h
+
+libwind_la_DEPENDENCIES = version-script.map
+
+dist_include_HEADERS = wind.h
+nodist_include_HEADERS = wind_err.h
+
+$(libwind_la_OBJECTS): wind_err.h
+
+libwind_la_LDFLAGS = -version-info 0:0:0
+
+libwind_la_LIBADD = \
+ $(LIB_roken) \
+ $(LIB_com_err)
+
+if versionscript
+libwind_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map
+endif
+
+BUILT_SOURCES = \
+ wind_err.c \
+ wind_err.h
+
+TESTS = \
+ $(check_PROGRAMS)
+
+check_PROGRAMS = \
+ test-bidi \
+ test-map \
+ test-rw \
+ test-normalize \
+ test-prohibited \
+ test-punycode \
+ test-ldap \
+ test-utf8
+
+test_punycode_SOURCES = \
+ test-punycode.c \
+ punycode_examples.c \
+ punycode_examples.h
+
+$(test_punycode_OBJECTS): $(built_tests)
+
+bin_PROGRAMS = idn-lookup
+
+idn_lookup_SOURCES = idn-lookup.c
+
+LDADD = libwind.la $(LIB_roken)
+
+if !MAINTAINER_MODE
+skip_python = test -f $@ ||
+endif
+
+map_table.h map_table.c: rfc3454.txt gen-map.py stringprep.py
+ $(skip_python) $(PYTHON) $(srcdir)/gen-map.py $(srcdir)/rfc3454.txt $(builddir)
+
+errorlist_table.h errorlist_table.c: rfc3454.txt gen-errorlist.py stringprep.py
+ $(skip_python) $(PYTHON) $(srcdir)/gen-errorlist.py $(srcdir)/rfc3454.txt $(builddir)
+
+normalize_table.h normalize_table.c: UnicodeData.txt CompositionExclusions-3.2.0.txt gen-normalize.py
+ $(skip_python) $(PYTHON) $(srcdir)/gen-normalize.py $(srcdir)/UnicodeData.txt $(srcdir)/CompositionExclusions-3.2.0.txt $(builddir)
+
+combining_table.h combining_table.c: UnicodeData.txt gen-combining.py
+ $(skip_python) $(PYTHON) $(srcdir)/gen-combining.py $(srcdir)/UnicodeData.txt $(builddir)
+
+bidi_table.h bidi_table.c: rfc3454.txt gen-bidi.py
+ $(skip_python) $(PYTHON) $(srcdir)/gen-bidi.py $(srcdir)/rfc3454.txt $(builddir)
+
+punycode_examples.h punycode_examples.c: gen-punycode-examples.py rfc3492.txt
+ $(PYTHON) $(srcdir)/gen-punycode-examples.py $(srcdir)/rfc3492.txt $(builddir)
+
+EXTRA_DIST = \
+ NTMakefile \
+ libwind-exports.def \
+ CompositionExclusions-3.2.0.txt \
+ DerivedNormalizationProps.txt \
+ NormalizationCorrections.txt \
+ NormalizationTest.txt \
+ UnicodeData.py \
+ UnicodeData.txt \
+ gen-bidi.py \
+ gen-combining.py \
+ gen-errorlist.py \
+ gen-map.py \
+ gen-normalize.py \
+ gen-punycode-examples.py \
+ generate.py \
+ rfc3454.py \
+ rfc3454.txt \
+ rfc3490.txt \
+ rfc3491.txt \
+ rfc3492.txt \
+ rfc4013.txt \
+ rfc4518.py \
+ rfc4518.txt \
+ stringprep.py \
+ util.py \
+ version-script.map \
+ wind_err.et
+
+CLEANFILES = \
+ wind_err.c \
+ wind_err.h
+
+wind_err.h: wind_err.et
diff --git a/third_party/heimdal/lib/wind/NTMakefile b/third_party/heimdal/lib/wind/NTMakefile
new file mode 100644
index 0000000..c6ec7c2
--- /dev/null
+++ b/third_party/heimdal/lib/wind/NTMakefile
@@ -0,0 +1,159 @@
+########################################################################
+#
+# Copyright (c) 2009, Secure Endpoints Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+
+RELDIR=lib\wind
+
+!include ../../windows/NTMakefile.w32
+
+libwind_OBJs= \
+ $(OBJ)\bidi.obj \
+ $(OBJ)\bidi_table.obj \
+ $(OBJ)\combining.obj \
+ $(OBJ)\combining_table.obj \
+ $(OBJ)\errorlist.obj \
+ $(OBJ)\errorlist_table.obj \
+ $(OBJ)\map.obj \
+ $(OBJ)\map_table.obj \
+ $(OBJ)\ldap.obj \
+ $(OBJ)\normalize.obj \
+ $(OBJ)\normalize_table.obj \
+ $(OBJ)\punycode.obj \
+ $(OBJ)\stringprep.obj \
+ $(OBJ)\wind_err.obj \
+ $(OBJ)\utf8.obj
+
+$(LIBWIND): $(libwind_OBJs)
+ $(LIBCON)
+
+INCFILES= \
+ $(INCDIR)\wind.h \
+ $(INCDIR)\wind_err.h \
+ $(INCDIR)\map_table.h \
+ $(INCDIR)\errorlist_table.h \
+ $(INCDIR)\normalize_table.h \
+ $(INCDIR)\combining_table.h \
+ $(INCDIR)\bidi_table.h \
+ $(INCDIR)\punycode_examples.h
+
+$(OBJ)\map_table.h $(OBJ)\map_table.c: rfc3454.txt gen-map.py stringprep.py
+ cd $(OBJ)
+ $(PYTHON) $(SRCDIR)\gen-map.py $(SRCDIR)\rfc3454.txt $(OBJ)
+ cd $(SRCDIR)
+
+$(OBJ)\errorlist_table.h $(OBJ)\errorlist_table.c: rfc3454.txt gen-errorlist.py stringprep.py
+ cd $(OBJ)
+ $(PYTHON) $(SRCDIR)\gen-errorlist.py $(SRCDIR)\rfc3454.txt $(OBJ)
+ cd $(SRCDIR)
+
+$(OBJ)\normalize_table.h $(OBJ)\normalize_table.c: UnicodeData.txt CompositionExclusions-3.2.0.txt gen-normalize.py
+ cd $(OBJ)
+ $(PYTHON) $(SRCDIR)\gen-normalize.py $(SRCDIR)\UnicodeData.txt $(SRCDIR)\CompositionExclusions-3.2.0.txt $(OBJ)
+ cd $(SRCDIR)
+
+$(OBJ)\combining_table.h $(OBJ)\combining_table.c: UnicodeData.txt gen-combining.py
+ cd $(OBJ)
+ $(PYTHON) $(SRCDIR)\gen-combining.py $(SRCDIR)\UnicodeData.txt $(OBJ)
+ cd $(SRCDIR)
+
+$(OBJ)\bidi_table.h $(OBJ)\bidi_table.c: rfc3454.txt gen-bidi.py
+ cd $(OBJ)
+ $(PYTHON) $(SRCDIR)\gen-bidi.py $(SRCDIR)\rfc3454.txt $(OBJ)
+ cd $(SRCDIR)
+
+$(OBJ)\punycode_examples.h $(OBJ)\punycode_examples.c: gen-punycode-examples.py rfc3492.txt
+ cd $(OBJ)
+ $(PYTHON) $(SRCDIR)\gen-punycode-examples.py $(SRCDIR)\rfc3492.txt $(OBJ)
+ cd $(SRCDIR)
+
+$(OBJ)\wind_err.c $(OBJ)\wind_err.h: wind_err.et
+ cd $(OBJ)
+ $(BINDIR)\compile_et.exe $(SRCDIR)\wind_err.et
+ cd $(SRCDIR)
+
+TEST_BINARIES=\
+ $(OBJ)\test-bidi.exe \
+ $(OBJ)\test-map.exe \
+ $(OBJ)\test-rw.exe \
+ $(OBJ)\test-normalize.exe \
+ $(OBJ)\test-prohibited.exe \
+ $(OBJ)\test-punycode.exe \
+ $(OBJ)\test-ldap.exe \
+ $(OBJ)\test-utf8.exe
+
+{$(OBJ)}.c{$(OBJ)}.obj::
+ $(C2OBJ_P) -I$(SRCDIR)
+
+{$(OBJ)}.obj{$(OBJ)}.exe:
+ $(EXECONLINK) $(LIBHEIMDAL) $(LIBROKEN)
+ $(EXEPREP_NODIST)
+
+$(OBJ)\test-bidi.exe: $(OBJ)\test-bidi.obj
+
+$(OBJ)\test-map.exe: $(OBJ)\test-map.obj
+
+$(OBJ)\test-rw.exe: $(OBJ)\test-rw.obj
+
+$(OBJ)\test-normalize.exe: $(OBJ)\test-normalize.obj
+
+$(OBJ)\test-prohibited.exe: $(OBJ)\test-prohibited.obj
+
+$(OBJ)\test-punycode.exe: $(OBJ)\test-punycode.obj $(OBJ)\punycode_examples.obj
+
+$(OBJ)\test-ldap.exe: $(OBJ)\test-ldap.obj
+
+$(OBJ)\test-utf8.exe: $(OBJ)\test-utf8.obj
+
+test-binaries: $(TEST_BINARIES)
+
+test-run:
+ cd $(OBJ)
+ -test-bidi.exe
+ -test-map.exe
+ -test-rw.exe
+ -test-normalize.exe $(SRCDIR)\NormalizationTest.txt
+ -test-prohibited.exe
+ -test-punycode.exe
+ -test-ldap.exe
+ -test-utf8.exe
+ cd $(SRCDIR)
+
+all:: $(INCFILES) $(LIBWIND)
+
+clean::
+ -$(RM) $(LIBWIND)
+ -$(RM) $(INCFILES)
+
+test:: test-binaries test-run
+
+test-exports:
+ $(PERL) ..\..\cf\w32-check-exported-symbols.pl --vs version-script.map --def libwind-exports.def
+
+test:: test-exports
diff --git a/third_party/heimdal/lib/wind/NormalizationCorrections.txt b/third_party/heimdal/lib/wind/NormalizationCorrections.txt
new file mode 100644
index 0000000..d76c150
--- /dev/null
+++ b/third_party/heimdal/lib/wind/NormalizationCorrections.txt
@@ -0,0 +1,43 @@
+# NormalizationCorrections-4.0.0.txt
+#
+# This file is a normative contributory data file in the
+# Unicode Character Database.
+#
+# The normalization stabilization policy of the Unicode
+# Consortium ordinarily precludes any change to the decomposition
+# for any character, once established in a relevant version
+# of the UnicodeData.txt data file. However, under certain
+# exceptional (and rare) conditions, an error in a decomposition
+# mapping may be discovered that is truly just an unintended
+# typo in the data, and not a matter of dubious interpretation.
+#
+# Whenever such an error may be found, and if it meets the
+# requirements for possible exceptions to normalization
+# stability, the correction is entered in this data file,
+# so that any implementation depending on absolute stability
+# of normalization, *including* any errors in the data, can
+# safely reconstruct the exact state of the data tables at
+# any given version of Unicode.
+#
+# Currently this list has exactly six entries in it, one for the
+# typo found and corrected in Corrigendum #3, and five for
+# the typos and misidentifications found and corrected in
+# Corrigendum #4. All efforts
+# will be made to keep the entries limited to just those fixes.
+#
+# Interpretation of the fields:
+# Field 1: Unicode code point
+# Field 2: Original (erroneous) decomposition
+# Field 3: Corrected decomposition
+# Field 4: Version of Unicode for which the correction was
+# entered into UnicodeData.txt, in n.n.n format.
+# Comment: Indicates the Unicode Corrigendum which documents
+# the correction
+#
+#
+F951;96FB;964B;3.2.0 # Corrigendum 3
+2F868;2136A;36FC;4.0.0 # Corrigendum 4
+2F874;5F33;5F53;4.0.0 # Corrigendum 4
+2F91F;43AB;243AB;4.0.0 # Corrigendum 4
+2F95F;7AAE;7AEE;4.0.0 # Corrigendum 4
+2F9BF;4D57;45D7;4.0.0 # Corrigendum 4
diff --git a/third_party/heimdal/lib/wind/NormalizationTest.txt b/third_party/heimdal/lib/wind/NormalizationTest.txt
new file mode 100644
index 0000000..afbb369
--- /dev/null
+++ b/third_party/heimdal/lib/wind/NormalizationTest.txt
@@ -0,0 +1,17166 @@
+# NormalizationTest-4.0.0.txt
+# Date: 2003-02-25,23:12:31 GMT [MD]
+#
+# Normalization Test Suite
+# Format:
+#
+# Columns (c1, c2,...) are separated by semicolons
+# Comments are indicated with hash marks
+#
+# CONFORMANCE:
+# 1. The following invariants must be true for all conformant implementations
+#
+# NFC
+# c2 == NFC(c1) == NFC(c2) == NFC(c3)
+# c4 == NFC(c4) == NFC(c5)
+#
+# NFD
+# c3 == NFD(c1) == NFD(c2) == NFD(c3)
+# c5 == NFD(c4) == NFD(c5)
+#
+# NFKC
+# c4 == NFKC(c1) == NFKC(c2) == NFKC(c3) == NFKC(c4) == NFKC(c5)
+#
+# NFKD
+# c5 == NFKD(c1) == NFKD(c2) == NFKD(c3) == NFKD(c4) == NFKD(c5)
+#
+# 2. For every code point X assigned in this version of Unicode that is not specifically
+# listed in Part 1, the following invariants must be true for all conformant
+# implementations:
+#
+# X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X)
+#
+@Part0 # Specific cases
+#
+1E0A;1E0A;0044 0307;1E0A;0044 0307; # (Ḋ; Ḋ; D◌̇; Ḋ; D◌̇; ) LATIN CAPITAL LETTER D WITH DOT ABOVE
+1E0C;1E0C;0044 0323;1E0C;0044 0323; # (Ḍ; Ḍ; D◌̣; Ḍ; D◌̣; ) LATIN CAPITAL LETTER D WITH DOT BELOW
+1E0A 0323;1E0C 0307;0044 0323 0307;1E0C 0307;0044 0323 0307; # (Ḋ◌̣; Ḍ◌̇; D◌̣◌̇; Ḍ◌̇; D◌̣◌̇; ) LATIN CAPITAL LETTER D WITH DOT ABOVE, COMBINING DOT BELOW
+1E0C 0307;1E0C 0307;0044 0323 0307;1E0C 0307;0044 0323 0307; # (Ḍ◌̇; Ḍ◌̇; D◌̣◌̇; Ḍ◌̇; D◌̣◌̇; ) LATIN CAPITAL LETTER D WITH DOT BELOW, COMBINING DOT ABOVE
+0044 0307 0323;1E0C 0307;0044 0323 0307;1E0C 0307;0044 0323 0307; # (D◌̇◌̣; Ḍ◌̇; D◌̣◌̇; Ḍ◌̇; D◌̣◌̇; ) LATIN CAPITAL LETTER D, COMBINING DOT ABOVE, COMBINING DOT BELOW
+0044 0323 0307;1E0C 0307;0044 0323 0307;1E0C 0307;0044 0323 0307; # (D◌̣◌̇; Ḍ◌̇; D◌̣◌̇; Ḍ◌̇; D◌̣◌̇; ) LATIN CAPITAL LETTER D, COMBINING DOT BELOW, COMBINING DOT ABOVE
+1E0A 031B;1E0A 031B;0044 031B 0307;1E0A 031B;0044 031B 0307; # (Ḋ◌̛; Ḋ◌̛; D◌̛◌̇; Ḋ◌̛; D◌̛◌̇; ) LATIN CAPITAL LETTER D WITH DOT ABOVE, COMBINING HORN
+1E0C 031B;1E0C 031B;0044 031B 0323;1E0C 031B;0044 031B 0323; # (Ḍ◌̛; Ḍ◌̛; D◌̛◌̣; Ḍ◌̛; D◌̛◌̣; ) LATIN CAPITAL LETTER D WITH DOT BELOW, COMBINING HORN
+1E0A 031B 0323;1E0C 031B 0307;0044 031B 0323 0307;1E0C 031B 0307;0044 031B 0323 0307; # (Ḋ◌̛◌̣; Ḍ◌̛◌̇; D◌̛◌̣◌̇; Ḍ◌̛◌̇; D◌̛◌̣◌̇; ) LATIN CAPITAL LETTER D WITH DOT ABOVE, COMBINING HORN, COMBINING DOT BELOW
+1E0C 031B 0307;1E0C 031B 0307;0044 031B 0323 0307;1E0C 031B 0307;0044 031B 0323 0307; # (Ḍ◌̛◌̇; Ḍ◌̛◌̇; D◌̛◌̣◌̇; Ḍ◌̛◌̇; D◌̛◌̣◌̇; ) LATIN CAPITAL LETTER D WITH DOT BELOW, COMBINING HORN, COMBINING DOT ABOVE
+0044 031B 0307 0323;1E0C 031B 0307;0044 031B 0323 0307;1E0C 031B 0307;0044 031B 0323 0307; # (D◌̛◌̇◌̣; Ḍ◌̛◌̇; D◌̛◌̣◌̇; Ḍ◌̛◌̇; D◌̛◌̣◌̇; ) LATIN CAPITAL LETTER D, COMBINING HORN, COMBINING DOT ABOVE, COMBINING DOT BELOW
+0044 031B 0323 0307;1E0C 031B 0307;0044 031B 0323 0307;1E0C 031B 0307;0044 031B 0323 0307; # (D◌̛◌̣◌̇; Ḍ◌̛◌̇; D◌̛◌̣◌̇; Ḍ◌̛◌̇; D◌̛◌̣◌̇; ) LATIN CAPITAL LETTER D, COMBINING HORN, COMBINING DOT BELOW, COMBINING DOT ABOVE
+00C8;00C8;0045 0300;00C8;0045 0300; # (È; È; E◌̀; È; E◌̀; ) LATIN CAPITAL LETTER E WITH GRAVE
+0112;0112;0045 0304;0112;0045 0304; # (Ē; Ē; E◌̄; Ē; E◌̄; ) LATIN CAPITAL LETTER E WITH MACRON
+0045 0300;00C8;0045 0300;00C8;0045 0300; # (E◌̀; È; E◌̀; È; E◌̀; ) LATIN CAPITAL LETTER E, COMBINING GRAVE ACCENT
+0045 0304;0112;0045 0304;0112;0045 0304; # (E◌̄; Ē; E◌̄; Ē; E◌̄; ) LATIN CAPITAL LETTER E, COMBINING MACRON
+1E14;1E14;0045 0304 0300;1E14;0045 0304 0300; # (Ḕ; Ḕ; E◌̄◌̀; Ḕ; E◌̄◌̀; ) LATIN CAPITAL LETTER E WITH MACRON AND GRAVE
+0112 0300;1E14;0045 0304 0300;1E14;0045 0304 0300; # (Ē◌̀; Ḕ; E◌̄◌̀; Ḕ; E◌̄◌̀; ) LATIN CAPITAL LETTER E WITH MACRON, COMBINING GRAVE ACCENT
+1E14 0304;1E14 0304;0045 0304 0300 0304;1E14 0304;0045 0304 0300 0304; # (Ḕ◌̄; Ḕ◌̄; E◌̄◌̀◌̄; Ḕ◌̄; E◌̄◌̀◌̄; ) LATIN CAPITAL LETTER E WITH MACRON AND GRAVE, COMBINING MACRON
+0045 0304 0300;1E14;0045 0304 0300;1E14;0045 0304 0300; # (E◌̄◌̀; Ḕ; E◌̄◌̀; Ḕ; E◌̄◌̀; ) LATIN CAPITAL LETTER E, COMBINING MACRON, COMBINING GRAVE ACCENT
+0045 0300 0304;00C8 0304;0045 0300 0304;00C8 0304;0045 0300 0304; # (E◌̀◌̄; È◌̄; E◌̀◌̄; È◌̄; E◌̀◌̄; ) LATIN CAPITAL LETTER E, COMBINING GRAVE ACCENT, COMBINING MACRON
+05B8 05B9 05B1 0591 05C3 05B0 05AC 059F;05B1 05B8 05B9 0591 05C3 05B0 05AC 059F;05B1 05B8 05B9 0591 05C3 05B0 05AC 059F;05B1 05B8 05B9 0591 05C3 05B0 05AC 059F;05B1 05B8 05B9 0591 05C3 05B0 05AC 059F; # (◌ָ◌ֹ◌ֱ◌֑׃◌ְ◌֬◌֟; ◌ֱ◌ָ◌ֹ◌֑׃◌ְ◌֬◌֟; ◌ֱ◌ָ◌ֹ◌֑׃◌ְ◌֬◌֟; ◌ֱ◌ָ◌ֹ◌֑׃◌ְ◌֬◌֟; ◌ֱ◌ָ◌ֹ◌֑׃◌ְ◌֬◌֟; ) HEBREW POINT QAMATS, HEBREW POINT HOLAM, HEBREW POINT HATAF SEGOL, HEBREW ACCENT ETNAHTA, HEBREW PUNCTUATION SOF PASUQ, HEBREW POINT SHEVA, HEBREW ACCENT ILUY, HEBREW ACCENT QARNEY PARA
+0592 05B7 05BC 05A5 05B0 05C0 05C4 05AD;05B0 05B7 05BC 05A5 0592 05C0 05AD 05C4;05B0 05B7 05BC 05A5 0592 05C0 05AD 05C4;05B0 05B7 05BC 05A5 0592 05C0 05AD 05C4;05B0 05B7 05BC 05A5 0592 05C0 05AD 05C4; # (◌֒◌ַ◌ּ◌֥◌ְ׀◌ׄ◌֭; ◌ְ◌ַ◌ּ◌֥◌֒׀◌֭◌ׄ; ◌ְ◌ַ◌ּ◌֥◌֒׀◌֭◌ׄ; ◌ְ◌ַ◌ּ◌֥◌֒׀◌֭◌ׄ; ◌ְ◌ַ◌ּ◌֥◌֒׀◌֭◌ׄ; ) HEBREW ACCENT SEGOL, HEBREW POINT PATAH, HEBREW POINT DAGESH OR MAPIQ, HEBREW ACCENT MERKHA, HEBREW POINT SHEVA, HEBREW PUNCTUATION PASEQ, HEBREW MARK UPPER DOT, HEBREW ACCENT DEHI
+#
+@Part1 # Character by character test
+# All characters not explicitly occurring in c1 of Part 1 have identical NFC, D, KC, KD forms.
+#
+00A0;00A0;00A0;0020;0020; # ( ;  ;  ; ; ; ) NO-BREAK SPACE
+00A8;00A8;00A8;0020 0308;0020 0308; # (¨; ¨; ¨; ◌̈; ◌̈; ) DIAERESIS
+00AA;00AA;00AA;0061;0061; # (ª; ª; ª; a; a; ) FEMININE ORDINAL INDICATOR
+00AF;00AF;00AF;0020 0304;0020 0304; # (¯; ¯; ¯; ◌̄; ◌̄; ) MACRON
+00B2;00B2;00B2;0032;0032; # (²; ²; ²; 2; 2; ) SUPERSCRIPT TWO
+00B3;00B3;00B3;0033;0033; # (³; ³; ³; 3; 3; ) SUPERSCRIPT THREE
+00B4;00B4;00B4;0020 0301;0020 0301; # (´; ´; ´; ◌́; ◌́; ) ACUTE ACCENT
+00B5;00B5;00B5;03BC;03BC; # (µ; µ; µ; μ; μ; ) MICRO SIGN
+00B8;00B8;00B8;0020 0327;0020 0327; # (¸; ¸; ¸; ◌̧; ◌̧; ) CEDILLA
+00B9;00B9;00B9;0031;0031; # (¹; ¹; ¹; 1; 1; ) SUPERSCRIPT ONE
+00BA;00BA;00BA;006F;006F; # (º; º; º; o; o; ) MASCULINE ORDINAL INDICATOR
+00BC;00BC;00BC;0031 2044 0034;0031 2044 0034; # (¼; ¼; ¼; 1⁄4; 1⁄4; ) VULGAR FRACTION ONE QUARTER
+00BD;00BD;00BD;0031 2044 0032;0031 2044 0032; # (½; ½; ½; 1⁄2; 1⁄2; ) VULGAR FRACTION ONE HALF
+00BE;00BE;00BE;0033 2044 0034;0033 2044 0034; # (¾; ¾; ¾; 3⁄4; 3⁄4; ) VULGAR FRACTION THREE QUARTERS
+00C0;00C0;0041 0300;00C0;0041 0300; # (À; À; A◌̀; À; A◌̀; ) LATIN CAPITAL LETTER A WITH GRAVE
+00C1;00C1;0041 0301;00C1;0041 0301; # (Á; Á; A◌́; Á; A◌́; ) LATIN CAPITAL LETTER A WITH ACUTE
+00C2;00C2;0041 0302;00C2;0041 0302; # (Â; Â; A◌̂; Â; A◌̂; ) LATIN CAPITAL LETTER A WITH CIRCUMFLEX
+00C3;00C3;0041 0303;00C3;0041 0303; # (Ã; Ã; A◌̃; Ã; A◌̃; ) LATIN CAPITAL LETTER A WITH TILDE
+00C4;00C4;0041 0308;00C4;0041 0308; # (Ä; Ä; A◌̈; Ä; A◌̈; ) LATIN CAPITAL LETTER A WITH DIAERESIS
+00C5;00C5;0041 030A;00C5;0041 030A; # (Å; Å; A◌̊; Å; A◌̊; ) LATIN CAPITAL LETTER A WITH RING ABOVE
+00C7;00C7;0043 0327;00C7;0043 0327; # (Ç; Ç; C◌̧; Ç; C◌̧; ) LATIN CAPITAL LETTER C WITH CEDILLA
+00C8;00C8;0045 0300;00C8;0045 0300; # (È; È; E◌̀; È; E◌̀; ) LATIN CAPITAL LETTER E WITH GRAVE
+00C9;00C9;0045 0301;00C9;0045 0301; # (É; É; E◌́; É; E◌́; ) LATIN CAPITAL LETTER E WITH ACUTE
+00CA;00CA;0045 0302;00CA;0045 0302; # (Ê; Ê; E◌̂; Ê; E◌̂; ) LATIN CAPITAL LETTER E WITH CIRCUMFLEX
+00CB;00CB;0045 0308;00CB;0045 0308; # (Ë; Ë; E◌̈; Ë; E◌̈; ) LATIN CAPITAL LETTER E WITH DIAERESIS
+00CC;00CC;0049 0300;00CC;0049 0300; # (Ì; Ì; I◌̀; Ì; I◌̀; ) LATIN CAPITAL LETTER I WITH GRAVE
+00CD;00CD;0049 0301;00CD;0049 0301; # (Í; Í; I◌́; Í; I◌́; ) LATIN CAPITAL LETTER I WITH ACUTE
+00CE;00CE;0049 0302;00CE;0049 0302; # (Î; Î; I◌̂; Î; I◌̂; ) LATIN CAPITAL LETTER I WITH CIRCUMFLEX
+00CF;00CF;0049 0308;00CF;0049 0308; # (Ï; Ï; I◌̈; Ï; I◌̈; ) LATIN CAPITAL LETTER I WITH DIAERESIS
+00D1;00D1;004E 0303;00D1;004E 0303; # (Ñ; Ñ; N◌̃; Ñ; N◌̃; ) LATIN CAPITAL LETTER N WITH TILDE
+00D2;00D2;004F 0300;00D2;004F 0300; # (Ò; Ò; O◌̀; Ò; O◌̀; ) LATIN CAPITAL LETTER O WITH GRAVE
+00D3;00D3;004F 0301;00D3;004F 0301; # (Ó; Ó; O◌́; Ó; O◌́; ) LATIN CAPITAL LETTER O WITH ACUTE
+00D4;00D4;004F 0302;00D4;004F 0302; # (Ô; Ô; O◌̂; Ô; O◌̂; ) LATIN CAPITAL LETTER O WITH CIRCUMFLEX
+00D5;00D5;004F 0303;00D5;004F 0303; # (Õ; Õ; O◌̃; Õ; O◌̃; ) LATIN CAPITAL LETTER O WITH TILDE
+00D6;00D6;004F 0308;00D6;004F 0308; # (Ö; Ö; O◌̈; Ö; O◌̈; ) LATIN CAPITAL LETTER O WITH DIAERESIS
+00D9;00D9;0055 0300;00D9;0055 0300; # (Ù; Ù; U◌̀; Ù; U◌̀; ) LATIN CAPITAL LETTER U WITH GRAVE
+00DA;00DA;0055 0301;00DA;0055 0301; # (Ú; Ú; U◌́; Ú; U◌́; ) LATIN CAPITAL LETTER U WITH ACUTE
+00DB;00DB;0055 0302;00DB;0055 0302; # (Û; Û; U◌̂; Û; U◌̂; ) LATIN CAPITAL LETTER U WITH CIRCUMFLEX
+00DC;00DC;0055 0308;00DC;0055 0308; # (Ü; Ü; U◌̈; Ü; U◌̈; ) LATIN CAPITAL LETTER U WITH DIAERESIS
+00DD;00DD;0059 0301;00DD;0059 0301; # (Ý; Ý; Y◌́; Ý; Y◌́; ) LATIN CAPITAL LETTER Y WITH ACUTE
+00E0;00E0;0061 0300;00E0;0061 0300; # (à; à; a◌̀; à; a◌̀; ) LATIN SMALL LETTER A WITH GRAVE
+00E1;00E1;0061 0301;00E1;0061 0301; # (á; á; a◌́; á; a◌́; ) LATIN SMALL LETTER A WITH ACUTE
+00E2;00E2;0061 0302;00E2;0061 0302; # (â; â; a◌̂; â; a◌̂; ) LATIN SMALL LETTER A WITH CIRCUMFLEX
+00E3;00E3;0061 0303;00E3;0061 0303; # (ã; ã; a◌̃; ã; a◌̃; ) LATIN SMALL LETTER A WITH TILDE
+00E4;00E4;0061 0308;00E4;0061 0308; # (ä; ä; a◌̈; ä; a◌̈; ) LATIN SMALL LETTER A WITH DIAERESIS
+00E5;00E5;0061 030A;00E5;0061 030A; # (å; å; a◌̊; å; a◌̊; ) LATIN SMALL LETTER A WITH RING ABOVE
+00E7;00E7;0063 0327;00E7;0063 0327; # (ç; ç; c◌̧; ç; c◌̧; ) LATIN SMALL LETTER C WITH CEDILLA
+00E8;00E8;0065 0300;00E8;0065 0300; # (è; è; e◌̀; è; e◌̀; ) LATIN SMALL LETTER E WITH GRAVE
+00E9;00E9;0065 0301;00E9;0065 0301; # (é; é; e◌́; é; e◌́; ) LATIN SMALL LETTER E WITH ACUTE
+00EA;00EA;0065 0302;00EA;0065 0302; # (ê; ê; e◌̂; ê; e◌̂; ) LATIN SMALL LETTER E WITH CIRCUMFLEX
+00EB;00EB;0065 0308;00EB;0065 0308; # (ë; ë; e◌̈; ë; e◌̈; ) LATIN SMALL LETTER E WITH DIAERESIS
+00EC;00EC;0069 0300;00EC;0069 0300; # (ì; ì; i◌̀; ì; i◌̀; ) LATIN SMALL LETTER I WITH GRAVE
+00ED;00ED;0069 0301;00ED;0069 0301; # (í; í; i◌́; í; i◌́; ) LATIN SMALL LETTER I WITH ACUTE
+00EE;00EE;0069 0302;00EE;0069 0302; # (î; î; i◌̂; î; i◌̂; ) LATIN SMALL LETTER I WITH CIRCUMFLEX
+00EF;00EF;0069 0308;00EF;0069 0308; # (ï; ï; i◌̈; ï; i◌̈; ) LATIN SMALL LETTER I WITH DIAERESIS
+00F1;00F1;006E 0303;00F1;006E 0303; # (ñ; ñ; n◌̃; ñ; n◌̃; ) LATIN SMALL LETTER N WITH TILDE
+00F2;00F2;006F 0300;00F2;006F 0300; # (ò; ò; o◌̀; ò; o◌̀; ) LATIN SMALL LETTER O WITH GRAVE
+00F3;00F3;006F 0301;00F3;006F 0301; # (ó; ó; o◌́; ó; o◌́; ) LATIN SMALL LETTER O WITH ACUTE
+00F4;00F4;006F 0302;00F4;006F 0302; # (ô; ô; o◌̂; ô; o◌̂; ) LATIN SMALL LETTER O WITH CIRCUMFLEX
+00F5;00F5;006F 0303;00F5;006F 0303; # (õ; õ; o◌̃; õ; o◌̃; ) LATIN SMALL LETTER O WITH TILDE
+00F6;00F6;006F 0308;00F6;006F 0308; # (ö; ö; o◌̈; ö; o◌̈; ) LATIN SMALL LETTER O WITH DIAERESIS
+00F9;00F9;0075 0300;00F9;0075 0300; # (ù; ù; u◌̀; ù; u◌̀; ) LATIN SMALL LETTER U WITH GRAVE
+00FA;00FA;0075 0301;00FA;0075 0301; # (ú; ú; u◌́; ú; u◌́; ) LATIN SMALL LETTER U WITH ACUTE
+00FB;00FB;0075 0302;00FB;0075 0302; # (û; û; u◌̂; û; u◌̂; ) LATIN SMALL LETTER U WITH CIRCUMFLEX
+00FC;00FC;0075 0308;00FC;0075 0308; # (ü; ü; u◌̈; ü; u◌̈; ) LATIN SMALL LETTER U WITH DIAERESIS
+00FD;00FD;0079 0301;00FD;0079 0301; # (ý; ý; y◌́; ý; y◌́; ) LATIN SMALL LETTER Y WITH ACUTE
+00FF;00FF;0079 0308;00FF;0079 0308; # (ÿ; ÿ; y◌̈; ÿ; y◌̈; ) LATIN SMALL LETTER Y WITH DIAERESIS
+0100;0100;0041 0304;0100;0041 0304; # (Ā; Ā; A◌̄; Ā; A◌̄; ) LATIN CAPITAL LETTER A WITH MACRON
+0101;0101;0061 0304;0101;0061 0304; # (ā; ā; a◌̄; ā; a◌̄; ) LATIN SMALL LETTER A WITH MACRON
+0102;0102;0041 0306;0102;0041 0306; # (Ă; Ă; A◌̆; Ă; A◌̆; ) LATIN CAPITAL LETTER A WITH BREVE
+0103;0103;0061 0306;0103;0061 0306; # (ă; ă; a◌̆; ă; a◌̆; ) LATIN SMALL LETTER A WITH BREVE
+0104;0104;0041 0328;0104;0041 0328; # (Ą; Ą; A◌̨; Ą; A◌̨; ) LATIN CAPITAL LETTER A WITH OGONEK
+0105;0105;0061 0328;0105;0061 0328; # (ą; ą; a◌̨; ą; a◌̨; ) LATIN SMALL LETTER A WITH OGONEK
+0106;0106;0043 0301;0106;0043 0301; # (Ć; Ć; C◌́; Ć; C◌́; ) LATIN CAPITAL LETTER C WITH ACUTE
+0107;0107;0063 0301;0107;0063 0301; # (ć; ć; c◌́; ć; c◌́; ) LATIN SMALL LETTER C WITH ACUTE
+0108;0108;0043 0302;0108;0043 0302; # (Ĉ; Ĉ; C◌̂; Ĉ; C◌̂; ) LATIN CAPITAL LETTER C WITH CIRCUMFLEX
+0109;0109;0063 0302;0109;0063 0302; # (ĉ; ĉ; c◌̂; ĉ; c◌̂; ) LATIN SMALL LETTER C WITH CIRCUMFLEX
+010A;010A;0043 0307;010A;0043 0307; # (Ċ; Ċ; C◌̇; Ċ; C◌̇; ) LATIN CAPITAL LETTER C WITH DOT ABOVE
+010B;010B;0063 0307;010B;0063 0307; # (ċ; ċ; c◌̇; ċ; c◌̇; ) LATIN SMALL LETTER C WITH DOT ABOVE
+010C;010C;0043 030C;010C;0043 030C; # (Č; Č; C◌̌; Č; C◌̌; ) LATIN CAPITAL LETTER C WITH CARON
+010D;010D;0063 030C;010D;0063 030C; # (č; č; c◌̌; č; c◌̌; ) LATIN SMALL LETTER C WITH CARON
+010E;010E;0044 030C;010E;0044 030C; # (Ď; Ď; D◌̌; Ď; D◌̌; ) LATIN CAPITAL LETTER D WITH CARON
+010F;010F;0064 030C;010F;0064 030C; # (ď; ď; d◌̌; ď; d◌̌; ) LATIN SMALL LETTER D WITH CARON
+0112;0112;0045 0304;0112;0045 0304; # (Ē; Ē; E◌̄; Ē; E◌̄; ) LATIN CAPITAL LETTER E WITH MACRON
+0113;0113;0065 0304;0113;0065 0304; # (ē; ē; e◌̄; ē; e◌̄; ) LATIN SMALL LETTER E WITH MACRON
+0114;0114;0045 0306;0114;0045 0306; # (Ĕ; Ĕ; E◌̆; Ĕ; E◌̆; ) LATIN CAPITAL LETTER E WITH BREVE
+0115;0115;0065 0306;0115;0065 0306; # (ĕ; ĕ; e◌̆; ĕ; e◌̆; ) LATIN SMALL LETTER E WITH BREVE
+0116;0116;0045 0307;0116;0045 0307; # (Ė; Ė; E◌̇; Ė; E◌̇; ) LATIN CAPITAL LETTER E WITH DOT ABOVE
+0117;0117;0065 0307;0117;0065 0307; # (ė; ė; e◌̇; ė; e◌̇; ) LATIN SMALL LETTER E WITH DOT ABOVE
+0118;0118;0045 0328;0118;0045 0328; # (Ę; Ę; E◌̨; Ę; E◌̨; ) LATIN CAPITAL LETTER E WITH OGONEK
+0119;0119;0065 0328;0119;0065 0328; # (ę; ę; e◌̨; ę; e◌̨; ) LATIN SMALL LETTER E WITH OGONEK
+011A;011A;0045 030C;011A;0045 030C; # (Ě; Ě; E◌̌; Ě; E◌̌; ) LATIN CAPITAL LETTER E WITH CARON
+011B;011B;0065 030C;011B;0065 030C; # (ě; ě; e◌̌; ě; e◌̌; ) LATIN SMALL LETTER E WITH CARON
+011C;011C;0047 0302;011C;0047 0302; # (Ĝ; Ĝ; G◌̂; Ĝ; G◌̂; ) LATIN CAPITAL LETTER G WITH CIRCUMFLEX
+011D;011D;0067 0302;011D;0067 0302; # (ĝ; ĝ; g◌̂; ĝ; g◌̂; ) LATIN SMALL LETTER G WITH CIRCUMFLEX
+011E;011E;0047 0306;011E;0047 0306; # (Ğ; Ğ; G◌̆; Ğ; G◌̆; ) LATIN CAPITAL LETTER G WITH BREVE
+011F;011F;0067 0306;011F;0067 0306; # (ğ; ğ; g◌̆; ğ; g◌̆; ) LATIN SMALL LETTER G WITH BREVE
+0120;0120;0047 0307;0120;0047 0307; # (Ġ; Ġ; G◌̇; Ġ; G◌̇; ) LATIN CAPITAL LETTER G WITH DOT ABOVE
+0121;0121;0067 0307;0121;0067 0307; # (ġ; ġ; g◌̇; ġ; g◌̇; ) LATIN SMALL LETTER G WITH DOT ABOVE
+0122;0122;0047 0327;0122;0047 0327; # (Ģ; Ģ; G◌̧; Ģ; G◌̧; ) LATIN CAPITAL LETTER G WITH CEDILLA
+0123;0123;0067 0327;0123;0067 0327; # (ģ; ģ; g◌̧; ģ; g◌̧; ) LATIN SMALL LETTER G WITH CEDILLA
+0124;0124;0048 0302;0124;0048 0302; # (Ĥ; Ĥ; H◌̂; Ĥ; H◌̂; ) LATIN CAPITAL LETTER H WITH CIRCUMFLEX
+0125;0125;0068 0302;0125;0068 0302; # (ĥ; ĥ; h◌̂; ĥ; h◌̂; ) LATIN SMALL LETTER H WITH CIRCUMFLEX
+0128;0128;0049 0303;0128;0049 0303; # (Ĩ; Ĩ; I◌̃; Ĩ; I◌̃; ) LATIN CAPITAL LETTER I WITH TILDE
+0129;0129;0069 0303;0129;0069 0303; # (ĩ; ĩ; i◌̃; ĩ; i◌̃; ) LATIN SMALL LETTER I WITH TILDE
+012A;012A;0049 0304;012A;0049 0304; # (Ī; Ī; I◌̄; Ī; I◌̄; ) LATIN CAPITAL LETTER I WITH MACRON
+012B;012B;0069 0304;012B;0069 0304; # (ī; ī; i◌̄; ī; i◌̄; ) LATIN SMALL LETTER I WITH MACRON
+012C;012C;0049 0306;012C;0049 0306; # (Ĭ; Ĭ; I◌̆; Ĭ; I◌̆; ) LATIN CAPITAL LETTER I WITH BREVE
+012D;012D;0069 0306;012D;0069 0306; # (ĭ; ĭ; i◌̆; ĭ; i◌̆; ) LATIN SMALL LETTER I WITH BREVE
+012E;012E;0049 0328;012E;0049 0328; # (Į; Į; I◌̨; Į; I◌̨; ) LATIN CAPITAL LETTER I WITH OGONEK
+012F;012F;0069 0328;012F;0069 0328; # (į; į; i◌̨; į; i◌̨; ) LATIN SMALL LETTER I WITH OGONEK
+0130;0130;0049 0307;0130;0049 0307; # (İ; İ; I◌̇; İ; I◌̇; ) LATIN CAPITAL LETTER I WITH DOT ABOVE
+0132;0132;0132;0049 004A;0049 004A; # (IJ; IJ; IJ; IJ; IJ; ) LATIN CAPITAL LIGATURE IJ
+0133;0133;0133;0069 006A;0069 006A; # (ij; ij; ij; ij; ij; ) LATIN SMALL LIGATURE IJ
+0134;0134;004A 0302;0134;004A 0302; # (Ĵ; Ĵ; J◌̂; Ĵ; J◌̂; ) LATIN CAPITAL LETTER J WITH CIRCUMFLEX
+0135;0135;006A 0302;0135;006A 0302; # (ĵ; ĵ; j◌̂; ĵ; j◌̂; ) LATIN SMALL LETTER J WITH CIRCUMFLEX
+0136;0136;004B 0327;0136;004B 0327; # (Ķ; Ķ; K◌̧; Ķ; K◌̧; ) LATIN CAPITAL LETTER K WITH CEDILLA
+0137;0137;006B 0327;0137;006B 0327; # (ķ; ķ; k◌̧; ķ; k◌̧; ) LATIN SMALL LETTER K WITH CEDILLA
+0139;0139;004C 0301;0139;004C 0301; # (Ĺ; Ĺ; L◌́; Ĺ; L◌́; ) LATIN CAPITAL LETTER L WITH ACUTE
+013A;013A;006C 0301;013A;006C 0301; # (ĺ; ĺ; l◌́; ĺ; l◌́; ) LATIN SMALL LETTER L WITH ACUTE
+013B;013B;004C 0327;013B;004C 0327; # (Ļ; Ļ; L◌̧; Ļ; L◌̧; ) LATIN CAPITAL LETTER L WITH CEDILLA
+013C;013C;006C 0327;013C;006C 0327; # (ļ; ļ; l◌̧; ļ; l◌̧; ) LATIN SMALL LETTER L WITH CEDILLA
+013D;013D;004C 030C;013D;004C 030C; # (Ľ; Ľ; L◌̌; Ľ; L◌̌; ) LATIN CAPITAL LETTER L WITH CARON
+013E;013E;006C 030C;013E;006C 030C; # (ľ; ľ; l◌̌; ľ; l◌̌; ) LATIN SMALL LETTER L WITH CARON
+013F;013F;013F;004C 00B7;004C 00B7; # (Ŀ; Ŀ; Ŀ; L·; L·; ) LATIN CAPITAL LETTER L WITH MIDDLE DOT
+0140;0140;0140;006C 00B7;006C 00B7; # (ŀ; ŀ; ŀ; l·; l·; ) LATIN SMALL LETTER L WITH MIDDLE DOT
+0143;0143;004E 0301;0143;004E 0301; # (Ń; Ń; N◌́; Ń; N◌́; ) LATIN CAPITAL LETTER N WITH ACUTE
+0144;0144;006E 0301;0144;006E 0301; # (ń; ń; n◌́; ń; n◌́; ) LATIN SMALL LETTER N WITH ACUTE
+0145;0145;004E 0327;0145;004E 0327; # (Ņ; Ņ; N◌̧; Ņ; N◌̧; ) LATIN CAPITAL LETTER N WITH CEDILLA
+0146;0146;006E 0327;0146;006E 0327; # (ņ; ņ; n◌̧; ņ; n◌̧; ) LATIN SMALL LETTER N WITH CEDILLA
+0147;0147;004E 030C;0147;004E 030C; # (Ň; Ň; N◌̌; Ň; N◌̌; ) LATIN CAPITAL LETTER N WITH CARON
+0148;0148;006E 030C;0148;006E 030C; # (ň; ň; n◌̌; ň; n◌̌; ) LATIN SMALL LETTER N WITH CARON
+0149;0149;0149;02BC 006E;02BC 006E; # (ʼn; ʼn; ʼn; ʼn; ʼn; ) LATIN SMALL LETTER N PRECEDED BY APOSTROPHE
+014C;014C;004F 0304;014C;004F 0304; # (Ō; Ō; O◌̄; Ō; O◌̄; ) LATIN CAPITAL LETTER O WITH MACRON
+014D;014D;006F 0304;014D;006F 0304; # (ō; ō; o◌̄; ō; o◌̄; ) LATIN SMALL LETTER O WITH MACRON
+014E;014E;004F 0306;014E;004F 0306; # (Ŏ; Ŏ; O◌̆; Ŏ; O◌̆; ) LATIN CAPITAL LETTER O WITH BREVE
+014F;014F;006F 0306;014F;006F 0306; # (ŏ; ŏ; o◌̆; ŏ; o◌̆; ) LATIN SMALL LETTER O WITH BREVE
+0150;0150;004F 030B;0150;004F 030B; # (Ő; Ő; O◌̋; Ő; O◌̋; ) LATIN CAPITAL LETTER O WITH DOUBLE ACUTE
+0151;0151;006F 030B;0151;006F 030B; # (ő; ő; o◌̋; ő; o◌̋; ) LATIN SMALL LETTER O WITH DOUBLE ACUTE
+0154;0154;0052 0301;0154;0052 0301; # (Ŕ; Ŕ; R◌́; Ŕ; R◌́; ) LATIN CAPITAL LETTER R WITH ACUTE
+0155;0155;0072 0301;0155;0072 0301; # (ŕ; ŕ; r◌́; ŕ; r◌́; ) LATIN SMALL LETTER R WITH ACUTE
+0156;0156;0052 0327;0156;0052 0327; # (Ŗ; Ŗ; R◌̧; Ŗ; R◌̧; ) LATIN CAPITAL LETTER R WITH CEDILLA
+0157;0157;0072 0327;0157;0072 0327; # (ŗ; ŗ; r◌̧; ŗ; r◌̧; ) LATIN SMALL LETTER R WITH CEDILLA
+0158;0158;0052 030C;0158;0052 030C; # (Ř; Ř; R◌̌; Ř; R◌̌; ) LATIN CAPITAL LETTER R WITH CARON
+0159;0159;0072 030C;0159;0072 030C; # (ř; ř; r◌̌; ř; r◌̌; ) LATIN SMALL LETTER R WITH CARON
+015A;015A;0053 0301;015A;0053 0301; # (Ś; Ś; S◌́; Ś; S◌́; ) LATIN CAPITAL LETTER S WITH ACUTE
+015B;015B;0073 0301;015B;0073 0301; # (ś; ś; s◌́; ś; s◌́; ) LATIN SMALL LETTER S WITH ACUTE
+015C;015C;0053 0302;015C;0053 0302; # (Ŝ; Ŝ; S◌̂; Ŝ; S◌̂; ) LATIN CAPITAL LETTER S WITH CIRCUMFLEX
+015D;015D;0073 0302;015D;0073 0302; # (ŝ; ŝ; s◌̂; ŝ; s◌̂; ) LATIN SMALL LETTER S WITH CIRCUMFLEX
+015E;015E;0053 0327;015E;0053 0327; # (Ş; Ş; S◌̧; Ş; S◌̧; ) LATIN CAPITAL LETTER S WITH CEDILLA
+015F;015F;0073 0327;015F;0073 0327; # (ş; ş; s◌̧; ş; s◌̧; ) LATIN SMALL LETTER S WITH CEDILLA
+0160;0160;0053 030C;0160;0053 030C; # (Š; Š; S◌̌; Š; S◌̌; ) LATIN CAPITAL LETTER S WITH CARON
+0161;0161;0073 030C;0161;0073 030C; # (š; š; s◌̌; š; s◌̌; ) LATIN SMALL LETTER S WITH CARON
+0162;0162;0054 0327;0162;0054 0327; # (Ţ; Ţ; T◌̧; Ţ; T◌̧; ) LATIN CAPITAL LETTER T WITH CEDILLA
+0163;0163;0074 0327;0163;0074 0327; # (ţ; ţ; t◌̧; ţ; t◌̧; ) LATIN SMALL LETTER T WITH CEDILLA
+0164;0164;0054 030C;0164;0054 030C; # (Ť; Ť; T◌̌; Ť; T◌̌; ) LATIN CAPITAL LETTER T WITH CARON
+0165;0165;0074 030C;0165;0074 030C; # (ť; ť; t◌̌; ť; t◌̌; ) LATIN SMALL LETTER T WITH CARON
+0168;0168;0055 0303;0168;0055 0303; # (Ũ; Ũ; U◌̃; Ũ; U◌̃; ) LATIN CAPITAL LETTER U WITH TILDE
+0169;0169;0075 0303;0169;0075 0303; # (ũ; ũ; u◌̃; ũ; u◌̃; ) LATIN SMALL LETTER U WITH TILDE
+016A;016A;0055 0304;016A;0055 0304; # (Ū; Ū; U◌̄; Ū; U◌̄; ) LATIN CAPITAL LETTER U WITH MACRON
+016B;016B;0075 0304;016B;0075 0304; # (ū; ū; u◌̄; ū; u◌̄; ) LATIN SMALL LETTER U WITH MACRON
+016C;016C;0055 0306;016C;0055 0306; # (Ŭ; Ŭ; U◌̆; Ŭ; U◌̆; ) LATIN CAPITAL LETTER U WITH BREVE
+016D;016D;0075 0306;016D;0075 0306; # (ŭ; ŭ; u◌̆; ŭ; u◌̆; ) LATIN SMALL LETTER U WITH BREVE
+016E;016E;0055 030A;016E;0055 030A; # (Ů; Ů; U◌̊; Ů; U◌̊; ) LATIN CAPITAL LETTER U WITH RING ABOVE
+016F;016F;0075 030A;016F;0075 030A; # (ů; ů; u◌̊; ů; u◌̊; ) LATIN SMALL LETTER U WITH RING ABOVE
+0170;0170;0055 030B;0170;0055 030B; # (Ű; Ű; U◌̋; Ű; U◌̋; ) LATIN CAPITAL LETTER U WITH DOUBLE ACUTE
+0171;0171;0075 030B;0171;0075 030B; # (ű; ű; u◌̋; ű; u◌̋; ) LATIN SMALL LETTER U WITH DOUBLE ACUTE
+0172;0172;0055 0328;0172;0055 0328; # (Ų; Ų; U◌̨; Ų; U◌̨; ) LATIN CAPITAL LETTER U WITH OGONEK
+0173;0173;0075 0328;0173;0075 0328; # (ų; ų; u◌̨; ų; u◌̨; ) LATIN SMALL LETTER U WITH OGONEK
+0174;0174;0057 0302;0174;0057 0302; # (Ŵ; Ŵ; W◌̂; Ŵ; W◌̂; ) LATIN CAPITAL LETTER W WITH CIRCUMFLEX
+0175;0175;0077 0302;0175;0077 0302; # (ŵ; ŵ; w◌̂; ŵ; w◌̂; ) LATIN SMALL LETTER W WITH CIRCUMFLEX
+0176;0176;0059 0302;0176;0059 0302; # (Ŷ; Ŷ; Y◌̂; Ŷ; Y◌̂; ) LATIN CAPITAL LETTER Y WITH CIRCUMFLEX
+0177;0177;0079 0302;0177;0079 0302; # (ŷ; ŷ; y◌̂; ŷ; y◌̂; ) LATIN SMALL LETTER Y WITH CIRCUMFLEX
+0178;0178;0059 0308;0178;0059 0308; # (Ÿ; Ÿ; Y◌̈; Ÿ; Y◌̈; ) LATIN CAPITAL LETTER Y WITH DIAERESIS
+0179;0179;005A 0301;0179;005A 0301; # (Ź; Ź; Z◌́; Ź; Z◌́; ) LATIN CAPITAL LETTER Z WITH ACUTE
+017A;017A;007A 0301;017A;007A 0301; # (ź; ź; z◌́; ź; z◌́; ) LATIN SMALL LETTER Z WITH ACUTE
+017B;017B;005A 0307;017B;005A 0307; # (Ż; Ż; Z◌̇; Ż; Z◌̇; ) LATIN CAPITAL LETTER Z WITH DOT ABOVE
+017C;017C;007A 0307;017C;007A 0307; # (ż; ż; z◌̇; ż; z◌̇; ) LATIN SMALL LETTER Z WITH DOT ABOVE
+017D;017D;005A 030C;017D;005A 030C; # (Ž; Ž; Z◌̌; Ž; Z◌̌; ) LATIN CAPITAL LETTER Z WITH CARON
+017E;017E;007A 030C;017E;007A 030C; # (ž; ž; z◌̌; ž; z◌̌; ) LATIN SMALL LETTER Z WITH CARON
+017F;017F;017F;0073;0073; # (ſ; ſ; ſ; s; s; ) LATIN SMALL LETTER LONG S
+01A0;01A0;004F 031B;01A0;004F 031B; # (Ơ; Ơ; O◌̛; Ơ; O◌̛; ) LATIN CAPITAL LETTER O WITH HORN
+01A1;01A1;006F 031B;01A1;006F 031B; # (ơ; ơ; o◌̛; ơ; o◌̛; ) LATIN SMALL LETTER O WITH HORN
+01AF;01AF;0055 031B;01AF;0055 031B; # (Ư; Ư; U◌̛; Ư; U◌̛; ) LATIN CAPITAL LETTER U WITH HORN
+01B0;01B0;0075 031B;01B0;0075 031B; # (ư; ư; u◌̛; ư; u◌̛; ) LATIN SMALL LETTER U WITH HORN
+01C4;01C4;01C4;0044 017D;0044 005A 030C; # (DŽ; DŽ; DŽ; DŽ; DZ◌̌; ) LATIN CAPITAL LETTER DZ WITH CARON
+01C5;01C5;01C5;0044 017E;0044 007A 030C; # (Dž; Dž; Dž; Dž; Dz◌̌; ) LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON
+01C6;01C6;01C6;0064 017E;0064 007A 030C; # (dž; dž; dž; dž; dz◌̌; ) LATIN SMALL LETTER DZ WITH CARON
+01C7;01C7;01C7;004C 004A;004C 004A; # (LJ; LJ; LJ; LJ; LJ; ) LATIN CAPITAL LETTER LJ
+01C8;01C8;01C8;004C 006A;004C 006A; # (Lj; Lj; Lj; Lj; Lj; ) LATIN CAPITAL LETTER L WITH SMALL LETTER J
+01C9;01C9;01C9;006C 006A;006C 006A; # (lj; lj; lj; lj; lj; ) LATIN SMALL LETTER LJ
+01CA;01CA;01CA;004E 004A;004E 004A; # (NJ; NJ; NJ; NJ; NJ; ) LATIN CAPITAL LETTER NJ
+01CB;01CB;01CB;004E 006A;004E 006A; # (Nj; Nj; Nj; Nj; Nj; ) LATIN CAPITAL LETTER N WITH SMALL LETTER J
+01CC;01CC;01CC;006E 006A;006E 006A; # (nj; nj; nj; nj; nj; ) LATIN SMALL LETTER NJ
+01CD;01CD;0041 030C;01CD;0041 030C; # (Ǎ; Ǎ; A◌̌; Ǎ; A◌̌; ) LATIN CAPITAL LETTER A WITH CARON
+01CE;01CE;0061 030C;01CE;0061 030C; # (ǎ; ǎ; a◌̌; ǎ; a◌̌; ) LATIN SMALL LETTER A WITH CARON
+01CF;01CF;0049 030C;01CF;0049 030C; # (Ǐ; Ǐ; I◌̌; Ǐ; I◌̌; ) LATIN CAPITAL LETTER I WITH CARON
+01D0;01D0;0069 030C;01D0;0069 030C; # (ǐ; ǐ; i◌̌; ǐ; i◌̌; ) LATIN SMALL LETTER I WITH CARON
+01D1;01D1;004F 030C;01D1;004F 030C; # (Ǒ; Ǒ; O◌̌; Ǒ; O◌̌; ) LATIN CAPITAL LETTER O WITH CARON
+01D2;01D2;006F 030C;01D2;006F 030C; # (ǒ; ǒ; o◌̌; ǒ; o◌̌; ) LATIN SMALL LETTER O WITH CARON
+01D3;01D3;0055 030C;01D3;0055 030C; # (Ǔ; Ǔ; U◌̌; Ǔ; U◌̌; ) LATIN CAPITAL LETTER U WITH CARON
+01D4;01D4;0075 030C;01D4;0075 030C; # (ǔ; ǔ; u◌̌; ǔ; u◌̌; ) LATIN SMALL LETTER U WITH CARON
+01D5;01D5;0055 0308 0304;01D5;0055 0308 0304; # (Ǖ; Ǖ; U◌̈◌̄; Ǖ; U◌̈◌̄; ) LATIN CAPITAL LETTER U WITH DIAERESIS AND MACRON
+01D6;01D6;0075 0308 0304;01D6;0075 0308 0304; # (ǖ; ǖ; u◌̈◌̄; ǖ; u◌̈◌̄; ) LATIN SMALL LETTER U WITH DIAERESIS AND MACRON
+01D7;01D7;0055 0308 0301;01D7;0055 0308 0301; # (Ǘ; Ǘ; U◌̈◌́; Ǘ; U◌̈◌́; ) LATIN CAPITAL LETTER U WITH DIAERESIS AND ACUTE
+01D8;01D8;0075 0308 0301;01D8;0075 0308 0301; # (ǘ; ǘ; u◌̈◌́; ǘ; u◌̈◌́; ) LATIN SMALL LETTER U WITH DIAERESIS AND ACUTE
+01D9;01D9;0055 0308 030C;01D9;0055 0308 030C; # (Ǚ; Ǚ; U◌̈◌̌; Ǚ; U◌̈◌̌; ) LATIN CAPITAL LETTER U WITH DIAERESIS AND CARON
+01DA;01DA;0075 0308 030C;01DA;0075 0308 030C; # (ǚ; ǚ; u◌̈◌̌; ǚ; u◌̈◌̌; ) LATIN SMALL LETTER U WITH DIAERESIS AND CARON
+01DB;01DB;0055 0308 0300;01DB;0055 0308 0300; # (Ǜ; Ǜ; U◌̈◌̀; Ǜ; U◌̈◌̀; ) LATIN CAPITAL LETTER U WITH DIAERESIS AND GRAVE
+01DC;01DC;0075 0308 0300;01DC;0075 0308 0300; # (ǜ; ǜ; u◌̈◌̀; ǜ; u◌̈◌̀; ) LATIN SMALL LETTER U WITH DIAERESIS AND GRAVE
+01DE;01DE;0041 0308 0304;01DE;0041 0308 0304; # (Ǟ; Ǟ; A◌̈◌̄; Ǟ; A◌̈◌̄; ) LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON
+01DF;01DF;0061 0308 0304;01DF;0061 0308 0304; # (ǟ; ǟ; a◌̈◌̄; ǟ; a◌̈◌̄; ) LATIN SMALL LETTER A WITH DIAERESIS AND MACRON
+01E0;01E0;0041 0307 0304;01E0;0041 0307 0304; # (Ǡ; Ǡ; A◌̇◌̄; Ǡ; A◌̇◌̄; ) LATIN CAPITAL LETTER A WITH DOT ABOVE AND MACRON
+01E1;01E1;0061 0307 0304;01E1;0061 0307 0304; # (ǡ; ǡ; a◌̇◌̄; ǡ; a◌̇◌̄; ) LATIN SMALL LETTER A WITH DOT ABOVE AND MACRON
+01E2;01E2;00C6 0304;01E2;00C6 0304; # (Ǣ; Ǣ; Æ◌̄; Ǣ; Æ◌̄; ) LATIN CAPITAL LETTER AE WITH MACRON
+01E3;01E3;00E6 0304;01E3;00E6 0304; # (ǣ; ǣ; æ◌̄; ǣ; æ◌̄; ) LATIN SMALL LETTER AE WITH MACRON
+01E6;01E6;0047 030C;01E6;0047 030C; # (Ǧ; Ǧ; G◌̌; Ǧ; G◌̌; ) LATIN CAPITAL LETTER G WITH CARON
+01E7;01E7;0067 030C;01E7;0067 030C; # (ǧ; ǧ; g◌̌; ǧ; g◌̌; ) LATIN SMALL LETTER G WITH CARON
+01E8;01E8;004B 030C;01E8;004B 030C; # (Ǩ; Ǩ; K◌̌; Ǩ; K◌̌; ) LATIN CAPITAL LETTER K WITH CARON
+01E9;01E9;006B 030C;01E9;006B 030C; # (ǩ; ǩ; k◌̌; ǩ; k◌̌; ) LATIN SMALL LETTER K WITH CARON
+01EA;01EA;004F 0328;01EA;004F 0328; # (Ǫ; Ǫ; O◌̨; Ǫ; O◌̨; ) LATIN CAPITAL LETTER O WITH OGONEK
+01EB;01EB;006F 0328;01EB;006F 0328; # (ǫ; ǫ; o◌̨; ǫ; o◌̨; ) LATIN SMALL LETTER O WITH OGONEK
+01EC;01EC;004F 0328 0304;01EC;004F 0328 0304; # (Ǭ; Ǭ; O◌̨◌̄; Ǭ; O◌̨◌̄; ) LATIN CAPITAL LETTER O WITH OGONEK AND MACRON
+01ED;01ED;006F 0328 0304;01ED;006F 0328 0304; # (ǭ; ǭ; o◌̨◌̄; ǭ; o◌̨◌̄; ) LATIN SMALL LETTER O WITH OGONEK AND MACRON
+01EE;01EE;01B7 030C;01EE;01B7 030C; # (Ǯ; Ǯ; Ʒ◌̌; Ǯ; Ʒ◌̌; ) LATIN CAPITAL LETTER EZH WITH CARON
+01EF;01EF;0292 030C;01EF;0292 030C; # (ǯ; ǯ; ʒ◌̌; ǯ; ʒ◌̌; ) LATIN SMALL LETTER EZH WITH CARON
+01F0;01F0;006A 030C;01F0;006A 030C; # (ǰ; ǰ; j◌̌; ǰ; j◌̌; ) LATIN SMALL LETTER J WITH CARON
+01F1;01F1;01F1;0044 005A;0044 005A; # (DZ; DZ; DZ; DZ; DZ; ) LATIN CAPITAL LETTER DZ
+01F2;01F2;01F2;0044 007A;0044 007A; # (Dz; Dz; Dz; Dz; Dz; ) LATIN CAPITAL LETTER D WITH SMALL LETTER Z
+01F3;01F3;01F3;0064 007A;0064 007A; # (dz; dz; dz; dz; dz; ) LATIN SMALL LETTER DZ
+01F4;01F4;0047 0301;01F4;0047 0301; # (Ǵ; Ǵ; G◌́; Ǵ; G◌́; ) LATIN CAPITAL LETTER G WITH ACUTE
+01F5;01F5;0067 0301;01F5;0067 0301; # (ǵ; ǵ; g◌́; ǵ; g◌́; ) LATIN SMALL LETTER G WITH ACUTE
+01F8;01F8;004E 0300;01F8;004E 0300; # (Ǹ; Ǹ; N◌̀; Ǹ; N◌̀; ) LATIN CAPITAL LETTER N WITH GRAVE
+01F9;01F9;006E 0300;01F9;006E 0300; # (ǹ; ǹ; n◌̀; ǹ; n◌̀; ) LATIN SMALL LETTER N WITH GRAVE
+01FA;01FA;0041 030A 0301;01FA;0041 030A 0301; # (Ǻ; Ǻ; A◌̊◌́; Ǻ; A◌̊◌́; ) LATIN CAPITAL LETTER A WITH RING ABOVE AND ACUTE
+01FB;01FB;0061 030A 0301;01FB;0061 030A 0301; # (ǻ; ǻ; a◌̊◌́; ǻ; a◌̊◌́; ) LATIN SMALL LETTER A WITH RING ABOVE AND ACUTE
+01FC;01FC;00C6 0301;01FC;00C6 0301; # (Ǽ; Ǽ; Æ◌́; Ǽ; Æ◌́; ) LATIN CAPITAL LETTER AE WITH ACUTE
+01FD;01FD;00E6 0301;01FD;00E6 0301; # (ǽ; ǽ; æ◌́; ǽ; æ◌́; ) LATIN SMALL LETTER AE WITH ACUTE
+01FE;01FE;00D8 0301;01FE;00D8 0301; # (Ǿ; Ǿ; Ø◌́; Ǿ; Ø◌́; ) LATIN CAPITAL LETTER O WITH STROKE AND ACUTE
+01FF;01FF;00F8 0301;01FF;00F8 0301; # (ǿ; ǿ; ø◌́; ǿ; ø◌́; ) LATIN SMALL LETTER O WITH STROKE AND ACUTE
+0200;0200;0041 030F;0200;0041 030F; # (Ȁ; Ȁ; A◌̏; Ȁ; A◌̏; ) LATIN CAPITAL LETTER A WITH DOUBLE GRAVE
+0201;0201;0061 030F;0201;0061 030F; # (ȁ; ȁ; a◌̏; ȁ; a◌̏; ) LATIN SMALL LETTER A WITH DOUBLE GRAVE
+0202;0202;0041 0311;0202;0041 0311; # (Ȃ; Ȃ; A◌̑; Ȃ; A◌̑; ) LATIN CAPITAL LETTER A WITH INVERTED BREVE
+0203;0203;0061 0311;0203;0061 0311; # (ȃ; ȃ; a◌̑; ȃ; a◌̑; ) LATIN SMALL LETTER A WITH INVERTED BREVE
+0204;0204;0045 030F;0204;0045 030F; # (Ȅ; Ȅ; E◌̏; Ȅ; E◌̏; ) LATIN CAPITAL LETTER E WITH DOUBLE GRAVE
+0205;0205;0065 030F;0205;0065 030F; # (ȅ; ȅ; e◌̏; ȅ; e◌̏; ) LATIN SMALL LETTER E WITH DOUBLE GRAVE
+0206;0206;0045 0311;0206;0045 0311; # (Ȇ; Ȇ; E◌̑; Ȇ; E◌̑; ) LATIN CAPITAL LETTER E WITH INVERTED BREVE
+0207;0207;0065 0311;0207;0065 0311; # (ȇ; ȇ; e◌̑; ȇ; e◌̑; ) LATIN SMALL LETTER E WITH INVERTED BREVE
+0208;0208;0049 030F;0208;0049 030F; # (Ȉ; Ȉ; I◌̏; Ȉ; I◌̏; ) LATIN CAPITAL LETTER I WITH DOUBLE GRAVE
+0209;0209;0069 030F;0209;0069 030F; # (ȉ; ȉ; i◌̏; ȉ; i◌̏; ) LATIN SMALL LETTER I WITH DOUBLE GRAVE
+020A;020A;0049 0311;020A;0049 0311; # (Ȋ; Ȋ; I◌̑; Ȋ; I◌̑; ) LATIN CAPITAL LETTER I WITH INVERTED BREVE
+020B;020B;0069 0311;020B;0069 0311; # (ȋ; ȋ; i◌̑; ȋ; i◌̑; ) LATIN SMALL LETTER I WITH INVERTED BREVE
+020C;020C;004F 030F;020C;004F 030F; # (Ȍ; Ȍ; O◌̏; Ȍ; O◌̏; ) LATIN CAPITAL LETTER O WITH DOUBLE GRAVE
+020D;020D;006F 030F;020D;006F 030F; # (ȍ; ȍ; o◌̏; ȍ; o◌̏; ) LATIN SMALL LETTER O WITH DOUBLE GRAVE
+020E;020E;004F 0311;020E;004F 0311; # (Ȏ; Ȏ; O◌̑; Ȏ; O◌̑; ) LATIN CAPITAL LETTER O WITH INVERTED BREVE
+020F;020F;006F 0311;020F;006F 0311; # (ȏ; ȏ; o◌̑; ȏ; o◌̑; ) LATIN SMALL LETTER O WITH INVERTED BREVE
+0210;0210;0052 030F;0210;0052 030F; # (Ȑ; Ȑ; R◌̏; Ȑ; R◌̏; ) LATIN CAPITAL LETTER R WITH DOUBLE GRAVE
+0211;0211;0072 030F;0211;0072 030F; # (ȑ; ȑ; r◌̏; ȑ; r◌̏; ) LATIN SMALL LETTER R WITH DOUBLE GRAVE
+0212;0212;0052 0311;0212;0052 0311; # (Ȓ; Ȓ; R◌̑; Ȓ; R◌̑; ) LATIN CAPITAL LETTER R WITH INVERTED BREVE
+0213;0213;0072 0311;0213;0072 0311; # (ȓ; ȓ; r◌̑; ȓ; r◌̑; ) LATIN SMALL LETTER R WITH INVERTED BREVE
+0214;0214;0055 030F;0214;0055 030F; # (Ȕ; Ȕ; U◌̏; Ȕ; U◌̏; ) LATIN CAPITAL LETTER U WITH DOUBLE GRAVE
+0215;0215;0075 030F;0215;0075 030F; # (ȕ; ȕ; u◌̏; ȕ; u◌̏; ) LATIN SMALL LETTER U WITH DOUBLE GRAVE
+0216;0216;0055 0311;0216;0055 0311; # (Ȗ; Ȗ; U◌̑; Ȗ; U◌̑; ) LATIN CAPITAL LETTER U WITH INVERTED BREVE
+0217;0217;0075 0311;0217;0075 0311; # (ȗ; ȗ; u◌̑; ȗ; u◌̑; ) LATIN SMALL LETTER U WITH INVERTED BREVE
+0218;0218;0053 0326;0218;0053 0326; # (Ș; Ș; S◌̦; Ș; S◌̦; ) LATIN CAPITAL LETTER S WITH COMMA BELOW
+0219;0219;0073 0326;0219;0073 0326; # (ș; ș; s◌̦; ș; s◌̦; ) LATIN SMALL LETTER S WITH COMMA BELOW
+021A;021A;0054 0326;021A;0054 0326; # (Ț; Ț; T◌̦; Ț; T◌̦; ) LATIN CAPITAL LETTER T WITH COMMA BELOW
+021B;021B;0074 0326;021B;0074 0326; # (ț; ț; t◌̦; ț; t◌̦; ) LATIN SMALL LETTER T WITH COMMA BELOW
+021E;021E;0048 030C;021E;0048 030C; # (Ȟ; Ȟ; H◌̌; Ȟ; H◌̌; ) LATIN CAPITAL LETTER H WITH CARON
+021F;021F;0068 030C;021F;0068 030C; # (ȟ; ȟ; h◌̌; ȟ; h◌̌; ) LATIN SMALL LETTER H WITH CARON
+0226;0226;0041 0307;0226;0041 0307; # (Ȧ; Ȧ; A◌̇; Ȧ; A◌̇; ) LATIN CAPITAL LETTER A WITH DOT ABOVE
+0227;0227;0061 0307;0227;0061 0307; # (ȧ; ȧ; a◌̇; ȧ; a◌̇; ) LATIN SMALL LETTER A WITH DOT ABOVE
+0228;0228;0045 0327;0228;0045 0327; # (Ȩ; Ȩ; E◌̧; Ȩ; E◌̧; ) LATIN CAPITAL LETTER E WITH CEDILLA
+0229;0229;0065 0327;0229;0065 0327; # (ȩ; ȩ; e◌̧; ȩ; e◌̧; ) LATIN SMALL LETTER E WITH CEDILLA
+022A;022A;004F 0308 0304;022A;004F 0308 0304; # (Ȫ; Ȫ; O◌̈◌̄; Ȫ; O◌̈◌̄; ) LATIN CAPITAL LETTER O WITH DIAERESIS AND MACRON
+022B;022B;006F 0308 0304;022B;006F 0308 0304; # (ȫ; ȫ; o◌̈◌̄; ȫ; o◌̈◌̄; ) LATIN SMALL LETTER O WITH DIAERESIS AND MACRON
+022C;022C;004F 0303 0304;022C;004F 0303 0304; # (Ȭ; Ȭ; O◌̃◌̄; Ȭ; O◌̃◌̄; ) LATIN CAPITAL LETTER O WITH TILDE AND MACRON
+022D;022D;006F 0303 0304;022D;006F 0303 0304; # (ȭ; ȭ; o◌̃◌̄; ȭ; o◌̃◌̄; ) LATIN SMALL LETTER O WITH TILDE AND MACRON
+022E;022E;004F 0307;022E;004F 0307; # (Ȯ; Ȯ; O◌̇; Ȯ; O◌̇; ) LATIN CAPITAL LETTER O WITH DOT ABOVE
+022F;022F;006F 0307;022F;006F 0307; # (ȯ; ȯ; o◌̇; ȯ; o◌̇; ) LATIN SMALL LETTER O WITH DOT ABOVE
+0230;0230;004F 0307 0304;0230;004F 0307 0304; # (Ȱ; Ȱ; O◌̇◌̄; Ȱ; O◌̇◌̄; ) LATIN CAPITAL LETTER O WITH DOT ABOVE AND MACRON
+0231;0231;006F 0307 0304;0231;006F 0307 0304; # (ȱ; ȱ; o◌̇◌̄; ȱ; o◌̇◌̄; ) LATIN SMALL LETTER O WITH DOT ABOVE AND MACRON
+0232;0232;0059 0304;0232;0059 0304; # (Ȳ; Ȳ; Y◌̄; Ȳ; Y◌̄; ) LATIN CAPITAL LETTER Y WITH MACRON
+0233;0233;0079 0304;0233;0079 0304; # (ȳ; ȳ; y◌̄; ȳ; y◌̄; ) LATIN SMALL LETTER Y WITH MACRON
+02B0;02B0;02B0;0068;0068; # (ʰ; ʰ; ʰ; h; h; ) MODIFIER LETTER SMALL H
+02B1;02B1;02B1;0266;0266; # (ʱ; ʱ; ʱ; ɦ; ɦ; ) MODIFIER LETTER SMALL H WITH HOOK
+02B2;02B2;02B2;006A;006A; # (ʲ; ʲ; ʲ; j; j; ) MODIFIER LETTER SMALL J
+02B3;02B3;02B3;0072;0072; # (ʳ; ʳ; ʳ; r; r; ) MODIFIER LETTER SMALL R
+02B4;02B4;02B4;0279;0279; # (ʴ; ʴ; ʴ; ɹ; ɹ; ) MODIFIER LETTER SMALL TURNED R
+02B5;02B5;02B5;027B;027B; # (ʵ; ʵ; ʵ; ɻ; ɻ; ) MODIFIER LETTER SMALL TURNED R WITH HOOK
+02B6;02B6;02B6;0281;0281; # (ʶ; ʶ; ʶ; ʁ; ʁ; ) MODIFIER LETTER SMALL CAPITAL INVERTED R
+02B7;02B7;02B7;0077;0077; # (ʷ; ʷ; ʷ; w; w; ) MODIFIER LETTER SMALL W
+02B8;02B8;02B8;0079;0079; # (ʸ; ʸ; ʸ; y; y; ) MODIFIER LETTER SMALL Y
+02D8;02D8;02D8;0020 0306;0020 0306; # (˘; ˘; ˘; ◌̆; ◌̆; ) BREVE
+02D9;02D9;02D9;0020 0307;0020 0307; # (˙; ˙; ˙; ◌̇; ◌̇; ) DOT ABOVE
+02DA;02DA;02DA;0020 030A;0020 030A; # (˚; ˚; ˚; ◌̊; ◌̊; ) RING ABOVE
+02DB;02DB;02DB;0020 0328;0020 0328; # (˛; ˛; ˛; ◌̨; ◌̨; ) OGONEK
+02DC;02DC;02DC;0020 0303;0020 0303; # (˜; ˜; ˜; ◌̃; ◌̃; ) SMALL TILDE
+02DD;02DD;02DD;0020 030B;0020 030B; # (˝; ˝; ˝; ◌̋; ◌̋; ) DOUBLE ACUTE ACCENT
+02E0;02E0;02E0;0263;0263; # (ˠ; ˠ; ˠ; ɣ; ɣ; ) MODIFIER LETTER SMALL GAMMA
+02E1;02E1;02E1;006C;006C; # (ˡ; ˡ; ˡ; l; l; ) MODIFIER LETTER SMALL L
+02E2;02E2;02E2;0073;0073; # (ˢ; ˢ; ˢ; s; s; ) MODIFIER LETTER SMALL S
+02E3;02E3;02E3;0078;0078; # (ˣ; ˣ; ˣ; x; x; ) MODIFIER LETTER SMALL X
+02E4;02E4;02E4;0295;0295; # (ˤ; ˤ; ˤ; ʕ; ʕ; ) MODIFIER LETTER SMALL REVERSED GLOTTAL STOP
+0340;0300;0300;0300;0300; # (◌̀; ◌̀; ◌̀; ◌̀; ◌̀; ) COMBINING GRAVE TONE MARK
+0341;0301;0301;0301;0301; # (◌́; ◌́; ◌́; ◌́; ◌́; ) COMBINING ACUTE TONE MARK
+0343;0313;0313;0313;0313; # (◌̓; ◌̓; ◌̓; ◌̓; ◌̓; ) COMBINING GREEK KORONIS
+0344;0308 0301;0308 0301;0308 0301;0308 0301; # (◌̈́; ◌̈◌́; ◌̈◌́; ◌̈◌́; ◌̈◌́; ) COMBINING GREEK DIALYTIKA TONOS
+0374;02B9;02B9;02B9;02B9; # (ʹ; ʹ; ʹ; ʹ; ʹ; ) GREEK NUMERAL SIGN
+037A;037A;037A;0020 0345;0020 0345; # (ͺ; ͺ; ͺ; ◌ͅ; ◌ͅ; ) GREEK YPOGEGRAMMENI
+037E;003B;003B;003B;003B; # (;; ;; ;; ;; ;; ) GREEK QUESTION MARK
+0384;0384;0384;0020 0301;0020 0301; # (΄; ΄; ΄; ◌́; ◌́; ) GREEK TONOS
+0385;0385;00A8 0301;0020 0308 0301;0020 0308 0301; # (΅; ΅; ¨◌́; ◌̈◌́; ◌̈◌́; ) GREEK DIALYTIKA TONOS
+0386;0386;0391 0301;0386;0391 0301; # (Ά; Ά; Α◌́; Ά; Α◌́; ) GREEK CAPITAL LETTER ALPHA WITH TONOS
+0387;00B7;00B7;00B7;00B7; # (·; ·; ·; ·; ·; ) GREEK ANO TELEIA
+0388;0388;0395 0301;0388;0395 0301; # (Έ; Έ; Ε◌́; Έ; Ε◌́; ) GREEK CAPITAL LETTER EPSILON WITH TONOS
+0389;0389;0397 0301;0389;0397 0301; # (Ή; Ή; Η◌́; Ή; Η◌́; ) GREEK CAPITAL LETTER ETA WITH TONOS
+038A;038A;0399 0301;038A;0399 0301; # (Ί; Ί; Ι◌́; Ί; Ι◌́; ) GREEK CAPITAL LETTER IOTA WITH TONOS
+038C;038C;039F 0301;038C;039F 0301; # (Ό; Ό; Ο◌́; Ό; Ο◌́; ) GREEK CAPITAL LETTER OMICRON WITH TONOS
+038E;038E;03A5 0301;038E;03A5 0301; # (Ύ; Ύ; Υ◌́; Ύ; Υ◌́; ) GREEK CAPITAL LETTER UPSILON WITH TONOS
+038F;038F;03A9 0301;038F;03A9 0301; # (Ώ; Ώ; Ω◌́; Ώ; Ω◌́; ) GREEK CAPITAL LETTER OMEGA WITH TONOS
+0390;0390;03B9 0308 0301;0390;03B9 0308 0301; # (ΐ; ΐ; ι◌̈◌́; ΐ; ι◌̈◌́; ) GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
+03AA;03AA;0399 0308;03AA;0399 0308; # (Ϊ; Ϊ; Ι◌̈; Ϊ; Ι◌̈; ) GREEK CAPITAL LETTER IOTA WITH DIALYTIKA
+03AB;03AB;03A5 0308;03AB;03A5 0308; # (Ϋ; Ϋ; Υ◌̈; Ϋ; Υ◌̈; ) GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA
+03AC;03AC;03B1 0301;03AC;03B1 0301; # (ά; ά; α◌́; ά; α◌́; ) GREEK SMALL LETTER ALPHA WITH TONOS
+03AD;03AD;03B5 0301;03AD;03B5 0301; # (έ; έ; ε◌́; έ; ε◌́; ) GREEK SMALL LETTER EPSILON WITH TONOS
+03AE;03AE;03B7 0301;03AE;03B7 0301; # (ή; ή; η◌́; ή; η◌́; ) GREEK SMALL LETTER ETA WITH TONOS
+03AF;03AF;03B9 0301;03AF;03B9 0301; # (ί; ί; ι◌́; ί; ι◌́; ) GREEK SMALL LETTER IOTA WITH TONOS
+03B0;03B0;03C5 0308 0301;03B0;03C5 0308 0301; # (ΰ; ΰ; υ◌̈◌́; ΰ; υ◌̈◌́; ) GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
+03CA;03CA;03B9 0308;03CA;03B9 0308; # (ϊ; ϊ; ι◌̈; ϊ; ι◌̈; ) GREEK SMALL LETTER IOTA WITH DIALYTIKA
+03CB;03CB;03C5 0308;03CB;03C5 0308; # (ϋ; ϋ; υ◌̈; ϋ; υ◌̈; ) GREEK SMALL LETTER UPSILON WITH DIALYTIKA
+03CC;03CC;03BF 0301;03CC;03BF 0301; # (ό; ό; ο◌́; ό; ο◌́; ) GREEK SMALL LETTER OMICRON WITH TONOS
+03CD;03CD;03C5 0301;03CD;03C5 0301; # (ύ; ύ; υ◌́; ύ; υ◌́; ) GREEK SMALL LETTER UPSILON WITH TONOS
+03CE;03CE;03C9 0301;03CE;03C9 0301; # (ώ; ώ; ω◌́; ώ; ω◌́; ) GREEK SMALL LETTER OMEGA WITH TONOS
+03D0;03D0;03D0;03B2;03B2; # (ϐ; ϐ; ϐ; β; β; ) GREEK BETA SYMBOL
+03D1;03D1;03D1;03B8;03B8; # (ϑ; ϑ; ϑ; θ; θ; ) GREEK THETA SYMBOL
+03D2;03D2;03D2;03A5;03A5; # (ϒ; ϒ; ϒ; Υ; Υ; ) GREEK UPSILON WITH HOOK SYMBOL
+03D3;03D3;03D2 0301;038E;03A5 0301; # (ϓ; ϓ; ϒ◌́; Ύ; Υ◌́; ) GREEK UPSILON WITH ACUTE AND HOOK SYMBOL
+03D4;03D4;03D2 0308;03AB;03A5 0308; # (ϔ; ϔ; ϒ◌̈; Ϋ; Υ◌̈; ) GREEK UPSILON WITH DIAERESIS AND HOOK SYMBOL
+03D5;03D5;03D5;03C6;03C6; # (ϕ; ϕ; ϕ; φ; φ; ) GREEK PHI SYMBOL
+03D6;03D6;03D6;03C0;03C0; # (ϖ; ϖ; ϖ; π; π; ) GREEK PI SYMBOL
+03F0;03F0;03F0;03BA;03BA; # (ϰ; ϰ; ϰ; κ; κ; ) GREEK KAPPA SYMBOL
+03F1;03F1;03F1;03C1;03C1; # (ϱ; ϱ; ϱ; ρ; ρ; ) GREEK RHO SYMBOL
+03F2;03F2;03F2;03C2;03C2; # (ϲ; ϲ; ϲ; ς; ς; ) GREEK LUNATE SIGMA SYMBOL
+03F4;03F4;03F4;0398;0398; # (ϴ; ϴ; ϴ; Θ; Θ; ) GREEK CAPITAL THETA SYMBOL
+03F5;03F5;03F5;03B5;03B5; # (ϵ; ϵ; ϵ; ε; ε; ) GREEK LUNATE EPSILON SYMBOL
+03F9;03F9;03F9;03A3;03A3; # (Ϲ; Ϲ; Ϲ; Σ; Σ; ) GREEK CAPITAL LUNATE SIGMA SYMBOL
+0400;0400;0415 0300;0400;0415 0300; # (Ѐ; Ѐ; Е◌̀; Ѐ; Е◌̀; ) CYRILLIC CAPITAL LETTER IE WITH GRAVE
+0401;0401;0415 0308;0401;0415 0308; # (Ё; Ё; Е◌̈; Ё; Е◌̈; ) CYRILLIC CAPITAL LETTER IO
+0403;0403;0413 0301;0403;0413 0301; # (Ѓ; Ѓ; Г◌́; Ѓ; Г◌́; ) CYRILLIC CAPITAL LETTER GJE
+0407;0407;0406 0308;0407;0406 0308; # (Ї; Ї; І◌̈; Ї; І◌̈; ) CYRILLIC CAPITAL LETTER YI
+040C;040C;041A 0301;040C;041A 0301; # (Ќ; Ќ; К◌́; Ќ; К◌́; ) CYRILLIC CAPITAL LETTER KJE
+040D;040D;0418 0300;040D;0418 0300; # (Ѝ; Ѝ; И◌̀; Ѝ; И◌̀; ) CYRILLIC CAPITAL LETTER I WITH GRAVE
+040E;040E;0423 0306;040E;0423 0306; # (Ў; Ў; У◌̆; Ў; У◌̆; ) CYRILLIC CAPITAL LETTER SHORT U
+0419;0419;0418 0306;0419;0418 0306; # (Й; Й; И◌̆; Й; И◌̆; ) CYRILLIC CAPITAL LETTER SHORT I
+0439;0439;0438 0306;0439;0438 0306; # (й; й; и◌̆; й; и◌̆; ) CYRILLIC SMALL LETTER SHORT I
+0450;0450;0435 0300;0450;0435 0300; # (ѐ; ѐ; е◌̀; ѐ; е◌̀; ) CYRILLIC SMALL LETTER IE WITH GRAVE
+0451;0451;0435 0308;0451;0435 0308; # (ё; ё; е◌̈; ё; е◌̈; ) CYRILLIC SMALL LETTER IO
+0453;0453;0433 0301;0453;0433 0301; # (ѓ; ѓ; г◌́; ѓ; г◌́; ) CYRILLIC SMALL LETTER GJE
+0457;0457;0456 0308;0457;0456 0308; # (ї; ї; і◌̈; ї; і◌̈; ) CYRILLIC SMALL LETTER YI
+045C;045C;043A 0301;045C;043A 0301; # (ќ; ќ; к◌́; ќ; к◌́; ) CYRILLIC SMALL LETTER KJE
+045D;045D;0438 0300;045D;0438 0300; # (ѝ; ѝ; и◌̀; ѝ; и◌̀; ) CYRILLIC SMALL LETTER I WITH GRAVE
+045E;045E;0443 0306;045E;0443 0306; # (ў; ў; у◌̆; ў; у◌̆; ) CYRILLIC SMALL LETTER SHORT U
+0476;0476;0474 030F;0476;0474 030F; # (Ѷ; Ѷ; Ѵ◌̏; Ѷ; Ѵ◌̏; ) CYRILLIC CAPITAL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT
+0477;0477;0475 030F;0477;0475 030F; # (ѷ; ѷ; ѵ◌̏; ѷ; ѵ◌̏; ) CYRILLIC SMALL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT
+04C1;04C1;0416 0306;04C1;0416 0306; # (Ӂ; Ӂ; Ж◌̆; Ӂ; Ж◌̆; ) CYRILLIC CAPITAL LETTER ZHE WITH BREVE
+04C2;04C2;0436 0306;04C2;0436 0306; # (ӂ; ӂ; ж◌̆; ӂ; ж◌̆; ) CYRILLIC SMALL LETTER ZHE WITH BREVE
+04D0;04D0;0410 0306;04D0;0410 0306; # (Ӑ; Ӑ; А◌̆; Ӑ; А◌̆; ) CYRILLIC CAPITAL LETTER A WITH BREVE
+04D1;04D1;0430 0306;04D1;0430 0306; # (ӑ; ӑ; а◌̆; ӑ; а◌̆; ) CYRILLIC SMALL LETTER A WITH BREVE
+04D2;04D2;0410 0308;04D2;0410 0308; # (Ӓ; Ӓ; А◌̈; Ӓ; А◌̈; ) CYRILLIC CAPITAL LETTER A WITH DIAERESIS
+04D3;04D3;0430 0308;04D3;0430 0308; # (ӓ; ӓ; а◌̈; ӓ; а◌̈; ) CYRILLIC SMALL LETTER A WITH DIAERESIS
+04D6;04D6;0415 0306;04D6;0415 0306; # (Ӗ; Ӗ; Е◌̆; Ӗ; Е◌̆; ) CYRILLIC CAPITAL LETTER IE WITH BREVE
+04D7;04D7;0435 0306;04D7;0435 0306; # (ӗ; ӗ; е◌̆; ӗ; е◌̆; ) CYRILLIC SMALL LETTER IE WITH BREVE
+04DA;04DA;04D8 0308;04DA;04D8 0308; # (Ӛ; Ӛ; Ә◌̈; Ӛ; Ә◌̈; ) CYRILLIC CAPITAL LETTER SCHWA WITH DIAERESIS
+04DB;04DB;04D9 0308;04DB;04D9 0308; # (ӛ; ӛ; ә◌̈; ӛ; ә◌̈; ) CYRILLIC SMALL LETTER SCHWA WITH DIAERESIS
+04DC;04DC;0416 0308;04DC;0416 0308; # (Ӝ; Ӝ; Ж◌̈; Ӝ; Ж◌̈; ) CYRILLIC CAPITAL LETTER ZHE WITH DIAERESIS
+04DD;04DD;0436 0308;04DD;0436 0308; # (ӝ; ӝ; ж◌̈; ӝ; ж◌̈; ) CYRILLIC SMALL LETTER ZHE WITH DIAERESIS
+04DE;04DE;0417 0308;04DE;0417 0308; # (Ӟ; Ӟ; З◌̈; Ӟ; З◌̈; ) CYRILLIC CAPITAL LETTER ZE WITH DIAERESIS
+04DF;04DF;0437 0308;04DF;0437 0308; # (ӟ; ӟ; з◌̈; ӟ; з◌̈; ) CYRILLIC SMALL LETTER ZE WITH DIAERESIS
+04E2;04E2;0418 0304;04E2;0418 0304; # (Ӣ; Ӣ; И◌̄; Ӣ; И◌̄; ) CYRILLIC CAPITAL LETTER I WITH MACRON
+04E3;04E3;0438 0304;04E3;0438 0304; # (ӣ; ӣ; и◌̄; ӣ; и◌̄; ) CYRILLIC SMALL LETTER I WITH MACRON
+04E4;04E4;0418 0308;04E4;0418 0308; # (Ӥ; Ӥ; И◌̈; Ӥ; И◌̈; ) CYRILLIC CAPITAL LETTER I WITH DIAERESIS
+04E5;04E5;0438 0308;04E5;0438 0308; # (ӥ; ӥ; и◌̈; ӥ; и◌̈; ) CYRILLIC SMALL LETTER I WITH DIAERESIS
+04E6;04E6;041E 0308;04E6;041E 0308; # (Ӧ; Ӧ; О◌̈; Ӧ; О◌̈; ) CYRILLIC CAPITAL LETTER O WITH DIAERESIS
+04E7;04E7;043E 0308;04E7;043E 0308; # (ӧ; ӧ; о◌̈; ӧ; о◌̈; ) CYRILLIC SMALL LETTER O WITH DIAERESIS
+04EA;04EA;04E8 0308;04EA;04E8 0308; # (Ӫ; Ӫ; Ө◌̈; Ӫ; Ө◌̈; ) CYRILLIC CAPITAL LETTER BARRED O WITH DIAERESIS
+04EB;04EB;04E9 0308;04EB;04E9 0308; # (ӫ; ӫ; ө◌̈; ӫ; ө◌̈; ) CYRILLIC SMALL LETTER BARRED O WITH DIAERESIS
+04EC;04EC;042D 0308;04EC;042D 0308; # (Ӭ; Ӭ; Э◌̈; Ӭ; Э◌̈; ) CYRILLIC CAPITAL LETTER E WITH DIAERESIS
+04ED;04ED;044D 0308;04ED;044D 0308; # (ӭ; ӭ; э◌̈; ӭ; э◌̈; ) CYRILLIC SMALL LETTER E WITH DIAERESIS
+04EE;04EE;0423 0304;04EE;0423 0304; # (Ӯ; Ӯ; У◌̄; Ӯ; У◌̄; ) CYRILLIC CAPITAL LETTER U WITH MACRON
+04EF;04EF;0443 0304;04EF;0443 0304; # (ӯ; ӯ; у◌̄; ӯ; у◌̄; ) CYRILLIC SMALL LETTER U WITH MACRON
+04F0;04F0;0423 0308;04F0;0423 0308; # (Ӱ; Ӱ; У◌̈; Ӱ; У◌̈; ) CYRILLIC CAPITAL LETTER U WITH DIAERESIS
+04F1;04F1;0443 0308;04F1;0443 0308; # (ӱ; ӱ; у◌̈; ӱ; у◌̈; ) CYRILLIC SMALL LETTER U WITH DIAERESIS
+04F2;04F2;0423 030B;04F2;0423 030B; # (Ӳ; Ӳ; У◌̋; Ӳ; У◌̋; ) CYRILLIC CAPITAL LETTER U WITH DOUBLE ACUTE
+04F3;04F3;0443 030B;04F3;0443 030B; # (ӳ; ӳ; у◌̋; ӳ; у◌̋; ) CYRILLIC SMALL LETTER U WITH DOUBLE ACUTE
+04F4;04F4;0427 0308;04F4;0427 0308; # (Ӵ; Ӵ; Ч◌̈; Ӵ; Ч◌̈; ) CYRILLIC CAPITAL LETTER CHE WITH DIAERESIS
+04F5;04F5;0447 0308;04F5;0447 0308; # (ӵ; ӵ; ч◌̈; ӵ; ч◌̈; ) CYRILLIC SMALL LETTER CHE WITH DIAERESIS
+04F8;04F8;042B 0308;04F8;042B 0308; # (Ӹ; Ӹ; Ы◌̈; Ӹ; Ы◌̈; ) CYRILLIC CAPITAL LETTER YERU WITH DIAERESIS
+04F9;04F9;044B 0308;04F9;044B 0308; # (ӹ; ӹ; ы◌̈; ӹ; ы◌̈; ) CYRILLIC SMALL LETTER YERU WITH DIAERESIS
+0587;0587;0587;0565 0582;0565 0582; # (և; և; և; եւ; եւ; ) ARMENIAN SMALL LIGATURE ECH YIWN
+0622;0622;0627 0653;0622;0627 0653; # (آ; آ; ا◌ٓ; آ; ا◌ٓ; ) ARABIC LETTER ALEF WITH MADDA ABOVE
+0623;0623;0627 0654;0623;0627 0654; # (أ; أ; ا◌ٔ; أ; ا◌ٔ; ) ARABIC LETTER ALEF WITH HAMZA ABOVE
+0624;0624;0648 0654;0624;0648 0654; # (ؤ; ؤ; و◌ٔ; ؤ; و◌ٔ; ) ARABIC LETTER WAW WITH HAMZA ABOVE
+0625;0625;0627 0655;0625;0627 0655; # (إ; إ; ا◌ٕ; إ; ا◌ٕ; ) ARABIC LETTER ALEF WITH HAMZA BELOW
+0626;0626;064A 0654;0626;064A 0654; # (ئ; ئ; ي◌ٔ; ئ; ي◌ٔ; ) ARABIC LETTER YEH WITH HAMZA ABOVE
+0675;0675;0675;0627 0674;0627 0674; # (ٵ; ٵ; ٵ; اٴ; اٴ; ) ARABIC LETTER HIGH HAMZA ALEF
+0676;0676;0676;0648 0674;0648 0674; # (ٶ; ٶ; ٶ; وٴ; وٴ; ) ARABIC LETTER HIGH HAMZA WAW
+0677;0677;0677;06C7 0674;06C7 0674; # (ٷ; ٷ; ٷ; ۇٴ; ۇٴ; ) ARABIC LETTER U WITH HAMZA ABOVE
+0678;0678;0678;064A 0674;064A 0674; # (ٸ; ٸ; ٸ; يٴ; يٴ; ) ARABIC LETTER HIGH HAMZA YEH
+06C0;06C0;06D5 0654;06C0;06D5 0654; # (ۀ; ۀ; ە◌ٔ; ۀ; ە◌ٔ; ) ARABIC LETTER HEH WITH YEH ABOVE
+06C2;06C2;06C1 0654;06C2;06C1 0654; # (ۂ; ۂ; ہ◌ٔ; ۂ; ہ◌ٔ; ) ARABIC LETTER HEH GOAL WITH HAMZA ABOVE
+06D3;06D3;06D2 0654;06D3;06D2 0654; # (ۓ; ۓ; ے◌ٔ; ۓ; ے◌ٔ; ) ARABIC LETTER YEH BARREE WITH HAMZA ABOVE
+0929;0929;0928 093C;0929;0928 093C; # (ऩ; ऩ; न◌़; ऩ; न◌़; ) DEVANAGARI LETTER NNNA
+0931;0931;0930 093C;0931;0930 093C; # (ऱ; ऱ; र◌़; ऱ; र◌़; ) DEVANAGARI LETTER RRA
+0934;0934;0933 093C;0934;0933 093C; # (ऴ; ऴ; ळ◌़; ऴ; ळ◌़; ) DEVANAGARI LETTER LLLA
+0958;0915 093C;0915 093C;0915 093C;0915 093C; # (क़; क◌़; क◌़; क◌़; क◌़; ) DEVANAGARI LETTER QA
+0959;0916 093C;0916 093C;0916 093C;0916 093C; # (ख़; ख◌़; ख◌़; ख◌़; ख◌़; ) DEVANAGARI LETTER KHHA
+095A;0917 093C;0917 093C;0917 093C;0917 093C; # (ग़; ग◌़; ग◌़; ग◌़; ग◌़; ) DEVANAGARI LETTER GHHA
+095B;091C 093C;091C 093C;091C 093C;091C 093C; # (ज़; ज◌़; ज◌़; ज◌़; ज◌़; ) DEVANAGARI LETTER ZA
+095C;0921 093C;0921 093C;0921 093C;0921 093C; # (ड़; ड◌़; ड◌़; ड◌़; ड◌़; ) DEVANAGARI LETTER DDDHA
+095D;0922 093C;0922 093C;0922 093C;0922 093C; # (ढ़; ढ◌़; ढ◌़; ढ◌़; ढ◌़; ) DEVANAGARI LETTER RHA
+095E;092B 093C;092B 093C;092B 093C;092B 093C; # (फ़; फ◌़; फ◌़; फ◌़; फ◌़; ) DEVANAGARI LETTER FA
+095F;092F 093C;092F 093C;092F 093C;092F 093C; # (य़; य◌़; य◌़; य◌़; य◌़; ) DEVANAGARI LETTER YYA
+09CB;09CB;09C7 09BE;09CB;09C7 09BE; # (ো; ো; ো; ো; ো; ) BENGALI VOWEL SIGN O
+09CC;09CC;09C7 09D7;09CC;09C7 09D7; # (ৌ; ৌ; ৌ; ৌ; ৌ; ) BENGALI VOWEL SIGN AU
+09DC;09A1 09BC;09A1 09BC;09A1 09BC;09A1 09BC; # (ড়; ড◌়; ড◌়; ড◌়; ড◌়; ) BENGALI LETTER RRA
+09DD;09A2 09BC;09A2 09BC;09A2 09BC;09A2 09BC; # (ঢ়; ঢ◌়; ঢ◌়; ঢ◌়; ঢ◌়; ) BENGALI LETTER RHA
+09DF;09AF 09BC;09AF 09BC;09AF 09BC;09AF 09BC; # (য়; য◌়; য◌়; য◌়; য◌়; ) BENGALI LETTER YYA
+0A33;0A32 0A3C;0A32 0A3C;0A32 0A3C;0A32 0A3C; # (ਲ਼; ਲ◌਼; ਲ◌਼; ਲ◌਼; ਲ◌਼; ) GURMUKHI LETTER LLA
+0A36;0A38 0A3C;0A38 0A3C;0A38 0A3C;0A38 0A3C; # (ਸ਼; ਸ◌਼; ਸ◌਼; ਸ◌਼; ਸ◌਼; ) GURMUKHI LETTER SHA
+0A59;0A16 0A3C;0A16 0A3C;0A16 0A3C;0A16 0A3C; # (ਖ਼; ਖ◌਼; ਖ◌਼; ਖ◌਼; ਖ◌਼; ) GURMUKHI LETTER KHHA
+0A5A;0A17 0A3C;0A17 0A3C;0A17 0A3C;0A17 0A3C; # (ਗ਼; ਗ◌਼; ਗ◌਼; ਗ◌਼; ਗ◌਼; ) GURMUKHI LETTER GHHA
+0A5B;0A1C 0A3C;0A1C 0A3C;0A1C 0A3C;0A1C 0A3C; # (ਜ਼; ਜ◌਼; ਜ◌਼; ਜ◌਼; ਜ◌਼; ) GURMUKHI LETTER ZA
+0A5E;0A2B 0A3C;0A2B 0A3C;0A2B 0A3C;0A2B 0A3C; # (ਫ਼; ਫ◌਼; ਫ◌਼; ਫ◌਼; ਫ◌਼; ) GURMUKHI LETTER FA
+0B48;0B48;0B47 0B56;0B48;0B47 0B56; # (ୈ; ୈ; େ◌ୖ; ୈ; େ◌ୖ; ) ORIYA VOWEL SIGN AI
+0B4B;0B4B;0B47 0B3E;0B4B;0B47 0B3E; # (ୋ; ୋ; ୋ; ୋ; ୋ; ) ORIYA VOWEL SIGN O
+0B4C;0B4C;0B47 0B57;0B4C;0B47 0B57; # (ୌ; ୌ; ୌ; ୌ; ୌ; ) ORIYA VOWEL SIGN AU
+0B5C;0B21 0B3C;0B21 0B3C;0B21 0B3C;0B21 0B3C; # (ଡ଼; ଡ◌଼; ଡ◌଼; ଡ◌଼; ଡ◌଼; ) ORIYA LETTER RRA
+0B5D;0B22 0B3C;0B22 0B3C;0B22 0B3C;0B22 0B3C; # (ଢ଼; ଢ◌଼; ଢ◌଼; ଢ◌଼; ଢ◌଼; ) ORIYA LETTER RHA
+0B94;0B94;0B92 0BD7;0B94;0B92 0BD7; # (ஔ; ஔ; ஔ; ஔ; ஔ; ) TAMIL LETTER AU
+0BCA;0BCA;0BC6 0BBE;0BCA;0BC6 0BBE; # (ொ; ொ; ொ; ொ; ொ; ) TAMIL VOWEL SIGN O
+0BCB;0BCB;0BC7 0BBE;0BCB;0BC7 0BBE; # (ோ; ோ; ோ; ோ; ோ; ) TAMIL VOWEL SIGN OO
+0BCC;0BCC;0BC6 0BD7;0BCC;0BC6 0BD7; # (ௌ; ௌ; ௌ; ௌ; ௌ; ) TAMIL VOWEL SIGN AU
+0C48;0C48;0C46 0C56;0C48;0C46 0C56; # (◌ై; ◌ై; ◌ె◌ౖ; ◌ై; ◌ె◌ౖ; ) TELUGU VOWEL SIGN AI
+0CC0;0CC0;0CBF 0CD5;0CC0;0CBF 0CD5; # (ೀ; ೀ; ◌ೀ; ೀ; ◌ೀ; ) KANNADA VOWEL SIGN II
+0CC7;0CC7;0CC6 0CD5;0CC7;0CC6 0CD5; # (ೇ; ೇ; ◌ೇ; ೇ; ◌ೇ; ) KANNADA VOWEL SIGN EE
+0CC8;0CC8;0CC6 0CD6;0CC8;0CC6 0CD6; # (ೈ; ೈ; ◌ೈ; ೈ; ◌ೈ; ) KANNADA VOWEL SIGN AI
+0CCA;0CCA;0CC6 0CC2;0CCA;0CC6 0CC2; # (ೊ; ೊ; ◌ೊ; ೊ; ◌ೊ; ) KANNADA VOWEL SIGN O
+0CCB;0CCB;0CC6 0CC2 0CD5;0CCB;0CC6 0CC2 0CD5; # (ೋ; ೋ; ◌ೋ; ೋ; ◌ೋ; ) KANNADA VOWEL SIGN OO
+0D4A;0D4A;0D46 0D3E;0D4A;0D46 0D3E; # (ൊ; ൊ; ൊ; ൊ; ൊ; ) MALAYALAM VOWEL SIGN O
+0D4B;0D4B;0D47 0D3E;0D4B;0D47 0D3E; # (ോ; ോ; ോ; ോ; ോ; ) MALAYALAM VOWEL SIGN OO
+0D4C;0D4C;0D46 0D57;0D4C;0D46 0D57; # (ൌ; ൌ; ൌ; ൌ; ൌ; ) MALAYALAM VOWEL SIGN AU
+0DDA;0DDA;0DD9 0DCA;0DDA;0DD9 0DCA; # (ේ; ේ; ෙ◌්; ේ; ෙ◌්; ) SINHALA VOWEL SIGN DIGA KOMBUVA
+0DDC;0DDC;0DD9 0DCF;0DDC;0DD9 0DCF; # (ො; ො; ො; ො; ො; ) SINHALA VOWEL SIGN KOMBUVA HAA AELA-PILLA
+0DDD;0DDD;0DD9 0DCF 0DCA;0DDD;0DD9 0DCF 0DCA; # (ෝ; ෝ; ො◌්; ෝ; ො◌්; ) SINHALA VOWEL SIGN KOMBUVA HAA DIGA AELA-PILLA
+0DDE;0DDE;0DD9 0DDF;0DDE;0DD9 0DDF; # (ෞ; ෞ; ෞ; ෞ; ෞ; ) SINHALA VOWEL SIGN KOMBUVA HAA GAYANUKITTA
+0E33;0E33;0E33;0E4D 0E32;0E4D 0E32; # (ำ; ำ; ำ; ◌ํา; ◌ํา; ) THAI CHARACTER SARA AM
+0EB3;0EB3;0EB3;0ECD 0EB2;0ECD 0EB2; # (ຳ; ຳ; ຳ; ◌ໍາ; ◌ໍາ; ) LAO VOWEL SIGN AM
+0EDC;0EDC;0EDC;0EAB 0E99;0EAB 0E99; # (ໜ; ໜ; ໜ; ຫນ; ຫນ; ) LAO HO NO
+0EDD;0EDD;0EDD;0EAB 0EA1;0EAB 0EA1; # (ໝ; ໝ; ໝ; ຫມ; ຫມ; ) LAO HO MO
+0F0C;0F0C;0F0C;0F0B;0F0B; # (༌; ༌; ༌; ་; ་; ) TIBETAN MARK DELIMITER TSHEG BSTAR
+0F43;0F42 0FB7;0F42 0FB7;0F42 0FB7;0F42 0FB7; # (གྷ; ག◌ྷ; ག◌ྷ; ག◌ྷ; ག◌ྷ; ) TIBETAN LETTER GHA
+0F4D;0F4C 0FB7;0F4C 0FB7;0F4C 0FB7;0F4C 0FB7; # (ཌྷ; ཌ◌ྷ; ཌ◌ྷ; ཌ◌ྷ; ཌ◌ྷ; ) TIBETAN LETTER DDHA
+0F52;0F51 0FB7;0F51 0FB7;0F51 0FB7;0F51 0FB7; # (དྷ; ད◌ྷ; ད◌ྷ; ད◌ྷ; ད◌ྷ; ) TIBETAN LETTER DHA
+0F57;0F56 0FB7;0F56 0FB7;0F56 0FB7;0F56 0FB7; # (བྷ; བ◌ྷ; བ◌ྷ; བ◌ྷ; བ◌ྷ; ) TIBETAN LETTER BHA
+0F5C;0F5B 0FB7;0F5B 0FB7;0F5B 0FB7;0F5B 0FB7; # (ཛྷ; ཛ◌ྷ; ཛ◌ྷ; ཛ◌ྷ; ཛ◌ྷ; ) TIBETAN LETTER DZHA
+0F69;0F40 0FB5;0F40 0FB5;0F40 0FB5;0F40 0FB5; # (ཀྵ; ཀ◌ྵ; ཀ◌ྵ; ཀ◌ྵ; ཀ◌ྵ; ) TIBETAN LETTER KSSA
+0F73;0F71 0F72;0F71 0F72;0F71 0F72;0F71 0F72; # (◌ཱི; ◌ཱ◌ི; ◌ཱ◌ི; ◌ཱ◌ི; ◌ཱ◌ི; ) TIBETAN VOWEL SIGN II
+0F75;0F71 0F74;0F71 0F74;0F71 0F74;0F71 0F74; # (◌ཱུ; ◌ཱ◌ུ; ◌ཱ◌ུ; ◌ཱ◌ུ; ◌ཱ◌ུ; ) TIBETAN VOWEL SIGN UU
+0F76;0FB2 0F80;0FB2 0F80;0FB2 0F80;0FB2 0F80; # (◌ྲྀ; ◌ྲ◌ྀ; ◌ྲ◌ྀ; ◌ྲ◌ྀ; ◌ྲ◌ྀ; ) TIBETAN VOWEL SIGN VOCALIC R
+0F77;0F77;0F77;0FB2 0F71 0F80;0FB2 0F71 0F80; # (◌ཷ; ◌ཷ; ◌ཷ; ◌ྲ◌ཱ◌ྀ; ◌ྲ◌ཱ◌ྀ; ) TIBETAN VOWEL SIGN VOCALIC RR
+0F78;0FB3 0F80;0FB3 0F80;0FB3 0F80;0FB3 0F80; # (◌ླྀ; ◌ླ◌ྀ; ◌ླ◌ྀ; ◌ླ◌ྀ; ◌ླ◌ྀ; ) TIBETAN VOWEL SIGN VOCALIC L
+0F79;0F79;0F79;0FB3 0F71 0F80;0FB3 0F71 0F80; # (◌ཹ; ◌ཹ; ◌ཹ; ◌ླ◌ཱ◌ྀ; ◌ླ◌ཱ◌ྀ; ) TIBETAN VOWEL SIGN VOCALIC LL
+0F81;0F71 0F80;0F71 0F80;0F71 0F80;0F71 0F80; # (◌ཱྀ; ◌ཱ◌ྀ; ◌ཱ◌ྀ; ◌ཱ◌ྀ; ◌ཱ◌ྀ; ) TIBETAN VOWEL SIGN REVERSED II
+0F93;0F92 0FB7;0F92 0FB7;0F92 0FB7;0F92 0FB7; # (◌ྒྷ; ◌ྒ◌ྷ; ◌ྒ◌ྷ; ◌ྒ◌ྷ; ◌ྒ◌ྷ; ) TIBETAN SUBJOINED LETTER GHA
+0F9D;0F9C 0FB7;0F9C 0FB7;0F9C 0FB7;0F9C 0FB7; # (◌ྜྷ; ◌ྜ◌ྷ; ◌ྜ◌ྷ; ◌ྜ◌ྷ; ◌ྜ◌ྷ; ) TIBETAN SUBJOINED LETTER DDHA
+0FA2;0FA1 0FB7;0FA1 0FB7;0FA1 0FB7;0FA1 0FB7; # (◌ྡྷ; ◌ྡ◌ྷ; ◌ྡ◌ྷ; ◌ྡ◌ྷ; ◌ྡ◌ྷ; ) TIBETAN SUBJOINED LETTER DHA
+0FA7;0FA6 0FB7;0FA6 0FB7;0FA6 0FB7;0FA6 0FB7; # (◌ྦྷ; ◌ྦ◌ྷ; ◌ྦ◌ྷ; ◌ྦ◌ྷ; ◌ྦ◌ྷ; ) TIBETAN SUBJOINED LETTER BHA
+0FAC;0FAB 0FB7;0FAB 0FB7;0FAB 0FB7;0FAB 0FB7; # (◌ྫྷ; ◌ྫ◌ྷ; ◌ྫ◌ྷ; ◌ྫ◌ྷ; ◌ྫ◌ྷ; ) TIBETAN SUBJOINED LETTER DZHA
+0FB9;0F90 0FB5;0F90 0FB5;0F90 0FB5;0F90 0FB5; # (◌ྐྵ; ◌ྐ◌ྵ; ◌ྐ◌ྵ; ◌ྐ◌ྵ; ◌ྐ◌ྵ; ) TIBETAN SUBJOINED LETTER KSSA
+1026;1026;1025 102E;1026;1025 102E; # (ဦ; ဦ; ဥ◌ီ; ဦ; ဥ◌ီ; ) MYANMAR LETTER UU
+1D2C;1D2C;1D2C;0041;0041; # (ᴬ; ᴬ; ᴬ; A; A; ) MODIFIER LETTER CAPITAL A
+1D2D;1D2D;1D2D;00C6;00C6; # (ᴭ; ᴭ; ᴭ; Æ; Æ; ) MODIFIER LETTER CAPITAL AE
+1D2E;1D2E;1D2E;0042;0042; # (ᴮ; ᴮ; ᴮ; B; B; ) MODIFIER LETTER CAPITAL B
+1D30;1D30;1D30;0044;0044; # (ᴰ; ᴰ; ᴰ; D; D; ) MODIFIER LETTER CAPITAL D
+1D31;1D31;1D31;0045;0045; # (ᴱ; ᴱ; ᴱ; E; E; ) MODIFIER LETTER CAPITAL E
+1D32;1D32;1D32;018E;018E; # (ᴲ; ᴲ; ᴲ; Ǝ; Ǝ; ) MODIFIER LETTER CAPITAL REVERSED E
+1D33;1D33;1D33;0047;0047; # (ᴳ; ᴳ; ᴳ; G; G; ) MODIFIER LETTER CAPITAL G
+1D34;1D34;1D34;0048;0048; # (ᴴ; ᴴ; ᴴ; H; H; ) MODIFIER LETTER CAPITAL H
+1D35;1D35;1D35;0049;0049; # (ᴵ; ᴵ; ᴵ; I; I; ) MODIFIER LETTER CAPITAL I
+1D36;1D36;1D36;004A;004A; # (ᴶ; ᴶ; ᴶ; J; J; ) MODIFIER LETTER CAPITAL J
+1D37;1D37;1D37;004B;004B; # (ᴷ; ᴷ; ᴷ; K; K; ) MODIFIER LETTER CAPITAL K
+1D38;1D38;1D38;004C;004C; # (ᴸ; ᴸ; ᴸ; L; L; ) MODIFIER LETTER CAPITAL L
+1D39;1D39;1D39;004D;004D; # (ᴹ; ᴹ; ᴹ; M; M; ) MODIFIER LETTER CAPITAL M
+1D3A;1D3A;1D3A;004E;004E; # (ᴺ; ᴺ; ᴺ; N; N; ) MODIFIER LETTER CAPITAL N
+1D3C;1D3C;1D3C;004F;004F; # (ᴼ; ᴼ; ᴼ; O; O; ) MODIFIER LETTER CAPITAL O
+1D3D;1D3D;1D3D;0222;0222; # (ᴽ; ᴽ; ᴽ; Ȣ; Ȣ; ) MODIFIER LETTER CAPITAL OU
+1D3E;1D3E;1D3E;0050;0050; # (ᴾ; ᴾ; ᴾ; P; P; ) MODIFIER LETTER CAPITAL P
+1D3F;1D3F;1D3F;0052;0052; # (ᴿ; ᴿ; ᴿ; R; R; ) MODIFIER LETTER CAPITAL R
+1D40;1D40;1D40;0054;0054; # (ᵀ; ᵀ; ᵀ; T; T; ) MODIFIER LETTER CAPITAL T
+1D41;1D41;1D41;0055;0055; # (ᵁ; ᵁ; ᵁ; U; U; ) MODIFIER LETTER CAPITAL U
+1D42;1D42;1D42;0057;0057; # (ᵂ; ᵂ; ᵂ; W; W; ) MODIFIER LETTER CAPITAL W
+1D43;1D43;1D43;0061;0061; # (ᵃ; ᵃ; ᵃ; a; a; ) MODIFIER LETTER SMALL A
+1D44;1D44;1D44;0250;0250; # (ᵄ; ᵄ; ᵄ; ɐ; ɐ; ) MODIFIER LETTER SMALL TURNED A
+1D45;1D45;1D45;0251;0251; # (ᵅ; ᵅ; ᵅ; ɑ; ɑ; ) MODIFIER LETTER SMALL ALPHA
+1D46;1D46;1D46;1D02;1D02; # (ᵆ; ᵆ; ᵆ; ᴂ; ᴂ; ) MODIFIER LETTER SMALL TURNED AE
+1D47;1D47;1D47;0062;0062; # (ᵇ; ᵇ; ᵇ; b; b; ) MODIFIER LETTER SMALL B
+1D48;1D48;1D48;0064;0064; # (ᵈ; ᵈ; ᵈ; d; d; ) MODIFIER LETTER SMALL D
+1D49;1D49;1D49;0065;0065; # (ᵉ; ᵉ; ᵉ; e; e; ) MODIFIER LETTER SMALL E
+1D4A;1D4A;1D4A;0259;0259; # (ᵊ; ᵊ; ᵊ; ə; ə; ) MODIFIER LETTER SMALL SCHWA
+1D4B;1D4B;1D4B;025B;025B; # (ᵋ; ᵋ; ᵋ; ɛ; ɛ; ) MODIFIER LETTER SMALL OPEN E
+1D4C;1D4C;1D4C;025C;025C; # (ᵌ; ᵌ; ᵌ; ɜ; ɜ; ) MODIFIER LETTER SMALL TURNED OPEN E
+1D4D;1D4D;1D4D;0067;0067; # (ᵍ; ᵍ; ᵍ; g; g; ) MODIFIER LETTER SMALL G
+1D4F;1D4F;1D4F;006B;006B; # (ᵏ; ᵏ; ᵏ; k; k; ) MODIFIER LETTER SMALL K
+1D50;1D50;1D50;006D;006D; # (ᵐ; ᵐ; ᵐ; m; m; ) MODIFIER LETTER SMALL M
+1D51;1D51;1D51;014B;014B; # (ᵑ; ᵑ; ᵑ; ŋ; ŋ; ) MODIFIER LETTER SMALL ENG
+1D52;1D52;1D52;006F;006F; # (ᵒ; ᵒ; ᵒ; o; o; ) MODIFIER LETTER SMALL O
+1D53;1D53;1D53;0254;0254; # (ᵓ; ᵓ; ᵓ; ɔ; ɔ; ) MODIFIER LETTER SMALL OPEN O
+1D54;1D54;1D54;1D16;1D16; # (ᵔ; ᵔ; ᵔ; ᴖ; ᴖ; ) MODIFIER LETTER SMALL TOP HALF O
+1D55;1D55;1D55;1D17;1D17; # (ᵕ; ᵕ; ᵕ; ᴗ; ᴗ; ) MODIFIER LETTER SMALL BOTTOM HALF O
+1D56;1D56;1D56;0070;0070; # (ᵖ; ᵖ; ᵖ; p; p; ) MODIFIER LETTER SMALL P
+1D57;1D57;1D57;0074;0074; # (ᵗ; ᵗ; ᵗ; t; t; ) MODIFIER LETTER SMALL T
+1D58;1D58;1D58;0075;0075; # (ᵘ; ᵘ; ᵘ; u; u; ) MODIFIER LETTER SMALL U
+1D59;1D59;1D59;1D1D;1D1D; # (ᵙ; ᵙ; ᵙ; ᴝ; ᴝ; ) MODIFIER LETTER SMALL SIDEWAYS U
+1D5A;1D5A;1D5A;026F;026F; # (ᵚ; ᵚ; ᵚ; ɯ; ɯ; ) MODIFIER LETTER SMALL TURNED M
+1D5B;1D5B;1D5B;0076;0076; # (ᵛ; ᵛ; ᵛ; v; v; ) MODIFIER LETTER SMALL V
+1D5C;1D5C;1D5C;1D25;1D25; # (ᵜ; ᵜ; ᵜ; ᴥ; ᴥ; ) MODIFIER LETTER SMALL AIN
+1D5D;1D5D;1D5D;03B2;03B2; # (ᵝ; ᵝ; ᵝ; β; β; ) MODIFIER LETTER SMALL BETA
+1D5E;1D5E;1D5E;03B3;03B3; # (ᵞ; ᵞ; ᵞ; γ; γ; ) MODIFIER LETTER SMALL GREEK GAMMA
+1D5F;1D5F;1D5F;03B4;03B4; # (ᵟ; ᵟ; ᵟ; δ; δ; ) MODIFIER LETTER SMALL DELTA
+1D60;1D60;1D60;03C6;03C6; # (ᵠ; ᵠ; ᵠ; φ; φ; ) MODIFIER LETTER SMALL GREEK PHI
+1D61;1D61;1D61;03C7;03C7; # (ᵡ; ᵡ; ᵡ; χ; χ; ) MODIFIER LETTER SMALL CHI
+1D62;1D62;1D62;0069;0069; # (ᵢ; ᵢ; ᵢ; i; i; ) LATIN SUBSCRIPT SMALL LETTER I
+1D63;1D63;1D63;0072;0072; # (ᵣ; ᵣ; ᵣ; r; r; ) LATIN SUBSCRIPT SMALL LETTER R
+1D64;1D64;1D64;0075;0075; # (ᵤ; ᵤ; ᵤ; u; u; ) LATIN SUBSCRIPT SMALL LETTER U
+1D65;1D65;1D65;0076;0076; # (ᵥ; ᵥ; ᵥ; v; v; ) LATIN SUBSCRIPT SMALL LETTER V
+1D66;1D66;1D66;03B2;03B2; # (ᵦ; ᵦ; ᵦ; β; β; ) GREEK SUBSCRIPT SMALL LETTER BETA
+1D67;1D67;1D67;03B3;03B3; # (ᵧ; ᵧ; ᵧ; γ; γ; ) GREEK SUBSCRIPT SMALL LETTER GAMMA
+1D68;1D68;1D68;03C1;03C1; # (ᵨ; ᵨ; ᵨ; ρ; ρ; ) GREEK SUBSCRIPT SMALL LETTER RHO
+1D69;1D69;1D69;03C6;03C6; # (ᵩ; ᵩ; ᵩ; φ; φ; ) GREEK SUBSCRIPT SMALL LETTER PHI
+1D6A;1D6A;1D6A;03C7;03C7; # (ᵪ; ᵪ; ᵪ; χ; χ; ) GREEK SUBSCRIPT SMALL LETTER CHI
+1E00;1E00;0041 0325;1E00;0041 0325; # (Ḁ; Ḁ; A◌̥; Ḁ; A◌̥; ) LATIN CAPITAL LETTER A WITH RING BELOW
+1E01;1E01;0061 0325;1E01;0061 0325; # (ḁ; ḁ; a◌̥; ḁ; a◌̥; ) LATIN SMALL LETTER A WITH RING BELOW
+1E02;1E02;0042 0307;1E02;0042 0307; # (Ḃ; Ḃ; B◌̇; Ḃ; B◌̇; ) LATIN CAPITAL LETTER B WITH DOT ABOVE
+1E03;1E03;0062 0307;1E03;0062 0307; # (ḃ; ḃ; b◌̇; ḃ; b◌̇; ) LATIN SMALL LETTER B WITH DOT ABOVE
+1E04;1E04;0042 0323;1E04;0042 0323; # (Ḅ; Ḅ; B◌̣; Ḅ; B◌̣; ) LATIN CAPITAL LETTER B WITH DOT BELOW
+1E05;1E05;0062 0323;1E05;0062 0323; # (ḅ; ḅ; b◌̣; ḅ; b◌̣; ) LATIN SMALL LETTER B WITH DOT BELOW
+1E06;1E06;0042 0331;1E06;0042 0331; # (Ḇ; Ḇ; B◌̱; Ḇ; B◌̱; ) LATIN CAPITAL LETTER B WITH LINE BELOW
+1E07;1E07;0062 0331;1E07;0062 0331; # (ḇ; ḇ; b◌̱; ḇ; b◌̱; ) LATIN SMALL LETTER B WITH LINE BELOW
+1E08;1E08;0043 0327 0301;1E08;0043 0327 0301; # (Ḉ; Ḉ; C◌̧◌́; Ḉ; C◌̧◌́; ) LATIN CAPITAL LETTER C WITH CEDILLA AND ACUTE
+1E09;1E09;0063 0327 0301;1E09;0063 0327 0301; # (ḉ; ḉ; c◌̧◌́; ḉ; c◌̧◌́; ) LATIN SMALL LETTER C WITH CEDILLA AND ACUTE
+1E0A;1E0A;0044 0307;1E0A;0044 0307; # (Ḋ; Ḋ; D◌̇; Ḋ; D◌̇; ) LATIN CAPITAL LETTER D WITH DOT ABOVE
+1E0B;1E0B;0064 0307;1E0B;0064 0307; # (ḋ; ḋ; d◌̇; ḋ; d◌̇; ) LATIN SMALL LETTER D WITH DOT ABOVE
+1E0C;1E0C;0044 0323;1E0C;0044 0323; # (Ḍ; Ḍ; D◌̣; Ḍ; D◌̣; ) LATIN CAPITAL LETTER D WITH DOT BELOW
+1E0D;1E0D;0064 0323;1E0D;0064 0323; # (ḍ; ḍ; d◌̣; ḍ; d◌̣; ) LATIN SMALL LETTER D WITH DOT BELOW
+1E0E;1E0E;0044 0331;1E0E;0044 0331; # (Ḏ; Ḏ; D◌̱; Ḏ; D◌̱; ) LATIN CAPITAL LETTER D WITH LINE BELOW
+1E0F;1E0F;0064 0331;1E0F;0064 0331; # (ḏ; ḏ; d◌̱; ḏ; d◌̱; ) LATIN SMALL LETTER D WITH LINE BELOW
+1E10;1E10;0044 0327;1E10;0044 0327; # (Ḑ; Ḑ; D◌̧; Ḑ; D◌̧; ) LATIN CAPITAL LETTER D WITH CEDILLA
+1E11;1E11;0064 0327;1E11;0064 0327; # (ḑ; ḑ; d◌̧; ḑ; d◌̧; ) LATIN SMALL LETTER D WITH CEDILLA
+1E12;1E12;0044 032D;1E12;0044 032D; # (Ḓ; Ḓ; D◌̭; Ḓ; D◌̭; ) LATIN CAPITAL LETTER D WITH CIRCUMFLEX BELOW
+1E13;1E13;0064 032D;1E13;0064 032D; # (ḓ; ḓ; d◌̭; ḓ; d◌̭; ) LATIN SMALL LETTER D WITH CIRCUMFLEX BELOW
+1E14;1E14;0045 0304 0300;1E14;0045 0304 0300; # (Ḕ; Ḕ; E◌̄◌̀; Ḕ; E◌̄◌̀; ) LATIN CAPITAL LETTER E WITH MACRON AND GRAVE
+1E15;1E15;0065 0304 0300;1E15;0065 0304 0300; # (ḕ; ḕ; e◌̄◌̀; ḕ; e◌̄◌̀; ) LATIN SMALL LETTER E WITH MACRON AND GRAVE
+1E16;1E16;0045 0304 0301;1E16;0045 0304 0301; # (Ḗ; Ḗ; E◌̄◌́; Ḗ; E◌̄◌́; ) LATIN CAPITAL LETTER E WITH MACRON AND ACUTE
+1E17;1E17;0065 0304 0301;1E17;0065 0304 0301; # (ḗ; ḗ; e◌̄◌́; ḗ; e◌̄◌́; ) LATIN SMALL LETTER E WITH MACRON AND ACUTE
+1E18;1E18;0045 032D;1E18;0045 032D; # (Ḙ; Ḙ; E◌̭; Ḙ; E◌̭; ) LATIN CAPITAL LETTER E WITH CIRCUMFLEX BELOW
+1E19;1E19;0065 032D;1E19;0065 032D; # (ḙ; ḙ; e◌̭; ḙ; e◌̭; ) LATIN SMALL LETTER E WITH CIRCUMFLEX BELOW
+1E1A;1E1A;0045 0330;1E1A;0045 0330; # (Ḛ; Ḛ; E◌̰; Ḛ; E◌̰; ) LATIN CAPITAL LETTER E WITH TILDE BELOW
+1E1B;1E1B;0065 0330;1E1B;0065 0330; # (ḛ; ḛ; e◌̰; ḛ; e◌̰; ) LATIN SMALL LETTER E WITH TILDE BELOW
+1E1C;1E1C;0045 0327 0306;1E1C;0045 0327 0306; # (Ḝ; Ḝ; E◌̧◌̆; Ḝ; E◌̧◌̆; ) LATIN CAPITAL LETTER E WITH CEDILLA AND BREVE
+1E1D;1E1D;0065 0327 0306;1E1D;0065 0327 0306; # (ḝ; ḝ; e◌̧◌̆; ḝ; e◌̧◌̆; ) LATIN SMALL LETTER E WITH CEDILLA AND BREVE
+1E1E;1E1E;0046 0307;1E1E;0046 0307; # (Ḟ; Ḟ; F◌̇; Ḟ; F◌̇; ) LATIN CAPITAL LETTER F WITH DOT ABOVE
+1E1F;1E1F;0066 0307;1E1F;0066 0307; # (ḟ; ḟ; f◌̇; ḟ; f◌̇; ) LATIN SMALL LETTER F WITH DOT ABOVE
+1E20;1E20;0047 0304;1E20;0047 0304; # (Ḡ; Ḡ; G◌̄; Ḡ; G◌̄; ) LATIN CAPITAL LETTER G WITH MACRON
+1E21;1E21;0067 0304;1E21;0067 0304; # (ḡ; ḡ; g◌̄; ḡ; g◌̄; ) LATIN SMALL LETTER G WITH MACRON
+1E22;1E22;0048 0307;1E22;0048 0307; # (Ḣ; Ḣ; H◌̇; Ḣ; H◌̇; ) LATIN CAPITAL LETTER H WITH DOT ABOVE
+1E23;1E23;0068 0307;1E23;0068 0307; # (ḣ; ḣ; h◌̇; ḣ; h◌̇; ) LATIN SMALL LETTER H WITH DOT ABOVE
+1E24;1E24;0048 0323;1E24;0048 0323; # (Ḥ; Ḥ; H◌̣; Ḥ; H◌̣; ) LATIN CAPITAL LETTER H WITH DOT BELOW
+1E25;1E25;0068 0323;1E25;0068 0323; # (ḥ; ḥ; h◌̣; ḥ; h◌̣; ) LATIN SMALL LETTER H WITH DOT BELOW
+1E26;1E26;0048 0308;1E26;0048 0308; # (Ḧ; Ḧ; H◌̈; Ḧ; H◌̈; ) LATIN CAPITAL LETTER H WITH DIAERESIS
+1E27;1E27;0068 0308;1E27;0068 0308; # (ḧ; ḧ; h◌̈; ḧ; h◌̈; ) LATIN SMALL LETTER H WITH DIAERESIS
+1E28;1E28;0048 0327;1E28;0048 0327; # (Ḩ; Ḩ; H◌̧; Ḩ; H◌̧; ) LATIN CAPITAL LETTER H WITH CEDILLA
+1E29;1E29;0068 0327;1E29;0068 0327; # (ḩ; ḩ; h◌̧; ḩ; h◌̧; ) LATIN SMALL LETTER H WITH CEDILLA
+1E2A;1E2A;0048 032E;1E2A;0048 032E; # (Ḫ; Ḫ; H◌̮; Ḫ; H◌̮; ) LATIN CAPITAL LETTER H WITH BREVE BELOW
+1E2B;1E2B;0068 032E;1E2B;0068 032E; # (ḫ; ḫ; h◌̮; ḫ; h◌̮; ) LATIN SMALL LETTER H WITH BREVE BELOW
+1E2C;1E2C;0049 0330;1E2C;0049 0330; # (Ḭ; Ḭ; I◌̰; Ḭ; I◌̰; ) LATIN CAPITAL LETTER I WITH TILDE BELOW
+1E2D;1E2D;0069 0330;1E2D;0069 0330; # (ḭ; ḭ; i◌̰; ḭ; i◌̰; ) LATIN SMALL LETTER I WITH TILDE BELOW
+1E2E;1E2E;0049 0308 0301;1E2E;0049 0308 0301; # (Ḯ; Ḯ; I◌̈◌́; Ḯ; I◌̈◌́; ) LATIN CAPITAL LETTER I WITH DIAERESIS AND ACUTE
+1E2F;1E2F;0069 0308 0301;1E2F;0069 0308 0301; # (ḯ; ḯ; i◌̈◌́; ḯ; i◌̈◌́; ) LATIN SMALL LETTER I WITH DIAERESIS AND ACUTE
+1E30;1E30;004B 0301;1E30;004B 0301; # (Ḱ; Ḱ; K◌́; Ḱ; K◌́; ) LATIN CAPITAL LETTER K WITH ACUTE
+1E31;1E31;006B 0301;1E31;006B 0301; # (ḱ; ḱ; k◌́; ḱ; k◌́; ) LATIN SMALL LETTER K WITH ACUTE
+1E32;1E32;004B 0323;1E32;004B 0323; # (Ḳ; Ḳ; K◌̣; Ḳ; K◌̣; ) LATIN CAPITAL LETTER K WITH DOT BELOW
+1E33;1E33;006B 0323;1E33;006B 0323; # (ḳ; ḳ; k◌̣; ḳ; k◌̣; ) LATIN SMALL LETTER K WITH DOT BELOW
+1E34;1E34;004B 0331;1E34;004B 0331; # (Ḵ; Ḵ; K◌̱; Ḵ; K◌̱; ) LATIN CAPITAL LETTER K WITH LINE BELOW
+1E35;1E35;006B 0331;1E35;006B 0331; # (ḵ; ḵ; k◌̱; ḵ; k◌̱; ) LATIN SMALL LETTER K WITH LINE BELOW
+1E36;1E36;004C 0323;1E36;004C 0323; # (Ḷ; Ḷ; L◌̣; Ḷ; L◌̣; ) LATIN CAPITAL LETTER L WITH DOT BELOW
+1E37;1E37;006C 0323;1E37;006C 0323; # (ḷ; ḷ; l◌̣; ḷ; l◌̣; ) LATIN SMALL LETTER L WITH DOT BELOW
+1E38;1E38;004C 0323 0304;1E38;004C 0323 0304; # (Ḹ; Ḹ; L◌̣◌̄; Ḹ; L◌̣◌̄; ) LATIN CAPITAL LETTER L WITH DOT BELOW AND MACRON
+1E39;1E39;006C 0323 0304;1E39;006C 0323 0304; # (ḹ; ḹ; l◌̣◌̄; ḹ; l◌̣◌̄; ) LATIN SMALL LETTER L WITH DOT BELOW AND MACRON
+1E3A;1E3A;004C 0331;1E3A;004C 0331; # (Ḻ; Ḻ; L◌̱; Ḻ; L◌̱; ) LATIN CAPITAL LETTER L WITH LINE BELOW
+1E3B;1E3B;006C 0331;1E3B;006C 0331; # (ḻ; ḻ; l◌̱; ḻ; l◌̱; ) LATIN SMALL LETTER L WITH LINE BELOW
+1E3C;1E3C;004C 032D;1E3C;004C 032D; # (Ḽ; Ḽ; L◌̭; Ḽ; L◌̭; ) LATIN CAPITAL LETTER L WITH CIRCUMFLEX BELOW
+1E3D;1E3D;006C 032D;1E3D;006C 032D; # (ḽ; ḽ; l◌̭; ḽ; l◌̭; ) LATIN SMALL LETTER L WITH CIRCUMFLEX BELOW
+1E3E;1E3E;004D 0301;1E3E;004D 0301; # (Ḿ; Ḿ; M◌́; Ḿ; M◌́; ) LATIN CAPITAL LETTER M WITH ACUTE
+1E3F;1E3F;006D 0301;1E3F;006D 0301; # (ḿ; ḿ; m◌́; ḿ; m◌́; ) LATIN SMALL LETTER M WITH ACUTE
+1E40;1E40;004D 0307;1E40;004D 0307; # (Ṁ; Ṁ; M◌̇; Ṁ; M◌̇; ) LATIN CAPITAL LETTER M WITH DOT ABOVE
+1E41;1E41;006D 0307;1E41;006D 0307; # (ṁ; ṁ; m◌̇; ṁ; m◌̇; ) LATIN SMALL LETTER M WITH DOT ABOVE
+1E42;1E42;004D 0323;1E42;004D 0323; # (Ṃ; Ṃ; M◌̣; Ṃ; M◌̣; ) LATIN CAPITAL LETTER M WITH DOT BELOW
+1E43;1E43;006D 0323;1E43;006D 0323; # (ṃ; ṃ; m◌̣; ṃ; m◌̣; ) LATIN SMALL LETTER M WITH DOT BELOW
+1E44;1E44;004E 0307;1E44;004E 0307; # (Ṅ; Ṅ; N◌̇; Ṅ; N◌̇; ) LATIN CAPITAL LETTER N WITH DOT ABOVE
+1E45;1E45;006E 0307;1E45;006E 0307; # (ṅ; ṅ; n◌̇; ṅ; n◌̇; ) LATIN SMALL LETTER N WITH DOT ABOVE
+1E46;1E46;004E 0323;1E46;004E 0323; # (Ṇ; Ṇ; N◌̣; Ṇ; N◌̣; ) LATIN CAPITAL LETTER N WITH DOT BELOW
+1E47;1E47;006E 0323;1E47;006E 0323; # (ṇ; ṇ; n◌̣; ṇ; n◌̣; ) LATIN SMALL LETTER N WITH DOT BELOW
+1E48;1E48;004E 0331;1E48;004E 0331; # (Ṉ; Ṉ; N◌̱; Ṉ; N◌̱; ) LATIN CAPITAL LETTER N WITH LINE BELOW
+1E49;1E49;006E 0331;1E49;006E 0331; # (ṉ; ṉ; n◌̱; ṉ; n◌̱; ) LATIN SMALL LETTER N WITH LINE BELOW
+1E4A;1E4A;004E 032D;1E4A;004E 032D; # (Ṋ; Ṋ; N◌̭; Ṋ; N◌̭; ) LATIN CAPITAL LETTER N WITH CIRCUMFLEX BELOW
+1E4B;1E4B;006E 032D;1E4B;006E 032D; # (ṋ; ṋ; n◌̭; ṋ; n◌̭; ) LATIN SMALL LETTER N WITH CIRCUMFLEX BELOW
+1E4C;1E4C;004F 0303 0301;1E4C;004F 0303 0301; # (Ṍ; Ṍ; O◌̃◌́; Ṍ; O◌̃◌́; ) LATIN CAPITAL LETTER O WITH TILDE AND ACUTE
+1E4D;1E4D;006F 0303 0301;1E4D;006F 0303 0301; # (ṍ; ṍ; o◌̃◌́; ṍ; o◌̃◌́; ) LATIN SMALL LETTER O WITH TILDE AND ACUTE
+1E4E;1E4E;004F 0303 0308;1E4E;004F 0303 0308; # (Ṏ; Ṏ; O◌̃◌̈; Ṏ; O◌̃◌̈; ) LATIN CAPITAL LETTER O WITH TILDE AND DIAERESIS
+1E4F;1E4F;006F 0303 0308;1E4F;006F 0303 0308; # (ṏ; ṏ; o◌̃◌̈; ṏ; o◌̃◌̈; ) LATIN SMALL LETTER O WITH TILDE AND DIAERESIS
+1E50;1E50;004F 0304 0300;1E50;004F 0304 0300; # (Ṑ; Ṑ; O◌̄◌̀; Ṑ; O◌̄◌̀; ) LATIN CAPITAL LETTER O WITH MACRON AND GRAVE
+1E51;1E51;006F 0304 0300;1E51;006F 0304 0300; # (ṑ; ṑ; o◌̄◌̀; ṑ; o◌̄◌̀; ) LATIN SMALL LETTER O WITH MACRON AND GRAVE
+1E52;1E52;004F 0304 0301;1E52;004F 0304 0301; # (Ṓ; Ṓ; O◌̄◌́; Ṓ; O◌̄◌́; ) LATIN CAPITAL LETTER O WITH MACRON AND ACUTE
+1E53;1E53;006F 0304 0301;1E53;006F 0304 0301; # (ṓ; ṓ; o◌̄◌́; ṓ; o◌̄◌́; ) LATIN SMALL LETTER O WITH MACRON AND ACUTE
+1E54;1E54;0050 0301;1E54;0050 0301; # (Ṕ; Ṕ; P◌́; Ṕ; P◌́; ) LATIN CAPITAL LETTER P WITH ACUTE
+1E55;1E55;0070 0301;1E55;0070 0301; # (ṕ; ṕ; p◌́; ṕ; p◌́; ) LATIN SMALL LETTER P WITH ACUTE
+1E56;1E56;0050 0307;1E56;0050 0307; # (Ṗ; Ṗ; P◌̇; Ṗ; P◌̇; ) LATIN CAPITAL LETTER P WITH DOT ABOVE
+1E57;1E57;0070 0307;1E57;0070 0307; # (ṗ; ṗ; p◌̇; ṗ; p◌̇; ) LATIN SMALL LETTER P WITH DOT ABOVE
+1E58;1E58;0052 0307;1E58;0052 0307; # (Ṙ; Ṙ; R◌̇; Ṙ; R◌̇; ) LATIN CAPITAL LETTER R WITH DOT ABOVE
+1E59;1E59;0072 0307;1E59;0072 0307; # (ṙ; ṙ; r◌̇; ṙ; r◌̇; ) LATIN SMALL LETTER R WITH DOT ABOVE
+1E5A;1E5A;0052 0323;1E5A;0052 0323; # (Ṛ; Ṛ; R◌̣; Ṛ; R◌̣; ) LATIN CAPITAL LETTER R WITH DOT BELOW
+1E5B;1E5B;0072 0323;1E5B;0072 0323; # (ṛ; ṛ; r◌̣; ṛ; r◌̣; ) LATIN SMALL LETTER R WITH DOT BELOW
+1E5C;1E5C;0052 0323 0304;1E5C;0052 0323 0304; # (Ṝ; Ṝ; R◌̣◌̄; Ṝ; R◌̣◌̄; ) LATIN CAPITAL LETTER R WITH DOT BELOW AND MACRON
+1E5D;1E5D;0072 0323 0304;1E5D;0072 0323 0304; # (ṝ; ṝ; r◌̣◌̄; ṝ; r◌̣◌̄; ) LATIN SMALL LETTER R WITH DOT BELOW AND MACRON
+1E5E;1E5E;0052 0331;1E5E;0052 0331; # (Ṟ; Ṟ; R◌̱; Ṟ; R◌̱; ) LATIN CAPITAL LETTER R WITH LINE BELOW
+1E5F;1E5F;0072 0331;1E5F;0072 0331; # (ṟ; ṟ; r◌̱; ṟ; r◌̱; ) LATIN SMALL LETTER R WITH LINE BELOW
+1E60;1E60;0053 0307;1E60;0053 0307; # (Ṡ; Ṡ; S◌̇; Ṡ; S◌̇; ) LATIN CAPITAL LETTER S WITH DOT ABOVE
+1E61;1E61;0073 0307;1E61;0073 0307; # (ṡ; ṡ; s◌̇; ṡ; s◌̇; ) LATIN SMALL LETTER S WITH DOT ABOVE
+1E62;1E62;0053 0323;1E62;0053 0323; # (Ṣ; Ṣ; S◌̣; Ṣ; S◌̣; ) LATIN CAPITAL LETTER S WITH DOT BELOW
+1E63;1E63;0073 0323;1E63;0073 0323; # (ṣ; ṣ; s◌̣; ṣ; s◌̣; ) LATIN SMALL LETTER S WITH DOT BELOW
+1E64;1E64;0053 0301 0307;1E64;0053 0301 0307; # (Ṥ; Ṥ; S◌́◌̇; Ṥ; S◌́◌̇; ) LATIN CAPITAL LETTER S WITH ACUTE AND DOT ABOVE
+1E65;1E65;0073 0301 0307;1E65;0073 0301 0307; # (ṥ; ṥ; s◌́◌̇; ṥ; s◌́◌̇; ) LATIN SMALL LETTER S WITH ACUTE AND DOT ABOVE
+1E66;1E66;0053 030C 0307;1E66;0053 030C 0307; # (Ṧ; Ṧ; S◌̌◌̇; Ṧ; S◌̌◌̇; ) LATIN CAPITAL LETTER S WITH CARON AND DOT ABOVE
+1E67;1E67;0073 030C 0307;1E67;0073 030C 0307; # (ṧ; ṧ; s◌̌◌̇; ṧ; s◌̌◌̇; ) LATIN SMALL LETTER S WITH CARON AND DOT ABOVE
+1E68;1E68;0053 0323 0307;1E68;0053 0323 0307; # (Ṩ; Ṩ; S◌̣◌̇; Ṩ; S◌̣◌̇; ) LATIN CAPITAL LETTER S WITH DOT BELOW AND DOT ABOVE
+1E69;1E69;0073 0323 0307;1E69;0073 0323 0307; # (ṩ; ṩ; s◌̣◌̇; ṩ; s◌̣◌̇; ) LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE
+1E6A;1E6A;0054 0307;1E6A;0054 0307; # (Ṫ; Ṫ; T◌̇; Ṫ; T◌̇; ) LATIN CAPITAL LETTER T WITH DOT ABOVE
+1E6B;1E6B;0074 0307;1E6B;0074 0307; # (ṫ; ṫ; t◌̇; ṫ; t◌̇; ) LATIN SMALL LETTER T WITH DOT ABOVE
+1E6C;1E6C;0054 0323;1E6C;0054 0323; # (Ṭ; Ṭ; T◌̣; Ṭ; T◌̣; ) LATIN CAPITAL LETTER T WITH DOT BELOW
+1E6D;1E6D;0074 0323;1E6D;0074 0323; # (ṭ; ṭ; t◌̣; ṭ; t◌̣; ) LATIN SMALL LETTER T WITH DOT BELOW
+1E6E;1E6E;0054 0331;1E6E;0054 0331; # (Ṯ; Ṯ; T◌̱; Ṯ; T◌̱; ) LATIN CAPITAL LETTER T WITH LINE BELOW
+1E6F;1E6F;0074 0331;1E6F;0074 0331; # (ṯ; ṯ; t◌̱; ṯ; t◌̱; ) LATIN SMALL LETTER T WITH LINE BELOW
+1E70;1E70;0054 032D;1E70;0054 032D; # (Ṱ; Ṱ; T◌̭; Ṱ; T◌̭; ) LATIN CAPITAL LETTER T WITH CIRCUMFLEX BELOW
+1E71;1E71;0074 032D;1E71;0074 032D; # (ṱ; ṱ; t◌̭; ṱ; t◌̭; ) LATIN SMALL LETTER T WITH CIRCUMFLEX BELOW
+1E72;1E72;0055 0324;1E72;0055 0324; # (Ṳ; Ṳ; U◌̤; Ṳ; U◌̤; ) LATIN CAPITAL LETTER U WITH DIAERESIS BELOW
+1E73;1E73;0075 0324;1E73;0075 0324; # (ṳ; ṳ; u◌̤; ṳ; u◌̤; ) LATIN SMALL LETTER U WITH DIAERESIS BELOW
+1E74;1E74;0055 0330;1E74;0055 0330; # (Ṵ; Ṵ; U◌̰; Ṵ; U◌̰; ) LATIN CAPITAL LETTER U WITH TILDE BELOW
+1E75;1E75;0075 0330;1E75;0075 0330; # (ṵ; ṵ; u◌̰; ṵ; u◌̰; ) LATIN SMALL LETTER U WITH TILDE BELOW
+1E76;1E76;0055 032D;1E76;0055 032D; # (Ṷ; Ṷ; U◌̭; Ṷ; U◌̭; ) LATIN CAPITAL LETTER U WITH CIRCUMFLEX BELOW
+1E77;1E77;0075 032D;1E77;0075 032D; # (ṷ; ṷ; u◌̭; ṷ; u◌̭; ) LATIN SMALL LETTER U WITH CIRCUMFLEX BELOW
+1E78;1E78;0055 0303 0301;1E78;0055 0303 0301; # (Ṹ; Ṹ; U◌̃◌́; Ṹ; U◌̃◌́; ) LATIN CAPITAL LETTER U WITH TILDE AND ACUTE
+1E79;1E79;0075 0303 0301;1E79;0075 0303 0301; # (ṹ; ṹ; u◌̃◌́; ṹ; u◌̃◌́; ) LATIN SMALL LETTER U WITH TILDE AND ACUTE
+1E7A;1E7A;0055 0304 0308;1E7A;0055 0304 0308; # (Ṻ; Ṻ; U◌̄◌̈; Ṻ; U◌̄◌̈; ) LATIN CAPITAL LETTER U WITH MACRON AND DIAERESIS
+1E7B;1E7B;0075 0304 0308;1E7B;0075 0304 0308; # (ṻ; ṻ; u◌̄◌̈; ṻ; u◌̄◌̈; ) LATIN SMALL LETTER U WITH MACRON AND DIAERESIS
+1E7C;1E7C;0056 0303;1E7C;0056 0303; # (Ṽ; Ṽ; V◌̃; Ṽ; V◌̃; ) LATIN CAPITAL LETTER V WITH TILDE
+1E7D;1E7D;0076 0303;1E7D;0076 0303; # (ṽ; ṽ; v◌̃; ṽ; v◌̃; ) LATIN SMALL LETTER V WITH TILDE
+1E7E;1E7E;0056 0323;1E7E;0056 0323; # (Ṿ; Ṿ; V◌̣; Ṿ; V◌̣; ) LATIN CAPITAL LETTER V WITH DOT BELOW
+1E7F;1E7F;0076 0323;1E7F;0076 0323; # (ṿ; ṿ; v◌̣; ṿ; v◌̣; ) LATIN SMALL LETTER V WITH DOT BELOW
+1E80;1E80;0057 0300;1E80;0057 0300; # (Ẁ; Ẁ; W◌̀; Ẁ; W◌̀; ) LATIN CAPITAL LETTER W WITH GRAVE
+1E81;1E81;0077 0300;1E81;0077 0300; # (ẁ; ẁ; w◌̀; ẁ; w◌̀; ) LATIN SMALL LETTER W WITH GRAVE
+1E82;1E82;0057 0301;1E82;0057 0301; # (Ẃ; Ẃ; W◌́; Ẃ; W◌́; ) LATIN CAPITAL LETTER W WITH ACUTE
+1E83;1E83;0077 0301;1E83;0077 0301; # (ẃ; ẃ; w◌́; ẃ; w◌́; ) LATIN SMALL LETTER W WITH ACUTE
+1E84;1E84;0057 0308;1E84;0057 0308; # (Ẅ; Ẅ; W◌̈; Ẅ; W◌̈; ) LATIN CAPITAL LETTER W WITH DIAERESIS
+1E85;1E85;0077 0308;1E85;0077 0308; # (ẅ; ẅ; w◌̈; ẅ; w◌̈; ) LATIN SMALL LETTER W WITH DIAERESIS
+1E86;1E86;0057 0307;1E86;0057 0307; # (Ẇ; Ẇ; W◌̇; Ẇ; W◌̇; ) LATIN CAPITAL LETTER W WITH DOT ABOVE
+1E87;1E87;0077 0307;1E87;0077 0307; # (ẇ; ẇ; w◌̇; ẇ; w◌̇; ) LATIN SMALL LETTER W WITH DOT ABOVE
+1E88;1E88;0057 0323;1E88;0057 0323; # (Ẉ; Ẉ; W◌̣; Ẉ; W◌̣; ) LATIN CAPITAL LETTER W WITH DOT BELOW
+1E89;1E89;0077 0323;1E89;0077 0323; # (ẉ; ẉ; w◌̣; ẉ; w◌̣; ) LATIN SMALL LETTER W WITH DOT BELOW
+1E8A;1E8A;0058 0307;1E8A;0058 0307; # (Ẋ; Ẋ; X◌̇; Ẋ; X◌̇; ) LATIN CAPITAL LETTER X WITH DOT ABOVE
+1E8B;1E8B;0078 0307;1E8B;0078 0307; # (ẋ; ẋ; x◌̇; ẋ; x◌̇; ) LATIN SMALL LETTER X WITH DOT ABOVE
+1E8C;1E8C;0058 0308;1E8C;0058 0308; # (Ẍ; Ẍ; X◌̈; Ẍ; X◌̈; ) LATIN CAPITAL LETTER X WITH DIAERESIS
+1E8D;1E8D;0078 0308;1E8D;0078 0308; # (ẍ; ẍ; x◌̈; ẍ; x◌̈; ) LATIN SMALL LETTER X WITH DIAERESIS
+1E8E;1E8E;0059 0307;1E8E;0059 0307; # (Ẏ; Ẏ; Y◌̇; Ẏ; Y◌̇; ) LATIN CAPITAL LETTER Y WITH DOT ABOVE
+1E8F;1E8F;0079 0307;1E8F;0079 0307; # (ẏ; ẏ; y◌̇; ẏ; y◌̇; ) LATIN SMALL LETTER Y WITH DOT ABOVE
+1E90;1E90;005A 0302;1E90;005A 0302; # (Ẑ; Ẑ; Z◌̂; Ẑ; Z◌̂; ) LATIN CAPITAL LETTER Z WITH CIRCUMFLEX
+1E91;1E91;007A 0302;1E91;007A 0302; # (ẑ; ẑ; z◌̂; ẑ; z◌̂; ) LATIN SMALL LETTER Z WITH CIRCUMFLEX
+1E92;1E92;005A 0323;1E92;005A 0323; # (Ẓ; Ẓ; Z◌̣; Ẓ; Z◌̣; ) LATIN CAPITAL LETTER Z WITH DOT BELOW
+1E93;1E93;007A 0323;1E93;007A 0323; # (ẓ; ẓ; z◌̣; ẓ; z◌̣; ) LATIN SMALL LETTER Z WITH DOT BELOW
+1E94;1E94;005A 0331;1E94;005A 0331; # (Ẕ; Ẕ; Z◌̱; Ẕ; Z◌̱; ) LATIN CAPITAL LETTER Z WITH LINE BELOW
+1E95;1E95;007A 0331;1E95;007A 0331; # (ẕ; ẕ; z◌̱; ẕ; z◌̱; ) LATIN SMALL LETTER Z WITH LINE BELOW
+1E96;1E96;0068 0331;1E96;0068 0331; # (ẖ; ẖ; h◌̱; ẖ; h◌̱; ) LATIN SMALL LETTER H WITH LINE BELOW
+1E97;1E97;0074 0308;1E97;0074 0308; # (ẗ; ẗ; t◌̈; ẗ; t◌̈; ) LATIN SMALL LETTER T WITH DIAERESIS
+1E98;1E98;0077 030A;1E98;0077 030A; # (ẘ; ẘ; w◌̊; ẘ; w◌̊; ) LATIN SMALL LETTER W WITH RING ABOVE
+1E99;1E99;0079 030A;1E99;0079 030A; # (ẙ; ẙ; y◌̊; ẙ; y◌̊; ) LATIN SMALL LETTER Y WITH RING ABOVE
+1E9A;1E9A;1E9A;0061 02BE;0061 02BE; # (ẚ; ẚ; ẚ; aʾ; aʾ; ) LATIN SMALL LETTER A WITH RIGHT HALF RING
+1E9B;1E9B;017F 0307;1E61;0073 0307; # (ẛ; ẛ; ſ◌̇; ṡ; s◌̇; ) LATIN SMALL LETTER LONG S WITH DOT ABOVE
+1EA0;1EA0;0041 0323;1EA0;0041 0323; # (Ạ; Ạ; A◌̣; Ạ; A◌̣; ) LATIN CAPITAL LETTER A WITH DOT BELOW
+1EA1;1EA1;0061 0323;1EA1;0061 0323; # (ạ; ạ; a◌̣; ạ; a◌̣; ) LATIN SMALL LETTER A WITH DOT BELOW
+1EA2;1EA2;0041 0309;1EA2;0041 0309; # (Ả; Ả; A◌̉; Ả; A◌̉; ) LATIN CAPITAL LETTER A WITH HOOK ABOVE
+1EA3;1EA3;0061 0309;1EA3;0061 0309; # (ả; ả; a◌̉; ả; a◌̉; ) LATIN SMALL LETTER A WITH HOOK ABOVE
+1EA4;1EA4;0041 0302 0301;1EA4;0041 0302 0301; # (Ấ; Ấ; A◌̂◌́; Ấ; A◌̂◌́; ) LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND ACUTE
+1EA5;1EA5;0061 0302 0301;1EA5;0061 0302 0301; # (ấ; ấ; a◌̂◌́; ấ; a◌̂◌́; ) LATIN SMALL LETTER A WITH CIRCUMFLEX AND ACUTE
+1EA6;1EA6;0041 0302 0300;1EA6;0041 0302 0300; # (Ầ; Ầ; A◌̂◌̀; Ầ; A◌̂◌̀; ) LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND GRAVE
+1EA7;1EA7;0061 0302 0300;1EA7;0061 0302 0300; # (ầ; ầ; a◌̂◌̀; ầ; a◌̂◌̀; ) LATIN SMALL LETTER A WITH CIRCUMFLEX AND GRAVE
+1EA8;1EA8;0041 0302 0309;1EA8;0041 0302 0309; # (Ẩ; Ẩ; A◌̂◌̉; Ẩ; A◌̂◌̉; ) LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE
+1EA9;1EA9;0061 0302 0309;1EA9;0061 0302 0309; # (ẩ; ẩ; a◌̂◌̉; ẩ; a◌̂◌̉; ) LATIN SMALL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE
+1EAA;1EAA;0041 0302 0303;1EAA;0041 0302 0303; # (Ẫ; Ẫ; A◌̂◌̃; Ẫ; A◌̂◌̃; ) LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND TILDE
+1EAB;1EAB;0061 0302 0303;1EAB;0061 0302 0303; # (ẫ; ẫ; a◌̂◌̃; ẫ; a◌̂◌̃; ) LATIN SMALL LETTER A WITH CIRCUMFLEX AND TILDE
+1EAC;1EAC;0041 0323 0302;1EAC;0041 0323 0302; # (Ậ; Ậ; A◌̣◌̂; Ậ; A◌̣◌̂; ) LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND DOT BELOW
+1EAD;1EAD;0061 0323 0302;1EAD;0061 0323 0302; # (ậ; ậ; a◌̣◌̂; ậ; a◌̣◌̂; ) LATIN SMALL LETTER A WITH CIRCUMFLEX AND DOT BELOW
+1EAE;1EAE;0041 0306 0301;1EAE;0041 0306 0301; # (Ắ; Ắ; A◌̆◌́; Ắ; A◌̆◌́; ) LATIN CAPITAL LETTER A WITH BREVE AND ACUTE
+1EAF;1EAF;0061 0306 0301;1EAF;0061 0306 0301; # (ắ; ắ; a◌̆◌́; ắ; a◌̆◌́; ) LATIN SMALL LETTER A WITH BREVE AND ACUTE
+1EB0;1EB0;0041 0306 0300;1EB0;0041 0306 0300; # (Ằ; Ằ; A◌̆◌̀; Ằ; A◌̆◌̀; ) LATIN CAPITAL LETTER A WITH BREVE AND GRAVE
+1EB1;1EB1;0061 0306 0300;1EB1;0061 0306 0300; # (ằ; ằ; a◌̆◌̀; ằ; a◌̆◌̀; ) LATIN SMALL LETTER A WITH BREVE AND GRAVE
+1EB2;1EB2;0041 0306 0309;1EB2;0041 0306 0309; # (Ẳ; Ẳ; A◌̆◌̉; Ẳ; A◌̆◌̉; ) LATIN CAPITAL LETTER A WITH BREVE AND HOOK ABOVE
+1EB3;1EB3;0061 0306 0309;1EB3;0061 0306 0309; # (ẳ; ẳ; a◌̆◌̉; ẳ; a◌̆◌̉; ) LATIN SMALL LETTER A WITH BREVE AND HOOK ABOVE
+1EB4;1EB4;0041 0306 0303;1EB4;0041 0306 0303; # (Ẵ; Ẵ; A◌̆◌̃; Ẵ; A◌̆◌̃; ) LATIN CAPITAL LETTER A WITH BREVE AND TILDE
+1EB5;1EB5;0061 0306 0303;1EB5;0061 0306 0303; # (ẵ; ẵ; a◌̆◌̃; ẵ; a◌̆◌̃; ) LATIN SMALL LETTER A WITH BREVE AND TILDE
+1EB6;1EB6;0041 0323 0306;1EB6;0041 0323 0306; # (Ặ; Ặ; A◌̣◌̆; Ặ; A◌̣◌̆; ) LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW
+1EB7;1EB7;0061 0323 0306;1EB7;0061 0323 0306; # (ặ; ặ; a◌̣◌̆; ặ; a◌̣◌̆; ) LATIN SMALL LETTER A WITH BREVE AND DOT BELOW
+1EB8;1EB8;0045 0323;1EB8;0045 0323; # (Ẹ; Ẹ; E◌̣; Ẹ; E◌̣; ) LATIN CAPITAL LETTER E WITH DOT BELOW
+1EB9;1EB9;0065 0323;1EB9;0065 0323; # (ẹ; ẹ; e◌̣; ẹ; e◌̣; ) LATIN SMALL LETTER E WITH DOT BELOW
+1EBA;1EBA;0045 0309;1EBA;0045 0309; # (Ẻ; Ẻ; E◌̉; Ẻ; E◌̉; ) LATIN CAPITAL LETTER E WITH HOOK ABOVE
+1EBB;1EBB;0065 0309;1EBB;0065 0309; # (ẻ; ẻ; e◌̉; ẻ; e◌̉; ) LATIN SMALL LETTER E WITH HOOK ABOVE
+1EBC;1EBC;0045 0303;1EBC;0045 0303; # (Ẽ; Ẽ; E◌̃; Ẽ; E◌̃; ) LATIN CAPITAL LETTER E WITH TILDE
+1EBD;1EBD;0065 0303;1EBD;0065 0303; # (ẽ; ẽ; e◌̃; ẽ; e◌̃; ) LATIN SMALL LETTER E WITH TILDE
+1EBE;1EBE;0045 0302 0301;1EBE;0045 0302 0301; # (Ế; Ế; E◌̂◌́; Ế; E◌̂◌́; ) LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND ACUTE
+1EBF;1EBF;0065 0302 0301;1EBF;0065 0302 0301; # (ế; ế; e◌̂◌́; ế; e◌̂◌́; ) LATIN SMALL LETTER E WITH CIRCUMFLEX AND ACUTE
+1EC0;1EC0;0045 0302 0300;1EC0;0045 0302 0300; # (Ề; Ề; E◌̂◌̀; Ề; E◌̂◌̀; ) LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND GRAVE
+1EC1;1EC1;0065 0302 0300;1EC1;0065 0302 0300; # (ề; ề; e◌̂◌̀; ề; e◌̂◌̀; ) LATIN SMALL LETTER E WITH CIRCUMFLEX AND GRAVE
+1EC2;1EC2;0045 0302 0309;1EC2;0045 0302 0309; # (Ể; Ể; E◌̂◌̉; Ể; E◌̂◌̉; ) LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE
+1EC3;1EC3;0065 0302 0309;1EC3;0065 0302 0309; # (ể; ể; e◌̂◌̉; ể; e◌̂◌̉; ) LATIN SMALL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE
+1EC4;1EC4;0045 0302 0303;1EC4;0045 0302 0303; # (Ễ; Ễ; E◌̂◌̃; Ễ; E◌̂◌̃; ) LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND TILDE
+1EC5;1EC5;0065 0302 0303;1EC5;0065 0302 0303; # (ễ; ễ; e◌̂◌̃; ễ; e◌̂◌̃; ) LATIN SMALL LETTER E WITH CIRCUMFLEX AND TILDE
+1EC6;1EC6;0045 0323 0302;1EC6;0045 0323 0302; # (Ệ; Ệ; E◌̣◌̂; Ệ; E◌̣◌̂; ) LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND DOT BELOW
+1EC7;1EC7;0065 0323 0302;1EC7;0065 0323 0302; # (ệ; ệ; e◌̣◌̂; ệ; e◌̣◌̂; ) LATIN SMALL LETTER E WITH CIRCUMFLEX AND DOT BELOW
+1EC8;1EC8;0049 0309;1EC8;0049 0309; # (Ỉ; Ỉ; I◌̉; Ỉ; I◌̉; ) LATIN CAPITAL LETTER I WITH HOOK ABOVE
+1EC9;1EC9;0069 0309;1EC9;0069 0309; # (ỉ; ỉ; i◌̉; ỉ; i◌̉; ) LATIN SMALL LETTER I WITH HOOK ABOVE
+1ECA;1ECA;0049 0323;1ECA;0049 0323; # (Ị; Ị; I◌̣; Ị; I◌̣; ) LATIN CAPITAL LETTER I WITH DOT BELOW
+1ECB;1ECB;0069 0323;1ECB;0069 0323; # (ị; ị; i◌̣; ị; i◌̣; ) LATIN SMALL LETTER I WITH DOT BELOW
+1ECC;1ECC;004F 0323;1ECC;004F 0323; # (Ọ; Ọ; O◌̣; Ọ; O◌̣; ) LATIN CAPITAL LETTER O WITH DOT BELOW
+1ECD;1ECD;006F 0323;1ECD;006F 0323; # (ọ; ọ; o◌̣; ọ; o◌̣; ) LATIN SMALL LETTER O WITH DOT BELOW
+1ECE;1ECE;004F 0309;1ECE;004F 0309; # (Ỏ; Ỏ; O◌̉; Ỏ; O◌̉; ) LATIN CAPITAL LETTER O WITH HOOK ABOVE
+1ECF;1ECF;006F 0309;1ECF;006F 0309; # (ỏ; ỏ; o◌̉; ỏ; o◌̉; ) LATIN SMALL LETTER O WITH HOOK ABOVE
+1ED0;1ED0;004F 0302 0301;1ED0;004F 0302 0301; # (Ố; Ố; O◌̂◌́; Ố; O◌̂◌́; ) LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND ACUTE
+1ED1;1ED1;006F 0302 0301;1ED1;006F 0302 0301; # (ố; ố; o◌̂◌́; ố; o◌̂◌́; ) LATIN SMALL LETTER O WITH CIRCUMFLEX AND ACUTE
+1ED2;1ED2;004F 0302 0300;1ED2;004F 0302 0300; # (Ồ; Ồ; O◌̂◌̀; Ồ; O◌̂◌̀; ) LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND GRAVE
+1ED3;1ED3;006F 0302 0300;1ED3;006F 0302 0300; # (ồ; ồ; o◌̂◌̀; ồ; o◌̂◌̀; ) LATIN SMALL LETTER O WITH CIRCUMFLEX AND GRAVE
+1ED4;1ED4;004F 0302 0309;1ED4;004F 0302 0309; # (Ổ; Ổ; O◌̂◌̉; Ổ; O◌̂◌̉; ) LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE
+1ED5;1ED5;006F 0302 0309;1ED5;006F 0302 0309; # (ổ; ổ; o◌̂◌̉; ổ; o◌̂◌̉; ) LATIN SMALL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE
+1ED6;1ED6;004F 0302 0303;1ED6;004F 0302 0303; # (Ỗ; Ỗ; O◌̂◌̃; Ỗ; O◌̂◌̃; ) LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND TILDE
+1ED7;1ED7;006F 0302 0303;1ED7;006F 0302 0303; # (ỗ; ỗ; o◌̂◌̃; ỗ; o◌̂◌̃; ) LATIN SMALL LETTER O WITH CIRCUMFLEX AND TILDE
+1ED8;1ED8;004F 0323 0302;1ED8;004F 0323 0302; # (Ộ; Ộ; O◌̣◌̂; Ộ; O◌̣◌̂; ) LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND DOT BELOW
+1ED9;1ED9;006F 0323 0302;1ED9;006F 0323 0302; # (ộ; ộ; o◌̣◌̂; ộ; o◌̣◌̂; ) LATIN SMALL LETTER O WITH CIRCUMFLEX AND DOT BELOW
+1EDA;1EDA;004F 031B 0301;1EDA;004F 031B 0301; # (Ớ; Ớ; O◌̛◌́; Ớ; O◌̛◌́; ) LATIN CAPITAL LETTER O WITH HORN AND ACUTE
+1EDB;1EDB;006F 031B 0301;1EDB;006F 031B 0301; # (ớ; ớ; o◌̛◌́; ớ; o◌̛◌́; ) LATIN SMALL LETTER O WITH HORN AND ACUTE
+1EDC;1EDC;004F 031B 0300;1EDC;004F 031B 0300; # (Ờ; Ờ; O◌̛◌̀; Ờ; O◌̛◌̀; ) LATIN CAPITAL LETTER O WITH HORN AND GRAVE
+1EDD;1EDD;006F 031B 0300;1EDD;006F 031B 0300; # (ờ; ờ; o◌̛◌̀; ờ; o◌̛◌̀; ) LATIN SMALL LETTER O WITH HORN AND GRAVE
+1EDE;1EDE;004F 031B 0309;1EDE;004F 031B 0309; # (Ở; Ở; O◌̛◌̉; Ở; O◌̛◌̉; ) LATIN CAPITAL LETTER O WITH HORN AND HOOK ABOVE
+1EDF;1EDF;006F 031B 0309;1EDF;006F 031B 0309; # (ở; ở; o◌̛◌̉; ở; o◌̛◌̉; ) LATIN SMALL LETTER O WITH HORN AND HOOK ABOVE
+1EE0;1EE0;004F 031B 0303;1EE0;004F 031B 0303; # (Ỡ; Ỡ; O◌̛◌̃; Ỡ; O◌̛◌̃; ) LATIN CAPITAL LETTER O WITH HORN AND TILDE
+1EE1;1EE1;006F 031B 0303;1EE1;006F 031B 0303; # (ỡ; ỡ; o◌̛◌̃; ỡ; o◌̛◌̃; ) LATIN SMALL LETTER O WITH HORN AND TILDE
+1EE2;1EE2;004F 031B 0323;1EE2;004F 031B 0323; # (Ợ; Ợ; O◌̛◌̣; Ợ; O◌̛◌̣; ) LATIN CAPITAL LETTER O WITH HORN AND DOT BELOW
+1EE3;1EE3;006F 031B 0323;1EE3;006F 031B 0323; # (ợ; ợ; o◌̛◌̣; ợ; o◌̛◌̣; ) LATIN SMALL LETTER O WITH HORN AND DOT BELOW
+1EE4;1EE4;0055 0323;1EE4;0055 0323; # (Ụ; Ụ; U◌̣; Ụ; U◌̣; ) LATIN CAPITAL LETTER U WITH DOT BELOW
+1EE5;1EE5;0075 0323;1EE5;0075 0323; # (ụ; ụ; u◌̣; ụ; u◌̣; ) LATIN SMALL LETTER U WITH DOT BELOW
+1EE6;1EE6;0055 0309;1EE6;0055 0309; # (Ủ; Ủ; U◌̉; Ủ; U◌̉; ) LATIN CAPITAL LETTER U WITH HOOK ABOVE
+1EE7;1EE7;0075 0309;1EE7;0075 0309; # (ủ; ủ; u◌̉; ủ; u◌̉; ) LATIN SMALL LETTER U WITH HOOK ABOVE
+1EE8;1EE8;0055 031B 0301;1EE8;0055 031B 0301; # (Ứ; Ứ; U◌̛◌́; Ứ; U◌̛◌́; ) LATIN CAPITAL LETTER U WITH HORN AND ACUTE
+1EE9;1EE9;0075 031B 0301;1EE9;0075 031B 0301; # (ứ; ứ; u◌̛◌́; ứ; u◌̛◌́; ) LATIN SMALL LETTER U WITH HORN AND ACUTE
+1EEA;1EEA;0055 031B 0300;1EEA;0055 031B 0300; # (Ừ; Ừ; U◌̛◌̀; Ừ; U◌̛◌̀; ) LATIN CAPITAL LETTER U WITH HORN AND GRAVE
+1EEB;1EEB;0075 031B 0300;1EEB;0075 031B 0300; # (ừ; ừ; u◌̛◌̀; ừ; u◌̛◌̀; ) LATIN SMALL LETTER U WITH HORN AND GRAVE
+1EEC;1EEC;0055 031B 0309;1EEC;0055 031B 0309; # (Ử; Ử; U◌̛◌̉; Ử; U◌̛◌̉; ) LATIN CAPITAL LETTER U WITH HORN AND HOOK ABOVE
+1EED;1EED;0075 031B 0309;1EED;0075 031B 0309; # (ử; ử; u◌̛◌̉; ử; u◌̛◌̉; ) LATIN SMALL LETTER U WITH HORN AND HOOK ABOVE
+1EEE;1EEE;0055 031B 0303;1EEE;0055 031B 0303; # (Ữ; Ữ; U◌̛◌̃; Ữ; U◌̛◌̃; ) LATIN CAPITAL LETTER U WITH HORN AND TILDE
+1EEF;1EEF;0075 031B 0303;1EEF;0075 031B 0303; # (ữ; ữ; u◌̛◌̃; ữ; u◌̛◌̃; ) LATIN SMALL LETTER U WITH HORN AND TILDE
+1EF0;1EF0;0055 031B 0323;1EF0;0055 031B 0323; # (Ự; Ự; U◌̛◌̣; Ự; U◌̛◌̣; ) LATIN CAPITAL LETTER U WITH HORN AND DOT BELOW
+1EF1;1EF1;0075 031B 0323;1EF1;0075 031B 0323; # (ự; ự; u◌̛◌̣; ự; u◌̛◌̣; ) LATIN SMALL LETTER U WITH HORN AND DOT BELOW
+1EF2;1EF2;0059 0300;1EF2;0059 0300; # (Ỳ; Ỳ; Y◌̀; Ỳ; Y◌̀; ) LATIN CAPITAL LETTER Y WITH GRAVE
+1EF3;1EF3;0079 0300;1EF3;0079 0300; # (ỳ; ỳ; y◌̀; ỳ; y◌̀; ) LATIN SMALL LETTER Y WITH GRAVE
+1EF4;1EF4;0059 0323;1EF4;0059 0323; # (Ỵ; Ỵ; Y◌̣; Ỵ; Y◌̣; ) LATIN CAPITAL LETTER Y WITH DOT BELOW
+1EF5;1EF5;0079 0323;1EF5;0079 0323; # (ỵ; ỵ; y◌̣; ỵ; y◌̣; ) LATIN SMALL LETTER Y WITH DOT BELOW
+1EF6;1EF6;0059 0309;1EF6;0059 0309; # (Ỷ; Ỷ; Y◌̉; Ỷ; Y◌̉; ) LATIN CAPITAL LETTER Y WITH HOOK ABOVE
+1EF7;1EF7;0079 0309;1EF7;0079 0309; # (ỷ; ỷ; y◌̉; ỷ; y◌̉; ) LATIN SMALL LETTER Y WITH HOOK ABOVE
+1EF8;1EF8;0059 0303;1EF8;0059 0303; # (Ỹ; Ỹ; Y◌̃; Ỹ; Y◌̃; ) LATIN CAPITAL LETTER Y WITH TILDE
+1EF9;1EF9;0079 0303;1EF9;0079 0303; # (ỹ; ỹ; y◌̃; ỹ; y◌̃; ) LATIN SMALL LETTER Y WITH TILDE
+1F00;1F00;03B1 0313;1F00;03B1 0313; # (ἀ; ἀ; α◌̓; ἀ; α◌̓; ) GREEK SMALL LETTER ALPHA WITH PSILI
+1F01;1F01;03B1 0314;1F01;03B1 0314; # (ἁ; ἁ; α◌̔; ἁ; α◌̔; ) GREEK SMALL LETTER ALPHA WITH DASIA
+1F02;1F02;03B1 0313 0300;1F02;03B1 0313 0300; # (ἂ; ἂ; α◌̓◌̀; ἂ; α◌̓◌̀; ) GREEK SMALL LETTER ALPHA WITH PSILI AND VARIA
+1F03;1F03;03B1 0314 0300;1F03;03B1 0314 0300; # (ἃ; ἃ; α◌̔◌̀; ἃ; α◌̔◌̀; ) GREEK SMALL LETTER ALPHA WITH DASIA AND VARIA
+1F04;1F04;03B1 0313 0301;1F04;03B1 0313 0301; # (ἄ; ἄ; α◌̓◌́; ἄ; α◌̓◌́; ) GREEK SMALL LETTER ALPHA WITH PSILI AND OXIA
+1F05;1F05;03B1 0314 0301;1F05;03B1 0314 0301; # (ἅ; ἅ; α◌̔◌́; ἅ; α◌̔◌́; ) GREEK SMALL LETTER ALPHA WITH DASIA AND OXIA
+1F06;1F06;03B1 0313 0342;1F06;03B1 0313 0342; # (ἆ; ἆ; α◌̓◌͂; ἆ; α◌̓◌͂; ) GREEK SMALL LETTER ALPHA WITH PSILI AND PERISPOMENI
+1F07;1F07;03B1 0314 0342;1F07;03B1 0314 0342; # (ἇ; ἇ; α◌̔◌͂; ἇ; α◌̔◌͂; ) GREEK SMALL LETTER ALPHA WITH DASIA AND PERISPOMENI
+1F08;1F08;0391 0313;1F08;0391 0313; # (Ἀ; Ἀ; Α◌̓; Ἀ; Α◌̓; ) GREEK CAPITAL LETTER ALPHA WITH PSILI
+1F09;1F09;0391 0314;1F09;0391 0314; # (Ἁ; Ἁ; Α◌̔; Ἁ; Α◌̔; ) GREEK CAPITAL LETTER ALPHA WITH DASIA
+1F0A;1F0A;0391 0313 0300;1F0A;0391 0313 0300; # (Ἂ; Ἂ; Α◌̓◌̀; Ἂ; Α◌̓◌̀; ) GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA
+1F0B;1F0B;0391 0314 0300;1F0B;0391 0314 0300; # (Ἃ; Ἃ; Α◌̔◌̀; Ἃ; Α◌̔◌̀; ) GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA
+1F0C;1F0C;0391 0313 0301;1F0C;0391 0313 0301; # (Ἄ; Ἄ; Α◌̓◌́; Ἄ; Α◌̓◌́; ) GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA
+1F0D;1F0D;0391 0314 0301;1F0D;0391 0314 0301; # (Ἅ; Ἅ; Α◌̔◌́; Ἅ; Α◌̔◌́; ) GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA
+1F0E;1F0E;0391 0313 0342;1F0E;0391 0313 0342; # (Ἆ; Ἆ; Α◌̓◌͂; Ἆ; Α◌̓◌͂; ) GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI
+1F0F;1F0F;0391 0314 0342;1F0F;0391 0314 0342; # (Ἇ; Ἇ; Α◌̔◌͂; Ἇ; Α◌̔◌͂; ) GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI
+1F10;1F10;03B5 0313;1F10;03B5 0313; # (ἐ; ἐ; ε◌̓; ἐ; ε◌̓; ) GREEK SMALL LETTER EPSILON WITH PSILI
+1F11;1F11;03B5 0314;1F11;03B5 0314; # (ἑ; ἑ; ε◌̔; ἑ; ε◌̔; ) GREEK SMALL LETTER EPSILON WITH DASIA
+1F12;1F12;03B5 0313 0300;1F12;03B5 0313 0300; # (ἒ; ἒ; ε◌̓◌̀; ἒ; ε◌̓◌̀; ) GREEK SMALL LETTER EPSILON WITH PSILI AND VARIA
+1F13;1F13;03B5 0314 0300;1F13;03B5 0314 0300; # (ἓ; ἓ; ε◌̔◌̀; ἓ; ε◌̔◌̀; ) GREEK SMALL LETTER EPSILON WITH DASIA AND VARIA
+1F14;1F14;03B5 0313 0301;1F14;03B5 0313 0301; # (ἔ; ἔ; ε◌̓◌́; ἔ; ε◌̓◌́; ) GREEK SMALL LETTER EPSILON WITH PSILI AND OXIA
+1F15;1F15;03B5 0314 0301;1F15;03B5 0314 0301; # (ἕ; ἕ; ε◌̔◌́; ἕ; ε◌̔◌́; ) GREEK SMALL LETTER EPSILON WITH DASIA AND OXIA
+1F18;1F18;0395 0313;1F18;0395 0313; # (Ἐ; Ἐ; Ε◌̓; Ἐ; Ε◌̓; ) GREEK CAPITAL LETTER EPSILON WITH PSILI
+1F19;1F19;0395 0314;1F19;0395 0314; # (Ἑ; Ἑ; Ε◌̔; Ἑ; Ε◌̔; ) GREEK CAPITAL LETTER EPSILON WITH DASIA
+1F1A;1F1A;0395 0313 0300;1F1A;0395 0313 0300; # (Ἒ; Ἒ; Ε◌̓◌̀; Ἒ; Ε◌̓◌̀; ) GREEK CAPITAL LETTER EPSILON WITH PSILI AND VARIA
+1F1B;1F1B;0395 0314 0300;1F1B;0395 0314 0300; # (Ἓ; Ἓ; Ε◌̔◌̀; Ἓ; Ε◌̔◌̀; ) GREEK CAPITAL LETTER EPSILON WITH DASIA AND VARIA
+1F1C;1F1C;0395 0313 0301;1F1C;0395 0313 0301; # (Ἔ; Ἔ; Ε◌̓◌́; Ἔ; Ε◌̓◌́; ) GREEK CAPITAL LETTER EPSILON WITH PSILI AND OXIA
+1F1D;1F1D;0395 0314 0301;1F1D;0395 0314 0301; # (Ἕ; Ἕ; Ε◌̔◌́; Ἕ; Ε◌̔◌́; ) GREEK CAPITAL LETTER EPSILON WITH DASIA AND OXIA
+1F20;1F20;03B7 0313;1F20;03B7 0313; # (ἠ; ἠ; η◌̓; ἠ; η◌̓; ) GREEK SMALL LETTER ETA WITH PSILI
+1F21;1F21;03B7 0314;1F21;03B7 0314; # (ἡ; ἡ; η◌̔; ἡ; η◌̔; ) GREEK SMALL LETTER ETA WITH DASIA
+1F22;1F22;03B7 0313 0300;1F22;03B7 0313 0300; # (ἢ; ἢ; η◌̓◌̀; ἢ; η◌̓◌̀; ) GREEK SMALL LETTER ETA WITH PSILI AND VARIA
+1F23;1F23;03B7 0314 0300;1F23;03B7 0314 0300; # (ἣ; ἣ; η◌̔◌̀; ἣ; η◌̔◌̀; ) GREEK SMALL LETTER ETA WITH DASIA AND VARIA
+1F24;1F24;03B7 0313 0301;1F24;03B7 0313 0301; # (ἤ; ἤ; η◌̓◌́; ἤ; η◌̓◌́; ) GREEK SMALL LETTER ETA WITH PSILI AND OXIA
+1F25;1F25;03B7 0314 0301;1F25;03B7 0314 0301; # (ἥ; ἥ; η◌̔◌́; ἥ; η◌̔◌́; ) GREEK SMALL LETTER ETA WITH DASIA AND OXIA
+1F26;1F26;03B7 0313 0342;1F26;03B7 0313 0342; # (ἦ; ἦ; η◌̓◌͂; ἦ; η◌̓◌͂; ) GREEK SMALL LETTER ETA WITH PSILI AND PERISPOMENI
+1F27;1F27;03B7 0314 0342;1F27;03B7 0314 0342; # (ἧ; ἧ; η◌̔◌͂; ἧ; η◌̔◌͂; ) GREEK SMALL LETTER ETA WITH DASIA AND PERISPOMENI
+1F28;1F28;0397 0313;1F28;0397 0313; # (Ἠ; Ἠ; Η◌̓; Ἠ; Η◌̓; ) GREEK CAPITAL LETTER ETA WITH PSILI
+1F29;1F29;0397 0314;1F29;0397 0314; # (Ἡ; Ἡ; Η◌̔; Ἡ; Η◌̔; ) GREEK CAPITAL LETTER ETA WITH DASIA
+1F2A;1F2A;0397 0313 0300;1F2A;0397 0313 0300; # (Ἢ; Ἢ; Η◌̓◌̀; Ἢ; Η◌̓◌̀; ) GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA
+1F2B;1F2B;0397 0314 0300;1F2B;0397 0314 0300; # (Ἣ; Ἣ; Η◌̔◌̀; Ἣ; Η◌̔◌̀; ) GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA
+1F2C;1F2C;0397 0313 0301;1F2C;0397 0313 0301; # (Ἤ; Ἤ; Η◌̓◌́; Ἤ; Η◌̓◌́; ) GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA
+1F2D;1F2D;0397 0314 0301;1F2D;0397 0314 0301; # (Ἥ; Ἥ; Η◌̔◌́; Ἥ; Η◌̔◌́; ) GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA
+1F2E;1F2E;0397 0313 0342;1F2E;0397 0313 0342; # (Ἦ; Ἦ; Η◌̓◌͂; Ἦ; Η◌̓◌͂; ) GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI
+1F2F;1F2F;0397 0314 0342;1F2F;0397 0314 0342; # (Ἧ; Ἧ; Η◌̔◌͂; Ἧ; Η◌̔◌͂; ) GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI
+1F30;1F30;03B9 0313;1F30;03B9 0313; # (ἰ; ἰ; ι◌̓; ἰ; ι◌̓; ) GREEK SMALL LETTER IOTA WITH PSILI
+1F31;1F31;03B9 0314;1F31;03B9 0314; # (ἱ; ἱ; ι◌̔; ἱ; ι◌̔; ) GREEK SMALL LETTER IOTA WITH DASIA
+1F32;1F32;03B9 0313 0300;1F32;03B9 0313 0300; # (ἲ; ἲ; ι◌̓◌̀; ἲ; ι◌̓◌̀; ) GREEK SMALL LETTER IOTA WITH PSILI AND VARIA
+1F33;1F33;03B9 0314 0300;1F33;03B9 0314 0300; # (ἳ; ἳ; ι◌̔◌̀; ἳ; ι◌̔◌̀; ) GREEK SMALL LETTER IOTA WITH DASIA AND VARIA
+1F34;1F34;03B9 0313 0301;1F34;03B9 0313 0301; # (ἴ; ἴ; ι◌̓◌́; ἴ; ι◌̓◌́; ) GREEK SMALL LETTER IOTA WITH PSILI AND OXIA
+1F35;1F35;03B9 0314 0301;1F35;03B9 0314 0301; # (ἵ; ἵ; ι◌̔◌́; ἵ; ι◌̔◌́; ) GREEK SMALL LETTER IOTA WITH DASIA AND OXIA
+1F36;1F36;03B9 0313 0342;1F36;03B9 0313 0342; # (ἶ; ἶ; ι◌̓◌͂; ἶ; ι◌̓◌͂; ) GREEK SMALL LETTER IOTA WITH PSILI AND PERISPOMENI
+1F37;1F37;03B9 0314 0342;1F37;03B9 0314 0342; # (ἷ; ἷ; ι◌̔◌͂; ἷ; ι◌̔◌͂; ) GREEK SMALL LETTER IOTA WITH DASIA AND PERISPOMENI
+1F38;1F38;0399 0313;1F38;0399 0313; # (Ἰ; Ἰ; Ι◌̓; Ἰ; Ι◌̓; ) GREEK CAPITAL LETTER IOTA WITH PSILI
+1F39;1F39;0399 0314;1F39;0399 0314; # (Ἱ; Ἱ; Ι◌̔; Ἱ; Ι◌̔; ) GREEK CAPITAL LETTER IOTA WITH DASIA
+1F3A;1F3A;0399 0313 0300;1F3A;0399 0313 0300; # (Ἲ; Ἲ; Ι◌̓◌̀; Ἲ; Ι◌̓◌̀; ) GREEK CAPITAL LETTER IOTA WITH PSILI AND VARIA
+1F3B;1F3B;0399 0314 0300;1F3B;0399 0314 0300; # (Ἳ; Ἳ; Ι◌̔◌̀; Ἳ; Ι◌̔◌̀; ) GREEK CAPITAL LETTER IOTA WITH DASIA AND VARIA
+1F3C;1F3C;0399 0313 0301;1F3C;0399 0313 0301; # (Ἴ; Ἴ; Ι◌̓◌́; Ἴ; Ι◌̓◌́; ) GREEK CAPITAL LETTER IOTA WITH PSILI AND OXIA
+1F3D;1F3D;0399 0314 0301;1F3D;0399 0314 0301; # (Ἵ; Ἵ; Ι◌̔◌́; Ἵ; Ι◌̔◌́; ) GREEK CAPITAL LETTER IOTA WITH DASIA AND OXIA
+1F3E;1F3E;0399 0313 0342;1F3E;0399 0313 0342; # (Ἶ; Ἶ; Ι◌̓◌͂; Ἶ; Ι◌̓◌͂; ) GREEK CAPITAL LETTER IOTA WITH PSILI AND PERISPOMENI
+1F3F;1F3F;0399 0314 0342;1F3F;0399 0314 0342; # (Ἷ; Ἷ; Ι◌̔◌͂; Ἷ; Ι◌̔◌͂; ) GREEK CAPITAL LETTER IOTA WITH DASIA AND PERISPOMENI
+1F40;1F40;03BF 0313;1F40;03BF 0313; # (ὀ; ὀ; ο◌̓; ὀ; ο◌̓; ) GREEK SMALL LETTER OMICRON WITH PSILI
+1F41;1F41;03BF 0314;1F41;03BF 0314; # (ὁ; ὁ; ο◌̔; ὁ; ο◌̔; ) GREEK SMALL LETTER OMICRON WITH DASIA
+1F42;1F42;03BF 0313 0300;1F42;03BF 0313 0300; # (ὂ; ὂ; ο◌̓◌̀; ὂ; ο◌̓◌̀; ) GREEK SMALL LETTER OMICRON WITH PSILI AND VARIA
+1F43;1F43;03BF 0314 0300;1F43;03BF 0314 0300; # (ὃ; ὃ; ο◌̔◌̀; ὃ; ο◌̔◌̀; ) GREEK SMALL LETTER OMICRON WITH DASIA AND VARIA
+1F44;1F44;03BF 0313 0301;1F44;03BF 0313 0301; # (ὄ; ὄ; ο◌̓◌́; ὄ; ο◌̓◌́; ) GREEK SMALL LETTER OMICRON WITH PSILI AND OXIA
+1F45;1F45;03BF 0314 0301;1F45;03BF 0314 0301; # (ὅ; ὅ; ο◌̔◌́; ὅ; ο◌̔◌́; ) GREEK SMALL LETTER OMICRON WITH DASIA AND OXIA
+1F48;1F48;039F 0313;1F48;039F 0313; # (Ὀ; Ὀ; Ο◌̓; Ὀ; Ο◌̓; ) GREEK CAPITAL LETTER OMICRON WITH PSILI
+1F49;1F49;039F 0314;1F49;039F 0314; # (Ὁ; Ὁ; Ο◌̔; Ὁ; Ο◌̔; ) GREEK CAPITAL LETTER OMICRON WITH DASIA
+1F4A;1F4A;039F 0313 0300;1F4A;039F 0313 0300; # (Ὂ; Ὂ; Ο◌̓◌̀; Ὂ; Ο◌̓◌̀; ) GREEK CAPITAL LETTER OMICRON WITH PSILI AND VARIA
+1F4B;1F4B;039F 0314 0300;1F4B;039F 0314 0300; # (Ὃ; Ὃ; Ο◌̔◌̀; Ὃ; Ο◌̔◌̀; ) GREEK CAPITAL LETTER OMICRON WITH DASIA AND VARIA
+1F4C;1F4C;039F 0313 0301;1F4C;039F 0313 0301; # (Ὄ; Ὄ; Ο◌̓◌́; Ὄ; Ο◌̓◌́; ) GREEK CAPITAL LETTER OMICRON WITH PSILI AND OXIA
+1F4D;1F4D;039F 0314 0301;1F4D;039F 0314 0301; # (Ὅ; Ὅ; Ο◌̔◌́; Ὅ; Ο◌̔◌́; ) GREEK CAPITAL LETTER OMICRON WITH DASIA AND OXIA
+1F50;1F50;03C5 0313;1F50;03C5 0313; # (ὐ; ὐ; υ◌̓; ὐ; υ◌̓; ) GREEK SMALL LETTER UPSILON WITH PSILI
+1F51;1F51;03C5 0314;1F51;03C5 0314; # (ὑ; ὑ; υ◌̔; ὑ; υ◌̔; ) GREEK SMALL LETTER UPSILON WITH DASIA
+1F52;1F52;03C5 0313 0300;1F52;03C5 0313 0300; # (ὒ; ὒ; υ◌̓◌̀; ὒ; υ◌̓◌̀; ) GREEK SMALL LETTER UPSILON WITH PSILI AND VARIA
+1F53;1F53;03C5 0314 0300;1F53;03C5 0314 0300; # (ὓ; ὓ; υ◌̔◌̀; ὓ; υ◌̔◌̀; ) GREEK SMALL LETTER UPSILON WITH DASIA AND VARIA
+1F54;1F54;03C5 0313 0301;1F54;03C5 0313 0301; # (ὔ; ὔ; υ◌̓◌́; ὔ; υ◌̓◌́; ) GREEK SMALL LETTER UPSILON WITH PSILI AND OXIA
+1F55;1F55;03C5 0314 0301;1F55;03C5 0314 0301; # (ὕ; ὕ; υ◌̔◌́; ὕ; υ◌̔◌́; ) GREEK SMALL LETTER UPSILON WITH DASIA AND OXIA
+1F56;1F56;03C5 0313 0342;1F56;03C5 0313 0342; # (ὖ; ὖ; υ◌̓◌͂; ὖ; υ◌̓◌͂; ) GREEK SMALL LETTER UPSILON WITH PSILI AND PERISPOMENI
+1F57;1F57;03C5 0314 0342;1F57;03C5 0314 0342; # (ὗ; ὗ; υ◌̔◌͂; ὗ; υ◌̔◌͂; ) GREEK SMALL LETTER UPSILON WITH DASIA AND PERISPOMENI
+1F59;1F59;03A5 0314;1F59;03A5 0314; # (Ὑ; Ὑ; Υ◌̔; Ὑ; Υ◌̔; ) GREEK CAPITAL LETTER UPSILON WITH DASIA
+1F5B;1F5B;03A5 0314 0300;1F5B;03A5 0314 0300; # (Ὓ; Ὓ; Υ◌̔◌̀; Ὓ; Υ◌̔◌̀; ) GREEK CAPITAL LETTER UPSILON WITH DASIA AND VARIA
+1F5D;1F5D;03A5 0314 0301;1F5D;03A5 0314 0301; # (Ὕ; Ὕ; Υ◌̔◌́; Ὕ; Υ◌̔◌́; ) GREEK CAPITAL LETTER UPSILON WITH DASIA AND OXIA
+1F5F;1F5F;03A5 0314 0342;1F5F;03A5 0314 0342; # (Ὗ; Ὗ; Υ◌̔◌͂; Ὗ; Υ◌̔◌͂; ) GREEK CAPITAL LETTER UPSILON WITH DASIA AND PERISPOMENI
+1F60;1F60;03C9 0313;1F60;03C9 0313; # (ὠ; ὠ; ω◌̓; ὠ; ω◌̓; ) GREEK SMALL LETTER OMEGA WITH PSILI
+1F61;1F61;03C9 0314;1F61;03C9 0314; # (ὡ; ὡ; ω◌̔; ὡ; ω◌̔; ) GREEK SMALL LETTER OMEGA WITH DASIA
+1F62;1F62;03C9 0313 0300;1F62;03C9 0313 0300; # (ὢ; ὢ; ω◌̓◌̀; ὢ; ω◌̓◌̀; ) GREEK SMALL LETTER OMEGA WITH PSILI AND VARIA
+1F63;1F63;03C9 0314 0300;1F63;03C9 0314 0300; # (ὣ; ὣ; ω◌̔◌̀; ὣ; ω◌̔◌̀; ) GREEK SMALL LETTER OMEGA WITH DASIA AND VARIA
+1F64;1F64;03C9 0313 0301;1F64;03C9 0313 0301; # (ὤ; ὤ; ω◌̓◌́; ὤ; ω◌̓◌́; ) GREEK SMALL LETTER OMEGA WITH PSILI AND OXIA
+1F65;1F65;03C9 0314 0301;1F65;03C9 0314 0301; # (ὥ; ὥ; ω◌̔◌́; ὥ; ω◌̔◌́; ) GREEK SMALL LETTER OMEGA WITH DASIA AND OXIA
+1F66;1F66;03C9 0313 0342;1F66;03C9 0313 0342; # (ὦ; ὦ; ω◌̓◌͂; ὦ; ω◌̓◌͂; ) GREEK SMALL LETTER OMEGA WITH PSILI AND PERISPOMENI
+1F67;1F67;03C9 0314 0342;1F67;03C9 0314 0342; # (ὧ; ὧ; ω◌̔◌͂; ὧ; ω◌̔◌͂; ) GREEK SMALL LETTER OMEGA WITH DASIA AND PERISPOMENI
+1F68;1F68;03A9 0313;1F68;03A9 0313; # (Ὠ; Ὠ; Ω◌̓; Ὠ; Ω◌̓; ) GREEK CAPITAL LETTER OMEGA WITH PSILI
+1F69;1F69;03A9 0314;1F69;03A9 0314; # (Ὡ; Ὡ; Ω◌̔; Ὡ; Ω◌̔; ) GREEK CAPITAL LETTER OMEGA WITH DASIA
+1F6A;1F6A;03A9 0313 0300;1F6A;03A9 0313 0300; # (Ὢ; Ὢ; Ω◌̓◌̀; Ὢ; Ω◌̓◌̀; ) GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA
+1F6B;1F6B;03A9 0314 0300;1F6B;03A9 0314 0300; # (Ὣ; Ὣ; Ω◌̔◌̀; Ὣ; Ω◌̔◌̀; ) GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA
+1F6C;1F6C;03A9 0313 0301;1F6C;03A9 0313 0301; # (Ὤ; Ὤ; Ω◌̓◌́; Ὤ; Ω◌̓◌́; ) GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA
+1F6D;1F6D;03A9 0314 0301;1F6D;03A9 0314 0301; # (Ὥ; Ὥ; Ω◌̔◌́; Ὥ; Ω◌̔◌́; ) GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA
+1F6E;1F6E;03A9 0313 0342;1F6E;03A9 0313 0342; # (Ὦ; Ὦ; Ω◌̓◌͂; Ὦ; Ω◌̓◌͂; ) GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI
+1F6F;1F6F;03A9 0314 0342;1F6F;03A9 0314 0342; # (Ὧ; Ὧ; Ω◌̔◌͂; Ὧ; Ω◌̔◌͂; ) GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI
+1F70;1F70;03B1 0300;1F70;03B1 0300; # (ὰ; ὰ; α◌̀; ὰ; α◌̀; ) GREEK SMALL LETTER ALPHA WITH VARIA
+1F71;03AC;03B1 0301;03AC;03B1 0301; # (ά; ά; α◌́; ά; α◌́; ) GREEK SMALL LETTER ALPHA WITH OXIA
+1F72;1F72;03B5 0300;1F72;03B5 0300; # (ὲ; ὲ; ε◌̀; ὲ; ε◌̀; ) GREEK SMALL LETTER EPSILON WITH VARIA
+1F73;03AD;03B5 0301;03AD;03B5 0301; # (έ; έ; ε◌́; έ; ε◌́; ) GREEK SMALL LETTER EPSILON WITH OXIA
+1F74;1F74;03B7 0300;1F74;03B7 0300; # (ὴ; ὴ; η◌̀; ὴ; η◌̀; ) GREEK SMALL LETTER ETA WITH VARIA
+1F75;03AE;03B7 0301;03AE;03B7 0301; # (ή; ή; η◌́; ή; η◌́; ) GREEK SMALL LETTER ETA WITH OXIA
+1F76;1F76;03B9 0300;1F76;03B9 0300; # (ὶ; ὶ; ι◌̀; ὶ; ι◌̀; ) GREEK SMALL LETTER IOTA WITH VARIA
+1F77;03AF;03B9 0301;03AF;03B9 0301; # (ί; ί; ι◌́; ί; ι◌́; ) GREEK SMALL LETTER IOTA WITH OXIA
+1F78;1F78;03BF 0300;1F78;03BF 0300; # (ὸ; ὸ; ο◌̀; ὸ; ο◌̀; ) GREEK SMALL LETTER OMICRON WITH VARIA
+1F79;03CC;03BF 0301;03CC;03BF 0301; # (ό; ό; ο◌́; ό; ο◌́; ) GREEK SMALL LETTER OMICRON WITH OXIA
+1F7A;1F7A;03C5 0300;1F7A;03C5 0300; # (ὺ; ὺ; υ◌̀; ὺ; υ◌̀; ) GREEK SMALL LETTER UPSILON WITH VARIA
+1F7B;03CD;03C5 0301;03CD;03C5 0301; # (ύ; ύ; υ◌́; ύ; υ◌́; ) GREEK SMALL LETTER UPSILON WITH OXIA
+1F7C;1F7C;03C9 0300;1F7C;03C9 0300; # (ὼ; ὼ; ω◌̀; ὼ; ω◌̀; ) GREEK SMALL LETTER OMEGA WITH VARIA
+1F7D;03CE;03C9 0301;03CE;03C9 0301; # (ώ; ώ; ω◌́; ώ; ω◌́; ) GREEK SMALL LETTER OMEGA WITH OXIA
+1F80;1F80;03B1 0313 0345;1F80;03B1 0313 0345; # (ᾀ; ᾀ; α◌̓◌ͅ; ᾀ; α◌̓◌ͅ; ) GREEK SMALL LETTER ALPHA WITH PSILI AND YPOGEGRAMMENI
+1F81;1F81;03B1 0314 0345;1F81;03B1 0314 0345; # (ᾁ; ᾁ; α◌̔◌ͅ; ᾁ; α◌̔◌ͅ; ) GREEK SMALL LETTER ALPHA WITH DASIA AND YPOGEGRAMMENI
+1F82;1F82;03B1 0313 0300 0345;1F82;03B1 0313 0300 0345; # (ᾂ; ᾂ; α◌̓◌̀◌ͅ; ᾂ; α◌̓◌̀◌ͅ; ) GREEK SMALL LETTER ALPHA WITH PSILI AND VARIA AND YPOGEGRAMMENI
+1F83;1F83;03B1 0314 0300 0345;1F83;03B1 0314 0300 0345; # (ᾃ; ᾃ; α◌̔◌̀◌ͅ; ᾃ; α◌̔◌̀◌ͅ; ) GREEK SMALL LETTER ALPHA WITH DASIA AND VARIA AND YPOGEGRAMMENI
+1F84;1F84;03B1 0313 0301 0345;1F84;03B1 0313 0301 0345; # (ᾄ; ᾄ; α◌̓◌́◌ͅ; ᾄ; α◌̓◌́◌ͅ; ) GREEK SMALL LETTER ALPHA WITH PSILI AND OXIA AND YPOGEGRAMMENI
+1F85;1F85;03B1 0314 0301 0345;1F85;03B1 0314 0301 0345; # (ᾅ; ᾅ; α◌̔◌́◌ͅ; ᾅ; α◌̔◌́◌ͅ; ) GREEK SMALL LETTER ALPHA WITH DASIA AND OXIA AND YPOGEGRAMMENI
+1F86;1F86;03B1 0313 0342 0345;1F86;03B1 0313 0342 0345; # (ᾆ; ᾆ; α◌̓◌͂◌ͅ; ᾆ; α◌̓◌͂◌ͅ; ) GREEK SMALL LETTER ALPHA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI
+1F87;1F87;03B1 0314 0342 0345;1F87;03B1 0314 0342 0345; # (ᾇ; ᾇ; α◌̔◌͂◌ͅ; ᾇ; α◌̔◌͂◌ͅ; ) GREEK SMALL LETTER ALPHA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI
+1F88;1F88;0391 0313 0345;1F88;0391 0313 0345; # (ᾈ; ᾈ; Α◌̓◌ͅ; ᾈ; Α◌̓◌ͅ; ) GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI
+1F89;1F89;0391 0314 0345;1F89;0391 0314 0345; # (ᾉ; ᾉ; Α◌̔◌ͅ; ᾉ; Α◌̔◌ͅ; ) GREEK CAPITAL LETTER ALPHA WITH DASIA AND PROSGEGRAMMENI
+1F8A;1F8A;0391 0313 0300 0345;1F8A;0391 0313 0300 0345; # (ᾊ; ᾊ; Α◌̓◌̀◌ͅ; ᾊ; Α◌̓◌̀◌ͅ; ) GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA AND PROSGEGRAMMENI
+1F8B;1F8B;0391 0314 0300 0345;1F8B;0391 0314 0300 0345; # (ᾋ; ᾋ; Α◌̔◌̀◌ͅ; ᾋ; Α◌̔◌̀◌ͅ; ) GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA AND PROSGEGRAMMENI
+1F8C;1F8C;0391 0313 0301 0345;1F8C;0391 0313 0301 0345; # (ᾌ; ᾌ; Α◌̓◌́◌ͅ; ᾌ; Α◌̓◌́◌ͅ; ) GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA AND PROSGEGRAMMENI
+1F8D;1F8D;0391 0314 0301 0345;1F8D;0391 0314 0301 0345; # (ᾍ; ᾍ; Α◌̔◌́◌ͅ; ᾍ; Α◌̔◌́◌ͅ; ) GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA AND PROSGEGRAMMENI
+1F8E;1F8E;0391 0313 0342 0345;1F8E;0391 0313 0342 0345; # (ᾎ; ᾎ; Α◌̓◌͂◌ͅ; ᾎ; Α◌̓◌͂◌ͅ; ) GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
+1F8F;1F8F;0391 0314 0342 0345;1F8F;0391 0314 0342 0345; # (ᾏ; ᾏ; Α◌̔◌͂◌ͅ; ᾏ; Α◌̔◌͂◌ͅ; ) GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
+1F90;1F90;03B7 0313 0345;1F90;03B7 0313 0345; # (ᾐ; ᾐ; η◌̓◌ͅ; ᾐ; η◌̓◌ͅ; ) GREEK SMALL LETTER ETA WITH PSILI AND YPOGEGRAMMENI
+1F91;1F91;03B7 0314 0345;1F91;03B7 0314 0345; # (ᾑ; ᾑ; η◌̔◌ͅ; ᾑ; η◌̔◌ͅ; ) GREEK SMALL LETTER ETA WITH DASIA AND YPOGEGRAMMENI
+1F92;1F92;03B7 0313 0300 0345;1F92;03B7 0313 0300 0345; # (ᾒ; ᾒ; η◌̓◌̀◌ͅ; ᾒ; η◌̓◌̀◌ͅ; ) GREEK SMALL LETTER ETA WITH PSILI AND VARIA AND YPOGEGRAMMENI
+1F93;1F93;03B7 0314 0300 0345;1F93;03B7 0314 0300 0345; # (ᾓ; ᾓ; η◌̔◌̀◌ͅ; ᾓ; η◌̔◌̀◌ͅ; ) GREEK SMALL LETTER ETA WITH DASIA AND VARIA AND YPOGEGRAMMENI
+1F94;1F94;03B7 0313 0301 0345;1F94;03B7 0313 0301 0345; # (ᾔ; ᾔ; η◌̓◌́◌ͅ; ᾔ; η◌̓◌́◌ͅ; ) GREEK SMALL LETTER ETA WITH PSILI AND OXIA AND YPOGEGRAMMENI
+1F95;1F95;03B7 0314 0301 0345;1F95;03B7 0314 0301 0345; # (ᾕ; ᾕ; η◌̔◌́◌ͅ; ᾕ; η◌̔◌́◌ͅ; ) GREEK SMALL LETTER ETA WITH DASIA AND OXIA AND YPOGEGRAMMENI
+1F96;1F96;03B7 0313 0342 0345;1F96;03B7 0313 0342 0345; # (ᾖ; ᾖ; η◌̓◌͂◌ͅ; ᾖ; η◌̓◌͂◌ͅ; ) GREEK SMALL LETTER ETA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI
+1F97;1F97;03B7 0314 0342 0345;1F97;03B7 0314 0342 0345; # (ᾗ; ᾗ; η◌̔◌͂◌ͅ; ᾗ; η◌̔◌͂◌ͅ; ) GREEK SMALL LETTER ETA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI
+1F98;1F98;0397 0313 0345;1F98;0397 0313 0345; # (ᾘ; ᾘ; Η◌̓◌ͅ; ᾘ; Η◌̓◌ͅ; ) GREEK CAPITAL LETTER ETA WITH PSILI AND PROSGEGRAMMENI
+1F99;1F99;0397 0314 0345;1F99;0397 0314 0345; # (ᾙ; ᾙ; Η◌̔◌ͅ; ᾙ; Η◌̔◌ͅ; ) GREEK CAPITAL LETTER ETA WITH DASIA AND PROSGEGRAMMENI
+1F9A;1F9A;0397 0313 0300 0345;1F9A;0397 0313 0300 0345; # (ᾚ; ᾚ; Η◌̓◌̀◌ͅ; ᾚ; Η◌̓◌̀◌ͅ; ) GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA AND PROSGEGRAMMENI
+1F9B;1F9B;0397 0314 0300 0345;1F9B;0397 0314 0300 0345; # (ᾛ; ᾛ; Η◌̔◌̀◌ͅ; ᾛ; Η◌̔◌̀◌ͅ; ) GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA AND PROSGEGRAMMENI
+1F9C;1F9C;0397 0313 0301 0345;1F9C;0397 0313 0301 0345; # (ᾜ; ᾜ; Η◌̓◌́◌ͅ; ᾜ; Η◌̓◌́◌ͅ; ) GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA AND PROSGEGRAMMENI
+1F9D;1F9D;0397 0314 0301 0345;1F9D;0397 0314 0301 0345; # (ᾝ; ᾝ; Η◌̔◌́◌ͅ; ᾝ; Η◌̔◌́◌ͅ; ) GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA AND PROSGEGRAMMENI
+1F9E;1F9E;0397 0313 0342 0345;1F9E;0397 0313 0342 0345; # (ᾞ; ᾞ; Η◌̓◌͂◌ͅ; ᾞ; Η◌̓◌͂◌ͅ; ) GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
+1F9F;1F9F;0397 0314 0342 0345;1F9F;0397 0314 0342 0345; # (ᾟ; ᾟ; Η◌̔◌͂◌ͅ; ᾟ; Η◌̔◌͂◌ͅ; ) GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
+1FA0;1FA0;03C9 0313 0345;1FA0;03C9 0313 0345; # (ᾠ; ᾠ; ω◌̓◌ͅ; ᾠ; ω◌̓◌ͅ; ) GREEK SMALL LETTER OMEGA WITH PSILI AND YPOGEGRAMMENI
+1FA1;1FA1;03C9 0314 0345;1FA1;03C9 0314 0345; # (ᾡ; ᾡ; ω◌̔◌ͅ; ᾡ; ω◌̔◌ͅ; ) GREEK SMALL LETTER OMEGA WITH DASIA AND YPOGEGRAMMENI
+1FA2;1FA2;03C9 0313 0300 0345;1FA2;03C9 0313 0300 0345; # (ᾢ; ᾢ; ω◌̓◌̀◌ͅ; ᾢ; ω◌̓◌̀◌ͅ; ) GREEK SMALL LETTER OMEGA WITH PSILI AND VARIA AND YPOGEGRAMMENI
+1FA3;1FA3;03C9 0314 0300 0345;1FA3;03C9 0314 0300 0345; # (ᾣ; ᾣ; ω◌̔◌̀◌ͅ; ᾣ; ω◌̔◌̀◌ͅ; ) GREEK SMALL LETTER OMEGA WITH DASIA AND VARIA AND YPOGEGRAMMENI
+1FA4;1FA4;03C9 0313 0301 0345;1FA4;03C9 0313 0301 0345; # (ᾤ; ᾤ; ω◌̓◌́◌ͅ; ᾤ; ω◌̓◌́◌ͅ; ) GREEK SMALL LETTER OMEGA WITH PSILI AND OXIA AND YPOGEGRAMMENI
+1FA5;1FA5;03C9 0314 0301 0345;1FA5;03C9 0314 0301 0345; # (ᾥ; ᾥ; ω◌̔◌́◌ͅ; ᾥ; ω◌̔◌́◌ͅ; ) GREEK SMALL LETTER OMEGA WITH DASIA AND OXIA AND YPOGEGRAMMENI
+1FA6;1FA6;03C9 0313 0342 0345;1FA6;03C9 0313 0342 0345; # (ᾦ; ᾦ; ω◌̓◌͂◌ͅ; ᾦ; ω◌̓◌͂◌ͅ; ) GREEK SMALL LETTER OMEGA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI
+1FA7;1FA7;03C9 0314 0342 0345;1FA7;03C9 0314 0342 0345; # (ᾧ; ᾧ; ω◌̔◌͂◌ͅ; ᾧ; ω◌̔◌͂◌ͅ; ) GREEK SMALL LETTER OMEGA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI
+1FA8;1FA8;03A9 0313 0345;1FA8;03A9 0313 0345; # (ᾨ; ᾨ; Ω◌̓◌ͅ; ᾨ; Ω◌̓◌ͅ; ) GREEK CAPITAL LETTER OMEGA WITH PSILI AND PROSGEGRAMMENI
+1FA9;1FA9;03A9 0314 0345;1FA9;03A9 0314 0345; # (ᾩ; ᾩ; Ω◌̔◌ͅ; ᾩ; Ω◌̔◌ͅ; ) GREEK CAPITAL LETTER OMEGA WITH DASIA AND PROSGEGRAMMENI
+1FAA;1FAA;03A9 0313 0300 0345;1FAA;03A9 0313 0300 0345; # (ᾪ; ᾪ; Ω◌̓◌̀◌ͅ; ᾪ; Ω◌̓◌̀◌ͅ; ) GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA AND PROSGEGRAMMENI
+1FAB;1FAB;03A9 0314 0300 0345;1FAB;03A9 0314 0300 0345; # (ᾫ; ᾫ; Ω◌̔◌̀◌ͅ; ᾫ; Ω◌̔◌̀◌ͅ; ) GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA AND PROSGEGRAMMENI
+1FAC;1FAC;03A9 0313 0301 0345;1FAC;03A9 0313 0301 0345; # (ᾬ; ᾬ; Ω◌̓◌́◌ͅ; ᾬ; Ω◌̓◌́◌ͅ; ) GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA AND PROSGEGRAMMENI
+1FAD;1FAD;03A9 0314 0301 0345;1FAD;03A9 0314 0301 0345; # (ᾭ; ᾭ; Ω◌̔◌́◌ͅ; ᾭ; Ω◌̔◌́◌ͅ; ) GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA AND PROSGEGRAMMENI
+1FAE;1FAE;03A9 0313 0342 0345;1FAE;03A9 0313 0342 0345; # (ᾮ; ᾮ; Ω◌̓◌͂◌ͅ; ᾮ; Ω◌̓◌͂◌ͅ; ) GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
+1FAF;1FAF;03A9 0314 0342 0345;1FAF;03A9 0314 0342 0345; # (ᾯ; ᾯ; Ω◌̔◌͂◌ͅ; ᾯ; Ω◌̔◌͂◌ͅ; ) GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
+1FB0;1FB0;03B1 0306;1FB0;03B1 0306; # (ᾰ; ᾰ; α◌̆; ᾰ; α◌̆; ) GREEK SMALL LETTER ALPHA WITH VRACHY
+1FB1;1FB1;03B1 0304;1FB1;03B1 0304; # (ᾱ; ᾱ; α◌̄; ᾱ; α◌̄; ) GREEK SMALL LETTER ALPHA WITH MACRON
+1FB2;1FB2;03B1 0300 0345;1FB2;03B1 0300 0345; # (ᾲ; ᾲ; α◌̀◌ͅ; ᾲ; α◌̀◌ͅ; ) GREEK SMALL LETTER ALPHA WITH VARIA AND YPOGEGRAMMENI
+1FB3;1FB3;03B1 0345;1FB3;03B1 0345; # (ᾳ; ᾳ; α◌ͅ; ᾳ; α◌ͅ; ) GREEK SMALL LETTER ALPHA WITH YPOGEGRAMMENI
+1FB4;1FB4;03B1 0301 0345;1FB4;03B1 0301 0345; # (ᾴ; ᾴ; α◌́◌ͅ; ᾴ; α◌́◌ͅ; ) GREEK SMALL LETTER ALPHA WITH OXIA AND YPOGEGRAMMENI
+1FB6;1FB6;03B1 0342;1FB6;03B1 0342; # (ᾶ; ᾶ; α◌͂; ᾶ; α◌͂; ) GREEK SMALL LETTER ALPHA WITH PERISPOMENI
+1FB7;1FB7;03B1 0342 0345;1FB7;03B1 0342 0345; # (ᾷ; ᾷ; α◌͂◌ͅ; ᾷ; α◌͂◌ͅ; ) GREEK SMALL LETTER ALPHA WITH PERISPOMENI AND YPOGEGRAMMENI
+1FB8;1FB8;0391 0306;1FB8;0391 0306; # (Ᾰ; Ᾰ; Α◌̆; Ᾰ; Α◌̆; ) GREEK CAPITAL LETTER ALPHA WITH VRACHY
+1FB9;1FB9;0391 0304;1FB9;0391 0304; # (Ᾱ; Ᾱ; Α◌̄; Ᾱ; Α◌̄; ) GREEK CAPITAL LETTER ALPHA WITH MACRON
+1FBA;1FBA;0391 0300;1FBA;0391 0300; # (Ὰ; Ὰ; Α◌̀; Ὰ; Α◌̀; ) GREEK CAPITAL LETTER ALPHA WITH VARIA
+1FBB;0386;0391 0301;0386;0391 0301; # (Ά; Ά; Α◌́; Ά; Α◌́; ) GREEK CAPITAL LETTER ALPHA WITH OXIA
+1FBC;1FBC;0391 0345;1FBC;0391 0345; # (ᾼ; ᾼ; Α◌ͅ; ᾼ; Α◌ͅ; ) GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI
+1FBD;1FBD;1FBD;0020 0313;0020 0313; # (᾽; ᾽; ᾽; ◌̓; ◌̓; ) GREEK KORONIS
+1FBE;03B9;03B9;03B9;03B9; # (ι; ι; ι; ι; ι; ) GREEK PROSGEGRAMMENI
+1FBF;1FBF;1FBF;0020 0313;0020 0313; # (᾿; ᾿; ᾿; ◌̓; ◌̓; ) GREEK PSILI
+1FC0;1FC0;1FC0;0020 0342;0020 0342; # (῀; ῀; ῀; ◌͂; ◌͂; ) GREEK PERISPOMENI
+1FC1;1FC1;00A8 0342;0020 0308 0342;0020 0308 0342; # (῁; ῁; ¨◌͂; ◌̈◌͂; ◌̈◌͂; ) GREEK DIALYTIKA AND PERISPOMENI
+1FC2;1FC2;03B7 0300 0345;1FC2;03B7 0300 0345; # (ῂ; ῂ; η◌̀◌ͅ; ῂ; η◌̀◌ͅ; ) GREEK SMALL LETTER ETA WITH VARIA AND YPOGEGRAMMENI
+1FC3;1FC3;03B7 0345;1FC3;03B7 0345; # (ῃ; ῃ; η◌ͅ; ῃ; η◌ͅ; ) GREEK SMALL LETTER ETA WITH YPOGEGRAMMENI
+1FC4;1FC4;03B7 0301 0345;1FC4;03B7 0301 0345; # (ῄ; ῄ; η◌́◌ͅ; ῄ; η◌́◌ͅ; ) GREEK SMALL LETTER ETA WITH OXIA AND YPOGEGRAMMENI
+1FC6;1FC6;03B7 0342;1FC6;03B7 0342; # (ῆ; ῆ; η◌͂; ῆ; η◌͂; ) GREEK SMALL LETTER ETA WITH PERISPOMENI
+1FC7;1FC7;03B7 0342 0345;1FC7;03B7 0342 0345; # (ῇ; ῇ; η◌͂◌ͅ; ῇ; η◌͂◌ͅ; ) GREEK SMALL LETTER ETA WITH PERISPOMENI AND YPOGEGRAMMENI
+1FC8;1FC8;0395 0300;1FC8;0395 0300; # (Ὲ; Ὲ; Ε◌̀; Ὲ; Ε◌̀; ) GREEK CAPITAL LETTER EPSILON WITH VARIA
+1FC9;0388;0395 0301;0388;0395 0301; # (Έ; Έ; Ε◌́; Έ; Ε◌́; ) GREEK CAPITAL LETTER EPSILON WITH OXIA
+1FCA;1FCA;0397 0300;1FCA;0397 0300; # (Ὴ; Ὴ; Η◌̀; Ὴ; Η◌̀; ) GREEK CAPITAL LETTER ETA WITH VARIA
+1FCB;0389;0397 0301;0389;0397 0301; # (Ή; Ή; Η◌́; Ή; Η◌́; ) GREEK CAPITAL LETTER ETA WITH OXIA
+1FCC;1FCC;0397 0345;1FCC;0397 0345; # (ῌ; ῌ; Η◌ͅ; ῌ; Η◌ͅ; ) GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI
+1FCD;1FCD;1FBF 0300;0020 0313 0300;0020 0313 0300; # (῍; ῍; ᾿◌̀; ◌̓◌̀; ◌̓◌̀; ) GREEK PSILI AND VARIA
+1FCE;1FCE;1FBF 0301;0020 0313 0301;0020 0313 0301; # (῎; ῎; ᾿◌́; ◌̓◌́; ◌̓◌́; ) GREEK PSILI AND OXIA
+1FCF;1FCF;1FBF 0342;0020 0313 0342;0020 0313 0342; # (῏; ῏; ᾿◌͂; ◌̓◌͂; ◌̓◌͂; ) GREEK PSILI AND PERISPOMENI
+1FD0;1FD0;03B9 0306;1FD0;03B9 0306; # (ῐ; ῐ; ι◌̆; ῐ; ι◌̆; ) GREEK SMALL LETTER IOTA WITH VRACHY
+1FD1;1FD1;03B9 0304;1FD1;03B9 0304; # (ῑ; ῑ; ι◌̄; ῑ; ι◌̄; ) GREEK SMALL LETTER IOTA WITH MACRON
+1FD2;1FD2;03B9 0308 0300;1FD2;03B9 0308 0300; # (ῒ; ῒ; ι◌̈◌̀; ῒ; ι◌̈◌̀; ) GREEK SMALL LETTER IOTA WITH DIALYTIKA AND VARIA
+1FD3;0390;03B9 0308 0301;0390;03B9 0308 0301; # (ΐ; ΐ; ι◌̈◌́; ΐ; ι◌̈◌́; ) GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA
+1FD6;1FD6;03B9 0342;1FD6;03B9 0342; # (ῖ; ῖ; ι◌͂; ῖ; ι◌͂; ) GREEK SMALL LETTER IOTA WITH PERISPOMENI
+1FD7;1FD7;03B9 0308 0342;1FD7;03B9 0308 0342; # (ῗ; ῗ; ι◌̈◌͂; ῗ; ι◌̈◌͂; ) GREEK SMALL LETTER IOTA WITH DIALYTIKA AND PERISPOMENI
+1FD8;1FD8;0399 0306;1FD8;0399 0306; # (Ῐ; Ῐ; Ι◌̆; Ῐ; Ι◌̆; ) GREEK CAPITAL LETTER IOTA WITH VRACHY
+1FD9;1FD9;0399 0304;1FD9;0399 0304; # (Ῑ; Ῑ; Ι◌̄; Ῑ; Ι◌̄; ) GREEK CAPITAL LETTER IOTA WITH MACRON
+1FDA;1FDA;0399 0300;1FDA;0399 0300; # (Ὶ; Ὶ; Ι◌̀; Ὶ; Ι◌̀; ) GREEK CAPITAL LETTER IOTA WITH VARIA
+1FDB;038A;0399 0301;038A;0399 0301; # (Ί; Ί; Ι◌́; Ί; Ι◌́; ) GREEK CAPITAL LETTER IOTA WITH OXIA
+1FDD;1FDD;1FFE 0300;0020 0314 0300;0020 0314 0300; # (῝; ῝; ῾◌̀; ◌̔◌̀; ◌̔◌̀; ) GREEK DASIA AND VARIA
+1FDE;1FDE;1FFE 0301;0020 0314 0301;0020 0314 0301; # (῞; ῞; ῾◌́; ◌̔◌́; ◌̔◌́; ) GREEK DASIA AND OXIA
+1FDF;1FDF;1FFE 0342;0020 0314 0342;0020 0314 0342; # (῟; ῟; ῾◌͂; ◌̔◌͂; ◌̔◌͂; ) GREEK DASIA AND PERISPOMENI
+1FE0;1FE0;03C5 0306;1FE0;03C5 0306; # (ῠ; ῠ; υ◌̆; ῠ; υ◌̆; ) GREEK SMALL LETTER UPSILON WITH VRACHY
+1FE1;1FE1;03C5 0304;1FE1;03C5 0304; # (ῡ; ῡ; υ◌̄; ῡ; υ◌̄; ) GREEK SMALL LETTER UPSILON WITH MACRON
+1FE2;1FE2;03C5 0308 0300;1FE2;03C5 0308 0300; # (ῢ; ῢ; υ◌̈◌̀; ῢ; υ◌̈◌̀; ) GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND VARIA
+1FE3;03B0;03C5 0308 0301;03B0;03C5 0308 0301; # (ΰ; ΰ; υ◌̈◌́; ΰ; υ◌̈◌́; ) GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA
+1FE4;1FE4;03C1 0313;1FE4;03C1 0313; # (ῤ; ῤ; ρ◌̓; ῤ; ρ◌̓; ) GREEK SMALL LETTER RHO WITH PSILI
+1FE5;1FE5;03C1 0314;1FE5;03C1 0314; # (ῥ; ῥ; ρ◌̔; ῥ; ρ◌̔; ) GREEK SMALL LETTER RHO WITH DASIA
+1FE6;1FE6;03C5 0342;1FE6;03C5 0342; # (ῦ; ῦ; υ◌͂; ῦ; υ◌͂; ) GREEK SMALL LETTER UPSILON WITH PERISPOMENI
+1FE7;1FE7;03C5 0308 0342;1FE7;03C5 0308 0342; # (ῧ; ῧ; υ◌̈◌͂; ῧ; υ◌̈◌͂; ) GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND PERISPOMENI
+1FE8;1FE8;03A5 0306;1FE8;03A5 0306; # (Ῠ; Ῠ; Υ◌̆; Ῠ; Υ◌̆; ) GREEK CAPITAL LETTER UPSILON WITH VRACHY
+1FE9;1FE9;03A5 0304;1FE9;03A5 0304; # (Ῡ; Ῡ; Υ◌̄; Ῡ; Υ◌̄; ) GREEK CAPITAL LETTER UPSILON WITH MACRON
+1FEA;1FEA;03A5 0300;1FEA;03A5 0300; # (Ὺ; Ὺ; Υ◌̀; Ὺ; Υ◌̀; ) GREEK CAPITAL LETTER UPSILON WITH VARIA
+1FEB;038E;03A5 0301;038E;03A5 0301; # (Ύ; Ύ; Υ◌́; Ύ; Υ◌́; ) GREEK CAPITAL LETTER UPSILON WITH OXIA
+1FEC;1FEC;03A1 0314;1FEC;03A1 0314; # (Ῥ; Ῥ; Ρ◌̔; Ῥ; Ρ◌̔; ) GREEK CAPITAL LETTER RHO WITH DASIA
+1FED;1FED;00A8 0300;0020 0308 0300;0020 0308 0300; # (῭; ῭; ¨◌̀; ◌̈◌̀; ◌̈◌̀; ) GREEK DIALYTIKA AND VARIA
+1FEE;0385;00A8 0301;0020 0308 0301;0020 0308 0301; # (΅; ΅; ¨◌́; ◌̈◌́; ◌̈◌́; ) GREEK DIALYTIKA AND OXIA
+1FEF;0060;0060;0060;0060; # (`; `; `; `; `; ) GREEK VARIA
+1FF2;1FF2;03C9 0300 0345;1FF2;03C9 0300 0345; # (ῲ; ῲ; ω◌̀◌ͅ; ῲ; ω◌̀◌ͅ; ) GREEK SMALL LETTER OMEGA WITH VARIA AND YPOGEGRAMMENI
+1FF3;1FF3;03C9 0345;1FF3;03C9 0345; # (ῳ; ῳ; ω◌ͅ; ῳ; ω◌ͅ; ) GREEK SMALL LETTER OMEGA WITH YPOGEGRAMMENI
+1FF4;1FF4;03C9 0301 0345;1FF4;03C9 0301 0345; # (ῴ; ῴ; ω◌́◌ͅ; ῴ; ω◌́◌ͅ; ) GREEK SMALL LETTER OMEGA WITH OXIA AND YPOGEGRAMMENI
+1FF6;1FF6;03C9 0342;1FF6;03C9 0342; # (ῶ; ῶ; ω◌͂; ῶ; ω◌͂; ) GREEK SMALL LETTER OMEGA WITH PERISPOMENI
+1FF7;1FF7;03C9 0342 0345;1FF7;03C9 0342 0345; # (ῷ; ῷ; ω◌͂◌ͅ; ῷ; ω◌͂◌ͅ; ) GREEK SMALL LETTER OMEGA WITH PERISPOMENI AND YPOGEGRAMMENI
+1FF8;1FF8;039F 0300;1FF8;039F 0300; # (Ὸ; Ὸ; Ο◌̀; Ὸ; Ο◌̀; ) GREEK CAPITAL LETTER OMICRON WITH VARIA
+1FF9;038C;039F 0301;038C;039F 0301; # (Ό; Ό; Ο◌́; Ό; Ο◌́; ) GREEK CAPITAL LETTER OMICRON WITH OXIA
+1FFA;1FFA;03A9 0300;1FFA;03A9 0300; # (Ὼ; Ὼ; Ω◌̀; Ὼ; Ω◌̀; ) GREEK CAPITAL LETTER OMEGA WITH VARIA
+1FFB;038F;03A9 0301;038F;03A9 0301; # (Ώ; Ώ; Ω◌́; Ώ; Ω◌́; ) GREEK CAPITAL LETTER OMEGA WITH OXIA
+1FFC;1FFC;03A9 0345;1FFC;03A9 0345; # (ῼ; ῼ; Ω◌ͅ; ῼ; Ω◌ͅ; ) GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI
+1FFD;00B4;00B4;0020 0301;0020 0301; # (´; ´; ´; ◌́; ◌́; ) GREEK OXIA
+1FFE;1FFE;1FFE;0020 0314;0020 0314; # (῾; ῾; ῾; ◌̔; ◌̔; ) GREEK DASIA
+2000;2002;2002;0020;0020; # ( ;  ;  ; ; ; ) EN QUAD
+2001;2003;2003;0020;0020; # ( ;  ;  ; ; ; ) EM QUAD
+2002;2002;2002;0020;0020; # ( ;  ;  ; ; ; ) EN SPACE
+2003;2003;2003;0020;0020; # ( ;  ;  ; ; ; ) EM SPACE
+2004;2004;2004;0020;0020; # ( ;  ;  ; ; ; ) THREE-PER-EM SPACE
+2005;2005;2005;0020;0020; # ( ;  ;  ; ; ; ) FOUR-PER-EM SPACE
+2006;2006;2006;0020;0020; # ( ;  ;  ; ; ; ) SIX-PER-EM SPACE
+2007;2007;2007;0020;0020; # ( ;  ;  ; ; ; ) FIGURE SPACE
+2008;2008;2008;0020;0020; # ( ;  ;  ; ; ; ) PUNCTUATION SPACE
+2009;2009;2009;0020;0020; # ( ;  ;  ; ; ; ) THIN SPACE
+200A;200A;200A;0020;0020; # ( ;  ;  ; ; ; ) HAIR SPACE
+2011;2011;2011;2010;2010; # (‑; ‑; ‑; ‐; ‐; ) NON-BREAKING HYPHEN
+2017;2017;2017;0020 0333;0020 0333; # (‗; ‗; ‗; ◌̳; ◌̳; ) DOUBLE LOW LINE
+2024;2024;2024;002E;002E; # (․; ․; ․; .; .; ) ONE DOT LEADER
+2025;2025;2025;002E 002E;002E 002E; # (‥; ‥; ‥; ..; ..; ) TWO DOT LEADER
+2026;2026;2026;002E 002E 002E;002E 002E 002E; # (…; …; …; ...; ...; ) HORIZONTAL ELLIPSIS
+202F;202F;202F;0020;0020; # ( ;  ;  ; ; ; ) NARROW NO-BREAK SPACE
+2033;2033;2033;2032 2032;2032 2032; # (″; ″; ″; ′′; ′′; ) DOUBLE PRIME
+2034;2034;2034;2032 2032 2032;2032 2032 2032; # (‴; ‴; ‴; ′′′; ′′′; ) TRIPLE PRIME
+2036;2036;2036;2035 2035;2035 2035; # (‶; ‶; ‶; ‵‵; ‵‵; ) REVERSED DOUBLE PRIME
+2037;2037;2037;2035 2035 2035;2035 2035 2035; # (‷; ‷; ‷; ‵‵‵; ‵‵‵; ) REVERSED TRIPLE PRIME
+203C;203C;203C;0021 0021;0021 0021; # (‼; ‼; ‼; !!; !!; ) DOUBLE EXCLAMATION MARK
+203E;203E;203E;0020 0305;0020 0305; # (‾; ‾; ‾; ◌̅; ◌̅; ) OVERLINE
+2047;2047;2047;003F 003F;003F 003F; # (⁇; ⁇; ⁇; ??; ??; ) DOUBLE QUESTION MARK
+2048;2048;2048;003F 0021;003F 0021; # (⁈; ⁈; ⁈; ?!; ?!; ) QUESTION EXCLAMATION MARK
+2049;2049;2049;0021 003F;0021 003F; # (⁉; ⁉; ⁉; !?; !?; ) EXCLAMATION QUESTION MARK
+2057;2057;2057;2032 2032 2032 2032;2032 2032 2032 2032; # (⁗; ⁗; ⁗; ′′′′; ′′′′; ) QUADRUPLE PRIME
+205F;205F;205F;0020;0020; # ( ;  ;  ; ; ; ) MEDIUM MATHEMATICAL SPACE
+2070;2070;2070;0030;0030; # (⁰; ⁰; ⁰; 0; 0; ) SUPERSCRIPT ZERO
+2071;2071;2071;0069;0069; # (ⁱ; ⁱ; ⁱ; i; i; ) SUPERSCRIPT LATIN SMALL LETTER I
+2074;2074;2074;0034;0034; # (⁴; ⁴; ⁴; 4; 4; ) SUPERSCRIPT FOUR
+2075;2075;2075;0035;0035; # (⁵; ⁵; ⁵; 5; 5; ) SUPERSCRIPT FIVE
+2076;2076;2076;0036;0036; # (⁶; ⁶; ⁶; 6; 6; ) SUPERSCRIPT SIX
+2077;2077;2077;0037;0037; # (⁷; ⁷; ⁷; 7; 7; ) SUPERSCRIPT SEVEN
+2078;2078;2078;0038;0038; # (⁸; ⁸; ⁸; 8; 8; ) SUPERSCRIPT EIGHT
+2079;2079;2079;0039;0039; # (⁹; ⁹; ⁹; 9; 9; ) SUPERSCRIPT NINE
+207A;207A;207A;002B;002B; # (⁺; ⁺; ⁺; +; +; ) SUPERSCRIPT PLUS SIGN
+207B;207B;207B;2212;2212; # (⁻; ⁻; ⁻; −; −; ) SUPERSCRIPT MINUS
+207C;207C;207C;003D;003D; # (⁼; ⁼; ⁼; =; =; ) SUPERSCRIPT EQUALS SIGN
+207D;207D;207D;0028;0028; # (⁽; ⁽; ⁽; (; (; ) SUPERSCRIPT LEFT PARENTHESIS
+207E;207E;207E;0029;0029; # (⁾; ⁾; ⁾; ); ); ) SUPERSCRIPT RIGHT PARENTHESIS
+207F;207F;207F;006E;006E; # (ⁿ; ⁿ; ⁿ; n; n; ) SUPERSCRIPT LATIN SMALL LETTER N
+2080;2080;2080;0030;0030; # (₀; ₀; ₀; 0; 0; ) SUBSCRIPT ZERO
+2081;2081;2081;0031;0031; # (₁; ₁; ₁; 1; 1; ) SUBSCRIPT ONE
+2082;2082;2082;0032;0032; # (₂; ₂; ₂; 2; 2; ) SUBSCRIPT TWO
+2083;2083;2083;0033;0033; # (₃; ₃; ₃; 3; 3; ) SUBSCRIPT THREE
+2084;2084;2084;0034;0034; # (₄; ₄; ₄; 4; 4; ) SUBSCRIPT FOUR
+2085;2085;2085;0035;0035; # (₅; ₅; ₅; 5; 5; ) SUBSCRIPT FIVE
+2086;2086;2086;0036;0036; # (₆; ₆; ₆; 6; 6; ) SUBSCRIPT SIX
+2087;2087;2087;0037;0037; # (₇; ₇; ₇; 7; 7; ) SUBSCRIPT SEVEN
+2088;2088;2088;0038;0038; # (₈; ₈; ₈; 8; 8; ) SUBSCRIPT EIGHT
+2089;2089;2089;0039;0039; # (₉; ₉; ₉; 9; 9; ) SUBSCRIPT NINE
+208A;208A;208A;002B;002B; # (₊; ₊; ₊; +; +; ) SUBSCRIPT PLUS SIGN
+208B;208B;208B;2212;2212; # (₋; ₋; ₋; −; −; ) SUBSCRIPT MINUS
+208C;208C;208C;003D;003D; # (₌; ₌; ₌; =; =; ) SUBSCRIPT EQUALS SIGN
+208D;208D;208D;0028;0028; # (₍; ₍; ₍; (; (; ) SUBSCRIPT LEFT PARENTHESIS
+208E;208E;208E;0029;0029; # (₎; ₎; ₎; ); ); ) SUBSCRIPT RIGHT PARENTHESIS
+20A8;20A8;20A8;0052 0073;0052 0073; # (₨; ₨; ₨; Rs; Rs; ) RUPEE SIGN
+2100;2100;2100;0061 002F 0063;0061 002F 0063; # (℀; ℀; ℀; a/c; a/c; ) ACCOUNT OF
+2101;2101;2101;0061 002F 0073;0061 002F 0073; # (℁; ℁; ℁; a/s; a/s; ) ADDRESSED TO THE SUBJECT
+2102;2102;2102;0043;0043; # (ℂ; ℂ; ℂ; C; C; ) DOUBLE-STRUCK CAPITAL C
+2103;2103;2103;00B0 0043;00B0 0043; # (℃; ℃; ℃; °C; °C; ) DEGREE CELSIUS
+2105;2105;2105;0063 002F 006F;0063 002F 006F; # (℅; ℅; ℅; c/o; c/o; ) CARE OF
+2106;2106;2106;0063 002F 0075;0063 002F 0075; # (℆; ℆; ℆; c/u; c/u; ) CADA UNA
+2107;2107;2107;0190;0190; # (ℇ; ℇ; ℇ; Ɛ; Ɛ; ) EULER CONSTANT
+2109;2109;2109;00B0 0046;00B0 0046; # (℉; ℉; ℉; °F; °F; ) DEGREE FAHRENHEIT
+210A;210A;210A;0067;0067; # (ℊ; ℊ; ℊ; g; g; ) SCRIPT SMALL G
+210B;210B;210B;0048;0048; # (ℋ; ℋ; ℋ; H; H; ) SCRIPT CAPITAL H
+210C;210C;210C;0048;0048; # (ℌ; ℌ; ℌ; H; H; ) BLACK-LETTER CAPITAL H
+210D;210D;210D;0048;0048; # (ℍ; ℍ; ℍ; H; H; ) DOUBLE-STRUCK CAPITAL H
+210E;210E;210E;0068;0068; # (ℎ; ℎ; ℎ; h; h; ) PLANCK CONSTANT
+210F;210F;210F;0127;0127; # (ℏ; ℏ; ℏ; ħ; ħ; ) PLANCK CONSTANT OVER TWO PI
+2110;2110;2110;0049;0049; # (ℐ; ℐ; ℐ; I; I; ) SCRIPT CAPITAL I
+2111;2111;2111;0049;0049; # (ℑ; ℑ; ℑ; I; I; ) BLACK-LETTER CAPITAL I
+2112;2112;2112;004C;004C; # (ℒ; ℒ; ℒ; L; L; ) SCRIPT CAPITAL L
+2113;2113;2113;006C;006C; # (ℓ; ℓ; ℓ; l; l; ) SCRIPT SMALL L
+2115;2115;2115;004E;004E; # (ℕ; ℕ; ℕ; N; N; ) DOUBLE-STRUCK CAPITAL N
+2116;2116;2116;004E 006F;004E 006F; # (№; №; №; No; No; ) NUMERO SIGN
+2119;2119;2119;0050;0050; # (ℙ; ℙ; ℙ; P; P; ) DOUBLE-STRUCK CAPITAL P
+211A;211A;211A;0051;0051; # (ℚ; ℚ; ℚ; Q; Q; ) DOUBLE-STRUCK CAPITAL Q
+211B;211B;211B;0052;0052; # (ℛ; ℛ; ℛ; R; R; ) SCRIPT CAPITAL R
+211C;211C;211C;0052;0052; # (ℜ; ℜ; ℜ; R; R; ) BLACK-LETTER CAPITAL R
+211D;211D;211D;0052;0052; # (ℝ; ℝ; ℝ; R; R; ) DOUBLE-STRUCK CAPITAL R
+2120;2120;2120;0053 004D;0053 004D; # (℠; ℠; ℠; SM; SM; ) SERVICE MARK
+2121;2121;2121;0054 0045 004C;0054 0045 004C; # (℡; ℡; ℡; TEL; TEL; ) TELEPHONE SIGN
+2122;2122;2122;0054 004D;0054 004D; # (™; ™; ™; TM; TM; ) TRADE MARK SIGN
+2124;2124;2124;005A;005A; # (ℤ; ℤ; ℤ; Z; Z; ) DOUBLE-STRUCK CAPITAL Z
+2126;03A9;03A9;03A9;03A9; # (Ω; Ω; Ω; Ω; Ω; ) OHM SIGN
+2128;2128;2128;005A;005A; # (ℨ; ℨ; ℨ; Z; Z; ) BLACK-LETTER CAPITAL Z
+212A;004B;004B;004B;004B; # (K; K; K; K; K; ) KELVIN SIGN
+212B;00C5;0041 030A;00C5;0041 030A; # (Å; Å; A◌̊; Å; A◌̊; ) ANGSTROM SIGN
+212C;212C;212C;0042;0042; # (ℬ; ℬ; ℬ; B; B; ) SCRIPT CAPITAL B
+212D;212D;212D;0043;0043; # (ℭ; ℭ; ℭ; C; C; ) BLACK-LETTER CAPITAL C
+212F;212F;212F;0065;0065; # (ℯ; ℯ; ℯ; e; e; ) SCRIPT SMALL E
+2130;2130;2130;0045;0045; # (ℰ; ℰ; ℰ; E; E; ) SCRIPT CAPITAL E
+2131;2131;2131;0046;0046; # (ℱ; ℱ; ℱ; F; F; ) SCRIPT CAPITAL F
+2133;2133;2133;004D;004D; # (ℳ; ℳ; ℳ; M; M; ) SCRIPT CAPITAL M
+2134;2134;2134;006F;006F; # (ℴ; ℴ; ℴ; o; o; ) SCRIPT SMALL O
+2135;2135;2135;05D0;05D0; # (ℵ; ℵ; ℵ; א; א; ) ALEF SYMBOL
+2136;2136;2136;05D1;05D1; # (ℶ; ℶ; ℶ; ב; ב; ) BET SYMBOL
+2137;2137;2137;05D2;05D2; # (ℷ; ℷ; ℷ; ג; ג; ) GIMEL SYMBOL
+2138;2138;2138;05D3;05D3; # (ℸ; ℸ; ℸ; ד; ד; ) DALET SYMBOL
+2139;2139;2139;0069;0069; # (ℹ; ℹ; ℹ; i; i; ) INFORMATION SOURCE
+213B;213B;213B;0046 0041 0058;0046 0041 0058; # (℻; ℻; ℻; FAX; FAX; ) FACSIMILE SIGN
+213D;213D;213D;03B3;03B3; # (ℽ; ℽ; ℽ; γ; γ; ) DOUBLE-STRUCK SMALL GAMMA
+213E;213E;213E;0393;0393; # (ℾ; ℾ; ℾ; Γ; Γ; ) DOUBLE-STRUCK CAPITAL GAMMA
+213F;213F;213F;03A0;03A0; # (ℿ; ℿ; ℿ; Π; Π; ) DOUBLE-STRUCK CAPITAL PI
+2140;2140;2140;2211;2211; # (⅀; ⅀; ⅀; ∑; ∑; ) DOUBLE-STRUCK N-ARY SUMMATION
+2145;2145;2145;0044;0044; # (ⅅ; ⅅ; ⅅ; D; D; ) DOUBLE-STRUCK ITALIC CAPITAL D
+2146;2146;2146;0064;0064; # (ⅆ; ⅆ; ⅆ; d; d; ) DOUBLE-STRUCK ITALIC SMALL D
+2147;2147;2147;0065;0065; # (ⅇ; ⅇ; ⅇ; e; e; ) DOUBLE-STRUCK ITALIC SMALL E
+2148;2148;2148;0069;0069; # (ⅈ; ⅈ; ⅈ; i; i; ) DOUBLE-STRUCK ITALIC SMALL I
+2149;2149;2149;006A;006A; # (ⅉ; ⅉ; ⅉ; j; j; ) DOUBLE-STRUCK ITALIC SMALL J
+2153;2153;2153;0031 2044 0033;0031 2044 0033; # (⅓; ⅓; ⅓; 1⁄3; 1⁄3; ) VULGAR FRACTION ONE THIRD
+2154;2154;2154;0032 2044 0033;0032 2044 0033; # (⅔; ⅔; ⅔; 2⁄3; 2⁄3; ) VULGAR FRACTION TWO THIRDS
+2155;2155;2155;0031 2044 0035;0031 2044 0035; # (⅕; ⅕; ⅕; 1⁄5; 1⁄5; ) VULGAR FRACTION ONE FIFTH
+2156;2156;2156;0032 2044 0035;0032 2044 0035; # (⅖; ⅖; ⅖; 2⁄5; 2⁄5; ) VULGAR FRACTION TWO FIFTHS
+2157;2157;2157;0033 2044 0035;0033 2044 0035; # (⅗; ⅗; ⅗; 3⁄5; 3⁄5; ) VULGAR FRACTION THREE FIFTHS
+2158;2158;2158;0034 2044 0035;0034 2044 0035; # (⅘; ⅘; ⅘; 4⁄5; 4⁄5; ) VULGAR FRACTION FOUR FIFTHS
+2159;2159;2159;0031 2044 0036;0031 2044 0036; # (⅙; ⅙; ⅙; 1⁄6; 1⁄6; ) VULGAR FRACTION ONE SIXTH
+215A;215A;215A;0035 2044 0036;0035 2044 0036; # (⅚; ⅚; ⅚; 5⁄6; 5⁄6; ) VULGAR FRACTION FIVE SIXTHS
+215B;215B;215B;0031 2044 0038;0031 2044 0038; # (⅛; ⅛; ⅛; 1⁄8; 1⁄8; ) VULGAR FRACTION ONE EIGHTH
+215C;215C;215C;0033 2044 0038;0033 2044 0038; # (⅜; ⅜; ⅜; 3⁄8; 3⁄8; ) VULGAR FRACTION THREE EIGHTHS
+215D;215D;215D;0035 2044 0038;0035 2044 0038; # (⅝; ⅝; ⅝; 5⁄8; 5⁄8; ) VULGAR FRACTION FIVE EIGHTHS
+215E;215E;215E;0037 2044 0038;0037 2044 0038; # (⅞; ⅞; ⅞; 7⁄8; 7⁄8; ) VULGAR FRACTION SEVEN EIGHTHS
+215F;215F;215F;0031 2044;0031 2044; # (⅟; ⅟; ⅟; 1⁄; 1⁄; ) FRACTION NUMERATOR ONE
+2160;2160;2160;0049;0049; # (Ⅰ; Ⅰ; Ⅰ; I; I; ) ROMAN NUMERAL ONE
+2161;2161;2161;0049 0049;0049 0049; # (Ⅱ; Ⅱ; Ⅱ; II; II; ) ROMAN NUMERAL TWO
+2162;2162;2162;0049 0049 0049;0049 0049 0049; # (Ⅲ; Ⅲ; Ⅲ; III; III; ) ROMAN NUMERAL THREE
+2163;2163;2163;0049 0056;0049 0056; # (Ⅳ; Ⅳ; Ⅳ; IV; IV; ) ROMAN NUMERAL FOUR
+2164;2164;2164;0056;0056; # (Ⅴ; Ⅴ; Ⅴ; V; V; ) ROMAN NUMERAL FIVE
+2165;2165;2165;0056 0049;0056 0049; # (Ⅵ; Ⅵ; Ⅵ; VI; VI; ) ROMAN NUMERAL SIX
+2166;2166;2166;0056 0049 0049;0056 0049 0049; # (Ⅶ; Ⅶ; Ⅶ; VII; VII; ) ROMAN NUMERAL SEVEN
+2167;2167;2167;0056 0049 0049 0049;0056 0049 0049 0049; # (Ⅷ; Ⅷ; Ⅷ; VIII; VIII; ) ROMAN NUMERAL EIGHT
+2168;2168;2168;0049 0058;0049 0058; # (Ⅸ; Ⅸ; Ⅸ; IX; IX; ) ROMAN NUMERAL NINE
+2169;2169;2169;0058;0058; # (Ⅹ; Ⅹ; Ⅹ; X; X; ) ROMAN NUMERAL TEN
+216A;216A;216A;0058 0049;0058 0049; # (Ⅺ; Ⅺ; Ⅺ; XI; XI; ) ROMAN NUMERAL ELEVEN
+216B;216B;216B;0058 0049 0049;0058 0049 0049; # (Ⅻ; Ⅻ; Ⅻ; XII; XII; ) ROMAN NUMERAL TWELVE
+216C;216C;216C;004C;004C; # (Ⅼ; Ⅼ; Ⅼ; L; L; ) ROMAN NUMERAL FIFTY
+216D;216D;216D;0043;0043; # (Ⅽ; Ⅽ; Ⅽ; C; C; ) ROMAN NUMERAL ONE HUNDRED
+216E;216E;216E;0044;0044; # (Ⅾ; Ⅾ; Ⅾ; D; D; ) ROMAN NUMERAL FIVE HUNDRED
+216F;216F;216F;004D;004D; # (Ⅿ; Ⅿ; Ⅿ; M; M; ) ROMAN NUMERAL ONE THOUSAND
+2170;2170;2170;0069;0069; # (ⅰ; ⅰ; ⅰ; i; i; ) SMALL ROMAN NUMERAL ONE
+2171;2171;2171;0069 0069;0069 0069; # (ⅱ; ⅱ; ⅱ; ii; ii; ) SMALL ROMAN NUMERAL TWO
+2172;2172;2172;0069 0069 0069;0069 0069 0069; # (ⅲ; ⅲ; ⅲ; iii; iii; ) SMALL ROMAN NUMERAL THREE
+2173;2173;2173;0069 0076;0069 0076; # (ⅳ; ⅳ; ⅳ; iv; iv; ) SMALL ROMAN NUMERAL FOUR
+2174;2174;2174;0076;0076; # (ⅴ; ⅴ; ⅴ; v; v; ) SMALL ROMAN NUMERAL FIVE
+2175;2175;2175;0076 0069;0076 0069; # (ⅵ; ⅵ; ⅵ; vi; vi; ) SMALL ROMAN NUMERAL SIX
+2176;2176;2176;0076 0069 0069;0076 0069 0069; # (ⅶ; ⅶ; ⅶ; vii; vii; ) SMALL ROMAN NUMERAL SEVEN
+2177;2177;2177;0076 0069 0069 0069;0076 0069 0069 0069; # (ⅷ; ⅷ; ⅷ; viii; viii; ) SMALL ROMAN NUMERAL EIGHT
+2178;2178;2178;0069 0078;0069 0078; # (ⅸ; ⅸ; ⅸ; ix; ix; ) SMALL ROMAN NUMERAL NINE
+2179;2179;2179;0078;0078; # (ⅹ; ⅹ; ⅹ; x; x; ) SMALL ROMAN NUMERAL TEN
+217A;217A;217A;0078 0069;0078 0069; # (ⅺ; ⅺ; ⅺ; xi; xi; ) SMALL ROMAN NUMERAL ELEVEN
+217B;217B;217B;0078 0069 0069;0078 0069 0069; # (ⅻ; ⅻ; ⅻ; xii; xii; ) SMALL ROMAN NUMERAL TWELVE
+217C;217C;217C;006C;006C; # (ⅼ; ⅼ; ⅼ; l; l; ) SMALL ROMAN NUMERAL FIFTY
+217D;217D;217D;0063;0063; # (ⅽ; ⅽ; ⅽ; c; c; ) SMALL ROMAN NUMERAL ONE HUNDRED
+217E;217E;217E;0064;0064; # (ⅾ; ⅾ; ⅾ; d; d; ) SMALL ROMAN NUMERAL FIVE HUNDRED
+217F;217F;217F;006D;006D; # (ⅿ; ⅿ; ⅿ; m; m; ) SMALL ROMAN NUMERAL ONE THOUSAND
+219A;219A;2190 0338;219A;2190 0338; # (↚; ↚; ←◌̸; ↚; ←◌̸; ) LEFTWARDS ARROW WITH STROKE
+219B;219B;2192 0338;219B;2192 0338; # (↛; ↛; →◌̸; ↛; →◌̸; ) RIGHTWARDS ARROW WITH STROKE
+21AE;21AE;2194 0338;21AE;2194 0338; # (↮; ↮; ↔◌̸; ↮; ↔◌̸; ) LEFT RIGHT ARROW WITH STROKE
+21CD;21CD;21D0 0338;21CD;21D0 0338; # (⇍; ⇍; ⇐◌̸; ⇍; ⇐◌̸; ) LEFTWARDS DOUBLE ARROW WITH STROKE
+21CE;21CE;21D4 0338;21CE;21D4 0338; # (⇎; ⇎; ⇔◌̸; ⇎; ⇔◌̸; ) LEFT RIGHT DOUBLE ARROW WITH STROKE
+21CF;21CF;21D2 0338;21CF;21D2 0338; # (⇏; ⇏; ⇒◌̸; ⇏; ⇒◌̸; ) RIGHTWARDS DOUBLE ARROW WITH STROKE
+2204;2204;2203 0338;2204;2203 0338; # (∄; ∄; ∃◌̸; ∄; ∃◌̸; ) THERE DOES NOT EXIST
+2209;2209;2208 0338;2209;2208 0338; # (∉; ∉; ∈◌̸; ∉; ∈◌̸; ) NOT AN ELEMENT OF
+220C;220C;220B 0338;220C;220B 0338; # (∌; ∌; ∋◌̸; ∌; ∋◌̸; ) DOES NOT CONTAIN AS MEMBER
+2224;2224;2223 0338;2224;2223 0338; # (∤; ∤; ∣◌̸; ∤; ∣◌̸; ) DOES NOT DIVIDE
+2226;2226;2225 0338;2226;2225 0338; # (∦; ∦; ∥◌̸; ∦; ∥◌̸; ) NOT PARALLEL TO
+222C;222C;222C;222B 222B;222B 222B; # (∬; ∬; ∬; ∫∫; ∫∫; ) DOUBLE INTEGRAL
+222D;222D;222D;222B 222B 222B;222B 222B 222B; # (∭; ∭; ∭; ∫∫∫; ∫∫∫; ) TRIPLE INTEGRAL
+222F;222F;222F;222E 222E;222E 222E; # (∯; ∯; ∯; ∮∮; ∮∮; ) SURFACE INTEGRAL
+2230;2230;2230;222E 222E 222E;222E 222E 222E; # (∰; ∰; ∰; ∮∮∮; ∮∮∮; ) VOLUME INTEGRAL
+2241;2241;223C 0338;2241;223C 0338; # (≁; ≁; ∼◌̸; ≁; ∼◌̸; ) NOT TILDE
+2244;2244;2243 0338;2244;2243 0338; # (≄; ≄; ≃◌̸; ≄; ≃◌̸; ) NOT ASYMPTOTICALLY EQUAL TO
+2247;2247;2245 0338;2247;2245 0338; # (≇; ≇; ≅◌̸; ≇; ≅◌̸; ) NEITHER APPROXIMATELY NOR ACTUALLY EQUAL TO
+2249;2249;2248 0338;2249;2248 0338; # (≉; ≉; ≈◌̸; ≉; ≈◌̸; ) NOT ALMOST EQUAL TO
+2260;2260;003D 0338;2260;003D 0338; # (≠; ≠; =◌̸; ≠; =◌̸; ) NOT EQUAL TO
+2262;2262;2261 0338;2262;2261 0338; # (≢; ≢; ≡◌̸; ≢; ≡◌̸; ) NOT IDENTICAL TO
+226D;226D;224D 0338;226D;224D 0338; # (≭; ≭; ≍◌̸; ≭; ≍◌̸; ) NOT EQUIVALENT TO
+226E;226E;003C 0338;226E;003C 0338; # (≮; ≮; <◌̸; ≮; <◌̸; ) NOT LESS-THAN
+226F;226F;003E 0338;226F;003E 0338; # (≯; ≯; >◌̸; ≯; >◌̸; ) NOT GREATER-THAN
+2270;2270;2264 0338;2270;2264 0338; # (≰; ≰; ≤◌̸; ≰; ≤◌̸; ) NEITHER LESS-THAN NOR EQUAL TO
+2271;2271;2265 0338;2271;2265 0338; # (≱; ≱; ≥◌̸; ≱; ≥◌̸; ) NEITHER GREATER-THAN NOR EQUAL TO
+2274;2274;2272 0338;2274;2272 0338; # (≴; ≴; ≲◌̸; ≴; ≲◌̸; ) NEITHER LESS-THAN NOR EQUIVALENT TO
+2275;2275;2273 0338;2275;2273 0338; # (≵; ≵; ≳◌̸; ≵; ≳◌̸; ) NEITHER GREATER-THAN NOR EQUIVALENT TO
+2278;2278;2276 0338;2278;2276 0338; # (≸; ≸; ≶◌̸; ≸; ≶◌̸; ) NEITHER LESS-THAN NOR GREATER-THAN
+2279;2279;2277 0338;2279;2277 0338; # (≹; ≹; ≷◌̸; ≹; ≷◌̸; ) NEITHER GREATER-THAN NOR LESS-THAN
+2280;2280;227A 0338;2280;227A 0338; # (⊀; ⊀; ≺◌̸; ⊀; ≺◌̸; ) DOES NOT PRECEDE
+2281;2281;227B 0338;2281;227B 0338; # (⊁; ⊁; ≻◌̸; ⊁; ≻◌̸; ) DOES NOT SUCCEED
+2284;2284;2282 0338;2284;2282 0338; # (⊄; ⊄; ⊂◌̸; ⊄; ⊂◌̸; ) NOT A SUBSET OF
+2285;2285;2283 0338;2285;2283 0338; # (⊅; ⊅; ⊃◌̸; ⊅; ⊃◌̸; ) NOT A SUPERSET OF
+2288;2288;2286 0338;2288;2286 0338; # (⊈; ⊈; ⊆◌̸; ⊈; ⊆◌̸; ) NEITHER A SUBSET OF NOR EQUAL TO
+2289;2289;2287 0338;2289;2287 0338; # (⊉; ⊉; ⊇◌̸; ⊉; ⊇◌̸; ) NEITHER A SUPERSET OF NOR EQUAL TO
+22AC;22AC;22A2 0338;22AC;22A2 0338; # (⊬; ⊬; ⊢◌̸; ⊬; ⊢◌̸; ) DOES NOT PROVE
+22AD;22AD;22A8 0338;22AD;22A8 0338; # (⊭; ⊭; ⊨◌̸; ⊭; ⊨◌̸; ) NOT TRUE
+22AE;22AE;22A9 0338;22AE;22A9 0338; # (⊮; ⊮; ⊩◌̸; ⊮; ⊩◌̸; ) DOES NOT FORCE
+22AF;22AF;22AB 0338;22AF;22AB 0338; # (⊯; ⊯; ⊫◌̸; ⊯; ⊫◌̸; ) NEGATED DOUBLE VERTICAL BAR DOUBLE RIGHT TURNSTILE
+22E0;22E0;227C 0338;22E0;227C 0338; # (⋠; ⋠; ≼◌̸; ⋠; ≼◌̸; ) DOES NOT PRECEDE OR EQUAL
+22E1;22E1;227D 0338;22E1;227D 0338; # (⋡; ⋡; ≽◌̸; ⋡; ≽◌̸; ) DOES NOT SUCCEED OR EQUAL
+22E2;22E2;2291 0338;22E2;2291 0338; # (⋢; ⋢; ⊑◌̸; ⋢; ⊑◌̸; ) NOT SQUARE IMAGE OF OR EQUAL TO
+22E3;22E3;2292 0338;22E3;2292 0338; # (⋣; ⋣; ⊒◌̸; ⋣; ⊒◌̸; ) NOT SQUARE ORIGINAL OF OR EQUAL TO
+22EA;22EA;22B2 0338;22EA;22B2 0338; # (⋪; ⋪; ⊲◌̸; ⋪; ⊲◌̸; ) NOT NORMAL SUBGROUP OF
+22EB;22EB;22B3 0338;22EB;22B3 0338; # (⋫; ⋫; ⊳◌̸; ⋫; ⊳◌̸; ) DOES NOT CONTAIN AS NORMAL SUBGROUP
+22EC;22EC;22B4 0338;22EC;22B4 0338; # (⋬; ⋬; ⊴◌̸; ⋬; ⊴◌̸; ) NOT NORMAL SUBGROUP OF OR EQUAL TO
+22ED;22ED;22B5 0338;22ED;22B5 0338; # (⋭; ⋭; ⊵◌̸; ⋭; ⊵◌̸; ) DOES NOT CONTAIN AS NORMAL SUBGROUP OR EQUAL
+2329;3008;3008;3008;3008; # (〈; 〈; 〈; 〈; 〈; ) LEFT-POINTING ANGLE BRACKET
+232A;3009;3009;3009;3009; # (〉; 〉; 〉; 〉; 〉; ) RIGHT-POINTING ANGLE BRACKET
+2460;2460;2460;0031;0031; # (①; ①; ①; 1; 1; ) CIRCLED DIGIT ONE
+2461;2461;2461;0032;0032; # (②; ②; ②; 2; 2; ) CIRCLED DIGIT TWO
+2462;2462;2462;0033;0033; # (③; ③; ③; 3; 3; ) CIRCLED DIGIT THREE
+2463;2463;2463;0034;0034; # (④; ④; ④; 4; 4; ) CIRCLED DIGIT FOUR
+2464;2464;2464;0035;0035; # (⑤; ⑤; ⑤; 5; 5; ) CIRCLED DIGIT FIVE
+2465;2465;2465;0036;0036; # (⑥; ⑥; ⑥; 6; 6; ) CIRCLED DIGIT SIX
+2466;2466;2466;0037;0037; # (⑦; ⑦; ⑦; 7; 7; ) CIRCLED DIGIT SEVEN
+2467;2467;2467;0038;0038; # (⑧; ⑧; ⑧; 8; 8; ) CIRCLED DIGIT EIGHT
+2468;2468;2468;0039;0039; # (⑨; ⑨; ⑨; 9; 9; ) CIRCLED DIGIT NINE
+2469;2469;2469;0031 0030;0031 0030; # (⑩; ⑩; ⑩; 10; 10; ) CIRCLED NUMBER TEN
+246A;246A;246A;0031 0031;0031 0031; # (⑪; ⑪; ⑪; 11; 11; ) CIRCLED NUMBER ELEVEN
+246B;246B;246B;0031 0032;0031 0032; # (⑫; ⑫; ⑫; 12; 12; ) CIRCLED NUMBER TWELVE
+246C;246C;246C;0031 0033;0031 0033; # (⑬; ⑬; ⑬; 13; 13; ) CIRCLED NUMBER THIRTEEN
+246D;246D;246D;0031 0034;0031 0034; # (⑭; ⑭; ⑭; 14; 14; ) CIRCLED NUMBER FOURTEEN
+246E;246E;246E;0031 0035;0031 0035; # (⑮; ⑮; ⑮; 15; 15; ) CIRCLED NUMBER FIFTEEN
+246F;246F;246F;0031 0036;0031 0036; # (⑯; ⑯; ⑯; 16; 16; ) CIRCLED NUMBER SIXTEEN
+2470;2470;2470;0031 0037;0031 0037; # (⑰; ⑰; ⑰; 17; 17; ) CIRCLED NUMBER SEVENTEEN
+2471;2471;2471;0031 0038;0031 0038; # (⑱; ⑱; ⑱; 18; 18; ) CIRCLED NUMBER EIGHTEEN
+2472;2472;2472;0031 0039;0031 0039; # (⑲; ⑲; ⑲; 19; 19; ) CIRCLED NUMBER NINETEEN
+2473;2473;2473;0032 0030;0032 0030; # (⑳; ⑳; ⑳; 20; 20; ) CIRCLED NUMBER TWENTY
+2474;2474;2474;0028 0031 0029;0028 0031 0029; # (⑴; ⑴; ⑴; (1); (1); ) PARENTHESIZED DIGIT ONE
+2475;2475;2475;0028 0032 0029;0028 0032 0029; # (⑵; ⑵; ⑵; (2); (2); ) PARENTHESIZED DIGIT TWO
+2476;2476;2476;0028 0033 0029;0028 0033 0029; # (⑶; ⑶; ⑶; (3); (3); ) PARENTHESIZED DIGIT THREE
+2477;2477;2477;0028 0034 0029;0028 0034 0029; # (⑷; ⑷; ⑷; (4); (4); ) PARENTHESIZED DIGIT FOUR
+2478;2478;2478;0028 0035 0029;0028 0035 0029; # (⑸; ⑸; ⑸; (5); (5); ) PARENTHESIZED DIGIT FIVE
+2479;2479;2479;0028 0036 0029;0028 0036 0029; # (⑹; ⑹; ⑹; (6); (6); ) PARENTHESIZED DIGIT SIX
+247A;247A;247A;0028 0037 0029;0028 0037 0029; # (⑺; ⑺; ⑺; (7); (7); ) PARENTHESIZED DIGIT SEVEN
+247B;247B;247B;0028 0038 0029;0028 0038 0029; # (⑻; ⑻; ⑻; (8); (8); ) PARENTHESIZED DIGIT EIGHT
+247C;247C;247C;0028 0039 0029;0028 0039 0029; # (⑼; ⑼; ⑼; (9); (9); ) PARENTHESIZED DIGIT NINE
+247D;247D;247D;0028 0031 0030 0029;0028 0031 0030 0029; # (⑽; ⑽; ⑽; (10); (10); ) PARENTHESIZED NUMBER TEN
+247E;247E;247E;0028 0031 0031 0029;0028 0031 0031 0029; # (⑾; ⑾; ⑾; (11); (11); ) PARENTHESIZED NUMBER ELEVEN
+247F;247F;247F;0028 0031 0032 0029;0028 0031 0032 0029; # (⑿; ⑿; ⑿; (12); (12); ) PARENTHESIZED NUMBER TWELVE
+2480;2480;2480;0028 0031 0033 0029;0028 0031 0033 0029; # (⒀; ⒀; ⒀; (13); (13); ) PARENTHESIZED NUMBER THIRTEEN
+2481;2481;2481;0028 0031 0034 0029;0028 0031 0034 0029; # (⒁; ⒁; ⒁; (14); (14); ) PARENTHESIZED NUMBER FOURTEEN
+2482;2482;2482;0028 0031 0035 0029;0028 0031 0035 0029; # (⒂; ⒂; ⒂; (15); (15); ) PARENTHESIZED NUMBER FIFTEEN
+2483;2483;2483;0028 0031 0036 0029;0028 0031 0036 0029; # (⒃; ⒃; ⒃; (16); (16); ) PARENTHESIZED NUMBER SIXTEEN
+2484;2484;2484;0028 0031 0037 0029;0028 0031 0037 0029; # (⒄; ⒄; ⒄; (17); (17); ) PARENTHESIZED NUMBER SEVENTEEN
+2485;2485;2485;0028 0031 0038 0029;0028 0031 0038 0029; # (⒅; ⒅; ⒅; (18); (18); ) PARENTHESIZED NUMBER EIGHTEEN
+2486;2486;2486;0028 0031 0039 0029;0028 0031 0039 0029; # (⒆; ⒆; ⒆; (19); (19); ) PARENTHESIZED NUMBER NINETEEN
+2487;2487;2487;0028 0032 0030 0029;0028 0032 0030 0029; # (⒇; ⒇; ⒇; (20); (20); ) PARENTHESIZED NUMBER TWENTY
+2488;2488;2488;0031 002E;0031 002E; # (⒈; ⒈; ⒈; 1.; 1.; ) DIGIT ONE FULL STOP
+2489;2489;2489;0032 002E;0032 002E; # (⒉; ⒉; ⒉; 2.; 2.; ) DIGIT TWO FULL STOP
+248A;248A;248A;0033 002E;0033 002E; # (⒊; ⒊; ⒊; 3.; 3.; ) DIGIT THREE FULL STOP
+248B;248B;248B;0034 002E;0034 002E; # (⒋; ⒋; ⒋; 4.; 4.; ) DIGIT FOUR FULL STOP
+248C;248C;248C;0035 002E;0035 002E; # (⒌; ⒌; ⒌; 5.; 5.; ) DIGIT FIVE FULL STOP
+248D;248D;248D;0036 002E;0036 002E; # (⒍; ⒍; ⒍; 6.; 6.; ) DIGIT SIX FULL STOP
+248E;248E;248E;0037 002E;0037 002E; # (⒎; ⒎; ⒎; 7.; 7.; ) DIGIT SEVEN FULL STOP
+248F;248F;248F;0038 002E;0038 002E; # (⒏; ⒏; ⒏; 8.; 8.; ) DIGIT EIGHT FULL STOP
+2490;2490;2490;0039 002E;0039 002E; # (⒐; ⒐; ⒐; 9.; 9.; ) DIGIT NINE FULL STOP
+2491;2491;2491;0031 0030 002E;0031 0030 002E; # (⒑; ⒑; ⒑; 10.; 10.; ) NUMBER TEN FULL STOP
+2492;2492;2492;0031 0031 002E;0031 0031 002E; # (⒒; ⒒; ⒒; 11.; 11.; ) NUMBER ELEVEN FULL STOP
+2493;2493;2493;0031 0032 002E;0031 0032 002E; # (⒓; ⒓; ⒓; 12.; 12.; ) NUMBER TWELVE FULL STOP
+2494;2494;2494;0031 0033 002E;0031 0033 002E; # (⒔; ⒔; ⒔; 13.; 13.; ) NUMBER THIRTEEN FULL STOP
+2495;2495;2495;0031 0034 002E;0031 0034 002E; # (⒕; ⒕; ⒕; 14.; 14.; ) NUMBER FOURTEEN FULL STOP
+2496;2496;2496;0031 0035 002E;0031 0035 002E; # (⒖; ⒖; ⒖; 15.; 15.; ) NUMBER FIFTEEN FULL STOP
+2497;2497;2497;0031 0036 002E;0031 0036 002E; # (⒗; ⒗; ⒗; 16.; 16.; ) NUMBER SIXTEEN FULL STOP
+2498;2498;2498;0031 0037 002E;0031 0037 002E; # (⒘; ⒘; ⒘; 17.; 17.; ) NUMBER SEVENTEEN FULL STOP
+2499;2499;2499;0031 0038 002E;0031 0038 002E; # (⒙; ⒙; ⒙; 18.; 18.; ) NUMBER EIGHTEEN FULL STOP
+249A;249A;249A;0031 0039 002E;0031 0039 002E; # (⒚; ⒚; ⒚; 19.; 19.; ) NUMBER NINETEEN FULL STOP
+249B;249B;249B;0032 0030 002E;0032 0030 002E; # (⒛; ⒛; ⒛; 20.; 20.; ) NUMBER TWENTY FULL STOP
+249C;249C;249C;0028 0061 0029;0028 0061 0029; # (⒜; ⒜; ⒜; (a); (a); ) PARENTHESIZED LATIN SMALL LETTER A
+249D;249D;249D;0028 0062 0029;0028 0062 0029; # (⒝; ⒝; ⒝; (b); (b); ) PARENTHESIZED LATIN SMALL LETTER B
+249E;249E;249E;0028 0063 0029;0028 0063 0029; # (⒞; ⒞; ⒞; (c); (c); ) PARENTHESIZED LATIN SMALL LETTER C
+249F;249F;249F;0028 0064 0029;0028 0064 0029; # (⒟; ⒟; ⒟; (d); (d); ) PARENTHESIZED LATIN SMALL LETTER D
+24A0;24A0;24A0;0028 0065 0029;0028 0065 0029; # (⒠; ⒠; ⒠; (e); (e); ) PARENTHESIZED LATIN SMALL LETTER E
+24A1;24A1;24A1;0028 0066 0029;0028 0066 0029; # (⒡; ⒡; ⒡; (f); (f); ) PARENTHESIZED LATIN SMALL LETTER F
+24A2;24A2;24A2;0028 0067 0029;0028 0067 0029; # (⒢; ⒢; ⒢; (g); (g); ) PARENTHESIZED LATIN SMALL LETTER G
+24A3;24A3;24A3;0028 0068 0029;0028 0068 0029; # (⒣; ⒣; ⒣; (h); (h); ) PARENTHESIZED LATIN SMALL LETTER H
+24A4;24A4;24A4;0028 0069 0029;0028 0069 0029; # (⒤; ⒤; ⒤; (i); (i); ) PARENTHESIZED LATIN SMALL LETTER I
+24A5;24A5;24A5;0028 006A 0029;0028 006A 0029; # (⒥; ⒥; ⒥; (j); (j); ) PARENTHESIZED LATIN SMALL LETTER J
+24A6;24A6;24A6;0028 006B 0029;0028 006B 0029; # (⒦; ⒦; ⒦; (k); (k); ) PARENTHESIZED LATIN SMALL LETTER K
+24A7;24A7;24A7;0028 006C 0029;0028 006C 0029; # (⒧; ⒧; ⒧; (l); (l); ) PARENTHESIZED LATIN SMALL LETTER L
+24A8;24A8;24A8;0028 006D 0029;0028 006D 0029; # (⒨; ⒨; ⒨; (m); (m); ) PARENTHESIZED LATIN SMALL LETTER M
+24A9;24A9;24A9;0028 006E 0029;0028 006E 0029; # (⒩; ⒩; ⒩; (n); (n); ) PARENTHESIZED LATIN SMALL LETTER N
+24AA;24AA;24AA;0028 006F 0029;0028 006F 0029; # (⒪; ⒪; ⒪; (o); (o); ) PARENTHESIZED LATIN SMALL LETTER O
+24AB;24AB;24AB;0028 0070 0029;0028 0070 0029; # (⒫; ⒫; ⒫; (p); (p); ) PARENTHESIZED LATIN SMALL LETTER P
+24AC;24AC;24AC;0028 0071 0029;0028 0071 0029; # (⒬; ⒬; ⒬; (q); (q); ) PARENTHESIZED LATIN SMALL LETTER Q
+24AD;24AD;24AD;0028 0072 0029;0028 0072 0029; # (⒭; ⒭; ⒭; (r); (r); ) PARENTHESIZED LATIN SMALL LETTER R
+24AE;24AE;24AE;0028 0073 0029;0028 0073 0029; # (⒮; ⒮; ⒮; (s); (s); ) PARENTHESIZED LATIN SMALL LETTER S
+24AF;24AF;24AF;0028 0074 0029;0028 0074 0029; # (⒯; ⒯; ⒯; (t); (t); ) PARENTHESIZED LATIN SMALL LETTER T
+24B0;24B0;24B0;0028 0075 0029;0028 0075 0029; # (⒰; ⒰; ⒰; (u); (u); ) PARENTHESIZED LATIN SMALL LETTER U
+24B1;24B1;24B1;0028 0076 0029;0028 0076 0029; # (⒱; ⒱; ⒱; (v); (v); ) PARENTHESIZED LATIN SMALL LETTER V
+24B2;24B2;24B2;0028 0077 0029;0028 0077 0029; # (⒲; ⒲; ⒲; (w); (w); ) PARENTHESIZED LATIN SMALL LETTER W
+24B3;24B3;24B3;0028 0078 0029;0028 0078 0029; # (⒳; ⒳; ⒳; (x); (x); ) PARENTHESIZED LATIN SMALL LETTER X
+24B4;24B4;24B4;0028 0079 0029;0028 0079 0029; # (⒴; ⒴; ⒴; (y); (y); ) PARENTHESIZED LATIN SMALL LETTER Y
+24B5;24B5;24B5;0028 007A 0029;0028 007A 0029; # (⒵; ⒵; ⒵; (z); (z); ) PARENTHESIZED LATIN SMALL LETTER Z
+24B6;24B6;24B6;0041;0041; # (Ⓐ; Ⓐ; Ⓐ; A; A; ) CIRCLED LATIN CAPITAL LETTER A
+24B7;24B7;24B7;0042;0042; # (Ⓑ; Ⓑ; Ⓑ; B; B; ) CIRCLED LATIN CAPITAL LETTER B
+24B8;24B8;24B8;0043;0043; # (Ⓒ; Ⓒ; Ⓒ; C; C; ) CIRCLED LATIN CAPITAL LETTER C
+24B9;24B9;24B9;0044;0044; # (Ⓓ; Ⓓ; Ⓓ; D; D; ) CIRCLED LATIN CAPITAL LETTER D
+24BA;24BA;24BA;0045;0045; # (Ⓔ; Ⓔ; Ⓔ; E; E; ) CIRCLED LATIN CAPITAL LETTER E
+24BB;24BB;24BB;0046;0046; # (Ⓕ; Ⓕ; Ⓕ; F; F; ) CIRCLED LATIN CAPITAL LETTER F
+24BC;24BC;24BC;0047;0047; # (Ⓖ; Ⓖ; Ⓖ; G; G; ) CIRCLED LATIN CAPITAL LETTER G
+24BD;24BD;24BD;0048;0048; # (Ⓗ; Ⓗ; Ⓗ; H; H; ) CIRCLED LATIN CAPITAL LETTER H
+24BE;24BE;24BE;0049;0049; # (Ⓘ; Ⓘ; Ⓘ; I; I; ) CIRCLED LATIN CAPITAL LETTER I
+24BF;24BF;24BF;004A;004A; # (Ⓙ; Ⓙ; Ⓙ; J; J; ) CIRCLED LATIN CAPITAL LETTER J
+24C0;24C0;24C0;004B;004B; # (Ⓚ; Ⓚ; Ⓚ; K; K; ) CIRCLED LATIN CAPITAL LETTER K
+24C1;24C1;24C1;004C;004C; # (Ⓛ; Ⓛ; Ⓛ; L; L; ) CIRCLED LATIN CAPITAL LETTER L
+24C2;24C2;24C2;004D;004D; # (Ⓜ; Ⓜ; Ⓜ; M; M; ) CIRCLED LATIN CAPITAL LETTER M
+24C3;24C3;24C3;004E;004E; # (Ⓝ; Ⓝ; Ⓝ; N; N; ) CIRCLED LATIN CAPITAL LETTER N
+24C4;24C4;24C4;004F;004F; # (Ⓞ; Ⓞ; Ⓞ; O; O; ) CIRCLED LATIN CAPITAL LETTER O
+24C5;24C5;24C5;0050;0050; # (Ⓟ; Ⓟ; Ⓟ; P; P; ) CIRCLED LATIN CAPITAL LETTER P
+24C6;24C6;24C6;0051;0051; # (Ⓠ; Ⓠ; Ⓠ; Q; Q; ) CIRCLED LATIN CAPITAL LETTER Q
+24C7;24C7;24C7;0052;0052; # (Ⓡ; Ⓡ; Ⓡ; R; R; ) CIRCLED LATIN CAPITAL LETTER R
+24C8;24C8;24C8;0053;0053; # (Ⓢ; Ⓢ; Ⓢ; S; S; ) CIRCLED LATIN CAPITAL LETTER S
+24C9;24C9;24C9;0054;0054; # (Ⓣ; Ⓣ; Ⓣ; T; T; ) CIRCLED LATIN CAPITAL LETTER T
+24CA;24CA;24CA;0055;0055; # (Ⓤ; Ⓤ; Ⓤ; U; U; ) CIRCLED LATIN CAPITAL LETTER U
+24CB;24CB;24CB;0056;0056; # (Ⓥ; Ⓥ; Ⓥ; V; V; ) CIRCLED LATIN CAPITAL LETTER V
+24CC;24CC;24CC;0057;0057; # (Ⓦ; Ⓦ; Ⓦ; W; W; ) CIRCLED LATIN CAPITAL LETTER W
+24CD;24CD;24CD;0058;0058; # (Ⓧ; Ⓧ; Ⓧ; X; X; ) CIRCLED LATIN CAPITAL LETTER X
+24CE;24CE;24CE;0059;0059; # (Ⓨ; Ⓨ; Ⓨ; Y; Y; ) CIRCLED LATIN CAPITAL LETTER Y
+24CF;24CF;24CF;005A;005A; # (Ⓩ; Ⓩ; Ⓩ; Z; Z; ) CIRCLED LATIN CAPITAL LETTER Z
+24D0;24D0;24D0;0061;0061; # (ⓐ; ⓐ; ⓐ; a; a; ) CIRCLED LATIN SMALL LETTER A
+24D1;24D1;24D1;0062;0062; # (ⓑ; ⓑ; ⓑ; b; b; ) CIRCLED LATIN SMALL LETTER B
+24D2;24D2;24D2;0063;0063; # (ⓒ; ⓒ; ⓒ; c; c; ) CIRCLED LATIN SMALL LETTER C
+24D3;24D3;24D3;0064;0064; # (ⓓ; ⓓ; ⓓ; d; d; ) CIRCLED LATIN SMALL LETTER D
+24D4;24D4;24D4;0065;0065; # (ⓔ; ⓔ; ⓔ; e; e; ) CIRCLED LATIN SMALL LETTER E
+24D5;24D5;24D5;0066;0066; # (ⓕ; ⓕ; ⓕ; f; f; ) CIRCLED LATIN SMALL LETTER F
+24D6;24D6;24D6;0067;0067; # (ⓖ; ⓖ; ⓖ; g; g; ) CIRCLED LATIN SMALL LETTER G
+24D7;24D7;24D7;0068;0068; # (ⓗ; ⓗ; ⓗ; h; h; ) CIRCLED LATIN SMALL LETTER H
+24D8;24D8;24D8;0069;0069; # (ⓘ; ⓘ; ⓘ; i; i; ) CIRCLED LATIN SMALL LETTER I
+24D9;24D9;24D9;006A;006A; # (ⓙ; ⓙ; ⓙ; j; j; ) CIRCLED LATIN SMALL LETTER J
+24DA;24DA;24DA;006B;006B; # (ⓚ; ⓚ; ⓚ; k; k; ) CIRCLED LATIN SMALL LETTER K
+24DB;24DB;24DB;006C;006C; # (ⓛ; ⓛ; ⓛ; l; l; ) CIRCLED LATIN SMALL LETTER L
+24DC;24DC;24DC;006D;006D; # (ⓜ; ⓜ; ⓜ; m; m; ) CIRCLED LATIN SMALL LETTER M
+24DD;24DD;24DD;006E;006E; # (ⓝ; ⓝ; ⓝ; n; n; ) CIRCLED LATIN SMALL LETTER N
+24DE;24DE;24DE;006F;006F; # (ⓞ; ⓞ; ⓞ; o; o; ) CIRCLED LATIN SMALL LETTER O
+24DF;24DF;24DF;0070;0070; # (ⓟ; ⓟ; ⓟ; p; p; ) CIRCLED LATIN SMALL LETTER P
+24E0;24E0;24E0;0071;0071; # (ⓠ; ⓠ; ⓠ; q; q; ) CIRCLED LATIN SMALL LETTER Q
+24E1;24E1;24E1;0072;0072; # (ⓡ; ⓡ; ⓡ; r; r; ) CIRCLED LATIN SMALL LETTER R
+24E2;24E2;24E2;0073;0073; # (ⓢ; ⓢ; ⓢ; s; s; ) CIRCLED LATIN SMALL LETTER S
+24E3;24E3;24E3;0074;0074; # (ⓣ; ⓣ; ⓣ; t; t; ) CIRCLED LATIN SMALL LETTER T
+24E4;24E4;24E4;0075;0075; # (ⓤ; ⓤ; ⓤ; u; u; ) CIRCLED LATIN SMALL LETTER U
+24E5;24E5;24E5;0076;0076; # (ⓥ; ⓥ; ⓥ; v; v; ) CIRCLED LATIN SMALL LETTER V
+24E6;24E6;24E6;0077;0077; # (ⓦ; ⓦ; ⓦ; w; w; ) CIRCLED LATIN SMALL LETTER W
+24E7;24E7;24E7;0078;0078; # (ⓧ; ⓧ; ⓧ; x; x; ) CIRCLED LATIN SMALL LETTER X
+24E8;24E8;24E8;0079;0079; # (ⓨ; ⓨ; ⓨ; y; y; ) CIRCLED LATIN SMALL LETTER Y
+24E9;24E9;24E9;007A;007A; # (ⓩ; ⓩ; ⓩ; z; z; ) CIRCLED LATIN SMALL LETTER Z
+24EA;24EA;24EA;0030;0030; # (⓪; ⓪; ⓪; 0; 0; ) CIRCLED DIGIT ZERO
+2A0C;2A0C;2A0C;222B 222B 222B 222B;222B 222B 222B 222B; # (⨌; ⨌; ⨌; ∫∫∫∫; ∫∫∫∫; ) QUADRUPLE INTEGRAL OPERATOR
+2A74;2A74;2A74;003A 003A 003D;003A 003A 003D; # (⩴; ⩴; ⩴; ::=; ::=; ) DOUBLE COLON EQUAL
+2A75;2A75;2A75;003D 003D;003D 003D; # (⩵; ⩵; ⩵; ==; ==; ) TWO CONSECUTIVE EQUALS SIGNS
+2A76;2A76;2A76;003D 003D 003D;003D 003D 003D; # (⩶; ⩶; ⩶; ===; ===; ) THREE CONSECUTIVE EQUALS SIGNS
+2ADC;2ADD 0338;2ADD 0338;2ADD 0338;2ADD 0338; # (⫝̸; ⫝◌̸; ⫝◌̸; ⫝◌̸; ⫝◌̸; ) FORKING
+2E9F;2E9F;2E9F;6BCD;6BCD; # (⺟; ⺟; ⺟; 母; 母; ) CJK RADICAL MOTHER
+2EF3;2EF3;2EF3;9F9F;9F9F; # (⻳; ⻳; ⻳; 龟; 龟; ) CJK RADICAL C-SIMPLIFIED TURTLE
+2F00;2F00;2F00;4E00;4E00; # (⼀; ⼀; ⼀; 一; 一; ) KANGXI RADICAL ONE
+2F01;2F01;2F01;4E28;4E28; # (⼁; ⼁; ⼁; 丨; 丨; ) KANGXI RADICAL LINE
+2F02;2F02;2F02;4E36;4E36; # (⼂; ⼂; ⼂; 丶; 丶; ) KANGXI RADICAL DOT
+2F03;2F03;2F03;4E3F;4E3F; # (⼃; ⼃; ⼃; 丿; 丿; ) KANGXI RADICAL SLASH
+2F04;2F04;2F04;4E59;4E59; # (⼄; ⼄; ⼄; 乙; 乙; ) KANGXI RADICAL SECOND
+2F05;2F05;2F05;4E85;4E85; # (⼅; ⼅; ⼅; 亅; 亅; ) KANGXI RADICAL HOOK
+2F06;2F06;2F06;4E8C;4E8C; # (⼆; ⼆; ⼆; 二; 二; ) KANGXI RADICAL TWO
+2F07;2F07;2F07;4EA0;4EA0; # (⼇; ⼇; ⼇; 亠; 亠; ) KANGXI RADICAL LID
+2F08;2F08;2F08;4EBA;4EBA; # (⼈; ⼈; ⼈; 人; 人; ) KANGXI RADICAL MAN
+2F09;2F09;2F09;513F;513F; # (⼉; ⼉; ⼉; 儿; 儿; ) KANGXI RADICAL LEGS
+2F0A;2F0A;2F0A;5165;5165; # (⼊; ⼊; ⼊; 入; 入; ) KANGXI RADICAL ENTER
+2F0B;2F0B;2F0B;516B;516B; # (⼋; ⼋; ⼋; 八; 八; ) KANGXI RADICAL EIGHT
+2F0C;2F0C;2F0C;5182;5182; # (⼌; ⼌; ⼌; 冂; 冂; ) KANGXI RADICAL DOWN BOX
+2F0D;2F0D;2F0D;5196;5196; # (⼍; ⼍; ⼍; 冖; 冖; ) KANGXI RADICAL COVER
+2F0E;2F0E;2F0E;51AB;51AB; # (⼎; ⼎; ⼎; 冫; 冫; ) KANGXI RADICAL ICE
+2F0F;2F0F;2F0F;51E0;51E0; # (⼏; ⼏; ⼏; 几; 几; ) KANGXI RADICAL TABLE
+2F10;2F10;2F10;51F5;51F5; # (⼐; ⼐; ⼐; 凵; 凵; ) KANGXI RADICAL OPEN BOX
+2F11;2F11;2F11;5200;5200; # (⼑; ⼑; ⼑; 刀; 刀; ) KANGXI RADICAL KNIFE
+2F12;2F12;2F12;529B;529B; # (⼒; ⼒; ⼒; 力; 力; ) KANGXI RADICAL POWER
+2F13;2F13;2F13;52F9;52F9; # (⼓; ⼓; ⼓; 勹; 勹; ) KANGXI RADICAL WRAP
+2F14;2F14;2F14;5315;5315; # (⼔; ⼔; ⼔; 匕; 匕; ) KANGXI RADICAL SPOON
+2F15;2F15;2F15;531A;531A; # (⼕; ⼕; ⼕; 匚; 匚; ) KANGXI RADICAL RIGHT OPEN BOX
+2F16;2F16;2F16;5338;5338; # (⼖; ⼖; ⼖; 匸; 匸; ) KANGXI RADICAL HIDING ENCLOSURE
+2F17;2F17;2F17;5341;5341; # (⼗; ⼗; ⼗; 十; 十; ) KANGXI RADICAL TEN
+2F18;2F18;2F18;535C;535C; # (⼘; ⼘; ⼘; 卜; 卜; ) KANGXI RADICAL DIVINATION
+2F19;2F19;2F19;5369;5369; # (⼙; ⼙; ⼙; 卩; 卩; ) KANGXI RADICAL SEAL
+2F1A;2F1A;2F1A;5382;5382; # (⼚; ⼚; ⼚; 厂; 厂; ) KANGXI RADICAL CLIFF
+2F1B;2F1B;2F1B;53B6;53B6; # (⼛; ⼛; ⼛; 厶; 厶; ) KANGXI RADICAL PRIVATE
+2F1C;2F1C;2F1C;53C8;53C8; # (⼜; ⼜; ⼜; 又; 又; ) KANGXI RADICAL AGAIN
+2F1D;2F1D;2F1D;53E3;53E3; # (⼝; ⼝; ⼝; 口; 口; ) KANGXI RADICAL MOUTH
+2F1E;2F1E;2F1E;56D7;56D7; # (⼞; ⼞; ⼞; 囗; 囗; ) KANGXI RADICAL ENCLOSURE
+2F1F;2F1F;2F1F;571F;571F; # (⼟; ⼟; ⼟; 土; 土; ) KANGXI RADICAL EARTH
+2F20;2F20;2F20;58EB;58EB; # (⼠; ⼠; ⼠; 士; 士; ) KANGXI RADICAL SCHOLAR
+2F21;2F21;2F21;5902;5902; # (⼡; ⼡; ⼡; 夂; 夂; ) KANGXI RADICAL GO
+2F22;2F22;2F22;590A;590A; # (⼢; ⼢; ⼢; 夊; 夊; ) KANGXI RADICAL GO SLOWLY
+2F23;2F23;2F23;5915;5915; # (⼣; ⼣; ⼣; 夕; 夕; ) KANGXI RADICAL EVENING
+2F24;2F24;2F24;5927;5927; # (⼤; ⼤; ⼤; 大; 大; ) KANGXI RADICAL BIG
+2F25;2F25;2F25;5973;5973; # (⼥; ⼥; ⼥; 女; 女; ) KANGXI RADICAL WOMAN
+2F26;2F26;2F26;5B50;5B50; # (⼦; ⼦; ⼦; 子; 子; ) KANGXI RADICAL CHILD
+2F27;2F27;2F27;5B80;5B80; # (⼧; ⼧; ⼧; 宀; 宀; ) KANGXI RADICAL ROOF
+2F28;2F28;2F28;5BF8;5BF8; # (⼨; ⼨; ⼨; 寸; 寸; ) KANGXI RADICAL INCH
+2F29;2F29;2F29;5C0F;5C0F; # (⼩; ⼩; ⼩; 小; 小; ) KANGXI RADICAL SMALL
+2F2A;2F2A;2F2A;5C22;5C22; # (⼪; ⼪; ⼪; 尢; 尢; ) KANGXI RADICAL LAME
+2F2B;2F2B;2F2B;5C38;5C38; # (⼫; ⼫; ⼫; 尸; 尸; ) KANGXI RADICAL CORPSE
+2F2C;2F2C;2F2C;5C6E;5C6E; # (⼬; ⼬; ⼬; 屮; 屮; ) KANGXI RADICAL SPROUT
+2F2D;2F2D;2F2D;5C71;5C71; # (⼭; ⼭; ⼭; 山; 山; ) KANGXI RADICAL MOUNTAIN
+2F2E;2F2E;2F2E;5DDB;5DDB; # (⼮; ⼮; ⼮; 巛; 巛; ) KANGXI RADICAL RIVER
+2F2F;2F2F;2F2F;5DE5;5DE5; # (⼯; ⼯; ⼯; 工; 工; ) KANGXI RADICAL WORK
+2F30;2F30;2F30;5DF1;5DF1; # (⼰; ⼰; ⼰; 己; 己; ) KANGXI RADICAL ONESELF
+2F31;2F31;2F31;5DFE;5DFE; # (⼱; ⼱; ⼱; 巾; 巾; ) KANGXI RADICAL TURBAN
+2F32;2F32;2F32;5E72;5E72; # (⼲; ⼲; ⼲; 干; 干; ) KANGXI RADICAL DRY
+2F33;2F33;2F33;5E7A;5E7A; # (⼳; ⼳; ⼳; 幺; 幺; ) KANGXI RADICAL SHORT THREAD
+2F34;2F34;2F34;5E7F;5E7F; # (⼴; ⼴; ⼴; 广; 广; ) KANGXI RADICAL DOTTED CLIFF
+2F35;2F35;2F35;5EF4;5EF4; # (⼵; ⼵; ⼵; 廴; 廴; ) KANGXI RADICAL LONG STRIDE
+2F36;2F36;2F36;5EFE;5EFE; # (⼶; ⼶; ⼶; 廾; 廾; ) KANGXI RADICAL TWO HANDS
+2F37;2F37;2F37;5F0B;5F0B; # (⼷; ⼷; ⼷; 弋; 弋; ) KANGXI RADICAL SHOOT
+2F38;2F38;2F38;5F13;5F13; # (⼸; ⼸; ⼸; 弓; 弓; ) KANGXI RADICAL BOW
+2F39;2F39;2F39;5F50;5F50; # (⼹; ⼹; ⼹; 彐; 彐; ) KANGXI RADICAL SNOUT
+2F3A;2F3A;2F3A;5F61;5F61; # (⼺; ⼺; ⼺; 彡; 彡; ) KANGXI RADICAL BRISTLE
+2F3B;2F3B;2F3B;5F73;5F73; # (⼻; ⼻; ⼻; 彳; 彳; ) KANGXI RADICAL STEP
+2F3C;2F3C;2F3C;5FC3;5FC3; # (⼼; ⼼; ⼼; 心; 心; ) KANGXI RADICAL HEART
+2F3D;2F3D;2F3D;6208;6208; # (⼽; ⼽; ⼽; 戈; 戈; ) KANGXI RADICAL HALBERD
+2F3E;2F3E;2F3E;6236;6236; # (⼾; ⼾; ⼾; 戶; 戶; ) KANGXI RADICAL DOOR
+2F3F;2F3F;2F3F;624B;624B; # (⼿; ⼿; ⼿; 手; 手; ) KANGXI RADICAL HAND
+2F40;2F40;2F40;652F;652F; # (⽀; ⽀; ⽀; 支; 支; ) KANGXI RADICAL BRANCH
+2F41;2F41;2F41;6534;6534; # (⽁; ⽁; ⽁; 攴; 攴; ) KANGXI RADICAL RAP
+2F42;2F42;2F42;6587;6587; # (⽂; ⽂; ⽂; 文; 文; ) KANGXI RADICAL SCRIPT
+2F43;2F43;2F43;6597;6597; # (⽃; ⽃; ⽃; 斗; 斗; ) KANGXI RADICAL DIPPER
+2F44;2F44;2F44;65A4;65A4; # (⽄; ⽄; ⽄; 斤; 斤; ) KANGXI RADICAL AXE
+2F45;2F45;2F45;65B9;65B9; # (⽅; ⽅; ⽅; 方; 方; ) KANGXI RADICAL SQUARE
+2F46;2F46;2F46;65E0;65E0; # (⽆; ⽆; ⽆; 无; 无; ) KANGXI RADICAL NOT
+2F47;2F47;2F47;65E5;65E5; # (⽇; ⽇; ⽇; 日; 日; ) KANGXI RADICAL SUN
+2F48;2F48;2F48;66F0;66F0; # (⽈; ⽈; ⽈; 曰; 曰; ) KANGXI RADICAL SAY
+2F49;2F49;2F49;6708;6708; # (⽉; ⽉; ⽉; 月; 月; ) KANGXI RADICAL MOON
+2F4A;2F4A;2F4A;6728;6728; # (⽊; ⽊; ⽊; 木; 木; ) KANGXI RADICAL TREE
+2F4B;2F4B;2F4B;6B20;6B20; # (⽋; ⽋; ⽋; 欠; 欠; ) KANGXI RADICAL LACK
+2F4C;2F4C;2F4C;6B62;6B62; # (⽌; ⽌; ⽌; 止; 止; ) KANGXI RADICAL STOP
+2F4D;2F4D;2F4D;6B79;6B79; # (⽍; ⽍; ⽍; 歹; 歹; ) KANGXI RADICAL DEATH
+2F4E;2F4E;2F4E;6BB3;6BB3; # (⽎; ⽎; ⽎; 殳; 殳; ) KANGXI RADICAL WEAPON
+2F4F;2F4F;2F4F;6BCB;6BCB; # (⽏; ⽏; ⽏; 毋; 毋; ) KANGXI RADICAL DO NOT
+2F50;2F50;2F50;6BD4;6BD4; # (⽐; ⽐; ⽐; 比; 比; ) KANGXI RADICAL COMPARE
+2F51;2F51;2F51;6BDB;6BDB; # (⽑; ⽑; ⽑; 毛; 毛; ) KANGXI RADICAL FUR
+2F52;2F52;2F52;6C0F;6C0F; # (⽒; ⽒; ⽒; 氏; 氏; ) KANGXI RADICAL CLAN
+2F53;2F53;2F53;6C14;6C14; # (⽓; ⽓; ⽓; 气; 气; ) KANGXI RADICAL STEAM
+2F54;2F54;2F54;6C34;6C34; # (⽔; ⽔; ⽔; 水; 水; ) KANGXI RADICAL WATER
+2F55;2F55;2F55;706B;706B; # (⽕; ⽕; ⽕; 火; 火; ) KANGXI RADICAL FIRE
+2F56;2F56;2F56;722A;722A; # (⽖; ⽖; ⽖; 爪; 爪; ) KANGXI RADICAL CLAW
+2F57;2F57;2F57;7236;7236; # (⽗; ⽗; ⽗; 父; 父; ) KANGXI RADICAL FATHER
+2F58;2F58;2F58;723B;723B; # (⽘; ⽘; ⽘; 爻; 爻; ) KANGXI RADICAL DOUBLE X
+2F59;2F59;2F59;723F;723F; # (⽙; ⽙; ⽙; 爿; 爿; ) KANGXI RADICAL HALF TREE TRUNK
+2F5A;2F5A;2F5A;7247;7247; # (⽚; ⽚; ⽚; 片; 片; ) KANGXI RADICAL SLICE
+2F5B;2F5B;2F5B;7259;7259; # (⽛; ⽛; ⽛; 牙; 牙; ) KANGXI RADICAL FANG
+2F5C;2F5C;2F5C;725B;725B; # (⽜; ⽜; ⽜; 牛; 牛; ) KANGXI RADICAL COW
+2F5D;2F5D;2F5D;72AC;72AC; # (⽝; ⽝; ⽝; 犬; 犬; ) KANGXI RADICAL DOG
+2F5E;2F5E;2F5E;7384;7384; # (⽞; ⽞; ⽞; 玄; 玄; ) KANGXI RADICAL PROFOUND
+2F5F;2F5F;2F5F;7389;7389; # (⽟; ⽟; ⽟; 玉; 玉; ) KANGXI RADICAL JADE
+2F60;2F60;2F60;74DC;74DC; # (⽠; ⽠; ⽠; 瓜; 瓜; ) KANGXI RADICAL MELON
+2F61;2F61;2F61;74E6;74E6; # (⽡; ⽡; ⽡; 瓦; 瓦; ) KANGXI RADICAL TILE
+2F62;2F62;2F62;7518;7518; # (⽢; ⽢; ⽢; 甘; 甘; ) KANGXI RADICAL SWEET
+2F63;2F63;2F63;751F;751F; # (⽣; ⽣; ⽣; 生; 生; ) KANGXI RADICAL LIFE
+2F64;2F64;2F64;7528;7528; # (⽤; ⽤; ⽤; 用; 用; ) KANGXI RADICAL USE
+2F65;2F65;2F65;7530;7530; # (⽥; ⽥; ⽥; 田; 田; ) KANGXI RADICAL FIELD
+2F66;2F66;2F66;758B;758B; # (⽦; ⽦; ⽦; 疋; 疋; ) KANGXI RADICAL BOLT OF CLOTH
+2F67;2F67;2F67;7592;7592; # (⽧; ⽧; ⽧; 疒; 疒; ) KANGXI RADICAL SICKNESS
+2F68;2F68;2F68;7676;7676; # (⽨; ⽨; ⽨; 癶; 癶; ) KANGXI RADICAL DOTTED TENT
+2F69;2F69;2F69;767D;767D; # (⽩; ⽩; ⽩; 白; 白; ) KANGXI RADICAL WHITE
+2F6A;2F6A;2F6A;76AE;76AE; # (⽪; ⽪; ⽪; 皮; 皮; ) KANGXI RADICAL SKIN
+2F6B;2F6B;2F6B;76BF;76BF; # (⽫; ⽫; ⽫; 皿; 皿; ) KANGXI RADICAL DISH
+2F6C;2F6C;2F6C;76EE;76EE; # (⽬; ⽬; ⽬; 目; 目; ) KANGXI RADICAL EYE
+2F6D;2F6D;2F6D;77DB;77DB; # (⽭; ⽭; ⽭; 矛; 矛; ) KANGXI RADICAL SPEAR
+2F6E;2F6E;2F6E;77E2;77E2; # (⽮; ⽮; ⽮; 矢; 矢; ) KANGXI RADICAL ARROW
+2F6F;2F6F;2F6F;77F3;77F3; # (⽯; ⽯; ⽯; 石; 石; ) KANGXI RADICAL STONE
+2F70;2F70;2F70;793A;793A; # (⽰; ⽰; ⽰; 示; 示; ) KANGXI RADICAL SPIRIT
+2F71;2F71;2F71;79B8;79B8; # (⽱; ⽱; ⽱; 禸; 禸; ) KANGXI RADICAL TRACK
+2F72;2F72;2F72;79BE;79BE; # (⽲; ⽲; ⽲; 禾; 禾; ) KANGXI RADICAL GRAIN
+2F73;2F73;2F73;7A74;7A74; # (⽳; ⽳; ⽳; 穴; 穴; ) KANGXI RADICAL CAVE
+2F74;2F74;2F74;7ACB;7ACB; # (⽴; ⽴; ⽴; 立; 立; ) KANGXI RADICAL STAND
+2F75;2F75;2F75;7AF9;7AF9; # (⽵; ⽵; ⽵; 竹; 竹; ) KANGXI RADICAL BAMBOO
+2F76;2F76;2F76;7C73;7C73; # (⽶; ⽶; ⽶; 米; 米; ) KANGXI RADICAL RICE
+2F77;2F77;2F77;7CF8;7CF8; # (⽷; ⽷; ⽷; 糸; 糸; ) KANGXI RADICAL SILK
+2F78;2F78;2F78;7F36;7F36; # (⽸; ⽸; ⽸; 缶; 缶; ) KANGXI RADICAL JAR
+2F79;2F79;2F79;7F51;7F51; # (⽹; ⽹; ⽹; 网; 网; ) KANGXI RADICAL NET
+2F7A;2F7A;2F7A;7F8A;7F8A; # (⽺; ⽺; ⽺; 羊; 羊; ) KANGXI RADICAL SHEEP
+2F7B;2F7B;2F7B;7FBD;7FBD; # (⽻; ⽻; ⽻; 羽; 羽; ) KANGXI RADICAL FEATHER
+2F7C;2F7C;2F7C;8001;8001; # (⽼; ⽼; ⽼; 老; 老; ) KANGXI RADICAL OLD
+2F7D;2F7D;2F7D;800C;800C; # (⽽; ⽽; ⽽; 而; 而; ) KANGXI RADICAL AND
+2F7E;2F7E;2F7E;8012;8012; # (⽾; ⽾; ⽾; 耒; 耒; ) KANGXI RADICAL PLOW
+2F7F;2F7F;2F7F;8033;8033; # (⽿; ⽿; ⽿; 耳; 耳; ) KANGXI RADICAL EAR
+2F80;2F80;2F80;807F;807F; # (⾀; ⾀; ⾀; 聿; 聿; ) KANGXI RADICAL BRUSH
+2F81;2F81;2F81;8089;8089; # (⾁; ⾁; ⾁; 肉; 肉; ) KANGXI RADICAL MEAT
+2F82;2F82;2F82;81E3;81E3; # (⾂; ⾂; ⾂; 臣; 臣; ) KANGXI RADICAL MINISTER
+2F83;2F83;2F83;81EA;81EA; # (⾃; ⾃; ⾃; 自; 自; ) KANGXI RADICAL SELF
+2F84;2F84;2F84;81F3;81F3; # (⾄; ⾄; ⾄; 至; 至; ) KANGXI RADICAL ARRIVE
+2F85;2F85;2F85;81FC;81FC; # (⾅; ⾅; ⾅; 臼; 臼; ) KANGXI RADICAL MORTAR
+2F86;2F86;2F86;820C;820C; # (⾆; ⾆; ⾆; 舌; 舌; ) KANGXI RADICAL TONGUE
+2F87;2F87;2F87;821B;821B; # (⾇; ⾇; ⾇; 舛; 舛; ) KANGXI RADICAL OPPOSE
+2F88;2F88;2F88;821F;821F; # (⾈; ⾈; ⾈; 舟; 舟; ) KANGXI RADICAL BOAT
+2F89;2F89;2F89;826E;826E; # (⾉; ⾉; ⾉; 艮; 艮; ) KANGXI RADICAL STOPPING
+2F8A;2F8A;2F8A;8272;8272; # (⾊; ⾊; ⾊; 色; 色; ) KANGXI RADICAL COLOR
+2F8B;2F8B;2F8B;8278;8278; # (⾋; ⾋; ⾋; 艸; 艸; ) KANGXI RADICAL GRASS
+2F8C;2F8C;2F8C;864D;864D; # (⾌; ⾌; ⾌; 虍; 虍; ) KANGXI RADICAL TIGER
+2F8D;2F8D;2F8D;866B;866B; # (⾍; ⾍; ⾍; 虫; 虫; ) KANGXI RADICAL INSECT
+2F8E;2F8E;2F8E;8840;8840; # (⾎; ⾎; ⾎; 血; 血; ) KANGXI RADICAL BLOOD
+2F8F;2F8F;2F8F;884C;884C; # (⾏; ⾏; ⾏; 行; 行; ) KANGXI RADICAL WALK ENCLOSURE
+2F90;2F90;2F90;8863;8863; # (⾐; ⾐; ⾐; 衣; 衣; ) KANGXI RADICAL CLOTHES
+2F91;2F91;2F91;897E;897E; # (⾑; ⾑; ⾑; 襾; 襾; ) KANGXI RADICAL WEST
+2F92;2F92;2F92;898B;898B; # (⾒; ⾒; ⾒; 見; 見; ) KANGXI RADICAL SEE
+2F93;2F93;2F93;89D2;89D2; # (⾓; ⾓; ⾓; 角; 角; ) KANGXI RADICAL HORN
+2F94;2F94;2F94;8A00;8A00; # (⾔; ⾔; ⾔; 言; 言; ) KANGXI RADICAL SPEECH
+2F95;2F95;2F95;8C37;8C37; # (⾕; ⾕; ⾕; 谷; 谷; ) KANGXI RADICAL VALLEY
+2F96;2F96;2F96;8C46;8C46; # (⾖; ⾖; ⾖; 豆; 豆; ) KANGXI RADICAL BEAN
+2F97;2F97;2F97;8C55;8C55; # (⾗; ⾗; ⾗; 豕; 豕; ) KANGXI RADICAL PIG
+2F98;2F98;2F98;8C78;8C78; # (⾘; ⾘; ⾘; 豸; 豸; ) KANGXI RADICAL BADGER
+2F99;2F99;2F99;8C9D;8C9D; # (⾙; ⾙; ⾙; 貝; 貝; ) KANGXI RADICAL SHELL
+2F9A;2F9A;2F9A;8D64;8D64; # (⾚; ⾚; ⾚; 赤; 赤; ) KANGXI RADICAL RED
+2F9B;2F9B;2F9B;8D70;8D70; # (⾛; ⾛; ⾛; 走; 走; ) KANGXI RADICAL RUN
+2F9C;2F9C;2F9C;8DB3;8DB3; # (⾜; ⾜; ⾜; 足; 足; ) KANGXI RADICAL FOOT
+2F9D;2F9D;2F9D;8EAB;8EAB; # (⾝; ⾝; ⾝; 身; 身; ) KANGXI RADICAL BODY
+2F9E;2F9E;2F9E;8ECA;8ECA; # (⾞; ⾞; ⾞; 車; 車; ) KANGXI RADICAL CART
+2F9F;2F9F;2F9F;8F9B;8F9B; # (⾟; ⾟; ⾟; 辛; 辛; ) KANGXI RADICAL BITTER
+2FA0;2FA0;2FA0;8FB0;8FB0; # (⾠; ⾠; ⾠; 辰; 辰; ) KANGXI RADICAL MORNING
+2FA1;2FA1;2FA1;8FB5;8FB5; # (⾡; ⾡; ⾡; 辵; 辵; ) KANGXI RADICAL WALK
+2FA2;2FA2;2FA2;9091;9091; # (⾢; ⾢; ⾢; 邑; 邑; ) KANGXI RADICAL CITY
+2FA3;2FA3;2FA3;9149;9149; # (⾣; ⾣; ⾣; 酉; 酉; ) KANGXI RADICAL WINE
+2FA4;2FA4;2FA4;91C6;91C6; # (⾤; ⾤; ⾤; 釆; 釆; ) KANGXI RADICAL DISTINGUISH
+2FA5;2FA5;2FA5;91CC;91CC; # (⾥; ⾥; ⾥; 里; 里; ) KANGXI RADICAL VILLAGE
+2FA6;2FA6;2FA6;91D1;91D1; # (⾦; ⾦; ⾦; 金; 金; ) KANGXI RADICAL GOLD
+2FA7;2FA7;2FA7;9577;9577; # (⾧; ⾧; ⾧; 長; 長; ) KANGXI RADICAL LONG
+2FA8;2FA8;2FA8;9580;9580; # (⾨; ⾨; ⾨; 門; 門; ) KANGXI RADICAL GATE
+2FA9;2FA9;2FA9;961C;961C; # (⾩; ⾩; ⾩; 阜; 阜; ) KANGXI RADICAL MOUND
+2FAA;2FAA;2FAA;96B6;96B6; # (⾪; ⾪; ⾪; 隶; 隶; ) KANGXI RADICAL SLAVE
+2FAB;2FAB;2FAB;96B9;96B9; # (⾫; ⾫; ⾫; 隹; 隹; ) KANGXI RADICAL SHORT TAILED BIRD
+2FAC;2FAC;2FAC;96E8;96E8; # (⾬; ⾬; ⾬; 雨; 雨; ) KANGXI RADICAL RAIN
+2FAD;2FAD;2FAD;9751;9751; # (⾭; ⾭; ⾭; 靑; 靑; ) KANGXI RADICAL BLUE
+2FAE;2FAE;2FAE;975E;975E; # (⾮; ⾮; ⾮; 非; 非; ) KANGXI RADICAL WRONG
+2FAF;2FAF;2FAF;9762;9762; # (⾯; ⾯; ⾯; 面; 面; ) KANGXI RADICAL FACE
+2FB0;2FB0;2FB0;9769;9769; # (⾰; ⾰; ⾰; 革; 革; ) KANGXI RADICAL LEATHER
+2FB1;2FB1;2FB1;97CB;97CB; # (⾱; ⾱; ⾱; 韋; 韋; ) KANGXI RADICAL TANNED LEATHER
+2FB2;2FB2;2FB2;97ED;97ED; # (⾲; ⾲; ⾲; 韭; 韭; ) KANGXI RADICAL LEEK
+2FB3;2FB3;2FB3;97F3;97F3; # (⾳; ⾳; ⾳; 音; 音; ) KANGXI RADICAL SOUND
+2FB4;2FB4;2FB4;9801;9801; # (⾴; ⾴; ⾴; 頁; 頁; ) KANGXI RADICAL LEAF
+2FB5;2FB5;2FB5;98A8;98A8; # (⾵; ⾵; ⾵; 風; 風; ) KANGXI RADICAL WIND
+2FB6;2FB6;2FB6;98DB;98DB; # (⾶; ⾶; ⾶; 飛; 飛; ) KANGXI RADICAL FLY
+2FB7;2FB7;2FB7;98DF;98DF; # (⾷; ⾷; ⾷; 食; 食; ) KANGXI RADICAL EAT
+2FB8;2FB8;2FB8;9996;9996; # (⾸; ⾸; ⾸; 首; 首; ) KANGXI RADICAL HEAD
+2FB9;2FB9;2FB9;9999;9999; # (⾹; ⾹; ⾹; 香; 香; ) KANGXI RADICAL FRAGRANT
+2FBA;2FBA;2FBA;99AC;99AC; # (⾺; ⾺; ⾺; 馬; 馬; ) KANGXI RADICAL HORSE
+2FBB;2FBB;2FBB;9AA8;9AA8; # (⾻; ⾻; ⾻; 骨; 骨; ) KANGXI RADICAL BONE
+2FBC;2FBC;2FBC;9AD8;9AD8; # (⾼; ⾼; ⾼; 高; 高; ) KANGXI RADICAL TALL
+2FBD;2FBD;2FBD;9ADF;9ADF; # (⾽; ⾽; ⾽; 髟; 髟; ) KANGXI RADICAL HAIR
+2FBE;2FBE;2FBE;9B25;9B25; # (⾾; ⾾; ⾾; 鬥; 鬥; ) KANGXI RADICAL FIGHT
+2FBF;2FBF;2FBF;9B2F;9B2F; # (⾿; ⾿; ⾿; 鬯; 鬯; ) KANGXI RADICAL SACRIFICIAL WINE
+2FC0;2FC0;2FC0;9B32;9B32; # (⿀; ⿀; ⿀; 鬲; 鬲; ) KANGXI RADICAL CAULDRON
+2FC1;2FC1;2FC1;9B3C;9B3C; # (⿁; ⿁; ⿁; 鬼; 鬼; ) KANGXI RADICAL GHOST
+2FC2;2FC2;2FC2;9B5A;9B5A; # (⿂; ⿂; ⿂; 魚; 魚; ) KANGXI RADICAL FISH
+2FC3;2FC3;2FC3;9CE5;9CE5; # (⿃; ⿃; ⿃; 鳥; 鳥; ) KANGXI RADICAL BIRD
+2FC4;2FC4;2FC4;9E75;9E75; # (⿄; ⿄; ⿄; 鹵; 鹵; ) KANGXI RADICAL SALT
+2FC5;2FC5;2FC5;9E7F;9E7F; # (⿅; ⿅; ⿅; 鹿; 鹿; ) KANGXI RADICAL DEER
+2FC6;2FC6;2FC6;9EA5;9EA5; # (⿆; ⿆; ⿆; 麥; 麥; ) KANGXI RADICAL WHEAT
+2FC7;2FC7;2FC7;9EBB;9EBB; # (⿇; ⿇; ⿇; 麻; 麻; ) KANGXI RADICAL HEMP
+2FC8;2FC8;2FC8;9EC3;9EC3; # (⿈; ⿈; ⿈; 黃; 黃; ) KANGXI RADICAL YELLOW
+2FC9;2FC9;2FC9;9ECD;9ECD; # (⿉; ⿉; ⿉; 黍; 黍; ) KANGXI RADICAL MILLET
+2FCA;2FCA;2FCA;9ED1;9ED1; # (⿊; ⿊; ⿊; 黑; 黑; ) KANGXI RADICAL BLACK
+2FCB;2FCB;2FCB;9EF9;9EF9; # (⿋; ⿋; ⿋; 黹; 黹; ) KANGXI RADICAL EMBROIDERY
+2FCC;2FCC;2FCC;9EFD;9EFD; # (⿌; ⿌; ⿌; 黽; 黽; ) KANGXI RADICAL FROG
+2FCD;2FCD;2FCD;9F0E;9F0E; # (⿍; ⿍; ⿍; 鼎; 鼎; ) KANGXI RADICAL TRIPOD
+2FCE;2FCE;2FCE;9F13;9F13; # (⿎; ⿎; ⿎; 鼓; 鼓; ) KANGXI RADICAL DRUM
+2FCF;2FCF;2FCF;9F20;9F20; # (⿏; ⿏; ⿏; 鼠; 鼠; ) KANGXI RADICAL RAT
+2FD0;2FD0;2FD0;9F3B;9F3B; # (⿐; ⿐; ⿐; 鼻; 鼻; ) KANGXI RADICAL NOSE
+2FD1;2FD1;2FD1;9F4A;9F4A; # (⿑; ⿑; ⿑; 齊; 齊; ) KANGXI RADICAL EVEN
+2FD2;2FD2;2FD2;9F52;9F52; # (⿒; ⿒; ⿒; 齒; 齒; ) KANGXI RADICAL TOOTH
+2FD3;2FD3;2FD3;9F8D;9F8D; # (⿓; ⿓; ⿓; 龍; 龍; ) KANGXI RADICAL DRAGON
+2FD4;2FD4;2FD4;9F9C;9F9C; # (⿔; ⿔; ⿔; 龜; 龜; ) KANGXI RADICAL TURTLE
+2FD5;2FD5;2FD5;9FA0;9FA0; # (⿕; ⿕; ⿕; 龠; 龠; ) KANGXI RADICAL FLUTE
+3000;3000;3000;0020;0020; # ( ;  ;  ; ; ; ) IDEOGRAPHIC SPACE
+3036;3036;3036;3012;3012; # (〶; 〶; 〶; 〒; 〒; ) CIRCLED POSTAL MARK
+3038;3038;3038;5341;5341; # (〸; 〸; 〸; 十; 十; ) HANGZHOU NUMERAL TEN
+3039;3039;3039;5344;5344; # (〹; 〹; 〹; 卄; 卄; ) HANGZHOU NUMERAL TWENTY
+303A;303A;303A;5345;5345; # (〺; 〺; 〺; 卅; 卅; ) HANGZHOU NUMERAL THIRTY
+304C;304C;304B 3099;304C;304B 3099; # (が; が; か◌゙; が; か◌゙; ) HIRAGANA LETTER GA
+304E;304E;304D 3099;304E;304D 3099; # (ぎ; ぎ; き◌゙; ぎ; き◌゙; ) HIRAGANA LETTER GI
+3050;3050;304F 3099;3050;304F 3099; # (ぐ; ぐ; く◌゙; ぐ; く◌゙; ) HIRAGANA LETTER GU
+3052;3052;3051 3099;3052;3051 3099; # (げ; げ; け◌゙; げ; け◌゙; ) HIRAGANA LETTER GE
+3054;3054;3053 3099;3054;3053 3099; # (ご; ご; こ◌゙; ご; こ◌゙; ) HIRAGANA LETTER GO
+3056;3056;3055 3099;3056;3055 3099; # (ざ; ざ; さ◌゙; ざ; さ◌゙; ) HIRAGANA LETTER ZA
+3058;3058;3057 3099;3058;3057 3099; # (じ; じ; し◌゙; じ; し◌゙; ) HIRAGANA LETTER ZI
+305A;305A;3059 3099;305A;3059 3099; # (ず; ず; す◌゙; ず; す◌゙; ) HIRAGANA LETTER ZU
+305C;305C;305B 3099;305C;305B 3099; # (ぜ; ぜ; せ◌゙; ぜ; せ◌゙; ) HIRAGANA LETTER ZE
+305E;305E;305D 3099;305E;305D 3099; # (ぞ; ぞ; そ◌゙; ぞ; そ◌゙; ) HIRAGANA LETTER ZO
+3060;3060;305F 3099;3060;305F 3099; # (だ; だ; た◌゙; だ; た◌゙; ) HIRAGANA LETTER DA
+3062;3062;3061 3099;3062;3061 3099; # (ぢ; ぢ; ち◌゙; ぢ; ち◌゙; ) HIRAGANA LETTER DI
+3065;3065;3064 3099;3065;3064 3099; # (づ; づ; つ◌゙; づ; つ◌゙; ) HIRAGANA LETTER DU
+3067;3067;3066 3099;3067;3066 3099; # (で; で; て◌゙; で; て◌゙; ) HIRAGANA LETTER DE
+3069;3069;3068 3099;3069;3068 3099; # (ど; ど; と◌゙; ど; と◌゙; ) HIRAGANA LETTER DO
+3070;3070;306F 3099;3070;306F 3099; # (ば; ば; は◌゙; ば; は◌゙; ) HIRAGANA LETTER BA
+3071;3071;306F 309A;3071;306F 309A; # (ぱ; ぱ; は◌゚; ぱ; は◌゚; ) HIRAGANA LETTER PA
+3073;3073;3072 3099;3073;3072 3099; # (び; び; ひ◌゙; び; ひ◌゙; ) HIRAGANA LETTER BI
+3074;3074;3072 309A;3074;3072 309A; # (ぴ; ぴ; ひ◌゚; ぴ; ひ◌゚; ) HIRAGANA LETTER PI
+3076;3076;3075 3099;3076;3075 3099; # (ぶ; ぶ; ふ◌゙; ぶ; ふ◌゙; ) HIRAGANA LETTER BU
+3077;3077;3075 309A;3077;3075 309A; # (ぷ; ぷ; ふ◌゚; ぷ; ふ◌゚; ) HIRAGANA LETTER PU
+3079;3079;3078 3099;3079;3078 3099; # (べ; べ; へ◌゙; べ; へ◌゙; ) HIRAGANA LETTER BE
+307A;307A;3078 309A;307A;3078 309A; # (ぺ; ぺ; へ◌゚; ぺ; へ◌゚; ) HIRAGANA LETTER PE
+307C;307C;307B 3099;307C;307B 3099; # (ぼ; ぼ; ほ◌゙; ぼ; ほ◌゙; ) HIRAGANA LETTER BO
+307D;307D;307B 309A;307D;307B 309A; # (ぽ; ぽ; ほ◌゚; ぽ; ほ◌゚; ) HIRAGANA LETTER PO
+3094;3094;3046 3099;3094;3046 3099; # (ゔ; ゔ; う◌゙; ゔ; う◌゙; ) HIRAGANA LETTER VU
+309B;309B;309B;0020 3099;0020 3099; # (゛; ゛; ゛; ◌゙; ◌゙; ) KATAKANA-HIRAGANA VOICED SOUND MARK
+309C;309C;309C;0020 309A;0020 309A; # (゜; ゜; ゜; ◌゚; ◌゚; ) KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
+309E;309E;309D 3099;309E;309D 3099; # (ゞ; ゞ; ゝ◌゙; ゞ; ゝ◌゙; ) HIRAGANA VOICED ITERATION MARK
+309F;309F;309F;3088 308A;3088 308A; # (ゟ; ゟ; ゟ; より; より; ) HIRAGANA DIGRAPH YORI
+30AC;30AC;30AB 3099;30AC;30AB 3099; # (ガ; ガ; カ◌゙; ガ; カ◌゙; ) KATAKANA LETTER GA
+30AE;30AE;30AD 3099;30AE;30AD 3099; # (ギ; ギ; キ◌゙; ギ; キ◌゙; ) KATAKANA LETTER GI
+30B0;30B0;30AF 3099;30B0;30AF 3099; # (グ; グ; ク◌゙; グ; ク◌゙; ) KATAKANA LETTER GU
+30B2;30B2;30B1 3099;30B2;30B1 3099; # (ゲ; ゲ; ケ◌゙; ゲ; ケ◌゙; ) KATAKANA LETTER GE
+30B4;30B4;30B3 3099;30B4;30B3 3099; # (ゴ; ゴ; コ◌゙; ゴ; コ◌゙; ) KATAKANA LETTER GO
+30B6;30B6;30B5 3099;30B6;30B5 3099; # (ザ; ザ; サ◌゙; ザ; サ◌゙; ) KATAKANA LETTER ZA
+30B8;30B8;30B7 3099;30B8;30B7 3099; # (ジ; ジ; シ◌゙; ジ; シ◌゙; ) KATAKANA LETTER ZI
+30BA;30BA;30B9 3099;30BA;30B9 3099; # (ズ; ズ; ス◌゙; ズ; ス◌゙; ) KATAKANA LETTER ZU
+30BC;30BC;30BB 3099;30BC;30BB 3099; # (ゼ; ゼ; セ◌゙; ゼ; セ◌゙; ) KATAKANA LETTER ZE
+30BE;30BE;30BD 3099;30BE;30BD 3099; # (ゾ; ゾ; ソ◌゙; ゾ; ソ◌゙; ) KATAKANA LETTER ZO
+30C0;30C0;30BF 3099;30C0;30BF 3099; # (ダ; ダ; タ◌゙; ダ; タ◌゙; ) KATAKANA LETTER DA
+30C2;30C2;30C1 3099;30C2;30C1 3099; # (ヂ; ヂ; チ◌゙; ヂ; チ◌゙; ) KATAKANA LETTER DI
+30C5;30C5;30C4 3099;30C5;30C4 3099; # (ヅ; ヅ; ツ◌゙; ヅ; ツ◌゙; ) KATAKANA LETTER DU
+30C7;30C7;30C6 3099;30C7;30C6 3099; # (デ; デ; テ◌゙; デ; テ◌゙; ) KATAKANA LETTER DE
+30C9;30C9;30C8 3099;30C9;30C8 3099; # (ド; ド; ト◌゙; ド; ト◌゙; ) KATAKANA LETTER DO
+30D0;30D0;30CF 3099;30D0;30CF 3099; # (バ; バ; ハ◌゙; バ; ハ◌゙; ) KATAKANA LETTER BA
+30D1;30D1;30CF 309A;30D1;30CF 309A; # (パ; パ; ハ◌゚; パ; ハ◌゚; ) KATAKANA LETTER PA
+30D3;30D3;30D2 3099;30D3;30D2 3099; # (ビ; ビ; ヒ◌゙; ビ; ヒ◌゙; ) KATAKANA LETTER BI
+30D4;30D4;30D2 309A;30D4;30D2 309A; # (ピ; ピ; ヒ◌゚; ピ; ヒ◌゚; ) KATAKANA LETTER PI
+30D6;30D6;30D5 3099;30D6;30D5 3099; # (ブ; ブ; フ◌゙; ブ; フ◌゙; ) KATAKANA LETTER BU
+30D7;30D7;30D5 309A;30D7;30D5 309A; # (プ; プ; フ◌゚; プ; フ◌゚; ) KATAKANA LETTER PU
+30D9;30D9;30D8 3099;30D9;30D8 3099; # (ベ; ベ; ヘ◌゙; ベ; ヘ◌゙; ) KATAKANA LETTER BE
+30DA;30DA;30D8 309A;30DA;30D8 309A; # (ペ; ペ; ヘ◌゚; ペ; ヘ◌゚; ) KATAKANA LETTER PE
+30DC;30DC;30DB 3099;30DC;30DB 3099; # (ボ; ボ; ホ◌゙; ボ; ホ◌゙; ) KATAKANA LETTER BO
+30DD;30DD;30DB 309A;30DD;30DB 309A; # (ポ; ポ; ホ◌゚; ポ; ホ◌゚; ) KATAKANA LETTER PO
+30F4;30F4;30A6 3099;30F4;30A6 3099; # (ヴ; ヴ; ウ◌゙; ヴ; ウ◌゙; ) KATAKANA LETTER VU
+30F7;30F7;30EF 3099;30F7;30EF 3099; # (ヷ; ヷ; ワ◌゙; ヷ; ワ◌゙; ) KATAKANA LETTER VA
+30F8;30F8;30F0 3099;30F8;30F0 3099; # (ヸ; ヸ; ヰ◌゙; ヸ; ヰ◌゙; ) KATAKANA LETTER VI
+30F9;30F9;30F1 3099;30F9;30F1 3099; # (ヹ; ヹ; ヱ◌゙; ヹ; ヱ◌゙; ) KATAKANA LETTER VE
+30FA;30FA;30F2 3099;30FA;30F2 3099; # (ヺ; ヺ; ヲ◌゙; ヺ; ヲ◌゙; ) KATAKANA LETTER VO
+30FE;30FE;30FD 3099;30FE;30FD 3099; # (ヾ; ヾ; ヽ◌゙; ヾ; ヽ◌゙; ) KATAKANA VOICED ITERATION MARK
+30FF;30FF;30FF;30B3 30C8;30B3 30C8; # (ヿ; ヿ; ヿ; コト; コト; ) KATAKANA DIGRAPH KOTO
+3131;3131;3131;1100;1100; # (ㄱ; ㄱ; ㄱ; ᄀ; ᄀ; ) HANGUL LETTER KIYEOK
+3132;3132;3132;1101;1101; # (ㄲ; ㄲ; ㄲ; ᄁ; ᄁ; ) HANGUL LETTER SSANGKIYEOK
+3133;3133;3133;11AA;11AA; # (ㄳ; ㄳ; ㄳ; ᆪ; ᆪ; ) HANGUL LETTER KIYEOK-SIOS
+3134;3134;3134;1102;1102; # (ㄴ; ㄴ; ㄴ; ᄂ; ᄂ; ) HANGUL LETTER NIEUN
+3135;3135;3135;11AC;11AC; # (ㄵ; ㄵ; ㄵ; ᆬ; ᆬ; ) HANGUL LETTER NIEUN-CIEUC
+3136;3136;3136;11AD;11AD; # (ㄶ; ㄶ; ㄶ; ᆭ; ᆭ; ) HANGUL LETTER NIEUN-HIEUH
+3137;3137;3137;1103;1103; # (ㄷ; ㄷ; ㄷ; ᄃ; ᄃ; ) HANGUL LETTER TIKEUT
+3138;3138;3138;1104;1104; # (ㄸ; ㄸ; ㄸ; ᄄ; ᄄ; ) HANGUL LETTER SSANGTIKEUT
+3139;3139;3139;1105;1105; # (ㄹ; ㄹ; ㄹ; ᄅ; ᄅ; ) HANGUL LETTER RIEUL
+313A;313A;313A;11B0;11B0; # (ㄺ; ㄺ; ㄺ; ᆰ; ᆰ; ) HANGUL LETTER RIEUL-KIYEOK
+313B;313B;313B;11B1;11B1; # (ㄻ; ㄻ; ㄻ; ᆱ; ᆱ; ) HANGUL LETTER RIEUL-MIEUM
+313C;313C;313C;11B2;11B2; # (ㄼ; ㄼ; ㄼ; ᆲ; ᆲ; ) HANGUL LETTER RIEUL-PIEUP
+313D;313D;313D;11B3;11B3; # (ㄽ; ㄽ; ㄽ; ᆳ; ᆳ; ) HANGUL LETTER RIEUL-SIOS
+313E;313E;313E;11B4;11B4; # (ㄾ; ㄾ; ㄾ; ᆴ; ᆴ; ) HANGUL LETTER RIEUL-THIEUTH
+313F;313F;313F;11B5;11B5; # (ㄿ; ㄿ; ㄿ; ᆵ; ᆵ; ) HANGUL LETTER RIEUL-PHIEUPH
+3140;3140;3140;111A;111A; # (ㅀ; ㅀ; ㅀ; ᄚ; ᄚ; ) HANGUL LETTER RIEUL-HIEUH
+3141;3141;3141;1106;1106; # (ㅁ; ㅁ; ㅁ; ᄆ; ᄆ; ) HANGUL LETTER MIEUM
+3142;3142;3142;1107;1107; # (ㅂ; ㅂ; ㅂ; ᄇ; ᄇ; ) HANGUL LETTER PIEUP
+3143;3143;3143;1108;1108; # (ㅃ; ㅃ; ㅃ; ᄈ; ᄈ; ) HANGUL LETTER SSANGPIEUP
+3144;3144;3144;1121;1121; # (ㅄ; ㅄ; ㅄ; ᄡ; ᄡ; ) HANGUL LETTER PIEUP-SIOS
+3145;3145;3145;1109;1109; # (ㅅ; ㅅ; ㅅ; ᄉ; ᄉ; ) HANGUL LETTER SIOS
+3146;3146;3146;110A;110A; # (ㅆ; ㅆ; ㅆ; ᄊ; ᄊ; ) HANGUL LETTER SSANGSIOS
+3147;3147;3147;110B;110B; # (ㅇ; ㅇ; ㅇ; ᄋ; ᄋ; ) HANGUL LETTER IEUNG
+3148;3148;3148;110C;110C; # (ㅈ; ㅈ; ㅈ; ᄌ; ᄌ; ) HANGUL LETTER CIEUC
+3149;3149;3149;110D;110D; # (ㅉ; ㅉ; ㅉ; ᄍ; ᄍ; ) HANGUL LETTER SSANGCIEUC
+314A;314A;314A;110E;110E; # (ㅊ; ㅊ; ㅊ; ᄎ; ᄎ; ) HANGUL LETTER CHIEUCH
+314B;314B;314B;110F;110F; # (ㅋ; ㅋ; ㅋ; ᄏ; ᄏ; ) HANGUL LETTER KHIEUKH
+314C;314C;314C;1110;1110; # (ㅌ; ㅌ; ㅌ; ᄐ; ᄐ; ) HANGUL LETTER THIEUTH
+314D;314D;314D;1111;1111; # (ㅍ; ㅍ; ㅍ; ᄑ; ᄑ; ) HANGUL LETTER PHIEUPH
+314E;314E;314E;1112;1112; # (ㅎ; ㅎ; ㅎ; ᄒ; ᄒ; ) HANGUL LETTER HIEUH
+314F;314F;314F;1161;1161; # (ㅏ; ㅏ; ㅏ; ᅡ; ᅡ; ) HANGUL LETTER A
+3150;3150;3150;1162;1162; # (ㅐ; ㅐ; ㅐ; ᅢ; ᅢ; ) HANGUL LETTER AE
+3151;3151;3151;1163;1163; # (ㅑ; ㅑ; ㅑ; ᅣ; ᅣ; ) HANGUL LETTER YA
+3152;3152;3152;1164;1164; # (ㅒ; ㅒ; ㅒ; ᅤ; ᅤ; ) HANGUL LETTER YAE
+3153;3153;3153;1165;1165; # (ㅓ; ㅓ; ㅓ; ᅥ; ᅥ; ) HANGUL LETTER EO
+3154;3154;3154;1166;1166; # (ㅔ; ㅔ; ㅔ; ᅦ; ᅦ; ) HANGUL LETTER E
+3155;3155;3155;1167;1167; # (ㅕ; ㅕ; ㅕ; ᅧ; ᅧ; ) HANGUL LETTER YEO
+3156;3156;3156;1168;1168; # (ㅖ; ㅖ; ㅖ; ᅨ; ᅨ; ) HANGUL LETTER YE
+3157;3157;3157;1169;1169; # (ㅗ; ㅗ; ㅗ; ᅩ; ᅩ; ) HANGUL LETTER O
+3158;3158;3158;116A;116A; # (ㅘ; ㅘ; ㅘ; ᅪ; ᅪ; ) HANGUL LETTER WA
+3159;3159;3159;116B;116B; # (ㅙ; ㅙ; ㅙ; ᅫ; ᅫ; ) HANGUL LETTER WAE
+315A;315A;315A;116C;116C; # (ㅚ; ㅚ; ㅚ; ᅬ; ᅬ; ) HANGUL LETTER OE
+315B;315B;315B;116D;116D; # (ㅛ; ㅛ; ㅛ; ᅭ; ᅭ; ) HANGUL LETTER YO
+315C;315C;315C;116E;116E; # (ㅜ; ㅜ; ㅜ; ᅮ; ᅮ; ) HANGUL LETTER U
+315D;315D;315D;116F;116F; # (ㅝ; ㅝ; ㅝ; ᅯ; ᅯ; ) HANGUL LETTER WEO
+315E;315E;315E;1170;1170; # (ㅞ; ㅞ; ㅞ; ᅰ; ᅰ; ) HANGUL LETTER WE
+315F;315F;315F;1171;1171; # (ㅟ; ㅟ; ㅟ; ᅱ; ᅱ; ) HANGUL LETTER WI
+3160;3160;3160;1172;1172; # (ㅠ; ㅠ; ㅠ; ᅲ; ᅲ; ) HANGUL LETTER YU
+3161;3161;3161;1173;1173; # (ㅡ; ㅡ; ㅡ; ᅳ; ᅳ; ) HANGUL LETTER EU
+3162;3162;3162;1174;1174; # (ㅢ; ㅢ; ㅢ; ᅴ; ᅴ; ) HANGUL LETTER YI
+3163;3163;3163;1175;1175; # (ㅣ; ㅣ; ㅣ; ᅵ; ᅵ; ) HANGUL LETTER I
+3164;3164;3164;1160;1160; # (ㅤ; ㅤ; ㅤ; ᅠ; ᅠ; ) HANGUL FILLER
+3165;3165;3165;1114;1114; # (ㅥ; ㅥ; ㅥ; ᄔ; ᄔ; ) HANGUL LETTER SSANGNIEUN
+3166;3166;3166;1115;1115; # (ㅦ; ㅦ; ㅦ; ᄕ; ᄕ; ) HANGUL LETTER NIEUN-TIKEUT
+3167;3167;3167;11C7;11C7; # (ㅧ; ㅧ; ㅧ; ᇇ; ᇇ; ) HANGUL LETTER NIEUN-SIOS
+3168;3168;3168;11C8;11C8; # (ㅨ; ㅨ; ㅨ; ᇈ; ᇈ; ) HANGUL LETTER NIEUN-PANSIOS
+3169;3169;3169;11CC;11CC; # (ㅩ; ㅩ; ㅩ; ᇌ; ᇌ; ) HANGUL LETTER RIEUL-KIYEOK-SIOS
+316A;316A;316A;11CE;11CE; # (ㅪ; ㅪ; ㅪ; ᇎ; ᇎ; ) HANGUL LETTER RIEUL-TIKEUT
+316B;316B;316B;11D3;11D3; # (ㅫ; ㅫ; ㅫ; ᇓ; ᇓ; ) HANGUL LETTER RIEUL-PIEUP-SIOS
+316C;316C;316C;11D7;11D7; # (ㅬ; ㅬ; ㅬ; ᇗ; ᇗ; ) HANGUL LETTER RIEUL-PANSIOS
+316D;316D;316D;11D9;11D9; # (ㅭ; ㅭ; ㅭ; ᇙ; ᇙ; ) HANGUL LETTER RIEUL-YEORINHIEUH
+316E;316E;316E;111C;111C; # (ㅮ; ㅮ; ㅮ; ᄜ; ᄜ; ) HANGUL LETTER MIEUM-PIEUP
+316F;316F;316F;11DD;11DD; # (ㅯ; ㅯ; ㅯ; ᇝ; ᇝ; ) HANGUL LETTER MIEUM-SIOS
+3170;3170;3170;11DF;11DF; # (ㅰ; ㅰ; ㅰ; ᇟ; ᇟ; ) HANGUL LETTER MIEUM-PANSIOS
+3171;3171;3171;111D;111D; # (ㅱ; ㅱ; ㅱ; ᄝ; ᄝ; ) HANGUL LETTER KAPYEOUNMIEUM
+3172;3172;3172;111E;111E; # (ㅲ; ㅲ; ㅲ; ᄞ; ᄞ; ) HANGUL LETTER PIEUP-KIYEOK
+3173;3173;3173;1120;1120; # (ㅳ; ㅳ; ㅳ; ᄠ; ᄠ; ) HANGUL LETTER PIEUP-TIKEUT
+3174;3174;3174;1122;1122; # (ㅴ; ㅴ; ㅴ; ᄢ; ᄢ; ) HANGUL LETTER PIEUP-SIOS-KIYEOK
+3175;3175;3175;1123;1123; # (ㅵ; ㅵ; ㅵ; ᄣ; ᄣ; ) HANGUL LETTER PIEUP-SIOS-TIKEUT
+3176;3176;3176;1127;1127; # (ㅶ; ㅶ; ㅶ; ᄧ; ᄧ; ) HANGUL LETTER PIEUP-CIEUC
+3177;3177;3177;1129;1129; # (ㅷ; ㅷ; ㅷ; ᄩ; ᄩ; ) HANGUL LETTER PIEUP-THIEUTH
+3178;3178;3178;112B;112B; # (ㅸ; ㅸ; ㅸ; ᄫ; ᄫ; ) HANGUL LETTER KAPYEOUNPIEUP
+3179;3179;3179;112C;112C; # (ㅹ; ㅹ; ㅹ; ᄬ; ᄬ; ) HANGUL LETTER KAPYEOUNSSANGPIEUP
+317A;317A;317A;112D;112D; # (ㅺ; ㅺ; ㅺ; ᄭ; ᄭ; ) HANGUL LETTER SIOS-KIYEOK
+317B;317B;317B;112E;112E; # (ㅻ; ㅻ; ㅻ; ᄮ; ᄮ; ) HANGUL LETTER SIOS-NIEUN
+317C;317C;317C;112F;112F; # (ㅼ; ㅼ; ㅼ; ᄯ; ᄯ; ) HANGUL LETTER SIOS-TIKEUT
+317D;317D;317D;1132;1132; # (ㅽ; ㅽ; ㅽ; ᄲ; ᄲ; ) HANGUL LETTER SIOS-PIEUP
+317E;317E;317E;1136;1136; # (ㅾ; ㅾ; ㅾ; ᄶ; ᄶ; ) HANGUL LETTER SIOS-CIEUC
+317F;317F;317F;1140;1140; # (ㅿ; ㅿ; ㅿ; ᅀ; ᅀ; ) HANGUL LETTER PANSIOS
+3180;3180;3180;1147;1147; # (ㆀ; ㆀ; ㆀ; ᅇ; ᅇ; ) HANGUL LETTER SSANGIEUNG
+3181;3181;3181;114C;114C; # (ㆁ; ㆁ; ㆁ; ᅌ; ᅌ; ) HANGUL LETTER YESIEUNG
+3182;3182;3182;11F1;11F1; # (ㆂ; ㆂ; ㆂ; ᇱ; ᇱ; ) HANGUL LETTER YESIEUNG-SIOS
+3183;3183;3183;11F2;11F2; # (ㆃ; ㆃ; ㆃ; ᇲ; ᇲ; ) HANGUL LETTER YESIEUNG-PANSIOS
+3184;3184;3184;1157;1157; # (ㆄ; ㆄ; ㆄ; ᅗ; ᅗ; ) HANGUL LETTER KAPYEOUNPHIEUPH
+3185;3185;3185;1158;1158; # (ㆅ; ㆅ; ㆅ; ᅘ; ᅘ; ) HANGUL LETTER SSANGHIEUH
+3186;3186;3186;1159;1159; # (ㆆ; ㆆ; ㆆ; ᅙ; ᅙ; ) HANGUL LETTER YEORINHIEUH
+3187;3187;3187;1184;1184; # (ㆇ; ㆇ; ㆇ; ᆄ; ᆄ; ) HANGUL LETTER YO-YA
+3188;3188;3188;1185;1185; # (ㆈ; ㆈ; ㆈ; ᆅ; ᆅ; ) HANGUL LETTER YO-YAE
+3189;3189;3189;1188;1188; # (ㆉ; ㆉ; ㆉ; ᆈ; ᆈ; ) HANGUL LETTER YO-I
+318A;318A;318A;1191;1191; # (ㆊ; ㆊ; ㆊ; ᆑ; ᆑ; ) HANGUL LETTER YU-YEO
+318B;318B;318B;1192;1192; # (ㆋ; ㆋ; ㆋ; ᆒ; ᆒ; ) HANGUL LETTER YU-YE
+318C;318C;318C;1194;1194; # (ㆌ; ㆌ; ㆌ; ᆔ; ᆔ; ) HANGUL LETTER YU-I
+318D;318D;318D;119E;119E; # (ㆍ; ㆍ; ㆍ; ᆞ; ᆞ; ) HANGUL LETTER ARAEA
+318E;318E;318E;11A1;11A1; # (ㆎ; ㆎ; ㆎ; ᆡ; ᆡ; ) HANGUL LETTER ARAEAE
+3192;3192;3192;4E00;4E00; # (㆒; ㆒; ㆒; 一; 一; ) IDEOGRAPHIC ANNOTATION ONE MARK
+3193;3193;3193;4E8C;4E8C; # (㆓; ㆓; ㆓; 二; 二; ) IDEOGRAPHIC ANNOTATION TWO MARK
+3194;3194;3194;4E09;4E09; # (㆔; ㆔; ㆔; 三; 三; ) IDEOGRAPHIC ANNOTATION THREE MARK
+3195;3195;3195;56DB;56DB; # (㆕; ㆕; ㆕; 四; 四; ) IDEOGRAPHIC ANNOTATION FOUR MARK
+3196;3196;3196;4E0A;4E0A; # (㆖; ㆖; ㆖; 上; 上; ) IDEOGRAPHIC ANNOTATION TOP MARK
+3197;3197;3197;4E2D;4E2D; # (㆗; ㆗; ㆗; 中; 中; ) IDEOGRAPHIC ANNOTATION MIDDLE MARK
+3198;3198;3198;4E0B;4E0B; # (㆘; ㆘; ㆘; 下; 下; ) IDEOGRAPHIC ANNOTATION BOTTOM MARK
+3199;3199;3199;7532;7532; # (㆙; ㆙; ㆙; 甲; 甲; ) IDEOGRAPHIC ANNOTATION FIRST MARK
+319A;319A;319A;4E59;4E59; # (㆚; ㆚; ㆚; 乙; 乙; ) IDEOGRAPHIC ANNOTATION SECOND MARK
+319B;319B;319B;4E19;4E19; # (㆛; ㆛; ㆛; 丙; 丙; ) IDEOGRAPHIC ANNOTATION THIRD MARK
+319C;319C;319C;4E01;4E01; # (㆜; ㆜; ㆜; 丁; 丁; ) IDEOGRAPHIC ANNOTATION FOURTH MARK
+319D;319D;319D;5929;5929; # (㆝; ㆝; ㆝; 天; 天; ) IDEOGRAPHIC ANNOTATION HEAVEN MARK
+319E;319E;319E;5730;5730; # (㆞; ㆞; ㆞; 地; 地; ) IDEOGRAPHIC ANNOTATION EARTH MARK
+319F;319F;319F;4EBA;4EBA; # (㆟; ㆟; ㆟; 人; 人; ) IDEOGRAPHIC ANNOTATION MAN MARK
+3200;3200;3200;0028 1100 0029;0028 1100 0029; # (㈀; ㈀; ㈀; (ᄀ); (ᄀ); ) PARENTHESIZED HANGUL KIYEOK
+3201;3201;3201;0028 1102 0029;0028 1102 0029; # (㈁; ㈁; ㈁; (ᄂ); (ᄂ); ) PARENTHESIZED HANGUL NIEUN
+3202;3202;3202;0028 1103 0029;0028 1103 0029; # (㈂; ㈂; ㈂; (ᄃ); (ᄃ); ) PARENTHESIZED HANGUL TIKEUT
+3203;3203;3203;0028 1105 0029;0028 1105 0029; # (㈃; ㈃; ㈃; (ᄅ); (ᄅ); ) PARENTHESIZED HANGUL RIEUL
+3204;3204;3204;0028 1106 0029;0028 1106 0029; # (㈄; ㈄; ㈄; (ᄆ); (ᄆ); ) PARENTHESIZED HANGUL MIEUM
+3205;3205;3205;0028 1107 0029;0028 1107 0029; # (㈅; ㈅; ㈅; (ᄇ); (ᄇ); ) PARENTHESIZED HANGUL PIEUP
+3206;3206;3206;0028 1109 0029;0028 1109 0029; # (㈆; ㈆; ㈆; (ᄉ); (ᄉ); ) PARENTHESIZED HANGUL SIOS
+3207;3207;3207;0028 110B 0029;0028 110B 0029; # (㈇; ㈇; ㈇; (ᄋ); (ᄋ); ) PARENTHESIZED HANGUL IEUNG
+3208;3208;3208;0028 110C 0029;0028 110C 0029; # (㈈; ㈈; ㈈; (ᄌ); (ᄌ); ) PARENTHESIZED HANGUL CIEUC
+3209;3209;3209;0028 110E 0029;0028 110E 0029; # (㈉; ㈉; ㈉; (ᄎ); (ᄎ); ) PARENTHESIZED HANGUL CHIEUCH
+320A;320A;320A;0028 110F 0029;0028 110F 0029; # (㈊; ㈊; ㈊; (ᄏ); (ᄏ); ) PARENTHESIZED HANGUL KHIEUKH
+320B;320B;320B;0028 1110 0029;0028 1110 0029; # (㈋; ㈋; ㈋; (ᄐ); (ᄐ); ) PARENTHESIZED HANGUL THIEUTH
+320C;320C;320C;0028 1111 0029;0028 1111 0029; # (㈌; ㈌; ㈌; (ᄑ); (ᄑ); ) PARENTHESIZED HANGUL PHIEUPH
+320D;320D;320D;0028 1112 0029;0028 1112 0029; # (㈍; ㈍; ㈍; (ᄒ); (ᄒ); ) PARENTHESIZED HANGUL HIEUH
+320E;320E;320E;0028 AC00 0029;0028 1100 1161 0029; # (㈎; ㈎; ㈎; (가); (가); ) PARENTHESIZED HANGUL KIYEOK A
+320F;320F;320F;0028 B098 0029;0028 1102 1161 0029; # (㈏; ㈏; ㈏; (나); (나); ) PARENTHESIZED HANGUL NIEUN A
+3210;3210;3210;0028 B2E4 0029;0028 1103 1161 0029; # (㈐; ㈐; ㈐; (다); (다); ) PARENTHESIZED HANGUL TIKEUT A
+3211;3211;3211;0028 B77C 0029;0028 1105 1161 0029; # (㈑; ㈑; ㈑; (라); (라); ) PARENTHESIZED HANGUL RIEUL A
+3212;3212;3212;0028 B9C8 0029;0028 1106 1161 0029; # (㈒; ㈒; ㈒; (마); (마); ) PARENTHESIZED HANGUL MIEUM A
+3213;3213;3213;0028 BC14 0029;0028 1107 1161 0029; # (㈓; ㈓; ㈓; (바); (바); ) PARENTHESIZED HANGUL PIEUP A
+3214;3214;3214;0028 C0AC 0029;0028 1109 1161 0029; # (㈔; ㈔; ㈔; (사); (사); ) PARENTHESIZED HANGUL SIOS A
+3215;3215;3215;0028 C544 0029;0028 110B 1161 0029; # (㈕; ㈕; ㈕; (아); (아); ) PARENTHESIZED HANGUL IEUNG A
+3216;3216;3216;0028 C790 0029;0028 110C 1161 0029; # (㈖; ㈖; ㈖; (자); (자); ) PARENTHESIZED HANGUL CIEUC A
+3217;3217;3217;0028 CC28 0029;0028 110E 1161 0029; # (㈗; ㈗; ㈗; (차); (차); ) PARENTHESIZED HANGUL CHIEUCH A
+3218;3218;3218;0028 CE74 0029;0028 110F 1161 0029; # (㈘; ㈘; ㈘; (카); (카); ) PARENTHESIZED HANGUL KHIEUKH A
+3219;3219;3219;0028 D0C0 0029;0028 1110 1161 0029; # (㈙; ㈙; ㈙; (타); (타); ) PARENTHESIZED HANGUL THIEUTH A
+321A;321A;321A;0028 D30C 0029;0028 1111 1161 0029; # (㈚; ㈚; ㈚; (파); (파); ) PARENTHESIZED HANGUL PHIEUPH A
+321B;321B;321B;0028 D558 0029;0028 1112 1161 0029; # (㈛; ㈛; ㈛; (하); (하); ) PARENTHESIZED HANGUL HIEUH A
+321C;321C;321C;0028 C8FC 0029;0028 110C 116E 0029; # (㈜; ㈜; ㈜; (주); (주); ) PARENTHESIZED HANGUL CIEUC U
+321D;321D;321D;0028 C624 C804 0029;0028 110B 1169 110C 1165 11AB 0029; # (㈝; ㈝; ㈝; (오전); (오전); ) PARENTHESIZED KOREAN CHARACTER OJEON
+321E;321E;321E;0028 C624 D6C4 0029;0028 110B 1169 1112 116E 0029; # (㈞; ㈞; ㈞; (오후); (오후); ) PARENTHESIZED KOREAN CHARACTER O HU
+3220;3220;3220;0028 4E00 0029;0028 4E00 0029; # (㈠; ㈠; ㈠; (一); (一); ) PARENTHESIZED IDEOGRAPH ONE
+3221;3221;3221;0028 4E8C 0029;0028 4E8C 0029; # (㈡; ㈡; ㈡; (二); (二); ) PARENTHESIZED IDEOGRAPH TWO
+3222;3222;3222;0028 4E09 0029;0028 4E09 0029; # (㈢; ㈢; ㈢; (三); (三); ) PARENTHESIZED IDEOGRAPH THREE
+3223;3223;3223;0028 56DB 0029;0028 56DB 0029; # (㈣; ㈣; ㈣; (四); (四); ) PARENTHESIZED IDEOGRAPH FOUR
+3224;3224;3224;0028 4E94 0029;0028 4E94 0029; # (㈤; ㈤; ㈤; (五); (五); ) PARENTHESIZED IDEOGRAPH FIVE
+3225;3225;3225;0028 516D 0029;0028 516D 0029; # (㈥; ㈥; ㈥; (六); (六); ) PARENTHESIZED IDEOGRAPH SIX
+3226;3226;3226;0028 4E03 0029;0028 4E03 0029; # (㈦; ㈦; ㈦; (七); (七); ) PARENTHESIZED IDEOGRAPH SEVEN
+3227;3227;3227;0028 516B 0029;0028 516B 0029; # (㈧; ㈧; ㈧; (八); (八); ) PARENTHESIZED IDEOGRAPH EIGHT
+3228;3228;3228;0028 4E5D 0029;0028 4E5D 0029; # (㈨; ㈨; ㈨; (九); (九); ) PARENTHESIZED IDEOGRAPH NINE
+3229;3229;3229;0028 5341 0029;0028 5341 0029; # (㈩; ㈩; ㈩; (十); (十); ) PARENTHESIZED IDEOGRAPH TEN
+322A;322A;322A;0028 6708 0029;0028 6708 0029; # (㈪; ㈪; ㈪; (月); (月); ) PARENTHESIZED IDEOGRAPH MOON
+322B;322B;322B;0028 706B 0029;0028 706B 0029; # (㈫; ㈫; ㈫; (火); (火); ) PARENTHESIZED IDEOGRAPH FIRE
+322C;322C;322C;0028 6C34 0029;0028 6C34 0029; # (㈬; ㈬; ㈬; (水); (水); ) PARENTHESIZED IDEOGRAPH WATER
+322D;322D;322D;0028 6728 0029;0028 6728 0029; # (㈭; ㈭; ㈭; (木); (木); ) PARENTHESIZED IDEOGRAPH WOOD
+322E;322E;322E;0028 91D1 0029;0028 91D1 0029; # (㈮; ㈮; ㈮; (金); (金); ) PARENTHESIZED IDEOGRAPH METAL
+322F;322F;322F;0028 571F 0029;0028 571F 0029; # (㈯; ㈯; ㈯; (土); (土); ) PARENTHESIZED IDEOGRAPH EARTH
+3230;3230;3230;0028 65E5 0029;0028 65E5 0029; # (㈰; ㈰; ㈰; (日); (日); ) PARENTHESIZED IDEOGRAPH SUN
+3231;3231;3231;0028 682A 0029;0028 682A 0029; # (㈱; ㈱; ㈱; (株); (株); ) PARENTHESIZED IDEOGRAPH STOCK
+3232;3232;3232;0028 6709 0029;0028 6709 0029; # (㈲; ㈲; ㈲; (有); (有); ) PARENTHESIZED IDEOGRAPH HAVE
+3233;3233;3233;0028 793E 0029;0028 793E 0029; # (㈳; ㈳; ㈳; (社); (社); ) PARENTHESIZED IDEOGRAPH SOCIETY
+3234;3234;3234;0028 540D 0029;0028 540D 0029; # (㈴; ㈴; ㈴; (名); (名); ) PARENTHESIZED IDEOGRAPH NAME
+3235;3235;3235;0028 7279 0029;0028 7279 0029; # (㈵; ㈵; ㈵; (特); (特); ) PARENTHESIZED IDEOGRAPH SPECIAL
+3236;3236;3236;0028 8CA1 0029;0028 8CA1 0029; # (㈶; ㈶; ㈶; (財); (財); ) PARENTHESIZED IDEOGRAPH FINANCIAL
+3237;3237;3237;0028 795D 0029;0028 795D 0029; # (㈷; ㈷; ㈷; (祝); (祝); ) PARENTHESIZED IDEOGRAPH CONGRATULATION
+3238;3238;3238;0028 52B4 0029;0028 52B4 0029; # (㈸; ㈸; ㈸; (労); (労); ) PARENTHESIZED IDEOGRAPH LABOR
+3239;3239;3239;0028 4EE3 0029;0028 4EE3 0029; # (㈹; ㈹; ㈹; (代); (代); ) PARENTHESIZED IDEOGRAPH REPRESENT
+323A;323A;323A;0028 547C 0029;0028 547C 0029; # (㈺; ㈺; ㈺; (呼); (呼); ) PARENTHESIZED IDEOGRAPH CALL
+323B;323B;323B;0028 5B66 0029;0028 5B66 0029; # (㈻; ㈻; ㈻; (学); (学); ) PARENTHESIZED IDEOGRAPH STUDY
+323C;323C;323C;0028 76E3 0029;0028 76E3 0029; # (㈼; ㈼; ㈼; (監); (監); ) PARENTHESIZED IDEOGRAPH SUPERVISE
+323D;323D;323D;0028 4F01 0029;0028 4F01 0029; # (㈽; ㈽; ㈽; (企); (企); ) PARENTHESIZED IDEOGRAPH ENTERPRISE
+323E;323E;323E;0028 8CC7 0029;0028 8CC7 0029; # (㈾; ㈾; ㈾; (資); (資); ) PARENTHESIZED IDEOGRAPH RESOURCE
+323F;323F;323F;0028 5354 0029;0028 5354 0029; # (㈿; ㈿; ㈿; (協); (協); ) PARENTHESIZED IDEOGRAPH ALLIANCE
+3240;3240;3240;0028 796D 0029;0028 796D 0029; # (㉀; ㉀; ㉀; (祭); (祭); ) PARENTHESIZED IDEOGRAPH FESTIVAL
+3241;3241;3241;0028 4F11 0029;0028 4F11 0029; # (㉁; ㉁; ㉁; (休); (休); ) PARENTHESIZED IDEOGRAPH REST
+3242;3242;3242;0028 81EA 0029;0028 81EA 0029; # (㉂; ㉂; ㉂; (自); (自); ) PARENTHESIZED IDEOGRAPH SELF
+3243;3243;3243;0028 81F3 0029;0028 81F3 0029; # (㉃; ㉃; ㉃; (至); (至); ) PARENTHESIZED IDEOGRAPH REACH
+3250;3250;3250;0050 0054 0045;0050 0054 0045; # (㉐; ㉐; ㉐; PTE; PTE; ) PARTNERSHIP SIGN
+3251;3251;3251;0032 0031;0032 0031; # (㉑; ㉑; ㉑; 21; 21; ) CIRCLED NUMBER TWENTY ONE
+3252;3252;3252;0032 0032;0032 0032; # (㉒; ㉒; ㉒; 22; 22; ) CIRCLED NUMBER TWENTY TWO
+3253;3253;3253;0032 0033;0032 0033; # (㉓; ㉓; ㉓; 23; 23; ) CIRCLED NUMBER TWENTY THREE
+3254;3254;3254;0032 0034;0032 0034; # (㉔; ㉔; ㉔; 24; 24; ) CIRCLED NUMBER TWENTY FOUR
+3255;3255;3255;0032 0035;0032 0035; # (㉕; ㉕; ㉕; 25; 25; ) CIRCLED NUMBER TWENTY FIVE
+3256;3256;3256;0032 0036;0032 0036; # (㉖; ㉖; ㉖; 26; 26; ) CIRCLED NUMBER TWENTY SIX
+3257;3257;3257;0032 0037;0032 0037; # (㉗; ㉗; ㉗; 27; 27; ) CIRCLED NUMBER TWENTY SEVEN
+3258;3258;3258;0032 0038;0032 0038; # (㉘; ㉘; ㉘; 28; 28; ) CIRCLED NUMBER TWENTY EIGHT
+3259;3259;3259;0032 0039;0032 0039; # (㉙; ㉙; ㉙; 29; 29; ) CIRCLED NUMBER TWENTY NINE
+325A;325A;325A;0033 0030;0033 0030; # (㉚; ㉚; ㉚; 30; 30; ) CIRCLED NUMBER THIRTY
+325B;325B;325B;0033 0031;0033 0031; # (㉛; ㉛; ㉛; 31; 31; ) CIRCLED NUMBER THIRTY ONE
+325C;325C;325C;0033 0032;0033 0032; # (㉜; ㉜; ㉜; 32; 32; ) CIRCLED NUMBER THIRTY TWO
+325D;325D;325D;0033 0033;0033 0033; # (㉝; ㉝; ㉝; 33; 33; ) CIRCLED NUMBER THIRTY THREE
+325E;325E;325E;0033 0034;0033 0034; # (㉞; ㉞; ㉞; 34; 34; ) CIRCLED NUMBER THIRTY FOUR
+325F;325F;325F;0033 0035;0033 0035; # (㉟; ㉟; ㉟; 35; 35; ) CIRCLED NUMBER THIRTY FIVE
+3260;3260;3260;1100;1100; # (㉠; ㉠; ㉠; ᄀ; ᄀ; ) CIRCLED HANGUL KIYEOK
+3261;3261;3261;1102;1102; # (㉡; ㉡; ㉡; ᄂ; ᄂ; ) CIRCLED HANGUL NIEUN
+3262;3262;3262;1103;1103; # (㉢; ㉢; ㉢; ᄃ; ᄃ; ) CIRCLED HANGUL TIKEUT
+3263;3263;3263;1105;1105; # (㉣; ㉣; ㉣; ᄅ; ᄅ; ) CIRCLED HANGUL RIEUL
+3264;3264;3264;1106;1106; # (㉤; ㉤; ㉤; ᄆ; ᄆ; ) CIRCLED HANGUL MIEUM
+3265;3265;3265;1107;1107; # (㉥; ㉥; ㉥; ᄇ; ᄇ; ) CIRCLED HANGUL PIEUP
+3266;3266;3266;1109;1109; # (㉦; ㉦; ㉦; ᄉ; ᄉ; ) CIRCLED HANGUL SIOS
+3267;3267;3267;110B;110B; # (㉧; ㉧; ㉧; ᄋ; ᄋ; ) CIRCLED HANGUL IEUNG
+3268;3268;3268;110C;110C; # (㉨; ㉨; ㉨; ᄌ; ᄌ; ) CIRCLED HANGUL CIEUC
+3269;3269;3269;110E;110E; # (㉩; ㉩; ㉩; ᄎ; ᄎ; ) CIRCLED HANGUL CHIEUCH
+326A;326A;326A;110F;110F; # (㉪; ㉪; ㉪; ᄏ; ᄏ; ) CIRCLED HANGUL KHIEUKH
+326B;326B;326B;1110;1110; # (㉫; ㉫; ㉫; ᄐ; ᄐ; ) CIRCLED HANGUL THIEUTH
+326C;326C;326C;1111;1111; # (㉬; ㉬; ㉬; ᄑ; ᄑ; ) CIRCLED HANGUL PHIEUPH
+326D;326D;326D;1112;1112; # (㉭; ㉭; ㉭; ᄒ; ᄒ; ) CIRCLED HANGUL HIEUH
+326E;326E;326E;AC00;1100 1161; # (㉮; ㉮; ㉮; 가; 가; ) CIRCLED HANGUL KIYEOK A
+326F;326F;326F;B098;1102 1161; # (㉯; ㉯; ㉯; 나; 나; ) CIRCLED HANGUL NIEUN A
+3270;3270;3270;B2E4;1103 1161; # (㉰; ㉰; ㉰; 다; 다; ) CIRCLED HANGUL TIKEUT A
+3271;3271;3271;B77C;1105 1161; # (㉱; ㉱; ㉱; 라; 라; ) CIRCLED HANGUL RIEUL A
+3272;3272;3272;B9C8;1106 1161; # (㉲; ㉲; ㉲; 마; 마; ) CIRCLED HANGUL MIEUM A
+3273;3273;3273;BC14;1107 1161; # (㉳; ㉳; ㉳; 바; 바; ) CIRCLED HANGUL PIEUP A
+3274;3274;3274;C0AC;1109 1161; # (㉴; ㉴; ㉴; 사; 사; ) CIRCLED HANGUL SIOS A
+3275;3275;3275;C544;110B 1161; # (㉵; ㉵; ㉵; 아; 아; ) CIRCLED HANGUL IEUNG A
+3276;3276;3276;C790;110C 1161; # (㉶; ㉶; ㉶; 자; 자; ) CIRCLED HANGUL CIEUC A
+3277;3277;3277;CC28;110E 1161; # (㉷; ㉷; ㉷; 차; 차; ) CIRCLED HANGUL CHIEUCH A
+3278;3278;3278;CE74;110F 1161; # (㉸; ㉸; ㉸; 카; 카; ) CIRCLED HANGUL KHIEUKH A
+3279;3279;3279;D0C0;1110 1161; # (㉹; ㉹; ㉹; 타; 타; ) CIRCLED HANGUL THIEUTH A
+327A;327A;327A;D30C;1111 1161; # (㉺; ㉺; ㉺; 파; 파; ) CIRCLED HANGUL PHIEUPH A
+327B;327B;327B;D558;1112 1161; # (㉻; ㉻; ㉻; 하; 하; ) CIRCLED HANGUL HIEUH A
+327C;327C;327C;CC38 ACE0;110E 1161 11B7 1100 1169; # (㉼; ㉼; ㉼; 참고; 참고; ) CIRCLED KOREAN CHARACTER CHAMKO
+327D;327D;327D;C8FC C758;110C 116E 110B 1174; # (㉽; ㉽; ㉽; 주의; 주의; ) CIRCLED KOREAN CHARACTER JUEUI
+3280;3280;3280;4E00;4E00; # (㊀; ㊀; ㊀; 一; 一; ) CIRCLED IDEOGRAPH ONE
+3281;3281;3281;4E8C;4E8C; # (㊁; ㊁; ㊁; 二; 二; ) CIRCLED IDEOGRAPH TWO
+3282;3282;3282;4E09;4E09; # (㊂; ㊂; ㊂; 三; 三; ) CIRCLED IDEOGRAPH THREE
+3283;3283;3283;56DB;56DB; # (㊃; ㊃; ㊃; 四; 四; ) CIRCLED IDEOGRAPH FOUR
+3284;3284;3284;4E94;4E94; # (㊄; ㊄; ㊄; 五; 五; ) CIRCLED IDEOGRAPH FIVE
+3285;3285;3285;516D;516D; # (㊅; ㊅; ㊅; 六; 六; ) CIRCLED IDEOGRAPH SIX
+3286;3286;3286;4E03;4E03; # (㊆; ㊆; ㊆; 七; 七; ) CIRCLED IDEOGRAPH SEVEN
+3287;3287;3287;516B;516B; # (㊇; ㊇; ㊇; 八; 八; ) CIRCLED IDEOGRAPH EIGHT
+3288;3288;3288;4E5D;4E5D; # (㊈; ㊈; ㊈; 九; 九; ) CIRCLED IDEOGRAPH NINE
+3289;3289;3289;5341;5341; # (㊉; ㊉; ㊉; 十; 十; ) CIRCLED IDEOGRAPH TEN
+328A;328A;328A;6708;6708; # (㊊; ㊊; ㊊; 月; 月; ) CIRCLED IDEOGRAPH MOON
+328B;328B;328B;706B;706B; # (㊋; ㊋; ㊋; 火; 火; ) CIRCLED IDEOGRAPH FIRE
+328C;328C;328C;6C34;6C34; # (㊌; ㊌; ㊌; 水; 水; ) CIRCLED IDEOGRAPH WATER
+328D;328D;328D;6728;6728; # (㊍; ㊍; ㊍; 木; 木; ) CIRCLED IDEOGRAPH WOOD
+328E;328E;328E;91D1;91D1; # (㊎; ㊎; ㊎; 金; 金; ) CIRCLED IDEOGRAPH METAL
+328F;328F;328F;571F;571F; # (㊏; ㊏; ㊏; 土; 土; ) CIRCLED IDEOGRAPH EARTH
+3290;3290;3290;65E5;65E5; # (㊐; ㊐; ㊐; 日; 日; ) CIRCLED IDEOGRAPH SUN
+3291;3291;3291;682A;682A; # (㊑; ㊑; ㊑; 株; 株; ) CIRCLED IDEOGRAPH STOCK
+3292;3292;3292;6709;6709; # (㊒; ㊒; ㊒; 有; 有; ) CIRCLED IDEOGRAPH HAVE
+3293;3293;3293;793E;793E; # (㊓; ㊓; ㊓; 社; 社; ) CIRCLED IDEOGRAPH SOCIETY
+3294;3294;3294;540D;540D; # (㊔; ㊔; ㊔; 名; 名; ) CIRCLED IDEOGRAPH NAME
+3295;3295;3295;7279;7279; # (㊕; ㊕; ㊕; 特; 特; ) CIRCLED IDEOGRAPH SPECIAL
+3296;3296;3296;8CA1;8CA1; # (㊖; ㊖; ㊖; 財; 財; ) CIRCLED IDEOGRAPH FINANCIAL
+3297;3297;3297;795D;795D; # (㊗; ㊗; ㊗; 祝; 祝; ) CIRCLED IDEOGRAPH CONGRATULATION
+3298;3298;3298;52B4;52B4; # (㊘; ㊘; ㊘; 労; 労; ) CIRCLED IDEOGRAPH LABOR
+3299;3299;3299;79D8;79D8; # (㊙; ㊙; ㊙; 秘; 秘; ) CIRCLED IDEOGRAPH SECRET
+329A;329A;329A;7537;7537; # (㊚; ㊚; ㊚; 男; 男; ) CIRCLED IDEOGRAPH MALE
+329B;329B;329B;5973;5973; # (㊛; ㊛; ㊛; 女; 女; ) CIRCLED IDEOGRAPH FEMALE
+329C;329C;329C;9069;9069; # (㊜; ㊜; ㊜; 適; 適; ) CIRCLED IDEOGRAPH SUITABLE
+329D;329D;329D;512A;512A; # (㊝; ㊝; ㊝; 優; 優; ) CIRCLED IDEOGRAPH EXCELLENT
+329E;329E;329E;5370;5370; # (㊞; ㊞; ㊞; 印; 印; ) CIRCLED IDEOGRAPH PRINT
+329F;329F;329F;6CE8;6CE8; # (㊟; ㊟; ㊟; 注; 注; ) CIRCLED IDEOGRAPH ATTENTION
+32A0;32A0;32A0;9805;9805; # (㊠; ㊠; ㊠; 項; 項; ) CIRCLED IDEOGRAPH ITEM
+32A1;32A1;32A1;4F11;4F11; # (㊡; ㊡; ㊡; 休; 休; ) CIRCLED IDEOGRAPH REST
+32A2;32A2;32A2;5199;5199; # (㊢; ㊢; ㊢; 写; 写; ) CIRCLED IDEOGRAPH COPY
+32A3;32A3;32A3;6B63;6B63; # (㊣; ㊣; ㊣; 正; 正; ) CIRCLED IDEOGRAPH CORRECT
+32A4;32A4;32A4;4E0A;4E0A; # (㊤; ㊤; ㊤; 上; 上; ) CIRCLED IDEOGRAPH HIGH
+32A5;32A5;32A5;4E2D;4E2D; # (㊥; ㊥; ㊥; 中; 中; ) CIRCLED IDEOGRAPH CENTRE
+32A6;32A6;32A6;4E0B;4E0B; # (㊦; ㊦; ㊦; 下; 下; ) CIRCLED IDEOGRAPH LOW
+32A7;32A7;32A7;5DE6;5DE6; # (㊧; ㊧; ㊧; 左; 左; ) CIRCLED IDEOGRAPH LEFT
+32A8;32A8;32A8;53F3;53F3; # (㊨; ㊨; ㊨; 右; 右; ) CIRCLED IDEOGRAPH RIGHT
+32A9;32A9;32A9;533B;533B; # (㊩; ㊩; ㊩; 医; 医; ) CIRCLED IDEOGRAPH MEDICINE
+32AA;32AA;32AA;5B97;5B97; # (㊪; ㊪; ㊪; 宗; 宗; ) CIRCLED IDEOGRAPH RELIGION
+32AB;32AB;32AB;5B66;5B66; # (㊫; ㊫; ㊫; 学; 学; ) CIRCLED IDEOGRAPH STUDY
+32AC;32AC;32AC;76E3;76E3; # (㊬; ㊬; ㊬; 監; 監; ) CIRCLED IDEOGRAPH SUPERVISE
+32AD;32AD;32AD;4F01;4F01; # (㊭; ㊭; ㊭; 企; 企; ) CIRCLED IDEOGRAPH ENTERPRISE
+32AE;32AE;32AE;8CC7;8CC7; # (㊮; ㊮; ㊮; 資; 資; ) CIRCLED IDEOGRAPH RESOURCE
+32AF;32AF;32AF;5354;5354; # (㊯; ㊯; ㊯; 協; 協; ) CIRCLED IDEOGRAPH ALLIANCE
+32B0;32B0;32B0;591C;591C; # (㊰; ㊰; ㊰; 夜; 夜; ) CIRCLED IDEOGRAPH NIGHT
+32B1;32B1;32B1;0033 0036;0033 0036; # (㊱; ㊱; ㊱; 36; 36; ) CIRCLED NUMBER THIRTY SIX
+32B2;32B2;32B2;0033 0037;0033 0037; # (㊲; ㊲; ㊲; 37; 37; ) CIRCLED NUMBER THIRTY SEVEN
+32B3;32B3;32B3;0033 0038;0033 0038; # (㊳; ㊳; ㊳; 38; 38; ) CIRCLED NUMBER THIRTY EIGHT
+32B4;32B4;32B4;0033 0039;0033 0039; # (㊴; ㊴; ㊴; 39; 39; ) CIRCLED NUMBER THIRTY NINE
+32B5;32B5;32B5;0034 0030;0034 0030; # (㊵; ㊵; ㊵; 40; 40; ) CIRCLED NUMBER FORTY
+32B6;32B6;32B6;0034 0031;0034 0031; # (㊶; ㊶; ㊶; 41; 41; ) CIRCLED NUMBER FORTY ONE
+32B7;32B7;32B7;0034 0032;0034 0032; # (㊷; ㊷; ㊷; 42; 42; ) CIRCLED NUMBER FORTY TWO
+32B8;32B8;32B8;0034 0033;0034 0033; # (㊸; ㊸; ㊸; 43; 43; ) CIRCLED NUMBER FORTY THREE
+32B9;32B9;32B9;0034 0034;0034 0034; # (㊹; ㊹; ㊹; 44; 44; ) CIRCLED NUMBER FORTY FOUR
+32BA;32BA;32BA;0034 0035;0034 0035; # (㊺; ㊺; ㊺; 45; 45; ) CIRCLED NUMBER FORTY FIVE
+32BB;32BB;32BB;0034 0036;0034 0036; # (㊻; ㊻; ㊻; 46; 46; ) CIRCLED NUMBER FORTY SIX
+32BC;32BC;32BC;0034 0037;0034 0037; # (㊼; ㊼; ㊼; 47; 47; ) CIRCLED NUMBER FORTY SEVEN
+32BD;32BD;32BD;0034 0038;0034 0038; # (㊽; ㊽; ㊽; 48; 48; ) CIRCLED NUMBER FORTY EIGHT
+32BE;32BE;32BE;0034 0039;0034 0039; # (㊾; ㊾; ㊾; 49; 49; ) CIRCLED NUMBER FORTY NINE
+32BF;32BF;32BF;0035 0030;0035 0030; # (㊿; ㊿; ㊿; 50; 50; ) CIRCLED NUMBER FIFTY
+32C0;32C0;32C0;0031 6708;0031 6708; # (㋀; ㋀; ㋀; 1月; 1月; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR JANUARY
+32C1;32C1;32C1;0032 6708;0032 6708; # (㋁; ㋁; ㋁; 2月; 2月; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR FEBRUARY
+32C2;32C2;32C2;0033 6708;0033 6708; # (㋂; ㋂; ㋂; 3月; 3月; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR MARCH
+32C3;32C3;32C3;0034 6708;0034 6708; # (㋃; ㋃; ㋃; 4月; 4月; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR APRIL
+32C4;32C4;32C4;0035 6708;0035 6708; # (㋄; ㋄; ㋄; 5月; 5月; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR MAY
+32C5;32C5;32C5;0036 6708;0036 6708; # (㋅; ㋅; ㋅; 6月; 6月; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR JUNE
+32C6;32C6;32C6;0037 6708;0037 6708; # (㋆; ㋆; ㋆; 7月; 7月; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR JULY
+32C7;32C7;32C7;0038 6708;0038 6708; # (㋇; ㋇; ㋇; 8月; 8月; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR AUGUST
+32C8;32C8;32C8;0039 6708;0039 6708; # (㋈; ㋈; ㋈; 9月; 9月; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR SEPTEMBER
+32C9;32C9;32C9;0031 0030 6708;0031 0030 6708; # (㋉; ㋉; ㋉; 10月; 10月; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR OCTOBER
+32CA;32CA;32CA;0031 0031 6708;0031 0031 6708; # (㋊; ㋊; ㋊; 11月; 11月; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR NOVEMBER
+32CB;32CB;32CB;0031 0032 6708;0031 0032 6708; # (㋋; ㋋; ㋋; 12月; 12月; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DECEMBER
+32CC;32CC;32CC;0048 0067;0048 0067; # (㋌; ㋌; ㋌; Hg; Hg; ) SQUARE HG
+32CD;32CD;32CD;0065 0072 0067;0065 0072 0067; # (㋍; ㋍; ㋍; erg; erg; ) SQUARE ERG
+32CE;32CE;32CE;0065 0056;0065 0056; # (㋎; ㋎; ㋎; eV; eV; ) SQUARE EV
+32CF;32CF;32CF;004C 0054 0044;004C 0054 0044; # (㋏; ㋏; ㋏; LTD; LTD; ) LIMITED LIABILITY SIGN
+32D0;32D0;32D0;30A2;30A2; # (㋐; ㋐; ㋐; ア; ア; ) CIRCLED KATAKANA A
+32D1;32D1;32D1;30A4;30A4; # (㋑; ㋑; ㋑; イ; イ; ) CIRCLED KATAKANA I
+32D2;32D2;32D2;30A6;30A6; # (㋒; ㋒; ㋒; ウ; ウ; ) CIRCLED KATAKANA U
+32D3;32D3;32D3;30A8;30A8; # (㋓; ㋓; ㋓; エ; エ; ) CIRCLED KATAKANA E
+32D4;32D4;32D4;30AA;30AA; # (㋔; ㋔; ㋔; オ; オ; ) CIRCLED KATAKANA O
+32D5;32D5;32D5;30AB;30AB; # (㋕; ㋕; ㋕; カ; カ; ) CIRCLED KATAKANA KA
+32D6;32D6;32D6;30AD;30AD; # (㋖; ㋖; ㋖; キ; キ; ) CIRCLED KATAKANA KI
+32D7;32D7;32D7;30AF;30AF; # (㋗; ㋗; ㋗; ク; ク; ) CIRCLED KATAKANA KU
+32D8;32D8;32D8;30B1;30B1; # (㋘; ㋘; ㋘; ケ; ケ; ) CIRCLED KATAKANA KE
+32D9;32D9;32D9;30B3;30B3; # (㋙; ㋙; ㋙; コ; コ; ) CIRCLED KATAKANA KO
+32DA;32DA;32DA;30B5;30B5; # (㋚; ㋚; ㋚; サ; サ; ) CIRCLED KATAKANA SA
+32DB;32DB;32DB;30B7;30B7; # (㋛; ㋛; ㋛; シ; シ; ) CIRCLED KATAKANA SI
+32DC;32DC;32DC;30B9;30B9; # (㋜; ㋜; ㋜; ス; ス; ) CIRCLED KATAKANA SU
+32DD;32DD;32DD;30BB;30BB; # (㋝; ㋝; ㋝; セ; セ; ) CIRCLED KATAKANA SE
+32DE;32DE;32DE;30BD;30BD; # (㋞; ㋞; ㋞; ソ; ソ; ) CIRCLED KATAKANA SO
+32DF;32DF;32DF;30BF;30BF; # (㋟; ㋟; ㋟; タ; タ; ) CIRCLED KATAKANA TA
+32E0;32E0;32E0;30C1;30C1; # (㋠; ㋠; ㋠; チ; チ; ) CIRCLED KATAKANA TI
+32E1;32E1;32E1;30C4;30C4; # (㋡; ㋡; ㋡; ツ; ツ; ) CIRCLED KATAKANA TU
+32E2;32E2;32E2;30C6;30C6; # (㋢; ㋢; ㋢; テ; テ; ) CIRCLED KATAKANA TE
+32E3;32E3;32E3;30C8;30C8; # (㋣; ㋣; ㋣; ト; ト; ) CIRCLED KATAKANA TO
+32E4;32E4;32E4;30CA;30CA; # (㋤; ㋤; ㋤; ナ; ナ; ) CIRCLED KATAKANA NA
+32E5;32E5;32E5;30CB;30CB; # (㋥; ㋥; ㋥; ニ; ニ; ) CIRCLED KATAKANA NI
+32E6;32E6;32E6;30CC;30CC; # (㋦; ㋦; ㋦; ヌ; ヌ; ) CIRCLED KATAKANA NU
+32E7;32E7;32E7;30CD;30CD; # (㋧; ㋧; ㋧; ネ; ネ; ) CIRCLED KATAKANA NE
+32E8;32E8;32E8;30CE;30CE; # (㋨; ㋨; ㋨; ノ; ノ; ) CIRCLED KATAKANA NO
+32E9;32E9;32E9;30CF;30CF; # (㋩; ㋩; ㋩; ハ; ハ; ) CIRCLED KATAKANA HA
+32EA;32EA;32EA;30D2;30D2; # (㋪; ㋪; ㋪; ヒ; ヒ; ) CIRCLED KATAKANA HI
+32EB;32EB;32EB;30D5;30D5; # (㋫; ㋫; ㋫; フ; フ; ) CIRCLED KATAKANA HU
+32EC;32EC;32EC;30D8;30D8; # (㋬; ㋬; ㋬; ヘ; ヘ; ) CIRCLED KATAKANA HE
+32ED;32ED;32ED;30DB;30DB; # (㋭; ㋭; ㋭; ホ; ホ; ) CIRCLED KATAKANA HO
+32EE;32EE;32EE;30DE;30DE; # (㋮; ㋮; ㋮; マ; マ; ) CIRCLED KATAKANA MA
+32EF;32EF;32EF;30DF;30DF; # (㋯; ㋯; ㋯; ミ; ミ; ) CIRCLED KATAKANA MI
+32F0;32F0;32F0;30E0;30E0; # (㋰; ㋰; ㋰; ム; ム; ) CIRCLED KATAKANA MU
+32F1;32F1;32F1;30E1;30E1; # (㋱; ㋱; ㋱; メ; メ; ) CIRCLED KATAKANA ME
+32F2;32F2;32F2;30E2;30E2; # (㋲; ㋲; ㋲; モ; モ; ) CIRCLED KATAKANA MO
+32F3;32F3;32F3;30E4;30E4; # (㋳; ㋳; ㋳; ヤ; ヤ; ) CIRCLED KATAKANA YA
+32F4;32F4;32F4;30E6;30E6; # (㋴; ㋴; ㋴; ユ; ユ; ) CIRCLED KATAKANA YU
+32F5;32F5;32F5;30E8;30E8; # (㋵; ㋵; ㋵; ヨ; ヨ; ) CIRCLED KATAKANA YO
+32F6;32F6;32F6;30E9;30E9; # (㋶; ㋶; ㋶; ラ; ラ; ) CIRCLED KATAKANA RA
+32F7;32F7;32F7;30EA;30EA; # (㋷; ㋷; ㋷; リ; リ; ) CIRCLED KATAKANA RI
+32F8;32F8;32F8;30EB;30EB; # (㋸; ㋸; ㋸; ル; ル; ) CIRCLED KATAKANA RU
+32F9;32F9;32F9;30EC;30EC; # (㋹; ㋹; ㋹; レ; レ; ) CIRCLED KATAKANA RE
+32FA;32FA;32FA;30ED;30ED; # (㋺; ㋺; ㋺; ロ; ロ; ) CIRCLED KATAKANA RO
+32FB;32FB;32FB;30EF;30EF; # (㋻; ㋻; ㋻; ワ; ワ; ) CIRCLED KATAKANA WA
+32FC;32FC;32FC;30F0;30F0; # (㋼; ㋼; ㋼; ヰ; ヰ; ) CIRCLED KATAKANA WI
+32FD;32FD;32FD;30F1;30F1; # (㋽; ㋽; ㋽; ヱ; ヱ; ) CIRCLED KATAKANA WE
+32FE;32FE;32FE;30F2;30F2; # (㋾; ㋾; ㋾; ヲ; ヲ; ) CIRCLED KATAKANA WO
+3300;3300;3300;30A2 30D1 30FC 30C8;30A2 30CF 309A 30FC 30C8; # (㌀; ㌀; ㌀; アパート; アハ◌゚ート; ) SQUARE APAATO
+3301;3301;3301;30A2 30EB 30D5 30A1;30A2 30EB 30D5 30A1; # (㌁; ㌁; ㌁; アルファ; アルファ; ) SQUARE ARUHUA
+3302;3302;3302;30A2 30F3 30DA 30A2;30A2 30F3 30D8 309A 30A2; # (㌂; ㌂; ㌂; アンペア; アンヘ◌゚ア; ) SQUARE ANPEA
+3303;3303;3303;30A2 30FC 30EB;30A2 30FC 30EB; # (㌃; ㌃; ㌃; アール; アール; ) SQUARE AARU
+3304;3304;3304;30A4 30CB 30F3 30B0;30A4 30CB 30F3 30AF 3099; # (㌄; ㌄; ㌄; イニング; イニンク◌゙; ) SQUARE ININGU
+3305;3305;3305;30A4 30F3 30C1;30A4 30F3 30C1; # (㌅; ㌅; ㌅; インチ; インチ; ) SQUARE INTI
+3306;3306;3306;30A6 30A9 30F3;30A6 30A9 30F3; # (㌆; ㌆; ㌆; ウォン; ウォン; ) SQUARE UON
+3307;3307;3307;30A8 30B9 30AF 30FC 30C9;30A8 30B9 30AF 30FC 30C8 3099; # (㌇; ㌇; ㌇; エスクード; エスクート◌゙; ) SQUARE ESUKUUDO
+3308;3308;3308;30A8 30FC 30AB 30FC;30A8 30FC 30AB 30FC; # (㌈; ㌈; ㌈; エーカー; エーカー; ) SQUARE EEKAA
+3309;3309;3309;30AA 30F3 30B9;30AA 30F3 30B9; # (㌉; ㌉; ㌉; オンス; オンス; ) SQUARE ONSU
+330A;330A;330A;30AA 30FC 30E0;30AA 30FC 30E0; # (㌊; ㌊; ㌊; オーム; オーム; ) SQUARE OOMU
+330B;330B;330B;30AB 30A4 30EA;30AB 30A4 30EA; # (㌋; ㌋; ㌋; カイリ; カイリ; ) SQUARE KAIRI
+330C;330C;330C;30AB 30E9 30C3 30C8;30AB 30E9 30C3 30C8; # (㌌; ㌌; ㌌; カラット; カラット; ) SQUARE KARATTO
+330D;330D;330D;30AB 30ED 30EA 30FC;30AB 30ED 30EA 30FC; # (㌍; ㌍; ㌍; カロリー; カロリー; ) SQUARE KARORII
+330E;330E;330E;30AC 30ED 30F3;30AB 3099 30ED 30F3; # (㌎; ㌎; ㌎; ガロン; カ◌゙ロン; ) SQUARE GARON
+330F;330F;330F;30AC 30F3 30DE;30AB 3099 30F3 30DE; # (㌏; ㌏; ㌏; ガンマ; カ◌゙ンマ; ) SQUARE GANMA
+3310;3310;3310;30AE 30AC;30AD 3099 30AB 3099; # (㌐; ㌐; ㌐; ギガ; キ◌゙カ◌゙; ) SQUARE GIGA
+3311;3311;3311;30AE 30CB 30FC;30AD 3099 30CB 30FC; # (㌑; ㌑; ㌑; ギニー; キ◌゙ニー; ) SQUARE GINII
+3312;3312;3312;30AD 30E5 30EA 30FC;30AD 30E5 30EA 30FC; # (㌒; ㌒; ㌒; キュリー; キュリー; ) SQUARE KYURII
+3313;3313;3313;30AE 30EB 30C0 30FC;30AD 3099 30EB 30BF 3099 30FC; # (㌓; ㌓; ㌓; ギルダー; キ◌゙ルタ◌゙ー; ) SQUARE GIRUDAA
+3314;3314;3314;30AD 30ED;30AD 30ED; # (㌔; ㌔; ㌔; キロ; キロ; ) SQUARE KIRO
+3315;3315;3315;30AD 30ED 30B0 30E9 30E0;30AD 30ED 30AF 3099 30E9 30E0; # (㌕; ㌕; ㌕; キログラム; キロク◌゙ラム; ) SQUARE KIROGURAMU
+3316;3316;3316;30AD 30ED 30E1 30FC 30C8 30EB;30AD 30ED 30E1 30FC 30C8 30EB; # (㌖; ㌖; ㌖; キロメートル; キロメートル; ) SQUARE KIROMEETORU
+3317;3317;3317;30AD 30ED 30EF 30C3 30C8;30AD 30ED 30EF 30C3 30C8; # (㌗; ㌗; ㌗; キロワット; キロワット; ) SQUARE KIROWATTO
+3318;3318;3318;30B0 30E9 30E0;30AF 3099 30E9 30E0; # (㌘; ㌘; ㌘; グラム; ク◌゙ラム; ) SQUARE GURAMU
+3319;3319;3319;30B0 30E9 30E0 30C8 30F3;30AF 3099 30E9 30E0 30C8 30F3; # (㌙; ㌙; ㌙; グラムトン; ク◌゙ラムトン; ) SQUARE GURAMUTON
+331A;331A;331A;30AF 30EB 30BC 30A4 30ED;30AF 30EB 30BB 3099 30A4 30ED; # (㌚; ㌚; ㌚; クルゼイロ; クルセ◌゙イロ; ) SQUARE KURUZEIRO
+331B;331B;331B;30AF 30ED 30FC 30CD;30AF 30ED 30FC 30CD; # (㌛; ㌛; ㌛; クローネ; クローネ; ) SQUARE KUROONE
+331C;331C;331C;30B1 30FC 30B9;30B1 30FC 30B9; # (㌜; ㌜; ㌜; ケース; ケース; ) SQUARE KEESU
+331D;331D;331D;30B3 30EB 30CA;30B3 30EB 30CA; # (㌝; ㌝; ㌝; コルナ; コルナ; ) SQUARE KORUNA
+331E;331E;331E;30B3 30FC 30DD;30B3 30FC 30DB 309A; # (㌞; ㌞; ㌞; コーポ; コーホ◌゚; ) SQUARE KOOPO
+331F;331F;331F;30B5 30A4 30AF 30EB;30B5 30A4 30AF 30EB; # (㌟; ㌟; ㌟; サイクル; サイクル; ) SQUARE SAIKURU
+3320;3320;3320;30B5 30F3 30C1 30FC 30E0;30B5 30F3 30C1 30FC 30E0; # (㌠; ㌠; ㌠; サンチーム; サンチーム; ) SQUARE SANTIIMU
+3321;3321;3321;30B7 30EA 30F3 30B0;30B7 30EA 30F3 30AF 3099; # (㌡; ㌡; ㌡; シリング; シリンク◌゙; ) SQUARE SIRINGU
+3322;3322;3322;30BB 30F3 30C1;30BB 30F3 30C1; # (㌢; ㌢; ㌢; センチ; センチ; ) SQUARE SENTI
+3323;3323;3323;30BB 30F3 30C8;30BB 30F3 30C8; # (㌣; ㌣; ㌣; セント; セント; ) SQUARE SENTO
+3324;3324;3324;30C0 30FC 30B9;30BF 3099 30FC 30B9; # (㌤; ㌤; ㌤; ダース; タ◌゙ース; ) SQUARE DAASU
+3325;3325;3325;30C7 30B7;30C6 3099 30B7; # (㌥; ㌥; ㌥; デシ; テ◌゙シ; ) SQUARE DESI
+3326;3326;3326;30C9 30EB;30C8 3099 30EB; # (㌦; ㌦; ㌦; ドル; ト◌゙ル; ) SQUARE DORU
+3327;3327;3327;30C8 30F3;30C8 30F3; # (㌧; ㌧; ㌧; トン; トン; ) SQUARE TON
+3328;3328;3328;30CA 30CE;30CA 30CE; # (㌨; ㌨; ㌨; ナノ; ナノ; ) SQUARE NANO
+3329;3329;3329;30CE 30C3 30C8;30CE 30C3 30C8; # (㌩; ㌩; ㌩; ノット; ノット; ) SQUARE NOTTO
+332A;332A;332A;30CF 30A4 30C4;30CF 30A4 30C4; # (㌪; ㌪; ㌪; ハイツ; ハイツ; ) SQUARE HAITU
+332B;332B;332B;30D1 30FC 30BB 30F3 30C8;30CF 309A 30FC 30BB 30F3 30C8; # (㌫; ㌫; ㌫; パーセント; ハ◌゚ーセント; ) SQUARE PAASENTO
+332C;332C;332C;30D1 30FC 30C4;30CF 309A 30FC 30C4; # (㌬; ㌬; ㌬; パーツ; ハ◌゚ーツ; ) SQUARE PAATU
+332D;332D;332D;30D0 30FC 30EC 30EB;30CF 3099 30FC 30EC 30EB; # (㌭; ㌭; ㌭; バーレル; ハ◌゙ーレル; ) SQUARE BAARERU
+332E;332E;332E;30D4 30A2 30B9 30C8 30EB;30D2 309A 30A2 30B9 30C8 30EB; # (㌮; ㌮; ㌮; ピアストル; ヒ◌゚アストル; ) SQUARE PIASUTORU
+332F;332F;332F;30D4 30AF 30EB;30D2 309A 30AF 30EB; # (㌯; ㌯; ㌯; ピクル; ヒ◌゚クル; ) SQUARE PIKURU
+3330;3330;3330;30D4 30B3;30D2 309A 30B3; # (㌰; ㌰; ㌰; ピコ; ヒ◌゚コ; ) SQUARE PIKO
+3331;3331;3331;30D3 30EB;30D2 3099 30EB; # (㌱; ㌱; ㌱; ビル; ヒ◌゙ル; ) SQUARE BIRU
+3332;3332;3332;30D5 30A1 30E9 30C3 30C9;30D5 30A1 30E9 30C3 30C8 3099; # (㌲; ㌲; ㌲; ファラッド; ファラット◌゙; ) SQUARE HUARADDO
+3333;3333;3333;30D5 30A3 30FC 30C8;30D5 30A3 30FC 30C8; # (㌳; ㌳; ㌳; フィート; フィート; ) SQUARE HUIITO
+3334;3334;3334;30D6 30C3 30B7 30A7 30EB;30D5 3099 30C3 30B7 30A7 30EB; # (㌴; ㌴; ㌴; ブッシェル; フ◌゙ッシェル; ) SQUARE BUSSYERU
+3335;3335;3335;30D5 30E9 30F3;30D5 30E9 30F3; # (㌵; ㌵; ㌵; フラン; フラン; ) SQUARE HURAN
+3336;3336;3336;30D8 30AF 30BF 30FC 30EB;30D8 30AF 30BF 30FC 30EB; # (㌶; ㌶; ㌶; ヘクタール; ヘクタール; ) SQUARE HEKUTAARU
+3337;3337;3337;30DA 30BD;30D8 309A 30BD; # (㌷; ㌷; ㌷; ペソ; ヘ◌゚ソ; ) SQUARE PESO
+3338;3338;3338;30DA 30CB 30D2;30D8 309A 30CB 30D2; # (㌸; ㌸; ㌸; ペニヒ; ヘ◌゚ニヒ; ) SQUARE PENIHI
+3339;3339;3339;30D8 30EB 30C4;30D8 30EB 30C4; # (㌹; ㌹; ㌹; ヘルツ; ヘルツ; ) SQUARE HERUTU
+333A;333A;333A;30DA 30F3 30B9;30D8 309A 30F3 30B9; # (㌺; ㌺; ㌺; ペンス; ヘ◌゚ンス; ) SQUARE PENSU
+333B;333B;333B;30DA 30FC 30B8;30D8 309A 30FC 30B7 3099; # (㌻; ㌻; ㌻; ページ; ヘ◌゚ーシ◌゙; ) SQUARE PEEZI
+333C;333C;333C;30D9 30FC 30BF;30D8 3099 30FC 30BF; # (㌼; ㌼; ㌼; ベータ; ヘ◌゙ータ; ) SQUARE BEETA
+333D;333D;333D;30DD 30A4 30F3 30C8;30DB 309A 30A4 30F3 30C8; # (㌽; ㌽; ㌽; ポイント; ホ◌゚イント; ) SQUARE POINTO
+333E;333E;333E;30DC 30EB 30C8;30DB 3099 30EB 30C8; # (㌾; ㌾; ㌾; ボルト; ホ◌゙ルト; ) SQUARE BORUTO
+333F;333F;333F;30DB 30F3;30DB 30F3; # (㌿; ㌿; ㌿; ホン; ホン; ) SQUARE HON
+3340;3340;3340;30DD 30F3 30C9;30DB 309A 30F3 30C8 3099; # (㍀; ㍀; ㍀; ポンド; ホ◌゚ント◌゙; ) SQUARE PONDO
+3341;3341;3341;30DB 30FC 30EB;30DB 30FC 30EB; # (㍁; ㍁; ㍁; ホール; ホール; ) SQUARE HOORU
+3342;3342;3342;30DB 30FC 30F3;30DB 30FC 30F3; # (㍂; ㍂; ㍂; ホーン; ホーン; ) SQUARE HOON
+3343;3343;3343;30DE 30A4 30AF 30ED;30DE 30A4 30AF 30ED; # (㍃; ㍃; ㍃; マイクロ; マイクロ; ) SQUARE MAIKURO
+3344;3344;3344;30DE 30A4 30EB;30DE 30A4 30EB; # (㍄; ㍄; ㍄; マイル; マイル; ) SQUARE MAIRU
+3345;3345;3345;30DE 30C3 30CF;30DE 30C3 30CF; # (㍅; ㍅; ㍅; マッハ; マッハ; ) SQUARE MAHHA
+3346;3346;3346;30DE 30EB 30AF;30DE 30EB 30AF; # (㍆; ㍆; ㍆; マルク; マルク; ) SQUARE MARUKU
+3347;3347;3347;30DE 30F3 30B7 30E7 30F3;30DE 30F3 30B7 30E7 30F3; # (㍇; ㍇; ㍇; マンション; マンション; ) SQUARE MANSYON
+3348;3348;3348;30DF 30AF 30ED 30F3;30DF 30AF 30ED 30F3; # (㍈; ㍈; ㍈; ミクロン; ミクロン; ) SQUARE MIKURON
+3349;3349;3349;30DF 30EA;30DF 30EA; # (㍉; ㍉; ㍉; ミリ; ミリ; ) SQUARE MIRI
+334A;334A;334A;30DF 30EA 30D0 30FC 30EB;30DF 30EA 30CF 3099 30FC 30EB; # (㍊; ㍊; ㍊; ミリバール; ミリハ◌゙ール; ) SQUARE MIRIBAARU
+334B;334B;334B;30E1 30AC;30E1 30AB 3099; # (㍋; ㍋; ㍋; メガ; メカ◌゙; ) SQUARE MEGA
+334C;334C;334C;30E1 30AC 30C8 30F3;30E1 30AB 3099 30C8 30F3; # (㍌; ㍌; ㍌; メガトン; メカ◌゙トン; ) SQUARE MEGATON
+334D;334D;334D;30E1 30FC 30C8 30EB;30E1 30FC 30C8 30EB; # (㍍; ㍍; ㍍; メートル; メートル; ) SQUARE MEETORU
+334E;334E;334E;30E4 30FC 30C9;30E4 30FC 30C8 3099; # (㍎; ㍎; ㍎; ヤード; ヤート◌゙; ) SQUARE YAADO
+334F;334F;334F;30E4 30FC 30EB;30E4 30FC 30EB; # (㍏; ㍏; ㍏; ヤール; ヤール; ) SQUARE YAARU
+3350;3350;3350;30E6 30A2 30F3;30E6 30A2 30F3; # (㍐; ㍐; ㍐; ユアン; ユアン; ) SQUARE YUAN
+3351;3351;3351;30EA 30C3 30C8 30EB;30EA 30C3 30C8 30EB; # (㍑; ㍑; ㍑; リットル; リットル; ) SQUARE RITTORU
+3352;3352;3352;30EA 30E9;30EA 30E9; # (㍒; ㍒; ㍒; リラ; リラ; ) SQUARE RIRA
+3353;3353;3353;30EB 30D4 30FC;30EB 30D2 309A 30FC; # (㍓; ㍓; ㍓; ルピー; ルヒ◌゚ー; ) SQUARE RUPII
+3354;3354;3354;30EB 30FC 30D6 30EB;30EB 30FC 30D5 3099 30EB; # (㍔; ㍔; ㍔; ルーブル; ルーフ◌゙ル; ) SQUARE RUUBURU
+3355;3355;3355;30EC 30E0;30EC 30E0; # (㍕; ㍕; ㍕; レム; レム; ) SQUARE REMU
+3356;3356;3356;30EC 30F3 30C8 30B2 30F3;30EC 30F3 30C8 30B1 3099 30F3; # (㍖; ㍖; ㍖; レントゲン; レントケ◌゙ン; ) SQUARE RENTOGEN
+3357;3357;3357;30EF 30C3 30C8;30EF 30C3 30C8; # (㍗; ㍗; ㍗; ワット; ワット; ) SQUARE WATTO
+3358;3358;3358;0030 70B9;0030 70B9; # (㍘; ㍘; ㍘; 0点; 0点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR ZERO
+3359;3359;3359;0031 70B9;0031 70B9; # (㍙; ㍙; ㍙; 1点; 1点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR ONE
+335A;335A;335A;0032 70B9;0032 70B9; # (㍚; ㍚; ㍚; 2点; 2点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWO
+335B;335B;335B;0033 70B9;0033 70B9; # (㍛; ㍛; ㍛; 3点; 3点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR THREE
+335C;335C;335C;0034 70B9;0034 70B9; # (㍜; ㍜; ㍜; 4点; 4点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FOUR
+335D;335D;335D;0035 70B9;0035 70B9; # (㍝; ㍝; ㍝; 5点; 5点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FIVE
+335E;335E;335E;0036 70B9;0036 70B9; # (㍞; ㍞; ㍞; 6点; 6点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SIX
+335F;335F;335F;0037 70B9;0037 70B9; # (㍟; ㍟; ㍟; 7点; 7点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SEVEN
+3360;3360;3360;0038 70B9;0038 70B9; # (㍠; ㍠; ㍠; 8点; 8点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR EIGHT
+3361;3361;3361;0039 70B9;0039 70B9; # (㍡; ㍡; ㍡; 9点; 9点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR NINE
+3362;3362;3362;0031 0030 70B9;0031 0030 70B9; # (㍢; ㍢; ㍢; 10点; 10点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TEN
+3363;3363;3363;0031 0031 70B9;0031 0031 70B9; # (㍣; ㍣; ㍣; 11点; 11点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR ELEVEN
+3364;3364;3364;0031 0032 70B9;0031 0032 70B9; # (㍤; ㍤; ㍤; 12点; 12点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWELVE
+3365;3365;3365;0031 0033 70B9;0031 0033 70B9; # (㍥; ㍥; ㍥; 13点; 13点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR THIRTEEN
+3366;3366;3366;0031 0034 70B9;0031 0034 70B9; # (㍦; ㍦; ㍦; 14点; 14点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FOURTEEN
+3367;3367;3367;0031 0035 70B9;0031 0035 70B9; # (㍧; ㍧; ㍧; 15点; 15点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FIFTEEN
+3368;3368;3368;0031 0036 70B9;0031 0036 70B9; # (㍨; ㍨; ㍨; 16点; 16点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SIXTEEN
+3369;3369;3369;0031 0037 70B9;0031 0037 70B9; # (㍩; ㍩; ㍩; 17点; 17点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SEVENTEEN
+336A;336A;336A;0031 0038 70B9;0031 0038 70B9; # (㍪; ㍪; ㍪; 18点; 18点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR EIGHTEEN
+336B;336B;336B;0031 0039 70B9;0031 0039 70B9; # (㍫; ㍫; ㍫; 19点; 19点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR NINETEEN
+336C;336C;336C;0032 0030 70B9;0032 0030 70B9; # (㍬; ㍬; ㍬; 20点; 20点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY
+336D;336D;336D;0032 0031 70B9;0032 0031 70B9; # (㍭; ㍭; ㍭; 21点; 21点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-ONE
+336E;336E;336E;0032 0032 70B9;0032 0032 70B9; # (㍮; ㍮; ㍮; 22点; 22点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-TWO
+336F;336F;336F;0032 0033 70B9;0032 0033 70B9; # (㍯; ㍯; ㍯; 23点; 23点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-THREE
+3370;3370;3370;0032 0034 70B9;0032 0034 70B9; # (㍰; ㍰; ㍰; 24点; 24点; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-FOUR
+3371;3371;3371;0068 0050 0061;0068 0050 0061; # (㍱; ㍱; ㍱; hPa; hPa; ) SQUARE HPA
+3372;3372;3372;0064 0061;0064 0061; # (㍲; ㍲; ㍲; da; da; ) SQUARE DA
+3373;3373;3373;0041 0055;0041 0055; # (㍳; ㍳; ㍳; AU; AU; ) SQUARE AU
+3374;3374;3374;0062 0061 0072;0062 0061 0072; # (㍴; ㍴; ㍴; bar; bar; ) SQUARE BAR
+3375;3375;3375;006F 0056;006F 0056; # (㍵; ㍵; ㍵; oV; oV; ) SQUARE OV
+3376;3376;3376;0070 0063;0070 0063; # (㍶; ㍶; ㍶; pc; pc; ) SQUARE PC
+3377;3377;3377;0064 006D;0064 006D; # (㍷; ㍷; ㍷; dm; dm; ) SQUARE DM
+3378;3378;3378;0064 006D 0032;0064 006D 0032; # (㍸; ㍸; ㍸; dm2; dm2; ) SQUARE DM SQUARED
+3379;3379;3379;0064 006D 0033;0064 006D 0033; # (㍹; ㍹; ㍹; dm3; dm3; ) SQUARE DM CUBED
+337A;337A;337A;0049 0055;0049 0055; # (㍺; ㍺; ㍺; IU; IU; ) SQUARE IU
+337B;337B;337B;5E73 6210;5E73 6210; # (㍻; ㍻; ㍻; 平成; 平成; ) SQUARE ERA NAME HEISEI
+337C;337C;337C;662D 548C;662D 548C; # (㍼; ㍼; ㍼; 昭和; 昭和; ) SQUARE ERA NAME SYOUWA
+337D;337D;337D;5927 6B63;5927 6B63; # (㍽; ㍽; ㍽; 大正; 大正; ) SQUARE ERA NAME TAISYOU
+337E;337E;337E;660E 6CBB;660E 6CBB; # (㍾; ㍾; ㍾; 明治; 明治; ) SQUARE ERA NAME MEIZI
+337F;337F;337F;682A 5F0F 4F1A 793E;682A 5F0F 4F1A 793E; # (㍿; ㍿; ㍿; 株式会社; 株式会社; ) SQUARE CORPORATION
+3380;3380;3380;0070 0041;0070 0041; # (㎀; ㎀; ㎀; pA; pA; ) SQUARE PA AMPS
+3381;3381;3381;006E 0041;006E 0041; # (㎁; ㎁; ㎁; nA; nA; ) SQUARE NA
+3382;3382;3382;03BC 0041;03BC 0041; # (㎂; ㎂; ㎂; μA; μA; ) SQUARE MU A
+3383;3383;3383;006D 0041;006D 0041; # (㎃; ㎃; ㎃; mA; mA; ) SQUARE MA
+3384;3384;3384;006B 0041;006B 0041; # (㎄; ㎄; ㎄; kA; kA; ) SQUARE KA
+3385;3385;3385;004B 0042;004B 0042; # (㎅; ㎅; ㎅; KB; KB; ) SQUARE KB
+3386;3386;3386;004D 0042;004D 0042; # (㎆; ㎆; ㎆; MB; MB; ) SQUARE MB
+3387;3387;3387;0047 0042;0047 0042; # (㎇; ㎇; ㎇; GB; GB; ) SQUARE GB
+3388;3388;3388;0063 0061 006C;0063 0061 006C; # (㎈; ㎈; ㎈; cal; cal; ) SQUARE CAL
+3389;3389;3389;006B 0063 0061 006C;006B 0063 0061 006C; # (㎉; ㎉; ㎉; kcal; kcal; ) SQUARE KCAL
+338A;338A;338A;0070 0046;0070 0046; # (㎊; ㎊; ㎊; pF; pF; ) SQUARE PF
+338B;338B;338B;006E 0046;006E 0046; # (㎋; ㎋; ㎋; nF; nF; ) SQUARE NF
+338C;338C;338C;03BC 0046;03BC 0046; # (㎌; ㎌; ㎌; μF; μF; ) SQUARE MU F
+338D;338D;338D;03BC 0067;03BC 0067; # (㎍; ㎍; ㎍; μg; μg; ) SQUARE MU G
+338E;338E;338E;006D 0067;006D 0067; # (㎎; ㎎; ㎎; mg; mg; ) SQUARE MG
+338F;338F;338F;006B 0067;006B 0067; # (㎏; ㎏; ㎏; kg; kg; ) SQUARE KG
+3390;3390;3390;0048 007A;0048 007A; # (㎐; ㎐; ㎐; Hz; Hz; ) SQUARE HZ
+3391;3391;3391;006B 0048 007A;006B 0048 007A; # (㎑; ㎑; ㎑; kHz; kHz; ) SQUARE KHZ
+3392;3392;3392;004D 0048 007A;004D 0048 007A; # (㎒; ㎒; ㎒; MHz; MHz; ) SQUARE MHZ
+3393;3393;3393;0047 0048 007A;0047 0048 007A; # (㎓; ㎓; ㎓; GHz; GHz; ) SQUARE GHZ
+3394;3394;3394;0054 0048 007A;0054 0048 007A; # (㎔; ㎔; ㎔; THz; THz; ) SQUARE THZ
+3395;3395;3395;03BC 006C;03BC 006C; # (㎕; ㎕; ㎕; μl; μl; ) SQUARE MU L
+3396;3396;3396;006D 006C;006D 006C; # (㎖; ㎖; ㎖; ml; ml; ) SQUARE ML
+3397;3397;3397;0064 006C;0064 006C; # (㎗; ㎗; ㎗; dl; dl; ) SQUARE DL
+3398;3398;3398;006B 006C;006B 006C; # (㎘; ㎘; ㎘; kl; kl; ) SQUARE KL
+3399;3399;3399;0066 006D;0066 006D; # (㎙; ㎙; ㎙; fm; fm; ) SQUARE FM
+339A;339A;339A;006E 006D;006E 006D; # (㎚; ㎚; ㎚; nm; nm; ) SQUARE NM
+339B;339B;339B;03BC 006D;03BC 006D; # (㎛; ㎛; ㎛; μm; μm; ) SQUARE MU M
+339C;339C;339C;006D 006D;006D 006D; # (㎜; ㎜; ㎜; mm; mm; ) SQUARE MM
+339D;339D;339D;0063 006D;0063 006D; # (㎝; ㎝; ㎝; cm; cm; ) SQUARE CM
+339E;339E;339E;006B 006D;006B 006D; # (㎞; ㎞; ㎞; km; km; ) SQUARE KM
+339F;339F;339F;006D 006D 0032;006D 006D 0032; # (㎟; ㎟; ㎟; mm2; mm2; ) SQUARE MM SQUARED
+33A0;33A0;33A0;0063 006D 0032;0063 006D 0032; # (㎠; ㎠; ㎠; cm2; cm2; ) SQUARE CM SQUARED
+33A1;33A1;33A1;006D 0032;006D 0032; # (㎡; ㎡; ㎡; m2; m2; ) SQUARE M SQUARED
+33A2;33A2;33A2;006B 006D 0032;006B 006D 0032; # (㎢; ㎢; ㎢; km2; km2; ) SQUARE KM SQUARED
+33A3;33A3;33A3;006D 006D 0033;006D 006D 0033; # (㎣; ㎣; ㎣; mm3; mm3; ) SQUARE MM CUBED
+33A4;33A4;33A4;0063 006D 0033;0063 006D 0033; # (㎤; ㎤; ㎤; cm3; cm3; ) SQUARE CM CUBED
+33A5;33A5;33A5;006D 0033;006D 0033; # (㎥; ㎥; ㎥; m3; m3; ) SQUARE M CUBED
+33A6;33A6;33A6;006B 006D 0033;006B 006D 0033; # (㎦; ㎦; ㎦; km3; km3; ) SQUARE KM CUBED
+33A7;33A7;33A7;006D 2215 0073;006D 2215 0073; # (㎧; ㎧; ㎧; m∕s; m∕s; ) SQUARE M OVER S
+33A8;33A8;33A8;006D 2215 0073 0032;006D 2215 0073 0032; # (㎨; ㎨; ㎨; m∕s2; m∕s2; ) SQUARE M OVER S SQUARED
+33A9;33A9;33A9;0050 0061;0050 0061; # (㎩; ㎩; ㎩; Pa; Pa; ) SQUARE PA
+33AA;33AA;33AA;006B 0050 0061;006B 0050 0061; # (㎪; ㎪; ㎪; kPa; kPa; ) SQUARE KPA
+33AB;33AB;33AB;004D 0050 0061;004D 0050 0061; # (㎫; ㎫; ㎫; MPa; MPa; ) SQUARE MPA
+33AC;33AC;33AC;0047 0050 0061;0047 0050 0061; # (㎬; ㎬; ㎬; GPa; GPa; ) SQUARE GPA
+33AD;33AD;33AD;0072 0061 0064;0072 0061 0064; # (㎭; ㎭; ㎭; rad; rad; ) SQUARE RAD
+33AE;33AE;33AE;0072 0061 0064 2215 0073;0072 0061 0064 2215 0073; # (㎮; ㎮; ㎮; rad∕s; rad∕s; ) SQUARE RAD OVER S
+33AF;33AF;33AF;0072 0061 0064 2215 0073 0032;0072 0061 0064 2215 0073 0032; # (㎯; ㎯; ㎯; rad∕s2; rad∕s2; ) SQUARE RAD OVER S SQUARED
+33B0;33B0;33B0;0070 0073;0070 0073; # (㎰; ㎰; ㎰; ps; ps; ) SQUARE PS
+33B1;33B1;33B1;006E 0073;006E 0073; # (㎱; ㎱; ㎱; ns; ns; ) SQUARE NS
+33B2;33B2;33B2;03BC 0073;03BC 0073; # (㎲; ㎲; ㎲; μs; μs; ) SQUARE MU S
+33B3;33B3;33B3;006D 0073;006D 0073; # (㎳; ㎳; ㎳; ms; ms; ) SQUARE MS
+33B4;33B4;33B4;0070 0056;0070 0056; # (㎴; ㎴; ㎴; pV; pV; ) SQUARE PV
+33B5;33B5;33B5;006E 0056;006E 0056; # (㎵; ㎵; ㎵; nV; nV; ) SQUARE NV
+33B6;33B6;33B6;03BC 0056;03BC 0056; # (㎶; ㎶; ㎶; μV; μV; ) SQUARE MU V
+33B7;33B7;33B7;006D 0056;006D 0056; # (㎷; ㎷; ㎷; mV; mV; ) SQUARE MV
+33B8;33B8;33B8;006B 0056;006B 0056; # (㎸; ㎸; ㎸; kV; kV; ) SQUARE KV
+33B9;33B9;33B9;004D 0056;004D 0056; # (㎹; ㎹; ㎹; MV; MV; ) SQUARE MV MEGA
+33BA;33BA;33BA;0070 0057;0070 0057; # (㎺; ㎺; ㎺; pW; pW; ) SQUARE PW
+33BB;33BB;33BB;006E 0057;006E 0057; # (㎻; ㎻; ㎻; nW; nW; ) SQUARE NW
+33BC;33BC;33BC;03BC 0057;03BC 0057; # (㎼; ㎼; ㎼; μW; μW; ) SQUARE MU W
+33BD;33BD;33BD;006D 0057;006D 0057; # (㎽; ㎽; ㎽; mW; mW; ) SQUARE MW
+33BE;33BE;33BE;006B 0057;006B 0057; # (㎾; ㎾; ㎾; kW; kW; ) SQUARE KW
+33BF;33BF;33BF;004D 0057;004D 0057; # (㎿; ㎿; ㎿; MW; MW; ) SQUARE MW MEGA
+33C0;33C0;33C0;006B 03A9;006B 03A9; # (㏀; ㏀; ㏀; kΩ; kΩ; ) SQUARE K OHM
+33C1;33C1;33C1;004D 03A9;004D 03A9; # (㏁; ㏁; ㏁; MΩ; MΩ; ) SQUARE M OHM
+33C2;33C2;33C2;0061 002E 006D 002E;0061 002E 006D 002E; # (㏂; ㏂; ㏂; a.m.; a.m.; ) SQUARE AM
+33C3;33C3;33C3;0042 0071;0042 0071; # (㏃; ㏃; ㏃; Bq; Bq; ) SQUARE BQ
+33C4;33C4;33C4;0063 0063;0063 0063; # (㏄; ㏄; ㏄; cc; cc; ) SQUARE CC
+33C5;33C5;33C5;0063 0064;0063 0064; # (㏅; ㏅; ㏅; cd; cd; ) SQUARE CD
+33C6;33C6;33C6;0043 2215 006B 0067;0043 2215 006B 0067; # (㏆; ㏆; ㏆; C∕kg; C∕kg; ) SQUARE C OVER KG
+33C7;33C7;33C7;0043 006F 002E;0043 006F 002E; # (㏇; ㏇; ㏇; Co.; Co.; ) SQUARE CO
+33C8;33C8;33C8;0064 0042;0064 0042; # (㏈; ㏈; ㏈; dB; dB; ) SQUARE DB
+33C9;33C9;33C9;0047 0079;0047 0079; # (㏉; ㏉; ㏉; Gy; Gy; ) SQUARE GY
+33CA;33CA;33CA;0068 0061;0068 0061; # (㏊; ㏊; ㏊; ha; ha; ) SQUARE HA
+33CB;33CB;33CB;0048 0050;0048 0050; # (㏋; ㏋; ㏋; HP; HP; ) SQUARE HP
+33CC;33CC;33CC;0069 006E;0069 006E; # (㏌; ㏌; ㏌; in; in; ) SQUARE IN
+33CD;33CD;33CD;004B 004B;004B 004B; # (㏍; ㏍; ㏍; KK; KK; ) SQUARE KK
+33CE;33CE;33CE;004B 004D;004B 004D; # (㏎; ㏎; ㏎; KM; KM; ) SQUARE KM CAPITAL
+33CF;33CF;33CF;006B 0074;006B 0074; # (㏏; ㏏; ㏏; kt; kt; ) SQUARE KT
+33D0;33D0;33D0;006C 006D;006C 006D; # (㏐; ㏐; ㏐; lm; lm; ) SQUARE LM
+33D1;33D1;33D1;006C 006E;006C 006E; # (㏑; ㏑; ㏑; ln; ln; ) SQUARE LN
+33D2;33D2;33D2;006C 006F 0067;006C 006F 0067; # (㏒; ㏒; ㏒; log; log; ) SQUARE LOG
+33D3;33D3;33D3;006C 0078;006C 0078; # (㏓; ㏓; ㏓; lx; lx; ) SQUARE LX
+33D4;33D4;33D4;006D 0062;006D 0062; # (㏔; ㏔; ㏔; mb; mb; ) SQUARE MB SMALL
+33D5;33D5;33D5;006D 0069 006C;006D 0069 006C; # (㏕; ㏕; ㏕; mil; mil; ) SQUARE MIL
+33D6;33D6;33D6;006D 006F 006C;006D 006F 006C; # (㏖; ㏖; ㏖; mol; mol; ) SQUARE MOL
+33D7;33D7;33D7;0050 0048;0050 0048; # (㏗; ㏗; ㏗; PH; PH; ) SQUARE PH
+33D8;33D8;33D8;0070 002E 006D 002E;0070 002E 006D 002E; # (㏘; ㏘; ㏘; p.m.; p.m.; ) SQUARE PM
+33D9;33D9;33D9;0050 0050 004D;0050 0050 004D; # (㏙; ㏙; ㏙; PPM; PPM; ) SQUARE PPM
+33DA;33DA;33DA;0050 0052;0050 0052; # (㏚; ㏚; ㏚; PR; PR; ) SQUARE PR
+33DB;33DB;33DB;0073 0072;0073 0072; # (㏛; ㏛; ㏛; sr; sr; ) SQUARE SR
+33DC;33DC;33DC;0053 0076;0053 0076; # (㏜; ㏜; ㏜; Sv; Sv; ) SQUARE SV
+33DD;33DD;33DD;0057 0062;0057 0062; # (㏝; ㏝; ㏝; Wb; Wb; ) SQUARE WB
+33DE;33DE;33DE;0056 2215 006D;0056 2215 006D; # (㏞; ㏞; ㏞; V∕m; V∕m; ) SQUARE V OVER M
+33DF;33DF;33DF;0041 2215 006D;0041 2215 006D; # (㏟; ㏟; ㏟; A∕m; A∕m; ) SQUARE A OVER M
+33E0;33E0;33E0;0031 65E5;0031 65E5; # (㏠; ㏠; ㏠; 1日; 1日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY ONE
+33E1;33E1;33E1;0032 65E5;0032 65E5; # (㏡; ㏡; ㏡; 2日; 2日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWO
+33E2;33E2;33E2;0033 65E5;0033 65E5; # (㏢; ㏢; ㏢; 3日; 3日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THREE
+33E3;33E3;33E3;0034 65E5;0034 65E5; # (㏣; ㏣; ㏣; 4日; 4日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FOUR
+33E4;33E4;33E4;0035 65E5;0035 65E5; # (㏤; ㏤; ㏤; 5日; 5日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FIVE
+33E5;33E5;33E5;0036 65E5;0036 65E5; # (㏥; ㏥; ㏥; 6日; 6日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SIX
+33E6;33E6;33E6;0037 65E5;0037 65E5; # (㏦; ㏦; ㏦; 7日; 7日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SEVEN
+33E7;33E7;33E7;0038 65E5;0038 65E5; # (㏧; ㏧; ㏧; 8日; 8日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY EIGHT
+33E8;33E8;33E8;0039 65E5;0039 65E5; # (㏨; ㏨; ㏨; 9日; 9日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY NINE
+33E9;33E9;33E9;0031 0030 65E5;0031 0030 65E5; # (㏩; ㏩; ㏩; 10日; 10日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TEN
+33EA;33EA;33EA;0031 0031 65E5;0031 0031 65E5; # (㏪; ㏪; ㏪; 11日; 11日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY ELEVEN
+33EB;33EB;33EB;0031 0032 65E5;0031 0032 65E5; # (㏫; ㏫; ㏫; 12日; 12日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWELVE
+33EC;33EC;33EC;0031 0033 65E5;0031 0033 65E5; # (㏬; ㏬; ㏬; 13日; 13日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THIRTEEN
+33ED;33ED;33ED;0031 0034 65E5;0031 0034 65E5; # (㏭; ㏭; ㏭; 14日; 14日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FOURTEEN
+33EE;33EE;33EE;0031 0035 65E5;0031 0035 65E5; # (㏮; ㏮; ㏮; 15日; 15日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FIFTEEN
+33EF;33EF;33EF;0031 0036 65E5;0031 0036 65E5; # (㏯; ㏯; ㏯; 16日; 16日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SIXTEEN
+33F0;33F0;33F0;0031 0037 65E5;0031 0037 65E5; # (㏰; ㏰; ㏰; 17日; 17日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SEVENTEEN
+33F1;33F1;33F1;0031 0038 65E5;0031 0038 65E5; # (㏱; ㏱; ㏱; 18日; 18日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY EIGHTEEN
+33F2;33F2;33F2;0031 0039 65E5;0031 0039 65E5; # (㏲; ㏲; ㏲; 19日; 19日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY NINETEEN
+33F3;33F3;33F3;0032 0030 65E5;0032 0030 65E5; # (㏳; ㏳; ㏳; 20日; 20日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY
+33F4;33F4;33F4;0032 0031 65E5;0032 0031 65E5; # (㏴; ㏴; ㏴; 21日; 21日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-ONE
+33F5;33F5;33F5;0032 0032 65E5;0032 0032 65E5; # (㏵; ㏵; ㏵; 22日; 22日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-TWO
+33F6;33F6;33F6;0032 0033 65E5;0032 0033 65E5; # (㏶; ㏶; ㏶; 23日; 23日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-THREE
+33F7;33F7;33F7;0032 0034 65E5;0032 0034 65E5; # (㏷; ㏷; ㏷; 24日; 24日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-FOUR
+33F8;33F8;33F8;0032 0035 65E5;0032 0035 65E5; # (㏸; ㏸; ㏸; 25日; 25日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-FIVE
+33F9;33F9;33F9;0032 0036 65E5;0032 0036 65E5; # (㏹; ㏹; ㏹; 26日; 26日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-SIX
+33FA;33FA;33FA;0032 0037 65E5;0032 0037 65E5; # (㏺; ㏺; ㏺; 27日; 27日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-SEVEN
+33FB;33FB;33FB;0032 0038 65E5;0032 0038 65E5; # (㏻; ㏻; ㏻; 28日; 28日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-EIGHT
+33FC;33FC;33FC;0032 0039 65E5;0032 0039 65E5; # (㏼; ㏼; ㏼; 29日; 29日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-NINE
+33FD;33FD;33FD;0033 0030 65E5;0033 0030 65E5; # (㏽; ㏽; ㏽; 30日; 30日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THIRTY
+33FE;33FE;33FE;0033 0031 65E5;0033 0031 65E5; # (㏾; ㏾; ㏾; 31日; 31日; ) IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THIRTY-ONE
+33FF;33FF;33FF;0067 0061 006C;0067 0061 006C; # (㏿; ㏿; ㏿; gal; gal; ) SQUARE GAL
+AC00;AC00;1100 1161;AC00;1100 1161; # (가; 가; 가; 가; 가; ) HANGUL SYLLABLE GA
+AC01;AC01;1100 1161 11A8;AC01;1100 1161 11A8; # (각; 각; 각; 각; 각; ) HANGUL SYLLABLE GAG
+AC02;AC02;1100 1161 11A9;AC02;1100 1161 11A9; # (갂; 갂; 갂; 갂; 갂; ) HANGUL SYLLABLE GAGG
+AC03;AC03;1100 1161 11AA;AC03;1100 1161 11AA; # (갃; 갃; 갃; 갃; 갃; ) HANGUL SYLLABLE GAGS
+AC04;AC04;1100 1161 11AB;AC04;1100 1161 11AB; # (간; 간; 간; 간; 간; ) HANGUL SYLLABLE GAN
+AC05;AC05;1100 1161 11AC;AC05;1100 1161 11AC; # (갅; 갅; 갅; 갅; 갅; ) HANGUL SYLLABLE GANJ
+AC06;AC06;1100 1161 11AD;AC06;1100 1161 11AD; # (갆; 갆; 갆; 갆; 갆; ) HANGUL SYLLABLE GANH
+AC07;AC07;1100 1161 11AE;AC07;1100 1161 11AE; # (갇; 갇; 갇; 갇; 갇; ) HANGUL SYLLABLE GAD
+AC08;AC08;1100 1161 11AF;AC08;1100 1161 11AF; # (갈; 갈; 갈; 갈; 갈; ) HANGUL SYLLABLE GAL
+AC09;AC09;1100 1161 11B0;AC09;1100 1161 11B0; # (갉; 갉; 갉; 갉; 갉; ) HANGUL SYLLABLE GALG
+AC0A;AC0A;1100 1161 11B1;AC0A;1100 1161 11B1; # (갊; 갊; 갊; 갊; 갊; ) HANGUL SYLLABLE GALM
+AC0B;AC0B;1100 1161 11B2;AC0B;1100 1161 11B2; # (갋; 갋; 갋; 갋; 갋; ) HANGUL SYLLABLE GALB
+AC0C;AC0C;1100 1161 11B3;AC0C;1100 1161 11B3; # (갌; 갌; 갌; 갌; 갌; ) HANGUL SYLLABLE GALS
+AC0D;AC0D;1100 1161 11B4;AC0D;1100 1161 11B4; # (갍; 갍; 갍; 갍; 갍; ) HANGUL SYLLABLE GALT
+AC0E;AC0E;1100 1161 11B5;AC0E;1100 1161 11B5; # (갎; 갎; 갎; 갎; 갎; ) HANGUL SYLLABLE GALP
+AC0F;AC0F;1100 1161 11B6;AC0F;1100 1161 11B6; # (갏; 갏; 갏; 갏; 갏; ) HANGUL SYLLABLE GALH
+AC10;AC10;1100 1161 11B7;AC10;1100 1161 11B7; # (감; 감; 감; 감; 감; ) HANGUL SYLLABLE GAM
+AC11;AC11;1100 1161 11B8;AC11;1100 1161 11B8; # (갑; 갑; 갑; 갑; 갑; ) HANGUL SYLLABLE GAB
+AC12;AC12;1100 1161 11B9;AC12;1100 1161 11B9; # (값; 값; 값; 값; 값; ) HANGUL SYLLABLE GABS
+AC13;AC13;1100 1161 11BA;AC13;1100 1161 11BA; # (갓; 갓; 갓; 갓; 갓; ) HANGUL SYLLABLE GAS
+AC14;AC14;1100 1161 11BB;AC14;1100 1161 11BB; # (갔; 갔; 갔; 갔; 갔; ) HANGUL SYLLABLE GASS
+AC15;AC15;1100 1161 11BC;AC15;1100 1161 11BC; # (강; 강; 강; 강; 강; ) HANGUL SYLLABLE GANG
+AC16;AC16;1100 1161 11BD;AC16;1100 1161 11BD; # (갖; 갖; 갖; 갖; 갖; ) HANGUL SYLLABLE GAJ
+AC17;AC17;1100 1161 11BE;AC17;1100 1161 11BE; # (갗; 갗; 갗; 갗; 갗; ) HANGUL SYLLABLE GAC
+AC18;AC18;1100 1161 11BF;AC18;1100 1161 11BF; # (갘; 갘; 갘; 갘; 갘; ) HANGUL SYLLABLE GAK
+AC19;AC19;1100 1161 11C0;AC19;1100 1161 11C0; # (같; 같; 같; 같; 같; ) HANGUL SYLLABLE GAT
+AC1A;AC1A;1100 1161 11C1;AC1A;1100 1161 11C1; # (갚; 갚; 갚; 갚; 갚; ) HANGUL SYLLABLE GAP
+AC1B;AC1B;1100 1161 11C2;AC1B;1100 1161 11C2; # (갛; 갛; 갛; 갛; 갛; ) HANGUL SYLLABLE GAH
+AC1C;AC1C;1100 1162;AC1C;1100 1162; # (개; 개; 개; 개; 개; ) HANGUL SYLLABLE GAE
+AC1D;AC1D;1100 1162 11A8;AC1D;1100 1162 11A8; # (객; 객; 객; 객; 객; ) HANGUL SYLLABLE GAEG
+AC1E;AC1E;1100 1162 11A9;AC1E;1100 1162 11A9; # (갞; 갞; 갞; 갞; 갞; ) HANGUL SYLLABLE GAEGG
+AC1F;AC1F;1100 1162 11AA;AC1F;1100 1162 11AA; # (갟; 갟; 갟; 갟; 갟; ) HANGUL SYLLABLE GAEGS
+AC20;AC20;1100 1162 11AB;AC20;1100 1162 11AB; # (갠; 갠; 갠; 갠; 갠; ) HANGUL SYLLABLE GAEN
+AC21;AC21;1100 1162 11AC;AC21;1100 1162 11AC; # (갡; 갡; 갡; 갡; 갡; ) HANGUL SYLLABLE GAENJ
+AC22;AC22;1100 1162 11AD;AC22;1100 1162 11AD; # (갢; 갢; 갢; 갢; 갢; ) HANGUL SYLLABLE GAENH
+AC23;AC23;1100 1162 11AE;AC23;1100 1162 11AE; # (갣; 갣; 갣; 갣; 갣; ) HANGUL SYLLABLE GAED
+AC24;AC24;1100 1162 11AF;AC24;1100 1162 11AF; # (갤; 갤; 갤; 갤; 갤; ) HANGUL SYLLABLE GAEL
+AC25;AC25;1100 1162 11B0;AC25;1100 1162 11B0; # (갥; 갥; 갥; 갥; 갥; ) HANGUL SYLLABLE GAELG
+AC26;AC26;1100 1162 11B1;AC26;1100 1162 11B1; # (갦; 갦; 갦; 갦; 갦; ) HANGUL SYLLABLE GAELM
+AC27;AC27;1100 1162 11B2;AC27;1100 1162 11B2; # (갧; 갧; 갧; 갧; 갧; ) HANGUL SYLLABLE GAELB
+AC28;AC28;1100 1162 11B3;AC28;1100 1162 11B3; # (갨; 갨; 갨; 갨; 갨; ) HANGUL SYLLABLE GAELS
+AC29;AC29;1100 1162 11B4;AC29;1100 1162 11B4; # (갩; 갩; 갩; 갩; 갩; ) HANGUL SYLLABLE GAELT
+AC2A;AC2A;1100 1162 11B5;AC2A;1100 1162 11B5; # (갪; 갪; 갪; 갪; 갪; ) HANGUL SYLLABLE GAELP
+AC2B;AC2B;1100 1162 11B6;AC2B;1100 1162 11B6; # (갫; 갫; 갫; 갫; 갫; ) HANGUL SYLLABLE GAELH
+AC2C;AC2C;1100 1162 11B7;AC2C;1100 1162 11B7; # (갬; 갬; 갬; 갬; 갬; ) HANGUL SYLLABLE GAEM
+AC2D;AC2D;1100 1162 11B8;AC2D;1100 1162 11B8; # (갭; 갭; 갭; 갭; 갭; ) HANGUL SYLLABLE GAEB
+AC2E;AC2E;1100 1162 11B9;AC2E;1100 1162 11B9; # (갮; 갮; 갮; 갮; 갮; ) HANGUL SYLLABLE GAEBS
+AC2F;AC2F;1100 1162 11BA;AC2F;1100 1162 11BA; # (갯; 갯; 갯; 갯; 갯; ) HANGUL SYLLABLE GAES
+AC30;AC30;1100 1162 11BB;AC30;1100 1162 11BB; # (갰; 갰; 갰; 갰; 갰; ) HANGUL SYLLABLE GAESS
+AC31;AC31;1100 1162 11BC;AC31;1100 1162 11BC; # (갱; 갱; 갱; 갱; 갱; ) HANGUL SYLLABLE GAENG
+AC32;AC32;1100 1162 11BD;AC32;1100 1162 11BD; # (갲; 갲; 갲; 갲; 갲; ) HANGUL SYLLABLE GAEJ
+AC33;AC33;1100 1162 11BE;AC33;1100 1162 11BE; # (갳; 갳; 갳; 갳; 갳; ) HANGUL SYLLABLE GAEC
+AC34;AC34;1100 1162 11BF;AC34;1100 1162 11BF; # (갴; 갴; 갴; 갴; 갴; ) HANGUL SYLLABLE GAEK
+AC35;AC35;1100 1162 11C0;AC35;1100 1162 11C0; # (갵; 갵; 갵; 갵; 갵; ) HANGUL SYLLABLE GAET
+AC36;AC36;1100 1162 11C1;AC36;1100 1162 11C1; # (갶; 갶; 갶; 갶; 갶; ) HANGUL SYLLABLE GAEP
+AC37;AC37;1100 1162 11C2;AC37;1100 1162 11C2; # (갷; 갷; 갷; 갷; 갷; ) HANGUL SYLLABLE GAEH
+AC38;AC38;1100 1163;AC38;1100 1163; # (갸; 갸; 갸; 갸; 갸; ) HANGUL SYLLABLE GYA
+AC39;AC39;1100 1163 11A8;AC39;1100 1163 11A8; # (갹; 갹; 갹; 갹; 갹; ) HANGUL SYLLABLE GYAG
+AC3A;AC3A;1100 1163 11A9;AC3A;1100 1163 11A9; # (갺; 갺; 갺; 갺; 갺; ) HANGUL SYLLABLE GYAGG
+AC3B;AC3B;1100 1163 11AA;AC3B;1100 1163 11AA; # (갻; 갻; 갻; 갻; 갻; ) HANGUL SYLLABLE GYAGS
+AC3C;AC3C;1100 1163 11AB;AC3C;1100 1163 11AB; # (갼; 갼; 갼; 갼; 갼; ) HANGUL SYLLABLE GYAN
+AC3D;AC3D;1100 1163 11AC;AC3D;1100 1163 11AC; # (갽; 갽; 갽; 갽; 갽; ) HANGUL SYLLABLE GYANJ
+AC3E;AC3E;1100 1163 11AD;AC3E;1100 1163 11AD; # (갾; 갾; 갾; 갾; 갾; ) HANGUL SYLLABLE GYANH
+AC3F;AC3F;1100 1163 11AE;AC3F;1100 1163 11AE; # (갿; 갿; 갿; 갿; 갿; ) HANGUL SYLLABLE GYAD
+AC40;AC40;1100 1163 11AF;AC40;1100 1163 11AF; # (걀; 걀; 걀; 걀; 걀; ) HANGUL SYLLABLE GYAL
+AC41;AC41;1100 1163 11B0;AC41;1100 1163 11B0; # (걁; 걁; 걁; 걁; 걁; ) HANGUL SYLLABLE GYALG
+AC42;AC42;1100 1163 11B1;AC42;1100 1163 11B1; # (걂; 걂; 걂; 걂; 걂; ) HANGUL SYLLABLE GYALM
+AC43;AC43;1100 1163 11B2;AC43;1100 1163 11B2; # (걃; 걃; 걃; 걃; 걃; ) HANGUL SYLLABLE GYALB
+AC44;AC44;1100 1163 11B3;AC44;1100 1163 11B3; # (걄; 걄; 걄; 걄; 걄; ) HANGUL SYLLABLE GYALS
+AC45;AC45;1100 1163 11B4;AC45;1100 1163 11B4; # (걅; 걅; 걅; 걅; 걅; ) HANGUL SYLLABLE GYALT
+AC46;AC46;1100 1163 11B5;AC46;1100 1163 11B5; # (걆; 걆; 걆; 걆; 걆; ) HANGUL SYLLABLE GYALP
+AC47;AC47;1100 1163 11B6;AC47;1100 1163 11B6; # (걇; 걇; 걇; 걇; 걇; ) HANGUL SYLLABLE GYALH
+AC48;AC48;1100 1163 11B7;AC48;1100 1163 11B7; # (걈; 걈; 걈; 걈; 걈; ) HANGUL SYLLABLE GYAM
+AC49;AC49;1100 1163 11B8;AC49;1100 1163 11B8; # (걉; 걉; 걉; 걉; 걉; ) HANGUL SYLLABLE GYAB
+AC4A;AC4A;1100 1163 11B9;AC4A;1100 1163 11B9; # (걊; 걊; 걊; 걊; 걊; ) HANGUL SYLLABLE GYABS
+AC4B;AC4B;1100 1163 11BA;AC4B;1100 1163 11BA; # (걋; 걋; 걋; 걋; 걋; ) HANGUL SYLLABLE GYAS
+AC4C;AC4C;1100 1163 11BB;AC4C;1100 1163 11BB; # (걌; 걌; 걌; 걌; 걌; ) HANGUL SYLLABLE GYASS
+AC4D;AC4D;1100 1163 11BC;AC4D;1100 1163 11BC; # (걍; 걍; 걍; 걍; 걍; ) HANGUL SYLLABLE GYANG
+AC4E;AC4E;1100 1163 11BD;AC4E;1100 1163 11BD; # (걎; 걎; 걎; 걎; 걎; ) HANGUL SYLLABLE GYAJ
+AC4F;AC4F;1100 1163 11BE;AC4F;1100 1163 11BE; # (걏; 걏; 걏; 걏; 걏; ) HANGUL SYLLABLE GYAC
+AC50;AC50;1100 1163 11BF;AC50;1100 1163 11BF; # (걐; 걐; 걐; 걐; 걐; ) HANGUL SYLLABLE GYAK
+AC51;AC51;1100 1163 11C0;AC51;1100 1163 11C0; # (걑; 걑; 걑; 걑; 걑; ) HANGUL SYLLABLE GYAT
+AC52;AC52;1100 1163 11C1;AC52;1100 1163 11C1; # (걒; 걒; 걒; 걒; 걒; ) HANGUL SYLLABLE GYAP
+AC53;AC53;1100 1163 11C2;AC53;1100 1163 11C2; # (걓; 걓; 걓; 걓; 걓; ) HANGUL SYLLABLE GYAH
+AC54;AC54;1100 1164;AC54;1100 1164; # (걔; 걔; 걔; 걔; 걔; ) HANGUL SYLLABLE GYAE
+AC55;AC55;1100 1164 11A8;AC55;1100 1164 11A8; # (걕; 걕; 걕; 걕; 걕; ) HANGUL SYLLABLE GYAEG
+AC56;AC56;1100 1164 11A9;AC56;1100 1164 11A9; # (걖; 걖; 걖; 걖; 걖; ) HANGUL SYLLABLE GYAEGG
+AC57;AC57;1100 1164 11AA;AC57;1100 1164 11AA; # (걗; 걗; 걗; 걗; 걗; ) HANGUL SYLLABLE GYAEGS
+AC58;AC58;1100 1164 11AB;AC58;1100 1164 11AB; # (걘; 걘; 걘; 걘; 걘; ) HANGUL SYLLABLE GYAEN
+AC59;AC59;1100 1164 11AC;AC59;1100 1164 11AC; # (걙; 걙; 걙; 걙; 걙; ) HANGUL SYLLABLE GYAENJ
+AC5A;AC5A;1100 1164 11AD;AC5A;1100 1164 11AD; # (걚; 걚; 걚; 걚; 걚; ) HANGUL SYLLABLE GYAENH
+AC5B;AC5B;1100 1164 11AE;AC5B;1100 1164 11AE; # (걛; 걛; 걛; 걛; 걛; ) HANGUL SYLLABLE GYAED
+AC5C;AC5C;1100 1164 11AF;AC5C;1100 1164 11AF; # (걜; 걜; 걜; 걜; 걜; ) HANGUL SYLLABLE GYAEL
+AC5D;AC5D;1100 1164 11B0;AC5D;1100 1164 11B0; # (걝; 걝; 걝; 걝; 걝; ) HANGUL SYLLABLE GYAELG
+AC5E;AC5E;1100 1164 11B1;AC5E;1100 1164 11B1; # (걞; 걞; 걞; 걞; 걞; ) HANGUL SYLLABLE GYAELM
+AC5F;AC5F;1100 1164 11B2;AC5F;1100 1164 11B2; # (걟; 걟; 걟; 걟; 걟; ) HANGUL SYLLABLE GYAELB
+AC60;AC60;1100 1164 11B3;AC60;1100 1164 11B3; # (걠; 걠; 걠; 걠; 걠; ) HANGUL SYLLABLE GYAELS
+AC61;AC61;1100 1164 11B4;AC61;1100 1164 11B4; # (걡; 걡; 걡; 걡; 걡; ) HANGUL SYLLABLE GYAELT
+AC62;AC62;1100 1164 11B5;AC62;1100 1164 11B5; # (걢; 걢; 걢; 걢; 걢; ) HANGUL SYLLABLE GYAELP
+AC63;AC63;1100 1164 11B6;AC63;1100 1164 11B6; # (걣; 걣; 걣; 걣; 걣; ) HANGUL SYLLABLE GYAELH
+AC64;AC64;1100 1164 11B7;AC64;1100 1164 11B7; # (걤; 걤; 걤; 걤; 걤; ) HANGUL SYLLABLE GYAEM
+AC65;AC65;1100 1164 11B8;AC65;1100 1164 11B8; # (걥; 걥; 걥; 걥; 걥; ) HANGUL SYLLABLE GYAEB
+AC66;AC66;1100 1164 11B9;AC66;1100 1164 11B9; # (걦; 걦; 걦; 걦; 걦; ) HANGUL SYLLABLE GYAEBS
+AC67;AC67;1100 1164 11BA;AC67;1100 1164 11BA; # (걧; 걧; 걧; 걧; 걧; ) HANGUL SYLLABLE GYAES
+AC68;AC68;1100 1164 11BB;AC68;1100 1164 11BB; # (걨; 걨; 걨; 걨; 걨; ) HANGUL SYLLABLE GYAESS
+AC69;AC69;1100 1164 11BC;AC69;1100 1164 11BC; # (걩; 걩; 걩; 걩; 걩; ) HANGUL SYLLABLE GYAENG
+AC6A;AC6A;1100 1164 11BD;AC6A;1100 1164 11BD; # (걪; 걪; 걪; 걪; 걪; ) HANGUL SYLLABLE GYAEJ
+AC6B;AC6B;1100 1164 11BE;AC6B;1100 1164 11BE; # (걫; 걫; 걫; 걫; 걫; ) HANGUL SYLLABLE GYAEC
+AC6C;AC6C;1100 1164 11BF;AC6C;1100 1164 11BF; # (걬; 걬; 걬; 걬; 걬; ) HANGUL SYLLABLE GYAEK
+AC6D;AC6D;1100 1164 11C0;AC6D;1100 1164 11C0; # (걭; 걭; 걭; 걭; 걭; ) HANGUL SYLLABLE GYAET
+AC6E;AC6E;1100 1164 11C1;AC6E;1100 1164 11C1; # (걮; 걮; 걮; 걮; 걮; ) HANGUL SYLLABLE GYAEP
+AC6F;AC6F;1100 1164 11C2;AC6F;1100 1164 11C2; # (걯; 걯; 걯; 걯; 걯; ) HANGUL SYLLABLE GYAEH
+AC70;AC70;1100 1165;AC70;1100 1165; # (거; 거; 거; 거; 거; ) HANGUL SYLLABLE GEO
+AC71;AC71;1100 1165 11A8;AC71;1100 1165 11A8; # (걱; 걱; 걱; 걱; 걱; ) HANGUL SYLLABLE GEOG
+AC72;AC72;1100 1165 11A9;AC72;1100 1165 11A9; # (걲; 걲; 걲; 걲; 걲; ) HANGUL SYLLABLE GEOGG
+AC73;AC73;1100 1165 11AA;AC73;1100 1165 11AA; # (걳; 걳; 걳; 걳; 걳; ) HANGUL SYLLABLE GEOGS
+AC74;AC74;1100 1165 11AB;AC74;1100 1165 11AB; # (건; 건; 건; 건; 건; ) HANGUL SYLLABLE GEON
+AC75;AC75;1100 1165 11AC;AC75;1100 1165 11AC; # (걵; 걵; 걵; 걵; 걵; ) HANGUL SYLLABLE GEONJ
+AC76;AC76;1100 1165 11AD;AC76;1100 1165 11AD; # (걶; 걶; 걶; 걶; 걶; ) HANGUL SYLLABLE GEONH
+AC77;AC77;1100 1165 11AE;AC77;1100 1165 11AE; # (걷; 걷; 걷; 걷; 걷; ) HANGUL SYLLABLE GEOD
+AC78;AC78;1100 1165 11AF;AC78;1100 1165 11AF; # (걸; 걸; 걸; 걸; 걸; ) HANGUL SYLLABLE GEOL
+AC79;AC79;1100 1165 11B0;AC79;1100 1165 11B0; # (걹; 걹; 걹; 걹; 걹; ) HANGUL SYLLABLE GEOLG
+AC7A;AC7A;1100 1165 11B1;AC7A;1100 1165 11B1; # (걺; 걺; 걺; 걺; 걺; ) HANGUL SYLLABLE GEOLM
+AC7B;AC7B;1100 1165 11B2;AC7B;1100 1165 11B2; # (걻; 걻; 걻; 걻; 걻; ) HANGUL SYLLABLE GEOLB
+AC7C;AC7C;1100 1165 11B3;AC7C;1100 1165 11B3; # (걼; 걼; 걼; 걼; 걼; ) HANGUL SYLLABLE GEOLS
+AC7D;AC7D;1100 1165 11B4;AC7D;1100 1165 11B4; # (걽; 걽; 걽; 걽; 걽; ) HANGUL SYLLABLE GEOLT
+AC7E;AC7E;1100 1165 11B5;AC7E;1100 1165 11B5; # (걾; 걾; 걾; 걾; 걾; ) HANGUL SYLLABLE GEOLP
+AC7F;AC7F;1100 1165 11B6;AC7F;1100 1165 11B6; # (걿; 걿; 걿; 걿; 걿; ) HANGUL SYLLABLE GEOLH
+AC80;AC80;1100 1165 11B7;AC80;1100 1165 11B7; # (검; 검; 검; 검; 검; ) HANGUL SYLLABLE GEOM
+AC81;AC81;1100 1165 11B8;AC81;1100 1165 11B8; # (겁; 겁; 겁; 겁; 겁; ) HANGUL SYLLABLE GEOB
+AC82;AC82;1100 1165 11B9;AC82;1100 1165 11B9; # (겂; 겂; 겂; 겂; 겂; ) HANGUL SYLLABLE GEOBS
+AC83;AC83;1100 1165 11BA;AC83;1100 1165 11BA; # (것; 것; 것; 것; 것; ) HANGUL SYLLABLE GEOS
+AC84;AC84;1100 1165 11BB;AC84;1100 1165 11BB; # (겄; 겄; 겄; 겄; 겄; ) HANGUL SYLLABLE GEOSS
+AC85;AC85;1100 1165 11BC;AC85;1100 1165 11BC; # (겅; 겅; 겅; 겅; 겅; ) HANGUL SYLLABLE GEONG
+AC86;AC86;1100 1165 11BD;AC86;1100 1165 11BD; # (겆; 겆; 겆; 겆; 겆; ) HANGUL SYLLABLE GEOJ
+AC87;AC87;1100 1165 11BE;AC87;1100 1165 11BE; # (겇; 겇; 겇; 겇; 겇; ) HANGUL SYLLABLE GEOC
+AC88;AC88;1100 1165 11BF;AC88;1100 1165 11BF; # (겈; 겈; 겈; 겈; 겈; ) HANGUL SYLLABLE GEOK
+AC89;AC89;1100 1165 11C0;AC89;1100 1165 11C0; # (겉; 겉; 겉; 겉; 겉; ) HANGUL SYLLABLE GEOT
+AC8A;AC8A;1100 1165 11C1;AC8A;1100 1165 11C1; # (겊; 겊; 겊; 겊; 겊; ) HANGUL SYLLABLE GEOP
+AC8B;AC8B;1100 1165 11C2;AC8B;1100 1165 11C2; # (겋; 겋; 겋; 겋; 겋; ) HANGUL SYLLABLE GEOH
+AC8C;AC8C;1100 1166;AC8C;1100 1166; # (게; 게; 게; 게; 게; ) HANGUL SYLLABLE GE
+AC8D;AC8D;1100 1166 11A8;AC8D;1100 1166 11A8; # (겍; 겍; 겍; 겍; 겍; ) HANGUL SYLLABLE GEG
+AC8E;AC8E;1100 1166 11A9;AC8E;1100 1166 11A9; # (겎; 겎; 겎; 겎; 겎; ) HANGUL SYLLABLE GEGG
+AC8F;AC8F;1100 1166 11AA;AC8F;1100 1166 11AA; # (겏; 겏; 겏; 겏; 겏; ) HANGUL SYLLABLE GEGS
+AC90;AC90;1100 1166 11AB;AC90;1100 1166 11AB; # (겐; 겐; 겐; 겐; 겐; ) HANGUL SYLLABLE GEN
+AC91;AC91;1100 1166 11AC;AC91;1100 1166 11AC; # (겑; 겑; 겑; 겑; 겑; ) HANGUL SYLLABLE GENJ
+AC92;AC92;1100 1166 11AD;AC92;1100 1166 11AD; # (겒; 겒; 겒; 겒; 겒; ) HANGUL SYLLABLE GENH
+AC93;AC93;1100 1166 11AE;AC93;1100 1166 11AE; # (겓; 겓; 겓; 겓; 겓; ) HANGUL SYLLABLE GED
+AC94;AC94;1100 1166 11AF;AC94;1100 1166 11AF; # (겔; 겔; 겔; 겔; 겔; ) HANGUL SYLLABLE GEL
+AC95;AC95;1100 1166 11B0;AC95;1100 1166 11B0; # (겕; 겕; 겕; 겕; 겕; ) HANGUL SYLLABLE GELG
+AC96;AC96;1100 1166 11B1;AC96;1100 1166 11B1; # (겖; 겖; 겖; 겖; 겖; ) HANGUL SYLLABLE GELM
+AC97;AC97;1100 1166 11B2;AC97;1100 1166 11B2; # (겗; 겗; 겗; 겗; 겗; ) HANGUL SYLLABLE GELB
+AC98;AC98;1100 1166 11B3;AC98;1100 1166 11B3; # (겘; 겘; 겘; 겘; 겘; ) HANGUL SYLLABLE GELS
+AC99;AC99;1100 1166 11B4;AC99;1100 1166 11B4; # (겙; 겙; 겙; 겙; 겙; ) HANGUL SYLLABLE GELT
+AC9A;AC9A;1100 1166 11B5;AC9A;1100 1166 11B5; # (겚; 겚; 겚; 겚; 겚; ) HANGUL SYLLABLE GELP
+AC9B;AC9B;1100 1166 11B6;AC9B;1100 1166 11B6; # (겛; 겛; 겛; 겛; 겛; ) HANGUL SYLLABLE GELH
+AC9C;AC9C;1100 1166 11B7;AC9C;1100 1166 11B7; # (겜; 겜; 겜; 겜; 겜; ) HANGUL SYLLABLE GEM
+AC9D;AC9D;1100 1166 11B8;AC9D;1100 1166 11B8; # (겝; 겝; 겝; 겝; 겝; ) HANGUL SYLLABLE GEB
+AC9E;AC9E;1100 1166 11B9;AC9E;1100 1166 11B9; # (겞; 겞; 겞; 겞; 겞; ) HANGUL SYLLABLE GEBS
+AC9F;AC9F;1100 1166 11BA;AC9F;1100 1166 11BA; # (겟; 겟; 겟; 겟; 겟; ) HANGUL SYLLABLE GES
+ACA0;ACA0;1100 1166 11BB;ACA0;1100 1166 11BB; # (겠; 겠; 겠; 겠; 겠; ) HANGUL SYLLABLE GESS
+ACA1;ACA1;1100 1166 11BC;ACA1;1100 1166 11BC; # (겡; 겡; 겡; 겡; 겡; ) HANGUL SYLLABLE GENG
+ACA2;ACA2;1100 1166 11BD;ACA2;1100 1166 11BD; # (겢; 겢; 겢; 겢; 겢; ) HANGUL SYLLABLE GEJ
+ACA3;ACA3;1100 1166 11BE;ACA3;1100 1166 11BE; # (겣; 겣; 겣; 겣; 겣; ) HANGUL SYLLABLE GEC
+ACA4;ACA4;1100 1166 11BF;ACA4;1100 1166 11BF; # (겤; 겤; 겤; 겤; 겤; ) HANGUL SYLLABLE GEK
+ACA5;ACA5;1100 1166 11C0;ACA5;1100 1166 11C0; # (겥; 겥; 겥; 겥; 겥; ) HANGUL SYLLABLE GET
+ACA6;ACA6;1100 1166 11C1;ACA6;1100 1166 11C1; # (겦; 겦; 겦; 겦; 겦; ) HANGUL SYLLABLE GEP
+ACA7;ACA7;1100 1166 11C2;ACA7;1100 1166 11C2; # (겧; 겧; 겧; 겧; 겧; ) HANGUL SYLLABLE GEH
+ACA8;ACA8;1100 1167;ACA8;1100 1167; # (겨; 겨; 겨; 겨; 겨; ) HANGUL SYLLABLE GYEO
+ACA9;ACA9;1100 1167 11A8;ACA9;1100 1167 11A8; # (격; 격; 격; 격; 격; ) HANGUL SYLLABLE GYEOG
+ACAA;ACAA;1100 1167 11A9;ACAA;1100 1167 11A9; # (겪; 겪; 겪; 겪; 겪; ) HANGUL SYLLABLE GYEOGG
+ACAB;ACAB;1100 1167 11AA;ACAB;1100 1167 11AA; # (겫; 겫; 겫; 겫; 겫; ) HANGUL SYLLABLE GYEOGS
+ACAC;ACAC;1100 1167 11AB;ACAC;1100 1167 11AB; # (견; 견; 견; 견; 견; ) HANGUL SYLLABLE GYEON
+ACAD;ACAD;1100 1167 11AC;ACAD;1100 1167 11AC; # (겭; 겭; 겭; 겭; 겭; ) HANGUL SYLLABLE GYEONJ
+ACAE;ACAE;1100 1167 11AD;ACAE;1100 1167 11AD; # (겮; 겮; 겮; 겮; 겮; ) HANGUL SYLLABLE GYEONH
+ACAF;ACAF;1100 1167 11AE;ACAF;1100 1167 11AE; # (겯; 겯; 겯; 겯; 겯; ) HANGUL SYLLABLE GYEOD
+ACB0;ACB0;1100 1167 11AF;ACB0;1100 1167 11AF; # (결; 결; 결; 결; 결; ) HANGUL SYLLABLE GYEOL
+ACB1;ACB1;1100 1167 11B0;ACB1;1100 1167 11B0; # (겱; 겱; 겱; 겱; 겱; ) HANGUL SYLLABLE GYEOLG
+ACB2;ACB2;1100 1167 11B1;ACB2;1100 1167 11B1; # (겲; 겲; 겲; 겲; 겲; ) HANGUL SYLLABLE GYEOLM
+ACB3;ACB3;1100 1167 11B2;ACB3;1100 1167 11B2; # (겳; 겳; 겳; 겳; 겳; ) HANGUL SYLLABLE GYEOLB
+ACB4;ACB4;1100 1167 11B3;ACB4;1100 1167 11B3; # (겴; 겴; 겴; 겴; 겴; ) HANGUL SYLLABLE GYEOLS
+ACB5;ACB5;1100 1167 11B4;ACB5;1100 1167 11B4; # (겵; 겵; 겵; 겵; 겵; ) HANGUL SYLLABLE GYEOLT
+ACB6;ACB6;1100 1167 11B5;ACB6;1100 1167 11B5; # (겶; 겶; 겶; 겶; 겶; ) HANGUL SYLLABLE GYEOLP
+ACB7;ACB7;1100 1167 11B6;ACB7;1100 1167 11B6; # (겷; 겷; 겷; 겷; 겷; ) HANGUL SYLLABLE GYEOLH
+ACB8;ACB8;1100 1167 11B7;ACB8;1100 1167 11B7; # (겸; 겸; 겸; 겸; 겸; ) HANGUL SYLLABLE GYEOM
+ACB9;ACB9;1100 1167 11B8;ACB9;1100 1167 11B8; # (겹; 겹; 겹; 겹; 겹; ) HANGUL SYLLABLE GYEOB
+ACBA;ACBA;1100 1167 11B9;ACBA;1100 1167 11B9; # (겺; 겺; 겺; 겺; 겺; ) HANGUL SYLLABLE GYEOBS
+ACBB;ACBB;1100 1167 11BA;ACBB;1100 1167 11BA; # (겻; 겻; 겻; 겻; 겻; ) HANGUL SYLLABLE GYEOS
+ACBC;ACBC;1100 1167 11BB;ACBC;1100 1167 11BB; # (겼; 겼; 겼; 겼; 겼; ) HANGUL SYLLABLE GYEOSS
+ACBD;ACBD;1100 1167 11BC;ACBD;1100 1167 11BC; # (경; 경; 경; 경; 경; ) HANGUL SYLLABLE GYEONG
+ACBE;ACBE;1100 1167 11BD;ACBE;1100 1167 11BD; # (겾; 겾; 겾; 겾; 겾; ) HANGUL SYLLABLE GYEOJ
+ACBF;ACBF;1100 1167 11BE;ACBF;1100 1167 11BE; # (겿; 겿; 겿; 겿; 겿; ) HANGUL SYLLABLE GYEOC
+ACC0;ACC0;1100 1167 11BF;ACC0;1100 1167 11BF; # (곀; 곀; 곀; 곀; 곀; ) HANGUL SYLLABLE GYEOK
+ACC1;ACC1;1100 1167 11C0;ACC1;1100 1167 11C0; # (곁; 곁; 곁; 곁; 곁; ) HANGUL SYLLABLE GYEOT
+ACC2;ACC2;1100 1167 11C1;ACC2;1100 1167 11C1; # (곂; 곂; 곂; 곂; 곂; ) HANGUL SYLLABLE GYEOP
+ACC3;ACC3;1100 1167 11C2;ACC3;1100 1167 11C2; # (곃; 곃; 곃; 곃; 곃; ) HANGUL SYLLABLE GYEOH
+ACC4;ACC4;1100 1168;ACC4;1100 1168; # (계; 계; 계; 계; 계; ) HANGUL SYLLABLE GYE
+ACC5;ACC5;1100 1168 11A8;ACC5;1100 1168 11A8; # (곅; 곅; 곅; 곅; 곅; ) HANGUL SYLLABLE GYEG
+ACC6;ACC6;1100 1168 11A9;ACC6;1100 1168 11A9; # (곆; 곆; 곆; 곆; 곆; ) HANGUL SYLLABLE GYEGG
+ACC7;ACC7;1100 1168 11AA;ACC7;1100 1168 11AA; # (곇; 곇; 곇; 곇; 곇; ) HANGUL SYLLABLE GYEGS
+ACC8;ACC8;1100 1168 11AB;ACC8;1100 1168 11AB; # (곈; 곈; 곈; 곈; 곈; ) HANGUL SYLLABLE GYEN
+ACC9;ACC9;1100 1168 11AC;ACC9;1100 1168 11AC; # (곉; 곉; 곉; 곉; 곉; ) HANGUL SYLLABLE GYENJ
+ACCA;ACCA;1100 1168 11AD;ACCA;1100 1168 11AD; # (곊; 곊; 곊; 곊; 곊; ) HANGUL SYLLABLE GYENH
+ACCB;ACCB;1100 1168 11AE;ACCB;1100 1168 11AE; # (곋; 곋; 곋; 곋; 곋; ) HANGUL SYLLABLE GYED
+ACCC;ACCC;1100 1168 11AF;ACCC;1100 1168 11AF; # (곌; 곌; 곌; 곌; 곌; ) HANGUL SYLLABLE GYEL
+ACCD;ACCD;1100 1168 11B0;ACCD;1100 1168 11B0; # (곍; 곍; 곍; 곍; 곍; ) HANGUL SYLLABLE GYELG
+ACCE;ACCE;1100 1168 11B1;ACCE;1100 1168 11B1; # (곎; 곎; 곎; 곎; 곎; ) HANGUL SYLLABLE GYELM
+ACCF;ACCF;1100 1168 11B2;ACCF;1100 1168 11B2; # (곏; 곏; 곏; 곏; 곏; ) HANGUL SYLLABLE GYELB
+ACD0;ACD0;1100 1168 11B3;ACD0;1100 1168 11B3; # (곐; 곐; 곐; 곐; 곐; ) HANGUL SYLLABLE GYELS
+ACD1;ACD1;1100 1168 11B4;ACD1;1100 1168 11B4; # (곑; 곑; 곑; 곑; 곑; ) HANGUL SYLLABLE GYELT
+ACD2;ACD2;1100 1168 11B5;ACD2;1100 1168 11B5; # (곒; 곒; 곒; 곒; 곒; ) HANGUL SYLLABLE GYELP
+ACD3;ACD3;1100 1168 11B6;ACD3;1100 1168 11B6; # (곓; 곓; 곓; 곓; 곓; ) HANGUL SYLLABLE GYELH
+ACD4;ACD4;1100 1168 11B7;ACD4;1100 1168 11B7; # (곔; 곔; 곔; 곔; 곔; ) HANGUL SYLLABLE GYEM
+ACD5;ACD5;1100 1168 11B8;ACD5;1100 1168 11B8; # (곕; 곕; 곕; 곕; 곕; ) HANGUL SYLLABLE GYEB
+ACD6;ACD6;1100 1168 11B9;ACD6;1100 1168 11B9; # (곖; 곖; 곖; 곖; 곖; ) HANGUL SYLLABLE GYEBS
+ACD7;ACD7;1100 1168 11BA;ACD7;1100 1168 11BA; # (곗; 곗; 곗; 곗; 곗; ) HANGUL SYLLABLE GYES
+ACD8;ACD8;1100 1168 11BB;ACD8;1100 1168 11BB; # (곘; 곘; 곘; 곘; 곘; ) HANGUL SYLLABLE GYESS
+ACD9;ACD9;1100 1168 11BC;ACD9;1100 1168 11BC; # (곙; 곙; 곙; 곙; 곙; ) HANGUL SYLLABLE GYENG
+ACDA;ACDA;1100 1168 11BD;ACDA;1100 1168 11BD; # (곚; 곚; 곚; 곚; 곚; ) HANGUL SYLLABLE GYEJ
+ACDB;ACDB;1100 1168 11BE;ACDB;1100 1168 11BE; # (곛; 곛; 곛; 곛; 곛; ) HANGUL SYLLABLE GYEC
+ACDC;ACDC;1100 1168 11BF;ACDC;1100 1168 11BF; # (곜; 곜; 곜; 곜; 곜; ) HANGUL SYLLABLE GYEK
+ACDD;ACDD;1100 1168 11C0;ACDD;1100 1168 11C0; # (곝; 곝; 곝; 곝; 곝; ) HANGUL SYLLABLE GYET
+ACDE;ACDE;1100 1168 11C1;ACDE;1100 1168 11C1; # (곞; 곞; 곞; 곞; 곞; ) HANGUL SYLLABLE GYEP
+ACDF;ACDF;1100 1168 11C2;ACDF;1100 1168 11C2; # (곟; 곟; 곟; 곟; 곟; ) HANGUL SYLLABLE GYEH
+ACE0;ACE0;1100 1169;ACE0;1100 1169; # (고; 고; 고; 고; 고; ) HANGUL SYLLABLE GO
+ACE1;ACE1;1100 1169 11A8;ACE1;1100 1169 11A8; # (곡; 곡; 곡; 곡; 곡; ) HANGUL SYLLABLE GOG
+ACE2;ACE2;1100 1169 11A9;ACE2;1100 1169 11A9; # (곢; 곢; 곢; 곢; 곢; ) HANGUL SYLLABLE GOGG
+ACE3;ACE3;1100 1169 11AA;ACE3;1100 1169 11AA; # (곣; 곣; 곣; 곣; 곣; ) HANGUL SYLLABLE GOGS
+ACE4;ACE4;1100 1169 11AB;ACE4;1100 1169 11AB; # (곤; 곤; 곤; 곤; 곤; ) HANGUL SYLLABLE GON
+ACE5;ACE5;1100 1169 11AC;ACE5;1100 1169 11AC; # (곥; 곥; 곥; 곥; 곥; ) HANGUL SYLLABLE GONJ
+ACE6;ACE6;1100 1169 11AD;ACE6;1100 1169 11AD; # (곦; 곦; 곦; 곦; 곦; ) HANGUL SYLLABLE GONH
+ACE7;ACE7;1100 1169 11AE;ACE7;1100 1169 11AE; # (곧; 곧; 곧; 곧; 곧; ) HANGUL SYLLABLE GOD
+ACE8;ACE8;1100 1169 11AF;ACE8;1100 1169 11AF; # (골; 골; 골; 골; 골; ) HANGUL SYLLABLE GOL
+ACE9;ACE9;1100 1169 11B0;ACE9;1100 1169 11B0; # (곩; 곩; 곩; 곩; 곩; ) HANGUL SYLLABLE GOLG
+ACEA;ACEA;1100 1169 11B1;ACEA;1100 1169 11B1; # (곪; 곪; 곪; 곪; 곪; ) HANGUL SYLLABLE GOLM
+ACEB;ACEB;1100 1169 11B2;ACEB;1100 1169 11B2; # (곫; 곫; 곫; 곫; 곫; ) HANGUL SYLLABLE GOLB
+ACEC;ACEC;1100 1169 11B3;ACEC;1100 1169 11B3; # (곬; 곬; 곬; 곬; 곬; ) HANGUL SYLLABLE GOLS
+ACED;ACED;1100 1169 11B4;ACED;1100 1169 11B4; # (곭; 곭; 곭; 곭; 곭; ) HANGUL SYLLABLE GOLT
+ACEE;ACEE;1100 1169 11B5;ACEE;1100 1169 11B5; # (곮; 곮; 곮; 곮; 곮; ) HANGUL SYLLABLE GOLP
+ACEF;ACEF;1100 1169 11B6;ACEF;1100 1169 11B6; # (곯; 곯; 곯; 곯; 곯; ) HANGUL SYLLABLE GOLH
+ACF0;ACF0;1100 1169 11B7;ACF0;1100 1169 11B7; # (곰; 곰; 곰; 곰; 곰; ) HANGUL SYLLABLE GOM
+ACF1;ACF1;1100 1169 11B8;ACF1;1100 1169 11B8; # (곱; 곱; 곱; 곱; 곱; ) HANGUL SYLLABLE GOB
+ACF2;ACF2;1100 1169 11B9;ACF2;1100 1169 11B9; # (곲; 곲; 곲; 곲; 곲; ) HANGUL SYLLABLE GOBS
+ACF3;ACF3;1100 1169 11BA;ACF3;1100 1169 11BA; # (곳; 곳; 곳; 곳; 곳; ) HANGUL SYLLABLE GOS
+ACF4;ACF4;1100 1169 11BB;ACF4;1100 1169 11BB; # (곴; 곴; 곴; 곴; 곴; ) HANGUL SYLLABLE GOSS
+ACF5;ACF5;1100 1169 11BC;ACF5;1100 1169 11BC; # (공; 공; 공; 공; 공; ) HANGUL SYLLABLE GONG
+ACF6;ACF6;1100 1169 11BD;ACF6;1100 1169 11BD; # (곶; 곶; 곶; 곶; 곶; ) HANGUL SYLLABLE GOJ
+ACF7;ACF7;1100 1169 11BE;ACF7;1100 1169 11BE; # (곷; 곷; 곷; 곷; 곷; ) HANGUL SYLLABLE GOC
+ACF8;ACF8;1100 1169 11BF;ACF8;1100 1169 11BF; # (곸; 곸; 곸; 곸; 곸; ) HANGUL SYLLABLE GOK
+ACF9;ACF9;1100 1169 11C0;ACF9;1100 1169 11C0; # (곹; 곹; 곹; 곹; 곹; ) HANGUL SYLLABLE GOT
+ACFA;ACFA;1100 1169 11C1;ACFA;1100 1169 11C1; # (곺; 곺; 곺; 곺; 곺; ) HANGUL SYLLABLE GOP
+ACFB;ACFB;1100 1169 11C2;ACFB;1100 1169 11C2; # (곻; 곻; 곻; 곻; 곻; ) HANGUL SYLLABLE GOH
+ACFC;ACFC;1100 116A;ACFC;1100 116A; # (과; 과; 과; 과; 과; ) HANGUL SYLLABLE GWA
+ACFD;ACFD;1100 116A 11A8;ACFD;1100 116A 11A8; # (곽; 곽; 곽; 곽; 곽; ) HANGUL SYLLABLE GWAG
+ACFE;ACFE;1100 116A 11A9;ACFE;1100 116A 11A9; # (곾; 곾; 곾; 곾; 곾; ) HANGUL SYLLABLE GWAGG
+ACFF;ACFF;1100 116A 11AA;ACFF;1100 116A 11AA; # (곿; 곿; 곿; 곿; 곿; ) HANGUL SYLLABLE GWAGS
+AD00;AD00;1100 116A 11AB;AD00;1100 116A 11AB; # (관; 관; 관; 관; 관; ) HANGUL SYLLABLE GWAN
+AD01;AD01;1100 116A 11AC;AD01;1100 116A 11AC; # (괁; 괁; 괁; 괁; 괁; ) HANGUL SYLLABLE GWANJ
+AD02;AD02;1100 116A 11AD;AD02;1100 116A 11AD; # (괂; 괂; 괂; 괂; 괂; ) HANGUL SYLLABLE GWANH
+AD03;AD03;1100 116A 11AE;AD03;1100 116A 11AE; # (괃; 괃; 괃; 괃; 괃; ) HANGUL SYLLABLE GWAD
+AD04;AD04;1100 116A 11AF;AD04;1100 116A 11AF; # (괄; 괄; 괄; 괄; 괄; ) HANGUL SYLLABLE GWAL
+AD05;AD05;1100 116A 11B0;AD05;1100 116A 11B0; # (괅; 괅; 괅; 괅; 괅; ) HANGUL SYLLABLE GWALG
+AD06;AD06;1100 116A 11B1;AD06;1100 116A 11B1; # (괆; 괆; 괆; 괆; 괆; ) HANGUL SYLLABLE GWALM
+AD07;AD07;1100 116A 11B2;AD07;1100 116A 11B2; # (괇; 괇; 괇; 괇; 괇; ) HANGUL SYLLABLE GWALB
+AD08;AD08;1100 116A 11B3;AD08;1100 116A 11B3; # (괈; 괈; 괈; 괈; 괈; ) HANGUL SYLLABLE GWALS
+AD09;AD09;1100 116A 11B4;AD09;1100 116A 11B4; # (괉; 괉; 괉; 괉; 괉; ) HANGUL SYLLABLE GWALT
+AD0A;AD0A;1100 116A 11B5;AD0A;1100 116A 11B5; # (괊; 괊; 괊; 괊; 괊; ) HANGUL SYLLABLE GWALP
+AD0B;AD0B;1100 116A 11B6;AD0B;1100 116A 11B6; # (괋; 괋; 괋; 괋; 괋; ) HANGUL SYLLABLE GWALH
+AD0C;AD0C;1100 116A 11B7;AD0C;1100 116A 11B7; # (괌; 괌; 괌; 괌; 괌; ) HANGUL SYLLABLE GWAM
+AD0D;AD0D;1100 116A 11B8;AD0D;1100 116A 11B8; # (괍; 괍; 괍; 괍; 괍; ) HANGUL SYLLABLE GWAB
+AD0E;AD0E;1100 116A 11B9;AD0E;1100 116A 11B9; # (괎; 괎; 괎; 괎; 괎; ) HANGUL SYLLABLE GWABS
+AD0F;AD0F;1100 116A 11BA;AD0F;1100 116A 11BA; # (괏; 괏; 괏; 괏; 괏; ) HANGUL SYLLABLE GWAS
+AD10;AD10;1100 116A 11BB;AD10;1100 116A 11BB; # (괐; 괐; 괐; 괐; 괐; ) HANGUL SYLLABLE GWASS
+AD11;AD11;1100 116A 11BC;AD11;1100 116A 11BC; # (광; 광; 광; 광; 광; ) HANGUL SYLLABLE GWANG
+AD12;AD12;1100 116A 11BD;AD12;1100 116A 11BD; # (괒; 괒; 괒; 괒; 괒; ) HANGUL SYLLABLE GWAJ
+AD13;AD13;1100 116A 11BE;AD13;1100 116A 11BE; # (괓; 괓; 괓; 괓; 괓; ) HANGUL SYLLABLE GWAC
+AD14;AD14;1100 116A 11BF;AD14;1100 116A 11BF; # (괔; 괔; 괔; 괔; 괔; ) HANGUL SYLLABLE GWAK
+AD15;AD15;1100 116A 11C0;AD15;1100 116A 11C0; # (괕; 괕; 괕; 괕; 괕; ) HANGUL SYLLABLE GWAT
+AD16;AD16;1100 116A 11C1;AD16;1100 116A 11C1; # (괖; 괖; 괖; 괖; 괖; ) HANGUL SYLLABLE GWAP
+AD17;AD17;1100 116A 11C2;AD17;1100 116A 11C2; # (괗; 괗; 괗; 괗; 괗; ) HANGUL SYLLABLE GWAH
+AD18;AD18;1100 116B;AD18;1100 116B; # (괘; 괘; 괘; 괘; 괘; ) HANGUL SYLLABLE GWAE
+AD19;AD19;1100 116B 11A8;AD19;1100 116B 11A8; # (괙; 괙; 괙; 괙; 괙; ) HANGUL SYLLABLE GWAEG
+AD1A;AD1A;1100 116B 11A9;AD1A;1100 116B 11A9; # (괚; 괚; 괚; 괚; 괚; ) HANGUL SYLLABLE GWAEGG
+AD1B;AD1B;1100 116B 11AA;AD1B;1100 116B 11AA; # (괛; 괛; 괛; 괛; 괛; ) HANGUL SYLLABLE GWAEGS
+AD1C;AD1C;1100 116B 11AB;AD1C;1100 116B 11AB; # (괜; 괜; 괜; 괜; 괜; ) HANGUL SYLLABLE GWAEN
+AD1D;AD1D;1100 116B 11AC;AD1D;1100 116B 11AC; # (괝; 괝; 괝; 괝; 괝; ) HANGUL SYLLABLE GWAENJ
+AD1E;AD1E;1100 116B 11AD;AD1E;1100 116B 11AD; # (괞; 괞; 괞; 괞; 괞; ) HANGUL SYLLABLE GWAENH
+AD1F;AD1F;1100 116B 11AE;AD1F;1100 116B 11AE; # (괟; 괟; 괟; 괟; 괟; ) HANGUL SYLLABLE GWAED
+AD20;AD20;1100 116B 11AF;AD20;1100 116B 11AF; # (괠; 괠; 괠; 괠; 괠; ) HANGUL SYLLABLE GWAEL
+AD21;AD21;1100 116B 11B0;AD21;1100 116B 11B0; # (괡; 괡; 괡; 괡; 괡; ) HANGUL SYLLABLE GWAELG
+AD22;AD22;1100 116B 11B1;AD22;1100 116B 11B1; # (괢; 괢; 괢; 괢; 괢; ) HANGUL SYLLABLE GWAELM
+AD23;AD23;1100 116B 11B2;AD23;1100 116B 11B2; # (괣; 괣; 괣; 괣; 괣; ) HANGUL SYLLABLE GWAELB
+AD24;AD24;1100 116B 11B3;AD24;1100 116B 11B3; # (괤; 괤; 괤; 괤; 괤; ) HANGUL SYLLABLE GWAELS
+AD25;AD25;1100 116B 11B4;AD25;1100 116B 11B4; # (괥; 괥; 괥; 괥; 괥; ) HANGUL SYLLABLE GWAELT
+AD26;AD26;1100 116B 11B5;AD26;1100 116B 11B5; # (괦; 괦; 괦; 괦; 괦; ) HANGUL SYLLABLE GWAELP
+AD27;AD27;1100 116B 11B6;AD27;1100 116B 11B6; # (괧; 괧; 괧; 괧; 괧; ) HANGUL SYLLABLE GWAELH
+AD28;AD28;1100 116B 11B7;AD28;1100 116B 11B7; # (괨; 괨; 괨; 괨; 괨; ) HANGUL SYLLABLE GWAEM
+AD29;AD29;1100 116B 11B8;AD29;1100 116B 11B8; # (괩; 괩; 괩; 괩; 괩; ) HANGUL SYLLABLE GWAEB
+AD2A;AD2A;1100 116B 11B9;AD2A;1100 116B 11B9; # (괪; 괪; 괪; 괪; 괪; ) HANGUL SYLLABLE GWAEBS
+AD2B;AD2B;1100 116B 11BA;AD2B;1100 116B 11BA; # (괫; 괫; 괫; 괫; 괫; ) HANGUL SYLLABLE GWAES
+AD2C;AD2C;1100 116B 11BB;AD2C;1100 116B 11BB; # (괬; 괬; 괬; 괬; 괬; ) HANGUL SYLLABLE GWAESS
+AD2D;AD2D;1100 116B 11BC;AD2D;1100 116B 11BC; # (괭; 괭; 괭; 괭; 괭; ) HANGUL SYLLABLE GWAENG
+AD2E;AD2E;1100 116B 11BD;AD2E;1100 116B 11BD; # (괮; 괮; 괮; 괮; 괮; ) HANGUL SYLLABLE GWAEJ
+AD2F;AD2F;1100 116B 11BE;AD2F;1100 116B 11BE; # (괯; 괯; 괯; 괯; 괯; ) HANGUL SYLLABLE GWAEC
+AD30;AD30;1100 116B 11BF;AD30;1100 116B 11BF; # (괰; 괰; 괰; 괰; 괰; ) HANGUL SYLLABLE GWAEK
+AD31;AD31;1100 116B 11C0;AD31;1100 116B 11C0; # (괱; 괱; 괱; 괱; 괱; ) HANGUL SYLLABLE GWAET
+AD32;AD32;1100 116B 11C1;AD32;1100 116B 11C1; # (괲; 괲; 괲; 괲; 괲; ) HANGUL SYLLABLE GWAEP
+AD33;AD33;1100 116B 11C2;AD33;1100 116B 11C2; # (괳; 괳; 괳; 괳; 괳; ) HANGUL SYLLABLE GWAEH
+AD34;AD34;1100 116C;AD34;1100 116C; # (괴; 괴; 괴; 괴; 괴; ) HANGUL SYLLABLE GOE
+AD35;AD35;1100 116C 11A8;AD35;1100 116C 11A8; # (괵; 괵; 괵; 괵; 괵; ) HANGUL SYLLABLE GOEG
+AD36;AD36;1100 116C 11A9;AD36;1100 116C 11A9; # (괶; 괶; 괶; 괶; 괶; ) HANGUL SYLLABLE GOEGG
+AD37;AD37;1100 116C 11AA;AD37;1100 116C 11AA; # (괷; 괷; 괷; 괷; 괷; ) HANGUL SYLLABLE GOEGS
+AD38;AD38;1100 116C 11AB;AD38;1100 116C 11AB; # (괸; 괸; 괸; 괸; 괸; ) HANGUL SYLLABLE GOEN
+AD39;AD39;1100 116C 11AC;AD39;1100 116C 11AC; # (괹; 괹; 괹; 괹; 괹; ) HANGUL SYLLABLE GOENJ
+AD3A;AD3A;1100 116C 11AD;AD3A;1100 116C 11AD; # (괺; 괺; 괺; 괺; 괺; ) HANGUL SYLLABLE GOENH
+AD3B;AD3B;1100 116C 11AE;AD3B;1100 116C 11AE; # (괻; 괻; 괻; 괻; 괻; ) HANGUL SYLLABLE GOED
+AD3C;AD3C;1100 116C 11AF;AD3C;1100 116C 11AF; # (괼; 괼; 괼; 괼; 괼; ) HANGUL SYLLABLE GOEL
+AD3D;AD3D;1100 116C 11B0;AD3D;1100 116C 11B0; # (괽; 괽; 괽; 괽; 괽; ) HANGUL SYLLABLE GOELG
+AD3E;AD3E;1100 116C 11B1;AD3E;1100 116C 11B1; # (괾; 괾; 괾; 괾; 괾; ) HANGUL SYLLABLE GOELM
+AD3F;AD3F;1100 116C 11B2;AD3F;1100 116C 11B2; # (괿; 괿; 괿; 괿; 괿; ) HANGUL SYLLABLE GOELB
+AD40;AD40;1100 116C 11B3;AD40;1100 116C 11B3; # (굀; 굀; 굀; 굀; 굀; ) HANGUL SYLLABLE GOELS
+AD41;AD41;1100 116C 11B4;AD41;1100 116C 11B4; # (굁; 굁; 굁; 굁; 굁; ) HANGUL SYLLABLE GOELT
+AD42;AD42;1100 116C 11B5;AD42;1100 116C 11B5; # (굂; 굂; 굂; 굂; 굂; ) HANGUL SYLLABLE GOELP
+AD43;AD43;1100 116C 11B6;AD43;1100 116C 11B6; # (굃; 굃; 굃; 굃; 굃; ) HANGUL SYLLABLE GOELH
+AD44;AD44;1100 116C 11B7;AD44;1100 116C 11B7; # (굄; 굄; 굄; 굄; 굄; ) HANGUL SYLLABLE GOEM
+AD45;AD45;1100 116C 11B8;AD45;1100 116C 11B8; # (굅; 굅; 굅; 굅; 굅; ) HANGUL SYLLABLE GOEB
+AD46;AD46;1100 116C 11B9;AD46;1100 116C 11B9; # (굆; 굆; 굆; 굆; 굆; ) HANGUL SYLLABLE GOEBS
+AD47;AD47;1100 116C 11BA;AD47;1100 116C 11BA; # (굇; 굇; 굇; 굇; 굇; ) HANGUL SYLLABLE GOES
+AD48;AD48;1100 116C 11BB;AD48;1100 116C 11BB; # (굈; 굈; 굈; 굈; 굈; ) HANGUL SYLLABLE GOESS
+AD49;AD49;1100 116C 11BC;AD49;1100 116C 11BC; # (굉; 굉; 굉; 굉; 굉; ) HANGUL SYLLABLE GOENG
+AD4A;AD4A;1100 116C 11BD;AD4A;1100 116C 11BD; # (굊; 굊; 굊; 굊; 굊; ) HANGUL SYLLABLE GOEJ
+AD4B;AD4B;1100 116C 11BE;AD4B;1100 116C 11BE; # (굋; 굋; 굋; 굋; 굋; ) HANGUL SYLLABLE GOEC
+AD4C;AD4C;1100 116C 11BF;AD4C;1100 116C 11BF; # (굌; 굌; 굌; 굌; 굌; ) HANGUL SYLLABLE GOEK
+AD4D;AD4D;1100 116C 11C0;AD4D;1100 116C 11C0; # (굍; 굍; 굍; 굍; 굍; ) HANGUL SYLLABLE GOET
+AD4E;AD4E;1100 116C 11C1;AD4E;1100 116C 11C1; # (굎; 굎; 굎; 굎; 굎; ) HANGUL SYLLABLE GOEP
+AD4F;AD4F;1100 116C 11C2;AD4F;1100 116C 11C2; # (굏; 굏; 굏; 굏; 굏; ) HANGUL SYLLABLE GOEH
+AD50;AD50;1100 116D;AD50;1100 116D; # (교; 교; 교; 교; 교; ) HANGUL SYLLABLE GYO
+AD51;AD51;1100 116D 11A8;AD51;1100 116D 11A8; # (굑; 굑; 굑; 굑; 굑; ) HANGUL SYLLABLE GYOG
+AD52;AD52;1100 116D 11A9;AD52;1100 116D 11A9; # (굒; 굒; 굒; 굒; 굒; ) HANGUL SYLLABLE GYOGG
+AD53;AD53;1100 116D 11AA;AD53;1100 116D 11AA; # (굓; 굓; 굓; 굓; 굓; ) HANGUL SYLLABLE GYOGS
+AD54;AD54;1100 116D 11AB;AD54;1100 116D 11AB; # (굔; 굔; 굔; 굔; 굔; ) HANGUL SYLLABLE GYON
+AD55;AD55;1100 116D 11AC;AD55;1100 116D 11AC; # (굕; 굕; 굕; 굕; 굕; ) HANGUL SYLLABLE GYONJ
+AD56;AD56;1100 116D 11AD;AD56;1100 116D 11AD; # (굖; 굖; 굖; 굖; 굖; ) HANGUL SYLLABLE GYONH
+AD57;AD57;1100 116D 11AE;AD57;1100 116D 11AE; # (굗; 굗; 굗; 굗; 굗; ) HANGUL SYLLABLE GYOD
+AD58;AD58;1100 116D 11AF;AD58;1100 116D 11AF; # (굘; 굘; 굘; 굘; 굘; ) HANGUL SYLLABLE GYOL
+AD59;AD59;1100 116D 11B0;AD59;1100 116D 11B0; # (굙; 굙; 굙; 굙; 굙; ) HANGUL SYLLABLE GYOLG
+AD5A;AD5A;1100 116D 11B1;AD5A;1100 116D 11B1; # (굚; 굚; 굚; 굚; 굚; ) HANGUL SYLLABLE GYOLM
+AD5B;AD5B;1100 116D 11B2;AD5B;1100 116D 11B2; # (굛; 굛; 굛; 굛; 굛; ) HANGUL SYLLABLE GYOLB
+AD5C;AD5C;1100 116D 11B3;AD5C;1100 116D 11B3; # (굜; 굜; 굜; 굜; 굜; ) HANGUL SYLLABLE GYOLS
+AD5D;AD5D;1100 116D 11B4;AD5D;1100 116D 11B4; # (굝; 굝; 굝; 굝; 굝; ) HANGUL SYLLABLE GYOLT
+AD5E;AD5E;1100 116D 11B5;AD5E;1100 116D 11B5; # (굞; 굞; 굞; 굞; 굞; ) HANGUL SYLLABLE GYOLP
+AD5F;AD5F;1100 116D 11B6;AD5F;1100 116D 11B6; # (굟; 굟; 굟; 굟; 굟; ) HANGUL SYLLABLE GYOLH
+AD60;AD60;1100 116D 11B7;AD60;1100 116D 11B7; # (굠; 굠; 굠; 굠; 굠; ) HANGUL SYLLABLE GYOM
+AD61;AD61;1100 116D 11B8;AD61;1100 116D 11B8; # (굡; 굡; 굡; 굡; 굡; ) HANGUL SYLLABLE GYOB
+AD62;AD62;1100 116D 11B9;AD62;1100 116D 11B9; # (굢; 굢; 굢; 굢; 굢; ) HANGUL SYLLABLE GYOBS
+AD63;AD63;1100 116D 11BA;AD63;1100 116D 11BA; # (굣; 굣; 굣; 굣; 굣; ) HANGUL SYLLABLE GYOS
+AD64;AD64;1100 116D 11BB;AD64;1100 116D 11BB; # (굤; 굤; 굤; 굤; 굤; ) HANGUL SYLLABLE GYOSS
+AD65;AD65;1100 116D 11BC;AD65;1100 116D 11BC; # (굥; 굥; 굥; 굥; 굥; ) HANGUL SYLLABLE GYONG
+AD66;AD66;1100 116D 11BD;AD66;1100 116D 11BD; # (굦; 굦; 굦; 굦; 굦; ) HANGUL SYLLABLE GYOJ
+AD67;AD67;1100 116D 11BE;AD67;1100 116D 11BE; # (굧; 굧; 굧; 굧; 굧; ) HANGUL SYLLABLE GYOC
+AD68;AD68;1100 116D 11BF;AD68;1100 116D 11BF; # (굨; 굨; 굨; 굨; 굨; ) HANGUL SYLLABLE GYOK
+AD69;AD69;1100 116D 11C0;AD69;1100 116D 11C0; # (굩; 굩; 굩; 굩; 굩; ) HANGUL SYLLABLE GYOT
+AD6A;AD6A;1100 116D 11C1;AD6A;1100 116D 11C1; # (굪; 굪; 굪; 굪; 굪; ) HANGUL SYLLABLE GYOP
+AD6B;AD6B;1100 116D 11C2;AD6B;1100 116D 11C2; # (굫; 굫; 굫; 굫; 굫; ) HANGUL SYLLABLE GYOH
+AD6C;AD6C;1100 116E;AD6C;1100 116E; # (구; 구; 구; 구; 구; ) HANGUL SYLLABLE GU
+AD6D;AD6D;1100 116E 11A8;AD6D;1100 116E 11A8; # (국; 국; 국; 국; 국; ) HANGUL SYLLABLE GUG
+AD6E;AD6E;1100 116E 11A9;AD6E;1100 116E 11A9; # (굮; 굮; 굮; 굮; 굮; ) HANGUL SYLLABLE GUGG
+AD6F;AD6F;1100 116E 11AA;AD6F;1100 116E 11AA; # (굯; 굯; 굯; 굯; 굯; ) HANGUL SYLLABLE GUGS
+AD70;AD70;1100 116E 11AB;AD70;1100 116E 11AB; # (군; 군; 군; 군; 군; ) HANGUL SYLLABLE GUN
+AD71;AD71;1100 116E 11AC;AD71;1100 116E 11AC; # (굱; 굱; 굱; 굱; 굱; ) HANGUL SYLLABLE GUNJ
+AD72;AD72;1100 116E 11AD;AD72;1100 116E 11AD; # (굲; 굲; 굲; 굲; 굲; ) HANGUL SYLLABLE GUNH
+AD73;AD73;1100 116E 11AE;AD73;1100 116E 11AE; # (굳; 굳; 굳; 굳; 굳; ) HANGUL SYLLABLE GUD
+AD74;AD74;1100 116E 11AF;AD74;1100 116E 11AF; # (굴; 굴; 굴; 굴; 굴; ) HANGUL SYLLABLE GUL
+AD75;AD75;1100 116E 11B0;AD75;1100 116E 11B0; # (굵; 굵; 굵; 굵; 굵; ) HANGUL SYLLABLE GULG
+AD76;AD76;1100 116E 11B1;AD76;1100 116E 11B1; # (굶; 굶; 굶; 굶; 굶; ) HANGUL SYLLABLE GULM
+AD77;AD77;1100 116E 11B2;AD77;1100 116E 11B2; # (굷; 굷; 굷; 굷; 굷; ) HANGUL SYLLABLE GULB
+AD78;AD78;1100 116E 11B3;AD78;1100 116E 11B3; # (굸; 굸; 굸; 굸; 굸; ) HANGUL SYLLABLE GULS
+AD79;AD79;1100 116E 11B4;AD79;1100 116E 11B4; # (굹; 굹; 굹; 굹; 굹; ) HANGUL SYLLABLE GULT
+AD7A;AD7A;1100 116E 11B5;AD7A;1100 116E 11B5; # (굺; 굺; 굺; 굺; 굺; ) HANGUL SYLLABLE GULP
+AD7B;AD7B;1100 116E 11B6;AD7B;1100 116E 11B6; # (굻; 굻; 굻; 굻; 굻; ) HANGUL SYLLABLE GULH
+AD7C;AD7C;1100 116E 11B7;AD7C;1100 116E 11B7; # (굼; 굼; 굼; 굼; 굼; ) HANGUL SYLLABLE GUM
+AD7D;AD7D;1100 116E 11B8;AD7D;1100 116E 11B8; # (굽; 굽; 굽; 굽; 굽; ) HANGUL SYLLABLE GUB
+AD7E;AD7E;1100 116E 11B9;AD7E;1100 116E 11B9; # (굾; 굾; 굾; 굾; 굾; ) HANGUL SYLLABLE GUBS
+AD7F;AD7F;1100 116E 11BA;AD7F;1100 116E 11BA; # (굿; 굿; 굿; 굿; 굿; ) HANGUL SYLLABLE GUS
+AD80;AD80;1100 116E 11BB;AD80;1100 116E 11BB; # (궀; 궀; 궀; 궀; 궀; ) HANGUL SYLLABLE GUSS
+AD81;AD81;1100 116E 11BC;AD81;1100 116E 11BC; # (궁; 궁; 궁; 궁; 궁; ) HANGUL SYLLABLE GUNG
+AD82;AD82;1100 116E 11BD;AD82;1100 116E 11BD; # (궂; 궂; 궂; 궂; 궂; ) HANGUL SYLLABLE GUJ
+AD83;AD83;1100 116E 11BE;AD83;1100 116E 11BE; # (궃; 궃; 궃; 궃; 궃; ) HANGUL SYLLABLE GUC
+AD84;AD84;1100 116E 11BF;AD84;1100 116E 11BF; # (궄; 궄; 궄; 궄; 궄; ) HANGUL SYLLABLE GUK
+AD85;AD85;1100 116E 11C0;AD85;1100 116E 11C0; # (궅; 궅; 궅; 궅; 궅; ) HANGUL SYLLABLE GUT
+AD86;AD86;1100 116E 11C1;AD86;1100 116E 11C1; # (궆; 궆; 궆; 궆; 궆; ) HANGUL SYLLABLE GUP
+AD87;AD87;1100 116E 11C2;AD87;1100 116E 11C2; # (궇; 궇; 궇; 궇; 궇; ) HANGUL SYLLABLE GUH
+AD88;AD88;1100 116F;AD88;1100 116F; # (궈; 궈; 궈; 궈; 궈; ) HANGUL SYLLABLE GWEO
+AD89;AD89;1100 116F 11A8;AD89;1100 116F 11A8; # (궉; 궉; 궉; 궉; 궉; ) HANGUL SYLLABLE GWEOG
+AD8A;AD8A;1100 116F 11A9;AD8A;1100 116F 11A9; # (궊; 궊; 궊; 궊; 궊; ) HANGUL SYLLABLE GWEOGG
+AD8B;AD8B;1100 116F 11AA;AD8B;1100 116F 11AA; # (궋; 궋; 궋; 궋; 궋; ) HANGUL SYLLABLE GWEOGS
+AD8C;AD8C;1100 116F 11AB;AD8C;1100 116F 11AB; # (권; 권; 권; 권; 권; ) HANGUL SYLLABLE GWEON
+AD8D;AD8D;1100 116F 11AC;AD8D;1100 116F 11AC; # (궍; 궍; 궍; 궍; 궍; ) HANGUL SYLLABLE GWEONJ
+AD8E;AD8E;1100 116F 11AD;AD8E;1100 116F 11AD; # (궎; 궎; 궎; 궎; 궎; ) HANGUL SYLLABLE GWEONH
+AD8F;AD8F;1100 116F 11AE;AD8F;1100 116F 11AE; # (궏; 궏; 궏; 궏; 궏; ) HANGUL SYLLABLE GWEOD
+AD90;AD90;1100 116F 11AF;AD90;1100 116F 11AF; # (궐; 궐; 궐; 궐; 궐; ) HANGUL SYLLABLE GWEOL
+AD91;AD91;1100 116F 11B0;AD91;1100 116F 11B0; # (궑; 궑; 궑; 궑; 궑; ) HANGUL SYLLABLE GWEOLG
+AD92;AD92;1100 116F 11B1;AD92;1100 116F 11B1; # (궒; 궒; 궒; 궒; 궒; ) HANGUL SYLLABLE GWEOLM
+AD93;AD93;1100 116F 11B2;AD93;1100 116F 11B2; # (궓; 궓; 궓; 궓; 궓; ) HANGUL SYLLABLE GWEOLB
+AD94;AD94;1100 116F 11B3;AD94;1100 116F 11B3; # (궔; 궔; 궔; 궔; 궔; ) HANGUL SYLLABLE GWEOLS
+AD95;AD95;1100 116F 11B4;AD95;1100 116F 11B4; # (궕; 궕; 궕; 궕; 궕; ) HANGUL SYLLABLE GWEOLT
+AD96;AD96;1100 116F 11B5;AD96;1100 116F 11B5; # (궖; 궖; 궖; 궖; 궖; ) HANGUL SYLLABLE GWEOLP
+AD97;AD97;1100 116F 11B6;AD97;1100 116F 11B6; # (궗; 궗; 궗; 궗; 궗; ) HANGUL SYLLABLE GWEOLH
+AD98;AD98;1100 116F 11B7;AD98;1100 116F 11B7; # (궘; 궘; 궘; 궘; 궘; ) HANGUL SYLLABLE GWEOM
+AD99;AD99;1100 116F 11B8;AD99;1100 116F 11B8; # (궙; 궙; 궙; 궙; 궙; ) HANGUL SYLLABLE GWEOB
+AD9A;AD9A;1100 116F 11B9;AD9A;1100 116F 11B9; # (궚; 궚; 궚; 궚; 궚; ) HANGUL SYLLABLE GWEOBS
+AD9B;AD9B;1100 116F 11BA;AD9B;1100 116F 11BA; # (궛; 궛; 궛; 궛; 궛; ) HANGUL SYLLABLE GWEOS
+AD9C;AD9C;1100 116F 11BB;AD9C;1100 116F 11BB; # (궜; 궜; 궜; 궜; 궜; ) HANGUL SYLLABLE GWEOSS
+AD9D;AD9D;1100 116F 11BC;AD9D;1100 116F 11BC; # (궝; 궝; 궝; 궝; 궝; ) HANGUL SYLLABLE GWEONG
+AD9E;AD9E;1100 116F 11BD;AD9E;1100 116F 11BD; # (궞; 궞; 궞; 궞; 궞; ) HANGUL SYLLABLE GWEOJ
+AD9F;AD9F;1100 116F 11BE;AD9F;1100 116F 11BE; # (궟; 궟; 궟; 궟; 궟; ) HANGUL SYLLABLE GWEOC
+ADA0;ADA0;1100 116F 11BF;ADA0;1100 116F 11BF; # (궠; 궠; 궠; 궠; 궠; ) HANGUL SYLLABLE GWEOK
+ADA1;ADA1;1100 116F 11C0;ADA1;1100 116F 11C0; # (궡; 궡; 궡; 궡; 궡; ) HANGUL SYLLABLE GWEOT
+ADA2;ADA2;1100 116F 11C1;ADA2;1100 116F 11C1; # (궢; 궢; 궢; 궢; 궢; ) HANGUL SYLLABLE GWEOP
+ADA3;ADA3;1100 116F 11C2;ADA3;1100 116F 11C2; # (궣; 궣; 궣; 궣; 궣; ) HANGUL SYLLABLE GWEOH
+ADA4;ADA4;1100 1170;ADA4;1100 1170; # (궤; 궤; 궤; 궤; 궤; ) HANGUL SYLLABLE GWE
+ADA5;ADA5;1100 1170 11A8;ADA5;1100 1170 11A8; # (궥; 궥; 궥; 궥; 궥; ) HANGUL SYLLABLE GWEG
+ADA6;ADA6;1100 1170 11A9;ADA6;1100 1170 11A9; # (궦; 궦; 궦; 궦; 궦; ) HANGUL SYLLABLE GWEGG
+ADA7;ADA7;1100 1170 11AA;ADA7;1100 1170 11AA; # (궧; 궧; 궧; 궧; 궧; ) HANGUL SYLLABLE GWEGS
+ADA8;ADA8;1100 1170 11AB;ADA8;1100 1170 11AB; # (궨; 궨; 궨; 궨; 궨; ) HANGUL SYLLABLE GWEN
+ADA9;ADA9;1100 1170 11AC;ADA9;1100 1170 11AC; # (궩; 궩; 궩; 궩; 궩; ) HANGUL SYLLABLE GWENJ
+ADAA;ADAA;1100 1170 11AD;ADAA;1100 1170 11AD; # (궪; 궪; 궪; 궪; 궪; ) HANGUL SYLLABLE GWENH
+ADAB;ADAB;1100 1170 11AE;ADAB;1100 1170 11AE; # (궫; 궫; 궫; 궫; 궫; ) HANGUL SYLLABLE GWED
+ADAC;ADAC;1100 1170 11AF;ADAC;1100 1170 11AF; # (궬; 궬; 궬; 궬; 궬; ) HANGUL SYLLABLE GWEL
+ADAD;ADAD;1100 1170 11B0;ADAD;1100 1170 11B0; # (궭; 궭; 궭; 궭; 궭; ) HANGUL SYLLABLE GWELG
+ADAE;ADAE;1100 1170 11B1;ADAE;1100 1170 11B1; # (궮; 궮; 궮; 궮; 궮; ) HANGUL SYLLABLE GWELM
+ADAF;ADAF;1100 1170 11B2;ADAF;1100 1170 11B2; # (궯; 궯; 궯; 궯; 궯; ) HANGUL SYLLABLE GWELB
+ADB0;ADB0;1100 1170 11B3;ADB0;1100 1170 11B3; # (궰; 궰; 궰; 궰; 궰; ) HANGUL SYLLABLE GWELS
+ADB1;ADB1;1100 1170 11B4;ADB1;1100 1170 11B4; # (궱; 궱; 궱; 궱; 궱; ) HANGUL SYLLABLE GWELT
+ADB2;ADB2;1100 1170 11B5;ADB2;1100 1170 11B5; # (궲; 궲; 궲; 궲; 궲; ) HANGUL SYLLABLE GWELP
+ADB3;ADB3;1100 1170 11B6;ADB3;1100 1170 11B6; # (궳; 궳; 궳; 궳; 궳; ) HANGUL SYLLABLE GWELH
+ADB4;ADB4;1100 1170 11B7;ADB4;1100 1170 11B7; # (궴; 궴; 궴; 궴; 궴; ) HANGUL SYLLABLE GWEM
+ADB5;ADB5;1100 1170 11B8;ADB5;1100 1170 11B8; # (궵; 궵; 궵; 궵; 궵; ) HANGUL SYLLABLE GWEB
+ADB6;ADB6;1100 1170 11B9;ADB6;1100 1170 11B9; # (궶; 궶; 궶; 궶; 궶; ) HANGUL SYLLABLE GWEBS
+ADB7;ADB7;1100 1170 11BA;ADB7;1100 1170 11BA; # (궷; 궷; 궷; 궷; 궷; ) HANGUL SYLLABLE GWES
+ADB8;ADB8;1100 1170 11BB;ADB8;1100 1170 11BB; # (궸; 궸; 궸; 궸; 궸; ) HANGUL SYLLABLE GWESS
+ADB9;ADB9;1100 1170 11BC;ADB9;1100 1170 11BC; # (궹; 궹; 궹; 궹; 궹; ) HANGUL SYLLABLE GWENG
+ADBA;ADBA;1100 1170 11BD;ADBA;1100 1170 11BD; # (궺; 궺; 궺; 궺; 궺; ) HANGUL SYLLABLE GWEJ
+ADBB;ADBB;1100 1170 11BE;ADBB;1100 1170 11BE; # (궻; 궻; 궻; 궻; 궻; ) HANGUL SYLLABLE GWEC
+ADBC;ADBC;1100 1170 11BF;ADBC;1100 1170 11BF; # (궼; 궼; 궼; 궼; 궼; ) HANGUL SYLLABLE GWEK
+ADBD;ADBD;1100 1170 11C0;ADBD;1100 1170 11C0; # (궽; 궽; 궽; 궽; 궽; ) HANGUL SYLLABLE GWET
+ADBE;ADBE;1100 1170 11C1;ADBE;1100 1170 11C1; # (궾; 궾; 궾; 궾; 궾; ) HANGUL SYLLABLE GWEP
+ADBF;ADBF;1100 1170 11C2;ADBF;1100 1170 11C2; # (궿; 궿; 궿; 궿; 궿; ) HANGUL SYLLABLE GWEH
+ADC0;ADC0;1100 1171;ADC0;1100 1171; # (귀; 귀; 귀; 귀; 귀; ) HANGUL SYLLABLE GWI
+ADC1;ADC1;1100 1171 11A8;ADC1;1100 1171 11A8; # (귁; 귁; 귁; 귁; 귁; ) HANGUL SYLLABLE GWIG
+ADC2;ADC2;1100 1171 11A9;ADC2;1100 1171 11A9; # (귂; 귂; 귂; 귂; 귂; ) HANGUL SYLLABLE GWIGG
+ADC3;ADC3;1100 1171 11AA;ADC3;1100 1171 11AA; # (귃; 귃; 귃; 귃; 귃; ) HANGUL SYLLABLE GWIGS
+ADC4;ADC4;1100 1171 11AB;ADC4;1100 1171 11AB; # (귄; 귄; 귄; 귄; 귄; ) HANGUL SYLLABLE GWIN
+ADC5;ADC5;1100 1171 11AC;ADC5;1100 1171 11AC; # (귅; 귅; 귅; 귅; 귅; ) HANGUL SYLLABLE GWINJ
+ADC6;ADC6;1100 1171 11AD;ADC6;1100 1171 11AD; # (귆; 귆; 귆; 귆; 귆; ) HANGUL SYLLABLE GWINH
+ADC7;ADC7;1100 1171 11AE;ADC7;1100 1171 11AE; # (귇; 귇; 귇; 귇; 귇; ) HANGUL SYLLABLE GWID
+ADC8;ADC8;1100 1171 11AF;ADC8;1100 1171 11AF; # (귈; 귈; 귈; 귈; 귈; ) HANGUL SYLLABLE GWIL
+ADC9;ADC9;1100 1171 11B0;ADC9;1100 1171 11B0; # (귉; 귉; 귉; 귉; 귉; ) HANGUL SYLLABLE GWILG
+ADCA;ADCA;1100 1171 11B1;ADCA;1100 1171 11B1; # (귊; 귊; 귊; 귊; 귊; ) HANGUL SYLLABLE GWILM
+ADCB;ADCB;1100 1171 11B2;ADCB;1100 1171 11B2; # (귋; 귋; 귋; 귋; 귋; ) HANGUL SYLLABLE GWILB
+ADCC;ADCC;1100 1171 11B3;ADCC;1100 1171 11B3; # (귌; 귌; 귌; 귌; 귌; ) HANGUL SYLLABLE GWILS
+ADCD;ADCD;1100 1171 11B4;ADCD;1100 1171 11B4; # (귍; 귍; 귍; 귍; 귍; ) HANGUL SYLLABLE GWILT
+ADCE;ADCE;1100 1171 11B5;ADCE;1100 1171 11B5; # (귎; 귎; 귎; 귎; 귎; ) HANGUL SYLLABLE GWILP
+ADCF;ADCF;1100 1171 11B6;ADCF;1100 1171 11B6; # (귏; 귏; 귏; 귏; 귏; ) HANGUL SYLLABLE GWILH
+ADD0;ADD0;1100 1171 11B7;ADD0;1100 1171 11B7; # (귐; 귐; 귐; 귐; 귐; ) HANGUL SYLLABLE GWIM
+ADD1;ADD1;1100 1171 11B8;ADD1;1100 1171 11B8; # (귑; 귑; 귑; 귑; 귑; ) HANGUL SYLLABLE GWIB
+ADD2;ADD2;1100 1171 11B9;ADD2;1100 1171 11B9; # (귒; 귒; 귒; 귒; 귒; ) HANGUL SYLLABLE GWIBS
+ADD3;ADD3;1100 1171 11BA;ADD3;1100 1171 11BA; # (귓; 귓; 귓; 귓; 귓; ) HANGUL SYLLABLE GWIS
+ADD4;ADD4;1100 1171 11BB;ADD4;1100 1171 11BB; # (귔; 귔; 귔; 귔; 귔; ) HANGUL SYLLABLE GWISS
+ADD5;ADD5;1100 1171 11BC;ADD5;1100 1171 11BC; # (귕; 귕; 귕; 귕; 귕; ) HANGUL SYLLABLE GWING
+ADD6;ADD6;1100 1171 11BD;ADD6;1100 1171 11BD; # (귖; 귖; 귖; 귖; 귖; ) HANGUL SYLLABLE GWIJ
+ADD7;ADD7;1100 1171 11BE;ADD7;1100 1171 11BE; # (귗; 귗; 귗; 귗; 귗; ) HANGUL SYLLABLE GWIC
+ADD8;ADD8;1100 1171 11BF;ADD8;1100 1171 11BF; # (귘; 귘; 귘; 귘; 귘; ) HANGUL SYLLABLE GWIK
+ADD9;ADD9;1100 1171 11C0;ADD9;1100 1171 11C0; # (귙; 귙; 귙; 귙; 귙; ) HANGUL SYLLABLE GWIT
+ADDA;ADDA;1100 1171 11C1;ADDA;1100 1171 11C1; # (귚; 귚; 귚; 귚; 귚; ) HANGUL SYLLABLE GWIP
+ADDB;ADDB;1100 1171 11C2;ADDB;1100 1171 11C2; # (귛; 귛; 귛; 귛; 귛; ) HANGUL SYLLABLE GWIH
+ADDC;ADDC;1100 1172;ADDC;1100 1172; # (규; 규; 규; 규; 규; ) HANGUL SYLLABLE GYU
+ADDD;ADDD;1100 1172 11A8;ADDD;1100 1172 11A8; # (귝; 귝; 귝; 귝; 귝; ) HANGUL SYLLABLE GYUG
+ADDE;ADDE;1100 1172 11A9;ADDE;1100 1172 11A9; # (귞; 귞; 귞; 귞; 귞; ) HANGUL SYLLABLE GYUGG
+ADDF;ADDF;1100 1172 11AA;ADDF;1100 1172 11AA; # (귟; 귟; 귟; 귟; 귟; ) HANGUL SYLLABLE GYUGS
+ADE0;ADE0;1100 1172 11AB;ADE0;1100 1172 11AB; # (균; 균; 균; 균; 균; ) HANGUL SYLLABLE GYUN
+ADE1;ADE1;1100 1172 11AC;ADE1;1100 1172 11AC; # (귡; 귡; 귡; 귡; 귡; ) HANGUL SYLLABLE GYUNJ
+ADE2;ADE2;1100 1172 11AD;ADE2;1100 1172 11AD; # (귢; 귢; 귢; 귢; 귢; ) HANGUL SYLLABLE GYUNH
+ADE3;ADE3;1100 1172 11AE;ADE3;1100 1172 11AE; # (귣; 귣; 귣; 귣; 귣; ) HANGUL SYLLABLE GYUD
+ADE4;ADE4;1100 1172 11AF;ADE4;1100 1172 11AF; # (귤; 귤; 귤; 귤; 귤; ) HANGUL SYLLABLE GYUL
+ADE5;ADE5;1100 1172 11B0;ADE5;1100 1172 11B0; # (귥; 귥; 귥; 귥; 귥; ) HANGUL SYLLABLE GYULG
+ADE6;ADE6;1100 1172 11B1;ADE6;1100 1172 11B1; # (귦; 귦; 귦; 귦; 귦; ) HANGUL SYLLABLE GYULM
+ADE7;ADE7;1100 1172 11B2;ADE7;1100 1172 11B2; # (귧; 귧; 귧; 귧; 귧; ) HANGUL SYLLABLE GYULB
+ADE8;ADE8;1100 1172 11B3;ADE8;1100 1172 11B3; # (귨; 귨; 귨; 귨; 귨; ) HANGUL SYLLABLE GYULS
+ADE9;ADE9;1100 1172 11B4;ADE9;1100 1172 11B4; # (귩; 귩; 귩; 귩; 귩; ) HANGUL SYLLABLE GYULT
+ADEA;ADEA;1100 1172 11B5;ADEA;1100 1172 11B5; # (귪; 귪; 귪; 귪; 귪; ) HANGUL SYLLABLE GYULP
+ADEB;ADEB;1100 1172 11B6;ADEB;1100 1172 11B6; # (귫; 귫; 귫; 귫; 귫; ) HANGUL SYLLABLE GYULH
+ADEC;ADEC;1100 1172 11B7;ADEC;1100 1172 11B7; # (귬; 귬; 귬; 귬; 귬; ) HANGUL SYLLABLE GYUM
+ADED;ADED;1100 1172 11B8;ADED;1100 1172 11B8; # (귭; 귭; 귭; 귭; 귭; ) HANGUL SYLLABLE GYUB
+ADEE;ADEE;1100 1172 11B9;ADEE;1100 1172 11B9; # (귮; 귮; 귮; 귮; 귮; ) HANGUL SYLLABLE GYUBS
+ADEF;ADEF;1100 1172 11BA;ADEF;1100 1172 11BA; # (귯; 귯; 귯; 귯; 귯; ) HANGUL SYLLABLE GYUS
+ADF0;ADF0;1100 1172 11BB;ADF0;1100 1172 11BB; # (귰; 귰; 귰; 귰; 귰; ) HANGUL SYLLABLE GYUSS
+ADF1;ADF1;1100 1172 11BC;ADF1;1100 1172 11BC; # (귱; 귱; 귱; 귱; 귱; ) HANGUL SYLLABLE GYUNG
+ADF2;ADF2;1100 1172 11BD;ADF2;1100 1172 11BD; # (귲; 귲; 귲; 귲; 귲; ) HANGUL SYLLABLE GYUJ
+ADF3;ADF3;1100 1172 11BE;ADF3;1100 1172 11BE; # (귳; 귳; 귳; 귳; 귳; ) HANGUL SYLLABLE GYUC
+ADF4;ADF4;1100 1172 11BF;ADF4;1100 1172 11BF; # (귴; 귴; 귴; 귴; 귴; ) HANGUL SYLLABLE GYUK
+ADF5;ADF5;1100 1172 11C0;ADF5;1100 1172 11C0; # (귵; 귵; 귵; 귵; 귵; ) HANGUL SYLLABLE GYUT
+ADF6;ADF6;1100 1172 11C1;ADF6;1100 1172 11C1; # (귶; 귶; 귶; 귶; 귶; ) HANGUL SYLLABLE GYUP
+ADF7;ADF7;1100 1172 11C2;ADF7;1100 1172 11C2; # (귷; 귷; 귷; 귷; 귷; ) HANGUL SYLLABLE GYUH
+ADF8;ADF8;1100 1173;ADF8;1100 1173; # (그; 그; 그; 그; 그; ) HANGUL SYLLABLE GEU
+ADF9;ADF9;1100 1173 11A8;ADF9;1100 1173 11A8; # (극; 극; 극; 극; 극; ) HANGUL SYLLABLE GEUG
+ADFA;ADFA;1100 1173 11A9;ADFA;1100 1173 11A9; # (귺; 귺; 귺; 귺; 귺; ) HANGUL SYLLABLE GEUGG
+ADFB;ADFB;1100 1173 11AA;ADFB;1100 1173 11AA; # (귻; 귻; 귻; 귻; 귻; ) HANGUL SYLLABLE GEUGS
+ADFC;ADFC;1100 1173 11AB;ADFC;1100 1173 11AB; # (근; 근; 근; 근; 근; ) HANGUL SYLLABLE GEUN
+ADFD;ADFD;1100 1173 11AC;ADFD;1100 1173 11AC; # (귽; 귽; 귽; 귽; 귽; ) HANGUL SYLLABLE GEUNJ
+ADFE;ADFE;1100 1173 11AD;ADFE;1100 1173 11AD; # (귾; 귾; 귾; 귾; 귾; ) HANGUL SYLLABLE GEUNH
+ADFF;ADFF;1100 1173 11AE;ADFF;1100 1173 11AE; # (귿; 귿; 귿; 귿; 귿; ) HANGUL SYLLABLE GEUD
+AE00;AE00;1100 1173 11AF;AE00;1100 1173 11AF; # (글; 글; 글; 글; 글; ) HANGUL SYLLABLE GEUL
+AE01;AE01;1100 1173 11B0;AE01;1100 1173 11B0; # (긁; 긁; 긁; 긁; 긁; ) HANGUL SYLLABLE GEULG
+AE02;AE02;1100 1173 11B1;AE02;1100 1173 11B1; # (긂; 긂; 긂; 긂; 긂; ) HANGUL SYLLABLE GEULM
+AE03;AE03;1100 1173 11B2;AE03;1100 1173 11B2; # (긃; 긃; 긃; 긃; 긃; ) HANGUL SYLLABLE GEULB
+AE04;AE04;1100 1173 11B3;AE04;1100 1173 11B3; # (긄; 긄; 긄; 긄; 긄; ) HANGUL SYLLABLE GEULS
+AE05;AE05;1100 1173 11B4;AE05;1100 1173 11B4; # (긅; 긅; 긅; 긅; 긅; ) HANGUL SYLLABLE GEULT
+AE06;AE06;1100 1173 11B5;AE06;1100 1173 11B5; # (긆; 긆; 긆; 긆; 긆; ) HANGUL SYLLABLE GEULP
+AE07;AE07;1100 1173 11B6;AE07;1100 1173 11B6; # (긇; 긇; 긇; 긇; 긇; ) HANGUL SYLLABLE GEULH
+AE08;AE08;1100 1173 11B7;AE08;1100 1173 11B7; # (금; 금; 금; 금; 금; ) HANGUL SYLLABLE GEUM
+AE09;AE09;1100 1173 11B8;AE09;1100 1173 11B8; # (급; 급; 급; 급; 급; ) HANGUL SYLLABLE GEUB
+AE0A;AE0A;1100 1173 11B9;AE0A;1100 1173 11B9; # (긊; 긊; 긊; 긊; 긊; ) HANGUL SYLLABLE GEUBS
+AE0B;AE0B;1100 1173 11BA;AE0B;1100 1173 11BA; # (긋; 긋; 긋; 긋; 긋; ) HANGUL SYLLABLE GEUS
+AE0C;AE0C;1100 1173 11BB;AE0C;1100 1173 11BB; # (긌; 긌; 긌; 긌; 긌; ) HANGUL SYLLABLE GEUSS
+AE0D;AE0D;1100 1173 11BC;AE0D;1100 1173 11BC; # (긍; 긍; 긍; 긍; 긍; ) HANGUL SYLLABLE GEUNG
+AE0E;AE0E;1100 1173 11BD;AE0E;1100 1173 11BD; # (긎; 긎; 긎; 긎; 긎; ) HANGUL SYLLABLE GEUJ
+AE0F;AE0F;1100 1173 11BE;AE0F;1100 1173 11BE; # (긏; 긏; 긏; 긏; 긏; ) HANGUL SYLLABLE GEUC
+AE10;AE10;1100 1173 11BF;AE10;1100 1173 11BF; # (긐; 긐; 긐; 긐; 긐; ) HANGUL SYLLABLE GEUK
+AE11;AE11;1100 1173 11C0;AE11;1100 1173 11C0; # (긑; 긑; 긑; 긑; 긑; ) HANGUL SYLLABLE GEUT
+AE12;AE12;1100 1173 11C1;AE12;1100 1173 11C1; # (긒; 긒; 긒; 긒; 긒; ) HANGUL SYLLABLE GEUP
+AE13;AE13;1100 1173 11C2;AE13;1100 1173 11C2; # (긓; 긓; 긓; 긓; 긓; ) HANGUL SYLLABLE GEUH
+AE14;AE14;1100 1174;AE14;1100 1174; # (긔; 긔; 긔; 긔; 긔; ) HANGUL SYLLABLE GYI
+AE15;AE15;1100 1174 11A8;AE15;1100 1174 11A8; # (긕; 긕; 긕; 긕; 긕; ) HANGUL SYLLABLE GYIG
+AE16;AE16;1100 1174 11A9;AE16;1100 1174 11A9; # (긖; 긖; 긖; 긖; 긖; ) HANGUL SYLLABLE GYIGG
+AE17;AE17;1100 1174 11AA;AE17;1100 1174 11AA; # (긗; 긗; 긗; 긗; 긗; ) HANGUL SYLLABLE GYIGS
+AE18;AE18;1100 1174 11AB;AE18;1100 1174 11AB; # (긘; 긘; 긘; 긘; 긘; ) HANGUL SYLLABLE GYIN
+AE19;AE19;1100 1174 11AC;AE19;1100 1174 11AC; # (긙; 긙; 긙; 긙; 긙; ) HANGUL SYLLABLE GYINJ
+AE1A;AE1A;1100 1174 11AD;AE1A;1100 1174 11AD; # (긚; 긚; 긚; 긚; 긚; ) HANGUL SYLLABLE GYINH
+AE1B;AE1B;1100 1174 11AE;AE1B;1100 1174 11AE; # (긛; 긛; 긛; 긛; 긛; ) HANGUL SYLLABLE GYID
+AE1C;AE1C;1100 1174 11AF;AE1C;1100 1174 11AF; # (긜; 긜; 긜; 긜; 긜; ) HANGUL SYLLABLE GYIL
+AE1D;AE1D;1100 1174 11B0;AE1D;1100 1174 11B0; # (긝; 긝; 긝; 긝; 긝; ) HANGUL SYLLABLE GYILG
+AE1E;AE1E;1100 1174 11B1;AE1E;1100 1174 11B1; # (긞; 긞; 긞; 긞; 긞; ) HANGUL SYLLABLE GYILM
+AE1F;AE1F;1100 1174 11B2;AE1F;1100 1174 11B2; # (긟; 긟; 긟; 긟; 긟; ) HANGUL SYLLABLE GYILB
+AE20;AE20;1100 1174 11B3;AE20;1100 1174 11B3; # (긠; 긠; 긠; 긠; 긠; ) HANGUL SYLLABLE GYILS
+AE21;AE21;1100 1174 11B4;AE21;1100 1174 11B4; # (긡; 긡; 긡; 긡; 긡; ) HANGUL SYLLABLE GYILT
+AE22;AE22;1100 1174 11B5;AE22;1100 1174 11B5; # (긢; 긢; 긢; 긢; 긢; ) HANGUL SYLLABLE GYILP
+AE23;AE23;1100 1174 11B6;AE23;1100 1174 11B6; # (긣; 긣; 긣; 긣; 긣; ) HANGUL SYLLABLE GYILH
+AE24;AE24;1100 1174 11B7;AE24;1100 1174 11B7; # (긤; 긤; 긤; 긤; 긤; ) HANGUL SYLLABLE GYIM
+AE25;AE25;1100 1174 11B8;AE25;1100 1174 11B8; # (긥; 긥; 긥; 긥; 긥; ) HANGUL SYLLABLE GYIB
+AE26;AE26;1100 1174 11B9;AE26;1100 1174 11B9; # (긦; 긦; 긦; 긦; 긦; ) HANGUL SYLLABLE GYIBS
+AE27;AE27;1100 1174 11BA;AE27;1100 1174 11BA; # (긧; 긧; 긧; 긧; 긧; ) HANGUL SYLLABLE GYIS
+AE28;AE28;1100 1174 11BB;AE28;1100 1174 11BB; # (긨; 긨; 긨; 긨; 긨; ) HANGUL SYLLABLE GYISS
+AE29;AE29;1100 1174 11BC;AE29;1100 1174 11BC; # (긩; 긩; 긩; 긩; 긩; ) HANGUL SYLLABLE GYING
+AE2A;AE2A;1100 1174 11BD;AE2A;1100 1174 11BD; # (긪; 긪; 긪; 긪; 긪; ) HANGUL SYLLABLE GYIJ
+AE2B;AE2B;1100 1174 11BE;AE2B;1100 1174 11BE; # (긫; 긫; 긫; 긫; 긫; ) HANGUL SYLLABLE GYIC
+AE2C;AE2C;1100 1174 11BF;AE2C;1100 1174 11BF; # (긬; 긬; 긬; 긬; 긬; ) HANGUL SYLLABLE GYIK
+AE2D;AE2D;1100 1174 11C0;AE2D;1100 1174 11C0; # (긭; 긭; 긭; 긭; 긭; ) HANGUL SYLLABLE GYIT
+AE2E;AE2E;1100 1174 11C1;AE2E;1100 1174 11C1; # (긮; 긮; 긮; 긮; 긮; ) HANGUL SYLLABLE GYIP
+AE2F;AE2F;1100 1174 11C2;AE2F;1100 1174 11C2; # (긯; 긯; 긯; 긯; 긯; ) HANGUL SYLLABLE GYIH
+AE30;AE30;1100 1175;AE30;1100 1175; # (기; 기; 기; 기; 기; ) HANGUL SYLLABLE GI
+AE31;AE31;1100 1175 11A8;AE31;1100 1175 11A8; # (긱; 긱; 긱; 긱; 긱; ) HANGUL SYLLABLE GIG
+AE32;AE32;1100 1175 11A9;AE32;1100 1175 11A9; # (긲; 긲; 긲; 긲; 긲; ) HANGUL SYLLABLE GIGG
+AE33;AE33;1100 1175 11AA;AE33;1100 1175 11AA; # (긳; 긳; 긳; 긳; 긳; ) HANGUL SYLLABLE GIGS
+AE34;AE34;1100 1175 11AB;AE34;1100 1175 11AB; # (긴; 긴; 긴; 긴; 긴; ) HANGUL SYLLABLE GIN
+AE35;AE35;1100 1175 11AC;AE35;1100 1175 11AC; # (긵; 긵; 긵; 긵; 긵; ) HANGUL SYLLABLE GINJ
+AE36;AE36;1100 1175 11AD;AE36;1100 1175 11AD; # (긶; 긶; 긶; 긶; 긶; ) HANGUL SYLLABLE GINH
+AE37;AE37;1100 1175 11AE;AE37;1100 1175 11AE; # (긷; 긷; 긷; 긷; 긷; ) HANGUL SYLLABLE GID
+AE38;AE38;1100 1175 11AF;AE38;1100 1175 11AF; # (길; 길; 길; 길; 길; ) HANGUL SYLLABLE GIL
+AE39;AE39;1100 1175 11B0;AE39;1100 1175 11B0; # (긹; 긹; 긹; 긹; 긹; ) HANGUL SYLLABLE GILG
+AE3A;AE3A;1100 1175 11B1;AE3A;1100 1175 11B1; # (긺; 긺; 긺; 긺; 긺; ) HANGUL SYLLABLE GILM
+AE3B;AE3B;1100 1175 11B2;AE3B;1100 1175 11B2; # (긻; 긻; 긻; 긻; 긻; ) HANGUL SYLLABLE GILB
+AE3C;AE3C;1100 1175 11B3;AE3C;1100 1175 11B3; # (긼; 긼; 긼; 긼; 긼; ) HANGUL SYLLABLE GILS
+AE3D;AE3D;1100 1175 11B4;AE3D;1100 1175 11B4; # (긽; 긽; 긽; 긽; 긽; ) HANGUL SYLLABLE GILT
+AE3E;AE3E;1100 1175 11B5;AE3E;1100 1175 11B5; # (긾; 긾; 긾; 긾; 긾; ) HANGUL SYLLABLE GILP
+AE3F;AE3F;1100 1175 11B6;AE3F;1100 1175 11B6; # (긿; 긿; 긿; 긿; 긿; ) HANGUL SYLLABLE GILH
+AE40;AE40;1100 1175 11B7;AE40;1100 1175 11B7; # (김; 김; 김; 김; 김; ) HANGUL SYLLABLE GIM
+AE41;AE41;1100 1175 11B8;AE41;1100 1175 11B8; # (깁; 깁; 깁; 깁; 깁; ) HANGUL SYLLABLE GIB
+AE42;AE42;1100 1175 11B9;AE42;1100 1175 11B9; # (깂; 깂; 깂; 깂; 깂; ) HANGUL SYLLABLE GIBS
+AE43;AE43;1100 1175 11BA;AE43;1100 1175 11BA; # (깃; 깃; 깃; 깃; 깃; ) HANGUL SYLLABLE GIS
+AE44;AE44;1100 1175 11BB;AE44;1100 1175 11BB; # (깄; 깄; 깄; 깄; 깄; ) HANGUL SYLLABLE GISS
+AE45;AE45;1100 1175 11BC;AE45;1100 1175 11BC; # (깅; 깅; 깅; 깅; 깅; ) HANGUL SYLLABLE GING
+AE46;AE46;1100 1175 11BD;AE46;1100 1175 11BD; # (깆; 깆; 깆; 깆; 깆; ) HANGUL SYLLABLE GIJ
+AE47;AE47;1100 1175 11BE;AE47;1100 1175 11BE; # (깇; 깇; 깇; 깇; 깇; ) HANGUL SYLLABLE GIC
+AE48;AE48;1100 1175 11BF;AE48;1100 1175 11BF; # (깈; 깈; 깈; 깈; 깈; ) HANGUL SYLLABLE GIK
+AE49;AE49;1100 1175 11C0;AE49;1100 1175 11C0; # (깉; 깉; 깉; 깉; 깉; ) HANGUL SYLLABLE GIT
+AE4A;AE4A;1100 1175 11C1;AE4A;1100 1175 11C1; # (깊; 깊; 깊; 깊; 깊; ) HANGUL SYLLABLE GIP
+AE4B;AE4B;1100 1175 11C2;AE4B;1100 1175 11C2; # (깋; 깋; 깋; 깋; 깋; ) HANGUL SYLLABLE GIH
+AE4C;AE4C;1101 1161;AE4C;1101 1161; # (까; 까; 까; 까; 까; ) HANGUL SYLLABLE GGA
+AE4D;AE4D;1101 1161 11A8;AE4D;1101 1161 11A8; # (깍; 깍; 깍; 깍; 깍; ) HANGUL SYLLABLE GGAG
+AE4E;AE4E;1101 1161 11A9;AE4E;1101 1161 11A9; # (깎; 깎; 깎; 깎; 깎; ) HANGUL SYLLABLE GGAGG
+AE4F;AE4F;1101 1161 11AA;AE4F;1101 1161 11AA; # (깏; 깏; 깏; 깏; 깏; ) HANGUL SYLLABLE GGAGS
+AE50;AE50;1101 1161 11AB;AE50;1101 1161 11AB; # (깐; 깐; 깐; 깐; 깐; ) HANGUL SYLLABLE GGAN
+AE51;AE51;1101 1161 11AC;AE51;1101 1161 11AC; # (깑; 깑; 깑; 깑; 깑; ) HANGUL SYLLABLE GGANJ
+AE52;AE52;1101 1161 11AD;AE52;1101 1161 11AD; # (깒; 깒; 깒; 깒; 깒; ) HANGUL SYLLABLE GGANH
+AE53;AE53;1101 1161 11AE;AE53;1101 1161 11AE; # (깓; 깓; 깓; 깓; 깓; ) HANGUL SYLLABLE GGAD
+AE54;AE54;1101 1161 11AF;AE54;1101 1161 11AF; # (깔; 깔; 깔; 깔; 깔; ) HANGUL SYLLABLE GGAL
+AE55;AE55;1101 1161 11B0;AE55;1101 1161 11B0; # (깕; 깕; 깕; 깕; 깕; ) HANGUL SYLLABLE GGALG
+AE56;AE56;1101 1161 11B1;AE56;1101 1161 11B1; # (깖; 깖; 깖; 깖; 깖; ) HANGUL SYLLABLE GGALM
+AE57;AE57;1101 1161 11B2;AE57;1101 1161 11B2; # (깗; 깗; 깗; 깗; 깗; ) HANGUL SYLLABLE GGALB
+AE58;AE58;1101 1161 11B3;AE58;1101 1161 11B3; # (깘; 깘; 깘; 깘; 깘; ) HANGUL SYLLABLE GGALS
+AE59;AE59;1101 1161 11B4;AE59;1101 1161 11B4; # (깙; 깙; 깙; 깙; 깙; ) HANGUL SYLLABLE GGALT
+AE5A;AE5A;1101 1161 11B5;AE5A;1101 1161 11B5; # (깚; 깚; 깚; 깚; 깚; ) HANGUL SYLLABLE GGALP
+AE5B;AE5B;1101 1161 11B6;AE5B;1101 1161 11B6; # (깛; 깛; 깛; 깛; 깛; ) HANGUL SYLLABLE GGALH
+AE5C;AE5C;1101 1161 11B7;AE5C;1101 1161 11B7; # (깜; 깜; 깜; 깜; 깜; ) HANGUL SYLLABLE GGAM
+AE5D;AE5D;1101 1161 11B8;AE5D;1101 1161 11B8; # (깝; 깝; 깝; 깝; 깝; ) HANGUL SYLLABLE GGAB
+AE5E;AE5E;1101 1161 11B9;AE5E;1101 1161 11B9; # (깞; 깞; 깞; 깞; 깞; ) HANGUL SYLLABLE GGABS
+AE5F;AE5F;1101 1161 11BA;AE5F;1101 1161 11BA; # (깟; 깟; 깟; 깟; 깟; ) HANGUL SYLLABLE GGAS
+AE60;AE60;1101 1161 11BB;AE60;1101 1161 11BB; # (깠; 깠; 깠; 깠; 깠; ) HANGUL SYLLABLE GGASS
+AE61;AE61;1101 1161 11BC;AE61;1101 1161 11BC; # (깡; 깡; 깡; 깡; 깡; ) HANGUL SYLLABLE GGANG
+AE62;AE62;1101 1161 11BD;AE62;1101 1161 11BD; # (깢; 깢; 깢; 깢; 깢; ) HANGUL SYLLABLE GGAJ
+AE63;AE63;1101 1161 11BE;AE63;1101 1161 11BE; # (깣; 깣; 깣; 깣; 깣; ) HANGUL SYLLABLE GGAC
+AE64;AE64;1101 1161 11BF;AE64;1101 1161 11BF; # (깤; 깤; 깤; 깤; 깤; ) HANGUL SYLLABLE GGAK
+AE65;AE65;1101 1161 11C0;AE65;1101 1161 11C0; # (깥; 깥; 깥; 깥; 깥; ) HANGUL SYLLABLE GGAT
+AE66;AE66;1101 1161 11C1;AE66;1101 1161 11C1; # (깦; 깦; 깦; 깦; 깦; ) HANGUL SYLLABLE GGAP
+AE67;AE67;1101 1161 11C2;AE67;1101 1161 11C2; # (깧; 깧; 깧; 깧; 깧; ) HANGUL SYLLABLE GGAH
+AE68;AE68;1101 1162;AE68;1101 1162; # (깨; 깨; 깨; 깨; 깨; ) HANGUL SYLLABLE GGAE
+AE69;AE69;1101 1162 11A8;AE69;1101 1162 11A8; # (깩; 깩; 깩; 깩; 깩; ) HANGUL SYLLABLE GGAEG
+AE6A;AE6A;1101 1162 11A9;AE6A;1101 1162 11A9; # (깪; 깪; 깪; 깪; 깪; ) HANGUL SYLLABLE GGAEGG
+AE6B;AE6B;1101 1162 11AA;AE6B;1101 1162 11AA; # (깫; 깫; 깫; 깫; 깫; ) HANGUL SYLLABLE GGAEGS
+AE6C;AE6C;1101 1162 11AB;AE6C;1101 1162 11AB; # (깬; 깬; 깬; 깬; 깬; ) HANGUL SYLLABLE GGAEN
+AE6D;AE6D;1101 1162 11AC;AE6D;1101 1162 11AC; # (깭; 깭; 깭; 깭; 깭; ) HANGUL SYLLABLE GGAENJ
+AE6E;AE6E;1101 1162 11AD;AE6E;1101 1162 11AD; # (깮; 깮; 깮; 깮; 깮; ) HANGUL SYLLABLE GGAENH
+AE6F;AE6F;1101 1162 11AE;AE6F;1101 1162 11AE; # (깯; 깯; 깯; 깯; 깯; ) HANGUL SYLLABLE GGAED
+AE70;AE70;1101 1162 11AF;AE70;1101 1162 11AF; # (깰; 깰; 깰; 깰; 깰; ) HANGUL SYLLABLE GGAEL
+AE71;AE71;1101 1162 11B0;AE71;1101 1162 11B0; # (깱; 깱; 깱; 깱; 깱; ) HANGUL SYLLABLE GGAELG
+AE72;AE72;1101 1162 11B1;AE72;1101 1162 11B1; # (깲; 깲; 깲; 깲; 깲; ) HANGUL SYLLABLE GGAELM
+AE73;AE73;1101 1162 11B2;AE73;1101 1162 11B2; # (깳; 깳; 깳; 깳; 깳; ) HANGUL SYLLABLE GGAELB
+AE74;AE74;1101 1162 11B3;AE74;1101 1162 11B3; # (깴; 깴; 깴; 깴; 깴; ) HANGUL SYLLABLE GGAELS
+AE75;AE75;1101 1162 11B4;AE75;1101 1162 11B4; # (깵; 깵; 깵; 깵; 깵; ) HANGUL SYLLABLE GGAELT
+AE76;AE76;1101 1162 11B5;AE76;1101 1162 11B5; # (깶; 깶; 깶; 깶; 깶; ) HANGUL SYLLABLE GGAELP
+AE77;AE77;1101 1162 11B6;AE77;1101 1162 11B6; # (깷; 깷; 깷; 깷; 깷; ) HANGUL SYLLABLE GGAELH
+AE78;AE78;1101 1162 11B7;AE78;1101 1162 11B7; # (깸; 깸; 깸; 깸; 깸; ) HANGUL SYLLABLE GGAEM
+AE79;AE79;1101 1162 11B8;AE79;1101 1162 11B8; # (깹; 깹; 깹; 깹; 깹; ) HANGUL SYLLABLE GGAEB
+AE7A;AE7A;1101 1162 11B9;AE7A;1101 1162 11B9; # (깺; 깺; 깺; 깺; 깺; ) HANGUL SYLLABLE GGAEBS
+AE7B;AE7B;1101 1162 11BA;AE7B;1101 1162 11BA; # (깻; 깻; 깻; 깻; 깻; ) HANGUL SYLLABLE GGAES
+AE7C;AE7C;1101 1162 11BB;AE7C;1101 1162 11BB; # (깼; 깼; 깼; 깼; 깼; ) HANGUL SYLLABLE GGAESS
+AE7D;AE7D;1101 1162 11BC;AE7D;1101 1162 11BC; # (깽; 깽; 깽; 깽; 깽; ) HANGUL SYLLABLE GGAENG
+AE7E;AE7E;1101 1162 11BD;AE7E;1101 1162 11BD; # (깾; 깾; 깾; 깾; 깾; ) HANGUL SYLLABLE GGAEJ
+AE7F;AE7F;1101 1162 11BE;AE7F;1101 1162 11BE; # (깿; 깿; 깿; 깿; 깿; ) HANGUL SYLLABLE GGAEC
+AE80;AE80;1101 1162 11BF;AE80;1101 1162 11BF; # (꺀; 꺀; 꺀; 꺀; 꺀; ) HANGUL SYLLABLE GGAEK
+AE81;AE81;1101 1162 11C0;AE81;1101 1162 11C0; # (꺁; 꺁; 꺁; 꺁; 꺁; ) HANGUL SYLLABLE GGAET
+AE82;AE82;1101 1162 11C1;AE82;1101 1162 11C1; # (꺂; 꺂; 꺂; 꺂; 꺂; ) HANGUL SYLLABLE GGAEP
+AE83;AE83;1101 1162 11C2;AE83;1101 1162 11C2; # (꺃; 꺃; 꺃; 꺃; 꺃; ) HANGUL SYLLABLE GGAEH
+AE84;AE84;1101 1163;AE84;1101 1163; # (꺄; 꺄; 꺄; 꺄; 꺄; ) HANGUL SYLLABLE GGYA
+AE85;AE85;1101 1163 11A8;AE85;1101 1163 11A8; # (꺅; 꺅; 꺅; 꺅; 꺅; ) HANGUL SYLLABLE GGYAG
+AE86;AE86;1101 1163 11A9;AE86;1101 1163 11A9; # (꺆; 꺆; 꺆; 꺆; 꺆; ) HANGUL SYLLABLE GGYAGG
+AE87;AE87;1101 1163 11AA;AE87;1101 1163 11AA; # (꺇; 꺇; 꺇; 꺇; 꺇; ) HANGUL SYLLABLE GGYAGS
+AE88;AE88;1101 1163 11AB;AE88;1101 1163 11AB; # (꺈; 꺈; 꺈; 꺈; 꺈; ) HANGUL SYLLABLE GGYAN
+AE89;AE89;1101 1163 11AC;AE89;1101 1163 11AC; # (꺉; 꺉; 꺉; 꺉; 꺉; ) HANGUL SYLLABLE GGYANJ
+AE8A;AE8A;1101 1163 11AD;AE8A;1101 1163 11AD; # (꺊; 꺊; 꺊; 꺊; 꺊; ) HANGUL SYLLABLE GGYANH
+AE8B;AE8B;1101 1163 11AE;AE8B;1101 1163 11AE; # (꺋; 꺋; 꺋; 꺋; 꺋; ) HANGUL SYLLABLE GGYAD
+AE8C;AE8C;1101 1163 11AF;AE8C;1101 1163 11AF; # (꺌; 꺌; 꺌; 꺌; 꺌; ) HANGUL SYLLABLE GGYAL
+AE8D;AE8D;1101 1163 11B0;AE8D;1101 1163 11B0; # (꺍; 꺍; 꺍; 꺍; 꺍; ) HANGUL SYLLABLE GGYALG
+AE8E;AE8E;1101 1163 11B1;AE8E;1101 1163 11B1; # (꺎; 꺎; 꺎; 꺎; 꺎; ) HANGUL SYLLABLE GGYALM
+AE8F;AE8F;1101 1163 11B2;AE8F;1101 1163 11B2; # (꺏; 꺏; 꺏; 꺏; 꺏; ) HANGUL SYLLABLE GGYALB
+AE90;AE90;1101 1163 11B3;AE90;1101 1163 11B3; # (꺐; 꺐; 꺐; 꺐; 꺐; ) HANGUL SYLLABLE GGYALS
+AE91;AE91;1101 1163 11B4;AE91;1101 1163 11B4; # (꺑; 꺑; 꺑; 꺑; 꺑; ) HANGUL SYLLABLE GGYALT
+AE92;AE92;1101 1163 11B5;AE92;1101 1163 11B5; # (꺒; 꺒; 꺒; 꺒; 꺒; ) HANGUL SYLLABLE GGYALP
+AE93;AE93;1101 1163 11B6;AE93;1101 1163 11B6; # (꺓; 꺓; 꺓; 꺓; 꺓; ) HANGUL SYLLABLE GGYALH
+AE94;AE94;1101 1163 11B7;AE94;1101 1163 11B7; # (꺔; 꺔; 꺔; 꺔; 꺔; ) HANGUL SYLLABLE GGYAM
+AE95;AE95;1101 1163 11B8;AE95;1101 1163 11B8; # (꺕; 꺕; 꺕; 꺕; 꺕; ) HANGUL SYLLABLE GGYAB
+AE96;AE96;1101 1163 11B9;AE96;1101 1163 11B9; # (꺖; 꺖; 꺖; 꺖; 꺖; ) HANGUL SYLLABLE GGYABS
+AE97;AE97;1101 1163 11BA;AE97;1101 1163 11BA; # (꺗; 꺗; 꺗; 꺗; 꺗; ) HANGUL SYLLABLE GGYAS
+AE98;AE98;1101 1163 11BB;AE98;1101 1163 11BB; # (꺘; 꺘; 꺘; 꺘; 꺘; ) HANGUL SYLLABLE GGYASS
+AE99;AE99;1101 1163 11BC;AE99;1101 1163 11BC; # (꺙; 꺙; 꺙; 꺙; 꺙; ) HANGUL SYLLABLE GGYANG
+AE9A;AE9A;1101 1163 11BD;AE9A;1101 1163 11BD; # (꺚; 꺚; 꺚; 꺚; 꺚; ) HANGUL SYLLABLE GGYAJ
+AE9B;AE9B;1101 1163 11BE;AE9B;1101 1163 11BE; # (꺛; 꺛; 꺛; 꺛; 꺛; ) HANGUL SYLLABLE GGYAC
+AE9C;AE9C;1101 1163 11BF;AE9C;1101 1163 11BF; # (꺜; 꺜; 꺜; 꺜; 꺜; ) HANGUL SYLLABLE GGYAK
+AE9D;AE9D;1101 1163 11C0;AE9D;1101 1163 11C0; # (꺝; 꺝; 꺝; 꺝; 꺝; ) HANGUL SYLLABLE GGYAT
+AE9E;AE9E;1101 1163 11C1;AE9E;1101 1163 11C1; # (꺞; 꺞; 꺞; 꺞; 꺞; ) HANGUL SYLLABLE GGYAP
+AE9F;AE9F;1101 1163 11C2;AE9F;1101 1163 11C2; # (꺟; 꺟; 꺟; 꺟; 꺟; ) HANGUL SYLLABLE GGYAH
+AEA0;AEA0;1101 1164;AEA0;1101 1164; # (꺠; 꺠; 꺠; 꺠; 꺠; ) HANGUL SYLLABLE GGYAE
+AEA1;AEA1;1101 1164 11A8;AEA1;1101 1164 11A8; # (꺡; 꺡; 꺡; 꺡; 꺡; ) HANGUL SYLLABLE GGYAEG
+AEA2;AEA2;1101 1164 11A9;AEA2;1101 1164 11A9; # (꺢; 꺢; 꺢; 꺢; 꺢; ) HANGUL SYLLABLE GGYAEGG
+AEA3;AEA3;1101 1164 11AA;AEA3;1101 1164 11AA; # (꺣; 꺣; 꺣; 꺣; 꺣; ) HANGUL SYLLABLE GGYAEGS
+AEA4;AEA4;1101 1164 11AB;AEA4;1101 1164 11AB; # (꺤; 꺤; 꺤; 꺤; 꺤; ) HANGUL SYLLABLE GGYAEN
+AEA5;AEA5;1101 1164 11AC;AEA5;1101 1164 11AC; # (꺥; 꺥; 꺥; 꺥; 꺥; ) HANGUL SYLLABLE GGYAENJ
+AEA6;AEA6;1101 1164 11AD;AEA6;1101 1164 11AD; # (꺦; 꺦; 꺦; 꺦; 꺦; ) HANGUL SYLLABLE GGYAENH
+AEA7;AEA7;1101 1164 11AE;AEA7;1101 1164 11AE; # (꺧; 꺧; 꺧; 꺧; 꺧; ) HANGUL SYLLABLE GGYAED
+AEA8;AEA8;1101 1164 11AF;AEA8;1101 1164 11AF; # (꺨; 꺨; 꺨; 꺨; 꺨; ) HANGUL SYLLABLE GGYAEL
+AEA9;AEA9;1101 1164 11B0;AEA9;1101 1164 11B0; # (꺩; 꺩; 꺩; 꺩; 꺩; ) HANGUL SYLLABLE GGYAELG
+AEAA;AEAA;1101 1164 11B1;AEAA;1101 1164 11B1; # (꺪; 꺪; 꺪; 꺪; 꺪; ) HANGUL SYLLABLE GGYAELM
+AEAB;AEAB;1101 1164 11B2;AEAB;1101 1164 11B2; # (꺫; 꺫; 꺫; 꺫; 꺫; ) HANGUL SYLLABLE GGYAELB
+AEAC;AEAC;1101 1164 11B3;AEAC;1101 1164 11B3; # (꺬; 꺬; 꺬; 꺬; 꺬; ) HANGUL SYLLABLE GGYAELS
+AEAD;AEAD;1101 1164 11B4;AEAD;1101 1164 11B4; # (꺭; 꺭; 꺭; 꺭; 꺭; ) HANGUL SYLLABLE GGYAELT
+AEAE;AEAE;1101 1164 11B5;AEAE;1101 1164 11B5; # (꺮; 꺮; 꺮; 꺮; 꺮; ) HANGUL SYLLABLE GGYAELP
+AEAF;AEAF;1101 1164 11B6;AEAF;1101 1164 11B6; # (꺯; 꺯; 꺯; 꺯; 꺯; ) HANGUL SYLLABLE GGYAELH
+AEB0;AEB0;1101 1164 11B7;AEB0;1101 1164 11B7; # (꺰; 꺰; 꺰; 꺰; 꺰; ) HANGUL SYLLABLE GGYAEM
+AEB1;AEB1;1101 1164 11B8;AEB1;1101 1164 11B8; # (꺱; 꺱; 꺱; 꺱; 꺱; ) HANGUL SYLLABLE GGYAEB
+AEB2;AEB2;1101 1164 11B9;AEB2;1101 1164 11B9; # (꺲; 꺲; 꺲; 꺲; 꺲; ) HANGUL SYLLABLE GGYAEBS
+AEB3;AEB3;1101 1164 11BA;AEB3;1101 1164 11BA; # (꺳; 꺳; 꺳; 꺳; 꺳; ) HANGUL SYLLABLE GGYAES
+AEB4;AEB4;1101 1164 11BB;AEB4;1101 1164 11BB; # (꺴; 꺴; 꺴; 꺴; 꺴; ) HANGUL SYLLABLE GGYAESS
+AEB5;AEB5;1101 1164 11BC;AEB5;1101 1164 11BC; # (꺵; 꺵; 꺵; 꺵; 꺵; ) HANGUL SYLLABLE GGYAENG
+AEB6;AEB6;1101 1164 11BD;AEB6;1101 1164 11BD; # (꺶; 꺶; 꺶; 꺶; 꺶; ) HANGUL SYLLABLE GGYAEJ
+AEB7;AEB7;1101 1164 11BE;AEB7;1101 1164 11BE; # (꺷; 꺷; 꺷; 꺷; 꺷; ) HANGUL SYLLABLE GGYAEC
+AEB8;AEB8;1101 1164 11BF;AEB8;1101 1164 11BF; # (꺸; 꺸; 꺸; 꺸; 꺸; ) HANGUL SYLLABLE GGYAEK
+AEB9;AEB9;1101 1164 11C0;AEB9;1101 1164 11C0; # (꺹; 꺹; 꺹; 꺹; 꺹; ) HANGUL SYLLABLE GGYAET
+AEBA;AEBA;1101 1164 11C1;AEBA;1101 1164 11C1; # (꺺; 꺺; 꺺; 꺺; 꺺; ) HANGUL SYLLABLE GGYAEP
+AEBB;AEBB;1101 1164 11C2;AEBB;1101 1164 11C2; # (꺻; 꺻; 꺻; 꺻; 꺻; ) HANGUL SYLLABLE GGYAEH
+AEBC;AEBC;1101 1165;AEBC;1101 1165; # (꺼; 꺼; 꺼; 꺼; 꺼; ) HANGUL SYLLABLE GGEO
+AEBD;AEBD;1101 1165 11A8;AEBD;1101 1165 11A8; # (꺽; 꺽; 꺽; 꺽; 꺽; ) HANGUL SYLLABLE GGEOG
+AEBE;AEBE;1101 1165 11A9;AEBE;1101 1165 11A9; # (꺾; 꺾; 꺾; 꺾; 꺾; ) HANGUL SYLLABLE GGEOGG
+AEBF;AEBF;1101 1165 11AA;AEBF;1101 1165 11AA; # (꺿; 꺿; 꺿; 꺿; 꺿; ) HANGUL SYLLABLE GGEOGS
+AEC0;AEC0;1101 1165 11AB;AEC0;1101 1165 11AB; # (껀; 껀; 껀; 껀; 껀; ) HANGUL SYLLABLE GGEON
+AEC1;AEC1;1101 1165 11AC;AEC1;1101 1165 11AC; # (껁; 껁; 껁; 껁; 껁; ) HANGUL SYLLABLE GGEONJ
+AEC2;AEC2;1101 1165 11AD;AEC2;1101 1165 11AD; # (껂; 껂; 껂; 껂; 껂; ) HANGUL SYLLABLE GGEONH
+AEC3;AEC3;1101 1165 11AE;AEC3;1101 1165 11AE; # (껃; 껃; 껃; 껃; 껃; ) HANGUL SYLLABLE GGEOD
+AEC4;AEC4;1101 1165 11AF;AEC4;1101 1165 11AF; # (껄; 껄; 껄; 껄; 껄; ) HANGUL SYLLABLE GGEOL
+AEC5;AEC5;1101 1165 11B0;AEC5;1101 1165 11B0; # (껅; 껅; 껅; 껅; 껅; ) HANGUL SYLLABLE GGEOLG
+AEC6;AEC6;1101 1165 11B1;AEC6;1101 1165 11B1; # (껆; 껆; 껆; 껆; 껆; ) HANGUL SYLLABLE GGEOLM
+AEC7;AEC7;1101 1165 11B2;AEC7;1101 1165 11B2; # (껇; 껇; 껇; 껇; 껇; ) HANGUL SYLLABLE GGEOLB
+AEC8;AEC8;1101 1165 11B3;AEC8;1101 1165 11B3; # (껈; 껈; 껈; 껈; 껈; ) HANGUL SYLLABLE GGEOLS
+AEC9;AEC9;1101 1165 11B4;AEC9;1101 1165 11B4; # (껉; 껉; 껉; 껉; 껉; ) HANGUL SYLLABLE GGEOLT
+AECA;AECA;1101 1165 11B5;AECA;1101 1165 11B5; # (껊; 껊; 껊; 껊; 껊; ) HANGUL SYLLABLE GGEOLP
+AECB;AECB;1101 1165 11B6;AECB;1101 1165 11B6; # (껋; 껋; 껋; 껋; 껋; ) HANGUL SYLLABLE GGEOLH
+AECC;AECC;1101 1165 11B7;AECC;1101 1165 11B7; # (껌; 껌; 껌; 껌; 껌; ) HANGUL SYLLABLE GGEOM
+AECD;AECD;1101 1165 11B8;AECD;1101 1165 11B8; # (껍; 껍; 껍; 껍; 껍; ) HANGUL SYLLABLE GGEOB
+AECE;AECE;1101 1165 11B9;AECE;1101 1165 11B9; # (껎; 껎; 껎; 껎; 껎; ) HANGUL SYLLABLE GGEOBS
+AECF;AECF;1101 1165 11BA;AECF;1101 1165 11BA; # (껏; 껏; 껏; 껏; 껏; ) HANGUL SYLLABLE GGEOS
+AED0;AED0;1101 1165 11BB;AED0;1101 1165 11BB; # (껐; 껐; 껐; 껐; 껐; ) HANGUL SYLLABLE GGEOSS
+AED1;AED1;1101 1165 11BC;AED1;1101 1165 11BC; # (껑; 껑; 껑; 껑; 껑; ) HANGUL SYLLABLE GGEONG
+AED2;AED2;1101 1165 11BD;AED2;1101 1165 11BD; # (껒; 껒; 껒; 껒; 껒; ) HANGUL SYLLABLE GGEOJ
+AED3;AED3;1101 1165 11BE;AED3;1101 1165 11BE; # (껓; 껓; 껓; 껓; 껓; ) HANGUL SYLLABLE GGEOC
+AED4;AED4;1101 1165 11BF;AED4;1101 1165 11BF; # (껔; 껔; 껔; 껔; 껔; ) HANGUL SYLLABLE GGEOK
+AED5;AED5;1101 1165 11C0;AED5;1101 1165 11C0; # (껕; 껕; 껕; 껕; 껕; ) HANGUL SYLLABLE GGEOT
+AED6;AED6;1101 1165 11C1;AED6;1101 1165 11C1; # (껖; 껖; 껖; 껖; 껖; ) HANGUL SYLLABLE GGEOP
+AED7;AED7;1101 1165 11C2;AED7;1101 1165 11C2; # (껗; 껗; 껗; 껗; 껗; ) HANGUL SYLLABLE GGEOH
+AED8;AED8;1101 1166;AED8;1101 1166; # (께; 께; 께; 께; 께; ) HANGUL SYLLABLE GGE
+AED9;AED9;1101 1166 11A8;AED9;1101 1166 11A8; # (껙; 껙; 껙; 껙; 껙; ) HANGUL SYLLABLE GGEG
+AEDA;AEDA;1101 1166 11A9;AEDA;1101 1166 11A9; # (껚; 껚; 껚; 껚; 껚; ) HANGUL SYLLABLE GGEGG
+AEDB;AEDB;1101 1166 11AA;AEDB;1101 1166 11AA; # (껛; 껛; 껛; 껛; 껛; ) HANGUL SYLLABLE GGEGS
+AEDC;AEDC;1101 1166 11AB;AEDC;1101 1166 11AB; # (껜; 껜; 껜; 껜; 껜; ) HANGUL SYLLABLE GGEN
+AEDD;AEDD;1101 1166 11AC;AEDD;1101 1166 11AC; # (껝; 껝; 껝; 껝; 껝; ) HANGUL SYLLABLE GGENJ
+AEDE;AEDE;1101 1166 11AD;AEDE;1101 1166 11AD; # (껞; 껞; 껞; 껞; 껞; ) HANGUL SYLLABLE GGENH
+AEDF;AEDF;1101 1166 11AE;AEDF;1101 1166 11AE; # (껟; 껟; 껟; 껟; 껟; ) HANGUL SYLLABLE GGED
+AEE0;AEE0;1101 1166 11AF;AEE0;1101 1166 11AF; # (껠; 껠; 껠; 껠; 껠; ) HANGUL SYLLABLE GGEL
+AEE1;AEE1;1101 1166 11B0;AEE1;1101 1166 11B0; # (껡; 껡; 껡; 껡; 껡; ) HANGUL SYLLABLE GGELG
+AEE2;AEE2;1101 1166 11B1;AEE2;1101 1166 11B1; # (껢; 껢; 껢; 껢; 껢; ) HANGUL SYLLABLE GGELM
+AEE3;AEE3;1101 1166 11B2;AEE3;1101 1166 11B2; # (껣; 껣; 껣; 껣; 껣; ) HANGUL SYLLABLE GGELB
+AEE4;AEE4;1101 1166 11B3;AEE4;1101 1166 11B3; # (껤; 껤; 껤; 껤; 껤; ) HANGUL SYLLABLE GGELS
+AEE5;AEE5;1101 1166 11B4;AEE5;1101 1166 11B4; # (껥; 껥; 껥; 껥; 껥; ) HANGUL SYLLABLE GGELT
+AEE6;AEE6;1101 1166 11B5;AEE6;1101 1166 11B5; # (껦; 껦; 껦; 껦; 껦; ) HANGUL SYLLABLE GGELP
+AEE7;AEE7;1101 1166 11B6;AEE7;1101 1166 11B6; # (껧; 껧; 껧; 껧; 껧; ) HANGUL SYLLABLE GGELH
+AEE8;AEE8;1101 1166 11B7;AEE8;1101 1166 11B7; # (껨; 껨; 껨; 껨; 껨; ) HANGUL SYLLABLE GGEM
+AEE9;AEE9;1101 1166 11B8;AEE9;1101 1166 11B8; # (껩; 껩; 껩; 껩; 껩; ) HANGUL SYLLABLE GGEB
+AEEA;AEEA;1101 1166 11B9;AEEA;1101 1166 11B9; # (껪; 껪; 껪; 껪; 껪; ) HANGUL SYLLABLE GGEBS
+AEEB;AEEB;1101 1166 11BA;AEEB;1101 1166 11BA; # (껫; 껫; 껫; 껫; 껫; ) HANGUL SYLLABLE GGES
+AEEC;AEEC;1101 1166 11BB;AEEC;1101 1166 11BB; # (껬; 껬; 껬; 껬; 껬; ) HANGUL SYLLABLE GGESS
+AEED;AEED;1101 1166 11BC;AEED;1101 1166 11BC; # (껭; 껭; 껭; 껭; 껭; ) HANGUL SYLLABLE GGENG
+AEEE;AEEE;1101 1166 11BD;AEEE;1101 1166 11BD; # (껮; 껮; 껮; 껮; 껮; ) HANGUL SYLLABLE GGEJ
+AEEF;AEEF;1101 1166 11BE;AEEF;1101 1166 11BE; # (껯; 껯; 껯; 껯; 껯; ) HANGUL SYLLABLE GGEC
+AEF0;AEF0;1101 1166 11BF;AEF0;1101 1166 11BF; # (껰; 껰; 껰; 껰; 껰; ) HANGUL SYLLABLE GGEK
+AEF1;AEF1;1101 1166 11C0;AEF1;1101 1166 11C0; # (껱; 껱; 껱; 껱; 껱; ) HANGUL SYLLABLE GGET
+AEF2;AEF2;1101 1166 11C1;AEF2;1101 1166 11C1; # (껲; 껲; 껲; 껲; 껲; ) HANGUL SYLLABLE GGEP
+AEF3;AEF3;1101 1166 11C2;AEF3;1101 1166 11C2; # (껳; 껳; 껳; 껳; 껳; ) HANGUL SYLLABLE GGEH
+AEF4;AEF4;1101 1167;AEF4;1101 1167; # (껴; 껴; 껴; 껴; 껴; ) HANGUL SYLLABLE GGYEO
+AEF5;AEF5;1101 1167 11A8;AEF5;1101 1167 11A8; # (껵; 껵; 껵; 껵; 껵; ) HANGUL SYLLABLE GGYEOG
+AEF6;AEF6;1101 1167 11A9;AEF6;1101 1167 11A9; # (껶; 껶; 껶; 껶; 껶; ) HANGUL SYLLABLE GGYEOGG
+AEF7;AEF7;1101 1167 11AA;AEF7;1101 1167 11AA; # (껷; 껷; 껷; 껷; 껷; ) HANGUL SYLLABLE GGYEOGS
+AEF8;AEF8;1101 1167 11AB;AEF8;1101 1167 11AB; # (껸; 껸; 껸; 껸; 껸; ) HANGUL SYLLABLE GGYEON
+AEF9;AEF9;1101 1167 11AC;AEF9;1101 1167 11AC; # (껹; 껹; 껹; 껹; 껹; ) HANGUL SYLLABLE GGYEONJ
+AEFA;AEFA;1101 1167 11AD;AEFA;1101 1167 11AD; # (껺; 껺; 껺; 껺; 껺; ) HANGUL SYLLABLE GGYEONH
+AEFB;AEFB;1101 1167 11AE;AEFB;1101 1167 11AE; # (껻; 껻; 껻; 껻; 껻; ) HANGUL SYLLABLE GGYEOD
+AEFC;AEFC;1101 1167 11AF;AEFC;1101 1167 11AF; # (껼; 껼; 껼; 껼; 껼; ) HANGUL SYLLABLE GGYEOL
+AEFD;AEFD;1101 1167 11B0;AEFD;1101 1167 11B0; # (껽; 껽; 껽; 껽; 껽; ) HANGUL SYLLABLE GGYEOLG
+AEFE;AEFE;1101 1167 11B1;AEFE;1101 1167 11B1; # (껾; 껾; 껾; 껾; 껾; ) HANGUL SYLLABLE GGYEOLM
+AEFF;AEFF;1101 1167 11B2;AEFF;1101 1167 11B2; # (껿; 껿; 껿; 껿; 껿; ) HANGUL SYLLABLE GGYEOLB
+AF00;AF00;1101 1167 11B3;AF00;1101 1167 11B3; # (꼀; 꼀; 꼀; 꼀; 꼀; ) HANGUL SYLLABLE GGYEOLS
+AF01;AF01;1101 1167 11B4;AF01;1101 1167 11B4; # (꼁; 꼁; 꼁; 꼁; 꼁; ) HANGUL SYLLABLE GGYEOLT
+AF02;AF02;1101 1167 11B5;AF02;1101 1167 11B5; # (꼂; 꼂; 꼂; 꼂; 꼂; ) HANGUL SYLLABLE GGYEOLP
+AF03;AF03;1101 1167 11B6;AF03;1101 1167 11B6; # (꼃; 꼃; 꼃; 꼃; 꼃; ) HANGUL SYLLABLE GGYEOLH
+AF04;AF04;1101 1167 11B7;AF04;1101 1167 11B7; # (꼄; 꼄; 꼄; 꼄; 꼄; ) HANGUL SYLLABLE GGYEOM
+AF05;AF05;1101 1167 11B8;AF05;1101 1167 11B8; # (꼅; 꼅; 꼅; 꼅; 꼅; ) HANGUL SYLLABLE GGYEOB
+AF06;AF06;1101 1167 11B9;AF06;1101 1167 11B9; # (꼆; 꼆; 꼆; 꼆; 꼆; ) HANGUL SYLLABLE GGYEOBS
+AF07;AF07;1101 1167 11BA;AF07;1101 1167 11BA; # (꼇; 꼇; 꼇; 꼇; 꼇; ) HANGUL SYLLABLE GGYEOS
+AF08;AF08;1101 1167 11BB;AF08;1101 1167 11BB; # (꼈; 꼈; 꼈; 꼈; 꼈; ) HANGUL SYLLABLE GGYEOSS
+AF09;AF09;1101 1167 11BC;AF09;1101 1167 11BC; # (꼉; 꼉; 꼉; 꼉; 꼉; ) HANGUL SYLLABLE GGYEONG
+AF0A;AF0A;1101 1167 11BD;AF0A;1101 1167 11BD; # (꼊; 꼊; 꼊; 꼊; 꼊; ) HANGUL SYLLABLE GGYEOJ
+AF0B;AF0B;1101 1167 11BE;AF0B;1101 1167 11BE; # (꼋; 꼋; 꼋; 꼋; 꼋; ) HANGUL SYLLABLE GGYEOC
+AF0C;AF0C;1101 1167 11BF;AF0C;1101 1167 11BF; # (꼌; 꼌; 꼌; 꼌; 꼌; ) HANGUL SYLLABLE GGYEOK
+AF0D;AF0D;1101 1167 11C0;AF0D;1101 1167 11C0; # (꼍; 꼍; 꼍; 꼍; 꼍; ) HANGUL SYLLABLE GGYEOT
+AF0E;AF0E;1101 1167 11C1;AF0E;1101 1167 11C1; # (꼎; 꼎; 꼎; 꼎; 꼎; ) HANGUL SYLLABLE GGYEOP
+AF0F;AF0F;1101 1167 11C2;AF0F;1101 1167 11C2; # (꼏; 꼏; 꼏; 꼏; 꼏; ) HANGUL SYLLABLE GGYEOH
+AF10;AF10;1101 1168;AF10;1101 1168; # (꼐; 꼐; 꼐; 꼐; 꼐; ) HANGUL SYLLABLE GGYE
+AF11;AF11;1101 1168 11A8;AF11;1101 1168 11A8; # (꼑; 꼑; 꼑; 꼑; 꼑; ) HANGUL SYLLABLE GGYEG
+AF12;AF12;1101 1168 11A9;AF12;1101 1168 11A9; # (꼒; 꼒; 꼒; 꼒; 꼒; ) HANGUL SYLLABLE GGYEGG
+AF13;AF13;1101 1168 11AA;AF13;1101 1168 11AA; # (꼓; 꼓; 꼓; 꼓; 꼓; ) HANGUL SYLLABLE GGYEGS
+AF14;AF14;1101 1168 11AB;AF14;1101 1168 11AB; # (꼔; 꼔; 꼔; 꼔; 꼔; ) HANGUL SYLLABLE GGYEN
+AF15;AF15;1101 1168 11AC;AF15;1101 1168 11AC; # (꼕; 꼕; 꼕; 꼕; 꼕; ) HANGUL SYLLABLE GGYENJ
+AF16;AF16;1101 1168 11AD;AF16;1101 1168 11AD; # (꼖; 꼖; 꼖; 꼖; 꼖; ) HANGUL SYLLABLE GGYENH
+AF17;AF17;1101 1168 11AE;AF17;1101 1168 11AE; # (꼗; 꼗; 꼗; 꼗; 꼗; ) HANGUL SYLLABLE GGYED
+AF18;AF18;1101 1168 11AF;AF18;1101 1168 11AF; # (꼘; 꼘; 꼘; 꼘; 꼘; ) HANGUL SYLLABLE GGYEL
+AF19;AF19;1101 1168 11B0;AF19;1101 1168 11B0; # (꼙; 꼙; 꼙; 꼙; 꼙; ) HANGUL SYLLABLE GGYELG
+AF1A;AF1A;1101 1168 11B1;AF1A;1101 1168 11B1; # (꼚; 꼚; 꼚; 꼚; 꼚; ) HANGUL SYLLABLE GGYELM
+AF1B;AF1B;1101 1168 11B2;AF1B;1101 1168 11B2; # (꼛; 꼛; 꼛; 꼛; 꼛; ) HANGUL SYLLABLE GGYELB
+AF1C;AF1C;1101 1168 11B3;AF1C;1101 1168 11B3; # (꼜; 꼜; 꼜; 꼜; 꼜; ) HANGUL SYLLABLE GGYELS
+AF1D;AF1D;1101 1168 11B4;AF1D;1101 1168 11B4; # (꼝; 꼝; 꼝; 꼝; 꼝; ) HANGUL SYLLABLE GGYELT
+AF1E;AF1E;1101 1168 11B5;AF1E;1101 1168 11B5; # (꼞; 꼞; 꼞; 꼞; 꼞; ) HANGUL SYLLABLE GGYELP
+AF1F;AF1F;1101 1168 11B6;AF1F;1101 1168 11B6; # (꼟; 꼟; 꼟; 꼟; 꼟; ) HANGUL SYLLABLE GGYELH
+AF20;AF20;1101 1168 11B7;AF20;1101 1168 11B7; # (꼠; 꼠; 꼠; 꼠; 꼠; ) HANGUL SYLLABLE GGYEM
+AF21;AF21;1101 1168 11B8;AF21;1101 1168 11B8; # (꼡; 꼡; 꼡; 꼡; 꼡; ) HANGUL SYLLABLE GGYEB
+AF22;AF22;1101 1168 11B9;AF22;1101 1168 11B9; # (꼢; 꼢; 꼢; 꼢; 꼢; ) HANGUL SYLLABLE GGYEBS
+AF23;AF23;1101 1168 11BA;AF23;1101 1168 11BA; # (꼣; 꼣; 꼣; 꼣; 꼣; ) HANGUL SYLLABLE GGYES
+AF24;AF24;1101 1168 11BB;AF24;1101 1168 11BB; # (꼤; 꼤; 꼤; 꼤; 꼤; ) HANGUL SYLLABLE GGYESS
+AF25;AF25;1101 1168 11BC;AF25;1101 1168 11BC; # (꼥; 꼥; 꼥; 꼥; 꼥; ) HANGUL SYLLABLE GGYENG
+AF26;AF26;1101 1168 11BD;AF26;1101 1168 11BD; # (꼦; 꼦; 꼦; 꼦; 꼦; ) HANGUL SYLLABLE GGYEJ
+AF27;AF27;1101 1168 11BE;AF27;1101 1168 11BE; # (꼧; 꼧; 꼧; 꼧; 꼧; ) HANGUL SYLLABLE GGYEC
+AF28;AF28;1101 1168 11BF;AF28;1101 1168 11BF; # (꼨; 꼨; 꼨; 꼨; 꼨; ) HANGUL SYLLABLE GGYEK
+AF29;AF29;1101 1168 11C0;AF29;1101 1168 11C0; # (꼩; 꼩; 꼩; 꼩; 꼩; ) HANGUL SYLLABLE GGYET
+AF2A;AF2A;1101 1168 11C1;AF2A;1101 1168 11C1; # (꼪; 꼪; 꼪; 꼪; 꼪; ) HANGUL SYLLABLE GGYEP
+AF2B;AF2B;1101 1168 11C2;AF2B;1101 1168 11C2; # (꼫; 꼫; 꼫; 꼫; 꼫; ) HANGUL SYLLABLE GGYEH
+AF2C;AF2C;1101 1169;AF2C;1101 1169; # (꼬; 꼬; 꼬; 꼬; 꼬; ) HANGUL SYLLABLE GGO
+AF2D;AF2D;1101 1169 11A8;AF2D;1101 1169 11A8; # (꼭; 꼭; 꼭; 꼭; 꼭; ) HANGUL SYLLABLE GGOG
+AF2E;AF2E;1101 1169 11A9;AF2E;1101 1169 11A9; # (꼮; 꼮; 꼮; 꼮; 꼮; ) HANGUL SYLLABLE GGOGG
+AF2F;AF2F;1101 1169 11AA;AF2F;1101 1169 11AA; # (꼯; 꼯; 꼯; 꼯; 꼯; ) HANGUL SYLLABLE GGOGS
+AF30;AF30;1101 1169 11AB;AF30;1101 1169 11AB; # (꼰; 꼰; 꼰; 꼰; 꼰; ) HANGUL SYLLABLE GGON
+AF31;AF31;1101 1169 11AC;AF31;1101 1169 11AC; # (꼱; 꼱; 꼱; 꼱; 꼱; ) HANGUL SYLLABLE GGONJ
+AF32;AF32;1101 1169 11AD;AF32;1101 1169 11AD; # (꼲; 꼲; 꼲; 꼲; 꼲; ) HANGUL SYLLABLE GGONH
+AF33;AF33;1101 1169 11AE;AF33;1101 1169 11AE; # (꼳; 꼳; 꼳; 꼳; 꼳; ) HANGUL SYLLABLE GGOD
+AF34;AF34;1101 1169 11AF;AF34;1101 1169 11AF; # (꼴; 꼴; 꼴; 꼴; 꼴; ) HANGUL SYLLABLE GGOL
+AF35;AF35;1101 1169 11B0;AF35;1101 1169 11B0; # (꼵; 꼵; 꼵; 꼵; 꼵; ) HANGUL SYLLABLE GGOLG
+AF36;AF36;1101 1169 11B1;AF36;1101 1169 11B1; # (꼶; 꼶; 꼶; 꼶; 꼶; ) HANGUL SYLLABLE GGOLM
+AF37;AF37;1101 1169 11B2;AF37;1101 1169 11B2; # (꼷; 꼷; 꼷; 꼷; 꼷; ) HANGUL SYLLABLE GGOLB
+AF38;AF38;1101 1169 11B3;AF38;1101 1169 11B3; # (꼸; 꼸; 꼸; 꼸; 꼸; ) HANGUL SYLLABLE GGOLS
+AF39;AF39;1101 1169 11B4;AF39;1101 1169 11B4; # (꼹; 꼹; 꼹; 꼹; 꼹; ) HANGUL SYLLABLE GGOLT
+AF3A;AF3A;1101 1169 11B5;AF3A;1101 1169 11B5; # (꼺; 꼺; 꼺; 꼺; 꼺; ) HANGUL SYLLABLE GGOLP
+AF3B;AF3B;1101 1169 11B6;AF3B;1101 1169 11B6; # (꼻; 꼻; 꼻; 꼻; 꼻; ) HANGUL SYLLABLE GGOLH
+AF3C;AF3C;1101 1169 11B7;AF3C;1101 1169 11B7; # (꼼; 꼼; 꼼; 꼼; 꼼; ) HANGUL SYLLABLE GGOM
+AF3D;AF3D;1101 1169 11B8;AF3D;1101 1169 11B8; # (꼽; 꼽; 꼽; 꼽; 꼽; ) HANGUL SYLLABLE GGOB
+AF3E;AF3E;1101 1169 11B9;AF3E;1101 1169 11B9; # (꼾; 꼾; 꼾; 꼾; 꼾; ) HANGUL SYLLABLE GGOBS
+AF3F;AF3F;1101 1169 11BA;AF3F;1101 1169 11BA; # (꼿; 꼿; 꼿; 꼿; 꼿; ) HANGUL SYLLABLE GGOS
+AF40;AF40;1101 1169 11BB;AF40;1101 1169 11BB; # (꽀; 꽀; 꽀; 꽀; 꽀; ) HANGUL SYLLABLE GGOSS
+AF41;AF41;1101 1169 11BC;AF41;1101 1169 11BC; # (꽁; 꽁; 꽁; 꽁; 꽁; ) HANGUL SYLLABLE GGONG
+AF42;AF42;1101 1169 11BD;AF42;1101 1169 11BD; # (꽂; 꽂; 꽂; 꽂; 꽂; ) HANGUL SYLLABLE GGOJ
+AF43;AF43;1101 1169 11BE;AF43;1101 1169 11BE; # (꽃; 꽃; 꽃; 꽃; 꽃; ) HANGUL SYLLABLE GGOC
+AF44;AF44;1101 1169 11BF;AF44;1101 1169 11BF; # (꽄; 꽄; 꽄; 꽄; 꽄; ) HANGUL SYLLABLE GGOK
+AF45;AF45;1101 1169 11C0;AF45;1101 1169 11C0; # (꽅; 꽅; 꽅; 꽅; 꽅; ) HANGUL SYLLABLE GGOT
+AF46;AF46;1101 1169 11C1;AF46;1101 1169 11C1; # (꽆; 꽆; 꽆; 꽆; 꽆; ) HANGUL SYLLABLE GGOP
+AF47;AF47;1101 1169 11C2;AF47;1101 1169 11C2; # (꽇; 꽇; 꽇; 꽇; 꽇; ) HANGUL SYLLABLE GGOH
+AF48;AF48;1101 116A;AF48;1101 116A; # (꽈; 꽈; 꽈; 꽈; 꽈; ) HANGUL SYLLABLE GGWA
+AF49;AF49;1101 116A 11A8;AF49;1101 116A 11A8; # (꽉; 꽉; 꽉; 꽉; 꽉; ) HANGUL SYLLABLE GGWAG
+AF4A;AF4A;1101 116A 11A9;AF4A;1101 116A 11A9; # (꽊; 꽊; 꽊; 꽊; 꽊; ) HANGUL SYLLABLE GGWAGG
+AF4B;AF4B;1101 116A 11AA;AF4B;1101 116A 11AA; # (꽋; 꽋; 꽋; 꽋; 꽋; ) HANGUL SYLLABLE GGWAGS
+AF4C;AF4C;1101 116A 11AB;AF4C;1101 116A 11AB; # (꽌; 꽌; 꽌; 꽌; 꽌; ) HANGUL SYLLABLE GGWAN
+AF4D;AF4D;1101 116A 11AC;AF4D;1101 116A 11AC; # (꽍; 꽍; 꽍; 꽍; 꽍; ) HANGUL SYLLABLE GGWANJ
+AF4E;AF4E;1101 116A 11AD;AF4E;1101 116A 11AD; # (꽎; 꽎; 꽎; 꽎; 꽎; ) HANGUL SYLLABLE GGWANH
+AF4F;AF4F;1101 116A 11AE;AF4F;1101 116A 11AE; # (꽏; 꽏; 꽏; 꽏; 꽏; ) HANGUL SYLLABLE GGWAD
+AF50;AF50;1101 116A 11AF;AF50;1101 116A 11AF; # (꽐; 꽐; 꽐; 꽐; 꽐; ) HANGUL SYLLABLE GGWAL
+AF51;AF51;1101 116A 11B0;AF51;1101 116A 11B0; # (꽑; 꽑; 꽑; 꽑; 꽑; ) HANGUL SYLLABLE GGWALG
+AF52;AF52;1101 116A 11B1;AF52;1101 116A 11B1; # (꽒; 꽒; 꽒; 꽒; 꽒; ) HANGUL SYLLABLE GGWALM
+AF53;AF53;1101 116A 11B2;AF53;1101 116A 11B2; # (꽓; 꽓; 꽓; 꽓; 꽓; ) HANGUL SYLLABLE GGWALB
+AF54;AF54;1101 116A 11B3;AF54;1101 116A 11B3; # (꽔; 꽔; 꽔; 꽔; 꽔; ) HANGUL SYLLABLE GGWALS
+AF55;AF55;1101 116A 11B4;AF55;1101 116A 11B4; # (꽕; 꽕; 꽕; 꽕; 꽕; ) HANGUL SYLLABLE GGWALT
+AF56;AF56;1101 116A 11B5;AF56;1101 116A 11B5; # (꽖; 꽖; 꽖; 꽖; 꽖; ) HANGUL SYLLABLE GGWALP
+AF57;AF57;1101 116A 11B6;AF57;1101 116A 11B6; # (꽗; 꽗; 꽗; 꽗; 꽗; ) HANGUL SYLLABLE GGWALH
+AF58;AF58;1101 116A 11B7;AF58;1101 116A 11B7; # (꽘; 꽘; 꽘; 꽘; 꽘; ) HANGUL SYLLABLE GGWAM
+AF59;AF59;1101 116A 11B8;AF59;1101 116A 11B8; # (꽙; 꽙; 꽙; 꽙; 꽙; ) HANGUL SYLLABLE GGWAB
+AF5A;AF5A;1101 116A 11B9;AF5A;1101 116A 11B9; # (꽚; 꽚; 꽚; 꽚; 꽚; ) HANGUL SYLLABLE GGWABS
+AF5B;AF5B;1101 116A 11BA;AF5B;1101 116A 11BA; # (꽛; 꽛; 꽛; 꽛; 꽛; ) HANGUL SYLLABLE GGWAS
+AF5C;AF5C;1101 116A 11BB;AF5C;1101 116A 11BB; # (꽜; 꽜; 꽜; 꽜; 꽜; ) HANGUL SYLLABLE GGWASS
+AF5D;AF5D;1101 116A 11BC;AF5D;1101 116A 11BC; # (꽝; 꽝; 꽝; 꽝; 꽝; ) HANGUL SYLLABLE GGWANG
+AF5E;AF5E;1101 116A 11BD;AF5E;1101 116A 11BD; # (꽞; 꽞; 꽞; 꽞; 꽞; ) HANGUL SYLLABLE GGWAJ
+AF5F;AF5F;1101 116A 11BE;AF5F;1101 116A 11BE; # (꽟; 꽟; 꽟; 꽟; 꽟; ) HANGUL SYLLABLE GGWAC
+AF60;AF60;1101 116A 11BF;AF60;1101 116A 11BF; # (꽠; 꽠; 꽠; 꽠; 꽠; ) HANGUL SYLLABLE GGWAK
+AF61;AF61;1101 116A 11C0;AF61;1101 116A 11C0; # (꽡; 꽡; 꽡; 꽡; 꽡; ) HANGUL SYLLABLE GGWAT
+AF62;AF62;1101 116A 11C1;AF62;1101 116A 11C1; # (꽢; 꽢; 꽢; 꽢; 꽢; ) HANGUL SYLLABLE GGWAP
+AF63;AF63;1101 116A 11C2;AF63;1101 116A 11C2; # (꽣; 꽣; 꽣; 꽣; 꽣; ) HANGUL SYLLABLE GGWAH
+AF64;AF64;1101 116B;AF64;1101 116B; # (꽤; 꽤; 꽤; 꽤; 꽤; ) HANGUL SYLLABLE GGWAE
+AF65;AF65;1101 116B 11A8;AF65;1101 116B 11A8; # (꽥; 꽥; 꽥; 꽥; 꽥; ) HANGUL SYLLABLE GGWAEG
+AF66;AF66;1101 116B 11A9;AF66;1101 116B 11A9; # (꽦; 꽦; 꽦; 꽦; 꽦; ) HANGUL SYLLABLE GGWAEGG
+AF67;AF67;1101 116B 11AA;AF67;1101 116B 11AA; # (꽧; 꽧; 꽧; 꽧; 꽧; ) HANGUL SYLLABLE GGWAEGS
+AF68;AF68;1101 116B 11AB;AF68;1101 116B 11AB; # (꽨; 꽨; 꽨; 꽨; 꽨; ) HANGUL SYLLABLE GGWAEN
+AF69;AF69;1101 116B 11AC;AF69;1101 116B 11AC; # (꽩; 꽩; 꽩; 꽩; 꽩; ) HANGUL SYLLABLE GGWAENJ
+AF6A;AF6A;1101 116B 11AD;AF6A;1101 116B 11AD; # (꽪; 꽪; 꽪; 꽪; 꽪; ) HANGUL SYLLABLE GGWAENH
+AF6B;AF6B;1101 116B 11AE;AF6B;1101 116B 11AE; # (꽫; 꽫; 꽫; 꽫; 꽫; ) HANGUL SYLLABLE GGWAED
+AF6C;AF6C;1101 116B 11AF;AF6C;1101 116B 11AF; # (꽬; 꽬; 꽬; 꽬; 꽬; ) HANGUL SYLLABLE GGWAEL
+AF6D;AF6D;1101 116B 11B0;AF6D;1101 116B 11B0; # (꽭; 꽭; 꽭; 꽭; 꽭; ) HANGUL SYLLABLE GGWAELG
+AF6E;AF6E;1101 116B 11B1;AF6E;1101 116B 11B1; # (꽮; 꽮; 꽮; 꽮; 꽮; ) HANGUL SYLLABLE GGWAELM
+AF6F;AF6F;1101 116B 11B2;AF6F;1101 116B 11B2; # (꽯; 꽯; 꽯; 꽯; 꽯; ) HANGUL SYLLABLE GGWAELB
+AF70;AF70;1101 116B 11B3;AF70;1101 116B 11B3; # (꽰; 꽰; 꽰; 꽰; 꽰; ) HANGUL SYLLABLE GGWAELS
+AF71;AF71;1101 116B 11B4;AF71;1101 116B 11B4; # (꽱; 꽱; 꽱; 꽱; 꽱; ) HANGUL SYLLABLE GGWAELT
+AF72;AF72;1101 116B 11B5;AF72;1101 116B 11B5; # (꽲; 꽲; 꽲; 꽲; 꽲; ) HANGUL SYLLABLE GGWAELP
+AF73;AF73;1101 116B 11B6;AF73;1101 116B 11B6; # (꽳; 꽳; 꽳; 꽳; 꽳; ) HANGUL SYLLABLE GGWAELH
+AF74;AF74;1101 116B 11B7;AF74;1101 116B 11B7; # (꽴; 꽴; 꽴; 꽴; 꽴; ) HANGUL SYLLABLE GGWAEM
+AF75;AF75;1101 116B 11B8;AF75;1101 116B 11B8; # (꽵; 꽵; 꽵; 꽵; 꽵; ) HANGUL SYLLABLE GGWAEB
+AF76;AF76;1101 116B 11B9;AF76;1101 116B 11B9; # (꽶; 꽶; 꽶; 꽶; 꽶; ) HANGUL SYLLABLE GGWAEBS
+AF77;AF77;1101 116B 11BA;AF77;1101 116B 11BA; # (꽷; 꽷; 꽷; 꽷; 꽷; ) HANGUL SYLLABLE GGWAES
+AF78;AF78;1101 116B 11BB;AF78;1101 116B 11BB; # (꽸; 꽸; 꽸; 꽸; 꽸; ) HANGUL SYLLABLE GGWAESS
+AF79;AF79;1101 116B 11BC;AF79;1101 116B 11BC; # (꽹; 꽹; 꽹; 꽹; 꽹; ) HANGUL SYLLABLE GGWAENG
+AF7A;AF7A;1101 116B 11BD;AF7A;1101 116B 11BD; # (꽺; 꽺; 꽺; 꽺; 꽺; ) HANGUL SYLLABLE GGWAEJ
+AF7B;AF7B;1101 116B 11BE;AF7B;1101 116B 11BE; # (꽻; 꽻; 꽻; 꽻; 꽻; ) HANGUL SYLLABLE GGWAEC
+AF7C;AF7C;1101 116B 11BF;AF7C;1101 116B 11BF; # (꽼; 꽼; 꽼; 꽼; 꽼; ) HANGUL SYLLABLE GGWAEK
+AF7D;AF7D;1101 116B 11C0;AF7D;1101 116B 11C0; # (꽽; 꽽; 꽽; 꽽; 꽽; ) HANGUL SYLLABLE GGWAET
+AF7E;AF7E;1101 116B 11C1;AF7E;1101 116B 11C1; # (꽾; 꽾; 꽾; 꽾; 꽾; ) HANGUL SYLLABLE GGWAEP
+AF7F;AF7F;1101 116B 11C2;AF7F;1101 116B 11C2; # (꽿; 꽿; 꽿; 꽿; 꽿; ) HANGUL SYLLABLE GGWAEH
+AF80;AF80;1101 116C;AF80;1101 116C; # (꾀; 꾀; 꾀; 꾀; 꾀; ) HANGUL SYLLABLE GGOE
+AF81;AF81;1101 116C 11A8;AF81;1101 116C 11A8; # (꾁; 꾁; 꾁; 꾁; 꾁; ) HANGUL SYLLABLE GGOEG
+AF82;AF82;1101 116C 11A9;AF82;1101 116C 11A9; # (꾂; 꾂; 꾂; 꾂; 꾂; ) HANGUL SYLLABLE GGOEGG
+AF83;AF83;1101 116C 11AA;AF83;1101 116C 11AA; # (꾃; 꾃; 꾃; 꾃; 꾃; ) HANGUL SYLLABLE GGOEGS
+AF84;AF84;1101 116C 11AB;AF84;1101 116C 11AB; # (꾄; 꾄; 꾄; 꾄; 꾄; ) HANGUL SYLLABLE GGOEN
+AF85;AF85;1101 116C 11AC;AF85;1101 116C 11AC; # (꾅; 꾅; 꾅; 꾅; 꾅; ) HANGUL SYLLABLE GGOENJ
+AF86;AF86;1101 116C 11AD;AF86;1101 116C 11AD; # (꾆; 꾆; 꾆; 꾆; 꾆; ) HANGUL SYLLABLE GGOENH
+AF87;AF87;1101 116C 11AE;AF87;1101 116C 11AE; # (꾇; 꾇; 꾇; 꾇; 꾇; ) HANGUL SYLLABLE GGOED
+AF88;AF88;1101 116C 11AF;AF88;1101 116C 11AF; # (꾈; 꾈; 꾈; 꾈; 꾈; ) HANGUL SYLLABLE GGOEL
+AF89;AF89;1101 116C 11B0;AF89;1101 116C 11B0; # (꾉; 꾉; 꾉; 꾉; 꾉; ) HANGUL SYLLABLE GGOELG
+AF8A;AF8A;1101 116C 11B1;AF8A;1101 116C 11B1; # (꾊; 꾊; 꾊; 꾊; 꾊; ) HANGUL SYLLABLE GGOELM
+AF8B;AF8B;1101 116C 11B2;AF8B;1101 116C 11B2; # (꾋; 꾋; 꾋; 꾋; 꾋; ) HANGUL SYLLABLE GGOELB
+AF8C;AF8C;1101 116C 11B3;AF8C;1101 116C 11B3; # (꾌; 꾌; 꾌; 꾌; 꾌; ) HANGUL SYLLABLE GGOELS
+AF8D;AF8D;1101 116C 11B4;AF8D;1101 116C 11B4; # (꾍; 꾍; 꾍; 꾍; 꾍; ) HANGUL SYLLABLE GGOELT
+AF8E;AF8E;1101 116C 11B5;AF8E;1101 116C 11B5; # (꾎; 꾎; 꾎; 꾎; 꾎; ) HANGUL SYLLABLE GGOELP
+AF8F;AF8F;1101 116C 11B6;AF8F;1101 116C 11B6; # (꾏; 꾏; 꾏; 꾏; 꾏; ) HANGUL SYLLABLE GGOELH
+AF90;AF90;1101 116C 11B7;AF90;1101 116C 11B7; # (꾐; 꾐; 꾐; 꾐; 꾐; ) HANGUL SYLLABLE GGOEM
+AF91;AF91;1101 116C 11B8;AF91;1101 116C 11B8; # (꾑; 꾑; 꾑; 꾑; 꾑; ) HANGUL SYLLABLE GGOEB
+AF92;AF92;1101 116C 11B9;AF92;1101 116C 11B9; # (꾒; 꾒; 꾒; 꾒; 꾒; ) HANGUL SYLLABLE GGOEBS
+AF93;AF93;1101 116C 11BA;AF93;1101 116C 11BA; # (꾓; 꾓; 꾓; 꾓; 꾓; ) HANGUL SYLLABLE GGOES
+AF94;AF94;1101 116C 11BB;AF94;1101 116C 11BB; # (꾔; 꾔; 꾔; 꾔; 꾔; ) HANGUL SYLLABLE GGOESS
+AF95;AF95;1101 116C 11BC;AF95;1101 116C 11BC; # (꾕; 꾕; 꾕; 꾕; 꾕; ) HANGUL SYLLABLE GGOENG
+AF96;AF96;1101 116C 11BD;AF96;1101 116C 11BD; # (꾖; 꾖; 꾖; 꾖; 꾖; ) HANGUL SYLLABLE GGOEJ
+AF97;AF97;1101 116C 11BE;AF97;1101 116C 11BE; # (꾗; 꾗; 꾗; 꾗; 꾗; ) HANGUL SYLLABLE GGOEC
+AF98;AF98;1101 116C 11BF;AF98;1101 116C 11BF; # (꾘; 꾘; 꾘; 꾘; 꾘; ) HANGUL SYLLABLE GGOEK
+AF99;AF99;1101 116C 11C0;AF99;1101 116C 11C0; # (꾙; 꾙; 꾙; 꾙; 꾙; ) HANGUL SYLLABLE GGOET
+AF9A;AF9A;1101 116C 11C1;AF9A;1101 116C 11C1; # (꾚; 꾚; 꾚; 꾚; 꾚; ) HANGUL SYLLABLE GGOEP
+AF9B;AF9B;1101 116C 11C2;AF9B;1101 116C 11C2; # (꾛; 꾛; 꾛; 꾛; 꾛; ) HANGUL SYLLABLE GGOEH
+AF9C;AF9C;1101 116D;AF9C;1101 116D; # (꾜; 꾜; 꾜; 꾜; 꾜; ) HANGUL SYLLABLE GGYO
+AF9D;AF9D;1101 116D 11A8;AF9D;1101 116D 11A8; # (꾝; 꾝; 꾝; 꾝; 꾝; ) HANGUL SYLLABLE GGYOG
+AF9E;AF9E;1101 116D 11A9;AF9E;1101 116D 11A9; # (꾞; 꾞; 꾞; 꾞; 꾞; ) HANGUL SYLLABLE GGYOGG
+AF9F;AF9F;1101 116D 11AA;AF9F;1101 116D 11AA; # (꾟; 꾟; 꾟; 꾟; 꾟; ) HANGUL SYLLABLE GGYOGS
+AFA0;AFA0;1101 116D 11AB;AFA0;1101 116D 11AB; # (꾠; 꾠; 꾠; 꾠; 꾠; ) HANGUL SYLLABLE GGYON
+AFA1;AFA1;1101 116D 11AC;AFA1;1101 116D 11AC; # (꾡; 꾡; 꾡; 꾡; 꾡; ) HANGUL SYLLABLE GGYONJ
+AFA2;AFA2;1101 116D 11AD;AFA2;1101 116D 11AD; # (꾢; 꾢; 꾢; 꾢; 꾢; ) HANGUL SYLLABLE GGYONH
+AFA3;AFA3;1101 116D 11AE;AFA3;1101 116D 11AE; # (꾣; 꾣; 꾣; 꾣; 꾣; ) HANGUL SYLLABLE GGYOD
+AFA4;AFA4;1101 116D 11AF;AFA4;1101 116D 11AF; # (꾤; 꾤; 꾤; 꾤; 꾤; ) HANGUL SYLLABLE GGYOL
+AFA5;AFA5;1101 116D 11B0;AFA5;1101 116D 11B0; # (꾥; 꾥; 꾥; 꾥; 꾥; ) HANGUL SYLLABLE GGYOLG
+AFA6;AFA6;1101 116D 11B1;AFA6;1101 116D 11B1; # (꾦; 꾦; 꾦; 꾦; 꾦; ) HANGUL SYLLABLE GGYOLM
+AFA7;AFA7;1101 116D 11B2;AFA7;1101 116D 11B2; # (꾧; 꾧; 꾧; 꾧; 꾧; ) HANGUL SYLLABLE GGYOLB
+AFA8;AFA8;1101 116D 11B3;AFA8;1101 116D 11B3; # (꾨; 꾨; 꾨; 꾨; 꾨; ) HANGUL SYLLABLE GGYOLS
+AFA9;AFA9;1101 116D 11B4;AFA9;1101 116D 11B4; # (꾩; 꾩; 꾩; 꾩; 꾩; ) HANGUL SYLLABLE GGYOLT
+AFAA;AFAA;1101 116D 11B5;AFAA;1101 116D 11B5; # (꾪; 꾪; 꾪; 꾪; 꾪; ) HANGUL SYLLABLE GGYOLP
+AFAB;AFAB;1101 116D 11B6;AFAB;1101 116D 11B6; # (꾫; 꾫; 꾫; 꾫; 꾫; ) HANGUL SYLLABLE GGYOLH
+AFAC;AFAC;1101 116D 11B7;AFAC;1101 116D 11B7; # (꾬; 꾬; 꾬; 꾬; 꾬; ) HANGUL SYLLABLE GGYOM
+AFAD;AFAD;1101 116D 11B8;AFAD;1101 116D 11B8; # (꾭; 꾭; 꾭; 꾭; 꾭; ) HANGUL SYLLABLE GGYOB
+AFAE;AFAE;1101 116D 11B9;AFAE;1101 116D 11B9; # (꾮; 꾮; 꾮; 꾮; 꾮; ) HANGUL SYLLABLE GGYOBS
+AFAF;AFAF;1101 116D 11BA;AFAF;1101 116D 11BA; # (꾯; 꾯; 꾯; 꾯; 꾯; ) HANGUL SYLLABLE GGYOS
+AFB0;AFB0;1101 116D 11BB;AFB0;1101 116D 11BB; # (꾰; 꾰; 꾰; 꾰; 꾰; ) HANGUL SYLLABLE GGYOSS
+AFB1;AFB1;1101 116D 11BC;AFB1;1101 116D 11BC; # (꾱; 꾱; 꾱; 꾱; 꾱; ) HANGUL SYLLABLE GGYONG
+AFB2;AFB2;1101 116D 11BD;AFB2;1101 116D 11BD; # (꾲; 꾲; 꾲; 꾲; 꾲; ) HANGUL SYLLABLE GGYOJ
+AFB3;AFB3;1101 116D 11BE;AFB3;1101 116D 11BE; # (꾳; 꾳; 꾳; 꾳; 꾳; ) HANGUL SYLLABLE GGYOC
+AFB4;AFB4;1101 116D 11BF;AFB4;1101 116D 11BF; # (꾴; 꾴; 꾴; 꾴; 꾴; ) HANGUL SYLLABLE GGYOK
+AFB5;AFB5;1101 116D 11C0;AFB5;1101 116D 11C0; # (꾵; 꾵; 꾵; 꾵; 꾵; ) HANGUL SYLLABLE GGYOT
+AFB6;AFB6;1101 116D 11C1;AFB6;1101 116D 11C1; # (꾶; 꾶; 꾶; 꾶; 꾶; ) HANGUL SYLLABLE GGYOP
+AFB7;AFB7;1101 116D 11C2;AFB7;1101 116D 11C2; # (꾷; 꾷; 꾷; 꾷; 꾷; ) HANGUL SYLLABLE GGYOH
+AFB8;AFB8;1101 116E;AFB8;1101 116E; # (꾸; 꾸; 꾸; 꾸; 꾸; ) HANGUL SYLLABLE GGU
+AFB9;AFB9;1101 116E 11A8;AFB9;1101 116E 11A8; # (꾹; 꾹; 꾹; 꾹; 꾹; ) HANGUL SYLLABLE GGUG
+AFBA;AFBA;1101 116E 11A9;AFBA;1101 116E 11A9; # (꾺; 꾺; 꾺; 꾺; 꾺; ) HANGUL SYLLABLE GGUGG
+AFBB;AFBB;1101 116E 11AA;AFBB;1101 116E 11AA; # (꾻; 꾻; 꾻; 꾻; 꾻; ) HANGUL SYLLABLE GGUGS
+AFBC;AFBC;1101 116E 11AB;AFBC;1101 116E 11AB; # (꾼; 꾼; 꾼; 꾼; 꾼; ) HANGUL SYLLABLE GGUN
+AFBD;AFBD;1101 116E 11AC;AFBD;1101 116E 11AC; # (꾽; 꾽; 꾽; 꾽; 꾽; ) HANGUL SYLLABLE GGUNJ
+AFBE;AFBE;1101 116E 11AD;AFBE;1101 116E 11AD; # (꾾; 꾾; 꾾; 꾾; 꾾; ) HANGUL SYLLABLE GGUNH
+AFBF;AFBF;1101 116E 11AE;AFBF;1101 116E 11AE; # (꾿; 꾿; 꾿; 꾿; 꾿; ) HANGUL SYLLABLE GGUD
+AFC0;AFC0;1101 116E 11AF;AFC0;1101 116E 11AF; # (꿀; 꿀; 꿀; 꿀; 꿀; ) HANGUL SYLLABLE GGUL
+AFC1;AFC1;1101 116E 11B0;AFC1;1101 116E 11B0; # (꿁; 꿁; 꿁; 꿁; 꿁; ) HANGUL SYLLABLE GGULG
+AFC2;AFC2;1101 116E 11B1;AFC2;1101 116E 11B1; # (꿂; 꿂; 꿂; 꿂; 꿂; ) HANGUL SYLLABLE GGULM
+AFC3;AFC3;1101 116E 11B2;AFC3;1101 116E 11B2; # (꿃; 꿃; 꿃; 꿃; 꿃; ) HANGUL SYLLABLE GGULB
+AFC4;AFC4;1101 116E 11B3;AFC4;1101 116E 11B3; # (꿄; 꿄; 꿄; 꿄; 꿄; ) HANGUL SYLLABLE GGULS
+AFC5;AFC5;1101 116E 11B4;AFC5;1101 116E 11B4; # (꿅; 꿅; 꿅; 꿅; 꿅; ) HANGUL SYLLABLE GGULT
+AFC6;AFC6;1101 116E 11B5;AFC6;1101 116E 11B5; # (꿆; 꿆; 꿆; 꿆; 꿆; ) HANGUL SYLLABLE GGULP
+AFC7;AFC7;1101 116E 11B6;AFC7;1101 116E 11B6; # (꿇; 꿇; 꿇; 꿇; 꿇; ) HANGUL SYLLABLE GGULH
+AFC8;AFC8;1101 116E 11B7;AFC8;1101 116E 11B7; # (꿈; 꿈; 꿈; 꿈; 꿈; ) HANGUL SYLLABLE GGUM
+AFC9;AFC9;1101 116E 11B8;AFC9;1101 116E 11B8; # (꿉; 꿉; 꿉; 꿉; 꿉; ) HANGUL SYLLABLE GGUB
+AFCA;AFCA;1101 116E 11B9;AFCA;1101 116E 11B9; # (꿊; 꿊; 꿊; 꿊; 꿊; ) HANGUL SYLLABLE GGUBS
+AFCB;AFCB;1101 116E 11BA;AFCB;1101 116E 11BA; # (꿋; 꿋; 꿋; 꿋; 꿋; ) HANGUL SYLLABLE GGUS
+AFCC;AFCC;1101 116E 11BB;AFCC;1101 116E 11BB; # (꿌; 꿌; 꿌; 꿌; 꿌; ) HANGUL SYLLABLE GGUSS
+AFCD;AFCD;1101 116E 11BC;AFCD;1101 116E 11BC; # (꿍; 꿍; 꿍; 꿍; 꿍; ) HANGUL SYLLABLE GGUNG
+AFCE;AFCE;1101 116E 11BD;AFCE;1101 116E 11BD; # (꿎; 꿎; 꿎; 꿎; 꿎; ) HANGUL SYLLABLE GGUJ
+AFCF;AFCF;1101 116E 11BE;AFCF;1101 116E 11BE; # (꿏; 꿏; 꿏; 꿏; 꿏; ) HANGUL SYLLABLE GGUC
+AFD0;AFD0;1101 116E 11BF;AFD0;1101 116E 11BF; # (꿐; 꿐; 꿐; 꿐; 꿐; ) HANGUL SYLLABLE GGUK
+AFD1;AFD1;1101 116E 11C0;AFD1;1101 116E 11C0; # (꿑; 꿑; 꿑; 꿑; 꿑; ) HANGUL SYLLABLE GGUT
+AFD2;AFD2;1101 116E 11C1;AFD2;1101 116E 11C1; # (꿒; 꿒; 꿒; 꿒; 꿒; ) HANGUL SYLLABLE GGUP
+AFD3;AFD3;1101 116E 11C2;AFD3;1101 116E 11C2; # (꿓; 꿓; 꿓; 꿓; 꿓; ) HANGUL SYLLABLE GGUH
+AFD4;AFD4;1101 116F;AFD4;1101 116F; # (꿔; 꿔; 꿔; 꿔; 꿔; ) HANGUL SYLLABLE GGWEO
+AFD5;AFD5;1101 116F 11A8;AFD5;1101 116F 11A8; # (꿕; 꿕; 꿕; 꿕; 꿕; ) HANGUL SYLLABLE GGWEOG
+AFD6;AFD6;1101 116F 11A9;AFD6;1101 116F 11A9; # (꿖; 꿖; 꿖; 꿖; 꿖; ) HANGUL SYLLABLE GGWEOGG
+AFD7;AFD7;1101 116F 11AA;AFD7;1101 116F 11AA; # (꿗; 꿗; 꿗; 꿗; 꿗; ) HANGUL SYLLABLE GGWEOGS
+AFD8;AFD8;1101 116F 11AB;AFD8;1101 116F 11AB; # (꿘; 꿘; 꿘; 꿘; 꿘; ) HANGUL SYLLABLE GGWEON
+AFD9;AFD9;1101 116F 11AC;AFD9;1101 116F 11AC; # (꿙; 꿙; 꿙; 꿙; 꿙; ) HANGUL SYLLABLE GGWEONJ
+AFDA;AFDA;1101 116F 11AD;AFDA;1101 116F 11AD; # (꿚; 꿚; 꿚; 꿚; 꿚; ) HANGUL SYLLABLE GGWEONH
+AFDB;AFDB;1101 116F 11AE;AFDB;1101 116F 11AE; # (꿛; 꿛; 꿛; 꿛; 꿛; ) HANGUL SYLLABLE GGWEOD
+AFDC;AFDC;1101 116F 11AF;AFDC;1101 116F 11AF; # (꿜; 꿜; 꿜; 꿜; 꿜; ) HANGUL SYLLABLE GGWEOL
+AFDD;AFDD;1101 116F 11B0;AFDD;1101 116F 11B0; # (꿝; 꿝; 꿝; 꿝; 꿝; ) HANGUL SYLLABLE GGWEOLG
+AFDE;AFDE;1101 116F 11B1;AFDE;1101 116F 11B1; # (꿞; 꿞; 꿞; 꿞; 꿞; ) HANGUL SYLLABLE GGWEOLM
+AFDF;AFDF;1101 116F 11B2;AFDF;1101 116F 11B2; # (꿟; 꿟; 꿟; 꿟; 꿟; ) HANGUL SYLLABLE GGWEOLB
+AFE0;AFE0;1101 116F 11B3;AFE0;1101 116F 11B3; # (꿠; 꿠; 꿠; 꿠; 꿠; ) HANGUL SYLLABLE GGWEOLS
+AFE1;AFE1;1101 116F 11B4;AFE1;1101 116F 11B4; # (꿡; 꿡; 꿡; 꿡; 꿡; ) HANGUL SYLLABLE GGWEOLT
+AFE2;AFE2;1101 116F 11B5;AFE2;1101 116F 11B5; # (꿢; 꿢; 꿢; 꿢; 꿢; ) HANGUL SYLLABLE GGWEOLP
+AFE3;AFE3;1101 116F 11B6;AFE3;1101 116F 11B6; # (꿣; 꿣; 꿣; 꿣; 꿣; ) HANGUL SYLLABLE GGWEOLH
+AFE4;AFE4;1101 116F 11B7;AFE4;1101 116F 11B7; # (꿤; 꿤; 꿤; 꿤; 꿤; ) HANGUL SYLLABLE GGWEOM
+AFE5;AFE5;1101 116F 11B8;AFE5;1101 116F 11B8; # (꿥; 꿥; 꿥; 꿥; 꿥; ) HANGUL SYLLABLE GGWEOB
+AFE6;AFE6;1101 116F 11B9;AFE6;1101 116F 11B9; # (꿦; 꿦; 꿦; 꿦; 꿦; ) HANGUL SYLLABLE GGWEOBS
+AFE7;AFE7;1101 116F 11BA;AFE7;1101 116F 11BA; # (꿧; 꿧; 꿧; 꿧; 꿧; ) HANGUL SYLLABLE GGWEOS
+AFE8;AFE8;1101 116F 11BB;AFE8;1101 116F 11BB; # (꿨; 꿨; 꿨; 꿨; 꿨; ) HANGUL SYLLABLE GGWEOSS
+AFE9;AFE9;1101 116F 11BC;AFE9;1101 116F 11BC; # (꿩; 꿩; 꿩; 꿩; 꿩; ) HANGUL SYLLABLE GGWEONG
+AFEA;AFEA;1101 116F 11BD;AFEA;1101 116F 11BD; # (꿪; 꿪; 꿪; 꿪; 꿪; ) HANGUL SYLLABLE GGWEOJ
+AFEB;AFEB;1101 116F 11BE;AFEB;1101 116F 11BE; # (꿫; 꿫; 꿫; 꿫; 꿫; ) HANGUL SYLLABLE GGWEOC
+AFEC;AFEC;1101 116F 11BF;AFEC;1101 116F 11BF; # (꿬; 꿬; 꿬; 꿬; 꿬; ) HANGUL SYLLABLE GGWEOK
+AFED;AFED;1101 116F 11C0;AFED;1101 116F 11C0; # (꿭; 꿭; 꿭; 꿭; 꿭; ) HANGUL SYLLABLE GGWEOT
+AFEE;AFEE;1101 116F 11C1;AFEE;1101 116F 11C1; # (꿮; 꿮; 꿮; 꿮; 꿮; ) HANGUL SYLLABLE GGWEOP
+AFEF;AFEF;1101 116F 11C2;AFEF;1101 116F 11C2; # (꿯; 꿯; 꿯; 꿯; 꿯; ) HANGUL SYLLABLE GGWEOH
+AFF0;AFF0;1101 1170;AFF0;1101 1170; # (꿰; 꿰; 꿰; 꿰; 꿰; ) HANGUL SYLLABLE GGWE
+AFF1;AFF1;1101 1170 11A8;AFF1;1101 1170 11A8; # (꿱; 꿱; 꿱; 꿱; 꿱; ) HANGUL SYLLABLE GGWEG
+AFF2;AFF2;1101 1170 11A9;AFF2;1101 1170 11A9; # (꿲; 꿲; 꿲; 꿲; 꿲; ) HANGUL SYLLABLE GGWEGG
+AFF3;AFF3;1101 1170 11AA;AFF3;1101 1170 11AA; # (꿳; 꿳; 꿳; 꿳; 꿳; ) HANGUL SYLLABLE GGWEGS
+AFF4;AFF4;1101 1170 11AB;AFF4;1101 1170 11AB; # (꿴; 꿴; 꿴; 꿴; 꿴; ) HANGUL SYLLABLE GGWEN
+AFF5;AFF5;1101 1170 11AC;AFF5;1101 1170 11AC; # (꿵; 꿵; 꿵; 꿵; 꿵; ) HANGUL SYLLABLE GGWENJ
+AFF6;AFF6;1101 1170 11AD;AFF6;1101 1170 11AD; # (꿶; 꿶; 꿶; 꿶; 꿶; ) HANGUL SYLLABLE GGWENH
+AFF7;AFF7;1101 1170 11AE;AFF7;1101 1170 11AE; # (꿷; 꿷; 꿷; 꿷; 꿷; ) HANGUL SYLLABLE GGWED
+AFF8;AFF8;1101 1170 11AF;AFF8;1101 1170 11AF; # (꿸; 꿸; 꿸; 꿸; 꿸; ) HANGUL SYLLABLE GGWEL
+AFF9;AFF9;1101 1170 11B0;AFF9;1101 1170 11B0; # (꿹; 꿹; 꿹; 꿹; 꿹; ) HANGUL SYLLABLE GGWELG
+AFFA;AFFA;1101 1170 11B1;AFFA;1101 1170 11B1; # (꿺; 꿺; 꿺; 꿺; 꿺; ) HANGUL SYLLABLE GGWELM
+AFFB;AFFB;1101 1170 11B2;AFFB;1101 1170 11B2; # (꿻; 꿻; 꿻; 꿻; 꿻; ) HANGUL SYLLABLE GGWELB
+AFFC;AFFC;1101 1170 11B3;AFFC;1101 1170 11B3; # (꿼; 꿼; 꿼; 꿼; 꿼; ) HANGUL SYLLABLE GGWELS
+AFFD;AFFD;1101 1170 11B4;AFFD;1101 1170 11B4; # (꿽; 꿽; 꿽; 꿽; 꿽; ) HANGUL SYLLABLE GGWELT
+AFFE;AFFE;1101 1170 11B5;AFFE;1101 1170 11B5; # (꿾; 꿾; 꿾; 꿾; 꿾; ) HANGUL SYLLABLE GGWELP
+AFFF;AFFF;1101 1170 11B6;AFFF;1101 1170 11B6; # (꿿; 꿿; 꿿; 꿿; 꿿; ) HANGUL SYLLABLE GGWELH
+B000;B000;1101 1170 11B7;B000;1101 1170 11B7; # (뀀; 뀀; 뀀; 뀀; 뀀; ) HANGUL SYLLABLE GGWEM
+B001;B001;1101 1170 11B8;B001;1101 1170 11B8; # (뀁; 뀁; 뀁; 뀁; 뀁; ) HANGUL SYLLABLE GGWEB
+B002;B002;1101 1170 11B9;B002;1101 1170 11B9; # (뀂; 뀂; 뀂; 뀂; 뀂; ) HANGUL SYLLABLE GGWEBS
+B003;B003;1101 1170 11BA;B003;1101 1170 11BA; # (뀃; 뀃; 뀃; 뀃; 뀃; ) HANGUL SYLLABLE GGWES
+B004;B004;1101 1170 11BB;B004;1101 1170 11BB; # (뀄; 뀄; 뀄; 뀄; 뀄; ) HANGUL SYLLABLE GGWESS
+B005;B005;1101 1170 11BC;B005;1101 1170 11BC; # (뀅; 뀅; 뀅; 뀅; 뀅; ) HANGUL SYLLABLE GGWENG
+B006;B006;1101 1170 11BD;B006;1101 1170 11BD; # (뀆; 뀆; 뀆; 뀆; 뀆; ) HANGUL SYLLABLE GGWEJ
+B007;B007;1101 1170 11BE;B007;1101 1170 11BE; # (뀇; 뀇; 뀇; 뀇; 뀇; ) HANGUL SYLLABLE GGWEC
+B008;B008;1101 1170 11BF;B008;1101 1170 11BF; # (뀈; 뀈; 뀈; 뀈; 뀈; ) HANGUL SYLLABLE GGWEK
+B009;B009;1101 1170 11C0;B009;1101 1170 11C0; # (뀉; 뀉; 뀉; 뀉; 뀉; ) HANGUL SYLLABLE GGWET
+B00A;B00A;1101 1170 11C1;B00A;1101 1170 11C1; # (뀊; 뀊; 뀊; 뀊; 뀊; ) HANGUL SYLLABLE GGWEP
+B00B;B00B;1101 1170 11C2;B00B;1101 1170 11C2; # (뀋; 뀋; 뀋; 뀋; 뀋; ) HANGUL SYLLABLE GGWEH
+B00C;B00C;1101 1171;B00C;1101 1171; # (뀌; 뀌; 뀌; 뀌; 뀌; ) HANGUL SYLLABLE GGWI
+B00D;B00D;1101 1171 11A8;B00D;1101 1171 11A8; # (뀍; 뀍; 뀍; 뀍; 뀍; ) HANGUL SYLLABLE GGWIG
+B00E;B00E;1101 1171 11A9;B00E;1101 1171 11A9; # (뀎; 뀎; 뀎; 뀎; 뀎; ) HANGUL SYLLABLE GGWIGG
+B00F;B00F;1101 1171 11AA;B00F;1101 1171 11AA; # (뀏; 뀏; 뀏; 뀏; 뀏; ) HANGUL SYLLABLE GGWIGS
+B010;B010;1101 1171 11AB;B010;1101 1171 11AB; # (뀐; 뀐; 뀐; 뀐; 뀐; ) HANGUL SYLLABLE GGWIN
+B011;B011;1101 1171 11AC;B011;1101 1171 11AC; # (뀑; 뀑; 뀑; 뀑; 뀑; ) HANGUL SYLLABLE GGWINJ
+B012;B012;1101 1171 11AD;B012;1101 1171 11AD; # (뀒; 뀒; 뀒; 뀒; 뀒; ) HANGUL SYLLABLE GGWINH
+B013;B013;1101 1171 11AE;B013;1101 1171 11AE; # (뀓; 뀓; 뀓; 뀓; 뀓; ) HANGUL SYLLABLE GGWID
+B014;B014;1101 1171 11AF;B014;1101 1171 11AF; # (뀔; 뀔; 뀔; 뀔; 뀔; ) HANGUL SYLLABLE GGWIL
+B015;B015;1101 1171 11B0;B015;1101 1171 11B0; # (뀕; 뀕; 뀕; 뀕; 뀕; ) HANGUL SYLLABLE GGWILG
+B016;B016;1101 1171 11B1;B016;1101 1171 11B1; # (뀖; 뀖; 뀖; 뀖; 뀖; ) HANGUL SYLLABLE GGWILM
+B017;B017;1101 1171 11B2;B017;1101 1171 11B2; # (뀗; 뀗; 뀗; 뀗; 뀗; ) HANGUL SYLLABLE GGWILB
+B018;B018;1101 1171 11B3;B018;1101 1171 11B3; # (뀘; 뀘; 뀘; 뀘; 뀘; ) HANGUL SYLLABLE GGWILS
+B019;B019;1101 1171 11B4;B019;1101 1171 11B4; # (뀙; 뀙; 뀙; 뀙; 뀙; ) HANGUL SYLLABLE GGWILT
+B01A;B01A;1101 1171 11B5;B01A;1101 1171 11B5; # (뀚; 뀚; 뀚; 뀚; 뀚; ) HANGUL SYLLABLE GGWILP
+B01B;B01B;1101 1171 11B6;B01B;1101 1171 11B6; # (뀛; 뀛; 뀛; 뀛; 뀛; ) HANGUL SYLLABLE GGWILH
+B01C;B01C;1101 1171 11B7;B01C;1101 1171 11B7; # (뀜; 뀜; 뀜; 뀜; 뀜; ) HANGUL SYLLABLE GGWIM
+B01D;B01D;1101 1171 11B8;B01D;1101 1171 11B8; # (뀝; 뀝; 뀝; 뀝; 뀝; ) HANGUL SYLLABLE GGWIB
+B01E;B01E;1101 1171 11B9;B01E;1101 1171 11B9; # (뀞; 뀞; 뀞; 뀞; 뀞; ) HANGUL SYLLABLE GGWIBS
+B01F;B01F;1101 1171 11BA;B01F;1101 1171 11BA; # (뀟; 뀟; 뀟; 뀟; 뀟; ) HANGUL SYLLABLE GGWIS
+B020;B020;1101 1171 11BB;B020;1101 1171 11BB; # (뀠; 뀠; 뀠; 뀠; 뀠; ) HANGUL SYLLABLE GGWISS
+B021;B021;1101 1171 11BC;B021;1101 1171 11BC; # (뀡; 뀡; 뀡; 뀡; 뀡; ) HANGUL SYLLABLE GGWING
+B022;B022;1101 1171 11BD;B022;1101 1171 11BD; # (뀢; 뀢; 뀢; 뀢; 뀢; ) HANGUL SYLLABLE GGWIJ
+B023;B023;1101 1171 11BE;B023;1101 1171 11BE; # (뀣; 뀣; 뀣; 뀣; 뀣; ) HANGUL SYLLABLE GGWIC
+B024;B024;1101 1171 11BF;B024;1101 1171 11BF; # (뀤; 뀤; 뀤; 뀤; 뀤; ) HANGUL SYLLABLE GGWIK
+B025;B025;1101 1171 11C0;B025;1101 1171 11C0; # (뀥; 뀥; 뀥; 뀥; 뀥; ) HANGUL SYLLABLE GGWIT
+B026;B026;1101 1171 11C1;B026;1101 1171 11C1; # (뀦; 뀦; 뀦; 뀦; 뀦; ) HANGUL SYLLABLE GGWIP
+B027;B027;1101 1171 11C2;B027;1101 1171 11C2; # (뀧; 뀧; 뀧; 뀧; 뀧; ) HANGUL SYLLABLE GGWIH
+B028;B028;1101 1172;B028;1101 1172; # (뀨; 뀨; 뀨; 뀨; 뀨; ) HANGUL SYLLABLE GGYU
+B029;B029;1101 1172 11A8;B029;1101 1172 11A8; # (뀩; 뀩; 뀩; 뀩; 뀩; ) HANGUL SYLLABLE GGYUG
+B02A;B02A;1101 1172 11A9;B02A;1101 1172 11A9; # (뀪; 뀪; 뀪; 뀪; 뀪; ) HANGUL SYLLABLE GGYUGG
+B02B;B02B;1101 1172 11AA;B02B;1101 1172 11AA; # (뀫; 뀫; 뀫; 뀫; 뀫; ) HANGUL SYLLABLE GGYUGS
+B02C;B02C;1101 1172 11AB;B02C;1101 1172 11AB; # (뀬; 뀬; 뀬; 뀬; 뀬; ) HANGUL SYLLABLE GGYUN
+B02D;B02D;1101 1172 11AC;B02D;1101 1172 11AC; # (뀭; 뀭; 뀭; 뀭; 뀭; ) HANGUL SYLLABLE GGYUNJ
+B02E;B02E;1101 1172 11AD;B02E;1101 1172 11AD; # (뀮; 뀮; 뀮; 뀮; 뀮; ) HANGUL SYLLABLE GGYUNH
+B02F;B02F;1101 1172 11AE;B02F;1101 1172 11AE; # (뀯; 뀯; 뀯; 뀯; 뀯; ) HANGUL SYLLABLE GGYUD
+B030;B030;1101 1172 11AF;B030;1101 1172 11AF; # (뀰; 뀰; 뀰; 뀰; 뀰; ) HANGUL SYLLABLE GGYUL
+B031;B031;1101 1172 11B0;B031;1101 1172 11B0; # (뀱; 뀱; 뀱; 뀱; 뀱; ) HANGUL SYLLABLE GGYULG
+B032;B032;1101 1172 11B1;B032;1101 1172 11B1; # (뀲; 뀲; 뀲; 뀲; 뀲; ) HANGUL SYLLABLE GGYULM
+B033;B033;1101 1172 11B2;B033;1101 1172 11B2; # (뀳; 뀳; 뀳; 뀳; 뀳; ) HANGUL SYLLABLE GGYULB
+B034;B034;1101 1172 11B3;B034;1101 1172 11B3; # (뀴; 뀴; 뀴; 뀴; 뀴; ) HANGUL SYLLABLE GGYULS
+B035;B035;1101 1172 11B4;B035;1101 1172 11B4; # (뀵; 뀵; 뀵; 뀵; 뀵; ) HANGUL SYLLABLE GGYULT
+B036;B036;1101 1172 11B5;B036;1101 1172 11B5; # (뀶; 뀶; 뀶; 뀶; 뀶; ) HANGUL SYLLABLE GGYULP
+B037;B037;1101 1172 11B6;B037;1101 1172 11B6; # (뀷; 뀷; 뀷; 뀷; 뀷; ) HANGUL SYLLABLE GGYULH
+B038;B038;1101 1172 11B7;B038;1101 1172 11B7; # (뀸; 뀸; 뀸; 뀸; 뀸; ) HANGUL SYLLABLE GGYUM
+B039;B039;1101 1172 11B8;B039;1101 1172 11B8; # (뀹; 뀹; 뀹; 뀹; 뀹; ) HANGUL SYLLABLE GGYUB
+B03A;B03A;1101 1172 11B9;B03A;1101 1172 11B9; # (뀺; 뀺; 뀺; 뀺; 뀺; ) HANGUL SYLLABLE GGYUBS
+B03B;B03B;1101 1172 11BA;B03B;1101 1172 11BA; # (뀻; 뀻; 뀻; 뀻; 뀻; ) HANGUL SYLLABLE GGYUS
+B03C;B03C;1101 1172 11BB;B03C;1101 1172 11BB; # (뀼; 뀼; 뀼; 뀼; 뀼; ) HANGUL SYLLABLE GGYUSS
+B03D;B03D;1101 1172 11BC;B03D;1101 1172 11BC; # (뀽; 뀽; 뀽; 뀽; 뀽; ) HANGUL SYLLABLE GGYUNG
+B03E;B03E;1101 1172 11BD;B03E;1101 1172 11BD; # (뀾; 뀾; 뀾; 뀾; 뀾; ) HANGUL SYLLABLE GGYUJ
+B03F;B03F;1101 1172 11BE;B03F;1101 1172 11BE; # (뀿; 뀿; 뀿; 뀿; 뀿; ) HANGUL SYLLABLE GGYUC
+B040;B040;1101 1172 11BF;B040;1101 1172 11BF; # (끀; 끀; 끀; 끀; 끀; ) HANGUL SYLLABLE GGYUK
+B041;B041;1101 1172 11C0;B041;1101 1172 11C0; # (끁; 끁; 끁; 끁; 끁; ) HANGUL SYLLABLE GGYUT
+B042;B042;1101 1172 11C1;B042;1101 1172 11C1; # (끂; 끂; 끂; 끂; 끂; ) HANGUL SYLLABLE GGYUP
+B043;B043;1101 1172 11C2;B043;1101 1172 11C2; # (끃; 끃; 끃; 끃; 끃; ) HANGUL SYLLABLE GGYUH
+B044;B044;1101 1173;B044;1101 1173; # (끄; 끄; 끄; 끄; 끄; ) HANGUL SYLLABLE GGEU
+B045;B045;1101 1173 11A8;B045;1101 1173 11A8; # (끅; 끅; 끅; 끅; 끅; ) HANGUL SYLLABLE GGEUG
+B046;B046;1101 1173 11A9;B046;1101 1173 11A9; # (끆; 끆; 끆; 끆; 끆; ) HANGUL SYLLABLE GGEUGG
+B047;B047;1101 1173 11AA;B047;1101 1173 11AA; # (끇; 끇; 끇; 끇; 끇; ) HANGUL SYLLABLE GGEUGS
+B048;B048;1101 1173 11AB;B048;1101 1173 11AB; # (끈; 끈; 끈; 끈; 끈; ) HANGUL SYLLABLE GGEUN
+B049;B049;1101 1173 11AC;B049;1101 1173 11AC; # (끉; 끉; 끉; 끉; 끉; ) HANGUL SYLLABLE GGEUNJ
+B04A;B04A;1101 1173 11AD;B04A;1101 1173 11AD; # (끊; 끊; 끊; 끊; 끊; ) HANGUL SYLLABLE GGEUNH
+B04B;B04B;1101 1173 11AE;B04B;1101 1173 11AE; # (끋; 끋; 끋; 끋; 끋; ) HANGUL SYLLABLE GGEUD
+B04C;B04C;1101 1173 11AF;B04C;1101 1173 11AF; # (끌; 끌; 끌; 끌; 끌; ) HANGUL SYLLABLE GGEUL
+B04D;B04D;1101 1173 11B0;B04D;1101 1173 11B0; # (끍; 끍; 끍; 끍; 끍; ) HANGUL SYLLABLE GGEULG
+B04E;B04E;1101 1173 11B1;B04E;1101 1173 11B1; # (끎; 끎; 끎; 끎; 끎; ) HANGUL SYLLABLE GGEULM
+B04F;B04F;1101 1173 11B2;B04F;1101 1173 11B2; # (끏; 끏; 끏; 끏; 끏; ) HANGUL SYLLABLE GGEULB
+B050;B050;1101 1173 11B3;B050;1101 1173 11B3; # (끐; 끐; 끐; 끐; 끐; ) HANGUL SYLLABLE GGEULS
+B051;B051;1101 1173 11B4;B051;1101 1173 11B4; # (끑; 끑; 끑; 끑; 끑; ) HANGUL SYLLABLE GGEULT
+B052;B052;1101 1173 11B5;B052;1101 1173 11B5; # (끒; 끒; 끒; 끒; 끒; ) HANGUL SYLLABLE GGEULP
+B053;B053;1101 1173 11B6;B053;1101 1173 11B6; # (끓; 끓; 끓; 끓; 끓; ) HANGUL SYLLABLE GGEULH
+B054;B054;1101 1173 11B7;B054;1101 1173 11B7; # (끔; 끔; 끔; 끔; 끔; ) HANGUL SYLLABLE GGEUM
+B055;B055;1101 1173 11B8;B055;1101 1173 11B8; # (끕; 끕; 끕; 끕; 끕; ) HANGUL SYLLABLE GGEUB
+B056;B056;1101 1173 11B9;B056;1101 1173 11B9; # (끖; 끖; 끖; 끖; 끖; ) HANGUL SYLLABLE GGEUBS
+B057;B057;1101 1173 11BA;B057;1101 1173 11BA; # (끗; 끗; 끗; 끗; 끗; ) HANGUL SYLLABLE GGEUS
+B058;B058;1101 1173 11BB;B058;1101 1173 11BB; # (끘; 끘; 끘; 끘; 끘; ) HANGUL SYLLABLE GGEUSS
+B059;B059;1101 1173 11BC;B059;1101 1173 11BC; # (끙; 끙; 끙; 끙; 끙; ) HANGUL SYLLABLE GGEUNG
+B05A;B05A;1101 1173 11BD;B05A;1101 1173 11BD; # (끚; 끚; 끚; 끚; 끚; ) HANGUL SYLLABLE GGEUJ
+B05B;B05B;1101 1173 11BE;B05B;1101 1173 11BE; # (끛; 끛; 끛; 끛; 끛; ) HANGUL SYLLABLE GGEUC
+B05C;B05C;1101 1173 11BF;B05C;1101 1173 11BF; # (끜; 끜; 끜; 끜; 끜; ) HANGUL SYLLABLE GGEUK
+B05D;B05D;1101 1173 11C0;B05D;1101 1173 11C0; # (끝; 끝; 끝; 끝; 끝; ) HANGUL SYLLABLE GGEUT
+B05E;B05E;1101 1173 11C1;B05E;1101 1173 11C1; # (끞; 끞; 끞; 끞; 끞; ) HANGUL SYLLABLE GGEUP
+B05F;B05F;1101 1173 11C2;B05F;1101 1173 11C2; # (끟; 끟; 끟; 끟; 끟; ) HANGUL SYLLABLE GGEUH
+B060;B060;1101 1174;B060;1101 1174; # (끠; 끠; 끠; 끠; 끠; ) HANGUL SYLLABLE GGYI
+B061;B061;1101 1174 11A8;B061;1101 1174 11A8; # (끡; 끡; 끡; 끡; 끡; ) HANGUL SYLLABLE GGYIG
+B062;B062;1101 1174 11A9;B062;1101 1174 11A9; # (끢; 끢; 끢; 끢; 끢; ) HANGUL SYLLABLE GGYIGG
+B063;B063;1101 1174 11AA;B063;1101 1174 11AA; # (끣; 끣; 끣; 끣; 끣; ) HANGUL SYLLABLE GGYIGS
+B064;B064;1101 1174 11AB;B064;1101 1174 11AB; # (끤; 끤; 끤; 끤; 끤; ) HANGUL SYLLABLE GGYIN
+B065;B065;1101 1174 11AC;B065;1101 1174 11AC; # (끥; 끥; 끥; 끥; 끥; ) HANGUL SYLLABLE GGYINJ
+B066;B066;1101 1174 11AD;B066;1101 1174 11AD; # (끦; 끦; 끦; 끦; 끦; ) HANGUL SYLLABLE GGYINH
+B067;B067;1101 1174 11AE;B067;1101 1174 11AE; # (끧; 끧; 끧; 끧; 끧; ) HANGUL SYLLABLE GGYID
+B068;B068;1101 1174 11AF;B068;1101 1174 11AF; # (끨; 끨; 끨; 끨; 끨; ) HANGUL SYLLABLE GGYIL
+B069;B069;1101 1174 11B0;B069;1101 1174 11B0; # (끩; 끩; 끩; 끩; 끩; ) HANGUL SYLLABLE GGYILG
+B06A;B06A;1101 1174 11B1;B06A;1101 1174 11B1; # (끪; 끪; 끪; 끪; 끪; ) HANGUL SYLLABLE GGYILM
+B06B;B06B;1101 1174 11B2;B06B;1101 1174 11B2; # (끫; 끫; 끫; 끫; 끫; ) HANGUL SYLLABLE GGYILB
+B06C;B06C;1101 1174 11B3;B06C;1101 1174 11B3; # (끬; 끬; 끬; 끬; 끬; ) HANGUL SYLLABLE GGYILS
+B06D;B06D;1101 1174 11B4;B06D;1101 1174 11B4; # (끭; 끭; 끭; 끭; 끭; ) HANGUL SYLLABLE GGYILT
+B06E;B06E;1101 1174 11B5;B06E;1101 1174 11B5; # (끮; 끮; 끮; 끮; 끮; ) HANGUL SYLLABLE GGYILP
+B06F;B06F;1101 1174 11B6;B06F;1101 1174 11B6; # (끯; 끯; 끯; 끯; 끯; ) HANGUL SYLLABLE GGYILH
+B070;B070;1101 1174 11B7;B070;1101 1174 11B7; # (끰; 끰; 끰; 끰; 끰; ) HANGUL SYLLABLE GGYIM
+B071;B071;1101 1174 11B8;B071;1101 1174 11B8; # (끱; 끱; 끱; 끱; 끱; ) HANGUL SYLLABLE GGYIB
+B072;B072;1101 1174 11B9;B072;1101 1174 11B9; # (끲; 끲; 끲; 끲; 끲; ) HANGUL SYLLABLE GGYIBS
+B073;B073;1101 1174 11BA;B073;1101 1174 11BA; # (끳; 끳; 끳; 끳; 끳; ) HANGUL SYLLABLE GGYIS
+B074;B074;1101 1174 11BB;B074;1101 1174 11BB; # (끴; 끴; 끴; 끴; 끴; ) HANGUL SYLLABLE GGYISS
+B075;B075;1101 1174 11BC;B075;1101 1174 11BC; # (끵; 끵; 끵; 끵; 끵; ) HANGUL SYLLABLE GGYING
+B076;B076;1101 1174 11BD;B076;1101 1174 11BD; # (끶; 끶; 끶; 끶; 끶; ) HANGUL SYLLABLE GGYIJ
+B077;B077;1101 1174 11BE;B077;1101 1174 11BE; # (끷; 끷; 끷; 끷; 끷; ) HANGUL SYLLABLE GGYIC
+B078;B078;1101 1174 11BF;B078;1101 1174 11BF; # (끸; 끸; 끸; 끸; 끸; ) HANGUL SYLLABLE GGYIK
+B079;B079;1101 1174 11C0;B079;1101 1174 11C0; # (끹; 끹; 끹; 끹; 끹; ) HANGUL SYLLABLE GGYIT
+B07A;B07A;1101 1174 11C1;B07A;1101 1174 11C1; # (끺; 끺; 끺; 끺; 끺; ) HANGUL SYLLABLE GGYIP
+B07B;B07B;1101 1174 11C2;B07B;1101 1174 11C2; # (끻; 끻; 끻; 끻; 끻; ) HANGUL SYLLABLE GGYIH
+B07C;B07C;1101 1175;B07C;1101 1175; # (끼; 끼; 끼; 끼; 끼; ) HANGUL SYLLABLE GGI
+B07D;B07D;1101 1175 11A8;B07D;1101 1175 11A8; # (끽; 끽; 끽; 끽; 끽; ) HANGUL SYLLABLE GGIG
+B07E;B07E;1101 1175 11A9;B07E;1101 1175 11A9; # (끾; 끾; 끾; 끾; 끾; ) HANGUL SYLLABLE GGIGG
+B07F;B07F;1101 1175 11AA;B07F;1101 1175 11AA; # (끿; 끿; 끿; 끿; 끿; ) HANGUL SYLLABLE GGIGS
+B080;B080;1101 1175 11AB;B080;1101 1175 11AB; # (낀; 낀; 낀; 낀; 낀; ) HANGUL SYLLABLE GGIN
+B081;B081;1101 1175 11AC;B081;1101 1175 11AC; # (낁; 낁; 낁; 낁; 낁; ) HANGUL SYLLABLE GGINJ
+B082;B082;1101 1175 11AD;B082;1101 1175 11AD; # (낂; 낂; 낂; 낂; 낂; ) HANGUL SYLLABLE GGINH
+B083;B083;1101 1175 11AE;B083;1101 1175 11AE; # (낃; 낃; 낃; 낃; 낃; ) HANGUL SYLLABLE GGID
+B084;B084;1101 1175 11AF;B084;1101 1175 11AF; # (낄; 낄; 낄; 낄; 낄; ) HANGUL SYLLABLE GGIL
+B085;B085;1101 1175 11B0;B085;1101 1175 11B0; # (낅; 낅; 낅; 낅; 낅; ) HANGUL SYLLABLE GGILG
+B086;B086;1101 1175 11B1;B086;1101 1175 11B1; # (낆; 낆; 낆; 낆; 낆; ) HANGUL SYLLABLE GGILM
+B087;B087;1101 1175 11B2;B087;1101 1175 11B2; # (낇; 낇; 낇; 낇; 낇; ) HANGUL SYLLABLE GGILB
+B088;B088;1101 1175 11B3;B088;1101 1175 11B3; # (낈; 낈; 낈; 낈; 낈; ) HANGUL SYLLABLE GGILS
+B089;B089;1101 1175 11B4;B089;1101 1175 11B4; # (낉; 낉; 낉; 낉; 낉; ) HANGUL SYLLABLE GGILT
+B08A;B08A;1101 1175 11B5;B08A;1101 1175 11B5; # (낊; 낊; 낊; 낊; 낊; ) HANGUL SYLLABLE GGILP
+B08B;B08B;1101 1175 11B6;B08B;1101 1175 11B6; # (낋; 낋; 낋; 낋; 낋; ) HANGUL SYLLABLE GGILH
+B08C;B08C;1101 1175 11B7;B08C;1101 1175 11B7; # (낌; 낌; 낌; 낌; 낌; ) HANGUL SYLLABLE GGIM
+B08D;B08D;1101 1175 11B8;B08D;1101 1175 11B8; # (낍; 낍; 낍; 낍; 낍; ) HANGUL SYLLABLE GGIB
+B08E;B08E;1101 1175 11B9;B08E;1101 1175 11B9; # (낎; 낎; 낎; 낎; 낎; ) HANGUL SYLLABLE GGIBS
+B08F;B08F;1101 1175 11BA;B08F;1101 1175 11BA; # (낏; 낏; 낏; 낏; 낏; ) HANGUL SYLLABLE GGIS
+B090;B090;1101 1175 11BB;B090;1101 1175 11BB; # (낐; 낐; 낐; 낐; 낐; ) HANGUL SYLLABLE GGISS
+B091;B091;1101 1175 11BC;B091;1101 1175 11BC; # (낑; 낑; 낑; 낑; 낑; ) HANGUL SYLLABLE GGING
+B092;B092;1101 1175 11BD;B092;1101 1175 11BD; # (낒; 낒; 낒; 낒; 낒; ) HANGUL SYLLABLE GGIJ
+B093;B093;1101 1175 11BE;B093;1101 1175 11BE; # (낓; 낓; 낓; 낓; 낓; ) HANGUL SYLLABLE GGIC
+B094;B094;1101 1175 11BF;B094;1101 1175 11BF; # (낔; 낔; 낔; 낔; 낔; ) HANGUL SYLLABLE GGIK
+B095;B095;1101 1175 11C0;B095;1101 1175 11C0; # (낕; 낕; 낕; 낕; 낕; ) HANGUL SYLLABLE GGIT
+B096;B096;1101 1175 11C1;B096;1101 1175 11C1; # (낖; 낖; 낖; 낖; 낖; ) HANGUL SYLLABLE GGIP
+B097;B097;1101 1175 11C2;B097;1101 1175 11C2; # (낗; 낗; 낗; 낗; 낗; ) HANGUL SYLLABLE GGIH
+B098;B098;1102 1161;B098;1102 1161; # (나; 나; 나; 나; 나; ) HANGUL SYLLABLE NA
+B099;B099;1102 1161 11A8;B099;1102 1161 11A8; # (낙; 낙; 낙; 낙; 낙; ) HANGUL SYLLABLE NAG
+B09A;B09A;1102 1161 11A9;B09A;1102 1161 11A9; # (낚; 낚; 낚; 낚; 낚; ) HANGUL SYLLABLE NAGG
+B09B;B09B;1102 1161 11AA;B09B;1102 1161 11AA; # (낛; 낛; 낛; 낛; 낛; ) HANGUL SYLLABLE NAGS
+B09C;B09C;1102 1161 11AB;B09C;1102 1161 11AB; # (난; 난; 난; 난; 난; ) HANGUL SYLLABLE NAN
+B09D;B09D;1102 1161 11AC;B09D;1102 1161 11AC; # (낝; 낝; 낝; 낝; 낝; ) HANGUL SYLLABLE NANJ
+B09E;B09E;1102 1161 11AD;B09E;1102 1161 11AD; # (낞; 낞; 낞; 낞; 낞; ) HANGUL SYLLABLE NANH
+B09F;B09F;1102 1161 11AE;B09F;1102 1161 11AE; # (낟; 낟; 낟; 낟; 낟; ) HANGUL SYLLABLE NAD
+B0A0;B0A0;1102 1161 11AF;B0A0;1102 1161 11AF; # (날; 날; 날; 날; 날; ) HANGUL SYLLABLE NAL
+B0A1;B0A1;1102 1161 11B0;B0A1;1102 1161 11B0; # (낡; 낡; 낡; 낡; 낡; ) HANGUL SYLLABLE NALG
+B0A2;B0A2;1102 1161 11B1;B0A2;1102 1161 11B1; # (낢; 낢; 낢; 낢; 낢; ) HANGUL SYLLABLE NALM
+B0A3;B0A3;1102 1161 11B2;B0A3;1102 1161 11B2; # (낣; 낣; 낣; 낣; 낣; ) HANGUL SYLLABLE NALB
+B0A4;B0A4;1102 1161 11B3;B0A4;1102 1161 11B3; # (낤; 낤; 낤; 낤; 낤; ) HANGUL SYLLABLE NALS
+B0A5;B0A5;1102 1161 11B4;B0A5;1102 1161 11B4; # (낥; 낥; 낥; 낥; 낥; ) HANGUL SYLLABLE NALT
+B0A6;B0A6;1102 1161 11B5;B0A6;1102 1161 11B5; # (낦; 낦; 낦; 낦; 낦; ) HANGUL SYLLABLE NALP
+B0A7;B0A7;1102 1161 11B6;B0A7;1102 1161 11B6; # (낧; 낧; 낧; 낧; 낧; ) HANGUL SYLLABLE NALH
+B0A8;B0A8;1102 1161 11B7;B0A8;1102 1161 11B7; # (남; 남; 남; 남; 남; ) HANGUL SYLLABLE NAM
+B0A9;B0A9;1102 1161 11B8;B0A9;1102 1161 11B8; # (납; 납; 납; 납; 납; ) HANGUL SYLLABLE NAB
+B0AA;B0AA;1102 1161 11B9;B0AA;1102 1161 11B9; # (낪; 낪; 낪; 낪; 낪; ) HANGUL SYLLABLE NABS
+B0AB;B0AB;1102 1161 11BA;B0AB;1102 1161 11BA; # (낫; 낫; 낫; 낫; 낫; ) HANGUL SYLLABLE NAS
+B0AC;B0AC;1102 1161 11BB;B0AC;1102 1161 11BB; # (났; 났; 났; 났; 났; ) HANGUL SYLLABLE NASS
+B0AD;B0AD;1102 1161 11BC;B0AD;1102 1161 11BC; # (낭; 낭; 낭; 낭; 낭; ) HANGUL SYLLABLE NANG
+B0AE;B0AE;1102 1161 11BD;B0AE;1102 1161 11BD; # (낮; 낮; 낮; 낮; 낮; ) HANGUL SYLLABLE NAJ
+B0AF;B0AF;1102 1161 11BE;B0AF;1102 1161 11BE; # (낯; 낯; 낯; 낯; 낯; ) HANGUL SYLLABLE NAC
+B0B0;B0B0;1102 1161 11BF;B0B0;1102 1161 11BF; # (낰; 낰; 낰; 낰; 낰; ) HANGUL SYLLABLE NAK
+B0B1;B0B1;1102 1161 11C0;B0B1;1102 1161 11C0; # (낱; 낱; 낱; 낱; 낱; ) HANGUL SYLLABLE NAT
+B0B2;B0B2;1102 1161 11C1;B0B2;1102 1161 11C1; # (낲; 낲; 낲; 낲; 낲; ) HANGUL SYLLABLE NAP
+B0B3;B0B3;1102 1161 11C2;B0B3;1102 1161 11C2; # (낳; 낳; 낳; 낳; 낳; ) HANGUL SYLLABLE NAH
+B0B4;B0B4;1102 1162;B0B4;1102 1162; # (내; 내; 내; 내; 내; ) HANGUL SYLLABLE NAE
+B0B5;B0B5;1102 1162 11A8;B0B5;1102 1162 11A8; # (낵; 낵; 낵; 낵; 낵; ) HANGUL SYLLABLE NAEG
+B0B6;B0B6;1102 1162 11A9;B0B6;1102 1162 11A9; # (낶; 낶; 낶; 낶; 낶; ) HANGUL SYLLABLE NAEGG
+B0B7;B0B7;1102 1162 11AA;B0B7;1102 1162 11AA; # (낷; 낷; 낷; 낷; 낷; ) HANGUL SYLLABLE NAEGS
+B0B8;B0B8;1102 1162 11AB;B0B8;1102 1162 11AB; # (낸; 낸; 낸; 낸; 낸; ) HANGUL SYLLABLE NAEN
+B0B9;B0B9;1102 1162 11AC;B0B9;1102 1162 11AC; # (낹; 낹; 낹; 낹; 낹; ) HANGUL SYLLABLE NAENJ
+B0BA;B0BA;1102 1162 11AD;B0BA;1102 1162 11AD; # (낺; 낺; 낺; 낺; 낺; ) HANGUL SYLLABLE NAENH
+B0BB;B0BB;1102 1162 11AE;B0BB;1102 1162 11AE; # (낻; 낻; 낻; 낻; 낻; ) HANGUL SYLLABLE NAED
+B0BC;B0BC;1102 1162 11AF;B0BC;1102 1162 11AF; # (낼; 낼; 낼; 낼; 낼; ) HANGUL SYLLABLE NAEL
+B0BD;B0BD;1102 1162 11B0;B0BD;1102 1162 11B0; # (낽; 낽; 낽; 낽; 낽; ) HANGUL SYLLABLE NAELG
+B0BE;B0BE;1102 1162 11B1;B0BE;1102 1162 11B1; # (낾; 낾; 낾; 낾; 낾; ) HANGUL SYLLABLE NAELM
+B0BF;B0BF;1102 1162 11B2;B0BF;1102 1162 11B2; # (낿; 낿; 낿; 낿; 낿; ) HANGUL SYLLABLE NAELB
+B0C0;B0C0;1102 1162 11B3;B0C0;1102 1162 11B3; # (냀; 냀; 냀; 냀; 냀; ) HANGUL SYLLABLE NAELS
+B0C1;B0C1;1102 1162 11B4;B0C1;1102 1162 11B4; # (냁; 냁; 냁; 냁; 냁; ) HANGUL SYLLABLE NAELT
+B0C2;B0C2;1102 1162 11B5;B0C2;1102 1162 11B5; # (냂; 냂; 냂; 냂; 냂; ) HANGUL SYLLABLE NAELP
+B0C3;B0C3;1102 1162 11B6;B0C3;1102 1162 11B6; # (냃; 냃; 냃; 냃; 냃; ) HANGUL SYLLABLE NAELH
+B0C4;B0C4;1102 1162 11B7;B0C4;1102 1162 11B7; # (냄; 냄; 냄; 냄; 냄; ) HANGUL SYLLABLE NAEM
+B0C5;B0C5;1102 1162 11B8;B0C5;1102 1162 11B8; # (냅; 냅; 냅; 냅; 냅; ) HANGUL SYLLABLE NAEB
+B0C6;B0C6;1102 1162 11B9;B0C6;1102 1162 11B9; # (냆; 냆; 냆; 냆; 냆; ) HANGUL SYLLABLE NAEBS
+B0C7;B0C7;1102 1162 11BA;B0C7;1102 1162 11BA; # (냇; 냇; 냇; 냇; 냇; ) HANGUL SYLLABLE NAES
+B0C8;B0C8;1102 1162 11BB;B0C8;1102 1162 11BB; # (냈; 냈; 냈; 냈; 냈; ) HANGUL SYLLABLE NAESS
+B0C9;B0C9;1102 1162 11BC;B0C9;1102 1162 11BC; # (냉; 냉; 냉; 냉; 냉; ) HANGUL SYLLABLE NAENG
+B0CA;B0CA;1102 1162 11BD;B0CA;1102 1162 11BD; # (냊; 냊; 냊; 냊; 냊; ) HANGUL SYLLABLE NAEJ
+B0CB;B0CB;1102 1162 11BE;B0CB;1102 1162 11BE; # (냋; 냋; 냋; 냋; 냋; ) HANGUL SYLLABLE NAEC
+B0CC;B0CC;1102 1162 11BF;B0CC;1102 1162 11BF; # (냌; 냌; 냌; 냌; 냌; ) HANGUL SYLLABLE NAEK
+B0CD;B0CD;1102 1162 11C0;B0CD;1102 1162 11C0; # (냍; 냍; 냍; 냍; 냍; ) HANGUL SYLLABLE NAET
+B0CE;B0CE;1102 1162 11C1;B0CE;1102 1162 11C1; # (냎; 냎; 냎; 냎; 냎; ) HANGUL SYLLABLE NAEP
+B0CF;B0CF;1102 1162 11C2;B0CF;1102 1162 11C2; # (냏; 냏; 냏; 냏; 냏; ) HANGUL SYLLABLE NAEH
+B0D0;B0D0;1102 1163;B0D0;1102 1163; # (냐; 냐; 냐; 냐; 냐; ) HANGUL SYLLABLE NYA
+B0D1;B0D1;1102 1163 11A8;B0D1;1102 1163 11A8; # (냑; 냑; 냑; 냑; 냑; ) HANGUL SYLLABLE NYAG
+B0D2;B0D2;1102 1163 11A9;B0D2;1102 1163 11A9; # (냒; 냒; 냒; 냒; 냒; ) HANGUL SYLLABLE NYAGG
+B0D3;B0D3;1102 1163 11AA;B0D3;1102 1163 11AA; # (냓; 냓; 냓; 냓; 냓; ) HANGUL SYLLABLE NYAGS
+B0D4;B0D4;1102 1163 11AB;B0D4;1102 1163 11AB; # (냔; 냔; 냔; 냔; 냔; ) HANGUL SYLLABLE NYAN
+B0D5;B0D5;1102 1163 11AC;B0D5;1102 1163 11AC; # (냕; 냕; 냕; 냕; 냕; ) HANGUL SYLLABLE NYANJ
+B0D6;B0D6;1102 1163 11AD;B0D6;1102 1163 11AD; # (냖; 냖; 냖; 냖; 냖; ) HANGUL SYLLABLE NYANH
+B0D7;B0D7;1102 1163 11AE;B0D7;1102 1163 11AE; # (냗; 냗; 냗; 냗; 냗; ) HANGUL SYLLABLE NYAD
+B0D8;B0D8;1102 1163 11AF;B0D8;1102 1163 11AF; # (냘; 냘; 냘; 냘; 냘; ) HANGUL SYLLABLE NYAL
+B0D9;B0D9;1102 1163 11B0;B0D9;1102 1163 11B0; # (냙; 냙; 냙; 냙; 냙; ) HANGUL SYLLABLE NYALG
+B0DA;B0DA;1102 1163 11B1;B0DA;1102 1163 11B1; # (냚; 냚; 냚; 냚; 냚; ) HANGUL SYLLABLE NYALM
+B0DB;B0DB;1102 1163 11B2;B0DB;1102 1163 11B2; # (냛; 냛; 냛; 냛; 냛; ) HANGUL SYLLABLE NYALB
+B0DC;B0DC;1102 1163 11B3;B0DC;1102 1163 11B3; # (냜; 냜; 냜; 냜; 냜; ) HANGUL SYLLABLE NYALS
+B0DD;B0DD;1102 1163 11B4;B0DD;1102 1163 11B4; # (냝; 냝; 냝; 냝; 냝; ) HANGUL SYLLABLE NYALT
+B0DE;B0DE;1102 1163 11B5;B0DE;1102 1163 11B5; # (냞; 냞; 냞; 냞; 냞; ) HANGUL SYLLABLE NYALP
+B0DF;B0DF;1102 1163 11B6;B0DF;1102 1163 11B6; # (냟; 냟; 냟; 냟; 냟; ) HANGUL SYLLABLE NYALH
+B0E0;B0E0;1102 1163 11B7;B0E0;1102 1163 11B7; # (냠; 냠; 냠; 냠; 냠; ) HANGUL SYLLABLE NYAM
+B0E1;B0E1;1102 1163 11B8;B0E1;1102 1163 11B8; # (냡; 냡; 냡; 냡; 냡; ) HANGUL SYLLABLE NYAB
+B0E2;B0E2;1102 1163 11B9;B0E2;1102 1163 11B9; # (냢; 냢; 냢; 냢; 냢; ) HANGUL SYLLABLE NYABS
+B0E3;B0E3;1102 1163 11BA;B0E3;1102 1163 11BA; # (냣; 냣; 냣; 냣; 냣; ) HANGUL SYLLABLE NYAS
+B0E4;B0E4;1102 1163 11BB;B0E4;1102 1163 11BB; # (냤; 냤; 냤; 냤; 냤; ) HANGUL SYLLABLE NYASS
+B0E5;B0E5;1102 1163 11BC;B0E5;1102 1163 11BC; # (냥; 냥; 냥; 냥; 냥; ) HANGUL SYLLABLE NYANG
+B0E6;B0E6;1102 1163 11BD;B0E6;1102 1163 11BD; # (냦; 냦; 냦; 냦; 냦; ) HANGUL SYLLABLE NYAJ
+B0E7;B0E7;1102 1163 11BE;B0E7;1102 1163 11BE; # (냧; 냧; 냧; 냧; 냧; ) HANGUL SYLLABLE NYAC
+B0E8;B0E8;1102 1163 11BF;B0E8;1102 1163 11BF; # (냨; 냨; 냨; 냨; 냨; ) HANGUL SYLLABLE NYAK
+B0E9;B0E9;1102 1163 11C0;B0E9;1102 1163 11C0; # (냩; 냩; 냩; 냩; 냩; ) HANGUL SYLLABLE NYAT
+B0EA;B0EA;1102 1163 11C1;B0EA;1102 1163 11C1; # (냪; 냪; 냪; 냪; 냪; ) HANGUL SYLLABLE NYAP
+B0EB;B0EB;1102 1163 11C2;B0EB;1102 1163 11C2; # (냫; 냫; 냫; 냫; 냫; ) HANGUL SYLLABLE NYAH
+B0EC;B0EC;1102 1164;B0EC;1102 1164; # (냬; 냬; 냬; 냬; 냬; ) HANGUL SYLLABLE NYAE
+B0ED;B0ED;1102 1164 11A8;B0ED;1102 1164 11A8; # (냭; 냭; 냭; 냭; 냭; ) HANGUL SYLLABLE NYAEG
+B0EE;B0EE;1102 1164 11A9;B0EE;1102 1164 11A9; # (냮; 냮; 냮; 냮; 냮; ) HANGUL SYLLABLE NYAEGG
+B0EF;B0EF;1102 1164 11AA;B0EF;1102 1164 11AA; # (냯; 냯; 냯; 냯; 냯; ) HANGUL SYLLABLE NYAEGS
+B0F0;B0F0;1102 1164 11AB;B0F0;1102 1164 11AB; # (냰; 냰; 냰; 냰; 냰; ) HANGUL SYLLABLE NYAEN
+B0F1;B0F1;1102 1164 11AC;B0F1;1102 1164 11AC; # (냱; 냱; 냱; 냱; 냱; ) HANGUL SYLLABLE NYAENJ
+B0F2;B0F2;1102 1164 11AD;B0F2;1102 1164 11AD; # (냲; 냲; 냲; 냲; 냲; ) HANGUL SYLLABLE NYAENH
+B0F3;B0F3;1102 1164 11AE;B0F3;1102 1164 11AE; # (냳; 냳; 냳; 냳; 냳; ) HANGUL SYLLABLE NYAED
+B0F4;B0F4;1102 1164 11AF;B0F4;1102 1164 11AF; # (냴; 냴; 냴; 냴; 냴; ) HANGUL SYLLABLE NYAEL
+B0F5;B0F5;1102 1164 11B0;B0F5;1102 1164 11B0; # (냵; 냵; 냵; 냵; 냵; ) HANGUL SYLLABLE NYAELG
+B0F6;B0F6;1102 1164 11B1;B0F6;1102 1164 11B1; # (냶; 냶; 냶; 냶; 냶; ) HANGUL SYLLABLE NYAELM
+B0F7;B0F7;1102 1164 11B2;B0F7;1102 1164 11B2; # (냷; 냷; 냷; 냷; 냷; ) HANGUL SYLLABLE NYAELB
+B0F8;B0F8;1102 1164 11B3;B0F8;1102 1164 11B3; # (냸; 냸; 냸; 냸; 냸; ) HANGUL SYLLABLE NYAELS
+B0F9;B0F9;1102 1164 11B4;B0F9;1102 1164 11B4; # (냹; 냹; 냹; 냹; 냹; ) HANGUL SYLLABLE NYAELT
+B0FA;B0FA;1102 1164 11B5;B0FA;1102 1164 11B5; # (냺; 냺; 냺; 냺; 냺; ) HANGUL SYLLABLE NYAELP
+B0FB;B0FB;1102 1164 11B6;B0FB;1102 1164 11B6; # (냻; 냻; 냻; 냻; 냻; ) HANGUL SYLLABLE NYAELH
+B0FC;B0FC;1102 1164 11B7;B0FC;1102 1164 11B7; # (냼; 냼; 냼; 냼; 냼; ) HANGUL SYLLABLE NYAEM
+B0FD;B0FD;1102 1164 11B8;B0FD;1102 1164 11B8; # (냽; 냽; 냽; 냽; 냽; ) HANGUL SYLLABLE NYAEB
+B0FE;B0FE;1102 1164 11B9;B0FE;1102 1164 11B9; # (냾; 냾; 냾; 냾; 냾; ) HANGUL SYLLABLE NYAEBS
+B0FF;B0FF;1102 1164 11BA;B0FF;1102 1164 11BA; # (냿; 냿; 냿; 냿; 냿; ) HANGUL SYLLABLE NYAES
+B100;B100;1102 1164 11BB;B100;1102 1164 11BB; # (넀; 넀; 넀; 넀; 넀; ) HANGUL SYLLABLE NYAESS
+B101;B101;1102 1164 11BC;B101;1102 1164 11BC; # (넁; 넁; 넁; 넁; 넁; ) HANGUL SYLLABLE NYAENG
+B102;B102;1102 1164 11BD;B102;1102 1164 11BD; # (넂; 넂; 넂; 넂; 넂; ) HANGUL SYLLABLE NYAEJ
+B103;B103;1102 1164 11BE;B103;1102 1164 11BE; # (넃; 넃; 넃; 넃; 넃; ) HANGUL SYLLABLE NYAEC
+B104;B104;1102 1164 11BF;B104;1102 1164 11BF; # (넄; 넄; 넄; 넄; 넄; ) HANGUL SYLLABLE NYAEK
+B105;B105;1102 1164 11C0;B105;1102 1164 11C0; # (넅; 넅; 넅; 넅; 넅; ) HANGUL SYLLABLE NYAET
+B106;B106;1102 1164 11C1;B106;1102 1164 11C1; # (넆; 넆; 넆; 넆; 넆; ) HANGUL SYLLABLE NYAEP
+B107;B107;1102 1164 11C2;B107;1102 1164 11C2; # (넇; 넇; 넇; 넇; 넇; ) HANGUL SYLLABLE NYAEH
+B108;B108;1102 1165;B108;1102 1165; # (너; 너; 너; 너; 너; ) HANGUL SYLLABLE NEO
+B109;B109;1102 1165 11A8;B109;1102 1165 11A8; # (넉; 넉; 넉; 넉; 넉; ) HANGUL SYLLABLE NEOG
+B10A;B10A;1102 1165 11A9;B10A;1102 1165 11A9; # (넊; 넊; 넊; 넊; 넊; ) HANGUL SYLLABLE NEOGG
+B10B;B10B;1102 1165 11AA;B10B;1102 1165 11AA; # (넋; 넋; 넋; 넋; 넋; ) HANGUL SYLLABLE NEOGS
+B10C;B10C;1102 1165 11AB;B10C;1102 1165 11AB; # (넌; 넌; 넌; 넌; 넌; ) HANGUL SYLLABLE NEON
+B10D;B10D;1102 1165 11AC;B10D;1102 1165 11AC; # (넍; 넍; 넍; 넍; 넍; ) HANGUL SYLLABLE NEONJ
+B10E;B10E;1102 1165 11AD;B10E;1102 1165 11AD; # (넎; 넎; 넎; 넎; 넎; ) HANGUL SYLLABLE NEONH
+B10F;B10F;1102 1165 11AE;B10F;1102 1165 11AE; # (넏; 넏; 넏; 넏; 넏; ) HANGUL SYLLABLE NEOD
+B110;B110;1102 1165 11AF;B110;1102 1165 11AF; # (널; 널; 널; 널; 널; ) HANGUL SYLLABLE NEOL
+B111;B111;1102 1165 11B0;B111;1102 1165 11B0; # (넑; 넑; 넑; 넑; 넑; ) HANGUL SYLLABLE NEOLG
+B112;B112;1102 1165 11B1;B112;1102 1165 11B1; # (넒; 넒; 넒; 넒; 넒; ) HANGUL SYLLABLE NEOLM
+B113;B113;1102 1165 11B2;B113;1102 1165 11B2; # (넓; 넓; 넓; 넓; 넓; ) HANGUL SYLLABLE NEOLB
+B114;B114;1102 1165 11B3;B114;1102 1165 11B3; # (넔; 넔; 넔; 넔; 넔; ) HANGUL SYLLABLE NEOLS
+B115;B115;1102 1165 11B4;B115;1102 1165 11B4; # (넕; 넕; 넕; 넕; 넕; ) HANGUL SYLLABLE NEOLT
+B116;B116;1102 1165 11B5;B116;1102 1165 11B5; # (넖; 넖; 넖; 넖; 넖; ) HANGUL SYLLABLE NEOLP
+B117;B117;1102 1165 11B6;B117;1102 1165 11B6; # (넗; 넗; 넗; 넗; 넗; ) HANGUL SYLLABLE NEOLH
+B118;B118;1102 1165 11B7;B118;1102 1165 11B7; # (넘; 넘; 넘; 넘; 넘; ) HANGUL SYLLABLE NEOM
+B119;B119;1102 1165 11B8;B119;1102 1165 11B8; # (넙; 넙; 넙; 넙; 넙; ) HANGUL SYLLABLE NEOB
+B11A;B11A;1102 1165 11B9;B11A;1102 1165 11B9; # (넚; 넚; 넚; 넚; 넚; ) HANGUL SYLLABLE NEOBS
+B11B;B11B;1102 1165 11BA;B11B;1102 1165 11BA; # (넛; 넛; 넛; 넛; 넛; ) HANGUL SYLLABLE NEOS
+B11C;B11C;1102 1165 11BB;B11C;1102 1165 11BB; # (넜; 넜; 넜; 넜; 넜; ) HANGUL SYLLABLE NEOSS
+B11D;B11D;1102 1165 11BC;B11D;1102 1165 11BC; # (넝; 넝; 넝; 넝; 넝; ) HANGUL SYLLABLE NEONG
+B11E;B11E;1102 1165 11BD;B11E;1102 1165 11BD; # (넞; 넞; 넞; 넞; 넞; ) HANGUL SYLLABLE NEOJ
+B11F;B11F;1102 1165 11BE;B11F;1102 1165 11BE; # (넟; 넟; 넟; 넟; 넟; ) HANGUL SYLLABLE NEOC
+B120;B120;1102 1165 11BF;B120;1102 1165 11BF; # (넠; 넠; 넠; 넠; 넠; ) HANGUL SYLLABLE NEOK
+B121;B121;1102 1165 11C0;B121;1102 1165 11C0; # (넡; 넡; 넡; 넡; 넡; ) HANGUL SYLLABLE NEOT
+B122;B122;1102 1165 11C1;B122;1102 1165 11C1; # (넢; 넢; 넢; 넢; 넢; ) HANGUL SYLLABLE NEOP
+B123;B123;1102 1165 11C2;B123;1102 1165 11C2; # (넣; 넣; 넣; 넣; 넣; ) HANGUL SYLLABLE NEOH
+B124;B124;1102 1166;B124;1102 1166; # (네; 네; 네; 네; 네; ) HANGUL SYLLABLE NE
+B125;B125;1102 1166 11A8;B125;1102 1166 11A8; # (넥; 넥; 넥; 넥; 넥; ) HANGUL SYLLABLE NEG
+B126;B126;1102 1166 11A9;B126;1102 1166 11A9; # (넦; 넦; 넦; 넦; 넦; ) HANGUL SYLLABLE NEGG
+B127;B127;1102 1166 11AA;B127;1102 1166 11AA; # (넧; 넧; 넧; 넧; 넧; ) HANGUL SYLLABLE NEGS
+B128;B128;1102 1166 11AB;B128;1102 1166 11AB; # (넨; 넨; 넨; 넨; 넨; ) HANGUL SYLLABLE NEN
+B129;B129;1102 1166 11AC;B129;1102 1166 11AC; # (넩; 넩; 넩; 넩; 넩; ) HANGUL SYLLABLE NENJ
+B12A;B12A;1102 1166 11AD;B12A;1102 1166 11AD; # (넪; 넪; 넪; 넪; 넪; ) HANGUL SYLLABLE NENH
+B12B;B12B;1102 1166 11AE;B12B;1102 1166 11AE; # (넫; 넫; 넫; 넫; 넫; ) HANGUL SYLLABLE NED
+B12C;B12C;1102 1166 11AF;B12C;1102 1166 11AF; # (넬; 넬; 넬; 넬; 넬; ) HANGUL SYLLABLE NEL
+B12D;B12D;1102 1166 11B0;B12D;1102 1166 11B0; # (넭; 넭; 넭; 넭; 넭; ) HANGUL SYLLABLE NELG
+B12E;B12E;1102 1166 11B1;B12E;1102 1166 11B1; # (넮; 넮; 넮; 넮; 넮; ) HANGUL SYLLABLE NELM
+B12F;B12F;1102 1166 11B2;B12F;1102 1166 11B2; # (넯; 넯; 넯; 넯; 넯; ) HANGUL SYLLABLE NELB
+B130;B130;1102 1166 11B3;B130;1102 1166 11B3; # (넰; 넰; 넰; 넰; 넰; ) HANGUL SYLLABLE NELS
+B131;B131;1102 1166 11B4;B131;1102 1166 11B4; # (넱; 넱; 넱; 넱; 넱; ) HANGUL SYLLABLE NELT
+B132;B132;1102 1166 11B5;B132;1102 1166 11B5; # (넲; 넲; 넲; 넲; 넲; ) HANGUL SYLLABLE NELP
+B133;B133;1102 1166 11B6;B133;1102 1166 11B6; # (넳; 넳; 넳; 넳; 넳; ) HANGUL SYLLABLE NELH
+B134;B134;1102 1166 11B7;B134;1102 1166 11B7; # (넴; 넴; 넴; 넴; 넴; ) HANGUL SYLLABLE NEM
+B135;B135;1102 1166 11B8;B135;1102 1166 11B8; # (넵; 넵; 넵; 넵; 넵; ) HANGUL SYLLABLE NEB
+B136;B136;1102 1166 11B9;B136;1102 1166 11B9; # (넶; 넶; 넶; 넶; 넶; ) HANGUL SYLLABLE NEBS
+B137;B137;1102 1166 11BA;B137;1102 1166 11BA; # (넷; 넷; 넷; 넷; 넷; ) HANGUL SYLLABLE NES
+B138;B138;1102 1166 11BB;B138;1102 1166 11BB; # (넸; 넸; 넸; 넸; 넸; ) HANGUL SYLLABLE NESS
+B139;B139;1102 1166 11BC;B139;1102 1166 11BC; # (넹; 넹; 넹; 넹; 넹; ) HANGUL SYLLABLE NENG
+B13A;B13A;1102 1166 11BD;B13A;1102 1166 11BD; # (넺; 넺; 넺; 넺; 넺; ) HANGUL SYLLABLE NEJ
+B13B;B13B;1102 1166 11BE;B13B;1102 1166 11BE; # (넻; 넻; 넻; 넻; 넻; ) HANGUL SYLLABLE NEC
+B13C;B13C;1102 1166 11BF;B13C;1102 1166 11BF; # (넼; 넼; 넼; 넼; 넼; ) HANGUL SYLLABLE NEK
+B13D;B13D;1102 1166 11C0;B13D;1102 1166 11C0; # (넽; 넽; 넽; 넽; 넽; ) HANGUL SYLLABLE NET
+B13E;B13E;1102 1166 11C1;B13E;1102 1166 11C1; # (넾; 넾; 넾; 넾; 넾; ) HANGUL SYLLABLE NEP
+B13F;B13F;1102 1166 11C2;B13F;1102 1166 11C2; # (넿; 넿; 넿; 넿; 넿; ) HANGUL SYLLABLE NEH
+B140;B140;1102 1167;B140;1102 1167; # (녀; 녀; 녀; 녀; 녀; ) HANGUL SYLLABLE NYEO
+B141;B141;1102 1167 11A8;B141;1102 1167 11A8; # (녁; 녁; 녁; 녁; 녁; ) HANGUL SYLLABLE NYEOG
+B142;B142;1102 1167 11A9;B142;1102 1167 11A9; # (녂; 녂; 녂; 녂; 녂; ) HANGUL SYLLABLE NYEOGG
+B143;B143;1102 1167 11AA;B143;1102 1167 11AA; # (녃; 녃; 녃; 녃; 녃; ) HANGUL SYLLABLE NYEOGS
+B144;B144;1102 1167 11AB;B144;1102 1167 11AB; # (년; 년; 년; 년; 년; ) HANGUL SYLLABLE NYEON
+B145;B145;1102 1167 11AC;B145;1102 1167 11AC; # (녅; 녅; 녅; 녅; 녅; ) HANGUL SYLLABLE NYEONJ
+B146;B146;1102 1167 11AD;B146;1102 1167 11AD; # (녆; 녆; 녆; 녆; 녆; ) HANGUL SYLLABLE NYEONH
+B147;B147;1102 1167 11AE;B147;1102 1167 11AE; # (녇; 녇; 녇; 녇; 녇; ) HANGUL SYLLABLE NYEOD
+B148;B148;1102 1167 11AF;B148;1102 1167 11AF; # (녈; 녈; 녈; 녈; 녈; ) HANGUL SYLLABLE NYEOL
+B149;B149;1102 1167 11B0;B149;1102 1167 11B0; # (녉; 녉; 녉; 녉; 녉; ) HANGUL SYLLABLE NYEOLG
+B14A;B14A;1102 1167 11B1;B14A;1102 1167 11B1; # (녊; 녊; 녊; 녊; 녊; ) HANGUL SYLLABLE NYEOLM
+B14B;B14B;1102 1167 11B2;B14B;1102 1167 11B2; # (녋; 녋; 녋; 녋; 녋; ) HANGUL SYLLABLE NYEOLB
+B14C;B14C;1102 1167 11B3;B14C;1102 1167 11B3; # (녌; 녌; 녌; 녌; 녌; ) HANGUL SYLLABLE NYEOLS
+B14D;B14D;1102 1167 11B4;B14D;1102 1167 11B4; # (녍; 녍; 녍; 녍; 녍; ) HANGUL SYLLABLE NYEOLT
+B14E;B14E;1102 1167 11B5;B14E;1102 1167 11B5; # (녎; 녎; 녎; 녎; 녎; ) HANGUL SYLLABLE NYEOLP
+B14F;B14F;1102 1167 11B6;B14F;1102 1167 11B6; # (녏; 녏; 녏; 녏; 녏; ) HANGUL SYLLABLE NYEOLH
+B150;B150;1102 1167 11B7;B150;1102 1167 11B7; # (념; 념; 념; 념; 념; ) HANGUL SYLLABLE NYEOM
+B151;B151;1102 1167 11B8;B151;1102 1167 11B8; # (녑; 녑; 녑; 녑; 녑; ) HANGUL SYLLABLE NYEOB
+B152;B152;1102 1167 11B9;B152;1102 1167 11B9; # (녒; 녒; 녒; 녒; 녒; ) HANGUL SYLLABLE NYEOBS
+B153;B153;1102 1167 11BA;B153;1102 1167 11BA; # (녓; 녓; 녓; 녓; 녓; ) HANGUL SYLLABLE NYEOS
+B154;B154;1102 1167 11BB;B154;1102 1167 11BB; # (녔; 녔; 녔; 녔; 녔; ) HANGUL SYLLABLE NYEOSS
+B155;B155;1102 1167 11BC;B155;1102 1167 11BC; # (녕; 녕; 녕; 녕; 녕; ) HANGUL SYLLABLE NYEONG
+B156;B156;1102 1167 11BD;B156;1102 1167 11BD; # (녖; 녖; 녖; 녖; 녖; ) HANGUL SYLLABLE NYEOJ
+B157;B157;1102 1167 11BE;B157;1102 1167 11BE; # (녗; 녗; 녗; 녗; 녗; ) HANGUL SYLLABLE NYEOC
+B158;B158;1102 1167 11BF;B158;1102 1167 11BF; # (녘; 녘; 녘; 녘; 녘; ) HANGUL SYLLABLE NYEOK
+B159;B159;1102 1167 11C0;B159;1102 1167 11C0; # (녙; 녙; 녙; 녙; 녙; ) HANGUL SYLLABLE NYEOT
+B15A;B15A;1102 1167 11C1;B15A;1102 1167 11C1; # (녚; 녚; 녚; 녚; 녚; ) HANGUL SYLLABLE NYEOP
+B15B;B15B;1102 1167 11C2;B15B;1102 1167 11C2; # (녛; 녛; 녛; 녛; 녛; ) HANGUL SYLLABLE NYEOH
+B15C;B15C;1102 1168;B15C;1102 1168; # (녜; 녜; 녜; 녜; 녜; ) HANGUL SYLLABLE NYE
+B15D;B15D;1102 1168 11A8;B15D;1102 1168 11A8; # (녝; 녝; 녝; 녝; 녝; ) HANGUL SYLLABLE NYEG
+B15E;B15E;1102 1168 11A9;B15E;1102 1168 11A9; # (녞; 녞; 녞; 녞; 녞; ) HANGUL SYLLABLE NYEGG
+B15F;B15F;1102 1168 11AA;B15F;1102 1168 11AA; # (녟; 녟; 녟; 녟; 녟; ) HANGUL SYLLABLE NYEGS
+B160;B160;1102 1168 11AB;B160;1102 1168 11AB; # (녠; 녠; 녠; 녠; 녠; ) HANGUL SYLLABLE NYEN
+B161;B161;1102 1168 11AC;B161;1102 1168 11AC; # (녡; 녡; 녡; 녡; 녡; ) HANGUL SYLLABLE NYENJ
+B162;B162;1102 1168 11AD;B162;1102 1168 11AD; # (녢; 녢; 녢; 녢; 녢; ) HANGUL SYLLABLE NYENH
+B163;B163;1102 1168 11AE;B163;1102 1168 11AE; # (녣; 녣; 녣; 녣; 녣; ) HANGUL SYLLABLE NYED
+B164;B164;1102 1168 11AF;B164;1102 1168 11AF; # (녤; 녤; 녤; 녤; 녤; ) HANGUL SYLLABLE NYEL
+B165;B165;1102 1168 11B0;B165;1102 1168 11B0; # (녥; 녥; 녥; 녥; 녥; ) HANGUL SYLLABLE NYELG
+B166;B166;1102 1168 11B1;B166;1102 1168 11B1; # (녦; 녦; 녦; 녦; 녦; ) HANGUL SYLLABLE NYELM
+B167;B167;1102 1168 11B2;B167;1102 1168 11B2; # (녧; 녧; 녧; 녧; 녧; ) HANGUL SYLLABLE NYELB
+B168;B168;1102 1168 11B3;B168;1102 1168 11B3; # (녨; 녨; 녨; 녨; 녨; ) HANGUL SYLLABLE NYELS
+B169;B169;1102 1168 11B4;B169;1102 1168 11B4; # (녩; 녩; 녩; 녩; 녩; ) HANGUL SYLLABLE NYELT
+B16A;B16A;1102 1168 11B5;B16A;1102 1168 11B5; # (녪; 녪; 녪; 녪; 녪; ) HANGUL SYLLABLE NYELP
+B16B;B16B;1102 1168 11B6;B16B;1102 1168 11B6; # (녫; 녫; 녫; 녫; 녫; ) HANGUL SYLLABLE NYELH
+B16C;B16C;1102 1168 11B7;B16C;1102 1168 11B7; # (녬; 녬; 녬; 녬; 녬; ) HANGUL SYLLABLE NYEM
+B16D;B16D;1102 1168 11B8;B16D;1102 1168 11B8; # (녭; 녭; 녭; 녭; 녭; ) HANGUL SYLLABLE NYEB
+B16E;B16E;1102 1168 11B9;B16E;1102 1168 11B9; # (녮; 녮; 녮; 녮; 녮; ) HANGUL SYLLABLE NYEBS
+B16F;B16F;1102 1168 11BA;B16F;1102 1168 11BA; # (녯; 녯; 녯; 녯; 녯; ) HANGUL SYLLABLE NYES
+B170;B170;1102 1168 11BB;B170;1102 1168 11BB; # (녰; 녰; 녰; 녰; 녰; ) HANGUL SYLLABLE NYESS
+B171;B171;1102 1168 11BC;B171;1102 1168 11BC; # (녱; 녱; 녱; 녱; 녱; ) HANGUL SYLLABLE NYENG
+B172;B172;1102 1168 11BD;B172;1102 1168 11BD; # (녲; 녲; 녲; 녲; 녲; ) HANGUL SYLLABLE NYEJ
+B173;B173;1102 1168 11BE;B173;1102 1168 11BE; # (녳; 녳; 녳; 녳; 녳; ) HANGUL SYLLABLE NYEC
+B174;B174;1102 1168 11BF;B174;1102 1168 11BF; # (녴; 녴; 녴; 녴; 녴; ) HANGUL SYLLABLE NYEK
+B175;B175;1102 1168 11C0;B175;1102 1168 11C0; # (녵; 녵; 녵; 녵; 녵; ) HANGUL SYLLABLE NYET
+B176;B176;1102 1168 11C1;B176;1102 1168 11C1; # (녶; 녶; 녶; 녶; 녶; ) HANGUL SYLLABLE NYEP
+B177;B177;1102 1168 11C2;B177;1102 1168 11C2; # (녷; 녷; 녷; 녷; 녷; ) HANGUL SYLLABLE NYEH
+B178;B178;1102 1169;B178;1102 1169; # (노; 노; 노; 노; 노; ) HANGUL SYLLABLE NO
+B179;B179;1102 1169 11A8;B179;1102 1169 11A8; # (녹; 녹; 녹; 녹; 녹; ) HANGUL SYLLABLE NOG
+B17A;B17A;1102 1169 11A9;B17A;1102 1169 11A9; # (녺; 녺; 녺; 녺; 녺; ) HANGUL SYLLABLE NOGG
+B17B;B17B;1102 1169 11AA;B17B;1102 1169 11AA; # (녻; 녻; 녻; 녻; 녻; ) HANGUL SYLLABLE NOGS
+B17C;B17C;1102 1169 11AB;B17C;1102 1169 11AB; # (논; 논; 논; 논; 논; ) HANGUL SYLLABLE NON
+B17D;B17D;1102 1169 11AC;B17D;1102 1169 11AC; # (녽; 녽; 녽; 녽; 녽; ) HANGUL SYLLABLE NONJ
+B17E;B17E;1102 1169 11AD;B17E;1102 1169 11AD; # (녾; 녾; 녾; 녾; 녾; ) HANGUL SYLLABLE NONH
+B17F;B17F;1102 1169 11AE;B17F;1102 1169 11AE; # (녿; 녿; 녿; 녿; 녿; ) HANGUL SYLLABLE NOD
+B180;B180;1102 1169 11AF;B180;1102 1169 11AF; # (놀; 놀; 놀; 놀; 놀; ) HANGUL SYLLABLE NOL
+B181;B181;1102 1169 11B0;B181;1102 1169 11B0; # (놁; 놁; 놁; 놁; 놁; ) HANGUL SYLLABLE NOLG
+B182;B182;1102 1169 11B1;B182;1102 1169 11B1; # (놂; 놂; 놂; 놂; 놂; ) HANGUL SYLLABLE NOLM
+B183;B183;1102 1169 11B2;B183;1102 1169 11B2; # (놃; 놃; 놃; 놃; 놃; ) HANGUL SYLLABLE NOLB
+B184;B184;1102 1169 11B3;B184;1102 1169 11B3; # (놄; 놄; 놄; 놄; 놄; ) HANGUL SYLLABLE NOLS
+B185;B185;1102 1169 11B4;B185;1102 1169 11B4; # (놅; 놅; 놅; 놅; 놅; ) HANGUL SYLLABLE NOLT
+B186;B186;1102 1169 11B5;B186;1102 1169 11B5; # (놆; 놆; 놆; 놆; 놆; ) HANGUL SYLLABLE NOLP
+B187;B187;1102 1169 11B6;B187;1102 1169 11B6; # (놇; 놇; 놇; 놇; 놇; ) HANGUL SYLLABLE NOLH
+B188;B188;1102 1169 11B7;B188;1102 1169 11B7; # (놈; 놈; 놈; 놈; 놈; ) HANGUL SYLLABLE NOM
+B189;B189;1102 1169 11B8;B189;1102 1169 11B8; # (놉; 놉; 놉; 놉; 놉; ) HANGUL SYLLABLE NOB
+B18A;B18A;1102 1169 11B9;B18A;1102 1169 11B9; # (놊; 놊; 놊; 놊; 놊; ) HANGUL SYLLABLE NOBS
+B18B;B18B;1102 1169 11BA;B18B;1102 1169 11BA; # (놋; 놋; 놋; 놋; 놋; ) HANGUL SYLLABLE NOS
+B18C;B18C;1102 1169 11BB;B18C;1102 1169 11BB; # (놌; 놌; 놌; 놌; 놌; ) HANGUL SYLLABLE NOSS
+B18D;B18D;1102 1169 11BC;B18D;1102 1169 11BC; # (농; 농; 농; 농; 농; ) HANGUL SYLLABLE NONG
+B18E;B18E;1102 1169 11BD;B18E;1102 1169 11BD; # (놎; 놎; 놎; 놎; 놎; ) HANGUL SYLLABLE NOJ
+B18F;B18F;1102 1169 11BE;B18F;1102 1169 11BE; # (놏; 놏; 놏; 놏; 놏; ) HANGUL SYLLABLE NOC
+B190;B190;1102 1169 11BF;B190;1102 1169 11BF; # (놐; 놐; 놐; 놐; 놐; ) HANGUL SYLLABLE NOK
+B191;B191;1102 1169 11C0;B191;1102 1169 11C0; # (놑; 놑; 놑; 놑; 놑; ) HANGUL SYLLABLE NOT
+B192;B192;1102 1169 11C1;B192;1102 1169 11C1; # (높; 높; 높; 높; 높; ) HANGUL SYLLABLE NOP
+B193;B193;1102 1169 11C2;B193;1102 1169 11C2; # (놓; 놓; 놓; 놓; 놓; ) HANGUL SYLLABLE NOH
+B194;B194;1102 116A;B194;1102 116A; # (놔; 놔; 놔; 놔; 놔; ) HANGUL SYLLABLE NWA
+B195;B195;1102 116A 11A8;B195;1102 116A 11A8; # (놕; 놕; 놕; 놕; 놕; ) HANGUL SYLLABLE NWAG
+B196;B196;1102 116A 11A9;B196;1102 116A 11A9; # (놖; 놖; 놖; 놖; 놖; ) HANGUL SYLLABLE NWAGG
+B197;B197;1102 116A 11AA;B197;1102 116A 11AA; # (놗; 놗; 놗; 놗; 놗; ) HANGUL SYLLABLE NWAGS
+B198;B198;1102 116A 11AB;B198;1102 116A 11AB; # (놘; 놘; 놘; 놘; 놘; ) HANGUL SYLLABLE NWAN
+B199;B199;1102 116A 11AC;B199;1102 116A 11AC; # (놙; 놙; 놙; 놙; 놙; ) HANGUL SYLLABLE NWANJ
+B19A;B19A;1102 116A 11AD;B19A;1102 116A 11AD; # (놚; 놚; 놚; 놚; 놚; ) HANGUL SYLLABLE NWANH
+B19B;B19B;1102 116A 11AE;B19B;1102 116A 11AE; # (놛; 놛; 놛; 놛; 놛; ) HANGUL SYLLABLE NWAD
+B19C;B19C;1102 116A 11AF;B19C;1102 116A 11AF; # (놜; 놜; 놜; 놜; 놜; ) HANGUL SYLLABLE NWAL
+B19D;B19D;1102 116A 11B0;B19D;1102 116A 11B0; # (놝; 놝; 놝; 놝; 놝; ) HANGUL SYLLABLE NWALG
+B19E;B19E;1102 116A 11B1;B19E;1102 116A 11B1; # (놞; 놞; 놞; 놞; 놞; ) HANGUL SYLLABLE NWALM
+B19F;B19F;1102 116A 11B2;B19F;1102 116A 11B2; # (놟; 놟; 놟; 놟; 놟; ) HANGUL SYLLABLE NWALB
+B1A0;B1A0;1102 116A 11B3;B1A0;1102 116A 11B3; # (놠; 놠; 놠; 놠; 놠; ) HANGUL SYLLABLE NWALS
+B1A1;B1A1;1102 116A 11B4;B1A1;1102 116A 11B4; # (놡; 놡; 놡; 놡; 놡; ) HANGUL SYLLABLE NWALT
+B1A2;B1A2;1102 116A 11B5;B1A2;1102 116A 11B5; # (놢; 놢; 놢; 놢; 놢; ) HANGUL SYLLABLE NWALP
+B1A3;B1A3;1102 116A 11B6;B1A3;1102 116A 11B6; # (놣; 놣; 놣; 놣; 놣; ) HANGUL SYLLABLE NWALH
+B1A4;B1A4;1102 116A 11B7;B1A4;1102 116A 11B7; # (놤; 놤; 놤; 놤; 놤; ) HANGUL SYLLABLE NWAM
+B1A5;B1A5;1102 116A 11B8;B1A5;1102 116A 11B8; # (놥; 놥; 놥; 놥; 놥; ) HANGUL SYLLABLE NWAB
+B1A6;B1A6;1102 116A 11B9;B1A6;1102 116A 11B9; # (놦; 놦; 놦; 놦; 놦; ) HANGUL SYLLABLE NWABS
+B1A7;B1A7;1102 116A 11BA;B1A7;1102 116A 11BA; # (놧; 놧; 놧; 놧; 놧; ) HANGUL SYLLABLE NWAS
+B1A8;B1A8;1102 116A 11BB;B1A8;1102 116A 11BB; # (놨; 놨; 놨; 놨; 놨; ) HANGUL SYLLABLE NWASS
+B1A9;B1A9;1102 116A 11BC;B1A9;1102 116A 11BC; # (놩; 놩; 놩; 놩; 놩; ) HANGUL SYLLABLE NWANG
+B1AA;B1AA;1102 116A 11BD;B1AA;1102 116A 11BD; # (놪; 놪; 놪; 놪; 놪; ) HANGUL SYLLABLE NWAJ
+B1AB;B1AB;1102 116A 11BE;B1AB;1102 116A 11BE; # (놫; 놫; 놫; 놫; 놫; ) HANGUL SYLLABLE NWAC
+B1AC;B1AC;1102 116A 11BF;B1AC;1102 116A 11BF; # (놬; 놬; 놬; 놬; 놬; ) HANGUL SYLLABLE NWAK
+B1AD;B1AD;1102 116A 11C0;B1AD;1102 116A 11C0; # (놭; 놭; 놭; 놭; 놭; ) HANGUL SYLLABLE NWAT
+B1AE;B1AE;1102 116A 11C1;B1AE;1102 116A 11C1; # (놮; 놮; 놮; 놮; 놮; ) HANGUL SYLLABLE NWAP
+B1AF;B1AF;1102 116A 11C2;B1AF;1102 116A 11C2; # (놯; 놯; 놯; 놯; 놯; ) HANGUL SYLLABLE NWAH
+B1B0;B1B0;1102 116B;B1B0;1102 116B; # (놰; 놰; 놰; 놰; 놰; ) HANGUL SYLLABLE NWAE
+B1B1;B1B1;1102 116B 11A8;B1B1;1102 116B 11A8; # (놱; 놱; 놱; 놱; 놱; ) HANGUL SYLLABLE NWAEG
+B1B2;B1B2;1102 116B 11A9;B1B2;1102 116B 11A9; # (놲; 놲; 놲; 놲; 놲; ) HANGUL SYLLABLE NWAEGG
+B1B3;B1B3;1102 116B 11AA;B1B3;1102 116B 11AA; # (놳; 놳; 놳; 놳; 놳; ) HANGUL SYLLABLE NWAEGS
+B1B4;B1B4;1102 116B 11AB;B1B4;1102 116B 11AB; # (놴; 놴; 놴; 놴; 놴; ) HANGUL SYLLABLE NWAEN
+B1B5;B1B5;1102 116B 11AC;B1B5;1102 116B 11AC; # (놵; 놵; 놵; 놵; 놵; ) HANGUL SYLLABLE NWAENJ
+B1B6;B1B6;1102 116B 11AD;B1B6;1102 116B 11AD; # (놶; 놶; 놶; 놶; 놶; ) HANGUL SYLLABLE NWAENH
+B1B7;B1B7;1102 116B 11AE;B1B7;1102 116B 11AE; # (놷; 놷; 놷; 놷; 놷; ) HANGUL SYLLABLE NWAED
+B1B8;B1B8;1102 116B 11AF;B1B8;1102 116B 11AF; # (놸; 놸; 놸; 놸; 놸; ) HANGUL SYLLABLE NWAEL
+B1B9;B1B9;1102 116B 11B0;B1B9;1102 116B 11B0; # (놹; 놹; 놹; 놹; 놹; ) HANGUL SYLLABLE NWAELG
+B1BA;B1BA;1102 116B 11B1;B1BA;1102 116B 11B1; # (놺; 놺; 놺; 놺; 놺; ) HANGUL SYLLABLE NWAELM
+B1BB;B1BB;1102 116B 11B2;B1BB;1102 116B 11B2; # (놻; 놻; 놻; 놻; 놻; ) HANGUL SYLLABLE NWAELB
+B1BC;B1BC;1102 116B 11B3;B1BC;1102 116B 11B3; # (놼; 놼; 놼; 놼; 놼; ) HANGUL SYLLABLE NWAELS
+B1BD;B1BD;1102 116B 11B4;B1BD;1102 116B 11B4; # (놽; 놽; 놽; 놽; 놽; ) HANGUL SYLLABLE NWAELT
+B1BE;B1BE;1102 116B 11B5;B1BE;1102 116B 11B5; # (놾; 놾; 놾; 놾; 놾; ) HANGUL SYLLABLE NWAELP
+B1BF;B1BF;1102 116B 11B6;B1BF;1102 116B 11B6; # (놿; 놿; 놿; 놿; 놿; ) HANGUL SYLLABLE NWAELH
+B1C0;B1C0;1102 116B 11B7;B1C0;1102 116B 11B7; # (뇀; 뇀; 뇀; 뇀; 뇀; ) HANGUL SYLLABLE NWAEM
+B1C1;B1C1;1102 116B 11B8;B1C1;1102 116B 11B8; # (뇁; 뇁; 뇁; 뇁; 뇁; ) HANGUL SYLLABLE NWAEB
+B1C2;B1C2;1102 116B 11B9;B1C2;1102 116B 11B9; # (뇂; 뇂; 뇂; 뇂; 뇂; ) HANGUL SYLLABLE NWAEBS
+B1C3;B1C3;1102 116B 11BA;B1C3;1102 116B 11BA; # (뇃; 뇃; 뇃; 뇃; 뇃; ) HANGUL SYLLABLE NWAES
+B1C4;B1C4;1102 116B 11BB;B1C4;1102 116B 11BB; # (뇄; 뇄; 뇄; 뇄; 뇄; ) HANGUL SYLLABLE NWAESS
+B1C5;B1C5;1102 116B 11BC;B1C5;1102 116B 11BC; # (뇅; 뇅; 뇅; 뇅; 뇅; ) HANGUL SYLLABLE NWAENG
+B1C6;B1C6;1102 116B 11BD;B1C6;1102 116B 11BD; # (뇆; 뇆; 뇆; 뇆; 뇆; ) HANGUL SYLLABLE NWAEJ
+B1C7;B1C7;1102 116B 11BE;B1C7;1102 116B 11BE; # (뇇; 뇇; 뇇; 뇇; 뇇; ) HANGUL SYLLABLE NWAEC
+B1C8;B1C8;1102 116B 11BF;B1C8;1102 116B 11BF; # (뇈; 뇈; 뇈; 뇈; 뇈; ) HANGUL SYLLABLE NWAEK
+B1C9;B1C9;1102 116B 11C0;B1C9;1102 116B 11C0; # (뇉; 뇉; 뇉; 뇉; 뇉; ) HANGUL SYLLABLE NWAET
+B1CA;B1CA;1102 116B 11C1;B1CA;1102 116B 11C1; # (뇊; 뇊; 뇊; 뇊; 뇊; ) HANGUL SYLLABLE NWAEP
+B1CB;B1CB;1102 116B 11C2;B1CB;1102 116B 11C2; # (뇋; 뇋; 뇋; 뇋; 뇋; ) HANGUL SYLLABLE NWAEH
+B1CC;B1CC;1102 116C;B1CC;1102 116C; # (뇌; 뇌; 뇌; 뇌; 뇌; ) HANGUL SYLLABLE NOE
+B1CD;B1CD;1102 116C 11A8;B1CD;1102 116C 11A8; # (뇍; 뇍; 뇍; 뇍; 뇍; ) HANGUL SYLLABLE NOEG
+B1CE;B1CE;1102 116C 11A9;B1CE;1102 116C 11A9; # (뇎; 뇎; 뇎; 뇎; 뇎; ) HANGUL SYLLABLE NOEGG
+B1CF;B1CF;1102 116C 11AA;B1CF;1102 116C 11AA; # (뇏; 뇏; 뇏; 뇏; 뇏; ) HANGUL SYLLABLE NOEGS
+B1D0;B1D0;1102 116C 11AB;B1D0;1102 116C 11AB; # (뇐; 뇐; 뇐; 뇐; 뇐; ) HANGUL SYLLABLE NOEN
+B1D1;B1D1;1102 116C 11AC;B1D1;1102 116C 11AC; # (뇑; 뇑; 뇑; 뇑; 뇑; ) HANGUL SYLLABLE NOENJ
+B1D2;B1D2;1102 116C 11AD;B1D2;1102 116C 11AD; # (뇒; 뇒; 뇒; 뇒; 뇒; ) HANGUL SYLLABLE NOENH
+B1D3;B1D3;1102 116C 11AE;B1D3;1102 116C 11AE; # (뇓; 뇓; 뇓; 뇓; 뇓; ) HANGUL SYLLABLE NOED
+B1D4;B1D4;1102 116C 11AF;B1D4;1102 116C 11AF; # (뇔; 뇔; 뇔; 뇔; 뇔; ) HANGUL SYLLABLE NOEL
+B1D5;B1D5;1102 116C 11B0;B1D5;1102 116C 11B0; # (뇕; 뇕; 뇕; 뇕; 뇕; ) HANGUL SYLLABLE NOELG
+B1D6;B1D6;1102 116C 11B1;B1D6;1102 116C 11B1; # (뇖; 뇖; 뇖; 뇖; 뇖; ) HANGUL SYLLABLE NOELM
+B1D7;B1D7;1102 116C 11B2;B1D7;1102 116C 11B2; # (뇗; 뇗; 뇗; 뇗; 뇗; ) HANGUL SYLLABLE NOELB
+B1D8;B1D8;1102 116C 11B3;B1D8;1102 116C 11B3; # (뇘; 뇘; 뇘; 뇘; 뇘; ) HANGUL SYLLABLE NOELS
+B1D9;B1D9;1102 116C 11B4;B1D9;1102 116C 11B4; # (뇙; 뇙; 뇙; 뇙; 뇙; ) HANGUL SYLLABLE NOELT
+B1DA;B1DA;1102 116C 11B5;B1DA;1102 116C 11B5; # (뇚; 뇚; 뇚; 뇚; 뇚; ) HANGUL SYLLABLE NOELP
+B1DB;B1DB;1102 116C 11B6;B1DB;1102 116C 11B6; # (뇛; 뇛; 뇛; 뇛; 뇛; ) HANGUL SYLLABLE NOELH
+B1DC;B1DC;1102 116C 11B7;B1DC;1102 116C 11B7; # (뇜; 뇜; 뇜; 뇜; 뇜; ) HANGUL SYLLABLE NOEM
+B1DD;B1DD;1102 116C 11B8;B1DD;1102 116C 11B8; # (뇝; 뇝; 뇝; 뇝; 뇝; ) HANGUL SYLLABLE NOEB
+B1DE;B1DE;1102 116C 11B9;B1DE;1102 116C 11B9; # (뇞; 뇞; 뇞; 뇞; 뇞; ) HANGUL SYLLABLE NOEBS
+B1DF;B1DF;1102 116C 11BA;B1DF;1102 116C 11BA; # (뇟; 뇟; 뇟; 뇟; 뇟; ) HANGUL SYLLABLE NOES
+B1E0;B1E0;1102 116C 11BB;B1E0;1102 116C 11BB; # (뇠; 뇠; 뇠; 뇠; 뇠; ) HANGUL SYLLABLE NOESS
+B1E1;B1E1;1102 116C 11BC;B1E1;1102 116C 11BC; # (뇡; 뇡; 뇡; 뇡; 뇡; ) HANGUL SYLLABLE NOENG
+B1E2;B1E2;1102 116C 11BD;B1E2;1102 116C 11BD; # (뇢; 뇢; 뇢; 뇢; 뇢; ) HANGUL SYLLABLE NOEJ
+B1E3;B1E3;1102 116C 11BE;B1E3;1102 116C 11BE; # (뇣; 뇣; 뇣; 뇣; 뇣; ) HANGUL SYLLABLE NOEC
+B1E4;B1E4;1102 116C 11BF;B1E4;1102 116C 11BF; # (뇤; 뇤; 뇤; 뇤; 뇤; ) HANGUL SYLLABLE NOEK
+B1E5;B1E5;1102 116C 11C0;B1E5;1102 116C 11C0; # (뇥; 뇥; 뇥; 뇥; 뇥; ) HANGUL SYLLABLE NOET
+B1E6;B1E6;1102 116C 11C1;B1E6;1102 116C 11C1; # (뇦; 뇦; 뇦; 뇦; 뇦; ) HANGUL SYLLABLE NOEP
+B1E7;B1E7;1102 116C 11C2;B1E7;1102 116C 11C2; # (뇧; 뇧; 뇧; 뇧; 뇧; ) HANGUL SYLLABLE NOEH
+B1E8;B1E8;1102 116D;B1E8;1102 116D; # (뇨; 뇨; 뇨; 뇨; 뇨; ) HANGUL SYLLABLE NYO
+B1E9;B1E9;1102 116D 11A8;B1E9;1102 116D 11A8; # (뇩; 뇩; 뇩; 뇩; 뇩; ) HANGUL SYLLABLE NYOG
+B1EA;B1EA;1102 116D 11A9;B1EA;1102 116D 11A9; # (뇪; 뇪; 뇪; 뇪; 뇪; ) HANGUL SYLLABLE NYOGG
+B1EB;B1EB;1102 116D 11AA;B1EB;1102 116D 11AA; # (뇫; 뇫; 뇫; 뇫; 뇫; ) HANGUL SYLLABLE NYOGS
+B1EC;B1EC;1102 116D 11AB;B1EC;1102 116D 11AB; # (뇬; 뇬; 뇬; 뇬; 뇬; ) HANGUL SYLLABLE NYON
+B1ED;B1ED;1102 116D 11AC;B1ED;1102 116D 11AC; # (뇭; 뇭; 뇭; 뇭; 뇭; ) HANGUL SYLLABLE NYONJ
+B1EE;B1EE;1102 116D 11AD;B1EE;1102 116D 11AD; # (뇮; 뇮; 뇮; 뇮; 뇮; ) HANGUL SYLLABLE NYONH
+B1EF;B1EF;1102 116D 11AE;B1EF;1102 116D 11AE; # (뇯; 뇯; 뇯; 뇯; 뇯; ) HANGUL SYLLABLE NYOD
+B1F0;B1F0;1102 116D 11AF;B1F0;1102 116D 11AF; # (뇰; 뇰; 뇰; 뇰; 뇰; ) HANGUL SYLLABLE NYOL
+B1F1;B1F1;1102 116D 11B0;B1F1;1102 116D 11B0; # (뇱; 뇱; 뇱; 뇱; 뇱; ) HANGUL SYLLABLE NYOLG
+B1F2;B1F2;1102 116D 11B1;B1F2;1102 116D 11B1; # (뇲; 뇲; 뇲; 뇲; 뇲; ) HANGUL SYLLABLE NYOLM
+B1F3;B1F3;1102 116D 11B2;B1F3;1102 116D 11B2; # (뇳; 뇳; 뇳; 뇳; 뇳; ) HANGUL SYLLABLE NYOLB
+B1F4;B1F4;1102 116D 11B3;B1F4;1102 116D 11B3; # (뇴; 뇴; 뇴; 뇴; 뇴; ) HANGUL SYLLABLE NYOLS
+B1F5;B1F5;1102 116D 11B4;B1F5;1102 116D 11B4; # (뇵; 뇵; 뇵; 뇵; 뇵; ) HANGUL SYLLABLE NYOLT
+B1F6;B1F6;1102 116D 11B5;B1F6;1102 116D 11B5; # (뇶; 뇶; 뇶; 뇶; 뇶; ) HANGUL SYLLABLE NYOLP
+B1F7;B1F7;1102 116D 11B6;B1F7;1102 116D 11B6; # (뇷; 뇷; 뇷; 뇷; 뇷; ) HANGUL SYLLABLE NYOLH
+B1F8;B1F8;1102 116D 11B7;B1F8;1102 116D 11B7; # (뇸; 뇸; 뇸; 뇸; 뇸; ) HANGUL SYLLABLE NYOM
+B1F9;B1F9;1102 116D 11B8;B1F9;1102 116D 11B8; # (뇹; 뇹; 뇹; 뇹; 뇹; ) HANGUL SYLLABLE NYOB
+B1FA;B1FA;1102 116D 11B9;B1FA;1102 116D 11B9; # (뇺; 뇺; 뇺; 뇺; 뇺; ) HANGUL SYLLABLE NYOBS
+B1FB;B1FB;1102 116D 11BA;B1FB;1102 116D 11BA; # (뇻; 뇻; 뇻; 뇻; 뇻; ) HANGUL SYLLABLE NYOS
+B1FC;B1FC;1102 116D 11BB;B1FC;1102 116D 11BB; # (뇼; 뇼; 뇼; 뇼; 뇼; ) HANGUL SYLLABLE NYOSS
+B1FD;B1FD;1102 116D 11BC;B1FD;1102 116D 11BC; # (뇽; 뇽; 뇽; 뇽; 뇽; ) HANGUL SYLLABLE NYONG
+B1FE;B1FE;1102 116D 11BD;B1FE;1102 116D 11BD; # (뇾; 뇾; 뇾; 뇾; 뇾; ) HANGUL SYLLABLE NYOJ
+B1FF;B1FF;1102 116D 11BE;B1FF;1102 116D 11BE; # (뇿; 뇿; 뇿; 뇿; 뇿; ) HANGUL SYLLABLE NYOC
+B200;B200;1102 116D 11BF;B200;1102 116D 11BF; # (눀; 눀; 눀; 눀; 눀; ) HANGUL SYLLABLE NYOK
+B201;B201;1102 116D 11C0;B201;1102 116D 11C0; # (눁; 눁; 눁; 눁; 눁; ) HANGUL SYLLABLE NYOT
+B202;B202;1102 116D 11C1;B202;1102 116D 11C1; # (눂; 눂; 눂; 눂; 눂; ) HANGUL SYLLABLE NYOP
+B203;B203;1102 116D 11C2;B203;1102 116D 11C2; # (눃; 눃; 눃; 눃; 눃; ) HANGUL SYLLABLE NYOH
+B204;B204;1102 116E;B204;1102 116E; # (누; 누; 누; 누; 누; ) HANGUL SYLLABLE NU
+B205;B205;1102 116E 11A8;B205;1102 116E 11A8; # (눅; 눅; 눅; 눅; 눅; ) HANGUL SYLLABLE NUG
+B206;B206;1102 116E 11A9;B206;1102 116E 11A9; # (눆; 눆; 눆; 눆; 눆; ) HANGUL SYLLABLE NUGG
+B207;B207;1102 116E 11AA;B207;1102 116E 11AA; # (눇; 눇; 눇; 눇; 눇; ) HANGUL SYLLABLE NUGS
+B208;B208;1102 116E 11AB;B208;1102 116E 11AB; # (눈; 눈; 눈; 눈; 눈; ) HANGUL SYLLABLE NUN
+B209;B209;1102 116E 11AC;B209;1102 116E 11AC; # (눉; 눉; 눉; 눉; 눉; ) HANGUL SYLLABLE NUNJ
+B20A;B20A;1102 116E 11AD;B20A;1102 116E 11AD; # (눊; 눊; 눊; 눊; 눊; ) HANGUL SYLLABLE NUNH
+B20B;B20B;1102 116E 11AE;B20B;1102 116E 11AE; # (눋; 눋; 눋; 눋; 눋; ) HANGUL SYLLABLE NUD
+B20C;B20C;1102 116E 11AF;B20C;1102 116E 11AF; # (눌; 눌; 눌; 눌; 눌; ) HANGUL SYLLABLE NUL
+B20D;B20D;1102 116E 11B0;B20D;1102 116E 11B0; # (눍; 눍; 눍; 눍; 눍; ) HANGUL SYLLABLE NULG
+B20E;B20E;1102 116E 11B1;B20E;1102 116E 11B1; # (눎; 눎; 눎; 눎; 눎; ) HANGUL SYLLABLE NULM
+B20F;B20F;1102 116E 11B2;B20F;1102 116E 11B2; # (눏; 눏; 눏; 눏; 눏; ) HANGUL SYLLABLE NULB
+B210;B210;1102 116E 11B3;B210;1102 116E 11B3; # (눐; 눐; 눐; 눐; 눐; ) HANGUL SYLLABLE NULS
+B211;B211;1102 116E 11B4;B211;1102 116E 11B4; # (눑; 눑; 눑; 눑; 눑; ) HANGUL SYLLABLE NULT
+B212;B212;1102 116E 11B5;B212;1102 116E 11B5; # (눒; 눒; 눒; 눒; 눒; ) HANGUL SYLLABLE NULP
+B213;B213;1102 116E 11B6;B213;1102 116E 11B6; # (눓; 눓; 눓; 눓; 눓; ) HANGUL SYLLABLE NULH
+B214;B214;1102 116E 11B7;B214;1102 116E 11B7; # (눔; 눔; 눔; 눔; 눔; ) HANGUL SYLLABLE NUM
+B215;B215;1102 116E 11B8;B215;1102 116E 11B8; # (눕; 눕; 눕; 눕; 눕; ) HANGUL SYLLABLE NUB
+B216;B216;1102 116E 11B9;B216;1102 116E 11B9; # (눖; 눖; 눖; 눖; 눖; ) HANGUL SYLLABLE NUBS
+B217;B217;1102 116E 11BA;B217;1102 116E 11BA; # (눗; 눗; 눗; 눗; 눗; ) HANGUL SYLLABLE NUS
+B218;B218;1102 116E 11BB;B218;1102 116E 11BB; # (눘; 눘; 눘; 눘; 눘; ) HANGUL SYLLABLE NUSS
+B219;B219;1102 116E 11BC;B219;1102 116E 11BC; # (눙; 눙; 눙; 눙; 눙; ) HANGUL SYLLABLE NUNG
+B21A;B21A;1102 116E 11BD;B21A;1102 116E 11BD; # (눚; 눚; 눚; 눚; 눚; ) HANGUL SYLLABLE NUJ
+B21B;B21B;1102 116E 11BE;B21B;1102 116E 11BE; # (눛; 눛; 눛; 눛; 눛; ) HANGUL SYLLABLE NUC
+B21C;B21C;1102 116E 11BF;B21C;1102 116E 11BF; # (눜; 눜; 눜; 눜; 눜; ) HANGUL SYLLABLE NUK
+B21D;B21D;1102 116E 11C0;B21D;1102 116E 11C0; # (눝; 눝; 눝; 눝; 눝; ) HANGUL SYLLABLE NUT
+B21E;B21E;1102 116E 11C1;B21E;1102 116E 11C1; # (눞; 눞; 눞; 눞; 눞; ) HANGUL SYLLABLE NUP
+B21F;B21F;1102 116E 11C2;B21F;1102 116E 11C2; # (눟; 눟; 눟; 눟; 눟; ) HANGUL SYLLABLE NUH
+B220;B220;1102 116F;B220;1102 116F; # (눠; 눠; 눠; 눠; 눠; ) HANGUL SYLLABLE NWEO
+B221;B221;1102 116F 11A8;B221;1102 116F 11A8; # (눡; 눡; 눡; 눡; 눡; ) HANGUL SYLLABLE NWEOG
+B222;B222;1102 116F 11A9;B222;1102 116F 11A9; # (눢; 눢; 눢; 눢; 눢; ) HANGUL SYLLABLE NWEOGG
+B223;B223;1102 116F 11AA;B223;1102 116F 11AA; # (눣; 눣; 눣; 눣; 눣; ) HANGUL SYLLABLE NWEOGS
+B224;B224;1102 116F 11AB;B224;1102 116F 11AB; # (눤; 눤; 눤; 눤; 눤; ) HANGUL SYLLABLE NWEON
+B225;B225;1102 116F 11AC;B225;1102 116F 11AC; # (눥; 눥; 눥; 눥; 눥; ) HANGUL SYLLABLE NWEONJ
+B226;B226;1102 116F 11AD;B226;1102 116F 11AD; # (눦; 눦; 눦; 눦; 눦; ) HANGUL SYLLABLE NWEONH
+B227;B227;1102 116F 11AE;B227;1102 116F 11AE; # (눧; 눧; 눧; 눧; 눧; ) HANGUL SYLLABLE NWEOD
+B228;B228;1102 116F 11AF;B228;1102 116F 11AF; # (눨; 눨; 눨; 눨; 눨; ) HANGUL SYLLABLE NWEOL
+B229;B229;1102 116F 11B0;B229;1102 116F 11B0; # (눩; 눩; 눩; 눩; 눩; ) HANGUL SYLLABLE NWEOLG
+B22A;B22A;1102 116F 11B1;B22A;1102 116F 11B1; # (눪; 눪; 눪; 눪; 눪; ) HANGUL SYLLABLE NWEOLM
+B22B;B22B;1102 116F 11B2;B22B;1102 116F 11B2; # (눫; 눫; 눫; 눫; 눫; ) HANGUL SYLLABLE NWEOLB
+B22C;B22C;1102 116F 11B3;B22C;1102 116F 11B3; # (눬; 눬; 눬; 눬; 눬; ) HANGUL SYLLABLE NWEOLS
+B22D;B22D;1102 116F 11B4;B22D;1102 116F 11B4; # (눭; 눭; 눭; 눭; 눭; ) HANGUL SYLLABLE NWEOLT
+B22E;B22E;1102 116F 11B5;B22E;1102 116F 11B5; # (눮; 눮; 눮; 눮; 눮; ) HANGUL SYLLABLE NWEOLP
+B22F;B22F;1102 116F 11B6;B22F;1102 116F 11B6; # (눯; 눯; 눯; 눯; 눯; ) HANGUL SYLLABLE NWEOLH
+B230;B230;1102 116F 11B7;B230;1102 116F 11B7; # (눰; 눰; 눰; 눰; 눰; ) HANGUL SYLLABLE NWEOM
+B231;B231;1102 116F 11B8;B231;1102 116F 11B8; # (눱; 눱; 눱; 눱; 눱; ) HANGUL SYLLABLE NWEOB
+B232;B232;1102 116F 11B9;B232;1102 116F 11B9; # (눲; 눲; 눲; 눲; 눲; ) HANGUL SYLLABLE NWEOBS
+B233;B233;1102 116F 11BA;B233;1102 116F 11BA; # (눳; 눳; 눳; 눳; 눳; ) HANGUL SYLLABLE NWEOS
+B234;B234;1102 116F 11BB;B234;1102 116F 11BB; # (눴; 눴; 눴; 눴; 눴; ) HANGUL SYLLABLE NWEOSS
+B235;B235;1102 116F 11BC;B235;1102 116F 11BC; # (눵; 눵; 눵; 눵; 눵; ) HANGUL SYLLABLE NWEONG
+B236;B236;1102 116F 11BD;B236;1102 116F 11BD; # (눶; 눶; 눶; 눶; 눶; ) HANGUL SYLLABLE NWEOJ
+B237;B237;1102 116F 11BE;B237;1102 116F 11BE; # (눷; 눷; 눷; 눷; 눷; ) HANGUL SYLLABLE NWEOC
+B238;B238;1102 116F 11BF;B238;1102 116F 11BF; # (눸; 눸; 눸; 눸; 눸; ) HANGUL SYLLABLE NWEOK
+B239;B239;1102 116F 11C0;B239;1102 116F 11C0; # (눹; 눹; 눹; 눹; 눹; ) HANGUL SYLLABLE NWEOT
+B23A;B23A;1102 116F 11C1;B23A;1102 116F 11C1; # (눺; 눺; 눺; 눺; 눺; ) HANGUL SYLLABLE NWEOP
+B23B;B23B;1102 116F 11C2;B23B;1102 116F 11C2; # (눻; 눻; 눻; 눻; 눻; ) HANGUL SYLLABLE NWEOH
+B23C;B23C;1102 1170;B23C;1102 1170; # (눼; 눼; 눼; 눼; 눼; ) HANGUL SYLLABLE NWE
+B23D;B23D;1102 1170 11A8;B23D;1102 1170 11A8; # (눽; 눽; 눽; 눽; 눽; ) HANGUL SYLLABLE NWEG
+B23E;B23E;1102 1170 11A9;B23E;1102 1170 11A9; # (눾; 눾; 눾; 눾; 눾; ) HANGUL SYLLABLE NWEGG
+B23F;B23F;1102 1170 11AA;B23F;1102 1170 11AA; # (눿; 눿; 눿; 눿; 눿; ) HANGUL SYLLABLE NWEGS
+B240;B240;1102 1170 11AB;B240;1102 1170 11AB; # (뉀; 뉀; 뉀; 뉀; 뉀; ) HANGUL SYLLABLE NWEN
+B241;B241;1102 1170 11AC;B241;1102 1170 11AC; # (뉁; 뉁; 뉁; 뉁; 뉁; ) HANGUL SYLLABLE NWENJ
+B242;B242;1102 1170 11AD;B242;1102 1170 11AD; # (뉂; 뉂; 뉂; 뉂; 뉂; ) HANGUL SYLLABLE NWENH
+B243;B243;1102 1170 11AE;B243;1102 1170 11AE; # (뉃; 뉃; 뉃; 뉃; 뉃; ) HANGUL SYLLABLE NWED
+B244;B244;1102 1170 11AF;B244;1102 1170 11AF; # (뉄; 뉄; 뉄; 뉄; 뉄; ) HANGUL SYLLABLE NWEL
+B245;B245;1102 1170 11B0;B245;1102 1170 11B0; # (뉅; 뉅; 뉅; 뉅; 뉅; ) HANGUL SYLLABLE NWELG
+B246;B246;1102 1170 11B1;B246;1102 1170 11B1; # (뉆; 뉆; 뉆; 뉆; 뉆; ) HANGUL SYLLABLE NWELM
+B247;B247;1102 1170 11B2;B247;1102 1170 11B2; # (뉇; 뉇; 뉇; 뉇; 뉇; ) HANGUL SYLLABLE NWELB
+B248;B248;1102 1170 11B3;B248;1102 1170 11B3; # (뉈; 뉈; 뉈; 뉈; 뉈; ) HANGUL SYLLABLE NWELS
+B249;B249;1102 1170 11B4;B249;1102 1170 11B4; # (뉉; 뉉; 뉉; 뉉; 뉉; ) HANGUL SYLLABLE NWELT
+B24A;B24A;1102 1170 11B5;B24A;1102 1170 11B5; # (뉊; 뉊; 뉊; 뉊; 뉊; ) HANGUL SYLLABLE NWELP
+B24B;B24B;1102 1170 11B6;B24B;1102 1170 11B6; # (뉋; 뉋; 뉋; 뉋; 뉋; ) HANGUL SYLLABLE NWELH
+B24C;B24C;1102 1170 11B7;B24C;1102 1170 11B7; # (뉌; 뉌; 뉌; 뉌; 뉌; ) HANGUL SYLLABLE NWEM
+B24D;B24D;1102 1170 11B8;B24D;1102 1170 11B8; # (뉍; 뉍; 뉍; 뉍; 뉍; ) HANGUL SYLLABLE NWEB
+B24E;B24E;1102 1170 11B9;B24E;1102 1170 11B9; # (뉎; 뉎; 뉎; 뉎; 뉎; ) HANGUL SYLLABLE NWEBS
+B24F;B24F;1102 1170 11BA;B24F;1102 1170 11BA; # (뉏; 뉏; 뉏; 뉏; 뉏; ) HANGUL SYLLABLE NWES
+B250;B250;1102 1170 11BB;B250;1102 1170 11BB; # (뉐; 뉐; 뉐; 뉐; 뉐; ) HANGUL SYLLABLE NWESS
+B251;B251;1102 1170 11BC;B251;1102 1170 11BC; # (뉑; 뉑; 뉑; 뉑; 뉑; ) HANGUL SYLLABLE NWENG
+B252;B252;1102 1170 11BD;B252;1102 1170 11BD; # (뉒; 뉒; 뉒; 뉒; 뉒; ) HANGUL SYLLABLE NWEJ
+B253;B253;1102 1170 11BE;B253;1102 1170 11BE; # (뉓; 뉓; 뉓; 뉓; 뉓; ) HANGUL SYLLABLE NWEC
+B254;B254;1102 1170 11BF;B254;1102 1170 11BF; # (뉔; 뉔; 뉔; 뉔; 뉔; ) HANGUL SYLLABLE NWEK
+B255;B255;1102 1170 11C0;B255;1102 1170 11C0; # (뉕; 뉕; 뉕; 뉕; 뉕; ) HANGUL SYLLABLE NWET
+B256;B256;1102 1170 11C1;B256;1102 1170 11C1; # (뉖; 뉖; 뉖; 뉖; 뉖; ) HANGUL SYLLABLE NWEP
+B257;B257;1102 1170 11C2;B257;1102 1170 11C2; # (뉗; 뉗; 뉗; 뉗; 뉗; ) HANGUL SYLLABLE NWEH
+B258;B258;1102 1171;B258;1102 1171; # (뉘; 뉘; 뉘; 뉘; 뉘; ) HANGUL SYLLABLE NWI
+B259;B259;1102 1171 11A8;B259;1102 1171 11A8; # (뉙; 뉙; 뉙; 뉙; 뉙; ) HANGUL SYLLABLE NWIG
+B25A;B25A;1102 1171 11A9;B25A;1102 1171 11A9; # (뉚; 뉚; 뉚; 뉚; 뉚; ) HANGUL SYLLABLE NWIGG
+B25B;B25B;1102 1171 11AA;B25B;1102 1171 11AA; # (뉛; 뉛; 뉛; 뉛; 뉛; ) HANGUL SYLLABLE NWIGS
+B25C;B25C;1102 1171 11AB;B25C;1102 1171 11AB; # (뉜; 뉜; 뉜; 뉜; 뉜; ) HANGUL SYLLABLE NWIN
+B25D;B25D;1102 1171 11AC;B25D;1102 1171 11AC; # (뉝; 뉝; 뉝; 뉝; 뉝; ) HANGUL SYLLABLE NWINJ
+B25E;B25E;1102 1171 11AD;B25E;1102 1171 11AD; # (뉞; 뉞; 뉞; 뉞; 뉞; ) HANGUL SYLLABLE NWINH
+B25F;B25F;1102 1171 11AE;B25F;1102 1171 11AE; # (뉟; 뉟; 뉟; 뉟; 뉟; ) HANGUL SYLLABLE NWID
+B260;B260;1102 1171 11AF;B260;1102 1171 11AF; # (뉠; 뉠; 뉠; 뉠; 뉠; ) HANGUL SYLLABLE NWIL
+B261;B261;1102 1171 11B0;B261;1102 1171 11B0; # (뉡; 뉡; 뉡; 뉡; 뉡; ) HANGUL SYLLABLE NWILG
+B262;B262;1102 1171 11B1;B262;1102 1171 11B1; # (뉢; 뉢; 뉢; 뉢; 뉢; ) HANGUL SYLLABLE NWILM
+B263;B263;1102 1171 11B2;B263;1102 1171 11B2; # (뉣; 뉣; 뉣; 뉣; 뉣; ) HANGUL SYLLABLE NWILB
+B264;B264;1102 1171 11B3;B264;1102 1171 11B3; # (뉤; 뉤; 뉤; 뉤; 뉤; ) HANGUL SYLLABLE NWILS
+B265;B265;1102 1171 11B4;B265;1102 1171 11B4; # (뉥; 뉥; 뉥; 뉥; 뉥; ) HANGUL SYLLABLE NWILT
+B266;B266;1102 1171 11B5;B266;1102 1171 11B5; # (뉦; 뉦; 뉦; 뉦; 뉦; ) HANGUL SYLLABLE NWILP
+B267;B267;1102 1171 11B6;B267;1102 1171 11B6; # (뉧; 뉧; 뉧; 뉧; 뉧; ) HANGUL SYLLABLE NWILH
+B268;B268;1102 1171 11B7;B268;1102 1171 11B7; # (뉨; 뉨; 뉨; 뉨; 뉨; ) HANGUL SYLLABLE NWIM
+B269;B269;1102 1171 11B8;B269;1102 1171 11B8; # (뉩; 뉩; 뉩; 뉩; 뉩; ) HANGUL SYLLABLE NWIB
+B26A;B26A;1102 1171 11B9;B26A;1102 1171 11B9; # (뉪; 뉪; 뉪; 뉪; 뉪; ) HANGUL SYLLABLE NWIBS
+B26B;B26B;1102 1171 11BA;B26B;1102 1171 11BA; # (뉫; 뉫; 뉫; 뉫; 뉫; ) HANGUL SYLLABLE NWIS
+B26C;B26C;1102 1171 11BB;B26C;1102 1171 11BB; # (뉬; 뉬; 뉬; 뉬; 뉬; ) HANGUL SYLLABLE NWISS
+B26D;B26D;1102 1171 11BC;B26D;1102 1171 11BC; # (뉭; 뉭; 뉭; 뉭; 뉭; ) HANGUL SYLLABLE NWING
+B26E;B26E;1102 1171 11BD;B26E;1102 1171 11BD; # (뉮; 뉮; 뉮; 뉮; 뉮; ) HANGUL SYLLABLE NWIJ
+B26F;B26F;1102 1171 11BE;B26F;1102 1171 11BE; # (뉯; 뉯; 뉯; 뉯; 뉯; ) HANGUL SYLLABLE NWIC
+B270;B270;1102 1171 11BF;B270;1102 1171 11BF; # (뉰; 뉰; 뉰; 뉰; 뉰; ) HANGUL SYLLABLE NWIK
+B271;B271;1102 1171 11C0;B271;1102 1171 11C0; # (뉱; 뉱; 뉱; 뉱; 뉱; ) HANGUL SYLLABLE NWIT
+B272;B272;1102 1171 11C1;B272;1102 1171 11C1; # (뉲; 뉲; 뉲; 뉲; 뉲; ) HANGUL SYLLABLE NWIP
+B273;B273;1102 1171 11C2;B273;1102 1171 11C2; # (뉳; 뉳; 뉳; 뉳; 뉳; ) HANGUL SYLLABLE NWIH
+B274;B274;1102 1172;B274;1102 1172; # (뉴; 뉴; 뉴; 뉴; 뉴; ) HANGUL SYLLABLE NYU
+B275;B275;1102 1172 11A8;B275;1102 1172 11A8; # (뉵; 뉵; 뉵; 뉵; 뉵; ) HANGUL SYLLABLE NYUG
+B276;B276;1102 1172 11A9;B276;1102 1172 11A9; # (뉶; 뉶; 뉶; 뉶; 뉶; ) HANGUL SYLLABLE NYUGG
+B277;B277;1102 1172 11AA;B277;1102 1172 11AA; # (뉷; 뉷; 뉷; 뉷; 뉷; ) HANGUL SYLLABLE NYUGS
+B278;B278;1102 1172 11AB;B278;1102 1172 11AB; # (뉸; 뉸; 뉸; 뉸; 뉸; ) HANGUL SYLLABLE NYUN
+B279;B279;1102 1172 11AC;B279;1102 1172 11AC; # (뉹; 뉹; 뉹; 뉹; 뉹; ) HANGUL SYLLABLE NYUNJ
+B27A;B27A;1102 1172 11AD;B27A;1102 1172 11AD; # (뉺; 뉺; 뉺; 뉺; 뉺; ) HANGUL SYLLABLE NYUNH
+B27B;B27B;1102 1172 11AE;B27B;1102 1172 11AE; # (뉻; 뉻; 뉻; 뉻; 뉻; ) HANGUL SYLLABLE NYUD
+B27C;B27C;1102 1172 11AF;B27C;1102 1172 11AF; # (뉼; 뉼; 뉼; 뉼; 뉼; ) HANGUL SYLLABLE NYUL
+B27D;B27D;1102 1172 11B0;B27D;1102 1172 11B0; # (뉽; 뉽; 뉽; 뉽; 뉽; ) HANGUL SYLLABLE NYULG
+B27E;B27E;1102 1172 11B1;B27E;1102 1172 11B1; # (뉾; 뉾; 뉾; 뉾; 뉾; ) HANGUL SYLLABLE NYULM
+B27F;B27F;1102 1172 11B2;B27F;1102 1172 11B2; # (뉿; 뉿; 뉿; 뉿; 뉿; ) HANGUL SYLLABLE NYULB
+B280;B280;1102 1172 11B3;B280;1102 1172 11B3; # (늀; 늀; 늀; 늀; 늀; ) HANGUL SYLLABLE NYULS
+B281;B281;1102 1172 11B4;B281;1102 1172 11B4; # (늁; 늁; 늁; 늁; 늁; ) HANGUL SYLLABLE NYULT
+B282;B282;1102 1172 11B5;B282;1102 1172 11B5; # (늂; 늂; 늂; 늂; 늂; ) HANGUL SYLLABLE NYULP
+B283;B283;1102 1172 11B6;B283;1102 1172 11B6; # (늃; 늃; 늃; 늃; 늃; ) HANGUL SYLLABLE NYULH
+B284;B284;1102 1172 11B7;B284;1102 1172 11B7; # (늄; 늄; 늄; 늄; 늄; ) HANGUL SYLLABLE NYUM
+B285;B285;1102 1172 11B8;B285;1102 1172 11B8; # (늅; 늅; 늅; 늅; 늅; ) HANGUL SYLLABLE NYUB
+B286;B286;1102 1172 11B9;B286;1102 1172 11B9; # (늆; 늆; 늆; 늆; 늆; ) HANGUL SYLLABLE NYUBS
+B287;B287;1102 1172 11BA;B287;1102 1172 11BA; # (늇; 늇; 늇; 늇; 늇; ) HANGUL SYLLABLE NYUS
+B288;B288;1102 1172 11BB;B288;1102 1172 11BB; # (늈; 늈; 늈; 늈; 늈; ) HANGUL SYLLABLE NYUSS
+B289;B289;1102 1172 11BC;B289;1102 1172 11BC; # (늉; 늉; 늉; 늉; 늉; ) HANGUL SYLLABLE NYUNG
+B28A;B28A;1102 1172 11BD;B28A;1102 1172 11BD; # (늊; 늊; 늊; 늊; 늊; ) HANGUL SYLLABLE NYUJ
+B28B;B28B;1102 1172 11BE;B28B;1102 1172 11BE; # (늋; 늋; 늋; 늋; 늋; ) HANGUL SYLLABLE NYUC
+B28C;B28C;1102 1172 11BF;B28C;1102 1172 11BF; # (늌; 늌; 늌; 늌; 늌; ) HANGUL SYLLABLE NYUK
+B28D;B28D;1102 1172 11C0;B28D;1102 1172 11C0; # (늍; 늍; 늍; 늍; 늍; ) HANGUL SYLLABLE NYUT
+B28E;B28E;1102 1172 11C1;B28E;1102 1172 11C1; # (늎; 늎; 늎; 늎; 늎; ) HANGUL SYLLABLE NYUP
+B28F;B28F;1102 1172 11C2;B28F;1102 1172 11C2; # (늏; 늏; 늏; 늏; 늏; ) HANGUL SYLLABLE NYUH
+B290;B290;1102 1173;B290;1102 1173; # (느; 느; 느; 느; 느; ) HANGUL SYLLABLE NEU
+B291;B291;1102 1173 11A8;B291;1102 1173 11A8; # (늑; 늑; 늑; 늑; 늑; ) HANGUL SYLLABLE NEUG
+B292;B292;1102 1173 11A9;B292;1102 1173 11A9; # (늒; 늒; 늒; 늒; 늒; ) HANGUL SYLLABLE NEUGG
+B293;B293;1102 1173 11AA;B293;1102 1173 11AA; # (늓; 늓; 늓; 늓; 늓; ) HANGUL SYLLABLE NEUGS
+B294;B294;1102 1173 11AB;B294;1102 1173 11AB; # (는; 는; 는; 는; 는; ) HANGUL SYLLABLE NEUN
+B295;B295;1102 1173 11AC;B295;1102 1173 11AC; # (늕; 늕; 늕; 늕; 늕; ) HANGUL SYLLABLE NEUNJ
+B296;B296;1102 1173 11AD;B296;1102 1173 11AD; # (늖; 늖; 늖; 늖; 늖; ) HANGUL SYLLABLE NEUNH
+B297;B297;1102 1173 11AE;B297;1102 1173 11AE; # (늗; 늗; 늗; 늗; 늗; ) HANGUL SYLLABLE NEUD
+B298;B298;1102 1173 11AF;B298;1102 1173 11AF; # (늘; 늘; 늘; 늘; 늘; ) HANGUL SYLLABLE NEUL
+B299;B299;1102 1173 11B0;B299;1102 1173 11B0; # (늙; 늙; 늙; 늙; 늙; ) HANGUL SYLLABLE NEULG
+B29A;B29A;1102 1173 11B1;B29A;1102 1173 11B1; # (늚; 늚; 늚; 늚; 늚; ) HANGUL SYLLABLE NEULM
+B29B;B29B;1102 1173 11B2;B29B;1102 1173 11B2; # (늛; 늛; 늛; 늛; 늛; ) HANGUL SYLLABLE NEULB
+B29C;B29C;1102 1173 11B3;B29C;1102 1173 11B3; # (늜; 늜; 늜; 늜; 늜; ) HANGUL SYLLABLE NEULS
+B29D;B29D;1102 1173 11B4;B29D;1102 1173 11B4; # (늝; 늝; 늝; 늝; 늝; ) HANGUL SYLLABLE NEULT
+B29E;B29E;1102 1173 11B5;B29E;1102 1173 11B5; # (늞; 늞; 늞; 늞; 늞; ) HANGUL SYLLABLE NEULP
+B29F;B29F;1102 1173 11B6;B29F;1102 1173 11B6; # (늟; 늟; 늟; 늟; 늟; ) HANGUL SYLLABLE NEULH
+B2A0;B2A0;1102 1173 11B7;B2A0;1102 1173 11B7; # (늠; 늠; 늠; 늠; 늠; ) HANGUL SYLLABLE NEUM
+B2A1;B2A1;1102 1173 11B8;B2A1;1102 1173 11B8; # (늡; 늡; 늡; 늡; 늡; ) HANGUL SYLLABLE NEUB
+B2A2;B2A2;1102 1173 11B9;B2A2;1102 1173 11B9; # (늢; 늢; 늢; 늢; 늢; ) HANGUL SYLLABLE NEUBS
+B2A3;B2A3;1102 1173 11BA;B2A3;1102 1173 11BA; # (늣; 늣; 늣; 늣; 늣; ) HANGUL SYLLABLE NEUS
+B2A4;B2A4;1102 1173 11BB;B2A4;1102 1173 11BB; # (늤; 늤; 늤; 늤; 늤; ) HANGUL SYLLABLE NEUSS
+B2A5;B2A5;1102 1173 11BC;B2A5;1102 1173 11BC; # (능; 능; 능; 능; 능; ) HANGUL SYLLABLE NEUNG
+B2A6;B2A6;1102 1173 11BD;B2A6;1102 1173 11BD; # (늦; 늦; 늦; 늦; 늦; ) HANGUL SYLLABLE NEUJ
+B2A7;B2A7;1102 1173 11BE;B2A7;1102 1173 11BE; # (늧; 늧; 늧; 늧; 늧; ) HANGUL SYLLABLE NEUC
+B2A8;B2A8;1102 1173 11BF;B2A8;1102 1173 11BF; # (늨; 늨; 늨; 늨; 늨; ) HANGUL SYLLABLE NEUK
+B2A9;B2A9;1102 1173 11C0;B2A9;1102 1173 11C0; # (늩; 늩; 늩; 늩; 늩; ) HANGUL SYLLABLE NEUT
+B2AA;B2AA;1102 1173 11C1;B2AA;1102 1173 11C1; # (늪; 늪; 늪; 늪; 늪; ) HANGUL SYLLABLE NEUP
+B2AB;B2AB;1102 1173 11C2;B2AB;1102 1173 11C2; # (늫; 늫; 늫; 늫; 늫; ) HANGUL SYLLABLE NEUH
+B2AC;B2AC;1102 1174;B2AC;1102 1174; # (늬; 늬; 늬; 늬; 늬; ) HANGUL SYLLABLE NYI
+B2AD;B2AD;1102 1174 11A8;B2AD;1102 1174 11A8; # (늭; 늭; 늭; 늭; 늭; ) HANGUL SYLLABLE NYIG
+B2AE;B2AE;1102 1174 11A9;B2AE;1102 1174 11A9; # (늮; 늮; 늮; 늮; 늮; ) HANGUL SYLLABLE NYIGG
+B2AF;B2AF;1102 1174 11AA;B2AF;1102 1174 11AA; # (늯; 늯; 늯; 늯; 늯; ) HANGUL SYLLABLE NYIGS
+B2B0;B2B0;1102 1174 11AB;B2B0;1102 1174 11AB; # (늰; 늰; 늰; 늰; 늰; ) HANGUL SYLLABLE NYIN
+B2B1;B2B1;1102 1174 11AC;B2B1;1102 1174 11AC; # (늱; 늱; 늱; 늱; 늱; ) HANGUL SYLLABLE NYINJ
+B2B2;B2B2;1102 1174 11AD;B2B2;1102 1174 11AD; # (늲; 늲; 늲; 늲; 늲; ) HANGUL SYLLABLE NYINH
+B2B3;B2B3;1102 1174 11AE;B2B3;1102 1174 11AE; # (늳; 늳; 늳; 늳; 늳; ) HANGUL SYLLABLE NYID
+B2B4;B2B4;1102 1174 11AF;B2B4;1102 1174 11AF; # (늴; 늴; 늴; 늴; 늴; ) HANGUL SYLLABLE NYIL
+B2B5;B2B5;1102 1174 11B0;B2B5;1102 1174 11B0; # (늵; 늵; 늵; 늵; 늵; ) HANGUL SYLLABLE NYILG
+B2B6;B2B6;1102 1174 11B1;B2B6;1102 1174 11B1; # (늶; 늶; 늶; 늶; 늶; ) HANGUL SYLLABLE NYILM
+B2B7;B2B7;1102 1174 11B2;B2B7;1102 1174 11B2; # (늷; 늷; 늷; 늷; 늷; ) HANGUL SYLLABLE NYILB
+B2B8;B2B8;1102 1174 11B3;B2B8;1102 1174 11B3; # (늸; 늸; 늸; 늸; 늸; ) HANGUL SYLLABLE NYILS
+B2B9;B2B9;1102 1174 11B4;B2B9;1102 1174 11B4; # (늹; 늹; 늹; 늹; 늹; ) HANGUL SYLLABLE NYILT
+B2BA;B2BA;1102 1174 11B5;B2BA;1102 1174 11B5; # (늺; 늺; 늺; 늺; 늺; ) HANGUL SYLLABLE NYILP
+B2BB;B2BB;1102 1174 11B6;B2BB;1102 1174 11B6; # (늻; 늻; 늻; 늻; 늻; ) HANGUL SYLLABLE NYILH
+B2BC;B2BC;1102 1174 11B7;B2BC;1102 1174 11B7; # (늼; 늼; 늼; 늼; 늼; ) HANGUL SYLLABLE NYIM
+B2BD;B2BD;1102 1174 11B8;B2BD;1102 1174 11B8; # (늽; 늽; 늽; 늽; 늽; ) HANGUL SYLLABLE NYIB
+B2BE;B2BE;1102 1174 11B9;B2BE;1102 1174 11B9; # (늾; 늾; 늾; 늾; 늾; ) HANGUL SYLLABLE NYIBS
+B2BF;B2BF;1102 1174 11BA;B2BF;1102 1174 11BA; # (늿; 늿; 늿; 늿; 늿; ) HANGUL SYLLABLE NYIS
+B2C0;B2C0;1102 1174 11BB;B2C0;1102 1174 11BB; # (닀; 닀; 닀; 닀; 닀; ) HANGUL SYLLABLE NYISS
+B2C1;B2C1;1102 1174 11BC;B2C1;1102 1174 11BC; # (닁; 닁; 닁; 닁; 닁; ) HANGUL SYLLABLE NYING
+B2C2;B2C2;1102 1174 11BD;B2C2;1102 1174 11BD; # (닂; 닂; 닂; 닂; 닂; ) HANGUL SYLLABLE NYIJ
+B2C3;B2C3;1102 1174 11BE;B2C3;1102 1174 11BE; # (닃; 닃; 닃; 닃; 닃; ) HANGUL SYLLABLE NYIC
+B2C4;B2C4;1102 1174 11BF;B2C4;1102 1174 11BF; # (닄; 닄; 닄; 닄; 닄; ) HANGUL SYLLABLE NYIK
+B2C5;B2C5;1102 1174 11C0;B2C5;1102 1174 11C0; # (닅; 닅; 닅; 닅; 닅; ) HANGUL SYLLABLE NYIT
+B2C6;B2C6;1102 1174 11C1;B2C6;1102 1174 11C1; # (닆; 닆; 닆; 닆; 닆; ) HANGUL SYLLABLE NYIP
+B2C7;B2C7;1102 1174 11C2;B2C7;1102 1174 11C2; # (닇; 닇; 닇; 닇; 닇; ) HANGUL SYLLABLE NYIH
+B2C8;B2C8;1102 1175;B2C8;1102 1175; # (니; 니; 니; 니; 니; ) HANGUL SYLLABLE NI
+B2C9;B2C9;1102 1175 11A8;B2C9;1102 1175 11A8; # (닉; 닉; 닉; 닉; 닉; ) HANGUL SYLLABLE NIG
+B2CA;B2CA;1102 1175 11A9;B2CA;1102 1175 11A9; # (닊; 닊; 닊; 닊; 닊; ) HANGUL SYLLABLE NIGG
+B2CB;B2CB;1102 1175 11AA;B2CB;1102 1175 11AA; # (닋; 닋; 닋; 닋; 닋; ) HANGUL SYLLABLE NIGS
+B2CC;B2CC;1102 1175 11AB;B2CC;1102 1175 11AB; # (닌; 닌; 닌; 닌; 닌; ) HANGUL SYLLABLE NIN
+B2CD;B2CD;1102 1175 11AC;B2CD;1102 1175 11AC; # (닍; 닍; 닍; 닍; 닍; ) HANGUL SYLLABLE NINJ
+B2CE;B2CE;1102 1175 11AD;B2CE;1102 1175 11AD; # (닎; 닎; 닎; 닎; 닎; ) HANGUL SYLLABLE NINH
+B2CF;B2CF;1102 1175 11AE;B2CF;1102 1175 11AE; # (닏; 닏; 닏; 닏; 닏; ) HANGUL SYLLABLE NID
+B2D0;B2D0;1102 1175 11AF;B2D0;1102 1175 11AF; # (닐; 닐; 닐; 닐; 닐; ) HANGUL SYLLABLE NIL
+B2D1;B2D1;1102 1175 11B0;B2D1;1102 1175 11B0; # (닑; 닑; 닑; 닑; 닑; ) HANGUL SYLLABLE NILG
+B2D2;B2D2;1102 1175 11B1;B2D2;1102 1175 11B1; # (닒; 닒; 닒; 닒; 닒; ) HANGUL SYLLABLE NILM
+B2D3;B2D3;1102 1175 11B2;B2D3;1102 1175 11B2; # (닓; 닓; 닓; 닓; 닓; ) HANGUL SYLLABLE NILB
+B2D4;B2D4;1102 1175 11B3;B2D4;1102 1175 11B3; # (닔; 닔; 닔; 닔; 닔; ) HANGUL SYLLABLE NILS
+B2D5;B2D5;1102 1175 11B4;B2D5;1102 1175 11B4; # (닕; 닕; 닕; 닕; 닕; ) HANGUL SYLLABLE NILT
+B2D6;B2D6;1102 1175 11B5;B2D6;1102 1175 11B5; # (닖; 닖; 닖; 닖; 닖; ) HANGUL SYLLABLE NILP
+B2D7;B2D7;1102 1175 11B6;B2D7;1102 1175 11B6; # (닗; 닗; 닗; 닗; 닗; ) HANGUL SYLLABLE NILH
+B2D8;B2D8;1102 1175 11B7;B2D8;1102 1175 11B7; # (님; 님; 님; 님; 님; ) HANGUL SYLLABLE NIM
+B2D9;B2D9;1102 1175 11B8;B2D9;1102 1175 11B8; # (닙; 닙; 닙; 닙; 닙; ) HANGUL SYLLABLE NIB
+B2DA;B2DA;1102 1175 11B9;B2DA;1102 1175 11B9; # (닚; 닚; 닚; 닚; 닚; ) HANGUL SYLLABLE NIBS
+B2DB;B2DB;1102 1175 11BA;B2DB;1102 1175 11BA; # (닛; 닛; 닛; 닛; 닛; ) HANGUL SYLLABLE NIS
+B2DC;B2DC;1102 1175 11BB;B2DC;1102 1175 11BB; # (닜; 닜; 닜; 닜; 닜; ) HANGUL SYLLABLE NISS
+B2DD;B2DD;1102 1175 11BC;B2DD;1102 1175 11BC; # (닝; 닝; 닝; 닝; 닝; ) HANGUL SYLLABLE NING
+B2DE;B2DE;1102 1175 11BD;B2DE;1102 1175 11BD; # (닞; 닞; 닞; 닞; 닞; ) HANGUL SYLLABLE NIJ
+B2DF;B2DF;1102 1175 11BE;B2DF;1102 1175 11BE; # (닟; 닟; 닟; 닟; 닟; ) HANGUL SYLLABLE NIC
+B2E0;B2E0;1102 1175 11BF;B2E0;1102 1175 11BF; # (닠; 닠; 닠; 닠; 닠; ) HANGUL SYLLABLE NIK
+B2E1;B2E1;1102 1175 11C0;B2E1;1102 1175 11C0; # (닡; 닡; 닡; 닡; 닡; ) HANGUL SYLLABLE NIT
+B2E2;B2E2;1102 1175 11C1;B2E2;1102 1175 11C1; # (닢; 닢; 닢; 닢; 닢; ) HANGUL SYLLABLE NIP
+B2E3;B2E3;1102 1175 11C2;B2E3;1102 1175 11C2; # (닣; 닣; 닣; 닣; 닣; ) HANGUL SYLLABLE NIH
+B2E4;B2E4;1103 1161;B2E4;1103 1161; # (다; 다; 다; 다; 다; ) HANGUL SYLLABLE DA
+B2E5;B2E5;1103 1161 11A8;B2E5;1103 1161 11A8; # (닥; 닥; 닥; 닥; 닥; ) HANGUL SYLLABLE DAG
+B2E6;B2E6;1103 1161 11A9;B2E6;1103 1161 11A9; # (닦; 닦; 닦; 닦; 닦; ) HANGUL SYLLABLE DAGG
+B2E7;B2E7;1103 1161 11AA;B2E7;1103 1161 11AA; # (닧; 닧; 닧; 닧; 닧; ) HANGUL SYLLABLE DAGS
+B2E8;B2E8;1103 1161 11AB;B2E8;1103 1161 11AB; # (단; 단; 단; 단; 단; ) HANGUL SYLLABLE DAN
+B2E9;B2E9;1103 1161 11AC;B2E9;1103 1161 11AC; # (닩; 닩; 닩; 닩; 닩; ) HANGUL SYLLABLE DANJ
+B2EA;B2EA;1103 1161 11AD;B2EA;1103 1161 11AD; # (닪; 닪; 닪; 닪; 닪; ) HANGUL SYLLABLE DANH
+B2EB;B2EB;1103 1161 11AE;B2EB;1103 1161 11AE; # (닫; 닫; 닫; 닫; 닫; ) HANGUL SYLLABLE DAD
+B2EC;B2EC;1103 1161 11AF;B2EC;1103 1161 11AF; # (달; 달; 달; 달; 달; ) HANGUL SYLLABLE DAL
+B2ED;B2ED;1103 1161 11B0;B2ED;1103 1161 11B0; # (닭; 닭; 닭; 닭; 닭; ) HANGUL SYLLABLE DALG
+B2EE;B2EE;1103 1161 11B1;B2EE;1103 1161 11B1; # (닮; 닮; 닮; 닮; 닮; ) HANGUL SYLLABLE DALM
+B2EF;B2EF;1103 1161 11B2;B2EF;1103 1161 11B2; # (닯; 닯; 닯; 닯; 닯; ) HANGUL SYLLABLE DALB
+B2F0;B2F0;1103 1161 11B3;B2F0;1103 1161 11B3; # (닰; 닰; 닰; 닰; 닰; ) HANGUL SYLLABLE DALS
+B2F1;B2F1;1103 1161 11B4;B2F1;1103 1161 11B4; # (닱; 닱; 닱; 닱; 닱; ) HANGUL SYLLABLE DALT
+B2F2;B2F2;1103 1161 11B5;B2F2;1103 1161 11B5; # (닲; 닲; 닲; 닲; 닲; ) HANGUL SYLLABLE DALP
+B2F3;B2F3;1103 1161 11B6;B2F3;1103 1161 11B6; # (닳; 닳; 닳; 닳; 닳; ) HANGUL SYLLABLE DALH
+B2F4;B2F4;1103 1161 11B7;B2F4;1103 1161 11B7; # (담; 담; 담; 담; 담; ) HANGUL SYLLABLE DAM
+B2F5;B2F5;1103 1161 11B8;B2F5;1103 1161 11B8; # (답; 답; 답; 답; 답; ) HANGUL SYLLABLE DAB
+B2F6;B2F6;1103 1161 11B9;B2F6;1103 1161 11B9; # (닶; 닶; 닶; 닶; 닶; ) HANGUL SYLLABLE DABS
+B2F7;B2F7;1103 1161 11BA;B2F7;1103 1161 11BA; # (닷; 닷; 닷; 닷; 닷; ) HANGUL SYLLABLE DAS
+B2F8;B2F8;1103 1161 11BB;B2F8;1103 1161 11BB; # (닸; 닸; 닸; 닸; 닸; ) HANGUL SYLLABLE DASS
+B2F9;B2F9;1103 1161 11BC;B2F9;1103 1161 11BC; # (당; 당; 당; 당; 당; ) HANGUL SYLLABLE DANG
+B2FA;B2FA;1103 1161 11BD;B2FA;1103 1161 11BD; # (닺; 닺; 닺; 닺; 닺; ) HANGUL SYLLABLE DAJ
+B2FB;B2FB;1103 1161 11BE;B2FB;1103 1161 11BE; # (닻; 닻; 닻; 닻; 닻; ) HANGUL SYLLABLE DAC
+B2FC;B2FC;1103 1161 11BF;B2FC;1103 1161 11BF; # (닼; 닼; 닼; 닼; 닼; ) HANGUL SYLLABLE DAK
+B2FD;B2FD;1103 1161 11C0;B2FD;1103 1161 11C0; # (닽; 닽; 닽; 닽; 닽; ) HANGUL SYLLABLE DAT
+B2FE;B2FE;1103 1161 11C1;B2FE;1103 1161 11C1; # (닾; 닾; 닾; 닾; 닾; ) HANGUL SYLLABLE DAP
+B2FF;B2FF;1103 1161 11C2;B2FF;1103 1161 11C2; # (닿; 닿; 닿; 닿; 닿; ) HANGUL SYLLABLE DAH
+B300;B300;1103 1162;B300;1103 1162; # (대; 대; 대; 대; 대; ) HANGUL SYLLABLE DAE
+B301;B301;1103 1162 11A8;B301;1103 1162 11A8; # (댁; 댁; 댁; 댁; 댁; ) HANGUL SYLLABLE DAEG
+B302;B302;1103 1162 11A9;B302;1103 1162 11A9; # (댂; 댂; 댂; 댂; 댂; ) HANGUL SYLLABLE DAEGG
+B303;B303;1103 1162 11AA;B303;1103 1162 11AA; # (댃; 댃; 댃; 댃; 댃; ) HANGUL SYLLABLE DAEGS
+B304;B304;1103 1162 11AB;B304;1103 1162 11AB; # (댄; 댄; 댄; 댄; 댄; ) HANGUL SYLLABLE DAEN
+B305;B305;1103 1162 11AC;B305;1103 1162 11AC; # (댅; 댅; 댅; 댅; 댅; ) HANGUL SYLLABLE DAENJ
+B306;B306;1103 1162 11AD;B306;1103 1162 11AD; # (댆; 댆; 댆; 댆; 댆; ) HANGUL SYLLABLE DAENH
+B307;B307;1103 1162 11AE;B307;1103 1162 11AE; # (댇; 댇; 댇; 댇; 댇; ) HANGUL SYLLABLE DAED
+B308;B308;1103 1162 11AF;B308;1103 1162 11AF; # (댈; 댈; 댈; 댈; 댈; ) HANGUL SYLLABLE DAEL
+B309;B309;1103 1162 11B0;B309;1103 1162 11B0; # (댉; 댉; 댉; 댉; 댉; ) HANGUL SYLLABLE DAELG
+B30A;B30A;1103 1162 11B1;B30A;1103 1162 11B1; # (댊; 댊; 댊; 댊; 댊; ) HANGUL SYLLABLE DAELM
+B30B;B30B;1103 1162 11B2;B30B;1103 1162 11B2; # (댋; 댋; 댋; 댋; 댋; ) HANGUL SYLLABLE DAELB
+B30C;B30C;1103 1162 11B3;B30C;1103 1162 11B3; # (댌; 댌; 댌; 댌; 댌; ) HANGUL SYLLABLE DAELS
+B30D;B30D;1103 1162 11B4;B30D;1103 1162 11B4; # (댍; 댍; 댍; 댍; 댍; ) HANGUL SYLLABLE DAELT
+B30E;B30E;1103 1162 11B5;B30E;1103 1162 11B5; # (댎; 댎; 댎; 댎; 댎; ) HANGUL SYLLABLE DAELP
+B30F;B30F;1103 1162 11B6;B30F;1103 1162 11B6; # (댏; 댏; 댏; 댏; 댏; ) HANGUL SYLLABLE DAELH
+B310;B310;1103 1162 11B7;B310;1103 1162 11B7; # (댐; 댐; 댐; 댐; 댐; ) HANGUL SYLLABLE DAEM
+B311;B311;1103 1162 11B8;B311;1103 1162 11B8; # (댑; 댑; 댑; 댑; 댑; ) HANGUL SYLLABLE DAEB
+B312;B312;1103 1162 11B9;B312;1103 1162 11B9; # (댒; 댒; 댒; 댒; 댒; ) HANGUL SYLLABLE DAEBS
+B313;B313;1103 1162 11BA;B313;1103 1162 11BA; # (댓; 댓; 댓; 댓; 댓; ) HANGUL SYLLABLE DAES
+B314;B314;1103 1162 11BB;B314;1103 1162 11BB; # (댔; 댔; 댔; 댔; 댔; ) HANGUL SYLLABLE DAESS
+B315;B315;1103 1162 11BC;B315;1103 1162 11BC; # (댕; 댕; 댕; 댕; 댕; ) HANGUL SYLLABLE DAENG
+B316;B316;1103 1162 11BD;B316;1103 1162 11BD; # (댖; 댖; 댖; 댖; 댖; ) HANGUL SYLLABLE DAEJ
+B317;B317;1103 1162 11BE;B317;1103 1162 11BE; # (댗; 댗; 댗; 댗; 댗; ) HANGUL SYLLABLE DAEC
+B318;B318;1103 1162 11BF;B318;1103 1162 11BF; # (댘; 댘; 댘; 댘; 댘; ) HANGUL SYLLABLE DAEK
+B319;B319;1103 1162 11C0;B319;1103 1162 11C0; # (댙; 댙; 댙; 댙; 댙; ) HANGUL SYLLABLE DAET
+B31A;B31A;1103 1162 11C1;B31A;1103 1162 11C1; # (댚; 댚; 댚; 댚; 댚; ) HANGUL SYLLABLE DAEP
+B31B;B31B;1103 1162 11C2;B31B;1103 1162 11C2; # (댛; 댛; 댛; 댛; 댛; ) HANGUL SYLLABLE DAEH
+B31C;B31C;1103 1163;B31C;1103 1163; # (댜; 댜; 댜; 댜; 댜; ) HANGUL SYLLABLE DYA
+B31D;B31D;1103 1163 11A8;B31D;1103 1163 11A8; # (댝; 댝; 댝; 댝; 댝; ) HANGUL SYLLABLE DYAG
+B31E;B31E;1103 1163 11A9;B31E;1103 1163 11A9; # (댞; 댞; 댞; 댞; 댞; ) HANGUL SYLLABLE DYAGG
+B31F;B31F;1103 1163 11AA;B31F;1103 1163 11AA; # (댟; 댟; 댟; 댟; 댟; ) HANGUL SYLLABLE DYAGS
+B320;B320;1103 1163 11AB;B320;1103 1163 11AB; # (댠; 댠; 댠; 댠; 댠; ) HANGUL SYLLABLE DYAN
+B321;B321;1103 1163 11AC;B321;1103 1163 11AC; # (댡; 댡; 댡; 댡; 댡; ) HANGUL SYLLABLE DYANJ
+B322;B322;1103 1163 11AD;B322;1103 1163 11AD; # (댢; 댢; 댢; 댢; 댢; ) HANGUL SYLLABLE DYANH
+B323;B323;1103 1163 11AE;B323;1103 1163 11AE; # (댣; 댣; 댣; 댣; 댣; ) HANGUL SYLLABLE DYAD
+B324;B324;1103 1163 11AF;B324;1103 1163 11AF; # (댤; 댤; 댤; 댤; 댤; ) HANGUL SYLLABLE DYAL
+B325;B325;1103 1163 11B0;B325;1103 1163 11B0; # (댥; 댥; 댥; 댥; 댥; ) HANGUL SYLLABLE DYALG
+B326;B326;1103 1163 11B1;B326;1103 1163 11B1; # (댦; 댦; 댦; 댦; 댦; ) HANGUL SYLLABLE DYALM
+B327;B327;1103 1163 11B2;B327;1103 1163 11B2; # (댧; 댧; 댧; 댧; 댧; ) HANGUL SYLLABLE DYALB
+B328;B328;1103 1163 11B3;B328;1103 1163 11B3; # (댨; 댨; 댨; 댨; 댨; ) HANGUL SYLLABLE DYALS
+B329;B329;1103 1163 11B4;B329;1103 1163 11B4; # (댩; 댩; 댩; 댩; 댩; ) HANGUL SYLLABLE DYALT
+B32A;B32A;1103 1163 11B5;B32A;1103 1163 11B5; # (댪; 댪; 댪; 댪; 댪; ) HANGUL SYLLABLE DYALP
+B32B;B32B;1103 1163 11B6;B32B;1103 1163 11B6; # (댫; 댫; 댫; 댫; 댫; ) HANGUL SYLLABLE DYALH
+B32C;B32C;1103 1163 11B7;B32C;1103 1163 11B7; # (댬; 댬; 댬; 댬; 댬; ) HANGUL SYLLABLE DYAM
+B32D;B32D;1103 1163 11B8;B32D;1103 1163 11B8; # (댭; 댭; 댭; 댭; 댭; ) HANGUL SYLLABLE DYAB
+B32E;B32E;1103 1163 11B9;B32E;1103 1163 11B9; # (댮; 댮; 댮; 댮; 댮; ) HANGUL SYLLABLE DYABS
+B32F;B32F;1103 1163 11BA;B32F;1103 1163 11BA; # (댯; 댯; 댯; 댯; 댯; ) HANGUL SYLLABLE DYAS
+B330;B330;1103 1163 11BB;B330;1103 1163 11BB; # (댰; 댰; 댰; 댰; 댰; ) HANGUL SYLLABLE DYASS
+B331;B331;1103 1163 11BC;B331;1103 1163 11BC; # (댱; 댱; 댱; 댱; 댱; ) HANGUL SYLLABLE DYANG
+B332;B332;1103 1163 11BD;B332;1103 1163 11BD; # (댲; 댲; 댲; 댲; 댲; ) HANGUL SYLLABLE DYAJ
+B333;B333;1103 1163 11BE;B333;1103 1163 11BE; # (댳; 댳; 댳; 댳; 댳; ) HANGUL SYLLABLE DYAC
+B334;B334;1103 1163 11BF;B334;1103 1163 11BF; # (댴; 댴; 댴; 댴; 댴; ) HANGUL SYLLABLE DYAK
+B335;B335;1103 1163 11C0;B335;1103 1163 11C0; # (댵; 댵; 댵; 댵; 댵; ) HANGUL SYLLABLE DYAT
+B336;B336;1103 1163 11C1;B336;1103 1163 11C1; # (댶; 댶; 댶; 댶; 댶; ) HANGUL SYLLABLE DYAP
+B337;B337;1103 1163 11C2;B337;1103 1163 11C2; # (댷; 댷; 댷; 댷; 댷; ) HANGUL SYLLABLE DYAH
+B338;B338;1103 1164;B338;1103 1164; # (댸; 댸; 댸; 댸; 댸; ) HANGUL SYLLABLE DYAE
+B339;B339;1103 1164 11A8;B339;1103 1164 11A8; # (댹; 댹; 댹; 댹; 댹; ) HANGUL SYLLABLE DYAEG
+B33A;B33A;1103 1164 11A9;B33A;1103 1164 11A9; # (댺; 댺; 댺; 댺; 댺; ) HANGUL SYLLABLE DYAEGG
+B33B;B33B;1103 1164 11AA;B33B;1103 1164 11AA; # (댻; 댻; 댻; 댻; 댻; ) HANGUL SYLLABLE DYAEGS
+B33C;B33C;1103 1164 11AB;B33C;1103 1164 11AB; # (댼; 댼; 댼; 댼; 댼; ) HANGUL SYLLABLE DYAEN
+B33D;B33D;1103 1164 11AC;B33D;1103 1164 11AC; # (댽; 댽; 댽; 댽; 댽; ) HANGUL SYLLABLE DYAENJ
+B33E;B33E;1103 1164 11AD;B33E;1103 1164 11AD; # (댾; 댾; 댾; 댾; 댾; ) HANGUL SYLLABLE DYAENH
+B33F;B33F;1103 1164 11AE;B33F;1103 1164 11AE; # (댿; 댿; 댿; 댿; 댿; ) HANGUL SYLLABLE DYAED
+B340;B340;1103 1164 11AF;B340;1103 1164 11AF; # (덀; 덀; 덀; 덀; 덀; ) HANGUL SYLLABLE DYAEL
+B341;B341;1103 1164 11B0;B341;1103 1164 11B0; # (덁; 덁; 덁; 덁; 덁; ) HANGUL SYLLABLE DYAELG
+B342;B342;1103 1164 11B1;B342;1103 1164 11B1; # (덂; 덂; 덂; 덂; 덂; ) HANGUL SYLLABLE DYAELM
+B343;B343;1103 1164 11B2;B343;1103 1164 11B2; # (덃; 덃; 덃; 덃; 덃; ) HANGUL SYLLABLE DYAELB
+B344;B344;1103 1164 11B3;B344;1103 1164 11B3; # (덄; 덄; 덄; 덄; 덄; ) HANGUL SYLLABLE DYAELS
+B345;B345;1103 1164 11B4;B345;1103 1164 11B4; # (덅; 덅; 덅; 덅; 덅; ) HANGUL SYLLABLE DYAELT
+B346;B346;1103 1164 11B5;B346;1103 1164 11B5; # (덆; 덆; 덆; 덆; 덆; ) HANGUL SYLLABLE DYAELP
+B347;B347;1103 1164 11B6;B347;1103 1164 11B6; # (덇; 덇; 덇; 덇; 덇; ) HANGUL SYLLABLE DYAELH
+B348;B348;1103 1164 11B7;B348;1103 1164 11B7; # (덈; 덈; 덈; 덈; 덈; ) HANGUL SYLLABLE DYAEM
+B349;B349;1103 1164 11B8;B349;1103 1164 11B8; # (덉; 덉; 덉; 덉; 덉; ) HANGUL SYLLABLE DYAEB
+B34A;B34A;1103 1164 11B9;B34A;1103 1164 11B9; # (덊; 덊; 덊; 덊; 덊; ) HANGUL SYLLABLE DYAEBS
+B34B;B34B;1103 1164 11BA;B34B;1103 1164 11BA; # (덋; 덋; 덋; 덋; 덋; ) HANGUL SYLLABLE DYAES
+B34C;B34C;1103 1164 11BB;B34C;1103 1164 11BB; # (덌; 덌; 덌; 덌; 덌; ) HANGUL SYLLABLE DYAESS
+B34D;B34D;1103 1164 11BC;B34D;1103 1164 11BC; # (덍; 덍; 덍; 덍; 덍; ) HANGUL SYLLABLE DYAENG
+B34E;B34E;1103 1164 11BD;B34E;1103 1164 11BD; # (덎; 덎; 덎; 덎; 덎; ) HANGUL SYLLABLE DYAEJ
+B34F;B34F;1103 1164 11BE;B34F;1103 1164 11BE; # (덏; 덏; 덏; 덏; 덏; ) HANGUL SYLLABLE DYAEC
+B350;B350;1103 1164 11BF;B350;1103 1164 11BF; # (덐; 덐; 덐; 덐; 덐; ) HANGUL SYLLABLE DYAEK
+B351;B351;1103 1164 11C0;B351;1103 1164 11C0; # (덑; 덑; 덑; 덑; 덑; ) HANGUL SYLLABLE DYAET
+B352;B352;1103 1164 11C1;B352;1103 1164 11C1; # (덒; 덒; 덒; 덒; 덒; ) HANGUL SYLLABLE DYAEP
+B353;B353;1103 1164 11C2;B353;1103 1164 11C2; # (덓; 덓; 덓; 덓; 덓; ) HANGUL SYLLABLE DYAEH
+B354;B354;1103 1165;B354;1103 1165; # (더; 더; 더; 더; 더; ) HANGUL SYLLABLE DEO
+B355;B355;1103 1165 11A8;B355;1103 1165 11A8; # (덕; 덕; 덕; 덕; 덕; ) HANGUL SYLLABLE DEOG
+B356;B356;1103 1165 11A9;B356;1103 1165 11A9; # (덖; 덖; 덖; 덖; 덖; ) HANGUL SYLLABLE DEOGG
+B357;B357;1103 1165 11AA;B357;1103 1165 11AA; # (덗; 덗; 덗; 덗; 덗; ) HANGUL SYLLABLE DEOGS
+B358;B358;1103 1165 11AB;B358;1103 1165 11AB; # (던; 던; 던; 던; 던; ) HANGUL SYLLABLE DEON
+B359;B359;1103 1165 11AC;B359;1103 1165 11AC; # (덙; 덙; 덙; 덙; 덙; ) HANGUL SYLLABLE DEONJ
+B35A;B35A;1103 1165 11AD;B35A;1103 1165 11AD; # (덚; 덚; 덚; 덚; 덚; ) HANGUL SYLLABLE DEONH
+B35B;B35B;1103 1165 11AE;B35B;1103 1165 11AE; # (덛; 덛; 덛; 덛; 덛; ) HANGUL SYLLABLE DEOD
+B35C;B35C;1103 1165 11AF;B35C;1103 1165 11AF; # (덜; 덜; 덜; 덜; 덜; ) HANGUL SYLLABLE DEOL
+B35D;B35D;1103 1165 11B0;B35D;1103 1165 11B0; # (덝; 덝; 덝; 덝; 덝; ) HANGUL SYLLABLE DEOLG
+B35E;B35E;1103 1165 11B1;B35E;1103 1165 11B1; # (덞; 덞; 덞; 덞; 덞; ) HANGUL SYLLABLE DEOLM
+B35F;B35F;1103 1165 11B2;B35F;1103 1165 11B2; # (덟; 덟; 덟; 덟; 덟; ) HANGUL SYLLABLE DEOLB
+B360;B360;1103 1165 11B3;B360;1103 1165 11B3; # (덠; 덠; 덠; 덠; 덠; ) HANGUL SYLLABLE DEOLS
+B361;B361;1103 1165 11B4;B361;1103 1165 11B4; # (덡; 덡; 덡; 덡; 덡; ) HANGUL SYLLABLE DEOLT
+B362;B362;1103 1165 11B5;B362;1103 1165 11B5; # (덢; 덢; 덢; 덢; 덢; ) HANGUL SYLLABLE DEOLP
+B363;B363;1103 1165 11B6;B363;1103 1165 11B6; # (덣; 덣; 덣; 덣; 덣; ) HANGUL SYLLABLE DEOLH
+B364;B364;1103 1165 11B7;B364;1103 1165 11B7; # (덤; 덤; 덤; 덤; 덤; ) HANGUL SYLLABLE DEOM
+B365;B365;1103 1165 11B8;B365;1103 1165 11B8; # (덥; 덥; 덥; 덥; 덥; ) HANGUL SYLLABLE DEOB
+B366;B366;1103 1165 11B9;B366;1103 1165 11B9; # (덦; 덦; 덦; 덦; 덦; ) HANGUL SYLLABLE DEOBS
+B367;B367;1103 1165 11BA;B367;1103 1165 11BA; # (덧; 덧; 덧; 덧; 덧; ) HANGUL SYLLABLE DEOS
+B368;B368;1103 1165 11BB;B368;1103 1165 11BB; # (덨; 덨; 덨; 덨; 덨; ) HANGUL SYLLABLE DEOSS
+B369;B369;1103 1165 11BC;B369;1103 1165 11BC; # (덩; 덩; 덩; 덩; 덩; ) HANGUL SYLLABLE DEONG
+B36A;B36A;1103 1165 11BD;B36A;1103 1165 11BD; # (덪; 덪; 덪; 덪; 덪; ) HANGUL SYLLABLE DEOJ
+B36B;B36B;1103 1165 11BE;B36B;1103 1165 11BE; # (덫; 덫; 덫; 덫; 덫; ) HANGUL SYLLABLE DEOC
+B36C;B36C;1103 1165 11BF;B36C;1103 1165 11BF; # (덬; 덬; 덬; 덬; 덬; ) HANGUL SYLLABLE DEOK
+B36D;B36D;1103 1165 11C0;B36D;1103 1165 11C0; # (덭; 덭; 덭; 덭; 덭; ) HANGUL SYLLABLE DEOT
+B36E;B36E;1103 1165 11C1;B36E;1103 1165 11C1; # (덮; 덮; 덮; 덮; 덮; ) HANGUL SYLLABLE DEOP
+B36F;B36F;1103 1165 11C2;B36F;1103 1165 11C2; # (덯; 덯; 덯; 덯; 덯; ) HANGUL SYLLABLE DEOH
+B370;B370;1103 1166;B370;1103 1166; # (데; 데; 데; 데; 데; ) HANGUL SYLLABLE DE
+B371;B371;1103 1166 11A8;B371;1103 1166 11A8; # (덱; 덱; 덱; 덱; 덱; ) HANGUL SYLLABLE DEG
+B372;B372;1103 1166 11A9;B372;1103 1166 11A9; # (덲; 덲; 덲; 덲; 덲; ) HANGUL SYLLABLE DEGG
+B373;B373;1103 1166 11AA;B373;1103 1166 11AA; # (덳; 덳; 덳; 덳; 덳; ) HANGUL SYLLABLE DEGS
+B374;B374;1103 1166 11AB;B374;1103 1166 11AB; # (덴; 덴; 덴; 덴; 덴; ) HANGUL SYLLABLE DEN
+B375;B375;1103 1166 11AC;B375;1103 1166 11AC; # (덵; 덵; 덵; 덵; 덵; ) HANGUL SYLLABLE DENJ
+B376;B376;1103 1166 11AD;B376;1103 1166 11AD; # (덶; 덶; 덶; 덶; 덶; ) HANGUL SYLLABLE DENH
+B377;B377;1103 1166 11AE;B377;1103 1166 11AE; # (덷; 덷; 덷; 덷; 덷; ) HANGUL SYLLABLE DED
+B378;B378;1103 1166 11AF;B378;1103 1166 11AF; # (델; 델; 델; 델; 델; ) HANGUL SYLLABLE DEL
+B379;B379;1103 1166 11B0;B379;1103 1166 11B0; # (덹; 덹; 덹; 덹; 덹; ) HANGUL SYLLABLE DELG
+B37A;B37A;1103 1166 11B1;B37A;1103 1166 11B1; # (덺; 덺; 덺; 덺; 덺; ) HANGUL SYLLABLE DELM
+B37B;B37B;1103 1166 11B2;B37B;1103 1166 11B2; # (덻; 덻; 덻; 덻; 덻; ) HANGUL SYLLABLE DELB
+B37C;B37C;1103 1166 11B3;B37C;1103 1166 11B3; # (덼; 덼; 덼; 덼; 덼; ) HANGUL SYLLABLE DELS
+B37D;B37D;1103 1166 11B4;B37D;1103 1166 11B4; # (덽; 덽; 덽; 덽; 덽; ) HANGUL SYLLABLE DELT
+B37E;B37E;1103 1166 11B5;B37E;1103 1166 11B5; # (덾; 덾; 덾; 덾; 덾; ) HANGUL SYLLABLE DELP
+B37F;B37F;1103 1166 11B6;B37F;1103 1166 11B6; # (덿; 덿; 덿; 덿; 덿; ) HANGUL SYLLABLE DELH
+B380;B380;1103 1166 11B7;B380;1103 1166 11B7; # (뎀; 뎀; 뎀; 뎀; 뎀; ) HANGUL SYLLABLE DEM
+B381;B381;1103 1166 11B8;B381;1103 1166 11B8; # (뎁; 뎁; 뎁; 뎁; 뎁; ) HANGUL SYLLABLE DEB
+B382;B382;1103 1166 11B9;B382;1103 1166 11B9; # (뎂; 뎂; 뎂; 뎂; 뎂; ) HANGUL SYLLABLE DEBS
+B383;B383;1103 1166 11BA;B383;1103 1166 11BA; # (뎃; 뎃; 뎃; 뎃; 뎃; ) HANGUL SYLLABLE DES
+B384;B384;1103 1166 11BB;B384;1103 1166 11BB; # (뎄; 뎄; 뎄; 뎄; 뎄; ) HANGUL SYLLABLE DESS
+B385;B385;1103 1166 11BC;B385;1103 1166 11BC; # (뎅; 뎅; 뎅; 뎅; 뎅; ) HANGUL SYLLABLE DENG
+B386;B386;1103 1166 11BD;B386;1103 1166 11BD; # (뎆; 뎆; 뎆; 뎆; 뎆; ) HANGUL SYLLABLE DEJ
+B387;B387;1103 1166 11BE;B387;1103 1166 11BE; # (뎇; 뎇; 뎇; 뎇; 뎇; ) HANGUL SYLLABLE DEC
+B388;B388;1103 1166 11BF;B388;1103 1166 11BF; # (뎈; 뎈; 뎈; 뎈; 뎈; ) HANGUL SYLLABLE DEK
+B389;B389;1103 1166 11C0;B389;1103 1166 11C0; # (뎉; 뎉; 뎉; 뎉; 뎉; ) HANGUL SYLLABLE DET
+B38A;B38A;1103 1166 11C1;B38A;1103 1166 11C1; # (뎊; 뎊; 뎊; 뎊; 뎊; ) HANGUL SYLLABLE DEP
+B38B;B38B;1103 1166 11C2;B38B;1103 1166 11C2; # (뎋; 뎋; 뎋; 뎋; 뎋; ) HANGUL SYLLABLE DEH
+B38C;B38C;1103 1167;B38C;1103 1167; # (뎌; 뎌; 뎌; 뎌; 뎌; ) HANGUL SYLLABLE DYEO
+B38D;B38D;1103 1167 11A8;B38D;1103 1167 11A8; # (뎍; 뎍; 뎍; 뎍; 뎍; ) HANGUL SYLLABLE DYEOG
+B38E;B38E;1103 1167 11A9;B38E;1103 1167 11A9; # (뎎; 뎎; 뎎; 뎎; 뎎; ) HANGUL SYLLABLE DYEOGG
+B38F;B38F;1103 1167 11AA;B38F;1103 1167 11AA; # (뎏; 뎏; 뎏; 뎏; 뎏; ) HANGUL SYLLABLE DYEOGS
+B390;B390;1103 1167 11AB;B390;1103 1167 11AB; # (뎐; 뎐; 뎐; 뎐; 뎐; ) HANGUL SYLLABLE DYEON
+B391;B391;1103 1167 11AC;B391;1103 1167 11AC; # (뎑; 뎑; 뎑; 뎑; 뎑; ) HANGUL SYLLABLE DYEONJ
+B392;B392;1103 1167 11AD;B392;1103 1167 11AD; # (뎒; 뎒; 뎒; 뎒; 뎒; ) HANGUL SYLLABLE DYEONH
+B393;B393;1103 1167 11AE;B393;1103 1167 11AE; # (뎓; 뎓; 뎓; 뎓; 뎓; ) HANGUL SYLLABLE DYEOD
+B394;B394;1103 1167 11AF;B394;1103 1167 11AF; # (뎔; 뎔; 뎔; 뎔; 뎔; ) HANGUL SYLLABLE DYEOL
+B395;B395;1103 1167 11B0;B395;1103 1167 11B0; # (뎕; 뎕; 뎕; 뎕; 뎕; ) HANGUL SYLLABLE DYEOLG
+B396;B396;1103 1167 11B1;B396;1103 1167 11B1; # (뎖; 뎖; 뎖; 뎖; 뎖; ) HANGUL SYLLABLE DYEOLM
+B397;B397;1103 1167 11B2;B397;1103 1167 11B2; # (뎗; 뎗; 뎗; 뎗; 뎗; ) HANGUL SYLLABLE DYEOLB
+B398;B398;1103 1167 11B3;B398;1103 1167 11B3; # (뎘; 뎘; 뎘; 뎘; 뎘; ) HANGUL SYLLABLE DYEOLS
+B399;B399;1103 1167 11B4;B399;1103 1167 11B4; # (뎙; 뎙; 뎙; 뎙; 뎙; ) HANGUL SYLLABLE DYEOLT
+B39A;B39A;1103 1167 11B5;B39A;1103 1167 11B5; # (뎚; 뎚; 뎚; 뎚; 뎚; ) HANGUL SYLLABLE DYEOLP
+B39B;B39B;1103 1167 11B6;B39B;1103 1167 11B6; # (뎛; 뎛; 뎛; 뎛; 뎛; ) HANGUL SYLLABLE DYEOLH
+B39C;B39C;1103 1167 11B7;B39C;1103 1167 11B7; # (뎜; 뎜; 뎜; 뎜; 뎜; ) HANGUL SYLLABLE DYEOM
+B39D;B39D;1103 1167 11B8;B39D;1103 1167 11B8; # (뎝; 뎝; 뎝; 뎝; 뎝; ) HANGUL SYLLABLE DYEOB
+B39E;B39E;1103 1167 11B9;B39E;1103 1167 11B9; # (뎞; 뎞; 뎞; 뎞; 뎞; ) HANGUL SYLLABLE DYEOBS
+B39F;B39F;1103 1167 11BA;B39F;1103 1167 11BA; # (뎟; 뎟; 뎟; 뎟; 뎟; ) HANGUL SYLLABLE DYEOS
+B3A0;B3A0;1103 1167 11BB;B3A0;1103 1167 11BB; # (뎠; 뎠; 뎠; 뎠; 뎠; ) HANGUL SYLLABLE DYEOSS
+B3A1;B3A1;1103 1167 11BC;B3A1;1103 1167 11BC; # (뎡; 뎡; 뎡; 뎡; 뎡; ) HANGUL SYLLABLE DYEONG
+B3A2;B3A2;1103 1167 11BD;B3A2;1103 1167 11BD; # (뎢; 뎢; 뎢; 뎢; 뎢; ) HANGUL SYLLABLE DYEOJ
+B3A3;B3A3;1103 1167 11BE;B3A3;1103 1167 11BE; # (뎣; 뎣; 뎣; 뎣; 뎣; ) HANGUL SYLLABLE DYEOC
+B3A4;B3A4;1103 1167 11BF;B3A4;1103 1167 11BF; # (뎤; 뎤; 뎤; 뎤; 뎤; ) HANGUL SYLLABLE DYEOK
+B3A5;B3A5;1103 1167 11C0;B3A5;1103 1167 11C0; # (뎥; 뎥; 뎥; 뎥; 뎥; ) HANGUL SYLLABLE DYEOT
+B3A6;B3A6;1103 1167 11C1;B3A6;1103 1167 11C1; # (뎦; 뎦; 뎦; 뎦; 뎦; ) HANGUL SYLLABLE DYEOP
+B3A7;B3A7;1103 1167 11C2;B3A7;1103 1167 11C2; # (뎧; 뎧; 뎧; 뎧; 뎧; ) HANGUL SYLLABLE DYEOH
+B3A8;B3A8;1103 1168;B3A8;1103 1168; # (뎨; 뎨; 뎨; 뎨; 뎨; ) HANGUL SYLLABLE DYE
+B3A9;B3A9;1103 1168 11A8;B3A9;1103 1168 11A8; # (뎩; 뎩; 뎩; 뎩; 뎩; ) HANGUL SYLLABLE DYEG
+B3AA;B3AA;1103 1168 11A9;B3AA;1103 1168 11A9; # (뎪; 뎪; 뎪; 뎪; 뎪; ) HANGUL SYLLABLE DYEGG
+B3AB;B3AB;1103 1168 11AA;B3AB;1103 1168 11AA; # (뎫; 뎫; 뎫; 뎫; 뎫; ) HANGUL SYLLABLE DYEGS
+B3AC;B3AC;1103 1168 11AB;B3AC;1103 1168 11AB; # (뎬; 뎬; 뎬; 뎬; 뎬; ) HANGUL SYLLABLE DYEN
+B3AD;B3AD;1103 1168 11AC;B3AD;1103 1168 11AC; # (뎭; 뎭; 뎭; 뎭; 뎭; ) HANGUL SYLLABLE DYENJ
+B3AE;B3AE;1103 1168 11AD;B3AE;1103 1168 11AD; # (뎮; 뎮; 뎮; 뎮; 뎮; ) HANGUL SYLLABLE DYENH
+B3AF;B3AF;1103 1168 11AE;B3AF;1103 1168 11AE; # (뎯; 뎯; 뎯; 뎯; 뎯; ) HANGUL SYLLABLE DYED
+B3B0;B3B0;1103 1168 11AF;B3B0;1103 1168 11AF; # (뎰; 뎰; 뎰; 뎰; 뎰; ) HANGUL SYLLABLE DYEL
+B3B1;B3B1;1103 1168 11B0;B3B1;1103 1168 11B0; # (뎱; 뎱; 뎱; 뎱; 뎱; ) HANGUL SYLLABLE DYELG
+B3B2;B3B2;1103 1168 11B1;B3B2;1103 1168 11B1; # (뎲; 뎲; 뎲; 뎲; 뎲; ) HANGUL SYLLABLE DYELM
+B3B3;B3B3;1103 1168 11B2;B3B3;1103 1168 11B2; # (뎳; 뎳; 뎳; 뎳; 뎳; ) HANGUL SYLLABLE DYELB
+B3B4;B3B4;1103 1168 11B3;B3B4;1103 1168 11B3; # (뎴; 뎴; 뎴; 뎴; 뎴; ) HANGUL SYLLABLE DYELS
+B3B5;B3B5;1103 1168 11B4;B3B5;1103 1168 11B4; # (뎵; 뎵; 뎵; 뎵; 뎵; ) HANGUL SYLLABLE DYELT
+B3B6;B3B6;1103 1168 11B5;B3B6;1103 1168 11B5; # (뎶; 뎶; 뎶; 뎶; 뎶; ) HANGUL SYLLABLE DYELP
+B3B7;B3B7;1103 1168 11B6;B3B7;1103 1168 11B6; # (뎷; 뎷; 뎷; 뎷; 뎷; ) HANGUL SYLLABLE DYELH
+B3B8;B3B8;1103 1168 11B7;B3B8;1103 1168 11B7; # (뎸; 뎸; 뎸; 뎸; 뎸; ) HANGUL SYLLABLE DYEM
+B3B9;B3B9;1103 1168 11B8;B3B9;1103 1168 11B8; # (뎹; 뎹; 뎹; 뎹; 뎹; ) HANGUL SYLLABLE DYEB
+B3BA;B3BA;1103 1168 11B9;B3BA;1103 1168 11B9; # (뎺; 뎺; 뎺; 뎺; 뎺; ) HANGUL SYLLABLE DYEBS
+B3BB;B3BB;1103 1168 11BA;B3BB;1103 1168 11BA; # (뎻; 뎻; 뎻; 뎻; 뎻; ) HANGUL SYLLABLE DYES
+B3BC;B3BC;1103 1168 11BB;B3BC;1103 1168 11BB; # (뎼; 뎼; 뎼; 뎼; 뎼; ) HANGUL SYLLABLE DYESS
+B3BD;B3BD;1103 1168 11BC;B3BD;1103 1168 11BC; # (뎽; 뎽; 뎽; 뎽; 뎽; ) HANGUL SYLLABLE DYENG
+B3BE;B3BE;1103 1168 11BD;B3BE;1103 1168 11BD; # (뎾; 뎾; 뎾; 뎾; 뎾; ) HANGUL SYLLABLE DYEJ
+B3BF;B3BF;1103 1168 11BE;B3BF;1103 1168 11BE; # (뎿; 뎿; 뎿; 뎿; 뎿; ) HANGUL SYLLABLE DYEC
+B3C0;B3C0;1103 1168 11BF;B3C0;1103 1168 11BF; # (돀; 돀; 돀; 돀; 돀; ) HANGUL SYLLABLE DYEK
+B3C1;B3C1;1103 1168 11C0;B3C1;1103 1168 11C0; # (돁; 돁; 돁; 돁; 돁; ) HANGUL SYLLABLE DYET
+B3C2;B3C2;1103 1168 11C1;B3C2;1103 1168 11C1; # (돂; 돂; 돂; 돂; 돂; ) HANGUL SYLLABLE DYEP
+B3C3;B3C3;1103 1168 11C2;B3C3;1103 1168 11C2; # (돃; 돃; 돃; 돃; 돃; ) HANGUL SYLLABLE DYEH
+B3C4;B3C4;1103 1169;B3C4;1103 1169; # (도; 도; 도; 도; 도; ) HANGUL SYLLABLE DO
+B3C5;B3C5;1103 1169 11A8;B3C5;1103 1169 11A8; # (독; 독; 독; 독; 독; ) HANGUL SYLLABLE DOG
+B3C6;B3C6;1103 1169 11A9;B3C6;1103 1169 11A9; # (돆; 돆; 돆; 돆; 돆; ) HANGUL SYLLABLE DOGG
+B3C7;B3C7;1103 1169 11AA;B3C7;1103 1169 11AA; # (돇; 돇; 돇; 돇; 돇; ) HANGUL SYLLABLE DOGS
+B3C8;B3C8;1103 1169 11AB;B3C8;1103 1169 11AB; # (돈; 돈; 돈; 돈; 돈; ) HANGUL SYLLABLE DON
+B3C9;B3C9;1103 1169 11AC;B3C9;1103 1169 11AC; # (돉; 돉; 돉; 돉; 돉; ) HANGUL SYLLABLE DONJ
+B3CA;B3CA;1103 1169 11AD;B3CA;1103 1169 11AD; # (돊; 돊; 돊; 돊; 돊; ) HANGUL SYLLABLE DONH
+B3CB;B3CB;1103 1169 11AE;B3CB;1103 1169 11AE; # (돋; 돋; 돋; 돋; 돋; ) HANGUL SYLLABLE DOD
+B3CC;B3CC;1103 1169 11AF;B3CC;1103 1169 11AF; # (돌; 돌; 돌; 돌; 돌; ) HANGUL SYLLABLE DOL
+B3CD;B3CD;1103 1169 11B0;B3CD;1103 1169 11B0; # (돍; 돍; 돍; 돍; 돍; ) HANGUL SYLLABLE DOLG
+B3CE;B3CE;1103 1169 11B1;B3CE;1103 1169 11B1; # (돎; 돎; 돎; 돎; 돎; ) HANGUL SYLLABLE DOLM
+B3CF;B3CF;1103 1169 11B2;B3CF;1103 1169 11B2; # (돏; 돏; 돏; 돏; 돏; ) HANGUL SYLLABLE DOLB
+B3D0;B3D0;1103 1169 11B3;B3D0;1103 1169 11B3; # (돐; 돐; 돐; 돐; 돐; ) HANGUL SYLLABLE DOLS
+B3D1;B3D1;1103 1169 11B4;B3D1;1103 1169 11B4; # (돑; 돑; 돑; 돑; 돑; ) HANGUL SYLLABLE DOLT
+B3D2;B3D2;1103 1169 11B5;B3D2;1103 1169 11B5; # (돒; 돒; 돒; 돒; 돒; ) HANGUL SYLLABLE DOLP
+B3D3;B3D3;1103 1169 11B6;B3D3;1103 1169 11B6; # (돓; 돓; 돓; 돓; 돓; ) HANGUL SYLLABLE DOLH
+B3D4;B3D4;1103 1169 11B7;B3D4;1103 1169 11B7; # (돔; 돔; 돔; 돔; 돔; ) HANGUL SYLLABLE DOM
+B3D5;B3D5;1103 1169 11B8;B3D5;1103 1169 11B8; # (돕; 돕; 돕; 돕; 돕; ) HANGUL SYLLABLE DOB
+B3D6;B3D6;1103 1169 11B9;B3D6;1103 1169 11B9; # (돖; 돖; 돖; 돖; 돖; ) HANGUL SYLLABLE DOBS
+B3D7;B3D7;1103 1169 11BA;B3D7;1103 1169 11BA; # (돗; 돗; 돗; 돗; 돗; ) HANGUL SYLLABLE DOS
+B3D8;B3D8;1103 1169 11BB;B3D8;1103 1169 11BB; # (돘; 돘; 돘; 돘; 돘; ) HANGUL SYLLABLE DOSS
+B3D9;B3D9;1103 1169 11BC;B3D9;1103 1169 11BC; # (동; 동; 동; 동; 동; ) HANGUL SYLLABLE DONG
+B3DA;B3DA;1103 1169 11BD;B3DA;1103 1169 11BD; # (돚; 돚; 돚; 돚; 돚; ) HANGUL SYLLABLE DOJ
+B3DB;B3DB;1103 1169 11BE;B3DB;1103 1169 11BE; # (돛; 돛; 돛; 돛; 돛; ) HANGUL SYLLABLE DOC
+B3DC;B3DC;1103 1169 11BF;B3DC;1103 1169 11BF; # (돜; 돜; 돜; 돜; 돜; ) HANGUL SYLLABLE DOK
+B3DD;B3DD;1103 1169 11C0;B3DD;1103 1169 11C0; # (돝; 돝; 돝; 돝; 돝; ) HANGUL SYLLABLE DOT
+B3DE;B3DE;1103 1169 11C1;B3DE;1103 1169 11C1; # (돞; 돞; 돞; 돞; 돞; ) HANGUL SYLLABLE DOP
+B3DF;B3DF;1103 1169 11C2;B3DF;1103 1169 11C2; # (돟; 돟; 돟; 돟; 돟; ) HANGUL SYLLABLE DOH
+B3E0;B3E0;1103 116A;B3E0;1103 116A; # (돠; 돠; 돠; 돠; 돠; ) HANGUL SYLLABLE DWA
+B3E1;B3E1;1103 116A 11A8;B3E1;1103 116A 11A8; # (돡; 돡; 돡; 돡; 돡; ) HANGUL SYLLABLE DWAG
+B3E2;B3E2;1103 116A 11A9;B3E2;1103 116A 11A9; # (돢; 돢; 돢; 돢; 돢; ) HANGUL SYLLABLE DWAGG
+B3E3;B3E3;1103 116A 11AA;B3E3;1103 116A 11AA; # (돣; 돣; 돣; 돣; 돣; ) HANGUL SYLLABLE DWAGS
+B3E4;B3E4;1103 116A 11AB;B3E4;1103 116A 11AB; # (돤; 돤; 돤; 돤; 돤; ) HANGUL SYLLABLE DWAN
+B3E5;B3E5;1103 116A 11AC;B3E5;1103 116A 11AC; # (돥; 돥; 돥; 돥; 돥; ) HANGUL SYLLABLE DWANJ
+B3E6;B3E6;1103 116A 11AD;B3E6;1103 116A 11AD; # (돦; 돦; 돦; 돦; 돦; ) HANGUL SYLLABLE DWANH
+B3E7;B3E7;1103 116A 11AE;B3E7;1103 116A 11AE; # (돧; 돧; 돧; 돧; 돧; ) HANGUL SYLLABLE DWAD
+B3E8;B3E8;1103 116A 11AF;B3E8;1103 116A 11AF; # (돨; 돨; 돨; 돨; 돨; ) HANGUL SYLLABLE DWAL
+B3E9;B3E9;1103 116A 11B0;B3E9;1103 116A 11B0; # (돩; 돩; 돩; 돩; 돩; ) HANGUL SYLLABLE DWALG
+B3EA;B3EA;1103 116A 11B1;B3EA;1103 116A 11B1; # (돪; 돪; 돪; 돪; 돪; ) HANGUL SYLLABLE DWALM
+B3EB;B3EB;1103 116A 11B2;B3EB;1103 116A 11B2; # (돫; 돫; 돫; 돫; 돫; ) HANGUL SYLLABLE DWALB
+B3EC;B3EC;1103 116A 11B3;B3EC;1103 116A 11B3; # (돬; 돬; 돬; 돬; 돬; ) HANGUL SYLLABLE DWALS
+B3ED;B3ED;1103 116A 11B4;B3ED;1103 116A 11B4; # (돭; 돭; 돭; 돭; 돭; ) HANGUL SYLLABLE DWALT
+B3EE;B3EE;1103 116A 11B5;B3EE;1103 116A 11B5; # (돮; 돮; 돮; 돮; 돮; ) HANGUL SYLLABLE DWALP
+B3EF;B3EF;1103 116A 11B6;B3EF;1103 116A 11B6; # (돯; 돯; 돯; 돯; 돯; ) HANGUL SYLLABLE DWALH
+B3F0;B3F0;1103 116A 11B7;B3F0;1103 116A 11B7; # (돰; 돰; 돰; 돰; 돰; ) HANGUL SYLLABLE DWAM
+B3F1;B3F1;1103 116A 11B8;B3F1;1103 116A 11B8; # (돱; 돱; 돱; 돱; 돱; ) HANGUL SYLLABLE DWAB
+B3F2;B3F2;1103 116A 11B9;B3F2;1103 116A 11B9; # (돲; 돲; 돲; 돲; 돲; ) HANGUL SYLLABLE DWABS
+B3F3;B3F3;1103 116A 11BA;B3F3;1103 116A 11BA; # (돳; 돳; 돳; 돳; 돳; ) HANGUL SYLLABLE DWAS
+B3F4;B3F4;1103 116A 11BB;B3F4;1103 116A 11BB; # (돴; 돴; 돴; 돴; 돴; ) HANGUL SYLLABLE DWASS
+B3F5;B3F5;1103 116A 11BC;B3F5;1103 116A 11BC; # (돵; 돵; 돵; 돵; 돵; ) HANGUL SYLLABLE DWANG
+B3F6;B3F6;1103 116A 11BD;B3F6;1103 116A 11BD; # (돶; 돶; 돶; 돶; 돶; ) HANGUL SYLLABLE DWAJ
+B3F7;B3F7;1103 116A 11BE;B3F7;1103 116A 11BE; # (돷; 돷; 돷; 돷; 돷; ) HANGUL SYLLABLE DWAC
+B3F8;B3F8;1103 116A 11BF;B3F8;1103 116A 11BF; # (돸; 돸; 돸; 돸; 돸; ) HANGUL SYLLABLE DWAK
+B3F9;B3F9;1103 116A 11C0;B3F9;1103 116A 11C0; # (돹; 돹; 돹; 돹; 돹; ) HANGUL SYLLABLE DWAT
+B3FA;B3FA;1103 116A 11C1;B3FA;1103 116A 11C1; # (돺; 돺; 돺; 돺; 돺; ) HANGUL SYLLABLE DWAP
+B3FB;B3FB;1103 116A 11C2;B3FB;1103 116A 11C2; # (돻; 돻; 돻; 돻; 돻; ) HANGUL SYLLABLE DWAH
+B3FC;B3FC;1103 116B;B3FC;1103 116B; # (돼; 돼; 돼; 돼; 돼; ) HANGUL SYLLABLE DWAE
+B3FD;B3FD;1103 116B 11A8;B3FD;1103 116B 11A8; # (돽; 돽; 돽; 돽; 돽; ) HANGUL SYLLABLE DWAEG
+B3FE;B3FE;1103 116B 11A9;B3FE;1103 116B 11A9; # (돾; 돾; 돾; 돾; 돾; ) HANGUL SYLLABLE DWAEGG
+B3FF;B3FF;1103 116B 11AA;B3FF;1103 116B 11AA; # (돿; 돿; 돿; 돿; 돿; ) HANGUL SYLLABLE DWAEGS
+B400;B400;1103 116B 11AB;B400;1103 116B 11AB; # (됀; 됀; 됀; 됀; 됀; ) HANGUL SYLLABLE DWAEN
+B401;B401;1103 116B 11AC;B401;1103 116B 11AC; # (됁; 됁; 됁; 됁; 됁; ) HANGUL SYLLABLE DWAENJ
+B402;B402;1103 116B 11AD;B402;1103 116B 11AD; # (됂; 됂; 됂; 됂; 됂; ) HANGUL SYLLABLE DWAENH
+B403;B403;1103 116B 11AE;B403;1103 116B 11AE; # (됃; 됃; 됃; 됃; 됃; ) HANGUL SYLLABLE DWAED
+B404;B404;1103 116B 11AF;B404;1103 116B 11AF; # (됄; 됄; 됄; 됄; 됄; ) HANGUL SYLLABLE DWAEL
+B405;B405;1103 116B 11B0;B405;1103 116B 11B0; # (됅; 됅; 됅; 됅; 됅; ) HANGUL SYLLABLE DWAELG
+B406;B406;1103 116B 11B1;B406;1103 116B 11B1; # (됆; 됆; 됆; 됆; 됆; ) HANGUL SYLLABLE DWAELM
+B407;B407;1103 116B 11B2;B407;1103 116B 11B2; # (됇; 됇; 됇; 됇; 됇; ) HANGUL SYLLABLE DWAELB
+B408;B408;1103 116B 11B3;B408;1103 116B 11B3; # (됈; 됈; 됈; 됈; 됈; ) HANGUL SYLLABLE DWAELS
+B409;B409;1103 116B 11B4;B409;1103 116B 11B4; # (됉; 됉; 됉; 됉; 됉; ) HANGUL SYLLABLE DWAELT
+B40A;B40A;1103 116B 11B5;B40A;1103 116B 11B5; # (됊; 됊; 됊; 됊; 됊; ) HANGUL SYLLABLE DWAELP
+B40B;B40B;1103 116B 11B6;B40B;1103 116B 11B6; # (됋; 됋; 됋; 됋; 됋; ) HANGUL SYLLABLE DWAELH
+B40C;B40C;1103 116B 11B7;B40C;1103 116B 11B7; # (됌; 됌; 됌; 됌; 됌; ) HANGUL SYLLABLE DWAEM
+B40D;B40D;1103 116B 11B8;B40D;1103 116B 11B8; # (됍; 됍; 됍; 됍; 됍; ) HANGUL SYLLABLE DWAEB
+B40E;B40E;1103 116B 11B9;B40E;1103 116B 11B9; # (됎; 됎; 됎; 됎; 됎; ) HANGUL SYLLABLE DWAEBS
+B40F;B40F;1103 116B 11BA;B40F;1103 116B 11BA; # (됏; 됏; 됏; 됏; 됏; ) HANGUL SYLLABLE DWAES
+B410;B410;1103 116B 11BB;B410;1103 116B 11BB; # (됐; 됐; 됐; 됐; 됐; ) HANGUL SYLLABLE DWAESS
+B411;B411;1103 116B 11BC;B411;1103 116B 11BC; # (됑; 됑; 됑; 됑; 됑; ) HANGUL SYLLABLE DWAENG
+B412;B412;1103 116B 11BD;B412;1103 116B 11BD; # (됒; 됒; 됒; 됒; 됒; ) HANGUL SYLLABLE DWAEJ
+B413;B413;1103 116B 11BE;B413;1103 116B 11BE; # (됓; 됓; 됓; 됓; 됓; ) HANGUL SYLLABLE DWAEC
+B414;B414;1103 116B 11BF;B414;1103 116B 11BF; # (됔; 됔; 됔; 됔; 됔; ) HANGUL SYLLABLE DWAEK
+B415;B415;1103 116B 11C0;B415;1103 116B 11C0; # (됕; 됕; 됕; 됕; 됕; ) HANGUL SYLLABLE DWAET
+B416;B416;1103 116B 11C1;B416;1103 116B 11C1; # (됖; 됖; 됖; 됖; 됖; ) HANGUL SYLLABLE DWAEP
+B417;B417;1103 116B 11C2;B417;1103 116B 11C2; # (됗; 됗; 됗; 됗; 됗; ) HANGUL SYLLABLE DWAEH
+B418;B418;1103 116C;B418;1103 116C; # (되; 되; 되; 되; 되; ) HANGUL SYLLABLE DOE
+B419;B419;1103 116C 11A8;B419;1103 116C 11A8; # (됙; 됙; 됙; 됙; 됙; ) HANGUL SYLLABLE DOEG
+B41A;B41A;1103 116C 11A9;B41A;1103 116C 11A9; # (됚; 됚; 됚; 됚; 됚; ) HANGUL SYLLABLE DOEGG
+B41B;B41B;1103 116C 11AA;B41B;1103 116C 11AA; # (됛; 됛; 됛; 됛; 됛; ) HANGUL SYLLABLE DOEGS
+B41C;B41C;1103 116C 11AB;B41C;1103 116C 11AB; # (된; 된; 된; 된; 된; ) HANGUL SYLLABLE DOEN
+B41D;B41D;1103 116C 11AC;B41D;1103 116C 11AC; # (됝; 됝; 됝; 됝; 됝; ) HANGUL SYLLABLE DOENJ
+B41E;B41E;1103 116C 11AD;B41E;1103 116C 11AD; # (됞; 됞; 됞; 됞; 됞; ) HANGUL SYLLABLE DOENH
+B41F;B41F;1103 116C 11AE;B41F;1103 116C 11AE; # (됟; 됟; 됟; 됟; 됟; ) HANGUL SYLLABLE DOED
+B420;B420;1103 116C 11AF;B420;1103 116C 11AF; # (될; 될; 될; 될; 될; ) HANGUL SYLLABLE DOEL
+B421;B421;1103 116C 11B0;B421;1103 116C 11B0; # (됡; 됡; 됡; 됡; 됡; ) HANGUL SYLLABLE DOELG
+B422;B422;1103 116C 11B1;B422;1103 116C 11B1; # (됢; 됢; 됢; 됢; 됢; ) HANGUL SYLLABLE DOELM
+B423;B423;1103 116C 11B2;B423;1103 116C 11B2; # (됣; 됣; 됣; 됣; 됣; ) HANGUL SYLLABLE DOELB
+B424;B424;1103 116C 11B3;B424;1103 116C 11B3; # (됤; 됤; 됤; 됤; 됤; ) HANGUL SYLLABLE DOELS
+B425;B425;1103 116C 11B4;B425;1103 116C 11B4; # (됥; 됥; 됥; 됥; 됥; ) HANGUL SYLLABLE DOELT
+B426;B426;1103 116C 11B5;B426;1103 116C 11B5; # (됦; 됦; 됦; 됦; 됦; ) HANGUL SYLLABLE DOELP
+B427;B427;1103 116C 11B6;B427;1103 116C 11B6; # (됧; 됧; 됧; 됧; 됧; ) HANGUL SYLLABLE DOELH
+B428;B428;1103 116C 11B7;B428;1103 116C 11B7; # (됨; 됨; 됨; 됨; 됨; ) HANGUL SYLLABLE DOEM
+B429;B429;1103 116C 11B8;B429;1103 116C 11B8; # (됩; 됩; 됩; 됩; 됩; ) HANGUL SYLLABLE DOEB
+B42A;B42A;1103 116C 11B9;B42A;1103 116C 11B9; # (됪; 됪; 됪; 됪; 됪; ) HANGUL SYLLABLE DOEBS
+B42B;B42B;1103 116C 11BA;B42B;1103 116C 11BA; # (됫; 됫; 됫; 됫; 됫; ) HANGUL SYLLABLE DOES
+B42C;B42C;1103 116C 11BB;B42C;1103 116C 11BB; # (됬; 됬; 됬; 됬; 됬; ) HANGUL SYLLABLE DOESS
+B42D;B42D;1103 116C 11BC;B42D;1103 116C 11BC; # (됭; 됭; 됭; 됭; 됭; ) HANGUL SYLLABLE DOENG
+B42E;B42E;1103 116C 11BD;B42E;1103 116C 11BD; # (됮; 됮; 됮; 됮; 됮; ) HANGUL SYLLABLE DOEJ
+B42F;B42F;1103 116C 11BE;B42F;1103 116C 11BE; # (됯; 됯; 됯; 됯; 됯; ) HANGUL SYLLABLE DOEC
+B430;B430;1103 116C 11BF;B430;1103 116C 11BF; # (됰; 됰; 됰; 됰; 됰; ) HANGUL SYLLABLE DOEK
+B431;B431;1103 116C 11C0;B431;1103 116C 11C0; # (됱; 됱; 됱; 됱; 됱; ) HANGUL SYLLABLE DOET
+B432;B432;1103 116C 11C1;B432;1103 116C 11C1; # (됲; 됲; 됲; 됲; 됲; ) HANGUL SYLLABLE DOEP
+B433;B433;1103 116C 11C2;B433;1103 116C 11C2; # (됳; 됳; 됳; 됳; 됳; ) HANGUL SYLLABLE DOEH
+B434;B434;1103 116D;B434;1103 116D; # (됴; 됴; 됴; 됴; 됴; ) HANGUL SYLLABLE DYO
+B435;B435;1103 116D 11A8;B435;1103 116D 11A8; # (됵; 됵; 됵; 됵; 됵; ) HANGUL SYLLABLE DYOG
+B436;B436;1103 116D 11A9;B436;1103 116D 11A9; # (됶; 됶; 됶; 됶; 됶; ) HANGUL SYLLABLE DYOGG
+B437;B437;1103 116D 11AA;B437;1103 116D 11AA; # (됷; 됷; 됷; 됷; 됷; ) HANGUL SYLLABLE DYOGS
+B438;B438;1103 116D 11AB;B438;1103 116D 11AB; # (됸; 됸; 됸; 됸; 됸; ) HANGUL SYLLABLE DYON
+B439;B439;1103 116D 11AC;B439;1103 116D 11AC; # (됹; 됹; 됹; 됹; 됹; ) HANGUL SYLLABLE DYONJ
+B43A;B43A;1103 116D 11AD;B43A;1103 116D 11AD; # (됺; 됺; 됺; 됺; 됺; ) HANGUL SYLLABLE DYONH
+B43B;B43B;1103 116D 11AE;B43B;1103 116D 11AE; # (됻; 됻; 됻; 됻; 됻; ) HANGUL SYLLABLE DYOD
+B43C;B43C;1103 116D 11AF;B43C;1103 116D 11AF; # (됼; 됼; 됼; 됼; 됼; ) HANGUL SYLLABLE DYOL
+B43D;B43D;1103 116D 11B0;B43D;1103 116D 11B0; # (됽; 됽; 됽; 됽; 됽; ) HANGUL SYLLABLE DYOLG
+B43E;B43E;1103 116D 11B1;B43E;1103 116D 11B1; # (됾; 됾; 됾; 됾; 됾; ) HANGUL SYLLABLE DYOLM
+B43F;B43F;1103 116D 11B2;B43F;1103 116D 11B2; # (됿; 됿; 됿; 됿; 됿; ) HANGUL SYLLABLE DYOLB
+B440;B440;1103 116D 11B3;B440;1103 116D 11B3; # (둀; 둀; 둀; 둀; 둀; ) HANGUL SYLLABLE DYOLS
+B441;B441;1103 116D 11B4;B441;1103 116D 11B4; # (둁; 둁; 둁; 둁; 둁; ) HANGUL SYLLABLE DYOLT
+B442;B442;1103 116D 11B5;B442;1103 116D 11B5; # (둂; 둂; 둂; 둂; 둂; ) HANGUL SYLLABLE DYOLP
+B443;B443;1103 116D 11B6;B443;1103 116D 11B6; # (둃; 둃; 둃; 둃; 둃; ) HANGUL SYLLABLE DYOLH
+B444;B444;1103 116D 11B7;B444;1103 116D 11B7; # (둄; 둄; 둄; 둄; 둄; ) HANGUL SYLLABLE DYOM
+B445;B445;1103 116D 11B8;B445;1103 116D 11B8; # (둅; 둅; 둅; 둅; 둅; ) HANGUL SYLLABLE DYOB
+B446;B446;1103 116D 11B9;B446;1103 116D 11B9; # (둆; 둆; 둆; 둆; 둆; ) HANGUL SYLLABLE DYOBS
+B447;B447;1103 116D 11BA;B447;1103 116D 11BA; # (둇; 둇; 둇; 둇; 둇; ) HANGUL SYLLABLE DYOS
+B448;B448;1103 116D 11BB;B448;1103 116D 11BB; # (둈; 둈; 둈; 둈; 둈; ) HANGUL SYLLABLE DYOSS
+B449;B449;1103 116D 11BC;B449;1103 116D 11BC; # (둉; 둉; 둉; 둉; 둉; ) HANGUL SYLLABLE DYONG
+B44A;B44A;1103 116D 11BD;B44A;1103 116D 11BD; # (둊; 둊; 둊; 둊; 둊; ) HANGUL SYLLABLE DYOJ
+B44B;B44B;1103 116D 11BE;B44B;1103 116D 11BE; # (둋; 둋; 둋; 둋; 둋; ) HANGUL SYLLABLE DYOC
+B44C;B44C;1103 116D 11BF;B44C;1103 116D 11BF; # (둌; 둌; 둌; 둌; 둌; ) HANGUL SYLLABLE DYOK
+B44D;B44D;1103 116D 11C0;B44D;1103 116D 11C0; # (둍; 둍; 둍; 둍; 둍; ) HANGUL SYLLABLE DYOT
+B44E;B44E;1103 116D 11C1;B44E;1103 116D 11C1; # (둎; 둎; 둎; 둎; 둎; ) HANGUL SYLLABLE DYOP
+B44F;B44F;1103 116D 11C2;B44F;1103 116D 11C2; # (둏; 둏; 둏; 둏; 둏; ) HANGUL SYLLABLE DYOH
+B450;B450;1103 116E;B450;1103 116E; # (두; 두; 두; 두; 두; ) HANGUL SYLLABLE DU
+B451;B451;1103 116E 11A8;B451;1103 116E 11A8; # (둑; 둑; 둑; 둑; 둑; ) HANGUL SYLLABLE DUG
+B452;B452;1103 116E 11A9;B452;1103 116E 11A9; # (둒; 둒; 둒; 둒; 둒; ) HANGUL SYLLABLE DUGG
+B453;B453;1103 116E 11AA;B453;1103 116E 11AA; # (둓; 둓; 둓; 둓; 둓; ) HANGUL SYLLABLE DUGS
+B454;B454;1103 116E 11AB;B454;1103 116E 11AB; # (둔; 둔; 둔; 둔; 둔; ) HANGUL SYLLABLE DUN
+B455;B455;1103 116E 11AC;B455;1103 116E 11AC; # (둕; 둕; 둕; 둕; 둕; ) HANGUL SYLLABLE DUNJ
+B456;B456;1103 116E 11AD;B456;1103 116E 11AD; # (둖; 둖; 둖; 둖; 둖; ) HANGUL SYLLABLE DUNH
+B457;B457;1103 116E 11AE;B457;1103 116E 11AE; # (둗; 둗; 둗; 둗; 둗; ) HANGUL SYLLABLE DUD
+B458;B458;1103 116E 11AF;B458;1103 116E 11AF; # (둘; 둘; 둘; 둘; 둘; ) HANGUL SYLLABLE DUL
+B459;B459;1103 116E 11B0;B459;1103 116E 11B0; # (둙; 둙; 둙; 둙; 둙; ) HANGUL SYLLABLE DULG
+B45A;B45A;1103 116E 11B1;B45A;1103 116E 11B1; # (둚; 둚; 둚; 둚; 둚; ) HANGUL SYLLABLE DULM
+B45B;B45B;1103 116E 11B2;B45B;1103 116E 11B2; # (둛; 둛; 둛; 둛; 둛; ) HANGUL SYLLABLE DULB
+B45C;B45C;1103 116E 11B3;B45C;1103 116E 11B3; # (둜; 둜; 둜; 둜; 둜; ) HANGUL SYLLABLE DULS
+B45D;B45D;1103 116E 11B4;B45D;1103 116E 11B4; # (둝; 둝; 둝; 둝; 둝; ) HANGUL SYLLABLE DULT
+B45E;B45E;1103 116E 11B5;B45E;1103 116E 11B5; # (둞; 둞; 둞; 둞; 둞; ) HANGUL SYLLABLE DULP
+B45F;B45F;1103 116E 11B6;B45F;1103 116E 11B6; # (둟; 둟; 둟; 둟; 둟; ) HANGUL SYLLABLE DULH
+B460;B460;1103 116E 11B7;B460;1103 116E 11B7; # (둠; 둠; 둠; 둠; 둠; ) HANGUL SYLLABLE DUM
+B461;B461;1103 116E 11B8;B461;1103 116E 11B8; # (둡; 둡; 둡; 둡; 둡; ) HANGUL SYLLABLE DUB
+B462;B462;1103 116E 11B9;B462;1103 116E 11B9; # (둢; 둢; 둢; 둢; 둢; ) HANGUL SYLLABLE DUBS
+B463;B463;1103 116E 11BA;B463;1103 116E 11BA; # (둣; 둣; 둣; 둣; 둣; ) HANGUL SYLLABLE DUS
+B464;B464;1103 116E 11BB;B464;1103 116E 11BB; # (둤; 둤; 둤; 둤; 둤; ) HANGUL SYLLABLE DUSS
+B465;B465;1103 116E 11BC;B465;1103 116E 11BC; # (둥; 둥; 둥; 둥; 둥; ) HANGUL SYLLABLE DUNG
+B466;B466;1103 116E 11BD;B466;1103 116E 11BD; # (둦; 둦; 둦; 둦; 둦; ) HANGUL SYLLABLE DUJ
+B467;B467;1103 116E 11BE;B467;1103 116E 11BE; # (둧; 둧; 둧; 둧; 둧; ) HANGUL SYLLABLE DUC
+B468;B468;1103 116E 11BF;B468;1103 116E 11BF; # (둨; 둨; 둨; 둨; 둨; ) HANGUL SYLLABLE DUK
+B469;B469;1103 116E 11C0;B469;1103 116E 11C0; # (둩; 둩; 둩; 둩; 둩; ) HANGUL SYLLABLE DUT
+B46A;B46A;1103 116E 11C1;B46A;1103 116E 11C1; # (둪; 둪; 둪; 둪; 둪; ) HANGUL SYLLABLE DUP
+B46B;B46B;1103 116E 11C2;B46B;1103 116E 11C2; # (둫; 둫; 둫; 둫; 둫; ) HANGUL SYLLABLE DUH
+B46C;B46C;1103 116F;B46C;1103 116F; # (둬; 둬; 둬; 둬; 둬; ) HANGUL SYLLABLE DWEO
+B46D;B46D;1103 116F 11A8;B46D;1103 116F 11A8; # (둭; 둭; 둭; 둭; 둭; ) HANGUL SYLLABLE DWEOG
+B46E;B46E;1103 116F 11A9;B46E;1103 116F 11A9; # (둮; 둮; 둮; 둮; 둮; ) HANGUL SYLLABLE DWEOGG
+B46F;B46F;1103 116F 11AA;B46F;1103 116F 11AA; # (둯; 둯; 둯; 둯; 둯; ) HANGUL SYLLABLE DWEOGS
+B470;B470;1103 116F 11AB;B470;1103 116F 11AB; # (둰; 둰; 둰; 둰; 둰; ) HANGUL SYLLABLE DWEON
+B471;B471;1103 116F 11AC;B471;1103 116F 11AC; # (둱; 둱; 둱; 둱; 둱; ) HANGUL SYLLABLE DWEONJ
+B472;B472;1103 116F 11AD;B472;1103 116F 11AD; # (둲; 둲; 둲; 둲; 둲; ) HANGUL SYLLABLE DWEONH
+B473;B473;1103 116F 11AE;B473;1103 116F 11AE; # (둳; 둳; 둳; 둳; 둳; ) HANGUL SYLLABLE DWEOD
+B474;B474;1103 116F 11AF;B474;1103 116F 11AF; # (둴; 둴; 둴; 둴; 둴; ) HANGUL SYLLABLE DWEOL
+B475;B475;1103 116F 11B0;B475;1103 116F 11B0; # (둵; 둵; 둵; 둵; 둵; ) HANGUL SYLLABLE DWEOLG
+B476;B476;1103 116F 11B1;B476;1103 116F 11B1; # (둶; 둶; 둶; 둶; 둶; ) HANGUL SYLLABLE DWEOLM
+B477;B477;1103 116F 11B2;B477;1103 116F 11B2; # (둷; 둷; 둷; 둷; 둷; ) HANGUL SYLLABLE DWEOLB
+B478;B478;1103 116F 11B3;B478;1103 116F 11B3; # (둸; 둸; 둸; 둸; 둸; ) HANGUL SYLLABLE DWEOLS
+B479;B479;1103 116F 11B4;B479;1103 116F 11B4; # (둹; 둹; 둹; 둹; 둹; ) HANGUL SYLLABLE DWEOLT
+B47A;B47A;1103 116F 11B5;B47A;1103 116F 11B5; # (둺; 둺; 둺; 둺; 둺; ) HANGUL SYLLABLE DWEOLP
+B47B;B47B;1103 116F 11B6;B47B;1103 116F 11B6; # (둻; 둻; 둻; 둻; 둻; ) HANGUL SYLLABLE DWEOLH
+B47C;B47C;1103 116F 11B7;B47C;1103 116F 11B7; # (둼; 둼; 둼; 둼; 둼; ) HANGUL SYLLABLE DWEOM
+B47D;B47D;1103 116F 11B8;B47D;1103 116F 11B8; # (둽; 둽; 둽; 둽; 둽; ) HANGUL SYLLABLE DWEOB
+B47E;B47E;1103 116F 11B9;B47E;1103 116F 11B9; # (둾; 둾; 둾; 둾; 둾; ) HANGUL SYLLABLE DWEOBS
+B47F;B47F;1103 116F 11BA;B47F;1103 116F 11BA; # (둿; 둿; 둿; 둿; 둿; ) HANGUL SYLLABLE DWEOS
+B480;B480;1103 116F 11BB;B480;1103 116F 11BB; # (뒀; 뒀; 뒀; 뒀; 뒀; ) HANGUL SYLLABLE DWEOSS
+B481;B481;1103 116F 11BC;B481;1103 116F 11BC; # (뒁; 뒁; 뒁; 뒁; 뒁; ) HANGUL SYLLABLE DWEONG
+B482;B482;1103 116F 11BD;B482;1103 116F 11BD; # (뒂; 뒂; 뒂; 뒂; 뒂; ) HANGUL SYLLABLE DWEOJ
+B483;B483;1103 116F 11BE;B483;1103 116F 11BE; # (뒃; 뒃; 뒃; 뒃; 뒃; ) HANGUL SYLLABLE DWEOC
+B484;B484;1103 116F 11BF;B484;1103 116F 11BF; # (뒄; 뒄; 뒄; 뒄; 뒄; ) HANGUL SYLLABLE DWEOK
+B485;B485;1103 116F 11C0;B485;1103 116F 11C0; # (뒅; 뒅; 뒅; 뒅; 뒅; ) HANGUL SYLLABLE DWEOT
+B486;B486;1103 116F 11C1;B486;1103 116F 11C1; # (뒆; 뒆; 뒆; 뒆; 뒆; ) HANGUL SYLLABLE DWEOP
+B487;B487;1103 116F 11C2;B487;1103 116F 11C2; # (뒇; 뒇; 뒇; 뒇; 뒇; ) HANGUL SYLLABLE DWEOH
+B488;B488;1103 1170;B488;1103 1170; # (뒈; 뒈; 뒈; 뒈; 뒈; ) HANGUL SYLLABLE DWE
+B489;B489;1103 1170 11A8;B489;1103 1170 11A8; # (뒉; 뒉; 뒉; 뒉; 뒉; ) HANGUL SYLLABLE DWEG
+B48A;B48A;1103 1170 11A9;B48A;1103 1170 11A9; # (뒊; 뒊; 뒊; 뒊; 뒊; ) HANGUL SYLLABLE DWEGG
+B48B;B48B;1103 1170 11AA;B48B;1103 1170 11AA; # (뒋; 뒋; 뒋; 뒋; 뒋; ) HANGUL SYLLABLE DWEGS
+B48C;B48C;1103 1170 11AB;B48C;1103 1170 11AB; # (뒌; 뒌; 뒌; 뒌; 뒌; ) HANGUL SYLLABLE DWEN
+B48D;B48D;1103 1170 11AC;B48D;1103 1170 11AC; # (뒍; 뒍; 뒍; 뒍; 뒍; ) HANGUL SYLLABLE DWENJ
+B48E;B48E;1103 1170 11AD;B48E;1103 1170 11AD; # (뒎; 뒎; 뒎; 뒎; 뒎; ) HANGUL SYLLABLE DWENH
+B48F;B48F;1103 1170 11AE;B48F;1103 1170 11AE; # (뒏; 뒏; 뒏; 뒏; 뒏; ) HANGUL SYLLABLE DWED
+B490;B490;1103 1170 11AF;B490;1103 1170 11AF; # (뒐; 뒐; 뒐; 뒐; 뒐; ) HANGUL SYLLABLE DWEL
+B491;B491;1103 1170 11B0;B491;1103 1170 11B0; # (뒑; 뒑; 뒑; 뒑; 뒑; ) HANGUL SYLLABLE DWELG
+B492;B492;1103 1170 11B1;B492;1103 1170 11B1; # (뒒; 뒒; 뒒; 뒒; 뒒; ) HANGUL SYLLABLE DWELM
+B493;B493;1103 1170 11B2;B493;1103 1170 11B2; # (뒓; 뒓; 뒓; 뒓; 뒓; ) HANGUL SYLLABLE DWELB
+B494;B494;1103 1170 11B3;B494;1103 1170 11B3; # (뒔; 뒔; 뒔; 뒔; 뒔; ) HANGUL SYLLABLE DWELS
+B495;B495;1103 1170 11B4;B495;1103 1170 11B4; # (뒕; 뒕; 뒕; 뒕; 뒕; ) HANGUL SYLLABLE DWELT
+B496;B496;1103 1170 11B5;B496;1103 1170 11B5; # (뒖; 뒖; 뒖; 뒖; 뒖; ) HANGUL SYLLABLE DWELP
+B497;B497;1103 1170 11B6;B497;1103 1170 11B6; # (뒗; 뒗; 뒗; 뒗; 뒗; ) HANGUL SYLLABLE DWELH
+B498;B498;1103 1170 11B7;B498;1103 1170 11B7; # (뒘; 뒘; 뒘; 뒘; 뒘; ) HANGUL SYLLABLE DWEM
+B499;B499;1103 1170 11B8;B499;1103 1170 11B8; # (뒙; 뒙; 뒙; 뒙; 뒙; ) HANGUL SYLLABLE DWEB
+B49A;B49A;1103 1170 11B9;B49A;1103 1170 11B9; # (뒚; 뒚; 뒚; 뒚; 뒚; ) HANGUL SYLLABLE DWEBS
+B49B;B49B;1103 1170 11BA;B49B;1103 1170 11BA; # (뒛; 뒛; 뒛; 뒛; 뒛; ) HANGUL SYLLABLE DWES
+B49C;B49C;1103 1170 11BB;B49C;1103 1170 11BB; # (뒜; 뒜; 뒜; 뒜; 뒜; ) HANGUL SYLLABLE DWESS
+B49D;B49D;1103 1170 11BC;B49D;1103 1170 11BC; # (뒝; 뒝; 뒝; 뒝; 뒝; ) HANGUL SYLLABLE DWENG
+B49E;B49E;1103 1170 11BD;B49E;1103 1170 11BD; # (뒞; 뒞; 뒞; 뒞; 뒞; ) HANGUL SYLLABLE DWEJ
+B49F;B49F;1103 1170 11BE;B49F;1103 1170 11BE; # (뒟; 뒟; 뒟; 뒟; 뒟; ) HANGUL SYLLABLE DWEC
+B4A0;B4A0;1103 1170 11BF;B4A0;1103 1170 11BF; # (뒠; 뒠; 뒠; 뒠; 뒠; ) HANGUL SYLLABLE DWEK
+B4A1;B4A1;1103 1170 11C0;B4A1;1103 1170 11C0; # (뒡; 뒡; 뒡; 뒡; 뒡; ) HANGUL SYLLABLE DWET
+B4A2;B4A2;1103 1170 11C1;B4A2;1103 1170 11C1; # (뒢; 뒢; 뒢; 뒢; 뒢; ) HANGUL SYLLABLE DWEP
+B4A3;B4A3;1103 1170 11C2;B4A3;1103 1170 11C2; # (뒣; 뒣; 뒣; 뒣; 뒣; ) HANGUL SYLLABLE DWEH
+B4A4;B4A4;1103 1171;B4A4;1103 1171; # (뒤; 뒤; 뒤; 뒤; 뒤; ) HANGUL SYLLABLE DWI
+B4A5;B4A5;1103 1171 11A8;B4A5;1103 1171 11A8; # (뒥; 뒥; 뒥; 뒥; 뒥; ) HANGUL SYLLABLE DWIG
+B4A6;B4A6;1103 1171 11A9;B4A6;1103 1171 11A9; # (뒦; 뒦; 뒦; 뒦; 뒦; ) HANGUL SYLLABLE DWIGG
+B4A7;B4A7;1103 1171 11AA;B4A7;1103 1171 11AA; # (뒧; 뒧; 뒧; 뒧; 뒧; ) HANGUL SYLLABLE DWIGS
+B4A8;B4A8;1103 1171 11AB;B4A8;1103 1171 11AB; # (뒨; 뒨; 뒨; 뒨; 뒨; ) HANGUL SYLLABLE DWIN
+B4A9;B4A9;1103 1171 11AC;B4A9;1103 1171 11AC; # (뒩; 뒩; 뒩; 뒩; 뒩; ) HANGUL SYLLABLE DWINJ
+B4AA;B4AA;1103 1171 11AD;B4AA;1103 1171 11AD; # (뒪; 뒪; 뒪; 뒪; 뒪; ) HANGUL SYLLABLE DWINH
+B4AB;B4AB;1103 1171 11AE;B4AB;1103 1171 11AE; # (뒫; 뒫; 뒫; 뒫; 뒫; ) HANGUL SYLLABLE DWID
+B4AC;B4AC;1103 1171 11AF;B4AC;1103 1171 11AF; # (뒬; 뒬; 뒬; 뒬; 뒬; ) HANGUL SYLLABLE DWIL
+B4AD;B4AD;1103 1171 11B0;B4AD;1103 1171 11B0; # (뒭; 뒭; 뒭; 뒭; 뒭; ) HANGUL SYLLABLE DWILG
+B4AE;B4AE;1103 1171 11B1;B4AE;1103 1171 11B1; # (뒮; 뒮; 뒮; 뒮; 뒮; ) HANGUL SYLLABLE DWILM
+B4AF;B4AF;1103 1171 11B2;B4AF;1103 1171 11B2; # (뒯; 뒯; 뒯; 뒯; 뒯; ) HANGUL SYLLABLE DWILB
+B4B0;B4B0;1103 1171 11B3;B4B0;1103 1171 11B3; # (뒰; 뒰; 뒰; 뒰; 뒰; ) HANGUL SYLLABLE DWILS
+B4B1;B4B1;1103 1171 11B4;B4B1;1103 1171 11B4; # (뒱; 뒱; 뒱; 뒱; 뒱; ) HANGUL SYLLABLE DWILT
+B4B2;B4B2;1103 1171 11B5;B4B2;1103 1171 11B5; # (뒲; 뒲; 뒲; 뒲; 뒲; ) HANGUL SYLLABLE DWILP
+B4B3;B4B3;1103 1171 11B6;B4B3;1103 1171 11B6; # (뒳; 뒳; 뒳; 뒳; 뒳; ) HANGUL SYLLABLE DWILH
+B4B4;B4B4;1103 1171 11B7;B4B4;1103 1171 11B7; # (뒴; 뒴; 뒴; 뒴; 뒴; ) HANGUL SYLLABLE DWIM
+B4B5;B4B5;1103 1171 11B8;B4B5;1103 1171 11B8; # (뒵; 뒵; 뒵; 뒵; 뒵; ) HANGUL SYLLABLE DWIB
+B4B6;B4B6;1103 1171 11B9;B4B6;1103 1171 11B9; # (뒶; 뒶; 뒶; 뒶; 뒶; ) HANGUL SYLLABLE DWIBS
+B4B7;B4B7;1103 1171 11BA;B4B7;1103 1171 11BA; # (뒷; 뒷; 뒷; 뒷; 뒷; ) HANGUL SYLLABLE DWIS
+B4B8;B4B8;1103 1171 11BB;B4B8;1103 1171 11BB; # (뒸; 뒸; 뒸; 뒸; 뒸; ) HANGUL SYLLABLE DWISS
+B4B9;B4B9;1103 1171 11BC;B4B9;1103 1171 11BC; # (뒹; 뒹; 뒹; 뒹; 뒹; ) HANGUL SYLLABLE DWING
+B4BA;B4BA;1103 1171 11BD;B4BA;1103 1171 11BD; # (뒺; 뒺; 뒺; 뒺; 뒺; ) HANGUL SYLLABLE DWIJ
+B4BB;B4BB;1103 1171 11BE;B4BB;1103 1171 11BE; # (뒻; 뒻; 뒻; 뒻; 뒻; ) HANGUL SYLLABLE DWIC
+B4BC;B4BC;1103 1171 11BF;B4BC;1103 1171 11BF; # (뒼; 뒼; 뒼; 뒼; 뒼; ) HANGUL SYLLABLE DWIK
+B4BD;B4BD;1103 1171 11C0;B4BD;1103 1171 11C0; # (뒽; 뒽; 뒽; 뒽; 뒽; ) HANGUL SYLLABLE DWIT
+B4BE;B4BE;1103 1171 11C1;B4BE;1103 1171 11C1; # (뒾; 뒾; 뒾; 뒾; 뒾; ) HANGUL SYLLABLE DWIP
+B4BF;B4BF;1103 1171 11C2;B4BF;1103 1171 11C2; # (뒿; 뒿; 뒿; 뒿; 뒿; ) HANGUL SYLLABLE DWIH
+B4C0;B4C0;1103 1172;B4C0;1103 1172; # (듀; 듀; 듀; 듀; 듀; ) HANGUL SYLLABLE DYU
+B4C1;B4C1;1103 1172 11A8;B4C1;1103 1172 11A8; # (듁; 듁; 듁; 듁; 듁; ) HANGUL SYLLABLE DYUG
+B4C2;B4C2;1103 1172 11A9;B4C2;1103 1172 11A9; # (듂; 듂; 듂; 듂; 듂; ) HANGUL SYLLABLE DYUGG
+B4C3;B4C3;1103 1172 11AA;B4C3;1103 1172 11AA; # (듃; 듃; 듃; 듃; 듃; ) HANGUL SYLLABLE DYUGS
+B4C4;B4C4;1103 1172 11AB;B4C4;1103 1172 11AB; # (듄; 듄; 듄; 듄; 듄; ) HANGUL SYLLABLE DYUN
+B4C5;B4C5;1103 1172 11AC;B4C5;1103 1172 11AC; # (듅; 듅; 듅; 듅; 듅; ) HANGUL SYLLABLE DYUNJ
+B4C6;B4C6;1103 1172 11AD;B4C6;1103 1172 11AD; # (듆; 듆; 듆; 듆; 듆; ) HANGUL SYLLABLE DYUNH
+B4C7;B4C7;1103 1172 11AE;B4C7;1103 1172 11AE; # (듇; 듇; 듇; 듇; 듇; ) HANGUL SYLLABLE DYUD
+B4C8;B4C8;1103 1172 11AF;B4C8;1103 1172 11AF; # (듈; 듈; 듈; 듈; 듈; ) HANGUL SYLLABLE DYUL
+B4C9;B4C9;1103 1172 11B0;B4C9;1103 1172 11B0; # (듉; 듉; 듉; 듉; 듉; ) HANGUL SYLLABLE DYULG
+B4CA;B4CA;1103 1172 11B1;B4CA;1103 1172 11B1; # (듊; 듊; 듊; 듊; 듊; ) HANGUL SYLLABLE DYULM
+B4CB;B4CB;1103 1172 11B2;B4CB;1103 1172 11B2; # (듋; 듋; 듋; 듋; 듋; ) HANGUL SYLLABLE DYULB
+B4CC;B4CC;1103 1172 11B3;B4CC;1103 1172 11B3; # (듌; 듌; 듌; 듌; 듌; ) HANGUL SYLLABLE DYULS
+B4CD;B4CD;1103 1172 11B4;B4CD;1103 1172 11B4; # (듍; 듍; 듍; 듍; 듍; ) HANGUL SYLLABLE DYULT
+B4CE;B4CE;1103 1172 11B5;B4CE;1103 1172 11B5; # (듎; 듎; 듎; 듎; 듎; ) HANGUL SYLLABLE DYULP
+B4CF;B4CF;1103 1172 11B6;B4CF;1103 1172 11B6; # (듏; 듏; 듏; 듏; 듏; ) HANGUL SYLLABLE DYULH
+B4D0;B4D0;1103 1172 11B7;B4D0;1103 1172 11B7; # (듐; 듐; 듐; 듐; 듐; ) HANGUL SYLLABLE DYUM
+B4D1;B4D1;1103 1172 11B8;B4D1;1103 1172 11B8; # (듑; 듑; 듑; 듑; 듑; ) HANGUL SYLLABLE DYUB
+B4D2;B4D2;1103 1172 11B9;B4D2;1103 1172 11B9; # (듒; 듒; 듒; 듒; 듒; ) HANGUL SYLLABLE DYUBS
+B4D3;B4D3;1103 1172 11BA;B4D3;1103 1172 11BA; # (듓; 듓; 듓; 듓; 듓; ) HANGUL SYLLABLE DYUS
+B4D4;B4D4;1103 1172 11BB;B4D4;1103 1172 11BB; # (듔; 듔; 듔; 듔; 듔; ) HANGUL SYLLABLE DYUSS
+B4D5;B4D5;1103 1172 11BC;B4D5;1103 1172 11BC; # (듕; 듕; 듕; 듕; 듕; ) HANGUL SYLLABLE DYUNG
+B4D6;B4D6;1103 1172 11BD;B4D6;1103 1172 11BD; # (듖; 듖; 듖; 듖; 듖; ) HANGUL SYLLABLE DYUJ
+B4D7;B4D7;1103 1172 11BE;B4D7;1103 1172 11BE; # (듗; 듗; 듗; 듗; 듗; ) HANGUL SYLLABLE DYUC
+B4D8;B4D8;1103 1172 11BF;B4D8;1103 1172 11BF; # (듘; 듘; 듘; 듘; 듘; ) HANGUL SYLLABLE DYUK
+B4D9;B4D9;1103 1172 11C0;B4D9;1103 1172 11C0; # (듙; 듙; 듙; 듙; 듙; ) HANGUL SYLLABLE DYUT
+B4DA;B4DA;1103 1172 11C1;B4DA;1103 1172 11C1; # (듚; 듚; 듚; 듚; 듚; ) HANGUL SYLLABLE DYUP
+B4DB;B4DB;1103 1172 11C2;B4DB;1103 1172 11C2; # (듛; 듛; 듛; 듛; 듛; ) HANGUL SYLLABLE DYUH
+B4DC;B4DC;1103 1173;B4DC;1103 1173; # (드; 드; 드; 드; 드; ) HANGUL SYLLABLE DEU
+B4DD;B4DD;1103 1173 11A8;B4DD;1103 1173 11A8; # (득; 득; 득; 득; 득; ) HANGUL SYLLABLE DEUG
+B4DE;B4DE;1103 1173 11A9;B4DE;1103 1173 11A9; # (듞; 듞; 듞; 듞; 듞; ) HANGUL SYLLABLE DEUGG
+B4DF;B4DF;1103 1173 11AA;B4DF;1103 1173 11AA; # (듟; 듟; 듟; 듟; 듟; ) HANGUL SYLLABLE DEUGS
+B4E0;B4E0;1103 1173 11AB;B4E0;1103 1173 11AB; # (든; 든; 든; 든; 든; ) HANGUL SYLLABLE DEUN
+B4E1;B4E1;1103 1173 11AC;B4E1;1103 1173 11AC; # (듡; 듡; 듡; 듡; 듡; ) HANGUL SYLLABLE DEUNJ
+B4E2;B4E2;1103 1173 11AD;B4E2;1103 1173 11AD; # (듢; 듢; 듢; 듢; 듢; ) HANGUL SYLLABLE DEUNH
+B4E3;B4E3;1103 1173 11AE;B4E3;1103 1173 11AE; # (듣; 듣; 듣; 듣; 듣; ) HANGUL SYLLABLE DEUD
+B4E4;B4E4;1103 1173 11AF;B4E4;1103 1173 11AF; # (들; 들; 들; 들; 들; ) HANGUL SYLLABLE DEUL
+B4E5;B4E5;1103 1173 11B0;B4E5;1103 1173 11B0; # (듥; 듥; 듥; 듥; 듥; ) HANGUL SYLLABLE DEULG
+B4E6;B4E6;1103 1173 11B1;B4E6;1103 1173 11B1; # (듦; 듦; 듦; 듦; 듦; ) HANGUL SYLLABLE DEULM
+B4E7;B4E7;1103 1173 11B2;B4E7;1103 1173 11B2; # (듧; 듧; 듧; 듧; 듧; ) HANGUL SYLLABLE DEULB
+B4E8;B4E8;1103 1173 11B3;B4E8;1103 1173 11B3; # (듨; 듨; 듨; 듨; 듨; ) HANGUL SYLLABLE DEULS
+B4E9;B4E9;1103 1173 11B4;B4E9;1103 1173 11B4; # (듩; 듩; 듩; 듩; 듩; ) HANGUL SYLLABLE DEULT
+B4EA;B4EA;1103 1173 11B5;B4EA;1103 1173 11B5; # (듪; 듪; 듪; 듪; 듪; ) HANGUL SYLLABLE DEULP
+B4EB;B4EB;1103 1173 11B6;B4EB;1103 1173 11B6; # (듫; 듫; 듫; 듫; 듫; ) HANGUL SYLLABLE DEULH
+B4EC;B4EC;1103 1173 11B7;B4EC;1103 1173 11B7; # (듬; 듬; 듬; 듬; 듬; ) HANGUL SYLLABLE DEUM
+B4ED;B4ED;1103 1173 11B8;B4ED;1103 1173 11B8; # (듭; 듭; 듭; 듭; 듭; ) HANGUL SYLLABLE DEUB
+B4EE;B4EE;1103 1173 11B9;B4EE;1103 1173 11B9; # (듮; 듮; 듮; 듮; 듮; ) HANGUL SYLLABLE DEUBS
+B4EF;B4EF;1103 1173 11BA;B4EF;1103 1173 11BA; # (듯; 듯; 듯; 듯; 듯; ) HANGUL SYLLABLE DEUS
+B4F0;B4F0;1103 1173 11BB;B4F0;1103 1173 11BB; # (듰; 듰; 듰; 듰; 듰; ) HANGUL SYLLABLE DEUSS
+B4F1;B4F1;1103 1173 11BC;B4F1;1103 1173 11BC; # (등; 등; 등; 등; 등; ) HANGUL SYLLABLE DEUNG
+B4F2;B4F2;1103 1173 11BD;B4F2;1103 1173 11BD; # (듲; 듲; 듲; 듲; 듲; ) HANGUL SYLLABLE DEUJ
+B4F3;B4F3;1103 1173 11BE;B4F3;1103 1173 11BE; # (듳; 듳; 듳; 듳; 듳; ) HANGUL SYLLABLE DEUC
+B4F4;B4F4;1103 1173 11BF;B4F4;1103 1173 11BF; # (듴; 듴; 듴; 듴; 듴; ) HANGUL SYLLABLE DEUK
+B4F5;B4F5;1103 1173 11C0;B4F5;1103 1173 11C0; # (듵; 듵; 듵; 듵; 듵; ) HANGUL SYLLABLE DEUT
+B4F6;B4F6;1103 1173 11C1;B4F6;1103 1173 11C1; # (듶; 듶; 듶; 듶; 듶; ) HANGUL SYLLABLE DEUP
+B4F7;B4F7;1103 1173 11C2;B4F7;1103 1173 11C2; # (듷; 듷; 듷; 듷; 듷; ) HANGUL SYLLABLE DEUH
+B4F8;B4F8;1103 1174;B4F8;1103 1174; # (듸; 듸; 듸; 듸; 듸; ) HANGUL SYLLABLE DYI
+B4F9;B4F9;1103 1174 11A8;B4F9;1103 1174 11A8; # (듹; 듹; 듹; 듹; 듹; ) HANGUL SYLLABLE DYIG
+B4FA;B4FA;1103 1174 11A9;B4FA;1103 1174 11A9; # (듺; 듺; 듺; 듺; 듺; ) HANGUL SYLLABLE DYIGG
+B4FB;B4FB;1103 1174 11AA;B4FB;1103 1174 11AA; # (듻; 듻; 듻; 듻; 듻; ) HANGUL SYLLABLE DYIGS
+B4FC;B4FC;1103 1174 11AB;B4FC;1103 1174 11AB; # (듼; 듼; 듼; 듼; 듼; ) HANGUL SYLLABLE DYIN
+B4FD;B4FD;1103 1174 11AC;B4FD;1103 1174 11AC; # (듽; 듽; 듽; 듽; 듽; ) HANGUL SYLLABLE DYINJ
+B4FE;B4FE;1103 1174 11AD;B4FE;1103 1174 11AD; # (듾; 듾; 듾; 듾; 듾; ) HANGUL SYLLABLE DYINH
+B4FF;B4FF;1103 1174 11AE;B4FF;1103 1174 11AE; # (듿; 듿; 듿; 듿; 듿; ) HANGUL SYLLABLE DYID
+B500;B500;1103 1174 11AF;B500;1103 1174 11AF; # (딀; 딀; 딀; 딀; 딀; ) HANGUL SYLLABLE DYIL
+B501;B501;1103 1174 11B0;B501;1103 1174 11B0; # (딁; 딁; 딁; 딁; 딁; ) HANGUL SYLLABLE DYILG
+B502;B502;1103 1174 11B1;B502;1103 1174 11B1; # (딂; 딂; 딂; 딂; 딂; ) HANGUL SYLLABLE DYILM
+B503;B503;1103 1174 11B2;B503;1103 1174 11B2; # (딃; 딃; 딃; 딃; 딃; ) HANGUL SYLLABLE DYILB
+B504;B504;1103 1174 11B3;B504;1103 1174 11B3; # (딄; 딄; 딄; 딄; 딄; ) HANGUL SYLLABLE DYILS
+B505;B505;1103 1174 11B4;B505;1103 1174 11B4; # (딅; 딅; 딅; 딅; 딅; ) HANGUL SYLLABLE DYILT
+B506;B506;1103 1174 11B5;B506;1103 1174 11B5; # (딆; 딆; 딆; 딆; 딆; ) HANGUL SYLLABLE DYILP
+B507;B507;1103 1174 11B6;B507;1103 1174 11B6; # (딇; 딇; 딇; 딇; 딇; ) HANGUL SYLLABLE DYILH
+B508;B508;1103 1174 11B7;B508;1103 1174 11B7; # (딈; 딈; 딈; 딈; 딈; ) HANGUL SYLLABLE DYIM
+B509;B509;1103 1174 11B8;B509;1103 1174 11B8; # (딉; 딉; 딉; 딉; 딉; ) HANGUL SYLLABLE DYIB
+B50A;B50A;1103 1174 11B9;B50A;1103 1174 11B9; # (딊; 딊; 딊; 딊; 딊; ) HANGUL SYLLABLE DYIBS
+B50B;B50B;1103 1174 11BA;B50B;1103 1174 11BA; # (딋; 딋; 딋; 딋; 딋; ) HANGUL SYLLABLE DYIS
+B50C;B50C;1103 1174 11BB;B50C;1103 1174 11BB; # (딌; 딌; 딌; 딌; 딌; ) HANGUL SYLLABLE DYISS
+B50D;B50D;1103 1174 11BC;B50D;1103 1174 11BC; # (딍; 딍; 딍; 딍; 딍; ) HANGUL SYLLABLE DYING
+B50E;B50E;1103 1174 11BD;B50E;1103 1174 11BD; # (딎; 딎; 딎; 딎; 딎; ) HANGUL SYLLABLE DYIJ
+B50F;B50F;1103 1174 11BE;B50F;1103 1174 11BE; # (딏; 딏; 딏; 딏; 딏; ) HANGUL SYLLABLE DYIC
+B510;B510;1103 1174 11BF;B510;1103 1174 11BF; # (딐; 딐; 딐; 딐; 딐; ) HANGUL SYLLABLE DYIK
+B511;B511;1103 1174 11C0;B511;1103 1174 11C0; # (딑; 딑; 딑; 딑; 딑; ) HANGUL SYLLABLE DYIT
+B512;B512;1103 1174 11C1;B512;1103 1174 11C1; # (딒; 딒; 딒; 딒; 딒; ) HANGUL SYLLABLE DYIP
+B513;B513;1103 1174 11C2;B513;1103 1174 11C2; # (딓; 딓; 딓; 딓; 딓; ) HANGUL SYLLABLE DYIH
+B514;B514;1103 1175;B514;1103 1175; # (디; 디; 디; 디; 디; ) HANGUL SYLLABLE DI
+B515;B515;1103 1175 11A8;B515;1103 1175 11A8; # (딕; 딕; 딕; 딕; 딕; ) HANGUL SYLLABLE DIG
+B516;B516;1103 1175 11A9;B516;1103 1175 11A9; # (딖; 딖; 딖; 딖; 딖; ) HANGUL SYLLABLE DIGG
+B517;B517;1103 1175 11AA;B517;1103 1175 11AA; # (딗; 딗; 딗; 딗; 딗; ) HANGUL SYLLABLE DIGS
+B518;B518;1103 1175 11AB;B518;1103 1175 11AB; # (딘; 딘; 딘; 딘; 딘; ) HANGUL SYLLABLE DIN
+B519;B519;1103 1175 11AC;B519;1103 1175 11AC; # (딙; 딙; 딙; 딙; 딙; ) HANGUL SYLLABLE DINJ
+B51A;B51A;1103 1175 11AD;B51A;1103 1175 11AD; # (딚; 딚; 딚; 딚; 딚; ) HANGUL SYLLABLE DINH
+B51B;B51B;1103 1175 11AE;B51B;1103 1175 11AE; # (딛; 딛; 딛; 딛; 딛; ) HANGUL SYLLABLE DID
+B51C;B51C;1103 1175 11AF;B51C;1103 1175 11AF; # (딜; 딜; 딜; 딜; 딜; ) HANGUL SYLLABLE DIL
+B51D;B51D;1103 1175 11B0;B51D;1103 1175 11B0; # (딝; 딝; 딝; 딝; 딝; ) HANGUL SYLLABLE DILG
+B51E;B51E;1103 1175 11B1;B51E;1103 1175 11B1; # (딞; 딞; 딞; 딞; 딞; ) HANGUL SYLLABLE DILM
+B51F;B51F;1103 1175 11B2;B51F;1103 1175 11B2; # (딟; 딟; 딟; 딟; 딟; ) HANGUL SYLLABLE DILB
+B520;B520;1103 1175 11B3;B520;1103 1175 11B3; # (딠; 딠; 딠; 딠; 딠; ) HANGUL SYLLABLE DILS
+B521;B521;1103 1175 11B4;B521;1103 1175 11B4; # (딡; 딡; 딡; 딡; 딡; ) HANGUL SYLLABLE DILT
+B522;B522;1103 1175 11B5;B522;1103 1175 11B5; # (딢; 딢; 딢; 딢; 딢; ) HANGUL SYLLABLE DILP
+B523;B523;1103 1175 11B6;B523;1103 1175 11B6; # (딣; 딣; 딣; 딣; 딣; ) HANGUL SYLLABLE DILH
+B524;B524;1103 1175 11B7;B524;1103 1175 11B7; # (딤; 딤; 딤; 딤; 딤; ) HANGUL SYLLABLE DIM
+B525;B525;1103 1175 11B8;B525;1103 1175 11B8; # (딥; 딥; 딥; 딥; 딥; ) HANGUL SYLLABLE DIB
+B526;B526;1103 1175 11B9;B526;1103 1175 11B9; # (딦; 딦; 딦; 딦; 딦; ) HANGUL SYLLABLE DIBS
+B527;B527;1103 1175 11BA;B527;1103 1175 11BA; # (딧; 딧; 딧; 딧; 딧; ) HANGUL SYLLABLE DIS
+B528;B528;1103 1175 11BB;B528;1103 1175 11BB; # (딨; 딨; 딨; 딨; 딨; ) HANGUL SYLLABLE DISS
+B529;B529;1103 1175 11BC;B529;1103 1175 11BC; # (딩; 딩; 딩; 딩; 딩; ) HANGUL SYLLABLE DING
+B52A;B52A;1103 1175 11BD;B52A;1103 1175 11BD; # (딪; 딪; 딪; 딪; 딪; ) HANGUL SYLLABLE DIJ
+B52B;B52B;1103 1175 11BE;B52B;1103 1175 11BE; # (딫; 딫; 딫; 딫; 딫; ) HANGUL SYLLABLE DIC
+B52C;B52C;1103 1175 11BF;B52C;1103 1175 11BF; # (딬; 딬; 딬; 딬; 딬; ) HANGUL SYLLABLE DIK
+B52D;B52D;1103 1175 11C0;B52D;1103 1175 11C0; # (딭; 딭; 딭; 딭; 딭; ) HANGUL SYLLABLE DIT
+B52E;B52E;1103 1175 11C1;B52E;1103 1175 11C1; # (딮; 딮; 딮; 딮; 딮; ) HANGUL SYLLABLE DIP
+B52F;B52F;1103 1175 11C2;B52F;1103 1175 11C2; # (딯; 딯; 딯; 딯; 딯; ) HANGUL SYLLABLE DIH
+B530;B530;1104 1161;B530;1104 1161; # (따; 따; 따; 따; 따; ) HANGUL SYLLABLE DDA
+B531;B531;1104 1161 11A8;B531;1104 1161 11A8; # (딱; 딱; 딱; 딱; 딱; ) HANGUL SYLLABLE DDAG
+B532;B532;1104 1161 11A9;B532;1104 1161 11A9; # (딲; 딲; 딲; 딲; 딲; ) HANGUL SYLLABLE DDAGG
+B533;B533;1104 1161 11AA;B533;1104 1161 11AA; # (딳; 딳; 딳; 딳; 딳; ) HANGUL SYLLABLE DDAGS
+B534;B534;1104 1161 11AB;B534;1104 1161 11AB; # (딴; 딴; 딴; 딴; 딴; ) HANGUL SYLLABLE DDAN
+B535;B535;1104 1161 11AC;B535;1104 1161 11AC; # (딵; 딵; 딵; 딵; 딵; ) HANGUL SYLLABLE DDANJ
+B536;B536;1104 1161 11AD;B536;1104 1161 11AD; # (딶; 딶; 딶; 딶; 딶; ) HANGUL SYLLABLE DDANH
+B537;B537;1104 1161 11AE;B537;1104 1161 11AE; # (딷; 딷; 딷; 딷; 딷; ) HANGUL SYLLABLE DDAD
+B538;B538;1104 1161 11AF;B538;1104 1161 11AF; # (딸; 딸; 딸; 딸; 딸; ) HANGUL SYLLABLE DDAL
+B539;B539;1104 1161 11B0;B539;1104 1161 11B0; # (딹; 딹; 딹; 딹; 딹; ) HANGUL SYLLABLE DDALG
+B53A;B53A;1104 1161 11B1;B53A;1104 1161 11B1; # (딺; 딺; 딺; 딺; 딺; ) HANGUL SYLLABLE DDALM
+B53B;B53B;1104 1161 11B2;B53B;1104 1161 11B2; # (딻; 딻; 딻; 딻; 딻; ) HANGUL SYLLABLE DDALB
+B53C;B53C;1104 1161 11B3;B53C;1104 1161 11B3; # (딼; 딼; 딼; 딼; 딼; ) HANGUL SYLLABLE DDALS
+B53D;B53D;1104 1161 11B4;B53D;1104 1161 11B4; # (딽; 딽; 딽; 딽; 딽; ) HANGUL SYLLABLE DDALT
+B53E;B53E;1104 1161 11B5;B53E;1104 1161 11B5; # (딾; 딾; 딾; 딾; 딾; ) HANGUL SYLLABLE DDALP
+B53F;B53F;1104 1161 11B6;B53F;1104 1161 11B6; # (딿; 딿; 딿; 딿; 딿; ) HANGUL SYLLABLE DDALH
+B540;B540;1104 1161 11B7;B540;1104 1161 11B7; # (땀; 땀; 땀; 땀; 땀; ) HANGUL SYLLABLE DDAM
+B541;B541;1104 1161 11B8;B541;1104 1161 11B8; # (땁; 땁; 땁; 땁; 땁; ) HANGUL SYLLABLE DDAB
+B542;B542;1104 1161 11B9;B542;1104 1161 11B9; # (땂; 땂; 땂; 땂; 땂; ) HANGUL SYLLABLE DDABS
+B543;B543;1104 1161 11BA;B543;1104 1161 11BA; # (땃; 땃; 땃; 땃; 땃; ) HANGUL SYLLABLE DDAS
+B544;B544;1104 1161 11BB;B544;1104 1161 11BB; # (땄; 땄; 땄; 땄; 땄; ) HANGUL SYLLABLE DDASS
+B545;B545;1104 1161 11BC;B545;1104 1161 11BC; # (땅; 땅; 땅; 땅; 땅; ) HANGUL SYLLABLE DDANG
+B546;B546;1104 1161 11BD;B546;1104 1161 11BD; # (땆; 땆; 땆; 땆; 땆; ) HANGUL SYLLABLE DDAJ
+B547;B547;1104 1161 11BE;B547;1104 1161 11BE; # (땇; 땇; 땇; 땇; 땇; ) HANGUL SYLLABLE DDAC
+B548;B548;1104 1161 11BF;B548;1104 1161 11BF; # (땈; 땈; 땈; 땈; 땈; ) HANGUL SYLLABLE DDAK
+B549;B549;1104 1161 11C0;B549;1104 1161 11C0; # (땉; 땉; 땉; 땉; 땉; ) HANGUL SYLLABLE DDAT
+B54A;B54A;1104 1161 11C1;B54A;1104 1161 11C1; # (땊; 땊; 땊; 땊; 땊; ) HANGUL SYLLABLE DDAP
+B54B;B54B;1104 1161 11C2;B54B;1104 1161 11C2; # (땋; 땋; 땋; 땋; 땋; ) HANGUL SYLLABLE DDAH
+B54C;B54C;1104 1162;B54C;1104 1162; # (때; 때; 때; 때; 때; ) HANGUL SYLLABLE DDAE
+B54D;B54D;1104 1162 11A8;B54D;1104 1162 11A8; # (땍; 땍; 땍; 땍; 땍; ) HANGUL SYLLABLE DDAEG
+B54E;B54E;1104 1162 11A9;B54E;1104 1162 11A9; # (땎; 땎; 땎; 땎; 땎; ) HANGUL SYLLABLE DDAEGG
+B54F;B54F;1104 1162 11AA;B54F;1104 1162 11AA; # (땏; 땏; 땏; 땏; 땏; ) HANGUL SYLLABLE DDAEGS
+B550;B550;1104 1162 11AB;B550;1104 1162 11AB; # (땐; 땐; 땐; 땐; 땐; ) HANGUL SYLLABLE DDAEN
+B551;B551;1104 1162 11AC;B551;1104 1162 11AC; # (땑; 땑; 땑; 땑; 땑; ) HANGUL SYLLABLE DDAENJ
+B552;B552;1104 1162 11AD;B552;1104 1162 11AD; # (땒; 땒; 땒; 땒; 땒; ) HANGUL SYLLABLE DDAENH
+B553;B553;1104 1162 11AE;B553;1104 1162 11AE; # (땓; 땓; 땓; 땓; 땓; ) HANGUL SYLLABLE DDAED
+B554;B554;1104 1162 11AF;B554;1104 1162 11AF; # (땔; 땔; 땔; 땔; 땔; ) HANGUL SYLLABLE DDAEL
+B555;B555;1104 1162 11B0;B555;1104 1162 11B0; # (땕; 땕; 땕; 땕; 땕; ) HANGUL SYLLABLE DDAELG
+B556;B556;1104 1162 11B1;B556;1104 1162 11B1; # (땖; 땖; 땖; 땖; 땖; ) HANGUL SYLLABLE DDAELM
+B557;B557;1104 1162 11B2;B557;1104 1162 11B2; # (땗; 땗; 땗; 땗; 땗; ) HANGUL SYLLABLE DDAELB
+B558;B558;1104 1162 11B3;B558;1104 1162 11B3; # (땘; 땘; 땘; 땘; 땘; ) HANGUL SYLLABLE DDAELS
+B559;B559;1104 1162 11B4;B559;1104 1162 11B4; # (땙; 땙; 땙; 땙; 땙; ) HANGUL SYLLABLE DDAELT
+B55A;B55A;1104 1162 11B5;B55A;1104 1162 11B5; # (땚; 땚; 땚; 땚; 땚; ) HANGUL SYLLABLE DDAELP
+B55B;B55B;1104 1162 11B6;B55B;1104 1162 11B6; # (땛; 땛; 땛; 땛; 땛; ) HANGUL SYLLABLE DDAELH
+B55C;B55C;1104 1162 11B7;B55C;1104 1162 11B7; # (땜; 땜; 땜; 땜; 땜; ) HANGUL SYLLABLE DDAEM
+B55D;B55D;1104 1162 11B8;B55D;1104 1162 11B8; # (땝; 땝; 땝; 땝; 땝; ) HANGUL SYLLABLE DDAEB
+B55E;B55E;1104 1162 11B9;B55E;1104 1162 11B9; # (땞; 땞; 땞; 땞; 땞; ) HANGUL SYLLABLE DDAEBS
+B55F;B55F;1104 1162 11BA;B55F;1104 1162 11BA; # (땟; 땟; 땟; 땟; 땟; ) HANGUL SYLLABLE DDAES
+B560;B560;1104 1162 11BB;B560;1104 1162 11BB; # (땠; 땠; 땠; 땠; 땠; ) HANGUL SYLLABLE DDAESS
+B561;B561;1104 1162 11BC;B561;1104 1162 11BC; # (땡; 땡; 땡; 땡; 땡; ) HANGUL SYLLABLE DDAENG
+B562;B562;1104 1162 11BD;B562;1104 1162 11BD; # (땢; 땢; 땢; 땢; 땢; ) HANGUL SYLLABLE DDAEJ
+B563;B563;1104 1162 11BE;B563;1104 1162 11BE; # (땣; 땣; 땣; 땣; 땣; ) HANGUL SYLLABLE DDAEC
+B564;B564;1104 1162 11BF;B564;1104 1162 11BF; # (땤; 땤; 땤; 땤; 땤; ) HANGUL SYLLABLE DDAEK
+B565;B565;1104 1162 11C0;B565;1104 1162 11C0; # (땥; 땥; 땥; 땥; 땥; ) HANGUL SYLLABLE DDAET
+B566;B566;1104 1162 11C1;B566;1104 1162 11C1; # (땦; 땦; 땦; 땦; 땦; ) HANGUL SYLLABLE DDAEP
+B567;B567;1104 1162 11C2;B567;1104 1162 11C2; # (땧; 땧; 땧; 땧; 땧; ) HANGUL SYLLABLE DDAEH
+B568;B568;1104 1163;B568;1104 1163; # (땨; 땨; 땨; 땨; 땨; ) HANGUL SYLLABLE DDYA
+B569;B569;1104 1163 11A8;B569;1104 1163 11A8; # (땩; 땩; 땩; 땩; 땩; ) HANGUL SYLLABLE DDYAG
+B56A;B56A;1104 1163 11A9;B56A;1104 1163 11A9; # (땪; 땪; 땪; 땪; 땪; ) HANGUL SYLLABLE DDYAGG
+B56B;B56B;1104 1163 11AA;B56B;1104 1163 11AA; # (땫; 땫; 땫; 땫; 땫; ) HANGUL SYLLABLE DDYAGS
+B56C;B56C;1104 1163 11AB;B56C;1104 1163 11AB; # (땬; 땬; 땬; 땬; 땬; ) HANGUL SYLLABLE DDYAN
+B56D;B56D;1104 1163 11AC;B56D;1104 1163 11AC; # (땭; 땭; 땭; 땭; 땭; ) HANGUL SYLLABLE DDYANJ
+B56E;B56E;1104 1163 11AD;B56E;1104 1163 11AD; # (땮; 땮; 땮; 땮; 땮; ) HANGUL SYLLABLE DDYANH
+B56F;B56F;1104 1163 11AE;B56F;1104 1163 11AE; # (땯; 땯; 땯; 땯; 땯; ) HANGUL SYLLABLE DDYAD
+B570;B570;1104 1163 11AF;B570;1104 1163 11AF; # (땰; 땰; 땰; 땰; 땰; ) HANGUL SYLLABLE DDYAL
+B571;B571;1104 1163 11B0;B571;1104 1163 11B0; # (땱; 땱; 땱; 땱; 땱; ) HANGUL SYLLABLE DDYALG
+B572;B572;1104 1163 11B1;B572;1104 1163 11B1; # (땲; 땲; 땲; 땲; 땲; ) HANGUL SYLLABLE DDYALM
+B573;B573;1104 1163 11B2;B573;1104 1163 11B2; # (땳; 땳; 땳; 땳; 땳; ) HANGUL SYLLABLE DDYALB
+B574;B574;1104 1163 11B3;B574;1104 1163 11B3; # (땴; 땴; 땴; 땴; 땴; ) HANGUL SYLLABLE DDYALS
+B575;B575;1104 1163 11B4;B575;1104 1163 11B4; # (땵; 땵; 땵; 땵; 땵; ) HANGUL SYLLABLE DDYALT
+B576;B576;1104 1163 11B5;B576;1104 1163 11B5; # (땶; 땶; 땶; 땶; 땶; ) HANGUL SYLLABLE DDYALP
+B577;B577;1104 1163 11B6;B577;1104 1163 11B6; # (땷; 땷; 땷; 땷; 땷; ) HANGUL SYLLABLE DDYALH
+B578;B578;1104 1163 11B7;B578;1104 1163 11B7; # (땸; 땸; 땸; 땸; 땸; ) HANGUL SYLLABLE DDYAM
+B579;B579;1104 1163 11B8;B579;1104 1163 11B8; # (땹; 땹; 땹; 땹; 땹; ) HANGUL SYLLABLE DDYAB
+B57A;B57A;1104 1163 11B9;B57A;1104 1163 11B9; # (땺; 땺; 땺; 땺; 땺; ) HANGUL SYLLABLE DDYABS
+B57B;B57B;1104 1163 11BA;B57B;1104 1163 11BA; # (땻; 땻; 땻; 땻; 땻; ) HANGUL SYLLABLE DDYAS
+B57C;B57C;1104 1163 11BB;B57C;1104 1163 11BB; # (땼; 땼; 땼; 땼; 땼; ) HANGUL SYLLABLE DDYASS
+B57D;B57D;1104 1163 11BC;B57D;1104 1163 11BC; # (땽; 땽; 땽; 땽; 땽; ) HANGUL SYLLABLE DDYANG
+B57E;B57E;1104 1163 11BD;B57E;1104 1163 11BD; # (땾; 땾; 땾; 땾; 땾; ) HANGUL SYLLABLE DDYAJ
+B57F;B57F;1104 1163 11BE;B57F;1104 1163 11BE; # (땿; 땿; 땿; 땿; 땿; ) HANGUL SYLLABLE DDYAC
+B580;B580;1104 1163 11BF;B580;1104 1163 11BF; # (떀; 떀; 떀; 떀; 떀; ) HANGUL SYLLABLE DDYAK
+B581;B581;1104 1163 11C0;B581;1104 1163 11C0; # (떁; 떁; 떁; 떁; 떁; ) HANGUL SYLLABLE DDYAT
+B582;B582;1104 1163 11C1;B582;1104 1163 11C1; # (떂; 떂; 떂; 떂; 떂; ) HANGUL SYLLABLE DDYAP
+B583;B583;1104 1163 11C2;B583;1104 1163 11C2; # (떃; 떃; 떃; 떃; 떃; ) HANGUL SYLLABLE DDYAH
+B584;B584;1104 1164;B584;1104 1164; # (떄; 떄; 떄; 떄; 떄; ) HANGUL SYLLABLE DDYAE
+B585;B585;1104 1164 11A8;B585;1104 1164 11A8; # (떅; 떅; 떅; 떅; 떅; ) HANGUL SYLLABLE DDYAEG
+B586;B586;1104 1164 11A9;B586;1104 1164 11A9; # (떆; 떆; 떆; 떆; 떆; ) HANGUL SYLLABLE DDYAEGG
+B587;B587;1104 1164 11AA;B587;1104 1164 11AA; # (떇; 떇; 떇; 떇; 떇; ) HANGUL SYLLABLE DDYAEGS
+B588;B588;1104 1164 11AB;B588;1104 1164 11AB; # (떈; 떈; 떈; 떈; 떈; ) HANGUL SYLLABLE DDYAEN
+B589;B589;1104 1164 11AC;B589;1104 1164 11AC; # (떉; 떉; 떉; 떉; 떉; ) HANGUL SYLLABLE DDYAENJ
+B58A;B58A;1104 1164 11AD;B58A;1104 1164 11AD; # (떊; 떊; 떊; 떊; 떊; ) HANGUL SYLLABLE DDYAENH
+B58B;B58B;1104 1164 11AE;B58B;1104 1164 11AE; # (떋; 떋; 떋; 떋; 떋; ) HANGUL SYLLABLE DDYAED
+B58C;B58C;1104 1164 11AF;B58C;1104 1164 11AF; # (떌; 떌; 떌; 떌; 떌; ) HANGUL SYLLABLE DDYAEL
+B58D;B58D;1104 1164 11B0;B58D;1104 1164 11B0; # (떍; 떍; 떍; 떍; 떍; ) HANGUL SYLLABLE DDYAELG
+B58E;B58E;1104 1164 11B1;B58E;1104 1164 11B1; # (떎; 떎; 떎; 떎; 떎; ) HANGUL SYLLABLE DDYAELM
+B58F;B58F;1104 1164 11B2;B58F;1104 1164 11B2; # (떏; 떏; 떏; 떏; 떏; ) HANGUL SYLLABLE DDYAELB
+B590;B590;1104 1164 11B3;B590;1104 1164 11B3; # (떐; 떐; 떐; 떐; 떐; ) HANGUL SYLLABLE DDYAELS
+B591;B591;1104 1164 11B4;B591;1104 1164 11B4; # (떑; 떑; 떑; 떑; 떑; ) HANGUL SYLLABLE DDYAELT
+B592;B592;1104 1164 11B5;B592;1104 1164 11B5; # (떒; 떒; 떒; 떒; 떒; ) HANGUL SYLLABLE DDYAELP
+B593;B593;1104 1164 11B6;B593;1104 1164 11B6; # (떓; 떓; 떓; 떓; 떓; ) HANGUL SYLLABLE DDYAELH
+B594;B594;1104 1164 11B7;B594;1104 1164 11B7; # (떔; 떔; 떔; 떔; 떔; ) HANGUL SYLLABLE DDYAEM
+B595;B595;1104 1164 11B8;B595;1104 1164 11B8; # (떕; 떕; 떕; 떕; 떕; ) HANGUL SYLLABLE DDYAEB
+B596;B596;1104 1164 11B9;B596;1104 1164 11B9; # (떖; 떖; 떖; 떖; 떖; ) HANGUL SYLLABLE DDYAEBS
+B597;B597;1104 1164 11BA;B597;1104 1164 11BA; # (떗; 떗; 떗; 떗; 떗; ) HANGUL SYLLABLE DDYAES
+B598;B598;1104 1164 11BB;B598;1104 1164 11BB; # (떘; 떘; 떘; 떘; 떘; ) HANGUL SYLLABLE DDYAESS
+B599;B599;1104 1164 11BC;B599;1104 1164 11BC; # (떙; 떙; 떙; 떙; 떙; ) HANGUL SYLLABLE DDYAENG
+B59A;B59A;1104 1164 11BD;B59A;1104 1164 11BD; # (떚; 떚; 떚; 떚; 떚; ) HANGUL SYLLABLE DDYAEJ
+B59B;B59B;1104 1164 11BE;B59B;1104 1164 11BE; # (떛; 떛; 떛; 떛; 떛; ) HANGUL SYLLABLE DDYAEC
+B59C;B59C;1104 1164 11BF;B59C;1104 1164 11BF; # (떜; 떜; 떜; 떜; 떜; ) HANGUL SYLLABLE DDYAEK
+B59D;B59D;1104 1164 11C0;B59D;1104 1164 11C0; # (떝; 떝; 떝; 떝; 떝; ) HANGUL SYLLABLE DDYAET
+B59E;B59E;1104 1164 11C1;B59E;1104 1164 11C1; # (떞; 떞; 떞; 떞; 떞; ) HANGUL SYLLABLE DDYAEP
+B59F;B59F;1104 1164 11C2;B59F;1104 1164 11C2; # (떟; 떟; 떟; 떟; 떟; ) HANGUL SYLLABLE DDYAEH
+B5A0;B5A0;1104 1165;B5A0;1104 1165; # (떠; 떠; 떠; 떠; 떠; ) HANGUL SYLLABLE DDEO
+B5A1;B5A1;1104 1165 11A8;B5A1;1104 1165 11A8; # (떡; 떡; 떡; 떡; 떡; ) HANGUL SYLLABLE DDEOG
+B5A2;B5A2;1104 1165 11A9;B5A2;1104 1165 11A9; # (떢; 떢; 떢; 떢; 떢; ) HANGUL SYLLABLE DDEOGG
+B5A3;B5A3;1104 1165 11AA;B5A3;1104 1165 11AA; # (떣; 떣; 떣; 떣; 떣; ) HANGUL SYLLABLE DDEOGS
+B5A4;B5A4;1104 1165 11AB;B5A4;1104 1165 11AB; # (떤; 떤; 떤; 떤; 떤; ) HANGUL SYLLABLE DDEON
+B5A5;B5A5;1104 1165 11AC;B5A5;1104 1165 11AC; # (떥; 떥; 떥; 떥; 떥; ) HANGUL SYLLABLE DDEONJ
+B5A6;B5A6;1104 1165 11AD;B5A6;1104 1165 11AD; # (떦; 떦; 떦; 떦; 떦; ) HANGUL SYLLABLE DDEONH
+B5A7;B5A7;1104 1165 11AE;B5A7;1104 1165 11AE; # (떧; 떧; 떧; 떧; 떧; ) HANGUL SYLLABLE DDEOD
+B5A8;B5A8;1104 1165 11AF;B5A8;1104 1165 11AF; # (떨; 떨; 떨; 떨; 떨; ) HANGUL SYLLABLE DDEOL
+B5A9;B5A9;1104 1165 11B0;B5A9;1104 1165 11B0; # (떩; 떩; 떩; 떩; 떩; ) HANGUL SYLLABLE DDEOLG
+B5AA;B5AA;1104 1165 11B1;B5AA;1104 1165 11B1; # (떪; 떪; 떪; 떪; 떪; ) HANGUL SYLLABLE DDEOLM
+B5AB;B5AB;1104 1165 11B2;B5AB;1104 1165 11B2; # (떫; 떫; 떫; 떫; 떫; ) HANGUL SYLLABLE DDEOLB
+B5AC;B5AC;1104 1165 11B3;B5AC;1104 1165 11B3; # (떬; 떬; 떬; 떬; 떬; ) HANGUL SYLLABLE DDEOLS
+B5AD;B5AD;1104 1165 11B4;B5AD;1104 1165 11B4; # (떭; 떭; 떭; 떭; 떭; ) HANGUL SYLLABLE DDEOLT
+B5AE;B5AE;1104 1165 11B5;B5AE;1104 1165 11B5; # (떮; 떮; 떮; 떮; 떮; ) HANGUL SYLLABLE DDEOLP
+B5AF;B5AF;1104 1165 11B6;B5AF;1104 1165 11B6; # (떯; 떯; 떯; 떯; 떯; ) HANGUL SYLLABLE DDEOLH
+B5B0;B5B0;1104 1165 11B7;B5B0;1104 1165 11B7; # (떰; 떰; 떰; 떰; 떰; ) HANGUL SYLLABLE DDEOM
+B5B1;B5B1;1104 1165 11B8;B5B1;1104 1165 11B8; # (떱; 떱; 떱; 떱; 떱; ) HANGUL SYLLABLE DDEOB
+B5B2;B5B2;1104 1165 11B9;B5B2;1104 1165 11B9; # (떲; 떲; 떲; 떲; 떲; ) HANGUL SYLLABLE DDEOBS
+B5B3;B5B3;1104 1165 11BA;B5B3;1104 1165 11BA; # (떳; 떳; 떳; 떳; 떳; ) HANGUL SYLLABLE DDEOS
+B5B4;B5B4;1104 1165 11BB;B5B4;1104 1165 11BB; # (떴; 떴; 떴; 떴; 떴; ) HANGUL SYLLABLE DDEOSS
+B5B5;B5B5;1104 1165 11BC;B5B5;1104 1165 11BC; # (떵; 떵; 떵; 떵; 떵; ) HANGUL SYLLABLE DDEONG
+B5B6;B5B6;1104 1165 11BD;B5B6;1104 1165 11BD; # (떶; 떶; 떶; 떶; 떶; ) HANGUL SYLLABLE DDEOJ
+B5B7;B5B7;1104 1165 11BE;B5B7;1104 1165 11BE; # (떷; 떷; 떷; 떷; 떷; ) HANGUL SYLLABLE DDEOC
+B5B8;B5B8;1104 1165 11BF;B5B8;1104 1165 11BF; # (떸; 떸; 떸; 떸; 떸; ) HANGUL SYLLABLE DDEOK
+B5B9;B5B9;1104 1165 11C0;B5B9;1104 1165 11C0; # (떹; 떹; 떹; 떹; 떹; ) HANGUL SYLLABLE DDEOT
+B5BA;B5BA;1104 1165 11C1;B5BA;1104 1165 11C1; # (떺; 떺; 떺; 떺; 떺; ) HANGUL SYLLABLE DDEOP
+B5BB;B5BB;1104 1165 11C2;B5BB;1104 1165 11C2; # (떻; 떻; 떻; 떻; 떻; ) HANGUL SYLLABLE DDEOH
+B5BC;B5BC;1104 1166;B5BC;1104 1166; # (떼; 떼; 떼; 떼; 떼; ) HANGUL SYLLABLE DDE
+B5BD;B5BD;1104 1166 11A8;B5BD;1104 1166 11A8; # (떽; 떽; 떽; 떽; 떽; ) HANGUL SYLLABLE DDEG
+B5BE;B5BE;1104 1166 11A9;B5BE;1104 1166 11A9; # (떾; 떾; 떾; 떾; 떾; ) HANGUL SYLLABLE DDEGG
+B5BF;B5BF;1104 1166 11AA;B5BF;1104 1166 11AA; # (떿; 떿; 떿; 떿; 떿; ) HANGUL SYLLABLE DDEGS
+B5C0;B5C0;1104 1166 11AB;B5C0;1104 1166 11AB; # (뗀; 뗀; 뗀; 뗀; 뗀; ) HANGUL SYLLABLE DDEN
+B5C1;B5C1;1104 1166 11AC;B5C1;1104 1166 11AC; # (뗁; 뗁; 뗁; 뗁; 뗁; ) HANGUL SYLLABLE DDENJ
+B5C2;B5C2;1104 1166 11AD;B5C2;1104 1166 11AD; # (뗂; 뗂; 뗂; 뗂; 뗂; ) HANGUL SYLLABLE DDENH
+B5C3;B5C3;1104 1166 11AE;B5C3;1104 1166 11AE; # (뗃; 뗃; 뗃; 뗃; 뗃; ) HANGUL SYLLABLE DDED
+B5C4;B5C4;1104 1166 11AF;B5C4;1104 1166 11AF; # (뗄; 뗄; 뗄; 뗄; 뗄; ) HANGUL SYLLABLE DDEL
+B5C5;B5C5;1104 1166 11B0;B5C5;1104 1166 11B0; # (뗅; 뗅; 뗅; 뗅; 뗅; ) HANGUL SYLLABLE DDELG
+B5C6;B5C6;1104 1166 11B1;B5C6;1104 1166 11B1; # (뗆; 뗆; 뗆; 뗆; 뗆; ) HANGUL SYLLABLE DDELM
+B5C7;B5C7;1104 1166 11B2;B5C7;1104 1166 11B2; # (뗇; 뗇; 뗇; 뗇; 뗇; ) HANGUL SYLLABLE DDELB
+B5C8;B5C8;1104 1166 11B3;B5C8;1104 1166 11B3; # (뗈; 뗈; 뗈; 뗈; 뗈; ) HANGUL SYLLABLE DDELS
+B5C9;B5C9;1104 1166 11B4;B5C9;1104 1166 11B4; # (뗉; 뗉; 뗉; 뗉; 뗉; ) HANGUL SYLLABLE DDELT
+B5CA;B5CA;1104 1166 11B5;B5CA;1104 1166 11B5; # (뗊; 뗊; 뗊; 뗊; 뗊; ) HANGUL SYLLABLE DDELP
+B5CB;B5CB;1104 1166 11B6;B5CB;1104 1166 11B6; # (뗋; 뗋; 뗋; 뗋; 뗋; ) HANGUL SYLLABLE DDELH
+B5CC;B5CC;1104 1166 11B7;B5CC;1104 1166 11B7; # (뗌; 뗌; 뗌; 뗌; 뗌; ) HANGUL SYLLABLE DDEM
+B5CD;B5CD;1104 1166 11B8;B5CD;1104 1166 11B8; # (뗍; 뗍; 뗍; 뗍; 뗍; ) HANGUL SYLLABLE DDEB
+B5CE;B5CE;1104 1166 11B9;B5CE;1104 1166 11B9; # (뗎; 뗎; 뗎; 뗎; 뗎; ) HANGUL SYLLABLE DDEBS
+B5CF;B5CF;1104 1166 11BA;B5CF;1104 1166 11BA; # (뗏; 뗏; 뗏; 뗏; 뗏; ) HANGUL SYLLABLE DDES
+B5D0;B5D0;1104 1166 11BB;B5D0;1104 1166 11BB; # (뗐; 뗐; 뗐; 뗐; 뗐; ) HANGUL SYLLABLE DDESS
+B5D1;B5D1;1104 1166 11BC;B5D1;1104 1166 11BC; # (뗑; 뗑; 뗑; 뗑; 뗑; ) HANGUL SYLLABLE DDENG
+B5D2;B5D2;1104 1166 11BD;B5D2;1104 1166 11BD; # (뗒; 뗒; 뗒; 뗒; 뗒; ) HANGUL SYLLABLE DDEJ
+B5D3;B5D3;1104 1166 11BE;B5D3;1104 1166 11BE; # (뗓; 뗓; 뗓; 뗓; 뗓; ) HANGUL SYLLABLE DDEC
+B5D4;B5D4;1104 1166 11BF;B5D4;1104 1166 11BF; # (뗔; 뗔; 뗔; 뗔; 뗔; ) HANGUL SYLLABLE DDEK
+B5D5;B5D5;1104 1166 11C0;B5D5;1104 1166 11C0; # (뗕; 뗕; 뗕; 뗕; 뗕; ) HANGUL SYLLABLE DDET
+B5D6;B5D6;1104 1166 11C1;B5D6;1104 1166 11C1; # (뗖; 뗖; 뗖; 뗖; 뗖; ) HANGUL SYLLABLE DDEP
+B5D7;B5D7;1104 1166 11C2;B5D7;1104 1166 11C2; # (뗗; 뗗; 뗗; 뗗; 뗗; ) HANGUL SYLLABLE DDEH
+B5D8;B5D8;1104 1167;B5D8;1104 1167; # (뗘; 뗘; 뗘; 뗘; 뗘; ) HANGUL SYLLABLE DDYEO
+B5D9;B5D9;1104 1167 11A8;B5D9;1104 1167 11A8; # (뗙; 뗙; 뗙; 뗙; 뗙; ) HANGUL SYLLABLE DDYEOG
+B5DA;B5DA;1104 1167 11A9;B5DA;1104 1167 11A9; # (뗚; 뗚; 뗚; 뗚; 뗚; ) HANGUL SYLLABLE DDYEOGG
+B5DB;B5DB;1104 1167 11AA;B5DB;1104 1167 11AA; # (뗛; 뗛; 뗛; 뗛; 뗛; ) HANGUL SYLLABLE DDYEOGS
+B5DC;B5DC;1104 1167 11AB;B5DC;1104 1167 11AB; # (뗜; 뗜; 뗜; 뗜; 뗜; ) HANGUL SYLLABLE DDYEON
+B5DD;B5DD;1104 1167 11AC;B5DD;1104 1167 11AC; # (뗝; 뗝; 뗝; 뗝; 뗝; ) HANGUL SYLLABLE DDYEONJ
+B5DE;B5DE;1104 1167 11AD;B5DE;1104 1167 11AD; # (뗞; 뗞; 뗞; 뗞; 뗞; ) HANGUL SYLLABLE DDYEONH
+B5DF;B5DF;1104 1167 11AE;B5DF;1104 1167 11AE; # (뗟; 뗟; 뗟; 뗟; 뗟; ) HANGUL SYLLABLE DDYEOD
+B5E0;B5E0;1104 1167 11AF;B5E0;1104 1167 11AF; # (뗠; 뗠; 뗠; 뗠; 뗠; ) HANGUL SYLLABLE DDYEOL
+B5E1;B5E1;1104 1167 11B0;B5E1;1104 1167 11B0; # (뗡; 뗡; 뗡; 뗡; 뗡; ) HANGUL SYLLABLE DDYEOLG
+B5E2;B5E2;1104 1167 11B1;B5E2;1104 1167 11B1; # (뗢; 뗢; 뗢; 뗢; 뗢; ) HANGUL SYLLABLE DDYEOLM
+B5E3;B5E3;1104 1167 11B2;B5E3;1104 1167 11B2; # (뗣; 뗣; 뗣; 뗣; 뗣; ) HANGUL SYLLABLE DDYEOLB
+B5E4;B5E4;1104 1167 11B3;B5E4;1104 1167 11B3; # (뗤; 뗤; 뗤; 뗤; 뗤; ) HANGUL SYLLABLE DDYEOLS
+B5E5;B5E5;1104 1167 11B4;B5E5;1104 1167 11B4; # (뗥; 뗥; 뗥; 뗥; 뗥; ) HANGUL SYLLABLE DDYEOLT
+B5E6;B5E6;1104 1167 11B5;B5E6;1104 1167 11B5; # (뗦; 뗦; 뗦; 뗦; 뗦; ) HANGUL SYLLABLE DDYEOLP
+B5E7;B5E7;1104 1167 11B6;B5E7;1104 1167 11B6; # (뗧; 뗧; 뗧; 뗧; 뗧; ) HANGUL SYLLABLE DDYEOLH
+B5E8;B5E8;1104 1167 11B7;B5E8;1104 1167 11B7; # (뗨; 뗨; 뗨; 뗨; 뗨; ) HANGUL SYLLABLE DDYEOM
+B5E9;B5E9;1104 1167 11B8;B5E9;1104 1167 11B8; # (뗩; 뗩; 뗩; 뗩; 뗩; ) HANGUL SYLLABLE DDYEOB
+B5EA;B5EA;1104 1167 11B9;B5EA;1104 1167 11B9; # (뗪; 뗪; 뗪; 뗪; 뗪; ) HANGUL SYLLABLE DDYEOBS
+B5EB;B5EB;1104 1167 11BA;B5EB;1104 1167 11BA; # (뗫; 뗫; 뗫; 뗫; 뗫; ) HANGUL SYLLABLE DDYEOS
+B5EC;B5EC;1104 1167 11BB;B5EC;1104 1167 11BB; # (뗬; 뗬; 뗬; 뗬; 뗬; ) HANGUL SYLLABLE DDYEOSS
+B5ED;B5ED;1104 1167 11BC;B5ED;1104 1167 11BC; # (뗭; 뗭; 뗭; 뗭; 뗭; ) HANGUL SYLLABLE DDYEONG
+B5EE;B5EE;1104 1167 11BD;B5EE;1104 1167 11BD; # (뗮; 뗮; 뗮; 뗮; 뗮; ) HANGUL SYLLABLE DDYEOJ
+B5EF;B5EF;1104 1167 11BE;B5EF;1104 1167 11BE; # (뗯; 뗯; 뗯; 뗯; 뗯; ) HANGUL SYLLABLE DDYEOC
+B5F0;B5F0;1104 1167 11BF;B5F0;1104 1167 11BF; # (뗰; 뗰; 뗰; 뗰; 뗰; ) HANGUL SYLLABLE DDYEOK
+B5F1;B5F1;1104 1167 11C0;B5F1;1104 1167 11C0; # (뗱; 뗱; 뗱; 뗱; 뗱; ) HANGUL SYLLABLE DDYEOT
+B5F2;B5F2;1104 1167 11C1;B5F2;1104 1167 11C1; # (뗲; 뗲; 뗲; 뗲; 뗲; ) HANGUL SYLLABLE DDYEOP
+B5F3;B5F3;1104 1167 11C2;B5F3;1104 1167 11C2; # (뗳; 뗳; 뗳; 뗳; 뗳; ) HANGUL SYLLABLE DDYEOH
+B5F4;B5F4;1104 1168;B5F4;1104 1168; # (뗴; 뗴; 뗴; 뗴; 뗴; ) HANGUL SYLLABLE DDYE
+B5F5;B5F5;1104 1168 11A8;B5F5;1104 1168 11A8; # (뗵; 뗵; 뗵; 뗵; 뗵; ) HANGUL SYLLABLE DDYEG
+B5F6;B5F6;1104 1168 11A9;B5F6;1104 1168 11A9; # (뗶; 뗶; 뗶; 뗶; 뗶; ) HANGUL SYLLABLE DDYEGG
+B5F7;B5F7;1104 1168 11AA;B5F7;1104 1168 11AA; # (뗷; 뗷; 뗷; 뗷; 뗷; ) HANGUL SYLLABLE DDYEGS
+B5F8;B5F8;1104 1168 11AB;B5F8;1104 1168 11AB; # (뗸; 뗸; 뗸; 뗸; 뗸; ) HANGUL SYLLABLE DDYEN
+B5F9;B5F9;1104 1168 11AC;B5F9;1104 1168 11AC; # (뗹; 뗹; 뗹; 뗹; 뗹; ) HANGUL SYLLABLE DDYENJ
+B5FA;B5FA;1104 1168 11AD;B5FA;1104 1168 11AD; # (뗺; 뗺; 뗺; 뗺; 뗺; ) HANGUL SYLLABLE DDYENH
+B5FB;B5FB;1104 1168 11AE;B5FB;1104 1168 11AE; # (뗻; 뗻; 뗻; 뗻; 뗻; ) HANGUL SYLLABLE DDYED
+B5FC;B5FC;1104 1168 11AF;B5FC;1104 1168 11AF; # (뗼; 뗼; 뗼; 뗼; 뗼; ) HANGUL SYLLABLE DDYEL
+B5FD;B5FD;1104 1168 11B0;B5FD;1104 1168 11B0; # (뗽; 뗽; 뗽; 뗽; 뗽; ) HANGUL SYLLABLE DDYELG
+B5FE;B5FE;1104 1168 11B1;B5FE;1104 1168 11B1; # (뗾; 뗾; 뗾; 뗾; 뗾; ) HANGUL SYLLABLE DDYELM
+B5FF;B5FF;1104 1168 11B2;B5FF;1104 1168 11B2; # (뗿; 뗿; 뗿; 뗿; 뗿; ) HANGUL SYLLABLE DDYELB
+B600;B600;1104 1168 11B3;B600;1104 1168 11B3; # (똀; 똀; 똀; 똀; 똀; ) HANGUL SYLLABLE DDYELS
+B601;B601;1104 1168 11B4;B601;1104 1168 11B4; # (똁; 똁; 똁; 똁; 똁; ) HANGUL SYLLABLE DDYELT
+B602;B602;1104 1168 11B5;B602;1104 1168 11B5; # (똂; 똂; 똂; 똂; 똂; ) HANGUL SYLLABLE DDYELP
+B603;B603;1104 1168 11B6;B603;1104 1168 11B6; # (똃; 똃; 똃; 똃; 똃; ) HANGUL SYLLABLE DDYELH
+B604;B604;1104 1168 11B7;B604;1104 1168 11B7; # (똄; 똄; 똄; 똄; 똄; ) HANGUL SYLLABLE DDYEM
+B605;B605;1104 1168 11B8;B605;1104 1168 11B8; # (똅; 똅; 똅; 똅; 똅; ) HANGUL SYLLABLE DDYEB
+B606;B606;1104 1168 11B9;B606;1104 1168 11B9; # (똆; 똆; 똆; 똆; 똆; ) HANGUL SYLLABLE DDYEBS
+B607;B607;1104 1168 11BA;B607;1104 1168 11BA; # (똇; 똇; 똇; 똇; 똇; ) HANGUL SYLLABLE DDYES
+B608;B608;1104 1168 11BB;B608;1104 1168 11BB; # (똈; 똈; 똈; 똈; 똈; ) HANGUL SYLLABLE DDYESS
+B609;B609;1104 1168 11BC;B609;1104 1168 11BC; # (똉; 똉; 똉; 똉; 똉; ) HANGUL SYLLABLE DDYENG
+B60A;B60A;1104 1168 11BD;B60A;1104 1168 11BD; # (똊; 똊; 똊; 똊; 똊; ) HANGUL SYLLABLE DDYEJ
+B60B;B60B;1104 1168 11BE;B60B;1104 1168 11BE; # (똋; 똋; 똋; 똋; 똋; ) HANGUL SYLLABLE DDYEC
+B60C;B60C;1104 1168 11BF;B60C;1104 1168 11BF; # (똌; 똌; 똌; 똌; 똌; ) HANGUL SYLLABLE DDYEK
+B60D;B60D;1104 1168 11C0;B60D;1104 1168 11C0; # (똍; 똍; 똍; 똍; 똍; ) HANGUL SYLLABLE DDYET
+B60E;B60E;1104 1168 11C1;B60E;1104 1168 11C1; # (똎; 똎; 똎; 똎; 똎; ) HANGUL SYLLABLE DDYEP
+B60F;B60F;1104 1168 11C2;B60F;1104 1168 11C2; # (똏; 똏; 똏; 똏; 똏; ) HANGUL SYLLABLE DDYEH
+B610;B610;1104 1169;B610;1104 1169; # (또; 또; 또; 또; 또; ) HANGUL SYLLABLE DDO
+B611;B611;1104 1169 11A8;B611;1104 1169 11A8; # (똑; 똑; 똑; 똑; 똑; ) HANGUL SYLLABLE DDOG
+B612;B612;1104 1169 11A9;B612;1104 1169 11A9; # (똒; 똒; 똒; 똒; 똒; ) HANGUL SYLLABLE DDOGG
+B613;B613;1104 1169 11AA;B613;1104 1169 11AA; # (똓; 똓; 똓; 똓; 똓; ) HANGUL SYLLABLE DDOGS
+B614;B614;1104 1169 11AB;B614;1104 1169 11AB; # (똔; 똔; 똔; 똔; 똔; ) HANGUL SYLLABLE DDON
+B615;B615;1104 1169 11AC;B615;1104 1169 11AC; # (똕; 똕; 똕; 똕; 똕; ) HANGUL SYLLABLE DDONJ
+B616;B616;1104 1169 11AD;B616;1104 1169 11AD; # (똖; 똖; 똖; 똖; 똖; ) HANGUL SYLLABLE DDONH
+B617;B617;1104 1169 11AE;B617;1104 1169 11AE; # (똗; 똗; 똗; 똗; 똗; ) HANGUL SYLLABLE DDOD
+B618;B618;1104 1169 11AF;B618;1104 1169 11AF; # (똘; 똘; 똘; 똘; 똘; ) HANGUL SYLLABLE DDOL
+B619;B619;1104 1169 11B0;B619;1104 1169 11B0; # (똙; 똙; 똙; 똙; 똙; ) HANGUL SYLLABLE DDOLG
+B61A;B61A;1104 1169 11B1;B61A;1104 1169 11B1; # (똚; 똚; 똚; 똚; 똚; ) HANGUL SYLLABLE DDOLM
+B61B;B61B;1104 1169 11B2;B61B;1104 1169 11B2; # (똛; 똛; 똛; 똛; 똛; ) HANGUL SYLLABLE DDOLB
+B61C;B61C;1104 1169 11B3;B61C;1104 1169 11B3; # (똜; 똜; 똜; 똜; 똜; ) HANGUL SYLLABLE DDOLS
+B61D;B61D;1104 1169 11B4;B61D;1104 1169 11B4; # (똝; 똝; 똝; 똝; 똝; ) HANGUL SYLLABLE DDOLT
+B61E;B61E;1104 1169 11B5;B61E;1104 1169 11B5; # (똞; 똞; 똞; 똞; 똞; ) HANGUL SYLLABLE DDOLP
+B61F;B61F;1104 1169 11B6;B61F;1104 1169 11B6; # (똟; 똟; 똟; 똟; 똟; ) HANGUL SYLLABLE DDOLH
+B620;B620;1104 1169 11B7;B620;1104 1169 11B7; # (똠; 똠; 똠; 똠; 똠; ) HANGUL SYLLABLE DDOM
+B621;B621;1104 1169 11B8;B621;1104 1169 11B8; # (똡; 똡; 똡; 똡; 똡; ) HANGUL SYLLABLE DDOB
+B622;B622;1104 1169 11B9;B622;1104 1169 11B9; # (똢; 똢; 똢; 똢; 똢; ) HANGUL SYLLABLE DDOBS
+B623;B623;1104 1169 11BA;B623;1104 1169 11BA; # (똣; 똣; 똣; 똣; 똣; ) HANGUL SYLLABLE DDOS
+B624;B624;1104 1169 11BB;B624;1104 1169 11BB; # (똤; 똤; 똤; 똤; 똤; ) HANGUL SYLLABLE DDOSS
+B625;B625;1104 1169 11BC;B625;1104 1169 11BC; # (똥; 똥; 똥; 똥; 똥; ) HANGUL SYLLABLE DDONG
+B626;B626;1104 1169 11BD;B626;1104 1169 11BD; # (똦; 똦; 똦; 똦; 똦; ) HANGUL SYLLABLE DDOJ
+B627;B627;1104 1169 11BE;B627;1104 1169 11BE; # (똧; 똧; 똧; 똧; 똧; ) HANGUL SYLLABLE DDOC
+B628;B628;1104 1169 11BF;B628;1104 1169 11BF; # (똨; 똨; 똨; 똨; 똨; ) HANGUL SYLLABLE DDOK
+B629;B629;1104 1169 11C0;B629;1104 1169 11C0; # (똩; 똩; 똩; 똩; 똩; ) HANGUL SYLLABLE DDOT
+B62A;B62A;1104 1169 11C1;B62A;1104 1169 11C1; # (똪; 똪; 똪; 똪; 똪; ) HANGUL SYLLABLE DDOP
+B62B;B62B;1104 1169 11C2;B62B;1104 1169 11C2; # (똫; 똫; 똫; 똫; 똫; ) HANGUL SYLLABLE DDOH
+B62C;B62C;1104 116A;B62C;1104 116A; # (똬; 똬; 똬; 똬; 똬; ) HANGUL SYLLABLE DDWA
+B62D;B62D;1104 116A 11A8;B62D;1104 116A 11A8; # (똭; 똭; 똭; 똭; 똭; ) HANGUL SYLLABLE DDWAG
+B62E;B62E;1104 116A 11A9;B62E;1104 116A 11A9; # (똮; 똮; 똮; 똮; 똮; ) HANGUL SYLLABLE DDWAGG
+B62F;B62F;1104 116A 11AA;B62F;1104 116A 11AA; # (똯; 똯; 똯; 똯; 똯; ) HANGUL SYLLABLE DDWAGS
+B630;B630;1104 116A 11AB;B630;1104 116A 11AB; # (똰; 똰; 똰; 똰; 똰; ) HANGUL SYLLABLE DDWAN
+B631;B631;1104 116A 11AC;B631;1104 116A 11AC; # (똱; 똱; 똱; 똱; 똱; ) HANGUL SYLLABLE DDWANJ
+B632;B632;1104 116A 11AD;B632;1104 116A 11AD; # (똲; 똲; 똲; 똲; 똲; ) HANGUL SYLLABLE DDWANH
+B633;B633;1104 116A 11AE;B633;1104 116A 11AE; # (똳; 똳; 똳; 똳; 똳; ) HANGUL SYLLABLE DDWAD
+B634;B634;1104 116A 11AF;B634;1104 116A 11AF; # (똴; 똴; 똴; 똴; 똴; ) HANGUL SYLLABLE DDWAL
+B635;B635;1104 116A 11B0;B635;1104 116A 11B0; # (똵; 똵; 똵; 똵; 똵; ) HANGUL SYLLABLE DDWALG
+B636;B636;1104 116A 11B1;B636;1104 116A 11B1; # (똶; 똶; 똶; 똶; 똶; ) HANGUL SYLLABLE DDWALM
+B637;B637;1104 116A 11B2;B637;1104 116A 11B2; # (똷; 똷; 똷; 똷; 똷; ) HANGUL SYLLABLE DDWALB
+B638;B638;1104 116A 11B3;B638;1104 116A 11B3; # (똸; 똸; 똸; 똸; 똸; ) HANGUL SYLLABLE DDWALS
+B639;B639;1104 116A 11B4;B639;1104 116A 11B4; # (똹; 똹; 똹; 똹; 똹; ) HANGUL SYLLABLE DDWALT
+B63A;B63A;1104 116A 11B5;B63A;1104 116A 11B5; # (똺; 똺; 똺; 똺; 똺; ) HANGUL SYLLABLE DDWALP
+B63B;B63B;1104 116A 11B6;B63B;1104 116A 11B6; # (똻; 똻; 똻; 똻; 똻; ) HANGUL SYLLABLE DDWALH
+B63C;B63C;1104 116A 11B7;B63C;1104 116A 11B7; # (똼; 똼; 똼; 똼; 똼; ) HANGUL SYLLABLE DDWAM
+B63D;B63D;1104 116A 11B8;B63D;1104 116A 11B8; # (똽; 똽; 똽; 똽; 똽; ) HANGUL SYLLABLE DDWAB
+B63E;B63E;1104 116A 11B9;B63E;1104 116A 11B9; # (똾; 똾; 똾; 똾; 똾; ) HANGUL SYLLABLE DDWABS
+B63F;B63F;1104 116A 11BA;B63F;1104 116A 11BA; # (똿; 똿; 똿; 똿; 똿; ) HANGUL SYLLABLE DDWAS
+B640;B640;1104 116A 11BB;B640;1104 116A 11BB; # (뙀; 뙀; 뙀; 뙀; 뙀; ) HANGUL SYLLABLE DDWASS
+B641;B641;1104 116A 11BC;B641;1104 116A 11BC; # (뙁; 뙁; 뙁; 뙁; 뙁; ) HANGUL SYLLABLE DDWANG
+B642;B642;1104 116A 11BD;B642;1104 116A 11BD; # (뙂; 뙂; 뙂; 뙂; 뙂; ) HANGUL SYLLABLE DDWAJ
+B643;B643;1104 116A 11BE;B643;1104 116A 11BE; # (뙃; 뙃; 뙃; 뙃; 뙃; ) HANGUL SYLLABLE DDWAC
+B644;B644;1104 116A 11BF;B644;1104 116A 11BF; # (뙄; 뙄; 뙄; 뙄; 뙄; ) HANGUL SYLLABLE DDWAK
+B645;B645;1104 116A 11C0;B645;1104 116A 11C0; # (뙅; 뙅; 뙅; 뙅; 뙅; ) HANGUL SYLLABLE DDWAT
+B646;B646;1104 116A 11C1;B646;1104 116A 11C1; # (뙆; 뙆; 뙆; 뙆; 뙆; ) HANGUL SYLLABLE DDWAP
+B647;B647;1104 116A 11C2;B647;1104 116A 11C2; # (뙇; 뙇; 뙇; 뙇; 뙇; ) HANGUL SYLLABLE DDWAH
+B648;B648;1104 116B;B648;1104 116B; # (뙈; 뙈; 뙈; 뙈; 뙈; ) HANGUL SYLLABLE DDWAE
+B649;B649;1104 116B 11A8;B649;1104 116B 11A8; # (뙉; 뙉; 뙉; 뙉; 뙉; ) HANGUL SYLLABLE DDWAEG
+B64A;B64A;1104 116B 11A9;B64A;1104 116B 11A9; # (뙊; 뙊; 뙊; 뙊; 뙊; ) HANGUL SYLLABLE DDWAEGG
+B64B;B64B;1104 116B 11AA;B64B;1104 116B 11AA; # (뙋; 뙋; 뙋; 뙋; 뙋; ) HANGUL SYLLABLE DDWAEGS
+B64C;B64C;1104 116B 11AB;B64C;1104 116B 11AB; # (뙌; 뙌; 뙌; 뙌; 뙌; ) HANGUL SYLLABLE DDWAEN
+B64D;B64D;1104 116B 11AC;B64D;1104 116B 11AC; # (뙍; 뙍; 뙍; 뙍; 뙍; ) HANGUL SYLLABLE DDWAENJ
+B64E;B64E;1104 116B 11AD;B64E;1104 116B 11AD; # (뙎; 뙎; 뙎; 뙎; 뙎; ) HANGUL SYLLABLE DDWAENH
+B64F;B64F;1104 116B 11AE;B64F;1104 116B 11AE; # (뙏; 뙏; 뙏; 뙏; 뙏; ) HANGUL SYLLABLE DDWAED
+B650;B650;1104 116B 11AF;B650;1104 116B 11AF; # (뙐; 뙐; 뙐; 뙐; 뙐; ) HANGUL SYLLABLE DDWAEL
+B651;B651;1104 116B 11B0;B651;1104 116B 11B0; # (뙑; 뙑; 뙑; 뙑; 뙑; ) HANGUL SYLLABLE DDWAELG
+B652;B652;1104 116B 11B1;B652;1104 116B 11B1; # (뙒; 뙒; 뙒; 뙒; 뙒; ) HANGUL SYLLABLE DDWAELM
+B653;B653;1104 116B 11B2;B653;1104 116B 11B2; # (뙓; 뙓; 뙓; 뙓; 뙓; ) HANGUL SYLLABLE DDWAELB
+B654;B654;1104 116B 11B3;B654;1104 116B 11B3; # (뙔; 뙔; 뙔; 뙔; 뙔; ) HANGUL SYLLABLE DDWAELS
+B655;B655;1104 116B 11B4;B655;1104 116B 11B4; # (뙕; 뙕; 뙕; 뙕; 뙕; ) HANGUL SYLLABLE DDWAELT
+B656;B656;1104 116B 11B5;B656;1104 116B 11B5; # (뙖; 뙖; 뙖; 뙖; 뙖; ) HANGUL SYLLABLE DDWAELP
+B657;B657;1104 116B 11B6;B657;1104 116B 11B6; # (뙗; 뙗; 뙗; 뙗; 뙗; ) HANGUL SYLLABLE DDWAELH
+B658;B658;1104 116B 11B7;B658;1104 116B 11B7; # (뙘; 뙘; 뙘; 뙘; 뙘; ) HANGUL SYLLABLE DDWAEM
+B659;B659;1104 116B 11B8;B659;1104 116B 11B8; # (뙙; 뙙; 뙙; 뙙; 뙙; ) HANGUL SYLLABLE DDWAEB
+B65A;B65A;1104 116B 11B9;B65A;1104 116B 11B9; # (뙚; 뙚; 뙚; 뙚; 뙚; ) HANGUL SYLLABLE DDWAEBS
+B65B;B65B;1104 116B 11BA;B65B;1104 116B 11BA; # (뙛; 뙛; 뙛; 뙛; 뙛; ) HANGUL SYLLABLE DDWAES
+B65C;B65C;1104 116B 11BB;B65C;1104 116B 11BB; # (뙜; 뙜; 뙜; 뙜; 뙜; ) HANGUL SYLLABLE DDWAESS
+B65D;B65D;1104 116B 11BC;B65D;1104 116B 11BC; # (뙝; 뙝; 뙝; 뙝; 뙝; ) HANGUL SYLLABLE DDWAENG
+B65E;B65E;1104 116B 11BD;B65E;1104 116B 11BD; # (뙞; 뙞; 뙞; 뙞; 뙞; ) HANGUL SYLLABLE DDWAEJ
+B65F;B65F;1104 116B 11BE;B65F;1104 116B 11BE; # (뙟; 뙟; 뙟; 뙟; 뙟; ) HANGUL SYLLABLE DDWAEC
+B660;B660;1104 116B 11BF;B660;1104 116B 11BF; # (뙠; 뙠; 뙠; 뙠; 뙠; ) HANGUL SYLLABLE DDWAEK
+B661;B661;1104 116B 11C0;B661;1104 116B 11C0; # (뙡; 뙡; 뙡; 뙡; 뙡; ) HANGUL SYLLABLE DDWAET
+B662;B662;1104 116B 11C1;B662;1104 116B 11C1; # (뙢; 뙢; 뙢; 뙢; 뙢; ) HANGUL SYLLABLE DDWAEP
+B663;B663;1104 116B 11C2;B663;1104 116B 11C2; # (뙣; 뙣; 뙣; 뙣; 뙣; ) HANGUL SYLLABLE DDWAEH
+B664;B664;1104 116C;B664;1104 116C; # (뙤; 뙤; 뙤; 뙤; 뙤; ) HANGUL SYLLABLE DDOE
+B665;B665;1104 116C 11A8;B665;1104 116C 11A8; # (뙥; 뙥; 뙥; 뙥; 뙥; ) HANGUL SYLLABLE DDOEG
+B666;B666;1104 116C 11A9;B666;1104 116C 11A9; # (뙦; 뙦; 뙦; 뙦; 뙦; ) HANGUL SYLLABLE DDOEGG
+B667;B667;1104 116C 11AA;B667;1104 116C 11AA; # (뙧; 뙧; 뙧; 뙧; 뙧; ) HANGUL SYLLABLE DDOEGS
+B668;B668;1104 116C 11AB;B668;1104 116C 11AB; # (뙨; 뙨; 뙨; 뙨; 뙨; ) HANGUL SYLLABLE DDOEN
+B669;B669;1104 116C 11AC;B669;1104 116C 11AC; # (뙩; 뙩; 뙩; 뙩; 뙩; ) HANGUL SYLLABLE DDOENJ
+B66A;B66A;1104 116C 11AD;B66A;1104 116C 11AD; # (뙪; 뙪; 뙪; 뙪; 뙪; ) HANGUL SYLLABLE DDOENH
+B66B;B66B;1104 116C 11AE;B66B;1104 116C 11AE; # (뙫; 뙫; 뙫; 뙫; 뙫; ) HANGUL SYLLABLE DDOED
+B66C;B66C;1104 116C 11AF;B66C;1104 116C 11AF; # (뙬; 뙬; 뙬; 뙬; 뙬; ) HANGUL SYLLABLE DDOEL
+B66D;B66D;1104 116C 11B0;B66D;1104 116C 11B0; # (뙭; 뙭; 뙭; 뙭; 뙭; ) HANGUL SYLLABLE DDOELG
+B66E;B66E;1104 116C 11B1;B66E;1104 116C 11B1; # (뙮; 뙮; 뙮; 뙮; 뙮; ) HANGUL SYLLABLE DDOELM
+B66F;B66F;1104 116C 11B2;B66F;1104 116C 11B2; # (뙯; 뙯; 뙯; 뙯; 뙯; ) HANGUL SYLLABLE DDOELB
+B670;B670;1104 116C 11B3;B670;1104 116C 11B3; # (뙰; 뙰; 뙰; 뙰; 뙰; ) HANGUL SYLLABLE DDOELS
+B671;B671;1104 116C 11B4;B671;1104 116C 11B4; # (뙱; 뙱; 뙱; 뙱; 뙱; ) HANGUL SYLLABLE DDOELT
+B672;B672;1104 116C 11B5;B672;1104 116C 11B5; # (뙲; 뙲; 뙲; 뙲; 뙲; ) HANGUL SYLLABLE DDOELP
+B673;B673;1104 116C 11B6;B673;1104 116C 11B6; # (뙳; 뙳; 뙳; 뙳; 뙳; ) HANGUL SYLLABLE DDOELH
+B674;B674;1104 116C 11B7;B674;1104 116C 11B7; # (뙴; 뙴; 뙴; 뙴; 뙴; ) HANGUL SYLLABLE DDOEM
+B675;B675;1104 116C 11B8;B675;1104 116C 11B8; # (뙵; 뙵; 뙵; 뙵; 뙵; ) HANGUL SYLLABLE DDOEB
+B676;B676;1104 116C 11B9;B676;1104 116C 11B9; # (뙶; 뙶; 뙶; 뙶; 뙶; ) HANGUL SYLLABLE DDOEBS
+B677;B677;1104 116C 11BA;B677;1104 116C 11BA; # (뙷; 뙷; 뙷; 뙷; 뙷; ) HANGUL SYLLABLE DDOES
+B678;B678;1104 116C 11BB;B678;1104 116C 11BB; # (뙸; 뙸; 뙸; 뙸; 뙸; ) HANGUL SYLLABLE DDOESS
+B679;B679;1104 116C 11BC;B679;1104 116C 11BC; # (뙹; 뙹; 뙹; 뙹; 뙹; ) HANGUL SYLLABLE DDOENG
+B67A;B67A;1104 116C 11BD;B67A;1104 116C 11BD; # (뙺; 뙺; 뙺; 뙺; 뙺; ) HANGUL SYLLABLE DDOEJ
+B67B;B67B;1104 116C 11BE;B67B;1104 116C 11BE; # (뙻; 뙻; 뙻; 뙻; 뙻; ) HANGUL SYLLABLE DDOEC
+B67C;B67C;1104 116C 11BF;B67C;1104 116C 11BF; # (뙼; 뙼; 뙼; 뙼; 뙼; ) HANGUL SYLLABLE DDOEK
+B67D;B67D;1104 116C 11C0;B67D;1104 116C 11C0; # (뙽; 뙽; 뙽; 뙽; 뙽; ) HANGUL SYLLABLE DDOET
+B67E;B67E;1104 116C 11C1;B67E;1104 116C 11C1; # (뙾; 뙾; 뙾; 뙾; 뙾; ) HANGUL SYLLABLE DDOEP
+B67F;B67F;1104 116C 11C2;B67F;1104 116C 11C2; # (뙿; 뙿; 뙿; 뙿; 뙿; ) HANGUL SYLLABLE DDOEH
+B680;B680;1104 116D;B680;1104 116D; # (뚀; 뚀; 뚀; 뚀; 뚀; ) HANGUL SYLLABLE DDYO
+B681;B681;1104 116D 11A8;B681;1104 116D 11A8; # (뚁; 뚁; 뚁; 뚁; 뚁; ) HANGUL SYLLABLE DDYOG
+B682;B682;1104 116D 11A9;B682;1104 116D 11A9; # (뚂; 뚂; 뚂; 뚂; 뚂; ) HANGUL SYLLABLE DDYOGG
+B683;B683;1104 116D 11AA;B683;1104 116D 11AA; # (뚃; 뚃; 뚃; 뚃; 뚃; ) HANGUL SYLLABLE DDYOGS
+B684;B684;1104 116D 11AB;B684;1104 116D 11AB; # (뚄; 뚄; 뚄; 뚄; 뚄; ) HANGUL SYLLABLE DDYON
+B685;B685;1104 116D 11AC;B685;1104 116D 11AC; # (뚅; 뚅; 뚅; 뚅; 뚅; ) HANGUL SYLLABLE DDYONJ
+B686;B686;1104 116D 11AD;B686;1104 116D 11AD; # (뚆; 뚆; 뚆; 뚆; 뚆; ) HANGUL SYLLABLE DDYONH
+B687;B687;1104 116D 11AE;B687;1104 116D 11AE; # (뚇; 뚇; 뚇; 뚇; 뚇; ) HANGUL SYLLABLE DDYOD
+B688;B688;1104 116D 11AF;B688;1104 116D 11AF; # (뚈; 뚈; 뚈; 뚈; 뚈; ) HANGUL SYLLABLE DDYOL
+B689;B689;1104 116D 11B0;B689;1104 116D 11B0; # (뚉; 뚉; 뚉; 뚉; 뚉; ) HANGUL SYLLABLE DDYOLG
+B68A;B68A;1104 116D 11B1;B68A;1104 116D 11B1; # (뚊; 뚊; 뚊; 뚊; 뚊; ) HANGUL SYLLABLE DDYOLM
+B68B;B68B;1104 116D 11B2;B68B;1104 116D 11B2; # (뚋; 뚋; 뚋; 뚋; 뚋; ) HANGUL SYLLABLE DDYOLB
+B68C;B68C;1104 116D 11B3;B68C;1104 116D 11B3; # (뚌; 뚌; 뚌; 뚌; 뚌; ) HANGUL SYLLABLE DDYOLS
+B68D;B68D;1104 116D 11B4;B68D;1104 116D 11B4; # (뚍; 뚍; 뚍; 뚍; 뚍; ) HANGUL SYLLABLE DDYOLT
+B68E;B68E;1104 116D 11B5;B68E;1104 116D 11B5; # (뚎; 뚎; 뚎; 뚎; 뚎; ) HANGUL SYLLABLE DDYOLP
+B68F;B68F;1104 116D 11B6;B68F;1104 116D 11B6; # (뚏; 뚏; 뚏; 뚏; 뚏; ) HANGUL SYLLABLE DDYOLH
+B690;B690;1104 116D 11B7;B690;1104 116D 11B7; # (뚐; 뚐; 뚐; 뚐; 뚐; ) HANGUL SYLLABLE DDYOM
+B691;B691;1104 116D 11B8;B691;1104 116D 11B8; # (뚑; 뚑; 뚑; 뚑; 뚑; ) HANGUL SYLLABLE DDYOB
+B692;B692;1104 116D 11B9;B692;1104 116D 11B9; # (뚒; 뚒; 뚒; 뚒; 뚒; ) HANGUL SYLLABLE DDYOBS
+B693;B693;1104 116D 11BA;B693;1104 116D 11BA; # (뚓; 뚓; 뚓; 뚓; 뚓; ) HANGUL SYLLABLE DDYOS
+B694;B694;1104 116D 11BB;B694;1104 116D 11BB; # (뚔; 뚔; 뚔; 뚔; 뚔; ) HANGUL SYLLABLE DDYOSS
+B695;B695;1104 116D 11BC;B695;1104 116D 11BC; # (뚕; 뚕; 뚕; 뚕; 뚕; ) HANGUL SYLLABLE DDYONG
+B696;B696;1104 116D 11BD;B696;1104 116D 11BD; # (뚖; 뚖; 뚖; 뚖; 뚖; ) HANGUL SYLLABLE DDYOJ
+B697;B697;1104 116D 11BE;B697;1104 116D 11BE; # (뚗; 뚗; 뚗; 뚗; 뚗; ) HANGUL SYLLABLE DDYOC
+B698;B698;1104 116D 11BF;B698;1104 116D 11BF; # (뚘; 뚘; 뚘; 뚘; 뚘; ) HANGUL SYLLABLE DDYOK
+B699;B699;1104 116D 11C0;B699;1104 116D 11C0; # (뚙; 뚙; 뚙; 뚙; 뚙; ) HANGUL SYLLABLE DDYOT
+B69A;B69A;1104 116D 11C1;B69A;1104 116D 11C1; # (뚚; 뚚; 뚚; 뚚; 뚚; ) HANGUL SYLLABLE DDYOP
+B69B;B69B;1104 116D 11C2;B69B;1104 116D 11C2; # (뚛; 뚛; 뚛; 뚛; 뚛; ) HANGUL SYLLABLE DDYOH
+B69C;B69C;1104 116E;B69C;1104 116E; # (뚜; 뚜; 뚜; 뚜; 뚜; ) HANGUL SYLLABLE DDU
+B69D;B69D;1104 116E 11A8;B69D;1104 116E 11A8; # (뚝; 뚝; 뚝; 뚝; 뚝; ) HANGUL SYLLABLE DDUG
+B69E;B69E;1104 116E 11A9;B69E;1104 116E 11A9; # (뚞; 뚞; 뚞; 뚞; 뚞; ) HANGUL SYLLABLE DDUGG
+B69F;B69F;1104 116E 11AA;B69F;1104 116E 11AA; # (뚟; 뚟; 뚟; 뚟; 뚟; ) HANGUL SYLLABLE DDUGS
+B6A0;B6A0;1104 116E 11AB;B6A0;1104 116E 11AB; # (뚠; 뚠; 뚠; 뚠; 뚠; ) HANGUL SYLLABLE DDUN
+B6A1;B6A1;1104 116E 11AC;B6A1;1104 116E 11AC; # (뚡; 뚡; 뚡; 뚡; 뚡; ) HANGUL SYLLABLE DDUNJ
+B6A2;B6A2;1104 116E 11AD;B6A2;1104 116E 11AD; # (뚢; 뚢; 뚢; 뚢; 뚢; ) HANGUL SYLLABLE DDUNH
+B6A3;B6A3;1104 116E 11AE;B6A3;1104 116E 11AE; # (뚣; 뚣; 뚣; 뚣; 뚣; ) HANGUL SYLLABLE DDUD
+B6A4;B6A4;1104 116E 11AF;B6A4;1104 116E 11AF; # (뚤; 뚤; 뚤; 뚤; 뚤; ) HANGUL SYLLABLE DDUL
+B6A5;B6A5;1104 116E 11B0;B6A5;1104 116E 11B0; # (뚥; 뚥; 뚥; 뚥; 뚥; ) HANGUL SYLLABLE DDULG
+B6A6;B6A6;1104 116E 11B1;B6A6;1104 116E 11B1; # (뚦; 뚦; 뚦; 뚦; 뚦; ) HANGUL SYLLABLE DDULM
+B6A7;B6A7;1104 116E 11B2;B6A7;1104 116E 11B2; # (뚧; 뚧; 뚧; 뚧; 뚧; ) HANGUL SYLLABLE DDULB
+B6A8;B6A8;1104 116E 11B3;B6A8;1104 116E 11B3; # (뚨; 뚨; 뚨; 뚨; 뚨; ) HANGUL SYLLABLE DDULS
+B6A9;B6A9;1104 116E 11B4;B6A9;1104 116E 11B4; # (뚩; 뚩; 뚩; 뚩; 뚩; ) HANGUL SYLLABLE DDULT
+B6AA;B6AA;1104 116E 11B5;B6AA;1104 116E 11B5; # (뚪; 뚪; 뚪; 뚪; 뚪; ) HANGUL SYLLABLE DDULP
+B6AB;B6AB;1104 116E 11B6;B6AB;1104 116E 11B6; # (뚫; 뚫; 뚫; 뚫; 뚫; ) HANGUL SYLLABLE DDULH
+B6AC;B6AC;1104 116E 11B7;B6AC;1104 116E 11B7; # (뚬; 뚬; 뚬; 뚬; 뚬; ) HANGUL SYLLABLE DDUM
+B6AD;B6AD;1104 116E 11B8;B6AD;1104 116E 11B8; # (뚭; 뚭; 뚭; 뚭; 뚭; ) HANGUL SYLLABLE DDUB
+B6AE;B6AE;1104 116E 11B9;B6AE;1104 116E 11B9; # (뚮; 뚮; 뚮; 뚮; 뚮; ) HANGUL SYLLABLE DDUBS
+B6AF;B6AF;1104 116E 11BA;B6AF;1104 116E 11BA; # (뚯; 뚯; 뚯; 뚯; 뚯; ) HANGUL SYLLABLE DDUS
+B6B0;B6B0;1104 116E 11BB;B6B0;1104 116E 11BB; # (뚰; 뚰; 뚰; 뚰; 뚰; ) HANGUL SYLLABLE DDUSS
+B6B1;B6B1;1104 116E 11BC;B6B1;1104 116E 11BC; # (뚱; 뚱; 뚱; 뚱; 뚱; ) HANGUL SYLLABLE DDUNG
+B6B2;B6B2;1104 116E 11BD;B6B2;1104 116E 11BD; # (뚲; 뚲; 뚲; 뚲; 뚲; ) HANGUL SYLLABLE DDUJ
+B6B3;B6B3;1104 116E 11BE;B6B3;1104 116E 11BE; # (뚳; 뚳; 뚳; 뚳; 뚳; ) HANGUL SYLLABLE DDUC
+B6B4;B6B4;1104 116E 11BF;B6B4;1104 116E 11BF; # (뚴; 뚴; 뚴; 뚴; 뚴; ) HANGUL SYLLABLE DDUK
+B6B5;B6B5;1104 116E 11C0;B6B5;1104 116E 11C0; # (뚵; 뚵; 뚵; 뚵; 뚵; ) HANGUL SYLLABLE DDUT
+B6B6;B6B6;1104 116E 11C1;B6B6;1104 116E 11C1; # (뚶; 뚶; 뚶; 뚶; 뚶; ) HANGUL SYLLABLE DDUP
+B6B7;B6B7;1104 116E 11C2;B6B7;1104 116E 11C2; # (뚷; 뚷; 뚷; 뚷; 뚷; ) HANGUL SYLLABLE DDUH
+B6B8;B6B8;1104 116F;B6B8;1104 116F; # (뚸; 뚸; 뚸; 뚸; 뚸; ) HANGUL SYLLABLE DDWEO
+B6B9;B6B9;1104 116F 11A8;B6B9;1104 116F 11A8; # (뚹; 뚹; 뚹; 뚹; 뚹; ) HANGUL SYLLABLE DDWEOG
+B6BA;B6BA;1104 116F 11A9;B6BA;1104 116F 11A9; # (뚺; 뚺; 뚺; 뚺; 뚺; ) HANGUL SYLLABLE DDWEOGG
+B6BB;B6BB;1104 116F 11AA;B6BB;1104 116F 11AA; # (뚻; 뚻; 뚻; 뚻; 뚻; ) HANGUL SYLLABLE DDWEOGS
+B6BC;B6BC;1104 116F 11AB;B6BC;1104 116F 11AB; # (뚼; 뚼; 뚼; 뚼; 뚼; ) HANGUL SYLLABLE DDWEON
+B6BD;B6BD;1104 116F 11AC;B6BD;1104 116F 11AC; # (뚽; 뚽; 뚽; 뚽; 뚽; ) HANGUL SYLLABLE DDWEONJ
+B6BE;B6BE;1104 116F 11AD;B6BE;1104 116F 11AD; # (뚾; 뚾; 뚾; 뚾; 뚾; ) HANGUL SYLLABLE DDWEONH
+B6BF;B6BF;1104 116F 11AE;B6BF;1104 116F 11AE; # (뚿; 뚿; 뚿; 뚿; 뚿; ) HANGUL SYLLABLE DDWEOD
+B6C0;B6C0;1104 116F 11AF;B6C0;1104 116F 11AF; # (뛀; 뛀; 뛀; 뛀; 뛀; ) HANGUL SYLLABLE DDWEOL
+B6C1;B6C1;1104 116F 11B0;B6C1;1104 116F 11B0; # (뛁; 뛁; 뛁; 뛁; 뛁; ) HANGUL SYLLABLE DDWEOLG
+B6C2;B6C2;1104 116F 11B1;B6C2;1104 116F 11B1; # (뛂; 뛂; 뛂; 뛂; 뛂; ) HANGUL SYLLABLE DDWEOLM
+B6C3;B6C3;1104 116F 11B2;B6C3;1104 116F 11B2; # (뛃; 뛃; 뛃; 뛃; 뛃; ) HANGUL SYLLABLE DDWEOLB
+B6C4;B6C4;1104 116F 11B3;B6C4;1104 116F 11B3; # (뛄; 뛄; 뛄; 뛄; 뛄; ) HANGUL SYLLABLE DDWEOLS
+B6C5;B6C5;1104 116F 11B4;B6C5;1104 116F 11B4; # (뛅; 뛅; 뛅; 뛅; 뛅; ) HANGUL SYLLABLE DDWEOLT
+B6C6;B6C6;1104 116F 11B5;B6C6;1104 116F 11B5; # (뛆; 뛆; 뛆; 뛆; 뛆; ) HANGUL SYLLABLE DDWEOLP
+B6C7;B6C7;1104 116F 11B6;B6C7;1104 116F 11B6; # (뛇; 뛇; 뛇; 뛇; 뛇; ) HANGUL SYLLABLE DDWEOLH
+B6C8;B6C8;1104 116F 11B7;B6C8;1104 116F 11B7; # (뛈; 뛈; 뛈; 뛈; 뛈; ) HANGUL SYLLABLE DDWEOM
+B6C9;B6C9;1104 116F 11B8;B6C9;1104 116F 11B8; # (뛉; 뛉; 뛉; 뛉; 뛉; ) HANGUL SYLLABLE DDWEOB
+B6CA;B6CA;1104 116F 11B9;B6CA;1104 116F 11B9; # (뛊; 뛊; 뛊; 뛊; 뛊; ) HANGUL SYLLABLE DDWEOBS
+B6CB;B6CB;1104 116F 11BA;B6CB;1104 116F 11BA; # (뛋; 뛋; 뛋; 뛋; 뛋; ) HANGUL SYLLABLE DDWEOS
+B6CC;B6CC;1104 116F 11BB;B6CC;1104 116F 11BB; # (뛌; 뛌; 뛌; 뛌; 뛌; ) HANGUL SYLLABLE DDWEOSS
+B6CD;B6CD;1104 116F 11BC;B6CD;1104 116F 11BC; # (뛍; 뛍; 뛍; 뛍; 뛍; ) HANGUL SYLLABLE DDWEONG
+B6CE;B6CE;1104 116F 11BD;B6CE;1104 116F 11BD; # (뛎; 뛎; 뛎; 뛎; 뛎; ) HANGUL SYLLABLE DDWEOJ
+B6CF;B6CF;1104 116F 11BE;B6CF;1104 116F 11BE; # (뛏; 뛏; 뛏; 뛏; 뛏; ) HANGUL SYLLABLE DDWEOC
+B6D0;B6D0;1104 116F 11BF;B6D0;1104 116F 11BF; # (뛐; 뛐; 뛐; 뛐; 뛐; ) HANGUL SYLLABLE DDWEOK
+B6D1;B6D1;1104 116F 11C0;B6D1;1104 116F 11C0; # (뛑; 뛑; 뛑; 뛑; 뛑; ) HANGUL SYLLABLE DDWEOT
+B6D2;B6D2;1104 116F 11C1;B6D2;1104 116F 11C1; # (뛒; 뛒; 뛒; 뛒; 뛒; ) HANGUL SYLLABLE DDWEOP
+B6D3;B6D3;1104 116F 11C2;B6D3;1104 116F 11C2; # (뛓; 뛓; 뛓; 뛓; 뛓; ) HANGUL SYLLABLE DDWEOH
+B6D4;B6D4;1104 1170;B6D4;1104 1170; # (뛔; 뛔; 뛔; 뛔; 뛔; ) HANGUL SYLLABLE DDWE
+B6D5;B6D5;1104 1170 11A8;B6D5;1104 1170 11A8; # (뛕; 뛕; 뛕; 뛕; 뛕; ) HANGUL SYLLABLE DDWEG
+B6D6;B6D6;1104 1170 11A9;B6D6;1104 1170 11A9; # (뛖; 뛖; 뛖; 뛖; 뛖; ) HANGUL SYLLABLE DDWEGG
+B6D7;B6D7;1104 1170 11AA;B6D7;1104 1170 11AA; # (뛗; 뛗; 뛗; 뛗; 뛗; ) HANGUL SYLLABLE DDWEGS
+B6D8;B6D8;1104 1170 11AB;B6D8;1104 1170 11AB; # (뛘; 뛘; 뛘; 뛘; 뛘; ) HANGUL SYLLABLE DDWEN
+B6D9;B6D9;1104 1170 11AC;B6D9;1104 1170 11AC; # (뛙; 뛙; 뛙; 뛙; 뛙; ) HANGUL SYLLABLE DDWENJ
+B6DA;B6DA;1104 1170 11AD;B6DA;1104 1170 11AD; # (뛚; 뛚; 뛚; 뛚; 뛚; ) HANGUL SYLLABLE DDWENH
+B6DB;B6DB;1104 1170 11AE;B6DB;1104 1170 11AE; # (뛛; 뛛; 뛛; 뛛; 뛛; ) HANGUL SYLLABLE DDWED
+B6DC;B6DC;1104 1170 11AF;B6DC;1104 1170 11AF; # (뛜; 뛜; 뛜; 뛜; 뛜; ) HANGUL SYLLABLE DDWEL
+B6DD;B6DD;1104 1170 11B0;B6DD;1104 1170 11B0; # (뛝; 뛝; 뛝; 뛝; 뛝; ) HANGUL SYLLABLE DDWELG
+B6DE;B6DE;1104 1170 11B1;B6DE;1104 1170 11B1; # (뛞; 뛞; 뛞; 뛞; 뛞; ) HANGUL SYLLABLE DDWELM
+B6DF;B6DF;1104 1170 11B2;B6DF;1104 1170 11B2; # (뛟; 뛟; 뛟; 뛟; 뛟; ) HANGUL SYLLABLE DDWELB
+B6E0;B6E0;1104 1170 11B3;B6E0;1104 1170 11B3; # (뛠; 뛠; 뛠; 뛠; 뛠; ) HANGUL SYLLABLE DDWELS
+B6E1;B6E1;1104 1170 11B4;B6E1;1104 1170 11B4; # (뛡; 뛡; 뛡; 뛡; 뛡; ) HANGUL SYLLABLE DDWELT
+B6E2;B6E2;1104 1170 11B5;B6E2;1104 1170 11B5; # (뛢; 뛢; 뛢; 뛢; 뛢; ) HANGUL SYLLABLE DDWELP
+B6E3;B6E3;1104 1170 11B6;B6E3;1104 1170 11B6; # (뛣; 뛣; 뛣; 뛣; 뛣; ) HANGUL SYLLABLE DDWELH
+B6E4;B6E4;1104 1170 11B7;B6E4;1104 1170 11B7; # (뛤; 뛤; 뛤; 뛤; 뛤; ) HANGUL SYLLABLE DDWEM
+B6E5;B6E5;1104 1170 11B8;B6E5;1104 1170 11B8; # (뛥; 뛥; 뛥; 뛥; 뛥; ) HANGUL SYLLABLE DDWEB
+B6E6;B6E6;1104 1170 11B9;B6E6;1104 1170 11B9; # (뛦; 뛦; 뛦; 뛦; 뛦; ) HANGUL SYLLABLE DDWEBS
+B6E7;B6E7;1104 1170 11BA;B6E7;1104 1170 11BA; # (뛧; 뛧; 뛧; 뛧; 뛧; ) HANGUL SYLLABLE DDWES
+B6E8;B6E8;1104 1170 11BB;B6E8;1104 1170 11BB; # (뛨; 뛨; 뛨; 뛨; 뛨; ) HANGUL SYLLABLE DDWESS
+B6E9;B6E9;1104 1170 11BC;B6E9;1104 1170 11BC; # (뛩; 뛩; 뛩; 뛩; 뛩; ) HANGUL SYLLABLE DDWENG
+B6EA;B6EA;1104 1170 11BD;B6EA;1104 1170 11BD; # (뛪; 뛪; 뛪; 뛪; 뛪; ) HANGUL SYLLABLE DDWEJ
+B6EB;B6EB;1104 1170 11BE;B6EB;1104 1170 11BE; # (뛫; 뛫; 뛫; 뛫; 뛫; ) HANGUL SYLLABLE DDWEC
+B6EC;B6EC;1104 1170 11BF;B6EC;1104 1170 11BF; # (뛬; 뛬; 뛬; 뛬; 뛬; ) HANGUL SYLLABLE DDWEK
+B6ED;B6ED;1104 1170 11C0;B6ED;1104 1170 11C0; # (뛭; 뛭; 뛭; 뛭; 뛭; ) HANGUL SYLLABLE DDWET
+B6EE;B6EE;1104 1170 11C1;B6EE;1104 1170 11C1; # (뛮; 뛮; 뛮; 뛮; 뛮; ) HANGUL SYLLABLE DDWEP
+B6EF;B6EF;1104 1170 11C2;B6EF;1104 1170 11C2; # (뛯; 뛯; 뛯; 뛯; 뛯; ) HANGUL SYLLABLE DDWEH
+B6F0;B6F0;1104 1171;B6F0;1104 1171; # (뛰; 뛰; 뛰; 뛰; 뛰; ) HANGUL SYLLABLE DDWI
+B6F1;B6F1;1104 1171 11A8;B6F1;1104 1171 11A8; # (뛱; 뛱; 뛱; 뛱; 뛱; ) HANGUL SYLLABLE DDWIG
+B6F2;B6F2;1104 1171 11A9;B6F2;1104 1171 11A9; # (뛲; 뛲; 뛲; 뛲; 뛲; ) HANGUL SYLLABLE DDWIGG
+B6F3;B6F3;1104 1171 11AA;B6F3;1104 1171 11AA; # (뛳; 뛳; 뛳; 뛳; 뛳; ) HANGUL SYLLABLE DDWIGS
+B6F4;B6F4;1104 1171 11AB;B6F4;1104 1171 11AB; # (뛴; 뛴; 뛴; 뛴; 뛴; ) HANGUL SYLLABLE DDWIN
+B6F5;B6F5;1104 1171 11AC;B6F5;1104 1171 11AC; # (뛵; 뛵; 뛵; 뛵; 뛵; ) HANGUL SYLLABLE DDWINJ
+B6F6;B6F6;1104 1171 11AD;B6F6;1104 1171 11AD; # (뛶; 뛶; 뛶; 뛶; 뛶; ) HANGUL SYLLABLE DDWINH
+B6F7;B6F7;1104 1171 11AE;B6F7;1104 1171 11AE; # (뛷; 뛷; 뛷; 뛷; 뛷; ) HANGUL SYLLABLE DDWID
+B6F8;B6F8;1104 1171 11AF;B6F8;1104 1171 11AF; # (뛸; 뛸; 뛸; 뛸; 뛸; ) HANGUL SYLLABLE DDWIL
+B6F9;B6F9;1104 1171 11B0;B6F9;1104 1171 11B0; # (뛹; 뛹; 뛹; 뛹; 뛹; ) HANGUL SYLLABLE DDWILG
+B6FA;B6FA;1104 1171 11B1;B6FA;1104 1171 11B1; # (뛺; 뛺; 뛺; 뛺; 뛺; ) HANGUL SYLLABLE DDWILM
+B6FB;B6FB;1104 1171 11B2;B6FB;1104 1171 11B2; # (뛻; 뛻; 뛻; 뛻; 뛻; ) HANGUL SYLLABLE DDWILB
+B6FC;B6FC;1104 1171 11B3;B6FC;1104 1171 11B3; # (뛼; 뛼; 뛼; 뛼; 뛼; ) HANGUL SYLLABLE DDWILS
+B6FD;B6FD;1104 1171 11B4;B6FD;1104 1171 11B4; # (뛽; 뛽; 뛽; 뛽; 뛽; ) HANGUL SYLLABLE DDWILT
+B6FE;B6FE;1104 1171 11B5;B6FE;1104 1171 11B5; # (뛾; 뛾; 뛾; 뛾; 뛾; ) HANGUL SYLLABLE DDWILP
+B6FF;B6FF;1104 1171 11B6;B6FF;1104 1171 11B6; # (뛿; 뛿; 뛿; 뛿; 뛿; ) HANGUL SYLLABLE DDWILH
+B700;B700;1104 1171 11B7;B700;1104 1171 11B7; # (뜀; 뜀; 뜀; 뜀; 뜀; ) HANGUL SYLLABLE DDWIM
+B701;B701;1104 1171 11B8;B701;1104 1171 11B8; # (뜁; 뜁; 뜁; 뜁; 뜁; ) HANGUL SYLLABLE DDWIB
+B702;B702;1104 1171 11B9;B702;1104 1171 11B9; # (뜂; 뜂; 뜂; 뜂; 뜂; ) HANGUL SYLLABLE DDWIBS
+B703;B703;1104 1171 11BA;B703;1104 1171 11BA; # (뜃; 뜃; 뜃; 뜃; 뜃; ) HANGUL SYLLABLE DDWIS
+B704;B704;1104 1171 11BB;B704;1104 1171 11BB; # (뜄; 뜄; 뜄; 뜄; 뜄; ) HANGUL SYLLABLE DDWISS
+B705;B705;1104 1171 11BC;B705;1104 1171 11BC; # (뜅; 뜅; 뜅; 뜅; 뜅; ) HANGUL SYLLABLE DDWING
+B706;B706;1104 1171 11BD;B706;1104 1171 11BD; # (뜆; 뜆; 뜆; 뜆; 뜆; ) HANGUL SYLLABLE DDWIJ
+B707;B707;1104 1171 11BE;B707;1104 1171 11BE; # (뜇; 뜇; 뜇; 뜇; 뜇; ) HANGUL SYLLABLE DDWIC
+B708;B708;1104 1171 11BF;B708;1104 1171 11BF; # (뜈; 뜈; 뜈; 뜈; 뜈; ) HANGUL SYLLABLE DDWIK
+B709;B709;1104 1171 11C0;B709;1104 1171 11C0; # (뜉; 뜉; 뜉; 뜉; 뜉; ) HANGUL SYLLABLE DDWIT
+B70A;B70A;1104 1171 11C1;B70A;1104 1171 11C1; # (뜊; 뜊; 뜊; 뜊; 뜊; ) HANGUL SYLLABLE DDWIP
+B70B;B70B;1104 1171 11C2;B70B;1104 1171 11C2; # (뜋; 뜋; 뜋; 뜋; 뜋; ) HANGUL SYLLABLE DDWIH
+B70C;B70C;1104 1172;B70C;1104 1172; # (뜌; 뜌; 뜌; 뜌; 뜌; ) HANGUL SYLLABLE DDYU
+B70D;B70D;1104 1172 11A8;B70D;1104 1172 11A8; # (뜍; 뜍; 뜍; 뜍; 뜍; ) HANGUL SYLLABLE DDYUG
+B70E;B70E;1104 1172 11A9;B70E;1104 1172 11A9; # (뜎; 뜎; 뜎; 뜎; 뜎; ) HANGUL SYLLABLE DDYUGG
+B70F;B70F;1104 1172 11AA;B70F;1104 1172 11AA; # (뜏; 뜏; 뜏; 뜏; 뜏; ) HANGUL SYLLABLE DDYUGS
+B710;B710;1104 1172 11AB;B710;1104 1172 11AB; # (뜐; 뜐; 뜐; 뜐; 뜐; ) HANGUL SYLLABLE DDYUN
+B711;B711;1104 1172 11AC;B711;1104 1172 11AC; # (뜑; 뜑; 뜑; 뜑; 뜑; ) HANGUL SYLLABLE DDYUNJ
+B712;B712;1104 1172 11AD;B712;1104 1172 11AD; # (뜒; 뜒; 뜒; 뜒; 뜒; ) HANGUL SYLLABLE DDYUNH
+B713;B713;1104 1172 11AE;B713;1104 1172 11AE; # (뜓; 뜓; 뜓; 뜓; 뜓; ) HANGUL SYLLABLE DDYUD
+B714;B714;1104 1172 11AF;B714;1104 1172 11AF; # (뜔; 뜔; 뜔; 뜔; 뜔; ) HANGUL SYLLABLE DDYUL
+B715;B715;1104 1172 11B0;B715;1104 1172 11B0; # (뜕; 뜕; 뜕; 뜕; 뜕; ) HANGUL SYLLABLE DDYULG
+B716;B716;1104 1172 11B1;B716;1104 1172 11B1; # (뜖; 뜖; 뜖; 뜖; 뜖; ) HANGUL SYLLABLE DDYULM
+B717;B717;1104 1172 11B2;B717;1104 1172 11B2; # (뜗; 뜗; 뜗; 뜗; 뜗; ) HANGUL SYLLABLE DDYULB
+B718;B718;1104 1172 11B3;B718;1104 1172 11B3; # (뜘; 뜘; 뜘; 뜘; 뜘; ) HANGUL SYLLABLE DDYULS
+B719;B719;1104 1172 11B4;B719;1104 1172 11B4; # (뜙; 뜙; 뜙; 뜙; 뜙; ) HANGUL SYLLABLE DDYULT
+B71A;B71A;1104 1172 11B5;B71A;1104 1172 11B5; # (뜚; 뜚; 뜚; 뜚; 뜚; ) HANGUL SYLLABLE DDYULP
+B71B;B71B;1104 1172 11B6;B71B;1104 1172 11B6; # (뜛; 뜛; 뜛; 뜛; 뜛; ) HANGUL SYLLABLE DDYULH
+B71C;B71C;1104 1172 11B7;B71C;1104 1172 11B7; # (뜜; 뜜; 뜜; 뜜; 뜜; ) HANGUL SYLLABLE DDYUM
+B71D;B71D;1104 1172 11B8;B71D;1104 1172 11B8; # (뜝; 뜝; 뜝; 뜝; 뜝; ) HANGUL SYLLABLE DDYUB
+B71E;B71E;1104 1172 11B9;B71E;1104 1172 11B9; # (뜞; 뜞; 뜞; 뜞; 뜞; ) HANGUL SYLLABLE DDYUBS
+B71F;B71F;1104 1172 11BA;B71F;1104 1172 11BA; # (뜟; 뜟; 뜟; 뜟; 뜟; ) HANGUL SYLLABLE DDYUS
+B720;B720;1104 1172 11BB;B720;1104 1172 11BB; # (뜠; 뜠; 뜠; 뜠; 뜠; ) HANGUL SYLLABLE DDYUSS
+B721;B721;1104 1172 11BC;B721;1104 1172 11BC; # (뜡; 뜡; 뜡; 뜡; 뜡; ) HANGUL SYLLABLE DDYUNG
+B722;B722;1104 1172 11BD;B722;1104 1172 11BD; # (뜢; 뜢; 뜢; 뜢; 뜢; ) HANGUL SYLLABLE DDYUJ
+B723;B723;1104 1172 11BE;B723;1104 1172 11BE; # (뜣; 뜣; 뜣; 뜣; 뜣; ) HANGUL SYLLABLE DDYUC
+B724;B724;1104 1172 11BF;B724;1104 1172 11BF; # (뜤; 뜤; 뜤; 뜤; 뜤; ) HANGUL SYLLABLE DDYUK
+B725;B725;1104 1172 11C0;B725;1104 1172 11C0; # (뜥; 뜥; 뜥; 뜥; 뜥; ) HANGUL SYLLABLE DDYUT
+B726;B726;1104 1172 11C1;B726;1104 1172 11C1; # (뜦; 뜦; 뜦; 뜦; 뜦; ) HANGUL SYLLABLE DDYUP
+B727;B727;1104 1172 11C2;B727;1104 1172 11C2; # (뜧; 뜧; 뜧; 뜧; 뜧; ) HANGUL SYLLABLE DDYUH
+B728;B728;1104 1173;B728;1104 1173; # (뜨; 뜨; 뜨; 뜨; 뜨; ) HANGUL SYLLABLE DDEU
+B729;B729;1104 1173 11A8;B729;1104 1173 11A8; # (뜩; 뜩; 뜩; 뜩; 뜩; ) HANGUL SYLLABLE DDEUG
+B72A;B72A;1104 1173 11A9;B72A;1104 1173 11A9; # (뜪; 뜪; 뜪; 뜪; 뜪; ) HANGUL SYLLABLE DDEUGG
+B72B;B72B;1104 1173 11AA;B72B;1104 1173 11AA; # (뜫; 뜫; 뜫; 뜫; 뜫; ) HANGUL SYLLABLE DDEUGS
+B72C;B72C;1104 1173 11AB;B72C;1104 1173 11AB; # (뜬; 뜬; 뜬; 뜬; 뜬; ) HANGUL SYLLABLE DDEUN
+B72D;B72D;1104 1173 11AC;B72D;1104 1173 11AC; # (뜭; 뜭; 뜭; 뜭; 뜭; ) HANGUL SYLLABLE DDEUNJ
+B72E;B72E;1104 1173 11AD;B72E;1104 1173 11AD; # (뜮; 뜮; 뜮; 뜮; 뜮; ) HANGUL SYLLABLE DDEUNH
+B72F;B72F;1104 1173 11AE;B72F;1104 1173 11AE; # (뜯; 뜯; 뜯; 뜯; 뜯; ) HANGUL SYLLABLE DDEUD
+B730;B730;1104 1173 11AF;B730;1104 1173 11AF; # (뜰; 뜰; 뜰; 뜰; 뜰; ) HANGUL SYLLABLE DDEUL
+B731;B731;1104 1173 11B0;B731;1104 1173 11B0; # (뜱; 뜱; 뜱; 뜱; 뜱; ) HANGUL SYLLABLE DDEULG
+B732;B732;1104 1173 11B1;B732;1104 1173 11B1; # (뜲; 뜲; 뜲; 뜲; 뜲; ) HANGUL SYLLABLE DDEULM
+B733;B733;1104 1173 11B2;B733;1104 1173 11B2; # (뜳; 뜳; 뜳; 뜳; 뜳; ) HANGUL SYLLABLE DDEULB
+B734;B734;1104 1173 11B3;B734;1104 1173 11B3; # (뜴; 뜴; 뜴; 뜴; 뜴; ) HANGUL SYLLABLE DDEULS
+B735;B735;1104 1173 11B4;B735;1104 1173 11B4; # (뜵; 뜵; 뜵; 뜵; 뜵; ) HANGUL SYLLABLE DDEULT
+B736;B736;1104 1173 11B5;B736;1104 1173 11B5; # (뜶; 뜶; 뜶; 뜶; 뜶; ) HANGUL SYLLABLE DDEULP
+B737;B737;1104 1173 11B6;B737;1104 1173 11B6; # (뜷; 뜷; 뜷; 뜷; 뜷; ) HANGUL SYLLABLE DDEULH
+B738;B738;1104 1173 11B7;B738;1104 1173 11B7; # (뜸; 뜸; 뜸; 뜸; 뜸; ) HANGUL SYLLABLE DDEUM
+B739;B739;1104 1173 11B8;B739;1104 1173 11B8; # (뜹; 뜹; 뜹; 뜹; 뜹; ) HANGUL SYLLABLE DDEUB
+B73A;B73A;1104 1173 11B9;B73A;1104 1173 11B9; # (뜺; 뜺; 뜺; 뜺; 뜺; ) HANGUL SYLLABLE DDEUBS
+B73B;B73B;1104 1173 11BA;B73B;1104 1173 11BA; # (뜻; 뜻; 뜻; 뜻; 뜻; ) HANGUL SYLLABLE DDEUS
+B73C;B73C;1104 1173 11BB;B73C;1104 1173 11BB; # (뜼; 뜼; 뜼; 뜼; 뜼; ) HANGUL SYLLABLE DDEUSS
+B73D;B73D;1104 1173 11BC;B73D;1104 1173 11BC; # (뜽; 뜽; 뜽; 뜽; 뜽; ) HANGUL SYLLABLE DDEUNG
+B73E;B73E;1104 1173 11BD;B73E;1104 1173 11BD; # (뜾; 뜾; 뜾; 뜾; 뜾; ) HANGUL SYLLABLE DDEUJ
+B73F;B73F;1104 1173 11BE;B73F;1104 1173 11BE; # (뜿; 뜿; 뜿; 뜿; 뜿; ) HANGUL SYLLABLE DDEUC
+B740;B740;1104 1173 11BF;B740;1104 1173 11BF; # (띀; 띀; 띀; 띀; 띀; ) HANGUL SYLLABLE DDEUK
+B741;B741;1104 1173 11C0;B741;1104 1173 11C0; # (띁; 띁; 띁; 띁; 띁; ) HANGUL SYLLABLE DDEUT
+B742;B742;1104 1173 11C1;B742;1104 1173 11C1; # (띂; 띂; 띂; 띂; 띂; ) HANGUL SYLLABLE DDEUP
+B743;B743;1104 1173 11C2;B743;1104 1173 11C2; # (띃; 띃; 띃; 띃; 띃; ) HANGUL SYLLABLE DDEUH
+B744;B744;1104 1174;B744;1104 1174; # (띄; 띄; 띄; 띄; 띄; ) HANGUL SYLLABLE DDYI
+B745;B745;1104 1174 11A8;B745;1104 1174 11A8; # (띅; 띅; 띅; 띅; 띅; ) HANGUL SYLLABLE DDYIG
+B746;B746;1104 1174 11A9;B746;1104 1174 11A9; # (띆; 띆; 띆; 띆; 띆; ) HANGUL SYLLABLE DDYIGG
+B747;B747;1104 1174 11AA;B747;1104 1174 11AA; # (띇; 띇; 띇; 띇; 띇; ) HANGUL SYLLABLE DDYIGS
+B748;B748;1104 1174 11AB;B748;1104 1174 11AB; # (띈; 띈; 띈; 띈; 띈; ) HANGUL SYLLABLE DDYIN
+B749;B749;1104 1174 11AC;B749;1104 1174 11AC; # (띉; 띉; 띉; 띉; 띉; ) HANGUL SYLLABLE DDYINJ
+B74A;B74A;1104 1174 11AD;B74A;1104 1174 11AD; # (띊; 띊; 띊; 띊; 띊; ) HANGUL SYLLABLE DDYINH
+B74B;B74B;1104 1174 11AE;B74B;1104 1174 11AE; # (띋; 띋; 띋; 띋; 띋; ) HANGUL SYLLABLE DDYID
+B74C;B74C;1104 1174 11AF;B74C;1104 1174 11AF; # (띌; 띌; 띌; 띌; 띌; ) HANGUL SYLLABLE DDYIL
+B74D;B74D;1104 1174 11B0;B74D;1104 1174 11B0; # (띍; 띍; 띍; 띍; 띍; ) HANGUL SYLLABLE DDYILG
+B74E;B74E;1104 1174 11B1;B74E;1104 1174 11B1; # (띎; 띎; 띎; 띎; 띎; ) HANGUL SYLLABLE DDYILM
+B74F;B74F;1104 1174 11B2;B74F;1104 1174 11B2; # (띏; 띏; 띏; 띏; 띏; ) HANGUL SYLLABLE DDYILB
+B750;B750;1104 1174 11B3;B750;1104 1174 11B3; # (띐; 띐; 띐; 띐; 띐; ) HANGUL SYLLABLE DDYILS
+B751;B751;1104 1174 11B4;B751;1104 1174 11B4; # (띑; 띑; 띑; 띑; 띑; ) HANGUL SYLLABLE DDYILT
+B752;B752;1104 1174 11B5;B752;1104 1174 11B5; # (띒; 띒; 띒; 띒; 띒; ) HANGUL SYLLABLE DDYILP
+B753;B753;1104 1174 11B6;B753;1104 1174 11B6; # (띓; 띓; 띓; 띓; 띓; ) HANGUL SYLLABLE DDYILH
+B754;B754;1104 1174 11B7;B754;1104 1174 11B7; # (띔; 띔; 띔; 띔; 띔; ) HANGUL SYLLABLE DDYIM
+B755;B755;1104 1174 11B8;B755;1104 1174 11B8; # (띕; 띕; 띕; 띕; 띕; ) HANGUL SYLLABLE DDYIB
+B756;B756;1104 1174 11B9;B756;1104 1174 11B9; # (띖; 띖; 띖; 띖; 띖; ) HANGUL SYLLABLE DDYIBS
+B757;B757;1104 1174 11BA;B757;1104 1174 11BA; # (띗; 띗; 띗; 띗; 띗; ) HANGUL SYLLABLE DDYIS
+B758;B758;1104 1174 11BB;B758;1104 1174 11BB; # (띘; 띘; 띘; 띘; 띘; ) HANGUL SYLLABLE DDYISS
+B759;B759;1104 1174 11BC;B759;1104 1174 11BC; # (띙; 띙; 띙; 띙; 띙; ) HANGUL SYLLABLE DDYING
+B75A;B75A;1104 1174 11BD;B75A;1104 1174 11BD; # (띚; 띚; 띚; 띚; 띚; ) HANGUL SYLLABLE DDYIJ
+B75B;B75B;1104 1174 11BE;B75B;1104 1174 11BE; # (띛; 띛; 띛; 띛; 띛; ) HANGUL SYLLABLE DDYIC
+B75C;B75C;1104 1174 11BF;B75C;1104 1174 11BF; # (띜; 띜; 띜; 띜; 띜; ) HANGUL SYLLABLE DDYIK
+B75D;B75D;1104 1174 11C0;B75D;1104 1174 11C0; # (띝; 띝; 띝; 띝; 띝; ) HANGUL SYLLABLE DDYIT
+B75E;B75E;1104 1174 11C1;B75E;1104 1174 11C1; # (띞; 띞; 띞; 띞; 띞; ) HANGUL SYLLABLE DDYIP
+B75F;B75F;1104 1174 11C2;B75F;1104 1174 11C2; # (띟; 띟; 띟; 띟; 띟; ) HANGUL SYLLABLE DDYIH
+B760;B760;1104 1175;B760;1104 1175; # (띠; 띠; 띠; 띠; 띠; ) HANGUL SYLLABLE DDI
+B761;B761;1104 1175 11A8;B761;1104 1175 11A8; # (띡; 띡; 띡; 띡; 띡; ) HANGUL SYLLABLE DDIG
+B762;B762;1104 1175 11A9;B762;1104 1175 11A9; # (띢; 띢; 띢; 띢; 띢; ) HANGUL SYLLABLE DDIGG
+B763;B763;1104 1175 11AA;B763;1104 1175 11AA; # (띣; 띣; 띣; 띣; 띣; ) HANGUL SYLLABLE DDIGS
+B764;B764;1104 1175 11AB;B764;1104 1175 11AB; # (띤; 띤; 띤; 띤; 띤; ) HANGUL SYLLABLE DDIN
+B765;B765;1104 1175 11AC;B765;1104 1175 11AC; # (띥; 띥; 띥; 띥; 띥; ) HANGUL SYLLABLE DDINJ
+B766;B766;1104 1175 11AD;B766;1104 1175 11AD; # (띦; 띦; 띦; 띦; 띦; ) HANGUL SYLLABLE DDINH
+B767;B767;1104 1175 11AE;B767;1104 1175 11AE; # (띧; 띧; 띧; 띧; 띧; ) HANGUL SYLLABLE DDID
+B768;B768;1104 1175 11AF;B768;1104 1175 11AF; # (띨; 띨; 띨; 띨; 띨; ) HANGUL SYLLABLE DDIL
+B769;B769;1104 1175 11B0;B769;1104 1175 11B0; # (띩; 띩; 띩; 띩; 띩; ) HANGUL SYLLABLE DDILG
+B76A;B76A;1104 1175 11B1;B76A;1104 1175 11B1; # (띪; 띪; 띪; 띪; 띪; ) HANGUL SYLLABLE DDILM
+B76B;B76B;1104 1175 11B2;B76B;1104 1175 11B2; # (띫; 띫; 띫; 띫; 띫; ) HANGUL SYLLABLE DDILB
+B76C;B76C;1104 1175 11B3;B76C;1104 1175 11B3; # (띬; 띬; 띬; 띬; 띬; ) HANGUL SYLLABLE DDILS
+B76D;B76D;1104 1175 11B4;B76D;1104 1175 11B4; # (띭; 띭; 띭; 띭; 띭; ) HANGUL SYLLABLE DDILT
+B76E;B76E;1104 1175 11B5;B76E;1104 1175 11B5; # (띮; 띮; 띮; 띮; 띮; ) HANGUL SYLLABLE DDILP
+B76F;B76F;1104 1175 11B6;B76F;1104 1175 11B6; # (띯; 띯; 띯; 띯; 띯; ) HANGUL SYLLABLE DDILH
+B770;B770;1104 1175 11B7;B770;1104 1175 11B7; # (띰; 띰; 띰; 띰; 띰; ) HANGUL SYLLABLE DDIM
+B771;B771;1104 1175 11B8;B771;1104 1175 11B8; # (띱; 띱; 띱; 띱; 띱; ) HANGUL SYLLABLE DDIB
+B772;B772;1104 1175 11B9;B772;1104 1175 11B9; # (띲; 띲; 띲; 띲; 띲; ) HANGUL SYLLABLE DDIBS
+B773;B773;1104 1175 11BA;B773;1104 1175 11BA; # (띳; 띳; 띳; 띳; 띳; ) HANGUL SYLLABLE DDIS
+B774;B774;1104 1175 11BB;B774;1104 1175 11BB; # (띴; 띴; 띴; 띴; 띴; ) HANGUL SYLLABLE DDISS
+B775;B775;1104 1175 11BC;B775;1104 1175 11BC; # (띵; 띵; 띵; 띵; 띵; ) HANGUL SYLLABLE DDING
+B776;B776;1104 1175 11BD;B776;1104 1175 11BD; # (띶; 띶; 띶; 띶; 띶; ) HANGUL SYLLABLE DDIJ
+B777;B777;1104 1175 11BE;B777;1104 1175 11BE; # (띷; 띷; 띷; 띷; 띷; ) HANGUL SYLLABLE DDIC
+B778;B778;1104 1175 11BF;B778;1104 1175 11BF; # (띸; 띸; 띸; 띸; 띸; ) HANGUL SYLLABLE DDIK
+B779;B779;1104 1175 11C0;B779;1104 1175 11C0; # (띹; 띹; 띹; 띹; 띹; ) HANGUL SYLLABLE DDIT
+B77A;B77A;1104 1175 11C1;B77A;1104 1175 11C1; # (띺; 띺; 띺; 띺; 띺; ) HANGUL SYLLABLE DDIP
+B77B;B77B;1104 1175 11C2;B77B;1104 1175 11C2; # (띻; 띻; 띻; 띻; 띻; ) HANGUL SYLLABLE DDIH
+B77C;B77C;1105 1161;B77C;1105 1161; # (라; 라; 라; 라; 라; ) HANGUL SYLLABLE RA
+B77D;B77D;1105 1161 11A8;B77D;1105 1161 11A8; # (락; 락; 락; 락; 락; ) HANGUL SYLLABLE RAG
+B77E;B77E;1105 1161 11A9;B77E;1105 1161 11A9; # (띾; 띾; 띾; 띾; 띾; ) HANGUL SYLLABLE RAGG
+B77F;B77F;1105 1161 11AA;B77F;1105 1161 11AA; # (띿; 띿; 띿; 띿; 띿; ) HANGUL SYLLABLE RAGS
+B780;B780;1105 1161 11AB;B780;1105 1161 11AB; # (란; 란; 란; 란; 란; ) HANGUL SYLLABLE RAN
+B781;B781;1105 1161 11AC;B781;1105 1161 11AC; # (랁; 랁; 랁; 랁; 랁; ) HANGUL SYLLABLE RANJ
+B782;B782;1105 1161 11AD;B782;1105 1161 11AD; # (랂; 랂; 랂; 랂; 랂; ) HANGUL SYLLABLE RANH
+B783;B783;1105 1161 11AE;B783;1105 1161 11AE; # (랃; 랃; 랃; 랃; 랃; ) HANGUL SYLLABLE RAD
+B784;B784;1105 1161 11AF;B784;1105 1161 11AF; # (랄; 랄; 랄; 랄; 랄; ) HANGUL SYLLABLE RAL
+B785;B785;1105 1161 11B0;B785;1105 1161 11B0; # (랅; 랅; 랅; 랅; 랅; ) HANGUL SYLLABLE RALG
+B786;B786;1105 1161 11B1;B786;1105 1161 11B1; # (랆; 랆; 랆; 랆; 랆; ) HANGUL SYLLABLE RALM
+B787;B787;1105 1161 11B2;B787;1105 1161 11B2; # (랇; 랇; 랇; 랇; 랇; ) HANGUL SYLLABLE RALB
+B788;B788;1105 1161 11B3;B788;1105 1161 11B3; # (랈; 랈; 랈; 랈; 랈; ) HANGUL SYLLABLE RALS
+B789;B789;1105 1161 11B4;B789;1105 1161 11B4; # (랉; 랉; 랉; 랉; 랉; ) HANGUL SYLLABLE RALT
+B78A;B78A;1105 1161 11B5;B78A;1105 1161 11B5; # (랊; 랊; 랊; 랊; 랊; ) HANGUL SYLLABLE RALP
+B78B;B78B;1105 1161 11B6;B78B;1105 1161 11B6; # (랋; 랋; 랋; 랋; 랋; ) HANGUL SYLLABLE RALH
+B78C;B78C;1105 1161 11B7;B78C;1105 1161 11B7; # (람; 람; 람; 람; 람; ) HANGUL SYLLABLE RAM
+B78D;B78D;1105 1161 11B8;B78D;1105 1161 11B8; # (랍; 랍; 랍; 랍; 랍; ) HANGUL SYLLABLE RAB
+B78E;B78E;1105 1161 11B9;B78E;1105 1161 11B9; # (랎; 랎; 랎; 랎; 랎; ) HANGUL SYLLABLE RABS
+B78F;B78F;1105 1161 11BA;B78F;1105 1161 11BA; # (랏; 랏; 랏; 랏; 랏; ) HANGUL SYLLABLE RAS
+B790;B790;1105 1161 11BB;B790;1105 1161 11BB; # (랐; 랐; 랐; 랐; 랐; ) HANGUL SYLLABLE RASS
+B791;B791;1105 1161 11BC;B791;1105 1161 11BC; # (랑; 랑; 랑; 랑; 랑; ) HANGUL SYLLABLE RANG
+B792;B792;1105 1161 11BD;B792;1105 1161 11BD; # (랒; 랒; 랒; 랒; 랒; ) HANGUL SYLLABLE RAJ
+B793;B793;1105 1161 11BE;B793;1105 1161 11BE; # (랓; 랓; 랓; 랓; 랓; ) HANGUL SYLLABLE RAC
+B794;B794;1105 1161 11BF;B794;1105 1161 11BF; # (랔; 랔; 랔; 랔; 랔; ) HANGUL SYLLABLE RAK
+B795;B795;1105 1161 11C0;B795;1105 1161 11C0; # (랕; 랕; 랕; 랕; 랕; ) HANGUL SYLLABLE RAT
+B796;B796;1105 1161 11C1;B796;1105 1161 11C1; # (랖; 랖; 랖; 랖; 랖; ) HANGUL SYLLABLE RAP
+B797;B797;1105 1161 11C2;B797;1105 1161 11C2; # (랗; 랗; 랗; 랗; 랗; ) HANGUL SYLLABLE RAH
+B798;B798;1105 1162;B798;1105 1162; # (래; 래; 래; 래; 래; ) HANGUL SYLLABLE RAE
+B799;B799;1105 1162 11A8;B799;1105 1162 11A8; # (랙; 랙; 랙; 랙; 랙; ) HANGUL SYLLABLE RAEG
+B79A;B79A;1105 1162 11A9;B79A;1105 1162 11A9; # (랚; 랚; 랚; 랚; 랚; ) HANGUL SYLLABLE RAEGG
+B79B;B79B;1105 1162 11AA;B79B;1105 1162 11AA; # (랛; 랛; 랛; 랛; 랛; ) HANGUL SYLLABLE RAEGS
+B79C;B79C;1105 1162 11AB;B79C;1105 1162 11AB; # (랜; 랜; 랜; 랜; 랜; ) HANGUL SYLLABLE RAEN
+B79D;B79D;1105 1162 11AC;B79D;1105 1162 11AC; # (랝; 랝; 랝; 랝; 랝; ) HANGUL SYLLABLE RAENJ
+B79E;B79E;1105 1162 11AD;B79E;1105 1162 11AD; # (랞; 랞; 랞; 랞; 랞; ) HANGUL SYLLABLE RAENH
+B79F;B79F;1105 1162 11AE;B79F;1105 1162 11AE; # (랟; 랟; 랟; 랟; 랟; ) HANGUL SYLLABLE RAED
+B7A0;B7A0;1105 1162 11AF;B7A0;1105 1162 11AF; # (랠; 랠; 랠; 랠; 랠; ) HANGUL SYLLABLE RAEL
+B7A1;B7A1;1105 1162 11B0;B7A1;1105 1162 11B0; # (랡; 랡; 랡; 랡; 랡; ) HANGUL SYLLABLE RAELG
+B7A2;B7A2;1105 1162 11B1;B7A2;1105 1162 11B1; # (랢; 랢; 랢; 랢; 랢; ) HANGUL SYLLABLE RAELM
+B7A3;B7A3;1105 1162 11B2;B7A3;1105 1162 11B2; # (랣; 랣; 랣; 랣; 랣; ) HANGUL SYLLABLE RAELB
+B7A4;B7A4;1105 1162 11B3;B7A4;1105 1162 11B3; # (랤; 랤; 랤; 랤; 랤; ) HANGUL SYLLABLE RAELS
+B7A5;B7A5;1105 1162 11B4;B7A5;1105 1162 11B4; # (랥; 랥; 랥; 랥; 랥; ) HANGUL SYLLABLE RAELT
+B7A6;B7A6;1105 1162 11B5;B7A6;1105 1162 11B5; # (랦; 랦; 랦; 랦; 랦; ) HANGUL SYLLABLE RAELP
+B7A7;B7A7;1105 1162 11B6;B7A7;1105 1162 11B6; # (랧; 랧; 랧; 랧; 랧; ) HANGUL SYLLABLE RAELH
+B7A8;B7A8;1105 1162 11B7;B7A8;1105 1162 11B7; # (램; 램; 램; 램; 램; ) HANGUL SYLLABLE RAEM
+B7A9;B7A9;1105 1162 11B8;B7A9;1105 1162 11B8; # (랩; 랩; 랩; 랩; 랩; ) HANGUL SYLLABLE RAEB
+B7AA;B7AA;1105 1162 11B9;B7AA;1105 1162 11B9; # (랪; 랪; 랪; 랪; 랪; ) HANGUL SYLLABLE RAEBS
+B7AB;B7AB;1105 1162 11BA;B7AB;1105 1162 11BA; # (랫; 랫; 랫; 랫; 랫; ) HANGUL SYLLABLE RAES
+B7AC;B7AC;1105 1162 11BB;B7AC;1105 1162 11BB; # (랬; 랬; 랬; 랬; 랬; ) HANGUL SYLLABLE RAESS
+B7AD;B7AD;1105 1162 11BC;B7AD;1105 1162 11BC; # (랭; 랭; 랭; 랭; 랭; ) HANGUL SYLLABLE RAENG
+B7AE;B7AE;1105 1162 11BD;B7AE;1105 1162 11BD; # (랮; 랮; 랮; 랮; 랮; ) HANGUL SYLLABLE RAEJ
+B7AF;B7AF;1105 1162 11BE;B7AF;1105 1162 11BE; # (랯; 랯; 랯; 랯; 랯; ) HANGUL SYLLABLE RAEC
+B7B0;B7B0;1105 1162 11BF;B7B0;1105 1162 11BF; # (랰; 랰; 랰; 랰; 랰; ) HANGUL SYLLABLE RAEK
+B7B1;B7B1;1105 1162 11C0;B7B1;1105 1162 11C0; # (랱; 랱; 랱; 랱; 랱; ) HANGUL SYLLABLE RAET
+B7B2;B7B2;1105 1162 11C1;B7B2;1105 1162 11C1; # (랲; 랲; 랲; 랲; 랲; ) HANGUL SYLLABLE RAEP
+B7B3;B7B3;1105 1162 11C2;B7B3;1105 1162 11C2; # (랳; 랳; 랳; 랳; 랳; ) HANGUL SYLLABLE RAEH
+B7B4;B7B4;1105 1163;B7B4;1105 1163; # (랴; 랴; 랴; 랴; 랴; ) HANGUL SYLLABLE RYA
+B7B5;B7B5;1105 1163 11A8;B7B5;1105 1163 11A8; # (략; 략; 략; 략; 략; ) HANGUL SYLLABLE RYAG
+B7B6;B7B6;1105 1163 11A9;B7B6;1105 1163 11A9; # (랶; 랶; 랶; 랶; 랶; ) HANGUL SYLLABLE RYAGG
+B7B7;B7B7;1105 1163 11AA;B7B7;1105 1163 11AA; # (랷; 랷; 랷; 랷; 랷; ) HANGUL SYLLABLE RYAGS
+B7B8;B7B8;1105 1163 11AB;B7B8;1105 1163 11AB; # (랸; 랸; 랸; 랸; 랸; ) HANGUL SYLLABLE RYAN
+B7B9;B7B9;1105 1163 11AC;B7B9;1105 1163 11AC; # (랹; 랹; 랹; 랹; 랹; ) HANGUL SYLLABLE RYANJ
+B7BA;B7BA;1105 1163 11AD;B7BA;1105 1163 11AD; # (랺; 랺; 랺; 랺; 랺; ) HANGUL SYLLABLE RYANH
+B7BB;B7BB;1105 1163 11AE;B7BB;1105 1163 11AE; # (랻; 랻; 랻; 랻; 랻; ) HANGUL SYLLABLE RYAD
+B7BC;B7BC;1105 1163 11AF;B7BC;1105 1163 11AF; # (랼; 랼; 랼; 랼; 랼; ) HANGUL SYLLABLE RYAL
+B7BD;B7BD;1105 1163 11B0;B7BD;1105 1163 11B0; # (랽; 랽; 랽; 랽; 랽; ) HANGUL SYLLABLE RYALG
+B7BE;B7BE;1105 1163 11B1;B7BE;1105 1163 11B1; # (랾; 랾; 랾; 랾; 랾; ) HANGUL SYLLABLE RYALM
+B7BF;B7BF;1105 1163 11B2;B7BF;1105 1163 11B2; # (랿; 랿; 랿; 랿; 랿; ) HANGUL SYLLABLE RYALB
+B7C0;B7C0;1105 1163 11B3;B7C0;1105 1163 11B3; # (럀; 럀; 럀; 럀; 럀; ) HANGUL SYLLABLE RYALS
+B7C1;B7C1;1105 1163 11B4;B7C1;1105 1163 11B4; # (럁; 럁; 럁; 럁; 럁; ) HANGUL SYLLABLE RYALT
+B7C2;B7C2;1105 1163 11B5;B7C2;1105 1163 11B5; # (럂; 럂; 럂; 럂; 럂; ) HANGUL SYLLABLE RYALP
+B7C3;B7C3;1105 1163 11B6;B7C3;1105 1163 11B6; # (럃; 럃; 럃; 럃; 럃; ) HANGUL SYLLABLE RYALH
+B7C4;B7C4;1105 1163 11B7;B7C4;1105 1163 11B7; # (럄; 럄; 럄; 럄; 럄; ) HANGUL SYLLABLE RYAM
+B7C5;B7C5;1105 1163 11B8;B7C5;1105 1163 11B8; # (럅; 럅; 럅; 럅; 럅; ) HANGUL SYLLABLE RYAB
+B7C6;B7C6;1105 1163 11B9;B7C6;1105 1163 11B9; # (럆; 럆; 럆; 럆; 럆; ) HANGUL SYLLABLE RYABS
+B7C7;B7C7;1105 1163 11BA;B7C7;1105 1163 11BA; # (럇; 럇; 럇; 럇; 럇; ) HANGUL SYLLABLE RYAS
+B7C8;B7C8;1105 1163 11BB;B7C8;1105 1163 11BB; # (럈; 럈; 럈; 럈; 럈; ) HANGUL SYLLABLE RYASS
+B7C9;B7C9;1105 1163 11BC;B7C9;1105 1163 11BC; # (량; 량; 량; 량; 량; ) HANGUL SYLLABLE RYANG
+B7CA;B7CA;1105 1163 11BD;B7CA;1105 1163 11BD; # (럊; 럊; 럊; 럊; 럊; ) HANGUL SYLLABLE RYAJ
+B7CB;B7CB;1105 1163 11BE;B7CB;1105 1163 11BE; # (럋; 럋; 럋; 럋; 럋; ) HANGUL SYLLABLE RYAC
+B7CC;B7CC;1105 1163 11BF;B7CC;1105 1163 11BF; # (럌; 럌; 럌; 럌; 럌; ) HANGUL SYLLABLE RYAK
+B7CD;B7CD;1105 1163 11C0;B7CD;1105 1163 11C0; # (럍; 럍; 럍; 럍; 럍; ) HANGUL SYLLABLE RYAT
+B7CE;B7CE;1105 1163 11C1;B7CE;1105 1163 11C1; # (럎; 럎; 럎; 럎; 럎; ) HANGUL SYLLABLE RYAP
+B7CF;B7CF;1105 1163 11C2;B7CF;1105 1163 11C2; # (럏; 럏; 럏; 럏; 럏; ) HANGUL SYLLABLE RYAH
+B7D0;B7D0;1105 1164;B7D0;1105 1164; # (럐; 럐; 럐; 럐; 럐; ) HANGUL SYLLABLE RYAE
+B7D1;B7D1;1105 1164 11A8;B7D1;1105 1164 11A8; # (럑; 럑; 럑; 럑; 럑; ) HANGUL SYLLABLE RYAEG
+B7D2;B7D2;1105 1164 11A9;B7D2;1105 1164 11A9; # (럒; 럒; 럒; 럒; 럒; ) HANGUL SYLLABLE RYAEGG
+B7D3;B7D3;1105 1164 11AA;B7D3;1105 1164 11AA; # (럓; 럓; 럓; 럓; 럓; ) HANGUL SYLLABLE RYAEGS
+B7D4;B7D4;1105 1164 11AB;B7D4;1105 1164 11AB; # (럔; 럔; 럔; 럔; 럔; ) HANGUL SYLLABLE RYAEN
+B7D5;B7D5;1105 1164 11AC;B7D5;1105 1164 11AC; # (럕; 럕; 럕; 럕; 럕; ) HANGUL SYLLABLE RYAENJ
+B7D6;B7D6;1105 1164 11AD;B7D6;1105 1164 11AD; # (럖; 럖; 럖; 럖; 럖; ) HANGUL SYLLABLE RYAENH
+B7D7;B7D7;1105 1164 11AE;B7D7;1105 1164 11AE; # (럗; 럗; 럗; 럗; 럗; ) HANGUL SYLLABLE RYAED
+B7D8;B7D8;1105 1164 11AF;B7D8;1105 1164 11AF; # (럘; 럘; 럘; 럘; 럘; ) HANGUL SYLLABLE RYAEL
+B7D9;B7D9;1105 1164 11B0;B7D9;1105 1164 11B0; # (럙; 럙; 럙; 럙; 럙; ) HANGUL SYLLABLE RYAELG
+B7DA;B7DA;1105 1164 11B1;B7DA;1105 1164 11B1; # (럚; 럚; 럚; 럚; 럚; ) HANGUL SYLLABLE RYAELM
+B7DB;B7DB;1105 1164 11B2;B7DB;1105 1164 11B2; # (럛; 럛; 럛; 럛; 럛; ) HANGUL SYLLABLE RYAELB
+B7DC;B7DC;1105 1164 11B3;B7DC;1105 1164 11B3; # (럜; 럜; 럜; 럜; 럜; ) HANGUL SYLLABLE RYAELS
+B7DD;B7DD;1105 1164 11B4;B7DD;1105 1164 11B4; # (럝; 럝; 럝; 럝; 럝; ) HANGUL SYLLABLE RYAELT
+B7DE;B7DE;1105 1164 11B5;B7DE;1105 1164 11B5; # (럞; 럞; 럞; 럞; 럞; ) HANGUL SYLLABLE RYAELP
+B7DF;B7DF;1105 1164 11B6;B7DF;1105 1164 11B6; # (럟; 럟; 럟; 럟; 럟; ) HANGUL SYLLABLE RYAELH
+B7E0;B7E0;1105 1164 11B7;B7E0;1105 1164 11B7; # (럠; 럠; 럠; 럠; 럠; ) HANGUL SYLLABLE RYAEM
+B7E1;B7E1;1105 1164 11B8;B7E1;1105 1164 11B8; # (럡; 럡; 럡; 럡; 럡; ) HANGUL SYLLABLE RYAEB
+B7E2;B7E2;1105 1164 11B9;B7E2;1105 1164 11B9; # (럢; 럢; 럢; 럢; 럢; ) HANGUL SYLLABLE RYAEBS
+B7E3;B7E3;1105 1164 11BA;B7E3;1105 1164 11BA; # (럣; 럣; 럣; 럣; 럣; ) HANGUL SYLLABLE RYAES
+B7E4;B7E4;1105 1164 11BB;B7E4;1105 1164 11BB; # (럤; 럤; 럤; 럤; 럤; ) HANGUL SYLLABLE RYAESS
+B7E5;B7E5;1105 1164 11BC;B7E5;1105 1164 11BC; # (럥; 럥; 럥; 럥; 럥; ) HANGUL SYLLABLE RYAENG
+B7E6;B7E6;1105 1164 11BD;B7E6;1105 1164 11BD; # (럦; 럦; 럦; 럦; 럦; ) HANGUL SYLLABLE RYAEJ
+B7E7;B7E7;1105 1164 11BE;B7E7;1105 1164 11BE; # (럧; 럧; 럧; 럧; 럧; ) HANGUL SYLLABLE RYAEC
+B7E8;B7E8;1105 1164 11BF;B7E8;1105 1164 11BF; # (럨; 럨; 럨; 럨; 럨; ) HANGUL SYLLABLE RYAEK
+B7E9;B7E9;1105 1164 11C0;B7E9;1105 1164 11C0; # (럩; 럩; 럩; 럩; 럩; ) HANGUL SYLLABLE RYAET
+B7EA;B7EA;1105 1164 11C1;B7EA;1105 1164 11C1; # (럪; 럪; 럪; 럪; 럪; ) HANGUL SYLLABLE RYAEP
+B7EB;B7EB;1105 1164 11C2;B7EB;1105 1164 11C2; # (럫; 럫; 럫; 럫; 럫; ) HANGUL SYLLABLE RYAEH
+B7EC;B7EC;1105 1165;B7EC;1105 1165; # (러; 러; 러; 러; 러; ) HANGUL SYLLABLE REO
+B7ED;B7ED;1105 1165 11A8;B7ED;1105 1165 11A8; # (럭; 럭; 럭; 럭; 럭; ) HANGUL SYLLABLE REOG
+B7EE;B7EE;1105 1165 11A9;B7EE;1105 1165 11A9; # (럮; 럮; 럮; 럮; 럮; ) HANGUL SYLLABLE REOGG
+B7EF;B7EF;1105 1165 11AA;B7EF;1105 1165 11AA; # (럯; 럯; 럯; 럯; 럯; ) HANGUL SYLLABLE REOGS
+B7F0;B7F0;1105 1165 11AB;B7F0;1105 1165 11AB; # (런; 런; 런; 런; 런; ) HANGUL SYLLABLE REON
+B7F1;B7F1;1105 1165 11AC;B7F1;1105 1165 11AC; # (럱; 럱; 럱; 럱; 럱; ) HANGUL SYLLABLE REONJ
+B7F2;B7F2;1105 1165 11AD;B7F2;1105 1165 11AD; # (럲; 럲; 럲; 럲; 럲; ) HANGUL SYLLABLE REONH
+B7F3;B7F3;1105 1165 11AE;B7F3;1105 1165 11AE; # (럳; 럳; 럳; 럳; 럳; ) HANGUL SYLLABLE REOD
+B7F4;B7F4;1105 1165 11AF;B7F4;1105 1165 11AF; # (럴; 럴; 럴; 럴; 럴; ) HANGUL SYLLABLE REOL
+B7F5;B7F5;1105 1165 11B0;B7F5;1105 1165 11B0; # (럵; 럵; 럵; 럵; 럵; ) HANGUL SYLLABLE REOLG
+B7F6;B7F6;1105 1165 11B1;B7F6;1105 1165 11B1; # (럶; 럶; 럶; 럶; 럶; ) HANGUL SYLLABLE REOLM
+B7F7;B7F7;1105 1165 11B2;B7F7;1105 1165 11B2; # (럷; 럷; 럷; 럷; 럷; ) HANGUL SYLLABLE REOLB
+B7F8;B7F8;1105 1165 11B3;B7F8;1105 1165 11B3; # (럸; 럸; 럸; 럸; 럸; ) HANGUL SYLLABLE REOLS
+B7F9;B7F9;1105 1165 11B4;B7F9;1105 1165 11B4; # (럹; 럹; 럹; 럹; 럹; ) HANGUL SYLLABLE REOLT
+B7FA;B7FA;1105 1165 11B5;B7FA;1105 1165 11B5; # (럺; 럺; 럺; 럺; 럺; ) HANGUL SYLLABLE REOLP
+B7FB;B7FB;1105 1165 11B6;B7FB;1105 1165 11B6; # (럻; 럻; 럻; 럻; 럻; ) HANGUL SYLLABLE REOLH
+B7FC;B7FC;1105 1165 11B7;B7FC;1105 1165 11B7; # (럼; 럼; 럼; 럼; 럼; ) HANGUL SYLLABLE REOM
+B7FD;B7FD;1105 1165 11B8;B7FD;1105 1165 11B8; # (럽; 럽; 럽; 럽; 럽; ) HANGUL SYLLABLE REOB
+B7FE;B7FE;1105 1165 11B9;B7FE;1105 1165 11B9; # (럾; 럾; 럾; 럾; 럾; ) HANGUL SYLLABLE REOBS
+B7FF;B7FF;1105 1165 11BA;B7FF;1105 1165 11BA; # (럿; 럿; 럿; 럿; 럿; ) HANGUL SYLLABLE REOS
+B800;B800;1105 1165 11BB;B800;1105 1165 11BB; # (렀; 렀; 렀; 렀; 렀; ) HANGUL SYLLABLE REOSS
+B801;B801;1105 1165 11BC;B801;1105 1165 11BC; # (렁; 렁; 렁; 렁; 렁; ) HANGUL SYLLABLE REONG
+B802;B802;1105 1165 11BD;B802;1105 1165 11BD; # (렂; 렂; 렂; 렂; 렂; ) HANGUL SYLLABLE REOJ
+B803;B803;1105 1165 11BE;B803;1105 1165 11BE; # (렃; 렃; 렃; 렃; 렃; ) HANGUL SYLLABLE REOC
+B804;B804;1105 1165 11BF;B804;1105 1165 11BF; # (렄; 렄; 렄; 렄; 렄; ) HANGUL SYLLABLE REOK
+B805;B805;1105 1165 11C0;B805;1105 1165 11C0; # (렅; 렅; 렅; 렅; 렅; ) HANGUL SYLLABLE REOT
+B806;B806;1105 1165 11C1;B806;1105 1165 11C1; # (렆; 렆; 렆; 렆; 렆; ) HANGUL SYLLABLE REOP
+B807;B807;1105 1165 11C2;B807;1105 1165 11C2; # (렇; 렇; 렇; 렇; 렇; ) HANGUL SYLLABLE REOH
+B808;B808;1105 1166;B808;1105 1166; # (레; 레; 레; 레; 레; ) HANGUL SYLLABLE RE
+B809;B809;1105 1166 11A8;B809;1105 1166 11A8; # (렉; 렉; 렉; 렉; 렉; ) HANGUL SYLLABLE REG
+B80A;B80A;1105 1166 11A9;B80A;1105 1166 11A9; # (렊; 렊; 렊; 렊; 렊; ) HANGUL SYLLABLE REGG
+B80B;B80B;1105 1166 11AA;B80B;1105 1166 11AA; # (렋; 렋; 렋; 렋; 렋; ) HANGUL SYLLABLE REGS
+B80C;B80C;1105 1166 11AB;B80C;1105 1166 11AB; # (렌; 렌; 렌; 렌; 렌; ) HANGUL SYLLABLE REN
+B80D;B80D;1105 1166 11AC;B80D;1105 1166 11AC; # (렍; 렍; 렍; 렍; 렍; ) HANGUL SYLLABLE RENJ
+B80E;B80E;1105 1166 11AD;B80E;1105 1166 11AD; # (렎; 렎; 렎; 렎; 렎; ) HANGUL SYLLABLE RENH
+B80F;B80F;1105 1166 11AE;B80F;1105 1166 11AE; # (렏; 렏; 렏; 렏; 렏; ) HANGUL SYLLABLE RED
+B810;B810;1105 1166 11AF;B810;1105 1166 11AF; # (렐; 렐; 렐; 렐; 렐; ) HANGUL SYLLABLE REL
+B811;B811;1105 1166 11B0;B811;1105 1166 11B0; # (렑; 렑; 렑; 렑; 렑; ) HANGUL SYLLABLE RELG
+B812;B812;1105 1166 11B1;B812;1105 1166 11B1; # (렒; 렒; 렒; 렒; 렒; ) HANGUL SYLLABLE RELM
+B813;B813;1105 1166 11B2;B813;1105 1166 11B2; # (렓; 렓; 렓; 렓; 렓; ) HANGUL SYLLABLE RELB
+B814;B814;1105 1166 11B3;B814;1105 1166 11B3; # (렔; 렔; 렔; 렔; 렔; ) HANGUL SYLLABLE RELS
+B815;B815;1105 1166 11B4;B815;1105 1166 11B4; # (렕; 렕; 렕; 렕; 렕; ) HANGUL SYLLABLE RELT
+B816;B816;1105 1166 11B5;B816;1105 1166 11B5; # (렖; 렖; 렖; 렖; 렖; ) HANGUL SYLLABLE RELP
+B817;B817;1105 1166 11B6;B817;1105 1166 11B6; # (렗; 렗; 렗; 렗; 렗; ) HANGUL SYLLABLE RELH
+B818;B818;1105 1166 11B7;B818;1105 1166 11B7; # (렘; 렘; 렘; 렘; 렘; ) HANGUL SYLLABLE REM
+B819;B819;1105 1166 11B8;B819;1105 1166 11B8; # (렙; 렙; 렙; 렙; 렙; ) HANGUL SYLLABLE REB
+B81A;B81A;1105 1166 11B9;B81A;1105 1166 11B9; # (렚; 렚; 렚; 렚; 렚; ) HANGUL SYLLABLE REBS
+B81B;B81B;1105 1166 11BA;B81B;1105 1166 11BA; # (렛; 렛; 렛; 렛; 렛; ) HANGUL SYLLABLE RES
+B81C;B81C;1105 1166 11BB;B81C;1105 1166 11BB; # (렜; 렜; 렜; 렜; 렜; ) HANGUL SYLLABLE RESS
+B81D;B81D;1105 1166 11BC;B81D;1105 1166 11BC; # (렝; 렝; 렝; 렝; 렝; ) HANGUL SYLLABLE RENG
+B81E;B81E;1105 1166 11BD;B81E;1105 1166 11BD; # (렞; 렞; 렞; 렞; 렞; ) HANGUL SYLLABLE REJ
+B81F;B81F;1105 1166 11BE;B81F;1105 1166 11BE; # (렟; 렟; 렟; 렟; 렟; ) HANGUL SYLLABLE REC
+B820;B820;1105 1166 11BF;B820;1105 1166 11BF; # (렠; 렠; 렠; 렠; 렠; ) HANGUL SYLLABLE REK
+B821;B821;1105 1166 11C0;B821;1105 1166 11C0; # (렡; 렡; 렡; 렡; 렡; ) HANGUL SYLLABLE RET
+B822;B822;1105 1166 11C1;B822;1105 1166 11C1; # (렢; 렢; 렢; 렢; 렢; ) HANGUL SYLLABLE REP
+B823;B823;1105 1166 11C2;B823;1105 1166 11C2; # (렣; 렣; 렣; 렣; 렣; ) HANGUL SYLLABLE REH
+B824;B824;1105 1167;B824;1105 1167; # (려; 려; 려; 려; 려; ) HANGUL SYLLABLE RYEO
+B825;B825;1105 1167 11A8;B825;1105 1167 11A8; # (력; 력; 력; 력; 력; ) HANGUL SYLLABLE RYEOG
+B826;B826;1105 1167 11A9;B826;1105 1167 11A9; # (렦; 렦; 렦; 렦; 렦; ) HANGUL SYLLABLE RYEOGG
+B827;B827;1105 1167 11AA;B827;1105 1167 11AA; # (렧; 렧; 렧; 렧; 렧; ) HANGUL SYLLABLE RYEOGS
+B828;B828;1105 1167 11AB;B828;1105 1167 11AB; # (련; 련; 련; 련; 련; ) HANGUL SYLLABLE RYEON
+B829;B829;1105 1167 11AC;B829;1105 1167 11AC; # (렩; 렩; 렩; 렩; 렩; ) HANGUL SYLLABLE RYEONJ
+B82A;B82A;1105 1167 11AD;B82A;1105 1167 11AD; # (렪; 렪; 렪; 렪; 렪; ) HANGUL SYLLABLE RYEONH
+B82B;B82B;1105 1167 11AE;B82B;1105 1167 11AE; # (렫; 렫; 렫; 렫; 렫; ) HANGUL SYLLABLE RYEOD
+B82C;B82C;1105 1167 11AF;B82C;1105 1167 11AF; # (렬; 렬; 렬; 렬; 렬; ) HANGUL SYLLABLE RYEOL
+B82D;B82D;1105 1167 11B0;B82D;1105 1167 11B0; # (렭; 렭; 렭; 렭; 렭; ) HANGUL SYLLABLE RYEOLG
+B82E;B82E;1105 1167 11B1;B82E;1105 1167 11B1; # (렮; 렮; 렮; 렮; 렮; ) HANGUL SYLLABLE RYEOLM
+B82F;B82F;1105 1167 11B2;B82F;1105 1167 11B2; # (렯; 렯; 렯; 렯; 렯; ) HANGUL SYLLABLE RYEOLB
+B830;B830;1105 1167 11B3;B830;1105 1167 11B3; # (렰; 렰; 렰; 렰; 렰; ) HANGUL SYLLABLE RYEOLS
+B831;B831;1105 1167 11B4;B831;1105 1167 11B4; # (렱; 렱; 렱; 렱; 렱; ) HANGUL SYLLABLE RYEOLT
+B832;B832;1105 1167 11B5;B832;1105 1167 11B5; # (렲; 렲; 렲; 렲; 렲; ) HANGUL SYLLABLE RYEOLP
+B833;B833;1105 1167 11B6;B833;1105 1167 11B6; # (렳; 렳; 렳; 렳; 렳; ) HANGUL SYLLABLE RYEOLH
+B834;B834;1105 1167 11B7;B834;1105 1167 11B7; # (렴; 렴; 렴; 렴; 렴; ) HANGUL SYLLABLE RYEOM
+B835;B835;1105 1167 11B8;B835;1105 1167 11B8; # (렵; 렵; 렵; 렵; 렵; ) HANGUL SYLLABLE RYEOB
+B836;B836;1105 1167 11B9;B836;1105 1167 11B9; # (렶; 렶; 렶; 렶; 렶; ) HANGUL SYLLABLE RYEOBS
+B837;B837;1105 1167 11BA;B837;1105 1167 11BA; # (렷; 렷; 렷; 렷; 렷; ) HANGUL SYLLABLE RYEOS
+B838;B838;1105 1167 11BB;B838;1105 1167 11BB; # (렸; 렸; 렸; 렸; 렸; ) HANGUL SYLLABLE RYEOSS
+B839;B839;1105 1167 11BC;B839;1105 1167 11BC; # (령; 령; 령; 령; 령; ) HANGUL SYLLABLE RYEONG
+B83A;B83A;1105 1167 11BD;B83A;1105 1167 11BD; # (렺; 렺; 렺; 렺; 렺; ) HANGUL SYLLABLE RYEOJ
+B83B;B83B;1105 1167 11BE;B83B;1105 1167 11BE; # (렻; 렻; 렻; 렻; 렻; ) HANGUL SYLLABLE RYEOC
+B83C;B83C;1105 1167 11BF;B83C;1105 1167 11BF; # (렼; 렼; 렼; 렼; 렼; ) HANGUL SYLLABLE RYEOK
+B83D;B83D;1105 1167 11C0;B83D;1105 1167 11C0; # (렽; 렽; 렽; 렽; 렽; ) HANGUL SYLLABLE RYEOT
+B83E;B83E;1105 1167 11C1;B83E;1105 1167 11C1; # (렾; 렾; 렾; 렾; 렾; ) HANGUL SYLLABLE RYEOP
+B83F;B83F;1105 1167 11C2;B83F;1105 1167 11C2; # (렿; 렿; 렿; 렿; 렿; ) HANGUL SYLLABLE RYEOH
+B840;B840;1105 1168;B840;1105 1168; # (례; 례; 례; 례; 례; ) HANGUL SYLLABLE RYE
+B841;B841;1105 1168 11A8;B841;1105 1168 11A8; # (롁; 롁; 롁; 롁; 롁; ) HANGUL SYLLABLE RYEG
+B842;B842;1105 1168 11A9;B842;1105 1168 11A9; # (롂; 롂; 롂; 롂; 롂; ) HANGUL SYLLABLE RYEGG
+B843;B843;1105 1168 11AA;B843;1105 1168 11AA; # (롃; 롃; 롃; 롃; 롃; ) HANGUL SYLLABLE RYEGS
+B844;B844;1105 1168 11AB;B844;1105 1168 11AB; # (롄; 롄; 롄; 롄; 롄; ) HANGUL SYLLABLE RYEN
+B845;B845;1105 1168 11AC;B845;1105 1168 11AC; # (롅; 롅; 롅; 롅; 롅; ) HANGUL SYLLABLE RYENJ
+B846;B846;1105 1168 11AD;B846;1105 1168 11AD; # (롆; 롆; 롆; 롆; 롆; ) HANGUL SYLLABLE RYENH
+B847;B847;1105 1168 11AE;B847;1105 1168 11AE; # (롇; 롇; 롇; 롇; 롇; ) HANGUL SYLLABLE RYED
+B848;B848;1105 1168 11AF;B848;1105 1168 11AF; # (롈; 롈; 롈; 롈; 롈; ) HANGUL SYLLABLE RYEL
+B849;B849;1105 1168 11B0;B849;1105 1168 11B0; # (롉; 롉; 롉; 롉; 롉; ) HANGUL SYLLABLE RYELG
+B84A;B84A;1105 1168 11B1;B84A;1105 1168 11B1; # (롊; 롊; 롊; 롊; 롊; ) HANGUL SYLLABLE RYELM
+B84B;B84B;1105 1168 11B2;B84B;1105 1168 11B2; # (롋; 롋; 롋; 롋; 롋; ) HANGUL SYLLABLE RYELB
+B84C;B84C;1105 1168 11B3;B84C;1105 1168 11B3; # (롌; 롌; 롌; 롌; 롌; ) HANGUL SYLLABLE RYELS
+B84D;B84D;1105 1168 11B4;B84D;1105 1168 11B4; # (롍; 롍; 롍; 롍; 롍; ) HANGUL SYLLABLE RYELT
+B84E;B84E;1105 1168 11B5;B84E;1105 1168 11B5; # (롎; 롎; 롎; 롎; 롎; ) HANGUL SYLLABLE RYELP
+B84F;B84F;1105 1168 11B6;B84F;1105 1168 11B6; # (롏; 롏; 롏; 롏; 롏; ) HANGUL SYLLABLE RYELH
+B850;B850;1105 1168 11B7;B850;1105 1168 11B7; # (롐; 롐; 롐; 롐; 롐; ) HANGUL SYLLABLE RYEM
+B851;B851;1105 1168 11B8;B851;1105 1168 11B8; # (롑; 롑; 롑; 롑; 롑; ) HANGUL SYLLABLE RYEB
+B852;B852;1105 1168 11B9;B852;1105 1168 11B9; # (롒; 롒; 롒; 롒; 롒; ) HANGUL SYLLABLE RYEBS
+B853;B853;1105 1168 11BA;B853;1105 1168 11BA; # (롓; 롓; 롓; 롓; 롓; ) HANGUL SYLLABLE RYES
+B854;B854;1105 1168 11BB;B854;1105 1168 11BB; # (롔; 롔; 롔; 롔; 롔; ) HANGUL SYLLABLE RYESS
+B855;B855;1105 1168 11BC;B855;1105 1168 11BC; # (롕; 롕; 롕; 롕; 롕; ) HANGUL SYLLABLE RYENG
+B856;B856;1105 1168 11BD;B856;1105 1168 11BD; # (롖; 롖; 롖; 롖; 롖; ) HANGUL SYLLABLE RYEJ
+B857;B857;1105 1168 11BE;B857;1105 1168 11BE; # (롗; 롗; 롗; 롗; 롗; ) HANGUL SYLLABLE RYEC
+B858;B858;1105 1168 11BF;B858;1105 1168 11BF; # (롘; 롘; 롘; 롘; 롘; ) HANGUL SYLLABLE RYEK
+B859;B859;1105 1168 11C0;B859;1105 1168 11C0; # (롙; 롙; 롙; 롙; 롙; ) HANGUL SYLLABLE RYET
+B85A;B85A;1105 1168 11C1;B85A;1105 1168 11C1; # (롚; 롚; 롚; 롚; 롚; ) HANGUL SYLLABLE RYEP
+B85B;B85B;1105 1168 11C2;B85B;1105 1168 11C2; # (롛; 롛; 롛; 롛; 롛; ) HANGUL SYLLABLE RYEH
+B85C;B85C;1105 1169;B85C;1105 1169; # (로; 로; 로; 로; 로; ) HANGUL SYLLABLE RO
+B85D;B85D;1105 1169 11A8;B85D;1105 1169 11A8; # (록; 록; 록; 록; 록; ) HANGUL SYLLABLE ROG
+B85E;B85E;1105 1169 11A9;B85E;1105 1169 11A9; # (롞; 롞; 롞; 롞; 롞; ) HANGUL SYLLABLE ROGG
+B85F;B85F;1105 1169 11AA;B85F;1105 1169 11AA; # (롟; 롟; 롟; 롟; 롟; ) HANGUL SYLLABLE ROGS
+B860;B860;1105 1169 11AB;B860;1105 1169 11AB; # (론; 론; 론; 론; 론; ) HANGUL SYLLABLE RON
+B861;B861;1105 1169 11AC;B861;1105 1169 11AC; # (롡; 롡; 롡; 롡; 롡; ) HANGUL SYLLABLE RONJ
+B862;B862;1105 1169 11AD;B862;1105 1169 11AD; # (롢; 롢; 롢; 롢; 롢; ) HANGUL SYLLABLE RONH
+B863;B863;1105 1169 11AE;B863;1105 1169 11AE; # (롣; 롣; 롣; 롣; 롣; ) HANGUL SYLLABLE ROD
+B864;B864;1105 1169 11AF;B864;1105 1169 11AF; # (롤; 롤; 롤; 롤; 롤; ) HANGUL SYLLABLE ROL
+B865;B865;1105 1169 11B0;B865;1105 1169 11B0; # (롥; 롥; 롥; 롥; 롥; ) HANGUL SYLLABLE ROLG
+B866;B866;1105 1169 11B1;B866;1105 1169 11B1; # (롦; 롦; 롦; 롦; 롦; ) HANGUL SYLLABLE ROLM
+B867;B867;1105 1169 11B2;B867;1105 1169 11B2; # (롧; 롧; 롧; 롧; 롧; ) HANGUL SYLLABLE ROLB
+B868;B868;1105 1169 11B3;B868;1105 1169 11B3; # (롨; 롨; 롨; 롨; 롨; ) HANGUL SYLLABLE ROLS
+B869;B869;1105 1169 11B4;B869;1105 1169 11B4; # (롩; 롩; 롩; 롩; 롩; ) HANGUL SYLLABLE ROLT
+B86A;B86A;1105 1169 11B5;B86A;1105 1169 11B5; # (롪; 롪; 롪; 롪; 롪; ) HANGUL SYLLABLE ROLP
+B86B;B86B;1105 1169 11B6;B86B;1105 1169 11B6; # (롫; 롫; 롫; 롫; 롫; ) HANGUL SYLLABLE ROLH
+B86C;B86C;1105 1169 11B7;B86C;1105 1169 11B7; # (롬; 롬; 롬; 롬; 롬; ) HANGUL SYLLABLE ROM
+B86D;B86D;1105 1169 11B8;B86D;1105 1169 11B8; # (롭; 롭; 롭; 롭; 롭; ) HANGUL SYLLABLE ROB
+B86E;B86E;1105 1169 11B9;B86E;1105 1169 11B9; # (롮; 롮; 롮; 롮; 롮; ) HANGUL SYLLABLE ROBS
+B86F;B86F;1105 1169 11BA;B86F;1105 1169 11BA; # (롯; 롯; 롯; 롯; 롯; ) HANGUL SYLLABLE ROS
+B870;B870;1105 1169 11BB;B870;1105 1169 11BB; # (롰; 롰; 롰; 롰; 롰; ) HANGUL SYLLABLE ROSS
+B871;B871;1105 1169 11BC;B871;1105 1169 11BC; # (롱; 롱; 롱; 롱; 롱; ) HANGUL SYLLABLE RONG
+B872;B872;1105 1169 11BD;B872;1105 1169 11BD; # (롲; 롲; 롲; 롲; 롲; ) HANGUL SYLLABLE ROJ
+B873;B873;1105 1169 11BE;B873;1105 1169 11BE; # (롳; 롳; 롳; 롳; 롳; ) HANGUL SYLLABLE ROC
+B874;B874;1105 1169 11BF;B874;1105 1169 11BF; # (롴; 롴; 롴; 롴; 롴; ) HANGUL SYLLABLE ROK
+B875;B875;1105 1169 11C0;B875;1105 1169 11C0; # (롵; 롵; 롵; 롵; 롵; ) HANGUL SYLLABLE ROT
+B876;B876;1105 1169 11C1;B876;1105 1169 11C1; # (롶; 롶; 롶; 롶; 롶; ) HANGUL SYLLABLE ROP
+B877;B877;1105 1169 11C2;B877;1105 1169 11C2; # (롷; 롷; 롷; 롷; 롷; ) HANGUL SYLLABLE ROH
+B878;B878;1105 116A;B878;1105 116A; # (롸; 롸; 롸; 롸; 롸; ) HANGUL SYLLABLE RWA
+B879;B879;1105 116A 11A8;B879;1105 116A 11A8; # (롹; 롹; 롹; 롹; 롹; ) HANGUL SYLLABLE RWAG
+B87A;B87A;1105 116A 11A9;B87A;1105 116A 11A9; # (롺; 롺; 롺; 롺; 롺; ) HANGUL SYLLABLE RWAGG
+B87B;B87B;1105 116A 11AA;B87B;1105 116A 11AA; # (롻; 롻; 롻; 롻; 롻; ) HANGUL SYLLABLE RWAGS
+B87C;B87C;1105 116A 11AB;B87C;1105 116A 11AB; # (롼; 롼; 롼; 롼; 롼; ) HANGUL SYLLABLE RWAN
+B87D;B87D;1105 116A 11AC;B87D;1105 116A 11AC; # (롽; 롽; 롽; 롽; 롽; ) HANGUL SYLLABLE RWANJ
+B87E;B87E;1105 116A 11AD;B87E;1105 116A 11AD; # (롾; 롾; 롾; 롾; 롾; ) HANGUL SYLLABLE RWANH
+B87F;B87F;1105 116A 11AE;B87F;1105 116A 11AE; # (롿; 롿; 롿; 롿; 롿; ) HANGUL SYLLABLE RWAD
+B880;B880;1105 116A 11AF;B880;1105 116A 11AF; # (뢀; 뢀; 뢀; 뢀; 뢀; ) HANGUL SYLLABLE RWAL
+B881;B881;1105 116A 11B0;B881;1105 116A 11B0; # (뢁; 뢁; 뢁; 뢁; 뢁; ) HANGUL SYLLABLE RWALG
+B882;B882;1105 116A 11B1;B882;1105 116A 11B1; # (뢂; 뢂; 뢂; 뢂; 뢂; ) HANGUL SYLLABLE RWALM
+B883;B883;1105 116A 11B2;B883;1105 116A 11B2; # (뢃; 뢃; 뢃; 뢃; 뢃; ) HANGUL SYLLABLE RWALB
+B884;B884;1105 116A 11B3;B884;1105 116A 11B3; # (뢄; 뢄; 뢄; 뢄; 뢄; ) HANGUL SYLLABLE RWALS
+B885;B885;1105 116A 11B4;B885;1105 116A 11B4; # (뢅; 뢅; 뢅; 뢅; 뢅; ) HANGUL SYLLABLE RWALT
+B886;B886;1105 116A 11B5;B886;1105 116A 11B5; # (뢆; 뢆; 뢆; 뢆; 뢆; ) HANGUL SYLLABLE RWALP
+B887;B887;1105 116A 11B6;B887;1105 116A 11B6; # (뢇; 뢇; 뢇; 뢇; 뢇; ) HANGUL SYLLABLE RWALH
+B888;B888;1105 116A 11B7;B888;1105 116A 11B7; # (뢈; 뢈; 뢈; 뢈; 뢈; ) HANGUL SYLLABLE RWAM
+B889;B889;1105 116A 11B8;B889;1105 116A 11B8; # (뢉; 뢉; 뢉; 뢉; 뢉; ) HANGUL SYLLABLE RWAB
+B88A;B88A;1105 116A 11B9;B88A;1105 116A 11B9; # (뢊; 뢊; 뢊; 뢊; 뢊; ) HANGUL SYLLABLE RWABS
+B88B;B88B;1105 116A 11BA;B88B;1105 116A 11BA; # (뢋; 뢋; 뢋; 뢋; 뢋; ) HANGUL SYLLABLE RWAS
+B88C;B88C;1105 116A 11BB;B88C;1105 116A 11BB; # (뢌; 뢌; 뢌; 뢌; 뢌; ) HANGUL SYLLABLE RWASS
+B88D;B88D;1105 116A 11BC;B88D;1105 116A 11BC; # (뢍; 뢍; 뢍; 뢍; 뢍; ) HANGUL SYLLABLE RWANG
+B88E;B88E;1105 116A 11BD;B88E;1105 116A 11BD; # (뢎; 뢎; 뢎; 뢎; 뢎; ) HANGUL SYLLABLE RWAJ
+B88F;B88F;1105 116A 11BE;B88F;1105 116A 11BE; # (뢏; 뢏; 뢏; 뢏; 뢏; ) HANGUL SYLLABLE RWAC
+B890;B890;1105 116A 11BF;B890;1105 116A 11BF; # (뢐; 뢐; 뢐; 뢐; 뢐; ) HANGUL SYLLABLE RWAK
+B891;B891;1105 116A 11C0;B891;1105 116A 11C0; # (뢑; 뢑; 뢑; 뢑; 뢑; ) HANGUL SYLLABLE RWAT
+B892;B892;1105 116A 11C1;B892;1105 116A 11C1; # (뢒; 뢒; 뢒; 뢒; 뢒; ) HANGUL SYLLABLE RWAP
+B893;B893;1105 116A 11C2;B893;1105 116A 11C2; # (뢓; 뢓; 뢓; 뢓; 뢓; ) HANGUL SYLLABLE RWAH
+B894;B894;1105 116B;B894;1105 116B; # (뢔; 뢔; 뢔; 뢔; 뢔; ) HANGUL SYLLABLE RWAE
+B895;B895;1105 116B 11A8;B895;1105 116B 11A8; # (뢕; 뢕; 뢕; 뢕; 뢕; ) HANGUL SYLLABLE RWAEG
+B896;B896;1105 116B 11A9;B896;1105 116B 11A9; # (뢖; 뢖; 뢖; 뢖; 뢖; ) HANGUL SYLLABLE RWAEGG
+B897;B897;1105 116B 11AA;B897;1105 116B 11AA; # (뢗; 뢗; 뢗; 뢗; 뢗; ) HANGUL SYLLABLE RWAEGS
+B898;B898;1105 116B 11AB;B898;1105 116B 11AB; # (뢘; 뢘; 뢘; 뢘; 뢘; ) HANGUL SYLLABLE RWAEN
+B899;B899;1105 116B 11AC;B899;1105 116B 11AC; # (뢙; 뢙; 뢙; 뢙; 뢙; ) HANGUL SYLLABLE RWAENJ
+B89A;B89A;1105 116B 11AD;B89A;1105 116B 11AD; # (뢚; 뢚; 뢚; 뢚; 뢚; ) HANGUL SYLLABLE RWAENH
+B89B;B89B;1105 116B 11AE;B89B;1105 116B 11AE; # (뢛; 뢛; 뢛; 뢛; 뢛; ) HANGUL SYLLABLE RWAED
+B89C;B89C;1105 116B 11AF;B89C;1105 116B 11AF; # (뢜; 뢜; 뢜; 뢜; 뢜; ) HANGUL SYLLABLE RWAEL
+B89D;B89D;1105 116B 11B0;B89D;1105 116B 11B0; # (뢝; 뢝; 뢝; 뢝; 뢝; ) HANGUL SYLLABLE RWAELG
+B89E;B89E;1105 116B 11B1;B89E;1105 116B 11B1; # (뢞; 뢞; 뢞; 뢞; 뢞; ) HANGUL SYLLABLE RWAELM
+B89F;B89F;1105 116B 11B2;B89F;1105 116B 11B2; # (뢟; 뢟; 뢟; 뢟; 뢟; ) HANGUL SYLLABLE RWAELB
+B8A0;B8A0;1105 116B 11B3;B8A0;1105 116B 11B3; # (뢠; 뢠; 뢠; 뢠; 뢠; ) HANGUL SYLLABLE RWAELS
+B8A1;B8A1;1105 116B 11B4;B8A1;1105 116B 11B4; # (뢡; 뢡; 뢡; 뢡; 뢡; ) HANGUL SYLLABLE RWAELT
+B8A2;B8A2;1105 116B 11B5;B8A2;1105 116B 11B5; # (뢢; 뢢; 뢢; 뢢; 뢢; ) HANGUL SYLLABLE RWAELP
+B8A3;B8A3;1105 116B 11B6;B8A3;1105 116B 11B6; # (뢣; 뢣; 뢣; 뢣; 뢣; ) HANGUL SYLLABLE RWAELH
+B8A4;B8A4;1105 116B 11B7;B8A4;1105 116B 11B7; # (뢤; 뢤; 뢤; 뢤; 뢤; ) HANGUL SYLLABLE RWAEM
+B8A5;B8A5;1105 116B 11B8;B8A5;1105 116B 11B8; # (뢥; 뢥; 뢥; 뢥; 뢥; ) HANGUL SYLLABLE RWAEB
+B8A6;B8A6;1105 116B 11B9;B8A6;1105 116B 11B9; # (뢦; 뢦; 뢦; 뢦; 뢦; ) HANGUL SYLLABLE RWAEBS
+B8A7;B8A7;1105 116B 11BA;B8A7;1105 116B 11BA; # (뢧; 뢧; 뢧; 뢧; 뢧; ) HANGUL SYLLABLE RWAES
+B8A8;B8A8;1105 116B 11BB;B8A8;1105 116B 11BB; # (뢨; 뢨; 뢨; 뢨; 뢨; ) HANGUL SYLLABLE RWAESS
+B8A9;B8A9;1105 116B 11BC;B8A9;1105 116B 11BC; # (뢩; 뢩; 뢩; 뢩; 뢩; ) HANGUL SYLLABLE RWAENG
+B8AA;B8AA;1105 116B 11BD;B8AA;1105 116B 11BD; # (뢪; 뢪; 뢪; 뢪; 뢪; ) HANGUL SYLLABLE RWAEJ
+B8AB;B8AB;1105 116B 11BE;B8AB;1105 116B 11BE; # (뢫; 뢫; 뢫; 뢫; 뢫; ) HANGUL SYLLABLE RWAEC
+B8AC;B8AC;1105 116B 11BF;B8AC;1105 116B 11BF; # (뢬; 뢬; 뢬; 뢬; 뢬; ) HANGUL SYLLABLE RWAEK
+B8AD;B8AD;1105 116B 11C0;B8AD;1105 116B 11C0; # (뢭; 뢭; 뢭; 뢭; 뢭; ) HANGUL SYLLABLE RWAET
+B8AE;B8AE;1105 116B 11C1;B8AE;1105 116B 11C1; # (뢮; 뢮; 뢮; 뢮; 뢮; ) HANGUL SYLLABLE RWAEP
+B8AF;B8AF;1105 116B 11C2;B8AF;1105 116B 11C2; # (뢯; 뢯; 뢯; 뢯; 뢯; ) HANGUL SYLLABLE RWAEH
+B8B0;B8B0;1105 116C;B8B0;1105 116C; # (뢰; 뢰; 뢰; 뢰; 뢰; ) HANGUL SYLLABLE ROE
+B8B1;B8B1;1105 116C 11A8;B8B1;1105 116C 11A8; # (뢱; 뢱; 뢱; 뢱; 뢱; ) HANGUL SYLLABLE ROEG
+B8B2;B8B2;1105 116C 11A9;B8B2;1105 116C 11A9; # (뢲; 뢲; 뢲; 뢲; 뢲; ) HANGUL SYLLABLE ROEGG
+B8B3;B8B3;1105 116C 11AA;B8B3;1105 116C 11AA; # (뢳; 뢳; 뢳; 뢳; 뢳; ) HANGUL SYLLABLE ROEGS
+B8B4;B8B4;1105 116C 11AB;B8B4;1105 116C 11AB; # (뢴; 뢴; 뢴; 뢴; 뢴; ) HANGUL SYLLABLE ROEN
+B8B5;B8B5;1105 116C 11AC;B8B5;1105 116C 11AC; # (뢵; 뢵; 뢵; 뢵; 뢵; ) HANGUL SYLLABLE ROENJ
+B8B6;B8B6;1105 116C 11AD;B8B6;1105 116C 11AD; # (뢶; 뢶; 뢶; 뢶; 뢶; ) HANGUL SYLLABLE ROENH
+B8B7;B8B7;1105 116C 11AE;B8B7;1105 116C 11AE; # (뢷; 뢷; 뢷; 뢷; 뢷; ) HANGUL SYLLABLE ROED
+B8B8;B8B8;1105 116C 11AF;B8B8;1105 116C 11AF; # (뢸; 뢸; 뢸; 뢸; 뢸; ) HANGUL SYLLABLE ROEL
+B8B9;B8B9;1105 116C 11B0;B8B9;1105 116C 11B0; # (뢹; 뢹; 뢹; 뢹; 뢹; ) HANGUL SYLLABLE ROELG
+B8BA;B8BA;1105 116C 11B1;B8BA;1105 116C 11B1; # (뢺; 뢺; 뢺; 뢺; 뢺; ) HANGUL SYLLABLE ROELM
+B8BB;B8BB;1105 116C 11B2;B8BB;1105 116C 11B2; # (뢻; 뢻; 뢻; 뢻; 뢻; ) HANGUL SYLLABLE ROELB
+B8BC;B8BC;1105 116C 11B3;B8BC;1105 116C 11B3; # (뢼; 뢼; 뢼; 뢼; 뢼; ) HANGUL SYLLABLE ROELS
+B8BD;B8BD;1105 116C 11B4;B8BD;1105 116C 11B4; # (뢽; 뢽; 뢽; 뢽; 뢽; ) HANGUL SYLLABLE ROELT
+B8BE;B8BE;1105 116C 11B5;B8BE;1105 116C 11B5; # (뢾; 뢾; 뢾; 뢾; 뢾; ) HANGUL SYLLABLE ROELP
+B8BF;B8BF;1105 116C 11B6;B8BF;1105 116C 11B6; # (뢿; 뢿; 뢿; 뢿; 뢿; ) HANGUL SYLLABLE ROELH
+B8C0;B8C0;1105 116C 11B7;B8C0;1105 116C 11B7; # (룀; 룀; 룀; 룀; 룀; ) HANGUL SYLLABLE ROEM
+B8C1;B8C1;1105 116C 11B8;B8C1;1105 116C 11B8; # (룁; 룁; 룁; 룁; 룁; ) HANGUL SYLLABLE ROEB
+B8C2;B8C2;1105 116C 11B9;B8C2;1105 116C 11B9; # (룂; 룂; 룂; 룂; 룂; ) HANGUL SYLLABLE ROEBS
+B8C3;B8C3;1105 116C 11BA;B8C3;1105 116C 11BA; # (룃; 룃; 룃; 룃; 룃; ) HANGUL SYLLABLE ROES
+B8C4;B8C4;1105 116C 11BB;B8C4;1105 116C 11BB; # (룄; 룄; 룄; 룄; 룄; ) HANGUL SYLLABLE ROESS
+B8C5;B8C5;1105 116C 11BC;B8C5;1105 116C 11BC; # (룅; 룅; 룅; 룅; 룅; ) HANGUL SYLLABLE ROENG
+B8C6;B8C6;1105 116C 11BD;B8C6;1105 116C 11BD; # (룆; 룆; 룆; 룆; 룆; ) HANGUL SYLLABLE ROEJ
+B8C7;B8C7;1105 116C 11BE;B8C7;1105 116C 11BE; # (룇; 룇; 룇; 룇; 룇; ) HANGUL SYLLABLE ROEC
+B8C8;B8C8;1105 116C 11BF;B8C8;1105 116C 11BF; # (룈; 룈; 룈; 룈; 룈; ) HANGUL SYLLABLE ROEK
+B8C9;B8C9;1105 116C 11C0;B8C9;1105 116C 11C0; # (룉; 룉; 룉; 룉; 룉; ) HANGUL SYLLABLE ROET
+B8CA;B8CA;1105 116C 11C1;B8CA;1105 116C 11C1; # (룊; 룊; 룊; 룊; 룊; ) HANGUL SYLLABLE ROEP
+B8CB;B8CB;1105 116C 11C2;B8CB;1105 116C 11C2; # (룋; 룋; 룋; 룋; 룋; ) HANGUL SYLLABLE ROEH
+B8CC;B8CC;1105 116D;B8CC;1105 116D; # (료; 료; 료; 료; 료; ) HANGUL SYLLABLE RYO
+B8CD;B8CD;1105 116D 11A8;B8CD;1105 116D 11A8; # (룍; 룍; 룍; 룍; 룍; ) HANGUL SYLLABLE RYOG
+B8CE;B8CE;1105 116D 11A9;B8CE;1105 116D 11A9; # (룎; 룎; 룎; 룎; 룎; ) HANGUL SYLLABLE RYOGG
+B8CF;B8CF;1105 116D 11AA;B8CF;1105 116D 11AA; # (룏; 룏; 룏; 룏; 룏; ) HANGUL SYLLABLE RYOGS
+B8D0;B8D0;1105 116D 11AB;B8D0;1105 116D 11AB; # (룐; 룐; 룐; 룐; 룐; ) HANGUL SYLLABLE RYON
+B8D1;B8D1;1105 116D 11AC;B8D1;1105 116D 11AC; # (룑; 룑; 룑; 룑; 룑; ) HANGUL SYLLABLE RYONJ
+B8D2;B8D2;1105 116D 11AD;B8D2;1105 116D 11AD; # (룒; 룒; 룒; 룒; 룒; ) HANGUL SYLLABLE RYONH
+B8D3;B8D3;1105 116D 11AE;B8D3;1105 116D 11AE; # (룓; 룓; 룓; 룓; 룓; ) HANGUL SYLLABLE RYOD
+B8D4;B8D4;1105 116D 11AF;B8D4;1105 116D 11AF; # (룔; 룔; 룔; 룔; 룔; ) HANGUL SYLLABLE RYOL
+B8D5;B8D5;1105 116D 11B0;B8D5;1105 116D 11B0; # (룕; 룕; 룕; 룕; 룕; ) HANGUL SYLLABLE RYOLG
+B8D6;B8D6;1105 116D 11B1;B8D6;1105 116D 11B1; # (룖; 룖; 룖; 룖; 룖; ) HANGUL SYLLABLE RYOLM
+B8D7;B8D7;1105 116D 11B2;B8D7;1105 116D 11B2; # (룗; 룗; 룗; 룗; 룗; ) HANGUL SYLLABLE RYOLB
+B8D8;B8D8;1105 116D 11B3;B8D8;1105 116D 11B3; # (룘; 룘; 룘; 룘; 룘; ) HANGUL SYLLABLE RYOLS
+B8D9;B8D9;1105 116D 11B4;B8D9;1105 116D 11B4; # (룙; 룙; 룙; 룙; 룙; ) HANGUL SYLLABLE RYOLT
+B8DA;B8DA;1105 116D 11B5;B8DA;1105 116D 11B5; # (룚; 룚; 룚; 룚; 룚; ) HANGUL SYLLABLE RYOLP
+B8DB;B8DB;1105 116D 11B6;B8DB;1105 116D 11B6; # (룛; 룛; 룛; 룛; 룛; ) HANGUL SYLLABLE RYOLH
+B8DC;B8DC;1105 116D 11B7;B8DC;1105 116D 11B7; # (룜; 룜; 룜; 룜; 룜; ) HANGUL SYLLABLE RYOM
+B8DD;B8DD;1105 116D 11B8;B8DD;1105 116D 11B8; # (룝; 룝; 룝; 룝; 룝; ) HANGUL SYLLABLE RYOB
+B8DE;B8DE;1105 116D 11B9;B8DE;1105 116D 11B9; # (룞; 룞; 룞; 룞; 룞; ) HANGUL SYLLABLE RYOBS
+B8DF;B8DF;1105 116D 11BA;B8DF;1105 116D 11BA; # (룟; 룟; 룟; 룟; 룟; ) HANGUL SYLLABLE RYOS
+B8E0;B8E0;1105 116D 11BB;B8E0;1105 116D 11BB; # (룠; 룠; 룠; 룠; 룠; ) HANGUL SYLLABLE RYOSS
+B8E1;B8E1;1105 116D 11BC;B8E1;1105 116D 11BC; # (룡; 룡; 룡; 룡; 룡; ) HANGUL SYLLABLE RYONG
+B8E2;B8E2;1105 116D 11BD;B8E2;1105 116D 11BD; # (룢; 룢; 룢; 룢; 룢; ) HANGUL SYLLABLE RYOJ
+B8E3;B8E3;1105 116D 11BE;B8E3;1105 116D 11BE; # (룣; 룣; 룣; 룣; 룣; ) HANGUL SYLLABLE RYOC
+B8E4;B8E4;1105 116D 11BF;B8E4;1105 116D 11BF; # (룤; 룤; 룤; 룤; 룤; ) HANGUL SYLLABLE RYOK
+B8E5;B8E5;1105 116D 11C0;B8E5;1105 116D 11C0; # (룥; 룥; 룥; 룥; 룥; ) HANGUL SYLLABLE RYOT
+B8E6;B8E6;1105 116D 11C1;B8E6;1105 116D 11C1; # (룦; 룦; 룦; 룦; 룦; ) HANGUL SYLLABLE RYOP
+B8E7;B8E7;1105 116D 11C2;B8E7;1105 116D 11C2; # (룧; 룧; 룧; 룧; 룧; ) HANGUL SYLLABLE RYOH
+B8E8;B8E8;1105 116E;B8E8;1105 116E; # (루; 루; 루; 루; 루; ) HANGUL SYLLABLE RU
+B8E9;B8E9;1105 116E 11A8;B8E9;1105 116E 11A8; # (룩; 룩; 룩; 룩; 룩; ) HANGUL SYLLABLE RUG
+B8EA;B8EA;1105 116E 11A9;B8EA;1105 116E 11A9; # (룪; 룪; 룪; 룪; 룪; ) HANGUL SYLLABLE RUGG
+B8EB;B8EB;1105 116E 11AA;B8EB;1105 116E 11AA; # (룫; 룫; 룫; 룫; 룫; ) HANGUL SYLLABLE RUGS
+B8EC;B8EC;1105 116E 11AB;B8EC;1105 116E 11AB; # (룬; 룬; 룬; 룬; 룬; ) HANGUL SYLLABLE RUN
+B8ED;B8ED;1105 116E 11AC;B8ED;1105 116E 11AC; # (룭; 룭; 룭; 룭; 룭; ) HANGUL SYLLABLE RUNJ
+B8EE;B8EE;1105 116E 11AD;B8EE;1105 116E 11AD; # (룮; 룮; 룮; 룮; 룮; ) HANGUL SYLLABLE RUNH
+B8EF;B8EF;1105 116E 11AE;B8EF;1105 116E 11AE; # (룯; 룯; 룯; 룯; 룯; ) HANGUL SYLLABLE RUD
+B8F0;B8F0;1105 116E 11AF;B8F0;1105 116E 11AF; # (룰; 룰; 룰; 룰; 룰; ) HANGUL SYLLABLE RUL
+B8F1;B8F1;1105 116E 11B0;B8F1;1105 116E 11B0; # (룱; 룱; 룱; 룱; 룱; ) HANGUL SYLLABLE RULG
+B8F2;B8F2;1105 116E 11B1;B8F2;1105 116E 11B1; # (룲; 룲; 룲; 룲; 룲; ) HANGUL SYLLABLE RULM
+B8F3;B8F3;1105 116E 11B2;B8F3;1105 116E 11B2; # (룳; 룳; 룳; 룳; 룳; ) HANGUL SYLLABLE RULB
+B8F4;B8F4;1105 116E 11B3;B8F4;1105 116E 11B3; # (룴; 룴; 룴; 룴; 룴; ) HANGUL SYLLABLE RULS
+B8F5;B8F5;1105 116E 11B4;B8F5;1105 116E 11B4; # (룵; 룵; 룵; 룵; 룵; ) HANGUL SYLLABLE RULT
+B8F6;B8F6;1105 116E 11B5;B8F6;1105 116E 11B5; # (룶; 룶; 룶; 룶; 룶; ) HANGUL SYLLABLE RULP
+B8F7;B8F7;1105 116E 11B6;B8F7;1105 116E 11B6; # (룷; 룷; 룷; 룷; 룷; ) HANGUL SYLLABLE RULH
+B8F8;B8F8;1105 116E 11B7;B8F8;1105 116E 11B7; # (룸; 룸; 룸; 룸; 룸; ) HANGUL SYLLABLE RUM
+B8F9;B8F9;1105 116E 11B8;B8F9;1105 116E 11B8; # (룹; 룹; 룹; 룹; 룹; ) HANGUL SYLLABLE RUB
+B8FA;B8FA;1105 116E 11B9;B8FA;1105 116E 11B9; # (룺; 룺; 룺; 룺; 룺; ) HANGUL SYLLABLE RUBS
+B8FB;B8FB;1105 116E 11BA;B8FB;1105 116E 11BA; # (룻; 룻; 룻; 룻; 룻; ) HANGUL SYLLABLE RUS
+B8FC;B8FC;1105 116E 11BB;B8FC;1105 116E 11BB; # (룼; 룼; 룼; 룼; 룼; ) HANGUL SYLLABLE RUSS
+B8FD;B8FD;1105 116E 11BC;B8FD;1105 116E 11BC; # (룽; 룽; 룽; 룽; 룽; ) HANGUL SYLLABLE RUNG
+B8FE;B8FE;1105 116E 11BD;B8FE;1105 116E 11BD; # (룾; 룾; 룾; 룾; 룾; ) HANGUL SYLLABLE RUJ
+B8FF;B8FF;1105 116E 11BE;B8FF;1105 116E 11BE; # (룿; 룿; 룿; 룿; 룿; ) HANGUL SYLLABLE RUC
+B900;B900;1105 116E 11BF;B900;1105 116E 11BF; # (뤀; 뤀; 뤀; 뤀; 뤀; ) HANGUL SYLLABLE RUK
+B901;B901;1105 116E 11C0;B901;1105 116E 11C0; # (뤁; 뤁; 뤁; 뤁; 뤁; ) HANGUL SYLLABLE RUT
+B902;B902;1105 116E 11C1;B902;1105 116E 11C1; # (뤂; 뤂; 뤂; 뤂; 뤂; ) HANGUL SYLLABLE RUP
+B903;B903;1105 116E 11C2;B903;1105 116E 11C2; # (뤃; 뤃; 뤃; 뤃; 뤃; ) HANGUL SYLLABLE RUH
+B904;B904;1105 116F;B904;1105 116F; # (뤄; 뤄; 뤄; 뤄; 뤄; ) HANGUL SYLLABLE RWEO
+B905;B905;1105 116F 11A8;B905;1105 116F 11A8; # (뤅; 뤅; 뤅; 뤅; 뤅; ) HANGUL SYLLABLE RWEOG
+B906;B906;1105 116F 11A9;B906;1105 116F 11A9; # (뤆; 뤆; 뤆; 뤆; 뤆; ) HANGUL SYLLABLE RWEOGG
+B907;B907;1105 116F 11AA;B907;1105 116F 11AA; # (뤇; 뤇; 뤇; 뤇; 뤇; ) HANGUL SYLLABLE RWEOGS
+B908;B908;1105 116F 11AB;B908;1105 116F 11AB; # (뤈; 뤈; 뤈; 뤈; 뤈; ) HANGUL SYLLABLE RWEON
+B909;B909;1105 116F 11AC;B909;1105 116F 11AC; # (뤉; 뤉; 뤉; 뤉; 뤉; ) HANGUL SYLLABLE RWEONJ
+B90A;B90A;1105 116F 11AD;B90A;1105 116F 11AD; # (뤊; 뤊; 뤊; 뤊; 뤊; ) HANGUL SYLLABLE RWEONH
+B90B;B90B;1105 116F 11AE;B90B;1105 116F 11AE; # (뤋; 뤋; 뤋; 뤋; 뤋; ) HANGUL SYLLABLE RWEOD
+B90C;B90C;1105 116F 11AF;B90C;1105 116F 11AF; # (뤌; 뤌; 뤌; 뤌; 뤌; ) HANGUL SYLLABLE RWEOL
+B90D;B90D;1105 116F 11B0;B90D;1105 116F 11B0; # (뤍; 뤍; 뤍; 뤍; 뤍; ) HANGUL SYLLABLE RWEOLG
+B90E;B90E;1105 116F 11B1;B90E;1105 116F 11B1; # (뤎; 뤎; 뤎; 뤎; 뤎; ) HANGUL SYLLABLE RWEOLM
+B90F;B90F;1105 116F 11B2;B90F;1105 116F 11B2; # (뤏; 뤏; 뤏; 뤏; 뤏; ) HANGUL SYLLABLE RWEOLB
+B910;B910;1105 116F 11B3;B910;1105 116F 11B3; # (뤐; 뤐; 뤐; 뤐; 뤐; ) HANGUL SYLLABLE RWEOLS
+B911;B911;1105 116F 11B4;B911;1105 116F 11B4; # (뤑; 뤑; 뤑; 뤑; 뤑; ) HANGUL SYLLABLE RWEOLT
+B912;B912;1105 116F 11B5;B912;1105 116F 11B5; # (뤒; 뤒; 뤒; 뤒; 뤒; ) HANGUL SYLLABLE RWEOLP
+B913;B913;1105 116F 11B6;B913;1105 116F 11B6; # (뤓; 뤓; 뤓; 뤓; 뤓; ) HANGUL SYLLABLE RWEOLH
+B914;B914;1105 116F 11B7;B914;1105 116F 11B7; # (뤔; 뤔; 뤔; 뤔; 뤔; ) HANGUL SYLLABLE RWEOM
+B915;B915;1105 116F 11B8;B915;1105 116F 11B8; # (뤕; 뤕; 뤕; 뤕; 뤕; ) HANGUL SYLLABLE RWEOB
+B916;B916;1105 116F 11B9;B916;1105 116F 11B9; # (뤖; 뤖; 뤖; 뤖; 뤖; ) HANGUL SYLLABLE RWEOBS
+B917;B917;1105 116F 11BA;B917;1105 116F 11BA; # (뤗; 뤗; 뤗; 뤗; 뤗; ) HANGUL SYLLABLE RWEOS
+B918;B918;1105 116F 11BB;B918;1105 116F 11BB; # (뤘; 뤘; 뤘; 뤘; 뤘; ) HANGUL SYLLABLE RWEOSS
+B919;B919;1105 116F 11BC;B919;1105 116F 11BC; # (뤙; 뤙; 뤙; 뤙; 뤙; ) HANGUL SYLLABLE RWEONG
+B91A;B91A;1105 116F 11BD;B91A;1105 116F 11BD; # (뤚; 뤚; 뤚; 뤚; 뤚; ) HANGUL SYLLABLE RWEOJ
+B91B;B91B;1105 116F 11BE;B91B;1105 116F 11BE; # (뤛; 뤛; 뤛; 뤛; 뤛; ) HANGUL SYLLABLE RWEOC
+B91C;B91C;1105 116F 11BF;B91C;1105 116F 11BF; # (뤜; 뤜; 뤜; 뤜; 뤜; ) HANGUL SYLLABLE RWEOK
+B91D;B91D;1105 116F 11C0;B91D;1105 116F 11C0; # (뤝; 뤝; 뤝; 뤝; 뤝; ) HANGUL SYLLABLE RWEOT
+B91E;B91E;1105 116F 11C1;B91E;1105 116F 11C1; # (뤞; 뤞; 뤞; 뤞; 뤞; ) HANGUL SYLLABLE RWEOP
+B91F;B91F;1105 116F 11C2;B91F;1105 116F 11C2; # (뤟; 뤟; 뤟; 뤟; 뤟; ) HANGUL SYLLABLE RWEOH
+B920;B920;1105 1170;B920;1105 1170; # (뤠; 뤠; 뤠; 뤠; 뤠; ) HANGUL SYLLABLE RWE
+B921;B921;1105 1170 11A8;B921;1105 1170 11A8; # (뤡; 뤡; 뤡; 뤡; 뤡; ) HANGUL SYLLABLE RWEG
+B922;B922;1105 1170 11A9;B922;1105 1170 11A9; # (뤢; 뤢; 뤢; 뤢; 뤢; ) HANGUL SYLLABLE RWEGG
+B923;B923;1105 1170 11AA;B923;1105 1170 11AA; # (뤣; 뤣; 뤣; 뤣; 뤣; ) HANGUL SYLLABLE RWEGS
+B924;B924;1105 1170 11AB;B924;1105 1170 11AB; # (뤤; 뤤; 뤤; 뤤; 뤤; ) HANGUL SYLLABLE RWEN
+B925;B925;1105 1170 11AC;B925;1105 1170 11AC; # (뤥; 뤥; 뤥; 뤥; 뤥; ) HANGUL SYLLABLE RWENJ
+B926;B926;1105 1170 11AD;B926;1105 1170 11AD; # (뤦; 뤦; 뤦; 뤦; 뤦; ) HANGUL SYLLABLE RWENH
+B927;B927;1105 1170 11AE;B927;1105 1170 11AE; # (뤧; 뤧; 뤧; 뤧; 뤧; ) HANGUL SYLLABLE RWED
+B928;B928;1105 1170 11AF;B928;1105 1170 11AF; # (뤨; 뤨; 뤨; 뤨; 뤨; ) HANGUL SYLLABLE RWEL
+B929;B929;1105 1170 11B0;B929;1105 1170 11B0; # (뤩; 뤩; 뤩; 뤩; 뤩; ) HANGUL SYLLABLE RWELG
+B92A;B92A;1105 1170 11B1;B92A;1105 1170 11B1; # (뤪; 뤪; 뤪; 뤪; 뤪; ) HANGUL SYLLABLE RWELM
+B92B;B92B;1105 1170 11B2;B92B;1105 1170 11B2; # (뤫; 뤫; 뤫; 뤫; 뤫; ) HANGUL SYLLABLE RWELB
+B92C;B92C;1105 1170 11B3;B92C;1105 1170 11B3; # (뤬; 뤬; 뤬; 뤬; 뤬; ) HANGUL SYLLABLE RWELS
+B92D;B92D;1105 1170 11B4;B92D;1105 1170 11B4; # (뤭; 뤭; 뤭; 뤭; 뤭; ) HANGUL SYLLABLE RWELT
+B92E;B92E;1105 1170 11B5;B92E;1105 1170 11B5; # (뤮; 뤮; 뤮; 뤮; 뤮; ) HANGUL SYLLABLE RWELP
+B92F;B92F;1105 1170 11B6;B92F;1105 1170 11B6; # (뤯; 뤯; 뤯; 뤯; 뤯; ) HANGUL SYLLABLE RWELH
+B930;B930;1105 1170 11B7;B930;1105 1170 11B7; # (뤰; 뤰; 뤰; 뤰; 뤰; ) HANGUL SYLLABLE RWEM
+B931;B931;1105 1170 11B8;B931;1105 1170 11B8; # (뤱; 뤱; 뤱; 뤱; 뤱; ) HANGUL SYLLABLE RWEB
+B932;B932;1105 1170 11B9;B932;1105 1170 11B9; # (뤲; 뤲; 뤲; 뤲; 뤲; ) HANGUL SYLLABLE RWEBS
+B933;B933;1105 1170 11BA;B933;1105 1170 11BA; # (뤳; 뤳; 뤳; 뤳; 뤳; ) HANGUL SYLLABLE RWES
+B934;B934;1105 1170 11BB;B934;1105 1170 11BB; # (뤴; 뤴; 뤴; 뤴; 뤴; ) HANGUL SYLLABLE RWESS
+B935;B935;1105 1170 11BC;B935;1105 1170 11BC; # (뤵; 뤵; 뤵; 뤵; 뤵; ) HANGUL SYLLABLE RWENG
+B936;B936;1105 1170 11BD;B936;1105 1170 11BD; # (뤶; 뤶; 뤶; 뤶; 뤶; ) HANGUL SYLLABLE RWEJ
+B937;B937;1105 1170 11BE;B937;1105 1170 11BE; # (뤷; 뤷; 뤷; 뤷; 뤷; ) HANGUL SYLLABLE RWEC
+B938;B938;1105 1170 11BF;B938;1105 1170 11BF; # (뤸; 뤸; 뤸; 뤸; 뤸; ) HANGUL SYLLABLE RWEK
+B939;B939;1105 1170 11C0;B939;1105 1170 11C0; # (뤹; 뤹; 뤹; 뤹; 뤹; ) HANGUL SYLLABLE RWET
+B93A;B93A;1105 1170 11C1;B93A;1105 1170 11C1; # (뤺; 뤺; 뤺; 뤺; 뤺; ) HANGUL SYLLABLE RWEP
+B93B;B93B;1105 1170 11C2;B93B;1105 1170 11C2; # (뤻; 뤻; 뤻; 뤻; 뤻; ) HANGUL SYLLABLE RWEH
+B93C;B93C;1105 1171;B93C;1105 1171; # (뤼; 뤼; 뤼; 뤼; 뤼; ) HANGUL SYLLABLE RWI
+B93D;B93D;1105 1171 11A8;B93D;1105 1171 11A8; # (뤽; 뤽; 뤽; 뤽; 뤽; ) HANGUL SYLLABLE RWIG
+B93E;B93E;1105 1171 11A9;B93E;1105 1171 11A9; # (뤾; 뤾; 뤾; 뤾; 뤾; ) HANGUL SYLLABLE RWIGG
+B93F;B93F;1105 1171 11AA;B93F;1105 1171 11AA; # (뤿; 뤿; 뤿; 뤿; 뤿; ) HANGUL SYLLABLE RWIGS
+B940;B940;1105 1171 11AB;B940;1105 1171 11AB; # (륀; 륀; 륀; 륀; 륀; ) HANGUL SYLLABLE RWIN
+B941;B941;1105 1171 11AC;B941;1105 1171 11AC; # (륁; 륁; 륁; 륁; 륁; ) HANGUL SYLLABLE RWINJ
+B942;B942;1105 1171 11AD;B942;1105 1171 11AD; # (륂; 륂; 륂; 륂; 륂; ) HANGUL SYLLABLE RWINH
+B943;B943;1105 1171 11AE;B943;1105 1171 11AE; # (륃; 륃; 륃; 륃; 륃; ) HANGUL SYLLABLE RWID
+B944;B944;1105 1171 11AF;B944;1105 1171 11AF; # (륄; 륄; 륄; 륄; 륄; ) HANGUL SYLLABLE RWIL
+B945;B945;1105 1171 11B0;B945;1105 1171 11B0; # (륅; 륅; 륅; 륅; 륅; ) HANGUL SYLLABLE RWILG
+B946;B946;1105 1171 11B1;B946;1105 1171 11B1; # (륆; 륆; 륆; 륆; 륆; ) HANGUL SYLLABLE RWILM
+B947;B947;1105 1171 11B2;B947;1105 1171 11B2; # (륇; 륇; 륇; 륇; 륇; ) HANGUL SYLLABLE RWILB
+B948;B948;1105 1171 11B3;B948;1105 1171 11B3; # (륈; 륈; 륈; 륈; 륈; ) HANGUL SYLLABLE RWILS
+B949;B949;1105 1171 11B4;B949;1105 1171 11B4; # (륉; 륉; 륉; 륉; 륉; ) HANGUL SYLLABLE RWILT
+B94A;B94A;1105 1171 11B5;B94A;1105 1171 11B5; # (륊; 륊; 륊; 륊; 륊; ) HANGUL SYLLABLE RWILP
+B94B;B94B;1105 1171 11B6;B94B;1105 1171 11B6; # (륋; 륋; 륋; 륋; 륋; ) HANGUL SYLLABLE RWILH
+B94C;B94C;1105 1171 11B7;B94C;1105 1171 11B7; # (륌; 륌; 륌; 륌; 륌; ) HANGUL SYLLABLE RWIM
+B94D;B94D;1105 1171 11B8;B94D;1105 1171 11B8; # (륍; 륍; 륍; 륍; 륍; ) HANGUL SYLLABLE RWIB
+B94E;B94E;1105 1171 11B9;B94E;1105 1171 11B9; # (륎; 륎; 륎; 륎; 륎; ) HANGUL SYLLABLE RWIBS
+B94F;B94F;1105 1171 11BA;B94F;1105 1171 11BA; # (륏; 륏; 륏; 륏; 륏; ) HANGUL SYLLABLE RWIS
+B950;B950;1105 1171 11BB;B950;1105 1171 11BB; # (륐; 륐; 륐; 륐; 륐; ) HANGUL SYLLABLE RWISS
+B951;B951;1105 1171 11BC;B951;1105 1171 11BC; # (륑; 륑; 륑; 륑; 륑; ) HANGUL SYLLABLE RWING
+B952;B952;1105 1171 11BD;B952;1105 1171 11BD; # (륒; 륒; 륒; 륒; 륒; ) HANGUL SYLLABLE RWIJ
+B953;B953;1105 1171 11BE;B953;1105 1171 11BE; # (륓; 륓; 륓; 륓; 륓; ) HANGUL SYLLABLE RWIC
+B954;B954;1105 1171 11BF;B954;1105 1171 11BF; # (륔; 륔; 륔; 륔; 륔; ) HANGUL SYLLABLE RWIK
+B955;B955;1105 1171 11C0;B955;1105 1171 11C0; # (륕; 륕; 륕; 륕; 륕; ) HANGUL SYLLABLE RWIT
+B956;B956;1105 1171 11C1;B956;1105 1171 11C1; # (륖; 륖; 륖; 륖; 륖; ) HANGUL SYLLABLE RWIP
+B957;B957;1105 1171 11C2;B957;1105 1171 11C2; # (륗; 륗; 륗; 륗; 륗; ) HANGUL SYLLABLE RWIH
+B958;B958;1105 1172;B958;1105 1172; # (류; 류; 류; 류; 류; ) HANGUL SYLLABLE RYU
+B959;B959;1105 1172 11A8;B959;1105 1172 11A8; # (륙; 륙; 륙; 륙; 륙; ) HANGUL SYLLABLE RYUG
+B95A;B95A;1105 1172 11A9;B95A;1105 1172 11A9; # (륚; 륚; 륚; 륚; 륚; ) HANGUL SYLLABLE RYUGG
+B95B;B95B;1105 1172 11AA;B95B;1105 1172 11AA; # (륛; 륛; 륛; 륛; 륛; ) HANGUL SYLLABLE RYUGS
+B95C;B95C;1105 1172 11AB;B95C;1105 1172 11AB; # (륜; 륜; 륜; 륜; 륜; ) HANGUL SYLLABLE RYUN
+B95D;B95D;1105 1172 11AC;B95D;1105 1172 11AC; # (륝; 륝; 륝; 륝; 륝; ) HANGUL SYLLABLE RYUNJ
+B95E;B95E;1105 1172 11AD;B95E;1105 1172 11AD; # (륞; 륞; 륞; 륞; 륞; ) HANGUL SYLLABLE RYUNH
+B95F;B95F;1105 1172 11AE;B95F;1105 1172 11AE; # (륟; 륟; 륟; 륟; 륟; ) HANGUL SYLLABLE RYUD
+B960;B960;1105 1172 11AF;B960;1105 1172 11AF; # (률; 률; 률; 률; 률; ) HANGUL SYLLABLE RYUL
+B961;B961;1105 1172 11B0;B961;1105 1172 11B0; # (륡; 륡; 륡; 륡; 륡; ) HANGUL SYLLABLE RYULG
+B962;B962;1105 1172 11B1;B962;1105 1172 11B1; # (륢; 륢; 륢; 륢; 륢; ) HANGUL SYLLABLE RYULM
+B963;B963;1105 1172 11B2;B963;1105 1172 11B2; # (륣; 륣; 륣; 륣; 륣; ) HANGUL SYLLABLE RYULB
+B964;B964;1105 1172 11B3;B964;1105 1172 11B3; # (륤; 륤; 륤; 륤; 륤; ) HANGUL SYLLABLE RYULS
+B965;B965;1105 1172 11B4;B965;1105 1172 11B4; # (륥; 륥; 륥; 륥; 륥; ) HANGUL SYLLABLE RYULT
+B966;B966;1105 1172 11B5;B966;1105 1172 11B5; # (륦; 륦; 륦; 륦; 륦; ) HANGUL SYLLABLE RYULP
+B967;B967;1105 1172 11B6;B967;1105 1172 11B6; # (륧; 륧; 륧; 륧; 륧; ) HANGUL SYLLABLE RYULH
+B968;B968;1105 1172 11B7;B968;1105 1172 11B7; # (륨; 륨; 륨; 륨; 륨; ) HANGUL SYLLABLE RYUM
+B969;B969;1105 1172 11B8;B969;1105 1172 11B8; # (륩; 륩; 륩; 륩; 륩; ) HANGUL SYLLABLE RYUB
+B96A;B96A;1105 1172 11B9;B96A;1105 1172 11B9; # (륪; 륪; 륪; 륪; 륪; ) HANGUL SYLLABLE RYUBS
+B96B;B96B;1105 1172 11BA;B96B;1105 1172 11BA; # (륫; 륫; 륫; 륫; 륫; ) HANGUL SYLLABLE RYUS
+B96C;B96C;1105 1172 11BB;B96C;1105 1172 11BB; # (륬; 륬; 륬; 륬; 륬; ) HANGUL SYLLABLE RYUSS
+B96D;B96D;1105 1172 11BC;B96D;1105 1172 11BC; # (륭; 륭; 륭; 륭; 륭; ) HANGUL SYLLABLE RYUNG
+B96E;B96E;1105 1172 11BD;B96E;1105 1172 11BD; # (륮; 륮; 륮; 륮; 륮; ) HANGUL SYLLABLE RYUJ
+B96F;B96F;1105 1172 11BE;B96F;1105 1172 11BE; # (륯; 륯; 륯; 륯; 륯; ) HANGUL SYLLABLE RYUC
+B970;B970;1105 1172 11BF;B970;1105 1172 11BF; # (륰; 륰; 륰; 륰; 륰; ) HANGUL SYLLABLE RYUK
+B971;B971;1105 1172 11C0;B971;1105 1172 11C0; # (륱; 륱; 륱; 륱; 륱; ) HANGUL SYLLABLE RYUT
+B972;B972;1105 1172 11C1;B972;1105 1172 11C1; # (륲; 륲; 륲; 륲; 륲; ) HANGUL SYLLABLE RYUP
+B973;B973;1105 1172 11C2;B973;1105 1172 11C2; # (륳; 륳; 륳; 륳; 륳; ) HANGUL SYLLABLE RYUH
+B974;B974;1105 1173;B974;1105 1173; # (르; 르; 르; 르; 르; ) HANGUL SYLLABLE REU
+B975;B975;1105 1173 11A8;B975;1105 1173 11A8; # (륵; 륵; 륵; 륵; 륵; ) HANGUL SYLLABLE REUG
+B976;B976;1105 1173 11A9;B976;1105 1173 11A9; # (륶; 륶; 륶; 륶; 륶; ) HANGUL SYLLABLE REUGG
+B977;B977;1105 1173 11AA;B977;1105 1173 11AA; # (륷; 륷; 륷; 륷; 륷; ) HANGUL SYLLABLE REUGS
+B978;B978;1105 1173 11AB;B978;1105 1173 11AB; # (른; 른; 른; 른; 른; ) HANGUL SYLLABLE REUN
+B979;B979;1105 1173 11AC;B979;1105 1173 11AC; # (륹; 륹; 륹; 륹; 륹; ) HANGUL SYLLABLE REUNJ
+B97A;B97A;1105 1173 11AD;B97A;1105 1173 11AD; # (륺; 륺; 륺; 륺; 륺; ) HANGUL SYLLABLE REUNH
+B97B;B97B;1105 1173 11AE;B97B;1105 1173 11AE; # (륻; 륻; 륻; 륻; 륻; ) HANGUL SYLLABLE REUD
+B97C;B97C;1105 1173 11AF;B97C;1105 1173 11AF; # (를; 를; 를; 를; 를; ) HANGUL SYLLABLE REUL
+B97D;B97D;1105 1173 11B0;B97D;1105 1173 11B0; # (륽; 륽; 륽; 륽; 륽; ) HANGUL SYLLABLE REULG
+B97E;B97E;1105 1173 11B1;B97E;1105 1173 11B1; # (륾; 륾; 륾; 륾; 륾; ) HANGUL SYLLABLE REULM
+B97F;B97F;1105 1173 11B2;B97F;1105 1173 11B2; # (륿; 륿; 륿; 륿; 륿; ) HANGUL SYLLABLE REULB
+B980;B980;1105 1173 11B3;B980;1105 1173 11B3; # (릀; 릀; 릀; 릀; 릀; ) HANGUL SYLLABLE REULS
+B981;B981;1105 1173 11B4;B981;1105 1173 11B4; # (릁; 릁; 릁; 릁; 릁; ) HANGUL SYLLABLE REULT
+B982;B982;1105 1173 11B5;B982;1105 1173 11B5; # (릂; 릂; 릂; 릂; 릂; ) HANGUL SYLLABLE REULP
+B983;B983;1105 1173 11B6;B983;1105 1173 11B6; # (릃; 릃; 릃; 릃; 릃; ) HANGUL SYLLABLE REULH
+B984;B984;1105 1173 11B7;B984;1105 1173 11B7; # (름; 름; 름; 름; 름; ) HANGUL SYLLABLE REUM
+B985;B985;1105 1173 11B8;B985;1105 1173 11B8; # (릅; 릅; 릅; 릅; 릅; ) HANGUL SYLLABLE REUB
+B986;B986;1105 1173 11B9;B986;1105 1173 11B9; # (릆; 릆; 릆; 릆; 릆; ) HANGUL SYLLABLE REUBS
+B987;B987;1105 1173 11BA;B987;1105 1173 11BA; # (릇; 릇; 릇; 릇; 릇; ) HANGUL SYLLABLE REUS
+B988;B988;1105 1173 11BB;B988;1105 1173 11BB; # (릈; 릈; 릈; 릈; 릈; ) HANGUL SYLLABLE REUSS
+B989;B989;1105 1173 11BC;B989;1105 1173 11BC; # (릉; 릉; 릉; 릉; 릉; ) HANGUL SYLLABLE REUNG
+B98A;B98A;1105 1173 11BD;B98A;1105 1173 11BD; # (릊; 릊; 릊; 릊; 릊; ) HANGUL SYLLABLE REUJ
+B98B;B98B;1105 1173 11BE;B98B;1105 1173 11BE; # (릋; 릋; 릋; 릋; 릋; ) HANGUL SYLLABLE REUC
+B98C;B98C;1105 1173 11BF;B98C;1105 1173 11BF; # (릌; 릌; 릌; 릌; 릌; ) HANGUL SYLLABLE REUK
+B98D;B98D;1105 1173 11C0;B98D;1105 1173 11C0; # (릍; 릍; 릍; 릍; 릍; ) HANGUL SYLLABLE REUT
+B98E;B98E;1105 1173 11C1;B98E;1105 1173 11C1; # (릎; 릎; 릎; 릎; 릎; ) HANGUL SYLLABLE REUP
+B98F;B98F;1105 1173 11C2;B98F;1105 1173 11C2; # (릏; 릏; 릏; 릏; 릏; ) HANGUL SYLLABLE REUH
+B990;B990;1105 1174;B990;1105 1174; # (릐; 릐; 릐; 릐; 릐; ) HANGUL SYLLABLE RYI
+B991;B991;1105 1174 11A8;B991;1105 1174 11A8; # (릑; 릑; 릑; 릑; 릑; ) HANGUL SYLLABLE RYIG
+B992;B992;1105 1174 11A9;B992;1105 1174 11A9; # (릒; 릒; 릒; 릒; 릒; ) HANGUL SYLLABLE RYIGG
+B993;B993;1105 1174 11AA;B993;1105 1174 11AA; # (릓; 릓; 릓; 릓; 릓; ) HANGUL SYLLABLE RYIGS
+B994;B994;1105 1174 11AB;B994;1105 1174 11AB; # (릔; 릔; 릔; 릔; 릔; ) HANGUL SYLLABLE RYIN
+B995;B995;1105 1174 11AC;B995;1105 1174 11AC; # (릕; 릕; 릕; 릕; 릕; ) HANGUL SYLLABLE RYINJ
+B996;B996;1105 1174 11AD;B996;1105 1174 11AD; # (릖; 릖; 릖; 릖; 릖; ) HANGUL SYLLABLE RYINH
+B997;B997;1105 1174 11AE;B997;1105 1174 11AE; # (릗; 릗; 릗; 릗; 릗; ) HANGUL SYLLABLE RYID
+B998;B998;1105 1174 11AF;B998;1105 1174 11AF; # (릘; 릘; 릘; 릘; 릘; ) HANGUL SYLLABLE RYIL
+B999;B999;1105 1174 11B0;B999;1105 1174 11B0; # (릙; 릙; 릙; 릙; 릙; ) HANGUL SYLLABLE RYILG
+B99A;B99A;1105 1174 11B1;B99A;1105 1174 11B1; # (릚; 릚; 릚; 릚; 릚; ) HANGUL SYLLABLE RYILM
+B99B;B99B;1105 1174 11B2;B99B;1105 1174 11B2; # (릛; 릛; 릛; 릛; 릛; ) HANGUL SYLLABLE RYILB
+B99C;B99C;1105 1174 11B3;B99C;1105 1174 11B3; # (릜; 릜; 릜; 릜; 릜; ) HANGUL SYLLABLE RYILS
+B99D;B99D;1105 1174 11B4;B99D;1105 1174 11B4; # (릝; 릝; 릝; 릝; 릝; ) HANGUL SYLLABLE RYILT
+B99E;B99E;1105 1174 11B5;B99E;1105 1174 11B5; # (릞; 릞; 릞; 릞; 릞; ) HANGUL SYLLABLE RYILP
+B99F;B99F;1105 1174 11B6;B99F;1105 1174 11B6; # (릟; 릟; 릟; 릟; 릟; ) HANGUL SYLLABLE RYILH
+B9A0;B9A0;1105 1174 11B7;B9A0;1105 1174 11B7; # (릠; 릠; 릠; 릠; 릠; ) HANGUL SYLLABLE RYIM
+B9A1;B9A1;1105 1174 11B8;B9A1;1105 1174 11B8; # (릡; 릡; 릡; 릡; 릡; ) HANGUL SYLLABLE RYIB
+B9A2;B9A2;1105 1174 11B9;B9A2;1105 1174 11B9; # (릢; 릢; 릢; 릢; 릢; ) HANGUL SYLLABLE RYIBS
+B9A3;B9A3;1105 1174 11BA;B9A3;1105 1174 11BA; # (릣; 릣; 릣; 릣; 릣; ) HANGUL SYLLABLE RYIS
+B9A4;B9A4;1105 1174 11BB;B9A4;1105 1174 11BB; # (릤; 릤; 릤; 릤; 릤; ) HANGUL SYLLABLE RYISS
+B9A5;B9A5;1105 1174 11BC;B9A5;1105 1174 11BC; # (릥; 릥; 릥; 릥; 릥; ) HANGUL SYLLABLE RYING
+B9A6;B9A6;1105 1174 11BD;B9A6;1105 1174 11BD; # (릦; 릦; 릦; 릦; 릦; ) HANGUL SYLLABLE RYIJ
+B9A7;B9A7;1105 1174 11BE;B9A7;1105 1174 11BE; # (릧; 릧; 릧; 릧; 릧; ) HANGUL SYLLABLE RYIC
+B9A8;B9A8;1105 1174 11BF;B9A8;1105 1174 11BF; # (릨; 릨; 릨; 릨; 릨; ) HANGUL SYLLABLE RYIK
+B9A9;B9A9;1105 1174 11C0;B9A9;1105 1174 11C0; # (릩; 릩; 릩; 릩; 릩; ) HANGUL SYLLABLE RYIT
+B9AA;B9AA;1105 1174 11C1;B9AA;1105 1174 11C1; # (릪; 릪; 릪; 릪; 릪; ) HANGUL SYLLABLE RYIP
+B9AB;B9AB;1105 1174 11C2;B9AB;1105 1174 11C2; # (릫; 릫; 릫; 릫; 릫; ) HANGUL SYLLABLE RYIH
+B9AC;B9AC;1105 1175;B9AC;1105 1175; # (리; 리; 리; 리; 리; ) HANGUL SYLLABLE RI
+B9AD;B9AD;1105 1175 11A8;B9AD;1105 1175 11A8; # (릭; 릭; 릭; 릭; 릭; ) HANGUL SYLLABLE RIG
+B9AE;B9AE;1105 1175 11A9;B9AE;1105 1175 11A9; # (릮; 릮; 릮; 릮; 릮; ) HANGUL SYLLABLE RIGG
+B9AF;B9AF;1105 1175 11AA;B9AF;1105 1175 11AA; # (릯; 릯; 릯; 릯; 릯; ) HANGUL SYLLABLE RIGS
+B9B0;B9B0;1105 1175 11AB;B9B0;1105 1175 11AB; # (린; 린; 린; 린; 린; ) HANGUL SYLLABLE RIN
+B9B1;B9B1;1105 1175 11AC;B9B1;1105 1175 11AC; # (릱; 릱; 릱; 릱; 릱; ) HANGUL SYLLABLE RINJ
+B9B2;B9B2;1105 1175 11AD;B9B2;1105 1175 11AD; # (릲; 릲; 릲; 릲; 릲; ) HANGUL SYLLABLE RINH
+B9B3;B9B3;1105 1175 11AE;B9B3;1105 1175 11AE; # (릳; 릳; 릳; 릳; 릳; ) HANGUL SYLLABLE RID
+B9B4;B9B4;1105 1175 11AF;B9B4;1105 1175 11AF; # (릴; 릴; 릴; 릴; 릴; ) HANGUL SYLLABLE RIL
+B9B5;B9B5;1105 1175 11B0;B9B5;1105 1175 11B0; # (릵; 릵; 릵; 릵; 릵; ) HANGUL SYLLABLE RILG
+B9B6;B9B6;1105 1175 11B1;B9B6;1105 1175 11B1; # (릶; 릶; 릶; 릶; 릶; ) HANGUL SYLLABLE RILM
+B9B7;B9B7;1105 1175 11B2;B9B7;1105 1175 11B2; # (릷; 릷; 릷; 릷; 릷; ) HANGUL SYLLABLE RILB
+B9B8;B9B8;1105 1175 11B3;B9B8;1105 1175 11B3; # (릸; 릸; 릸; 릸; 릸; ) HANGUL SYLLABLE RILS
+B9B9;B9B9;1105 1175 11B4;B9B9;1105 1175 11B4; # (릹; 릹; 릹; 릹; 릹; ) HANGUL SYLLABLE RILT
+B9BA;B9BA;1105 1175 11B5;B9BA;1105 1175 11B5; # (릺; 릺; 릺; 릺; 릺; ) HANGUL SYLLABLE RILP
+B9BB;B9BB;1105 1175 11B6;B9BB;1105 1175 11B6; # (릻; 릻; 릻; 릻; 릻; ) HANGUL SYLLABLE RILH
+B9BC;B9BC;1105 1175 11B7;B9BC;1105 1175 11B7; # (림; 림; 림; 림; 림; ) HANGUL SYLLABLE RIM
+B9BD;B9BD;1105 1175 11B8;B9BD;1105 1175 11B8; # (립; 립; 립; 립; 립; ) HANGUL SYLLABLE RIB
+B9BE;B9BE;1105 1175 11B9;B9BE;1105 1175 11B9; # (릾; 릾; 릾; 릾; 릾; ) HANGUL SYLLABLE RIBS
+B9BF;B9BF;1105 1175 11BA;B9BF;1105 1175 11BA; # (릿; 릿; 릿; 릿; 릿; ) HANGUL SYLLABLE RIS
+B9C0;B9C0;1105 1175 11BB;B9C0;1105 1175 11BB; # (맀; 맀; 맀; 맀; 맀; ) HANGUL SYLLABLE RISS
+B9C1;B9C1;1105 1175 11BC;B9C1;1105 1175 11BC; # (링; 링; 링; 링; 링; ) HANGUL SYLLABLE RING
+B9C2;B9C2;1105 1175 11BD;B9C2;1105 1175 11BD; # (맂; 맂; 맂; 맂; 맂; ) HANGUL SYLLABLE RIJ
+B9C3;B9C3;1105 1175 11BE;B9C3;1105 1175 11BE; # (맃; 맃; 맃; 맃; 맃; ) HANGUL SYLLABLE RIC
+B9C4;B9C4;1105 1175 11BF;B9C4;1105 1175 11BF; # (맄; 맄; 맄; 맄; 맄; ) HANGUL SYLLABLE RIK
+B9C5;B9C5;1105 1175 11C0;B9C5;1105 1175 11C0; # (맅; 맅; 맅; 맅; 맅; ) HANGUL SYLLABLE RIT
+B9C6;B9C6;1105 1175 11C1;B9C6;1105 1175 11C1; # (맆; 맆; 맆; 맆; 맆; ) HANGUL SYLLABLE RIP
+B9C7;B9C7;1105 1175 11C2;B9C7;1105 1175 11C2; # (맇; 맇; 맇; 맇; 맇; ) HANGUL SYLLABLE RIH
+B9C8;B9C8;1106 1161;B9C8;1106 1161; # (마; 마; 마; 마; 마; ) HANGUL SYLLABLE MA
+B9C9;B9C9;1106 1161 11A8;B9C9;1106 1161 11A8; # (막; 막; 막; 막; 막; ) HANGUL SYLLABLE MAG
+B9CA;B9CA;1106 1161 11A9;B9CA;1106 1161 11A9; # (맊; 맊; 맊; 맊; 맊; ) HANGUL SYLLABLE MAGG
+B9CB;B9CB;1106 1161 11AA;B9CB;1106 1161 11AA; # (맋; 맋; 맋; 맋; 맋; ) HANGUL SYLLABLE MAGS
+B9CC;B9CC;1106 1161 11AB;B9CC;1106 1161 11AB; # (만; 만; 만; 만; 만; ) HANGUL SYLLABLE MAN
+B9CD;B9CD;1106 1161 11AC;B9CD;1106 1161 11AC; # (맍; 맍; 맍; 맍; 맍; ) HANGUL SYLLABLE MANJ
+B9CE;B9CE;1106 1161 11AD;B9CE;1106 1161 11AD; # (많; 많; 많; 많; 많; ) HANGUL SYLLABLE MANH
+B9CF;B9CF;1106 1161 11AE;B9CF;1106 1161 11AE; # (맏; 맏; 맏; 맏; 맏; ) HANGUL SYLLABLE MAD
+B9D0;B9D0;1106 1161 11AF;B9D0;1106 1161 11AF; # (말; 말; 말; 말; 말; ) HANGUL SYLLABLE MAL
+B9D1;B9D1;1106 1161 11B0;B9D1;1106 1161 11B0; # (맑; 맑; 맑; 맑; 맑; ) HANGUL SYLLABLE MALG
+B9D2;B9D2;1106 1161 11B1;B9D2;1106 1161 11B1; # (맒; 맒; 맒; 맒; 맒; ) HANGUL SYLLABLE MALM
+B9D3;B9D3;1106 1161 11B2;B9D3;1106 1161 11B2; # (맓; 맓; 맓; 맓; 맓; ) HANGUL SYLLABLE MALB
+B9D4;B9D4;1106 1161 11B3;B9D4;1106 1161 11B3; # (맔; 맔; 맔; 맔; 맔; ) HANGUL SYLLABLE MALS
+B9D5;B9D5;1106 1161 11B4;B9D5;1106 1161 11B4; # (맕; 맕; 맕; 맕; 맕; ) HANGUL SYLLABLE MALT
+B9D6;B9D6;1106 1161 11B5;B9D6;1106 1161 11B5; # (맖; 맖; 맖; 맖; 맖; ) HANGUL SYLLABLE MALP
+B9D7;B9D7;1106 1161 11B6;B9D7;1106 1161 11B6; # (맗; 맗; 맗; 맗; 맗; ) HANGUL SYLLABLE MALH
+B9D8;B9D8;1106 1161 11B7;B9D8;1106 1161 11B7; # (맘; 맘; 맘; 맘; 맘; ) HANGUL SYLLABLE MAM
+B9D9;B9D9;1106 1161 11B8;B9D9;1106 1161 11B8; # (맙; 맙; 맙; 맙; 맙; ) HANGUL SYLLABLE MAB
+B9DA;B9DA;1106 1161 11B9;B9DA;1106 1161 11B9; # (맚; 맚; 맚; 맚; 맚; ) HANGUL SYLLABLE MABS
+B9DB;B9DB;1106 1161 11BA;B9DB;1106 1161 11BA; # (맛; 맛; 맛; 맛; 맛; ) HANGUL SYLLABLE MAS
+B9DC;B9DC;1106 1161 11BB;B9DC;1106 1161 11BB; # (맜; 맜; 맜; 맜; 맜; ) HANGUL SYLLABLE MASS
+B9DD;B9DD;1106 1161 11BC;B9DD;1106 1161 11BC; # (망; 망; 망; 망; 망; ) HANGUL SYLLABLE MANG
+B9DE;B9DE;1106 1161 11BD;B9DE;1106 1161 11BD; # (맞; 맞; 맞; 맞; 맞; ) HANGUL SYLLABLE MAJ
+B9DF;B9DF;1106 1161 11BE;B9DF;1106 1161 11BE; # (맟; 맟; 맟; 맟; 맟; ) HANGUL SYLLABLE MAC
+B9E0;B9E0;1106 1161 11BF;B9E0;1106 1161 11BF; # (맠; 맠; 맠; 맠; 맠; ) HANGUL SYLLABLE MAK
+B9E1;B9E1;1106 1161 11C0;B9E1;1106 1161 11C0; # (맡; 맡; 맡; 맡; 맡; ) HANGUL SYLLABLE MAT
+B9E2;B9E2;1106 1161 11C1;B9E2;1106 1161 11C1; # (맢; 맢; 맢; 맢; 맢; ) HANGUL SYLLABLE MAP
+B9E3;B9E3;1106 1161 11C2;B9E3;1106 1161 11C2; # (맣; 맣; 맣; 맣; 맣; ) HANGUL SYLLABLE MAH
+B9E4;B9E4;1106 1162;B9E4;1106 1162; # (매; 매; 매; 매; 매; ) HANGUL SYLLABLE MAE
+B9E5;B9E5;1106 1162 11A8;B9E5;1106 1162 11A8; # (맥; 맥; 맥; 맥; 맥; ) HANGUL SYLLABLE MAEG
+B9E6;B9E6;1106 1162 11A9;B9E6;1106 1162 11A9; # (맦; 맦; 맦; 맦; 맦; ) HANGUL SYLLABLE MAEGG
+B9E7;B9E7;1106 1162 11AA;B9E7;1106 1162 11AA; # (맧; 맧; 맧; 맧; 맧; ) HANGUL SYLLABLE MAEGS
+B9E8;B9E8;1106 1162 11AB;B9E8;1106 1162 11AB; # (맨; 맨; 맨; 맨; 맨; ) HANGUL SYLLABLE MAEN
+B9E9;B9E9;1106 1162 11AC;B9E9;1106 1162 11AC; # (맩; 맩; 맩; 맩; 맩; ) HANGUL SYLLABLE MAENJ
+B9EA;B9EA;1106 1162 11AD;B9EA;1106 1162 11AD; # (맪; 맪; 맪; 맪; 맪; ) HANGUL SYLLABLE MAENH
+B9EB;B9EB;1106 1162 11AE;B9EB;1106 1162 11AE; # (맫; 맫; 맫; 맫; 맫; ) HANGUL SYLLABLE MAED
+B9EC;B9EC;1106 1162 11AF;B9EC;1106 1162 11AF; # (맬; 맬; 맬; 맬; 맬; ) HANGUL SYLLABLE MAEL
+B9ED;B9ED;1106 1162 11B0;B9ED;1106 1162 11B0; # (맭; 맭; 맭; 맭; 맭; ) HANGUL SYLLABLE MAELG
+B9EE;B9EE;1106 1162 11B1;B9EE;1106 1162 11B1; # (맮; 맮; 맮; 맮; 맮; ) HANGUL SYLLABLE MAELM
+B9EF;B9EF;1106 1162 11B2;B9EF;1106 1162 11B2; # (맯; 맯; 맯; 맯; 맯; ) HANGUL SYLLABLE MAELB
+B9F0;B9F0;1106 1162 11B3;B9F0;1106 1162 11B3; # (맰; 맰; 맰; 맰; 맰; ) HANGUL SYLLABLE MAELS
+B9F1;B9F1;1106 1162 11B4;B9F1;1106 1162 11B4; # (맱; 맱; 맱; 맱; 맱; ) HANGUL SYLLABLE MAELT
+B9F2;B9F2;1106 1162 11B5;B9F2;1106 1162 11B5; # (맲; 맲; 맲; 맲; 맲; ) HANGUL SYLLABLE MAELP
+B9F3;B9F3;1106 1162 11B6;B9F3;1106 1162 11B6; # (맳; 맳; 맳; 맳; 맳; ) HANGUL SYLLABLE MAELH
+B9F4;B9F4;1106 1162 11B7;B9F4;1106 1162 11B7; # (맴; 맴; 맴; 맴; 맴; ) HANGUL SYLLABLE MAEM
+B9F5;B9F5;1106 1162 11B8;B9F5;1106 1162 11B8; # (맵; 맵; 맵; 맵; 맵; ) HANGUL SYLLABLE MAEB
+B9F6;B9F6;1106 1162 11B9;B9F6;1106 1162 11B9; # (맶; 맶; 맶; 맶; 맶; ) HANGUL SYLLABLE MAEBS
+B9F7;B9F7;1106 1162 11BA;B9F7;1106 1162 11BA; # (맷; 맷; 맷; 맷; 맷; ) HANGUL SYLLABLE MAES
+B9F8;B9F8;1106 1162 11BB;B9F8;1106 1162 11BB; # (맸; 맸; 맸; 맸; 맸; ) HANGUL SYLLABLE MAESS
+B9F9;B9F9;1106 1162 11BC;B9F9;1106 1162 11BC; # (맹; 맹; 맹; 맹; 맹; ) HANGUL SYLLABLE MAENG
+B9FA;B9FA;1106 1162 11BD;B9FA;1106 1162 11BD; # (맺; 맺; 맺; 맺; 맺; ) HANGUL SYLLABLE MAEJ
+B9FB;B9FB;1106 1162 11BE;B9FB;1106 1162 11BE; # (맻; 맻; 맻; 맻; 맻; ) HANGUL SYLLABLE MAEC
+B9FC;B9FC;1106 1162 11BF;B9FC;1106 1162 11BF; # (맼; 맼; 맼; 맼; 맼; ) HANGUL SYLLABLE MAEK
+B9FD;B9FD;1106 1162 11C0;B9FD;1106 1162 11C0; # (맽; 맽; 맽; 맽; 맽; ) HANGUL SYLLABLE MAET
+B9FE;B9FE;1106 1162 11C1;B9FE;1106 1162 11C1; # (맾; 맾; 맾; 맾; 맾; ) HANGUL SYLLABLE MAEP
+B9FF;B9FF;1106 1162 11C2;B9FF;1106 1162 11C2; # (맿; 맿; 맿; 맿; 맿; ) HANGUL SYLLABLE MAEH
+BA00;BA00;1106 1163;BA00;1106 1163; # (먀; 먀; 먀; 먀; 먀; ) HANGUL SYLLABLE MYA
+BA01;BA01;1106 1163 11A8;BA01;1106 1163 11A8; # (먁; 먁; 먁; 먁; 먁; ) HANGUL SYLLABLE MYAG
+BA02;BA02;1106 1163 11A9;BA02;1106 1163 11A9; # (먂; 먂; 먂; 먂; 먂; ) HANGUL SYLLABLE MYAGG
+BA03;BA03;1106 1163 11AA;BA03;1106 1163 11AA; # (먃; 먃; 먃; 먃; 먃; ) HANGUL SYLLABLE MYAGS
+BA04;BA04;1106 1163 11AB;BA04;1106 1163 11AB; # (먄; 먄; 먄; 먄; 먄; ) HANGUL SYLLABLE MYAN
+BA05;BA05;1106 1163 11AC;BA05;1106 1163 11AC; # (먅; 먅; 먅; 먅; 먅; ) HANGUL SYLLABLE MYANJ
+BA06;BA06;1106 1163 11AD;BA06;1106 1163 11AD; # (먆; 먆; 먆; 먆; 먆; ) HANGUL SYLLABLE MYANH
+BA07;BA07;1106 1163 11AE;BA07;1106 1163 11AE; # (먇; 먇; 먇; 먇; 먇; ) HANGUL SYLLABLE MYAD
+BA08;BA08;1106 1163 11AF;BA08;1106 1163 11AF; # (먈; 먈; 먈; 먈; 먈; ) HANGUL SYLLABLE MYAL
+BA09;BA09;1106 1163 11B0;BA09;1106 1163 11B0; # (먉; 먉; 먉; 먉; 먉; ) HANGUL SYLLABLE MYALG
+BA0A;BA0A;1106 1163 11B1;BA0A;1106 1163 11B1; # (먊; 먊; 먊; 먊; 먊; ) HANGUL SYLLABLE MYALM
+BA0B;BA0B;1106 1163 11B2;BA0B;1106 1163 11B2; # (먋; 먋; 먋; 먋; 먋; ) HANGUL SYLLABLE MYALB
+BA0C;BA0C;1106 1163 11B3;BA0C;1106 1163 11B3; # (먌; 먌; 먌; 먌; 먌; ) HANGUL SYLLABLE MYALS
+BA0D;BA0D;1106 1163 11B4;BA0D;1106 1163 11B4; # (먍; 먍; 먍; 먍; 먍; ) HANGUL SYLLABLE MYALT
+BA0E;BA0E;1106 1163 11B5;BA0E;1106 1163 11B5; # (먎; 먎; 먎; 먎; 먎; ) HANGUL SYLLABLE MYALP
+BA0F;BA0F;1106 1163 11B6;BA0F;1106 1163 11B6; # (먏; 먏; 먏; 먏; 먏; ) HANGUL SYLLABLE MYALH
+BA10;BA10;1106 1163 11B7;BA10;1106 1163 11B7; # (먐; 먐; 먐; 먐; 먐; ) HANGUL SYLLABLE MYAM
+BA11;BA11;1106 1163 11B8;BA11;1106 1163 11B8; # (먑; 먑; 먑; 먑; 먑; ) HANGUL SYLLABLE MYAB
+BA12;BA12;1106 1163 11B9;BA12;1106 1163 11B9; # (먒; 먒; 먒; 먒; 먒; ) HANGUL SYLLABLE MYABS
+BA13;BA13;1106 1163 11BA;BA13;1106 1163 11BA; # (먓; 먓; 먓; 먓; 먓; ) HANGUL SYLLABLE MYAS
+BA14;BA14;1106 1163 11BB;BA14;1106 1163 11BB; # (먔; 먔; 먔; 먔; 먔; ) HANGUL SYLLABLE MYASS
+BA15;BA15;1106 1163 11BC;BA15;1106 1163 11BC; # (먕; 먕; 먕; 먕; 먕; ) HANGUL SYLLABLE MYANG
+BA16;BA16;1106 1163 11BD;BA16;1106 1163 11BD; # (먖; 먖; 먖; 먖; 먖; ) HANGUL SYLLABLE MYAJ
+BA17;BA17;1106 1163 11BE;BA17;1106 1163 11BE; # (먗; 먗; 먗; 먗; 먗; ) HANGUL SYLLABLE MYAC
+BA18;BA18;1106 1163 11BF;BA18;1106 1163 11BF; # (먘; 먘; 먘; 먘; 먘; ) HANGUL SYLLABLE MYAK
+BA19;BA19;1106 1163 11C0;BA19;1106 1163 11C0; # (먙; 먙; 먙; 먙; 먙; ) HANGUL SYLLABLE MYAT
+BA1A;BA1A;1106 1163 11C1;BA1A;1106 1163 11C1; # (먚; 먚; 먚; 먚; 먚; ) HANGUL SYLLABLE MYAP
+BA1B;BA1B;1106 1163 11C2;BA1B;1106 1163 11C2; # (먛; 먛; 먛; 먛; 먛; ) HANGUL SYLLABLE MYAH
+BA1C;BA1C;1106 1164;BA1C;1106 1164; # (먜; 먜; 먜; 먜; 먜; ) HANGUL SYLLABLE MYAE
+BA1D;BA1D;1106 1164 11A8;BA1D;1106 1164 11A8; # (먝; 먝; 먝; 먝; 먝; ) HANGUL SYLLABLE MYAEG
+BA1E;BA1E;1106 1164 11A9;BA1E;1106 1164 11A9; # (먞; 먞; 먞; 먞; 먞; ) HANGUL SYLLABLE MYAEGG
+BA1F;BA1F;1106 1164 11AA;BA1F;1106 1164 11AA; # (먟; 먟; 먟; 먟; 먟; ) HANGUL SYLLABLE MYAEGS
+BA20;BA20;1106 1164 11AB;BA20;1106 1164 11AB; # (먠; 먠; 먠; 먠; 먠; ) HANGUL SYLLABLE MYAEN
+BA21;BA21;1106 1164 11AC;BA21;1106 1164 11AC; # (먡; 먡; 먡; 먡; 먡; ) HANGUL SYLLABLE MYAENJ
+BA22;BA22;1106 1164 11AD;BA22;1106 1164 11AD; # (먢; 먢; 먢; 먢; 먢; ) HANGUL SYLLABLE MYAENH
+BA23;BA23;1106 1164 11AE;BA23;1106 1164 11AE; # (먣; 먣; 먣; 먣; 먣; ) HANGUL SYLLABLE MYAED
+BA24;BA24;1106 1164 11AF;BA24;1106 1164 11AF; # (먤; 먤; 먤; 먤; 먤; ) HANGUL SYLLABLE MYAEL
+BA25;BA25;1106 1164 11B0;BA25;1106 1164 11B0; # (먥; 먥; 먥; 먥; 먥; ) HANGUL SYLLABLE MYAELG
+BA26;BA26;1106 1164 11B1;BA26;1106 1164 11B1; # (먦; 먦; 먦; 먦; 먦; ) HANGUL SYLLABLE MYAELM
+BA27;BA27;1106 1164 11B2;BA27;1106 1164 11B2; # (먧; 먧; 먧; 먧; 먧; ) HANGUL SYLLABLE MYAELB
+BA28;BA28;1106 1164 11B3;BA28;1106 1164 11B3; # (먨; 먨; 먨; 먨; 먨; ) HANGUL SYLLABLE MYAELS
+BA29;BA29;1106 1164 11B4;BA29;1106 1164 11B4; # (먩; 먩; 먩; 먩; 먩; ) HANGUL SYLLABLE MYAELT
+BA2A;BA2A;1106 1164 11B5;BA2A;1106 1164 11B5; # (먪; 먪; 먪; 먪; 먪; ) HANGUL SYLLABLE MYAELP
+BA2B;BA2B;1106 1164 11B6;BA2B;1106 1164 11B6; # (먫; 먫; 먫; 먫; 먫; ) HANGUL SYLLABLE MYAELH
+BA2C;BA2C;1106 1164 11B7;BA2C;1106 1164 11B7; # (먬; 먬; 먬; 먬; 먬; ) HANGUL SYLLABLE MYAEM
+BA2D;BA2D;1106 1164 11B8;BA2D;1106 1164 11B8; # (먭; 먭; 먭; 먭; 먭; ) HANGUL SYLLABLE MYAEB
+BA2E;BA2E;1106 1164 11B9;BA2E;1106 1164 11B9; # (먮; 먮; 먮; 먮; 먮; ) HANGUL SYLLABLE MYAEBS
+BA2F;BA2F;1106 1164 11BA;BA2F;1106 1164 11BA; # (먯; 먯; 먯; 먯; 먯; ) HANGUL SYLLABLE MYAES
+BA30;BA30;1106 1164 11BB;BA30;1106 1164 11BB; # (먰; 먰; 먰; 먰; 먰; ) HANGUL SYLLABLE MYAESS
+BA31;BA31;1106 1164 11BC;BA31;1106 1164 11BC; # (먱; 먱; 먱; 먱; 먱; ) HANGUL SYLLABLE MYAENG
+BA32;BA32;1106 1164 11BD;BA32;1106 1164 11BD; # (먲; 먲; 먲; 먲; 먲; ) HANGUL SYLLABLE MYAEJ
+BA33;BA33;1106 1164 11BE;BA33;1106 1164 11BE; # (먳; 먳; 먳; 먳; 먳; ) HANGUL SYLLABLE MYAEC
+BA34;BA34;1106 1164 11BF;BA34;1106 1164 11BF; # (먴; 먴; 먴; 먴; 먴; ) HANGUL SYLLABLE MYAEK
+BA35;BA35;1106 1164 11C0;BA35;1106 1164 11C0; # (먵; 먵; 먵; 먵; 먵; ) HANGUL SYLLABLE MYAET
+BA36;BA36;1106 1164 11C1;BA36;1106 1164 11C1; # (먶; 먶; 먶; 먶; 먶; ) HANGUL SYLLABLE MYAEP
+BA37;BA37;1106 1164 11C2;BA37;1106 1164 11C2; # (먷; 먷; 먷; 먷; 먷; ) HANGUL SYLLABLE MYAEH
+BA38;BA38;1106 1165;BA38;1106 1165; # (머; 머; 머; 머; 머; ) HANGUL SYLLABLE MEO
+BA39;BA39;1106 1165 11A8;BA39;1106 1165 11A8; # (먹; 먹; 먹; 먹; 먹; ) HANGUL SYLLABLE MEOG
+BA3A;BA3A;1106 1165 11A9;BA3A;1106 1165 11A9; # (먺; 먺; 먺; 먺; 먺; ) HANGUL SYLLABLE MEOGG
+BA3B;BA3B;1106 1165 11AA;BA3B;1106 1165 11AA; # (먻; 먻; 먻; 먻; 먻; ) HANGUL SYLLABLE MEOGS
+BA3C;BA3C;1106 1165 11AB;BA3C;1106 1165 11AB; # (먼; 먼; 먼; 먼; 먼; ) HANGUL SYLLABLE MEON
+BA3D;BA3D;1106 1165 11AC;BA3D;1106 1165 11AC; # (먽; 먽; 먽; 먽; 먽; ) HANGUL SYLLABLE MEONJ
+BA3E;BA3E;1106 1165 11AD;BA3E;1106 1165 11AD; # (먾; 먾; 먾; 먾; 먾; ) HANGUL SYLLABLE MEONH
+BA3F;BA3F;1106 1165 11AE;BA3F;1106 1165 11AE; # (먿; 먿; 먿; 먿; 먿; ) HANGUL SYLLABLE MEOD
+BA40;BA40;1106 1165 11AF;BA40;1106 1165 11AF; # (멀; 멀; 멀; 멀; 멀; ) HANGUL SYLLABLE MEOL
+BA41;BA41;1106 1165 11B0;BA41;1106 1165 11B0; # (멁; 멁; 멁; 멁; 멁; ) HANGUL SYLLABLE MEOLG
+BA42;BA42;1106 1165 11B1;BA42;1106 1165 11B1; # (멂; 멂; 멂; 멂; 멂; ) HANGUL SYLLABLE MEOLM
+BA43;BA43;1106 1165 11B2;BA43;1106 1165 11B2; # (멃; 멃; 멃; 멃; 멃; ) HANGUL SYLLABLE MEOLB
+BA44;BA44;1106 1165 11B3;BA44;1106 1165 11B3; # (멄; 멄; 멄; 멄; 멄; ) HANGUL SYLLABLE MEOLS
+BA45;BA45;1106 1165 11B4;BA45;1106 1165 11B4; # (멅; 멅; 멅; 멅; 멅; ) HANGUL SYLLABLE MEOLT
+BA46;BA46;1106 1165 11B5;BA46;1106 1165 11B5; # (멆; 멆; 멆; 멆; 멆; ) HANGUL SYLLABLE MEOLP
+BA47;BA47;1106 1165 11B6;BA47;1106 1165 11B6; # (멇; 멇; 멇; 멇; 멇; ) HANGUL SYLLABLE MEOLH
+BA48;BA48;1106 1165 11B7;BA48;1106 1165 11B7; # (멈; 멈; 멈; 멈; 멈; ) HANGUL SYLLABLE MEOM
+BA49;BA49;1106 1165 11B8;BA49;1106 1165 11B8; # (멉; 멉; 멉; 멉; 멉; ) HANGUL SYLLABLE MEOB
+BA4A;BA4A;1106 1165 11B9;BA4A;1106 1165 11B9; # (멊; 멊; 멊; 멊; 멊; ) HANGUL SYLLABLE MEOBS
+BA4B;BA4B;1106 1165 11BA;BA4B;1106 1165 11BA; # (멋; 멋; 멋; 멋; 멋; ) HANGUL SYLLABLE MEOS
+BA4C;BA4C;1106 1165 11BB;BA4C;1106 1165 11BB; # (멌; 멌; 멌; 멌; 멌; ) HANGUL SYLLABLE MEOSS
+BA4D;BA4D;1106 1165 11BC;BA4D;1106 1165 11BC; # (멍; 멍; 멍; 멍; 멍; ) HANGUL SYLLABLE MEONG
+BA4E;BA4E;1106 1165 11BD;BA4E;1106 1165 11BD; # (멎; 멎; 멎; 멎; 멎; ) HANGUL SYLLABLE MEOJ
+BA4F;BA4F;1106 1165 11BE;BA4F;1106 1165 11BE; # (멏; 멏; 멏; 멏; 멏; ) HANGUL SYLLABLE MEOC
+BA50;BA50;1106 1165 11BF;BA50;1106 1165 11BF; # (멐; 멐; 멐; 멐; 멐; ) HANGUL SYLLABLE MEOK
+BA51;BA51;1106 1165 11C0;BA51;1106 1165 11C0; # (멑; 멑; 멑; 멑; 멑; ) HANGUL SYLLABLE MEOT
+BA52;BA52;1106 1165 11C1;BA52;1106 1165 11C1; # (멒; 멒; 멒; 멒; 멒; ) HANGUL SYLLABLE MEOP
+BA53;BA53;1106 1165 11C2;BA53;1106 1165 11C2; # (멓; 멓; 멓; 멓; 멓; ) HANGUL SYLLABLE MEOH
+BA54;BA54;1106 1166;BA54;1106 1166; # (메; 메; 메; 메; 메; ) HANGUL SYLLABLE ME
+BA55;BA55;1106 1166 11A8;BA55;1106 1166 11A8; # (멕; 멕; 멕; 멕; 멕; ) HANGUL SYLLABLE MEG
+BA56;BA56;1106 1166 11A9;BA56;1106 1166 11A9; # (멖; 멖; 멖; 멖; 멖; ) HANGUL SYLLABLE MEGG
+BA57;BA57;1106 1166 11AA;BA57;1106 1166 11AA; # (멗; 멗; 멗; 멗; 멗; ) HANGUL SYLLABLE MEGS
+BA58;BA58;1106 1166 11AB;BA58;1106 1166 11AB; # (멘; 멘; 멘; 멘; 멘; ) HANGUL SYLLABLE MEN
+BA59;BA59;1106 1166 11AC;BA59;1106 1166 11AC; # (멙; 멙; 멙; 멙; 멙; ) HANGUL SYLLABLE MENJ
+BA5A;BA5A;1106 1166 11AD;BA5A;1106 1166 11AD; # (멚; 멚; 멚; 멚; 멚; ) HANGUL SYLLABLE MENH
+BA5B;BA5B;1106 1166 11AE;BA5B;1106 1166 11AE; # (멛; 멛; 멛; 멛; 멛; ) HANGUL SYLLABLE MED
+BA5C;BA5C;1106 1166 11AF;BA5C;1106 1166 11AF; # (멜; 멜; 멜; 멜; 멜; ) HANGUL SYLLABLE MEL
+BA5D;BA5D;1106 1166 11B0;BA5D;1106 1166 11B0; # (멝; 멝; 멝; 멝; 멝; ) HANGUL SYLLABLE MELG
+BA5E;BA5E;1106 1166 11B1;BA5E;1106 1166 11B1; # (멞; 멞; 멞; 멞; 멞; ) HANGUL SYLLABLE MELM
+BA5F;BA5F;1106 1166 11B2;BA5F;1106 1166 11B2; # (멟; 멟; 멟; 멟; 멟; ) HANGUL SYLLABLE MELB
+BA60;BA60;1106 1166 11B3;BA60;1106 1166 11B3; # (멠; 멠; 멠; 멠; 멠; ) HANGUL SYLLABLE MELS
+BA61;BA61;1106 1166 11B4;BA61;1106 1166 11B4; # (멡; 멡; 멡; 멡; 멡; ) HANGUL SYLLABLE MELT
+BA62;BA62;1106 1166 11B5;BA62;1106 1166 11B5; # (멢; 멢; 멢; 멢; 멢; ) HANGUL SYLLABLE MELP
+BA63;BA63;1106 1166 11B6;BA63;1106 1166 11B6; # (멣; 멣; 멣; 멣; 멣; ) HANGUL SYLLABLE MELH
+BA64;BA64;1106 1166 11B7;BA64;1106 1166 11B7; # (멤; 멤; 멤; 멤; 멤; ) HANGUL SYLLABLE MEM
+BA65;BA65;1106 1166 11B8;BA65;1106 1166 11B8; # (멥; 멥; 멥; 멥; 멥; ) HANGUL SYLLABLE MEB
+BA66;BA66;1106 1166 11B9;BA66;1106 1166 11B9; # (멦; 멦; 멦; 멦; 멦; ) HANGUL SYLLABLE MEBS
+BA67;BA67;1106 1166 11BA;BA67;1106 1166 11BA; # (멧; 멧; 멧; 멧; 멧; ) HANGUL SYLLABLE MES
+BA68;BA68;1106 1166 11BB;BA68;1106 1166 11BB; # (멨; 멨; 멨; 멨; 멨; ) HANGUL SYLLABLE MESS
+BA69;BA69;1106 1166 11BC;BA69;1106 1166 11BC; # (멩; 멩; 멩; 멩; 멩; ) HANGUL SYLLABLE MENG
+BA6A;BA6A;1106 1166 11BD;BA6A;1106 1166 11BD; # (멪; 멪; 멪; 멪; 멪; ) HANGUL SYLLABLE MEJ
+BA6B;BA6B;1106 1166 11BE;BA6B;1106 1166 11BE; # (멫; 멫; 멫; 멫; 멫; ) HANGUL SYLLABLE MEC
+BA6C;BA6C;1106 1166 11BF;BA6C;1106 1166 11BF; # (멬; 멬; 멬; 멬; 멬; ) HANGUL SYLLABLE MEK
+BA6D;BA6D;1106 1166 11C0;BA6D;1106 1166 11C0; # (멭; 멭; 멭; 멭; 멭; ) HANGUL SYLLABLE MET
+BA6E;BA6E;1106 1166 11C1;BA6E;1106 1166 11C1; # (멮; 멮; 멮; 멮; 멮; ) HANGUL SYLLABLE MEP
+BA6F;BA6F;1106 1166 11C2;BA6F;1106 1166 11C2; # (멯; 멯; 멯; 멯; 멯; ) HANGUL SYLLABLE MEH
+BA70;BA70;1106 1167;BA70;1106 1167; # (며; 며; 며; 며; 며; ) HANGUL SYLLABLE MYEO
+BA71;BA71;1106 1167 11A8;BA71;1106 1167 11A8; # (멱; 멱; 멱; 멱; 멱; ) HANGUL SYLLABLE MYEOG
+BA72;BA72;1106 1167 11A9;BA72;1106 1167 11A9; # (멲; 멲; 멲; 멲; 멲; ) HANGUL SYLLABLE MYEOGG
+BA73;BA73;1106 1167 11AA;BA73;1106 1167 11AA; # (멳; 멳; 멳; 멳; 멳; ) HANGUL SYLLABLE MYEOGS
+BA74;BA74;1106 1167 11AB;BA74;1106 1167 11AB; # (면; 면; 면; 면; 면; ) HANGUL SYLLABLE MYEON
+BA75;BA75;1106 1167 11AC;BA75;1106 1167 11AC; # (멵; 멵; 멵; 멵; 멵; ) HANGUL SYLLABLE MYEONJ
+BA76;BA76;1106 1167 11AD;BA76;1106 1167 11AD; # (멶; 멶; 멶; 멶; 멶; ) HANGUL SYLLABLE MYEONH
+BA77;BA77;1106 1167 11AE;BA77;1106 1167 11AE; # (멷; 멷; 멷; 멷; 멷; ) HANGUL SYLLABLE MYEOD
+BA78;BA78;1106 1167 11AF;BA78;1106 1167 11AF; # (멸; 멸; 멸; 멸; 멸; ) HANGUL SYLLABLE MYEOL
+BA79;BA79;1106 1167 11B0;BA79;1106 1167 11B0; # (멹; 멹; 멹; 멹; 멹; ) HANGUL SYLLABLE MYEOLG
+BA7A;BA7A;1106 1167 11B1;BA7A;1106 1167 11B1; # (멺; 멺; 멺; 멺; 멺; ) HANGUL SYLLABLE MYEOLM
+BA7B;BA7B;1106 1167 11B2;BA7B;1106 1167 11B2; # (멻; 멻; 멻; 멻; 멻; ) HANGUL SYLLABLE MYEOLB
+BA7C;BA7C;1106 1167 11B3;BA7C;1106 1167 11B3; # (멼; 멼; 멼; 멼; 멼; ) HANGUL SYLLABLE MYEOLS
+BA7D;BA7D;1106 1167 11B4;BA7D;1106 1167 11B4; # (멽; 멽; 멽; 멽; 멽; ) HANGUL SYLLABLE MYEOLT
+BA7E;BA7E;1106 1167 11B5;BA7E;1106 1167 11B5; # (멾; 멾; 멾; 멾; 멾; ) HANGUL SYLLABLE MYEOLP
+BA7F;BA7F;1106 1167 11B6;BA7F;1106 1167 11B6; # (멿; 멿; 멿; 멿; 멿; ) HANGUL SYLLABLE MYEOLH
+BA80;BA80;1106 1167 11B7;BA80;1106 1167 11B7; # (몀; 몀; 몀; 몀; 몀; ) HANGUL SYLLABLE MYEOM
+BA81;BA81;1106 1167 11B8;BA81;1106 1167 11B8; # (몁; 몁; 몁; 몁; 몁; ) HANGUL SYLLABLE MYEOB
+BA82;BA82;1106 1167 11B9;BA82;1106 1167 11B9; # (몂; 몂; 몂; 몂; 몂; ) HANGUL SYLLABLE MYEOBS
+BA83;BA83;1106 1167 11BA;BA83;1106 1167 11BA; # (몃; 몃; 몃; 몃; 몃; ) HANGUL SYLLABLE MYEOS
+BA84;BA84;1106 1167 11BB;BA84;1106 1167 11BB; # (몄; 몄; 몄; 몄; 몄; ) HANGUL SYLLABLE MYEOSS
+BA85;BA85;1106 1167 11BC;BA85;1106 1167 11BC; # (명; 명; 명; 명; 명; ) HANGUL SYLLABLE MYEONG
+BA86;BA86;1106 1167 11BD;BA86;1106 1167 11BD; # (몆; 몆; 몆; 몆; 몆; ) HANGUL SYLLABLE MYEOJ
+BA87;BA87;1106 1167 11BE;BA87;1106 1167 11BE; # (몇; 몇; 몇; 몇; 몇; ) HANGUL SYLLABLE MYEOC
+BA88;BA88;1106 1167 11BF;BA88;1106 1167 11BF; # (몈; 몈; 몈; 몈; 몈; ) HANGUL SYLLABLE MYEOK
+BA89;BA89;1106 1167 11C0;BA89;1106 1167 11C0; # (몉; 몉; 몉; 몉; 몉; ) HANGUL SYLLABLE MYEOT
+BA8A;BA8A;1106 1167 11C1;BA8A;1106 1167 11C1; # (몊; 몊; 몊; 몊; 몊; ) HANGUL SYLLABLE MYEOP
+BA8B;BA8B;1106 1167 11C2;BA8B;1106 1167 11C2; # (몋; 몋; 몋; 몋; 몋; ) HANGUL SYLLABLE MYEOH
+BA8C;BA8C;1106 1168;BA8C;1106 1168; # (몌; 몌; 몌; 몌; 몌; ) HANGUL SYLLABLE MYE
+BA8D;BA8D;1106 1168 11A8;BA8D;1106 1168 11A8; # (몍; 몍; 몍; 몍; 몍; ) HANGUL SYLLABLE MYEG
+BA8E;BA8E;1106 1168 11A9;BA8E;1106 1168 11A9; # (몎; 몎; 몎; 몎; 몎; ) HANGUL SYLLABLE MYEGG
+BA8F;BA8F;1106 1168 11AA;BA8F;1106 1168 11AA; # (몏; 몏; 몏; 몏; 몏; ) HANGUL SYLLABLE MYEGS
+BA90;BA90;1106 1168 11AB;BA90;1106 1168 11AB; # (몐; 몐; 몐; 몐; 몐; ) HANGUL SYLLABLE MYEN
+BA91;BA91;1106 1168 11AC;BA91;1106 1168 11AC; # (몑; 몑; 몑; 몑; 몑; ) HANGUL SYLLABLE MYENJ
+BA92;BA92;1106 1168 11AD;BA92;1106 1168 11AD; # (몒; 몒; 몒; 몒; 몒; ) HANGUL SYLLABLE MYENH
+BA93;BA93;1106 1168 11AE;BA93;1106 1168 11AE; # (몓; 몓; 몓; 몓; 몓; ) HANGUL SYLLABLE MYED
+BA94;BA94;1106 1168 11AF;BA94;1106 1168 11AF; # (몔; 몔; 몔; 몔; 몔; ) HANGUL SYLLABLE MYEL
+BA95;BA95;1106 1168 11B0;BA95;1106 1168 11B0; # (몕; 몕; 몕; 몕; 몕; ) HANGUL SYLLABLE MYELG
+BA96;BA96;1106 1168 11B1;BA96;1106 1168 11B1; # (몖; 몖; 몖; 몖; 몖; ) HANGUL SYLLABLE MYELM
+BA97;BA97;1106 1168 11B2;BA97;1106 1168 11B2; # (몗; 몗; 몗; 몗; 몗; ) HANGUL SYLLABLE MYELB
+BA98;BA98;1106 1168 11B3;BA98;1106 1168 11B3; # (몘; 몘; 몘; 몘; 몘; ) HANGUL SYLLABLE MYELS
+BA99;BA99;1106 1168 11B4;BA99;1106 1168 11B4; # (몙; 몙; 몙; 몙; 몙; ) HANGUL SYLLABLE MYELT
+BA9A;BA9A;1106 1168 11B5;BA9A;1106 1168 11B5; # (몚; 몚; 몚; 몚; 몚; ) HANGUL SYLLABLE MYELP
+BA9B;BA9B;1106 1168 11B6;BA9B;1106 1168 11B6; # (몛; 몛; 몛; 몛; 몛; ) HANGUL SYLLABLE MYELH
+BA9C;BA9C;1106 1168 11B7;BA9C;1106 1168 11B7; # (몜; 몜; 몜; 몜; 몜; ) HANGUL SYLLABLE MYEM
+BA9D;BA9D;1106 1168 11B8;BA9D;1106 1168 11B8; # (몝; 몝; 몝; 몝; 몝; ) HANGUL SYLLABLE MYEB
+BA9E;BA9E;1106 1168 11B9;BA9E;1106 1168 11B9; # (몞; 몞; 몞; 몞; 몞; ) HANGUL SYLLABLE MYEBS
+BA9F;BA9F;1106 1168 11BA;BA9F;1106 1168 11BA; # (몟; 몟; 몟; 몟; 몟; ) HANGUL SYLLABLE MYES
+BAA0;BAA0;1106 1168 11BB;BAA0;1106 1168 11BB; # (몠; 몠; 몠; 몠; 몠; ) HANGUL SYLLABLE MYESS
+BAA1;BAA1;1106 1168 11BC;BAA1;1106 1168 11BC; # (몡; 몡; 몡; 몡; 몡; ) HANGUL SYLLABLE MYENG
+BAA2;BAA2;1106 1168 11BD;BAA2;1106 1168 11BD; # (몢; 몢; 몢; 몢; 몢; ) HANGUL SYLLABLE MYEJ
+BAA3;BAA3;1106 1168 11BE;BAA3;1106 1168 11BE; # (몣; 몣; 몣; 몣; 몣; ) HANGUL SYLLABLE MYEC
+BAA4;BAA4;1106 1168 11BF;BAA4;1106 1168 11BF; # (몤; 몤; 몤; 몤; 몤; ) HANGUL SYLLABLE MYEK
+BAA5;BAA5;1106 1168 11C0;BAA5;1106 1168 11C0; # (몥; 몥; 몥; 몥; 몥; ) HANGUL SYLLABLE MYET
+BAA6;BAA6;1106 1168 11C1;BAA6;1106 1168 11C1; # (몦; 몦; 몦; 몦; 몦; ) HANGUL SYLLABLE MYEP
+BAA7;BAA7;1106 1168 11C2;BAA7;1106 1168 11C2; # (몧; 몧; 몧; 몧; 몧; ) HANGUL SYLLABLE MYEH
+BAA8;BAA8;1106 1169;BAA8;1106 1169; # (모; 모; 모; 모; 모; ) HANGUL SYLLABLE MO
+BAA9;BAA9;1106 1169 11A8;BAA9;1106 1169 11A8; # (목; 목; 목; 목; 목; ) HANGUL SYLLABLE MOG
+BAAA;BAAA;1106 1169 11A9;BAAA;1106 1169 11A9; # (몪; 몪; 몪; 몪; 몪; ) HANGUL SYLLABLE MOGG
+BAAB;BAAB;1106 1169 11AA;BAAB;1106 1169 11AA; # (몫; 몫; 몫; 몫; 몫; ) HANGUL SYLLABLE MOGS
+BAAC;BAAC;1106 1169 11AB;BAAC;1106 1169 11AB; # (몬; 몬; 몬; 몬; 몬; ) HANGUL SYLLABLE MON
+BAAD;BAAD;1106 1169 11AC;BAAD;1106 1169 11AC; # (몭; 몭; 몭; 몭; 몭; ) HANGUL SYLLABLE MONJ
+BAAE;BAAE;1106 1169 11AD;BAAE;1106 1169 11AD; # (몮; 몮; 몮; 몮; 몮; ) HANGUL SYLLABLE MONH
+BAAF;BAAF;1106 1169 11AE;BAAF;1106 1169 11AE; # (몯; 몯; 몯; 몯; 몯; ) HANGUL SYLLABLE MOD
+BAB0;BAB0;1106 1169 11AF;BAB0;1106 1169 11AF; # (몰; 몰; 몰; 몰; 몰; ) HANGUL SYLLABLE MOL
+BAB1;BAB1;1106 1169 11B0;BAB1;1106 1169 11B0; # (몱; 몱; 몱; 몱; 몱; ) HANGUL SYLLABLE MOLG
+BAB2;BAB2;1106 1169 11B1;BAB2;1106 1169 11B1; # (몲; 몲; 몲; 몲; 몲; ) HANGUL SYLLABLE MOLM
+BAB3;BAB3;1106 1169 11B2;BAB3;1106 1169 11B2; # (몳; 몳; 몳; 몳; 몳; ) HANGUL SYLLABLE MOLB
+BAB4;BAB4;1106 1169 11B3;BAB4;1106 1169 11B3; # (몴; 몴; 몴; 몴; 몴; ) HANGUL SYLLABLE MOLS
+BAB5;BAB5;1106 1169 11B4;BAB5;1106 1169 11B4; # (몵; 몵; 몵; 몵; 몵; ) HANGUL SYLLABLE MOLT
+BAB6;BAB6;1106 1169 11B5;BAB6;1106 1169 11B5; # (몶; 몶; 몶; 몶; 몶; ) HANGUL SYLLABLE MOLP
+BAB7;BAB7;1106 1169 11B6;BAB7;1106 1169 11B6; # (몷; 몷; 몷; 몷; 몷; ) HANGUL SYLLABLE MOLH
+BAB8;BAB8;1106 1169 11B7;BAB8;1106 1169 11B7; # (몸; 몸; 몸; 몸; 몸; ) HANGUL SYLLABLE MOM
+BAB9;BAB9;1106 1169 11B8;BAB9;1106 1169 11B8; # (몹; 몹; 몹; 몹; 몹; ) HANGUL SYLLABLE MOB
+BABA;BABA;1106 1169 11B9;BABA;1106 1169 11B9; # (몺; 몺; 몺; 몺; 몺; ) HANGUL SYLLABLE MOBS
+BABB;BABB;1106 1169 11BA;BABB;1106 1169 11BA; # (못; 못; 못; 못; 못; ) HANGUL SYLLABLE MOS
+BABC;BABC;1106 1169 11BB;BABC;1106 1169 11BB; # (몼; 몼; 몼; 몼; 몼; ) HANGUL SYLLABLE MOSS
+BABD;BABD;1106 1169 11BC;BABD;1106 1169 11BC; # (몽; 몽; 몽; 몽; 몽; ) HANGUL SYLLABLE MONG
+BABE;BABE;1106 1169 11BD;BABE;1106 1169 11BD; # (몾; 몾; 몾; 몾; 몾; ) HANGUL SYLLABLE MOJ
+BABF;BABF;1106 1169 11BE;BABF;1106 1169 11BE; # (몿; 몿; 몿; 몿; 몿; ) HANGUL SYLLABLE MOC
+BAC0;BAC0;1106 1169 11BF;BAC0;1106 1169 11BF; # (뫀; 뫀; 뫀; 뫀; 뫀; ) HANGUL SYLLABLE MOK
+BAC1;BAC1;1106 1169 11C0;BAC1;1106 1169 11C0; # (뫁; 뫁; 뫁; 뫁; 뫁; ) HANGUL SYLLABLE MOT
+BAC2;BAC2;1106 1169 11C1;BAC2;1106 1169 11C1; # (뫂; 뫂; 뫂; 뫂; 뫂; ) HANGUL SYLLABLE MOP
+BAC3;BAC3;1106 1169 11C2;BAC3;1106 1169 11C2; # (뫃; 뫃; 뫃; 뫃; 뫃; ) HANGUL SYLLABLE MOH
+BAC4;BAC4;1106 116A;BAC4;1106 116A; # (뫄; 뫄; 뫄; 뫄; 뫄; ) HANGUL SYLLABLE MWA
+BAC5;BAC5;1106 116A 11A8;BAC5;1106 116A 11A8; # (뫅; 뫅; 뫅; 뫅; 뫅; ) HANGUL SYLLABLE MWAG
+BAC6;BAC6;1106 116A 11A9;BAC6;1106 116A 11A9; # (뫆; 뫆; 뫆; 뫆; 뫆; ) HANGUL SYLLABLE MWAGG
+BAC7;BAC7;1106 116A 11AA;BAC7;1106 116A 11AA; # (뫇; 뫇; 뫇; 뫇; 뫇; ) HANGUL SYLLABLE MWAGS
+BAC8;BAC8;1106 116A 11AB;BAC8;1106 116A 11AB; # (뫈; 뫈; 뫈; 뫈; 뫈; ) HANGUL SYLLABLE MWAN
+BAC9;BAC9;1106 116A 11AC;BAC9;1106 116A 11AC; # (뫉; 뫉; 뫉; 뫉; 뫉; ) HANGUL SYLLABLE MWANJ
+BACA;BACA;1106 116A 11AD;BACA;1106 116A 11AD; # (뫊; 뫊; 뫊; 뫊; 뫊; ) HANGUL SYLLABLE MWANH
+BACB;BACB;1106 116A 11AE;BACB;1106 116A 11AE; # (뫋; 뫋; 뫋; 뫋; 뫋; ) HANGUL SYLLABLE MWAD
+BACC;BACC;1106 116A 11AF;BACC;1106 116A 11AF; # (뫌; 뫌; 뫌; 뫌; 뫌; ) HANGUL SYLLABLE MWAL
+BACD;BACD;1106 116A 11B0;BACD;1106 116A 11B0; # (뫍; 뫍; 뫍; 뫍; 뫍; ) HANGUL SYLLABLE MWALG
+BACE;BACE;1106 116A 11B1;BACE;1106 116A 11B1; # (뫎; 뫎; 뫎; 뫎; 뫎; ) HANGUL SYLLABLE MWALM
+BACF;BACF;1106 116A 11B2;BACF;1106 116A 11B2; # (뫏; 뫏; 뫏; 뫏; 뫏; ) HANGUL SYLLABLE MWALB
+BAD0;BAD0;1106 116A 11B3;BAD0;1106 116A 11B3; # (뫐; 뫐; 뫐; 뫐; 뫐; ) HANGUL SYLLABLE MWALS
+BAD1;BAD1;1106 116A 11B4;BAD1;1106 116A 11B4; # (뫑; 뫑; 뫑; 뫑; 뫑; ) HANGUL SYLLABLE MWALT
+BAD2;BAD2;1106 116A 11B5;BAD2;1106 116A 11B5; # (뫒; 뫒; 뫒; 뫒; 뫒; ) HANGUL SYLLABLE MWALP
+BAD3;BAD3;1106 116A 11B6;BAD3;1106 116A 11B6; # (뫓; 뫓; 뫓; 뫓; 뫓; ) HANGUL SYLLABLE MWALH
+BAD4;BAD4;1106 116A 11B7;BAD4;1106 116A 11B7; # (뫔; 뫔; 뫔; 뫔; 뫔; ) HANGUL SYLLABLE MWAM
+BAD5;BAD5;1106 116A 11B8;BAD5;1106 116A 11B8; # (뫕; 뫕; 뫕; 뫕; 뫕; ) HANGUL SYLLABLE MWAB
+BAD6;BAD6;1106 116A 11B9;BAD6;1106 116A 11B9; # (뫖; 뫖; 뫖; 뫖; 뫖; ) HANGUL SYLLABLE MWABS
+BAD7;BAD7;1106 116A 11BA;BAD7;1106 116A 11BA; # (뫗; 뫗; 뫗; 뫗; 뫗; ) HANGUL SYLLABLE MWAS
+BAD8;BAD8;1106 116A 11BB;BAD8;1106 116A 11BB; # (뫘; 뫘; 뫘; 뫘; 뫘; ) HANGUL SYLLABLE MWASS
+BAD9;BAD9;1106 116A 11BC;BAD9;1106 116A 11BC; # (뫙; 뫙; 뫙; 뫙; 뫙; ) HANGUL SYLLABLE MWANG
+BADA;BADA;1106 116A 11BD;BADA;1106 116A 11BD; # (뫚; 뫚; 뫚; 뫚; 뫚; ) HANGUL SYLLABLE MWAJ
+BADB;BADB;1106 116A 11BE;BADB;1106 116A 11BE; # (뫛; 뫛; 뫛; 뫛; 뫛; ) HANGUL SYLLABLE MWAC
+BADC;BADC;1106 116A 11BF;BADC;1106 116A 11BF; # (뫜; 뫜; 뫜; 뫜; 뫜; ) HANGUL SYLLABLE MWAK
+BADD;BADD;1106 116A 11C0;BADD;1106 116A 11C0; # (뫝; 뫝; 뫝; 뫝; 뫝; ) HANGUL SYLLABLE MWAT
+BADE;BADE;1106 116A 11C1;BADE;1106 116A 11C1; # (뫞; 뫞; 뫞; 뫞; 뫞; ) HANGUL SYLLABLE MWAP
+BADF;BADF;1106 116A 11C2;BADF;1106 116A 11C2; # (뫟; 뫟; 뫟; 뫟; 뫟; ) HANGUL SYLLABLE MWAH
+BAE0;BAE0;1106 116B;BAE0;1106 116B; # (뫠; 뫠; 뫠; 뫠; 뫠; ) HANGUL SYLLABLE MWAE
+BAE1;BAE1;1106 116B 11A8;BAE1;1106 116B 11A8; # (뫡; 뫡; 뫡; 뫡; 뫡; ) HANGUL SYLLABLE MWAEG
+BAE2;BAE2;1106 116B 11A9;BAE2;1106 116B 11A9; # (뫢; 뫢; 뫢; 뫢; 뫢; ) HANGUL SYLLABLE MWAEGG
+BAE3;BAE3;1106 116B 11AA;BAE3;1106 116B 11AA; # (뫣; 뫣; 뫣; 뫣; 뫣; ) HANGUL SYLLABLE MWAEGS
+BAE4;BAE4;1106 116B 11AB;BAE4;1106 116B 11AB; # (뫤; 뫤; 뫤; 뫤; 뫤; ) HANGUL SYLLABLE MWAEN
+BAE5;BAE5;1106 116B 11AC;BAE5;1106 116B 11AC; # (뫥; 뫥; 뫥; 뫥; 뫥; ) HANGUL SYLLABLE MWAENJ
+BAE6;BAE6;1106 116B 11AD;BAE6;1106 116B 11AD; # (뫦; 뫦; 뫦; 뫦; 뫦; ) HANGUL SYLLABLE MWAENH
+BAE7;BAE7;1106 116B 11AE;BAE7;1106 116B 11AE; # (뫧; 뫧; 뫧; 뫧; 뫧; ) HANGUL SYLLABLE MWAED
+BAE8;BAE8;1106 116B 11AF;BAE8;1106 116B 11AF; # (뫨; 뫨; 뫨; 뫨; 뫨; ) HANGUL SYLLABLE MWAEL
+BAE9;BAE9;1106 116B 11B0;BAE9;1106 116B 11B0; # (뫩; 뫩; 뫩; 뫩; 뫩; ) HANGUL SYLLABLE MWAELG
+BAEA;BAEA;1106 116B 11B1;BAEA;1106 116B 11B1; # (뫪; 뫪; 뫪; 뫪; 뫪; ) HANGUL SYLLABLE MWAELM
+BAEB;BAEB;1106 116B 11B2;BAEB;1106 116B 11B2; # (뫫; 뫫; 뫫; 뫫; 뫫; ) HANGUL SYLLABLE MWAELB
+BAEC;BAEC;1106 116B 11B3;BAEC;1106 116B 11B3; # (뫬; 뫬; 뫬; 뫬; 뫬; ) HANGUL SYLLABLE MWAELS
+BAED;BAED;1106 116B 11B4;BAED;1106 116B 11B4; # (뫭; 뫭; 뫭; 뫭; 뫭; ) HANGUL SYLLABLE MWAELT
+BAEE;BAEE;1106 116B 11B5;BAEE;1106 116B 11B5; # (뫮; 뫮; 뫮; 뫮; 뫮; ) HANGUL SYLLABLE MWAELP
+BAEF;BAEF;1106 116B 11B6;BAEF;1106 116B 11B6; # (뫯; 뫯; 뫯; 뫯; 뫯; ) HANGUL SYLLABLE MWAELH
+BAF0;BAF0;1106 116B 11B7;BAF0;1106 116B 11B7; # (뫰; 뫰; 뫰; 뫰; 뫰; ) HANGUL SYLLABLE MWAEM
+BAF1;BAF1;1106 116B 11B8;BAF1;1106 116B 11B8; # (뫱; 뫱; 뫱; 뫱; 뫱; ) HANGUL SYLLABLE MWAEB
+BAF2;BAF2;1106 116B 11B9;BAF2;1106 116B 11B9; # (뫲; 뫲; 뫲; 뫲; 뫲; ) HANGUL SYLLABLE MWAEBS
+BAF3;BAF3;1106 116B 11BA;BAF3;1106 116B 11BA; # (뫳; 뫳; 뫳; 뫳; 뫳; ) HANGUL SYLLABLE MWAES
+BAF4;BAF4;1106 116B 11BB;BAF4;1106 116B 11BB; # (뫴; 뫴; 뫴; 뫴; 뫴; ) HANGUL SYLLABLE MWAESS
+BAF5;BAF5;1106 116B 11BC;BAF5;1106 116B 11BC; # (뫵; 뫵; 뫵; 뫵; 뫵; ) HANGUL SYLLABLE MWAENG
+BAF6;BAF6;1106 116B 11BD;BAF6;1106 116B 11BD; # (뫶; 뫶; 뫶; 뫶; 뫶; ) HANGUL SYLLABLE MWAEJ
+BAF7;BAF7;1106 116B 11BE;BAF7;1106 116B 11BE; # (뫷; 뫷; 뫷; 뫷; 뫷; ) HANGUL SYLLABLE MWAEC
+BAF8;BAF8;1106 116B 11BF;BAF8;1106 116B 11BF; # (뫸; 뫸; 뫸; 뫸; 뫸; ) HANGUL SYLLABLE MWAEK
+BAF9;BAF9;1106 116B 11C0;BAF9;1106 116B 11C0; # (뫹; 뫹; 뫹; 뫹; 뫹; ) HANGUL SYLLABLE MWAET
+BAFA;BAFA;1106 116B 11C1;BAFA;1106 116B 11C1; # (뫺; 뫺; 뫺; 뫺; 뫺; ) HANGUL SYLLABLE MWAEP
+BAFB;BAFB;1106 116B 11C2;BAFB;1106 116B 11C2; # (뫻; 뫻; 뫻; 뫻; 뫻; ) HANGUL SYLLABLE MWAEH
+BAFC;BAFC;1106 116C;BAFC;1106 116C; # (뫼; 뫼; 뫼; 뫼; 뫼; ) HANGUL SYLLABLE MOE
+BAFD;BAFD;1106 116C 11A8;BAFD;1106 116C 11A8; # (뫽; 뫽; 뫽; 뫽; 뫽; ) HANGUL SYLLABLE MOEG
+BAFE;BAFE;1106 116C 11A9;BAFE;1106 116C 11A9; # (뫾; 뫾; 뫾; 뫾; 뫾; ) HANGUL SYLLABLE MOEGG
+BAFF;BAFF;1106 116C 11AA;BAFF;1106 116C 11AA; # (뫿; 뫿; 뫿; 뫿; 뫿; ) HANGUL SYLLABLE MOEGS
+BB00;BB00;1106 116C 11AB;BB00;1106 116C 11AB; # (묀; 묀; 묀; 묀; 묀; ) HANGUL SYLLABLE MOEN
+BB01;BB01;1106 116C 11AC;BB01;1106 116C 11AC; # (묁; 묁; 묁; 묁; 묁; ) HANGUL SYLLABLE MOENJ
+BB02;BB02;1106 116C 11AD;BB02;1106 116C 11AD; # (묂; 묂; 묂; 묂; 묂; ) HANGUL SYLLABLE MOENH
+BB03;BB03;1106 116C 11AE;BB03;1106 116C 11AE; # (묃; 묃; 묃; 묃; 묃; ) HANGUL SYLLABLE MOED
+BB04;BB04;1106 116C 11AF;BB04;1106 116C 11AF; # (묄; 묄; 묄; 묄; 묄; ) HANGUL SYLLABLE MOEL
+BB05;BB05;1106 116C 11B0;BB05;1106 116C 11B0; # (묅; 묅; 묅; 묅; 묅; ) HANGUL SYLLABLE MOELG
+BB06;BB06;1106 116C 11B1;BB06;1106 116C 11B1; # (묆; 묆; 묆; 묆; 묆; ) HANGUL SYLLABLE MOELM
+BB07;BB07;1106 116C 11B2;BB07;1106 116C 11B2; # (묇; 묇; 묇; 묇; 묇; ) HANGUL SYLLABLE MOELB
+BB08;BB08;1106 116C 11B3;BB08;1106 116C 11B3; # (묈; 묈; 묈; 묈; 묈; ) HANGUL SYLLABLE MOELS
+BB09;BB09;1106 116C 11B4;BB09;1106 116C 11B4; # (묉; 묉; 묉; 묉; 묉; ) HANGUL SYLLABLE MOELT
+BB0A;BB0A;1106 116C 11B5;BB0A;1106 116C 11B5; # (묊; 묊; 묊; 묊; 묊; ) HANGUL SYLLABLE MOELP
+BB0B;BB0B;1106 116C 11B6;BB0B;1106 116C 11B6; # (묋; 묋; 묋; 묋; 묋; ) HANGUL SYLLABLE MOELH
+BB0C;BB0C;1106 116C 11B7;BB0C;1106 116C 11B7; # (묌; 묌; 묌; 묌; 묌; ) HANGUL SYLLABLE MOEM
+BB0D;BB0D;1106 116C 11B8;BB0D;1106 116C 11B8; # (묍; 묍; 묍; 묍; 묍; ) HANGUL SYLLABLE MOEB
+BB0E;BB0E;1106 116C 11B9;BB0E;1106 116C 11B9; # (묎; 묎; 묎; 묎; 묎; ) HANGUL SYLLABLE MOEBS
+BB0F;BB0F;1106 116C 11BA;BB0F;1106 116C 11BA; # (묏; 묏; 묏; 묏; 묏; ) HANGUL SYLLABLE MOES
+BB10;BB10;1106 116C 11BB;BB10;1106 116C 11BB; # (묐; 묐; 묐; 묐; 묐; ) HANGUL SYLLABLE MOESS
+BB11;BB11;1106 116C 11BC;BB11;1106 116C 11BC; # (묑; 묑; 묑; 묑; 묑; ) HANGUL SYLLABLE MOENG
+BB12;BB12;1106 116C 11BD;BB12;1106 116C 11BD; # (묒; 묒; 묒; 묒; 묒; ) HANGUL SYLLABLE MOEJ
+BB13;BB13;1106 116C 11BE;BB13;1106 116C 11BE; # (묓; 묓; 묓; 묓; 묓; ) HANGUL SYLLABLE MOEC
+BB14;BB14;1106 116C 11BF;BB14;1106 116C 11BF; # (묔; 묔; 묔; 묔; 묔; ) HANGUL SYLLABLE MOEK
+BB15;BB15;1106 116C 11C0;BB15;1106 116C 11C0; # (묕; 묕; 묕; 묕; 묕; ) HANGUL SYLLABLE MOET
+BB16;BB16;1106 116C 11C1;BB16;1106 116C 11C1; # (묖; 묖; 묖; 묖; 묖; ) HANGUL SYLLABLE MOEP
+BB17;BB17;1106 116C 11C2;BB17;1106 116C 11C2; # (묗; 묗; 묗; 묗; 묗; ) HANGUL SYLLABLE MOEH
+BB18;BB18;1106 116D;BB18;1106 116D; # (묘; 묘; 묘; 묘; 묘; ) HANGUL SYLLABLE MYO
+BB19;BB19;1106 116D 11A8;BB19;1106 116D 11A8; # (묙; 묙; 묙; 묙; 묙; ) HANGUL SYLLABLE MYOG
+BB1A;BB1A;1106 116D 11A9;BB1A;1106 116D 11A9; # (묚; 묚; 묚; 묚; 묚; ) HANGUL SYLLABLE MYOGG
+BB1B;BB1B;1106 116D 11AA;BB1B;1106 116D 11AA; # (묛; 묛; 묛; 묛; 묛; ) HANGUL SYLLABLE MYOGS
+BB1C;BB1C;1106 116D 11AB;BB1C;1106 116D 11AB; # (묜; 묜; 묜; 묜; 묜; ) HANGUL SYLLABLE MYON
+BB1D;BB1D;1106 116D 11AC;BB1D;1106 116D 11AC; # (묝; 묝; 묝; 묝; 묝; ) HANGUL SYLLABLE MYONJ
+BB1E;BB1E;1106 116D 11AD;BB1E;1106 116D 11AD; # (묞; 묞; 묞; 묞; 묞; ) HANGUL SYLLABLE MYONH
+BB1F;BB1F;1106 116D 11AE;BB1F;1106 116D 11AE; # (묟; 묟; 묟; 묟; 묟; ) HANGUL SYLLABLE MYOD
+BB20;BB20;1106 116D 11AF;BB20;1106 116D 11AF; # (묠; 묠; 묠; 묠; 묠; ) HANGUL SYLLABLE MYOL
+BB21;BB21;1106 116D 11B0;BB21;1106 116D 11B0; # (묡; 묡; 묡; 묡; 묡; ) HANGUL SYLLABLE MYOLG
+BB22;BB22;1106 116D 11B1;BB22;1106 116D 11B1; # (묢; 묢; 묢; 묢; 묢; ) HANGUL SYLLABLE MYOLM
+BB23;BB23;1106 116D 11B2;BB23;1106 116D 11B2; # (묣; 묣; 묣; 묣; 묣; ) HANGUL SYLLABLE MYOLB
+BB24;BB24;1106 116D 11B3;BB24;1106 116D 11B3; # (묤; 묤; 묤; 묤; 묤; ) HANGUL SYLLABLE MYOLS
+BB25;BB25;1106 116D 11B4;BB25;1106 116D 11B4; # (묥; 묥; 묥; 묥; 묥; ) HANGUL SYLLABLE MYOLT
+BB26;BB26;1106 116D 11B5;BB26;1106 116D 11B5; # (묦; 묦; 묦; 묦; 묦; ) HANGUL SYLLABLE MYOLP
+BB27;BB27;1106 116D 11B6;BB27;1106 116D 11B6; # (묧; 묧; 묧; 묧; 묧; ) HANGUL SYLLABLE MYOLH
+BB28;BB28;1106 116D 11B7;BB28;1106 116D 11B7; # (묨; 묨; 묨; 묨; 묨; ) HANGUL SYLLABLE MYOM
+BB29;BB29;1106 116D 11B8;BB29;1106 116D 11B8; # (묩; 묩; 묩; 묩; 묩; ) HANGUL SYLLABLE MYOB
+BB2A;BB2A;1106 116D 11B9;BB2A;1106 116D 11B9; # (묪; 묪; 묪; 묪; 묪; ) HANGUL SYLLABLE MYOBS
+BB2B;BB2B;1106 116D 11BA;BB2B;1106 116D 11BA; # (묫; 묫; 묫; 묫; 묫; ) HANGUL SYLLABLE MYOS
+BB2C;BB2C;1106 116D 11BB;BB2C;1106 116D 11BB; # (묬; 묬; 묬; 묬; 묬; ) HANGUL SYLLABLE MYOSS
+BB2D;BB2D;1106 116D 11BC;BB2D;1106 116D 11BC; # (묭; 묭; 묭; 묭; 묭; ) HANGUL SYLLABLE MYONG
+BB2E;BB2E;1106 116D 11BD;BB2E;1106 116D 11BD; # (묮; 묮; 묮; 묮; 묮; ) HANGUL SYLLABLE MYOJ
+BB2F;BB2F;1106 116D 11BE;BB2F;1106 116D 11BE; # (묯; 묯; 묯; 묯; 묯; ) HANGUL SYLLABLE MYOC
+BB30;BB30;1106 116D 11BF;BB30;1106 116D 11BF; # (묰; 묰; 묰; 묰; 묰; ) HANGUL SYLLABLE MYOK
+BB31;BB31;1106 116D 11C0;BB31;1106 116D 11C0; # (묱; 묱; 묱; 묱; 묱; ) HANGUL SYLLABLE MYOT
+BB32;BB32;1106 116D 11C1;BB32;1106 116D 11C1; # (묲; 묲; 묲; 묲; 묲; ) HANGUL SYLLABLE MYOP
+BB33;BB33;1106 116D 11C2;BB33;1106 116D 11C2; # (묳; 묳; 묳; 묳; 묳; ) HANGUL SYLLABLE MYOH
+BB34;BB34;1106 116E;BB34;1106 116E; # (무; 무; 무; 무; 무; ) HANGUL SYLLABLE MU
+BB35;BB35;1106 116E 11A8;BB35;1106 116E 11A8; # (묵; 묵; 묵; 묵; 묵; ) HANGUL SYLLABLE MUG
+BB36;BB36;1106 116E 11A9;BB36;1106 116E 11A9; # (묶; 묶; 묶; 묶; 묶; ) HANGUL SYLLABLE MUGG
+BB37;BB37;1106 116E 11AA;BB37;1106 116E 11AA; # (묷; 묷; 묷; 묷; 묷; ) HANGUL SYLLABLE MUGS
+BB38;BB38;1106 116E 11AB;BB38;1106 116E 11AB; # (문; 문; 문; 문; 문; ) HANGUL SYLLABLE MUN
+BB39;BB39;1106 116E 11AC;BB39;1106 116E 11AC; # (묹; 묹; 묹; 묹; 묹; ) HANGUL SYLLABLE MUNJ
+BB3A;BB3A;1106 116E 11AD;BB3A;1106 116E 11AD; # (묺; 묺; 묺; 묺; 묺; ) HANGUL SYLLABLE MUNH
+BB3B;BB3B;1106 116E 11AE;BB3B;1106 116E 11AE; # (묻; 묻; 묻; 묻; 묻; ) HANGUL SYLLABLE MUD
+BB3C;BB3C;1106 116E 11AF;BB3C;1106 116E 11AF; # (물; 물; 물; 물; 물; ) HANGUL SYLLABLE MUL
+BB3D;BB3D;1106 116E 11B0;BB3D;1106 116E 11B0; # (묽; 묽; 묽; 묽; 묽; ) HANGUL SYLLABLE MULG
+BB3E;BB3E;1106 116E 11B1;BB3E;1106 116E 11B1; # (묾; 묾; 묾; 묾; 묾; ) HANGUL SYLLABLE MULM
+BB3F;BB3F;1106 116E 11B2;BB3F;1106 116E 11B2; # (묿; 묿; 묿; 묿; 묿; ) HANGUL SYLLABLE MULB
+BB40;BB40;1106 116E 11B3;BB40;1106 116E 11B3; # (뭀; 뭀; 뭀; 뭀; 뭀; ) HANGUL SYLLABLE MULS
+BB41;BB41;1106 116E 11B4;BB41;1106 116E 11B4; # (뭁; 뭁; 뭁; 뭁; 뭁; ) HANGUL SYLLABLE MULT
+BB42;BB42;1106 116E 11B5;BB42;1106 116E 11B5; # (뭂; 뭂; 뭂; 뭂; 뭂; ) HANGUL SYLLABLE MULP
+BB43;BB43;1106 116E 11B6;BB43;1106 116E 11B6; # (뭃; 뭃; 뭃; 뭃; 뭃; ) HANGUL SYLLABLE MULH
+BB44;BB44;1106 116E 11B7;BB44;1106 116E 11B7; # (뭄; 뭄; 뭄; 뭄; 뭄; ) HANGUL SYLLABLE MUM
+BB45;BB45;1106 116E 11B8;BB45;1106 116E 11B8; # (뭅; 뭅; 뭅; 뭅; 뭅; ) HANGUL SYLLABLE MUB
+BB46;BB46;1106 116E 11B9;BB46;1106 116E 11B9; # (뭆; 뭆; 뭆; 뭆; 뭆; ) HANGUL SYLLABLE MUBS
+BB47;BB47;1106 116E 11BA;BB47;1106 116E 11BA; # (뭇; 뭇; 뭇; 뭇; 뭇; ) HANGUL SYLLABLE MUS
+BB48;BB48;1106 116E 11BB;BB48;1106 116E 11BB; # (뭈; 뭈; 뭈; 뭈; 뭈; ) HANGUL SYLLABLE MUSS
+BB49;BB49;1106 116E 11BC;BB49;1106 116E 11BC; # (뭉; 뭉; 뭉; 뭉; 뭉; ) HANGUL SYLLABLE MUNG
+BB4A;BB4A;1106 116E 11BD;BB4A;1106 116E 11BD; # (뭊; 뭊; 뭊; 뭊; 뭊; ) HANGUL SYLLABLE MUJ
+BB4B;BB4B;1106 116E 11BE;BB4B;1106 116E 11BE; # (뭋; 뭋; 뭋; 뭋; 뭋; ) HANGUL SYLLABLE MUC
+BB4C;BB4C;1106 116E 11BF;BB4C;1106 116E 11BF; # (뭌; 뭌; 뭌; 뭌; 뭌; ) HANGUL SYLLABLE MUK
+BB4D;BB4D;1106 116E 11C0;BB4D;1106 116E 11C0; # (뭍; 뭍; 뭍; 뭍; 뭍; ) HANGUL SYLLABLE MUT
+BB4E;BB4E;1106 116E 11C1;BB4E;1106 116E 11C1; # (뭎; 뭎; 뭎; 뭎; 뭎; ) HANGUL SYLLABLE MUP
+BB4F;BB4F;1106 116E 11C2;BB4F;1106 116E 11C2; # (뭏; 뭏; 뭏; 뭏; 뭏; ) HANGUL SYLLABLE MUH
+BB50;BB50;1106 116F;BB50;1106 116F; # (뭐; 뭐; 뭐; 뭐; 뭐; ) HANGUL SYLLABLE MWEO
+BB51;BB51;1106 116F 11A8;BB51;1106 116F 11A8; # (뭑; 뭑; 뭑; 뭑; 뭑; ) HANGUL SYLLABLE MWEOG
+BB52;BB52;1106 116F 11A9;BB52;1106 116F 11A9; # (뭒; 뭒; 뭒; 뭒; 뭒; ) HANGUL SYLLABLE MWEOGG
+BB53;BB53;1106 116F 11AA;BB53;1106 116F 11AA; # (뭓; 뭓; 뭓; 뭓; 뭓; ) HANGUL SYLLABLE MWEOGS
+BB54;BB54;1106 116F 11AB;BB54;1106 116F 11AB; # (뭔; 뭔; 뭔; 뭔; 뭔; ) HANGUL SYLLABLE MWEON
+BB55;BB55;1106 116F 11AC;BB55;1106 116F 11AC; # (뭕; 뭕; 뭕; 뭕; 뭕; ) HANGUL SYLLABLE MWEONJ
+BB56;BB56;1106 116F 11AD;BB56;1106 116F 11AD; # (뭖; 뭖; 뭖; 뭖; 뭖; ) HANGUL SYLLABLE MWEONH
+BB57;BB57;1106 116F 11AE;BB57;1106 116F 11AE; # (뭗; 뭗; 뭗; 뭗; 뭗; ) HANGUL SYLLABLE MWEOD
+BB58;BB58;1106 116F 11AF;BB58;1106 116F 11AF; # (뭘; 뭘; 뭘; 뭘; 뭘; ) HANGUL SYLLABLE MWEOL
+BB59;BB59;1106 116F 11B0;BB59;1106 116F 11B0; # (뭙; 뭙; 뭙; 뭙; 뭙; ) HANGUL SYLLABLE MWEOLG
+BB5A;BB5A;1106 116F 11B1;BB5A;1106 116F 11B1; # (뭚; 뭚; 뭚; 뭚; 뭚; ) HANGUL SYLLABLE MWEOLM
+BB5B;BB5B;1106 116F 11B2;BB5B;1106 116F 11B2; # (뭛; 뭛; 뭛; 뭛; 뭛; ) HANGUL SYLLABLE MWEOLB
+BB5C;BB5C;1106 116F 11B3;BB5C;1106 116F 11B3; # (뭜; 뭜; 뭜; 뭜; 뭜; ) HANGUL SYLLABLE MWEOLS
+BB5D;BB5D;1106 116F 11B4;BB5D;1106 116F 11B4; # (뭝; 뭝; 뭝; 뭝; 뭝; ) HANGUL SYLLABLE MWEOLT
+BB5E;BB5E;1106 116F 11B5;BB5E;1106 116F 11B5; # (뭞; 뭞; 뭞; 뭞; 뭞; ) HANGUL SYLLABLE MWEOLP
+BB5F;BB5F;1106 116F 11B6;BB5F;1106 116F 11B6; # (뭟; 뭟; 뭟; 뭟; 뭟; ) HANGUL SYLLABLE MWEOLH
+BB60;BB60;1106 116F 11B7;BB60;1106 116F 11B7; # (뭠; 뭠; 뭠; 뭠; 뭠; ) HANGUL SYLLABLE MWEOM
+BB61;BB61;1106 116F 11B8;BB61;1106 116F 11B8; # (뭡; 뭡; 뭡; 뭡; 뭡; ) HANGUL SYLLABLE MWEOB
+BB62;BB62;1106 116F 11B9;BB62;1106 116F 11B9; # (뭢; 뭢; 뭢; 뭢; 뭢; ) HANGUL SYLLABLE MWEOBS
+BB63;BB63;1106 116F 11BA;BB63;1106 116F 11BA; # (뭣; 뭣; 뭣; 뭣; 뭣; ) HANGUL SYLLABLE MWEOS
+BB64;BB64;1106 116F 11BB;BB64;1106 116F 11BB; # (뭤; 뭤; 뭤; 뭤; 뭤; ) HANGUL SYLLABLE MWEOSS
+BB65;BB65;1106 116F 11BC;BB65;1106 116F 11BC; # (뭥; 뭥; 뭥; 뭥; 뭥; ) HANGUL SYLLABLE MWEONG
+BB66;BB66;1106 116F 11BD;BB66;1106 116F 11BD; # (뭦; 뭦; 뭦; 뭦; 뭦; ) HANGUL SYLLABLE MWEOJ
+BB67;BB67;1106 116F 11BE;BB67;1106 116F 11BE; # (뭧; 뭧; 뭧; 뭧; 뭧; ) HANGUL SYLLABLE MWEOC
+BB68;BB68;1106 116F 11BF;BB68;1106 116F 11BF; # (뭨; 뭨; 뭨; 뭨; 뭨; ) HANGUL SYLLABLE MWEOK
+BB69;BB69;1106 116F 11C0;BB69;1106 116F 11C0; # (뭩; 뭩; 뭩; 뭩; 뭩; ) HANGUL SYLLABLE MWEOT
+BB6A;BB6A;1106 116F 11C1;BB6A;1106 116F 11C1; # (뭪; 뭪; 뭪; 뭪; 뭪; ) HANGUL SYLLABLE MWEOP
+BB6B;BB6B;1106 116F 11C2;BB6B;1106 116F 11C2; # (뭫; 뭫; 뭫; 뭫; 뭫; ) HANGUL SYLLABLE MWEOH
+BB6C;BB6C;1106 1170;BB6C;1106 1170; # (뭬; 뭬; 뭬; 뭬; 뭬; ) HANGUL SYLLABLE MWE
+BB6D;BB6D;1106 1170 11A8;BB6D;1106 1170 11A8; # (뭭; 뭭; 뭭; 뭭; 뭭; ) HANGUL SYLLABLE MWEG
+BB6E;BB6E;1106 1170 11A9;BB6E;1106 1170 11A9; # (뭮; 뭮; 뭮; 뭮; 뭮; ) HANGUL SYLLABLE MWEGG
+BB6F;BB6F;1106 1170 11AA;BB6F;1106 1170 11AA; # (뭯; 뭯; 뭯; 뭯; 뭯; ) HANGUL SYLLABLE MWEGS
+BB70;BB70;1106 1170 11AB;BB70;1106 1170 11AB; # (뭰; 뭰; 뭰; 뭰; 뭰; ) HANGUL SYLLABLE MWEN
+BB71;BB71;1106 1170 11AC;BB71;1106 1170 11AC; # (뭱; 뭱; 뭱; 뭱; 뭱; ) HANGUL SYLLABLE MWENJ
+BB72;BB72;1106 1170 11AD;BB72;1106 1170 11AD; # (뭲; 뭲; 뭲; 뭲; 뭲; ) HANGUL SYLLABLE MWENH
+BB73;BB73;1106 1170 11AE;BB73;1106 1170 11AE; # (뭳; 뭳; 뭳; 뭳; 뭳; ) HANGUL SYLLABLE MWED
+BB74;BB74;1106 1170 11AF;BB74;1106 1170 11AF; # (뭴; 뭴; 뭴; 뭴; 뭴; ) HANGUL SYLLABLE MWEL
+BB75;BB75;1106 1170 11B0;BB75;1106 1170 11B0; # (뭵; 뭵; 뭵; 뭵; 뭵; ) HANGUL SYLLABLE MWELG
+BB76;BB76;1106 1170 11B1;BB76;1106 1170 11B1; # (뭶; 뭶; 뭶; 뭶; 뭶; ) HANGUL SYLLABLE MWELM
+BB77;BB77;1106 1170 11B2;BB77;1106 1170 11B2; # (뭷; 뭷; 뭷; 뭷; 뭷; ) HANGUL SYLLABLE MWELB
+BB78;BB78;1106 1170 11B3;BB78;1106 1170 11B3; # (뭸; 뭸; 뭸; 뭸; 뭸; ) HANGUL SYLLABLE MWELS
+BB79;BB79;1106 1170 11B4;BB79;1106 1170 11B4; # (뭹; 뭹; 뭹; 뭹; 뭹; ) HANGUL SYLLABLE MWELT
+BB7A;BB7A;1106 1170 11B5;BB7A;1106 1170 11B5; # (뭺; 뭺; 뭺; 뭺; 뭺; ) HANGUL SYLLABLE MWELP
+BB7B;BB7B;1106 1170 11B6;BB7B;1106 1170 11B6; # (뭻; 뭻; 뭻; 뭻; 뭻; ) HANGUL SYLLABLE MWELH
+BB7C;BB7C;1106 1170 11B7;BB7C;1106 1170 11B7; # (뭼; 뭼; 뭼; 뭼; 뭼; ) HANGUL SYLLABLE MWEM
+BB7D;BB7D;1106 1170 11B8;BB7D;1106 1170 11B8; # (뭽; 뭽; 뭽; 뭽; 뭽; ) HANGUL SYLLABLE MWEB
+BB7E;BB7E;1106 1170 11B9;BB7E;1106 1170 11B9; # (뭾; 뭾; 뭾; 뭾; 뭾; ) HANGUL SYLLABLE MWEBS
+BB7F;BB7F;1106 1170 11BA;BB7F;1106 1170 11BA; # (뭿; 뭿; 뭿; 뭿; 뭿; ) HANGUL SYLLABLE MWES
+BB80;BB80;1106 1170 11BB;BB80;1106 1170 11BB; # (뮀; 뮀; 뮀; 뮀; 뮀; ) HANGUL SYLLABLE MWESS
+BB81;BB81;1106 1170 11BC;BB81;1106 1170 11BC; # (뮁; 뮁; 뮁; 뮁; 뮁; ) HANGUL SYLLABLE MWENG
+BB82;BB82;1106 1170 11BD;BB82;1106 1170 11BD; # (뮂; 뮂; 뮂; 뮂; 뮂; ) HANGUL SYLLABLE MWEJ
+BB83;BB83;1106 1170 11BE;BB83;1106 1170 11BE; # (뮃; 뮃; 뮃; 뮃; 뮃; ) HANGUL SYLLABLE MWEC
+BB84;BB84;1106 1170 11BF;BB84;1106 1170 11BF; # (뮄; 뮄; 뮄; 뮄; 뮄; ) HANGUL SYLLABLE MWEK
+BB85;BB85;1106 1170 11C0;BB85;1106 1170 11C0; # (뮅; 뮅; 뮅; 뮅; 뮅; ) HANGUL SYLLABLE MWET
+BB86;BB86;1106 1170 11C1;BB86;1106 1170 11C1; # (뮆; 뮆; 뮆; 뮆; 뮆; ) HANGUL SYLLABLE MWEP
+BB87;BB87;1106 1170 11C2;BB87;1106 1170 11C2; # (뮇; 뮇; 뮇; 뮇; 뮇; ) HANGUL SYLLABLE MWEH
+BB88;BB88;1106 1171;BB88;1106 1171; # (뮈; 뮈; 뮈; 뮈; 뮈; ) HANGUL SYLLABLE MWI
+BB89;BB89;1106 1171 11A8;BB89;1106 1171 11A8; # (뮉; 뮉; 뮉; 뮉; 뮉; ) HANGUL SYLLABLE MWIG
+BB8A;BB8A;1106 1171 11A9;BB8A;1106 1171 11A9; # (뮊; 뮊; 뮊; 뮊; 뮊; ) HANGUL SYLLABLE MWIGG
+BB8B;BB8B;1106 1171 11AA;BB8B;1106 1171 11AA; # (뮋; 뮋; 뮋; 뮋; 뮋; ) HANGUL SYLLABLE MWIGS
+BB8C;BB8C;1106 1171 11AB;BB8C;1106 1171 11AB; # (뮌; 뮌; 뮌; 뮌; 뮌; ) HANGUL SYLLABLE MWIN
+BB8D;BB8D;1106 1171 11AC;BB8D;1106 1171 11AC; # (뮍; 뮍; 뮍; 뮍; 뮍; ) HANGUL SYLLABLE MWINJ
+BB8E;BB8E;1106 1171 11AD;BB8E;1106 1171 11AD; # (뮎; 뮎; 뮎; 뮎; 뮎; ) HANGUL SYLLABLE MWINH
+BB8F;BB8F;1106 1171 11AE;BB8F;1106 1171 11AE; # (뮏; 뮏; 뮏; 뮏; 뮏; ) HANGUL SYLLABLE MWID
+BB90;BB90;1106 1171 11AF;BB90;1106 1171 11AF; # (뮐; 뮐; 뮐; 뮐; 뮐; ) HANGUL SYLLABLE MWIL
+BB91;BB91;1106 1171 11B0;BB91;1106 1171 11B0; # (뮑; 뮑; 뮑; 뮑; 뮑; ) HANGUL SYLLABLE MWILG
+BB92;BB92;1106 1171 11B1;BB92;1106 1171 11B1; # (뮒; 뮒; 뮒; 뮒; 뮒; ) HANGUL SYLLABLE MWILM
+BB93;BB93;1106 1171 11B2;BB93;1106 1171 11B2; # (뮓; 뮓; 뮓; 뮓; 뮓; ) HANGUL SYLLABLE MWILB
+BB94;BB94;1106 1171 11B3;BB94;1106 1171 11B3; # (뮔; 뮔; 뮔; 뮔; 뮔; ) HANGUL SYLLABLE MWILS
+BB95;BB95;1106 1171 11B4;BB95;1106 1171 11B4; # (뮕; 뮕; 뮕; 뮕; 뮕; ) HANGUL SYLLABLE MWILT
+BB96;BB96;1106 1171 11B5;BB96;1106 1171 11B5; # (뮖; 뮖; 뮖; 뮖; 뮖; ) HANGUL SYLLABLE MWILP
+BB97;BB97;1106 1171 11B6;BB97;1106 1171 11B6; # (뮗; 뮗; 뮗; 뮗; 뮗; ) HANGUL SYLLABLE MWILH
+BB98;BB98;1106 1171 11B7;BB98;1106 1171 11B7; # (뮘; 뮘; 뮘; 뮘; 뮘; ) HANGUL SYLLABLE MWIM
+BB99;BB99;1106 1171 11B8;BB99;1106 1171 11B8; # (뮙; 뮙; 뮙; 뮙; 뮙; ) HANGUL SYLLABLE MWIB
+BB9A;BB9A;1106 1171 11B9;BB9A;1106 1171 11B9; # (뮚; 뮚; 뮚; 뮚; 뮚; ) HANGUL SYLLABLE MWIBS
+BB9B;BB9B;1106 1171 11BA;BB9B;1106 1171 11BA; # (뮛; 뮛; 뮛; 뮛; 뮛; ) HANGUL SYLLABLE MWIS
+BB9C;BB9C;1106 1171 11BB;BB9C;1106 1171 11BB; # (뮜; 뮜; 뮜; 뮜; 뮜; ) HANGUL SYLLABLE MWISS
+BB9D;BB9D;1106 1171 11BC;BB9D;1106 1171 11BC; # (뮝; 뮝; 뮝; 뮝; 뮝; ) HANGUL SYLLABLE MWING
+BB9E;BB9E;1106 1171 11BD;BB9E;1106 1171 11BD; # (뮞; 뮞; 뮞; 뮞; 뮞; ) HANGUL SYLLABLE MWIJ
+BB9F;BB9F;1106 1171 11BE;BB9F;1106 1171 11BE; # (뮟; 뮟; 뮟; 뮟; 뮟; ) HANGUL SYLLABLE MWIC
+BBA0;BBA0;1106 1171 11BF;BBA0;1106 1171 11BF; # (뮠; 뮠; 뮠; 뮠; 뮠; ) HANGUL SYLLABLE MWIK
+BBA1;BBA1;1106 1171 11C0;BBA1;1106 1171 11C0; # (뮡; 뮡; 뮡; 뮡; 뮡; ) HANGUL SYLLABLE MWIT
+BBA2;BBA2;1106 1171 11C1;BBA2;1106 1171 11C1; # (뮢; 뮢; 뮢; 뮢; 뮢; ) HANGUL SYLLABLE MWIP
+BBA3;BBA3;1106 1171 11C2;BBA3;1106 1171 11C2; # (뮣; 뮣; 뮣; 뮣; 뮣; ) HANGUL SYLLABLE MWIH
+BBA4;BBA4;1106 1172;BBA4;1106 1172; # (뮤; 뮤; 뮤; 뮤; 뮤; ) HANGUL SYLLABLE MYU
+BBA5;BBA5;1106 1172 11A8;BBA5;1106 1172 11A8; # (뮥; 뮥; 뮥; 뮥; 뮥; ) HANGUL SYLLABLE MYUG
+BBA6;BBA6;1106 1172 11A9;BBA6;1106 1172 11A9; # (뮦; 뮦; 뮦; 뮦; 뮦; ) HANGUL SYLLABLE MYUGG
+BBA7;BBA7;1106 1172 11AA;BBA7;1106 1172 11AA; # (뮧; 뮧; 뮧; 뮧; 뮧; ) HANGUL SYLLABLE MYUGS
+BBA8;BBA8;1106 1172 11AB;BBA8;1106 1172 11AB; # (뮨; 뮨; 뮨; 뮨; 뮨; ) HANGUL SYLLABLE MYUN
+BBA9;BBA9;1106 1172 11AC;BBA9;1106 1172 11AC; # (뮩; 뮩; 뮩; 뮩; 뮩; ) HANGUL SYLLABLE MYUNJ
+BBAA;BBAA;1106 1172 11AD;BBAA;1106 1172 11AD; # (뮪; 뮪; 뮪; 뮪; 뮪; ) HANGUL SYLLABLE MYUNH
+BBAB;BBAB;1106 1172 11AE;BBAB;1106 1172 11AE; # (뮫; 뮫; 뮫; 뮫; 뮫; ) HANGUL SYLLABLE MYUD
+BBAC;BBAC;1106 1172 11AF;BBAC;1106 1172 11AF; # (뮬; 뮬; 뮬; 뮬; 뮬; ) HANGUL SYLLABLE MYUL
+BBAD;BBAD;1106 1172 11B0;BBAD;1106 1172 11B0; # (뮭; 뮭; 뮭; 뮭; 뮭; ) HANGUL SYLLABLE MYULG
+BBAE;BBAE;1106 1172 11B1;BBAE;1106 1172 11B1; # (뮮; 뮮; 뮮; 뮮; 뮮; ) HANGUL SYLLABLE MYULM
+BBAF;BBAF;1106 1172 11B2;BBAF;1106 1172 11B2; # (뮯; 뮯; 뮯; 뮯; 뮯; ) HANGUL SYLLABLE MYULB
+BBB0;BBB0;1106 1172 11B3;BBB0;1106 1172 11B3; # (뮰; 뮰; 뮰; 뮰; 뮰; ) HANGUL SYLLABLE MYULS
+BBB1;BBB1;1106 1172 11B4;BBB1;1106 1172 11B4; # (뮱; 뮱; 뮱; 뮱; 뮱; ) HANGUL SYLLABLE MYULT
+BBB2;BBB2;1106 1172 11B5;BBB2;1106 1172 11B5; # (뮲; 뮲; 뮲; 뮲; 뮲; ) HANGUL SYLLABLE MYULP
+BBB3;BBB3;1106 1172 11B6;BBB3;1106 1172 11B6; # (뮳; 뮳; 뮳; 뮳; 뮳; ) HANGUL SYLLABLE MYULH
+BBB4;BBB4;1106 1172 11B7;BBB4;1106 1172 11B7; # (뮴; 뮴; 뮴; 뮴; 뮴; ) HANGUL SYLLABLE MYUM
+BBB5;BBB5;1106 1172 11B8;BBB5;1106 1172 11B8; # (뮵; 뮵; 뮵; 뮵; 뮵; ) HANGUL SYLLABLE MYUB
+BBB6;BBB6;1106 1172 11B9;BBB6;1106 1172 11B9; # (뮶; 뮶; 뮶; 뮶; 뮶; ) HANGUL SYLLABLE MYUBS
+BBB7;BBB7;1106 1172 11BA;BBB7;1106 1172 11BA; # (뮷; 뮷; 뮷; 뮷; 뮷; ) HANGUL SYLLABLE MYUS
+BBB8;BBB8;1106 1172 11BB;BBB8;1106 1172 11BB; # (뮸; 뮸; 뮸; 뮸; 뮸; ) HANGUL SYLLABLE MYUSS
+BBB9;BBB9;1106 1172 11BC;BBB9;1106 1172 11BC; # (뮹; 뮹; 뮹; 뮹; 뮹; ) HANGUL SYLLABLE MYUNG
+BBBA;BBBA;1106 1172 11BD;BBBA;1106 1172 11BD; # (뮺; 뮺; 뮺; 뮺; 뮺; ) HANGUL SYLLABLE MYUJ
+BBBB;BBBB;1106 1172 11BE;BBBB;1106 1172 11BE; # (뮻; 뮻; 뮻; 뮻; 뮻; ) HANGUL SYLLABLE MYUC
+BBBC;BBBC;1106 1172 11BF;BBBC;1106 1172 11BF; # (뮼; 뮼; 뮼; 뮼; 뮼; ) HANGUL SYLLABLE MYUK
+BBBD;BBBD;1106 1172 11C0;BBBD;1106 1172 11C0; # (뮽; 뮽; 뮽; 뮽; 뮽; ) HANGUL SYLLABLE MYUT
+BBBE;BBBE;1106 1172 11C1;BBBE;1106 1172 11C1; # (뮾; 뮾; 뮾; 뮾; 뮾; ) HANGUL SYLLABLE MYUP
+BBBF;BBBF;1106 1172 11C2;BBBF;1106 1172 11C2; # (뮿; 뮿; 뮿; 뮿; 뮿; ) HANGUL SYLLABLE MYUH
+BBC0;BBC0;1106 1173;BBC0;1106 1173; # (므; 므; 므; 므; 므; ) HANGUL SYLLABLE MEU
+BBC1;BBC1;1106 1173 11A8;BBC1;1106 1173 11A8; # (믁; 믁; 믁; 믁; 믁; ) HANGUL SYLLABLE MEUG
+BBC2;BBC2;1106 1173 11A9;BBC2;1106 1173 11A9; # (믂; 믂; 믂; 믂; 믂; ) HANGUL SYLLABLE MEUGG
+BBC3;BBC3;1106 1173 11AA;BBC3;1106 1173 11AA; # (믃; 믃; 믃; 믃; 믃; ) HANGUL SYLLABLE MEUGS
+BBC4;BBC4;1106 1173 11AB;BBC4;1106 1173 11AB; # (믄; 믄; 믄; 믄; 믄; ) HANGUL SYLLABLE MEUN
+BBC5;BBC5;1106 1173 11AC;BBC5;1106 1173 11AC; # (믅; 믅; 믅; 믅; 믅; ) HANGUL SYLLABLE MEUNJ
+BBC6;BBC6;1106 1173 11AD;BBC6;1106 1173 11AD; # (믆; 믆; 믆; 믆; 믆; ) HANGUL SYLLABLE MEUNH
+BBC7;BBC7;1106 1173 11AE;BBC7;1106 1173 11AE; # (믇; 믇; 믇; 믇; 믇; ) HANGUL SYLLABLE MEUD
+BBC8;BBC8;1106 1173 11AF;BBC8;1106 1173 11AF; # (믈; 믈; 믈; 믈; 믈; ) HANGUL SYLLABLE MEUL
+BBC9;BBC9;1106 1173 11B0;BBC9;1106 1173 11B0; # (믉; 믉; 믉; 믉; 믉; ) HANGUL SYLLABLE MEULG
+BBCA;BBCA;1106 1173 11B1;BBCA;1106 1173 11B1; # (믊; 믊; 믊; 믊; 믊; ) HANGUL SYLLABLE MEULM
+BBCB;BBCB;1106 1173 11B2;BBCB;1106 1173 11B2; # (믋; 믋; 믋; 믋; 믋; ) HANGUL SYLLABLE MEULB
+BBCC;BBCC;1106 1173 11B3;BBCC;1106 1173 11B3; # (믌; 믌; 믌; 믌; 믌; ) HANGUL SYLLABLE MEULS
+BBCD;BBCD;1106 1173 11B4;BBCD;1106 1173 11B4; # (믍; 믍; 믍; 믍; 믍; ) HANGUL SYLLABLE MEULT
+BBCE;BBCE;1106 1173 11B5;BBCE;1106 1173 11B5; # (믎; 믎; 믎; 믎; 믎; ) HANGUL SYLLABLE MEULP
+BBCF;BBCF;1106 1173 11B6;BBCF;1106 1173 11B6; # (믏; 믏; 믏; 믏; 믏; ) HANGUL SYLLABLE MEULH
+BBD0;BBD0;1106 1173 11B7;BBD0;1106 1173 11B7; # (믐; 믐; 믐; 믐; 믐; ) HANGUL SYLLABLE MEUM
+BBD1;BBD1;1106 1173 11B8;BBD1;1106 1173 11B8; # (믑; 믑; 믑; 믑; 믑; ) HANGUL SYLLABLE MEUB
+BBD2;BBD2;1106 1173 11B9;BBD2;1106 1173 11B9; # (믒; 믒; 믒; 믒; 믒; ) HANGUL SYLLABLE MEUBS
+BBD3;BBD3;1106 1173 11BA;BBD3;1106 1173 11BA; # (믓; 믓; 믓; 믓; 믓; ) HANGUL SYLLABLE MEUS
+BBD4;BBD4;1106 1173 11BB;BBD4;1106 1173 11BB; # (믔; 믔; 믔; 믔; 믔; ) HANGUL SYLLABLE MEUSS
+BBD5;BBD5;1106 1173 11BC;BBD5;1106 1173 11BC; # (믕; 믕; 믕; 믕; 믕; ) HANGUL SYLLABLE MEUNG
+BBD6;BBD6;1106 1173 11BD;BBD6;1106 1173 11BD; # (믖; 믖; 믖; 믖; 믖; ) HANGUL SYLLABLE MEUJ
+BBD7;BBD7;1106 1173 11BE;BBD7;1106 1173 11BE; # (믗; 믗; 믗; 믗; 믗; ) HANGUL SYLLABLE MEUC
+BBD8;BBD8;1106 1173 11BF;BBD8;1106 1173 11BF; # (믘; 믘; 믘; 믘; 믘; ) HANGUL SYLLABLE MEUK
+BBD9;BBD9;1106 1173 11C0;BBD9;1106 1173 11C0; # (믙; 믙; 믙; 믙; 믙; ) HANGUL SYLLABLE MEUT
+BBDA;BBDA;1106 1173 11C1;BBDA;1106 1173 11C1; # (믚; 믚; 믚; 믚; 믚; ) HANGUL SYLLABLE MEUP
+BBDB;BBDB;1106 1173 11C2;BBDB;1106 1173 11C2; # (믛; 믛; 믛; 믛; 믛; ) HANGUL SYLLABLE MEUH
+BBDC;BBDC;1106 1174;BBDC;1106 1174; # (믜; 믜; 믜; 믜; 믜; ) HANGUL SYLLABLE MYI
+BBDD;BBDD;1106 1174 11A8;BBDD;1106 1174 11A8; # (믝; 믝; 믝; 믝; 믝; ) HANGUL SYLLABLE MYIG
+BBDE;BBDE;1106 1174 11A9;BBDE;1106 1174 11A9; # (믞; 믞; 믞; 믞; 믞; ) HANGUL SYLLABLE MYIGG
+BBDF;BBDF;1106 1174 11AA;BBDF;1106 1174 11AA; # (믟; 믟; 믟; 믟; 믟; ) HANGUL SYLLABLE MYIGS
+BBE0;BBE0;1106 1174 11AB;BBE0;1106 1174 11AB; # (믠; 믠; 믠; 믠; 믠; ) HANGUL SYLLABLE MYIN
+BBE1;BBE1;1106 1174 11AC;BBE1;1106 1174 11AC; # (믡; 믡; 믡; 믡; 믡; ) HANGUL SYLLABLE MYINJ
+BBE2;BBE2;1106 1174 11AD;BBE2;1106 1174 11AD; # (믢; 믢; 믢; 믢; 믢; ) HANGUL SYLLABLE MYINH
+BBE3;BBE3;1106 1174 11AE;BBE3;1106 1174 11AE; # (믣; 믣; 믣; 믣; 믣; ) HANGUL SYLLABLE MYID
+BBE4;BBE4;1106 1174 11AF;BBE4;1106 1174 11AF; # (믤; 믤; 믤; 믤; 믤; ) HANGUL SYLLABLE MYIL
+BBE5;BBE5;1106 1174 11B0;BBE5;1106 1174 11B0; # (믥; 믥; 믥; 믥; 믥; ) HANGUL SYLLABLE MYILG
+BBE6;BBE6;1106 1174 11B1;BBE6;1106 1174 11B1; # (믦; 믦; 믦; 믦; 믦; ) HANGUL SYLLABLE MYILM
+BBE7;BBE7;1106 1174 11B2;BBE7;1106 1174 11B2; # (믧; 믧; 믧; 믧; 믧; ) HANGUL SYLLABLE MYILB
+BBE8;BBE8;1106 1174 11B3;BBE8;1106 1174 11B3; # (믨; 믨; 믨; 믨; 믨; ) HANGUL SYLLABLE MYILS
+BBE9;BBE9;1106 1174 11B4;BBE9;1106 1174 11B4; # (믩; 믩; 믩; 믩; 믩; ) HANGUL SYLLABLE MYILT
+BBEA;BBEA;1106 1174 11B5;BBEA;1106 1174 11B5; # (믪; 믪; 믪; 믪; 믪; ) HANGUL SYLLABLE MYILP
+BBEB;BBEB;1106 1174 11B6;BBEB;1106 1174 11B6; # (믫; 믫; 믫; 믫; 믫; ) HANGUL SYLLABLE MYILH
+BBEC;BBEC;1106 1174 11B7;BBEC;1106 1174 11B7; # (믬; 믬; 믬; 믬; 믬; ) HANGUL SYLLABLE MYIM
+BBED;BBED;1106 1174 11B8;BBED;1106 1174 11B8; # (믭; 믭; 믭; 믭; 믭; ) HANGUL SYLLABLE MYIB
+BBEE;BBEE;1106 1174 11B9;BBEE;1106 1174 11B9; # (믮; 믮; 믮; 믮; 믮; ) HANGUL SYLLABLE MYIBS
+BBEF;BBEF;1106 1174 11BA;BBEF;1106 1174 11BA; # (믯; 믯; 믯; 믯; 믯; ) HANGUL SYLLABLE MYIS
+BBF0;BBF0;1106 1174 11BB;BBF0;1106 1174 11BB; # (믰; 믰; 믰; 믰; 믰; ) HANGUL SYLLABLE MYISS
+BBF1;BBF1;1106 1174 11BC;BBF1;1106 1174 11BC; # (믱; 믱; 믱; 믱; 믱; ) HANGUL SYLLABLE MYING
+BBF2;BBF2;1106 1174 11BD;BBF2;1106 1174 11BD; # (믲; 믲; 믲; 믲; 믲; ) HANGUL SYLLABLE MYIJ
+BBF3;BBF3;1106 1174 11BE;BBF3;1106 1174 11BE; # (믳; 믳; 믳; 믳; 믳; ) HANGUL SYLLABLE MYIC
+BBF4;BBF4;1106 1174 11BF;BBF4;1106 1174 11BF; # (믴; 믴; 믴; 믴; 믴; ) HANGUL SYLLABLE MYIK
+BBF5;BBF5;1106 1174 11C0;BBF5;1106 1174 11C0; # (믵; 믵; 믵; 믵; 믵; ) HANGUL SYLLABLE MYIT
+BBF6;BBF6;1106 1174 11C1;BBF6;1106 1174 11C1; # (믶; 믶; 믶; 믶; 믶; ) HANGUL SYLLABLE MYIP
+BBF7;BBF7;1106 1174 11C2;BBF7;1106 1174 11C2; # (믷; 믷; 믷; 믷; 믷; ) HANGUL SYLLABLE MYIH
+BBF8;BBF8;1106 1175;BBF8;1106 1175; # (미; 미; 미; 미; 미; ) HANGUL SYLLABLE MI
+BBF9;BBF9;1106 1175 11A8;BBF9;1106 1175 11A8; # (믹; 믹; 믹; 믹; 믹; ) HANGUL SYLLABLE MIG
+BBFA;BBFA;1106 1175 11A9;BBFA;1106 1175 11A9; # (믺; 믺; 믺; 믺; 믺; ) HANGUL SYLLABLE MIGG
+BBFB;BBFB;1106 1175 11AA;BBFB;1106 1175 11AA; # (믻; 믻; 믻; 믻; 믻; ) HANGUL SYLLABLE MIGS
+BBFC;BBFC;1106 1175 11AB;BBFC;1106 1175 11AB; # (민; 민; 민; 민; 민; ) HANGUL SYLLABLE MIN
+BBFD;BBFD;1106 1175 11AC;BBFD;1106 1175 11AC; # (믽; 믽; 믽; 믽; 믽; ) HANGUL SYLLABLE MINJ
+BBFE;BBFE;1106 1175 11AD;BBFE;1106 1175 11AD; # (믾; 믾; 믾; 믾; 믾; ) HANGUL SYLLABLE MINH
+BBFF;BBFF;1106 1175 11AE;BBFF;1106 1175 11AE; # (믿; 믿; 믿; 믿; 믿; ) HANGUL SYLLABLE MID
+BC00;BC00;1106 1175 11AF;BC00;1106 1175 11AF; # (밀; 밀; 밀; 밀; 밀; ) HANGUL SYLLABLE MIL
+BC01;BC01;1106 1175 11B0;BC01;1106 1175 11B0; # (밁; 밁; 밁; 밁; 밁; ) HANGUL SYLLABLE MILG
+BC02;BC02;1106 1175 11B1;BC02;1106 1175 11B1; # (밂; 밂; 밂; 밂; 밂; ) HANGUL SYLLABLE MILM
+BC03;BC03;1106 1175 11B2;BC03;1106 1175 11B2; # (밃; 밃; 밃; 밃; 밃; ) HANGUL SYLLABLE MILB
+BC04;BC04;1106 1175 11B3;BC04;1106 1175 11B3; # (밄; 밄; 밄; 밄; 밄; ) HANGUL SYLLABLE MILS
+BC05;BC05;1106 1175 11B4;BC05;1106 1175 11B4; # (밅; 밅; 밅; 밅; 밅; ) HANGUL SYLLABLE MILT
+BC06;BC06;1106 1175 11B5;BC06;1106 1175 11B5; # (밆; 밆; 밆; 밆; 밆; ) HANGUL SYLLABLE MILP
+BC07;BC07;1106 1175 11B6;BC07;1106 1175 11B6; # (밇; 밇; 밇; 밇; 밇; ) HANGUL SYLLABLE MILH
+BC08;BC08;1106 1175 11B7;BC08;1106 1175 11B7; # (밈; 밈; 밈; 밈; 밈; ) HANGUL SYLLABLE MIM
+BC09;BC09;1106 1175 11B8;BC09;1106 1175 11B8; # (밉; 밉; 밉; 밉; 밉; ) HANGUL SYLLABLE MIB
+BC0A;BC0A;1106 1175 11B9;BC0A;1106 1175 11B9; # (밊; 밊; 밊; 밊; 밊; ) HANGUL SYLLABLE MIBS
+BC0B;BC0B;1106 1175 11BA;BC0B;1106 1175 11BA; # (밋; 밋; 밋; 밋; 밋; ) HANGUL SYLLABLE MIS
+BC0C;BC0C;1106 1175 11BB;BC0C;1106 1175 11BB; # (밌; 밌; 밌; 밌; 밌; ) HANGUL SYLLABLE MISS
+BC0D;BC0D;1106 1175 11BC;BC0D;1106 1175 11BC; # (밍; 밍; 밍; 밍; 밍; ) HANGUL SYLLABLE MING
+BC0E;BC0E;1106 1175 11BD;BC0E;1106 1175 11BD; # (밎; 밎; 밎; 밎; 밎; ) HANGUL SYLLABLE MIJ
+BC0F;BC0F;1106 1175 11BE;BC0F;1106 1175 11BE; # (및; 및; 및; 및; 및; ) HANGUL SYLLABLE MIC
+BC10;BC10;1106 1175 11BF;BC10;1106 1175 11BF; # (밐; 밐; 밐; 밐; 밐; ) HANGUL SYLLABLE MIK
+BC11;BC11;1106 1175 11C0;BC11;1106 1175 11C0; # (밑; 밑; 밑; 밑; 밑; ) HANGUL SYLLABLE MIT
+BC12;BC12;1106 1175 11C1;BC12;1106 1175 11C1; # (밒; 밒; 밒; 밒; 밒; ) HANGUL SYLLABLE MIP
+BC13;BC13;1106 1175 11C2;BC13;1106 1175 11C2; # (밓; 밓; 밓; 밓; 밓; ) HANGUL SYLLABLE MIH
+BC14;BC14;1107 1161;BC14;1107 1161; # (바; 바; 바; 바; 바; ) HANGUL SYLLABLE BA
+BC15;BC15;1107 1161 11A8;BC15;1107 1161 11A8; # (박; 박; 박; 박; 박; ) HANGUL SYLLABLE BAG
+BC16;BC16;1107 1161 11A9;BC16;1107 1161 11A9; # (밖; 밖; 밖; 밖; 밖; ) HANGUL SYLLABLE BAGG
+BC17;BC17;1107 1161 11AA;BC17;1107 1161 11AA; # (밗; 밗; 밗; 밗; 밗; ) HANGUL SYLLABLE BAGS
+BC18;BC18;1107 1161 11AB;BC18;1107 1161 11AB; # (반; 반; 반; 반; 반; ) HANGUL SYLLABLE BAN
+BC19;BC19;1107 1161 11AC;BC19;1107 1161 11AC; # (밙; 밙; 밙; 밙; 밙; ) HANGUL SYLLABLE BANJ
+BC1A;BC1A;1107 1161 11AD;BC1A;1107 1161 11AD; # (밚; 밚; 밚; 밚; 밚; ) HANGUL SYLLABLE BANH
+BC1B;BC1B;1107 1161 11AE;BC1B;1107 1161 11AE; # (받; 받; 받; 받; 받; ) HANGUL SYLLABLE BAD
+BC1C;BC1C;1107 1161 11AF;BC1C;1107 1161 11AF; # (발; 발; 발; 발; 발; ) HANGUL SYLLABLE BAL
+BC1D;BC1D;1107 1161 11B0;BC1D;1107 1161 11B0; # (밝; 밝; 밝; 밝; 밝; ) HANGUL SYLLABLE BALG
+BC1E;BC1E;1107 1161 11B1;BC1E;1107 1161 11B1; # (밞; 밞; 밞; 밞; 밞; ) HANGUL SYLLABLE BALM
+BC1F;BC1F;1107 1161 11B2;BC1F;1107 1161 11B2; # (밟; 밟; 밟; 밟; 밟; ) HANGUL SYLLABLE BALB
+BC20;BC20;1107 1161 11B3;BC20;1107 1161 11B3; # (밠; 밠; 밠; 밠; 밠; ) HANGUL SYLLABLE BALS
+BC21;BC21;1107 1161 11B4;BC21;1107 1161 11B4; # (밡; 밡; 밡; 밡; 밡; ) HANGUL SYLLABLE BALT
+BC22;BC22;1107 1161 11B5;BC22;1107 1161 11B5; # (밢; 밢; 밢; 밢; 밢; ) HANGUL SYLLABLE BALP
+BC23;BC23;1107 1161 11B6;BC23;1107 1161 11B6; # (밣; 밣; 밣; 밣; 밣; ) HANGUL SYLLABLE BALH
+BC24;BC24;1107 1161 11B7;BC24;1107 1161 11B7; # (밤; 밤; 밤; 밤; 밤; ) HANGUL SYLLABLE BAM
+BC25;BC25;1107 1161 11B8;BC25;1107 1161 11B8; # (밥; 밥; 밥; 밥; 밥; ) HANGUL SYLLABLE BAB
+BC26;BC26;1107 1161 11B9;BC26;1107 1161 11B9; # (밦; 밦; 밦; 밦; 밦; ) HANGUL SYLLABLE BABS
+BC27;BC27;1107 1161 11BA;BC27;1107 1161 11BA; # (밧; 밧; 밧; 밧; 밧; ) HANGUL SYLLABLE BAS
+BC28;BC28;1107 1161 11BB;BC28;1107 1161 11BB; # (밨; 밨; 밨; 밨; 밨; ) HANGUL SYLLABLE BASS
+BC29;BC29;1107 1161 11BC;BC29;1107 1161 11BC; # (방; 방; 방; 방; 방; ) HANGUL SYLLABLE BANG
+BC2A;BC2A;1107 1161 11BD;BC2A;1107 1161 11BD; # (밪; 밪; 밪; 밪; 밪; ) HANGUL SYLLABLE BAJ
+BC2B;BC2B;1107 1161 11BE;BC2B;1107 1161 11BE; # (밫; 밫; 밫; 밫; 밫; ) HANGUL SYLLABLE BAC
+BC2C;BC2C;1107 1161 11BF;BC2C;1107 1161 11BF; # (밬; 밬; 밬; 밬; 밬; ) HANGUL SYLLABLE BAK
+BC2D;BC2D;1107 1161 11C0;BC2D;1107 1161 11C0; # (밭; 밭; 밭; 밭; 밭; ) HANGUL SYLLABLE BAT
+BC2E;BC2E;1107 1161 11C1;BC2E;1107 1161 11C1; # (밮; 밮; 밮; 밮; 밮; ) HANGUL SYLLABLE BAP
+BC2F;BC2F;1107 1161 11C2;BC2F;1107 1161 11C2; # (밯; 밯; 밯; 밯; 밯; ) HANGUL SYLLABLE BAH
+BC30;BC30;1107 1162;BC30;1107 1162; # (배; 배; 배; 배; 배; ) HANGUL SYLLABLE BAE
+BC31;BC31;1107 1162 11A8;BC31;1107 1162 11A8; # (백; 백; 백; 백; 백; ) HANGUL SYLLABLE BAEG
+BC32;BC32;1107 1162 11A9;BC32;1107 1162 11A9; # (밲; 밲; 밲; 밲; 밲; ) HANGUL SYLLABLE BAEGG
+BC33;BC33;1107 1162 11AA;BC33;1107 1162 11AA; # (밳; 밳; 밳; 밳; 밳; ) HANGUL SYLLABLE BAEGS
+BC34;BC34;1107 1162 11AB;BC34;1107 1162 11AB; # (밴; 밴; 밴; 밴; 밴; ) HANGUL SYLLABLE BAEN
+BC35;BC35;1107 1162 11AC;BC35;1107 1162 11AC; # (밵; 밵; 밵; 밵; 밵; ) HANGUL SYLLABLE BAENJ
+BC36;BC36;1107 1162 11AD;BC36;1107 1162 11AD; # (밶; 밶; 밶; 밶; 밶; ) HANGUL SYLLABLE BAENH
+BC37;BC37;1107 1162 11AE;BC37;1107 1162 11AE; # (밷; 밷; 밷; 밷; 밷; ) HANGUL SYLLABLE BAED
+BC38;BC38;1107 1162 11AF;BC38;1107 1162 11AF; # (밸; 밸; 밸; 밸; 밸; ) HANGUL SYLLABLE BAEL
+BC39;BC39;1107 1162 11B0;BC39;1107 1162 11B0; # (밹; 밹; 밹; 밹; 밹; ) HANGUL SYLLABLE BAELG
+BC3A;BC3A;1107 1162 11B1;BC3A;1107 1162 11B1; # (밺; 밺; 밺; 밺; 밺; ) HANGUL SYLLABLE BAELM
+BC3B;BC3B;1107 1162 11B2;BC3B;1107 1162 11B2; # (밻; 밻; 밻; 밻; 밻; ) HANGUL SYLLABLE BAELB
+BC3C;BC3C;1107 1162 11B3;BC3C;1107 1162 11B3; # (밼; 밼; 밼; 밼; 밼; ) HANGUL SYLLABLE BAELS
+BC3D;BC3D;1107 1162 11B4;BC3D;1107 1162 11B4; # (밽; 밽; 밽; 밽; 밽; ) HANGUL SYLLABLE BAELT
+BC3E;BC3E;1107 1162 11B5;BC3E;1107 1162 11B5; # (밾; 밾; 밾; 밾; 밾; ) HANGUL SYLLABLE BAELP
+BC3F;BC3F;1107 1162 11B6;BC3F;1107 1162 11B6; # (밿; 밿; 밿; 밿; 밿; ) HANGUL SYLLABLE BAELH
+BC40;BC40;1107 1162 11B7;BC40;1107 1162 11B7; # (뱀; 뱀; 뱀; 뱀; 뱀; ) HANGUL SYLLABLE BAEM
+BC41;BC41;1107 1162 11B8;BC41;1107 1162 11B8; # (뱁; 뱁; 뱁; 뱁; 뱁; ) HANGUL SYLLABLE BAEB
+BC42;BC42;1107 1162 11B9;BC42;1107 1162 11B9; # (뱂; 뱂; 뱂; 뱂; 뱂; ) HANGUL SYLLABLE BAEBS
+BC43;BC43;1107 1162 11BA;BC43;1107 1162 11BA; # (뱃; 뱃; 뱃; 뱃; 뱃; ) HANGUL SYLLABLE BAES
+BC44;BC44;1107 1162 11BB;BC44;1107 1162 11BB; # (뱄; 뱄; 뱄; 뱄; 뱄; ) HANGUL SYLLABLE BAESS
+BC45;BC45;1107 1162 11BC;BC45;1107 1162 11BC; # (뱅; 뱅; 뱅; 뱅; 뱅; ) HANGUL SYLLABLE BAENG
+BC46;BC46;1107 1162 11BD;BC46;1107 1162 11BD; # (뱆; 뱆; 뱆; 뱆; 뱆; ) HANGUL SYLLABLE BAEJ
+BC47;BC47;1107 1162 11BE;BC47;1107 1162 11BE; # (뱇; 뱇; 뱇; 뱇; 뱇; ) HANGUL SYLLABLE BAEC
+BC48;BC48;1107 1162 11BF;BC48;1107 1162 11BF; # (뱈; 뱈; 뱈; 뱈; 뱈; ) HANGUL SYLLABLE BAEK
+BC49;BC49;1107 1162 11C0;BC49;1107 1162 11C0; # (뱉; 뱉; 뱉; 뱉; 뱉; ) HANGUL SYLLABLE BAET
+BC4A;BC4A;1107 1162 11C1;BC4A;1107 1162 11C1; # (뱊; 뱊; 뱊; 뱊; 뱊; ) HANGUL SYLLABLE BAEP
+BC4B;BC4B;1107 1162 11C2;BC4B;1107 1162 11C2; # (뱋; 뱋; 뱋; 뱋; 뱋; ) HANGUL SYLLABLE BAEH
+BC4C;BC4C;1107 1163;BC4C;1107 1163; # (뱌; 뱌; 뱌; 뱌; 뱌; ) HANGUL SYLLABLE BYA
+BC4D;BC4D;1107 1163 11A8;BC4D;1107 1163 11A8; # (뱍; 뱍; 뱍; 뱍; 뱍; ) HANGUL SYLLABLE BYAG
+BC4E;BC4E;1107 1163 11A9;BC4E;1107 1163 11A9; # (뱎; 뱎; 뱎; 뱎; 뱎; ) HANGUL SYLLABLE BYAGG
+BC4F;BC4F;1107 1163 11AA;BC4F;1107 1163 11AA; # (뱏; 뱏; 뱏; 뱏; 뱏; ) HANGUL SYLLABLE BYAGS
+BC50;BC50;1107 1163 11AB;BC50;1107 1163 11AB; # (뱐; 뱐; 뱐; 뱐; 뱐; ) HANGUL SYLLABLE BYAN
+BC51;BC51;1107 1163 11AC;BC51;1107 1163 11AC; # (뱑; 뱑; 뱑; 뱑; 뱑; ) HANGUL SYLLABLE BYANJ
+BC52;BC52;1107 1163 11AD;BC52;1107 1163 11AD; # (뱒; 뱒; 뱒; 뱒; 뱒; ) HANGUL SYLLABLE BYANH
+BC53;BC53;1107 1163 11AE;BC53;1107 1163 11AE; # (뱓; 뱓; 뱓; 뱓; 뱓; ) HANGUL SYLLABLE BYAD
+BC54;BC54;1107 1163 11AF;BC54;1107 1163 11AF; # (뱔; 뱔; 뱔; 뱔; 뱔; ) HANGUL SYLLABLE BYAL
+BC55;BC55;1107 1163 11B0;BC55;1107 1163 11B0; # (뱕; 뱕; 뱕; 뱕; 뱕; ) HANGUL SYLLABLE BYALG
+BC56;BC56;1107 1163 11B1;BC56;1107 1163 11B1; # (뱖; 뱖; 뱖; 뱖; 뱖; ) HANGUL SYLLABLE BYALM
+BC57;BC57;1107 1163 11B2;BC57;1107 1163 11B2; # (뱗; 뱗; 뱗; 뱗; 뱗; ) HANGUL SYLLABLE BYALB
+BC58;BC58;1107 1163 11B3;BC58;1107 1163 11B3; # (뱘; 뱘; 뱘; 뱘; 뱘; ) HANGUL SYLLABLE BYALS
+BC59;BC59;1107 1163 11B4;BC59;1107 1163 11B4; # (뱙; 뱙; 뱙; 뱙; 뱙; ) HANGUL SYLLABLE BYALT
+BC5A;BC5A;1107 1163 11B5;BC5A;1107 1163 11B5; # (뱚; 뱚; 뱚; 뱚; 뱚; ) HANGUL SYLLABLE BYALP
+BC5B;BC5B;1107 1163 11B6;BC5B;1107 1163 11B6; # (뱛; 뱛; 뱛; 뱛; 뱛; ) HANGUL SYLLABLE BYALH
+BC5C;BC5C;1107 1163 11B7;BC5C;1107 1163 11B7; # (뱜; 뱜; 뱜; 뱜; 뱜; ) HANGUL SYLLABLE BYAM
+BC5D;BC5D;1107 1163 11B8;BC5D;1107 1163 11B8; # (뱝; 뱝; 뱝; 뱝; 뱝; ) HANGUL SYLLABLE BYAB
+BC5E;BC5E;1107 1163 11B9;BC5E;1107 1163 11B9; # (뱞; 뱞; 뱞; 뱞; 뱞; ) HANGUL SYLLABLE BYABS
+BC5F;BC5F;1107 1163 11BA;BC5F;1107 1163 11BA; # (뱟; 뱟; 뱟; 뱟; 뱟; ) HANGUL SYLLABLE BYAS
+BC60;BC60;1107 1163 11BB;BC60;1107 1163 11BB; # (뱠; 뱠; 뱠; 뱠; 뱠; ) HANGUL SYLLABLE BYASS
+BC61;BC61;1107 1163 11BC;BC61;1107 1163 11BC; # (뱡; 뱡; 뱡; 뱡; 뱡; ) HANGUL SYLLABLE BYANG
+BC62;BC62;1107 1163 11BD;BC62;1107 1163 11BD; # (뱢; 뱢; 뱢; 뱢; 뱢; ) HANGUL SYLLABLE BYAJ
+BC63;BC63;1107 1163 11BE;BC63;1107 1163 11BE; # (뱣; 뱣; 뱣; 뱣; 뱣; ) HANGUL SYLLABLE BYAC
+BC64;BC64;1107 1163 11BF;BC64;1107 1163 11BF; # (뱤; 뱤; 뱤; 뱤; 뱤; ) HANGUL SYLLABLE BYAK
+BC65;BC65;1107 1163 11C0;BC65;1107 1163 11C0; # (뱥; 뱥; 뱥; 뱥; 뱥; ) HANGUL SYLLABLE BYAT
+BC66;BC66;1107 1163 11C1;BC66;1107 1163 11C1; # (뱦; 뱦; 뱦; 뱦; 뱦; ) HANGUL SYLLABLE BYAP
+BC67;BC67;1107 1163 11C2;BC67;1107 1163 11C2; # (뱧; 뱧; 뱧; 뱧; 뱧; ) HANGUL SYLLABLE BYAH
+BC68;BC68;1107 1164;BC68;1107 1164; # (뱨; 뱨; 뱨; 뱨; 뱨; ) HANGUL SYLLABLE BYAE
+BC69;BC69;1107 1164 11A8;BC69;1107 1164 11A8; # (뱩; 뱩; 뱩; 뱩; 뱩; ) HANGUL SYLLABLE BYAEG
+BC6A;BC6A;1107 1164 11A9;BC6A;1107 1164 11A9; # (뱪; 뱪; 뱪; 뱪; 뱪; ) HANGUL SYLLABLE BYAEGG
+BC6B;BC6B;1107 1164 11AA;BC6B;1107 1164 11AA; # (뱫; 뱫; 뱫; 뱫; 뱫; ) HANGUL SYLLABLE BYAEGS
+BC6C;BC6C;1107 1164 11AB;BC6C;1107 1164 11AB; # (뱬; 뱬; 뱬; 뱬; 뱬; ) HANGUL SYLLABLE BYAEN
+BC6D;BC6D;1107 1164 11AC;BC6D;1107 1164 11AC; # (뱭; 뱭; 뱭; 뱭; 뱭; ) HANGUL SYLLABLE BYAENJ
+BC6E;BC6E;1107 1164 11AD;BC6E;1107 1164 11AD; # (뱮; 뱮; 뱮; 뱮; 뱮; ) HANGUL SYLLABLE BYAENH
+BC6F;BC6F;1107 1164 11AE;BC6F;1107 1164 11AE; # (뱯; 뱯; 뱯; 뱯; 뱯; ) HANGUL SYLLABLE BYAED
+BC70;BC70;1107 1164 11AF;BC70;1107 1164 11AF; # (뱰; 뱰; 뱰; 뱰; 뱰; ) HANGUL SYLLABLE BYAEL
+BC71;BC71;1107 1164 11B0;BC71;1107 1164 11B0; # (뱱; 뱱; 뱱; 뱱; 뱱; ) HANGUL SYLLABLE BYAELG
+BC72;BC72;1107 1164 11B1;BC72;1107 1164 11B1; # (뱲; 뱲; 뱲; 뱲; 뱲; ) HANGUL SYLLABLE BYAELM
+BC73;BC73;1107 1164 11B2;BC73;1107 1164 11B2; # (뱳; 뱳; 뱳; 뱳; 뱳; ) HANGUL SYLLABLE BYAELB
+BC74;BC74;1107 1164 11B3;BC74;1107 1164 11B3; # (뱴; 뱴; 뱴; 뱴; 뱴; ) HANGUL SYLLABLE BYAELS
+BC75;BC75;1107 1164 11B4;BC75;1107 1164 11B4; # (뱵; 뱵; 뱵; 뱵; 뱵; ) HANGUL SYLLABLE BYAELT
+BC76;BC76;1107 1164 11B5;BC76;1107 1164 11B5; # (뱶; 뱶; 뱶; 뱶; 뱶; ) HANGUL SYLLABLE BYAELP
+BC77;BC77;1107 1164 11B6;BC77;1107 1164 11B6; # (뱷; 뱷; 뱷; 뱷; 뱷; ) HANGUL SYLLABLE BYAELH
+BC78;BC78;1107 1164 11B7;BC78;1107 1164 11B7; # (뱸; 뱸; 뱸; 뱸; 뱸; ) HANGUL SYLLABLE BYAEM
+BC79;BC79;1107 1164 11B8;BC79;1107 1164 11B8; # (뱹; 뱹; 뱹; 뱹; 뱹; ) HANGUL SYLLABLE BYAEB
+BC7A;BC7A;1107 1164 11B9;BC7A;1107 1164 11B9; # (뱺; 뱺; 뱺; 뱺; 뱺; ) HANGUL SYLLABLE BYAEBS
+BC7B;BC7B;1107 1164 11BA;BC7B;1107 1164 11BA; # (뱻; 뱻; 뱻; 뱻; 뱻; ) HANGUL SYLLABLE BYAES
+BC7C;BC7C;1107 1164 11BB;BC7C;1107 1164 11BB; # (뱼; 뱼; 뱼; 뱼; 뱼; ) HANGUL SYLLABLE BYAESS
+BC7D;BC7D;1107 1164 11BC;BC7D;1107 1164 11BC; # (뱽; 뱽; 뱽; 뱽; 뱽; ) HANGUL SYLLABLE BYAENG
+BC7E;BC7E;1107 1164 11BD;BC7E;1107 1164 11BD; # (뱾; 뱾; 뱾; 뱾; 뱾; ) HANGUL SYLLABLE BYAEJ
+BC7F;BC7F;1107 1164 11BE;BC7F;1107 1164 11BE; # (뱿; 뱿; 뱿; 뱿; 뱿; ) HANGUL SYLLABLE BYAEC
+BC80;BC80;1107 1164 11BF;BC80;1107 1164 11BF; # (벀; 벀; 벀; 벀; 벀; ) HANGUL SYLLABLE BYAEK
+BC81;BC81;1107 1164 11C0;BC81;1107 1164 11C0; # (벁; 벁; 벁; 벁; 벁; ) HANGUL SYLLABLE BYAET
+BC82;BC82;1107 1164 11C1;BC82;1107 1164 11C1; # (벂; 벂; 벂; 벂; 벂; ) HANGUL SYLLABLE BYAEP
+BC83;BC83;1107 1164 11C2;BC83;1107 1164 11C2; # (벃; 벃; 벃; 벃; 벃; ) HANGUL SYLLABLE BYAEH
+BC84;BC84;1107 1165;BC84;1107 1165; # (버; 버; 버; 버; 버; ) HANGUL SYLLABLE BEO
+BC85;BC85;1107 1165 11A8;BC85;1107 1165 11A8; # (벅; 벅; 벅; 벅; 벅; ) HANGUL SYLLABLE BEOG
+BC86;BC86;1107 1165 11A9;BC86;1107 1165 11A9; # (벆; 벆; 벆; 벆; 벆; ) HANGUL SYLLABLE BEOGG
+BC87;BC87;1107 1165 11AA;BC87;1107 1165 11AA; # (벇; 벇; 벇; 벇; 벇; ) HANGUL SYLLABLE BEOGS
+BC88;BC88;1107 1165 11AB;BC88;1107 1165 11AB; # (번; 번; 번; 번; 번; ) HANGUL SYLLABLE BEON
+BC89;BC89;1107 1165 11AC;BC89;1107 1165 11AC; # (벉; 벉; 벉; 벉; 벉; ) HANGUL SYLLABLE BEONJ
+BC8A;BC8A;1107 1165 11AD;BC8A;1107 1165 11AD; # (벊; 벊; 벊; 벊; 벊; ) HANGUL SYLLABLE BEONH
+BC8B;BC8B;1107 1165 11AE;BC8B;1107 1165 11AE; # (벋; 벋; 벋; 벋; 벋; ) HANGUL SYLLABLE BEOD
+BC8C;BC8C;1107 1165 11AF;BC8C;1107 1165 11AF; # (벌; 벌; 벌; 벌; 벌; ) HANGUL SYLLABLE BEOL
+BC8D;BC8D;1107 1165 11B0;BC8D;1107 1165 11B0; # (벍; 벍; 벍; 벍; 벍; ) HANGUL SYLLABLE BEOLG
+BC8E;BC8E;1107 1165 11B1;BC8E;1107 1165 11B1; # (벎; 벎; 벎; 벎; 벎; ) HANGUL SYLLABLE BEOLM
+BC8F;BC8F;1107 1165 11B2;BC8F;1107 1165 11B2; # (벏; 벏; 벏; 벏; 벏; ) HANGUL SYLLABLE BEOLB
+BC90;BC90;1107 1165 11B3;BC90;1107 1165 11B3; # (벐; 벐; 벐; 벐; 벐; ) HANGUL SYLLABLE BEOLS
+BC91;BC91;1107 1165 11B4;BC91;1107 1165 11B4; # (벑; 벑; 벑; 벑; 벑; ) HANGUL SYLLABLE BEOLT
+BC92;BC92;1107 1165 11B5;BC92;1107 1165 11B5; # (벒; 벒; 벒; 벒; 벒; ) HANGUL SYLLABLE BEOLP
+BC93;BC93;1107 1165 11B6;BC93;1107 1165 11B6; # (벓; 벓; 벓; 벓; 벓; ) HANGUL SYLLABLE BEOLH
+BC94;BC94;1107 1165 11B7;BC94;1107 1165 11B7; # (범; 범; 범; 범; 범; ) HANGUL SYLLABLE BEOM
+BC95;BC95;1107 1165 11B8;BC95;1107 1165 11B8; # (법; 법; 법; 법; 법; ) HANGUL SYLLABLE BEOB
+BC96;BC96;1107 1165 11B9;BC96;1107 1165 11B9; # (벖; 벖; 벖; 벖; 벖; ) HANGUL SYLLABLE BEOBS
+BC97;BC97;1107 1165 11BA;BC97;1107 1165 11BA; # (벗; 벗; 벗; 벗; 벗; ) HANGUL SYLLABLE BEOS
+BC98;BC98;1107 1165 11BB;BC98;1107 1165 11BB; # (벘; 벘; 벘; 벘; 벘; ) HANGUL SYLLABLE BEOSS
+BC99;BC99;1107 1165 11BC;BC99;1107 1165 11BC; # (벙; 벙; 벙; 벙; 벙; ) HANGUL SYLLABLE BEONG
+BC9A;BC9A;1107 1165 11BD;BC9A;1107 1165 11BD; # (벚; 벚; 벚; 벚; 벚; ) HANGUL SYLLABLE BEOJ
+BC9B;BC9B;1107 1165 11BE;BC9B;1107 1165 11BE; # (벛; 벛; 벛; 벛; 벛; ) HANGUL SYLLABLE BEOC
+BC9C;BC9C;1107 1165 11BF;BC9C;1107 1165 11BF; # (벜; 벜; 벜; 벜; 벜; ) HANGUL SYLLABLE BEOK
+BC9D;BC9D;1107 1165 11C0;BC9D;1107 1165 11C0; # (벝; 벝; 벝; 벝; 벝; ) HANGUL SYLLABLE BEOT
+BC9E;BC9E;1107 1165 11C1;BC9E;1107 1165 11C1; # (벞; 벞; 벞; 벞; 벞; ) HANGUL SYLLABLE BEOP
+BC9F;BC9F;1107 1165 11C2;BC9F;1107 1165 11C2; # (벟; 벟; 벟; 벟; 벟; ) HANGUL SYLLABLE BEOH
+BCA0;BCA0;1107 1166;BCA0;1107 1166; # (베; 베; 베; 베; 베; ) HANGUL SYLLABLE BE
+BCA1;BCA1;1107 1166 11A8;BCA1;1107 1166 11A8; # (벡; 벡; 벡; 벡; 벡; ) HANGUL SYLLABLE BEG
+BCA2;BCA2;1107 1166 11A9;BCA2;1107 1166 11A9; # (벢; 벢; 벢; 벢; 벢; ) HANGUL SYLLABLE BEGG
+BCA3;BCA3;1107 1166 11AA;BCA3;1107 1166 11AA; # (벣; 벣; 벣; 벣; 벣; ) HANGUL SYLLABLE BEGS
+BCA4;BCA4;1107 1166 11AB;BCA4;1107 1166 11AB; # (벤; 벤; 벤; 벤; 벤; ) HANGUL SYLLABLE BEN
+BCA5;BCA5;1107 1166 11AC;BCA5;1107 1166 11AC; # (벥; 벥; 벥; 벥; 벥; ) HANGUL SYLLABLE BENJ
+BCA6;BCA6;1107 1166 11AD;BCA6;1107 1166 11AD; # (벦; 벦; 벦; 벦; 벦; ) HANGUL SYLLABLE BENH
+BCA7;BCA7;1107 1166 11AE;BCA7;1107 1166 11AE; # (벧; 벧; 벧; 벧; 벧; ) HANGUL SYLLABLE BED
+BCA8;BCA8;1107 1166 11AF;BCA8;1107 1166 11AF; # (벨; 벨; 벨; 벨; 벨; ) HANGUL SYLLABLE BEL
+BCA9;BCA9;1107 1166 11B0;BCA9;1107 1166 11B0; # (벩; 벩; 벩; 벩; 벩; ) HANGUL SYLLABLE BELG
+BCAA;BCAA;1107 1166 11B1;BCAA;1107 1166 11B1; # (벪; 벪; 벪; 벪; 벪; ) HANGUL SYLLABLE BELM
+BCAB;BCAB;1107 1166 11B2;BCAB;1107 1166 11B2; # (벫; 벫; 벫; 벫; 벫; ) HANGUL SYLLABLE BELB
+BCAC;BCAC;1107 1166 11B3;BCAC;1107 1166 11B3; # (벬; 벬; 벬; 벬; 벬; ) HANGUL SYLLABLE BELS
+BCAD;BCAD;1107 1166 11B4;BCAD;1107 1166 11B4; # (벭; 벭; 벭; 벭; 벭; ) HANGUL SYLLABLE BELT
+BCAE;BCAE;1107 1166 11B5;BCAE;1107 1166 11B5; # (벮; 벮; 벮; 벮; 벮; ) HANGUL SYLLABLE BELP
+BCAF;BCAF;1107 1166 11B6;BCAF;1107 1166 11B6; # (벯; 벯; 벯; 벯; 벯; ) HANGUL SYLLABLE BELH
+BCB0;BCB0;1107 1166 11B7;BCB0;1107 1166 11B7; # (벰; 벰; 벰; 벰; 벰; ) HANGUL SYLLABLE BEM
+BCB1;BCB1;1107 1166 11B8;BCB1;1107 1166 11B8; # (벱; 벱; 벱; 벱; 벱; ) HANGUL SYLLABLE BEB
+BCB2;BCB2;1107 1166 11B9;BCB2;1107 1166 11B9; # (벲; 벲; 벲; 벲; 벲; ) HANGUL SYLLABLE BEBS
+BCB3;BCB3;1107 1166 11BA;BCB3;1107 1166 11BA; # (벳; 벳; 벳; 벳; 벳; ) HANGUL SYLLABLE BES
+BCB4;BCB4;1107 1166 11BB;BCB4;1107 1166 11BB; # (벴; 벴; 벴; 벴; 벴; ) HANGUL SYLLABLE BESS
+BCB5;BCB5;1107 1166 11BC;BCB5;1107 1166 11BC; # (벵; 벵; 벵; 벵; 벵; ) HANGUL SYLLABLE BENG
+BCB6;BCB6;1107 1166 11BD;BCB6;1107 1166 11BD; # (벶; 벶; 벶; 벶; 벶; ) HANGUL SYLLABLE BEJ
+BCB7;BCB7;1107 1166 11BE;BCB7;1107 1166 11BE; # (벷; 벷; 벷; 벷; 벷; ) HANGUL SYLLABLE BEC
+BCB8;BCB8;1107 1166 11BF;BCB8;1107 1166 11BF; # (벸; 벸; 벸; 벸; 벸; ) HANGUL SYLLABLE BEK
+BCB9;BCB9;1107 1166 11C0;BCB9;1107 1166 11C0; # (벹; 벹; 벹; 벹; 벹; ) HANGUL SYLLABLE BET
+BCBA;BCBA;1107 1166 11C1;BCBA;1107 1166 11C1; # (벺; 벺; 벺; 벺; 벺; ) HANGUL SYLLABLE BEP
+BCBB;BCBB;1107 1166 11C2;BCBB;1107 1166 11C2; # (벻; 벻; 벻; 벻; 벻; ) HANGUL SYLLABLE BEH
+BCBC;BCBC;1107 1167;BCBC;1107 1167; # (벼; 벼; 벼; 벼; 벼; ) HANGUL SYLLABLE BYEO
+BCBD;BCBD;1107 1167 11A8;BCBD;1107 1167 11A8; # (벽; 벽; 벽; 벽; 벽; ) HANGUL SYLLABLE BYEOG
+BCBE;BCBE;1107 1167 11A9;BCBE;1107 1167 11A9; # (벾; 벾; 벾; 벾; 벾; ) HANGUL SYLLABLE BYEOGG
+BCBF;BCBF;1107 1167 11AA;BCBF;1107 1167 11AA; # (벿; 벿; 벿; 벿; 벿; ) HANGUL SYLLABLE BYEOGS
+BCC0;BCC0;1107 1167 11AB;BCC0;1107 1167 11AB; # (변; 변; 변; 변; 변; ) HANGUL SYLLABLE BYEON
+BCC1;BCC1;1107 1167 11AC;BCC1;1107 1167 11AC; # (볁; 볁; 볁; 볁; 볁; ) HANGUL SYLLABLE BYEONJ
+BCC2;BCC2;1107 1167 11AD;BCC2;1107 1167 11AD; # (볂; 볂; 볂; 볂; 볂; ) HANGUL SYLLABLE BYEONH
+BCC3;BCC3;1107 1167 11AE;BCC3;1107 1167 11AE; # (볃; 볃; 볃; 볃; 볃; ) HANGUL SYLLABLE BYEOD
+BCC4;BCC4;1107 1167 11AF;BCC4;1107 1167 11AF; # (별; 별; 별; 별; 별; ) HANGUL SYLLABLE BYEOL
+BCC5;BCC5;1107 1167 11B0;BCC5;1107 1167 11B0; # (볅; 볅; 볅; 볅; 볅; ) HANGUL SYLLABLE BYEOLG
+BCC6;BCC6;1107 1167 11B1;BCC6;1107 1167 11B1; # (볆; 볆; 볆; 볆; 볆; ) HANGUL SYLLABLE BYEOLM
+BCC7;BCC7;1107 1167 11B2;BCC7;1107 1167 11B2; # (볇; 볇; 볇; 볇; 볇; ) HANGUL SYLLABLE BYEOLB
+BCC8;BCC8;1107 1167 11B3;BCC8;1107 1167 11B3; # (볈; 볈; 볈; 볈; 볈; ) HANGUL SYLLABLE BYEOLS
+BCC9;BCC9;1107 1167 11B4;BCC9;1107 1167 11B4; # (볉; 볉; 볉; 볉; 볉; ) HANGUL SYLLABLE BYEOLT
+BCCA;BCCA;1107 1167 11B5;BCCA;1107 1167 11B5; # (볊; 볊; 볊; 볊; 볊; ) HANGUL SYLLABLE BYEOLP
+BCCB;BCCB;1107 1167 11B6;BCCB;1107 1167 11B6; # (볋; 볋; 볋; 볋; 볋; ) HANGUL SYLLABLE BYEOLH
+BCCC;BCCC;1107 1167 11B7;BCCC;1107 1167 11B7; # (볌; 볌; 볌; 볌; 볌; ) HANGUL SYLLABLE BYEOM
+BCCD;BCCD;1107 1167 11B8;BCCD;1107 1167 11B8; # (볍; 볍; 볍; 볍; 볍; ) HANGUL SYLLABLE BYEOB
+BCCE;BCCE;1107 1167 11B9;BCCE;1107 1167 11B9; # (볎; 볎; 볎; 볎; 볎; ) HANGUL SYLLABLE BYEOBS
+BCCF;BCCF;1107 1167 11BA;BCCF;1107 1167 11BA; # (볏; 볏; 볏; 볏; 볏; ) HANGUL SYLLABLE BYEOS
+BCD0;BCD0;1107 1167 11BB;BCD0;1107 1167 11BB; # (볐; 볐; 볐; 볐; 볐; ) HANGUL SYLLABLE BYEOSS
+BCD1;BCD1;1107 1167 11BC;BCD1;1107 1167 11BC; # (병; 병; 병; 병; 병; ) HANGUL SYLLABLE BYEONG
+BCD2;BCD2;1107 1167 11BD;BCD2;1107 1167 11BD; # (볒; 볒; 볒; 볒; 볒; ) HANGUL SYLLABLE BYEOJ
+BCD3;BCD3;1107 1167 11BE;BCD3;1107 1167 11BE; # (볓; 볓; 볓; 볓; 볓; ) HANGUL SYLLABLE BYEOC
+BCD4;BCD4;1107 1167 11BF;BCD4;1107 1167 11BF; # (볔; 볔; 볔; 볔; 볔; ) HANGUL SYLLABLE BYEOK
+BCD5;BCD5;1107 1167 11C0;BCD5;1107 1167 11C0; # (볕; 볕; 볕; 볕; 볕; ) HANGUL SYLLABLE BYEOT
+BCD6;BCD6;1107 1167 11C1;BCD6;1107 1167 11C1; # (볖; 볖; 볖; 볖; 볖; ) HANGUL SYLLABLE BYEOP
+BCD7;BCD7;1107 1167 11C2;BCD7;1107 1167 11C2; # (볗; 볗; 볗; 볗; 볗; ) HANGUL SYLLABLE BYEOH
+BCD8;BCD8;1107 1168;BCD8;1107 1168; # (볘; 볘; 볘; 볘; 볘; ) HANGUL SYLLABLE BYE
+BCD9;BCD9;1107 1168 11A8;BCD9;1107 1168 11A8; # (볙; 볙; 볙; 볙; 볙; ) HANGUL SYLLABLE BYEG
+BCDA;BCDA;1107 1168 11A9;BCDA;1107 1168 11A9; # (볚; 볚; 볚; 볚; 볚; ) HANGUL SYLLABLE BYEGG
+BCDB;BCDB;1107 1168 11AA;BCDB;1107 1168 11AA; # (볛; 볛; 볛; 볛; 볛; ) HANGUL SYLLABLE BYEGS
+BCDC;BCDC;1107 1168 11AB;BCDC;1107 1168 11AB; # (볜; 볜; 볜; 볜; 볜; ) HANGUL SYLLABLE BYEN
+BCDD;BCDD;1107 1168 11AC;BCDD;1107 1168 11AC; # (볝; 볝; 볝; 볝; 볝; ) HANGUL SYLLABLE BYENJ
+BCDE;BCDE;1107 1168 11AD;BCDE;1107 1168 11AD; # (볞; 볞; 볞; 볞; 볞; ) HANGUL SYLLABLE BYENH
+BCDF;BCDF;1107 1168 11AE;BCDF;1107 1168 11AE; # (볟; 볟; 볟; 볟; 볟; ) HANGUL SYLLABLE BYED
+BCE0;BCE0;1107 1168 11AF;BCE0;1107 1168 11AF; # (볠; 볠; 볠; 볠; 볠; ) HANGUL SYLLABLE BYEL
+BCE1;BCE1;1107 1168 11B0;BCE1;1107 1168 11B0; # (볡; 볡; 볡; 볡; 볡; ) HANGUL SYLLABLE BYELG
+BCE2;BCE2;1107 1168 11B1;BCE2;1107 1168 11B1; # (볢; 볢; 볢; 볢; 볢; ) HANGUL SYLLABLE BYELM
+BCE3;BCE3;1107 1168 11B2;BCE3;1107 1168 11B2; # (볣; 볣; 볣; 볣; 볣; ) HANGUL SYLLABLE BYELB
+BCE4;BCE4;1107 1168 11B3;BCE4;1107 1168 11B3; # (볤; 볤; 볤; 볤; 볤; ) HANGUL SYLLABLE BYELS
+BCE5;BCE5;1107 1168 11B4;BCE5;1107 1168 11B4; # (볥; 볥; 볥; 볥; 볥; ) HANGUL SYLLABLE BYELT
+BCE6;BCE6;1107 1168 11B5;BCE6;1107 1168 11B5; # (볦; 볦; 볦; 볦; 볦; ) HANGUL SYLLABLE BYELP
+BCE7;BCE7;1107 1168 11B6;BCE7;1107 1168 11B6; # (볧; 볧; 볧; 볧; 볧; ) HANGUL SYLLABLE BYELH
+BCE8;BCE8;1107 1168 11B7;BCE8;1107 1168 11B7; # (볨; 볨; 볨; 볨; 볨; ) HANGUL SYLLABLE BYEM
+BCE9;BCE9;1107 1168 11B8;BCE9;1107 1168 11B8; # (볩; 볩; 볩; 볩; 볩; ) HANGUL SYLLABLE BYEB
+BCEA;BCEA;1107 1168 11B9;BCEA;1107 1168 11B9; # (볪; 볪; 볪; 볪; 볪; ) HANGUL SYLLABLE BYEBS
+BCEB;BCEB;1107 1168 11BA;BCEB;1107 1168 11BA; # (볫; 볫; 볫; 볫; 볫; ) HANGUL SYLLABLE BYES
+BCEC;BCEC;1107 1168 11BB;BCEC;1107 1168 11BB; # (볬; 볬; 볬; 볬; 볬; ) HANGUL SYLLABLE BYESS
+BCED;BCED;1107 1168 11BC;BCED;1107 1168 11BC; # (볭; 볭; 볭; 볭; 볭; ) HANGUL SYLLABLE BYENG
+BCEE;BCEE;1107 1168 11BD;BCEE;1107 1168 11BD; # (볮; 볮; 볮; 볮; 볮; ) HANGUL SYLLABLE BYEJ
+BCEF;BCEF;1107 1168 11BE;BCEF;1107 1168 11BE; # (볯; 볯; 볯; 볯; 볯; ) HANGUL SYLLABLE BYEC
+BCF0;BCF0;1107 1168 11BF;BCF0;1107 1168 11BF; # (볰; 볰; 볰; 볰; 볰; ) HANGUL SYLLABLE BYEK
+BCF1;BCF1;1107 1168 11C0;BCF1;1107 1168 11C0; # (볱; 볱; 볱; 볱; 볱; ) HANGUL SYLLABLE BYET
+BCF2;BCF2;1107 1168 11C1;BCF2;1107 1168 11C1; # (볲; 볲; 볲; 볲; 볲; ) HANGUL SYLLABLE BYEP
+BCF3;BCF3;1107 1168 11C2;BCF3;1107 1168 11C2; # (볳; 볳; 볳; 볳; 볳; ) HANGUL SYLLABLE BYEH
+BCF4;BCF4;1107 1169;BCF4;1107 1169; # (보; 보; 보; 보; 보; ) HANGUL SYLLABLE BO
+BCF5;BCF5;1107 1169 11A8;BCF5;1107 1169 11A8; # (복; 복; 복; 복; 복; ) HANGUL SYLLABLE BOG
+BCF6;BCF6;1107 1169 11A9;BCF6;1107 1169 11A9; # (볶; 볶; 볶; 볶; 볶; ) HANGUL SYLLABLE BOGG
+BCF7;BCF7;1107 1169 11AA;BCF7;1107 1169 11AA; # (볷; 볷; 볷; 볷; 볷; ) HANGUL SYLLABLE BOGS
+BCF8;BCF8;1107 1169 11AB;BCF8;1107 1169 11AB; # (본; 본; 본; 본; 본; ) HANGUL SYLLABLE BON
+BCF9;BCF9;1107 1169 11AC;BCF9;1107 1169 11AC; # (볹; 볹; 볹; 볹; 볹; ) HANGUL SYLLABLE BONJ
+BCFA;BCFA;1107 1169 11AD;BCFA;1107 1169 11AD; # (볺; 볺; 볺; 볺; 볺; ) HANGUL SYLLABLE BONH
+BCFB;BCFB;1107 1169 11AE;BCFB;1107 1169 11AE; # (볻; 볻; 볻; 볻; 볻; ) HANGUL SYLLABLE BOD
+BCFC;BCFC;1107 1169 11AF;BCFC;1107 1169 11AF; # (볼; 볼; 볼; 볼; 볼; ) HANGUL SYLLABLE BOL
+BCFD;BCFD;1107 1169 11B0;BCFD;1107 1169 11B0; # (볽; 볽; 볽; 볽; 볽; ) HANGUL SYLLABLE BOLG
+BCFE;BCFE;1107 1169 11B1;BCFE;1107 1169 11B1; # (볾; 볾; 볾; 볾; 볾; ) HANGUL SYLLABLE BOLM
+BCFF;BCFF;1107 1169 11B2;BCFF;1107 1169 11B2; # (볿; 볿; 볿; 볿; 볿; ) HANGUL SYLLABLE BOLB
+BD00;BD00;1107 1169 11B3;BD00;1107 1169 11B3; # (봀; 봀; 봀; 봀; 봀; ) HANGUL SYLLABLE BOLS
+BD01;BD01;1107 1169 11B4;BD01;1107 1169 11B4; # (봁; 봁; 봁; 봁; 봁; ) HANGUL SYLLABLE BOLT
+BD02;BD02;1107 1169 11B5;BD02;1107 1169 11B5; # (봂; 봂; 봂; 봂; 봂; ) HANGUL SYLLABLE BOLP
+BD03;BD03;1107 1169 11B6;BD03;1107 1169 11B6; # (봃; 봃; 봃; 봃; 봃; ) HANGUL SYLLABLE BOLH
+BD04;BD04;1107 1169 11B7;BD04;1107 1169 11B7; # (봄; 봄; 봄; 봄; 봄; ) HANGUL SYLLABLE BOM
+BD05;BD05;1107 1169 11B8;BD05;1107 1169 11B8; # (봅; 봅; 봅; 봅; 봅; ) HANGUL SYLLABLE BOB
+BD06;BD06;1107 1169 11B9;BD06;1107 1169 11B9; # (봆; 봆; 봆; 봆; 봆; ) HANGUL SYLLABLE BOBS
+BD07;BD07;1107 1169 11BA;BD07;1107 1169 11BA; # (봇; 봇; 봇; 봇; 봇; ) HANGUL SYLLABLE BOS
+BD08;BD08;1107 1169 11BB;BD08;1107 1169 11BB; # (봈; 봈; 봈; 봈; 봈; ) HANGUL SYLLABLE BOSS
+BD09;BD09;1107 1169 11BC;BD09;1107 1169 11BC; # (봉; 봉; 봉; 봉; 봉; ) HANGUL SYLLABLE BONG
+BD0A;BD0A;1107 1169 11BD;BD0A;1107 1169 11BD; # (봊; 봊; 봊; 봊; 봊; ) HANGUL SYLLABLE BOJ
+BD0B;BD0B;1107 1169 11BE;BD0B;1107 1169 11BE; # (봋; 봋; 봋; 봋; 봋; ) HANGUL SYLLABLE BOC
+BD0C;BD0C;1107 1169 11BF;BD0C;1107 1169 11BF; # (봌; 봌; 봌; 봌; 봌; ) HANGUL SYLLABLE BOK
+BD0D;BD0D;1107 1169 11C0;BD0D;1107 1169 11C0; # (봍; 봍; 봍; 봍; 봍; ) HANGUL SYLLABLE BOT
+BD0E;BD0E;1107 1169 11C1;BD0E;1107 1169 11C1; # (봎; 봎; 봎; 봎; 봎; ) HANGUL SYLLABLE BOP
+BD0F;BD0F;1107 1169 11C2;BD0F;1107 1169 11C2; # (봏; 봏; 봏; 봏; 봏; ) HANGUL SYLLABLE BOH
+BD10;BD10;1107 116A;BD10;1107 116A; # (봐; 봐; 봐; 봐; 봐; ) HANGUL SYLLABLE BWA
+BD11;BD11;1107 116A 11A8;BD11;1107 116A 11A8; # (봑; 봑; 봑; 봑; 봑; ) HANGUL SYLLABLE BWAG
+BD12;BD12;1107 116A 11A9;BD12;1107 116A 11A9; # (봒; 봒; 봒; 봒; 봒; ) HANGUL SYLLABLE BWAGG
+BD13;BD13;1107 116A 11AA;BD13;1107 116A 11AA; # (봓; 봓; 봓; 봓; 봓; ) HANGUL SYLLABLE BWAGS
+BD14;BD14;1107 116A 11AB;BD14;1107 116A 11AB; # (봔; 봔; 봔; 봔; 봔; ) HANGUL SYLLABLE BWAN
+BD15;BD15;1107 116A 11AC;BD15;1107 116A 11AC; # (봕; 봕; 봕; 봕; 봕; ) HANGUL SYLLABLE BWANJ
+BD16;BD16;1107 116A 11AD;BD16;1107 116A 11AD; # (봖; 봖; 봖; 봖; 봖; ) HANGUL SYLLABLE BWANH
+BD17;BD17;1107 116A 11AE;BD17;1107 116A 11AE; # (봗; 봗; 봗; 봗; 봗; ) HANGUL SYLLABLE BWAD
+BD18;BD18;1107 116A 11AF;BD18;1107 116A 11AF; # (봘; 봘; 봘; 봘; 봘; ) HANGUL SYLLABLE BWAL
+BD19;BD19;1107 116A 11B0;BD19;1107 116A 11B0; # (봙; 봙; 봙; 봙; 봙; ) HANGUL SYLLABLE BWALG
+BD1A;BD1A;1107 116A 11B1;BD1A;1107 116A 11B1; # (봚; 봚; 봚; 봚; 봚; ) HANGUL SYLLABLE BWALM
+BD1B;BD1B;1107 116A 11B2;BD1B;1107 116A 11B2; # (봛; 봛; 봛; 봛; 봛; ) HANGUL SYLLABLE BWALB
+BD1C;BD1C;1107 116A 11B3;BD1C;1107 116A 11B3; # (봜; 봜; 봜; 봜; 봜; ) HANGUL SYLLABLE BWALS
+BD1D;BD1D;1107 116A 11B4;BD1D;1107 116A 11B4; # (봝; 봝; 봝; 봝; 봝; ) HANGUL SYLLABLE BWALT
+BD1E;BD1E;1107 116A 11B5;BD1E;1107 116A 11B5; # (봞; 봞; 봞; 봞; 봞; ) HANGUL SYLLABLE BWALP
+BD1F;BD1F;1107 116A 11B6;BD1F;1107 116A 11B6; # (봟; 봟; 봟; 봟; 봟; ) HANGUL SYLLABLE BWALH
+BD20;BD20;1107 116A 11B7;BD20;1107 116A 11B7; # (봠; 봠; 봠; 봠; 봠; ) HANGUL SYLLABLE BWAM
+BD21;BD21;1107 116A 11B8;BD21;1107 116A 11B8; # (봡; 봡; 봡; 봡; 봡; ) HANGUL SYLLABLE BWAB
+BD22;BD22;1107 116A 11B9;BD22;1107 116A 11B9; # (봢; 봢; 봢; 봢; 봢; ) HANGUL SYLLABLE BWABS
+BD23;BD23;1107 116A 11BA;BD23;1107 116A 11BA; # (봣; 봣; 봣; 봣; 봣; ) HANGUL SYLLABLE BWAS
+BD24;BD24;1107 116A 11BB;BD24;1107 116A 11BB; # (봤; 봤; 봤; 봤; 봤; ) HANGUL SYLLABLE BWASS
+BD25;BD25;1107 116A 11BC;BD25;1107 116A 11BC; # (봥; 봥; 봥; 봥; 봥; ) HANGUL SYLLABLE BWANG
+BD26;BD26;1107 116A 11BD;BD26;1107 116A 11BD; # (봦; 봦; 봦; 봦; 봦; ) HANGUL SYLLABLE BWAJ
+BD27;BD27;1107 116A 11BE;BD27;1107 116A 11BE; # (봧; 봧; 봧; 봧; 봧; ) HANGUL SYLLABLE BWAC
+BD28;BD28;1107 116A 11BF;BD28;1107 116A 11BF; # (봨; 봨; 봨; 봨; 봨; ) HANGUL SYLLABLE BWAK
+BD29;BD29;1107 116A 11C0;BD29;1107 116A 11C0; # (봩; 봩; 봩; 봩; 봩; ) HANGUL SYLLABLE BWAT
+BD2A;BD2A;1107 116A 11C1;BD2A;1107 116A 11C1; # (봪; 봪; 봪; 봪; 봪; ) HANGUL SYLLABLE BWAP
+BD2B;BD2B;1107 116A 11C2;BD2B;1107 116A 11C2; # (봫; 봫; 봫; 봫; 봫; ) HANGUL SYLLABLE BWAH
+BD2C;BD2C;1107 116B;BD2C;1107 116B; # (봬; 봬; 봬; 봬; 봬; ) HANGUL SYLLABLE BWAE
+BD2D;BD2D;1107 116B 11A8;BD2D;1107 116B 11A8; # (봭; 봭; 봭; 봭; 봭; ) HANGUL SYLLABLE BWAEG
+BD2E;BD2E;1107 116B 11A9;BD2E;1107 116B 11A9; # (봮; 봮; 봮; 봮; 봮; ) HANGUL SYLLABLE BWAEGG
+BD2F;BD2F;1107 116B 11AA;BD2F;1107 116B 11AA; # (봯; 봯; 봯; 봯; 봯; ) HANGUL SYLLABLE BWAEGS
+BD30;BD30;1107 116B 11AB;BD30;1107 116B 11AB; # (봰; 봰; 봰; 봰; 봰; ) HANGUL SYLLABLE BWAEN
+BD31;BD31;1107 116B 11AC;BD31;1107 116B 11AC; # (봱; 봱; 봱; 봱; 봱; ) HANGUL SYLLABLE BWAENJ
+BD32;BD32;1107 116B 11AD;BD32;1107 116B 11AD; # (봲; 봲; 봲; 봲; 봲; ) HANGUL SYLLABLE BWAENH
+BD33;BD33;1107 116B 11AE;BD33;1107 116B 11AE; # (봳; 봳; 봳; 봳; 봳; ) HANGUL SYLLABLE BWAED
+BD34;BD34;1107 116B 11AF;BD34;1107 116B 11AF; # (봴; 봴; 봴; 봴; 봴; ) HANGUL SYLLABLE BWAEL
+BD35;BD35;1107 116B 11B0;BD35;1107 116B 11B0; # (봵; 봵; 봵; 봵; 봵; ) HANGUL SYLLABLE BWAELG
+BD36;BD36;1107 116B 11B1;BD36;1107 116B 11B1; # (봶; 봶; 봶; 봶; 봶; ) HANGUL SYLLABLE BWAELM
+BD37;BD37;1107 116B 11B2;BD37;1107 116B 11B2; # (봷; 봷; 봷; 봷; 봷; ) HANGUL SYLLABLE BWAELB
+BD38;BD38;1107 116B 11B3;BD38;1107 116B 11B3; # (봸; 봸; 봸; 봸; 봸; ) HANGUL SYLLABLE BWAELS
+BD39;BD39;1107 116B 11B4;BD39;1107 116B 11B4; # (봹; 봹; 봹; 봹; 봹; ) HANGUL SYLLABLE BWAELT
+BD3A;BD3A;1107 116B 11B5;BD3A;1107 116B 11B5; # (봺; 봺; 봺; 봺; 봺; ) HANGUL SYLLABLE BWAELP
+BD3B;BD3B;1107 116B 11B6;BD3B;1107 116B 11B6; # (봻; 봻; 봻; 봻; 봻; ) HANGUL SYLLABLE BWAELH
+BD3C;BD3C;1107 116B 11B7;BD3C;1107 116B 11B7; # (봼; 봼; 봼; 봼; 봼; ) HANGUL SYLLABLE BWAEM
+BD3D;BD3D;1107 116B 11B8;BD3D;1107 116B 11B8; # (봽; 봽; 봽; 봽; 봽; ) HANGUL SYLLABLE BWAEB
+BD3E;BD3E;1107 116B 11B9;BD3E;1107 116B 11B9; # (봾; 봾; 봾; 봾; 봾; ) HANGUL SYLLABLE BWAEBS
+BD3F;BD3F;1107 116B 11BA;BD3F;1107 116B 11BA; # (봿; 봿; 봿; 봿; 봿; ) HANGUL SYLLABLE BWAES
+BD40;BD40;1107 116B 11BB;BD40;1107 116B 11BB; # (뵀; 뵀; 뵀; 뵀; 뵀; ) HANGUL SYLLABLE BWAESS
+BD41;BD41;1107 116B 11BC;BD41;1107 116B 11BC; # (뵁; 뵁; 뵁; 뵁; 뵁; ) HANGUL SYLLABLE BWAENG
+BD42;BD42;1107 116B 11BD;BD42;1107 116B 11BD; # (뵂; 뵂; 뵂; 뵂; 뵂; ) HANGUL SYLLABLE BWAEJ
+BD43;BD43;1107 116B 11BE;BD43;1107 116B 11BE; # (뵃; 뵃; 뵃; 뵃; 뵃; ) HANGUL SYLLABLE BWAEC
+BD44;BD44;1107 116B 11BF;BD44;1107 116B 11BF; # (뵄; 뵄; 뵄; 뵄; 뵄; ) HANGUL SYLLABLE BWAEK
+BD45;BD45;1107 116B 11C0;BD45;1107 116B 11C0; # (뵅; 뵅; 뵅; 뵅; 뵅; ) HANGUL SYLLABLE BWAET
+BD46;BD46;1107 116B 11C1;BD46;1107 116B 11C1; # (뵆; 뵆; 뵆; 뵆; 뵆; ) HANGUL SYLLABLE BWAEP
+BD47;BD47;1107 116B 11C2;BD47;1107 116B 11C2; # (뵇; 뵇; 뵇; 뵇; 뵇; ) HANGUL SYLLABLE BWAEH
+BD48;BD48;1107 116C;BD48;1107 116C; # (뵈; 뵈; 뵈; 뵈; 뵈; ) HANGUL SYLLABLE BOE
+BD49;BD49;1107 116C 11A8;BD49;1107 116C 11A8; # (뵉; 뵉; 뵉; 뵉; 뵉; ) HANGUL SYLLABLE BOEG
+BD4A;BD4A;1107 116C 11A9;BD4A;1107 116C 11A9; # (뵊; 뵊; 뵊; 뵊; 뵊; ) HANGUL SYLLABLE BOEGG
+BD4B;BD4B;1107 116C 11AA;BD4B;1107 116C 11AA; # (뵋; 뵋; 뵋; 뵋; 뵋; ) HANGUL SYLLABLE BOEGS
+BD4C;BD4C;1107 116C 11AB;BD4C;1107 116C 11AB; # (뵌; 뵌; 뵌; 뵌; 뵌; ) HANGUL SYLLABLE BOEN
+BD4D;BD4D;1107 116C 11AC;BD4D;1107 116C 11AC; # (뵍; 뵍; 뵍; 뵍; 뵍; ) HANGUL SYLLABLE BOENJ
+BD4E;BD4E;1107 116C 11AD;BD4E;1107 116C 11AD; # (뵎; 뵎; 뵎; 뵎; 뵎; ) HANGUL SYLLABLE BOENH
+BD4F;BD4F;1107 116C 11AE;BD4F;1107 116C 11AE; # (뵏; 뵏; 뵏; 뵏; 뵏; ) HANGUL SYLLABLE BOED
+BD50;BD50;1107 116C 11AF;BD50;1107 116C 11AF; # (뵐; 뵐; 뵐; 뵐; 뵐; ) HANGUL SYLLABLE BOEL
+BD51;BD51;1107 116C 11B0;BD51;1107 116C 11B0; # (뵑; 뵑; 뵑; 뵑; 뵑; ) HANGUL SYLLABLE BOELG
+BD52;BD52;1107 116C 11B1;BD52;1107 116C 11B1; # (뵒; 뵒; 뵒; 뵒; 뵒; ) HANGUL SYLLABLE BOELM
+BD53;BD53;1107 116C 11B2;BD53;1107 116C 11B2; # (뵓; 뵓; 뵓; 뵓; 뵓; ) HANGUL SYLLABLE BOELB
+BD54;BD54;1107 116C 11B3;BD54;1107 116C 11B3; # (뵔; 뵔; 뵔; 뵔; 뵔; ) HANGUL SYLLABLE BOELS
+BD55;BD55;1107 116C 11B4;BD55;1107 116C 11B4; # (뵕; 뵕; 뵕; 뵕; 뵕; ) HANGUL SYLLABLE BOELT
+BD56;BD56;1107 116C 11B5;BD56;1107 116C 11B5; # (뵖; 뵖; 뵖; 뵖; 뵖; ) HANGUL SYLLABLE BOELP
+BD57;BD57;1107 116C 11B6;BD57;1107 116C 11B6; # (뵗; 뵗; 뵗; 뵗; 뵗; ) HANGUL SYLLABLE BOELH
+BD58;BD58;1107 116C 11B7;BD58;1107 116C 11B7; # (뵘; 뵘; 뵘; 뵘; 뵘; ) HANGUL SYLLABLE BOEM
+BD59;BD59;1107 116C 11B8;BD59;1107 116C 11B8; # (뵙; 뵙; 뵙; 뵙; 뵙; ) HANGUL SYLLABLE BOEB
+BD5A;BD5A;1107 116C 11B9;BD5A;1107 116C 11B9; # (뵚; 뵚; 뵚; 뵚; 뵚; ) HANGUL SYLLABLE BOEBS
+BD5B;BD5B;1107 116C 11BA;BD5B;1107 116C 11BA; # (뵛; 뵛; 뵛; 뵛; 뵛; ) HANGUL SYLLABLE BOES
+BD5C;BD5C;1107 116C 11BB;BD5C;1107 116C 11BB; # (뵜; 뵜; 뵜; 뵜; 뵜; ) HANGUL SYLLABLE BOESS
+BD5D;BD5D;1107 116C 11BC;BD5D;1107 116C 11BC; # (뵝; 뵝; 뵝; 뵝; 뵝; ) HANGUL SYLLABLE BOENG
+BD5E;BD5E;1107 116C 11BD;BD5E;1107 116C 11BD; # (뵞; 뵞; 뵞; 뵞; 뵞; ) HANGUL SYLLABLE BOEJ
+BD5F;BD5F;1107 116C 11BE;BD5F;1107 116C 11BE; # (뵟; 뵟; 뵟; 뵟; 뵟; ) HANGUL SYLLABLE BOEC
+BD60;BD60;1107 116C 11BF;BD60;1107 116C 11BF; # (뵠; 뵠; 뵠; 뵠; 뵠; ) HANGUL SYLLABLE BOEK
+BD61;BD61;1107 116C 11C0;BD61;1107 116C 11C0; # (뵡; 뵡; 뵡; 뵡; 뵡; ) HANGUL SYLLABLE BOET
+BD62;BD62;1107 116C 11C1;BD62;1107 116C 11C1; # (뵢; 뵢; 뵢; 뵢; 뵢; ) HANGUL SYLLABLE BOEP
+BD63;BD63;1107 116C 11C2;BD63;1107 116C 11C2; # (뵣; 뵣; 뵣; 뵣; 뵣; ) HANGUL SYLLABLE BOEH
+BD64;BD64;1107 116D;BD64;1107 116D; # (뵤; 뵤; 뵤; 뵤; 뵤; ) HANGUL SYLLABLE BYO
+BD65;BD65;1107 116D 11A8;BD65;1107 116D 11A8; # (뵥; 뵥; 뵥; 뵥; 뵥; ) HANGUL SYLLABLE BYOG
+BD66;BD66;1107 116D 11A9;BD66;1107 116D 11A9; # (뵦; 뵦; 뵦; 뵦; 뵦; ) HANGUL SYLLABLE BYOGG
+BD67;BD67;1107 116D 11AA;BD67;1107 116D 11AA; # (뵧; 뵧; 뵧; 뵧; 뵧; ) HANGUL SYLLABLE BYOGS
+BD68;BD68;1107 116D 11AB;BD68;1107 116D 11AB; # (뵨; 뵨; 뵨; 뵨; 뵨; ) HANGUL SYLLABLE BYON
+BD69;BD69;1107 116D 11AC;BD69;1107 116D 11AC; # (뵩; 뵩; 뵩; 뵩; 뵩; ) HANGUL SYLLABLE BYONJ
+BD6A;BD6A;1107 116D 11AD;BD6A;1107 116D 11AD; # (뵪; 뵪; 뵪; 뵪; 뵪; ) HANGUL SYLLABLE BYONH
+BD6B;BD6B;1107 116D 11AE;BD6B;1107 116D 11AE; # (뵫; 뵫; 뵫; 뵫; 뵫; ) HANGUL SYLLABLE BYOD
+BD6C;BD6C;1107 116D 11AF;BD6C;1107 116D 11AF; # (뵬; 뵬; 뵬; 뵬; 뵬; ) HANGUL SYLLABLE BYOL
+BD6D;BD6D;1107 116D 11B0;BD6D;1107 116D 11B0; # (뵭; 뵭; 뵭; 뵭; 뵭; ) HANGUL SYLLABLE BYOLG
+BD6E;BD6E;1107 116D 11B1;BD6E;1107 116D 11B1; # (뵮; 뵮; 뵮; 뵮; 뵮; ) HANGUL SYLLABLE BYOLM
+BD6F;BD6F;1107 116D 11B2;BD6F;1107 116D 11B2; # (뵯; 뵯; 뵯; 뵯; 뵯; ) HANGUL SYLLABLE BYOLB
+BD70;BD70;1107 116D 11B3;BD70;1107 116D 11B3; # (뵰; 뵰; 뵰; 뵰; 뵰; ) HANGUL SYLLABLE BYOLS
+BD71;BD71;1107 116D 11B4;BD71;1107 116D 11B4; # (뵱; 뵱; 뵱; 뵱; 뵱; ) HANGUL SYLLABLE BYOLT
+BD72;BD72;1107 116D 11B5;BD72;1107 116D 11B5; # (뵲; 뵲; 뵲; 뵲; 뵲; ) HANGUL SYLLABLE BYOLP
+BD73;BD73;1107 116D 11B6;BD73;1107 116D 11B6; # (뵳; 뵳; 뵳; 뵳; 뵳; ) HANGUL SYLLABLE BYOLH
+BD74;BD74;1107 116D 11B7;BD74;1107 116D 11B7; # (뵴; 뵴; 뵴; 뵴; 뵴; ) HANGUL SYLLABLE BYOM
+BD75;BD75;1107 116D 11B8;BD75;1107 116D 11B8; # (뵵; 뵵; 뵵; 뵵; 뵵; ) HANGUL SYLLABLE BYOB
+BD76;BD76;1107 116D 11B9;BD76;1107 116D 11B9; # (뵶; 뵶; 뵶; 뵶; 뵶; ) HANGUL SYLLABLE BYOBS
+BD77;BD77;1107 116D 11BA;BD77;1107 116D 11BA; # (뵷; 뵷; 뵷; 뵷; 뵷; ) HANGUL SYLLABLE BYOS
+BD78;BD78;1107 116D 11BB;BD78;1107 116D 11BB; # (뵸; 뵸; 뵸; 뵸; 뵸; ) HANGUL SYLLABLE BYOSS
+BD79;BD79;1107 116D 11BC;BD79;1107 116D 11BC; # (뵹; 뵹; 뵹; 뵹; 뵹; ) HANGUL SYLLABLE BYONG
+BD7A;BD7A;1107 116D 11BD;BD7A;1107 116D 11BD; # (뵺; 뵺; 뵺; 뵺; 뵺; ) HANGUL SYLLABLE BYOJ
+BD7B;BD7B;1107 116D 11BE;BD7B;1107 116D 11BE; # (뵻; 뵻; 뵻; 뵻; 뵻; ) HANGUL SYLLABLE BYOC
+BD7C;BD7C;1107 116D 11BF;BD7C;1107 116D 11BF; # (뵼; 뵼; 뵼; 뵼; 뵼; ) HANGUL SYLLABLE BYOK
+BD7D;BD7D;1107 116D 11C0;BD7D;1107 116D 11C0; # (뵽; 뵽; 뵽; 뵽; 뵽; ) HANGUL SYLLABLE BYOT
+BD7E;BD7E;1107 116D 11C1;BD7E;1107 116D 11C1; # (뵾; 뵾; 뵾; 뵾; 뵾; ) HANGUL SYLLABLE BYOP
+BD7F;BD7F;1107 116D 11C2;BD7F;1107 116D 11C2; # (뵿; 뵿; 뵿; 뵿; 뵿; ) HANGUL SYLLABLE BYOH
+BD80;BD80;1107 116E;BD80;1107 116E; # (부; 부; 부; 부; 부; ) HANGUL SYLLABLE BU
+BD81;BD81;1107 116E 11A8;BD81;1107 116E 11A8; # (북; 북; 북; 북; 북; ) HANGUL SYLLABLE BUG
+BD82;BD82;1107 116E 11A9;BD82;1107 116E 11A9; # (붂; 붂; 붂; 붂; 붂; ) HANGUL SYLLABLE BUGG
+BD83;BD83;1107 116E 11AA;BD83;1107 116E 11AA; # (붃; 붃; 붃; 붃; 붃; ) HANGUL SYLLABLE BUGS
+BD84;BD84;1107 116E 11AB;BD84;1107 116E 11AB; # (분; 분; 분; 분; 분; ) HANGUL SYLLABLE BUN
+BD85;BD85;1107 116E 11AC;BD85;1107 116E 11AC; # (붅; 붅; 붅; 붅; 붅; ) HANGUL SYLLABLE BUNJ
+BD86;BD86;1107 116E 11AD;BD86;1107 116E 11AD; # (붆; 붆; 붆; 붆; 붆; ) HANGUL SYLLABLE BUNH
+BD87;BD87;1107 116E 11AE;BD87;1107 116E 11AE; # (붇; 붇; 붇; 붇; 붇; ) HANGUL SYLLABLE BUD
+BD88;BD88;1107 116E 11AF;BD88;1107 116E 11AF; # (불; 불; 불; 불; 불; ) HANGUL SYLLABLE BUL
+BD89;BD89;1107 116E 11B0;BD89;1107 116E 11B0; # (붉; 붉; 붉; 붉; 붉; ) HANGUL SYLLABLE BULG
+BD8A;BD8A;1107 116E 11B1;BD8A;1107 116E 11B1; # (붊; 붊; 붊; 붊; 붊; ) HANGUL SYLLABLE BULM
+BD8B;BD8B;1107 116E 11B2;BD8B;1107 116E 11B2; # (붋; 붋; 붋; 붋; 붋; ) HANGUL SYLLABLE BULB
+BD8C;BD8C;1107 116E 11B3;BD8C;1107 116E 11B3; # (붌; 붌; 붌; 붌; 붌; ) HANGUL SYLLABLE BULS
+BD8D;BD8D;1107 116E 11B4;BD8D;1107 116E 11B4; # (붍; 붍; 붍; 붍; 붍; ) HANGUL SYLLABLE BULT
+BD8E;BD8E;1107 116E 11B5;BD8E;1107 116E 11B5; # (붎; 붎; 붎; 붎; 붎; ) HANGUL SYLLABLE BULP
+BD8F;BD8F;1107 116E 11B6;BD8F;1107 116E 11B6; # (붏; 붏; 붏; 붏; 붏; ) HANGUL SYLLABLE BULH
+BD90;BD90;1107 116E 11B7;BD90;1107 116E 11B7; # (붐; 붐; 붐; 붐; 붐; ) HANGUL SYLLABLE BUM
+BD91;BD91;1107 116E 11B8;BD91;1107 116E 11B8; # (붑; 붑; 붑; 붑; 붑; ) HANGUL SYLLABLE BUB
+BD92;BD92;1107 116E 11B9;BD92;1107 116E 11B9; # (붒; 붒; 붒; 붒; 붒; ) HANGUL SYLLABLE BUBS
+BD93;BD93;1107 116E 11BA;BD93;1107 116E 11BA; # (붓; 붓; 붓; 붓; 붓; ) HANGUL SYLLABLE BUS
+BD94;BD94;1107 116E 11BB;BD94;1107 116E 11BB; # (붔; 붔; 붔; 붔; 붔; ) HANGUL SYLLABLE BUSS
+BD95;BD95;1107 116E 11BC;BD95;1107 116E 11BC; # (붕; 붕; 붕; 붕; 붕; ) HANGUL SYLLABLE BUNG
+BD96;BD96;1107 116E 11BD;BD96;1107 116E 11BD; # (붖; 붖; 붖; 붖; 붖; ) HANGUL SYLLABLE BUJ
+BD97;BD97;1107 116E 11BE;BD97;1107 116E 11BE; # (붗; 붗; 붗; 붗; 붗; ) HANGUL SYLLABLE BUC
+BD98;BD98;1107 116E 11BF;BD98;1107 116E 11BF; # (붘; 붘; 붘; 붘; 붘; ) HANGUL SYLLABLE BUK
+BD99;BD99;1107 116E 11C0;BD99;1107 116E 11C0; # (붙; 붙; 붙; 붙; 붙; ) HANGUL SYLLABLE BUT
+BD9A;BD9A;1107 116E 11C1;BD9A;1107 116E 11C1; # (붚; 붚; 붚; 붚; 붚; ) HANGUL SYLLABLE BUP
+BD9B;BD9B;1107 116E 11C2;BD9B;1107 116E 11C2; # (붛; 붛; 붛; 붛; 붛; ) HANGUL SYLLABLE BUH
+BD9C;BD9C;1107 116F;BD9C;1107 116F; # (붜; 붜; 붜; 붜; 붜; ) HANGUL SYLLABLE BWEO
+BD9D;BD9D;1107 116F 11A8;BD9D;1107 116F 11A8; # (붝; 붝; 붝; 붝; 붝; ) HANGUL SYLLABLE BWEOG
+BD9E;BD9E;1107 116F 11A9;BD9E;1107 116F 11A9; # (붞; 붞; 붞; 붞; 붞; ) HANGUL SYLLABLE BWEOGG
+BD9F;BD9F;1107 116F 11AA;BD9F;1107 116F 11AA; # (붟; 붟; 붟; 붟; 붟; ) HANGUL SYLLABLE BWEOGS
+BDA0;BDA0;1107 116F 11AB;BDA0;1107 116F 11AB; # (붠; 붠; 붠; 붠; 붠; ) HANGUL SYLLABLE BWEON
+BDA1;BDA1;1107 116F 11AC;BDA1;1107 116F 11AC; # (붡; 붡; 붡; 붡; 붡; ) HANGUL SYLLABLE BWEONJ
+BDA2;BDA2;1107 116F 11AD;BDA2;1107 116F 11AD; # (붢; 붢; 붢; 붢; 붢; ) HANGUL SYLLABLE BWEONH
+BDA3;BDA3;1107 116F 11AE;BDA3;1107 116F 11AE; # (붣; 붣; 붣; 붣; 붣; ) HANGUL SYLLABLE BWEOD
+BDA4;BDA4;1107 116F 11AF;BDA4;1107 116F 11AF; # (붤; 붤; 붤; 붤; 붤; ) HANGUL SYLLABLE BWEOL
+BDA5;BDA5;1107 116F 11B0;BDA5;1107 116F 11B0; # (붥; 붥; 붥; 붥; 붥; ) HANGUL SYLLABLE BWEOLG
+BDA6;BDA6;1107 116F 11B1;BDA6;1107 116F 11B1; # (붦; 붦; 붦; 붦; 붦; ) HANGUL SYLLABLE BWEOLM
+BDA7;BDA7;1107 116F 11B2;BDA7;1107 116F 11B2; # (붧; 붧; 붧; 붧; 붧; ) HANGUL SYLLABLE BWEOLB
+BDA8;BDA8;1107 116F 11B3;BDA8;1107 116F 11B3; # (붨; 붨; 붨; 붨; 붨; ) HANGUL SYLLABLE BWEOLS
+BDA9;BDA9;1107 116F 11B4;BDA9;1107 116F 11B4; # (붩; 붩; 붩; 붩; 붩; ) HANGUL SYLLABLE BWEOLT
+BDAA;BDAA;1107 116F 11B5;BDAA;1107 116F 11B5; # (붪; 붪; 붪; 붪; 붪; ) HANGUL SYLLABLE BWEOLP
+BDAB;BDAB;1107 116F 11B6;BDAB;1107 116F 11B6; # (붫; 붫; 붫; 붫; 붫; ) HANGUL SYLLABLE BWEOLH
+BDAC;BDAC;1107 116F 11B7;BDAC;1107 116F 11B7; # (붬; 붬; 붬; 붬; 붬; ) HANGUL SYLLABLE BWEOM
+BDAD;BDAD;1107 116F 11B8;BDAD;1107 116F 11B8; # (붭; 붭; 붭; 붭; 붭; ) HANGUL SYLLABLE BWEOB
+BDAE;BDAE;1107 116F 11B9;BDAE;1107 116F 11B9; # (붮; 붮; 붮; 붮; 붮; ) HANGUL SYLLABLE BWEOBS
+BDAF;BDAF;1107 116F 11BA;BDAF;1107 116F 11BA; # (붯; 붯; 붯; 붯; 붯; ) HANGUL SYLLABLE BWEOS
+BDB0;BDB0;1107 116F 11BB;BDB0;1107 116F 11BB; # (붰; 붰; 붰; 붰; 붰; ) HANGUL SYLLABLE BWEOSS
+BDB1;BDB1;1107 116F 11BC;BDB1;1107 116F 11BC; # (붱; 붱; 붱; 붱; 붱; ) HANGUL SYLLABLE BWEONG
+BDB2;BDB2;1107 116F 11BD;BDB2;1107 116F 11BD; # (붲; 붲; 붲; 붲; 붲; ) HANGUL SYLLABLE BWEOJ
+BDB3;BDB3;1107 116F 11BE;BDB3;1107 116F 11BE; # (붳; 붳; 붳; 붳; 붳; ) HANGUL SYLLABLE BWEOC
+BDB4;BDB4;1107 116F 11BF;BDB4;1107 116F 11BF; # (붴; 붴; 붴; 붴; 붴; ) HANGUL SYLLABLE BWEOK
+BDB5;BDB5;1107 116F 11C0;BDB5;1107 116F 11C0; # (붵; 붵; 붵; 붵; 붵; ) HANGUL SYLLABLE BWEOT
+BDB6;BDB6;1107 116F 11C1;BDB6;1107 116F 11C1; # (붶; 붶; 붶; 붶; 붶; ) HANGUL SYLLABLE BWEOP
+BDB7;BDB7;1107 116F 11C2;BDB7;1107 116F 11C2; # (붷; 붷; 붷; 붷; 붷; ) HANGUL SYLLABLE BWEOH
+BDB8;BDB8;1107 1170;BDB8;1107 1170; # (붸; 붸; 붸; 붸; 붸; ) HANGUL SYLLABLE BWE
+BDB9;BDB9;1107 1170 11A8;BDB9;1107 1170 11A8; # (붹; 붹; 붹; 붹; 붹; ) HANGUL SYLLABLE BWEG
+BDBA;BDBA;1107 1170 11A9;BDBA;1107 1170 11A9; # (붺; 붺; 붺; 붺; 붺; ) HANGUL SYLLABLE BWEGG
+BDBB;BDBB;1107 1170 11AA;BDBB;1107 1170 11AA; # (붻; 붻; 붻; 붻; 붻; ) HANGUL SYLLABLE BWEGS
+BDBC;BDBC;1107 1170 11AB;BDBC;1107 1170 11AB; # (붼; 붼; 붼; 붼; 붼; ) HANGUL SYLLABLE BWEN
+BDBD;BDBD;1107 1170 11AC;BDBD;1107 1170 11AC; # (붽; 붽; 붽; 붽; 붽; ) HANGUL SYLLABLE BWENJ
+BDBE;BDBE;1107 1170 11AD;BDBE;1107 1170 11AD; # (붾; 붾; 붾; 붾; 붾; ) HANGUL SYLLABLE BWENH
+BDBF;BDBF;1107 1170 11AE;BDBF;1107 1170 11AE; # (붿; 붿; 붿; 붿; 붿; ) HANGUL SYLLABLE BWED
+BDC0;BDC0;1107 1170 11AF;BDC0;1107 1170 11AF; # (뷀; 뷀; 뷀; 뷀; 뷀; ) HANGUL SYLLABLE BWEL
+BDC1;BDC1;1107 1170 11B0;BDC1;1107 1170 11B0; # (뷁; 뷁; 뷁; 뷁; 뷁; ) HANGUL SYLLABLE BWELG
+BDC2;BDC2;1107 1170 11B1;BDC2;1107 1170 11B1; # (뷂; 뷂; 뷂; 뷂; 뷂; ) HANGUL SYLLABLE BWELM
+BDC3;BDC3;1107 1170 11B2;BDC3;1107 1170 11B2; # (뷃; 뷃; 뷃; 뷃; 뷃; ) HANGUL SYLLABLE BWELB
+BDC4;BDC4;1107 1170 11B3;BDC4;1107 1170 11B3; # (뷄; 뷄; 뷄; 뷄; 뷄; ) HANGUL SYLLABLE BWELS
+BDC5;BDC5;1107 1170 11B4;BDC5;1107 1170 11B4; # (뷅; 뷅; 뷅; 뷅; 뷅; ) HANGUL SYLLABLE BWELT
+BDC6;BDC6;1107 1170 11B5;BDC6;1107 1170 11B5; # (뷆; 뷆; 뷆; 뷆; 뷆; ) HANGUL SYLLABLE BWELP
+BDC7;BDC7;1107 1170 11B6;BDC7;1107 1170 11B6; # (뷇; 뷇; 뷇; 뷇; 뷇; ) HANGUL SYLLABLE BWELH
+BDC8;BDC8;1107 1170 11B7;BDC8;1107 1170 11B7; # (뷈; 뷈; 뷈; 뷈; 뷈; ) HANGUL SYLLABLE BWEM
+BDC9;BDC9;1107 1170 11B8;BDC9;1107 1170 11B8; # (뷉; 뷉; 뷉; 뷉; 뷉; ) HANGUL SYLLABLE BWEB
+BDCA;BDCA;1107 1170 11B9;BDCA;1107 1170 11B9; # (뷊; 뷊; 뷊; 뷊; 뷊; ) HANGUL SYLLABLE BWEBS
+BDCB;BDCB;1107 1170 11BA;BDCB;1107 1170 11BA; # (뷋; 뷋; 뷋; 뷋; 뷋; ) HANGUL SYLLABLE BWES
+BDCC;BDCC;1107 1170 11BB;BDCC;1107 1170 11BB; # (뷌; 뷌; 뷌; 뷌; 뷌; ) HANGUL SYLLABLE BWESS
+BDCD;BDCD;1107 1170 11BC;BDCD;1107 1170 11BC; # (뷍; 뷍; 뷍; 뷍; 뷍; ) HANGUL SYLLABLE BWENG
+BDCE;BDCE;1107 1170 11BD;BDCE;1107 1170 11BD; # (뷎; 뷎; 뷎; 뷎; 뷎; ) HANGUL SYLLABLE BWEJ
+BDCF;BDCF;1107 1170 11BE;BDCF;1107 1170 11BE; # (뷏; 뷏; 뷏; 뷏; 뷏; ) HANGUL SYLLABLE BWEC
+BDD0;BDD0;1107 1170 11BF;BDD0;1107 1170 11BF; # (뷐; 뷐; 뷐; 뷐; 뷐; ) HANGUL SYLLABLE BWEK
+BDD1;BDD1;1107 1170 11C0;BDD1;1107 1170 11C0; # (뷑; 뷑; 뷑; 뷑; 뷑; ) HANGUL SYLLABLE BWET
+BDD2;BDD2;1107 1170 11C1;BDD2;1107 1170 11C1; # (뷒; 뷒; 뷒; 뷒; 뷒; ) HANGUL SYLLABLE BWEP
+BDD3;BDD3;1107 1170 11C2;BDD3;1107 1170 11C2; # (뷓; 뷓; 뷓; 뷓; 뷓; ) HANGUL SYLLABLE BWEH
+BDD4;BDD4;1107 1171;BDD4;1107 1171; # (뷔; 뷔; 뷔; 뷔; 뷔; ) HANGUL SYLLABLE BWI
+BDD5;BDD5;1107 1171 11A8;BDD5;1107 1171 11A8; # (뷕; 뷕; 뷕; 뷕; 뷕; ) HANGUL SYLLABLE BWIG
+BDD6;BDD6;1107 1171 11A9;BDD6;1107 1171 11A9; # (뷖; 뷖; 뷖; 뷖; 뷖; ) HANGUL SYLLABLE BWIGG
+BDD7;BDD7;1107 1171 11AA;BDD7;1107 1171 11AA; # (뷗; 뷗; 뷗; 뷗; 뷗; ) HANGUL SYLLABLE BWIGS
+BDD8;BDD8;1107 1171 11AB;BDD8;1107 1171 11AB; # (뷘; 뷘; 뷘; 뷘; 뷘; ) HANGUL SYLLABLE BWIN
+BDD9;BDD9;1107 1171 11AC;BDD9;1107 1171 11AC; # (뷙; 뷙; 뷙; 뷙; 뷙; ) HANGUL SYLLABLE BWINJ
+BDDA;BDDA;1107 1171 11AD;BDDA;1107 1171 11AD; # (뷚; 뷚; 뷚; 뷚; 뷚; ) HANGUL SYLLABLE BWINH
+BDDB;BDDB;1107 1171 11AE;BDDB;1107 1171 11AE; # (뷛; 뷛; 뷛; 뷛; 뷛; ) HANGUL SYLLABLE BWID
+BDDC;BDDC;1107 1171 11AF;BDDC;1107 1171 11AF; # (뷜; 뷜; 뷜; 뷜; 뷜; ) HANGUL SYLLABLE BWIL
+BDDD;BDDD;1107 1171 11B0;BDDD;1107 1171 11B0; # (뷝; 뷝; 뷝; 뷝; 뷝; ) HANGUL SYLLABLE BWILG
+BDDE;BDDE;1107 1171 11B1;BDDE;1107 1171 11B1; # (뷞; 뷞; 뷞; 뷞; 뷞; ) HANGUL SYLLABLE BWILM
+BDDF;BDDF;1107 1171 11B2;BDDF;1107 1171 11B2; # (뷟; 뷟; 뷟; 뷟; 뷟; ) HANGUL SYLLABLE BWILB
+BDE0;BDE0;1107 1171 11B3;BDE0;1107 1171 11B3; # (뷠; 뷠; 뷠; 뷠; 뷠; ) HANGUL SYLLABLE BWILS
+BDE1;BDE1;1107 1171 11B4;BDE1;1107 1171 11B4; # (뷡; 뷡; 뷡; 뷡; 뷡; ) HANGUL SYLLABLE BWILT
+BDE2;BDE2;1107 1171 11B5;BDE2;1107 1171 11B5; # (뷢; 뷢; 뷢; 뷢; 뷢; ) HANGUL SYLLABLE BWILP
+BDE3;BDE3;1107 1171 11B6;BDE3;1107 1171 11B6; # (뷣; 뷣; 뷣; 뷣; 뷣; ) HANGUL SYLLABLE BWILH
+BDE4;BDE4;1107 1171 11B7;BDE4;1107 1171 11B7; # (뷤; 뷤; 뷤; 뷤; 뷤; ) HANGUL SYLLABLE BWIM
+BDE5;BDE5;1107 1171 11B8;BDE5;1107 1171 11B8; # (뷥; 뷥; 뷥; 뷥; 뷥; ) HANGUL SYLLABLE BWIB
+BDE6;BDE6;1107 1171 11B9;BDE6;1107 1171 11B9; # (뷦; 뷦; 뷦; 뷦; 뷦; ) HANGUL SYLLABLE BWIBS
+BDE7;BDE7;1107 1171 11BA;BDE7;1107 1171 11BA; # (뷧; 뷧; 뷧; 뷧; 뷧; ) HANGUL SYLLABLE BWIS
+BDE8;BDE8;1107 1171 11BB;BDE8;1107 1171 11BB; # (뷨; 뷨; 뷨; 뷨; 뷨; ) HANGUL SYLLABLE BWISS
+BDE9;BDE9;1107 1171 11BC;BDE9;1107 1171 11BC; # (뷩; 뷩; 뷩; 뷩; 뷩; ) HANGUL SYLLABLE BWING
+BDEA;BDEA;1107 1171 11BD;BDEA;1107 1171 11BD; # (뷪; 뷪; 뷪; 뷪; 뷪; ) HANGUL SYLLABLE BWIJ
+BDEB;BDEB;1107 1171 11BE;BDEB;1107 1171 11BE; # (뷫; 뷫; 뷫; 뷫; 뷫; ) HANGUL SYLLABLE BWIC
+BDEC;BDEC;1107 1171 11BF;BDEC;1107 1171 11BF; # (뷬; 뷬; 뷬; 뷬; 뷬; ) HANGUL SYLLABLE BWIK
+BDED;BDED;1107 1171 11C0;BDED;1107 1171 11C0; # (뷭; 뷭; 뷭; 뷭; 뷭; ) HANGUL SYLLABLE BWIT
+BDEE;BDEE;1107 1171 11C1;BDEE;1107 1171 11C1; # (뷮; 뷮; 뷮; 뷮; 뷮; ) HANGUL SYLLABLE BWIP
+BDEF;BDEF;1107 1171 11C2;BDEF;1107 1171 11C2; # (뷯; 뷯; 뷯; 뷯; 뷯; ) HANGUL SYLLABLE BWIH
+BDF0;BDF0;1107 1172;BDF0;1107 1172; # (뷰; 뷰; 뷰; 뷰; 뷰; ) HANGUL SYLLABLE BYU
+BDF1;BDF1;1107 1172 11A8;BDF1;1107 1172 11A8; # (뷱; 뷱; 뷱; 뷱; 뷱; ) HANGUL SYLLABLE BYUG
+BDF2;BDF2;1107 1172 11A9;BDF2;1107 1172 11A9; # (뷲; 뷲; 뷲; 뷲; 뷲; ) HANGUL SYLLABLE BYUGG
+BDF3;BDF3;1107 1172 11AA;BDF3;1107 1172 11AA; # (뷳; 뷳; 뷳; 뷳; 뷳; ) HANGUL SYLLABLE BYUGS
+BDF4;BDF4;1107 1172 11AB;BDF4;1107 1172 11AB; # (뷴; 뷴; 뷴; 뷴; 뷴; ) HANGUL SYLLABLE BYUN
+BDF5;BDF5;1107 1172 11AC;BDF5;1107 1172 11AC; # (뷵; 뷵; 뷵; 뷵; 뷵; ) HANGUL SYLLABLE BYUNJ
+BDF6;BDF6;1107 1172 11AD;BDF6;1107 1172 11AD; # (뷶; 뷶; 뷶; 뷶; 뷶; ) HANGUL SYLLABLE BYUNH
+BDF7;BDF7;1107 1172 11AE;BDF7;1107 1172 11AE; # (뷷; 뷷; 뷷; 뷷; 뷷; ) HANGUL SYLLABLE BYUD
+BDF8;BDF8;1107 1172 11AF;BDF8;1107 1172 11AF; # (뷸; 뷸; 뷸; 뷸; 뷸; ) HANGUL SYLLABLE BYUL
+BDF9;BDF9;1107 1172 11B0;BDF9;1107 1172 11B0; # (뷹; 뷹; 뷹; 뷹; 뷹; ) HANGUL SYLLABLE BYULG
+BDFA;BDFA;1107 1172 11B1;BDFA;1107 1172 11B1; # (뷺; 뷺; 뷺; 뷺; 뷺; ) HANGUL SYLLABLE BYULM
+BDFB;BDFB;1107 1172 11B2;BDFB;1107 1172 11B2; # (뷻; 뷻; 뷻; 뷻; 뷻; ) HANGUL SYLLABLE BYULB
+BDFC;BDFC;1107 1172 11B3;BDFC;1107 1172 11B3; # (뷼; 뷼; 뷼; 뷼; 뷼; ) HANGUL SYLLABLE BYULS
+BDFD;BDFD;1107 1172 11B4;BDFD;1107 1172 11B4; # (뷽; 뷽; 뷽; 뷽; 뷽; ) HANGUL SYLLABLE BYULT
+BDFE;BDFE;1107 1172 11B5;BDFE;1107 1172 11B5; # (뷾; 뷾; 뷾; 뷾; 뷾; ) HANGUL SYLLABLE BYULP
+BDFF;BDFF;1107 1172 11B6;BDFF;1107 1172 11B6; # (뷿; 뷿; 뷿; 뷿; 뷿; ) HANGUL SYLLABLE BYULH
+BE00;BE00;1107 1172 11B7;BE00;1107 1172 11B7; # (븀; 븀; 븀; 븀; 븀; ) HANGUL SYLLABLE BYUM
+BE01;BE01;1107 1172 11B8;BE01;1107 1172 11B8; # (븁; 븁; 븁; 븁; 븁; ) HANGUL SYLLABLE BYUB
+BE02;BE02;1107 1172 11B9;BE02;1107 1172 11B9; # (븂; 븂; 븂; 븂; 븂; ) HANGUL SYLLABLE BYUBS
+BE03;BE03;1107 1172 11BA;BE03;1107 1172 11BA; # (븃; 븃; 븃; 븃; 븃; ) HANGUL SYLLABLE BYUS
+BE04;BE04;1107 1172 11BB;BE04;1107 1172 11BB; # (븄; 븄; 븄; 븄; 븄; ) HANGUL SYLLABLE BYUSS
+BE05;BE05;1107 1172 11BC;BE05;1107 1172 11BC; # (븅; 븅; 븅; 븅; 븅; ) HANGUL SYLLABLE BYUNG
+BE06;BE06;1107 1172 11BD;BE06;1107 1172 11BD; # (븆; 븆; 븆; 븆; 븆; ) HANGUL SYLLABLE BYUJ
+BE07;BE07;1107 1172 11BE;BE07;1107 1172 11BE; # (븇; 븇; 븇; 븇; 븇; ) HANGUL SYLLABLE BYUC
+BE08;BE08;1107 1172 11BF;BE08;1107 1172 11BF; # (븈; 븈; 븈; 븈; 븈; ) HANGUL SYLLABLE BYUK
+BE09;BE09;1107 1172 11C0;BE09;1107 1172 11C0; # (븉; 븉; 븉; 븉; 븉; ) HANGUL SYLLABLE BYUT
+BE0A;BE0A;1107 1172 11C1;BE0A;1107 1172 11C1; # (븊; 븊; 븊; 븊; 븊; ) HANGUL SYLLABLE BYUP
+BE0B;BE0B;1107 1172 11C2;BE0B;1107 1172 11C2; # (븋; 븋; 븋; 븋; 븋; ) HANGUL SYLLABLE BYUH
+BE0C;BE0C;1107 1173;BE0C;1107 1173; # (브; 브; 브; 브; 브; ) HANGUL SYLLABLE BEU
+BE0D;BE0D;1107 1173 11A8;BE0D;1107 1173 11A8; # (븍; 븍; 븍; 븍; 븍; ) HANGUL SYLLABLE BEUG
+BE0E;BE0E;1107 1173 11A9;BE0E;1107 1173 11A9; # (븎; 븎; 븎; 븎; 븎; ) HANGUL SYLLABLE BEUGG
+BE0F;BE0F;1107 1173 11AA;BE0F;1107 1173 11AA; # (븏; 븏; 븏; 븏; 븏; ) HANGUL SYLLABLE BEUGS
+BE10;BE10;1107 1173 11AB;BE10;1107 1173 11AB; # (븐; 븐; 븐; 븐; 븐; ) HANGUL SYLLABLE BEUN
+BE11;BE11;1107 1173 11AC;BE11;1107 1173 11AC; # (븑; 븑; 븑; 븑; 븑; ) HANGUL SYLLABLE BEUNJ
+BE12;BE12;1107 1173 11AD;BE12;1107 1173 11AD; # (븒; 븒; 븒; 븒; 븒; ) HANGUL SYLLABLE BEUNH
+BE13;BE13;1107 1173 11AE;BE13;1107 1173 11AE; # (븓; 븓; 븓; 븓; 븓; ) HANGUL SYLLABLE BEUD
+BE14;BE14;1107 1173 11AF;BE14;1107 1173 11AF; # (블; 블; 블; 블; 블; ) HANGUL SYLLABLE BEUL
+BE15;BE15;1107 1173 11B0;BE15;1107 1173 11B0; # (븕; 븕; 븕; 븕; 븕; ) HANGUL SYLLABLE BEULG
+BE16;BE16;1107 1173 11B1;BE16;1107 1173 11B1; # (븖; 븖; 븖; 븖; 븖; ) HANGUL SYLLABLE BEULM
+BE17;BE17;1107 1173 11B2;BE17;1107 1173 11B2; # (븗; 븗; 븗; 븗; 븗; ) HANGUL SYLLABLE BEULB
+BE18;BE18;1107 1173 11B3;BE18;1107 1173 11B3; # (븘; 븘; 븘; 븘; 븘; ) HANGUL SYLLABLE BEULS
+BE19;BE19;1107 1173 11B4;BE19;1107 1173 11B4; # (븙; 븙; 븙; 븙; 븙; ) HANGUL SYLLABLE BEULT
+BE1A;BE1A;1107 1173 11B5;BE1A;1107 1173 11B5; # (븚; 븚; 븚; 븚; 븚; ) HANGUL SYLLABLE BEULP
+BE1B;BE1B;1107 1173 11B6;BE1B;1107 1173 11B6; # (븛; 븛; 븛; 븛; 븛; ) HANGUL SYLLABLE BEULH
+BE1C;BE1C;1107 1173 11B7;BE1C;1107 1173 11B7; # (븜; 븜; 븜; 븜; 븜; ) HANGUL SYLLABLE BEUM
+BE1D;BE1D;1107 1173 11B8;BE1D;1107 1173 11B8; # (븝; 븝; 븝; 븝; 븝; ) HANGUL SYLLABLE BEUB
+BE1E;BE1E;1107 1173 11B9;BE1E;1107 1173 11B9; # (븞; 븞; 븞; 븞; 븞; ) HANGUL SYLLABLE BEUBS
+BE1F;BE1F;1107 1173 11BA;BE1F;1107 1173 11BA; # (븟; 븟; 븟; 븟; 븟; ) HANGUL SYLLABLE BEUS
+BE20;BE20;1107 1173 11BB;BE20;1107 1173 11BB; # (븠; 븠; 븠; 븠; 븠; ) HANGUL SYLLABLE BEUSS
+BE21;BE21;1107 1173 11BC;BE21;1107 1173 11BC; # (븡; 븡; 븡; 븡; 븡; ) HANGUL SYLLABLE BEUNG
+BE22;BE22;1107 1173 11BD;BE22;1107 1173 11BD; # (븢; 븢; 븢; 븢; 븢; ) HANGUL SYLLABLE BEUJ
+BE23;BE23;1107 1173 11BE;BE23;1107 1173 11BE; # (븣; 븣; 븣; 븣; 븣; ) HANGUL SYLLABLE BEUC
+BE24;BE24;1107 1173 11BF;BE24;1107 1173 11BF; # (븤; 븤; 븤; 븤; 븤; ) HANGUL SYLLABLE BEUK
+BE25;BE25;1107 1173 11C0;BE25;1107 1173 11C0; # (븥; 븥; 븥; 븥; 븥; ) HANGUL SYLLABLE BEUT
+BE26;BE26;1107 1173 11C1;BE26;1107 1173 11C1; # (븦; 븦; 븦; 븦; 븦; ) HANGUL SYLLABLE BEUP
+BE27;BE27;1107 1173 11C2;BE27;1107 1173 11C2; # (븧; 븧; 븧; 븧; 븧; ) HANGUL SYLLABLE BEUH
+BE28;BE28;1107 1174;BE28;1107 1174; # (븨; 븨; 븨; 븨; 븨; ) HANGUL SYLLABLE BYI
+BE29;BE29;1107 1174 11A8;BE29;1107 1174 11A8; # (븩; 븩; 븩; 븩; 븩; ) HANGUL SYLLABLE BYIG
+BE2A;BE2A;1107 1174 11A9;BE2A;1107 1174 11A9; # (븪; 븪; 븪; 븪; 븪; ) HANGUL SYLLABLE BYIGG
+BE2B;BE2B;1107 1174 11AA;BE2B;1107 1174 11AA; # (븫; 븫; 븫; 븫; 븫; ) HANGUL SYLLABLE BYIGS
+BE2C;BE2C;1107 1174 11AB;BE2C;1107 1174 11AB; # (븬; 븬; 븬; 븬; 븬; ) HANGUL SYLLABLE BYIN
+BE2D;BE2D;1107 1174 11AC;BE2D;1107 1174 11AC; # (븭; 븭; 븭; 븭; 븭; ) HANGUL SYLLABLE BYINJ
+BE2E;BE2E;1107 1174 11AD;BE2E;1107 1174 11AD; # (븮; 븮; 븮; 븮; 븮; ) HANGUL SYLLABLE BYINH
+BE2F;BE2F;1107 1174 11AE;BE2F;1107 1174 11AE; # (븯; 븯; 븯; 븯; 븯; ) HANGUL SYLLABLE BYID
+BE30;BE30;1107 1174 11AF;BE30;1107 1174 11AF; # (븰; 븰; 븰; 븰; 븰; ) HANGUL SYLLABLE BYIL
+BE31;BE31;1107 1174 11B0;BE31;1107 1174 11B0; # (븱; 븱; 븱; 븱; 븱; ) HANGUL SYLLABLE BYILG
+BE32;BE32;1107 1174 11B1;BE32;1107 1174 11B1; # (븲; 븲; 븲; 븲; 븲; ) HANGUL SYLLABLE BYILM
+BE33;BE33;1107 1174 11B2;BE33;1107 1174 11B2; # (븳; 븳; 븳; 븳; 븳; ) HANGUL SYLLABLE BYILB
+BE34;BE34;1107 1174 11B3;BE34;1107 1174 11B3; # (븴; 븴; 븴; 븴; 븴; ) HANGUL SYLLABLE BYILS
+BE35;BE35;1107 1174 11B4;BE35;1107 1174 11B4; # (븵; 븵; 븵; 븵; 븵; ) HANGUL SYLLABLE BYILT
+BE36;BE36;1107 1174 11B5;BE36;1107 1174 11B5; # (븶; 븶; 븶; 븶; 븶; ) HANGUL SYLLABLE BYILP
+BE37;BE37;1107 1174 11B6;BE37;1107 1174 11B6; # (븷; 븷; 븷; 븷; 븷; ) HANGUL SYLLABLE BYILH
+BE38;BE38;1107 1174 11B7;BE38;1107 1174 11B7; # (븸; 븸; 븸; 븸; 븸; ) HANGUL SYLLABLE BYIM
+BE39;BE39;1107 1174 11B8;BE39;1107 1174 11B8; # (븹; 븹; 븹; 븹; 븹; ) HANGUL SYLLABLE BYIB
+BE3A;BE3A;1107 1174 11B9;BE3A;1107 1174 11B9; # (븺; 븺; 븺; 븺; 븺; ) HANGUL SYLLABLE BYIBS
+BE3B;BE3B;1107 1174 11BA;BE3B;1107 1174 11BA; # (븻; 븻; 븻; 븻; 븻; ) HANGUL SYLLABLE BYIS
+BE3C;BE3C;1107 1174 11BB;BE3C;1107 1174 11BB; # (븼; 븼; 븼; 븼; 븼; ) HANGUL SYLLABLE BYISS
+BE3D;BE3D;1107 1174 11BC;BE3D;1107 1174 11BC; # (븽; 븽; 븽; 븽; 븽; ) HANGUL SYLLABLE BYING
+BE3E;BE3E;1107 1174 11BD;BE3E;1107 1174 11BD; # (븾; 븾; 븾; 븾; 븾; ) HANGUL SYLLABLE BYIJ
+BE3F;BE3F;1107 1174 11BE;BE3F;1107 1174 11BE; # (븿; 븿; 븿; 븿; 븿; ) HANGUL SYLLABLE BYIC
+BE40;BE40;1107 1174 11BF;BE40;1107 1174 11BF; # (빀; 빀; 빀; 빀; 빀; ) HANGUL SYLLABLE BYIK
+BE41;BE41;1107 1174 11C0;BE41;1107 1174 11C0; # (빁; 빁; 빁; 빁; 빁; ) HANGUL SYLLABLE BYIT
+BE42;BE42;1107 1174 11C1;BE42;1107 1174 11C1; # (빂; 빂; 빂; 빂; 빂; ) HANGUL SYLLABLE BYIP
+BE43;BE43;1107 1174 11C2;BE43;1107 1174 11C2; # (빃; 빃; 빃; 빃; 빃; ) HANGUL SYLLABLE BYIH
+BE44;BE44;1107 1175;BE44;1107 1175; # (비; 비; 비; 비; 비; ) HANGUL SYLLABLE BI
+BE45;BE45;1107 1175 11A8;BE45;1107 1175 11A8; # (빅; 빅; 빅; 빅; 빅; ) HANGUL SYLLABLE BIG
+BE46;BE46;1107 1175 11A9;BE46;1107 1175 11A9; # (빆; 빆; 빆; 빆; 빆; ) HANGUL SYLLABLE BIGG
+BE47;BE47;1107 1175 11AA;BE47;1107 1175 11AA; # (빇; 빇; 빇; 빇; 빇; ) HANGUL SYLLABLE BIGS
+BE48;BE48;1107 1175 11AB;BE48;1107 1175 11AB; # (빈; 빈; 빈; 빈; 빈; ) HANGUL SYLLABLE BIN
+BE49;BE49;1107 1175 11AC;BE49;1107 1175 11AC; # (빉; 빉; 빉; 빉; 빉; ) HANGUL SYLLABLE BINJ
+BE4A;BE4A;1107 1175 11AD;BE4A;1107 1175 11AD; # (빊; 빊; 빊; 빊; 빊; ) HANGUL SYLLABLE BINH
+BE4B;BE4B;1107 1175 11AE;BE4B;1107 1175 11AE; # (빋; 빋; 빋; 빋; 빋; ) HANGUL SYLLABLE BID
+BE4C;BE4C;1107 1175 11AF;BE4C;1107 1175 11AF; # (빌; 빌; 빌; 빌; 빌; ) HANGUL SYLLABLE BIL
+BE4D;BE4D;1107 1175 11B0;BE4D;1107 1175 11B0; # (빍; 빍; 빍; 빍; 빍; ) HANGUL SYLLABLE BILG
+BE4E;BE4E;1107 1175 11B1;BE4E;1107 1175 11B1; # (빎; 빎; 빎; 빎; 빎; ) HANGUL SYLLABLE BILM
+BE4F;BE4F;1107 1175 11B2;BE4F;1107 1175 11B2; # (빏; 빏; 빏; 빏; 빏; ) HANGUL SYLLABLE BILB
+BE50;BE50;1107 1175 11B3;BE50;1107 1175 11B3; # (빐; 빐; 빐; 빐; 빐; ) HANGUL SYLLABLE BILS
+BE51;BE51;1107 1175 11B4;BE51;1107 1175 11B4; # (빑; 빑; 빑; 빑; 빑; ) HANGUL SYLLABLE BILT
+BE52;BE52;1107 1175 11B5;BE52;1107 1175 11B5; # (빒; 빒; 빒; 빒; 빒; ) HANGUL SYLLABLE BILP
+BE53;BE53;1107 1175 11B6;BE53;1107 1175 11B6; # (빓; 빓; 빓; 빓; 빓; ) HANGUL SYLLABLE BILH
+BE54;BE54;1107 1175 11B7;BE54;1107 1175 11B7; # (빔; 빔; 빔; 빔; 빔; ) HANGUL SYLLABLE BIM
+BE55;BE55;1107 1175 11B8;BE55;1107 1175 11B8; # (빕; 빕; 빕; 빕; 빕; ) HANGUL SYLLABLE BIB
+BE56;BE56;1107 1175 11B9;BE56;1107 1175 11B9; # (빖; 빖; 빖; 빖; 빖; ) HANGUL SYLLABLE BIBS
+BE57;BE57;1107 1175 11BA;BE57;1107 1175 11BA; # (빗; 빗; 빗; 빗; 빗; ) HANGUL SYLLABLE BIS
+BE58;BE58;1107 1175 11BB;BE58;1107 1175 11BB; # (빘; 빘; 빘; 빘; 빘; ) HANGUL SYLLABLE BISS
+BE59;BE59;1107 1175 11BC;BE59;1107 1175 11BC; # (빙; 빙; 빙; 빙; 빙; ) HANGUL SYLLABLE BING
+BE5A;BE5A;1107 1175 11BD;BE5A;1107 1175 11BD; # (빚; 빚; 빚; 빚; 빚; ) HANGUL SYLLABLE BIJ
+BE5B;BE5B;1107 1175 11BE;BE5B;1107 1175 11BE; # (빛; 빛; 빛; 빛; 빛; ) HANGUL SYLLABLE BIC
+BE5C;BE5C;1107 1175 11BF;BE5C;1107 1175 11BF; # (빜; 빜; 빜; 빜; 빜; ) HANGUL SYLLABLE BIK
+BE5D;BE5D;1107 1175 11C0;BE5D;1107 1175 11C0; # (빝; 빝; 빝; 빝; 빝; ) HANGUL SYLLABLE BIT
+BE5E;BE5E;1107 1175 11C1;BE5E;1107 1175 11C1; # (빞; 빞; 빞; 빞; 빞; ) HANGUL SYLLABLE BIP
+BE5F;BE5F;1107 1175 11C2;BE5F;1107 1175 11C2; # (빟; 빟; 빟; 빟; 빟; ) HANGUL SYLLABLE BIH
+BE60;BE60;1108 1161;BE60;1108 1161; # (빠; 빠; 빠; 빠; 빠; ) HANGUL SYLLABLE BBA
+BE61;BE61;1108 1161 11A8;BE61;1108 1161 11A8; # (빡; 빡; 빡; 빡; 빡; ) HANGUL SYLLABLE BBAG
+BE62;BE62;1108 1161 11A9;BE62;1108 1161 11A9; # (빢; 빢; 빢; 빢; 빢; ) HANGUL SYLLABLE BBAGG
+BE63;BE63;1108 1161 11AA;BE63;1108 1161 11AA; # (빣; 빣; 빣; 빣; 빣; ) HANGUL SYLLABLE BBAGS
+BE64;BE64;1108 1161 11AB;BE64;1108 1161 11AB; # (빤; 빤; 빤; 빤; 빤; ) HANGUL SYLLABLE BBAN
+BE65;BE65;1108 1161 11AC;BE65;1108 1161 11AC; # (빥; 빥; 빥; 빥; 빥; ) HANGUL SYLLABLE BBANJ
+BE66;BE66;1108 1161 11AD;BE66;1108 1161 11AD; # (빦; 빦; 빦; 빦; 빦; ) HANGUL SYLLABLE BBANH
+BE67;BE67;1108 1161 11AE;BE67;1108 1161 11AE; # (빧; 빧; 빧; 빧; 빧; ) HANGUL SYLLABLE BBAD
+BE68;BE68;1108 1161 11AF;BE68;1108 1161 11AF; # (빨; 빨; 빨; 빨; 빨; ) HANGUL SYLLABLE BBAL
+BE69;BE69;1108 1161 11B0;BE69;1108 1161 11B0; # (빩; 빩; 빩; 빩; 빩; ) HANGUL SYLLABLE BBALG
+BE6A;BE6A;1108 1161 11B1;BE6A;1108 1161 11B1; # (빪; 빪; 빪; 빪; 빪; ) HANGUL SYLLABLE BBALM
+BE6B;BE6B;1108 1161 11B2;BE6B;1108 1161 11B2; # (빫; 빫; 빫; 빫; 빫; ) HANGUL SYLLABLE BBALB
+BE6C;BE6C;1108 1161 11B3;BE6C;1108 1161 11B3; # (빬; 빬; 빬; 빬; 빬; ) HANGUL SYLLABLE BBALS
+BE6D;BE6D;1108 1161 11B4;BE6D;1108 1161 11B4; # (빭; 빭; 빭; 빭; 빭; ) HANGUL SYLLABLE BBALT
+BE6E;BE6E;1108 1161 11B5;BE6E;1108 1161 11B5; # (빮; 빮; 빮; 빮; 빮; ) HANGUL SYLLABLE BBALP
+BE6F;BE6F;1108 1161 11B6;BE6F;1108 1161 11B6; # (빯; 빯; 빯; 빯; 빯; ) HANGUL SYLLABLE BBALH
+BE70;BE70;1108 1161 11B7;BE70;1108 1161 11B7; # (빰; 빰; 빰; 빰; 빰; ) HANGUL SYLLABLE BBAM
+BE71;BE71;1108 1161 11B8;BE71;1108 1161 11B8; # (빱; 빱; 빱; 빱; 빱; ) HANGUL SYLLABLE BBAB
+BE72;BE72;1108 1161 11B9;BE72;1108 1161 11B9; # (빲; 빲; 빲; 빲; 빲; ) HANGUL SYLLABLE BBABS
+BE73;BE73;1108 1161 11BA;BE73;1108 1161 11BA; # (빳; 빳; 빳; 빳; 빳; ) HANGUL SYLLABLE BBAS
+BE74;BE74;1108 1161 11BB;BE74;1108 1161 11BB; # (빴; 빴; 빴; 빴; 빴; ) HANGUL SYLLABLE BBASS
+BE75;BE75;1108 1161 11BC;BE75;1108 1161 11BC; # (빵; 빵; 빵; 빵; 빵; ) HANGUL SYLLABLE BBANG
+BE76;BE76;1108 1161 11BD;BE76;1108 1161 11BD; # (빶; 빶; 빶; 빶; 빶; ) HANGUL SYLLABLE BBAJ
+BE77;BE77;1108 1161 11BE;BE77;1108 1161 11BE; # (빷; 빷; 빷; 빷; 빷; ) HANGUL SYLLABLE BBAC
+BE78;BE78;1108 1161 11BF;BE78;1108 1161 11BF; # (빸; 빸; 빸; 빸; 빸; ) HANGUL SYLLABLE BBAK
+BE79;BE79;1108 1161 11C0;BE79;1108 1161 11C0; # (빹; 빹; 빹; 빹; 빹; ) HANGUL SYLLABLE BBAT
+BE7A;BE7A;1108 1161 11C1;BE7A;1108 1161 11C1; # (빺; 빺; 빺; 빺; 빺; ) HANGUL SYLLABLE BBAP
+BE7B;BE7B;1108 1161 11C2;BE7B;1108 1161 11C2; # (빻; 빻; 빻; 빻; 빻; ) HANGUL SYLLABLE BBAH
+BE7C;BE7C;1108 1162;BE7C;1108 1162; # (빼; 빼; 빼; 빼; 빼; ) HANGUL SYLLABLE BBAE
+BE7D;BE7D;1108 1162 11A8;BE7D;1108 1162 11A8; # (빽; 빽; 빽; 빽; 빽; ) HANGUL SYLLABLE BBAEG
+BE7E;BE7E;1108 1162 11A9;BE7E;1108 1162 11A9; # (빾; 빾; 빾; 빾; 빾; ) HANGUL SYLLABLE BBAEGG
+BE7F;BE7F;1108 1162 11AA;BE7F;1108 1162 11AA; # (빿; 빿; 빿; 빿; 빿; ) HANGUL SYLLABLE BBAEGS
+BE80;BE80;1108 1162 11AB;BE80;1108 1162 11AB; # (뺀; 뺀; 뺀; 뺀; 뺀; ) HANGUL SYLLABLE BBAEN
+BE81;BE81;1108 1162 11AC;BE81;1108 1162 11AC; # (뺁; 뺁; 뺁; 뺁; 뺁; ) HANGUL SYLLABLE BBAENJ
+BE82;BE82;1108 1162 11AD;BE82;1108 1162 11AD; # (뺂; 뺂; 뺂; 뺂; 뺂; ) HANGUL SYLLABLE BBAENH
+BE83;BE83;1108 1162 11AE;BE83;1108 1162 11AE; # (뺃; 뺃; 뺃; 뺃; 뺃; ) HANGUL SYLLABLE BBAED
+BE84;BE84;1108 1162 11AF;BE84;1108 1162 11AF; # (뺄; 뺄; 뺄; 뺄; 뺄; ) HANGUL SYLLABLE BBAEL
+BE85;BE85;1108 1162 11B0;BE85;1108 1162 11B0; # (뺅; 뺅; 뺅; 뺅; 뺅; ) HANGUL SYLLABLE BBAELG
+BE86;BE86;1108 1162 11B1;BE86;1108 1162 11B1; # (뺆; 뺆; 뺆; 뺆; 뺆; ) HANGUL SYLLABLE BBAELM
+BE87;BE87;1108 1162 11B2;BE87;1108 1162 11B2; # (뺇; 뺇; 뺇; 뺇; 뺇; ) HANGUL SYLLABLE BBAELB
+BE88;BE88;1108 1162 11B3;BE88;1108 1162 11B3; # (뺈; 뺈; 뺈; 뺈; 뺈; ) HANGUL SYLLABLE BBAELS
+BE89;BE89;1108 1162 11B4;BE89;1108 1162 11B4; # (뺉; 뺉; 뺉; 뺉; 뺉; ) HANGUL SYLLABLE BBAELT
+BE8A;BE8A;1108 1162 11B5;BE8A;1108 1162 11B5; # (뺊; 뺊; 뺊; 뺊; 뺊; ) HANGUL SYLLABLE BBAELP
+BE8B;BE8B;1108 1162 11B6;BE8B;1108 1162 11B6; # (뺋; 뺋; 뺋; 뺋; 뺋; ) HANGUL SYLLABLE BBAELH
+BE8C;BE8C;1108 1162 11B7;BE8C;1108 1162 11B7; # (뺌; 뺌; 뺌; 뺌; 뺌; ) HANGUL SYLLABLE BBAEM
+BE8D;BE8D;1108 1162 11B8;BE8D;1108 1162 11B8; # (뺍; 뺍; 뺍; 뺍; 뺍; ) HANGUL SYLLABLE BBAEB
+BE8E;BE8E;1108 1162 11B9;BE8E;1108 1162 11B9; # (뺎; 뺎; 뺎; 뺎; 뺎; ) HANGUL SYLLABLE BBAEBS
+BE8F;BE8F;1108 1162 11BA;BE8F;1108 1162 11BA; # (뺏; 뺏; 뺏; 뺏; 뺏; ) HANGUL SYLLABLE BBAES
+BE90;BE90;1108 1162 11BB;BE90;1108 1162 11BB; # (뺐; 뺐; 뺐; 뺐; 뺐; ) HANGUL SYLLABLE BBAESS
+BE91;BE91;1108 1162 11BC;BE91;1108 1162 11BC; # (뺑; 뺑; 뺑; 뺑; 뺑; ) HANGUL SYLLABLE BBAENG
+BE92;BE92;1108 1162 11BD;BE92;1108 1162 11BD; # (뺒; 뺒; 뺒; 뺒; 뺒; ) HANGUL SYLLABLE BBAEJ
+BE93;BE93;1108 1162 11BE;BE93;1108 1162 11BE; # (뺓; 뺓; 뺓; 뺓; 뺓; ) HANGUL SYLLABLE BBAEC
+BE94;BE94;1108 1162 11BF;BE94;1108 1162 11BF; # (뺔; 뺔; 뺔; 뺔; 뺔; ) HANGUL SYLLABLE BBAEK
+BE95;BE95;1108 1162 11C0;BE95;1108 1162 11C0; # (뺕; 뺕; 뺕; 뺕; 뺕; ) HANGUL SYLLABLE BBAET
+BE96;BE96;1108 1162 11C1;BE96;1108 1162 11C1; # (뺖; 뺖; 뺖; 뺖; 뺖; ) HANGUL SYLLABLE BBAEP
+BE97;BE97;1108 1162 11C2;BE97;1108 1162 11C2; # (뺗; 뺗; 뺗; 뺗; 뺗; ) HANGUL SYLLABLE BBAEH
+BE98;BE98;1108 1163;BE98;1108 1163; # (뺘; 뺘; 뺘; 뺘; 뺘; ) HANGUL SYLLABLE BBYA
+BE99;BE99;1108 1163 11A8;BE99;1108 1163 11A8; # (뺙; 뺙; 뺙; 뺙; 뺙; ) HANGUL SYLLABLE BBYAG
+BE9A;BE9A;1108 1163 11A9;BE9A;1108 1163 11A9; # (뺚; 뺚; 뺚; 뺚; 뺚; ) HANGUL SYLLABLE BBYAGG
+BE9B;BE9B;1108 1163 11AA;BE9B;1108 1163 11AA; # (뺛; 뺛; 뺛; 뺛; 뺛; ) HANGUL SYLLABLE BBYAGS
+BE9C;BE9C;1108 1163 11AB;BE9C;1108 1163 11AB; # (뺜; 뺜; 뺜; 뺜; 뺜; ) HANGUL SYLLABLE BBYAN
+BE9D;BE9D;1108 1163 11AC;BE9D;1108 1163 11AC; # (뺝; 뺝; 뺝; 뺝; 뺝; ) HANGUL SYLLABLE BBYANJ
+BE9E;BE9E;1108 1163 11AD;BE9E;1108 1163 11AD; # (뺞; 뺞; 뺞; 뺞; 뺞; ) HANGUL SYLLABLE BBYANH
+BE9F;BE9F;1108 1163 11AE;BE9F;1108 1163 11AE; # (뺟; 뺟; 뺟; 뺟; 뺟; ) HANGUL SYLLABLE BBYAD
+BEA0;BEA0;1108 1163 11AF;BEA0;1108 1163 11AF; # (뺠; 뺠; 뺠; 뺠; 뺠; ) HANGUL SYLLABLE BBYAL
+BEA1;BEA1;1108 1163 11B0;BEA1;1108 1163 11B0; # (뺡; 뺡; 뺡; 뺡; 뺡; ) HANGUL SYLLABLE BBYALG
+BEA2;BEA2;1108 1163 11B1;BEA2;1108 1163 11B1; # (뺢; 뺢; 뺢; 뺢; 뺢; ) HANGUL SYLLABLE BBYALM
+BEA3;BEA3;1108 1163 11B2;BEA3;1108 1163 11B2; # (뺣; 뺣; 뺣; 뺣; 뺣; ) HANGUL SYLLABLE BBYALB
+BEA4;BEA4;1108 1163 11B3;BEA4;1108 1163 11B3; # (뺤; 뺤; 뺤; 뺤; 뺤; ) HANGUL SYLLABLE BBYALS
+BEA5;BEA5;1108 1163 11B4;BEA5;1108 1163 11B4; # (뺥; 뺥; 뺥; 뺥; 뺥; ) HANGUL SYLLABLE BBYALT
+BEA6;BEA6;1108 1163 11B5;BEA6;1108 1163 11B5; # (뺦; 뺦; 뺦; 뺦; 뺦; ) HANGUL SYLLABLE BBYALP
+BEA7;BEA7;1108 1163 11B6;BEA7;1108 1163 11B6; # (뺧; 뺧; 뺧; 뺧; 뺧; ) HANGUL SYLLABLE BBYALH
+BEA8;BEA8;1108 1163 11B7;BEA8;1108 1163 11B7; # (뺨; 뺨; 뺨; 뺨; 뺨; ) HANGUL SYLLABLE BBYAM
+BEA9;BEA9;1108 1163 11B8;BEA9;1108 1163 11B8; # (뺩; 뺩; 뺩; 뺩; 뺩; ) HANGUL SYLLABLE BBYAB
+BEAA;BEAA;1108 1163 11B9;BEAA;1108 1163 11B9; # (뺪; 뺪; 뺪; 뺪; 뺪; ) HANGUL SYLLABLE BBYABS
+BEAB;BEAB;1108 1163 11BA;BEAB;1108 1163 11BA; # (뺫; 뺫; 뺫; 뺫; 뺫; ) HANGUL SYLLABLE BBYAS
+BEAC;BEAC;1108 1163 11BB;BEAC;1108 1163 11BB; # (뺬; 뺬; 뺬; 뺬; 뺬; ) HANGUL SYLLABLE BBYASS
+BEAD;BEAD;1108 1163 11BC;BEAD;1108 1163 11BC; # (뺭; 뺭; 뺭; 뺭; 뺭; ) HANGUL SYLLABLE BBYANG
+BEAE;BEAE;1108 1163 11BD;BEAE;1108 1163 11BD; # (뺮; 뺮; 뺮; 뺮; 뺮; ) HANGUL SYLLABLE BBYAJ
+BEAF;BEAF;1108 1163 11BE;BEAF;1108 1163 11BE; # (뺯; 뺯; 뺯; 뺯; 뺯; ) HANGUL SYLLABLE BBYAC
+BEB0;BEB0;1108 1163 11BF;BEB0;1108 1163 11BF; # (뺰; 뺰; 뺰; 뺰; 뺰; ) HANGUL SYLLABLE BBYAK
+BEB1;BEB1;1108 1163 11C0;BEB1;1108 1163 11C0; # (뺱; 뺱; 뺱; 뺱; 뺱; ) HANGUL SYLLABLE BBYAT
+BEB2;BEB2;1108 1163 11C1;BEB2;1108 1163 11C1; # (뺲; 뺲; 뺲; 뺲; 뺲; ) HANGUL SYLLABLE BBYAP
+BEB3;BEB3;1108 1163 11C2;BEB3;1108 1163 11C2; # (뺳; 뺳; 뺳; 뺳; 뺳; ) HANGUL SYLLABLE BBYAH
+BEB4;BEB4;1108 1164;BEB4;1108 1164; # (뺴; 뺴; 뺴; 뺴; 뺴; ) HANGUL SYLLABLE BBYAE
+BEB5;BEB5;1108 1164 11A8;BEB5;1108 1164 11A8; # (뺵; 뺵; 뺵; 뺵; 뺵; ) HANGUL SYLLABLE BBYAEG
+BEB6;BEB6;1108 1164 11A9;BEB6;1108 1164 11A9; # (뺶; 뺶; 뺶; 뺶; 뺶; ) HANGUL SYLLABLE BBYAEGG
+BEB7;BEB7;1108 1164 11AA;BEB7;1108 1164 11AA; # (뺷; 뺷; 뺷; 뺷; 뺷; ) HANGUL SYLLABLE BBYAEGS
+BEB8;BEB8;1108 1164 11AB;BEB8;1108 1164 11AB; # (뺸; 뺸; 뺸; 뺸; 뺸; ) HANGUL SYLLABLE BBYAEN
+BEB9;BEB9;1108 1164 11AC;BEB9;1108 1164 11AC; # (뺹; 뺹; 뺹; 뺹; 뺹; ) HANGUL SYLLABLE BBYAENJ
+BEBA;BEBA;1108 1164 11AD;BEBA;1108 1164 11AD; # (뺺; 뺺; 뺺; 뺺; 뺺; ) HANGUL SYLLABLE BBYAENH
+BEBB;BEBB;1108 1164 11AE;BEBB;1108 1164 11AE; # (뺻; 뺻; 뺻; 뺻; 뺻; ) HANGUL SYLLABLE BBYAED
+BEBC;BEBC;1108 1164 11AF;BEBC;1108 1164 11AF; # (뺼; 뺼; 뺼; 뺼; 뺼; ) HANGUL SYLLABLE BBYAEL
+BEBD;BEBD;1108 1164 11B0;BEBD;1108 1164 11B0; # (뺽; 뺽; 뺽; 뺽; 뺽; ) HANGUL SYLLABLE BBYAELG
+BEBE;BEBE;1108 1164 11B1;BEBE;1108 1164 11B1; # (뺾; 뺾; 뺾; 뺾; 뺾; ) HANGUL SYLLABLE BBYAELM
+BEBF;BEBF;1108 1164 11B2;BEBF;1108 1164 11B2; # (뺿; 뺿; 뺿; 뺿; 뺿; ) HANGUL SYLLABLE BBYAELB
+BEC0;BEC0;1108 1164 11B3;BEC0;1108 1164 11B3; # (뻀; 뻀; 뻀; 뻀; 뻀; ) HANGUL SYLLABLE BBYAELS
+BEC1;BEC1;1108 1164 11B4;BEC1;1108 1164 11B4; # (뻁; 뻁; 뻁; 뻁; 뻁; ) HANGUL SYLLABLE BBYAELT
+BEC2;BEC2;1108 1164 11B5;BEC2;1108 1164 11B5; # (뻂; 뻂; 뻂; 뻂; 뻂; ) HANGUL SYLLABLE BBYAELP
+BEC3;BEC3;1108 1164 11B6;BEC3;1108 1164 11B6; # (뻃; 뻃; 뻃; 뻃; 뻃; ) HANGUL SYLLABLE BBYAELH
+BEC4;BEC4;1108 1164 11B7;BEC4;1108 1164 11B7; # (뻄; 뻄; 뻄; 뻄; 뻄; ) HANGUL SYLLABLE BBYAEM
+BEC5;BEC5;1108 1164 11B8;BEC5;1108 1164 11B8; # (뻅; 뻅; 뻅; 뻅; 뻅; ) HANGUL SYLLABLE BBYAEB
+BEC6;BEC6;1108 1164 11B9;BEC6;1108 1164 11B9; # (뻆; 뻆; 뻆; 뻆; 뻆; ) HANGUL SYLLABLE BBYAEBS
+BEC7;BEC7;1108 1164 11BA;BEC7;1108 1164 11BA; # (뻇; 뻇; 뻇; 뻇; 뻇; ) HANGUL SYLLABLE BBYAES
+BEC8;BEC8;1108 1164 11BB;BEC8;1108 1164 11BB; # (뻈; 뻈; 뻈; 뻈; 뻈; ) HANGUL SYLLABLE BBYAESS
+BEC9;BEC9;1108 1164 11BC;BEC9;1108 1164 11BC; # (뻉; 뻉; 뻉; 뻉; 뻉; ) HANGUL SYLLABLE BBYAENG
+BECA;BECA;1108 1164 11BD;BECA;1108 1164 11BD; # (뻊; 뻊; 뻊; 뻊; 뻊; ) HANGUL SYLLABLE BBYAEJ
+BECB;BECB;1108 1164 11BE;BECB;1108 1164 11BE; # (뻋; 뻋; 뻋; 뻋; 뻋; ) HANGUL SYLLABLE BBYAEC
+BECC;BECC;1108 1164 11BF;BECC;1108 1164 11BF; # (뻌; 뻌; 뻌; 뻌; 뻌; ) HANGUL SYLLABLE BBYAEK
+BECD;BECD;1108 1164 11C0;BECD;1108 1164 11C0; # (뻍; 뻍; 뻍; 뻍; 뻍; ) HANGUL SYLLABLE BBYAET
+BECE;BECE;1108 1164 11C1;BECE;1108 1164 11C1; # (뻎; 뻎; 뻎; 뻎; 뻎; ) HANGUL SYLLABLE BBYAEP
+BECF;BECF;1108 1164 11C2;BECF;1108 1164 11C2; # (뻏; 뻏; 뻏; 뻏; 뻏; ) HANGUL SYLLABLE BBYAEH
+BED0;BED0;1108 1165;BED0;1108 1165; # (뻐; 뻐; 뻐; 뻐; 뻐; ) HANGUL SYLLABLE BBEO
+BED1;BED1;1108 1165 11A8;BED1;1108 1165 11A8; # (뻑; 뻑; 뻑; 뻑; 뻑; ) HANGUL SYLLABLE BBEOG
+BED2;BED2;1108 1165 11A9;BED2;1108 1165 11A9; # (뻒; 뻒; 뻒; 뻒; 뻒; ) HANGUL SYLLABLE BBEOGG
+BED3;BED3;1108 1165 11AA;BED3;1108 1165 11AA; # (뻓; 뻓; 뻓; 뻓; 뻓; ) HANGUL SYLLABLE BBEOGS
+BED4;BED4;1108 1165 11AB;BED4;1108 1165 11AB; # (뻔; 뻔; 뻔; 뻔; 뻔; ) HANGUL SYLLABLE BBEON
+BED5;BED5;1108 1165 11AC;BED5;1108 1165 11AC; # (뻕; 뻕; 뻕; 뻕; 뻕; ) HANGUL SYLLABLE BBEONJ
+BED6;BED6;1108 1165 11AD;BED6;1108 1165 11AD; # (뻖; 뻖; 뻖; 뻖; 뻖; ) HANGUL SYLLABLE BBEONH
+BED7;BED7;1108 1165 11AE;BED7;1108 1165 11AE; # (뻗; 뻗; 뻗; 뻗; 뻗; ) HANGUL SYLLABLE BBEOD
+BED8;BED8;1108 1165 11AF;BED8;1108 1165 11AF; # (뻘; 뻘; 뻘; 뻘; 뻘; ) HANGUL SYLLABLE BBEOL
+BED9;BED9;1108 1165 11B0;BED9;1108 1165 11B0; # (뻙; 뻙; 뻙; 뻙; 뻙; ) HANGUL SYLLABLE BBEOLG
+BEDA;BEDA;1108 1165 11B1;BEDA;1108 1165 11B1; # (뻚; 뻚; 뻚; 뻚; 뻚; ) HANGUL SYLLABLE BBEOLM
+BEDB;BEDB;1108 1165 11B2;BEDB;1108 1165 11B2; # (뻛; 뻛; 뻛; 뻛; 뻛; ) HANGUL SYLLABLE BBEOLB
+BEDC;BEDC;1108 1165 11B3;BEDC;1108 1165 11B3; # (뻜; 뻜; 뻜; 뻜; 뻜; ) HANGUL SYLLABLE BBEOLS
+BEDD;BEDD;1108 1165 11B4;BEDD;1108 1165 11B4; # (뻝; 뻝; 뻝; 뻝; 뻝; ) HANGUL SYLLABLE BBEOLT
+BEDE;BEDE;1108 1165 11B5;BEDE;1108 1165 11B5; # (뻞; 뻞; 뻞; 뻞; 뻞; ) HANGUL SYLLABLE BBEOLP
+BEDF;BEDF;1108 1165 11B6;BEDF;1108 1165 11B6; # (뻟; 뻟; 뻟; 뻟; 뻟; ) HANGUL SYLLABLE BBEOLH
+BEE0;BEE0;1108 1165 11B7;BEE0;1108 1165 11B7; # (뻠; 뻠; 뻠; 뻠; 뻠; ) HANGUL SYLLABLE BBEOM
+BEE1;BEE1;1108 1165 11B8;BEE1;1108 1165 11B8; # (뻡; 뻡; 뻡; 뻡; 뻡; ) HANGUL SYLLABLE BBEOB
+BEE2;BEE2;1108 1165 11B9;BEE2;1108 1165 11B9; # (뻢; 뻢; 뻢; 뻢; 뻢; ) HANGUL SYLLABLE BBEOBS
+BEE3;BEE3;1108 1165 11BA;BEE3;1108 1165 11BA; # (뻣; 뻣; 뻣; 뻣; 뻣; ) HANGUL SYLLABLE BBEOS
+BEE4;BEE4;1108 1165 11BB;BEE4;1108 1165 11BB; # (뻤; 뻤; 뻤; 뻤; 뻤; ) HANGUL SYLLABLE BBEOSS
+BEE5;BEE5;1108 1165 11BC;BEE5;1108 1165 11BC; # (뻥; 뻥; 뻥; 뻥; 뻥; ) HANGUL SYLLABLE BBEONG
+BEE6;BEE6;1108 1165 11BD;BEE6;1108 1165 11BD; # (뻦; 뻦; 뻦; 뻦; 뻦; ) HANGUL SYLLABLE BBEOJ
+BEE7;BEE7;1108 1165 11BE;BEE7;1108 1165 11BE; # (뻧; 뻧; 뻧; 뻧; 뻧; ) HANGUL SYLLABLE BBEOC
+BEE8;BEE8;1108 1165 11BF;BEE8;1108 1165 11BF; # (뻨; 뻨; 뻨; 뻨; 뻨; ) HANGUL SYLLABLE BBEOK
+BEE9;BEE9;1108 1165 11C0;BEE9;1108 1165 11C0; # (뻩; 뻩; 뻩; 뻩; 뻩; ) HANGUL SYLLABLE BBEOT
+BEEA;BEEA;1108 1165 11C1;BEEA;1108 1165 11C1; # (뻪; 뻪; 뻪; 뻪; 뻪; ) HANGUL SYLLABLE BBEOP
+BEEB;BEEB;1108 1165 11C2;BEEB;1108 1165 11C2; # (뻫; 뻫; 뻫; 뻫; 뻫; ) HANGUL SYLLABLE BBEOH
+BEEC;BEEC;1108 1166;BEEC;1108 1166; # (뻬; 뻬; 뻬; 뻬; 뻬; ) HANGUL SYLLABLE BBE
+BEED;BEED;1108 1166 11A8;BEED;1108 1166 11A8; # (뻭; 뻭; 뻭; 뻭; 뻭; ) HANGUL SYLLABLE BBEG
+BEEE;BEEE;1108 1166 11A9;BEEE;1108 1166 11A9; # (뻮; 뻮; 뻮; 뻮; 뻮; ) HANGUL SYLLABLE BBEGG
+BEEF;BEEF;1108 1166 11AA;BEEF;1108 1166 11AA; # (뻯; 뻯; 뻯; 뻯; 뻯; ) HANGUL SYLLABLE BBEGS
+BEF0;BEF0;1108 1166 11AB;BEF0;1108 1166 11AB; # (뻰; 뻰; 뻰; 뻰; 뻰; ) HANGUL SYLLABLE BBEN
+BEF1;BEF1;1108 1166 11AC;BEF1;1108 1166 11AC; # (뻱; 뻱; 뻱; 뻱; 뻱; ) HANGUL SYLLABLE BBENJ
+BEF2;BEF2;1108 1166 11AD;BEF2;1108 1166 11AD; # (뻲; 뻲; 뻲; 뻲; 뻲; ) HANGUL SYLLABLE BBENH
+BEF3;BEF3;1108 1166 11AE;BEF3;1108 1166 11AE; # (뻳; 뻳; 뻳; 뻳; 뻳; ) HANGUL SYLLABLE BBED
+BEF4;BEF4;1108 1166 11AF;BEF4;1108 1166 11AF; # (뻴; 뻴; 뻴; 뻴; 뻴; ) HANGUL SYLLABLE BBEL
+BEF5;BEF5;1108 1166 11B0;BEF5;1108 1166 11B0; # (뻵; 뻵; 뻵; 뻵; 뻵; ) HANGUL SYLLABLE BBELG
+BEF6;BEF6;1108 1166 11B1;BEF6;1108 1166 11B1; # (뻶; 뻶; 뻶; 뻶; 뻶; ) HANGUL SYLLABLE BBELM
+BEF7;BEF7;1108 1166 11B2;BEF7;1108 1166 11B2; # (뻷; 뻷; 뻷; 뻷; 뻷; ) HANGUL SYLLABLE BBELB
+BEF8;BEF8;1108 1166 11B3;BEF8;1108 1166 11B3; # (뻸; 뻸; 뻸; 뻸; 뻸; ) HANGUL SYLLABLE BBELS
+BEF9;BEF9;1108 1166 11B4;BEF9;1108 1166 11B4; # (뻹; 뻹; 뻹; 뻹; 뻹; ) HANGUL SYLLABLE BBELT
+BEFA;BEFA;1108 1166 11B5;BEFA;1108 1166 11B5; # (뻺; 뻺; 뻺; 뻺; 뻺; ) HANGUL SYLLABLE BBELP
+BEFB;BEFB;1108 1166 11B6;BEFB;1108 1166 11B6; # (뻻; 뻻; 뻻; 뻻; 뻻; ) HANGUL SYLLABLE BBELH
+BEFC;BEFC;1108 1166 11B7;BEFC;1108 1166 11B7; # (뻼; 뻼; 뻼; 뻼; 뻼; ) HANGUL SYLLABLE BBEM
+BEFD;BEFD;1108 1166 11B8;BEFD;1108 1166 11B8; # (뻽; 뻽; 뻽; 뻽; 뻽; ) HANGUL SYLLABLE BBEB
+BEFE;BEFE;1108 1166 11B9;BEFE;1108 1166 11B9; # (뻾; 뻾; 뻾; 뻾; 뻾; ) HANGUL SYLLABLE BBEBS
+BEFF;BEFF;1108 1166 11BA;BEFF;1108 1166 11BA; # (뻿; 뻿; 뻿; 뻿; 뻿; ) HANGUL SYLLABLE BBES
+BF00;BF00;1108 1166 11BB;BF00;1108 1166 11BB; # (뼀; 뼀; 뼀; 뼀; 뼀; ) HANGUL SYLLABLE BBESS
+BF01;BF01;1108 1166 11BC;BF01;1108 1166 11BC; # (뼁; 뼁; 뼁; 뼁; 뼁; ) HANGUL SYLLABLE BBENG
+BF02;BF02;1108 1166 11BD;BF02;1108 1166 11BD; # (뼂; 뼂; 뼂; 뼂; 뼂; ) HANGUL SYLLABLE BBEJ
+BF03;BF03;1108 1166 11BE;BF03;1108 1166 11BE; # (뼃; 뼃; 뼃; 뼃; 뼃; ) HANGUL SYLLABLE BBEC
+BF04;BF04;1108 1166 11BF;BF04;1108 1166 11BF; # (뼄; 뼄; 뼄; 뼄; 뼄; ) HANGUL SYLLABLE BBEK
+BF05;BF05;1108 1166 11C0;BF05;1108 1166 11C0; # (뼅; 뼅; 뼅; 뼅; 뼅; ) HANGUL SYLLABLE BBET
+BF06;BF06;1108 1166 11C1;BF06;1108 1166 11C1; # (뼆; 뼆; 뼆; 뼆; 뼆; ) HANGUL SYLLABLE BBEP
+BF07;BF07;1108 1166 11C2;BF07;1108 1166 11C2; # (뼇; 뼇; 뼇; 뼇; 뼇; ) HANGUL SYLLABLE BBEH
+BF08;BF08;1108 1167;BF08;1108 1167; # (뼈; 뼈; 뼈; 뼈; 뼈; ) HANGUL SYLLABLE BBYEO
+BF09;BF09;1108 1167 11A8;BF09;1108 1167 11A8; # (뼉; 뼉; 뼉; 뼉; 뼉; ) HANGUL SYLLABLE BBYEOG
+BF0A;BF0A;1108 1167 11A9;BF0A;1108 1167 11A9; # (뼊; 뼊; 뼊; 뼊; 뼊; ) HANGUL SYLLABLE BBYEOGG
+BF0B;BF0B;1108 1167 11AA;BF0B;1108 1167 11AA; # (뼋; 뼋; 뼋; 뼋; 뼋; ) HANGUL SYLLABLE BBYEOGS
+BF0C;BF0C;1108 1167 11AB;BF0C;1108 1167 11AB; # (뼌; 뼌; 뼌; 뼌; 뼌; ) HANGUL SYLLABLE BBYEON
+BF0D;BF0D;1108 1167 11AC;BF0D;1108 1167 11AC; # (뼍; 뼍; 뼍; 뼍; 뼍; ) HANGUL SYLLABLE BBYEONJ
+BF0E;BF0E;1108 1167 11AD;BF0E;1108 1167 11AD; # (뼎; 뼎; 뼎; 뼎; 뼎; ) HANGUL SYLLABLE BBYEONH
+BF0F;BF0F;1108 1167 11AE;BF0F;1108 1167 11AE; # (뼏; 뼏; 뼏; 뼏; 뼏; ) HANGUL SYLLABLE BBYEOD
+BF10;BF10;1108 1167 11AF;BF10;1108 1167 11AF; # (뼐; 뼐; 뼐; 뼐; 뼐; ) HANGUL SYLLABLE BBYEOL
+BF11;BF11;1108 1167 11B0;BF11;1108 1167 11B0; # (뼑; 뼑; 뼑; 뼑; 뼑; ) HANGUL SYLLABLE BBYEOLG
+BF12;BF12;1108 1167 11B1;BF12;1108 1167 11B1; # (뼒; 뼒; 뼒; 뼒; 뼒; ) HANGUL SYLLABLE BBYEOLM
+BF13;BF13;1108 1167 11B2;BF13;1108 1167 11B2; # (뼓; 뼓; 뼓; 뼓; 뼓; ) HANGUL SYLLABLE BBYEOLB
+BF14;BF14;1108 1167 11B3;BF14;1108 1167 11B3; # (뼔; 뼔; 뼔; 뼔; 뼔; ) HANGUL SYLLABLE BBYEOLS
+BF15;BF15;1108 1167 11B4;BF15;1108 1167 11B4; # (뼕; 뼕; 뼕; 뼕; 뼕; ) HANGUL SYLLABLE BBYEOLT
+BF16;BF16;1108 1167 11B5;BF16;1108 1167 11B5; # (뼖; 뼖; 뼖; 뼖; 뼖; ) HANGUL SYLLABLE BBYEOLP
+BF17;BF17;1108 1167 11B6;BF17;1108 1167 11B6; # (뼗; 뼗; 뼗; 뼗; 뼗; ) HANGUL SYLLABLE BBYEOLH
+BF18;BF18;1108 1167 11B7;BF18;1108 1167 11B7; # (뼘; 뼘; 뼘; 뼘; 뼘; ) HANGUL SYLLABLE BBYEOM
+BF19;BF19;1108 1167 11B8;BF19;1108 1167 11B8; # (뼙; 뼙; 뼙; 뼙; 뼙; ) HANGUL SYLLABLE BBYEOB
+BF1A;BF1A;1108 1167 11B9;BF1A;1108 1167 11B9; # (뼚; 뼚; 뼚; 뼚; 뼚; ) HANGUL SYLLABLE BBYEOBS
+BF1B;BF1B;1108 1167 11BA;BF1B;1108 1167 11BA; # (뼛; 뼛; 뼛; 뼛; 뼛; ) HANGUL SYLLABLE BBYEOS
+BF1C;BF1C;1108 1167 11BB;BF1C;1108 1167 11BB; # (뼜; 뼜; 뼜; 뼜; 뼜; ) HANGUL SYLLABLE BBYEOSS
+BF1D;BF1D;1108 1167 11BC;BF1D;1108 1167 11BC; # (뼝; 뼝; 뼝; 뼝; 뼝; ) HANGUL SYLLABLE BBYEONG
+BF1E;BF1E;1108 1167 11BD;BF1E;1108 1167 11BD; # (뼞; 뼞; 뼞; 뼞; 뼞; ) HANGUL SYLLABLE BBYEOJ
+BF1F;BF1F;1108 1167 11BE;BF1F;1108 1167 11BE; # (뼟; 뼟; 뼟; 뼟; 뼟; ) HANGUL SYLLABLE BBYEOC
+BF20;BF20;1108 1167 11BF;BF20;1108 1167 11BF; # (뼠; 뼠; 뼠; 뼠; 뼠; ) HANGUL SYLLABLE BBYEOK
+BF21;BF21;1108 1167 11C0;BF21;1108 1167 11C0; # (뼡; 뼡; 뼡; 뼡; 뼡; ) HANGUL SYLLABLE BBYEOT
+BF22;BF22;1108 1167 11C1;BF22;1108 1167 11C1; # (뼢; 뼢; 뼢; 뼢; 뼢; ) HANGUL SYLLABLE BBYEOP
+BF23;BF23;1108 1167 11C2;BF23;1108 1167 11C2; # (뼣; 뼣; 뼣; 뼣; 뼣; ) HANGUL SYLLABLE BBYEOH
+BF24;BF24;1108 1168;BF24;1108 1168; # (뼤; 뼤; 뼤; 뼤; 뼤; ) HANGUL SYLLABLE BBYE
+BF25;BF25;1108 1168 11A8;BF25;1108 1168 11A8; # (뼥; 뼥; 뼥; 뼥; 뼥; ) HANGUL SYLLABLE BBYEG
+BF26;BF26;1108 1168 11A9;BF26;1108 1168 11A9; # (뼦; 뼦; 뼦; 뼦; 뼦; ) HANGUL SYLLABLE BBYEGG
+BF27;BF27;1108 1168 11AA;BF27;1108 1168 11AA; # (뼧; 뼧; 뼧; 뼧; 뼧; ) HANGUL SYLLABLE BBYEGS
+BF28;BF28;1108 1168 11AB;BF28;1108 1168 11AB; # (뼨; 뼨; 뼨; 뼨; 뼨; ) HANGUL SYLLABLE BBYEN
+BF29;BF29;1108 1168 11AC;BF29;1108 1168 11AC; # (뼩; 뼩; 뼩; 뼩; 뼩; ) HANGUL SYLLABLE BBYENJ
+BF2A;BF2A;1108 1168 11AD;BF2A;1108 1168 11AD; # (뼪; 뼪; 뼪; 뼪; 뼪; ) HANGUL SYLLABLE BBYENH
+BF2B;BF2B;1108 1168 11AE;BF2B;1108 1168 11AE; # (뼫; 뼫; 뼫; 뼫; 뼫; ) HANGUL SYLLABLE BBYED
+BF2C;BF2C;1108 1168 11AF;BF2C;1108 1168 11AF; # (뼬; 뼬; 뼬; 뼬; 뼬; ) HANGUL SYLLABLE BBYEL
+BF2D;BF2D;1108 1168 11B0;BF2D;1108 1168 11B0; # (뼭; 뼭; 뼭; 뼭; 뼭; ) HANGUL SYLLABLE BBYELG
+BF2E;BF2E;1108 1168 11B1;BF2E;1108 1168 11B1; # (뼮; 뼮; 뼮; 뼮; 뼮; ) HANGUL SYLLABLE BBYELM
+BF2F;BF2F;1108 1168 11B2;BF2F;1108 1168 11B2; # (뼯; 뼯; 뼯; 뼯; 뼯; ) HANGUL SYLLABLE BBYELB
+BF30;BF30;1108 1168 11B3;BF30;1108 1168 11B3; # (뼰; 뼰; 뼰; 뼰; 뼰; ) HANGUL SYLLABLE BBYELS
+BF31;BF31;1108 1168 11B4;BF31;1108 1168 11B4; # (뼱; 뼱; 뼱; 뼱; 뼱; ) HANGUL SYLLABLE BBYELT
+BF32;BF32;1108 1168 11B5;BF32;1108 1168 11B5; # (뼲; 뼲; 뼲; 뼲; 뼲; ) HANGUL SYLLABLE BBYELP
+BF33;BF33;1108 1168 11B6;BF33;1108 1168 11B6; # (뼳; 뼳; 뼳; 뼳; 뼳; ) HANGUL SYLLABLE BBYELH
+BF34;BF34;1108 1168 11B7;BF34;1108 1168 11B7; # (뼴; 뼴; 뼴; 뼴; 뼴; ) HANGUL SYLLABLE BBYEM
+BF35;BF35;1108 1168 11B8;BF35;1108 1168 11B8; # (뼵; 뼵; 뼵; 뼵; 뼵; ) HANGUL SYLLABLE BBYEB
+BF36;BF36;1108 1168 11B9;BF36;1108 1168 11B9; # (뼶; 뼶; 뼶; 뼶; 뼶; ) HANGUL SYLLABLE BBYEBS
+BF37;BF37;1108 1168 11BA;BF37;1108 1168 11BA; # (뼷; 뼷; 뼷; 뼷; 뼷; ) HANGUL SYLLABLE BBYES
+BF38;BF38;1108 1168 11BB;BF38;1108 1168 11BB; # (뼸; 뼸; 뼸; 뼸; 뼸; ) HANGUL SYLLABLE BBYESS
+BF39;BF39;1108 1168 11BC;BF39;1108 1168 11BC; # (뼹; 뼹; 뼹; 뼹; 뼹; ) HANGUL SYLLABLE BBYENG
+BF3A;BF3A;1108 1168 11BD;BF3A;1108 1168 11BD; # (뼺; 뼺; 뼺; 뼺; 뼺; ) HANGUL SYLLABLE BBYEJ
+BF3B;BF3B;1108 1168 11BE;BF3B;1108 1168 11BE; # (뼻; 뼻; 뼻; 뼻; 뼻; ) HANGUL SYLLABLE BBYEC
+BF3C;BF3C;1108 1168 11BF;BF3C;1108 1168 11BF; # (뼼; 뼼; 뼼; 뼼; 뼼; ) HANGUL SYLLABLE BBYEK
+BF3D;BF3D;1108 1168 11C0;BF3D;1108 1168 11C0; # (뼽; 뼽; 뼽; 뼽; 뼽; ) HANGUL SYLLABLE BBYET
+BF3E;BF3E;1108 1168 11C1;BF3E;1108 1168 11C1; # (뼾; 뼾; 뼾; 뼾; 뼾; ) HANGUL SYLLABLE BBYEP
+BF3F;BF3F;1108 1168 11C2;BF3F;1108 1168 11C2; # (뼿; 뼿; 뼿; 뼿; 뼿; ) HANGUL SYLLABLE BBYEH
+BF40;BF40;1108 1169;BF40;1108 1169; # (뽀; 뽀; 뽀; 뽀; 뽀; ) HANGUL SYLLABLE BBO
+BF41;BF41;1108 1169 11A8;BF41;1108 1169 11A8; # (뽁; 뽁; 뽁; 뽁; 뽁; ) HANGUL SYLLABLE BBOG
+BF42;BF42;1108 1169 11A9;BF42;1108 1169 11A9; # (뽂; 뽂; 뽂; 뽂; 뽂; ) HANGUL SYLLABLE BBOGG
+BF43;BF43;1108 1169 11AA;BF43;1108 1169 11AA; # (뽃; 뽃; 뽃; 뽃; 뽃; ) HANGUL SYLLABLE BBOGS
+BF44;BF44;1108 1169 11AB;BF44;1108 1169 11AB; # (뽄; 뽄; 뽄; 뽄; 뽄; ) HANGUL SYLLABLE BBON
+BF45;BF45;1108 1169 11AC;BF45;1108 1169 11AC; # (뽅; 뽅; 뽅; 뽅; 뽅; ) HANGUL SYLLABLE BBONJ
+BF46;BF46;1108 1169 11AD;BF46;1108 1169 11AD; # (뽆; 뽆; 뽆; 뽆; 뽆; ) HANGUL SYLLABLE BBONH
+BF47;BF47;1108 1169 11AE;BF47;1108 1169 11AE; # (뽇; 뽇; 뽇; 뽇; 뽇; ) HANGUL SYLLABLE BBOD
+BF48;BF48;1108 1169 11AF;BF48;1108 1169 11AF; # (뽈; 뽈; 뽈; 뽈; 뽈; ) HANGUL SYLLABLE BBOL
+BF49;BF49;1108 1169 11B0;BF49;1108 1169 11B0; # (뽉; 뽉; 뽉; 뽉; 뽉; ) HANGUL SYLLABLE BBOLG
+BF4A;BF4A;1108 1169 11B1;BF4A;1108 1169 11B1; # (뽊; 뽊; 뽊; 뽊; 뽊; ) HANGUL SYLLABLE BBOLM
+BF4B;BF4B;1108 1169 11B2;BF4B;1108 1169 11B2; # (뽋; 뽋; 뽋; 뽋; 뽋; ) HANGUL SYLLABLE BBOLB
+BF4C;BF4C;1108 1169 11B3;BF4C;1108 1169 11B3; # (뽌; 뽌; 뽌; 뽌; 뽌; ) HANGUL SYLLABLE BBOLS
+BF4D;BF4D;1108 1169 11B4;BF4D;1108 1169 11B4; # (뽍; 뽍; 뽍; 뽍; 뽍; ) HANGUL SYLLABLE BBOLT
+BF4E;BF4E;1108 1169 11B5;BF4E;1108 1169 11B5; # (뽎; 뽎; 뽎; 뽎; 뽎; ) HANGUL SYLLABLE BBOLP
+BF4F;BF4F;1108 1169 11B6;BF4F;1108 1169 11B6; # (뽏; 뽏; 뽏; 뽏; 뽏; ) HANGUL SYLLABLE BBOLH
+BF50;BF50;1108 1169 11B7;BF50;1108 1169 11B7; # (뽐; 뽐; 뽐; 뽐; 뽐; ) HANGUL SYLLABLE BBOM
+BF51;BF51;1108 1169 11B8;BF51;1108 1169 11B8; # (뽑; 뽑; 뽑; 뽑; 뽑; ) HANGUL SYLLABLE BBOB
+BF52;BF52;1108 1169 11B9;BF52;1108 1169 11B9; # (뽒; 뽒; 뽒; 뽒; 뽒; ) HANGUL SYLLABLE BBOBS
+BF53;BF53;1108 1169 11BA;BF53;1108 1169 11BA; # (뽓; 뽓; 뽓; 뽓; 뽓; ) HANGUL SYLLABLE BBOS
+BF54;BF54;1108 1169 11BB;BF54;1108 1169 11BB; # (뽔; 뽔; 뽔; 뽔; 뽔; ) HANGUL SYLLABLE BBOSS
+BF55;BF55;1108 1169 11BC;BF55;1108 1169 11BC; # (뽕; 뽕; 뽕; 뽕; 뽕; ) HANGUL SYLLABLE BBONG
+BF56;BF56;1108 1169 11BD;BF56;1108 1169 11BD; # (뽖; 뽖; 뽖; 뽖; 뽖; ) HANGUL SYLLABLE BBOJ
+BF57;BF57;1108 1169 11BE;BF57;1108 1169 11BE; # (뽗; 뽗; 뽗; 뽗; 뽗; ) HANGUL SYLLABLE BBOC
+BF58;BF58;1108 1169 11BF;BF58;1108 1169 11BF; # (뽘; 뽘; 뽘; 뽘; 뽘; ) HANGUL SYLLABLE BBOK
+BF59;BF59;1108 1169 11C0;BF59;1108 1169 11C0; # (뽙; 뽙; 뽙; 뽙; 뽙; ) HANGUL SYLLABLE BBOT
+BF5A;BF5A;1108 1169 11C1;BF5A;1108 1169 11C1; # (뽚; 뽚; 뽚; 뽚; 뽚; ) HANGUL SYLLABLE BBOP
+BF5B;BF5B;1108 1169 11C2;BF5B;1108 1169 11C2; # (뽛; 뽛; 뽛; 뽛; 뽛; ) HANGUL SYLLABLE BBOH
+BF5C;BF5C;1108 116A;BF5C;1108 116A; # (뽜; 뽜; 뽜; 뽜; 뽜; ) HANGUL SYLLABLE BBWA
+BF5D;BF5D;1108 116A 11A8;BF5D;1108 116A 11A8; # (뽝; 뽝; 뽝; 뽝; 뽝; ) HANGUL SYLLABLE BBWAG
+BF5E;BF5E;1108 116A 11A9;BF5E;1108 116A 11A9; # (뽞; 뽞; 뽞; 뽞; 뽞; ) HANGUL SYLLABLE BBWAGG
+BF5F;BF5F;1108 116A 11AA;BF5F;1108 116A 11AA; # (뽟; 뽟; 뽟; 뽟; 뽟; ) HANGUL SYLLABLE BBWAGS
+BF60;BF60;1108 116A 11AB;BF60;1108 116A 11AB; # (뽠; 뽠; 뽠; 뽠; 뽠; ) HANGUL SYLLABLE BBWAN
+BF61;BF61;1108 116A 11AC;BF61;1108 116A 11AC; # (뽡; 뽡; 뽡; 뽡; 뽡; ) HANGUL SYLLABLE BBWANJ
+BF62;BF62;1108 116A 11AD;BF62;1108 116A 11AD; # (뽢; 뽢; 뽢; 뽢; 뽢; ) HANGUL SYLLABLE BBWANH
+BF63;BF63;1108 116A 11AE;BF63;1108 116A 11AE; # (뽣; 뽣; 뽣; 뽣; 뽣; ) HANGUL SYLLABLE BBWAD
+BF64;BF64;1108 116A 11AF;BF64;1108 116A 11AF; # (뽤; 뽤; 뽤; 뽤; 뽤; ) HANGUL SYLLABLE BBWAL
+BF65;BF65;1108 116A 11B0;BF65;1108 116A 11B0; # (뽥; 뽥; 뽥; 뽥; 뽥; ) HANGUL SYLLABLE BBWALG
+BF66;BF66;1108 116A 11B1;BF66;1108 116A 11B1; # (뽦; 뽦; 뽦; 뽦; 뽦; ) HANGUL SYLLABLE BBWALM
+BF67;BF67;1108 116A 11B2;BF67;1108 116A 11B2; # (뽧; 뽧; 뽧; 뽧; 뽧; ) HANGUL SYLLABLE BBWALB
+BF68;BF68;1108 116A 11B3;BF68;1108 116A 11B3; # (뽨; 뽨; 뽨; 뽨; 뽨; ) HANGUL SYLLABLE BBWALS
+BF69;BF69;1108 116A 11B4;BF69;1108 116A 11B4; # (뽩; 뽩; 뽩; 뽩; 뽩; ) HANGUL SYLLABLE BBWALT
+BF6A;BF6A;1108 116A 11B5;BF6A;1108 116A 11B5; # (뽪; 뽪; 뽪; 뽪; 뽪; ) HANGUL SYLLABLE BBWALP
+BF6B;BF6B;1108 116A 11B6;BF6B;1108 116A 11B6; # (뽫; 뽫; 뽫; 뽫; 뽫; ) HANGUL SYLLABLE BBWALH
+BF6C;BF6C;1108 116A 11B7;BF6C;1108 116A 11B7; # (뽬; 뽬; 뽬; 뽬; 뽬; ) HANGUL SYLLABLE BBWAM
+BF6D;BF6D;1108 116A 11B8;BF6D;1108 116A 11B8; # (뽭; 뽭; 뽭; 뽭; 뽭; ) HANGUL SYLLABLE BBWAB
+BF6E;BF6E;1108 116A 11B9;BF6E;1108 116A 11B9; # (뽮; 뽮; 뽮; 뽮; 뽮; ) HANGUL SYLLABLE BBWABS
+BF6F;BF6F;1108 116A 11BA;BF6F;1108 116A 11BA; # (뽯; 뽯; 뽯; 뽯; 뽯; ) HANGUL SYLLABLE BBWAS
+BF70;BF70;1108 116A 11BB;BF70;1108 116A 11BB; # (뽰; 뽰; 뽰; 뽰; 뽰; ) HANGUL SYLLABLE BBWASS
+BF71;BF71;1108 116A 11BC;BF71;1108 116A 11BC; # (뽱; 뽱; 뽱; 뽱; 뽱; ) HANGUL SYLLABLE BBWANG
+BF72;BF72;1108 116A 11BD;BF72;1108 116A 11BD; # (뽲; 뽲; 뽲; 뽲; 뽲; ) HANGUL SYLLABLE BBWAJ
+BF73;BF73;1108 116A 11BE;BF73;1108 116A 11BE; # (뽳; 뽳; 뽳; 뽳; 뽳; ) HANGUL SYLLABLE BBWAC
+BF74;BF74;1108 116A 11BF;BF74;1108 116A 11BF; # (뽴; 뽴; 뽴; 뽴; 뽴; ) HANGUL SYLLABLE BBWAK
+BF75;BF75;1108 116A 11C0;BF75;1108 116A 11C0; # (뽵; 뽵; 뽵; 뽵; 뽵; ) HANGUL SYLLABLE BBWAT
+BF76;BF76;1108 116A 11C1;BF76;1108 116A 11C1; # (뽶; 뽶; 뽶; 뽶; 뽶; ) HANGUL SYLLABLE BBWAP
+BF77;BF77;1108 116A 11C2;BF77;1108 116A 11C2; # (뽷; 뽷; 뽷; 뽷; 뽷; ) HANGUL SYLLABLE BBWAH
+BF78;BF78;1108 116B;BF78;1108 116B; # (뽸; 뽸; 뽸; 뽸; 뽸; ) HANGUL SYLLABLE BBWAE
+BF79;BF79;1108 116B 11A8;BF79;1108 116B 11A8; # (뽹; 뽹; 뽹; 뽹; 뽹; ) HANGUL SYLLABLE BBWAEG
+BF7A;BF7A;1108 116B 11A9;BF7A;1108 116B 11A9; # (뽺; 뽺; 뽺; 뽺; 뽺; ) HANGUL SYLLABLE BBWAEGG
+BF7B;BF7B;1108 116B 11AA;BF7B;1108 116B 11AA; # (뽻; 뽻; 뽻; 뽻; 뽻; ) HANGUL SYLLABLE BBWAEGS
+BF7C;BF7C;1108 116B 11AB;BF7C;1108 116B 11AB; # (뽼; 뽼; 뽼; 뽼; 뽼; ) HANGUL SYLLABLE BBWAEN
+BF7D;BF7D;1108 116B 11AC;BF7D;1108 116B 11AC; # (뽽; 뽽; 뽽; 뽽; 뽽; ) HANGUL SYLLABLE BBWAENJ
+BF7E;BF7E;1108 116B 11AD;BF7E;1108 116B 11AD; # (뽾; 뽾; 뽾; 뽾; 뽾; ) HANGUL SYLLABLE BBWAENH
+BF7F;BF7F;1108 116B 11AE;BF7F;1108 116B 11AE; # (뽿; 뽿; 뽿; 뽿; 뽿; ) HANGUL SYLLABLE BBWAED
+BF80;BF80;1108 116B 11AF;BF80;1108 116B 11AF; # (뾀; 뾀; 뾀; 뾀; 뾀; ) HANGUL SYLLABLE BBWAEL
+BF81;BF81;1108 116B 11B0;BF81;1108 116B 11B0; # (뾁; 뾁; 뾁; 뾁; 뾁; ) HANGUL SYLLABLE BBWAELG
+BF82;BF82;1108 116B 11B1;BF82;1108 116B 11B1; # (뾂; 뾂; 뾂; 뾂; 뾂; ) HANGUL SYLLABLE BBWAELM
+BF83;BF83;1108 116B 11B2;BF83;1108 116B 11B2; # (뾃; 뾃; 뾃; 뾃; 뾃; ) HANGUL SYLLABLE BBWAELB
+BF84;BF84;1108 116B 11B3;BF84;1108 116B 11B3; # (뾄; 뾄; 뾄; 뾄; 뾄; ) HANGUL SYLLABLE BBWAELS
+BF85;BF85;1108 116B 11B4;BF85;1108 116B 11B4; # (뾅; 뾅; 뾅; 뾅; 뾅; ) HANGUL SYLLABLE BBWAELT
+BF86;BF86;1108 116B 11B5;BF86;1108 116B 11B5; # (뾆; 뾆; 뾆; 뾆; 뾆; ) HANGUL SYLLABLE BBWAELP
+BF87;BF87;1108 116B 11B6;BF87;1108 116B 11B6; # (뾇; 뾇; 뾇; 뾇; 뾇; ) HANGUL SYLLABLE BBWAELH
+BF88;BF88;1108 116B 11B7;BF88;1108 116B 11B7; # (뾈; 뾈; 뾈; 뾈; 뾈; ) HANGUL SYLLABLE BBWAEM
+BF89;BF89;1108 116B 11B8;BF89;1108 116B 11B8; # (뾉; 뾉; 뾉; 뾉; 뾉; ) HANGUL SYLLABLE BBWAEB
+BF8A;BF8A;1108 116B 11B9;BF8A;1108 116B 11B9; # (뾊; 뾊; 뾊; 뾊; 뾊; ) HANGUL SYLLABLE BBWAEBS
+BF8B;BF8B;1108 116B 11BA;BF8B;1108 116B 11BA; # (뾋; 뾋; 뾋; 뾋; 뾋; ) HANGUL SYLLABLE BBWAES
+BF8C;BF8C;1108 116B 11BB;BF8C;1108 116B 11BB; # (뾌; 뾌; 뾌; 뾌; 뾌; ) HANGUL SYLLABLE BBWAESS
+BF8D;BF8D;1108 116B 11BC;BF8D;1108 116B 11BC; # (뾍; 뾍; 뾍; 뾍; 뾍; ) HANGUL SYLLABLE BBWAENG
+BF8E;BF8E;1108 116B 11BD;BF8E;1108 116B 11BD; # (뾎; 뾎; 뾎; 뾎; 뾎; ) HANGUL SYLLABLE BBWAEJ
+BF8F;BF8F;1108 116B 11BE;BF8F;1108 116B 11BE; # (뾏; 뾏; 뾏; 뾏; 뾏; ) HANGUL SYLLABLE BBWAEC
+BF90;BF90;1108 116B 11BF;BF90;1108 116B 11BF; # (뾐; 뾐; 뾐; 뾐; 뾐; ) HANGUL SYLLABLE BBWAEK
+BF91;BF91;1108 116B 11C0;BF91;1108 116B 11C0; # (뾑; 뾑; 뾑; 뾑; 뾑; ) HANGUL SYLLABLE BBWAET
+BF92;BF92;1108 116B 11C1;BF92;1108 116B 11C1; # (뾒; 뾒; 뾒; 뾒; 뾒; ) HANGUL SYLLABLE BBWAEP
+BF93;BF93;1108 116B 11C2;BF93;1108 116B 11C2; # (뾓; 뾓; 뾓; 뾓; 뾓; ) HANGUL SYLLABLE BBWAEH
+BF94;BF94;1108 116C;BF94;1108 116C; # (뾔; 뾔; 뾔; 뾔; 뾔; ) HANGUL SYLLABLE BBOE
+BF95;BF95;1108 116C 11A8;BF95;1108 116C 11A8; # (뾕; 뾕; 뾕; 뾕; 뾕; ) HANGUL SYLLABLE BBOEG
+BF96;BF96;1108 116C 11A9;BF96;1108 116C 11A9; # (뾖; 뾖; 뾖; 뾖; 뾖; ) HANGUL SYLLABLE BBOEGG
+BF97;BF97;1108 116C 11AA;BF97;1108 116C 11AA; # (뾗; 뾗; 뾗; 뾗; 뾗; ) HANGUL SYLLABLE BBOEGS
+BF98;BF98;1108 116C 11AB;BF98;1108 116C 11AB; # (뾘; 뾘; 뾘; 뾘; 뾘; ) HANGUL SYLLABLE BBOEN
+BF99;BF99;1108 116C 11AC;BF99;1108 116C 11AC; # (뾙; 뾙; 뾙; 뾙; 뾙; ) HANGUL SYLLABLE BBOENJ
+BF9A;BF9A;1108 116C 11AD;BF9A;1108 116C 11AD; # (뾚; 뾚; 뾚; 뾚; 뾚; ) HANGUL SYLLABLE BBOENH
+BF9B;BF9B;1108 116C 11AE;BF9B;1108 116C 11AE; # (뾛; 뾛; 뾛; 뾛; 뾛; ) HANGUL SYLLABLE BBOED
+BF9C;BF9C;1108 116C 11AF;BF9C;1108 116C 11AF; # (뾜; 뾜; 뾜; 뾜; 뾜; ) HANGUL SYLLABLE BBOEL
+BF9D;BF9D;1108 116C 11B0;BF9D;1108 116C 11B0; # (뾝; 뾝; 뾝; 뾝; 뾝; ) HANGUL SYLLABLE BBOELG
+BF9E;BF9E;1108 116C 11B1;BF9E;1108 116C 11B1; # (뾞; 뾞; 뾞; 뾞; 뾞; ) HANGUL SYLLABLE BBOELM
+BF9F;BF9F;1108 116C 11B2;BF9F;1108 116C 11B2; # (뾟; 뾟; 뾟; 뾟; 뾟; ) HANGUL SYLLABLE BBOELB
+BFA0;BFA0;1108 116C 11B3;BFA0;1108 116C 11B3; # (뾠; 뾠; 뾠; 뾠; 뾠; ) HANGUL SYLLABLE BBOELS
+BFA1;BFA1;1108 116C 11B4;BFA1;1108 116C 11B4; # (뾡; 뾡; 뾡; 뾡; 뾡; ) HANGUL SYLLABLE BBOELT
+BFA2;BFA2;1108 116C 11B5;BFA2;1108 116C 11B5; # (뾢; 뾢; 뾢; 뾢; 뾢; ) HANGUL SYLLABLE BBOELP
+BFA3;BFA3;1108 116C 11B6;BFA3;1108 116C 11B6; # (뾣; 뾣; 뾣; 뾣; 뾣; ) HANGUL SYLLABLE BBOELH
+BFA4;BFA4;1108 116C 11B7;BFA4;1108 116C 11B7; # (뾤; 뾤; 뾤; 뾤; 뾤; ) HANGUL SYLLABLE BBOEM
+BFA5;BFA5;1108 116C 11B8;BFA5;1108 116C 11B8; # (뾥; 뾥; 뾥; 뾥; 뾥; ) HANGUL SYLLABLE BBOEB
+BFA6;BFA6;1108 116C 11B9;BFA6;1108 116C 11B9; # (뾦; 뾦; 뾦; 뾦; 뾦; ) HANGUL SYLLABLE BBOEBS
+BFA7;BFA7;1108 116C 11BA;BFA7;1108 116C 11BA; # (뾧; 뾧; 뾧; 뾧; 뾧; ) HANGUL SYLLABLE BBOES
+BFA8;BFA8;1108 116C 11BB;BFA8;1108 116C 11BB; # (뾨; 뾨; 뾨; 뾨; 뾨; ) HANGUL SYLLABLE BBOESS
+BFA9;BFA9;1108 116C 11BC;BFA9;1108 116C 11BC; # (뾩; 뾩; 뾩; 뾩; 뾩; ) HANGUL SYLLABLE BBOENG
+BFAA;BFAA;1108 116C 11BD;BFAA;1108 116C 11BD; # (뾪; 뾪; 뾪; 뾪; 뾪; ) HANGUL SYLLABLE BBOEJ
+BFAB;BFAB;1108 116C 11BE;BFAB;1108 116C 11BE; # (뾫; 뾫; 뾫; 뾫; 뾫; ) HANGUL SYLLABLE BBOEC
+BFAC;BFAC;1108 116C 11BF;BFAC;1108 116C 11BF; # (뾬; 뾬; 뾬; 뾬; 뾬; ) HANGUL SYLLABLE BBOEK
+BFAD;BFAD;1108 116C 11C0;BFAD;1108 116C 11C0; # (뾭; 뾭; 뾭; 뾭; 뾭; ) HANGUL SYLLABLE BBOET
+BFAE;BFAE;1108 116C 11C1;BFAE;1108 116C 11C1; # (뾮; 뾮; 뾮; 뾮; 뾮; ) HANGUL SYLLABLE BBOEP
+BFAF;BFAF;1108 116C 11C2;BFAF;1108 116C 11C2; # (뾯; 뾯; 뾯; 뾯; 뾯; ) HANGUL SYLLABLE BBOEH
+BFB0;BFB0;1108 116D;BFB0;1108 116D; # (뾰; 뾰; 뾰; 뾰; 뾰; ) HANGUL SYLLABLE BBYO
+BFB1;BFB1;1108 116D 11A8;BFB1;1108 116D 11A8; # (뾱; 뾱; 뾱; 뾱; 뾱; ) HANGUL SYLLABLE BBYOG
+BFB2;BFB2;1108 116D 11A9;BFB2;1108 116D 11A9; # (뾲; 뾲; 뾲; 뾲; 뾲; ) HANGUL SYLLABLE BBYOGG
+BFB3;BFB3;1108 116D 11AA;BFB3;1108 116D 11AA; # (뾳; 뾳; 뾳; 뾳; 뾳; ) HANGUL SYLLABLE BBYOGS
+BFB4;BFB4;1108 116D 11AB;BFB4;1108 116D 11AB; # (뾴; 뾴; 뾴; 뾴; 뾴; ) HANGUL SYLLABLE BBYON
+BFB5;BFB5;1108 116D 11AC;BFB5;1108 116D 11AC; # (뾵; 뾵; 뾵; 뾵; 뾵; ) HANGUL SYLLABLE BBYONJ
+BFB6;BFB6;1108 116D 11AD;BFB6;1108 116D 11AD; # (뾶; 뾶; 뾶; 뾶; 뾶; ) HANGUL SYLLABLE BBYONH
+BFB7;BFB7;1108 116D 11AE;BFB7;1108 116D 11AE; # (뾷; 뾷; 뾷; 뾷; 뾷; ) HANGUL SYLLABLE BBYOD
+BFB8;BFB8;1108 116D 11AF;BFB8;1108 116D 11AF; # (뾸; 뾸; 뾸; 뾸; 뾸; ) HANGUL SYLLABLE BBYOL
+BFB9;BFB9;1108 116D 11B0;BFB9;1108 116D 11B0; # (뾹; 뾹; 뾹; 뾹; 뾹; ) HANGUL SYLLABLE BBYOLG
+BFBA;BFBA;1108 116D 11B1;BFBA;1108 116D 11B1; # (뾺; 뾺; 뾺; 뾺; 뾺; ) HANGUL SYLLABLE BBYOLM
+BFBB;BFBB;1108 116D 11B2;BFBB;1108 116D 11B2; # (뾻; 뾻; 뾻; 뾻; 뾻; ) HANGUL SYLLABLE BBYOLB
+BFBC;BFBC;1108 116D 11B3;BFBC;1108 116D 11B3; # (뾼; 뾼; 뾼; 뾼; 뾼; ) HANGUL SYLLABLE BBYOLS
+BFBD;BFBD;1108 116D 11B4;BFBD;1108 116D 11B4; # (뾽; 뾽; 뾽; 뾽; 뾽; ) HANGUL SYLLABLE BBYOLT
+BFBE;BFBE;1108 116D 11B5;BFBE;1108 116D 11B5; # (뾾; 뾾; 뾾; 뾾; 뾾; ) HANGUL SYLLABLE BBYOLP
+BFBF;BFBF;1108 116D 11B6;BFBF;1108 116D 11B6; # (뾿; 뾿; 뾿; 뾿; 뾿; ) HANGUL SYLLABLE BBYOLH
+BFC0;BFC0;1108 116D 11B7;BFC0;1108 116D 11B7; # (뿀; 뿀; 뿀; 뿀; 뿀; ) HANGUL SYLLABLE BBYOM
+BFC1;BFC1;1108 116D 11B8;BFC1;1108 116D 11B8; # (뿁; 뿁; 뿁; 뿁; 뿁; ) HANGUL SYLLABLE BBYOB
+BFC2;BFC2;1108 116D 11B9;BFC2;1108 116D 11B9; # (뿂; 뿂; 뿂; 뿂; 뿂; ) HANGUL SYLLABLE BBYOBS
+BFC3;BFC3;1108 116D 11BA;BFC3;1108 116D 11BA; # (뿃; 뿃; 뿃; 뿃; 뿃; ) HANGUL SYLLABLE BBYOS
+BFC4;BFC4;1108 116D 11BB;BFC4;1108 116D 11BB; # (뿄; 뿄; 뿄; 뿄; 뿄; ) HANGUL SYLLABLE BBYOSS
+BFC5;BFC5;1108 116D 11BC;BFC5;1108 116D 11BC; # (뿅; 뿅; 뿅; 뿅; 뿅; ) HANGUL SYLLABLE BBYONG
+BFC6;BFC6;1108 116D 11BD;BFC6;1108 116D 11BD; # (뿆; 뿆; 뿆; 뿆; 뿆; ) HANGUL SYLLABLE BBYOJ
+BFC7;BFC7;1108 116D 11BE;BFC7;1108 116D 11BE; # (뿇; 뿇; 뿇; 뿇; 뿇; ) HANGUL SYLLABLE BBYOC
+BFC8;BFC8;1108 116D 11BF;BFC8;1108 116D 11BF; # (뿈; 뿈; 뿈; 뿈; 뿈; ) HANGUL SYLLABLE BBYOK
+BFC9;BFC9;1108 116D 11C0;BFC9;1108 116D 11C0; # (뿉; 뿉; 뿉; 뿉; 뿉; ) HANGUL SYLLABLE BBYOT
+BFCA;BFCA;1108 116D 11C1;BFCA;1108 116D 11C1; # (뿊; 뿊; 뿊; 뿊; 뿊; ) HANGUL SYLLABLE BBYOP
+BFCB;BFCB;1108 116D 11C2;BFCB;1108 116D 11C2; # (뿋; 뿋; 뿋; 뿋; 뿋; ) HANGUL SYLLABLE BBYOH
+BFCC;BFCC;1108 116E;BFCC;1108 116E; # (뿌; 뿌; 뿌; 뿌; 뿌; ) HANGUL SYLLABLE BBU
+BFCD;BFCD;1108 116E 11A8;BFCD;1108 116E 11A8; # (뿍; 뿍; 뿍; 뿍; 뿍; ) HANGUL SYLLABLE BBUG
+BFCE;BFCE;1108 116E 11A9;BFCE;1108 116E 11A9; # (뿎; 뿎; 뿎; 뿎; 뿎; ) HANGUL SYLLABLE BBUGG
+BFCF;BFCF;1108 116E 11AA;BFCF;1108 116E 11AA; # (뿏; 뿏; 뿏; 뿏; 뿏; ) HANGUL SYLLABLE BBUGS
+BFD0;BFD0;1108 116E 11AB;BFD0;1108 116E 11AB; # (뿐; 뿐; 뿐; 뿐; 뿐; ) HANGUL SYLLABLE BBUN
+BFD1;BFD1;1108 116E 11AC;BFD1;1108 116E 11AC; # (뿑; 뿑; 뿑; 뿑; 뿑; ) HANGUL SYLLABLE BBUNJ
+BFD2;BFD2;1108 116E 11AD;BFD2;1108 116E 11AD; # (뿒; 뿒; 뿒; 뿒; 뿒; ) HANGUL SYLLABLE BBUNH
+BFD3;BFD3;1108 116E 11AE;BFD3;1108 116E 11AE; # (뿓; 뿓; 뿓; 뿓; 뿓; ) HANGUL SYLLABLE BBUD
+BFD4;BFD4;1108 116E 11AF;BFD4;1108 116E 11AF; # (뿔; 뿔; 뿔; 뿔; 뿔; ) HANGUL SYLLABLE BBUL
+BFD5;BFD5;1108 116E 11B0;BFD5;1108 116E 11B0; # (뿕; 뿕; 뿕; 뿕; 뿕; ) HANGUL SYLLABLE BBULG
+BFD6;BFD6;1108 116E 11B1;BFD6;1108 116E 11B1; # (뿖; 뿖; 뿖; 뿖; 뿖; ) HANGUL SYLLABLE BBULM
+BFD7;BFD7;1108 116E 11B2;BFD7;1108 116E 11B2; # (뿗; 뿗; 뿗; 뿗; 뿗; ) HANGUL SYLLABLE BBULB
+BFD8;BFD8;1108 116E 11B3;BFD8;1108 116E 11B3; # (뿘; 뿘; 뿘; 뿘; 뿘; ) HANGUL SYLLABLE BBULS
+BFD9;BFD9;1108 116E 11B4;BFD9;1108 116E 11B4; # (뿙; 뿙; 뿙; 뿙; 뿙; ) HANGUL SYLLABLE BBULT
+BFDA;BFDA;1108 116E 11B5;BFDA;1108 116E 11B5; # (뿚; 뿚; 뿚; 뿚; 뿚; ) HANGUL SYLLABLE BBULP
+BFDB;BFDB;1108 116E 11B6;BFDB;1108 116E 11B6; # (뿛; 뿛; 뿛; 뿛; 뿛; ) HANGUL SYLLABLE BBULH
+BFDC;BFDC;1108 116E 11B7;BFDC;1108 116E 11B7; # (뿜; 뿜; 뿜; 뿜; 뿜; ) HANGUL SYLLABLE BBUM
+BFDD;BFDD;1108 116E 11B8;BFDD;1108 116E 11B8; # (뿝; 뿝; 뿝; 뿝; 뿝; ) HANGUL SYLLABLE BBUB
+BFDE;BFDE;1108 116E 11B9;BFDE;1108 116E 11B9; # (뿞; 뿞; 뿞; 뿞; 뿞; ) HANGUL SYLLABLE BBUBS
+BFDF;BFDF;1108 116E 11BA;BFDF;1108 116E 11BA; # (뿟; 뿟; 뿟; 뿟; 뿟; ) HANGUL SYLLABLE BBUS
+BFE0;BFE0;1108 116E 11BB;BFE0;1108 116E 11BB; # (뿠; 뿠; 뿠; 뿠; 뿠; ) HANGUL SYLLABLE BBUSS
+BFE1;BFE1;1108 116E 11BC;BFE1;1108 116E 11BC; # (뿡; 뿡; 뿡; 뿡; 뿡; ) HANGUL SYLLABLE BBUNG
+BFE2;BFE2;1108 116E 11BD;BFE2;1108 116E 11BD; # (뿢; 뿢; 뿢; 뿢; 뿢; ) HANGUL SYLLABLE BBUJ
+BFE3;BFE3;1108 116E 11BE;BFE3;1108 116E 11BE; # (뿣; 뿣; 뿣; 뿣; 뿣; ) HANGUL SYLLABLE BBUC
+BFE4;BFE4;1108 116E 11BF;BFE4;1108 116E 11BF; # (뿤; 뿤; 뿤; 뿤; 뿤; ) HANGUL SYLLABLE BBUK
+BFE5;BFE5;1108 116E 11C0;BFE5;1108 116E 11C0; # (뿥; 뿥; 뿥; 뿥; 뿥; ) HANGUL SYLLABLE BBUT
+BFE6;BFE6;1108 116E 11C1;BFE6;1108 116E 11C1; # (뿦; 뿦; 뿦; 뿦; 뿦; ) HANGUL SYLLABLE BBUP
+BFE7;BFE7;1108 116E 11C2;BFE7;1108 116E 11C2; # (뿧; 뿧; 뿧; 뿧; 뿧; ) HANGUL SYLLABLE BBUH
+BFE8;BFE8;1108 116F;BFE8;1108 116F; # (뿨; 뿨; 뿨; 뿨; 뿨; ) HANGUL SYLLABLE BBWEO
+BFE9;BFE9;1108 116F 11A8;BFE9;1108 116F 11A8; # (뿩; 뿩; 뿩; 뿩; 뿩; ) HANGUL SYLLABLE BBWEOG
+BFEA;BFEA;1108 116F 11A9;BFEA;1108 116F 11A9; # (뿪; 뿪; 뿪; 뿪; 뿪; ) HANGUL SYLLABLE BBWEOGG
+BFEB;BFEB;1108 116F 11AA;BFEB;1108 116F 11AA; # (뿫; 뿫; 뿫; 뿫; 뿫; ) HANGUL SYLLABLE BBWEOGS
+BFEC;BFEC;1108 116F 11AB;BFEC;1108 116F 11AB; # (뿬; 뿬; 뿬; 뿬; 뿬; ) HANGUL SYLLABLE BBWEON
+BFED;BFED;1108 116F 11AC;BFED;1108 116F 11AC; # (뿭; 뿭; 뿭; 뿭; 뿭; ) HANGUL SYLLABLE BBWEONJ
+BFEE;BFEE;1108 116F 11AD;BFEE;1108 116F 11AD; # (뿮; 뿮; 뿮; 뿮; 뿮; ) HANGUL SYLLABLE BBWEONH
+BFEF;BFEF;1108 116F 11AE;BFEF;1108 116F 11AE; # (뿯; 뿯; 뿯; 뿯; 뿯; ) HANGUL SYLLABLE BBWEOD
+BFF0;BFF0;1108 116F 11AF;BFF0;1108 116F 11AF; # (뿰; 뿰; 뿰; 뿰; 뿰; ) HANGUL SYLLABLE BBWEOL
+BFF1;BFF1;1108 116F 11B0;BFF1;1108 116F 11B0; # (뿱; 뿱; 뿱; 뿱; 뿱; ) HANGUL SYLLABLE BBWEOLG
+BFF2;BFF2;1108 116F 11B1;BFF2;1108 116F 11B1; # (뿲; 뿲; 뿲; 뿲; 뿲; ) HANGUL SYLLABLE BBWEOLM
+BFF3;BFF3;1108 116F 11B2;BFF3;1108 116F 11B2; # (뿳; 뿳; 뿳; 뿳; 뿳; ) HANGUL SYLLABLE BBWEOLB
+BFF4;BFF4;1108 116F 11B3;BFF4;1108 116F 11B3; # (뿴; 뿴; 뿴; 뿴; 뿴; ) HANGUL SYLLABLE BBWEOLS
+BFF5;BFF5;1108 116F 11B4;BFF5;1108 116F 11B4; # (뿵; 뿵; 뿵; 뿵; 뿵; ) HANGUL SYLLABLE BBWEOLT
+BFF6;BFF6;1108 116F 11B5;BFF6;1108 116F 11B5; # (뿶; 뿶; 뿶; 뿶; 뿶; ) HANGUL SYLLABLE BBWEOLP
+BFF7;BFF7;1108 116F 11B6;BFF7;1108 116F 11B6; # (뿷; 뿷; 뿷; 뿷; 뿷; ) HANGUL SYLLABLE BBWEOLH
+BFF8;BFF8;1108 116F 11B7;BFF8;1108 116F 11B7; # (뿸; 뿸; 뿸; 뿸; 뿸; ) HANGUL SYLLABLE BBWEOM
+BFF9;BFF9;1108 116F 11B8;BFF9;1108 116F 11B8; # (뿹; 뿹; 뿹; 뿹; 뿹; ) HANGUL SYLLABLE BBWEOB
+BFFA;BFFA;1108 116F 11B9;BFFA;1108 116F 11B9; # (뿺; 뿺; 뿺; 뿺; 뿺; ) HANGUL SYLLABLE BBWEOBS
+BFFB;BFFB;1108 116F 11BA;BFFB;1108 116F 11BA; # (뿻; 뿻; 뿻; 뿻; 뿻; ) HANGUL SYLLABLE BBWEOS
+BFFC;BFFC;1108 116F 11BB;BFFC;1108 116F 11BB; # (뿼; 뿼; 뿼; 뿼; 뿼; ) HANGUL SYLLABLE BBWEOSS
+BFFD;BFFD;1108 116F 11BC;BFFD;1108 116F 11BC; # (뿽; 뿽; 뿽; 뿽; 뿽; ) HANGUL SYLLABLE BBWEONG
+BFFE;BFFE;1108 116F 11BD;BFFE;1108 116F 11BD; # (뿾; 뿾; 뿾; 뿾; 뿾; ) HANGUL SYLLABLE BBWEOJ
+BFFF;BFFF;1108 116F 11BE;BFFF;1108 116F 11BE; # (뿿; 뿿; 뿿; 뿿; 뿿; ) HANGUL SYLLABLE BBWEOC
+C000;C000;1108 116F 11BF;C000;1108 116F 11BF; # (쀀; 쀀; 쀀; 쀀; 쀀; ) HANGUL SYLLABLE BBWEOK
+C001;C001;1108 116F 11C0;C001;1108 116F 11C0; # (쀁; 쀁; 쀁; 쀁; 쀁; ) HANGUL SYLLABLE BBWEOT
+C002;C002;1108 116F 11C1;C002;1108 116F 11C1; # (쀂; 쀂; 쀂; 쀂; 쀂; ) HANGUL SYLLABLE BBWEOP
+C003;C003;1108 116F 11C2;C003;1108 116F 11C2; # (쀃; 쀃; 쀃; 쀃; 쀃; ) HANGUL SYLLABLE BBWEOH
+C004;C004;1108 1170;C004;1108 1170; # (쀄; 쀄; 쀄; 쀄; 쀄; ) HANGUL SYLLABLE BBWE
+C005;C005;1108 1170 11A8;C005;1108 1170 11A8; # (쀅; 쀅; 쀅; 쀅; 쀅; ) HANGUL SYLLABLE BBWEG
+C006;C006;1108 1170 11A9;C006;1108 1170 11A9; # (쀆; 쀆; 쀆; 쀆; 쀆; ) HANGUL SYLLABLE BBWEGG
+C007;C007;1108 1170 11AA;C007;1108 1170 11AA; # (쀇; 쀇; 쀇; 쀇; 쀇; ) HANGUL SYLLABLE BBWEGS
+C008;C008;1108 1170 11AB;C008;1108 1170 11AB; # (쀈; 쀈; 쀈; 쀈; 쀈; ) HANGUL SYLLABLE BBWEN
+C009;C009;1108 1170 11AC;C009;1108 1170 11AC; # (쀉; 쀉; 쀉; 쀉; 쀉; ) HANGUL SYLLABLE BBWENJ
+C00A;C00A;1108 1170 11AD;C00A;1108 1170 11AD; # (쀊; 쀊; 쀊; 쀊; 쀊; ) HANGUL SYLLABLE BBWENH
+C00B;C00B;1108 1170 11AE;C00B;1108 1170 11AE; # (쀋; 쀋; 쀋; 쀋; 쀋; ) HANGUL SYLLABLE BBWED
+C00C;C00C;1108 1170 11AF;C00C;1108 1170 11AF; # (쀌; 쀌; 쀌; 쀌; 쀌; ) HANGUL SYLLABLE BBWEL
+C00D;C00D;1108 1170 11B0;C00D;1108 1170 11B0; # (쀍; 쀍; 쀍; 쀍; 쀍; ) HANGUL SYLLABLE BBWELG
+C00E;C00E;1108 1170 11B1;C00E;1108 1170 11B1; # (쀎; 쀎; 쀎; 쀎; 쀎; ) HANGUL SYLLABLE BBWELM
+C00F;C00F;1108 1170 11B2;C00F;1108 1170 11B2; # (쀏; 쀏; 쀏; 쀏; 쀏; ) HANGUL SYLLABLE BBWELB
+C010;C010;1108 1170 11B3;C010;1108 1170 11B3; # (쀐; 쀐; 쀐; 쀐; 쀐; ) HANGUL SYLLABLE BBWELS
+C011;C011;1108 1170 11B4;C011;1108 1170 11B4; # (쀑; 쀑; 쀑; 쀑; 쀑; ) HANGUL SYLLABLE BBWELT
+C012;C012;1108 1170 11B5;C012;1108 1170 11B5; # (쀒; 쀒; 쀒; 쀒; 쀒; ) HANGUL SYLLABLE BBWELP
+C013;C013;1108 1170 11B6;C013;1108 1170 11B6; # (쀓; 쀓; 쀓; 쀓; 쀓; ) HANGUL SYLLABLE BBWELH
+C014;C014;1108 1170 11B7;C014;1108 1170 11B7; # (쀔; 쀔; 쀔; 쀔; 쀔; ) HANGUL SYLLABLE BBWEM
+C015;C015;1108 1170 11B8;C015;1108 1170 11B8; # (쀕; 쀕; 쀕; 쀕; 쀕; ) HANGUL SYLLABLE BBWEB
+C016;C016;1108 1170 11B9;C016;1108 1170 11B9; # (쀖; 쀖; 쀖; 쀖; 쀖; ) HANGUL SYLLABLE BBWEBS
+C017;C017;1108 1170 11BA;C017;1108 1170 11BA; # (쀗; 쀗; 쀗; 쀗; 쀗; ) HANGUL SYLLABLE BBWES
+C018;C018;1108 1170 11BB;C018;1108 1170 11BB; # (쀘; 쀘; 쀘; 쀘; 쀘; ) HANGUL SYLLABLE BBWESS
+C019;C019;1108 1170 11BC;C019;1108 1170 11BC; # (쀙; 쀙; 쀙; 쀙; 쀙; ) HANGUL SYLLABLE BBWENG
+C01A;C01A;1108 1170 11BD;C01A;1108 1170 11BD; # (쀚; 쀚; 쀚; 쀚; 쀚; ) HANGUL SYLLABLE BBWEJ
+C01B;C01B;1108 1170 11BE;C01B;1108 1170 11BE; # (쀛; 쀛; 쀛; 쀛; 쀛; ) HANGUL SYLLABLE BBWEC
+C01C;C01C;1108 1170 11BF;C01C;1108 1170 11BF; # (쀜; 쀜; 쀜; 쀜; 쀜; ) HANGUL SYLLABLE BBWEK
+C01D;C01D;1108 1170 11C0;C01D;1108 1170 11C0; # (쀝; 쀝; 쀝; 쀝; 쀝; ) HANGUL SYLLABLE BBWET
+C01E;C01E;1108 1170 11C1;C01E;1108 1170 11C1; # (쀞; 쀞; 쀞; 쀞; 쀞; ) HANGUL SYLLABLE BBWEP
+C01F;C01F;1108 1170 11C2;C01F;1108 1170 11C2; # (쀟; 쀟; 쀟; 쀟; 쀟; ) HANGUL SYLLABLE BBWEH
+C020;C020;1108 1171;C020;1108 1171; # (쀠; 쀠; 쀠; 쀠; 쀠; ) HANGUL SYLLABLE BBWI
+C021;C021;1108 1171 11A8;C021;1108 1171 11A8; # (쀡; 쀡; 쀡; 쀡; 쀡; ) HANGUL SYLLABLE BBWIG
+C022;C022;1108 1171 11A9;C022;1108 1171 11A9; # (쀢; 쀢; 쀢; 쀢; 쀢; ) HANGUL SYLLABLE BBWIGG
+C023;C023;1108 1171 11AA;C023;1108 1171 11AA; # (쀣; 쀣; 쀣; 쀣; 쀣; ) HANGUL SYLLABLE BBWIGS
+C024;C024;1108 1171 11AB;C024;1108 1171 11AB; # (쀤; 쀤; 쀤; 쀤; 쀤; ) HANGUL SYLLABLE BBWIN
+C025;C025;1108 1171 11AC;C025;1108 1171 11AC; # (쀥; 쀥; 쀥; 쀥; 쀥; ) HANGUL SYLLABLE BBWINJ
+C026;C026;1108 1171 11AD;C026;1108 1171 11AD; # (쀦; 쀦; 쀦; 쀦; 쀦; ) HANGUL SYLLABLE BBWINH
+C027;C027;1108 1171 11AE;C027;1108 1171 11AE; # (쀧; 쀧; 쀧; 쀧; 쀧; ) HANGUL SYLLABLE BBWID
+C028;C028;1108 1171 11AF;C028;1108 1171 11AF; # (쀨; 쀨; 쀨; 쀨; 쀨; ) HANGUL SYLLABLE BBWIL
+C029;C029;1108 1171 11B0;C029;1108 1171 11B0; # (쀩; 쀩; 쀩; 쀩; 쀩; ) HANGUL SYLLABLE BBWILG
+C02A;C02A;1108 1171 11B1;C02A;1108 1171 11B1; # (쀪; 쀪; 쀪; 쀪; 쀪; ) HANGUL SYLLABLE BBWILM
+C02B;C02B;1108 1171 11B2;C02B;1108 1171 11B2; # (쀫; 쀫; 쀫; 쀫; 쀫; ) HANGUL SYLLABLE BBWILB
+C02C;C02C;1108 1171 11B3;C02C;1108 1171 11B3; # (쀬; 쀬; 쀬; 쀬; 쀬; ) HANGUL SYLLABLE BBWILS
+C02D;C02D;1108 1171 11B4;C02D;1108 1171 11B4; # (쀭; 쀭; 쀭; 쀭; 쀭; ) HANGUL SYLLABLE BBWILT
+C02E;C02E;1108 1171 11B5;C02E;1108 1171 11B5; # (쀮; 쀮; 쀮; 쀮; 쀮; ) HANGUL SYLLABLE BBWILP
+C02F;C02F;1108 1171 11B6;C02F;1108 1171 11B6; # (쀯; 쀯; 쀯; 쀯; 쀯; ) HANGUL SYLLABLE BBWILH
+C030;C030;1108 1171 11B7;C030;1108 1171 11B7; # (쀰; 쀰; 쀰; 쀰; 쀰; ) HANGUL SYLLABLE BBWIM
+C031;C031;1108 1171 11B8;C031;1108 1171 11B8; # (쀱; 쀱; 쀱; 쀱; 쀱; ) HANGUL SYLLABLE BBWIB
+C032;C032;1108 1171 11B9;C032;1108 1171 11B9; # (쀲; 쀲; 쀲; 쀲; 쀲; ) HANGUL SYLLABLE BBWIBS
+C033;C033;1108 1171 11BA;C033;1108 1171 11BA; # (쀳; 쀳; 쀳; 쀳; 쀳; ) HANGUL SYLLABLE BBWIS
+C034;C034;1108 1171 11BB;C034;1108 1171 11BB; # (쀴; 쀴; 쀴; 쀴; 쀴; ) HANGUL SYLLABLE BBWISS
+C035;C035;1108 1171 11BC;C035;1108 1171 11BC; # (쀵; 쀵; 쀵; 쀵; 쀵; ) HANGUL SYLLABLE BBWING
+C036;C036;1108 1171 11BD;C036;1108 1171 11BD; # (쀶; 쀶; 쀶; 쀶; 쀶; ) HANGUL SYLLABLE BBWIJ
+C037;C037;1108 1171 11BE;C037;1108 1171 11BE; # (쀷; 쀷; 쀷; 쀷; 쀷; ) HANGUL SYLLABLE BBWIC
+C038;C038;1108 1171 11BF;C038;1108 1171 11BF; # (쀸; 쀸; 쀸; 쀸; 쀸; ) HANGUL SYLLABLE BBWIK
+C039;C039;1108 1171 11C0;C039;1108 1171 11C0; # (쀹; 쀹; 쀹; 쀹; 쀹; ) HANGUL SYLLABLE BBWIT
+C03A;C03A;1108 1171 11C1;C03A;1108 1171 11C1; # (쀺; 쀺; 쀺; 쀺; 쀺; ) HANGUL SYLLABLE BBWIP
+C03B;C03B;1108 1171 11C2;C03B;1108 1171 11C2; # (쀻; 쀻; 쀻; 쀻; 쀻; ) HANGUL SYLLABLE BBWIH
+C03C;C03C;1108 1172;C03C;1108 1172; # (쀼; 쀼; 쀼; 쀼; 쀼; ) HANGUL SYLLABLE BBYU
+C03D;C03D;1108 1172 11A8;C03D;1108 1172 11A8; # (쀽; 쀽; 쀽; 쀽; 쀽; ) HANGUL SYLLABLE BBYUG
+C03E;C03E;1108 1172 11A9;C03E;1108 1172 11A9; # (쀾; 쀾; 쀾; 쀾; 쀾; ) HANGUL SYLLABLE BBYUGG
+C03F;C03F;1108 1172 11AA;C03F;1108 1172 11AA; # (쀿; 쀿; 쀿; 쀿; 쀿; ) HANGUL SYLLABLE BBYUGS
+C040;C040;1108 1172 11AB;C040;1108 1172 11AB; # (쁀; 쁀; 쁀; 쁀; 쁀; ) HANGUL SYLLABLE BBYUN
+C041;C041;1108 1172 11AC;C041;1108 1172 11AC; # (쁁; 쁁; 쁁; 쁁; 쁁; ) HANGUL SYLLABLE BBYUNJ
+C042;C042;1108 1172 11AD;C042;1108 1172 11AD; # (쁂; 쁂; 쁂; 쁂; 쁂; ) HANGUL SYLLABLE BBYUNH
+C043;C043;1108 1172 11AE;C043;1108 1172 11AE; # (쁃; 쁃; 쁃; 쁃; 쁃; ) HANGUL SYLLABLE BBYUD
+C044;C044;1108 1172 11AF;C044;1108 1172 11AF; # (쁄; 쁄; 쁄; 쁄; 쁄; ) HANGUL SYLLABLE BBYUL
+C045;C045;1108 1172 11B0;C045;1108 1172 11B0; # (쁅; 쁅; 쁅; 쁅; 쁅; ) HANGUL SYLLABLE BBYULG
+C046;C046;1108 1172 11B1;C046;1108 1172 11B1; # (쁆; 쁆; 쁆; 쁆; 쁆; ) HANGUL SYLLABLE BBYULM
+C047;C047;1108 1172 11B2;C047;1108 1172 11B2; # (쁇; 쁇; 쁇; 쁇; 쁇; ) HANGUL SYLLABLE BBYULB
+C048;C048;1108 1172 11B3;C048;1108 1172 11B3; # (쁈; 쁈; 쁈; 쁈; 쁈; ) HANGUL SYLLABLE BBYULS
+C049;C049;1108 1172 11B4;C049;1108 1172 11B4; # (쁉; 쁉; 쁉; 쁉; 쁉; ) HANGUL SYLLABLE BBYULT
+C04A;C04A;1108 1172 11B5;C04A;1108 1172 11B5; # (쁊; 쁊; 쁊; 쁊; 쁊; ) HANGUL SYLLABLE BBYULP
+C04B;C04B;1108 1172 11B6;C04B;1108 1172 11B6; # (쁋; 쁋; 쁋; 쁋; 쁋; ) HANGUL SYLLABLE BBYULH
+C04C;C04C;1108 1172 11B7;C04C;1108 1172 11B7; # (쁌; 쁌; 쁌; 쁌; 쁌; ) HANGUL SYLLABLE BBYUM
+C04D;C04D;1108 1172 11B8;C04D;1108 1172 11B8; # (쁍; 쁍; 쁍; 쁍; 쁍; ) HANGUL SYLLABLE BBYUB
+C04E;C04E;1108 1172 11B9;C04E;1108 1172 11B9; # (쁎; 쁎; 쁎; 쁎; 쁎; ) HANGUL SYLLABLE BBYUBS
+C04F;C04F;1108 1172 11BA;C04F;1108 1172 11BA; # (쁏; 쁏; 쁏; 쁏; 쁏; ) HANGUL SYLLABLE BBYUS
+C050;C050;1108 1172 11BB;C050;1108 1172 11BB; # (쁐; 쁐; 쁐; 쁐; 쁐; ) HANGUL SYLLABLE BBYUSS
+C051;C051;1108 1172 11BC;C051;1108 1172 11BC; # (쁑; 쁑; 쁑; 쁑; 쁑; ) HANGUL SYLLABLE BBYUNG
+C052;C052;1108 1172 11BD;C052;1108 1172 11BD; # (쁒; 쁒; 쁒; 쁒; 쁒; ) HANGUL SYLLABLE BBYUJ
+C053;C053;1108 1172 11BE;C053;1108 1172 11BE; # (쁓; 쁓; 쁓; 쁓; 쁓; ) HANGUL SYLLABLE BBYUC
+C054;C054;1108 1172 11BF;C054;1108 1172 11BF; # (쁔; 쁔; 쁔; 쁔; 쁔; ) HANGUL SYLLABLE BBYUK
+C055;C055;1108 1172 11C0;C055;1108 1172 11C0; # (쁕; 쁕; 쁕; 쁕; 쁕; ) HANGUL SYLLABLE BBYUT
+C056;C056;1108 1172 11C1;C056;1108 1172 11C1; # (쁖; 쁖; 쁖; 쁖; 쁖; ) HANGUL SYLLABLE BBYUP
+C057;C057;1108 1172 11C2;C057;1108 1172 11C2; # (쁗; 쁗; 쁗; 쁗; 쁗; ) HANGUL SYLLABLE BBYUH
+C058;C058;1108 1173;C058;1108 1173; # (쁘; 쁘; 쁘; 쁘; 쁘; ) HANGUL SYLLABLE BBEU
+C059;C059;1108 1173 11A8;C059;1108 1173 11A8; # (쁙; 쁙; 쁙; 쁙; 쁙; ) HANGUL SYLLABLE BBEUG
+C05A;C05A;1108 1173 11A9;C05A;1108 1173 11A9; # (쁚; 쁚; 쁚; 쁚; 쁚; ) HANGUL SYLLABLE BBEUGG
+C05B;C05B;1108 1173 11AA;C05B;1108 1173 11AA; # (쁛; 쁛; 쁛; 쁛; 쁛; ) HANGUL SYLLABLE BBEUGS
+C05C;C05C;1108 1173 11AB;C05C;1108 1173 11AB; # (쁜; 쁜; 쁜; 쁜; 쁜; ) HANGUL SYLLABLE BBEUN
+C05D;C05D;1108 1173 11AC;C05D;1108 1173 11AC; # (쁝; 쁝; 쁝; 쁝; 쁝; ) HANGUL SYLLABLE BBEUNJ
+C05E;C05E;1108 1173 11AD;C05E;1108 1173 11AD; # (쁞; 쁞; 쁞; 쁞; 쁞; ) HANGUL SYLLABLE BBEUNH
+C05F;C05F;1108 1173 11AE;C05F;1108 1173 11AE; # (쁟; 쁟; 쁟; 쁟; 쁟; ) HANGUL SYLLABLE BBEUD
+C060;C060;1108 1173 11AF;C060;1108 1173 11AF; # (쁠; 쁠; 쁠; 쁠; 쁠; ) HANGUL SYLLABLE BBEUL
+C061;C061;1108 1173 11B0;C061;1108 1173 11B0; # (쁡; 쁡; 쁡; 쁡; 쁡; ) HANGUL SYLLABLE BBEULG
+C062;C062;1108 1173 11B1;C062;1108 1173 11B1; # (쁢; 쁢; 쁢; 쁢; 쁢; ) HANGUL SYLLABLE BBEULM
+C063;C063;1108 1173 11B2;C063;1108 1173 11B2; # (쁣; 쁣; 쁣; 쁣; 쁣; ) HANGUL SYLLABLE BBEULB
+C064;C064;1108 1173 11B3;C064;1108 1173 11B3; # (쁤; 쁤; 쁤; 쁤; 쁤; ) HANGUL SYLLABLE BBEULS
+C065;C065;1108 1173 11B4;C065;1108 1173 11B4; # (쁥; 쁥; 쁥; 쁥; 쁥; ) HANGUL SYLLABLE BBEULT
+C066;C066;1108 1173 11B5;C066;1108 1173 11B5; # (쁦; 쁦; 쁦; 쁦; 쁦; ) HANGUL SYLLABLE BBEULP
+C067;C067;1108 1173 11B6;C067;1108 1173 11B6; # (쁧; 쁧; 쁧; 쁧; 쁧; ) HANGUL SYLLABLE BBEULH
+C068;C068;1108 1173 11B7;C068;1108 1173 11B7; # (쁨; 쁨; 쁨; 쁨; 쁨; ) HANGUL SYLLABLE BBEUM
+C069;C069;1108 1173 11B8;C069;1108 1173 11B8; # (쁩; 쁩; 쁩; 쁩; 쁩; ) HANGUL SYLLABLE BBEUB
+C06A;C06A;1108 1173 11B9;C06A;1108 1173 11B9; # (쁪; 쁪; 쁪; 쁪; 쁪; ) HANGUL SYLLABLE BBEUBS
+C06B;C06B;1108 1173 11BA;C06B;1108 1173 11BA; # (쁫; 쁫; 쁫; 쁫; 쁫; ) HANGUL SYLLABLE BBEUS
+C06C;C06C;1108 1173 11BB;C06C;1108 1173 11BB; # (쁬; 쁬; 쁬; 쁬; 쁬; ) HANGUL SYLLABLE BBEUSS
+C06D;C06D;1108 1173 11BC;C06D;1108 1173 11BC; # (쁭; 쁭; 쁭; 쁭; 쁭; ) HANGUL SYLLABLE BBEUNG
+C06E;C06E;1108 1173 11BD;C06E;1108 1173 11BD; # (쁮; 쁮; 쁮; 쁮; 쁮; ) HANGUL SYLLABLE BBEUJ
+C06F;C06F;1108 1173 11BE;C06F;1108 1173 11BE; # (쁯; 쁯; 쁯; 쁯; 쁯; ) HANGUL SYLLABLE BBEUC
+C070;C070;1108 1173 11BF;C070;1108 1173 11BF; # (쁰; 쁰; 쁰; 쁰; 쁰; ) HANGUL SYLLABLE BBEUK
+C071;C071;1108 1173 11C0;C071;1108 1173 11C0; # (쁱; 쁱; 쁱; 쁱; 쁱; ) HANGUL SYLLABLE BBEUT
+C072;C072;1108 1173 11C1;C072;1108 1173 11C1; # (쁲; 쁲; 쁲; 쁲; 쁲; ) HANGUL SYLLABLE BBEUP
+C073;C073;1108 1173 11C2;C073;1108 1173 11C2; # (쁳; 쁳; 쁳; 쁳; 쁳; ) HANGUL SYLLABLE BBEUH
+C074;C074;1108 1174;C074;1108 1174; # (쁴; 쁴; 쁴; 쁴; 쁴; ) HANGUL SYLLABLE BBYI
+C075;C075;1108 1174 11A8;C075;1108 1174 11A8; # (쁵; 쁵; 쁵; 쁵; 쁵; ) HANGUL SYLLABLE BBYIG
+C076;C076;1108 1174 11A9;C076;1108 1174 11A9; # (쁶; 쁶; 쁶; 쁶; 쁶; ) HANGUL SYLLABLE BBYIGG
+C077;C077;1108 1174 11AA;C077;1108 1174 11AA; # (쁷; 쁷; 쁷; 쁷; 쁷; ) HANGUL SYLLABLE BBYIGS
+C078;C078;1108 1174 11AB;C078;1108 1174 11AB; # (쁸; 쁸; 쁸; 쁸; 쁸; ) HANGUL SYLLABLE BBYIN
+C079;C079;1108 1174 11AC;C079;1108 1174 11AC; # (쁹; 쁹; 쁹; 쁹; 쁹; ) HANGUL SYLLABLE BBYINJ
+C07A;C07A;1108 1174 11AD;C07A;1108 1174 11AD; # (쁺; 쁺; 쁺; 쁺; 쁺; ) HANGUL SYLLABLE BBYINH
+C07B;C07B;1108 1174 11AE;C07B;1108 1174 11AE; # (쁻; 쁻; 쁻; 쁻; 쁻; ) HANGUL SYLLABLE BBYID
+C07C;C07C;1108 1174 11AF;C07C;1108 1174 11AF; # (쁼; 쁼; 쁼; 쁼; 쁼; ) HANGUL SYLLABLE BBYIL
+C07D;C07D;1108 1174 11B0;C07D;1108 1174 11B0; # (쁽; 쁽; 쁽; 쁽; 쁽; ) HANGUL SYLLABLE BBYILG
+C07E;C07E;1108 1174 11B1;C07E;1108 1174 11B1; # (쁾; 쁾; 쁾; 쁾; 쁾; ) HANGUL SYLLABLE BBYILM
+C07F;C07F;1108 1174 11B2;C07F;1108 1174 11B2; # (쁿; 쁿; 쁿; 쁿; 쁿; ) HANGUL SYLLABLE BBYILB
+C080;C080;1108 1174 11B3;C080;1108 1174 11B3; # (삀; 삀; 삀; 삀; 삀; ) HANGUL SYLLABLE BBYILS
+C081;C081;1108 1174 11B4;C081;1108 1174 11B4; # (삁; 삁; 삁; 삁; 삁; ) HANGUL SYLLABLE BBYILT
+C082;C082;1108 1174 11B5;C082;1108 1174 11B5; # (삂; 삂; 삂; 삂; 삂; ) HANGUL SYLLABLE BBYILP
+C083;C083;1108 1174 11B6;C083;1108 1174 11B6; # (삃; 삃; 삃; 삃; 삃; ) HANGUL SYLLABLE BBYILH
+C084;C084;1108 1174 11B7;C084;1108 1174 11B7; # (삄; 삄; 삄; 삄; 삄; ) HANGUL SYLLABLE BBYIM
+C085;C085;1108 1174 11B8;C085;1108 1174 11B8; # (삅; 삅; 삅; 삅; 삅; ) HANGUL SYLLABLE BBYIB
+C086;C086;1108 1174 11B9;C086;1108 1174 11B9; # (삆; 삆; 삆; 삆; 삆; ) HANGUL SYLLABLE BBYIBS
+C087;C087;1108 1174 11BA;C087;1108 1174 11BA; # (삇; 삇; 삇; 삇; 삇; ) HANGUL SYLLABLE BBYIS
+C088;C088;1108 1174 11BB;C088;1108 1174 11BB; # (삈; 삈; 삈; 삈; 삈; ) HANGUL SYLLABLE BBYISS
+C089;C089;1108 1174 11BC;C089;1108 1174 11BC; # (삉; 삉; 삉; 삉; 삉; ) HANGUL SYLLABLE BBYING
+C08A;C08A;1108 1174 11BD;C08A;1108 1174 11BD; # (삊; 삊; 삊; 삊; 삊; ) HANGUL SYLLABLE BBYIJ
+C08B;C08B;1108 1174 11BE;C08B;1108 1174 11BE; # (삋; 삋; 삋; 삋; 삋; ) HANGUL SYLLABLE BBYIC
+C08C;C08C;1108 1174 11BF;C08C;1108 1174 11BF; # (삌; 삌; 삌; 삌; 삌; ) HANGUL SYLLABLE BBYIK
+C08D;C08D;1108 1174 11C0;C08D;1108 1174 11C0; # (삍; 삍; 삍; 삍; 삍; ) HANGUL SYLLABLE BBYIT
+C08E;C08E;1108 1174 11C1;C08E;1108 1174 11C1; # (삎; 삎; 삎; 삎; 삎; ) HANGUL SYLLABLE BBYIP
+C08F;C08F;1108 1174 11C2;C08F;1108 1174 11C2; # (삏; 삏; 삏; 삏; 삏; ) HANGUL SYLLABLE BBYIH
+C090;C090;1108 1175;C090;1108 1175; # (삐; 삐; 삐; 삐; 삐; ) HANGUL SYLLABLE BBI
+C091;C091;1108 1175 11A8;C091;1108 1175 11A8; # (삑; 삑; 삑; 삑; 삑; ) HANGUL SYLLABLE BBIG
+C092;C092;1108 1175 11A9;C092;1108 1175 11A9; # (삒; 삒; 삒; 삒; 삒; ) HANGUL SYLLABLE BBIGG
+C093;C093;1108 1175 11AA;C093;1108 1175 11AA; # (삓; 삓; 삓; 삓; 삓; ) HANGUL SYLLABLE BBIGS
+C094;C094;1108 1175 11AB;C094;1108 1175 11AB; # (삔; 삔; 삔; 삔; 삔; ) HANGUL SYLLABLE BBIN
+C095;C095;1108 1175 11AC;C095;1108 1175 11AC; # (삕; 삕; 삕; 삕; 삕; ) HANGUL SYLLABLE BBINJ
+C096;C096;1108 1175 11AD;C096;1108 1175 11AD; # (삖; 삖; 삖; 삖; 삖; ) HANGUL SYLLABLE BBINH
+C097;C097;1108 1175 11AE;C097;1108 1175 11AE; # (삗; 삗; 삗; 삗; 삗; ) HANGUL SYLLABLE BBID
+C098;C098;1108 1175 11AF;C098;1108 1175 11AF; # (삘; 삘; 삘; 삘; 삘; ) HANGUL SYLLABLE BBIL
+C099;C099;1108 1175 11B0;C099;1108 1175 11B0; # (삙; 삙; 삙; 삙; 삙; ) HANGUL SYLLABLE BBILG
+C09A;C09A;1108 1175 11B1;C09A;1108 1175 11B1; # (삚; 삚; 삚; 삚; 삚; ) HANGUL SYLLABLE BBILM
+C09B;C09B;1108 1175 11B2;C09B;1108 1175 11B2; # (삛; 삛; 삛; 삛; 삛; ) HANGUL SYLLABLE BBILB
+C09C;C09C;1108 1175 11B3;C09C;1108 1175 11B3; # (삜; 삜; 삜; 삜; 삜; ) HANGUL SYLLABLE BBILS
+C09D;C09D;1108 1175 11B4;C09D;1108 1175 11B4; # (삝; 삝; 삝; 삝; 삝; ) HANGUL SYLLABLE BBILT
+C09E;C09E;1108 1175 11B5;C09E;1108 1175 11B5; # (삞; 삞; 삞; 삞; 삞; ) HANGUL SYLLABLE BBILP
+C09F;C09F;1108 1175 11B6;C09F;1108 1175 11B6; # (삟; 삟; 삟; 삟; 삟; ) HANGUL SYLLABLE BBILH
+C0A0;C0A0;1108 1175 11B7;C0A0;1108 1175 11B7; # (삠; 삠; 삠; 삠; 삠; ) HANGUL SYLLABLE BBIM
+C0A1;C0A1;1108 1175 11B8;C0A1;1108 1175 11B8; # (삡; 삡; 삡; 삡; 삡; ) HANGUL SYLLABLE BBIB
+C0A2;C0A2;1108 1175 11B9;C0A2;1108 1175 11B9; # (삢; 삢; 삢; 삢; 삢; ) HANGUL SYLLABLE BBIBS
+C0A3;C0A3;1108 1175 11BA;C0A3;1108 1175 11BA; # (삣; 삣; 삣; 삣; 삣; ) HANGUL SYLLABLE BBIS
+C0A4;C0A4;1108 1175 11BB;C0A4;1108 1175 11BB; # (삤; 삤; 삤; 삤; 삤; ) HANGUL SYLLABLE BBISS
+C0A5;C0A5;1108 1175 11BC;C0A5;1108 1175 11BC; # (삥; 삥; 삥; 삥; 삥; ) HANGUL SYLLABLE BBING
+C0A6;C0A6;1108 1175 11BD;C0A6;1108 1175 11BD; # (삦; 삦; 삦; 삦; 삦; ) HANGUL SYLLABLE BBIJ
+C0A7;C0A7;1108 1175 11BE;C0A7;1108 1175 11BE; # (삧; 삧; 삧; 삧; 삧; ) HANGUL SYLLABLE BBIC
+C0A8;C0A8;1108 1175 11BF;C0A8;1108 1175 11BF; # (삨; 삨; 삨; 삨; 삨; ) HANGUL SYLLABLE BBIK
+C0A9;C0A9;1108 1175 11C0;C0A9;1108 1175 11C0; # (삩; 삩; 삩; 삩; 삩; ) HANGUL SYLLABLE BBIT
+C0AA;C0AA;1108 1175 11C1;C0AA;1108 1175 11C1; # (삪; 삪; 삪; 삪; 삪; ) HANGUL SYLLABLE BBIP
+C0AB;C0AB;1108 1175 11C2;C0AB;1108 1175 11C2; # (삫; 삫; 삫; 삫; 삫; ) HANGUL SYLLABLE BBIH
+C0AC;C0AC;1109 1161;C0AC;1109 1161; # (사; 사; 사; 사; 사; ) HANGUL SYLLABLE SA
+C0AD;C0AD;1109 1161 11A8;C0AD;1109 1161 11A8; # (삭; 삭; 삭; 삭; 삭; ) HANGUL SYLLABLE SAG
+C0AE;C0AE;1109 1161 11A9;C0AE;1109 1161 11A9; # (삮; 삮; 삮; 삮; 삮; ) HANGUL SYLLABLE SAGG
+C0AF;C0AF;1109 1161 11AA;C0AF;1109 1161 11AA; # (삯; 삯; 삯; 삯; 삯; ) HANGUL SYLLABLE SAGS
+C0B0;C0B0;1109 1161 11AB;C0B0;1109 1161 11AB; # (산; 산; 산; 산; 산; ) HANGUL SYLLABLE SAN
+C0B1;C0B1;1109 1161 11AC;C0B1;1109 1161 11AC; # (삱; 삱; 삱; 삱; 삱; ) HANGUL SYLLABLE SANJ
+C0B2;C0B2;1109 1161 11AD;C0B2;1109 1161 11AD; # (삲; 삲; 삲; 삲; 삲; ) HANGUL SYLLABLE SANH
+C0B3;C0B3;1109 1161 11AE;C0B3;1109 1161 11AE; # (삳; 삳; 삳; 삳; 삳; ) HANGUL SYLLABLE SAD
+C0B4;C0B4;1109 1161 11AF;C0B4;1109 1161 11AF; # (살; 살; 살; 살; 살; ) HANGUL SYLLABLE SAL
+C0B5;C0B5;1109 1161 11B0;C0B5;1109 1161 11B0; # (삵; 삵; 삵; 삵; 삵; ) HANGUL SYLLABLE SALG
+C0B6;C0B6;1109 1161 11B1;C0B6;1109 1161 11B1; # (삶; 삶; 삶; 삶; 삶; ) HANGUL SYLLABLE SALM
+C0B7;C0B7;1109 1161 11B2;C0B7;1109 1161 11B2; # (삷; 삷; 삷; 삷; 삷; ) HANGUL SYLLABLE SALB
+C0B8;C0B8;1109 1161 11B3;C0B8;1109 1161 11B3; # (삸; 삸; 삸; 삸; 삸; ) HANGUL SYLLABLE SALS
+C0B9;C0B9;1109 1161 11B4;C0B9;1109 1161 11B4; # (삹; 삹; 삹; 삹; 삹; ) HANGUL SYLLABLE SALT
+C0BA;C0BA;1109 1161 11B5;C0BA;1109 1161 11B5; # (삺; 삺; 삺; 삺; 삺; ) HANGUL SYLLABLE SALP
+C0BB;C0BB;1109 1161 11B6;C0BB;1109 1161 11B6; # (삻; 삻; 삻; 삻; 삻; ) HANGUL SYLLABLE SALH
+C0BC;C0BC;1109 1161 11B7;C0BC;1109 1161 11B7; # (삼; 삼; 삼; 삼; 삼; ) HANGUL SYLLABLE SAM
+C0BD;C0BD;1109 1161 11B8;C0BD;1109 1161 11B8; # (삽; 삽; 삽; 삽; 삽; ) HANGUL SYLLABLE SAB
+C0BE;C0BE;1109 1161 11B9;C0BE;1109 1161 11B9; # (삾; 삾; 삾; 삾; 삾; ) HANGUL SYLLABLE SABS
+C0BF;C0BF;1109 1161 11BA;C0BF;1109 1161 11BA; # (삿; 삿; 삿; 삿; 삿; ) HANGUL SYLLABLE SAS
+C0C0;C0C0;1109 1161 11BB;C0C0;1109 1161 11BB; # (샀; 샀; 샀; 샀; 샀; ) HANGUL SYLLABLE SASS
+C0C1;C0C1;1109 1161 11BC;C0C1;1109 1161 11BC; # (상; 상; 상; 상; 상; ) HANGUL SYLLABLE SANG
+C0C2;C0C2;1109 1161 11BD;C0C2;1109 1161 11BD; # (샂; 샂; 샂; 샂; 샂; ) HANGUL SYLLABLE SAJ
+C0C3;C0C3;1109 1161 11BE;C0C3;1109 1161 11BE; # (샃; 샃; 샃; 샃; 샃; ) HANGUL SYLLABLE SAC
+C0C4;C0C4;1109 1161 11BF;C0C4;1109 1161 11BF; # (샄; 샄; 샄; 샄; 샄; ) HANGUL SYLLABLE SAK
+C0C5;C0C5;1109 1161 11C0;C0C5;1109 1161 11C0; # (샅; 샅; 샅; 샅; 샅; ) HANGUL SYLLABLE SAT
+C0C6;C0C6;1109 1161 11C1;C0C6;1109 1161 11C1; # (샆; 샆; 샆; 샆; 샆; ) HANGUL SYLLABLE SAP
+C0C7;C0C7;1109 1161 11C2;C0C7;1109 1161 11C2; # (샇; 샇; 샇; 샇; 샇; ) HANGUL SYLLABLE SAH
+C0C8;C0C8;1109 1162;C0C8;1109 1162; # (새; 새; 새; 새; 새; ) HANGUL SYLLABLE SAE
+C0C9;C0C9;1109 1162 11A8;C0C9;1109 1162 11A8; # (색; 색; 색; 색; 색; ) HANGUL SYLLABLE SAEG
+C0CA;C0CA;1109 1162 11A9;C0CA;1109 1162 11A9; # (샊; 샊; 샊; 샊; 샊; ) HANGUL SYLLABLE SAEGG
+C0CB;C0CB;1109 1162 11AA;C0CB;1109 1162 11AA; # (샋; 샋; 샋; 샋; 샋; ) HANGUL SYLLABLE SAEGS
+C0CC;C0CC;1109 1162 11AB;C0CC;1109 1162 11AB; # (샌; 샌; 샌; 샌; 샌; ) HANGUL SYLLABLE SAEN
+C0CD;C0CD;1109 1162 11AC;C0CD;1109 1162 11AC; # (샍; 샍; 샍; 샍; 샍; ) HANGUL SYLLABLE SAENJ
+C0CE;C0CE;1109 1162 11AD;C0CE;1109 1162 11AD; # (샎; 샎; 샎; 샎; 샎; ) HANGUL SYLLABLE SAENH
+C0CF;C0CF;1109 1162 11AE;C0CF;1109 1162 11AE; # (샏; 샏; 샏; 샏; 샏; ) HANGUL SYLLABLE SAED
+C0D0;C0D0;1109 1162 11AF;C0D0;1109 1162 11AF; # (샐; 샐; 샐; 샐; 샐; ) HANGUL SYLLABLE SAEL
+C0D1;C0D1;1109 1162 11B0;C0D1;1109 1162 11B0; # (샑; 샑; 샑; 샑; 샑; ) HANGUL SYLLABLE SAELG
+C0D2;C0D2;1109 1162 11B1;C0D2;1109 1162 11B1; # (샒; 샒; 샒; 샒; 샒; ) HANGUL SYLLABLE SAELM
+C0D3;C0D3;1109 1162 11B2;C0D3;1109 1162 11B2; # (샓; 샓; 샓; 샓; 샓; ) HANGUL SYLLABLE SAELB
+C0D4;C0D4;1109 1162 11B3;C0D4;1109 1162 11B3; # (샔; 샔; 샔; 샔; 샔; ) HANGUL SYLLABLE SAELS
+C0D5;C0D5;1109 1162 11B4;C0D5;1109 1162 11B4; # (샕; 샕; 샕; 샕; 샕; ) HANGUL SYLLABLE SAELT
+C0D6;C0D6;1109 1162 11B5;C0D6;1109 1162 11B5; # (샖; 샖; 샖; 샖; 샖; ) HANGUL SYLLABLE SAELP
+C0D7;C0D7;1109 1162 11B6;C0D7;1109 1162 11B6; # (샗; 샗; 샗; 샗; 샗; ) HANGUL SYLLABLE SAELH
+C0D8;C0D8;1109 1162 11B7;C0D8;1109 1162 11B7; # (샘; 샘; 샘; 샘; 샘; ) HANGUL SYLLABLE SAEM
+C0D9;C0D9;1109 1162 11B8;C0D9;1109 1162 11B8; # (샙; 샙; 샙; 샙; 샙; ) HANGUL SYLLABLE SAEB
+C0DA;C0DA;1109 1162 11B9;C0DA;1109 1162 11B9; # (샚; 샚; 샚; 샚; 샚; ) HANGUL SYLLABLE SAEBS
+C0DB;C0DB;1109 1162 11BA;C0DB;1109 1162 11BA; # (샛; 샛; 샛; 샛; 샛; ) HANGUL SYLLABLE SAES
+C0DC;C0DC;1109 1162 11BB;C0DC;1109 1162 11BB; # (샜; 샜; 샜; 샜; 샜; ) HANGUL SYLLABLE SAESS
+C0DD;C0DD;1109 1162 11BC;C0DD;1109 1162 11BC; # (생; 생; 생; 생; 생; ) HANGUL SYLLABLE SAENG
+C0DE;C0DE;1109 1162 11BD;C0DE;1109 1162 11BD; # (샞; 샞; 샞; 샞; 샞; ) HANGUL SYLLABLE SAEJ
+C0DF;C0DF;1109 1162 11BE;C0DF;1109 1162 11BE; # (샟; 샟; 샟; 샟; 샟; ) HANGUL SYLLABLE SAEC
+C0E0;C0E0;1109 1162 11BF;C0E0;1109 1162 11BF; # (샠; 샠; 샠; 샠; 샠; ) HANGUL SYLLABLE SAEK
+C0E1;C0E1;1109 1162 11C0;C0E1;1109 1162 11C0; # (샡; 샡; 샡; 샡; 샡; ) HANGUL SYLLABLE SAET
+C0E2;C0E2;1109 1162 11C1;C0E2;1109 1162 11C1; # (샢; 샢; 샢; 샢; 샢; ) HANGUL SYLLABLE SAEP
+C0E3;C0E3;1109 1162 11C2;C0E3;1109 1162 11C2; # (샣; 샣; 샣; 샣; 샣; ) HANGUL SYLLABLE SAEH
+C0E4;C0E4;1109 1163;C0E4;1109 1163; # (샤; 샤; 샤; 샤; 샤; ) HANGUL SYLLABLE SYA
+C0E5;C0E5;1109 1163 11A8;C0E5;1109 1163 11A8; # (샥; 샥; 샥; 샥; 샥; ) HANGUL SYLLABLE SYAG
+C0E6;C0E6;1109 1163 11A9;C0E6;1109 1163 11A9; # (샦; 샦; 샦; 샦; 샦; ) HANGUL SYLLABLE SYAGG
+C0E7;C0E7;1109 1163 11AA;C0E7;1109 1163 11AA; # (샧; 샧; 샧; 샧; 샧; ) HANGUL SYLLABLE SYAGS
+C0E8;C0E8;1109 1163 11AB;C0E8;1109 1163 11AB; # (샨; 샨; 샨; 샨; 샨; ) HANGUL SYLLABLE SYAN
+C0E9;C0E9;1109 1163 11AC;C0E9;1109 1163 11AC; # (샩; 샩; 샩; 샩; 샩; ) HANGUL SYLLABLE SYANJ
+C0EA;C0EA;1109 1163 11AD;C0EA;1109 1163 11AD; # (샪; 샪; 샪; 샪; 샪; ) HANGUL SYLLABLE SYANH
+C0EB;C0EB;1109 1163 11AE;C0EB;1109 1163 11AE; # (샫; 샫; 샫; 샫; 샫; ) HANGUL SYLLABLE SYAD
+C0EC;C0EC;1109 1163 11AF;C0EC;1109 1163 11AF; # (샬; 샬; 샬; 샬; 샬; ) HANGUL SYLLABLE SYAL
+C0ED;C0ED;1109 1163 11B0;C0ED;1109 1163 11B0; # (샭; 샭; 샭; 샭; 샭; ) HANGUL SYLLABLE SYALG
+C0EE;C0EE;1109 1163 11B1;C0EE;1109 1163 11B1; # (샮; 샮; 샮; 샮; 샮; ) HANGUL SYLLABLE SYALM
+C0EF;C0EF;1109 1163 11B2;C0EF;1109 1163 11B2; # (샯; 샯; 샯; 샯; 샯; ) HANGUL SYLLABLE SYALB
+C0F0;C0F0;1109 1163 11B3;C0F0;1109 1163 11B3; # (샰; 샰; 샰; 샰; 샰; ) HANGUL SYLLABLE SYALS
+C0F1;C0F1;1109 1163 11B4;C0F1;1109 1163 11B4; # (샱; 샱; 샱; 샱; 샱; ) HANGUL SYLLABLE SYALT
+C0F2;C0F2;1109 1163 11B5;C0F2;1109 1163 11B5; # (샲; 샲; 샲; 샲; 샲; ) HANGUL SYLLABLE SYALP
+C0F3;C0F3;1109 1163 11B6;C0F3;1109 1163 11B6; # (샳; 샳; 샳; 샳; 샳; ) HANGUL SYLLABLE SYALH
+C0F4;C0F4;1109 1163 11B7;C0F4;1109 1163 11B7; # (샴; 샴; 샴; 샴; 샴; ) HANGUL SYLLABLE SYAM
+C0F5;C0F5;1109 1163 11B8;C0F5;1109 1163 11B8; # (샵; 샵; 샵; 샵; 샵; ) HANGUL SYLLABLE SYAB
+C0F6;C0F6;1109 1163 11B9;C0F6;1109 1163 11B9; # (샶; 샶; 샶; 샶; 샶; ) HANGUL SYLLABLE SYABS
+C0F7;C0F7;1109 1163 11BA;C0F7;1109 1163 11BA; # (샷; 샷; 샷; 샷; 샷; ) HANGUL SYLLABLE SYAS
+C0F8;C0F8;1109 1163 11BB;C0F8;1109 1163 11BB; # (샸; 샸; 샸; 샸; 샸; ) HANGUL SYLLABLE SYASS
+C0F9;C0F9;1109 1163 11BC;C0F9;1109 1163 11BC; # (샹; 샹; 샹; 샹; 샹; ) HANGUL SYLLABLE SYANG
+C0FA;C0FA;1109 1163 11BD;C0FA;1109 1163 11BD; # (샺; 샺; 샺; 샺; 샺; ) HANGUL SYLLABLE SYAJ
+C0FB;C0FB;1109 1163 11BE;C0FB;1109 1163 11BE; # (샻; 샻; 샻; 샻; 샻; ) HANGUL SYLLABLE SYAC
+C0FC;C0FC;1109 1163 11BF;C0FC;1109 1163 11BF; # (샼; 샼; 샼; 샼; 샼; ) HANGUL SYLLABLE SYAK
+C0FD;C0FD;1109 1163 11C0;C0FD;1109 1163 11C0; # (샽; 샽; 샽; 샽; 샽; ) HANGUL SYLLABLE SYAT
+C0FE;C0FE;1109 1163 11C1;C0FE;1109 1163 11C1; # (샾; 샾; 샾; 샾; 샾; ) HANGUL SYLLABLE SYAP
+C0FF;C0FF;1109 1163 11C2;C0FF;1109 1163 11C2; # (샿; 샿; 샿; 샿; 샿; ) HANGUL SYLLABLE SYAH
+C100;C100;1109 1164;C100;1109 1164; # (섀; 섀; 섀; 섀; 섀; ) HANGUL SYLLABLE SYAE
+C101;C101;1109 1164 11A8;C101;1109 1164 11A8; # (섁; 섁; 섁; 섁; 섁; ) HANGUL SYLLABLE SYAEG
+C102;C102;1109 1164 11A9;C102;1109 1164 11A9; # (섂; 섂; 섂; 섂; 섂; ) HANGUL SYLLABLE SYAEGG
+C103;C103;1109 1164 11AA;C103;1109 1164 11AA; # (섃; 섃; 섃; 섃; 섃; ) HANGUL SYLLABLE SYAEGS
+C104;C104;1109 1164 11AB;C104;1109 1164 11AB; # (섄; 섄; 섄; 섄; 섄; ) HANGUL SYLLABLE SYAEN
+C105;C105;1109 1164 11AC;C105;1109 1164 11AC; # (섅; 섅; 섅; 섅; 섅; ) HANGUL SYLLABLE SYAENJ
+C106;C106;1109 1164 11AD;C106;1109 1164 11AD; # (섆; 섆; 섆; 섆; 섆; ) HANGUL SYLLABLE SYAENH
+C107;C107;1109 1164 11AE;C107;1109 1164 11AE; # (섇; 섇; 섇; 섇; 섇; ) HANGUL SYLLABLE SYAED
+C108;C108;1109 1164 11AF;C108;1109 1164 11AF; # (섈; 섈; 섈; 섈; 섈; ) HANGUL SYLLABLE SYAEL
+C109;C109;1109 1164 11B0;C109;1109 1164 11B0; # (섉; 섉; 섉; 섉; 섉; ) HANGUL SYLLABLE SYAELG
+C10A;C10A;1109 1164 11B1;C10A;1109 1164 11B1; # (섊; 섊; 섊; 섊; 섊; ) HANGUL SYLLABLE SYAELM
+C10B;C10B;1109 1164 11B2;C10B;1109 1164 11B2; # (섋; 섋; 섋; 섋; 섋; ) HANGUL SYLLABLE SYAELB
+C10C;C10C;1109 1164 11B3;C10C;1109 1164 11B3; # (섌; 섌; 섌; 섌; 섌; ) HANGUL SYLLABLE SYAELS
+C10D;C10D;1109 1164 11B4;C10D;1109 1164 11B4; # (섍; 섍; 섍; 섍; 섍; ) HANGUL SYLLABLE SYAELT
+C10E;C10E;1109 1164 11B5;C10E;1109 1164 11B5; # (섎; 섎; 섎; 섎; 섎; ) HANGUL SYLLABLE SYAELP
+C10F;C10F;1109 1164 11B6;C10F;1109 1164 11B6; # (섏; 섏; 섏; 섏; 섏; ) HANGUL SYLLABLE SYAELH
+C110;C110;1109 1164 11B7;C110;1109 1164 11B7; # (섐; 섐; 섐; 섐; 섐; ) HANGUL SYLLABLE SYAEM
+C111;C111;1109 1164 11B8;C111;1109 1164 11B8; # (섑; 섑; 섑; 섑; 섑; ) HANGUL SYLLABLE SYAEB
+C112;C112;1109 1164 11B9;C112;1109 1164 11B9; # (섒; 섒; 섒; 섒; 섒; ) HANGUL SYLLABLE SYAEBS
+C113;C113;1109 1164 11BA;C113;1109 1164 11BA; # (섓; 섓; 섓; 섓; 섓; ) HANGUL SYLLABLE SYAES
+C114;C114;1109 1164 11BB;C114;1109 1164 11BB; # (섔; 섔; 섔; 섔; 섔; ) HANGUL SYLLABLE SYAESS
+C115;C115;1109 1164 11BC;C115;1109 1164 11BC; # (섕; 섕; 섕; 섕; 섕; ) HANGUL SYLLABLE SYAENG
+C116;C116;1109 1164 11BD;C116;1109 1164 11BD; # (섖; 섖; 섖; 섖; 섖; ) HANGUL SYLLABLE SYAEJ
+C117;C117;1109 1164 11BE;C117;1109 1164 11BE; # (섗; 섗; 섗; 섗; 섗; ) HANGUL SYLLABLE SYAEC
+C118;C118;1109 1164 11BF;C118;1109 1164 11BF; # (섘; 섘; 섘; 섘; 섘; ) HANGUL SYLLABLE SYAEK
+C119;C119;1109 1164 11C0;C119;1109 1164 11C0; # (섙; 섙; 섙; 섙; 섙; ) HANGUL SYLLABLE SYAET
+C11A;C11A;1109 1164 11C1;C11A;1109 1164 11C1; # (섚; 섚; 섚; 섚; 섚; ) HANGUL SYLLABLE SYAEP
+C11B;C11B;1109 1164 11C2;C11B;1109 1164 11C2; # (섛; 섛; 섛; 섛; 섛; ) HANGUL SYLLABLE SYAEH
+C11C;C11C;1109 1165;C11C;1109 1165; # (서; 서; 서; 서; 서; ) HANGUL SYLLABLE SEO
+C11D;C11D;1109 1165 11A8;C11D;1109 1165 11A8; # (석; 석; 석; 석; 석; ) HANGUL SYLLABLE SEOG
+C11E;C11E;1109 1165 11A9;C11E;1109 1165 11A9; # (섞; 섞; 섞; 섞; 섞; ) HANGUL SYLLABLE SEOGG
+C11F;C11F;1109 1165 11AA;C11F;1109 1165 11AA; # (섟; 섟; 섟; 섟; 섟; ) HANGUL SYLLABLE SEOGS
+C120;C120;1109 1165 11AB;C120;1109 1165 11AB; # (선; 선; 선; 선; 선; ) HANGUL SYLLABLE SEON
+C121;C121;1109 1165 11AC;C121;1109 1165 11AC; # (섡; 섡; 섡; 섡; 섡; ) HANGUL SYLLABLE SEONJ
+C122;C122;1109 1165 11AD;C122;1109 1165 11AD; # (섢; 섢; 섢; 섢; 섢; ) HANGUL SYLLABLE SEONH
+C123;C123;1109 1165 11AE;C123;1109 1165 11AE; # (섣; 섣; 섣; 섣; 섣; ) HANGUL SYLLABLE SEOD
+C124;C124;1109 1165 11AF;C124;1109 1165 11AF; # (설; 설; 설; 설; 설; ) HANGUL SYLLABLE SEOL
+C125;C125;1109 1165 11B0;C125;1109 1165 11B0; # (섥; 섥; 섥; 섥; 섥; ) HANGUL SYLLABLE SEOLG
+C126;C126;1109 1165 11B1;C126;1109 1165 11B1; # (섦; 섦; 섦; 섦; 섦; ) HANGUL SYLLABLE SEOLM
+C127;C127;1109 1165 11B2;C127;1109 1165 11B2; # (섧; 섧; 섧; 섧; 섧; ) HANGUL SYLLABLE SEOLB
+C128;C128;1109 1165 11B3;C128;1109 1165 11B3; # (섨; 섨; 섨; 섨; 섨; ) HANGUL SYLLABLE SEOLS
+C129;C129;1109 1165 11B4;C129;1109 1165 11B4; # (섩; 섩; 섩; 섩; 섩; ) HANGUL SYLLABLE SEOLT
+C12A;C12A;1109 1165 11B5;C12A;1109 1165 11B5; # (섪; 섪; 섪; 섪; 섪; ) HANGUL SYLLABLE SEOLP
+C12B;C12B;1109 1165 11B6;C12B;1109 1165 11B6; # (섫; 섫; 섫; 섫; 섫; ) HANGUL SYLLABLE SEOLH
+C12C;C12C;1109 1165 11B7;C12C;1109 1165 11B7; # (섬; 섬; 섬; 섬; 섬; ) HANGUL SYLLABLE SEOM
+C12D;C12D;1109 1165 11B8;C12D;1109 1165 11B8; # (섭; 섭; 섭; 섭; 섭; ) HANGUL SYLLABLE SEOB
+C12E;C12E;1109 1165 11B9;C12E;1109 1165 11B9; # (섮; 섮; 섮; 섮; 섮; ) HANGUL SYLLABLE SEOBS
+C12F;C12F;1109 1165 11BA;C12F;1109 1165 11BA; # (섯; 섯; 섯; 섯; 섯; ) HANGUL SYLLABLE SEOS
+C130;C130;1109 1165 11BB;C130;1109 1165 11BB; # (섰; 섰; 섰; 섰; 섰; ) HANGUL SYLLABLE SEOSS
+C131;C131;1109 1165 11BC;C131;1109 1165 11BC; # (성; 성; 성; 성; 성; ) HANGUL SYLLABLE SEONG
+C132;C132;1109 1165 11BD;C132;1109 1165 11BD; # (섲; 섲; 섲; 섲; 섲; ) HANGUL SYLLABLE SEOJ
+C133;C133;1109 1165 11BE;C133;1109 1165 11BE; # (섳; 섳; 섳; 섳; 섳; ) HANGUL SYLLABLE SEOC
+C134;C134;1109 1165 11BF;C134;1109 1165 11BF; # (섴; 섴; 섴; 섴; 섴; ) HANGUL SYLLABLE SEOK
+C135;C135;1109 1165 11C0;C135;1109 1165 11C0; # (섵; 섵; 섵; 섵; 섵; ) HANGUL SYLLABLE SEOT
+C136;C136;1109 1165 11C1;C136;1109 1165 11C1; # (섶; 섶; 섶; 섶; 섶; ) HANGUL SYLLABLE SEOP
+C137;C137;1109 1165 11C2;C137;1109 1165 11C2; # (섷; 섷; 섷; 섷; 섷; ) HANGUL SYLLABLE SEOH
+C138;C138;1109 1166;C138;1109 1166; # (세; 세; 세; 세; 세; ) HANGUL SYLLABLE SE
+C139;C139;1109 1166 11A8;C139;1109 1166 11A8; # (섹; 섹; 섹; 섹; 섹; ) HANGUL SYLLABLE SEG
+C13A;C13A;1109 1166 11A9;C13A;1109 1166 11A9; # (섺; 섺; 섺; 섺; 섺; ) HANGUL SYLLABLE SEGG
+C13B;C13B;1109 1166 11AA;C13B;1109 1166 11AA; # (섻; 섻; 섻; 섻; 섻; ) HANGUL SYLLABLE SEGS
+C13C;C13C;1109 1166 11AB;C13C;1109 1166 11AB; # (센; 센; 센; 센; 센; ) HANGUL SYLLABLE SEN
+C13D;C13D;1109 1166 11AC;C13D;1109 1166 11AC; # (섽; 섽; 섽; 섽; 섽; ) HANGUL SYLLABLE SENJ
+C13E;C13E;1109 1166 11AD;C13E;1109 1166 11AD; # (섾; 섾; 섾; 섾; 섾; ) HANGUL SYLLABLE SENH
+C13F;C13F;1109 1166 11AE;C13F;1109 1166 11AE; # (섿; 섿; 섿; 섿; 섿; ) HANGUL SYLLABLE SED
+C140;C140;1109 1166 11AF;C140;1109 1166 11AF; # (셀; 셀; 셀; 셀; 셀; ) HANGUL SYLLABLE SEL
+C141;C141;1109 1166 11B0;C141;1109 1166 11B0; # (셁; 셁; 셁; 셁; 셁; ) HANGUL SYLLABLE SELG
+C142;C142;1109 1166 11B1;C142;1109 1166 11B1; # (셂; 셂; 셂; 셂; 셂; ) HANGUL SYLLABLE SELM
+C143;C143;1109 1166 11B2;C143;1109 1166 11B2; # (셃; 셃; 셃; 셃; 셃; ) HANGUL SYLLABLE SELB
+C144;C144;1109 1166 11B3;C144;1109 1166 11B3; # (셄; 셄; 셄; 셄; 셄; ) HANGUL SYLLABLE SELS
+C145;C145;1109 1166 11B4;C145;1109 1166 11B4; # (셅; 셅; 셅; 셅; 셅; ) HANGUL SYLLABLE SELT
+C146;C146;1109 1166 11B5;C146;1109 1166 11B5; # (셆; 셆; 셆; 셆; 셆; ) HANGUL SYLLABLE SELP
+C147;C147;1109 1166 11B6;C147;1109 1166 11B6; # (셇; 셇; 셇; 셇; 셇; ) HANGUL SYLLABLE SELH
+C148;C148;1109 1166 11B7;C148;1109 1166 11B7; # (셈; 셈; 셈; 셈; 셈; ) HANGUL SYLLABLE SEM
+C149;C149;1109 1166 11B8;C149;1109 1166 11B8; # (셉; 셉; 셉; 셉; 셉; ) HANGUL SYLLABLE SEB
+C14A;C14A;1109 1166 11B9;C14A;1109 1166 11B9; # (셊; 셊; 셊; 셊; 셊; ) HANGUL SYLLABLE SEBS
+C14B;C14B;1109 1166 11BA;C14B;1109 1166 11BA; # (셋; 셋; 셋; 셋; 셋; ) HANGUL SYLLABLE SES
+C14C;C14C;1109 1166 11BB;C14C;1109 1166 11BB; # (셌; 셌; 셌; 셌; 셌; ) HANGUL SYLLABLE SESS
+C14D;C14D;1109 1166 11BC;C14D;1109 1166 11BC; # (셍; 셍; 셍; 셍; 셍; ) HANGUL SYLLABLE SENG
+C14E;C14E;1109 1166 11BD;C14E;1109 1166 11BD; # (셎; 셎; 셎; 셎; 셎; ) HANGUL SYLLABLE SEJ
+C14F;C14F;1109 1166 11BE;C14F;1109 1166 11BE; # (셏; 셏; 셏; 셏; 셏; ) HANGUL SYLLABLE SEC
+C150;C150;1109 1166 11BF;C150;1109 1166 11BF; # (셐; 셐; 셐; 셐; 셐; ) HANGUL SYLLABLE SEK
+C151;C151;1109 1166 11C0;C151;1109 1166 11C0; # (셑; 셑; 셑; 셑; 셑; ) HANGUL SYLLABLE SET
+C152;C152;1109 1166 11C1;C152;1109 1166 11C1; # (셒; 셒; 셒; 셒; 셒; ) HANGUL SYLLABLE SEP
+C153;C153;1109 1166 11C2;C153;1109 1166 11C2; # (셓; 셓; 셓; 셓; 셓; ) HANGUL SYLLABLE SEH
+C154;C154;1109 1167;C154;1109 1167; # (셔; 셔; 셔; 셔; 셔; ) HANGUL SYLLABLE SYEO
+C155;C155;1109 1167 11A8;C155;1109 1167 11A8; # (셕; 셕; 셕; 셕; 셕; ) HANGUL SYLLABLE SYEOG
+C156;C156;1109 1167 11A9;C156;1109 1167 11A9; # (셖; 셖; 셖; 셖; 셖; ) HANGUL SYLLABLE SYEOGG
+C157;C157;1109 1167 11AA;C157;1109 1167 11AA; # (셗; 셗; 셗; 셗; 셗; ) HANGUL SYLLABLE SYEOGS
+C158;C158;1109 1167 11AB;C158;1109 1167 11AB; # (션; 션; 션; 션; 션; ) HANGUL SYLLABLE SYEON
+C159;C159;1109 1167 11AC;C159;1109 1167 11AC; # (셙; 셙; 셙; 셙; 셙; ) HANGUL SYLLABLE SYEONJ
+C15A;C15A;1109 1167 11AD;C15A;1109 1167 11AD; # (셚; 셚; 셚; 셚; 셚; ) HANGUL SYLLABLE SYEONH
+C15B;C15B;1109 1167 11AE;C15B;1109 1167 11AE; # (셛; 셛; 셛; 셛; 셛; ) HANGUL SYLLABLE SYEOD
+C15C;C15C;1109 1167 11AF;C15C;1109 1167 11AF; # (셜; 셜; 셜; 셜; 셜; ) HANGUL SYLLABLE SYEOL
+C15D;C15D;1109 1167 11B0;C15D;1109 1167 11B0; # (셝; 셝; 셝; 셝; 셝; ) HANGUL SYLLABLE SYEOLG
+C15E;C15E;1109 1167 11B1;C15E;1109 1167 11B1; # (셞; 셞; 셞; 셞; 셞; ) HANGUL SYLLABLE SYEOLM
+C15F;C15F;1109 1167 11B2;C15F;1109 1167 11B2; # (셟; 셟; 셟; 셟; 셟; ) HANGUL SYLLABLE SYEOLB
+C160;C160;1109 1167 11B3;C160;1109 1167 11B3; # (셠; 셠; 셠; 셠; 셠; ) HANGUL SYLLABLE SYEOLS
+C161;C161;1109 1167 11B4;C161;1109 1167 11B4; # (셡; 셡; 셡; 셡; 셡; ) HANGUL SYLLABLE SYEOLT
+C162;C162;1109 1167 11B5;C162;1109 1167 11B5; # (셢; 셢; 셢; 셢; 셢; ) HANGUL SYLLABLE SYEOLP
+C163;C163;1109 1167 11B6;C163;1109 1167 11B6; # (셣; 셣; 셣; 셣; 셣; ) HANGUL SYLLABLE SYEOLH
+C164;C164;1109 1167 11B7;C164;1109 1167 11B7; # (셤; 셤; 셤; 셤; 셤; ) HANGUL SYLLABLE SYEOM
+C165;C165;1109 1167 11B8;C165;1109 1167 11B8; # (셥; 셥; 셥; 셥; 셥; ) HANGUL SYLLABLE SYEOB
+C166;C166;1109 1167 11B9;C166;1109 1167 11B9; # (셦; 셦; 셦; 셦; 셦; ) HANGUL SYLLABLE SYEOBS
+C167;C167;1109 1167 11BA;C167;1109 1167 11BA; # (셧; 셧; 셧; 셧; 셧; ) HANGUL SYLLABLE SYEOS
+C168;C168;1109 1167 11BB;C168;1109 1167 11BB; # (셨; 셨; 셨; 셨; 셨; ) HANGUL SYLLABLE SYEOSS
+C169;C169;1109 1167 11BC;C169;1109 1167 11BC; # (셩; 셩; 셩; 셩; 셩; ) HANGUL SYLLABLE SYEONG
+C16A;C16A;1109 1167 11BD;C16A;1109 1167 11BD; # (셪; 셪; 셪; 셪; 셪; ) HANGUL SYLLABLE SYEOJ
+C16B;C16B;1109 1167 11BE;C16B;1109 1167 11BE; # (셫; 셫; 셫; 셫; 셫; ) HANGUL SYLLABLE SYEOC
+C16C;C16C;1109 1167 11BF;C16C;1109 1167 11BF; # (셬; 셬; 셬; 셬; 셬; ) HANGUL SYLLABLE SYEOK
+C16D;C16D;1109 1167 11C0;C16D;1109 1167 11C0; # (셭; 셭; 셭; 셭; 셭; ) HANGUL SYLLABLE SYEOT
+C16E;C16E;1109 1167 11C1;C16E;1109 1167 11C1; # (셮; 셮; 셮; 셮; 셮; ) HANGUL SYLLABLE SYEOP
+C16F;C16F;1109 1167 11C2;C16F;1109 1167 11C2; # (셯; 셯; 셯; 셯; 셯; ) HANGUL SYLLABLE SYEOH
+C170;C170;1109 1168;C170;1109 1168; # (셰; 셰; 셰; 셰; 셰; ) HANGUL SYLLABLE SYE
+C171;C171;1109 1168 11A8;C171;1109 1168 11A8; # (셱; 셱; 셱; 셱; 셱; ) HANGUL SYLLABLE SYEG
+C172;C172;1109 1168 11A9;C172;1109 1168 11A9; # (셲; 셲; 셲; 셲; 셲; ) HANGUL SYLLABLE SYEGG
+C173;C173;1109 1168 11AA;C173;1109 1168 11AA; # (셳; 셳; 셳; 셳; 셳; ) HANGUL SYLLABLE SYEGS
+C174;C174;1109 1168 11AB;C174;1109 1168 11AB; # (셴; 셴; 셴; 셴; 셴; ) HANGUL SYLLABLE SYEN
+C175;C175;1109 1168 11AC;C175;1109 1168 11AC; # (셵; 셵; 셵; 셵; 셵; ) HANGUL SYLLABLE SYENJ
+C176;C176;1109 1168 11AD;C176;1109 1168 11AD; # (셶; 셶; 셶; 셶; 셶; ) HANGUL SYLLABLE SYENH
+C177;C177;1109 1168 11AE;C177;1109 1168 11AE; # (셷; 셷; 셷; 셷; 셷; ) HANGUL SYLLABLE SYED
+C178;C178;1109 1168 11AF;C178;1109 1168 11AF; # (셸; 셸; 셸; 셸; 셸; ) HANGUL SYLLABLE SYEL
+C179;C179;1109 1168 11B0;C179;1109 1168 11B0; # (셹; 셹; 셹; 셹; 셹; ) HANGUL SYLLABLE SYELG
+C17A;C17A;1109 1168 11B1;C17A;1109 1168 11B1; # (셺; 셺; 셺; 셺; 셺; ) HANGUL SYLLABLE SYELM
+C17B;C17B;1109 1168 11B2;C17B;1109 1168 11B2; # (셻; 셻; 셻; 셻; 셻; ) HANGUL SYLLABLE SYELB
+C17C;C17C;1109 1168 11B3;C17C;1109 1168 11B3; # (셼; 셼; 셼; 셼; 셼; ) HANGUL SYLLABLE SYELS
+C17D;C17D;1109 1168 11B4;C17D;1109 1168 11B4; # (셽; 셽; 셽; 셽; 셽; ) HANGUL SYLLABLE SYELT
+C17E;C17E;1109 1168 11B5;C17E;1109 1168 11B5; # (셾; 셾; 셾; 셾; 셾; ) HANGUL SYLLABLE SYELP
+C17F;C17F;1109 1168 11B6;C17F;1109 1168 11B6; # (셿; 셿; 셿; 셿; 셿; ) HANGUL SYLLABLE SYELH
+C180;C180;1109 1168 11B7;C180;1109 1168 11B7; # (솀; 솀; 솀; 솀; 솀; ) HANGUL SYLLABLE SYEM
+C181;C181;1109 1168 11B8;C181;1109 1168 11B8; # (솁; 솁; 솁; 솁; 솁; ) HANGUL SYLLABLE SYEB
+C182;C182;1109 1168 11B9;C182;1109 1168 11B9; # (솂; 솂; 솂; 솂; 솂; ) HANGUL SYLLABLE SYEBS
+C183;C183;1109 1168 11BA;C183;1109 1168 11BA; # (솃; 솃; 솃; 솃; 솃; ) HANGUL SYLLABLE SYES
+C184;C184;1109 1168 11BB;C184;1109 1168 11BB; # (솄; 솄; 솄; 솄; 솄; ) HANGUL SYLLABLE SYESS
+C185;C185;1109 1168 11BC;C185;1109 1168 11BC; # (솅; 솅; 솅; 솅; 솅; ) HANGUL SYLLABLE SYENG
+C186;C186;1109 1168 11BD;C186;1109 1168 11BD; # (솆; 솆; 솆; 솆; 솆; ) HANGUL SYLLABLE SYEJ
+C187;C187;1109 1168 11BE;C187;1109 1168 11BE; # (솇; 솇; 솇; 솇; 솇; ) HANGUL SYLLABLE SYEC
+C188;C188;1109 1168 11BF;C188;1109 1168 11BF; # (솈; 솈; 솈; 솈; 솈; ) HANGUL SYLLABLE SYEK
+C189;C189;1109 1168 11C0;C189;1109 1168 11C0; # (솉; 솉; 솉; 솉; 솉; ) HANGUL SYLLABLE SYET
+C18A;C18A;1109 1168 11C1;C18A;1109 1168 11C1; # (솊; 솊; 솊; 솊; 솊; ) HANGUL SYLLABLE SYEP
+C18B;C18B;1109 1168 11C2;C18B;1109 1168 11C2; # (솋; 솋; 솋; 솋; 솋; ) HANGUL SYLLABLE SYEH
+C18C;C18C;1109 1169;C18C;1109 1169; # (소; 소; 소; 소; 소; ) HANGUL SYLLABLE SO
+C18D;C18D;1109 1169 11A8;C18D;1109 1169 11A8; # (속; 속; 속; 속; 속; ) HANGUL SYLLABLE SOG
+C18E;C18E;1109 1169 11A9;C18E;1109 1169 11A9; # (솎; 솎; 솎; 솎; 솎; ) HANGUL SYLLABLE SOGG
+C18F;C18F;1109 1169 11AA;C18F;1109 1169 11AA; # (솏; 솏; 솏; 솏; 솏; ) HANGUL SYLLABLE SOGS
+C190;C190;1109 1169 11AB;C190;1109 1169 11AB; # (손; 손; 손; 손; 손; ) HANGUL SYLLABLE SON
+C191;C191;1109 1169 11AC;C191;1109 1169 11AC; # (솑; 솑; 솑; 솑; 솑; ) HANGUL SYLLABLE SONJ
+C192;C192;1109 1169 11AD;C192;1109 1169 11AD; # (솒; 솒; 솒; 솒; 솒; ) HANGUL SYLLABLE SONH
+C193;C193;1109 1169 11AE;C193;1109 1169 11AE; # (솓; 솓; 솓; 솓; 솓; ) HANGUL SYLLABLE SOD
+C194;C194;1109 1169 11AF;C194;1109 1169 11AF; # (솔; 솔; 솔; 솔; 솔; ) HANGUL SYLLABLE SOL
+C195;C195;1109 1169 11B0;C195;1109 1169 11B0; # (솕; 솕; 솕; 솕; 솕; ) HANGUL SYLLABLE SOLG
+C196;C196;1109 1169 11B1;C196;1109 1169 11B1; # (솖; 솖; 솖; 솖; 솖; ) HANGUL SYLLABLE SOLM
+C197;C197;1109 1169 11B2;C197;1109 1169 11B2; # (솗; 솗; 솗; 솗; 솗; ) HANGUL SYLLABLE SOLB
+C198;C198;1109 1169 11B3;C198;1109 1169 11B3; # (솘; 솘; 솘; 솘; 솘; ) HANGUL SYLLABLE SOLS
+C199;C199;1109 1169 11B4;C199;1109 1169 11B4; # (솙; 솙; 솙; 솙; 솙; ) HANGUL SYLLABLE SOLT
+C19A;C19A;1109 1169 11B5;C19A;1109 1169 11B5; # (솚; 솚; 솚; 솚; 솚; ) HANGUL SYLLABLE SOLP
+C19B;C19B;1109 1169 11B6;C19B;1109 1169 11B6; # (솛; 솛; 솛; 솛; 솛; ) HANGUL SYLLABLE SOLH
+C19C;C19C;1109 1169 11B7;C19C;1109 1169 11B7; # (솜; 솜; 솜; 솜; 솜; ) HANGUL SYLLABLE SOM
+C19D;C19D;1109 1169 11B8;C19D;1109 1169 11B8; # (솝; 솝; 솝; 솝; 솝; ) HANGUL SYLLABLE SOB
+C19E;C19E;1109 1169 11B9;C19E;1109 1169 11B9; # (솞; 솞; 솞; 솞; 솞; ) HANGUL SYLLABLE SOBS
+C19F;C19F;1109 1169 11BA;C19F;1109 1169 11BA; # (솟; 솟; 솟; 솟; 솟; ) HANGUL SYLLABLE SOS
+C1A0;C1A0;1109 1169 11BB;C1A0;1109 1169 11BB; # (솠; 솠; 솠; 솠; 솠; ) HANGUL SYLLABLE SOSS
+C1A1;C1A1;1109 1169 11BC;C1A1;1109 1169 11BC; # (송; 송; 송; 송; 송; ) HANGUL SYLLABLE SONG
+C1A2;C1A2;1109 1169 11BD;C1A2;1109 1169 11BD; # (솢; 솢; 솢; 솢; 솢; ) HANGUL SYLLABLE SOJ
+C1A3;C1A3;1109 1169 11BE;C1A3;1109 1169 11BE; # (솣; 솣; 솣; 솣; 솣; ) HANGUL SYLLABLE SOC
+C1A4;C1A4;1109 1169 11BF;C1A4;1109 1169 11BF; # (솤; 솤; 솤; 솤; 솤; ) HANGUL SYLLABLE SOK
+C1A5;C1A5;1109 1169 11C0;C1A5;1109 1169 11C0; # (솥; 솥; 솥; 솥; 솥; ) HANGUL SYLLABLE SOT
+C1A6;C1A6;1109 1169 11C1;C1A6;1109 1169 11C1; # (솦; 솦; 솦; 솦; 솦; ) HANGUL SYLLABLE SOP
+C1A7;C1A7;1109 1169 11C2;C1A7;1109 1169 11C2; # (솧; 솧; 솧; 솧; 솧; ) HANGUL SYLLABLE SOH
+C1A8;C1A8;1109 116A;C1A8;1109 116A; # (솨; 솨; 솨; 솨; 솨; ) HANGUL SYLLABLE SWA
+C1A9;C1A9;1109 116A 11A8;C1A9;1109 116A 11A8; # (솩; 솩; 솩; 솩; 솩; ) HANGUL SYLLABLE SWAG
+C1AA;C1AA;1109 116A 11A9;C1AA;1109 116A 11A9; # (솪; 솪; 솪; 솪; 솪; ) HANGUL SYLLABLE SWAGG
+C1AB;C1AB;1109 116A 11AA;C1AB;1109 116A 11AA; # (솫; 솫; 솫; 솫; 솫; ) HANGUL SYLLABLE SWAGS
+C1AC;C1AC;1109 116A 11AB;C1AC;1109 116A 11AB; # (솬; 솬; 솬; 솬; 솬; ) HANGUL SYLLABLE SWAN
+C1AD;C1AD;1109 116A 11AC;C1AD;1109 116A 11AC; # (솭; 솭; 솭; 솭; 솭; ) HANGUL SYLLABLE SWANJ
+C1AE;C1AE;1109 116A 11AD;C1AE;1109 116A 11AD; # (솮; 솮; 솮; 솮; 솮; ) HANGUL SYLLABLE SWANH
+C1AF;C1AF;1109 116A 11AE;C1AF;1109 116A 11AE; # (솯; 솯; 솯; 솯; 솯; ) HANGUL SYLLABLE SWAD
+C1B0;C1B0;1109 116A 11AF;C1B0;1109 116A 11AF; # (솰; 솰; 솰; 솰; 솰; ) HANGUL SYLLABLE SWAL
+C1B1;C1B1;1109 116A 11B0;C1B1;1109 116A 11B0; # (솱; 솱; 솱; 솱; 솱; ) HANGUL SYLLABLE SWALG
+C1B2;C1B2;1109 116A 11B1;C1B2;1109 116A 11B1; # (솲; 솲; 솲; 솲; 솲; ) HANGUL SYLLABLE SWALM
+C1B3;C1B3;1109 116A 11B2;C1B3;1109 116A 11B2; # (솳; 솳; 솳; 솳; 솳; ) HANGUL SYLLABLE SWALB
+C1B4;C1B4;1109 116A 11B3;C1B4;1109 116A 11B3; # (솴; 솴; 솴; 솴; 솴; ) HANGUL SYLLABLE SWALS
+C1B5;C1B5;1109 116A 11B4;C1B5;1109 116A 11B4; # (솵; 솵; 솵; 솵; 솵; ) HANGUL SYLLABLE SWALT
+C1B6;C1B6;1109 116A 11B5;C1B6;1109 116A 11B5; # (솶; 솶; 솶; 솶; 솶; ) HANGUL SYLLABLE SWALP
+C1B7;C1B7;1109 116A 11B6;C1B7;1109 116A 11B6; # (솷; 솷; 솷; 솷; 솷; ) HANGUL SYLLABLE SWALH
+C1B8;C1B8;1109 116A 11B7;C1B8;1109 116A 11B7; # (솸; 솸; 솸; 솸; 솸; ) HANGUL SYLLABLE SWAM
+C1B9;C1B9;1109 116A 11B8;C1B9;1109 116A 11B8; # (솹; 솹; 솹; 솹; 솹; ) HANGUL SYLLABLE SWAB
+C1BA;C1BA;1109 116A 11B9;C1BA;1109 116A 11B9; # (솺; 솺; 솺; 솺; 솺; ) HANGUL SYLLABLE SWABS
+C1BB;C1BB;1109 116A 11BA;C1BB;1109 116A 11BA; # (솻; 솻; 솻; 솻; 솻; ) HANGUL SYLLABLE SWAS
+C1BC;C1BC;1109 116A 11BB;C1BC;1109 116A 11BB; # (솼; 솼; 솼; 솼; 솼; ) HANGUL SYLLABLE SWASS
+C1BD;C1BD;1109 116A 11BC;C1BD;1109 116A 11BC; # (솽; 솽; 솽; 솽; 솽; ) HANGUL SYLLABLE SWANG
+C1BE;C1BE;1109 116A 11BD;C1BE;1109 116A 11BD; # (솾; 솾; 솾; 솾; 솾; ) HANGUL SYLLABLE SWAJ
+C1BF;C1BF;1109 116A 11BE;C1BF;1109 116A 11BE; # (솿; 솿; 솿; 솿; 솿; ) HANGUL SYLLABLE SWAC
+C1C0;C1C0;1109 116A 11BF;C1C0;1109 116A 11BF; # (쇀; 쇀; 쇀; 쇀; 쇀; ) HANGUL SYLLABLE SWAK
+C1C1;C1C1;1109 116A 11C0;C1C1;1109 116A 11C0; # (쇁; 쇁; 쇁; 쇁; 쇁; ) HANGUL SYLLABLE SWAT
+C1C2;C1C2;1109 116A 11C1;C1C2;1109 116A 11C1; # (쇂; 쇂; 쇂; 쇂; 쇂; ) HANGUL SYLLABLE SWAP
+C1C3;C1C3;1109 116A 11C2;C1C3;1109 116A 11C2; # (쇃; 쇃; 쇃; 쇃; 쇃; ) HANGUL SYLLABLE SWAH
+C1C4;C1C4;1109 116B;C1C4;1109 116B; # (쇄; 쇄; 쇄; 쇄; 쇄; ) HANGUL SYLLABLE SWAE
+C1C5;C1C5;1109 116B 11A8;C1C5;1109 116B 11A8; # (쇅; 쇅; 쇅; 쇅; 쇅; ) HANGUL SYLLABLE SWAEG
+C1C6;C1C6;1109 116B 11A9;C1C6;1109 116B 11A9; # (쇆; 쇆; 쇆; 쇆; 쇆; ) HANGUL SYLLABLE SWAEGG
+C1C7;C1C7;1109 116B 11AA;C1C7;1109 116B 11AA; # (쇇; 쇇; 쇇; 쇇; 쇇; ) HANGUL SYLLABLE SWAEGS
+C1C8;C1C8;1109 116B 11AB;C1C8;1109 116B 11AB; # (쇈; 쇈; 쇈; 쇈; 쇈; ) HANGUL SYLLABLE SWAEN
+C1C9;C1C9;1109 116B 11AC;C1C9;1109 116B 11AC; # (쇉; 쇉; 쇉; 쇉; 쇉; ) HANGUL SYLLABLE SWAENJ
+C1CA;C1CA;1109 116B 11AD;C1CA;1109 116B 11AD; # (쇊; 쇊; 쇊; 쇊; 쇊; ) HANGUL SYLLABLE SWAENH
+C1CB;C1CB;1109 116B 11AE;C1CB;1109 116B 11AE; # (쇋; 쇋; 쇋; 쇋; 쇋; ) HANGUL SYLLABLE SWAED
+C1CC;C1CC;1109 116B 11AF;C1CC;1109 116B 11AF; # (쇌; 쇌; 쇌; 쇌; 쇌; ) HANGUL SYLLABLE SWAEL
+C1CD;C1CD;1109 116B 11B0;C1CD;1109 116B 11B0; # (쇍; 쇍; 쇍; 쇍; 쇍; ) HANGUL SYLLABLE SWAELG
+C1CE;C1CE;1109 116B 11B1;C1CE;1109 116B 11B1; # (쇎; 쇎; 쇎; 쇎; 쇎; ) HANGUL SYLLABLE SWAELM
+C1CF;C1CF;1109 116B 11B2;C1CF;1109 116B 11B2; # (쇏; 쇏; 쇏; 쇏; 쇏; ) HANGUL SYLLABLE SWAELB
+C1D0;C1D0;1109 116B 11B3;C1D0;1109 116B 11B3; # (쇐; 쇐; 쇐; 쇐; 쇐; ) HANGUL SYLLABLE SWAELS
+C1D1;C1D1;1109 116B 11B4;C1D1;1109 116B 11B4; # (쇑; 쇑; 쇑; 쇑; 쇑; ) HANGUL SYLLABLE SWAELT
+C1D2;C1D2;1109 116B 11B5;C1D2;1109 116B 11B5; # (쇒; 쇒; 쇒; 쇒; 쇒; ) HANGUL SYLLABLE SWAELP
+C1D3;C1D3;1109 116B 11B6;C1D3;1109 116B 11B6; # (쇓; 쇓; 쇓; 쇓; 쇓; ) HANGUL SYLLABLE SWAELH
+C1D4;C1D4;1109 116B 11B7;C1D4;1109 116B 11B7; # (쇔; 쇔; 쇔; 쇔; 쇔; ) HANGUL SYLLABLE SWAEM
+C1D5;C1D5;1109 116B 11B8;C1D5;1109 116B 11B8; # (쇕; 쇕; 쇕; 쇕; 쇕; ) HANGUL SYLLABLE SWAEB
+C1D6;C1D6;1109 116B 11B9;C1D6;1109 116B 11B9; # (쇖; 쇖; 쇖; 쇖; 쇖; ) HANGUL SYLLABLE SWAEBS
+C1D7;C1D7;1109 116B 11BA;C1D7;1109 116B 11BA; # (쇗; 쇗; 쇗; 쇗; 쇗; ) HANGUL SYLLABLE SWAES
+C1D8;C1D8;1109 116B 11BB;C1D8;1109 116B 11BB; # (쇘; 쇘; 쇘; 쇘; 쇘; ) HANGUL SYLLABLE SWAESS
+C1D9;C1D9;1109 116B 11BC;C1D9;1109 116B 11BC; # (쇙; 쇙; 쇙; 쇙; 쇙; ) HANGUL SYLLABLE SWAENG
+C1DA;C1DA;1109 116B 11BD;C1DA;1109 116B 11BD; # (쇚; 쇚; 쇚; 쇚; 쇚; ) HANGUL SYLLABLE SWAEJ
+C1DB;C1DB;1109 116B 11BE;C1DB;1109 116B 11BE; # (쇛; 쇛; 쇛; 쇛; 쇛; ) HANGUL SYLLABLE SWAEC
+C1DC;C1DC;1109 116B 11BF;C1DC;1109 116B 11BF; # (쇜; 쇜; 쇜; 쇜; 쇜; ) HANGUL SYLLABLE SWAEK
+C1DD;C1DD;1109 116B 11C0;C1DD;1109 116B 11C0; # (쇝; 쇝; 쇝; 쇝; 쇝; ) HANGUL SYLLABLE SWAET
+C1DE;C1DE;1109 116B 11C1;C1DE;1109 116B 11C1; # (쇞; 쇞; 쇞; 쇞; 쇞; ) HANGUL SYLLABLE SWAEP
+C1DF;C1DF;1109 116B 11C2;C1DF;1109 116B 11C2; # (쇟; 쇟; 쇟; 쇟; 쇟; ) HANGUL SYLLABLE SWAEH
+C1E0;C1E0;1109 116C;C1E0;1109 116C; # (쇠; 쇠; 쇠; 쇠; 쇠; ) HANGUL SYLLABLE SOE
+C1E1;C1E1;1109 116C 11A8;C1E1;1109 116C 11A8; # (쇡; 쇡; 쇡; 쇡; 쇡; ) HANGUL SYLLABLE SOEG
+C1E2;C1E2;1109 116C 11A9;C1E2;1109 116C 11A9; # (쇢; 쇢; 쇢; 쇢; 쇢; ) HANGUL SYLLABLE SOEGG
+C1E3;C1E3;1109 116C 11AA;C1E3;1109 116C 11AA; # (쇣; 쇣; 쇣; 쇣; 쇣; ) HANGUL SYLLABLE SOEGS
+C1E4;C1E4;1109 116C 11AB;C1E4;1109 116C 11AB; # (쇤; 쇤; 쇤; 쇤; 쇤; ) HANGUL SYLLABLE SOEN
+C1E5;C1E5;1109 116C 11AC;C1E5;1109 116C 11AC; # (쇥; 쇥; 쇥; 쇥; 쇥; ) HANGUL SYLLABLE SOENJ
+C1E6;C1E6;1109 116C 11AD;C1E6;1109 116C 11AD; # (쇦; 쇦; 쇦; 쇦; 쇦; ) HANGUL SYLLABLE SOENH
+C1E7;C1E7;1109 116C 11AE;C1E7;1109 116C 11AE; # (쇧; 쇧; 쇧; 쇧; 쇧; ) HANGUL SYLLABLE SOED
+C1E8;C1E8;1109 116C 11AF;C1E8;1109 116C 11AF; # (쇨; 쇨; 쇨; 쇨; 쇨; ) HANGUL SYLLABLE SOEL
+C1E9;C1E9;1109 116C 11B0;C1E9;1109 116C 11B0; # (쇩; 쇩; 쇩; 쇩; 쇩; ) HANGUL SYLLABLE SOELG
+C1EA;C1EA;1109 116C 11B1;C1EA;1109 116C 11B1; # (쇪; 쇪; 쇪; 쇪; 쇪; ) HANGUL SYLLABLE SOELM
+C1EB;C1EB;1109 116C 11B2;C1EB;1109 116C 11B2; # (쇫; 쇫; 쇫; 쇫; 쇫; ) HANGUL SYLLABLE SOELB
+C1EC;C1EC;1109 116C 11B3;C1EC;1109 116C 11B3; # (쇬; 쇬; 쇬; 쇬; 쇬; ) HANGUL SYLLABLE SOELS
+C1ED;C1ED;1109 116C 11B4;C1ED;1109 116C 11B4; # (쇭; 쇭; 쇭; 쇭; 쇭; ) HANGUL SYLLABLE SOELT
+C1EE;C1EE;1109 116C 11B5;C1EE;1109 116C 11B5; # (쇮; 쇮; 쇮; 쇮; 쇮; ) HANGUL SYLLABLE SOELP
+C1EF;C1EF;1109 116C 11B6;C1EF;1109 116C 11B6; # (쇯; 쇯; 쇯; 쇯; 쇯; ) HANGUL SYLLABLE SOELH
+C1F0;C1F0;1109 116C 11B7;C1F0;1109 116C 11B7; # (쇰; 쇰; 쇰; 쇰; 쇰; ) HANGUL SYLLABLE SOEM
+C1F1;C1F1;1109 116C 11B8;C1F1;1109 116C 11B8; # (쇱; 쇱; 쇱; 쇱; 쇱; ) HANGUL SYLLABLE SOEB
+C1F2;C1F2;1109 116C 11B9;C1F2;1109 116C 11B9; # (쇲; 쇲; 쇲; 쇲; 쇲; ) HANGUL SYLLABLE SOEBS
+C1F3;C1F3;1109 116C 11BA;C1F3;1109 116C 11BA; # (쇳; 쇳; 쇳; 쇳; 쇳; ) HANGUL SYLLABLE SOES
+C1F4;C1F4;1109 116C 11BB;C1F4;1109 116C 11BB; # (쇴; 쇴; 쇴; 쇴; 쇴; ) HANGUL SYLLABLE SOESS
+C1F5;C1F5;1109 116C 11BC;C1F5;1109 116C 11BC; # (쇵; 쇵; 쇵; 쇵; 쇵; ) HANGUL SYLLABLE SOENG
+C1F6;C1F6;1109 116C 11BD;C1F6;1109 116C 11BD; # (쇶; 쇶; 쇶; 쇶; 쇶; ) HANGUL SYLLABLE SOEJ
+C1F7;C1F7;1109 116C 11BE;C1F7;1109 116C 11BE; # (쇷; 쇷; 쇷; 쇷; 쇷; ) HANGUL SYLLABLE SOEC
+C1F8;C1F8;1109 116C 11BF;C1F8;1109 116C 11BF; # (쇸; 쇸; 쇸; 쇸; 쇸; ) HANGUL SYLLABLE SOEK
+C1F9;C1F9;1109 116C 11C0;C1F9;1109 116C 11C0; # (쇹; 쇹; 쇹; 쇹; 쇹; ) HANGUL SYLLABLE SOET
+C1FA;C1FA;1109 116C 11C1;C1FA;1109 116C 11C1; # (쇺; 쇺; 쇺; 쇺; 쇺; ) HANGUL SYLLABLE SOEP
+C1FB;C1FB;1109 116C 11C2;C1FB;1109 116C 11C2; # (쇻; 쇻; 쇻; 쇻; 쇻; ) HANGUL SYLLABLE SOEH
+C1FC;C1FC;1109 116D;C1FC;1109 116D; # (쇼; 쇼; 쇼; 쇼; 쇼; ) HANGUL SYLLABLE SYO
+C1FD;C1FD;1109 116D 11A8;C1FD;1109 116D 11A8; # (쇽; 쇽; 쇽; 쇽; 쇽; ) HANGUL SYLLABLE SYOG
+C1FE;C1FE;1109 116D 11A9;C1FE;1109 116D 11A9; # (쇾; 쇾; 쇾; 쇾; 쇾; ) HANGUL SYLLABLE SYOGG
+C1FF;C1FF;1109 116D 11AA;C1FF;1109 116D 11AA; # (쇿; 쇿; 쇿; 쇿; 쇿; ) HANGUL SYLLABLE SYOGS
+C200;C200;1109 116D 11AB;C200;1109 116D 11AB; # (숀; 숀; 숀; 숀; 숀; ) HANGUL SYLLABLE SYON
+C201;C201;1109 116D 11AC;C201;1109 116D 11AC; # (숁; 숁; 숁; 숁; 숁; ) HANGUL SYLLABLE SYONJ
+C202;C202;1109 116D 11AD;C202;1109 116D 11AD; # (숂; 숂; 숂; 숂; 숂; ) HANGUL SYLLABLE SYONH
+C203;C203;1109 116D 11AE;C203;1109 116D 11AE; # (숃; 숃; 숃; 숃; 숃; ) HANGUL SYLLABLE SYOD
+C204;C204;1109 116D 11AF;C204;1109 116D 11AF; # (숄; 숄; 숄; 숄; 숄; ) HANGUL SYLLABLE SYOL
+C205;C205;1109 116D 11B0;C205;1109 116D 11B0; # (숅; 숅; 숅; 숅; 숅; ) HANGUL SYLLABLE SYOLG
+C206;C206;1109 116D 11B1;C206;1109 116D 11B1; # (숆; 숆; 숆; 숆; 숆; ) HANGUL SYLLABLE SYOLM
+C207;C207;1109 116D 11B2;C207;1109 116D 11B2; # (숇; 숇; 숇; 숇; 숇; ) HANGUL SYLLABLE SYOLB
+C208;C208;1109 116D 11B3;C208;1109 116D 11B3; # (숈; 숈; 숈; 숈; 숈; ) HANGUL SYLLABLE SYOLS
+C209;C209;1109 116D 11B4;C209;1109 116D 11B4; # (숉; 숉; 숉; 숉; 숉; ) HANGUL SYLLABLE SYOLT
+C20A;C20A;1109 116D 11B5;C20A;1109 116D 11B5; # (숊; 숊; 숊; 숊; 숊; ) HANGUL SYLLABLE SYOLP
+C20B;C20B;1109 116D 11B6;C20B;1109 116D 11B6; # (숋; 숋; 숋; 숋; 숋; ) HANGUL SYLLABLE SYOLH
+C20C;C20C;1109 116D 11B7;C20C;1109 116D 11B7; # (숌; 숌; 숌; 숌; 숌; ) HANGUL SYLLABLE SYOM
+C20D;C20D;1109 116D 11B8;C20D;1109 116D 11B8; # (숍; 숍; 숍; 숍; 숍; ) HANGUL SYLLABLE SYOB
+C20E;C20E;1109 116D 11B9;C20E;1109 116D 11B9; # (숎; 숎; 숎; 숎; 숎; ) HANGUL SYLLABLE SYOBS
+C20F;C20F;1109 116D 11BA;C20F;1109 116D 11BA; # (숏; 숏; 숏; 숏; 숏; ) HANGUL SYLLABLE SYOS
+C210;C210;1109 116D 11BB;C210;1109 116D 11BB; # (숐; 숐; 숐; 숐; 숐; ) HANGUL SYLLABLE SYOSS
+C211;C211;1109 116D 11BC;C211;1109 116D 11BC; # (숑; 숑; 숑; 숑; 숑; ) HANGUL SYLLABLE SYONG
+C212;C212;1109 116D 11BD;C212;1109 116D 11BD; # (숒; 숒; 숒; 숒; 숒; ) HANGUL SYLLABLE SYOJ
+C213;C213;1109 116D 11BE;C213;1109 116D 11BE; # (숓; 숓; 숓; 숓; 숓; ) HANGUL SYLLABLE SYOC
+C214;C214;1109 116D 11BF;C214;1109 116D 11BF; # (숔; 숔; 숔; 숔; 숔; ) HANGUL SYLLABLE SYOK
+C215;C215;1109 116D 11C0;C215;1109 116D 11C0; # (숕; 숕; 숕; 숕; 숕; ) HANGUL SYLLABLE SYOT
+C216;C216;1109 116D 11C1;C216;1109 116D 11C1; # (숖; 숖; 숖; 숖; 숖; ) HANGUL SYLLABLE SYOP
+C217;C217;1109 116D 11C2;C217;1109 116D 11C2; # (숗; 숗; 숗; 숗; 숗; ) HANGUL SYLLABLE SYOH
+C218;C218;1109 116E;C218;1109 116E; # (수; 수; 수; 수; 수; ) HANGUL SYLLABLE SU
+C219;C219;1109 116E 11A8;C219;1109 116E 11A8; # (숙; 숙; 숙; 숙; 숙; ) HANGUL SYLLABLE SUG
+C21A;C21A;1109 116E 11A9;C21A;1109 116E 11A9; # (숚; 숚; 숚; 숚; 숚; ) HANGUL SYLLABLE SUGG
+C21B;C21B;1109 116E 11AA;C21B;1109 116E 11AA; # (숛; 숛; 숛; 숛; 숛; ) HANGUL SYLLABLE SUGS
+C21C;C21C;1109 116E 11AB;C21C;1109 116E 11AB; # (순; 순; 순; 순; 순; ) HANGUL SYLLABLE SUN
+C21D;C21D;1109 116E 11AC;C21D;1109 116E 11AC; # (숝; 숝; 숝; 숝; 숝; ) HANGUL SYLLABLE SUNJ
+C21E;C21E;1109 116E 11AD;C21E;1109 116E 11AD; # (숞; 숞; 숞; 숞; 숞; ) HANGUL SYLLABLE SUNH
+C21F;C21F;1109 116E 11AE;C21F;1109 116E 11AE; # (숟; 숟; 숟; 숟; 숟; ) HANGUL SYLLABLE SUD
+C220;C220;1109 116E 11AF;C220;1109 116E 11AF; # (술; 술; 술; 술; 술; ) HANGUL SYLLABLE SUL
+C221;C221;1109 116E 11B0;C221;1109 116E 11B0; # (숡; 숡; 숡; 숡; 숡; ) HANGUL SYLLABLE SULG
+C222;C222;1109 116E 11B1;C222;1109 116E 11B1; # (숢; 숢; 숢; 숢; 숢; ) HANGUL SYLLABLE SULM
+C223;C223;1109 116E 11B2;C223;1109 116E 11B2; # (숣; 숣; 숣; 숣; 숣; ) HANGUL SYLLABLE SULB
+C224;C224;1109 116E 11B3;C224;1109 116E 11B3; # (숤; 숤; 숤; 숤; 숤; ) HANGUL SYLLABLE SULS
+C225;C225;1109 116E 11B4;C225;1109 116E 11B4; # (숥; 숥; 숥; 숥; 숥; ) HANGUL SYLLABLE SULT
+C226;C226;1109 116E 11B5;C226;1109 116E 11B5; # (숦; 숦; 숦; 숦; 숦; ) HANGUL SYLLABLE SULP
+C227;C227;1109 116E 11B6;C227;1109 116E 11B6; # (숧; 숧; 숧; 숧; 숧; ) HANGUL SYLLABLE SULH
+C228;C228;1109 116E 11B7;C228;1109 116E 11B7; # (숨; 숨; 숨; 숨; 숨; ) HANGUL SYLLABLE SUM
+C229;C229;1109 116E 11B8;C229;1109 116E 11B8; # (숩; 숩; 숩; 숩; 숩; ) HANGUL SYLLABLE SUB
+C22A;C22A;1109 116E 11B9;C22A;1109 116E 11B9; # (숪; 숪; 숪; 숪; 숪; ) HANGUL SYLLABLE SUBS
+C22B;C22B;1109 116E 11BA;C22B;1109 116E 11BA; # (숫; 숫; 숫; 숫; 숫; ) HANGUL SYLLABLE SUS
+C22C;C22C;1109 116E 11BB;C22C;1109 116E 11BB; # (숬; 숬; 숬; 숬; 숬; ) HANGUL SYLLABLE SUSS
+C22D;C22D;1109 116E 11BC;C22D;1109 116E 11BC; # (숭; 숭; 숭; 숭; 숭; ) HANGUL SYLLABLE SUNG
+C22E;C22E;1109 116E 11BD;C22E;1109 116E 11BD; # (숮; 숮; 숮; 숮; 숮; ) HANGUL SYLLABLE SUJ
+C22F;C22F;1109 116E 11BE;C22F;1109 116E 11BE; # (숯; 숯; 숯; 숯; 숯; ) HANGUL SYLLABLE SUC
+C230;C230;1109 116E 11BF;C230;1109 116E 11BF; # (숰; 숰; 숰; 숰; 숰; ) HANGUL SYLLABLE SUK
+C231;C231;1109 116E 11C0;C231;1109 116E 11C0; # (숱; 숱; 숱; 숱; 숱; ) HANGUL SYLLABLE SUT
+C232;C232;1109 116E 11C1;C232;1109 116E 11C1; # (숲; 숲; 숲; 숲; 숲; ) HANGUL SYLLABLE SUP
+C233;C233;1109 116E 11C2;C233;1109 116E 11C2; # (숳; 숳; 숳; 숳; 숳; ) HANGUL SYLLABLE SUH
+C234;C234;1109 116F;C234;1109 116F; # (숴; 숴; 숴; 숴; 숴; ) HANGUL SYLLABLE SWEO
+C235;C235;1109 116F 11A8;C235;1109 116F 11A8; # (숵; 숵; 숵; 숵; 숵; ) HANGUL SYLLABLE SWEOG
+C236;C236;1109 116F 11A9;C236;1109 116F 11A9; # (숶; 숶; 숶; 숶; 숶; ) HANGUL SYLLABLE SWEOGG
+C237;C237;1109 116F 11AA;C237;1109 116F 11AA; # (숷; 숷; 숷; 숷; 숷; ) HANGUL SYLLABLE SWEOGS
+C238;C238;1109 116F 11AB;C238;1109 116F 11AB; # (숸; 숸; 숸; 숸; 숸; ) HANGUL SYLLABLE SWEON
+C239;C239;1109 116F 11AC;C239;1109 116F 11AC; # (숹; 숹; 숹; 숹; 숹; ) HANGUL SYLLABLE SWEONJ
+C23A;C23A;1109 116F 11AD;C23A;1109 116F 11AD; # (숺; 숺; 숺; 숺; 숺; ) HANGUL SYLLABLE SWEONH
+C23B;C23B;1109 116F 11AE;C23B;1109 116F 11AE; # (숻; 숻; 숻; 숻; 숻; ) HANGUL SYLLABLE SWEOD
+C23C;C23C;1109 116F 11AF;C23C;1109 116F 11AF; # (숼; 숼; 숼; 숼; 숼; ) HANGUL SYLLABLE SWEOL
+C23D;C23D;1109 116F 11B0;C23D;1109 116F 11B0; # (숽; 숽; 숽; 숽; 숽; ) HANGUL SYLLABLE SWEOLG
+C23E;C23E;1109 116F 11B1;C23E;1109 116F 11B1; # (숾; 숾; 숾; 숾; 숾; ) HANGUL SYLLABLE SWEOLM
+C23F;C23F;1109 116F 11B2;C23F;1109 116F 11B2; # (숿; 숿; 숿; 숿; 숿; ) HANGUL SYLLABLE SWEOLB
+C240;C240;1109 116F 11B3;C240;1109 116F 11B3; # (쉀; 쉀; 쉀; 쉀; 쉀; ) HANGUL SYLLABLE SWEOLS
+C241;C241;1109 116F 11B4;C241;1109 116F 11B4; # (쉁; 쉁; 쉁; 쉁; 쉁; ) HANGUL SYLLABLE SWEOLT
+C242;C242;1109 116F 11B5;C242;1109 116F 11B5; # (쉂; 쉂; 쉂; 쉂; 쉂; ) HANGUL SYLLABLE SWEOLP
+C243;C243;1109 116F 11B6;C243;1109 116F 11B6; # (쉃; 쉃; 쉃; 쉃; 쉃; ) HANGUL SYLLABLE SWEOLH
+C244;C244;1109 116F 11B7;C244;1109 116F 11B7; # (쉄; 쉄; 쉄; 쉄; 쉄; ) HANGUL SYLLABLE SWEOM
+C245;C245;1109 116F 11B8;C245;1109 116F 11B8; # (쉅; 쉅; 쉅; 쉅; 쉅; ) HANGUL SYLLABLE SWEOB
+C246;C246;1109 116F 11B9;C246;1109 116F 11B9; # (쉆; 쉆; 쉆; 쉆; 쉆; ) HANGUL SYLLABLE SWEOBS
+C247;C247;1109 116F 11BA;C247;1109 116F 11BA; # (쉇; 쉇; 쉇; 쉇; 쉇; ) HANGUL SYLLABLE SWEOS
+C248;C248;1109 116F 11BB;C248;1109 116F 11BB; # (쉈; 쉈; 쉈; 쉈; 쉈; ) HANGUL SYLLABLE SWEOSS
+C249;C249;1109 116F 11BC;C249;1109 116F 11BC; # (쉉; 쉉; 쉉; 쉉; 쉉; ) HANGUL SYLLABLE SWEONG
+C24A;C24A;1109 116F 11BD;C24A;1109 116F 11BD; # (쉊; 쉊; 쉊; 쉊; 쉊; ) HANGUL SYLLABLE SWEOJ
+C24B;C24B;1109 116F 11BE;C24B;1109 116F 11BE; # (쉋; 쉋; 쉋; 쉋; 쉋; ) HANGUL SYLLABLE SWEOC
+C24C;C24C;1109 116F 11BF;C24C;1109 116F 11BF; # (쉌; 쉌; 쉌; 쉌; 쉌; ) HANGUL SYLLABLE SWEOK
+C24D;C24D;1109 116F 11C0;C24D;1109 116F 11C0; # (쉍; 쉍; 쉍; 쉍; 쉍; ) HANGUL SYLLABLE SWEOT
+C24E;C24E;1109 116F 11C1;C24E;1109 116F 11C1; # (쉎; 쉎; 쉎; 쉎; 쉎; ) HANGUL SYLLABLE SWEOP
+C24F;C24F;1109 116F 11C2;C24F;1109 116F 11C2; # (쉏; 쉏; 쉏; 쉏; 쉏; ) HANGUL SYLLABLE SWEOH
+C250;C250;1109 1170;C250;1109 1170; # (쉐; 쉐; 쉐; 쉐; 쉐; ) HANGUL SYLLABLE SWE
+C251;C251;1109 1170 11A8;C251;1109 1170 11A8; # (쉑; 쉑; 쉑; 쉑; 쉑; ) HANGUL SYLLABLE SWEG
+C252;C252;1109 1170 11A9;C252;1109 1170 11A9; # (쉒; 쉒; 쉒; 쉒; 쉒; ) HANGUL SYLLABLE SWEGG
+C253;C253;1109 1170 11AA;C253;1109 1170 11AA; # (쉓; 쉓; 쉓; 쉓; 쉓; ) HANGUL SYLLABLE SWEGS
+C254;C254;1109 1170 11AB;C254;1109 1170 11AB; # (쉔; 쉔; 쉔; 쉔; 쉔; ) HANGUL SYLLABLE SWEN
+C255;C255;1109 1170 11AC;C255;1109 1170 11AC; # (쉕; 쉕; 쉕; 쉕; 쉕; ) HANGUL SYLLABLE SWENJ
+C256;C256;1109 1170 11AD;C256;1109 1170 11AD; # (쉖; 쉖; 쉖; 쉖; 쉖; ) HANGUL SYLLABLE SWENH
+C257;C257;1109 1170 11AE;C257;1109 1170 11AE; # (쉗; 쉗; 쉗; 쉗; 쉗; ) HANGUL SYLLABLE SWED
+C258;C258;1109 1170 11AF;C258;1109 1170 11AF; # (쉘; 쉘; 쉘; 쉘; 쉘; ) HANGUL SYLLABLE SWEL
+C259;C259;1109 1170 11B0;C259;1109 1170 11B0; # (쉙; 쉙; 쉙; 쉙; 쉙; ) HANGUL SYLLABLE SWELG
+C25A;C25A;1109 1170 11B1;C25A;1109 1170 11B1; # (쉚; 쉚; 쉚; 쉚; 쉚; ) HANGUL SYLLABLE SWELM
+C25B;C25B;1109 1170 11B2;C25B;1109 1170 11B2; # (쉛; 쉛; 쉛; 쉛; 쉛; ) HANGUL SYLLABLE SWELB
+C25C;C25C;1109 1170 11B3;C25C;1109 1170 11B3; # (쉜; 쉜; 쉜; 쉜; 쉜; ) HANGUL SYLLABLE SWELS
+C25D;C25D;1109 1170 11B4;C25D;1109 1170 11B4; # (쉝; 쉝; 쉝; 쉝; 쉝; ) HANGUL SYLLABLE SWELT
+C25E;C25E;1109 1170 11B5;C25E;1109 1170 11B5; # (쉞; 쉞; 쉞; 쉞; 쉞; ) HANGUL SYLLABLE SWELP
+C25F;C25F;1109 1170 11B6;C25F;1109 1170 11B6; # (쉟; 쉟; 쉟; 쉟; 쉟; ) HANGUL SYLLABLE SWELH
+C260;C260;1109 1170 11B7;C260;1109 1170 11B7; # (쉠; 쉠; 쉠; 쉠; 쉠; ) HANGUL SYLLABLE SWEM
+C261;C261;1109 1170 11B8;C261;1109 1170 11B8; # (쉡; 쉡; 쉡; 쉡; 쉡; ) HANGUL SYLLABLE SWEB
+C262;C262;1109 1170 11B9;C262;1109 1170 11B9; # (쉢; 쉢; 쉢; 쉢; 쉢; ) HANGUL SYLLABLE SWEBS
+C263;C263;1109 1170 11BA;C263;1109 1170 11BA; # (쉣; 쉣; 쉣; 쉣; 쉣; ) HANGUL SYLLABLE SWES
+C264;C264;1109 1170 11BB;C264;1109 1170 11BB; # (쉤; 쉤; 쉤; 쉤; 쉤; ) HANGUL SYLLABLE SWESS
+C265;C265;1109 1170 11BC;C265;1109 1170 11BC; # (쉥; 쉥; 쉥; 쉥; 쉥; ) HANGUL SYLLABLE SWENG
+C266;C266;1109 1170 11BD;C266;1109 1170 11BD; # (쉦; 쉦; 쉦; 쉦; 쉦; ) HANGUL SYLLABLE SWEJ
+C267;C267;1109 1170 11BE;C267;1109 1170 11BE; # (쉧; 쉧; 쉧; 쉧; 쉧; ) HANGUL SYLLABLE SWEC
+C268;C268;1109 1170 11BF;C268;1109 1170 11BF; # (쉨; 쉨; 쉨; 쉨; 쉨; ) HANGUL SYLLABLE SWEK
+C269;C269;1109 1170 11C0;C269;1109 1170 11C0; # (쉩; 쉩; 쉩; 쉩; 쉩; ) HANGUL SYLLABLE SWET
+C26A;C26A;1109 1170 11C1;C26A;1109 1170 11C1; # (쉪; 쉪; 쉪; 쉪; 쉪; ) HANGUL SYLLABLE SWEP
+C26B;C26B;1109 1170 11C2;C26B;1109 1170 11C2; # (쉫; 쉫; 쉫; 쉫; 쉫; ) HANGUL SYLLABLE SWEH
+C26C;C26C;1109 1171;C26C;1109 1171; # (쉬; 쉬; 쉬; 쉬; 쉬; ) HANGUL SYLLABLE SWI
+C26D;C26D;1109 1171 11A8;C26D;1109 1171 11A8; # (쉭; 쉭; 쉭; 쉭; 쉭; ) HANGUL SYLLABLE SWIG
+C26E;C26E;1109 1171 11A9;C26E;1109 1171 11A9; # (쉮; 쉮; 쉮; 쉮; 쉮; ) HANGUL SYLLABLE SWIGG
+C26F;C26F;1109 1171 11AA;C26F;1109 1171 11AA; # (쉯; 쉯; 쉯; 쉯; 쉯; ) HANGUL SYLLABLE SWIGS
+C270;C270;1109 1171 11AB;C270;1109 1171 11AB; # (쉰; 쉰; 쉰; 쉰; 쉰; ) HANGUL SYLLABLE SWIN
+C271;C271;1109 1171 11AC;C271;1109 1171 11AC; # (쉱; 쉱; 쉱; 쉱; 쉱; ) HANGUL SYLLABLE SWINJ
+C272;C272;1109 1171 11AD;C272;1109 1171 11AD; # (쉲; 쉲; 쉲; 쉲; 쉲; ) HANGUL SYLLABLE SWINH
+C273;C273;1109 1171 11AE;C273;1109 1171 11AE; # (쉳; 쉳; 쉳; 쉳; 쉳; ) HANGUL SYLLABLE SWID
+C274;C274;1109 1171 11AF;C274;1109 1171 11AF; # (쉴; 쉴; 쉴; 쉴; 쉴; ) HANGUL SYLLABLE SWIL
+C275;C275;1109 1171 11B0;C275;1109 1171 11B0; # (쉵; 쉵; 쉵; 쉵; 쉵; ) HANGUL SYLLABLE SWILG
+C276;C276;1109 1171 11B1;C276;1109 1171 11B1; # (쉶; 쉶; 쉶; 쉶; 쉶; ) HANGUL SYLLABLE SWILM
+C277;C277;1109 1171 11B2;C277;1109 1171 11B2; # (쉷; 쉷; 쉷; 쉷; 쉷; ) HANGUL SYLLABLE SWILB
+C278;C278;1109 1171 11B3;C278;1109 1171 11B3; # (쉸; 쉸; 쉸; 쉸; 쉸; ) HANGUL SYLLABLE SWILS
+C279;C279;1109 1171 11B4;C279;1109 1171 11B4; # (쉹; 쉹; 쉹; 쉹; 쉹; ) HANGUL SYLLABLE SWILT
+C27A;C27A;1109 1171 11B5;C27A;1109 1171 11B5; # (쉺; 쉺; 쉺; 쉺; 쉺; ) HANGUL SYLLABLE SWILP
+C27B;C27B;1109 1171 11B6;C27B;1109 1171 11B6; # (쉻; 쉻; 쉻; 쉻; 쉻; ) HANGUL SYLLABLE SWILH
+C27C;C27C;1109 1171 11B7;C27C;1109 1171 11B7; # (쉼; 쉼; 쉼; 쉼; 쉼; ) HANGUL SYLLABLE SWIM
+C27D;C27D;1109 1171 11B8;C27D;1109 1171 11B8; # (쉽; 쉽; 쉽; 쉽; 쉽; ) HANGUL SYLLABLE SWIB
+C27E;C27E;1109 1171 11B9;C27E;1109 1171 11B9; # (쉾; 쉾; 쉾; 쉾; 쉾; ) HANGUL SYLLABLE SWIBS
+C27F;C27F;1109 1171 11BA;C27F;1109 1171 11BA; # (쉿; 쉿; 쉿; 쉿; 쉿; ) HANGUL SYLLABLE SWIS
+C280;C280;1109 1171 11BB;C280;1109 1171 11BB; # (슀; 슀; 슀; 슀; 슀; ) HANGUL SYLLABLE SWISS
+C281;C281;1109 1171 11BC;C281;1109 1171 11BC; # (슁; 슁; 슁; 슁; 슁; ) HANGUL SYLLABLE SWING
+C282;C282;1109 1171 11BD;C282;1109 1171 11BD; # (슂; 슂; 슂; 슂; 슂; ) HANGUL SYLLABLE SWIJ
+C283;C283;1109 1171 11BE;C283;1109 1171 11BE; # (슃; 슃; 슃; 슃; 슃; ) HANGUL SYLLABLE SWIC
+C284;C284;1109 1171 11BF;C284;1109 1171 11BF; # (슄; 슄; 슄; 슄; 슄; ) HANGUL SYLLABLE SWIK
+C285;C285;1109 1171 11C0;C285;1109 1171 11C0; # (슅; 슅; 슅; 슅; 슅; ) HANGUL SYLLABLE SWIT
+C286;C286;1109 1171 11C1;C286;1109 1171 11C1; # (슆; 슆; 슆; 슆; 슆; ) HANGUL SYLLABLE SWIP
+C287;C287;1109 1171 11C2;C287;1109 1171 11C2; # (슇; 슇; 슇; 슇; 슇; ) HANGUL SYLLABLE SWIH
+C288;C288;1109 1172;C288;1109 1172; # (슈; 슈; 슈; 슈; 슈; ) HANGUL SYLLABLE SYU
+C289;C289;1109 1172 11A8;C289;1109 1172 11A8; # (슉; 슉; 슉; 슉; 슉; ) HANGUL SYLLABLE SYUG
+C28A;C28A;1109 1172 11A9;C28A;1109 1172 11A9; # (슊; 슊; 슊; 슊; 슊; ) HANGUL SYLLABLE SYUGG
+C28B;C28B;1109 1172 11AA;C28B;1109 1172 11AA; # (슋; 슋; 슋; 슋; 슋; ) HANGUL SYLLABLE SYUGS
+C28C;C28C;1109 1172 11AB;C28C;1109 1172 11AB; # (슌; 슌; 슌; 슌; 슌; ) HANGUL SYLLABLE SYUN
+C28D;C28D;1109 1172 11AC;C28D;1109 1172 11AC; # (슍; 슍; 슍; 슍; 슍; ) HANGUL SYLLABLE SYUNJ
+C28E;C28E;1109 1172 11AD;C28E;1109 1172 11AD; # (슎; 슎; 슎; 슎; 슎; ) HANGUL SYLLABLE SYUNH
+C28F;C28F;1109 1172 11AE;C28F;1109 1172 11AE; # (슏; 슏; 슏; 슏; 슏; ) HANGUL SYLLABLE SYUD
+C290;C290;1109 1172 11AF;C290;1109 1172 11AF; # (슐; 슐; 슐; 슐; 슐; ) HANGUL SYLLABLE SYUL
+C291;C291;1109 1172 11B0;C291;1109 1172 11B0; # (슑; 슑; 슑; 슑; 슑; ) HANGUL SYLLABLE SYULG
+C292;C292;1109 1172 11B1;C292;1109 1172 11B1; # (슒; 슒; 슒; 슒; 슒; ) HANGUL SYLLABLE SYULM
+C293;C293;1109 1172 11B2;C293;1109 1172 11B2; # (슓; 슓; 슓; 슓; 슓; ) HANGUL SYLLABLE SYULB
+C294;C294;1109 1172 11B3;C294;1109 1172 11B3; # (슔; 슔; 슔; 슔; 슔; ) HANGUL SYLLABLE SYULS
+C295;C295;1109 1172 11B4;C295;1109 1172 11B4; # (슕; 슕; 슕; 슕; 슕; ) HANGUL SYLLABLE SYULT
+C296;C296;1109 1172 11B5;C296;1109 1172 11B5; # (슖; 슖; 슖; 슖; 슖; ) HANGUL SYLLABLE SYULP
+C297;C297;1109 1172 11B6;C297;1109 1172 11B6; # (슗; 슗; 슗; 슗; 슗; ) HANGUL SYLLABLE SYULH
+C298;C298;1109 1172 11B7;C298;1109 1172 11B7; # (슘; 슘; 슘; 슘; 슘; ) HANGUL SYLLABLE SYUM
+C299;C299;1109 1172 11B8;C299;1109 1172 11B8; # (슙; 슙; 슙; 슙; 슙; ) HANGUL SYLLABLE SYUB
+C29A;C29A;1109 1172 11B9;C29A;1109 1172 11B9; # (슚; 슚; 슚; 슚; 슚; ) HANGUL SYLLABLE SYUBS
+C29B;C29B;1109 1172 11BA;C29B;1109 1172 11BA; # (슛; 슛; 슛; 슛; 슛; ) HANGUL SYLLABLE SYUS
+C29C;C29C;1109 1172 11BB;C29C;1109 1172 11BB; # (슜; 슜; 슜; 슜; 슜; ) HANGUL SYLLABLE SYUSS
+C29D;C29D;1109 1172 11BC;C29D;1109 1172 11BC; # (슝; 슝; 슝; 슝; 슝; ) HANGUL SYLLABLE SYUNG
+C29E;C29E;1109 1172 11BD;C29E;1109 1172 11BD; # (슞; 슞; 슞; 슞; 슞; ) HANGUL SYLLABLE SYUJ
+C29F;C29F;1109 1172 11BE;C29F;1109 1172 11BE; # (슟; 슟; 슟; 슟; 슟; ) HANGUL SYLLABLE SYUC
+C2A0;C2A0;1109 1172 11BF;C2A0;1109 1172 11BF; # (슠; 슠; 슠; 슠; 슠; ) HANGUL SYLLABLE SYUK
+C2A1;C2A1;1109 1172 11C0;C2A1;1109 1172 11C0; # (슡; 슡; 슡; 슡; 슡; ) HANGUL SYLLABLE SYUT
+C2A2;C2A2;1109 1172 11C1;C2A2;1109 1172 11C1; # (슢; 슢; 슢; 슢; 슢; ) HANGUL SYLLABLE SYUP
+C2A3;C2A3;1109 1172 11C2;C2A3;1109 1172 11C2; # (슣; 슣; 슣; 슣; 슣; ) HANGUL SYLLABLE SYUH
+C2A4;C2A4;1109 1173;C2A4;1109 1173; # (스; 스; 스; 스; 스; ) HANGUL SYLLABLE SEU
+C2A5;C2A5;1109 1173 11A8;C2A5;1109 1173 11A8; # (슥; 슥; 슥; 슥; 슥; ) HANGUL SYLLABLE SEUG
+C2A6;C2A6;1109 1173 11A9;C2A6;1109 1173 11A9; # (슦; 슦; 슦; 슦; 슦; ) HANGUL SYLLABLE SEUGG
+C2A7;C2A7;1109 1173 11AA;C2A7;1109 1173 11AA; # (슧; 슧; 슧; 슧; 슧; ) HANGUL SYLLABLE SEUGS
+C2A8;C2A8;1109 1173 11AB;C2A8;1109 1173 11AB; # (슨; 슨; 슨; 슨; 슨; ) HANGUL SYLLABLE SEUN
+C2A9;C2A9;1109 1173 11AC;C2A9;1109 1173 11AC; # (슩; 슩; 슩; 슩; 슩; ) HANGUL SYLLABLE SEUNJ
+C2AA;C2AA;1109 1173 11AD;C2AA;1109 1173 11AD; # (슪; 슪; 슪; 슪; 슪; ) HANGUL SYLLABLE SEUNH
+C2AB;C2AB;1109 1173 11AE;C2AB;1109 1173 11AE; # (슫; 슫; 슫; 슫; 슫; ) HANGUL SYLLABLE SEUD
+C2AC;C2AC;1109 1173 11AF;C2AC;1109 1173 11AF; # (슬; 슬; 슬; 슬; 슬; ) HANGUL SYLLABLE SEUL
+C2AD;C2AD;1109 1173 11B0;C2AD;1109 1173 11B0; # (슭; 슭; 슭; 슭; 슭; ) HANGUL SYLLABLE SEULG
+C2AE;C2AE;1109 1173 11B1;C2AE;1109 1173 11B1; # (슮; 슮; 슮; 슮; 슮; ) HANGUL SYLLABLE SEULM
+C2AF;C2AF;1109 1173 11B2;C2AF;1109 1173 11B2; # (슯; 슯; 슯; 슯; 슯; ) HANGUL SYLLABLE SEULB
+C2B0;C2B0;1109 1173 11B3;C2B0;1109 1173 11B3; # (슰; 슰; 슰; 슰; 슰; ) HANGUL SYLLABLE SEULS
+C2B1;C2B1;1109 1173 11B4;C2B1;1109 1173 11B4; # (슱; 슱; 슱; 슱; 슱; ) HANGUL SYLLABLE SEULT
+C2B2;C2B2;1109 1173 11B5;C2B2;1109 1173 11B5; # (슲; 슲; 슲; 슲; 슲; ) HANGUL SYLLABLE SEULP
+C2B3;C2B3;1109 1173 11B6;C2B3;1109 1173 11B6; # (슳; 슳; 슳; 슳; 슳; ) HANGUL SYLLABLE SEULH
+C2B4;C2B4;1109 1173 11B7;C2B4;1109 1173 11B7; # (슴; 슴; 슴; 슴; 슴; ) HANGUL SYLLABLE SEUM
+C2B5;C2B5;1109 1173 11B8;C2B5;1109 1173 11B8; # (습; 습; 습; 습; 습; ) HANGUL SYLLABLE SEUB
+C2B6;C2B6;1109 1173 11B9;C2B6;1109 1173 11B9; # (슶; 슶; 슶; 슶; 슶; ) HANGUL SYLLABLE SEUBS
+C2B7;C2B7;1109 1173 11BA;C2B7;1109 1173 11BA; # (슷; 슷; 슷; 슷; 슷; ) HANGUL SYLLABLE SEUS
+C2B8;C2B8;1109 1173 11BB;C2B8;1109 1173 11BB; # (슸; 슸; 슸; 슸; 슸; ) HANGUL SYLLABLE SEUSS
+C2B9;C2B9;1109 1173 11BC;C2B9;1109 1173 11BC; # (승; 승; 승; 승; 승; ) HANGUL SYLLABLE SEUNG
+C2BA;C2BA;1109 1173 11BD;C2BA;1109 1173 11BD; # (슺; 슺; 슺; 슺; 슺; ) HANGUL SYLLABLE SEUJ
+C2BB;C2BB;1109 1173 11BE;C2BB;1109 1173 11BE; # (슻; 슻; 슻; 슻; 슻; ) HANGUL SYLLABLE SEUC
+C2BC;C2BC;1109 1173 11BF;C2BC;1109 1173 11BF; # (슼; 슼; 슼; 슼; 슼; ) HANGUL SYLLABLE SEUK
+C2BD;C2BD;1109 1173 11C0;C2BD;1109 1173 11C0; # (슽; 슽; 슽; 슽; 슽; ) HANGUL SYLLABLE SEUT
+C2BE;C2BE;1109 1173 11C1;C2BE;1109 1173 11C1; # (슾; 슾; 슾; 슾; 슾; ) HANGUL SYLLABLE SEUP
+C2BF;C2BF;1109 1173 11C2;C2BF;1109 1173 11C2; # (슿; 슿; 슿; 슿; 슿; ) HANGUL SYLLABLE SEUH
+C2C0;C2C0;1109 1174;C2C0;1109 1174; # (싀; 싀; 싀; 싀; 싀; ) HANGUL SYLLABLE SYI
+C2C1;C2C1;1109 1174 11A8;C2C1;1109 1174 11A8; # (싁; 싁; 싁; 싁; 싁; ) HANGUL SYLLABLE SYIG
+C2C2;C2C2;1109 1174 11A9;C2C2;1109 1174 11A9; # (싂; 싂; 싂; 싂; 싂; ) HANGUL SYLLABLE SYIGG
+C2C3;C2C3;1109 1174 11AA;C2C3;1109 1174 11AA; # (싃; 싃; 싃; 싃; 싃; ) HANGUL SYLLABLE SYIGS
+C2C4;C2C4;1109 1174 11AB;C2C4;1109 1174 11AB; # (싄; 싄; 싄; 싄; 싄; ) HANGUL SYLLABLE SYIN
+C2C5;C2C5;1109 1174 11AC;C2C5;1109 1174 11AC; # (싅; 싅; 싅; 싅; 싅; ) HANGUL SYLLABLE SYINJ
+C2C6;C2C6;1109 1174 11AD;C2C6;1109 1174 11AD; # (싆; 싆; 싆; 싆; 싆; ) HANGUL SYLLABLE SYINH
+C2C7;C2C7;1109 1174 11AE;C2C7;1109 1174 11AE; # (싇; 싇; 싇; 싇; 싇; ) HANGUL SYLLABLE SYID
+C2C8;C2C8;1109 1174 11AF;C2C8;1109 1174 11AF; # (싈; 싈; 싈; 싈; 싈; ) HANGUL SYLLABLE SYIL
+C2C9;C2C9;1109 1174 11B0;C2C9;1109 1174 11B0; # (싉; 싉; 싉; 싉; 싉; ) HANGUL SYLLABLE SYILG
+C2CA;C2CA;1109 1174 11B1;C2CA;1109 1174 11B1; # (싊; 싊; 싊; 싊; 싊; ) HANGUL SYLLABLE SYILM
+C2CB;C2CB;1109 1174 11B2;C2CB;1109 1174 11B2; # (싋; 싋; 싋; 싋; 싋; ) HANGUL SYLLABLE SYILB
+C2CC;C2CC;1109 1174 11B3;C2CC;1109 1174 11B3; # (싌; 싌; 싌; 싌; 싌; ) HANGUL SYLLABLE SYILS
+C2CD;C2CD;1109 1174 11B4;C2CD;1109 1174 11B4; # (싍; 싍; 싍; 싍; 싍; ) HANGUL SYLLABLE SYILT
+C2CE;C2CE;1109 1174 11B5;C2CE;1109 1174 11B5; # (싎; 싎; 싎; 싎; 싎; ) HANGUL SYLLABLE SYILP
+C2CF;C2CF;1109 1174 11B6;C2CF;1109 1174 11B6; # (싏; 싏; 싏; 싏; 싏; ) HANGUL SYLLABLE SYILH
+C2D0;C2D0;1109 1174 11B7;C2D0;1109 1174 11B7; # (싐; 싐; 싐; 싐; 싐; ) HANGUL SYLLABLE SYIM
+C2D1;C2D1;1109 1174 11B8;C2D1;1109 1174 11B8; # (싑; 싑; 싑; 싑; 싑; ) HANGUL SYLLABLE SYIB
+C2D2;C2D2;1109 1174 11B9;C2D2;1109 1174 11B9; # (싒; 싒; 싒; 싒; 싒; ) HANGUL SYLLABLE SYIBS
+C2D3;C2D3;1109 1174 11BA;C2D3;1109 1174 11BA; # (싓; 싓; 싓; 싓; 싓; ) HANGUL SYLLABLE SYIS
+C2D4;C2D4;1109 1174 11BB;C2D4;1109 1174 11BB; # (싔; 싔; 싔; 싔; 싔; ) HANGUL SYLLABLE SYISS
+C2D5;C2D5;1109 1174 11BC;C2D5;1109 1174 11BC; # (싕; 싕; 싕; 싕; 싕; ) HANGUL SYLLABLE SYING
+C2D6;C2D6;1109 1174 11BD;C2D6;1109 1174 11BD; # (싖; 싖; 싖; 싖; 싖; ) HANGUL SYLLABLE SYIJ
+C2D7;C2D7;1109 1174 11BE;C2D7;1109 1174 11BE; # (싗; 싗; 싗; 싗; 싗; ) HANGUL SYLLABLE SYIC
+C2D8;C2D8;1109 1174 11BF;C2D8;1109 1174 11BF; # (싘; 싘; 싘; 싘; 싘; ) HANGUL SYLLABLE SYIK
+C2D9;C2D9;1109 1174 11C0;C2D9;1109 1174 11C0; # (싙; 싙; 싙; 싙; 싙; ) HANGUL SYLLABLE SYIT
+C2DA;C2DA;1109 1174 11C1;C2DA;1109 1174 11C1; # (싚; 싚; 싚; 싚; 싚; ) HANGUL SYLLABLE SYIP
+C2DB;C2DB;1109 1174 11C2;C2DB;1109 1174 11C2; # (싛; 싛; 싛; 싛; 싛; ) HANGUL SYLLABLE SYIH
+C2DC;C2DC;1109 1175;C2DC;1109 1175; # (시; 시; 시; 시; 시; ) HANGUL SYLLABLE SI
+C2DD;C2DD;1109 1175 11A8;C2DD;1109 1175 11A8; # (식; 식; 식; 식; 식; ) HANGUL SYLLABLE SIG
+C2DE;C2DE;1109 1175 11A9;C2DE;1109 1175 11A9; # (싞; 싞; 싞; 싞; 싞; ) HANGUL SYLLABLE SIGG
+C2DF;C2DF;1109 1175 11AA;C2DF;1109 1175 11AA; # (싟; 싟; 싟; 싟; 싟; ) HANGUL SYLLABLE SIGS
+C2E0;C2E0;1109 1175 11AB;C2E0;1109 1175 11AB; # (신; 신; 신; 신; 신; ) HANGUL SYLLABLE SIN
+C2E1;C2E1;1109 1175 11AC;C2E1;1109 1175 11AC; # (싡; 싡; 싡; 싡; 싡; ) HANGUL SYLLABLE SINJ
+C2E2;C2E2;1109 1175 11AD;C2E2;1109 1175 11AD; # (싢; 싢; 싢; 싢; 싢; ) HANGUL SYLLABLE SINH
+C2E3;C2E3;1109 1175 11AE;C2E3;1109 1175 11AE; # (싣; 싣; 싣; 싣; 싣; ) HANGUL SYLLABLE SID
+C2E4;C2E4;1109 1175 11AF;C2E4;1109 1175 11AF; # (실; 실; 실; 실; 실; ) HANGUL SYLLABLE SIL
+C2E5;C2E5;1109 1175 11B0;C2E5;1109 1175 11B0; # (싥; 싥; 싥; 싥; 싥; ) HANGUL SYLLABLE SILG
+C2E6;C2E6;1109 1175 11B1;C2E6;1109 1175 11B1; # (싦; 싦; 싦; 싦; 싦; ) HANGUL SYLLABLE SILM
+C2E7;C2E7;1109 1175 11B2;C2E7;1109 1175 11B2; # (싧; 싧; 싧; 싧; 싧; ) HANGUL SYLLABLE SILB
+C2E8;C2E8;1109 1175 11B3;C2E8;1109 1175 11B3; # (싨; 싨; 싨; 싨; 싨; ) HANGUL SYLLABLE SILS
+C2E9;C2E9;1109 1175 11B4;C2E9;1109 1175 11B4; # (싩; 싩; 싩; 싩; 싩; ) HANGUL SYLLABLE SILT
+C2EA;C2EA;1109 1175 11B5;C2EA;1109 1175 11B5; # (싪; 싪; 싪; 싪; 싪; ) HANGUL SYLLABLE SILP
+C2EB;C2EB;1109 1175 11B6;C2EB;1109 1175 11B6; # (싫; 싫; 싫; 싫; 싫; ) HANGUL SYLLABLE SILH
+C2EC;C2EC;1109 1175 11B7;C2EC;1109 1175 11B7; # (심; 심; 심; 심; 심; ) HANGUL SYLLABLE SIM
+C2ED;C2ED;1109 1175 11B8;C2ED;1109 1175 11B8; # (십; 십; 십; 십; 십; ) HANGUL SYLLABLE SIB
+C2EE;C2EE;1109 1175 11B9;C2EE;1109 1175 11B9; # (싮; 싮; 싮; 싮; 싮; ) HANGUL SYLLABLE SIBS
+C2EF;C2EF;1109 1175 11BA;C2EF;1109 1175 11BA; # (싯; 싯; 싯; 싯; 싯; ) HANGUL SYLLABLE SIS
+C2F0;C2F0;1109 1175 11BB;C2F0;1109 1175 11BB; # (싰; 싰; 싰; 싰; 싰; ) HANGUL SYLLABLE SISS
+C2F1;C2F1;1109 1175 11BC;C2F1;1109 1175 11BC; # (싱; 싱; 싱; 싱; 싱; ) HANGUL SYLLABLE SING
+C2F2;C2F2;1109 1175 11BD;C2F2;1109 1175 11BD; # (싲; 싲; 싲; 싲; 싲; ) HANGUL SYLLABLE SIJ
+C2F3;C2F3;1109 1175 11BE;C2F3;1109 1175 11BE; # (싳; 싳; 싳; 싳; 싳; ) HANGUL SYLLABLE SIC
+C2F4;C2F4;1109 1175 11BF;C2F4;1109 1175 11BF; # (싴; 싴; 싴; 싴; 싴; ) HANGUL SYLLABLE SIK
+C2F5;C2F5;1109 1175 11C0;C2F5;1109 1175 11C0; # (싵; 싵; 싵; 싵; 싵; ) HANGUL SYLLABLE SIT
+C2F6;C2F6;1109 1175 11C1;C2F6;1109 1175 11C1; # (싶; 싶; 싶; 싶; 싶; ) HANGUL SYLLABLE SIP
+C2F7;C2F7;1109 1175 11C2;C2F7;1109 1175 11C2; # (싷; 싷; 싷; 싷; 싷; ) HANGUL SYLLABLE SIH
+C2F8;C2F8;110A 1161;C2F8;110A 1161; # (싸; 싸; 싸; 싸; 싸; ) HANGUL SYLLABLE SSA
+C2F9;C2F9;110A 1161 11A8;C2F9;110A 1161 11A8; # (싹; 싹; 싹; 싹; 싹; ) HANGUL SYLLABLE SSAG
+C2FA;C2FA;110A 1161 11A9;C2FA;110A 1161 11A9; # (싺; 싺; 싺; 싺; 싺; ) HANGUL SYLLABLE SSAGG
+C2FB;C2FB;110A 1161 11AA;C2FB;110A 1161 11AA; # (싻; 싻; 싻; 싻; 싻; ) HANGUL SYLLABLE SSAGS
+C2FC;C2FC;110A 1161 11AB;C2FC;110A 1161 11AB; # (싼; 싼; 싼; 싼; 싼; ) HANGUL SYLLABLE SSAN
+C2FD;C2FD;110A 1161 11AC;C2FD;110A 1161 11AC; # (싽; 싽; 싽; 싽; 싽; ) HANGUL SYLLABLE SSANJ
+C2FE;C2FE;110A 1161 11AD;C2FE;110A 1161 11AD; # (싾; 싾; 싾; 싾; 싾; ) HANGUL SYLLABLE SSANH
+C2FF;C2FF;110A 1161 11AE;C2FF;110A 1161 11AE; # (싿; 싿; 싿; 싿; 싿; ) HANGUL SYLLABLE SSAD
+C300;C300;110A 1161 11AF;C300;110A 1161 11AF; # (쌀; 쌀; 쌀; 쌀; 쌀; ) HANGUL SYLLABLE SSAL
+C301;C301;110A 1161 11B0;C301;110A 1161 11B0; # (쌁; 쌁; 쌁; 쌁; 쌁; ) HANGUL SYLLABLE SSALG
+C302;C302;110A 1161 11B1;C302;110A 1161 11B1; # (쌂; 쌂; 쌂; 쌂; 쌂; ) HANGUL SYLLABLE SSALM
+C303;C303;110A 1161 11B2;C303;110A 1161 11B2; # (쌃; 쌃; 쌃; 쌃; 쌃; ) HANGUL SYLLABLE SSALB
+C304;C304;110A 1161 11B3;C304;110A 1161 11B3; # (쌄; 쌄; 쌄; 쌄; 쌄; ) HANGUL SYLLABLE SSALS
+C305;C305;110A 1161 11B4;C305;110A 1161 11B4; # (쌅; 쌅; 쌅; 쌅; 쌅; ) HANGUL SYLLABLE SSALT
+C306;C306;110A 1161 11B5;C306;110A 1161 11B5; # (쌆; 쌆; 쌆; 쌆; 쌆; ) HANGUL SYLLABLE SSALP
+C307;C307;110A 1161 11B6;C307;110A 1161 11B6; # (쌇; 쌇; 쌇; 쌇; 쌇; ) HANGUL SYLLABLE SSALH
+C308;C308;110A 1161 11B7;C308;110A 1161 11B7; # (쌈; 쌈; 쌈; 쌈; 쌈; ) HANGUL SYLLABLE SSAM
+C309;C309;110A 1161 11B8;C309;110A 1161 11B8; # (쌉; 쌉; 쌉; 쌉; 쌉; ) HANGUL SYLLABLE SSAB
+C30A;C30A;110A 1161 11B9;C30A;110A 1161 11B9; # (쌊; 쌊; 쌊; 쌊; 쌊; ) HANGUL SYLLABLE SSABS
+C30B;C30B;110A 1161 11BA;C30B;110A 1161 11BA; # (쌋; 쌋; 쌋; 쌋; 쌋; ) HANGUL SYLLABLE SSAS
+C30C;C30C;110A 1161 11BB;C30C;110A 1161 11BB; # (쌌; 쌌; 쌌; 쌌; 쌌; ) HANGUL SYLLABLE SSASS
+C30D;C30D;110A 1161 11BC;C30D;110A 1161 11BC; # (쌍; 쌍; 쌍; 쌍; 쌍; ) HANGUL SYLLABLE SSANG
+C30E;C30E;110A 1161 11BD;C30E;110A 1161 11BD; # (쌎; 쌎; 쌎; 쌎; 쌎; ) HANGUL SYLLABLE SSAJ
+C30F;C30F;110A 1161 11BE;C30F;110A 1161 11BE; # (쌏; 쌏; 쌏; 쌏; 쌏; ) HANGUL SYLLABLE SSAC
+C310;C310;110A 1161 11BF;C310;110A 1161 11BF; # (쌐; 쌐; 쌐; 쌐; 쌐; ) HANGUL SYLLABLE SSAK
+C311;C311;110A 1161 11C0;C311;110A 1161 11C0; # (쌑; 쌑; 쌑; 쌑; 쌑; ) HANGUL SYLLABLE SSAT
+C312;C312;110A 1161 11C1;C312;110A 1161 11C1; # (쌒; 쌒; 쌒; 쌒; 쌒; ) HANGUL SYLLABLE SSAP
+C313;C313;110A 1161 11C2;C313;110A 1161 11C2; # (쌓; 쌓; 쌓; 쌓; 쌓; ) HANGUL SYLLABLE SSAH
+C314;C314;110A 1162;C314;110A 1162; # (쌔; 쌔; 쌔; 쌔; 쌔; ) HANGUL SYLLABLE SSAE
+C315;C315;110A 1162 11A8;C315;110A 1162 11A8; # (쌕; 쌕; 쌕; 쌕; 쌕; ) HANGUL SYLLABLE SSAEG
+C316;C316;110A 1162 11A9;C316;110A 1162 11A9; # (쌖; 쌖; 쌖; 쌖; 쌖; ) HANGUL SYLLABLE SSAEGG
+C317;C317;110A 1162 11AA;C317;110A 1162 11AA; # (쌗; 쌗; 쌗; 쌗; 쌗; ) HANGUL SYLLABLE SSAEGS
+C318;C318;110A 1162 11AB;C318;110A 1162 11AB; # (쌘; 쌘; 쌘; 쌘; 쌘; ) HANGUL SYLLABLE SSAEN
+C319;C319;110A 1162 11AC;C319;110A 1162 11AC; # (쌙; 쌙; 쌙; 쌙; 쌙; ) HANGUL SYLLABLE SSAENJ
+C31A;C31A;110A 1162 11AD;C31A;110A 1162 11AD; # (쌚; 쌚; 쌚; 쌚; 쌚; ) HANGUL SYLLABLE SSAENH
+C31B;C31B;110A 1162 11AE;C31B;110A 1162 11AE; # (쌛; 쌛; 쌛; 쌛; 쌛; ) HANGUL SYLLABLE SSAED
+C31C;C31C;110A 1162 11AF;C31C;110A 1162 11AF; # (쌜; 쌜; 쌜; 쌜; 쌜; ) HANGUL SYLLABLE SSAEL
+C31D;C31D;110A 1162 11B0;C31D;110A 1162 11B0; # (쌝; 쌝; 쌝; 쌝; 쌝; ) HANGUL SYLLABLE SSAELG
+C31E;C31E;110A 1162 11B1;C31E;110A 1162 11B1; # (쌞; 쌞; 쌞; 쌞; 쌞; ) HANGUL SYLLABLE SSAELM
+C31F;C31F;110A 1162 11B2;C31F;110A 1162 11B2; # (쌟; 쌟; 쌟; 쌟; 쌟; ) HANGUL SYLLABLE SSAELB
+C320;C320;110A 1162 11B3;C320;110A 1162 11B3; # (쌠; 쌠; 쌠; 쌠; 쌠; ) HANGUL SYLLABLE SSAELS
+C321;C321;110A 1162 11B4;C321;110A 1162 11B4; # (쌡; 쌡; 쌡; 쌡; 쌡; ) HANGUL SYLLABLE SSAELT
+C322;C322;110A 1162 11B5;C322;110A 1162 11B5; # (쌢; 쌢; 쌢; 쌢; 쌢; ) HANGUL SYLLABLE SSAELP
+C323;C323;110A 1162 11B6;C323;110A 1162 11B6; # (쌣; 쌣; 쌣; 쌣; 쌣; ) HANGUL SYLLABLE SSAELH
+C324;C324;110A 1162 11B7;C324;110A 1162 11B7; # (쌤; 쌤; 쌤; 쌤; 쌤; ) HANGUL SYLLABLE SSAEM
+C325;C325;110A 1162 11B8;C325;110A 1162 11B8; # (쌥; 쌥; 쌥; 쌥; 쌥; ) HANGUL SYLLABLE SSAEB
+C326;C326;110A 1162 11B9;C326;110A 1162 11B9; # (쌦; 쌦; 쌦; 쌦; 쌦; ) HANGUL SYLLABLE SSAEBS
+C327;C327;110A 1162 11BA;C327;110A 1162 11BA; # (쌧; 쌧; 쌧; 쌧; 쌧; ) HANGUL SYLLABLE SSAES
+C328;C328;110A 1162 11BB;C328;110A 1162 11BB; # (쌨; 쌨; 쌨; 쌨; 쌨; ) HANGUL SYLLABLE SSAESS
+C329;C329;110A 1162 11BC;C329;110A 1162 11BC; # (쌩; 쌩; 쌩; 쌩; 쌩; ) HANGUL SYLLABLE SSAENG
+C32A;C32A;110A 1162 11BD;C32A;110A 1162 11BD; # (쌪; 쌪; 쌪; 쌪; 쌪; ) HANGUL SYLLABLE SSAEJ
+C32B;C32B;110A 1162 11BE;C32B;110A 1162 11BE; # (쌫; 쌫; 쌫; 쌫; 쌫; ) HANGUL SYLLABLE SSAEC
+C32C;C32C;110A 1162 11BF;C32C;110A 1162 11BF; # (쌬; 쌬; 쌬; 쌬; 쌬; ) HANGUL SYLLABLE SSAEK
+C32D;C32D;110A 1162 11C0;C32D;110A 1162 11C0; # (쌭; 쌭; 쌭; 쌭; 쌭; ) HANGUL SYLLABLE SSAET
+C32E;C32E;110A 1162 11C1;C32E;110A 1162 11C1; # (쌮; 쌮; 쌮; 쌮; 쌮; ) HANGUL SYLLABLE SSAEP
+C32F;C32F;110A 1162 11C2;C32F;110A 1162 11C2; # (쌯; 쌯; 쌯; 쌯; 쌯; ) HANGUL SYLLABLE SSAEH
+C330;C330;110A 1163;C330;110A 1163; # (쌰; 쌰; 쌰; 쌰; 쌰; ) HANGUL SYLLABLE SSYA
+C331;C331;110A 1163 11A8;C331;110A 1163 11A8; # (쌱; 쌱; 쌱; 쌱; 쌱; ) HANGUL SYLLABLE SSYAG
+C332;C332;110A 1163 11A9;C332;110A 1163 11A9; # (쌲; 쌲; 쌲; 쌲; 쌲; ) HANGUL SYLLABLE SSYAGG
+C333;C333;110A 1163 11AA;C333;110A 1163 11AA; # (쌳; 쌳; 쌳; 쌳; 쌳; ) HANGUL SYLLABLE SSYAGS
+C334;C334;110A 1163 11AB;C334;110A 1163 11AB; # (쌴; 쌴; 쌴; 쌴; 쌴; ) HANGUL SYLLABLE SSYAN
+C335;C335;110A 1163 11AC;C335;110A 1163 11AC; # (쌵; 쌵; 쌵; 쌵; 쌵; ) HANGUL SYLLABLE SSYANJ
+C336;C336;110A 1163 11AD;C336;110A 1163 11AD; # (쌶; 쌶; 쌶; 쌶; 쌶; ) HANGUL SYLLABLE SSYANH
+C337;C337;110A 1163 11AE;C337;110A 1163 11AE; # (쌷; 쌷; 쌷; 쌷; 쌷; ) HANGUL SYLLABLE SSYAD
+C338;C338;110A 1163 11AF;C338;110A 1163 11AF; # (쌸; 쌸; 쌸; 쌸; 쌸; ) HANGUL SYLLABLE SSYAL
+C339;C339;110A 1163 11B0;C339;110A 1163 11B0; # (쌹; 쌹; 쌹; 쌹; 쌹; ) HANGUL SYLLABLE SSYALG
+C33A;C33A;110A 1163 11B1;C33A;110A 1163 11B1; # (쌺; 쌺; 쌺; 쌺; 쌺; ) HANGUL SYLLABLE SSYALM
+C33B;C33B;110A 1163 11B2;C33B;110A 1163 11B2; # (쌻; 쌻; 쌻; 쌻; 쌻; ) HANGUL SYLLABLE SSYALB
+C33C;C33C;110A 1163 11B3;C33C;110A 1163 11B3; # (쌼; 쌼; 쌼; 쌼; 쌼; ) HANGUL SYLLABLE SSYALS
+C33D;C33D;110A 1163 11B4;C33D;110A 1163 11B4; # (쌽; 쌽; 쌽; 쌽; 쌽; ) HANGUL SYLLABLE SSYALT
+C33E;C33E;110A 1163 11B5;C33E;110A 1163 11B5; # (쌾; 쌾; 쌾; 쌾; 쌾; ) HANGUL SYLLABLE SSYALP
+C33F;C33F;110A 1163 11B6;C33F;110A 1163 11B6; # (쌿; 쌿; 쌿; 쌿; 쌿; ) HANGUL SYLLABLE SSYALH
+C340;C340;110A 1163 11B7;C340;110A 1163 11B7; # (썀; 썀; 썀; 썀; 썀; ) HANGUL SYLLABLE SSYAM
+C341;C341;110A 1163 11B8;C341;110A 1163 11B8; # (썁; 썁; 썁; 썁; 썁; ) HANGUL SYLLABLE SSYAB
+C342;C342;110A 1163 11B9;C342;110A 1163 11B9; # (썂; 썂; 썂; 썂; 썂; ) HANGUL SYLLABLE SSYABS
+C343;C343;110A 1163 11BA;C343;110A 1163 11BA; # (썃; 썃; 썃; 썃; 썃; ) HANGUL SYLLABLE SSYAS
+C344;C344;110A 1163 11BB;C344;110A 1163 11BB; # (썄; 썄; 썄; 썄; 썄; ) HANGUL SYLLABLE SSYASS
+C345;C345;110A 1163 11BC;C345;110A 1163 11BC; # (썅; 썅; 썅; 썅; 썅; ) HANGUL SYLLABLE SSYANG
+C346;C346;110A 1163 11BD;C346;110A 1163 11BD; # (썆; 썆; 썆; 썆; 썆; ) HANGUL SYLLABLE SSYAJ
+C347;C347;110A 1163 11BE;C347;110A 1163 11BE; # (썇; 썇; 썇; 썇; 썇; ) HANGUL SYLLABLE SSYAC
+C348;C348;110A 1163 11BF;C348;110A 1163 11BF; # (썈; 썈; 썈; 썈; 썈; ) HANGUL SYLLABLE SSYAK
+C349;C349;110A 1163 11C0;C349;110A 1163 11C0; # (썉; 썉; 썉; 썉; 썉; ) HANGUL SYLLABLE SSYAT
+C34A;C34A;110A 1163 11C1;C34A;110A 1163 11C1; # (썊; 썊; 썊; 썊; 썊; ) HANGUL SYLLABLE SSYAP
+C34B;C34B;110A 1163 11C2;C34B;110A 1163 11C2; # (썋; 썋; 썋; 썋; 썋; ) HANGUL SYLLABLE SSYAH
+C34C;C34C;110A 1164;C34C;110A 1164; # (썌; 썌; 썌; 썌; 썌; ) HANGUL SYLLABLE SSYAE
+C34D;C34D;110A 1164 11A8;C34D;110A 1164 11A8; # (썍; 썍; 썍; 썍; 썍; ) HANGUL SYLLABLE SSYAEG
+C34E;C34E;110A 1164 11A9;C34E;110A 1164 11A9; # (썎; 썎; 썎; 썎; 썎; ) HANGUL SYLLABLE SSYAEGG
+C34F;C34F;110A 1164 11AA;C34F;110A 1164 11AA; # (썏; 썏; 썏; 썏; 썏; ) HANGUL SYLLABLE SSYAEGS
+C350;C350;110A 1164 11AB;C350;110A 1164 11AB; # (썐; 썐; 썐; 썐; 썐; ) HANGUL SYLLABLE SSYAEN
+C351;C351;110A 1164 11AC;C351;110A 1164 11AC; # (썑; 썑; 썑; 썑; 썑; ) HANGUL SYLLABLE SSYAENJ
+C352;C352;110A 1164 11AD;C352;110A 1164 11AD; # (썒; 썒; 썒; 썒; 썒; ) HANGUL SYLLABLE SSYAENH
+C353;C353;110A 1164 11AE;C353;110A 1164 11AE; # (썓; 썓; 썓; 썓; 썓; ) HANGUL SYLLABLE SSYAED
+C354;C354;110A 1164 11AF;C354;110A 1164 11AF; # (썔; 썔; 썔; 썔; 썔; ) HANGUL SYLLABLE SSYAEL
+C355;C355;110A 1164 11B0;C355;110A 1164 11B0; # (썕; 썕; 썕; 썕; 썕; ) HANGUL SYLLABLE SSYAELG
+C356;C356;110A 1164 11B1;C356;110A 1164 11B1; # (썖; 썖; 썖; 썖; 썖; ) HANGUL SYLLABLE SSYAELM
+C357;C357;110A 1164 11B2;C357;110A 1164 11B2; # (썗; 썗; 썗; 썗; 썗; ) HANGUL SYLLABLE SSYAELB
+C358;C358;110A 1164 11B3;C358;110A 1164 11B3; # (썘; 썘; 썘; 썘; 썘; ) HANGUL SYLLABLE SSYAELS
+C359;C359;110A 1164 11B4;C359;110A 1164 11B4; # (썙; 썙; 썙; 썙; 썙; ) HANGUL SYLLABLE SSYAELT
+C35A;C35A;110A 1164 11B5;C35A;110A 1164 11B5; # (썚; 썚; 썚; 썚; 썚; ) HANGUL SYLLABLE SSYAELP
+C35B;C35B;110A 1164 11B6;C35B;110A 1164 11B6; # (썛; 썛; 썛; 썛; 썛; ) HANGUL SYLLABLE SSYAELH
+C35C;C35C;110A 1164 11B7;C35C;110A 1164 11B7; # (썜; 썜; 썜; 썜; 썜; ) HANGUL SYLLABLE SSYAEM
+C35D;C35D;110A 1164 11B8;C35D;110A 1164 11B8; # (썝; 썝; 썝; 썝; 썝; ) HANGUL SYLLABLE SSYAEB
+C35E;C35E;110A 1164 11B9;C35E;110A 1164 11B9; # (썞; 썞; 썞; 썞; 썞; ) HANGUL SYLLABLE SSYAEBS
+C35F;C35F;110A 1164 11BA;C35F;110A 1164 11BA; # (썟; 썟; 썟; 썟; 썟; ) HANGUL SYLLABLE SSYAES
+C360;C360;110A 1164 11BB;C360;110A 1164 11BB; # (썠; 썠; 썠; 썠; 썠; ) HANGUL SYLLABLE SSYAESS
+C361;C361;110A 1164 11BC;C361;110A 1164 11BC; # (썡; 썡; 썡; 썡; 썡; ) HANGUL SYLLABLE SSYAENG
+C362;C362;110A 1164 11BD;C362;110A 1164 11BD; # (썢; 썢; 썢; 썢; 썢; ) HANGUL SYLLABLE SSYAEJ
+C363;C363;110A 1164 11BE;C363;110A 1164 11BE; # (썣; 썣; 썣; 썣; 썣; ) HANGUL SYLLABLE SSYAEC
+C364;C364;110A 1164 11BF;C364;110A 1164 11BF; # (썤; 썤; 썤; 썤; 썤; ) HANGUL SYLLABLE SSYAEK
+C365;C365;110A 1164 11C0;C365;110A 1164 11C0; # (썥; 썥; 썥; 썥; 썥; ) HANGUL SYLLABLE SSYAET
+C366;C366;110A 1164 11C1;C366;110A 1164 11C1; # (썦; 썦; 썦; 썦; 썦; ) HANGUL SYLLABLE SSYAEP
+C367;C367;110A 1164 11C2;C367;110A 1164 11C2; # (썧; 썧; 썧; 썧; 썧; ) HANGUL SYLLABLE SSYAEH
+C368;C368;110A 1165;C368;110A 1165; # (써; 써; 써; 써; 써; ) HANGUL SYLLABLE SSEO
+C369;C369;110A 1165 11A8;C369;110A 1165 11A8; # (썩; 썩; 썩; 썩; 썩; ) HANGUL SYLLABLE SSEOG
+C36A;C36A;110A 1165 11A9;C36A;110A 1165 11A9; # (썪; 썪; 썪; 썪; 썪; ) HANGUL SYLLABLE SSEOGG
+C36B;C36B;110A 1165 11AA;C36B;110A 1165 11AA; # (썫; 썫; 썫; 썫; 썫; ) HANGUL SYLLABLE SSEOGS
+C36C;C36C;110A 1165 11AB;C36C;110A 1165 11AB; # (썬; 썬; 썬; 썬; 썬; ) HANGUL SYLLABLE SSEON
+C36D;C36D;110A 1165 11AC;C36D;110A 1165 11AC; # (썭; 썭; 썭; 썭; 썭; ) HANGUL SYLLABLE SSEONJ
+C36E;C36E;110A 1165 11AD;C36E;110A 1165 11AD; # (썮; 썮; 썮; 썮; 썮; ) HANGUL SYLLABLE SSEONH
+C36F;C36F;110A 1165 11AE;C36F;110A 1165 11AE; # (썯; 썯; 썯; 썯; 썯; ) HANGUL SYLLABLE SSEOD
+C370;C370;110A 1165 11AF;C370;110A 1165 11AF; # (썰; 썰; 썰; 썰; 썰; ) HANGUL SYLLABLE SSEOL
+C371;C371;110A 1165 11B0;C371;110A 1165 11B0; # (썱; 썱; 썱; 썱; 썱; ) HANGUL SYLLABLE SSEOLG
+C372;C372;110A 1165 11B1;C372;110A 1165 11B1; # (썲; 썲; 썲; 썲; 썲; ) HANGUL SYLLABLE SSEOLM
+C373;C373;110A 1165 11B2;C373;110A 1165 11B2; # (썳; 썳; 썳; 썳; 썳; ) HANGUL SYLLABLE SSEOLB
+C374;C374;110A 1165 11B3;C374;110A 1165 11B3; # (썴; 썴; 썴; 썴; 썴; ) HANGUL SYLLABLE SSEOLS
+C375;C375;110A 1165 11B4;C375;110A 1165 11B4; # (썵; 썵; 썵; 썵; 썵; ) HANGUL SYLLABLE SSEOLT
+C376;C376;110A 1165 11B5;C376;110A 1165 11B5; # (썶; 썶; 썶; 썶; 썶; ) HANGUL SYLLABLE SSEOLP
+C377;C377;110A 1165 11B6;C377;110A 1165 11B6; # (썷; 썷; 썷; 썷; 썷; ) HANGUL SYLLABLE SSEOLH
+C378;C378;110A 1165 11B7;C378;110A 1165 11B7; # (썸; 썸; 썸; 썸; 썸; ) HANGUL SYLLABLE SSEOM
+C379;C379;110A 1165 11B8;C379;110A 1165 11B8; # (썹; 썹; 썹; 썹; 썹; ) HANGUL SYLLABLE SSEOB
+C37A;C37A;110A 1165 11B9;C37A;110A 1165 11B9; # (썺; 썺; 썺; 썺; 썺; ) HANGUL SYLLABLE SSEOBS
+C37B;C37B;110A 1165 11BA;C37B;110A 1165 11BA; # (썻; 썻; 썻; 썻; 썻; ) HANGUL SYLLABLE SSEOS
+C37C;C37C;110A 1165 11BB;C37C;110A 1165 11BB; # (썼; 썼; 썼; 썼; 썼; ) HANGUL SYLLABLE SSEOSS
+C37D;C37D;110A 1165 11BC;C37D;110A 1165 11BC; # (썽; 썽; 썽; 썽; 썽; ) HANGUL SYLLABLE SSEONG
+C37E;C37E;110A 1165 11BD;C37E;110A 1165 11BD; # (썾; 썾; 썾; 썾; 썾; ) HANGUL SYLLABLE SSEOJ
+C37F;C37F;110A 1165 11BE;C37F;110A 1165 11BE; # (썿; 썿; 썿; 썿; 썿; ) HANGUL SYLLABLE SSEOC
+C380;C380;110A 1165 11BF;C380;110A 1165 11BF; # (쎀; 쎀; 쎀; 쎀; 쎀; ) HANGUL SYLLABLE SSEOK
+C381;C381;110A 1165 11C0;C381;110A 1165 11C0; # (쎁; 쎁; 쎁; 쎁; 쎁; ) HANGUL SYLLABLE SSEOT
+C382;C382;110A 1165 11C1;C382;110A 1165 11C1; # (쎂; 쎂; 쎂; 쎂; 쎂; ) HANGUL SYLLABLE SSEOP
+C383;C383;110A 1165 11C2;C383;110A 1165 11C2; # (쎃; 쎃; 쎃; 쎃; 쎃; ) HANGUL SYLLABLE SSEOH
+C384;C384;110A 1166;C384;110A 1166; # (쎄; 쎄; 쎄; 쎄; 쎄; ) HANGUL SYLLABLE SSE
+C385;C385;110A 1166 11A8;C385;110A 1166 11A8; # (쎅; 쎅; 쎅; 쎅; 쎅; ) HANGUL SYLLABLE SSEG
+C386;C386;110A 1166 11A9;C386;110A 1166 11A9; # (쎆; 쎆; 쎆; 쎆; 쎆; ) HANGUL SYLLABLE SSEGG
+C387;C387;110A 1166 11AA;C387;110A 1166 11AA; # (쎇; 쎇; 쎇; 쎇; 쎇; ) HANGUL SYLLABLE SSEGS
+C388;C388;110A 1166 11AB;C388;110A 1166 11AB; # (쎈; 쎈; 쎈; 쎈; 쎈; ) HANGUL SYLLABLE SSEN
+C389;C389;110A 1166 11AC;C389;110A 1166 11AC; # (쎉; 쎉; 쎉; 쎉; 쎉; ) HANGUL SYLLABLE SSENJ
+C38A;C38A;110A 1166 11AD;C38A;110A 1166 11AD; # (쎊; 쎊; 쎊; 쎊; 쎊; ) HANGUL SYLLABLE SSENH
+C38B;C38B;110A 1166 11AE;C38B;110A 1166 11AE; # (쎋; 쎋; 쎋; 쎋; 쎋; ) HANGUL SYLLABLE SSED
+C38C;C38C;110A 1166 11AF;C38C;110A 1166 11AF; # (쎌; 쎌; 쎌; 쎌; 쎌; ) HANGUL SYLLABLE SSEL
+C38D;C38D;110A 1166 11B0;C38D;110A 1166 11B0; # (쎍; 쎍; 쎍; 쎍; 쎍; ) HANGUL SYLLABLE SSELG
+C38E;C38E;110A 1166 11B1;C38E;110A 1166 11B1; # (쎎; 쎎; 쎎; 쎎; 쎎; ) HANGUL SYLLABLE SSELM
+C38F;C38F;110A 1166 11B2;C38F;110A 1166 11B2; # (쎏; 쎏; 쎏; 쎏; 쎏; ) HANGUL SYLLABLE SSELB
+C390;C390;110A 1166 11B3;C390;110A 1166 11B3; # (쎐; 쎐; 쎐; 쎐; 쎐; ) HANGUL SYLLABLE SSELS
+C391;C391;110A 1166 11B4;C391;110A 1166 11B4; # (쎑; 쎑; 쎑; 쎑; 쎑; ) HANGUL SYLLABLE SSELT
+C392;C392;110A 1166 11B5;C392;110A 1166 11B5; # (쎒; 쎒; 쎒; 쎒; 쎒; ) HANGUL SYLLABLE SSELP
+C393;C393;110A 1166 11B6;C393;110A 1166 11B6; # (쎓; 쎓; 쎓; 쎓; 쎓; ) HANGUL SYLLABLE SSELH
+C394;C394;110A 1166 11B7;C394;110A 1166 11B7; # (쎔; 쎔; 쎔; 쎔; 쎔; ) HANGUL SYLLABLE SSEM
+C395;C395;110A 1166 11B8;C395;110A 1166 11B8; # (쎕; 쎕; 쎕; 쎕; 쎕; ) HANGUL SYLLABLE SSEB
+C396;C396;110A 1166 11B9;C396;110A 1166 11B9; # (쎖; 쎖; 쎖; 쎖; 쎖; ) HANGUL SYLLABLE SSEBS
+C397;C397;110A 1166 11BA;C397;110A 1166 11BA; # (쎗; 쎗; 쎗; 쎗; 쎗; ) HANGUL SYLLABLE SSES
+C398;C398;110A 1166 11BB;C398;110A 1166 11BB; # (쎘; 쎘; 쎘; 쎘; 쎘; ) HANGUL SYLLABLE SSESS
+C399;C399;110A 1166 11BC;C399;110A 1166 11BC; # (쎙; 쎙; 쎙; 쎙; 쎙; ) HANGUL SYLLABLE SSENG
+C39A;C39A;110A 1166 11BD;C39A;110A 1166 11BD; # (쎚; 쎚; 쎚; 쎚; 쎚; ) HANGUL SYLLABLE SSEJ
+C39B;C39B;110A 1166 11BE;C39B;110A 1166 11BE; # (쎛; 쎛; 쎛; 쎛; 쎛; ) HANGUL SYLLABLE SSEC
+C39C;C39C;110A 1166 11BF;C39C;110A 1166 11BF; # (쎜; 쎜; 쎜; 쎜; 쎜; ) HANGUL SYLLABLE SSEK
+C39D;C39D;110A 1166 11C0;C39D;110A 1166 11C0; # (쎝; 쎝; 쎝; 쎝; 쎝; ) HANGUL SYLLABLE SSET
+C39E;C39E;110A 1166 11C1;C39E;110A 1166 11C1; # (쎞; 쎞; 쎞; 쎞; 쎞; ) HANGUL SYLLABLE SSEP
+C39F;C39F;110A 1166 11C2;C39F;110A 1166 11C2; # (쎟; 쎟; 쎟; 쎟; 쎟; ) HANGUL SYLLABLE SSEH
+C3A0;C3A0;110A 1167;C3A0;110A 1167; # (쎠; 쎠; 쎠; 쎠; 쎠; ) HANGUL SYLLABLE SSYEO
+C3A1;C3A1;110A 1167 11A8;C3A1;110A 1167 11A8; # (쎡; 쎡; 쎡; 쎡; 쎡; ) HANGUL SYLLABLE SSYEOG
+C3A2;C3A2;110A 1167 11A9;C3A2;110A 1167 11A9; # (쎢; 쎢; 쎢; 쎢; 쎢; ) HANGUL SYLLABLE SSYEOGG
+C3A3;C3A3;110A 1167 11AA;C3A3;110A 1167 11AA; # (쎣; 쎣; 쎣; 쎣; 쎣; ) HANGUL SYLLABLE SSYEOGS
+C3A4;C3A4;110A 1167 11AB;C3A4;110A 1167 11AB; # (쎤; 쎤; 쎤; 쎤; 쎤; ) HANGUL SYLLABLE SSYEON
+C3A5;C3A5;110A 1167 11AC;C3A5;110A 1167 11AC; # (쎥; 쎥; 쎥; 쎥; 쎥; ) HANGUL SYLLABLE SSYEONJ
+C3A6;C3A6;110A 1167 11AD;C3A6;110A 1167 11AD; # (쎦; 쎦; 쎦; 쎦; 쎦; ) HANGUL SYLLABLE SSYEONH
+C3A7;C3A7;110A 1167 11AE;C3A7;110A 1167 11AE; # (쎧; 쎧; 쎧; 쎧; 쎧; ) HANGUL SYLLABLE SSYEOD
+C3A8;C3A8;110A 1167 11AF;C3A8;110A 1167 11AF; # (쎨; 쎨; 쎨; 쎨; 쎨; ) HANGUL SYLLABLE SSYEOL
+C3A9;C3A9;110A 1167 11B0;C3A9;110A 1167 11B0; # (쎩; 쎩; 쎩; 쎩; 쎩; ) HANGUL SYLLABLE SSYEOLG
+C3AA;C3AA;110A 1167 11B1;C3AA;110A 1167 11B1; # (쎪; 쎪; 쎪; 쎪; 쎪; ) HANGUL SYLLABLE SSYEOLM
+C3AB;C3AB;110A 1167 11B2;C3AB;110A 1167 11B2; # (쎫; 쎫; 쎫; 쎫; 쎫; ) HANGUL SYLLABLE SSYEOLB
+C3AC;C3AC;110A 1167 11B3;C3AC;110A 1167 11B3; # (쎬; 쎬; 쎬; 쎬; 쎬; ) HANGUL SYLLABLE SSYEOLS
+C3AD;C3AD;110A 1167 11B4;C3AD;110A 1167 11B4; # (쎭; 쎭; 쎭; 쎭; 쎭; ) HANGUL SYLLABLE SSYEOLT
+C3AE;C3AE;110A 1167 11B5;C3AE;110A 1167 11B5; # (쎮; 쎮; 쎮; 쎮; 쎮; ) HANGUL SYLLABLE SSYEOLP
+C3AF;C3AF;110A 1167 11B6;C3AF;110A 1167 11B6; # (쎯; 쎯; 쎯; 쎯; 쎯; ) HANGUL SYLLABLE SSYEOLH
+C3B0;C3B0;110A 1167 11B7;C3B0;110A 1167 11B7; # (쎰; 쎰; 쎰; 쎰; 쎰; ) HANGUL SYLLABLE SSYEOM
+C3B1;C3B1;110A 1167 11B8;C3B1;110A 1167 11B8; # (쎱; 쎱; 쎱; 쎱; 쎱; ) HANGUL SYLLABLE SSYEOB
+C3B2;C3B2;110A 1167 11B9;C3B2;110A 1167 11B9; # (쎲; 쎲; 쎲; 쎲; 쎲; ) HANGUL SYLLABLE SSYEOBS
+C3B3;C3B3;110A 1167 11BA;C3B3;110A 1167 11BA; # (쎳; 쎳; 쎳; 쎳; 쎳; ) HANGUL SYLLABLE SSYEOS
+C3B4;C3B4;110A 1167 11BB;C3B4;110A 1167 11BB; # (쎴; 쎴; 쎴; 쎴; 쎴; ) HANGUL SYLLABLE SSYEOSS
+C3B5;C3B5;110A 1167 11BC;C3B5;110A 1167 11BC; # (쎵; 쎵; 쎵; 쎵; 쎵; ) HANGUL SYLLABLE SSYEONG
+C3B6;C3B6;110A 1167 11BD;C3B6;110A 1167 11BD; # (쎶; 쎶; 쎶; 쎶; 쎶; ) HANGUL SYLLABLE SSYEOJ
+C3B7;C3B7;110A 1167 11BE;C3B7;110A 1167 11BE; # (쎷; 쎷; 쎷; 쎷; 쎷; ) HANGUL SYLLABLE SSYEOC
+C3B8;C3B8;110A 1167 11BF;C3B8;110A 1167 11BF; # (쎸; 쎸; 쎸; 쎸; 쎸; ) HANGUL SYLLABLE SSYEOK
+C3B9;C3B9;110A 1167 11C0;C3B9;110A 1167 11C0; # (쎹; 쎹; 쎹; 쎹; 쎹; ) HANGUL SYLLABLE SSYEOT
+C3BA;C3BA;110A 1167 11C1;C3BA;110A 1167 11C1; # (쎺; 쎺; 쎺; 쎺; 쎺; ) HANGUL SYLLABLE SSYEOP
+C3BB;C3BB;110A 1167 11C2;C3BB;110A 1167 11C2; # (쎻; 쎻; 쎻; 쎻; 쎻; ) HANGUL SYLLABLE SSYEOH
+C3BC;C3BC;110A 1168;C3BC;110A 1168; # (쎼; 쎼; 쎼; 쎼; 쎼; ) HANGUL SYLLABLE SSYE
+C3BD;C3BD;110A 1168 11A8;C3BD;110A 1168 11A8; # (쎽; 쎽; 쎽; 쎽; 쎽; ) HANGUL SYLLABLE SSYEG
+C3BE;C3BE;110A 1168 11A9;C3BE;110A 1168 11A9; # (쎾; 쎾; 쎾; 쎾; 쎾; ) HANGUL SYLLABLE SSYEGG
+C3BF;C3BF;110A 1168 11AA;C3BF;110A 1168 11AA; # (쎿; 쎿; 쎿; 쎿; 쎿; ) HANGUL SYLLABLE SSYEGS
+C3C0;C3C0;110A 1168 11AB;C3C0;110A 1168 11AB; # (쏀; 쏀; 쏀; 쏀; 쏀; ) HANGUL SYLLABLE SSYEN
+C3C1;C3C1;110A 1168 11AC;C3C1;110A 1168 11AC; # (쏁; 쏁; 쏁; 쏁; 쏁; ) HANGUL SYLLABLE SSYENJ
+C3C2;C3C2;110A 1168 11AD;C3C2;110A 1168 11AD; # (쏂; 쏂; 쏂; 쏂; 쏂; ) HANGUL SYLLABLE SSYENH
+C3C3;C3C3;110A 1168 11AE;C3C3;110A 1168 11AE; # (쏃; 쏃; 쏃; 쏃; 쏃; ) HANGUL SYLLABLE SSYED
+C3C4;C3C4;110A 1168 11AF;C3C4;110A 1168 11AF; # (쏄; 쏄; 쏄; 쏄; 쏄; ) HANGUL SYLLABLE SSYEL
+C3C5;C3C5;110A 1168 11B0;C3C5;110A 1168 11B0; # (쏅; 쏅; 쏅; 쏅; 쏅; ) HANGUL SYLLABLE SSYELG
+C3C6;C3C6;110A 1168 11B1;C3C6;110A 1168 11B1; # (쏆; 쏆; 쏆; 쏆; 쏆; ) HANGUL SYLLABLE SSYELM
+C3C7;C3C7;110A 1168 11B2;C3C7;110A 1168 11B2; # (쏇; 쏇; 쏇; 쏇; 쏇; ) HANGUL SYLLABLE SSYELB
+C3C8;C3C8;110A 1168 11B3;C3C8;110A 1168 11B3; # (쏈; 쏈; 쏈; 쏈; 쏈; ) HANGUL SYLLABLE SSYELS
+C3C9;C3C9;110A 1168 11B4;C3C9;110A 1168 11B4; # (쏉; 쏉; 쏉; 쏉; 쏉; ) HANGUL SYLLABLE SSYELT
+C3CA;C3CA;110A 1168 11B5;C3CA;110A 1168 11B5; # (쏊; 쏊; 쏊; 쏊; 쏊; ) HANGUL SYLLABLE SSYELP
+C3CB;C3CB;110A 1168 11B6;C3CB;110A 1168 11B6; # (쏋; 쏋; 쏋; 쏋; 쏋; ) HANGUL SYLLABLE SSYELH
+C3CC;C3CC;110A 1168 11B7;C3CC;110A 1168 11B7; # (쏌; 쏌; 쏌; 쏌; 쏌; ) HANGUL SYLLABLE SSYEM
+C3CD;C3CD;110A 1168 11B8;C3CD;110A 1168 11B8; # (쏍; 쏍; 쏍; 쏍; 쏍; ) HANGUL SYLLABLE SSYEB
+C3CE;C3CE;110A 1168 11B9;C3CE;110A 1168 11B9; # (쏎; 쏎; 쏎; 쏎; 쏎; ) HANGUL SYLLABLE SSYEBS
+C3CF;C3CF;110A 1168 11BA;C3CF;110A 1168 11BA; # (쏏; 쏏; 쏏; 쏏; 쏏; ) HANGUL SYLLABLE SSYES
+C3D0;C3D0;110A 1168 11BB;C3D0;110A 1168 11BB; # (쏐; 쏐; 쏐; 쏐; 쏐; ) HANGUL SYLLABLE SSYESS
+C3D1;C3D1;110A 1168 11BC;C3D1;110A 1168 11BC; # (쏑; 쏑; 쏑; 쏑; 쏑; ) HANGUL SYLLABLE SSYENG
+C3D2;C3D2;110A 1168 11BD;C3D2;110A 1168 11BD; # (쏒; 쏒; 쏒; 쏒; 쏒; ) HANGUL SYLLABLE SSYEJ
+C3D3;C3D3;110A 1168 11BE;C3D3;110A 1168 11BE; # (쏓; 쏓; 쏓; 쏓; 쏓; ) HANGUL SYLLABLE SSYEC
+C3D4;C3D4;110A 1168 11BF;C3D4;110A 1168 11BF; # (쏔; 쏔; 쏔; 쏔; 쏔; ) HANGUL SYLLABLE SSYEK
+C3D5;C3D5;110A 1168 11C0;C3D5;110A 1168 11C0; # (쏕; 쏕; 쏕; 쏕; 쏕; ) HANGUL SYLLABLE SSYET
+C3D6;C3D6;110A 1168 11C1;C3D6;110A 1168 11C1; # (쏖; 쏖; 쏖; 쏖; 쏖; ) HANGUL SYLLABLE SSYEP
+C3D7;C3D7;110A 1168 11C2;C3D7;110A 1168 11C2; # (쏗; 쏗; 쏗; 쏗; 쏗; ) HANGUL SYLLABLE SSYEH
+C3D8;C3D8;110A 1169;C3D8;110A 1169; # (쏘; 쏘; 쏘; 쏘; 쏘; ) HANGUL SYLLABLE SSO
+C3D9;C3D9;110A 1169 11A8;C3D9;110A 1169 11A8; # (쏙; 쏙; 쏙; 쏙; 쏙; ) HANGUL SYLLABLE SSOG
+C3DA;C3DA;110A 1169 11A9;C3DA;110A 1169 11A9; # (쏚; 쏚; 쏚; 쏚; 쏚; ) HANGUL SYLLABLE SSOGG
+C3DB;C3DB;110A 1169 11AA;C3DB;110A 1169 11AA; # (쏛; 쏛; 쏛; 쏛; 쏛; ) HANGUL SYLLABLE SSOGS
+C3DC;C3DC;110A 1169 11AB;C3DC;110A 1169 11AB; # (쏜; 쏜; 쏜; 쏜; 쏜; ) HANGUL SYLLABLE SSON
+C3DD;C3DD;110A 1169 11AC;C3DD;110A 1169 11AC; # (쏝; 쏝; 쏝; 쏝; 쏝; ) HANGUL SYLLABLE SSONJ
+C3DE;C3DE;110A 1169 11AD;C3DE;110A 1169 11AD; # (쏞; 쏞; 쏞; 쏞; 쏞; ) HANGUL SYLLABLE SSONH
+C3DF;C3DF;110A 1169 11AE;C3DF;110A 1169 11AE; # (쏟; 쏟; 쏟; 쏟; 쏟; ) HANGUL SYLLABLE SSOD
+C3E0;C3E0;110A 1169 11AF;C3E0;110A 1169 11AF; # (쏠; 쏠; 쏠; 쏠; 쏠; ) HANGUL SYLLABLE SSOL
+C3E1;C3E1;110A 1169 11B0;C3E1;110A 1169 11B0; # (쏡; 쏡; 쏡; 쏡; 쏡; ) HANGUL SYLLABLE SSOLG
+C3E2;C3E2;110A 1169 11B1;C3E2;110A 1169 11B1; # (쏢; 쏢; 쏢; 쏢; 쏢; ) HANGUL SYLLABLE SSOLM
+C3E3;C3E3;110A 1169 11B2;C3E3;110A 1169 11B2; # (쏣; 쏣; 쏣; 쏣; 쏣; ) HANGUL SYLLABLE SSOLB
+C3E4;C3E4;110A 1169 11B3;C3E4;110A 1169 11B3; # (쏤; 쏤; 쏤; 쏤; 쏤; ) HANGUL SYLLABLE SSOLS
+C3E5;C3E5;110A 1169 11B4;C3E5;110A 1169 11B4; # (쏥; 쏥; 쏥; 쏥; 쏥; ) HANGUL SYLLABLE SSOLT
+C3E6;C3E6;110A 1169 11B5;C3E6;110A 1169 11B5; # (쏦; 쏦; 쏦; 쏦; 쏦; ) HANGUL SYLLABLE SSOLP
+C3E7;C3E7;110A 1169 11B6;C3E7;110A 1169 11B6; # (쏧; 쏧; 쏧; 쏧; 쏧; ) HANGUL SYLLABLE SSOLH
+C3E8;C3E8;110A 1169 11B7;C3E8;110A 1169 11B7; # (쏨; 쏨; 쏨; 쏨; 쏨; ) HANGUL SYLLABLE SSOM
+C3E9;C3E9;110A 1169 11B8;C3E9;110A 1169 11B8; # (쏩; 쏩; 쏩; 쏩; 쏩; ) HANGUL SYLLABLE SSOB
+C3EA;C3EA;110A 1169 11B9;C3EA;110A 1169 11B9; # (쏪; 쏪; 쏪; 쏪; 쏪; ) HANGUL SYLLABLE SSOBS
+C3EB;C3EB;110A 1169 11BA;C3EB;110A 1169 11BA; # (쏫; 쏫; 쏫; 쏫; 쏫; ) HANGUL SYLLABLE SSOS
+C3EC;C3EC;110A 1169 11BB;C3EC;110A 1169 11BB; # (쏬; 쏬; 쏬; 쏬; 쏬; ) HANGUL SYLLABLE SSOSS
+C3ED;C3ED;110A 1169 11BC;C3ED;110A 1169 11BC; # (쏭; 쏭; 쏭; 쏭; 쏭; ) HANGUL SYLLABLE SSONG
+C3EE;C3EE;110A 1169 11BD;C3EE;110A 1169 11BD; # (쏮; 쏮; 쏮; 쏮; 쏮; ) HANGUL SYLLABLE SSOJ
+C3EF;C3EF;110A 1169 11BE;C3EF;110A 1169 11BE; # (쏯; 쏯; 쏯; 쏯; 쏯; ) HANGUL SYLLABLE SSOC
+C3F0;C3F0;110A 1169 11BF;C3F0;110A 1169 11BF; # (쏰; 쏰; 쏰; 쏰; 쏰; ) HANGUL SYLLABLE SSOK
+C3F1;C3F1;110A 1169 11C0;C3F1;110A 1169 11C0; # (쏱; 쏱; 쏱; 쏱; 쏱; ) HANGUL SYLLABLE SSOT
+C3F2;C3F2;110A 1169 11C1;C3F2;110A 1169 11C1; # (쏲; 쏲; 쏲; 쏲; 쏲; ) HANGUL SYLLABLE SSOP
+C3F3;C3F3;110A 1169 11C2;C3F3;110A 1169 11C2; # (쏳; 쏳; 쏳; 쏳; 쏳; ) HANGUL SYLLABLE SSOH
+C3F4;C3F4;110A 116A;C3F4;110A 116A; # (쏴; 쏴; 쏴; 쏴; 쏴; ) HANGUL SYLLABLE SSWA
+C3F5;C3F5;110A 116A 11A8;C3F5;110A 116A 11A8; # (쏵; 쏵; 쏵; 쏵; 쏵; ) HANGUL SYLLABLE SSWAG
+C3F6;C3F6;110A 116A 11A9;C3F6;110A 116A 11A9; # (쏶; 쏶; 쏶; 쏶; 쏶; ) HANGUL SYLLABLE SSWAGG
+C3F7;C3F7;110A 116A 11AA;C3F7;110A 116A 11AA; # (쏷; 쏷; 쏷; 쏷; 쏷; ) HANGUL SYLLABLE SSWAGS
+C3F8;C3F8;110A 116A 11AB;C3F8;110A 116A 11AB; # (쏸; 쏸; 쏸; 쏸; 쏸; ) HANGUL SYLLABLE SSWAN
+C3F9;C3F9;110A 116A 11AC;C3F9;110A 116A 11AC; # (쏹; 쏹; 쏹; 쏹; 쏹; ) HANGUL SYLLABLE SSWANJ
+C3FA;C3FA;110A 116A 11AD;C3FA;110A 116A 11AD; # (쏺; 쏺; 쏺; 쏺; 쏺; ) HANGUL SYLLABLE SSWANH
+C3FB;C3FB;110A 116A 11AE;C3FB;110A 116A 11AE; # (쏻; 쏻; 쏻; 쏻; 쏻; ) HANGUL SYLLABLE SSWAD
+C3FC;C3FC;110A 116A 11AF;C3FC;110A 116A 11AF; # (쏼; 쏼; 쏼; 쏼; 쏼; ) HANGUL SYLLABLE SSWAL
+C3FD;C3FD;110A 116A 11B0;C3FD;110A 116A 11B0; # (쏽; 쏽; 쏽; 쏽; 쏽; ) HANGUL SYLLABLE SSWALG
+C3FE;C3FE;110A 116A 11B1;C3FE;110A 116A 11B1; # (쏾; 쏾; 쏾; 쏾; 쏾; ) HANGUL SYLLABLE SSWALM
+C3FF;C3FF;110A 116A 11B2;C3FF;110A 116A 11B2; # (쏿; 쏿; 쏿; 쏿; 쏿; ) HANGUL SYLLABLE SSWALB
+C400;C400;110A 116A 11B3;C400;110A 116A 11B3; # (쐀; 쐀; 쐀; 쐀; 쐀; ) HANGUL SYLLABLE SSWALS
+C401;C401;110A 116A 11B4;C401;110A 116A 11B4; # (쐁; 쐁; 쐁; 쐁; 쐁; ) HANGUL SYLLABLE SSWALT
+C402;C402;110A 116A 11B5;C402;110A 116A 11B5; # (쐂; 쐂; 쐂; 쐂; 쐂; ) HANGUL SYLLABLE SSWALP
+C403;C403;110A 116A 11B6;C403;110A 116A 11B6; # (쐃; 쐃; 쐃; 쐃; 쐃; ) HANGUL SYLLABLE SSWALH
+C404;C404;110A 116A 11B7;C404;110A 116A 11B7; # (쐄; 쐄; 쐄; 쐄; 쐄; ) HANGUL SYLLABLE SSWAM
+C405;C405;110A 116A 11B8;C405;110A 116A 11B8; # (쐅; 쐅; 쐅; 쐅; 쐅; ) HANGUL SYLLABLE SSWAB
+C406;C406;110A 116A 11B9;C406;110A 116A 11B9; # (쐆; 쐆; 쐆; 쐆; 쐆; ) HANGUL SYLLABLE SSWABS
+C407;C407;110A 116A 11BA;C407;110A 116A 11BA; # (쐇; 쐇; 쐇; 쐇; 쐇; ) HANGUL SYLLABLE SSWAS
+C408;C408;110A 116A 11BB;C408;110A 116A 11BB; # (쐈; 쐈; 쐈; 쐈; 쐈; ) HANGUL SYLLABLE SSWASS
+C409;C409;110A 116A 11BC;C409;110A 116A 11BC; # (쐉; 쐉; 쐉; 쐉; 쐉; ) HANGUL SYLLABLE SSWANG
+C40A;C40A;110A 116A 11BD;C40A;110A 116A 11BD; # (쐊; 쐊; 쐊; 쐊; 쐊; ) HANGUL SYLLABLE SSWAJ
+C40B;C40B;110A 116A 11BE;C40B;110A 116A 11BE; # (쐋; 쐋; 쐋; 쐋; 쐋; ) HANGUL SYLLABLE SSWAC
+C40C;C40C;110A 116A 11BF;C40C;110A 116A 11BF; # (쐌; 쐌; 쐌; 쐌; 쐌; ) HANGUL SYLLABLE SSWAK
+C40D;C40D;110A 116A 11C0;C40D;110A 116A 11C0; # (쐍; 쐍; 쐍; 쐍; 쐍; ) HANGUL SYLLABLE SSWAT
+C40E;C40E;110A 116A 11C1;C40E;110A 116A 11C1; # (쐎; 쐎; 쐎; 쐎; 쐎; ) HANGUL SYLLABLE SSWAP
+C40F;C40F;110A 116A 11C2;C40F;110A 116A 11C2; # (쐏; 쐏; 쐏; 쐏; 쐏; ) HANGUL SYLLABLE SSWAH
+C410;C410;110A 116B;C410;110A 116B; # (쐐; 쐐; 쐐; 쐐; 쐐; ) HANGUL SYLLABLE SSWAE
+C411;C411;110A 116B 11A8;C411;110A 116B 11A8; # (쐑; 쐑; 쐑; 쐑; 쐑; ) HANGUL SYLLABLE SSWAEG
+C412;C412;110A 116B 11A9;C412;110A 116B 11A9; # (쐒; 쐒; 쐒; 쐒; 쐒; ) HANGUL SYLLABLE SSWAEGG
+C413;C413;110A 116B 11AA;C413;110A 116B 11AA; # (쐓; 쐓; 쐓; 쐓; 쐓; ) HANGUL SYLLABLE SSWAEGS
+C414;C414;110A 116B 11AB;C414;110A 116B 11AB; # (쐔; 쐔; 쐔; 쐔; 쐔; ) HANGUL SYLLABLE SSWAEN
+C415;C415;110A 116B 11AC;C415;110A 116B 11AC; # (쐕; 쐕; 쐕; 쐕; 쐕; ) HANGUL SYLLABLE SSWAENJ
+C416;C416;110A 116B 11AD;C416;110A 116B 11AD; # (쐖; 쐖; 쐖; 쐖; 쐖; ) HANGUL SYLLABLE SSWAENH
+C417;C417;110A 116B 11AE;C417;110A 116B 11AE; # (쐗; 쐗; 쐗; 쐗; 쐗; ) HANGUL SYLLABLE SSWAED
+C418;C418;110A 116B 11AF;C418;110A 116B 11AF; # (쐘; 쐘; 쐘; 쐘; 쐘; ) HANGUL SYLLABLE SSWAEL
+C419;C419;110A 116B 11B0;C419;110A 116B 11B0; # (쐙; 쐙; 쐙; 쐙; 쐙; ) HANGUL SYLLABLE SSWAELG
+C41A;C41A;110A 116B 11B1;C41A;110A 116B 11B1; # (쐚; 쐚; 쐚; 쐚; 쐚; ) HANGUL SYLLABLE SSWAELM
+C41B;C41B;110A 116B 11B2;C41B;110A 116B 11B2; # (쐛; 쐛; 쐛; 쐛; 쐛; ) HANGUL SYLLABLE SSWAELB
+C41C;C41C;110A 116B 11B3;C41C;110A 116B 11B3; # (쐜; 쐜; 쐜; 쐜; 쐜; ) HANGUL SYLLABLE SSWAELS
+C41D;C41D;110A 116B 11B4;C41D;110A 116B 11B4; # (쐝; 쐝; 쐝; 쐝; 쐝; ) HANGUL SYLLABLE SSWAELT
+C41E;C41E;110A 116B 11B5;C41E;110A 116B 11B5; # (쐞; 쐞; 쐞; 쐞; 쐞; ) HANGUL SYLLABLE SSWAELP
+C41F;C41F;110A 116B 11B6;C41F;110A 116B 11B6; # (쐟; 쐟; 쐟; 쐟; 쐟; ) HANGUL SYLLABLE SSWAELH
+C420;C420;110A 116B 11B7;C420;110A 116B 11B7; # (쐠; 쐠; 쐠; 쐠; 쐠; ) HANGUL SYLLABLE SSWAEM
+C421;C421;110A 116B 11B8;C421;110A 116B 11B8; # (쐡; 쐡; 쐡; 쐡; 쐡; ) HANGUL SYLLABLE SSWAEB
+C422;C422;110A 116B 11B9;C422;110A 116B 11B9; # (쐢; 쐢; 쐢; 쐢; 쐢; ) HANGUL SYLLABLE SSWAEBS
+C423;C423;110A 116B 11BA;C423;110A 116B 11BA; # (쐣; 쐣; 쐣; 쐣; 쐣; ) HANGUL SYLLABLE SSWAES
+C424;C424;110A 116B 11BB;C424;110A 116B 11BB; # (쐤; 쐤; 쐤; 쐤; 쐤; ) HANGUL SYLLABLE SSWAESS
+C425;C425;110A 116B 11BC;C425;110A 116B 11BC; # (쐥; 쐥; 쐥; 쐥; 쐥; ) HANGUL SYLLABLE SSWAENG
+C426;C426;110A 116B 11BD;C426;110A 116B 11BD; # (쐦; 쐦; 쐦; 쐦; 쐦; ) HANGUL SYLLABLE SSWAEJ
+C427;C427;110A 116B 11BE;C427;110A 116B 11BE; # (쐧; 쐧; 쐧; 쐧; 쐧; ) HANGUL SYLLABLE SSWAEC
+C428;C428;110A 116B 11BF;C428;110A 116B 11BF; # (쐨; 쐨; 쐨; 쐨; 쐨; ) HANGUL SYLLABLE SSWAEK
+C429;C429;110A 116B 11C0;C429;110A 116B 11C0; # (쐩; 쐩; 쐩; 쐩; 쐩; ) HANGUL SYLLABLE SSWAET
+C42A;C42A;110A 116B 11C1;C42A;110A 116B 11C1; # (쐪; 쐪; 쐪; 쐪; 쐪; ) HANGUL SYLLABLE SSWAEP
+C42B;C42B;110A 116B 11C2;C42B;110A 116B 11C2; # (쐫; 쐫; 쐫; 쐫; 쐫; ) HANGUL SYLLABLE SSWAEH
+C42C;C42C;110A 116C;C42C;110A 116C; # (쐬; 쐬; 쐬; 쐬; 쐬; ) HANGUL SYLLABLE SSOE
+C42D;C42D;110A 116C 11A8;C42D;110A 116C 11A8; # (쐭; 쐭; 쐭; 쐭; 쐭; ) HANGUL SYLLABLE SSOEG
+C42E;C42E;110A 116C 11A9;C42E;110A 116C 11A9; # (쐮; 쐮; 쐮; 쐮; 쐮; ) HANGUL SYLLABLE SSOEGG
+C42F;C42F;110A 116C 11AA;C42F;110A 116C 11AA; # (쐯; 쐯; 쐯; 쐯; 쐯; ) HANGUL SYLLABLE SSOEGS
+C430;C430;110A 116C 11AB;C430;110A 116C 11AB; # (쐰; 쐰; 쐰; 쐰; 쐰; ) HANGUL SYLLABLE SSOEN
+C431;C431;110A 116C 11AC;C431;110A 116C 11AC; # (쐱; 쐱; 쐱; 쐱; 쐱; ) HANGUL SYLLABLE SSOENJ
+C432;C432;110A 116C 11AD;C432;110A 116C 11AD; # (쐲; 쐲; 쐲; 쐲; 쐲; ) HANGUL SYLLABLE SSOENH
+C433;C433;110A 116C 11AE;C433;110A 116C 11AE; # (쐳; 쐳; 쐳; 쐳; 쐳; ) HANGUL SYLLABLE SSOED
+C434;C434;110A 116C 11AF;C434;110A 116C 11AF; # (쐴; 쐴; 쐴; 쐴; 쐴; ) HANGUL SYLLABLE SSOEL
+C435;C435;110A 116C 11B0;C435;110A 116C 11B0; # (쐵; 쐵; 쐵; 쐵; 쐵; ) HANGUL SYLLABLE SSOELG
+C436;C436;110A 116C 11B1;C436;110A 116C 11B1; # (쐶; 쐶; 쐶; 쐶; 쐶; ) HANGUL SYLLABLE SSOELM
+C437;C437;110A 116C 11B2;C437;110A 116C 11B2; # (쐷; 쐷; 쐷; 쐷; 쐷; ) HANGUL SYLLABLE SSOELB
+C438;C438;110A 116C 11B3;C438;110A 116C 11B3; # (쐸; 쐸; 쐸; 쐸; 쐸; ) HANGUL SYLLABLE SSOELS
+C439;C439;110A 116C 11B4;C439;110A 116C 11B4; # (쐹; 쐹; 쐹; 쐹; 쐹; ) HANGUL SYLLABLE SSOELT
+C43A;C43A;110A 116C 11B5;C43A;110A 116C 11B5; # (쐺; 쐺; 쐺; 쐺; 쐺; ) HANGUL SYLLABLE SSOELP
+C43B;C43B;110A 116C 11B6;C43B;110A 116C 11B6; # (쐻; 쐻; 쐻; 쐻; 쐻; ) HANGUL SYLLABLE SSOELH
+C43C;C43C;110A 116C 11B7;C43C;110A 116C 11B7; # (쐼; 쐼; 쐼; 쐼; 쐼; ) HANGUL SYLLABLE SSOEM
+C43D;C43D;110A 116C 11B8;C43D;110A 116C 11B8; # (쐽; 쐽; 쐽; 쐽; 쐽; ) HANGUL SYLLABLE SSOEB
+C43E;C43E;110A 116C 11B9;C43E;110A 116C 11B9; # (쐾; 쐾; 쐾; 쐾; 쐾; ) HANGUL SYLLABLE SSOEBS
+C43F;C43F;110A 116C 11BA;C43F;110A 116C 11BA; # (쐿; 쐿; 쐿; 쐿; 쐿; ) HANGUL SYLLABLE SSOES
+C440;C440;110A 116C 11BB;C440;110A 116C 11BB; # (쑀; 쑀; 쑀; 쑀; 쑀; ) HANGUL SYLLABLE SSOESS
+C441;C441;110A 116C 11BC;C441;110A 116C 11BC; # (쑁; 쑁; 쑁; 쑁; 쑁; ) HANGUL SYLLABLE SSOENG
+C442;C442;110A 116C 11BD;C442;110A 116C 11BD; # (쑂; 쑂; 쑂; 쑂; 쑂; ) HANGUL SYLLABLE SSOEJ
+C443;C443;110A 116C 11BE;C443;110A 116C 11BE; # (쑃; 쑃; 쑃; 쑃; 쑃; ) HANGUL SYLLABLE SSOEC
+C444;C444;110A 116C 11BF;C444;110A 116C 11BF; # (쑄; 쑄; 쑄; 쑄; 쑄; ) HANGUL SYLLABLE SSOEK
+C445;C445;110A 116C 11C0;C445;110A 116C 11C0; # (쑅; 쑅; 쑅; 쑅; 쑅; ) HANGUL SYLLABLE SSOET
+C446;C446;110A 116C 11C1;C446;110A 116C 11C1; # (쑆; 쑆; 쑆; 쑆; 쑆; ) HANGUL SYLLABLE SSOEP
+C447;C447;110A 116C 11C2;C447;110A 116C 11C2; # (쑇; 쑇; 쑇; 쑇; 쑇; ) HANGUL SYLLABLE SSOEH
+C448;C448;110A 116D;C448;110A 116D; # (쑈; 쑈; 쑈; 쑈; 쑈; ) HANGUL SYLLABLE SSYO
+C449;C449;110A 116D 11A8;C449;110A 116D 11A8; # (쑉; 쑉; 쑉; 쑉; 쑉; ) HANGUL SYLLABLE SSYOG
+C44A;C44A;110A 116D 11A9;C44A;110A 116D 11A9; # (쑊; 쑊; 쑊; 쑊; 쑊; ) HANGUL SYLLABLE SSYOGG
+C44B;C44B;110A 116D 11AA;C44B;110A 116D 11AA; # (쑋; 쑋; 쑋; 쑋; 쑋; ) HANGUL SYLLABLE SSYOGS
+C44C;C44C;110A 116D 11AB;C44C;110A 116D 11AB; # (쑌; 쑌; 쑌; 쑌; 쑌; ) HANGUL SYLLABLE SSYON
+C44D;C44D;110A 116D 11AC;C44D;110A 116D 11AC; # (쑍; 쑍; 쑍; 쑍; 쑍; ) HANGUL SYLLABLE SSYONJ
+C44E;C44E;110A 116D 11AD;C44E;110A 116D 11AD; # (쑎; 쑎; 쑎; 쑎; 쑎; ) HANGUL SYLLABLE SSYONH
+C44F;C44F;110A 116D 11AE;C44F;110A 116D 11AE; # (쑏; 쑏; 쑏; 쑏; 쑏; ) HANGUL SYLLABLE SSYOD
+C450;C450;110A 116D 11AF;C450;110A 116D 11AF; # (쑐; 쑐; 쑐; 쑐; 쑐; ) HANGUL SYLLABLE SSYOL
+C451;C451;110A 116D 11B0;C451;110A 116D 11B0; # (쑑; 쑑; 쑑; 쑑; 쑑; ) HANGUL SYLLABLE SSYOLG
+C452;C452;110A 116D 11B1;C452;110A 116D 11B1; # (쑒; 쑒; 쑒; 쑒; 쑒; ) HANGUL SYLLABLE SSYOLM
+C453;C453;110A 116D 11B2;C453;110A 116D 11B2; # (쑓; 쑓; 쑓; 쑓; 쑓; ) HANGUL SYLLABLE SSYOLB
+C454;C454;110A 116D 11B3;C454;110A 116D 11B3; # (쑔; 쑔; 쑔; 쑔; 쑔; ) HANGUL SYLLABLE SSYOLS
+C455;C455;110A 116D 11B4;C455;110A 116D 11B4; # (쑕; 쑕; 쑕; 쑕; 쑕; ) HANGUL SYLLABLE SSYOLT
+C456;C456;110A 116D 11B5;C456;110A 116D 11B5; # (쑖; 쑖; 쑖; 쑖; 쑖; ) HANGUL SYLLABLE SSYOLP
+C457;C457;110A 116D 11B6;C457;110A 116D 11B6; # (쑗; 쑗; 쑗; 쑗; 쑗; ) HANGUL SYLLABLE SSYOLH
+C458;C458;110A 116D 11B7;C458;110A 116D 11B7; # (쑘; 쑘; 쑘; 쑘; 쑘; ) HANGUL SYLLABLE SSYOM
+C459;C459;110A 116D 11B8;C459;110A 116D 11B8; # (쑙; 쑙; 쑙; 쑙; 쑙; ) HANGUL SYLLABLE SSYOB
+C45A;C45A;110A 116D 11B9;C45A;110A 116D 11B9; # (쑚; 쑚; 쑚; 쑚; 쑚; ) HANGUL SYLLABLE SSYOBS
+C45B;C45B;110A 116D 11BA;C45B;110A 116D 11BA; # (쑛; 쑛; 쑛; 쑛; 쑛; ) HANGUL SYLLABLE SSYOS
+C45C;C45C;110A 116D 11BB;C45C;110A 116D 11BB; # (쑜; 쑜; 쑜; 쑜; 쑜; ) HANGUL SYLLABLE SSYOSS
+C45D;C45D;110A 116D 11BC;C45D;110A 116D 11BC; # (쑝; 쑝; 쑝; 쑝; 쑝; ) HANGUL SYLLABLE SSYONG
+C45E;C45E;110A 116D 11BD;C45E;110A 116D 11BD; # (쑞; 쑞; 쑞; 쑞; 쑞; ) HANGUL SYLLABLE SSYOJ
+C45F;C45F;110A 116D 11BE;C45F;110A 116D 11BE; # (쑟; 쑟; 쑟; 쑟; 쑟; ) HANGUL SYLLABLE SSYOC
+C460;C460;110A 116D 11BF;C460;110A 116D 11BF; # (쑠; 쑠; 쑠; 쑠; 쑠; ) HANGUL SYLLABLE SSYOK
+C461;C461;110A 116D 11C0;C461;110A 116D 11C0; # (쑡; 쑡; 쑡; 쑡; 쑡; ) HANGUL SYLLABLE SSYOT
+C462;C462;110A 116D 11C1;C462;110A 116D 11C1; # (쑢; 쑢; 쑢; 쑢; 쑢; ) HANGUL SYLLABLE SSYOP
+C463;C463;110A 116D 11C2;C463;110A 116D 11C2; # (쑣; 쑣; 쑣; 쑣; 쑣; ) HANGUL SYLLABLE SSYOH
+C464;C464;110A 116E;C464;110A 116E; # (쑤; 쑤; 쑤; 쑤; 쑤; ) HANGUL SYLLABLE SSU
+C465;C465;110A 116E 11A8;C465;110A 116E 11A8; # (쑥; 쑥; 쑥; 쑥; 쑥; ) HANGUL SYLLABLE SSUG
+C466;C466;110A 116E 11A9;C466;110A 116E 11A9; # (쑦; 쑦; 쑦; 쑦; 쑦; ) HANGUL SYLLABLE SSUGG
+C467;C467;110A 116E 11AA;C467;110A 116E 11AA; # (쑧; 쑧; 쑧; 쑧; 쑧; ) HANGUL SYLLABLE SSUGS
+C468;C468;110A 116E 11AB;C468;110A 116E 11AB; # (쑨; 쑨; 쑨; 쑨; 쑨; ) HANGUL SYLLABLE SSUN
+C469;C469;110A 116E 11AC;C469;110A 116E 11AC; # (쑩; 쑩; 쑩; 쑩; 쑩; ) HANGUL SYLLABLE SSUNJ
+C46A;C46A;110A 116E 11AD;C46A;110A 116E 11AD; # (쑪; 쑪; 쑪; 쑪; 쑪; ) HANGUL SYLLABLE SSUNH
+C46B;C46B;110A 116E 11AE;C46B;110A 116E 11AE; # (쑫; 쑫; 쑫; 쑫; 쑫; ) HANGUL SYLLABLE SSUD
+C46C;C46C;110A 116E 11AF;C46C;110A 116E 11AF; # (쑬; 쑬; 쑬; 쑬; 쑬; ) HANGUL SYLLABLE SSUL
+C46D;C46D;110A 116E 11B0;C46D;110A 116E 11B0; # (쑭; 쑭; 쑭; 쑭; 쑭; ) HANGUL SYLLABLE SSULG
+C46E;C46E;110A 116E 11B1;C46E;110A 116E 11B1; # (쑮; 쑮; 쑮; 쑮; 쑮; ) HANGUL SYLLABLE SSULM
+C46F;C46F;110A 116E 11B2;C46F;110A 116E 11B2; # (쑯; 쑯; 쑯; 쑯; 쑯; ) HANGUL SYLLABLE SSULB
+C470;C470;110A 116E 11B3;C470;110A 116E 11B3; # (쑰; 쑰; 쑰; 쑰; 쑰; ) HANGUL SYLLABLE SSULS
+C471;C471;110A 116E 11B4;C471;110A 116E 11B4; # (쑱; 쑱; 쑱; 쑱; 쑱; ) HANGUL SYLLABLE SSULT
+C472;C472;110A 116E 11B5;C472;110A 116E 11B5; # (쑲; 쑲; 쑲; 쑲; 쑲; ) HANGUL SYLLABLE SSULP
+C473;C473;110A 116E 11B6;C473;110A 116E 11B6; # (쑳; 쑳; 쑳; 쑳; 쑳; ) HANGUL SYLLABLE SSULH
+C474;C474;110A 116E 11B7;C474;110A 116E 11B7; # (쑴; 쑴; 쑴; 쑴; 쑴; ) HANGUL SYLLABLE SSUM
+C475;C475;110A 116E 11B8;C475;110A 116E 11B8; # (쑵; 쑵; 쑵; 쑵; 쑵; ) HANGUL SYLLABLE SSUB
+C476;C476;110A 116E 11B9;C476;110A 116E 11B9; # (쑶; 쑶; 쑶; 쑶; 쑶; ) HANGUL SYLLABLE SSUBS
+C477;C477;110A 116E 11BA;C477;110A 116E 11BA; # (쑷; 쑷; 쑷; 쑷; 쑷; ) HANGUL SYLLABLE SSUS
+C478;C478;110A 116E 11BB;C478;110A 116E 11BB; # (쑸; 쑸; 쑸; 쑸; 쑸; ) HANGUL SYLLABLE SSUSS
+C479;C479;110A 116E 11BC;C479;110A 116E 11BC; # (쑹; 쑹; 쑹; 쑹; 쑹; ) HANGUL SYLLABLE SSUNG
+C47A;C47A;110A 116E 11BD;C47A;110A 116E 11BD; # (쑺; 쑺; 쑺; 쑺; 쑺; ) HANGUL SYLLABLE SSUJ
+C47B;C47B;110A 116E 11BE;C47B;110A 116E 11BE; # (쑻; 쑻; 쑻; 쑻; 쑻; ) HANGUL SYLLABLE SSUC
+C47C;C47C;110A 116E 11BF;C47C;110A 116E 11BF; # (쑼; 쑼; 쑼; 쑼; 쑼; ) HANGUL SYLLABLE SSUK
+C47D;C47D;110A 116E 11C0;C47D;110A 116E 11C0; # (쑽; 쑽; 쑽; 쑽; 쑽; ) HANGUL SYLLABLE SSUT
+C47E;C47E;110A 116E 11C1;C47E;110A 116E 11C1; # (쑾; 쑾; 쑾; 쑾; 쑾; ) HANGUL SYLLABLE SSUP
+C47F;C47F;110A 116E 11C2;C47F;110A 116E 11C2; # (쑿; 쑿; 쑿; 쑿; 쑿; ) HANGUL SYLLABLE SSUH
+C480;C480;110A 116F;C480;110A 116F; # (쒀; 쒀; 쒀; 쒀; 쒀; ) HANGUL SYLLABLE SSWEO
+C481;C481;110A 116F 11A8;C481;110A 116F 11A8; # (쒁; 쒁; 쒁; 쒁; 쒁; ) HANGUL SYLLABLE SSWEOG
+C482;C482;110A 116F 11A9;C482;110A 116F 11A9; # (쒂; 쒂; 쒂; 쒂; 쒂; ) HANGUL SYLLABLE SSWEOGG
+C483;C483;110A 116F 11AA;C483;110A 116F 11AA; # (쒃; 쒃; 쒃; 쒃; 쒃; ) HANGUL SYLLABLE SSWEOGS
+C484;C484;110A 116F 11AB;C484;110A 116F 11AB; # (쒄; 쒄; 쒄; 쒄; 쒄; ) HANGUL SYLLABLE SSWEON
+C485;C485;110A 116F 11AC;C485;110A 116F 11AC; # (쒅; 쒅; 쒅; 쒅; 쒅; ) HANGUL SYLLABLE SSWEONJ
+C486;C486;110A 116F 11AD;C486;110A 116F 11AD; # (쒆; 쒆; 쒆; 쒆; 쒆; ) HANGUL SYLLABLE SSWEONH
+C487;C487;110A 116F 11AE;C487;110A 116F 11AE; # (쒇; 쒇; 쒇; 쒇; 쒇; ) HANGUL SYLLABLE SSWEOD
+C488;C488;110A 116F 11AF;C488;110A 116F 11AF; # (쒈; 쒈; 쒈; 쒈; 쒈; ) HANGUL SYLLABLE SSWEOL
+C489;C489;110A 116F 11B0;C489;110A 116F 11B0; # (쒉; 쒉; 쒉; 쒉; 쒉; ) HANGUL SYLLABLE SSWEOLG
+C48A;C48A;110A 116F 11B1;C48A;110A 116F 11B1; # (쒊; 쒊; 쒊; 쒊; 쒊; ) HANGUL SYLLABLE SSWEOLM
+C48B;C48B;110A 116F 11B2;C48B;110A 116F 11B2; # (쒋; 쒋; 쒋; 쒋; 쒋; ) HANGUL SYLLABLE SSWEOLB
+C48C;C48C;110A 116F 11B3;C48C;110A 116F 11B3; # (쒌; 쒌; 쒌; 쒌; 쒌; ) HANGUL SYLLABLE SSWEOLS
+C48D;C48D;110A 116F 11B4;C48D;110A 116F 11B4; # (쒍; 쒍; 쒍; 쒍; 쒍; ) HANGUL SYLLABLE SSWEOLT
+C48E;C48E;110A 116F 11B5;C48E;110A 116F 11B5; # (쒎; 쒎; 쒎; 쒎; 쒎; ) HANGUL SYLLABLE SSWEOLP
+C48F;C48F;110A 116F 11B6;C48F;110A 116F 11B6; # (쒏; 쒏; 쒏; 쒏; 쒏; ) HANGUL SYLLABLE SSWEOLH
+C490;C490;110A 116F 11B7;C490;110A 116F 11B7; # (쒐; 쒐; 쒐; 쒐; 쒐; ) HANGUL SYLLABLE SSWEOM
+C491;C491;110A 116F 11B8;C491;110A 116F 11B8; # (쒑; 쒑; 쒑; 쒑; 쒑; ) HANGUL SYLLABLE SSWEOB
+C492;C492;110A 116F 11B9;C492;110A 116F 11B9; # (쒒; 쒒; 쒒; 쒒; 쒒; ) HANGUL SYLLABLE SSWEOBS
+C493;C493;110A 116F 11BA;C493;110A 116F 11BA; # (쒓; 쒓; 쒓; 쒓; 쒓; ) HANGUL SYLLABLE SSWEOS
+C494;C494;110A 116F 11BB;C494;110A 116F 11BB; # (쒔; 쒔; 쒔; 쒔; 쒔; ) HANGUL SYLLABLE SSWEOSS
+C495;C495;110A 116F 11BC;C495;110A 116F 11BC; # (쒕; 쒕; 쒕; 쒕; 쒕; ) HANGUL SYLLABLE SSWEONG
+C496;C496;110A 116F 11BD;C496;110A 116F 11BD; # (쒖; 쒖; 쒖; 쒖; 쒖; ) HANGUL SYLLABLE SSWEOJ
+C497;C497;110A 116F 11BE;C497;110A 116F 11BE; # (쒗; 쒗; 쒗; 쒗; 쒗; ) HANGUL SYLLABLE SSWEOC
+C498;C498;110A 116F 11BF;C498;110A 116F 11BF; # (쒘; 쒘; 쒘; 쒘; 쒘; ) HANGUL SYLLABLE SSWEOK
+C499;C499;110A 116F 11C0;C499;110A 116F 11C0; # (쒙; 쒙; 쒙; 쒙; 쒙; ) HANGUL SYLLABLE SSWEOT
+C49A;C49A;110A 116F 11C1;C49A;110A 116F 11C1; # (쒚; 쒚; 쒚; 쒚; 쒚; ) HANGUL SYLLABLE SSWEOP
+C49B;C49B;110A 116F 11C2;C49B;110A 116F 11C2; # (쒛; 쒛; 쒛; 쒛; 쒛; ) HANGUL SYLLABLE SSWEOH
+C49C;C49C;110A 1170;C49C;110A 1170; # (쒜; 쒜; 쒜; 쒜; 쒜; ) HANGUL SYLLABLE SSWE
+C49D;C49D;110A 1170 11A8;C49D;110A 1170 11A8; # (쒝; 쒝; 쒝; 쒝; 쒝; ) HANGUL SYLLABLE SSWEG
+C49E;C49E;110A 1170 11A9;C49E;110A 1170 11A9; # (쒞; 쒞; 쒞; 쒞; 쒞; ) HANGUL SYLLABLE SSWEGG
+C49F;C49F;110A 1170 11AA;C49F;110A 1170 11AA; # (쒟; 쒟; 쒟; 쒟; 쒟; ) HANGUL SYLLABLE SSWEGS
+C4A0;C4A0;110A 1170 11AB;C4A0;110A 1170 11AB; # (쒠; 쒠; 쒠; 쒠; 쒠; ) HANGUL SYLLABLE SSWEN
+C4A1;C4A1;110A 1170 11AC;C4A1;110A 1170 11AC; # (쒡; 쒡; 쒡; 쒡; 쒡; ) HANGUL SYLLABLE SSWENJ
+C4A2;C4A2;110A 1170 11AD;C4A2;110A 1170 11AD; # (쒢; 쒢; 쒢; 쒢; 쒢; ) HANGUL SYLLABLE SSWENH
+C4A3;C4A3;110A 1170 11AE;C4A3;110A 1170 11AE; # (쒣; 쒣; 쒣; 쒣; 쒣; ) HANGUL SYLLABLE SSWED
+C4A4;C4A4;110A 1170 11AF;C4A4;110A 1170 11AF; # (쒤; 쒤; 쒤; 쒤; 쒤; ) HANGUL SYLLABLE SSWEL
+C4A5;C4A5;110A 1170 11B0;C4A5;110A 1170 11B0; # (쒥; 쒥; 쒥; 쒥; 쒥; ) HANGUL SYLLABLE SSWELG
+C4A6;C4A6;110A 1170 11B1;C4A6;110A 1170 11B1; # (쒦; 쒦; 쒦; 쒦; 쒦; ) HANGUL SYLLABLE SSWELM
+C4A7;C4A7;110A 1170 11B2;C4A7;110A 1170 11B2; # (쒧; 쒧; 쒧; 쒧; 쒧; ) HANGUL SYLLABLE SSWELB
+C4A8;C4A8;110A 1170 11B3;C4A8;110A 1170 11B3; # (쒨; 쒨; 쒨; 쒨; 쒨; ) HANGUL SYLLABLE SSWELS
+C4A9;C4A9;110A 1170 11B4;C4A9;110A 1170 11B4; # (쒩; 쒩; 쒩; 쒩; 쒩; ) HANGUL SYLLABLE SSWELT
+C4AA;C4AA;110A 1170 11B5;C4AA;110A 1170 11B5; # (쒪; 쒪; 쒪; 쒪; 쒪; ) HANGUL SYLLABLE SSWELP
+C4AB;C4AB;110A 1170 11B6;C4AB;110A 1170 11B6; # (쒫; 쒫; 쒫; 쒫; 쒫; ) HANGUL SYLLABLE SSWELH
+C4AC;C4AC;110A 1170 11B7;C4AC;110A 1170 11B7; # (쒬; 쒬; 쒬; 쒬; 쒬; ) HANGUL SYLLABLE SSWEM
+C4AD;C4AD;110A 1170 11B8;C4AD;110A 1170 11B8; # (쒭; 쒭; 쒭; 쒭; 쒭; ) HANGUL SYLLABLE SSWEB
+C4AE;C4AE;110A 1170 11B9;C4AE;110A 1170 11B9; # (쒮; 쒮; 쒮; 쒮; 쒮; ) HANGUL SYLLABLE SSWEBS
+C4AF;C4AF;110A 1170 11BA;C4AF;110A 1170 11BA; # (쒯; 쒯; 쒯; 쒯; 쒯; ) HANGUL SYLLABLE SSWES
+C4B0;C4B0;110A 1170 11BB;C4B0;110A 1170 11BB; # (쒰; 쒰; 쒰; 쒰; 쒰; ) HANGUL SYLLABLE SSWESS
+C4B1;C4B1;110A 1170 11BC;C4B1;110A 1170 11BC; # (쒱; 쒱; 쒱; 쒱; 쒱; ) HANGUL SYLLABLE SSWENG
+C4B2;C4B2;110A 1170 11BD;C4B2;110A 1170 11BD; # (쒲; 쒲; 쒲; 쒲; 쒲; ) HANGUL SYLLABLE SSWEJ
+C4B3;C4B3;110A 1170 11BE;C4B3;110A 1170 11BE; # (쒳; 쒳; 쒳; 쒳; 쒳; ) HANGUL SYLLABLE SSWEC
+C4B4;C4B4;110A 1170 11BF;C4B4;110A 1170 11BF; # (쒴; 쒴; 쒴; 쒴; 쒴; ) HANGUL SYLLABLE SSWEK
+C4B5;C4B5;110A 1170 11C0;C4B5;110A 1170 11C0; # (쒵; 쒵; 쒵; 쒵; 쒵; ) HANGUL SYLLABLE SSWET
+C4B6;C4B6;110A 1170 11C1;C4B6;110A 1170 11C1; # (쒶; 쒶; 쒶; 쒶; 쒶; ) HANGUL SYLLABLE SSWEP
+C4B7;C4B7;110A 1170 11C2;C4B7;110A 1170 11C2; # (쒷; 쒷; 쒷; 쒷; 쒷; ) HANGUL SYLLABLE SSWEH
+C4B8;C4B8;110A 1171;C4B8;110A 1171; # (쒸; 쒸; 쒸; 쒸; 쒸; ) HANGUL SYLLABLE SSWI
+C4B9;C4B9;110A 1171 11A8;C4B9;110A 1171 11A8; # (쒹; 쒹; 쒹; 쒹; 쒹; ) HANGUL SYLLABLE SSWIG
+C4BA;C4BA;110A 1171 11A9;C4BA;110A 1171 11A9; # (쒺; 쒺; 쒺; 쒺; 쒺; ) HANGUL SYLLABLE SSWIGG
+C4BB;C4BB;110A 1171 11AA;C4BB;110A 1171 11AA; # (쒻; 쒻; 쒻; 쒻; 쒻; ) HANGUL SYLLABLE SSWIGS
+C4BC;C4BC;110A 1171 11AB;C4BC;110A 1171 11AB; # (쒼; 쒼; 쒼; 쒼; 쒼; ) HANGUL SYLLABLE SSWIN
+C4BD;C4BD;110A 1171 11AC;C4BD;110A 1171 11AC; # (쒽; 쒽; 쒽; 쒽; 쒽; ) HANGUL SYLLABLE SSWINJ
+C4BE;C4BE;110A 1171 11AD;C4BE;110A 1171 11AD; # (쒾; 쒾; 쒾; 쒾; 쒾; ) HANGUL SYLLABLE SSWINH
+C4BF;C4BF;110A 1171 11AE;C4BF;110A 1171 11AE; # (쒿; 쒿; 쒿; 쒿; 쒿; ) HANGUL SYLLABLE SSWID
+C4C0;C4C0;110A 1171 11AF;C4C0;110A 1171 11AF; # (쓀; 쓀; 쓀; 쓀; 쓀; ) HANGUL SYLLABLE SSWIL
+C4C1;C4C1;110A 1171 11B0;C4C1;110A 1171 11B0; # (쓁; 쓁; 쓁; 쓁; 쓁; ) HANGUL SYLLABLE SSWILG
+C4C2;C4C2;110A 1171 11B1;C4C2;110A 1171 11B1; # (쓂; 쓂; 쓂; 쓂; 쓂; ) HANGUL SYLLABLE SSWILM
+C4C3;C4C3;110A 1171 11B2;C4C3;110A 1171 11B2; # (쓃; 쓃; 쓃; 쓃; 쓃; ) HANGUL SYLLABLE SSWILB
+C4C4;C4C4;110A 1171 11B3;C4C4;110A 1171 11B3; # (쓄; 쓄; 쓄; 쓄; 쓄; ) HANGUL SYLLABLE SSWILS
+C4C5;C4C5;110A 1171 11B4;C4C5;110A 1171 11B4; # (쓅; 쓅; 쓅; 쓅; 쓅; ) HANGUL SYLLABLE SSWILT
+C4C6;C4C6;110A 1171 11B5;C4C6;110A 1171 11B5; # (쓆; 쓆; 쓆; 쓆; 쓆; ) HANGUL SYLLABLE SSWILP
+C4C7;C4C7;110A 1171 11B6;C4C7;110A 1171 11B6; # (쓇; 쓇; 쓇; 쓇; 쓇; ) HANGUL SYLLABLE SSWILH
+C4C8;C4C8;110A 1171 11B7;C4C8;110A 1171 11B7; # (쓈; 쓈; 쓈; 쓈; 쓈; ) HANGUL SYLLABLE SSWIM
+C4C9;C4C9;110A 1171 11B8;C4C9;110A 1171 11B8; # (쓉; 쓉; 쓉; 쓉; 쓉; ) HANGUL SYLLABLE SSWIB
+C4CA;C4CA;110A 1171 11B9;C4CA;110A 1171 11B9; # (쓊; 쓊; 쓊; 쓊; 쓊; ) HANGUL SYLLABLE SSWIBS
+C4CB;C4CB;110A 1171 11BA;C4CB;110A 1171 11BA; # (쓋; 쓋; 쓋; 쓋; 쓋; ) HANGUL SYLLABLE SSWIS
+C4CC;C4CC;110A 1171 11BB;C4CC;110A 1171 11BB; # (쓌; 쓌; 쓌; 쓌; 쓌; ) HANGUL SYLLABLE SSWISS
+C4CD;C4CD;110A 1171 11BC;C4CD;110A 1171 11BC; # (쓍; 쓍; 쓍; 쓍; 쓍; ) HANGUL SYLLABLE SSWING
+C4CE;C4CE;110A 1171 11BD;C4CE;110A 1171 11BD; # (쓎; 쓎; 쓎; 쓎; 쓎; ) HANGUL SYLLABLE SSWIJ
+C4CF;C4CF;110A 1171 11BE;C4CF;110A 1171 11BE; # (쓏; 쓏; 쓏; 쓏; 쓏; ) HANGUL SYLLABLE SSWIC
+C4D0;C4D0;110A 1171 11BF;C4D0;110A 1171 11BF; # (쓐; 쓐; 쓐; 쓐; 쓐; ) HANGUL SYLLABLE SSWIK
+C4D1;C4D1;110A 1171 11C0;C4D1;110A 1171 11C0; # (쓑; 쓑; 쓑; 쓑; 쓑; ) HANGUL SYLLABLE SSWIT
+C4D2;C4D2;110A 1171 11C1;C4D2;110A 1171 11C1; # (쓒; 쓒; 쓒; 쓒; 쓒; ) HANGUL SYLLABLE SSWIP
+C4D3;C4D3;110A 1171 11C2;C4D3;110A 1171 11C2; # (쓓; 쓓; 쓓; 쓓; 쓓; ) HANGUL SYLLABLE SSWIH
+C4D4;C4D4;110A 1172;C4D4;110A 1172; # (쓔; 쓔; 쓔; 쓔; 쓔; ) HANGUL SYLLABLE SSYU
+C4D5;C4D5;110A 1172 11A8;C4D5;110A 1172 11A8; # (쓕; 쓕; 쓕; 쓕; 쓕; ) HANGUL SYLLABLE SSYUG
+C4D6;C4D6;110A 1172 11A9;C4D6;110A 1172 11A9; # (쓖; 쓖; 쓖; 쓖; 쓖; ) HANGUL SYLLABLE SSYUGG
+C4D7;C4D7;110A 1172 11AA;C4D7;110A 1172 11AA; # (쓗; 쓗; 쓗; 쓗; 쓗; ) HANGUL SYLLABLE SSYUGS
+C4D8;C4D8;110A 1172 11AB;C4D8;110A 1172 11AB; # (쓘; 쓘; 쓘; 쓘; 쓘; ) HANGUL SYLLABLE SSYUN
+C4D9;C4D9;110A 1172 11AC;C4D9;110A 1172 11AC; # (쓙; 쓙; 쓙; 쓙; 쓙; ) HANGUL SYLLABLE SSYUNJ
+C4DA;C4DA;110A 1172 11AD;C4DA;110A 1172 11AD; # (쓚; 쓚; 쓚; 쓚; 쓚; ) HANGUL SYLLABLE SSYUNH
+C4DB;C4DB;110A 1172 11AE;C4DB;110A 1172 11AE; # (쓛; 쓛; 쓛; 쓛; 쓛; ) HANGUL SYLLABLE SSYUD
+C4DC;C4DC;110A 1172 11AF;C4DC;110A 1172 11AF; # (쓜; 쓜; 쓜; 쓜; 쓜; ) HANGUL SYLLABLE SSYUL
+C4DD;C4DD;110A 1172 11B0;C4DD;110A 1172 11B0; # (쓝; 쓝; 쓝; 쓝; 쓝; ) HANGUL SYLLABLE SSYULG
+C4DE;C4DE;110A 1172 11B1;C4DE;110A 1172 11B1; # (쓞; 쓞; 쓞; 쓞; 쓞; ) HANGUL SYLLABLE SSYULM
+C4DF;C4DF;110A 1172 11B2;C4DF;110A 1172 11B2; # (쓟; 쓟; 쓟; 쓟; 쓟; ) HANGUL SYLLABLE SSYULB
+C4E0;C4E0;110A 1172 11B3;C4E0;110A 1172 11B3; # (쓠; 쓠; 쓠; 쓠; 쓠; ) HANGUL SYLLABLE SSYULS
+C4E1;C4E1;110A 1172 11B4;C4E1;110A 1172 11B4; # (쓡; 쓡; 쓡; 쓡; 쓡; ) HANGUL SYLLABLE SSYULT
+C4E2;C4E2;110A 1172 11B5;C4E2;110A 1172 11B5; # (쓢; 쓢; 쓢; 쓢; 쓢; ) HANGUL SYLLABLE SSYULP
+C4E3;C4E3;110A 1172 11B6;C4E3;110A 1172 11B6; # (쓣; 쓣; 쓣; 쓣; 쓣; ) HANGUL SYLLABLE SSYULH
+C4E4;C4E4;110A 1172 11B7;C4E4;110A 1172 11B7; # (쓤; 쓤; 쓤; 쓤; 쓤; ) HANGUL SYLLABLE SSYUM
+C4E5;C4E5;110A 1172 11B8;C4E5;110A 1172 11B8; # (쓥; 쓥; 쓥; 쓥; 쓥; ) HANGUL SYLLABLE SSYUB
+C4E6;C4E6;110A 1172 11B9;C4E6;110A 1172 11B9; # (쓦; 쓦; 쓦; 쓦; 쓦; ) HANGUL SYLLABLE SSYUBS
+C4E7;C4E7;110A 1172 11BA;C4E7;110A 1172 11BA; # (쓧; 쓧; 쓧; 쓧; 쓧; ) HANGUL SYLLABLE SSYUS
+C4E8;C4E8;110A 1172 11BB;C4E8;110A 1172 11BB; # (쓨; 쓨; 쓨; 쓨; 쓨; ) HANGUL SYLLABLE SSYUSS
+C4E9;C4E9;110A 1172 11BC;C4E9;110A 1172 11BC; # (쓩; 쓩; 쓩; 쓩; 쓩; ) HANGUL SYLLABLE SSYUNG
+C4EA;C4EA;110A 1172 11BD;C4EA;110A 1172 11BD; # (쓪; 쓪; 쓪; 쓪; 쓪; ) HANGUL SYLLABLE SSYUJ
+C4EB;C4EB;110A 1172 11BE;C4EB;110A 1172 11BE; # (쓫; 쓫; 쓫; 쓫; 쓫; ) HANGUL SYLLABLE SSYUC
+C4EC;C4EC;110A 1172 11BF;C4EC;110A 1172 11BF; # (쓬; 쓬; 쓬; 쓬; 쓬; ) HANGUL SYLLABLE SSYUK
+C4ED;C4ED;110A 1172 11C0;C4ED;110A 1172 11C0; # (쓭; 쓭; 쓭; 쓭; 쓭; ) HANGUL SYLLABLE SSYUT
+C4EE;C4EE;110A 1172 11C1;C4EE;110A 1172 11C1; # (쓮; 쓮; 쓮; 쓮; 쓮; ) HANGUL SYLLABLE SSYUP
+C4EF;C4EF;110A 1172 11C2;C4EF;110A 1172 11C2; # (쓯; 쓯; 쓯; 쓯; 쓯; ) HANGUL SYLLABLE SSYUH
+C4F0;C4F0;110A 1173;C4F0;110A 1173; # (쓰; 쓰; 쓰; 쓰; 쓰; ) HANGUL SYLLABLE SSEU
+C4F1;C4F1;110A 1173 11A8;C4F1;110A 1173 11A8; # (쓱; 쓱; 쓱; 쓱; 쓱; ) HANGUL SYLLABLE SSEUG
+C4F2;C4F2;110A 1173 11A9;C4F2;110A 1173 11A9; # (쓲; 쓲; 쓲; 쓲; 쓲; ) HANGUL SYLLABLE SSEUGG
+C4F3;C4F3;110A 1173 11AA;C4F3;110A 1173 11AA; # (쓳; 쓳; 쓳; 쓳; 쓳; ) HANGUL SYLLABLE SSEUGS
+C4F4;C4F4;110A 1173 11AB;C4F4;110A 1173 11AB; # (쓴; 쓴; 쓴; 쓴; 쓴; ) HANGUL SYLLABLE SSEUN
+C4F5;C4F5;110A 1173 11AC;C4F5;110A 1173 11AC; # (쓵; 쓵; 쓵; 쓵; 쓵; ) HANGUL SYLLABLE SSEUNJ
+C4F6;C4F6;110A 1173 11AD;C4F6;110A 1173 11AD; # (쓶; 쓶; 쓶; 쓶; 쓶; ) HANGUL SYLLABLE SSEUNH
+C4F7;C4F7;110A 1173 11AE;C4F7;110A 1173 11AE; # (쓷; 쓷; 쓷; 쓷; 쓷; ) HANGUL SYLLABLE SSEUD
+C4F8;C4F8;110A 1173 11AF;C4F8;110A 1173 11AF; # (쓸; 쓸; 쓸; 쓸; 쓸; ) HANGUL SYLLABLE SSEUL
+C4F9;C4F9;110A 1173 11B0;C4F9;110A 1173 11B0; # (쓹; 쓹; 쓹; 쓹; 쓹; ) HANGUL SYLLABLE SSEULG
+C4FA;C4FA;110A 1173 11B1;C4FA;110A 1173 11B1; # (쓺; 쓺; 쓺; 쓺; 쓺; ) HANGUL SYLLABLE SSEULM
+C4FB;C4FB;110A 1173 11B2;C4FB;110A 1173 11B2; # (쓻; 쓻; 쓻; 쓻; 쓻; ) HANGUL SYLLABLE SSEULB
+C4FC;C4FC;110A 1173 11B3;C4FC;110A 1173 11B3; # (쓼; 쓼; 쓼; 쓼; 쓼; ) HANGUL SYLLABLE SSEULS
+C4FD;C4FD;110A 1173 11B4;C4FD;110A 1173 11B4; # (쓽; 쓽; 쓽; 쓽; 쓽; ) HANGUL SYLLABLE SSEULT
+C4FE;C4FE;110A 1173 11B5;C4FE;110A 1173 11B5; # (쓾; 쓾; 쓾; 쓾; 쓾; ) HANGUL SYLLABLE SSEULP
+C4FF;C4FF;110A 1173 11B6;C4FF;110A 1173 11B6; # (쓿; 쓿; 쓿; 쓿; 쓿; ) HANGUL SYLLABLE SSEULH
+C500;C500;110A 1173 11B7;C500;110A 1173 11B7; # (씀; 씀; 씀; 씀; 씀; ) HANGUL SYLLABLE SSEUM
+C501;C501;110A 1173 11B8;C501;110A 1173 11B8; # (씁; 씁; 씁; 씁; 씁; ) HANGUL SYLLABLE SSEUB
+C502;C502;110A 1173 11B9;C502;110A 1173 11B9; # (씂; 씂; 씂; 씂; 씂; ) HANGUL SYLLABLE SSEUBS
+C503;C503;110A 1173 11BA;C503;110A 1173 11BA; # (씃; 씃; 씃; 씃; 씃; ) HANGUL SYLLABLE SSEUS
+C504;C504;110A 1173 11BB;C504;110A 1173 11BB; # (씄; 씄; 씄; 씄; 씄; ) HANGUL SYLLABLE SSEUSS
+C505;C505;110A 1173 11BC;C505;110A 1173 11BC; # (씅; 씅; 씅; 씅; 씅; ) HANGUL SYLLABLE SSEUNG
+C506;C506;110A 1173 11BD;C506;110A 1173 11BD; # (씆; 씆; 씆; 씆; 씆; ) HANGUL SYLLABLE SSEUJ
+C507;C507;110A 1173 11BE;C507;110A 1173 11BE; # (씇; 씇; 씇; 씇; 씇; ) HANGUL SYLLABLE SSEUC
+C508;C508;110A 1173 11BF;C508;110A 1173 11BF; # (씈; 씈; 씈; 씈; 씈; ) HANGUL SYLLABLE SSEUK
+C509;C509;110A 1173 11C0;C509;110A 1173 11C0; # (씉; 씉; 씉; 씉; 씉; ) HANGUL SYLLABLE SSEUT
+C50A;C50A;110A 1173 11C1;C50A;110A 1173 11C1; # (씊; 씊; 씊; 씊; 씊; ) HANGUL SYLLABLE SSEUP
+C50B;C50B;110A 1173 11C2;C50B;110A 1173 11C2; # (씋; 씋; 씋; 씋; 씋; ) HANGUL SYLLABLE SSEUH
+C50C;C50C;110A 1174;C50C;110A 1174; # (씌; 씌; 씌; 씌; 씌; ) HANGUL SYLLABLE SSYI
+C50D;C50D;110A 1174 11A8;C50D;110A 1174 11A8; # (씍; 씍; 씍; 씍; 씍; ) HANGUL SYLLABLE SSYIG
+C50E;C50E;110A 1174 11A9;C50E;110A 1174 11A9; # (씎; 씎; 씎; 씎; 씎; ) HANGUL SYLLABLE SSYIGG
+C50F;C50F;110A 1174 11AA;C50F;110A 1174 11AA; # (씏; 씏; 씏; 씏; 씏; ) HANGUL SYLLABLE SSYIGS
+C510;C510;110A 1174 11AB;C510;110A 1174 11AB; # (씐; 씐; 씐; 씐; 씐; ) HANGUL SYLLABLE SSYIN
+C511;C511;110A 1174 11AC;C511;110A 1174 11AC; # (씑; 씑; 씑; 씑; 씑; ) HANGUL SYLLABLE SSYINJ
+C512;C512;110A 1174 11AD;C512;110A 1174 11AD; # (씒; 씒; 씒; 씒; 씒; ) HANGUL SYLLABLE SSYINH
+C513;C513;110A 1174 11AE;C513;110A 1174 11AE; # (씓; 씓; 씓; 씓; 씓; ) HANGUL SYLLABLE SSYID
+C514;C514;110A 1174 11AF;C514;110A 1174 11AF; # (씔; 씔; 씔; 씔; 씔; ) HANGUL SYLLABLE SSYIL
+C515;C515;110A 1174 11B0;C515;110A 1174 11B0; # (씕; 씕; 씕; 씕; 씕; ) HANGUL SYLLABLE SSYILG
+C516;C516;110A 1174 11B1;C516;110A 1174 11B1; # (씖; 씖; 씖; 씖; 씖; ) HANGUL SYLLABLE SSYILM
+C517;C517;110A 1174 11B2;C517;110A 1174 11B2; # (씗; 씗; 씗; 씗; 씗; ) HANGUL SYLLABLE SSYILB
+C518;C518;110A 1174 11B3;C518;110A 1174 11B3; # (씘; 씘; 씘; 씘; 씘; ) HANGUL SYLLABLE SSYILS
+C519;C519;110A 1174 11B4;C519;110A 1174 11B4; # (씙; 씙; 씙; 씙; 씙; ) HANGUL SYLLABLE SSYILT
+C51A;C51A;110A 1174 11B5;C51A;110A 1174 11B5; # (씚; 씚; 씚; 씚; 씚; ) HANGUL SYLLABLE SSYILP
+C51B;C51B;110A 1174 11B6;C51B;110A 1174 11B6; # (씛; 씛; 씛; 씛; 씛; ) HANGUL SYLLABLE SSYILH
+C51C;C51C;110A 1174 11B7;C51C;110A 1174 11B7; # (씜; 씜; 씜; 씜; 씜; ) HANGUL SYLLABLE SSYIM
+C51D;C51D;110A 1174 11B8;C51D;110A 1174 11B8; # (씝; 씝; 씝; 씝; 씝; ) HANGUL SYLLABLE SSYIB
+C51E;C51E;110A 1174 11B9;C51E;110A 1174 11B9; # (씞; 씞; 씞; 씞; 씞; ) HANGUL SYLLABLE SSYIBS
+C51F;C51F;110A 1174 11BA;C51F;110A 1174 11BA; # (씟; 씟; 씟; 씟; 씟; ) HANGUL SYLLABLE SSYIS
+C520;C520;110A 1174 11BB;C520;110A 1174 11BB; # (씠; 씠; 씠; 씠; 씠; ) HANGUL SYLLABLE SSYISS
+C521;C521;110A 1174 11BC;C521;110A 1174 11BC; # (씡; 씡; 씡; 씡; 씡; ) HANGUL SYLLABLE SSYING
+C522;C522;110A 1174 11BD;C522;110A 1174 11BD; # (씢; 씢; 씢; 씢; 씢; ) HANGUL SYLLABLE SSYIJ
+C523;C523;110A 1174 11BE;C523;110A 1174 11BE; # (씣; 씣; 씣; 씣; 씣; ) HANGUL SYLLABLE SSYIC
+C524;C524;110A 1174 11BF;C524;110A 1174 11BF; # (씤; 씤; 씤; 씤; 씤; ) HANGUL SYLLABLE SSYIK
+C525;C525;110A 1174 11C0;C525;110A 1174 11C0; # (씥; 씥; 씥; 씥; 씥; ) HANGUL SYLLABLE SSYIT
+C526;C526;110A 1174 11C1;C526;110A 1174 11C1; # (씦; 씦; 씦; 씦; 씦; ) HANGUL SYLLABLE SSYIP
+C527;C527;110A 1174 11C2;C527;110A 1174 11C2; # (씧; 씧; 씧; 씧; 씧; ) HANGUL SYLLABLE SSYIH
+C528;C528;110A 1175;C528;110A 1175; # (씨; 씨; 씨; 씨; 씨; ) HANGUL SYLLABLE SSI
+C529;C529;110A 1175 11A8;C529;110A 1175 11A8; # (씩; 씩; 씩; 씩; 씩; ) HANGUL SYLLABLE SSIG
+C52A;C52A;110A 1175 11A9;C52A;110A 1175 11A9; # (씪; 씪; 씪; 씪; 씪; ) HANGUL SYLLABLE SSIGG
+C52B;C52B;110A 1175 11AA;C52B;110A 1175 11AA; # (씫; 씫; 씫; 씫; 씫; ) HANGUL SYLLABLE SSIGS
+C52C;C52C;110A 1175 11AB;C52C;110A 1175 11AB; # (씬; 씬; 씬; 씬; 씬; ) HANGUL SYLLABLE SSIN
+C52D;C52D;110A 1175 11AC;C52D;110A 1175 11AC; # (씭; 씭; 씭; 씭; 씭; ) HANGUL SYLLABLE SSINJ
+C52E;C52E;110A 1175 11AD;C52E;110A 1175 11AD; # (씮; 씮; 씮; 씮; 씮; ) HANGUL SYLLABLE SSINH
+C52F;C52F;110A 1175 11AE;C52F;110A 1175 11AE; # (씯; 씯; 씯; 씯; 씯; ) HANGUL SYLLABLE SSID
+C530;C530;110A 1175 11AF;C530;110A 1175 11AF; # (씰; 씰; 씰; 씰; 씰; ) HANGUL SYLLABLE SSIL
+C531;C531;110A 1175 11B0;C531;110A 1175 11B0; # (씱; 씱; 씱; 씱; 씱; ) HANGUL SYLLABLE SSILG
+C532;C532;110A 1175 11B1;C532;110A 1175 11B1; # (씲; 씲; 씲; 씲; 씲; ) HANGUL SYLLABLE SSILM
+C533;C533;110A 1175 11B2;C533;110A 1175 11B2; # (씳; 씳; 씳; 씳; 씳; ) HANGUL SYLLABLE SSILB
+C534;C534;110A 1175 11B3;C534;110A 1175 11B3; # (씴; 씴; 씴; 씴; 씴; ) HANGUL SYLLABLE SSILS
+C535;C535;110A 1175 11B4;C535;110A 1175 11B4; # (씵; 씵; 씵; 씵; 씵; ) HANGUL SYLLABLE SSILT
+C536;C536;110A 1175 11B5;C536;110A 1175 11B5; # (씶; 씶; 씶; 씶; 씶; ) HANGUL SYLLABLE SSILP
+C537;C537;110A 1175 11B6;C537;110A 1175 11B6; # (씷; 씷; 씷; 씷; 씷; ) HANGUL SYLLABLE SSILH
+C538;C538;110A 1175 11B7;C538;110A 1175 11B7; # (씸; 씸; 씸; 씸; 씸; ) HANGUL SYLLABLE SSIM
+C539;C539;110A 1175 11B8;C539;110A 1175 11B8; # (씹; 씹; 씹; 씹; 씹; ) HANGUL SYLLABLE SSIB
+C53A;C53A;110A 1175 11B9;C53A;110A 1175 11B9; # (씺; 씺; 씺; 씺; 씺; ) HANGUL SYLLABLE SSIBS
+C53B;C53B;110A 1175 11BA;C53B;110A 1175 11BA; # (씻; 씻; 씻; 씻; 씻; ) HANGUL SYLLABLE SSIS
+C53C;C53C;110A 1175 11BB;C53C;110A 1175 11BB; # (씼; 씼; 씼; 씼; 씼; ) HANGUL SYLLABLE SSISS
+C53D;C53D;110A 1175 11BC;C53D;110A 1175 11BC; # (씽; 씽; 씽; 씽; 씽; ) HANGUL SYLLABLE SSING
+C53E;C53E;110A 1175 11BD;C53E;110A 1175 11BD; # (씾; 씾; 씾; 씾; 씾; ) HANGUL SYLLABLE SSIJ
+C53F;C53F;110A 1175 11BE;C53F;110A 1175 11BE; # (씿; 씿; 씿; 씿; 씿; ) HANGUL SYLLABLE SSIC
+C540;C540;110A 1175 11BF;C540;110A 1175 11BF; # (앀; 앀; 앀; 앀; 앀; ) HANGUL SYLLABLE SSIK
+C541;C541;110A 1175 11C0;C541;110A 1175 11C0; # (앁; 앁; 앁; 앁; 앁; ) HANGUL SYLLABLE SSIT
+C542;C542;110A 1175 11C1;C542;110A 1175 11C1; # (앂; 앂; 앂; 앂; 앂; ) HANGUL SYLLABLE SSIP
+C543;C543;110A 1175 11C2;C543;110A 1175 11C2; # (앃; 앃; 앃; 앃; 앃; ) HANGUL SYLLABLE SSIH
+C544;C544;110B 1161;C544;110B 1161; # (아; 아; 아; 아; 아; ) HANGUL SYLLABLE A
+C545;C545;110B 1161 11A8;C545;110B 1161 11A8; # (악; 악; 악; 악; 악; ) HANGUL SYLLABLE AG
+C546;C546;110B 1161 11A9;C546;110B 1161 11A9; # (앆; 앆; 앆; 앆; 앆; ) HANGUL SYLLABLE AGG
+C547;C547;110B 1161 11AA;C547;110B 1161 11AA; # (앇; 앇; 앇; 앇; 앇; ) HANGUL SYLLABLE AGS
+C548;C548;110B 1161 11AB;C548;110B 1161 11AB; # (안; 안; 안; 안; 안; ) HANGUL SYLLABLE AN
+C549;C549;110B 1161 11AC;C549;110B 1161 11AC; # (앉; 앉; 앉; 앉; 앉; ) HANGUL SYLLABLE ANJ
+C54A;C54A;110B 1161 11AD;C54A;110B 1161 11AD; # (않; 않; 않; 않; 않; ) HANGUL SYLLABLE ANH
+C54B;C54B;110B 1161 11AE;C54B;110B 1161 11AE; # (앋; 앋; 앋; 앋; 앋; ) HANGUL SYLLABLE AD
+C54C;C54C;110B 1161 11AF;C54C;110B 1161 11AF; # (알; 알; 알; 알; 알; ) HANGUL SYLLABLE AL
+C54D;C54D;110B 1161 11B0;C54D;110B 1161 11B0; # (앍; 앍; 앍; 앍; 앍; ) HANGUL SYLLABLE ALG
+C54E;C54E;110B 1161 11B1;C54E;110B 1161 11B1; # (앎; 앎; 앎; 앎; 앎; ) HANGUL SYLLABLE ALM
+C54F;C54F;110B 1161 11B2;C54F;110B 1161 11B2; # (앏; 앏; 앏; 앏; 앏; ) HANGUL SYLLABLE ALB
+C550;C550;110B 1161 11B3;C550;110B 1161 11B3; # (앐; 앐; 앐; 앐; 앐; ) HANGUL SYLLABLE ALS
+C551;C551;110B 1161 11B4;C551;110B 1161 11B4; # (앑; 앑; 앑; 앑; 앑; ) HANGUL SYLLABLE ALT
+C552;C552;110B 1161 11B5;C552;110B 1161 11B5; # (앒; 앒; 앒; 앒; 앒; ) HANGUL SYLLABLE ALP
+C553;C553;110B 1161 11B6;C553;110B 1161 11B6; # (앓; 앓; 앓; 앓; 앓; ) HANGUL SYLLABLE ALH
+C554;C554;110B 1161 11B7;C554;110B 1161 11B7; # (암; 암; 암; 암; 암; ) HANGUL SYLLABLE AM
+C555;C555;110B 1161 11B8;C555;110B 1161 11B8; # (압; 압; 압; 압; 압; ) HANGUL SYLLABLE AB
+C556;C556;110B 1161 11B9;C556;110B 1161 11B9; # (앖; 앖; 앖; 앖; 앖; ) HANGUL SYLLABLE ABS
+C557;C557;110B 1161 11BA;C557;110B 1161 11BA; # (앗; 앗; 앗; 앗; 앗; ) HANGUL SYLLABLE AS
+C558;C558;110B 1161 11BB;C558;110B 1161 11BB; # (았; 았; 았; 았; 았; ) HANGUL SYLLABLE ASS
+C559;C559;110B 1161 11BC;C559;110B 1161 11BC; # (앙; 앙; 앙; 앙; 앙; ) HANGUL SYLLABLE ANG
+C55A;C55A;110B 1161 11BD;C55A;110B 1161 11BD; # (앚; 앚; 앚; 앚; 앚; ) HANGUL SYLLABLE AJ
+C55B;C55B;110B 1161 11BE;C55B;110B 1161 11BE; # (앛; 앛; 앛; 앛; 앛; ) HANGUL SYLLABLE AC
+C55C;C55C;110B 1161 11BF;C55C;110B 1161 11BF; # (앜; 앜; 앜; 앜; 앜; ) HANGUL SYLLABLE AK
+C55D;C55D;110B 1161 11C0;C55D;110B 1161 11C0; # (앝; 앝; 앝; 앝; 앝; ) HANGUL SYLLABLE AT
+C55E;C55E;110B 1161 11C1;C55E;110B 1161 11C1; # (앞; 앞; 앞; 앞; 앞; ) HANGUL SYLLABLE AP
+C55F;C55F;110B 1161 11C2;C55F;110B 1161 11C2; # (앟; 앟; 앟; 앟; 앟; ) HANGUL SYLLABLE AH
+C560;C560;110B 1162;C560;110B 1162; # (애; 애; 애; 애; 애; ) HANGUL SYLLABLE AE
+C561;C561;110B 1162 11A8;C561;110B 1162 11A8; # (액; 액; 액; 액; 액; ) HANGUL SYLLABLE AEG
+C562;C562;110B 1162 11A9;C562;110B 1162 11A9; # (앢; 앢; 앢; 앢; 앢; ) HANGUL SYLLABLE AEGG
+C563;C563;110B 1162 11AA;C563;110B 1162 11AA; # (앣; 앣; 앣; 앣; 앣; ) HANGUL SYLLABLE AEGS
+C564;C564;110B 1162 11AB;C564;110B 1162 11AB; # (앤; 앤; 앤; 앤; 앤; ) HANGUL SYLLABLE AEN
+C565;C565;110B 1162 11AC;C565;110B 1162 11AC; # (앥; 앥; 앥; 앥; 앥; ) HANGUL SYLLABLE AENJ
+C566;C566;110B 1162 11AD;C566;110B 1162 11AD; # (앦; 앦; 앦; 앦; 앦; ) HANGUL SYLLABLE AENH
+C567;C567;110B 1162 11AE;C567;110B 1162 11AE; # (앧; 앧; 앧; 앧; 앧; ) HANGUL SYLLABLE AED
+C568;C568;110B 1162 11AF;C568;110B 1162 11AF; # (앨; 앨; 앨; 앨; 앨; ) HANGUL SYLLABLE AEL
+C569;C569;110B 1162 11B0;C569;110B 1162 11B0; # (앩; 앩; 앩; 앩; 앩; ) HANGUL SYLLABLE AELG
+C56A;C56A;110B 1162 11B1;C56A;110B 1162 11B1; # (앪; 앪; 앪; 앪; 앪; ) HANGUL SYLLABLE AELM
+C56B;C56B;110B 1162 11B2;C56B;110B 1162 11B2; # (앫; 앫; 앫; 앫; 앫; ) HANGUL SYLLABLE AELB
+C56C;C56C;110B 1162 11B3;C56C;110B 1162 11B3; # (앬; 앬; 앬; 앬; 앬; ) HANGUL SYLLABLE AELS
+C56D;C56D;110B 1162 11B4;C56D;110B 1162 11B4; # (앭; 앭; 앭; 앭; 앭; ) HANGUL SYLLABLE AELT
+C56E;C56E;110B 1162 11B5;C56E;110B 1162 11B5; # (앮; 앮; 앮; 앮; 앮; ) HANGUL SYLLABLE AELP
+C56F;C56F;110B 1162 11B6;C56F;110B 1162 11B6; # (앯; 앯; 앯; 앯; 앯; ) HANGUL SYLLABLE AELH
+C570;C570;110B 1162 11B7;C570;110B 1162 11B7; # (앰; 앰; 앰; 앰; 앰; ) HANGUL SYLLABLE AEM
+C571;C571;110B 1162 11B8;C571;110B 1162 11B8; # (앱; 앱; 앱; 앱; 앱; ) HANGUL SYLLABLE AEB
+C572;C572;110B 1162 11B9;C572;110B 1162 11B9; # (앲; 앲; 앲; 앲; 앲; ) HANGUL SYLLABLE AEBS
+C573;C573;110B 1162 11BA;C573;110B 1162 11BA; # (앳; 앳; 앳; 앳; 앳; ) HANGUL SYLLABLE AES
+C574;C574;110B 1162 11BB;C574;110B 1162 11BB; # (앴; 앴; 앴; 앴; 앴; ) HANGUL SYLLABLE AESS
+C575;C575;110B 1162 11BC;C575;110B 1162 11BC; # (앵; 앵; 앵; 앵; 앵; ) HANGUL SYLLABLE AENG
+C576;C576;110B 1162 11BD;C576;110B 1162 11BD; # (앶; 앶; 앶; 앶; 앶; ) HANGUL SYLLABLE AEJ
+C577;C577;110B 1162 11BE;C577;110B 1162 11BE; # (앷; 앷; 앷; 앷; 앷; ) HANGUL SYLLABLE AEC
+C578;C578;110B 1162 11BF;C578;110B 1162 11BF; # (앸; 앸; 앸; 앸; 앸; ) HANGUL SYLLABLE AEK
+C579;C579;110B 1162 11C0;C579;110B 1162 11C0; # (앹; 앹; 앹; 앹; 앹; ) HANGUL SYLLABLE AET
+C57A;C57A;110B 1162 11C1;C57A;110B 1162 11C1; # (앺; 앺; 앺; 앺; 앺; ) HANGUL SYLLABLE AEP
+C57B;C57B;110B 1162 11C2;C57B;110B 1162 11C2; # (앻; 앻; 앻; 앻; 앻; ) HANGUL SYLLABLE AEH
+C57C;C57C;110B 1163;C57C;110B 1163; # (야; 야; 야; 야; 야; ) HANGUL SYLLABLE YA
+C57D;C57D;110B 1163 11A8;C57D;110B 1163 11A8; # (약; 약; 약; 약; 약; ) HANGUL SYLLABLE YAG
+C57E;C57E;110B 1163 11A9;C57E;110B 1163 11A9; # (앾; 앾; 앾; 앾; 앾; ) HANGUL SYLLABLE YAGG
+C57F;C57F;110B 1163 11AA;C57F;110B 1163 11AA; # (앿; 앿; 앿; 앿; 앿; ) HANGUL SYLLABLE YAGS
+C580;C580;110B 1163 11AB;C580;110B 1163 11AB; # (얀; 얀; 얀; 얀; 얀; ) HANGUL SYLLABLE YAN
+C581;C581;110B 1163 11AC;C581;110B 1163 11AC; # (얁; 얁; 얁; 얁; 얁; ) HANGUL SYLLABLE YANJ
+C582;C582;110B 1163 11AD;C582;110B 1163 11AD; # (얂; 얂; 얂; 얂; 얂; ) HANGUL SYLLABLE YANH
+C583;C583;110B 1163 11AE;C583;110B 1163 11AE; # (얃; 얃; 얃; 얃; 얃; ) HANGUL SYLLABLE YAD
+C584;C584;110B 1163 11AF;C584;110B 1163 11AF; # (얄; 얄; 얄; 얄; 얄; ) HANGUL SYLLABLE YAL
+C585;C585;110B 1163 11B0;C585;110B 1163 11B0; # (얅; 얅; 얅; 얅; 얅; ) HANGUL SYLLABLE YALG
+C586;C586;110B 1163 11B1;C586;110B 1163 11B1; # (얆; 얆; 얆; 얆; 얆; ) HANGUL SYLLABLE YALM
+C587;C587;110B 1163 11B2;C587;110B 1163 11B2; # (얇; 얇; 얇; 얇; 얇; ) HANGUL SYLLABLE YALB
+C588;C588;110B 1163 11B3;C588;110B 1163 11B3; # (얈; 얈; 얈; 얈; 얈; ) HANGUL SYLLABLE YALS
+C589;C589;110B 1163 11B4;C589;110B 1163 11B4; # (얉; 얉; 얉; 얉; 얉; ) HANGUL SYLLABLE YALT
+C58A;C58A;110B 1163 11B5;C58A;110B 1163 11B5; # (얊; 얊; 얊; 얊; 얊; ) HANGUL SYLLABLE YALP
+C58B;C58B;110B 1163 11B6;C58B;110B 1163 11B6; # (얋; 얋; 얋; 얋; 얋; ) HANGUL SYLLABLE YALH
+C58C;C58C;110B 1163 11B7;C58C;110B 1163 11B7; # (얌; 얌; 얌; 얌; 얌; ) HANGUL SYLLABLE YAM
+C58D;C58D;110B 1163 11B8;C58D;110B 1163 11B8; # (얍; 얍; 얍; 얍; 얍; ) HANGUL SYLLABLE YAB
+C58E;C58E;110B 1163 11B9;C58E;110B 1163 11B9; # (얎; 얎; 얎; 얎; 얎; ) HANGUL SYLLABLE YABS
+C58F;C58F;110B 1163 11BA;C58F;110B 1163 11BA; # (얏; 얏; 얏; 얏; 얏; ) HANGUL SYLLABLE YAS
+C590;C590;110B 1163 11BB;C590;110B 1163 11BB; # (얐; 얐; 얐; 얐; 얐; ) HANGUL SYLLABLE YASS
+C591;C591;110B 1163 11BC;C591;110B 1163 11BC; # (양; 양; 양; 양; 양; ) HANGUL SYLLABLE YANG
+C592;C592;110B 1163 11BD;C592;110B 1163 11BD; # (얒; 얒; 얒; 얒; 얒; ) HANGUL SYLLABLE YAJ
+C593;C593;110B 1163 11BE;C593;110B 1163 11BE; # (얓; 얓; 얓; 얓; 얓; ) HANGUL SYLLABLE YAC
+C594;C594;110B 1163 11BF;C594;110B 1163 11BF; # (얔; 얔; 얔; 얔; 얔; ) HANGUL SYLLABLE YAK
+C595;C595;110B 1163 11C0;C595;110B 1163 11C0; # (얕; 얕; 얕; 얕; 얕; ) HANGUL SYLLABLE YAT
+C596;C596;110B 1163 11C1;C596;110B 1163 11C1; # (얖; 얖; 얖; 얖; 얖; ) HANGUL SYLLABLE YAP
+C597;C597;110B 1163 11C2;C597;110B 1163 11C2; # (얗; 얗; 얗; 얗; 얗; ) HANGUL SYLLABLE YAH
+C598;C598;110B 1164;C598;110B 1164; # (얘; 얘; 얘; 얘; 얘; ) HANGUL SYLLABLE YAE
+C599;C599;110B 1164 11A8;C599;110B 1164 11A8; # (얙; 얙; 얙; 얙; 얙; ) HANGUL SYLLABLE YAEG
+C59A;C59A;110B 1164 11A9;C59A;110B 1164 11A9; # (얚; 얚; 얚; 얚; 얚; ) HANGUL SYLLABLE YAEGG
+C59B;C59B;110B 1164 11AA;C59B;110B 1164 11AA; # (얛; 얛; 얛; 얛; 얛; ) HANGUL SYLLABLE YAEGS
+C59C;C59C;110B 1164 11AB;C59C;110B 1164 11AB; # (얜; 얜; 얜; 얜; 얜; ) HANGUL SYLLABLE YAEN
+C59D;C59D;110B 1164 11AC;C59D;110B 1164 11AC; # (얝; 얝; 얝; 얝; 얝; ) HANGUL SYLLABLE YAENJ
+C59E;C59E;110B 1164 11AD;C59E;110B 1164 11AD; # (얞; 얞; 얞; 얞; 얞; ) HANGUL SYLLABLE YAENH
+C59F;C59F;110B 1164 11AE;C59F;110B 1164 11AE; # (얟; 얟; 얟; 얟; 얟; ) HANGUL SYLLABLE YAED
+C5A0;C5A0;110B 1164 11AF;C5A0;110B 1164 11AF; # (얠; 얠; 얠; 얠; 얠; ) HANGUL SYLLABLE YAEL
+C5A1;C5A1;110B 1164 11B0;C5A1;110B 1164 11B0; # (얡; 얡; 얡; 얡; 얡; ) HANGUL SYLLABLE YAELG
+C5A2;C5A2;110B 1164 11B1;C5A2;110B 1164 11B1; # (얢; 얢; 얢; 얢; 얢; ) HANGUL SYLLABLE YAELM
+C5A3;C5A3;110B 1164 11B2;C5A3;110B 1164 11B2; # (얣; 얣; 얣; 얣; 얣; ) HANGUL SYLLABLE YAELB
+C5A4;C5A4;110B 1164 11B3;C5A4;110B 1164 11B3; # (얤; 얤; 얤; 얤; 얤; ) HANGUL SYLLABLE YAELS
+C5A5;C5A5;110B 1164 11B4;C5A5;110B 1164 11B4; # (얥; 얥; 얥; 얥; 얥; ) HANGUL SYLLABLE YAELT
+C5A6;C5A6;110B 1164 11B5;C5A6;110B 1164 11B5; # (얦; 얦; 얦; 얦; 얦; ) HANGUL SYLLABLE YAELP
+C5A7;C5A7;110B 1164 11B6;C5A7;110B 1164 11B6; # (얧; 얧; 얧; 얧; 얧; ) HANGUL SYLLABLE YAELH
+C5A8;C5A8;110B 1164 11B7;C5A8;110B 1164 11B7; # (얨; 얨; 얨; 얨; 얨; ) HANGUL SYLLABLE YAEM
+C5A9;C5A9;110B 1164 11B8;C5A9;110B 1164 11B8; # (얩; 얩; 얩; 얩; 얩; ) HANGUL SYLLABLE YAEB
+C5AA;C5AA;110B 1164 11B9;C5AA;110B 1164 11B9; # (얪; 얪; 얪; 얪; 얪; ) HANGUL SYLLABLE YAEBS
+C5AB;C5AB;110B 1164 11BA;C5AB;110B 1164 11BA; # (얫; 얫; 얫; 얫; 얫; ) HANGUL SYLLABLE YAES
+C5AC;C5AC;110B 1164 11BB;C5AC;110B 1164 11BB; # (얬; 얬; 얬; 얬; 얬; ) HANGUL SYLLABLE YAESS
+C5AD;C5AD;110B 1164 11BC;C5AD;110B 1164 11BC; # (얭; 얭; 얭; 얭; 얭; ) HANGUL SYLLABLE YAENG
+C5AE;C5AE;110B 1164 11BD;C5AE;110B 1164 11BD; # (얮; 얮; 얮; 얮; 얮; ) HANGUL SYLLABLE YAEJ
+C5AF;C5AF;110B 1164 11BE;C5AF;110B 1164 11BE; # (얯; 얯; 얯; 얯; 얯; ) HANGUL SYLLABLE YAEC
+C5B0;C5B0;110B 1164 11BF;C5B0;110B 1164 11BF; # (얰; 얰; 얰; 얰; 얰; ) HANGUL SYLLABLE YAEK
+C5B1;C5B1;110B 1164 11C0;C5B1;110B 1164 11C0; # (얱; 얱; 얱; 얱; 얱; ) HANGUL SYLLABLE YAET
+C5B2;C5B2;110B 1164 11C1;C5B2;110B 1164 11C1; # (얲; 얲; 얲; 얲; 얲; ) HANGUL SYLLABLE YAEP
+C5B3;C5B3;110B 1164 11C2;C5B3;110B 1164 11C2; # (얳; 얳; 얳; 얳; 얳; ) HANGUL SYLLABLE YAEH
+C5B4;C5B4;110B 1165;C5B4;110B 1165; # (어; 어; 어; 어; 어; ) HANGUL SYLLABLE EO
+C5B5;C5B5;110B 1165 11A8;C5B5;110B 1165 11A8; # (억; 억; 억; 억; 억; ) HANGUL SYLLABLE EOG
+C5B6;C5B6;110B 1165 11A9;C5B6;110B 1165 11A9; # (얶; 얶; 얶; 얶; 얶; ) HANGUL SYLLABLE EOGG
+C5B7;C5B7;110B 1165 11AA;C5B7;110B 1165 11AA; # (얷; 얷; 얷; 얷; 얷; ) HANGUL SYLLABLE EOGS
+C5B8;C5B8;110B 1165 11AB;C5B8;110B 1165 11AB; # (언; 언; 언; 언; 언; ) HANGUL SYLLABLE EON
+C5B9;C5B9;110B 1165 11AC;C5B9;110B 1165 11AC; # (얹; 얹; 얹; 얹; 얹; ) HANGUL SYLLABLE EONJ
+C5BA;C5BA;110B 1165 11AD;C5BA;110B 1165 11AD; # (얺; 얺; 얺; 얺; 얺; ) HANGUL SYLLABLE EONH
+C5BB;C5BB;110B 1165 11AE;C5BB;110B 1165 11AE; # (얻; 얻; 얻; 얻; 얻; ) HANGUL SYLLABLE EOD
+C5BC;C5BC;110B 1165 11AF;C5BC;110B 1165 11AF; # (얼; 얼; 얼; 얼; 얼; ) HANGUL SYLLABLE EOL
+C5BD;C5BD;110B 1165 11B0;C5BD;110B 1165 11B0; # (얽; 얽; 얽; 얽; 얽; ) HANGUL SYLLABLE EOLG
+C5BE;C5BE;110B 1165 11B1;C5BE;110B 1165 11B1; # (얾; 얾; 얾; 얾; 얾; ) HANGUL SYLLABLE EOLM
+C5BF;C5BF;110B 1165 11B2;C5BF;110B 1165 11B2; # (얿; 얿; 얿; 얿; 얿; ) HANGUL SYLLABLE EOLB
+C5C0;C5C0;110B 1165 11B3;C5C0;110B 1165 11B3; # (엀; 엀; 엀; 엀; 엀; ) HANGUL SYLLABLE EOLS
+C5C1;C5C1;110B 1165 11B4;C5C1;110B 1165 11B4; # (엁; 엁; 엁; 엁; 엁; ) HANGUL SYLLABLE EOLT
+C5C2;C5C2;110B 1165 11B5;C5C2;110B 1165 11B5; # (엂; 엂; 엂; 엂; 엂; ) HANGUL SYLLABLE EOLP
+C5C3;C5C3;110B 1165 11B6;C5C3;110B 1165 11B6; # (엃; 엃; 엃; 엃; 엃; ) HANGUL SYLLABLE EOLH
+C5C4;C5C4;110B 1165 11B7;C5C4;110B 1165 11B7; # (엄; 엄; 엄; 엄; 엄; ) HANGUL SYLLABLE EOM
+C5C5;C5C5;110B 1165 11B8;C5C5;110B 1165 11B8; # (업; 업; 업; 업; 업; ) HANGUL SYLLABLE EOB
+C5C6;C5C6;110B 1165 11B9;C5C6;110B 1165 11B9; # (없; 없; 없; 없; 없; ) HANGUL SYLLABLE EOBS
+C5C7;C5C7;110B 1165 11BA;C5C7;110B 1165 11BA; # (엇; 엇; 엇; 엇; 엇; ) HANGUL SYLLABLE EOS
+C5C8;C5C8;110B 1165 11BB;C5C8;110B 1165 11BB; # (었; 었; 었; 었; 었; ) HANGUL SYLLABLE EOSS
+C5C9;C5C9;110B 1165 11BC;C5C9;110B 1165 11BC; # (엉; 엉; 엉; 엉; 엉; ) HANGUL SYLLABLE EONG
+C5CA;C5CA;110B 1165 11BD;C5CA;110B 1165 11BD; # (엊; 엊; 엊; 엊; 엊; ) HANGUL SYLLABLE EOJ
+C5CB;C5CB;110B 1165 11BE;C5CB;110B 1165 11BE; # (엋; 엋; 엋; 엋; 엋; ) HANGUL SYLLABLE EOC
+C5CC;C5CC;110B 1165 11BF;C5CC;110B 1165 11BF; # (엌; 엌; 엌; 엌; 엌; ) HANGUL SYLLABLE EOK
+C5CD;C5CD;110B 1165 11C0;C5CD;110B 1165 11C0; # (엍; 엍; 엍; 엍; 엍; ) HANGUL SYLLABLE EOT
+C5CE;C5CE;110B 1165 11C1;C5CE;110B 1165 11C1; # (엎; 엎; 엎; 엎; 엎; ) HANGUL SYLLABLE EOP
+C5CF;C5CF;110B 1165 11C2;C5CF;110B 1165 11C2; # (엏; 엏; 엏; 엏; 엏; ) HANGUL SYLLABLE EOH
+C5D0;C5D0;110B 1166;C5D0;110B 1166; # (에; 에; 에; 에; 에; ) HANGUL SYLLABLE E
+C5D1;C5D1;110B 1166 11A8;C5D1;110B 1166 11A8; # (엑; 엑; 엑; 엑; 엑; ) HANGUL SYLLABLE EG
+C5D2;C5D2;110B 1166 11A9;C5D2;110B 1166 11A9; # (엒; 엒; 엒; 엒; 엒; ) HANGUL SYLLABLE EGG
+C5D3;C5D3;110B 1166 11AA;C5D3;110B 1166 11AA; # (엓; 엓; 엓; 엓; 엓; ) HANGUL SYLLABLE EGS
+C5D4;C5D4;110B 1166 11AB;C5D4;110B 1166 11AB; # (엔; 엔; 엔; 엔; 엔; ) HANGUL SYLLABLE EN
+C5D5;C5D5;110B 1166 11AC;C5D5;110B 1166 11AC; # (엕; 엕; 엕; 엕; 엕; ) HANGUL SYLLABLE ENJ
+C5D6;C5D6;110B 1166 11AD;C5D6;110B 1166 11AD; # (엖; 엖; 엖; 엖; 엖; ) HANGUL SYLLABLE ENH
+C5D7;C5D7;110B 1166 11AE;C5D7;110B 1166 11AE; # (엗; 엗; 엗; 엗; 엗; ) HANGUL SYLLABLE ED
+C5D8;C5D8;110B 1166 11AF;C5D8;110B 1166 11AF; # (엘; 엘; 엘; 엘; 엘; ) HANGUL SYLLABLE EL
+C5D9;C5D9;110B 1166 11B0;C5D9;110B 1166 11B0; # (엙; 엙; 엙; 엙; 엙; ) HANGUL SYLLABLE ELG
+C5DA;C5DA;110B 1166 11B1;C5DA;110B 1166 11B1; # (엚; 엚; 엚; 엚; 엚; ) HANGUL SYLLABLE ELM
+C5DB;C5DB;110B 1166 11B2;C5DB;110B 1166 11B2; # (엛; 엛; 엛; 엛; 엛; ) HANGUL SYLLABLE ELB
+C5DC;C5DC;110B 1166 11B3;C5DC;110B 1166 11B3; # (엜; 엜; 엜; 엜; 엜; ) HANGUL SYLLABLE ELS
+C5DD;C5DD;110B 1166 11B4;C5DD;110B 1166 11B4; # (엝; 엝; 엝; 엝; 엝; ) HANGUL SYLLABLE ELT
+C5DE;C5DE;110B 1166 11B5;C5DE;110B 1166 11B5; # (엞; 엞; 엞; 엞; 엞; ) HANGUL SYLLABLE ELP
+C5DF;C5DF;110B 1166 11B6;C5DF;110B 1166 11B6; # (엟; 엟; 엟; 엟; 엟; ) HANGUL SYLLABLE ELH
+C5E0;C5E0;110B 1166 11B7;C5E0;110B 1166 11B7; # (엠; 엠; 엠; 엠; 엠; ) HANGUL SYLLABLE EM
+C5E1;C5E1;110B 1166 11B8;C5E1;110B 1166 11B8; # (엡; 엡; 엡; 엡; 엡; ) HANGUL SYLLABLE EB
+C5E2;C5E2;110B 1166 11B9;C5E2;110B 1166 11B9; # (엢; 엢; 엢; 엢; 엢; ) HANGUL SYLLABLE EBS
+C5E3;C5E3;110B 1166 11BA;C5E3;110B 1166 11BA; # (엣; 엣; 엣; 엣; 엣; ) HANGUL SYLLABLE ES
+C5E4;C5E4;110B 1166 11BB;C5E4;110B 1166 11BB; # (엤; 엤; 엤; 엤; 엤; ) HANGUL SYLLABLE ESS
+C5E5;C5E5;110B 1166 11BC;C5E5;110B 1166 11BC; # (엥; 엥; 엥; 엥; 엥; ) HANGUL SYLLABLE ENG
+C5E6;C5E6;110B 1166 11BD;C5E6;110B 1166 11BD; # (엦; 엦; 엦; 엦; 엦; ) HANGUL SYLLABLE EJ
+C5E7;C5E7;110B 1166 11BE;C5E7;110B 1166 11BE; # (엧; 엧; 엧; 엧; 엧; ) HANGUL SYLLABLE EC
+C5E8;C5E8;110B 1166 11BF;C5E8;110B 1166 11BF; # (엨; 엨; 엨; 엨; 엨; ) HANGUL SYLLABLE EK
+C5E9;C5E9;110B 1166 11C0;C5E9;110B 1166 11C0; # (엩; 엩; 엩; 엩; 엩; ) HANGUL SYLLABLE ET
+C5EA;C5EA;110B 1166 11C1;C5EA;110B 1166 11C1; # (엪; 엪; 엪; 엪; 엪; ) HANGUL SYLLABLE EP
+C5EB;C5EB;110B 1166 11C2;C5EB;110B 1166 11C2; # (엫; 엫; 엫; 엫; 엫; ) HANGUL SYLLABLE EH
+C5EC;C5EC;110B 1167;C5EC;110B 1167; # (여; 여; 여; 여; 여; ) HANGUL SYLLABLE YEO
+C5ED;C5ED;110B 1167 11A8;C5ED;110B 1167 11A8; # (역; 역; 역; 역; 역; ) HANGUL SYLLABLE YEOG
+C5EE;C5EE;110B 1167 11A9;C5EE;110B 1167 11A9; # (엮; 엮; 엮; 엮; 엮; ) HANGUL SYLLABLE YEOGG
+C5EF;C5EF;110B 1167 11AA;C5EF;110B 1167 11AA; # (엯; 엯; 엯; 엯; 엯; ) HANGUL SYLLABLE YEOGS
+C5F0;C5F0;110B 1167 11AB;C5F0;110B 1167 11AB; # (연; 연; 연; 연; 연; ) HANGUL SYLLABLE YEON
+C5F1;C5F1;110B 1167 11AC;C5F1;110B 1167 11AC; # (엱; 엱; 엱; 엱; 엱; ) HANGUL SYLLABLE YEONJ
+C5F2;C5F2;110B 1167 11AD;C5F2;110B 1167 11AD; # (엲; 엲; 엲; 엲; 엲; ) HANGUL SYLLABLE YEONH
+C5F3;C5F3;110B 1167 11AE;C5F3;110B 1167 11AE; # (엳; 엳; 엳; 엳; 엳; ) HANGUL SYLLABLE YEOD
+C5F4;C5F4;110B 1167 11AF;C5F4;110B 1167 11AF; # (열; 열; 열; 열; 열; ) HANGUL SYLLABLE YEOL
+C5F5;C5F5;110B 1167 11B0;C5F5;110B 1167 11B0; # (엵; 엵; 엵; 엵; 엵; ) HANGUL SYLLABLE YEOLG
+C5F6;C5F6;110B 1167 11B1;C5F6;110B 1167 11B1; # (엶; 엶; 엶; 엶; 엶; ) HANGUL SYLLABLE YEOLM
+C5F7;C5F7;110B 1167 11B2;C5F7;110B 1167 11B2; # (엷; 엷; 엷; 엷; 엷; ) HANGUL SYLLABLE YEOLB
+C5F8;C5F8;110B 1167 11B3;C5F8;110B 1167 11B3; # (엸; 엸; 엸; 엸; 엸; ) HANGUL SYLLABLE YEOLS
+C5F9;C5F9;110B 1167 11B4;C5F9;110B 1167 11B4; # (엹; 엹; 엹; 엹; 엹; ) HANGUL SYLLABLE YEOLT
+C5FA;C5FA;110B 1167 11B5;C5FA;110B 1167 11B5; # (엺; 엺; 엺; 엺; 엺; ) HANGUL SYLLABLE YEOLP
+C5FB;C5FB;110B 1167 11B6;C5FB;110B 1167 11B6; # (엻; 엻; 엻; 엻; 엻; ) HANGUL SYLLABLE YEOLH
+C5FC;C5FC;110B 1167 11B7;C5FC;110B 1167 11B7; # (염; 염; 염; 염; 염; ) HANGUL SYLLABLE YEOM
+C5FD;C5FD;110B 1167 11B8;C5FD;110B 1167 11B8; # (엽; 엽; 엽; 엽; 엽; ) HANGUL SYLLABLE YEOB
+C5FE;C5FE;110B 1167 11B9;C5FE;110B 1167 11B9; # (엾; 엾; 엾; 엾; 엾; ) HANGUL SYLLABLE YEOBS
+C5FF;C5FF;110B 1167 11BA;C5FF;110B 1167 11BA; # (엿; 엿; 엿; 엿; 엿; ) HANGUL SYLLABLE YEOS
+C600;C600;110B 1167 11BB;C600;110B 1167 11BB; # (였; 였; 였; 였; 였; ) HANGUL SYLLABLE YEOSS
+C601;C601;110B 1167 11BC;C601;110B 1167 11BC; # (영; 영; 영; 영; 영; ) HANGUL SYLLABLE YEONG
+C602;C602;110B 1167 11BD;C602;110B 1167 11BD; # (옂; 옂; 옂; 옂; 옂; ) HANGUL SYLLABLE YEOJ
+C603;C603;110B 1167 11BE;C603;110B 1167 11BE; # (옃; 옃; 옃; 옃; 옃; ) HANGUL SYLLABLE YEOC
+C604;C604;110B 1167 11BF;C604;110B 1167 11BF; # (옄; 옄; 옄; 옄; 옄; ) HANGUL SYLLABLE YEOK
+C605;C605;110B 1167 11C0;C605;110B 1167 11C0; # (옅; 옅; 옅; 옅; 옅; ) HANGUL SYLLABLE YEOT
+C606;C606;110B 1167 11C1;C606;110B 1167 11C1; # (옆; 옆; 옆; 옆; 옆; ) HANGUL SYLLABLE YEOP
+C607;C607;110B 1167 11C2;C607;110B 1167 11C2; # (옇; 옇; 옇; 옇; 옇; ) HANGUL SYLLABLE YEOH
+C608;C608;110B 1168;C608;110B 1168; # (예; 예; 예; 예; 예; ) HANGUL SYLLABLE YE
+C609;C609;110B 1168 11A8;C609;110B 1168 11A8; # (옉; 옉; 옉; 옉; 옉; ) HANGUL SYLLABLE YEG
+C60A;C60A;110B 1168 11A9;C60A;110B 1168 11A9; # (옊; 옊; 옊; 옊; 옊; ) HANGUL SYLLABLE YEGG
+C60B;C60B;110B 1168 11AA;C60B;110B 1168 11AA; # (옋; 옋; 옋; 옋; 옋; ) HANGUL SYLLABLE YEGS
+C60C;C60C;110B 1168 11AB;C60C;110B 1168 11AB; # (옌; 옌; 옌; 옌; 옌; ) HANGUL SYLLABLE YEN
+C60D;C60D;110B 1168 11AC;C60D;110B 1168 11AC; # (옍; 옍; 옍; 옍; 옍; ) HANGUL SYLLABLE YENJ
+C60E;C60E;110B 1168 11AD;C60E;110B 1168 11AD; # (옎; 옎; 옎; 옎; 옎; ) HANGUL SYLLABLE YENH
+C60F;C60F;110B 1168 11AE;C60F;110B 1168 11AE; # (옏; 옏; 옏; 옏; 옏; ) HANGUL SYLLABLE YED
+C610;C610;110B 1168 11AF;C610;110B 1168 11AF; # (옐; 옐; 옐; 옐; 옐; ) HANGUL SYLLABLE YEL
+C611;C611;110B 1168 11B0;C611;110B 1168 11B0; # (옑; 옑; 옑; 옑; 옑; ) HANGUL SYLLABLE YELG
+C612;C612;110B 1168 11B1;C612;110B 1168 11B1; # (옒; 옒; 옒; 옒; 옒; ) HANGUL SYLLABLE YELM
+C613;C613;110B 1168 11B2;C613;110B 1168 11B2; # (옓; 옓; 옓; 옓; 옓; ) HANGUL SYLLABLE YELB
+C614;C614;110B 1168 11B3;C614;110B 1168 11B3; # (옔; 옔; 옔; 옔; 옔; ) HANGUL SYLLABLE YELS
+C615;C615;110B 1168 11B4;C615;110B 1168 11B4; # (옕; 옕; 옕; 옕; 옕; ) HANGUL SYLLABLE YELT
+C616;C616;110B 1168 11B5;C616;110B 1168 11B5; # (옖; 옖; 옖; 옖; 옖; ) HANGUL SYLLABLE YELP
+C617;C617;110B 1168 11B6;C617;110B 1168 11B6; # (옗; 옗; 옗; 옗; 옗; ) HANGUL SYLLABLE YELH
+C618;C618;110B 1168 11B7;C618;110B 1168 11B7; # (옘; 옘; 옘; 옘; 옘; ) HANGUL SYLLABLE YEM
+C619;C619;110B 1168 11B8;C619;110B 1168 11B8; # (옙; 옙; 옙; 옙; 옙; ) HANGUL SYLLABLE YEB
+C61A;C61A;110B 1168 11B9;C61A;110B 1168 11B9; # (옚; 옚; 옚; 옚; 옚; ) HANGUL SYLLABLE YEBS
+C61B;C61B;110B 1168 11BA;C61B;110B 1168 11BA; # (옛; 옛; 옛; 옛; 옛; ) HANGUL SYLLABLE YES
+C61C;C61C;110B 1168 11BB;C61C;110B 1168 11BB; # (옜; 옜; 옜; 옜; 옜; ) HANGUL SYLLABLE YESS
+C61D;C61D;110B 1168 11BC;C61D;110B 1168 11BC; # (옝; 옝; 옝; 옝; 옝; ) HANGUL SYLLABLE YENG
+C61E;C61E;110B 1168 11BD;C61E;110B 1168 11BD; # (옞; 옞; 옞; 옞; 옞; ) HANGUL SYLLABLE YEJ
+C61F;C61F;110B 1168 11BE;C61F;110B 1168 11BE; # (옟; 옟; 옟; 옟; 옟; ) HANGUL SYLLABLE YEC
+C620;C620;110B 1168 11BF;C620;110B 1168 11BF; # (옠; 옠; 옠; 옠; 옠; ) HANGUL SYLLABLE YEK
+C621;C621;110B 1168 11C0;C621;110B 1168 11C0; # (옡; 옡; 옡; 옡; 옡; ) HANGUL SYLLABLE YET
+C622;C622;110B 1168 11C1;C622;110B 1168 11C1; # (옢; 옢; 옢; 옢; 옢; ) HANGUL SYLLABLE YEP
+C623;C623;110B 1168 11C2;C623;110B 1168 11C2; # (옣; 옣; 옣; 옣; 옣; ) HANGUL SYLLABLE YEH
+C624;C624;110B 1169;C624;110B 1169; # (오; 오; 오; 오; 오; ) HANGUL SYLLABLE O
+C625;C625;110B 1169 11A8;C625;110B 1169 11A8; # (옥; 옥; 옥; 옥; 옥; ) HANGUL SYLLABLE OG
+C626;C626;110B 1169 11A9;C626;110B 1169 11A9; # (옦; 옦; 옦; 옦; 옦; ) HANGUL SYLLABLE OGG
+C627;C627;110B 1169 11AA;C627;110B 1169 11AA; # (옧; 옧; 옧; 옧; 옧; ) HANGUL SYLLABLE OGS
+C628;C628;110B 1169 11AB;C628;110B 1169 11AB; # (온; 온; 온; 온; 온; ) HANGUL SYLLABLE ON
+C629;C629;110B 1169 11AC;C629;110B 1169 11AC; # (옩; 옩; 옩; 옩; 옩; ) HANGUL SYLLABLE ONJ
+C62A;C62A;110B 1169 11AD;C62A;110B 1169 11AD; # (옪; 옪; 옪; 옪; 옪; ) HANGUL SYLLABLE ONH
+C62B;C62B;110B 1169 11AE;C62B;110B 1169 11AE; # (옫; 옫; 옫; 옫; 옫; ) HANGUL SYLLABLE OD
+C62C;C62C;110B 1169 11AF;C62C;110B 1169 11AF; # (올; 올; 올; 올; 올; ) HANGUL SYLLABLE OL
+C62D;C62D;110B 1169 11B0;C62D;110B 1169 11B0; # (옭; 옭; 옭; 옭; 옭; ) HANGUL SYLLABLE OLG
+C62E;C62E;110B 1169 11B1;C62E;110B 1169 11B1; # (옮; 옮; 옮; 옮; 옮; ) HANGUL SYLLABLE OLM
+C62F;C62F;110B 1169 11B2;C62F;110B 1169 11B2; # (옯; 옯; 옯; 옯; 옯; ) HANGUL SYLLABLE OLB
+C630;C630;110B 1169 11B3;C630;110B 1169 11B3; # (옰; 옰; 옰; 옰; 옰; ) HANGUL SYLLABLE OLS
+C631;C631;110B 1169 11B4;C631;110B 1169 11B4; # (옱; 옱; 옱; 옱; 옱; ) HANGUL SYLLABLE OLT
+C632;C632;110B 1169 11B5;C632;110B 1169 11B5; # (옲; 옲; 옲; 옲; 옲; ) HANGUL SYLLABLE OLP
+C633;C633;110B 1169 11B6;C633;110B 1169 11B6; # (옳; 옳; 옳; 옳; 옳; ) HANGUL SYLLABLE OLH
+C634;C634;110B 1169 11B7;C634;110B 1169 11B7; # (옴; 옴; 옴; 옴; 옴; ) HANGUL SYLLABLE OM
+C635;C635;110B 1169 11B8;C635;110B 1169 11B8; # (옵; 옵; 옵; 옵; 옵; ) HANGUL SYLLABLE OB
+C636;C636;110B 1169 11B9;C636;110B 1169 11B9; # (옶; 옶; 옶; 옶; 옶; ) HANGUL SYLLABLE OBS
+C637;C637;110B 1169 11BA;C637;110B 1169 11BA; # (옷; 옷; 옷; 옷; 옷; ) HANGUL SYLLABLE OS
+C638;C638;110B 1169 11BB;C638;110B 1169 11BB; # (옸; 옸; 옸; 옸; 옸; ) HANGUL SYLLABLE OSS
+C639;C639;110B 1169 11BC;C639;110B 1169 11BC; # (옹; 옹; 옹; 옹; 옹; ) HANGUL SYLLABLE ONG
+C63A;C63A;110B 1169 11BD;C63A;110B 1169 11BD; # (옺; 옺; 옺; 옺; 옺; ) HANGUL SYLLABLE OJ
+C63B;C63B;110B 1169 11BE;C63B;110B 1169 11BE; # (옻; 옻; 옻; 옻; 옻; ) HANGUL SYLLABLE OC
+C63C;C63C;110B 1169 11BF;C63C;110B 1169 11BF; # (옼; 옼; 옼; 옼; 옼; ) HANGUL SYLLABLE OK
+C63D;C63D;110B 1169 11C0;C63D;110B 1169 11C0; # (옽; 옽; 옽; 옽; 옽; ) HANGUL SYLLABLE OT
+C63E;C63E;110B 1169 11C1;C63E;110B 1169 11C1; # (옾; 옾; 옾; 옾; 옾; ) HANGUL SYLLABLE OP
+C63F;C63F;110B 1169 11C2;C63F;110B 1169 11C2; # (옿; 옿; 옿; 옿; 옿; ) HANGUL SYLLABLE OH
+C640;C640;110B 116A;C640;110B 116A; # (와; 와; 와; 와; 와; ) HANGUL SYLLABLE WA
+C641;C641;110B 116A 11A8;C641;110B 116A 11A8; # (왁; 왁; 왁; 왁; 왁; ) HANGUL SYLLABLE WAG
+C642;C642;110B 116A 11A9;C642;110B 116A 11A9; # (왂; 왂; 왂; 왂; 왂; ) HANGUL SYLLABLE WAGG
+C643;C643;110B 116A 11AA;C643;110B 116A 11AA; # (왃; 왃; 왃; 왃; 왃; ) HANGUL SYLLABLE WAGS
+C644;C644;110B 116A 11AB;C644;110B 116A 11AB; # (완; 완; 완; 완; 완; ) HANGUL SYLLABLE WAN
+C645;C645;110B 116A 11AC;C645;110B 116A 11AC; # (왅; 왅; 왅; 왅; 왅; ) HANGUL SYLLABLE WANJ
+C646;C646;110B 116A 11AD;C646;110B 116A 11AD; # (왆; 왆; 왆; 왆; 왆; ) HANGUL SYLLABLE WANH
+C647;C647;110B 116A 11AE;C647;110B 116A 11AE; # (왇; 왇; 왇; 왇; 왇; ) HANGUL SYLLABLE WAD
+C648;C648;110B 116A 11AF;C648;110B 116A 11AF; # (왈; 왈; 왈; 왈; 왈; ) HANGUL SYLLABLE WAL
+C649;C649;110B 116A 11B0;C649;110B 116A 11B0; # (왉; 왉; 왉; 왉; 왉; ) HANGUL SYLLABLE WALG
+C64A;C64A;110B 116A 11B1;C64A;110B 116A 11B1; # (왊; 왊; 왊; 왊; 왊; ) HANGUL SYLLABLE WALM
+C64B;C64B;110B 116A 11B2;C64B;110B 116A 11B2; # (왋; 왋; 왋; 왋; 왋; ) HANGUL SYLLABLE WALB
+C64C;C64C;110B 116A 11B3;C64C;110B 116A 11B3; # (왌; 왌; 왌; 왌; 왌; ) HANGUL SYLLABLE WALS
+C64D;C64D;110B 116A 11B4;C64D;110B 116A 11B4; # (왍; 왍; 왍; 왍; 왍; ) HANGUL SYLLABLE WALT
+C64E;C64E;110B 116A 11B5;C64E;110B 116A 11B5; # (왎; 왎; 왎; 왎; 왎; ) HANGUL SYLLABLE WALP
+C64F;C64F;110B 116A 11B6;C64F;110B 116A 11B6; # (왏; 왏; 왏; 왏; 왏; ) HANGUL SYLLABLE WALH
+C650;C650;110B 116A 11B7;C650;110B 116A 11B7; # (왐; 왐; 왐; 왐; 왐; ) HANGUL SYLLABLE WAM
+C651;C651;110B 116A 11B8;C651;110B 116A 11B8; # (왑; 왑; 왑; 왑; 왑; ) HANGUL SYLLABLE WAB
+C652;C652;110B 116A 11B9;C652;110B 116A 11B9; # (왒; 왒; 왒; 왒; 왒; ) HANGUL SYLLABLE WABS
+C653;C653;110B 116A 11BA;C653;110B 116A 11BA; # (왓; 왓; 왓; 왓; 왓; ) HANGUL SYLLABLE WAS
+C654;C654;110B 116A 11BB;C654;110B 116A 11BB; # (왔; 왔; 왔; 왔; 왔; ) HANGUL SYLLABLE WASS
+C655;C655;110B 116A 11BC;C655;110B 116A 11BC; # (왕; 왕; 왕; 왕; 왕; ) HANGUL SYLLABLE WANG
+C656;C656;110B 116A 11BD;C656;110B 116A 11BD; # (왖; 왖; 왖; 왖; 왖; ) HANGUL SYLLABLE WAJ
+C657;C657;110B 116A 11BE;C657;110B 116A 11BE; # (왗; 왗; 왗; 왗; 왗; ) HANGUL SYLLABLE WAC
+C658;C658;110B 116A 11BF;C658;110B 116A 11BF; # (왘; 왘; 왘; 왘; 왘; ) HANGUL SYLLABLE WAK
+C659;C659;110B 116A 11C0;C659;110B 116A 11C0; # (왙; 왙; 왙; 왙; 왙; ) HANGUL SYLLABLE WAT
+C65A;C65A;110B 116A 11C1;C65A;110B 116A 11C1; # (왚; 왚; 왚; 왚; 왚; ) HANGUL SYLLABLE WAP
+C65B;C65B;110B 116A 11C2;C65B;110B 116A 11C2; # (왛; 왛; 왛; 왛; 왛; ) HANGUL SYLLABLE WAH
+C65C;C65C;110B 116B;C65C;110B 116B; # (왜; 왜; 왜; 왜; 왜; ) HANGUL SYLLABLE WAE
+C65D;C65D;110B 116B 11A8;C65D;110B 116B 11A8; # (왝; 왝; 왝; 왝; 왝; ) HANGUL SYLLABLE WAEG
+C65E;C65E;110B 116B 11A9;C65E;110B 116B 11A9; # (왞; 왞; 왞; 왞; 왞; ) HANGUL SYLLABLE WAEGG
+C65F;C65F;110B 116B 11AA;C65F;110B 116B 11AA; # (왟; 왟; 왟; 왟; 왟; ) HANGUL SYLLABLE WAEGS
+C660;C660;110B 116B 11AB;C660;110B 116B 11AB; # (왠; 왠; 왠; 왠; 왠; ) HANGUL SYLLABLE WAEN
+C661;C661;110B 116B 11AC;C661;110B 116B 11AC; # (왡; 왡; 왡; 왡; 왡; ) HANGUL SYLLABLE WAENJ
+C662;C662;110B 116B 11AD;C662;110B 116B 11AD; # (왢; 왢; 왢; 왢; 왢; ) HANGUL SYLLABLE WAENH
+C663;C663;110B 116B 11AE;C663;110B 116B 11AE; # (왣; 왣; 왣; 왣; 왣; ) HANGUL SYLLABLE WAED
+C664;C664;110B 116B 11AF;C664;110B 116B 11AF; # (왤; 왤; 왤; 왤; 왤; ) HANGUL SYLLABLE WAEL
+C665;C665;110B 116B 11B0;C665;110B 116B 11B0; # (왥; 왥; 왥; 왥; 왥; ) HANGUL SYLLABLE WAELG
+C666;C666;110B 116B 11B1;C666;110B 116B 11B1; # (왦; 왦; 왦; 왦; 왦; ) HANGUL SYLLABLE WAELM
+C667;C667;110B 116B 11B2;C667;110B 116B 11B2; # (왧; 왧; 왧; 왧; 왧; ) HANGUL SYLLABLE WAELB
+C668;C668;110B 116B 11B3;C668;110B 116B 11B3; # (왨; 왨; 왨; 왨; 왨; ) HANGUL SYLLABLE WAELS
+C669;C669;110B 116B 11B4;C669;110B 116B 11B4; # (왩; 왩; 왩; 왩; 왩; ) HANGUL SYLLABLE WAELT
+C66A;C66A;110B 116B 11B5;C66A;110B 116B 11B5; # (왪; 왪; 왪; 왪; 왪; ) HANGUL SYLLABLE WAELP
+C66B;C66B;110B 116B 11B6;C66B;110B 116B 11B6; # (왫; 왫; 왫; 왫; 왫; ) HANGUL SYLLABLE WAELH
+C66C;C66C;110B 116B 11B7;C66C;110B 116B 11B7; # (왬; 왬; 왬; 왬; 왬; ) HANGUL SYLLABLE WAEM
+C66D;C66D;110B 116B 11B8;C66D;110B 116B 11B8; # (왭; 왭; 왭; 왭; 왭; ) HANGUL SYLLABLE WAEB
+C66E;C66E;110B 116B 11B9;C66E;110B 116B 11B9; # (왮; 왮; 왮; 왮; 왮; ) HANGUL SYLLABLE WAEBS
+C66F;C66F;110B 116B 11BA;C66F;110B 116B 11BA; # (왯; 왯; 왯; 왯; 왯; ) HANGUL SYLLABLE WAES
+C670;C670;110B 116B 11BB;C670;110B 116B 11BB; # (왰; 왰; 왰; 왰; 왰; ) HANGUL SYLLABLE WAESS
+C671;C671;110B 116B 11BC;C671;110B 116B 11BC; # (왱; 왱; 왱; 왱; 왱; ) HANGUL SYLLABLE WAENG
+C672;C672;110B 116B 11BD;C672;110B 116B 11BD; # (왲; 왲; 왲; 왲; 왲; ) HANGUL SYLLABLE WAEJ
+C673;C673;110B 116B 11BE;C673;110B 116B 11BE; # (왳; 왳; 왳; 왳; 왳; ) HANGUL SYLLABLE WAEC
+C674;C674;110B 116B 11BF;C674;110B 116B 11BF; # (왴; 왴; 왴; 왴; 왴; ) HANGUL SYLLABLE WAEK
+C675;C675;110B 116B 11C0;C675;110B 116B 11C0; # (왵; 왵; 왵; 왵; 왵; ) HANGUL SYLLABLE WAET
+C676;C676;110B 116B 11C1;C676;110B 116B 11C1; # (왶; 왶; 왶; 왶; 왶; ) HANGUL SYLLABLE WAEP
+C677;C677;110B 116B 11C2;C677;110B 116B 11C2; # (왷; 왷; 왷; 왷; 왷; ) HANGUL SYLLABLE WAEH
+C678;C678;110B 116C;C678;110B 116C; # (외; 외; 외; 외; 외; ) HANGUL SYLLABLE OE
+C679;C679;110B 116C 11A8;C679;110B 116C 11A8; # (왹; 왹; 왹; 왹; 왹; ) HANGUL SYLLABLE OEG
+C67A;C67A;110B 116C 11A9;C67A;110B 116C 11A9; # (왺; 왺; 왺; 왺; 왺; ) HANGUL SYLLABLE OEGG
+C67B;C67B;110B 116C 11AA;C67B;110B 116C 11AA; # (왻; 왻; 왻; 왻; 왻; ) HANGUL SYLLABLE OEGS
+C67C;C67C;110B 116C 11AB;C67C;110B 116C 11AB; # (왼; 왼; 왼; 왼; 왼; ) HANGUL SYLLABLE OEN
+C67D;C67D;110B 116C 11AC;C67D;110B 116C 11AC; # (왽; 왽; 왽; 왽; 왽; ) HANGUL SYLLABLE OENJ
+C67E;C67E;110B 116C 11AD;C67E;110B 116C 11AD; # (왾; 왾; 왾; 왾; 왾; ) HANGUL SYLLABLE OENH
+C67F;C67F;110B 116C 11AE;C67F;110B 116C 11AE; # (왿; 왿; 왿; 왿; 왿; ) HANGUL SYLLABLE OED
+C680;C680;110B 116C 11AF;C680;110B 116C 11AF; # (욀; 욀; 욀; 욀; 욀; ) HANGUL SYLLABLE OEL
+C681;C681;110B 116C 11B0;C681;110B 116C 11B0; # (욁; 욁; 욁; 욁; 욁; ) HANGUL SYLLABLE OELG
+C682;C682;110B 116C 11B1;C682;110B 116C 11B1; # (욂; 욂; 욂; 욂; 욂; ) HANGUL SYLLABLE OELM
+C683;C683;110B 116C 11B2;C683;110B 116C 11B2; # (욃; 욃; 욃; 욃; 욃; ) HANGUL SYLLABLE OELB
+C684;C684;110B 116C 11B3;C684;110B 116C 11B3; # (욄; 욄; 욄; 욄; 욄; ) HANGUL SYLLABLE OELS
+C685;C685;110B 116C 11B4;C685;110B 116C 11B4; # (욅; 욅; 욅; 욅; 욅; ) HANGUL SYLLABLE OELT
+C686;C686;110B 116C 11B5;C686;110B 116C 11B5; # (욆; 욆; 욆; 욆; 욆; ) HANGUL SYLLABLE OELP
+C687;C687;110B 116C 11B6;C687;110B 116C 11B6; # (욇; 욇; 욇; 욇; 욇; ) HANGUL SYLLABLE OELH
+C688;C688;110B 116C 11B7;C688;110B 116C 11B7; # (욈; 욈; 욈; 욈; 욈; ) HANGUL SYLLABLE OEM
+C689;C689;110B 116C 11B8;C689;110B 116C 11B8; # (욉; 욉; 욉; 욉; 욉; ) HANGUL SYLLABLE OEB
+C68A;C68A;110B 116C 11B9;C68A;110B 116C 11B9; # (욊; 욊; 욊; 욊; 욊; ) HANGUL SYLLABLE OEBS
+C68B;C68B;110B 116C 11BA;C68B;110B 116C 11BA; # (욋; 욋; 욋; 욋; 욋; ) HANGUL SYLLABLE OES
+C68C;C68C;110B 116C 11BB;C68C;110B 116C 11BB; # (욌; 욌; 욌; 욌; 욌; ) HANGUL SYLLABLE OESS
+C68D;C68D;110B 116C 11BC;C68D;110B 116C 11BC; # (욍; 욍; 욍; 욍; 욍; ) HANGUL SYLLABLE OENG
+C68E;C68E;110B 116C 11BD;C68E;110B 116C 11BD; # (욎; 욎; 욎; 욎; 욎; ) HANGUL SYLLABLE OEJ
+C68F;C68F;110B 116C 11BE;C68F;110B 116C 11BE; # (욏; 욏; 욏; 욏; 욏; ) HANGUL SYLLABLE OEC
+C690;C690;110B 116C 11BF;C690;110B 116C 11BF; # (욐; 욐; 욐; 욐; 욐; ) HANGUL SYLLABLE OEK
+C691;C691;110B 116C 11C0;C691;110B 116C 11C0; # (욑; 욑; 욑; 욑; 욑; ) HANGUL SYLLABLE OET
+C692;C692;110B 116C 11C1;C692;110B 116C 11C1; # (욒; 욒; 욒; 욒; 욒; ) HANGUL SYLLABLE OEP
+C693;C693;110B 116C 11C2;C693;110B 116C 11C2; # (욓; 욓; 욓; 욓; 욓; ) HANGUL SYLLABLE OEH
+C694;C694;110B 116D;C694;110B 116D; # (요; 요; 요; 요; 요; ) HANGUL SYLLABLE YO
+C695;C695;110B 116D 11A8;C695;110B 116D 11A8; # (욕; 욕; 욕; 욕; 욕; ) HANGUL SYLLABLE YOG
+C696;C696;110B 116D 11A9;C696;110B 116D 11A9; # (욖; 욖; 욖; 욖; 욖; ) HANGUL SYLLABLE YOGG
+C697;C697;110B 116D 11AA;C697;110B 116D 11AA; # (욗; 욗; 욗; 욗; 욗; ) HANGUL SYLLABLE YOGS
+C698;C698;110B 116D 11AB;C698;110B 116D 11AB; # (욘; 욘; 욘; 욘; 욘; ) HANGUL SYLLABLE YON
+C699;C699;110B 116D 11AC;C699;110B 116D 11AC; # (욙; 욙; 욙; 욙; 욙; ) HANGUL SYLLABLE YONJ
+C69A;C69A;110B 116D 11AD;C69A;110B 116D 11AD; # (욚; 욚; 욚; 욚; 욚; ) HANGUL SYLLABLE YONH
+C69B;C69B;110B 116D 11AE;C69B;110B 116D 11AE; # (욛; 욛; 욛; 욛; 욛; ) HANGUL SYLLABLE YOD
+C69C;C69C;110B 116D 11AF;C69C;110B 116D 11AF; # (욜; 욜; 욜; 욜; 욜; ) HANGUL SYLLABLE YOL
+C69D;C69D;110B 116D 11B0;C69D;110B 116D 11B0; # (욝; 욝; 욝; 욝; 욝; ) HANGUL SYLLABLE YOLG
+C69E;C69E;110B 116D 11B1;C69E;110B 116D 11B1; # (욞; 욞; 욞; 욞; 욞; ) HANGUL SYLLABLE YOLM
+C69F;C69F;110B 116D 11B2;C69F;110B 116D 11B2; # (욟; 욟; 욟; 욟; 욟; ) HANGUL SYLLABLE YOLB
+C6A0;C6A0;110B 116D 11B3;C6A0;110B 116D 11B3; # (욠; 욠; 욠; 욠; 욠; ) HANGUL SYLLABLE YOLS
+C6A1;C6A1;110B 116D 11B4;C6A1;110B 116D 11B4; # (욡; 욡; 욡; 욡; 욡; ) HANGUL SYLLABLE YOLT
+C6A2;C6A2;110B 116D 11B5;C6A2;110B 116D 11B5; # (욢; 욢; 욢; 욢; 욢; ) HANGUL SYLLABLE YOLP
+C6A3;C6A3;110B 116D 11B6;C6A3;110B 116D 11B6; # (욣; 욣; 욣; 욣; 욣; ) HANGUL SYLLABLE YOLH
+C6A4;C6A4;110B 116D 11B7;C6A4;110B 116D 11B7; # (욤; 욤; 욤; 욤; 욤; ) HANGUL SYLLABLE YOM
+C6A5;C6A5;110B 116D 11B8;C6A5;110B 116D 11B8; # (욥; 욥; 욥; 욥; 욥; ) HANGUL SYLLABLE YOB
+C6A6;C6A6;110B 116D 11B9;C6A6;110B 116D 11B9; # (욦; 욦; 욦; 욦; 욦; ) HANGUL SYLLABLE YOBS
+C6A7;C6A7;110B 116D 11BA;C6A7;110B 116D 11BA; # (욧; 욧; 욧; 욧; 욧; ) HANGUL SYLLABLE YOS
+C6A8;C6A8;110B 116D 11BB;C6A8;110B 116D 11BB; # (욨; 욨; 욨; 욨; 욨; ) HANGUL SYLLABLE YOSS
+C6A9;C6A9;110B 116D 11BC;C6A9;110B 116D 11BC; # (용; 용; 용; 용; 용; ) HANGUL SYLLABLE YONG
+C6AA;C6AA;110B 116D 11BD;C6AA;110B 116D 11BD; # (욪; 욪; 욪; 욪; 욪; ) HANGUL SYLLABLE YOJ
+C6AB;C6AB;110B 116D 11BE;C6AB;110B 116D 11BE; # (욫; 욫; 욫; 욫; 욫; ) HANGUL SYLLABLE YOC
+C6AC;C6AC;110B 116D 11BF;C6AC;110B 116D 11BF; # (욬; 욬; 욬; 욬; 욬; ) HANGUL SYLLABLE YOK
+C6AD;C6AD;110B 116D 11C0;C6AD;110B 116D 11C0; # (욭; 욭; 욭; 욭; 욭; ) HANGUL SYLLABLE YOT
+C6AE;C6AE;110B 116D 11C1;C6AE;110B 116D 11C1; # (욮; 욮; 욮; 욮; 욮; ) HANGUL SYLLABLE YOP
+C6AF;C6AF;110B 116D 11C2;C6AF;110B 116D 11C2; # (욯; 욯; 욯; 욯; 욯; ) HANGUL SYLLABLE YOH
+C6B0;C6B0;110B 116E;C6B0;110B 116E; # (우; 우; 우; 우; 우; ) HANGUL SYLLABLE U
+C6B1;C6B1;110B 116E 11A8;C6B1;110B 116E 11A8; # (욱; 욱; 욱; 욱; 욱; ) HANGUL SYLLABLE UG
+C6B2;C6B2;110B 116E 11A9;C6B2;110B 116E 11A9; # (욲; 욲; 욲; 욲; 욲; ) HANGUL SYLLABLE UGG
+C6B3;C6B3;110B 116E 11AA;C6B3;110B 116E 11AA; # (욳; 욳; 욳; 욳; 욳; ) HANGUL SYLLABLE UGS
+C6B4;C6B4;110B 116E 11AB;C6B4;110B 116E 11AB; # (운; 운; 운; 운; 운; ) HANGUL SYLLABLE UN
+C6B5;C6B5;110B 116E 11AC;C6B5;110B 116E 11AC; # (욵; 욵; 욵; 욵; 욵; ) HANGUL SYLLABLE UNJ
+C6B6;C6B6;110B 116E 11AD;C6B6;110B 116E 11AD; # (욶; 욶; 욶; 욶; 욶; ) HANGUL SYLLABLE UNH
+C6B7;C6B7;110B 116E 11AE;C6B7;110B 116E 11AE; # (욷; 욷; 욷; 욷; 욷; ) HANGUL SYLLABLE UD
+C6B8;C6B8;110B 116E 11AF;C6B8;110B 116E 11AF; # (울; 울; 울; 울; 울; ) HANGUL SYLLABLE UL
+C6B9;C6B9;110B 116E 11B0;C6B9;110B 116E 11B0; # (욹; 욹; 욹; 욹; 욹; ) HANGUL SYLLABLE ULG
+C6BA;C6BA;110B 116E 11B1;C6BA;110B 116E 11B1; # (욺; 욺; 욺; 욺; 욺; ) HANGUL SYLLABLE ULM
+C6BB;C6BB;110B 116E 11B2;C6BB;110B 116E 11B2; # (욻; 욻; 욻; 욻; 욻; ) HANGUL SYLLABLE ULB
+C6BC;C6BC;110B 116E 11B3;C6BC;110B 116E 11B3; # (욼; 욼; 욼; 욼; 욼; ) HANGUL SYLLABLE ULS
+C6BD;C6BD;110B 116E 11B4;C6BD;110B 116E 11B4; # (욽; 욽; 욽; 욽; 욽; ) HANGUL SYLLABLE ULT
+C6BE;C6BE;110B 116E 11B5;C6BE;110B 116E 11B5; # (욾; 욾; 욾; 욾; 욾; ) HANGUL SYLLABLE ULP
+C6BF;C6BF;110B 116E 11B6;C6BF;110B 116E 11B6; # (욿; 욿; 욿; 욿; 욿; ) HANGUL SYLLABLE ULH
+C6C0;C6C0;110B 116E 11B7;C6C0;110B 116E 11B7; # (움; 움; 움; 움; 움; ) HANGUL SYLLABLE UM
+C6C1;C6C1;110B 116E 11B8;C6C1;110B 116E 11B8; # (웁; 웁; 웁; 웁; 웁; ) HANGUL SYLLABLE UB
+C6C2;C6C2;110B 116E 11B9;C6C2;110B 116E 11B9; # (웂; 웂; 웂; 웂; 웂; ) HANGUL SYLLABLE UBS
+C6C3;C6C3;110B 116E 11BA;C6C3;110B 116E 11BA; # (웃; 웃; 웃; 웃; 웃; ) HANGUL SYLLABLE US
+C6C4;C6C4;110B 116E 11BB;C6C4;110B 116E 11BB; # (웄; 웄; 웄; 웄; 웄; ) HANGUL SYLLABLE USS
+C6C5;C6C5;110B 116E 11BC;C6C5;110B 116E 11BC; # (웅; 웅; 웅; 웅; 웅; ) HANGUL SYLLABLE UNG
+C6C6;C6C6;110B 116E 11BD;C6C6;110B 116E 11BD; # (웆; 웆; 웆; 웆; 웆; ) HANGUL SYLLABLE UJ
+C6C7;C6C7;110B 116E 11BE;C6C7;110B 116E 11BE; # (웇; 웇; 웇; 웇; 웇; ) HANGUL SYLLABLE UC
+C6C8;C6C8;110B 116E 11BF;C6C8;110B 116E 11BF; # (웈; 웈; 웈; 웈; 웈; ) HANGUL SYLLABLE UK
+C6C9;C6C9;110B 116E 11C0;C6C9;110B 116E 11C0; # (웉; 웉; 웉; 웉; 웉; ) HANGUL SYLLABLE UT
+C6CA;C6CA;110B 116E 11C1;C6CA;110B 116E 11C1; # (웊; 웊; 웊; 웊; 웊; ) HANGUL SYLLABLE UP
+C6CB;C6CB;110B 116E 11C2;C6CB;110B 116E 11C2; # (웋; 웋; 웋; 웋; 웋; ) HANGUL SYLLABLE UH
+C6CC;C6CC;110B 116F;C6CC;110B 116F; # (워; 워; 워; 워; 워; ) HANGUL SYLLABLE WEO
+C6CD;C6CD;110B 116F 11A8;C6CD;110B 116F 11A8; # (웍; 웍; 웍; 웍; 웍; ) HANGUL SYLLABLE WEOG
+C6CE;C6CE;110B 116F 11A9;C6CE;110B 116F 11A9; # (웎; 웎; 웎; 웎; 웎; ) HANGUL SYLLABLE WEOGG
+C6CF;C6CF;110B 116F 11AA;C6CF;110B 116F 11AA; # (웏; 웏; 웏; 웏; 웏; ) HANGUL SYLLABLE WEOGS
+C6D0;C6D0;110B 116F 11AB;C6D0;110B 116F 11AB; # (원; 원; 원; 원; 원; ) HANGUL SYLLABLE WEON
+C6D1;C6D1;110B 116F 11AC;C6D1;110B 116F 11AC; # (웑; 웑; 웑; 웑; 웑; ) HANGUL SYLLABLE WEONJ
+C6D2;C6D2;110B 116F 11AD;C6D2;110B 116F 11AD; # (웒; 웒; 웒; 웒; 웒; ) HANGUL SYLLABLE WEONH
+C6D3;C6D3;110B 116F 11AE;C6D3;110B 116F 11AE; # (웓; 웓; 웓; 웓; 웓; ) HANGUL SYLLABLE WEOD
+C6D4;C6D4;110B 116F 11AF;C6D4;110B 116F 11AF; # (월; 월; 월; 월; 월; ) HANGUL SYLLABLE WEOL
+C6D5;C6D5;110B 116F 11B0;C6D5;110B 116F 11B0; # (웕; 웕; 웕; 웕; 웕; ) HANGUL SYLLABLE WEOLG
+C6D6;C6D6;110B 116F 11B1;C6D6;110B 116F 11B1; # (웖; 웖; 웖; 웖; 웖; ) HANGUL SYLLABLE WEOLM
+C6D7;C6D7;110B 116F 11B2;C6D7;110B 116F 11B2; # (웗; 웗; 웗; 웗; 웗; ) HANGUL SYLLABLE WEOLB
+C6D8;C6D8;110B 116F 11B3;C6D8;110B 116F 11B3; # (웘; 웘; 웘; 웘; 웘; ) HANGUL SYLLABLE WEOLS
+C6D9;C6D9;110B 116F 11B4;C6D9;110B 116F 11B4; # (웙; 웙; 웙; 웙; 웙; ) HANGUL SYLLABLE WEOLT
+C6DA;C6DA;110B 116F 11B5;C6DA;110B 116F 11B5; # (웚; 웚; 웚; 웚; 웚; ) HANGUL SYLLABLE WEOLP
+C6DB;C6DB;110B 116F 11B6;C6DB;110B 116F 11B6; # (웛; 웛; 웛; 웛; 웛; ) HANGUL SYLLABLE WEOLH
+C6DC;C6DC;110B 116F 11B7;C6DC;110B 116F 11B7; # (웜; 웜; 웜; 웜; 웜; ) HANGUL SYLLABLE WEOM
+C6DD;C6DD;110B 116F 11B8;C6DD;110B 116F 11B8; # (웝; 웝; 웝; 웝; 웝; ) HANGUL SYLLABLE WEOB
+C6DE;C6DE;110B 116F 11B9;C6DE;110B 116F 11B9; # (웞; 웞; 웞; 웞; 웞; ) HANGUL SYLLABLE WEOBS
+C6DF;C6DF;110B 116F 11BA;C6DF;110B 116F 11BA; # (웟; 웟; 웟; 웟; 웟; ) HANGUL SYLLABLE WEOS
+C6E0;C6E0;110B 116F 11BB;C6E0;110B 116F 11BB; # (웠; 웠; 웠; 웠; 웠; ) HANGUL SYLLABLE WEOSS
+C6E1;C6E1;110B 116F 11BC;C6E1;110B 116F 11BC; # (웡; 웡; 웡; 웡; 웡; ) HANGUL SYLLABLE WEONG
+C6E2;C6E2;110B 116F 11BD;C6E2;110B 116F 11BD; # (웢; 웢; 웢; 웢; 웢; ) HANGUL SYLLABLE WEOJ
+C6E3;C6E3;110B 116F 11BE;C6E3;110B 116F 11BE; # (웣; 웣; 웣; 웣; 웣; ) HANGUL SYLLABLE WEOC
+C6E4;C6E4;110B 116F 11BF;C6E4;110B 116F 11BF; # (웤; 웤; 웤; 웤; 웤; ) HANGUL SYLLABLE WEOK
+C6E5;C6E5;110B 116F 11C0;C6E5;110B 116F 11C0; # (웥; 웥; 웥; 웥; 웥; ) HANGUL SYLLABLE WEOT
+C6E6;C6E6;110B 116F 11C1;C6E6;110B 116F 11C1; # (웦; 웦; 웦; 웦; 웦; ) HANGUL SYLLABLE WEOP
+C6E7;C6E7;110B 116F 11C2;C6E7;110B 116F 11C2; # (웧; 웧; 웧; 웧; 웧; ) HANGUL SYLLABLE WEOH
+C6E8;C6E8;110B 1170;C6E8;110B 1170; # (웨; 웨; 웨; 웨; 웨; ) HANGUL SYLLABLE WE
+C6E9;C6E9;110B 1170 11A8;C6E9;110B 1170 11A8; # (웩; 웩; 웩; 웩; 웩; ) HANGUL SYLLABLE WEG
+C6EA;C6EA;110B 1170 11A9;C6EA;110B 1170 11A9; # (웪; 웪; 웪; 웪; 웪; ) HANGUL SYLLABLE WEGG
+C6EB;C6EB;110B 1170 11AA;C6EB;110B 1170 11AA; # (웫; 웫; 웫; 웫; 웫; ) HANGUL SYLLABLE WEGS
+C6EC;C6EC;110B 1170 11AB;C6EC;110B 1170 11AB; # (웬; 웬; 웬; 웬; 웬; ) HANGUL SYLLABLE WEN
+C6ED;C6ED;110B 1170 11AC;C6ED;110B 1170 11AC; # (웭; 웭; 웭; 웭; 웭; ) HANGUL SYLLABLE WENJ
+C6EE;C6EE;110B 1170 11AD;C6EE;110B 1170 11AD; # (웮; 웮; 웮; 웮; 웮; ) HANGUL SYLLABLE WENH
+C6EF;C6EF;110B 1170 11AE;C6EF;110B 1170 11AE; # (웯; 웯; 웯; 웯; 웯; ) HANGUL SYLLABLE WED
+C6F0;C6F0;110B 1170 11AF;C6F0;110B 1170 11AF; # (웰; 웰; 웰; 웰; 웰; ) HANGUL SYLLABLE WEL
+C6F1;C6F1;110B 1170 11B0;C6F1;110B 1170 11B0; # (웱; 웱; 웱; 웱; 웱; ) HANGUL SYLLABLE WELG
+C6F2;C6F2;110B 1170 11B1;C6F2;110B 1170 11B1; # (웲; 웲; 웲; 웲; 웲; ) HANGUL SYLLABLE WELM
+C6F3;C6F3;110B 1170 11B2;C6F3;110B 1170 11B2; # (웳; 웳; 웳; 웳; 웳; ) HANGUL SYLLABLE WELB
+C6F4;C6F4;110B 1170 11B3;C6F4;110B 1170 11B3; # (웴; 웴; 웴; 웴; 웴; ) HANGUL SYLLABLE WELS
+C6F5;C6F5;110B 1170 11B4;C6F5;110B 1170 11B4; # (웵; 웵; 웵; 웵; 웵; ) HANGUL SYLLABLE WELT
+C6F6;C6F6;110B 1170 11B5;C6F6;110B 1170 11B5; # (웶; 웶; 웶; 웶; 웶; ) HANGUL SYLLABLE WELP
+C6F7;C6F7;110B 1170 11B6;C6F7;110B 1170 11B6; # (웷; 웷; 웷; 웷; 웷; ) HANGUL SYLLABLE WELH
+C6F8;C6F8;110B 1170 11B7;C6F8;110B 1170 11B7; # (웸; 웸; 웸; 웸; 웸; ) HANGUL SYLLABLE WEM
+C6F9;C6F9;110B 1170 11B8;C6F9;110B 1170 11B8; # (웹; 웹; 웹; 웹; 웹; ) HANGUL SYLLABLE WEB
+C6FA;C6FA;110B 1170 11B9;C6FA;110B 1170 11B9; # (웺; 웺; 웺; 웺; 웺; ) HANGUL SYLLABLE WEBS
+C6FB;C6FB;110B 1170 11BA;C6FB;110B 1170 11BA; # (웻; 웻; 웻; 웻; 웻; ) HANGUL SYLLABLE WES
+C6FC;C6FC;110B 1170 11BB;C6FC;110B 1170 11BB; # (웼; 웼; 웼; 웼; 웼; ) HANGUL SYLLABLE WESS
+C6FD;C6FD;110B 1170 11BC;C6FD;110B 1170 11BC; # (웽; 웽; 웽; 웽; 웽; ) HANGUL SYLLABLE WENG
+C6FE;C6FE;110B 1170 11BD;C6FE;110B 1170 11BD; # (웾; 웾; 웾; 웾; 웾; ) HANGUL SYLLABLE WEJ
+C6FF;C6FF;110B 1170 11BE;C6FF;110B 1170 11BE; # (웿; 웿; 웿; 웿; 웿; ) HANGUL SYLLABLE WEC
+C700;C700;110B 1170 11BF;C700;110B 1170 11BF; # (윀; 윀; 윀; 윀; 윀; ) HANGUL SYLLABLE WEK
+C701;C701;110B 1170 11C0;C701;110B 1170 11C0; # (윁; 윁; 윁; 윁; 윁; ) HANGUL SYLLABLE WET
+C702;C702;110B 1170 11C1;C702;110B 1170 11C1; # (윂; 윂; 윂; 윂; 윂; ) HANGUL SYLLABLE WEP
+C703;C703;110B 1170 11C2;C703;110B 1170 11C2; # (윃; 윃; 윃; 윃; 윃; ) HANGUL SYLLABLE WEH
+C704;C704;110B 1171;C704;110B 1171; # (위; 위; 위; 위; 위; ) HANGUL SYLLABLE WI
+C705;C705;110B 1171 11A8;C705;110B 1171 11A8; # (윅; 윅; 윅; 윅; 윅; ) HANGUL SYLLABLE WIG
+C706;C706;110B 1171 11A9;C706;110B 1171 11A9; # (윆; 윆; 윆; 윆; 윆; ) HANGUL SYLLABLE WIGG
+C707;C707;110B 1171 11AA;C707;110B 1171 11AA; # (윇; 윇; 윇; 윇; 윇; ) HANGUL SYLLABLE WIGS
+C708;C708;110B 1171 11AB;C708;110B 1171 11AB; # (윈; 윈; 윈; 윈; 윈; ) HANGUL SYLLABLE WIN
+C709;C709;110B 1171 11AC;C709;110B 1171 11AC; # (윉; 윉; 윉; 윉; 윉; ) HANGUL SYLLABLE WINJ
+C70A;C70A;110B 1171 11AD;C70A;110B 1171 11AD; # (윊; 윊; 윊; 윊; 윊; ) HANGUL SYLLABLE WINH
+C70B;C70B;110B 1171 11AE;C70B;110B 1171 11AE; # (윋; 윋; 윋; 윋; 윋; ) HANGUL SYLLABLE WID
+C70C;C70C;110B 1171 11AF;C70C;110B 1171 11AF; # (윌; 윌; 윌; 윌; 윌; ) HANGUL SYLLABLE WIL
+C70D;C70D;110B 1171 11B0;C70D;110B 1171 11B0; # (윍; 윍; 윍; 윍; 윍; ) HANGUL SYLLABLE WILG
+C70E;C70E;110B 1171 11B1;C70E;110B 1171 11B1; # (윎; 윎; 윎; 윎; 윎; ) HANGUL SYLLABLE WILM
+C70F;C70F;110B 1171 11B2;C70F;110B 1171 11B2; # (윏; 윏; 윏; 윏; 윏; ) HANGUL SYLLABLE WILB
+C710;C710;110B 1171 11B3;C710;110B 1171 11B3; # (윐; 윐; 윐; 윐; 윐; ) HANGUL SYLLABLE WILS
+C711;C711;110B 1171 11B4;C711;110B 1171 11B4; # (윑; 윑; 윑; 윑; 윑; ) HANGUL SYLLABLE WILT
+C712;C712;110B 1171 11B5;C712;110B 1171 11B5; # (윒; 윒; 윒; 윒; 윒; ) HANGUL SYLLABLE WILP
+C713;C713;110B 1171 11B6;C713;110B 1171 11B6; # (윓; 윓; 윓; 윓; 윓; ) HANGUL SYLLABLE WILH
+C714;C714;110B 1171 11B7;C714;110B 1171 11B7; # (윔; 윔; 윔; 윔; 윔; ) HANGUL SYLLABLE WIM
+C715;C715;110B 1171 11B8;C715;110B 1171 11B8; # (윕; 윕; 윕; 윕; 윕; ) HANGUL SYLLABLE WIB
+C716;C716;110B 1171 11B9;C716;110B 1171 11B9; # (윖; 윖; 윖; 윖; 윖; ) HANGUL SYLLABLE WIBS
+C717;C717;110B 1171 11BA;C717;110B 1171 11BA; # (윗; 윗; 윗; 윗; 윗; ) HANGUL SYLLABLE WIS
+C718;C718;110B 1171 11BB;C718;110B 1171 11BB; # (윘; 윘; 윘; 윘; 윘; ) HANGUL SYLLABLE WISS
+C719;C719;110B 1171 11BC;C719;110B 1171 11BC; # (윙; 윙; 윙; 윙; 윙; ) HANGUL SYLLABLE WING
+C71A;C71A;110B 1171 11BD;C71A;110B 1171 11BD; # (윚; 윚; 윚; 윚; 윚; ) HANGUL SYLLABLE WIJ
+C71B;C71B;110B 1171 11BE;C71B;110B 1171 11BE; # (윛; 윛; 윛; 윛; 윛; ) HANGUL SYLLABLE WIC
+C71C;C71C;110B 1171 11BF;C71C;110B 1171 11BF; # (윜; 윜; 윜; 윜; 윜; ) HANGUL SYLLABLE WIK
+C71D;C71D;110B 1171 11C0;C71D;110B 1171 11C0; # (윝; 윝; 윝; 윝; 윝; ) HANGUL SYLLABLE WIT
+C71E;C71E;110B 1171 11C1;C71E;110B 1171 11C1; # (윞; 윞; 윞; 윞; 윞; ) HANGUL SYLLABLE WIP
+C71F;C71F;110B 1171 11C2;C71F;110B 1171 11C2; # (윟; 윟; 윟; 윟; 윟; ) HANGUL SYLLABLE WIH
+C720;C720;110B 1172;C720;110B 1172; # (유; 유; 유; 유; 유; ) HANGUL SYLLABLE YU
+C721;C721;110B 1172 11A8;C721;110B 1172 11A8; # (육; 육; 육; 육; 육; ) HANGUL SYLLABLE YUG
+C722;C722;110B 1172 11A9;C722;110B 1172 11A9; # (윢; 윢; 윢; 윢; 윢; ) HANGUL SYLLABLE YUGG
+C723;C723;110B 1172 11AA;C723;110B 1172 11AA; # (윣; 윣; 윣; 윣; 윣; ) HANGUL SYLLABLE YUGS
+C724;C724;110B 1172 11AB;C724;110B 1172 11AB; # (윤; 윤; 윤; 윤; 윤; ) HANGUL SYLLABLE YUN
+C725;C725;110B 1172 11AC;C725;110B 1172 11AC; # (윥; 윥; 윥; 윥; 윥; ) HANGUL SYLLABLE YUNJ
+C726;C726;110B 1172 11AD;C726;110B 1172 11AD; # (윦; 윦; 윦; 윦; 윦; ) HANGUL SYLLABLE YUNH
+C727;C727;110B 1172 11AE;C727;110B 1172 11AE; # (윧; 윧; 윧; 윧; 윧; ) HANGUL SYLLABLE YUD
+C728;C728;110B 1172 11AF;C728;110B 1172 11AF; # (율; 율; 율; 율; 율; ) HANGUL SYLLABLE YUL
+C729;C729;110B 1172 11B0;C729;110B 1172 11B0; # (윩; 윩; 윩; 윩; 윩; ) HANGUL SYLLABLE YULG
+C72A;C72A;110B 1172 11B1;C72A;110B 1172 11B1; # (윪; 윪; 윪; 윪; 윪; ) HANGUL SYLLABLE YULM
+C72B;C72B;110B 1172 11B2;C72B;110B 1172 11B2; # (윫; 윫; 윫; 윫; 윫; ) HANGUL SYLLABLE YULB
+C72C;C72C;110B 1172 11B3;C72C;110B 1172 11B3; # (윬; 윬; 윬; 윬; 윬; ) HANGUL SYLLABLE YULS
+C72D;C72D;110B 1172 11B4;C72D;110B 1172 11B4; # (윭; 윭; 윭; 윭; 윭; ) HANGUL SYLLABLE YULT
+C72E;C72E;110B 1172 11B5;C72E;110B 1172 11B5; # (윮; 윮; 윮; 윮; 윮; ) HANGUL SYLLABLE YULP
+C72F;C72F;110B 1172 11B6;C72F;110B 1172 11B6; # (윯; 윯; 윯; 윯; 윯; ) HANGUL SYLLABLE YULH
+C730;C730;110B 1172 11B7;C730;110B 1172 11B7; # (윰; 윰; 윰; 윰; 윰; ) HANGUL SYLLABLE YUM
+C731;C731;110B 1172 11B8;C731;110B 1172 11B8; # (윱; 윱; 윱; 윱; 윱; ) HANGUL SYLLABLE YUB
+C732;C732;110B 1172 11B9;C732;110B 1172 11B9; # (윲; 윲; 윲; 윲; 윲; ) HANGUL SYLLABLE YUBS
+C733;C733;110B 1172 11BA;C733;110B 1172 11BA; # (윳; 윳; 윳; 윳; 윳; ) HANGUL SYLLABLE YUS
+C734;C734;110B 1172 11BB;C734;110B 1172 11BB; # (윴; 윴; 윴; 윴; 윴; ) HANGUL SYLLABLE YUSS
+C735;C735;110B 1172 11BC;C735;110B 1172 11BC; # (융; 융; 융; 융; 융; ) HANGUL SYLLABLE YUNG
+C736;C736;110B 1172 11BD;C736;110B 1172 11BD; # (윶; 윶; 윶; 윶; 윶; ) HANGUL SYLLABLE YUJ
+C737;C737;110B 1172 11BE;C737;110B 1172 11BE; # (윷; 윷; 윷; 윷; 윷; ) HANGUL SYLLABLE YUC
+C738;C738;110B 1172 11BF;C738;110B 1172 11BF; # (윸; 윸; 윸; 윸; 윸; ) HANGUL SYLLABLE YUK
+C739;C739;110B 1172 11C0;C739;110B 1172 11C0; # (윹; 윹; 윹; 윹; 윹; ) HANGUL SYLLABLE YUT
+C73A;C73A;110B 1172 11C1;C73A;110B 1172 11C1; # (윺; 윺; 윺; 윺; 윺; ) HANGUL SYLLABLE YUP
+C73B;C73B;110B 1172 11C2;C73B;110B 1172 11C2; # (윻; 윻; 윻; 윻; 윻; ) HANGUL SYLLABLE YUH
+C73C;C73C;110B 1173;C73C;110B 1173; # (으; 으; 으; 으; 으; ) HANGUL SYLLABLE EU
+C73D;C73D;110B 1173 11A8;C73D;110B 1173 11A8; # (윽; 윽; 윽; 윽; 윽; ) HANGUL SYLLABLE EUG
+C73E;C73E;110B 1173 11A9;C73E;110B 1173 11A9; # (윾; 윾; 윾; 윾; 윾; ) HANGUL SYLLABLE EUGG
+C73F;C73F;110B 1173 11AA;C73F;110B 1173 11AA; # (윿; 윿; 윿; 윿; 윿; ) HANGUL SYLLABLE EUGS
+C740;C740;110B 1173 11AB;C740;110B 1173 11AB; # (은; 은; 은; 은; 은; ) HANGUL SYLLABLE EUN
+C741;C741;110B 1173 11AC;C741;110B 1173 11AC; # (읁; 읁; 읁; 읁; 읁; ) HANGUL SYLLABLE EUNJ
+C742;C742;110B 1173 11AD;C742;110B 1173 11AD; # (읂; 읂; 읂; 읂; 읂; ) HANGUL SYLLABLE EUNH
+C743;C743;110B 1173 11AE;C743;110B 1173 11AE; # (읃; 읃; 읃; 읃; 읃; ) HANGUL SYLLABLE EUD
+C744;C744;110B 1173 11AF;C744;110B 1173 11AF; # (을; 을; 을; 을; 을; ) HANGUL SYLLABLE EUL
+C745;C745;110B 1173 11B0;C745;110B 1173 11B0; # (읅; 읅; 읅; 읅; 읅; ) HANGUL SYLLABLE EULG
+C746;C746;110B 1173 11B1;C746;110B 1173 11B1; # (읆; 읆; 읆; 읆; 읆; ) HANGUL SYLLABLE EULM
+C747;C747;110B 1173 11B2;C747;110B 1173 11B2; # (읇; 읇; 읇; 읇; 읇; ) HANGUL SYLLABLE EULB
+C748;C748;110B 1173 11B3;C748;110B 1173 11B3; # (읈; 읈; 읈; 읈; 읈; ) HANGUL SYLLABLE EULS
+C749;C749;110B 1173 11B4;C749;110B 1173 11B4; # (읉; 읉; 읉; 읉; 읉; ) HANGUL SYLLABLE EULT
+C74A;C74A;110B 1173 11B5;C74A;110B 1173 11B5; # (읊; 읊; 읊; 읊; 읊; ) HANGUL SYLLABLE EULP
+C74B;C74B;110B 1173 11B6;C74B;110B 1173 11B6; # (읋; 읋; 읋; 읋; 읋; ) HANGUL SYLLABLE EULH
+C74C;C74C;110B 1173 11B7;C74C;110B 1173 11B7; # (음; 음; 음; 음; 음; ) HANGUL SYLLABLE EUM
+C74D;C74D;110B 1173 11B8;C74D;110B 1173 11B8; # (읍; 읍; 읍; 읍; 읍; ) HANGUL SYLLABLE EUB
+C74E;C74E;110B 1173 11B9;C74E;110B 1173 11B9; # (읎; 읎; 읎; 읎; 읎; ) HANGUL SYLLABLE EUBS
+C74F;C74F;110B 1173 11BA;C74F;110B 1173 11BA; # (읏; 읏; 읏; 읏; 읏; ) HANGUL SYLLABLE EUS
+C750;C750;110B 1173 11BB;C750;110B 1173 11BB; # (읐; 읐; 읐; 읐; 읐; ) HANGUL SYLLABLE EUSS
+C751;C751;110B 1173 11BC;C751;110B 1173 11BC; # (응; 응; 응; 응; 응; ) HANGUL SYLLABLE EUNG
+C752;C752;110B 1173 11BD;C752;110B 1173 11BD; # (읒; 읒; 읒; 읒; 읒; ) HANGUL SYLLABLE EUJ
+C753;C753;110B 1173 11BE;C753;110B 1173 11BE; # (읓; 읓; 읓; 읓; 읓; ) HANGUL SYLLABLE EUC
+C754;C754;110B 1173 11BF;C754;110B 1173 11BF; # (읔; 읔; 읔; 읔; 읔; ) HANGUL SYLLABLE EUK
+C755;C755;110B 1173 11C0;C755;110B 1173 11C0; # (읕; 읕; 읕; 읕; 읕; ) HANGUL SYLLABLE EUT
+C756;C756;110B 1173 11C1;C756;110B 1173 11C1; # (읖; 읖; 읖; 읖; 읖; ) HANGUL SYLLABLE EUP
+C757;C757;110B 1173 11C2;C757;110B 1173 11C2; # (읗; 읗; 읗; 읗; 읗; ) HANGUL SYLLABLE EUH
+C758;C758;110B 1174;C758;110B 1174; # (의; 의; 의; 의; 의; ) HANGUL SYLLABLE YI
+C759;C759;110B 1174 11A8;C759;110B 1174 11A8; # (읙; 읙; 읙; 읙; 읙; ) HANGUL SYLLABLE YIG
+C75A;C75A;110B 1174 11A9;C75A;110B 1174 11A9; # (읚; 읚; 읚; 읚; 읚; ) HANGUL SYLLABLE YIGG
+C75B;C75B;110B 1174 11AA;C75B;110B 1174 11AA; # (읛; 읛; 읛; 읛; 읛; ) HANGUL SYLLABLE YIGS
+C75C;C75C;110B 1174 11AB;C75C;110B 1174 11AB; # (읜; 읜; 읜; 읜; 읜; ) HANGUL SYLLABLE YIN
+C75D;C75D;110B 1174 11AC;C75D;110B 1174 11AC; # (읝; 읝; 읝; 읝; 읝; ) HANGUL SYLLABLE YINJ
+C75E;C75E;110B 1174 11AD;C75E;110B 1174 11AD; # (읞; 읞; 읞; 읞; 읞; ) HANGUL SYLLABLE YINH
+C75F;C75F;110B 1174 11AE;C75F;110B 1174 11AE; # (읟; 읟; 읟; 읟; 읟; ) HANGUL SYLLABLE YID
+C760;C760;110B 1174 11AF;C760;110B 1174 11AF; # (읠; 읠; 읠; 읠; 읠; ) HANGUL SYLLABLE YIL
+C761;C761;110B 1174 11B0;C761;110B 1174 11B0; # (읡; 읡; 읡; 읡; 읡; ) HANGUL SYLLABLE YILG
+C762;C762;110B 1174 11B1;C762;110B 1174 11B1; # (읢; 읢; 읢; 읢; 읢; ) HANGUL SYLLABLE YILM
+C763;C763;110B 1174 11B2;C763;110B 1174 11B2; # (읣; 읣; 읣; 읣; 읣; ) HANGUL SYLLABLE YILB
+C764;C764;110B 1174 11B3;C764;110B 1174 11B3; # (읤; 읤; 읤; 읤; 읤; ) HANGUL SYLLABLE YILS
+C765;C765;110B 1174 11B4;C765;110B 1174 11B4; # (읥; 읥; 읥; 읥; 읥; ) HANGUL SYLLABLE YILT
+C766;C766;110B 1174 11B5;C766;110B 1174 11B5; # (읦; 읦; 읦; 읦; 읦; ) HANGUL SYLLABLE YILP
+C767;C767;110B 1174 11B6;C767;110B 1174 11B6; # (읧; 읧; 읧; 읧; 읧; ) HANGUL SYLLABLE YILH
+C768;C768;110B 1174 11B7;C768;110B 1174 11B7; # (읨; 읨; 읨; 읨; 읨; ) HANGUL SYLLABLE YIM
+C769;C769;110B 1174 11B8;C769;110B 1174 11B8; # (읩; 읩; 읩; 읩; 읩; ) HANGUL SYLLABLE YIB
+C76A;C76A;110B 1174 11B9;C76A;110B 1174 11B9; # (읪; 읪; 읪; 읪; 읪; ) HANGUL SYLLABLE YIBS
+C76B;C76B;110B 1174 11BA;C76B;110B 1174 11BA; # (읫; 읫; 읫; 읫; 읫; ) HANGUL SYLLABLE YIS
+C76C;C76C;110B 1174 11BB;C76C;110B 1174 11BB; # (읬; 읬; 읬; 읬; 읬; ) HANGUL SYLLABLE YISS
+C76D;C76D;110B 1174 11BC;C76D;110B 1174 11BC; # (읭; 읭; 읭; 읭; 읭; ) HANGUL SYLLABLE YING
+C76E;C76E;110B 1174 11BD;C76E;110B 1174 11BD; # (읮; 읮; 읮; 읮; 읮; ) HANGUL SYLLABLE YIJ
+C76F;C76F;110B 1174 11BE;C76F;110B 1174 11BE; # (읯; 읯; 읯; 읯; 읯; ) HANGUL SYLLABLE YIC
+C770;C770;110B 1174 11BF;C770;110B 1174 11BF; # (읰; 읰; 읰; 읰; 읰; ) HANGUL SYLLABLE YIK
+C771;C771;110B 1174 11C0;C771;110B 1174 11C0; # (읱; 읱; 읱; 읱; 읱; ) HANGUL SYLLABLE YIT
+C772;C772;110B 1174 11C1;C772;110B 1174 11C1; # (읲; 읲; 읲; 읲; 읲; ) HANGUL SYLLABLE YIP
+C773;C773;110B 1174 11C2;C773;110B 1174 11C2; # (읳; 읳; 읳; 읳; 읳; ) HANGUL SYLLABLE YIH
+C774;C774;110B 1175;C774;110B 1175; # (이; 이; 이; 이; 이; ) HANGUL SYLLABLE I
+C775;C775;110B 1175 11A8;C775;110B 1175 11A8; # (익; 익; 익; 익; 익; ) HANGUL SYLLABLE IG
+C776;C776;110B 1175 11A9;C776;110B 1175 11A9; # (읶; 읶; 읶; 읶; 읶; ) HANGUL SYLLABLE IGG
+C777;C777;110B 1175 11AA;C777;110B 1175 11AA; # (읷; 읷; 읷; 읷; 읷; ) HANGUL SYLLABLE IGS
+C778;C778;110B 1175 11AB;C778;110B 1175 11AB; # (인; 인; 인; 인; 인; ) HANGUL SYLLABLE IN
+C779;C779;110B 1175 11AC;C779;110B 1175 11AC; # (읹; 읹; 읹; 읹; 읹; ) HANGUL SYLLABLE INJ
+C77A;C77A;110B 1175 11AD;C77A;110B 1175 11AD; # (읺; 읺; 읺; 읺; 읺; ) HANGUL SYLLABLE INH
+C77B;C77B;110B 1175 11AE;C77B;110B 1175 11AE; # (읻; 읻; 읻; 읻; 읻; ) HANGUL SYLLABLE ID
+C77C;C77C;110B 1175 11AF;C77C;110B 1175 11AF; # (일; 일; 일; 일; 일; ) HANGUL SYLLABLE IL
+C77D;C77D;110B 1175 11B0;C77D;110B 1175 11B0; # (읽; 읽; 읽; 읽; 읽; ) HANGUL SYLLABLE ILG
+C77E;C77E;110B 1175 11B1;C77E;110B 1175 11B1; # (읾; 읾; 읾; 읾; 읾; ) HANGUL SYLLABLE ILM
+C77F;C77F;110B 1175 11B2;C77F;110B 1175 11B2; # (읿; 읿; 읿; 읿; 읿; ) HANGUL SYLLABLE ILB
+C780;C780;110B 1175 11B3;C780;110B 1175 11B3; # (잀; 잀; 잀; 잀; 잀; ) HANGUL SYLLABLE ILS
+C781;C781;110B 1175 11B4;C781;110B 1175 11B4; # (잁; 잁; 잁; 잁; 잁; ) HANGUL SYLLABLE ILT
+C782;C782;110B 1175 11B5;C782;110B 1175 11B5; # (잂; 잂; 잂; 잂; 잂; ) HANGUL SYLLABLE ILP
+C783;C783;110B 1175 11B6;C783;110B 1175 11B6; # (잃; 잃; 잃; 잃; 잃; ) HANGUL SYLLABLE ILH
+C784;C784;110B 1175 11B7;C784;110B 1175 11B7; # (임; 임; 임; 임; 임; ) HANGUL SYLLABLE IM
+C785;C785;110B 1175 11B8;C785;110B 1175 11B8; # (입; 입; 입; 입; 입; ) HANGUL SYLLABLE IB
+C786;C786;110B 1175 11B9;C786;110B 1175 11B9; # (잆; 잆; 잆; 잆; 잆; ) HANGUL SYLLABLE IBS
+C787;C787;110B 1175 11BA;C787;110B 1175 11BA; # (잇; 잇; 잇; 잇; 잇; ) HANGUL SYLLABLE IS
+C788;C788;110B 1175 11BB;C788;110B 1175 11BB; # (있; 있; 있; 있; 있; ) HANGUL SYLLABLE ISS
+C789;C789;110B 1175 11BC;C789;110B 1175 11BC; # (잉; 잉; 잉; 잉; 잉; ) HANGUL SYLLABLE ING
+C78A;C78A;110B 1175 11BD;C78A;110B 1175 11BD; # (잊; 잊; 잊; 잊; 잊; ) HANGUL SYLLABLE IJ
+C78B;C78B;110B 1175 11BE;C78B;110B 1175 11BE; # (잋; 잋; 잋; 잋; 잋; ) HANGUL SYLLABLE IC
+C78C;C78C;110B 1175 11BF;C78C;110B 1175 11BF; # (잌; 잌; 잌; 잌; 잌; ) HANGUL SYLLABLE IK
+C78D;C78D;110B 1175 11C0;C78D;110B 1175 11C0; # (잍; 잍; 잍; 잍; 잍; ) HANGUL SYLLABLE IT
+C78E;C78E;110B 1175 11C1;C78E;110B 1175 11C1; # (잎; 잎; 잎; 잎; 잎; ) HANGUL SYLLABLE IP
+C78F;C78F;110B 1175 11C2;C78F;110B 1175 11C2; # (잏; 잏; 잏; 잏; 잏; ) HANGUL SYLLABLE IH
+C790;C790;110C 1161;C790;110C 1161; # (자; 자; 자; 자; 자; ) HANGUL SYLLABLE JA
+C791;C791;110C 1161 11A8;C791;110C 1161 11A8; # (작; 작; 작; 작; 작; ) HANGUL SYLLABLE JAG
+C792;C792;110C 1161 11A9;C792;110C 1161 11A9; # (잒; 잒; 잒; 잒; 잒; ) HANGUL SYLLABLE JAGG
+C793;C793;110C 1161 11AA;C793;110C 1161 11AA; # (잓; 잓; 잓; 잓; 잓; ) HANGUL SYLLABLE JAGS
+C794;C794;110C 1161 11AB;C794;110C 1161 11AB; # (잔; 잔; 잔; 잔; 잔; ) HANGUL SYLLABLE JAN
+C795;C795;110C 1161 11AC;C795;110C 1161 11AC; # (잕; 잕; 잕; 잕; 잕; ) HANGUL SYLLABLE JANJ
+C796;C796;110C 1161 11AD;C796;110C 1161 11AD; # (잖; 잖; 잖; 잖; 잖; ) HANGUL SYLLABLE JANH
+C797;C797;110C 1161 11AE;C797;110C 1161 11AE; # (잗; 잗; 잗; 잗; 잗; ) HANGUL SYLLABLE JAD
+C798;C798;110C 1161 11AF;C798;110C 1161 11AF; # (잘; 잘; 잘; 잘; 잘; ) HANGUL SYLLABLE JAL
+C799;C799;110C 1161 11B0;C799;110C 1161 11B0; # (잙; 잙; 잙; 잙; 잙; ) HANGUL SYLLABLE JALG
+C79A;C79A;110C 1161 11B1;C79A;110C 1161 11B1; # (잚; 잚; 잚; 잚; 잚; ) HANGUL SYLLABLE JALM
+C79B;C79B;110C 1161 11B2;C79B;110C 1161 11B2; # (잛; 잛; 잛; 잛; 잛; ) HANGUL SYLLABLE JALB
+C79C;C79C;110C 1161 11B3;C79C;110C 1161 11B3; # (잜; 잜; 잜; 잜; 잜; ) HANGUL SYLLABLE JALS
+C79D;C79D;110C 1161 11B4;C79D;110C 1161 11B4; # (잝; 잝; 잝; 잝; 잝; ) HANGUL SYLLABLE JALT
+C79E;C79E;110C 1161 11B5;C79E;110C 1161 11B5; # (잞; 잞; 잞; 잞; 잞; ) HANGUL SYLLABLE JALP
+C79F;C79F;110C 1161 11B6;C79F;110C 1161 11B6; # (잟; 잟; 잟; 잟; 잟; ) HANGUL SYLLABLE JALH
+C7A0;C7A0;110C 1161 11B7;C7A0;110C 1161 11B7; # (잠; 잠; 잠; 잠; 잠; ) HANGUL SYLLABLE JAM
+C7A1;C7A1;110C 1161 11B8;C7A1;110C 1161 11B8; # (잡; 잡; 잡; 잡; 잡; ) HANGUL SYLLABLE JAB
+C7A2;C7A2;110C 1161 11B9;C7A2;110C 1161 11B9; # (잢; 잢; 잢; 잢; 잢; ) HANGUL SYLLABLE JABS
+C7A3;C7A3;110C 1161 11BA;C7A3;110C 1161 11BA; # (잣; 잣; 잣; 잣; 잣; ) HANGUL SYLLABLE JAS
+C7A4;C7A4;110C 1161 11BB;C7A4;110C 1161 11BB; # (잤; 잤; 잤; 잤; 잤; ) HANGUL SYLLABLE JASS
+C7A5;C7A5;110C 1161 11BC;C7A5;110C 1161 11BC; # (장; 장; 장; 장; 장; ) HANGUL SYLLABLE JANG
+C7A6;C7A6;110C 1161 11BD;C7A6;110C 1161 11BD; # (잦; 잦; 잦; 잦; 잦; ) HANGUL SYLLABLE JAJ
+C7A7;C7A7;110C 1161 11BE;C7A7;110C 1161 11BE; # (잧; 잧; 잧; 잧; 잧; ) HANGUL SYLLABLE JAC
+C7A8;C7A8;110C 1161 11BF;C7A8;110C 1161 11BF; # (잨; 잨; 잨; 잨; 잨; ) HANGUL SYLLABLE JAK
+C7A9;C7A9;110C 1161 11C0;C7A9;110C 1161 11C0; # (잩; 잩; 잩; 잩; 잩; ) HANGUL SYLLABLE JAT
+C7AA;C7AA;110C 1161 11C1;C7AA;110C 1161 11C1; # (잪; 잪; 잪; 잪; 잪; ) HANGUL SYLLABLE JAP
+C7AB;C7AB;110C 1161 11C2;C7AB;110C 1161 11C2; # (잫; 잫; 잫; 잫; 잫; ) HANGUL SYLLABLE JAH
+C7AC;C7AC;110C 1162;C7AC;110C 1162; # (재; 재; 재; 재; 재; ) HANGUL SYLLABLE JAE
+C7AD;C7AD;110C 1162 11A8;C7AD;110C 1162 11A8; # (잭; 잭; 잭; 잭; 잭; ) HANGUL SYLLABLE JAEG
+C7AE;C7AE;110C 1162 11A9;C7AE;110C 1162 11A9; # (잮; 잮; 잮; 잮; 잮; ) HANGUL SYLLABLE JAEGG
+C7AF;C7AF;110C 1162 11AA;C7AF;110C 1162 11AA; # (잯; 잯; 잯; 잯; 잯; ) HANGUL SYLLABLE JAEGS
+C7B0;C7B0;110C 1162 11AB;C7B0;110C 1162 11AB; # (잰; 잰; 잰; 잰; 잰; ) HANGUL SYLLABLE JAEN
+C7B1;C7B1;110C 1162 11AC;C7B1;110C 1162 11AC; # (잱; 잱; 잱; 잱; 잱; ) HANGUL SYLLABLE JAENJ
+C7B2;C7B2;110C 1162 11AD;C7B2;110C 1162 11AD; # (잲; 잲; 잲; 잲; 잲; ) HANGUL SYLLABLE JAENH
+C7B3;C7B3;110C 1162 11AE;C7B3;110C 1162 11AE; # (잳; 잳; 잳; 잳; 잳; ) HANGUL SYLLABLE JAED
+C7B4;C7B4;110C 1162 11AF;C7B4;110C 1162 11AF; # (잴; 잴; 잴; 잴; 잴; ) HANGUL SYLLABLE JAEL
+C7B5;C7B5;110C 1162 11B0;C7B5;110C 1162 11B0; # (잵; 잵; 잵; 잵; 잵; ) HANGUL SYLLABLE JAELG
+C7B6;C7B6;110C 1162 11B1;C7B6;110C 1162 11B1; # (잶; 잶; 잶; 잶; 잶; ) HANGUL SYLLABLE JAELM
+C7B7;C7B7;110C 1162 11B2;C7B7;110C 1162 11B2; # (잷; 잷; 잷; 잷; 잷; ) HANGUL SYLLABLE JAELB
+C7B8;C7B8;110C 1162 11B3;C7B8;110C 1162 11B3; # (잸; 잸; 잸; 잸; 잸; ) HANGUL SYLLABLE JAELS
+C7B9;C7B9;110C 1162 11B4;C7B9;110C 1162 11B4; # (잹; 잹; 잹; 잹; 잹; ) HANGUL SYLLABLE JAELT
+C7BA;C7BA;110C 1162 11B5;C7BA;110C 1162 11B5; # (잺; 잺; 잺; 잺; 잺; ) HANGUL SYLLABLE JAELP
+C7BB;C7BB;110C 1162 11B6;C7BB;110C 1162 11B6; # (잻; 잻; 잻; 잻; 잻; ) HANGUL SYLLABLE JAELH
+C7BC;C7BC;110C 1162 11B7;C7BC;110C 1162 11B7; # (잼; 잼; 잼; 잼; 잼; ) HANGUL SYLLABLE JAEM
+C7BD;C7BD;110C 1162 11B8;C7BD;110C 1162 11B8; # (잽; 잽; 잽; 잽; 잽; ) HANGUL SYLLABLE JAEB
+C7BE;C7BE;110C 1162 11B9;C7BE;110C 1162 11B9; # (잾; 잾; 잾; 잾; 잾; ) HANGUL SYLLABLE JAEBS
+C7BF;C7BF;110C 1162 11BA;C7BF;110C 1162 11BA; # (잿; 잿; 잿; 잿; 잿; ) HANGUL SYLLABLE JAES
+C7C0;C7C0;110C 1162 11BB;C7C0;110C 1162 11BB; # (쟀; 쟀; 쟀; 쟀; 쟀; ) HANGUL SYLLABLE JAESS
+C7C1;C7C1;110C 1162 11BC;C7C1;110C 1162 11BC; # (쟁; 쟁; 쟁; 쟁; 쟁; ) HANGUL SYLLABLE JAENG
+C7C2;C7C2;110C 1162 11BD;C7C2;110C 1162 11BD; # (쟂; 쟂; 쟂; 쟂; 쟂; ) HANGUL SYLLABLE JAEJ
+C7C3;C7C3;110C 1162 11BE;C7C3;110C 1162 11BE; # (쟃; 쟃; 쟃; 쟃; 쟃; ) HANGUL SYLLABLE JAEC
+C7C4;C7C4;110C 1162 11BF;C7C4;110C 1162 11BF; # (쟄; 쟄; 쟄; 쟄; 쟄; ) HANGUL SYLLABLE JAEK
+C7C5;C7C5;110C 1162 11C0;C7C5;110C 1162 11C0; # (쟅; 쟅; 쟅; 쟅; 쟅; ) HANGUL SYLLABLE JAET
+C7C6;C7C6;110C 1162 11C1;C7C6;110C 1162 11C1; # (쟆; 쟆; 쟆; 쟆; 쟆; ) HANGUL SYLLABLE JAEP
+C7C7;C7C7;110C 1162 11C2;C7C7;110C 1162 11C2; # (쟇; 쟇; 쟇; 쟇; 쟇; ) HANGUL SYLLABLE JAEH
+C7C8;C7C8;110C 1163;C7C8;110C 1163; # (쟈; 쟈; 쟈; 쟈; 쟈; ) HANGUL SYLLABLE JYA
+C7C9;C7C9;110C 1163 11A8;C7C9;110C 1163 11A8; # (쟉; 쟉; 쟉; 쟉; 쟉; ) HANGUL SYLLABLE JYAG
+C7CA;C7CA;110C 1163 11A9;C7CA;110C 1163 11A9; # (쟊; 쟊; 쟊; 쟊; 쟊; ) HANGUL SYLLABLE JYAGG
+C7CB;C7CB;110C 1163 11AA;C7CB;110C 1163 11AA; # (쟋; 쟋; 쟋; 쟋; 쟋; ) HANGUL SYLLABLE JYAGS
+C7CC;C7CC;110C 1163 11AB;C7CC;110C 1163 11AB; # (쟌; 쟌; 쟌; 쟌; 쟌; ) HANGUL SYLLABLE JYAN
+C7CD;C7CD;110C 1163 11AC;C7CD;110C 1163 11AC; # (쟍; 쟍; 쟍; 쟍; 쟍; ) HANGUL SYLLABLE JYANJ
+C7CE;C7CE;110C 1163 11AD;C7CE;110C 1163 11AD; # (쟎; 쟎; 쟎; 쟎; 쟎; ) HANGUL SYLLABLE JYANH
+C7CF;C7CF;110C 1163 11AE;C7CF;110C 1163 11AE; # (쟏; 쟏; 쟏; 쟏; 쟏; ) HANGUL SYLLABLE JYAD
+C7D0;C7D0;110C 1163 11AF;C7D0;110C 1163 11AF; # (쟐; 쟐; 쟐; 쟐; 쟐; ) HANGUL SYLLABLE JYAL
+C7D1;C7D1;110C 1163 11B0;C7D1;110C 1163 11B0; # (쟑; 쟑; 쟑; 쟑; 쟑; ) HANGUL SYLLABLE JYALG
+C7D2;C7D2;110C 1163 11B1;C7D2;110C 1163 11B1; # (쟒; 쟒; 쟒; 쟒; 쟒; ) HANGUL SYLLABLE JYALM
+C7D3;C7D3;110C 1163 11B2;C7D3;110C 1163 11B2; # (쟓; 쟓; 쟓; 쟓; 쟓; ) HANGUL SYLLABLE JYALB
+C7D4;C7D4;110C 1163 11B3;C7D4;110C 1163 11B3; # (쟔; 쟔; 쟔; 쟔; 쟔; ) HANGUL SYLLABLE JYALS
+C7D5;C7D5;110C 1163 11B4;C7D5;110C 1163 11B4; # (쟕; 쟕; 쟕; 쟕; 쟕; ) HANGUL SYLLABLE JYALT
+C7D6;C7D6;110C 1163 11B5;C7D6;110C 1163 11B5; # (쟖; 쟖; 쟖; 쟖; 쟖; ) HANGUL SYLLABLE JYALP
+C7D7;C7D7;110C 1163 11B6;C7D7;110C 1163 11B6; # (쟗; 쟗; 쟗; 쟗; 쟗; ) HANGUL SYLLABLE JYALH
+C7D8;C7D8;110C 1163 11B7;C7D8;110C 1163 11B7; # (쟘; 쟘; 쟘; 쟘; 쟘; ) HANGUL SYLLABLE JYAM
+C7D9;C7D9;110C 1163 11B8;C7D9;110C 1163 11B8; # (쟙; 쟙; 쟙; 쟙; 쟙; ) HANGUL SYLLABLE JYAB
+C7DA;C7DA;110C 1163 11B9;C7DA;110C 1163 11B9; # (쟚; 쟚; 쟚; 쟚; 쟚; ) HANGUL SYLLABLE JYABS
+C7DB;C7DB;110C 1163 11BA;C7DB;110C 1163 11BA; # (쟛; 쟛; 쟛; 쟛; 쟛; ) HANGUL SYLLABLE JYAS
+C7DC;C7DC;110C 1163 11BB;C7DC;110C 1163 11BB; # (쟜; 쟜; 쟜; 쟜; 쟜; ) HANGUL SYLLABLE JYASS
+C7DD;C7DD;110C 1163 11BC;C7DD;110C 1163 11BC; # (쟝; 쟝; 쟝; 쟝; 쟝; ) HANGUL SYLLABLE JYANG
+C7DE;C7DE;110C 1163 11BD;C7DE;110C 1163 11BD; # (쟞; 쟞; 쟞; 쟞; 쟞; ) HANGUL SYLLABLE JYAJ
+C7DF;C7DF;110C 1163 11BE;C7DF;110C 1163 11BE; # (쟟; 쟟; 쟟; 쟟; 쟟; ) HANGUL SYLLABLE JYAC
+C7E0;C7E0;110C 1163 11BF;C7E0;110C 1163 11BF; # (쟠; 쟠; 쟠; 쟠; 쟠; ) HANGUL SYLLABLE JYAK
+C7E1;C7E1;110C 1163 11C0;C7E1;110C 1163 11C0; # (쟡; 쟡; 쟡; 쟡; 쟡; ) HANGUL SYLLABLE JYAT
+C7E2;C7E2;110C 1163 11C1;C7E2;110C 1163 11C1; # (쟢; 쟢; 쟢; 쟢; 쟢; ) HANGUL SYLLABLE JYAP
+C7E3;C7E3;110C 1163 11C2;C7E3;110C 1163 11C2; # (쟣; 쟣; 쟣; 쟣; 쟣; ) HANGUL SYLLABLE JYAH
+C7E4;C7E4;110C 1164;C7E4;110C 1164; # (쟤; 쟤; 쟤; 쟤; 쟤; ) HANGUL SYLLABLE JYAE
+C7E5;C7E5;110C 1164 11A8;C7E5;110C 1164 11A8; # (쟥; 쟥; 쟥; 쟥; 쟥; ) HANGUL SYLLABLE JYAEG
+C7E6;C7E6;110C 1164 11A9;C7E6;110C 1164 11A9; # (쟦; 쟦; 쟦; 쟦; 쟦; ) HANGUL SYLLABLE JYAEGG
+C7E7;C7E7;110C 1164 11AA;C7E7;110C 1164 11AA; # (쟧; 쟧; 쟧; 쟧; 쟧; ) HANGUL SYLLABLE JYAEGS
+C7E8;C7E8;110C 1164 11AB;C7E8;110C 1164 11AB; # (쟨; 쟨; 쟨; 쟨; 쟨; ) HANGUL SYLLABLE JYAEN
+C7E9;C7E9;110C 1164 11AC;C7E9;110C 1164 11AC; # (쟩; 쟩; 쟩; 쟩; 쟩; ) HANGUL SYLLABLE JYAENJ
+C7EA;C7EA;110C 1164 11AD;C7EA;110C 1164 11AD; # (쟪; 쟪; 쟪; 쟪; 쟪; ) HANGUL SYLLABLE JYAENH
+C7EB;C7EB;110C 1164 11AE;C7EB;110C 1164 11AE; # (쟫; 쟫; 쟫; 쟫; 쟫; ) HANGUL SYLLABLE JYAED
+C7EC;C7EC;110C 1164 11AF;C7EC;110C 1164 11AF; # (쟬; 쟬; 쟬; 쟬; 쟬; ) HANGUL SYLLABLE JYAEL
+C7ED;C7ED;110C 1164 11B0;C7ED;110C 1164 11B0; # (쟭; 쟭; 쟭; 쟭; 쟭; ) HANGUL SYLLABLE JYAELG
+C7EE;C7EE;110C 1164 11B1;C7EE;110C 1164 11B1; # (쟮; 쟮; 쟮; 쟮; 쟮; ) HANGUL SYLLABLE JYAELM
+C7EF;C7EF;110C 1164 11B2;C7EF;110C 1164 11B2; # (쟯; 쟯; 쟯; 쟯; 쟯; ) HANGUL SYLLABLE JYAELB
+C7F0;C7F0;110C 1164 11B3;C7F0;110C 1164 11B3; # (쟰; 쟰; 쟰; 쟰; 쟰; ) HANGUL SYLLABLE JYAELS
+C7F1;C7F1;110C 1164 11B4;C7F1;110C 1164 11B4; # (쟱; 쟱; 쟱; 쟱; 쟱; ) HANGUL SYLLABLE JYAELT
+C7F2;C7F2;110C 1164 11B5;C7F2;110C 1164 11B5; # (쟲; 쟲; 쟲; 쟲; 쟲; ) HANGUL SYLLABLE JYAELP
+C7F3;C7F3;110C 1164 11B6;C7F3;110C 1164 11B6; # (쟳; 쟳; 쟳; 쟳; 쟳; ) HANGUL SYLLABLE JYAELH
+C7F4;C7F4;110C 1164 11B7;C7F4;110C 1164 11B7; # (쟴; 쟴; 쟴; 쟴; 쟴; ) HANGUL SYLLABLE JYAEM
+C7F5;C7F5;110C 1164 11B8;C7F5;110C 1164 11B8; # (쟵; 쟵; 쟵; 쟵; 쟵; ) HANGUL SYLLABLE JYAEB
+C7F6;C7F6;110C 1164 11B9;C7F6;110C 1164 11B9; # (쟶; 쟶; 쟶; 쟶; 쟶; ) HANGUL SYLLABLE JYAEBS
+C7F7;C7F7;110C 1164 11BA;C7F7;110C 1164 11BA; # (쟷; 쟷; 쟷; 쟷; 쟷; ) HANGUL SYLLABLE JYAES
+C7F8;C7F8;110C 1164 11BB;C7F8;110C 1164 11BB; # (쟸; 쟸; 쟸; 쟸; 쟸; ) HANGUL SYLLABLE JYAESS
+C7F9;C7F9;110C 1164 11BC;C7F9;110C 1164 11BC; # (쟹; 쟹; 쟹; 쟹; 쟹; ) HANGUL SYLLABLE JYAENG
+C7FA;C7FA;110C 1164 11BD;C7FA;110C 1164 11BD; # (쟺; 쟺; 쟺; 쟺; 쟺; ) HANGUL SYLLABLE JYAEJ
+C7FB;C7FB;110C 1164 11BE;C7FB;110C 1164 11BE; # (쟻; 쟻; 쟻; 쟻; 쟻; ) HANGUL SYLLABLE JYAEC
+C7FC;C7FC;110C 1164 11BF;C7FC;110C 1164 11BF; # (쟼; 쟼; 쟼; 쟼; 쟼; ) HANGUL SYLLABLE JYAEK
+C7FD;C7FD;110C 1164 11C0;C7FD;110C 1164 11C0; # (쟽; 쟽; 쟽; 쟽; 쟽; ) HANGUL SYLLABLE JYAET
+C7FE;C7FE;110C 1164 11C1;C7FE;110C 1164 11C1; # (쟾; 쟾; 쟾; 쟾; 쟾; ) HANGUL SYLLABLE JYAEP
+C7FF;C7FF;110C 1164 11C2;C7FF;110C 1164 11C2; # (쟿; 쟿; 쟿; 쟿; 쟿; ) HANGUL SYLLABLE JYAEH
+C800;C800;110C 1165;C800;110C 1165; # (저; 저; 저; 저; 저; ) HANGUL SYLLABLE JEO
+C801;C801;110C 1165 11A8;C801;110C 1165 11A8; # (적; 적; 적; 적; 적; ) HANGUL SYLLABLE JEOG
+C802;C802;110C 1165 11A9;C802;110C 1165 11A9; # (젂; 젂; 젂; 젂; 젂; ) HANGUL SYLLABLE JEOGG
+C803;C803;110C 1165 11AA;C803;110C 1165 11AA; # (젃; 젃; 젃; 젃; 젃; ) HANGUL SYLLABLE JEOGS
+C804;C804;110C 1165 11AB;C804;110C 1165 11AB; # (전; 전; 전; 전; 전; ) HANGUL SYLLABLE JEON
+C805;C805;110C 1165 11AC;C805;110C 1165 11AC; # (젅; 젅; 젅; 젅; 젅; ) HANGUL SYLLABLE JEONJ
+C806;C806;110C 1165 11AD;C806;110C 1165 11AD; # (젆; 젆; 젆; 젆; 젆; ) HANGUL SYLLABLE JEONH
+C807;C807;110C 1165 11AE;C807;110C 1165 11AE; # (젇; 젇; 젇; 젇; 젇; ) HANGUL SYLLABLE JEOD
+C808;C808;110C 1165 11AF;C808;110C 1165 11AF; # (절; 절; 절; 절; 절; ) HANGUL SYLLABLE JEOL
+C809;C809;110C 1165 11B0;C809;110C 1165 11B0; # (젉; 젉; 젉; 젉; 젉; ) HANGUL SYLLABLE JEOLG
+C80A;C80A;110C 1165 11B1;C80A;110C 1165 11B1; # (젊; 젊; 젊; 젊; 젊; ) HANGUL SYLLABLE JEOLM
+C80B;C80B;110C 1165 11B2;C80B;110C 1165 11B2; # (젋; 젋; 젋; 젋; 젋; ) HANGUL SYLLABLE JEOLB
+C80C;C80C;110C 1165 11B3;C80C;110C 1165 11B3; # (젌; 젌; 젌; 젌; 젌; ) HANGUL SYLLABLE JEOLS
+C80D;C80D;110C 1165 11B4;C80D;110C 1165 11B4; # (젍; 젍; 젍; 젍; 젍; ) HANGUL SYLLABLE JEOLT
+C80E;C80E;110C 1165 11B5;C80E;110C 1165 11B5; # (젎; 젎; 젎; 젎; 젎; ) HANGUL SYLLABLE JEOLP
+C80F;C80F;110C 1165 11B6;C80F;110C 1165 11B6; # (젏; 젏; 젏; 젏; 젏; ) HANGUL SYLLABLE JEOLH
+C810;C810;110C 1165 11B7;C810;110C 1165 11B7; # (점; 점; 점; 점; 점; ) HANGUL SYLLABLE JEOM
+C811;C811;110C 1165 11B8;C811;110C 1165 11B8; # (접; 접; 접; 접; 접; ) HANGUL SYLLABLE JEOB
+C812;C812;110C 1165 11B9;C812;110C 1165 11B9; # (젒; 젒; 젒; 젒; 젒; ) HANGUL SYLLABLE JEOBS
+C813;C813;110C 1165 11BA;C813;110C 1165 11BA; # (젓; 젓; 젓; 젓; 젓; ) HANGUL SYLLABLE JEOS
+C814;C814;110C 1165 11BB;C814;110C 1165 11BB; # (젔; 젔; 젔; 젔; 젔; ) HANGUL SYLLABLE JEOSS
+C815;C815;110C 1165 11BC;C815;110C 1165 11BC; # (정; 정; 정; 정; 정; ) HANGUL SYLLABLE JEONG
+C816;C816;110C 1165 11BD;C816;110C 1165 11BD; # (젖; 젖; 젖; 젖; 젖; ) HANGUL SYLLABLE JEOJ
+C817;C817;110C 1165 11BE;C817;110C 1165 11BE; # (젗; 젗; 젗; 젗; 젗; ) HANGUL SYLLABLE JEOC
+C818;C818;110C 1165 11BF;C818;110C 1165 11BF; # (젘; 젘; 젘; 젘; 젘; ) HANGUL SYLLABLE JEOK
+C819;C819;110C 1165 11C0;C819;110C 1165 11C0; # (젙; 젙; 젙; 젙; 젙; ) HANGUL SYLLABLE JEOT
+C81A;C81A;110C 1165 11C1;C81A;110C 1165 11C1; # (젚; 젚; 젚; 젚; 젚; ) HANGUL SYLLABLE JEOP
+C81B;C81B;110C 1165 11C2;C81B;110C 1165 11C2; # (젛; 젛; 젛; 젛; 젛; ) HANGUL SYLLABLE JEOH
+C81C;C81C;110C 1166;C81C;110C 1166; # (제; 제; 제; 제; 제; ) HANGUL SYLLABLE JE
+C81D;C81D;110C 1166 11A8;C81D;110C 1166 11A8; # (젝; 젝; 젝; 젝; 젝; ) HANGUL SYLLABLE JEG
+C81E;C81E;110C 1166 11A9;C81E;110C 1166 11A9; # (젞; 젞; 젞; 젞; 젞; ) HANGUL SYLLABLE JEGG
+C81F;C81F;110C 1166 11AA;C81F;110C 1166 11AA; # (젟; 젟; 젟; 젟; 젟; ) HANGUL SYLLABLE JEGS
+C820;C820;110C 1166 11AB;C820;110C 1166 11AB; # (젠; 젠; 젠; 젠; 젠; ) HANGUL SYLLABLE JEN
+C821;C821;110C 1166 11AC;C821;110C 1166 11AC; # (젡; 젡; 젡; 젡; 젡; ) HANGUL SYLLABLE JENJ
+C822;C822;110C 1166 11AD;C822;110C 1166 11AD; # (젢; 젢; 젢; 젢; 젢; ) HANGUL SYLLABLE JENH
+C823;C823;110C 1166 11AE;C823;110C 1166 11AE; # (젣; 젣; 젣; 젣; 젣; ) HANGUL SYLLABLE JED
+C824;C824;110C 1166 11AF;C824;110C 1166 11AF; # (젤; 젤; 젤; 젤; 젤; ) HANGUL SYLLABLE JEL
+C825;C825;110C 1166 11B0;C825;110C 1166 11B0; # (젥; 젥; 젥; 젥; 젥; ) HANGUL SYLLABLE JELG
+C826;C826;110C 1166 11B1;C826;110C 1166 11B1; # (젦; 젦; 젦; 젦; 젦; ) HANGUL SYLLABLE JELM
+C827;C827;110C 1166 11B2;C827;110C 1166 11B2; # (젧; 젧; 젧; 젧; 젧; ) HANGUL SYLLABLE JELB
+C828;C828;110C 1166 11B3;C828;110C 1166 11B3; # (젨; 젨; 젨; 젨; 젨; ) HANGUL SYLLABLE JELS
+C829;C829;110C 1166 11B4;C829;110C 1166 11B4; # (젩; 젩; 젩; 젩; 젩; ) HANGUL SYLLABLE JELT
+C82A;C82A;110C 1166 11B5;C82A;110C 1166 11B5; # (젪; 젪; 젪; 젪; 젪; ) HANGUL SYLLABLE JELP
+C82B;C82B;110C 1166 11B6;C82B;110C 1166 11B6; # (젫; 젫; 젫; 젫; 젫; ) HANGUL SYLLABLE JELH
+C82C;C82C;110C 1166 11B7;C82C;110C 1166 11B7; # (젬; 젬; 젬; 젬; 젬; ) HANGUL SYLLABLE JEM
+C82D;C82D;110C 1166 11B8;C82D;110C 1166 11B8; # (젭; 젭; 젭; 젭; 젭; ) HANGUL SYLLABLE JEB
+C82E;C82E;110C 1166 11B9;C82E;110C 1166 11B9; # (젮; 젮; 젮; 젮; 젮; ) HANGUL SYLLABLE JEBS
+C82F;C82F;110C 1166 11BA;C82F;110C 1166 11BA; # (젯; 젯; 젯; 젯; 젯; ) HANGUL SYLLABLE JES
+C830;C830;110C 1166 11BB;C830;110C 1166 11BB; # (젰; 젰; 젰; 젰; 젰; ) HANGUL SYLLABLE JESS
+C831;C831;110C 1166 11BC;C831;110C 1166 11BC; # (젱; 젱; 젱; 젱; 젱; ) HANGUL SYLLABLE JENG
+C832;C832;110C 1166 11BD;C832;110C 1166 11BD; # (젲; 젲; 젲; 젲; 젲; ) HANGUL SYLLABLE JEJ
+C833;C833;110C 1166 11BE;C833;110C 1166 11BE; # (젳; 젳; 젳; 젳; 젳; ) HANGUL SYLLABLE JEC
+C834;C834;110C 1166 11BF;C834;110C 1166 11BF; # (젴; 젴; 젴; 젴; 젴; ) HANGUL SYLLABLE JEK
+C835;C835;110C 1166 11C0;C835;110C 1166 11C0; # (젵; 젵; 젵; 젵; 젵; ) HANGUL SYLLABLE JET
+C836;C836;110C 1166 11C1;C836;110C 1166 11C1; # (젶; 젶; 젶; 젶; 젶; ) HANGUL SYLLABLE JEP
+C837;C837;110C 1166 11C2;C837;110C 1166 11C2; # (젷; 젷; 젷; 젷; 젷; ) HANGUL SYLLABLE JEH
+C838;C838;110C 1167;C838;110C 1167; # (져; 져; 져; 져; 져; ) HANGUL SYLLABLE JYEO
+C839;C839;110C 1167 11A8;C839;110C 1167 11A8; # (젹; 젹; 젹; 젹; 젹; ) HANGUL SYLLABLE JYEOG
+C83A;C83A;110C 1167 11A9;C83A;110C 1167 11A9; # (젺; 젺; 젺; 젺; 젺; ) HANGUL SYLLABLE JYEOGG
+C83B;C83B;110C 1167 11AA;C83B;110C 1167 11AA; # (젻; 젻; 젻; 젻; 젻; ) HANGUL SYLLABLE JYEOGS
+C83C;C83C;110C 1167 11AB;C83C;110C 1167 11AB; # (젼; 젼; 젼; 젼; 젼; ) HANGUL SYLLABLE JYEON
+C83D;C83D;110C 1167 11AC;C83D;110C 1167 11AC; # (젽; 젽; 젽; 젽; 젽; ) HANGUL SYLLABLE JYEONJ
+C83E;C83E;110C 1167 11AD;C83E;110C 1167 11AD; # (젾; 젾; 젾; 젾; 젾; ) HANGUL SYLLABLE JYEONH
+C83F;C83F;110C 1167 11AE;C83F;110C 1167 11AE; # (젿; 젿; 젿; 젿; 젿; ) HANGUL SYLLABLE JYEOD
+C840;C840;110C 1167 11AF;C840;110C 1167 11AF; # (졀; 졀; 졀; 졀; 졀; ) HANGUL SYLLABLE JYEOL
+C841;C841;110C 1167 11B0;C841;110C 1167 11B0; # (졁; 졁; 졁; 졁; 졁; ) HANGUL SYLLABLE JYEOLG
+C842;C842;110C 1167 11B1;C842;110C 1167 11B1; # (졂; 졂; 졂; 졂; 졂; ) HANGUL SYLLABLE JYEOLM
+C843;C843;110C 1167 11B2;C843;110C 1167 11B2; # (졃; 졃; 졃; 졃; 졃; ) HANGUL SYLLABLE JYEOLB
+C844;C844;110C 1167 11B3;C844;110C 1167 11B3; # (졄; 졄; 졄; 졄; 졄; ) HANGUL SYLLABLE JYEOLS
+C845;C845;110C 1167 11B4;C845;110C 1167 11B4; # (졅; 졅; 졅; 졅; 졅; ) HANGUL SYLLABLE JYEOLT
+C846;C846;110C 1167 11B5;C846;110C 1167 11B5; # (졆; 졆; 졆; 졆; 졆; ) HANGUL SYLLABLE JYEOLP
+C847;C847;110C 1167 11B6;C847;110C 1167 11B6; # (졇; 졇; 졇; 졇; 졇; ) HANGUL SYLLABLE JYEOLH
+C848;C848;110C 1167 11B7;C848;110C 1167 11B7; # (졈; 졈; 졈; 졈; 졈; ) HANGUL SYLLABLE JYEOM
+C849;C849;110C 1167 11B8;C849;110C 1167 11B8; # (졉; 졉; 졉; 졉; 졉; ) HANGUL SYLLABLE JYEOB
+C84A;C84A;110C 1167 11B9;C84A;110C 1167 11B9; # (졊; 졊; 졊; 졊; 졊; ) HANGUL SYLLABLE JYEOBS
+C84B;C84B;110C 1167 11BA;C84B;110C 1167 11BA; # (졋; 졋; 졋; 졋; 졋; ) HANGUL SYLLABLE JYEOS
+C84C;C84C;110C 1167 11BB;C84C;110C 1167 11BB; # (졌; 졌; 졌; 졌; 졌; ) HANGUL SYLLABLE JYEOSS
+C84D;C84D;110C 1167 11BC;C84D;110C 1167 11BC; # (졍; 졍; 졍; 졍; 졍; ) HANGUL SYLLABLE JYEONG
+C84E;C84E;110C 1167 11BD;C84E;110C 1167 11BD; # (졎; 졎; 졎; 졎; 졎; ) HANGUL SYLLABLE JYEOJ
+C84F;C84F;110C 1167 11BE;C84F;110C 1167 11BE; # (졏; 졏; 졏; 졏; 졏; ) HANGUL SYLLABLE JYEOC
+C850;C850;110C 1167 11BF;C850;110C 1167 11BF; # (졐; 졐; 졐; 졐; 졐; ) HANGUL SYLLABLE JYEOK
+C851;C851;110C 1167 11C0;C851;110C 1167 11C0; # (졑; 졑; 졑; 졑; 졑; ) HANGUL SYLLABLE JYEOT
+C852;C852;110C 1167 11C1;C852;110C 1167 11C1; # (졒; 졒; 졒; 졒; 졒; ) HANGUL SYLLABLE JYEOP
+C853;C853;110C 1167 11C2;C853;110C 1167 11C2; # (졓; 졓; 졓; 졓; 졓; ) HANGUL SYLLABLE JYEOH
+C854;C854;110C 1168;C854;110C 1168; # (졔; 졔; 졔; 졔; 졔; ) HANGUL SYLLABLE JYE
+C855;C855;110C 1168 11A8;C855;110C 1168 11A8; # (졕; 졕; 졕; 졕; 졕; ) HANGUL SYLLABLE JYEG
+C856;C856;110C 1168 11A9;C856;110C 1168 11A9; # (졖; 졖; 졖; 졖; 졖; ) HANGUL SYLLABLE JYEGG
+C857;C857;110C 1168 11AA;C857;110C 1168 11AA; # (졗; 졗; 졗; 졗; 졗; ) HANGUL SYLLABLE JYEGS
+C858;C858;110C 1168 11AB;C858;110C 1168 11AB; # (졘; 졘; 졘; 졘; 졘; ) HANGUL SYLLABLE JYEN
+C859;C859;110C 1168 11AC;C859;110C 1168 11AC; # (졙; 졙; 졙; 졙; 졙; ) HANGUL SYLLABLE JYENJ
+C85A;C85A;110C 1168 11AD;C85A;110C 1168 11AD; # (졚; 졚; 졚; 졚; 졚; ) HANGUL SYLLABLE JYENH
+C85B;C85B;110C 1168 11AE;C85B;110C 1168 11AE; # (졛; 졛; 졛; 졛; 졛; ) HANGUL SYLLABLE JYED
+C85C;C85C;110C 1168 11AF;C85C;110C 1168 11AF; # (졜; 졜; 졜; 졜; 졜; ) HANGUL SYLLABLE JYEL
+C85D;C85D;110C 1168 11B0;C85D;110C 1168 11B0; # (졝; 졝; 졝; 졝; 졝; ) HANGUL SYLLABLE JYELG
+C85E;C85E;110C 1168 11B1;C85E;110C 1168 11B1; # (졞; 졞; 졞; 졞; 졞; ) HANGUL SYLLABLE JYELM
+C85F;C85F;110C 1168 11B2;C85F;110C 1168 11B2; # (졟; 졟; 졟; 졟; 졟; ) HANGUL SYLLABLE JYELB
+C860;C860;110C 1168 11B3;C860;110C 1168 11B3; # (졠; 졠; 졠; 졠; 졠; ) HANGUL SYLLABLE JYELS
+C861;C861;110C 1168 11B4;C861;110C 1168 11B4; # (졡; 졡; 졡; 졡; 졡; ) HANGUL SYLLABLE JYELT
+C862;C862;110C 1168 11B5;C862;110C 1168 11B5; # (졢; 졢; 졢; 졢; 졢; ) HANGUL SYLLABLE JYELP
+C863;C863;110C 1168 11B6;C863;110C 1168 11B6; # (졣; 졣; 졣; 졣; 졣; ) HANGUL SYLLABLE JYELH
+C864;C864;110C 1168 11B7;C864;110C 1168 11B7; # (졤; 졤; 졤; 졤; 졤; ) HANGUL SYLLABLE JYEM
+C865;C865;110C 1168 11B8;C865;110C 1168 11B8; # (졥; 졥; 졥; 졥; 졥; ) HANGUL SYLLABLE JYEB
+C866;C866;110C 1168 11B9;C866;110C 1168 11B9; # (졦; 졦; 졦; 졦; 졦; ) HANGUL SYLLABLE JYEBS
+C867;C867;110C 1168 11BA;C867;110C 1168 11BA; # (졧; 졧; 졧; 졧; 졧; ) HANGUL SYLLABLE JYES
+C868;C868;110C 1168 11BB;C868;110C 1168 11BB; # (졨; 졨; 졨; 졨; 졨; ) HANGUL SYLLABLE JYESS
+C869;C869;110C 1168 11BC;C869;110C 1168 11BC; # (졩; 졩; 졩; 졩; 졩; ) HANGUL SYLLABLE JYENG
+C86A;C86A;110C 1168 11BD;C86A;110C 1168 11BD; # (졪; 졪; 졪; 졪; 졪; ) HANGUL SYLLABLE JYEJ
+C86B;C86B;110C 1168 11BE;C86B;110C 1168 11BE; # (졫; 졫; 졫; 졫; 졫; ) HANGUL SYLLABLE JYEC
+C86C;C86C;110C 1168 11BF;C86C;110C 1168 11BF; # (졬; 졬; 졬; 졬; 졬; ) HANGUL SYLLABLE JYEK
+C86D;C86D;110C 1168 11C0;C86D;110C 1168 11C0; # (졭; 졭; 졭; 졭; 졭; ) HANGUL SYLLABLE JYET
+C86E;C86E;110C 1168 11C1;C86E;110C 1168 11C1; # (졮; 졮; 졮; 졮; 졮; ) HANGUL SYLLABLE JYEP
+C86F;C86F;110C 1168 11C2;C86F;110C 1168 11C2; # (졯; 졯; 졯; 졯; 졯; ) HANGUL SYLLABLE JYEH
+C870;C870;110C 1169;C870;110C 1169; # (조; 조; 조; 조; 조; ) HANGUL SYLLABLE JO
+C871;C871;110C 1169 11A8;C871;110C 1169 11A8; # (족; 족; 족; 족; 족; ) HANGUL SYLLABLE JOG
+C872;C872;110C 1169 11A9;C872;110C 1169 11A9; # (졲; 졲; 졲; 졲; 졲; ) HANGUL SYLLABLE JOGG
+C873;C873;110C 1169 11AA;C873;110C 1169 11AA; # (졳; 졳; 졳; 졳; 졳; ) HANGUL SYLLABLE JOGS
+C874;C874;110C 1169 11AB;C874;110C 1169 11AB; # (존; 존; 존; 존; 존; ) HANGUL SYLLABLE JON
+C875;C875;110C 1169 11AC;C875;110C 1169 11AC; # (졵; 졵; 졵; 졵; 졵; ) HANGUL SYLLABLE JONJ
+C876;C876;110C 1169 11AD;C876;110C 1169 11AD; # (졶; 졶; 졶; 졶; 졶; ) HANGUL SYLLABLE JONH
+C877;C877;110C 1169 11AE;C877;110C 1169 11AE; # (졷; 졷; 졷; 졷; 졷; ) HANGUL SYLLABLE JOD
+C878;C878;110C 1169 11AF;C878;110C 1169 11AF; # (졸; 졸; 졸; 졸; 졸; ) HANGUL SYLLABLE JOL
+C879;C879;110C 1169 11B0;C879;110C 1169 11B0; # (졹; 졹; 졹; 졹; 졹; ) HANGUL SYLLABLE JOLG
+C87A;C87A;110C 1169 11B1;C87A;110C 1169 11B1; # (졺; 졺; 졺; 졺; 졺; ) HANGUL SYLLABLE JOLM
+C87B;C87B;110C 1169 11B2;C87B;110C 1169 11B2; # (졻; 졻; 졻; 졻; 졻; ) HANGUL SYLLABLE JOLB
+C87C;C87C;110C 1169 11B3;C87C;110C 1169 11B3; # (졼; 졼; 졼; 졼; 졼; ) HANGUL SYLLABLE JOLS
+C87D;C87D;110C 1169 11B4;C87D;110C 1169 11B4; # (졽; 졽; 졽; 졽; 졽; ) HANGUL SYLLABLE JOLT
+C87E;C87E;110C 1169 11B5;C87E;110C 1169 11B5; # (졾; 졾; 졾; 졾; 졾; ) HANGUL SYLLABLE JOLP
+C87F;C87F;110C 1169 11B6;C87F;110C 1169 11B6; # (졿; 졿; 졿; 졿; 졿; ) HANGUL SYLLABLE JOLH
+C880;C880;110C 1169 11B7;C880;110C 1169 11B7; # (좀; 좀; 좀; 좀; 좀; ) HANGUL SYLLABLE JOM
+C881;C881;110C 1169 11B8;C881;110C 1169 11B8; # (좁; 좁; 좁; 좁; 좁; ) HANGUL SYLLABLE JOB
+C882;C882;110C 1169 11B9;C882;110C 1169 11B9; # (좂; 좂; 좂; 좂; 좂; ) HANGUL SYLLABLE JOBS
+C883;C883;110C 1169 11BA;C883;110C 1169 11BA; # (좃; 좃; 좃; 좃; 좃; ) HANGUL SYLLABLE JOS
+C884;C884;110C 1169 11BB;C884;110C 1169 11BB; # (좄; 좄; 좄; 좄; 좄; ) HANGUL SYLLABLE JOSS
+C885;C885;110C 1169 11BC;C885;110C 1169 11BC; # (종; 종; 종; 종; 종; ) HANGUL SYLLABLE JONG
+C886;C886;110C 1169 11BD;C886;110C 1169 11BD; # (좆; 좆; 좆; 좆; 좆; ) HANGUL SYLLABLE JOJ
+C887;C887;110C 1169 11BE;C887;110C 1169 11BE; # (좇; 좇; 좇; 좇; 좇; ) HANGUL SYLLABLE JOC
+C888;C888;110C 1169 11BF;C888;110C 1169 11BF; # (좈; 좈; 좈; 좈; 좈; ) HANGUL SYLLABLE JOK
+C889;C889;110C 1169 11C0;C889;110C 1169 11C0; # (좉; 좉; 좉; 좉; 좉; ) HANGUL SYLLABLE JOT
+C88A;C88A;110C 1169 11C1;C88A;110C 1169 11C1; # (좊; 좊; 좊; 좊; 좊; ) HANGUL SYLLABLE JOP
+C88B;C88B;110C 1169 11C2;C88B;110C 1169 11C2; # (좋; 좋; 좋; 좋; 좋; ) HANGUL SYLLABLE JOH
+C88C;C88C;110C 116A;C88C;110C 116A; # (좌; 좌; 좌; 좌; 좌; ) HANGUL SYLLABLE JWA
+C88D;C88D;110C 116A 11A8;C88D;110C 116A 11A8; # (좍; 좍; 좍; 좍; 좍; ) HANGUL SYLLABLE JWAG
+C88E;C88E;110C 116A 11A9;C88E;110C 116A 11A9; # (좎; 좎; 좎; 좎; 좎; ) HANGUL SYLLABLE JWAGG
+C88F;C88F;110C 116A 11AA;C88F;110C 116A 11AA; # (좏; 좏; 좏; 좏; 좏; ) HANGUL SYLLABLE JWAGS
+C890;C890;110C 116A 11AB;C890;110C 116A 11AB; # (좐; 좐; 좐; 좐; 좐; ) HANGUL SYLLABLE JWAN
+C891;C891;110C 116A 11AC;C891;110C 116A 11AC; # (좑; 좑; 좑; 좑; 좑; ) HANGUL SYLLABLE JWANJ
+C892;C892;110C 116A 11AD;C892;110C 116A 11AD; # (좒; 좒; 좒; 좒; 좒; ) HANGUL SYLLABLE JWANH
+C893;C893;110C 116A 11AE;C893;110C 116A 11AE; # (좓; 좓; 좓; 좓; 좓; ) HANGUL SYLLABLE JWAD
+C894;C894;110C 116A 11AF;C894;110C 116A 11AF; # (좔; 좔; 좔; 좔; 좔; ) HANGUL SYLLABLE JWAL
+C895;C895;110C 116A 11B0;C895;110C 116A 11B0; # (좕; 좕; 좕; 좕; 좕; ) HANGUL SYLLABLE JWALG
+C896;C896;110C 116A 11B1;C896;110C 116A 11B1; # (좖; 좖; 좖; 좖; 좖; ) HANGUL SYLLABLE JWALM
+C897;C897;110C 116A 11B2;C897;110C 116A 11B2; # (좗; 좗; 좗; 좗; 좗; ) HANGUL SYLLABLE JWALB
+C898;C898;110C 116A 11B3;C898;110C 116A 11B3; # (좘; 좘; 좘; 좘; 좘; ) HANGUL SYLLABLE JWALS
+C899;C899;110C 116A 11B4;C899;110C 116A 11B4; # (좙; 좙; 좙; 좙; 좙; ) HANGUL SYLLABLE JWALT
+C89A;C89A;110C 116A 11B5;C89A;110C 116A 11B5; # (좚; 좚; 좚; 좚; 좚; ) HANGUL SYLLABLE JWALP
+C89B;C89B;110C 116A 11B6;C89B;110C 116A 11B6; # (좛; 좛; 좛; 좛; 좛; ) HANGUL SYLLABLE JWALH
+C89C;C89C;110C 116A 11B7;C89C;110C 116A 11B7; # (좜; 좜; 좜; 좜; 좜; ) HANGUL SYLLABLE JWAM
+C89D;C89D;110C 116A 11B8;C89D;110C 116A 11B8; # (좝; 좝; 좝; 좝; 좝; ) HANGUL SYLLABLE JWAB
+C89E;C89E;110C 116A 11B9;C89E;110C 116A 11B9; # (좞; 좞; 좞; 좞; 좞; ) HANGUL SYLLABLE JWABS
+C89F;C89F;110C 116A 11BA;C89F;110C 116A 11BA; # (좟; 좟; 좟; 좟; 좟; ) HANGUL SYLLABLE JWAS
+C8A0;C8A0;110C 116A 11BB;C8A0;110C 116A 11BB; # (좠; 좠; 좠; 좠; 좠; ) HANGUL SYLLABLE JWASS
+C8A1;C8A1;110C 116A 11BC;C8A1;110C 116A 11BC; # (좡; 좡; 좡; 좡; 좡; ) HANGUL SYLLABLE JWANG
+C8A2;C8A2;110C 116A 11BD;C8A2;110C 116A 11BD; # (좢; 좢; 좢; 좢; 좢; ) HANGUL SYLLABLE JWAJ
+C8A3;C8A3;110C 116A 11BE;C8A3;110C 116A 11BE; # (좣; 좣; 좣; 좣; 좣; ) HANGUL SYLLABLE JWAC
+C8A4;C8A4;110C 116A 11BF;C8A4;110C 116A 11BF; # (좤; 좤; 좤; 좤; 좤; ) HANGUL SYLLABLE JWAK
+C8A5;C8A5;110C 116A 11C0;C8A5;110C 116A 11C0; # (좥; 좥; 좥; 좥; 좥; ) HANGUL SYLLABLE JWAT
+C8A6;C8A6;110C 116A 11C1;C8A6;110C 116A 11C1; # (좦; 좦; 좦; 좦; 좦; ) HANGUL SYLLABLE JWAP
+C8A7;C8A7;110C 116A 11C2;C8A7;110C 116A 11C2; # (좧; 좧; 좧; 좧; 좧; ) HANGUL SYLLABLE JWAH
+C8A8;C8A8;110C 116B;C8A8;110C 116B; # (좨; 좨; 좨; 좨; 좨; ) HANGUL SYLLABLE JWAE
+C8A9;C8A9;110C 116B 11A8;C8A9;110C 116B 11A8; # (좩; 좩; 좩; 좩; 좩; ) HANGUL SYLLABLE JWAEG
+C8AA;C8AA;110C 116B 11A9;C8AA;110C 116B 11A9; # (좪; 좪; 좪; 좪; 좪; ) HANGUL SYLLABLE JWAEGG
+C8AB;C8AB;110C 116B 11AA;C8AB;110C 116B 11AA; # (좫; 좫; 좫; 좫; 좫; ) HANGUL SYLLABLE JWAEGS
+C8AC;C8AC;110C 116B 11AB;C8AC;110C 116B 11AB; # (좬; 좬; 좬; 좬; 좬; ) HANGUL SYLLABLE JWAEN
+C8AD;C8AD;110C 116B 11AC;C8AD;110C 116B 11AC; # (좭; 좭; 좭; 좭; 좭; ) HANGUL SYLLABLE JWAENJ
+C8AE;C8AE;110C 116B 11AD;C8AE;110C 116B 11AD; # (좮; 좮; 좮; 좮; 좮; ) HANGUL SYLLABLE JWAENH
+C8AF;C8AF;110C 116B 11AE;C8AF;110C 116B 11AE; # (좯; 좯; 좯; 좯; 좯; ) HANGUL SYLLABLE JWAED
+C8B0;C8B0;110C 116B 11AF;C8B0;110C 116B 11AF; # (좰; 좰; 좰; 좰; 좰; ) HANGUL SYLLABLE JWAEL
+C8B1;C8B1;110C 116B 11B0;C8B1;110C 116B 11B0; # (좱; 좱; 좱; 좱; 좱; ) HANGUL SYLLABLE JWAELG
+C8B2;C8B2;110C 116B 11B1;C8B2;110C 116B 11B1; # (좲; 좲; 좲; 좲; 좲; ) HANGUL SYLLABLE JWAELM
+C8B3;C8B3;110C 116B 11B2;C8B3;110C 116B 11B2; # (좳; 좳; 좳; 좳; 좳; ) HANGUL SYLLABLE JWAELB
+C8B4;C8B4;110C 116B 11B3;C8B4;110C 116B 11B3; # (좴; 좴; 좴; 좴; 좴; ) HANGUL SYLLABLE JWAELS
+C8B5;C8B5;110C 116B 11B4;C8B5;110C 116B 11B4; # (좵; 좵; 좵; 좵; 좵; ) HANGUL SYLLABLE JWAELT
+C8B6;C8B6;110C 116B 11B5;C8B6;110C 116B 11B5; # (좶; 좶; 좶; 좶; 좶; ) HANGUL SYLLABLE JWAELP
+C8B7;C8B7;110C 116B 11B6;C8B7;110C 116B 11B6; # (좷; 좷; 좷; 좷; 좷; ) HANGUL SYLLABLE JWAELH
+C8B8;C8B8;110C 116B 11B7;C8B8;110C 116B 11B7; # (좸; 좸; 좸; 좸; 좸; ) HANGUL SYLLABLE JWAEM
+C8B9;C8B9;110C 116B 11B8;C8B9;110C 116B 11B8; # (좹; 좹; 좹; 좹; 좹; ) HANGUL SYLLABLE JWAEB
+C8BA;C8BA;110C 116B 11B9;C8BA;110C 116B 11B9; # (좺; 좺; 좺; 좺; 좺; ) HANGUL SYLLABLE JWAEBS
+C8BB;C8BB;110C 116B 11BA;C8BB;110C 116B 11BA; # (좻; 좻; 좻; 좻; 좻; ) HANGUL SYLLABLE JWAES
+C8BC;C8BC;110C 116B 11BB;C8BC;110C 116B 11BB; # (좼; 좼; 좼; 좼; 좼; ) HANGUL SYLLABLE JWAESS
+C8BD;C8BD;110C 116B 11BC;C8BD;110C 116B 11BC; # (좽; 좽; 좽; 좽; 좽; ) HANGUL SYLLABLE JWAENG
+C8BE;C8BE;110C 116B 11BD;C8BE;110C 116B 11BD; # (좾; 좾; 좾; 좾; 좾; ) HANGUL SYLLABLE JWAEJ
+C8BF;C8BF;110C 116B 11BE;C8BF;110C 116B 11BE; # (좿; 좿; 좿; 좿; 좿; ) HANGUL SYLLABLE JWAEC
+C8C0;C8C0;110C 116B 11BF;C8C0;110C 116B 11BF; # (죀; 죀; 죀; 죀; 죀; ) HANGUL SYLLABLE JWAEK
+C8C1;C8C1;110C 116B 11C0;C8C1;110C 116B 11C0; # (죁; 죁; 죁; 죁; 죁; ) HANGUL SYLLABLE JWAET
+C8C2;C8C2;110C 116B 11C1;C8C2;110C 116B 11C1; # (죂; 죂; 죂; 죂; 죂; ) HANGUL SYLLABLE JWAEP
+C8C3;C8C3;110C 116B 11C2;C8C3;110C 116B 11C2; # (죃; 죃; 죃; 죃; 죃; ) HANGUL SYLLABLE JWAEH
+C8C4;C8C4;110C 116C;C8C4;110C 116C; # (죄; 죄; 죄; 죄; 죄; ) HANGUL SYLLABLE JOE
+C8C5;C8C5;110C 116C 11A8;C8C5;110C 116C 11A8; # (죅; 죅; 죅; 죅; 죅; ) HANGUL SYLLABLE JOEG
+C8C6;C8C6;110C 116C 11A9;C8C6;110C 116C 11A9; # (죆; 죆; 죆; 죆; 죆; ) HANGUL SYLLABLE JOEGG
+C8C7;C8C7;110C 116C 11AA;C8C7;110C 116C 11AA; # (죇; 죇; 죇; 죇; 죇; ) HANGUL SYLLABLE JOEGS
+C8C8;C8C8;110C 116C 11AB;C8C8;110C 116C 11AB; # (죈; 죈; 죈; 죈; 죈; ) HANGUL SYLLABLE JOEN
+C8C9;C8C9;110C 116C 11AC;C8C9;110C 116C 11AC; # (죉; 죉; 죉; 죉; 죉; ) HANGUL SYLLABLE JOENJ
+C8CA;C8CA;110C 116C 11AD;C8CA;110C 116C 11AD; # (죊; 죊; 죊; 죊; 죊; ) HANGUL SYLLABLE JOENH
+C8CB;C8CB;110C 116C 11AE;C8CB;110C 116C 11AE; # (죋; 죋; 죋; 죋; 죋; ) HANGUL SYLLABLE JOED
+C8CC;C8CC;110C 116C 11AF;C8CC;110C 116C 11AF; # (죌; 죌; 죌; 죌; 죌; ) HANGUL SYLLABLE JOEL
+C8CD;C8CD;110C 116C 11B0;C8CD;110C 116C 11B0; # (죍; 죍; 죍; 죍; 죍; ) HANGUL SYLLABLE JOELG
+C8CE;C8CE;110C 116C 11B1;C8CE;110C 116C 11B1; # (죎; 죎; 죎; 죎; 죎; ) HANGUL SYLLABLE JOELM
+C8CF;C8CF;110C 116C 11B2;C8CF;110C 116C 11B2; # (죏; 죏; 죏; 죏; 죏; ) HANGUL SYLLABLE JOELB
+C8D0;C8D0;110C 116C 11B3;C8D0;110C 116C 11B3; # (죐; 죐; 죐; 죐; 죐; ) HANGUL SYLLABLE JOELS
+C8D1;C8D1;110C 116C 11B4;C8D1;110C 116C 11B4; # (죑; 죑; 죑; 죑; 죑; ) HANGUL SYLLABLE JOELT
+C8D2;C8D2;110C 116C 11B5;C8D2;110C 116C 11B5; # (죒; 죒; 죒; 죒; 죒; ) HANGUL SYLLABLE JOELP
+C8D3;C8D3;110C 116C 11B6;C8D3;110C 116C 11B6; # (죓; 죓; 죓; 죓; 죓; ) HANGUL SYLLABLE JOELH
+C8D4;C8D4;110C 116C 11B7;C8D4;110C 116C 11B7; # (죔; 죔; 죔; 죔; 죔; ) HANGUL SYLLABLE JOEM
+C8D5;C8D5;110C 116C 11B8;C8D5;110C 116C 11B8; # (죕; 죕; 죕; 죕; 죕; ) HANGUL SYLLABLE JOEB
+C8D6;C8D6;110C 116C 11B9;C8D6;110C 116C 11B9; # (죖; 죖; 죖; 죖; 죖; ) HANGUL SYLLABLE JOEBS
+C8D7;C8D7;110C 116C 11BA;C8D7;110C 116C 11BA; # (죗; 죗; 죗; 죗; 죗; ) HANGUL SYLLABLE JOES
+C8D8;C8D8;110C 116C 11BB;C8D8;110C 116C 11BB; # (죘; 죘; 죘; 죘; 죘; ) HANGUL SYLLABLE JOESS
+C8D9;C8D9;110C 116C 11BC;C8D9;110C 116C 11BC; # (죙; 죙; 죙; 죙; 죙; ) HANGUL SYLLABLE JOENG
+C8DA;C8DA;110C 116C 11BD;C8DA;110C 116C 11BD; # (죚; 죚; 죚; 죚; 죚; ) HANGUL SYLLABLE JOEJ
+C8DB;C8DB;110C 116C 11BE;C8DB;110C 116C 11BE; # (죛; 죛; 죛; 죛; 죛; ) HANGUL SYLLABLE JOEC
+C8DC;C8DC;110C 116C 11BF;C8DC;110C 116C 11BF; # (죜; 죜; 죜; 죜; 죜; ) HANGUL SYLLABLE JOEK
+C8DD;C8DD;110C 116C 11C0;C8DD;110C 116C 11C0; # (죝; 죝; 죝; 죝; 죝; ) HANGUL SYLLABLE JOET
+C8DE;C8DE;110C 116C 11C1;C8DE;110C 116C 11C1; # (죞; 죞; 죞; 죞; 죞; ) HANGUL SYLLABLE JOEP
+C8DF;C8DF;110C 116C 11C2;C8DF;110C 116C 11C2; # (죟; 죟; 죟; 죟; 죟; ) HANGUL SYLLABLE JOEH
+C8E0;C8E0;110C 116D;C8E0;110C 116D; # (죠; 죠; 죠; 죠; 죠; ) HANGUL SYLLABLE JYO
+C8E1;C8E1;110C 116D 11A8;C8E1;110C 116D 11A8; # (죡; 죡; 죡; 죡; 죡; ) HANGUL SYLLABLE JYOG
+C8E2;C8E2;110C 116D 11A9;C8E2;110C 116D 11A9; # (죢; 죢; 죢; 죢; 죢; ) HANGUL SYLLABLE JYOGG
+C8E3;C8E3;110C 116D 11AA;C8E3;110C 116D 11AA; # (죣; 죣; 죣; 죣; 죣; ) HANGUL SYLLABLE JYOGS
+C8E4;C8E4;110C 116D 11AB;C8E4;110C 116D 11AB; # (죤; 죤; 죤; 죤; 죤; ) HANGUL SYLLABLE JYON
+C8E5;C8E5;110C 116D 11AC;C8E5;110C 116D 11AC; # (죥; 죥; 죥; 죥; 죥; ) HANGUL SYLLABLE JYONJ
+C8E6;C8E6;110C 116D 11AD;C8E6;110C 116D 11AD; # (죦; 죦; 죦; 죦; 죦; ) HANGUL SYLLABLE JYONH
+C8E7;C8E7;110C 116D 11AE;C8E7;110C 116D 11AE; # (죧; 죧; 죧; 죧; 죧; ) HANGUL SYLLABLE JYOD
+C8E8;C8E8;110C 116D 11AF;C8E8;110C 116D 11AF; # (죨; 죨; 죨; 죨; 죨; ) HANGUL SYLLABLE JYOL
+C8E9;C8E9;110C 116D 11B0;C8E9;110C 116D 11B0; # (죩; 죩; 죩; 죩; 죩; ) HANGUL SYLLABLE JYOLG
+C8EA;C8EA;110C 116D 11B1;C8EA;110C 116D 11B1; # (죪; 죪; 죪; 죪; 죪; ) HANGUL SYLLABLE JYOLM
+C8EB;C8EB;110C 116D 11B2;C8EB;110C 116D 11B2; # (죫; 죫; 죫; 죫; 죫; ) HANGUL SYLLABLE JYOLB
+C8EC;C8EC;110C 116D 11B3;C8EC;110C 116D 11B3; # (죬; 죬; 죬; 죬; 죬; ) HANGUL SYLLABLE JYOLS
+C8ED;C8ED;110C 116D 11B4;C8ED;110C 116D 11B4; # (죭; 죭; 죭; 죭; 죭; ) HANGUL SYLLABLE JYOLT
+C8EE;C8EE;110C 116D 11B5;C8EE;110C 116D 11B5; # (죮; 죮; 죮; 죮; 죮; ) HANGUL SYLLABLE JYOLP
+C8EF;C8EF;110C 116D 11B6;C8EF;110C 116D 11B6; # (죯; 죯; 죯; 죯; 죯; ) HANGUL SYLLABLE JYOLH
+C8F0;C8F0;110C 116D 11B7;C8F0;110C 116D 11B7; # (죰; 죰; 죰; 죰; 죰; ) HANGUL SYLLABLE JYOM
+C8F1;C8F1;110C 116D 11B8;C8F1;110C 116D 11B8; # (죱; 죱; 죱; 죱; 죱; ) HANGUL SYLLABLE JYOB
+C8F2;C8F2;110C 116D 11B9;C8F2;110C 116D 11B9; # (죲; 죲; 죲; 죲; 죲; ) HANGUL SYLLABLE JYOBS
+C8F3;C8F3;110C 116D 11BA;C8F3;110C 116D 11BA; # (죳; 죳; 죳; 죳; 죳; ) HANGUL SYLLABLE JYOS
+C8F4;C8F4;110C 116D 11BB;C8F4;110C 116D 11BB; # (죴; 죴; 죴; 죴; 죴; ) HANGUL SYLLABLE JYOSS
+C8F5;C8F5;110C 116D 11BC;C8F5;110C 116D 11BC; # (죵; 죵; 죵; 죵; 죵; ) HANGUL SYLLABLE JYONG
+C8F6;C8F6;110C 116D 11BD;C8F6;110C 116D 11BD; # (죶; 죶; 죶; 죶; 죶; ) HANGUL SYLLABLE JYOJ
+C8F7;C8F7;110C 116D 11BE;C8F7;110C 116D 11BE; # (죷; 죷; 죷; 죷; 죷; ) HANGUL SYLLABLE JYOC
+C8F8;C8F8;110C 116D 11BF;C8F8;110C 116D 11BF; # (죸; 죸; 죸; 죸; 죸; ) HANGUL SYLLABLE JYOK
+C8F9;C8F9;110C 116D 11C0;C8F9;110C 116D 11C0; # (죹; 죹; 죹; 죹; 죹; ) HANGUL SYLLABLE JYOT
+C8FA;C8FA;110C 116D 11C1;C8FA;110C 116D 11C1; # (죺; 죺; 죺; 죺; 죺; ) HANGUL SYLLABLE JYOP
+C8FB;C8FB;110C 116D 11C2;C8FB;110C 116D 11C2; # (죻; 죻; 죻; 죻; 죻; ) HANGUL SYLLABLE JYOH
+C8FC;C8FC;110C 116E;C8FC;110C 116E; # (주; 주; 주; 주; 주; ) HANGUL SYLLABLE JU
+C8FD;C8FD;110C 116E 11A8;C8FD;110C 116E 11A8; # (죽; 죽; 죽; 죽; 죽; ) HANGUL SYLLABLE JUG
+C8FE;C8FE;110C 116E 11A9;C8FE;110C 116E 11A9; # (죾; 죾; 죾; 죾; 죾; ) HANGUL SYLLABLE JUGG
+C8FF;C8FF;110C 116E 11AA;C8FF;110C 116E 11AA; # (죿; 죿; 죿; 죿; 죿; ) HANGUL SYLLABLE JUGS
+C900;C900;110C 116E 11AB;C900;110C 116E 11AB; # (준; 준; 준; 준; 준; ) HANGUL SYLLABLE JUN
+C901;C901;110C 116E 11AC;C901;110C 116E 11AC; # (줁; 줁; 줁; 줁; 줁; ) HANGUL SYLLABLE JUNJ
+C902;C902;110C 116E 11AD;C902;110C 116E 11AD; # (줂; 줂; 줂; 줂; 줂; ) HANGUL SYLLABLE JUNH
+C903;C903;110C 116E 11AE;C903;110C 116E 11AE; # (줃; 줃; 줃; 줃; 줃; ) HANGUL SYLLABLE JUD
+C904;C904;110C 116E 11AF;C904;110C 116E 11AF; # (줄; 줄; 줄; 줄; 줄; ) HANGUL SYLLABLE JUL
+C905;C905;110C 116E 11B0;C905;110C 116E 11B0; # (줅; 줅; 줅; 줅; 줅; ) HANGUL SYLLABLE JULG
+C906;C906;110C 116E 11B1;C906;110C 116E 11B1; # (줆; 줆; 줆; 줆; 줆; ) HANGUL SYLLABLE JULM
+C907;C907;110C 116E 11B2;C907;110C 116E 11B2; # (줇; 줇; 줇; 줇; 줇; ) HANGUL SYLLABLE JULB
+C908;C908;110C 116E 11B3;C908;110C 116E 11B3; # (줈; 줈; 줈; 줈; 줈; ) HANGUL SYLLABLE JULS
+C909;C909;110C 116E 11B4;C909;110C 116E 11B4; # (줉; 줉; 줉; 줉; 줉; ) HANGUL SYLLABLE JULT
+C90A;C90A;110C 116E 11B5;C90A;110C 116E 11B5; # (줊; 줊; 줊; 줊; 줊; ) HANGUL SYLLABLE JULP
+C90B;C90B;110C 116E 11B6;C90B;110C 116E 11B6; # (줋; 줋; 줋; 줋; 줋; ) HANGUL SYLLABLE JULH
+C90C;C90C;110C 116E 11B7;C90C;110C 116E 11B7; # (줌; 줌; 줌; 줌; 줌; ) HANGUL SYLLABLE JUM
+C90D;C90D;110C 116E 11B8;C90D;110C 116E 11B8; # (줍; 줍; 줍; 줍; 줍; ) HANGUL SYLLABLE JUB
+C90E;C90E;110C 116E 11B9;C90E;110C 116E 11B9; # (줎; 줎; 줎; 줎; 줎; ) HANGUL SYLLABLE JUBS
+C90F;C90F;110C 116E 11BA;C90F;110C 116E 11BA; # (줏; 줏; 줏; 줏; 줏; ) HANGUL SYLLABLE JUS
+C910;C910;110C 116E 11BB;C910;110C 116E 11BB; # (줐; 줐; 줐; 줐; 줐; ) HANGUL SYLLABLE JUSS
+C911;C911;110C 116E 11BC;C911;110C 116E 11BC; # (중; 중; 중; 중; 중; ) HANGUL SYLLABLE JUNG
+C912;C912;110C 116E 11BD;C912;110C 116E 11BD; # (줒; 줒; 줒; 줒; 줒; ) HANGUL SYLLABLE JUJ
+C913;C913;110C 116E 11BE;C913;110C 116E 11BE; # (줓; 줓; 줓; 줓; 줓; ) HANGUL SYLLABLE JUC
+C914;C914;110C 116E 11BF;C914;110C 116E 11BF; # (줔; 줔; 줔; 줔; 줔; ) HANGUL SYLLABLE JUK
+C915;C915;110C 116E 11C0;C915;110C 116E 11C0; # (줕; 줕; 줕; 줕; 줕; ) HANGUL SYLLABLE JUT
+C916;C916;110C 116E 11C1;C916;110C 116E 11C1; # (줖; 줖; 줖; 줖; 줖; ) HANGUL SYLLABLE JUP
+C917;C917;110C 116E 11C2;C917;110C 116E 11C2; # (줗; 줗; 줗; 줗; 줗; ) HANGUL SYLLABLE JUH
+C918;C918;110C 116F;C918;110C 116F; # (줘; 줘; 줘; 줘; 줘; ) HANGUL SYLLABLE JWEO
+C919;C919;110C 116F 11A8;C919;110C 116F 11A8; # (줙; 줙; 줙; 줙; 줙; ) HANGUL SYLLABLE JWEOG
+C91A;C91A;110C 116F 11A9;C91A;110C 116F 11A9; # (줚; 줚; 줚; 줚; 줚; ) HANGUL SYLLABLE JWEOGG
+C91B;C91B;110C 116F 11AA;C91B;110C 116F 11AA; # (줛; 줛; 줛; 줛; 줛; ) HANGUL SYLLABLE JWEOGS
+C91C;C91C;110C 116F 11AB;C91C;110C 116F 11AB; # (줜; 줜; 줜; 줜; 줜; ) HANGUL SYLLABLE JWEON
+C91D;C91D;110C 116F 11AC;C91D;110C 116F 11AC; # (줝; 줝; 줝; 줝; 줝; ) HANGUL SYLLABLE JWEONJ
+C91E;C91E;110C 116F 11AD;C91E;110C 116F 11AD; # (줞; 줞; 줞; 줞; 줞; ) HANGUL SYLLABLE JWEONH
+C91F;C91F;110C 116F 11AE;C91F;110C 116F 11AE; # (줟; 줟; 줟; 줟; 줟; ) HANGUL SYLLABLE JWEOD
+C920;C920;110C 116F 11AF;C920;110C 116F 11AF; # (줠; 줠; 줠; 줠; 줠; ) HANGUL SYLLABLE JWEOL
+C921;C921;110C 116F 11B0;C921;110C 116F 11B0; # (줡; 줡; 줡; 줡; 줡; ) HANGUL SYLLABLE JWEOLG
+C922;C922;110C 116F 11B1;C922;110C 116F 11B1; # (줢; 줢; 줢; 줢; 줢; ) HANGUL SYLLABLE JWEOLM
+C923;C923;110C 116F 11B2;C923;110C 116F 11B2; # (줣; 줣; 줣; 줣; 줣; ) HANGUL SYLLABLE JWEOLB
+C924;C924;110C 116F 11B3;C924;110C 116F 11B3; # (줤; 줤; 줤; 줤; 줤; ) HANGUL SYLLABLE JWEOLS
+C925;C925;110C 116F 11B4;C925;110C 116F 11B4; # (줥; 줥; 줥; 줥; 줥; ) HANGUL SYLLABLE JWEOLT
+C926;C926;110C 116F 11B5;C926;110C 116F 11B5; # (줦; 줦; 줦; 줦; 줦; ) HANGUL SYLLABLE JWEOLP
+C927;C927;110C 116F 11B6;C927;110C 116F 11B6; # (줧; 줧; 줧; 줧; 줧; ) HANGUL SYLLABLE JWEOLH
+C928;C928;110C 116F 11B7;C928;110C 116F 11B7; # (줨; 줨; 줨; 줨; 줨; ) HANGUL SYLLABLE JWEOM
+C929;C929;110C 116F 11B8;C929;110C 116F 11B8; # (줩; 줩; 줩; 줩; 줩; ) HANGUL SYLLABLE JWEOB
+C92A;C92A;110C 116F 11B9;C92A;110C 116F 11B9; # (줪; 줪; 줪; 줪; 줪; ) HANGUL SYLLABLE JWEOBS
+C92B;C92B;110C 116F 11BA;C92B;110C 116F 11BA; # (줫; 줫; 줫; 줫; 줫; ) HANGUL SYLLABLE JWEOS
+C92C;C92C;110C 116F 11BB;C92C;110C 116F 11BB; # (줬; 줬; 줬; 줬; 줬; ) HANGUL SYLLABLE JWEOSS
+C92D;C92D;110C 116F 11BC;C92D;110C 116F 11BC; # (줭; 줭; 줭; 줭; 줭; ) HANGUL SYLLABLE JWEONG
+C92E;C92E;110C 116F 11BD;C92E;110C 116F 11BD; # (줮; 줮; 줮; 줮; 줮; ) HANGUL SYLLABLE JWEOJ
+C92F;C92F;110C 116F 11BE;C92F;110C 116F 11BE; # (줯; 줯; 줯; 줯; 줯; ) HANGUL SYLLABLE JWEOC
+C930;C930;110C 116F 11BF;C930;110C 116F 11BF; # (줰; 줰; 줰; 줰; 줰; ) HANGUL SYLLABLE JWEOK
+C931;C931;110C 116F 11C0;C931;110C 116F 11C0; # (줱; 줱; 줱; 줱; 줱; ) HANGUL SYLLABLE JWEOT
+C932;C932;110C 116F 11C1;C932;110C 116F 11C1; # (줲; 줲; 줲; 줲; 줲; ) HANGUL SYLLABLE JWEOP
+C933;C933;110C 116F 11C2;C933;110C 116F 11C2; # (줳; 줳; 줳; 줳; 줳; ) HANGUL SYLLABLE JWEOH
+C934;C934;110C 1170;C934;110C 1170; # (줴; 줴; 줴; 줴; 줴; ) HANGUL SYLLABLE JWE
+C935;C935;110C 1170 11A8;C935;110C 1170 11A8; # (줵; 줵; 줵; 줵; 줵; ) HANGUL SYLLABLE JWEG
+C936;C936;110C 1170 11A9;C936;110C 1170 11A9; # (줶; 줶; 줶; 줶; 줶; ) HANGUL SYLLABLE JWEGG
+C937;C937;110C 1170 11AA;C937;110C 1170 11AA; # (줷; 줷; 줷; 줷; 줷; ) HANGUL SYLLABLE JWEGS
+C938;C938;110C 1170 11AB;C938;110C 1170 11AB; # (줸; 줸; 줸; 줸; 줸; ) HANGUL SYLLABLE JWEN
+C939;C939;110C 1170 11AC;C939;110C 1170 11AC; # (줹; 줹; 줹; 줹; 줹; ) HANGUL SYLLABLE JWENJ
+C93A;C93A;110C 1170 11AD;C93A;110C 1170 11AD; # (줺; 줺; 줺; 줺; 줺; ) HANGUL SYLLABLE JWENH
+C93B;C93B;110C 1170 11AE;C93B;110C 1170 11AE; # (줻; 줻; 줻; 줻; 줻; ) HANGUL SYLLABLE JWED
+C93C;C93C;110C 1170 11AF;C93C;110C 1170 11AF; # (줼; 줼; 줼; 줼; 줼; ) HANGUL SYLLABLE JWEL
+C93D;C93D;110C 1170 11B0;C93D;110C 1170 11B0; # (줽; 줽; 줽; 줽; 줽; ) HANGUL SYLLABLE JWELG
+C93E;C93E;110C 1170 11B1;C93E;110C 1170 11B1; # (줾; 줾; 줾; 줾; 줾; ) HANGUL SYLLABLE JWELM
+C93F;C93F;110C 1170 11B2;C93F;110C 1170 11B2; # (줿; 줿; 줿; 줿; 줿; ) HANGUL SYLLABLE JWELB
+C940;C940;110C 1170 11B3;C940;110C 1170 11B3; # (쥀; 쥀; 쥀; 쥀; 쥀; ) HANGUL SYLLABLE JWELS
+C941;C941;110C 1170 11B4;C941;110C 1170 11B4; # (쥁; 쥁; 쥁; 쥁; 쥁; ) HANGUL SYLLABLE JWELT
+C942;C942;110C 1170 11B5;C942;110C 1170 11B5; # (쥂; 쥂; 쥂; 쥂; 쥂; ) HANGUL SYLLABLE JWELP
+C943;C943;110C 1170 11B6;C943;110C 1170 11B6; # (쥃; 쥃; 쥃; 쥃; 쥃; ) HANGUL SYLLABLE JWELH
+C944;C944;110C 1170 11B7;C944;110C 1170 11B7; # (쥄; 쥄; 쥄; 쥄; 쥄; ) HANGUL SYLLABLE JWEM
+C945;C945;110C 1170 11B8;C945;110C 1170 11B8; # (쥅; 쥅; 쥅; 쥅; 쥅; ) HANGUL SYLLABLE JWEB
+C946;C946;110C 1170 11B9;C946;110C 1170 11B9; # (쥆; 쥆; 쥆; 쥆; 쥆; ) HANGUL SYLLABLE JWEBS
+C947;C947;110C 1170 11BA;C947;110C 1170 11BA; # (쥇; 쥇; 쥇; 쥇; 쥇; ) HANGUL SYLLABLE JWES
+C948;C948;110C 1170 11BB;C948;110C 1170 11BB; # (쥈; 쥈; 쥈; 쥈; 쥈; ) HANGUL SYLLABLE JWESS
+C949;C949;110C 1170 11BC;C949;110C 1170 11BC; # (쥉; 쥉; 쥉; 쥉; 쥉; ) HANGUL SYLLABLE JWENG
+C94A;C94A;110C 1170 11BD;C94A;110C 1170 11BD; # (쥊; 쥊; 쥊; 쥊; 쥊; ) HANGUL SYLLABLE JWEJ
+C94B;C94B;110C 1170 11BE;C94B;110C 1170 11BE; # (쥋; 쥋; 쥋; 쥋; 쥋; ) HANGUL SYLLABLE JWEC
+C94C;C94C;110C 1170 11BF;C94C;110C 1170 11BF; # (쥌; 쥌; 쥌; 쥌; 쥌; ) HANGUL SYLLABLE JWEK
+C94D;C94D;110C 1170 11C0;C94D;110C 1170 11C0; # (쥍; 쥍; 쥍; 쥍; 쥍; ) HANGUL SYLLABLE JWET
+C94E;C94E;110C 1170 11C1;C94E;110C 1170 11C1; # (쥎; 쥎; 쥎; 쥎; 쥎; ) HANGUL SYLLABLE JWEP
+C94F;C94F;110C 1170 11C2;C94F;110C 1170 11C2; # (쥏; 쥏; 쥏; 쥏; 쥏; ) HANGUL SYLLABLE JWEH
+C950;C950;110C 1171;C950;110C 1171; # (쥐; 쥐; 쥐; 쥐; 쥐; ) HANGUL SYLLABLE JWI
+C951;C951;110C 1171 11A8;C951;110C 1171 11A8; # (쥑; 쥑; 쥑; 쥑; 쥑; ) HANGUL SYLLABLE JWIG
+C952;C952;110C 1171 11A9;C952;110C 1171 11A9; # (쥒; 쥒; 쥒; 쥒; 쥒; ) HANGUL SYLLABLE JWIGG
+C953;C953;110C 1171 11AA;C953;110C 1171 11AA; # (쥓; 쥓; 쥓; 쥓; 쥓; ) HANGUL SYLLABLE JWIGS
+C954;C954;110C 1171 11AB;C954;110C 1171 11AB; # (쥔; 쥔; 쥔; 쥔; 쥔; ) HANGUL SYLLABLE JWIN
+C955;C955;110C 1171 11AC;C955;110C 1171 11AC; # (쥕; 쥕; 쥕; 쥕; 쥕; ) HANGUL SYLLABLE JWINJ
+C956;C956;110C 1171 11AD;C956;110C 1171 11AD; # (쥖; 쥖; 쥖; 쥖; 쥖; ) HANGUL SYLLABLE JWINH
+C957;C957;110C 1171 11AE;C957;110C 1171 11AE; # (쥗; 쥗; 쥗; 쥗; 쥗; ) HANGUL SYLLABLE JWID
+C958;C958;110C 1171 11AF;C958;110C 1171 11AF; # (쥘; 쥘; 쥘; 쥘; 쥘; ) HANGUL SYLLABLE JWIL
+C959;C959;110C 1171 11B0;C959;110C 1171 11B0; # (쥙; 쥙; 쥙; 쥙; 쥙; ) HANGUL SYLLABLE JWILG
+C95A;C95A;110C 1171 11B1;C95A;110C 1171 11B1; # (쥚; 쥚; 쥚; 쥚; 쥚; ) HANGUL SYLLABLE JWILM
+C95B;C95B;110C 1171 11B2;C95B;110C 1171 11B2; # (쥛; 쥛; 쥛; 쥛; 쥛; ) HANGUL SYLLABLE JWILB
+C95C;C95C;110C 1171 11B3;C95C;110C 1171 11B3; # (쥜; 쥜; 쥜; 쥜; 쥜; ) HANGUL SYLLABLE JWILS
+C95D;C95D;110C 1171 11B4;C95D;110C 1171 11B4; # (쥝; 쥝; 쥝; 쥝; 쥝; ) HANGUL SYLLABLE JWILT
+C95E;C95E;110C 1171 11B5;C95E;110C 1171 11B5; # (쥞; 쥞; 쥞; 쥞; 쥞; ) HANGUL SYLLABLE JWILP
+C95F;C95F;110C 1171 11B6;C95F;110C 1171 11B6; # (쥟; 쥟; 쥟; 쥟; 쥟; ) HANGUL SYLLABLE JWILH
+C960;C960;110C 1171 11B7;C960;110C 1171 11B7; # (쥠; 쥠; 쥠; 쥠; 쥠; ) HANGUL SYLLABLE JWIM
+C961;C961;110C 1171 11B8;C961;110C 1171 11B8; # (쥡; 쥡; 쥡; 쥡; 쥡; ) HANGUL SYLLABLE JWIB
+C962;C962;110C 1171 11B9;C962;110C 1171 11B9; # (쥢; 쥢; 쥢; 쥢; 쥢; ) HANGUL SYLLABLE JWIBS
+C963;C963;110C 1171 11BA;C963;110C 1171 11BA; # (쥣; 쥣; 쥣; 쥣; 쥣; ) HANGUL SYLLABLE JWIS
+C964;C964;110C 1171 11BB;C964;110C 1171 11BB; # (쥤; 쥤; 쥤; 쥤; 쥤; ) HANGUL SYLLABLE JWISS
+C965;C965;110C 1171 11BC;C965;110C 1171 11BC; # (쥥; 쥥; 쥥; 쥥; 쥥; ) HANGUL SYLLABLE JWING
+C966;C966;110C 1171 11BD;C966;110C 1171 11BD; # (쥦; 쥦; 쥦; 쥦; 쥦; ) HANGUL SYLLABLE JWIJ
+C967;C967;110C 1171 11BE;C967;110C 1171 11BE; # (쥧; 쥧; 쥧; 쥧; 쥧; ) HANGUL SYLLABLE JWIC
+C968;C968;110C 1171 11BF;C968;110C 1171 11BF; # (쥨; 쥨; 쥨; 쥨; 쥨; ) HANGUL SYLLABLE JWIK
+C969;C969;110C 1171 11C0;C969;110C 1171 11C0; # (쥩; 쥩; 쥩; 쥩; 쥩; ) HANGUL SYLLABLE JWIT
+C96A;C96A;110C 1171 11C1;C96A;110C 1171 11C1; # (쥪; 쥪; 쥪; 쥪; 쥪; ) HANGUL SYLLABLE JWIP
+C96B;C96B;110C 1171 11C2;C96B;110C 1171 11C2; # (쥫; 쥫; 쥫; 쥫; 쥫; ) HANGUL SYLLABLE JWIH
+C96C;C96C;110C 1172;C96C;110C 1172; # (쥬; 쥬; 쥬; 쥬; 쥬; ) HANGUL SYLLABLE JYU
+C96D;C96D;110C 1172 11A8;C96D;110C 1172 11A8; # (쥭; 쥭; 쥭; 쥭; 쥭; ) HANGUL SYLLABLE JYUG
+C96E;C96E;110C 1172 11A9;C96E;110C 1172 11A9; # (쥮; 쥮; 쥮; 쥮; 쥮; ) HANGUL SYLLABLE JYUGG
+C96F;C96F;110C 1172 11AA;C96F;110C 1172 11AA; # (쥯; 쥯; 쥯; 쥯; 쥯; ) HANGUL SYLLABLE JYUGS
+C970;C970;110C 1172 11AB;C970;110C 1172 11AB; # (쥰; 쥰; 쥰; 쥰; 쥰; ) HANGUL SYLLABLE JYUN
+C971;C971;110C 1172 11AC;C971;110C 1172 11AC; # (쥱; 쥱; 쥱; 쥱; 쥱; ) HANGUL SYLLABLE JYUNJ
+C972;C972;110C 1172 11AD;C972;110C 1172 11AD; # (쥲; 쥲; 쥲; 쥲; 쥲; ) HANGUL SYLLABLE JYUNH
+C973;C973;110C 1172 11AE;C973;110C 1172 11AE; # (쥳; 쥳; 쥳; 쥳; 쥳; ) HANGUL SYLLABLE JYUD
+C974;C974;110C 1172 11AF;C974;110C 1172 11AF; # (쥴; 쥴; 쥴; 쥴; 쥴; ) HANGUL SYLLABLE JYUL
+C975;C975;110C 1172 11B0;C975;110C 1172 11B0; # (쥵; 쥵; 쥵; 쥵; 쥵; ) HANGUL SYLLABLE JYULG
+C976;C976;110C 1172 11B1;C976;110C 1172 11B1; # (쥶; 쥶; 쥶; 쥶; 쥶; ) HANGUL SYLLABLE JYULM
+C977;C977;110C 1172 11B2;C977;110C 1172 11B2; # (쥷; 쥷; 쥷; 쥷; 쥷; ) HANGUL SYLLABLE JYULB
+C978;C978;110C 1172 11B3;C978;110C 1172 11B3; # (쥸; 쥸; 쥸; 쥸; 쥸; ) HANGUL SYLLABLE JYULS
+C979;C979;110C 1172 11B4;C979;110C 1172 11B4; # (쥹; 쥹; 쥹; 쥹; 쥹; ) HANGUL SYLLABLE JYULT
+C97A;C97A;110C 1172 11B5;C97A;110C 1172 11B5; # (쥺; 쥺; 쥺; 쥺; 쥺; ) HANGUL SYLLABLE JYULP
+C97B;C97B;110C 1172 11B6;C97B;110C 1172 11B6; # (쥻; 쥻; 쥻; 쥻; 쥻; ) HANGUL SYLLABLE JYULH
+C97C;C97C;110C 1172 11B7;C97C;110C 1172 11B7; # (쥼; 쥼; 쥼; 쥼; 쥼; ) HANGUL SYLLABLE JYUM
+C97D;C97D;110C 1172 11B8;C97D;110C 1172 11B8; # (쥽; 쥽; 쥽; 쥽; 쥽; ) HANGUL SYLLABLE JYUB
+C97E;C97E;110C 1172 11B9;C97E;110C 1172 11B9; # (쥾; 쥾; 쥾; 쥾; 쥾; ) HANGUL SYLLABLE JYUBS
+C97F;C97F;110C 1172 11BA;C97F;110C 1172 11BA; # (쥿; 쥿; 쥿; 쥿; 쥿; ) HANGUL SYLLABLE JYUS
+C980;C980;110C 1172 11BB;C980;110C 1172 11BB; # (즀; 즀; 즀; 즀; 즀; ) HANGUL SYLLABLE JYUSS
+C981;C981;110C 1172 11BC;C981;110C 1172 11BC; # (즁; 즁; 즁; 즁; 즁; ) HANGUL SYLLABLE JYUNG
+C982;C982;110C 1172 11BD;C982;110C 1172 11BD; # (즂; 즂; 즂; 즂; 즂; ) HANGUL SYLLABLE JYUJ
+C983;C983;110C 1172 11BE;C983;110C 1172 11BE; # (즃; 즃; 즃; 즃; 즃; ) HANGUL SYLLABLE JYUC
+C984;C984;110C 1172 11BF;C984;110C 1172 11BF; # (즄; 즄; 즄; 즄; 즄; ) HANGUL SYLLABLE JYUK
+C985;C985;110C 1172 11C0;C985;110C 1172 11C0; # (즅; 즅; 즅; 즅; 즅; ) HANGUL SYLLABLE JYUT
+C986;C986;110C 1172 11C1;C986;110C 1172 11C1; # (즆; 즆; 즆; 즆; 즆; ) HANGUL SYLLABLE JYUP
+C987;C987;110C 1172 11C2;C987;110C 1172 11C2; # (즇; 즇; 즇; 즇; 즇; ) HANGUL SYLLABLE JYUH
+C988;C988;110C 1173;C988;110C 1173; # (즈; 즈; 즈; 즈; 즈; ) HANGUL SYLLABLE JEU
+C989;C989;110C 1173 11A8;C989;110C 1173 11A8; # (즉; 즉; 즉; 즉; 즉; ) HANGUL SYLLABLE JEUG
+C98A;C98A;110C 1173 11A9;C98A;110C 1173 11A9; # (즊; 즊; 즊; 즊; 즊; ) HANGUL SYLLABLE JEUGG
+C98B;C98B;110C 1173 11AA;C98B;110C 1173 11AA; # (즋; 즋; 즋; 즋; 즋; ) HANGUL SYLLABLE JEUGS
+C98C;C98C;110C 1173 11AB;C98C;110C 1173 11AB; # (즌; 즌; 즌; 즌; 즌; ) HANGUL SYLLABLE JEUN
+C98D;C98D;110C 1173 11AC;C98D;110C 1173 11AC; # (즍; 즍; 즍; 즍; 즍; ) HANGUL SYLLABLE JEUNJ
+C98E;C98E;110C 1173 11AD;C98E;110C 1173 11AD; # (즎; 즎; 즎; 즎; 즎; ) HANGUL SYLLABLE JEUNH
+C98F;C98F;110C 1173 11AE;C98F;110C 1173 11AE; # (즏; 즏; 즏; 즏; 즏; ) HANGUL SYLLABLE JEUD
+C990;C990;110C 1173 11AF;C990;110C 1173 11AF; # (즐; 즐; 즐; 즐; 즐; ) HANGUL SYLLABLE JEUL
+C991;C991;110C 1173 11B0;C991;110C 1173 11B0; # (즑; 즑; 즑; 즑; 즑; ) HANGUL SYLLABLE JEULG
+C992;C992;110C 1173 11B1;C992;110C 1173 11B1; # (즒; 즒; 즒; 즒; 즒; ) HANGUL SYLLABLE JEULM
+C993;C993;110C 1173 11B2;C993;110C 1173 11B2; # (즓; 즓; 즓; 즓; 즓; ) HANGUL SYLLABLE JEULB
+C994;C994;110C 1173 11B3;C994;110C 1173 11B3; # (즔; 즔; 즔; 즔; 즔; ) HANGUL SYLLABLE JEULS
+C995;C995;110C 1173 11B4;C995;110C 1173 11B4; # (즕; 즕; 즕; 즕; 즕; ) HANGUL SYLLABLE JEULT
+C996;C996;110C 1173 11B5;C996;110C 1173 11B5; # (즖; 즖; 즖; 즖; 즖; ) HANGUL SYLLABLE JEULP
+C997;C997;110C 1173 11B6;C997;110C 1173 11B6; # (즗; 즗; 즗; 즗; 즗; ) HANGUL SYLLABLE JEULH
+C998;C998;110C 1173 11B7;C998;110C 1173 11B7; # (즘; 즘; 즘; 즘; 즘; ) HANGUL SYLLABLE JEUM
+C999;C999;110C 1173 11B8;C999;110C 1173 11B8; # (즙; 즙; 즙; 즙; 즙; ) HANGUL SYLLABLE JEUB
+C99A;C99A;110C 1173 11B9;C99A;110C 1173 11B9; # (즚; 즚; 즚; 즚; 즚; ) HANGUL SYLLABLE JEUBS
+C99B;C99B;110C 1173 11BA;C99B;110C 1173 11BA; # (즛; 즛; 즛; 즛; 즛; ) HANGUL SYLLABLE JEUS
+C99C;C99C;110C 1173 11BB;C99C;110C 1173 11BB; # (즜; 즜; 즜; 즜; 즜; ) HANGUL SYLLABLE JEUSS
+C99D;C99D;110C 1173 11BC;C99D;110C 1173 11BC; # (증; 증; 증; 증; 증; ) HANGUL SYLLABLE JEUNG
+C99E;C99E;110C 1173 11BD;C99E;110C 1173 11BD; # (즞; 즞; 즞; 즞; 즞; ) HANGUL SYLLABLE JEUJ
+C99F;C99F;110C 1173 11BE;C99F;110C 1173 11BE; # (즟; 즟; 즟; 즟; 즟; ) HANGUL SYLLABLE JEUC
+C9A0;C9A0;110C 1173 11BF;C9A0;110C 1173 11BF; # (즠; 즠; 즠; 즠; 즠; ) HANGUL SYLLABLE JEUK
+C9A1;C9A1;110C 1173 11C0;C9A1;110C 1173 11C0; # (즡; 즡; 즡; 즡; 즡; ) HANGUL SYLLABLE JEUT
+C9A2;C9A2;110C 1173 11C1;C9A2;110C 1173 11C1; # (즢; 즢; 즢; 즢; 즢; ) HANGUL SYLLABLE JEUP
+C9A3;C9A3;110C 1173 11C2;C9A3;110C 1173 11C2; # (즣; 즣; 즣; 즣; 즣; ) HANGUL SYLLABLE JEUH
+C9A4;C9A4;110C 1174;C9A4;110C 1174; # (즤; 즤; 즤; 즤; 즤; ) HANGUL SYLLABLE JYI
+C9A5;C9A5;110C 1174 11A8;C9A5;110C 1174 11A8; # (즥; 즥; 즥; 즥; 즥; ) HANGUL SYLLABLE JYIG
+C9A6;C9A6;110C 1174 11A9;C9A6;110C 1174 11A9; # (즦; 즦; 즦; 즦; 즦; ) HANGUL SYLLABLE JYIGG
+C9A7;C9A7;110C 1174 11AA;C9A7;110C 1174 11AA; # (즧; 즧; 즧; 즧; 즧; ) HANGUL SYLLABLE JYIGS
+C9A8;C9A8;110C 1174 11AB;C9A8;110C 1174 11AB; # (즨; 즨; 즨; 즨; 즨; ) HANGUL SYLLABLE JYIN
+C9A9;C9A9;110C 1174 11AC;C9A9;110C 1174 11AC; # (즩; 즩; 즩; 즩; 즩; ) HANGUL SYLLABLE JYINJ
+C9AA;C9AA;110C 1174 11AD;C9AA;110C 1174 11AD; # (즪; 즪; 즪; 즪; 즪; ) HANGUL SYLLABLE JYINH
+C9AB;C9AB;110C 1174 11AE;C9AB;110C 1174 11AE; # (즫; 즫; 즫; 즫; 즫; ) HANGUL SYLLABLE JYID
+C9AC;C9AC;110C 1174 11AF;C9AC;110C 1174 11AF; # (즬; 즬; 즬; 즬; 즬; ) HANGUL SYLLABLE JYIL
+C9AD;C9AD;110C 1174 11B0;C9AD;110C 1174 11B0; # (즭; 즭; 즭; 즭; 즭; ) HANGUL SYLLABLE JYILG
+C9AE;C9AE;110C 1174 11B1;C9AE;110C 1174 11B1; # (즮; 즮; 즮; 즮; 즮; ) HANGUL SYLLABLE JYILM
+C9AF;C9AF;110C 1174 11B2;C9AF;110C 1174 11B2; # (즯; 즯; 즯; 즯; 즯; ) HANGUL SYLLABLE JYILB
+C9B0;C9B0;110C 1174 11B3;C9B0;110C 1174 11B3; # (즰; 즰; 즰; 즰; 즰; ) HANGUL SYLLABLE JYILS
+C9B1;C9B1;110C 1174 11B4;C9B1;110C 1174 11B4; # (즱; 즱; 즱; 즱; 즱; ) HANGUL SYLLABLE JYILT
+C9B2;C9B2;110C 1174 11B5;C9B2;110C 1174 11B5; # (즲; 즲; 즲; 즲; 즲; ) HANGUL SYLLABLE JYILP
+C9B3;C9B3;110C 1174 11B6;C9B3;110C 1174 11B6; # (즳; 즳; 즳; 즳; 즳; ) HANGUL SYLLABLE JYILH
+C9B4;C9B4;110C 1174 11B7;C9B4;110C 1174 11B7; # (즴; 즴; 즴; 즴; 즴; ) HANGUL SYLLABLE JYIM
+C9B5;C9B5;110C 1174 11B8;C9B5;110C 1174 11B8; # (즵; 즵; 즵; 즵; 즵; ) HANGUL SYLLABLE JYIB
+C9B6;C9B6;110C 1174 11B9;C9B6;110C 1174 11B9; # (즶; 즶; 즶; 즶; 즶; ) HANGUL SYLLABLE JYIBS
+C9B7;C9B7;110C 1174 11BA;C9B7;110C 1174 11BA; # (즷; 즷; 즷; 즷; 즷; ) HANGUL SYLLABLE JYIS
+C9B8;C9B8;110C 1174 11BB;C9B8;110C 1174 11BB; # (즸; 즸; 즸; 즸; 즸; ) HANGUL SYLLABLE JYISS
+C9B9;C9B9;110C 1174 11BC;C9B9;110C 1174 11BC; # (즹; 즹; 즹; 즹; 즹; ) HANGUL SYLLABLE JYING
+C9BA;C9BA;110C 1174 11BD;C9BA;110C 1174 11BD; # (즺; 즺; 즺; 즺; 즺; ) HANGUL SYLLABLE JYIJ
+C9BB;C9BB;110C 1174 11BE;C9BB;110C 1174 11BE; # (즻; 즻; 즻; 즻; 즻; ) HANGUL SYLLABLE JYIC
+C9BC;C9BC;110C 1174 11BF;C9BC;110C 1174 11BF; # (즼; 즼; 즼; 즼; 즼; ) HANGUL SYLLABLE JYIK
+C9BD;C9BD;110C 1174 11C0;C9BD;110C 1174 11C0; # (즽; 즽; 즽; 즽; 즽; ) HANGUL SYLLABLE JYIT
+C9BE;C9BE;110C 1174 11C1;C9BE;110C 1174 11C1; # (즾; 즾; 즾; 즾; 즾; ) HANGUL SYLLABLE JYIP
+C9BF;C9BF;110C 1174 11C2;C9BF;110C 1174 11C2; # (즿; 즿; 즿; 즿; 즿; ) HANGUL SYLLABLE JYIH
+C9C0;C9C0;110C 1175;C9C0;110C 1175; # (지; 지; 지; 지; 지; ) HANGUL SYLLABLE JI
+C9C1;C9C1;110C 1175 11A8;C9C1;110C 1175 11A8; # (직; 직; 직; 직; 직; ) HANGUL SYLLABLE JIG
+C9C2;C9C2;110C 1175 11A9;C9C2;110C 1175 11A9; # (짂; 짂; 짂; 짂; 짂; ) HANGUL SYLLABLE JIGG
+C9C3;C9C3;110C 1175 11AA;C9C3;110C 1175 11AA; # (짃; 짃; 짃; 짃; 짃; ) HANGUL SYLLABLE JIGS
+C9C4;C9C4;110C 1175 11AB;C9C4;110C 1175 11AB; # (진; 진; 진; 진; 진; ) HANGUL SYLLABLE JIN
+C9C5;C9C5;110C 1175 11AC;C9C5;110C 1175 11AC; # (짅; 짅; 짅; 짅; 짅; ) HANGUL SYLLABLE JINJ
+C9C6;C9C6;110C 1175 11AD;C9C6;110C 1175 11AD; # (짆; 짆; 짆; 짆; 짆; ) HANGUL SYLLABLE JINH
+C9C7;C9C7;110C 1175 11AE;C9C7;110C 1175 11AE; # (짇; 짇; 짇; 짇; 짇; ) HANGUL SYLLABLE JID
+C9C8;C9C8;110C 1175 11AF;C9C8;110C 1175 11AF; # (질; 질; 질; 질; 질; ) HANGUL SYLLABLE JIL
+C9C9;C9C9;110C 1175 11B0;C9C9;110C 1175 11B0; # (짉; 짉; 짉; 짉; 짉; ) HANGUL SYLLABLE JILG
+C9CA;C9CA;110C 1175 11B1;C9CA;110C 1175 11B1; # (짊; 짊; 짊; 짊; 짊; ) HANGUL SYLLABLE JILM
+C9CB;C9CB;110C 1175 11B2;C9CB;110C 1175 11B2; # (짋; 짋; 짋; 짋; 짋; ) HANGUL SYLLABLE JILB
+C9CC;C9CC;110C 1175 11B3;C9CC;110C 1175 11B3; # (짌; 짌; 짌; 짌; 짌; ) HANGUL SYLLABLE JILS
+C9CD;C9CD;110C 1175 11B4;C9CD;110C 1175 11B4; # (짍; 짍; 짍; 짍; 짍; ) HANGUL SYLLABLE JILT
+C9CE;C9CE;110C 1175 11B5;C9CE;110C 1175 11B5; # (짎; 짎; 짎; 짎; 짎; ) HANGUL SYLLABLE JILP
+C9CF;C9CF;110C 1175 11B6;C9CF;110C 1175 11B6; # (짏; 짏; 짏; 짏; 짏; ) HANGUL SYLLABLE JILH
+C9D0;C9D0;110C 1175 11B7;C9D0;110C 1175 11B7; # (짐; 짐; 짐; 짐; 짐; ) HANGUL SYLLABLE JIM
+C9D1;C9D1;110C 1175 11B8;C9D1;110C 1175 11B8; # (집; 집; 집; 집; 집; ) HANGUL SYLLABLE JIB
+C9D2;C9D2;110C 1175 11B9;C9D2;110C 1175 11B9; # (짒; 짒; 짒; 짒; 짒; ) HANGUL SYLLABLE JIBS
+C9D3;C9D3;110C 1175 11BA;C9D3;110C 1175 11BA; # (짓; 짓; 짓; 짓; 짓; ) HANGUL SYLLABLE JIS
+C9D4;C9D4;110C 1175 11BB;C9D4;110C 1175 11BB; # (짔; 짔; 짔; 짔; 짔; ) HANGUL SYLLABLE JISS
+C9D5;C9D5;110C 1175 11BC;C9D5;110C 1175 11BC; # (징; 징; 징; 징; 징; ) HANGUL SYLLABLE JING
+C9D6;C9D6;110C 1175 11BD;C9D6;110C 1175 11BD; # (짖; 짖; 짖; 짖; 짖; ) HANGUL SYLLABLE JIJ
+C9D7;C9D7;110C 1175 11BE;C9D7;110C 1175 11BE; # (짗; 짗; 짗; 짗; 짗; ) HANGUL SYLLABLE JIC
+C9D8;C9D8;110C 1175 11BF;C9D8;110C 1175 11BF; # (짘; 짘; 짘; 짘; 짘; ) HANGUL SYLLABLE JIK
+C9D9;C9D9;110C 1175 11C0;C9D9;110C 1175 11C0; # (짙; 짙; 짙; 짙; 짙; ) HANGUL SYLLABLE JIT
+C9DA;C9DA;110C 1175 11C1;C9DA;110C 1175 11C1; # (짚; 짚; 짚; 짚; 짚; ) HANGUL SYLLABLE JIP
+C9DB;C9DB;110C 1175 11C2;C9DB;110C 1175 11C2; # (짛; 짛; 짛; 짛; 짛; ) HANGUL SYLLABLE JIH
+C9DC;C9DC;110D 1161;C9DC;110D 1161; # (짜; 짜; 짜; 짜; 짜; ) HANGUL SYLLABLE JJA
+C9DD;C9DD;110D 1161 11A8;C9DD;110D 1161 11A8; # (짝; 짝; 짝; 짝; 짝; ) HANGUL SYLLABLE JJAG
+C9DE;C9DE;110D 1161 11A9;C9DE;110D 1161 11A9; # (짞; 짞; 짞; 짞; 짞; ) HANGUL SYLLABLE JJAGG
+C9DF;C9DF;110D 1161 11AA;C9DF;110D 1161 11AA; # (짟; 짟; 짟; 짟; 짟; ) HANGUL SYLLABLE JJAGS
+C9E0;C9E0;110D 1161 11AB;C9E0;110D 1161 11AB; # (짠; 짠; 짠; 짠; 짠; ) HANGUL SYLLABLE JJAN
+C9E1;C9E1;110D 1161 11AC;C9E1;110D 1161 11AC; # (짡; 짡; 짡; 짡; 짡; ) HANGUL SYLLABLE JJANJ
+C9E2;C9E2;110D 1161 11AD;C9E2;110D 1161 11AD; # (짢; 짢; 짢; 짢; 짢; ) HANGUL SYLLABLE JJANH
+C9E3;C9E3;110D 1161 11AE;C9E3;110D 1161 11AE; # (짣; 짣; 짣; 짣; 짣; ) HANGUL SYLLABLE JJAD
+C9E4;C9E4;110D 1161 11AF;C9E4;110D 1161 11AF; # (짤; 짤; 짤; 짤; 짤; ) HANGUL SYLLABLE JJAL
+C9E5;C9E5;110D 1161 11B0;C9E5;110D 1161 11B0; # (짥; 짥; 짥; 짥; 짥; ) HANGUL SYLLABLE JJALG
+C9E6;C9E6;110D 1161 11B1;C9E6;110D 1161 11B1; # (짦; 짦; 짦; 짦; 짦; ) HANGUL SYLLABLE JJALM
+C9E7;C9E7;110D 1161 11B2;C9E7;110D 1161 11B2; # (짧; 짧; 짧; 짧; 짧; ) HANGUL SYLLABLE JJALB
+C9E8;C9E8;110D 1161 11B3;C9E8;110D 1161 11B3; # (짨; 짨; 짨; 짨; 짨; ) HANGUL SYLLABLE JJALS
+C9E9;C9E9;110D 1161 11B4;C9E9;110D 1161 11B4; # (짩; 짩; 짩; 짩; 짩; ) HANGUL SYLLABLE JJALT
+C9EA;C9EA;110D 1161 11B5;C9EA;110D 1161 11B5; # (짪; 짪; 짪; 짪; 짪; ) HANGUL SYLLABLE JJALP
+C9EB;C9EB;110D 1161 11B6;C9EB;110D 1161 11B6; # (짫; 짫; 짫; 짫; 짫; ) HANGUL SYLLABLE JJALH
+C9EC;C9EC;110D 1161 11B7;C9EC;110D 1161 11B7; # (짬; 짬; 짬; 짬; 짬; ) HANGUL SYLLABLE JJAM
+C9ED;C9ED;110D 1161 11B8;C9ED;110D 1161 11B8; # (짭; 짭; 짭; 짭; 짭; ) HANGUL SYLLABLE JJAB
+C9EE;C9EE;110D 1161 11B9;C9EE;110D 1161 11B9; # (짮; 짮; 짮; 짮; 짮; ) HANGUL SYLLABLE JJABS
+C9EF;C9EF;110D 1161 11BA;C9EF;110D 1161 11BA; # (짯; 짯; 짯; 짯; 짯; ) HANGUL SYLLABLE JJAS
+C9F0;C9F0;110D 1161 11BB;C9F0;110D 1161 11BB; # (짰; 짰; 짰; 짰; 짰; ) HANGUL SYLLABLE JJASS
+C9F1;C9F1;110D 1161 11BC;C9F1;110D 1161 11BC; # (짱; 짱; 짱; 짱; 짱; ) HANGUL SYLLABLE JJANG
+C9F2;C9F2;110D 1161 11BD;C9F2;110D 1161 11BD; # (짲; 짲; 짲; 짲; 짲; ) HANGUL SYLLABLE JJAJ
+C9F3;C9F3;110D 1161 11BE;C9F3;110D 1161 11BE; # (짳; 짳; 짳; 짳; 짳; ) HANGUL SYLLABLE JJAC
+C9F4;C9F4;110D 1161 11BF;C9F4;110D 1161 11BF; # (짴; 짴; 짴; 짴; 짴; ) HANGUL SYLLABLE JJAK
+C9F5;C9F5;110D 1161 11C0;C9F5;110D 1161 11C0; # (짵; 짵; 짵; 짵; 짵; ) HANGUL SYLLABLE JJAT
+C9F6;C9F6;110D 1161 11C1;C9F6;110D 1161 11C1; # (짶; 짶; 짶; 짶; 짶; ) HANGUL SYLLABLE JJAP
+C9F7;C9F7;110D 1161 11C2;C9F7;110D 1161 11C2; # (짷; 짷; 짷; 짷; 짷; ) HANGUL SYLLABLE JJAH
+C9F8;C9F8;110D 1162;C9F8;110D 1162; # (째; 째; 째; 째; 째; ) HANGUL SYLLABLE JJAE
+C9F9;C9F9;110D 1162 11A8;C9F9;110D 1162 11A8; # (짹; 짹; 짹; 짹; 짹; ) HANGUL SYLLABLE JJAEG
+C9FA;C9FA;110D 1162 11A9;C9FA;110D 1162 11A9; # (짺; 짺; 짺; 짺; 짺; ) HANGUL SYLLABLE JJAEGG
+C9FB;C9FB;110D 1162 11AA;C9FB;110D 1162 11AA; # (짻; 짻; 짻; 짻; 짻; ) HANGUL SYLLABLE JJAEGS
+C9FC;C9FC;110D 1162 11AB;C9FC;110D 1162 11AB; # (짼; 짼; 짼; 짼; 짼; ) HANGUL SYLLABLE JJAEN
+C9FD;C9FD;110D 1162 11AC;C9FD;110D 1162 11AC; # (짽; 짽; 짽; 짽; 짽; ) HANGUL SYLLABLE JJAENJ
+C9FE;C9FE;110D 1162 11AD;C9FE;110D 1162 11AD; # (짾; 짾; 짾; 짾; 짾; ) HANGUL SYLLABLE JJAENH
+C9FF;C9FF;110D 1162 11AE;C9FF;110D 1162 11AE; # (짿; 짿; 짿; 짿; 짿; ) HANGUL SYLLABLE JJAED
+CA00;CA00;110D 1162 11AF;CA00;110D 1162 11AF; # (쨀; 쨀; 쨀; 쨀; 쨀; ) HANGUL SYLLABLE JJAEL
+CA01;CA01;110D 1162 11B0;CA01;110D 1162 11B0; # (쨁; 쨁; 쨁; 쨁; 쨁; ) HANGUL SYLLABLE JJAELG
+CA02;CA02;110D 1162 11B1;CA02;110D 1162 11B1; # (쨂; 쨂; 쨂; 쨂; 쨂; ) HANGUL SYLLABLE JJAELM
+CA03;CA03;110D 1162 11B2;CA03;110D 1162 11B2; # (쨃; 쨃; 쨃; 쨃; 쨃; ) HANGUL SYLLABLE JJAELB
+CA04;CA04;110D 1162 11B3;CA04;110D 1162 11B3; # (쨄; 쨄; 쨄; 쨄; 쨄; ) HANGUL SYLLABLE JJAELS
+CA05;CA05;110D 1162 11B4;CA05;110D 1162 11B4; # (쨅; 쨅; 쨅; 쨅; 쨅; ) HANGUL SYLLABLE JJAELT
+CA06;CA06;110D 1162 11B5;CA06;110D 1162 11B5; # (쨆; 쨆; 쨆; 쨆; 쨆; ) HANGUL SYLLABLE JJAELP
+CA07;CA07;110D 1162 11B6;CA07;110D 1162 11B6; # (쨇; 쨇; 쨇; 쨇; 쨇; ) HANGUL SYLLABLE JJAELH
+CA08;CA08;110D 1162 11B7;CA08;110D 1162 11B7; # (쨈; 쨈; 쨈; 쨈; 쨈; ) HANGUL SYLLABLE JJAEM
+CA09;CA09;110D 1162 11B8;CA09;110D 1162 11B8; # (쨉; 쨉; 쨉; 쨉; 쨉; ) HANGUL SYLLABLE JJAEB
+CA0A;CA0A;110D 1162 11B9;CA0A;110D 1162 11B9; # (쨊; 쨊; 쨊; 쨊; 쨊; ) HANGUL SYLLABLE JJAEBS
+CA0B;CA0B;110D 1162 11BA;CA0B;110D 1162 11BA; # (쨋; 쨋; 쨋; 쨋; 쨋; ) HANGUL SYLLABLE JJAES
+CA0C;CA0C;110D 1162 11BB;CA0C;110D 1162 11BB; # (쨌; 쨌; 쨌; 쨌; 쨌; ) HANGUL SYLLABLE JJAESS
+CA0D;CA0D;110D 1162 11BC;CA0D;110D 1162 11BC; # (쨍; 쨍; 쨍; 쨍; 쨍; ) HANGUL SYLLABLE JJAENG
+CA0E;CA0E;110D 1162 11BD;CA0E;110D 1162 11BD; # (쨎; 쨎; 쨎; 쨎; 쨎; ) HANGUL SYLLABLE JJAEJ
+CA0F;CA0F;110D 1162 11BE;CA0F;110D 1162 11BE; # (쨏; 쨏; 쨏; 쨏; 쨏; ) HANGUL SYLLABLE JJAEC
+CA10;CA10;110D 1162 11BF;CA10;110D 1162 11BF; # (쨐; 쨐; 쨐; 쨐; 쨐; ) HANGUL SYLLABLE JJAEK
+CA11;CA11;110D 1162 11C0;CA11;110D 1162 11C0; # (쨑; 쨑; 쨑; 쨑; 쨑; ) HANGUL SYLLABLE JJAET
+CA12;CA12;110D 1162 11C1;CA12;110D 1162 11C1; # (쨒; 쨒; 쨒; 쨒; 쨒; ) HANGUL SYLLABLE JJAEP
+CA13;CA13;110D 1162 11C2;CA13;110D 1162 11C2; # (쨓; 쨓; 쨓; 쨓; 쨓; ) HANGUL SYLLABLE JJAEH
+CA14;CA14;110D 1163;CA14;110D 1163; # (쨔; 쨔; 쨔; 쨔; 쨔; ) HANGUL SYLLABLE JJYA
+CA15;CA15;110D 1163 11A8;CA15;110D 1163 11A8; # (쨕; 쨕; 쨕; 쨕; 쨕; ) HANGUL SYLLABLE JJYAG
+CA16;CA16;110D 1163 11A9;CA16;110D 1163 11A9; # (쨖; 쨖; 쨖; 쨖; 쨖; ) HANGUL SYLLABLE JJYAGG
+CA17;CA17;110D 1163 11AA;CA17;110D 1163 11AA; # (쨗; 쨗; 쨗; 쨗; 쨗; ) HANGUL SYLLABLE JJYAGS
+CA18;CA18;110D 1163 11AB;CA18;110D 1163 11AB; # (쨘; 쨘; 쨘; 쨘; 쨘; ) HANGUL SYLLABLE JJYAN
+CA19;CA19;110D 1163 11AC;CA19;110D 1163 11AC; # (쨙; 쨙; 쨙; 쨙; 쨙; ) HANGUL SYLLABLE JJYANJ
+CA1A;CA1A;110D 1163 11AD;CA1A;110D 1163 11AD; # (쨚; 쨚; 쨚; 쨚; 쨚; ) HANGUL SYLLABLE JJYANH
+CA1B;CA1B;110D 1163 11AE;CA1B;110D 1163 11AE; # (쨛; 쨛; 쨛; 쨛; 쨛; ) HANGUL SYLLABLE JJYAD
+CA1C;CA1C;110D 1163 11AF;CA1C;110D 1163 11AF; # (쨜; 쨜; 쨜; 쨜; 쨜; ) HANGUL SYLLABLE JJYAL
+CA1D;CA1D;110D 1163 11B0;CA1D;110D 1163 11B0; # (쨝; 쨝; 쨝; 쨝; 쨝; ) HANGUL SYLLABLE JJYALG
+CA1E;CA1E;110D 1163 11B1;CA1E;110D 1163 11B1; # (쨞; 쨞; 쨞; 쨞; 쨞; ) HANGUL SYLLABLE JJYALM
+CA1F;CA1F;110D 1163 11B2;CA1F;110D 1163 11B2; # (쨟; 쨟; 쨟; 쨟; 쨟; ) HANGUL SYLLABLE JJYALB
+CA20;CA20;110D 1163 11B3;CA20;110D 1163 11B3; # (쨠; 쨠; 쨠; 쨠; 쨠; ) HANGUL SYLLABLE JJYALS
+CA21;CA21;110D 1163 11B4;CA21;110D 1163 11B4; # (쨡; 쨡; 쨡; 쨡; 쨡; ) HANGUL SYLLABLE JJYALT
+CA22;CA22;110D 1163 11B5;CA22;110D 1163 11B5; # (쨢; 쨢; 쨢; 쨢; 쨢; ) HANGUL SYLLABLE JJYALP
+CA23;CA23;110D 1163 11B6;CA23;110D 1163 11B6; # (쨣; 쨣; 쨣; 쨣; 쨣; ) HANGUL SYLLABLE JJYALH
+CA24;CA24;110D 1163 11B7;CA24;110D 1163 11B7; # (쨤; 쨤; 쨤; 쨤; 쨤; ) HANGUL SYLLABLE JJYAM
+CA25;CA25;110D 1163 11B8;CA25;110D 1163 11B8; # (쨥; 쨥; 쨥; 쨥; 쨥; ) HANGUL SYLLABLE JJYAB
+CA26;CA26;110D 1163 11B9;CA26;110D 1163 11B9; # (쨦; 쨦; 쨦; 쨦; 쨦; ) HANGUL SYLLABLE JJYABS
+CA27;CA27;110D 1163 11BA;CA27;110D 1163 11BA; # (쨧; 쨧; 쨧; 쨧; 쨧; ) HANGUL SYLLABLE JJYAS
+CA28;CA28;110D 1163 11BB;CA28;110D 1163 11BB; # (쨨; 쨨; 쨨; 쨨; 쨨; ) HANGUL SYLLABLE JJYASS
+CA29;CA29;110D 1163 11BC;CA29;110D 1163 11BC; # (쨩; 쨩; 쨩; 쨩; 쨩; ) HANGUL SYLLABLE JJYANG
+CA2A;CA2A;110D 1163 11BD;CA2A;110D 1163 11BD; # (쨪; 쨪; 쨪; 쨪; 쨪; ) HANGUL SYLLABLE JJYAJ
+CA2B;CA2B;110D 1163 11BE;CA2B;110D 1163 11BE; # (쨫; 쨫; 쨫; 쨫; 쨫; ) HANGUL SYLLABLE JJYAC
+CA2C;CA2C;110D 1163 11BF;CA2C;110D 1163 11BF; # (쨬; 쨬; 쨬; 쨬; 쨬; ) HANGUL SYLLABLE JJYAK
+CA2D;CA2D;110D 1163 11C0;CA2D;110D 1163 11C0; # (쨭; 쨭; 쨭; 쨭; 쨭; ) HANGUL SYLLABLE JJYAT
+CA2E;CA2E;110D 1163 11C1;CA2E;110D 1163 11C1; # (쨮; 쨮; 쨮; 쨮; 쨮; ) HANGUL SYLLABLE JJYAP
+CA2F;CA2F;110D 1163 11C2;CA2F;110D 1163 11C2; # (쨯; 쨯; 쨯; 쨯; 쨯; ) HANGUL SYLLABLE JJYAH
+CA30;CA30;110D 1164;CA30;110D 1164; # (쨰; 쨰; 쨰; 쨰; 쨰; ) HANGUL SYLLABLE JJYAE
+CA31;CA31;110D 1164 11A8;CA31;110D 1164 11A8; # (쨱; 쨱; 쨱; 쨱; 쨱; ) HANGUL SYLLABLE JJYAEG
+CA32;CA32;110D 1164 11A9;CA32;110D 1164 11A9; # (쨲; 쨲; 쨲; 쨲; 쨲; ) HANGUL SYLLABLE JJYAEGG
+CA33;CA33;110D 1164 11AA;CA33;110D 1164 11AA; # (쨳; 쨳; 쨳; 쨳; 쨳; ) HANGUL SYLLABLE JJYAEGS
+CA34;CA34;110D 1164 11AB;CA34;110D 1164 11AB; # (쨴; 쨴; 쨴; 쨴; 쨴; ) HANGUL SYLLABLE JJYAEN
+CA35;CA35;110D 1164 11AC;CA35;110D 1164 11AC; # (쨵; 쨵; 쨵; 쨵; 쨵; ) HANGUL SYLLABLE JJYAENJ
+CA36;CA36;110D 1164 11AD;CA36;110D 1164 11AD; # (쨶; 쨶; 쨶; 쨶; 쨶; ) HANGUL SYLLABLE JJYAENH
+CA37;CA37;110D 1164 11AE;CA37;110D 1164 11AE; # (쨷; 쨷; 쨷; 쨷; 쨷; ) HANGUL SYLLABLE JJYAED
+CA38;CA38;110D 1164 11AF;CA38;110D 1164 11AF; # (쨸; 쨸; 쨸; 쨸; 쨸; ) HANGUL SYLLABLE JJYAEL
+CA39;CA39;110D 1164 11B0;CA39;110D 1164 11B0; # (쨹; 쨹; 쨹; 쨹; 쨹; ) HANGUL SYLLABLE JJYAELG
+CA3A;CA3A;110D 1164 11B1;CA3A;110D 1164 11B1; # (쨺; 쨺; 쨺; 쨺; 쨺; ) HANGUL SYLLABLE JJYAELM
+CA3B;CA3B;110D 1164 11B2;CA3B;110D 1164 11B2; # (쨻; 쨻; 쨻; 쨻; 쨻; ) HANGUL SYLLABLE JJYAELB
+CA3C;CA3C;110D 1164 11B3;CA3C;110D 1164 11B3; # (쨼; 쨼; 쨼; 쨼; 쨼; ) HANGUL SYLLABLE JJYAELS
+CA3D;CA3D;110D 1164 11B4;CA3D;110D 1164 11B4; # (쨽; 쨽; 쨽; 쨽; 쨽; ) HANGUL SYLLABLE JJYAELT
+CA3E;CA3E;110D 1164 11B5;CA3E;110D 1164 11B5; # (쨾; 쨾; 쨾; 쨾; 쨾; ) HANGUL SYLLABLE JJYAELP
+CA3F;CA3F;110D 1164 11B6;CA3F;110D 1164 11B6; # (쨿; 쨿; 쨿; 쨿; 쨿; ) HANGUL SYLLABLE JJYAELH
+CA40;CA40;110D 1164 11B7;CA40;110D 1164 11B7; # (쩀; 쩀; 쩀; 쩀; 쩀; ) HANGUL SYLLABLE JJYAEM
+CA41;CA41;110D 1164 11B8;CA41;110D 1164 11B8; # (쩁; 쩁; 쩁; 쩁; 쩁; ) HANGUL SYLLABLE JJYAEB
+CA42;CA42;110D 1164 11B9;CA42;110D 1164 11B9; # (쩂; 쩂; 쩂; 쩂; 쩂; ) HANGUL SYLLABLE JJYAEBS
+CA43;CA43;110D 1164 11BA;CA43;110D 1164 11BA; # (쩃; 쩃; 쩃; 쩃; 쩃; ) HANGUL SYLLABLE JJYAES
+CA44;CA44;110D 1164 11BB;CA44;110D 1164 11BB; # (쩄; 쩄; 쩄; 쩄; 쩄; ) HANGUL SYLLABLE JJYAESS
+CA45;CA45;110D 1164 11BC;CA45;110D 1164 11BC; # (쩅; 쩅; 쩅; 쩅; 쩅; ) HANGUL SYLLABLE JJYAENG
+CA46;CA46;110D 1164 11BD;CA46;110D 1164 11BD; # (쩆; 쩆; 쩆; 쩆; 쩆; ) HANGUL SYLLABLE JJYAEJ
+CA47;CA47;110D 1164 11BE;CA47;110D 1164 11BE; # (쩇; 쩇; 쩇; 쩇; 쩇; ) HANGUL SYLLABLE JJYAEC
+CA48;CA48;110D 1164 11BF;CA48;110D 1164 11BF; # (쩈; 쩈; 쩈; 쩈; 쩈; ) HANGUL SYLLABLE JJYAEK
+CA49;CA49;110D 1164 11C0;CA49;110D 1164 11C0; # (쩉; 쩉; 쩉; 쩉; 쩉; ) HANGUL SYLLABLE JJYAET
+CA4A;CA4A;110D 1164 11C1;CA4A;110D 1164 11C1; # (쩊; 쩊; 쩊; 쩊; 쩊; ) HANGUL SYLLABLE JJYAEP
+CA4B;CA4B;110D 1164 11C2;CA4B;110D 1164 11C2; # (쩋; 쩋; 쩋; 쩋; 쩋; ) HANGUL SYLLABLE JJYAEH
+CA4C;CA4C;110D 1165;CA4C;110D 1165; # (쩌; 쩌; 쩌; 쩌; 쩌; ) HANGUL SYLLABLE JJEO
+CA4D;CA4D;110D 1165 11A8;CA4D;110D 1165 11A8; # (쩍; 쩍; 쩍; 쩍; 쩍; ) HANGUL SYLLABLE JJEOG
+CA4E;CA4E;110D 1165 11A9;CA4E;110D 1165 11A9; # (쩎; 쩎; 쩎; 쩎; 쩎; ) HANGUL SYLLABLE JJEOGG
+CA4F;CA4F;110D 1165 11AA;CA4F;110D 1165 11AA; # (쩏; 쩏; 쩏; 쩏; 쩏; ) HANGUL SYLLABLE JJEOGS
+CA50;CA50;110D 1165 11AB;CA50;110D 1165 11AB; # (쩐; 쩐; 쩐; 쩐; 쩐; ) HANGUL SYLLABLE JJEON
+CA51;CA51;110D 1165 11AC;CA51;110D 1165 11AC; # (쩑; 쩑; 쩑; 쩑; 쩑; ) HANGUL SYLLABLE JJEONJ
+CA52;CA52;110D 1165 11AD;CA52;110D 1165 11AD; # (쩒; 쩒; 쩒; 쩒; 쩒; ) HANGUL SYLLABLE JJEONH
+CA53;CA53;110D 1165 11AE;CA53;110D 1165 11AE; # (쩓; 쩓; 쩓; 쩓; 쩓; ) HANGUL SYLLABLE JJEOD
+CA54;CA54;110D 1165 11AF;CA54;110D 1165 11AF; # (쩔; 쩔; 쩔; 쩔; 쩔; ) HANGUL SYLLABLE JJEOL
+CA55;CA55;110D 1165 11B0;CA55;110D 1165 11B0; # (쩕; 쩕; 쩕; 쩕; 쩕; ) HANGUL SYLLABLE JJEOLG
+CA56;CA56;110D 1165 11B1;CA56;110D 1165 11B1; # (쩖; 쩖; 쩖; 쩖; 쩖; ) HANGUL SYLLABLE JJEOLM
+CA57;CA57;110D 1165 11B2;CA57;110D 1165 11B2; # (쩗; 쩗; 쩗; 쩗; 쩗; ) HANGUL SYLLABLE JJEOLB
+CA58;CA58;110D 1165 11B3;CA58;110D 1165 11B3; # (쩘; 쩘; 쩘; 쩘; 쩘; ) HANGUL SYLLABLE JJEOLS
+CA59;CA59;110D 1165 11B4;CA59;110D 1165 11B4; # (쩙; 쩙; 쩙; 쩙; 쩙; ) HANGUL SYLLABLE JJEOLT
+CA5A;CA5A;110D 1165 11B5;CA5A;110D 1165 11B5; # (쩚; 쩚; 쩚; 쩚; 쩚; ) HANGUL SYLLABLE JJEOLP
+CA5B;CA5B;110D 1165 11B6;CA5B;110D 1165 11B6; # (쩛; 쩛; 쩛; 쩛; 쩛; ) HANGUL SYLLABLE JJEOLH
+CA5C;CA5C;110D 1165 11B7;CA5C;110D 1165 11B7; # (쩜; 쩜; 쩜; 쩜; 쩜; ) HANGUL SYLLABLE JJEOM
+CA5D;CA5D;110D 1165 11B8;CA5D;110D 1165 11B8; # (쩝; 쩝; 쩝; 쩝; 쩝; ) HANGUL SYLLABLE JJEOB
+CA5E;CA5E;110D 1165 11B9;CA5E;110D 1165 11B9; # (쩞; 쩞; 쩞; 쩞; 쩞; ) HANGUL SYLLABLE JJEOBS
+CA5F;CA5F;110D 1165 11BA;CA5F;110D 1165 11BA; # (쩟; 쩟; 쩟; 쩟; 쩟; ) HANGUL SYLLABLE JJEOS
+CA60;CA60;110D 1165 11BB;CA60;110D 1165 11BB; # (쩠; 쩠; 쩠; 쩠; 쩠; ) HANGUL SYLLABLE JJEOSS
+CA61;CA61;110D 1165 11BC;CA61;110D 1165 11BC; # (쩡; 쩡; 쩡; 쩡; 쩡; ) HANGUL SYLLABLE JJEONG
+CA62;CA62;110D 1165 11BD;CA62;110D 1165 11BD; # (쩢; 쩢; 쩢; 쩢; 쩢; ) HANGUL SYLLABLE JJEOJ
+CA63;CA63;110D 1165 11BE;CA63;110D 1165 11BE; # (쩣; 쩣; 쩣; 쩣; 쩣; ) HANGUL SYLLABLE JJEOC
+CA64;CA64;110D 1165 11BF;CA64;110D 1165 11BF; # (쩤; 쩤; 쩤; 쩤; 쩤; ) HANGUL SYLLABLE JJEOK
+CA65;CA65;110D 1165 11C0;CA65;110D 1165 11C0; # (쩥; 쩥; 쩥; 쩥; 쩥; ) HANGUL SYLLABLE JJEOT
+CA66;CA66;110D 1165 11C1;CA66;110D 1165 11C1; # (쩦; 쩦; 쩦; 쩦; 쩦; ) HANGUL SYLLABLE JJEOP
+CA67;CA67;110D 1165 11C2;CA67;110D 1165 11C2; # (쩧; 쩧; 쩧; 쩧; 쩧; ) HANGUL SYLLABLE JJEOH
+CA68;CA68;110D 1166;CA68;110D 1166; # (쩨; 쩨; 쩨; 쩨; 쩨; ) HANGUL SYLLABLE JJE
+CA69;CA69;110D 1166 11A8;CA69;110D 1166 11A8; # (쩩; 쩩; 쩩; 쩩; 쩩; ) HANGUL SYLLABLE JJEG
+CA6A;CA6A;110D 1166 11A9;CA6A;110D 1166 11A9; # (쩪; 쩪; 쩪; 쩪; 쩪; ) HANGUL SYLLABLE JJEGG
+CA6B;CA6B;110D 1166 11AA;CA6B;110D 1166 11AA; # (쩫; 쩫; 쩫; 쩫; 쩫; ) HANGUL SYLLABLE JJEGS
+CA6C;CA6C;110D 1166 11AB;CA6C;110D 1166 11AB; # (쩬; 쩬; 쩬; 쩬; 쩬; ) HANGUL SYLLABLE JJEN
+CA6D;CA6D;110D 1166 11AC;CA6D;110D 1166 11AC; # (쩭; 쩭; 쩭; 쩭; 쩭; ) HANGUL SYLLABLE JJENJ
+CA6E;CA6E;110D 1166 11AD;CA6E;110D 1166 11AD; # (쩮; 쩮; 쩮; 쩮; 쩮; ) HANGUL SYLLABLE JJENH
+CA6F;CA6F;110D 1166 11AE;CA6F;110D 1166 11AE; # (쩯; 쩯; 쩯; 쩯; 쩯; ) HANGUL SYLLABLE JJED
+CA70;CA70;110D 1166 11AF;CA70;110D 1166 11AF; # (쩰; 쩰; 쩰; 쩰; 쩰; ) HANGUL SYLLABLE JJEL
+CA71;CA71;110D 1166 11B0;CA71;110D 1166 11B0; # (쩱; 쩱; 쩱; 쩱; 쩱; ) HANGUL SYLLABLE JJELG
+CA72;CA72;110D 1166 11B1;CA72;110D 1166 11B1; # (쩲; 쩲; 쩲; 쩲; 쩲; ) HANGUL SYLLABLE JJELM
+CA73;CA73;110D 1166 11B2;CA73;110D 1166 11B2; # (쩳; 쩳; 쩳; 쩳; 쩳; ) HANGUL SYLLABLE JJELB
+CA74;CA74;110D 1166 11B3;CA74;110D 1166 11B3; # (쩴; 쩴; 쩴; 쩴; 쩴; ) HANGUL SYLLABLE JJELS
+CA75;CA75;110D 1166 11B4;CA75;110D 1166 11B4; # (쩵; 쩵; 쩵; 쩵; 쩵; ) HANGUL SYLLABLE JJELT
+CA76;CA76;110D 1166 11B5;CA76;110D 1166 11B5; # (쩶; 쩶; 쩶; 쩶; 쩶; ) HANGUL SYLLABLE JJELP
+CA77;CA77;110D 1166 11B6;CA77;110D 1166 11B6; # (쩷; 쩷; 쩷; 쩷; 쩷; ) HANGUL SYLLABLE JJELH
+CA78;CA78;110D 1166 11B7;CA78;110D 1166 11B7; # (쩸; 쩸; 쩸; 쩸; 쩸; ) HANGUL SYLLABLE JJEM
+CA79;CA79;110D 1166 11B8;CA79;110D 1166 11B8; # (쩹; 쩹; 쩹; 쩹; 쩹; ) HANGUL SYLLABLE JJEB
+CA7A;CA7A;110D 1166 11B9;CA7A;110D 1166 11B9; # (쩺; 쩺; 쩺; 쩺; 쩺; ) HANGUL SYLLABLE JJEBS
+CA7B;CA7B;110D 1166 11BA;CA7B;110D 1166 11BA; # (쩻; 쩻; 쩻; 쩻; 쩻; ) HANGUL SYLLABLE JJES
+CA7C;CA7C;110D 1166 11BB;CA7C;110D 1166 11BB; # (쩼; 쩼; 쩼; 쩼; 쩼; ) HANGUL SYLLABLE JJESS
+CA7D;CA7D;110D 1166 11BC;CA7D;110D 1166 11BC; # (쩽; 쩽; 쩽; 쩽; 쩽; ) HANGUL SYLLABLE JJENG
+CA7E;CA7E;110D 1166 11BD;CA7E;110D 1166 11BD; # (쩾; 쩾; 쩾; 쩾; 쩾; ) HANGUL SYLLABLE JJEJ
+CA7F;CA7F;110D 1166 11BE;CA7F;110D 1166 11BE; # (쩿; 쩿; 쩿; 쩿; 쩿; ) HANGUL SYLLABLE JJEC
+CA80;CA80;110D 1166 11BF;CA80;110D 1166 11BF; # (쪀; 쪀; 쪀; 쪀; 쪀; ) HANGUL SYLLABLE JJEK
+CA81;CA81;110D 1166 11C0;CA81;110D 1166 11C0; # (쪁; 쪁; 쪁; 쪁; 쪁; ) HANGUL SYLLABLE JJET
+CA82;CA82;110D 1166 11C1;CA82;110D 1166 11C1; # (쪂; 쪂; 쪂; 쪂; 쪂; ) HANGUL SYLLABLE JJEP
+CA83;CA83;110D 1166 11C2;CA83;110D 1166 11C2; # (쪃; 쪃; 쪃; 쪃; 쪃; ) HANGUL SYLLABLE JJEH
+CA84;CA84;110D 1167;CA84;110D 1167; # (쪄; 쪄; 쪄; 쪄; 쪄; ) HANGUL SYLLABLE JJYEO
+CA85;CA85;110D 1167 11A8;CA85;110D 1167 11A8; # (쪅; 쪅; 쪅; 쪅; 쪅; ) HANGUL SYLLABLE JJYEOG
+CA86;CA86;110D 1167 11A9;CA86;110D 1167 11A9; # (쪆; 쪆; 쪆; 쪆; 쪆; ) HANGUL SYLLABLE JJYEOGG
+CA87;CA87;110D 1167 11AA;CA87;110D 1167 11AA; # (쪇; 쪇; 쪇; 쪇; 쪇; ) HANGUL SYLLABLE JJYEOGS
+CA88;CA88;110D 1167 11AB;CA88;110D 1167 11AB; # (쪈; 쪈; 쪈; 쪈; 쪈; ) HANGUL SYLLABLE JJYEON
+CA89;CA89;110D 1167 11AC;CA89;110D 1167 11AC; # (쪉; 쪉; 쪉; 쪉; 쪉; ) HANGUL SYLLABLE JJYEONJ
+CA8A;CA8A;110D 1167 11AD;CA8A;110D 1167 11AD; # (쪊; 쪊; 쪊; 쪊; 쪊; ) HANGUL SYLLABLE JJYEONH
+CA8B;CA8B;110D 1167 11AE;CA8B;110D 1167 11AE; # (쪋; 쪋; 쪋; 쪋; 쪋; ) HANGUL SYLLABLE JJYEOD
+CA8C;CA8C;110D 1167 11AF;CA8C;110D 1167 11AF; # (쪌; 쪌; 쪌; 쪌; 쪌; ) HANGUL SYLLABLE JJYEOL
+CA8D;CA8D;110D 1167 11B0;CA8D;110D 1167 11B0; # (쪍; 쪍; 쪍; 쪍; 쪍; ) HANGUL SYLLABLE JJYEOLG
+CA8E;CA8E;110D 1167 11B1;CA8E;110D 1167 11B1; # (쪎; 쪎; 쪎; 쪎; 쪎; ) HANGUL SYLLABLE JJYEOLM
+CA8F;CA8F;110D 1167 11B2;CA8F;110D 1167 11B2; # (쪏; 쪏; 쪏; 쪏; 쪏; ) HANGUL SYLLABLE JJYEOLB
+CA90;CA90;110D 1167 11B3;CA90;110D 1167 11B3; # (쪐; 쪐; 쪐; 쪐; 쪐; ) HANGUL SYLLABLE JJYEOLS
+CA91;CA91;110D 1167 11B4;CA91;110D 1167 11B4; # (쪑; 쪑; 쪑; 쪑; 쪑; ) HANGUL SYLLABLE JJYEOLT
+CA92;CA92;110D 1167 11B5;CA92;110D 1167 11B5; # (쪒; 쪒; 쪒; 쪒; 쪒; ) HANGUL SYLLABLE JJYEOLP
+CA93;CA93;110D 1167 11B6;CA93;110D 1167 11B6; # (쪓; 쪓; 쪓; 쪓; 쪓; ) HANGUL SYLLABLE JJYEOLH
+CA94;CA94;110D 1167 11B7;CA94;110D 1167 11B7; # (쪔; 쪔; 쪔; 쪔; 쪔; ) HANGUL SYLLABLE JJYEOM
+CA95;CA95;110D 1167 11B8;CA95;110D 1167 11B8; # (쪕; 쪕; 쪕; 쪕; 쪕; ) HANGUL SYLLABLE JJYEOB
+CA96;CA96;110D 1167 11B9;CA96;110D 1167 11B9; # (쪖; 쪖; 쪖; 쪖; 쪖; ) HANGUL SYLLABLE JJYEOBS
+CA97;CA97;110D 1167 11BA;CA97;110D 1167 11BA; # (쪗; 쪗; 쪗; 쪗; 쪗; ) HANGUL SYLLABLE JJYEOS
+CA98;CA98;110D 1167 11BB;CA98;110D 1167 11BB; # (쪘; 쪘; 쪘; 쪘; 쪘; ) HANGUL SYLLABLE JJYEOSS
+CA99;CA99;110D 1167 11BC;CA99;110D 1167 11BC; # (쪙; 쪙; 쪙; 쪙; 쪙; ) HANGUL SYLLABLE JJYEONG
+CA9A;CA9A;110D 1167 11BD;CA9A;110D 1167 11BD; # (쪚; 쪚; 쪚; 쪚; 쪚; ) HANGUL SYLLABLE JJYEOJ
+CA9B;CA9B;110D 1167 11BE;CA9B;110D 1167 11BE; # (쪛; 쪛; 쪛; 쪛; 쪛; ) HANGUL SYLLABLE JJYEOC
+CA9C;CA9C;110D 1167 11BF;CA9C;110D 1167 11BF; # (쪜; 쪜; 쪜; 쪜; 쪜; ) HANGUL SYLLABLE JJYEOK
+CA9D;CA9D;110D 1167 11C0;CA9D;110D 1167 11C0; # (쪝; 쪝; 쪝; 쪝; 쪝; ) HANGUL SYLLABLE JJYEOT
+CA9E;CA9E;110D 1167 11C1;CA9E;110D 1167 11C1; # (쪞; 쪞; 쪞; 쪞; 쪞; ) HANGUL SYLLABLE JJYEOP
+CA9F;CA9F;110D 1167 11C2;CA9F;110D 1167 11C2; # (쪟; 쪟; 쪟; 쪟; 쪟; ) HANGUL SYLLABLE JJYEOH
+CAA0;CAA0;110D 1168;CAA0;110D 1168; # (쪠; 쪠; 쪠; 쪠; 쪠; ) HANGUL SYLLABLE JJYE
+CAA1;CAA1;110D 1168 11A8;CAA1;110D 1168 11A8; # (쪡; 쪡; 쪡; 쪡; 쪡; ) HANGUL SYLLABLE JJYEG
+CAA2;CAA2;110D 1168 11A9;CAA2;110D 1168 11A9; # (쪢; 쪢; 쪢; 쪢; 쪢; ) HANGUL SYLLABLE JJYEGG
+CAA3;CAA3;110D 1168 11AA;CAA3;110D 1168 11AA; # (쪣; 쪣; 쪣; 쪣; 쪣; ) HANGUL SYLLABLE JJYEGS
+CAA4;CAA4;110D 1168 11AB;CAA4;110D 1168 11AB; # (쪤; 쪤; 쪤; 쪤; 쪤; ) HANGUL SYLLABLE JJYEN
+CAA5;CAA5;110D 1168 11AC;CAA5;110D 1168 11AC; # (쪥; 쪥; 쪥; 쪥; 쪥; ) HANGUL SYLLABLE JJYENJ
+CAA6;CAA6;110D 1168 11AD;CAA6;110D 1168 11AD; # (쪦; 쪦; 쪦; 쪦; 쪦; ) HANGUL SYLLABLE JJYENH
+CAA7;CAA7;110D 1168 11AE;CAA7;110D 1168 11AE; # (쪧; 쪧; 쪧; 쪧; 쪧; ) HANGUL SYLLABLE JJYED
+CAA8;CAA8;110D 1168 11AF;CAA8;110D 1168 11AF; # (쪨; 쪨; 쪨; 쪨; 쪨; ) HANGUL SYLLABLE JJYEL
+CAA9;CAA9;110D 1168 11B0;CAA9;110D 1168 11B0; # (쪩; 쪩; 쪩; 쪩; 쪩; ) HANGUL SYLLABLE JJYELG
+CAAA;CAAA;110D 1168 11B1;CAAA;110D 1168 11B1; # (쪪; 쪪; 쪪; 쪪; 쪪; ) HANGUL SYLLABLE JJYELM
+CAAB;CAAB;110D 1168 11B2;CAAB;110D 1168 11B2; # (쪫; 쪫; 쪫; 쪫; 쪫; ) HANGUL SYLLABLE JJYELB
+CAAC;CAAC;110D 1168 11B3;CAAC;110D 1168 11B3; # (쪬; 쪬; 쪬; 쪬; 쪬; ) HANGUL SYLLABLE JJYELS
+CAAD;CAAD;110D 1168 11B4;CAAD;110D 1168 11B4; # (쪭; 쪭; 쪭; 쪭; 쪭; ) HANGUL SYLLABLE JJYELT
+CAAE;CAAE;110D 1168 11B5;CAAE;110D 1168 11B5; # (쪮; 쪮; 쪮; 쪮; 쪮; ) HANGUL SYLLABLE JJYELP
+CAAF;CAAF;110D 1168 11B6;CAAF;110D 1168 11B6; # (쪯; 쪯; 쪯; 쪯; 쪯; ) HANGUL SYLLABLE JJYELH
+CAB0;CAB0;110D 1168 11B7;CAB0;110D 1168 11B7; # (쪰; 쪰; 쪰; 쪰; 쪰; ) HANGUL SYLLABLE JJYEM
+CAB1;CAB1;110D 1168 11B8;CAB1;110D 1168 11B8; # (쪱; 쪱; 쪱; 쪱; 쪱; ) HANGUL SYLLABLE JJYEB
+CAB2;CAB2;110D 1168 11B9;CAB2;110D 1168 11B9; # (쪲; 쪲; 쪲; 쪲; 쪲; ) HANGUL SYLLABLE JJYEBS
+CAB3;CAB3;110D 1168 11BA;CAB3;110D 1168 11BA; # (쪳; 쪳; 쪳; 쪳; 쪳; ) HANGUL SYLLABLE JJYES
+CAB4;CAB4;110D 1168 11BB;CAB4;110D 1168 11BB; # (쪴; 쪴; 쪴; 쪴; 쪴; ) HANGUL SYLLABLE JJYESS
+CAB5;CAB5;110D 1168 11BC;CAB5;110D 1168 11BC; # (쪵; 쪵; 쪵; 쪵; 쪵; ) HANGUL SYLLABLE JJYENG
+CAB6;CAB6;110D 1168 11BD;CAB6;110D 1168 11BD; # (쪶; 쪶; 쪶; 쪶; 쪶; ) HANGUL SYLLABLE JJYEJ
+CAB7;CAB7;110D 1168 11BE;CAB7;110D 1168 11BE; # (쪷; 쪷; 쪷; 쪷; 쪷; ) HANGUL SYLLABLE JJYEC
+CAB8;CAB8;110D 1168 11BF;CAB8;110D 1168 11BF; # (쪸; 쪸; 쪸; 쪸; 쪸; ) HANGUL SYLLABLE JJYEK
+CAB9;CAB9;110D 1168 11C0;CAB9;110D 1168 11C0; # (쪹; 쪹; 쪹; 쪹; 쪹; ) HANGUL SYLLABLE JJYET
+CABA;CABA;110D 1168 11C1;CABA;110D 1168 11C1; # (쪺; 쪺; 쪺; 쪺; 쪺; ) HANGUL SYLLABLE JJYEP
+CABB;CABB;110D 1168 11C2;CABB;110D 1168 11C2; # (쪻; 쪻; 쪻; 쪻; 쪻; ) HANGUL SYLLABLE JJYEH
+CABC;CABC;110D 1169;CABC;110D 1169; # (쪼; 쪼; 쪼; 쪼; 쪼; ) HANGUL SYLLABLE JJO
+CABD;CABD;110D 1169 11A8;CABD;110D 1169 11A8; # (쪽; 쪽; 쪽; 쪽; 쪽; ) HANGUL SYLLABLE JJOG
+CABE;CABE;110D 1169 11A9;CABE;110D 1169 11A9; # (쪾; 쪾; 쪾; 쪾; 쪾; ) HANGUL SYLLABLE JJOGG
+CABF;CABF;110D 1169 11AA;CABF;110D 1169 11AA; # (쪿; 쪿; 쪿; 쪿; 쪿; ) HANGUL SYLLABLE JJOGS
+CAC0;CAC0;110D 1169 11AB;CAC0;110D 1169 11AB; # (쫀; 쫀; 쫀; 쫀; 쫀; ) HANGUL SYLLABLE JJON
+CAC1;CAC1;110D 1169 11AC;CAC1;110D 1169 11AC; # (쫁; 쫁; 쫁; 쫁; 쫁; ) HANGUL SYLLABLE JJONJ
+CAC2;CAC2;110D 1169 11AD;CAC2;110D 1169 11AD; # (쫂; 쫂; 쫂; 쫂; 쫂; ) HANGUL SYLLABLE JJONH
+CAC3;CAC3;110D 1169 11AE;CAC3;110D 1169 11AE; # (쫃; 쫃; 쫃; 쫃; 쫃; ) HANGUL SYLLABLE JJOD
+CAC4;CAC4;110D 1169 11AF;CAC4;110D 1169 11AF; # (쫄; 쫄; 쫄; 쫄; 쫄; ) HANGUL SYLLABLE JJOL
+CAC5;CAC5;110D 1169 11B0;CAC5;110D 1169 11B0; # (쫅; 쫅; 쫅; 쫅; 쫅; ) HANGUL SYLLABLE JJOLG
+CAC6;CAC6;110D 1169 11B1;CAC6;110D 1169 11B1; # (쫆; 쫆; 쫆; 쫆; 쫆; ) HANGUL SYLLABLE JJOLM
+CAC7;CAC7;110D 1169 11B2;CAC7;110D 1169 11B2; # (쫇; 쫇; 쫇; 쫇; 쫇; ) HANGUL SYLLABLE JJOLB
+CAC8;CAC8;110D 1169 11B3;CAC8;110D 1169 11B3; # (쫈; 쫈; 쫈; 쫈; 쫈; ) HANGUL SYLLABLE JJOLS
+CAC9;CAC9;110D 1169 11B4;CAC9;110D 1169 11B4; # (쫉; 쫉; 쫉; 쫉; 쫉; ) HANGUL SYLLABLE JJOLT
+CACA;CACA;110D 1169 11B5;CACA;110D 1169 11B5; # (쫊; 쫊; 쫊; 쫊; 쫊; ) HANGUL SYLLABLE JJOLP
+CACB;CACB;110D 1169 11B6;CACB;110D 1169 11B6; # (쫋; 쫋; 쫋; 쫋; 쫋; ) HANGUL SYLLABLE JJOLH
+CACC;CACC;110D 1169 11B7;CACC;110D 1169 11B7; # (쫌; 쫌; 쫌; 쫌; 쫌; ) HANGUL SYLLABLE JJOM
+CACD;CACD;110D 1169 11B8;CACD;110D 1169 11B8; # (쫍; 쫍; 쫍; 쫍; 쫍; ) HANGUL SYLLABLE JJOB
+CACE;CACE;110D 1169 11B9;CACE;110D 1169 11B9; # (쫎; 쫎; 쫎; 쫎; 쫎; ) HANGUL SYLLABLE JJOBS
+CACF;CACF;110D 1169 11BA;CACF;110D 1169 11BA; # (쫏; 쫏; 쫏; 쫏; 쫏; ) HANGUL SYLLABLE JJOS
+CAD0;CAD0;110D 1169 11BB;CAD0;110D 1169 11BB; # (쫐; 쫐; 쫐; 쫐; 쫐; ) HANGUL SYLLABLE JJOSS
+CAD1;CAD1;110D 1169 11BC;CAD1;110D 1169 11BC; # (쫑; 쫑; 쫑; 쫑; 쫑; ) HANGUL SYLLABLE JJONG
+CAD2;CAD2;110D 1169 11BD;CAD2;110D 1169 11BD; # (쫒; 쫒; 쫒; 쫒; 쫒; ) HANGUL SYLLABLE JJOJ
+CAD3;CAD3;110D 1169 11BE;CAD3;110D 1169 11BE; # (쫓; 쫓; 쫓; 쫓; 쫓; ) HANGUL SYLLABLE JJOC
+CAD4;CAD4;110D 1169 11BF;CAD4;110D 1169 11BF; # (쫔; 쫔; 쫔; 쫔; 쫔; ) HANGUL SYLLABLE JJOK
+CAD5;CAD5;110D 1169 11C0;CAD5;110D 1169 11C0; # (쫕; 쫕; 쫕; 쫕; 쫕; ) HANGUL SYLLABLE JJOT
+CAD6;CAD6;110D 1169 11C1;CAD6;110D 1169 11C1; # (쫖; 쫖; 쫖; 쫖; 쫖; ) HANGUL SYLLABLE JJOP
+CAD7;CAD7;110D 1169 11C2;CAD7;110D 1169 11C2; # (쫗; 쫗; 쫗; 쫗; 쫗; ) HANGUL SYLLABLE JJOH
+CAD8;CAD8;110D 116A;CAD8;110D 116A; # (쫘; 쫘; 쫘; 쫘; 쫘; ) HANGUL SYLLABLE JJWA
+CAD9;CAD9;110D 116A 11A8;CAD9;110D 116A 11A8; # (쫙; 쫙; 쫙; 쫙; 쫙; ) HANGUL SYLLABLE JJWAG
+CADA;CADA;110D 116A 11A9;CADA;110D 116A 11A9; # (쫚; 쫚; 쫚; 쫚; 쫚; ) HANGUL SYLLABLE JJWAGG
+CADB;CADB;110D 116A 11AA;CADB;110D 116A 11AA; # (쫛; 쫛; 쫛; 쫛; 쫛; ) HANGUL SYLLABLE JJWAGS
+CADC;CADC;110D 116A 11AB;CADC;110D 116A 11AB; # (쫜; 쫜; 쫜; 쫜; 쫜; ) HANGUL SYLLABLE JJWAN
+CADD;CADD;110D 116A 11AC;CADD;110D 116A 11AC; # (쫝; 쫝; 쫝; 쫝; 쫝; ) HANGUL SYLLABLE JJWANJ
+CADE;CADE;110D 116A 11AD;CADE;110D 116A 11AD; # (쫞; 쫞; 쫞; 쫞; 쫞; ) HANGUL SYLLABLE JJWANH
+CADF;CADF;110D 116A 11AE;CADF;110D 116A 11AE; # (쫟; 쫟; 쫟; 쫟; 쫟; ) HANGUL SYLLABLE JJWAD
+CAE0;CAE0;110D 116A 11AF;CAE0;110D 116A 11AF; # (쫠; 쫠; 쫠; 쫠; 쫠; ) HANGUL SYLLABLE JJWAL
+CAE1;CAE1;110D 116A 11B0;CAE1;110D 116A 11B0; # (쫡; 쫡; 쫡; 쫡; 쫡; ) HANGUL SYLLABLE JJWALG
+CAE2;CAE2;110D 116A 11B1;CAE2;110D 116A 11B1; # (쫢; 쫢; 쫢; 쫢; 쫢; ) HANGUL SYLLABLE JJWALM
+CAE3;CAE3;110D 116A 11B2;CAE3;110D 116A 11B2; # (쫣; 쫣; 쫣; 쫣; 쫣; ) HANGUL SYLLABLE JJWALB
+CAE4;CAE4;110D 116A 11B3;CAE4;110D 116A 11B3; # (쫤; 쫤; 쫤; 쫤; 쫤; ) HANGUL SYLLABLE JJWALS
+CAE5;CAE5;110D 116A 11B4;CAE5;110D 116A 11B4; # (쫥; 쫥; 쫥; 쫥; 쫥; ) HANGUL SYLLABLE JJWALT
+CAE6;CAE6;110D 116A 11B5;CAE6;110D 116A 11B5; # (쫦; 쫦; 쫦; 쫦; 쫦; ) HANGUL SYLLABLE JJWALP
+CAE7;CAE7;110D 116A 11B6;CAE7;110D 116A 11B6; # (쫧; 쫧; 쫧; 쫧; 쫧; ) HANGUL SYLLABLE JJWALH
+CAE8;CAE8;110D 116A 11B7;CAE8;110D 116A 11B7; # (쫨; 쫨; 쫨; 쫨; 쫨; ) HANGUL SYLLABLE JJWAM
+CAE9;CAE9;110D 116A 11B8;CAE9;110D 116A 11B8; # (쫩; 쫩; 쫩; 쫩; 쫩; ) HANGUL SYLLABLE JJWAB
+CAEA;CAEA;110D 116A 11B9;CAEA;110D 116A 11B9; # (쫪; 쫪; 쫪; 쫪; 쫪; ) HANGUL SYLLABLE JJWABS
+CAEB;CAEB;110D 116A 11BA;CAEB;110D 116A 11BA; # (쫫; 쫫; 쫫; 쫫; 쫫; ) HANGUL SYLLABLE JJWAS
+CAEC;CAEC;110D 116A 11BB;CAEC;110D 116A 11BB; # (쫬; 쫬; 쫬; 쫬; 쫬; ) HANGUL SYLLABLE JJWASS
+CAED;CAED;110D 116A 11BC;CAED;110D 116A 11BC; # (쫭; 쫭; 쫭; 쫭; 쫭; ) HANGUL SYLLABLE JJWANG
+CAEE;CAEE;110D 116A 11BD;CAEE;110D 116A 11BD; # (쫮; 쫮; 쫮; 쫮; 쫮; ) HANGUL SYLLABLE JJWAJ
+CAEF;CAEF;110D 116A 11BE;CAEF;110D 116A 11BE; # (쫯; 쫯; 쫯; 쫯; 쫯; ) HANGUL SYLLABLE JJWAC
+CAF0;CAF0;110D 116A 11BF;CAF0;110D 116A 11BF; # (쫰; 쫰; 쫰; 쫰; 쫰; ) HANGUL SYLLABLE JJWAK
+CAF1;CAF1;110D 116A 11C0;CAF1;110D 116A 11C0; # (쫱; 쫱; 쫱; 쫱; 쫱; ) HANGUL SYLLABLE JJWAT
+CAF2;CAF2;110D 116A 11C1;CAF2;110D 116A 11C1; # (쫲; 쫲; 쫲; 쫲; 쫲; ) HANGUL SYLLABLE JJWAP
+CAF3;CAF3;110D 116A 11C2;CAF3;110D 116A 11C2; # (쫳; 쫳; 쫳; 쫳; 쫳; ) HANGUL SYLLABLE JJWAH
+CAF4;CAF4;110D 116B;CAF4;110D 116B; # (쫴; 쫴; 쫴; 쫴; 쫴; ) HANGUL SYLLABLE JJWAE
+CAF5;CAF5;110D 116B 11A8;CAF5;110D 116B 11A8; # (쫵; 쫵; 쫵; 쫵; 쫵; ) HANGUL SYLLABLE JJWAEG
+CAF6;CAF6;110D 116B 11A9;CAF6;110D 116B 11A9; # (쫶; 쫶; 쫶; 쫶; 쫶; ) HANGUL SYLLABLE JJWAEGG
+CAF7;CAF7;110D 116B 11AA;CAF7;110D 116B 11AA; # (쫷; 쫷; 쫷; 쫷; 쫷; ) HANGUL SYLLABLE JJWAEGS
+CAF8;CAF8;110D 116B 11AB;CAF8;110D 116B 11AB; # (쫸; 쫸; 쫸; 쫸; 쫸; ) HANGUL SYLLABLE JJWAEN
+CAF9;CAF9;110D 116B 11AC;CAF9;110D 116B 11AC; # (쫹; 쫹; 쫹; 쫹; 쫹; ) HANGUL SYLLABLE JJWAENJ
+CAFA;CAFA;110D 116B 11AD;CAFA;110D 116B 11AD; # (쫺; 쫺; 쫺; 쫺; 쫺; ) HANGUL SYLLABLE JJWAENH
+CAFB;CAFB;110D 116B 11AE;CAFB;110D 116B 11AE; # (쫻; 쫻; 쫻; 쫻; 쫻; ) HANGUL SYLLABLE JJWAED
+CAFC;CAFC;110D 116B 11AF;CAFC;110D 116B 11AF; # (쫼; 쫼; 쫼; 쫼; 쫼; ) HANGUL SYLLABLE JJWAEL
+CAFD;CAFD;110D 116B 11B0;CAFD;110D 116B 11B0; # (쫽; 쫽; 쫽; 쫽; 쫽; ) HANGUL SYLLABLE JJWAELG
+CAFE;CAFE;110D 116B 11B1;CAFE;110D 116B 11B1; # (쫾; 쫾; 쫾; 쫾; 쫾; ) HANGUL SYLLABLE JJWAELM
+CAFF;CAFF;110D 116B 11B2;CAFF;110D 116B 11B2; # (쫿; 쫿; 쫿; 쫿; 쫿; ) HANGUL SYLLABLE JJWAELB
+CB00;CB00;110D 116B 11B3;CB00;110D 116B 11B3; # (쬀; 쬀; 쬀; 쬀; 쬀; ) HANGUL SYLLABLE JJWAELS
+CB01;CB01;110D 116B 11B4;CB01;110D 116B 11B4; # (쬁; 쬁; 쬁; 쬁; 쬁; ) HANGUL SYLLABLE JJWAELT
+CB02;CB02;110D 116B 11B5;CB02;110D 116B 11B5; # (쬂; 쬂; 쬂; 쬂; 쬂; ) HANGUL SYLLABLE JJWAELP
+CB03;CB03;110D 116B 11B6;CB03;110D 116B 11B6; # (쬃; 쬃; 쬃; 쬃; 쬃; ) HANGUL SYLLABLE JJWAELH
+CB04;CB04;110D 116B 11B7;CB04;110D 116B 11B7; # (쬄; 쬄; 쬄; 쬄; 쬄; ) HANGUL SYLLABLE JJWAEM
+CB05;CB05;110D 116B 11B8;CB05;110D 116B 11B8; # (쬅; 쬅; 쬅; 쬅; 쬅; ) HANGUL SYLLABLE JJWAEB
+CB06;CB06;110D 116B 11B9;CB06;110D 116B 11B9; # (쬆; 쬆; 쬆; 쬆; 쬆; ) HANGUL SYLLABLE JJWAEBS
+CB07;CB07;110D 116B 11BA;CB07;110D 116B 11BA; # (쬇; 쬇; 쬇; 쬇; 쬇; ) HANGUL SYLLABLE JJWAES
+CB08;CB08;110D 116B 11BB;CB08;110D 116B 11BB; # (쬈; 쬈; 쬈; 쬈; 쬈; ) HANGUL SYLLABLE JJWAESS
+CB09;CB09;110D 116B 11BC;CB09;110D 116B 11BC; # (쬉; 쬉; 쬉; 쬉; 쬉; ) HANGUL SYLLABLE JJWAENG
+CB0A;CB0A;110D 116B 11BD;CB0A;110D 116B 11BD; # (쬊; 쬊; 쬊; 쬊; 쬊; ) HANGUL SYLLABLE JJWAEJ
+CB0B;CB0B;110D 116B 11BE;CB0B;110D 116B 11BE; # (쬋; 쬋; 쬋; 쬋; 쬋; ) HANGUL SYLLABLE JJWAEC
+CB0C;CB0C;110D 116B 11BF;CB0C;110D 116B 11BF; # (쬌; 쬌; 쬌; 쬌; 쬌; ) HANGUL SYLLABLE JJWAEK
+CB0D;CB0D;110D 116B 11C0;CB0D;110D 116B 11C0; # (쬍; 쬍; 쬍; 쬍; 쬍; ) HANGUL SYLLABLE JJWAET
+CB0E;CB0E;110D 116B 11C1;CB0E;110D 116B 11C1; # (쬎; 쬎; 쬎; 쬎; 쬎; ) HANGUL SYLLABLE JJWAEP
+CB0F;CB0F;110D 116B 11C2;CB0F;110D 116B 11C2; # (쬏; 쬏; 쬏; 쬏; 쬏; ) HANGUL SYLLABLE JJWAEH
+CB10;CB10;110D 116C;CB10;110D 116C; # (쬐; 쬐; 쬐; 쬐; 쬐; ) HANGUL SYLLABLE JJOE
+CB11;CB11;110D 116C 11A8;CB11;110D 116C 11A8; # (쬑; 쬑; 쬑; 쬑; 쬑; ) HANGUL SYLLABLE JJOEG
+CB12;CB12;110D 116C 11A9;CB12;110D 116C 11A9; # (쬒; 쬒; 쬒; 쬒; 쬒; ) HANGUL SYLLABLE JJOEGG
+CB13;CB13;110D 116C 11AA;CB13;110D 116C 11AA; # (쬓; 쬓; 쬓; 쬓; 쬓; ) HANGUL SYLLABLE JJOEGS
+CB14;CB14;110D 116C 11AB;CB14;110D 116C 11AB; # (쬔; 쬔; 쬔; 쬔; 쬔; ) HANGUL SYLLABLE JJOEN
+CB15;CB15;110D 116C 11AC;CB15;110D 116C 11AC; # (쬕; 쬕; 쬕; 쬕; 쬕; ) HANGUL SYLLABLE JJOENJ
+CB16;CB16;110D 116C 11AD;CB16;110D 116C 11AD; # (쬖; 쬖; 쬖; 쬖; 쬖; ) HANGUL SYLLABLE JJOENH
+CB17;CB17;110D 116C 11AE;CB17;110D 116C 11AE; # (쬗; 쬗; 쬗; 쬗; 쬗; ) HANGUL SYLLABLE JJOED
+CB18;CB18;110D 116C 11AF;CB18;110D 116C 11AF; # (쬘; 쬘; 쬘; 쬘; 쬘; ) HANGUL SYLLABLE JJOEL
+CB19;CB19;110D 116C 11B0;CB19;110D 116C 11B0; # (쬙; 쬙; 쬙; 쬙; 쬙; ) HANGUL SYLLABLE JJOELG
+CB1A;CB1A;110D 116C 11B1;CB1A;110D 116C 11B1; # (쬚; 쬚; 쬚; 쬚; 쬚; ) HANGUL SYLLABLE JJOELM
+CB1B;CB1B;110D 116C 11B2;CB1B;110D 116C 11B2; # (쬛; 쬛; 쬛; 쬛; 쬛; ) HANGUL SYLLABLE JJOELB
+CB1C;CB1C;110D 116C 11B3;CB1C;110D 116C 11B3; # (쬜; 쬜; 쬜; 쬜; 쬜; ) HANGUL SYLLABLE JJOELS
+CB1D;CB1D;110D 116C 11B4;CB1D;110D 116C 11B4; # (쬝; 쬝; 쬝; 쬝; 쬝; ) HANGUL SYLLABLE JJOELT
+CB1E;CB1E;110D 116C 11B5;CB1E;110D 116C 11B5; # (쬞; 쬞; 쬞; 쬞; 쬞; ) HANGUL SYLLABLE JJOELP
+CB1F;CB1F;110D 116C 11B6;CB1F;110D 116C 11B6; # (쬟; 쬟; 쬟; 쬟; 쬟; ) HANGUL SYLLABLE JJOELH
+CB20;CB20;110D 116C 11B7;CB20;110D 116C 11B7; # (쬠; 쬠; 쬠; 쬠; 쬠; ) HANGUL SYLLABLE JJOEM
+CB21;CB21;110D 116C 11B8;CB21;110D 116C 11B8; # (쬡; 쬡; 쬡; 쬡; 쬡; ) HANGUL SYLLABLE JJOEB
+CB22;CB22;110D 116C 11B9;CB22;110D 116C 11B9; # (쬢; 쬢; 쬢; 쬢; 쬢; ) HANGUL SYLLABLE JJOEBS
+CB23;CB23;110D 116C 11BA;CB23;110D 116C 11BA; # (쬣; 쬣; 쬣; 쬣; 쬣; ) HANGUL SYLLABLE JJOES
+CB24;CB24;110D 116C 11BB;CB24;110D 116C 11BB; # (쬤; 쬤; 쬤; 쬤; 쬤; ) HANGUL SYLLABLE JJOESS
+CB25;CB25;110D 116C 11BC;CB25;110D 116C 11BC; # (쬥; 쬥; 쬥; 쬥; 쬥; ) HANGUL SYLLABLE JJOENG
+CB26;CB26;110D 116C 11BD;CB26;110D 116C 11BD; # (쬦; 쬦; 쬦; 쬦; 쬦; ) HANGUL SYLLABLE JJOEJ
+CB27;CB27;110D 116C 11BE;CB27;110D 116C 11BE; # (쬧; 쬧; 쬧; 쬧; 쬧; ) HANGUL SYLLABLE JJOEC
+CB28;CB28;110D 116C 11BF;CB28;110D 116C 11BF; # (쬨; 쬨; 쬨; 쬨; 쬨; ) HANGUL SYLLABLE JJOEK
+CB29;CB29;110D 116C 11C0;CB29;110D 116C 11C0; # (쬩; 쬩; 쬩; 쬩; 쬩; ) HANGUL SYLLABLE JJOET
+CB2A;CB2A;110D 116C 11C1;CB2A;110D 116C 11C1; # (쬪; 쬪; 쬪; 쬪; 쬪; ) HANGUL SYLLABLE JJOEP
+CB2B;CB2B;110D 116C 11C2;CB2B;110D 116C 11C2; # (쬫; 쬫; 쬫; 쬫; 쬫; ) HANGUL SYLLABLE JJOEH
+CB2C;CB2C;110D 116D;CB2C;110D 116D; # (쬬; 쬬; 쬬; 쬬; 쬬; ) HANGUL SYLLABLE JJYO
+CB2D;CB2D;110D 116D 11A8;CB2D;110D 116D 11A8; # (쬭; 쬭; 쬭; 쬭; 쬭; ) HANGUL SYLLABLE JJYOG
+CB2E;CB2E;110D 116D 11A9;CB2E;110D 116D 11A9; # (쬮; 쬮; 쬮; 쬮; 쬮; ) HANGUL SYLLABLE JJYOGG
+CB2F;CB2F;110D 116D 11AA;CB2F;110D 116D 11AA; # (쬯; 쬯; 쬯; 쬯; 쬯; ) HANGUL SYLLABLE JJYOGS
+CB30;CB30;110D 116D 11AB;CB30;110D 116D 11AB; # (쬰; 쬰; 쬰; 쬰; 쬰; ) HANGUL SYLLABLE JJYON
+CB31;CB31;110D 116D 11AC;CB31;110D 116D 11AC; # (쬱; 쬱; 쬱; 쬱; 쬱; ) HANGUL SYLLABLE JJYONJ
+CB32;CB32;110D 116D 11AD;CB32;110D 116D 11AD; # (쬲; 쬲; 쬲; 쬲; 쬲; ) HANGUL SYLLABLE JJYONH
+CB33;CB33;110D 116D 11AE;CB33;110D 116D 11AE; # (쬳; 쬳; 쬳; 쬳; 쬳; ) HANGUL SYLLABLE JJYOD
+CB34;CB34;110D 116D 11AF;CB34;110D 116D 11AF; # (쬴; 쬴; 쬴; 쬴; 쬴; ) HANGUL SYLLABLE JJYOL
+CB35;CB35;110D 116D 11B0;CB35;110D 116D 11B0; # (쬵; 쬵; 쬵; 쬵; 쬵; ) HANGUL SYLLABLE JJYOLG
+CB36;CB36;110D 116D 11B1;CB36;110D 116D 11B1; # (쬶; 쬶; 쬶; 쬶; 쬶; ) HANGUL SYLLABLE JJYOLM
+CB37;CB37;110D 116D 11B2;CB37;110D 116D 11B2; # (쬷; 쬷; 쬷; 쬷; 쬷; ) HANGUL SYLLABLE JJYOLB
+CB38;CB38;110D 116D 11B3;CB38;110D 116D 11B3; # (쬸; 쬸; 쬸; 쬸; 쬸; ) HANGUL SYLLABLE JJYOLS
+CB39;CB39;110D 116D 11B4;CB39;110D 116D 11B4; # (쬹; 쬹; 쬹; 쬹; 쬹; ) HANGUL SYLLABLE JJYOLT
+CB3A;CB3A;110D 116D 11B5;CB3A;110D 116D 11B5; # (쬺; 쬺; 쬺; 쬺; 쬺; ) HANGUL SYLLABLE JJYOLP
+CB3B;CB3B;110D 116D 11B6;CB3B;110D 116D 11B6; # (쬻; 쬻; 쬻; 쬻; 쬻; ) HANGUL SYLLABLE JJYOLH
+CB3C;CB3C;110D 116D 11B7;CB3C;110D 116D 11B7; # (쬼; 쬼; 쬼; 쬼; 쬼; ) HANGUL SYLLABLE JJYOM
+CB3D;CB3D;110D 116D 11B8;CB3D;110D 116D 11B8; # (쬽; 쬽; 쬽; 쬽; 쬽; ) HANGUL SYLLABLE JJYOB
+CB3E;CB3E;110D 116D 11B9;CB3E;110D 116D 11B9; # (쬾; 쬾; 쬾; 쬾; 쬾; ) HANGUL SYLLABLE JJYOBS
+CB3F;CB3F;110D 116D 11BA;CB3F;110D 116D 11BA; # (쬿; 쬿; 쬿; 쬿; 쬿; ) HANGUL SYLLABLE JJYOS
+CB40;CB40;110D 116D 11BB;CB40;110D 116D 11BB; # (쭀; 쭀; 쭀; 쭀; 쭀; ) HANGUL SYLLABLE JJYOSS
+CB41;CB41;110D 116D 11BC;CB41;110D 116D 11BC; # (쭁; 쭁; 쭁; 쭁; 쭁; ) HANGUL SYLLABLE JJYONG
+CB42;CB42;110D 116D 11BD;CB42;110D 116D 11BD; # (쭂; 쭂; 쭂; 쭂; 쭂; ) HANGUL SYLLABLE JJYOJ
+CB43;CB43;110D 116D 11BE;CB43;110D 116D 11BE; # (쭃; 쭃; 쭃; 쭃; 쭃; ) HANGUL SYLLABLE JJYOC
+CB44;CB44;110D 116D 11BF;CB44;110D 116D 11BF; # (쭄; 쭄; 쭄; 쭄; 쭄; ) HANGUL SYLLABLE JJYOK
+CB45;CB45;110D 116D 11C0;CB45;110D 116D 11C0; # (쭅; 쭅; 쭅; 쭅; 쭅; ) HANGUL SYLLABLE JJYOT
+CB46;CB46;110D 116D 11C1;CB46;110D 116D 11C1; # (쭆; 쭆; 쭆; 쭆; 쭆; ) HANGUL SYLLABLE JJYOP
+CB47;CB47;110D 116D 11C2;CB47;110D 116D 11C2; # (쭇; 쭇; 쭇; 쭇; 쭇; ) HANGUL SYLLABLE JJYOH
+CB48;CB48;110D 116E;CB48;110D 116E; # (쭈; 쭈; 쭈; 쭈; 쭈; ) HANGUL SYLLABLE JJU
+CB49;CB49;110D 116E 11A8;CB49;110D 116E 11A8; # (쭉; 쭉; 쭉; 쭉; 쭉; ) HANGUL SYLLABLE JJUG
+CB4A;CB4A;110D 116E 11A9;CB4A;110D 116E 11A9; # (쭊; 쭊; 쭊; 쭊; 쭊; ) HANGUL SYLLABLE JJUGG
+CB4B;CB4B;110D 116E 11AA;CB4B;110D 116E 11AA; # (쭋; 쭋; 쭋; 쭋; 쭋; ) HANGUL SYLLABLE JJUGS
+CB4C;CB4C;110D 116E 11AB;CB4C;110D 116E 11AB; # (쭌; 쭌; 쭌; 쭌; 쭌; ) HANGUL SYLLABLE JJUN
+CB4D;CB4D;110D 116E 11AC;CB4D;110D 116E 11AC; # (쭍; 쭍; 쭍; 쭍; 쭍; ) HANGUL SYLLABLE JJUNJ
+CB4E;CB4E;110D 116E 11AD;CB4E;110D 116E 11AD; # (쭎; 쭎; 쭎; 쭎; 쭎; ) HANGUL SYLLABLE JJUNH
+CB4F;CB4F;110D 116E 11AE;CB4F;110D 116E 11AE; # (쭏; 쭏; 쭏; 쭏; 쭏; ) HANGUL SYLLABLE JJUD
+CB50;CB50;110D 116E 11AF;CB50;110D 116E 11AF; # (쭐; 쭐; 쭐; 쭐; 쭐; ) HANGUL SYLLABLE JJUL
+CB51;CB51;110D 116E 11B0;CB51;110D 116E 11B0; # (쭑; 쭑; 쭑; 쭑; 쭑; ) HANGUL SYLLABLE JJULG
+CB52;CB52;110D 116E 11B1;CB52;110D 116E 11B1; # (쭒; 쭒; 쭒; 쭒; 쭒; ) HANGUL SYLLABLE JJULM
+CB53;CB53;110D 116E 11B2;CB53;110D 116E 11B2; # (쭓; 쭓; 쭓; 쭓; 쭓; ) HANGUL SYLLABLE JJULB
+CB54;CB54;110D 116E 11B3;CB54;110D 116E 11B3; # (쭔; 쭔; 쭔; 쭔; 쭔; ) HANGUL SYLLABLE JJULS
+CB55;CB55;110D 116E 11B4;CB55;110D 116E 11B4; # (쭕; 쭕; 쭕; 쭕; 쭕; ) HANGUL SYLLABLE JJULT
+CB56;CB56;110D 116E 11B5;CB56;110D 116E 11B5; # (쭖; 쭖; 쭖; 쭖; 쭖; ) HANGUL SYLLABLE JJULP
+CB57;CB57;110D 116E 11B6;CB57;110D 116E 11B6; # (쭗; 쭗; 쭗; 쭗; 쭗; ) HANGUL SYLLABLE JJULH
+CB58;CB58;110D 116E 11B7;CB58;110D 116E 11B7; # (쭘; 쭘; 쭘; 쭘; 쭘; ) HANGUL SYLLABLE JJUM
+CB59;CB59;110D 116E 11B8;CB59;110D 116E 11B8; # (쭙; 쭙; 쭙; 쭙; 쭙; ) HANGUL SYLLABLE JJUB
+CB5A;CB5A;110D 116E 11B9;CB5A;110D 116E 11B9; # (쭚; 쭚; 쭚; 쭚; 쭚; ) HANGUL SYLLABLE JJUBS
+CB5B;CB5B;110D 116E 11BA;CB5B;110D 116E 11BA; # (쭛; 쭛; 쭛; 쭛; 쭛; ) HANGUL SYLLABLE JJUS
+CB5C;CB5C;110D 116E 11BB;CB5C;110D 116E 11BB; # (쭜; 쭜; 쭜; 쭜; 쭜; ) HANGUL SYLLABLE JJUSS
+CB5D;CB5D;110D 116E 11BC;CB5D;110D 116E 11BC; # (쭝; 쭝; 쭝; 쭝; 쭝; ) HANGUL SYLLABLE JJUNG
+CB5E;CB5E;110D 116E 11BD;CB5E;110D 116E 11BD; # (쭞; 쭞; 쭞; 쭞; 쭞; ) HANGUL SYLLABLE JJUJ
+CB5F;CB5F;110D 116E 11BE;CB5F;110D 116E 11BE; # (쭟; 쭟; 쭟; 쭟; 쭟; ) HANGUL SYLLABLE JJUC
+CB60;CB60;110D 116E 11BF;CB60;110D 116E 11BF; # (쭠; 쭠; 쭠; 쭠; 쭠; ) HANGUL SYLLABLE JJUK
+CB61;CB61;110D 116E 11C0;CB61;110D 116E 11C0; # (쭡; 쭡; 쭡; 쭡; 쭡; ) HANGUL SYLLABLE JJUT
+CB62;CB62;110D 116E 11C1;CB62;110D 116E 11C1; # (쭢; 쭢; 쭢; 쭢; 쭢; ) HANGUL SYLLABLE JJUP
+CB63;CB63;110D 116E 11C2;CB63;110D 116E 11C2; # (쭣; 쭣; 쭣; 쭣; 쭣; ) HANGUL SYLLABLE JJUH
+CB64;CB64;110D 116F;CB64;110D 116F; # (쭤; 쭤; 쭤; 쭤; 쭤; ) HANGUL SYLLABLE JJWEO
+CB65;CB65;110D 116F 11A8;CB65;110D 116F 11A8; # (쭥; 쭥; 쭥; 쭥; 쭥; ) HANGUL SYLLABLE JJWEOG
+CB66;CB66;110D 116F 11A9;CB66;110D 116F 11A9; # (쭦; 쭦; 쭦; 쭦; 쭦; ) HANGUL SYLLABLE JJWEOGG
+CB67;CB67;110D 116F 11AA;CB67;110D 116F 11AA; # (쭧; 쭧; 쭧; 쭧; 쭧; ) HANGUL SYLLABLE JJWEOGS
+CB68;CB68;110D 116F 11AB;CB68;110D 116F 11AB; # (쭨; 쭨; 쭨; 쭨; 쭨; ) HANGUL SYLLABLE JJWEON
+CB69;CB69;110D 116F 11AC;CB69;110D 116F 11AC; # (쭩; 쭩; 쭩; 쭩; 쭩; ) HANGUL SYLLABLE JJWEONJ
+CB6A;CB6A;110D 116F 11AD;CB6A;110D 116F 11AD; # (쭪; 쭪; 쭪; 쭪; 쭪; ) HANGUL SYLLABLE JJWEONH
+CB6B;CB6B;110D 116F 11AE;CB6B;110D 116F 11AE; # (쭫; 쭫; 쭫; 쭫; 쭫; ) HANGUL SYLLABLE JJWEOD
+CB6C;CB6C;110D 116F 11AF;CB6C;110D 116F 11AF; # (쭬; 쭬; 쭬; 쭬; 쭬; ) HANGUL SYLLABLE JJWEOL
+CB6D;CB6D;110D 116F 11B0;CB6D;110D 116F 11B0; # (쭭; 쭭; 쭭; 쭭; 쭭; ) HANGUL SYLLABLE JJWEOLG
+CB6E;CB6E;110D 116F 11B1;CB6E;110D 116F 11B1; # (쭮; 쭮; 쭮; 쭮; 쭮; ) HANGUL SYLLABLE JJWEOLM
+CB6F;CB6F;110D 116F 11B2;CB6F;110D 116F 11B2; # (쭯; 쭯; 쭯; 쭯; 쭯; ) HANGUL SYLLABLE JJWEOLB
+CB70;CB70;110D 116F 11B3;CB70;110D 116F 11B3; # (쭰; 쭰; 쭰; 쭰; 쭰; ) HANGUL SYLLABLE JJWEOLS
+CB71;CB71;110D 116F 11B4;CB71;110D 116F 11B4; # (쭱; 쭱; 쭱; 쭱; 쭱; ) HANGUL SYLLABLE JJWEOLT
+CB72;CB72;110D 116F 11B5;CB72;110D 116F 11B5; # (쭲; 쭲; 쭲; 쭲; 쭲; ) HANGUL SYLLABLE JJWEOLP
+CB73;CB73;110D 116F 11B6;CB73;110D 116F 11B6; # (쭳; 쭳; 쭳; 쭳; 쭳; ) HANGUL SYLLABLE JJWEOLH
+CB74;CB74;110D 116F 11B7;CB74;110D 116F 11B7; # (쭴; 쭴; 쭴; 쭴; 쭴; ) HANGUL SYLLABLE JJWEOM
+CB75;CB75;110D 116F 11B8;CB75;110D 116F 11B8; # (쭵; 쭵; 쭵; 쭵; 쭵; ) HANGUL SYLLABLE JJWEOB
+CB76;CB76;110D 116F 11B9;CB76;110D 116F 11B9; # (쭶; 쭶; 쭶; 쭶; 쭶; ) HANGUL SYLLABLE JJWEOBS
+CB77;CB77;110D 116F 11BA;CB77;110D 116F 11BA; # (쭷; 쭷; 쭷; 쭷; 쭷; ) HANGUL SYLLABLE JJWEOS
+CB78;CB78;110D 116F 11BB;CB78;110D 116F 11BB; # (쭸; 쭸; 쭸; 쭸; 쭸; ) HANGUL SYLLABLE JJWEOSS
+CB79;CB79;110D 116F 11BC;CB79;110D 116F 11BC; # (쭹; 쭹; 쭹; 쭹; 쭹; ) HANGUL SYLLABLE JJWEONG
+CB7A;CB7A;110D 116F 11BD;CB7A;110D 116F 11BD; # (쭺; 쭺; 쭺; 쭺; 쭺; ) HANGUL SYLLABLE JJWEOJ
+CB7B;CB7B;110D 116F 11BE;CB7B;110D 116F 11BE; # (쭻; 쭻; 쭻; 쭻; 쭻; ) HANGUL SYLLABLE JJWEOC
+CB7C;CB7C;110D 116F 11BF;CB7C;110D 116F 11BF; # (쭼; 쭼; 쭼; 쭼; 쭼; ) HANGUL SYLLABLE JJWEOK
+CB7D;CB7D;110D 116F 11C0;CB7D;110D 116F 11C0; # (쭽; 쭽; 쭽; 쭽; 쭽; ) HANGUL SYLLABLE JJWEOT
+CB7E;CB7E;110D 116F 11C1;CB7E;110D 116F 11C1; # (쭾; 쭾; 쭾; 쭾; 쭾; ) HANGUL SYLLABLE JJWEOP
+CB7F;CB7F;110D 116F 11C2;CB7F;110D 116F 11C2; # (쭿; 쭿; 쭿; 쭿; 쭿; ) HANGUL SYLLABLE JJWEOH
+CB80;CB80;110D 1170;CB80;110D 1170; # (쮀; 쮀; 쮀; 쮀; 쮀; ) HANGUL SYLLABLE JJWE
+CB81;CB81;110D 1170 11A8;CB81;110D 1170 11A8; # (쮁; 쮁; 쮁; 쮁; 쮁; ) HANGUL SYLLABLE JJWEG
+CB82;CB82;110D 1170 11A9;CB82;110D 1170 11A9; # (쮂; 쮂; 쮂; 쮂; 쮂; ) HANGUL SYLLABLE JJWEGG
+CB83;CB83;110D 1170 11AA;CB83;110D 1170 11AA; # (쮃; 쮃; 쮃; 쮃; 쮃; ) HANGUL SYLLABLE JJWEGS
+CB84;CB84;110D 1170 11AB;CB84;110D 1170 11AB; # (쮄; 쮄; 쮄; 쮄; 쮄; ) HANGUL SYLLABLE JJWEN
+CB85;CB85;110D 1170 11AC;CB85;110D 1170 11AC; # (쮅; 쮅; 쮅; 쮅; 쮅; ) HANGUL SYLLABLE JJWENJ
+CB86;CB86;110D 1170 11AD;CB86;110D 1170 11AD; # (쮆; 쮆; 쮆; 쮆; 쮆; ) HANGUL SYLLABLE JJWENH
+CB87;CB87;110D 1170 11AE;CB87;110D 1170 11AE; # (쮇; 쮇; 쮇; 쮇; 쮇; ) HANGUL SYLLABLE JJWED
+CB88;CB88;110D 1170 11AF;CB88;110D 1170 11AF; # (쮈; 쮈; 쮈; 쮈; 쮈; ) HANGUL SYLLABLE JJWEL
+CB89;CB89;110D 1170 11B0;CB89;110D 1170 11B0; # (쮉; 쮉; 쮉; 쮉; 쮉; ) HANGUL SYLLABLE JJWELG
+CB8A;CB8A;110D 1170 11B1;CB8A;110D 1170 11B1; # (쮊; 쮊; 쮊; 쮊; 쮊; ) HANGUL SYLLABLE JJWELM
+CB8B;CB8B;110D 1170 11B2;CB8B;110D 1170 11B2; # (쮋; 쮋; 쮋; 쮋; 쮋; ) HANGUL SYLLABLE JJWELB
+CB8C;CB8C;110D 1170 11B3;CB8C;110D 1170 11B3; # (쮌; 쮌; 쮌; 쮌; 쮌; ) HANGUL SYLLABLE JJWELS
+CB8D;CB8D;110D 1170 11B4;CB8D;110D 1170 11B4; # (쮍; 쮍; 쮍; 쮍; 쮍; ) HANGUL SYLLABLE JJWELT
+CB8E;CB8E;110D 1170 11B5;CB8E;110D 1170 11B5; # (쮎; 쮎; 쮎; 쮎; 쮎; ) HANGUL SYLLABLE JJWELP
+CB8F;CB8F;110D 1170 11B6;CB8F;110D 1170 11B6; # (쮏; 쮏; 쮏; 쮏; 쮏; ) HANGUL SYLLABLE JJWELH
+CB90;CB90;110D 1170 11B7;CB90;110D 1170 11B7; # (쮐; 쮐; 쮐; 쮐; 쮐; ) HANGUL SYLLABLE JJWEM
+CB91;CB91;110D 1170 11B8;CB91;110D 1170 11B8; # (쮑; 쮑; 쮑; 쮑; 쮑; ) HANGUL SYLLABLE JJWEB
+CB92;CB92;110D 1170 11B9;CB92;110D 1170 11B9; # (쮒; 쮒; 쮒; 쮒; 쮒; ) HANGUL SYLLABLE JJWEBS
+CB93;CB93;110D 1170 11BA;CB93;110D 1170 11BA; # (쮓; 쮓; 쮓; 쮓; 쮓; ) HANGUL SYLLABLE JJWES
+CB94;CB94;110D 1170 11BB;CB94;110D 1170 11BB; # (쮔; 쮔; 쮔; 쮔; 쮔; ) HANGUL SYLLABLE JJWESS
+CB95;CB95;110D 1170 11BC;CB95;110D 1170 11BC; # (쮕; 쮕; 쮕; 쮕; 쮕; ) HANGUL SYLLABLE JJWENG
+CB96;CB96;110D 1170 11BD;CB96;110D 1170 11BD; # (쮖; 쮖; 쮖; 쮖; 쮖; ) HANGUL SYLLABLE JJWEJ
+CB97;CB97;110D 1170 11BE;CB97;110D 1170 11BE; # (쮗; 쮗; 쮗; 쮗; 쮗; ) HANGUL SYLLABLE JJWEC
+CB98;CB98;110D 1170 11BF;CB98;110D 1170 11BF; # (쮘; 쮘; 쮘; 쮘; 쮘; ) HANGUL SYLLABLE JJWEK
+CB99;CB99;110D 1170 11C0;CB99;110D 1170 11C0; # (쮙; 쮙; 쮙; 쮙; 쮙; ) HANGUL SYLLABLE JJWET
+CB9A;CB9A;110D 1170 11C1;CB9A;110D 1170 11C1; # (쮚; 쮚; 쮚; 쮚; 쮚; ) HANGUL SYLLABLE JJWEP
+CB9B;CB9B;110D 1170 11C2;CB9B;110D 1170 11C2; # (쮛; 쮛; 쮛; 쮛; 쮛; ) HANGUL SYLLABLE JJWEH
+CB9C;CB9C;110D 1171;CB9C;110D 1171; # (쮜; 쮜; 쮜; 쮜; 쮜; ) HANGUL SYLLABLE JJWI
+CB9D;CB9D;110D 1171 11A8;CB9D;110D 1171 11A8; # (쮝; 쮝; 쮝; 쮝; 쮝; ) HANGUL SYLLABLE JJWIG
+CB9E;CB9E;110D 1171 11A9;CB9E;110D 1171 11A9; # (쮞; 쮞; 쮞; 쮞; 쮞; ) HANGUL SYLLABLE JJWIGG
+CB9F;CB9F;110D 1171 11AA;CB9F;110D 1171 11AA; # (쮟; 쮟; 쮟; 쮟; 쮟; ) HANGUL SYLLABLE JJWIGS
+CBA0;CBA0;110D 1171 11AB;CBA0;110D 1171 11AB; # (쮠; 쮠; 쮠; 쮠; 쮠; ) HANGUL SYLLABLE JJWIN
+CBA1;CBA1;110D 1171 11AC;CBA1;110D 1171 11AC; # (쮡; 쮡; 쮡; 쮡; 쮡; ) HANGUL SYLLABLE JJWINJ
+CBA2;CBA2;110D 1171 11AD;CBA2;110D 1171 11AD; # (쮢; 쮢; 쮢; 쮢; 쮢; ) HANGUL SYLLABLE JJWINH
+CBA3;CBA3;110D 1171 11AE;CBA3;110D 1171 11AE; # (쮣; 쮣; 쮣; 쮣; 쮣; ) HANGUL SYLLABLE JJWID
+CBA4;CBA4;110D 1171 11AF;CBA4;110D 1171 11AF; # (쮤; 쮤; 쮤; 쮤; 쮤; ) HANGUL SYLLABLE JJWIL
+CBA5;CBA5;110D 1171 11B0;CBA5;110D 1171 11B0; # (쮥; 쮥; 쮥; 쮥; 쮥; ) HANGUL SYLLABLE JJWILG
+CBA6;CBA6;110D 1171 11B1;CBA6;110D 1171 11B1; # (쮦; 쮦; 쮦; 쮦; 쮦; ) HANGUL SYLLABLE JJWILM
+CBA7;CBA7;110D 1171 11B2;CBA7;110D 1171 11B2; # (쮧; 쮧; 쮧; 쮧; 쮧; ) HANGUL SYLLABLE JJWILB
+CBA8;CBA8;110D 1171 11B3;CBA8;110D 1171 11B3; # (쮨; 쮨; 쮨; 쮨; 쮨; ) HANGUL SYLLABLE JJWILS
+CBA9;CBA9;110D 1171 11B4;CBA9;110D 1171 11B4; # (쮩; 쮩; 쮩; 쮩; 쮩; ) HANGUL SYLLABLE JJWILT
+CBAA;CBAA;110D 1171 11B5;CBAA;110D 1171 11B5; # (쮪; 쮪; 쮪; 쮪; 쮪; ) HANGUL SYLLABLE JJWILP
+CBAB;CBAB;110D 1171 11B6;CBAB;110D 1171 11B6; # (쮫; 쮫; 쮫; 쮫; 쮫; ) HANGUL SYLLABLE JJWILH
+CBAC;CBAC;110D 1171 11B7;CBAC;110D 1171 11B7; # (쮬; 쮬; 쮬; 쮬; 쮬; ) HANGUL SYLLABLE JJWIM
+CBAD;CBAD;110D 1171 11B8;CBAD;110D 1171 11B8; # (쮭; 쮭; 쮭; 쮭; 쮭; ) HANGUL SYLLABLE JJWIB
+CBAE;CBAE;110D 1171 11B9;CBAE;110D 1171 11B9; # (쮮; 쮮; 쮮; 쮮; 쮮; ) HANGUL SYLLABLE JJWIBS
+CBAF;CBAF;110D 1171 11BA;CBAF;110D 1171 11BA; # (쮯; 쮯; 쮯; 쮯; 쮯; ) HANGUL SYLLABLE JJWIS
+CBB0;CBB0;110D 1171 11BB;CBB0;110D 1171 11BB; # (쮰; 쮰; 쮰; 쮰; 쮰; ) HANGUL SYLLABLE JJWISS
+CBB1;CBB1;110D 1171 11BC;CBB1;110D 1171 11BC; # (쮱; 쮱; 쮱; 쮱; 쮱; ) HANGUL SYLLABLE JJWING
+CBB2;CBB2;110D 1171 11BD;CBB2;110D 1171 11BD; # (쮲; 쮲; 쮲; 쮲; 쮲; ) HANGUL SYLLABLE JJWIJ
+CBB3;CBB3;110D 1171 11BE;CBB3;110D 1171 11BE; # (쮳; 쮳; 쮳; 쮳; 쮳; ) HANGUL SYLLABLE JJWIC
+CBB4;CBB4;110D 1171 11BF;CBB4;110D 1171 11BF; # (쮴; 쮴; 쮴; 쮴; 쮴; ) HANGUL SYLLABLE JJWIK
+CBB5;CBB5;110D 1171 11C0;CBB5;110D 1171 11C0; # (쮵; 쮵; 쮵; 쮵; 쮵; ) HANGUL SYLLABLE JJWIT
+CBB6;CBB6;110D 1171 11C1;CBB6;110D 1171 11C1; # (쮶; 쮶; 쮶; 쮶; 쮶; ) HANGUL SYLLABLE JJWIP
+CBB7;CBB7;110D 1171 11C2;CBB7;110D 1171 11C2; # (쮷; 쮷; 쮷; 쮷; 쮷; ) HANGUL SYLLABLE JJWIH
+CBB8;CBB8;110D 1172;CBB8;110D 1172; # (쮸; 쮸; 쮸; 쮸; 쮸; ) HANGUL SYLLABLE JJYU
+CBB9;CBB9;110D 1172 11A8;CBB9;110D 1172 11A8; # (쮹; 쮹; 쮹; 쮹; 쮹; ) HANGUL SYLLABLE JJYUG
+CBBA;CBBA;110D 1172 11A9;CBBA;110D 1172 11A9; # (쮺; 쮺; 쮺; 쮺; 쮺; ) HANGUL SYLLABLE JJYUGG
+CBBB;CBBB;110D 1172 11AA;CBBB;110D 1172 11AA; # (쮻; 쮻; 쮻; 쮻; 쮻; ) HANGUL SYLLABLE JJYUGS
+CBBC;CBBC;110D 1172 11AB;CBBC;110D 1172 11AB; # (쮼; 쮼; 쮼; 쮼; 쮼; ) HANGUL SYLLABLE JJYUN
+CBBD;CBBD;110D 1172 11AC;CBBD;110D 1172 11AC; # (쮽; 쮽; 쮽; 쮽; 쮽; ) HANGUL SYLLABLE JJYUNJ
+CBBE;CBBE;110D 1172 11AD;CBBE;110D 1172 11AD; # (쮾; 쮾; 쮾; 쮾; 쮾; ) HANGUL SYLLABLE JJYUNH
+CBBF;CBBF;110D 1172 11AE;CBBF;110D 1172 11AE; # (쮿; 쮿; 쮿; 쮿; 쮿; ) HANGUL SYLLABLE JJYUD
+CBC0;CBC0;110D 1172 11AF;CBC0;110D 1172 11AF; # (쯀; 쯀; 쯀; 쯀; 쯀; ) HANGUL SYLLABLE JJYUL
+CBC1;CBC1;110D 1172 11B0;CBC1;110D 1172 11B0; # (쯁; 쯁; 쯁; 쯁; 쯁; ) HANGUL SYLLABLE JJYULG
+CBC2;CBC2;110D 1172 11B1;CBC2;110D 1172 11B1; # (쯂; 쯂; 쯂; 쯂; 쯂; ) HANGUL SYLLABLE JJYULM
+CBC3;CBC3;110D 1172 11B2;CBC3;110D 1172 11B2; # (쯃; 쯃; 쯃; 쯃; 쯃; ) HANGUL SYLLABLE JJYULB
+CBC4;CBC4;110D 1172 11B3;CBC4;110D 1172 11B3; # (쯄; 쯄; 쯄; 쯄; 쯄; ) HANGUL SYLLABLE JJYULS
+CBC5;CBC5;110D 1172 11B4;CBC5;110D 1172 11B4; # (쯅; 쯅; 쯅; 쯅; 쯅; ) HANGUL SYLLABLE JJYULT
+CBC6;CBC6;110D 1172 11B5;CBC6;110D 1172 11B5; # (쯆; 쯆; 쯆; 쯆; 쯆; ) HANGUL SYLLABLE JJYULP
+CBC7;CBC7;110D 1172 11B6;CBC7;110D 1172 11B6; # (쯇; 쯇; 쯇; 쯇; 쯇; ) HANGUL SYLLABLE JJYULH
+CBC8;CBC8;110D 1172 11B7;CBC8;110D 1172 11B7; # (쯈; 쯈; 쯈; 쯈; 쯈; ) HANGUL SYLLABLE JJYUM
+CBC9;CBC9;110D 1172 11B8;CBC9;110D 1172 11B8; # (쯉; 쯉; 쯉; 쯉; 쯉; ) HANGUL SYLLABLE JJYUB
+CBCA;CBCA;110D 1172 11B9;CBCA;110D 1172 11B9; # (쯊; 쯊; 쯊; 쯊; 쯊; ) HANGUL SYLLABLE JJYUBS
+CBCB;CBCB;110D 1172 11BA;CBCB;110D 1172 11BA; # (쯋; 쯋; 쯋; 쯋; 쯋; ) HANGUL SYLLABLE JJYUS
+CBCC;CBCC;110D 1172 11BB;CBCC;110D 1172 11BB; # (쯌; 쯌; 쯌; 쯌; 쯌; ) HANGUL SYLLABLE JJYUSS
+CBCD;CBCD;110D 1172 11BC;CBCD;110D 1172 11BC; # (쯍; 쯍; 쯍; 쯍; 쯍; ) HANGUL SYLLABLE JJYUNG
+CBCE;CBCE;110D 1172 11BD;CBCE;110D 1172 11BD; # (쯎; 쯎; 쯎; 쯎; 쯎; ) HANGUL SYLLABLE JJYUJ
+CBCF;CBCF;110D 1172 11BE;CBCF;110D 1172 11BE; # (쯏; 쯏; 쯏; 쯏; 쯏; ) HANGUL SYLLABLE JJYUC
+CBD0;CBD0;110D 1172 11BF;CBD0;110D 1172 11BF; # (쯐; 쯐; 쯐; 쯐; 쯐; ) HANGUL SYLLABLE JJYUK
+CBD1;CBD1;110D 1172 11C0;CBD1;110D 1172 11C0; # (쯑; 쯑; 쯑; 쯑; 쯑; ) HANGUL SYLLABLE JJYUT
+CBD2;CBD2;110D 1172 11C1;CBD2;110D 1172 11C1; # (쯒; 쯒; 쯒; 쯒; 쯒; ) HANGUL SYLLABLE JJYUP
+CBD3;CBD3;110D 1172 11C2;CBD3;110D 1172 11C2; # (쯓; 쯓; 쯓; 쯓; 쯓; ) HANGUL SYLLABLE JJYUH
+CBD4;CBD4;110D 1173;CBD4;110D 1173; # (쯔; 쯔; 쯔; 쯔; 쯔; ) HANGUL SYLLABLE JJEU
+CBD5;CBD5;110D 1173 11A8;CBD5;110D 1173 11A8; # (쯕; 쯕; 쯕; 쯕; 쯕; ) HANGUL SYLLABLE JJEUG
+CBD6;CBD6;110D 1173 11A9;CBD6;110D 1173 11A9; # (쯖; 쯖; 쯖; 쯖; 쯖; ) HANGUL SYLLABLE JJEUGG
+CBD7;CBD7;110D 1173 11AA;CBD7;110D 1173 11AA; # (쯗; 쯗; 쯗; 쯗; 쯗; ) HANGUL SYLLABLE JJEUGS
+CBD8;CBD8;110D 1173 11AB;CBD8;110D 1173 11AB; # (쯘; 쯘; 쯘; 쯘; 쯘; ) HANGUL SYLLABLE JJEUN
+CBD9;CBD9;110D 1173 11AC;CBD9;110D 1173 11AC; # (쯙; 쯙; 쯙; 쯙; 쯙; ) HANGUL SYLLABLE JJEUNJ
+CBDA;CBDA;110D 1173 11AD;CBDA;110D 1173 11AD; # (쯚; 쯚; 쯚; 쯚; 쯚; ) HANGUL SYLLABLE JJEUNH
+CBDB;CBDB;110D 1173 11AE;CBDB;110D 1173 11AE; # (쯛; 쯛; 쯛; 쯛; 쯛; ) HANGUL SYLLABLE JJEUD
+CBDC;CBDC;110D 1173 11AF;CBDC;110D 1173 11AF; # (쯜; 쯜; 쯜; 쯜; 쯜; ) HANGUL SYLLABLE JJEUL
+CBDD;CBDD;110D 1173 11B0;CBDD;110D 1173 11B0; # (쯝; 쯝; 쯝; 쯝; 쯝; ) HANGUL SYLLABLE JJEULG
+CBDE;CBDE;110D 1173 11B1;CBDE;110D 1173 11B1; # (쯞; 쯞; 쯞; 쯞; 쯞; ) HANGUL SYLLABLE JJEULM
+CBDF;CBDF;110D 1173 11B2;CBDF;110D 1173 11B2; # (쯟; 쯟; 쯟; 쯟; 쯟; ) HANGUL SYLLABLE JJEULB
+CBE0;CBE0;110D 1173 11B3;CBE0;110D 1173 11B3; # (쯠; 쯠; 쯠; 쯠; 쯠; ) HANGUL SYLLABLE JJEULS
+CBE1;CBE1;110D 1173 11B4;CBE1;110D 1173 11B4; # (쯡; 쯡; 쯡; 쯡; 쯡; ) HANGUL SYLLABLE JJEULT
+CBE2;CBE2;110D 1173 11B5;CBE2;110D 1173 11B5; # (쯢; 쯢; 쯢; 쯢; 쯢; ) HANGUL SYLLABLE JJEULP
+CBE3;CBE3;110D 1173 11B6;CBE3;110D 1173 11B6; # (쯣; 쯣; 쯣; 쯣; 쯣; ) HANGUL SYLLABLE JJEULH
+CBE4;CBE4;110D 1173 11B7;CBE4;110D 1173 11B7; # (쯤; 쯤; 쯤; 쯤; 쯤; ) HANGUL SYLLABLE JJEUM
+CBE5;CBE5;110D 1173 11B8;CBE5;110D 1173 11B8; # (쯥; 쯥; 쯥; 쯥; 쯥; ) HANGUL SYLLABLE JJEUB
+CBE6;CBE6;110D 1173 11B9;CBE6;110D 1173 11B9; # (쯦; 쯦; 쯦; 쯦; 쯦; ) HANGUL SYLLABLE JJEUBS
+CBE7;CBE7;110D 1173 11BA;CBE7;110D 1173 11BA; # (쯧; 쯧; 쯧; 쯧; 쯧; ) HANGUL SYLLABLE JJEUS
+CBE8;CBE8;110D 1173 11BB;CBE8;110D 1173 11BB; # (쯨; 쯨; 쯨; 쯨; 쯨; ) HANGUL SYLLABLE JJEUSS
+CBE9;CBE9;110D 1173 11BC;CBE9;110D 1173 11BC; # (쯩; 쯩; 쯩; 쯩; 쯩; ) HANGUL SYLLABLE JJEUNG
+CBEA;CBEA;110D 1173 11BD;CBEA;110D 1173 11BD; # (쯪; 쯪; 쯪; 쯪; 쯪; ) HANGUL SYLLABLE JJEUJ
+CBEB;CBEB;110D 1173 11BE;CBEB;110D 1173 11BE; # (쯫; 쯫; 쯫; 쯫; 쯫; ) HANGUL SYLLABLE JJEUC
+CBEC;CBEC;110D 1173 11BF;CBEC;110D 1173 11BF; # (쯬; 쯬; 쯬; 쯬; 쯬; ) HANGUL SYLLABLE JJEUK
+CBED;CBED;110D 1173 11C0;CBED;110D 1173 11C0; # (쯭; 쯭; 쯭; 쯭; 쯭; ) HANGUL SYLLABLE JJEUT
+CBEE;CBEE;110D 1173 11C1;CBEE;110D 1173 11C1; # (쯮; 쯮; 쯮; 쯮; 쯮; ) HANGUL SYLLABLE JJEUP
+CBEF;CBEF;110D 1173 11C2;CBEF;110D 1173 11C2; # (쯯; 쯯; 쯯; 쯯; 쯯; ) HANGUL SYLLABLE JJEUH
+CBF0;CBF0;110D 1174;CBF0;110D 1174; # (쯰; 쯰; 쯰; 쯰; 쯰; ) HANGUL SYLLABLE JJYI
+CBF1;CBF1;110D 1174 11A8;CBF1;110D 1174 11A8; # (쯱; 쯱; 쯱; 쯱; 쯱; ) HANGUL SYLLABLE JJYIG
+CBF2;CBF2;110D 1174 11A9;CBF2;110D 1174 11A9; # (쯲; 쯲; 쯲; 쯲; 쯲; ) HANGUL SYLLABLE JJYIGG
+CBF3;CBF3;110D 1174 11AA;CBF3;110D 1174 11AA; # (쯳; 쯳; 쯳; 쯳; 쯳; ) HANGUL SYLLABLE JJYIGS
+CBF4;CBF4;110D 1174 11AB;CBF4;110D 1174 11AB; # (쯴; 쯴; 쯴; 쯴; 쯴; ) HANGUL SYLLABLE JJYIN
+CBF5;CBF5;110D 1174 11AC;CBF5;110D 1174 11AC; # (쯵; 쯵; 쯵; 쯵; 쯵; ) HANGUL SYLLABLE JJYINJ
+CBF6;CBF6;110D 1174 11AD;CBF6;110D 1174 11AD; # (쯶; 쯶; 쯶; 쯶; 쯶; ) HANGUL SYLLABLE JJYINH
+CBF7;CBF7;110D 1174 11AE;CBF7;110D 1174 11AE; # (쯷; 쯷; 쯷; 쯷; 쯷; ) HANGUL SYLLABLE JJYID
+CBF8;CBF8;110D 1174 11AF;CBF8;110D 1174 11AF; # (쯸; 쯸; 쯸; 쯸; 쯸; ) HANGUL SYLLABLE JJYIL
+CBF9;CBF9;110D 1174 11B0;CBF9;110D 1174 11B0; # (쯹; 쯹; 쯹; 쯹; 쯹; ) HANGUL SYLLABLE JJYILG
+CBFA;CBFA;110D 1174 11B1;CBFA;110D 1174 11B1; # (쯺; 쯺; 쯺; 쯺; 쯺; ) HANGUL SYLLABLE JJYILM
+CBFB;CBFB;110D 1174 11B2;CBFB;110D 1174 11B2; # (쯻; 쯻; 쯻; 쯻; 쯻; ) HANGUL SYLLABLE JJYILB
+CBFC;CBFC;110D 1174 11B3;CBFC;110D 1174 11B3; # (쯼; 쯼; 쯼; 쯼; 쯼; ) HANGUL SYLLABLE JJYILS
+CBFD;CBFD;110D 1174 11B4;CBFD;110D 1174 11B4; # (쯽; 쯽; 쯽; 쯽; 쯽; ) HANGUL SYLLABLE JJYILT
+CBFE;CBFE;110D 1174 11B5;CBFE;110D 1174 11B5; # (쯾; 쯾; 쯾; 쯾; 쯾; ) HANGUL SYLLABLE JJYILP
+CBFF;CBFF;110D 1174 11B6;CBFF;110D 1174 11B6; # (쯿; 쯿; 쯿; 쯿; 쯿; ) HANGUL SYLLABLE JJYILH
+CC00;CC00;110D 1174 11B7;CC00;110D 1174 11B7; # (찀; 찀; 찀; 찀; 찀; ) HANGUL SYLLABLE JJYIM
+CC01;CC01;110D 1174 11B8;CC01;110D 1174 11B8; # (찁; 찁; 찁; 찁; 찁; ) HANGUL SYLLABLE JJYIB
+CC02;CC02;110D 1174 11B9;CC02;110D 1174 11B9; # (찂; 찂; 찂; 찂; 찂; ) HANGUL SYLLABLE JJYIBS
+CC03;CC03;110D 1174 11BA;CC03;110D 1174 11BA; # (찃; 찃; 찃; 찃; 찃; ) HANGUL SYLLABLE JJYIS
+CC04;CC04;110D 1174 11BB;CC04;110D 1174 11BB; # (찄; 찄; 찄; 찄; 찄; ) HANGUL SYLLABLE JJYISS
+CC05;CC05;110D 1174 11BC;CC05;110D 1174 11BC; # (찅; 찅; 찅; 찅; 찅; ) HANGUL SYLLABLE JJYING
+CC06;CC06;110D 1174 11BD;CC06;110D 1174 11BD; # (찆; 찆; 찆; 찆; 찆; ) HANGUL SYLLABLE JJYIJ
+CC07;CC07;110D 1174 11BE;CC07;110D 1174 11BE; # (찇; 찇; 찇; 찇; 찇; ) HANGUL SYLLABLE JJYIC
+CC08;CC08;110D 1174 11BF;CC08;110D 1174 11BF; # (찈; 찈; 찈; 찈; 찈; ) HANGUL SYLLABLE JJYIK
+CC09;CC09;110D 1174 11C0;CC09;110D 1174 11C0; # (찉; 찉; 찉; 찉; 찉; ) HANGUL SYLLABLE JJYIT
+CC0A;CC0A;110D 1174 11C1;CC0A;110D 1174 11C1; # (찊; 찊; 찊; 찊; 찊; ) HANGUL SYLLABLE JJYIP
+CC0B;CC0B;110D 1174 11C2;CC0B;110D 1174 11C2; # (찋; 찋; 찋; 찋; 찋; ) HANGUL SYLLABLE JJYIH
+CC0C;CC0C;110D 1175;CC0C;110D 1175; # (찌; 찌; 찌; 찌; 찌; ) HANGUL SYLLABLE JJI
+CC0D;CC0D;110D 1175 11A8;CC0D;110D 1175 11A8; # (찍; 찍; 찍; 찍; 찍; ) HANGUL SYLLABLE JJIG
+CC0E;CC0E;110D 1175 11A9;CC0E;110D 1175 11A9; # (찎; 찎; 찎; 찎; 찎; ) HANGUL SYLLABLE JJIGG
+CC0F;CC0F;110D 1175 11AA;CC0F;110D 1175 11AA; # (찏; 찏; 찏; 찏; 찏; ) HANGUL SYLLABLE JJIGS
+CC10;CC10;110D 1175 11AB;CC10;110D 1175 11AB; # (찐; 찐; 찐; 찐; 찐; ) HANGUL SYLLABLE JJIN
+CC11;CC11;110D 1175 11AC;CC11;110D 1175 11AC; # (찑; 찑; 찑; 찑; 찑; ) HANGUL SYLLABLE JJINJ
+CC12;CC12;110D 1175 11AD;CC12;110D 1175 11AD; # (찒; 찒; 찒; 찒; 찒; ) HANGUL SYLLABLE JJINH
+CC13;CC13;110D 1175 11AE;CC13;110D 1175 11AE; # (찓; 찓; 찓; 찓; 찓; ) HANGUL SYLLABLE JJID
+CC14;CC14;110D 1175 11AF;CC14;110D 1175 11AF; # (찔; 찔; 찔; 찔; 찔; ) HANGUL SYLLABLE JJIL
+CC15;CC15;110D 1175 11B0;CC15;110D 1175 11B0; # (찕; 찕; 찕; 찕; 찕; ) HANGUL SYLLABLE JJILG
+CC16;CC16;110D 1175 11B1;CC16;110D 1175 11B1; # (찖; 찖; 찖; 찖; 찖; ) HANGUL SYLLABLE JJILM
+CC17;CC17;110D 1175 11B2;CC17;110D 1175 11B2; # (찗; 찗; 찗; 찗; 찗; ) HANGUL SYLLABLE JJILB
+CC18;CC18;110D 1175 11B3;CC18;110D 1175 11B3; # (찘; 찘; 찘; 찘; 찘; ) HANGUL SYLLABLE JJILS
+CC19;CC19;110D 1175 11B4;CC19;110D 1175 11B4; # (찙; 찙; 찙; 찙; 찙; ) HANGUL SYLLABLE JJILT
+CC1A;CC1A;110D 1175 11B5;CC1A;110D 1175 11B5; # (찚; 찚; 찚; 찚; 찚; ) HANGUL SYLLABLE JJILP
+CC1B;CC1B;110D 1175 11B6;CC1B;110D 1175 11B6; # (찛; 찛; 찛; 찛; 찛; ) HANGUL SYLLABLE JJILH
+CC1C;CC1C;110D 1175 11B7;CC1C;110D 1175 11B7; # (찜; 찜; 찜; 찜; 찜; ) HANGUL SYLLABLE JJIM
+CC1D;CC1D;110D 1175 11B8;CC1D;110D 1175 11B8; # (찝; 찝; 찝; 찝; 찝; ) HANGUL SYLLABLE JJIB
+CC1E;CC1E;110D 1175 11B9;CC1E;110D 1175 11B9; # (찞; 찞; 찞; 찞; 찞; ) HANGUL SYLLABLE JJIBS
+CC1F;CC1F;110D 1175 11BA;CC1F;110D 1175 11BA; # (찟; 찟; 찟; 찟; 찟; ) HANGUL SYLLABLE JJIS
+CC20;CC20;110D 1175 11BB;CC20;110D 1175 11BB; # (찠; 찠; 찠; 찠; 찠; ) HANGUL SYLLABLE JJISS
+CC21;CC21;110D 1175 11BC;CC21;110D 1175 11BC; # (찡; 찡; 찡; 찡; 찡; ) HANGUL SYLLABLE JJING
+CC22;CC22;110D 1175 11BD;CC22;110D 1175 11BD; # (찢; 찢; 찢; 찢; 찢; ) HANGUL SYLLABLE JJIJ
+CC23;CC23;110D 1175 11BE;CC23;110D 1175 11BE; # (찣; 찣; 찣; 찣; 찣; ) HANGUL SYLLABLE JJIC
+CC24;CC24;110D 1175 11BF;CC24;110D 1175 11BF; # (찤; 찤; 찤; 찤; 찤; ) HANGUL SYLLABLE JJIK
+CC25;CC25;110D 1175 11C0;CC25;110D 1175 11C0; # (찥; 찥; 찥; 찥; 찥; ) HANGUL SYLLABLE JJIT
+CC26;CC26;110D 1175 11C1;CC26;110D 1175 11C1; # (찦; 찦; 찦; 찦; 찦; ) HANGUL SYLLABLE JJIP
+CC27;CC27;110D 1175 11C2;CC27;110D 1175 11C2; # (찧; 찧; 찧; 찧; 찧; ) HANGUL SYLLABLE JJIH
+CC28;CC28;110E 1161;CC28;110E 1161; # (차; 차; 차; 차; 차; ) HANGUL SYLLABLE CA
+CC29;CC29;110E 1161 11A8;CC29;110E 1161 11A8; # (착; 착; 착; 착; 착; ) HANGUL SYLLABLE CAG
+CC2A;CC2A;110E 1161 11A9;CC2A;110E 1161 11A9; # (찪; 찪; 찪; 찪; 찪; ) HANGUL SYLLABLE CAGG
+CC2B;CC2B;110E 1161 11AA;CC2B;110E 1161 11AA; # (찫; 찫; 찫; 찫; 찫; ) HANGUL SYLLABLE CAGS
+CC2C;CC2C;110E 1161 11AB;CC2C;110E 1161 11AB; # (찬; 찬; 찬; 찬; 찬; ) HANGUL SYLLABLE CAN
+CC2D;CC2D;110E 1161 11AC;CC2D;110E 1161 11AC; # (찭; 찭; 찭; 찭; 찭; ) HANGUL SYLLABLE CANJ
+CC2E;CC2E;110E 1161 11AD;CC2E;110E 1161 11AD; # (찮; 찮; 찮; 찮; 찮; ) HANGUL SYLLABLE CANH
+CC2F;CC2F;110E 1161 11AE;CC2F;110E 1161 11AE; # (찯; 찯; 찯; 찯; 찯; ) HANGUL SYLLABLE CAD
+CC30;CC30;110E 1161 11AF;CC30;110E 1161 11AF; # (찰; 찰; 찰; 찰; 찰; ) HANGUL SYLLABLE CAL
+CC31;CC31;110E 1161 11B0;CC31;110E 1161 11B0; # (찱; 찱; 찱; 찱; 찱; ) HANGUL SYLLABLE CALG
+CC32;CC32;110E 1161 11B1;CC32;110E 1161 11B1; # (찲; 찲; 찲; 찲; 찲; ) HANGUL SYLLABLE CALM
+CC33;CC33;110E 1161 11B2;CC33;110E 1161 11B2; # (찳; 찳; 찳; 찳; 찳; ) HANGUL SYLLABLE CALB
+CC34;CC34;110E 1161 11B3;CC34;110E 1161 11B3; # (찴; 찴; 찴; 찴; 찴; ) HANGUL SYLLABLE CALS
+CC35;CC35;110E 1161 11B4;CC35;110E 1161 11B4; # (찵; 찵; 찵; 찵; 찵; ) HANGUL SYLLABLE CALT
+CC36;CC36;110E 1161 11B5;CC36;110E 1161 11B5; # (찶; 찶; 찶; 찶; 찶; ) HANGUL SYLLABLE CALP
+CC37;CC37;110E 1161 11B6;CC37;110E 1161 11B6; # (찷; 찷; 찷; 찷; 찷; ) HANGUL SYLLABLE CALH
+CC38;CC38;110E 1161 11B7;CC38;110E 1161 11B7; # (참; 참; 참; 참; 참; ) HANGUL SYLLABLE CAM
+CC39;CC39;110E 1161 11B8;CC39;110E 1161 11B8; # (찹; 찹; 찹; 찹; 찹; ) HANGUL SYLLABLE CAB
+CC3A;CC3A;110E 1161 11B9;CC3A;110E 1161 11B9; # (찺; 찺; 찺; 찺; 찺; ) HANGUL SYLLABLE CABS
+CC3B;CC3B;110E 1161 11BA;CC3B;110E 1161 11BA; # (찻; 찻; 찻; 찻; 찻; ) HANGUL SYLLABLE CAS
+CC3C;CC3C;110E 1161 11BB;CC3C;110E 1161 11BB; # (찼; 찼; 찼; 찼; 찼; ) HANGUL SYLLABLE CASS
+CC3D;CC3D;110E 1161 11BC;CC3D;110E 1161 11BC; # (창; 창; 창; 창; 창; ) HANGUL SYLLABLE CANG
+CC3E;CC3E;110E 1161 11BD;CC3E;110E 1161 11BD; # (찾; 찾; 찾; 찾; 찾; ) HANGUL SYLLABLE CAJ
+CC3F;CC3F;110E 1161 11BE;CC3F;110E 1161 11BE; # (찿; 찿; 찿; 찿; 찿; ) HANGUL SYLLABLE CAC
+CC40;CC40;110E 1161 11BF;CC40;110E 1161 11BF; # (챀; 챀; 챀; 챀; 챀; ) HANGUL SYLLABLE CAK
+CC41;CC41;110E 1161 11C0;CC41;110E 1161 11C0; # (챁; 챁; 챁; 챁; 챁; ) HANGUL SYLLABLE CAT
+CC42;CC42;110E 1161 11C1;CC42;110E 1161 11C1; # (챂; 챂; 챂; 챂; 챂; ) HANGUL SYLLABLE CAP
+CC43;CC43;110E 1161 11C2;CC43;110E 1161 11C2; # (챃; 챃; 챃; 챃; 챃; ) HANGUL SYLLABLE CAH
+CC44;CC44;110E 1162;CC44;110E 1162; # (채; 채; 채; 채; 채; ) HANGUL SYLLABLE CAE
+CC45;CC45;110E 1162 11A8;CC45;110E 1162 11A8; # (책; 책; 책; 책; 책; ) HANGUL SYLLABLE CAEG
+CC46;CC46;110E 1162 11A9;CC46;110E 1162 11A9; # (챆; 챆; 챆; 챆; 챆; ) HANGUL SYLLABLE CAEGG
+CC47;CC47;110E 1162 11AA;CC47;110E 1162 11AA; # (챇; 챇; 챇; 챇; 챇; ) HANGUL SYLLABLE CAEGS
+CC48;CC48;110E 1162 11AB;CC48;110E 1162 11AB; # (챈; 챈; 챈; 챈; 챈; ) HANGUL SYLLABLE CAEN
+CC49;CC49;110E 1162 11AC;CC49;110E 1162 11AC; # (챉; 챉; 챉; 챉; 챉; ) HANGUL SYLLABLE CAENJ
+CC4A;CC4A;110E 1162 11AD;CC4A;110E 1162 11AD; # (챊; 챊; 챊; 챊; 챊; ) HANGUL SYLLABLE CAENH
+CC4B;CC4B;110E 1162 11AE;CC4B;110E 1162 11AE; # (챋; 챋; 챋; 챋; 챋; ) HANGUL SYLLABLE CAED
+CC4C;CC4C;110E 1162 11AF;CC4C;110E 1162 11AF; # (챌; 챌; 챌; 챌; 챌; ) HANGUL SYLLABLE CAEL
+CC4D;CC4D;110E 1162 11B0;CC4D;110E 1162 11B0; # (챍; 챍; 챍; 챍; 챍; ) HANGUL SYLLABLE CAELG
+CC4E;CC4E;110E 1162 11B1;CC4E;110E 1162 11B1; # (챎; 챎; 챎; 챎; 챎; ) HANGUL SYLLABLE CAELM
+CC4F;CC4F;110E 1162 11B2;CC4F;110E 1162 11B2; # (챏; 챏; 챏; 챏; 챏; ) HANGUL SYLLABLE CAELB
+CC50;CC50;110E 1162 11B3;CC50;110E 1162 11B3; # (챐; 챐; 챐; 챐; 챐; ) HANGUL SYLLABLE CAELS
+CC51;CC51;110E 1162 11B4;CC51;110E 1162 11B4; # (챑; 챑; 챑; 챑; 챑; ) HANGUL SYLLABLE CAELT
+CC52;CC52;110E 1162 11B5;CC52;110E 1162 11B5; # (챒; 챒; 챒; 챒; 챒; ) HANGUL SYLLABLE CAELP
+CC53;CC53;110E 1162 11B6;CC53;110E 1162 11B6; # (챓; 챓; 챓; 챓; 챓; ) HANGUL SYLLABLE CAELH
+CC54;CC54;110E 1162 11B7;CC54;110E 1162 11B7; # (챔; 챔; 챔; 챔; 챔; ) HANGUL SYLLABLE CAEM
+CC55;CC55;110E 1162 11B8;CC55;110E 1162 11B8; # (챕; 챕; 챕; 챕; 챕; ) HANGUL SYLLABLE CAEB
+CC56;CC56;110E 1162 11B9;CC56;110E 1162 11B9; # (챖; 챖; 챖; 챖; 챖; ) HANGUL SYLLABLE CAEBS
+CC57;CC57;110E 1162 11BA;CC57;110E 1162 11BA; # (챗; 챗; 챗; 챗; 챗; ) HANGUL SYLLABLE CAES
+CC58;CC58;110E 1162 11BB;CC58;110E 1162 11BB; # (챘; 챘; 챘; 챘; 챘; ) HANGUL SYLLABLE CAESS
+CC59;CC59;110E 1162 11BC;CC59;110E 1162 11BC; # (챙; 챙; 챙; 챙; 챙; ) HANGUL SYLLABLE CAENG
+CC5A;CC5A;110E 1162 11BD;CC5A;110E 1162 11BD; # (챚; 챚; 챚; 챚; 챚; ) HANGUL SYLLABLE CAEJ
+CC5B;CC5B;110E 1162 11BE;CC5B;110E 1162 11BE; # (챛; 챛; 챛; 챛; 챛; ) HANGUL SYLLABLE CAEC
+CC5C;CC5C;110E 1162 11BF;CC5C;110E 1162 11BF; # (챜; 챜; 챜; 챜; 챜; ) HANGUL SYLLABLE CAEK
+CC5D;CC5D;110E 1162 11C0;CC5D;110E 1162 11C0; # (챝; 챝; 챝; 챝; 챝; ) HANGUL SYLLABLE CAET
+CC5E;CC5E;110E 1162 11C1;CC5E;110E 1162 11C1; # (챞; 챞; 챞; 챞; 챞; ) HANGUL SYLLABLE CAEP
+CC5F;CC5F;110E 1162 11C2;CC5F;110E 1162 11C2; # (챟; 챟; 챟; 챟; 챟; ) HANGUL SYLLABLE CAEH
+CC60;CC60;110E 1163;CC60;110E 1163; # (챠; 챠; 챠; 챠; 챠; ) HANGUL SYLLABLE CYA
+CC61;CC61;110E 1163 11A8;CC61;110E 1163 11A8; # (챡; 챡; 챡; 챡; 챡; ) HANGUL SYLLABLE CYAG
+CC62;CC62;110E 1163 11A9;CC62;110E 1163 11A9; # (챢; 챢; 챢; 챢; 챢; ) HANGUL SYLLABLE CYAGG
+CC63;CC63;110E 1163 11AA;CC63;110E 1163 11AA; # (챣; 챣; 챣; 챣; 챣; ) HANGUL SYLLABLE CYAGS
+CC64;CC64;110E 1163 11AB;CC64;110E 1163 11AB; # (챤; 챤; 챤; 챤; 챤; ) HANGUL SYLLABLE CYAN
+CC65;CC65;110E 1163 11AC;CC65;110E 1163 11AC; # (챥; 챥; 챥; 챥; 챥; ) HANGUL SYLLABLE CYANJ
+CC66;CC66;110E 1163 11AD;CC66;110E 1163 11AD; # (챦; 챦; 챦; 챦; 챦; ) HANGUL SYLLABLE CYANH
+CC67;CC67;110E 1163 11AE;CC67;110E 1163 11AE; # (챧; 챧; 챧; 챧; 챧; ) HANGUL SYLLABLE CYAD
+CC68;CC68;110E 1163 11AF;CC68;110E 1163 11AF; # (챨; 챨; 챨; 챨; 챨; ) HANGUL SYLLABLE CYAL
+CC69;CC69;110E 1163 11B0;CC69;110E 1163 11B0; # (챩; 챩; 챩; 챩; 챩; ) HANGUL SYLLABLE CYALG
+CC6A;CC6A;110E 1163 11B1;CC6A;110E 1163 11B1; # (챪; 챪; 챪; 챪; 챪; ) HANGUL SYLLABLE CYALM
+CC6B;CC6B;110E 1163 11B2;CC6B;110E 1163 11B2; # (챫; 챫; 챫; 챫; 챫; ) HANGUL SYLLABLE CYALB
+CC6C;CC6C;110E 1163 11B3;CC6C;110E 1163 11B3; # (챬; 챬; 챬; 챬; 챬; ) HANGUL SYLLABLE CYALS
+CC6D;CC6D;110E 1163 11B4;CC6D;110E 1163 11B4; # (챭; 챭; 챭; 챭; 챭; ) HANGUL SYLLABLE CYALT
+CC6E;CC6E;110E 1163 11B5;CC6E;110E 1163 11B5; # (챮; 챮; 챮; 챮; 챮; ) HANGUL SYLLABLE CYALP
+CC6F;CC6F;110E 1163 11B6;CC6F;110E 1163 11B6; # (챯; 챯; 챯; 챯; 챯; ) HANGUL SYLLABLE CYALH
+CC70;CC70;110E 1163 11B7;CC70;110E 1163 11B7; # (챰; 챰; 챰; 챰; 챰; ) HANGUL SYLLABLE CYAM
+CC71;CC71;110E 1163 11B8;CC71;110E 1163 11B8; # (챱; 챱; 챱; 챱; 챱; ) HANGUL SYLLABLE CYAB
+CC72;CC72;110E 1163 11B9;CC72;110E 1163 11B9; # (챲; 챲; 챲; 챲; 챲; ) HANGUL SYLLABLE CYABS
+CC73;CC73;110E 1163 11BA;CC73;110E 1163 11BA; # (챳; 챳; 챳; 챳; 챳; ) HANGUL SYLLABLE CYAS
+CC74;CC74;110E 1163 11BB;CC74;110E 1163 11BB; # (챴; 챴; 챴; 챴; 챴; ) HANGUL SYLLABLE CYASS
+CC75;CC75;110E 1163 11BC;CC75;110E 1163 11BC; # (챵; 챵; 챵; 챵; 챵; ) HANGUL SYLLABLE CYANG
+CC76;CC76;110E 1163 11BD;CC76;110E 1163 11BD; # (챶; 챶; 챶; 챶; 챶; ) HANGUL SYLLABLE CYAJ
+CC77;CC77;110E 1163 11BE;CC77;110E 1163 11BE; # (챷; 챷; 챷; 챷; 챷; ) HANGUL SYLLABLE CYAC
+CC78;CC78;110E 1163 11BF;CC78;110E 1163 11BF; # (챸; 챸; 챸; 챸; 챸; ) HANGUL SYLLABLE CYAK
+CC79;CC79;110E 1163 11C0;CC79;110E 1163 11C0; # (챹; 챹; 챹; 챹; 챹; ) HANGUL SYLLABLE CYAT
+CC7A;CC7A;110E 1163 11C1;CC7A;110E 1163 11C1; # (챺; 챺; 챺; 챺; 챺; ) HANGUL SYLLABLE CYAP
+CC7B;CC7B;110E 1163 11C2;CC7B;110E 1163 11C2; # (챻; 챻; 챻; 챻; 챻; ) HANGUL SYLLABLE CYAH
+CC7C;CC7C;110E 1164;CC7C;110E 1164; # (챼; 챼; 챼; 챼; 챼; ) HANGUL SYLLABLE CYAE
+CC7D;CC7D;110E 1164 11A8;CC7D;110E 1164 11A8; # (챽; 챽; 챽; 챽; 챽; ) HANGUL SYLLABLE CYAEG
+CC7E;CC7E;110E 1164 11A9;CC7E;110E 1164 11A9; # (챾; 챾; 챾; 챾; 챾; ) HANGUL SYLLABLE CYAEGG
+CC7F;CC7F;110E 1164 11AA;CC7F;110E 1164 11AA; # (챿; 챿; 챿; 챿; 챿; ) HANGUL SYLLABLE CYAEGS
+CC80;CC80;110E 1164 11AB;CC80;110E 1164 11AB; # (첀; 첀; 첀; 첀; 첀; ) HANGUL SYLLABLE CYAEN
+CC81;CC81;110E 1164 11AC;CC81;110E 1164 11AC; # (첁; 첁; 첁; 첁; 첁; ) HANGUL SYLLABLE CYAENJ
+CC82;CC82;110E 1164 11AD;CC82;110E 1164 11AD; # (첂; 첂; 첂; 첂; 첂; ) HANGUL SYLLABLE CYAENH
+CC83;CC83;110E 1164 11AE;CC83;110E 1164 11AE; # (첃; 첃; 첃; 첃; 첃; ) HANGUL SYLLABLE CYAED
+CC84;CC84;110E 1164 11AF;CC84;110E 1164 11AF; # (첄; 첄; 첄; 첄; 첄; ) HANGUL SYLLABLE CYAEL
+CC85;CC85;110E 1164 11B0;CC85;110E 1164 11B0; # (첅; 첅; 첅; 첅; 첅; ) HANGUL SYLLABLE CYAELG
+CC86;CC86;110E 1164 11B1;CC86;110E 1164 11B1; # (첆; 첆; 첆; 첆; 첆; ) HANGUL SYLLABLE CYAELM
+CC87;CC87;110E 1164 11B2;CC87;110E 1164 11B2; # (첇; 첇; 첇; 첇; 첇; ) HANGUL SYLLABLE CYAELB
+CC88;CC88;110E 1164 11B3;CC88;110E 1164 11B3; # (첈; 첈; 첈; 첈; 첈; ) HANGUL SYLLABLE CYAELS
+CC89;CC89;110E 1164 11B4;CC89;110E 1164 11B4; # (첉; 첉; 첉; 첉; 첉; ) HANGUL SYLLABLE CYAELT
+CC8A;CC8A;110E 1164 11B5;CC8A;110E 1164 11B5; # (첊; 첊; 첊; 첊; 첊; ) HANGUL SYLLABLE CYAELP
+CC8B;CC8B;110E 1164 11B6;CC8B;110E 1164 11B6; # (첋; 첋; 첋; 첋; 첋; ) HANGUL SYLLABLE CYAELH
+CC8C;CC8C;110E 1164 11B7;CC8C;110E 1164 11B7; # (첌; 첌; 첌; 첌; 첌; ) HANGUL SYLLABLE CYAEM
+CC8D;CC8D;110E 1164 11B8;CC8D;110E 1164 11B8; # (첍; 첍; 첍; 첍; 첍; ) HANGUL SYLLABLE CYAEB
+CC8E;CC8E;110E 1164 11B9;CC8E;110E 1164 11B9; # (첎; 첎; 첎; 첎; 첎; ) HANGUL SYLLABLE CYAEBS
+CC8F;CC8F;110E 1164 11BA;CC8F;110E 1164 11BA; # (첏; 첏; 첏; 첏; 첏; ) HANGUL SYLLABLE CYAES
+CC90;CC90;110E 1164 11BB;CC90;110E 1164 11BB; # (첐; 첐; 첐; 첐; 첐; ) HANGUL SYLLABLE CYAESS
+CC91;CC91;110E 1164 11BC;CC91;110E 1164 11BC; # (첑; 첑; 첑; 첑; 첑; ) HANGUL SYLLABLE CYAENG
+CC92;CC92;110E 1164 11BD;CC92;110E 1164 11BD; # (첒; 첒; 첒; 첒; 첒; ) HANGUL SYLLABLE CYAEJ
+CC93;CC93;110E 1164 11BE;CC93;110E 1164 11BE; # (첓; 첓; 첓; 첓; 첓; ) HANGUL SYLLABLE CYAEC
+CC94;CC94;110E 1164 11BF;CC94;110E 1164 11BF; # (첔; 첔; 첔; 첔; 첔; ) HANGUL SYLLABLE CYAEK
+CC95;CC95;110E 1164 11C0;CC95;110E 1164 11C0; # (첕; 첕; 첕; 첕; 첕; ) HANGUL SYLLABLE CYAET
+CC96;CC96;110E 1164 11C1;CC96;110E 1164 11C1; # (첖; 첖; 첖; 첖; 첖; ) HANGUL SYLLABLE CYAEP
+CC97;CC97;110E 1164 11C2;CC97;110E 1164 11C2; # (첗; 첗; 첗; 첗; 첗; ) HANGUL SYLLABLE CYAEH
+CC98;CC98;110E 1165;CC98;110E 1165; # (처; 처; 처; 처; 처; ) HANGUL SYLLABLE CEO
+CC99;CC99;110E 1165 11A8;CC99;110E 1165 11A8; # (척; 척; 척; 척; 척; ) HANGUL SYLLABLE CEOG
+CC9A;CC9A;110E 1165 11A9;CC9A;110E 1165 11A9; # (첚; 첚; 첚; 첚; 첚; ) HANGUL SYLLABLE CEOGG
+CC9B;CC9B;110E 1165 11AA;CC9B;110E 1165 11AA; # (첛; 첛; 첛; 첛; 첛; ) HANGUL SYLLABLE CEOGS
+CC9C;CC9C;110E 1165 11AB;CC9C;110E 1165 11AB; # (천; 천; 천; 천; 천; ) HANGUL SYLLABLE CEON
+CC9D;CC9D;110E 1165 11AC;CC9D;110E 1165 11AC; # (첝; 첝; 첝; 첝; 첝; ) HANGUL SYLLABLE CEONJ
+CC9E;CC9E;110E 1165 11AD;CC9E;110E 1165 11AD; # (첞; 첞; 첞; 첞; 첞; ) HANGUL SYLLABLE CEONH
+CC9F;CC9F;110E 1165 11AE;CC9F;110E 1165 11AE; # (첟; 첟; 첟; 첟; 첟; ) HANGUL SYLLABLE CEOD
+CCA0;CCA0;110E 1165 11AF;CCA0;110E 1165 11AF; # (철; 철; 철; 철; 철; ) HANGUL SYLLABLE CEOL
+CCA1;CCA1;110E 1165 11B0;CCA1;110E 1165 11B0; # (첡; 첡; 첡; 첡; 첡; ) HANGUL SYLLABLE CEOLG
+CCA2;CCA2;110E 1165 11B1;CCA2;110E 1165 11B1; # (첢; 첢; 첢; 첢; 첢; ) HANGUL SYLLABLE CEOLM
+CCA3;CCA3;110E 1165 11B2;CCA3;110E 1165 11B2; # (첣; 첣; 첣; 첣; 첣; ) HANGUL SYLLABLE CEOLB
+CCA4;CCA4;110E 1165 11B3;CCA4;110E 1165 11B3; # (첤; 첤; 첤; 첤; 첤; ) HANGUL SYLLABLE CEOLS
+CCA5;CCA5;110E 1165 11B4;CCA5;110E 1165 11B4; # (첥; 첥; 첥; 첥; 첥; ) HANGUL SYLLABLE CEOLT
+CCA6;CCA6;110E 1165 11B5;CCA6;110E 1165 11B5; # (첦; 첦; 첦; 첦; 첦; ) HANGUL SYLLABLE CEOLP
+CCA7;CCA7;110E 1165 11B6;CCA7;110E 1165 11B6; # (첧; 첧; 첧; 첧; 첧; ) HANGUL SYLLABLE CEOLH
+CCA8;CCA8;110E 1165 11B7;CCA8;110E 1165 11B7; # (첨; 첨; 첨; 첨; 첨; ) HANGUL SYLLABLE CEOM
+CCA9;CCA9;110E 1165 11B8;CCA9;110E 1165 11B8; # (첩; 첩; 첩; 첩; 첩; ) HANGUL SYLLABLE CEOB
+CCAA;CCAA;110E 1165 11B9;CCAA;110E 1165 11B9; # (첪; 첪; 첪; 첪; 첪; ) HANGUL SYLLABLE CEOBS
+CCAB;CCAB;110E 1165 11BA;CCAB;110E 1165 11BA; # (첫; 첫; 첫; 첫; 첫; ) HANGUL SYLLABLE CEOS
+CCAC;CCAC;110E 1165 11BB;CCAC;110E 1165 11BB; # (첬; 첬; 첬; 첬; 첬; ) HANGUL SYLLABLE CEOSS
+CCAD;CCAD;110E 1165 11BC;CCAD;110E 1165 11BC; # (청; 청; 청; 청; 청; ) HANGUL SYLLABLE CEONG
+CCAE;CCAE;110E 1165 11BD;CCAE;110E 1165 11BD; # (첮; 첮; 첮; 첮; 첮; ) HANGUL SYLLABLE CEOJ
+CCAF;CCAF;110E 1165 11BE;CCAF;110E 1165 11BE; # (첯; 첯; 첯; 첯; 첯; ) HANGUL SYLLABLE CEOC
+CCB0;CCB0;110E 1165 11BF;CCB0;110E 1165 11BF; # (첰; 첰; 첰; 첰; 첰; ) HANGUL SYLLABLE CEOK
+CCB1;CCB1;110E 1165 11C0;CCB1;110E 1165 11C0; # (첱; 첱; 첱; 첱; 첱; ) HANGUL SYLLABLE CEOT
+CCB2;CCB2;110E 1165 11C1;CCB2;110E 1165 11C1; # (첲; 첲; 첲; 첲; 첲; ) HANGUL SYLLABLE CEOP
+CCB3;CCB3;110E 1165 11C2;CCB3;110E 1165 11C2; # (첳; 첳; 첳; 첳; 첳; ) HANGUL SYLLABLE CEOH
+CCB4;CCB4;110E 1166;CCB4;110E 1166; # (체; 체; 체; 체; 체; ) HANGUL SYLLABLE CE
+CCB5;CCB5;110E 1166 11A8;CCB5;110E 1166 11A8; # (첵; 첵; 첵; 첵; 첵; ) HANGUL SYLLABLE CEG
+CCB6;CCB6;110E 1166 11A9;CCB6;110E 1166 11A9; # (첶; 첶; 첶; 첶; 첶; ) HANGUL SYLLABLE CEGG
+CCB7;CCB7;110E 1166 11AA;CCB7;110E 1166 11AA; # (첷; 첷; 첷; 첷; 첷; ) HANGUL SYLLABLE CEGS
+CCB8;CCB8;110E 1166 11AB;CCB8;110E 1166 11AB; # (첸; 첸; 첸; 첸; 첸; ) HANGUL SYLLABLE CEN
+CCB9;CCB9;110E 1166 11AC;CCB9;110E 1166 11AC; # (첹; 첹; 첹; 첹; 첹; ) HANGUL SYLLABLE CENJ
+CCBA;CCBA;110E 1166 11AD;CCBA;110E 1166 11AD; # (첺; 첺; 첺; 첺; 첺; ) HANGUL SYLLABLE CENH
+CCBB;CCBB;110E 1166 11AE;CCBB;110E 1166 11AE; # (첻; 첻; 첻; 첻; 첻; ) HANGUL SYLLABLE CED
+CCBC;CCBC;110E 1166 11AF;CCBC;110E 1166 11AF; # (첼; 첼; 첼; 첼; 첼; ) HANGUL SYLLABLE CEL
+CCBD;CCBD;110E 1166 11B0;CCBD;110E 1166 11B0; # (첽; 첽; 첽; 첽; 첽; ) HANGUL SYLLABLE CELG
+CCBE;CCBE;110E 1166 11B1;CCBE;110E 1166 11B1; # (첾; 첾; 첾; 첾; 첾; ) HANGUL SYLLABLE CELM
+CCBF;CCBF;110E 1166 11B2;CCBF;110E 1166 11B2; # (첿; 첿; 첿; 첿; 첿; ) HANGUL SYLLABLE CELB
+CCC0;CCC0;110E 1166 11B3;CCC0;110E 1166 11B3; # (쳀; 쳀; 쳀; 쳀; 쳀; ) HANGUL SYLLABLE CELS
+CCC1;CCC1;110E 1166 11B4;CCC1;110E 1166 11B4; # (쳁; 쳁; 쳁; 쳁; 쳁; ) HANGUL SYLLABLE CELT
+CCC2;CCC2;110E 1166 11B5;CCC2;110E 1166 11B5; # (쳂; 쳂; 쳂; 쳂; 쳂; ) HANGUL SYLLABLE CELP
+CCC3;CCC3;110E 1166 11B6;CCC3;110E 1166 11B6; # (쳃; 쳃; 쳃; 쳃; 쳃; ) HANGUL SYLLABLE CELH
+CCC4;CCC4;110E 1166 11B7;CCC4;110E 1166 11B7; # (쳄; 쳄; 쳄; 쳄; 쳄; ) HANGUL SYLLABLE CEM
+CCC5;CCC5;110E 1166 11B8;CCC5;110E 1166 11B8; # (쳅; 쳅; 쳅; 쳅; 쳅; ) HANGUL SYLLABLE CEB
+CCC6;CCC6;110E 1166 11B9;CCC6;110E 1166 11B9; # (쳆; 쳆; 쳆; 쳆; 쳆; ) HANGUL SYLLABLE CEBS
+CCC7;CCC7;110E 1166 11BA;CCC7;110E 1166 11BA; # (쳇; 쳇; 쳇; 쳇; 쳇; ) HANGUL SYLLABLE CES
+CCC8;CCC8;110E 1166 11BB;CCC8;110E 1166 11BB; # (쳈; 쳈; 쳈; 쳈; 쳈; ) HANGUL SYLLABLE CESS
+CCC9;CCC9;110E 1166 11BC;CCC9;110E 1166 11BC; # (쳉; 쳉; 쳉; 쳉; 쳉; ) HANGUL SYLLABLE CENG
+CCCA;CCCA;110E 1166 11BD;CCCA;110E 1166 11BD; # (쳊; 쳊; 쳊; 쳊; 쳊; ) HANGUL SYLLABLE CEJ
+CCCB;CCCB;110E 1166 11BE;CCCB;110E 1166 11BE; # (쳋; 쳋; 쳋; 쳋; 쳋; ) HANGUL SYLLABLE CEC
+CCCC;CCCC;110E 1166 11BF;CCCC;110E 1166 11BF; # (쳌; 쳌; 쳌; 쳌; 쳌; ) HANGUL SYLLABLE CEK
+CCCD;CCCD;110E 1166 11C0;CCCD;110E 1166 11C0; # (쳍; 쳍; 쳍; 쳍; 쳍; ) HANGUL SYLLABLE CET
+CCCE;CCCE;110E 1166 11C1;CCCE;110E 1166 11C1; # (쳎; 쳎; 쳎; 쳎; 쳎; ) HANGUL SYLLABLE CEP
+CCCF;CCCF;110E 1166 11C2;CCCF;110E 1166 11C2; # (쳏; 쳏; 쳏; 쳏; 쳏; ) HANGUL SYLLABLE CEH
+CCD0;CCD0;110E 1167;CCD0;110E 1167; # (쳐; 쳐; 쳐; 쳐; 쳐; ) HANGUL SYLLABLE CYEO
+CCD1;CCD1;110E 1167 11A8;CCD1;110E 1167 11A8; # (쳑; 쳑; 쳑; 쳑; 쳑; ) HANGUL SYLLABLE CYEOG
+CCD2;CCD2;110E 1167 11A9;CCD2;110E 1167 11A9; # (쳒; 쳒; 쳒; 쳒; 쳒; ) HANGUL SYLLABLE CYEOGG
+CCD3;CCD3;110E 1167 11AA;CCD3;110E 1167 11AA; # (쳓; 쳓; 쳓; 쳓; 쳓; ) HANGUL SYLLABLE CYEOGS
+CCD4;CCD4;110E 1167 11AB;CCD4;110E 1167 11AB; # (쳔; 쳔; 쳔; 쳔; 쳔; ) HANGUL SYLLABLE CYEON
+CCD5;CCD5;110E 1167 11AC;CCD5;110E 1167 11AC; # (쳕; 쳕; 쳕; 쳕; 쳕; ) HANGUL SYLLABLE CYEONJ
+CCD6;CCD6;110E 1167 11AD;CCD6;110E 1167 11AD; # (쳖; 쳖; 쳖; 쳖; 쳖; ) HANGUL SYLLABLE CYEONH
+CCD7;CCD7;110E 1167 11AE;CCD7;110E 1167 11AE; # (쳗; 쳗; 쳗; 쳗; 쳗; ) HANGUL SYLLABLE CYEOD
+CCD8;CCD8;110E 1167 11AF;CCD8;110E 1167 11AF; # (쳘; 쳘; 쳘; 쳘; 쳘; ) HANGUL SYLLABLE CYEOL
+CCD9;CCD9;110E 1167 11B0;CCD9;110E 1167 11B0; # (쳙; 쳙; 쳙; 쳙; 쳙; ) HANGUL SYLLABLE CYEOLG
+CCDA;CCDA;110E 1167 11B1;CCDA;110E 1167 11B1; # (쳚; 쳚; 쳚; 쳚; 쳚; ) HANGUL SYLLABLE CYEOLM
+CCDB;CCDB;110E 1167 11B2;CCDB;110E 1167 11B2; # (쳛; 쳛; 쳛; 쳛; 쳛; ) HANGUL SYLLABLE CYEOLB
+CCDC;CCDC;110E 1167 11B3;CCDC;110E 1167 11B3; # (쳜; 쳜; 쳜; 쳜; 쳜; ) HANGUL SYLLABLE CYEOLS
+CCDD;CCDD;110E 1167 11B4;CCDD;110E 1167 11B4; # (쳝; 쳝; 쳝; 쳝; 쳝; ) HANGUL SYLLABLE CYEOLT
+CCDE;CCDE;110E 1167 11B5;CCDE;110E 1167 11B5; # (쳞; 쳞; 쳞; 쳞; 쳞; ) HANGUL SYLLABLE CYEOLP
+CCDF;CCDF;110E 1167 11B6;CCDF;110E 1167 11B6; # (쳟; 쳟; 쳟; 쳟; 쳟; ) HANGUL SYLLABLE CYEOLH
+CCE0;CCE0;110E 1167 11B7;CCE0;110E 1167 11B7; # (쳠; 쳠; 쳠; 쳠; 쳠; ) HANGUL SYLLABLE CYEOM
+CCE1;CCE1;110E 1167 11B8;CCE1;110E 1167 11B8; # (쳡; 쳡; 쳡; 쳡; 쳡; ) HANGUL SYLLABLE CYEOB
+CCE2;CCE2;110E 1167 11B9;CCE2;110E 1167 11B9; # (쳢; 쳢; 쳢; 쳢; 쳢; ) HANGUL SYLLABLE CYEOBS
+CCE3;CCE3;110E 1167 11BA;CCE3;110E 1167 11BA; # (쳣; 쳣; 쳣; 쳣; 쳣; ) HANGUL SYLLABLE CYEOS
+CCE4;CCE4;110E 1167 11BB;CCE4;110E 1167 11BB; # (쳤; 쳤; 쳤; 쳤; 쳤; ) HANGUL SYLLABLE CYEOSS
+CCE5;CCE5;110E 1167 11BC;CCE5;110E 1167 11BC; # (쳥; 쳥; 쳥; 쳥; 쳥; ) HANGUL SYLLABLE CYEONG
+CCE6;CCE6;110E 1167 11BD;CCE6;110E 1167 11BD; # (쳦; 쳦; 쳦; 쳦; 쳦; ) HANGUL SYLLABLE CYEOJ
+CCE7;CCE7;110E 1167 11BE;CCE7;110E 1167 11BE; # (쳧; 쳧; 쳧; 쳧; 쳧; ) HANGUL SYLLABLE CYEOC
+CCE8;CCE8;110E 1167 11BF;CCE8;110E 1167 11BF; # (쳨; 쳨; 쳨; 쳨; 쳨; ) HANGUL SYLLABLE CYEOK
+CCE9;CCE9;110E 1167 11C0;CCE9;110E 1167 11C0; # (쳩; 쳩; 쳩; 쳩; 쳩; ) HANGUL SYLLABLE CYEOT
+CCEA;CCEA;110E 1167 11C1;CCEA;110E 1167 11C1; # (쳪; 쳪; 쳪; 쳪; 쳪; ) HANGUL SYLLABLE CYEOP
+CCEB;CCEB;110E 1167 11C2;CCEB;110E 1167 11C2; # (쳫; 쳫; 쳫; 쳫; 쳫; ) HANGUL SYLLABLE CYEOH
+CCEC;CCEC;110E 1168;CCEC;110E 1168; # (쳬; 쳬; 쳬; 쳬; 쳬; ) HANGUL SYLLABLE CYE
+CCED;CCED;110E 1168 11A8;CCED;110E 1168 11A8; # (쳭; 쳭; 쳭; 쳭; 쳭; ) HANGUL SYLLABLE CYEG
+CCEE;CCEE;110E 1168 11A9;CCEE;110E 1168 11A9; # (쳮; 쳮; 쳮; 쳮; 쳮; ) HANGUL SYLLABLE CYEGG
+CCEF;CCEF;110E 1168 11AA;CCEF;110E 1168 11AA; # (쳯; 쳯; 쳯; 쳯; 쳯; ) HANGUL SYLLABLE CYEGS
+CCF0;CCF0;110E 1168 11AB;CCF0;110E 1168 11AB; # (쳰; 쳰; 쳰; 쳰; 쳰; ) HANGUL SYLLABLE CYEN
+CCF1;CCF1;110E 1168 11AC;CCF1;110E 1168 11AC; # (쳱; 쳱; 쳱; 쳱; 쳱; ) HANGUL SYLLABLE CYENJ
+CCF2;CCF2;110E 1168 11AD;CCF2;110E 1168 11AD; # (쳲; 쳲; 쳲; 쳲; 쳲; ) HANGUL SYLLABLE CYENH
+CCF3;CCF3;110E 1168 11AE;CCF3;110E 1168 11AE; # (쳳; 쳳; 쳳; 쳳; 쳳; ) HANGUL SYLLABLE CYED
+CCF4;CCF4;110E 1168 11AF;CCF4;110E 1168 11AF; # (쳴; 쳴; 쳴; 쳴; 쳴; ) HANGUL SYLLABLE CYEL
+CCF5;CCF5;110E 1168 11B0;CCF5;110E 1168 11B0; # (쳵; 쳵; 쳵; 쳵; 쳵; ) HANGUL SYLLABLE CYELG
+CCF6;CCF6;110E 1168 11B1;CCF6;110E 1168 11B1; # (쳶; 쳶; 쳶; 쳶; 쳶; ) HANGUL SYLLABLE CYELM
+CCF7;CCF7;110E 1168 11B2;CCF7;110E 1168 11B2; # (쳷; 쳷; 쳷; 쳷; 쳷; ) HANGUL SYLLABLE CYELB
+CCF8;CCF8;110E 1168 11B3;CCF8;110E 1168 11B3; # (쳸; 쳸; 쳸; 쳸; 쳸; ) HANGUL SYLLABLE CYELS
+CCF9;CCF9;110E 1168 11B4;CCF9;110E 1168 11B4; # (쳹; 쳹; 쳹; 쳹; 쳹; ) HANGUL SYLLABLE CYELT
+CCFA;CCFA;110E 1168 11B5;CCFA;110E 1168 11B5; # (쳺; 쳺; 쳺; 쳺; 쳺; ) HANGUL SYLLABLE CYELP
+CCFB;CCFB;110E 1168 11B6;CCFB;110E 1168 11B6; # (쳻; 쳻; 쳻; 쳻; 쳻; ) HANGUL SYLLABLE CYELH
+CCFC;CCFC;110E 1168 11B7;CCFC;110E 1168 11B7; # (쳼; 쳼; 쳼; 쳼; 쳼; ) HANGUL SYLLABLE CYEM
+CCFD;CCFD;110E 1168 11B8;CCFD;110E 1168 11B8; # (쳽; 쳽; 쳽; 쳽; 쳽; ) HANGUL SYLLABLE CYEB
+CCFE;CCFE;110E 1168 11B9;CCFE;110E 1168 11B9; # (쳾; 쳾; 쳾; 쳾; 쳾; ) HANGUL SYLLABLE CYEBS
+CCFF;CCFF;110E 1168 11BA;CCFF;110E 1168 11BA; # (쳿; 쳿; 쳿; 쳿; 쳿; ) HANGUL SYLLABLE CYES
+CD00;CD00;110E 1168 11BB;CD00;110E 1168 11BB; # (촀; 촀; 촀; 촀; 촀; ) HANGUL SYLLABLE CYESS
+CD01;CD01;110E 1168 11BC;CD01;110E 1168 11BC; # (촁; 촁; 촁; 촁; 촁; ) HANGUL SYLLABLE CYENG
+CD02;CD02;110E 1168 11BD;CD02;110E 1168 11BD; # (촂; 촂; 촂; 촂; 촂; ) HANGUL SYLLABLE CYEJ
+CD03;CD03;110E 1168 11BE;CD03;110E 1168 11BE; # (촃; 촃; 촃; 촃; 촃; ) HANGUL SYLLABLE CYEC
+CD04;CD04;110E 1168 11BF;CD04;110E 1168 11BF; # (촄; 촄; 촄; 촄; 촄; ) HANGUL SYLLABLE CYEK
+CD05;CD05;110E 1168 11C0;CD05;110E 1168 11C0; # (촅; 촅; 촅; 촅; 촅; ) HANGUL SYLLABLE CYET
+CD06;CD06;110E 1168 11C1;CD06;110E 1168 11C1; # (촆; 촆; 촆; 촆; 촆; ) HANGUL SYLLABLE CYEP
+CD07;CD07;110E 1168 11C2;CD07;110E 1168 11C2; # (촇; 촇; 촇; 촇; 촇; ) HANGUL SYLLABLE CYEH
+CD08;CD08;110E 1169;CD08;110E 1169; # (초; 초; 초; 초; 초; ) HANGUL SYLLABLE CO
+CD09;CD09;110E 1169 11A8;CD09;110E 1169 11A8; # (촉; 촉; 촉; 촉; 촉; ) HANGUL SYLLABLE COG
+CD0A;CD0A;110E 1169 11A9;CD0A;110E 1169 11A9; # (촊; 촊; 촊; 촊; 촊; ) HANGUL SYLLABLE COGG
+CD0B;CD0B;110E 1169 11AA;CD0B;110E 1169 11AA; # (촋; 촋; 촋; 촋; 촋; ) HANGUL SYLLABLE COGS
+CD0C;CD0C;110E 1169 11AB;CD0C;110E 1169 11AB; # (촌; 촌; 촌; 촌; 촌; ) HANGUL SYLLABLE CON
+CD0D;CD0D;110E 1169 11AC;CD0D;110E 1169 11AC; # (촍; 촍; 촍; 촍; 촍; ) HANGUL SYLLABLE CONJ
+CD0E;CD0E;110E 1169 11AD;CD0E;110E 1169 11AD; # (촎; 촎; 촎; 촎; 촎; ) HANGUL SYLLABLE CONH
+CD0F;CD0F;110E 1169 11AE;CD0F;110E 1169 11AE; # (촏; 촏; 촏; 촏; 촏; ) HANGUL SYLLABLE COD
+CD10;CD10;110E 1169 11AF;CD10;110E 1169 11AF; # (촐; 촐; 촐; 촐; 촐; ) HANGUL SYLLABLE COL
+CD11;CD11;110E 1169 11B0;CD11;110E 1169 11B0; # (촑; 촑; 촑; 촑; 촑; ) HANGUL SYLLABLE COLG
+CD12;CD12;110E 1169 11B1;CD12;110E 1169 11B1; # (촒; 촒; 촒; 촒; 촒; ) HANGUL SYLLABLE COLM
+CD13;CD13;110E 1169 11B2;CD13;110E 1169 11B2; # (촓; 촓; 촓; 촓; 촓; ) HANGUL SYLLABLE COLB
+CD14;CD14;110E 1169 11B3;CD14;110E 1169 11B3; # (촔; 촔; 촔; 촔; 촔; ) HANGUL SYLLABLE COLS
+CD15;CD15;110E 1169 11B4;CD15;110E 1169 11B4; # (촕; 촕; 촕; 촕; 촕; ) HANGUL SYLLABLE COLT
+CD16;CD16;110E 1169 11B5;CD16;110E 1169 11B5; # (촖; 촖; 촖; 촖; 촖; ) HANGUL SYLLABLE COLP
+CD17;CD17;110E 1169 11B6;CD17;110E 1169 11B6; # (촗; 촗; 촗; 촗; 촗; ) HANGUL SYLLABLE COLH
+CD18;CD18;110E 1169 11B7;CD18;110E 1169 11B7; # (촘; 촘; 촘; 촘; 촘; ) HANGUL SYLLABLE COM
+CD19;CD19;110E 1169 11B8;CD19;110E 1169 11B8; # (촙; 촙; 촙; 촙; 촙; ) HANGUL SYLLABLE COB
+CD1A;CD1A;110E 1169 11B9;CD1A;110E 1169 11B9; # (촚; 촚; 촚; 촚; 촚; ) HANGUL SYLLABLE COBS
+CD1B;CD1B;110E 1169 11BA;CD1B;110E 1169 11BA; # (촛; 촛; 촛; 촛; 촛; ) HANGUL SYLLABLE COS
+CD1C;CD1C;110E 1169 11BB;CD1C;110E 1169 11BB; # (촜; 촜; 촜; 촜; 촜; ) HANGUL SYLLABLE COSS
+CD1D;CD1D;110E 1169 11BC;CD1D;110E 1169 11BC; # (총; 총; 총; 총; 총; ) HANGUL SYLLABLE CONG
+CD1E;CD1E;110E 1169 11BD;CD1E;110E 1169 11BD; # (촞; 촞; 촞; 촞; 촞; ) HANGUL SYLLABLE COJ
+CD1F;CD1F;110E 1169 11BE;CD1F;110E 1169 11BE; # (촟; 촟; 촟; 촟; 촟; ) HANGUL SYLLABLE COC
+CD20;CD20;110E 1169 11BF;CD20;110E 1169 11BF; # (촠; 촠; 촠; 촠; 촠; ) HANGUL SYLLABLE COK
+CD21;CD21;110E 1169 11C0;CD21;110E 1169 11C0; # (촡; 촡; 촡; 촡; 촡; ) HANGUL SYLLABLE COT
+CD22;CD22;110E 1169 11C1;CD22;110E 1169 11C1; # (촢; 촢; 촢; 촢; 촢; ) HANGUL SYLLABLE COP
+CD23;CD23;110E 1169 11C2;CD23;110E 1169 11C2; # (촣; 촣; 촣; 촣; 촣; ) HANGUL SYLLABLE COH
+CD24;CD24;110E 116A;CD24;110E 116A; # (촤; 촤; 촤; 촤; 촤; ) HANGUL SYLLABLE CWA
+CD25;CD25;110E 116A 11A8;CD25;110E 116A 11A8; # (촥; 촥; 촥; 촥; 촥; ) HANGUL SYLLABLE CWAG
+CD26;CD26;110E 116A 11A9;CD26;110E 116A 11A9; # (촦; 촦; 촦; 촦; 촦; ) HANGUL SYLLABLE CWAGG
+CD27;CD27;110E 116A 11AA;CD27;110E 116A 11AA; # (촧; 촧; 촧; 촧; 촧; ) HANGUL SYLLABLE CWAGS
+CD28;CD28;110E 116A 11AB;CD28;110E 116A 11AB; # (촨; 촨; 촨; 촨; 촨; ) HANGUL SYLLABLE CWAN
+CD29;CD29;110E 116A 11AC;CD29;110E 116A 11AC; # (촩; 촩; 촩; 촩; 촩; ) HANGUL SYLLABLE CWANJ
+CD2A;CD2A;110E 116A 11AD;CD2A;110E 116A 11AD; # (촪; 촪; 촪; 촪; 촪; ) HANGUL SYLLABLE CWANH
+CD2B;CD2B;110E 116A 11AE;CD2B;110E 116A 11AE; # (촫; 촫; 촫; 촫; 촫; ) HANGUL SYLLABLE CWAD
+CD2C;CD2C;110E 116A 11AF;CD2C;110E 116A 11AF; # (촬; 촬; 촬; 촬; 촬; ) HANGUL SYLLABLE CWAL
+CD2D;CD2D;110E 116A 11B0;CD2D;110E 116A 11B0; # (촭; 촭; 촭; 촭; 촭; ) HANGUL SYLLABLE CWALG
+CD2E;CD2E;110E 116A 11B1;CD2E;110E 116A 11B1; # (촮; 촮; 촮; 촮; 촮; ) HANGUL SYLLABLE CWALM
+CD2F;CD2F;110E 116A 11B2;CD2F;110E 116A 11B2; # (촯; 촯; 촯; 촯; 촯; ) HANGUL SYLLABLE CWALB
+CD30;CD30;110E 116A 11B3;CD30;110E 116A 11B3; # (촰; 촰; 촰; 촰; 촰; ) HANGUL SYLLABLE CWALS
+CD31;CD31;110E 116A 11B4;CD31;110E 116A 11B4; # (촱; 촱; 촱; 촱; 촱; ) HANGUL SYLLABLE CWALT
+CD32;CD32;110E 116A 11B5;CD32;110E 116A 11B5; # (촲; 촲; 촲; 촲; 촲; ) HANGUL SYLLABLE CWALP
+CD33;CD33;110E 116A 11B6;CD33;110E 116A 11B6; # (촳; 촳; 촳; 촳; 촳; ) HANGUL SYLLABLE CWALH
+CD34;CD34;110E 116A 11B7;CD34;110E 116A 11B7; # (촴; 촴; 촴; 촴; 촴; ) HANGUL SYLLABLE CWAM
+CD35;CD35;110E 116A 11B8;CD35;110E 116A 11B8; # (촵; 촵; 촵; 촵; 촵; ) HANGUL SYLLABLE CWAB
+CD36;CD36;110E 116A 11B9;CD36;110E 116A 11B9; # (촶; 촶; 촶; 촶; 촶; ) HANGUL SYLLABLE CWABS
+CD37;CD37;110E 116A 11BA;CD37;110E 116A 11BA; # (촷; 촷; 촷; 촷; 촷; ) HANGUL SYLLABLE CWAS
+CD38;CD38;110E 116A 11BB;CD38;110E 116A 11BB; # (촸; 촸; 촸; 촸; 촸; ) HANGUL SYLLABLE CWASS
+CD39;CD39;110E 116A 11BC;CD39;110E 116A 11BC; # (촹; 촹; 촹; 촹; 촹; ) HANGUL SYLLABLE CWANG
+CD3A;CD3A;110E 116A 11BD;CD3A;110E 116A 11BD; # (촺; 촺; 촺; 촺; 촺; ) HANGUL SYLLABLE CWAJ
+CD3B;CD3B;110E 116A 11BE;CD3B;110E 116A 11BE; # (촻; 촻; 촻; 촻; 촻; ) HANGUL SYLLABLE CWAC
+CD3C;CD3C;110E 116A 11BF;CD3C;110E 116A 11BF; # (촼; 촼; 촼; 촼; 촼; ) HANGUL SYLLABLE CWAK
+CD3D;CD3D;110E 116A 11C0;CD3D;110E 116A 11C0; # (촽; 촽; 촽; 촽; 촽; ) HANGUL SYLLABLE CWAT
+CD3E;CD3E;110E 116A 11C1;CD3E;110E 116A 11C1; # (촾; 촾; 촾; 촾; 촾; ) HANGUL SYLLABLE CWAP
+CD3F;CD3F;110E 116A 11C2;CD3F;110E 116A 11C2; # (촿; 촿; 촿; 촿; 촿; ) HANGUL SYLLABLE CWAH
+CD40;CD40;110E 116B;CD40;110E 116B; # (쵀; 쵀; 쵀; 쵀; 쵀; ) HANGUL SYLLABLE CWAE
+CD41;CD41;110E 116B 11A8;CD41;110E 116B 11A8; # (쵁; 쵁; 쵁; 쵁; 쵁; ) HANGUL SYLLABLE CWAEG
+CD42;CD42;110E 116B 11A9;CD42;110E 116B 11A9; # (쵂; 쵂; 쵂; 쵂; 쵂; ) HANGUL SYLLABLE CWAEGG
+CD43;CD43;110E 116B 11AA;CD43;110E 116B 11AA; # (쵃; 쵃; 쵃; 쵃; 쵃; ) HANGUL SYLLABLE CWAEGS
+CD44;CD44;110E 116B 11AB;CD44;110E 116B 11AB; # (쵄; 쵄; 쵄; 쵄; 쵄; ) HANGUL SYLLABLE CWAEN
+CD45;CD45;110E 116B 11AC;CD45;110E 116B 11AC; # (쵅; 쵅; 쵅; 쵅; 쵅; ) HANGUL SYLLABLE CWAENJ
+CD46;CD46;110E 116B 11AD;CD46;110E 116B 11AD; # (쵆; 쵆; 쵆; 쵆; 쵆; ) HANGUL SYLLABLE CWAENH
+CD47;CD47;110E 116B 11AE;CD47;110E 116B 11AE; # (쵇; 쵇; 쵇; 쵇; 쵇; ) HANGUL SYLLABLE CWAED
+CD48;CD48;110E 116B 11AF;CD48;110E 116B 11AF; # (쵈; 쵈; 쵈; 쵈; 쵈; ) HANGUL SYLLABLE CWAEL
+CD49;CD49;110E 116B 11B0;CD49;110E 116B 11B0; # (쵉; 쵉; 쵉; 쵉; 쵉; ) HANGUL SYLLABLE CWAELG
+CD4A;CD4A;110E 116B 11B1;CD4A;110E 116B 11B1; # (쵊; 쵊; 쵊; 쵊; 쵊; ) HANGUL SYLLABLE CWAELM
+CD4B;CD4B;110E 116B 11B2;CD4B;110E 116B 11B2; # (쵋; 쵋; 쵋; 쵋; 쵋; ) HANGUL SYLLABLE CWAELB
+CD4C;CD4C;110E 116B 11B3;CD4C;110E 116B 11B3; # (쵌; 쵌; 쵌; 쵌; 쵌; ) HANGUL SYLLABLE CWAELS
+CD4D;CD4D;110E 116B 11B4;CD4D;110E 116B 11B4; # (쵍; 쵍; 쵍; 쵍; 쵍; ) HANGUL SYLLABLE CWAELT
+CD4E;CD4E;110E 116B 11B5;CD4E;110E 116B 11B5; # (쵎; 쵎; 쵎; 쵎; 쵎; ) HANGUL SYLLABLE CWAELP
+CD4F;CD4F;110E 116B 11B6;CD4F;110E 116B 11B6; # (쵏; 쵏; 쵏; 쵏; 쵏; ) HANGUL SYLLABLE CWAELH
+CD50;CD50;110E 116B 11B7;CD50;110E 116B 11B7; # (쵐; 쵐; 쵐; 쵐; 쵐; ) HANGUL SYLLABLE CWAEM
+CD51;CD51;110E 116B 11B8;CD51;110E 116B 11B8; # (쵑; 쵑; 쵑; 쵑; 쵑; ) HANGUL SYLLABLE CWAEB
+CD52;CD52;110E 116B 11B9;CD52;110E 116B 11B9; # (쵒; 쵒; 쵒; 쵒; 쵒; ) HANGUL SYLLABLE CWAEBS
+CD53;CD53;110E 116B 11BA;CD53;110E 116B 11BA; # (쵓; 쵓; 쵓; 쵓; 쵓; ) HANGUL SYLLABLE CWAES
+CD54;CD54;110E 116B 11BB;CD54;110E 116B 11BB; # (쵔; 쵔; 쵔; 쵔; 쵔; ) HANGUL SYLLABLE CWAESS
+CD55;CD55;110E 116B 11BC;CD55;110E 116B 11BC; # (쵕; 쵕; 쵕; 쵕; 쵕; ) HANGUL SYLLABLE CWAENG
+CD56;CD56;110E 116B 11BD;CD56;110E 116B 11BD; # (쵖; 쵖; 쵖; 쵖; 쵖; ) HANGUL SYLLABLE CWAEJ
+CD57;CD57;110E 116B 11BE;CD57;110E 116B 11BE; # (쵗; 쵗; 쵗; 쵗; 쵗; ) HANGUL SYLLABLE CWAEC
+CD58;CD58;110E 116B 11BF;CD58;110E 116B 11BF; # (쵘; 쵘; 쵘; 쵘; 쵘; ) HANGUL SYLLABLE CWAEK
+CD59;CD59;110E 116B 11C0;CD59;110E 116B 11C0; # (쵙; 쵙; 쵙; 쵙; 쵙; ) HANGUL SYLLABLE CWAET
+CD5A;CD5A;110E 116B 11C1;CD5A;110E 116B 11C1; # (쵚; 쵚; 쵚; 쵚; 쵚; ) HANGUL SYLLABLE CWAEP
+CD5B;CD5B;110E 116B 11C2;CD5B;110E 116B 11C2; # (쵛; 쵛; 쵛; 쵛; 쵛; ) HANGUL SYLLABLE CWAEH
+CD5C;CD5C;110E 116C;CD5C;110E 116C; # (최; 최; 최; 최; 최; ) HANGUL SYLLABLE COE
+CD5D;CD5D;110E 116C 11A8;CD5D;110E 116C 11A8; # (쵝; 쵝; 쵝; 쵝; 쵝; ) HANGUL SYLLABLE COEG
+CD5E;CD5E;110E 116C 11A9;CD5E;110E 116C 11A9; # (쵞; 쵞; 쵞; 쵞; 쵞; ) HANGUL SYLLABLE COEGG
+CD5F;CD5F;110E 116C 11AA;CD5F;110E 116C 11AA; # (쵟; 쵟; 쵟; 쵟; 쵟; ) HANGUL SYLLABLE COEGS
+CD60;CD60;110E 116C 11AB;CD60;110E 116C 11AB; # (쵠; 쵠; 쵠; 쵠; 쵠; ) HANGUL SYLLABLE COEN
+CD61;CD61;110E 116C 11AC;CD61;110E 116C 11AC; # (쵡; 쵡; 쵡; 쵡; 쵡; ) HANGUL SYLLABLE COENJ
+CD62;CD62;110E 116C 11AD;CD62;110E 116C 11AD; # (쵢; 쵢; 쵢; 쵢; 쵢; ) HANGUL SYLLABLE COENH
+CD63;CD63;110E 116C 11AE;CD63;110E 116C 11AE; # (쵣; 쵣; 쵣; 쵣; 쵣; ) HANGUL SYLLABLE COED
+CD64;CD64;110E 116C 11AF;CD64;110E 116C 11AF; # (쵤; 쵤; 쵤; 쵤; 쵤; ) HANGUL SYLLABLE COEL
+CD65;CD65;110E 116C 11B0;CD65;110E 116C 11B0; # (쵥; 쵥; 쵥; 쵥; 쵥; ) HANGUL SYLLABLE COELG
+CD66;CD66;110E 116C 11B1;CD66;110E 116C 11B1; # (쵦; 쵦; 쵦; 쵦; 쵦; ) HANGUL SYLLABLE COELM
+CD67;CD67;110E 116C 11B2;CD67;110E 116C 11B2; # (쵧; 쵧; 쵧; 쵧; 쵧; ) HANGUL SYLLABLE COELB
+CD68;CD68;110E 116C 11B3;CD68;110E 116C 11B3; # (쵨; 쵨; 쵨; 쵨; 쵨; ) HANGUL SYLLABLE COELS
+CD69;CD69;110E 116C 11B4;CD69;110E 116C 11B4; # (쵩; 쵩; 쵩; 쵩; 쵩; ) HANGUL SYLLABLE COELT
+CD6A;CD6A;110E 116C 11B5;CD6A;110E 116C 11B5; # (쵪; 쵪; 쵪; 쵪; 쵪; ) HANGUL SYLLABLE COELP
+CD6B;CD6B;110E 116C 11B6;CD6B;110E 116C 11B6; # (쵫; 쵫; 쵫; 쵫; 쵫; ) HANGUL SYLLABLE COELH
+CD6C;CD6C;110E 116C 11B7;CD6C;110E 116C 11B7; # (쵬; 쵬; 쵬; 쵬; 쵬; ) HANGUL SYLLABLE COEM
+CD6D;CD6D;110E 116C 11B8;CD6D;110E 116C 11B8; # (쵭; 쵭; 쵭; 쵭; 쵭; ) HANGUL SYLLABLE COEB
+CD6E;CD6E;110E 116C 11B9;CD6E;110E 116C 11B9; # (쵮; 쵮; 쵮; 쵮; 쵮; ) HANGUL SYLLABLE COEBS
+CD6F;CD6F;110E 116C 11BA;CD6F;110E 116C 11BA; # (쵯; 쵯; 쵯; 쵯; 쵯; ) HANGUL SYLLABLE COES
+CD70;CD70;110E 116C 11BB;CD70;110E 116C 11BB; # (쵰; 쵰; 쵰; 쵰; 쵰; ) HANGUL SYLLABLE COESS
+CD71;CD71;110E 116C 11BC;CD71;110E 116C 11BC; # (쵱; 쵱; 쵱; 쵱; 쵱; ) HANGUL SYLLABLE COENG
+CD72;CD72;110E 116C 11BD;CD72;110E 116C 11BD; # (쵲; 쵲; 쵲; 쵲; 쵲; ) HANGUL SYLLABLE COEJ
+CD73;CD73;110E 116C 11BE;CD73;110E 116C 11BE; # (쵳; 쵳; 쵳; 쵳; 쵳; ) HANGUL SYLLABLE COEC
+CD74;CD74;110E 116C 11BF;CD74;110E 116C 11BF; # (쵴; 쵴; 쵴; 쵴; 쵴; ) HANGUL SYLLABLE COEK
+CD75;CD75;110E 116C 11C0;CD75;110E 116C 11C0; # (쵵; 쵵; 쵵; 쵵; 쵵; ) HANGUL SYLLABLE COET
+CD76;CD76;110E 116C 11C1;CD76;110E 116C 11C1; # (쵶; 쵶; 쵶; 쵶; 쵶; ) HANGUL SYLLABLE COEP
+CD77;CD77;110E 116C 11C2;CD77;110E 116C 11C2; # (쵷; 쵷; 쵷; 쵷; 쵷; ) HANGUL SYLLABLE COEH
+CD78;CD78;110E 116D;CD78;110E 116D; # (쵸; 쵸; 쵸; 쵸; 쵸; ) HANGUL SYLLABLE CYO
+CD79;CD79;110E 116D 11A8;CD79;110E 116D 11A8; # (쵹; 쵹; 쵹; 쵹; 쵹; ) HANGUL SYLLABLE CYOG
+CD7A;CD7A;110E 116D 11A9;CD7A;110E 116D 11A9; # (쵺; 쵺; 쵺; 쵺; 쵺; ) HANGUL SYLLABLE CYOGG
+CD7B;CD7B;110E 116D 11AA;CD7B;110E 116D 11AA; # (쵻; 쵻; 쵻; 쵻; 쵻; ) HANGUL SYLLABLE CYOGS
+CD7C;CD7C;110E 116D 11AB;CD7C;110E 116D 11AB; # (쵼; 쵼; 쵼; 쵼; 쵼; ) HANGUL SYLLABLE CYON
+CD7D;CD7D;110E 116D 11AC;CD7D;110E 116D 11AC; # (쵽; 쵽; 쵽; 쵽; 쵽; ) HANGUL SYLLABLE CYONJ
+CD7E;CD7E;110E 116D 11AD;CD7E;110E 116D 11AD; # (쵾; 쵾; 쵾; 쵾; 쵾; ) HANGUL SYLLABLE CYONH
+CD7F;CD7F;110E 116D 11AE;CD7F;110E 116D 11AE; # (쵿; 쵿; 쵿; 쵿; 쵿; ) HANGUL SYLLABLE CYOD
+CD80;CD80;110E 116D 11AF;CD80;110E 116D 11AF; # (춀; 춀; 춀; 춀; 춀; ) HANGUL SYLLABLE CYOL
+CD81;CD81;110E 116D 11B0;CD81;110E 116D 11B0; # (춁; 춁; 춁; 춁; 춁; ) HANGUL SYLLABLE CYOLG
+CD82;CD82;110E 116D 11B1;CD82;110E 116D 11B1; # (춂; 춂; 춂; 춂; 춂; ) HANGUL SYLLABLE CYOLM
+CD83;CD83;110E 116D 11B2;CD83;110E 116D 11B2; # (춃; 춃; 춃; 춃; 춃; ) HANGUL SYLLABLE CYOLB
+CD84;CD84;110E 116D 11B3;CD84;110E 116D 11B3; # (춄; 춄; 춄; 춄; 춄; ) HANGUL SYLLABLE CYOLS
+CD85;CD85;110E 116D 11B4;CD85;110E 116D 11B4; # (춅; 춅; 춅; 춅; 춅; ) HANGUL SYLLABLE CYOLT
+CD86;CD86;110E 116D 11B5;CD86;110E 116D 11B5; # (춆; 춆; 춆; 춆; 춆; ) HANGUL SYLLABLE CYOLP
+CD87;CD87;110E 116D 11B6;CD87;110E 116D 11B6; # (춇; 춇; 춇; 춇; 춇; ) HANGUL SYLLABLE CYOLH
+CD88;CD88;110E 116D 11B7;CD88;110E 116D 11B7; # (춈; 춈; 춈; 춈; 춈; ) HANGUL SYLLABLE CYOM
+CD89;CD89;110E 116D 11B8;CD89;110E 116D 11B8; # (춉; 춉; 춉; 춉; 춉; ) HANGUL SYLLABLE CYOB
+CD8A;CD8A;110E 116D 11B9;CD8A;110E 116D 11B9; # (춊; 춊; 춊; 춊; 춊; ) HANGUL SYLLABLE CYOBS
+CD8B;CD8B;110E 116D 11BA;CD8B;110E 116D 11BA; # (춋; 춋; 춋; 춋; 춋; ) HANGUL SYLLABLE CYOS
+CD8C;CD8C;110E 116D 11BB;CD8C;110E 116D 11BB; # (춌; 춌; 춌; 춌; 춌; ) HANGUL SYLLABLE CYOSS
+CD8D;CD8D;110E 116D 11BC;CD8D;110E 116D 11BC; # (춍; 춍; 춍; 춍; 춍; ) HANGUL SYLLABLE CYONG
+CD8E;CD8E;110E 116D 11BD;CD8E;110E 116D 11BD; # (춎; 춎; 춎; 춎; 춎; ) HANGUL SYLLABLE CYOJ
+CD8F;CD8F;110E 116D 11BE;CD8F;110E 116D 11BE; # (춏; 춏; 춏; 춏; 춏; ) HANGUL SYLLABLE CYOC
+CD90;CD90;110E 116D 11BF;CD90;110E 116D 11BF; # (춐; 춐; 춐; 춐; 춐; ) HANGUL SYLLABLE CYOK
+CD91;CD91;110E 116D 11C0;CD91;110E 116D 11C0; # (춑; 춑; 춑; 춑; 춑; ) HANGUL SYLLABLE CYOT
+CD92;CD92;110E 116D 11C1;CD92;110E 116D 11C1; # (춒; 춒; 춒; 춒; 춒; ) HANGUL SYLLABLE CYOP
+CD93;CD93;110E 116D 11C2;CD93;110E 116D 11C2; # (춓; 춓; 춓; 춓; 춓; ) HANGUL SYLLABLE CYOH
+CD94;CD94;110E 116E;CD94;110E 116E; # (추; 추; 추; 추; 추; ) HANGUL SYLLABLE CU
+CD95;CD95;110E 116E 11A8;CD95;110E 116E 11A8; # (축; 축; 축; 축; 축; ) HANGUL SYLLABLE CUG
+CD96;CD96;110E 116E 11A9;CD96;110E 116E 11A9; # (춖; 춖; 춖; 춖; 춖; ) HANGUL SYLLABLE CUGG
+CD97;CD97;110E 116E 11AA;CD97;110E 116E 11AA; # (춗; 춗; 춗; 춗; 춗; ) HANGUL SYLLABLE CUGS
+CD98;CD98;110E 116E 11AB;CD98;110E 116E 11AB; # (춘; 춘; 춘; 춘; 춘; ) HANGUL SYLLABLE CUN
+CD99;CD99;110E 116E 11AC;CD99;110E 116E 11AC; # (춙; 춙; 춙; 춙; 춙; ) HANGUL SYLLABLE CUNJ
+CD9A;CD9A;110E 116E 11AD;CD9A;110E 116E 11AD; # (춚; 춚; 춚; 춚; 춚; ) HANGUL SYLLABLE CUNH
+CD9B;CD9B;110E 116E 11AE;CD9B;110E 116E 11AE; # (춛; 춛; 춛; 춛; 춛; ) HANGUL SYLLABLE CUD
+CD9C;CD9C;110E 116E 11AF;CD9C;110E 116E 11AF; # (출; 출; 출; 출; 출; ) HANGUL SYLLABLE CUL
+CD9D;CD9D;110E 116E 11B0;CD9D;110E 116E 11B0; # (춝; 춝; 춝; 춝; 춝; ) HANGUL SYLLABLE CULG
+CD9E;CD9E;110E 116E 11B1;CD9E;110E 116E 11B1; # (춞; 춞; 춞; 춞; 춞; ) HANGUL SYLLABLE CULM
+CD9F;CD9F;110E 116E 11B2;CD9F;110E 116E 11B2; # (춟; 춟; 춟; 춟; 춟; ) HANGUL SYLLABLE CULB
+CDA0;CDA0;110E 116E 11B3;CDA0;110E 116E 11B3; # (춠; 춠; 춠; 춠; 춠; ) HANGUL SYLLABLE CULS
+CDA1;CDA1;110E 116E 11B4;CDA1;110E 116E 11B4; # (춡; 춡; 춡; 춡; 춡; ) HANGUL SYLLABLE CULT
+CDA2;CDA2;110E 116E 11B5;CDA2;110E 116E 11B5; # (춢; 춢; 춢; 춢; 춢; ) HANGUL SYLLABLE CULP
+CDA3;CDA3;110E 116E 11B6;CDA3;110E 116E 11B6; # (춣; 춣; 춣; 춣; 춣; ) HANGUL SYLLABLE CULH
+CDA4;CDA4;110E 116E 11B7;CDA4;110E 116E 11B7; # (춤; 춤; 춤; 춤; 춤; ) HANGUL SYLLABLE CUM
+CDA5;CDA5;110E 116E 11B8;CDA5;110E 116E 11B8; # (춥; 춥; 춥; 춥; 춥; ) HANGUL SYLLABLE CUB
+CDA6;CDA6;110E 116E 11B9;CDA6;110E 116E 11B9; # (춦; 춦; 춦; 춦; 춦; ) HANGUL SYLLABLE CUBS
+CDA7;CDA7;110E 116E 11BA;CDA7;110E 116E 11BA; # (춧; 춧; 춧; 춧; 춧; ) HANGUL SYLLABLE CUS
+CDA8;CDA8;110E 116E 11BB;CDA8;110E 116E 11BB; # (춨; 춨; 춨; 춨; 춨; ) HANGUL SYLLABLE CUSS
+CDA9;CDA9;110E 116E 11BC;CDA9;110E 116E 11BC; # (충; 충; 충; 충; 충; ) HANGUL SYLLABLE CUNG
+CDAA;CDAA;110E 116E 11BD;CDAA;110E 116E 11BD; # (춪; 춪; 춪; 춪; 춪; ) HANGUL SYLLABLE CUJ
+CDAB;CDAB;110E 116E 11BE;CDAB;110E 116E 11BE; # (춫; 춫; 춫; 춫; 춫; ) HANGUL SYLLABLE CUC
+CDAC;CDAC;110E 116E 11BF;CDAC;110E 116E 11BF; # (춬; 춬; 춬; 춬; 춬; ) HANGUL SYLLABLE CUK
+CDAD;CDAD;110E 116E 11C0;CDAD;110E 116E 11C0; # (춭; 춭; 춭; 춭; 춭; ) HANGUL SYLLABLE CUT
+CDAE;CDAE;110E 116E 11C1;CDAE;110E 116E 11C1; # (춮; 춮; 춮; 춮; 춮; ) HANGUL SYLLABLE CUP
+CDAF;CDAF;110E 116E 11C2;CDAF;110E 116E 11C2; # (춯; 춯; 춯; 춯; 춯; ) HANGUL SYLLABLE CUH
+CDB0;CDB0;110E 116F;CDB0;110E 116F; # (춰; 춰; 춰; 춰; 춰; ) HANGUL SYLLABLE CWEO
+CDB1;CDB1;110E 116F 11A8;CDB1;110E 116F 11A8; # (춱; 춱; 춱; 춱; 춱; ) HANGUL SYLLABLE CWEOG
+CDB2;CDB2;110E 116F 11A9;CDB2;110E 116F 11A9; # (춲; 춲; 춲; 춲; 춲; ) HANGUL SYLLABLE CWEOGG
+CDB3;CDB3;110E 116F 11AA;CDB3;110E 116F 11AA; # (춳; 춳; 춳; 춳; 춳; ) HANGUL SYLLABLE CWEOGS
+CDB4;CDB4;110E 116F 11AB;CDB4;110E 116F 11AB; # (춴; 춴; 춴; 춴; 춴; ) HANGUL SYLLABLE CWEON
+CDB5;CDB5;110E 116F 11AC;CDB5;110E 116F 11AC; # (춵; 춵; 춵; 춵; 춵; ) HANGUL SYLLABLE CWEONJ
+CDB6;CDB6;110E 116F 11AD;CDB6;110E 116F 11AD; # (춶; 춶; 춶; 춶; 춶; ) HANGUL SYLLABLE CWEONH
+CDB7;CDB7;110E 116F 11AE;CDB7;110E 116F 11AE; # (춷; 춷; 춷; 춷; 춷; ) HANGUL SYLLABLE CWEOD
+CDB8;CDB8;110E 116F 11AF;CDB8;110E 116F 11AF; # (춸; 춸; 춸; 춸; 춸; ) HANGUL SYLLABLE CWEOL
+CDB9;CDB9;110E 116F 11B0;CDB9;110E 116F 11B0; # (춹; 춹; 춹; 춹; 춹; ) HANGUL SYLLABLE CWEOLG
+CDBA;CDBA;110E 116F 11B1;CDBA;110E 116F 11B1; # (춺; 춺; 춺; 춺; 춺; ) HANGUL SYLLABLE CWEOLM
+CDBB;CDBB;110E 116F 11B2;CDBB;110E 116F 11B2; # (춻; 춻; 춻; 춻; 춻; ) HANGUL SYLLABLE CWEOLB
+CDBC;CDBC;110E 116F 11B3;CDBC;110E 116F 11B3; # (춼; 춼; 춼; 춼; 춼; ) HANGUL SYLLABLE CWEOLS
+CDBD;CDBD;110E 116F 11B4;CDBD;110E 116F 11B4; # (춽; 춽; 춽; 춽; 춽; ) HANGUL SYLLABLE CWEOLT
+CDBE;CDBE;110E 116F 11B5;CDBE;110E 116F 11B5; # (춾; 춾; 춾; 춾; 춾; ) HANGUL SYLLABLE CWEOLP
+CDBF;CDBF;110E 116F 11B6;CDBF;110E 116F 11B6; # (춿; 춿; 춿; 춿; 춿; ) HANGUL SYLLABLE CWEOLH
+CDC0;CDC0;110E 116F 11B7;CDC0;110E 116F 11B7; # (췀; 췀; 췀; 췀; 췀; ) HANGUL SYLLABLE CWEOM
+CDC1;CDC1;110E 116F 11B8;CDC1;110E 116F 11B8; # (췁; 췁; 췁; 췁; 췁; ) HANGUL SYLLABLE CWEOB
+CDC2;CDC2;110E 116F 11B9;CDC2;110E 116F 11B9; # (췂; 췂; 췂; 췂; 췂; ) HANGUL SYLLABLE CWEOBS
+CDC3;CDC3;110E 116F 11BA;CDC3;110E 116F 11BA; # (췃; 췃; 췃; 췃; 췃; ) HANGUL SYLLABLE CWEOS
+CDC4;CDC4;110E 116F 11BB;CDC4;110E 116F 11BB; # (췄; 췄; 췄; 췄; 췄; ) HANGUL SYLLABLE CWEOSS
+CDC5;CDC5;110E 116F 11BC;CDC5;110E 116F 11BC; # (췅; 췅; 췅; 췅; 췅; ) HANGUL SYLLABLE CWEONG
+CDC6;CDC6;110E 116F 11BD;CDC6;110E 116F 11BD; # (췆; 췆; 췆; 췆; 췆; ) HANGUL SYLLABLE CWEOJ
+CDC7;CDC7;110E 116F 11BE;CDC7;110E 116F 11BE; # (췇; 췇; 췇; 췇; 췇; ) HANGUL SYLLABLE CWEOC
+CDC8;CDC8;110E 116F 11BF;CDC8;110E 116F 11BF; # (췈; 췈; 췈; 췈; 췈; ) HANGUL SYLLABLE CWEOK
+CDC9;CDC9;110E 116F 11C0;CDC9;110E 116F 11C0; # (췉; 췉; 췉; 췉; 췉; ) HANGUL SYLLABLE CWEOT
+CDCA;CDCA;110E 116F 11C1;CDCA;110E 116F 11C1; # (췊; 췊; 췊; 췊; 췊; ) HANGUL SYLLABLE CWEOP
+CDCB;CDCB;110E 116F 11C2;CDCB;110E 116F 11C2; # (췋; 췋; 췋; 췋; 췋; ) HANGUL SYLLABLE CWEOH
+CDCC;CDCC;110E 1170;CDCC;110E 1170; # (췌; 췌; 췌; 췌; 췌; ) HANGUL SYLLABLE CWE
+CDCD;CDCD;110E 1170 11A8;CDCD;110E 1170 11A8; # (췍; 췍; 췍; 췍; 췍; ) HANGUL SYLLABLE CWEG
+CDCE;CDCE;110E 1170 11A9;CDCE;110E 1170 11A9; # (췎; 췎; 췎; 췎; 췎; ) HANGUL SYLLABLE CWEGG
+CDCF;CDCF;110E 1170 11AA;CDCF;110E 1170 11AA; # (췏; 췏; 췏; 췏; 췏; ) HANGUL SYLLABLE CWEGS
+CDD0;CDD0;110E 1170 11AB;CDD0;110E 1170 11AB; # (췐; 췐; 췐; 췐; 췐; ) HANGUL SYLLABLE CWEN
+CDD1;CDD1;110E 1170 11AC;CDD1;110E 1170 11AC; # (췑; 췑; 췑; 췑; 췑; ) HANGUL SYLLABLE CWENJ
+CDD2;CDD2;110E 1170 11AD;CDD2;110E 1170 11AD; # (췒; 췒; 췒; 췒; 췒; ) HANGUL SYLLABLE CWENH
+CDD3;CDD3;110E 1170 11AE;CDD3;110E 1170 11AE; # (췓; 췓; 췓; 췓; 췓; ) HANGUL SYLLABLE CWED
+CDD4;CDD4;110E 1170 11AF;CDD4;110E 1170 11AF; # (췔; 췔; 췔; 췔; 췔; ) HANGUL SYLLABLE CWEL
+CDD5;CDD5;110E 1170 11B0;CDD5;110E 1170 11B0; # (췕; 췕; 췕; 췕; 췕; ) HANGUL SYLLABLE CWELG
+CDD6;CDD6;110E 1170 11B1;CDD6;110E 1170 11B1; # (췖; 췖; 췖; 췖; 췖; ) HANGUL SYLLABLE CWELM
+CDD7;CDD7;110E 1170 11B2;CDD7;110E 1170 11B2; # (췗; 췗; 췗; 췗; 췗; ) HANGUL SYLLABLE CWELB
+CDD8;CDD8;110E 1170 11B3;CDD8;110E 1170 11B3; # (췘; 췘; 췘; 췘; 췘; ) HANGUL SYLLABLE CWELS
+CDD9;CDD9;110E 1170 11B4;CDD9;110E 1170 11B4; # (췙; 췙; 췙; 췙; 췙; ) HANGUL SYLLABLE CWELT
+CDDA;CDDA;110E 1170 11B5;CDDA;110E 1170 11B5; # (췚; 췚; 췚; 췚; 췚; ) HANGUL SYLLABLE CWELP
+CDDB;CDDB;110E 1170 11B6;CDDB;110E 1170 11B6; # (췛; 췛; 췛; 췛; 췛; ) HANGUL SYLLABLE CWELH
+CDDC;CDDC;110E 1170 11B7;CDDC;110E 1170 11B7; # (췜; 췜; 췜; 췜; 췜; ) HANGUL SYLLABLE CWEM
+CDDD;CDDD;110E 1170 11B8;CDDD;110E 1170 11B8; # (췝; 췝; 췝; 췝; 췝; ) HANGUL SYLLABLE CWEB
+CDDE;CDDE;110E 1170 11B9;CDDE;110E 1170 11B9; # (췞; 췞; 췞; 췞; 췞; ) HANGUL SYLLABLE CWEBS
+CDDF;CDDF;110E 1170 11BA;CDDF;110E 1170 11BA; # (췟; 췟; 췟; 췟; 췟; ) HANGUL SYLLABLE CWES
+CDE0;CDE0;110E 1170 11BB;CDE0;110E 1170 11BB; # (췠; 췠; 췠; 췠; 췠; ) HANGUL SYLLABLE CWESS
+CDE1;CDE1;110E 1170 11BC;CDE1;110E 1170 11BC; # (췡; 췡; 췡; 췡; 췡; ) HANGUL SYLLABLE CWENG
+CDE2;CDE2;110E 1170 11BD;CDE2;110E 1170 11BD; # (췢; 췢; 췢; 췢; 췢; ) HANGUL SYLLABLE CWEJ
+CDE3;CDE3;110E 1170 11BE;CDE3;110E 1170 11BE; # (췣; 췣; 췣; 췣; 췣; ) HANGUL SYLLABLE CWEC
+CDE4;CDE4;110E 1170 11BF;CDE4;110E 1170 11BF; # (췤; 췤; 췤; 췤; 췤; ) HANGUL SYLLABLE CWEK
+CDE5;CDE5;110E 1170 11C0;CDE5;110E 1170 11C0; # (췥; 췥; 췥; 췥; 췥; ) HANGUL SYLLABLE CWET
+CDE6;CDE6;110E 1170 11C1;CDE6;110E 1170 11C1; # (췦; 췦; 췦; 췦; 췦; ) HANGUL SYLLABLE CWEP
+CDE7;CDE7;110E 1170 11C2;CDE7;110E 1170 11C2; # (췧; 췧; 췧; 췧; 췧; ) HANGUL SYLLABLE CWEH
+CDE8;CDE8;110E 1171;CDE8;110E 1171; # (취; 취; 취; 취; 취; ) HANGUL SYLLABLE CWI
+CDE9;CDE9;110E 1171 11A8;CDE9;110E 1171 11A8; # (췩; 췩; 췩; 췩; 췩; ) HANGUL SYLLABLE CWIG
+CDEA;CDEA;110E 1171 11A9;CDEA;110E 1171 11A9; # (췪; 췪; 췪; 췪; 췪; ) HANGUL SYLLABLE CWIGG
+CDEB;CDEB;110E 1171 11AA;CDEB;110E 1171 11AA; # (췫; 췫; 췫; 췫; 췫; ) HANGUL SYLLABLE CWIGS
+CDEC;CDEC;110E 1171 11AB;CDEC;110E 1171 11AB; # (췬; 췬; 췬; 췬; 췬; ) HANGUL SYLLABLE CWIN
+CDED;CDED;110E 1171 11AC;CDED;110E 1171 11AC; # (췭; 췭; 췭; 췭; 췭; ) HANGUL SYLLABLE CWINJ
+CDEE;CDEE;110E 1171 11AD;CDEE;110E 1171 11AD; # (췮; 췮; 췮; 췮; 췮; ) HANGUL SYLLABLE CWINH
+CDEF;CDEF;110E 1171 11AE;CDEF;110E 1171 11AE; # (췯; 췯; 췯; 췯; 췯; ) HANGUL SYLLABLE CWID
+CDF0;CDF0;110E 1171 11AF;CDF0;110E 1171 11AF; # (췰; 췰; 췰; 췰; 췰; ) HANGUL SYLLABLE CWIL
+CDF1;CDF1;110E 1171 11B0;CDF1;110E 1171 11B0; # (췱; 췱; 췱; 췱; 췱; ) HANGUL SYLLABLE CWILG
+CDF2;CDF2;110E 1171 11B1;CDF2;110E 1171 11B1; # (췲; 췲; 췲; 췲; 췲; ) HANGUL SYLLABLE CWILM
+CDF3;CDF3;110E 1171 11B2;CDF3;110E 1171 11B2; # (췳; 췳; 췳; 췳; 췳; ) HANGUL SYLLABLE CWILB
+CDF4;CDF4;110E 1171 11B3;CDF4;110E 1171 11B3; # (췴; 췴; 췴; 췴; 췴; ) HANGUL SYLLABLE CWILS
+CDF5;CDF5;110E 1171 11B4;CDF5;110E 1171 11B4; # (췵; 췵; 췵; 췵; 췵; ) HANGUL SYLLABLE CWILT
+CDF6;CDF6;110E 1171 11B5;CDF6;110E 1171 11B5; # (췶; 췶; 췶; 췶; 췶; ) HANGUL SYLLABLE CWILP
+CDF7;CDF7;110E 1171 11B6;CDF7;110E 1171 11B6; # (췷; 췷; 췷; 췷; 췷; ) HANGUL SYLLABLE CWILH
+CDF8;CDF8;110E 1171 11B7;CDF8;110E 1171 11B7; # (췸; 췸; 췸; 췸; 췸; ) HANGUL SYLLABLE CWIM
+CDF9;CDF9;110E 1171 11B8;CDF9;110E 1171 11B8; # (췹; 췹; 췹; 췹; 췹; ) HANGUL SYLLABLE CWIB
+CDFA;CDFA;110E 1171 11B9;CDFA;110E 1171 11B9; # (췺; 췺; 췺; 췺; 췺; ) HANGUL SYLLABLE CWIBS
+CDFB;CDFB;110E 1171 11BA;CDFB;110E 1171 11BA; # (췻; 췻; 췻; 췻; 췻; ) HANGUL SYLLABLE CWIS
+CDFC;CDFC;110E 1171 11BB;CDFC;110E 1171 11BB; # (췼; 췼; 췼; 췼; 췼; ) HANGUL SYLLABLE CWISS
+CDFD;CDFD;110E 1171 11BC;CDFD;110E 1171 11BC; # (췽; 췽; 췽; 췽; 췽; ) HANGUL SYLLABLE CWING
+CDFE;CDFE;110E 1171 11BD;CDFE;110E 1171 11BD; # (췾; 췾; 췾; 췾; 췾; ) HANGUL SYLLABLE CWIJ
+CDFF;CDFF;110E 1171 11BE;CDFF;110E 1171 11BE; # (췿; 췿; 췿; 췿; 췿; ) HANGUL SYLLABLE CWIC
+CE00;CE00;110E 1171 11BF;CE00;110E 1171 11BF; # (츀; 츀; 츀; 츀; 츀; ) HANGUL SYLLABLE CWIK
+CE01;CE01;110E 1171 11C0;CE01;110E 1171 11C0; # (츁; 츁; 츁; 츁; 츁; ) HANGUL SYLLABLE CWIT
+CE02;CE02;110E 1171 11C1;CE02;110E 1171 11C1; # (츂; 츂; 츂; 츂; 츂; ) HANGUL SYLLABLE CWIP
+CE03;CE03;110E 1171 11C2;CE03;110E 1171 11C2; # (츃; 츃; 츃; 츃; 츃; ) HANGUL SYLLABLE CWIH
+CE04;CE04;110E 1172;CE04;110E 1172; # (츄; 츄; 츄; 츄; 츄; ) HANGUL SYLLABLE CYU
+CE05;CE05;110E 1172 11A8;CE05;110E 1172 11A8; # (츅; 츅; 츅; 츅; 츅; ) HANGUL SYLLABLE CYUG
+CE06;CE06;110E 1172 11A9;CE06;110E 1172 11A9; # (츆; 츆; 츆; 츆; 츆; ) HANGUL SYLLABLE CYUGG
+CE07;CE07;110E 1172 11AA;CE07;110E 1172 11AA; # (츇; 츇; 츇; 츇; 츇; ) HANGUL SYLLABLE CYUGS
+CE08;CE08;110E 1172 11AB;CE08;110E 1172 11AB; # (츈; 츈; 츈; 츈; 츈; ) HANGUL SYLLABLE CYUN
+CE09;CE09;110E 1172 11AC;CE09;110E 1172 11AC; # (츉; 츉; 츉; 츉; 츉; ) HANGUL SYLLABLE CYUNJ
+CE0A;CE0A;110E 1172 11AD;CE0A;110E 1172 11AD; # (츊; 츊; 츊; 츊; 츊; ) HANGUL SYLLABLE CYUNH
+CE0B;CE0B;110E 1172 11AE;CE0B;110E 1172 11AE; # (츋; 츋; 츋; 츋; 츋; ) HANGUL SYLLABLE CYUD
+CE0C;CE0C;110E 1172 11AF;CE0C;110E 1172 11AF; # (츌; 츌; 츌; 츌; 츌; ) HANGUL SYLLABLE CYUL
+CE0D;CE0D;110E 1172 11B0;CE0D;110E 1172 11B0; # (츍; 츍; 츍; 츍; 츍; ) HANGUL SYLLABLE CYULG
+CE0E;CE0E;110E 1172 11B1;CE0E;110E 1172 11B1; # (츎; 츎; 츎; 츎; 츎; ) HANGUL SYLLABLE CYULM
+CE0F;CE0F;110E 1172 11B2;CE0F;110E 1172 11B2; # (츏; 츏; 츏; 츏; 츏; ) HANGUL SYLLABLE CYULB
+CE10;CE10;110E 1172 11B3;CE10;110E 1172 11B3; # (츐; 츐; 츐; 츐; 츐; ) HANGUL SYLLABLE CYULS
+CE11;CE11;110E 1172 11B4;CE11;110E 1172 11B4; # (츑; 츑; 츑; 츑; 츑; ) HANGUL SYLLABLE CYULT
+CE12;CE12;110E 1172 11B5;CE12;110E 1172 11B5; # (츒; 츒; 츒; 츒; 츒; ) HANGUL SYLLABLE CYULP
+CE13;CE13;110E 1172 11B6;CE13;110E 1172 11B6; # (츓; 츓; 츓; 츓; 츓; ) HANGUL SYLLABLE CYULH
+CE14;CE14;110E 1172 11B7;CE14;110E 1172 11B7; # (츔; 츔; 츔; 츔; 츔; ) HANGUL SYLLABLE CYUM
+CE15;CE15;110E 1172 11B8;CE15;110E 1172 11B8; # (츕; 츕; 츕; 츕; 츕; ) HANGUL SYLLABLE CYUB
+CE16;CE16;110E 1172 11B9;CE16;110E 1172 11B9; # (츖; 츖; 츖; 츖; 츖; ) HANGUL SYLLABLE CYUBS
+CE17;CE17;110E 1172 11BA;CE17;110E 1172 11BA; # (츗; 츗; 츗; 츗; 츗; ) HANGUL SYLLABLE CYUS
+CE18;CE18;110E 1172 11BB;CE18;110E 1172 11BB; # (츘; 츘; 츘; 츘; 츘; ) HANGUL SYLLABLE CYUSS
+CE19;CE19;110E 1172 11BC;CE19;110E 1172 11BC; # (츙; 츙; 츙; 츙; 츙; ) HANGUL SYLLABLE CYUNG
+CE1A;CE1A;110E 1172 11BD;CE1A;110E 1172 11BD; # (츚; 츚; 츚; 츚; 츚; ) HANGUL SYLLABLE CYUJ
+CE1B;CE1B;110E 1172 11BE;CE1B;110E 1172 11BE; # (츛; 츛; 츛; 츛; 츛; ) HANGUL SYLLABLE CYUC
+CE1C;CE1C;110E 1172 11BF;CE1C;110E 1172 11BF; # (츜; 츜; 츜; 츜; 츜; ) HANGUL SYLLABLE CYUK
+CE1D;CE1D;110E 1172 11C0;CE1D;110E 1172 11C0; # (츝; 츝; 츝; 츝; 츝; ) HANGUL SYLLABLE CYUT
+CE1E;CE1E;110E 1172 11C1;CE1E;110E 1172 11C1; # (츞; 츞; 츞; 츞; 츞; ) HANGUL SYLLABLE CYUP
+CE1F;CE1F;110E 1172 11C2;CE1F;110E 1172 11C2; # (츟; 츟; 츟; 츟; 츟; ) HANGUL SYLLABLE CYUH
+CE20;CE20;110E 1173;CE20;110E 1173; # (츠; 츠; 츠; 츠; 츠; ) HANGUL SYLLABLE CEU
+CE21;CE21;110E 1173 11A8;CE21;110E 1173 11A8; # (측; 측; 측; 측; 측; ) HANGUL SYLLABLE CEUG
+CE22;CE22;110E 1173 11A9;CE22;110E 1173 11A9; # (츢; 츢; 츢; 츢; 츢; ) HANGUL SYLLABLE CEUGG
+CE23;CE23;110E 1173 11AA;CE23;110E 1173 11AA; # (츣; 츣; 츣; 츣; 츣; ) HANGUL SYLLABLE CEUGS
+CE24;CE24;110E 1173 11AB;CE24;110E 1173 11AB; # (츤; 츤; 츤; 츤; 츤; ) HANGUL SYLLABLE CEUN
+CE25;CE25;110E 1173 11AC;CE25;110E 1173 11AC; # (츥; 츥; 츥; 츥; 츥; ) HANGUL SYLLABLE CEUNJ
+CE26;CE26;110E 1173 11AD;CE26;110E 1173 11AD; # (츦; 츦; 츦; 츦; 츦; ) HANGUL SYLLABLE CEUNH
+CE27;CE27;110E 1173 11AE;CE27;110E 1173 11AE; # (츧; 츧; 츧; 츧; 츧; ) HANGUL SYLLABLE CEUD
+CE28;CE28;110E 1173 11AF;CE28;110E 1173 11AF; # (츨; 츨; 츨; 츨; 츨; ) HANGUL SYLLABLE CEUL
+CE29;CE29;110E 1173 11B0;CE29;110E 1173 11B0; # (츩; 츩; 츩; 츩; 츩; ) HANGUL SYLLABLE CEULG
+CE2A;CE2A;110E 1173 11B1;CE2A;110E 1173 11B1; # (츪; 츪; 츪; 츪; 츪; ) HANGUL SYLLABLE CEULM
+CE2B;CE2B;110E 1173 11B2;CE2B;110E 1173 11B2; # (츫; 츫; 츫; 츫; 츫; ) HANGUL SYLLABLE CEULB
+CE2C;CE2C;110E 1173 11B3;CE2C;110E 1173 11B3; # (츬; 츬; 츬; 츬; 츬; ) HANGUL SYLLABLE CEULS
+CE2D;CE2D;110E 1173 11B4;CE2D;110E 1173 11B4; # (츭; 츭; 츭; 츭; 츭; ) HANGUL SYLLABLE CEULT
+CE2E;CE2E;110E 1173 11B5;CE2E;110E 1173 11B5; # (츮; 츮; 츮; 츮; 츮; ) HANGUL SYLLABLE CEULP
+CE2F;CE2F;110E 1173 11B6;CE2F;110E 1173 11B6; # (츯; 츯; 츯; 츯; 츯; ) HANGUL SYLLABLE CEULH
+CE30;CE30;110E 1173 11B7;CE30;110E 1173 11B7; # (츰; 츰; 츰; 츰; 츰; ) HANGUL SYLLABLE CEUM
+CE31;CE31;110E 1173 11B8;CE31;110E 1173 11B8; # (츱; 츱; 츱; 츱; 츱; ) HANGUL SYLLABLE CEUB
+CE32;CE32;110E 1173 11B9;CE32;110E 1173 11B9; # (츲; 츲; 츲; 츲; 츲; ) HANGUL SYLLABLE CEUBS
+CE33;CE33;110E 1173 11BA;CE33;110E 1173 11BA; # (츳; 츳; 츳; 츳; 츳; ) HANGUL SYLLABLE CEUS
+CE34;CE34;110E 1173 11BB;CE34;110E 1173 11BB; # (츴; 츴; 츴; 츴; 츴; ) HANGUL SYLLABLE CEUSS
+CE35;CE35;110E 1173 11BC;CE35;110E 1173 11BC; # (층; 층; 층; 층; 층; ) HANGUL SYLLABLE CEUNG
+CE36;CE36;110E 1173 11BD;CE36;110E 1173 11BD; # (츶; 츶; 츶; 츶; 츶; ) HANGUL SYLLABLE CEUJ
+CE37;CE37;110E 1173 11BE;CE37;110E 1173 11BE; # (츷; 츷; 츷; 츷; 츷; ) HANGUL SYLLABLE CEUC
+CE38;CE38;110E 1173 11BF;CE38;110E 1173 11BF; # (츸; 츸; 츸; 츸; 츸; ) HANGUL SYLLABLE CEUK
+CE39;CE39;110E 1173 11C0;CE39;110E 1173 11C0; # (츹; 츹; 츹; 츹; 츹; ) HANGUL SYLLABLE CEUT
+CE3A;CE3A;110E 1173 11C1;CE3A;110E 1173 11C1; # (츺; 츺; 츺; 츺; 츺; ) HANGUL SYLLABLE CEUP
+CE3B;CE3B;110E 1173 11C2;CE3B;110E 1173 11C2; # (츻; 츻; 츻; 츻; 츻; ) HANGUL SYLLABLE CEUH
+CE3C;CE3C;110E 1174;CE3C;110E 1174; # (츼; 츼; 츼; 츼; 츼; ) HANGUL SYLLABLE CYI
+CE3D;CE3D;110E 1174 11A8;CE3D;110E 1174 11A8; # (츽; 츽; 츽; 츽; 츽; ) HANGUL SYLLABLE CYIG
+CE3E;CE3E;110E 1174 11A9;CE3E;110E 1174 11A9; # (츾; 츾; 츾; 츾; 츾; ) HANGUL SYLLABLE CYIGG
+CE3F;CE3F;110E 1174 11AA;CE3F;110E 1174 11AA; # (츿; 츿; 츿; 츿; 츿; ) HANGUL SYLLABLE CYIGS
+CE40;CE40;110E 1174 11AB;CE40;110E 1174 11AB; # (칀; 칀; 칀; 칀; 칀; ) HANGUL SYLLABLE CYIN
+CE41;CE41;110E 1174 11AC;CE41;110E 1174 11AC; # (칁; 칁; 칁; 칁; 칁; ) HANGUL SYLLABLE CYINJ
+CE42;CE42;110E 1174 11AD;CE42;110E 1174 11AD; # (칂; 칂; 칂; 칂; 칂; ) HANGUL SYLLABLE CYINH
+CE43;CE43;110E 1174 11AE;CE43;110E 1174 11AE; # (칃; 칃; 칃; 칃; 칃; ) HANGUL SYLLABLE CYID
+CE44;CE44;110E 1174 11AF;CE44;110E 1174 11AF; # (칄; 칄; 칄; 칄; 칄; ) HANGUL SYLLABLE CYIL
+CE45;CE45;110E 1174 11B0;CE45;110E 1174 11B0; # (칅; 칅; 칅; 칅; 칅; ) HANGUL SYLLABLE CYILG
+CE46;CE46;110E 1174 11B1;CE46;110E 1174 11B1; # (칆; 칆; 칆; 칆; 칆; ) HANGUL SYLLABLE CYILM
+CE47;CE47;110E 1174 11B2;CE47;110E 1174 11B2; # (칇; 칇; 칇; 칇; 칇; ) HANGUL SYLLABLE CYILB
+CE48;CE48;110E 1174 11B3;CE48;110E 1174 11B3; # (칈; 칈; 칈; 칈; 칈; ) HANGUL SYLLABLE CYILS
+CE49;CE49;110E 1174 11B4;CE49;110E 1174 11B4; # (칉; 칉; 칉; 칉; 칉; ) HANGUL SYLLABLE CYILT
+CE4A;CE4A;110E 1174 11B5;CE4A;110E 1174 11B5; # (칊; 칊; 칊; 칊; 칊; ) HANGUL SYLLABLE CYILP
+CE4B;CE4B;110E 1174 11B6;CE4B;110E 1174 11B6; # (칋; 칋; 칋; 칋; 칋; ) HANGUL SYLLABLE CYILH
+CE4C;CE4C;110E 1174 11B7;CE4C;110E 1174 11B7; # (칌; 칌; 칌; 칌; 칌; ) HANGUL SYLLABLE CYIM
+CE4D;CE4D;110E 1174 11B8;CE4D;110E 1174 11B8; # (칍; 칍; 칍; 칍; 칍; ) HANGUL SYLLABLE CYIB
+CE4E;CE4E;110E 1174 11B9;CE4E;110E 1174 11B9; # (칎; 칎; 칎; 칎; 칎; ) HANGUL SYLLABLE CYIBS
+CE4F;CE4F;110E 1174 11BA;CE4F;110E 1174 11BA; # (칏; 칏; 칏; 칏; 칏; ) HANGUL SYLLABLE CYIS
+CE50;CE50;110E 1174 11BB;CE50;110E 1174 11BB; # (칐; 칐; 칐; 칐; 칐; ) HANGUL SYLLABLE CYISS
+CE51;CE51;110E 1174 11BC;CE51;110E 1174 11BC; # (칑; 칑; 칑; 칑; 칑; ) HANGUL SYLLABLE CYING
+CE52;CE52;110E 1174 11BD;CE52;110E 1174 11BD; # (칒; 칒; 칒; 칒; 칒; ) HANGUL SYLLABLE CYIJ
+CE53;CE53;110E 1174 11BE;CE53;110E 1174 11BE; # (칓; 칓; 칓; 칓; 칓; ) HANGUL SYLLABLE CYIC
+CE54;CE54;110E 1174 11BF;CE54;110E 1174 11BF; # (칔; 칔; 칔; 칔; 칔; ) HANGUL SYLLABLE CYIK
+CE55;CE55;110E 1174 11C0;CE55;110E 1174 11C0; # (칕; 칕; 칕; 칕; 칕; ) HANGUL SYLLABLE CYIT
+CE56;CE56;110E 1174 11C1;CE56;110E 1174 11C1; # (칖; 칖; 칖; 칖; 칖; ) HANGUL SYLLABLE CYIP
+CE57;CE57;110E 1174 11C2;CE57;110E 1174 11C2; # (칗; 칗; 칗; 칗; 칗; ) HANGUL SYLLABLE CYIH
+CE58;CE58;110E 1175;CE58;110E 1175; # (치; 치; 치; 치; 치; ) HANGUL SYLLABLE CI
+CE59;CE59;110E 1175 11A8;CE59;110E 1175 11A8; # (칙; 칙; 칙; 칙; 칙; ) HANGUL SYLLABLE CIG
+CE5A;CE5A;110E 1175 11A9;CE5A;110E 1175 11A9; # (칚; 칚; 칚; 칚; 칚; ) HANGUL SYLLABLE CIGG
+CE5B;CE5B;110E 1175 11AA;CE5B;110E 1175 11AA; # (칛; 칛; 칛; 칛; 칛; ) HANGUL SYLLABLE CIGS
+CE5C;CE5C;110E 1175 11AB;CE5C;110E 1175 11AB; # (친; 친; 친; 친; 친; ) HANGUL SYLLABLE CIN
+CE5D;CE5D;110E 1175 11AC;CE5D;110E 1175 11AC; # (칝; 칝; 칝; 칝; 칝; ) HANGUL SYLLABLE CINJ
+CE5E;CE5E;110E 1175 11AD;CE5E;110E 1175 11AD; # (칞; 칞; 칞; 칞; 칞; ) HANGUL SYLLABLE CINH
+CE5F;CE5F;110E 1175 11AE;CE5F;110E 1175 11AE; # (칟; 칟; 칟; 칟; 칟; ) HANGUL SYLLABLE CID
+CE60;CE60;110E 1175 11AF;CE60;110E 1175 11AF; # (칠; 칠; 칠; 칠; 칠; ) HANGUL SYLLABLE CIL
+CE61;CE61;110E 1175 11B0;CE61;110E 1175 11B0; # (칡; 칡; 칡; 칡; 칡; ) HANGUL SYLLABLE CILG
+CE62;CE62;110E 1175 11B1;CE62;110E 1175 11B1; # (칢; 칢; 칢; 칢; 칢; ) HANGUL SYLLABLE CILM
+CE63;CE63;110E 1175 11B2;CE63;110E 1175 11B2; # (칣; 칣; 칣; 칣; 칣; ) HANGUL SYLLABLE CILB
+CE64;CE64;110E 1175 11B3;CE64;110E 1175 11B3; # (칤; 칤; 칤; 칤; 칤; ) HANGUL SYLLABLE CILS
+CE65;CE65;110E 1175 11B4;CE65;110E 1175 11B4; # (칥; 칥; 칥; 칥; 칥; ) HANGUL SYLLABLE CILT
+CE66;CE66;110E 1175 11B5;CE66;110E 1175 11B5; # (칦; 칦; 칦; 칦; 칦; ) HANGUL SYLLABLE CILP
+CE67;CE67;110E 1175 11B6;CE67;110E 1175 11B6; # (칧; 칧; 칧; 칧; 칧; ) HANGUL SYLLABLE CILH
+CE68;CE68;110E 1175 11B7;CE68;110E 1175 11B7; # (침; 침; 침; 침; 침; ) HANGUL SYLLABLE CIM
+CE69;CE69;110E 1175 11B8;CE69;110E 1175 11B8; # (칩; 칩; 칩; 칩; 칩; ) HANGUL SYLLABLE CIB
+CE6A;CE6A;110E 1175 11B9;CE6A;110E 1175 11B9; # (칪; 칪; 칪; 칪; 칪; ) HANGUL SYLLABLE CIBS
+CE6B;CE6B;110E 1175 11BA;CE6B;110E 1175 11BA; # (칫; 칫; 칫; 칫; 칫; ) HANGUL SYLLABLE CIS
+CE6C;CE6C;110E 1175 11BB;CE6C;110E 1175 11BB; # (칬; 칬; 칬; 칬; 칬; ) HANGUL SYLLABLE CISS
+CE6D;CE6D;110E 1175 11BC;CE6D;110E 1175 11BC; # (칭; 칭; 칭; 칭; 칭; ) HANGUL SYLLABLE CING
+CE6E;CE6E;110E 1175 11BD;CE6E;110E 1175 11BD; # (칮; 칮; 칮; 칮; 칮; ) HANGUL SYLLABLE CIJ
+CE6F;CE6F;110E 1175 11BE;CE6F;110E 1175 11BE; # (칯; 칯; 칯; 칯; 칯; ) HANGUL SYLLABLE CIC
+CE70;CE70;110E 1175 11BF;CE70;110E 1175 11BF; # (칰; 칰; 칰; 칰; 칰; ) HANGUL SYLLABLE CIK
+CE71;CE71;110E 1175 11C0;CE71;110E 1175 11C0; # (칱; 칱; 칱; 칱; 칱; ) HANGUL SYLLABLE CIT
+CE72;CE72;110E 1175 11C1;CE72;110E 1175 11C1; # (칲; 칲; 칲; 칲; 칲; ) HANGUL SYLLABLE CIP
+CE73;CE73;110E 1175 11C2;CE73;110E 1175 11C2; # (칳; 칳; 칳; 칳; 칳; ) HANGUL SYLLABLE CIH
+CE74;CE74;110F 1161;CE74;110F 1161; # (카; 카; 카; 카; 카; ) HANGUL SYLLABLE KA
+CE75;CE75;110F 1161 11A8;CE75;110F 1161 11A8; # (칵; 칵; 칵; 칵; 칵; ) HANGUL SYLLABLE KAG
+CE76;CE76;110F 1161 11A9;CE76;110F 1161 11A9; # (칶; 칶; 칶; 칶; 칶; ) HANGUL SYLLABLE KAGG
+CE77;CE77;110F 1161 11AA;CE77;110F 1161 11AA; # (칷; 칷; 칷; 칷; 칷; ) HANGUL SYLLABLE KAGS
+CE78;CE78;110F 1161 11AB;CE78;110F 1161 11AB; # (칸; 칸; 칸; 칸; 칸; ) HANGUL SYLLABLE KAN
+CE79;CE79;110F 1161 11AC;CE79;110F 1161 11AC; # (칹; 칹; 칹; 칹; 칹; ) HANGUL SYLLABLE KANJ
+CE7A;CE7A;110F 1161 11AD;CE7A;110F 1161 11AD; # (칺; 칺; 칺; 칺; 칺; ) HANGUL SYLLABLE KANH
+CE7B;CE7B;110F 1161 11AE;CE7B;110F 1161 11AE; # (칻; 칻; 칻; 칻; 칻; ) HANGUL SYLLABLE KAD
+CE7C;CE7C;110F 1161 11AF;CE7C;110F 1161 11AF; # (칼; 칼; 칼; 칼; 칼; ) HANGUL SYLLABLE KAL
+CE7D;CE7D;110F 1161 11B0;CE7D;110F 1161 11B0; # (칽; 칽; 칽; 칽; 칽; ) HANGUL SYLLABLE KALG
+CE7E;CE7E;110F 1161 11B1;CE7E;110F 1161 11B1; # (칾; 칾; 칾; 칾; 칾; ) HANGUL SYLLABLE KALM
+CE7F;CE7F;110F 1161 11B2;CE7F;110F 1161 11B2; # (칿; 칿; 칿; 칿; 칿; ) HANGUL SYLLABLE KALB
+CE80;CE80;110F 1161 11B3;CE80;110F 1161 11B3; # (캀; 캀; 캀; 캀; 캀; ) HANGUL SYLLABLE KALS
+CE81;CE81;110F 1161 11B4;CE81;110F 1161 11B4; # (캁; 캁; 캁; 캁; 캁; ) HANGUL SYLLABLE KALT
+CE82;CE82;110F 1161 11B5;CE82;110F 1161 11B5; # (캂; 캂; 캂; 캂; 캂; ) HANGUL SYLLABLE KALP
+CE83;CE83;110F 1161 11B6;CE83;110F 1161 11B6; # (캃; 캃; 캃; 캃; 캃; ) HANGUL SYLLABLE KALH
+CE84;CE84;110F 1161 11B7;CE84;110F 1161 11B7; # (캄; 캄; 캄; 캄; 캄; ) HANGUL SYLLABLE KAM
+CE85;CE85;110F 1161 11B8;CE85;110F 1161 11B8; # (캅; 캅; 캅; 캅; 캅; ) HANGUL SYLLABLE KAB
+CE86;CE86;110F 1161 11B9;CE86;110F 1161 11B9; # (캆; 캆; 캆; 캆; 캆; ) HANGUL SYLLABLE KABS
+CE87;CE87;110F 1161 11BA;CE87;110F 1161 11BA; # (캇; 캇; 캇; 캇; 캇; ) HANGUL SYLLABLE KAS
+CE88;CE88;110F 1161 11BB;CE88;110F 1161 11BB; # (캈; 캈; 캈; 캈; 캈; ) HANGUL SYLLABLE KASS
+CE89;CE89;110F 1161 11BC;CE89;110F 1161 11BC; # (캉; 캉; 캉; 캉; 캉; ) HANGUL SYLLABLE KANG
+CE8A;CE8A;110F 1161 11BD;CE8A;110F 1161 11BD; # (캊; 캊; 캊; 캊; 캊; ) HANGUL SYLLABLE KAJ
+CE8B;CE8B;110F 1161 11BE;CE8B;110F 1161 11BE; # (캋; 캋; 캋; 캋; 캋; ) HANGUL SYLLABLE KAC
+CE8C;CE8C;110F 1161 11BF;CE8C;110F 1161 11BF; # (캌; 캌; 캌; 캌; 캌; ) HANGUL SYLLABLE KAK
+CE8D;CE8D;110F 1161 11C0;CE8D;110F 1161 11C0; # (캍; 캍; 캍; 캍; 캍; ) HANGUL SYLLABLE KAT
+CE8E;CE8E;110F 1161 11C1;CE8E;110F 1161 11C1; # (캎; 캎; 캎; 캎; 캎; ) HANGUL SYLLABLE KAP
+CE8F;CE8F;110F 1161 11C2;CE8F;110F 1161 11C2; # (캏; 캏; 캏; 캏; 캏; ) HANGUL SYLLABLE KAH
+CE90;CE90;110F 1162;CE90;110F 1162; # (캐; 캐; 캐; 캐; 캐; ) HANGUL SYLLABLE KAE
+CE91;CE91;110F 1162 11A8;CE91;110F 1162 11A8; # (캑; 캑; 캑; 캑; 캑; ) HANGUL SYLLABLE KAEG
+CE92;CE92;110F 1162 11A9;CE92;110F 1162 11A9; # (캒; 캒; 캒; 캒; 캒; ) HANGUL SYLLABLE KAEGG
+CE93;CE93;110F 1162 11AA;CE93;110F 1162 11AA; # (캓; 캓; 캓; 캓; 캓; ) HANGUL SYLLABLE KAEGS
+CE94;CE94;110F 1162 11AB;CE94;110F 1162 11AB; # (캔; 캔; 캔; 캔; 캔; ) HANGUL SYLLABLE KAEN
+CE95;CE95;110F 1162 11AC;CE95;110F 1162 11AC; # (캕; 캕; 캕; 캕; 캕; ) HANGUL SYLLABLE KAENJ
+CE96;CE96;110F 1162 11AD;CE96;110F 1162 11AD; # (캖; 캖; 캖; 캖; 캖; ) HANGUL SYLLABLE KAENH
+CE97;CE97;110F 1162 11AE;CE97;110F 1162 11AE; # (캗; 캗; 캗; 캗; 캗; ) HANGUL SYLLABLE KAED
+CE98;CE98;110F 1162 11AF;CE98;110F 1162 11AF; # (캘; 캘; 캘; 캘; 캘; ) HANGUL SYLLABLE KAEL
+CE99;CE99;110F 1162 11B0;CE99;110F 1162 11B0; # (캙; 캙; 캙; 캙; 캙; ) HANGUL SYLLABLE KAELG
+CE9A;CE9A;110F 1162 11B1;CE9A;110F 1162 11B1; # (캚; 캚; 캚; 캚; 캚; ) HANGUL SYLLABLE KAELM
+CE9B;CE9B;110F 1162 11B2;CE9B;110F 1162 11B2; # (캛; 캛; 캛; 캛; 캛; ) HANGUL SYLLABLE KAELB
+CE9C;CE9C;110F 1162 11B3;CE9C;110F 1162 11B3; # (캜; 캜; 캜; 캜; 캜; ) HANGUL SYLLABLE KAELS
+CE9D;CE9D;110F 1162 11B4;CE9D;110F 1162 11B4; # (캝; 캝; 캝; 캝; 캝; ) HANGUL SYLLABLE KAELT
+CE9E;CE9E;110F 1162 11B5;CE9E;110F 1162 11B5; # (캞; 캞; 캞; 캞; 캞; ) HANGUL SYLLABLE KAELP
+CE9F;CE9F;110F 1162 11B6;CE9F;110F 1162 11B6; # (캟; 캟; 캟; 캟; 캟; ) HANGUL SYLLABLE KAELH
+CEA0;CEA0;110F 1162 11B7;CEA0;110F 1162 11B7; # (캠; 캠; 캠; 캠; 캠; ) HANGUL SYLLABLE KAEM
+CEA1;CEA1;110F 1162 11B8;CEA1;110F 1162 11B8; # (캡; 캡; 캡; 캡; 캡; ) HANGUL SYLLABLE KAEB
+CEA2;CEA2;110F 1162 11B9;CEA2;110F 1162 11B9; # (캢; 캢; 캢; 캢; 캢; ) HANGUL SYLLABLE KAEBS
+CEA3;CEA3;110F 1162 11BA;CEA3;110F 1162 11BA; # (캣; 캣; 캣; 캣; 캣; ) HANGUL SYLLABLE KAES
+CEA4;CEA4;110F 1162 11BB;CEA4;110F 1162 11BB; # (캤; 캤; 캤; 캤; 캤; ) HANGUL SYLLABLE KAESS
+CEA5;CEA5;110F 1162 11BC;CEA5;110F 1162 11BC; # (캥; 캥; 캥; 캥; 캥; ) HANGUL SYLLABLE KAENG
+CEA6;CEA6;110F 1162 11BD;CEA6;110F 1162 11BD; # (캦; 캦; 캦; 캦; 캦; ) HANGUL SYLLABLE KAEJ
+CEA7;CEA7;110F 1162 11BE;CEA7;110F 1162 11BE; # (캧; 캧; 캧; 캧; 캧; ) HANGUL SYLLABLE KAEC
+CEA8;CEA8;110F 1162 11BF;CEA8;110F 1162 11BF; # (캨; 캨; 캨; 캨; 캨; ) HANGUL SYLLABLE KAEK
+CEA9;CEA9;110F 1162 11C0;CEA9;110F 1162 11C0; # (캩; 캩; 캩; 캩; 캩; ) HANGUL SYLLABLE KAET
+CEAA;CEAA;110F 1162 11C1;CEAA;110F 1162 11C1; # (캪; 캪; 캪; 캪; 캪; ) HANGUL SYLLABLE KAEP
+CEAB;CEAB;110F 1162 11C2;CEAB;110F 1162 11C2; # (캫; 캫; 캫; 캫; 캫; ) HANGUL SYLLABLE KAEH
+CEAC;CEAC;110F 1163;CEAC;110F 1163; # (캬; 캬; 캬; 캬; 캬; ) HANGUL SYLLABLE KYA
+CEAD;CEAD;110F 1163 11A8;CEAD;110F 1163 11A8; # (캭; 캭; 캭; 캭; 캭; ) HANGUL SYLLABLE KYAG
+CEAE;CEAE;110F 1163 11A9;CEAE;110F 1163 11A9; # (캮; 캮; 캮; 캮; 캮; ) HANGUL SYLLABLE KYAGG
+CEAF;CEAF;110F 1163 11AA;CEAF;110F 1163 11AA; # (캯; 캯; 캯; 캯; 캯; ) HANGUL SYLLABLE KYAGS
+CEB0;CEB0;110F 1163 11AB;CEB0;110F 1163 11AB; # (캰; 캰; 캰; 캰; 캰; ) HANGUL SYLLABLE KYAN
+CEB1;CEB1;110F 1163 11AC;CEB1;110F 1163 11AC; # (캱; 캱; 캱; 캱; 캱; ) HANGUL SYLLABLE KYANJ
+CEB2;CEB2;110F 1163 11AD;CEB2;110F 1163 11AD; # (캲; 캲; 캲; 캲; 캲; ) HANGUL SYLLABLE KYANH
+CEB3;CEB3;110F 1163 11AE;CEB3;110F 1163 11AE; # (캳; 캳; 캳; 캳; 캳; ) HANGUL SYLLABLE KYAD
+CEB4;CEB4;110F 1163 11AF;CEB4;110F 1163 11AF; # (캴; 캴; 캴; 캴; 캴; ) HANGUL SYLLABLE KYAL
+CEB5;CEB5;110F 1163 11B0;CEB5;110F 1163 11B0; # (캵; 캵; 캵; 캵; 캵; ) HANGUL SYLLABLE KYALG
+CEB6;CEB6;110F 1163 11B1;CEB6;110F 1163 11B1; # (캶; 캶; 캶; 캶; 캶; ) HANGUL SYLLABLE KYALM
+CEB7;CEB7;110F 1163 11B2;CEB7;110F 1163 11B2; # (캷; 캷; 캷; 캷; 캷; ) HANGUL SYLLABLE KYALB
+CEB8;CEB8;110F 1163 11B3;CEB8;110F 1163 11B3; # (캸; 캸; 캸; 캸; 캸; ) HANGUL SYLLABLE KYALS
+CEB9;CEB9;110F 1163 11B4;CEB9;110F 1163 11B4; # (캹; 캹; 캹; 캹; 캹; ) HANGUL SYLLABLE KYALT
+CEBA;CEBA;110F 1163 11B5;CEBA;110F 1163 11B5; # (캺; 캺; 캺; 캺; 캺; ) HANGUL SYLLABLE KYALP
+CEBB;CEBB;110F 1163 11B6;CEBB;110F 1163 11B6; # (캻; 캻; 캻; 캻; 캻; ) HANGUL SYLLABLE KYALH
+CEBC;CEBC;110F 1163 11B7;CEBC;110F 1163 11B7; # (캼; 캼; 캼; 캼; 캼; ) HANGUL SYLLABLE KYAM
+CEBD;CEBD;110F 1163 11B8;CEBD;110F 1163 11B8; # (캽; 캽; 캽; 캽; 캽; ) HANGUL SYLLABLE KYAB
+CEBE;CEBE;110F 1163 11B9;CEBE;110F 1163 11B9; # (캾; 캾; 캾; 캾; 캾; ) HANGUL SYLLABLE KYABS
+CEBF;CEBF;110F 1163 11BA;CEBF;110F 1163 11BA; # (캿; 캿; 캿; 캿; 캿; ) HANGUL SYLLABLE KYAS
+CEC0;CEC0;110F 1163 11BB;CEC0;110F 1163 11BB; # (컀; 컀; 컀; 컀; 컀; ) HANGUL SYLLABLE KYASS
+CEC1;CEC1;110F 1163 11BC;CEC1;110F 1163 11BC; # (컁; 컁; 컁; 컁; 컁; ) HANGUL SYLLABLE KYANG
+CEC2;CEC2;110F 1163 11BD;CEC2;110F 1163 11BD; # (컂; 컂; 컂; 컂; 컂; ) HANGUL SYLLABLE KYAJ
+CEC3;CEC3;110F 1163 11BE;CEC3;110F 1163 11BE; # (컃; 컃; 컃; 컃; 컃; ) HANGUL SYLLABLE KYAC
+CEC4;CEC4;110F 1163 11BF;CEC4;110F 1163 11BF; # (컄; 컄; 컄; 컄; 컄; ) HANGUL SYLLABLE KYAK
+CEC5;CEC5;110F 1163 11C0;CEC5;110F 1163 11C0; # (컅; 컅; 컅; 컅; 컅; ) HANGUL SYLLABLE KYAT
+CEC6;CEC6;110F 1163 11C1;CEC6;110F 1163 11C1; # (컆; 컆; 컆; 컆; 컆; ) HANGUL SYLLABLE KYAP
+CEC7;CEC7;110F 1163 11C2;CEC7;110F 1163 11C2; # (컇; 컇; 컇; 컇; 컇; ) HANGUL SYLLABLE KYAH
+CEC8;CEC8;110F 1164;CEC8;110F 1164; # (컈; 컈; 컈; 컈; 컈; ) HANGUL SYLLABLE KYAE
+CEC9;CEC9;110F 1164 11A8;CEC9;110F 1164 11A8; # (컉; 컉; 컉; 컉; 컉; ) HANGUL SYLLABLE KYAEG
+CECA;CECA;110F 1164 11A9;CECA;110F 1164 11A9; # (컊; 컊; 컊; 컊; 컊; ) HANGUL SYLLABLE KYAEGG
+CECB;CECB;110F 1164 11AA;CECB;110F 1164 11AA; # (컋; 컋; 컋; 컋; 컋; ) HANGUL SYLLABLE KYAEGS
+CECC;CECC;110F 1164 11AB;CECC;110F 1164 11AB; # (컌; 컌; 컌; 컌; 컌; ) HANGUL SYLLABLE KYAEN
+CECD;CECD;110F 1164 11AC;CECD;110F 1164 11AC; # (컍; 컍; 컍; 컍; 컍; ) HANGUL SYLLABLE KYAENJ
+CECE;CECE;110F 1164 11AD;CECE;110F 1164 11AD; # (컎; 컎; 컎; 컎; 컎; ) HANGUL SYLLABLE KYAENH
+CECF;CECF;110F 1164 11AE;CECF;110F 1164 11AE; # (컏; 컏; 컏; 컏; 컏; ) HANGUL SYLLABLE KYAED
+CED0;CED0;110F 1164 11AF;CED0;110F 1164 11AF; # (컐; 컐; 컐; 컐; 컐; ) HANGUL SYLLABLE KYAEL
+CED1;CED1;110F 1164 11B0;CED1;110F 1164 11B0; # (컑; 컑; 컑; 컑; 컑; ) HANGUL SYLLABLE KYAELG
+CED2;CED2;110F 1164 11B1;CED2;110F 1164 11B1; # (컒; 컒; 컒; 컒; 컒; ) HANGUL SYLLABLE KYAELM
+CED3;CED3;110F 1164 11B2;CED3;110F 1164 11B2; # (컓; 컓; 컓; 컓; 컓; ) HANGUL SYLLABLE KYAELB
+CED4;CED4;110F 1164 11B3;CED4;110F 1164 11B3; # (컔; 컔; 컔; 컔; 컔; ) HANGUL SYLLABLE KYAELS
+CED5;CED5;110F 1164 11B4;CED5;110F 1164 11B4; # (컕; 컕; 컕; 컕; 컕; ) HANGUL SYLLABLE KYAELT
+CED6;CED6;110F 1164 11B5;CED6;110F 1164 11B5; # (컖; 컖; 컖; 컖; 컖; ) HANGUL SYLLABLE KYAELP
+CED7;CED7;110F 1164 11B6;CED7;110F 1164 11B6; # (컗; 컗; 컗; 컗; 컗; ) HANGUL SYLLABLE KYAELH
+CED8;CED8;110F 1164 11B7;CED8;110F 1164 11B7; # (컘; 컘; 컘; 컘; 컘; ) HANGUL SYLLABLE KYAEM
+CED9;CED9;110F 1164 11B8;CED9;110F 1164 11B8; # (컙; 컙; 컙; 컙; 컙; ) HANGUL SYLLABLE KYAEB
+CEDA;CEDA;110F 1164 11B9;CEDA;110F 1164 11B9; # (컚; 컚; 컚; 컚; 컚; ) HANGUL SYLLABLE KYAEBS
+CEDB;CEDB;110F 1164 11BA;CEDB;110F 1164 11BA; # (컛; 컛; 컛; 컛; 컛; ) HANGUL SYLLABLE KYAES
+CEDC;CEDC;110F 1164 11BB;CEDC;110F 1164 11BB; # (컜; 컜; 컜; 컜; 컜; ) HANGUL SYLLABLE KYAESS
+CEDD;CEDD;110F 1164 11BC;CEDD;110F 1164 11BC; # (컝; 컝; 컝; 컝; 컝; ) HANGUL SYLLABLE KYAENG
+CEDE;CEDE;110F 1164 11BD;CEDE;110F 1164 11BD; # (컞; 컞; 컞; 컞; 컞; ) HANGUL SYLLABLE KYAEJ
+CEDF;CEDF;110F 1164 11BE;CEDF;110F 1164 11BE; # (컟; 컟; 컟; 컟; 컟; ) HANGUL SYLLABLE KYAEC
+CEE0;CEE0;110F 1164 11BF;CEE0;110F 1164 11BF; # (컠; 컠; 컠; 컠; 컠; ) HANGUL SYLLABLE KYAEK
+CEE1;CEE1;110F 1164 11C0;CEE1;110F 1164 11C0; # (컡; 컡; 컡; 컡; 컡; ) HANGUL SYLLABLE KYAET
+CEE2;CEE2;110F 1164 11C1;CEE2;110F 1164 11C1; # (컢; 컢; 컢; 컢; 컢; ) HANGUL SYLLABLE KYAEP
+CEE3;CEE3;110F 1164 11C2;CEE3;110F 1164 11C2; # (컣; 컣; 컣; 컣; 컣; ) HANGUL SYLLABLE KYAEH
+CEE4;CEE4;110F 1165;CEE4;110F 1165; # (커; 커; 커; 커; 커; ) HANGUL SYLLABLE KEO
+CEE5;CEE5;110F 1165 11A8;CEE5;110F 1165 11A8; # (컥; 컥; 컥; 컥; 컥; ) HANGUL SYLLABLE KEOG
+CEE6;CEE6;110F 1165 11A9;CEE6;110F 1165 11A9; # (컦; 컦; 컦; 컦; 컦; ) HANGUL SYLLABLE KEOGG
+CEE7;CEE7;110F 1165 11AA;CEE7;110F 1165 11AA; # (컧; 컧; 컧; 컧; 컧; ) HANGUL SYLLABLE KEOGS
+CEE8;CEE8;110F 1165 11AB;CEE8;110F 1165 11AB; # (컨; 컨; 컨; 컨; 컨; ) HANGUL SYLLABLE KEON
+CEE9;CEE9;110F 1165 11AC;CEE9;110F 1165 11AC; # (컩; 컩; 컩; 컩; 컩; ) HANGUL SYLLABLE KEONJ
+CEEA;CEEA;110F 1165 11AD;CEEA;110F 1165 11AD; # (컪; 컪; 컪; 컪; 컪; ) HANGUL SYLLABLE KEONH
+CEEB;CEEB;110F 1165 11AE;CEEB;110F 1165 11AE; # (컫; 컫; 컫; 컫; 컫; ) HANGUL SYLLABLE KEOD
+CEEC;CEEC;110F 1165 11AF;CEEC;110F 1165 11AF; # (컬; 컬; 컬; 컬; 컬; ) HANGUL SYLLABLE KEOL
+CEED;CEED;110F 1165 11B0;CEED;110F 1165 11B0; # (컭; 컭; 컭; 컭; 컭; ) HANGUL SYLLABLE KEOLG
+CEEE;CEEE;110F 1165 11B1;CEEE;110F 1165 11B1; # (컮; 컮; 컮; 컮; 컮; ) HANGUL SYLLABLE KEOLM
+CEEF;CEEF;110F 1165 11B2;CEEF;110F 1165 11B2; # (컯; 컯; 컯; 컯; 컯; ) HANGUL SYLLABLE KEOLB
+CEF0;CEF0;110F 1165 11B3;CEF0;110F 1165 11B3; # (컰; 컰; 컰; 컰; 컰; ) HANGUL SYLLABLE KEOLS
+CEF1;CEF1;110F 1165 11B4;CEF1;110F 1165 11B4; # (컱; 컱; 컱; 컱; 컱; ) HANGUL SYLLABLE KEOLT
+CEF2;CEF2;110F 1165 11B5;CEF2;110F 1165 11B5; # (컲; 컲; 컲; 컲; 컲; ) HANGUL SYLLABLE KEOLP
+CEF3;CEF3;110F 1165 11B6;CEF3;110F 1165 11B6; # (컳; 컳; 컳; 컳; 컳; ) HANGUL SYLLABLE KEOLH
+CEF4;CEF4;110F 1165 11B7;CEF4;110F 1165 11B7; # (컴; 컴; 컴; 컴; 컴; ) HANGUL SYLLABLE KEOM
+CEF5;CEF5;110F 1165 11B8;CEF5;110F 1165 11B8; # (컵; 컵; 컵; 컵; 컵; ) HANGUL SYLLABLE KEOB
+CEF6;CEF6;110F 1165 11B9;CEF6;110F 1165 11B9; # (컶; 컶; 컶; 컶; 컶; ) HANGUL SYLLABLE KEOBS
+CEF7;CEF7;110F 1165 11BA;CEF7;110F 1165 11BA; # (컷; 컷; 컷; 컷; 컷; ) HANGUL SYLLABLE KEOS
+CEF8;CEF8;110F 1165 11BB;CEF8;110F 1165 11BB; # (컸; 컸; 컸; 컸; 컸; ) HANGUL SYLLABLE KEOSS
+CEF9;CEF9;110F 1165 11BC;CEF9;110F 1165 11BC; # (컹; 컹; 컹; 컹; 컹; ) HANGUL SYLLABLE KEONG
+CEFA;CEFA;110F 1165 11BD;CEFA;110F 1165 11BD; # (컺; 컺; 컺; 컺; 컺; ) HANGUL SYLLABLE KEOJ
+CEFB;CEFB;110F 1165 11BE;CEFB;110F 1165 11BE; # (컻; 컻; 컻; 컻; 컻; ) HANGUL SYLLABLE KEOC
+CEFC;CEFC;110F 1165 11BF;CEFC;110F 1165 11BF; # (컼; 컼; 컼; 컼; 컼; ) HANGUL SYLLABLE KEOK
+CEFD;CEFD;110F 1165 11C0;CEFD;110F 1165 11C0; # (컽; 컽; 컽; 컽; 컽; ) HANGUL SYLLABLE KEOT
+CEFE;CEFE;110F 1165 11C1;CEFE;110F 1165 11C1; # (컾; 컾; 컾; 컾; 컾; ) HANGUL SYLLABLE KEOP
+CEFF;CEFF;110F 1165 11C2;CEFF;110F 1165 11C2; # (컿; 컿; 컿; 컿; 컿; ) HANGUL SYLLABLE KEOH
+CF00;CF00;110F 1166;CF00;110F 1166; # (케; 케; 케; 케; 케; ) HANGUL SYLLABLE KE
+CF01;CF01;110F 1166 11A8;CF01;110F 1166 11A8; # (켁; 켁; 켁; 켁; 켁; ) HANGUL SYLLABLE KEG
+CF02;CF02;110F 1166 11A9;CF02;110F 1166 11A9; # (켂; 켂; 켂; 켂; 켂; ) HANGUL SYLLABLE KEGG
+CF03;CF03;110F 1166 11AA;CF03;110F 1166 11AA; # (켃; 켃; 켃; 켃; 켃; ) HANGUL SYLLABLE KEGS
+CF04;CF04;110F 1166 11AB;CF04;110F 1166 11AB; # (켄; 켄; 켄; 켄; 켄; ) HANGUL SYLLABLE KEN
+CF05;CF05;110F 1166 11AC;CF05;110F 1166 11AC; # (켅; 켅; 켅; 켅; 켅; ) HANGUL SYLLABLE KENJ
+CF06;CF06;110F 1166 11AD;CF06;110F 1166 11AD; # (켆; 켆; 켆; 켆; 켆; ) HANGUL SYLLABLE KENH
+CF07;CF07;110F 1166 11AE;CF07;110F 1166 11AE; # (켇; 켇; 켇; 켇; 켇; ) HANGUL SYLLABLE KED
+CF08;CF08;110F 1166 11AF;CF08;110F 1166 11AF; # (켈; 켈; 켈; 켈; 켈; ) HANGUL SYLLABLE KEL
+CF09;CF09;110F 1166 11B0;CF09;110F 1166 11B0; # (켉; 켉; 켉; 켉; 켉; ) HANGUL SYLLABLE KELG
+CF0A;CF0A;110F 1166 11B1;CF0A;110F 1166 11B1; # (켊; 켊; 켊; 켊; 켊; ) HANGUL SYLLABLE KELM
+CF0B;CF0B;110F 1166 11B2;CF0B;110F 1166 11B2; # (켋; 켋; 켋; 켋; 켋; ) HANGUL SYLLABLE KELB
+CF0C;CF0C;110F 1166 11B3;CF0C;110F 1166 11B3; # (켌; 켌; 켌; 켌; 켌; ) HANGUL SYLLABLE KELS
+CF0D;CF0D;110F 1166 11B4;CF0D;110F 1166 11B4; # (켍; 켍; 켍; 켍; 켍; ) HANGUL SYLLABLE KELT
+CF0E;CF0E;110F 1166 11B5;CF0E;110F 1166 11B5; # (켎; 켎; 켎; 켎; 켎; ) HANGUL SYLLABLE KELP
+CF0F;CF0F;110F 1166 11B6;CF0F;110F 1166 11B6; # (켏; 켏; 켏; 켏; 켏; ) HANGUL SYLLABLE KELH
+CF10;CF10;110F 1166 11B7;CF10;110F 1166 11B7; # (켐; 켐; 켐; 켐; 켐; ) HANGUL SYLLABLE KEM
+CF11;CF11;110F 1166 11B8;CF11;110F 1166 11B8; # (켑; 켑; 켑; 켑; 켑; ) HANGUL SYLLABLE KEB
+CF12;CF12;110F 1166 11B9;CF12;110F 1166 11B9; # (켒; 켒; 켒; 켒; 켒; ) HANGUL SYLLABLE KEBS
+CF13;CF13;110F 1166 11BA;CF13;110F 1166 11BA; # (켓; 켓; 켓; 켓; 켓; ) HANGUL SYLLABLE KES
+CF14;CF14;110F 1166 11BB;CF14;110F 1166 11BB; # (켔; 켔; 켔; 켔; 켔; ) HANGUL SYLLABLE KESS
+CF15;CF15;110F 1166 11BC;CF15;110F 1166 11BC; # (켕; 켕; 켕; 켕; 켕; ) HANGUL SYLLABLE KENG
+CF16;CF16;110F 1166 11BD;CF16;110F 1166 11BD; # (켖; 켖; 켖; 켖; 켖; ) HANGUL SYLLABLE KEJ
+CF17;CF17;110F 1166 11BE;CF17;110F 1166 11BE; # (켗; 켗; 켗; 켗; 켗; ) HANGUL SYLLABLE KEC
+CF18;CF18;110F 1166 11BF;CF18;110F 1166 11BF; # (켘; 켘; 켘; 켘; 켘; ) HANGUL SYLLABLE KEK
+CF19;CF19;110F 1166 11C0;CF19;110F 1166 11C0; # (켙; 켙; 켙; 켙; 켙; ) HANGUL SYLLABLE KET
+CF1A;CF1A;110F 1166 11C1;CF1A;110F 1166 11C1; # (켚; 켚; 켚; 켚; 켚; ) HANGUL SYLLABLE KEP
+CF1B;CF1B;110F 1166 11C2;CF1B;110F 1166 11C2; # (켛; 켛; 켛; 켛; 켛; ) HANGUL SYLLABLE KEH
+CF1C;CF1C;110F 1167;CF1C;110F 1167; # (켜; 켜; 켜; 켜; 켜; ) HANGUL SYLLABLE KYEO
+CF1D;CF1D;110F 1167 11A8;CF1D;110F 1167 11A8; # (켝; 켝; 켝; 켝; 켝; ) HANGUL SYLLABLE KYEOG
+CF1E;CF1E;110F 1167 11A9;CF1E;110F 1167 11A9; # (켞; 켞; 켞; 켞; 켞; ) HANGUL SYLLABLE KYEOGG
+CF1F;CF1F;110F 1167 11AA;CF1F;110F 1167 11AA; # (켟; 켟; 켟; 켟; 켟; ) HANGUL SYLLABLE KYEOGS
+CF20;CF20;110F 1167 11AB;CF20;110F 1167 11AB; # (켠; 켠; 켠; 켠; 켠; ) HANGUL SYLLABLE KYEON
+CF21;CF21;110F 1167 11AC;CF21;110F 1167 11AC; # (켡; 켡; 켡; 켡; 켡; ) HANGUL SYLLABLE KYEONJ
+CF22;CF22;110F 1167 11AD;CF22;110F 1167 11AD; # (켢; 켢; 켢; 켢; 켢; ) HANGUL SYLLABLE KYEONH
+CF23;CF23;110F 1167 11AE;CF23;110F 1167 11AE; # (켣; 켣; 켣; 켣; 켣; ) HANGUL SYLLABLE KYEOD
+CF24;CF24;110F 1167 11AF;CF24;110F 1167 11AF; # (켤; 켤; 켤; 켤; 켤; ) HANGUL SYLLABLE KYEOL
+CF25;CF25;110F 1167 11B0;CF25;110F 1167 11B0; # (켥; 켥; 켥; 켥; 켥; ) HANGUL SYLLABLE KYEOLG
+CF26;CF26;110F 1167 11B1;CF26;110F 1167 11B1; # (켦; 켦; 켦; 켦; 켦; ) HANGUL SYLLABLE KYEOLM
+CF27;CF27;110F 1167 11B2;CF27;110F 1167 11B2; # (켧; 켧; 켧; 켧; 켧; ) HANGUL SYLLABLE KYEOLB
+CF28;CF28;110F 1167 11B3;CF28;110F 1167 11B3; # (켨; 켨; 켨; 켨; 켨; ) HANGUL SYLLABLE KYEOLS
+CF29;CF29;110F 1167 11B4;CF29;110F 1167 11B4; # (켩; 켩; 켩; 켩; 켩; ) HANGUL SYLLABLE KYEOLT
+CF2A;CF2A;110F 1167 11B5;CF2A;110F 1167 11B5; # (켪; 켪; 켪; 켪; 켪; ) HANGUL SYLLABLE KYEOLP
+CF2B;CF2B;110F 1167 11B6;CF2B;110F 1167 11B6; # (켫; 켫; 켫; 켫; 켫; ) HANGUL SYLLABLE KYEOLH
+CF2C;CF2C;110F 1167 11B7;CF2C;110F 1167 11B7; # (켬; 켬; 켬; 켬; 켬; ) HANGUL SYLLABLE KYEOM
+CF2D;CF2D;110F 1167 11B8;CF2D;110F 1167 11B8; # (켭; 켭; 켭; 켭; 켭; ) HANGUL SYLLABLE KYEOB
+CF2E;CF2E;110F 1167 11B9;CF2E;110F 1167 11B9; # (켮; 켮; 켮; 켮; 켮; ) HANGUL SYLLABLE KYEOBS
+CF2F;CF2F;110F 1167 11BA;CF2F;110F 1167 11BA; # (켯; 켯; 켯; 켯; 켯; ) HANGUL SYLLABLE KYEOS
+CF30;CF30;110F 1167 11BB;CF30;110F 1167 11BB; # (켰; 켰; 켰; 켰; 켰; ) HANGUL SYLLABLE KYEOSS
+CF31;CF31;110F 1167 11BC;CF31;110F 1167 11BC; # (켱; 켱; 켱; 켱; 켱; ) HANGUL SYLLABLE KYEONG
+CF32;CF32;110F 1167 11BD;CF32;110F 1167 11BD; # (켲; 켲; 켲; 켲; 켲; ) HANGUL SYLLABLE KYEOJ
+CF33;CF33;110F 1167 11BE;CF33;110F 1167 11BE; # (켳; 켳; 켳; 켳; 켳; ) HANGUL SYLLABLE KYEOC
+CF34;CF34;110F 1167 11BF;CF34;110F 1167 11BF; # (켴; 켴; 켴; 켴; 켴; ) HANGUL SYLLABLE KYEOK
+CF35;CF35;110F 1167 11C0;CF35;110F 1167 11C0; # (켵; 켵; 켵; 켵; 켵; ) HANGUL SYLLABLE KYEOT
+CF36;CF36;110F 1167 11C1;CF36;110F 1167 11C1; # (켶; 켶; 켶; 켶; 켶; ) HANGUL SYLLABLE KYEOP
+CF37;CF37;110F 1167 11C2;CF37;110F 1167 11C2; # (켷; 켷; 켷; 켷; 켷; ) HANGUL SYLLABLE KYEOH
+CF38;CF38;110F 1168;CF38;110F 1168; # (켸; 켸; 켸; 켸; 켸; ) HANGUL SYLLABLE KYE
+CF39;CF39;110F 1168 11A8;CF39;110F 1168 11A8; # (켹; 켹; 켹; 켹; 켹; ) HANGUL SYLLABLE KYEG
+CF3A;CF3A;110F 1168 11A9;CF3A;110F 1168 11A9; # (켺; 켺; 켺; 켺; 켺; ) HANGUL SYLLABLE KYEGG
+CF3B;CF3B;110F 1168 11AA;CF3B;110F 1168 11AA; # (켻; 켻; 켻; 켻; 켻; ) HANGUL SYLLABLE KYEGS
+CF3C;CF3C;110F 1168 11AB;CF3C;110F 1168 11AB; # (켼; 켼; 켼; 켼; 켼; ) HANGUL SYLLABLE KYEN
+CF3D;CF3D;110F 1168 11AC;CF3D;110F 1168 11AC; # (켽; 켽; 켽; 켽; 켽; ) HANGUL SYLLABLE KYENJ
+CF3E;CF3E;110F 1168 11AD;CF3E;110F 1168 11AD; # (켾; 켾; 켾; 켾; 켾; ) HANGUL SYLLABLE KYENH
+CF3F;CF3F;110F 1168 11AE;CF3F;110F 1168 11AE; # (켿; 켿; 켿; 켿; 켿; ) HANGUL SYLLABLE KYED
+CF40;CF40;110F 1168 11AF;CF40;110F 1168 11AF; # (콀; 콀; 콀; 콀; 콀; ) HANGUL SYLLABLE KYEL
+CF41;CF41;110F 1168 11B0;CF41;110F 1168 11B0; # (콁; 콁; 콁; 콁; 콁; ) HANGUL SYLLABLE KYELG
+CF42;CF42;110F 1168 11B1;CF42;110F 1168 11B1; # (콂; 콂; 콂; 콂; 콂; ) HANGUL SYLLABLE KYELM
+CF43;CF43;110F 1168 11B2;CF43;110F 1168 11B2; # (콃; 콃; 콃; 콃; 콃; ) HANGUL SYLLABLE KYELB
+CF44;CF44;110F 1168 11B3;CF44;110F 1168 11B3; # (콄; 콄; 콄; 콄; 콄; ) HANGUL SYLLABLE KYELS
+CF45;CF45;110F 1168 11B4;CF45;110F 1168 11B4; # (콅; 콅; 콅; 콅; 콅; ) HANGUL SYLLABLE KYELT
+CF46;CF46;110F 1168 11B5;CF46;110F 1168 11B5; # (콆; 콆; 콆; 콆; 콆; ) HANGUL SYLLABLE KYELP
+CF47;CF47;110F 1168 11B6;CF47;110F 1168 11B6; # (콇; 콇; 콇; 콇; 콇; ) HANGUL SYLLABLE KYELH
+CF48;CF48;110F 1168 11B7;CF48;110F 1168 11B7; # (콈; 콈; 콈; 콈; 콈; ) HANGUL SYLLABLE KYEM
+CF49;CF49;110F 1168 11B8;CF49;110F 1168 11B8; # (콉; 콉; 콉; 콉; 콉; ) HANGUL SYLLABLE KYEB
+CF4A;CF4A;110F 1168 11B9;CF4A;110F 1168 11B9; # (콊; 콊; 콊; 콊; 콊; ) HANGUL SYLLABLE KYEBS
+CF4B;CF4B;110F 1168 11BA;CF4B;110F 1168 11BA; # (콋; 콋; 콋; 콋; 콋; ) HANGUL SYLLABLE KYES
+CF4C;CF4C;110F 1168 11BB;CF4C;110F 1168 11BB; # (콌; 콌; 콌; 콌; 콌; ) HANGUL SYLLABLE KYESS
+CF4D;CF4D;110F 1168 11BC;CF4D;110F 1168 11BC; # (콍; 콍; 콍; 콍; 콍; ) HANGUL SYLLABLE KYENG
+CF4E;CF4E;110F 1168 11BD;CF4E;110F 1168 11BD; # (콎; 콎; 콎; 콎; 콎; ) HANGUL SYLLABLE KYEJ
+CF4F;CF4F;110F 1168 11BE;CF4F;110F 1168 11BE; # (콏; 콏; 콏; 콏; 콏; ) HANGUL SYLLABLE KYEC
+CF50;CF50;110F 1168 11BF;CF50;110F 1168 11BF; # (콐; 콐; 콐; 콐; 콐; ) HANGUL SYLLABLE KYEK
+CF51;CF51;110F 1168 11C0;CF51;110F 1168 11C0; # (콑; 콑; 콑; 콑; 콑; ) HANGUL SYLLABLE KYET
+CF52;CF52;110F 1168 11C1;CF52;110F 1168 11C1; # (콒; 콒; 콒; 콒; 콒; ) HANGUL SYLLABLE KYEP
+CF53;CF53;110F 1168 11C2;CF53;110F 1168 11C2; # (콓; 콓; 콓; 콓; 콓; ) HANGUL SYLLABLE KYEH
+CF54;CF54;110F 1169;CF54;110F 1169; # (코; 코; 코; 코; 코; ) HANGUL SYLLABLE KO
+CF55;CF55;110F 1169 11A8;CF55;110F 1169 11A8; # (콕; 콕; 콕; 콕; 콕; ) HANGUL SYLLABLE KOG
+CF56;CF56;110F 1169 11A9;CF56;110F 1169 11A9; # (콖; 콖; 콖; 콖; 콖; ) HANGUL SYLLABLE KOGG
+CF57;CF57;110F 1169 11AA;CF57;110F 1169 11AA; # (콗; 콗; 콗; 콗; 콗; ) HANGUL SYLLABLE KOGS
+CF58;CF58;110F 1169 11AB;CF58;110F 1169 11AB; # (콘; 콘; 콘; 콘; 콘; ) HANGUL SYLLABLE KON
+CF59;CF59;110F 1169 11AC;CF59;110F 1169 11AC; # (콙; 콙; 콙; 콙; 콙; ) HANGUL SYLLABLE KONJ
+CF5A;CF5A;110F 1169 11AD;CF5A;110F 1169 11AD; # (콚; 콚; 콚; 콚; 콚; ) HANGUL SYLLABLE KONH
+CF5B;CF5B;110F 1169 11AE;CF5B;110F 1169 11AE; # (콛; 콛; 콛; 콛; 콛; ) HANGUL SYLLABLE KOD
+CF5C;CF5C;110F 1169 11AF;CF5C;110F 1169 11AF; # (콜; 콜; 콜; 콜; 콜; ) HANGUL SYLLABLE KOL
+CF5D;CF5D;110F 1169 11B0;CF5D;110F 1169 11B0; # (콝; 콝; 콝; 콝; 콝; ) HANGUL SYLLABLE KOLG
+CF5E;CF5E;110F 1169 11B1;CF5E;110F 1169 11B1; # (콞; 콞; 콞; 콞; 콞; ) HANGUL SYLLABLE KOLM
+CF5F;CF5F;110F 1169 11B2;CF5F;110F 1169 11B2; # (콟; 콟; 콟; 콟; 콟; ) HANGUL SYLLABLE KOLB
+CF60;CF60;110F 1169 11B3;CF60;110F 1169 11B3; # (콠; 콠; 콠; 콠; 콠; ) HANGUL SYLLABLE KOLS
+CF61;CF61;110F 1169 11B4;CF61;110F 1169 11B4; # (콡; 콡; 콡; 콡; 콡; ) HANGUL SYLLABLE KOLT
+CF62;CF62;110F 1169 11B5;CF62;110F 1169 11B5; # (콢; 콢; 콢; 콢; 콢; ) HANGUL SYLLABLE KOLP
+CF63;CF63;110F 1169 11B6;CF63;110F 1169 11B6; # (콣; 콣; 콣; 콣; 콣; ) HANGUL SYLLABLE KOLH
+CF64;CF64;110F 1169 11B7;CF64;110F 1169 11B7; # (콤; 콤; 콤; 콤; 콤; ) HANGUL SYLLABLE KOM
+CF65;CF65;110F 1169 11B8;CF65;110F 1169 11B8; # (콥; 콥; 콥; 콥; 콥; ) HANGUL SYLLABLE KOB
+CF66;CF66;110F 1169 11B9;CF66;110F 1169 11B9; # (콦; 콦; 콦; 콦; 콦; ) HANGUL SYLLABLE KOBS
+CF67;CF67;110F 1169 11BA;CF67;110F 1169 11BA; # (콧; 콧; 콧; 콧; 콧; ) HANGUL SYLLABLE KOS
+CF68;CF68;110F 1169 11BB;CF68;110F 1169 11BB; # (콨; 콨; 콨; 콨; 콨; ) HANGUL SYLLABLE KOSS
+CF69;CF69;110F 1169 11BC;CF69;110F 1169 11BC; # (콩; 콩; 콩; 콩; 콩; ) HANGUL SYLLABLE KONG
+CF6A;CF6A;110F 1169 11BD;CF6A;110F 1169 11BD; # (콪; 콪; 콪; 콪; 콪; ) HANGUL SYLLABLE KOJ
+CF6B;CF6B;110F 1169 11BE;CF6B;110F 1169 11BE; # (콫; 콫; 콫; 콫; 콫; ) HANGUL SYLLABLE KOC
+CF6C;CF6C;110F 1169 11BF;CF6C;110F 1169 11BF; # (콬; 콬; 콬; 콬; 콬; ) HANGUL SYLLABLE KOK
+CF6D;CF6D;110F 1169 11C0;CF6D;110F 1169 11C0; # (콭; 콭; 콭; 콭; 콭; ) HANGUL SYLLABLE KOT
+CF6E;CF6E;110F 1169 11C1;CF6E;110F 1169 11C1; # (콮; 콮; 콮; 콮; 콮; ) HANGUL SYLLABLE KOP
+CF6F;CF6F;110F 1169 11C2;CF6F;110F 1169 11C2; # (콯; 콯; 콯; 콯; 콯; ) HANGUL SYLLABLE KOH
+CF70;CF70;110F 116A;CF70;110F 116A; # (콰; 콰; 콰; 콰; 콰; ) HANGUL SYLLABLE KWA
+CF71;CF71;110F 116A 11A8;CF71;110F 116A 11A8; # (콱; 콱; 콱; 콱; 콱; ) HANGUL SYLLABLE KWAG
+CF72;CF72;110F 116A 11A9;CF72;110F 116A 11A9; # (콲; 콲; 콲; 콲; 콲; ) HANGUL SYLLABLE KWAGG
+CF73;CF73;110F 116A 11AA;CF73;110F 116A 11AA; # (콳; 콳; 콳; 콳; 콳; ) HANGUL SYLLABLE KWAGS
+CF74;CF74;110F 116A 11AB;CF74;110F 116A 11AB; # (콴; 콴; 콴; 콴; 콴; ) HANGUL SYLLABLE KWAN
+CF75;CF75;110F 116A 11AC;CF75;110F 116A 11AC; # (콵; 콵; 콵; 콵; 콵; ) HANGUL SYLLABLE KWANJ
+CF76;CF76;110F 116A 11AD;CF76;110F 116A 11AD; # (콶; 콶; 콶; 콶; 콶; ) HANGUL SYLLABLE KWANH
+CF77;CF77;110F 116A 11AE;CF77;110F 116A 11AE; # (콷; 콷; 콷; 콷; 콷; ) HANGUL SYLLABLE KWAD
+CF78;CF78;110F 116A 11AF;CF78;110F 116A 11AF; # (콸; 콸; 콸; 콸; 콸; ) HANGUL SYLLABLE KWAL
+CF79;CF79;110F 116A 11B0;CF79;110F 116A 11B0; # (콹; 콹; 콹; 콹; 콹; ) HANGUL SYLLABLE KWALG
+CF7A;CF7A;110F 116A 11B1;CF7A;110F 116A 11B1; # (콺; 콺; 콺; 콺; 콺; ) HANGUL SYLLABLE KWALM
+CF7B;CF7B;110F 116A 11B2;CF7B;110F 116A 11B2; # (콻; 콻; 콻; 콻; 콻; ) HANGUL SYLLABLE KWALB
+CF7C;CF7C;110F 116A 11B3;CF7C;110F 116A 11B3; # (콼; 콼; 콼; 콼; 콼; ) HANGUL SYLLABLE KWALS
+CF7D;CF7D;110F 116A 11B4;CF7D;110F 116A 11B4; # (콽; 콽; 콽; 콽; 콽; ) HANGUL SYLLABLE KWALT
+CF7E;CF7E;110F 116A 11B5;CF7E;110F 116A 11B5; # (콾; 콾; 콾; 콾; 콾; ) HANGUL SYLLABLE KWALP
+CF7F;CF7F;110F 116A 11B6;CF7F;110F 116A 11B6; # (콿; 콿; 콿; 콿; 콿; ) HANGUL SYLLABLE KWALH
+CF80;CF80;110F 116A 11B7;CF80;110F 116A 11B7; # (쾀; 쾀; 쾀; 쾀; 쾀; ) HANGUL SYLLABLE KWAM
+CF81;CF81;110F 116A 11B8;CF81;110F 116A 11B8; # (쾁; 쾁; 쾁; 쾁; 쾁; ) HANGUL SYLLABLE KWAB
+CF82;CF82;110F 116A 11B9;CF82;110F 116A 11B9; # (쾂; 쾂; 쾂; 쾂; 쾂; ) HANGUL SYLLABLE KWABS
+CF83;CF83;110F 116A 11BA;CF83;110F 116A 11BA; # (쾃; 쾃; 쾃; 쾃; 쾃; ) HANGUL SYLLABLE KWAS
+CF84;CF84;110F 116A 11BB;CF84;110F 116A 11BB; # (쾄; 쾄; 쾄; 쾄; 쾄; ) HANGUL SYLLABLE KWASS
+CF85;CF85;110F 116A 11BC;CF85;110F 116A 11BC; # (쾅; 쾅; 쾅; 쾅; 쾅; ) HANGUL SYLLABLE KWANG
+CF86;CF86;110F 116A 11BD;CF86;110F 116A 11BD; # (쾆; 쾆; 쾆; 쾆; 쾆; ) HANGUL SYLLABLE KWAJ
+CF87;CF87;110F 116A 11BE;CF87;110F 116A 11BE; # (쾇; 쾇; 쾇; 쾇; 쾇; ) HANGUL SYLLABLE KWAC
+CF88;CF88;110F 116A 11BF;CF88;110F 116A 11BF; # (쾈; 쾈; 쾈; 쾈; 쾈; ) HANGUL SYLLABLE KWAK
+CF89;CF89;110F 116A 11C0;CF89;110F 116A 11C0; # (쾉; 쾉; 쾉; 쾉; 쾉; ) HANGUL SYLLABLE KWAT
+CF8A;CF8A;110F 116A 11C1;CF8A;110F 116A 11C1; # (쾊; 쾊; 쾊; 쾊; 쾊; ) HANGUL SYLLABLE KWAP
+CF8B;CF8B;110F 116A 11C2;CF8B;110F 116A 11C2; # (쾋; 쾋; 쾋; 쾋; 쾋; ) HANGUL SYLLABLE KWAH
+CF8C;CF8C;110F 116B;CF8C;110F 116B; # (쾌; 쾌; 쾌; 쾌; 쾌; ) HANGUL SYLLABLE KWAE
+CF8D;CF8D;110F 116B 11A8;CF8D;110F 116B 11A8; # (쾍; 쾍; 쾍; 쾍; 쾍; ) HANGUL SYLLABLE KWAEG
+CF8E;CF8E;110F 116B 11A9;CF8E;110F 116B 11A9; # (쾎; 쾎; 쾎; 쾎; 쾎; ) HANGUL SYLLABLE KWAEGG
+CF8F;CF8F;110F 116B 11AA;CF8F;110F 116B 11AA; # (쾏; 쾏; 쾏; 쾏; 쾏; ) HANGUL SYLLABLE KWAEGS
+CF90;CF90;110F 116B 11AB;CF90;110F 116B 11AB; # (쾐; 쾐; 쾐; 쾐; 쾐; ) HANGUL SYLLABLE KWAEN
+CF91;CF91;110F 116B 11AC;CF91;110F 116B 11AC; # (쾑; 쾑; 쾑; 쾑; 쾑; ) HANGUL SYLLABLE KWAENJ
+CF92;CF92;110F 116B 11AD;CF92;110F 116B 11AD; # (쾒; 쾒; 쾒; 쾒; 쾒; ) HANGUL SYLLABLE KWAENH
+CF93;CF93;110F 116B 11AE;CF93;110F 116B 11AE; # (쾓; 쾓; 쾓; 쾓; 쾓; ) HANGUL SYLLABLE KWAED
+CF94;CF94;110F 116B 11AF;CF94;110F 116B 11AF; # (쾔; 쾔; 쾔; 쾔; 쾔; ) HANGUL SYLLABLE KWAEL
+CF95;CF95;110F 116B 11B0;CF95;110F 116B 11B0; # (쾕; 쾕; 쾕; 쾕; 쾕; ) HANGUL SYLLABLE KWAELG
+CF96;CF96;110F 116B 11B1;CF96;110F 116B 11B1; # (쾖; 쾖; 쾖; 쾖; 쾖; ) HANGUL SYLLABLE KWAELM
+CF97;CF97;110F 116B 11B2;CF97;110F 116B 11B2; # (쾗; 쾗; 쾗; 쾗; 쾗; ) HANGUL SYLLABLE KWAELB
+CF98;CF98;110F 116B 11B3;CF98;110F 116B 11B3; # (쾘; 쾘; 쾘; 쾘; 쾘; ) HANGUL SYLLABLE KWAELS
+CF99;CF99;110F 116B 11B4;CF99;110F 116B 11B4; # (쾙; 쾙; 쾙; 쾙; 쾙; ) HANGUL SYLLABLE KWAELT
+CF9A;CF9A;110F 116B 11B5;CF9A;110F 116B 11B5; # (쾚; 쾚; 쾚; 쾚; 쾚; ) HANGUL SYLLABLE KWAELP
+CF9B;CF9B;110F 116B 11B6;CF9B;110F 116B 11B6; # (쾛; 쾛; 쾛; 쾛; 쾛; ) HANGUL SYLLABLE KWAELH
+CF9C;CF9C;110F 116B 11B7;CF9C;110F 116B 11B7; # (쾜; 쾜; 쾜; 쾜; 쾜; ) HANGUL SYLLABLE KWAEM
+CF9D;CF9D;110F 116B 11B8;CF9D;110F 116B 11B8; # (쾝; 쾝; 쾝; 쾝; 쾝; ) HANGUL SYLLABLE KWAEB
+CF9E;CF9E;110F 116B 11B9;CF9E;110F 116B 11B9; # (쾞; 쾞; 쾞; 쾞; 쾞; ) HANGUL SYLLABLE KWAEBS
+CF9F;CF9F;110F 116B 11BA;CF9F;110F 116B 11BA; # (쾟; 쾟; 쾟; 쾟; 쾟; ) HANGUL SYLLABLE KWAES
+CFA0;CFA0;110F 116B 11BB;CFA0;110F 116B 11BB; # (쾠; 쾠; 쾠; 쾠; 쾠; ) HANGUL SYLLABLE KWAESS
+CFA1;CFA1;110F 116B 11BC;CFA1;110F 116B 11BC; # (쾡; 쾡; 쾡; 쾡; 쾡; ) HANGUL SYLLABLE KWAENG
+CFA2;CFA2;110F 116B 11BD;CFA2;110F 116B 11BD; # (쾢; 쾢; 쾢; 쾢; 쾢; ) HANGUL SYLLABLE KWAEJ
+CFA3;CFA3;110F 116B 11BE;CFA3;110F 116B 11BE; # (쾣; 쾣; 쾣; 쾣; 쾣; ) HANGUL SYLLABLE KWAEC
+CFA4;CFA4;110F 116B 11BF;CFA4;110F 116B 11BF; # (쾤; 쾤; 쾤; 쾤; 쾤; ) HANGUL SYLLABLE KWAEK
+CFA5;CFA5;110F 116B 11C0;CFA5;110F 116B 11C0; # (쾥; 쾥; 쾥; 쾥; 쾥; ) HANGUL SYLLABLE KWAET
+CFA6;CFA6;110F 116B 11C1;CFA6;110F 116B 11C1; # (쾦; 쾦; 쾦; 쾦; 쾦; ) HANGUL SYLLABLE KWAEP
+CFA7;CFA7;110F 116B 11C2;CFA7;110F 116B 11C2; # (쾧; 쾧; 쾧; 쾧; 쾧; ) HANGUL SYLLABLE KWAEH
+CFA8;CFA8;110F 116C;CFA8;110F 116C; # (쾨; 쾨; 쾨; 쾨; 쾨; ) HANGUL SYLLABLE KOE
+CFA9;CFA9;110F 116C 11A8;CFA9;110F 116C 11A8; # (쾩; 쾩; 쾩; 쾩; 쾩; ) HANGUL SYLLABLE KOEG
+CFAA;CFAA;110F 116C 11A9;CFAA;110F 116C 11A9; # (쾪; 쾪; 쾪; 쾪; 쾪; ) HANGUL SYLLABLE KOEGG
+CFAB;CFAB;110F 116C 11AA;CFAB;110F 116C 11AA; # (쾫; 쾫; 쾫; 쾫; 쾫; ) HANGUL SYLLABLE KOEGS
+CFAC;CFAC;110F 116C 11AB;CFAC;110F 116C 11AB; # (쾬; 쾬; 쾬; 쾬; 쾬; ) HANGUL SYLLABLE KOEN
+CFAD;CFAD;110F 116C 11AC;CFAD;110F 116C 11AC; # (쾭; 쾭; 쾭; 쾭; 쾭; ) HANGUL SYLLABLE KOENJ
+CFAE;CFAE;110F 116C 11AD;CFAE;110F 116C 11AD; # (쾮; 쾮; 쾮; 쾮; 쾮; ) HANGUL SYLLABLE KOENH
+CFAF;CFAF;110F 116C 11AE;CFAF;110F 116C 11AE; # (쾯; 쾯; 쾯; 쾯; 쾯; ) HANGUL SYLLABLE KOED
+CFB0;CFB0;110F 116C 11AF;CFB0;110F 116C 11AF; # (쾰; 쾰; 쾰; 쾰; 쾰; ) HANGUL SYLLABLE KOEL
+CFB1;CFB1;110F 116C 11B0;CFB1;110F 116C 11B0; # (쾱; 쾱; 쾱; 쾱; 쾱; ) HANGUL SYLLABLE KOELG
+CFB2;CFB2;110F 116C 11B1;CFB2;110F 116C 11B1; # (쾲; 쾲; 쾲; 쾲; 쾲; ) HANGUL SYLLABLE KOELM
+CFB3;CFB3;110F 116C 11B2;CFB3;110F 116C 11B2; # (쾳; 쾳; 쾳; 쾳; 쾳; ) HANGUL SYLLABLE KOELB
+CFB4;CFB4;110F 116C 11B3;CFB4;110F 116C 11B3; # (쾴; 쾴; 쾴; 쾴; 쾴; ) HANGUL SYLLABLE KOELS
+CFB5;CFB5;110F 116C 11B4;CFB5;110F 116C 11B4; # (쾵; 쾵; 쾵; 쾵; 쾵; ) HANGUL SYLLABLE KOELT
+CFB6;CFB6;110F 116C 11B5;CFB6;110F 116C 11B5; # (쾶; 쾶; 쾶; 쾶; 쾶; ) HANGUL SYLLABLE KOELP
+CFB7;CFB7;110F 116C 11B6;CFB7;110F 116C 11B6; # (쾷; 쾷; 쾷; 쾷; 쾷; ) HANGUL SYLLABLE KOELH
+CFB8;CFB8;110F 116C 11B7;CFB8;110F 116C 11B7; # (쾸; 쾸; 쾸; 쾸; 쾸; ) HANGUL SYLLABLE KOEM
+CFB9;CFB9;110F 116C 11B8;CFB9;110F 116C 11B8; # (쾹; 쾹; 쾹; 쾹; 쾹; ) HANGUL SYLLABLE KOEB
+CFBA;CFBA;110F 116C 11B9;CFBA;110F 116C 11B9; # (쾺; 쾺; 쾺; 쾺; 쾺; ) HANGUL SYLLABLE KOEBS
+CFBB;CFBB;110F 116C 11BA;CFBB;110F 116C 11BA; # (쾻; 쾻; 쾻; 쾻; 쾻; ) HANGUL SYLLABLE KOES
+CFBC;CFBC;110F 116C 11BB;CFBC;110F 116C 11BB; # (쾼; 쾼; 쾼; 쾼; 쾼; ) HANGUL SYLLABLE KOESS
+CFBD;CFBD;110F 116C 11BC;CFBD;110F 116C 11BC; # (쾽; 쾽; 쾽; 쾽; 쾽; ) HANGUL SYLLABLE KOENG
+CFBE;CFBE;110F 116C 11BD;CFBE;110F 116C 11BD; # (쾾; 쾾; 쾾; 쾾; 쾾; ) HANGUL SYLLABLE KOEJ
+CFBF;CFBF;110F 116C 11BE;CFBF;110F 116C 11BE; # (쾿; 쾿; 쾿; 쾿; 쾿; ) HANGUL SYLLABLE KOEC
+CFC0;CFC0;110F 116C 11BF;CFC0;110F 116C 11BF; # (쿀; 쿀; 쿀; 쿀; 쿀; ) HANGUL SYLLABLE KOEK
+CFC1;CFC1;110F 116C 11C0;CFC1;110F 116C 11C0; # (쿁; 쿁; 쿁; 쿁; 쿁; ) HANGUL SYLLABLE KOET
+CFC2;CFC2;110F 116C 11C1;CFC2;110F 116C 11C1; # (쿂; 쿂; 쿂; 쿂; 쿂; ) HANGUL SYLLABLE KOEP
+CFC3;CFC3;110F 116C 11C2;CFC3;110F 116C 11C2; # (쿃; 쿃; 쿃; 쿃; 쿃; ) HANGUL SYLLABLE KOEH
+CFC4;CFC4;110F 116D;CFC4;110F 116D; # (쿄; 쿄; 쿄; 쿄; 쿄; ) HANGUL SYLLABLE KYO
+CFC5;CFC5;110F 116D 11A8;CFC5;110F 116D 11A8; # (쿅; 쿅; 쿅; 쿅; 쿅; ) HANGUL SYLLABLE KYOG
+CFC6;CFC6;110F 116D 11A9;CFC6;110F 116D 11A9; # (쿆; 쿆; 쿆; 쿆; 쿆; ) HANGUL SYLLABLE KYOGG
+CFC7;CFC7;110F 116D 11AA;CFC7;110F 116D 11AA; # (쿇; 쿇; 쿇; 쿇; 쿇; ) HANGUL SYLLABLE KYOGS
+CFC8;CFC8;110F 116D 11AB;CFC8;110F 116D 11AB; # (쿈; 쿈; 쿈; 쿈; 쿈; ) HANGUL SYLLABLE KYON
+CFC9;CFC9;110F 116D 11AC;CFC9;110F 116D 11AC; # (쿉; 쿉; 쿉; 쿉; 쿉; ) HANGUL SYLLABLE KYONJ
+CFCA;CFCA;110F 116D 11AD;CFCA;110F 116D 11AD; # (쿊; 쿊; 쿊; 쿊; 쿊; ) HANGUL SYLLABLE KYONH
+CFCB;CFCB;110F 116D 11AE;CFCB;110F 116D 11AE; # (쿋; 쿋; 쿋; 쿋; 쿋; ) HANGUL SYLLABLE KYOD
+CFCC;CFCC;110F 116D 11AF;CFCC;110F 116D 11AF; # (쿌; 쿌; 쿌; 쿌; 쿌; ) HANGUL SYLLABLE KYOL
+CFCD;CFCD;110F 116D 11B0;CFCD;110F 116D 11B0; # (쿍; 쿍; 쿍; 쿍; 쿍; ) HANGUL SYLLABLE KYOLG
+CFCE;CFCE;110F 116D 11B1;CFCE;110F 116D 11B1; # (쿎; 쿎; 쿎; 쿎; 쿎; ) HANGUL SYLLABLE KYOLM
+CFCF;CFCF;110F 116D 11B2;CFCF;110F 116D 11B2; # (쿏; 쿏; 쿏; 쿏; 쿏; ) HANGUL SYLLABLE KYOLB
+CFD0;CFD0;110F 116D 11B3;CFD0;110F 116D 11B3; # (쿐; 쿐; 쿐; 쿐; 쿐; ) HANGUL SYLLABLE KYOLS
+CFD1;CFD1;110F 116D 11B4;CFD1;110F 116D 11B4; # (쿑; 쿑; 쿑; 쿑; 쿑; ) HANGUL SYLLABLE KYOLT
+CFD2;CFD2;110F 116D 11B5;CFD2;110F 116D 11B5; # (쿒; 쿒; 쿒; 쿒; 쿒; ) HANGUL SYLLABLE KYOLP
+CFD3;CFD3;110F 116D 11B6;CFD3;110F 116D 11B6; # (쿓; 쿓; 쿓; 쿓; 쿓; ) HANGUL SYLLABLE KYOLH
+CFD4;CFD4;110F 116D 11B7;CFD4;110F 116D 11B7; # (쿔; 쿔; 쿔; 쿔; 쿔; ) HANGUL SYLLABLE KYOM
+CFD5;CFD5;110F 116D 11B8;CFD5;110F 116D 11B8; # (쿕; 쿕; 쿕; 쿕; 쿕; ) HANGUL SYLLABLE KYOB
+CFD6;CFD6;110F 116D 11B9;CFD6;110F 116D 11B9; # (쿖; 쿖; 쿖; 쿖; 쿖; ) HANGUL SYLLABLE KYOBS
+CFD7;CFD7;110F 116D 11BA;CFD7;110F 116D 11BA; # (쿗; 쿗; 쿗; 쿗; 쿗; ) HANGUL SYLLABLE KYOS
+CFD8;CFD8;110F 116D 11BB;CFD8;110F 116D 11BB; # (쿘; 쿘; 쿘; 쿘; 쿘; ) HANGUL SYLLABLE KYOSS
+CFD9;CFD9;110F 116D 11BC;CFD9;110F 116D 11BC; # (쿙; 쿙; 쿙; 쿙; 쿙; ) HANGUL SYLLABLE KYONG
+CFDA;CFDA;110F 116D 11BD;CFDA;110F 116D 11BD; # (쿚; 쿚; 쿚; 쿚; 쿚; ) HANGUL SYLLABLE KYOJ
+CFDB;CFDB;110F 116D 11BE;CFDB;110F 116D 11BE; # (쿛; 쿛; 쿛; 쿛; 쿛; ) HANGUL SYLLABLE KYOC
+CFDC;CFDC;110F 116D 11BF;CFDC;110F 116D 11BF; # (쿜; 쿜; 쿜; 쿜; 쿜; ) HANGUL SYLLABLE KYOK
+CFDD;CFDD;110F 116D 11C0;CFDD;110F 116D 11C0; # (쿝; 쿝; 쿝; 쿝; 쿝; ) HANGUL SYLLABLE KYOT
+CFDE;CFDE;110F 116D 11C1;CFDE;110F 116D 11C1; # (쿞; 쿞; 쿞; 쿞; 쿞; ) HANGUL SYLLABLE KYOP
+CFDF;CFDF;110F 116D 11C2;CFDF;110F 116D 11C2; # (쿟; 쿟; 쿟; 쿟; 쿟; ) HANGUL SYLLABLE KYOH
+CFE0;CFE0;110F 116E;CFE0;110F 116E; # (쿠; 쿠; 쿠; 쿠; 쿠; ) HANGUL SYLLABLE KU
+CFE1;CFE1;110F 116E 11A8;CFE1;110F 116E 11A8; # (쿡; 쿡; 쿡; 쿡; 쿡; ) HANGUL SYLLABLE KUG
+CFE2;CFE2;110F 116E 11A9;CFE2;110F 116E 11A9; # (쿢; 쿢; 쿢; 쿢; 쿢; ) HANGUL SYLLABLE KUGG
+CFE3;CFE3;110F 116E 11AA;CFE3;110F 116E 11AA; # (쿣; 쿣; 쿣; 쿣; 쿣; ) HANGUL SYLLABLE KUGS
+CFE4;CFE4;110F 116E 11AB;CFE4;110F 116E 11AB; # (쿤; 쿤; 쿤; 쿤; 쿤; ) HANGUL SYLLABLE KUN
+CFE5;CFE5;110F 116E 11AC;CFE5;110F 116E 11AC; # (쿥; 쿥; 쿥; 쿥; 쿥; ) HANGUL SYLLABLE KUNJ
+CFE6;CFE6;110F 116E 11AD;CFE6;110F 116E 11AD; # (쿦; 쿦; 쿦; 쿦; 쿦; ) HANGUL SYLLABLE KUNH
+CFE7;CFE7;110F 116E 11AE;CFE7;110F 116E 11AE; # (쿧; 쿧; 쿧; 쿧; 쿧; ) HANGUL SYLLABLE KUD
+CFE8;CFE8;110F 116E 11AF;CFE8;110F 116E 11AF; # (쿨; 쿨; 쿨; 쿨; 쿨; ) HANGUL SYLLABLE KUL
+CFE9;CFE9;110F 116E 11B0;CFE9;110F 116E 11B0; # (쿩; 쿩; 쿩; 쿩; 쿩; ) HANGUL SYLLABLE KULG
+CFEA;CFEA;110F 116E 11B1;CFEA;110F 116E 11B1; # (쿪; 쿪; 쿪; 쿪; 쿪; ) HANGUL SYLLABLE KULM
+CFEB;CFEB;110F 116E 11B2;CFEB;110F 116E 11B2; # (쿫; 쿫; 쿫; 쿫; 쿫; ) HANGUL SYLLABLE KULB
+CFEC;CFEC;110F 116E 11B3;CFEC;110F 116E 11B3; # (쿬; 쿬; 쿬; 쿬; 쿬; ) HANGUL SYLLABLE KULS
+CFED;CFED;110F 116E 11B4;CFED;110F 116E 11B4; # (쿭; 쿭; 쿭; 쿭; 쿭; ) HANGUL SYLLABLE KULT
+CFEE;CFEE;110F 116E 11B5;CFEE;110F 116E 11B5; # (쿮; 쿮; 쿮; 쿮; 쿮; ) HANGUL SYLLABLE KULP
+CFEF;CFEF;110F 116E 11B6;CFEF;110F 116E 11B6; # (쿯; 쿯; 쿯; 쿯; 쿯; ) HANGUL SYLLABLE KULH
+CFF0;CFF0;110F 116E 11B7;CFF0;110F 116E 11B7; # (쿰; 쿰; 쿰; 쿰; 쿰; ) HANGUL SYLLABLE KUM
+CFF1;CFF1;110F 116E 11B8;CFF1;110F 116E 11B8; # (쿱; 쿱; 쿱; 쿱; 쿱; ) HANGUL SYLLABLE KUB
+CFF2;CFF2;110F 116E 11B9;CFF2;110F 116E 11B9; # (쿲; 쿲; 쿲; 쿲; 쿲; ) HANGUL SYLLABLE KUBS
+CFF3;CFF3;110F 116E 11BA;CFF3;110F 116E 11BA; # (쿳; 쿳; 쿳; 쿳; 쿳; ) HANGUL SYLLABLE KUS
+CFF4;CFF4;110F 116E 11BB;CFF4;110F 116E 11BB; # (쿴; 쿴; 쿴; 쿴; 쿴; ) HANGUL SYLLABLE KUSS
+CFF5;CFF5;110F 116E 11BC;CFF5;110F 116E 11BC; # (쿵; 쿵; 쿵; 쿵; 쿵; ) HANGUL SYLLABLE KUNG
+CFF6;CFF6;110F 116E 11BD;CFF6;110F 116E 11BD; # (쿶; 쿶; 쿶; 쿶; 쿶; ) HANGUL SYLLABLE KUJ
+CFF7;CFF7;110F 116E 11BE;CFF7;110F 116E 11BE; # (쿷; 쿷; 쿷; 쿷; 쿷; ) HANGUL SYLLABLE KUC
+CFF8;CFF8;110F 116E 11BF;CFF8;110F 116E 11BF; # (쿸; 쿸; 쿸; 쿸; 쿸; ) HANGUL SYLLABLE KUK
+CFF9;CFF9;110F 116E 11C0;CFF9;110F 116E 11C0; # (쿹; 쿹; 쿹; 쿹; 쿹; ) HANGUL SYLLABLE KUT
+CFFA;CFFA;110F 116E 11C1;CFFA;110F 116E 11C1; # (쿺; 쿺; 쿺; 쿺; 쿺; ) HANGUL SYLLABLE KUP
+CFFB;CFFB;110F 116E 11C2;CFFB;110F 116E 11C2; # (쿻; 쿻; 쿻; 쿻; 쿻; ) HANGUL SYLLABLE KUH
+CFFC;CFFC;110F 116F;CFFC;110F 116F; # (쿼; 쿼; 쿼; 쿼; 쿼; ) HANGUL SYLLABLE KWEO
+CFFD;CFFD;110F 116F 11A8;CFFD;110F 116F 11A8; # (쿽; 쿽; 쿽; 쿽; 쿽; ) HANGUL SYLLABLE KWEOG
+CFFE;CFFE;110F 116F 11A9;CFFE;110F 116F 11A9; # (쿾; 쿾; 쿾; 쿾; 쿾; ) HANGUL SYLLABLE KWEOGG
+CFFF;CFFF;110F 116F 11AA;CFFF;110F 116F 11AA; # (쿿; 쿿; 쿿; 쿿; 쿿; ) HANGUL SYLLABLE KWEOGS
+D000;D000;110F 116F 11AB;D000;110F 116F 11AB; # (퀀; 퀀; 퀀; 퀀; 퀀; ) HANGUL SYLLABLE KWEON
+D001;D001;110F 116F 11AC;D001;110F 116F 11AC; # (퀁; 퀁; 퀁; 퀁; 퀁; ) HANGUL SYLLABLE KWEONJ
+D002;D002;110F 116F 11AD;D002;110F 116F 11AD; # (퀂; 퀂; 퀂; 퀂; 퀂; ) HANGUL SYLLABLE KWEONH
+D003;D003;110F 116F 11AE;D003;110F 116F 11AE; # (퀃; 퀃; 퀃; 퀃; 퀃; ) HANGUL SYLLABLE KWEOD
+D004;D004;110F 116F 11AF;D004;110F 116F 11AF; # (퀄; 퀄; 퀄; 퀄; 퀄; ) HANGUL SYLLABLE KWEOL
+D005;D005;110F 116F 11B0;D005;110F 116F 11B0; # (퀅; 퀅; 퀅; 퀅; 퀅; ) HANGUL SYLLABLE KWEOLG
+D006;D006;110F 116F 11B1;D006;110F 116F 11B1; # (퀆; 퀆; 퀆; 퀆; 퀆; ) HANGUL SYLLABLE KWEOLM
+D007;D007;110F 116F 11B2;D007;110F 116F 11B2; # (퀇; 퀇; 퀇; 퀇; 퀇; ) HANGUL SYLLABLE KWEOLB
+D008;D008;110F 116F 11B3;D008;110F 116F 11B3; # (퀈; 퀈; 퀈; 퀈; 퀈; ) HANGUL SYLLABLE KWEOLS
+D009;D009;110F 116F 11B4;D009;110F 116F 11B4; # (퀉; 퀉; 퀉; 퀉; 퀉; ) HANGUL SYLLABLE KWEOLT
+D00A;D00A;110F 116F 11B5;D00A;110F 116F 11B5; # (퀊; 퀊; 퀊; 퀊; 퀊; ) HANGUL SYLLABLE KWEOLP
+D00B;D00B;110F 116F 11B6;D00B;110F 116F 11B6; # (퀋; 퀋; 퀋; 퀋; 퀋; ) HANGUL SYLLABLE KWEOLH
+D00C;D00C;110F 116F 11B7;D00C;110F 116F 11B7; # (퀌; 퀌; 퀌; 퀌; 퀌; ) HANGUL SYLLABLE KWEOM
+D00D;D00D;110F 116F 11B8;D00D;110F 116F 11B8; # (퀍; 퀍; 퀍; 퀍; 퀍; ) HANGUL SYLLABLE KWEOB
+D00E;D00E;110F 116F 11B9;D00E;110F 116F 11B9; # (퀎; 퀎; 퀎; 퀎; 퀎; ) HANGUL SYLLABLE KWEOBS
+D00F;D00F;110F 116F 11BA;D00F;110F 116F 11BA; # (퀏; 퀏; 퀏; 퀏; 퀏; ) HANGUL SYLLABLE KWEOS
+D010;D010;110F 116F 11BB;D010;110F 116F 11BB; # (퀐; 퀐; 퀐; 퀐; 퀐; ) HANGUL SYLLABLE KWEOSS
+D011;D011;110F 116F 11BC;D011;110F 116F 11BC; # (퀑; 퀑; 퀑; 퀑; 퀑; ) HANGUL SYLLABLE KWEONG
+D012;D012;110F 116F 11BD;D012;110F 116F 11BD; # (퀒; 퀒; 퀒; 퀒; 퀒; ) HANGUL SYLLABLE KWEOJ
+D013;D013;110F 116F 11BE;D013;110F 116F 11BE; # (퀓; 퀓; 퀓; 퀓; 퀓; ) HANGUL SYLLABLE KWEOC
+D014;D014;110F 116F 11BF;D014;110F 116F 11BF; # (퀔; 퀔; 퀔; 퀔; 퀔; ) HANGUL SYLLABLE KWEOK
+D015;D015;110F 116F 11C0;D015;110F 116F 11C0; # (퀕; 퀕; 퀕; 퀕; 퀕; ) HANGUL SYLLABLE KWEOT
+D016;D016;110F 116F 11C1;D016;110F 116F 11C1; # (퀖; 퀖; 퀖; 퀖; 퀖; ) HANGUL SYLLABLE KWEOP
+D017;D017;110F 116F 11C2;D017;110F 116F 11C2; # (퀗; 퀗; 퀗; 퀗; 퀗; ) HANGUL SYLLABLE KWEOH
+D018;D018;110F 1170;D018;110F 1170; # (퀘; 퀘; 퀘; 퀘; 퀘; ) HANGUL SYLLABLE KWE
+D019;D019;110F 1170 11A8;D019;110F 1170 11A8; # (퀙; 퀙; 퀙; 퀙; 퀙; ) HANGUL SYLLABLE KWEG
+D01A;D01A;110F 1170 11A9;D01A;110F 1170 11A9; # (퀚; 퀚; 퀚; 퀚; 퀚; ) HANGUL SYLLABLE KWEGG
+D01B;D01B;110F 1170 11AA;D01B;110F 1170 11AA; # (퀛; 퀛; 퀛; 퀛; 퀛; ) HANGUL SYLLABLE KWEGS
+D01C;D01C;110F 1170 11AB;D01C;110F 1170 11AB; # (퀜; 퀜; 퀜; 퀜; 퀜; ) HANGUL SYLLABLE KWEN
+D01D;D01D;110F 1170 11AC;D01D;110F 1170 11AC; # (퀝; 퀝; 퀝; 퀝; 퀝; ) HANGUL SYLLABLE KWENJ
+D01E;D01E;110F 1170 11AD;D01E;110F 1170 11AD; # (퀞; 퀞; 퀞; 퀞; 퀞; ) HANGUL SYLLABLE KWENH
+D01F;D01F;110F 1170 11AE;D01F;110F 1170 11AE; # (퀟; 퀟; 퀟; 퀟; 퀟; ) HANGUL SYLLABLE KWED
+D020;D020;110F 1170 11AF;D020;110F 1170 11AF; # (퀠; 퀠; 퀠; 퀠; 퀠; ) HANGUL SYLLABLE KWEL
+D021;D021;110F 1170 11B0;D021;110F 1170 11B0; # (퀡; 퀡; 퀡; 퀡; 퀡; ) HANGUL SYLLABLE KWELG
+D022;D022;110F 1170 11B1;D022;110F 1170 11B1; # (퀢; 퀢; 퀢; 퀢; 퀢; ) HANGUL SYLLABLE KWELM
+D023;D023;110F 1170 11B2;D023;110F 1170 11B2; # (퀣; 퀣; 퀣; 퀣; 퀣; ) HANGUL SYLLABLE KWELB
+D024;D024;110F 1170 11B3;D024;110F 1170 11B3; # (퀤; 퀤; 퀤; 퀤; 퀤; ) HANGUL SYLLABLE KWELS
+D025;D025;110F 1170 11B4;D025;110F 1170 11B4; # (퀥; 퀥; 퀥; 퀥; 퀥; ) HANGUL SYLLABLE KWELT
+D026;D026;110F 1170 11B5;D026;110F 1170 11B5; # (퀦; 퀦; 퀦; 퀦; 퀦; ) HANGUL SYLLABLE KWELP
+D027;D027;110F 1170 11B6;D027;110F 1170 11B6; # (퀧; 퀧; 퀧; 퀧; 퀧; ) HANGUL SYLLABLE KWELH
+D028;D028;110F 1170 11B7;D028;110F 1170 11B7; # (퀨; 퀨; 퀨; 퀨; 퀨; ) HANGUL SYLLABLE KWEM
+D029;D029;110F 1170 11B8;D029;110F 1170 11B8; # (퀩; 퀩; 퀩; 퀩; 퀩; ) HANGUL SYLLABLE KWEB
+D02A;D02A;110F 1170 11B9;D02A;110F 1170 11B9; # (퀪; 퀪; 퀪; 퀪; 퀪; ) HANGUL SYLLABLE KWEBS
+D02B;D02B;110F 1170 11BA;D02B;110F 1170 11BA; # (퀫; 퀫; 퀫; 퀫; 퀫; ) HANGUL SYLLABLE KWES
+D02C;D02C;110F 1170 11BB;D02C;110F 1170 11BB; # (퀬; 퀬; 퀬; 퀬; 퀬; ) HANGUL SYLLABLE KWESS
+D02D;D02D;110F 1170 11BC;D02D;110F 1170 11BC; # (퀭; 퀭; 퀭; 퀭; 퀭; ) HANGUL SYLLABLE KWENG
+D02E;D02E;110F 1170 11BD;D02E;110F 1170 11BD; # (퀮; 퀮; 퀮; 퀮; 퀮; ) HANGUL SYLLABLE KWEJ
+D02F;D02F;110F 1170 11BE;D02F;110F 1170 11BE; # (퀯; 퀯; 퀯; 퀯; 퀯; ) HANGUL SYLLABLE KWEC
+D030;D030;110F 1170 11BF;D030;110F 1170 11BF; # (퀰; 퀰; 퀰; 퀰; 퀰; ) HANGUL SYLLABLE KWEK
+D031;D031;110F 1170 11C0;D031;110F 1170 11C0; # (퀱; 퀱; 퀱; 퀱; 퀱; ) HANGUL SYLLABLE KWET
+D032;D032;110F 1170 11C1;D032;110F 1170 11C1; # (퀲; 퀲; 퀲; 퀲; 퀲; ) HANGUL SYLLABLE KWEP
+D033;D033;110F 1170 11C2;D033;110F 1170 11C2; # (퀳; 퀳; 퀳; 퀳; 퀳; ) HANGUL SYLLABLE KWEH
+D034;D034;110F 1171;D034;110F 1171; # (퀴; 퀴; 퀴; 퀴; 퀴; ) HANGUL SYLLABLE KWI
+D035;D035;110F 1171 11A8;D035;110F 1171 11A8; # (퀵; 퀵; 퀵; 퀵; 퀵; ) HANGUL SYLLABLE KWIG
+D036;D036;110F 1171 11A9;D036;110F 1171 11A9; # (퀶; 퀶; 퀶; 퀶; 퀶; ) HANGUL SYLLABLE KWIGG
+D037;D037;110F 1171 11AA;D037;110F 1171 11AA; # (퀷; 퀷; 퀷; 퀷; 퀷; ) HANGUL SYLLABLE KWIGS
+D038;D038;110F 1171 11AB;D038;110F 1171 11AB; # (퀸; 퀸; 퀸; 퀸; 퀸; ) HANGUL SYLLABLE KWIN
+D039;D039;110F 1171 11AC;D039;110F 1171 11AC; # (퀹; 퀹; 퀹; 퀹; 퀹; ) HANGUL SYLLABLE KWINJ
+D03A;D03A;110F 1171 11AD;D03A;110F 1171 11AD; # (퀺; 퀺; 퀺; 퀺; 퀺; ) HANGUL SYLLABLE KWINH
+D03B;D03B;110F 1171 11AE;D03B;110F 1171 11AE; # (퀻; 퀻; 퀻; 퀻; 퀻; ) HANGUL SYLLABLE KWID
+D03C;D03C;110F 1171 11AF;D03C;110F 1171 11AF; # (퀼; 퀼; 퀼; 퀼; 퀼; ) HANGUL SYLLABLE KWIL
+D03D;D03D;110F 1171 11B0;D03D;110F 1171 11B0; # (퀽; 퀽; 퀽; 퀽; 퀽; ) HANGUL SYLLABLE KWILG
+D03E;D03E;110F 1171 11B1;D03E;110F 1171 11B1; # (퀾; 퀾; 퀾; 퀾; 퀾; ) HANGUL SYLLABLE KWILM
+D03F;D03F;110F 1171 11B2;D03F;110F 1171 11B2; # (퀿; 퀿; 퀿; 퀿; 퀿; ) HANGUL SYLLABLE KWILB
+D040;D040;110F 1171 11B3;D040;110F 1171 11B3; # (큀; 큀; 큀; 큀; 큀; ) HANGUL SYLLABLE KWILS
+D041;D041;110F 1171 11B4;D041;110F 1171 11B4; # (큁; 큁; 큁; 큁; 큁; ) HANGUL SYLLABLE KWILT
+D042;D042;110F 1171 11B5;D042;110F 1171 11B5; # (큂; 큂; 큂; 큂; 큂; ) HANGUL SYLLABLE KWILP
+D043;D043;110F 1171 11B6;D043;110F 1171 11B6; # (큃; 큃; 큃; 큃; 큃; ) HANGUL SYLLABLE KWILH
+D044;D044;110F 1171 11B7;D044;110F 1171 11B7; # (큄; 큄; 큄; 큄; 큄; ) HANGUL SYLLABLE KWIM
+D045;D045;110F 1171 11B8;D045;110F 1171 11B8; # (큅; 큅; 큅; 큅; 큅; ) HANGUL SYLLABLE KWIB
+D046;D046;110F 1171 11B9;D046;110F 1171 11B9; # (큆; 큆; 큆; 큆; 큆; ) HANGUL SYLLABLE KWIBS
+D047;D047;110F 1171 11BA;D047;110F 1171 11BA; # (큇; 큇; 큇; 큇; 큇; ) HANGUL SYLLABLE KWIS
+D048;D048;110F 1171 11BB;D048;110F 1171 11BB; # (큈; 큈; 큈; 큈; 큈; ) HANGUL SYLLABLE KWISS
+D049;D049;110F 1171 11BC;D049;110F 1171 11BC; # (큉; 큉; 큉; 큉; 큉; ) HANGUL SYLLABLE KWING
+D04A;D04A;110F 1171 11BD;D04A;110F 1171 11BD; # (큊; 큊; 큊; 큊; 큊; ) HANGUL SYLLABLE KWIJ
+D04B;D04B;110F 1171 11BE;D04B;110F 1171 11BE; # (큋; 큋; 큋; 큋; 큋; ) HANGUL SYLLABLE KWIC
+D04C;D04C;110F 1171 11BF;D04C;110F 1171 11BF; # (큌; 큌; 큌; 큌; 큌; ) HANGUL SYLLABLE KWIK
+D04D;D04D;110F 1171 11C0;D04D;110F 1171 11C0; # (큍; 큍; 큍; 큍; 큍; ) HANGUL SYLLABLE KWIT
+D04E;D04E;110F 1171 11C1;D04E;110F 1171 11C1; # (큎; 큎; 큎; 큎; 큎; ) HANGUL SYLLABLE KWIP
+D04F;D04F;110F 1171 11C2;D04F;110F 1171 11C2; # (큏; 큏; 큏; 큏; 큏; ) HANGUL SYLLABLE KWIH
+D050;D050;110F 1172;D050;110F 1172; # (큐; 큐; 큐; 큐; 큐; ) HANGUL SYLLABLE KYU
+D051;D051;110F 1172 11A8;D051;110F 1172 11A8; # (큑; 큑; 큑; 큑; 큑; ) HANGUL SYLLABLE KYUG
+D052;D052;110F 1172 11A9;D052;110F 1172 11A9; # (큒; 큒; 큒; 큒; 큒; ) HANGUL SYLLABLE KYUGG
+D053;D053;110F 1172 11AA;D053;110F 1172 11AA; # (큓; 큓; 큓; 큓; 큓; ) HANGUL SYLLABLE KYUGS
+D054;D054;110F 1172 11AB;D054;110F 1172 11AB; # (큔; 큔; 큔; 큔; 큔; ) HANGUL SYLLABLE KYUN
+D055;D055;110F 1172 11AC;D055;110F 1172 11AC; # (큕; 큕; 큕; 큕; 큕; ) HANGUL SYLLABLE KYUNJ
+D056;D056;110F 1172 11AD;D056;110F 1172 11AD; # (큖; 큖; 큖; 큖; 큖; ) HANGUL SYLLABLE KYUNH
+D057;D057;110F 1172 11AE;D057;110F 1172 11AE; # (큗; 큗; 큗; 큗; 큗; ) HANGUL SYLLABLE KYUD
+D058;D058;110F 1172 11AF;D058;110F 1172 11AF; # (큘; 큘; 큘; 큘; 큘; ) HANGUL SYLLABLE KYUL
+D059;D059;110F 1172 11B0;D059;110F 1172 11B0; # (큙; 큙; 큙; 큙; 큙; ) HANGUL SYLLABLE KYULG
+D05A;D05A;110F 1172 11B1;D05A;110F 1172 11B1; # (큚; 큚; 큚; 큚; 큚; ) HANGUL SYLLABLE KYULM
+D05B;D05B;110F 1172 11B2;D05B;110F 1172 11B2; # (큛; 큛; 큛; 큛; 큛; ) HANGUL SYLLABLE KYULB
+D05C;D05C;110F 1172 11B3;D05C;110F 1172 11B3; # (큜; 큜; 큜; 큜; 큜; ) HANGUL SYLLABLE KYULS
+D05D;D05D;110F 1172 11B4;D05D;110F 1172 11B4; # (큝; 큝; 큝; 큝; 큝; ) HANGUL SYLLABLE KYULT
+D05E;D05E;110F 1172 11B5;D05E;110F 1172 11B5; # (큞; 큞; 큞; 큞; 큞; ) HANGUL SYLLABLE KYULP
+D05F;D05F;110F 1172 11B6;D05F;110F 1172 11B6; # (큟; 큟; 큟; 큟; 큟; ) HANGUL SYLLABLE KYULH
+D060;D060;110F 1172 11B7;D060;110F 1172 11B7; # (큠; 큠; 큠; 큠; 큠; ) HANGUL SYLLABLE KYUM
+D061;D061;110F 1172 11B8;D061;110F 1172 11B8; # (큡; 큡; 큡; 큡; 큡; ) HANGUL SYLLABLE KYUB
+D062;D062;110F 1172 11B9;D062;110F 1172 11B9; # (큢; 큢; 큢; 큢; 큢; ) HANGUL SYLLABLE KYUBS
+D063;D063;110F 1172 11BA;D063;110F 1172 11BA; # (큣; 큣; 큣; 큣; 큣; ) HANGUL SYLLABLE KYUS
+D064;D064;110F 1172 11BB;D064;110F 1172 11BB; # (큤; 큤; 큤; 큤; 큤; ) HANGUL SYLLABLE KYUSS
+D065;D065;110F 1172 11BC;D065;110F 1172 11BC; # (큥; 큥; 큥; 큥; 큥; ) HANGUL SYLLABLE KYUNG
+D066;D066;110F 1172 11BD;D066;110F 1172 11BD; # (큦; 큦; 큦; 큦; 큦; ) HANGUL SYLLABLE KYUJ
+D067;D067;110F 1172 11BE;D067;110F 1172 11BE; # (큧; 큧; 큧; 큧; 큧; ) HANGUL SYLLABLE KYUC
+D068;D068;110F 1172 11BF;D068;110F 1172 11BF; # (큨; 큨; 큨; 큨; 큨; ) HANGUL SYLLABLE KYUK
+D069;D069;110F 1172 11C0;D069;110F 1172 11C0; # (큩; 큩; 큩; 큩; 큩; ) HANGUL SYLLABLE KYUT
+D06A;D06A;110F 1172 11C1;D06A;110F 1172 11C1; # (큪; 큪; 큪; 큪; 큪; ) HANGUL SYLLABLE KYUP
+D06B;D06B;110F 1172 11C2;D06B;110F 1172 11C2; # (큫; 큫; 큫; 큫; 큫; ) HANGUL SYLLABLE KYUH
+D06C;D06C;110F 1173;D06C;110F 1173; # (크; 크; 크; 크; 크; ) HANGUL SYLLABLE KEU
+D06D;D06D;110F 1173 11A8;D06D;110F 1173 11A8; # (큭; 큭; 큭; 큭; 큭; ) HANGUL SYLLABLE KEUG
+D06E;D06E;110F 1173 11A9;D06E;110F 1173 11A9; # (큮; 큮; 큮; 큮; 큮; ) HANGUL SYLLABLE KEUGG
+D06F;D06F;110F 1173 11AA;D06F;110F 1173 11AA; # (큯; 큯; 큯; 큯; 큯; ) HANGUL SYLLABLE KEUGS
+D070;D070;110F 1173 11AB;D070;110F 1173 11AB; # (큰; 큰; 큰; 큰; 큰; ) HANGUL SYLLABLE KEUN
+D071;D071;110F 1173 11AC;D071;110F 1173 11AC; # (큱; 큱; 큱; 큱; 큱; ) HANGUL SYLLABLE KEUNJ
+D072;D072;110F 1173 11AD;D072;110F 1173 11AD; # (큲; 큲; 큲; 큲; 큲; ) HANGUL SYLLABLE KEUNH
+D073;D073;110F 1173 11AE;D073;110F 1173 11AE; # (큳; 큳; 큳; 큳; 큳; ) HANGUL SYLLABLE KEUD
+D074;D074;110F 1173 11AF;D074;110F 1173 11AF; # (클; 클; 클; 클; 클; ) HANGUL SYLLABLE KEUL
+D075;D075;110F 1173 11B0;D075;110F 1173 11B0; # (큵; 큵; 큵; 큵; 큵; ) HANGUL SYLLABLE KEULG
+D076;D076;110F 1173 11B1;D076;110F 1173 11B1; # (큶; 큶; 큶; 큶; 큶; ) HANGUL SYLLABLE KEULM
+D077;D077;110F 1173 11B2;D077;110F 1173 11B2; # (큷; 큷; 큷; 큷; 큷; ) HANGUL SYLLABLE KEULB
+D078;D078;110F 1173 11B3;D078;110F 1173 11B3; # (큸; 큸; 큸; 큸; 큸; ) HANGUL SYLLABLE KEULS
+D079;D079;110F 1173 11B4;D079;110F 1173 11B4; # (큹; 큹; 큹; 큹; 큹; ) HANGUL SYLLABLE KEULT
+D07A;D07A;110F 1173 11B5;D07A;110F 1173 11B5; # (큺; 큺; 큺; 큺; 큺; ) HANGUL SYLLABLE KEULP
+D07B;D07B;110F 1173 11B6;D07B;110F 1173 11B6; # (큻; 큻; 큻; 큻; 큻; ) HANGUL SYLLABLE KEULH
+D07C;D07C;110F 1173 11B7;D07C;110F 1173 11B7; # (큼; 큼; 큼; 큼; 큼; ) HANGUL SYLLABLE KEUM
+D07D;D07D;110F 1173 11B8;D07D;110F 1173 11B8; # (큽; 큽; 큽; 큽; 큽; ) HANGUL SYLLABLE KEUB
+D07E;D07E;110F 1173 11B9;D07E;110F 1173 11B9; # (큾; 큾; 큾; 큾; 큾; ) HANGUL SYLLABLE KEUBS
+D07F;D07F;110F 1173 11BA;D07F;110F 1173 11BA; # (큿; 큿; 큿; 큿; 큿; ) HANGUL SYLLABLE KEUS
+D080;D080;110F 1173 11BB;D080;110F 1173 11BB; # (킀; 킀; 킀; 킀; 킀; ) HANGUL SYLLABLE KEUSS
+D081;D081;110F 1173 11BC;D081;110F 1173 11BC; # (킁; 킁; 킁; 킁; 킁; ) HANGUL SYLLABLE KEUNG
+D082;D082;110F 1173 11BD;D082;110F 1173 11BD; # (킂; 킂; 킂; 킂; 킂; ) HANGUL SYLLABLE KEUJ
+D083;D083;110F 1173 11BE;D083;110F 1173 11BE; # (킃; 킃; 킃; 킃; 킃; ) HANGUL SYLLABLE KEUC
+D084;D084;110F 1173 11BF;D084;110F 1173 11BF; # (킄; 킄; 킄; 킄; 킄; ) HANGUL SYLLABLE KEUK
+D085;D085;110F 1173 11C0;D085;110F 1173 11C0; # (킅; 킅; 킅; 킅; 킅; ) HANGUL SYLLABLE KEUT
+D086;D086;110F 1173 11C1;D086;110F 1173 11C1; # (킆; 킆; 킆; 킆; 킆; ) HANGUL SYLLABLE KEUP
+D087;D087;110F 1173 11C2;D087;110F 1173 11C2; # (킇; 킇; 킇; 킇; 킇; ) HANGUL SYLLABLE KEUH
+D088;D088;110F 1174;D088;110F 1174; # (킈; 킈; 킈; 킈; 킈; ) HANGUL SYLLABLE KYI
+D089;D089;110F 1174 11A8;D089;110F 1174 11A8; # (킉; 킉; 킉; 킉; 킉; ) HANGUL SYLLABLE KYIG
+D08A;D08A;110F 1174 11A9;D08A;110F 1174 11A9; # (킊; 킊; 킊; 킊; 킊; ) HANGUL SYLLABLE KYIGG
+D08B;D08B;110F 1174 11AA;D08B;110F 1174 11AA; # (킋; 킋; 킋; 킋; 킋; ) HANGUL SYLLABLE KYIGS
+D08C;D08C;110F 1174 11AB;D08C;110F 1174 11AB; # (킌; 킌; 킌; 킌; 킌; ) HANGUL SYLLABLE KYIN
+D08D;D08D;110F 1174 11AC;D08D;110F 1174 11AC; # (킍; 킍; 킍; 킍; 킍; ) HANGUL SYLLABLE KYINJ
+D08E;D08E;110F 1174 11AD;D08E;110F 1174 11AD; # (킎; 킎; 킎; 킎; 킎; ) HANGUL SYLLABLE KYINH
+D08F;D08F;110F 1174 11AE;D08F;110F 1174 11AE; # (킏; 킏; 킏; 킏; 킏; ) HANGUL SYLLABLE KYID
+D090;D090;110F 1174 11AF;D090;110F 1174 11AF; # (킐; 킐; 킐; 킐; 킐; ) HANGUL SYLLABLE KYIL
+D091;D091;110F 1174 11B0;D091;110F 1174 11B0; # (킑; 킑; 킑; 킑; 킑; ) HANGUL SYLLABLE KYILG
+D092;D092;110F 1174 11B1;D092;110F 1174 11B1; # (킒; 킒; 킒; 킒; 킒; ) HANGUL SYLLABLE KYILM
+D093;D093;110F 1174 11B2;D093;110F 1174 11B2; # (킓; 킓; 킓; 킓; 킓; ) HANGUL SYLLABLE KYILB
+D094;D094;110F 1174 11B3;D094;110F 1174 11B3; # (킔; 킔; 킔; 킔; 킔; ) HANGUL SYLLABLE KYILS
+D095;D095;110F 1174 11B4;D095;110F 1174 11B4; # (킕; 킕; 킕; 킕; 킕; ) HANGUL SYLLABLE KYILT
+D096;D096;110F 1174 11B5;D096;110F 1174 11B5; # (킖; 킖; 킖; 킖; 킖; ) HANGUL SYLLABLE KYILP
+D097;D097;110F 1174 11B6;D097;110F 1174 11B6; # (킗; 킗; 킗; 킗; 킗; ) HANGUL SYLLABLE KYILH
+D098;D098;110F 1174 11B7;D098;110F 1174 11B7; # (킘; 킘; 킘; 킘; 킘; ) HANGUL SYLLABLE KYIM
+D099;D099;110F 1174 11B8;D099;110F 1174 11B8; # (킙; 킙; 킙; 킙; 킙; ) HANGUL SYLLABLE KYIB
+D09A;D09A;110F 1174 11B9;D09A;110F 1174 11B9; # (킚; 킚; 킚; 킚; 킚; ) HANGUL SYLLABLE KYIBS
+D09B;D09B;110F 1174 11BA;D09B;110F 1174 11BA; # (킛; 킛; 킛; 킛; 킛; ) HANGUL SYLLABLE KYIS
+D09C;D09C;110F 1174 11BB;D09C;110F 1174 11BB; # (킜; 킜; 킜; 킜; 킜; ) HANGUL SYLLABLE KYISS
+D09D;D09D;110F 1174 11BC;D09D;110F 1174 11BC; # (킝; 킝; 킝; 킝; 킝; ) HANGUL SYLLABLE KYING
+D09E;D09E;110F 1174 11BD;D09E;110F 1174 11BD; # (킞; 킞; 킞; 킞; 킞; ) HANGUL SYLLABLE KYIJ
+D09F;D09F;110F 1174 11BE;D09F;110F 1174 11BE; # (킟; 킟; 킟; 킟; 킟; ) HANGUL SYLLABLE KYIC
+D0A0;D0A0;110F 1174 11BF;D0A0;110F 1174 11BF; # (킠; 킠; 킠; 킠; 킠; ) HANGUL SYLLABLE KYIK
+D0A1;D0A1;110F 1174 11C0;D0A1;110F 1174 11C0; # (킡; 킡; 킡; 킡; 킡; ) HANGUL SYLLABLE KYIT
+D0A2;D0A2;110F 1174 11C1;D0A2;110F 1174 11C1; # (킢; 킢; 킢; 킢; 킢; ) HANGUL SYLLABLE KYIP
+D0A3;D0A3;110F 1174 11C2;D0A3;110F 1174 11C2; # (킣; 킣; 킣; 킣; 킣; ) HANGUL SYLLABLE KYIH
+D0A4;D0A4;110F 1175;D0A4;110F 1175; # (키; 키; 키; 키; 키; ) HANGUL SYLLABLE KI
+D0A5;D0A5;110F 1175 11A8;D0A5;110F 1175 11A8; # (킥; 킥; 킥; 킥; 킥; ) HANGUL SYLLABLE KIG
+D0A6;D0A6;110F 1175 11A9;D0A6;110F 1175 11A9; # (킦; 킦; 킦; 킦; 킦; ) HANGUL SYLLABLE KIGG
+D0A7;D0A7;110F 1175 11AA;D0A7;110F 1175 11AA; # (킧; 킧; 킧; 킧; 킧; ) HANGUL SYLLABLE KIGS
+D0A8;D0A8;110F 1175 11AB;D0A8;110F 1175 11AB; # (킨; 킨; 킨; 킨; 킨; ) HANGUL SYLLABLE KIN
+D0A9;D0A9;110F 1175 11AC;D0A9;110F 1175 11AC; # (킩; 킩; 킩; 킩; 킩; ) HANGUL SYLLABLE KINJ
+D0AA;D0AA;110F 1175 11AD;D0AA;110F 1175 11AD; # (킪; 킪; 킪; 킪; 킪; ) HANGUL SYLLABLE KINH
+D0AB;D0AB;110F 1175 11AE;D0AB;110F 1175 11AE; # (킫; 킫; 킫; 킫; 킫; ) HANGUL SYLLABLE KID
+D0AC;D0AC;110F 1175 11AF;D0AC;110F 1175 11AF; # (킬; 킬; 킬; 킬; 킬; ) HANGUL SYLLABLE KIL
+D0AD;D0AD;110F 1175 11B0;D0AD;110F 1175 11B0; # (킭; 킭; 킭; 킭; 킭; ) HANGUL SYLLABLE KILG
+D0AE;D0AE;110F 1175 11B1;D0AE;110F 1175 11B1; # (킮; 킮; 킮; 킮; 킮; ) HANGUL SYLLABLE KILM
+D0AF;D0AF;110F 1175 11B2;D0AF;110F 1175 11B2; # (킯; 킯; 킯; 킯; 킯; ) HANGUL SYLLABLE KILB
+D0B0;D0B0;110F 1175 11B3;D0B0;110F 1175 11B3; # (킰; 킰; 킰; 킰; 킰; ) HANGUL SYLLABLE KILS
+D0B1;D0B1;110F 1175 11B4;D0B1;110F 1175 11B4; # (킱; 킱; 킱; 킱; 킱; ) HANGUL SYLLABLE KILT
+D0B2;D0B2;110F 1175 11B5;D0B2;110F 1175 11B5; # (킲; 킲; 킲; 킲; 킲; ) HANGUL SYLLABLE KILP
+D0B3;D0B3;110F 1175 11B6;D0B3;110F 1175 11B6; # (킳; 킳; 킳; 킳; 킳; ) HANGUL SYLLABLE KILH
+D0B4;D0B4;110F 1175 11B7;D0B4;110F 1175 11B7; # (킴; 킴; 킴; 킴; 킴; ) HANGUL SYLLABLE KIM
+D0B5;D0B5;110F 1175 11B8;D0B5;110F 1175 11B8; # (킵; 킵; 킵; 킵; 킵; ) HANGUL SYLLABLE KIB
+D0B6;D0B6;110F 1175 11B9;D0B6;110F 1175 11B9; # (킶; 킶; 킶; 킶; 킶; ) HANGUL SYLLABLE KIBS
+D0B7;D0B7;110F 1175 11BA;D0B7;110F 1175 11BA; # (킷; 킷; 킷; 킷; 킷; ) HANGUL SYLLABLE KIS
+D0B8;D0B8;110F 1175 11BB;D0B8;110F 1175 11BB; # (킸; 킸; 킸; 킸; 킸; ) HANGUL SYLLABLE KISS
+D0B9;D0B9;110F 1175 11BC;D0B9;110F 1175 11BC; # (킹; 킹; 킹; 킹; 킹; ) HANGUL SYLLABLE KING
+D0BA;D0BA;110F 1175 11BD;D0BA;110F 1175 11BD; # (킺; 킺; 킺; 킺; 킺; ) HANGUL SYLLABLE KIJ
+D0BB;D0BB;110F 1175 11BE;D0BB;110F 1175 11BE; # (킻; 킻; 킻; 킻; 킻; ) HANGUL SYLLABLE KIC
+D0BC;D0BC;110F 1175 11BF;D0BC;110F 1175 11BF; # (킼; 킼; 킼; 킼; 킼; ) HANGUL SYLLABLE KIK
+D0BD;D0BD;110F 1175 11C0;D0BD;110F 1175 11C0; # (킽; 킽; 킽; 킽; 킽; ) HANGUL SYLLABLE KIT
+D0BE;D0BE;110F 1175 11C1;D0BE;110F 1175 11C1; # (킾; 킾; 킾; 킾; 킾; ) HANGUL SYLLABLE KIP
+D0BF;D0BF;110F 1175 11C2;D0BF;110F 1175 11C2; # (킿; 킿; 킿; 킿; 킿; ) HANGUL SYLLABLE KIH
+D0C0;D0C0;1110 1161;D0C0;1110 1161; # (타; 타; 타; 타; 타; ) HANGUL SYLLABLE TA
+D0C1;D0C1;1110 1161 11A8;D0C1;1110 1161 11A8; # (탁; 탁; 탁; 탁; 탁; ) HANGUL SYLLABLE TAG
+D0C2;D0C2;1110 1161 11A9;D0C2;1110 1161 11A9; # (탂; 탂; 탂; 탂; 탂; ) HANGUL SYLLABLE TAGG
+D0C3;D0C3;1110 1161 11AA;D0C3;1110 1161 11AA; # (탃; 탃; 탃; 탃; 탃; ) HANGUL SYLLABLE TAGS
+D0C4;D0C4;1110 1161 11AB;D0C4;1110 1161 11AB; # (탄; 탄; 탄; 탄; 탄; ) HANGUL SYLLABLE TAN
+D0C5;D0C5;1110 1161 11AC;D0C5;1110 1161 11AC; # (탅; 탅; 탅; 탅; 탅; ) HANGUL SYLLABLE TANJ
+D0C6;D0C6;1110 1161 11AD;D0C6;1110 1161 11AD; # (탆; 탆; 탆; 탆; 탆; ) HANGUL SYLLABLE TANH
+D0C7;D0C7;1110 1161 11AE;D0C7;1110 1161 11AE; # (탇; 탇; 탇; 탇; 탇; ) HANGUL SYLLABLE TAD
+D0C8;D0C8;1110 1161 11AF;D0C8;1110 1161 11AF; # (탈; 탈; 탈; 탈; 탈; ) HANGUL SYLLABLE TAL
+D0C9;D0C9;1110 1161 11B0;D0C9;1110 1161 11B0; # (탉; 탉; 탉; 탉; 탉; ) HANGUL SYLLABLE TALG
+D0CA;D0CA;1110 1161 11B1;D0CA;1110 1161 11B1; # (탊; 탊; 탊; 탊; 탊; ) HANGUL SYLLABLE TALM
+D0CB;D0CB;1110 1161 11B2;D0CB;1110 1161 11B2; # (탋; 탋; 탋; 탋; 탋; ) HANGUL SYLLABLE TALB
+D0CC;D0CC;1110 1161 11B3;D0CC;1110 1161 11B3; # (탌; 탌; 탌; 탌; 탌; ) HANGUL SYLLABLE TALS
+D0CD;D0CD;1110 1161 11B4;D0CD;1110 1161 11B4; # (탍; 탍; 탍; 탍; 탍; ) HANGUL SYLLABLE TALT
+D0CE;D0CE;1110 1161 11B5;D0CE;1110 1161 11B5; # (탎; 탎; 탎; 탎; 탎; ) HANGUL SYLLABLE TALP
+D0CF;D0CF;1110 1161 11B6;D0CF;1110 1161 11B6; # (탏; 탏; 탏; 탏; 탏; ) HANGUL SYLLABLE TALH
+D0D0;D0D0;1110 1161 11B7;D0D0;1110 1161 11B7; # (탐; 탐; 탐; 탐; 탐; ) HANGUL SYLLABLE TAM
+D0D1;D0D1;1110 1161 11B8;D0D1;1110 1161 11B8; # (탑; 탑; 탑; 탑; 탑; ) HANGUL SYLLABLE TAB
+D0D2;D0D2;1110 1161 11B9;D0D2;1110 1161 11B9; # (탒; 탒; 탒; 탒; 탒; ) HANGUL SYLLABLE TABS
+D0D3;D0D3;1110 1161 11BA;D0D3;1110 1161 11BA; # (탓; 탓; 탓; 탓; 탓; ) HANGUL SYLLABLE TAS
+D0D4;D0D4;1110 1161 11BB;D0D4;1110 1161 11BB; # (탔; 탔; 탔; 탔; 탔; ) HANGUL SYLLABLE TASS
+D0D5;D0D5;1110 1161 11BC;D0D5;1110 1161 11BC; # (탕; 탕; 탕; 탕; 탕; ) HANGUL SYLLABLE TANG
+D0D6;D0D6;1110 1161 11BD;D0D6;1110 1161 11BD; # (탖; 탖; 탖; 탖; 탖; ) HANGUL SYLLABLE TAJ
+D0D7;D0D7;1110 1161 11BE;D0D7;1110 1161 11BE; # (탗; 탗; 탗; 탗; 탗; ) HANGUL SYLLABLE TAC
+D0D8;D0D8;1110 1161 11BF;D0D8;1110 1161 11BF; # (탘; 탘; 탘; 탘; 탘; ) HANGUL SYLLABLE TAK
+D0D9;D0D9;1110 1161 11C0;D0D9;1110 1161 11C0; # (탙; 탙; 탙; 탙; 탙; ) HANGUL SYLLABLE TAT
+D0DA;D0DA;1110 1161 11C1;D0DA;1110 1161 11C1; # (탚; 탚; 탚; 탚; 탚; ) HANGUL SYLLABLE TAP
+D0DB;D0DB;1110 1161 11C2;D0DB;1110 1161 11C2; # (탛; 탛; 탛; 탛; 탛; ) HANGUL SYLLABLE TAH
+D0DC;D0DC;1110 1162;D0DC;1110 1162; # (태; 태; 태; 태; 태; ) HANGUL SYLLABLE TAE
+D0DD;D0DD;1110 1162 11A8;D0DD;1110 1162 11A8; # (택; 택; 택; 택; 택; ) HANGUL SYLLABLE TAEG
+D0DE;D0DE;1110 1162 11A9;D0DE;1110 1162 11A9; # (탞; 탞; 탞; 탞; 탞; ) HANGUL SYLLABLE TAEGG
+D0DF;D0DF;1110 1162 11AA;D0DF;1110 1162 11AA; # (탟; 탟; 탟; 탟; 탟; ) HANGUL SYLLABLE TAEGS
+D0E0;D0E0;1110 1162 11AB;D0E0;1110 1162 11AB; # (탠; 탠; 탠; 탠; 탠; ) HANGUL SYLLABLE TAEN
+D0E1;D0E1;1110 1162 11AC;D0E1;1110 1162 11AC; # (탡; 탡; 탡; 탡; 탡; ) HANGUL SYLLABLE TAENJ
+D0E2;D0E2;1110 1162 11AD;D0E2;1110 1162 11AD; # (탢; 탢; 탢; 탢; 탢; ) HANGUL SYLLABLE TAENH
+D0E3;D0E3;1110 1162 11AE;D0E3;1110 1162 11AE; # (탣; 탣; 탣; 탣; 탣; ) HANGUL SYLLABLE TAED
+D0E4;D0E4;1110 1162 11AF;D0E4;1110 1162 11AF; # (탤; 탤; 탤; 탤; 탤; ) HANGUL SYLLABLE TAEL
+D0E5;D0E5;1110 1162 11B0;D0E5;1110 1162 11B0; # (탥; 탥; 탥; 탥; 탥; ) HANGUL SYLLABLE TAELG
+D0E6;D0E6;1110 1162 11B1;D0E6;1110 1162 11B1; # (탦; 탦; 탦; 탦; 탦; ) HANGUL SYLLABLE TAELM
+D0E7;D0E7;1110 1162 11B2;D0E7;1110 1162 11B2; # (탧; 탧; 탧; 탧; 탧; ) HANGUL SYLLABLE TAELB
+D0E8;D0E8;1110 1162 11B3;D0E8;1110 1162 11B3; # (탨; 탨; 탨; 탨; 탨; ) HANGUL SYLLABLE TAELS
+D0E9;D0E9;1110 1162 11B4;D0E9;1110 1162 11B4; # (탩; 탩; 탩; 탩; 탩; ) HANGUL SYLLABLE TAELT
+D0EA;D0EA;1110 1162 11B5;D0EA;1110 1162 11B5; # (탪; 탪; 탪; 탪; 탪; ) HANGUL SYLLABLE TAELP
+D0EB;D0EB;1110 1162 11B6;D0EB;1110 1162 11B6; # (탫; 탫; 탫; 탫; 탫; ) HANGUL SYLLABLE TAELH
+D0EC;D0EC;1110 1162 11B7;D0EC;1110 1162 11B7; # (탬; 탬; 탬; 탬; 탬; ) HANGUL SYLLABLE TAEM
+D0ED;D0ED;1110 1162 11B8;D0ED;1110 1162 11B8; # (탭; 탭; 탭; 탭; 탭; ) HANGUL SYLLABLE TAEB
+D0EE;D0EE;1110 1162 11B9;D0EE;1110 1162 11B9; # (탮; 탮; 탮; 탮; 탮; ) HANGUL SYLLABLE TAEBS
+D0EF;D0EF;1110 1162 11BA;D0EF;1110 1162 11BA; # (탯; 탯; 탯; 탯; 탯; ) HANGUL SYLLABLE TAES
+D0F0;D0F0;1110 1162 11BB;D0F0;1110 1162 11BB; # (탰; 탰; 탰; 탰; 탰; ) HANGUL SYLLABLE TAESS
+D0F1;D0F1;1110 1162 11BC;D0F1;1110 1162 11BC; # (탱; 탱; 탱; 탱; 탱; ) HANGUL SYLLABLE TAENG
+D0F2;D0F2;1110 1162 11BD;D0F2;1110 1162 11BD; # (탲; 탲; 탲; 탲; 탲; ) HANGUL SYLLABLE TAEJ
+D0F3;D0F3;1110 1162 11BE;D0F3;1110 1162 11BE; # (탳; 탳; 탳; 탳; 탳; ) HANGUL SYLLABLE TAEC
+D0F4;D0F4;1110 1162 11BF;D0F4;1110 1162 11BF; # (탴; 탴; 탴; 탴; 탴; ) HANGUL SYLLABLE TAEK
+D0F5;D0F5;1110 1162 11C0;D0F5;1110 1162 11C0; # (탵; 탵; 탵; 탵; 탵; ) HANGUL SYLLABLE TAET
+D0F6;D0F6;1110 1162 11C1;D0F6;1110 1162 11C1; # (탶; 탶; 탶; 탶; 탶; ) HANGUL SYLLABLE TAEP
+D0F7;D0F7;1110 1162 11C2;D0F7;1110 1162 11C2; # (탷; 탷; 탷; 탷; 탷; ) HANGUL SYLLABLE TAEH
+D0F8;D0F8;1110 1163;D0F8;1110 1163; # (탸; 탸; 탸; 탸; 탸; ) HANGUL SYLLABLE TYA
+D0F9;D0F9;1110 1163 11A8;D0F9;1110 1163 11A8; # (탹; 탹; 탹; 탹; 탹; ) HANGUL SYLLABLE TYAG
+D0FA;D0FA;1110 1163 11A9;D0FA;1110 1163 11A9; # (탺; 탺; 탺; 탺; 탺; ) HANGUL SYLLABLE TYAGG
+D0FB;D0FB;1110 1163 11AA;D0FB;1110 1163 11AA; # (탻; 탻; 탻; 탻; 탻; ) HANGUL SYLLABLE TYAGS
+D0FC;D0FC;1110 1163 11AB;D0FC;1110 1163 11AB; # (탼; 탼; 탼; 탼; 탼; ) HANGUL SYLLABLE TYAN
+D0FD;D0FD;1110 1163 11AC;D0FD;1110 1163 11AC; # (탽; 탽; 탽; 탽; 탽; ) HANGUL SYLLABLE TYANJ
+D0FE;D0FE;1110 1163 11AD;D0FE;1110 1163 11AD; # (탾; 탾; 탾; 탾; 탾; ) HANGUL SYLLABLE TYANH
+D0FF;D0FF;1110 1163 11AE;D0FF;1110 1163 11AE; # (탿; 탿; 탿; 탿; 탿; ) HANGUL SYLLABLE TYAD
+D100;D100;1110 1163 11AF;D100;1110 1163 11AF; # (턀; 턀; 턀; 턀; 턀; ) HANGUL SYLLABLE TYAL
+D101;D101;1110 1163 11B0;D101;1110 1163 11B0; # (턁; 턁; 턁; 턁; 턁; ) HANGUL SYLLABLE TYALG
+D102;D102;1110 1163 11B1;D102;1110 1163 11B1; # (턂; 턂; 턂; 턂; 턂; ) HANGUL SYLLABLE TYALM
+D103;D103;1110 1163 11B2;D103;1110 1163 11B2; # (턃; 턃; 턃; 턃; 턃; ) HANGUL SYLLABLE TYALB
+D104;D104;1110 1163 11B3;D104;1110 1163 11B3; # (턄; 턄; 턄; 턄; 턄; ) HANGUL SYLLABLE TYALS
+D105;D105;1110 1163 11B4;D105;1110 1163 11B4; # (턅; 턅; 턅; 턅; 턅; ) HANGUL SYLLABLE TYALT
+D106;D106;1110 1163 11B5;D106;1110 1163 11B5; # (턆; 턆; 턆; 턆; 턆; ) HANGUL SYLLABLE TYALP
+D107;D107;1110 1163 11B6;D107;1110 1163 11B6; # (턇; 턇; 턇; 턇; 턇; ) HANGUL SYLLABLE TYALH
+D108;D108;1110 1163 11B7;D108;1110 1163 11B7; # (턈; 턈; 턈; 턈; 턈; ) HANGUL SYLLABLE TYAM
+D109;D109;1110 1163 11B8;D109;1110 1163 11B8; # (턉; 턉; 턉; 턉; 턉; ) HANGUL SYLLABLE TYAB
+D10A;D10A;1110 1163 11B9;D10A;1110 1163 11B9; # (턊; 턊; 턊; 턊; 턊; ) HANGUL SYLLABLE TYABS
+D10B;D10B;1110 1163 11BA;D10B;1110 1163 11BA; # (턋; 턋; 턋; 턋; 턋; ) HANGUL SYLLABLE TYAS
+D10C;D10C;1110 1163 11BB;D10C;1110 1163 11BB; # (턌; 턌; 턌; 턌; 턌; ) HANGUL SYLLABLE TYASS
+D10D;D10D;1110 1163 11BC;D10D;1110 1163 11BC; # (턍; 턍; 턍; 턍; 턍; ) HANGUL SYLLABLE TYANG
+D10E;D10E;1110 1163 11BD;D10E;1110 1163 11BD; # (턎; 턎; 턎; 턎; 턎; ) HANGUL SYLLABLE TYAJ
+D10F;D10F;1110 1163 11BE;D10F;1110 1163 11BE; # (턏; 턏; 턏; 턏; 턏; ) HANGUL SYLLABLE TYAC
+D110;D110;1110 1163 11BF;D110;1110 1163 11BF; # (턐; 턐; 턐; 턐; 턐; ) HANGUL SYLLABLE TYAK
+D111;D111;1110 1163 11C0;D111;1110 1163 11C0; # (턑; 턑; 턑; 턑; 턑; ) HANGUL SYLLABLE TYAT
+D112;D112;1110 1163 11C1;D112;1110 1163 11C1; # (턒; 턒; 턒; 턒; 턒; ) HANGUL SYLLABLE TYAP
+D113;D113;1110 1163 11C2;D113;1110 1163 11C2; # (턓; 턓; 턓; 턓; 턓; ) HANGUL SYLLABLE TYAH
+D114;D114;1110 1164;D114;1110 1164; # (턔; 턔; 턔; 턔; 턔; ) HANGUL SYLLABLE TYAE
+D115;D115;1110 1164 11A8;D115;1110 1164 11A8; # (턕; 턕; 턕; 턕; 턕; ) HANGUL SYLLABLE TYAEG
+D116;D116;1110 1164 11A9;D116;1110 1164 11A9; # (턖; 턖; 턖; 턖; 턖; ) HANGUL SYLLABLE TYAEGG
+D117;D117;1110 1164 11AA;D117;1110 1164 11AA; # (턗; 턗; 턗; 턗; 턗; ) HANGUL SYLLABLE TYAEGS
+D118;D118;1110 1164 11AB;D118;1110 1164 11AB; # (턘; 턘; 턘; 턘; 턘; ) HANGUL SYLLABLE TYAEN
+D119;D119;1110 1164 11AC;D119;1110 1164 11AC; # (턙; 턙; 턙; 턙; 턙; ) HANGUL SYLLABLE TYAENJ
+D11A;D11A;1110 1164 11AD;D11A;1110 1164 11AD; # (턚; 턚; 턚; 턚; 턚; ) HANGUL SYLLABLE TYAENH
+D11B;D11B;1110 1164 11AE;D11B;1110 1164 11AE; # (턛; 턛; 턛; 턛; 턛; ) HANGUL SYLLABLE TYAED
+D11C;D11C;1110 1164 11AF;D11C;1110 1164 11AF; # (턜; 턜; 턜; 턜; 턜; ) HANGUL SYLLABLE TYAEL
+D11D;D11D;1110 1164 11B0;D11D;1110 1164 11B0; # (턝; 턝; 턝; 턝; 턝; ) HANGUL SYLLABLE TYAELG
+D11E;D11E;1110 1164 11B1;D11E;1110 1164 11B1; # (턞; 턞; 턞; 턞; 턞; ) HANGUL SYLLABLE TYAELM
+D11F;D11F;1110 1164 11B2;D11F;1110 1164 11B2; # (턟; 턟; 턟; 턟; 턟; ) HANGUL SYLLABLE TYAELB
+D120;D120;1110 1164 11B3;D120;1110 1164 11B3; # (턠; 턠; 턠; 턠; 턠; ) HANGUL SYLLABLE TYAELS
+D121;D121;1110 1164 11B4;D121;1110 1164 11B4; # (턡; 턡; 턡; 턡; 턡; ) HANGUL SYLLABLE TYAELT
+D122;D122;1110 1164 11B5;D122;1110 1164 11B5; # (턢; 턢; 턢; 턢; 턢; ) HANGUL SYLLABLE TYAELP
+D123;D123;1110 1164 11B6;D123;1110 1164 11B6; # (턣; 턣; 턣; 턣; 턣; ) HANGUL SYLLABLE TYAELH
+D124;D124;1110 1164 11B7;D124;1110 1164 11B7; # (턤; 턤; 턤; 턤; 턤; ) HANGUL SYLLABLE TYAEM
+D125;D125;1110 1164 11B8;D125;1110 1164 11B8; # (턥; 턥; 턥; 턥; 턥; ) HANGUL SYLLABLE TYAEB
+D126;D126;1110 1164 11B9;D126;1110 1164 11B9; # (턦; 턦; 턦; 턦; 턦; ) HANGUL SYLLABLE TYAEBS
+D127;D127;1110 1164 11BA;D127;1110 1164 11BA; # (턧; 턧; 턧; 턧; 턧; ) HANGUL SYLLABLE TYAES
+D128;D128;1110 1164 11BB;D128;1110 1164 11BB; # (턨; 턨; 턨; 턨; 턨; ) HANGUL SYLLABLE TYAESS
+D129;D129;1110 1164 11BC;D129;1110 1164 11BC; # (턩; 턩; 턩; 턩; 턩; ) HANGUL SYLLABLE TYAENG
+D12A;D12A;1110 1164 11BD;D12A;1110 1164 11BD; # (턪; 턪; 턪; 턪; 턪; ) HANGUL SYLLABLE TYAEJ
+D12B;D12B;1110 1164 11BE;D12B;1110 1164 11BE; # (턫; 턫; 턫; 턫; 턫; ) HANGUL SYLLABLE TYAEC
+D12C;D12C;1110 1164 11BF;D12C;1110 1164 11BF; # (턬; 턬; 턬; 턬; 턬; ) HANGUL SYLLABLE TYAEK
+D12D;D12D;1110 1164 11C0;D12D;1110 1164 11C0; # (턭; 턭; 턭; 턭; 턭; ) HANGUL SYLLABLE TYAET
+D12E;D12E;1110 1164 11C1;D12E;1110 1164 11C1; # (턮; 턮; 턮; 턮; 턮; ) HANGUL SYLLABLE TYAEP
+D12F;D12F;1110 1164 11C2;D12F;1110 1164 11C2; # (턯; 턯; 턯; 턯; 턯; ) HANGUL SYLLABLE TYAEH
+D130;D130;1110 1165;D130;1110 1165; # (터; 터; 터; 터; 터; ) HANGUL SYLLABLE TEO
+D131;D131;1110 1165 11A8;D131;1110 1165 11A8; # (턱; 턱; 턱; 턱; 턱; ) HANGUL SYLLABLE TEOG
+D132;D132;1110 1165 11A9;D132;1110 1165 11A9; # (턲; 턲; 턲; 턲; 턲; ) HANGUL SYLLABLE TEOGG
+D133;D133;1110 1165 11AA;D133;1110 1165 11AA; # (턳; 턳; 턳; 턳; 턳; ) HANGUL SYLLABLE TEOGS
+D134;D134;1110 1165 11AB;D134;1110 1165 11AB; # (턴; 턴; 턴; 턴; 턴; ) HANGUL SYLLABLE TEON
+D135;D135;1110 1165 11AC;D135;1110 1165 11AC; # (턵; 턵; 턵; 턵; 턵; ) HANGUL SYLLABLE TEONJ
+D136;D136;1110 1165 11AD;D136;1110 1165 11AD; # (턶; 턶; 턶; 턶; 턶; ) HANGUL SYLLABLE TEONH
+D137;D137;1110 1165 11AE;D137;1110 1165 11AE; # (턷; 턷; 턷; 턷; 턷; ) HANGUL SYLLABLE TEOD
+D138;D138;1110 1165 11AF;D138;1110 1165 11AF; # (털; 털; 털; 털; 털; ) HANGUL SYLLABLE TEOL
+D139;D139;1110 1165 11B0;D139;1110 1165 11B0; # (턹; 턹; 턹; 턹; 턹; ) HANGUL SYLLABLE TEOLG
+D13A;D13A;1110 1165 11B1;D13A;1110 1165 11B1; # (턺; 턺; 턺; 턺; 턺; ) HANGUL SYLLABLE TEOLM
+D13B;D13B;1110 1165 11B2;D13B;1110 1165 11B2; # (턻; 턻; 턻; 턻; 턻; ) HANGUL SYLLABLE TEOLB
+D13C;D13C;1110 1165 11B3;D13C;1110 1165 11B3; # (턼; 턼; 턼; 턼; 턼; ) HANGUL SYLLABLE TEOLS
+D13D;D13D;1110 1165 11B4;D13D;1110 1165 11B4; # (턽; 턽; 턽; 턽; 턽; ) HANGUL SYLLABLE TEOLT
+D13E;D13E;1110 1165 11B5;D13E;1110 1165 11B5; # (턾; 턾; 턾; 턾; 턾; ) HANGUL SYLLABLE TEOLP
+D13F;D13F;1110 1165 11B6;D13F;1110 1165 11B6; # (턿; 턿; 턿; 턿; 턿; ) HANGUL SYLLABLE TEOLH
+D140;D140;1110 1165 11B7;D140;1110 1165 11B7; # (텀; 텀; 텀; 텀; 텀; ) HANGUL SYLLABLE TEOM
+D141;D141;1110 1165 11B8;D141;1110 1165 11B8; # (텁; 텁; 텁; 텁; 텁; ) HANGUL SYLLABLE TEOB
+D142;D142;1110 1165 11B9;D142;1110 1165 11B9; # (텂; 텂; 텂; 텂; 텂; ) HANGUL SYLLABLE TEOBS
+D143;D143;1110 1165 11BA;D143;1110 1165 11BA; # (텃; 텃; 텃; 텃; 텃; ) HANGUL SYLLABLE TEOS
+D144;D144;1110 1165 11BB;D144;1110 1165 11BB; # (텄; 텄; 텄; 텄; 텄; ) HANGUL SYLLABLE TEOSS
+D145;D145;1110 1165 11BC;D145;1110 1165 11BC; # (텅; 텅; 텅; 텅; 텅; ) HANGUL SYLLABLE TEONG
+D146;D146;1110 1165 11BD;D146;1110 1165 11BD; # (텆; 텆; 텆; 텆; 텆; ) HANGUL SYLLABLE TEOJ
+D147;D147;1110 1165 11BE;D147;1110 1165 11BE; # (텇; 텇; 텇; 텇; 텇; ) HANGUL SYLLABLE TEOC
+D148;D148;1110 1165 11BF;D148;1110 1165 11BF; # (텈; 텈; 텈; 텈; 텈; ) HANGUL SYLLABLE TEOK
+D149;D149;1110 1165 11C0;D149;1110 1165 11C0; # (텉; 텉; 텉; 텉; 텉; ) HANGUL SYLLABLE TEOT
+D14A;D14A;1110 1165 11C1;D14A;1110 1165 11C1; # (텊; 텊; 텊; 텊; 텊; ) HANGUL SYLLABLE TEOP
+D14B;D14B;1110 1165 11C2;D14B;1110 1165 11C2; # (텋; 텋; 텋; 텋; 텋; ) HANGUL SYLLABLE TEOH
+D14C;D14C;1110 1166;D14C;1110 1166; # (테; 테; 테; 테; 테; ) HANGUL SYLLABLE TE
+D14D;D14D;1110 1166 11A8;D14D;1110 1166 11A8; # (텍; 텍; 텍; 텍; 텍; ) HANGUL SYLLABLE TEG
+D14E;D14E;1110 1166 11A9;D14E;1110 1166 11A9; # (텎; 텎; 텎; 텎; 텎; ) HANGUL SYLLABLE TEGG
+D14F;D14F;1110 1166 11AA;D14F;1110 1166 11AA; # (텏; 텏; 텏; 텏; 텏; ) HANGUL SYLLABLE TEGS
+D150;D150;1110 1166 11AB;D150;1110 1166 11AB; # (텐; 텐; 텐; 텐; 텐; ) HANGUL SYLLABLE TEN
+D151;D151;1110 1166 11AC;D151;1110 1166 11AC; # (텑; 텑; 텑; 텑; 텑; ) HANGUL SYLLABLE TENJ
+D152;D152;1110 1166 11AD;D152;1110 1166 11AD; # (텒; 텒; 텒; 텒; 텒; ) HANGUL SYLLABLE TENH
+D153;D153;1110 1166 11AE;D153;1110 1166 11AE; # (텓; 텓; 텓; 텓; 텓; ) HANGUL SYLLABLE TED
+D154;D154;1110 1166 11AF;D154;1110 1166 11AF; # (텔; 텔; 텔; 텔; 텔; ) HANGUL SYLLABLE TEL
+D155;D155;1110 1166 11B0;D155;1110 1166 11B0; # (텕; 텕; 텕; 텕; 텕; ) HANGUL SYLLABLE TELG
+D156;D156;1110 1166 11B1;D156;1110 1166 11B1; # (텖; 텖; 텖; 텖; 텖; ) HANGUL SYLLABLE TELM
+D157;D157;1110 1166 11B2;D157;1110 1166 11B2; # (텗; 텗; 텗; 텗; 텗; ) HANGUL SYLLABLE TELB
+D158;D158;1110 1166 11B3;D158;1110 1166 11B3; # (텘; 텘; 텘; 텘; 텘; ) HANGUL SYLLABLE TELS
+D159;D159;1110 1166 11B4;D159;1110 1166 11B4; # (텙; 텙; 텙; 텙; 텙; ) HANGUL SYLLABLE TELT
+D15A;D15A;1110 1166 11B5;D15A;1110 1166 11B5; # (텚; 텚; 텚; 텚; 텚; ) HANGUL SYLLABLE TELP
+D15B;D15B;1110 1166 11B6;D15B;1110 1166 11B6; # (텛; 텛; 텛; 텛; 텛; ) HANGUL SYLLABLE TELH
+D15C;D15C;1110 1166 11B7;D15C;1110 1166 11B7; # (템; 템; 템; 템; 템; ) HANGUL SYLLABLE TEM
+D15D;D15D;1110 1166 11B8;D15D;1110 1166 11B8; # (텝; 텝; 텝; 텝; 텝; ) HANGUL SYLLABLE TEB
+D15E;D15E;1110 1166 11B9;D15E;1110 1166 11B9; # (텞; 텞; 텞; 텞; 텞; ) HANGUL SYLLABLE TEBS
+D15F;D15F;1110 1166 11BA;D15F;1110 1166 11BA; # (텟; 텟; 텟; 텟; 텟; ) HANGUL SYLLABLE TES
+D160;D160;1110 1166 11BB;D160;1110 1166 11BB; # (텠; 텠; 텠; 텠; 텠; ) HANGUL SYLLABLE TESS
+D161;D161;1110 1166 11BC;D161;1110 1166 11BC; # (텡; 텡; 텡; 텡; 텡; ) HANGUL SYLLABLE TENG
+D162;D162;1110 1166 11BD;D162;1110 1166 11BD; # (텢; 텢; 텢; 텢; 텢; ) HANGUL SYLLABLE TEJ
+D163;D163;1110 1166 11BE;D163;1110 1166 11BE; # (텣; 텣; 텣; 텣; 텣; ) HANGUL SYLLABLE TEC
+D164;D164;1110 1166 11BF;D164;1110 1166 11BF; # (텤; 텤; 텤; 텤; 텤; ) HANGUL SYLLABLE TEK
+D165;D165;1110 1166 11C0;D165;1110 1166 11C0; # (텥; 텥; 텥; 텥; 텥; ) HANGUL SYLLABLE TET
+D166;D166;1110 1166 11C1;D166;1110 1166 11C1; # (텦; 텦; 텦; 텦; 텦; ) HANGUL SYLLABLE TEP
+D167;D167;1110 1166 11C2;D167;1110 1166 11C2; # (텧; 텧; 텧; 텧; 텧; ) HANGUL SYLLABLE TEH
+D168;D168;1110 1167;D168;1110 1167; # (텨; 텨; 텨; 텨; 텨; ) HANGUL SYLLABLE TYEO
+D169;D169;1110 1167 11A8;D169;1110 1167 11A8; # (텩; 텩; 텩; 텩; 텩; ) HANGUL SYLLABLE TYEOG
+D16A;D16A;1110 1167 11A9;D16A;1110 1167 11A9; # (텪; 텪; 텪; 텪; 텪; ) HANGUL SYLLABLE TYEOGG
+D16B;D16B;1110 1167 11AA;D16B;1110 1167 11AA; # (텫; 텫; 텫; 텫; 텫; ) HANGUL SYLLABLE TYEOGS
+D16C;D16C;1110 1167 11AB;D16C;1110 1167 11AB; # (텬; 텬; 텬; 텬; 텬; ) HANGUL SYLLABLE TYEON
+D16D;D16D;1110 1167 11AC;D16D;1110 1167 11AC; # (텭; 텭; 텭; 텭; 텭; ) HANGUL SYLLABLE TYEONJ
+D16E;D16E;1110 1167 11AD;D16E;1110 1167 11AD; # (텮; 텮; 텮; 텮; 텮; ) HANGUL SYLLABLE TYEONH
+D16F;D16F;1110 1167 11AE;D16F;1110 1167 11AE; # (텯; 텯; 텯; 텯; 텯; ) HANGUL SYLLABLE TYEOD
+D170;D170;1110 1167 11AF;D170;1110 1167 11AF; # (텰; 텰; 텰; 텰; 텰; ) HANGUL SYLLABLE TYEOL
+D171;D171;1110 1167 11B0;D171;1110 1167 11B0; # (텱; 텱; 텱; 텱; 텱; ) HANGUL SYLLABLE TYEOLG
+D172;D172;1110 1167 11B1;D172;1110 1167 11B1; # (텲; 텲; 텲; 텲; 텲; ) HANGUL SYLLABLE TYEOLM
+D173;D173;1110 1167 11B2;D173;1110 1167 11B2; # (텳; 텳; 텳; 텳; 텳; ) HANGUL SYLLABLE TYEOLB
+D174;D174;1110 1167 11B3;D174;1110 1167 11B3; # (텴; 텴; 텴; 텴; 텴; ) HANGUL SYLLABLE TYEOLS
+D175;D175;1110 1167 11B4;D175;1110 1167 11B4; # (텵; 텵; 텵; 텵; 텵; ) HANGUL SYLLABLE TYEOLT
+D176;D176;1110 1167 11B5;D176;1110 1167 11B5; # (텶; 텶; 텶; 텶; 텶; ) HANGUL SYLLABLE TYEOLP
+D177;D177;1110 1167 11B6;D177;1110 1167 11B6; # (텷; 텷; 텷; 텷; 텷; ) HANGUL SYLLABLE TYEOLH
+D178;D178;1110 1167 11B7;D178;1110 1167 11B7; # (텸; 텸; 텸; 텸; 텸; ) HANGUL SYLLABLE TYEOM
+D179;D179;1110 1167 11B8;D179;1110 1167 11B8; # (텹; 텹; 텹; 텹; 텹; ) HANGUL SYLLABLE TYEOB
+D17A;D17A;1110 1167 11B9;D17A;1110 1167 11B9; # (텺; 텺; 텺; 텺; 텺; ) HANGUL SYLLABLE TYEOBS
+D17B;D17B;1110 1167 11BA;D17B;1110 1167 11BA; # (텻; 텻; 텻; 텻; 텻; ) HANGUL SYLLABLE TYEOS
+D17C;D17C;1110 1167 11BB;D17C;1110 1167 11BB; # (텼; 텼; 텼; 텼; 텼; ) HANGUL SYLLABLE TYEOSS
+D17D;D17D;1110 1167 11BC;D17D;1110 1167 11BC; # (텽; 텽; 텽; 텽; 텽; ) HANGUL SYLLABLE TYEONG
+D17E;D17E;1110 1167 11BD;D17E;1110 1167 11BD; # (텾; 텾; 텾; 텾; 텾; ) HANGUL SYLLABLE TYEOJ
+D17F;D17F;1110 1167 11BE;D17F;1110 1167 11BE; # (텿; 텿; 텿; 텿; 텿; ) HANGUL SYLLABLE TYEOC
+D180;D180;1110 1167 11BF;D180;1110 1167 11BF; # (톀; 톀; 톀; 톀; 톀; ) HANGUL SYLLABLE TYEOK
+D181;D181;1110 1167 11C0;D181;1110 1167 11C0; # (톁; 톁; 톁; 톁; 톁; ) HANGUL SYLLABLE TYEOT
+D182;D182;1110 1167 11C1;D182;1110 1167 11C1; # (톂; 톂; 톂; 톂; 톂; ) HANGUL SYLLABLE TYEOP
+D183;D183;1110 1167 11C2;D183;1110 1167 11C2; # (톃; 톃; 톃; 톃; 톃; ) HANGUL SYLLABLE TYEOH
+D184;D184;1110 1168;D184;1110 1168; # (톄; 톄; 톄; 톄; 톄; ) HANGUL SYLLABLE TYE
+D185;D185;1110 1168 11A8;D185;1110 1168 11A8; # (톅; 톅; 톅; 톅; 톅; ) HANGUL SYLLABLE TYEG
+D186;D186;1110 1168 11A9;D186;1110 1168 11A9; # (톆; 톆; 톆; 톆; 톆; ) HANGUL SYLLABLE TYEGG
+D187;D187;1110 1168 11AA;D187;1110 1168 11AA; # (톇; 톇; 톇; 톇; 톇; ) HANGUL SYLLABLE TYEGS
+D188;D188;1110 1168 11AB;D188;1110 1168 11AB; # (톈; 톈; 톈; 톈; 톈; ) HANGUL SYLLABLE TYEN
+D189;D189;1110 1168 11AC;D189;1110 1168 11AC; # (톉; 톉; 톉; 톉; 톉; ) HANGUL SYLLABLE TYENJ
+D18A;D18A;1110 1168 11AD;D18A;1110 1168 11AD; # (톊; 톊; 톊; 톊; 톊; ) HANGUL SYLLABLE TYENH
+D18B;D18B;1110 1168 11AE;D18B;1110 1168 11AE; # (톋; 톋; 톋; 톋; 톋; ) HANGUL SYLLABLE TYED
+D18C;D18C;1110 1168 11AF;D18C;1110 1168 11AF; # (톌; 톌; 톌; 톌; 톌; ) HANGUL SYLLABLE TYEL
+D18D;D18D;1110 1168 11B0;D18D;1110 1168 11B0; # (톍; 톍; 톍; 톍; 톍; ) HANGUL SYLLABLE TYELG
+D18E;D18E;1110 1168 11B1;D18E;1110 1168 11B1; # (톎; 톎; 톎; 톎; 톎; ) HANGUL SYLLABLE TYELM
+D18F;D18F;1110 1168 11B2;D18F;1110 1168 11B2; # (톏; 톏; 톏; 톏; 톏; ) HANGUL SYLLABLE TYELB
+D190;D190;1110 1168 11B3;D190;1110 1168 11B3; # (톐; 톐; 톐; 톐; 톐; ) HANGUL SYLLABLE TYELS
+D191;D191;1110 1168 11B4;D191;1110 1168 11B4; # (톑; 톑; 톑; 톑; 톑; ) HANGUL SYLLABLE TYELT
+D192;D192;1110 1168 11B5;D192;1110 1168 11B5; # (톒; 톒; 톒; 톒; 톒; ) HANGUL SYLLABLE TYELP
+D193;D193;1110 1168 11B6;D193;1110 1168 11B6; # (톓; 톓; 톓; 톓; 톓; ) HANGUL SYLLABLE TYELH
+D194;D194;1110 1168 11B7;D194;1110 1168 11B7; # (톔; 톔; 톔; 톔; 톔; ) HANGUL SYLLABLE TYEM
+D195;D195;1110 1168 11B8;D195;1110 1168 11B8; # (톕; 톕; 톕; 톕; 톕; ) HANGUL SYLLABLE TYEB
+D196;D196;1110 1168 11B9;D196;1110 1168 11B9; # (톖; 톖; 톖; 톖; 톖; ) HANGUL SYLLABLE TYEBS
+D197;D197;1110 1168 11BA;D197;1110 1168 11BA; # (톗; 톗; 톗; 톗; 톗; ) HANGUL SYLLABLE TYES
+D198;D198;1110 1168 11BB;D198;1110 1168 11BB; # (톘; 톘; 톘; 톘; 톘; ) HANGUL SYLLABLE TYESS
+D199;D199;1110 1168 11BC;D199;1110 1168 11BC; # (톙; 톙; 톙; 톙; 톙; ) HANGUL SYLLABLE TYENG
+D19A;D19A;1110 1168 11BD;D19A;1110 1168 11BD; # (톚; 톚; 톚; 톚; 톚; ) HANGUL SYLLABLE TYEJ
+D19B;D19B;1110 1168 11BE;D19B;1110 1168 11BE; # (톛; 톛; 톛; 톛; 톛; ) HANGUL SYLLABLE TYEC
+D19C;D19C;1110 1168 11BF;D19C;1110 1168 11BF; # (톜; 톜; 톜; 톜; 톜; ) HANGUL SYLLABLE TYEK
+D19D;D19D;1110 1168 11C0;D19D;1110 1168 11C0; # (톝; 톝; 톝; 톝; 톝; ) HANGUL SYLLABLE TYET
+D19E;D19E;1110 1168 11C1;D19E;1110 1168 11C1; # (톞; 톞; 톞; 톞; 톞; ) HANGUL SYLLABLE TYEP
+D19F;D19F;1110 1168 11C2;D19F;1110 1168 11C2; # (톟; 톟; 톟; 톟; 톟; ) HANGUL SYLLABLE TYEH
+D1A0;D1A0;1110 1169;D1A0;1110 1169; # (토; 토; 토; 토; 토; ) HANGUL SYLLABLE TO
+D1A1;D1A1;1110 1169 11A8;D1A1;1110 1169 11A8; # (톡; 톡; 톡; 톡; 톡; ) HANGUL SYLLABLE TOG
+D1A2;D1A2;1110 1169 11A9;D1A2;1110 1169 11A9; # (톢; 톢; 톢; 톢; 톢; ) HANGUL SYLLABLE TOGG
+D1A3;D1A3;1110 1169 11AA;D1A3;1110 1169 11AA; # (톣; 톣; 톣; 톣; 톣; ) HANGUL SYLLABLE TOGS
+D1A4;D1A4;1110 1169 11AB;D1A4;1110 1169 11AB; # (톤; 톤; 톤; 톤; 톤; ) HANGUL SYLLABLE TON
+D1A5;D1A5;1110 1169 11AC;D1A5;1110 1169 11AC; # (톥; 톥; 톥; 톥; 톥; ) HANGUL SYLLABLE TONJ
+D1A6;D1A6;1110 1169 11AD;D1A6;1110 1169 11AD; # (톦; 톦; 톦; 톦; 톦; ) HANGUL SYLLABLE TONH
+D1A7;D1A7;1110 1169 11AE;D1A7;1110 1169 11AE; # (톧; 톧; 톧; 톧; 톧; ) HANGUL SYLLABLE TOD
+D1A8;D1A8;1110 1169 11AF;D1A8;1110 1169 11AF; # (톨; 톨; 톨; 톨; 톨; ) HANGUL SYLLABLE TOL
+D1A9;D1A9;1110 1169 11B0;D1A9;1110 1169 11B0; # (톩; 톩; 톩; 톩; 톩; ) HANGUL SYLLABLE TOLG
+D1AA;D1AA;1110 1169 11B1;D1AA;1110 1169 11B1; # (톪; 톪; 톪; 톪; 톪; ) HANGUL SYLLABLE TOLM
+D1AB;D1AB;1110 1169 11B2;D1AB;1110 1169 11B2; # (톫; 톫; 톫; 톫; 톫; ) HANGUL SYLLABLE TOLB
+D1AC;D1AC;1110 1169 11B3;D1AC;1110 1169 11B3; # (톬; 톬; 톬; 톬; 톬; ) HANGUL SYLLABLE TOLS
+D1AD;D1AD;1110 1169 11B4;D1AD;1110 1169 11B4; # (톭; 톭; 톭; 톭; 톭; ) HANGUL SYLLABLE TOLT
+D1AE;D1AE;1110 1169 11B5;D1AE;1110 1169 11B5; # (톮; 톮; 톮; 톮; 톮; ) HANGUL SYLLABLE TOLP
+D1AF;D1AF;1110 1169 11B6;D1AF;1110 1169 11B6; # (톯; 톯; 톯; 톯; 톯; ) HANGUL SYLLABLE TOLH
+D1B0;D1B0;1110 1169 11B7;D1B0;1110 1169 11B7; # (톰; 톰; 톰; 톰; 톰; ) HANGUL SYLLABLE TOM
+D1B1;D1B1;1110 1169 11B8;D1B1;1110 1169 11B8; # (톱; 톱; 톱; 톱; 톱; ) HANGUL SYLLABLE TOB
+D1B2;D1B2;1110 1169 11B9;D1B2;1110 1169 11B9; # (톲; 톲; 톲; 톲; 톲; ) HANGUL SYLLABLE TOBS
+D1B3;D1B3;1110 1169 11BA;D1B3;1110 1169 11BA; # (톳; 톳; 톳; 톳; 톳; ) HANGUL SYLLABLE TOS
+D1B4;D1B4;1110 1169 11BB;D1B4;1110 1169 11BB; # (톴; 톴; 톴; 톴; 톴; ) HANGUL SYLLABLE TOSS
+D1B5;D1B5;1110 1169 11BC;D1B5;1110 1169 11BC; # (통; 통; 통; 통; 통; ) HANGUL SYLLABLE TONG
+D1B6;D1B6;1110 1169 11BD;D1B6;1110 1169 11BD; # (톶; 톶; 톶; 톶; 톶; ) HANGUL SYLLABLE TOJ
+D1B7;D1B7;1110 1169 11BE;D1B7;1110 1169 11BE; # (톷; 톷; 톷; 톷; 톷; ) HANGUL SYLLABLE TOC
+D1B8;D1B8;1110 1169 11BF;D1B8;1110 1169 11BF; # (톸; 톸; 톸; 톸; 톸; ) HANGUL SYLLABLE TOK
+D1B9;D1B9;1110 1169 11C0;D1B9;1110 1169 11C0; # (톹; 톹; 톹; 톹; 톹; ) HANGUL SYLLABLE TOT
+D1BA;D1BA;1110 1169 11C1;D1BA;1110 1169 11C1; # (톺; 톺; 톺; 톺; 톺; ) HANGUL SYLLABLE TOP
+D1BB;D1BB;1110 1169 11C2;D1BB;1110 1169 11C2; # (톻; 톻; 톻; 톻; 톻; ) HANGUL SYLLABLE TOH
+D1BC;D1BC;1110 116A;D1BC;1110 116A; # (톼; 톼; 톼; 톼; 톼; ) HANGUL SYLLABLE TWA
+D1BD;D1BD;1110 116A 11A8;D1BD;1110 116A 11A8; # (톽; 톽; 톽; 톽; 톽; ) HANGUL SYLLABLE TWAG
+D1BE;D1BE;1110 116A 11A9;D1BE;1110 116A 11A9; # (톾; 톾; 톾; 톾; 톾; ) HANGUL SYLLABLE TWAGG
+D1BF;D1BF;1110 116A 11AA;D1BF;1110 116A 11AA; # (톿; 톿; 톿; 톿; 톿; ) HANGUL SYLLABLE TWAGS
+D1C0;D1C0;1110 116A 11AB;D1C0;1110 116A 11AB; # (퇀; 퇀; 퇀; 퇀; 퇀; ) HANGUL SYLLABLE TWAN
+D1C1;D1C1;1110 116A 11AC;D1C1;1110 116A 11AC; # (퇁; 퇁; 퇁; 퇁; 퇁; ) HANGUL SYLLABLE TWANJ
+D1C2;D1C2;1110 116A 11AD;D1C2;1110 116A 11AD; # (퇂; 퇂; 퇂; 퇂; 퇂; ) HANGUL SYLLABLE TWANH
+D1C3;D1C3;1110 116A 11AE;D1C3;1110 116A 11AE; # (퇃; 퇃; 퇃; 퇃; 퇃; ) HANGUL SYLLABLE TWAD
+D1C4;D1C4;1110 116A 11AF;D1C4;1110 116A 11AF; # (퇄; 퇄; 퇄; 퇄; 퇄; ) HANGUL SYLLABLE TWAL
+D1C5;D1C5;1110 116A 11B0;D1C5;1110 116A 11B0; # (퇅; 퇅; 퇅; 퇅; 퇅; ) HANGUL SYLLABLE TWALG
+D1C6;D1C6;1110 116A 11B1;D1C6;1110 116A 11B1; # (퇆; 퇆; 퇆; 퇆; 퇆; ) HANGUL SYLLABLE TWALM
+D1C7;D1C7;1110 116A 11B2;D1C7;1110 116A 11B2; # (퇇; 퇇; 퇇; 퇇; 퇇; ) HANGUL SYLLABLE TWALB
+D1C8;D1C8;1110 116A 11B3;D1C8;1110 116A 11B3; # (퇈; 퇈; 퇈; 퇈; 퇈; ) HANGUL SYLLABLE TWALS
+D1C9;D1C9;1110 116A 11B4;D1C9;1110 116A 11B4; # (퇉; 퇉; 퇉; 퇉; 퇉; ) HANGUL SYLLABLE TWALT
+D1CA;D1CA;1110 116A 11B5;D1CA;1110 116A 11B5; # (퇊; 퇊; 퇊; 퇊; 퇊; ) HANGUL SYLLABLE TWALP
+D1CB;D1CB;1110 116A 11B6;D1CB;1110 116A 11B6; # (퇋; 퇋; 퇋; 퇋; 퇋; ) HANGUL SYLLABLE TWALH
+D1CC;D1CC;1110 116A 11B7;D1CC;1110 116A 11B7; # (퇌; 퇌; 퇌; 퇌; 퇌; ) HANGUL SYLLABLE TWAM
+D1CD;D1CD;1110 116A 11B8;D1CD;1110 116A 11B8; # (퇍; 퇍; 퇍; 퇍; 퇍; ) HANGUL SYLLABLE TWAB
+D1CE;D1CE;1110 116A 11B9;D1CE;1110 116A 11B9; # (퇎; 퇎; 퇎; 퇎; 퇎; ) HANGUL SYLLABLE TWABS
+D1CF;D1CF;1110 116A 11BA;D1CF;1110 116A 11BA; # (퇏; 퇏; 퇏; 퇏; 퇏; ) HANGUL SYLLABLE TWAS
+D1D0;D1D0;1110 116A 11BB;D1D0;1110 116A 11BB; # (퇐; 퇐; 퇐; 퇐; 퇐; ) HANGUL SYLLABLE TWASS
+D1D1;D1D1;1110 116A 11BC;D1D1;1110 116A 11BC; # (퇑; 퇑; 퇑; 퇑; 퇑; ) HANGUL SYLLABLE TWANG
+D1D2;D1D2;1110 116A 11BD;D1D2;1110 116A 11BD; # (퇒; 퇒; 퇒; 퇒; 퇒; ) HANGUL SYLLABLE TWAJ
+D1D3;D1D3;1110 116A 11BE;D1D3;1110 116A 11BE; # (퇓; 퇓; 퇓; 퇓; 퇓; ) HANGUL SYLLABLE TWAC
+D1D4;D1D4;1110 116A 11BF;D1D4;1110 116A 11BF; # (퇔; 퇔; 퇔; 퇔; 퇔; ) HANGUL SYLLABLE TWAK
+D1D5;D1D5;1110 116A 11C0;D1D5;1110 116A 11C0; # (퇕; 퇕; 퇕; 퇕; 퇕; ) HANGUL SYLLABLE TWAT
+D1D6;D1D6;1110 116A 11C1;D1D6;1110 116A 11C1; # (퇖; 퇖; 퇖; 퇖; 퇖; ) HANGUL SYLLABLE TWAP
+D1D7;D1D7;1110 116A 11C2;D1D7;1110 116A 11C2; # (퇗; 퇗; 퇗; 퇗; 퇗; ) HANGUL SYLLABLE TWAH
+D1D8;D1D8;1110 116B;D1D8;1110 116B; # (퇘; 퇘; 퇘; 퇘; 퇘; ) HANGUL SYLLABLE TWAE
+D1D9;D1D9;1110 116B 11A8;D1D9;1110 116B 11A8; # (퇙; 퇙; 퇙; 퇙; 퇙; ) HANGUL SYLLABLE TWAEG
+D1DA;D1DA;1110 116B 11A9;D1DA;1110 116B 11A9; # (퇚; 퇚; 퇚; 퇚; 퇚; ) HANGUL SYLLABLE TWAEGG
+D1DB;D1DB;1110 116B 11AA;D1DB;1110 116B 11AA; # (퇛; 퇛; 퇛; 퇛; 퇛; ) HANGUL SYLLABLE TWAEGS
+D1DC;D1DC;1110 116B 11AB;D1DC;1110 116B 11AB; # (퇜; 퇜; 퇜; 퇜; 퇜; ) HANGUL SYLLABLE TWAEN
+D1DD;D1DD;1110 116B 11AC;D1DD;1110 116B 11AC; # (퇝; 퇝; 퇝; 퇝; 퇝; ) HANGUL SYLLABLE TWAENJ
+D1DE;D1DE;1110 116B 11AD;D1DE;1110 116B 11AD; # (퇞; 퇞; 퇞; 퇞; 퇞; ) HANGUL SYLLABLE TWAENH
+D1DF;D1DF;1110 116B 11AE;D1DF;1110 116B 11AE; # (퇟; 퇟; 퇟; 퇟; 퇟; ) HANGUL SYLLABLE TWAED
+D1E0;D1E0;1110 116B 11AF;D1E0;1110 116B 11AF; # (퇠; 퇠; 퇠; 퇠; 퇠; ) HANGUL SYLLABLE TWAEL
+D1E1;D1E1;1110 116B 11B0;D1E1;1110 116B 11B0; # (퇡; 퇡; 퇡; 퇡; 퇡; ) HANGUL SYLLABLE TWAELG
+D1E2;D1E2;1110 116B 11B1;D1E2;1110 116B 11B1; # (퇢; 퇢; 퇢; 퇢; 퇢; ) HANGUL SYLLABLE TWAELM
+D1E3;D1E3;1110 116B 11B2;D1E3;1110 116B 11B2; # (퇣; 퇣; 퇣; 퇣; 퇣; ) HANGUL SYLLABLE TWAELB
+D1E4;D1E4;1110 116B 11B3;D1E4;1110 116B 11B3; # (퇤; 퇤; 퇤; 퇤; 퇤; ) HANGUL SYLLABLE TWAELS
+D1E5;D1E5;1110 116B 11B4;D1E5;1110 116B 11B4; # (퇥; 퇥; 퇥; 퇥; 퇥; ) HANGUL SYLLABLE TWAELT
+D1E6;D1E6;1110 116B 11B5;D1E6;1110 116B 11B5; # (퇦; 퇦; 퇦; 퇦; 퇦; ) HANGUL SYLLABLE TWAELP
+D1E7;D1E7;1110 116B 11B6;D1E7;1110 116B 11B6; # (퇧; 퇧; 퇧; 퇧; 퇧; ) HANGUL SYLLABLE TWAELH
+D1E8;D1E8;1110 116B 11B7;D1E8;1110 116B 11B7; # (퇨; 퇨; 퇨; 퇨; 퇨; ) HANGUL SYLLABLE TWAEM
+D1E9;D1E9;1110 116B 11B8;D1E9;1110 116B 11B8; # (퇩; 퇩; 퇩; 퇩; 퇩; ) HANGUL SYLLABLE TWAEB
+D1EA;D1EA;1110 116B 11B9;D1EA;1110 116B 11B9; # (퇪; 퇪; 퇪; 퇪; 퇪; ) HANGUL SYLLABLE TWAEBS
+D1EB;D1EB;1110 116B 11BA;D1EB;1110 116B 11BA; # (퇫; 퇫; 퇫; 퇫; 퇫; ) HANGUL SYLLABLE TWAES
+D1EC;D1EC;1110 116B 11BB;D1EC;1110 116B 11BB; # (퇬; 퇬; 퇬; 퇬; 퇬; ) HANGUL SYLLABLE TWAESS
+D1ED;D1ED;1110 116B 11BC;D1ED;1110 116B 11BC; # (퇭; 퇭; 퇭; 퇭; 퇭; ) HANGUL SYLLABLE TWAENG
+D1EE;D1EE;1110 116B 11BD;D1EE;1110 116B 11BD; # (퇮; 퇮; 퇮; 퇮; 퇮; ) HANGUL SYLLABLE TWAEJ
+D1EF;D1EF;1110 116B 11BE;D1EF;1110 116B 11BE; # (퇯; 퇯; 퇯; 퇯; 퇯; ) HANGUL SYLLABLE TWAEC
+D1F0;D1F0;1110 116B 11BF;D1F0;1110 116B 11BF; # (퇰; 퇰; 퇰; 퇰; 퇰; ) HANGUL SYLLABLE TWAEK
+D1F1;D1F1;1110 116B 11C0;D1F1;1110 116B 11C0; # (퇱; 퇱; 퇱; 퇱; 퇱; ) HANGUL SYLLABLE TWAET
+D1F2;D1F2;1110 116B 11C1;D1F2;1110 116B 11C1; # (퇲; 퇲; 퇲; 퇲; 퇲; ) HANGUL SYLLABLE TWAEP
+D1F3;D1F3;1110 116B 11C2;D1F3;1110 116B 11C2; # (퇳; 퇳; 퇳; 퇳; 퇳; ) HANGUL SYLLABLE TWAEH
+D1F4;D1F4;1110 116C;D1F4;1110 116C; # (퇴; 퇴; 퇴; 퇴; 퇴; ) HANGUL SYLLABLE TOE
+D1F5;D1F5;1110 116C 11A8;D1F5;1110 116C 11A8; # (퇵; 퇵; 퇵; 퇵; 퇵; ) HANGUL SYLLABLE TOEG
+D1F6;D1F6;1110 116C 11A9;D1F6;1110 116C 11A9; # (퇶; 퇶; 퇶; 퇶; 퇶; ) HANGUL SYLLABLE TOEGG
+D1F7;D1F7;1110 116C 11AA;D1F7;1110 116C 11AA; # (퇷; 퇷; 퇷; 퇷; 퇷; ) HANGUL SYLLABLE TOEGS
+D1F8;D1F8;1110 116C 11AB;D1F8;1110 116C 11AB; # (퇸; 퇸; 퇸; 퇸; 퇸; ) HANGUL SYLLABLE TOEN
+D1F9;D1F9;1110 116C 11AC;D1F9;1110 116C 11AC; # (퇹; 퇹; 퇹; 퇹; 퇹; ) HANGUL SYLLABLE TOENJ
+D1FA;D1FA;1110 116C 11AD;D1FA;1110 116C 11AD; # (퇺; 퇺; 퇺; 퇺; 퇺; ) HANGUL SYLLABLE TOENH
+D1FB;D1FB;1110 116C 11AE;D1FB;1110 116C 11AE; # (퇻; 퇻; 퇻; 퇻; 퇻; ) HANGUL SYLLABLE TOED
+D1FC;D1FC;1110 116C 11AF;D1FC;1110 116C 11AF; # (퇼; 퇼; 퇼; 퇼; 퇼; ) HANGUL SYLLABLE TOEL
+D1FD;D1FD;1110 116C 11B0;D1FD;1110 116C 11B0; # (퇽; 퇽; 퇽; 퇽; 퇽; ) HANGUL SYLLABLE TOELG
+D1FE;D1FE;1110 116C 11B1;D1FE;1110 116C 11B1; # (퇾; 퇾; 퇾; 퇾; 퇾; ) HANGUL SYLLABLE TOELM
+D1FF;D1FF;1110 116C 11B2;D1FF;1110 116C 11B2; # (퇿; 퇿; 퇿; 퇿; 퇿; ) HANGUL SYLLABLE TOELB
+D200;D200;1110 116C 11B3;D200;1110 116C 11B3; # (툀; 툀; 툀; 툀; 툀; ) HANGUL SYLLABLE TOELS
+D201;D201;1110 116C 11B4;D201;1110 116C 11B4; # (툁; 툁; 툁; 툁; 툁; ) HANGUL SYLLABLE TOELT
+D202;D202;1110 116C 11B5;D202;1110 116C 11B5; # (툂; 툂; 툂; 툂; 툂; ) HANGUL SYLLABLE TOELP
+D203;D203;1110 116C 11B6;D203;1110 116C 11B6; # (툃; 툃; 툃; 툃; 툃; ) HANGUL SYLLABLE TOELH
+D204;D204;1110 116C 11B7;D204;1110 116C 11B7; # (툄; 툄; 툄; 툄; 툄; ) HANGUL SYLLABLE TOEM
+D205;D205;1110 116C 11B8;D205;1110 116C 11B8; # (툅; 툅; 툅; 툅; 툅; ) HANGUL SYLLABLE TOEB
+D206;D206;1110 116C 11B9;D206;1110 116C 11B9; # (툆; 툆; 툆; 툆; 툆; ) HANGUL SYLLABLE TOEBS
+D207;D207;1110 116C 11BA;D207;1110 116C 11BA; # (툇; 툇; 툇; 툇; 툇; ) HANGUL SYLLABLE TOES
+D208;D208;1110 116C 11BB;D208;1110 116C 11BB; # (툈; 툈; 툈; 툈; 툈; ) HANGUL SYLLABLE TOESS
+D209;D209;1110 116C 11BC;D209;1110 116C 11BC; # (툉; 툉; 툉; 툉; 툉; ) HANGUL SYLLABLE TOENG
+D20A;D20A;1110 116C 11BD;D20A;1110 116C 11BD; # (툊; 툊; 툊; 툊; 툊; ) HANGUL SYLLABLE TOEJ
+D20B;D20B;1110 116C 11BE;D20B;1110 116C 11BE; # (툋; 툋; 툋; 툋; 툋; ) HANGUL SYLLABLE TOEC
+D20C;D20C;1110 116C 11BF;D20C;1110 116C 11BF; # (툌; 툌; 툌; 툌; 툌; ) HANGUL SYLLABLE TOEK
+D20D;D20D;1110 116C 11C0;D20D;1110 116C 11C0; # (툍; 툍; 툍; 툍; 툍; ) HANGUL SYLLABLE TOET
+D20E;D20E;1110 116C 11C1;D20E;1110 116C 11C1; # (툎; 툎; 툎; 툎; 툎; ) HANGUL SYLLABLE TOEP
+D20F;D20F;1110 116C 11C2;D20F;1110 116C 11C2; # (툏; 툏; 툏; 툏; 툏; ) HANGUL SYLLABLE TOEH
+D210;D210;1110 116D;D210;1110 116D; # (툐; 툐; 툐; 툐; 툐; ) HANGUL SYLLABLE TYO
+D211;D211;1110 116D 11A8;D211;1110 116D 11A8; # (툑; 툑; 툑; 툑; 툑; ) HANGUL SYLLABLE TYOG
+D212;D212;1110 116D 11A9;D212;1110 116D 11A9; # (툒; 툒; 툒; 툒; 툒; ) HANGUL SYLLABLE TYOGG
+D213;D213;1110 116D 11AA;D213;1110 116D 11AA; # (툓; 툓; 툓; 툓; 툓; ) HANGUL SYLLABLE TYOGS
+D214;D214;1110 116D 11AB;D214;1110 116D 11AB; # (툔; 툔; 툔; 툔; 툔; ) HANGUL SYLLABLE TYON
+D215;D215;1110 116D 11AC;D215;1110 116D 11AC; # (툕; 툕; 툕; 툕; 툕; ) HANGUL SYLLABLE TYONJ
+D216;D216;1110 116D 11AD;D216;1110 116D 11AD; # (툖; 툖; 툖; 툖; 툖; ) HANGUL SYLLABLE TYONH
+D217;D217;1110 116D 11AE;D217;1110 116D 11AE; # (툗; 툗; 툗; 툗; 툗; ) HANGUL SYLLABLE TYOD
+D218;D218;1110 116D 11AF;D218;1110 116D 11AF; # (툘; 툘; 툘; 툘; 툘; ) HANGUL SYLLABLE TYOL
+D219;D219;1110 116D 11B0;D219;1110 116D 11B0; # (툙; 툙; 툙; 툙; 툙; ) HANGUL SYLLABLE TYOLG
+D21A;D21A;1110 116D 11B1;D21A;1110 116D 11B1; # (툚; 툚; 툚; 툚; 툚; ) HANGUL SYLLABLE TYOLM
+D21B;D21B;1110 116D 11B2;D21B;1110 116D 11B2; # (툛; 툛; 툛; 툛; 툛; ) HANGUL SYLLABLE TYOLB
+D21C;D21C;1110 116D 11B3;D21C;1110 116D 11B3; # (툜; 툜; 툜; 툜; 툜; ) HANGUL SYLLABLE TYOLS
+D21D;D21D;1110 116D 11B4;D21D;1110 116D 11B4; # (툝; 툝; 툝; 툝; 툝; ) HANGUL SYLLABLE TYOLT
+D21E;D21E;1110 116D 11B5;D21E;1110 116D 11B5; # (툞; 툞; 툞; 툞; 툞; ) HANGUL SYLLABLE TYOLP
+D21F;D21F;1110 116D 11B6;D21F;1110 116D 11B6; # (툟; 툟; 툟; 툟; 툟; ) HANGUL SYLLABLE TYOLH
+D220;D220;1110 116D 11B7;D220;1110 116D 11B7; # (툠; 툠; 툠; 툠; 툠; ) HANGUL SYLLABLE TYOM
+D221;D221;1110 116D 11B8;D221;1110 116D 11B8; # (툡; 툡; 툡; 툡; 툡; ) HANGUL SYLLABLE TYOB
+D222;D222;1110 116D 11B9;D222;1110 116D 11B9; # (툢; 툢; 툢; 툢; 툢; ) HANGUL SYLLABLE TYOBS
+D223;D223;1110 116D 11BA;D223;1110 116D 11BA; # (툣; 툣; 툣; 툣; 툣; ) HANGUL SYLLABLE TYOS
+D224;D224;1110 116D 11BB;D224;1110 116D 11BB; # (툤; 툤; 툤; 툤; 툤; ) HANGUL SYLLABLE TYOSS
+D225;D225;1110 116D 11BC;D225;1110 116D 11BC; # (툥; 툥; 툥; 툥; 툥; ) HANGUL SYLLABLE TYONG
+D226;D226;1110 116D 11BD;D226;1110 116D 11BD; # (툦; 툦; 툦; 툦; 툦; ) HANGUL SYLLABLE TYOJ
+D227;D227;1110 116D 11BE;D227;1110 116D 11BE; # (툧; 툧; 툧; 툧; 툧; ) HANGUL SYLLABLE TYOC
+D228;D228;1110 116D 11BF;D228;1110 116D 11BF; # (툨; 툨; 툨; 툨; 툨; ) HANGUL SYLLABLE TYOK
+D229;D229;1110 116D 11C0;D229;1110 116D 11C0; # (툩; 툩; 툩; 툩; 툩; ) HANGUL SYLLABLE TYOT
+D22A;D22A;1110 116D 11C1;D22A;1110 116D 11C1; # (툪; 툪; 툪; 툪; 툪; ) HANGUL SYLLABLE TYOP
+D22B;D22B;1110 116D 11C2;D22B;1110 116D 11C2; # (툫; 툫; 툫; 툫; 툫; ) HANGUL SYLLABLE TYOH
+D22C;D22C;1110 116E;D22C;1110 116E; # (투; 투; 투; 투; 투; ) HANGUL SYLLABLE TU
+D22D;D22D;1110 116E 11A8;D22D;1110 116E 11A8; # (툭; 툭; 툭; 툭; 툭; ) HANGUL SYLLABLE TUG
+D22E;D22E;1110 116E 11A9;D22E;1110 116E 11A9; # (툮; 툮; 툮; 툮; 툮; ) HANGUL SYLLABLE TUGG
+D22F;D22F;1110 116E 11AA;D22F;1110 116E 11AA; # (툯; 툯; 툯; 툯; 툯; ) HANGUL SYLLABLE TUGS
+D230;D230;1110 116E 11AB;D230;1110 116E 11AB; # (툰; 툰; 툰; 툰; 툰; ) HANGUL SYLLABLE TUN
+D231;D231;1110 116E 11AC;D231;1110 116E 11AC; # (툱; 툱; 툱; 툱; 툱; ) HANGUL SYLLABLE TUNJ
+D232;D232;1110 116E 11AD;D232;1110 116E 11AD; # (툲; 툲; 툲; 툲; 툲; ) HANGUL SYLLABLE TUNH
+D233;D233;1110 116E 11AE;D233;1110 116E 11AE; # (툳; 툳; 툳; 툳; 툳; ) HANGUL SYLLABLE TUD
+D234;D234;1110 116E 11AF;D234;1110 116E 11AF; # (툴; 툴; 툴; 툴; 툴; ) HANGUL SYLLABLE TUL
+D235;D235;1110 116E 11B0;D235;1110 116E 11B0; # (툵; 툵; 툵; 툵; 툵; ) HANGUL SYLLABLE TULG
+D236;D236;1110 116E 11B1;D236;1110 116E 11B1; # (툶; 툶; 툶; 툶; 툶; ) HANGUL SYLLABLE TULM
+D237;D237;1110 116E 11B2;D237;1110 116E 11B2; # (툷; 툷; 툷; 툷; 툷; ) HANGUL SYLLABLE TULB
+D238;D238;1110 116E 11B3;D238;1110 116E 11B3; # (툸; 툸; 툸; 툸; 툸; ) HANGUL SYLLABLE TULS
+D239;D239;1110 116E 11B4;D239;1110 116E 11B4; # (툹; 툹; 툹; 툹; 툹; ) HANGUL SYLLABLE TULT
+D23A;D23A;1110 116E 11B5;D23A;1110 116E 11B5; # (툺; 툺; 툺; 툺; 툺; ) HANGUL SYLLABLE TULP
+D23B;D23B;1110 116E 11B6;D23B;1110 116E 11B6; # (툻; 툻; 툻; 툻; 툻; ) HANGUL SYLLABLE TULH
+D23C;D23C;1110 116E 11B7;D23C;1110 116E 11B7; # (툼; 툼; 툼; 툼; 툼; ) HANGUL SYLLABLE TUM
+D23D;D23D;1110 116E 11B8;D23D;1110 116E 11B8; # (툽; 툽; 툽; 툽; 툽; ) HANGUL SYLLABLE TUB
+D23E;D23E;1110 116E 11B9;D23E;1110 116E 11B9; # (툾; 툾; 툾; 툾; 툾; ) HANGUL SYLLABLE TUBS
+D23F;D23F;1110 116E 11BA;D23F;1110 116E 11BA; # (툿; 툿; 툿; 툿; 툿; ) HANGUL SYLLABLE TUS
+D240;D240;1110 116E 11BB;D240;1110 116E 11BB; # (퉀; 퉀; 퉀; 퉀; 퉀; ) HANGUL SYLLABLE TUSS
+D241;D241;1110 116E 11BC;D241;1110 116E 11BC; # (퉁; 퉁; 퉁; 퉁; 퉁; ) HANGUL SYLLABLE TUNG
+D242;D242;1110 116E 11BD;D242;1110 116E 11BD; # (퉂; 퉂; 퉂; 퉂; 퉂; ) HANGUL SYLLABLE TUJ
+D243;D243;1110 116E 11BE;D243;1110 116E 11BE; # (퉃; 퉃; 퉃; 퉃; 퉃; ) HANGUL SYLLABLE TUC
+D244;D244;1110 116E 11BF;D244;1110 116E 11BF; # (퉄; 퉄; 퉄; 퉄; 퉄; ) HANGUL SYLLABLE TUK
+D245;D245;1110 116E 11C0;D245;1110 116E 11C0; # (퉅; 퉅; 퉅; 퉅; 퉅; ) HANGUL SYLLABLE TUT
+D246;D246;1110 116E 11C1;D246;1110 116E 11C1; # (퉆; 퉆; 퉆; 퉆; 퉆; ) HANGUL SYLLABLE TUP
+D247;D247;1110 116E 11C2;D247;1110 116E 11C2; # (퉇; 퉇; 퉇; 퉇; 퉇; ) HANGUL SYLLABLE TUH
+D248;D248;1110 116F;D248;1110 116F; # (퉈; 퉈; 퉈; 퉈; 퉈; ) HANGUL SYLLABLE TWEO
+D249;D249;1110 116F 11A8;D249;1110 116F 11A8; # (퉉; 퉉; 퉉; 퉉; 퉉; ) HANGUL SYLLABLE TWEOG
+D24A;D24A;1110 116F 11A9;D24A;1110 116F 11A9; # (퉊; 퉊; 퉊; 퉊; 퉊; ) HANGUL SYLLABLE TWEOGG
+D24B;D24B;1110 116F 11AA;D24B;1110 116F 11AA; # (퉋; 퉋; 퉋; 퉋; 퉋; ) HANGUL SYLLABLE TWEOGS
+D24C;D24C;1110 116F 11AB;D24C;1110 116F 11AB; # (퉌; 퉌; 퉌; 퉌; 퉌; ) HANGUL SYLLABLE TWEON
+D24D;D24D;1110 116F 11AC;D24D;1110 116F 11AC; # (퉍; 퉍; 퉍; 퉍; 퉍; ) HANGUL SYLLABLE TWEONJ
+D24E;D24E;1110 116F 11AD;D24E;1110 116F 11AD; # (퉎; 퉎; 퉎; 퉎; 퉎; ) HANGUL SYLLABLE TWEONH
+D24F;D24F;1110 116F 11AE;D24F;1110 116F 11AE; # (퉏; 퉏; 퉏; 퉏; 퉏; ) HANGUL SYLLABLE TWEOD
+D250;D250;1110 116F 11AF;D250;1110 116F 11AF; # (퉐; 퉐; 퉐; 퉐; 퉐; ) HANGUL SYLLABLE TWEOL
+D251;D251;1110 116F 11B0;D251;1110 116F 11B0; # (퉑; 퉑; 퉑; 퉑; 퉑; ) HANGUL SYLLABLE TWEOLG
+D252;D252;1110 116F 11B1;D252;1110 116F 11B1; # (퉒; 퉒; 퉒; 퉒; 퉒; ) HANGUL SYLLABLE TWEOLM
+D253;D253;1110 116F 11B2;D253;1110 116F 11B2; # (퉓; 퉓; 퉓; 퉓; 퉓; ) HANGUL SYLLABLE TWEOLB
+D254;D254;1110 116F 11B3;D254;1110 116F 11B3; # (퉔; 퉔; 퉔; 퉔; 퉔; ) HANGUL SYLLABLE TWEOLS
+D255;D255;1110 116F 11B4;D255;1110 116F 11B4; # (퉕; 퉕; 퉕; 퉕; 퉕; ) HANGUL SYLLABLE TWEOLT
+D256;D256;1110 116F 11B5;D256;1110 116F 11B5; # (퉖; 퉖; 퉖; 퉖; 퉖; ) HANGUL SYLLABLE TWEOLP
+D257;D257;1110 116F 11B6;D257;1110 116F 11B6; # (퉗; 퉗; 퉗; 퉗; 퉗; ) HANGUL SYLLABLE TWEOLH
+D258;D258;1110 116F 11B7;D258;1110 116F 11B7; # (퉘; 퉘; 퉘; 퉘; 퉘; ) HANGUL SYLLABLE TWEOM
+D259;D259;1110 116F 11B8;D259;1110 116F 11B8; # (퉙; 퉙; 퉙; 퉙; 퉙; ) HANGUL SYLLABLE TWEOB
+D25A;D25A;1110 116F 11B9;D25A;1110 116F 11B9; # (퉚; 퉚; 퉚; 퉚; 퉚; ) HANGUL SYLLABLE TWEOBS
+D25B;D25B;1110 116F 11BA;D25B;1110 116F 11BA; # (퉛; 퉛; 퉛; 퉛; 퉛; ) HANGUL SYLLABLE TWEOS
+D25C;D25C;1110 116F 11BB;D25C;1110 116F 11BB; # (퉜; 퉜; 퉜; 퉜; 퉜; ) HANGUL SYLLABLE TWEOSS
+D25D;D25D;1110 116F 11BC;D25D;1110 116F 11BC; # (퉝; 퉝; 퉝; 퉝; 퉝; ) HANGUL SYLLABLE TWEONG
+D25E;D25E;1110 116F 11BD;D25E;1110 116F 11BD; # (퉞; 퉞; 퉞; 퉞; 퉞; ) HANGUL SYLLABLE TWEOJ
+D25F;D25F;1110 116F 11BE;D25F;1110 116F 11BE; # (퉟; 퉟; 퉟; 퉟; 퉟; ) HANGUL SYLLABLE TWEOC
+D260;D260;1110 116F 11BF;D260;1110 116F 11BF; # (퉠; 퉠; 퉠; 퉠; 퉠; ) HANGUL SYLLABLE TWEOK
+D261;D261;1110 116F 11C0;D261;1110 116F 11C0; # (퉡; 퉡; 퉡; 퉡; 퉡; ) HANGUL SYLLABLE TWEOT
+D262;D262;1110 116F 11C1;D262;1110 116F 11C1; # (퉢; 퉢; 퉢; 퉢; 퉢; ) HANGUL SYLLABLE TWEOP
+D263;D263;1110 116F 11C2;D263;1110 116F 11C2; # (퉣; 퉣; 퉣; 퉣; 퉣; ) HANGUL SYLLABLE TWEOH
+D264;D264;1110 1170;D264;1110 1170; # (퉤; 퉤; 퉤; 퉤; 퉤; ) HANGUL SYLLABLE TWE
+D265;D265;1110 1170 11A8;D265;1110 1170 11A8; # (퉥; 퉥; 퉥; 퉥; 퉥; ) HANGUL SYLLABLE TWEG
+D266;D266;1110 1170 11A9;D266;1110 1170 11A9; # (퉦; 퉦; 퉦; 퉦; 퉦; ) HANGUL SYLLABLE TWEGG
+D267;D267;1110 1170 11AA;D267;1110 1170 11AA; # (퉧; 퉧; 퉧; 퉧; 퉧; ) HANGUL SYLLABLE TWEGS
+D268;D268;1110 1170 11AB;D268;1110 1170 11AB; # (퉨; 퉨; 퉨; 퉨; 퉨; ) HANGUL SYLLABLE TWEN
+D269;D269;1110 1170 11AC;D269;1110 1170 11AC; # (퉩; 퉩; 퉩; 퉩; 퉩; ) HANGUL SYLLABLE TWENJ
+D26A;D26A;1110 1170 11AD;D26A;1110 1170 11AD; # (퉪; 퉪; 퉪; 퉪; 퉪; ) HANGUL SYLLABLE TWENH
+D26B;D26B;1110 1170 11AE;D26B;1110 1170 11AE; # (퉫; 퉫; 퉫; 퉫; 퉫; ) HANGUL SYLLABLE TWED
+D26C;D26C;1110 1170 11AF;D26C;1110 1170 11AF; # (퉬; 퉬; 퉬; 퉬; 퉬; ) HANGUL SYLLABLE TWEL
+D26D;D26D;1110 1170 11B0;D26D;1110 1170 11B0; # (퉭; 퉭; 퉭; 퉭; 퉭; ) HANGUL SYLLABLE TWELG
+D26E;D26E;1110 1170 11B1;D26E;1110 1170 11B1; # (퉮; 퉮; 퉮; 퉮; 퉮; ) HANGUL SYLLABLE TWELM
+D26F;D26F;1110 1170 11B2;D26F;1110 1170 11B2; # (퉯; 퉯; 퉯; 퉯; 퉯; ) HANGUL SYLLABLE TWELB
+D270;D270;1110 1170 11B3;D270;1110 1170 11B3; # (퉰; 퉰; 퉰; 퉰; 퉰; ) HANGUL SYLLABLE TWELS
+D271;D271;1110 1170 11B4;D271;1110 1170 11B4; # (퉱; 퉱; 퉱; 퉱; 퉱; ) HANGUL SYLLABLE TWELT
+D272;D272;1110 1170 11B5;D272;1110 1170 11B5; # (퉲; 퉲; 퉲; 퉲; 퉲; ) HANGUL SYLLABLE TWELP
+D273;D273;1110 1170 11B6;D273;1110 1170 11B6; # (퉳; 퉳; 퉳; 퉳; 퉳; ) HANGUL SYLLABLE TWELH
+D274;D274;1110 1170 11B7;D274;1110 1170 11B7; # (퉴; 퉴; 퉴; 퉴; 퉴; ) HANGUL SYLLABLE TWEM
+D275;D275;1110 1170 11B8;D275;1110 1170 11B8; # (퉵; 퉵; 퉵; 퉵; 퉵; ) HANGUL SYLLABLE TWEB
+D276;D276;1110 1170 11B9;D276;1110 1170 11B9; # (퉶; 퉶; 퉶; 퉶; 퉶; ) HANGUL SYLLABLE TWEBS
+D277;D277;1110 1170 11BA;D277;1110 1170 11BA; # (퉷; 퉷; 퉷; 퉷; 퉷; ) HANGUL SYLLABLE TWES
+D278;D278;1110 1170 11BB;D278;1110 1170 11BB; # (퉸; 퉸; 퉸; 퉸; 퉸; ) HANGUL SYLLABLE TWESS
+D279;D279;1110 1170 11BC;D279;1110 1170 11BC; # (퉹; 퉹; 퉹; 퉹; 퉹; ) HANGUL SYLLABLE TWENG
+D27A;D27A;1110 1170 11BD;D27A;1110 1170 11BD; # (퉺; 퉺; 퉺; 퉺; 퉺; ) HANGUL SYLLABLE TWEJ
+D27B;D27B;1110 1170 11BE;D27B;1110 1170 11BE; # (퉻; 퉻; 퉻; 퉻; 퉻; ) HANGUL SYLLABLE TWEC
+D27C;D27C;1110 1170 11BF;D27C;1110 1170 11BF; # (퉼; 퉼; 퉼; 퉼; 퉼; ) HANGUL SYLLABLE TWEK
+D27D;D27D;1110 1170 11C0;D27D;1110 1170 11C0; # (퉽; 퉽; 퉽; 퉽; 퉽; ) HANGUL SYLLABLE TWET
+D27E;D27E;1110 1170 11C1;D27E;1110 1170 11C1; # (퉾; 퉾; 퉾; 퉾; 퉾; ) HANGUL SYLLABLE TWEP
+D27F;D27F;1110 1170 11C2;D27F;1110 1170 11C2; # (퉿; 퉿; 퉿; 퉿; 퉿; ) HANGUL SYLLABLE TWEH
+D280;D280;1110 1171;D280;1110 1171; # (튀; 튀; 튀; 튀; 튀; ) HANGUL SYLLABLE TWI
+D281;D281;1110 1171 11A8;D281;1110 1171 11A8; # (튁; 튁; 튁; 튁; 튁; ) HANGUL SYLLABLE TWIG
+D282;D282;1110 1171 11A9;D282;1110 1171 11A9; # (튂; 튂; 튂; 튂; 튂; ) HANGUL SYLLABLE TWIGG
+D283;D283;1110 1171 11AA;D283;1110 1171 11AA; # (튃; 튃; 튃; 튃; 튃; ) HANGUL SYLLABLE TWIGS
+D284;D284;1110 1171 11AB;D284;1110 1171 11AB; # (튄; 튄; 튄; 튄; 튄; ) HANGUL SYLLABLE TWIN
+D285;D285;1110 1171 11AC;D285;1110 1171 11AC; # (튅; 튅; 튅; 튅; 튅; ) HANGUL SYLLABLE TWINJ
+D286;D286;1110 1171 11AD;D286;1110 1171 11AD; # (튆; 튆; 튆; 튆; 튆; ) HANGUL SYLLABLE TWINH
+D287;D287;1110 1171 11AE;D287;1110 1171 11AE; # (튇; 튇; 튇; 튇; 튇; ) HANGUL SYLLABLE TWID
+D288;D288;1110 1171 11AF;D288;1110 1171 11AF; # (튈; 튈; 튈; 튈; 튈; ) HANGUL SYLLABLE TWIL
+D289;D289;1110 1171 11B0;D289;1110 1171 11B0; # (튉; 튉; 튉; 튉; 튉; ) HANGUL SYLLABLE TWILG
+D28A;D28A;1110 1171 11B1;D28A;1110 1171 11B1; # (튊; 튊; 튊; 튊; 튊; ) HANGUL SYLLABLE TWILM
+D28B;D28B;1110 1171 11B2;D28B;1110 1171 11B2; # (튋; 튋; 튋; 튋; 튋; ) HANGUL SYLLABLE TWILB
+D28C;D28C;1110 1171 11B3;D28C;1110 1171 11B3; # (튌; 튌; 튌; 튌; 튌; ) HANGUL SYLLABLE TWILS
+D28D;D28D;1110 1171 11B4;D28D;1110 1171 11B4; # (튍; 튍; 튍; 튍; 튍; ) HANGUL SYLLABLE TWILT
+D28E;D28E;1110 1171 11B5;D28E;1110 1171 11B5; # (튎; 튎; 튎; 튎; 튎; ) HANGUL SYLLABLE TWILP
+D28F;D28F;1110 1171 11B6;D28F;1110 1171 11B6; # (튏; 튏; 튏; 튏; 튏; ) HANGUL SYLLABLE TWILH
+D290;D290;1110 1171 11B7;D290;1110 1171 11B7; # (튐; 튐; 튐; 튐; 튐; ) HANGUL SYLLABLE TWIM
+D291;D291;1110 1171 11B8;D291;1110 1171 11B8; # (튑; 튑; 튑; 튑; 튑; ) HANGUL SYLLABLE TWIB
+D292;D292;1110 1171 11B9;D292;1110 1171 11B9; # (튒; 튒; 튒; 튒; 튒; ) HANGUL SYLLABLE TWIBS
+D293;D293;1110 1171 11BA;D293;1110 1171 11BA; # (튓; 튓; 튓; 튓; 튓; ) HANGUL SYLLABLE TWIS
+D294;D294;1110 1171 11BB;D294;1110 1171 11BB; # (튔; 튔; 튔; 튔; 튔; ) HANGUL SYLLABLE TWISS
+D295;D295;1110 1171 11BC;D295;1110 1171 11BC; # (튕; 튕; 튕; 튕; 튕; ) HANGUL SYLLABLE TWING
+D296;D296;1110 1171 11BD;D296;1110 1171 11BD; # (튖; 튖; 튖; 튖; 튖; ) HANGUL SYLLABLE TWIJ
+D297;D297;1110 1171 11BE;D297;1110 1171 11BE; # (튗; 튗; 튗; 튗; 튗; ) HANGUL SYLLABLE TWIC
+D298;D298;1110 1171 11BF;D298;1110 1171 11BF; # (튘; 튘; 튘; 튘; 튘; ) HANGUL SYLLABLE TWIK
+D299;D299;1110 1171 11C0;D299;1110 1171 11C0; # (튙; 튙; 튙; 튙; 튙; ) HANGUL SYLLABLE TWIT
+D29A;D29A;1110 1171 11C1;D29A;1110 1171 11C1; # (튚; 튚; 튚; 튚; 튚; ) HANGUL SYLLABLE TWIP
+D29B;D29B;1110 1171 11C2;D29B;1110 1171 11C2; # (튛; 튛; 튛; 튛; 튛; ) HANGUL SYLLABLE TWIH
+D29C;D29C;1110 1172;D29C;1110 1172; # (튜; 튜; 튜; 튜; 튜; ) HANGUL SYLLABLE TYU
+D29D;D29D;1110 1172 11A8;D29D;1110 1172 11A8; # (튝; 튝; 튝; 튝; 튝; ) HANGUL SYLLABLE TYUG
+D29E;D29E;1110 1172 11A9;D29E;1110 1172 11A9; # (튞; 튞; 튞; 튞; 튞; ) HANGUL SYLLABLE TYUGG
+D29F;D29F;1110 1172 11AA;D29F;1110 1172 11AA; # (튟; 튟; 튟; 튟; 튟; ) HANGUL SYLLABLE TYUGS
+D2A0;D2A0;1110 1172 11AB;D2A0;1110 1172 11AB; # (튠; 튠; 튠; 튠; 튠; ) HANGUL SYLLABLE TYUN
+D2A1;D2A1;1110 1172 11AC;D2A1;1110 1172 11AC; # (튡; 튡; 튡; 튡; 튡; ) HANGUL SYLLABLE TYUNJ
+D2A2;D2A2;1110 1172 11AD;D2A2;1110 1172 11AD; # (튢; 튢; 튢; 튢; 튢; ) HANGUL SYLLABLE TYUNH
+D2A3;D2A3;1110 1172 11AE;D2A3;1110 1172 11AE; # (튣; 튣; 튣; 튣; 튣; ) HANGUL SYLLABLE TYUD
+D2A4;D2A4;1110 1172 11AF;D2A4;1110 1172 11AF; # (튤; 튤; 튤; 튤; 튤; ) HANGUL SYLLABLE TYUL
+D2A5;D2A5;1110 1172 11B0;D2A5;1110 1172 11B0; # (튥; 튥; 튥; 튥; 튥; ) HANGUL SYLLABLE TYULG
+D2A6;D2A6;1110 1172 11B1;D2A6;1110 1172 11B1; # (튦; 튦; 튦; 튦; 튦; ) HANGUL SYLLABLE TYULM
+D2A7;D2A7;1110 1172 11B2;D2A7;1110 1172 11B2; # (튧; 튧; 튧; 튧; 튧; ) HANGUL SYLLABLE TYULB
+D2A8;D2A8;1110 1172 11B3;D2A8;1110 1172 11B3; # (튨; 튨; 튨; 튨; 튨; ) HANGUL SYLLABLE TYULS
+D2A9;D2A9;1110 1172 11B4;D2A9;1110 1172 11B4; # (튩; 튩; 튩; 튩; 튩; ) HANGUL SYLLABLE TYULT
+D2AA;D2AA;1110 1172 11B5;D2AA;1110 1172 11B5; # (튪; 튪; 튪; 튪; 튪; ) HANGUL SYLLABLE TYULP
+D2AB;D2AB;1110 1172 11B6;D2AB;1110 1172 11B6; # (튫; 튫; 튫; 튫; 튫; ) HANGUL SYLLABLE TYULH
+D2AC;D2AC;1110 1172 11B7;D2AC;1110 1172 11B7; # (튬; 튬; 튬; 튬; 튬; ) HANGUL SYLLABLE TYUM
+D2AD;D2AD;1110 1172 11B8;D2AD;1110 1172 11B8; # (튭; 튭; 튭; 튭; 튭; ) HANGUL SYLLABLE TYUB
+D2AE;D2AE;1110 1172 11B9;D2AE;1110 1172 11B9; # (튮; 튮; 튮; 튮; 튮; ) HANGUL SYLLABLE TYUBS
+D2AF;D2AF;1110 1172 11BA;D2AF;1110 1172 11BA; # (튯; 튯; 튯; 튯; 튯; ) HANGUL SYLLABLE TYUS
+D2B0;D2B0;1110 1172 11BB;D2B0;1110 1172 11BB; # (튰; 튰; 튰; 튰; 튰; ) HANGUL SYLLABLE TYUSS
+D2B1;D2B1;1110 1172 11BC;D2B1;1110 1172 11BC; # (튱; 튱; 튱; 튱; 튱; ) HANGUL SYLLABLE TYUNG
+D2B2;D2B2;1110 1172 11BD;D2B2;1110 1172 11BD; # (튲; 튲; 튲; 튲; 튲; ) HANGUL SYLLABLE TYUJ
+D2B3;D2B3;1110 1172 11BE;D2B3;1110 1172 11BE; # (튳; 튳; 튳; 튳; 튳; ) HANGUL SYLLABLE TYUC
+D2B4;D2B4;1110 1172 11BF;D2B4;1110 1172 11BF; # (튴; 튴; 튴; 튴; 튴; ) HANGUL SYLLABLE TYUK
+D2B5;D2B5;1110 1172 11C0;D2B5;1110 1172 11C0; # (튵; 튵; 튵; 튵; 튵; ) HANGUL SYLLABLE TYUT
+D2B6;D2B6;1110 1172 11C1;D2B6;1110 1172 11C1; # (튶; 튶; 튶; 튶; 튶; ) HANGUL SYLLABLE TYUP
+D2B7;D2B7;1110 1172 11C2;D2B7;1110 1172 11C2; # (튷; 튷; 튷; 튷; 튷; ) HANGUL SYLLABLE TYUH
+D2B8;D2B8;1110 1173;D2B8;1110 1173; # (트; 트; 트; 트; 트; ) HANGUL SYLLABLE TEU
+D2B9;D2B9;1110 1173 11A8;D2B9;1110 1173 11A8; # (특; 특; 특; 특; 특; ) HANGUL SYLLABLE TEUG
+D2BA;D2BA;1110 1173 11A9;D2BA;1110 1173 11A9; # (튺; 튺; 튺; 튺; 튺; ) HANGUL SYLLABLE TEUGG
+D2BB;D2BB;1110 1173 11AA;D2BB;1110 1173 11AA; # (튻; 튻; 튻; 튻; 튻; ) HANGUL SYLLABLE TEUGS
+D2BC;D2BC;1110 1173 11AB;D2BC;1110 1173 11AB; # (튼; 튼; 튼; 튼; 튼; ) HANGUL SYLLABLE TEUN
+D2BD;D2BD;1110 1173 11AC;D2BD;1110 1173 11AC; # (튽; 튽; 튽; 튽; 튽; ) HANGUL SYLLABLE TEUNJ
+D2BE;D2BE;1110 1173 11AD;D2BE;1110 1173 11AD; # (튾; 튾; 튾; 튾; 튾; ) HANGUL SYLLABLE TEUNH
+D2BF;D2BF;1110 1173 11AE;D2BF;1110 1173 11AE; # (튿; 튿; 튿; 튿; 튿; ) HANGUL SYLLABLE TEUD
+D2C0;D2C0;1110 1173 11AF;D2C0;1110 1173 11AF; # (틀; 틀; 틀; 틀; 틀; ) HANGUL SYLLABLE TEUL
+D2C1;D2C1;1110 1173 11B0;D2C1;1110 1173 11B0; # (틁; 틁; 틁; 틁; 틁; ) HANGUL SYLLABLE TEULG
+D2C2;D2C2;1110 1173 11B1;D2C2;1110 1173 11B1; # (틂; 틂; 틂; 틂; 틂; ) HANGUL SYLLABLE TEULM
+D2C3;D2C3;1110 1173 11B2;D2C3;1110 1173 11B2; # (틃; 틃; 틃; 틃; 틃; ) HANGUL SYLLABLE TEULB
+D2C4;D2C4;1110 1173 11B3;D2C4;1110 1173 11B3; # (틄; 틄; 틄; 틄; 틄; ) HANGUL SYLLABLE TEULS
+D2C5;D2C5;1110 1173 11B4;D2C5;1110 1173 11B4; # (틅; 틅; 틅; 틅; 틅; ) HANGUL SYLLABLE TEULT
+D2C6;D2C6;1110 1173 11B5;D2C6;1110 1173 11B5; # (틆; 틆; 틆; 틆; 틆; ) HANGUL SYLLABLE TEULP
+D2C7;D2C7;1110 1173 11B6;D2C7;1110 1173 11B6; # (틇; 틇; 틇; 틇; 틇; ) HANGUL SYLLABLE TEULH
+D2C8;D2C8;1110 1173 11B7;D2C8;1110 1173 11B7; # (틈; 틈; 틈; 틈; 틈; ) HANGUL SYLLABLE TEUM
+D2C9;D2C9;1110 1173 11B8;D2C9;1110 1173 11B8; # (틉; 틉; 틉; 틉; 틉; ) HANGUL SYLLABLE TEUB
+D2CA;D2CA;1110 1173 11B9;D2CA;1110 1173 11B9; # (틊; 틊; 틊; 틊; 틊; ) HANGUL SYLLABLE TEUBS
+D2CB;D2CB;1110 1173 11BA;D2CB;1110 1173 11BA; # (틋; 틋; 틋; 틋; 틋; ) HANGUL SYLLABLE TEUS
+D2CC;D2CC;1110 1173 11BB;D2CC;1110 1173 11BB; # (틌; 틌; 틌; 틌; 틌; ) HANGUL SYLLABLE TEUSS
+D2CD;D2CD;1110 1173 11BC;D2CD;1110 1173 11BC; # (틍; 틍; 틍; 틍; 틍; ) HANGUL SYLLABLE TEUNG
+D2CE;D2CE;1110 1173 11BD;D2CE;1110 1173 11BD; # (틎; 틎; 틎; 틎; 틎; ) HANGUL SYLLABLE TEUJ
+D2CF;D2CF;1110 1173 11BE;D2CF;1110 1173 11BE; # (틏; 틏; 틏; 틏; 틏; ) HANGUL SYLLABLE TEUC
+D2D0;D2D0;1110 1173 11BF;D2D0;1110 1173 11BF; # (틐; 틐; 틐; 틐; 틐; ) HANGUL SYLLABLE TEUK
+D2D1;D2D1;1110 1173 11C0;D2D1;1110 1173 11C0; # (틑; 틑; 틑; 틑; 틑; ) HANGUL SYLLABLE TEUT
+D2D2;D2D2;1110 1173 11C1;D2D2;1110 1173 11C1; # (틒; 틒; 틒; 틒; 틒; ) HANGUL SYLLABLE TEUP
+D2D3;D2D3;1110 1173 11C2;D2D3;1110 1173 11C2; # (틓; 틓; 틓; 틓; 틓; ) HANGUL SYLLABLE TEUH
+D2D4;D2D4;1110 1174;D2D4;1110 1174; # (틔; 틔; 틔; 틔; 틔; ) HANGUL SYLLABLE TYI
+D2D5;D2D5;1110 1174 11A8;D2D5;1110 1174 11A8; # (틕; 틕; 틕; 틕; 틕; ) HANGUL SYLLABLE TYIG
+D2D6;D2D6;1110 1174 11A9;D2D6;1110 1174 11A9; # (틖; 틖; 틖; 틖; 틖; ) HANGUL SYLLABLE TYIGG
+D2D7;D2D7;1110 1174 11AA;D2D7;1110 1174 11AA; # (틗; 틗; 틗; 틗; 틗; ) HANGUL SYLLABLE TYIGS
+D2D8;D2D8;1110 1174 11AB;D2D8;1110 1174 11AB; # (틘; 틘; 틘; 틘; 틘; ) HANGUL SYLLABLE TYIN
+D2D9;D2D9;1110 1174 11AC;D2D9;1110 1174 11AC; # (틙; 틙; 틙; 틙; 틙; ) HANGUL SYLLABLE TYINJ
+D2DA;D2DA;1110 1174 11AD;D2DA;1110 1174 11AD; # (틚; 틚; 틚; 틚; 틚; ) HANGUL SYLLABLE TYINH
+D2DB;D2DB;1110 1174 11AE;D2DB;1110 1174 11AE; # (틛; 틛; 틛; 틛; 틛; ) HANGUL SYLLABLE TYID
+D2DC;D2DC;1110 1174 11AF;D2DC;1110 1174 11AF; # (틜; 틜; 틜; 틜; 틜; ) HANGUL SYLLABLE TYIL
+D2DD;D2DD;1110 1174 11B0;D2DD;1110 1174 11B0; # (틝; 틝; 틝; 틝; 틝; ) HANGUL SYLLABLE TYILG
+D2DE;D2DE;1110 1174 11B1;D2DE;1110 1174 11B1; # (틞; 틞; 틞; 틞; 틞; ) HANGUL SYLLABLE TYILM
+D2DF;D2DF;1110 1174 11B2;D2DF;1110 1174 11B2; # (틟; 틟; 틟; 틟; 틟; ) HANGUL SYLLABLE TYILB
+D2E0;D2E0;1110 1174 11B3;D2E0;1110 1174 11B3; # (틠; 틠; 틠; 틠; 틠; ) HANGUL SYLLABLE TYILS
+D2E1;D2E1;1110 1174 11B4;D2E1;1110 1174 11B4; # (틡; 틡; 틡; 틡; 틡; ) HANGUL SYLLABLE TYILT
+D2E2;D2E2;1110 1174 11B5;D2E2;1110 1174 11B5; # (틢; 틢; 틢; 틢; 틢; ) HANGUL SYLLABLE TYILP
+D2E3;D2E3;1110 1174 11B6;D2E3;1110 1174 11B6; # (틣; 틣; 틣; 틣; 틣; ) HANGUL SYLLABLE TYILH
+D2E4;D2E4;1110 1174 11B7;D2E4;1110 1174 11B7; # (틤; 틤; 틤; 틤; 틤; ) HANGUL SYLLABLE TYIM
+D2E5;D2E5;1110 1174 11B8;D2E5;1110 1174 11B8; # (틥; 틥; 틥; 틥; 틥; ) HANGUL SYLLABLE TYIB
+D2E6;D2E6;1110 1174 11B9;D2E6;1110 1174 11B9; # (틦; 틦; 틦; 틦; 틦; ) HANGUL SYLLABLE TYIBS
+D2E7;D2E7;1110 1174 11BA;D2E7;1110 1174 11BA; # (틧; 틧; 틧; 틧; 틧; ) HANGUL SYLLABLE TYIS
+D2E8;D2E8;1110 1174 11BB;D2E8;1110 1174 11BB; # (틨; 틨; 틨; 틨; 틨; ) HANGUL SYLLABLE TYISS
+D2E9;D2E9;1110 1174 11BC;D2E9;1110 1174 11BC; # (틩; 틩; 틩; 틩; 틩; ) HANGUL SYLLABLE TYING
+D2EA;D2EA;1110 1174 11BD;D2EA;1110 1174 11BD; # (틪; 틪; 틪; 틪; 틪; ) HANGUL SYLLABLE TYIJ
+D2EB;D2EB;1110 1174 11BE;D2EB;1110 1174 11BE; # (틫; 틫; 틫; 틫; 틫; ) HANGUL SYLLABLE TYIC
+D2EC;D2EC;1110 1174 11BF;D2EC;1110 1174 11BF; # (틬; 틬; 틬; 틬; 틬; ) HANGUL SYLLABLE TYIK
+D2ED;D2ED;1110 1174 11C0;D2ED;1110 1174 11C0; # (틭; 틭; 틭; 틭; 틭; ) HANGUL SYLLABLE TYIT
+D2EE;D2EE;1110 1174 11C1;D2EE;1110 1174 11C1; # (틮; 틮; 틮; 틮; 틮; ) HANGUL SYLLABLE TYIP
+D2EF;D2EF;1110 1174 11C2;D2EF;1110 1174 11C2; # (틯; 틯; 틯; 틯; 틯; ) HANGUL SYLLABLE TYIH
+D2F0;D2F0;1110 1175;D2F0;1110 1175; # (티; 티; 티; 티; 티; ) HANGUL SYLLABLE TI
+D2F1;D2F1;1110 1175 11A8;D2F1;1110 1175 11A8; # (틱; 틱; 틱; 틱; 틱; ) HANGUL SYLLABLE TIG
+D2F2;D2F2;1110 1175 11A9;D2F2;1110 1175 11A9; # (틲; 틲; 틲; 틲; 틲; ) HANGUL SYLLABLE TIGG
+D2F3;D2F3;1110 1175 11AA;D2F3;1110 1175 11AA; # (틳; 틳; 틳; 틳; 틳; ) HANGUL SYLLABLE TIGS
+D2F4;D2F4;1110 1175 11AB;D2F4;1110 1175 11AB; # (틴; 틴; 틴; 틴; 틴; ) HANGUL SYLLABLE TIN
+D2F5;D2F5;1110 1175 11AC;D2F5;1110 1175 11AC; # (틵; 틵; 틵; 틵; 틵; ) HANGUL SYLLABLE TINJ
+D2F6;D2F6;1110 1175 11AD;D2F6;1110 1175 11AD; # (틶; 틶; 틶; 틶; 틶; ) HANGUL SYLLABLE TINH
+D2F7;D2F7;1110 1175 11AE;D2F7;1110 1175 11AE; # (틷; 틷; 틷; 틷; 틷; ) HANGUL SYLLABLE TID
+D2F8;D2F8;1110 1175 11AF;D2F8;1110 1175 11AF; # (틸; 틸; 틸; 틸; 틸; ) HANGUL SYLLABLE TIL
+D2F9;D2F9;1110 1175 11B0;D2F9;1110 1175 11B0; # (틹; 틹; 틹; 틹; 틹; ) HANGUL SYLLABLE TILG
+D2FA;D2FA;1110 1175 11B1;D2FA;1110 1175 11B1; # (틺; 틺; 틺; 틺; 틺; ) HANGUL SYLLABLE TILM
+D2FB;D2FB;1110 1175 11B2;D2FB;1110 1175 11B2; # (틻; 틻; 틻; 틻; 틻; ) HANGUL SYLLABLE TILB
+D2FC;D2FC;1110 1175 11B3;D2FC;1110 1175 11B3; # (틼; 틼; 틼; 틼; 틼; ) HANGUL SYLLABLE TILS
+D2FD;D2FD;1110 1175 11B4;D2FD;1110 1175 11B4; # (틽; 틽; 틽; 틽; 틽; ) HANGUL SYLLABLE TILT
+D2FE;D2FE;1110 1175 11B5;D2FE;1110 1175 11B5; # (틾; 틾; 틾; 틾; 틾; ) HANGUL SYLLABLE TILP
+D2FF;D2FF;1110 1175 11B6;D2FF;1110 1175 11B6; # (틿; 틿; 틿; 틿; 틿; ) HANGUL SYLLABLE TILH
+D300;D300;1110 1175 11B7;D300;1110 1175 11B7; # (팀; 팀; 팀; 팀; 팀; ) HANGUL SYLLABLE TIM
+D301;D301;1110 1175 11B8;D301;1110 1175 11B8; # (팁; 팁; 팁; 팁; 팁; ) HANGUL SYLLABLE TIB
+D302;D302;1110 1175 11B9;D302;1110 1175 11B9; # (팂; 팂; 팂; 팂; 팂; ) HANGUL SYLLABLE TIBS
+D303;D303;1110 1175 11BA;D303;1110 1175 11BA; # (팃; 팃; 팃; 팃; 팃; ) HANGUL SYLLABLE TIS
+D304;D304;1110 1175 11BB;D304;1110 1175 11BB; # (팄; 팄; 팄; 팄; 팄; ) HANGUL SYLLABLE TISS
+D305;D305;1110 1175 11BC;D305;1110 1175 11BC; # (팅; 팅; 팅; 팅; 팅; ) HANGUL SYLLABLE TING
+D306;D306;1110 1175 11BD;D306;1110 1175 11BD; # (팆; 팆; 팆; 팆; 팆; ) HANGUL SYLLABLE TIJ
+D307;D307;1110 1175 11BE;D307;1110 1175 11BE; # (팇; 팇; 팇; 팇; 팇; ) HANGUL SYLLABLE TIC
+D308;D308;1110 1175 11BF;D308;1110 1175 11BF; # (팈; 팈; 팈; 팈; 팈; ) HANGUL SYLLABLE TIK
+D309;D309;1110 1175 11C0;D309;1110 1175 11C0; # (팉; 팉; 팉; 팉; 팉; ) HANGUL SYLLABLE TIT
+D30A;D30A;1110 1175 11C1;D30A;1110 1175 11C1; # (팊; 팊; 팊; 팊; 팊; ) HANGUL SYLLABLE TIP
+D30B;D30B;1110 1175 11C2;D30B;1110 1175 11C2; # (팋; 팋; 팋; 팋; 팋; ) HANGUL SYLLABLE TIH
+D30C;D30C;1111 1161;D30C;1111 1161; # (파; 파; 파; 파; 파; ) HANGUL SYLLABLE PA
+D30D;D30D;1111 1161 11A8;D30D;1111 1161 11A8; # (팍; 팍; 팍; 팍; 팍; ) HANGUL SYLLABLE PAG
+D30E;D30E;1111 1161 11A9;D30E;1111 1161 11A9; # (팎; 팎; 팎; 팎; 팎; ) HANGUL SYLLABLE PAGG
+D30F;D30F;1111 1161 11AA;D30F;1111 1161 11AA; # (팏; 팏; 팏; 팏; 팏; ) HANGUL SYLLABLE PAGS
+D310;D310;1111 1161 11AB;D310;1111 1161 11AB; # (판; 판; 판; 판; 판; ) HANGUL SYLLABLE PAN
+D311;D311;1111 1161 11AC;D311;1111 1161 11AC; # (팑; 팑; 팑; 팑; 팑; ) HANGUL SYLLABLE PANJ
+D312;D312;1111 1161 11AD;D312;1111 1161 11AD; # (팒; 팒; 팒; 팒; 팒; ) HANGUL SYLLABLE PANH
+D313;D313;1111 1161 11AE;D313;1111 1161 11AE; # (팓; 팓; 팓; 팓; 팓; ) HANGUL SYLLABLE PAD
+D314;D314;1111 1161 11AF;D314;1111 1161 11AF; # (팔; 팔; 팔; 팔; 팔; ) HANGUL SYLLABLE PAL
+D315;D315;1111 1161 11B0;D315;1111 1161 11B0; # (팕; 팕; 팕; 팕; 팕; ) HANGUL SYLLABLE PALG
+D316;D316;1111 1161 11B1;D316;1111 1161 11B1; # (팖; 팖; 팖; 팖; 팖; ) HANGUL SYLLABLE PALM
+D317;D317;1111 1161 11B2;D317;1111 1161 11B2; # (팗; 팗; 팗; 팗; 팗; ) HANGUL SYLLABLE PALB
+D318;D318;1111 1161 11B3;D318;1111 1161 11B3; # (팘; 팘; 팘; 팘; 팘; ) HANGUL SYLLABLE PALS
+D319;D319;1111 1161 11B4;D319;1111 1161 11B4; # (팙; 팙; 팙; 팙; 팙; ) HANGUL SYLLABLE PALT
+D31A;D31A;1111 1161 11B5;D31A;1111 1161 11B5; # (팚; 팚; 팚; 팚; 팚; ) HANGUL SYLLABLE PALP
+D31B;D31B;1111 1161 11B6;D31B;1111 1161 11B6; # (팛; 팛; 팛; 팛; 팛; ) HANGUL SYLLABLE PALH
+D31C;D31C;1111 1161 11B7;D31C;1111 1161 11B7; # (팜; 팜; 팜; 팜; 팜; ) HANGUL SYLLABLE PAM
+D31D;D31D;1111 1161 11B8;D31D;1111 1161 11B8; # (팝; 팝; 팝; 팝; 팝; ) HANGUL SYLLABLE PAB
+D31E;D31E;1111 1161 11B9;D31E;1111 1161 11B9; # (팞; 팞; 팞; 팞; 팞; ) HANGUL SYLLABLE PABS
+D31F;D31F;1111 1161 11BA;D31F;1111 1161 11BA; # (팟; 팟; 팟; 팟; 팟; ) HANGUL SYLLABLE PAS
+D320;D320;1111 1161 11BB;D320;1111 1161 11BB; # (팠; 팠; 팠; 팠; 팠; ) HANGUL SYLLABLE PASS
+D321;D321;1111 1161 11BC;D321;1111 1161 11BC; # (팡; 팡; 팡; 팡; 팡; ) HANGUL SYLLABLE PANG
+D322;D322;1111 1161 11BD;D322;1111 1161 11BD; # (팢; 팢; 팢; 팢; 팢; ) HANGUL SYLLABLE PAJ
+D323;D323;1111 1161 11BE;D323;1111 1161 11BE; # (팣; 팣; 팣; 팣; 팣; ) HANGUL SYLLABLE PAC
+D324;D324;1111 1161 11BF;D324;1111 1161 11BF; # (팤; 팤; 팤; 팤; 팤; ) HANGUL SYLLABLE PAK
+D325;D325;1111 1161 11C0;D325;1111 1161 11C0; # (팥; 팥; 팥; 팥; 팥; ) HANGUL SYLLABLE PAT
+D326;D326;1111 1161 11C1;D326;1111 1161 11C1; # (팦; 팦; 팦; 팦; 팦; ) HANGUL SYLLABLE PAP
+D327;D327;1111 1161 11C2;D327;1111 1161 11C2; # (팧; 팧; 팧; 팧; 팧; ) HANGUL SYLLABLE PAH
+D328;D328;1111 1162;D328;1111 1162; # (패; 패; 패; 패; 패; ) HANGUL SYLLABLE PAE
+D329;D329;1111 1162 11A8;D329;1111 1162 11A8; # (팩; 팩; 팩; 팩; 팩; ) HANGUL SYLLABLE PAEG
+D32A;D32A;1111 1162 11A9;D32A;1111 1162 11A9; # (팪; 팪; 팪; 팪; 팪; ) HANGUL SYLLABLE PAEGG
+D32B;D32B;1111 1162 11AA;D32B;1111 1162 11AA; # (팫; 팫; 팫; 팫; 팫; ) HANGUL SYLLABLE PAEGS
+D32C;D32C;1111 1162 11AB;D32C;1111 1162 11AB; # (팬; 팬; 팬; 팬; 팬; ) HANGUL SYLLABLE PAEN
+D32D;D32D;1111 1162 11AC;D32D;1111 1162 11AC; # (팭; 팭; 팭; 팭; 팭; ) HANGUL SYLLABLE PAENJ
+D32E;D32E;1111 1162 11AD;D32E;1111 1162 11AD; # (팮; 팮; 팮; 팮; 팮; ) HANGUL SYLLABLE PAENH
+D32F;D32F;1111 1162 11AE;D32F;1111 1162 11AE; # (팯; 팯; 팯; 팯; 팯; ) HANGUL SYLLABLE PAED
+D330;D330;1111 1162 11AF;D330;1111 1162 11AF; # (팰; 팰; 팰; 팰; 팰; ) HANGUL SYLLABLE PAEL
+D331;D331;1111 1162 11B0;D331;1111 1162 11B0; # (팱; 팱; 팱; 팱; 팱; ) HANGUL SYLLABLE PAELG
+D332;D332;1111 1162 11B1;D332;1111 1162 11B1; # (팲; 팲; 팲; 팲; 팲; ) HANGUL SYLLABLE PAELM
+D333;D333;1111 1162 11B2;D333;1111 1162 11B2; # (팳; 팳; 팳; 팳; 팳; ) HANGUL SYLLABLE PAELB
+D334;D334;1111 1162 11B3;D334;1111 1162 11B3; # (팴; 팴; 팴; 팴; 팴; ) HANGUL SYLLABLE PAELS
+D335;D335;1111 1162 11B4;D335;1111 1162 11B4; # (팵; 팵; 팵; 팵; 팵; ) HANGUL SYLLABLE PAELT
+D336;D336;1111 1162 11B5;D336;1111 1162 11B5; # (팶; 팶; 팶; 팶; 팶; ) HANGUL SYLLABLE PAELP
+D337;D337;1111 1162 11B6;D337;1111 1162 11B6; # (팷; 팷; 팷; 팷; 팷; ) HANGUL SYLLABLE PAELH
+D338;D338;1111 1162 11B7;D338;1111 1162 11B7; # (팸; 팸; 팸; 팸; 팸; ) HANGUL SYLLABLE PAEM
+D339;D339;1111 1162 11B8;D339;1111 1162 11B8; # (팹; 팹; 팹; 팹; 팹; ) HANGUL SYLLABLE PAEB
+D33A;D33A;1111 1162 11B9;D33A;1111 1162 11B9; # (팺; 팺; 팺; 팺; 팺; ) HANGUL SYLLABLE PAEBS
+D33B;D33B;1111 1162 11BA;D33B;1111 1162 11BA; # (팻; 팻; 팻; 팻; 팻; ) HANGUL SYLLABLE PAES
+D33C;D33C;1111 1162 11BB;D33C;1111 1162 11BB; # (팼; 팼; 팼; 팼; 팼; ) HANGUL SYLLABLE PAESS
+D33D;D33D;1111 1162 11BC;D33D;1111 1162 11BC; # (팽; 팽; 팽; 팽; 팽; ) HANGUL SYLLABLE PAENG
+D33E;D33E;1111 1162 11BD;D33E;1111 1162 11BD; # (팾; 팾; 팾; 팾; 팾; ) HANGUL SYLLABLE PAEJ
+D33F;D33F;1111 1162 11BE;D33F;1111 1162 11BE; # (팿; 팿; 팿; 팿; 팿; ) HANGUL SYLLABLE PAEC
+D340;D340;1111 1162 11BF;D340;1111 1162 11BF; # (퍀; 퍀; 퍀; 퍀; 퍀; ) HANGUL SYLLABLE PAEK
+D341;D341;1111 1162 11C0;D341;1111 1162 11C0; # (퍁; 퍁; 퍁; 퍁; 퍁; ) HANGUL SYLLABLE PAET
+D342;D342;1111 1162 11C1;D342;1111 1162 11C1; # (퍂; 퍂; 퍂; 퍂; 퍂; ) HANGUL SYLLABLE PAEP
+D343;D343;1111 1162 11C2;D343;1111 1162 11C2; # (퍃; 퍃; 퍃; 퍃; 퍃; ) HANGUL SYLLABLE PAEH
+D344;D344;1111 1163;D344;1111 1163; # (퍄; 퍄; 퍄; 퍄; 퍄; ) HANGUL SYLLABLE PYA
+D345;D345;1111 1163 11A8;D345;1111 1163 11A8; # (퍅; 퍅; 퍅; 퍅; 퍅; ) HANGUL SYLLABLE PYAG
+D346;D346;1111 1163 11A9;D346;1111 1163 11A9; # (퍆; 퍆; 퍆; 퍆; 퍆; ) HANGUL SYLLABLE PYAGG
+D347;D347;1111 1163 11AA;D347;1111 1163 11AA; # (퍇; 퍇; 퍇; 퍇; 퍇; ) HANGUL SYLLABLE PYAGS
+D348;D348;1111 1163 11AB;D348;1111 1163 11AB; # (퍈; 퍈; 퍈; 퍈; 퍈; ) HANGUL SYLLABLE PYAN
+D349;D349;1111 1163 11AC;D349;1111 1163 11AC; # (퍉; 퍉; 퍉; 퍉; 퍉; ) HANGUL SYLLABLE PYANJ
+D34A;D34A;1111 1163 11AD;D34A;1111 1163 11AD; # (퍊; 퍊; 퍊; 퍊; 퍊; ) HANGUL SYLLABLE PYANH
+D34B;D34B;1111 1163 11AE;D34B;1111 1163 11AE; # (퍋; 퍋; 퍋; 퍋; 퍋; ) HANGUL SYLLABLE PYAD
+D34C;D34C;1111 1163 11AF;D34C;1111 1163 11AF; # (퍌; 퍌; 퍌; 퍌; 퍌; ) HANGUL SYLLABLE PYAL
+D34D;D34D;1111 1163 11B0;D34D;1111 1163 11B0; # (퍍; 퍍; 퍍; 퍍; 퍍; ) HANGUL SYLLABLE PYALG
+D34E;D34E;1111 1163 11B1;D34E;1111 1163 11B1; # (퍎; 퍎; 퍎; 퍎; 퍎; ) HANGUL SYLLABLE PYALM
+D34F;D34F;1111 1163 11B2;D34F;1111 1163 11B2; # (퍏; 퍏; 퍏; 퍏; 퍏; ) HANGUL SYLLABLE PYALB
+D350;D350;1111 1163 11B3;D350;1111 1163 11B3; # (퍐; 퍐; 퍐; 퍐; 퍐; ) HANGUL SYLLABLE PYALS
+D351;D351;1111 1163 11B4;D351;1111 1163 11B4; # (퍑; 퍑; 퍑; 퍑; 퍑; ) HANGUL SYLLABLE PYALT
+D352;D352;1111 1163 11B5;D352;1111 1163 11B5; # (퍒; 퍒; 퍒; 퍒; 퍒; ) HANGUL SYLLABLE PYALP
+D353;D353;1111 1163 11B6;D353;1111 1163 11B6; # (퍓; 퍓; 퍓; 퍓; 퍓; ) HANGUL SYLLABLE PYALH
+D354;D354;1111 1163 11B7;D354;1111 1163 11B7; # (퍔; 퍔; 퍔; 퍔; 퍔; ) HANGUL SYLLABLE PYAM
+D355;D355;1111 1163 11B8;D355;1111 1163 11B8; # (퍕; 퍕; 퍕; 퍕; 퍕; ) HANGUL SYLLABLE PYAB
+D356;D356;1111 1163 11B9;D356;1111 1163 11B9; # (퍖; 퍖; 퍖; 퍖; 퍖; ) HANGUL SYLLABLE PYABS
+D357;D357;1111 1163 11BA;D357;1111 1163 11BA; # (퍗; 퍗; 퍗; 퍗; 퍗; ) HANGUL SYLLABLE PYAS
+D358;D358;1111 1163 11BB;D358;1111 1163 11BB; # (퍘; 퍘; 퍘; 퍘; 퍘; ) HANGUL SYLLABLE PYASS
+D359;D359;1111 1163 11BC;D359;1111 1163 11BC; # (퍙; 퍙; 퍙; 퍙; 퍙; ) HANGUL SYLLABLE PYANG
+D35A;D35A;1111 1163 11BD;D35A;1111 1163 11BD; # (퍚; 퍚; 퍚; 퍚; 퍚; ) HANGUL SYLLABLE PYAJ
+D35B;D35B;1111 1163 11BE;D35B;1111 1163 11BE; # (퍛; 퍛; 퍛; 퍛; 퍛; ) HANGUL SYLLABLE PYAC
+D35C;D35C;1111 1163 11BF;D35C;1111 1163 11BF; # (퍜; 퍜; 퍜; 퍜; 퍜; ) HANGUL SYLLABLE PYAK
+D35D;D35D;1111 1163 11C0;D35D;1111 1163 11C0; # (퍝; 퍝; 퍝; 퍝; 퍝; ) HANGUL SYLLABLE PYAT
+D35E;D35E;1111 1163 11C1;D35E;1111 1163 11C1; # (퍞; 퍞; 퍞; 퍞; 퍞; ) HANGUL SYLLABLE PYAP
+D35F;D35F;1111 1163 11C2;D35F;1111 1163 11C2; # (퍟; 퍟; 퍟; 퍟; 퍟; ) HANGUL SYLLABLE PYAH
+D360;D360;1111 1164;D360;1111 1164; # (퍠; 퍠; 퍠; 퍠; 퍠; ) HANGUL SYLLABLE PYAE
+D361;D361;1111 1164 11A8;D361;1111 1164 11A8; # (퍡; 퍡; 퍡; 퍡; 퍡; ) HANGUL SYLLABLE PYAEG
+D362;D362;1111 1164 11A9;D362;1111 1164 11A9; # (퍢; 퍢; 퍢; 퍢; 퍢; ) HANGUL SYLLABLE PYAEGG
+D363;D363;1111 1164 11AA;D363;1111 1164 11AA; # (퍣; 퍣; 퍣; 퍣; 퍣; ) HANGUL SYLLABLE PYAEGS
+D364;D364;1111 1164 11AB;D364;1111 1164 11AB; # (퍤; 퍤; 퍤; 퍤; 퍤; ) HANGUL SYLLABLE PYAEN
+D365;D365;1111 1164 11AC;D365;1111 1164 11AC; # (퍥; 퍥; 퍥; 퍥; 퍥; ) HANGUL SYLLABLE PYAENJ
+D366;D366;1111 1164 11AD;D366;1111 1164 11AD; # (퍦; 퍦; 퍦; 퍦; 퍦; ) HANGUL SYLLABLE PYAENH
+D367;D367;1111 1164 11AE;D367;1111 1164 11AE; # (퍧; 퍧; 퍧; 퍧; 퍧; ) HANGUL SYLLABLE PYAED
+D368;D368;1111 1164 11AF;D368;1111 1164 11AF; # (퍨; 퍨; 퍨; 퍨; 퍨; ) HANGUL SYLLABLE PYAEL
+D369;D369;1111 1164 11B0;D369;1111 1164 11B0; # (퍩; 퍩; 퍩; 퍩; 퍩; ) HANGUL SYLLABLE PYAELG
+D36A;D36A;1111 1164 11B1;D36A;1111 1164 11B1; # (퍪; 퍪; 퍪; 퍪; 퍪; ) HANGUL SYLLABLE PYAELM
+D36B;D36B;1111 1164 11B2;D36B;1111 1164 11B2; # (퍫; 퍫; 퍫; 퍫; 퍫; ) HANGUL SYLLABLE PYAELB
+D36C;D36C;1111 1164 11B3;D36C;1111 1164 11B3; # (퍬; 퍬; 퍬; 퍬; 퍬; ) HANGUL SYLLABLE PYAELS
+D36D;D36D;1111 1164 11B4;D36D;1111 1164 11B4; # (퍭; 퍭; 퍭; 퍭; 퍭; ) HANGUL SYLLABLE PYAELT
+D36E;D36E;1111 1164 11B5;D36E;1111 1164 11B5; # (퍮; 퍮; 퍮; 퍮; 퍮; ) HANGUL SYLLABLE PYAELP
+D36F;D36F;1111 1164 11B6;D36F;1111 1164 11B6; # (퍯; 퍯; 퍯; 퍯; 퍯; ) HANGUL SYLLABLE PYAELH
+D370;D370;1111 1164 11B7;D370;1111 1164 11B7; # (퍰; 퍰; 퍰; 퍰; 퍰; ) HANGUL SYLLABLE PYAEM
+D371;D371;1111 1164 11B8;D371;1111 1164 11B8; # (퍱; 퍱; 퍱; 퍱; 퍱; ) HANGUL SYLLABLE PYAEB
+D372;D372;1111 1164 11B9;D372;1111 1164 11B9; # (퍲; 퍲; 퍲; 퍲; 퍲; ) HANGUL SYLLABLE PYAEBS
+D373;D373;1111 1164 11BA;D373;1111 1164 11BA; # (퍳; 퍳; 퍳; 퍳; 퍳; ) HANGUL SYLLABLE PYAES
+D374;D374;1111 1164 11BB;D374;1111 1164 11BB; # (퍴; 퍴; 퍴; 퍴; 퍴; ) HANGUL SYLLABLE PYAESS
+D375;D375;1111 1164 11BC;D375;1111 1164 11BC; # (퍵; 퍵; 퍵; 퍵; 퍵; ) HANGUL SYLLABLE PYAENG
+D376;D376;1111 1164 11BD;D376;1111 1164 11BD; # (퍶; 퍶; 퍶; 퍶; 퍶; ) HANGUL SYLLABLE PYAEJ
+D377;D377;1111 1164 11BE;D377;1111 1164 11BE; # (퍷; 퍷; 퍷; 퍷; 퍷; ) HANGUL SYLLABLE PYAEC
+D378;D378;1111 1164 11BF;D378;1111 1164 11BF; # (퍸; 퍸; 퍸; 퍸; 퍸; ) HANGUL SYLLABLE PYAEK
+D379;D379;1111 1164 11C0;D379;1111 1164 11C0; # (퍹; 퍹; 퍹; 퍹; 퍹; ) HANGUL SYLLABLE PYAET
+D37A;D37A;1111 1164 11C1;D37A;1111 1164 11C1; # (퍺; 퍺; 퍺; 퍺; 퍺; ) HANGUL SYLLABLE PYAEP
+D37B;D37B;1111 1164 11C2;D37B;1111 1164 11C2; # (퍻; 퍻; 퍻; 퍻; 퍻; ) HANGUL SYLLABLE PYAEH
+D37C;D37C;1111 1165;D37C;1111 1165; # (퍼; 퍼; 퍼; 퍼; 퍼; ) HANGUL SYLLABLE PEO
+D37D;D37D;1111 1165 11A8;D37D;1111 1165 11A8; # (퍽; 퍽; 퍽; 퍽; 퍽; ) HANGUL SYLLABLE PEOG
+D37E;D37E;1111 1165 11A9;D37E;1111 1165 11A9; # (퍾; 퍾; 퍾; 퍾; 퍾; ) HANGUL SYLLABLE PEOGG
+D37F;D37F;1111 1165 11AA;D37F;1111 1165 11AA; # (퍿; 퍿; 퍿; 퍿; 퍿; ) HANGUL SYLLABLE PEOGS
+D380;D380;1111 1165 11AB;D380;1111 1165 11AB; # (펀; 펀; 펀; 펀; 펀; ) HANGUL SYLLABLE PEON
+D381;D381;1111 1165 11AC;D381;1111 1165 11AC; # (펁; 펁; 펁; 펁; 펁; ) HANGUL SYLLABLE PEONJ
+D382;D382;1111 1165 11AD;D382;1111 1165 11AD; # (펂; 펂; 펂; 펂; 펂; ) HANGUL SYLLABLE PEONH
+D383;D383;1111 1165 11AE;D383;1111 1165 11AE; # (펃; 펃; 펃; 펃; 펃; ) HANGUL SYLLABLE PEOD
+D384;D384;1111 1165 11AF;D384;1111 1165 11AF; # (펄; 펄; 펄; 펄; 펄; ) HANGUL SYLLABLE PEOL
+D385;D385;1111 1165 11B0;D385;1111 1165 11B0; # (펅; 펅; 펅; 펅; 펅; ) HANGUL SYLLABLE PEOLG
+D386;D386;1111 1165 11B1;D386;1111 1165 11B1; # (펆; 펆; 펆; 펆; 펆; ) HANGUL SYLLABLE PEOLM
+D387;D387;1111 1165 11B2;D387;1111 1165 11B2; # (펇; 펇; 펇; 펇; 펇; ) HANGUL SYLLABLE PEOLB
+D388;D388;1111 1165 11B3;D388;1111 1165 11B3; # (펈; 펈; 펈; 펈; 펈; ) HANGUL SYLLABLE PEOLS
+D389;D389;1111 1165 11B4;D389;1111 1165 11B4; # (펉; 펉; 펉; 펉; 펉; ) HANGUL SYLLABLE PEOLT
+D38A;D38A;1111 1165 11B5;D38A;1111 1165 11B5; # (펊; 펊; 펊; 펊; 펊; ) HANGUL SYLLABLE PEOLP
+D38B;D38B;1111 1165 11B6;D38B;1111 1165 11B6; # (펋; 펋; 펋; 펋; 펋; ) HANGUL SYLLABLE PEOLH
+D38C;D38C;1111 1165 11B7;D38C;1111 1165 11B7; # (펌; 펌; 펌; 펌; 펌; ) HANGUL SYLLABLE PEOM
+D38D;D38D;1111 1165 11B8;D38D;1111 1165 11B8; # (펍; 펍; 펍; 펍; 펍; ) HANGUL SYLLABLE PEOB
+D38E;D38E;1111 1165 11B9;D38E;1111 1165 11B9; # (펎; 펎; 펎; 펎; 펎; ) HANGUL SYLLABLE PEOBS
+D38F;D38F;1111 1165 11BA;D38F;1111 1165 11BA; # (펏; 펏; 펏; 펏; 펏; ) HANGUL SYLLABLE PEOS
+D390;D390;1111 1165 11BB;D390;1111 1165 11BB; # (펐; 펐; 펐; 펐; 펐; ) HANGUL SYLLABLE PEOSS
+D391;D391;1111 1165 11BC;D391;1111 1165 11BC; # (펑; 펑; 펑; 펑; 펑; ) HANGUL SYLLABLE PEONG
+D392;D392;1111 1165 11BD;D392;1111 1165 11BD; # (펒; 펒; 펒; 펒; 펒; ) HANGUL SYLLABLE PEOJ
+D393;D393;1111 1165 11BE;D393;1111 1165 11BE; # (펓; 펓; 펓; 펓; 펓; ) HANGUL SYLLABLE PEOC
+D394;D394;1111 1165 11BF;D394;1111 1165 11BF; # (펔; 펔; 펔; 펔; 펔; ) HANGUL SYLLABLE PEOK
+D395;D395;1111 1165 11C0;D395;1111 1165 11C0; # (펕; 펕; 펕; 펕; 펕; ) HANGUL SYLLABLE PEOT
+D396;D396;1111 1165 11C1;D396;1111 1165 11C1; # (펖; 펖; 펖; 펖; 펖; ) HANGUL SYLLABLE PEOP
+D397;D397;1111 1165 11C2;D397;1111 1165 11C2; # (펗; 펗; 펗; 펗; 펗; ) HANGUL SYLLABLE PEOH
+D398;D398;1111 1166;D398;1111 1166; # (페; 페; 페; 페; 페; ) HANGUL SYLLABLE PE
+D399;D399;1111 1166 11A8;D399;1111 1166 11A8; # (펙; 펙; 펙; 펙; 펙; ) HANGUL SYLLABLE PEG
+D39A;D39A;1111 1166 11A9;D39A;1111 1166 11A9; # (펚; 펚; 펚; 펚; 펚; ) HANGUL SYLLABLE PEGG
+D39B;D39B;1111 1166 11AA;D39B;1111 1166 11AA; # (펛; 펛; 펛; 펛; 펛; ) HANGUL SYLLABLE PEGS
+D39C;D39C;1111 1166 11AB;D39C;1111 1166 11AB; # (펜; 펜; 펜; 펜; 펜; ) HANGUL SYLLABLE PEN
+D39D;D39D;1111 1166 11AC;D39D;1111 1166 11AC; # (펝; 펝; 펝; 펝; 펝; ) HANGUL SYLLABLE PENJ
+D39E;D39E;1111 1166 11AD;D39E;1111 1166 11AD; # (펞; 펞; 펞; 펞; 펞; ) HANGUL SYLLABLE PENH
+D39F;D39F;1111 1166 11AE;D39F;1111 1166 11AE; # (펟; 펟; 펟; 펟; 펟; ) HANGUL SYLLABLE PED
+D3A0;D3A0;1111 1166 11AF;D3A0;1111 1166 11AF; # (펠; 펠; 펠; 펠; 펠; ) HANGUL SYLLABLE PEL
+D3A1;D3A1;1111 1166 11B0;D3A1;1111 1166 11B0; # (펡; 펡; 펡; 펡; 펡; ) HANGUL SYLLABLE PELG
+D3A2;D3A2;1111 1166 11B1;D3A2;1111 1166 11B1; # (펢; 펢; 펢; 펢; 펢; ) HANGUL SYLLABLE PELM
+D3A3;D3A3;1111 1166 11B2;D3A3;1111 1166 11B2; # (펣; 펣; 펣; 펣; 펣; ) HANGUL SYLLABLE PELB
+D3A4;D3A4;1111 1166 11B3;D3A4;1111 1166 11B3; # (펤; 펤; 펤; 펤; 펤; ) HANGUL SYLLABLE PELS
+D3A5;D3A5;1111 1166 11B4;D3A5;1111 1166 11B4; # (펥; 펥; 펥; 펥; 펥; ) HANGUL SYLLABLE PELT
+D3A6;D3A6;1111 1166 11B5;D3A6;1111 1166 11B5; # (펦; 펦; 펦; 펦; 펦; ) HANGUL SYLLABLE PELP
+D3A7;D3A7;1111 1166 11B6;D3A7;1111 1166 11B6; # (펧; 펧; 펧; 펧; 펧; ) HANGUL SYLLABLE PELH
+D3A8;D3A8;1111 1166 11B7;D3A8;1111 1166 11B7; # (펨; 펨; 펨; 펨; 펨; ) HANGUL SYLLABLE PEM
+D3A9;D3A9;1111 1166 11B8;D3A9;1111 1166 11B8; # (펩; 펩; 펩; 펩; 펩; ) HANGUL SYLLABLE PEB
+D3AA;D3AA;1111 1166 11B9;D3AA;1111 1166 11B9; # (펪; 펪; 펪; 펪; 펪; ) HANGUL SYLLABLE PEBS
+D3AB;D3AB;1111 1166 11BA;D3AB;1111 1166 11BA; # (펫; 펫; 펫; 펫; 펫; ) HANGUL SYLLABLE PES
+D3AC;D3AC;1111 1166 11BB;D3AC;1111 1166 11BB; # (펬; 펬; 펬; 펬; 펬; ) HANGUL SYLLABLE PESS
+D3AD;D3AD;1111 1166 11BC;D3AD;1111 1166 11BC; # (펭; 펭; 펭; 펭; 펭; ) HANGUL SYLLABLE PENG
+D3AE;D3AE;1111 1166 11BD;D3AE;1111 1166 11BD; # (펮; 펮; 펮; 펮; 펮; ) HANGUL SYLLABLE PEJ
+D3AF;D3AF;1111 1166 11BE;D3AF;1111 1166 11BE; # (펯; 펯; 펯; 펯; 펯; ) HANGUL SYLLABLE PEC
+D3B0;D3B0;1111 1166 11BF;D3B0;1111 1166 11BF; # (펰; 펰; 펰; 펰; 펰; ) HANGUL SYLLABLE PEK
+D3B1;D3B1;1111 1166 11C0;D3B1;1111 1166 11C0; # (펱; 펱; 펱; 펱; 펱; ) HANGUL SYLLABLE PET
+D3B2;D3B2;1111 1166 11C1;D3B2;1111 1166 11C1; # (펲; 펲; 펲; 펲; 펲; ) HANGUL SYLLABLE PEP
+D3B3;D3B3;1111 1166 11C2;D3B3;1111 1166 11C2; # (펳; 펳; 펳; 펳; 펳; ) HANGUL SYLLABLE PEH
+D3B4;D3B4;1111 1167;D3B4;1111 1167; # (펴; 펴; 펴; 펴; 펴; ) HANGUL SYLLABLE PYEO
+D3B5;D3B5;1111 1167 11A8;D3B5;1111 1167 11A8; # (펵; 펵; 펵; 펵; 펵; ) HANGUL SYLLABLE PYEOG
+D3B6;D3B6;1111 1167 11A9;D3B6;1111 1167 11A9; # (펶; 펶; 펶; 펶; 펶; ) HANGUL SYLLABLE PYEOGG
+D3B7;D3B7;1111 1167 11AA;D3B7;1111 1167 11AA; # (펷; 펷; 펷; 펷; 펷; ) HANGUL SYLLABLE PYEOGS
+D3B8;D3B8;1111 1167 11AB;D3B8;1111 1167 11AB; # (편; 편; 편; 편; 편; ) HANGUL SYLLABLE PYEON
+D3B9;D3B9;1111 1167 11AC;D3B9;1111 1167 11AC; # (펹; 펹; 펹; 펹; 펹; ) HANGUL SYLLABLE PYEONJ
+D3BA;D3BA;1111 1167 11AD;D3BA;1111 1167 11AD; # (펺; 펺; 펺; 펺; 펺; ) HANGUL SYLLABLE PYEONH
+D3BB;D3BB;1111 1167 11AE;D3BB;1111 1167 11AE; # (펻; 펻; 펻; 펻; 펻; ) HANGUL SYLLABLE PYEOD
+D3BC;D3BC;1111 1167 11AF;D3BC;1111 1167 11AF; # (펼; 펼; 펼; 펼; 펼; ) HANGUL SYLLABLE PYEOL
+D3BD;D3BD;1111 1167 11B0;D3BD;1111 1167 11B0; # (펽; 펽; 펽; 펽; 펽; ) HANGUL SYLLABLE PYEOLG
+D3BE;D3BE;1111 1167 11B1;D3BE;1111 1167 11B1; # (펾; 펾; 펾; 펾; 펾; ) HANGUL SYLLABLE PYEOLM
+D3BF;D3BF;1111 1167 11B2;D3BF;1111 1167 11B2; # (펿; 펿; 펿; 펿; 펿; ) HANGUL SYLLABLE PYEOLB
+D3C0;D3C0;1111 1167 11B3;D3C0;1111 1167 11B3; # (폀; 폀; 폀; 폀; 폀; ) HANGUL SYLLABLE PYEOLS
+D3C1;D3C1;1111 1167 11B4;D3C1;1111 1167 11B4; # (폁; 폁; 폁; 폁; 폁; ) HANGUL SYLLABLE PYEOLT
+D3C2;D3C2;1111 1167 11B5;D3C2;1111 1167 11B5; # (폂; 폂; 폂; 폂; 폂; ) HANGUL SYLLABLE PYEOLP
+D3C3;D3C3;1111 1167 11B6;D3C3;1111 1167 11B6; # (폃; 폃; 폃; 폃; 폃; ) HANGUL SYLLABLE PYEOLH
+D3C4;D3C4;1111 1167 11B7;D3C4;1111 1167 11B7; # (폄; 폄; 폄; 폄; 폄; ) HANGUL SYLLABLE PYEOM
+D3C5;D3C5;1111 1167 11B8;D3C5;1111 1167 11B8; # (폅; 폅; 폅; 폅; 폅; ) HANGUL SYLLABLE PYEOB
+D3C6;D3C6;1111 1167 11B9;D3C6;1111 1167 11B9; # (폆; 폆; 폆; 폆; 폆; ) HANGUL SYLLABLE PYEOBS
+D3C7;D3C7;1111 1167 11BA;D3C7;1111 1167 11BA; # (폇; 폇; 폇; 폇; 폇; ) HANGUL SYLLABLE PYEOS
+D3C8;D3C8;1111 1167 11BB;D3C8;1111 1167 11BB; # (폈; 폈; 폈; 폈; 폈; ) HANGUL SYLLABLE PYEOSS
+D3C9;D3C9;1111 1167 11BC;D3C9;1111 1167 11BC; # (평; 평; 평; 평; 평; ) HANGUL SYLLABLE PYEONG
+D3CA;D3CA;1111 1167 11BD;D3CA;1111 1167 11BD; # (폊; 폊; 폊; 폊; 폊; ) HANGUL SYLLABLE PYEOJ
+D3CB;D3CB;1111 1167 11BE;D3CB;1111 1167 11BE; # (폋; 폋; 폋; 폋; 폋; ) HANGUL SYLLABLE PYEOC
+D3CC;D3CC;1111 1167 11BF;D3CC;1111 1167 11BF; # (폌; 폌; 폌; 폌; 폌; ) HANGUL SYLLABLE PYEOK
+D3CD;D3CD;1111 1167 11C0;D3CD;1111 1167 11C0; # (폍; 폍; 폍; 폍; 폍; ) HANGUL SYLLABLE PYEOT
+D3CE;D3CE;1111 1167 11C1;D3CE;1111 1167 11C1; # (폎; 폎; 폎; 폎; 폎; ) HANGUL SYLLABLE PYEOP
+D3CF;D3CF;1111 1167 11C2;D3CF;1111 1167 11C2; # (폏; 폏; 폏; 폏; 폏; ) HANGUL SYLLABLE PYEOH
+D3D0;D3D0;1111 1168;D3D0;1111 1168; # (폐; 폐; 폐; 폐; 폐; ) HANGUL SYLLABLE PYE
+D3D1;D3D1;1111 1168 11A8;D3D1;1111 1168 11A8; # (폑; 폑; 폑; 폑; 폑; ) HANGUL SYLLABLE PYEG
+D3D2;D3D2;1111 1168 11A9;D3D2;1111 1168 11A9; # (폒; 폒; 폒; 폒; 폒; ) HANGUL SYLLABLE PYEGG
+D3D3;D3D3;1111 1168 11AA;D3D3;1111 1168 11AA; # (폓; 폓; 폓; 폓; 폓; ) HANGUL SYLLABLE PYEGS
+D3D4;D3D4;1111 1168 11AB;D3D4;1111 1168 11AB; # (폔; 폔; 폔; 폔; 폔; ) HANGUL SYLLABLE PYEN
+D3D5;D3D5;1111 1168 11AC;D3D5;1111 1168 11AC; # (폕; 폕; 폕; 폕; 폕; ) HANGUL SYLLABLE PYENJ
+D3D6;D3D6;1111 1168 11AD;D3D6;1111 1168 11AD; # (폖; 폖; 폖; 폖; 폖; ) HANGUL SYLLABLE PYENH
+D3D7;D3D7;1111 1168 11AE;D3D7;1111 1168 11AE; # (폗; 폗; 폗; 폗; 폗; ) HANGUL SYLLABLE PYED
+D3D8;D3D8;1111 1168 11AF;D3D8;1111 1168 11AF; # (폘; 폘; 폘; 폘; 폘; ) HANGUL SYLLABLE PYEL
+D3D9;D3D9;1111 1168 11B0;D3D9;1111 1168 11B0; # (폙; 폙; 폙; 폙; 폙; ) HANGUL SYLLABLE PYELG
+D3DA;D3DA;1111 1168 11B1;D3DA;1111 1168 11B1; # (폚; 폚; 폚; 폚; 폚; ) HANGUL SYLLABLE PYELM
+D3DB;D3DB;1111 1168 11B2;D3DB;1111 1168 11B2; # (폛; 폛; 폛; 폛; 폛; ) HANGUL SYLLABLE PYELB
+D3DC;D3DC;1111 1168 11B3;D3DC;1111 1168 11B3; # (폜; 폜; 폜; 폜; 폜; ) HANGUL SYLLABLE PYELS
+D3DD;D3DD;1111 1168 11B4;D3DD;1111 1168 11B4; # (폝; 폝; 폝; 폝; 폝; ) HANGUL SYLLABLE PYELT
+D3DE;D3DE;1111 1168 11B5;D3DE;1111 1168 11B5; # (폞; 폞; 폞; 폞; 폞; ) HANGUL SYLLABLE PYELP
+D3DF;D3DF;1111 1168 11B6;D3DF;1111 1168 11B6; # (폟; 폟; 폟; 폟; 폟; ) HANGUL SYLLABLE PYELH
+D3E0;D3E0;1111 1168 11B7;D3E0;1111 1168 11B7; # (폠; 폠; 폠; 폠; 폠; ) HANGUL SYLLABLE PYEM
+D3E1;D3E1;1111 1168 11B8;D3E1;1111 1168 11B8; # (폡; 폡; 폡; 폡; 폡; ) HANGUL SYLLABLE PYEB
+D3E2;D3E2;1111 1168 11B9;D3E2;1111 1168 11B9; # (폢; 폢; 폢; 폢; 폢; ) HANGUL SYLLABLE PYEBS
+D3E3;D3E3;1111 1168 11BA;D3E3;1111 1168 11BA; # (폣; 폣; 폣; 폣; 폣; ) HANGUL SYLLABLE PYES
+D3E4;D3E4;1111 1168 11BB;D3E4;1111 1168 11BB; # (폤; 폤; 폤; 폤; 폤; ) HANGUL SYLLABLE PYESS
+D3E5;D3E5;1111 1168 11BC;D3E5;1111 1168 11BC; # (폥; 폥; 폥; 폥; 폥; ) HANGUL SYLLABLE PYENG
+D3E6;D3E6;1111 1168 11BD;D3E6;1111 1168 11BD; # (폦; 폦; 폦; 폦; 폦; ) HANGUL SYLLABLE PYEJ
+D3E7;D3E7;1111 1168 11BE;D3E7;1111 1168 11BE; # (폧; 폧; 폧; 폧; 폧; ) HANGUL SYLLABLE PYEC
+D3E8;D3E8;1111 1168 11BF;D3E8;1111 1168 11BF; # (폨; 폨; 폨; 폨; 폨; ) HANGUL SYLLABLE PYEK
+D3E9;D3E9;1111 1168 11C0;D3E9;1111 1168 11C0; # (폩; 폩; 폩; 폩; 폩; ) HANGUL SYLLABLE PYET
+D3EA;D3EA;1111 1168 11C1;D3EA;1111 1168 11C1; # (폪; 폪; 폪; 폪; 폪; ) HANGUL SYLLABLE PYEP
+D3EB;D3EB;1111 1168 11C2;D3EB;1111 1168 11C2; # (폫; 폫; 폫; 폫; 폫; ) HANGUL SYLLABLE PYEH
+D3EC;D3EC;1111 1169;D3EC;1111 1169; # (포; 포; 포; 포; 포; ) HANGUL SYLLABLE PO
+D3ED;D3ED;1111 1169 11A8;D3ED;1111 1169 11A8; # (폭; 폭; 폭; 폭; 폭; ) HANGUL SYLLABLE POG
+D3EE;D3EE;1111 1169 11A9;D3EE;1111 1169 11A9; # (폮; 폮; 폮; 폮; 폮; ) HANGUL SYLLABLE POGG
+D3EF;D3EF;1111 1169 11AA;D3EF;1111 1169 11AA; # (폯; 폯; 폯; 폯; 폯; ) HANGUL SYLLABLE POGS
+D3F0;D3F0;1111 1169 11AB;D3F0;1111 1169 11AB; # (폰; 폰; 폰; 폰; 폰; ) HANGUL SYLLABLE PON
+D3F1;D3F1;1111 1169 11AC;D3F1;1111 1169 11AC; # (폱; 폱; 폱; 폱; 폱; ) HANGUL SYLLABLE PONJ
+D3F2;D3F2;1111 1169 11AD;D3F2;1111 1169 11AD; # (폲; 폲; 폲; 폲; 폲; ) HANGUL SYLLABLE PONH
+D3F3;D3F3;1111 1169 11AE;D3F3;1111 1169 11AE; # (폳; 폳; 폳; 폳; 폳; ) HANGUL SYLLABLE POD
+D3F4;D3F4;1111 1169 11AF;D3F4;1111 1169 11AF; # (폴; 폴; 폴; 폴; 폴; ) HANGUL SYLLABLE POL
+D3F5;D3F5;1111 1169 11B0;D3F5;1111 1169 11B0; # (폵; 폵; 폵; 폵; 폵; ) HANGUL SYLLABLE POLG
+D3F6;D3F6;1111 1169 11B1;D3F6;1111 1169 11B1; # (폶; 폶; 폶; 폶; 폶; ) HANGUL SYLLABLE POLM
+D3F7;D3F7;1111 1169 11B2;D3F7;1111 1169 11B2; # (폷; 폷; 폷; 폷; 폷; ) HANGUL SYLLABLE POLB
+D3F8;D3F8;1111 1169 11B3;D3F8;1111 1169 11B3; # (폸; 폸; 폸; 폸; 폸; ) HANGUL SYLLABLE POLS
+D3F9;D3F9;1111 1169 11B4;D3F9;1111 1169 11B4; # (폹; 폹; 폹; 폹; 폹; ) HANGUL SYLLABLE POLT
+D3FA;D3FA;1111 1169 11B5;D3FA;1111 1169 11B5; # (폺; 폺; 폺; 폺; 폺; ) HANGUL SYLLABLE POLP
+D3FB;D3FB;1111 1169 11B6;D3FB;1111 1169 11B6; # (폻; 폻; 폻; 폻; 폻; ) HANGUL SYLLABLE POLH
+D3FC;D3FC;1111 1169 11B7;D3FC;1111 1169 11B7; # (폼; 폼; 폼; 폼; 폼; ) HANGUL SYLLABLE POM
+D3FD;D3FD;1111 1169 11B8;D3FD;1111 1169 11B8; # (폽; 폽; 폽; 폽; 폽; ) HANGUL SYLLABLE POB
+D3FE;D3FE;1111 1169 11B9;D3FE;1111 1169 11B9; # (폾; 폾; 폾; 폾; 폾; ) HANGUL SYLLABLE POBS
+D3FF;D3FF;1111 1169 11BA;D3FF;1111 1169 11BA; # (폿; 폿; 폿; 폿; 폿; ) HANGUL SYLLABLE POS
+D400;D400;1111 1169 11BB;D400;1111 1169 11BB; # (퐀; 퐀; 퐀; 퐀; 퐀; ) HANGUL SYLLABLE POSS
+D401;D401;1111 1169 11BC;D401;1111 1169 11BC; # (퐁; 퐁; 퐁; 퐁; 퐁; ) HANGUL SYLLABLE PONG
+D402;D402;1111 1169 11BD;D402;1111 1169 11BD; # (퐂; 퐂; 퐂; 퐂; 퐂; ) HANGUL SYLLABLE POJ
+D403;D403;1111 1169 11BE;D403;1111 1169 11BE; # (퐃; 퐃; 퐃; 퐃; 퐃; ) HANGUL SYLLABLE POC
+D404;D404;1111 1169 11BF;D404;1111 1169 11BF; # (퐄; 퐄; 퐄; 퐄; 퐄; ) HANGUL SYLLABLE POK
+D405;D405;1111 1169 11C0;D405;1111 1169 11C0; # (퐅; 퐅; 퐅; 퐅; 퐅; ) HANGUL SYLLABLE POT
+D406;D406;1111 1169 11C1;D406;1111 1169 11C1; # (퐆; 퐆; 퐆; 퐆; 퐆; ) HANGUL SYLLABLE POP
+D407;D407;1111 1169 11C2;D407;1111 1169 11C2; # (퐇; 퐇; 퐇; 퐇; 퐇; ) HANGUL SYLLABLE POH
+D408;D408;1111 116A;D408;1111 116A; # (퐈; 퐈; 퐈; 퐈; 퐈; ) HANGUL SYLLABLE PWA
+D409;D409;1111 116A 11A8;D409;1111 116A 11A8; # (퐉; 퐉; 퐉; 퐉; 퐉; ) HANGUL SYLLABLE PWAG
+D40A;D40A;1111 116A 11A9;D40A;1111 116A 11A9; # (퐊; 퐊; 퐊; 퐊; 퐊; ) HANGUL SYLLABLE PWAGG
+D40B;D40B;1111 116A 11AA;D40B;1111 116A 11AA; # (퐋; 퐋; 퐋; 퐋; 퐋; ) HANGUL SYLLABLE PWAGS
+D40C;D40C;1111 116A 11AB;D40C;1111 116A 11AB; # (퐌; 퐌; 퐌; 퐌; 퐌; ) HANGUL SYLLABLE PWAN
+D40D;D40D;1111 116A 11AC;D40D;1111 116A 11AC; # (퐍; 퐍; 퐍; 퐍; 퐍; ) HANGUL SYLLABLE PWANJ
+D40E;D40E;1111 116A 11AD;D40E;1111 116A 11AD; # (퐎; 퐎; 퐎; 퐎; 퐎; ) HANGUL SYLLABLE PWANH
+D40F;D40F;1111 116A 11AE;D40F;1111 116A 11AE; # (퐏; 퐏; 퐏; 퐏; 퐏; ) HANGUL SYLLABLE PWAD
+D410;D410;1111 116A 11AF;D410;1111 116A 11AF; # (퐐; 퐐; 퐐; 퐐; 퐐; ) HANGUL SYLLABLE PWAL
+D411;D411;1111 116A 11B0;D411;1111 116A 11B0; # (퐑; 퐑; 퐑; 퐑; 퐑; ) HANGUL SYLLABLE PWALG
+D412;D412;1111 116A 11B1;D412;1111 116A 11B1; # (퐒; 퐒; 퐒; 퐒; 퐒; ) HANGUL SYLLABLE PWALM
+D413;D413;1111 116A 11B2;D413;1111 116A 11B2; # (퐓; 퐓; 퐓; 퐓; 퐓; ) HANGUL SYLLABLE PWALB
+D414;D414;1111 116A 11B3;D414;1111 116A 11B3; # (퐔; 퐔; 퐔; 퐔; 퐔; ) HANGUL SYLLABLE PWALS
+D415;D415;1111 116A 11B4;D415;1111 116A 11B4; # (퐕; 퐕; 퐕; 퐕; 퐕; ) HANGUL SYLLABLE PWALT
+D416;D416;1111 116A 11B5;D416;1111 116A 11B5; # (퐖; 퐖; 퐖; 퐖; 퐖; ) HANGUL SYLLABLE PWALP
+D417;D417;1111 116A 11B6;D417;1111 116A 11B6; # (퐗; 퐗; 퐗; 퐗; 퐗; ) HANGUL SYLLABLE PWALH
+D418;D418;1111 116A 11B7;D418;1111 116A 11B7; # (퐘; 퐘; 퐘; 퐘; 퐘; ) HANGUL SYLLABLE PWAM
+D419;D419;1111 116A 11B8;D419;1111 116A 11B8; # (퐙; 퐙; 퐙; 퐙; 퐙; ) HANGUL SYLLABLE PWAB
+D41A;D41A;1111 116A 11B9;D41A;1111 116A 11B9; # (퐚; 퐚; 퐚; 퐚; 퐚; ) HANGUL SYLLABLE PWABS
+D41B;D41B;1111 116A 11BA;D41B;1111 116A 11BA; # (퐛; 퐛; 퐛; 퐛; 퐛; ) HANGUL SYLLABLE PWAS
+D41C;D41C;1111 116A 11BB;D41C;1111 116A 11BB; # (퐜; 퐜; 퐜; 퐜; 퐜; ) HANGUL SYLLABLE PWASS
+D41D;D41D;1111 116A 11BC;D41D;1111 116A 11BC; # (퐝; 퐝; 퐝; 퐝; 퐝; ) HANGUL SYLLABLE PWANG
+D41E;D41E;1111 116A 11BD;D41E;1111 116A 11BD; # (퐞; 퐞; 퐞; 퐞; 퐞; ) HANGUL SYLLABLE PWAJ
+D41F;D41F;1111 116A 11BE;D41F;1111 116A 11BE; # (퐟; 퐟; 퐟; 퐟; 퐟; ) HANGUL SYLLABLE PWAC
+D420;D420;1111 116A 11BF;D420;1111 116A 11BF; # (퐠; 퐠; 퐠; 퐠; 퐠; ) HANGUL SYLLABLE PWAK
+D421;D421;1111 116A 11C0;D421;1111 116A 11C0; # (퐡; 퐡; 퐡; 퐡; 퐡; ) HANGUL SYLLABLE PWAT
+D422;D422;1111 116A 11C1;D422;1111 116A 11C1; # (퐢; 퐢; 퐢; 퐢; 퐢; ) HANGUL SYLLABLE PWAP
+D423;D423;1111 116A 11C2;D423;1111 116A 11C2; # (퐣; 퐣; 퐣; 퐣; 퐣; ) HANGUL SYLLABLE PWAH
+D424;D424;1111 116B;D424;1111 116B; # (퐤; 퐤; 퐤; 퐤; 퐤; ) HANGUL SYLLABLE PWAE
+D425;D425;1111 116B 11A8;D425;1111 116B 11A8; # (퐥; 퐥; 퐥; 퐥; 퐥; ) HANGUL SYLLABLE PWAEG
+D426;D426;1111 116B 11A9;D426;1111 116B 11A9; # (퐦; 퐦; 퐦; 퐦; 퐦; ) HANGUL SYLLABLE PWAEGG
+D427;D427;1111 116B 11AA;D427;1111 116B 11AA; # (퐧; 퐧; 퐧; 퐧; 퐧; ) HANGUL SYLLABLE PWAEGS
+D428;D428;1111 116B 11AB;D428;1111 116B 11AB; # (퐨; 퐨; 퐨; 퐨; 퐨; ) HANGUL SYLLABLE PWAEN
+D429;D429;1111 116B 11AC;D429;1111 116B 11AC; # (퐩; 퐩; 퐩; 퐩; 퐩; ) HANGUL SYLLABLE PWAENJ
+D42A;D42A;1111 116B 11AD;D42A;1111 116B 11AD; # (퐪; 퐪; 퐪; 퐪; 퐪; ) HANGUL SYLLABLE PWAENH
+D42B;D42B;1111 116B 11AE;D42B;1111 116B 11AE; # (퐫; 퐫; 퐫; 퐫; 퐫; ) HANGUL SYLLABLE PWAED
+D42C;D42C;1111 116B 11AF;D42C;1111 116B 11AF; # (퐬; 퐬; 퐬; 퐬; 퐬; ) HANGUL SYLLABLE PWAEL
+D42D;D42D;1111 116B 11B0;D42D;1111 116B 11B0; # (퐭; 퐭; 퐭; 퐭; 퐭; ) HANGUL SYLLABLE PWAELG
+D42E;D42E;1111 116B 11B1;D42E;1111 116B 11B1; # (퐮; 퐮; 퐮; 퐮; 퐮; ) HANGUL SYLLABLE PWAELM
+D42F;D42F;1111 116B 11B2;D42F;1111 116B 11B2; # (퐯; 퐯; 퐯; 퐯; 퐯; ) HANGUL SYLLABLE PWAELB
+D430;D430;1111 116B 11B3;D430;1111 116B 11B3; # (퐰; 퐰; 퐰; 퐰; 퐰; ) HANGUL SYLLABLE PWAELS
+D431;D431;1111 116B 11B4;D431;1111 116B 11B4; # (퐱; 퐱; 퐱; 퐱; 퐱; ) HANGUL SYLLABLE PWAELT
+D432;D432;1111 116B 11B5;D432;1111 116B 11B5; # (퐲; 퐲; 퐲; 퐲; 퐲; ) HANGUL SYLLABLE PWAELP
+D433;D433;1111 116B 11B6;D433;1111 116B 11B6; # (퐳; 퐳; 퐳; 퐳; 퐳; ) HANGUL SYLLABLE PWAELH
+D434;D434;1111 116B 11B7;D434;1111 116B 11B7; # (퐴; 퐴; 퐴; 퐴; 퐴; ) HANGUL SYLLABLE PWAEM
+D435;D435;1111 116B 11B8;D435;1111 116B 11B8; # (퐵; 퐵; 퐵; 퐵; 퐵; ) HANGUL SYLLABLE PWAEB
+D436;D436;1111 116B 11B9;D436;1111 116B 11B9; # (퐶; 퐶; 퐶; 퐶; 퐶; ) HANGUL SYLLABLE PWAEBS
+D437;D437;1111 116B 11BA;D437;1111 116B 11BA; # (퐷; 퐷; 퐷; 퐷; 퐷; ) HANGUL SYLLABLE PWAES
+D438;D438;1111 116B 11BB;D438;1111 116B 11BB; # (퐸; 퐸; 퐸; 퐸; 퐸; ) HANGUL SYLLABLE PWAESS
+D439;D439;1111 116B 11BC;D439;1111 116B 11BC; # (퐹; 퐹; 퐹; 퐹; 퐹; ) HANGUL SYLLABLE PWAENG
+D43A;D43A;1111 116B 11BD;D43A;1111 116B 11BD; # (퐺; 퐺; 퐺; 퐺; 퐺; ) HANGUL SYLLABLE PWAEJ
+D43B;D43B;1111 116B 11BE;D43B;1111 116B 11BE; # (퐻; 퐻; 퐻; 퐻; 퐻; ) HANGUL SYLLABLE PWAEC
+D43C;D43C;1111 116B 11BF;D43C;1111 116B 11BF; # (퐼; 퐼; 퐼; 퐼; 퐼; ) HANGUL SYLLABLE PWAEK
+D43D;D43D;1111 116B 11C0;D43D;1111 116B 11C0; # (퐽; 퐽; 퐽; 퐽; 퐽; ) HANGUL SYLLABLE PWAET
+D43E;D43E;1111 116B 11C1;D43E;1111 116B 11C1; # (퐾; 퐾; 퐾; 퐾; 퐾; ) HANGUL SYLLABLE PWAEP
+D43F;D43F;1111 116B 11C2;D43F;1111 116B 11C2; # (퐿; 퐿; 퐿; 퐿; 퐿; ) HANGUL SYLLABLE PWAEH
+D440;D440;1111 116C;D440;1111 116C; # (푀; 푀; 푀; 푀; 푀; ) HANGUL SYLLABLE POE
+D441;D441;1111 116C 11A8;D441;1111 116C 11A8; # (푁; 푁; 푁; 푁; 푁; ) HANGUL SYLLABLE POEG
+D442;D442;1111 116C 11A9;D442;1111 116C 11A9; # (푂; 푂; 푂; 푂; 푂; ) HANGUL SYLLABLE POEGG
+D443;D443;1111 116C 11AA;D443;1111 116C 11AA; # (푃; 푃; 푃; 푃; 푃; ) HANGUL SYLLABLE POEGS
+D444;D444;1111 116C 11AB;D444;1111 116C 11AB; # (푄; 푄; 푄; 푄; 푄; ) HANGUL SYLLABLE POEN
+D445;D445;1111 116C 11AC;D445;1111 116C 11AC; # (푅; 푅; 푅; 푅; 푅; ) HANGUL SYLLABLE POENJ
+D446;D446;1111 116C 11AD;D446;1111 116C 11AD; # (푆; 푆; 푆; 푆; 푆; ) HANGUL SYLLABLE POENH
+D447;D447;1111 116C 11AE;D447;1111 116C 11AE; # (푇; 푇; 푇; 푇; 푇; ) HANGUL SYLLABLE POED
+D448;D448;1111 116C 11AF;D448;1111 116C 11AF; # (푈; 푈; 푈; 푈; 푈; ) HANGUL SYLLABLE POEL
+D449;D449;1111 116C 11B0;D449;1111 116C 11B0; # (푉; 푉; 푉; 푉; 푉; ) HANGUL SYLLABLE POELG
+D44A;D44A;1111 116C 11B1;D44A;1111 116C 11B1; # (푊; 푊; 푊; 푊; 푊; ) HANGUL SYLLABLE POELM
+D44B;D44B;1111 116C 11B2;D44B;1111 116C 11B2; # (푋; 푋; 푋; 푋; 푋; ) HANGUL SYLLABLE POELB
+D44C;D44C;1111 116C 11B3;D44C;1111 116C 11B3; # (푌; 푌; 푌; 푌; 푌; ) HANGUL SYLLABLE POELS
+D44D;D44D;1111 116C 11B4;D44D;1111 116C 11B4; # (푍; 푍; 푍; 푍; 푍; ) HANGUL SYLLABLE POELT
+D44E;D44E;1111 116C 11B5;D44E;1111 116C 11B5; # (푎; 푎; 푎; 푎; 푎; ) HANGUL SYLLABLE POELP
+D44F;D44F;1111 116C 11B6;D44F;1111 116C 11B6; # (푏; 푏; 푏; 푏; 푏; ) HANGUL SYLLABLE POELH
+D450;D450;1111 116C 11B7;D450;1111 116C 11B7; # (푐; 푐; 푐; 푐; 푐; ) HANGUL SYLLABLE POEM
+D451;D451;1111 116C 11B8;D451;1111 116C 11B8; # (푑; 푑; 푑; 푑; 푑; ) HANGUL SYLLABLE POEB
+D452;D452;1111 116C 11B9;D452;1111 116C 11B9; # (푒; 푒; 푒; 푒; 푒; ) HANGUL SYLLABLE POEBS
+D453;D453;1111 116C 11BA;D453;1111 116C 11BA; # (푓; 푓; 푓; 푓; 푓; ) HANGUL SYLLABLE POES
+D454;D454;1111 116C 11BB;D454;1111 116C 11BB; # (푔; 푔; 푔; 푔; 푔; ) HANGUL SYLLABLE POESS
+D455;D455;1111 116C 11BC;D455;1111 116C 11BC; # (푕; 푕; 푕; 푕; 푕; ) HANGUL SYLLABLE POENG
+D456;D456;1111 116C 11BD;D456;1111 116C 11BD; # (푖; 푖; 푖; 푖; 푖; ) HANGUL SYLLABLE POEJ
+D457;D457;1111 116C 11BE;D457;1111 116C 11BE; # (푗; 푗; 푗; 푗; 푗; ) HANGUL SYLLABLE POEC
+D458;D458;1111 116C 11BF;D458;1111 116C 11BF; # (푘; 푘; 푘; 푘; 푘; ) HANGUL SYLLABLE POEK
+D459;D459;1111 116C 11C0;D459;1111 116C 11C0; # (푙; 푙; 푙; 푙; 푙; ) HANGUL SYLLABLE POET
+D45A;D45A;1111 116C 11C1;D45A;1111 116C 11C1; # (푚; 푚; 푚; 푚; 푚; ) HANGUL SYLLABLE POEP
+D45B;D45B;1111 116C 11C2;D45B;1111 116C 11C2; # (푛; 푛; 푛; 푛; 푛; ) HANGUL SYLLABLE POEH
+D45C;D45C;1111 116D;D45C;1111 116D; # (표; 표; 표; 표; 표; ) HANGUL SYLLABLE PYO
+D45D;D45D;1111 116D 11A8;D45D;1111 116D 11A8; # (푝; 푝; 푝; 푝; 푝; ) HANGUL SYLLABLE PYOG
+D45E;D45E;1111 116D 11A9;D45E;1111 116D 11A9; # (푞; 푞; 푞; 푞; 푞; ) HANGUL SYLLABLE PYOGG
+D45F;D45F;1111 116D 11AA;D45F;1111 116D 11AA; # (푟; 푟; 푟; 푟; 푟; ) HANGUL SYLLABLE PYOGS
+D460;D460;1111 116D 11AB;D460;1111 116D 11AB; # (푠; 푠; 푠; 푠; 푠; ) HANGUL SYLLABLE PYON
+D461;D461;1111 116D 11AC;D461;1111 116D 11AC; # (푡; 푡; 푡; 푡; 푡; ) HANGUL SYLLABLE PYONJ
+D462;D462;1111 116D 11AD;D462;1111 116D 11AD; # (푢; 푢; 푢; 푢; 푢; ) HANGUL SYLLABLE PYONH
+D463;D463;1111 116D 11AE;D463;1111 116D 11AE; # (푣; 푣; 푣; 푣; 푣; ) HANGUL SYLLABLE PYOD
+D464;D464;1111 116D 11AF;D464;1111 116D 11AF; # (푤; 푤; 푤; 푤; 푤; ) HANGUL SYLLABLE PYOL
+D465;D465;1111 116D 11B0;D465;1111 116D 11B0; # (푥; 푥; 푥; 푥; 푥; ) HANGUL SYLLABLE PYOLG
+D466;D466;1111 116D 11B1;D466;1111 116D 11B1; # (푦; 푦; 푦; 푦; 푦; ) HANGUL SYLLABLE PYOLM
+D467;D467;1111 116D 11B2;D467;1111 116D 11B2; # (푧; 푧; 푧; 푧; 푧; ) HANGUL SYLLABLE PYOLB
+D468;D468;1111 116D 11B3;D468;1111 116D 11B3; # (푨; 푨; 푨; 푨; 푨; ) HANGUL SYLLABLE PYOLS
+D469;D469;1111 116D 11B4;D469;1111 116D 11B4; # (푩; 푩; 푩; 푩; 푩; ) HANGUL SYLLABLE PYOLT
+D46A;D46A;1111 116D 11B5;D46A;1111 116D 11B5; # (푪; 푪; 푪; 푪; 푪; ) HANGUL SYLLABLE PYOLP
+D46B;D46B;1111 116D 11B6;D46B;1111 116D 11B6; # (푫; 푫; 푫; 푫; 푫; ) HANGUL SYLLABLE PYOLH
+D46C;D46C;1111 116D 11B7;D46C;1111 116D 11B7; # (푬; 푬; 푬; 푬; 푬; ) HANGUL SYLLABLE PYOM
+D46D;D46D;1111 116D 11B8;D46D;1111 116D 11B8; # (푭; 푭; 푭; 푭; 푭; ) HANGUL SYLLABLE PYOB
+D46E;D46E;1111 116D 11B9;D46E;1111 116D 11B9; # (푮; 푮; 푮; 푮; 푮; ) HANGUL SYLLABLE PYOBS
+D46F;D46F;1111 116D 11BA;D46F;1111 116D 11BA; # (푯; 푯; 푯; 푯; 푯; ) HANGUL SYLLABLE PYOS
+D470;D470;1111 116D 11BB;D470;1111 116D 11BB; # (푰; 푰; 푰; 푰; 푰; ) HANGUL SYLLABLE PYOSS
+D471;D471;1111 116D 11BC;D471;1111 116D 11BC; # (푱; 푱; 푱; 푱; 푱; ) HANGUL SYLLABLE PYONG
+D472;D472;1111 116D 11BD;D472;1111 116D 11BD; # (푲; 푲; 푲; 푲; 푲; ) HANGUL SYLLABLE PYOJ
+D473;D473;1111 116D 11BE;D473;1111 116D 11BE; # (푳; 푳; 푳; 푳; 푳; ) HANGUL SYLLABLE PYOC
+D474;D474;1111 116D 11BF;D474;1111 116D 11BF; # (푴; 푴; 푴; 푴; 푴; ) HANGUL SYLLABLE PYOK
+D475;D475;1111 116D 11C0;D475;1111 116D 11C0; # (푵; 푵; 푵; 푵; 푵; ) HANGUL SYLLABLE PYOT
+D476;D476;1111 116D 11C1;D476;1111 116D 11C1; # (푶; 푶; 푶; 푶; 푶; ) HANGUL SYLLABLE PYOP
+D477;D477;1111 116D 11C2;D477;1111 116D 11C2; # (푷; 푷; 푷; 푷; 푷; ) HANGUL SYLLABLE PYOH
+D478;D478;1111 116E;D478;1111 116E; # (푸; 푸; 푸; 푸; 푸; ) HANGUL SYLLABLE PU
+D479;D479;1111 116E 11A8;D479;1111 116E 11A8; # (푹; 푹; 푹; 푹; 푹; ) HANGUL SYLLABLE PUG
+D47A;D47A;1111 116E 11A9;D47A;1111 116E 11A9; # (푺; 푺; 푺; 푺; 푺; ) HANGUL SYLLABLE PUGG
+D47B;D47B;1111 116E 11AA;D47B;1111 116E 11AA; # (푻; 푻; 푻; 푻; 푻; ) HANGUL SYLLABLE PUGS
+D47C;D47C;1111 116E 11AB;D47C;1111 116E 11AB; # (푼; 푼; 푼; 푼; 푼; ) HANGUL SYLLABLE PUN
+D47D;D47D;1111 116E 11AC;D47D;1111 116E 11AC; # (푽; 푽; 푽; 푽; 푽; ) HANGUL SYLLABLE PUNJ
+D47E;D47E;1111 116E 11AD;D47E;1111 116E 11AD; # (푾; 푾; 푾; 푾; 푾; ) HANGUL SYLLABLE PUNH
+D47F;D47F;1111 116E 11AE;D47F;1111 116E 11AE; # (푿; 푿; 푿; 푿; 푿; ) HANGUL SYLLABLE PUD
+D480;D480;1111 116E 11AF;D480;1111 116E 11AF; # (풀; 풀; 풀; 풀; 풀; ) HANGUL SYLLABLE PUL
+D481;D481;1111 116E 11B0;D481;1111 116E 11B0; # (풁; 풁; 풁; 풁; 풁; ) HANGUL SYLLABLE PULG
+D482;D482;1111 116E 11B1;D482;1111 116E 11B1; # (풂; 풂; 풂; 풂; 풂; ) HANGUL SYLLABLE PULM
+D483;D483;1111 116E 11B2;D483;1111 116E 11B2; # (풃; 풃; 풃; 풃; 풃; ) HANGUL SYLLABLE PULB
+D484;D484;1111 116E 11B3;D484;1111 116E 11B3; # (풄; 풄; 풄; 풄; 풄; ) HANGUL SYLLABLE PULS
+D485;D485;1111 116E 11B4;D485;1111 116E 11B4; # (풅; 풅; 풅; 풅; 풅; ) HANGUL SYLLABLE PULT
+D486;D486;1111 116E 11B5;D486;1111 116E 11B5; # (풆; 풆; 풆; 풆; 풆; ) HANGUL SYLLABLE PULP
+D487;D487;1111 116E 11B6;D487;1111 116E 11B6; # (풇; 풇; 풇; 풇; 풇; ) HANGUL SYLLABLE PULH
+D488;D488;1111 116E 11B7;D488;1111 116E 11B7; # (품; 품; 품; 품; 품; ) HANGUL SYLLABLE PUM
+D489;D489;1111 116E 11B8;D489;1111 116E 11B8; # (풉; 풉; 풉; 풉; 풉; ) HANGUL SYLLABLE PUB
+D48A;D48A;1111 116E 11B9;D48A;1111 116E 11B9; # (풊; 풊; 풊; 풊; 풊; ) HANGUL SYLLABLE PUBS
+D48B;D48B;1111 116E 11BA;D48B;1111 116E 11BA; # (풋; 풋; 풋; 풋; 풋; ) HANGUL SYLLABLE PUS
+D48C;D48C;1111 116E 11BB;D48C;1111 116E 11BB; # (풌; 풌; 풌; 풌; 풌; ) HANGUL SYLLABLE PUSS
+D48D;D48D;1111 116E 11BC;D48D;1111 116E 11BC; # (풍; 풍; 풍; 풍; 풍; ) HANGUL SYLLABLE PUNG
+D48E;D48E;1111 116E 11BD;D48E;1111 116E 11BD; # (풎; 풎; 풎; 풎; 풎; ) HANGUL SYLLABLE PUJ
+D48F;D48F;1111 116E 11BE;D48F;1111 116E 11BE; # (풏; 풏; 풏; 풏; 풏; ) HANGUL SYLLABLE PUC
+D490;D490;1111 116E 11BF;D490;1111 116E 11BF; # (풐; 풐; 풐; 풐; 풐; ) HANGUL SYLLABLE PUK
+D491;D491;1111 116E 11C0;D491;1111 116E 11C0; # (풑; 풑; 풑; 풑; 풑; ) HANGUL SYLLABLE PUT
+D492;D492;1111 116E 11C1;D492;1111 116E 11C1; # (풒; 풒; 풒; 풒; 풒; ) HANGUL SYLLABLE PUP
+D493;D493;1111 116E 11C2;D493;1111 116E 11C2; # (풓; 풓; 풓; 풓; 풓; ) HANGUL SYLLABLE PUH
+D494;D494;1111 116F;D494;1111 116F; # (풔; 풔; 풔; 풔; 풔; ) HANGUL SYLLABLE PWEO
+D495;D495;1111 116F 11A8;D495;1111 116F 11A8; # (풕; 풕; 풕; 풕; 풕; ) HANGUL SYLLABLE PWEOG
+D496;D496;1111 116F 11A9;D496;1111 116F 11A9; # (풖; 풖; 풖; 풖; 풖; ) HANGUL SYLLABLE PWEOGG
+D497;D497;1111 116F 11AA;D497;1111 116F 11AA; # (풗; 풗; 풗; 풗; 풗; ) HANGUL SYLLABLE PWEOGS
+D498;D498;1111 116F 11AB;D498;1111 116F 11AB; # (풘; 풘; 풘; 풘; 풘; ) HANGUL SYLLABLE PWEON
+D499;D499;1111 116F 11AC;D499;1111 116F 11AC; # (풙; 풙; 풙; 풙; 풙; ) HANGUL SYLLABLE PWEONJ
+D49A;D49A;1111 116F 11AD;D49A;1111 116F 11AD; # (풚; 풚; 풚; 풚; 풚; ) HANGUL SYLLABLE PWEONH
+D49B;D49B;1111 116F 11AE;D49B;1111 116F 11AE; # (풛; 풛; 풛; 풛; 풛; ) HANGUL SYLLABLE PWEOD
+D49C;D49C;1111 116F 11AF;D49C;1111 116F 11AF; # (풜; 풜; 풜; 풜; 풜; ) HANGUL SYLLABLE PWEOL
+D49D;D49D;1111 116F 11B0;D49D;1111 116F 11B0; # (풝; 풝; 풝; 풝; 풝; ) HANGUL SYLLABLE PWEOLG
+D49E;D49E;1111 116F 11B1;D49E;1111 116F 11B1; # (풞; 풞; 풞; 풞; 풞; ) HANGUL SYLLABLE PWEOLM
+D49F;D49F;1111 116F 11B2;D49F;1111 116F 11B2; # (풟; 풟; 풟; 풟; 풟; ) HANGUL SYLLABLE PWEOLB
+D4A0;D4A0;1111 116F 11B3;D4A0;1111 116F 11B3; # (풠; 풠; 풠; 풠; 풠; ) HANGUL SYLLABLE PWEOLS
+D4A1;D4A1;1111 116F 11B4;D4A1;1111 116F 11B4; # (풡; 풡; 풡; 풡; 풡; ) HANGUL SYLLABLE PWEOLT
+D4A2;D4A2;1111 116F 11B5;D4A2;1111 116F 11B5; # (풢; 풢; 풢; 풢; 풢; ) HANGUL SYLLABLE PWEOLP
+D4A3;D4A3;1111 116F 11B6;D4A3;1111 116F 11B6; # (풣; 풣; 풣; 풣; 풣; ) HANGUL SYLLABLE PWEOLH
+D4A4;D4A4;1111 116F 11B7;D4A4;1111 116F 11B7; # (풤; 풤; 풤; 풤; 풤; ) HANGUL SYLLABLE PWEOM
+D4A5;D4A5;1111 116F 11B8;D4A5;1111 116F 11B8; # (풥; 풥; 풥; 풥; 풥; ) HANGUL SYLLABLE PWEOB
+D4A6;D4A6;1111 116F 11B9;D4A6;1111 116F 11B9; # (풦; 풦; 풦; 풦; 풦; ) HANGUL SYLLABLE PWEOBS
+D4A7;D4A7;1111 116F 11BA;D4A7;1111 116F 11BA; # (풧; 풧; 풧; 풧; 풧; ) HANGUL SYLLABLE PWEOS
+D4A8;D4A8;1111 116F 11BB;D4A8;1111 116F 11BB; # (풨; 풨; 풨; 풨; 풨; ) HANGUL SYLLABLE PWEOSS
+D4A9;D4A9;1111 116F 11BC;D4A9;1111 116F 11BC; # (풩; 풩; 풩; 풩; 풩; ) HANGUL SYLLABLE PWEONG
+D4AA;D4AA;1111 116F 11BD;D4AA;1111 116F 11BD; # (풪; 풪; 풪; 풪; 풪; ) HANGUL SYLLABLE PWEOJ
+D4AB;D4AB;1111 116F 11BE;D4AB;1111 116F 11BE; # (풫; 풫; 풫; 풫; 풫; ) HANGUL SYLLABLE PWEOC
+D4AC;D4AC;1111 116F 11BF;D4AC;1111 116F 11BF; # (풬; 풬; 풬; 풬; 풬; ) HANGUL SYLLABLE PWEOK
+D4AD;D4AD;1111 116F 11C0;D4AD;1111 116F 11C0; # (풭; 풭; 풭; 풭; 풭; ) HANGUL SYLLABLE PWEOT
+D4AE;D4AE;1111 116F 11C1;D4AE;1111 116F 11C1; # (풮; 풮; 풮; 풮; 풮; ) HANGUL SYLLABLE PWEOP
+D4AF;D4AF;1111 116F 11C2;D4AF;1111 116F 11C2; # (풯; 풯; 풯; 풯; 풯; ) HANGUL SYLLABLE PWEOH
+D4B0;D4B0;1111 1170;D4B0;1111 1170; # (풰; 풰; 풰; 풰; 풰; ) HANGUL SYLLABLE PWE
+D4B1;D4B1;1111 1170 11A8;D4B1;1111 1170 11A8; # (풱; 풱; 풱; 풱; 풱; ) HANGUL SYLLABLE PWEG
+D4B2;D4B2;1111 1170 11A9;D4B2;1111 1170 11A9; # (풲; 풲; 풲; 풲; 풲; ) HANGUL SYLLABLE PWEGG
+D4B3;D4B3;1111 1170 11AA;D4B3;1111 1170 11AA; # (풳; 풳; 풳; 풳; 풳; ) HANGUL SYLLABLE PWEGS
+D4B4;D4B4;1111 1170 11AB;D4B4;1111 1170 11AB; # (풴; 풴; 풴; 풴; 풴; ) HANGUL SYLLABLE PWEN
+D4B5;D4B5;1111 1170 11AC;D4B5;1111 1170 11AC; # (풵; 풵; 풵; 풵; 풵; ) HANGUL SYLLABLE PWENJ
+D4B6;D4B6;1111 1170 11AD;D4B6;1111 1170 11AD; # (풶; 풶; 풶; 풶; 풶; ) HANGUL SYLLABLE PWENH
+D4B7;D4B7;1111 1170 11AE;D4B7;1111 1170 11AE; # (풷; 풷; 풷; 풷; 풷; ) HANGUL SYLLABLE PWED
+D4B8;D4B8;1111 1170 11AF;D4B8;1111 1170 11AF; # (풸; 풸; 풸; 풸; 풸; ) HANGUL SYLLABLE PWEL
+D4B9;D4B9;1111 1170 11B0;D4B9;1111 1170 11B0; # (풹; 풹; 풹; 풹; 풹; ) HANGUL SYLLABLE PWELG
+D4BA;D4BA;1111 1170 11B1;D4BA;1111 1170 11B1; # (풺; 풺; 풺; 풺; 풺; ) HANGUL SYLLABLE PWELM
+D4BB;D4BB;1111 1170 11B2;D4BB;1111 1170 11B2; # (풻; 풻; 풻; 풻; 풻; ) HANGUL SYLLABLE PWELB
+D4BC;D4BC;1111 1170 11B3;D4BC;1111 1170 11B3; # (풼; 풼; 풼; 풼; 풼; ) HANGUL SYLLABLE PWELS
+D4BD;D4BD;1111 1170 11B4;D4BD;1111 1170 11B4; # (풽; 풽; 풽; 풽; 풽; ) HANGUL SYLLABLE PWELT
+D4BE;D4BE;1111 1170 11B5;D4BE;1111 1170 11B5; # (풾; 풾; 풾; 풾; 풾; ) HANGUL SYLLABLE PWELP
+D4BF;D4BF;1111 1170 11B6;D4BF;1111 1170 11B6; # (풿; 풿; 풿; 풿; 풿; ) HANGUL SYLLABLE PWELH
+D4C0;D4C0;1111 1170 11B7;D4C0;1111 1170 11B7; # (퓀; 퓀; 퓀; 퓀; 퓀; ) HANGUL SYLLABLE PWEM
+D4C1;D4C1;1111 1170 11B8;D4C1;1111 1170 11B8; # (퓁; 퓁; 퓁; 퓁; 퓁; ) HANGUL SYLLABLE PWEB
+D4C2;D4C2;1111 1170 11B9;D4C2;1111 1170 11B9; # (퓂; 퓂; 퓂; 퓂; 퓂; ) HANGUL SYLLABLE PWEBS
+D4C3;D4C3;1111 1170 11BA;D4C3;1111 1170 11BA; # (퓃; 퓃; 퓃; 퓃; 퓃; ) HANGUL SYLLABLE PWES
+D4C4;D4C4;1111 1170 11BB;D4C4;1111 1170 11BB; # (퓄; 퓄; 퓄; 퓄; 퓄; ) HANGUL SYLLABLE PWESS
+D4C5;D4C5;1111 1170 11BC;D4C5;1111 1170 11BC; # (퓅; 퓅; 퓅; 퓅; 퓅; ) HANGUL SYLLABLE PWENG
+D4C6;D4C6;1111 1170 11BD;D4C6;1111 1170 11BD; # (퓆; 퓆; 퓆; 퓆; 퓆; ) HANGUL SYLLABLE PWEJ
+D4C7;D4C7;1111 1170 11BE;D4C7;1111 1170 11BE; # (퓇; 퓇; 퓇; 퓇; 퓇; ) HANGUL SYLLABLE PWEC
+D4C8;D4C8;1111 1170 11BF;D4C8;1111 1170 11BF; # (퓈; 퓈; 퓈; 퓈; 퓈; ) HANGUL SYLLABLE PWEK
+D4C9;D4C9;1111 1170 11C0;D4C9;1111 1170 11C0; # (퓉; 퓉; 퓉; 퓉; 퓉; ) HANGUL SYLLABLE PWET
+D4CA;D4CA;1111 1170 11C1;D4CA;1111 1170 11C1; # (퓊; 퓊; 퓊; 퓊; 퓊; ) HANGUL SYLLABLE PWEP
+D4CB;D4CB;1111 1170 11C2;D4CB;1111 1170 11C2; # (퓋; 퓋; 퓋; 퓋; 퓋; ) HANGUL SYLLABLE PWEH
+D4CC;D4CC;1111 1171;D4CC;1111 1171; # (퓌; 퓌; 퓌; 퓌; 퓌; ) HANGUL SYLLABLE PWI
+D4CD;D4CD;1111 1171 11A8;D4CD;1111 1171 11A8; # (퓍; 퓍; 퓍; 퓍; 퓍; ) HANGUL SYLLABLE PWIG
+D4CE;D4CE;1111 1171 11A9;D4CE;1111 1171 11A9; # (퓎; 퓎; 퓎; 퓎; 퓎; ) HANGUL SYLLABLE PWIGG
+D4CF;D4CF;1111 1171 11AA;D4CF;1111 1171 11AA; # (퓏; 퓏; 퓏; 퓏; 퓏; ) HANGUL SYLLABLE PWIGS
+D4D0;D4D0;1111 1171 11AB;D4D0;1111 1171 11AB; # (퓐; 퓐; 퓐; 퓐; 퓐; ) HANGUL SYLLABLE PWIN
+D4D1;D4D1;1111 1171 11AC;D4D1;1111 1171 11AC; # (퓑; 퓑; 퓑; 퓑; 퓑; ) HANGUL SYLLABLE PWINJ
+D4D2;D4D2;1111 1171 11AD;D4D2;1111 1171 11AD; # (퓒; 퓒; 퓒; 퓒; 퓒; ) HANGUL SYLLABLE PWINH
+D4D3;D4D3;1111 1171 11AE;D4D3;1111 1171 11AE; # (퓓; 퓓; 퓓; 퓓; 퓓; ) HANGUL SYLLABLE PWID
+D4D4;D4D4;1111 1171 11AF;D4D4;1111 1171 11AF; # (퓔; 퓔; 퓔; 퓔; 퓔; ) HANGUL SYLLABLE PWIL
+D4D5;D4D5;1111 1171 11B0;D4D5;1111 1171 11B0; # (퓕; 퓕; 퓕; 퓕; 퓕; ) HANGUL SYLLABLE PWILG
+D4D6;D4D6;1111 1171 11B1;D4D6;1111 1171 11B1; # (퓖; 퓖; 퓖; 퓖; 퓖; ) HANGUL SYLLABLE PWILM
+D4D7;D4D7;1111 1171 11B2;D4D7;1111 1171 11B2; # (퓗; 퓗; 퓗; 퓗; 퓗; ) HANGUL SYLLABLE PWILB
+D4D8;D4D8;1111 1171 11B3;D4D8;1111 1171 11B3; # (퓘; 퓘; 퓘; 퓘; 퓘; ) HANGUL SYLLABLE PWILS
+D4D9;D4D9;1111 1171 11B4;D4D9;1111 1171 11B4; # (퓙; 퓙; 퓙; 퓙; 퓙; ) HANGUL SYLLABLE PWILT
+D4DA;D4DA;1111 1171 11B5;D4DA;1111 1171 11B5; # (퓚; 퓚; 퓚; 퓚; 퓚; ) HANGUL SYLLABLE PWILP
+D4DB;D4DB;1111 1171 11B6;D4DB;1111 1171 11B6; # (퓛; 퓛; 퓛; 퓛; 퓛; ) HANGUL SYLLABLE PWILH
+D4DC;D4DC;1111 1171 11B7;D4DC;1111 1171 11B7; # (퓜; 퓜; 퓜; 퓜; 퓜; ) HANGUL SYLLABLE PWIM
+D4DD;D4DD;1111 1171 11B8;D4DD;1111 1171 11B8; # (퓝; 퓝; 퓝; 퓝; 퓝; ) HANGUL SYLLABLE PWIB
+D4DE;D4DE;1111 1171 11B9;D4DE;1111 1171 11B9; # (퓞; 퓞; 퓞; 퓞; 퓞; ) HANGUL SYLLABLE PWIBS
+D4DF;D4DF;1111 1171 11BA;D4DF;1111 1171 11BA; # (퓟; 퓟; 퓟; 퓟; 퓟; ) HANGUL SYLLABLE PWIS
+D4E0;D4E0;1111 1171 11BB;D4E0;1111 1171 11BB; # (퓠; 퓠; 퓠; 퓠; 퓠; ) HANGUL SYLLABLE PWISS
+D4E1;D4E1;1111 1171 11BC;D4E1;1111 1171 11BC; # (퓡; 퓡; 퓡; 퓡; 퓡; ) HANGUL SYLLABLE PWING
+D4E2;D4E2;1111 1171 11BD;D4E2;1111 1171 11BD; # (퓢; 퓢; 퓢; 퓢; 퓢; ) HANGUL SYLLABLE PWIJ
+D4E3;D4E3;1111 1171 11BE;D4E3;1111 1171 11BE; # (퓣; 퓣; 퓣; 퓣; 퓣; ) HANGUL SYLLABLE PWIC
+D4E4;D4E4;1111 1171 11BF;D4E4;1111 1171 11BF; # (퓤; 퓤; 퓤; 퓤; 퓤; ) HANGUL SYLLABLE PWIK
+D4E5;D4E5;1111 1171 11C0;D4E5;1111 1171 11C0; # (퓥; 퓥; 퓥; 퓥; 퓥; ) HANGUL SYLLABLE PWIT
+D4E6;D4E6;1111 1171 11C1;D4E6;1111 1171 11C1; # (퓦; 퓦; 퓦; 퓦; 퓦; ) HANGUL SYLLABLE PWIP
+D4E7;D4E7;1111 1171 11C2;D4E7;1111 1171 11C2; # (퓧; 퓧; 퓧; 퓧; 퓧; ) HANGUL SYLLABLE PWIH
+D4E8;D4E8;1111 1172;D4E8;1111 1172; # (퓨; 퓨; 퓨; 퓨; 퓨; ) HANGUL SYLLABLE PYU
+D4E9;D4E9;1111 1172 11A8;D4E9;1111 1172 11A8; # (퓩; 퓩; 퓩; 퓩; 퓩; ) HANGUL SYLLABLE PYUG
+D4EA;D4EA;1111 1172 11A9;D4EA;1111 1172 11A9; # (퓪; 퓪; 퓪; 퓪; 퓪; ) HANGUL SYLLABLE PYUGG
+D4EB;D4EB;1111 1172 11AA;D4EB;1111 1172 11AA; # (퓫; 퓫; 퓫; 퓫; 퓫; ) HANGUL SYLLABLE PYUGS
+D4EC;D4EC;1111 1172 11AB;D4EC;1111 1172 11AB; # (퓬; 퓬; 퓬; 퓬; 퓬; ) HANGUL SYLLABLE PYUN
+D4ED;D4ED;1111 1172 11AC;D4ED;1111 1172 11AC; # (퓭; 퓭; 퓭; 퓭; 퓭; ) HANGUL SYLLABLE PYUNJ
+D4EE;D4EE;1111 1172 11AD;D4EE;1111 1172 11AD; # (퓮; 퓮; 퓮; 퓮; 퓮; ) HANGUL SYLLABLE PYUNH
+D4EF;D4EF;1111 1172 11AE;D4EF;1111 1172 11AE; # (퓯; 퓯; 퓯; 퓯; 퓯; ) HANGUL SYLLABLE PYUD
+D4F0;D4F0;1111 1172 11AF;D4F0;1111 1172 11AF; # (퓰; 퓰; 퓰; 퓰; 퓰; ) HANGUL SYLLABLE PYUL
+D4F1;D4F1;1111 1172 11B0;D4F1;1111 1172 11B0; # (퓱; 퓱; 퓱; 퓱; 퓱; ) HANGUL SYLLABLE PYULG
+D4F2;D4F2;1111 1172 11B1;D4F2;1111 1172 11B1; # (퓲; 퓲; 퓲; 퓲; 퓲; ) HANGUL SYLLABLE PYULM
+D4F3;D4F3;1111 1172 11B2;D4F3;1111 1172 11B2; # (퓳; 퓳; 퓳; 퓳; 퓳; ) HANGUL SYLLABLE PYULB
+D4F4;D4F4;1111 1172 11B3;D4F4;1111 1172 11B3; # (퓴; 퓴; 퓴; 퓴; 퓴; ) HANGUL SYLLABLE PYULS
+D4F5;D4F5;1111 1172 11B4;D4F5;1111 1172 11B4; # (퓵; 퓵; 퓵; 퓵; 퓵; ) HANGUL SYLLABLE PYULT
+D4F6;D4F6;1111 1172 11B5;D4F6;1111 1172 11B5; # (퓶; 퓶; 퓶; 퓶; 퓶; ) HANGUL SYLLABLE PYULP
+D4F7;D4F7;1111 1172 11B6;D4F7;1111 1172 11B6; # (퓷; 퓷; 퓷; 퓷; 퓷; ) HANGUL SYLLABLE PYULH
+D4F8;D4F8;1111 1172 11B7;D4F8;1111 1172 11B7; # (퓸; 퓸; 퓸; 퓸; 퓸; ) HANGUL SYLLABLE PYUM
+D4F9;D4F9;1111 1172 11B8;D4F9;1111 1172 11B8; # (퓹; 퓹; 퓹; 퓹; 퓹; ) HANGUL SYLLABLE PYUB
+D4FA;D4FA;1111 1172 11B9;D4FA;1111 1172 11B9; # (퓺; 퓺; 퓺; 퓺; 퓺; ) HANGUL SYLLABLE PYUBS
+D4FB;D4FB;1111 1172 11BA;D4FB;1111 1172 11BA; # (퓻; 퓻; 퓻; 퓻; 퓻; ) HANGUL SYLLABLE PYUS
+D4FC;D4FC;1111 1172 11BB;D4FC;1111 1172 11BB; # (퓼; 퓼; 퓼; 퓼; 퓼; ) HANGUL SYLLABLE PYUSS
+D4FD;D4FD;1111 1172 11BC;D4FD;1111 1172 11BC; # (퓽; 퓽; 퓽; 퓽; 퓽; ) HANGUL SYLLABLE PYUNG
+D4FE;D4FE;1111 1172 11BD;D4FE;1111 1172 11BD; # (퓾; 퓾; 퓾; 퓾; 퓾; ) HANGUL SYLLABLE PYUJ
+D4FF;D4FF;1111 1172 11BE;D4FF;1111 1172 11BE; # (퓿; 퓿; 퓿; 퓿; 퓿; ) HANGUL SYLLABLE PYUC
+D500;D500;1111 1172 11BF;D500;1111 1172 11BF; # (픀; 픀; 픀; 픀; 픀; ) HANGUL SYLLABLE PYUK
+D501;D501;1111 1172 11C0;D501;1111 1172 11C0; # (픁; 픁; 픁; 픁; 픁; ) HANGUL SYLLABLE PYUT
+D502;D502;1111 1172 11C1;D502;1111 1172 11C1; # (픂; 픂; 픂; 픂; 픂; ) HANGUL SYLLABLE PYUP
+D503;D503;1111 1172 11C2;D503;1111 1172 11C2; # (픃; 픃; 픃; 픃; 픃; ) HANGUL SYLLABLE PYUH
+D504;D504;1111 1173;D504;1111 1173; # (프; 프; 프; 프; 프; ) HANGUL SYLLABLE PEU
+D505;D505;1111 1173 11A8;D505;1111 1173 11A8; # (픅; 픅; 픅; 픅; 픅; ) HANGUL SYLLABLE PEUG
+D506;D506;1111 1173 11A9;D506;1111 1173 11A9; # (픆; 픆; 픆; 픆; 픆; ) HANGUL SYLLABLE PEUGG
+D507;D507;1111 1173 11AA;D507;1111 1173 11AA; # (픇; 픇; 픇; 픇; 픇; ) HANGUL SYLLABLE PEUGS
+D508;D508;1111 1173 11AB;D508;1111 1173 11AB; # (픈; 픈; 픈; 픈; 픈; ) HANGUL SYLLABLE PEUN
+D509;D509;1111 1173 11AC;D509;1111 1173 11AC; # (픉; 픉; 픉; 픉; 픉; ) HANGUL SYLLABLE PEUNJ
+D50A;D50A;1111 1173 11AD;D50A;1111 1173 11AD; # (픊; 픊; 픊; 픊; 픊; ) HANGUL SYLLABLE PEUNH
+D50B;D50B;1111 1173 11AE;D50B;1111 1173 11AE; # (픋; 픋; 픋; 픋; 픋; ) HANGUL SYLLABLE PEUD
+D50C;D50C;1111 1173 11AF;D50C;1111 1173 11AF; # (플; 플; 플; 플; 플; ) HANGUL SYLLABLE PEUL
+D50D;D50D;1111 1173 11B0;D50D;1111 1173 11B0; # (픍; 픍; 픍; 픍; 픍; ) HANGUL SYLLABLE PEULG
+D50E;D50E;1111 1173 11B1;D50E;1111 1173 11B1; # (픎; 픎; 픎; 픎; 픎; ) HANGUL SYLLABLE PEULM
+D50F;D50F;1111 1173 11B2;D50F;1111 1173 11B2; # (픏; 픏; 픏; 픏; 픏; ) HANGUL SYLLABLE PEULB
+D510;D510;1111 1173 11B3;D510;1111 1173 11B3; # (픐; 픐; 픐; 픐; 픐; ) HANGUL SYLLABLE PEULS
+D511;D511;1111 1173 11B4;D511;1111 1173 11B4; # (픑; 픑; 픑; 픑; 픑; ) HANGUL SYLLABLE PEULT
+D512;D512;1111 1173 11B5;D512;1111 1173 11B5; # (픒; 픒; 픒; 픒; 픒; ) HANGUL SYLLABLE PEULP
+D513;D513;1111 1173 11B6;D513;1111 1173 11B6; # (픓; 픓; 픓; 픓; 픓; ) HANGUL SYLLABLE PEULH
+D514;D514;1111 1173 11B7;D514;1111 1173 11B7; # (픔; 픔; 픔; 픔; 픔; ) HANGUL SYLLABLE PEUM
+D515;D515;1111 1173 11B8;D515;1111 1173 11B8; # (픕; 픕; 픕; 픕; 픕; ) HANGUL SYLLABLE PEUB
+D516;D516;1111 1173 11B9;D516;1111 1173 11B9; # (픖; 픖; 픖; 픖; 픖; ) HANGUL SYLLABLE PEUBS
+D517;D517;1111 1173 11BA;D517;1111 1173 11BA; # (픗; 픗; 픗; 픗; 픗; ) HANGUL SYLLABLE PEUS
+D518;D518;1111 1173 11BB;D518;1111 1173 11BB; # (픘; 픘; 픘; 픘; 픘; ) HANGUL SYLLABLE PEUSS
+D519;D519;1111 1173 11BC;D519;1111 1173 11BC; # (픙; 픙; 픙; 픙; 픙; ) HANGUL SYLLABLE PEUNG
+D51A;D51A;1111 1173 11BD;D51A;1111 1173 11BD; # (픚; 픚; 픚; 픚; 픚; ) HANGUL SYLLABLE PEUJ
+D51B;D51B;1111 1173 11BE;D51B;1111 1173 11BE; # (픛; 픛; 픛; 픛; 픛; ) HANGUL SYLLABLE PEUC
+D51C;D51C;1111 1173 11BF;D51C;1111 1173 11BF; # (픜; 픜; 픜; 픜; 픜; ) HANGUL SYLLABLE PEUK
+D51D;D51D;1111 1173 11C0;D51D;1111 1173 11C0; # (픝; 픝; 픝; 픝; 픝; ) HANGUL SYLLABLE PEUT
+D51E;D51E;1111 1173 11C1;D51E;1111 1173 11C1; # (픞; 픞; 픞; 픞; 픞; ) HANGUL SYLLABLE PEUP
+D51F;D51F;1111 1173 11C2;D51F;1111 1173 11C2; # (픟; 픟; 픟; 픟; 픟; ) HANGUL SYLLABLE PEUH
+D520;D520;1111 1174;D520;1111 1174; # (픠; 픠; 픠; 픠; 픠; ) HANGUL SYLLABLE PYI
+D521;D521;1111 1174 11A8;D521;1111 1174 11A8; # (픡; 픡; 픡; 픡; 픡; ) HANGUL SYLLABLE PYIG
+D522;D522;1111 1174 11A9;D522;1111 1174 11A9; # (픢; 픢; 픢; 픢; 픢; ) HANGUL SYLLABLE PYIGG
+D523;D523;1111 1174 11AA;D523;1111 1174 11AA; # (픣; 픣; 픣; 픣; 픣; ) HANGUL SYLLABLE PYIGS
+D524;D524;1111 1174 11AB;D524;1111 1174 11AB; # (픤; 픤; 픤; 픤; 픤; ) HANGUL SYLLABLE PYIN
+D525;D525;1111 1174 11AC;D525;1111 1174 11AC; # (픥; 픥; 픥; 픥; 픥; ) HANGUL SYLLABLE PYINJ
+D526;D526;1111 1174 11AD;D526;1111 1174 11AD; # (픦; 픦; 픦; 픦; 픦; ) HANGUL SYLLABLE PYINH
+D527;D527;1111 1174 11AE;D527;1111 1174 11AE; # (픧; 픧; 픧; 픧; 픧; ) HANGUL SYLLABLE PYID
+D528;D528;1111 1174 11AF;D528;1111 1174 11AF; # (픨; 픨; 픨; 픨; 픨; ) HANGUL SYLLABLE PYIL
+D529;D529;1111 1174 11B0;D529;1111 1174 11B0; # (픩; 픩; 픩; 픩; 픩; ) HANGUL SYLLABLE PYILG
+D52A;D52A;1111 1174 11B1;D52A;1111 1174 11B1; # (픪; 픪; 픪; 픪; 픪; ) HANGUL SYLLABLE PYILM
+D52B;D52B;1111 1174 11B2;D52B;1111 1174 11B2; # (픫; 픫; 픫; 픫; 픫; ) HANGUL SYLLABLE PYILB
+D52C;D52C;1111 1174 11B3;D52C;1111 1174 11B3; # (픬; 픬; 픬; 픬; 픬; ) HANGUL SYLLABLE PYILS
+D52D;D52D;1111 1174 11B4;D52D;1111 1174 11B4; # (픭; 픭; 픭; 픭; 픭; ) HANGUL SYLLABLE PYILT
+D52E;D52E;1111 1174 11B5;D52E;1111 1174 11B5; # (픮; 픮; 픮; 픮; 픮; ) HANGUL SYLLABLE PYILP
+D52F;D52F;1111 1174 11B6;D52F;1111 1174 11B6; # (픯; 픯; 픯; 픯; 픯; ) HANGUL SYLLABLE PYILH
+D530;D530;1111 1174 11B7;D530;1111 1174 11B7; # (픰; 픰; 픰; 픰; 픰; ) HANGUL SYLLABLE PYIM
+D531;D531;1111 1174 11B8;D531;1111 1174 11B8; # (픱; 픱; 픱; 픱; 픱; ) HANGUL SYLLABLE PYIB
+D532;D532;1111 1174 11B9;D532;1111 1174 11B9; # (픲; 픲; 픲; 픲; 픲; ) HANGUL SYLLABLE PYIBS
+D533;D533;1111 1174 11BA;D533;1111 1174 11BA; # (픳; 픳; 픳; 픳; 픳; ) HANGUL SYLLABLE PYIS
+D534;D534;1111 1174 11BB;D534;1111 1174 11BB; # (픴; 픴; 픴; 픴; 픴; ) HANGUL SYLLABLE PYISS
+D535;D535;1111 1174 11BC;D535;1111 1174 11BC; # (픵; 픵; 픵; 픵; 픵; ) HANGUL SYLLABLE PYING
+D536;D536;1111 1174 11BD;D536;1111 1174 11BD; # (픶; 픶; 픶; 픶; 픶; ) HANGUL SYLLABLE PYIJ
+D537;D537;1111 1174 11BE;D537;1111 1174 11BE; # (픷; 픷; 픷; 픷; 픷; ) HANGUL SYLLABLE PYIC
+D538;D538;1111 1174 11BF;D538;1111 1174 11BF; # (픸; 픸; 픸; 픸; 픸; ) HANGUL SYLLABLE PYIK
+D539;D539;1111 1174 11C0;D539;1111 1174 11C0; # (픹; 픹; 픹; 픹; 픹; ) HANGUL SYLLABLE PYIT
+D53A;D53A;1111 1174 11C1;D53A;1111 1174 11C1; # (픺; 픺; 픺; 픺; 픺; ) HANGUL SYLLABLE PYIP
+D53B;D53B;1111 1174 11C2;D53B;1111 1174 11C2; # (픻; 픻; 픻; 픻; 픻; ) HANGUL SYLLABLE PYIH
+D53C;D53C;1111 1175;D53C;1111 1175; # (피; 피; 피; 피; 피; ) HANGUL SYLLABLE PI
+D53D;D53D;1111 1175 11A8;D53D;1111 1175 11A8; # (픽; 픽; 픽; 픽; 픽; ) HANGUL SYLLABLE PIG
+D53E;D53E;1111 1175 11A9;D53E;1111 1175 11A9; # (픾; 픾; 픾; 픾; 픾; ) HANGUL SYLLABLE PIGG
+D53F;D53F;1111 1175 11AA;D53F;1111 1175 11AA; # (픿; 픿; 픿; 픿; 픿; ) HANGUL SYLLABLE PIGS
+D540;D540;1111 1175 11AB;D540;1111 1175 11AB; # (핀; 핀; 핀; 핀; 핀; ) HANGUL SYLLABLE PIN
+D541;D541;1111 1175 11AC;D541;1111 1175 11AC; # (핁; 핁; 핁; 핁; 핁; ) HANGUL SYLLABLE PINJ
+D542;D542;1111 1175 11AD;D542;1111 1175 11AD; # (핂; 핂; 핂; 핂; 핂; ) HANGUL SYLLABLE PINH
+D543;D543;1111 1175 11AE;D543;1111 1175 11AE; # (핃; 핃; 핃; 핃; 핃; ) HANGUL SYLLABLE PID
+D544;D544;1111 1175 11AF;D544;1111 1175 11AF; # (필; 필; 필; 필; 필; ) HANGUL SYLLABLE PIL
+D545;D545;1111 1175 11B0;D545;1111 1175 11B0; # (핅; 핅; 핅; 핅; 핅; ) HANGUL SYLLABLE PILG
+D546;D546;1111 1175 11B1;D546;1111 1175 11B1; # (핆; 핆; 핆; 핆; 핆; ) HANGUL SYLLABLE PILM
+D547;D547;1111 1175 11B2;D547;1111 1175 11B2; # (핇; 핇; 핇; 핇; 핇; ) HANGUL SYLLABLE PILB
+D548;D548;1111 1175 11B3;D548;1111 1175 11B3; # (핈; 핈; 핈; 핈; 핈; ) HANGUL SYLLABLE PILS
+D549;D549;1111 1175 11B4;D549;1111 1175 11B4; # (핉; 핉; 핉; 핉; 핉; ) HANGUL SYLLABLE PILT
+D54A;D54A;1111 1175 11B5;D54A;1111 1175 11B5; # (핊; 핊; 핊; 핊; 핊; ) HANGUL SYLLABLE PILP
+D54B;D54B;1111 1175 11B6;D54B;1111 1175 11B6; # (핋; 핋; 핋; 핋; 핋; ) HANGUL SYLLABLE PILH
+D54C;D54C;1111 1175 11B7;D54C;1111 1175 11B7; # (핌; 핌; 핌; 핌; 핌; ) HANGUL SYLLABLE PIM
+D54D;D54D;1111 1175 11B8;D54D;1111 1175 11B8; # (핍; 핍; 핍; 핍; 핍; ) HANGUL SYLLABLE PIB
+D54E;D54E;1111 1175 11B9;D54E;1111 1175 11B9; # (핎; 핎; 핎; 핎; 핎; ) HANGUL SYLLABLE PIBS
+D54F;D54F;1111 1175 11BA;D54F;1111 1175 11BA; # (핏; 핏; 핏; 핏; 핏; ) HANGUL SYLLABLE PIS
+D550;D550;1111 1175 11BB;D550;1111 1175 11BB; # (핐; 핐; 핐; 핐; 핐; ) HANGUL SYLLABLE PISS
+D551;D551;1111 1175 11BC;D551;1111 1175 11BC; # (핑; 핑; 핑; 핑; 핑; ) HANGUL SYLLABLE PING
+D552;D552;1111 1175 11BD;D552;1111 1175 11BD; # (핒; 핒; 핒; 핒; 핒; ) HANGUL SYLLABLE PIJ
+D553;D553;1111 1175 11BE;D553;1111 1175 11BE; # (핓; 핓; 핓; 핓; 핓; ) HANGUL SYLLABLE PIC
+D554;D554;1111 1175 11BF;D554;1111 1175 11BF; # (핔; 핔; 핔; 핔; 핔; ) HANGUL SYLLABLE PIK
+D555;D555;1111 1175 11C0;D555;1111 1175 11C0; # (핕; 핕; 핕; 핕; 핕; ) HANGUL SYLLABLE PIT
+D556;D556;1111 1175 11C1;D556;1111 1175 11C1; # (핖; 핖; 핖; 핖; 핖; ) HANGUL SYLLABLE PIP
+D557;D557;1111 1175 11C2;D557;1111 1175 11C2; # (핗; 핗; 핗; 핗; 핗; ) HANGUL SYLLABLE PIH
+D558;D558;1112 1161;D558;1112 1161; # (하; 하; 하; 하; 하; ) HANGUL SYLLABLE HA
+D559;D559;1112 1161 11A8;D559;1112 1161 11A8; # (학; 학; 학; 학; 학; ) HANGUL SYLLABLE HAG
+D55A;D55A;1112 1161 11A9;D55A;1112 1161 11A9; # (핚; 핚; 핚; 핚; 핚; ) HANGUL SYLLABLE HAGG
+D55B;D55B;1112 1161 11AA;D55B;1112 1161 11AA; # (핛; 핛; 핛; 핛; 핛; ) HANGUL SYLLABLE HAGS
+D55C;D55C;1112 1161 11AB;D55C;1112 1161 11AB; # (한; 한; 한; 한; 한; ) HANGUL SYLLABLE HAN
+D55D;D55D;1112 1161 11AC;D55D;1112 1161 11AC; # (핝; 핝; 핝; 핝; 핝; ) HANGUL SYLLABLE HANJ
+D55E;D55E;1112 1161 11AD;D55E;1112 1161 11AD; # (핞; 핞; 핞; 핞; 핞; ) HANGUL SYLLABLE HANH
+D55F;D55F;1112 1161 11AE;D55F;1112 1161 11AE; # (핟; 핟; 핟; 핟; 핟; ) HANGUL SYLLABLE HAD
+D560;D560;1112 1161 11AF;D560;1112 1161 11AF; # (할; 할; 할; 할; 할; ) HANGUL SYLLABLE HAL
+D561;D561;1112 1161 11B0;D561;1112 1161 11B0; # (핡; 핡; 핡; 핡; 핡; ) HANGUL SYLLABLE HALG
+D562;D562;1112 1161 11B1;D562;1112 1161 11B1; # (핢; 핢; 핢; 핢; 핢; ) HANGUL SYLLABLE HALM
+D563;D563;1112 1161 11B2;D563;1112 1161 11B2; # (핣; 핣; 핣; 핣; 핣; ) HANGUL SYLLABLE HALB
+D564;D564;1112 1161 11B3;D564;1112 1161 11B3; # (핤; 핤; 핤; 핤; 핤; ) HANGUL SYLLABLE HALS
+D565;D565;1112 1161 11B4;D565;1112 1161 11B4; # (핥; 핥; 핥; 핥; 핥; ) HANGUL SYLLABLE HALT
+D566;D566;1112 1161 11B5;D566;1112 1161 11B5; # (핦; 핦; 핦; 핦; 핦; ) HANGUL SYLLABLE HALP
+D567;D567;1112 1161 11B6;D567;1112 1161 11B6; # (핧; 핧; 핧; 핧; 핧; ) HANGUL SYLLABLE HALH
+D568;D568;1112 1161 11B7;D568;1112 1161 11B7; # (함; 함; 함; 함; 함; ) HANGUL SYLLABLE HAM
+D569;D569;1112 1161 11B8;D569;1112 1161 11B8; # (합; 합; 합; 합; 합; ) HANGUL SYLLABLE HAB
+D56A;D56A;1112 1161 11B9;D56A;1112 1161 11B9; # (핪; 핪; 핪; 핪; 핪; ) HANGUL SYLLABLE HABS
+D56B;D56B;1112 1161 11BA;D56B;1112 1161 11BA; # (핫; 핫; 핫; 핫; 핫; ) HANGUL SYLLABLE HAS
+D56C;D56C;1112 1161 11BB;D56C;1112 1161 11BB; # (핬; 핬; 핬; 핬; 핬; ) HANGUL SYLLABLE HASS
+D56D;D56D;1112 1161 11BC;D56D;1112 1161 11BC; # (항; 항; 항; 항; 항; ) HANGUL SYLLABLE HANG
+D56E;D56E;1112 1161 11BD;D56E;1112 1161 11BD; # (핮; 핮; 핮; 핮; 핮; ) HANGUL SYLLABLE HAJ
+D56F;D56F;1112 1161 11BE;D56F;1112 1161 11BE; # (핯; 핯; 핯; 핯; 핯; ) HANGUL SYLLABLE HAC
+D570;D570;1112 1161 11BF;D570;1112 1161 11BF; # (핰; 핰; 핰; 핰; 핰; ) HANGUL SYLLABLE HAK
+D571;D571;1112 1161 11C0;D571;1112 1161 11C0; # (핱; 핱; 핱; 핱; 핱; ) HANGUL SYLLABLE HAT
+D572;D572;1112 1161 11C1;D572;1112 1161 11C1; # (핲; 핲; 핲; 핲; 핲; ) HANGUL SYLLABLE HAP
+D573;D573;1112 1161 11C2;D573;1112 1161 11C2; # (핳; 핳; 핳; 핳; 핳; ) HANGUL SYLLABLE HAH
+D574;D574;1112 1162;D574;1112 1162; # (해; 해; 해; 해; 해; ) HANGUL SYLLABLE HAE
+D575;D575;1112 1162 11A8;D575;1112 1162 11A8; # (핵; 핵; 핵; 핵; 핵; ) HANGUL SYLLABLE HAEG
+D576;D576;1112 1162 11A9;D576;1112 1162 11A9; # (핶; 핶; 핶; 핶; 핶; ) HANGUL SYLLABLE HAEGG
+D577;D577;1112 1162 11AA;D577;1112 1162 11AA; # (핷; 핷; 핷; 핷; 핷; ) HANGUL SYLLABLE HAEGS
+D578;D578;1112 1162 11AB;D578;1112 1162 11AB; # (핸; 핸; 핸; 핸; 핸; ) HANGUL SYLLABLE HAEN
+D579;D579;1112 1162 11AC;D579;1112 1162 11AC; # (핹; 핹; 핹; 핹; 핹; ) HANGUL SYLLABLE HAENJ
+D57A;D57A;1112 1162 11AD;D57A;1112 1162 11AD; # (핺; 핺; 핺; 핺; 핺; ) HANGUL SYLLABLE HAENH
+D57B;D57B;1112 1162 11AE;D57B;1112 1162 11AE; # (핻; 핻; 핻; 핻; 핻; ) HANGUL SYLLABLE HAED
+D57C;D57C;1112 1162 11AF;D57C;1112 1162 11AF; # (핼; 핼; 핼; 핼; 핼; ) HANGUL SYLLABLE HAEL
+D57D;D57D;1112 1162 11B0;D57D;1112 1162 11B0; # (핽; 핽; 핽; 핽; 핽; ) HANGUL SYLLABLE HAELG
+D57E;D57E;1112 1162 11B1;D57E;1112 1162 11B1; # (핾; 핾; 핾; 핾; 핾; ) HANGUL SYLLABLE HAELM
+D57F;D57F;1112 1162 11B2;D57F;1112 1162 11B2; # (핿; 핿; 핿; 핿; 핿; ) HANGUL SYLLABLE HAELB
+D580;D580;1112 1162 11B3;D580;1112 1162 11B3; # (햀; 햀; 햀; 햀; 햀; ) HANGUL SYLLABLE HAELS
+D581;D581;1112 1162 11B4;D581;1112 1162 11B4; # (햁; 햁; 햁; 햁; 햁; ) HANGUL SYLLABLE HAELT
+D582;D582;1112 1162 11B5;D582;1112 1162 11B5; # (햂; 햂; 햂; 햂; 햂; ) HANGUL SYLLABLE HAELP
+D583;D583;1112 1162 11B6;D583;1112 1162 11B6; # (햃; 햃; 햃; 햃; 햃; ) HANGUL SYLLABLE HAELH
+D584;D584;1112 1162 11B7;D584;1112 1162 11B7; # (햄; 햄; 햄; 햄; 햄; ) HANGUL SYLLABLE HAEM
+D585;D585;1112 1162 11B8;D585;1112 1162 11B8; # (햅; 햅; 햅; 햅; 햅; ) HANGUL SYLLABLE HAEB
+D586;D586;1112 1162 11B9;D586;1112 1162 11B9; # (햆; 햆; 햆; 햆; 햆; ) HANGUL SYLLABLE HAEBS
+D587;D587;1112 1162 11BA;D587;1112 1162 11BA; # (햇; 햇; 햇; 햇; 햇; ) HANGUL SYLLABLE HAES
+D588;D588;1112 1162 11BB;D588;1112 1162 11BB; # (했; 했; 했; 했; 했; ) HANGUL SYLLABLE HAESS
+D589;D589;1112 1162 11BC;D589;1112 1162 11BC; # (행; 행; 행; 행; 행; ) HANGUL SYLLABLE HAENG
+D58A;D58A;1112 1162 11BD;D58A;1112 1162 11BD; # (햊; 햊; 햊; 햊; 햊; ) HANGUL SYLLABLE HAEJ
+D58B;D58B;1112 1162 11BE;D58B;1112 1162 11BE; # (햋; 햋; 햋; 햋; 햋; ) HANGUL SYLLABLE HAEC
+D58C;D58C;1112 1162 11BF;D58C;1112 1162 11BF; # (햌; 햌; 햌; 햌; 햌; ) HANGUL SYLLABLE HAEK
+D58D;D58D;1112 1162 11C0;D58D;1112 1162 11C0; # (햍; 햍; 햍; 햍; 햍; ) HANGUL SYLLABLE HAET
+D58E;D58E;1112 1162 11C1;D58E;1112 1162 11C1; # (햎; 햎; 햎; 햎; 햎; ) HANGUL SYLLABLE HAEP
+D58F;D58F;1112 1162 11C2;D58F;1112 1162 11C2; # (햏; 햏; 햏; 햏; 햏; ) HANGUL SYLLABLE HAEH
+D590;D590;1112 1163;D590;1112 1163; # (햐; 햐; 햐; 햐; 햐; ) HANGUL SYLLABLE HYA
+D591;D591;1112 1163 11A8;D591;1112 1163 11A8; # (햑; 햑; 햑; 햑; 햑; ) HANGUL SYLLABLE HYAG
+D592;D592;1112 1163 11A9;D592;1112 1163 11A9; # (햒; 햒; 햒; 햒; 햒; ) HANGUL SYLLABLE HYAGG
+D593;D593;1112 1163 11AA;D593;1112 1163 11AA; # (햓; 햓; 햓; 햓; 햓; ) HANGUL SYLLABLE HYAGS
+D594;D594;1112 1163 11AB;D594;1112 1163 11AB; # (햔; 햔; 햔; 햔; 햔; ) HANGUL SYLLABLE HYAN
+D595;D595;1112 1163 11AC;D595;1112 1163 11AC; # (햕; 햕; 햕; 햕; 햕; ) HANGUL SYLLABLE HYANJ
+D596;D596;1112 1163 11AD;D596;1112 1163 11AD; # (햖; 햖; 햖; 햖; 햖; ) HANGUL SYLLABLE HYANH
+D597;D597;1112 1163 11AE;D597;1112 1163 11AE; # (햗; 햗; 햗; 햗; 햗; ) HANGUL SYLLABLE HYAD
+D598;D598;1112 1163 11AF;D598;1112 1163 11AF; # (햘; 햘; 햘; 햘; 햘; ) HANGUL SYLLABLE HYAL
+D599;D599;1112 1163 11B0;D599;1112 1163 11B0; # (햙; 햙; 햙; 햙; 햙; ) HANGUL SYLLABLE HYALG
+D59A;D59A;1112 1163 11B1;D59A;1112 1163 11B1; # (햚; 햚; 햚; 햚; 햚; ) HANGUL SYLLABLE HYALM
+D59B;D59B;1112 1163 11B2;D59B;1112 1163 11B2; # (햛; 햛; 햛; 햛; 햛; ) HANGUL SYLLABLE HYALB
+D59C;D59C;1112 1163 11B3;D59C;1112 1163 11B3; # (햜; 햜; 햜; 햜; 햜; ) HANGUL SYLLABLE HYALS
+D59D;D59D;1112 1163 11B4;D59D;1112 1163 11B4; # (햝; 햝; 햝; 햝; 햝; ) HANGUL SYLLABLE HYALT
+D59E;D59E;1112 1163 11B5;D59E;1112 1163 11B5; # (햞; 햞; 햞; 햞; 햞; ) HANGUL SYLLABLE HYALP
+D59F;D59F;1112 1163 11B6;D59F;1112 1163 11B6; # (햟; 햟; 햟; 햟; 햟; ) HANGUL SYLLABLE HYALH
+D5A0;D5A0;1112 1163 11B7;D5A0;1112 1163 11B7; # (햠; 햠; 햠; 햠; 햠; ) HANGUL SYLLABLE HYAM
+D5A1;D5A1;1112 1163 11B8;D5A1;1112 1163 11B8; # (햡; 햡; 햡; 햡; 햡; ) HANGUL SYLLABLE HYAB
+D5A2;D5A2;1112 1163 11B9;D5A2;1112 1163 11B9; # (햢; 햢; 햢; 햢; 햢; ) HANGUL SYLLABLE HYABS
+D5A3;D5A3;1112 1163 11BA;D5A3;1112 1163 11BA; # (햣; 햣; 햣; 햣; 햣; ) HANGUL SYLLABLE HYAS
+D5A4;D5A4;1112 1163 11BB;D5A4;1112 1163 11BB; # (햤; 햤; 햤; 햤; 햤; ) HANGUL SYLLABLE HYASS
+D5A5;D5A5;1112 1163 11BC;D5A5;1112 1163 11BC; # (향; 향; 향; 향; 향; ) HANGUL SYLLABLE HYANG
+D5A6;D5A6;1112 1163 11BD;D5A6;1112 1163 11BD; # (햦; 햦; 햦; 햦; 햦; ) HANGUL SYLLABLE HYAJ
+D5A7;D5A7;1112 1163 11BE;D5A7;1112 1163 11BE; # (햧; 햧; 햧; 햧; 햧; ) HANGUL SYLLABLE HYAC
+D5A8;D5A8;1112 1163 11BF;D5A8;1112 1163 11BF; # (햨; 햨; 햨; 햨; 햨; ) HANGUL SYLLABLE HYAK
+D5A9;D5A9;1112 1163 11C0;D5A9;1112 1163 11C0; # (햩; 햩; 햩; 햩; 햩; ) HANGUL SYLLABLE HYAT
+D5AA;D5AA;1112 1163 11C1;D5AA;1112 1163 11C1; # (햪; 햪; 햪; 햪; 햪; ) HANGUL SYLLABLE HYAP
+D5AB;D5AB;1112 1163 11C2;D5AB;1112 1163 11C2; # (햫; 햫; 햫; 햫; 햫; ) HANGUL SYLLABLE HYAH
+D5AC;D5AC;1112 1164;D5AC;1112 1164; # (햬; 햬; 햬; 햬; 햬; ) HANGUL SYLLABLE HYAE
+D5AD;D5AD;1112 1164 11A8;D5AD;1112 1164 11A8; # (햭; 햭; 햭; 햭; 햭; ) HANGUL SYLLABLE HYAEG
+D5AE;D5AE;1112 1164 11A9;D5AE;1112 1164 11A9; # (햮; 햮; 햮; 햮; 햮; ) HANGUL SYLLABLE HYAEGG
+D5AF;D5AF;1112 1164 11AA;D5AF;1112 1164 11AA; # (햯; 햯; 햯; 햯; 햯; ) HANGUL SYLLABLE HYAEGS
+D5B0;D5B0;1112 1164 11AB;D5B0;1112 1164 11AB; # (햰; 햰; 햰; 햰; 햰; ) HANGUL SYLLABLE HYAEN
+D5B1;D5B1;1112 1164 11AC;D5B1;1112 1164 11AC; # (햱; 햱; 햱; 햱; 햱; ) HANGUL SYLLABLE HYAENJ
+D5B2;D5B2;1112 1164 11AD;D5B2;1112 1164 11AD; # (햲; 햲; 햲; 햲; 햲; ) HANGUL SYLLABLE HYAENH
+D5B3;D5B3;1112 1164 11AE;D5B3;1112 1164 11AE; # (햳; 햳; 햳; 햳; 햳; ) HANGUL SYLLABLE HYAED
+D5B4;D5B4;1112 1164 11AF;D5B4;1112 1164 11AF; # (햴; 햴; 햴; 햴; 햴; ) HANGUL SYLLABLE HYAEL
+D5B5;D5B5;1112 1164 11B0;D5B5;1112 1164 11B0; # (햵; 햵; 햵; 햵; 햵; ) HANGUL SYLLABLE HYAELG
+D5B6;D5B6;1112 1164 11B1;D5B6;1112 1164 11B1; # (햶; 햶; 햶; 햶; 햶; ) HANGUL SYLLABLE HYAELM
+D5B7;D5B7;1112 1164 11B2;D5B7;1112 1164 11B2; # (햷; 햷; 햷; 햷; 햷; ) HANGUL SYLLABLE HYAELB
+D5B8;D5B8;1112 1164 11B3;D5B8;1112 1164 11B3; # (햸; 햸; 햸; 햸; 햸; ) HANGUL SYLLABLE HYAELS
+D5B9;D5B9;1112 1164 11B4;D5B9;1112 1164 11B4; # (햹; 햹; 햹; 햹; 햹; ) HANGUL SYLLABLE HYAELT
+D5BA;D5BA;1112 1164 11B5;D5BA;1112 1164 11B5; # (햺; 햺; 햺; 햺; 햺; ) HANGUL SYLLABLE HYAELP
+D5BB;D5BB;1112 1164 11B6;D5BB;1112 1164 11B6; # (햻; 햻; 햻; 햻; 햻; ) HANGUL SYLLABLE HYAELH
+D5BC;D5BC;1112 1164 11B7;D5BC;1112 1164 11B7; # (햼; 햼; 햼; 햼; 햼; ) HANGUL SYLLABLE HYAEM
+D5BD;D5BD;1112 1164 11B8;D5BD;1112 1164 11B8; # (햽; 햽; 햽; 햽; 햽; ) HANGUL SYLLABLE HYAEB
+D5BE;D5BE;1112 1164 11B9;D5BE;1112 1164 11B9; # (햾; 햾; 햾; 햾; 햾; ) HANGUL SYLLABLE HYAEBS
+D5BF;D5BF;1112 1164 11BA;D5BF;1112 1164 11BA; # (햿; 햿; 햿; 햿; 햿; ) HANGUL SYLLABLE HYAES
+D5C0;D5C0;1112 1164 11BB;D5C0;1112 1164 11BB; # (헀; 헀; 헀; 헀; 헀; ) HANGUL SYLLABLE HYAESS
+D5C1;D5C1;1112 1164 11BC;D5C1;1112 1164 11BC; # (헁; 헁; 헁; 헁; 헁; ) HANGUL SYLLABLE HYAENG
+D5C2;D5C2;1112 1164 11BD;D5C2;1112 1164 11BD; # (헂; 헂; 헂; 헂; 헂; ) HANGUL SYLLABLE HYAEJ
+D5C3;D5C3;1112 1164 11BE;D5C3;1112 1164 11BE; # (헃; 헃; 헃; 헃; 헃; ) HANGUL SYLLABLE HYAEC
+D5C4;D5C4;1112 1164 11BF;D5C4;1112 1164 11BF; # (헄; 헄; 헄; 헄; 헄; ) HANGUL SYLLABLE HYAEK
+D5C5;D5C5;1112 1164 11C0;D5C5;1112 1164 11C0; # (헅; 헅; 헅; 헅; 헅; ) HANGUL SYLLABLE HYAET
+D5C6;D5C6;1112 1164 11C1;D5C6;1112 1164 11C1; # (헆; 헆; 헆; 헆; 헆; ) HANGUL SYLLABLE HYAEP
+D5C7;D5C7;1112 1164 11C2;D5C7;1112 1164 11C2; # (헇; 헇; 헇; 헇; 헇; ) HANGUL SYLLABLE HYAEH
+D5C8;D5C8;1112 1165;D5C8;1112 1165; # (허; 허; 허; 허; 허; ) HANGUL SYLLABLE HEO
+D5C9;D5C9;1112 1165 11A8;D5C9;1112 1165 11A8; # (헉; 헉; 헉; 헉; 헉; ) HANGUL SYLLABLE HEOG
+D5CA;D5CA;1112 1165 11A9;D5CA;1112 1165 11A9; # (헊; 헊; 헊; 헊; 헊; ) HANGUL SYLLABLE HEOGG
+D5CB;D5CB;1112 1165 11AA;D5CB;1112 1165 11AA; # (헋; 헋; 헋; 헋; 헋; ) HANGUL SYLLABLE HEOGS
+D5CC;D5CC;1112 1165 11AB;D5CC;1112 1165 11AB; # (헌; 헌; 헌; 헌; 헌; ) HANGUL SYLLABLE HEON
+D5CD;D5CD;1112 1165 11AC;D5CD;1112 1165 11AC; # (헍; 헍; 헍; 헍; 헍; ) HANGUL SYLLABLE HEONJ
+D5CE;D5CE;1112 1165 11AD;D5CE;1112 1165 11AD; # (헎; 헎; 헎; 헎; 헎; ) HANGUL SYLLABLE HEONH
+D5CF;D5CF;1112 1165 11AE;D5CF;1112 1165 11AE; # (헏; 헏; 헏; 헏; 헏; ) HANGUL SYLLABLE HEOD
+D5D0;D5D0;1112 1165 11AF;D5D0;1112 1165 11AF; # (헐; 헐; 헐; 헐; 헐; ) HANGUL SYLLABLE HEOL
+D5D1;D5D1;1112 1165 11B0;D5D1;1112 1165 11B0; # (헑; 헑; 헑; 헑; 헑; ) HANGUL SYLLABLE HEOLG
+D5D2;D5D2;1112 1165 11B1;D5D2;1112 1165 11B1; # (헒; 헒; 헒; 헒; 헒; ) HANGUL SYLLABLE HEOLM
+D5D3;D5D3;1112 1165 11B2;D5D3;1112 1165 11B2; # (헓; 헓; 헓; 헓; 헓; ) HANGUL SYLLABLE HEOLB
+D5D4;D5D4;1112 1165 11B3;D5D4;1112 1165 11B3; # (헔; 헔; 헔; 헔; 헔; ) HANGUL SYLLABLE HEOLS
+D5D5;D5D5;1112 1165 11B4;D5D5;1112 1165 11B4; # (헕; 헕; 헕; 헕; 헕; ) HANGUL SYLLABLE HEOLT
+D5D6;D5D6;1112 1165 11B5;D5D6;1112 1165 11B5; # (헖; 헖; 헖; 헖; 헖; ) HANGUL SYLLABLE HEOLP
+D5D7;D5D7;1112 1165 11B6;D5D7;1112 1165 11B6; # (헗; 헗; 헗; 헗; 헗; ) HANGUL SYLLABLE HEOLH
+D5D8;D5D8;1112 1165 11B7;D5D8;1112 1165 11B7; # (험; 험; 험; 험; 험; ) HANGUL SYLLABLE HEOM
+D5D9;D5D9;1112 1165 11B8;D5D9;1112 1165 11B8; # (헙; 헙; 헙; 헙; 헙; ) HANGUL SYLLABLE HEOB
+D5DA;D5DA;1112 1165 11B9;D5DA;1112 1165 11B9; # (헚; 헚; 헚; 헚; 헚; ) HANGUL SYLLABLE HEOBS
+D5DB;D5DB;1112 1165 11BA;D5DB;1112 1165 11BA; # (헛; 헛; 헛; 헛; 헛; ) HANGUL SYLLABLE HEOS
+D5DC;D5DC;1112 1165 11BB;D5DC;1112 1165 11BB; # (헜; 헜; 헜; 헜; 헜; ) HANGUL SYLLABLE HEOSS
+D5DD;D5DD;1112 1165 11BC;D5DD;1112 1165 11BC; # (헝; 헝; 헝; 헝; 헝; ) HANGUL SYLLABLE HEONG
+D5DE;D5DE;1112 1165 11BD;D5DE;1112 1165 11BD; # (헞; 헞; 헞; 헞; 헞; ) HANGUL SYLLABLE HEOJ
+D5DF;D5DF;1112 1165 11BE;D5DF;1112 1165 11BE; # (헟; 헟; 헟; 헟; 헟; ) HANGUL SYLLABLE HEOC
+D5E0;D5E0;1112 1165 11BF;D5E0;1112 1165 11BF; # (헠; 헠; 헠; 헠; 헠; ) HANGUL SYLLABLE HEOK
+D5E1;D5E1;1112 1165 11C0;D5E1;1112 1165 11C0; # (헡; 헡; 헡; 헡; 헡; ) HANGUL SYLLABLE HEOT
+D5E2;D5E2;1112 1165 11C1;D5E2;1112 1165 11C1; # (헢; 헢; 헢; 헢; 헢; ) HANGUL SYLLABLE HEOP
+D5E3;D5E3;1112 1165 11C2;D5E3;1112 1165 11C2; # (헣; 헣; 헣; 헣; 헣; ) HANGUL SYLLABLE HEOH
+D5E4;D5E4;1112 1166;D5E4;1112 1166; # (헤; 헤; 헤; 헤; 헤; ) HANGUL SYLLABLE HE
+D5E5;D5E5;1112 1166 11A8;D5E5;1112 1166 11A8; # (헥; 헥; 헥; 헥; 헥; ) HANGUL SYLLABLE HEG
+D5E6;D5E6;1112 1166 11A9;D5E6;1112 1166 11A9; # (헦; 헦; 헦; 헦; 헦; ) HANGUL SYLLABLE HEGG
+D5E7;D5E7;1112 1166 11AA;D5E7;1112 1166 11AA; # (헧; 헧; 헧; 헧; 헧; ) HANGUL SYLLABLE HEGS
+D5E8;D5E8;1112 1166 11AB;D5E8;1112 1166 11AB; # (헨; 헨; 헨; 헨; 헨; ) HANGUL SYLLABLE HEN
+D5E9;D5E9;1112 1166 11AC;D5E9;1112 1166 11AC; # (헩; 헩; 헩; 헩; 헩; ) HANGUL SYLLABLE HENJ
+D5EA;D5EA;1112 1166 11AD;D5EA;1112 1166 11AD; # (헪; 헪; 헪; 헪; 헪; ) HANGUL SYLLABLE HENH
+D5EB;D5EB;1112 1166 11AE;D5EB;1112 1166 11AE; # (헫; 헫; 헫; 헫; 헫; ) HANGUL SYLLABLE HED
+D5EC;D5EC;1112 1166 11AF;D5EC;1112 1166 11AF; # (헬; 헬; 헬; 헬; 헬; ) HANGUL SYLLABLE HEL
+D5ED;D5ED;1112 1166 11B0;D5ED;1112 1166 11B0; # (헭; 헭; 헭; 헭; 헭; ) HANGUL SYLLABLE HELG
+D5EE;D5EE;1112 1166 11B1;D5EE;1112 1166 11B1; # (헮; 헮; 헮; 헮; 헮; ) HANGUL SYLLABLE HELM
+D5EF;D5EF;1112 1166 11B2;D5EF;1112 1166 11B2; # (헯; 헯; 헯; 헯; 헯; ) HANGUL SYLLABLE HELB
+D5F0;D5F0;1112 1166 11B3;D5F0;1112 1166 11B3; # (헰; 헰; 헰; 헰; 헰; ) HANGUL SYLLABLE HELS
+D5F1;D5F1;1112 1166 11B4;D5F1;1112 1166 11B4; # (헱; 헱; 헱; 헱; 헱; ) HANGUL SYLLABLE HELT
+D5F2;D5F2;1112 1166 11B5;D5F2;1112 1166 11B5; # (헲; 헲; 헲; 헲; 헲; ) HANGUL SYLLABLE HELP
+D5F3;D5F3;1112 1166 11B6;D5F3;1112 1166 11B6; # (헳; 헳; 헳; 헳; 헳; ) HANGUL SYLLABLE HELH
+D5F4;D5F4;1112 1166 11B7;D5F4;1112 1166 11B7; # (헴; 헴; 헴; 헴; 헴; ) HANGUL SYLLABLE HEM
+D5F5;D5F5;1112 1166 11B8;D5F5;1112 1166 11B8; # (헵; 헵; 헵; 헵; 헵; ) HANGUL SYLLABLE HEB
+D5F6;D5F6;1112 1166 11B9;D5F6;1112 1166 11B9; # (헶; 헶; 헶; 헶; 헶; ) HANGUL SYLLABLE HEBS
+D5F7;D5F7;1112 1166 11BA;D5F7;1112 1166 11BA; # (헷; 헷; 헷; 헷; 헷; ) HANGUL SYLLABLE HES
+D5F8;D5F8;1112 1166 11BB;D5F8;1112 1166 11BB; # (헸; 헸; 헸; 헸; 헸; ) HANGUL SYLLABLE HESS
+D5F9;D5F9;1112 1166 11BC;D5F9;1112 1166 11BC; # (헹; 헹; 헹; 헹; 헹; ) HANGUL SYLLABLE HENG
+D5FA;D5FA;1112 1166 11BD;D5FA;1112 1166 11BD; # (헺; 헺; 헺; 헺; 헺; ) HANGUL SYLLABLE HEJ
+D5FB;D5FB;1112 1166 11BE;D5FB;1112 1166 11BE; # (헻; 헻; 헻; 헻; 헻; ) HANGUL SYLLABLE HEC
+D5FC;D5FC;1112 1166 11BF;D5FC;1112 1166 11BF; # (헼; 헼; 헼; 헼; 헼; ) HANGUL SYLLABLE HEK
+D5FD;D5FD;1112 1166 11C0;D5FD;1112 1166 11C0; # (헽; 헽; 헽; 헽; 헽; ) HANGUL SYLLABLE HET
+D5FE;D5FE;1112 1166 11C1;D5FE;1112 1166 11C1; # (헾; 헾; 헾; 헾; 헾; ) HANGUL SYLLABLE HEP
+D5FF;D5FF;1112 1166 11C2;D5FF;1112 1166 11C2; # (헿; 헿; 헿; 헿; 헿; ) HANGUL SYLLABLE HEH
+D600;D600;1112 1167;D600;1112 1167; # (혀; 혀; 혀; 혀; 혀; ) HANGUL SYLLABLE HYEO
+D601;D601;1112 1167 11A8;D601;1112 1167 11A8; # (혁; 혁; 혁; 혁; 혁; ) HANGUL SYLLABLE HYEOG
+D602;D602;1112 1167 11A9;D602;1112 1167 11A9; # (혂; 혂; 혂; 혂; 혂; ) HANGUL SYLLABLE HYEOGG
+D603;D603;1112 1167 11AA;D603;1112 1167 11AA; # (혃; 혃; 혃; 혃; 혃; ) HANGUL SYLLABLE HYEOGS
+D604;D604;1112 1167 11AB;D604;1112 1167 11AB; # (현; 현; 현; 현; 현; ) HANGUL SYLLABLE HYEON
+D605;D605;1112 1167 11AC;D605;1112 1167 11AC; # (혅; 혅; 혅; 혅; 혅; ) HANGUL SYLLABLE HYEONJ
+D606;D606;1112 1167 11AD;D606;1112 1167 11AD; # (혆; 혆; 혆; 혆; 혆; ) HANGUL SYLLABLE HYEONH
+D607;D607;1112 1167 11AE;D607;1112 1167 11AE; # (혇; 혇; 혇; 혇; 혇; ) HANGUL SYLLABLE HYEOD
+D608;D608;1112 1167 11AF;D608;1112 1167 11AF; # (혈; 혈; 혈; 혈; 혈; ) HANGUL SYLLABLE HYEOL
+D609;D609;1112 1167 11B0;D609;1112 1167 11B0; # (혉; 혉; 혉; 혉; 혉; ) HANGUL SYLLABLE HYEOLG
+D60A;D60A;1112 1167 11B1;D60A;1112 1167 11B1; # (혊; 혊; 혊; 혊; 혊; ) HANGUL SYLLABLE HYEOLM
+D60B;D60B;1112 1167 11B2;D60B;1112 1167 11B2; # (혋; 혋; 혋; 혋; 혋; ) HANGUL SYLLABLE HYEOLB
+D60C;D60C;1112 1167 11B3;D60C;1112 1167 11B3; # (혌; 혌; 혌; 혌; 혌; ) HANGUL SYLLABLE HYEOLS
+D60D;D60D;1112 1167 11B4;D60D;1112 1167 11B4; # (혍; 혍; 혍; 혍; 혍; ) HANGUL SYLLABLE HYEOLT
+D60E;D60E;1112 1167 11B5;D60E;1112 1167 11B5; # (혎; 혎; 혎; 혎; 혎; ) HANGUL SYLLABLE HYEOLP
+D60F;D60F;1112 1167 11B6;D60F;1112 1167 11B6; # (혏; 혏; 혏; 혏; 혏; ) HANGUL SYLLABLE HYEOLH
+D610;D610;1112 1167 11B7;D610;1112 1167 11B7; # (혐; 혐; 혐; 혐; 혐; ) HANGUL SYLLABLE HYEOM
+D611;D611;1112 1167 11B8;D611;1112 1167 11B8; # (협; 협; 협; 협; 협; ) HANGUL SYLLABLE HYEOB
+D612;D612;1112 1167 11B9;D612;1112 1167 11B9; # (혒; 혒; 혒; 혒; 혒; ) HANGUL SYLLABLE HYEOBS
+D613;D613;1112 1167 11BA;D613;1112 1167 11BA; # (혓; 혓; 혓; 혓; 혓; ) HANGUL SYLLABLE HYEOS
+D614;D614;1112 1167 11BB;D614;1112 1167 11BB; # (혔; 혔; 혔; 혔; 혔; ) HANGUL SYLLABLE HYEOSS
+D615;D615;1112 1167 11BC;D615;1112 1167 11BC; # (형; 형; 형; 형; 형; ) HANGUL SYLLABLE HYEONG
+D616;D616;1112 1167 11BD;D616;1112 1167 11BD; # (혖; 혖; 혖; 혖; 혖; ) HANGUL SYLLABLE HYEOJ
+D617;D617;1112 1167 11BE;D617;1112 1167 11BE; # (혗; 혗; 혗; 혗; 혗; ) HANGUL SYLLABLE HYEOC
+D618;D618;1112 1167 11BF;D618;1112 1167 11BF; # (혘; 혘; 혘; 혘; 혘; ) HANGUL SYLLABLE HYEOK
+D619;D619;1112 1167 11C0;D619;1112 1167 11C0; # (혙; 혙; 혙; 혙; 혙; ) HANGUL SYLLABLE HYEOT
+D61A;D61A;1112 1167 11C1;D61A;1112 1167 11C1; # (혚; 혚; 혚; 혚; 혚; ) HANGUL SYLLABLE HYEOP
+D61B;D61B;1112 1167 11C2;D61B;1112 1167 11C2; # (혛; 혛; 혛; 혛; 혛; ) HANGUL SYLLABLE HYEOH
+D61C;D61C;1112 1168;D61C;1112 1168; # (혜; 혜; 혜; 혜; 혜; ) HANGUL SYLLABLE HYE
+D61D;D61D;1112 1168 11A8;D61D;1112 1168 11A8; # (혝; 혝; 혝; 혝; 혝; ) HANGUL SYLLABLE HYEG
+D61E;D61E;1112 1168 11A9;D61E;1112 1168 11A9; # (혞; 혞; 혞; 혞; 혞; ) HANGUL SYLLABLE HYEGG
+D61F;D61F;1112 1168 11AA;D61F;1112 1168 11AA; # (혟; 혟; 혟; 혟; 혟; ) HANGUL SYLLABLE HYEGS
+D620;D620;1112 1168 11AB;D620;1112 1168 11AB; # (혠; 혠; 혠; 혠; 혠; ) HANGUL SYLLABLE HYEN
+D621;D621;1112 1168 11AC;D621;1112 1168 11AC; # (혡; 혡; 혡; 혡; 혡; ) HANGUL SYLLABLE HYENJ
+D622;D622;1112 1168 11AD;D622;1112 1168 11AD; # (혢; 혢; 혢; 혢; 혢; ) HANGUL SYLLABLE HYENH
+D623;D623;1112 1168 11AE;D623;1112 1168 11AE; # (혣; 혣; 혣; 혣; 혣; ) HANGUL SYLLABLE HYED
+D624;D624;1112 1168 11AF;D624;1112 1168 11AF; # (혤; 혤; 혤; 혤; 혤; ) HANGUL SYLLABLE HYEL
+D625;D625;1112 1168 11B0;D625;1112 1168 11B0; # (혥; 혥; 혥; 혥; 혥; ) HANGUL SYLLABLE HYELG
+D626;D626;1112 1168 11B1;D626;1112 1168 11B1; # (혦; 혦; 혦; 혦; 혦; ) HANGUL SYLLABLE HYELM
+D627;D627;1112 1168 11B2;D627;1112 1168 11B2; # (혧; 혧; 혧; 혧; 혧; ) HANGUL SYLLABLE HYELB
+D628;D628;1112 1168 11B3;D628;1112 1168 11B3; # (혨; 혨; 혨; 혨; 혨; ) HANGUL SYLLABLE HYELS
+D629;D629;1112 1168 11B4;D629;1112 1168 11B4; # (혩; 혩; 혩; 혩; 혩; ) HANGUL SYLLABLE HYELT
+D62A;D62A;1112 1168 11B5;D62A;1112 1168 11B5; # (혪; 혪; 혪; 혪; 혪; ) HANGUL SYLLABLE HYELP
+D62B;D62B;1112 1168 11B6;D62B;1112 1168 11B6; # (혫; 혫; 혫; 혫; 혫; ) HANGUL SYLLABLE HYELH
+D62C;D62C;1112 1168 11B7;D62C;1112 1168 11B7; # (혬; 혬; 혬; 혬; 혬; ) HANGUL SYLLABLE HYEM
+D62D;D62D;1112 1168 11B8;D62D;1112 1168 11B8; # (혭; 혭; 혭; 혭; 혭; ) HANGUL SYLLABLE HYEB
+D62E;D62E;1112 1168 11B9;D62E;1112 1168 11B9; # (혮; 혮; 혮; 혮; 혮; ) HANGUL SYLLABLE HYEBS
+D62F;D62F;1112 1168 11BA;D62F;1112 1168 11BA; # (혯; 혯; 혯; 혯; 혯; ) HANGUL SYLLABLE HYES
+D630;D630;1112 1168 11BB;D630;1112 1168 11BB; # (혰; 혰; 혰; 혰; 혰; ) HANGUL SYLLABLE HYESS
+D631;D631;1112 1168 11BC;D631;1112 1168 11BC; # (혱; 혱; 혱; 혱; 혱; ) HANGUL SYLLABLE HYENG
+D632;D632;1112 1168 11BD;D632;1112 1168 11BD; # (혲; 혲; 혲; 혲; 혲; ) HANGUL SYLLABLE HYEJ
+D633;D633;1112 1168 11BE;D633;1112 1168 11BE; # (혳; 혳; 혳; 혳; 혳; ) HANGUL SYLLABLE HYEC
+D634;D634;1112 1168 11BF;D634;1112 1168 11BF; # (혴; 혴; 혴; 혴; 혴; ) HANGUL SYLLABLE HYEK
+D635;D635;1112 1168 11C0;D635;1112 1168 11C0; # (혵; 혵; 혵; 혵; 혵; ) HANGUL SYLLABLE HYET
+D636;D636;1112 1168 11C1;D636;1112 1168 11C1; # (혶; 혶; 혶; 혶; 혶; ) HANGUL SYLLABLE HYEP
+D637;D637;1112 1168 11C2;D637;1112 1168 11C2; # (혷; 혷; 혷; 혷; 혷; ) HANGUL SYLLABLE HYEH
+D638;D638;1112 1169;D638;1112 1169; # (호; 호; 호; 호; 호; ) HANGUL SYLLABLE HO
+D639;D639;1112 1169 11A8;D639;1112 1169 11A8; # (혹; 혹; 혹; 혹; 혹; ) HANGUL SYLLABLE HOG
+D63A;D63A;1112 1169 11A9;D63A;1112 1169 11A9; # (혺; 혺; 혺; 혺; 혺; ) HANGUL SYLLABLE HOGG
+D63B;D63B;1112 1169 11AA;D63B;1112 1169 11AA; # (혻; 혻; 혻; 혻; 혻; ) HANGUL SYLLABLE HOGS
+D63C;D63C;1112 1169 11AB;D63C;1112 1169 11AB; # (혼; 혼; 혼; 혼; 혼; ) HANGUL SYLLABLE HON
+D63D;D63D;1112 1169 11AC;D63D;1112 1169 11AC; # (혽; 혽; 혽; 혽; 혽; ) HANGUL SYLLABLE HONJ
+D63E;D63E;1112 1169 11AD;D63E;1112 1169 11AD; # (혾; 혾; 혾; 혾; 혾; ) HANGUL SYLLABLE HONH
+D63F;D63F;1112 1169 11AE;D63F;1112 1169 11AE; # (혿; 혿; 혿; 혿; 혿; ) HANGUL SYLLABLE HOD
+D640;D640;1112 1169 11AF;D640;1112 1169 11AF; # (홀; 홀; 홀; 홀; 홀; ) HANGUL SYLLABLE HOL
+D641;D641;1112 1169 11B0;D641;1112 1169 11B0; # (홁; 홁; 홁; 홁; 홁; ) HANGUL SYLLABLE HOLG
+D642;D642;1112 1169 11B1;D642;1112 1169 11B1; # (홂; 홂; 홂; 홂; 홂; ) HANGUL SYLLABLE HOLM
+D643;D643;1112 1169 11B2;D643;1112 1169 11B2; # (홃; 홃; 홃; 홃; 홃; ) HANGUL SYLLABLE HOLB
+D644;D644;1112 1169 11B3;D644;1112 1169 11B3; # (홄; 홄; 홄; 홄; 홄; ) HANGUL SYLLABLE HOLS
+D645;D645;1112 1169 11B4;D645;1112 1169 11B4; # (홅; 홅; 홅; 홅; 홅; ) HANGUL SYLLABLE HOLT
+D646;D646;1112 1169 11B5;D646;1112 1169 11B5; # (홆; 홆; 홆; 홆; 홆; ) HANGUL SYLLABLE HOLP
+D647;D647;1112 1169 11B6;D647;1112 1169 11B6; # (홇; 홇; 홇; 홇; 홇; ) HANGUL SYLLABLE HOLH
+D648;D648;1112 1169 11B7;D648;1112 1169 11B7; # (홈; 홈; 홈; 홈; 홈; ) HANGUL SYLLABLE HOM
+D649;D649;1112 1169 11B8;D649;1112 1169 11B8; # (홉; 홉; 홉; 홉; 홉; ) HANGUL SYLLABLE HOB
+D64A;D64A;1112 1169 11B9;D64A;1112 1169 11B9; # (홊; 홊; 홊; 홊; 홊; ) HANGUL SYLLABLE HOBS
+D64B;D64B;1112 1169 11BA;D64B;1112 1169 11BA; # (홋; 홋; 홋; 홋; 홋; ) HANGUL SYLLABLE HOS
+D64C;D64C;1112 1169 11BB;D64C;1112 1169 11BB; # (홌; 홌; 홌; 홌; 홌; ) HANGUL SYLLABLE HOSS
+D64D;D64D;1112 1169 11BC;D64D;1112 1169 11BC; # (홍; 홍; 홍; 홍; 홍; ) HANGUL SYLLABLE HONG
+D64E;D64E;1112 1169 11BD;D64E;1112 1169 11BD; # (홎; 홎; 홎; 홎; 홎; ) HANGUL SYLLABLE HOJ
+D64F;D64F;1112 1169 11BE;D64F;1112 1169 11BE; # (홏; 홏; 홏; 홏; 홏; ) HANGUL SYLLABLE HOC
+D650;D650;1112 1169 11BF;D650;1112 1169 11BF; # (홐; 홐; 홐; 홐; 홐; ) HANGUL SYLLABLE HOK
+D651;D651;1112 1169 11C0;D651;1112 1169 11C0; # (홑; 홑; 홑; 홑; 홑; ) HANGUL SYLLABLE HOT
+D652;D652;1112 1169 11C1;D652;1112 1169 11C1; # (홒; 홒; 홒; 홒; 홒; ) HANGUL SYLLABLE HOP
+D653;D653;1112 1169 11C2;D653;1112 1169 11C2; # (홓; 홓; 홓; 홓; 홓; ) HANGUL SYLLABLE HOH
+D654;D654;1112 116A;D654;1112 116A; # (화; 화; 화; 화; 화; ) HANGUL SYLLABLE HWA
+D655;D655;1112 116A 11A8;D655;1112 116A 11A8; # (확; 확; 확; 확; 확; ) HANGUL SYLLABLE HWAG
+D656;D656;1112 116A 11A9;D656;1112 116A 11A9; # (홖; 홖; 홖; 홖; 홖; ) HANGUL SYLLABLE HWAGG
+D657;D657;1112 116A 11AA;D657;1112 116A 11AA; # (홗; 홗; 홗; 홗; 홗; ) HANGUL SYLLABLE HWAGS
+D658;D658;1112 116A 11AB;D658;1112 116A 11AB; # (환; 환; 환; 환; 환; ) HANGUL SYLLABLE HWAN
+D659;D659;1112 116A 11AC;D659;1112 116A 11AC; # (홙; 홙; 홙; 홙; 홙; ) HANGUL SYLLABLE HWANJ
+D65A;D65A;1112 116A 11AD;D65A;1112 116A 11AD; # (홚; 홚; 홚; 홚; 홚; ) HANGUL SYLLABLE HWANH
+D65B;D65B;1112 116A 11AE;D65B;1112 116A 11AE; # (홛; 홛; 홛; 홛; 홛; ) HANGUL SYLLABLE HWAD
+D65C;D65C;1112 116A 11AF;D65C;1112 116A 11AF; # (활; 활; 활; 활; 활; ) HANGUL SYLLABLE HWAL
+D65D;D65D;1112 116A 11B0;D65D;1112 116A 11B0; # (홝; 홝; 홝; 홝; 홝; ) HANGUL SYLLABLE HWALG
+D65E;D65E;1112 116A 11B1;D65E;1112 116A 11B1; # (홞; 홞; 홞; 홞; 홞; ) HANGUL SYLLABLE HWALM
+D65F;D65F;1112 116A 11B2;D65F;1112 116A 11B2; # (홟; 홟; 홟; 홟; 홟; ) HANGUL SYLLABLE HWALB
+D660;D660;1112 116A 11B3;D660;1112 116A 11B3; # (홠; 홠; 홠; 홠; 홠; ) HANGUL SYLLABLE HWALS
+D661;D661;1112 116A 11B4;D661;1112 116A 11B4; # (홡; 홡; 홡; 홡; 홡; ) HANGUL SYLLABLE HWALT
+D662;D662;1112 116A 11B5;D662;1112 116A 11B5; # (홢; 홢; 홢; 홢; 홢; ) HANGUL SYLLABLE HWALP
+D663;D663;1112 116A 11B6;D663;1112 116A 11B6; # (홣; 홣; 홣; 홣; 홣; ) HANGUL SYLLABLE HWALH
+D664;D664;1112 116A 11B7;D664;1112 116A 11B7; # (홤; 홤; 홤; 홤; 홤; ) HANGUL SYLLABLE HWAM
+D665;D665;1112 116A 11B8;D665;1112 116A 11B8; # (홥; 홥; 홥; 홥; 홥; ) HANGUL SYLLABLE HWAB
+D666;D666;1112 116A 11B9;D666;1112 116A 11B9; # (홦; 홦; 홦; 홦; 홦; ) HANGUL SYLLABLE HWABS
+D667;D667;1112 116A 11BA;D667;1112 116A 11BA; # (홧; 홧; 홧; 홧; 홧; ) HANGUL SYLLABLE HWAS
+D668;D668;1112 116A 11BB;D668;1112 116A 11BB; # (홨; 홨; 홨; 홨; 홨; ) HANGUL SYLLABLE HWASS
+D669;D669;1112 116A 11BC;D669;1112 116A 11BC; # (황; 황; 황; 황; 황; ) HANGUL SYLLABLE HWANG
+D66A;D66A;1112 116A 11BD;D66A;1112 116A 11BD; # (홪; 홪; 홪; 홪; 홪; ) HANGUL SYLLABLE HWAJ
+D66B;D66B;1112 116A 11BE;D66B;1112 116A 11BE; # (홫; 홫; 홫; 홫; 홫; ) HANGUL SYLLABLE HWAC
+D66C;D66C;1112 116A 11BF;D66C;1112 116A 11BF; # (홬; 홬; 홬; 홬; 홬; ) HANGUL SYLLABLE HWAK
+D66D;D66D;1112 116A 11C0;D66D;1112 116A 11C0; # (홭; 홭; 홭; 홭; 홭; ) HANGUL SYLLABLE HWAT
+D66E;D66E;1112 116A 11C1;D66E;1112 116A 11C1; # (홮; 홮; 홮; 홮; 홮; ) HANGUL SYLLABLE HWAP
+D66F;D66F;1112 116A 11C2;D66F;1112 116A 11C2; # (홯; 홯; 홯; 홯; 홯; ) HANGUL SYLLABLE HWAH
+D670;D670;1112 116B;D670;1112 116B; # (홰; 홰; 홰; 홰; 홰; ) HANGUL SYLLABLE HWAE
+D671;D671;1112 116B 11A8;D671;1112 116B 11A8; # (홱; 홱; 홱; 홱; 홱; ) HANGUL SYLLABLE HWAEG
+D672;D672;1112 116B 11A9;D672;1112 116B 11A9; # (홲; 홲; 홲; 홲; 홲; ) HANGUL SYLLABLE HWAEGG
+D673;D673;1112 116B 11AA;D673;1112 116B 11AA; # (홳; 홳; 홳; 홳; 홳; ) HANGUL SYLLABLE HWAEGS
+D674;D674;1112 116B 11AB;D674;1112 116B 11AB; # (홴; 홴; 홴; 홴; 홴; ) HANGUL SYLLABLE HWAEN
+D675;D675;1112 116B 11AC;D675;1112 116B 11AC; # (홵; 홵; 홵; 홵; 홵; ) HANGUL SYLLABLE HWAENJ
+D676;D676;1112 116B 11AD;D676;1112 116B 11AD; # (홶; 홶; 홶; 홶; 홶; ) HANGUL SYLLABLE HWAENH
+D677;D677;1112 116B 11AE;D677;1112 116B 11AE; # (홷; 홷; 홷; 홷; 홷; ) HANGUL SYLLABLE HWAED
+D678;D678;1112 116B 11AF;D678;1112 116B 11AF; # (홸; 홸; 홸; 홸; 홸; ) HANGUL SYLLABLE HWAEL
+D679;D679;1112 116B 11B0;D679;1112 116B 11B0; # (홹; 홹; 홹; 홹; 홹; ) HANGUL SYLLABLE HWAELG
+D67A;D67A;1112 116B 11B1;D67A;1112 116B 11B1; # (홺; 홺; 홺; 홺; 홺; ) HANGUL SYLLABLE HWAELM
+D67B;D67B;1112 116B 11B2;D67B;1112 116B 11B2; # (홻; 홻; 홻; 홻; 홻; ) HANGUL SYLLABLE HWAELB
+D67C;D67C;1112 116B 11B3;D67C;1112 116B 11B3; # (홼; 홼; 홼; 홼; 홼; ) HANGUL SYLLABLE HWAELS
+D67D;D67D;1112 116B 11B4;D67D;1112 116B 11B4; # (홽; 홽; 홽; 홽; 홽; ) HANGUL SYLLABLE HWAELT
+D67E;D67E;1112 116B 11B5;D67E;1112 116B 11B5; # (홾; 홾; 홾; 홾; 홾; ) HANGUL SYLLABLE HWAELP
+D67F;D67F;1112 116B 11B6;D67F;1112 116B 11B6; # (홿; 홿; 홿; 홿; 홿; ) HANGUL SYLLABLE HWAELH
+D680;D680;1112 116B 11B7;D680;1112 116B 11B7; # (횀; 횀; 횀; 횀; 횀; ) HANGUL SYLLABLE HWAEM
+D681;D681;1112 116B 11B8;D681;1112 116B 11B8; # (횁; 횁; 횁; 횁; 횁; ) HANGUL SYLLABLE HWAEB
+D682;D682;1112 116B 11B9;D682;1112 116B 11B9; # (횂; 횂; 횂; 횂; 횂; ) HANGUL SYLLABLE HWAEBS
+D683;D683;1112 116B 11BA;D683;1112 116B 11BA; # (횃; 횃; 횃; 횃; 횃; ) HANGUL SYLLABLE HWAES
+D684;D684;1112 116B 11BB;D684;1112 116B 11BB; # (횄; 횄; 횄; 횄; 횄; ) HANGUL SYLLABLE HWAESS
+D685;D685;1112 116B 11BC;D685;1112 116B 11BC; # (횅; 횅; 횅; 횅; 횅; ) HANGUL SYLLABLE HWAENG
+D686;D686;1112 116B 11BD;D686;1112 116B 11BD; # (횆; 횆; 횆; 횆; 횆; ) HANGUL SYLLABLE HWAEJ
+D687;D687;1112 116B 11BE;D687;1112 116B 11BE; # (횇; 횇; 횇; 횇; 횇; ) HANGUL SYLLABLE HWAEC
+D688;D688;1112 116B 11BF;D688;1112 116B 11BF; # (횈; 횈; 횈; 횈; 횈; ) HANGUL SYLLABLE HWAEK
+D689;D689;1112 116B 11C0;D689;1112 116B 11C0; # (횉; 횉; 횉; 횉; 횉; ) HANGUL SYLLABLE HWAET
+D68A;D68A;1112 116B 11C1;D68A;1112 116B 11C1; # (횊; 횊; 횊; 횊; 횊; ) HANGUL SYLLABLE HWAEP
+D68B;D68B;1112 116B 11C2;D68B;1112 116B 11C2; # (횋; 횋; 횋; 횋; 횋; ) HANGUL SYLLABLE HWAEH
+D68C;D68C;1112 116C;D68C;1112 116C; # (회; 회; 회; 회; 회; ) HANGUL SYLLABLE HOE
+D68D;D68D;1112 116C 11A8;D68D;1112 116C 11A8; # (획; 획; 획; 획; 획; ) HANGUL SYLLABLE HOEG
+D68E;D68E;1112 116C 11A9;D68E;1112 116C 11A9; # (횎; 횎; 횎; 횎; 횎; ) HANGUL SYLLABLE HOEGG
+D68F;D68F;1112 116C 11AA;D68F;1112 116C 11AA; # (횏; 횏; 횏; 횏; 횏; ) HANGUL SYLLABLE HOEGS
+D690;D690;1112 116C 11AB;D690;1112 116C 11AB; # (횐; 횐; 횐; 횐; 횐; ) HANGUL SYLLABLE HOEN
+D691;D691;1112 116C 11AC;D691;1112 116C 11AC; # (횑; 횑; 횑; 횑; 횑; ) HANGUL SYLLABLE HOENJ
+D692;D692;1112 116C 11AD;D692;1112 116C 11AD; # (횒; 횒; 횒; 횒; 횒; ) HANGUL SYLLABLE HOENH
+D693;D693;1112 116C 11AE;D693;1112 116C 11AE; # (횓; 횓; 횓; 횓; 횓; ) HANGUL SYLLABLE HOED
+D694;D694;1112 116C 11AF;D694;1112 116C 11AF; # (횔; 횔; 횔; 횔; 횔; ) HANGUL SYLLABLE HOEL
+D695;D695;1112 116C 11B0;D695;1112 116C 11B0; # (횕; 횕; 횕; 횕; 횕; ) HANGUL SYLLABLE HOELG
+D696;D696;1112 116C 11B1;D696;1112 116C 11B1; # (횖; 횖; 횖; 횖; 횖; ) HANGUL SYLLABLE HOELM
+D697;D697;1112 116C 11B2;D697;1112 116C 11B2; # (횗; 횗; 횗; 횗; 횗; ) HANGUL SYLLABLE HOELB
+D698;D698;1112 116C 11B3;D698;1112 116C 11B3; # (횘; 횘; 횘; 횘; 횘; ) HANGUL SYLLABLE HOELS
+D699;D699;1112 116C 11B4;D699;1112 116C 11B4; # (횙; 횙; 횙; 횙; 횙; ) HANGUL SYLLABLE HOELT
+D69A;D69A;1112 116C 11B5;D69A;1112 116C 11B5; # (횚; 횚; 횚; 횚; 횚; ) HANGUL SYLLABLE HOELP
+D69B;D69B;1112 116C 11B6;D69B;1112 116C 11B6; # (횛; 횛; 횛; 횛; 횛; ) HANGUL SYLLABLE HOELH
+D69C;D69C;1112 116C 11B7;D69C;1112 116C 11B7; # (횜; 횜; 횜; 횜; 횜; ) HANGUL SYLLABLE HOEM
+D69D;D69D;1112 116C 11B8;D69D;1112 116C 11B8; # (횝; 횝; 횝; 횝; 횝; ) HANGUL SYLLABLE HOEB
+D69E;D69E;1112 116C 11B9;D69E;1112 116C 11B9; # (횞; 횞; 횞; 횞; 횞; ) HANGUL SYLLABLE HOEBS
+D69F;D69F;1112 116C 11BA;D69F;1112 116C 11BA; # (횟; 횟; 횟; 횟; 횟; ) HANGUL SYLLABLE HOES
+D6A0;D6A0;1112 116C 11BB;D6A0;1112 116C 11BB; # (횠; 횠; 횠; 횠; 횠; ) HANGUL SYLLABLE HOESS
+D6A1;D6A1;1112 116C 11BC;D6A1;1112 116C 11BC; # (횡; 횡; 횡; 횡; 횡; ) HANGUL SYLLABLE HOENG
+D6A2;D6A2;1112 116C 11BD;D6A2;1112 116C 11BD; # (횢; 횢; 횢; 횢; 횢; ) HANGUL SYLLABLE HOEJ
+D6A3;D6A3;1112 116C 11BE;D6A3;1112 116C 11BE; # (횣; 횣; 횣; 횣; 횣; ) HANGUL SYLLABLE HOEC
+D6A4;D6A4;1112 116C 11BF;D6A4;1112 116C 11BF; # (횤; 횤; 횤; 횤; 횤; ) HANGUL SYLLABLE HOEK
+D6A5;D6A5;1112 116C 11C0;D6A5;1112 116C 11C0; # (횥; 횥; 횥; 횥; 횥; ) HANGUL SYLLABLE HOET
+D6A6;D6A6;1112 116C 11C1;D6A6;1112 116C 11C1; # (횦; 횦; 횦; 횦; 횦; ) HANGUL SYLLABLE HOEP
+D6A7;D6A7;1112 116C 11C2;D6A7;1112 116C 11C2; # (횧; 횧; 횧; 횧; 횧; ) HANGUL SYLLABLE HOEH
+D6A8;D6A8;1112 116D;D6A8;1112 116D; # (효; 효; 효; 효; 효; ) HANGUL SYLLABLE HYO
+D6A9;D6A9;1112 116D 11A8;D6A9;1112 116D 11A8; # (횩; 횩; 횩; 횩; 횩; ) HANGUL SYLLABLE HYOG
+D6AA;D6AA;1112 116D 11A9;D6AA;1112 116D 11A9; # (횪; 횪; 횪; 횪; 횪; ) HANGUL SYLLABLE HYOGG
+D6AB;D6AB;1112 116D 11AA;D6AB;1112 116D 11AA; # (횫; 횫; 횫; 횫; 횫; ) HANGUL SYLLABLE HYOGS
+D6AC;D6AC;1112 116D 11AB;D6AC;1112 116D 11AB; # (횬; 횬; 횬; 횬; 횬; ) HANGUL SYLLABLE HYON
+D6AD;D6AD;1112 116D 11AC;D6AD;1112 116D 11AC; # (횭; 횭; 횭; 횭; 횭; ) HANGUL SYLLABLE HYONJ
+D6AE;D6AE;1112 116D 11AD;D6AE;1112 116D 11AD; # (횮; 횮; 횮; 횮; 횮; ) HANGUL SYLLABLE HYONH
+D6AF;D6AF;1112 116D 11AE;D6AF;1112 116D 11AE; # (횯; 횯; 횯; 횯; 횯; ) HANGUL SYLLABLE HYOD
+D6B0;D6B0;1112 116D 11AF;D6B0;1112 116D 11AF; # (횰; 횰; 횰; 횰; 횰; ) HANGUL SYLLABLE HYOL
+D6B1;D6B1;1112 116D 11B0;D6B1;1112 116D 11B0; # (횱; 횱; 횱; 횱; 횱; ) HANGUL SYLLABLE HYOLG
+D6B2;D6B2;1112 116D 11B1;D6B2;1112 116D 11B1; # (횲; 횲; 횲; 횲; 횲; ) HANGUL SYLLABLE HYOLM
+D6B3;D6B3;1112 116D 11B2;D6B3;1112 116D 11B2; # (횳; 횳; 횳; 횳; 횳; ) HANGUL SYLLABLE HYOLB
+D6B4;D6B4;1112 116D 11B3;D6B4;1112 116D 11B3; # (횴; 횴; 횴; 횴; 횴; ) HANGUL SYLLABLE HYOLS
+D6B5;D6B5;1112 116D 11B4;D6B5;1112 116D 11B4; # (횵; 횵; 횵; 횵; 횵; ) HANGUL SYLLABLE HYOLT
+D6B6;D6B6;1112 116D 11B5;D6B6;1112 116D 11B5; # (횶; 횶; 횶; 횶; 횶; ) HANGUL SYLLABLE HYOLP
+D6B7;D6B7;1112 116D 11B6;D6B7;1112 116D 11B6; # (횷; 횷; 횷; 횷; 횷; ) HANGUL SYLLABLE HYOLH
+D6B8;D6B8;1112 116D 11B7;D6B8;1112 116D 11B7; # (횸; 횸; 횸; 횸; 횸; ) HANGUL SYLLABLE HYOM
+D6B9;D6B9;1112 116D 11B8;D6B9;1112 116D 11B8; # (횹; 횹; 횹; 횹; 횹; ) HANGUL SYLLABLE HYOB
+D6BA;D6BA;1112 116D 11B9;D6BA;1112 116D 11B9; # (횺; 횺; 횺; 횺; 횺; ) HANGUL SYLLABLE HYOBS
+D6BB;D6BB;1112 116D 11BA;D6BB;1112 116D 11BA; # (횻; 횻; 횻; 횻; 횻; ) HANGUL SYLLABLE HYOS
+D6BC;D6BC;1112 116D 11BB;D6BC;1112 116D 11BB; # (횼; 횼; 횼; 횼; 횼; ) HANGUL SYLLABLE HYOSS
+D6BD;D6BD;1112 116D 11BC;D6BD;1112 116D 11BC; # (횽; 횽; 횽; 횽; 횽; ) HANGUL SYLLABLE HYONG
+D6BE;D6BE;1112 116D 11BD;D6BE;1112 116D 11BD; # (횾; 횾; 횾; 횾; 횾; ) HANGUL SYLLABLE HYOJ
+D6BF;D6BF;1112 116D 11BE;D6BF;1112 116D 11BE; # (횿; 횿; 횿; 횿; 횿; ) HANGUL SYLLABLE HYOC
+D6C0;D6C0;1112 116D 11BF;D6C0;1112 116D 11BF; # (훀; 훀; 훀; 훀; 훀; ) HANGUL SYLLABLE HYOK
+D6C1;D6C1;1112 116D 11C0;D6C1;1112 116D 11C0; # (훁; 훁; 훁; 훁; 훁; ) HANGUL SYLLABLE HYOT
+D6C2;D6C2;1112 116D 11C1;D6C2;1112 116D 11C1; # (훂; 훂; 훂; 훂; 훂; ) HANGUL SYLLABLE HYOP
+D6C3;D6C3;1112 116D 11C2;D6C3;1112 116D 11C2; # (훃; 훃; 훃; 훃; 훃; ) HANGUL SYLLABLE HYOH
+D6C4;D6C4;1112 116E;D6C4;1112 116E; # (후; 후; 후; 후; 후; ) HANGUL SYLLABLE HU
+D6C5;D6C5;1112 116E 11A8;D6C5;1112 116E 11A8; # (훅; 훅; 훅; 훅; 훅; ) HANGUL SYLLABLE HUG
+D6C6;D6C6;1112 116E 11A9;D6C6;1112 116E 11A9; # (훆; 훆; 훆; 훆; 훆; ) HANGUL SYLLABLE HUGG
+D6C7;D6C7;1112 116E 11AA;D6C7;1112 116E 11AA; # (훇; 훇; 훇; 훇; 훇; ) HANGUL SYLLABLE HUGS
+D6C8;D6C8;1112 116E 11AB;D6C8;1112 116E 11AB; # (훈; 훈; 훈; 훈; 훈; ) HANGUL SYLLABLE HUN
+D6C9;D6C9;1112 116E 11AC;D6C9;1112 116E 11AC; # (훉; 훉; 훉; 훉; 훉; ) HANGUL SYLLABLE HUNJ
+D6CA;D6CA;1112 116E 11AD;D6CA;1112 116E 11AD; # (훊; 훊; 훊; 훊; 훊; ) HANGUL SYLLABLE HUNH
+D6CB;D6CB;1112 116E 11AE;D6CB;1112 116E 11AE; # (훋; 훋; 훋; 훋; 훋; ) HANGUL SYLLABLE HUD
+D6CC;D6CC;1112 116E 11AF;D6CC;1112 116E 11AF; # (훌; 훌; 훌; 훌; 훌; ) HANGUL SYLLABLE HUL
+D6CD;D6CD;1112 116E 11B0;D6CD;1112 116E 11B0; # (훍; 훍; 훍; 훍; 훍; ) HANGUL SYLLABLE HULG
+D6CE;D6CE;1112 116E 11B1;D6CE;1112 116E 11B1; # (훎; 훎; 훎; 훎; 훎; ) HANGUL SYLLABLE HULM
+D6CF;D6CF;1112 116E 11B2;D6CF;1112 116E 11B2; # (훏; 훏; 훏; 훏; 훏; ) HANGUL SYLLABLE HULB
+D6D0;D6D0;1112 116E 11B3;D6D0;1112 116E 11B3; # (훐; 훐; 훐; 훐; 훐; ) HANGUL SYLLABLE HULS
+D6D1;D6D1;1112 116E 11B4;D6D1;1112 116E 11B4; # (훑; 훑; 훑; 훑; 훑; ) HANGUL SYLLABLE HULT
+D6D2;D6D2;1112 116E 11B5;D6D2;1112 116E 11B5; # (훒; 훒; 훒; 훒; 훒; ) HANGUL SYLLABLE HULP
+D6D3;D6D3;1112 116E 11B6;D6D3;1112 116E 11B6; # (훓; 훓; 훓; 훓; 훓; ) HANGUL SYLLABLE HULH
+D6D4;D6D4;1112 116E 11B7;D6D4;1112 116E 11B7; # (훔; 훔; 훔; 훔; 훔; ) HANGUL SYLLABLE HUM
+D6D5;D6D5;1112 116E 11B8;D6D5;1112 116E 11B8; # (훕; 훕; 훕; 훕; 훕; ) HANGUL SYLLABLE HUB
+D6D6;D6D6;1112 116E 11B9;D6D6;1112 116E 11B9; # (훖; 훖; 훖; 훖; 훖; ) HANGUL SYLLABLE HUBS
+D6D7;D6D7;1112 116E 11BA;D6D7;1112 116E 11BA; # (훗; 훗; 훗; 훗; 훗; ) HANGUL SYLLABLE HUS
+D6D8;D6D8;1112 116E 11BB;D6D8;1112 116E 11BB; # (훘; 훘; 훘; 훘; 훘; ) HANGUL SYLLABLE HUSS
+D6D9;D6D9;1112 116E 11BC;D6D9;1112 116E 11BC; # (훙; 훙; 훙; 훙; 훙; ) HANGUL SYLLABLE HUNG
+D6DA;D6DA;1112 116E 11BD;D6DA;1112 116E 11BD; # (훚; 훚; 훚; 훚; 훚; ) HANGUL SYLLABLE HUJ
+D6DB;D6DB;1112 116E 11BE;D6DB;1112 116E 11BE; # (훛; 훛; 훛; 훛; 훛; ) HANGUL SYLLABLE HUC
+D6DC;D6DC;1112 116E 11BF;D6DC;1112 116E 11BF; # (훜; 훜; 훜; 훜; 훜; ) HANGUL SYLLABLE HUK
+D6DD;D6DD;1112 116E 11C0;D6DD;1112 116E 11C0; # (훝; 훝; 훝; 훝; 훝; ) HANGUL SYLLABLE HUT
+D6DE;D6DE;1112 116E 11C1;D6DE;1112 116E 11C1; # (훞; 훞; 훞; 훞; 훞; ) HANGUL SYLLABLE HUP
+D6DF;D6DF;1112 116E 11C2;D6DF;1112 116E 11C2; # (훟; 훟; 훟; 훟; 훟; ) HANGUL SYLLABLE HUH
+D6E0;D6E0;1112 116F;D6E0;1112 116F; # (훠; 훠; 훠; 훠; 훠; ) HANGUL SYLLABLE HWEO
+D6E1;D6E1;1112 116F 11A8;D6E1;1112 116F 11A8; # (훡; 훡; 훡; 훡; 훡; ) HANGUL SYLLABLE HWEOG
+D6E2;D6E2;1112 116F 11A9;D6E2;1112 116F 11A9; # (훢; 훢; 훢; 훢; 훢; ) HANGUL SYLLABLE HWEOGG
+D6E3;D6E3;1112 116F 11AA;D6E3;1112 116F 11AA; # (훣; 훣; 훣; 훣; 훣; ) HANGUL SYLLABLE HWEOGS
+D6E4;D6E4;1112 116F 11AB;D6E4;1112 116F 11AB; # (훤; 훤; 훤; 훤; 훤; ) HANGUL SYLLABLE HWEON
+D6E5;D6E5;1112 116F 11AC;D6E5;1112 116F 11AC; # (훥; 훥; 훥; 훥; 훥; ) HANGUL SYLLABLE HWEONJ
+D6E6;D6E6;1112 116F 11AD;D6E6;1112 116F 11AD; # (훦; 훦; 훦; 훦; 훦; ) HANGUL SYLLABLE HWEONH
+D6E7;D6E7;1112 116F 11AE;D6E7;1112 116F 11AE; # (훧; 훧; 훧; 훧; 훧; ) HANGUL SYLLABLE HWEOD
+D6E8;D6E8;1112 116F 11AF;D6E8;1112 116F 11AF; # (훨; 훨; 훨; 훨; 훨; ) HANGUL SYLLABLE HWEOL
+D6E9;D6E9;1112 116F 11B0;D6E9;1112 116F 11B0; # (훩; 훩; 훩; 훩; 훩; ) HANGUL SYLLABLE HWEOLG
+D6EA;D6EA;1112 116F 11B1;D6EA;1112 116F 11B1; # (훪; 훪; 훪; 훪; 훪; ) HANGUL SYLLABLE HWEOLM
+D6EB;D6EB;1112 116F 11B2;D6EB;1112 116F 11B2; # (훫; 훫; 훫; 훫; 훫; ) HANGUL SYLLABLE HWEOLB
+D6EC;D6EC;1112 116F 11B3;D6EC;1112 116F 11B3; # (훬; 훬; 훬; 훬; 훬; ) HANGUL SYLLABLE HWEOLS
+D6ED;D6ED;1112 116F 11B4;D6ED;1112 116F 11B4; # (훭; 훭; 훭; 훭; 훭; ) HANGUL SYLLABLE HWEOLT
+D6EE;D6EE;1112 116F 11B5;D6EE;1112 116F 11B5; # (훮; 훮; 훮; 훮; 훮; ) HANGUL SYLLABLE HWEOLP
+D6EF;D6EF;1112 116F 11B6;D6EF;1112 116F 11B6; # (훯; 훯; 훯; 훯; 훯; ) HANGUL SYLLABLE HWEOLH
+D6F0;D6F0;1112 116F 11B7;D6F0;1112 116F 11B7; # (훰; 훰; 훰; 훰; 훰; ) HANGUL SYLLABLE HWEOM
+D6F1;D6F1;1112 116F 11B8;D6F1;1112 116F 11B8; # (훱; 훱; 훱; 훱; 훱; ) HANGUL SYLLABLE HWEOB
+D6F2;D6F2;1112 116F 11B9;D6F2;1112 116F 11B9; # (훲; 훲; 훲; 훲; 훲; ) HANGUL SYLLABLE HWEOBS
+D6F3;D6F3;1112 116F 11BA;D6F3;1112 116F 11BA; # (훳; 훳; 훳; 훳; 훳; ) HANGUL SYLLABLE HWEOS
+D6F4;D6F4;1112 116F 11BB;D6F4;1112 116F 11BB; # (훴; 훴; 훴; 훴; 훴; ) HANGUL SYLLABLE HWEOSS
+D6F5;D6F5;1112 116F 11BC;D6F5;1112 116F 11BC; # (훵; 훵; 훵; 훵; 훵; ) HANGUL SYLLABLE HWEONG
+D6F6;D6F6;1112 116F 11BD;D6F6;1112 116F 11BD; # (훶; 훶; 훶; 훶; 훶; ) HANGUL SYLLABLE HWEOJ
+D6F7;D6F7;1112 116F 11BE;D6F7;1112 116F 11BE; # (훷; 훷; 훷; 훷; 훷; ) HANGUL SYLLABLE HWEOC
+D6F8;D6F8;1112 116F 11BF;D6F8;1112 116F 11BF; # (훸; 훸; 훸; 훸; 훸; ) HANGUL SYLLABLE HWEOK
+D6F9;D6F9;1112 116F 11C0;D6F9;1112 116F 11C0; # (훹; 훹; 훹; 훹; 훹; ) HANGUL SYLLABLE HWEOT
+D6FA;D6FA;1112 116F 11C1;D6FA;1112 116F 11C1; # (훺; 훺; 훺; 훺; 훺; ) HANGUL SYLLABLE HWEOP
+D6FB;D6FB;1112 116F 11C2;D6FB;1112 116F 11C2; # (훻; 훻; 훻; 훻; 훻; ) HANGUL SYLLABLE HWEOH
+D6FC;D6FC;1112 1170;D6FC;1112 1170; # (훼; 훼; 훼; 훼; 훼; ) HANGUL SYLLABLE HWE
+D6FD;D6FD;1112 1170 11A8;D6FD;1112 1170 11A8; # (훽; 훽; 훽; 훽; 훽; ) HANGUL SYLLABLE HWEG
+D6FE;D6FE;1112 1170 11A9;D6FE;1112 1170 11A9; # (훾; 훾; 훾; 훾; 훾; ) HANGUL SYLLABLE HWEGG
+D6FF;D6FF;1112 1170 11AA;D6FF;1112 1170 11AA; # (훿; 훿; 훿; 훿; 훿; ) HANGUL SYLLABLE HWEGS
+D700;D700;1112 1170 11AB;D700;1112 1170 11AB; # (휀; 휀; 휀; 휀; 휀; ) HANGUL SYLLABLE HWEN
+D701;D701;1112 1170 11AC;D701;1112 1170 11AC; # (휁; 휁; 휁; 휁; 휁; ) HANGUL SYLLABLE HWENJ
+D702;D702;1112 1170 11AD;D702;1112 1170 11AD; # (휂; 휂; 휂; 휂; 휂; ) HANGUL SYLLABLE HWENH
+D703;D703;1112 1170 11AE;D703;1112 1170 11AE; # (휃; 휃; 휃; 휃; 휃; ) HANGUL SYLLABLE HWED
+D704;D704;1112 1170 11AF;D704;1112 1170 11AF; # (휄; 휄; 휄; 휄; 휄; ) HANGUL SYLLABLE HWEL
+D705;D705;1112 1170 11B0;D705;1112 1170 11B0; # (휅; 휅; 휅; 휅; 휅; ) HANGUL SYLLABLE HWELG
+D706;D706;1112 1170 11B1;D706;1112 1170 11B1; # (휆; 휆; 휆; 휆; 휆; ) HANGUL SYLLABLE HWELM
+D707;D707;1112 1170 11B2;D707;1112 1170 11B2; # (휇; 휇; 휇; 휇; 휇; ) HANGUL SYLLABLE HWELB
+D708;D708;1112 1170 11B3;D708;1112 1170 11B3; # (휈; 휈; 휈; 휈; 휈; ) HANGUL SYLLABLE HWELS
+D709;D709;1112 1170 11B4;D709;1112 1170 11B4; # (휉; 휉; 휉; 휉; 휉; ) HANGUL SYLLABLE HWELT
+D70A;D70A;1112 1170 11B5;D70A;1112 1170 11B5; # (휊; 휊; 휊; 휊; 휊; ) HANGUL SYLLABLE HWELP
+D70B;D70B;1112 1170 11B6;D70B;1112 1170 11B6; # (휋; 휋; 휋; 휋; 휋; ) HANGUL SYLLABLE HWELH
+D70C;D70C;1112 1170 11B7;D70C;1112 1170 11B7; # (휌; 휌; 휌; 휌; 휌; ) HANGUL SYLLABLE HWEM
+D70D;D70D;1112 1170 11B8;D70D;1112 1170 11B8; # (휍; 휍; 휍; 휍; 휍; ) HANGUL SYLLABLE HWEB
+D70E;D70E;1112 1170 11B9;D70E;1112 1170 11B9; # (휎; 휎; 휎; 휎; 휎; ) HANGUL SYLLABLE HWEBS
+D70F;D70F;1112 1170 11BA;D70F;1112 1170 11BA; # (휏; 휏; 휏; 휏; 휏; ) HANGUL SYLLABLE HWES
+D710;D710;1112 1170 11BB;D710;1112 1170 11BB; # (휐; 휐; 휐; 휐; 휐; ) HANGUL SYLLABLE HWESS
+D711;D711;1112 1170 11BC;D711;1112 1170 11BC; # (휑; 휑; 휑; 휑; 휑; ) HANGUL SYLLABLE HWENG
+D712;D712;1112 1170 11BD;D712;1112 1170 11BD; # (휒; 휒; 휒; 휒; 휒; ) HANGUL SYLLABLE HWEJ
+D713;D713;1112 1170 11BE;D713;1112 1170 11BE; # (휓; 휓; 휓; 휓; 휓; ) HANGUL SYLLABLE HWEC
+D714;D714;1112 1170 11BF;D714;1112 1170 11BF; # (휔; 휔; 휔; 휔; 휔; ) HANGUL SYLLABLE HWEK
+D715;D715;1112 1170 11C0;D715;1112 1170 11C0; # (휕; 휕; 휕; 휕; 휕; ) HANGUL SYLLABLE HWET
+D716;D716;1112 1170 11C1;D716;1112 1170 11C1; # (휖; 휖; 휖; 휖; 휖; ) HANGUL SYLLABLE HWEP
+D717;D717;1112 1170 11C2;D717;1112 1170 11C2; # (휗; 휗; 휗; 휗; 휗; ) HANGUL SYLLABLE HWEH
+D718;D718;1112 1171;D718;1112 1171; # (휘; 휘; 휘; 휘; 휘; ) HANGUL SYLLABLE HWI
+D719;D719;1112 1171 11A8;D719;1112 1171 11A8; # (휙; 휙; 휙; 휙; 휙; ) HANGUL SYLLABLE HWIG
+D71A;D71A;1112 1171 11A9;D71A;1112 1171 11A9; # (휚; 휚; 휚; 휚; 휚; ) HANGUL SYLLABLE HWIGG
+D71B;D71B;1112 1171 11AA;D71B;1112 1171 11AA; # (휛; 휛; 휛; 휛; 휛; ) HANGUL SYLLABLE HWIGS
+D71C;D71C;1112 1171 11AB;D71C;1112 1171 11AB; # (휜; 휜; 휜; 휜; 휜; ) HANGUL SYLLABLE HWIN
+D71D;D71D;1112 1171 11AC;D71D;1112 1171 11AC; # (휝; 휝; 휝; 휝; 휝; ) HANGUL SYLLABLE HWINJ
+D71E;D71E;1112 1171 11AD;D71E;1112 1171 11AD; # (휞; 휞; 휞; 휞; 휞; ) HANGUL SYLLABLE HWINH
+D71F;D71F;1112 1171 11AE;D71F;1112 1171 11AE; # (휟; 휟; 휟; 휟; 휟; ) HANGUL SYLLABLE HWID
+D720;D720;1112 1171 11AF;D720;1112 1171 11AF; # (휠; 휠; 휠; 휠; 휠; ) HANGUL SYLLABLE HWIL
+D721;D721;1112 1171 11B0;D721;1112 1171 11B0; # (휡; 휡; 휡; 휡; 휡; ) HANGUL SYLLABLE HWILG
+D722;D722;1112 1171 11B1;D722;1112 1171 11B1; # (휢; 휢; 휢; 휢; 휢; ) HANGUL SYLLABLE HWILM
+D723;D723;1112 1171 11B2;D723;1112 1171 11B2; # (휣; 휣; 휣; 휣; 휣; ) HANGUL SYLLABLE HWILB
+D724;D724;1112 1171 11B3;D724;1112 1171 11B3; # (휤; 휤; 휤; 휤; 휤; ) HANGUL SYLLABLE HWILS
+D725;D725;1112 1171 11B4;D725;1112 1171 11B4; # (휥; 휥; 휥; 휥; 휥; ) HANGUL SYLLABLE HWILT
+D726;D726;1112 1171 11B5;D726;1112 1171 11B5; # (휦; 휦; 휦; 휦; 휦; ) HANGUL SYLLABLE HWILP
+D727;D727;1112 1171 11B6;D727;1112 1171 11B6; # (휧; 휧; 휧; 휧; 휧; ) HANGUL SYLLABLE HWILH
+D728;D728;1112 1171 11B7;D728;1112 1171 11B7; # (휨; 휨; 휨; 휨; 휨; ) HANGUL SYLLABLE HWIM
+D729;D729;1112 1171 11B8;D729;1112 1171 11B8; # (휩; 휩; 휩; 휩; 휩; ) HANGUL SYLLABLE HWIB
+D72A;D72A;1112 1171 11B9;D72A;1112 1171 11B9; # (휪; 휪; 휪; 휪; 휪; ) HANGUL SYLLABLE HWIBS
+D72B;D72B;1112 1171 11BA;D72B;1112 1171 11BA; # (휫; 휫; 휫; 휫; 휫; ) HANGUL SYLLABLE HWIS
+D72C;D72C;1112 1171 11BB;D72C;1112 1171 11BB; # (휬; 휬; 휬; 휬; 휬; ) HANGUL SYLLABLE HWISS
+D72D;D72D;1112 1171 11BC;D72D;1112 1171 11BC; # (휭; 휭; 휭; 휭; 휭; ) HANGUL SYLLABLE HWING
+D72E;D72E;1112 1171 11BD;D72E;1112 1171 11BD; # (휮; 휮; 휮; 휮; 휮; ) HANGUL SYLLABLE HWIJ
+D72F;D72F;1112 1171 11BE;D72F;1112 1171 11BE; # (휯; 휯; 휯; 휯; 휯; ) HANGUL SYLLABLE HWIC
+D730;D730;1112 1171 11BF;D730;1112 1171 11BF; # (휰; 휰; 휰; 휰; 휰; ) HANGUL SYLLABLE HWIK
+D731;D731;1112 1171 11C0;D731;1112 1171 11C0; # (휱; 휱; 휱; 휱; 휱; ) HANGUL SYLLABLE HWIT
+D732;D732;1112 1171 11C1;D732;1112 1171 11C1; # (휲; 휲; 휲; 휲; 휲; ) HANGUL SYLLABLE HWIP
+D733;D733;1112 1171 11C2;D733;1112 1171 11C2; # (휳; 휳; 휳; 휳; 휳; ) HANGUL SYLLABLE HWIH
+D734;D734;1112 1172;D734;1112 1172; # (휴; 휴; 휴; 휴; 휴; ) HANGUL SYLLABLE HYU
+D735;D735;1112 1172 11A8;D735;1112 1172 11A8; # (휵; 휵; 휵; 휵; 휵; ) HANGUL SYLLABLE HYUG
+D736;D736;1112 1172 11A9;D736;1112 1172 11A9; # (휶; 휶; 휶; 휶; 휶; ) HANGUL SYLLABLE HYUGG
+D737;D737;1112 1172 11AA;D737;1112 1172 11AA; # (휷; 휷; 휷; 휷; 휷; ) HANGUL SYLLABLE HYUGS
+D738;D738;1112 1172 11AB;D738;1112 1172 11AB; # (휸; 휸; 휸; 휸; 휸; ) HANGUL SYLLABLE HYUN
+D739;D739;1112 1172 11AC;D739;1112 1172 11AC; # (휹; 휹; 휹; 휹; 휹; ) HANGUL SYLLABLE HYUNJ
+D73A;D73A;1112 1172 11AD;D73A;1112 1172 11AD; # (휺; 휺; 휺; 휺; 휺; ) HANGUL SYLLABLE HYUNH
+D73B;D73B;1112 1172 11AE;D73B;1112 1172 11AE; # (휻; 휻; 휻; 휻; 휻; ) HANGUL SYLLABLE HYUD
+D73C;D73C;1112 1172 11AF;D73C;1112 1172 11AF; # (휼; 휼; 휼; 휼; 휼; ) HANGUL SYLLABLE HYUL
+D73D;D73D;1112 1172 11B0;D73D;1112 1172 11B0; # (휽; 휽; 휽; 휽; 휽; ) HANGUL SYLLABLE HYULG
+D73E;D73E;1112 1172 11B1;D73E;1112 1172 11B1; # (휾; 휾; 휾; 휾; 휾; ) HANGUL SYLLABLE HYULM
+D73F;D73F;1112 1172 11B2;D73F;1112 1172 11B2; # (휿; 휿; 휿; 휿; 휿; ) HANGUL SYLLABLE HYULB
+D740;D740;1112 1172 11B3;D740;1112 1172 11B3; # (흀; 흀; 흀; 흀; 흀; ) HANGUL SYLLABLE HYULS
+D741;D741;1112 1172 11B4;D741;1112 1172 11B4; # (흁; 흁; 흁; 흁; 흁; ) HANGUL SYLLABLE HYULT
+D742;D742;1112 1172 11B5;D742;1112 1172 11B5; # (흂; 흂; 흂; 흂; 흂; ) HANGUL SYLLABLE HYULP
+D743;D743;1112 1172 11B6;D743;1112 1172 11B6; # (흃; 흃; 흃; 흃; 흃; ) HANGUL SYLLABLE HYULH
+D744;D744;1112 1172 11B7;D744;1112 1172 11B7; # (흄; 흄; 흄; 흄; 흄; ) HANGUL SYLLABLE HYUM
+D745;D745;1112 1172 11B8;D745;1112 1172 11B8; # (흅; 흅; 흅; 흅; 흅; ) HANGUL SYLLABLE HYUB
+D746;D746;1112 1172 11B9;D746;1112 1172 11B9; # (흆; 흆; 흆; 흆; 흆; ) HANGUL SYLLABLE HYUBS
+D747;D747;1112 1172 11BA;D747;1112 1172 11BA; # (흇; 흇; 흇; 흇; 흇; ) HANGUL SYLLABLE HYUS
+D748;D748;1112 1172 11BB;D748;1112 1172 11BB; # (흈; 흈; 흈; 흈; 흈; ) HANGUL SYLLABLE HYUSS
+D749;D749;1112 1172 11BC;D749;1112 1172 11BC; # (흉; 흉; 흉; 흉; 흉; ) HANGUL SYLLABLE HYUNG
+D74A;D74A;1112 1172 11BD;D74A;1112 1172 11BD; # (흊; 흊; 흊; 흊; 흊; ) HANGUL SYLLABLE HYUJ
+D74B;D74B;1112 1172 11BE;D74B;1112 1172 11BE; # (흋; 흋; 흋; 흋; 흋; ) HANGUL SYLLABLE HYUC
+D74C;D74C;1112 1172 11BF;D74C;1112 1172 11BF; # (흌; 흌; 흌; 흌; 흌; ) HANGUL SYLLABLE HYUK
+D74D;D74D;1112 1172 11C0;D74D;1112 1172 11C0; # (흍; 흍; 흍; 흍; 흍; ) HANGUL SYLLABLE HYUT
+D74E;D74E;1112 1172 11C1;D74E;1112 1172 11C1; # (흎; 흎; 흎; 흎; 흎; ) HANGUL SYLLABLE HYUP
+D74F;D74F;1112 1172 11C2;D74F;1112 1172 11C2; # (흏; 흏; 흏; 흏; 흏; ) HANGUL SYLLABLE HYUH
+D750;D750;1112 1173;D750;1112 1173; # (흐; 흐; 흐; 흐; 흐; ) HANGUL SYLLABLE HEU
+D751;D751;1112 1173 11A8;D751;1112 1173 11A8; # (흑; 흑; 흑; 흑; 흑; ) HANGUL SYLLABLE HEUG
+D752;D752;1112 1173 11A9;D752;1112 1173 11A9; # (흒; 흒; 흒; 흒; 흒; ) HANGUL SYLLABLE HEUGG
+D753;D753;1112 1173 11AA;D753;1112 1173 11AA; # (흓; 흓; 흓; 흓; 흓; ) HANGUL SYLLABLE HEUGS
+D754;D754;1112 1173 11AB;D754;1112 1173 11AB; # (흔; 흔; 흔; 흔; 흔; ) HANGUL SYLLABLE HEUN
+D755;D755;1112 1173 11AC;D755;1112 1173 11AC; # (흕; 흕; 흕; 흕; 흕; ) HANGUL SYLLABLE HEUNJ
+D756;D756;1112 1173 11AD;D756;1112 1173 11AD; # (흖; 흖; 흖; 흖; 흖; ) HANGUL SYLLABLE HEUNH
+D757;D757;1112 1173 11AE;D757;1112 1173 11AE; # (흗; 흗; 흗; 흗; 흗; ) HANGUL SYLLABLE HEUD
+D758;D758;1112 1173 11AF;D758;1112 1173 11AF; # (흘; 흘; 흘; 흘; 흘; ) HANGUL SYLLABLE HEUL
+D759;D759;1112 1173 11B0;D759;1112 1173 11B0; # (흙; 흙; 흙; 흙; 흙; ) HANGUL SYLLABLE HEULG
+D75A;D75A;1112 1173 11B1;D75A;1112 1173 11B1; # (흚; 흚; 흚; 흚; 흚; ) HANGUL SYLLABLE HEULM
+D75B;D75B;1112 1173 11B2;D75B;1112 1173 11B2; # (흛; 흛; 흛; 흛; 흛; ) HANGUL SYLLABLE HEULB
+D75C;D75C;1112 1173 11B3;D75C;1112 1173 11B3; # (흜; 흜; 흜; 흜; 흜; ) HANGUL SYLLABLE HEULS
+D75D;D75D;1112 1173 11B4;D75D;1112 1173 11B4; # (흝; 흝; 흝; 흝; 흝; ) HANGUL SYLLABLE HEULT
+D75E;D75E;1112 1173 11B5;D75E;1112 1173 11B5; # (흞; 흞; 흞; 흞; 흞; ) HANGUL SYLLABLE HEULP
+D75F;D75F;1112 1173 11B6;D75F;1112 1173 11B6; # (흟; 흟; 흟; 흟; 흟; ) HANGUL SYLLABLE HEULH
+D760;D760;1112 1173 11B7;D760;1112 1173 11B7; # (흠; 흠; 흠; 흠; 흠; ) HANGUL SYLLABLE HEUM
+D761;D761;1112 1173 11B8;D761;1112 1173 11B8; # (흡; 흡; 흡; 흡; 흡; ) HANGUL SYLLABLE HEUB
+D762;D762;1112 1173 11B9;D762;1112 1173 11B9; # (흢; 흢; 흢; 흢; 흢; ) HANGUL SYLLABLE HEUBS
+D763;D763;1112 1173 11BA;D763;1112 1173 11BA; # (흣; 흣; 흣; 흣; 흣; ) HANGUL SYLLABLE HEUS
+D764;D764;1112 1173 11BB;D764;1112 1173 11BB; # (흤; 흤; 흤; 흤; 흤; ) HANGUL SYLLABLE HEUSS
+D765;D765;1112 1173 11BC;D765;1112 1173 11BC; # (흥; 흥; 흥; 흥; 흥; ) HANGUL SYLLABLE HEUNG
+D766;D766;1112 1173 11BD;D766;1112 1173 11BD; # (흦; 흦; 흦; 흦; 흦; ) HANGUL SYLLABLE HEUJ
+D767;D767;1112 1173 11BE;D767;1112 1173 11BE; # (흧; 흧; 흧; 흧; 흧; ) HANGUL SYLLABLE HEUC
+D768;D768;1112 1173 11BF;D768;1112 1173 11BF; # (흨; 흨; 흨; 흨; 흨; ) HANGUL SYLLABLE HEUK
+D769;D769;1112 1173 11C0;D769;1112 1173 11C0; # (흩; 흩; 흩; 흩; 흩; ) HANGUL SYLLABLE HEUT
+D76A;D76A;1112 1173 11C1;D76A;1112 1173 11C1; # (흪; 흪; 흪; 흪; 흪; ) HANGUL SYLLABLE HEUP
+D76B;D76B;1112 1173 11C2;D76B;1112 1173 11C2; # (흫; 흫; 흫; 흫; 흫; ) HANGUL SYLLABLE HEUH
+D76C;D76C;1112 1174;D76C;1112 1174; # (희; 희; 희; 희; 희; ) HANGUL SYLLABLE HYI
+D76D;D76D;1112 1174 11A8;D76D;1112 1174 11A8; # (흭; 흭; 흭; 흭; 흭; ) HANGUL SYLLABLE HYIG
+D76E;D76E;1112 1174 11A9;D76E;1112 1174 11A9; # (흮; 흮; 흮; 흮; 흮; ) HANGUL SYLLABLE HYIGG
+D76F;D76F;1112 1174 11AA;D76F;1112 1174 11AA; # (흯; 흯; 흯; 흯; 흯; ) HANGUL SYLLABLE HYIGS
+D770;D770;1112 1174 11AB;D770;1112 1174 11AB; # (흰; 흰; 흰; 흰; 흰; ) HANGUL SYLLABLE HYIN
+D771;D771;1112 1174 11AC;D771;1112 1174 11AC; # (흱; 흱; 흱; 흱; 흱; ) HANGUL SYLLABLE HYINJ
+D772;D772;1112 1174 11AD;D772;1112 1174 11AD; # (흲; 흲; 흲; 흲; 흲; ) HANGUL SYLLABLE HYINH
+D773;D773;1112 1174 11AE;D773;1112 1174 11AE; # (흳; 흳; 흳; 흳; 흳; ) HANGUL SYLLABLE HYID
+D774;D774;1112 1174 11AF;D774;1112 1174 11AF; # (흴; 흴; 흴; 흴; 흴; ) HANGUL SYLLABLE HYIL
+D775;D775;1112 1174 11B0;D775;1112 1174 11B0; # (흵; 흵; 흵; 흵; 흵; ) HANGUL SYLLABLE HYILG
+D776;D776;1112 1174 11B1;D776;1112 1174 11B1; # (흶; 흶; 흶; 흶; 흶; ) HANGUL SYLLABLE HYILM
+D777;D777;1112 1174 11B2;D777;1112 1174 11B2; # (흷; 흷; 흷; 흷; 흷; ) HANGUL SYLLABLE HYILB
+D778;D778;1112 1174 11B3;D778;1112 1174 11B3; # (흸; 흸; 흸; 흸; 흸; ) HANGUL SYLLABLE HYILS
+D779;D779;1112 1174 11B4;D779;1112 1174 11B4; # (흹; 흹; 흹; 흹; 흹; ) HANGUL SYLLABLE HYILT
+D77A;D77A;1112 1174 11B5;D77A;1112 1174 11B5; # (흺; 흺; 흺; 흺; 흺; ) HANGUL SYLLABLE HYILP
+D77B;D77B;1112 1174 11B6;D77B;1112 1174 11B6; # (흻; 흻; 흻; 흻; 흻; ) HANGUL SYLLABLE HYILH
+D77C;D77C;1112 1174 11B7;D77C;1112 1174 11B7; # (흼; 흼; 흼; 흼; 흼; ) HANGUL SYLLABLE HYIM
+D77D;D77D;1112 1174 11B8;D77D;1112 1174 11B8; # (흽; 흽; 흽; 흽; 흽; ) HANGUL SYLLABLE HYIB
+D77E;D77E;1112 1174 11B9;D77E;1112 1174 11B9; # (흾; 흾; 흾; 흾; 흾; ) HANGUL SYLLABLE HYIBS
+D77F;D77F;1112 1174 11BA;D77F;1112 1174 11BA; # (흿; 흿; 흿; 흿; 흿; ) HANGUL SYLLABLE HYIS
+D780;D780;1112 1174 11BB;D780;1112 1174 11BB; # (힀; 힀; 힀; 힀; 힀; ) HANGUL SYLLABLE HYISS
+D781;D781;1112 1174 11BC;D781;1112 1174 11BC; # (힁; 힁; 힁; 힁; 힁; ) HANGUL SYLLABLE HYING
+D782;D782;1112 1174 11BD;D782;1112 1174 11BD; # (힂; 힂; 힂; 힂; 힂; ) HANGUL SYLLABLE HYIJ
+D783;D783;1112 1174 11BE;D783;1112 1174 11BE; # (힃; 힃; 힃; 힃; 힃; ) HANGUL SYLLABLE HYIC
+D784;D784;1112 1174 11BF;D784;1112 1174 11BF; # (힄; 힄; 힄; 힄; 힄; ) HANGUL SYLLABLE HYIK
+D785;D785;1112 1174 11C0;D785;1112 1174 11C0; # (힅; 힅; 힅; 힅; 힅; ) HANGUL SYLLABLE HYIT
+D786;D786;1112 1174 11C1;D786;1112 1174 11C1; # (힆; 힆; 힆; 힆; 힆; ) HANGUL SYLLABLE HYIP
+D787;D787;1112 1174 11C2;D787;1112 1174 11C2; # (힇; 힇; 힇; 힇; 힇; ) HANGUL SYLLABLE HYIH
+D788;D788;1112 1175;D788;1112 1175; # (히; 히; 히; 히; 히; ) HANGUL SYLLABLE HI
+D789;D789;1112 1175 11A8;D789;1112 1175 11A8; # (힉; 힉; 힉; 힉; 힉; ) HANGUL SYLLABLE HIG
+D78A;D78A;1112 1175 11A9;D78A;1112 1175 11A9; # (힊; 힊; 힊; 힊; 힊; ) HANGUL SYLLABLE HIGG
+D78B;D78B;1112 1175 11AA;D78B;1112 1175 11AA; # (힋; 힋; 힋; 힋; 힋; ) HANGUL SYLLABLE HIGS
+D78C;D78C;1112 1175 11AB;D78C;1112 1175 11AB; # (힌; 힌; 힌; 힌; 힌; ) HANGUL SYLLABLE HIN
+D78D;D78D;1112 1175 11AC;D78D;1112 1175 11AC; # (힍; 힍; 힍; 힍; 힍; ) HANGUL SYLLABLE HINJ
+D78E;D78E;1112 1175 11AD;D78E;1112 1175 11AD; # (힎; 힎; 힎; 힎; 힎; ) HANGUL SYLLABLE HINH
+D78F;D78F;1112 1175 11AE;D78F;1112 1175 11AE; # (힏; 힏; 힏; 힏; 힏; ) HANGUL SYLLABLE HID
+D790;D790;1112 1175 11AF;D790;1112 1175 11AF; # (힐; 힐; 힐; 힐; 힐; ) HANGUL SYLLABLE HIL
+D791;D791;1112 1175 11B0;D791;1112 1175 11B0; # (힑; 힑; 힑; 힑; 힑; ) HANGUL SYLLABLE HILG
+D792;D792;1112 1175 11B1;D792;1112 1175 11B1; # (힒; 힒; 힒; 힒; 힒; ) HANGUL SYLLABLE HILM
+D793;D793;1112 1175 11B2;D793;1112 1175 11B2; # (힓; 힓; 힓; 힓; 힓; ) HANGUL SYLLABLE HILB
+D794;D794;1112 1175 11B3;D794;1112 1175 11B3; # (힔; 힔; 힔; 힔; 힔; ) HANGUL SYLLABLE HILS
+D795;D795;1112 1175 11B4;D795;1112 1175 11B4; # (힕; 힕; 힕; 힕; 힕; ) HANGUL SYLLABLE HILT
+D796;D796;1112 1175 11B5;D796;1112 1175 11B5; # (힖; 힖; 힖; 힖; 힖; ) HANGUL SYLLABLE HILP
+D797;D797;1112 1175 11B6;D797;1112 1175 11B6; # (힗; 힗; 힗; 힗; 힗; ) HANGUL SYLLABLE HILH
+D798;D798;1112 1175 11B7;D798;1112 1175 11B7; # (힘; 힘; 힘; 힘; 힘; ) HANGUL SYLLABLE HIM
+D799;D799;1112 1175 11B8;D799;1112 1175 11B8; # (힙; 힙; 힙; 힙; 힙; ) HANGUL SYLLABLE HIB
+D79A;D79A;1112 1175 11B9;D79A;1112 1175 11B9; # (힚; 힚; 힚; 힚; 힚; ) HANGUL SYLLABLE HIBS
+D79B;D79B;1112 1175 11BA;D79B;1112 1175 11BA; # (힛; 힛; 힛; 힛; 힛; ) HANGUL SYLLABLE HIS
+D79C;D79C;1112 1175 11BB;D79C;1112 1175 11BB; # (힜; 힜; 힜; 힜; 힜; ) HANGUL SYLLABLE HISS
+D79D;D79D;1112 1175 11BC;D79D;1112 1175 11BC; # (힝; 힝; 힝; 힝; 힝; ) HANGUL SYLLABLE HING
+D79E;D79E;1112 1175 11BD;D79E;1112 1175 11BD; # (힞; 힞; 힞; 힞; 힞; ) HANGUL SYLLABLE HIJ
+D79F;D79F;1112 1175 11BE;D79F;1112 1175 11BE; # (힟; 힟; 힟; 힟; 힟; ) HANGUL SYLLABLE HIC
+D7A0;D7A0;1112 1175 11BF;D7A0;1112 1175 11BF; # (힠; 힠; 힠; 힠; 힠; ) HANGUL SYLLABLE HIK
+D7A1;D7A1;1112 1175 11C0;D7A1;1112 1175 11C0; # (힡; 힡; 힡; 힡; 힡; ) HANGUL SYLLABLE HIT
+D7A2;D7A2;1112 1175 11C1;D7A2;1112 1175 11C1; # (힢; 힢; 힢; 힢; 힢; ) HANGUL SYLLABLE HIP
+D7A3;D7A3;1112 1175 11C2;D7A3;1112 1175 11C2; # (힣; 힣; 힣; 힣; 힣; ) HANGUL SYLLABLE HIH
+F900;8C48;8C48;8C48;8C48; # (豈; 豈; 豈; 豈; 豈; ) CJK COMPATIBILITY IDEOGRAPH-F900
+F901;66F4;66F4;66F4;66F4; # (更; 更; 更; 更; 更; ) CJK COMPATIBILITY IDEOGRAPH-F901
+F902;8ECA;8ECA;8ECA;8ECA; # (車; 車; 車; 車; 車; ) CJK COMPATIBILITY IDEOGRAPH-F902
+F903;8CC8;8CC8;8CC8;8CC8; # (賈; 賈; 賈; 賈; 賈; ) CJK COMPATIBILITY IDEOGRAPH-F903
+F904;6ED1;6ED1;6ED1;6ED1; # (滑; 滑; 滑; 滑; 滑; ) CJK COMPATIBILITY IDEOGRAPH-F904
+F905;4E32;4E32;4E32;4E32; # (串; 串; 串; 串; 串; ) CJK COMPATIBILITY IDEOGRAPH-F905
+F906;53E5;53E5;53E5;53E5; # (句; 句; 句; 句; 句; ) CJK COMPATIBILITY IDEOGRAPH-F906
+F907;9F9C;9F9C;9F9C;9F9C; # (龜; 龜; 龜; 龜; 龜; ) CJK COMPATIBILITY IDEOGRAPH-F907
+F908;9F9C;9F9C;9F9C;9F9C; # (龜; 龜; 龜; 龜; 龜; ) CJK COMPATIBILITY IDEOGRAPH-F908
+F909;5951;5951;5951;5951; # (契; 契; 契; 契; 契; ) CJK COMPATIBILITY IDEOGRAPH-F909
+F90A;91D1;91D1;91D1;91D1; # (金; 金; 金; 金; 金; ) CJK COMPATIBILITY IDEOGRAPH-F90A
+F90B;5587;5587;5587;5587; # (喇; 喇; 喇; 喇; 喇; ) CJK COMPATIBILITY IDEOGRAPH-F90B
+F90C;5948;5948;5948;5948; # (奈; 奈; 奈; 奈; 奈; ) CJK COMPATIBILITY IDEOGRAPH-F90C
+F90D;61F6;61F6;61F6;61F6; # (懶; 懶; 懶; 懶; 懶; ) CJK COMPATIBILITY IDEOGRAPH-F90D
+F90E;7669;7669;7669;7669; # (癩; 癩; 癩; 癩; 癩; ) CJK COMPATIBILITY IDEOGRAPH-F90E
+F90F;7F85;7F85;7F85;7F85; # (羅; 羅; 羅; 羅; 羅; ) CJK COMPATIBILITY IDEOGRAPH-F90F
+F910;863F;863F;863F;863F; # (蘿; 蘿; 蘿; 蘿; 蘿; ) CJK COMPATIBILITY IDEOGRAPH-F910
+F911;87BA;87BA;87BA;87BA; # (螺; 螺; 螺; 螺; 螺; ) CJK COMPATIBILITY IDEOGRAPH-F911
+F912;88F8;88F8;88F8;88F8; # (裸; 裸; 裸; 裸; 裸; ) CJK COMPATIBILITY IDEOGRAPH-F912
+F913;908F;908F;908F;908F; # (邏; 邏; 邏; 邏; 邏; ) CJK COMPATIBILITY IDEOGRAPH-F913
+F914;6A02;6A02;6A02;6A02; # (樂; 樂; 樂; 樂; 樂; ) CJK COMPATIBILITY IDEOGRAPH-F914
+F915;6D1B;6D1B;6D1B;6D1B; # (洛; 洛; 洛; 洛; 洛; ) CJK COMPATIBILITY IDEOGRAPH-F915
+F916;70D9;70D9;70D9;70D9; # (烙; 烙; 烙; 烙; 烙; ) CJK COMPATIBILITY IDEOGRAPH-F916
+F917;73DE;73DE;73DE;73DE; # (珞; 珞; 珞; 珞; 珞; ) CJK COMPATIBILITY IDEOGRAPH-F917
+F918;843D;843D;843D;843D; # (落; 落; 落; 落; 落; ) CJK COMPATIBILITY IDEOGRAPH-F918
+F919;916A;916A;916A;916A; # (酪; 酪; 酪; 酪; 酪; ) CJK COMPATIBILITY IDEOGRAPH-F919
+F91A;99F1;99F1;99F1;99F1; # (駱; 駱; 駱; 駱; 駱; ) CJK COMPATIBILITY IDEOGRAPH-F91A
+F91B;4E82;4E82;4E82;4E82; # (亂; 亂; 亂; 亂; 亂; ) CJK COMPATIBILITY IDEOGRAPH-F91B
+F91C;5375;5375;5375;5375; # (卵; 卵; 卵; 卵; 卵; ) CJK COMPATIBILITY IDEOGRAPH-F91C
+F91D;6B04;6B04;6B04;6B04; # (欄; 欄; 欄; 欄; 欄; ) CJK COMPATIBILITY IDEOGRAPH-F91D
+F91E;721B;721B;721B;721B; # (爛; 爛; 爛; 爛; 爛; ) CJK COMPATIBILITY IDEOGRAPH-F91E
+F91F;862D;862D;862D;862D; # (蘭; 蘭; 蘭; 蘭; 蘭; ) CJK COMPATIBILITY IDEOGRAPH-F91F
+F920;9E1E;9E1E;9E1E;9E1E; # (鸞; 鸞; 鸞; 鸞; 鸞; ) CJK COMPATIBILITY IDEOGRAPH-F920
+F921;5D50;5D50;5D50;5D50; # (嵐; 嵐; 嵐; 嵐; 嵐; ) CJK COMPATIBILITY IDEOGRAPH-F921
+F922;6FEB;6FEB;6FEB;6FEB; # (濫; 濫; 濫; 濫; 濫; ) CJK COMPATIBILITY IDEOGRAPH-F922
+F923;85CD;85CD;85CD;85CD; # (藍; 藍; 藍; 藍; 藍; ) CJK COMPATIBILITY IDEOGRAPH-F923
+F924;8964;8964;8964;8964; # (襤; 襤; 襤; 襤; 襤; ) CJK COMPATIBILITY IDEOGRAPH-F924
+F925;62C9;62C9;62C9;62C9; # (拉; 拉; 拉; 拉; 拉; ) CJK COMPATIBILITY IDEOGRAPH-F925
+F926;81D8;81D8;81D8;81D8; # (臘; 臘; 臘; 臘; 臘; ) CJK COMPATIBILITY IDEOGRAPH-F926
+F927;881F;881F;881F;881F; # (蠟; 蠟; 蠟; 蠟; 蠟; ) CJK COMPATIBILITY IDEOGRAPH-F927
+F928;5ECA;5ECA;5ECA;5ECA; # (廊; 廊; 廊; 廊; 廊; ) CJK COMPATIBILITY IDEOGRAPH-F928
+F929;6717;6717;6717;6717; # (朗; 朗; 朗; 朗; 朗; ) CJK COMPATIBILITY IDEOGRAPH-F929
+F92A;6D6A;6D6A;6D6A;6D6A; # (浪; 浪; 浪; 浪; 浪; ) CJK COMPATIBILITY IDEOGRAPH-F92A
+F92B;72FC;72FC;72FC;72FC; # (狼; 狼; 狼; 狼; 狼; ) CJK COMPATIBILITY IDEOGRAPH-F92B
+F92C;90CE;90CE;90CE;90CE; # (郎; 郎; 郎; 郎; 郎; ) CJK COMPATIBILITY IDEOGRAPH-F92C
+F92D;4F86;4F86;4F86;4F86; # (來; 來; 來; 來; 來; ) CJK COMPATIBILITY IDEOGRAPH-F92D
+F92E;51B7;51B7;51B7;51B7; # (冷; 冷; 冷; 冷; 冷; ) CJK COMPATIBILITY IDEOGRAPH-F92E
+F92F;52DE;52DE;52DE;52DE; # (勞; 勞; 勞; 勞; 勞; ) CJK COMPATIBILITY IDEOGRAPH-F92F
+F930;64C4;64C4;64C4;64C4; # (擄; 擄; 擄; 擄; 擄; ) CJK COMPATIBILITY IDEOGRAPH-F930
+F931;6AD3;6AD3;6AD3;6AD3; # (櫓; 櫓; 櫓; 櫓; 櫓; ) CJK COMPATIBILITY IDEOGRAPH-F931
+F932;7210;7210;7210;7210; # (爐; 爐; 爐; 爐; 爐; ) CJK COMPATIBILITY IDEOGRAPH-F932
+F933;76E7;76E7;76E7;76E7; # (盧; 盧; 盧; 盧; 盧; ) CJK COMPATIBILITY IDEOGRAPH-F933
+F934;8001;8001;8001;8001; # (老; 老; 老; 老; 老; ) CJK COMPATIBILITY IDEOGRAPH-F934
+F935;8606;8606;8606;8606; # (蘆; 蘆; 蘆; 蘆; 蘆; ) CJK COMPATIBILITY IDEOGRAPH-F935
+F936;865C;865C;865C;865C; # (虜; 虜; 虜; 虜; 虜; ) CJK COMPATIBILITY IDEOGRAPH-F936
+F937;8DEF;8DEF;8DEF;8DEF; # (路; 路; 路; 路; 路; ) CJK COMPATIBILITY IDEOGRAPH-F937
+F938;9732;9732;9732;9732; # (露; 露; 露; 露; 露; ) CJK COMPATIBILITY IDEOGRAPH-F938
+F939;9B6F;9B6F;9B6F;9B6F; # (魯; 魯; 魯; 魯; 魯; ) CJK COMPATIBILITY IDEOGRAPH-F939
+F93A;9DFA;9DFA;9DFA;9DFA; # (鷺; 鷺; 鷺; 鷺; 鷺; ) CJK COMPATIBILITY IDEOGRAPH-F93A
+F93B;788C;788C;788C;788C; # (碌; 碌; 碌; 碌; 碌; ) CJK COMPATIBILITY IDEOGRAPH-F93B
+F93C;797F;797F;797F;797F; # (祿; 祿; 祿; 祿; 祿; ) CJK COMPATIBILITY IDEOGRAPH-F93C
+F93D;7DA0;7DA0;7DA0;7DA0; # (綠; 綠; 綠; 綠; 綠; ) CJK COMPATIBILITY IDEOGRAPH-F93D
+F93E;83C9;83C9;83C9;83C9; # (菉; 菉; 菉; 菉; 菉; ) CJK COMPATIBILITY IDEOGRAPH-F93E
+F93F;9304;9304;9304;9304; # (錄; 錄; 錄; 錄; 錄; ) CJK COMPATIBILITY IDEOGRAPH-F93F
+F940;9E7F;9E7F;9E7F;9E7F; # (鹿; 鹿; 鹿; 鹿; 鹿; ) CJK COMPATIBILITY IDEOGRAPH-F940
+F941;8AD6;8AD6;8AD6;8AD6; # (論; 論; 論; 論; 論; ) CJK COMPATIBILITY IDEOGRAPH-F941
+F942;58DF;58DF;58DF;58DF; # (壟; 壟; 壟; 壟; 壟; ) CJK COMPATIBILITY IDEOGRAPH-F942
+F943;5F04;5F04;5F04;5F04; # (弄; 弄; 弄; 弄; 弄; ) CJK COMPATIBILITY IDEOGRAPH-F943
+F944;7C60;7C60;7C60;7C60; # (籠; 籠; 籠; 籠; 籠; ) CJK COMPATIBILITY IDEOGRAPH-F944
+F945;807E;807E;807E;807E; # (聾; 聾; 聾; 聾; 聾; ) CJK COMPATIBILITY IDEOGRAPH-F945
+F946;7262;7262;7262;7262; # (牢; 牢; 牢; 牢; 牢; ) CJK COMPATIBILITY IDEOGRAPH-F946
+F947;78CA;78CA;78CA;78CA; # (磊; 磊; 磊; 磊; 磊; ) CJK COMPATIBILITY IDEOGRAPH-F947
+F948;8CC2;8CC2;8CC2;8CC2; # (賂; 賂; 賂; 賂; 賂; ) CJK COMPATIBILITY IDEOGRAPH-F948
+F949;96F7;96F7;96F7;96F7; # (雷; 雷; 雷; 雷; 雷; ) CJK COMPATIBILITY IDEOGRAPH-F949
+F94A;58D8;58D8;58D8;58D8; # (壘; 壘; 壘; 壘; 壘; ) CJK COMPATIBILITY IDEOGRAPH-F94A
+F94B;5C62;5C62;5C62;5C62; # (屢; 屢; 屢; 屢; 屢; ) CJK COMPATIBILITY IDEOGRAPH-F94B
+F94C;6A13;6A13;6A13;6A13; # (樓; 樓; 樓; 樓; 樓; ) CJK COMPATIBILITY IDEOGRAPH-F94C
+F94D;6DDA;6DDA;6DDA;6DDA; # (淚; 淚; 淚; 淚; 淚; ) CJK COMPATIBILITY IDEOGRAPH-F94D
+F94E;6F0F;6F0F;6F0F;6F0F; # (漏; 漏; 漏; 漏; 漏; ) CJK COMPATIBILITY IDEOGRAPH-F94E
+F94F;7D2F;7D2F;7D2F;7D2F; # (累; 累; 累; 累; 累; ) CJK COMPATIBILITY IDEOGRAPH-F94F
+F950;7E37;7E37;7E37;7E37; # (縷; 縷; 縷; 縷; 縷; ) CJK COMPATIBILITY IDEOGRAPH-F950
+F951;964B;964B;964B;964B; # (陋; 陋; 陋; 陋; 陋; ) CJK COMPATIBILITY IDEOGRAPH-F951
+F952;52D2;52D2;52D2;52D2; # (勒; 勒; 勒; 勒; 勒; ) CJK COMPATIBILITY IDEOGRAPH-F952
+F953;808B;808B;808B;808B; # (肋; 肋; 肋; 肋; 肋; ) CJK COMPATIBILITY IDEOGRAPH-F953
+F954;51DC;51DC;51DC;51DC; # (凜; 凜; 凜; 凜; 凜; ) CJK COMPATIBILITY IDEOGRAPH-F954
+F955;51CC;51CC;51CC;51CC; # (凌; 凌; 凌; 凌; 凌; ) CJK COMPATIBILITY IDEOGRAPH-F955
+F956;7A1C;7A1C;7A1C;7A1C; # (稜; 稜; 稜; 稜; 稜; ) CJK COMPATIBILITY IDEOGRAPH-F956
+F957;7DBE;7DBE;7DBE;7DBE; # (綾; 綾; 綾; 綾; 綾; ) CJK COMPATIBILITY IDEOGRAPH-F957
+F958;83F1;83F1;83F1;83F1; # (菱; 菱; 菱; 菱; 菱; ) CJK COMPATIBILITY IDEOGRAPH-F958
+F959;9675;9675;9675;9675; # (陵; 陵; 陵; 陵; 陵; ) CJK COMPATIBILITY IDEOGRAPH-F959
+F95A;8B80;8B80;8B80;8B80; # (讀; 讀; 讀; 讀; 讀; ) CJK COMPATIBILITY IDEOGRAPH-F95A
+F95B;62CF;62CF;62CF;62CF; # (拏; 拏; 拏; 拏; 拏; ) CJK COMPATIBILITY IDEOGRAPH-F95B
+F95C;6A02;6A02;6A02;6A02; # (樂; 樂; 樂; 樂; 樂; ) CJK COMPATIBILITY IDEOGRAPH-F95C
+F95D;8AFE;8AFE;8AFE;8AFE; # (諾; 諾; 諾; 諾; 諾; ) CJK COMPATIBILITY IDEOGRAPH-F95D
+F95E;4E39;4E39;4E39;4E39; # (丹; 丹; 丹; 丹; 丹; ) CJK COMPATIBILITY IDEOGRAPH-F95E
+F95F;5BE7;5BE7;5BE7;5BE7; # (寧; 寧; 寧; 寧; 寧; ) CJK COMPATIBILITY IDEOGRAPH-F95F
+F960;6012;6012;6012;6012; # (怒; 怒; 怒; 怒; 怒; ) CJK COMPATIBILITY IDEOGRAPH-F960
+F961;7387;7387;7387;7387; # (率; 率; 率; 率; 率; ) CJK COMPATIBILITY IDEOGRAPH-F961
+F962;7570;7570;7570;7570; # (異; 異; 異; 異; 異; ) CJK COMPATIBILITY IDEOGRAPH-F962
+F963;5317;5317;5317;5317; # (北; 北; 北; 北; 北; ) CJK COMPATIBILITY IDEOGRAPH-F963
+F964;78FB;78FB;78FB;78FB; # (磻; 磻; 磻; 磻; 磻; ) CJK COMPATIBILITY IDEOGRAPH-F964
+F965;4FBF;4FBF;4FBF;4FBF; # (便; 便; 便; 便; 便; ) CJK COMPATIBILITY IDEOGRAPH-F965
+F966;5FA9;5FA9;5FA9;5FA9; # (復; 復; 復; 復; 復; ) CJK COMPATIBILITY IDEOGRAPH-F966
+F967;4E0D;4E0D;4E0D;4E0D; # (不; 不; 不; 不; 不; ) CJK COMPATIBILITY IDEOGRAPH-F967
+F968;6CCC;6CCC;6CCC;6CCC; # (泌; 泌; 泌; 泌; 泌; ) CJK COMPATIBILITY IDEOGRAPH-F968
+F969;6578;6578;6578;6578; # (數; 數; 數; 數; 數; ) CJK COMPATIBILITY IDEOGRAPH-F969
+F96A;7D22;7D22;7D22;7D22; # (索; 索; 索; 索; 索; ) CJK COMPATIBILITY IDEOGRAPH-F96A
+F96B;53C3;53C3;53C3;53C3; # (參; 參; 參; 參; 參; ) CJK COMPATIBILITY IDEOGRAPH-F96B
+F96C;585E;585E;585E;585E; # (塞; 塞; 塞; 塞; 塞; ) CJK COMPATIBILITY IDEOGRAPH-F96C
+F96D;7701;7701;7701;7701; # (省; 省; 省; 省; 省; ) CJK COMPATIBILITY IDEOGRAPH-F96D
+F96E;8449;8449;8449;8449; # (葉; 葉; 葉; 葉; 葉; ) CJK COMPATIBILITY IDEOGRAPH-F96E
+F96F;8AAA;8AAA;8AAA;8AAA; # (說; 說; 說; 說; 說; ) CJK COMPATIBILITY IDEOGRAPH-F96F
+F970;6BBA;6BBA;6BBA;6BBA; # (殺; 殺; 殺; 殺; 殺; ) CJK COMPATIBILITY IDEOGRAPH-F970
+F971;8FB0;8FB0;8FB0;8FB0; # (辰; 辰; 辰; 辰; 辰; ) CJK COMPATIBILITY IDEOGRAPH-F971
+F972;6C88;6C88;6C88;6C88; # (沈; 沈; 沈; 沈; 沈; ) CJK COMPATIBILITY IDEOGRAPH-F972
+F973;62FE;62FE;62FE;62FE; # (拾; 拾; 拾; 拾; 拾; ) CJK COMPATIBILITY IDEOGRAPH-F973
+F974;82E5;82E5;82E5;82E5; # (若; 若; 若; 若; 若; ) CJK COMPATIBILITY IDEOGRAPH-F974
+F975;63A0;63A0;63A0;63A0; # (掠; 掠; 掠; 掠; 掠; ) CJK COMPATIBILITY IDEOGRAPH-F975
+F976;7565;7565;7565;7565; # (略; 略; 略; 略; 略; ) CJK COMPATIBILITY IDEOGRAPH-F976
+F977;4EAE;4EAE;4EAE;4EAE; # (亮; 亮; 亮; 亮; 亮; ) CJK COMPATIBILITY IDEOGRAPH-F977
+F978;5169;5169;5169;5169; # (兩; 兩; 兩; 兩; 兩; ) CJK COMPATIBILITY IDEOGRAPH-F978
+F979;51C9;51C9;51C9;51C9; # (凉; 凉; 凉; 凉; 凉; ) CJK COMPATIBILITY IDEOGRAPH-F979
+F97A;6881;6881;6881;6881; # (梁; 梁; 梁; 梁; 梁; ) CJK COMPATIBILITY IDEOGRAPH-F97A
+F97B;7CE7;7CE7;7CE7;7CE7; # (糧; 糧; 糧; 糧; 糧; ) CJK COMPATIBILITY IDEOGRAPH-F97B
+F97C;826F;826F;826F;826F; # (良; 良; 良; 良; 良; ) CJK COMPATIBILITY IDEOGRAPH-F97C
+F97D;8AD2;8AD2;8AD2;8AD2; # (諒; 諒; 諒; 諒; 諒; ) CJK COMPATIBILITY IDEOGRAPH-F97D
+F97E;91CF;91CF;91CF;91CF; # (量; 量; 量; 量; 量; ) CJK COMPATIBILITY IDEOGRAPH-F97E
+F97F;52F5;52F5;52F5;52F5; # (勵; 勵; 勵; 勵; 勵; ) CJK COMPATIBILITY IDEOGRAPH-F97F
+F980;5442;5442;5442;5442; # (呂; 呂; 呂; 呂; 呂; ) CJK COMPATIBILITY IDEOGRAPH-F980
+F981;5973;5973;5973;5973; # (女; 女; 女; 女; 女; ) CJK COMPATIBILITY IDEOGRAPH-F981
+F982;5EEC;5EEC;5EEC;5EEC; # (廬; 廬; 廬; 廬; 廬; ) CJK COMPATIBILITY IDEOGRAPH-F982
+F983;65C5;65C5;65C5;65C5; # (旅; 旅; 旅; 旅; 旅; ) CJK COMPATIBILITY IDEOGRAPH-F983
+F984;6FFE;6FFE;6FFE;6FFE; # (濾; 濾; 濾; 濾; 濾; ) CJK COMPATIBILITY IDEOGRAPH-F984
+F985;792A;792A;792A;792A; # (礪; 礪; 礪; 礪; 礪; ) CJK COMPATIBILITY IDEOGRAPH-F985
+F986;95AD;95AD;95AD;95AD; # (閭; 閭; 閭; 閭; 閭; ) CJK COMPATIBILITY IDEOGRAPH-F986
+F987;9A6A;9A6A;9A6A;9A6A; # (驪; 驪; 驪; 驪; 驪; ) CJK COMPATIBILITY IDEOGRAPH-F987
+F988;9E97;9E97;9E97;9E97; # (麗; 麗; 麗; 麗; 麗; ) CJK COMPATIBILITY IDEOGRAPH-F988
+F989;9ECE;9ECE;9ECE;9ECE; # (黎; 黎; 黎; 黎; 黎; ) CJK COMPATIBILITY IDEOGRAPH-F989
+F98A;529B;529B;529B;529B; # (力; 力; 力; 力; 力; ) CJK COMPATIBILITY IDEOGRAPH-F98A
+F98B;66C6;66C6;66C6;66C6; # (曆; 曆; 曆; 曆; 曆; ) CJK COMPATIBILITY IDEOGRAPH-F98B
+F98C;6B77;6B77;6B77;6B77; # (歷; 歷; 歷; 歷; 歷; ) CJK COMPATIBILITY IDEOGRAPH-F98C
+F98D;8F62;8F62;8F62;8F62; # (轢; 轢; 轢; 轢; 轢; ) CJK COMPATIBILITY IDEOGRAPH-F98D
+F98E;5E74;5E74;5E74;5E74; # (年; 年; 年; 年; 年; ) CJK COMPATIBILITY IDEOGRAPH-F98E
+F98F;6190;6190;6190;6190; # (憐; 憐; 憐; 憐; 憐; ) CJK COMPATIBILITY IDEOGRAPH-F98F
+F990;6200;6200;6200;6200; # (戀; 戀; 戀; 戀; 戀; ) CJK COMPATIBILITY IDEOGRAPH-F990
+F991;649A;649A;649A;649A; # (撚; 撚; 撚; 撚; 撚; ) CJK COMPATIBILITY IDEOGRAPH-F991
+F992;6F23;6F23;6F23;6F23; # (漣; 漣; 漣; 漣; 漣; ) CJK COMPATIBILITY IDEOGRAPH-F992
+F993;7149;7149;7149;7149; # (煉; 煉; 煉; 煉; 煉; ) CJK COMPATIBILITY IDEOGRAPH-F993
+F994;7489;7489;7489;7489; # (璉; 璉; 璉; 璉; 璉; ) CJK COMPATIBILITY IDEOGRAPH-F994
+F995;79CA;79CA;79CA;79CA; # (秊; 秊; 秊; 秊; 秊; ) CJK COMPATIBILITY IDEOGRAPH-F995
+F996;7DF4;7DF4;7DF4;7DF4; # (練; 練; 練; 練; 練; ) CJK COMPATIBILITY IDEOGRAPH-F996
+F997;806F;806F;806F;806F; # (聯; 聯; 聯; 聯; 聯; ) CJK COMPATIBILITY IDEOGRAPH-F997
+F998;8F26;8F26;8F26;8F26; # (輦; 輦; 輦; 輦; 輦; ) CJK COMPATIBILITY IDEOGRAPH-F998
+F999;84EE;84EE;84EE;84EE; # (蓮; 蓮; 蓮; 蓮; 蓮; ) CJK COMPATIBILITY IDEOGRAPH-F999
+F99A;9023;9023;9023;9023; # (連; 連; 連; 連; 連; ) CJK COMPATIBILITY IDEOGRAPH-F99A
+F99B;934A;934A;934A;934A; # (鍊; 鍊; 鍊; 鍊; 鍊; ) CJK COMPATIBILITY IDEOGRAPH-F99B
+F99C;5217;5217;5217;5217; # (列; 列; 列; 列; 列; ) CJK COMPATIBILITY IDEOGRAPH-F99C
+F99D;52A3;52A3;52A3;52A3; # (劣; 劣; 劣; 劣; 劣; ) CJK COMPATIBILITY IDEOGRAPH-F99D
+F99E;54BD;54BD;54BD;54BD; # (咽; 咽; 咽; 咽; 咽; ) CJK COMPATIBILITY IDEOGRAPH-F99E
+F99F;70C8;70C8;70C8;70C8; # (烈; 烈; 烈; 烈; 烈; ) CJK COMPATIBILITY IDEOGRAPH-F99F
+F9A0;88C2;88C2;88C2;88C2; # (裂; 裂; 裂; 裂; 裂; ) CJK COMPATIBILITY IDEOGRAPH-F9A0
+F9A1;8AAA;8AAA;8AAA;8AAA; # (說; 說; 說; 說; 說; ) CJK COMPATIBILITY IDEOGRAPH-F9A1
+F9A2;5EC9;5EC9;5EC9;5EC9; # (廉; 廉; 廉; 廉; 廉; ) CJK COMPATIBILITY IDEOGRAPH-F9A2
+F9A3;5FF5;5FF5;5FF5;5FF5; # (念; 念; 念; 念; 念; ) CJK COMPATIBILITY IDEOGRAPH-F9A3
+F9A4;637B;637B;637B;637B; # (捻; 捻; 捻; 捻; 捻; ) CJK COMPATIBILITY IDEOGRAPH-F9A4
+F9A5;6BAE;6BAE;6BAE;6BAE; # (殮; 殮; 殮; 殮; 殮; ) CJK COMPATIBILITY IDEOGRAPH-F9A5
+F9A6;7C3E;7C3E;7C3E;7C3E; # (簾; 簾; 簾; 簾; 簾; ) CJK COMPATIBILITY IDEOGRAPH-F9A6
+F9A7;7375;7375;7375;7375; # (獵; 獵; 獵; 獵; 獵; ) CJK COMPATIBILITY IDEOGRAPH-F9A7
+F9A8;4EE4;4EE4;4EE4;4EE4; # (令; 令; 令; 令; 令; ) CJK COMPATIBILITY IDEOGRAPH-F9A8
+F9A9;56F9;56F9;56F9;56F9; # (囹; 囹; 囹; 囹; 囹; ) CJK COMPATIBILITY IDEOGRAPH-F9A9
+F9AA;5BE7;5BE7;5BE7;5BE7; # (寧; 寧; 寧; 寧; 寧; ) CJK COMPATIBILITY IDEOGRAPH-F9AA
+F9AB;5DBA;5DBA;5DBA;5DBA; # (嶺; 嶺; 嶺; 嶺; 嶺; ) CJK COMPATIBILITY IDEOGRAPH-F9AB
+F9AC;601C;601C;601C;601C; # (怜; 怜; 怜; 怜; 怜; ) CJK COMPATIBILITY IDEOGRAPH-F9AC
+F9AD;73B2;73B2;73B2;73B2; # (玲; 玲; 玲; 玲; 玲; ) CJK COMPATIBILITY IDEOGRAPH-F9AD
+F9AE;7469;7469;7469;7469; # (瑩; 瑩; 瑩; 瑩; 瑩; ) CJK COMPATIBILITY IDEOGRAPH-F9AE
+F9AF;7F9A;7F9A;7F9A;7F9A; # (羚; 羚; 羚; 羚; 羚; ) CJK COMPATIBILITY IDEOGRAPH-F9AF
+F9B0;8046;8046;8046;8046; # (聆; 聆; 聆; 聆; 聆; ) CJK COMPATIBILITY IDEOGRAPH-F9B0
+F9B1;9234;9234;9234;9234; # (鈴; 鈴; 鈴; 鈴; 鈴; ) CJK COMPATIBILITY IDEOGRAPH-F9B1
+F9B2;96F6;96F6;96F6;96F6; # (零; 零; 零; 零; 零; ) CJK COMPATIBILITY IDEOGRAPH-F9B2
+F9B3;9748;9748;9748;9748; # (靈; 靈; 靈; 靈; 靈; ) CJK COMPATIBILITY IDEOGRAPH-F9B3
+F9B4;9818;9818;9818;9818; # (領; 領; 領; 領; 領; ) CJK COMPATIBILITY IDEOGRAPH-F9B4
+F9B5;4F8B;4F8B;4F8B;4F8B; # (例; 例; 例; 例; 例; ) CJK COMPATIBILITY IDEOGRAPH-F9B5
+F9B6;79AE;79AE;79AE;79AE; # (禮; 禮; 禮; 禮; 禮; ) CJK COMPATIBILITY IDEOGRAPH-F9B6
+F9B7;91B4;91B4;91B4;91B4; # (醴; 醴; 醴; 醴; 醴; ) CJK COMPATIBILITY IDEOGRAPH-F9B7
+F9B8;96B8;96B8;96B8;96B8; # (隸; 隸; 隸; 隸; 隸; ) CJK COMPATIBILITY IDEOGRAPH-F9B8
+F9B9;60E1;60E1;60E1;60E1; # (惡; 惡; 惡; 惡; 惡; ) CJK COMPATIBILITY IDEOGRAPH-F9B9
+F9BA;4E86;4E86;4E86;4E86; # (了; 了; 了; 了; 了; ) CJK COMPATIBILITY IDEOGRAPH-F9BA
+F9BB;50DA;50DA;50DA;50DA; # (僚; 僚; 僚; 僚; 僚; ) CJK COMPATIBILITY IDEOGRAPH-F9BB
+F9BC;5BEE;5BEE;5BEE;5BEE; # (寮; 寮; 寮; 寮; 寮; ) CJK COMPATIBILITY IDEOGRAPH-F9BC
+F9BD;5C3F;5C3F;5C3F;5C3F; # (尿; 尿; 尿; 尿; 尿; ) CJK COMPATIBILITY IDEOGRAPH-F9BD
+F9BE;6599;6599;6599;6599; # (料; 料; 料; 料; 料; ) CJK COMPATIBILITY IDEOGRAPH-F9BE
+F9BF;6A02;6A02;6A02;6A02; # (樂; 樂; 樂; 樂; 樂; ) CJK COMPATIBILITY IDEOGRAPH-F9BF
+F9C0;71CE;71CE;71CE;71CE; # (燎; 燎; 燎; 燎; 燎; ) CJK COMPATIBILITY IDEOGRAPH-F9C0
+F9C1;7642;7642;7642;7642; # (療; 療; 療; 療; 療; ) CJK COMPATIBILITY IDEOGRAPH-F9C1
+F9C2;84FC;84FC;84FC;84FC; # (蓼; 蓼; 蓼; 蓼; 蓼; ) CJK COMPATIBILITY IDEOGRAPH-F9C2
+F9C3;907C;907C;907C;907C; # (遼; 遼; 遼; 遼; 遼; ) CJK COMPATIBILITY IDEOGRAPH-F9C3
+F9C4;9F8D;9F8D;9F8D;9F8D; # (龍; 龍; 龍; 龍; 龍; ) CJK COMPATIBILITY IDEOGRAPH-F9C4
+F9C5;6688;6688;6688;6688; # (暈; 暈; 暈; 暈; 暈; ) CJK COMPATIBILITY IDEOGRAPH-F9C5
+F9C6;962E;962E;962E;962E; # (阮; 阮; 阮; 阮; 阮; ) CJK COMPATIBILITY IDEOGRAPH-F9C6
+F9C7;5289;5289;5289;5289; # (劉; 劉; 劉; 劉; 劉; ) CJK COMPATIBILITY IDEOGRAPH-F9C7
+F9C8;677B;677B;677B;677B; # (杻; 杻; 杻; 杻; 杻; ) CJK COMPATIBILITY IDEOGRAPH-F9C8
+F9C9;67F3;67F3;67F3;67F3; # (柳; 柳; 柳; 柳; 柳; ) CJK COMPATIBILITY IDEOGRAPH-F9C9
+F9CA;6D41;6D41;6D41;6D41; # (流; 流; 流; 流; 流; ) CJK COMPATIBILITY IDEOGRAPH-F9CA
+F9CB;6E9C;6E9C;6E9C;6E9C; # (溜; 溜; 溜; 溜; 溜; ) CJK COMPATIBILITY IDEOGRAPH-F9CB
+F9CC;7409;7409;7409;7409; # (琉; 琉; 琉; 琉; 琉; ) CJK COMPATIBILITY IDEOGRAPH-F9CC
+F9CD;7559;7559;7559;7559; # (留; 留; 留; 留; 留; ) CJK COMPATIBILITY IDEOGRAPH-F9CD
+F9CE;786B;786B;786B;786B; # (硫; 硫; 硫; 硫; 硫; ) CJK COMPATIBILITY IDEOGRAPH-F9CE
+F9CF;7D10;7D10;7D10;7D10; # (紐; 紐; 紐; 紐; 紐; ) CJK COMPATIBILITY IDEOGRAPH-F9CF
+F9D0;985E;985E;985E;985E; # (類; 類; 類; 類; 類; ) CJK COMPATIBILITY IDEOGRAPH-F9D0
+F9D1;516D;516D;516D;516D; # (六; 六; 六; 六; 六; ) CJK COMPATIBILITY IDEOGRAPH-F9D1
+F9D2;622E;622E;622E;622E; # (戮; 戮; 戮; 戮; 戮; ) CJK COMPATIBILITY IDEOGRAPH-F9D2
+F9D3;9678;9678;9678;9678; # (陸; 陸; 陸; 陸; 陸; ) CJK COMPATIBILITY IDEOGRAPH-F9D3
+F9D4;502B;502B;502B;502B; # (倫; 倫; 倫; 倫; 倫; ) CJK COMPATIBILITY IDEOGRAPH-F9D4
+F9D5;5D19;5D19;5D19;5D19; # (崙; 崙; 崙; 崙; 崙; ) CJK COMPATIBILITY IDEOGRAPH-F9D5
+F9D6;6DEA;6DEA;6DEA;6DEA; # (淪; 淪; 淪; 淪; 淪; ) CJK COMPATIBILITY IDEOGRAPH-F9D6
+F9D7;8F2A;8F2A;8F2A;8F2A; # (輪; 輪; 輪; 輪; 輪; ) CJK COMPATIBILITY IDEOGRAPH-F9D7
+F9D8;5F8B;5F8B;5F8B;5F8B; # (律; 律; 律; 律; 律; ) CJK COMPATIBILITY IDEOGRAPH-F9D8
+F9D9;6144;6144;6144;6144; # (慄; 慄; 慄; 慄; 慄; ) CJK COMPATIBILITY IDEOGRAPH-F9D9
+F9DA;6817;6817;6817;6817; # (栗; 栗; 栗; 栗; 栗; ) CJK COMPATIBILITY IDEOGRAPH-F9DA
+F9DB;7387;7387;7387;7387; # (率; 率; 率; 率; 率; ) CJK COMPATIBILITY IDEOGRAPH-F9DB
+F9DC;9686;9686;9686;9686; # (隆; 隆; 隆; 隆; 隆; ) CJK COMPATIBILITY IDEOGRAPH-F9DC
+F9DD;5229;5229;5229;5229; # (利; 利; 利; 利; 利; ) CJK COMPATIBILITY IDEOGRAPH-F9DD
+F9DE;540F;540F;540F;540F; # (吏; 吏; 吏; 吏; 吏; ) CJK COMPATIBILITY IDEOGRAPH-F9DE
+F9DF;5C65;5C65;5C65;5C65; # (履; 履; 履; 履; 履; ) CJK COMPATIBILITY IDEOGRAPH-F9DF
+F9E0;6613;6613;6613;6613; # (易; 易; 易; 易; 易; ) CJK COMPATIBILITY IDEOGRAPH-F9E0
+F9E1;674E;674E;674E;674E; # (李; 李; 李; 李; 李; ) CJK COMPATIBILITY IDEOGRAPH-F9E1
+F9E2;68A8;68A8;68A8;68A8; # (梨; 梨; 梨; 梨; 梨; ) CJK COMPATIBILITY IDEOGRAPH-F9E2
+F9E3;6CE5;6CE5;6CE5;6CE5; # (泥; 泥; 泥; 泥; 泥; ) CJK COMPATIBILITY IDEOGRAPH-F9E3
+F9E4;7406;7406;7406;7406; # (理; 理; 理; 理; 理; ) CJK COMPATIBILITY IDEOGRAPH-F9E4
+F9E5;75E2;75E2;75E2;75E2; # (痢; 痢; 痢; 痢; 痢; ) CJK COMPATIBILITY IDEOGRAPH-F9E5
+F9E6;7F79;7F79;7F79;7F79; # (罹; 罹; 罹; 罹; 罹; ) CJK COMPATIBILITY IDEOGRAPH-F9E6
+F9E7;88CF;88CF;88CF;88CF; # (裏; 裏; 裏; 裏; 裏; ) CJK COMPATIBILITY IDEOGRAPH-F9E7
+F9E8;88E1;88E1;88E1;88E1; # (裡; 裡; 裡; 裡; 裡; ) CJK COMPATIBILITY IDEOGRAPH-F9E8
+F9E9;91CC;91CC;91CC;91CC; # (里; 里; 里; 里; 里; ) CJK COMPATIBILITY IDEOGRAPH-F9E9
+F9EA;96E2;96E2;96E2;96E2; # (離; 離; 離; 離; 離; ) CJK COMPATIBILITY IDEOGRAPH-F9EA
+F9EB;533F;533F;533F;533F; # (匿; 匿; 匿; 匿; 匿; ) CJK COMPATIBILITY IDEOGRAPH-F9EB
+F9EC;6EBA;6EBA;6EBA;6EBA; # (溺; 溺; 溺; 溺; 溺; ) CJK COMPATIBILITY IDEOGRAPH-F9EC
+F9ED;541D;541D;541D;541D; # (吝; 吝; 吝; 吝; 吝; ) CJK COMPATIBILITY IDEOGRAPH-F9ED
+F9EE;71D0;71D0;71D0;71D0; # (燐; 燐; 燐; 燐; 燐; ) CJK COMPATIBILITY IDEOGRAPH-F9EE
+F9EF;7498;7498;7498;7498; # (璘; 璘; 璘; 璘; 璘; ) CJK COMPATIBILITY IDEOGRAPH-F9EF
+F9F0;85FA;85FA;85FA;85FA; # (藺; 藺; 藺; 藺; 藺; ) CJK COMPATIBILITY IDEOGRAPH-F9F0
+F9F1;96A3;96A3;96A3;96A3; # (隣; 隣; 隣; 隣; 隣; ) CJK COMPATIBILITY IDEOGRAPH-F9F1
+F9F2;9C57;9C57;9C57;9C57; # (鱗; 鱗; 鱗; 鱗; 鱗; ) CJK COMPATIBILITY IDEOGRAPH-F9F2
+F9F3;9E9F;9E9F;9E9F;9E9F; # (麟; 麟; 麟; 麟; 麟; ) CJK COMPATIBILITY IDEOGRAPH-F9F3
+F9F4;6797;6797;6797;6797; # (林; 林; 林; 林; 林; ) CJK COMPATIBILITY IDEOGRAPH-F9F4
+F9F5;6DCB;6DCB;6DCB;6DCB; # (淋; 淋; 淋; 淋; 淋; ) CJK COMPATIBILITY IDEOGRAPH-F9F5
+F9F6;81E8;81E8;81E8;81E8; # (臨; 臨; 臨; 臨; 臨; ) CJK COMPATIBILITY IDEOGRAPH-F9F6
+F9F7;7ACB;7ACB;7ACB;7ACB; # (立; 立; 立; 立; 立; ) CJK COMPATIBILITY IDEOGRAPH-F9F7
+F9F8;7B20;7B20;7B20;7B20; # (笠; 笠; 笠; 笠; 笠; ) CJK COMPATIBILITY IDEOGRAPH-F9F8
+F9F9;7C92;7C92;7C92;7C92; # (粒; 粒; 粒; 粒; 粒; ) CJK COMPATIBILITY IDEOGRAPH-F9F9
+F9FA;72C0;72C0;72C0;72C0; # (狀; 狀; 狀; 狀; 狀; ) CJK COMPATIBILITY IDEOGRAPH-F9FA
+F9FB;7099;7099;7099;7099; # (炙; 炙; 炙; 炙; 炙; ) CJK COMPATIBILITY IDEOGRAPH-F9FB
+F9FC;8B58;8B58;8B58;8B58; # (識; 識; 識; 識; 識; ) CJK COMPATIBILITY IDEOGRAPH-F9FC
+F9FD;4EC0;4EC0;4EC0;4EC0; # (什; 什; 什; 什; 什; ) CJK COMPATIBILITY IDEOGRAPH-F9FD
+F9FE;8336;8336;8336;8336; # (茶; 茶; 茶; 茶; 茶; ) CJK COMPATIBILITY IDEOGRAPH-F9FE
+F9FF;523A;523A;523A;523A; # (刺; 刺; 刺; 刺; 刺; ) CJK COMPATIBILITY IDEOGRAPH-F9FF
+FA00;5207;5207;5207;5207; # (切; 切; 切; 切; 切; ) CJK COMPATIBILITY IDEOGRAPH-FA00
+FA01;5EA6;5EA6;5EA6;5EA6; # (度; 度; 度; 度; 度; ) CJK COMPATIBILITY IDEOGRAPH-FA01
+FA02;62D3;62D3;62D3;62D3; # (拓; 拓; 拓; 拓; 拓; ) CJK COMPATIBILITY IDEOGRAPH-FA02
+FA03;7CD6;7CD6;7CD6;7CD6; # (糖; 糖; 糖; 糖; 糖; ) CJK COMPATIBILITY IDEOGRAPH-FA03
+FA04;5B85;5B85;5B85;5B85; # (宅; 宅; 宅; 宅; 宅; ) CJK COMPATIBILITY IDEOGRAPH-FA04
+FA05;6D1E;6D1E;6D1E;6D1E; # (洞; 洞; 洞; 洞; 洞; ) CJK COMPATIBILITY IDEOGRAPH-FA05
+FA06;66B4;66B4;66B4;66B4; # (暴; 暴; 暴; 暴; 暴; ) CJK COMPATIBILITY IDEOGRAPH-FA06
+FA07;8F3B;8F3B;8F3B;8F3B; # (輻; 輻; 輻; 輻; 輻; ) CJK COMPATIBILITY IDEOGRAPH-FA07
+FA08;884C;884C;884C;884C; # (行; 行; 行; 行; 行; ) CJK COMPATIBILITY IDEOGRAPH-FA08
+FA09;964D;964D;964D;964D; # (降; 降; 降; 降; 降; ) CJK COMPATIBILITY IDEOGRAPH-FA09
+FA0A;898B;898B;898B;898B; # (見; 見; 見; 見; 見; ) CJK COMPATIBILITY IDEOGRAPH-FA0A
+FA0B;5ED3;5ED3;5ED3;5ED3; # (廓; 廓; 廓; 廓; 廓; ) CJK COMPATIBILITY IDEOGRAPH-FA0B
+FA0C;5140;5140;5140;5140; # (兀; 兀; 兀; 兀; 兀; ) CJK COMPATIBILITY IDEOGRAPH-FA0C
+FA0D;55C0;55C0;55C0;55C0; # (嗀; 嗀; 嗀; 嗀; 嗀; ) CJK COMPATIBILITY IDEOGRAPH-FA0D
+FA10;585A;585A;585A;585A; # (塚; 塚; 塚; 塚; 塚; ) CJK COMPATIBILITY IDEOGRAPH-FA10
+FA12;6674;6674;6674;6674; # (晴; 晴; 晴; 晴; 晴; ) CJK COMPATIBILITY IDEOGRAPH-FA12
+FA15;51DE;51DE;51DE;51DE; # (凞; 凞; 凞; 凞; 凞; ) CJK COMPATIBILITY IDEOGRAPH-FA15
+FA16;732A;732A;732A;732A; # (猪; 猪; 猪; 猪; 猪; ) CJK COMPATIBILITY IDEOGRAPH-FA16
+FA17;76CA;76CA;76CA;76CA; # (益; 益; 益; 益; 益; ) CJK COMPATIBILITY IDEOGRAPH-FA17
+FA18;793C;793C;793C;793C; # (礼; 礼; 礼; 礼; 礼; ) CJK COMPATIBILITY IDEOGRAPH-FA18
+FA19;795E;795E;795E;795E; # (神; 神; 神; 神; 神; ) CJK COMPATIBILITY IDEOGRAPH-FA19
+FA1A;7965;7965;7965;7965; # (祥; 祥; 祥; 祥; 祥; ) CJK COMPATIBILITY IDEOGRAPH-FA1A
+FA1B;798F;798F;798F;798F; # (福; 福; 福; 福; 福; ) CJK COMPATIBILITY IDEOGRAPH-FA1B
+FA1C;9756;9756;9756;9756; # (靖; 靖; 靖; 靖; 靖; ) CJK COMPATIBILITY IDEOGRAPH-FA1C
+FA1D;7CBE;7CBE;7CBE;7CBE; # (精; 精; 精; 精; 精; ) CJK COMPATIBILITY IDEOGRAPH-FA1D
+FA1E;7FBD;7FBD;7FBD;7FBD; # (羽; 羽; 羽; 羽; 羽; ) CJK COMPATIBILITY IDEOGRAPH-FA1E
+FA20;8612;8612;8612;8612; # (蘒; 蘒; 蘒; 蘒; 蘒; ) CJK COMPATIBILITY IDEOGRAPH-FA20
+FA22;8AF8;8AF8;8AF8;8AF8; # (諸; 諸; 諸; 諸; 諸; ) CJK COMPATIBILITY IDEOGRAPH-FA22
+FA25;9038;9038;9038;9038; # (逸; 逸; 逸; 逸; 逸; ) CJK COMPATIBILITY IDEOGRAPH-FA25
+FA26;90FD;90FD;90FD;90FD; # (都; 都; 都; 都; 都; ) CJK COMPATIBILITY IDEOGRAPH-FA26
+FA2A;98EF;98EF;98EF;98EF; # (飯; 飯; 飯; 飯; 飯; ) CJK COMPATIBILITY IDEOGRAPH-FA2A
+FA2B;98FC;98FC;98FC;98FC; # (飼; 飼; 飼; 飼; 飼; ) CJK COMPATIBILITY IDEOGRAPH-FA2B
+FA2C;9928;9928;9928;9928; # (館; 館; 館; 館; 館; ) CJK COMPATIBILITY IDEOGRAPH-FA2C
+FA2D;9DB4;9DB4;9DB4;9DB4; # (鶴; 鶴; 鶴; 鶴; 鶴; ) CJK COMPATIBILITY IDEOGRAPH-FA2D
+FA30;4FAE;4FAE;4FAE;4FAE; # (侮; 侮; 侮; 侮; 侮; ) CJK COMPATIBILITY IDEOGRAPH-FA30
+FA31;50E7;50E7;50E7;50E7; # (僧; 僧; 僧; 僧; 僧; ) CJK COMPATIBILITY IDEOGRAPH-FA31
+FA32;514D;514D;514D;514D; # (免; 免; 免; 免; 免; ) CJK COMPATIBILITY IDEOGRAPH-FA32
+FA33;52C9;52C9;52C9;52C9; # (勉; 勉; 勉; 勉; 勉; ) CJK COMPATIBILITY IDEOGRAPH-FA33
+FA34;52E4;52E4;52E4;52E4; # (勤; 勤; 勤; 勤; 勤; ) CJK COMPATIBILITY IDEOGRAPH-FA34
+FA35;5351;5351;5351;5351; # (卑; 卑; 卑; 卑; 卑; ) CJK COMPATIBILITY IDEOGRAPH-FA35
+FA36;559D;559D;559D;559D; # (喝; 喝; 喝; 喝; 喝; ) CJK COMPATIBILITY IDEOGRAPH-FA36
+FA37;5606;5606;5606;5606; # (嘆; 嘆; 嘆; 嘆; 嘆; ) CJK COMPATIBILITY IDEOGRAPH-FA37
+FA38;5668;5668;5668;5668; # (器; 器; 器; 器; 器; ) CJK COMPATIBILITY IDEOGRAPH-FA38
+FA39;5840;5840;5840;5840; # (塀; 塀; 塀; 塀; 塀; ) CJK COMPATIBILITY IDEOGRAPH-FA39
+FA3A;58A8;58A8;58A8;58A8; # (墨; 墨; 墨; 墨; 墨; ) CJK COMPATIBILITY IDEOGRAPH-FA3A
+FA3B;5C64;5C64;5C64;5C64; # (層; 層; 層; 層; 層; ) CJK COMPATIBILITY IDEOGRAPH-FA3B
+FA3C;5C6E;5C6E;5C6E;5C6E; # (屮; 屮; 屮; 屮; 屮; ) CJK COMPATIBILITY IDEOGRAPH-FA3C
+FA3D;6094;6094;6094;6094; # (悔; 悔; 悔; 悔; 悔; ) CJK COMPATIBILITY IDEOGRAPH-FA3D
+FA3E;6168;6168;6168;6168; # (慨; 慨; 慨; 慨; 慨; ) CJK COMPATIBILITY IDEOGRAPH-FA3E
+FA3F;618E;618E;618E;618E; # (憎; 憎; 憎; 憎; 憎; ) CJK COMPATIBILITY IDEOGRAPH-FA3F
+FA40;61F2;61F2;61F2;61F2; # (懲; 懲; 懲; 懲; 懲; ) CJK COMPATIBILITY IDEOGRAPH-FA40
+FA41;654F;654F;654F;654F; # (敏; 敏; 敏; 敏; 敏; ) CJK COMPATIBILITY IDEOGRAPH-FA41
+FA42;65E2;65E2;65E2;65E2; # (既; 既; 既; 既; 既; ) CJK COMPATIBILITY IDEOGRAPH-FA42
+FA43;6691;6691;6691;6691; # (暑; 暑; 暑; 暑; 暑; ) CJK COMPATIBILITY IDEOGRAPH-FA43
+FA44;6885;6885;6885;6885; # (梅; 梅; 梅; 梅; 梅; ) CJK COMPATIBILITY IDEOGRAPH-FA44
+FA45;6D77;6D77;6D77;6D77; # (海; 海; 海; 海; 海; ) CJK COMPATIBILITY IDEOGRAPH-FA45
+FA46;6E1A;6E1A;6E1A;6E1A; # (渚; 渚; 渚; 渚; 渚; ) CJK COMPATIBILITY IDEOGRAPH-FA46
+FA47;6F22;6F22;6F22;6F22; # (漢; 漢; 漢; 漢; 漢; ) CJK COMPATIBILITY IDEOGRAPH-FA47
+FA48;716E;716E;716E;716E; # (煮; 煮; 煮; 煮; 煮; ) CJK COMPATIBILITY IDEOGRAPH-FA48
+FA49;722B;722B;722B;722B; # (爫; 爫; 爫; 爫; 爫; ) CJK COMPATIBILITY IDEOGRAPH-FA49
+FA4A;7422;7422;7422;7422; # (琢; 琢; 琢; 琢; 琢; ) CJK COMPATIBILITY IDEOGRAPH-FA4A
+FA4B;7891;7891;7891;7891; # (碑; 碑; 碑; 碑; 碑; ) CJK COMPATIBILITY IDEOGRAPH-FA4B
+FA4C;793E;793E;793E;793E; # (社; 社; 社; 社; 社; ) CJK COMPATIBILITY IDEOGRAPH-FA4C
+FA4D;7949;7949;7949;7949; # (祉; 祉; 祉; 祉; 祉; ) CJK COMPATIBILITY IDEOGRAPH-FA4D
+FA4E;7948;7948;7948;7948; # (祈; 祈; 祈; 祈; 祈; ) CJK COMPATIBILITY IDEOGRAPH-FA4E
+FA4F;7950;7950;7950;7950; # (祐; 祐; 祐; 祐; 祐; ) CJK COMPATIBILITY IDEOGRAPH-FA4F
+FA50;7956;7956;7956;7956; # (祖; 祖; 祖; 祖; 祖; ) CJK COMPATIBILITY IDEOGRAPH-FA50
+FA51;795D;795D;795D;795D; # (祝; 祝; 祝; 祝; 祝; ) CJK COMPATIBILITY IDEOGRAPH-FA51
+FA52;798D;798D;798D;798D; # (禍; 禍; 禍; 禍; 禍; ) CJK COMPATIBILITY IDEOGRAPH-FA52
+FA53;798E;798E;798E;798E; # (禎; 禎; 禎; 禎; 禎; ) CJK COMPATIBILITY IDEOGRAPH-FA53
+FA54;7A40;7A40;7A40;7A40; # (穀; 穀; 穀; 穀; 穀; ) CJK COMPATIBILITY IDEOGRAPH-FA54
+FA55;7A81;7A81;7A81;7A81; # (突; 突; 突; 突; 突; ) CJK COMPATIBILITY IDEOGRAPH-FA55
+FA56;7BC0;7BC0;7BC0;7BC0; # (節; 節; 節; 節; 節; ) CJK COMPATIBILITY IDEOGRAPH-FA56
+FA57;7DF4;7DF4;7DF4;7DF4; # (練; 練; 練; 練; 練; ) CJK COMPATIBILITY IDEOGRAPH-FA57
+FA58;7E09;7E09;7E09;7E09; # (縉; 縉; 縉; 縉; 縉; ) CJK COMPATIBILITY IDEOGRAPH-FA58
+FA59;7E41;7E41;7E41;7E41; # (繁; 繁; 繁; 繁; 繁; ) CJK COMPATIBILITY IDEOGRAPH-FA59
+FA5A;7F72;7F72;7F72;7F72; # (署; 署; 署; 署; 署; ) CJK COMPATIBILITY IDEOGRAPH-FA5A
+FA5B;8005;8005;8005;8005; # (者; 者; 者; 者; 者; ) CJK COMPATIBILITY IDEOGRAPH-FA5B
+FA5C;81ED;81ED;81ED;81ED; # (臭; 臭; 臭; 臭; 臭; ) CJK COMPATIBILITY IDEOGRAPH-FA5C
+FA5D;8279;8279;8279;8279; # (艹; 艹; 艹; 艹; 艹; ) CJK COMPATIBILITY IDEOGRAPH-FA5D
+FA5E;8279;8279;8279;8279; # (艹; 艹; 艹; 艹; 艹; ) CJK COMPATIBILITY IDEOGRAPH-FA5E
+FA5F;8457;8457;8457;8457; # (著; 著; 著; 著; 著; ) CJK COMPATIBILITY IDEOGRAPH-FA5F
+FA60;8910;8910;8910;8910; # (褐; 褐; 褐; 褐; 褐; ) CJK COMPATIBILITY IDEOGRAPH-FA60
+FA61;8996;8996;8996;8996; # (視; 視; 視; 視; 視; ) CJK COMPATIBILITY IDEOGRAPH-FA61
+FA62;8B01;8B01;8B01;8B01; # (謁; 謁; 謁; 謁; 謁; ) CJK COMPATIBILITY IDEOGRAPH-FA62
+FA63;8B39;8B39;8B39;8B39; # (謹; 謹; 謹; 謹; 謹; ) CJK COMPATIBILITY IDEOGRAPH-FA63
+FA64;8CD3;8CD3;8CD3;8CD3; # (賓; 賓; 賓; 賓; 賓; ) CJK COMPATIBILITY IDEOGRAPH-FA64
+FA65;8D08;8D08;8D08;8D08; # (贈; 贈; 贈; 贈; 贈; ) CJK COMPATIBILITY IDEOGRAPH-FA65
+FA66;8FB6;8FB6;8FB6;8FB6; # (辶; 辶; 辶; 辶; 辶; ) CJK COMPATIBILITY IDEOGRAPH-FA66
+FA67;9038;9038;9038;9038; # (逸; 逸; 逸; 逸; 逸; ) CJK COMPATIBILITY IDEOGRAPH-FA67
+FA68;96E3;96E3;96E3;96E3; # (難; 難; 難; 難; 難; ) CJK COMPATIBILITY IDEOGRAPH-FA68
+FA69;97FF;97FF;97FF;97FF; # (響; 響; 響; 響; 響; ) CJK COMPATIBILITY IDEOGRAPH-FA69
+FA6A;983B;983B;983B;983B; # (頻; 頻; 頻; 頻; 頻; ) CJK COMPATIBILITY IDEOGRAPH-FA6A
+FB00;FB00;FB00;0066 0066;0066 0066; # (ff; ff; ff; ff; ff; ) LATIN SMALL LIGATURE FF
+FB01;FB01;FB01;0066 0069;0066 0069; # (fi; fi; fi; fi; fi; ) LATIN SMALL LIGATURE FI
+FB02;FB02;FB02;0066 006C;0066 006C; # (fl; fl; fl; fl; fl; ) LATIN SMALL LIGATURE FL
+FB03;FB03;FB03;0066 0066 0069;0066 0066 0069; # (ffi; ffi; ffi; ffi; ffi; ) LATIN SMALL LIGATURE FFI
+FB04;FB04;FB04;0066 0066 006C;0066 0066 006C; # (ffl; ffl; ffl; ffl; ffl; ) LATIN SMALL LIGATURE FFL
+FB05;FB05;FB05;0073 0074;0073 0074; # (ſt; ſt; ſt; st; st; ) LATIN SMALL LIGATURE LONG S T
+FB06;FB06;FB06;0073 0074;0073 0074; # (st; st; st; st; st; ) LATIN SMALL LIGATURE ST
+FB13;FB13;FB13;0574 0576;0574 0576; # (ﬓ; ﬓ; ﬓ; մն; մն; ) ARMENIAN SMALL LIGATURE MEN NOW
+FB14;FB14;FB14;0574 0565;0574 0565; # (ﬔ; ﬔ; ﬔ; մե; մե; ) ARMENIAN SMALL LIGATURE MEN ECH
+FB15;FB15;FB15;0574 056B;0574 056B; # (ﬕ; ﬕ; ﬕ; մի; մի; ) ARMENIAN SMALL LIGATURE MEN INI
+FB16;FB16;FB16;057E 0576;057E 0576; # (ﬖ; ﬖ; ﬖ; վն; վն; ) ARMENIAN SMALL LIGATURE VEW NOW
+FB17;FB17;FB17;0574 056D;0574 056D; # (ﬗ; ﬗ; ﬗ; մխ; մխ; ) ARMENIAN SMALL LIGATURE MEN XEH
+FB1D;05D9 05B4;05D9 05B4;05D9 05B4;05D9 05B4; # (יִ; י◌ִ; י◌ִ; י◌ִ; י◌ִ; ) HEBREW LETTER YOD WITH HIRIQ
+FB1F;05F2 05B7;05F2 05B7;05F2 05B7;05F2 05B7; # (ײַ; ײ◌ַ; ײ◌ַ; ײ◌ַ; ײ◌ַ; ) HEBREW LIGATURE YIDDISH YOD YOD PATAH
+FB20;FB20;FB20;05E2;05E2; # (ﬠ; ﬠ; ﬠ; ע; ע; ) HEBREW LETTER ALTERNATIVE AYIN
+FB21;FB21;FB21;05D0;05D0; # (ﬡ; ﬡ; ﬡ; א; א; ) HEBREW LETTER WIDE ALEF
+FB22;FB22;FB22;05D3;05D3; # (ﬢ; ﬢ; ﬢ; ד; ד; ) HEBREW LETTER WIDE DALET
+FB23;FB23;FB23;05D4;05D4; # (ﬣ; ﬣ; ﬣ; ה; ה; ) HEBREW LETTER WIDE HE
+FB24;FB24;FB24;05DB;05DB; # (ﬤ; ﬤ; ﬤ; כ; כ; ) HEBREW LETTER WIDE KAF
+FB25;FB25;FB25;05DC;05DC; # (ﬥ; ﬥ; ﬥ; ל; ל; ) HEBREW LETTER WIDE LAMED
+FB26;FB26;FB26;05DD;05DD; # (ﬦ; ﬦ; ﬦ; ם; ם; ) HEBREW LETTER WIDE FINAL MEM
+FB27;FB27;FB27;05E8;05E8; # (ﬧ; ﬧ; ﬧ; ר; ר; ) HEBREW LETTER WIDE RESH
+FB28;FB28;FB28;05EA;05EA; # (ﬨ; ﬨ; ﬨ; ת; ת; ) HEBREW LETTER WIDE TAV
+FB29;FB29;FB29;002B;002B; # (﬩; ﬩; ﬩; +; +; ) HEBREW LETTER ALTERNATIVE PLUS SIGN
+FB2A;05E9 05C1;05E9 05C1;05E9 05C1;05E9 05C1; # (שׁ; ש◌ׁ; ש◌ׁ; ש◌ׁ; ש◌ׁ; ) HEBREW LETTER SHIN WITH SHIN DOT
+FB2B;05E9 05C2;05E9 05C2;05E9 05C2;05E9 05C2; # (שׂ; ש◌ׂ; ש◌ׂ; ש◌ׂ; ש◌ׂ; ) HEBREW LETTER SHIN WITH SIN DOT
+FB2C;05E9 05BC 05C1;05E9 05BC 05C1;05E9 05BC 05C1;05E9 05BC 05C1; # (שּׁ; ש◌ּ◌ׁ; ש◌ּ◌ׁ; ש◌ּ◌ׁ; ש◌ּ◌ׁ; ) HEBREW LETTER SHIN WITH DAGESH AND SHIN DOT
+FB2D;05E9 05BC 05C2;05E9 05BC 05C2;05E9 05BC 05C2;05E9 05BC 05C2; # (שּׂ; ש◌ּ◌ׂ; ש◌ּ◌ׂ; ש◌ּ◌ׂ; ש◌ּ◌ׂ; ) HEBREW LETTER SHIN WITH DAGESH AND SIN DOT
+FB2E;05D0 05B7;05D0 05B7;05D0 05B7;05D0 05B7; # (אַ; א◌ַ; א◌ַ; א◌ַ; א◌ַ; ) HEBREW LETTER ALEF WITH PATAH
+FB2F;05D0 05B8;05D0 05B8;05D0 05B8;05D0 05B8; # (אָ; א◌ָ; א◌ָ; א◌ָ; א◌ָ; ) HEBREW LETTER ALEF WITH QAMATS
+FB30;05D0 05BC;05D0 05BC;05D0 05BC;05D0 05BC; # (אּ; א◌ּ; א◌ּ; א◌ּ; א◌ּ; ) HEBREW LETTER ALEF WITH MAPIQ
+FB31;05D1 05BC;05D1 05BC;05D1 05BC;05D1 05BC; # (בּ; ב◌ּ; ב◌ּ; ב◌ּ; ב◌ּ; ) HEBREW LETTER BET WITH DAGESH
+FB32;05D2 05BC;05D2 05BC;05D2 05BC;05D2 05BC; # (גּ; ג◌ּ; ג◌ּ; ג◌ּ; ג◌ּ; ) HEBREW LETTER GIMEL WITH DAGESH
+FB33;05D3 05BC;05D3 05BC;05D3 05BC;05D3 05BC; # (דּ; ד◌ּ; ד◌ּ; ד◌ּ; ד◌ּ; ) HEBREW LETTER DALET WITH DAGESH
+FB34;05D4 05BC;05D4 05BC;05D4 05BC;05D4 05BC; # (הּ; ה◌ּ; ה◌ּ; ה◌ּ; ה◌ּ; ) HEBREW LETTER HE WITH MAPIQ
+FB35;05D5 05BC;05D5 05BC;05D5 05BC;05D5 05BC; # (וּ; ו◌ּ; ו◌ּ; ו◌ּ; ו◌ּ; ) HEBREW LETTER VAV WITH DAGESH
+FB36;05D6 05BC;05D6 05BC;05D6 05BC;05D6 05BC; # (זּ; ז◌ּ; ז◌ּ; ז◌ּ; ז◌ּ; ) HEBREW LETTER ZAYIN WITH DAGESH
+FB38;05D8 05BC;05D8 05BC;05D8 05BC;05D8 05BC; # (טּ; ט◌ּ; ט◌ּ; ט◌ּ; ט◌ּ; ) HEBREW LETTER TET WITH DAGESH
+FB39;05D9 05BC;05D9 05BC;05D9 05BC;05D9 05BC; # (יּ; י◌ּ; י◌ּ; י◌ּ; י◌ּ; ) HEBREW LETTER YOD WITH DAGESH
+FB3A;05DA 05BC;05DA 05BC;05DA 05BC;05DA 05BC; # (ךּ; ך◌ּ; ך◌ּ; ך◌ּ; ך◌ּ; ) HEBREW LETTER FINAL KAF WITH DAGESH
+FB3B;05DB 05BC;05DB 05BC;05DB 05BC;05DB 05BC; # (כּ; כ◌ּ; כ◌ּ; כ◌ּ; כ◌ּ; ) HEBREW LETTER KAF WITH DAGESH
+FB3C;05DC 05BC;05DC 05BC;05DC 05BC;05DC 05BC; # (לּ; ל◌ּ; ל◌ּ; ל◌ּ; ל◌ּ; ) HEBREW LETTER LAMED WITH DAGESH
+FB3E;05DE 05BC;05DE 05BC;05DE 05BC;05DE 05BC; # (מּ; מ◌ּ; מ◌ּ; מ◌ּ; מ◌ּ; ) HEBREW LETTER MEM WITH DAGESH
+FB40;05E0 05BC;05E0 05BC;05E0 05BC;05E0 05BC; # (נּ; נ◌ּ; נ◌ּ; נ◌ּ; נ◌ּ; ) HEBREW LETTER NUN WITH DAGESH
+FB41;05E1 05BC;05E1 05BC;05E1 05BC;05E1 05BC; # (סּ; ס◌ּ; ס◌ּ; ס◌ּ; ס◌ּ; ) HEBREW LETTER SAMEKH WITH DAGESH
+FB43;05E3 05BC;05E3 05BC;05E3 05BC;05E3 05BC; # (ףּ; ף◌ּ; ף◌ּ; ף◌ּ; ף◌ּ; ) HEBREW LETTER FINAL PE WITH DAGESH
+FB44;05E4 05BC;05E4 05BC;05E4 05BC;05E4 05BC; # (פּ; פ◌ּ; פ◌ּ; פ◌ּ; פ◌ּ; ) HEBREW LETTER PE WITH DAGESH
+FB46;05E6 05BC;05E6 05BC;05E6 05BC;05E6 05BC; # (צּ; צ◌ּ; צ◌ּ; צ◌ּ; צ◌ּ; ) HEBREW LETTER TSADI WITH DAGESH
+FB47;05E7 05BC;05E7 05BC;05E7 05BC;05E7 05BC; # (קּ; ק◌ּ; ק◌ּ; ק◌ּ; ק◌ּ; ) HEBREW LETTER QOF WITH DAGESH
+FB48;05E8 05BC;05E8 05BC;05E8 05BC;05E8 05BC; # (רּ; ר◌ּ; ר◌ּ; ר◌ּ; ר◌ּ; ) HEBREW LETTER RESH WITH DAGESH
+FB49;05E9 05BC;05E9 05BC;05E9 05BC;05E9 05BC; # (שּ; ש◌ּ; ש◌ּ; ש◌ּ; ש◌ּ; ) HEBREW LETTER SHIN WITH DAGESH
+FB4A;05EA 05BC;05EA 05BC;05EA 05BC;05EA 05BC; # (תּ; ת◌ּ; ת◌ּ; ת◌ּ; ת◌ּ; ) HEBREW LETTER TAV WITH DAGESH
+FB4B;05D5 05B9;05D5 05B9;05D5 05B9;05D5 05B9; # (וֹ; ו◌ֹ; ו◌ֹ; ו◌ֹ; ו◌ֹ; ) HEBREW LETTER VAV WITH HOLAM
+FB4C;05D1 05BF;05D1 05BF;05D1 05BF;05D1 05BF; # (בֿ; ב◌ֿ; ב◌ֿ; ב◌ֿ; ב◌ֿ; ) HEBREW LETTER BET WITH RAFE
+FB4D;05DB 05BF;05DB 05BF;05DB 05BF;05DB 05BF; # (כֿ; כ◌ֿ; כ◌ֿ; כ◌ֿ; כ◌ֿ; ) HEBREW LETTER KAF WITH RAFE
+FB4E;05E4 05BF;05E4 05BF;05E4 05BF;05E4 05BF; # (פֿ; פ◌ֿ; פ◌ֿ; פ◌ֿ; פ◌ֿ; ) HEBREW LETTER PE WITH RAFE
+FB4F;FB4F;FB4F;05D0 05DC;05D0 05DC; # (ﭏ; ﭏ; ﭏ; אל; אל; ) HEBREW LIGATURE ALEF LAMED
+FB50;FB50;FB50;0671;0671; # (ﭐ; ﭐ; ﭐ; ٱ; ٱ; ) ARABIC LETTER ALEF WASLA ISOLATED FORM
+FB51;FB51;FB51;0671;0671; # (ﭑ; ﭑ; ﭑ; ٱ; ٱ; ) ARABIC LETTER ALEF WASLA FINAL FORM
+FB52;FB52;FB52;067B;067B; # (ﭒ; ﭒ; ﭒ; ٻ; ٻ; ) ARABIC LETTER BEEH ISOLATED FORM
+FB53;FB53;FB53;067B;067B; # (ﭓ; ﭓ; ﭓ; ٻ; ٻ; ) ARABIC LETTER BEEH FINAL FORM
+FB54;FB54;FB54;067B;067B; # (ﭔ; ﭔ; ﭔ; ٻ; ٻ; ) ARABIC LETTER BEEH INITIAL FORM
+FB55;FB55;FB55;067B;067B; # (ﭕ; ﭕ; ﭕ; ٻ; ٻ; ) ARABIC LETTER BEEH MEDIAL FORM
+FB56;FB56;FB56;067E;067E; # (ﭖ; ﭖ; ﭖ; پ; پ; ) ARABIC LETTER PEH ISOLATED FORM
+FB57;FB57;FB57;067E;067E; # (ﭗ; ﭗ; ﭗ; پ; پ; ) ARABIC LETTER PEH FINAL FORM
+FB58;FB58;FB58;067E;067E; # (ﭘ; ﭘ; ﭘ; پ; پ; ) ARABIC LETTER PEH INITIAL FORM
+FB59;FB59;FB59;067E;067E; # (ﭙ; ﭙ; ﭙ; پ; پ; ) ARABIC LETTER PEH MEDIAL FORM
+FB5A;FB5A;FB5A;0680;0680; # (ﭚ; ﭚ; ﭚ; ڀ; ڀ; ) ARABIC LETTER BEHEH ISOLATED FORM
+FB5B;FB5B;FB5B;0680;0680; # (ﭛ; ﭛ; ﭛ; ڀ; ڀ; ) ARABIC LETTER BEHEH FINAL FORM
+FB5C;FB5C;FB5C;0680;0680; # (ﭜ; ﭜ; ﭜ; ڀ; ڀ; ) ARABIC LETTER BEHEH INITIAL FORM
+FB5D;FB5D;FB5D;0680;0680; # (ﭝ; ﭝ; ﭝ; ڀ; ڀ; ) ARABIC LETTER BEHEH MEDIAL FORM
+FB5E;FB5E;FB5E;067A;067A; # (ﭞ; ﭞ; ﭞ; ٺ; ٺ; ) ARABIC LETTER TTEHEH ISOLATED FORM
+FB5F;FB5F;FB5F;067A;067A; # (ﭟ; ﭟ; ﭟ; ٺ; ٺ; ) ARABIC LETTER TTEHEH FINAL FORM
+FB60;FB60;FB60;067A;067A; # (ﭠ; ﭠ; ﭠ; ٺ; ٺ; ) ARABIC LETTER TTEHEH INITIAL FORM
+FB61;FB61;FB61;067A;067A; # (ﭡ; ﭡ; ﭡ; ٺ; ٺ; ) ARABIC LETTER TTEHEH MEDIAL FORM
+FB62;FB62;FB62;067F;067F; # (ﭢ; ﭢ; ﭢ; ٿ; ٿ; ) ARABIC LETTER TEHEH ISOLATED FORM
+FB63;FB63;FB63;067F;067F; # (ﭣ; ﭣ; ﭣ; ٿ; ٿ; ) ARABIC LETTER TEHEH FINAL FORM
+FB64;FB64;FB64;067F;067F; # (ﭤ; ﭤ; ﭤ; ٿ; ٿ; ) ARABIC LETTER TEHEH INITIAL FORM
+FB65;FB65;FB65;067F;067F; # (ﭥ; ﭥ; ﭥ; ٿ; ٿ; ) ARABIC LETTER TEHEH MEDIAL FORM
+FB66;FB66;FB66;0679;0679; # (ﭦ; ﭦ; ﭦ; ٹ; ٹ; ) ARABIC LETTER TTEH ISOLATED FORM
+FB67;FB67;FB67;0679;0679; # (ﭧ; ﭧ; ﭧ; ٹ; ٹ; ) ARABIC LETTER TTEH FINAL FORM
+FB68;FB68;FB68;0679;0679; # (ﭨ; ﭨ; ﭨ; ٹ; ٹ; ) ARABIC LETTER TTEH INITIAL FORM
+FB69;FB69;FB69;0679;0679; # (ﭩ; ﭩ; ﭩ; ٹ; ٹ; ) ARABIC LETTER TTEH MEDIAL FORM
+FB6A;FB6A;FB6A;06A4;06A4; # (ﭪ; ﭪ; ﭪ; ڤ; ڤ; ) ARABIC LETTER VEH ISOLATED FORM
+FB6B;FB6B;FB6B;06A4;06A4; # (ﭫ; ﭫ; ﭫ; ڤ; ڤ; ) ARABIC LETTER VEH FINAL FORM
+FB6C;FB6C;FB6C;06A4;06A4; # (ﭬ; ﭬ; ﭬ; ڤ; ڤ; ) ARABIC LETTER VEH INITIAL FORM
+FB6D;FB6D;FB6D;06A4;06A4; # (ﭭ; ﭭ; ﭭ; ڤ; ڤ; ) ARABIC LETTER VEH MEDIAL FORM
+FB6E;FB6E;FB6E;06A6;06A6; # (ﭮ; ﭮ; ﭮ; ڦ; ڦ; ) ARABIC LETTER PEHEH ISOLATED FORM
+FB6F;FB6F;FB6F;06A6;06A6; # (ﭯ; ﭯ; ﭯ; ڦ; ڦ; ) ARABIC LETTER PEHEH FINAL FORM
+FB70;FB70;FB70;06A6;06A6; # (ﭰ; ﭰ; ﭰ; ڦ; ڦ; ) ARABIC LETTER PEHEH INITIAL FORM
+FB71;FB71;FB71;06A6;06A6; # (ﭱ; ﭱ; ﭱ; ڦ; ڦ; ) ARABIC LETTER PEHEH MEDIAL FORM
+FB72;FB72;FB72;0684;0684; # (ﭲ; ﭲ; ﭲ; ڄ; ڄ; ) ARABIC LETTER DYEH ISOLATED FORM
+FB73;FB73;FB73;0684;0684; # (ﭳ; ﭳ; ﭳ; ڄ; ڄ; ) ARABIC LETTER DYEH FINAL FORM
+FB74;FB74;FB74;0684;0684; # (ﭴ; ﭴ; ﭴ; ڄ; ڄ; ) ARABIC LETTER DYEH INITIAL FORM
+FB75;FB75;FB75;0684;0684; # (ﭵ; ﭵ; ﭵ; ڄ; ڄ; ) ARABIC LETTER DYEH MEDIAL FORM
+FB76;FB76;FB76;0683;0683; # (ﭶ; ﭶ; ﭶ; ڃ; ڃ; ) ARABIC LETTER NYEH ISOLATED FORM
+FB77;FB77;FB77;0683;0683; # (ﭷ; ﭷ; ﭷ; ڃ; ڃ; ) ARABIC LETTER NYEH FINAL FORM
+FB78;FB78;FB78;0683;0683; # (ﭸ; ﭸ; ﭸ; ڃ; ڃ; ) ARABIC LETTER NYEH INITIAL FORM
+FB79;FB79;FB79;0683;0683; # (ﭹ; ﭹ; ﭹ; ڃ; ڃ; ) ARABIC LETTER NYEH MEDIAL FORM
+FB7A;FB7A;FB7A;0686;0686; # (ﭺ; ﭺ; ﭺ; چ; چ; ) ARABIC LETTER TCHEH ISOLATED FORM
+FB7B;FB7B;FB7B;0686;0686; # (ﭻ; ﭻ; ﭻ; چ; چ; ) ARABIC LETTER TCHEH FINAL FORM
+FB7C;FB7C;FB7C;0686;0686; # (ﭼ; ﭼ; ﭼ; چ; چ; ) ARABIC LETTER TCHEH INITIAL FORM
+FB7D;FB7D;FB7D;0686;0686; # (ﭽ; ﭽ; ﭽ; چ; چ; ) ARABIC LETTER TCHEH MEDIAL FORM
+FB7E;FB7E;FB7E;0687;0687; # (ﭾ; ﭾ; ﭾ; ڇ; ڇ; ) ARABIC LETTER TCHEHEH ISOLATED FORM
+FB7F;FB7F;FB7F;0687;0687; # (ﭿ; ﭿ; ﭿ; ڇ; ڇ; ) ARABIC LETTER TCHEHEH FINAL FORM
+FB80;FB80;FB80;0687;0687; # (ﮀ; ﮀ; ﮀ; ڇ; ڇ; ) ARABIC LETTER TCHEHEH INITIAL FORM
+FB81;FB81;FB81;0687;0687; # (ﮁ; ﮁ; ﮁ; ڇ; ڇ; ) ARABIC LETTER TCHEHEH MEDIAL FORM
+FB82;FB82;FB82;068D;068D; # (ﮂ; ﮂ; ﮂ; ڍ; ڍ; ) ARABIC LETTER DDAHAL ISOLATED FORM
+FB83;FB83;FB83;068D;068D; # (ﮃ; ﮃ; ﮃ; ڍ; ڍ; ) ARABIC LETTER DDAHAL FINAL FORM
+FB84;FB84;FB84;068C;068C; # (ﮄ; ﮄ; ﮄ; ڌ; ڌ; ) ARABIC LETTER DAHAL ISOLATED FORM
+FB85;FB85;FB85;068C;068C; # (ﮅ; ﮅ; ﮅ; ڌ; ڌ; ) ARABIC LETTER DAHAL FINAL FORM
+FB86;FB86;FB86;068E;068E; # (ﮆ; ﮆ; ﮆ; ڎ; ڎ; ) ARABIC LETTER DUL ISOLATED FORM
+FB87;FB87;FB87;068E;068E; # (ﮇ; ﮇ; ﮇ; ڎ; ڎ; ) ARABIC LETTER DUL FINAL FORM
+FB88;FB88;FB88;0688;0688; # (ﮈ; ﮈ; ﮈ; ڈ; ڈ; ) ARABIC LETTER DDAL ISOLATED FORM
+FB89;FB89;FB89;0688;0688; # (ﮉ; ﮉ; ﮉ; ڈ; ڈ; ) ARABIC LETTER DDAL FINAL FORM
+FB8A;FB8A;FB8A;0698;0698; # (ﮊ; ﮊ; ﮊ; ژ; ژ; ) ARABIC LETTER JEH ISOLATED FORM
+FB8B;FB8B;FB8B;0698;0698; # (ﮋ; ﮋ; ﮋ; ژ; ژ; ) ARABIC LETTER JEH FINAL FORM
+FB8C;FB8C;FB8C;0691;0691; # (ﮌ; ﮌ; ﮌ; ڑ; ڑ; ) ARABIC LETTER RREH ISOLATED FORM
+FB8D;FB8D;FB8D;0691;0691; # (ﮍ; ﮍ; ﮍ; ڑ; ڑ; ) ARABIC LETTER RREH FINAL FORM
+FB8E;FB8E;FB8E;06A9;06A9; # (ﮎ; ﮎ; ﮎ; ک; ک; ) ARABIC LETTER KEHEH ISOLATED FORM
+FB8F;FB8F;FB8F;06A9;06A9; # (ﮏ; ﮏ; ﮏ; ک; ک; ) ARABIC LETTER KEHEH FINAL FORM
+FB90;FB90;FB90;06A9;06A9; # (ﮐ; ﮐ; ﮐ; ک; ک; ) ARABIC LETTER KEHEH INITIAL FORM
+FB91;FB91;FB91;06A9;06A9; # (ﮑ; ﮑ; ﮑ; ک; ک; ) ARABIC LETTER KEHEH MEDIAL FORM
+FB92;FB92;FB92;06AF;06AF; # (ﮒ; ﮒ; ﮒ; گ; گ; ) ARABIC LETTER GAF ISOLATED FORM
+FB93;FB93;FB93;06AF;06AF; # (ﮓ; ﮓ; ﮓ; گ; گ; ) ARABIC LETTER GAF FINAL FORM
+FB94;FB94;FB94;06AF;06AF; # (ﮔ; ﮔ; ﮔ; گ; گ; ) ARABIC LETTER GAF INITIAL FORM
+FB95;FB95;FB95;06AF;06AF; # (ﮕ; ﮕ; ﮕ; گ; گ; ) ARABIC LETTER GAF MEDIAL FORM
+FB96;FB96;FB96;06B3;06B3; # (ﮖ; ﮖ; ﮖ; ڳ; ڳ; ) ARABIC LETTER GUEH ISOLATED FORM
+FB97;FB97;FB97;06B3;06B3; # (ﮗ; ﮗ; ﮗ; ڳ; ڳ; ) ARABIC LETTER GUEH FINAL FORM
+FB98;FB98;FB98;06B3;06B3; # (ﮘ; ﮘ; ﮘ; ڳ; ڳ; ) ARABIC LETTER GUEH INITIAL FORM
+FB99;FB99;FB99;06B3;06B3; # (ﮙ; ﮙ; ﮙ; ڳ; ڳ; ) ARABIC LETTER GUEH MEDIAL FORM
+FB9A;FB9A;FB9A;06B1;06B1; # (ﮚ; ﮚ; ﮚ; ڱ; ڱ; ) ARABIC LETTER NGOEH ISOLATED FORM
+FB9B;FB9B;FB9B;06B1;06B1; # (ﮛ; ﮛ; ﮛ; ڱ; ڱ; ) ARABIC LETTER NGOEH FINAL FORM
+FB9C;FB9C;FB9C;06B1;06B1; # (ﮜ; ﮜ; ﮜ; ڱ; ڱ; ) ARABIC LETTER NGOEH INITIAL FORM
+FB9D;FB9D;FB9D;06B1;06B1; # (ﮝ; ﮝ; ﮝ; ڱ; ڱ; ) ARABIC LETTER NGOEH MEDIAL FORM
+FB9E;FB9E;FB9E;06BA;06BA; # (ﮞ; ﮞ; ﮞ; ں; ں; ) ARABIC LETTER NOON GHUNNA ISOLATED FORM
+FB9F;FB9F;FB9F;06BA;06BA; # (ﮟ; ﮟ; ﮟ; ں; ں; ) ARABIC LETTER NOON GHUNNA FINAL FORM
+FBA0;FBA0;FBA0;06BB;06BB; # (ﮠ; ﮠ; ﮠ; ڻ; ڻ; ) ARABIC LETTER RNOON ISOLATED FORM
+FBA1;FBA1;FBA1;06BB;06BB; # (ﮡ; ﮡ; ﮡ; ڻ; ڻ; ) ARABIC LETTER RNOON FINAL FORM
+FBA2;FBA2;FBA2;06BB;06BB; # (ﮢ; ﮢ; ﮢ; ڻ; ڻ; ) ARABIC LETTER RNOON INITIAL FORM
+FBA3;FBA3;FBA3;06BB;06BB; # (ﮣ; ﮣ; ﮣ; ڻ; ڻ; ) ARABIC LETTER RNOON MEDIAL FORM
+FBA4;FBA4;FBA4;06C0;06D5 0654; # (ﮤ; ﮤ; ﮤ; ۀ; ە◌ٔ; ) ARABIC LETTER HEH WITH YEH ABOVE ISOLATED FORM
+FBA5;FBA5;FBA5;06C0;06D5 0654; # (ﮥ; ﮥ; ﮥ; ۀ; ە◌ٔ; ) ARABIC LETTER HEH WITH YEH ABOVE FINAL FORM
+FBA6;FBA6;FBA6;06C1;06C1; # (ﮦ; ﮦ; ﮦ; ہ; ہ; ) ARABIC LETTER HEH GOAL ISOLATED FORM
+FBA7;FBA7;FBA7;06C1;06C1; # (ﮧ; ﮧ; ﮧ; ہ; ہ; ) ARABIC LETTER HEH GOAL FINAL FORM
+FBA8;FBA8;FBA8;06C1;06C1; # (ﮨ; ﮨ; ﮨ; ہ; ہ; ) ARABIC LETTER HEH GOAL INITIAL FORM
+FBA9;FBA9;FBA9;06C1;06C1; # (ﮩ; ﮩ; ﮩ; ہ; ہ; ) ARABIC LETTER HEH GOAL MEDIAL FORM
+FBAA;FBAA;FBAA;06BE;06BE; # (ﮪ; ﮪ; ﮪ; ھ; ھ; ) ARABIC LETTER HEH DOACHASHMEE ISOLATED FORM
+FBAB;FBAB;FBAB;06BE;06BE; # (ﮫ; ﮫ; ﮫ; ھ; ھ; ) ARABIC LETTER HEH DOACHASHMEE FINAL FORM
+FBAC;FBAC;FBAC;06BE;06BE; # (ﮬ; ﮬ; ﮬ; ھ; ھ; ) ARABIC LETTER HEH DOACHASHMEE INITIAL FORM
+FBAD;FBAD;FBAD;06BE;06BE; # (ﮭ; ﮭ; ﮭ; ھ; ھ; ) ARABIC LETTER HEH DOACHASHMEE MEDIAL FORM
+FBAE;FBAE;FBAE;06D2;06D2; # (ﮮ; ﮮ; ﮮ; ے; ے; ) ARABIC LETTER YEH BARREE ISOLATED FORM
+FBAF;FBAF;FBAF;06D2;06D2; # (ﮯ; ﮯ; ﮯ; ے; ے; ) ARABIC LETTER YEH BARREE FINAL FORM
+FBB0;FBB0;FBB0;06D3;06D2 0654; # (ﮰ; ﮰ; ﮰ; ۓ; ے◌ٔ; ) ARABIC LETTER YEH BARREE WITH HAMZA ABOVE ISOLATED FORM
+FBB1;FBB1;FBB1;06D3;06D2 0654; # (ﮱ; ﮱ; ﮱ; ۓ; ے◌ٔ; ) ARABIC LETTER YEH BARREE WITH HAMZA ABOVE FINAL FORM
+FBD3;FBD3;FBD3;06AD;06AD; # (ﯓ; ﯓ; ﯓ; ڭ; ڭ; ) ARABIC LETTER NG ISOLATED FORM
+FBD4;FBD4;FBD4;06AD;06AD; # (ﯔ; ﯔ; ﯔ; ڭ; ڭ; ) ARABIC LETTER NG FINAL FORM
+FBD5;FBD5;FBD5;06AD;06AD; # (ﯕ; ﯕ; ﯕ; ڭ; ڭ; ) ARABIC LETTER NG INITIAL FORM
+FBD6;FBD6;FBD6;06AD;06AD; # (ﯖ; ﯖ; ﯖ; ڭ; ڭ; ) ARABIC LETTER NG MEDIAL FORM
+FBD7;FBD7;FBD7;06C7;06C7; # (ﯗ; ﯗ; ﯗ; ۇ; ۇ; ) ARABIC LETTER U ISOLATED FORM
+FBD8;FBD8;FBD8;06C7;06C7; # (ﯘ; ﯘ; ﯘ; ۇ; ۇ; ) ARABIC LETTER U FINAL FORM
+FBD9;FBD9;FBD9;06C6;06C6; # (ﯙ; ﯙ; ﯙ; ۆ; ۆ; ) ARABIC LETTER OE ISOLATED FORM
+FBDA;FBDA;FBDA;06C6;06C6; # (ﯚ; ﯚ; ﯚ; ۆ; ۆ; ) ARABIC LETTER OE FINAL FORM
+FBDB;FBDB;FBDB;06C8;06C8; # (ﯛ; ﯛ; ﯛ; ۈ; ۈ; ) ARABIC LETTER YU ISOLATED FORM
+FBDC;FBDC;FBDC;06C8;06C8; # (ﯜ; ﯜ; ﯜ; ۈ; ۈ; ) ARABIC LETTER YU FINAL FORM
+FBDD;FBDD;FBDD;06C7 0674;06C7 0674; # (ﯝ; ﯝ; ﯝ; ۇٴ; ۇٴ; ) ARABIC LETTER U WITH HAMZA ABOVE ISOLATED FORM
+FBDE;FBDE;FBDE;06CB;06CB; # (ﯞ; ﯞ; ﯞ; ۋ; ۋ; ) ARABIC LETTER VE ISOLATED FORM
+FBDF;FBDF;FBDF;06CB;06CB; # (ﯟ; ﯟ; ﯟ; ۋ; ۋ; ) ARABIC LETTER VE FINAL FORM
+FBE0;FBE0;FBE0;06C5;06C5; # (ﯠ; ﯠ; ﯠ; ۅ; ۅ; ) ARABIC LETTER KIRGHIZ OE ISOLATED FORM
+FBE1;FBE1;FBE1;06C5;06C5; # (ﯡ; ﯡ; ﯡ; ۅ; ۅ; ) ARABIC LETTER KIRGHIZ OE FINAL FORM
+FBE2;FBE2;FBE2;06C9;06C9; # (ﯢ; ﯢ; ﯢ; ۉ; ۉ; ) ARABIC LETTER KIRGHIZ YU ISOLATED FORM
+FBE3;FBE3;FBE3;06C9;06C9; # (ﯣ; ﯣ; ﯣ; ۉ; ۉ; ) ARABIC LETTER KIRGHIZ YU FINAL FORM
+FBE4;FBE4;FBE4;06D0;06D0; # (ﯤ; ﯤ; ﯤ; ې; ې; ) ARABIC LETTER E ISOLATED FORM
+FBE5;FBE5;FBE5;06D0;06D0; # (ﯥ; ﯥ; ﯥ; ې; ې; ) ARABIC LETTER E FINAL FORM
+FBE6;FBE6;FBE6;06D0;06D0; # (ﯦ; ﯦ; ﯦ; ې; ې; ) ARABIC LETTER E INITIAL FORM
+FBE7;FBE7;FBE7;06D0;06D0; # (ﯧ; ﯧ; ﯧ; ې; ې; ) ARABIC LETTER E MEDIAL FORM
+FBE8;FBE8;FBE8;0649;0649; # (ﯨ; ﯨ; ﯨ; ى; ى; ) ARABIC LETTER UIGHUR KAZAKH KIRGHIZ ALEF MAKSURA INITIAL FORM
+FBE9;FBE9;FBE9;0649;0649; # (ﯩ; ﯩ; ﯩ; ى; ى; ) ARABIC LETTER UIGHUR KAZAKH KIRGHIZ ALEF MAKSURA MEDIAL FORM
+FBEA;FBEA;FBEA;0626 0627;064A 0654 0627; # (ﯪ; ﯪ; ﯪ; ئا; ي◌ٔا; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF ISOLATED FORM
+FBEB;FBEB;FBEB;0626 0627;064A 0654 0627; # (ﯫ; ﯫ; ﯫ; ئا; ي◌ٔا; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF FINAL FORM
+FBEC;FBEC;FBEC;0626 06D5;064A 0654 06D5; # (ﯬ; ﯬ; ﯬ; ئە; ي◌ٔە; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH AE ISOLATED FORM
+FBED;FBED;FBED;0626 06D5;064A 0654 06D5; # (ﯭ; ﯭ; ﯭ; ئە; ي◌ٔە; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH AE FINAL FORM
+FBEE;FBEE;FBEE;0626 0648;064A 0654 0648; # (ﯮ; ﯮ; ﯮ; ئو; ي◌ٔو; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH WAW ISOLATED FORM
+FBEF;FBEF;FBEF;0626 0648;064A 0654 0648; # (ﯯ; ﯯ; ﯯ; ئو; ي◌ٔو; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH WAW FINAL FORM
+FBF0;FBF0;FBF0;0626 06C7;064A 0654 06C7; # (ﯰ; ﯰ; ﯰ; ئۇ; ي◌ٔۇ; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH U ISOLATED FORM
+FBF1;FBF1;FBF1;0626 06C7;064A 0654 06C7; # (ﯱ; ﯱ; ﯱ; ئۇ; ي◌ٔۇ; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH U FINAL FORM
+FBF2;FBF2;FBF2;0626 06C6;064A 0654 06C6; # (ﯲ; ﯲ; ﯲ; ئۆ; ي◌ٔۆ; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH OE ISOLATED FORM
+FBF3;FBF3;FBF3;0626 06C6;064A 0654 06C6; # (ﯳ; ﯳ; ﯳ; ئۆ; ي◌ٔۆ; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH OE FINAL FORM
+FBF4;FBF4;FBF4;0626 06C8;064A 0654 06C8; # (ﯴ; ﯴ; ﯴ; ئۈ; ي◌ٔۈ; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH YU ISOLATED FORM
+FBF5;FBF5;FBF5;0626 06C8;064A 0654 06C8; # (ﯵ; ﯵ; ﯵ; ئۈ; ي◌ٔۈ; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH YU FINAL FORM
+FBF6;FBF6;FBF6;0626 06D0;064A 0654 06D0; # (ﯶ; ﯶ; ﯶ; ئې; ي◌ٔې; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH E ISOLATED FORM
+FBF7;FBF7;FBF7;0626 06D0;064A 0654 06D0; # (ﯷ; ﯷ; ﯷ; ئې; ي◌ٔې; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH E FINAL FORM
+FBF8;FBF8;FBF8;0626 06D0;064A 0654 06D0; # (ﯸ; ﯸ; ﯸ; ئې; ي◌ٔې; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH E INITIAL FORM
+FBF9;FBF9;FBF9;0626 0649;064A 0654 0649; # (ﯹ; ﯹ; ﯹ; ئى; ي◌ٔى; ) ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH HAMZA ABOVE WITH ALEF MAKSURA ISOLATED FORM
+FBFA;FBFA;FBFA;0626 0649;064A 0654 0649; # (ﯺ; ﯺ; ﯺ; ئى; ي◌ٔى; ) ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH HAMZA ABOVE WITH ALEF MAKSURA FINAL FORM
+FBFB;FBFB;FBFB;0626 0649;064A 0654 0649; # (ﯻ; ﯻ; ﯻ; ئى; ي◌ٔى; ) ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH HAMZA ABOVE WITH ALEF MAKSURA INITIAL FORM
+FBFC;FBFC;FBFC;06CC;06CC; # (ﯼ; ﯼ; ﯼ; ی; ی; ) ARABIC LETTER FARSI YEH ISOLATED FORM
+FBFD;FBFD;FBFD;06CC;06CC; # (ﯽ; ﯽ; ﯽ; ی; ی; ) ARABIC LETTER FARSI YEH FINAL FORM
+FBFE;FBFE;FBFE;06CC;06CC; # (ﯾ; ﯾ; ﯾ; ی; ی; ) ARABIC LETTER FARSI YEH INITIAL FORM
+FBFF;FBFF;FBFF;06CC;06CC; # (ﯿ; ﯿ; ﯿ; ی; ی; ) ARABIC LETTER FARSI YEH MEDIAL FORM
+FC00;FC00;FC00;0626 062C;064A 0654 062C; # (ﰀ; ﰀ; ﰀ; ئج; ي◌ٔج; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH JEEM ISOLATED FORM
+FC01;FC01;FC01;0626 062D;064A 0654 062D; # (ﰁ; ﰁ; ﰁ; ئح; ي◌ٔح; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH HAH ISOLATED FORM
+FC02;FC02;FC02;0626 0645;064A 0654 0645; # (ﰂ; ﰂ; ﰂ; ئم; ي◌ٔم; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH MEEM ISOLATED FORM
+FC03;FC03;FC03;0626 0649;064A 0654 0649; # (ﰃ; ﰃ; ﰃ; ئى; ي◌ٔى; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF MAKSURA ISOLATED FORM
+FC04;FC04;FC04;0626 064A;064A 0654 064A; # (ﰄ; ﰄ; ﰄ; ئي; ي◌ٔي; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH YEH ISOLATED FORM
+FC05;FC05;FC05;0628 062C;0628 062C; # (ﰅ; ﰅ; ﰅ; بج; بج; ) ARABIC LIGATURE BEH WITH JEEM ISOLATED FORM
+FC06;FC06;FC06;0628 062D;0628 062D; # (ﰆ; ﰆ; ﰆ; بح; بح; ) ARABIC LIGATURE BEH WITH HAH ISOLATED FORM
+FC07;FC07;FC07;0628 062E;0628 062E; # (ﰇ; ﰇ; ﰇ; بخ; بخ; ) ARABIC LIGATURE BEH WITH KHAH ISOLATED FORM
+FC08;FC08;FC08;0628 0645;0628 0645; # (ﰈ; ﰈ; ﰈ; بم; بم; ) ARABIC LIGATURE BEH WITH MEEM ISOLATED FORM
+FC09;FC09;FC09;0628 0649;0628 0649; # (ﰉ; ﰉ; ﰉ; بى; بى; ) ARABIC LIGATURE BEH WITH ALEF MAKSURA ISOLATED FORM
+FC0A;FC0A;FC0A;0628 064A;0628 064A; # (ﰊ; ﰊ; ﰊ; بي; بي; ) ARABIC LIGATURE BEH WITH YEH ISOLATED FORM
+FC0B;FC0B;FC0B;062A 062C;062A 062C; # (ﰋ; ﰋ; ﰋ; تج; تج; ) ARABIC LIGATURE TEH WITH JEEM ISOLATED FORM
+FC0C;FC0C;FC0C;062A 062D;062A 062D; # (ﰌ; ﰌ; ﰌ; تح; تح; ) ARABIC LIGATURE TEH WITH HAH ISOLATED FORM
+FC0D;FC0D;FC0D;062A 062E;062A 062E; # (ﰍ; ﰍ; ﰍ; تخ; تخ; ) ARABIC LIGATURE TEH WITH KHAH ISOLATED FORM
+FC0E;FC0E;FC0E;062A 0645;062A 0645; # (ﰎ; ﰎ; ﰎ; تم; تم; ) ARABIC LIGATURE TEH WITH MEEM ISOLATED FORM
+FC0F;FC0F;FC0F;062A 0649;062A 0649; # (ﰏ; ﰏ; ﰏ; تى; تى; ) ARABIC LIGATURE TEH WITH ALEF MAKSURA ISOLATED FORM
+FC10;FC10;FC10;062A 064A;062A 064A; # (ﰐ; ﰐ; ﰐ; تي; تي; ) ARABIC LIGATURE TEH WITH YEH ISOLATED FORM
+FC11;FC11;FC11;062B 062C;062B 062C; # (ﰑ; ﰑ; ﰑ; ثج; ثج; ) ARABIC LIGATURE THEH WITH JEEM ISOLATED FORM
+FC12;FC12;FC12;062B 0645;062B 0645; # (ﰒ; ﰒ; ﰒ; ثم; ثم; ) ARABIC LIGATURE THEH WITH MEEM ISOLATED FORM
+FC13;FC13;FC13;062B 0649;062B 0649; # (ﰓ; ﰓ; ﰓ; ثى; ثى; ) ARABIC LIGATURE THEH WITH ALEF MAKSURA ISOLATED FORM
+FC14;FC14;FC14;062B 064A;062B 064A; # (ﰔ; ﰔ; ﰔ; ثي; ثي; ) ARABIC LIGATURE THEH WITH YEH ISOLATED FORM
+FC15;FC15;FC15;062C 062D;062C 062D; # (ﰕ; ﰕ; ﰕ; جح; جح; ) ARABIC LIGATURE JEEM WITH HAH ISOLATED FORM
+FC16;FC16;FC16;062C 0645;062C 0645; # (ﰖ; ﰖ; ﰖ; جم; جم; ) ARABIC LIGATURE JEEM WITH MEEM ISOLATED FORM
+FC17;FC17;FC17;062D 062C;062D 062C; # (ﰗ; ﰗ; ﰗ; حج; حج; ) ARABIC LIGATURE HAH WITH JEEM ISOLATED FORM
+FC18;FC18;FC18;062D 0645;062D 0645; # (ﰘ; ﰘ; ﰘ; حم; حم; ) ARABIC LIGATURE HAH WITH MEEM ISOLATED FORM
+FC19;FC19;FC19;062E 062C;062E 062C; # (ﰙ; ﰙ; ﰙ; خج; خج; ) ARABIC LIGATURE KHAH WITH JEEM ISOLATED FORM
+FC1A;FC1A;FC1A;062E 062D;062E 062D; # (ﰚ; ﰚ; ﰚ; خح; خح; ) ARABIC LIGATURE KHAH WITH HAH ISOLATED FORM
+FC1B;FC1B;FC1B;062E 0645;062E 0645; # (ﰛ; ﰛ; ﰛ; خم; خم; ) ARABIC LIGATURE KHAH WITH MEEM ISOLATED FORM
+FC1C;FC1C;FC1C;0633 062C;0633 062C; # (ﰜ; ﰜ; ﰜ; سج; سج; ) ARABIC LIGATURE SEEN WITH JEEM ISOLATED FORM
+FC1D;FC1D;FC1D;0633 062D;0633 062D; # (ﰝ; ﰝ; ﰝ; سح; سح; ) ARABIC LIGATURE SEEN WITH HAH ISOLATED FORM
+FC1E;FC1E;FC1E;0633 062E;0633 062E; # (ﰞ; ﰞ; ﰞ; سخ; سخ; ) ARABIC LIGATURE SEEN WITH KHAH ISOLATED FORM
+FC1F;FC1F;FC1F;0633 0645;0633 0645; # (ﰟ; ﰟ; ﰟ; سم; سم; ) ARABIC LIGATURE SEEN WITH MEEM ISOLATED FORM
+FC20;FC20;FC20;0635 062D;0635 062D; # (ﰠ; ﰠ; ﰠ; صح; صح; ) ARABIC LIGATURE SAD WITH HAH ISOLATED FORM
+FC21;FC21;FC21;0635 0645;0635 0645; # (ﰡ; ﰡ; ﰡ; صم; صم; ) ARABIC LIGATURE SAD WITH MEEM ISOLATED FORM
+FC22;FC22;FC22;0636 062C;0636 062C; # (ﰢ; ﰢ; ﰢ; ضج; ضج; ) ARABIC LIGATURE DAD WITH JEEM ISOLATED FORM
+FC23;FC23;FC23;0636 062D;0636 062D; # (ﰣ; ﰣ; ﰣ; ضح; ضح; ) ARABIC LIGATURE DAD WITH HAH ISOLATED FORM
+FC24;FC24;FC24;0636 062E;0636 062E; # (ﰤ; ﰤ; ﰤ; ضخ; ضخ; ) ARABIC LIGATURE DAD WITH KHAH ISOLATED FORM
+FC25;FC25;FC25;0636 0645;0636 0645; # (ﰥ; ﰥ; ﰥ; ضم; ضم; ) ARABIC LIGATURE DAD WITH MEEM ISOLATED FORM
+FC26;FC26;FC26;0637 062D;0637 062D; # (ﰦ; ﰦ; ﰦ; طح; طح; ) ARABIC LIGATURE TAH WITH HAH ISOLATED FORM
+FC27;FC27;FC27;0637 0645;0637 0645; # (ﰧ; ﰧ; ﰧ; طم; طم; ) ARABIC LIGATURE TAH WITH MEEM ISOLATED FORM
+FC28;FC28;FC28;0638 0645;0638 0645; # (ﰨ; ﰨ; ﰨ; ظم; ظم; ) ARABIC LIGATURE ZAH WITH MEEM ISOLATED FORM
+FC29;FC29;FC29;0639 062C;0639 062C; # (ﰩ; ﰩ; ﰩ; عج; عج; ) ARABIC LIGATURE AIN WITH JEEM ISOLATED FORM
+FC2A;FC2A;FC2A;0639 0645;0639 0645; # (ﰪ; ﰪ; ﰪ; عم; عم; ) ARABIC LIGATURE AIN WITH MEEM ISOLATED FORM
+FC2B;FC2B;FC2B;063A 062C;063A 062C; # (ﰫ; ﰫ; ﰫ; غج; غج; ) ARABIC LIGATURE GHAIN WITH JEEM ISOLATED FORM
+FC2C;FC2C;FC2C;063A 0645;063A 0645; # (ﰬ; ﰬ; ﰬ; غم; غم; ) ARABIC LIGATURE GHAIN WITH MEEM ISOLATED FORM
+FC2D;FC2D;FC2D;0641 062C;0641 062C; # (ﰭ; ﰭ; ﰭ; فج; فج; ) ARABIC LIGATURE FEH WITH JEEM ISOLATED FORM
+FC2E;FC2E;FC2E;0641 062D;0641 062D; # (ﰮ; ﰮ; ﰮ; فح; فح; ) ARABIC LIGATURE FEH WITH HAH ISOLATED FORM
+FC2F;FC2F;FC2F;0641 062E;0641 062E; # (ﰯ; ﰯ; ﰯ; فخ; فخ; ) ARABIC LIGATURE FEH WITH KHAH ISOLATED FORM
+FC30;FC30;FC30;0641 0645;0641 0645; # (ﰰ; ﰰ; ﰰ; فم; فم; ) ARABIC LIGATURE FEH WITH MEEM ISOLATED FORM
+FC31;FC31;FC31;0641 0649;0641 0649; # (ﰱ; ﰱ; ﰱ; فى; فى; ) ARABIC LIGATURE FEH WITH ALEF MAKSURA ISOLATED FORM
+FC32;FC32;FC32;0641 064A;0641 064A; # (ﰲ; ﰲ; ﰲ; في; في; ) ARABIC LIGATURE FEH WITH YEH ISOLATED FORM
+FC33;FC33;FC33;0642 062D;0642 062D; # (ﰳ; ﰳ; ﰳ; قح; قح; ) ARABIC LIGATURE QAF WITH HAH ISOLATED FORM
+FC34;FC34;FC34;0642 0645;0642 0645; # (ﰴ; ﰴ; ﰴ; قم; قم; ) ARABIC LIGATURE QAF WITH MEEM ISOLATED FORM
+FC35;FC35;FC35;0642 0649;0642 0649; # (ﰵ; ﰵ; ﰵ; قى; قى; ) ARABIC LIGATURE QAF WITH ALEF MAKSURA ISOLATED FORM
+FC36;FC36;FC36;0642 064A;0642 064A; # (ﰶ; ﰶ; ﰶ; قي; قي; ) ARABIC LIGATURE QAF WITH YEH ISOLATED FORM
+FC37;FC37;FC37;0643 0627;0643 0627; # (ﰷ; ﰷ; ﰷ; كا; كا; ) ARABIC LIGATURE KAF WITH ALEF ISOLATED FORM
+FC38;FC38;FC38;0643 062C;0643 062C; # (ﰸ; ﰸ; ﰸ; كج; كج; ) ARABIC LIGATURE KAF WITH JEEM ISOLATED FORM
+FC39;FC39;FC39;0643 062D;0643 062D; # (ﰹ; ﰹ; ﰹ; كح; كح; ) ARABIC LIGATURE KAF WITH HAH ISOLATED FORM
+FC3A;FC3A;FC3A;0643 062E;0643 062E; # (ﰺ; ﰺ; ﰺ; كخ; كخ; ) ARABIC LIGATURE KAF WITH KHAH ISOLATED FORM
+FC3B;FC3B;FC3B;0643 0644;0643 0644; # (ﰻ; ﰻ; ﰻ; كل; كل; ) ARABIC LIGATURE KAF WITH LAM ISOLATED FORM
+FC3C;FC3C;FC3C;0643 0645;0643 0645; # (ﰼ; ﰼ; ﰼ; كم; كم; ) ARABIC LIGATURE KAF WITH MEEM ISOLATED FORM
+FC3D;FC3D;FC3D;0643 0649;0643 0649; # (ﰽ; ﰽ; ﰽ; كى; كى; ) ARABIC LIGATURE KAF WITH ALEF MAKSURA ISOLATED FORM
+FC3E;FC3E;FC3E;0643 064A;0643 064A; # (ﰾ; ﰾ; ﰾ; كي; كي; ) ARABIC LIGATURE KAF WITH YEH ISOLATED FORM
+FC3F;FC3F;FC3F;0644 062C;0644 062C; # (ﰿ; ﰿ; ﰿ; لج; لج; ) ARABIC LIGATURE LAM WITH JEEM ISOLATED FORM
+FC40;FC40;FC40;0644 062D;0644 062D; # (ﱀ; ﱀ; ﱀ; لح; لح; ) ARABIC LIGATURE LAM WITH HAH ISOLATED FORM
+FC41;FC41;FC41;0644 062E;0644 062E; # (ﱁ; ﱁ; ﱁ; لخ; لخ; ) ARABIC LIGATURE LAM WITH KHAH ISOLATED FORM
+FC42;FC42;FC42;0644 0645;0644 0645; # (ﱂ; ﱂ; ﱂ; لم; لم; ) ARABIC LIGATURE LAM WITH MEEM ISOLATED FORM
+FC43;FC43;FC43;0644 0649;0644 0649; # (ﱃ; ﱃ; ﱃ; لى; لى; ) ARABIC LIGATURE LAM WITH ALEF MAKSURA ISOLATED FORM
+FC44;FC44;FC44;0644 064A;0644 064A; # (ﱄ; ﱄ; ﱄ; لي; لي; ) ARABIC LIGATURE LAM WITH YEH ISOLATED FORM
+FC45;FC45;FC45;0645 062C;0645 062C; # (ﱅ; ﱅ; ﱅ; مج; مج; ) ARABIC LIGATURE MEEM WITH JEEM ISOLATED FORM
+FC46;FC46;FC46;0645 062D;0645 062D; # (ﱆ; ﱆ; ﱆ; مح; مح; ) ARABIC LIGATURE MEEM WITH HAH ISOLATED FORM
+FC47;FC47;FC47;0645 062E;0645 062E; # (ﱇ; ﱇ; ﱇ; مخ; مخ; ) ARABIC LIGATURE MEEM WITH KHAH ISOLATED FORM
+FC48;FC48;FC48;0645 0645;0645 0645; # (ﱈ; ﱈ; ﱈ; مم; مم; ) ARABIC LIGATURE MEEM WITH MEEM ISOLATED FORM
+FC49;FC49;FC49;0645 0649;0645 0649; # (ﱉ; ﱉ; ﱉ; مى; مى; ) ARABIC LIGATURE MEEM WITH ALEF MAKSURA ISOLATED FORM
+FC4A;FC4A;FC4A;0645 064A;0645 064A; # (ﱊ; ﱊ; ﱊ; مي; مي; ) ARABIC LIGATURE MEEM WITH YEH ISOLATED FORM
+FC4B;FC4B;FC4B;0646 062C;0646 062C; # (ﱋ; ﱋ; ﱋ; نج; نج; ) ARABIC LIGATURE NOON WITH JEEM ISOLATED FORM
+FC4C;FC4C;FC4C;0646 062D;0646 062D; # (ﱌ; ﱌ; ﱌ; نح; نح; ) ARABIC LIGATURE NOON WITH HAH ISOLATED FORM
+FC4D;FC4D;FC4D;0646 062E;0646 062E; # (ﱍ; ﱍ; ﱍ; نخ; نخ; ) ARABIC LIGATURE NOON WITH KHAH ISOLATED FORM
+FC4E;FC4E;FC4E;0646 0645;0646 0645; # (ﱎ; ﱎ; ﱎ; نم; نم; ) ARABIC LIGATURE NOON WITH MEEM ISOLATED FORM
+FC4F;FC4F;FC4F;0646 0649;0646 0649; # (ﱏ; ﱏ; ﱏ; نى; نى; ) ARABIC LIGATURE NOON WITH ALEF MAKSURA ISOLATED FORM
+FC50;FC50;FC50;0646 064A;0646 064A; # (ﱐ; ﱐ; ﱐ; ني; ني; ) ARABIC LIGATURE NOON WITH YEH ISOLATED FORM
+FC51;FC51;FC51;0647 062C;0647 062C; # (ﱑ; ﱑ; ﱑ; هج; هج; ) ARABIC LIGATURE HEH WITH JEEM ISOLATED FORM
+FC52;FC52;FC52;0647 0645;0647 0645; # (ﱒ; ﱒ; ﱒ; هم; هم; ) ARABIC LIGATURE HEH WITH MEEM ISOLATED FORM
+FC53;FC53;FC53;0647 0649;0647 0649; # (ﱓ; ﱓ; ﱓ; هى; هى; ) ARABIC LIGATURE HEH WITH ALEF MAKSURA ISOLATED FORM
+FC54;FC54;FC54;0647 064A;0647 064A; # (ﱔ; ﱔ; ﱔ; هي; هي; ) ARABIC LIGATURE HEH WITH YEH ISOLATED FORM
+FC55;FC55;FC55;064A 062C;064A 062C; # (ﱕ; ﱕ; ﱕ; يج; يج; ) ARABIC LIGATURE YEH WITH JEEM ISOLATED FORM
+FC56;FC56;FC56;064A 062D;064A 062D; # (ﱖ; ﱖ; ﱖ; يح; يح; ) ARABIC LIGATURE YEH WITH HAH ISOLATED FORM
+FC57;FC57;FC57;064A 062E;064A 062E; # (ﱗ; ﱗ; ﱗ; يخ; يخ; ) ARABIC LIGATURE YEH WITH KHAH ISOLATED FORM
+FC58;FC58;FC58;064A 0645;064A 0645; # (ﱘ; ﱘ; ﱘ; يم; يم; ) ARABIC LIGATURE YEH WITH MEEM ISOLATED FORM
+FC59;FC59;FC59;064A 0649;064A 0649; # (ﱙ; ﱙ; ﱙ; يى; يى; ) ARABIC LIGATURE YEH WITH ALEF MAKSURA ISOLATED FORM
+FC5A;FC5A;FC5A;064A 064A;064A 064A; # (ﱚ; ﱚ; ﱚ; يي; يي; ) ARABIC LIGATURE YEH WITH YEH ISOLATED FORM
+FC5B;FC5B;FC5B;0630 0670;0630 0670; # (ﱛ; ﱛ; ﱛ; ذ◌ٰ; ذ◌ٰ; ) ARABIC LIGATURE THAL WITH SUPERSCRIPT ALEF ISOLATED FORM
+FC5C;FC5C;FC5C;0631 0670;0631 0670; # (ﱜ; ﱜ; ﱜ; ر◌ٰ; ر◌ٰ; ) ARABIC LIGATURE REH WITH SUPERSCRIPT ALEF ISOLATED FORM
+FC5D;FC5D;FC5D;0649 0670;0649 0670; # (ﱝ; ﱝ; ﱝ; ى◌ٰ; ى◌ٰ; ) ARABIC LIGATURE ALEF MAKSURA WITH SUPERSCRIPT ALEF ISOLATED FORM
+FC5E;FC5E;FC5E;0020 064C 0651;0020 064C 0651; # (ﱞ; ﱞ; ﱞ; ◌ٌ◌ّ; ◌ٌ◌ّ; ) ARABIC LIGATURE SHADDA WITH DAMMATAN ISOLATED FORM
+FC5F;FC5F;FC5F;0020 064D 0651;0020 064D 0651; # (ﱟ; ﱟ; ﱟ; ◌ٍ◌ّ; ◌ٍ◌ّ; ) ARABIC LIGATURE SHADDA WITH KASRATAN ISOLATED FORM
+FC60;FC60;FC60;0020 064E 0651;0020 064E 0651; # (ﱠ; ﱠ; ﱠ; ◌َ◌ّ; ◌َ◌ّ; ) ARABIC LIGATURE SHADDA WITH FATHA ISOLATED FORM
+FC61;FC61;FC61;0020 064F 0651;0020 064F 0651; # (ﱡ; ﱡ; ﱡ; ◌ُ◌ّ; ◌ُ◌ّ; ) ARABIC LIGATURE SHADDA WITH DAMMA ISOLATED FORM
+FC62;FC62;FC62;0020 0650 0651;0020 0650 0651; # (ﱢ; ﱢ; ﱢ; ◌ِ◌ّ; ◌ِ◌ّ; ) ARABIC LIGATURE SHADDA WITH KASRA ISOLATED FORM
+FC63;FC63;FC63;0020 0651 0670;0020 0651 0670; # (ﱣ; ﱣ; ﱣ; ◌ّ◌ٰ; ◌ّ◌ٰ; ) ARABIC LIGATURE SHADDA WITH SUPERSCRIPT ALEF ISOLATED FORM
+FC64;FC64;FC64;0626 0631;064A 0654 0631; # (ﱤ; ﱤ; ﱤ; ئر; ي◌ٔر; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH REH FINAL FORM
+FC65;FC65;FC65;0626 0632;064A 0654 0632; # (ﱥ; ﱥ; ﱥ; ئز; ي◌ٔز; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ZAIN FINAL FORM
+FC66;FC66;FC66;0626 0645;064A 0654 0645; # (ﱦ; ﱦ; ﱦ; ئم; ي◌ٔم; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH MEEM FINAL FORM
+FC67;FC67;FC67;0626 0646;064A 0654 0646; # (ﱧ; ﱧ; ﱧ; ئن; ي◌ٔن; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH NOON FINAL FORM
+FC68;FC68;FC68;0626 0649;064A 0654 0649; # (ﱨ; ﱨ; ﱨ; ئى; ي◌ٔى; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF MAKSURA FINAL FORM
+FC69;FC69;FC69;0626 064A;064A 0654 064A; # (ﱩ; ﱩ; ﱩ; ئي; ي◌ٔي; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH YEH FINAL FORM
+FC6A;FC6A;FC6A;0628 0631;0628 0631; # (ﱪ; ﱪ; ﱪ; بر; بر; ) ARABIC LIGATURE BEH WITH REH FINAL FORM
+FC6B;FC6B;FC6B;0628 0632;0628 0632; # (ﱫ; ﱫ; ﱫ; بز; بز; ) ARABIC LIGATURE BEH WITH ZAIN FINAL FORM
+FC6C;FC6C;FC6C;0628 0645;0628 0645; # (ﱬ; ﱬ; ﱬ; بم; بم; ) ARABIC LIGATURE BEH WITH MEEM FINAL FORM
+FC6D;FC6D;FC6D;0628 0646;0628 0646; # (ﱭ; ﱭ; ﱭ; بن; بن; ) ARABIC LIGATURE BEH WITH NOON FINAL FORM
+FC6E;FC6E;FC6E;0628 0649;0628 0649; # (ﱮ; ﱮ; ﱮ; بى; بى; ) ARABIC LIGATURE BEH WITH ALEF MAKSURA FINAL FORM
+FC6F;FC6F;FC6F;0628 064A;0628 064A; # (ﱯ; ﱯ; ﱯ; بي; بي; ) ARABIC LIGATURE BEH WITH YEH FINAL FORM
+FC70;FC70;FC70;062A 0631;062A 0631; # (ﱰ; ﱰ; ﱰ; تر; تر; ) ARABIC LIGATURE TEH WITH REH FINAL FORM
+FC71;FC71;FC71;062A 0632;062A 0632; # (ﱱ; ﱱ; ﱱ; تز; تز; ) ARABIC LIGATURE TEH WITH ZAIN FINAL FORM
+FC72;FC72;FC72;062A 0645;062A 0645; # (ﱲ; ﱲ; ﱲ; تم; تم; ) ARABIC LIGATURE TEH WITH MEEM FINAL FORM
+FC73;FC73;FC73;062A 0646;062A 0646; # (ﱳ; ﱳ; ﱳ; تن; تن; ) ARABIC LIGATURE TEH WITH NOON FINAL FORM
+FC74;FC74;FC74;062A 0649;062A 0649; # (ﱴ; ﱴ; ﱴ; تى; تى; ) ARABIC LIGATURE TEH WITH ALEF MAKSURA FINAL FORM
+FC75;FC75;FC75;062A 064A;062A 064A; # (ﱵ; ﱵ; ﱵ; تي; تي; ) ARABIC LIGATURE TEH WITH YEH FINAL FORM
+FC76;FC76;FC76;062B 0631;062B 0631; # (ﱶ; ﱶ; ﱶ; ثر; ثر; ) ARABIC LIGATURE THEH WITH REH FINAL FORM
+FC77;FC77;FC77;062B 0632;062B 0632; # (ﱷ; ﱷ; ﱷ; ثز; ثز; ) ARABIC LIGATURE THEH WITH ZAIN FINAL FORM
+FC78;FC78;FC78;062B 0645;062B 0645; # (ﱸ; ﱸ; ﱸ; ثم; ثم; ) ARABIC LIGATURE THEH WITH MEEM FINAL FORM
+FC79;FC79;FC79;062B 0646;062B 0646; # (ﱹ; ﱹ; ﱹ; ثن; ثن; ) ARABIC LIGATURE THEH WITH NOON FINAL FORM
+FC7A;FC7A;FC7A;062B 0649;062B 0649; # (ﱺ; ﱺ; ﱺ; ثى; ثى; ) ARABIC LIGATURE THEH WITH ALEF MAKSURA FINAL FORM
+FC7B;FC7B;FC7B;062B 064A;062B 064A; # (ﱻ; ﱻ; ﱻ; ثي; ثي; ) ARABIC LIGATURE THEH WITH YEH FINAL FORM
+FC7C;FC7C;FC7C;0641 0649;0641 0649; # (ﱼ; ﱼ; ﱼ; فى; فى; ) ARABIC LIGATURE FEH WITH ALEF MAKSURA FINAL FORM
+FC7D;FC7D;FC7D;0641 064A;0641 064A; # (ﱽ; ﱽ; ﱽ; في; في; ) ARABIC LIGATURE FEH WITH YEH FINAL FORM
+FC7E;FC7E;FC7E;0642 0649;0642 0649; # (ﱾ; ﱾ; ﱾ; قى; قى; ) ARABIC LIGATURE QAF WITH ALEF MAKSURA FINAL FORM
+FC7F;FC7F;FC7F;0642 064A;0642 064A; # (ﱿ; ﱿ; ﱿ; قي; قي; ) ARABIC LIGATURE QAF WITH YEH FINAL FORM
+FC80;FC80;FC80;0643 0627;0643 0627; # (ﲀ; ﲀ; ﲀ; كا; كا; ) ARABIC LIGATURE KAF WITH ALEF FINAL FORM
+FC81;FC81;FC81;0643 0644;0643 0644; # (ﲁ; ﲁ; ﲁ; كل; كل; ) ARABIC LIGATURE KAF WITH LAM FINAL FORM
+FC82;FC82;FC82;0643 0645;0643 0645; # (ﲂ; ﲂ; ﲂ; كم; كم; ) ARABIC LIGATURE KAF WITH MEEM FINAL FORM
+FC83;FC83;FC83;0643 0649;0643 0649; # (ﲃ; ﲃ; ﲃ; كى; كى; ) ARABIC LIGATURE KAF WITH ALEF MAKSURA FINAL FORM
+FC84;FC84;FC84;0643 064A;0643 064A; # (ﲄ; ﲄ; ﲄ; كي; كي; ) ARABIC LIGATURE KAF WITH YEH FINAL FORM
+FC85;FC85;FC85;0644 0645;0644 0645; # (ﲅ; ﲅ; ﲅ; لم; لم; ) ARABIC LIGATURE LAM WITH MEEM FINAL FORM
+FC86;FC86;FC86;0644 0649;0644 0649; # (ﲆ; ﲆ; ﲆ; لى; لى; ) ARABIC LIGATURE LAM WITH ALEF MAKSURA FINAL FORM
+FC87;FC87;FC87;0644 064A;0644 064A; # (ﲇ; ﲇ; ﲇ; لي; لي; ) ARABIC LIGATURE LAM WITH YEH FINAL FORM
+FC88;FC88;FC88;0645 0627;0645 0627; # (ﲈ; ﲈ; ﲈ; ما; ما; ) ARABIC LIGATURE MEEM WITH ALEF FINAL FORM
+FC89;FC89;FC89;0645 0645;0645 0645; # (ﲉ; ﲉ; ﲉ; مم; مم; ) ARABIC LIGATURE MEEM WITH MEEM FINAL FORM
+FC8A;FC8A;FC8A;0646 0631;0646 0631; # (ﲊ; ﲊ; ﲊ; نر; نر; ) ARABIC LIGATURE NOON WITH REH FINAL FORM
+FC8B;FC8B;FC8B;0646 0632;0646 0632; # (ﲋ; ﲋ; ﲋ; نز; نز; ) ARABIC LIGATURE NOON WITH ZAIN FINAL FORM
+FC8C;FC8C;FC8C;0646 0645;0646 0645; # (ﲌ; ﲌ; ﲌ; نم; نم; ) ARABIC LIGATURE NOON WITH MEEM FINAL FORM
+FC8D;FC8D;FC8D;0646 0646;0646 0646; # (ﲍ; ﲍ; ﲍ; نن; نن; ) ARABIC LIGATURE NOON WITH NOON FINAL FORM
+FC8E;FC8E;FC8E;0646 0649;0646 0649; # (ﲎ; ﲎ; ﲎ; نى; نى; ) ARABIC LIGATURE NOON WITH ALEF MAKSURA FINAL FORM
+FC8F;FC8F;FC8F;0646 064A;0646 064A; # (ﲏ; ﲏ; ﲏ; ني; ني; ) ARABIC LIGATURE NOON WITH YEH FINAL FORM
+FC90;FC90;FC90;0649 0670;0649 0670; # (ﲐ; ﲐ; ﲐ; ى◌ٰ; ى◌ٰ; ) ARABIC LIGATURE ALEF MAKSURA WITH SUPERSCRIPT ALEF FINAL FORM
+FC91;FC91;FC91;064A 0631;064A 0631; # (ﲑ; ﲑ; ﲑ; ير; ير; ) ARABIC LIGATURE YEH WITH REH FINAL FORM
+FC92;FC92;FC92;064A 0632;064A 0632; # (ﲒ; ﲒ; ﲒ; يز; يز; ) ARABIC LIGATURE YEH WITH ZAIN FINAL FORM
+FC93;FC93;FC93;064A 0645;064A 0645; # (ﲓ; ﲓ; ﲓ; يم; يم; ) ARABIC LIGATURE YEH WITH MEEM FINAL FORM
+FC94;FC94;FC94;064A 0646;064A 0646; # (ﲔ; ﲔ; ﲔ; ين; ين; ) ARABIC LIGATURE YEH WITH NOON FINAL FORM
+FC95;FC95;FC95;064A 0649;064A 0649; # (ﲕ; ﲕ; ﲕ; يى; يى; ) ARABIC LIGATURE YEH WITH ALEF MAKSURA FINAL FORM
+FC96;FC96;FC96;064A 064A;064A 064A; # (ﲖ; ﲖ; ﲖ; يي; يي; ) ARABIC LIGATURE YEH WITH YEH FINAL FORM
+FC97;FC97;FC97;0626 062C;064A 0654 062C; # (ﲗ; ﲗ; ﲗ; ئج; ي◌ٔج; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH JEEM INITIAL FORM
+FC98;FC98;FC98;0626 062D;064A 0654 062D; # (ﲘ; ﲘ; ﲘ; ئح; ي◌ٔح; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH HAH INITIAL FORM
+FC99;FC99;FC99;0626 062E;064A 0654 062E; # (ﲙ; ﲙ; ﲙ; ئخ; ي◌ٔخ; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH KHAH INITIAL FORM
+FC9A;FC9A;FC9A;0626 0645;064A 0654 0645; # (ﲚ; ﲚ; ﲚ; ئم; ي◌ٔم; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH MEEM INITIAL FORM
+FC9B;FC9B;FC9B;0626 0647;064A 0654 0647; # (ﲛ; ﲛ; ﲛ; ئه; ي◌ٔه; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH HEH INITIAL FORM
+FC9C;FC9C;FC9C;0628 062C;0628 062C; # (ﲜ; ﲜ; ﲜ; بج; بج; ) ARABIC LIGATURE BEH WITH JEEM INITIAL FORM
+FC9D;FC9D;FC9D;0628 062D;0628 062D; # (ﲝ; ﲝ; ﲝ; بح; بح; ) ARABIC LIGATURE BEH WITH HAH INITIAL FORM
+FC9E;FC9E;FC9E;0628 062E;0628 062E; # (ﲞ; ﲞ; ﲞ; بخ; بخ; ) ARABIC LIGATURE BEH WITH KHAH INITIAL FORM
+FC9F;FC9F;FC9F;0628 0645;0628 0645; # (ﲟ; ﲟ; ﲟ; بم; بم; ) ARABIC LIGATURE BEH WITH MEEM INITIAL FORM
+FCA0;FCA0;FCA0;0628 0647;0628 0647; # (ﲠ; ﲠ; ﲠ; به; به; ) ARABIC LIGATURE BEH WITH HEH INITIAL FORM
+FCA1;FCA1;FCA1;062A 062C;062A 062C; # (ﲡ; ﲡ; ﲡ; تج; تج; ) ARABIC LIGATURE TEH WITH JEEM INITIAL FORM
+FCA2;FCA2;FCA2;062A 062D;062A 062D; # (ﲢ; ﲢ; ﲢ; تح; تح; ) ARABIC LIGATURE TEH WITH HAH INITIAL FORM
+FCA3;FCA3;FCA3;062A 062E;062A 062E; # (ﲣ; ﲣ; ﲣ; تخ; تخ; ) ARABIC LIGATURE TEH WITH KHAH INITIAL FORM
+FCA4;FCA4;FCA4;062A 0645;062A 0645; # (ﲤ; ﲤ; ﲤ; تم; تم; ) ARABIC LIGATURE TEH WITH MEEM INITIAL FORM
+FCA5;FCA5;FCA5;062A 0647;062A 0647; # (ﲥ; ﲥ; ﲥ; ته; ته; ) ARABIC LIGATURE TEH WITH HEH INITIAL FORM
+FCA6;FCA6;FCA6;062B 0645;062B 0645; # (ﲦ; ﲦ; ﲦ; ثم; ثم; ) ARABIC LIGATURE THEH WITH MEEM INITIAL FORM
+FCA7;FCA7;FCA7;062C 062D;062C 062D; # (ﲧ; ﲧ; ﲧ; جح; جح; ) ARABIC LIGATURE JEEM WITH HAH INITIAL FORM
+FCA8;FCA8;FCA8;062C 0645;062C 0645; # (ﲨ; ﲨ; ﲨ; جم; جم; ) ARABIC LIGATURE JEEM WITH MEEM INITIAL FORM
+FCA9;FCA9;FCA9;062D 062C;062D 062C; # (ﲩ; ﲩ; ﲩ; حج; حج; ) ARABIC LIGATURE HAH WITH JEEM INITIAL FORM
+FCAA;FCAA;FCAA;062D 0645;062D 0645; # (ﲪ; ﲪ; ﲪ; حم; حم; ) ARABIC LIGATURE HAH WITH MEEM INITIAL FORM
+FCAB;FCAB;FCAB;062E 062C;062E 062C; # (ﲫ; ﲫ; ﲫ; خج; خج; ) ARABIC LIGATURE KHAH WITH JEEM INITIAL FORM
+FCAC;FCAC;FCAC;062E 0645;062E 0645; # (ﲬ; ﲬ; ﲬ; خم; خم; ) ARABIC LIGATURE KHAH WITH MEEM INITIAL FORM
+FCAD;FCAD;FCAD;0633 062C;0633 062C; # (ﲭ; ﲭ; ﲭ; سج; سج; ) ARABIC LIGATURE SEEN WITH JEEM INITIAL FORM
+FCAE;FCAE;FCAE;0633 062D;0633 062D; # (ﲮ; ﲮ; ﲮ; سح; سح; ) ARABIC LIGATURE SEEN WITH HAH INITIAL FORM
+FCAF;FCAF;FCAF;0633 062E;0633 062E; # (ﲯ; ﲯ; ﲯ; سخ; سخ; ) ARABIC LIGATURE SEEN WITH KHAH INITIAL FORM
+FCB0;FCB0;FCB0;0633 0645;0633 0645; # (ﲰ; ﲰ; ﲰ; سم; سم; ) ARABIC LIGATURE SEEN WITH MEEM INITIAL FORM
+FCB1;FCB1;FCB1;0635 062D;0635 062D; # (ﲱ; ﲱ; ﲱ; صح; صح; ) ARABIC LIGATURE SAD WITH HAH INITIAL FORM
+FCB2;FCB2;FCB2;0635 062E;0635 062E; # (ﲲ; ﲲ; ﲲ; صخ; صخ; ) ARABIC LIGATURE SAD WITH KHAH INITIAL FORM
+FCB3;FCB3;FCB3;0635 0645;0635 0645; # (ﲳ; ﲳ; ﲳ; صم; صم; ) ARABIC LIGATURE SAD WITH MEEM INITIAL FORM
+FCB4;FCB4;FCB4;0636 062C;0636 062C; # (ﲴ; ﲴ; ﲴ; ضج; ضج; ) ARABIC LIGATURE DAD WITH JEEM INITIAL FORM
+FCB5;FCB5;FCB5;0636 062D;0636 062D; # (ﲵ; ﲵ; ﲵ; ضح; ضح; ) ARABIC LIGATURE DAD WITH HAH INITIAL FORM
+FCB6;FCB6;FCB6;0636 062E;0636 062E; # (ﲶ; ﲶ; ﲶ; ضخ; ضخ; ) ARABIC LIGATURE DAD WITH KHAH INITIAL FORM
+FCB7;FCB7;FCB7;0636 0645;0636 0645; # (ﲷ; ﲷ; ﲷ; ضم; ضم; ) ARABIC LIGATURE DAD WITH MEEM INITIAL FORM
+FCB8;FCB8;FCB8;0637 062D;0637 062D; # (ﲸ; ﲸ; ﲸ; طح; طح; ) ARABIC LIGATURE TAH WITH HAH INITIAL FORM
+FCB9;FCB9;FCB9;0638 0645;0638 0645; # (ﲹ; ﲹ; ﲹ; ظم; ظم; ) ARABIC LIGATURE ZAH WITH MEEM INITIAL FORM
+FCBA;FCBA;FCBA;0639 062C;0639 062C; # (ﲺ; ﲺ; ﲺ; عج; عج; ) ARABIC LIGATURE AIN WITH JEEM INITIAL FORM
+FCBB;FCBB;FCBB;0639 0645;0639 0645; # (ﲻ; ﲻ; ﲻ; عم; عم; ) ARABIC LIGATURE AIN WITH MEEM INITIAL FORM
+FCBC;FCBC;FCBC;063A 062C;063A 062C; # (ﲼ; ﲼ; ﲼ; غج; غج; ) ARABIC LIGATURE GHAIN WITH JEEM INITIAL FORM
+FCBD;FCBD;FCBD;063A 0645;063A 0645; # (ﲽ; ﲽ; ﲽ; غم; غم; ) ARABIC LIGATURE GHAIN WITH MEEM INITIAL FORM
+FCBE;FCBE;FCBE;0641 062C;0641 062C; # (ﲾ; ﲾ; ﲾ; فج; فج; ) ARABIC LIGATURE FEH WITH JEEM INITIAL FORM
+FCBF;FCBF;FCBF;0641 062D;0641 062D; # (ﲿ; ﲿ; ﲿ; فح; فح; ) ARABIC LIGATURE FEH WITH HAH INITIAL FORM
+FCC0;FCC0;FCC0;0641 062E;0641 062E; # (ﳀ; ﳀ; ﳀ; فخ; فخ; ) ARABIC LIGATURE FEH WITH KHAH INITIAL FORM
+FCC1;FCC1;FCC1;0641 0645;0641 0645; # (ﳁ; ﳁ; ﳁ; فم; فم; ) ARABIC LIGATURE FEH WITH MEEM INITIAL FORM
+FCC2;FCC2;FCC2;0642 062D;0642 062D; # (ﳂ; ﳂ; ﳂ; قح; قح; ) ARABIC LIGATURE QAF WITH HAH INITIAL FORM
+FCC3;FCC3;FCC3;0642 0645;0642 0645; # (ﳃ; ﳃ; ﳃ; قم; قم; ) ARABIC LIGATURE QAF WITH MEEM INITIAL FORM
+FCC4;FCC4;FCC4;0643 062C;0643 062C; # (ﳄ; ﳄ; ﳄ; كج; كج; ) ARABIC LIGATURE KAF WITH JEEM INITIAL FORM
+FCC5;FCC5;FCC5;0643 062D;0643 062D; # (ﳅ; ﳅ; ﳅ; كح; كح; ) ARABIC LIGATURE KAF WITH HAH INITIAL FORM
+FCC6;FCC6;FCC6;0643 062E;0643 062E; # (ﳆ; ﳆ; ﳆ; كخ; كخ; ) ARABIC LIGATURE KAF WITH KHAH INITIAL FORM
+FCC7;FCC7;FCC7;0643 0644;0643 0644; # (ﳇ; ﳇ; ﳇ; كل; كل; ) ARABIC LIGATURE KAF WITH LAM INITIAL FORM
+FCC8;FCC8;FCC8;0643 0645;0643 0645; # (ﳈ; ﳈ; ﳈ; كم; كم; ) ARABIC LIGATURE KAF WITH MEEM INITIAL FORM
+FCC9;FCC9;FCC9;0644 062C;0644 062C; # (ﳉ; ﳉ; ﳉ; لج; لج; ) ARABIC LIGATURE LAM WITH JEEM INITIAL FORM
+FCCA;FCCA;FCCA;0644 062D;0644 062D; # (ﳊ; ﳊ; ﳊ; لح; لح; ) ARABIC LIGATURE LAM WITH HAH INITIAL FORM
+FCCB;FCCB;FCCB;0644 062E;0644 062E; # (ﳋ; ﳋ; ﳋ; لخ; لخ; ) ARABIC LIGATURE LAM WITH KHAH INITIAL FORM
+FCCC;FCCC;FCCC;0644 0645;0644 0645; # (ﳌ; ﳌ; ﳌ; لم; لم; ) ARABIC LIGATURE LAM WITH MEEM INITIAL FORM
+FCCD;FCCD;FCCD;0644 0647;0644 0647; # (ﳍ; ﳍ; ﳍ; له; له; ) ARABIC LIGATURE LAM WITH HEH INITIAL FORM
+FCCE;FCCE;FCCE;0645 062C;0645 062C; # (ﳎ; ﳎ; ﳎ; مج; مج; ) ARABIC LIGATURE MEEM WITH JEEM INITIAL FORM
+FCCF;FCCF;FCCF;0645 062D;0645 062D; # (ﳏ; ﳏ; ﳏ; مح; مح; ) ARABIC LIGATURE MEEM WITH HAH INITIAL FORM
+FCD0;FCD0;FCD0;0645 062E;0645 062E; # (ﳐ; ﳐ; ﳐ; مخ; مخ; ) ARABIC LIGATURE MEEM WITH KHAH INITIAL FORM
+FCD1;FCD1;FCD1;0645 0645;0645 0645; # (ﳑ; ﳑ; ﳑ; مم; مم; ) ARABIC LIGATURE MEEM WITH MEEM INITIAL FORM
+FCD2;FCD2;FCD2;0646 062C;0646 062C; # (ﳒ; ﳒ; ﳒ; نج; نج; ) ARABIC LIGATURE NOON WITH JEEM INITIAL FORM
+FCD3;FCD3;FCD3;0646 062D;0646 062D; # (ﳓ; ﳓ; ﳓ; نح; نح; ) ARABIC LIGATURE NOON WITH HAH INITIAL FORM
+FCD4;FCD4;FCD4;0646 062E;0646 062E; # (ﳔ; ﳔ; ﳔ; نخ; نخ; ) ARABIC LIGATURE NOON WITH KHAH INITIAL FORM
+FCD5;FCD5;FCD5;0646 0645;0646 0645; # (ﳕ; ﳕ; ﳕ; نم; نم; ) ARABIC LIGATURE NOON WITH MEEM INITIAL FORM
+FCD6;FCD6;FCD6;0646 0647;0646 0647; # (ﳖ; ﳖ; ﳖ; نه; نه; ) ARABIC LIGATURE NOON WITH HEH INITIAL FORM
+FCD7;FCD7;FCD7;0647 062C;0647 062C; # (ﳗ; ﳗ; ﳗ; هج; هج; ) ARABIC LIGATURE HEH WITH JEEM INITIAL FORM
+FCD8;FCD8;FCD8;0647 0645;0647 0645; # (ﳘ; ﳘ; ﳘ; هم; هم; ) ARABIC LIGATURE HEH WITH MEEM INITIAL FORM
+FCD9;FCD9;FCD9;0647 0670;0647 0670; # (ﳙ; ﳙ; ﳙ; ه◌ٰ; ه◌ٰ; ) ARABIC LIGATURE HEH WITH SUPERSCRIPT ALEF INITIAL FORM
+FCDA;FCDA;FCDA;064A 062C;064A 062C; # (ﳚ; ﳚ; ﳚ; يج; يج; ) ARABIC LIGATURE YEH WITH JEEM INITIAL FORM
+FCDB;FCDB;FCDB;064A 062D;064A 062D; # (ﳛ; ﳛ; ﳛ; يح; يح; ) ARABIC LIGATURE YEH WITH HAH INITIAL FORM
+FCDC;FCDC;FCDC;064A 062E;064A 062E; # (ﳜ; ﳜ; ﳜ; يخ; يخ; ) ARABIC LIGATURE YEH WITH KHAH INITIAL FORM
+FCDD;FCDD;FCDD;064A 0645;064A 0645; # (ﳝ; ﳝ; ﳝ; يم; يم; ) ARABIC LIGATURE YEH WITH MEEM INITIAL FORM
+FCDE;FCDE;FCDE;064A 0647;064A 0647; # (ﳞ; ﳞ; ﳞ; يه; يه; ) ARABIC LIGATURE YEH WITH HEH INITIAL FORM
+FCDF;FCDF;FCDF;0626 0645;064A 0654 0645; # (ﳟ; ﳟ; ﳟ; ئم; ي◌ٔم; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH MEEM MEDIAL FORM
+FCE0;FCE0;FCE0;0626 0647;064A 0654 0647; # (ﳠ; ﳠ; ﳠ; ئه; ي◌ٔه; ) ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH HEH MEDIAL FORM
+FCE1;FCE1;FCE1;0628 0645;0628 0645; # (ﳡ; ﳡ; ﳡ; بم; بم; ) ARABIC LIGATURE BEH WITH MEEM MEDIAL FORM
+FCE2;FCE2;FCE2;0628 0647;0628 0647; # (ﳢ; ﳢ; ﳢ; به; به; ) ARABIC LIGATURE BEH WITH HEH MEDIAL FORM
+FCE3;FCE3;FCE3;062A 0645;062A 0645; # (ﳣ; ﳣ; ﳣ; تم; تم; ) ARABIC LIGATURE TEH WITH MEEM MEDIAL FORM
+FCE4;FCE4;FCE4;062A 0647;062A 0647; # (ﳤ; ﳤ; ﳤ; ته; ته; ) ARABIC LIGATURE TEH WITH HEH MEDIAL FORM
+FCE5;FCE5;FCE5;062B 0645;062B 0645; # (ﳥ; ﳥ; ﳥ; ثم; ثم; ) ARABIC LIGATURE THEH WITH MEEM MEDIAL FORM
+FCE6;FCE6;FCE6;062B 0647;062B 0647; # (ﳦ; ﳦ; ﳦ; ثه; ثه; ) ARABIC LIGATURE THEH WITH HEH MEDIAL FORM
+FCE7;FCE7;FCE7;0633 0645;0633 0645; # (ﳧ; ﳧ; ﳧ; سم; سم; ) ARABIC LIGATURE SEEN WITH MEEM MEDIAL FORM
+FCE8;FCE8;FCE8;0633 0647;0633 0647; # (ﳨ; ﳨ; ﳨ; سه; سه; ) ARABIC LIGATURE SEEN WITH HEH MEDIAL FORM
+FCE9;FCE9;FCE9;0634 0645;0634 0645; # (ﳩ; ﳩ; ﳩ; شم; شم; ) ARABIC LIGATURE SHEEN WITH MEEM MEDIAL FORM
+FCEA;FCEA;FCEA;0634 0647;0634 0647; # (ﳪ; ﳪ; ﳪ; شه; شه; ) ARABIC LIGATURE SHEEN WITH HEH MEDIAL FORM
+FCEB;FCEB;FCEB;0643 0644;0643 0644; # (ﳫ; ﳫ; ﳫ; كل; كل; ) ARABIC LIGATURE KAF WITH LAM MEDIAL FORM
+FCEC;FCEC;FCEC;0643 0645;0643 0645; # (ﳬ; ﳬ; ﳬ; كم; كم; ) ARABIC LIGATURE KAF WITH MEEM MEDIAL FORM
+FCED;FCED;FCED;0644 0645;0644 0645; # (ﳭ; ﳭ; ﳭ; لم; لم; ) ARABIC LIGATURE LAM WITH MEEM MEDIAL FORM
+FCEE;FCEE;FCEE;0646 0645;0646 0645; # (ﳮ; ﳮ; ﳮ; نم; نم; ) ARABIC LIGATURE NOON WITH MEEM MEDIAL FORM
+FCEF;FCEF;FCEF;0646 0647;0646 0647; # (ﳯ; ﳯ; ﳯ; نه; نه; ) ARABIC LIGATURE NOON WITH HEH MEDIAL FORM
+FCF0;FCF0;FCF0;064A 0645;064A 0645; # (ﳰ; ﳰ; ﳰ; يم; يم; ) ARABIC LIGATURE YEH WITH MEEM MEDIAL FORM
+FCF1;FCF1;FCF1;064A 0647;064A 0647; # (ﳱ; ﳱ; ﳱ; يه; يه; ) ARABIC LIGATURE YEH WITH HEH MEDIAL FORM
+FCF2;FCF2;FCF2;0640 064E 0651;0640 064E 0651; # (ﳲ; ﳲ; ﳲ; ـ◌َ◌ّ; ـ◌َ◌ّ; ) ARABIC LIGATURE SHADDA WITH FATHA MEDIAL FORM
+FCF3;FCF3;FCF3;0640 064F 0651;0640 064F 0651; # (ﳳ; ﳳ; ﳳ; ـ◌ُ◌ّ; ـ◌ُ◌ّ; ) ARABIC LIGATURE SHADDA WITH DAMMA MEDIAL FORM
+FCF4;FCF4;FCF4;0640 0650 0651;0640 0650 0651; # (ﳴ; ﳴ; ﳴ; ـ◌ِ◌ّ; ـ◌ِ◌ّ; ) ARABIC LIGATURE SHADDA WITH KASRA MEDIAL FORM
+FCF5;FCF5;FCF5;0637 0649;0637 0649; # (ﳵ; ﳵ; ﳵ; طى; طى; ) ARABIC LIGATURE TAH WITH ALEF MAKSURA ISOLATED FORM
+FCF6;FCF6;FCF6;0637 064A;0637 064A; # (ﳶ; ﳶ; ﳶ; طي; طي; ) ARABIC LIGATURE TAH WITH YEH ISOLATED FORM
+FCF7;FCF7;FCF7;0639 0649;0639 0649; # (ﳷ; ﳷ; ﳷ; عى; عى; ) ARABIC LIGATURE AIN WITH ALEF MAKSURA ISOLATED FORM
+FCF8;FCF8;FCF8;0639 064A;0639 064A; # (ﳸ; ﳸ; ﳸ; عي; عي; ) ARABIC LIGATURE AIN WITH YEH ISOLATED FORM
+FCF9;FCF9;FCF9;063A 0649;063A 0649; # (ﳹ; ﳹ; ﳹ; غى; غى; ) ARABIC LIGATURE GHAIN WITH ALEF MAKSURA ISOLATED FORM
+FCFA;FCFA;FCFA;063A 064A;063A 064A; # (ﳺ; ﳺ; ﳺ; غي; غي; ) ARABIC LIGATURE GHAIN WITH YEH ISOLATED FORM
+FCFB;FCFB;FCFB;0633 0649;0633 0649; # (ﳻ; ﳻ; ﳻ; سى; سى; ) ARABIC LIGATURE SEEN WITH ALEF MAKSURA ISOLATED FORM
+FCFC;FCFC;FCFC;0633 064A;0633 064A; # (ﳼ; ﳼ; ﳼ; سي; سي; ) ARABIC LIGATURE SEEN WITH YEH ISOLATED FORM
+FCFD;FCFD;FCFD;0634 0649;0634 0649; # (ﳽ; ﳽ; ﳽ; شى; شى; ) ARABIC LIGATURE SHEEN WITH ALEF MAKSURA ISOLATED FORM
+FCFE;FCFE;FCFE;0634 064A;0634 064A; # (ﳾ; ﳾ; ﳾ; شي; شي; ) ARABIC LIGATURE SHEEN WITH YEH ISOLATED FORM
+FCFF;FCFF;FCFF;062D 0649;062D 0649; # (ﳿ; ﳿ; ﳿ; حى; حى; ) ARABIC LIGATURE HAH WITH ALEF MAKSURA ISOLATED FORM
+FD00;FD00;FD00;062D 064A;062D 064A; # (ﴀ; ﴀ; ﴀ; حي; حي; ) ARABIC LIGATURE HAH WITH YEH ISOLATED FORM
+FD01;FD01;FD01;062C 0649;062C 0649; # (ﴁ; ﴁ; ﴁ; جى; جى; ) ARABIC LIGATURE JEEM WITH ALEF MAKSURA ISOLATED FORM
+FD02;FD02;FD02;062C 064A;062C 064A; # (ﴂ; ﴂ; ﴂ; جي; جي; ) ARABIC LIGATURE JEEM WITH YEH ISOLATED FORM
+FD03;FD03;FD03;062E 0649;062E 0649; # (ﴃ; ﴃ; ﴃ; خى; خى; ) ARABIC LIGATURE KHAH WITH ALEF MAKSURA ISOLATED FORM
+FD04;FD04;FD04;062E 064A;062E 064A; # (ﴄ; ﴄ; ﴄ; خي; خي; ) ARABIC LIGATURE KHAH WITH YEH ISOLATED FORM
+FD05;FD05;FD05;0635 0649;0635 0649; # (ﴅ; ﴅ; ﴅ; صى; صى; ) ARABIC LIGATURE SAD WITH ALEF MAKSURA ISOLATED FORM
+FD06;FD06;FD06;0635 064A;0635 064A; # (ﴆ; ﴆ; ﴆ; صي; صي; ) ARABIC LIGATURE SAD WITH YEH ISOLATED FORM
+FD07;FD07;FD07;0636 0649;0636 0649; # (ﴇ; ﴇ; ﴇ; ضى; ضى; ) ARABIC LIGATURE DAD WITH ALEF MAKSURA ISOLATED FORM
+FD08;FD08;FD08;0636 064A;0636 064A; # (ﴈ; ﴈ; ﴈ; ضي; ضي; ) ARABIC LIGATURE DAD WITH YEH ISOLATED FORM
+FD09;FD09;FD09;0634 062C;0634 062C; # (ﴉ; ﴉ; ﴉ; شج; شج; ) ARABIC LIGATURE SHEEN WITH JEEM ISOLATED FORM
+FD0A;FD0A;FD0A;0634 062D;0634 062D; # (ﴊ; ﴊ; ﴊ; شح; شح; ) ARABIC LIGATURE SHEEN WITH HAH ISOLATED FORM
+FD0B;FD0B;FD0B;0634 062E;0634 062E; # (ﴋ; ﴋ; ﴋ; شخ; شخ; ) ARABIC LIGATURE SHEEN WITH KHAH ISOLATED FORM
+FD0C;FD0C;FD0C;0634 0645;0634 0645; # (ﴌ; ﴌ; ﴌ; شم; شم; ) ARABIC LIGATURE SHEEN WITH MEEM ISOLATED FORM
+FD0D;FD0D;FD0D;0634 0631;0634 0631; # (ﴍ; ﴍ; ﴍ; شر; شر; ) ARABIC LIGATURE SHEEN WITH REH ISOLATED FORM
+FD0E;FD0E;FD0E;0633 0631;0633 0631; # (ﴎ; ﴎ; ﴎ; سر; سر; ) ARABIC LIGATURE SEEN WITH REH ISOLATED FORM
+FD0F;FD0F;FD0F;0635 0631;0635 0631; # (ﴏ; ﴏ; ﴏ; صر; صر; ) ARABIC LIGATURE SAD WITH REH ISOLATED FORM
+FD10;FD10;FD10;0636 0631;0636 0631; # (ﴐ; ﴐ; ﴐ; ضر; ضر; ) ARABIC LIGATURE DAD WITH REH ISOLATED FORM
+FD11;FD11;FD11;0637 0649;0637 0649; # (ﴑ; ﴑ; ﴑ; طى; طى; ) ARABIC LIGATURE TAH WITH ALEF MAKSURA FINAL FORM
+FD12;FD12;FD12;0637 064A;0637 064A; # (ﴒ; ﴒ; ﴒ; طي; طي; ) ARABIC LIGATURE TAH WITH YEH FINAL FORM
+FD13;FD13;FD13;0639 0649;0639 0649; # (ﴓ; ﴓ; ﴓ; عى; عى; ) ARABIC LIGATURE AIN WITH ALEF MAKSURA FINAL FORM
+FD14;FD14;FD14;0639 064A;0639 064A; # (ﴔ; ﴔ; ﴔ; عي; عي; ) ARABIC LIGATURE AIN WITH YEH FINAL FORM
+FD15;FD15;FD15;063A 0649;063A 0649; # (ﴕ; ﴕ; ﴕ; غى; غى; ) ARABIC LIGATURE GHAIN WITH ALEF MAKSURA FINAL FORM
+FD16;FD16;FD16;063A 064A;063A 064A; # (ﴖ; ﴖ; ﴖ; غي; غي; ) ARABIC LIGATURE GHAIN WITH YEH FINAL FORM
+FD17;FD17;FD17;0633 0649;0633 0649; # (ﴗ; ﴗ; ﴗ; سى; سى; ) ARABIC LIGATURE SEEN WITH ALEF MAKSURA FINAL FORM
+FD18;FD18;FD18;0633 064A;0633 064A; # (ﴘ; ﴘ; ﴘ; سي; سي; ) ARABIC LIGATURE SEEN WITH YEH FINAL FORM
+FD19;FD19;FD19;0634 0649;0634 0649; # (ﴙ; ﴙ; ﴙ; شى; شى; ) ARABIC LIGATURE SHEEN WITH ALEF MAKSURA FINAL FORM
+FD1A;FD1A;FD1A;0634 064A;0634 064A; # (ﴚ; ﴚ; ﴚ; شي; شي; ) ARABIC LIGATURE SHEEN WITH YEH FINAL FORM
+FD1B;FD1B;FD1B;062D 0649;062D 0649; # (ﴛ; ﴛ; ﴛ; حى; حى; ) ARABIC LIGATURE HAH WITH ALEF MAKSURA FINAL FORM
+FD1C;FD1C;FD1C;062D 064A;062D 064A; # (ﴜ; ﴜ; ﴜ; حي; حي; ) ARABIC LIGATURE HAH WITH YEH FINAL FORM
+FD1D;FD1D;FD1D;062C 0649;062C 0649; # (ﴝ; ﴝ; ﴝ; جى; جى; ) ARABIC LIGATURE JEEM WITH ALEF MAKSURA FINAL FORM
+FD1E;FD1E;FD1E;062C 064A;062C 064A; # (ﴞ; ﴞ; ﴞ; جي; جي; ) ARABIC LIGATURE JEEM WITH YEH FINAL FORM
+FD1F;FD1F;FD1F;062E 0649;062E 0649; # (ﴟ; ﴟ; ﴟ; خى; خى; ) ARABIC LIGATURE KHAH WITH ALEF MAKSURA FINAL FORM
+FD20;FD20;FD20;062E 064A;062E 064A; # (ﴠ; ﴠ; ﴠ; خي; خي; ) ARABIC LIGATURE KHAH WITH YEH FINAL FORM
+FD21;FD21;FD21;0635 0649;0635 0649; # (ﴡ; ﴡ; ﴡ; صى; صى; ) ARABIC LIGATURE SAD WITH ALEF MAKSURA FINAL FORM
+FD22;FD22;FD22;0635 064A;0635 064A; # (ﴢ; ﴢ; ﴢ; صي; صي; ) ARABIC LIGATURE SAD WITH YEH FINAL FORM
+FD23;FD23;FD23;0636 0649;0636 0649; # (ﴣ; ﴣ; ﴣ; ضى; ضى; ) ARABIC LIGATURE DAD WITH ALEF MAKSURA FINAL FORM
+FD24;FD24;FD24;0636 064A;0636 064A; # (ﴤ; ﴤ; ﴤ; ضي; ضي; ) ARABIC LIGATURE DAD WITH YEH FINAL FORM
+FD25;FD25;FD25;0634 062C;0634 062C; # (ﴥ; ﴥ; ﴥ; شج; شج; ) ARABIC LIGATURE SHEEN WITH JEEM FINAL FORM
+FD26;FD26;FD26;0634 062D;0634 062D; # (ﴦ; ﴦ; ﴦ; شح; شح; ) ARABIC LIGATURE SHEEN WITH HAH FINAL FORM
+FD27;FD27;FD27;0634 062E;0634 062E; # (ﴧ; ﴧ; ﴧ; شخ; شخ; ) ARABIC LIGATURE SHEEN WITH KHAH FINAL FORM
+FD28;FD28;FD28;0634 0645;0634 0645; # (ﴨ; ﴨ; ﴨ; شم; شم; ) ARABIC LIGATURE SHEEN WITH MEEM FINAL FORM
+FD29;FD29;FD29;0634 0631;0634 0631; # (ﴩ; ﴩ; ﴩ; شر; شر; ) ARABIC LIGATURE SHEEN WITH REH FINAL FORM
+FD2A;FD2A;FD2A;0633 0631;0633 0631; # (ﴪ; ﴪ; ﴪ; سر; سر; ) ARABIC LIGATURE SEEN WITH REH FINAL FORM
+FD2B;FD2B;FD2B;0635 0631;0635 0631; # (ﴫ; ﴫ; ﴫ; صر; صر; ) ARABIC LIGATURE SAD WITH REH FINAL FORM
+FD2C;FD2C;FD2C;0636 0631;0636 0631; # (ﴬ; ﴬ; ﴬ; ضر; ضر; ) ARABIC LIGATURE DAD WITH REH FINAL FORM
+FD2D;FD2D;FD2D;0634 062C;0634 062C; # (ﴭ; ﴭ; ﴭ; شج; شج; ) ARABIC LIGATURE SHEEN WITH JEEM INITIAL FORM
+FD2E;FD2E;FD2E;0634 062D;0634 062D; # (ﴮ; ﴮ; ﴮ; شح; شح; ) ARABIC LIGATURE SHEEN WITH HAH INITIAL FORM
+FD2F;FD2F;FD2F;0634 062E;0634 062E; # (ﴯ; ﴯ; ﴯ; شخ; شخ; ) ARABIC LIGATURE SHEEN WITH KHAH INITIAL FORM
+FD30;FD30;FD30;0634 0645;0634 0645; # (ﴰ; ﴰ; ﴰ; شم; شم; ) ARABIC LIGATURE SHEEN WITH MEEM INITIAL FORM
+FD31;FD31;FD31;0633 0647;0633 0647; # (ﴱ; ﴱ; ﴱ; سه; سه; ) ARABIC LIGATURE SEEN WITH HEH INITIAL FORM
+FD32;FD32;FD32;0634 0647;0634 0647; # (ﴲ; ﴲ; ﴲ; شه; شه; ) ARABIC LIGATURE SHEEN WITH HEH INITIAL FORM
+FD33;FD33;FD33;0637 0645;0637 0645; # (ﴳ; ﴳ; ﴳ; طم; طم; ) ARABIC LIGATURE TAH WITH MEEM INITIAL FORM
+FD34;FD34;FD34;0633 062C;0633 062C; # (ﴴ; ﴴ; ﴴ; سج; سج; ) ARABIC LIGATURE SEEN WITH JEEM MEDIAL FORM
+FD35;FD35;FD35;0633 062D;0633 062D; # (ﴵ; ﴵ; ﴵ; سح; سح; ) ARABIC LIGATURE SEEN WITH HAH MEDIAL FORM
+FD36;FD36;FD36;0633 062E;0633 062E; # (ﴶ; ﴶ; ﴶ; سخ; سخ; ) ARABIC LIGATURE SEEN WITH KHAH MEDIAL FORM
+FD37;FD37;FD37;0634 062C;0634 062C; # (ﴷ; ﴷ; ﴷ; شج; شج; ) ARABIC LIGATURE SHEEN WITH JEEM MEDIAL FORM
+FD38;FD38;FD38;0634 062D;0634 062D; # (ﴸ; ﴸ; ﴸ; شح; شح; ) ARABIC LIGATURE SHEEN WITH HAH MEDIAL FORM
+FD39;FD39;FD39;0634 062E;0634 062E; # (ﴹ; ﴹ; ﴹ; شخ; شخ; ) ARABIC LIGATURE SHEEN WITH KHAH MEDIAL FORM
+FD3A;FD3A;FD3A;0637 0645;0637 0645; # (ﴺ; ﴺ; ﴺ; طم; طم; ) ARABIC LIGATURE TAH WITH MEEM MEDIAL FORM
+FD3B;FD3B;FD3B;0638 0645;0638 0645; # (ﴻ; ﴻ; ﴻ; ظم; ظم; ) ARABIC LIGATURE ZAH WITH MEEM MEDIAL FORM
+FD3C;FD3C;FD3C;0627 064B;0627 064B; # (ﴼ; ﴼ; ﴼ; ا◌ً; ا◌ً; ) ARABIC LIGATURE ALEF WITH FATHATAN FINAL FORM
+FD3D;FD3D;FD3D;0627 064B;0627 064B; # (ﴽ; ﴽ; ﴽ; ا◌ً; ا◌ً; ) ARABIC LIGATURE ALEF WITH FATHATAN ISOLATED FORM
+FD50;FD50;FD50;062A 062C 0645;062A 062C 0645; # (ﵐ; ﵐ; ﵐ; تجم; تجم; ) ARABIC LIGATURE TEH WITH JEEM WITH MEEM INITIAL FORM
+FD51;FD51;FD51;062A 062D 062C;062A 062D 062C; # (ﵑ; ﵑ; ﵑ; تحج; تحج; ) ARABIC LIGATURE TEH WITH HAH WITH JEEM FINAL FORM
+FD52;FD52;FD52;062A 062D 062C;062A 062D 062C; # (ﵒ; ﵒ; ﵒ; تحج; تحج; ) ARABIC LIGATURE TEH WITH HAH WITH JEEM INITIAL FORM
+FD53;FD53;FD53;062A 062D 0645;062A 062D 0645; # (ﵓ; ﵓ; ﵓ; تحم; تحم; ) ARABIC LIGATURE TEH WITH HAH WITH MEEM INITIAL FORM
+FD54;FD54;FD54;062A 062E 0645;062A 062E 0645; # (ﵔ; ﵔ; ﵔ; تخم; تخم; ) ARABIC LIGATURE TEH WITH KHAH WITH MEEM INITIAL FORM
+FD55;FD55;FD55;062A 0645 062C;062A 0645 062C; # (ﵕ; ﵕ; ﵕ; تمج; تمج; ) ARABIC LIGATURE TEH WITH MEEM WITH JEEM INITIAL FORM
+FD56;FD56;FD56;062A 0645 062D;062A 0645 062D; # (ﵖ; ﵖ; ﵖ; تمح; تمح; ) ARABIC LIGATURE TEH WITH MEEM WITH HAH INITIAL FORM
+FD57;FD57;FD57;062A 0645 062E;062A 0645 062E; # (ﵗ; ﵗ; ﵗ; تمخ; تمخ; ) ARABIC LIGATURE TEH WITH MEEM WITH KHAH INITIAL FORM
+FD58;FD58;FD58;062C 0645 062D;062C 0645 062D; # (ﵘ; ﵘ; ﵘ; جمح; جمح; ) ARABIC LIGATURE JEEM WITH MEEM WITH HAH FINAL FORM
+FD59;FD59;FD59;062C 0645 062D;062C 0645 062D; # (ﵙ; ﵙ; ﵙ; جمح; جمح; ) ARABIC LIGATURE JEEM WITH MEEM WITH HAH INITIAL FORM
+FD5A;FD5A;FD5A;062D 0645 064A;062D 0645 064A; # (ﵚ; ﵚ; ﵚ; حمي; حمي; ) ARABIC LIGATURE HAH WITH MEEM WITH YEH FINAL FORM
+FD5B;FD5B;FD5B;062D 0645 0649;062D 0645 0649; # (ﵛ; ﵛ; ﵛ; حمى; حمى; ) ARABIC LIGATURE HAH WITH MEEM WITH ALEF MAKSURA FINAL FORM
+FD5C;FD5C;FD5C;0633 062D 062C;0633 062D 062C; # (ﵜ; ﵜ; ﵜ; سحج; سحج; ) ARABIC LIGATURE SEEN WITH HAH WITH JEEM INITIAL FORM
+FD5D;FD5D;FD5D;0633 062C 062D;0633 062C 062D; # (ﵝ; ﵝ; ﵝ; سجح; سجح; ) ARABIC LIGATURE SEEN WITH JEEM WITH HAH INITIAL FORM
+FD5E;FD5E;FD5E;0633 062C 0649;0633 062C 0649; # (ﵞ; ﵞ; ﵞ; سجى; سجى; ) ARABIC LIGATURE SEEN WITH JEEM WITH ALEF MAKSURA FINAL FORM
+FD5F;FD5F;FD5F;0633 0645 062D;0633 0645 062D; # (ﵟ; ﵟ; ﵟ; سمح; سمح; ) ARABIC LIGATURE SEEN WITH MEEM WITH HAH FINAL FORM
+FD60;FD60;FD60;0633 0645 062D;0633 0645 062D; # (ﵠ; ﵠ; ﵠ; سمح; سمح; ) ARABIC LIGATURE SEEN WITH MEEM WITH HAH INITIAL FORM
+FD61;FD61;FD61;0633 0645 062C;0633 0645 062C; # (ﵡ; ﵡ; ﵡ; سمج; سمج; ) ARABIC LIGATURE SEEN WITH MEEM WITH JEEM INITIAL FORM
+FD62;FD62;FD62;0633 0645 0645;0633 0645 0645; # (ﵢ; ﵢ; ﵢ; سمم; سمم; ) ARABIC LIGATURE SEEN WITH MEEM WITH MEEM FINAL FORM
+FD63;FD63;FD63;0633 0645 0645;0633 0645 0645; # (ﵣ; ﵣ; ﵣ; سمم; سمم; ) ARABIC LIGATURE SEEN WITH MEEM WITH MEEM INITIAL FORM
+FD64;FD64;FD64;0635 062D 062D;0635 062D 062D; # (ﵤ; ﵤ; ﵤ; صحح; صحح; ) ARABIC LIGATURE SAD WITH HAH WITH HAH FINAL FORM
+FD65;FD65;FD65;0635 062D 062D;0635 062D 062D; # (ﵥ; ﵥ; ﵥ; صحح; صحح; ) ARABIC LIGATURE SAD WITH HAH WITH HAH INITIAL FORM
+FD66;FD66;FD66;0635 0645 0645;0635 0645 0645; # (ﵦ; ﵦ; ﵦ; صمم; صمم; ) ARABIC LIGATURE SAD WITH MEEM WITH MEEM FINAL FORM
+FD67;FD67;FD67;0634 062D 0645;0634 062D 0645; # (ﵧ; ﵧ; ﵧ; شحم; شحم; ) ARABIC LIGATURE SHEEN WITH HAH WITH MEEM FINAL FORM
+FD68;FD68;FD68;0634 062D 0645;0634 062D 0645; # (ﵨ; ﵨ; ﵨ; شحم; شحم; ) ARABIC LIGATURE SHEEN WITH HAH WITH MEEM INITIAL FORM
+FD69;FD69;FD69;0634 062C 064A;0634 062C 064A; # (ﵩ; ﵩ; ﵩ; شجي; شجي; ) ARABIC LIGATURE SHEEN WITH JEEM WITH YEH FINAL FORM
+FD6A;FD6A;FD6A;0634 0645 062E;0634 0645 062E; # (ﵪ; ﵪ; ﵪ; شمخ; شمخ; ) ARABIC LIGATURE SHEEN WITH MEEM WITH KHAH FINAL FORM
+FD6B;FD6B;FD6B;0634 0645 062E;0634 0645 062E; # (ﵫ; ﵫ; ﵫ; شمخ; شمخ; ) ARABIC LIGATURE SHEEN WITH MEEM WITH KHAH INITIAL FORM
+FD6C;FD6C;FD6C;0634 0645 0645;0634 0645 0645; # (ﵬ; ﵬ; ﵬ; شمم; شمم; ) ARABIC LIGATURE SHEEN WITH MEEM WITH MEEM FINAL FORM
+FD6D;FD6D;FD6D;0634 0645 0645;0634 0645 0645; # (ﵭ; ﵭ; ﵭ; شمم; شمم; ) ARABIC LIGATURE SHEEN WITH MEEM WITH MEEM INITIAL FORM
+FD6E;FD6E;FD6E;0636 062D 0649;0636 062D 0649; # (ﵮ; ﵮ; ﵮ; ضحى; ضحى; ) ARABIC LIGATURE DAD WITH HAH WITH ALEF MAKSURA FINAL FORM
+FD6F;FD6F;FD6F;0636 062E 0645;0636 062E 0645; # (ﵯ; ﵯ; ﵯ; ضخم; ضخم; ) ARABIC LIGATURE DAD WITH KHAH WITH MEEM FINAL FORM
+FD70;FD70;FD70;0636 062E 0645;0636 062E 0645; # (ﵰ; ﵰ; ﵰ; ضخم; ضخم; ) ARABIC LIGATURE DAD WITH KHAH WITH MEEM INITIAL FORM
+FD71;FD71;FD71;0637 0645 062D;0637 0645 062D; # (ﵱ; ﵱ; ﵱ; طمح; طمح; ) ARABIC LIGATURE TAH WITH MEEM WITH HAH FINAL FORM
+FD72;FD72;FD72;0637 0645 062D;0637 0645 062D; # (ﵲ; ﵲ; ﵲ; طمح; طمح; ) ARABIC LIGATURE TAH WITH MEEM WITH HAH INITIAL FORM
+FD73;FD73;FD73;0637 0645 0645;0637 0645 0645; # (ﵳ; ﵳ; ﵳ; طمم; طمم; ) ARABIC LIGATURE TAH WITH MEEM WITH MEEM INITIAL FORM
+FD74;FD74;FD74;0637 0645 064A;0637 0645 064A; # (ﵴ; ﵴ; ﵴ; طمي; طمي; ) ARABIC LIGATURE TAH WITH MEEM WITH YEH FINAL FORM
+FD75;FD75;FD75;0639 062C 0645;0639 062C 0645; # (ﵵ; ﵵ; ﵵ; عجم; عجم; ) ARABIC LIGATURE AIN WITH JEEM WITH MEEM FINAL FORM
+FD76;FD76;FD76;0639 0645 0645;0639 0645 0645; # (ﵶ; ﵶ; ﵶ; عمم; عمم; ) ARABIC LIGATURE AIN WITH MEEM WITH MEEM FINAL FORM
+FD77;FD77;FD77;0639 0645 0645;0639 0645 0645; # (ﵷ; ﵷ; ﵷ; عمم; عمم; ) ARABIC LIGATURE AIN WITH MEEM WITH MEEM INITIAL FORM
+FD78;FD78;FD78;0639 0645 0649;0639 0645 0649; # (ﵸ; ﵸ; ﵸ; عمى; عمى; ) ARABIC LIGATURE AIN WITH MEEM WITH ALEF MAKSURA FINAL FORM
+FD79;FD79;FD79;063A 0645 0645;063A 0645 0645; # (ﵹ; ﵹ; ﵹ; غمم; غمم; ) ARABIC LIGATURE GHAIN WITH MEEM WITH MEEM FINAL FORM
+FD7A;FD7A;FD7A;063A 0645 064A;063A 0645 064A; # (ﵺ; ﵺ; ﵺ; غمي; غمي; ) ARABIC LIGATURE GHAIN WITH MEEM WITH YEH FINAL FORM
+FD7B;FD7B;FD7B;063A 0645 0649;063A 0645 0649; # (ﵻ; ﵻ; ﵻ; غمى; غمى; ) ARABIC LIGATURE GHAIN WITH MEEM WITH ALEF MAKSURA FINAL FORM
+FD7C;FD7C;FD7C;0641 062E 0645;0641 062E 0645; # (ﵼ; ﵼ; ﵼ; فخم; فخم; ) ARABIC LIGATURE FEH WITH KHAH WITH MEEM FINAL FORM
+FD7D;FD7D;FD7D;0641 062E 0645;0641 062E 0645; # (ﵽ; ﵽ; ﵽ; فخم; فخم; ) ARABIC LIGATURE FEH WITH KHAH WITH MEEM INITIAL FORM
+FD7E;FD7E;FD7E;0642 0645 062D;0642 0645 062D; # (ﵾ; ﵾ; ﵾ; قمح; قمح; ) ARABIC LIGATURE QAF WITH MEEM WITH HAH FINAL FORM
+FD7F;FD7F;FD7F;0642 0645 0645;0642 0645 0645; # (ﵿ; ﵿ; ﵿ; قمم; قمم; ) ARABIC LIGATURE QAF WITH MEEM WITH MEEM FINAL FORM
+FD80;FD80;FD80;0644 062D 0645;0644 062D 0645; # (ﶀ; ﶀ; ﶀ; لحم; لحم; ) ARABIC LIGATURE LAM WITH HAH WITH MEEM FINAL FORM
+FD81;FD81;FD81;0644 062D 064A;0644 062D 064A; # (ﶁ; ﶁ; ﶁ; لحي; لحي; ) ARABIC LIGATURE LAM WITH HAH WITH YEH FINAL FORM
+FD82;FD82;FD82;0644 062D 0649;0644 062D 0649; # (ﶂ; ﶂ; ﶂ; لحى; لحى; ) ARABIC LIGATURE LAM WITH HAH WITH ALEF MAKSURA FINAL FORM
+FD83;FD83;FD83;0644 062C 062C;0644 062C 062C; # (ﶃ; ﶃ; ﶃ; لجج; لجج; ) ARABIC LIGATURE LAM WITH JEEM WITH JEEM INITIAL FORM
+FD84;FD84;FD84;0644 062C 062C;0644 062C 062C; # (ﶄ; ﶄ; ﶄ; لجج; لجج; ) ARABIC LIGATURE LAM WITH JEEM WITH JEEM FINAL FORM
+FD85;FD85;FD85;0644 062E 0645;0644 062E 0645; # (ﶅ; ﶅ; ﶅ; لخم; لخم; ) ARABIC LIGATURE LAM WITH KHAH WITH MEEM FINAL FORM
+FD86;FD86;FD86;0644 062E 0645;0644 062E 0645; # (ﶆ; ﶆ; ﶆ; لخم; لخم; ) ARABIC LIGATURE LAM WITH KHAH WITH MEEM INITIAL FORM
+FD87;FD87;FD87;0644 0645 062D;0644 0645 062D; # (ﶇ; ﶇ; ﶇ; لمح; لمح; ) ARABIC LIGATURE LAM WITH MEEM WITH HAH FINAL FORM
+FD88;FD88;FD88;0644 0645 062D;0644 0645 062D; # (ﶈ; ﶈ; ﶈ; لمح; لمح; ) ARABIC LIGATURE LAM WITH MEEM WITH HAH INITIAL FORM
+FD89;FD89;FD89;0645 062D 062C;0645 062D 062C; # (ﶉ; ﶉ; ﶉ; محج; محج; ) ARABIC LIGATURE MEEM WITH HAH WITH JEEM INITIAL FORM
+FD8A;FD8A;FD8A;0645 062D 0645;0645 062D 0645; # (ﶊ; ﶊ; ﶊ; محم; محم; ) ARABIC LIGATURE MEEM WITH HAH WITH MEEM INITIAL FORM
+FD8B;FD8B;FD8B;0645 062D 064A;0645 062D 064A; # (ﶋ; ﶋ; ﶋ; محي; محي; ) ARABIC LIGATURE MEEM WITH HAH WITH YEH FINAL FORM
+FD8C;FD8C;FD8C;0645 062C 062D;0645 062C 062D; # (ﶌ; ﶌ; ﶌ; مجح; مجح; ) ARABIC LIGATURE MEEM WITH JEEM WITH HAH INITIAL FORM
+FD8D;FD8D;FD8D;0645 062C 0645;0645 062C 0645; # (ﶍ; ﶍ; ﶍ; مجم; مجم; ) ARABIC LIGATURE MEEM WITH JEEM WITH MEEM INITIAL FORM
+FD8E;FD8E;FD8E;0645 062E 062C;0645 062E 062C; # (ﶎ; ﶎ; ﶎ; مخج; مخج; ) ARABIC LIGATURE MEEM WITH KHAH WITH JEEM INITIAL FORM
+FD8F;FD8F;FD8F;0645 062E 0645;0645 062E 0645; # (ﶏ; ﶏ; ﶏ; مخم; مخم; ) ARABIC LIGATURE MEEM WITH KHAH WITH MEEM INITIAL FORM
+FD92;FD92;FD92;0645 062C 062E;0645 062C 062E; # (ﶒ; ﶒ; ﶒ; مجخ; مجخ; ) ARABIC LIGATURE MEEM WITH JEEM WITH KHAH INITIAL FORM
+FD93;FD93;FD93;0647 0645 062C;0647 0645 062C; # (ﶓ; ﶓ; ﶓ; همج; همج; ) ARABIC LIGATURE HEH WITH MEEM WITH JEEM INITIAL FORM
+FD94;FD94;FD94;0647 0645 0645;0647 0645 0645; # (ﶔ; ﶔ; ﶔ; همم; همم; ) ARABIC LIGATURE HEH WITH MEEM WITH MEEM INITIAL FORM
+FD95;FD95;FD95;0646 062D 0645;0646 062D 0645; # (ﶕ; ﶕ; ﶕ; نحم; نحم; ) ARABIC LIGATURE NOON WITH HAH WITH MEEM INITIAL FORM
+FD96;FD96;FD96;0646 062D 0649;0646 062D 0649; # (ﶖ; ﶖ; ﶖ; نحى; نحى; ) ARABIC LIGATURE NOON WITH HAH WITH ALEF MAKSURA FINAL FORM
+FD97;FD97;FD97;0646 062C 0645;0646 062C 0645; # (ﶗ; ﶗ; ﶗ; نجم; نجم; ) ARABIC LIGATURE NOON WITH JEEM WITH MEEM FINAL FORM
+FD98;FD98;FD98;0646 062C 0645;0646 062C 0645; # (ﶘ; ﶘ; ﶘ; نجم; نجم; ) ARABIC LIGATURE NOON WITH JEEM WITH MEEM INITIAL FORM
+FD99;FD99;FD99;0646 062C 0649;0646 062C 0649; # (ﶙ; ﶙ; ﶙ; نجى; نجى; ) ARABIC LIGATURE NOON WITH JEEM WITH ALEF MAKSURA FINAL FORM
+FD9A;FD9A;FD9A;0646 0645 064A;0646 0645 064A; # (ﶚ; ﶚ; ﶚ; نمي; نمي; ) ARABIC LIGATURE NOON WITH MEEM WITH YEH FINAL FORM
+FD9B;FD9B;FD9B;0646 0645 0649;0646 0645 0649; # (ﶛ; ﶛ; ﶛ; نمى; نمى; ) ARABIC LIGATURE NOON WITH MEEM WITH ALEF MAKSURA FINAL FORM
+FD9C;FD9C;FD9C;064A 0645 0645;064A 0645 0645; # (ﶜ; ﶜ; ﶜ; يمم; يمم; ) ARABIC LIGATURE YEH WITH MEEM WITH MEEM FINAL FORM
+FD9D;FD9D;FD9D;064A 0645 0645;064A 0645 0645; # (ﶝ; ﶝ; ﶝ; يمم; يمم; ) ARABIC LIGATURE YEH WITH MEEM WITH MEEM INITIAL FORM
+FD9E;FD9E;FD9E;0628 062E 064A;0628 062E 064A; # (ﶞ; ﶞ; ﶞ; بخي; بخي; ) ARABIC LIGATURE BEH WITH KHAH WITH YEH FINAL FORM
+FD9F;FD9F;FD9F;062A 062C 064A;062A 062C 064A; # (ﶟ; ﶟ; ﶟ; تجي; تجي; ) ARABIC LIGATURE TEH WITH JEEM WITH YEH FINAL FORM
+FDA0;FDA0;FDA0;062A 062C 0649;062A 062C 0649; # (ﶠ; ﶠ; ﶠ; تجى; تجى; ) ARABIC LIGATURE TEH WITH JEEM WITH ALEF MAKSURA FINAL FORM
+FDA1;FDA1;FDA1;062A 062E 064A;062A 062E 064A; # (ﶡ; ﶡ; ﶡ; تخي; تخي; ) ARABIC LIGATURE TEH WITH KHAH WITH YEH FINAL FORM
+FDA2;FDA2;FDA2;062A 062E 0649;062A 062E 0649; # (ﶢ; ﶢ; ﶢ; تخى; تخى; ) ARABIC LIGATURE TEH WITH KHAH WITH ALEF MAKSURA FINAL FORM
+FDA3;FDA3;FDA3;062A 0645 064A;062A 0645 064A; # (ﶣ; ﶣ; ﶣ; تمي; تمي; ) ARABIC LIGATURE TEH WITH MEEM WITH YEH FINAL FORM
+FDA4;FDA4;FDA4;062A 0645 0649;062A 0645 0649; # (ﶤ; ﶤ; ﶤ; تمى; تمى; ) ARABIC LIGATURE TEH WITH MEEM WITH ALEF MAKSURA FINAL FORM
+FDA5;FDA5;FDA5;062C 0645 064A;062C 0645 064A; # (ﶥ; ﶥ; ﶥ; جمي; جمي; ) ARABIC LIGATURE JEEM WITH MEEM WITH YEH FINAL FORM
+FDA6;FDA6;FDA6;062C 062D 0649;062C 062D 0649; # (ﶦ; ﶦ; ﶦ; جحى; جحى; ) ARABIC LIGATURE JEEM WITH HAH WITH ALEF MAKSURA FINAL FORM
+FDA7;FDA7;FDA7;062C 0645 0649;062C 0645 0649; # (ﶧ; ﶧ; ﶧ; جمى; جمى; ) ARABIC LIGATURE JEEM WITH MEEM WITH ALEF MAKSURA FINAL FORM
+FDA8;FDA8;FDA8;0633 062E 0649;0633 062E 0649; # (ﶨ; ﶨ; ﶨ; سخى; سخى; ) ARABIC LIGATURE SEEN WITH KHAH WITH ALEF MAKSURA FINAL FORM
+FDA9;FDA9;FDA9;0635 062D 064A;0635 062D 064A; # (ﶩ; ﶩ; ﶩ; صحي; صحي; ) ARABIC LIGATURE SAD WITH HAH WITH YEH FINAL FORM
+FDAA;FDAA;FDAA;0634 062D 064A;0634 062D 064A; # (ﶪ; ﶪ; ﶪ; شحي; شحي; ) ARABIC LIGATURE SHEEN WITH HAH WITH YEH FINAL FORM
+FDAB;FDAB;FDAB;0636 062D 064A;0636 062D 064A; # (ﶫ; ﶫ; ﶫ; ضحي; ضحي; ) ARABIC LIGATURE DAD WITH HAH WITH YEH FINAL FORM
+FDAC;FDAC;FDAC;0644 062C 064A;0644 062C 064A; # (ﶬ; ﶬ; ﶬ; لجي; لجي; ) ARABIC LIGATURE LAM WITH JEEM WITH YEH FINAL FORM
+FDAD;FDAD;FDAD;0644 0645 064A;0644 0645 064A; # (ﶭ; ﶭ; ﶭ; لمي; لمي; ) ARABIC LIGATURE LAM WITH MEEM WITH YEH FINAL FORM
+FDAE;FDAE;FDAE;064A 062D 064A;064A 062D 064A; # (ﶮ; ﶮ; ﶮ; يحي; يحي; ) ARABIC LIGATURE YEH WITH HAH WITH YEH FINAL FORM
+FDAF;FDAF;FDAF;064A 062C 064A;064A 062C 064A; # (ﶯ; ﶯ; ﶯ; يجي; يجي; ) ARABIC LIGATURE YEH WITH JEEM WITH YEH FINAL FORM
+FDB0;FDB0;FDB0;064A 0645 064A;064A 0645 064A; # (ﶰ; ﶰ; ﶰ; يمي; يمي; ) ARABIC LIGATURE YEH WITH MEEM WITH YEH FINAL FORM
+FDB1;FDB1;FDB1;0645 0645 064A;0645 0645 064A; # (ﶱ; ﶱ; ﶱ; ممي; ممي; ) ARABIC LIGATURE MEEM WITH MEEM WITH YEH FINAL FORM
+FDB2;FDB2;FDB2;0642 0645 064A;0642 0645 064A; # (ﶲ; ﶲ; ﶲ; قمي; قمي; ) ARABIC LIGATURE QAF WITH MEEM WITH YEH FINAL FORM
+FDB3;FDB3;FDB3;0646 062D 064A;0646 062D 064A; # (ﶳ; ﶳ; ﶳ; نحي; نحي; ) ARABIC LIGATURE NOON WITH HAH WITH YEH FINAL FORM
+FDB4;FDB4;FDB4;0642 0645 062D;0642 0645 062D; # (ﶴ; ﶴ; ﶴ; قمح; قمح; ) ARABIC LIGATURE QAF WITH MEEM WITH HAH INITIAL FORM
+FDB5;FDB5;FDB5;0644 062D 0645;0644 062D 0645; # (ﶵ; ﶵ; ﶵ; لحم; لحم; ) ARABIC LIGATURE LAM WITH HAH WITH MEEM INITIAL FORM
+FDB6;FDB6;FDB6;0639 0645 064A;0639 0645 064A; # (ﶶ; ﶶ; ﶶ; عمي; عمي; ) ARABIC LIGATURE AIN WITH MEEM WITH YEH FINAL FORM
+FDB7;FDB7;FDB7;0643 0645 064A;0643 0645 064A; # (ﶷ; ﶷ; ﶷ; كمي; كمي; ) ARABIC LIGATURE KAF WITH MEEM WITH YEH FINAL FORM
+FDB8;FDB8;FDB8;0646 062C 062D;0646 062C 062D; # (ﶸ; ﶸ; ﶸ; نجح; نجح; ) ARABIC LIGATURE NOON WITH JEEM WITH HAH INITIAL FORM
+FDB9;FDB9;FDB9;0645 062E 064A;0645 062E 064A; # (ﶹ; ﶹ; ﶹ; مخي; مخي; ) ARABIC LIGATURE MEEM WITH KHAH WITH YEH FINAL FORM
+FDBA;FDBA;FDBA;0644 062C 0645;0644 062C 0645; # (ﶺ; ﶺ; ﶺ; لجم; لجم; ) ARABIC LIGATURE LAM WITH JEEM WITH MEEM INITIAL FORM
+FDBB;FDBB;FDBB;0643 0645 0645;0643 0645 0645; # (ﶻ; ﶻ; ﶻ; كمم; كمم; ) ARABIC LIGATURE KAF WITH MEEM WITH MEEM FINAL FORM
+FDBC;FDBC;FDBC;0644 062C 0645;0644 062C 0645; # (ﶼ; ﶼ; ﶼ; لجم; لجم; ) ARABIC LIGATURE LAM WITH JEEM WITH MEEM FINAL FORM
+FDBD;FDBD;FDBD;0646 062C 062D;0646 062C 062D; # (ﶽ; ﶽ; ﶽ; نجح; نجح; ) ARABIC LIGATURE NOON WITH JEEM WITH HAH FINAL FORM
+FDBE;FDBE;FDBE;062C 062D 064A;062C 062D 064A; # (ﶾ; ﶾ; ﶾ; جحي; جحي; ) ARABIC LIGATURE JEEM WITH HAH WITH YEH FINAL FORM
+FDBF;FDBF;FDBF;062D 062C 064A;062D 062C 064A; # (ﶿ; ﶿ; ﶿ; حجي; حجي; ) ARABIC LIGATURE HAH WITH JEEM WITH YEH FINAL FORM
+FDC0;FDC0;FDC0;0645 062C 064A;0645 062C 064A; # (ﷀ; ﷀ; ﷀ; مجي; مجي; ) ARABIC LIGATURE MEEM WITH JEEM WITH YEH FINAL FORM
+FDC1;FDC1;FDC1;0641 0645 064A;0641 0645 064A; # (ﷁ; ﷁ; ﷁ; فمي; فمي; ) ARABIC LIGATURE FEH WITH MEEM WITH YEH FINAL FORM
+FDC2;FDC2;FDC2;0628 062D 064A;0628 062D 064A; # (ﷂ; ﷂ; ﷂ; بحي; بحي; ) ARABIC LIGATURE BEH WITH HAH WITH YEH FINAL FORM
+FDC3;FDC3;FDC3;0643 0645 0645;0643 0645 0645; # (ﷃ; ﷃ; ﷃ; كمم; كمم; ) ARABIC LIGATURE KAF WITH MEEM WITH MEEM INITIAL FORM
+FDC4;FDC4;FDC4;0639 062C 0645;0639 062C 0645; # (ﷄ; ﷄ; ﷄ; عجم; عجم; ) ARABIC LIGATURE AIN WITH JEEM WITH MEEM INITIAL FORM
+FDC5;FDC5;FDC5;0635 0645 0645;0635 0645 0645; # (ﷅ; ﷅ; ﷅ; صمم; صمم; ) ARABIC LIGATURE SAD WITH MEEM WITH MEEM INITIAL FORM
+FDC6;FDC6;FDC6;0633 062E 064A;0633 062E 064A; # (ﷆ; ﷆ; ﷆ; سخي; سخي; ) ARABIC LIGATURE SEEN WITH KHAH WITH YEH FINAL FORM
+FDC7;FDC7;FDC7;0646 062C 064A;0646 062C 064A; # (ﷇ; ﷇ; ﷇ; نجي; نجي; ) ARABIC LIGATURE NOON WITH JEEM WITH YEH FINAL FORM
+FDF0;FDF0;FDF0;0635 0644 06D2;0635 0644 06D2; # (ﷰ; ﷰ; ﷰ; صلے; صلے; ) ARABIC LIGATURE SALLA USED AS KORANIC STOP SIGN ISOLATED FORM
+FDF1;FDF1;FDF1;0642 0644 06D2;0642 0644 06D2; # (ﷱ; ﷱ; ﷱ; قلے; قلے; ) ARABIC LIGATURE QALA USED AS KORANIC STOP SIGN ISOLATED FORM
+FDF2;FDF2;FDF2;0627 0644 0644 0647;0627 0644 0644 0647; # (ﷲ; ﷲ; ﷲ; الله; الله; ) ARABIC LIGATURE ALLAH ISOLATED FORM
+FDF3;FDF3;FDF3;0627 0643 0628 0631;0627 0643 0628 0631; # (ﷳ; ﷳ; ﷳ; اكبر; اكبر; ) ARABIC LIGATURE AKBAR ISOLATED FORM
+FDF4;FDF4;FDF4;0645 062D 0645 062F;0645 062D 0645 062F; # (ﷴ; ﷴ; ﷴ; محمد; محمد; ) ARABIC LIGATURE MOHAMMAD ISOLATED FORM
+FDF5;FDF5;FDF5;0635 0644 0639 0645;0635 0644 0639 0645; # (ﷵ; ﷵ; ﷵ; صلعم; صلعم; ) ARABIC LIGATURE SALAM ISOLATED FORM
+FDF6;FDF6;FDF6;0631 0633 0648 0644;0631 0633 0648 0644; # (ﷶ; ﷶ; ﷶ; رسول; رسول; ) ARABIC LIGATURE RASOUL ISOLATED FORM
+FDF7;FDF7;FDF7;0639 0644 064A 0647;0639 0644 064A 0647; # (ﷷ; ﷷ; ﷷ; عليه; عليه; ) ARABIC LIGATURE ALAYHE ISOLATED FORM
+FDF8;FDF8;FDF8;0648 0633 0644 0645;0648 0633 0644 0645; # (ﷸ; ﷸ; ﷸ; وسلم; وسلم; ) ARABIC LIGATURE WASALLAM ISOLATED FORM
+FDF9;FDF9;FDF9;0635 0644 0649;0635 0644 0649; # (ﷹ; ﷹ; ﷹ; صلى; صلى; ) ARABIC LIGATURE SALLA ISOLATED FORM
+FDFA;FDFA;FDFA;0635 0644 0649 0020 0627 0644 0644 0647 0020 0639 0644 064A 0647 0020 0648 0633 0644 0645;0635 0644 0649 0020 0627 0644 0644 0647 0020 0639 0644 064A 0647 0020 0648 0633 0644 0645; # (ﷺ; ﷺ; ﷺ; صلى الله عليه وسلم; صلى الله عليه وسلم; ) ARABIC LIGATURE SALLALLAHOU ALAYHE WASALLAM
+FDFB;FDFB;FDFB;062C 0644 0020 062C 0644 0627 0644 0647;062C 0644 0020 062C 0644 0627 0644 0647; # (ﷻ; ﷻ; ﷻ; جل جلاله; جل جلاله; ) ARABIC LIGATURE JALLAJALALOUHOU
+FDFC;FDFC;FDFC;0631 06CC 0627 0644;0631 06CC 0627 0644; # (﷼; ﷼; ﷼; ریال; ریال; ) RIAL SIGN
+FE30;FE30;FE30;002E 002E;002E 002E; # (︰; ︰; ︰; ..; ..; ) PRESENTATION FORM FOR VERTICAL TWO DOT LEADER
+FE31;FE31;FE31;2014;2014; # (︱; ︱; ︱; —; —; ) PRESENTATION FORM FOR VERTICAL EM DASH
+FE32;FE32;FE32;2013;2013; # (︲; ︲; ︲; –; –; ) PRESENTATION FORM FOR VERTICAL EN DASH
+FE33;FE33;FE33;005F;005F; # (︳; ︳; ︳; _; _; ) PRESENTATION FORM FOR VERTICAL LOW LINE
+FE34;FE34;FE34;005F;005F; # (︴; ︴; ︴; _; _; ) PRESENTATION FORM FOR VERTICAL WAVY LOW LINE
+FE35;FE35;FE35;0028;0028; # (︵; ︵; ︵; (; (; ) PRESENTATION FORM FOR VERTICAL LEFT PARENTHESIS
+FE36;FE36;FE36;0029;0029; # (︶; ︶; ︶; ); ); ) PRESENTATION FORM FOR VERTICAL RIGHT PARENTHESIS
+FE37;FE37;FE37;007B;007B; # (︷; ︷; ︷; {; {; ) PRESENTATION FORM FOR VERTICAL LEFT CURLY BRACKET
+FE38;FE38;FE38;007D;007D; # (︸; ︸; ︸; }; }; ) PRESENTATION FORM FOR VERTICAL RIGHT CURLY BRACKET
+FE39;FE39;FE39;3014;3014; # (︹; ︹; ︹; 〔; 〔; ) PRESENTATION FORM FOR VERTICAL LEFT TORTOISE SHELL BRACKET
+FE3A;FE3A;FE3A;3015;3015; # (︺; ︺; ︺; 〕; 〕; ) PRESENTATION FORM FOR VERTICAL RIGHT TORTOISE SHELL BRACKET
+FE3B;FE3B;FE3B;3010;3010; # (︻; ︻; ︻; 【; 【; ) PRESENTATION FORM FOR VERTICAL LEFT BLACK LENTICULAR BRACKET
+FE3C;FE3C;FE3C;3011;3011; # (︼; ︼; ︼; 】; 】; ) PRESENTATION FORM FOR VERTICAL RIGHT BLACK LENTICULAR BRACKET
+FE3D;FE3D;FE3D;300A;300A; # (︽; ︽; ︽; 《; 《; ) PRESENTATION FORM FOR VERTICAL LEFT DOUBLE ANGLE BRACKET
+FE3E;FE3E;FE3E;300B;300B; # (︾; ︾; ︾; 》; 》; ) PRESENTATION FORM FOR VERTICAL RIGHT DOUBLE ANGLE BRACKET
+FE3F;FE3F;FE3F;3008;3008; # (︿; ︿; ︿; 〈; 〈; ) PRESENTATION FORM FOR VERTICAL LEFT ANGLE BRACKET
+FE40;FE40;FE40;3009;3009; # (﹀; ﹀; ﹀; 〉; 〉; ) PRESENTATION FORM FOR VERTICAL RIGHT ANGLE BRACKET
+FE41;FE41;FE41;300C;300C; # (﹁; ﹁; ﹁; 「; 「; ) PRESENTATION FORM FOR VERTICAL LEFT CORNER BRACKET
+FE42;FE42;FE42;300D;300D; # (﹂; ﹂; ﹂; 」; 」; ) PRESENTATION FORM FOR VERTICAL RIGHT CORNER BRACKET
+FE43;FE43;FE43;300E;300E; # (﹃; ﹃; ﹃; 『; 『; ) PRESENTATION FORM FOR VERTICAL LEFT WHITE CORNER BRACKET
+FE44;FE44;FE44;300F;300F; # (﹄; ﹄; ﹄; 』; 』; ) PRESENTATION FORM FOR VERTICAL RIGHT WHITE CORNER BRACKET
+FE47;FE47;FE47;005B;005B; # (﹇; ﹇; ﹇; [; [; ) PRESENTATION FORM FOR VERTICAL LEFT SQUARE BRACKET
+FE48;FE48;FE48;005D;005D; # (﹈; ﹈; ﹈; ]; ]; ) PRESENTATION FORM FOR VERTICAL RIGHT SQUARE BRACKET
+FE49;FE49;FE49;0020 0305;0020 0305; # (﹉; ﹉; ﹉; ◌̅; ◌̅; ) DASHED OVERLINE
+FE4A;FE4A;FE4A;0020 0305;0020 0305; # (﹊; ﹊; ﹊; ◌̅; ◌̅; ) CENTRELINE OVERLINE
+FE4B;FE4B;FE4B;0020 0305;0020 0305; # (﹋; ﹋; ﹋; ◌̅; ◌̅; ) WAVY OVERLINE
+FE4C;FE4C;FE4C;0020 0305;0020 0305; # (﹌; ﹌; ﹌; ◌̅; ◌̅; ) DOUBLE WAVY OVERLINE
+FE4D;FE4D;FE4D;005F;005F; # (﹍; ﹍; ﹍; _; _; ) DASHED LOW LINE
+FE4E;FE4E;FE4E;005F;005F; # (﹎; ﹎; ﹎; _; _; ) CENTRELINE LOW LINE
+FE4F;FE4F;FE4F;005F;005F; # (﹏; ﹏; ﹏; _; _; ) WAVY LOW LINE
+FE50;FE50;FE50;002C;002C; # (﹐; ﹐; ﹐; ,; ,; ) SMALL COMMA
+FE51;FE51;FE51;3001;3001; # (﹑; ﹑; ﹑; 、; 、; ) SMALL IDEOGRAPHIC COMMA
+FE52;FE52;FE52;002E;002E; # (﹒; ﹒; ﹒; .; .; ) SMALL FULL STOP
+FE54;FE54;FE54;003B;003B; # (﹔; ﹔; ﹔; ;; ;; ) SMALL SEMICOLON
+FE55;FE55;FE55;003A;003A; # (﹕; ﹕; ﹕; :; :; ) SMALL COLON
+FE56;FE56;FE56;003F;003F; # (﹖; ﹖; ﹖; ?; ?; ) SMALL QUESTION MARK
+FE57;FE57;FE57;0021;0021; # (﹗; ﹗; ﹗; !; !; ) SMALL EXCLAMATION MARK
+FE58;FE58;FE58;2014;2014; # (﹘; ﹘; ﹘; —; —; ) SMALL EM DASH
+FE59;FE59;FE59;0028;0028; # (﹙; ﹙; ﹙; (; (; ) SMALL LEFT PARENTHESIS
+FE5A;FE5A;FE5A;0029;0029; # (﹚; ﹚; ﹚; ); ); ) SMALL RIGHT PARENTHESIS
+FE5B;FE5B;FE5B;007B;007B; # (﹛; ﹛; ﹛; {; {; ) SMALL LEFT CURLY BRACKET
+FE5C;FE5C;FE5C;007D;007D; # (﹜; ﹜; ﹜; }; }; ) SMALL RIGHT CURLY BRACKET
+FE5D;FE5D;FE5D;3014;3014; # (﹝; ﹝; ﹝; 〔; 〔; ) SMALL LEFT TORTOISE SHELL BRACKET
+FE5E;FE5E;FE5E;3015;3015; # (﹞; ﹞; ﹞; 〕; 〕; ) SMALL RIGHT TORTOISE SHELL BRACKET
+FE5F;FE5F;FE5F;0023;0023; # (﹟; ﹟; ﹟; #; #; ) SMALL NUMBER SIGN
+FE60;FE60;FE60;0026;0026; # (﹠; ﹠; ﹠; &; &; ) SMALL AMPERSAND
+FE61;FE61;FE61;002A;002A; # (﹡; ﹡; ﹡; *; *; ) SMALL ASTERISK
+FE62;FE62;FE62;002B;002B; # (﹢; ﹢; ﹢; +; +; ) SMALL PLUS SIGN
+FE63;FE63;FE63;002D;002D; # (﹣; ﹣; ﹣; -; -; ) SMALL HYPHEN-MINUS
+FE64;FE64;FE64;003C;003C; # (﹤; ﹤; ﹤; <; <; ) SMALL LESS-THAN SIGN
+FE65;FE65;FE65;003E;003E; # (﹥; ﹥; ﹥; >; >; ) SMALL GREATER-THAN SIGN
+FE66;FE66;FE66;003D;003D; # (﹦; ﹦; ﹦; =; =; ) SMALL EQUALS SIGN
+FE68;FE68;FE68;005C;005C; # (﹨; ﹨; ﹨; \; \; ) SMALL REVERSE SOLIDUS
+FE69;FE69;FE69;0024;0024; # (﹩; ﹩; ﹩; $; $; ) SMALL DOLLAR SIGN
+FE6A;FE6A;FE6A;0025;0025; # (﹪; ﹪; ﹪; %; %; ) SMALL PERCENT SIGN
+FE6B;FE6B;FE6B;0040;0040; # (﹫; ﹫; ﹫; @; @; ) SMALL COMMERCIAL AT
+FE70;FE70;FE70;0020 064B;0020 064B; # (ﹰ; ﹰ; ﹰ; ◌ً; ◌ً; ) ARABIC FATHATAN ISOLATED FORM
+FE71;FE71;FE71;0640 064B;0640 064B; # (ﹱ; ﹱ; ﹱ; ـ◌ً; ـ◌ً; ) ARABIC TATWEEL WITH FATHATAN ABOVE
+FE72;FE72;FE72;0020 064C;0020 064C; # (ﹲ; ﹲ; ﹲ; ◌ٌ; ◌ٌ; ) ARABIC DAMMATAN ISOLATED FORM
+FE74;FE74;FE74;0020 064D;0020 064D; # (ﹴ; ﹴ; ﹴ; ◌ٍ; ◌ٍ; ) ARABIC KASRATAN ISOLATED FORM
+FE76;FE76;FE76;0020 064E;0020 064E; # (ﹶ; ﹶ; ﹶ; ◌َ; ◌َ; ) ARABIC FATHA ISOLATED FORM
+FE77;FE77;FE77;0640 064E;0640 064E; # (ﹷ; ﹷ; ﹷ; ـ◌َ; ـ◌َ; ) ARABIC FATHA MEDIAL FORM
+FE78;FE78;FE78;0020 064F;0020 064F; # (ﹸ; ﹸ; ﹸ; ◌ُ; ◌ُ; ) ARABIC DAMMA ISOLATED FORM
+FE79;FE79;FE79;0640 064F;0640 064F; # (ﹹ; ﹹ; ﹹ; ـ◌ُ; ـ◌ُ; ) ARABIC DAMMA MEDIAL FORM
+FE7A;FE7A;FE7A;0020 0650;0020 0650; # (ﹺ; ﹺ; ﹺ; ◌ِ; ◌ِ; ) ARABIC KASRA ISOLATED FORM
+FE7B;FE7B;FE7B;0640 0650;0640 0650; # (ﹻ; ﹻ; ﹻ; ـ◌ِ; ـ◌ِ; ) ARABIC KASRA MEDIAL FORM
+FE7C;FE7C;FE7C;0020 0651;0020 0651; # (ﹼ; ﹼ; ﹼ; ◌ّ; ◌ّ; ) ARABIC SHADDA ISOLATED FORM
+FE7D;FE7D;FE7D;0640 0651;0640 0651; # (ﹽ; ﹽ; ﹽ; ـ◌ّ; ـ◌ّ; ) ARABIC SHADDA MEDIAL FORM
+FE7E;FE7E;FE7E;0020 0652;0020 0652; # (ﹾ; ﹾ; ﹾ; ◌ْ; ◌ْ; ) ARABIC SUKUN ISOLATED FORM
+FE7F;FE7F;FE7F;0640 0652;0640 0652; # (ﹿ; ﹿ; ﹿ; ـ◌ْ; ـ◌ْ; ) ARABIC SUKUN MEDIAL FORM
+FE80;FE80;FE80;0621;0621; # (ﺀ; ﺀ; ﺀ; ء; ء; ) ARABIC LETTER HAMZA ISOLATED FORM
+FE81;FE81;FE81;0622;0627 0653; # (ﺁ; ﺁ; ﺁ; آ; ا◌ٓ; ) ARABIC LETTER ALEF WITH MADDA ABOVE ISOLATED FORM
+FE82;FE82;FE82;0622;0627 0653; # (ﺂ; ﺂ; ﺂ; آ; ا◌ٓ; ) ARABIC LETTER ALEF WITH MADDA ABOVE FINAL FORM
+FE83;FE83;FE83;0623;0627 0654; # (ﺃ; ﺃ; ﺃ; أ; ا◌ٔ; ) ARABIC LETTER ALEF WITH HAMZA ABOVE ISOLATED FORM
+FE84;FE84;FE84;0623;0627 0654; # (ﺄ; ﺄ; ﺄ; أ; ا◌ٔ; ) ARABIC LETTER ALEF WITH HAMZA ABOVE FINAL FORM
+FE85;FE85;FE85;0624;0648 0654; # (ﺅ; ﺅ; ﺅ; ؤ; و◌ٔ; ) ARABIC LETTER WAW WITH HAMZA ABOVE ISOLATED FORM
+FE86;FE86;FE86;0624;0648 0654; # (ﺆ; ﺆ; ﺆ; ؤ; و◌ٔ; ) ARABIC LETTER WAW WITH HAMZA ABOVE FINAL FORM
+FE87;FE87;FE87;0625;0627 0655; # (ﺇ; ﺇ; ﺇ; إ; ا◌ٕ; ) ARABIC LETTER ALEF WITH HAMZA BELOW ISOLATED FORM
+FE88;FE88;FE88;0625;0627 0655; # (ﺈ; ﺈ; ﺈ; إ; ا◌ٕ; ) ARABIC LETTER ALEF WITH HAMZA BELOW FINAL FORM
+FE89;FE89;FE89;0626;064A 0654; # (ﺉ; ﺉ; ﺉ; ئ; ي◌ٔ; ) ARABIC LETTER YEH WITH HAMZA ABOVE ISOLATED FORM
+FE8A;FE8A;FE8A;0626;064A 0654; # (ﺊ; ﺊ; ﺊ; ئ; ي◌ٔ; ) ARABIC LETTER YEH WITH HAMZA ABOVE FINAL FORM
+FE8B;FE8B;FE8B;0626;064A 0654; # (ﺋ; ﺋ; ﺋ; ئ; ي◌ٔ; ) ARABIC LETTER YEH WITH HAMZA ABOVE INITIAL FORM
+FE8C;FE8C;FE8C;0626;064A 0654; # (ﺌ; ﺌ; ﺌ; ئ; ي◌ٔ; ) ARABIC LETTER YEH WITH HAMZA ABOVE MEDIAL FORM
+FE8D;FE8D;FE8D;0627;0627; # (ﺍ; ﺍ; ﺍ; ا; ا; ) ARABIC LETTER ALEF ISOLATED FORM
+FE8E;FE8E;FE8E;0627;0627; # (ﺎ; ﺎ; ﺎ; ا; ا; ) ARABIC LETTER ALEF FINAL FORM
+FE8F;FE8F;FE8F;0628;0628; # (ﺏ; ﺏ; ﺏ; ب; ب; ) ARABIC LETTER BEH ISOLATED FORM
+FE90;FE90;FE90;0628;0628; # (ﺐ; ﺐ; ﺐ; ب; ب; ) ARABIC LETTER BEH FINAL FORM
+FE91;FE91;FE91;0628;0628; # (ﺑ; ﺑ; ﺑ; ب; ب; ) ARABIC LETTER BEH INITIAL FORM
+FE92;FE92;FE92;0628;0628; # (ﺒ; ﺒ; ﺒ; ب; ب; ) ARABIC LETTER BEH MEDIAL FORM
+FE93;FE93;FE93;0629;0629; # (ﺓ; ﺓ; ﺓ; ة; ة; ) ARABIC LETTER TEH MARBUTA ISOLATED FORM
+FE94;FE94;FE94;0629;0629; # (ﺔ; ﺔ; ﺔ; ة; ة; ) ARABIC LETTER TEH MARBUTA FINAL FORM
+FE95;FE95;FE95;062A;062A; # (ﺕ; ﺕ; ﺕ; ت; ت; ) ARABIC LETTER TEH ISOLATED FORM
+FE96;FE96;FE96;062A;062A; # (ﺖ; ﺖ; ﺖ; ت; ت; ) ARABIC LETTER TEH FINAL FORM
+FE97;FE97;FE97;062A;062A; # (ﺗ; ﺗ; ﺗ; ت; ت; ) ARABIC LETTER TEH INITIAL FORM
+FE98;FE98;FE98;062A;062A; # (ﺘ; ﺘ; ﺘ; ت; ت; ) ARABIC LETTER TEH MEDIAL FORM
+FE99;FE99;FE99;062B;062B; # (ﺙ; ﺙ; ﺙ; ث; ث; ) ARABIC LETTER THEH ISOLATED FORM
+FE9A;FE9A;FE9A;062B;062B; # (ﺚ; ﺚ; ﺚ; ث; ث; ) ARABIC LETTER THEH FINAL FORM
+FE9B;FE9B;FE9B;062B;062B; # (ﺛ; ﺛ; ﺛ; ث; ث; ) ARABIC LETTER THEH INITIAL FORM
+FE9C;FE9C;FE9C;062B;062B; # (ﺜ; ﺜ; ﺜ; ث; ث; ) ARABIC LETTER THEH MEDIAL FORM
+FE9D;FE9D;FE9D;062C;062C; # (ﺝ; ﺝ; ﺝ; ج; ج; ) ARABIC LETTER JEEM ISOLATED FORM
+FE9E;FE9E;FE9E;062C;062C; # (ﺞ; ﺞ; ﺞ; ج; ج; ) ARABIC LETTER JEEM FINAL FORM
+FE9F;FE9F;FE9F;062C;062C; # (ﺟ; ﺟ; ﺟ; ج; ج; ) ARABIC LETTER JEEM INITIAL FORM
+FEA0;FEA0;FEA0;062C;062C; # (ﺠ; ﺠ; ﺠ; ج; ج; ) ARABIC LETTER JEEM MEDIAL FORM
+FEA1;FEA1;FEA1;062D;062D; # (ﺡ; ﺡ; ﺡ; ح; ح; ) ARABIC LETTER HAH ISOLATED FORM
+FEA2;FEA2;FEA2;062D;062D; # (ﺢ; ﺢ; ﺢ; ح; ح; ) ARABIC LETTER HAH FINAL FORM
+FEA3;FEA3;FEA3;062D;062D; # (ﺣ; ﺣ; ﺣ; ح; ح; ) ARABIC LETTER HAH INITIAL FORM
+FEA4;FEA4;FEA4;062D;062D; # (ﺤ; ﺤ; ﺤ; ح; ح; ) ARABIC LETTER HAH MEDIAL FORM
+FEA5;FEA5;FEA5;062E;062E; # (ﺥ; ﺥ; ﺥ; خ; خ; ) ARABIC LETTER KHAH ISOLATED FORM
+FEA6;FEA6;FEA6;062E;062E; # (ﺦ; ﺦ; ﺦ; خ; خ; ) ARABIC LETTER KHAH FINAL FORM
+FEA7;FEA7;FEA7;062E;062E; # (ﺧ; ﺧ; ﺧ; خ; خ; ) ARABIC LETTER KHAH INITIAL FORM
+FEA8;FEA8;FEA8;062E;062E; # (ﺨ; ﺨ; ﺨ; خ; خ; ) ARABIC LETTER KHAH MEDIAL FORM
+FEA9;FEA9;FEA9;062F;062F; # (ﺩ; ﺩ; ﺩ; د; د; ) ARABIC LETTER DAL ISOLATED FORM
+FEAA;FEAA;FEAA;062F;062F; # (ﺪ; ﺪ; ﺪ; د; د; ) ARABIC LETTER DAL FINAL FORM
+FEAB;FEAB;FEAB;0630;0630; # (ﺫ; ﺫ; ﺫ; ذ; ذ; ) ARABIC LETTER THAL ISOLATED FORM
+FEAC;FEAC;FEAC;0630;0630; # (ﺬ; ﺬ; ﺬ; ذ; ذ; ) ARABIC LETTER THAL FINAL FORM
+FEAD;FEAD;FEAD;0631;0631; # (ﺭ; ﺭ; ﺭ; ر; ر; ) ARABIC LETTER REH ISOLATED FORM
+FEAE;FEAE;FEAE;0631;0631; # (ﺮ; ﺮ; ﺮ; ر; ر; ) ARABIC LETTER REH FINAL FORM
+FEAF;FEAF;FEAF;0632;0632; # (ﺯ; ﺯ; ﺯ; ز; ز; ) ARABIC LETTER ZAIN ISOLATED FORM
+FEB0;FEB0;FEB0;0632;0632; # (ﺰ; ﺰ; ﺰ; ز; ز; ) ARABIC LETTER ZAIN FINAL FORM
+FEB1;FEB1;FEB1;0633;0633; # (ﺱ; ﺱ; ﺱ; س; س; ) ARABIC LETTER SEEN ISOLATED FORM
+FEB2;FEB2;FEB2;0633;0633; # (ﺲ; ﺲ; ﺲ; س; س; ) ARABIC LETTER SEEN FINAL FORM
+FEB3;FEB3;FEB3;0633;0633; # (ﺳ; ﺳ; ﺳ; س; س; ) ARABIC LETTER SEEN INITIAL FORM
+FEB4;FEB4;FEB4;0633;0633; # (ﺴ; ﺴ; ﺴ; س; س; ) ARABIC LETTER SEEN MEDIAL FORM
+FEB5;FEB5;FEB5;0634;0634; # (ﺵ; ﺵ; ﺵ; ش; ش; ) ARABIC LETTER SHEEN ISOLATED FORM
+FEB6;FEB6;FEB6;0634;0634; # (ﺶ; ﺶ; ﺶ; ش; ش; ) ARABIC LETTER SHEEN FINAL FORM
+FEB7;FEB7;FEB7;0634;0634; # (ﺷ; ﺷ; ﺷ; ش; ش; ) ARABIC LETTER SHEEN INITIAL FORM
+FEB8;FEB8;FEB8;0634;0634; # (ﺸ; ﺸ; ﺸ; ش; ش; ) ARABIC LETTER SHEEN MEDIAL FORM
+FEB9;FEB9;FEB9;0635;0635; # (ﺹ; ﺹ; ﺹ; ص; ص; ) ARABIC LETTER SAD ISOLATED FORM
+FEBA;FEBA;FEBA;0635;0635; # (ﺺ; ﺺ; ﺺ; ص; ص; ) ARABIC LETTER SAD FINAL FORM
+FEBB;FEBB;FEBB;0635;0635; # (ﺻ; ﺻ; ﺻ; ص; ص; ) ARABIC LETTER SAD INITIAL FORM
+FEBC;FEBC;FEBC;0635;0635; # (ﺼ; ﺼ; ﺼ; ص; ص; ) ARABIC LETTER SAD MEDIAL FORM
+FEBD;FEBD;FEBD;0636;0636; # (ﺽ; ﺽ; ﺽ; ض; ض; ) ARABIC LETTER DAD ISOLATED FORM
+FEBE;FEBE;FEBE;0636;0636; # (ﺾ; ﺾ; ﺾ; ض; ض; ) ARABIC LETTER DAD FINAL FORM
+FEBF;FEBF;FEBF;0636;0636; # (ﺿ; ﺿ; ﺿ; ض; ض; ) ARABIC LETTER DAD INITIAL FORM
+FEC0;FEC0;FEC0;0636;0636; # (ﻀ; ﻀ; ﻀ; ض; ض; ) ARABIC LETTER DAD MEDIAL FORM
+FEC1;FEC1;FEC1;0637;0637; # (ﻁ; ﻁ; ﻁ; ط; ط; ) ARABIC LETTER TAH ISOLATED FORM
+FEC2;FEC2;FEC2;0637;0637; # (ﻂ; ﻂ; ﻂ; ط; ط; ) ARABIC LETTER TAH FINAL FORM
+FEC3;FEC3;FEC3;0637;0637; # (ﻃ; ﻃ; ﻃ; ط; ط; ) ARABIC LETTER TAH INITIAL FORM
+FEC4;FEC4;FEC4;0637;0637; # (ﻄ; ﻄ; ﻄ; ط; ط; ) ARABIC LETTER TAH MEDIAL FORM
+FEC5;FEC5;FEC5;0638;0638; # (ﻅ; ﻅ; ﻅ; ظ; ظ; ) ARABIC LETTER ZAH ISOLATED FORM
+FEC6;FEC6;FEC6;0638;0638; # (ﻆ; ﻆ; ﻆ; ظ; ظ; ) ARABIC LETTER ZAH FINAL FORM
+FEC7;FEC7;FEC7;0638;0638; # (ﻇ; ﻇ; ﻇ; ظ; ظ; ) ARABIC LETTER ZAH INITIAL FORM
+FEC8;FEC8;FEC8;0638;0638; # (ﻈ; ﻈ; ﻈ; ظ; ظ; ) ARABIC LETTER ZAH MEDIAL FORM
+FEC9;FEC9;FEC9;0639;0639; # (ﻉ; ﻉ; ﻉ; ع; ع; ) ARABIC LETTER AIN ISOLATED FORM
+FECA;FECA;FECA;0639;0639; # (ﻊ; ﻊ; ﻊ; ع; ع; ) ARABIC LETTER AIN FINAL FORM
+FECB;FECB;FECB;0639;0639; # (ﻋ; ﻋ; ﻋ; ع; ع; ) ARABIC LETTER AIN INITIAL FORM
+FECC;FECC;FECC;0639;0639; # (ﻌ; ﻌ; ﻌ; ع; ع; ) ARABIC LETTER AIN MEDIAL FORM
+FECD;FECD;FECD;063A;063A; # (ﻍ; ﻍ; ﻍ; غ; غ; ) ARABIC LETTER GHAIN ISOLATED FORM
+FECE;FECE;FECE;063A;063A; # (ﻎ; ﻎ; ﻎ; غ; غ; ) ARABIC LETTER GHAIN FINAL FORM
+FECF;FECF;FECF;063A;063A; # (ﻏ; ﻏ; ﻏ; غ; غ; ) ARABIC LETTER GHAIN INITIAL FORM
+FED0;FED0;FED0;063A;063A; # (ﻐ; ﻐ; ﻐ; غ; غ; ) ARABIC LETTER GHAIN MEDIAL FORM
+FED1;FED1;FED1;0641;0641; # (ﻑ; ﻑ; ﻑ; ف; ف; ) ARABIC LETTER FEH ISOLATED FORM
+FED2;FED2;FED2;0641;0641; # (ﻒ; ﻒ; ﻒ; ف; ف; ) ARABIC LETTER FEH FINAL FORM
+FED3;FED3;FED3;0641;0641; # (ﻓ; ﻓ; ﻓ; ف; ف; ) ARABIC LETTER FEH INITIAL FORM
+FED4;FED4;FED4;0641;0641; # (ﻔ; ﻔ; ﻔ; ف; ف; ) ARABIC LETTER FEH MEDIAL FORM
+FED5;FED5;FED5;0642;0642; # (ﻕ; ﻕ; ﻕ; ق; ق; ) ARABIC LETTER QAF ISOLATED FORM
+FED6;FED6;FED6;0642;0642; # (ﻖ; ﻖ; ﻖ; ق; ق; ) ARABIC LETTER QAF FINAL FORM
+FED7;FED7;FED7;0642;0642; # (ﻗ; ﻗ; ﻗ; ق; ق; ) ARABIC LETTER QAF INITIAL FORM
+FED8;FED8;FED8;0642;0642; # (ﻘ; ﻘ; ﻘ; ق; ق; ) ARABIC LETTER QAF MEDIAL FORM
+FED9;FED9;FED9;0643;0643; # (ﻙ; ﻙ; ﻙ; ك; ك; ) ARABIC LETTER KAF ISOLATED FORM
+FEDA;FEDA;FEDA;0643;0643; # (ﻚ; ﻚ; ﻚ; ك; ك; ) ARABIC LETTER KAF FINAL FORM
+FEDB;FEDB;FEDB;0643;0643; # (ﻛ; ﻛ; ﻛ; ك; ك; ) ARABIC LETTER KAF INITIAL FORM
+FEDC;FEDC;FEDC;0643;0643; # (ﻜ; ﻜ; ﻜ; ك; ك; ) ARABIC LETTER KAF MEDIAL FORM
+FEDD;FEDD;FEDD;0644;0644; # (ﻝ; ﻝ; ﻝ; ل; ل; ) ARABIC LETTER LAM ISOLATED FORM
+FEDE;FEDE;FEDE;0644;0644; # (ﻞ; ﻞ; ﻞ; ل; ل; ) ARABIC LETTER LAM FINAL FORM
+FEDF;FEDF;FEDF;0644;0644; # (ﻟ; ﻟ; ﻟ; ل; ل; ) ARABIC LETTER LAM INITIAL FORM
+FEE0;FEE0;FEE0;0644;0644; # (ﻠ; ﻠ; ﻠ; ل; ل; ) ARABIC LETTER LAM MEDIAL FORM
+FEE1;FEE1;FEE1;0645;0645; # (ﻡ; ﻡ; ﻡ; م; م; ) ARABIC LETTER MEEM ISOLATED FORM
+FEE2;FEE2;FEE2;0645;0645; # (ﻢ; ﻢ; ﻢ; م; م; ) ARABIC LETTER MEEM FINAL FORM
+FEE3;FEE3;FEE3;0645;0645; # (ﻣ; ﻣ; ﻣ; م; م; ) ARABIC LETTER MEEM INITIAL FORM
+FEE4;FEE4;FEE4;0645;0645; # (ﻤ; ﻤ; ﻤ; م; م; ) ARABIC LETTER MEEM MEDIAL FORM
+FEE5;FEE5;FEE5;0646;0646; # (ﻥ; ﻥ; ﻥ; ن; ن; ) ARABIC LETTER NOON ISOLATED FORM
+FEE6;FEE6;FEE6;0646;0646; # (ﻦ; ﻦ; ﻦ; ن; ن; ) ARABIC LETTER NOON FINAL FORM
+FEE7;FEE7;FEE7;0646;0646; # (ﻧ; ﻧ; ﻧ; ن; ن; ) ARABIC LETTER NOON INITIAL FORM
+FEE8;FEE8;FEE8;0646;0646; # (ﻨ; ﻨ; ﻨ; ن; ن; ) ARABIC LETTER NOON MEDIAL FORM
+FEE9;FEE9;FEE9;0647;0647; # (ﻩ; ﻩ; ﻩ; ه; ه; ) ARABIC LETTER HEH ISOLATED FORM
+FEEA;FEEA;FEEA;0647;0647; # (ﻪ; ﻪ; ﻪ; ه; ه; ) ARABIC LETTER HEH FINAL FORM
+FEEB;FEEB;FEEB;0647;0647; # (ﻫ; ﻫ; ﻫ; ه; ه; ) ARABIC LETTER HEH INITIAL FORM
+FEEC;FEEC;FEEC;0647;0647; # (ﻬ; ﻬ; ﻬ; ه; ه; ) ARABIC LETTER HEH MEDIAL FORM
+FEED;FEED;FEED;0648;0648; # (ﻭ; ﻭ; ﻭ; و; و; ) ARABIC LETTER WAW ISOLATED FORM
+FEEE;FEEE;FEEE;0648;0648; # (ﻮ; ﻮ; ﻮ; و; و; ) ARABIC LETTER WAW FINAL FORM
+FEEF;FEEF;FEEF;0649;0649; # (ﻯ; ﻯ; ﻯ; ى; ى; ) ARABIC LETTER ALEF MAKSURA ISOLATED FORM
+FEF0;FEF0;FEF0;0649;0649; # (ﻰ; ﻰ; ﻰ; ى; ى; ) ARABIC LETTER ALEF MAKSURA FINAL FORM
+FEF1;FEF1;FEF1;064A;064A; # (ﻱ; ﻱ; ﻱ; ي; ي; ) ARABIC LETTER YEH ISOLATED FORM
+FEF2;FEF2;FEF2;064A;064A; # (ﻲ; ﻲ; ﻲ; ي; ي; ) ARABIC LETTER YEH FINAL FORM
+FEF3;FEF3;FEF3;064A;064A; # (ﻳ; ﻳ; ﻳ; ي; ي; ) ARABIC LETTER YEH INITIAL FORM
+FEF4;FEF4;FEF4;064A;064A; # (ﻴ; ﻴ; ﻴ; ي; ي; ) ARABIC LETTER YEH MEDIAL FORM
+FEF5;FEF5;FEF5;0644 0622;0644 0627 0653; # (ﻵ; ﻵ; ﻵ; لآ; لا◌ٓ; ) ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM
+FEF6;FEF6;FEF6;0644 0622;0644 0627 0653; # (ﻶ; ﻶ; ﻶ; لآ; لا◌ٓ; ) ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE FINAL FORM
+FEF7;FEF7;FEF7;0644 0623;0644 0627 0654; # (ﻷ; ﻷ; ﻷ; لأ; لا◌ٔ; ) ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE ISOLATED FORM
+FEF8;FEF8;FEF8;0644 0623;0644 0627 0654; # (ﻸ; ﻸ; ﻸ; لأ; لا◌ٔ; ) ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE FINAL FORM
+FEF9;FEF9;FEF9;0644 0625;0644 0627 0655; # (ﻹ; ﻹ; ﻹ; لإ; لا◌ٕ; ) ARABIC LIGATURE LAM WITH ALEF WITH HAMZA BELOW ISOLATED FORM
+FEFA;FEFA;FEFA;0644 0625;0644 0627 0655; # (ﻺ; ﻺ; ﻺ; لإ; لا◌ٕ; ) ARABIC LIGATURE LAM WITH ALEF WITH HAMZA BELOW FINAL FORM
+FEFB;FEFB;FEFB;0644 0627;0644 0627; # (ﻻ; ﻻ; ﻻ; لا; لا; ) ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM
+FEFC;FEFC;FEFC;0644 0627;0644 0627; # (ﻼ; ﻼ; ﻼ; لا; لا; ) ARABIC LIGATURE LAM WITH ALEF FINAL FORM
+FF01;FF01;FF01;0021;0021; # (!; !; !; !; !; ) FULLWIDTH EXCLAMATION MARK
+FF02;FF02;FF02;0022;0022; # ("; "; "; "; "; ) FULLWIDTH QUOTATION MARK
+FF03;FF03;FF03;0023;0023; # (#; #; #; #; #; ) FULLWIDTH NUMBER SIGN
+FF04;FF04;FF04;0024;0024; # ($; $; $; $; $; ) FULLWIDTH DOLLAR SIGN
+FF05;FF05;FF05;0025;0025; # (%; %; %; %; %; ) FULLWIDTH PERCENT SIGN
+FF06;FF06;FF06;0026;0026; # (&; &; &; &; &; ) FULLWIDTH AMPERSAND
+FF07;FF07;FF07;0027;0027; # ('; '; '; '; '; ) FULLWIDTH APOSTROPHE
+FF08;FF08;FF08;0028;0028; # ((; (; (; (; (; ) FULLWIDTH LEFT PARENTHESIS
+FF09;FF09;FF09;0029;0029; # (); ); ); ); ); ) FULLWIDTH RIGHT PARENTHESIS
+FF0A;FF0A;FF0A;002A;002A; # (*; *; *; *; *; ) FULLWIDTH ASTERISK
+FF0B;FF0B;FF0B;002B;002B; # (+; +; +; +; +; ) FULLWIDTH PLUS SIGN
+FF0C;FF0C;FF0C;002C;002C; # (,; ,; ,; ,; ,; ) FULLWIDTH COMMA
+FF0D;FF0D;FF0D;002D;002D; # (-; -; -; -; -; ) FULLWIDTH HYPHEN-MINUS
+FF0E;FF0E;FF0E;002E;002E; # (.; .; .; .; .; ) FULLWIDTH FULL STOP
+FF0F;FF0F;FF0F;002F;002F; # (/; /; /; /; /; ) FULLWIDTH SOLIDUS
+FF10;FF10;FF10;0030;0030; # (0; 0; 0; 0; 0; ) FULLWIDTH DIGIT ZERO
+FF11;FF11;FF11;0031;0031; # (1; 1; 1; 1; 1; ) FULLWIDTH DIGIT ONE
+FF12;FF12;FF12;0032;0032; # (2; 2; 2; 2; 2; ) FULLWIDTH DIGIT TWO
+FF13;FF13;FF13;0033;0033; # (3; 3; 3; 3; 3; ) FULLWIDTH DIGIT THREE
+FF14;FF14;FF14;0034;0034; # (4; 4; 4; 4; 4; ) FULLWIDTH DIGIT FOUR
+FF15;FF15;FF15;0035;0035; # (5; 5; 5; 5; 5; ) FULLWIDTH DIGIT FIVE
+FF16;FF16;FF16;0036;0036; # (6; 6; 6; 6; 6; ) FULLWIDTH DIGIT SIX
+FF17;FF17;FF17;0037;0037; # (7; 7; 7; 7; 7; ) FULLWIDTH DIGIT SEVEN
+FF18;FF18;FF18;0038;0038; # (8; 8; 8; 8; 8; ) FULLWIDTH DIGIT EIGHT
+FF19;FF19;FF19;0039;0039; # (9; 9; 9; 9; 9; ) FULLWIDTH DIGIT NINE
+FF1A;FF1A;FF1A;003A;003A; # (:; :; :; :; :; ) FULLWIDTH COLON
+FF1B;FF1B;FF1B;003B;003B; # (;; ;; ;; ;; ;; ) FULLWIDTH SEMICOLON
+FF1C;FF1C;FF1C;003C;003C; # (<; <; <; <; <; ) FULLWIDTH LESS-THAN SIGN
+FF1D;FF1D;FF1D;003D;003D; # (=; =; =; =; =; ) FULLWIDTH EQUALS SIGN
+FF1E;FF1E;FF1E;003E;003E; # (>; >; >; >; >; ) FULLWIDTH GREATER-THAN SIGN
+FF1F;FF1F;FF1F;003F;003F; # (?; ?; ?; ?; ?; ) FULLWIDTH QUESTION MARK
+FF20;FF20;FF20;0040;0040; # (@; @; @; @; @; ) FULLWIDTH COMMERCIAL AT
+FF21;FF21;FF21;0041;0041; # (A; A; A; A; A; ) FULLWIDTH LATIN CAPITAL LETTER A
+FF22;FF22;FF22;0042;0042; # (B; B; B; B; B; ) FULLWIDTH LATIN CAPITAL LETTER B
+FF23;FF23;FF23;0043;0043; # (C; C; C; C; C; ) FULLWIDTH LATIN CAPITAL LETTER C
+FF24;FF24;FF24;0044;0044; # (D; D; D; D; D; ) FULLWIDTH LATIN CAPITAL LETTER D
+FF25;FF25;FF25;0045;0045; # (E; E; E; E; E; ) FULLWIDTH LATIN CAPITAL LETTER E
+FF26;FF26;FF26;0046;0046; # (F; F; F; F; F; ) FULLWIDTH LATIN CAPITAL LETTER F
+FF27;FF27;FF27;0047;0047; # (G; G; G; G; G; ) FULLWIDTH LATIN CAPITAL LETTER G
+FF28;FF28;FF28;0048;0048; # (H; H; H; H; H; ) FULLWIDTH LATIN CAPITAL LETTER H
+FF29;FF29;FF29;0049;0049; # (I; I; I; I; I; ) FULLWIDTH LATIN CAPITAL LETTER I
+FF2A;FF2A;FF2A;004A;004A; # (J; J; J; J; J; ) FULLWIDTH LATIN CAPITAL LETTER J
+FF2B;FF2B;FF2B;004B;004B; # (K; K; K; K; K; ) FULLWIDTH LATIN CAPITAL LETTER K
+FF2C;FF2C;FF2C;004C;004C; # (L; L; L; L; L; ) FULLWIDTH LATIN CAPITAL LETTER L
+FF2D;FF2D;FF2D;004D;004D; # (M; M; M; M; M; ) FULLWIDTH LATIN CAPITAL LETTER M
+FF2E;FF2E;FF2E;004E;004E; # (N; N; N; N; N; ) FULLWIDTH LATIN CAPITAL LETTER N
+FF2F;FF2F;FF2F;004F;004F; # (O; O; O; O; O; ) FULLWIDTH LATIN CAPITAL LETTER O
+FF30;FF30;FF30;0050;0050; # (P; P; P; P; P; ) FULLWIDTH LATIN CAPITAL LETTER P
+FF31;FF31;FF31;0051;0051; # (Q; Q; Q; Q; Q; ) FULLWIDTH LATIN CAPITAL LETTER Q
+FF32;FF32;FF32;0052;0052; # (R; R; R; R; R; ) FULLWIDTH LATIN CAPITAL LETTER R
+FF33;FF33;FF33;0053;0053; # (S; S; S; S; S; ) FULLWIDTH LATIN CAPITAL LETTER S
+FF34;FF34;FF34;0054;0054; # (T; T; T; T; T; ) FULLWIDTH LATIN CAPITAL LETTER T
+FF35;FF35;FF35;0055;0055; # (U; U; U; U; U; ) FULLWIDTH LATIN CAPITAL LETTER U
+FF36;FF36;FF36;0056;0056; # (V; V; V; V; V; ) FULLWIDTH LATIN CAPITAL LETTER V
+FF37;FF37;FF37;0057;0057; # (W; W; W; W; W; ) FULLWIDTH LATIN CAPITAL LETTER W
+FF38;FF38;FF38;0058;0058; # (X; X; X; X; X; ) FULLWIDTH LATIN CAPITAL LETTER X
+FF39;FF39;FF39;0059;0059; # (Y; Y; Y; Y; Y; ) FULLWIDTH LATIN CAPITAL LETTER Y
+FF3A;FF3A;FF3A;005A;005A; # (Z; Z; Z; Z; Z; ) FULLWIDTH LATIN CAPITAL LETTER Z
+FF3B;FF3B;FF3B;005B;005B; # ([; [; [; [; [; ) FULLWIDTH LEFT SQUARE BRACKET
+FF3C;FF3C;FF3C;005C;005C; # (\; \; \; \; \; ) FULLWIDTH REVERSE SOLIDUS
+FF3D;FF3D;FF3D;005D;005D; # (]; ]; ]; ]; ]; ) FULLWIDTH RIGHT SQUARE BRACKET
+FF3E;FF3E;FF3E;005E;005E; # (^; ^; ^; ^; ^; ) FULLWIDTH CIRCUMFLEX ACCENT
+FF3F;FF3F;FF3F;005F;005F; # (_; _; _; _; _; ) FULLWIDTH LOW LINE
+FF40;FF40;FF40;0060;0060; # (`; `; `; `; `; ) FULLWIDTH GRAVE ACCENT
+FF41;FF41;FF41;0061;0061; # (a; a; a; a; a; ) FULLWIDTH LATIN SMALL LETTER A
+FF42;FF42;FF42;0062;0062; # (b; b; b; b; b; ) FULLWIDTH LATIN SMALL LETTER B
+FF43;FF43;FF43;0063;0063; # (c; c; c; c; c; ) FULLWIDTH LATIN SMALL LETTER C
+FF44;FF44;FF44;0064;0064; # (d; d; d; d; d; ) FULLWIDTH LATIN SMALL LETTER D
+FF45;FF45;FF45;0065;0065; # (e; e; e; e; e; ) FULLWIDTH LATIN SMALL LETTER E
+FF46;FF46;FF46;0066;0066; # (f; f; f; f; f; ) FULLWIDTH LATIN SMALL LETTER F
+FF47;FF47;FF47;0067;0067; # (g; g; g; g; g; ) FULLWIDTH LATIN SMALL LETTER G
+FF48;FF48;FF48;0068;0068; # (h; h; h; h; h; ) FULLWIDTH LATIN SMALL LETTER H
+FF49;FF49;FF49;0069;0069; # (i; i; i; i; i; ) FULLWIDTH LATIN SMALL LETTER I
+FF4A;FF4A;FF4A;006A;006A; # (j; j; j; j; j; ) FULLWIDTH LATIN SMALL LETTER J
+FF4B;FF4B;FF4B;006B;006B; # (k; k; k; k; k; ) FULLWIDTH LATIN SMALL LETTER K
+FF4C;FF4C;FF4C;006C;006C; # (l; l; l; l; l; ) FULLWIDTH LATIN SMALL LETTER L
+FF4D;FF4D;FF4D;006D;006D; # (m; m; m; m; m; ) FULLWIDTH LATIN SMALL LETTER M
+FF4E;FF4E;FF4E;006E;006E; # (n; n; n; n; n; ) FULLWIDTH LATIN SMALL LETTER N
+FF4F;FF4F;FF4F;006F;006F; # (o; o; o; o; o; ) FULLWIDTH LATIN SMALL LETTER O
+FF50;FF50;FF50;0070;0070; # (p; p; p; p; p; ) FULLWIDTH LATIN SMALL LETTER P
+FF51;FF51;FF51;0071;0071; # (q; q; q; q; q; ) FULLWIDTH LATIN SMALL LETTER Q
+FF52;FF52;FF52;0072;0072; # (r; r; r; r; r; ) FULLWIDTH LATIN SMALL LETTER R
+FF53;FF53;FF53;0073;0073; # (s; s; s; s; s; ) FULLWIDTH LATIN SMALL LETTER S
+FF54;FF54;FF54;0074;0074; # (t; t; t; t; t; ) FULLWIDTH LATIN SMALL LETTER T
+FF55;FF55;FF55;0075;0075; # (u; u; u; u; u; ) FULLWIDTH LATIN SMALL LETTER U
+FF56;FF56;FF56;0076;0076; # (v; v; v; v; v; ) FULLWIDTH LATIN SMALL LETTER V
+FF57;FF57;FF57;0077;0077; # (w; w; w; w; w; ) FULLWIDTH LATIN SMALL LETTER W
+FF58;FF58;FF58;0078;0078; # (x; x; x; x; x; ) FULLWIDTH LATIN SMALL LETTER X
+FF59;FF59;FF59;0079;0079; # (y; y; y; y; y; ) FULLWIDTH LATIN SMALL LETTER Y
+FF5A;FF5A;FF5A;007A;007A; # (z; z; z; z; z; ) FULLWIDTH LATIN SMALL LETTER Z
+FF5B;FF5B;FF5B;007B;007B; # ({; {; {; {; {; ) FULLWIDTH LEFT CURLY BRACKET
+FF5C;FF5C;FF5C;007C;007C; # (|; |; |; |; |; ) FULLWIDTH VERTICAL LINE
+FF5D;FF5D;FF5D;007D;007D; # (}; }; }; }; }; ) FULLWIDTH RIGHT CURLY BRACKET
+FF5E;FF5E;FF5E;007E;007E; # (~; ~; ~; ~; ~; ) FULLWIDTH TILDE
+FF5F;FF5F;FF5F;2985;2985; # (⦅; ⦅; ⦅; ⦅; ⦅; ) FULLWIDTH LEFT WHITE PARENTHESIS
+FF60;FF60;FF60;2986;2986; # (⦆; ⦆; ⦆; ⦆; ⦆; ) FULLWIDTH RIGHT WHITE PARENTHESIS
+FF61;FF61;FF61;3002;3002; # (。; 。; 。; 。; 。; ) HALFWIDTH IDEOGRAPHIC FULL STOP
+FF62;FF62;FF62;300C;300C; # (「; 「; 「; 「; 「; ) HALFWIDTH LEFT CORNER BRACKET
+FF63;FF63;FF63;300D;300D; # (」; 」; 」; 」; 」; ) HALFWIDTH RIGHT CORNER BRACKET
+FF64;FF64;FF64;3001;3001; # (、; 、; 、; 、; 、; ) HALFWIDTH IDEOGRAPHIC COMMA
+FF65;FF65;FF65;30FB;30FB; # (・; ・; ・; ・; ・; ) HALFWIDTH KATAKANA MIDDLE DOT
+FF66;FF66;FF66;30F2;30F2; # (ヲ; ヲ; ヲ; ヲ; ヲ; ) HALFWIDTH KATAKANA LETTER WO
+FF67;FF67;FF67;30A1;30A1; # (ァ; ァ; ァ; ァ; ァ; ) HALFWIDTH KATAKANA LETTER SMALL A
+FF68;FF68;FF68;30A3;30A3; # (ィ; ィ; ィ; ィ; ィ; ) HALFWIDTH KATAKANA LETTER SMALL I
+FF69;FF69;FF69;30A5;30A5; # (ゥ; ゥ; ゥ; ゥ; ゥ; ) HALFWIDTH KATAKANA LETTER SMALL U
+FF6A;FF6A;FF6A;30A7;30A7; # (ェ; ェ; ェ; ェ; ェ; ) HALFWIDTH KATAKANA LETTER SMALL E
+FF6B;FF6B;FF6B;30A9;30A9; # (ォ; ォ; ォ; ォ; ォ; ) HALFWIDTH KATAKANA LETTER SMALL O
+FF6C;FF6C;FF6C;30E3;30E3; # (ャ; ャ; ャ; ャ; ャ; ) HALFWIDTH KATAKANA LETTER SMALL YA
+FF6D;FF6D;FF6D;30E5;30E5; # (ュ; ュ; ュ; ュ; ュ; ) HALFWIDTH KATAKANA LETTER SMALL YU
+FF6E;FF6E;FF6E;30E7;30E7; # (ョ; ョ; ョ; ョ; ョ; ) HALFWIDTH KATAKANA LETTER SMALL YO
+FF6F;FF6F;FF6F;30C3;30C3; # (ッ; ッ; ッ; ッ; ッ; ) HALFWIDTH KATAKANA LETTER SMALL TU
+FF70;FF70;FF70;30FC;30FC; # (ー; ー; ー; ー; ー; ) HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK
+FF71;FF71;FF71;30A2;30A2; # (ア; ア; ア; ア; ア; ) HALFWIDTH KATAKANA LETTER A
+FF72;FF72;FF72;30A4;30A4; # (イ; イ; イ; イ; イ; ) HALFWIDTH KATAKANA LETTER I
+FF73;FF73;FF73;30A6;30A6; # (ウ; ウ; ウ; ウ; ウ; ) HALFWIDTH KATAKANA LETTER U
+FF74;FF74;FF74;30A8;30A8; # (エ; エ; エ; エ; エ; ) HALFWIDTH KATAKANA LETTER E
+FF75;FF75;FF75;30AA;30AA; # (オ; オ; オ; オ; オ; ) HALFWIDTH KATAKANA LETTER O
+FF76;FF76;FF76;30AB;30AB; # (カ; カ; カ; カ; カ; ) HALFWIDTH KATAKANA LETTER KA
+FF77;FF77;FF77;30AD;30AD; # (キ; キ; キ; キ; キ; ) HALFWIDTH KATAKANA LETTER KI
+FF78;FF78;FF78;30AF;30AF; # (ク; ク; ク; ク; ク; ) HALFWIDTH KATAKANA LETTER KU
+FF79;FF79;FF79;30B1;30B1; # (ケ; ケ; ケ; ケ; ケ; ) HALFWIDTH KATAKANA LETTER KE
+FF7A;FF7A;FF7A;30B3;30B3; # (コ; コ; コ; コ; コ; ) HALFWIDTH KATAKANA LETTER KO
+FF7B;FF7B;FF7B;30B5;30B5; # (サ; サ; サ; サ; サ; ) HALFWIDTH KATAKANA LETTER SA
+FF7C;FF7C;FF7C;30B7;30B7; # (シ; シ; シ; シ; シ; ) HALFWIDTH KATAKANA LETTER SI
+FF7D;FF7D;FF7D;30B9;30B9; # (ス; ス; ス; ス; ス; ) HALFWIDTH KATAKANA LETTER SU
+FF7E;FF7E;FF7E;30BB;30BB; # (セ; セ; セ; セ; セ; ) HALFWIDTH KATAKANA LETTER SE
+FF7F;FF7F;FF7F;30BD;30BD; # (ソ; ソ; ソ; ソ; ソ; ) HALFWIDTH KATAKANA LETTER SO
+FF80;FF80;FF80;30BF;30BF; # (タ; タ; タ; タ; タ; ) HALFWIDTH KATAKANA LETTER TA
+FF81;FF81;FF81;30C1;30C1; # (チ; チ; チ; チ; チ; ) HALFWIDTH KATAKANA LETTER TI
+FF82;FF82;FF82;30C4;30C4; # (ツ; ツ; ツ; ツ; ツ; ) HALFWIDTH KATAKANA LETTER TU
+FF83;FF83;FF83;30C6;30C6; # (テ; テ; テ; テ; テ; ) HALFWIDTH KATAKANA LETTER TE
+FF84;FF84;FF84;30C8;30C8; # (ト; ト; ト; ト; ト; ) HALFWIDTH KATAKANA LETTER TO
+FF85;FF85;FF85;30CA;30CA; # (ナ; ナ; ナ; ナ; ナ; ) HALFWIDTH KATAKANA LETTER NA
+FF86;FF86;FF86;30CB;30CB; # (ニ; ニ; ニ; ニ; ニ; ) HALFWIDTH KATAKANA LETTER NI
+FF87;FF87;FF87;30CC;30CC; # (ヌ; ヌ; ヌ; ヌ; ヌ; ) HALFWIDTH KATAKANA LETTER NU
+FF88;FF88;FF88;30CD;30CD; # (ネ; ネ; ネ; ネ; ネ; ) HALFWIDTH KATAKANA LETTER NE
+FF89;FF89;FF89;30CE;30CE; # (ノ; ノ; ノ; ノ; ノ; ) HALFWIDTH KATAKANA LETTER NO
+FF8A;FF8A;FF8A;30CF;30CF; # (ハ; ハ; ハ; ハ; ハ; ) HALFWIDTH KATAKANA LETTER HA
+FF8B;FF8B;FF8B;30D2;30D2; # (ヒ; ヒ; ヒ; ヒ; ヒ; ) HALFWIDTH KATAKANA LETTER HI
+FF8C;FF8C;FF8C;30D5;30D5; # (フ; フ; フ; フ; フ; ) HALFWIDTH KATAKANA LETTER HU
+FF8D;FF8D;FF8D;30D8;30D8; # (ヘ; ヘ; ヘ; ヘ; ヘ; ) HALFWIDTH KATAKANA LETTER HE
+FF8E;FF8E;FF8E;30DB;30DB; # (ホ; ホ; ホ; ホ; ホ; ) HALFWIDTH KATAKANA LETTER HO
+FF8F;FF8F;FF8F;30DE;30DE; # (マ; マ; マ; マ; マ; ) HALFWIDTH KATAKANA LETTER MA
+FF90;FF90;FF90;30DF;30DF; # (ミ; ミ; ミ; ミ; ミ; ) HALFWIDTH KATAKANA LETTER MI
+FF91;FF91;FF91;30E0;30E0; # (ム; ム; ム; ム; ム; ) HALFWIDTH KATAKANA LETTER MU
+FF92;FF92;FF92;30E1;30E1; # (メ; メ; メ; メ; メ; ) HALFWIDTH KATAKANA LETTER ME
+FF93;FF93;FF93;30E2;30E2; # (モ; モ; モ; モ; モ; ) HALFWIDTH KATAKANA LETTER MO
+FF94;FF94;FF94;30E4;30E4; # (ヤ; ヤ; ヤ; ヤ; ヤ; ) HALFWIDTH KATAKANA LETTER YA
+FF95;FF95;FF95;30E6;30E6; # (ユ; ユ; ユ; ユ; ユ; ) HALFWIDTH KATAKANA LETTER YU
+FF96;FF96;FF96;30E8;30E8; # (ヨ; ヨ; ヨ; ヨ; ヨ; ) HALFWIDTH KATAKANA LETTER YO
+FF97;FF97;FF97;30E9;30E9; # (ラ; ラ; ラ; ラ; ラ; ) HALFWIDTH KATAKANA LETTER RA
+FF98;FF98;FF98;30EA;30EA; # (リ; リ; リ; リ; リ; ) HALFWIDTH KATAKANA LETTER RI
+FF99;FF99;FF99;30EB;30EB; # (ル; ル; ル; ル; ル; ) HALFWIDTH KATAKANA LETTER RU
+FF9A;FF9A;FF9A;30EC;30EC; # (レ; レ; レ; レ; レ; ) HALFWIDTH KATAKANA LETTER RE
+FF9B;FF9B;FF9B;30ED;30ED; # (ロ; ロ; ロ; ロ; ロ; ) HALFWIDTH KATAKANA LETTER RO
+FF9C;FF9C;FF9C;30EF;30EF; # (ワ; ワ; ワ; ワ; ワ; ) HALFWIDTH KATAKANA LETTER WA
+FF9D;FF9D;FF9D;30F3;30F3; # (ン; ン; ン; ン; ン; ) HALFWIDTH KATAKANA LETTER N
+FF9E;FF9E;FF9E;3099;3099; # (゙; ゙; ゙; ◌゙; ◌゙; ) HALFWIDTH KATAKANA VOICED SOUND MARK
+FF9F;FF9F;FF9F;309A;309A; # (゚; ゚; ゚; ◌゚; ◌゚; ) HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK
+FFA0;FFA0;FFA0;1160;1160; # (ᅠ; ᅠ; ᅠ; ᅠ; ᅠ; ) HALFWIDTH HANGUL FILLER
+FFA1;FFA1;FFA1;1100;1100; # (ᄀ; ᄀ; ᄀ; ᄀ; ᄀ; ) HALFWIDTH HANGUL LETTER KIYEOK
+FFA2;FFA2;FFA2;1101;1101; # (ᄁ; ᄁ; ᄁ; ᄁ; ᄁ; ) HALFWIDTH HANGUL LETTER SSANGKIYEOK
+FFA3;FFA3;FFA3;11AA;11AA; # (ᆪ; ᆪ; ᆪ; ᆪ; ᆪ; ) HALFWIDTH HANGUL LETTER KIYEOK-SIOS
+FFA4;FFA4;FFA4;1102;1102; # (ᄂ; ᄂ; ᄂ; ᄂ; ᄂ; ) HALFWIDTH HANGUL LETTER NIEUN
+FFA5;FFA5;FFA5;11AC;11AC; # (ᆬ; ᆬ; ᆬ; ᆬ; ᆬ; ) HALFWIDTH HANGUL LETTER NIEUN-CIEUC
+FFA6;FFA6;FFA6;11AD;11AD; # (ᆭ; ᆭ; ᆭ; ᆭ; ᆭ; ) HALFWIDTH HANGUL LETTER NIEUN-HIEUH
+FFA7;FFA7;FFA7;1103;1103; # (ᄃ; ᄃ; ᄃ; ᄃ; ᄃ; ) HALFWIDTH HANGUL LETTER TIKEUT
+FFA8;FFA8;FFA8;1104;1104; # (ᄄ; ᄄ; ᄄ; ᄄ; ᄄ; ) HALFWIDTH HANGUL LETTER SSANGTIKEUT
+FFA9;FFA9;FFA9;1105;1105; # (ᄅ; ᄅ; ᄅ; ᄅ; ᄅ; ) HALFWIDTH HANGUL LETTER RIEUL
+FFAA;FFAA;FFAA;11B0;11B0; # (ᆰ; ᆰ; ᆰ; ᆰ; ᆰ; ) HALFWIDTH HANGUL LETTER RIEUL-KIYEOK
+FFAB;FFAB;FFAB;11B1;11B1; # (ᆱ; ᆱ; ᆱ; ᆱ; ᆱ; ) HALFWIDTH HANGUL LETTER RIEUL-MIEUM
+FFAC;FFAC;FFAC;11B2;11B2; # (ᆲ; ᆲ; ᆲ; ᆲ; ᆲ; ) HALFWIDTH HANGUL LETTER RIEUL-PIEUP
+FFAD;FFAD;FFAD;11B3;11B3; # (ᆳ; ᆳ; ᆳ; ᆳ; ᆳ; ) HALFWIDTH HANGUL LETTER RIEUL-SIOS
+FFAE;FFAE;FFAE;11B4;11B4; # (ᆴ; ᆴ; ᆴ; ᆴ; ᆴ; ) HALFWIDTH HANGUL LETTER RIEUL-THIEUTH
+FFAF;FFAF;FFAF;11B5;11B5; # (ᆵ; ᆵ; ᆵ; ᆵ; ᆵ; ) HALFWIDTH HANGUL LETTER RIEUL-PHIEUPH
+FFB0;FFB0;FFB0;111A;111A; # (ᄚ; ᄚ; ᄚ; ᄚ; ᄚ; ) HALFWIDTH HANGUL LETTER RIEUL-HIEUH
+FFB1;FFB1;FFB1;1106;1106; # (ᄆ; ᄆ; ᄆ; ᄆ; ᄆ; ) HALFWIDTH HANGUL LETTER MIEUM
+FFB2;FFB2;FFB2;1107;1107; # (ᄇ; ᄇ; ᄇ; ᄇ; ᄇ; ) HALFWIDTH HANGUL LETTER PIEUP
+FFB3;FFB3;FFB3;1108;1108; # (ᄈ; ᄈ; ᄈ; ᄈ; ᄈ; ) HALFWIDTH HANGUL LETTER SSANGPIEUP
+FFB4;FFB4;FFB4;1121;1121; # (ᄡ; ᄡ; ᄡ; ᄡ; ᄡ; ) HALFWIDTH HANGUL LETTER PIEUP-SIOS
+FFB5;FFB5;FFB5;1109;1109; # (ᄉ; ᄉ; ᄉ; ᄉ; ᄉ; ) HALFWIDTH HANGUL LETTER SIOS
+FFB6;FFB6;FFB6;110A;110A; # (ᄊ; ᄊ; ᄊ; ᄊ; ᄊ; ) HALFWIDTH HANGUL LETTER SSANGSIOS
+FFB7;FFB7;FFB7;110B;110B; # (ᄋ; ᄋ; ᄋ; ᄋ; ᄋ; ) HALFWIDTH HANGUL LETTER IEUNG
+FFB8;FFB8;FFB8;110C;110C; # (ᄌ; ᄌ; ᄌ; ᄌ; ᄌ; ) HALFWIDTH HANGUL LETTER CIEUC
+FFB9;FFB9;FFB9;110D;110D; # (ᄍ; ᄍ; ᄍ; ᄍ; ᄍ; ) HALFWIDTH HANGUL LETTER SSANGCIEUC
+FFBA;FFBA;FFBA;110E;110E; # (ᄎ; ᄎ; ᄎ; ᄎ; ᄎ; ) HALFWIDTH HANGUL LETTER CHIEUCH
+FFBB;FFBB;FFBB;110F;110F; # (ᄏ; ᄏ; ᄏ; ᄏ; ᄏ; ) HALFWIDTH HANGUL LETTER KHIEUKH
+FFBC;FFBC;FFBC;1110;1110; # (ᄐ; ᄐ; ᄐ; ᄐ; ᄐ; ) HALFWIDTH HANGUL LETTER THIEUTH
+FFBD;FFBD;FFBD;1111;1111; # (ᄑ; ᄑ; ᄑ; ᄑ; ᄑ; ) HALFWIDTH HANGUL LETTER PHIEUPH
+FFBE;FFBE;FFBE;1112;1112; # (ᄒ; ᄒ; ᄒ; ᄒ; ᄒ; ) HALFWIDTH HANGUL LETTER HIEUH
+FFC2;FFC2;FFC2;1161;1161; # (ᅡ; ᅡ; ᅡ; ᅡ; ᅡ; ) HALFWIDTH HANGUL LETTER A
+FFC3;FFC3;FFC3;1162;1162; # (ᅢ; ᅢ; ᅢ; ᅢ; ᅢ; ) HALFWIDTH HANGUL LETTER AE
+FFC4;FFC4;FFC4;1163;1163; # (ᅣ; ᅣ; ᅣ; ᅣ; ᅣ; ) HALFWIDTH HANGUL LETTER YA
+FFC5;FFC5;FFC5;1164;1164; # (ᅤ; ᅤ; ᅤ; ᅤ; ᅤ; ) HALFWIDTH HANGUL LETTER YAE
+FFC6;FFC6;FFC6;1165;1165; # (ᅥ; ᅥ; ᅥ; ᅥ; ᅥ; ) HALFWIDTH HANGUL LETTER EO
+FFC7;FFC7;FFC7;1166;1166; # (ᅦ; ᅦ; ᅦ; ᅦ; ᅦ; ) HALFWIDTH HANGUL LETTER E
+FFCA;FFCA;FFCA;1167;1167; # (ᅧ; ᅧ; ᅧ; ᅧ; ᅧ; ) HALFWIDTH HANGUL LETTER YEO
+FFCB;FFCB;FFCB;1168;1168; # (ᅨ; ᅨ; ᅨ; ᅨ; ᅨ; ) HALFWIDTH HANGUL LETTER YE
+FFCC;FFCC;FFCC;1169;1169; # (ᅩ; ᅩ; ᅩ; ᅩ; ᅩ; ) HALFWIDTH HANGUL LETTER O
+FFCD;FFCD;FFCD;116A;116A; # (ᅪ; ᅪ; ᅪ; ᅪ; ᅪ; ) HALFWIDTH HANGUL LETTER WA
+FFCE;FFCE;FFCE;116B;116B; # (ᅫ; ᅫ; ᅫ; ᅫ; ᅫ; ) HALFWIDTH HANGUL LETTER WAE
+FFCF;FFCF;FFCF;116C;116C; # (ᅬ; ᅬ; ᅬ; ᅬ; ᅬ; ) HALFWIDTH HANGUL LETTER OE
+FFD2;FFD2;FFD2;116D;116D; # (ᅭ; ᅭ; ᅭ; ᅭ; ᅭ; ) HALFWIDTH HANGUL LETTER YO
+FFD3;FFD3;FFD3;116E;116E; # (ᅮ; ᅮ; ᅮ; ᅮ; ᅮ; ) HALFWIDTH HANGUL LETTER U
+FFD4;FFD4;FFD4;116F;116F; # (ᅯ; ᅯ; ᅯ; ᅯ; ᅯ; ) HALFWIDTH HANGUL LETTER WEO
+FFD5;FFD5;FFD5;1170;1170; # (ᅰ; ᅰ; ᅰ; ᅰ; ᅰ; ) HALFWIDTH HANGUL LETTER WE
+FFD6;FFD6;FFD6;1171;1171; # (ᅱ; ᅱ; ᅱ; ᅱ; ᅱ; ) HALFWIDTH HANGUL LETTER WI
+FFD7;FFD7;FFD7;1172;1172; # (ᅲ; ᅲ; ᅲ; ᅲ; ᅲ; ) HALFWIDTH HANGUL LETTER YU
+FFDA;FFDA;FFDA;1173;1173; # (ᅳ; ᅳ; ᅳ; ᅳ; ᅳ; ) HALFWIDTH HANGUL LETTER EU
+FFDB;FFDB;FFDB;1174;1174; # (ᅴ; ᅴ; ᅴ; ᅴ; ᅴ; ) HALFWIDTH HANGUL LETTER YI
+FFDC;FFDC;FFDC;1175;1175; # (ᅵ; ᅵ; ᅵ; ᅵ; ᅵ; ) HALFWIDTH HANGUL LETTER I
+FFE0;FFE0;FFE0;00A2;00A2; # (¢; ¢; ¢; ¢; ¢; ) FULLWIDTH CENT SIGN
+FFE1;FFE1;FFE1;00A3;00A3; # (£; £; £; £; £; ) FULLWIDTH POUND SIGN
+FFE2;FFE2;FFE2;00AC;00AC; # (¬; ¬; ¬; ¬; ¬; ) FULLWIDTH NOT SIGN
+FFE3;FFE3;FFE3;0020 0304;0020 0304; # ( ̄;  ̄;  ̄; ◌̄; ◌̄; ) FULLWIDTH MACRON
+FFE4;FFE4;FFE4;00A6;00A6; # (¦; ¦; ¦; ¦; ¦; ) FULLWIDTH BROKEN BAR
+FFE5;FFE5;FFE5;00A5;00A5; # (¥; ¥; ¥; ¥; ¥; ) FULLWIDTH YEN SIGN
+FFE6;FFE6;FFE6;20A9;20A9; # (₩; ₩; ₩; ₩; ₩; ) FULLWIDTH WON SIGN
+FFE8;FFE8;FFE8;2502;2502; # (│; │; │; │; │; ) HALFWIDTH FORMS LIGHT VERTICAL
+FFE9;FFE9;FFE9;2190;2190; # (←; ←; ←; ←; ←; ) HALFWIDTH LEFTWARDS ARROW
+FFEA;FFEA;FFEA;2191;2191; # (↑; ↑; ↑; ↑; ↑; ) HALFWIDTH UPWARDS ARROW
+FFEB;FFEB;FFEB;2192;2192; # (→; →; →; →; →; ) HALFWIDTH RIGHTWARDS ARROW
+FFEC;FFEC;FFEC;2193;2193; # (↓; ↓; ↓; ↓; ↓; ) HALFWIDTH DOWNWARDS ARROW
+FFED;FFED;FFED;25A0;25A0; # (■; ■; ■; ■; ■; ) HALFWIDTH BLACK SQUARE
+FFEE;FFEE;FFEE;25CB;25CB; # (○; ○; ○; ○; ○; ) HALFWIDTH WHITE CIRCLE
+1D15E;1D157 1D165;1D157 1D165;1D157 1D165;1D157 1D165; # (𝅗𝅥𝅗𝅥; 𝅗𝅗𝅥𝅥; 𝅗𝅗𝅥𝅥; 𝅗𝅗𝅥𝅥; 𝅗𝅗𝅥𝅥; ) MUSICAL SYMBOL HALF NOTE
+1D15F;1D158 1D165;1D158 1D165;1D158 1D165;1D158 1D165; # (𝅘𝅥𝅘𝅥; 𝅘𝅘𝅥𝅥; 𝅘𝅘𝅥𝅥; 𝅘𝅘𝅥𝅥; 𝅘𝅘𝅥𝅥; ) MUSICAL SYMBOL QUARTER NOTE
+1D160;1D158 1D165 1D16E;1D158 1D165 1D16E;1D158 1D165 1D16E;1D158 1D165 1D16E; # (𝅘𝅥𝅮𝅘𝅥𝅮; 𝅘𝅘𝅥𝅥𝅮𝅮; 𝅘𝅘𝅥𝅥𝅮𝅮; 𝅘𝅘𝅥𝅥𝅮𝅮; 𝅘𝅘𝅥𝅥𝅮𝅮; ) MUSICAL SYMBOL EIGHTH NOTE
+1D161;1D158 1D165 1D16F;1D158 1D165 1D16F;1D158 1D165 1D16F;1D158 1D165 1D16F; # (𝅘𝅥𝅯𝅘𝅥𝅯; 𝅘𝅘𝅥𝅥𝅯𝅯; 𝅘𝅘𝅥𝅥𝅯𝅯; 𝅘𝅘𝅥𝅥𝅯𝅯; 𝅘𝅘𝅥𝅥𝅯𝅯; ) MUSICAL SYMBOL SIXTEENTH NOTE
+1D162;1D158 1D165 1D170;1D158 1D165 1D170;1D158 1D165 1D170;1D158 1D165 1D170; # (𝅘𝅥𝅰𝅘𝅥𝅰; 𝅘𝅘𝅥𝅥𝅰𝅰; 𝅘𝅘𝅥𝅥𝅰𝅰; 𝅘𝅘𝅥𝅥𝅰𝅰; 𝅘𝅘𝅥𝅥𝅰𝅰; ) MUSICAL SYMBOL THIRTY-SECOND NOTE
+1D163;1D158 1D165 1D171;1D158 1D165 1D171;1D158 1D165 1D171;1D158 1D165 1D171; # (𝅘𝅥𝅱𝅘𝅥𝅱; 𝅘𝅘𝅥𝅥𝅱𝅱; 𝅘𝅘𝅥𝅥𝅱𝅱; 𝅘𝅘𝅥𝅥𝅱𝅱; 𝅘𝅘𝅥𝅥𝅱𝅱; ) MUSICAL SYMBOL SIXTY-FOURTH NOTE
+1D164;1D158 1D165 1D172;1D158 1D165 1D172;1D158 1D165 1D172;1D158 1D165 1D172; # (𝅘𝅥𝅲𝅘𝅥𝅲; 𝅘𝅘𝅥𝅥𝅲𝅲; 𝅘𝅘𝅥𝅥𝅲𝅲; 𝅘𝅘𝅥𝅥𝅲𝅲; 𝅘𝅘𝅥𝅥𝅲𝅲; ) MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH NOTE
+1D1BB;1D1B9 1D165;1D1B9 1D165;1D1B9 1D165;1D1B9 1D165; # (𝆹𝅥𝆹𝅥; 𝆹𝆹𝅥𝅥; 𝆹𝆹𝅥𝅥; 𝆹𝆹𝅥𝅥; 𝆹𝆹𝅥𝅥; ) MUSICAL SYMBOL MINIMA
+1D1BC;1D1BA 1D165;1D1BA 1D165;1D1BA 1D165;1D1BA 1D165; # (𝆺𝅥𝆺𝅥; 𝆺𝆺𝅥𝅥; 𝆺𝆺𝅥𝅥; 𝆺𝆺𝅥𝅥; 𝆺𝆺𝅥𝅥; ) MUSICAL SYMBOL MINIMA BLACK
+1D1BD;1D1B9 1D165 1D16E;1D1B9 1D165 1D16E;1D1B9 1D165 1D16E;1D1B9 1D165 1D16E; # (𝆹𝅥𝅮𝆹𝅥𝅮; 𝆹𝆹𝅥𝅥𝅮𝅮; 𝆹𝆹𝅥𝅥𝅮𝅮; 𝆹𝆹𝅥𝅥𝅮𝅮; 𝆹𝆹𝅥𝅥𝅮𝅮; ) MUSICAL SYMBOL SEMIMINIMA WHITE
+1D1BE;1D1BA 1D165 1D16E;1D1BA 1D165 1D16E;1D1BA 1D165 1D16E;1D1BA 1D165 1D16E; # (𝆺𝅥𝅮𝆺𝅥𝅮; 𝆺𝆺𝅥𝅥𝅮𝅮; 𝆺𝆺𝅥𝅥𝅮𝅮; 𝆺𝆺𝅥𝅥𝅮𝅮; 𝆺𝆺𝅥𝅥𝅮𝅮; ) MUSICAL SYMBOL SEMIMINIMA BLACK
+1D1BF;1D1B9 1D165 1D16F;1D1B9 1D165 1D16F;1D1B9 1D165 1D16F;1D1B9 1D165 1D16F; # (𝆹𝅥𝅯𝆹𝅥𝅯; 𝆹𝆹𝅥𝅥𝅯𝅯; 𝆹𝆹𝅥𝅥𝅯𝅯; 𝆹𝆹𝅥𝅥𝅯𝅯; 𝆹𝆹𝅥𝅥𝅯𝅯; ) MUSICAL SYMBOL FUSA WHITE
+1D1C0;1D1BA 1D165 1D16F;1D1BA 1D165 1D16F;1D1BA 1D165 1D16F;1D1BA 1D165 1D16F; # (𝆺𝅥𝅯𝆺𝅥𝅯; 𝆺𝆺𝅥𝅥𝅯𝅯; 𝆺𝆺𝅥𝅥𝅯𝅯; 𝆺𝆺𝅥𝅥𝅯𝅯; 𝆺𝆺𝅥𝅥𝅯𝅯; ) MUSICAL SYMBOL FUSA BLACK
+1D400;1D400;1D400;0041;0041; # (𝐀𝐀; 𝐀𝐀; 𝐀𝐀; A; A; ) MATHEMATICAL BOLD CAPITAL A
+1D401;1D401;1D401;0042;0042; # (𝐁𝐁; 𝐁𝐁; 𝐁𝐁; B; B; ) MATHEMATICAL BOLD CAPITAL B
+1D402;1D402;1D402;0043;0043; # (𝐂𝐂; 𝐂𝐂; 𝐂𝐂; C; C; ) MATHEMATICAL BOLD CAPITAL C
+1D403;1D403;1D403;0044;0044; # (𝐃𝐃; 𝐃𝐃; 𝐃𝐃; D; D; ) MATHEMATICAL BOLD CAPITAL D
+1D404;1D404;1D404;0045;0045; # (𝐄𝐄; 𝐄𝐄; 𝐄𝐄; E; E; ) MATHEMATICAL BOLD CAPITAL E
+1D405;1D405;1D405;0046;0046; # (𝐅𝐅; 𝐅𝐅; 𝐅𝐅; F; F; ) MATHEMATICAL BOLD CAPITAL F
+1D406;1D406;1D406;0047;0047; # (𝐆𝐆; 𝐆𝐆; 𝐆𝐆; G; G; ) MATHEMATICAL BOLD CAPITAL G
+1D407;1D407;1D407;0048;0048; # (𝐇𝐇; 𝐇𝐇; 𝐇𝐇; H; H; ) MATHEMATICAL BOLD CAPITAL H
+1D408;1D408;1D408;0049;0049; # (𝐈𝐈; 𝐈𝐈; 𝐈𝐈; I; I; ) MATHEMATICAL BOLD CAPITAL I
+1D409;1D409;1D409;004A;004A; # (𝐉𝐉; 𝐉𝐉; 𝐉𝐉; J; J; ) MATHEMATICAL BOLD CAPITAL J
+1D40A;1D40A;1D40A;004B;004B; # (𝐊𝐊; 𝐊𝐊; 𝐊𝐊; K; K; ) MATHEMATICAL BOLD CAPITAL K
+1D40B;1D40B;1D40B;004C;004C; # (𝐋𝐋; 𝐋𝐋; 𝐋𝐋; L; L; ) MATHEMATICAL BOLD CAPITAL L
+1D40C;1D40C;1D40C;004D;004D; # (𝐌𝐌; 𝐌𝐌; 𝐌𝐌; M; M; ) MATHEMATICAL BOLD CAPITAL M
+1D40D;1D40D;1D40D;004E;004E; # (𝐍𝐍; 𝐍𝐍; 𝐍𝐍; N; N; ) MATHEMATICAL BOLD CAPITAL N
+1D40E;1D40E;1D40E;004F;004F; # (𝐎𝐎; 𝐎𝐎; 𝐎𝐎; O; O; ) MATHEMATICAL BOLD CAPITAL O
+1D40F;1D40F;1D40F;0050;0050; # (𝐏𝐏; 𝐏𝐏; 𝐏𝐏; P; P; ) MATHEMATICAL BOLD CAPITAL P
+1D410;1D410;1D410;0051;0051; # (𝐐𝐐; 𝐐𝐐; 𝐐𝐐; Q; Q; ) MATHEMATICAL BOLD CAPITAL Q
+1D411;1D411;1D411;0052;0052; # (𝐑𝐑; 𝐑𝐑; 𝐑𝐑; R; R; ) MATHEMATICAL BOLD CAPITAL R
+1D412;1D412;1D412;0053;0053; # (𝐒𝐒; 𝐒𝐒; 𝐒𝐒; S; S; ) MATHEMATICAL BOLD CAPITAL S
+1D413;1D413;1D413;0054;0054; # (𝐓𝐓; 𝐓𝐓; 𝐓𝐓; T; T; ) MATHEMATICAL BOLD CAPITAL T
+1D414;1D414;1D414;0055;0055; # (𝐔𝐔; 𝐔𝐔; 𝐔𝐔; U; U; ) MATHEMATICAL BOLD CAPITAL U
+1D415;1D415;1D415;0056;0056; # (𝐕𝐕; 𝐕𝐕; 𝐕𝐕; V; V; ) MATHEMATICAL BOLD CAPITAL V
+1D416;1D416;1D416;0057;0057; # (𝐖𝐖; 𝐖𝐖; 𝐖𝐖; W; W; ) MATHEMATICAL BOLD CAPITAL W
+1D417;1D417;1D417;0058;0058; # (𝐗𝐗; 𝐗𝐗; 𝐗𝐗; X; X; ) MATHEMATICAL BOLD CAPITAL X
+1D418;1D418;1D418;0059;0059; # (𝐘𝐘; 𝐘𝐘; 𝐘𝐘; Y; Y; ) MATHEMATICAL BOLD CAPITAL Y
+1D419;1D419;1D419;005A;005A; # (𝐙𝐙; 𝐙𝐙; 𝐙𝐙; Z; Z; ) MATHEMATICAL BOLD CAPITAL Z
+1D41A;1D41A;1D41A;0061;0061; # (𝐚𝐚; 𝐚𝐚; 𝐚𝐚; a; a; ) MATHEMATICAL BOLD SMALL A
+1D41B;1D41B;1D41B;0062;0062; # (𝐛𝐛; 𝐛𝐛; 𝐛𝐛; b; b; ) MATHEMATICAL BOLD SMALL B
+1D41C;1D41C;1D41C;0063;0063; # (𝐜𝐜; 𝐜𝐜; 𝐜𝐜; c; c; ) MATHEMATICAL BOLD SMALL C
+1D41D;1D41D;1D41D;0064;0064; # (𝐝𝐝; 𝐝𝐝; 𝐝𝐝; d; d; ) MATHEMATICAL BOLD SMALL D
+1D41E;1D41E;1D41E;0065;0065; # (𝐞𝐞; 𝐞𝐞; 𝐞𝐞; e; e; ) MATHEMATICAL BOLD SMALL E
+1D41F;1D41F;1D41F;0066;0066; # (𝐟𝐟; 𝐟𝐟; 𝐟𝐟; f; f; ) MATHEMATICAL BOLD SMALL F
+1D420;1D420;1D420;0067;0067; # (𝐠𝐠; 𝐠𝐠; 𝐠𝐠; g; g; ) MATHEMATICAL BOLD SMALL G
+1D421;1D421;1D421;0068;0068; # (𝐡𝐡; 𝐡𝐡; 𝐡𝐡; h; h; ) MATHEMATICAL BOLD SMALL H
+1D422;1D422;1D422;0069;0069; # (𝐢𝐢; 𝐢𝐢; 𝐢𝐢; i; i; ) MATHEMATICAL BOLD SMALL I
+1D423;1D423;1D423;006A;006A; # (𝐣𝐣; 𝐣𝐣; 𝐣𝐣; j; j; ) MATHEMATICAL BOLD SMALL J
+1D424;1D424;1D424;006B;006B; # (𝐤𝐤; 𝐤𝐤; 𝐤𝐤; k; k; ) MATHEMATICAL BOLD SMALL K
+1D425;1D425;1D425;006C;006C; # (𝐥𝐥; 𝐥𝐥; 𝐥𝐥; l; l; ) MATHEMATICAL BOLD SMALL L
+1D426;1D426;1D426;006D;006D; # (𝐦𝐦; 𝐦𝐦; 𝐦𝐦; m; m; ) MATHEMATICAL BOLD SMALL M
+1D427;1D427;1D427;006E;006E; # (𝐧𝐧; 𝐧𝐧; 𝐧𝐧; n; n; ) MATHEMATICAL BOLD SMALL N
+1D428;1D428;1D428;006F;006F; # (𝐨𝐨; 𝐨𝐨; 𝐨𝐨; o; o; ) MATHEMATICAL BOLD SMALL O
+1D429;1D429;1D429;0070;0070; # (𝐩𝐩; 𝐩𝐩; 𝐩𝐩; p; p; ) MATHEMATICAL BOLD SMALL P
+1D42A;1D42A;1D42A;0071;0071; # (𝐪𝐪; 𝐪𝐪; 𝐪𝐪; q; q; ) MATHEMATICAL BOLD SMALL Q
+1D42B;1D42B;1D42B;0072;0072; # (𝐫𝐫; 𝐫𝐫; 𝐫𝐫; r; r; ) MATHEMATICAL BOLD SMALL R
+1D42C;1D42C;1D42C;0073;0073; # (𝐬𝐬; 𝐬𝐬; 𝐬𝐬; s; s; ) MATHEMATICAL BOLD SMALL S
+1D42D;1D42D;1D42D;0074;0074; # (𝐭𝐭; 𝐭𝐭; 𝐭𝐭; t; t; ) MATHEMATICAL BOLD SMALL T
+1D42E;1D42E;1D42E;0075;0075; # (𝐮𝐮; 𝐮𝐮; 𝐮𝐮; u; u; ) MATHEMATICAL BOLD SMALL U
+1D42F;1D42F;1D42F;0076;0076; # (𝐯𝐯; 𝐯𝐯; 𝐯𝐯; v; v; ) MATHEMATICAL BOLD SMALL V
+1D430;1D430;1D430;0077;0077; # (𝐰𝐰; 𝐰𝐰; 𝐰𝐰; w; w; ) MATHEMATICAL BOLD SMALL W
+1D431;1D431;1D431;0078;0078; # (𝐱𝐱; 𝐱𝐱; 𝐱𝐱; x; x; ) MATHEMATICAL BOLD SMALL X
+1D432;1D432;1D432;0079;0079; # (𝐲𝐲; 𝐲𝐲; 𝐲𝐲; y; y; ) MATHEMATICAL BOLD SMALL Y
+1D433;1D433;1D433;007A;007A; # (𝐳𝐳; 𝐳𝐳; 𝐳𝐳; z; z; ) MATHEMATICAL BOLD SMALL Z
+1D434;1D434;1D434;0041;0041; # (𝐴𝐴; 𝐴𝐴; 𝐴𝐴; A; A; ) MATHEMATICAL ITALIC CAPITAL A
+1D435;1D435;1D435;0042;0042; # (𝐵𝐵; 𝐵𝐵; 𝐵𝐵; B; B; ) MATHEMATICAL ITALIC CAPITAL B
+1D436;1D436;1D436;0043;0043; # (𝐶𝐶; 𝐶𝐶; 𝐶𝐶; C; C; ) MATHEMATICAL ITALIC CAPITAL C
+1D437;1D437;1D437;0044;0044; # (𝐷𝐷; 𝐷𝐷; 𝐷𝐷; D; D; ) MATHEMATICAL ITALIC CAPITAL D
+1D438;1D438;1D438;0045;0045; # (𝐸𝐸; 𝐸𝐸; 𝐸𝐸; E; E; ) MATHEMATICAL ITALIC CAPITAL E
+1D439;1D439;1D439;0046;0046; # (𝐹𝐹; 𝐹𝐹; 𝐹𝐹; F; F; ) MATHEMATICAL ITALIC CAPITAL F
+1D43A;1D43A;1D43A;0047;0047; # (𝐺𝐺; 𝐺𝐺; 𝐺𝐺; G; G; ) MATHEMATICAL ITALIC CAPITAL G
+1D43B;1D43B;1D43B;0048;0048; # (𝐻𝐻; 𝐻𝐻; 𝐻𝐻; H; H; ) MATHEMATICAL ITALIC CAPITAL H
+1D43C;1D43C;1D43C;0049;0049; # (𝐼𝐼; 𝐼𝐼; 𝐼𝐼; I; I; ) MATHEMATICAL ITALIC CAPITAL I
+1D43D;1D43D;1D43D;004A;004A; # (𝐽𝐽; 𝐽𝐽; 𝐽𝐽; J; J; ) MATHEMATICAL ITALIC CAPITAL J
+1D43E;1D43E;1D43E;004B;004B; # (𝐾𝐾; 𝐾𝐾; 𝐾𝐾; K; K; ) MATHEMATICAL ITALIC CAPITAL K
+1D43F;1D43F;1D43F;004C;004C; # (𝐿𝐿; 𝐿𝐿; 𝐿𝐿; L; L; ) MATHEMATICAL ITALIC CAPITAL L
+1D440;1D440;1D440;004D;004D; # (𝑀𝑀; 𝑀𝑀; 𝑀𝑀; M; M; ) MATHEMATICAL ITALIC CAPITAL M
+1D441;1D441;1D441;004E;004E; # (𝑁𝑁; 𝑁𝑁; 𝑁𝑁; N; N; ) MATHEMATICAL ITALIC CAPITAL N
+1D442;1D442;1D442;004F;004F; # (𝑂𝑂; 𝑂𝑂; 𝑂𝑂; O; O; ) MATHEMATICAL ITALIC CAPITAL O
+1D443;1D443;1D443;0050;0050; # (𝑃𝑃; 𝑃𝑃; 𝑃𝑃; P; P; ) MATHEMATICAL ITALIC CAPITAL P
+1D444;1D444;1D444;0051;0051; # (𝑄𝑄; 𝑄𝑄; 𝑄𝑄; Q; Q; ) MATHEMATICAL ITALIC CAPITAL Q
+1D445;1D445;1D445;0052;0052; # (𝑅𝑅; 𝑅𝑅; 𝑅𝑅; R; R; ) MATHEMATICAL ITALIC CAPITAL R
+1D446;1D446;1D446;0053;0053; # (𝑆𝑆; 𝑆𝑆; 𝑆𝑆; S; S; ) MATHEMATICAL ITALIC CAPITAL S
+1D447;1D447;1D447;0054;0054; # (𝑇𝑇; 𝑇𝑇; 𝑇𝑇; T; T; ) MATHEMATICAL ITALIC CAPITAL T
+1D448;1D448;1D448;0055;0055; # (𝑈𝑈; 𝑈𝑈; 𝑈𝑈; U; U; ) MATHEMATICAL ITALIC CAPITAL U
+1D449;1D449;1D449;0056;0056; # (𝑉𝑉; 𝑉𝑉; 𝑉𝑉; V; V; ) MATHEMATICAL ITALIC CAPITAL V
+1D44A;1D44A;1D44A;0057;0057; # (𝑊𝑊; 𝑊𝑊; 𝑊𝑊; W; W; ) MATHEMATICAL ITALIC CAPITAL W
+1D44B;1D44B;1D44B;0058;0058; # (𝑋𝑋; 𝑋𝑋; 𝑋𝑋; X; X; ) MATHEMATICAL ITALIC CAPITAL X
+1D44C;1D44C;1D44C;0059;0059; # (𝑌𝑌; 𝑌𝑌; 𝑌𝑌; Y; Y; ) MATHEMATICAL ITALIC CAPITAL Y
+1D44D;1D44D;1D44D;005A;005A; # (𝑍𝑍; 𝑍𝑍; 𝑍𝑍; Z; Z; ) MATHEMATICAL ITALIC CAPITAL Z
+1D44E;1D44E;1D44E;0061;0061; # (𝑎𝑎; 𝑎𝑎; 𝑎𝑎; a; a; ) MATHEMATICAL ITALIC SMALL A
+1D44F;1D44F;1D44F;0062;0062; # (𝑏𝑏; 𝑏𝑏; 𝑏𝑏; b; b; ) MATHEMATICAL ITALIC SMALL B
+1D450;1D450;1D450;0063;0063; # (𝑐𝑐; 𝑐𝑐; 𝑐𝑐; c; c; ) MATHEMATICAL ITALIC SMALL C
+1D451;1D451;1D451;0064;0064; # (𝑑𝑑; 𝑑𝑑; 𝑑𝑑; d; d; ) MATHEMATICAL ITALIC SMALL D
+1D452;1D452;1D452;0065;0065; # (𝑒𝑒; 𝑒𝑒; 𝑒𝑒; e; e; ) MATHEMATICAL ITALIC SMALL E
+1D453;1D453;1D453;0066;0066; # (𝑓𝑓; 𝑓𝑓; 𝑓𝑓; f; f; ) MATHEMATICAL ITALIC SMALL F
+1D454;1D454;1D454;0067;0067; # (𝑔𝑔; 𝑔𝑔; 𝑔𝑔; g; g; ) MATHEMATICAL ITALIC SMALL G
+1D456;1D456;1D456;0069;0069; # (𝑖𝑖; 𝑖𝑖; 𝑖𝑖; i; i; ) MATHEMATICAL ITALIC SMALL I
+1D457;1D457;1D457;006A;006A; # (𝑗𝑗; 𝑗𝑗; 𝑗𝑗; j; j; ) MATHEMATICAL ITALIC SMALL J
+1D458;1D458;1D458;006B;006B; # (𝑘𝑘; 𝑘𝑘; 𝑘𝑘; k; k; ) MATHEMATICAL ITALIC SMALL K
+1D459;1D459;1D459;006C;006C; # (𝑙𝑙; 𝑙𝑙; 𝑙𝑙; l; l; ) MATHEMATICAL ITALIC SMALL L
+1D45A;1D45A;1D45A;006D;006D; # (𝑚𝑚; 𝑚𝑚; 𝑚𝑚; m; m; ) MATHEMATICAL ITALIC SMALL M
+1D45B;1D45B;1D45B;006E;006E; # (𝑛𝑛; 𝑛𝑛; 𝑛𝑛; n; n; ) MATHEMATICAL ITALIC SMALL N
+1D45C;1D45C;1D45C;006F;006F; # (𝑜𝑜; 𝑜𝑜; 𝑜𝑜; o; o; ) MATHEMATICAL ITALIC SMALL O
+1D45D;1D45D;1D45D;0070;0070; # (𝑝𝑝; 𝑝𝑝; 𝑝𝑝; p; p; ) MATHEMATICAL ITALIC SMALL P
+1D45E;1D45E;1D45E;0071;0071; # (𝑞𝑞; 𝑞𝑞; 𝑞𝑞; q; q; ) MATHEMATICAL ITALIC SMALL Q
+1D45F;1D45F;1D45F;0072;0072; # (𝑟𝑟; 𝑟𝑟; 𝑟𝑟; r; r; ) MATHEMATICAL ITALIC SMALL R
+1D460;1D460;1D460;0073;0073; # (𝑠𝑠; 𝑠𝑠; 𝑠𝑠; s; s; ) MATHEMATICAL ITALIC SMALL S
+1D461;1D461;1D461;0074;0074; # (𝑡𝑡; 𝑡𝑡; 𝑡𝑡; t; t; ) MATHEMATICAL ITALIC SMALL T
+1D462;1D462;1D462;0075;0075; # (𝑢𝑢; 𝑢𝑢; 𝑢𝑢; u; u; ) MATHEMATICAL ITALIC SMALL U
+1D463;1D463;1D463;0076;0076; # (𝑣𝑣; 𝑣𝑣; 𝑣𝑣; v; v; ) MATHEMATICAL ITALIC SMALL V
+1D464;1D464;1D464;0077;0077; # (𝑤𝑤; 𝑤𝑤; 𝑤𝑤; w; w; ) MATHEMATICAL ITALIC SMALL W
+1D465;1D465;1D465;0078;0078; # (𝑥𝑥; 𝑥𝑥; 𝑥𝑥; x; x; ) MATHEMATICAL ITALIC SMALL X
+1D466;1D466;1D466;0079;0079; # (𝑦𝑦; 𝑦𝑦; 𝑦𝑦; y; y; ) MATHEMATICAL ITALIC SMALL Y
+1D467;1D467;1D467;007A;007A; # (𝑧𝑧; 𝑧𝑧; 𝑧𝑧; z; z; ) MATHEMATICAL ITALIC SMALL Z
+1D468;1D468;1D468;0041;0041; # (𝑨𝑨; 𝑨𝑨; 𝑨𝑨; A; A; ) MATHEMATICAL BOLD ITALIC CAPITAL A
+1D469;1D469;1D469;0042;0042; # (𝑩𝑩; 𝑩𝑩; 𝑩𝑩; B; B; ) MATHEMATICAL BOLD ITALIC CAPITAL B
+1D46A;1D46A;1D46A;0043;0043; # (𝑪𝑪; 𝑪𝑪; 𝑪𝑪; C; C; ) MATHEMATICAL BOLD ITALIC CAPITAL C
+1D46B;1D46B;1D46B;0044;0044; # (𝑫𝑫; 𝑫𝑫; 𝑫𝑫; D; D; ) MATHEMATICAL BOLD ITALIC CAPITAL D
+1D46C;1D46C;1D46C;0045;0045; # (𝑬𝑬; 𝑬𝑬; 𝑬𝑬; E; E; ) MATHEMATICAL BOLD ITALIC CAPITAL E
+1D46D;1D46D;1D46D;0046;0046; # (𝑭𝑭; 𝑭𝑭; 𝑭𝑭; F; F; ) MATHEMATICAL BOLD ITALIC CAPITAL F
+1D46E;1D46E;1D46E;0047;0047; # (𝑮𝑮; 𝑮𝑮; 𝑮𝑮; G; G; ) MATHEMATICAL BOLD ITALIC CAPITAL G
+1D46F;1D46F;1D46F;0048;0048; # (𝑯𝑯; 𝑯𝑯; 𝑯𝑯; H; H; ) MATHEMATICAL BOLD ITALIC CAPITAL H
+1D470;1D470;1D470;0049;0049; # (𝑰𝑰; 𝑰𝑰; 𝑰𝑰; I; I; ) MATHEMATICAL BOLD ITALIC CAPITAL I
+1D471;1D471;1D471;004A;004A; # (𝑱𝑱; 𝑱𝑱; 𝑱𝑱; J; J; ) MATHEMATICAL BOLD ITALIC CAPITAL J
+1D472;1D472;1D472;004B;004B; # (𝑲𝑲; 𝑲𝑲; 𝑲𝑲; K; K; ) MATHEMATICAL BOLD ITALIC CAPITAL K
+1D473;1D473;1D473;004C;004C; # (𝑳𝑳; 𝑳𝑳; 𝑳𝑳; L; L; ) MATHEMATICAL BOLD ITALIC CAPITAL L
+1D474;1D474;1D474;004D;004D; # (𝑴𝑴; 𝑴𝑴; 𝑴𝑴; M; M; ) MATHEMATICAL BOLD ITALIC CAPITAL M
+1D475;1D475;1D475;004E;004E; # (𝑵𝑵; 𝑵𝑵; 𝑵𝑵; N; N; ) MATHEMATICAL BOLD ITALIC CAPITAL N
+1D476;1D476;1D476;004F;004F; # (𝑶𝑶; 𝑶𝑶; 𝑶𝑶; O; O; ) MATHEMATICAL BOLD ITALIC CAPITAL O
+1D477;1D477;1D477;0050;0050; # (𝑷𝑷; 𝑷𝑷; 𝑷𝑷; P; P; ) MATHEMATICAL BOLD ITALIC CAPITAL P
+1D478;1D478;1D478;0051;0051; # (𝑸𝑸; 𝑸𝑸; 𝑸𝑸; Q; Q; ) MATHEMATICAL BOLD ITALIC CAPITAL Q
+1D479;1D479;1D479;0052;0052; # (𝑹𝑹; 𝑹𝑹; 𝑹𝑹; R; R; ) MATHEMATICAL BOLD ITALIC CAPITAL R
+1D47A;1D47A;1D47A;0053;0053; # (𝑺𝑺; 𝑺𝑺; 𝑺𝑺; S; S; ) MATHEMATICAL BOLD ITALIC CAPITAL S
+1D47B;1D47B;1D47B;0054;0054; # (𝑻𝑻; 𝑻𝑻; 𝑻𝑻; T; T; ) MATHEMATICAL BOLD ITALIC CAPITAL T
+1D47C;1D47C;1D47C;0055;0055; # (𝑼𝑼; 𝑼𝑼; 𝑼𝑼; U; U; ) MATHEMATICAL BOLD ITALIC CAPITAL U
+1D47D;1D47D;1D47D;0056;0056; # (𝑽𝑽; 𝑽𝑽; 𝑽𝑽; V; V; ) MATHEMATICAL BOLD ITALIC CAPITAL V
+1D47E;1D47E;1D47E;0057;0057; # (𝑾𝑾; 𝑾𝑾; 𝑾𝑾; W; W; ) MATHEMATICAL BOLD ITALIC CAPITAL W
+1D47F;1D47F;1D47F;0058;0058; # (𝑿𝑿; 𝑿𝑿; 𝑿𝑿; X; X; ) MATHEMATICAL BOLD ITALIC CAPITAL X
+1D480;1D480;1D480;0059;0059; # (𝒀𝒀; 𝒀𝒀; 𝒀𝒀; Y; Y; ) MATHEMATICAL BOLD ITALIC CAPITAL Y
+1D481;1D481;1D481;005A;005A; # (𝒁𝒁; 𝒁𝒁; 𝒁𝒁; Z; Z; ) MATHEMATICAL BOLD ITALIC CAPITAL Z
+1D482;1D482;1D482;0061;0061; # (𝒂𝒂; 𝒂𝒂; 𝒂𝒂; a; a; ) MATHEMATICAL BOLD ITALIC SMALL A
+1D483;1D483;1D483;0062;0062; # (𝒃𝒃; 𝒃𝒃; 𝒃𝒃; b; b; ) MATHEMATICAL BOLD ITALIC SMALL B
+1D484;1D484;1D484;0063;0063; # (𝒄𝒄; 𝒄𝒄; 𝒄𝒄; c; c; ) MATHEMATICAL BOLD ITALIC SMALL C
+1D485;1D485;1D485;0064;0064; # (𝒅𝒅; 𝒅𝒅; 𝒅𝒅; d; d; ) MATHEMATICAL BOLD ITALIC SMALL D
+1D486;1D486;1D486;0065;0065; # (𝒆𝒆; 𝒆𝒆; 𝒆𝒆; e; e; ) MATHEMATICAL BOLD ITALIC SMALL E
+1D487;1D487;1D487;0066;0066; # (𝒇𝒇; 𝒇𝒇; 𝒇𝒇; f; f; ) MATHEMATICAL BOLD ITALIC SMALL F
+1D488;1D488;1D488;0067;0067; # (𝒈𝒈; 𝒈𝒈; 𝒈𝒈; g; g; ) MATHEMATICAL BOLD ITALIC SMALL G
+1D489;1D489;1D489;0068;0068; # (𝒉𝒉; 𝒉𝒉; 𝒉𝒉; h; h; ) MATHEMATICAL BOLD ITALIC SMALL H
+1D48A;1D48A;1D48A;0069;0069; # (𝒊𝒊; 𝒊𝒊; 𝒊𝒊; i; i; ) MATHEMATICAL BOLD ITALIC SMALL I
+1D48B;1D48B;1D48B;006A;006A; # (𝒋𝒋; 𝒋𝒋; 𝒋𝒋; j; j; ) MATHEMATICAL BOLD ITALIC SMALL J
+1D48C;1D48C;1D48C;006B;006B; # (𝒌𝒌; 𝒌𝒌; 𝒌𝒌; k; k; ) MATHEMATICAL BOLD ITALIC SMALL K
+1D48D;1D48D;1D48D;006C;006C; # (𝒍𝒍; 𝒍𝒍; 𝒍𝒍; l; l; ) MATHEMATICAL BOLD ITALIC SMALL L
+1D48E;1D48E;1D48E;006D;006D; # (𝒎𝒎; 𝒎𝒎; 𝒎𝒎; m; m; ) MATHEMATICAL BOLD ITALIC SMALL M
+1D48F;1D48F;1D48F;006E;006E; # (𝒏𝒏; 𝒏𝒏; 𝒏𝒏; n; n; ) MATHEMATICAL BOLD ITALIC SMALL N
+1D490;1D490;1D490;006F;006F; # (𝒐𝒐; 𝒐𝒐; 𝒐𝒐; o; o; ) MATHEMATICAL BOLD ITALIC SMALL O
+1D491;1D491;1D491;0070;0070; # (𝒑𝒑; 𝒑𝒑; 𝒑𝒑; p; p; ) MATHEMATICAL BOLD ITALIC SMALL P
+1D492;1D492;1D492;0071;0071; # (𝒒𝒒; 𝒒𝒒; 𝒒𝒒; q; q; ) MATHEMATICAL BOLD ITALIC SMALL Q
+1D493;1D493;1D493;0072;0072; # (𝒓𝒓; 𝒓𝒓; 𝒓𝒓; r; r; ) MATHEMATICAL BOLD ITALIC SMALL R
+1D494;1D494;1D494;0073;0073; # (𝒔𝒔; 𝒔𝒔; 𝒔𝒔; s; s; ) MATHEMATICAL BOLD ITALIC SMALL S
+1D495;1D495;1D495;0074;0074; # (𝒕𝒕; 𝒕𝒕; 𝒕𝒕; t; t; ) MATHEMATICAL BOLD ITALIC SMALL T
+1D496;1D496;1D496;0075;0075; # (𝒖𝒖; 𝒖𝒖; 𝒖𝒖; u; u; ) MATHEMATICAL BOLD ITALIC SMALL U
+1D497;1D497;1D497;0076;0076; # (𝒗𝒗; 𝒗𝒗; 𝒗𝒗; v; v; ) MATHEMATICAL BOLD ITALIC SMALL V
+1D498;1D498;1D498;0077;0077; # (𝒘𝒘; 𝒘𝒘; 𝒘𝒘; w; w; ) MATHEMATICAL BOLD ITALIC SMALL W
+1D499;1D499;1D499;0078;0078; # (𝒙𝒙; 𝒙𝒙; 𝒙𝒙; x; x; ) MATHEMATICAL BOLD ITALIC SMALL X
+1D49A;1D49A;1D49A;0079;0079; # (𝒚𝒚; 𝒚𝒚; 𝒚𝒚; y; y; ) MATHEMATICAL BOLD ITALIC SMALL Y
+1D49B;1D49B;1D49B;007A;007A; # (𝒛𝒛; 𝒛𝒛; 𝒛𝒛; z; z; ) MATHEMATICAL BOLD ITALIC SMALL Z
+1D49C;1D49C;1D49C;0041;0041; # (𝒜𝒜; 𝒜𝒜; 𝒜𝒜; A; A; ) MATHEMATICAL SCRIPT CAPITAL A
+1D49E;1D49E;1D49E;0043;0043; # (𝒞𝒞; 𝒞𝒞; 𝒞𝒞; C; C; ) MATHEMATICAL SCRIPT CAPITAL C
+1D49F;1D49F;1D49F;0044;0044; # (𝒟𝒟; 𝒟𝒟; 𝒟𝒟; D; D; ) MATHEMATICAL SCRIPT CAPITAL D
+1D4A2;1D4A2;1D4A2;0047;0047; # (𝒢𝒢; 𝒢𝒢; 𝒢𝒢; G; G; ) MATHEMATICAL SCRIPT CAPITAL G
+1D4A5;1D4A5;1D4A5;004A;004A; # (𝒥𝒥; 𝒥𝒥; 𝒥𝒥; J; J; ) MATHEMATICAL SCRIPT CAPITAL J
+1D4A6;1D4A6;1D4A6;004B;004B; # (𝒦𝒦; 𝒦𝒦; 𝒦𝒦; K; K; ) MATHEMATICAL SCRIPT CAPITAL K
+1D4A9;1D4A9;1D4A9;004E;004E; # (𝒩𝒩; 𝒩𝒩; 𝒩𝒩; N; N; ) MATHEMATICAL SCRIPT CAPITAL N
+1D4AA;1D4AA;1D4AA;004F;004F; # (𝒪𝒪; 𝒪𝒪; 𝒪𝒪; O; O; ) MATHEMATICAL SCRIPT CAPITAL O
+1D4AB;1D4AB;1D4AB;0050;0050; # (𝒫𝒫; 𝒫𝒫; 𝒫𝒫; P; P; ) MATHEMATICAL SCRIPT CAPITAL P
+1D4AC;1D4AC;1D4AC;0051;0051; # (𝒬𝒬; 𝒬𝒬; 𝒬𝒬; Q; Q; ) MATHEMATICAL SCRIPT CAPITAL Q
+1D4AE;1D4AE;1D4AE;0053;0053; # (𝒮𝒮; 𝒮𝒮; 𝒮𝒮; S; S; ) MATHEMATICAL SCRIPT CAPITAL S
+1D4AF;1D4AF;1D4AF;0054;0054; # (𝒯𝒯; 𝒯𝒯; 𝒯𝒯; T; T; ) MATHEMATICAL SCRIPT CAPITAL T
+1D4B0;1D4B0;1D4B0;0055;0055; # (𝒰𝒰; 𝒰𝒰; 𝒰𝒰; U; U; ) MATHEMATICAL SCRIPT CAPITAL U
+1D4B1;1D4B1;1D4B1;0056;0056; # (𝒱𝒱; 𝒱𝒱; 𝒱𝒱; V; V; ) MATHEMATICAL SCRIPT CAPITAL V
+1D4B2;1D4B2;1D4B2;0057;0057; # (𝒲𝒲; 𝒲𝒲; 𝒲𝒲; W; W; ) MATHEMATICAL SCRIPT CAPITAL W
+1D4B3;1D4B3;1D4B3;0058;0058; # (𝒳𝒳; 𝒳𝒳; 𝒳𝒳; X; X; ) MATHEMATICAL SCRIPT CAPITAL X
+1D4B4;1D4B4;1D4B4;0059;0059; # (𝒴𝒴; 𝒴𝒴; 𝒴𝒴; Y; Y; ) MATHEMATICAL SCRIPT CAPITAL Y
+1D4B5;1D4B5;1D4B5;005A;005A; # (𝒵𝒵; 𝒵𝒵; 𝒵𝒵; Z; Z; ) MATHEMATICAL SCRIPT CAPITAL Z
+1D4B6;1D4B6;1D4B6;0061;0061; # (𝒶𝒶; 𝒶𝒶; 𝒶𝒶; a; a; ) MATHEMATICAL SCRIPT SMALL A
+1D4B7;1D4B7;1D4B7;0062;0062; # (𝒷𝒷; 𝒷𝒷; 𝒷𝒷; b; b; ) MATHEMATICAL SCRIPT SMALL B
+1D4B8;1D4B8;1D4B8;0063;0063; # (𝒸𝒸; 𝒸𝒸; 𝒸𝒸; c; c; ) MATHEMATICAL SCRIPT SMALL C
+1D4B9;1D4B9;1D4B9;0064;0064; # (𝒹𝒹; 𝒹𝒹; 𝒹𝒹; d; d; ) MATHEMATICAL SCRIPT SMALL D
+1D4BB;1D4BB;1D4BB;0066;0066; # (𝒻𝒻; 𝒻𝒻; 𝒻𝒻; f; f; ) MATHEMATICAL SCRIPT SMALL F
+1D4BD;1D4BD;1D4BD;0068;0068; # (𝒽𝒽; 𝒽𝒽; 𝒽𝒽; h; h; ) MATHEMATICAL SCRIPT SMALL H
+1D4BE;1D4BE;1D4BE;0069;0069; # (𝒾𝒾; 𝒾𝒾; 𝒾𝒾; i; i; ) MATHEMATICAL SCRIPT SMALL I
+1D4BF;1D4BF;1D4BF;006A;006A; # (𝒿𝒿; 𝒿𝒿; 𝒿𝒿; j; j; ) MATHEMATICAL SCRIPT SMALL J
+1D4C0;1D4C0;1D4C0;006B;006B; # (𝓀𝓀; 𝓀𝓀; 𝓀𝓀; k; k; ) MATHEMATICAL SCRIPT SMALL K
+1D4C1;1D4C1;1D4C1;006C;006C; # (𝓁𝓁; 𝓁𝓁; 𝓁𝓁; l; l; ) MATHEMATICAL SCRIPT SMALL L
+1D4C2;1D4C2;1D4C2;006D;006D; # (𝓂𝓂; 𝓂𝓂; 𝓂𝓂; m; m; ) MATHEMATICAL SCRIPT SMALL M
+1D4C3;1D4C3;1D4C3;006E;006E; # (𝓃𝓃; 𝓃𝓃; 𝓃𝓃; n; n; ) MATHEMATICAL SCRIPT SMALL N
+1D4C5;1D4C5;1D4C5;0070;0070; # (𝓅𝓅; 𝓅𝓅; 𝓅𝓅; p; p; ) MATHEMATICAL SCRIPT SMALL P
+1D4C6;1D4C6;1D4C6;0071;0071; # (𝓆𝓆; 𝓆𝓆; 𝓆𝓆; q; q; ) MATHEMATICAL SCRIPT SMALL Q
+1D4C7;1D4C7;1D4C7;0072;0072; # (𝓇𝓇; 𝓇𝓇; 𝓇𝓇; r; r; ) MATHEMATICAL SCRIPT SMALL R
+1D4C8;1D4C8;1D4C8;0073;0073; # (𝓈𝓈; 𝓈𝓈; 𝓈𝓈; s; s; ) MATHEMATICAL SCRIPT SMALL S
+1D4C9;1D4C9;1D4C9;0074;0074; # (𝓉𝓉; 𝓉𝓉; 𝓉𝓉; t; t; ) MATHEMATICAL SCRIPT SMALL T
+1D4CA;1D4CA;1D4CA;0075;0075; # (𝓊𝓊; 𝓊𝓊; 𝓊𝓊; u; u; ) MATHEMATICAL SCRIPT SMALL U
+1D4CB;1D4CB;1D4CB;0076;0076; # (𝓋𝓋; 𝓋𝓋; 𝓋𝓋; v; v; ) MATHEMATICAL SCRIPT SMALL V
+1D4CC;1D4CC;1D4CC;0077;0077; # (𝓌𝓌; 𝓌𝓌; 𝓌𝓌; w; w; ) MATHEMATICAL SCRIPT SMALL W
+1D4CD;1D4CD;1D4CD;0078;0078; # (𝓍𝓍; 𝓍𝓍; 𝓍𝓍; x; x; ) MATHEMATICAL SCRIPT SMALL X
+1D4CE;1D4CE;1D4CE;0079;0079; # (𝓎𝓎; 𝓎𝓎; 𝓎𝓎; y; y; ) MATHEMATICAL SCRIPT SMALL Y
+1D4CF;1D4CF;1D4CF;007A;007A; # (𝓏𝓏; 𝓏𝓏; 𝓏𝓏; z; z; ) MATHEMATICAL SCRIPT SMALL Z
+1D4D0;1D4D0;1D4D0;0041;0041; # (𝓐𝓐; 𝓐𝓐; 𝓐𝓐; A; A; ) MATHEMATICAL BOLD SCRIPT CAPITAL A
+1D4D1;1D4D1;1D4D1;0042;0042; # (𝓑𝓑; 𝓑𝓑; 𝓑𝓑; B; B; ) MATHEMATICAL BOLD SCRIPT CAPITAL B
+1D4D2;1D4D2;1D4D2;0043;0043; # (𝓒𝓒; 𝓒𝓒; 𝓒𝓒; C; C; ) MATHEMATICAL BOLD SCRIPT CAPITAL C
+1D4D3;1D4D3;1D4D3;0044;0044; # (𝓓𝓓; 𝓓𝓓; 𝓓𝓓; D; D; ) MATHEMATICAL BOLD SCRIPT CAPITAL D
+1D4D4;1D4D4;1D4D4;0045;0045; # (𝓔𝓔; 𝓔𝓔; 𝓔𝓔; E; E; ) MATHEMATICAL BOLD SCRIPT CAPITAL E
+1D4D5;1D4D5;1D4D5;0046;0046; # (𝓕𝓕; 𝓕𝓕; 𝓕𝓕; F; F; ) MATHEMATICAL BOLD SCRIPT CAPITAL F
+1D4D6;1D4D6;1D4D6;0047;0047; # (𝓖𝓖; 𝓖𝓖; 𝓖𝓖; G; G; ) MATHEMATICAL BOLD SCRIPT CAPITAL G
+1D4D7;1D4D7;1D4D7;0048;0048; # (𝓗𝓗; 𝓗𝓗; 𝓗𝓗; H; H; ) MATHEMATICAL BOLD SCRIPT CAPITAL H
+1D4D8;1D4D8;1D4D8;0049;0049; # (𝓘𝓘; 𝓘𝓘; 𝓘𝓘; I; I; ) MATHEMATICAL BOLD SCRIPT CAPITAL I
+1D4D9;1D4D9;1D4D9;004A;004A; # (𝓙𝓙; 𝓙𝓙; 𝓙𝓙; J; J; ) MATHEMATICAL BOLD SCRIPT CAPITAL J
+1D4DA;1D4DA;1D4DA;004B;004B; # (𝓚𝓚; 𝓚𝓚; 𝓚𝓚; K; K; ) MATHEMATICAL BOLD SCRIPT CAPITAL K
+1D4DB;1D4DB;1D4DB;004C;004C; # (𝓛𝓛; 𝓛𝓛; 𝓛𝓛; L; L; ) MATHEMATICAL BOLD SCRIPT CAPITAL L
+1D4DC;1D4DC;1D4DC;004D;004D; # (𝓜𝓜; 𝓜𝓜; 𝓜𝓜; M; M; ) MATHEMATICAL BOLD SCRIPT CAPITAL M
+1D4DD;1D4DD;1D4DD;004E;004E; # (𝓝𝓝; 𝓝𝓝; 𝓝𝓝; N; N; ) MATHEMATICAL BOLD SCRIPT CAPITAL N
+1D4DE;1D4DE;1D4DE;004F;004F; # (𝓞𝓞; 𝓞𝓞; 𝓞𝓞; O; O; ) MATHEMATICAL BOLD SCRIPT CAPITAL O
+1D4DF;1D4DF;1D4DF;0050;0050; # (𝓟𝓟; 𝓟𝓟; 𝓟𝓟; P; P; ) MATHEMATICAL BOLD SCRIPT CAPITAL P
+1D4E0;1D4E0;1D4E0;0051;0051; # (𝓠𝓠; 𝓠𝓠; 𝓠𝓠; Q; Q; ) MATHEMATICAL BOLD SCRIPT CAPITAL Q
+1D4E1;1D4E1;1D4E1;0052;0052; # (𝓡𝓡; 𝓡𝓡; 𝓡𝓡; R; R; ) MATHEMATICAL BOLD SCRIPT CAPITAL R
+1D4E2;1D4E2;1D4E2;0053;0053; # (𝓢𝓢; 𝓢𝓢; 𝓢𝓢; S; S; ) MATHEMATICAL BOLD SCRIPT CAPITAL S
+1D4E3;1D4E3;1D4E3;0054;0054; # (𝓣𝓣; 𝓣𝓣; 𝓣𝓣; T; T; ) MATHEMATICAL BOLD SCRIPT CAPITAL T
+1D4E4;1D4E4;1D4E4;0055;0055; # (𝓤𝓤; 𝓤𝓤; 𝓤𝓤; U; U; ) MATHEMATICAL BOLD SCRIPT CAPITAL U
+1D4E5;1D4E5;1D4E5;0056;0056; # (𝓥𝓥; 𝓥𝓥; 𝓥𝓥; V; V; ) MATHEMATICAL BOLD SCRIPT CAPITAL V
+1D4E6;1D4E6;1D4E6;0057;0057; # (𝓦𝓦; 𝓦𝓦; 𝓦𝓦; W; W; ) MATHEMATICAL BOLD SCRIPT CAPITAL W
+1D4E7;1D4E7;1D4E7;0058;0058; # (𝓧𝓧; 𝓧𝓧; 𝓧𝓧; X; X; ) MATHEMATICAL BOLD SCRIPT CAPITAL X
+1D4E8;1D4E8;1D4E8;0059;0059; # (𝓨𝓨; 𝓨𝓨; 𝓨𝓨; Y; Y; ) MATHEMATICAL BOLD SCRIPT CAPITAL Y
+1D4E9;1D4E9;1D4E9;005A;005A; # (𝓩𝓩; 𝓩𝓩; 𝓩𝓩; Z; Z; ) MATHEMATICAL BOLD SCRIPT CAPITAL Z
+1D4EA;1D4EA;1D4EA;0061;0061; # (𝓪𝓪; 𝓪𝓪; 𝓪𝓪; a; a; ) MATHEMATICAL BOLD SCRIPT SMALL A
+1D4EB;1D4EB;1D4EB;0062;0062; # (𝓫𝓫; 𝓫𝓫; 𝓫𝓫; b; b; ) MATHEMATICAL BOLD SCRIPT SMALL B
+1D4EC;1D4EC;1D4EC;0063;0063; # (𝓬𝓬; 𝓬𝓬; 𝓬𝓬; c; c; ) MATHEMATICAL BOLD SCRIPT SMALL C
+1D4ED;1D4ED;1D4ED;0064;0064; # (𝓭𝓭; 𝓭𝓭; 𝓭𝓭; d; d; ) MATHEMATICAL BOLD SCRIPT SMALL D
+1D4EE;1D4EE;1D4EE;0065;0065; # (𝓮𝓮; 𝓮𝓮; 𝓮𝓮; e; e; ) MATHEMATICAL BOLD SCRIPT SMALL E
+1D4EF;1D4EF;1D4EF;0066;0066; # (𝓯𝓯; 𝓯𝓯; 𝓯𝓯; f; f; ) MATHEMATICAL BOLD SCRIPT SMALL F
+1D4F0;1D4F0;1D4F0;0067;0067; # (𝓰𝓰; 𝓰𝓰; 𝓰𝓰; g; g; ) MATHEMATICAL BOLD SCRIPT SMALL G
+1D4F1;1D4F1;1D4F1;0068;0068; # (𝓱𝓱; 𝓱𝓱; 𝓱𝓱; h; h; ) MATHEMATICAL BOLD SCRIPT SMALL H
+1D4F2;1D4F2;1D4F2;0069;0069; # (𝓲𝓲; 𝓲𝓲; 𝓲𝓲; i; i; ) MATHEMATICAL BOLD SCRIPT SMALL I
+1D4F3;1D4F3;1D4F3;006A;006A; # (𝓳𝓳; 𝓳𝓳; 𝓳𝓳; j; j; ) MATHEMATICAL BOLD SCRIPT SMALL J
+1D4F4;1D4F4;1D4F4;006B;006B; # (𝓴𝓴; 𝓴𝓴; 𝓴𝓴; k; k; ) MATHEMATICAL BOLD SCRIPT SMALL K
+1D4F5;1D4F5;1D4F5;006C;006C; # (𝓵𝓵; 𝓵𝓵; 𝓵𝓵; l; l; ) MATHEMATICAL BOLD SCRIPT SMALL L
+1D4F6;1D4F6;1D4F6;006D;006D; # (𝓶𝓶; 𝓶𝓶; 𝓶𝓶; m; m; ) MATHEMATICAL BOLD SCRIPT SMALL M
+1D4F7;1D4F7;1D4F7;006E;006E; # (𝓷𝓷; 𝓷𝓷; 𝓷𝓷; n; n; ) MATHEMATICAL BOLD SCRIPT SMALL N
+1D4F8;1D4F8;1D4F8;006F;006F; # (𝓸𝓸; 𝓸𝓸; 𝓸𝓸; o; o; ) MATHEMATICAL BOLD SCRIPT SMALL O
+1D4F9;1D4F9;1D4F9;0070;0070; # (𝓹𝓹; 𝓹𝓹; 𝓹𝓹; p; p; ) MATHEMATICAL BOLD SCRIPT SMALL P
+1D4FA;1D4FA;1D4FA;0071;0071; # (𝓺𝓺; 𝓺𝓺; 𝓺𝓺; q; q; ) MATHEMATICAL BOLD SCRIPT SMALL Q
+1D4FB;1D4FB;1D4FB;0072;0072; # (𝓻𝓻; 𝓻𝓻; 𝓻𝓻; r; r; ) MATHEMATICAL BOLD SCRIPT SMALL R
+1D4FC;1D4FC;1D4FC;0073;0073; # (𝓼𝓼; 𝓼𝓼; 𝓼𝓼; s; s; ) MATHEMATICAL BOLD SCRIPT SMALL S
+1D4FD;1D4FD;1D4FD;0074;0074; # (𝓽𝓽; 𝓽𝓽; 𝓽𝓽; t; t; ) MATHEMATICAL BOLD SCRIPT SMALL T
+1D4FE;1D4FE;1D4FE;0075;0075; # (𝓾𝓾; 𝓾𝓾; 𝓾𝓾; u; u; ) MATHEMATICAL BOLD SCRIPT SMALL U
+1D4FF;1D4FF;1D4FF;0076;0076; # (𝓿𝓿; 𝓿𝓿; 𝓿𝓿; v; v; ) MATHEMATICAL BOLD SCRIPT SMALL V
+1D500;1D500;1D500;0077;0077; # (𝔀𝔀; 𝔀𝔀; 𝔀𝔀; w; w; ) MATHEMATICAL BOLD SCRIPT SMALL W
+1D501;1D501;1D501;0078;0078; # (𝔁𝔁; 𝔁𝔁; 𝔁𝔁; x; x; ) MATHEMATICAL BOLD SCRIPT SMALL X
+1D502;1D502;1D502;0079;0079; # (𝔂𝔂; 𝔂𝔂; 𝔂𝔂; y; y; ) MATHEMATICAL BOLD SCRIPT SMALL Y
+1D503;1D503;1D503;007A;007A; # (𝔃𝔃; 𝔃𝔃; 𝔃𝔃; z; z; ) MATHEMATICAL BOLD SCRIPT SMALL Z
+1D504;1D504;1D504;0041;0041; # (𝔄𝔄; 𝔄𝔄; 𝔄𝔄; A; A; ) MATHEMATICAL FRAKTUR CAPITAL A
+1D505;1D505;1D505;0042;0042; # (𝔅𝔅; 𝔅𝔅; 𝔅𝔅; B; B; ) MATHEMATICAL FRAKTUR CAPITAL B
+1D507;1D507;1D507;0044;0044; # (𝔇𝔇; 𝔇𝔇; 𝔇𝔇; D; D; ) MATHEMATICAL FRAKTUR CAPITAL D
+1D508;1D508;1D508;0045;0045; # (𝔈𝔈; 𝔈𝔈; 𝔈𝔈; E; E; ) MATHEMATICAL FRAKTUR CAPITAL E
+1D509;1D509;1D509;0046;0046; # (𝔉𝔉; 𝔉𝔉; 𝔉𝔉; F; F; ) MATHEMATICAL FRAKTUR CAPITAL F
+1D50A;1D50A;1D50A;0047;0047; # (𝔊𝔊; 𝔊𝔊; 𝔊𝔊; G; G; ) MATHEMATICAL FRAKTUR CAPITAL G
+1D50D;1D50D;1D50D;004A;004A; # (𝔍𝔍; 𝔍𝔍; 𝔍𝔍; J; J; ) MATHEMATICAL FRAKTUR CAPITAL J
+1D50E;1D50E;1D50E;004B;004B; # (𝔎𝔎; 𝔎𝔎; 𝔎𝔎; K; K; ) MATHEMATICAL FRAKTUR CAPITAL K
+1D50F;1D50F;1D50F;004C;004C; # (𝔏𝔏; 𝔏𝔏; 𝔏𝔏; L; L; ) MATHEMATICAL FRAKTUR CAPITAL L
+1D510;1D510;1D510;004D;004D; # (𝔐𝔐; 𝔐𝔐; 𝔐𝔐; M; M; ) MATHEMATICAL FRAKTUR CAPITAL M
+1D511;1D511;1D511;004E;004E; # (𝔑𝔑; 𝔑𝔑; 𝔑𝔑; N; N; ) MATHEMATICAL FRAKTUR CAPITAL N
+1D512;1D512;1D512;004F;004F; # (𝔒𝔒; 𝔒𝔒; 𝔒𝔒; O; O; ) MATHEMATICAL FRAKTUR CAPITAL O
+1D513;1D513;1D513;0050;0050; # (𝔓𝔓; 𝔓𝔓; 𝔓𝔓; P; P; ) MATHEMATICAL FRAKTUR CAPITAL P
+1D514;1D514;1D514;0051;0051; # (𝔔𝔔; 𝔔𝔔; 𝔔𝔔; Q; Q; ) MATHEMATICAL FRAKTUR CAPITAL Q
+1D516;1D516;1D516;0053;0053; # (𝔖𝔖; 𝔖𝔖; 𝔖𝔖; S; S; ) MATHEMATICAL FRAKTUR CAPITAL S
+1D517;1D517;1D517;0054;0054; # (𝔗𝔗; 𝔗𝔗; 𝔗𝔗; T; T; ) MATHEMATICAL FRAKTUR CAPITAL T
+1D518;1D518;1D518;0055;0055; # (𝔘𝔘; 𝔘𝔘; 𝔘𝔘; U; U; ) MATHEMATICAL FRAKTUR CAPITAL U
+1D519;1D519;1D519;0056;0056; # (𝔙𝔙; 𝔙𝔙; 𝔙𝔙; V; V; ) MATHEMATICAL FRAKTUR CAPITAL V
+1D51A;1D51A;1D51A;0057;0057; # (𝔚𝔚; 𝔚𝔚; 𝔚𝔚; W; W; ) MATHEMATICAL FRAKTUR CAPITAL W
+1D51B;1D51B;1D51B;0058;0058; # (𝔛𝔛; 𝔛𝔛; 𝔛𝔛; X; X; ) MATHEMATICAL FRAKTUR CAPITAL X
+1D51C;1D51C;1D51C;0059;0059; # (𝔜𝔜; 𝔜𝔜; 𝔜𝔜; Y; Y; ) MATHEMATICAL FRAKTUR CAPITAL Y
+1D51E;1D51E;1D51E;0061;0061; # (𝔞𝔞; 𝔞𝔞; 𝔞𝔞; a; a; ) MATHEMATICAL FRAKTUR SMALL A
+1D51F;1D51F;1D51F;0062;0062; # (𝔟𝔟; 𝔟𝔟; 𝔟𝔟; b; b; ) MATHEMATICAL FRAKTUR SMALL B
+1D520;1D520;1D520;0063;0063; # (𝔠𝔠; 𝔠𝔠; 𝔠𝔠; c; c; ) MATHEMATICAL FRAKTUR SMALL C
+1D521;1D521;1D521;0064;0064; # (𝔡𝔡; 𝔡𝔡; 𝔡𝔡; d; d; ) MATHEMATICAL FRAKTUR SMALL D
+1D522;1D522;1D522;0065;0065; # (𝔢𝔢; 𝔢𝔢; 𝔢𝔢; e; e; ) MATHEMATICAL FRAKTUR SMALL E
+1D523;1D523;1D523;0066;0066; # (𝔣𝔣; 𝔣𝔣; 𝔣𝔣; f; f; ) MATHEMATICAL FRAKTUR SMALL F
+1D524;1D524;1D524;0067;0067; # (𝔤𝔤; 𝔤𝔤; 𝔤𝔤; g; g; ) MATHEMATICAL FRAKTUR SMALL G
+1D525;1D525;1D525;0068;0068; # (𝔥𝔥; 𝔥𝔥; 𝔥𝔥; h; h; ) MATHEMATICAL FRAKTUR SMALL H
+1D526;1D526;1D526;0069;0069; # (𝔦𝔦; 𝔦𝔦; 𝔦𝔦; i; i; ) MATHEMATICAL FRAKTUR SMALL I
+1D527;1D527;1D527;006A;006A; # (𝔧𝔧; 𝔧𝔧; 𝔧𝔧; j; j; ) MATHEMATICAL FRAKTUR SMALL J
+1D528;1D528;1D528;006B;006B; # (𝔨𝔨; 𝔨𝔨; 𝔨𝔨; k; k; ) MATHEMATICAL FRAKTUR SMALL K
+1D529;1D529;1D529;006C;006C; # (𝔩𝔩; 𝔩𝔩; 𝔩𝔩; l; l; ) MATHEMATICAL FRAKTUR SMALL L
+1D52A;1D52A;1D52A;006D;006D; # (𝔪𝔪; 𝔪𝔪; 𝔪𝔪; m; m; ) MATHEMATICAL FRAKTUR SMALL M
+1D52B;1D52B;1D52B;006E;006E; # (𝔫𝔫; 𝔫𝔫; 𝔫𝔫; n; n; ) MATHEMATICAL FRAKTUR SMALL N
+1D52C;1D52C;1D52C;006F;006F; # (𝔬𝔬; 𝔬𝔬; 𝔬𝔬; o; o; ) MATHEMATICAL FRAKTUR SMALL O
+1D52D;1D52D;1D52D;0070;0070; # (𝔭𝔭; 𝔭𝔭; 𝔭𝔭; p; p; ) MATHEMATICAL FRAKTUR SMALL P
+1D52E;1D52E;1D52E;0071;0071; # (𝔮𝔮; 𝔮𝔮; 𝔮𝔮; q; q; ) MATHEMATICAL FRAKTUR SMALL Q
+1D52F;1D52F;1D52F;0072;0072; # (𝔯𝔯; 𝔯𝔯; 𝔯𝔯; r; r; ) MATHEMATICAL FRAKTUR SMALL R
+1D530;1D530;1D530;0073;0073; # (𝔰𝔰; 𝔰𝔰; 𝔰𝔰; s; s; ) MATHEMATICAL FRAKTUR SMALL S
+1D531;1D531;1D531;0074;0074; # (𝔱𝔱; 𝔱𝔱; 𝔱𝔱; t; t; ) MATHEMATICAL FRAKTUR SMALL T
+1D532;1D532;1D532;0075;0075; # (𝔲𝔲; 𝔲𝔲; 𝔲𝔲; u; u; ) MATHEMATICAL FRAKTUR SMALL U
+1D533;1D533;1D533;0076;0076; # (𝔳𝔳; 𝔳𝔳; 𝔳𝔳; v; v; ) MATHEMATICAL FRAKTUR SMALL V
+1D534;1D534;1D534;0077;0077; # (𝔴𝔴; 𝔴𝔴; 𝔴𝔴; w; w; ) MATHEMATICAL FRAKTUR SMALL W
+1D535;1D535;1D535;0078;0078; # (𝔵𝔵; 𝔵𝔵; 𝔵𝔵; x; x; ) MATHEMATICAL FRAKTUR SMALL X
+1D536;1D536;1D536;0079;0079; # (𝔶𝔶; 𝔶𝔶; 𝔶𝔶; y; y; ) MATHEMATICAL FRAKTUR SMALL Y
+1D537;1D537;1D537;007A;007A; # (𝔷𝔷; 𝔷𝔷; 𝔷𝔷; z; z; ) MATHEMATICAL FRAKTUR SMALL Z
+1D538;1D538;1D538;0041;0041; # (𝔸𝔸; 𝔸𝔸; 𝔸𝔸; A; A; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL A
+1D539;1D539;1D539;0042;0042; # (𝔹𝔹; 𝔹𝔹; 𝔹𝔹; B; B; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL B
+1D53B;1D53B;1D53B;0044;0044; # (𝔻𝔻; 𝔻𝔻; 𝔻𝔻; D; D; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL D
+1D53C;1D53C;1D53C;0045;0045; # (𝔼𝔼; 𝔼𝔼; 𝔼𝔼; E; E; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL E
+1D53D;1D53D;1D53D;0046;0046; # (𝔽𝔽; 𝔽𝔽; 𝔽𝔽; F; F; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL F
+1D53E;1D53E;1D53E;0047;0047; # (𝔾𝔾; 𝔾𝔾; 𝔾𝔾; G; G; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL G
+1D540;1D540;1D540;0049;0049; # (𝕀𝕀; 𝕀𝕀; 𝕀𝕀; I; I; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL I
+1D541;1D541;1D541;004A;004A; # (𝕁𝕁; 𝕁𝕁; 𝕁𝕁; J; J; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL J
+1D542;1D542;1D542;004B;004B; # (𝕂𝕂; 𝕂𝕂; 𝕂𝕂; K; K; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL K
+1D543;1D543;1D543;004C;004C; # (𝕃𝕃; 𝕃𝕃; 𝕃𝕃; L; L; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL L
+1D544;1D544;1D544;004D;004D; # (𝕄𝕄; 𝕄𝕄; 𝕄𝕄; M; M; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL M
+1D546;1D546;1D546;004F;004F; # (𝕆𝕆; 𝕆𝕆; 𝕆𝕆; O; O; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL O
+1D54A;1D54A;1D54A;0053;0053; # (𝕊𝕊; 𝕊𝕊; 𝕊𝕊; S; S; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL S
+1D54B;1D54B;1D54B;0054;0054; # (𝕋𝕋; 𝕋𝕋; 𝕋𝕋; T; T; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL T
+1D54C;1D54C;1D54C;0055;0055; # (𝕌𝕌; 𝕌𝕌; 𝕌𝕌; U; U; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL U
+1D54D;1D54D;1D54D;0056;0056; # (𝕍𝕍; 𝕍𝕍; 𝕍𝕍; V; V; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL V
+1D54E;1D54E;1D54E;0057;0057; # (𝕎𝕎; 𝕎𝕎; 𝕎𝕎; W; W; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL W
+1D54F;1D54F;1D54F;0058;0058; # (𝕏𝕏; 𝕏𝕏; 𝕏𝕏; X; X; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL X
+1D550;1D550;1D550;0059;0059; # (𝕐𝕐; 𝕐𝕐; 𝕐𝕐; Y; Y; ) MATHEMATICAL DOUBLE-STRUCK CAPITAL Y
+1D552;1D552;1D552;0061;0061; # (𝕒𝕒; 𝕒𝕒; 𝕒𝕒; a; a; ) MATHEMATICAL DOUBLE-STRUCK SMALL A
+1D553;1D553;1D553;0062;0062; # (𝕓𝕓; 𝕓𝕓; 𝕓𝕓; b; b; ) MATHEMATICAL DOUBLE-STRUCK SMALL B
+1D554;1D554;1D554;0063;0063; # (𝕔𝕔; 𝕔𝕔; 𝕔𝕔; c; c; ) MATHEMATICAL DOUBLE-STRUCK SMALL C
+1D555;1D555;1D555;0064;0064; # (𝕕𝕕; 𝕕𝕕; 𝕕𝕕; d; d; ) MATHEMATICAL DOUBLE-STRUCK SMALL D
+1D556;1D556;1D556;0065;0065; # (𝕖𝕖; 𝕖𝕖; 𝕖𝕖; e; e; ) MATHEMATICAL DOUBLE-STRUCK SMALL E
+1D557;1D557;1D557;0066;0066; # (𝕗𝕗; 𝕗𝕗; 𝕗𝕗; f; f; ) MATHEMATICAL DOUBLE-STRUCK SMALL F
+1D558;1D558;1D558;0067;0067; # (𝕘𝕘; 𝕘𝕘; 𝕘𝕘; g; g; ) MATHEMATICAL DOUBLE-STRUCK SMALL G
+1D559;1D559;1D559;0068;0068; # (𝕙𝕙; 𝕙𝕙; 𝕙𝕙; h; h; ) MATHEMATICAL DOUBLE-STRUCK SMALL H
+1D55A;1D55A;1D55A;0069;0069; # (𝕚𝕚; 𝕚𝕚; 𝕚𝕚; i; i; ) MATHEMATICAL DOUBLE-STRUCK SMALL I
+1D55B;1D55B;1D55B;006A;006A; # (𝕛𝕛; 𝕛𝕛; 𝕛𝕛; j; j; ) MATHEMATICAL DOUBLE-STRUCK SMALL J
+1D55C;1D55C;1D55C;006B;006B; # (𝕜𝕜; 𝕜𝕜; 𝕜𝕜; k; k; ) MATHEMATICAL DOUBLE-STRUCK SMALL K
+1D55D;1D55D;1D55D;006C;006C; # (𝕝𝕝; 𝕝𝕝; 𝕝𝕝; l; l; ) MATHEMATICAL DOUBLE-STRUCK SMALL L
+1D55E;1D55E;1D55E;006D;006D; # (𝕞𝕞; 𝕞𝕞; 𝕞𝕞; m; m; ) MATHEMATICAL DOUBLE-STRUCK SMALL M
+1D55F;1D55F;1D55F;006E;006E; # (𝕟𝕟; 𝕟𝕟; 𝕟𝕟; n; n; ) MATHEMATICAL DOUBLE-STRUCK SMALL N
+1D560;1D560;1D560;006F;006F; # (𝕠𝕠; 𝕠𝕠; 𝕠𝕠; o; o; ) MATHEMATICAL DOUBLE-STRUCK SMALL O
+1D561;1D561;1D561;0070;0070; # (𝕡𝕡; 𝕡𝕡; 𝕡𝕡; p; p; ) MATHEMATICAL DOUBLE-STRUCK SMALL P
+1D562;1D562;1D562;0071;0071; # (𝕢𝕢; 𝕢𝕢; 𝕢𝕢; q; q; ) MATHEMATICAL DOUBLE-STRUCK SMALL Q
+1D563;1D563;1D563;0072;0072; # (𝕣𝕣; 𝕣𝕣; 𝕣𝕣; r; r; ) MATHEMATICAL DOUBLE-STRUCK SMALL R
+1D564;1D564;1D564;0073;0073; # (𝕤𝕤; 𝕤𝕤; 𝕤𝕤; s; s; ) MATHEMATICAL DOUBLE-STRUCK SMALL S
+1D565;1D565;1D565;0074;0074; # (𝕥𝕥; 𝕥𝕥; 𝕥𝕥; t; t; ) MATHEMATICAL DOUBLE-STRUCK SMALL T
+1D566;1D566;1D566;0075;0075; # (𝕦𝕦; 𝕦𝕦; 𝕦𝕦; u; u; ) MATHEMATICAL DOUBLE-STRUCK SMALL U
+1D567;1D567;1D567;0076;0076; # (𝕧𝕧; 𝕧𝕧; 𝕧𝕧; v; v; ) MATHEMATICAL DOUBLE-STRUCK SMALL V
+1D568;1D568;1D568;0077;0077; # (𝕨𝕨; 𝕨𝕨; 𝕨𝕨; w; w; ) MATHEMATICAL DOUBLE-STRUCK SMALL W
+1D569;1D569;1D569;0078;0078; # (𝕩𝕩; 𝕩𝕩; 𝕩𝕩; x; x; ) MATHEMATICAL DOUBLE-STRUCK SMALL X
+1D56A;1D56A;1D56A;0079;0079; # (𝕪𝕪; 𝕪𝕪; 𝕪𝕪; y; y; ) MATHEMATICAL DOUBLE-STRUCK SMALL Y
+1D56B;1D56B;1D56B;007A;007A; # (𝕫𝕫; 𝕫𝕫; 𝕫𝕫; z; z; ) MATHEMATICAL DOUBLE-STRUCK SMALL Z
+1D56C;1D56C;1D56C;0041;0041; # (𝕬𝕬; 𝕬𝕬; 𝕬𝕬; A; A; ) MATHEMATICAL BOLD FRAKTUR CAPITAL A
+1D56D;1D56D;1D56D;0042;0042; # (𝕭𝕭; 𝕭𝕭; 𝕭𝕭; B; B; ) MATHEMATICAL BOLD FRAKTUR CAPITAL B
+1D56E;1D56E;1D56E;0043;0043; # (𝕮𝕮; 𝕮𝕮; 𝕮𝕮; C; C; ) MATHEMATICAL BOLD FRAKTUR CAPITAL C
+1D56F;1D56F;1D56F;0044;0044; # (𝕯𝕯; 𝕯𝕯; 𝕯𝕯; D; D; ) MATHEMATICAL BOLD FRAKTUR CAPITAL D
+1D570;1D570;1D570;0045;0045; # (𝕰𝕰; 𝕰𝕰; 𝕰𝕰; E; E; ) MATHEMATICAL BOLD FRAKTUR CAPITAL E
+1D571;1D571;1D571;0046;0046; # (𝕱𝕱; 𝕱𝕱; 𝕱𝕱; F; F; ) MATHEMATICAL BOLD FRAKTUR CAPITAL F
+1D572;1D572;1D572;0047;0047; # (𝕲𝕲; 𝕲𝕲; 𝕲𝕲; G; G; ) MATHEMATICAL BOLD FRAKTUR CAPITAL G
+1D573;1D573;1D573;0048;0048; # (𝕳𝕳; 𝕳𝕳; 𝕳𝕳; H; H; ) MATHEMATICAL BOLD FRAKTUR CAPITAL H
+1D574;1D574;1D574;0049;0049; # (𝕴𝕴; 𝕴𝕴; 𝕴𝕴; I; I; ) MATHEMATICAL BOLD FRAKTUR CAPITAL I
+1D575;1D575;1D575;004A;004A; # (𝕵𝕵; 𝕵𝕵; 𝕵𝕵; J; J; ) MATHEMATICAL BOLD FRAKTUR CAPITAL J
+1D576;1D576;1D576;004B;004B; # (𝕶𝕶; 𝕶𝕶; 𝕶𝕶; K; K; ) MATHEMATICAL BOLD FRAKTUR CAPITAL K
+1D577;1D577;1D577;004C;004C; # (𝕷𝕷; 𝕷𝕷; 𝕷𝕷; L; L; ) MATHEMATICAL BOLD FRAKTUR CAPITAL L
+1D578;1D578;1D578;004D;004D; # (𝕸𝕸; 𝕸𝕸; 𝕸𝕸; M; M; ) MATHEMATICAL BOLD FRAKTUR CAPITAL M
+1D579;1D579;1D579;004E;004E; # (𝕹𝕹; 𝕹𝕹; 𝕹𝕹; N; N; ) MATHEMATICAL BOLD FRAKTUR CAPITAL N
+1D57A;1D57A;1D57A;004F;004F; # (𝕺𝕺; 𝕺𝕺; 𝕺𝕺; O; O; ) MATHEMATICAL BOLD FRAKTUR CAPITAL O
+1D57B;1D57B;1D57B;0050;0050; # (𝕻𝕻; 𝕻𝕻; 𝕻𝕻; P; P; ) MATHEMATICAL BOLD FRAKTUR CAPITAL P
+1D57C;1D57C;1D57C;0051;0051; # (𝕼𝕼; 𝕼𝕼; 𝕼𝕼; Q; Q; ) MATHEMATICAL BOLD FRAKTUR CAPITAL Q
+1D57D;1D57D;1D57D;0052;0052; # (𝕽𝕽; 𝕽𝕽; 𝕽𝕽; R; R; ) MATHEMATICAL BOLD FRAKTUR CAPITAL R
+1D57E;1D57E;1D57E;0053;0053; # (𝕾𝕾; 𝕾𝕾; 𝕾𝕾; S; S; ) MATHEMATICAL BOLD FRAKTUR CAPITAL S
+1D57F;1D57F;1D57F;0054;0054; # (𝕿𝕿; 𝕿𝕿; 𝕿𝕿; T; T; ) MATHEMATICAL BOLD FRAKTUR CAPITAL T
+1D580;1D580;1D580;0055;0055; # (𝖀𝖀; 𝖀𝖀; 𝖀𝖀; U; U; ) MATHEMATICAL BOLD FRAKTUR CAPITAL U
+1D581;1D581;1D581;0056;0056; # (𝖁𝖁; 𝖁𝖁; 𝖁𝖁; V; V; ) MATHEMATICAL BOLD FRAKTUR CAPITAL V
+1D582;1D582;1D582;0057;0057; # (𝖂𝖂; 𝖂𝖂; 𝖂𝖂; W; W; ) MATHEMATICAL BOLD FRAKTUR CAPITAL W
+1D583;1D583;1D583;0058;0058; # (𝖃𝖃; 𝖃𝖃; 𝖃𝖃; X; X; ) MATHEMATICAL BOLD FRAKTUR CAPITAL X
+1D584;1D584;1D584;0059;0059; # (𝖄𝖄; 𝖄𝖄; 𝖄𝖄; Y; Y; ) MATHEMATICAL BOLD FRAKTUR CAPITAL Y
+1D585;1D585;1D585;005A;005A; # (𝖅𝖅; 𝖅𝖅; 𝖅𝖅; Z; Z; ) MATHEMATICAL BOLD FRAKTUR CAPITAL Z
+1D586;1D586;1D586;0061;0061; # (𝖆𝖆; 𝖆𝖆; 𝖆𝖆; a; a; ) MATHEMATICAL BOLD FRAKTUR SMALL A
+1D587;1D587;1D587;0062;0062; # (𝖇𝖇; 𝖇𝖇; 𝖇𝖇; b; b; ) MATHEMATICAL BOLD FRAKTUR SMALL B
+1D588;1D588;1D588;0063;0063; # (𝖈𝖈; 𝖈𝖈; 𝖈𝖈; c; c; ) MATHEMATICAL BOLD FRAKTUR SMALL C
+1D589;1D589;1D589;0064;0064; # (𝖉𝖉; 𝖉𝖉; 𝖉𝖉; d; d; ) MATHEMATICAL BOLD FRAKTUR SMALL D
+1D58A;1D58A;1D58A;0065;0065; # (𝖊𝖊; 𝖊𝖊; 𝖊𝖊; e; e; ) MATHEMATICAL BOLD FRAKTUR SMALL E
+1D58B;1D58B;1D58B;0066;0066; # (𝖋𝖋; 𝖋𝖋; 𝖋𝖋; f; f; ) MATHEMATICAL BOLD FRAKTUR SMALL F
+1D58C;1D58C;1D58C;0067;0067; # (𝖌𝖌; 𝖌𝖌; 𝖌𝖌; g; g; ) MATHEMATICAL BOLD FRAKTUR SMALL G
+1D58D;1D58D;1D58D;0068;0068; # (𝖍𝖍; 𝖍𝖍; 𝖍𝖍; h; h; ) MATHEMATICAL BOLD FRAKTUR SMALL H
+1D58E;1D58E;1D58E;0069;0069; # (𝖎𝖎; 𝖎𝖎; 𝖎𝖎; i; i; ) MATHEMATICAL BOLD FRAKTUR SMALL I
+1D58F;1D58F;1D58F;006A;006A; # (𝖏𝖏; 𝖏𝖏; 𝖏𝖏; j; j; ) MATHEMATICAL BOLD FRAKTUR SMALL J
+1D590;1D590;1D590;006B;006B; # (𝖐𝖐; 𝖐𝖐; 𝖐𝖐; k; k; ) MATHEMATICAL BOLD FRAKTUR SMALL K
+1D591;1D591;1D591;006C;006C; # (𝖑𝖑; 𝖑𝖑; 𝖑𝖑; l; l; ) MATHEMATICAL BOLD FRAKTUR SMALL L
+1D592;1D592;1D592;006D;006D; # (𝖒𝖒; 𝖒𝖒; 𝖒𝖒; m; m; ) MATHEMATICAL BOLD FRAKTUR SMALL M
+1D593;1D593;1D593;006E;006E; # (𝖓𝖓; 𝖓𝖓; 𝖓𝖓; n; n; ) MATHEMATICAL BOLD FRAKTUR SMALL N
+1D594;1D594;1D594;006F;006F; # (𝖔𝖔; 𝖔𝖔; 𝖔𝖔; o; o; ) MATHEMATICAL BOLD FRAKTUR SMALL O
+1D595;1D595;1D595;0070;0070; # (𝖕𝖕; 𝖕𝖕; 𝖕𝖕; p; p; ) MATHEMATICAL BOLD FRAKTUR SMALL P
+1D596;1D596;1D596;0071;0071; # (𝖖𝖖; 𝖖𝖖; 𝖖𝖖; q; q; ) MATHEMATICAL BOLD FRAKTUR SMALL Q
+1D597;1D597;1D597;0072;0072; # (𝖗𝖗; 𝖗𝖗; 𝖗𝖗; r; r; ) MATHEMATICAL BOLD FRAKTUR SMALL R
+1D598;1D598;1D598;0073;0073; # (𝖘𝖘; 𝖘𝖘; 𝖘𝖘; s; s; ) MATHEMATICAL BOLD FRAKTUR SMALL S
+1D599;1D599;1D599;0074;0074; # (𝖙𝖙; 𝖙𝖙; 𝖙𝖙; t; t; ) MATHEMATICAL BOLD FRAKTUR SMALL T
+1D59A;1D59A;1D59A;0075;0075; # (𝖚𝖚; 𝖚𝖚; 𝖚𝖚; u; u; ) MATHEMATICAL BOLD FRAKTUR SMALL U
+1D59B;1D59B;1D59B;0076;0076; # (𝖛𝖛; 𝖛𝖛; 𝖛𝖛; v; v; ) MATHEMATICAL BOLD FRAKTUR SMALL V
+1D59C;1D59C;1D59C;0077;0077; # (𝖜𝖜; 𝖜𝖜; 𝖜𝖜; w; w; ) MATHEMATICAL BOLD FRAKTUR SMALL W
+1D59D;1D59D;1D59D;0078;0078; # (𝖝𝖝; 𝖝𝖝; 𝖝𝖝; x; x; ) MATHEMATICAL BOLD FRAKTUR SMALL X
+1D59E;1D59E;1D59E;0079;0079; # (𝖞𝖞; 𝖞𝖞; 𝖞𝖞; y; y; ) MATHEMATICAL BOLD FRAKTUR SMALL Y
+1D59F;1D59F;1D59F;007A;007A; # (𝖟𝖟; 𝖟𝖟; 𝖟𝖟; z; z; ) MATHEMATICAL BOLD FRAKTUR SMALL Z
+1D5A0;1D5A0;1D5A0;0041;0041; # (𝖠𝖠; 𝖠𝖠; 𝖠𝖠; A; A; ) MATHEMATICAL SANS-SERIF CAPITAL A
+1D5A1;1D5A1;1D5A1;0042;0042; # (𝖡𝖡; 𝖡𝖡; 𝖡𝖡; B; B; ) MATHEMATICAL SANS-SERIF CAPITAL B
+1D5A2;1D5A2;1D5A2;0043;0043; # (𝖢𝖢; 𝖢𝖢; 𝖢𝖢; C; C; ) MATHEMATICAL SANS-SERIF CAPITAL C
+1D5A3;1D5A3;1D5A3;0044;0044; # (𝖣𝖣; 𝖣𝖣; 𝖣𝖣; D; D; ) MATHEMATICAL SANS-SERIF CAPITAL D
+1D5A4;1D5A4;1D5A4;0045;0045; # (𝖤𝖤; 𝖤𝖤; 𝖤𝖤; E; E; ) MATHEMATICAL SANS-SERIF CAPITAL E
+1D5A5;1D5A5;1D5A5;0046;0046; # (𝖥𝖥; 𝖥𝖥; 𝖥𝖥; F; F; ) MATHEMATICAL SANS-SERIF CAPITAL F
+1D5A6;1D5A6;1D5A6;0047;0047; # (𝖦𝖦; 𝖦𝖦; 𝖦𝖦; G; G; ) MATHEMATICAL SANS-SERIF CAPITAL G
+1D5A7;1D5A7;1D5A7;0048;0048; # (𝖧𝖧; 𝖧𝖧; 𝖧𝖧; H; H; ) MATHEMATICAL SANS-SERIF CAPITAL H
+1D5A8;1D5A8;1D5A8;0049;0049; # (𝖨𝖨; 𝖨𝖨; 𝖨𝖨; I; I; ) MATHEMATICAL SANS-SERIF CAPITAL I
+1D5A9;1D5A9;1D5A9;004A;004A; # (𝖩𝖩; 𝖩𝖩; 𝖩𝖩; J; J; ) MATHEMATICAL SANS-SERIF CAPITAL J
+1D5AA;1D5AA;1D5AA;004B;004B; # (𝖪𝖪; 𝖪𝖪; 𝖪𝖪; K; K; ) MATHEMATICAL SANS-SERIF CAPITAL K
+1D5AB;1D5AB;1D5AB;004C;004C; # (𝖫𝖫; 𝖫𝖫; 𝖫𝖫; L; L; ) MATHEMATICAL SANS-SERIF CAPITAL L
+1D5AC;1D5AC;1D5AC;004D;004D; # (𝖬𝖬; 𝖬𝖬; 𝖬𝖬; M; M; ) MATHEMATICAL SANS-SERIF CAPITAL M
+1D5AD;1D5AD;1D5AD;004E;004E; # (𝖭𝖭; 𝖭𝖭; 𝖭𝖭; N; N; ) MATHEMATICAL SANS-SERIF CAPITAL N
+1D5AE;1D5AE;1D5AE;004F;004F; # (𝖮𝖮; 𝖮𝖮; 𝖮𝖮; O; O; ) MATHEMATICAL SANS-SERIF CAPITAL O
+1D5AF;1D5AF;1D5AF;0050;0050; # (𝖯𝖯; 𝖯𝖯; 𝖯𝖯; P; P; ) MATHEMATICAL SANS-SERIF CAPITAL P
+1D5B0;1D5B0;1D5B0;0051;0051; # (𝖰𝖰; 𝖰𝖰; 𝖰𝖰; Q; Q; ) MATHEMATICAL SANS-SERIF CAPITAL Q
+1D5B1;1D5B1;1D5B1;0052;0052; # (𝖱𝖱; 𝖱𝖱; 𝖱𝖱; R; R; ) MATHEMATICAL SANS-SERIF CAPITAL R
+1D5B2;1D5B2;1D5B2;0053;0053; # (𝖲𝖲; 𝖲𝖲; 𝖲𝖲; S; S; ) MATHEMATICAL SANS-SERIF CAPITAL S
+1D5B3;1D5B3;1D5B3;0054;0054; # (𝖳𝖳; 𝖳𝖳; 𝖳𝖳; T; T; ) MATHEMATICAL SANS-SERIF CAPITAL T
+1D5B4;1D5B4;1D5B4;0055;0055; # (𝖴𝖴; 𝖴𝖴; 𝖴𝖴; U; U; ) MATHEMATICAL SANS-SERIF CAPITAL U
+1D5B5;1D5B5;1D5B5;0056;0056; # (𝖵𝖵; 𝖵𝖵; 𝖵𝖵; V; V; ) MATHEMATICAL SANS-SERIF CAPITAL V
+1D5B6;1D5B6;1D5B6;0057;0057; # (𝖶𝖶; 𝖶𝖶; 𝖶𝖶; W; W; ) MATHEMATICAL SANS-SERIF CAPITAL W
+1D5B7;1D5B7;1D5B7;0058;0058; # (𝖷𝖷; 𝖷𝖷; 𝖷𝖷; X; X; ) MATHEMATICAL SANS-SERIF CAPITAL X
+1D5B8;1D5B8;1D5B8;0059;0059; # (𝖸𝖸; 𝖸𝖸; 𝖸𝖸; Y; Y; ) MATHEMATICAL SANS-SERIF CAPITAL Y
+1D5B9;1D5B9;1D5B9;005A;005A; # (𝖹𝖹; 𝖹𝖹; 𝖹𝖹; Z; Z; ) MATHEMATICAL SANS-SERIF CAPITAL Z
+1D5BA;1D5BA;1D5BA;0061;0061; # (𝖺𝖺; 𝖺𝖺; 𝖺𝖺; a; a; ) MATHEMATICAL SANS-SERIF SMALL A
+1D5BB;1D5BB;1D5BB;0062;0062; # (𝖻𝖻; 𝖻𝖻; 𝖻𝖻; b; b; ) MATHEMATICAL SANS-SERIF SMALL B
+1D5BC;1D5BC;1D5BC;0063;0063; # (𝖼𝖼; 𝖼𝖼; 𝖼𝖼; c; c; ) MATHEMATICAL SANS-SERIF SMALL C
+1D5BD;1D5BD;1D5BD;0064;0064; # (𝖽𝖽; 𝖽𝖽; 𝖽𝖽; d; d; ) MATHEMATICAL SANS-SERIF SMALL D
+1D5BE;1D5BE;1D5BE;0065;0065; # (𝖾𝖾; 𝖾𝖾; 𝖾𝖾; e; e; ) MATHEMATICAL SANS-SERIF SMALL E
+1D5BF;1D5BF;1D5BF;0066;0066; # (𝖿𝖿; 𝖿𝖿; 𝖿𝖿; f; f; ) MATHEMATICAL SANS-SERIF SMALL F
+1D5C0;1D5C0;1D5C0;0067;0067; # (𝗀𝗀; 𝗀𝗀; 𝗀𝗀; g; g; ) MATHEMATICAL SANS-SERIF SMALL G
+1D5C1;1D5C1;1D5C1;0068;0068; # (𝗁𝗁; 𝗁𝗁; 𝗁𝗁; h; h; ) MATHEMATICAL SANS-SERIF SMALL H
+1D5C2;1D5C2;1D5C2;0069;0069; # (𝗂𝗂; 𝗂𝗂; 𝗂𝗂; i; i; ) MATHEMATICAL SANS-SERIF SMALL I
+1D5C3;1D5C3;1D5C3;006A;006A; # (𝗃𝗃; 𝗃𝗃; 𝗃𝗃; j; j; ) MATHEMATICAL SANS-SERIF SMALL J
+1D5C4;1D5C4;1D5C4;006B;006B; # (𝗄𝗄; 𝗄𝗄; 𝗄𝗄; k; k; ) MATHEMATICAL SANS-SERIF SMALL K
+1D5C5;1D5C5;1D5C5;006C;006C; # (𝗅𝗅; 𝗅𝗅; 𝗅𝗅; l; l; ) MATHEMATICAL SANS-SERIF SMALL L
+1D5C6;1D5C6;1D5C6;006D;006D; # (𝗆𝗆; 𝗆𝗆; 𝗆𝗆; m; m; ) MATHEMATICAL SANS-SERIF SMALL M
+1D5C7;1D5C7;1D5C7;006E;006E; # (𝗇𝗇; 𝗇𝗇; 𝗇𝗇; n; n; ) MATHEMATICAL SANS-SERIF SMALL N
+1D5C8;1D5C8;1D5C8;006F;006F; # (𝗈𝗈; 𝗈𝗈; 𝗈𝗈; o; o; ) MATHEMATICAL SANS-SERIF SMALL O
+1D5C9;1D5C9;1D5C9;0070;0070; # (𝗉𝗉; 𝗉𝗉; 𝗉𝗉; p; p; ) MATHEMATICAL SANS-SERIF SMALL P
+1D5CA;1D5CA;1D5CA;0071;0071; # (𝗊𝗊; 𝗊𝗊; 𝗊𝗊; q; q; ) MATHEMATICAL SANS-SERIF SMALL Q
+1D5CB;1D5CB;1D5CB;0072;0072; # (𝗋𝗋; 𝗋𝗋; 𝗋𝗋; r; r; ) MATHEMATICAL SANS-SERIF SMALL R
+1D5CC;1D5CC;1D5CC;0073;0073; # (𝗌𝗌; 𝗌𝗌; 𝗌𝗌; s; s; ) MATHEMATICAL SANS-SERIF SMALL S
+1D5CD;1D5CD;1D5CD;0074;0074; # (𝗍𝗍; 𝗍𝗍; 𝗍𝗍; t; t; ) MATHEMATICAL SANS-SERIF SMALL T
+1D5CE;1D5CE;1D5CE;0075;0075; # (𝗎𝗎; 𝗎𝗎; 𝗎𝗎; u; u; ) MATHEMATICAL SANS-SERIF SMALL U
+1D5CF;1D5CF;1D5CF;0076;0076; # (𝗏𝗏; 𝗏𝗏; 𝗏𝗏; v; v; ) MATHEMATICAL SANS-SERIF SMALL V
+1D5D0;1D5D0;1D5D0;0077;0077; # (𝗐𝗐; 𝗐𝗐; 𝗐𝗐; w; w; ) MATHEMATICAL SANS-SERIF SMALL W
+1D5D1;1D5D1;1D5D1;0078;0078; # (𝗑𝗑; 𝗑𝗑; 𝗑𝗑; x; x; ) MATHEMATICAL SANS-SERIF SMALL X
+1D5D2;1D5D2;1D5D2;0079;0079; # (𝗒𝗒; 𝗒𝗒; 𝗒𝗒; y; y; ) MATHEMATICAL SANS-SERIF SMALL Y
+1D5D3;1D5D3;1D5D3;007A;007A; # (𝗓𝗓; 𝗓𝗓; 𝗓𝗓; z; z; ) MATHEMATICAL SANS-SERIF SMALL Z
+1D5D4;1D5D4;1D5D4;0041;0041; # (𝗔𝗔; 𝗔𝗔; 𝗔𝗔; A; A; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL A
+1D5D5;1D5D5;1D5D5;0042;0042; # (𝗕𝗕; 𝗕𝗕; 𝗕𝗕; B; B; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL B
+1D5D6;1D5D6;1D5D6;0043;0043; # (𝗖𝗖; 𝗖𝗖; 𝗖𝗖; C; C; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL C
+1D5D7;1D5D7;1D5D7;0044;0044; # (𝗗𝗗; 𝗗𝗗; 𝗗𝗗; D; D; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL D
+1D5D8;1D5D8;1D5D8;0045;0045; # (𝗘𝗘; 𝗘𝗘; 𝗘𝗘; E; E; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL E
+1D5D9;1D5D9;1D5D9;0046;0046; # (𝗙𝗙; 𝗙𝗙; 𝗙𝗙; F; F; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL F
+1D5DA;1D5DA;1D5DA;0047;0047; # (𝗚𝗚; 𝗚𝗚; 𝗚𝗚; G; G; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL G
+1D5DB;1D5DB;1D5DB;0048;0048; # (𝗛𝗛; 𝗛𝗛; 𝗛𝗛; H; H; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL H
+1D5DC;1D5DC;1D5DC;0049;0049; # (𝗜𝗜; 𝗜𝗜; 𝗜𝗜; I; I; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL I
+1D5DD;1D5DD;1D5DD;004A;004A; # (𝗝𝗝; 𝗝𝗝; 𝗝𝗝; J; J; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL J
+1D5DE;1D5DE;1D5DE;004B;004B; # (𝗞𝗞; 𝗞𝗞; 𝗞𝗞; K; K; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL K
+1D5DF;1D5DF;1D5DF;004C;004C; # (𝗟𝗟; 𝗟𝗟; 𝗟𝗟; L; L; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL L
+1D5E0;1D5E0;1D5E0;004D;004D; # (𝗠𝗠; 𝗠𝗠; 𝗠𝗠; M; M; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL M
+1D5E1;1D5E1;1D5E1;004E;004E; # (𝗡𝗡; 𝗡𝗡; 𝗡𝗡; N; N; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL N
+1D5E2;1D5E2;1D5E2;004F;004F; # (𝗢𝗢; 𝗢𝗢; 𝗢𝗢; O; O; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL O
+1D5E3;1D5E3;1D5E3;0050;0050; # (𝗣𝗣; 𝗣𝗣; 𝗣𝗣; P; P; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL P
+1D5E4;1D5E4;1D5E4;0051;0051; # (𝗤𝗤; 𝗤𝗤; 𝗤𝗤; Q; Q; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL Q
+1D5E5;1D5E5;1D5E5;0052;0052; # (𝗥𝗥; 𝗥𝗥; 𝗥𝗥; R; R; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL R
+1D5E6;1D5E6;1D5E6;0053;0053; # (𝗦𝗦; 𝗦𝗦; 𝗦𝗦; S; S; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL S
+1D5E7;1D5E7;1D5E7;0054;0054; # (𝗧𝗧; 𝗧𝗧; 𝗧𝗧; T; T; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL T
+1D5E8;1D5E8;1D5E8;0055;0055; # (𝗨𝗨; 𝗨𝗨; 𝗨𝗨; U; U; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL U
+1D5E9;1D5E9;1D5E9;0056;0056; # (𝗩𝗩; 𝗩𝗩; 𝗩𝗩; V; V; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL V
+1D5EA;1D5EA;1D5EA;0057;0057; # (𝗪𝗪; 𝗪𝗪; 𝗪𝗪; W; W; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL W
+1D5EB;1D5EB;1D5EB;0058;0058; # (𝗫𝗫; 𝗫𝗫; 𝗫𝗫; X; X; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL X
+1D5EC;1D5EC;1D5EC;0059;0059; # (𝗬𝗬; 𝗬𝗬; 𝗬𝗬; Y; Y; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL Y
+1D5ED;1D5ED;1D5ED;005A;005A; # (𝗭𝗭; 𝗭𝗭; 𝗭𝗭; Z; Z; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL Z
+1D5EE;1D5EE;1D5EE;0061;0061; # (𝗮𝗮; 𝗮𝗮; 𝗮𝗮; a; a; ) MATHEMATICAL SANS-SERIF BOLD SMALL A
+1D5EF;1D5EF;1D5EF;0062;0062; # (𝗯𝗯; 𝗯𝗯; 𝗯𝗯; b; b; ) MATHEMATICAL SANS-SERIF BOLD SMALL B
+1D5F0;1D5F0;1D5F0;0063;0063; # (𝗰𝗰; 𝗰𝗰; 𝗰𝗰; c; c; ) MATHEMATICAL SANS-SERIF BOLD SMALL C
+1D5F1;1D5F1;1D5F1;0064;0064; # (𝗱𝗱; 𝗱𝗱; 𝗱𝗱; d; d; ) MATHEMATICAL SANS-SERIF BOLD SMALL D
+1D5F2;1D5F2;1D5F2;0065;0065; # (𝗲𝗲; 𝗲𝗲; 𝗲𝗲; e; e; ) MATHEMATICAL SANS-SERIF BOLD SMALL E
+1D5F3;1D5F3;1D5F3;0066;0066; # (𝗳𝗳; 𝗳𝗳; 𝗳𝗳; f; f; ) MATHEMATICAL SANS-SERIF BOLD SMALL F
+1D5F4;1D5F4;1D5F4;0067;0067; # (𝗴𝗴; 𝗴𝗴; 𝗴𝗴; g; g; ) MATHEMATICAL SANS-SERIF BOLD SMALL G
+1D5F5;1D5F5;1D5F5;0068;0068; # (𝗵𝗵; 𝗵𝗵; 𝗵𝗵; h; h; ) MATHEMATICAL SANS-SERIF BOLD SMALL H
+1D5F6;1D5F6;1D5F6;0069;0069; # (𝗶𝗶; 𝗶𝗶; 𝗶𝗶; i; i; ) MATHEMATICAL SANS-SERIF BOLD SMALL I
+1D5F7;1D5F7;1D5F7;006A;006A; # (𝗷𝗷; 𝗷𝗷; 𝗷𝗷; j; j; ) MATHEMATICAL SANS-SERIF BOLD SMALL J
+1D5F8;1D5F8;1D5F8;006B;006B; # (𝗸𝗸; 𝗸𝗸; 𝗸𝗸; k; k; ) MATHEMATICAL SANS-SERIF BOLD SMALL K
+1D5F9;1D5F9;1D5F9;006C;006C; # (𝗹𝗹; 𝗹𝗹; 𝗹𝗹; l; l; ) MATHEMATICAL SANS-SERIF BOLD SMALL L
+1D5FA;1D5FA;1D5FA;006D;006D; # (𝗺𝗺; 𝗺𝗺; 𝗺𝗺; m; m; ) MATHEMATICAL SANS-SERIF BOLD SMALL M
+1D5FB;1D5FB;1D5FB;006E;006E; # (𝗻𝗻; 𝗻𝗻; 𝗻𝗻; n; n; ) MATHEMATICAL SANS-SERIF BOLD SMALL N
+1D5FC;1D5FC;1D5FC;006F;006F; # (𝗼𝗼; 𝗼𝗼; 𝗼𝗼; o; o; ) MATHEMATICAL SANS-SERIF BOLD SMALL O
+1D5FD;1D5FD;1D5FD;0070;0070; # (𝗽𝗽; 𝗽𝗽; 𝗽𝗽; p; p; ) MATHEMATICAL SANS-SERIF BOLD SMALL P
+1D5FE;1D5FE;1D5FE;0071;0071; # (𝗾𝗾; 𝗾𝗾; 𝗾𝗾; q; q; ) MATHEMATICAL SANS-SERIF BOLD SMALL Q
+1D5FF;1D5FF;1D5FF;0072;0072; # (𝗿𝗿; 𝗿𝗿; 𝗿𝗿; r; r; ) MATHEMATICAL SANS-SERIF BOLD SMALL R
+1D600;1D600;1D600;0073;0073; # (𝘀𝘀; 𝘀𝘀; 𝘀𝘀; s; s; ) MATHEMATICAL SANS-SERIF BOLD SMALL S
+1D601;1D601;1D601;0074;0074; # (𝘁𝘁; 𝘁𝘁; 𝘁𝘁; t; t; ) MATHEMATICAL SANS-SERIF BOLD SMALL T
+1D602;1D602;1D602;0075;0075; # (𝘂𝘂; 𝘂𝘂; 𝘂𝘂; u; u; ) MATHEMATICAL SANS-SERIF BOLD SMALL U
+1D603;1D603;1D603;0076;0076; # (𝘃𝘃; 𝘃𝘃; 𝘃𝘃; v; v; ) MATHEMATICAL SANS-SERIF BOLD SMALL V
+1D604;1D604;1D604;0077;0077; # (𝘄𝘄; 𝘄𝘄; 𝘄𝘄; w; w; ) MATHEMATICAL SANS-SERIF BOLD SMALL W
+1D605;1D605;1D605;0078;0078; # (𝘅𝘅; 𝘅𝘅; 𝘅𝘅; x; x; ) MATHEMATICAL SANS-SERIF BOLD SMALL X
+1D606;1D606;1D606;0079;0079; # (𝘆𝘆; 𝘆𝘆; 𝘆𝘆; y; y; ) MATHEMATICAL SANS-SERIF BOLD SMALL Y
+1D607;1D607;1D607;007A;007A; # (𝘇𝘇; 𝘇𝘇; 𝘇𝘇; z; z; ) MATHEMATICAL SANS-SERIF BOLD SMALL Z
+1D608;1D608;1D608;0041;0041; # (𝘈𝘈; 𝘈𝘈; 𝘈𝘈; A; A; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL A
+1D609;1D609;1D609;0042;0042; # (𝘉𝘉; 𝘉𝘉; 𝘉𝘉; B; B; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL B
+1D60A;1D60A;1D60A;0043;0043; # (𝘊𝘊; 𝘊𝘊; 𝘊𝘊; C; C; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL C
+1D60B;1D60B;1D60B;0044;0044; # (𝘋𝘋; 𝘋𝘋; 𝘋𝘋; D; D; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL D
+1D60C;1D60C;1D60C;0045;0045; # (𝘌𝘌; 𝘌𝘌; 𝘌𝘌; E; E; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL E
+1D60D;1D60D;1D60D;0046;0046; # (𝘍𝘍; 𝘍𝘍; 𝘍𝘍; F; F; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL F
+1D60E;1D60E;1D60E;0047;0047; # (𝘎𝘎; 𝘎𝘎; 𝘎𝘎; G; G; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL G
+1D60F;1D60F;1D60F;0048;0048; # (𝘏𝘏; 𝘏𝘏; 𝘏𝘏; H; H; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL H
+1D610;1D610;1D610;0049;0049; # (𝘐𝘐; 𝘐𝘐; 𝘐𝘐; I; I; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL I
+1D611;1D611;1D611;004A;004A; # (𝘑𝘑; 𝘑𝘑; 𝘑𝘑; J; J; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL J
+1D612;1D612;1D612;004B;004B; # (𝘒𝘒; 𝘒𝘒; 𝘒𝘒; K; K; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL K
+1D613;1D613;1D613;004C;004C; # (𝘓𝘓; 𝘓𝘓; 𝘓𝘓; L; L; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL L
+1D614;1D614;1D614;004D;004D; # (𝘔𝘔; 𝘔𝘔; 𝘔𝘔; M; M; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL M
+1D615;1D615;1D615;004E;004E; # (𝘕𝘕; 𝘕𝘕; 𝘕𝘕; N; N; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL N
+1D616;1D616;1D616;004F;004F; # (𝘖𝘖; 𝘖𝘖; 𝘖𝘖; O; O; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL O
+1D617;1D617;1D617;0050;0050; # (𝘗𝘗; 𝘗𝘗; 𝘗𝘗; P; P; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL P
+1D618;1D618;1D618;0051;0051; # (𝘘𝘘; 𝘘𝘘; 𝘘𝘘; Q; Q; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL Q
+1D619;1D619;1D619;0052;0052; # (𝘙𝘙; 𝘙𝘙; 𝘙𝘙; R; R; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL R
+1D61A;1D61A;1D61A;0053;0053; # (𝘚𝘚; 𝘚𝘚; 𝘚𝘚; S; S; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL S
+1D61B;1D61B;1D61B;0054;0054; # (𝘛𝘛; 𝘛𝘛; 𝘛𝘛; T; T; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL T
+1D61C;1D61C;1D61C;0055;0055; # (𝘜𝘜; 𝘜𝘜; 𝘜𝘜; U; U; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL U
+1D61D;1D61D;1D61D;0056;0056; # (𝘝𝘝; 𝘝𝘝; 𝘝𝘝; V; V; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL V
+1D61E;1D61E;1D61E;0057;0057; # (𝘞𝘞; 𝘞𝘞; 𝘞𝘞; W; W; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL W
+1D61F;1D61F;1D61F;0058;0058; # (𝘟𝘟; 𝘟𝘟; 𝘟𝘟; X; X; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL X
+1D620;1D620;1D620;0059;0059; # (𝘠𝘠; 𝘠𝘠; 𝘠𝘠; Y; Y; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL Y
+1D621;1D621;1D621;005A;005A; # (𝘡𝘡; 𝘡𝘡; 𝘡𝘡; Z; Z; ) MATHEMATICAL SANS-SERIF ITALIC CAPITAL Z
+1D622;1D622;1D622;0061;0061; # (𝘢𝘢; 𝘢𝘢; 𝘢𝘢; a; a; ) MATHEMATICAL SANS-SERIF ITALIC SMALL A
+1D623;1D623;1D623;0062;0062; # (𝘣𝘣; 𝘣𝘣; 𝘣𝘣; b; b; ) MATHEMATICAL SANS-SERIF ITALIC SMALL B
+1D624;1D624;1D624;0063;0063; # (𝘤𝘤; 𝘤𝘤; 𝘤𝘤; c; c; ) MATHEMATICAL SANS-SERIF ITALIC SMALL C
+1D625;1D625;1D625;0064;0064; # (𝘥𝘥; 𝘥𝘥; 𝘥𝘥; d; d; ) MATHEMATICAL SANS-SERIF ITALIC SMALL D
+1D626;1D626;1D626;0065;0065; # (𝘦𝘦; 𝘦𝘦; 𝘦𝘦; e; e; ) MATHEMATICAL SANS-SERIF ITALIC SMALL E
+1D627;1D627;1D627;0066;0066; # (𝘧𝘧; 𝘧𝘧; 𝘧𝘧; f; f; ) MATHEMATICAL SANS-SERIF ITALIC SMALL F
+1D628;1D628;1D628;0067;0067; # (𝘨𝘨; 𝘨𝘨; 𝘨𝘨; g; g; ) MATHEMATICAL SANS-SERIF ITALIC SMALL G
+1D629;1D629;1D629;0068;0068; # (𝘩𝘩; 𝘩𝘩; 𝘩𝘩; h; h; ) MATHEMATICAL SANS-SERIF ITALIC SMALL H
+1D62A;1D62A;1D62A;0069;0069; # (𝘪𝘪; 𝘪𝘪; 𝘪𝘪; i; i; ) MATHEMATICAL SANS-SERIF ITALIC SMALL I
+1D62B;1D62B;1D62B;006A;006A; # (𝘫𝘫; 𝘫𝘫; 𝘫𝘫; j; j; ) MATHEMATICAL SANS-SERIF ITALIC SMALL J
+1D62C;1D62C;1D62C;006B;006B; # (𝘬𝘬; 𝘬𝘬; 𝘬𝘬; k; k; ) MATHEMATICAL SANS-SERIF ITALIC SMALL K
+1D62D;1D62D;1D62D;006C;006C; # (𝘭𝘭; 𝘭𝘭; 𝘭𝘭; l; l; ) MATHEMATICAL SANS-SERIF ITALIC SMALL L
+1D62E;1D62E;1D62E;006D;006D; # (𝘮𝘮; 𝘮𝘮; 𝘮𝘮; m; m; ) MATHEMATICAL SANS-SERIF ITALIC SMALL M
+1D62F;1D62F;1D62F;006E;006E; # (𝘯𝘯; 𝘯𝘯; 𝘯𝘯; n; n; ) MATHEMATICAL SANS-SERIF ITALIC SMALL N
+1D630;1D630;1D630;006F;006F; # (𝘰𝘰; 𝘰𝘰; 𝘰𝘰; o; o; ) MATHEMATICAL SANS-SERIF ITALIC SMALL O
+1D631;1D631;1D631;0070;0070; # (𝘱𝘱; 𝘱𝘱; 𝘱𝘱; p; p; ) MATHEMATICAL SANS-SERIF ITALIC SMALL P
+1D632;1D632;1D632;0071;0071; # (𝘲𝘲; 𝘲𝘲; 𝘲𝘲; q; q; ) MATHEMATICAL SANS-SERIF ITALIC SMALL Q
+1D633;1D633;1D633;0072;0072; # (𝘳𝘳; 𝘳𝘳; 𝘳𝘳; r; r; ) MATHEMATICAL SANS-SERIF ITALIC SMALL R
+1D634;1D634;1D634;0073;0073; # (𝘴𝘴; 𝘴𝘴; 𝘴𝘴; s; s; ) MATHEMATICAL SANS-SERIF ITALIC SMALL S
+1D635;1D635;1D635;0074;0074; # (𝘵𝘵; 𝘵𝘵; 𝘵𝘵; t; t; ) MATHEMATICAL SANS-SERIF ITALIC SMALL T
+1D636;1D636;1D636;0075;0075; # (𝘶𝘶; 𝘶𝘶; 𝘶𝘶; u; u; ) MATHEMATICAL SANS-SERIF ITALIC SMALL U
+1D637;1D637;1D637;0076;0076; # (𝘷𝘷; 𝘷𝘷; 𝘷𝘷; v; v; ) MATHEMATICAL SANS-SERIF ITALIC SMALL V
+1D638;1D638;1D638;0077;0077; # (𝘸𝘸; 𝘸𝘸; 𝘸𝘸; w; w; ) MATHEMATICAL SANS-SERIF ITALIC SMALL W
+1D639;1D639;1D639;0078;0078; # (𝘹𝘹; 𝘹𝘹; 𝘹𝘹; x; x; ) MATHEMATICAL SANS-SERIF ITALIC SMALL X
+1D63A;1D63A;1D63A;0079;0079; # (𝘺𝘺; 𝘺𝘺; 𝘺𝘺; y; y; ) MATHEMATICAL SANS-SERIF ITALIC SMALL Y
+1D63B;1D63B;1D63B;007A;007A; # (𝘻𝘻; 𝘻𝘻; 𝘻𝘻; z; z; ) MATHEMATICAL SANS-SERIF ITALIC SMALL Z
+1D63C;1D63C;1D63C;0041;0041; # (𝘼𝘼; 𝘼𝘼; 𝘼𝘼; A; A; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL A
+1D63D;1D63D;1D63D;0042;0042; # (𝘽𝘽; 𝘽𝘽; 𝘽𝘽; B; B; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL B
+1D63E;1D63E;1D63E;0043;0043; # (𝘾𝘾; 𝘾𝘾; 𝘾𝘾; C; C; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL C
+1D63F;1D63F;1D63F;0044;0044; # (𝘿𝘿; 𝘿𝘿; 𝘿𝘿; D; D; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL D
+1D640;1D640;1D640;0045;0045; # (𝙀𝙀; 𝙀𝙀; 𝙀𝙀; E; E; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL E
+1D641;1D641;1D641;0046;0046; # (𝙁𝙁; 𝙁𝙁; 𝙁𝙁; F; F; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL F
+1D642;1D642;1D642;0047;0047; # (𝙂𝙂; 𝙂𝙂; 𝙂𝙂; G; G; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL G
+1D643;1D643;1D643;0048;0048; # (𝙃𝙃; 𝙃𝙃; 𝙃𝙃; H; H; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL H
+1D644;1D644;1D644;0049;0049; # (𝙄𝙄; 𝙄𝙄; 𝙄𝙄; I; I; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL I
+1D645;1D645;1D645;004A;004A; # (𝙅𝙅; 𝙅𝙅; 𝙅𝙅; J; J; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL J
+1D646;1D646;1D646;004B;004B; # (𝙆𝙆; 𝙆𝙆; 𝙆𝙆; K; K; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL K
+1D647;1D647;1D647;004C;004C; # (𝙇𝙇; 𝙇𝙇; 𝙇𝙇; L; L; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL L
+1D648;1D648;1D648;004D;004D; # (𝙈𝙈; 𝙈𝙈; 𝙈𝙈; M; M; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL M
+1D649;1D649;1D649;004E;004E; # (𝙉𝙉; 𝙉𝙉; 𝙉𝙉; N; N; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL N
+1D64A;1D64A;1D64A;004F;004F; # (𝙊𝙊; 𝙊𝙊; 𝙊𝙊; O; O; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL O
+1D64B;1D64B;1D64B;0050;0050; # (𝙋𝙋; 𝙋𝙋; 𝙋𝙋; P; P; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL P
+1D64C;1D64C;1D64C;0051;0051; # (𝙌𝙌; 𝙌𝙌; 𝙌𝙌; Q; Q; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL Q
+1D64D;1D64D;1D64D;0052;0052; # (𝙍𝙍; 𝙍𝙍; 𝙍𝙍; R; R; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL R
+1D64E;1D64E;1D64E;0053;0053; # (𝙎𝙎; 𝙎𝙎; 𝙎𝙎; S; S; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL S
+1D64F;1D64F;1D64F;0054;0054; # (𝙏𝙏; 𝙏𝙏; 𝙏𝙏; T; T; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL T
+1D650;1D650;1D650;0055;0055; # (𝙐𝙐; 𝙐𝙐; 𝙐𝙐; U; U; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL U
+1D651;1D651;1D651;0056;0056; # (𝙑𝙑; 𝙑𝙑; 𝙑𝙑; V; V; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL V
+1D652;1D652;1D652;0057;0057; # (𝙒𝙒; 𝙒𝙒; 𝙒𝙒; W; W; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL W
+1D653;1D653;1D653;0058;0058; # (𝙓𝙓; 𝙓𝙓; 𝙓𝙓; X; X; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL X
+1D654;1D654;1D654;0059;0059; # (𝙔𝙔; 𝙔𝙔; 𝙔𝙔; Y; Y; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL Y
+1D655;1D655;1D655;005A;005A; # (𝙕𝙕; 𝙕𝙕; 𝙕𝙕; Z; Z; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL Z
+1D656;1D656;1D656;0061;0061; # (𝙖𝙖; 𝙖𝙖; 𝙖𝙖; a; a; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL A
+1D657;1D657;1D657;0062;0062; # (𝙗𝙗; 𝙗𝙗; 𝙗𝙗; b; b; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL B
+1D658;1D658;1D658;0063;0063; # (𝙘𝙘; 𝙘𝙘; 𝙘𝙘; c; c; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL C
+1D659;1D659;1D659;0064;0064; # (𝙙𝙙; 𝙙𝙙; 𝙙𝙙; d; d; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL D
+1D65A;1D65A;1D65A;0065;0065; # (𝙚𝙚; 𝙚𝙚; 𝙚𝙚; e; e; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL E
+1D65B;1D65B;1D65B;0066;0066; # (𝙛𝙛; 𝙛𝙛; 𝙛𝙛; f; f; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL F
+1D65C;1D65C;1D65C;0067;0067; # (𝙜𝙜; 𝙜𝙜; 𝙜𝙜; g; g; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL G
+1D65D;1D65D;1D65D;0068;0068; # (𝙝𝙝; 𝙝𝙝; 𝙝𝙝; h; h; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL H
+1D65E;1D65E;1D65E;0069;0069; # (𝙞𝙞; 𝙞𝙞; 𝙞𝙞; i; i; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL I
+1D65F;1D65F;1D65F;006A;006A; # (𝙟𝙟; 𝙟𝙟; 𝙟𝙟; j; j; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL J
+1D660;1D660;1D660;006B;006B; # (𝙠𝙠; 𝙠𝙠; 𝙠𝙠; k; k; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL K
+1D661;1D661;1D661;006C;006C; # (𝙡𝙡; 𝙡𝙡; 𝙡𝙡; l; l; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL L
+1D662;1D662;1D662;006D;006D; # (𝙢𝙢; 𝙢𝙢; 𝙢𝙢; m; m; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL M
+1D663;1D663;1D663;006E;006E; # (𝙣𝙣; 𝙣𝙣; 𝙣𝙣; n; n; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL N
+1D664;1D664;1D664;006F;006F; # (𝙤𝙤; 𝙤𝙤; 𝙤𝙤; o; o; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL O
+1D665;1D665;1D665;0070;0070; # (𝙥𝙥; 𝙥𝙥; 𝙥𝙥; p; p; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL P
+1D666;1D666;1D666;0071;0071; # (𝙦𝙦; 𝙦𝙦; 𝙦𝙦; q; q; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL Q
+1D667;1D667;1D667;0072;0072; # (𝙧𝙧; 𝙧𝙧; 𝙧𝙧; r; r; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL R
+1D668;1D668;1D668;0073;0073; # (𝙨𝙨; 𝙨𝙨; 𝙨𝙨; s; s; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL S
+1D669;1D669;1D669;0074;0074; # (𝙩𝙩; 𝙩𝙩; 𝙩𝙩; t; t; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL T
+1D66A;1D66A;1D66A;0075;0075; # (𝙪𝙪; 𝙪𝙪; 𝙪𝙪; u; u; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL U
+1D66B;1D66B;1D66B;0076;0076; # (𝙫𝙫; 𝙫𝙫; 𝙫𝙫; v; v; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL V
+1D66C;1D66C;1D66C;0077;0077; # (𝙬𝙬; 𝙬𝙬; 𝙬𝙬; w; w; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL W
+1D66D;1D66D;1D66D;0078;0078; # (𝙭𝙭; 𝙭𝙭; 𝙭𝙭; x; x; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL X
+1D66E;1D66E;1D66E;0079;0079; # (𝙮𝙮; 𝙮𝙮; 𝙮𝙮; y; y; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL Y
+1D66F;1D66F;1D66F;007A;007A; # (𝙯𝙯; 𝙯𝙯; 𝙯𝙯; z; z; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL Z
+1D670;1D670;1D670;0041;0041; # (𝙰𝙰; 𝙰𝙰; 𝙰𝙰; A; A; ) MATHEMATICAL MONOSPACE CAPITAL A
+1D671;1D671;1D671;0042;0042; # (𝙱𝙱; 𝙱𝙱; 𝙱𝙱; B; B; ) MATHEMATICAL MONOSPACE CAPITAL B
+1D672;1D672;1D672;0043;0043; # (𝙲𝙲; 𝙲𝙲; 𝙲𝙲; C; C; ) MATHEMATICAL MONOSPACE CAPITAL C
+1D673;1D673;1D673;0044;0044; # (𝙳𝙳; 𝙳𝙳; 𝙳𝙳; D; D; ) MATHEMATICAL MONOSPACE CAPITAL D
+1D674;1D674;1D674;0045;0045; # (𝙴𝙴; 𝙴𝙴; 𝙴𝙴; E; E; ) MATHEMATICAL MONOSPACE CAPITAL E
+1D675;1D675;1D675;0046;0046; # (𝙵𝙵; 𝙵𝙵; 𝙵𝙵; F; F; ) MATHEMATICAL MONOSPACE CAPITAL F
+1D676;1D676;1D676;0047;0047; # (𝙶𝙶; 𝙶𝙶; 𝙶𝙶; G; G; ) MATHEMATICAL MONOSPACE CAPITAL G
+1D677;1D677;1D677;0048;0048; # (𝙷𝙷; 𝙷𝙷; 𝙷𝙷; H; H; ) MATHEMATICAL MONOSPACE CAPITAL H
+1D678;1D678;1D678;0049;0049; # (𝙸𝙸; 𝙸𝙸; 𝙸𝙸; I; I; ) MATHEMATICAL MONOSPACE CAPITAL I
+1D679;1D679;1D679;004A;004A; # (𝙹𝙹; 𝙹𝙹; 𝙹𝙹; J; J; ) MATHEMATICAL MONOSPACE CAPITAL J
+1D67A;1D67A;1D67A;004B;004B; # (𝙺𝙺; 𝙺𝙺; 𝙺𝙺; K; K; ) MATHEMATICAL MONOSPACE CAPITAL K
+1D67B;1D67B;1D67B;004C;004C; # (𝙻𝙻; 𝙻𝙻; 𝙻𝙻; L; L; ) MATHEMATICAL MONOSPACE CAPITAL L
+1D67C;1D67C;1D67C;004D;004D; # (𝙼𝙼; 𝙼𝙼; 𝙼𝙼; M; M; ) MATHEMATICAL MONOSPACE CAPITAL M
+1D67D;1D67D;1D67D;004E;004E; # (𝙽𝙽; 𝙽𝙽; 𝙽𝙽; N; N; ) MATHEMATICAL MONOSPACE CAPITAL N
+1D67E;1D67E;1D67E;004F;004F; # (𝙾𝙾; 𝙾𝙾; 𝙾𝙾; O; O; ) MATHEMATICAL MONOSPACE CAPITAL O
+1D67F;1D67F;1D67F;0050;0050; # (𝙿𝙿; 𝙿𝙿; 𝙿𝙿; P; P; ) MATHEMATICAL MONOSPACE CAPITAL P
+1D680;1D680;1D680;0051;0051; # (𝚀𝚀; 𝚀𝚀; 𝚀𝚀; Q; Q; ) MATHEMATICAL MONOSPACE CAPITAL Q
+1D681;1D681;1D681;0052;0052; # (𝚁𝚁; 𝚁𝚁; 𝚁𝚁; R; R; ) MATHEMATICAL MONOSPACE CAPITAL R
+1D682;1D682;1D682;0053;0053; # (𝚂𝚂; 𝚂𝚂; 𝚂𝚂; S; S; ) MATHEMATICAL MONOSPACE CAPITAL S
+1D683;1D683;1D683;0054;0054; # (𝚃𝚃; 𝚃𝚃; 𝚃𝚃; T; T; ) MATHEMATICAL MONOSPACE CAPITAL T
+1D684;1D684;1D684;0055;0055; # (𝚄𝚄; 𝚄𝚄; 𝚄𝚄; U; U; ) MATHEMATICAL MONOSPACE CAPITAL U
+1D685;1D685;1D685;0056;0056; # (𝚅𝚅; 𝚅𝚅; 𝚅𝚅; V; V; ) MATHEMATICAL MONOSPACE CAPITAL V
+1D686;1D686;1D686;0057;0057; # (𝚆𝚆; 𝚆𝚆; 𝚆𝚆; W; W; ) MATHEMATICAL MONOSPACE CAPITAL W
+1D687;1D687;1D687;0058;0058; # (𝚇𝚇; 𝚇𝚇; 𝚇𝚇; X; X; ) MATHEMATICAL MONOSPACE CAPITAL X
+1D688;1D688;1D688;0059;0059; # (𝚈𝚈; 𝚈𝚈; 𝚈𝚈; Y; Y; ) MATHEMATICAL MONOSPACE CAPITAL Y
+1D689;1D689;1D689;005A;005A; # (𝚉𝚉; 𝚉𝚉; 𝚉𝚉; Z; Z; ) MATHEMATICAL MONOSPACE CAPITAL Z
+1D68A;1D68A;1D68A;0061;0061; # (𝚊𝚊; 𝚊𝚊; 𝚊𝚊; a; a; ) MATHEMATICAL MONOSPACE SMALL A
+1D68B;1D68B;1D68B;0062;0062; # (𝚋𝚋; 𝚋𝚋; 𝚋𝚋; b; b; ) MATHEMATICAL MONOSPACE SMALL B
+1D68C;1D68C;1D68C;0063;0063; # (𝚌𝚌; 𝚌𝚌; 𝚌𝚌; c; c; ) MATHEMATICAL MONOSPACE SMALL C
+1D68D;1D68D;1D68D;0064;0064; # (𝚍𝚍; 𝚍𝚍; 𝚍𝚍; d; d; ) MATHEMATICAL MONOSPACE SMALL D
+1D68E;1D68E;1D68E;0065;0065; # (𝚎𝚎; 𝚎𝚎; 𝚎𝚎; e; e; ) MATHEMATICAL MONOSPACE SMALL E
+1D68F;1D68F;1D68F;0066;0066; # (𝚏𝚏; 𝚏𝚏; 𝚏𝚏; f; f; ) MATHEMATICAL MONOSPACE SMALL F
+1D690;1D690;1D690;0067;0067; # (𝚐𝚐; 𝚐𝚐; 𝚐𝚐; g; g; ) MATHEMATICAL MONOSPACE SMALL G
+1D691;1D691;1D691;0068;0068; # (𝚑𝚑; 𝚑𝚑; 𝚑𝚑; h; h; ) MATHEMATICAL MONOSPACE SMALL H
+1D692;1D692;1D692;0069;0069; # (𝚒𝚒; 𝚒𝚒; 𝚒𝚒; i; i; ) MATHEMATICAL MONOSPACE SMALL I
+1D693;1D693;1D693;006A;006A; # (𝚓𝚓; 𝚓𝚓; 𝚓𝚓; j; j; ) MATHEMATICAL MONOSPACE SMALL J
+1D694;1D694;1D694;006B;006B; # (𝚔𝚔; 𝚔𝚔; 𝚔𝚔; k; k; ) MATHEMATICAL MONOSPACE SMALL K
+1D695;1D695;1D695;006C;006C; # (𝚕𝚕; 𝚕𝚕; 𝚕𝚕; l; l; ) MATHEMATICAL MONOSPACE SMALL L
+1D696;1D696;1D696;006D;006D; # (𝚖𝚖; 𝚖𝚖; 𝚖𝚖; m; m; ) MATHEMATICAL MONOSPACE SMALL M
+1D697;1D697;1D697;006E;006E; # (𝚗𝚗; 𝚗𝚗; 𝚗𝚗; n; n; ) MATHEMATICAL MONOSPACE SMALL N
+1D698;1D698;1D698;006F;006F; # (𝚘𝚘; 𝚘𝚘; 𝚘𝚘; o; o; ) MATHEMATICAL MONOSPACE SMALL O
+1D699;1D699;1D699;0070;0070; # (𝚙𝚙; 𝚙𝚙; 𝚙𝚙; p; p; ) MATHEMATICAL MONOSPACE SMALL P
+1D69A;1D69A;1D69A;0071;0071; # (𝚚𝚚; 𝚚𝚚; 𝚚𝚚; q; q; ) MATHEMATICAL MONOSPACE SMALL Q
+1D69B;1D69B;1D69B;0072;0072; # (𝚛𝚛; 𝚛𝚛; 𝚛𝚛; r; r; ) MATHEMATICAL MONOSPACE SMALL R
+1D69C;1D69C;1D69C;0073;0073; # (𝚜𝚜; 𝚜𝚜; 𝚜𝚜; s; s; ) MATHEMATICAL MONOSPACE SMALL S
+1D69D;1D69D;1D69D;0074;0074; # (𝚝𝚝; 𝚝𝚝; 𝚝𝚝; t; t; ) MATHEMATICAL MONOSPACE SMALL T
+1D69E;1D69E;1D69E;0075;0075; # (𝚞𝚞; 𝚞𝚞; 𝚞𝚞; u; u; ) MATHEMATICAL MONOSPACE SMALL U
+1D69F;1D69F;1D69F;0076;0076; # (𝚟𝚟; 𝚟𝚟; 𝚟𝚟; v; v; ) MATHEMATICAL MONOSPACE SMALL V
+1D6A0;1D6A0;1D6A0;0077;0077; # (𝚠𝚠; 𝚠𝚠; 𝚠𝚠; w; w; ) MATHEMATICAL MONOSPACE SMALL W
+1D6A1;1D6A1;1D6A1;0078;0078; # (𝚡𝚡; 𝚡𝚡; 𝚡𝚡; x; x; ) MATHEMATICAL MONOSPACE SMALL X
+1D6A2;1D6A2;1D6A2;0079;0079; # (𝚢𝚢; 𝚢𝚢; 𝚢𝚢; y; y; ) MATHEMATICAL MONOSPACE SMALL Y
+1D6A3;1D6A3;1D6A3;007A;007A; # (𝚣𝚣; 𝚣𝚣; 𝚣𝚣; z; z; ) MATHEMATICAL MONOSPACE SMALL Z
+1D6A8;1D6A8;1D6A8;0391;0391; # (𝚨𝚨; 𝚨𝚨; 𝚨𝚨; Α; Α; ) MATHEMATICAL BOLD CAPITAL ALPHA
+1D6A9;1D6A9;1D6A9;0392;0392; # (𝚩𝚩; 𝚩𝚩; 𝚩𝚩; Β; Β; ) MATHEMATICAL BOLD CAPITAL BETA
+1D6AA;1D6AA;1D6AA;0393;0393; # (𝚪𝚪; 𝚪𝚪; 𝚪𝚪; Γ; Γ; ) MATHEMATICAL BOLD CAPITAL GAMMA
+1D6AB;1D6AB;1D6AB;0394;0394; # (𝚫𝚫; 𝚫𝚫; 𝚫𝚫; Δ; Δ; ) MATHEMATICAL BOLD CAPITAL DELTA
+1D6AC;1D6AC;1D6AC;0395;0395; # (𝚬𝚬; 𝚬𝚬; 𝚬𝚬; Ε; Ε; ) MATHEMATICAL BOLD CAPITAL EPSILON
+1D6AD;1D6AD;1D6AD;0396;0396; # (𝚭𝚭; 𝚭𝚭; 𝚭𝚭; Ζ; Ζ; ) MATHEMATICAL BOLD CAPITAL ZETA
+1D6AE;1D6AE;1D6AE;0397;0397; # (𝚮𝚮; 𝚮𝚮; 𝚮𝚮; Η; Η; ) MATHEMATICAL BOLD CAPITAL ETA
+1D6AF;1D6AF;1D6AF;0398;0398; # (𝚯𝚯; 𝚯𝚯; 𝚯𝚯; Θ; Θ; ) MATHEMATICAL BOLD CAPITAL THETA
+1D6B0;1D6B0;1D6B0;0399;0399; # (𝚰𝚰; 𝚰𝚰; 𝚰𝚰; Ι; Ι; ) MATHEMATICAL BOLD CAPITAL IOTA
+1D6B1;1D6B1;1D6B1;039A;039A; # (𝚱𝚱; 𝚱𝚱; 𝚱𝚱; Κ; Κ; ) MATHEMATICAL BOLD CAPITAL KAPPA
+1D6B2;1D6B2;1D6B2;039B;039B; # (𝚲𝚲; 𝚲𝚲; 𝚲𝚲; Λ; Λ; ) MATHEMATICAL BOLD CAPITAL LAMDA
+1D6B3;1D6B3;1D6B3;039C;039C; # (𝚳𝚳; 𝚳𝚳; 𝚳𝚳; Μ; Μ; ) MATHEMATICAL BOLD CAPITAL MU
+1D6B4;1D6B4;1D6B4;039D;039D; # (𝚴𝚴; 𝚴𝚴; 𝚴𝚴; Ν; Ν; ) MATHEMATICAL BOLD CAPITAL NU
+1D6B5;1D6B5;1D6B5;039E;039E; # (𝚵𝚵; 𝚵𝚵; 𝚵𝚵; Ξ; Ξ; ) MATHEMATICAL BOLD CAPITAL XI
+1D6B6;1D6B6;1D6B6;039F;039F; # (𝚶𝚶; 𝚶𝚶; 𝚶𝚶; Ο; Ο; ) MATHEMATICAL BOLD CAPITAL OMICRON
+1D6B7;1D6B7;1D6B7;03A0;03A0; # (𝚷𝚷; 𝚷𝚷; 𝚷𝚷; Π; Π; ) MATHEMATICAL BOLD CAPITAL PI
+1D6B8;1D6B8;1D6B8;03A1;03A1; # (𝚸𝚸; 𝚸𝚸; 𝚸𝚸; Ρ; Ρ; ) MATHEMATICAL BOLD CAPITAL RHO
+1D6B9;1D6B9;1D6B9;0398;0398; # (𝚹𝚹; 𝚹𝚹; 𝚹𝚹; Θ; Θ; ) MATHEMATICAL BOLD CAPITAL THETA SYMBOL
+1D6BA;1D6BA;1D6BA;03A3;03A3; # (𝚺𝚺; 𝚺𝚺; 𝚺𝚺; Σ; Σ; ) MATHEMATICAL BOLD CAPITAL SIGMA
+1D6BB;1D6BB;1D6BB;03A4;03A4; # (𝚻𝚻; 𝚻𝚻; 𝚻𝚻; Τ; Τ; ) MATHEMATICAL BOLD CAPITAL TAU
+1D6BC;1D6BC;1D6BC;03A5;03A5; # (𝚼𝚼; 𝚼𝚼; 𝚼𝚼; Υ; Υ; ) MATHEMATICAL BOLD CAPITAL UPSILON
+1D6BD;1D6BD;1D6BD;03A6;03A6; # (𝚽𝚽; 𝚽𝚽; 𝚽𝚽; Φ; Φ; ) MATHEMATICAL BOLD CAPITAL PHI
+1D6BE;1D6BE;1D6BE;03A7;03A7; # (𝚾𝚾; 𝚾𝚾; 𝚾𝚾; Χ; Χ; ) MATHEMATICAL BOLD CAPITAL CHI
+1D6BF;1D6BF;1D6BF;03A8;03A8; # (𝚿𝚿; 𝚿𝚿; 𝚿𝚿; Ψ; Ψ; ) MATHEMATICAL BOLD CAPITAL PSI
+1D6C0;1D6C0;1D6C0;03A9;03A9; # (𝛀𝛀; 𝛀𝛀; 𝛀𝛀; Ω; Ω; ) MATHEMATICAL BOLD CAPITAL OMEGA
+1D6C1;1D6C1;1D6C1;2207;2207; # (𝛁𝛁; 𝛁𝛁; 𝛁𝛁; ∇; ∇; ) MATHEMATICAL BOLD NABLA
+1D6C2;1D6C2;1D6C2;03B1;03B1; # (𝛂𝛂; 𝛂𝛂; 𝛂𝛂; α; α; ) MATHEMATICAL BOLD SMALL ALPHA
+1D6C3;1D6C3;1D6C3;03B2;03B2; # (𝛃𝛃; 𝛃𝛃; 𝛃𝛃; β; β; ) MATHEMATICAL BOLD SMALL BETA
+1D6C4;1D6C4;1D6C4;03B3;03B3; # (𝛄𝛄; 𝛄𝛄; 𝛄𝛄; γ; γ; ) MATHEMATICAL BOLD SMALL GAMMA
+1D6C5;1D6C5;1D6C5;03B4;03B4; # (𝛅𝛅; 𝛅𝛅; 𝛅𝛅; δ; δ; ) MATHEMATICAL BOLD SMALL DELTA
+1D6C6;1D6C6;1D6C6;03B5;03B5; # (𝛆𝛆; 𝛆𝛆; 𝛆𝛆; ε; ε; ) MATHEMATICAL BOLD SMALL EPSILON
+1D6C7;1D6C7;1D6C7;03B6;03B6; # (𝛇𝛇; 𝛇𝛇; 𝛇𝛇; ζ; ζ; ) MATHEMATICAL BOLD SMALL ZETA
+1D6C8;1D6C8;1D6C8;03B7;03B7; # (𝛈𝛈; 𝛈𝛈; 𝛈𝛈; η; η; ) MATHEMATICAL BOLD SMALL ETA
+1D6C9;1D6C9;1D6C9;03B8;03B8; # (𝛉𝛉; 𝛉𝛉; 𝛉𝛉; θ; θ; ) MATHEMATICAL BOLD SMALL THETA
+1D6CA;1D6CA;1D6CA;03B9;03B9; # (𝛊𝛊; 𝛊𝛊; 𝛊𝛊; ι; ι; ) MATHEMATICAL BOLD SMALL IOTA
+1D6CB;1D6CB;1D6CB;03BA;03BA; # (𝛋𝛋; 𝛋𝛋; 𝛋𝛋; κ; κ; ) MATHEMATICAL BOLD SMALL KAPPA
+1D6CC;1D6CC;1D6CC;03BB;03BB; # (𝛌𝛌; 𝛌𝛌; 𝛌𝛌; λ; λ; ) MATHEMATICAL BOLD SMALL LAMDA
+1D6CD;1D6CD;1D6CD;03BC;03BC; # (𝛍𝛍; 𝛍𝛍; 𝛍𝛍; μ; μ; ) MATHEMATICAL BOLD SMALL MU
+1D6CE;1D6CE;1D6CE;03BD;03BD; # (𝛎𝛎; 𝛎𝛎; 𝛎𝛎; ν; ν; ) MATHEMATICAL BOLD SMALL NU
+1D6CF;1D6CF;1D6CF;03BE;03BE; # (𝛏𝛏; 𝛏𝛏; 𝛏𝛏; ξ; ξ; ) MATHEMATICAL BOLD SMALL XI
+1D6D0;1D6D0;1D6D0;03BF;03BF; # (𝛐𝛐; 𝛐𝛐; 𝛐𝛐; ο; ο; ) MATHEMATICAL BOLD SMALL OMICRON
+1D6D1;1D6D1;1D6D1;03C0;03C0; # (𝛑𝛑; 𝛑𝛑; 𝛑𝛑; π; π; ) MATHEMATICAL BOLD SMALL PI
+1D6D2;1D6D2;1D6D2;03C1;03C1; # (𝛒𝛒; 𝛒𝛒; 𝛒𝛒; ρ; ρ; ) MATHEMATICAL BOLD SMALL RHO
+1D6D3;1D6D3;1D6D3;03C2;03C2; # (𝛓𝛓; 𝛓𝛓; 𝛓𝛓; ς; ς; ) MATHEMATICAL BOLD SMALL FINAL SIGMA
+1D6D4;1D6D4;1D6D4;03C3;03C3; # (𝛔𝛔; 𝛔𝛔; 𝛔𝛔; σ; σ; ) MATHEMATICAL BOLD SMALL SIGMA
+1D6D5;1D6D5;1D6D5;03C4;03C4; # (𝛕𝛕; 𝛕𝛕; 𝛕𝛕; τ; τ; ) MATHEMATICAL BOLD SMALL TAU
+1D6D6;1D6D6;1D6D6;03C5;03C5; # (𝛖𝛖; 𝛖𝛖; 𝛖𝛖; υ; υ; ) MATHEMATICAL BOLD SMALL UPSILON
+1D6D7;1D6D7;1D6D7;03C6;03C6; # (𝛗𝛗; 𝛗𝛗; 𝛗𝛗; φ; φ; ) MATHEMATICAL BOLD SMALL PHI
+1D6D8;1D6D8;1D6D8;03C7;03C7; # (𝛘𝛘; 𝛘𝛘; 𝛘𝛘; χ; χ; ) MATHEMATICAL BOLD SMALL CHI
+1D6D9;1D6D9;1D6D9;03C8;03C8; # (𝛙𝛙; 𝛙𝛙; 𝛙𝛙; ψ; ψ; ) MATHEMATICAL BOLD SMALL PSI
+1D6DA;1D6DA;1D6DA;03C9;03C9; # (𝛚𝛚; 𝛚𝛚; 𝛚𝛚; ω; ω; ) MATHEMATICAL BOLD SMALL OMEGA
+1D6DB;1D6DB;1D6DB;2202;2202; # (𝛛𝛛; 𝛛𝛛; 𝛛𝛛; ∂; ∂; ) MATHEMATICAL BOLD PARTIAL DIFFERENTIAL
+1D6DC;1D6DC;1D6DC;03B5;03B5; # (𝛜𝛜; 𝛜𝛜; 𝛜𝛜; ε; ε; ) MATHEMATICAL BOLD EPSILON SYMBOL
+1D6DD;1D6DD;1D6DD;03B8;03B8; # (𝛝𝛝; 𝛝𝛝; 𝛝𝛝; θ; θ; ) MATHEMATICAL BOLD THETA SYMBOL
+1D6DE;1D6DE;1D6DE;03BA;03BA; # (𝛞𝛞; 𝛞𝛞; 𝛞𝛞; κ; κ; ) MATHEMATICAL BOLD KAPPA SYMBOL
+1D6DF;1D6DF;1D6DF;03C6;03C6; # (𝛟𝛟; 𝛟𝛟; 𝛟𝛟; φ; φ; ) MATHEMATICAL BOLD PHI SYMBOL
+1D6E0;1D6E0;1D6E0;03C1;03C1; # (𝛠𝛠; 𝛠𝛠; 𝛠𝛠; ρ; ρ; ) MATHEMATICAL BOLD RHO SYMBOL
+1D6E1;1D6E1;1D6E1;03C0;03C0; # (𝛡𝛡; 𝛡𝛡; 𝛡𝛡; π; π; ) MATHEMATICAL BOLD PI SYMBOL
+1D6E2;1D6E2;1D6E2;0391;0391; # (𝛢𝛢; 𝛢𝛢; 𝛢𝛢; Α; Α; ) MATHEMATICAL ITALIC CAPITAL ALPHA
+1D6E3;1D6E3;1D6E3;0392;0392; # (𝛣𝛣; 𝛣𝛣; 𝛣𝛣; Β; Β; ) MATHEMATICAL ITALIC CAPITAL BETA
+1D6E4;1D6E4;1D6E4;0393;0393; # (𝛤𝛤; 𝛤𝛤; 𝛤𝛤; Γ; Γ; ) MATHEMATICAL ITALIC CAPITAL GAMMA
+1D6E5;1D6E5;1D6E5;0394;0394; # (𝛥𝛥; 𝛥𝛥; 𝛥𝛥; Δ; Δ; ) MATHEMATICAL ITALIC CAPITAL DELTA
+1D6E6;1D6E6;1D6E6;0395;0395; # (𝛦𝛦; 𝛦𝛦; 𝛦𝛦; Ε; Ε; ) MATHEMATICAL ITALIC CAPITAL EPSILON
+1D6E7;1D6E7;1D6E7;0396;0396; # (𝛧𝛧; 𝛧𝛧; 𝛧𝛧; Ζ; Ζ; ) MATHEMATICAL ITALIC CAPITAL ZETA
+1D6E8;1D6E8;1D6E8;0397;0397; # (𝛨𝛨; 𝛨𝛨; 𝛨𝛨; Η; Η; ) MATHEMATICAL ITALIC CAPITAL ETA
+1D6E9;1D6E9;1D6E9;0398;0398; # (𝛩𝛩; 𝛩𝛩; 𝛩𝛩; Θ; Θ; ) MATHEMATICAL ITALIC CAPITAL THETA
+1D6EA;1D6EA;1D6EA;0399;0399; # (𝛪𝛪; 𝛪𝛪; 𝛪𝛪; Ι; Ι; ) MATHEMATICAL ITALIC CAPITAL IOTA
+1D6EB;1D6EB;1D6EB;039A;039A; # (𝛫𝛫; 𝛫𝛫; 𝛫𝛫; Κ; Κ; ) MATHEMATICAL ITALIC CAPITAL KAPPA
+1D6EC;1D6EC;1D6EC;039B;039B; # (𝛬𝛬; 𝛬𝛬; 𝛬𝛬; Λ; Λ; ) MATHEMATICAL ITALIC CAPITAL LAMDA
+1D6ED;1D6ED;1D6ED;039C;039C; # (𝛭𝛭; 𝛭𝛭; 𝛭𝛭; Μ; Μ; ) MATHEMATICAL ITALIC CAPITAL MU
+1D6EE;1D6EE;1D6EE;039D;039D; # (𝛮𝛮; 𝛮𝛮; 𝛮𝛮; Ν; Ν; ) MATHEMATICAL ITALIC CAPITAL NU
+1D6EF;1D6EF;1D6EF;039E;039E; # (𝛯𝛯; 𝛯𝛯; 𝛯𝛯; Ξ; Ξ; ) MATHEMATICAL ITALIC CAPITAL XI
+1D6F0;1D6F0;1D6F0;039F;039F; # (𝛰𝛰; 𝛰𝛰; 𝛰𝛰; Ο; Ο; ) MATHEMATICAL ITALIC CAPITAL OMICRON
+1D6F1;1D6F1;1D6F1;03A0;03A0; # (𝛱𝛱; 𝛱𝛱; 𝛱𝛱; Π; Π; ) MATHEMATICAL ITALIC CAPITAL PI
+1D6F2;1D6F2;1D6F2;03A1;03A1; # (𝛲𝛲; 𝛲𝛲; 𝛲𝛲; Ρ; Ρ; ) MATHEMATICAL ITALIC CAPITAL RHO
+1D6F3;1D6F3;1D6F3;0398;0398; # (𝛳𝛳; 𝛳𝛳; 𝛳𝛳; Θ; Θ; ) MATHEMATICAL ITALIC CAPITAL THETA SYMBOL
+1D6F4;1D6F4;1D6F4;03A3;03A3; # (𝛴𝛴; 𝛴𝛴; 𝛴𝛴; Σ; Σ; ) MATHEMATICAL ITALIC CAPITAL SIGMA
+1D6F5;1D6F5;1D6F5;03A4;03A4; # (𝛵𝛵; 𝛵𝛵; 𝛵𝛵; Τ; Τ; ) MATHEMATICAL ITALIC CAPITAL TAU
+1D6F6;1D6F6;1D6F6;03A5;03A5; # (𝛶𝛶; 𝛶𝛶; 𝛶𝛶; Υ; Υ; ) MATHEMATICAL ITALIC CAPITAL UPSILON
+1D6F7;1D6F7;1D6F7;03A6;03A6; # (𝛷𝛷; 𝛷𝛷; 𝛷𝛷; Φ; Φ; ) MATHEMATICAL ITALIC CAPITAL PHI
+1D6F8;1D6F8;1D6F8;03A7;03A7; # (𝛸𝛸; 𝛸𝛸; 𝛸𝛸; Χ; Χ; ) MATHEMATICAL ITALIC CAPITAL CHI
+1D6F9;1D6F9;1D6F9;03A8;03A8; # (𝛹𝛹; 𝛹𝛹; 𝛹𝛹; Ψ; Ψ; ) MATHEMATICAL ITALIC CAPITAL PSI
+1D6FA;1D6FA;1D6FA;03A9;03A9; # (𝛺𝛺; 𝛺𝛺; 𝛺𝛺; Ω; Ω; ) MATHEMATICAL ITALIC CAPITAL OMEGA
+1D6FB;1D6FB;1D6FB;2207;2207; # (𝛻𝛻; 𝛻𝛻; 𝛻𝛻; ∇; ∇; ) MATHEMATICAL ITALIC NABLA
+1D6FC;1D6FC;1D6FC;03B1;03B1; # (𝛼𝛼; 𝛼𝛼; 𝛼𝛼; α; α; ) MATHEMATICAL ITALIC SMALL ALPHA
+1D6FD;1D6FD;1D6FD;03B2;03B2; # (𝛽𝛽; 𝛽𝛽; 𝛽𝛽; β; β; ) MATHEMATICAL ITALIC SMALL BETA
+1D6FE;1D6FE;1D6FE;03B3;03B3; # (𝛾𝛾; 𝛾𝛾; 𝛾𝛾; γ; γ; ) MATHEMATICAL ITALIC SMALL GAMMA
+1D6FF;1D6FF;1D6FF;03B4;03B4; # (𝛿𝛿; 𝛿𝛿; 𝛿𝛿; δ; δ; ) MATHEMATICAL ITALIC SMALL DELTA
+1D700;1D700;1D700;03B5;03B5; # (𝜀𝜀; 𝜀𝜀; 𝜀𝜀; ε; ε; ) MATHEMATICAL ITALIC SMALL EPSILON
+1D701;1D701;1D701;03B6;03B6; # (𝜁𝜁; 𝜁𝜁; 𝜁𝜁; ζ; ζ; ) MATHEMATICAL ITALIC SMALL ZETA
+1D702;1D702;1D702;03B7;03B7; # (𝜂𝜂; 𝜂𝜂; 𝜂𝜂; η; η; ) MATHEMATICAL ITALIC SMALL ETA
+1D703;1D703;1D703;03B8;03B8; # (𝜃𝜃; 𝜃𝜃; 𝜃𝜃; θ; θ; ) MATHEMATICAL ITALIC SMALL THETA
+1D704;1D704;1D704;03B9;03B9; # (𝜄𝜄; 𝜄𝜄; 𝜄𝜄; ι; ι; ) MATHEMATICAL ITALIC SMALL IOTA
+1D705;1D705;1D705;03BA;03BA; # (𝜅𝜅; 𝜅𝜅; 𝜅𝜅; κ; κ; ) MATHEMATICAL ITALIC SMALL KAPPA
+1D706;1D706;1D706;03BB;03BB; # (𝜆𝜆; 𝜆𝜆; 𝜆𝜆; λ; λ; ) MATHEMATICAL ITALIC SMALL LAMDA
+1D707;1D707;1D707;03BC;03BC; # (𝜇𝜇; 𝜇𝜇; 𝜇𝜇; μ; μ; ) MATHEMATICAL ITALIC SMALL MU
+1D708;1D708;1D708;03BD;03BD; # (𝜈𝜈; 𝜈𝜈; 𝜈𝜈; ν; ν; ) MATHEMATICAL ITALIC SMALL NU
+1D709;1D709;1D709;03BE;03BE; # (𝜉𝜉; 𝜉𝜉; 𝜉𝜉; ξ; ξ; ) MATHEMATICAL ITALIC SMALL XI
+1D70A;1D70A;1D70A;03BF;03BF; # (𝜊𝜊; 𝜊𝜊; 𝜊𝜊; ο; ο; ) MATHEMATICAL ITALIC SMALL OMICRON
+1D70B;1D70B;1D70B;03C0;03C0; # (𝜋𝜋; 𝜋𝜋; 𝜋𝜋; π; π; ) MATHEMATICAL ITALIC SMALL PI
+1D70C;1D70C;1D70C;03C1;03C1; # (𝜌𝜌; 𝜌𝜌; 𝜌𝜌; ρ; ρ; ) MATHEMATICAL ITALIC SMALL RHO
+1D70D;1D70D;1D70D;03C2;03C2; # (𝜍𝜍; 𝜍𝜍; 𝜍𝜍; ς; ς; ) MATHEMATICAL ITALIC SMALL FINAL SIGMA
+1D70E;1D70E;1D70E;03C3;03C3; # (𝜎𝜎; 𝜎𝜎; 𝜎𝜎; σ; σ; ) MATHEMATICAL ITALIC SMALL SIGMA
+1D70F;1D70F;1D70F;03C4;03C4; # (𝜏𝜏; 𝜏𝜏; 𝜏𝜏; τ; τ; ) MATHEMATICAL ITALIC SMALL TAU
+1D710;1D710;1D710;03C5;03C5; # (𝜐𝜐; 𝜐𝜐; 𝜐𝜐; υ; υ; ) MATHEMATICAL ITALIC SMALL UPSILON
+1D711;1D711;1D711;03C6;03C6; # (𝜑𝜑; 𝜑𝜑; 𝜑𝜑; φ; φ; ) MATHEMATICAL ITALIC SMALL PHI
+1D712;1D712;1D712;03C7;03C7; # (𝜒𝜒; 𝜒𝜒; 𝜒𝜒; χ; χ; ) MATHEMATICAL ITALIC SMALL CHI
+1D713;1D713;1D713;03C8;03C8; # (𝜓𝜓; 𝜓𝜓; 𝜓𝜓; ψ; ψ; ) MATHEMATICAL ITALIC SMALL PSI
+1D714;1D714;1D714;03C9;03C9; # (𝜔𝜔; 𝜔𝜔; 𝜔𝜔; ω; ω; ) MATHEMATICAL ITALIC SMALL OMEGA
+1D715;1D715;1D715;2202;2202; # (𝜕𝜕; 𝜕𝜕; 𝜕𝜕; ∂; ∂; ) MATHEMATICAL ITALIC PARTIAL DIFFERENTIAL
+1D716;1D716;1D716;03B5;03B5; # (𝜖𝜖; 𝜖𝜖; 𝜖𝜖; ε; ε; ) MATHEMATICAL ITALIC EPSILON SYMBOL
+1D717;1D717;1D717;03B8;03B8; # (𝜗𝜗; 𝜗𝜗; 𝜗𝜗; θ; θ; ) MATHEMATICAL ITALIC THETA SYMBOL
+1D718;1D718;1D718;03BA;03BA; # (𝜘𝜘; 𝜘𝜘; 𝜘𝜘; κ; κ; ) MATHEMATICAL ITALIC KAPPA SYMBOL
+1D719;1D719;1D719;03C6;03C6; # (𝜙𝜙; 𝜙𝜙; 𝜙𝜙; φ; φ; ) MATHEMATICAL ITALIC PHI SYMBOL
+1D71A;1D71A;1D71A;03C1;03C1; # (𝜚𝜚; 𝜚𝜚; 𝜚𝜚; ρ; ρ; ) MATHEMATICAL ITALIC RHO SYMBOL
+1D71B;1D71B;1D71B;03C0;03C0; # (𝜛𝜛; 𝜛𝜛; 𝜛𝜛; π; π; ) MATHEMATICAL ITALIC PI SYMBOL
+1D71C;1D71C;1D71C;0391;0391; # (𝜜𝜜; 𝜜𝜜; 𝜜𝜜; Α; Α; ) MATHEMATICAL BOLD ITALIC CAPITAL ALPHA
+1D71D;1D71D;1D71D;0392;0392; # (𝜝𝜝; 𝜝𝜝; 𝜝𝜝; Β; Β; ) MATHEMATICAL BOLD ITALIC CAPITAL BETA
+1D71E;1D71E;1D71E;0393;0393; # (𝜞𝜞; 𝜞𝜞; 𝜞𝜞; Γ; Γ; ) MATHEMATICAL BOLD ITALIC CAPITAL GAMMA
+1D71F;1D71F;1D71F;0394;0394; # (𝜟𝜟; 𝜟𝜟; 𝜟𝜟; Δ; Δ; ) MATHEMATICAL BOLD ITALIC CAPITAL DELTA
+1D720;1D720;1D720;0395;0395; # (𝜠𝜠; 𝜠𝜠; 𝜠𝜠; Ε; Ε; ) MATHEMATICAL BOLD ITALIC CAPITAL EPSILON
+1D721;1D721;1D721;0396;0396; # (𝜡𝜡; 𝜡𝜡; 𝜡𝜡; Ζ; Ζ; ) MATHEMATICAL BOLD ITALIC CAPITAL ZETA
+1D722;1D722;1D722;0397;0397; # (𝜢𝜢; 𝜢𝜢; 𝜢𝜢; Η; Η; ) MATHEMATICAL BOLD ITALIC CAPITAL ETA
+1D723;1D723;1D723;0398;0398; # (𝜣𝜣; 𝜣𝜣; 𝜣𝜣; Θ; Θ; ) MATHEMATICAL BOLD ITALIC CAPITAL THETA
+1D724;1D724;1D724;0399;0399; # (𝜤𝜤; 𝜤𝜤; 𝜤𝜤; Ι; Ι; ) MATHEMATICAL BOLD ITALIC CAPITAL IOTA
+1D725;1D725;1D725;039A;039A; # (𝜥𝜥; 𝜥𝜥; 𝜥𝜥; Κ; Κ; ) MATHEMATICAL BOLD ITALIC CAPITAL KAPPA
+1D726;1D726;1D726;039B;039B; # (𝜦𝜦; 𝜦𝜦; 𝜦𝜦; Λ; Λ; ) MATHEMATICAL BOLD ITALIC CAPITAL LAMDA
+1D727;1D727;1D727;039C;039C; # (𝜧𝜧; 𝜧𝜧; 𝜧𝜧; Μ; Μ; ) MATHEMATICAL BOLD ITALIC CAPITAL MU
+1D728;1D728;1D728;039D;039D; # (𝜨𝜨; 𝜨𝜨; 𝜨𝜨; Ν; Ν; ) MATHEMATICAL BOLD ITALIC CAPITAL NU
+1D729;1D729;1D729;039E;039E; # (𝜩𝜩; 𝜩𝜩; 𝜩𝜩; Ξ; Ξ; ) MATHEMATICAL BOLD ITALIC CAPITAL XI
+1D72A;1D72A;1D72A;039F;039F; # (𝜪𝜪; 𝜪𝜪; 𝜪𝜪; Ο; Ο; ) MATHEMATICAL BOLD ITALIC CAPITAL OMICRON
+1D72B;1D72B;1D72B;03A0;03A0; # (𝜫𝜫; 𝜫𝜫; 𝜫𝜫; Π; Π; ) MATHEMATICAL BOLD ITALIC CAPITAL PI
+1D72C;1D72C;1D72C;03A1;03A1; # (𝜬𝜬; 𝜬𝜬; 𝜬𝜬; Ρ; Ρ; ) MATHEMATICAL BOLD ITALIC CAPITAL RHO
+1D72D;1D72D;1D72D;0398;0398; # (𝜭𝜭; 𝜭𝜭; 𝜭𝜭; Θ; Θ; ) MATHEMATICAL BOLD ITALIC CAPITAL THETA SYMBOL
+1D72E;1D72E;1D72E;03A3;03A3; # (𝜮𝜮; 𝜮𝜮; 𝜮𝜮; Σ; Σ; ) MATHEMATICAL BOLD ITALIC CAPITAL SIGMA
+1D72F;1D72F;1D72F;03A4;03A4; # (𝜯𝜯; 𝜯𝜯; 𝜯𝜯; Τ; Τ; ) MATHEMATICAL BOLD ITALIC CAPITAL TAU
+1D730;1D730;1D730;03A5;03A5; # (𝜰𝜰; 𝜰𝜰; 𝜰𝜰; Υ; Υ; ) MATHEMATICAL BOLD ITALIC CAPITAL UPSILON
+1D731;1D731;1D731;03A6;03A6; # (𝜱𝜱; 𝜱𝜱; 𝜱𝜱; Φ; Φ; ) MATHEMATICAL BOLD ITALIC CAPITAL PHI
+1D732;1D732;1D732;03A7;03A7; # (𝜲𝜲; 𝜲𝜲; 𝜲𝜲; Χ; Χ; ) MATHEMATICAL BOLD ITALIC CAPITAL CHI
+1D733;1D733;1D733;03A8;03A8; # (𝜳𝜳; 𝜳𝜳; 𝜳𝜳; Ψ; Ψ; ) MATHEMATICAL BOLD ITALIC CAPITAL PSI
+1D734;1D734;1D734;03A9;03A9; # (𝜴𝜴; 𝜴𝜴; 𝜴𝜴; Ω; Ω; ) MATHEMATICAL BOLD ITALIC CAPITAL OMEGA
+1D735;1D735;1D735;2207;2207; # (𝜵𝜵; 𝜵𝜵; 𝜵𝜵; ∇; ∇; ) MATHEMATICAL BOLD ITALIC NABLA
+1D736;1D736;1D736;03B1;03B1; # (𝜶𝜶; 𝜶𝜶; 𝜶𝜶; α; α; ) MATHEMATICAL BOLD ITALIC SMALL ALPHA
+1D737;1D737;1D737;03B2;03B2; # (𝜷𝜷; 𝜷𝜷; 𝜷𝜷; β; β; ) MATHEMATICAL BOLD ITALIC SMALL BETA
+1D738;1D738;1D738;03B3;03B3; # (𝜸𝜸; 𝜸𝜸; 𝜸𝜸; γ; γ; ) MATHEMATICAL BOLD ITALIC SMALL GAMMA
+1D739;1D739;1D739;03B4;03B4; # (𝜹𝜹; 𝜹𝜹; 𝜹𝜹; δ; δ; ) MATHEMATICAL BOLD ITALIC SMALL DELTA
+1D73A;1D73A;1D73A;03B5;03B5; # (𝜺𝜺; 𝜺𝜺; 𝜺𝜺; ε; ε; ) MATHEMATICAL BOLD ITALIC SMALL EPSILON
+1D73B;1D73B;1D73B;03B6;03B6; # (𝜻𝜻; 𝜻𝜻; 𝜻𝜻; ζ; ζ; ) MATHEMATICAL BOLD ITALIC SMALL ZETA
+1D73C;1D73C;1D73C;03B7;03B7; # (𝜼𝜼; 𝜼𝜼; 𝜼𝜼; η; η; ) MATHEMATICAL BOLD ITALIC SMALL ETA
+1D73D;1D73D;1D73D;03B8;03B8; # (𝜽𝜽; 𝜽𝜽; 𝜽𝜽; θ; θ; ) MATHEMATICAL BOLD ITALIC SMALL THETA
+1D73E;1D73E;1D73E;03B9;03B9; # (𝜾𝜾; 𝜾𝜾; 𝜾𝜾; ι; ι; ) MATHEMATICAL BOLD ITALIC SMALL IOTA
+1D73F;1D73F;1D73F;03BA;03BA; # (𝜿𝜿; 𝜿𝜿; 𝜿𝜿; κ; κ; ) MATHEMATICAL BOLD ITALIC SMALL KAPPA
+1D740;1D740;1D740;03BB;03BB; # (𝝀𝝀; 𝝀𝝀; 𝝀𝝀; λ; λ; ) MATHEMATICAL BOLD ITALIC SMALL LAMDA
+1D741;1D741;1D741;03BC;03BC; # (𝝁𝝁; 𝝁𝝁; 𝝁𝝁; μ; μ; ) MATHEMATICAL BOLD ITALIC SMALL MU
+1D742;1D742;1D742;03BD;03BD; # (𝝂𝝂; 𝝂𝝂; 𝝂𝝂; ν; ν; ) MATHEMATICAL BOLD ITALIC SMALL NU
+1D743;1D743;1D743;03BE;03BE; # (𝝃𝝃; 𝝃𝝃; 𝝃𝝃; ξ; ξ; ) MATHEMATICAL BOLD ITALIC SMALL XI
+1D744;1D744;1D744;03BF;03BF; # (𝝄𝝄; 𝝄𝝄; 𝝄𝝄; ο; ο; ) MATHEMATICAL BOLD ITALIC SMALL OMICRON
+1D745;1D745;1D745;03C0;03C0; # (𝝅𝝅; 𝝅𝝅; 𝝅𝝅; π; π; ) MATHEMATICAL BOLD ITALIC SMALL PI
+1D746;1D746;1D746;03C1;03C1; # (𝝆𝝆; 𝝆𝝆; 𝝆𝝆; ρ; ρ; ) MATHEMATICAL BOLD ITALIC SMALL RHO
+1D747;1D747;1D747;03C2;03C2; # (𝝇𝝇; 𝝇𝝇; 𝝇𝝇; ς; ς; ) MATHEMATICAL BOLD ITALIC SMALL FINAL SIGMA
+1D748;1D748;1D748;03C3;03C3; # (𝝈𝝈; 𝝈𝝈; 𝝈𝝈; σ; σ; ) MATHEMATICAL BOLD ITALIC SMALL SIGMA
+1D749;1D749;1D749;03C4;03C4; # (𝝉𝝉; 𝝉𝝉; 𝝉𝝉; τ; τ; ) MATHEMATICAL BOLD ITALIC SMALL TAU
+1D74A;1D74A;1D74A;03C5;03C5; # (𝝊𝝊; 𝝊𝝊; 𝝊𝝊; υ; υ; ) MATHEMATICAL BOLD ITALIC SMALL UPSILON
+1D74B;1D74B;1D74B;03C6;03C6; # (𝝋𝝋; 𝝋𝝋; 𝝋𝝋; φ; φ; ) MATHEMATICAL BOLD ITALIC SMALL PHI
+1D74C;1D74C;1D74C;03C7;03C7; # (𝝌𝝌; 𝝌𝝌; 𝝌𝝌; χ; χ; ) MATHEMATICAL BOLD ITALIC SMALL CHI
+1D74D;1D74D;1D74D;03C8;03C8; # (𝝍𝝍; 𝝍𝝍; 𝝍𝝍; ψ; ψ; ) MATHEMATICAL BOLD ITALIC SMALL PSI
+1D74E;1D74E;1D74E;03C9;03C9; # (𝝎𝝎; 𝝎𝝎; 𝝎𝝎; ω; ω; ) MATHEMATICAL BOLD ITALIC SMALL OMEGA
+1D74F;1D74F;1D74F;2202;2202; # (𝝏𝝏; 𝝏𝝏; 𝝏𝝏; ∂; ∂; ) MATHEMATICAL BOLD ITALIC PARTIAL DIFFERENTIAL
+1D750;1D750;1D750;03B5;03B5; # (𝝐𝝐; 𝝐𝝐; 𝝐𝝐; ε; ε; ) MATHEMATICAL BOLD ITALIC EPSILON SYMBOL
+1D751;1D751;1D751;03B8;03B8; # (𝝑𝝑; 𝝑𝝑; 𝝑𝝑; θ; θ; ) MATHEMATICAL BOLD ITALIC THETA SYMBOL
+1D752;1D752;1D752;03BA;03BA; # (𝝒𝝒; 𝝒𝝒; 𝝒𝝒; κ; κ; ) MATHEMATICAL BOLD ITALIC KAPPA SYMBOL
+1D753;1D753;1D753;03C6;03C6; # (𝝓𝝓; 𝝓𝝓; 𝝓𝝓; φ; φ; ) MATHEMATICAL BOLD ITALIC PHI SYMBOL
+1D754;1D754;1D754;03C1;03C1; # (𝝔𝝔; 𝝔𝝔; 𝝔𝝔; ρ; ρ; ) MATHEMATICAL BOLD ITALIC RHO SYMBOL
+1D755;1D755;1D755;03C0;03C0; # (𝝕𝝕; 𝝕𝝕; 𝝕𝝕; π; π; ) MATHEMATICAL BOLD ITALIC PI SYMBOL
+1D756;1D756;1D756;0391;0391; # (𝝖𝝖; 𝝖𝝖; 𝝖𝝖; Α; Α; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL ALPHA
+1D757;1D757;1D757;0392;0392; # (𝝗𝝗; 𝝗𝝗; 𝝗𝝗; Β; Β; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL BETA
+1D758;1D758;1D758;0393;0393; # (𝝘𝝘; 𝝘𝝘; 𝝘𝝘; Γ; Γ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL GAMMA
+1D759;1D759;1D759;0394;0394; # (𝝙𝝙; 𝝙𝝙; 𝝙𝝙; Δ; Δ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL DELTA
+1D75A;1D75A;1D75A;0395;0395; # (𝝚𝝚; 𝝚𝝚; 𝝚𝝚; Ε; Ε; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL EPSILON
+1D75B;1D75B;1D75B;0396;0396; # (𝝛𝝛; 𝝛𝝛; 𝝛𝝛; Ζ; Ζ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL ZETA
+1D75C;1D75C;1D75C;0397;0397; # (𝝜𝝜; 𝝜𝝜; 𝝜𝝜; Η; Η; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL ETA
+1D75D;1D75D;1D75D;0398;0398; # (𝝝𝝝; 𝝝𝝝; 𝝝𝝝; Θ; Θ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL THETA
+1D75E;1D75E;1D75E;0399;0399; # (𝝞𝝞; 𝝞𝝞; 𝝞𝝞; Ι; Ι; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL IOTA
+1D75F;1D75F;1D75F;039A;039A; # (𝝟𝝟; 𝝟𝝟; 𝝟𝝟; Κ; Κ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL KAPPA
+1D760;1D760;1D760;039B;039B; # (𝝠𝝠; 𝝠𝝠; 𝝠𝝠; Λ; Λ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL LAMDA
+1D761;1D761;1D761;039C;039C; # (𝝡𝝡; 𝝡𝝡; 𝝡𝝡; Μ; Μ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL MU
+1D762;1D762;1D762;039D;039D; # (𝝢𝝢; 𝝢𝝢; 𝝢𝝢; Ν; Ν; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL NU
+1D763;1D763;1D763;039E;039E; # (𝝣𝝣; 𝝣𝝣; 𝝣𝝣; Ξ; Ξ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL XI
+1D764;1D764;1D764;039F;039F; # (𝝤𝝤; 𝝤𝝤; 𝝤𝝤; Ο; Ο; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL OMICRON
+1D765;1D765;1D765;03A0;03A0; # (𝝥𝝥; 𝝥𝝥; 𝝥𝝥; Π; Π; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL PI
+1D766;1D766;1D766;03A1;03A1; # (𝝦𝝦; 𝝦𝝦; 𝝦𝝦; Ρ; Ρ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL RHO
+1D767;1D767;1D767;0398;0398; # (𝝧𝝧; 𝝧𝝧; 𝝧𝝧; Θ; Θ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL THETA SYMBOL
+1D768;1D768;1D768;03A3;03A3; # (𝝨𝝨; 𝝨𝝨; 𝝨𝝨; Σ; Σ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL SIGMA
+1D769;1D769;1D769;03A4;03A4; # (𝝩𝝩; 𝝩𝝩; 𝝩𝝩; Τ; Τ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL TAU
+1D76A;1D76A;1D76A;03A5;03A5; # (𝝪𝝪; 𝝪𝝪; 𝝪𝝪; Υ; Υ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL UPSILON
+1D76B;1D76B;1D76B;03A6;03A6; # (𝝫𝝫; 𝝫𝝫; 𝝫𝝫; Φ; Φ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL PHI
+1D76C;1D76C;1D76C;03A7;03A7; # (𝝬𝝬; 𝝬𝝬; 𝝬𝝬; Χ; Χ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL CHI
+1D76D;1D76D;1D76D;03A8;03A8; # (𝝭𝝭; 𝝭𝝭; 𝝭𝝭; Ψ; Ψ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL PSI
+1D76E;1D76E;1D76E;03A9;03A9; # (𝝮𝝮; 𝝮𝝮; 𝝮𝝮; Ω; Ω; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL OMEGA
+1D76F;1D76F;1D76F;2207;2207; # (𝝯𝝯; 𝝯𝝯; 𝝯𝝯; ∇; ∇; ) MATHEMATICAL SANS-SERIF BOLD NABLA
+1D770;1D770;1D770;03B1;03B1; # (𝝰𝝰; 𝝰𝝰; 𝝰𝝰; α; α; ) MATHEMATICAL SANS-SERIF BOLD SMALL ALPHA
+1D771;1D771;1D771;03B2;03B2; # (𝝱𝝱; 𝝱𝝱; 𝝱𝝱; β; β; ) MATHEMATICAL SANS-SERIF BOLD SMALL BETA
+1D772;1D772;1D772;03B3;03B3; # (𝝲𝝲; 𝝲𝝲; 𝝲𝝲; γ; γ; ) MATHEMATICAL SANS-SERIF BOLD SMALL GAMMA
+1D773;1D773;1D773;03B4;03B4; # (𝝳𝝳; 𝝳𝝳; 𝝳𝝳; δ; δ; ) MATHEMATICAL SANS-SERIF BOLD SMALL DELTA
+1D774;1D774;1D774;03B5;03B5; # (𝝴𝝴; 𝝴𝝴; 𝝴𝝴; ε; ε; ) MATHEMATICAL SANS-SERIF BOLD SMALL EPSILON
+1D775;1D775;1D775;03B6;03B6; # (𝝵𝝵; 𝝵𝝵; 𝝵𝝵; ζ; ζ; ) MATHEMATICAL SANS-SERIF BOLD SMALL ZETA
+1D776;1D776;1D776;03B7;03B7; # (𝝶𝝶; 𝝶𝝶; 𝝶𝝶; η; η; ) MATHEMATICAL SANS-SERIF BOLD SMALL ETA
+1D777;1D777;1D777;03B8;03B8; # (𝝷𝝷; 𝝷𝝷; 𝝷𝝷; θ; θ; ) MATHEMATICAL SANS-SERIF BOLD SMALL THETA
+1D778;1D778;1D778;03B9;03B9; # (𝝸𝝸; 𝝸𝝸; 𝝸𝝸; ι; ι; ) MATHEMATICAL SANS-SERIF BOLD SMALL IOTA
+1D779;1D779;1D779;03BA;03BA; # (𝝹𝝹; 𝝹𝝹; 𝝹𝝹; κ; κ; ) MATHEMATICAL SANS-SERIF BOLD SMALL KAPPA
+1D77A;1D77A;1D77A;03BB;03BB; # (𝝺𝝺; 𝝺𝝺; 𝝺𝝺; λ; λ; ) MATHEMATICAL SANS-SERIF BOLD SMALL LAMDA
+1D77B;1D77B;1D77B;03BC;03BC; # (𝝻𝝻; 𝝻𝝻; 𝝻𝝻; μ; μ; ) MATHEMATICAL SANS-SERIF BOLD SMALL MU
+1D77C;1D77C;1D77C;03BD;03BD; # (𝝼𝝼; 𝝼𝝼; 𝝼𝝼; ν; ν; ) MATHEMATICAL SANS-SERIF BOLD SMALL NU
+1D77D;1D77D;1D77D;03BE;03BE; # (𝝽𝝽; 𝝽𝝽; 𝝽𝝽; ξ; ξ; ) MATHEMATICAL SANS-SERIF BOLD SMALL XI
+1D77E;1D77E;1D77E;03BF;03BF; # (𝝾𝝾; 𝝾𝝾; 𝝾𝝾; ο; ο; ) MATHEMATICAL SANS-SERIF BOLD SMALL OMICRON
+1D77F;1D77F;1D77F;03C0;03C0; # (𝝿𝝿; 𝝿𝝿; 𝝿𝝿; π; π; ) MATHEMATICAL SANS-SERIF BOLD SMALL PI
+1D780;1D780;1D780;03C1;03C1; # (𝞀𝞀; 𝞀𝞀; 𝞀𝞀; ρ; ρ; ) MATHEMATICAL SANS-SERIF BOLD SMALL RHO
+1D781;1D781;1D781;03C2;03C2; # (𝞁𝞁; 𝞁𝞁; 𝞁𝞁; ς; ς; ) MATHEMATICAL SANS-SERIF BOLD SMALL FINAL SIGMA
+1D782;1D782;1D782;03C3;03C3; # (𝞂𝞂; 𝞂𝞂; 𝞂𝞂; σ; σ; ) MATHEMATICAL SANS-SERIF BOLD SMALL SIGMA
+1D783;1D783;1D783;03C4;03C4; # (𝞃𝞃; 𝞃𝞃; 𝞃𝞃; τ; τ; ) MATHEMATICAL SANS-SERIF BOLD SMALL TAU
+1D784;1D784;1D784;03C5;03C5; # (𝞄𝞄; 𝞄𝞄; 𝞄𝞄; υ; υ; ) MATHEMATICAL SANS-SERIF BOLD SMALL UPSILON
+1D785;1D785;1D785;03C6;03C6; # (𝞅𝞅; 𝞅𝞅; 𝞅𝞅; φ; φ; ) MATHEMATICAL SANS-SERIF BOLD SMALL PHI
+1D786;1D786;1D786;03C7;03C7; # (𝞆𝞆; 𝞆𝞆; 𝞆𝞆; χ; χ; ) MATHEMATICAL SANS-SERIF BOLD SMALL CHI
+1D787;1D787;1D787;03C8;03C8; # (𝞇𝞇; 𝞇𝞇; 𝞇𝞇; ψ; ψ; ) MATHEMATICAL SANS-SERIF BOLD SMALL PSI
+1D788;1D788;1D788;03C9;03C9; # (𝞈𝞈; 𝞈𝞈; 𝞈𝞈; ω; ω; ) MATHEMATICAL SANS-SERIF BOLD SMALL OMEGA
+1D789;1D789;1D789;2202;2202; # (𝞉𝞉; 𝞉𝞉; 𝞉𝞉; ∂; ∂; ) MATHEMATICAL SANS-SERIF BOLD PARTIAL DIFFERENTIAL
+1D78A;1D78A;1D78A;03B5;03B5; # (𝞊𝞊; 𝞊𝞊; 𝞊𝞊; ε; ε; ) MATHEMATICAL SANS-SERIF BOLD EPSILON SYMBOL
+1D78B;1D78B;1D78B;03B8;03B8; # (𝞋𝞋; 𝞋𝞋; 𝞋𝞋; θ; θ; ) MATHEMATICAL SANS-SERIF BOLD THETA SYMBOL
+1D78C;1D78C;1D78C;03BA;03BA; # (𝞌𝞌; 𝞌𝞌; 𝞌𝞌; κ; κ; ) MATHEMATICAL SANS-SERIF BOLD KAPPA SYMBOL
+1D78D;1D78D;1D78D;03C6;03C6; # (𝞍𝞍; 𝞍𝞍; 𝞍𝞍; φ; φ; ) MATHEMATICAL SANS-SERIF BOLD PHI SYMBOL
+1D78E;1D78E;1D78E;03C1;03C1; # (𝞎𝞎; 𝞎𝞎; 𝞎𝞎; ρ; ρ; ) MATHEMATICAL SANS-SERIF BOLD RHO SYMBOL
+1D78F;1D78F;1D78F;03C0;03C0; # (𝞏𝞏; 𝞏𝞏; 𝞏𝞏; π; π; ) MATHEMATICAL SANS-SERIF BOLD PI SYMBOL
+1D790;1D790;1D790;0391;0391; # (𝞐𝞐; 𝞐𝞐; 𝞐𝞐; Α; Α; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ALPHA
+1D791;1D791;1D791;0392;0392; # (𝞑𝞑; 𝞑𝞑; 𝞑𝞑; Β; Β; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL BETA
+1D792;1D792;1D792;0393;0393; # (𝞒𝞒; 𝞒𝞒; 𝞒𝞒; Γ; Γ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL GAMMA
+1D793;1D793;1D793;0394;0394; # (𝞓𝞓; 𝞓𝞓; 𝞓𝞓; Δ; Δ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL DELTA
+1D794;1D794;1D794;0395;0395; # (𝞔𝞔; 𝞔𝞔; 𝞔𝞔; Ε; Ε; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL EPSILON
+1D795;1D795;1D795;0396;0396; # (𝞕𝞕; 𝞕𝞕; 𝞕𝞕; Ζ; Ζ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ZETA
+1D796;1D796;1D796;0397;0397; # (𝞖𝞖; 𝞖𝞖; 𝞖𝞖; Η; Η; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ETA
+1D797;1D797;1D797;0398;0398; # (𝞗𝞗; 𝞗𝞗; 𝞗𝞗; Θ; Θ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL THETA
+1D798;1D798;1D798;0399;0399; # (𝞘𝞘; 𝞘𝞘; 𝞘𝞘; Ι; Ι; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL IOTA
+1D799;1D799;1D799;039A;039A; # (𝞙𝞙; 𝞙𝞙; 𝞙𝞙; Κ; Κ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL KAPPA
+1D79A;1D79A;1D79A;039B;039B; # (𝞚𝞚; 𝞚𝞚; 𝞚𝞚; Λ; Λ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL LAMDA
+1D79B;1D79B;1D79B;039C;039C; # (𝞛𝞛; 𝞛𝞛; 𝞛𝞛; Μ; Μ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL MU
+1D79C;1D79C;1D79C;039D;039D; # (𝞜𝞜; 𝞜𝞜; 𝞜𝞜; Ν; Ν; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL NU
+1D79D;1D79D;1D79D;039E;039E; # (𝞝𝞝; 𝞝𝞝; 𝞝𝞝; Ξ; Ξ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL XI
+1D79E;1D79E;1D79E;039F;039F; # (𝞞𝞞; 𝞞𝞞; 𝞞𝞞; Ο; Ο; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL OMICRON
+1D79F;1D79F;1D79F;03A0;03A0; # (𝞟𝞟; 𝞟𝞟; 𝞟𝞟; Π; Π; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PI
+1D7A0;1D7A0;1D7A0;03A1;03A1; # (𝞠𝞠; 𝞠𝞠; 𝞠𝞠; Ρ; Ρ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL RHO
+1D7A1;1D7A1;1D7A1;0398;0398; # (𝞡𝞡; 𝞡𝞡; 𝞡𝞡; Θ; Θ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL THETA SYMBOL
+1D7A2;1D7A2;1D7A2;03A3;03A3; # (𝞢𝞢; 𝞢𝞢; 𝞢𝞢; Σ; Σ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL SIGMA
+1D7A3;1D7A3;1D7A3;03A4;03A4; # (𝞣𝞣; 𝞣𝞣; 𝞣𝞣; Τ; Τ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL TAU
+1D7A4;1D7A4;1D7A4;03A5;03A5; # (𝞤𝞤; 𝞤𝞤; 𝞤𝞤; Υ; Υ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL UPSILON
+1D7A5;1D7A5;1D7A5;03A6;03A6; # (𝞥𝞥; 𝞥𝞥; 𝞥𝞥; Φ; Φ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PHI
+1D7A6;1D7A6;1D7A6;03A7;03A7; # (𝞦𝞦; 𝞦𝞦; 𝞦𝞦; Χ; Χ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL CHI
+1D7A7;1D7A7;1D7A7;03A8;03A8; # (𝞧𝞧; 𝞧𝞧; 𝞧𝞧; Ψ; Ψ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PSI
+1D7A8;1D7A8;1D7A8;03A9;03A9; # (𝞨𝞨; 𝞨𝞨; 𝞨𝞨; Ω; Ω; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL OMEGA
+1D7A9;1D7A9;1D7A9;2207;2207; # (𝞩𝞩; 𝞩𝞩; 𝞩𝞩; ∇; ∇; ) MATHEMATICAL SANS-SERIF BOLD ITALIC NABLA
+1D7AA;1D7AA;1D7AA;03B1;03B1; # (𝞪𝞪; 𝞪𝞪; 𝞪𝞪; α; α; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ALPHA
+1D7AB;1D7AB;1D7AB;03B2;03B2; # (𝞫𝞫; 𝞫𝞫; 𝞫𝞫; β; β; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL BETA
+1D7AC;1D7AC;1D7AC;03B3;03B3; # (𝞬𝞬; 𝞬𝞬; 𝞬𝞬; γ; γ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL GAMMA
+1D7AD;1D7AD;1D7AD;03B4;03B4; # (𝞭𝞭; 𝞭𝞭; 𝞭𝞭; δ; δ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL DELTA
+1D7AE;1D7AE;1D7AE;03B5;03B5; # (𝞮𝞮; 𝞮𝞮; 𝞮𝞮; ε; ε; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL EPSILON
+1D7AF;1D7AF;1D7AF;03B6;03B6; # (𝞯𝞯; 𝞯𝞯; 𝞯𝞯; ζ; ζ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ZETA
+1D7B0;1D7B0;1D7B0;03B7;03B7; # (𝞰𝞰; 𝞰𝞰; 𝞰𝞰; η; η; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ETA
+1D7B1;1D7B1;1D7B1;03B8;03B8; # (𝞱𝞱; 𝞱𝞱; 𝞱𝞱; θ; θ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL THETA
+1D7B2;1D7B2;1D7B2;03B9;03B9; # (𝞲𝞲; 𝞲𝞲; 𝞲𝞲; ι; ι; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL IOTA
+1D7B3;1D7B3;1D7B3;03BA;03BA; # (𝞳𝞳; 𝞳𝞳; 𝞳𝞳; κ; κ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL KAPPA
+1D7B4;1D7B4;1D7B4;03BB;03BB; # (𝞴𝞴; 𝞴𝞴; 𝞴𝞴; λ; λ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL LAMDA
+1D7B5;1D7B5;1D7B5;03BC;03BC; # (𝞵𝞵; 𝞵𝞵; 𝞵𝞵; μ; μ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL MU
+1D7B6;1D7B6;1D7B6;03BD;03BD; # (𝞶𝞶; 𝞶𝞶; 𝞶𝞶; ν; ν; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL NU
+1D7B7;1D7B7;1D7B7;03BE;03BE; # (𝞷𝞷; 𝞷𝞷; 𝞷𝞷; ξ; ξ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL XI
+1D7B8;1D7B8;1D7B8;03BF;03BF; # (𝞸𝞸; 𝞸𝞸; 𝞸𝞸; ο; ο; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL OMICRON
+1D7B9;1D7B9;1D7B9;03C0;03C0; # (𝞹𝞹; 𝞹𝞹; 𝞹𝞹; π; π; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL PI
+1D7BA;1D7BA;1D7BA;03C1;03C1; # (𝞺𝞺; 𝞺𝞺; 𝞺𝞺; ρ; ρ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL RHO
+1D7BB;1D7BB;1D7BB;03C2;03C2; # (𝞻𝞻; 𝞻𝞻; 𝞻𝞻; ς; ς; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL FINAL SIGMA
+1D7BC;1D7BC;1D7BC;03C3;03C3; # (𝞼𝞼; 𝞼𝞼; 𝞼𝞼; σ; σ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL SIGMA
+1D7BD;1D7BD;1D7BD;03C4;03C4; # (𝞽𝞽; 𝞽𝞽; 𝞽𝞽; τ; τ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL TAU
+1D7BE;1D7BE;1D7BE;03C5;03C5; # (𝞾𝞾; 𝞾𝞾; 𝞾𝞾; υ; υ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL UPSILON
+1D7BF;1D7BF;1D7BF;03C6;03C6; # (𝞿𝞿; 𝞿𝞿; 𝞿𝞿; φ; φ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL PHI
+1D7C0;1D7C0;1D7C0;03C7;03C7; # (𝟀𝟀; 𝟀𝟀; 𝟀𝟀; χ; χ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL CHI
+1D7C1;1D7C1;1D7C1;03C8;03C8; # (𝟁𝟁; 𝟁𝟁; 𝟁𝟁; ψ; ψ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL PSI
+1D7C2;1D7C2;1D7C2;03C9;03C9; # (𝟂𝟂; 𝟂𝟂; 𝟂𝟂; ω; ω; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL OMEGA
+1D7C3;1D7C3;1D7C3;2202;2202; # (𝟃𝟃; 𝟃𝟃; 𝟃𝟃; ∂; ∂; ) MATHEMATICAL SANS-SERIF BOLD ITALIC PARTIAL DIFFERENTIAL
+1D7C4;1D7C4;1D7C4;03B5;03B5; # (𝟄𝟄; 𝟄𝟄; 𝟄𝟄; ε; ε; ) MATHEMATICAL SANS-SERIF BOLD ITALIC EPSILON SYMBOL
+1D7C5;1D7C5;1D7C5;03B8;03B8; # (𝟅𝟅; 𝟅𝟅; 𝟅𝟅; θ; θ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC THETA SYMBOL
+1D7C6;1D7C6;1D7C6;03BA;03BA; # (𝟆𝟆; 𝟆𝟆; 𝟆𝟆; κ; κ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC KAPPA SYMBOL
+1D7C7;1D7C7;1D7C7;03C6;03C6; # (𝟇𝟇; 𝟇𝟇; 𝟇𝟇; φ; φ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC PHI SYMBOL
+1D7C8;1D7C8;1D7C8;03C1;03C1; # (𝟈𝟈; 𝟈𝟈; 𝟈𝟈; ρ; ρ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC RHO SYMBOL
+1D7C9;1D7C9;1D7C9;03C0;03C0; # (𝟉𝟉; 𝟉𝟉; 𝟉𝟉; π; π; ) MATHEMATICAL SANS-SERIF BOLD ITALIC PI SYMBOL
+1D7CE;1D7CE;1D7CE;0030;0030; # (𝟎𝟎; 𝟎𝟎; 𝟎𝟎; 0; 0; ) MATHEMATICAL BOLD DIGIT ZERO
+1D7CF;1D7CF;1D7CF;0031;0031; # (𝟏𝟏; 𝟏𝟏; 𝟏𝟏; 1; 1; ) MATHEMATICAL BOLD DIGIT ONE
+1D7D0;1D7D0;1D7D0;0032;0032; # (𝟐𝟐; 𝟐𝟐; 𝟐𝟐; 2; 2; ) MATHEMATICAL BOLD DIGIT TWO
+1D7D1;1D7D1;1D7D1;0033;0033; # (𝟑𝟑; 𝟑𝟑; 𝟑𝟑; 3; 3; ) MATHEMATICAL BOLD DIGIT THREE
+1D7D2;1D7D2;1D7D2;0034;0034; # (𝟒𝟒; 𝟒𝟒; 𝟒𝟒; 4; 4; ) MATHEMATICAL BOLD DIGIT FOUR
+1D7D3;1D7D3;1D7D3;0035;0035; # (𝟓𝟓; 𝟓𝟓; 𝟓𝟓; 5; 5; ) MATHEMATICAL BOLD DIGIT FIVE
+1D7D4;1D7D4;1D7D4;0036;0036; # (𝟔𝟔; 𝟔𝟔; 𝟔𝟔; 6; 6; ) MATHEMATICAL BOLD DIGIT SIX
+1D7D5;1D7D5;1D7D5;0037;0037; # (𝟕𝟕; 𝟕𝟕; 𝟕𝟕; 7; 7; ) MATHEMATICAL BOLD DIGIT SEVEN
+1D7D6;1D7D6;1D7D6;0038;0038; # (𝟖𝟖; 𝟖𝟖; 𝟖𝟖; 8; 8; ) MATHEMATICAL BOLD DIGIT EIGHT
+1D7D7;1D7D7;1D7D7;0039;0039; # (𝟗𝟗; 𝟗𝟗; 𝟗𝟗; 9; 9; ) MATHEMATICAL BOLD DIGIT NINE
+1D7D8;1D7D8;1D7D8;0030;0030; # (𝟘𝟘; 𝟘𝟘; 𝟘𝟘; 0; 0; ) MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO
+1D7D9;1D7D9;1D7D9;0031;0031; # (𝟙𝟙; 𝟙𝟙; 𝟙𝟙; 1; 1; ) MATHEMATICAL DOUBLE-STRUCK DIGIT ONE
+1D7DA;1D7DA;1D7DA;0032;0032; # (𝟚𝟚; 𝟚𝟚; 𝟚𝟚; 2; 2; ) MATHEMATICAL DOUBLE-STRUCK DIGIT TWO
+1D7DB;1D7DB;1D7DB;0033;0033; # (𝟛𝟛; 𝟛𝟛; 𝟛𝟛; 3; 3; ) MATHEMATICAL DOUBLE-STRUCK DIGIT THREE
+1D7DC;1D7DC;1D7DC;0034;0034; # (𝟜𝟜; 𝟜𝟜; 𝟜𝟜; 4; 4; ) MATHEMATICAL DOUBLE-STRUCK DIGIT FOUR
+1D7DD;1D7DD;1D7DD;0035;0035; # (𝟝𝟝; 𝟝𝟝; 𝟝𝟝; 5; 5; ) MATHEMATICAL DOUBLE-STRUCK DIGIT FIVE
+1D7DE;1D7DE;1D7DE;0036;0036; # (𝟞𝟞; 𝟞𝟞; 𝟞𝟞; 6; 6; ) MATHEMATICAL DOUBLE-STRUCK DIGIT SIX
+1D7DF;1D7DF;1D7DF;0037;0037; # (𝟟𝟟; 𝟟𝟟; 𝟟𝟟; 7; 7; ) MATHEMATICAL DOUBLE-STRUCK DIGIT SEVEN
+1D7E0;1D7E0;1D7E0;0038;0038; # (𝟠𝟠; 𝟠𝟠; 𝟠𝟠; 8; 8; ) MATHEMATICAL DOUBLE-STRUCK DIGIT EIGHT
+1D7E1;1D7E1;1D7E1;0039;0039; # (𝟡𝟡; 𝟡𝟡; 𝟡𝟡; 9; 9; ) MATHEMATICAL DOUBLE-STRUCK DIGIT NINE
+1D7E2;1D7E2;1D7E2;0030;0030; # (𝟢𝟢; 𝟢𝟢; 𝟢𝟢; 0; 0; ) MATHEMATICAL SANS-SERIF DIGIT ZERO
+1D7E3;1D7E3;1D7E3;0031;0031; # (𝟣𝟣; 𝟣𝟣; 𝟣𝟣; 1; 1; ) MATHEMATICAL SANS-SERIF DIGIT ONE
+1D7E4;1D7E4;1D7E4;0032;0032; # (𝟤𝟤; 𝟤𝟤; 𝟤𝟤; 2; 2; ) MATHEMATICAL SANS-SERIF DIGIT TWO
+1D7E5;1D7E5;1D7E5;0033;0033; # (𝟥𝟥; 𝟥𝟥; 𝟥𝟥; 3; 3; ) MATHEMATICAL SANS-SERIF DIGIT THREE
+1D7E6;1D7E6;1D7E6;0034;0034; # (𝟦𝟦; 𝟦𝟦; 𝟦𝟦; 4; 4; ) MATHEMATICAL SANS-SERIF DIGIT FOUR
+1D7E7;1D7E7;1D7E7;0035;0035; # (𝟧𝟧; 𝟧𝟧; 𝟧𝟧; 5; 5; ) MATHEMATICAL SANS-SERIF DIGIT FIVE
+1D7E8;1D7E8;1D7E8;0036;0036; # (𝟨𝟨; 𝟨𝟨; 𝟨𝟨; 6; 6; ) MATHEMATICAL SANS-SERIF DIGIT SIX
+1D7E9;1D7E9;1D7E9;0037;0037; # (𝟩𝟩; 𝟩𝟩; 𝟩𝟩; 7; 7; ) MATHEMATICAL SANS-SERIF DIGIT SEVEN
+1D7EA;1D7EA;1D7EA;0038;0038; # (𝟪𝟪; 𝟪𝟪; 𝟪𝟪; 8; 8; ) MATHEMATICAL SANS-SERIF DIGIT EIGHT
+1D7EB;1D7EB;1D7EB;0039;0039; # (𝟫𝟫; 𝟫𝟫; 𝟫𝟫; 9; 9; ) MATHEMATICAL SANS-SERIF DIGIT NINE
+1D7EC;1D7EC;1D7EC;0030;0030; # (𝟬𝟬; 𝟬𝟬; 𝟬𝟬; 0; 0; ) MATHEMATICAL SANS-SERIF BOLD DIGIT ZERO
+1D7ED;1D7ED;1D7ED;0031;0031; # (𝟭𝟭; 𝟭𝟭; 𝟭𝟭; 1; 1; ) MATHEMATICAL SANS-SERIF BOLD DIGIT ONE
+1D7EE;1D7EE;1D7EE;0032;0032; # (𝟮𝟮; 𝟮𝟮; 𝟮𝟮; 2; 2; ) MATHEMATICAL SANS-SERIF BOLD DIGIT TWO
+1D7EF;1D7EF;1D7EF;0033;0033; # (𝟯𝟯; 𝟯𝟯; 𝟯𝟯; 3; 3; ) MATHEMATICAL SANS-SERIF BOLD DIGIT THREE
+1D7F0;1D7F0;1D7F0;0034;0034; # (𝟰𝟰; 𝟰𝟰; 𝟰𝟰; 4; 4; ) MATHEMATICAL SANS-SERIF BOLD DIGIT FOUR
+1D7F1;1D7F1;1D7F1;0035;0035; # (𝟱𝟱; 𝟱𝟱; 𝟱𝟱; 5; 5; ) MATHEMATICAL SANS-SERIF BOLD DIGIT FIVE
+1D7F2;1D7F2;1D7F2;0036;0036; # (𝟲𝟲; 𝟲𝟲; 𝟲𝟲; 6; 6; ) MATHEMATICAL SANS-SERIF BOLD DIGIT SIX
+1D7F3;1D7F3;1D7F3;0037;0037; # (𝟳𝟳; 𝟳𝟳; 𝟳𝟳; 7; 7; ) MATHEMATICAL SANS-SERIF BOLD DIGIT SEVEN
+1D7F4;1D7F4;1D7F4;0038;0038; # (𝟴𝟴; 𝟴𝟴; 𝟴𝟴; 8; 8; ) MATHEMATICAL SANS-SERIF BOLD DIGIT EIGHT
+1D7F5;1D7F5;1D7F5;0039;0039; # (𝟵𝟵; 𝟵𝟵; 𝟵𝟵; 9; 9; ) MATHEMATICAL SANS-SERIF BOLD DIGIT NINE
+1D7F6;1D7F6;1D7F6;0030;0030; # (𝟶𝟶; 𝟶𝟶; 𝟶𝟶; 0; 0; ) MATHEMATICAL MONOSPACE DIGIT ZERO
+1D7F7;1D7F7;1D7F7;0031;0031; # (𝟷𝟷; 𝟷𝟷; 𝟷𝟷; 1; 1; ) MATHEMATICAL MONOSPACE DIGIT ONE
+1D7F8;1D7F8;1D7F8;0032;0032; # (𝟸𝟸; 𝟸𝟸; 𝟸𝟸; 2; 2; ) MATHEMATICAL MONOSPACE DIGIT TWO
+1D7F9;1D7F9;1D7F9;0033;0033; # (𝟹𝟹; 𝟹𝟹; 𝟹𝟹; 3; 3; ) MATHEMATICAL MONOSPACE DIGIT THREE
+1D7FA;1D7FA;1D7FA;0034;0034; # (𝟺𝟺; 𝟺𝟺; 𝟺𝟺; 4; 4; ) MATHEMATICAL MONOSPACE DIGIT FOUR
+1D7FB;1D7FB;1D7FB;0035;0035; # (𝟻𝟻; 𝟻𝟻; 𝟻𝟻; 5; 5; ) MATHEMATICAL MONOSPACE DIGIT FIVE
+1D7FC;1D7FC;1D7FC;0036;0036; # (𝟼𝟼; 𝟼𝟼; 𝟼𝟼; 6; 6; ) MATHEMATICAL MONOSPACE DIGIT SIX
+1D7FD;1D7FD;1D7FD;0037;0037; # (𝟽𝟽; 𝟽𝟽; 𝟽𝟽; 7; 7; ) MATHEMATICAL MONOSPACE DIGIT SEVEN
+1D7FE;1D7FE;1D7FE;0038;0038; # (𝟾𝟾; 𝟾𝟾; 𝟾𝟾; 8; 8; ) MATHEMATICAL MONOSPACE DIGIT EIGHT
+1D7FF;1D7FF;1D7FF;0039;0039; # (𝟿𝟿; 𝟿𝟿; 𝟿𝟿; 9; 9; ) MATHEMATICAL MONOSPACE DIGIT NINE
+2F800;4E3D;4E3D;4E3D;4E3D; # (丽丽; 丽; 丽; 丽; 丽; ) CJK COMPATIBILITY IDEOGRAPH-2F800
+2F801;4E38;4E38;4E38;4E38; # (丸丸; 丸; 丸; 丸; 丸; ) CJK COMPATIBILITY IDEOGRAPH-2F801
+2F802;4E41;4E41;4E41;4E41; # (乁乁; 乁; 乁; 乁; 乁; ) CJK COMPATIBILITY IDEOGRAPH-2F802
+2F803;20122;20122;20122;20122; # (𠄢𠄢; 𠄢𠄢; 𠄢𠄢; 𠄢𠄢; 𠄢𠄢; ) CJK COMPATIBILITY IDEOGRAPH-2F803
+2F804;4F60;4F60;4F60;4F60; # (你你; 你; 你; 你; 你; ) CJK COMPATIBILITY IDEOGRAPH-2F804
+2F805;4FAE;4FAE;4FAE;4FAE; # (侮侮; 侮; 侮; 侮; 侮; ) CJK COMPATIBILITY IDEOGRAPH-2F805
+2F806;4FBB;4FBB;4FBB;4FBB; # (侻侻; 侻; 侻; 侻; 侻; ) CJK COMPATIBILITY IDEOGRAPH-2F806
+2F807;5002;5002;5002;5002; # (倂倂; 倂; 倂; 倂; 倂; ) CJK COMPATIBILITY IDEOGRAPH-2F807
+2F808;507A;507A;507A;507A; # (偺偺; 偺; 偺; 偺; 偺; ) CJK COMPATIBILITY IDEOGRAPH-2F808
+2F809;5099;5099;5099;5099; # (備備; 備; 備; 備; 備; ) CJK COMPATIBILITY IDEOGRAPH-2F809
+2F80A;50E7;50E7;50E7;50E7; # (僧僧; 僧; 僧; 僧; 僧; ) CJK COMPATIBILITY IDEOGRAPH-2F80A
+2F80B;50CF;50CF;50CF;50CF; # (像像; 像; 像; 像; 像; ) CJK COMPATIBILITY IDEOGRAPH-2F80B
+2F80C;349E;349E;349E;349E; # (㒞㒞; 㒞; 㒞; 㒞; 㒞; ) CJK COMPATIBILITY IDEOGRAPH-2F80C
+2F80D;2063A;2063A;2063A;2063A; # (𠘺𠘺; 𠘺𠘺; 𠘺𠘺; 𠘺𠘺; 𠘺𠘺; ) CJK COMPATIBILITY IDEOGRAPH-2F80D
+2F80E;514D;514D;514D;514D; # (免免; 免; 免; 免; 免; ) CJK COMPATIBILITY IDEOGRAPH-2F80E
+2F80F;5154;5154;5154;5154; # (兔兔; 兔; 兔; 兔; 兔; ) CJK COMPATIBILITY IDEOGRAPH-2F80F
+2F810;5164;5164;5164;5164; # (兤兤; 兤; 兤; 兤; 兤; ) CJK COMPATIBILITY IDEOGRAPH-2F810
+2F811;5177;5177;5177;5177; # (具具; 具; 具; 具; 具; ) CJK COMPATIBILITY IDEOGRAPH-2F811
+2F812;2051C;2051C;2051C;2051C; # (𠔜𠔜; 𠔜𠔜; 𠔜𠔜; 𠔜𠔜; 𠔜𠔜; ) CJK COMPATIBILITY IDEOGRAPH-2F812
+2F813;34B9;34B9;34B9;34B9; # (㒹㒹; 㒹; 㒹; 㒹; 㒹; ) CJK COMPATIBILITY IDEOGRAPH-2F813
+2F814;5167;5167;5167;5167; # (內內; 內; 內; 內; 內; ) CJK COMPATIBILITY IDEOGRAPH-2F814
+2F815;518D;518D;518D;518D; # (再再; 再; 再; 再; 再; ) CJK COMPATIBILITY IDEOGRAPH-2F815
+2F816;2054B;2054B;2054B;2054B; # (𠕋𠕋; 𠕋𠕋; 𠕋𠕋; 𠕋𠕋; 𠕋𠕋; ) CJK COMPATIBILITY IDEOGRAPH-2F816
+2F817;5197;5197;5197;5197; # (冗冗; 冗; 冗; 冗; 冗; ) CJK COMPATIBILITY IDEOGRAPH-2F817
+2F818;51A4;51A4;51A4;51A4; # (冤冤; 冤; 冤; 冤; 冤; ) CJK COMPATIBILITY IDEOGRAPH-2F818
+2F819;4ECC;4ECC;4ECC;4ECC; # (仌仌; 仌; 仌; 仌; 仌; ) CJK COMPATIBILITY IDEOGRAPH-2F819
+2F81A;51AC;51AC;51AC;51AC; # (冬冬; 冬; 冬; 冬; 冬; ) CJK COMPATIBILITY IDEOGRAPH-2F81A
+2F81B;51B5;51B5;51B5;51B5; # (况况; 况; 况; 况; 况; ) CJK COMPATIBILITY IDEOGRAPH-2F81B
+2F81C;291DF;291DF;291DF;291DF; # (𩇟𩇟; 𩇟𩇟; 𩇟𩇟; 𩇟𩇟; 𩇟𩇟; ) CJK COMPATIBILITY IDEOGRAPH-2F81C
+2F81D;51F5;51F5;51F5;51F5; # (凵凵; 凵; 凵; 凵; 凵; ) CJK COMPATIBILITY IDEOGRAPH-2F81D
+2F81E;5203;5203;5203;5203; # (刃刃; 刃; 刃; 刃; 刃; ) CJK COMPATIBILITY IDEOGRAPH-2F81E
+2F81F;34DF;34DF;34DF;34DF; # (㓟㓟; 㓟; 㓟; 㓟; 㓟; ) CJK COMPATIBILITY IDEOGRAPH-2F81F
+2F820;523B;523B;523B;523B; # (刻刻; 刻; 刻; 刻; 刻; ) CJK COMPATIBILITY IDEOGRAPH-2F820
+2F821;5246;5246;5246;5246; # (剆剆; 剆; 剆; 剆; 剆; ) CJK COMPATIBILITY IDEOGRAPH-2F821
+2F822;5272;5272;5272;5272; # (割割; 割; 割; 割; 割; ) CJK COMPATIBILITY IDEOGRAPH-2F822
+2F823;5277;5277;5277;5277; # (剷剷; 剷; 剷; 剷; 剷; ) CJK COMPATIBILITY IDEOGRAPH-2F823
+2F824;3515;3515;3515;3515; # (㔕㔕; 㔕; 㔕; 㔕; 㔕; ) CJK COMPATIBILITY IDEOGRAPH-2F824
+2F825;52C7;52C7;52C7;52C7; # (勇勇; 勇; 勇; 勇; 勇; ) CJK COMPATIBILITY IDEOGRAPH-2F825
+2F826;52C9;52C9;52C9;52C9; # (勉勉; 勉; 勉; 勉; 勉; ) CJK COMPATIBILITY IDEOGRAPH-2F826
+2F827;52E4;52E4;52E4;52E4; # (勤勤; 勤; 勤; 勤; 勤; ) CJK COMPATIBILITY IDEOGRAPH-2F827
+2F828;52FA;52FA;52FA;52FA; # (勺勺; 勺; 勺; 勺; 勺; ) CJK COMPATIBILITY IDEOGRAPH-2F828
+2F829;5305;5305;5305;5305; # (包包; 包; 包; 包; 包; ) CJK COMPATIBILITY IDEOGRAPH-2F829
+2F82A;5306;5306;5306;5306; # (匆匆; 匆; 匆; 匆; 匆; ) CJK COMPATIBILITY IDEOGRAPH-2F82A
+2F82B;5317;5317;5317;5317; # (北北; 北; 北; 北; 北; ) CJK COMPATIBILITY IDEOGRAPH-2F82B
+2F82C;5349;5349;5349;5349; # (卉卉; 卉; 卉; 卉; 卉; ) CJK COMPATIBILITY IDEOGRAPH-2F82C
+2F82D;5351;5351;5351;5351; # (卑卑; 卑; 卑; 卑; 卑; ) CJK COMPATIBILITY IDEOGRAPH-2F82D
+2F82E;535A;535A;535A;535A; # (博博; 博; 博; 博; 博; ) CJK COMPATIBILITY IDEOGRAPH-2F82E
+2F82F;5373;5373;5373;5373; # (即即; 即; 即; 即; 即; ) CJK COMPATIBILITY IDEOGRAPH-2F82F
+2F830;537D;537D;537D;537D; # (卽卽; 卽; 卽; 卽; 卽; ) CJK COMPATIBILITY IDEOGRAPH-2F830
+2F831;537F;537F;537F;537F; # (卿卿; 卿; 卿; 卿; 卿; ) CJK COMPATIBILITY IDEOGRAPH-2F831
+2F832;537F;537F;537F;537F; # (卿卿; 卿; 卿; 卿; 卿; ) CJK COMPATIBILITY IDEOGRAPH-2F832
+2F833;537F;537F;537F;537F; # (卿卿; 卿; 卿; 卿; 卿; ) CJK COMPATIBILITY IDEOGRAPH-2F833
+2F834;20A2C;20A2C;20A2C;20A2C; # (𠨬𠨬; 𠨬𠨬; 𠨬𠨬; 𠨬𠨬; 𠨬𠨬; ) CJK COMPATIBILITY IDEOGRAPH-2F834
+2F835;7070;7070;7070;7070; # (灰灰; 灰; 灰; 灰; 灰; ) CJK COMPATIBILITY IDEOGRAPH-2F835
+2F836;53CA;53CA;53CA;53CA; # (及及; 及; 及; 及; 及; ) CJK COMPATIBILITY IDEOGRAPH-2F836
+2F837;53DF;53DF;53DF;53DF; # (叟叟; 叟; 叟; 叟; 叟; ) CJK COMPATIBILITY IDEOGRAPH-2F837
+2F838;20B63;20B63;20B63;20B63; # (𠭣𠭣; 𠭣𠭣; 𠭣𠭣; 𠭣𠭣; 𠭣𠭣; ) CJK COMPATIBILITY IDEOGRAPH-2F838
+2F839;53EB;53EB;53EB;53EB; # (叫叫; 叫; 叫; 叫; 叫; ) CJK COMPATIBILITY IDEOGRAPH-2F839
+2F83A;53F1;53F1;53F1;53F1; # (叱叱; 叱; 叱; 叱; 叱; ) CJK COMPATIBILITY IDEOGRAPH-2F83A
+2F83B;5406;5406;5406;5406; # (吆吆; 吆; 吆; 吆; 吆; ) CJK COMPATIBILITY IDEOGRAPH-2F83B
+2F83C;549E;549E;549E;549E; # (咞咞; 咞; 咞; 咞; 咞; ) CJK COMPATIBILITY IDEOGRAPH-2F83C
+2F83D;5438;5438;5438;5438; # (吸吸; 吸; 吸; 吸; 吸; ) CJK COMPATIBILITY IDEOGRAPH-2F83D
+2F83E;5448;5448;5448;5448; # (呈呈; 呈; 呈; 呈; 呈; ) CJK COMPATIBILITY IDEOGRAPH-2F83E
+2F83F;5468;5468;5468;5468; # (周周; 周; 周; 周; 周; ) CJK COMPATIBILITY IDEOGRAPH-2F83F
+2F840;54A2;54A2;54A2;54A2; # (咢咢; 咢; 咢; 咢; 咢; ) CJK COMPATIBILITY IDEOGRAPH-2F840
+2F841;54F6;54F6;54F6;54F6; # (哶哶; 哶; 哶; 哶; 哶; ) CJK COMPATIBILITY IDEOGRAPH-2F841
+2F842;5510;5510;5510;5510; # (唐唐; 唐; 唐; 唐; 唐; ) CJK COMPATIBILITY IDEOGRAPH-2F842
+2F843;5553;5553;5553;5553; # (啓啓; 啓; 啓; 啓; 啓; ) CJK COMPATIBILITY IDEOGRAPH-2F843
+2F844;5563;5563;5563;5563; # (啣啣; 啣; 啣; 啣; 啣; ) CJK COMPATIBILITY IDEOGRAPH-2F844
+2F845;5584;5584;5584;5584; # (善善; 善; 善; 善; 善; ) CJK COMPATIBILITY IDEOGRAPH-2F845
+2F846;5584;5584;5584;5584; # (善善; 善; 善; 善; 善; ) CJK COMPATIBILITY IDEOGRAPH-2F846
+2F847;5599;5599;5599;5599; # (喙喙; 喙; 喙; 喙; 喙; ) CJK COMPATIBILITY IDEOGRAPH-2F847
+2F848;55AB;55AB;55AB;55AB; # (喫喫; 喫; 喫; 喫; 喫; ) CJK COMPATIBILITY IDEOGRAPH-2F848
+2F849;55B3;55B3;55B3;55B3; # (喳喳; 喳; 喳; 喳; 喳; ) CJK COMPATIBILITY IDEOGRAPH-2F849
+2F84A;55C2;55C2;55C2;55C2; # (嗂嗂; 嗂; 嗂; 嗂; 嗂; ) CJK COMPATIBILITY IDEOGRAPH-2F84A
+2F84B;5716;5716;5716;5716; # (圖圖; 圖; 圖; 圖; 圖; ) CJK COMPATIBILITY IDEOGRAPH-2F84B
+2F84C;5606;5606;5606;5606; # (嘆嘆; 嘆; 嘆; 嘆; 嘆; ) CJK COMPATIBILITY IDEOGRAPH-2F84C
+2F84D;5717;5717;5717;5717; # (圗圗; 圗; 圗; 圗; 圗; ) CJK COMPATIBILITY IDEOGRAPH-2F84D
+2F84E;5651;5651;5651;5651; # (噑噑; 噑; 噑; 噑; 噑; ) CJK COMPATIBILITY IDEOGRAPH-2F84E
+2F84F;5674;5674;5674;5674; # (噴噴; 噴; 噴; 噴; 噴; ) CJK COMPATIBILITY IDEOGRAPH-2F84F
+2F850;5207;5207;5207;5207; # (切切; 切; 切; 切; 切; ) CJK COMPATIBILITY IDEOGRAPH-2F850
+2F851;58EE;58EE;58EE;58EE; # (壮壮; 壮; 壮; 壮; 壮; ) CJK COMPATIBILITY IDEOGRAPH-2F851
+2F852;57CE;57CE;57CE;57CE; # (城城; 城; 城; 城; 城; ) CJK COMPATIBILITY IDEOGRAPH-2F852
+2F853;57F4;57F4;57F4;57F4; # (埴埴; 埴; 埴; 埴; 埴; ) CJK COMPATIBILITY IDEOGRAPH-2F853
+2F854;580D;580D;580D;580D; # (堍堍; 堍; 堍; 堍; 堍; ) CJK COMPATIBILITY IDEOGRAPH-2F854
+2F855;578B;578B;578B;578B; # (型型; 型; 型; 型; 型; ) CJK COMPATIBILITY IDEOGRAPH-2F855
+2F856;5832;5832;5832;5832; # (堲堲; 堲; 堲; 堲; 堲; ) CJK COMPATIBILITY IDEOGRAPH-2F856
+2F857;5831;5831;5831;5831; # (報報; 報; 報; 報; 報; ) CJK COMPATIBILITY IDEOGRAPH-2F857
+2F858;58AC;58AC;58AC;58AC; # (墬墬; 墬; 墬; 墬; 墬; ) CJK COMPATIBILITY IDEOGRAPH-2F858
+2F859;214E4;214E4;214E4;214E4; # (𡓤𡓤; 𡓤𡓤; 𡓤𡓤; 𡓤𡓤; 𡓤𡓤; ) CJK COMPATIBILITY IDEOGRAPH-2F859
+2F85A;58F2;58F2;58F2;58F2; # (売売; 売; 売; 売; 売; ) CJK COMPATIBILITY IDEOGRAPH-2F85A
+2F85B;58F7;58F7;58F7;58F7; # (壷壷; 壷; 壷; 壷; 壷; ) CJK COMPATIBILITY IDEOGRAPH-2F85B
+2F85C;5906;5906;5906;5906; # (夆夆; 夆; 夆; 夆; 夆; ) CJK COMPATIBILITY IDEOGRAPH-2F85C
+2F85D;591A;591A;591A;591A; # (多多; 多; 多; 多; 多; ) CJK COMPATIBILITY IDEOGRAPH-2F85D
+2F85E;5922;5922;5922;5922; # (夢夢; 夢; 夢; 夢; 夢; ) CJK COMPATIBILITY IDEOGRAPH-2F85E
+2F85F;5962;5962;5962;5962; # (奢奢; 奢; 奢; 奢; 奢; ) CJK COMPATIBILITY IDEOGRAPH-2F85F
+2F860;216A8;216A8;216A8;216A8; # (𡚨𡚨; 𡚨𡚨; 𡚨𡚨; 𡚨𡚨; 𡚨𡚨; ) CJK COMPATIBILITY IDEOGRAPH-2F860
+2F861;216EA;216EA;216EA;216EA; # (𡛪𡛪; 𡛪𡛪; 𡛪𡛪; 𡛪𡛪; 𡛪𡛪; ) CJK COMPATIBILITY IDEOGRAPH-2F861
+2F862;59EC;59EC;59EC;59EC; # (姬姬; 姬; 姬; 姬; 姬; ) CJK COMPATIBILITY IDEOGRAPH-2F862
+2F863;5A1B;5A1B;5A1B;5A1B; # (娛娛; 娛; 娛; 娛; 娛; ) CJK COMPATIBILITY IDEOGRAPH-2F863
+2F864;5A27;5A27;5A27;5A27; # (娧娧; 娧; 娧; 娧; 娧; ) CJK COMPATIBILITY IDEOGRAPH-2F864
+2F865;59D8;59D8;59D8;59D8; # (姘姘; 姘; 姘; 姘; 姘; ) CJK COMPATIBILITY IDEOGRAPH-2F865
+2F866;5A66;5A66;5A66;5A66; # (婦婦; 婦; 婦; 婦; 婦; ) CJK COMPATIBILITY IDEOGRAPH-2F866
+2F867;36EE;36EE;36EE;36EE; # (㛮㛮; 㛮; 㛮; 㛮; 㛮; ) CJK COMPATIBILITY IDEOGRAPH-2F867
+2F868;36FC;36FC;36FC;36FC; # (㛼㛼; 㛼; 㛼; 㛼; 㛼; ) CJK COMPATIBILITY IDEOGRAPH-2F868
+2F869;5B08;5B08;5B08;5B08; # (嬈嬈; 嬈; 嬈; 嬈; 嬈; ) CJK COMPATIBILITY IDEOGRAPH-2F869
+2F86A;5B3E;5B3E;5B3E;5B3E; # (嬾嬾; 嬾; 嬾; 嬾; 嬾; ) CJK COMPATIBILITY IDEOGRAPH-2F86A
+2F86B;5B3E;5B3E;5B3E;5B3E; # (嬾嬾; 嬾; 嬾; 嬾; 嬾; ) CJK COMPATIBILITY IDEOGRAPH-2F86B
+2F86C;219C8;219C8;219C8;219C8; # (𡧈𡧈; 𡧈𡧈; 𡧈𡧈; 𡧈𡧈; 𡧈𡧈; ) CJK COMPATIBILITY IDEOGRAPH-2F86C
+2F86D;5BC3;5BC3;5BC3;5BC3; # (寃寃; 寃; 寃; 寃; 寃; ) CJK COMPATIBILITY IDEOGRAPH-2F86D
+2F86E;5BD8;5BD8;5BD8;5BD8; # (寘寘; 寘; 寘; 寘; 寘; ) CJK COMPATIBILITY IDEOGRAPH-2F86E
+2F86F;5BE7;5BE7;5BE7;5BE7; # (寧寧; 寧; 寧; 寧; 寧; ) CJK COMPATIBILITY IDEOGRAPH-2F86F
+2F870;5BF3;5BF3;5BF3;5BF3; # (寳寳; 寳; 寳; 寳; 寳; ) CJK COMPATIBILITY IDEOGRAPH-2F870
+2F871;21B18;21B18;21B18;21B18; # (𡬘𡬘; 𡬘𡬘; 𡬘𡬘; 𡬘𡬘; 𡬘𡬘; ) CJK COMPATIBILITY IDEOGRAPH-2F871
+2F872;5BFF;5BFF;5BFF;5BFF; # (寿寿; 寿; 寿; 寿; 寿; ) CJK COMPATIBILITY IDEOGRAPH-2F872
+2F873;5C06;5C06;5C06;5C06; # (将将; 将; 将; 将; 将; ) CJK COMPATIBILITY IDEOGRAPH-2F873
+2F874;5F53;5F53;5F53;5F53; # (当当; 当; 当; 当; 当; ) CJK COMPATIBILITY IDEOGRAPH-2F874
+2F875;5C22;5C22;5C22;5C22; # (尢尢; 尢; 尢; 尢; 尢; ) CJK COMPATIBILITY IDEOGRAPH-2F875
+2F876;3781;3781;3781;3781; # (㞁㞁; 㞁; 㞁; 㞁; 㞁; ) CJK COMPATIBILITY IDEOGRAPH-2F876
+2F877;5C60;5C60;5C60;5C60; # (屠屠; 屠; 屠; 屠; 屠; ) CJK COMPATIBILITY IDEOGRAPH-2F877
+2F878;5C6E;5C6E;5C6E;5C6E; # (屮屮; 屮; 屮; 屮; 屮; ) CJK COMPATIBILITY IDEOGRAPH-2F878
+2F879;5CC0;5CC0;5CC0;5CC0; # (峀峀; 峀; 峀; 峀; 峀; ) CJK COMPATIBILITY IDEOGRAPH-2F879
+2F87A;5C8D;5C8D;5C8D;5C8D; # (岍岍; 岍; 岍; 岍; 岍; ) CJK COMPATIBILITY IDEOGRAPH-2F87A
+2F87B;21DE4;21DE4;21DE4;21DE4; # (𡷤𡷤; 𡷤𡷤; 𡷤𡷤; 𡷤𡷤; 𡷤𡷤; ) CJK COMPATIBILITY IDEOGRAPH-2F87B
+2F87C;5D43;5D43;5D43;5D43; # (嵃嵃; 嵃; 嵃; 嵃; 嵃; ) CJK COMPATIBILITY IDEOGRAPH-2F87C
+2F87D;21DE6;21DE6;21DE6;21DE6; # (𡷦𡷦; 𡷦𡷦; 𡷦𡷦; 𡷦𡷦; 𡷦𡷦; ) CJK COMPATIBILITY IDEOGRAPH-2F87D
+2F87E;5D6E;5D6E;5D6E;5D6E; # (嵮嵮; 嵮; 嵮; 嵮; 嵮; ) CJK COMPATIBILITY IDEOGRAPH-2F87E
+2F87F;5D6B;5D6B;5D6B;5D6B; # (嵫嵫; 嵫; 嵫; 嵫; 嵫; ) CJK COMPATIBILITY IDEOGRAPH-2F87F
+2F880;5D7C;5D7C;5D7C;5D7C; # (嵼嵼; 嵼; 嵼; 嵼; 嵼; ) CJK COMPATIBILITY IDEOGRAPH-2F880
+2F881;5DE1;5DE1;5DE1;5DE1; # (巡巡; 巡; 巡; 巡; 巡; ) CJK COMPATIBILITY IDEOGRAPH-2F881
+2F882;5DE2;5DE2;5DE2;5DE2; # (巢巢; 巢; 巢; 巢; 巢; ) CJK COMPATIBILITY IDEOGRAPH-2F882
+2F883;382F;382F;382F;382F; # (㠯㠯; 㠯; 㠯; 㠯; 㠯; ) CJK COMPATIBILITY IDEOGRAPH-2F883
+2F884;5DFD;5DFD;5DFD;5DFD; # (巽巽; 巽; 巽; 巽; 巽; ) CJK COMPATIBILITY IDEOGRAPH-2F884
+2F885;5E28;5E28;5E28;5E28; # (帨帨; 帨; 帨; 帨; 帨; ) CJK COMPATIBILITY IDEOGRAPH-2F885
+2F886;5E3D;5E3D;5E3D;5E3D; # (帽帽; 帽; 帽; 帽; 帽; ) CJK COMPATIBILITY IDEOGRAPH-2F886
+2F887;5E69;5E69;5E69;5E69; # (幩幩; 幩; 幩; 幩; 幩; ) CJK COMPATIBILITY IDEOGRAPH-2F887
+2F888;3862;3862;3862;3862; # (㡢㡢; 㡢; 㡢; 㡢; 㡢; ) CJK COMPATIBILITY IDEOGRAPH-2F888
+2F889;22183;22183;22183;22183; # (𢆃𢆃; 𢆃𢆃; 𢆃𢆃; 𢆃𢆃; 𢆃𢆃; ) CJK COMPATIBILITY IDEOGRAPH-2F889
+2F88A;387C;387C;387C;387C; # (㡼㡼; 㡼; 㡼; 㡼; 㡼; ) CJK COMPATIBILITY IDEOGRAPH-2F88A
+2F88B;5EB0;5EB0;5EB0;5EB0; # (庰庰; 庰; 庰; 庰; 庰; ) CJK COMPATIBILITY IDEOGRAPH-2F88B
+2F88C;5EB3;5EB3;5EB3;5EB3; # (庳庳; 庳; 庳; 庳; 庳; ) CJK COMPATIBILITY IDEOGRAPH-2F88C
+2F88D;5EB6;5EB6;5EB6;5EB6; # (庶庶; 庶; 庶; 庶; 庶; ) CJK COMPATIBILITY IDEOGRAPH-2F88D
+2F88E;5ECA;5ECA;5ECA;5ECA; # (廊廊; 廊; 廊; 廊; 廊; ) CJK COMPATIBILITY IDEOGRAPH-2F88E
+2F88F;2A392;2A392;2A392;2A392; # (𪎒𪎒; 𪎒𪎒; 𪎒𪎒; 𪎒𪎒; 𪎒𪎒; ) CJK COMPATIBILITY IDEOGRAPH-2F88F
+2F890;5EFE;5EFE;5EFE;5EFE; # (廾廾; 廾; 廾; 廾; 廾; ) CJK COMPATIBILITY IDEOGRAPH-2F890
+2F891;22331;22331;22331;22331; # (𢌱𢌱; 𢌱𢌱; 𢌱𢌱; 𢌱𢌱; 𢌱𢌱; ) CJK COMPATIBILITY IDEOGRAPH-2F891
+2F892;22331;22331;22331;22331; # (𢌱𢌱; 𢌱𢌱; 𢌱𢌱; 𢌱𢌱; 𢌱𢌱; ) CJK COMPATIBILITY IDEOGRAPH-2F892
+2F893;8201;8201;8201;8201; # (舁舁; 舁; 舁; 舁; 舁; ) CJK COMPATIBILITY IDEOGRAPH-2F893
+2F894;5F22;5F22;5F22;5F22; # (弢弢; 弢; 弢; 弢; 弢; ) CJK COMPATIBILITY IDEOGRAPH-2F894
+2F895;5F22;5F22;5F22;5F22; # (弢弢; 弢; 弢; 弢; 弢; ) CJK COMPATIBILITY IDEOGRAPH-2F895
+2F896;38C7;38C7;38C7;38C7; # (㣇㣇; 㣇; 㣇; 㣇; 㣇; ) CJK COMPATIBILITY IDEOGRAPH-2F896
+2F897;232B8;232B8;232B8;232B8; # (𣊸𣊸; 𣊸𣊸; 𣊸𣊸; 𣊸𣊸; 𣊸𣊸; ) CJK COMPATIBILITY IDEOGRAPH-2F897
+2F898;261DA;261DA;261DA;261DA; # (𦇚𦇚; 𦇚𦇚; 𦇚𦇚; 𦇚𦇚; 𦇚𦇚; ) CJK COMPATIBILITY IDEOGRAPH-2F898
+2F899;5F62;5F62;5F62;5F62; # (形形; 形; 形; 形; 形; ) CJK COMPATIBILITY IDEOGRAPH-2F899
+2F89A;5F6B;5F6B;5F6B;5F6B; # (彫彫; 彫; 彫; 彫; 彫; ) CJK COMPATIBILITY IDEOGRAPH-2F89A
+2F89B;38E3;38E3;38E3;38E3; # (㣣㣣; 㣣; 㣣; 㣣; 㣣; ) CJK COMPATIBILITY IDEOGRAPH-2F89B
+2F89C;5F9A;5F9A;5F9A;5F9A; # (徚徚; 徚; 徚; 徚; 徚; ) CJK COMPATIBILITY IDEOGRAPH-2F89C
+2F89D;5FCD;5FCD;5FCD;5FCD; # (忍忍; 忍; 忍; 忍; 忍; ) CJK COMPATIBILITY IDEOGRAPH-2F89D
+2F89E;5FD7;5FD7;5FD7;5FD7; # (志志; 志; 志; 志; 志; ) CJK COMPATIBILITY IDEOGRAPH-2F89E
+2F89F;5FF9;5FF9;5FF9;5FF9; # (忹忹; 忹; 忹; 忹; 忹; ) CJK COMPATIBILITY IDEOGRAPH-2F89F
+2F8A0;6081;6081;6081;6081; # (悁悁; 悁; 悁; 悁; 悁; ) CJK COMPATIBILITY IDEOGRAPH-2F8A0
+2F8A1;393A;393A;393A;393A; # (㤺㤺; 㤺; 㤺; 㤺; 㤺; ) CJK COMPATIBILITY IDEOGRAPH-2F8A1
+2F8A2;391C;391C;391C;391C; # (㤜㤜; 㤜; 㤜; 㤜; 㤜; ) CJK COMPATIBILITY IDEOGRAPH-2F8A2
+2F8A3;6094;6094;6094;6094; # (悔悔; 悔; 悔; 悔; 悔; ) CJK COMPATIBILITY IDEOGRAPH-2F8A3
+2F8A4;226D4;226D4;226D4;226D4; # (𢛔𢛔; 𢛔𢛔; 𢛔𢛔; 𢛔𢛔; 𢛔𢛔; ) CJK COMPATIBILITY IDEOGRAPH-2F8A4
+2F8A5;60C7;60C7;60C7;60C7; # (惇惇; 惇; 惇; 惇; 惇; ) CJK COMPATIBILITY IDEOGRAPH-2F8A5
+2F8A6;6148;6148;6148;6148; # (慈慈; 慈; 慈; 慈; 慈; ) CJK COMPATIBILITY IDEOGRAPH-2F8A6
+2F8A7;614C;614C;614C;614C; # (慌慌; 慌; 慌; 慌; 慌; ) CJK COMPATIBILITY IDEOGRAPH-2F8A7
+2F8A8;614E;614E;614E;614E; # (慎慎; 慎; 慎; 慎; 慎; ) CJK COMPATIBILITY IDEOGRAPH-2F8A8
+2F8A9;614C;614C;614C;614C; # (慌慌; 慌; 慌; 慌; 慌; ) CJK COMPATIBILITY IDEOGRAPH-2F8A9
+2F8AA;617A;617A;617A;617A; # (慺慺; 慺; 慺; 慺; 慺; ) CJK COMPATIBILITY IDEOGRAPH-2F8AA
+2F8AB;618E;618E;618E;618E; # (憎憎; 憎; 憎; 憎; 憎; ) CJK COMPATIBILITY IDEOGRAPH-2F8AB
+2F8AC;61B2;61B2;61B2;61B2; # (憲憲; 憲; 憲; 憲; 憲; ) CJK COMPATIBILITY IDEOGRAPH-2F8AC
+2F8AD;61A4;61A4;61A4;61A4; # (憤憤; 憤; 憤; 憤; 憤; ) CJK COMPATIBILITY IDEOGRAPH-2F8AD
+2F8AE;61AF;61AF;61AF;61AF; # (憯憯; 憯; 憯; 憯; 憯; ) CJK COMPATIBILITY IDEOGRAPH-2F8AE
+2F8AF;61DE;61DE;61DE;61DE; # (懞懞; 懞; 懞; 懞; 懞; ) CJK COMPATIBILITY IDEOGRAPH-2F8AF
+2F8B0;61F2;61F2;61F2;61F2; # (懲懲; 懲; 懲; 懲; 懲; ) CJK COMPATIBILITY IDEOGRAPH-2F8B0
+2F8B1;61F6;61F6;61F6;61F6; # (懶懶; 懶; 懶; 懶; 懶; ) CJK COMPATIBILITY IDEOGRAPH-2F8B1
+2F8B2;6210;6210;6210;6210; # (成成; 成; 成; 成; 成; ) CJK COMPATIBILITY IDEOGRAPH-2F8B2
+2F8B3;621B;621B;621B;621B; # (戛戛; 戛; 戛; 戛; 戛; ) CJK COMPATIBILITY IDEOGRAPH-2F8B3
+2F8B4;625D;625D;625D;625D; # (扝扝; 扝; 扝; 扝; 扝; ) CJK COMPATIBILITY IDEOGRAPH-2F8B4
+2F8B5;62B1;62B1;62B1;62B1; # (抱抱; 抱; 抱; 抱; 抱; ) CJK COMPATIBILITY IDEOGRAPH-2F8B5
+2F8B6;62D4;62D4;62D4;62D4; # (拔拔; 拔; 拔; 拔; 拔; ) CJK COMPATIBILITY IDEOGRAPH-2F8B6
+2F8B7;6350;6350;6350;6350; # (捐捐; 捐; 捐; 捐; 捐; ) CJK COMPATIBILITY IDEOGRAPH-2F8B7
+2F8B8;22B0C;22B0C;22B0C;22B0C; # (𢬌𢬌; 𢬌𢬌; 𢬌𢬌; 𢬌𢬌; 𢬌𢬌; ) CJK COMPATIBILITY IDEOGRAPH-2F8B8
+2F8B9;633D;633D;633D;633D; # (挽挽; 挽; 挽; 挽; 挽; ) CJK COMPATIBILITY IDEOGRAPH-2F8B9
+2F8BA;62FC;62FC;62FC;62FC; # (拼拼; 拼; 拼; 拼; 拼; ) CJK COMPATIBILITY IDEOGRAPH-2F8BA
+2F8BB;6368;6368;6368;6368; # (捨捨; 捨; 捨; 捨; 捨; ) CJK COMPATIBILITY IDEOGRAPH-2F8BB
+2F8BC;6383;6383;6383;6383; # (掃掃; 掃; 掃; 掃; 掃; ) CJK COMPATIBILITY IDEOGRAPH-2F8BC
+2F8BD;63E4;63E4;63E4;63E4; # (揤揤; 揤; 揤; 揤; 揤; ) CJK COMPATIBILITY IDEOGRAPH-2F8BD
+2F8BE;22BF1;22BF1;22BF1;22BF1; # (𢯱𢯱; 𢯱𢯱; 𢯱𢯱; 𢯱𢯱; 𢯱𢯱; ) CJK COMPATIBILITY IDEOGRAPH-2F8BE
+2F8BF;6422;6422;6422;6422; # (搢搢; 搢; 搢; 搢; 搢; ) CJK COMPATIBILITY IDEOGRAPH-2F8BF
+2F8C0;63C5;63C5;63C5;63C5; # (揅揅; 揅; 揅; 揅; 揅; ) CJK COMPATIBILITY IDEOGRAPH-2F8C0
+2F8C1;63A9;63A9;63A9;63A9; # (掩掩; 掩; 掩; 掩; 掩; ) CJK COMPATIBILITY IDEOGRAPH-2F8C1
+2F8C2;3A2E;3A2E;3A2E;3A2E; # (㨮㨮; 㨮; 㨮; 㨮; 㨮; ) CJK COMPATIBILITY IDEOGRAPH-2F8C2
+2F8C3;6469;6469;6469;6469; # (摩摩; 摩; 摩; 摩; 摩; ) CJK COMPATIBILITY IDEOGRAPH-2F8C3
+2F8C4;647E;647E;647E;647E; # (摾摾; 摾; 摾; 摾; 摾; ) CJK COMPATIBILITY IDEOGRAPH-2F8C4
+2F8C5;649D;649D;649D;649D; # (撝撝; 撝; 撝; 撝; 撝; ) CJK COMPATIBILITY IDEOGRAPH-2F8C5
+2F8C6;6477;6477;6477;6477; # (摷摷; 摷; 摷; 摷; 摷; ) CJK COMPATIBILITY IDEOGRAPH-2F8C6
+2F8C7;3A6C;3A6C;3A6C;3A6C; # (㩬㩬; 㩬; 㩬; 㩬; 㩬; ) CJK COMPATIBILITY IDEOGRAPH-2F8C7
+2F8C8;654F;654F;654F;654F; # (敏敏; 敏; 敏; 敏; 敏; ) CJK COMPATIBILITY IDEOGRAPH-2F8C8
+2F8C9;656C;656C;656C;656C; # (敬敬; 敬; 敬; 敬; 敬; ) CJK COMPATIBILITY IDEOGRAPH-2F8C9
+2F8CA;2300A;2300A;2300A;2300A; # (𣀊𣀊; 𣀊𣀊; 𣀊𣀊; 𣀊𣀊; 𣀊𣀊; ) CJK COMPATIBILITY IDEOGRAPH-2F8CA
+2F8CB;65E3;65E3;65E3;65E3; # (旣旣; 旣; 旣; 旣; 旣; ) CJK COMPATIBILITY IDEOGRAPH-2F8CB
+2F8CC;66F8;66F8;66F8;66F8; # (書書; 書; 書; 書; 書; ) CJK COMPATIBILITY IDEOGRAPH-2F8CC
+2F8CD;6649;6649;6649;6649; # (晉晉; 晉; 晉; 晉; 晉; ) CJK COMPATIBILITY IDEOGRAPH-2F8CD
+2F8CE;3B19;3B19;3B19;3B19; # (㬙㬙; 㬙; 㬙; 㬙; 㬙; ) CJK COMPATIBILITY IDEOGRAPH-2F8CE
+2F8CF;6691;6691;6691;6691; # (暑暑; 暑; 暑; 暑; 暑; ) CJK COMPATIBILITY IDEOGRAPH-2F8CF
+2F8D0;3B08;3B08;3B08;3B08; # (㬈㬈; 㬈; 㬈; 㬈; 㬈; ) CJK COMPATIBILITY IDEOGRAPH-2F8D0
+2F8D1;3AE4;3AE4;3AE4;3AE4; # (㫤㫤; 㫤; 㫤; 㫤; 㫤; ) CJK COMPATIBILITY IDEOGRAPH-2F8D1
+2F8D2;5192;5192;5192;5192; # (冒冒; 冒; 冒; 冒; 冒; ) CJK COMPATIBILITY IDEOGRAPH-2F8D2
+2F8D3;5195;5195;5195;5195; # (冕冕; 冕; 冕; 冕; 冕; ) CJK COMPATIBILITY IDEOGRAPH-2F8D3
+2F8D4;6700;6700;6700;6700; # (最最; 最; 最; 最; 最; ) CJK COMPATIBILITY IDEOGRAPH-2F8D4
+2F8D5;669C;669C;669C;669C; # (暜暜; 暜; 暜; 暜; 暜; ) CJK COMPATIBILITY IDEOGRAPH-2F8D5
+2F8D6;80AD;80AD;80AD;80AD; # (肭肭; 肭; 肭; 肭; 肭; ) CJK COMPATIBILITY IDEOGRAPH-2F8D6
+2F8D7;43D9;43D9;43D9;43D9; # (䏙䏙; 䏙; 䏙; 䏙; 䏙; ) CJK COMPATIBILITY IDEOGRAPH-2F8D7
+2F8D8;6717;6717;6717;6717; # (朗朗; 朗; 朗; 朗; 朗; ) CJK COMPATIBILITY IDEOGRAPH-2F8D8
+2F8D9;671B;671B;671B;671B; # (望望; 望; 望; 望; 望; ) CJK COMPATIBILITY IDEOGRAPH-2F8D9
+2F8DA;6721;6721;6721;6721; # (朡朡; 朡; 朡; 朡; 朡; ) CJK COMPATIBILITY IDEOGRAPH-2F8DA
+2F8DB;675E;675E;675E;675E; # (杞杞; 杞; 杞; 杞; 杞; ) CJK COMPATIBILITY IDEOGRAPH-2F8DB
+2F8DC;6753;6753;6753;6753; # (杓杓; 杓; 杓; 杓; 杓; ) CJK COMPATIBILITY IDEOGRAPH-2F8DC
+2F8DD;233C3;233C3;233C3;233C3; # (𣏃𣏃; 𣏃𣏃; 𣏃𣏃; 𣏃𣏃; 𣏃𣏃; ) CJK COMPATIBILITY IDEOGRAPH-2F8DD
+2F8DE;3B49;3B49;3B49;3B49; # (㭉㭉; 㭉; 㭉; 㭉; 㭉; ) CJK COMPATIBILITY IDEOGRAPH-2F8DE
+2F8DF;67FA;67FA;67FA;67FA; # (柺柺; 柺; 柺; 柺; 柺; ) CJK COMPATIBILITY IDEOGRAPH-2F8DF
+2F8E0;6785;6785;6785;6785; # (枅枅; 枅; 枅; 枅; 枅; ) CJK COMPATIBILITY IDEOGRAPH-2F8E0
+2F8E1;6852;6852;6852;6852; # (桒桒; 桒; 桒; 桒; 桒; ) CJK COMPATIBILITY IDEOGRAPH-2F8E1
+2F8E2;6885;6885;6885;6885; # (梅梅; 梅; 梅; 梅; 梅; ) CJK COMPATIBILITY IDEOGRAPH-2F8E2
+2F8E3;2346D;2346D;2346D;2346D; # (𣑭𣑭; 𣑭𣑭; 𣑭𣑭; 𣑭𣑭; 𣑭𣑭; ) CJK COMPATIBILITY IDEOGRAPH-2F8E3
+2F8E4;688E;688E;688E;688E; # (梎梎; 梎; 梎; 梎; 梎; ) CJK COMPATIBILITY IDEOGRAPH-2F8E4
+2F8E5;681F;681F;681F;681F; # (栟栟; 栟; 栟; 栟; 栟; ) CJK COMPATIBILITY IDEOGRAPH-2F8E5
+2F8E6;6914;6914;6914;6914; # (椔椔; 椔; 椔; 椔; 椔; ) CJK COMPATIBILITY IDEOGRAPH-2F8E6
+2F8E7;3B9D;3B9D;3B9D;3B9D; # (㮝㮝; 㮝; 㮝; 㮝; 㮝; ) CJK COMPATIBILITY IDEOGRAPH-2F8E7
+2F8E8;6942;6942;6942;6942; # (楂楂; 楂; 楂; 楂; 楂; ) CJK COMPATIBILITY IDEOGRAPH-2F8E8
+2F8E9;69A3;69A3;69A3;69A3; # (榣榣; 榣; 榣; 榣; 榣; ) CJK COMPATIBILITY IDEOGRAPH-2F8E9
+2F8EA;69EA;69EA;69EA;69EA; # (槪槪; 槪; 槪; 槪; 槪; ) CJK COMPATIBILITY IDEOGRAPH-2F8EA
+2F8EB;6AA8;6AA8;6AA8;6AA8; # (檨檨; 檨; 檨; 檨; 檨; ) CJK COMPATIBILITY IDEOGRAPH-2F8EB
+2F8EC;236A3;236A3;236A3;236A3; # (𣚣𣚣; 𣚣𣚣; 𣚣𣚣; 𣚣𣚣; 𣚣𣚣; ) CJK COMPATIBILITY IDEOGRAPH-2F8EC
+2F8ED;6ADB;6ADB;6ADB;6ADB; # (櫛櫛; 櫛; 櫛; 櫛; 櫛; ) CJK COMPATIBILITY IDEOGRAPH-2F8ED
+2F8EE;3C18;3C18;3C18;3C18; # (㰘㰘; 㰘; 㰘; 㰘; 㰘; ) CJK COMPATIBILITY IDEOGRAPH-2F8EE
+2F8EF;6B21;6B21;6B21;6B21; # (次次; 次; 次; 次; 次; ) CJK COMPATIBILITY IDEOGRAPH-2F8EF
+2F8F0;238A7;238A7;238A7;238A7; # (𣢧𣢧; 𣢧𣢧; 𣢧𣢧; 𣢧𣢧; 𣢧𣢧; ) CJK COMPATIBILITY IDEOGRAPH-2F8F0
+2F8F1;6B54;6B54;6B54;6B54; # (歔歔; 歔; 歔; 歔; 歔; ) CJK COMPATIBILITY IDEOGRAPH-2F8F1
+2F8F2;3C4E;3C4E;3C4E;3C4E; # (㱎㱎; 㱎; 㱎; 㱎; 㱎; ) CJK COMPATIBILITY IDEOGRAPH-2F8F2
+2F8F3;6B72;6B72;6B72;6B72; # (歲歲; 歲; 歲; 歲; 歲; ) CJK COMPATIBILITY IDEOGRAPH-2F8F3
+2F8F4;6B9F;6B9F;6B9F;6B9F; # (殟殟; 殟; 殟; 殟; 殟; ) CJK COMPATIBILITY IDEOGRAPH-2F8F4
+2F8F5;6BBA;6BBA;6BBA;6BBA; # (殺殺; 殺; 殺; 殺; 殺; ) CJK COMPATIBILITY IDEOGRAPH-2F8F5
+2F8F6;6BBB;6BBB;6BBB;6BBB; # (殻殻; 殻; 殻; 殻; 殻; ) CJK COMPATIBILITY IDEOGRAPH-2F8F6
+2F8F7;23A8D;23A8D;23A8D;23A8D; # (𣪍𣪍; 𣪍𣪍; 𣪍𣪍; 𣪍𣪍; 𣪍𣪍; ) CJK COMPATIBILITY IDEOGRAPH-2F8F7
+2F8F8;21D0B;21D0B;21D0B;21D0B; # (𡴋𡴋; 𡴋𡴋; 𡴋𡴋; 𡴋𡴋; 𡴋𡴋; ) CJK COMPATIBILITY IDEOGRAPH-2F8F8
+2F8F9;23AFA;23AFA;23AFA;23AFA; # (𣫺𣫺; 𣫺𣫺; 𣫺𣫺; 𣫺𣫺; 𣫺𣫺; ) CJK COMPATIBILITY IDEOGRAPH-2F8F9
+2F8FA;6C4E;6C4E;6C4E;6C4E; # (汎汎; 汎; 汎; 汎; 汎; ) CJK COMPATIBILITY IDEOGRAPH-2F8FA
+2F8FB;23CBC;23CBC;23CBC;23CBC; # (𣲼𣲼; 𣲼𣲼; 𣲼𣲼; 𣲼𣲼; 𣲼𣲼; ) CJK COMPATIBILITY IDEOGRAPH-2F8FB
+2F8FC;6CBF;6CBF;6CBF;6CBF; # (沿沿; 沿; 沿; 沿; 沿; ) CJK COMPATIBILITY IDEOGRAPH-2F8FC
+2F8FD;6CCD;6CCD;6CCD;6CCD; # (泍泍; 泍; 泍; 泍; 泍; ) CJK COMPATIBILITY IDEOGRAPH-2F8FD
+2F8FE;6C67;6C67;6C67;6C67; # (汧汧; 汧; 汧; 汧; 汧; ) CJK COMPATIBILITY IDEOGRAPH-2F8FE
+2F8FF;6D16;6D16;6D16;6D16; # (洖洖; 洖; 洖; 洖; 洖; ) CJK COMPATIBILITY IDEOGRAPH-2F8FF
+2F900;6D3E;6D3E;6D3E;6D3E; # (派派; 派; 派; 派; 派; ) CJK COMPATIBILITY IDEOGRAPH-2F900
+2F901;6D77;6D77;6D77;6D77; # (海海; 海; 海; 海; 海; ) CJK COMPATIBILITY IDEOGRAPH-2F901
+2F902;6D41;6D41;6D41;6D41; # (流流; 流; 流; 流; 流; ) CJK COMPATIBILITY IDEOGRAPH-2F902
+2F903;6D69;6D69;6D69;6D69; # (浩浩; 浩; 浩; 浩; 浩; ) CJK COMPATIBILITY IDEOGRAPH-2F903
+2F904;6D78;6D78;6D78;6D78; # (浸浸; 浸; 浸; 浸; 浸; ) CJK COMPATIBILITY IDEOGRAPH-2F904
+2F905;6D85;6D85;6D85;6D85; # (涅涅; 涅; 涅; 涅; 涅; ) CJK COMPATIBILITY IDEOGRAPH-2F905
+2F906;23D1E;23D1E;23D1E;23D1E; # (𣴞𣴞; 𣴞𣴞; 𣴞𣴞; 𣴞𣴞; 𣴞𣴞; ) CJK COMPATIBILITY IDEOGRAPH-2F906
+2F907;6D34;6D34;6D34;6D34; # (洴洴; 洴; 洴; 洴; 洴; ) CJK COMPATIBILITY IDEOGRAPH-2F907
+2F908;6E2F;6E2F;6E2F;6E2F; # (港港; 港; 港; 港; 港; ) CJK COMPATIBILITY IDEOGRAPH-2F908
+2F909;6E6E;6E6E;6E6E;6E6E; # (湮湮; 湮; 湮; 湮; 湮; ) CJK COMPATIBILITY IDEOGRAPH-2F909
+2F90A;3D33;3D33;3D33;3D33; # (㴳㴳; 㴳; 㴳; 㴳; 㴳; ) CJK COMPATIBILITY IDEOGRAPH-2F90A
+2F90B;6ECB;6ECB;6ECB;6ECB; # (滋滋; 滋; 滋; 滋; 滋; ) CJK COMPATIBILITY IDEOGRAPH-2F90B
+2F90C;6EC7;6EC7;6EC7;6EC7; # (滇滇; 滇; 滇; 滇; 滇; ) CJK COMPATIBILITY IDEOGRAPH-2F90C
+2F90D;23ED1;23ED1;23ED1;23ED1; # (𣻑𣻑; 𣻑𣻑; 𣻑𣻑; 𣻑𣻑; 𣻑𣻑; ) CJK COMPATIBILITY IDEOGRAPH-2F90D
+2F90E;6DF9;6DF9;6DF9;6DF9; # (淹淹; 淹; 淹; 淹; 淹; ) CJK COMPATIBILITY IDEOGRAPH-2F90E
+2F90F;6F6E;6F6E;6F6E;6F6E; # (潮潮; 潮; 潮; 潮; 潮; ) CJK COMPATIBILITY IDEOGRAPH-2F90F
+2F910;23F5E;23F5E;23F5E;23F5E; # (𣽞𣽞; 𣽞𣽞; 𣽞𣽞; 𣽞𣽞; 𣽞𣽞; ) CJK COMPATIBILITY IDEOGRAPH-2F910
+2F911;23F8E;23F8E;23F8E;23F8E; # (𣾎𣾎; 𣾎𣾎; 𣾎𣾎; 𣾎𣾎; 𣾎𣾎; ) CJK COMPATIBILITY IDEOGRAPH-2F911
+2F912;6FC6;6FC6;6FC6;6FC6; # (濆濆; 濆; 濆; 濆; 濆; ) CJK COMPATIBILITY IDEOGRAPH-2F912
+2F913;7039;7039;7039;7039; # (瀹瀹; 瀹; 瀹; 瀹; 瀹; ) CJK COMPATIBILITY IDEOGRAPH-2F913
+2F914;701E;701E;701E;701E; # (瀞瀞; 瀞; 瀞; 瀞; 瀞; ) CJK COMPATIBILITY IDEOGRAPH-2F914
+2F915;701B;701B;701B;701B; # (瀛瀛; 瀛; 瀛; 瀛; 瀛; ) CJK COMPATIBILITY IDEOGRAPH-2F915
+2F916;3D96;3D96;3D96;3D96; # (㶖㶖; 㶖; 㶖; 㶖; 㶖; ) CJK COMPATIBILITY IDEOGRAPH-2F916
+2F917;704A;704A;704A;704A; # (灊灊; 灊; 灊; 灊; 灊; ) CJK COMPATIBILITY IDEOGRAPH-2F917
+2F918;707D;707D;707D;707D; # (災災; 災; 災; 災; 災; ) CJK COMPATIBILITY IDEOGRAPH-2F918
+2F919;7077;7077;7077;7077; # (灷灷; 灷; 灷; 灷; 灷; ) CJK COMPATIBILITY IDEOGRAPH-2F919
+2F91A;70AD;70AD;70AD;70AD; # (炭炭; 炭; 炭; 炭; 炭; ) CJK COMPATIBILITY IDEOGRAPH-2F91A
+2F91B;20525;20525;20525;20525; # (𠔥𠔥; 𠔥𠔥; 𠔥𠔥; 𠔥𠔥; 𠔥𠔥; ) CJK COMPATIBILITY IDEOGRAPH-2F91B
+2F91C;7145;7145;7145;7145; # (煅煅; 煅; 煅; 煅; 煅; ) CJK COMPATIBILITY IDEOGRAPH-2F91C
+2F91D;24263;24263;24263;24263; # (𤉣𤉣; 𤉣𤉣; 𤉣𤉣; 𤉣𤉣; 𤉣𤉣; ) CJK COMPATIBILITY IDEOGRAPH-2F91D
+2F91E;719C;719C;719C;719C; # (熜熜; 熜; 熜; 熜; 熜; ) CJK COMPATIBILITY IDEOGRAPH-2F91E
+2F91F;243AB;243AB;243AB;243AB; # (𤎫𤎫; 𤎫𤎫; 𤎫𤎫; 𤎫𤎫; 𤎫𤎫; ) CJK COMPATIBILITY IDEOGRAPH-2F91F
+2F920;7228;7228;7228;7228; # (爨爨; 爨; 爨; 爨; 爨; ) CJK COMPATIBILITY IDEOGRAPH-2F920
+2F921;7235;7235;7235;7235; # (爵爵; 爵; 爵; 爵; 爵; ) CJK COMPATIBILITY IDEOGRAPH-2F921
+2F922;7250;7250;7250;7250; # (牐牐; 牐; 牐; 牐; 牐; ) CJK COMPATIBILITY IDEOGRAPH-2F922
+2F923;24608;24608;24608;24608; # (𤘈𤘈; 𤘈𤘈; 𤘈𤘈; 𤘈𤘈; 𤘈𤘈; ) CJK COMPATIBILITY IDEOGRAPH-2F923
+2F924;7280;7280;7280;7280; # (犀犀; 犀; 犀; 犀; 犀; ) CJK COMPATIBILITY IDEOGRAPH-2F924
+2F925;7295;7295;7295;7295; # (犕犕; 犕; 犕; 犕; 犕; ) CJK COMPATIBILITY IDEOGRAPH-2F925
+2F926;24735;24735;24735;24735; # (𤜵𤜵; 𤜵𤜵; 𤜵𤜵; 𤜵𤜵; 𤜵𤜵; ) CJK COMPATIBILITY IDEOGRAPH-2F926
+2F927;24814;24814;24814;24814; # (𤠔𤠔; 𤠔𤠔; 𤠔𤠔; 𤠔𤠔; 𤠔𤠔; ) CJK COMPATIBILITY IDEOGRAPH-2F927
+2F928;737A;737A;737A;737A; # (獺獺; 獺; 獺; 獺; 獺; ) CJK COMPATIBILITY IDEOGRAPH-2F928
+2F929;738B;738B;738B;738B; # (王王; 王; 王; 王; 王; ) CJK COMPATIBILITY IDEOGRAPH-2F929
+2F92A;3EAC;3EAC;3EAC;3EAC; # (㺬㺬; 㺬; 㺬; 㺬; 㺬; ) CJK COMPATIBILITY IDEOGRAPH-2F92A
+2F92B;73A5;73A5;73A5;73A5; # (玥玥; 玥; 玥; 玥; 玥; ) CJK COMPATIBILITY IDEOGRAPH-2F92B
+2F92C;3EB8;3EB8;3EB8;3EB8; # (㺸㺸; 㺸; 㺸; 㺸; 㺸; ) CJK COMPATIBILITY IDEOGRAPH-2F92C
+2F92D;3EB8;3EB8;3EB8;3EB8; # (㺸㺸; 㺸; 㺸; 㺸; 㺸; ) CJK COMPATIBILITY IDEOGRAPH-2F92D
+2F92E;7447;7447;7447;7447; # (瑇瑇; 瑇; 瑇; 瑇; 瑇; ) CJK COMPATIBILITY IDEOGRAPH-2F92E
+2F92F;745C;745C;745C;745C; # (瑜瑜; 瑜; 瑜; 瑜; 瑜; ) CJK COMPATIBILITY IDEOGRAPH-2F92F
+2F930;7471;7471;7471;7471; # (瑱瑱; 瑱; 瑱; 瑱; 瑱; ) CJK COMPATIBILITY IDEOGRAPH-2F930
+2F931;7485;7485;7485;7485; # (璅璅; 璅; 璅; 璅; 璅; ) CJK COMPATIBILITY IDEOGRAPH-2F931
+2F932;74CA;74CA;74CA;74CA; # (瓊瓊; 瓊; 瓊; 瓊; 瓊; ) CJK COMPATIBILITY IDEOGRAPH-2F932
+2F933;3F1B;3F1B;3F1B;3F1B; # (㼛㼛; 㼛; 㼛; 㼛; 㼛; ) CJK COMPATIBILITY IDEOGRAPH-2F933
+2F934;7524;7524;7524;7524; # (甤甤; 甤; 甤; 甤; 甤; ) CJK COMPATIBILITY IDEOGRAPH-2F934
+2F935;24C36;24C36;24C36;24C36; # (𤰶𤰶; 𤰶𤰶; 𤰶𤰶; 𤰶𤰶; 𤰶𤰶; ) CJK COMPATIBILITY IDEOGRAPH-2F935
+2F936;753E;753E;753E;753E; # (甾甾; 甾; 甾; 甾; 甾; ) CJK COMPATIBILITY IDEOGRAPH-2F936
+2F937;24C92;24C92;24C92;24C92; # (𤲒𤲒; 𤲒𤲒; 𤲒𤲒; 𤲒𤲒; 𤲒𤲒; ) CJK COMPATIBILITY IDEOGRAPH-2F937
+2F938;7570;7570;7570;7570; # (異異; 異; 異; 異; 異; ) CJK COMPATIBILITY IDEOGRAPH-2F938
+2F939;2219F;2219F;2219F;2219F; # (𢆟𢆟; 𢆟𢆟; 𢆟𢆟; 𢆟𢆟; 𢆟𢆟; ) CJK COMPATIBILITY IDEOGRAPH-2F939
+2F93A;7610;7610;7610;7610; # (瘐瘐; 瘐; 瘐; 瘐; 瘐; ) CJK COMPATIBILITY IDEOGRAPH-2F93A
+2F93B;24FA1;24FA1;24FA1;24FA1; # (𤾡𤾡; 𤾡𤾡; 𤾡𤾡; 𤾡𤾡; 𤾡𤾡; ) CJK COMPATIBILITY IDEOGRAPH-2F93B
+2F93C;24FB8;24FB8;24FB8;24FB8; # (𤾸𤾸; 𤾸𤾸; 𤾸𤾸; 𤾸𤾸; 𤾸𤾸; ) CJK COMPATIBILITY IDEOGRAPH-2F93C
+2F93D;25044;25044;25044;25044; # (𥁄𥁄; 𥁄𥁄; 𥁄𥁄; 𥁄𥁄; 𥁄𥁄; ) CJK COMPATIBILITY IDEOGRAPH-2F93D
+2F93E;3FFC;3FFC;3FFC;3FFC; # (㿼㿼; 㿼; 㿼; 㿼; 㿼; ) CJK COMPATIBILITY IDEOGRAPH-2F93E
+2F93F;4008;4008;4008;4008; # (䀈䀈; 䀈; 䀈; 䀈; 䀈; ) CJK COMPATIBILITY IDEOGRAPH-2F93F
+2F940;76F4;76F4;76F4;76F4; # (直直; 直; 直; 直; 直; ) CJK COMPATIBILITY IDEOGRAPH-2F940
+2F941;250F3;250F3;250F3;250F3; # (𥃳𥃳; 𥃳𥃳; 𥃳𥃳; 𥃳𥃳; 𥃳𥃳; ) CJK COMPATIBILITY IDEOGRAPH-2F941
+2F942;250F2;250F2;250F2;250F2; # (𥃲𥃲; 𥃲𥃲; 𥃲𥃲; 𥃲𥃲; 𥃲𥃲; ) CJK COMPATIBILITY IDEOGRAPH-2F942
+2F943;25119;25119;25119;25119; # (𥄙𥄙; 𥄙𥄙; 𥄙𥄙; 𥄙𥄙; 𥄙𥄙; ) CJK COMPATIBILITY IDEOGRAPH-2F943
+2F944;25133;25133;25133;25133; # (𥄳𥄳; 𥄳𥄳; 𥄳𥄳; 𥄳𥄳; 𥄳𥄳; ) CJK COMPATIBILITY IDEOGRAPH-2F944
+2F945;771E;771E;771E;771E; # (眞眞; 眞; 眞; 眞; 眞; ) CJK COMPATIBILITY IDEOGRAPH-2F945
+2F946;771F;771F;771F;771F; # (真真; 真; 真; 真; 真; ) CJK COMPATIBILITY IDEOGRAPH-2F946
+2F947;771F;771F;771F;771F; # (真真; 真; 真; 真; 真; ) CJK COMPATIBILITY IDEOGRAPH-2F947
+2F948;774A;774A;774A;774A; # (睊睊; 睊; 睊; 睊; 睊; ) CJK COMPATIBILITY IDEOGRAPH-2F948
+2F949;4039;4039;4039;4039; # (䀹䀹; 䀹; 䀹; 䀹; 䀹; ) CJK COMPATIBILITY IDEOGRAPH-2F949
+2F94A;778B;778B;778B;778B; # (瞋瞋; 瞋; 瞋; 瞋; 瞋; ) CJK COMPATIBILITY IDEOGRAPH-2F94A
+2F94B;4046;4046;4046;4046; # (䁆䁆; 䁆; 䁆; 䁆; 䁆; ) CJK COMPATIBILITY IDEOGRAPH-2F94B
+2F94C;4096;4096;4096;4096; # (䂖䂖; 䂖; 䂖; 䂖; 䂖; ) CJK COMPATIBILITY IDEOGRAPH-2F94C
+2F94D;2541D;2541D;2541D;2541D; # (𥐝𥐝; 𥐝𥐝; 𥐝𥐝; 𥐝𥐝; 𥐝𥐝; ) CJK COMPATIBILITY IDEOGRAPH-2F94D
+2F94E;784E;784E;784E;784E; # (硎硎; 硎; 硎; 硎; 硎; ) CJK COMPATIBILITY IDEOGRAPH-2F94E
+2F94F;788C;788C;788C;788C; # (碌碌; 碌; 碌; 碌; 碌; ) CJK COMPATIBILITY IDEOGRAPH-2F94F
+2F950;78CC;78CC;78CC;78CC; # (磌磌; 磌; 磌; 磌; 磌; ) CJK COMPATIBILITY IDEOGRAPH-2F950
+2F951;40E3;40E3;40E3;40E3; # (䃣䃣; 䃣; 䃣; 䃣; 䃣; ) CJK COMPATIBILITY IDEOGRAPH-2F951
+2F952;25626;25626;25626;25626; # (𥘦𥘦; 𥘦𥘦; 𥘦𥘦; 𥘦𥘦; 𥘦𥘦; ) CJK COMPATIBILITY IDEOGRAPH-2F952
+2F953;7956;7956;7956;7956; # (祖祖; 祖; 祖; 祖; 祖; ) CJK COMPATIBILITY IDEOGRAPH-2F953
+2F954;2569A;2569A;2569A;2569A; # (𥚚𥚚; 𥚚𥚚; 𥚚𥚚; 𥚚𥚚; 𥚚𥚚; ) CJK COMPATIBILITY IDEOGRAPH-2F954
+2F955;256C5;256C5;256C5;256C5; # (𥛅𥛅; 𥛅𥛅; 𥛅𥛅; 𥛅𥛅; 𥛅𥛅; ) CJK COMPATIBILITY IDEOGRAPH-2F955
+2F956;798F;798F;798F;798F; # (福福; 福; 福; 福; 福; ) CJK COMPATIBILITY IDEOGRAPH-2F956
+2F957;79EB;79EB;79EB;79EB; # (秫秫; 秫; 秫; 秫; 秫; ) CJK COMPATIBILITY IDEOGRAPH-2F957
+2F958;412F;412F;412F;412F; # (䄯䄯; 䄯; 䄯; 䄯; 䄯; ) CJK COMPATIBILITY IDEOGRAPH-2F958
+2F959;7A40;7A40;7A40;7A40; # (穀穀; 穀; 穀; 穀; 穀; ) CJK COMPATIBILITY IDEOGRAPH-2F959
+2F95A;7A4A;7A4A;7A4A;7A4A; # (穊穊; 穊; 穊; 穊; 穊; ) CJK COMPATIBILITY IDEOGRAPH-2F95A
+2F95B;7A4F;7A4F;7A4F;7A4F; # (穏穏; 穏; 穏; 穏; 穏; ) CJK COMPATIBILITY IDEOGRAPH-2F95B
+2F95C;2597C;2597C;2597C;2597C; # (𥥼𥥼; 𥥼𥥼; 𥥼𥥼; 𥥼𥥼; 𥥼𥥼; ) CJK COMPATIBILITY IDEOGRAPH-2F95C
+2F95D;25AA7;25AA7;25AA7;25AA7; # (𥪧𥪧; 𥪧𥪧; 𥪧𥪧; 𥪧𥪧; 𥪧𥪧; ) CJK COMPATIBILITY IDEOGRAPH-2F95D
+2F95E;25AA7;25AA7;25AA7;25AA7; # (𥪧𥪧; 𥪧𥪧; 𥪧𥪧; 𥪧𥪧; 𥪧𥪧; ) CJK COMPATIBILITY IDEOGRAPH-2F95E
+2F95F;7AEE;7AEE;7AEE;7AEE; # (竮竮; 竮; 竮; 竮; 竮; ) CJK COMPATIBILITY IDEOGRAPH-2F95F
+2F960;4202;4202;4202;4202; # (䈂䈂; 䈂; 䈂; 䈂; 䈂; ) CJK COMPATIBILITY IDEOGRAPH-2F960
+2F961;25BAB;25BAB;25BAB;25BAB; # (𥮫𥮫; 𥮫𥮫; 𥮫𥮫; 𥮫𥮫; 𥮫𥮫; ) CJK COMPATIBILITY IDEOGRAPH-2F961
+2F962;7BC6;7BC6;7BC6;7BC6; # (篆篆; 篆; 篆; 篆; 篆; ) CJK COMPATIBILITY IDEOGRAPH-2F962
+2F963;7BC9;7BC9;7BC9;7BC9; # (築築; 築; 築; 築; 築; ) CJK COMPATIBILITY IDEOGRAPH-2F963
+2F964;4227;4227;4227;4227; # (䈧䈧; 䈧; 䈧; 䈧; 䈧; ) CJK COMPATIBILITY IDEOGRAPH-2F964
+2F965;25C80;25C80;25C80;25C80; # (𥲀𥲀; 𥲀𥲀; 𥲀𥲀; 𥲀𥲀; 𥲀𥲀; ) CJK COMPATIBILITY IDEOGRAPH-2F965
+2F966;7CD2;7CD2;7CD2;7CD2; # (糒糒; 糒; 糒; 糒; 糒; ) CJK COMPATIBILITY IDEOGRAPH-2F966
+2F967;42A0;42A0;42A0;42A0; # (䊠䊠; 䊠; 䊠; 䊠; 䊠; ) CJK COMPATIBILITY IDEOGRAPH-2F967
+2F968;7CE8;7CE8;7CE8;7CE8; # (糨糨; 糨; 糨; 糨; 糨; ) CJK COMPATIBILITY IDEOGRAPH-2F968
+2F969;7CE3;7CE3;7CE3;7CE3; # (糣糣; 糣; 糣; 糣; 糣; ) CJK COMPATIBILITY IDEOGRAPH-2F969
+2F96A;7D00;7D00;7D00;7D00; # (紀紀; 紀; 紀; 紀; 紀; ) CJK COMPATIBILITY IDEOGRAPH-2F96A
+2F96B;25F86;25F86;25F86;25F86; # (𥾆𥾆; 𥾆𥾆; 𥾆𥾆; 𥾆𥾆; 𥾆𥾆; ) CJK COMPATIBILITY IDEOGRAPH-2F96B
+2F96C;7D63;7D63;7D63;7D63; # (絣絣; 絣; 絣; 絣; 絣; ) CJK COMPATIBILITY IDEOGRAPH-2F96C
+2F96D;4301;4301;4301;4301; # (䌁䌁; 䌁; 䌁; 䌁; 䌁; ) CJK COMPATIBILITY IDEOGRAPH-2F96D
+2F96E;7DC7;7DC7;7DC7;7DC7; # (緇緇; 緇; 緇; 緇; 緇; ) CJK COMPATIBILITY IDEOGRAPH-2F96E
+2F96F;7E02;7E02;7E02;7E02; # (縂縂; 縂; 縂; 縂; 縂; ) CJK COMPATIBILITY IDEOGRAPH-2F96F
+2F970;7E45;7E45;7E45;7E45; # (繅繅; 繅; 繅; 繅; 繅; ) CJK COMPATIBILITY IDEOGRAPH-2F970
+2F971;4334;4334;4334;4334; # (䌴䌴; 䌴; 䌴; 䌴; 䌴; ) CJK COMPATIBILITY IDEOGRAPH-2F971
+2F972;26228;26228;26228;26228; # (𦈨𦈨; 𦈨𦈨; 𦈨𦈨; 𦈨𦈨; 𦈨𦈨; ) CJK COMPATIBILITY IDEOGRAPH-2F972
+2F973;26247;26247;26247;26247; # (𦉇𦉇; 𦉇𦉇; 𦉇𦉇; 𦉇𦉇; 𦉇𦉇; ) CJK COMPATIBILITY IDEOGRAPH-2F973
+2F974;4359;4359;4359;4359; # (䍙䍙; 䍙; 䍙; 䍙; 䍙; ) CJK COMPATIBILITY IDEOGRAPH-2F974
+2F975;262D9;262D9;262D9;262D9; # (𦋙𦋙; 𦋙𦋙; 𦋙𦋙; 𦋙𦋙; 𦋙𦋙; ) CJK COMPATIBILITY IDEOGRAPH-2F975
+2F976;7F7A;7F7A;7F7A;7F7A; # (罺罺; 罺; 罺; 罺; 罺; ) CJK COMPATIBILITY IDEOGRAPH-2F976
+2F977;2633E;2633E;2633E;2633E; # (𦌾𦌾; 𦌾𦌾; 𦌾𦌾; 𦌾𦌾; 𦌾𦌾; ) CJK COMPATIBILITY IDEOGRAPH-2F977
+2F978;7F95;7F95;7F95;7F95; # (羕羕; 羕; 羕; 羕; 羕; ) CJK COMPATIBILITY IDEOGRAPH-2F978
+2F979;7FFA;7FFA;7FFA;7FFA; # (翺翺; 翺; 翺; 翺; 翺; ) CJK COMPATIBILITY IDEOGRAPH-2F979
+2F97A;8005;8005;8005;8005; # (者者; 者; 者; 者; 者; ) CJK COMPATIBILITY IDEOGRAPH-2F97A
+2F97B;264DA;264DA;264DA;264DA; # (𦓚𦓚; 𦓚𦓚; 𦓚𦓚; 𦓚𦓚; 𦓚𦓚; ) CJK COMPATIBILITY IDEOGRAPH-2F97B
+2F97C;26523;26523;26523;26523; # (𦔣𦔣; 𦔣𦔣; 𦔣𦔣; 𦔣𦔣; 𦔣𦔣; ) CJK COMPATIBILITY IDEOGRAPH-2F97C
+2F97D;8060;8060;8060;8060; # (聠聠; 聠; 聠; 聠; 聠; ) CJK COMPATIBILITY IDEOGRAPH-2F97D
+2F97E;265A8;265A8;265A8;265A8; # (𦖨𦖨; 𦖨𦖨; 𦖨𦖨; 𦖨𦖨; 𦖨𦖨; ) CJK COMPATIBILITY IDEOGRAPH-2F97E
+2F97F;8070;8070;8070;8070; # (聰聰; 聰; 聰; 聰; 聰; ) CJK COMPATIBILITY IDEOGRAPH-2F97F
+2F980;2335F;2335F;2335F;2335F; # (𣍟𣍟; 𣍟𣍟; 𣍟𣍟; 𣍟𣍟; 𣍟𣍟; ) CJK COMPATIBILITY IDEOGRAPH-2F980
+2F981;43D5;43D5;43D5;43D5; # (䏕䏕; 䏕; 䏕; 䏕; 䏕; ) CJK COMPATIBILITY IDEOGRAPH-2F981
+2F982;80B2;80B2;80B2;80B2; # (育育; 育; 育; 育; 育; ) CJK COMPATIBILITY IDEOGRAPH-2F982
+2F983;8103;8103;8103;8103; # (脃脃; 脃; 脃; 脃; 脃; ) CJK COMPATIBILITY IDEOGRAPH-2F983
+2F984;440B;440B;440B;440B; # (䐋䐋; 䐋; 䐋; 䐋; 䐋; ) CJK COMPATIBILITY IDEOGRAPH-2F984
+2F985;813E;813E;813E;813E; # (脾脾; 脾; 脾; 脾; 脾; ) CJK COMPATIBILITY IDEOGRAPH-2F985
+2F986;5AB5;5AB5;5AB5;5AB5; # (媵媵; 媵; 媵; 媵; 媵; ) CJK COMPATIBILITY IDEOGRAPH-2F986
+2F987;267A7;267A7;267A7;267A7; # (𦞧𦞧; 𦞧𦞧; 𦞧𦞧; 𦞧𦞧; 𦞧𦞧; ) CJK COMPATIBILITY IDEOGRAPH-2F987
+2F988;267B5;267B5;267B5;267B5; # (𦞵𦞵; 𦞵𦞵; 𦞵𦞵; 𦞵𦞵; 𦞵𦞵; ) CJK COMPATIBILITY IDEOGRAPH-2F988
+2F989;23393;23393;23393;23393; # (𣎓𣎓; 𣎓𣎓; 𣎓𣎓; 𣎓𣎓; 𣎓𣎓; ) CJK COMPATIBILITY IDEOGRAPH-2F989
+2F98A;2339C;2339C;2339C;2339C; # (𣎜𣎜; 𣎜𣎜; 𣎜𣎜; 𣎜𣎜; 𣎜𣎜; ) CJK COMPATIBILITY IDEOGRAPH-2F98A
+2F98B;8201;8201;8201;8201; # (舁舁; 舁; 舁; 舁; 舁; ) CJK COMPATIBILITY IDEOGRAPH-2F98B
+2F98C;8204;8204;8204;8204; # (舄舄; 舄; 舄; 舄; 舄; ) CJK COMPATIBILITY IDEOGRAPH-2F98C
+2F98D;8F9E;8F9E;8F9E;8F9E; # (辞辞; 辞; 辞; 辞; 辞; ) CJK COMPATIBILITY IDEOGRAPH-2F98D
+2F98E;446B;446B;446B;446B; # (䑫䑫; 䑫; 䑫; 䑫; 䑫; ) CJK COMPATIBILITY IDEOGRAPH-2F98E
+2F98F;8291;8291;8291;8291; # (芑芑; 芑; 芑; 芑; 芑; ) CJK COMPATIBILITY IDEOGRAPH-2F98F
+2F990;828B;828B;828B;828B; # (芋芋; 芋; 芋; 芋; 芋; ) CJK COMPATIBILITY IDEOGRAPH-2F990
+2F991;829D;829D;829D;829D; # (芝芝; 芝; 芝; 芝; 芝; ) CJK COMPATIBILITY IDEOGRAPH-2F991
+2F992;52B3;52B3;52B3;52B3; # (劳劳; 劳; 劳; 劳; 劳; ) CJK COMPATIBILITY IDEOGRAPH-2F992
+2F993;82B1;82B1;82B1;82B1; # (花花; 花; 花; 花; 花; ) CJK COMPATIBILITY IDEOGRAPH-2F993
+2F994;82B3;82B3;82B3;82B3; # (芳芳; 芳; 芳; 芳; 芳; ) CJK COMPATIBILITY IDEOGRAPH-2F994
+2F995;82BD;82BD;82BD;82BD; # (芽芽; 芽; 芽; 芽; 芽; ) CJK COMPATIBILITY IDEOGRAPH-2F995
+2F996;82E6;82E6;82E6;82E6; # (苦苦; 苦; 苦; 苦; 苦; ) CJK COMPATIBILITY IDEOGRAPH-2F996
+2F997;26B3C;26B3C;26B3C;26B3C; # (𦬼𦬼; 𦬼𦬼; 𦬼𦬼; 𦬼𦬼; 𦬼𦬼; ) CJK COMPATIBILITY IDEOGRAPH-2F997
+2F998;82E5;82E5;82E5;82E5; # (若若; 若; 若; 若; 若; ) CJK COMPATIBILITY IDEOGRAPH-2F998
+2F999;831D;831D;831D;831D; # (茝茝; 茝; 茝; 茝; 茝; ) CJK COMPATIBILITY IDEOGRAPH-2F999
+2F99A;8363;8363;8363;8363; # (荣荣; 荣; 荣; 荣; 荣; ) CJK COMPATIBILITY IDEOGRAPH-2F99A
+2F99B;83AD;83AD;83AD;83AD; # (莭莭; 莭; 莭; 莭; 莭; ) CJK COMPATIBILITY IDEOGRAPH-2F99B
+2F99C;8323;8323;8323;8323; # (茣茣; 茣; 茣; 茣; 茣; ) CJK COMPATIBILITY IDEOGRAPH-2F99C
+2F99D;83BD;83BD;83BD;83BD; # (莽莽; 莽; 莽; 莽; 莽; ) CJK COMPATIBILITY IDEOGRAPH-2F99D
+2F99E;83E7;83E7;83E7;83E7; # (菧菧; 菧; 菧; 菧; 菧; ) CJK COMPATIBILITY IDEOGRAPH-2F99E
+2F99F;8457;8457;8457;8457; # (著著; 著; 著; 著; 著; ) CJK COMPATIBILITY IDEOGRAPH-2F99F
+2F9A0;8353;8353;8353;8353; # (荓荓; 荓; 荓; 荓; 荓; ) CJK COMPATIBILITY IDEOGRAPH-2F9A0
+2F9A1;83CA;83CA;83CA;83CA; # (菊菊; 菊; 菊; 菊; 菊; ) CJK COMPATIBILITY IDEOGRAPH-2F9A1
+2F9A2;83CC;83CC;83CC;83CC; # (菌菌; 菌; 菌; 菌; 菌; ) CJK COMPATIBILITY IDEOGRAPH-2F9A2
+2F9A3;83DC;83DC;83DC;83DC; # (菜菜; 菜; 菜; 菜; 菜; ) CJK COMPATIBILITY IDEOGRAPH-2F9A3
+2F9A4;26C36;26C36;26C36;26C36; # (𦰶𦰶; 𦰶𦰶; 𦰶𦰶; 𦰶𦰶; 𦰶𦰶; ) CJK COMPATIBILITY IDEOGRAPH-2F9A4
+2F9A5;26D6B;26D6B;26D6B;26D6B; # (𦵫𦵫; 𦵫𦵫; 𦵫𦵫; 𦵫𦵫; 𦵫𦵫; ) CJK COMPATIBILITY IDEOGRAPH-2F9A5
+2F9A6;26CD5;26CD5;26CD5;26CD5; # (𦳕𦳕; 𦳕𦳕; 𦳕𦳕; 𦳕𦳕; 𦳕𦳕; ) CJK COMPATIBILITY IDEOGRAPH-2F9A6
+2F9A7;452B;452B;452B;452B; # (䔫䔫; 䔫; 䔫; 䔫; 䔫; ) CJK COMPATIBILITY IDEOGRAPH-2F9A7
+2F9A8;84F1;84F1;84F1;84F1; # (蓱蓱; 蓱; 蓱; 蓱; 蓱; ) CJK COMPATIBILITY IDEOGRAPH-2F9A8
+2F9A9;84F3;84F3;84F3;84F3; # (蓳蓳; 蓳; 蓳; 蓳; 蓳; ) CJK COMPATIBILITY IDEOGRAPH-2F9A9
+2F9AA;8516;8516;8516;8516; # (蔖蔖; 蔖; 蔖; 蔖; 蔖; ) CJK COMPATIBILITY IDEOGRAPH-2F9AA
+2F9AB;273CA;273CA;273CA;273CA; # (𧏊𧏊; 𧏊𧏊; 𧏊𧏊; 𧏊𧏊; 𧏊𧏊; ) CJK COMPATIBILITY IDEOGRAPH-2F9AB
+2F9AC;8564;8564;8564;8564; # (蕤蕤; 蕤; 蕤; 蕤; 蕤; ) CJK COMPATIBILITY IDEOGRAPH-2F9AC
+2F9AD;26F2C;26F2C;26F2C;26F2C; # (𦼬𦼬; 𦼬𦼬; 𦼬𦼬; 𦼬𦼬; 𦼬𦼬; ) CJK COMPATIBILITY IDEOGRAPH-2F9AD
+2F9AE;455D;455D;455D;455D; # (䕝䕝; 䕝; 䕝; 䕝; 䕝; ) CJK COMPATIBILITY IDEOGRAPH-2F9AE
+2F9AF;4561;4561;4561;4561; # (䕡䕡; 䕡; 䕡; 䕡; 䕡; ) CJK COMPATIBILITY IDEOGRAPH-2F9AF
+2F9B0;26FB1;26FB1;26FB1;26FB1; # (𦾱𦾱; 𦾱𦾱; 𦾱𦾱; 𦾱𦾱; 𦾱𦾱; ) CJK COMPATIBILITY IDEOGRAPH-2F9B0
+2F9B1;270D2;270D2;270D2;270D2; # (𧃒𧃒; 𧃒𧃒; 𧃒𧃒; 𧃒𧃒; 𧃒𧃒; ) CJK COMPATIBILITY IDEOGRAPH-2F9B1
+2F9B2;456B;456B;456B;456B; # (䕫䕫; 䕫; 䕫; 䕫; 䕫; ) CJK COMPATIBILITY IDEOGRAPH-2F9B2
+2F9B3;8650;8650;8650;8650; # (虐虐; 虐; 虐; 虐; 虐; ) CJK COMPATIBILITY IDEOGRAPH-2F9B3
+2F9B4;865C;865C;865C;865C; # (虜虜; 虜; 虜; 虜; 虜; ) CJK COMPATIBILITY IDEOGRAPH-2F9B4
+2F9B5;8667;8667;8667;8667; # (虧虧; 虧; 虧; 虧; 虧; ) CJK COMPATIBILITY IDEOGRAPH-2F9B5
+2F9B6;8669;8669;8669;8669; # (虩虩; 虩; 虩; 虩; 虩; ) CJK COMPATIBILITY IDEOGRAPH-2F9B6
+2F9B7;86A9;86A9;86A9;86A9; # (蚩蚩; 蚩; 蚩; 蚩; 蚩; ) CJK COMPATIBILITY IDEOGRAPH-2F9B7
+2F9B8;8688;8688;8688;8688; # (蚈蚈; 蚈; 蚈; 蚈; 蚈; ) CJK COMPATIBILITY IDEOGRAPH-2F9B8
+2F9B9;870E;870E;870E;870E; # (蜎蜎; 蜎; 蜎; 蜎; 蜎; ) CJK COMPATIBILITY IDEOGRAPH-2F9B9
+2F9BA;86E2;86E2;86E2;86E2; # (蛢蛢; 蛢; 蛢; 蛢; 蛢; ) CJK COMPATIBILITY IDEOGRAPH-2F9BA
+2F9BB;8779;8779;8779;8779; # (蝹蝹; 蝹; 蝹; 蝹; 蝹; ) CJK COMPATIBILITY IDEOGRAPH-2F9BB
+2F9BC;8728;8728;8728;8728; # (蜨蜨; 蜨; 蜨; 蜨; 蜨; ) CJK COMPATIBILITY IDEOGRAPH-2F9BC
+2F9BD;876B;876B;876B;876B; # (蝫蝫; 蝫; 蝫; 蝫; 蝫; ) CJK COMPATIBILITY IDEOGRAPH-2F9BD
+2F9BE;8786;8786;8786;8786; # (螆螆; 螆; 螆; 螆; 螆; ) CJK COMPATIBILITY IDEOGRAPH-2F9BE
+2F9BF;45D7;45D7;45D7;45D7; # (䗗䗗; 䗗; 䗗; 䗗; 䗗; ) CJK COMPATIBILITY IDEOGRAPH-2F9BF
+2F9C0;87E1;87E1;87E1;87E1; # (蟡蟡; 蟡; 蟡; 蟡; 蟡; ) CJK COMPATIBILITY IDEOGRAPH-2F9C0
+2F9C1;8801;8801;8801;8801; # (蠁蠁; 蠁; 蠁; 蠁; 蠁; ) CJK COMPATIBILITY IDEOGRAPH-2F9C1
+2F9C2;45F9;45F9;45F9;45F9; # (䗹䗹; 䗹; 䗹; 䗹; 䗹; ) CJK COMPATIBILITY IDEOGRAPH-2F9C2
+2F9C3;8860;8860;8860;8860; # (衠衠; 衠; 衠; 衠; 衠; ) CJK COMPATIBILITY IDEOGRAPH-2F9C3
+2F9C4;8863;8863;8863;8863; # (衣衣; 衣; 衣; 衣; 衣; ) CJK COMPATIBILITY IDEOGRAPH-2F9C4
+2F9C5;27667;27667;27667;27667; # (𧙧𧙧; 𧙧𧙧; 𧙧𧙧; 𧙧𧙧; 𧙧𧙧; ) CJK COMPATIBILITY IDEOGRAPH-2F9C5
+2F9C6;88D7;88D7;88D7;88D7; # (裗裗; 裗; 裗; 裗; 裗; ) CJK COMPATIBILITY IDEOGRAPH-2F9C6
+2F9C7;88DE;88DE;88DE;88DE; # (裞裞; 裞; 裞; 裞; 裞; ) CJK COMPATIBILITY IDEOGRAPH-2F9C7
+2F9C8;4635;4635;4635;4635; # (䘵䘵; 䘵; 䘵; 䘵; 䘵; ) CJK COMPATIBILITY IDEOGRAPH-2F9C8
+2F9C9;88FA;88FA;88FA;88FA; # (裺裺; 裺; 裺; 裺; 裺; ) CJK COMPATIBILITY IDEOGRAPH-2F9C9
+2F9CA;34BB;34BB;34BB;34BB; # (㒻㒻; 㒻; 㒻; 㒻; 㒻; ) CJK COMPATIBILITY IDEOGRAPH-2F9CA
+2F9CB;278AE;278AE;278AE;278AE; # (𧢮𧢮; 𧢮𧢮; 𧢮𧢮; 𧢮𧢮; 𧢮𧢮; ) CJK COMPATIBILITY IDEOGRAPH-2F9CB
+2F9CC;27966;27966;27966;27966; # (𧥦𧥦; 𧥦𧥦; 𧥦𧥦; 𧥦𧥦; 𧥦𧥦; ) CJK COMPATIBILITY IDEOGRAPH-2F9CC
+2F9CD;46BE;46BE;46BE;46BE; # (䚾䚾; 䚾; 䚾; 䚾; 䚾; ) CJK COMPATIBILITY IDEOGRAPH-2F9CD
+2F9CE;46C7;46C7;46C7;46C7; # (䛇䛇; 䛇; 䛇; 䛇; 䛇; ) CJK COMPATIBILITY IDEOGRAPH-2F9CE
+2F9CF;8AA0;8AA0;8AA0;8AA0; # (誠誠; 誠; 誠; 誠; 誠; ) CJK COMPATIBILITY IDEOGRAPH-2F9CF
+2F9D0;8AED;8AED;8AED;8AED; # (諭諭; 諭; 諭; 諭; 諭; ) CJK COMPATIBILITY IDEOGRAPH-2F9D0
+2F9D1;8B8A;8B8A;8B8A;8B8A; # (變變; 變; 變; 變; 變; ) CJK COMPATIBILITY IDEOGRAPH-2F9D1
+2F9D2;8C55;8C55;8C55;8C55; # (豕豕; 豕; 豕; 豕; 豕; ) CJK COMPATIBILITY IDEOGRAPH-2F9D2
+2F9D3;27CA8;27CA8;27CA8;27CA8; # (𧲨𧲨; 𧲨𧲨; 𧲨𧲨; 𧲨𧲨; 𧲨𧲨; ) CJK COMPATIBILITY IDEOGRAPH-2F9D3
+2F9D4;8CAB;8CAB;8CAB;8CAB; # (貫貫; 貫; 貫; 貫; 貫; ) CJK COMPATIBILITY IDEOGRAPH-2F9D4
+2F9D5;8CC1;8CC1;8CC1;8CC1; # (賁賁; 賁; 賁; 賁; 賁; ) CJK COMPATIBILITY IDEOGRAPH-2F9D5
+2F9D6;8D1B;8D1B;8D1B;8D1B; # (贛贛; 贛; 贛; 贛; 贛; ) CJK COMPATIBILITY IDEOGRAPH-2F9D6
+2F9D7;8D77;8D77;8D77;8D77; # (起起; 起; 起; 起; 起; ) CJK COMPATIBILITY IDEOGRAPH-2F9D7
+2F9D8;27F2F;27F2F;27F2F;27F2F; # (𧼯𧼯; 𧼯𧼯; 𧼯𧼯; 𧼯𧼯; 𧼯𧼯; ) CJK COMPATIBILITY IDEOGRAPH-2F9D8
+2F9D9;20804;20804;20804;20804; # (𠠄𠠄; 𠠄𠠄; 𠠄𠠄; 𠠄𠠄; 𠠄𠠄; ) CJK COMPATIBILITY IDEOGRAPH-2F9D9
+2F9DA;8DCB;8DCB;8DCB;8DCB; # (跋跋; 跋; 跋; 跋; 跋; ) CJK COMPATIBILITY IDEOGRAPH-2F9DA
+2F9DB;8DBC;8DBC;8DBC;8DBC; # (趼趼; 趼; 趼; 趼; 趼; ) CJK COMPATIBILITY IDEOGRAPH-2F9DB
+2F9DC;8DF0;8DF0;8DF0;8DF0; # (跰跰; 跰; 跰; 跰; 跰; ) CJK COMPATIBILITY IDEOGRAPH-2F9DC
+2F9DD;208DE;208DE;208DE;208DE; # (𠣞𠣞; 𠣞𠣞; 𠣞𠣞; 𠣞𠣞; 𠣞𠣞; ) CJK COMPATIBILITY IDEOGRAPH-2F9DD
+2F9DE;8ED4;8ED4;8ED4;8ED4; # (軔軔; 軔; 軔; 軔; 軔; ) CJK COMPATIBILITY IDEOGRAPH-2F9DE
+2F9DF;8F38;8F38;8F38;8F38; # (輸輸; 輸; 輸; 輸; 輸; ) CJK COMPATIBILITY IDEOGRAPH-2F9DF
+2F9E0;285D2;285D2;285D2;285D2; # (𨗒𨗒; 𨗒𨗒; 𨗒𨗒; 𨗒𨗒; 𨗒𨗒; ) CJK COMPATIBILITY IDEOGRAPH-2F9E0
+2F9E1;285ED;285ED;285ED;285ED; # (𨗭𨗭; 𨗭𨗭; 𨗭𨗭; 𨗭𨗭; 𨗭𨗭; ) CJK COMPATIBILITY IDEOGRAPH-2F9E1
+2F9E2;9094;9094;9094;9094; # (邔邔; 邔; 邔; 邔; 邔; ) CJK COMPATIBILITY IDEOGRAPH-2F9E2
+2F9E3;90F1;90F1;90F1;90F1; # (郱郱; 郱; 郱; 郱; 郱; ) CJK COMPATIBILITY IDEOGRAPH-2F9E3
+2F9E4;9111;9111;9111;9111; # (鄑鄑; 鄑; 鄑; 鄑; 鄑; ) CJK COMPATIBILITY IDEOGRAPH-2F9E4
+2F9E5;2872E;2872E;2872E;2872E; # (𨜮𨜮; 𨜮𨜮; 𨜮𨜮; 𨜮𨜮; 𨜮𨜮; ) CJK COMPATIBILITY IDEOGRAPH-2F9E5
+2F9E6;911B;911B;911B;911B; # (鄛鄛; 鄛; 鄛; 鄛; 鄛; ) CJK COMPATIBILITY IDEOGRAPH-2F9E6
+2F9E7;9238;9238;9238;9238; # (鈸鈸; 鈸; 鈸; 鈸; 鈸; ) CJK COMPATIBILITY IDEOGRAPH-2F9E7
+2F9E8;92D7;92D7;92D7;92D7; # (鋗鋗; 鋗; 鋗; 鋗; 鋗; ) CJK COMPATIBILITY IDEOGRAPH-2F9E8
+2F9E9;92D8;92D8;92D8;92D8; # (鋘鋘; 鋘; 鋘; 鋘; 鋘; ) CJK COMPATIBILITY IDEOGRAPH-2F9E9
+2F9EA;927C;927C;927C;927C; # (鉼鉼; 鉼; 鉼; 鉼; 鉼; ) CJK COMPATIBILITY IDEOGRAPH-2F9EA
+2F9EB;93F9;93F9;93F9;93F9; # (鏹鏹; 鏹; 鏹; 鏹; 鏹; ) CJK COMPATIBILITY IDEOGRAPH-2F9EB
+2F9EC;9415;9415;9415;9415; # (鐕鐕; 鐕; 鐕; 鐕; 鐕; ) CJK COMPATIBILITY IDEOGRAPH-2F9EC
+2F9ED;28BFA;28BFA;28BFA;28BFA; # (𨯺𨯺; 𨯺𨯺; 𨯺𨯺; 𨯺𨯺; 𨯺𨯺; ) CJK COMPATIBILITY IDEOGRAPH-2F9ED
+2F9EE;958B;958B;958B;958B; # (開開; 開; 開; 開; 開; ) CJK COMPATIBILITY IDEOGRAPH-2F9EE
+2F9EF;4995;4995;4995;4995; # (䦕䦕; 䦕; 䦕; 䦕; 䦕; ) CJK COMPATIBILITY IDEOGRAPH-2F9EF
+2F9F0;95B7;95B7;95B7;95B7; # (閷閷; 閷; 閷; 閷; 閷; ) CJK COMPATIBILITY IDEOGRAPH-2F9F0
+2F9F1;28D77;28D77;28D77;28D77; # (𨵷𨵷; 𨵷𨵷; 𨵷𨵷; 𨵷𨵷; 𨵷𨵷; ) CJK COMPATIBILITY IDEOGRAPH-2F9F1
+2F9F2;49E6;49E6;49E6;49E6; # (䧦䧦; 䧦; 䧦; 䧦; 䧦; ) CJK COMPATIBILITY IDEOGRAPH-2F9F2
+2F9F3;96C3;96C3;96C3;96C3; # (雃雃; 雃; 雃; 雃; 雃; ) CJK COMPATIBILITY IDEOGRAPH-2F9F3
+2F9F4;5DB2;5DB2;5DB2;5DB2; # (嶲嶲; 嶲; 嶲; 嶲; 嶲; ) CJK COMPATIBILITY IDEOGRAPH-2F9F4
+2F9F5;9723;9723;9723;9723; # (霣霣; 霣; 霣; 霣; 霣; ) CJK COMPATIBILITY IDEOGRAPH-2F9F5
+2F9F6;29145;29145;29145;29145; # (𩅅𩅅; 𩅅𩅅; 𩅅𩅅; 𩅅𩅅; 𩅅𩅅; ) CJK COMPATIBILITY IDEOGRAPH-2F9F6
+2F9F7;2921A;2921A;2921A;2921A; # (𩈚𩈚; 𩈚𩈚; 𩈚𩈚; 𩈚𩈚; 𩈚𩈚; ) CJK COMPATIBILITY IDEOGRAPH-2F9F7
+2F9F8;4A6E;4A6E;4A6E;4A6E; # (䩮䩮; 䩮; 䩮; 䩮; 䩮; ) CJK COMPATIBILITY IDEOGRAPH-2F9F8
+2F9F9;4A76;4A76;4A76;4A76; # (䩶䩶; 䩶; 䩶; 䩶; 䩶; ) CJK COMPATIBILITY IDEOGRAPH-2F9F9
+2F9FA;97E0;97E0;97E0;97E0; # (韠韠; 韠; 韠; 韠; 韠; ) CJK COMPATIBILITY IDEOGRAPH-2F9FA
+2F9FB;2940A;2940A;2940A;2940A; # (𩐊𩐊; 𩐊𩐊; 𩐊𩐊; 𩐊𩐊; 𩐊𩐊; ) CJK COMPATIBILITY IDEOGRAPH-2F9FB
+2F9FC;4AB2;4AB2;4AB2;4AB2; # (䪲䪲; 䪲; 䪲; 䪲; 䪲; ) CJK COMPATIBILITY IDEOGRAPH-2F9FC
+2F9FD;29496;29496;29496;29496; # (𩒖𩒖; 𩒖𩒖; 𩒖𩒖; 𩒖𩒖; 𩒖𩒖; ) CJK COMPATIBILITY IDEOGRAPH-2F9FD
+2F9FE;980B;980B;980B;980B; # (頋頋; 頋; 頋; 頋; 頋; ) CJK COMPATIBILITY IDEOGRAPH-2F9FE
+2F9FF;980B;980B;980B;980B; # (頋頋; 頋; 頋; 頋; 頋; ) CJK COMPATIBILITY IDEOGRAPH-2F9FF
+2FA00;9829;9829;9829;9829; # (頩頩; 頩; 頩; 頩; 頩; ) CJK COMPATIBILITY IDEOGRAPH-2FA00
+2FA01;295B6;295B6;295B6;295B6; # (𩖶𩖶; 𩖶𩖶; 𩖶𩖶; 𩖶𩖶; 𩖶𩖶; ) CJK COMPATIBILITY IDEOGRAPH-2FA01
+2FA02;98E2;98E2;98E2;98E2; # (飢飢; 飢; 飢; 飢; 飢; ) CJK COMPATIBILITY IDEOGRAPH-2FA02
+2FA03;4B33;4B33;4B33;4B33; # (䬳䬳; 䬳; 䬳; 䬳; 䬳; ) CJK COMPATIBILITY IDEOGRAPH-2FA03
+2FA04;9929;9929;9929;9929; # (餩餩; 餩; 餩; 餩; 餩; ) CJK COMPATIBILITY IDEOGRAPH-2FA04
+2FA05;99A7;99A7;99A7;99A7; # (馧馧; 馧; 馧; 馧; 馧; ) CJK COMPATIBILITY IDEOGRAPH-2FA05
+2FA06;99C2;99C2;99C2;99C2; # (駂駂; 駂; 駂; 駂; 駂; ) CJK COMPATIBILITY IDEOGRAPH-2FA06
+2FA07;99FE;99FE;99FE;99FE; # (駾駾; 駾; 駾; 駾; 駾; ) CJK COMPATIBILITY IDEOGRAPH-2FA07
+2FA08;4BCE;4BCE;4BCE;4BCE; # (䯎䯎; 䯎; 䯎; 䯎; 䯎; ) CJK COMPATIBILITY IDEOGRAPH-2FA08
+2FA09;29B30;29B30;29B30;29B30; # (𩬰𩬰; 𩬰𩬰; 𩬰𩬰; 𩬰𩬰; 𩬰𩬰; ) CJK COMPATIBILITY IDEOGRAPH-2FA09
+2FA0A;9B12;9B12;9B12;9B12; # (鬒鬒; 鬒; 鬒; 鬒; 鬒; ) CJK COMPATIBILITY IDEOGRAPH-2FA0A
+2FA0B;9C40;9C40;9C40;9C40; # (鱀鱀; 鱀; 鱀; 鱀; 鱀; ) CJK COMPATIBILITY IDEOGRAPH-2FA0B
+2FA0C;9CFD;9CFD;9CFD;9CFD; # (鳽鳽; 鳽; 鳽; 鳽; 鳽; ) CJK COMPATIBILITY IDEOGRAPH-2FA0C
+2FA0D;4CCE;4CCE;4CCE;4CCE; # (䳎䳎; 䳎; 䳎; 䳎; 䳎; ) CJK COMPATIBILITY IDEOGRAPH-2FA0D
+2FA0E;4CED;4CED;4CED;4CED; # (䳭䳭; 䳭; 䳭; 䳭; 䳭; ) CJK COMPATIBILITY IDEOGRAPH-2FA0E
+2FA0F;9D67;9D67;9D67;9D67; # (鵧鵧; 鵧; 鵧; 鵧; 鵧; ) CJK COMPATIBILITY IDEOGRAPH-2FA0F
+2FA10;2A0CE;2A0CE;2A0CE;2A0CE; # (𪃎𪃎; 𪃎𪃎; 𪃎𪃎; 𪃎𪃎; 𪃎𪃎; ) CJK COMPATIBILITY IDEOGRAPH-2FA10
+2FA11;4CF8;4CF8;4CF8;4CF8; # (䳸䳸; 䳸; 䳸; 䳸; 䳸; ) CJK COMPATIBILITY IDEOGRAPH-2FA11
+2FA12;2A105;2A105;2A105;2A105; # (𪄅𪄅; 𪄅𪄅; 𪄅𪄅; 𪄅𪄅; 𪄅𪄅; ) CJK COMPATIBILITY IDEOGRAPH-2FA12
+2FA13;2A20E;2A20E;2A20E;2A20E; # (𪈎𪈎; 𪈎𪈎; 𪈎𪈎; 𪈎𪈎; 𪈎𪈎; ) CJK COMPATIBILITY IDEOGRAPH-2FA13
+2FA14;2A291;2A291;2A291;2A291; # (𪊑𪊑; 𪊑𪊑; 𪊑𪊑; 𪊑𪊑; 𪊑𪊑; ) CJK COMPATIBILITY IDEOGRAPH-2FA14
+2FA15;9EBB;9EBB;9EBB;9EBB; # (麻麻; 麻; 麻; 麻; 麻; ) CJK COMPATIBILITY IDEOGRAPH-2FA15
+2FA16;4D56;4D56;4D56;4D56; # (䵖䵖; 䵖; 䵖; 䵖; 䵖; ) CJK COMPATIBILITY IDEOGRAPH-2FA16
+2FA17;9EF9;9EF9;9EF9;9EF9; # (黹黹; 黹; 黹; 黹; 黹; ) CJK COMPATIBILITY IDEOGRAPH-2FA17
+2FA18;9EFE;9EFE;9EFE;9EFE; # (黾黾; 黾; 黾; 黾; 黾; ) CJK COMPATIBILITY IDEOGRAPH-2FA18
+2FA19;9F05;9F05;9F05;9F05; # (鼅鼅; 鼅; 鼅; 鼅; 鼅; ) CJK COMPATIBILITY IDEOGRAPH-2FA19
+2FA1A;9F0F;9F0F;9F0F;9F0F; # (鼏鼏; 鼏; 鼏; 鼏; 鼏; ) CJK COMPATIBILITY IDEOGRAPH-2FA1A
+2FA1B;9F16;9F16;9F16;9F16; # (鼖鼖; 鼖; 鼖; 鼖; 鼖; ) CJK COMPATIBILITY IDEOGRAPH-2FA1B
+2FA1C;9F3B;9F3B;9F3B;9F3B; # (鼻鼻; 鼻; 鼻; 鼻; 鼻; ) CJK COMPATIBILITY IDEOGRAPH-2FA1C
+2FA1D;2A600;2A600;2A600;2A600; # (𪘀𪘀; 𪘀𪘀; 𪘀𪘀; 𪘀𪘀; 𪘀𪘀; ) CJK COMPATIBILITY IDEOGRAPH-2FA1D
+#
+@Part2 # Canonical Order Test
+#
+0061 0315 0300 05AE 0300 0062;00E0 05AE 0300 0315 0062;0061 05AE 0300 0300 0315 0062;00E0 05AE 0300 0315 0062;0061 05AE 0300 0300 0315 0062; # (a◌̕◌̀◌֮◌̀b; à◌֮◌̀◌̕b; a◌֮◌̀◌̀◌̕b; à◌֮◌̀◌̕b; a◌֮◌̀◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING GRAVE ACCENT, LATIN SMALL LETTER B
+0061 0300 0315 0300 05AE 0062;00E0 05AE 0300 0315 0062;0061 05AE 0300 0300 0315 0062;00E0 05AE 0300 0315 0062;0061 05AE 0300 0300 0315 0062; # (a◌̀◌̕◌̀◌֮b; à◌֮◌̀◌̕b; a◌֮◌̀◌̀◌̕b; à◌֮◌̀◌̕b; a◌֮◌̀◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING GRAVE ACCENT, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0301 0062;00E0 05AE 0301 0315 0062;0061 05AE 0300 0301 0315 0062;00E0 05AE 0301 0315 0062;0061 05AE 0300 0301 0315 0062; # (a◌̕◌̀◌֮◌́b; à◌֮◌́◌̕b; a◌֮◌̀◌́◌̕b; à◌֮◌́◌̕b; a◌֮◌̀◌́◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING ACUTE ACCENT, LATIN SMALL LETTER B
+0061 0301 0315 0300 05AE 0062;00E1 05AE 0300 0315 0062;0061 05AE 0301 0300 0315 0062;00E1 05AE 0300 0315 0062;0061 05AE 0301 0300 0315 0062; # (a◌́◌̕◌̀◌֮b; á◌֮◌̀◌̕b; a◌֮◌́◌̀◌̕b; á◌֮◌̀◌̕b; a◌֮◌́◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING ACUTE ACCENT, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0302 0062;00E0 05AE 0302 0315 0062;0061 05AE 0300 0302 0315 0062;00E0 05AE 0302 0315 0062;0061 05AE 0300 0302 0315 0062; # (a◌̕◌̀◌֮◌̂b; à◌֮◌̂◌̕b; a◌֮◌̀◌̂◌̕b; à◌֮◌̂◌̕b; a◌֮◌̀◌̂◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING CIRCUMFLEX ACCENT, LATIN SMALL LETTER B
+0061 0302 0315 0300 05AE 0062;1EA7 05AE 0315 0062;0061 05AE 0302 0300 0315 0062;1EA7 05AE 0315 0062;0061 05AE 0302 0300 0315 0062; # (a◌̂◌̕◌̀◌֮b; ầ◌֮◌̕b; a◌֮◌̂◌̀◌̕b; ầ◌֮◌̕b; a◌֮◌̂◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING CIRCUMFLEX ACCENT, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0303 0062;00E0 05AE 0303 0315 0062;0061 05AE 0300 0303 0315 0062;00E0 05AE 0303 0315 0062;0061 05AE 0300 0303 0315 0062; # (a◌̕◌̀◌֮◌̃b; à◌֮◌̃◌̕b; a◌֮◌̀◌̃◌̕b; à◌֮◌̃◌̕b; a◌֮◌̀◌̃◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING TILDE, LATIN SMALL LETTER B
+0061 0303 0315 0300 05AE 0062;00E3 05AE 0300 0315 0062;0061 05AE 0303 0300 0315 0062;00E3 05AE 0300 0315 0062;0061 05AE 0303 0300 0315 0062; # (a◌̃◌̕◌̀◌֮b; ã◌֮◌̀◌̕b; a◌֮◌̃◌̀◌̕b; ã◌֮◌̀◌̕b; a◌֮◌̃◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING TILDE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0304 0062;00E0 05AE 0304 0315 0062;0061 05AE 0300 0304 0315 0062;00E0 05AE 0304 0315 0062;0061 05AE 0300 0304 0315 0062; # (a◌̕◌̀◌֮◌̄b; à◌֮◌̄◌̕b; a◌֮◌̀◌̄◌̕b; à◌֮◌̄◌̕b; a◌֮◌̀◌̄◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING MACRON, LATIN SMALL LETTER B
+0061 0304 0315 0300 05AE 0062;0101 05AE 0300 0315 0062;0061 05AE 0304 0300 0315 0062;0101 05AE 0300 0315 0062;0061 05AE 0304 0300 0315 0062; # (a◌̄◌̕◌̀◌֮b; ā◌֮◌̀◌̕b; a◌֮◌̄◌̀◌̕b; ā◌֮◌̀◌̕b; a◌֮◌̄◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING MACRON, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0305 0062;00E0 05AE 0305 0315 0062;0061 05AE 0300 0305 0315 0062;00E0 05AE 0305 0315 0062;0061 05AE 0300 0305 0315 0062; # (a◌̕◌̀◌֮◌̅b; à◌֮◌̅◌̕b; a◌֮◌̀◌̅◌̕b; à◌֮◌̅◌̕b; a◌֮◌̀◌̅◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING OVERLINE, LATIN SMALL LETTER B
+0061 0305 0315 0300 05AE 0062;0061 05AE 0305 0300 0315 0062;0061 05AE 0305 0300 0315 0062;0061 05AE 0305 0300 0315 0062;0061 05AE 0305 0300 0315 0062; # (a◌̅◌̕◌̀◌֮b; a◌֮◌̅◌̀◌̕b; a◌֮◌̅◌̀◌̕b; a◌֮◌̅◌̀◌̕b; a◌֮◌̅◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING OVERLINE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0306 0062;00E0 05AE 0306 0315 0062;0061 05AE 0300 0306 0315 0062;00E0 05AE 0306 0315 0062;0061 05AE 0300 0306 0315 0062; # (a◌̕◌̀◌֮◌̆b; à◌֮◌̆◌̕b; a◌֮◌̀◌̆◌̕b; à◌֮◌̆◌̕b; a◌֮◌̀◌̆◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING BREVE, LATIN SMALL LETTER B
+0061 0306 0315 0300 05AE 0062;1EB1 05AE 0315 0062;0061 05AE 0306 0300 0315 0062;1EB1 05AE 0315 0062;0061 05AE 0306 0300 0315 0062; # (a◌̆◌̕◌̀◌֮b; ằ◌֮◌̕b; a◌֮◌̆◌̀◌̕b; ằ◌֮◌̕b; a◌֮◌̆◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING BREVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0307 0062;00E0 05AE 0307 0315 0062;0061 05AE 0300 0307 0315 0062;00E0 05AE 0307 0315 0062;0061 05AE 0300 0307 0315 0062; # (a◌̕◌̀◌֮◌̇b; à◌֮◌̇◌̕b; a◌֮◌̀◌̇◌̕b; à◌֮◌̇◌̕b; a◌֮◌̀◌̇◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING DOT ABOVE, LATIN SMALL LETTER B
+0061 0307 0315 0300 05AE 0062;0227 05AE 0300 0315 0062;0061 05AE 0307 0300 0315 0062;0227 05AE 0300 0315 0062;0061 05AE 0307 0300 0315 0062; # (a◌̇◌̕◌̀◌֮b; ȧ◌֮◌̀◌̕b; a◌֮◌̇◌̀◌̕b; ȧ◌֮◌̀◌̕b; a◌֮◌̇◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING DOT ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0308 0062;00E0 05AE 0308 0315 0062;0061 05AE 0300 0308 0315 0062;00E0 05AE 0308 0315 0062;0061 05AE 0300 0308 0315 0062; # (a◌̕◌̀◌֮◌̈b; à◌֮◌̈◌̕b; a◌֮◌̀◌̈◌̕b; à◌֮◌̈◌̕b; a◌֮◌̀◌̈◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING DIAERESIS, LATIN SMALL LETTER B
+0061 0308 0315 0300 05AE 0062;00E4 05AE 0300 0315 0062;0061 05AE 0308 0300 0315 0062;00E4 05AE 0300 0315 0062;0061 05AE 0308 0300 0315 0062; # (a◌̈◌̕◌̀◌֮b; ä◌֮◌̀◌̕b; a◌֮◌̈◌̀◌̕b; ä◌֮◌̀◌̕b; a◌֮◌̈◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING DIAERESIS, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0309 0062;00E0 05AE 0309 0315 0062;0061 05AE 0300 0309 0315 0062;00E0 05AE 0309 0315 0062;0061 05AE 0300 0309 0315 0062; # (a◌̕◌̀◌֮◌̉b; à◌֮◌̉◌̕b; a◌֮◌̀◌̉◌̕b; à◌֮◌̉◌̕b; a◌֮◌̀◌̉◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING HOOK ABOVE, LATIN SMALL LETTER B
+0061 0309 0315 0300 05AE 0062;1EA3 05AE 0300 0315 0062;0061 05AE 0309 0300 0315 0062;1EA3 05AE 0300 0315 0062;0061 05AE 0309 0300 0315 0062; # (a◌̉◌̕◌̀◌֮b; ả◌֮◌̀◌̕b; a◌֮◌̉◌̀◌̕b; ả◌֮◌̀◌̕b; a◌֮◌̉◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING HOOK ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 030A 0062;00E0 05AE 030A 0315 0062;0061 05AE 0300 030A 0315 0062;00E0 05AE 030A 0315 0062;0061 05AE 0300 030A 0315 0062; # (a◌̕◌̀◌֮◌̊b; à◌֮◌̊◌̕b; a◌֮◌̀◌̊◌̕b; à◌֮◌̊◌̕b; a◌֮◌̀◌̊◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING RING ABOVE, LATIN SMALL LETTER B
+0061 030A 0315 0300 05AE 0062;00E5 05AE 0300 0315 0062;0061 05AE 030A 0300 0315 0062;00E5 05AE 0300 0315 0062;0061 05AE 030A 0300 0315 0062; # (a◌̊◌̕◌̀◌֮b; å◌֮◌̀◌̕b; a◌֮◌̊◌̀◌̕b; å◌֮◌̀◌̕b; a◌֮◌̊◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING RING ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 030B 0062;00E0 05AE 030B 0315 0062;0061 05AE 0300 030B 0315 0062;00E0 05AE 030B 0315 0062;0061 05AE 0300 030B 0315 0062; # (a◌̕◌̀◌֮◌̋b; à◌֮◌̋◌̕b; a◌֮◌̀◌̋◌̕b; à◌֮◌̋◌̕b; a◌֮◌̀◌̋◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING DOUBLE ACUTE ACCENT, LATIN SMALL LETTER B
+0061 030B 0315 0300 05AE 0062;0061 05AE 030B 0300 0315 0062;0061 05AE 030B 0300 0315 0062;0061 05AE 030B 0300 0315 0062;0061 05AE 030B 0300 0315 0062; # (a◌̋◌̕◌̀◌֮b; a◌֮◌̋◌̀◌̕b; a◌֮◌̋◌̀◌̕b; a◌֮◌̋◌̀◌̕b; a◌֮◌̋◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING DOUBLE ACUTE ACCENT, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 030C 0062;00E0 05AE 030C 0315 0062;0061 05AE 0300 030C 0315 0062;00E0 05AE 030C 0315 0062;0061 05AE 0300 030C 0315 0062; # (a◌̕◌̀◌֮◌̌b; à◌֮◌̌◌̕b; a◌֮◌̀◌̌◌̕b; à◌֮◌̌◌̕b; a◌֮◌̀◌̌◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING CARON, LATIN SMALL LETTER B
+0061 030C 0315 0300 05AE 0062;01CE 05AE 0300 0315 0062;0061 05AE 030C 0300 0315 0062;01CE 05AE 0300 0315 0062;0061 05AE 030C 0300 0315 0062; # (a◌̌◌̕◌̀◌֮b; ǎ◌֮◌̀◌̕b; a◌֮◌̌◌̀◌̕b; ǎ◌֮◌̀◌̕b; a◌֮◌̌◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING CARON, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 030D 0062;00E0 05AE 030D 0315 0062;0061 05AE 0300 030D 0315 0062;00E0 05AE 030D 0315 0062;0061 05AE 0300 030D 0315 0062; # (a◌̕◌̀◌֮◌̍b; à◌֮◌̍◌̕b; a◌֮◌̀◌̍◌̕b; à◌֮◌̍◌̕b; a◌֮◌̀◌̍◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING VERTICAL LINE ABOVE, LATIN SMALL LETTER B
+0061 030D 0315 0300 05AE 0062;0061 05AE 030D 0300 0315 0062;0061 05AE 030D 0300 0315 0062;0061 05AE 030D 0300 0315 0062;0061 05AE 030D 0300 0315 0062; # (a◌̍◌̕◌̀◌֮b; a◌֮◌̍◌̀◌̕b; a◌֮◌̍◌̀◌̕b; a◌֮◌̍◌̀◌̕b; a◌֮◌̍◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING VERTICAL LINE ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 030E 0062;00E0 05AE 030E 0315 0062;0061 05AE 0300 030E 0315 0062;00E0 05AE 030E 0315 0062;0061 05AE 0300 030E 0315 0062; # (a◌̕◌̀◌֮◌̎b; à◌֮◌̎◌̕b; a◌֮◌̀◌̎◌̕b; à◌֮◌̎◌̕b; a◌֮◌̀◌̎◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING DOUBLE VERTICAL LINE ABOVE, LATIN SMALL LETTER B
+0061 030E 0315 0300 05AE 0062;0061 05AE 030E 0300 0315 0062;0061 05AE 030E 0300 0315 0062;0061 05AE 030E 0300 0315 0062;0061 05AE 030E 0300 0315 0062; # (a◌̎◌̕◌̀◌֮b; a◌֮◌̎◌̀◌̕b; a◌֮◌̎◌̀◌̕b; a◌֮◌̎◌̀◌̕b; a◌֮◌̎◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING DOUBLE VERTICAL LINE ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 030F 0062;00E0 05AE 030F 0315 0062;0061 05AE 0300 030F 0315 0062;00E0 05AE 030F 0315 0062;0061 05AE 0300 030F 0315 0062; # (a◌̕◌̀◌֮◌̏b; à◌֮◌̏◌̕b; a◌֮◌̀◌̏◌̕b; à◌֮◌̏◌̕b; a◌֮◌̀◌̏◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING DOUBLE GRAVE ACCENT, LATIN SMALL LETTER B
+0061 030F 0315 0300 05AE 0062;0201 05AE 0300 0315 0062;0061 05AE 030F 0300 0315 0062;0201 05AE 0300 0315 0062;0061 05AE 030F 0300 0315 0062; # (a◌̏◌̕◌̀◌֮b; ȁ◌֮◌̀◌̕b; a◌֮◌̏◌̀◌̕b; ȁ◌֮◌̀◌̕b; a◌֮◌̏◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING DOUBLE GRAVE ACCENT, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0310 0062;00E0 05AE 0310 0315 0062;0061 05AE 0300 0310 0315 0062;00E0 05AE 0310 0315 0062;0061 05AE 0300 0310 0315 0062; # (a◌̕◌̀◌֮◌̐b; à◌֮◌̐◌̕b; a◌֮◌̀◌̐◌̕b; à◌֮◌̐◌̕b; a◌֮◌̀◌̐◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING CANDRABINDU, LATIN SMALL LETTER B
+0061 0310 0315 0300 05AE 0062;0061 05AE 0310 0300 0315 0062;0061 05AE 0310 0300 0315 0062;0061 05AE 0310 0300 0315 0062;0061 05AE 0310 0300 0315 0062; # (a◌̐◌̕◌̀◌֮b; a◌֮◌̐◌̀◌̕b; a◌֮◌̐◌̀◌̕b; a◌֮◌̐◌̀◌̕b; a◌֮◌̐◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING CANDRABINDU, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0311 0062;00E0 05AE 0311 0315 0062;0061 05AE 0300 0311 0315 0062;00E0 05AE 0311 0315 0062;0061 05AE 0300 0311 0315 0062; # (a◌̕◌̀◌֮◌̑b; à◌֮◌̑◌̕b; a◌֮◌̀◌̑◌̕b; à◌֮◌̑◌̕b; a◌֮◌̀◌̑◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING INVERTED BREVE, LATIN SMALL LETTER B
+0061 0311 0315 0300 05AE 0062;0203 05AE 0300 0315 0062;0061 05AE 0311 0300 0315 0062;0203 05AE 0300 0315 0062;0061 05AE 0311 0300 0315 0062; # (a◌̑◌̕◌̀◌֮b; ȃ◌֮◌̀◌̕b; a◌֮◌̑◌̀◌̕b; ȃ◌֮◌̀◌̕b; a◌֮◌̑◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING INVERTED BREVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0312 0062;00E0 05AE 0312 0315 0062;0061 05AE 0300 0312 0315 0062;00E0 05AE 0312 0315 0062;0061 05AE 0300 0312 0315 0062; # (a◌̕◌̀◌֮◌̒b; à◌֮◌̒◌̕b; a◌֮◌̀◌̒◌̕b; à◌֮◌̒◌̕b; a◌֮◌̀◌̒◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING TURNED COMMA ABOVE, LATIN SMALL LETTER B
+0061 0312 0315 0300 05AE 0062;0061 05AE 0312 0300 0315 0062;0061 05AE 0312 0300 0315 0062;0061 05AE 0312 0300 0315 0062;0061 05AE 0312 0300 0315 0062; # (a◌̒◌̕◌̀◌֮b; a◌֮◌̒◌̀◌̕b; a◌֮◌̒◌̀◌̕b; a◌֮◌̒◌̀◌̕b; a◌֮◌̒◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING TURNED COMMA ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0313 0062;00E0 05AE 0313 0315 0062;0061 05AE 0300 0313 0315 0062;00E0 05AE 0313 0315 0062;0061 05AE 0300 0313 0315 0062; # (a◌̕◌̀◌֮◌̓b; à◌֮◌̓◌̕b; a◌֮◌̀◌̓◌̕b; à◌֮◌̓◌̕b; a◌֮◌̀◌̓◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING COMMA ABOVE, LATIN SMALL LETTER B
+0061 0313 0315 0300 05AE 0062;0061 05AE 0313 0300 0315 0062;0061 05AE 0313 0300 0315 0062;0061 05AE 0313 0300 0315 0062;0061 05AE 0313 0300 0315 0062; # (a◌̓◌̕◌̀◌֮b; a◌֮◌̓◌̀◌̕b; a◌֮◌̓◌̀◌̕b; a◌֮◌̓◌̀◌̕b; a◌֮◌̓◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0314 0062;00E0 05AE 0314 0315 0062;0061 05AE 0300 0314 0315 0062;00E0 05AE 0314 0315 0062;0061 05AE 0300 0314 0315 0062; # (a◌̕◌̀◌֮◌̔b; à◌֮◌̔◌̕b; a◌֮◌̀◌̔◌̕b; à◌֮◌̔◌̕b; a◌֮◌̀◌̔◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING REVERSED COMMA ABOVE, LATIN SMALL LETTER B
+0061 0314 0315 0300 05AE 0062;0061 05AE 0314 0300 0315 0062;0061 05AE 0314 0300 0315 0062;0061 05AE 0314 0300 0315 0062;0061 05AE 0314 0300 0315 0062; # (a◌̔◌̕◌̀◌֮b; a◌֮◌̔◌̀◌̕b; a◌֮◌̔◌̀◌̕b; a◌֮◌̔◌̀◌̕b; a◌֮◌̔◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING REVERSED COMMA ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 035F 0315 0300 0315 0062;00E0 0315 0315 035F 0062;0061 0300 0315 0315 035F 0062;00E0 0315 0315 035F 0062;0061 0300 0315 0315 035F 0062; # (a◌͟◌̕◌̀◌̕b; à◌̕◌̕◌͟b; a◌̀◌̕◌̕◌͟b; à◌̕◌̕◌͟b; a◌̀◌̕◌̕◌͟b; ) LATIN SMALL LETTER A, COMBINING DOUBLE MACRON BELOW, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, COMBINING COMMA ABOVE RIGHT, LATIN SMALL LETTER B
+0061 0315 035F 0315 0300 0062;00E0 0315 0315 035F 0062;0061 0300 0315 0315 035F 0062;00E0 0315 0315 035F 0062;0061 0300 0315 0315 035F 0062; # (a◌̕◌͟◌̕◌̀b; à◌̕◌̕◌͟b; a◌̀◌̕◌̕◌͟b; à◌̕◌̕◌͟b; a◌̀◌̕◌̕◌͟b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING DOUBLE MACRON BELOW, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, LATIN SMALL LETTER B
+0061 059A 0316 302A 0316 0062;0061 302A 0316 0316 059A 0062;0061 302A 0316 0316 059A 0062;0061 302A 0316 0316 059A 0062;0061 302A 0316 0316 059A 0062; # (a◌֚◌̖◌〪◌̖b; a◌〪◌̖◌̖◌֚b; a◌〪◌̖◌̖◌֚b; a◌〪◌̖◌̖◌֚b; a◌〪◌̖◌̖◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING GRAVE ACCENT BELOW, LATIN SMALL LETTER B
+0061 0316 059A 0316 302A 0062;0061 302A 0316 0316 059A 0062;0061 302A 0316 0316 059A 0062;0061 302A 0316 0316 059A 0062;0061 302A 0316 0316 059A 0062; # (a◌̖◌֚◌̖◌〪b; a◌〪◌̖◌̖◌֚b; a◌〪◌̖◌̖◌֚b; a◌〪◌̖◌̖◌֚b; a◌〪◌̖◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING GRAVE ACCENT BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0317 0062;0061 302A 0316 0317 059A 0062;0061 302A 0316 0317 059A 0062;0061 302A 0316 0317 059A 0062;0061 302A 0316 0317 059A 0062; # (a◌֚◌̖◌〪◌̗b; a◌〪◌̖◌̗◌֚b; a◌〪◌̖◌̗◌֚b; a◌〪◌̖◌̗◌֚b; a◌〪◌̖◌̗◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING ACUTE ACCENT BELOW, LATIN SMALL LETTER B
+0061 0317 059A 0316 302A 0062;0061 302A 0317 0316 059A 0062;0061 302A 0317 0316 059A 0062;0061 302A 0317 0316 059A 0062;0061 302A 0317 0316 059A 0062; # (a◌̗◌֚◌̖◌〪b; a◌〪◌̗◌̖◌֚b; a◌〪◌̗◌̖◌֚b; a◌〪◌̗◌̖◌֚b; a◌〪◌̗◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING ACUTE ACCENT BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0318 0062;0061 302A 0316 0318 059A 0062;0061 302A 0316 0318 059A 0062;0061 302A 0316 0318 059A 0062;0061 302A 0316 0318 059A 0062; # (a◌֚◌̖◌〪◌̘b; a◌〪◌̖◌̘◌֚b; a◌〪◌̖◌̘◌֚b; a◌〪◌̖◌̘◌֚b; a◌〪◌̖◌̘◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING LEFT TACK BELOW, LATIN SMALL LETTER B
+0061 0318 059A 0316 302A 0062;0061 302A 0318 0316 059A 0062;0061 302A 0318 0316 059A 0062;0061 302A 0318 0316 059A 0062;0061 302A 0318 0316 059A 0062; # (a◌̘◌֚◌̖◌〪b; a◌〪◌̘◌̖◌֚b; a◌〪◌̘◌̖◌֚b; a◌〪◌̘◌̖◌֚b; a◌〪◌̘◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING LEFT TACK BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0319 0062;0061 302A 0316 0319 059A 0062;0061 302A 0316 0319 059A 0062;0061 302A 0316 0319 059A 0062;0061 302A 0316 0319 059A 0062; # (a◌֚◌̖◌〪◌̙b; a◌〪◌̖◌̙◌֚b; a◌〪◌̖◌̙◌֚b; a◌〪◌̖◌̙◌֚b; a◌〪◌̖◌̙◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING RIGHT TACK BELOW, LATIN SMALL LETTER B
+0061 0319 059A 0316 302A 0062;0061 302A 0319 0316 059A 0062;0061 302A 0319 0316 059A 0062;0061 302A 0319 0316 059A 0062;0061 302A 0319 0316 059A 0062; # (a◌̙◌֚◌̖◌〪b; a◌〪◌̙◌̖◌֚b; a◌〪◌̙◌̖◌֚b; a◌〪◌̙◌̖◌֚b; a◌〪◌̙◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING RIGHT TACK BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 035F 0315 0300 031A 0062;00E0 0315 031A 035F 0062;0061 0300 0315 031A 035F 0062;00E0 0315 031A 035F 0062;0061 0300 0315 031A 035F 0062; # (a◌͟◌̕◌̀◌̚b; à◌̕◌̚◌͟b; a◌̀◌̕◌̚◌͟b; à◌̕◌̚◌͟b; a◌̀◌̕◌̚◌͟b; ) LATIN SMALL LETTER A, COMBINING DOUBLE MACRON BELOW, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, COMBINING LEFT ANGLE ABOVE, LATIN SMALL LETTER B
+0061 031A 035F 0315 0300 0062;00E0 031A 0315 035F 0062;0061 0300 031A 0315 035F 0062;00E0 031A 0315 035F 0062;0061 0300 031A 0315 035F 0062; # (a◌̚◌͟◌̕◌̀b; à◌̚◌̕◌͟b; a◌̀◌̚◌̕◌͟b; à◌̚◌̕◌͟b; a◌̀◌̚◌̕◌͟b; ) LATIN SMALL LETTER A, COMBINING LEFT ANGLE ABOVE, COMBINING DOUBLE MACRON BELOW, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, LATIN SMALL LETTER B
+0061 302A 031B 0321 031B 0062;0061 0321 031B 031B 302A 0062;0061 0321 031B 031B 302A 0062;0061 0321 031B 031B 302A 0062;0061 0321 031B 031B 302A 0062; # (a◌〪◌̛◌̡◌̛b; a◌̡◌̛◌̛◌〪b; a◌̡◌̛◌̛◌〪b; a◌̡◌̛◌̛◌〪b; a◌̡◌̛◌̛◌〪b; ) LATIN SMALL LETTER A, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, COMBINING HORN, LATIN SMALL LETTER B
+0061 031B 302A 031B 0321 0062;0061 0321 031B 031B 302A 0062;0061 0321 031B 031B 302A 0062;0061 0321 031B 031B 302A 0062;0061 0321 031B 031B 302A 0062; # (a◌̛◌〪◌̛◌̡b; a◌̡◌̛◌̛◌〪b; a◌̡◌̛◌̛◌〪b; a◌̡◌̛◌̛◌〪b; a◌̡◌̛◌̛◌〪b; ) LATIN SMALL LETTER A, COMBINING HORN, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, LATIN SMALL LETTER B
+0061 059A 0316 302A 031C 0062;0061 302A 0316 031C 059A 0062;0061 302A 0316 031C 059A 0062;0061 302A 0316 031C 059A 0062;0061 302A 0316 031C 059A 0062; # (a◌֚◌̖◌〪◌̜b; a◌〪◌̖◌̜◌֚b; a◌〪◌̖◌̜◌֚b; a◌〪◌̖◌̜◌֚b; a◌〪◌̖◌̜◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING LEFT HALF RING BELOW, LATIN SMALL LETTER B
+0061 031C 059A 0316 302A 0062;0061 302A 031C 0316 059A 0062;0061 302A 031C 0316 059A 0062;0061 302A 031C 0316 059A 0062;0061 302A 031C 0316 059A 0062; # (a◌̜◌֚◌̖◌〪b; a◌〪◌̜◌̖◌֚b; a◌〪◌̜◌̖◌֚b; a◌〪◌̜◌̖◌֚b; a◌〪◌̜◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING LEFT HALF RING BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 031D 0062;0061 302A 0316 031D 059A 0062;0061 302A 0316 031D 059A 0062;0061 302A 0316 031D 059A 0062;0061 302A 0316 031D 059A 0062; # (a◌֚◌̖◌〪◌̝b; a◌〪◌̖◌̝◌֚b; a◌〪◌̖◌̝◌֚b; a◌〪◌̖◌̝◌֚b; a◌〪◌̖◌̝◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING UP TACK BELOW, LATIN SMALL LETTER B
+0061 031D 059A 0316 302A 0062;0061 302A 031D 0316 059A 0062;0061 302A 031D 0316 059A 0062;0061 302A 031D 0316 059A 0062;0061 302A 031D 0316 059A 0062; # (a◌̝◌֚◌̖◌〪b; a◌〪◌̝◌̖◌֚b; a◌〪◌̝◌̖◌֚b; a◌〪◌̝◌̖◌֚b; a◌〪◌̝◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING UP TACK BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 031E 0062;0061 302A 0316 031E 059A 0062;0061 302A 0316 031E 059A 0062;0061 302A 0316 031E 059A 0062;0061 302A 0316 031E 059A 0062; # (a◌֚◌̖◌〪◌̞b; a◌〪◌̖◌̞◌֚b; a◌〪◌̖◌̞◌֚b; a◌〪◌̖◌̞◌֚b; a◌〪◌̖◌̞◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING DOWN TACK BELOW, LATIN SMALL LETTER B
+0061 031E 059A 0316 302A 0062;0061 302A 031E 0316 059A 0062;0061 302A 031E 0316 059A 0062;0061 302A 031E 0316 059A 0062;0061 302A 031E 0316 059A 0062; # (a◌̞◌֚◌̖◌〪b; a◌〪◌̞◌̖◌֚b; a◌〪◌̞◌̖◌֚b; a◌〪◌̞◌̖◌֚b; a◌〪◌̞◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING DOWN TACK BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 031F 0062;0061 302A 0316 031F 059A 0062;0061 302A 0316 031F 059A 0062;0061 302A 0316 031F 059A 0062;0061 302A 0316 031F 059A 0062; # (a◌֚◌̖◌〪◌̟b; a◌〪◌̖◌̟◌֚b; a◌〪◌̖◌̟◌֚b; a◌〪◌̖◌̟◌֚b; a◌〪◌̖◌̟◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING PLUS SIGN BELOW, LATIN SMALL LETTER B
+0061 031F 059A 0316 302A 0062;0061 302A 031F 0316 059A 0062;0061 302A 031F 0316 059A 0062;0061 302A 031F 0316 059A 0062;0061 302A 031F 0316 059A 0062; # (a◌̟◌֚◌̖◌〪b; a◌〪◌̟◌̖◌֚b; a◌〪◌̟◌̖◌֚b; a◌〪◌̟◌̖◌֚b; a◌〪◌̟◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING PLUS SIGN BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0320 0062;0061 302A 0316 0320 059A 0062;0061 302A 0316 0320 059A 0062;0061 302A 0316 0320 059A 0062;0061 302A 0316 0320 059A 0062; # (a◌֚◌̖◌〪◌̠b; a◌〪◌̖◌̠◌֚b; a◌〪◌̖◌̠◌֚b; a◌〪◌̖◌̠◌֚b; a◌〪◌̖◌̠◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING MINUS SIGN BELOW, LATIN SMALL LETTER B
+0061 0320 059A 0316 302A 0062;0061 302A 0320 0316 059A 0062;0061 302A 0320 0316 059A 0062;0061 302A 0320 0316 059A 0062;0061 302A 0320 0316 059A 0062; # (a◌̠◌֚◌̖◌〪b; a◌〪◌̠◌̖◌֚b; a◌〪◌̠◌̖◌֚b; a◌〪◌̠◌̖◌֚b; a◌〪◌̠◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING MINUS SIGN BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 031B 0321 0F74 0321 0062;0061 0F74 0321 0321 031B 0062;0061 0F74 0321 0321 031B 0062;0061 0F74 0321 0321 031B 0062;0061 0F74 0321 0321 031B 0062; # (a◌̛◌̡◌ུ◌̡b; a◌ུ◌̡◌̡◌̛b; a◌ུ◌̡◌̡◌̛b; a◌ུ◌̡◌̡◌̛b; a◌ུ◌̡◌̡◌̛b; ) LATIN SMALL LETTER A, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, TIBETAN VOWEL SIGN U, COMBINING PALATALIZED HOOK BELOW, LATIN SMALL LETTER B
+0061 0321 031B 0321 0F74 0062;0061 0F74 0321 0321 031B 0062;0061 0F74 0321 0321 031B 0062;0061 0F74 0321 0321 031B 0062;0061 0F74 0321 0321 031B 0062; # (a◌̡◌̛◌̡◌ུb; a◌ུ◌̡◌̡◌̛b; a◌ུ◌̡◌̡◌̛b; a◌ུ◌̡◌̡◌̛b; a◌ུ◌̡◌̡◌̛b; ) LATIN SMALL LETTER A, COMBINING PALATALIZED HOOK BELOW, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, TIBETAN VOWEL SIGN U, LATIN SMALL LETTER B
+0061 031B 0321 0F74 0322 0062;0061 0F74 0321 0322 031B 0062;0061 0F74 0321 0322 031B 0062;0061 0F74 0321 0322 031B 0062;0061 0F74 0321 0322 031B 0062; # (a◌̛◌̡◌ུ◌̢b; a◌ུ◌̡◌̢◌̛b; a◌ུ◌̡◌̢◌̛b; a◌ུ◌̡◌̢◌̛b; a◌ུ◌̡◌̢◌̛b; ) LATIN SMALL LETTER A, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, TIBETAN VOWEL SIGN U, COMBINING RETROFLEX HOOK BELOW, LATIN SMALL LETTER B
+0061 0322 031B 0321 0F74 0062;0061 0F74 0322 0321 031B 0062;0061 0F74 0322 0321 031B 0062;0061 0F74 0322 0321 031B 0062;0061 0F74 0322 0321 031B 0062; # (a◌̢◌̛◌̡◌ུb; a◌ུ◌̢◌̡◌̛b; a◌ུ◌̢◌̡◌̛b; a◌ུ◌̢◌̡◌̛b; a◌ུ◌̢◌̡◌̛b; ) LATIN SMALL LETTER A, COMBINING RETROFLEX HOOK BELOW, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, TIBETAN VOWEL SIGN U, LATIN SMALL LETTER B
+0061 059A 0316 302A 0323 0062;0061 302A 0316 0323 059A 0062;0061 302A 0316 0323 059A 0062;0061 302A 0316 0323 059A 0062;0061 302A 0316 0323 059A 0062; # (a◌֚◌̖◌〪◌̣b; a◌〪◌̖◌̣◌֚b; a◌〪◌̖◌̣◌֚b; a◌〪◌̖◌̣◌֚b; a◌〪◌̖◌̣◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING DOT BELOW, LATIN SMALL LETTER B
+0061 0323 059A 0316 302A 0062;1EA1 302A 0316 059A 0062;0061 302A 0323 0316 059A 0062;1EA1 302A 0316 059A 0062;0061 302A 0323 0316 059A 0062; # (a◌̣◌֚◌̖◌〪b; ạ◌〪◌̖◌֚b; a◌〪◌̣◌̖◌֚b; ạ◌〪◌̖◌֚b; a◌〪◌̣◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING DOT BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0324 0062;0061 302A 0316 0324 059A 0062;0061 302A 0316 0324 059A 0062;0061 302A 0316 0324 059A 0062;0061 302A 0316 0324 059A 0062; # (a◌֚◌̖◌〪◌̤b; a◌〪◌̖◌̤◌֚b; a◌〪◌̖◌̤◌֚b; a◌〪◌̖◌̤◌֚b; a◌〪◌̖◌̤◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING DIAERESIS BELOW, LATIN SMALL LETTER B
+0061 0324 059A 0316 302A 0062;0061 302A 0324 0316 059A 0062;0061 302A 0324 0316 059A 0062;0061 302A 0324 0316 059A 0062;0061 302A 0324 0316 059A 0062; # (a◌̤◌֚◌̖◌〪b; a◌〪◌̤◌̖◌֚b; a◌〪◌̤◌̖◌֚b; a◌〪◌̤◌̖◌֚b; a◌〪◌̤◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING DIAERESIS BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0325 0062;0061 302A 0316 0325 059A 0062;0061 302A 0316 0325 059A 0062;0061 302A 0316 0325 059A 0062;0061 302A 0316 0325 059A 0062; # (a◌֚◌̖◌〪◌̥b; a◌〪◌̖◌̥◌֚b; a◌〪◌̖◌̥◌֚b; a◌〪◌̖◌̥◌֚b; a◌〪◌̖◌̥◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING RING BELOW, LATIN SMALL LETTER B
+0061 0325 059A 0316 302A 0062;1E01 302A 0316 059A 0062;0061 302A 0325 0316 059A 0062;1E01 302A 0316 059A 0062;0061 302A 0325 0316 059A 0062; # (a◌̥◌֚◌̖◌〪b; ḁ◌〪◌̖◌֚b; a◌〪◌̥◌̖◌֚b; ḁ◌〪◌̖◌֚b; a◌〪◌̥◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING RING BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0326 0062;0061 302A 0316 0326 059A 0062;0061 302A 0316 0326 059A 0062;0061 302A 0316 0326 059A 0062;0061 302A 0316 0326 059A 0062; # (a◌֚◌̖◌〪◌̦b; a◌〪◌̖◌̦◌֚b; a◌〪◌̖◌̦◌֚b; a◌〪◌̖◌̦◌֚b; a◌〪◌̖◌̦◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING COMMA BELOW, LATIN SMALL LETTER B
+0061 0326 059A 0316 302A 0062;0061 302A 0326 0316 059A 0062;0061 302A 0326 0316 059A 0062;0061 302A 0326 0316 059A 0062;0061 302A 0326 0316 059A 0062; # (a◌̦◌֚◌̖◌〪b; a◌〪◌̦◌̖◌֚b; a◌〪◌̦◌̖◌֚b; a◌〪◌̦◌̖◌֚b; a◌〪◌̦◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING COMMA BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 031B 0321 0F74 0327 0062;0061 0F74 0321 0327 031B 0062;0061 0F74 0321 0327 031B 0062;0061 0F74 0321 0327 031B 0062;0061 0F74 0321 0327 031B 0062; # (a◌̛◌̡◌ུ◌̧b; a◌ུ◌̡◌̧◌̛b; a◌ུ◌̡◌̧◌̛b; a◌ུ◌̡◌̧◌̛b; a◌ུ◌̡◌̧◌̛b; ) LATIN SMALL LETTER A, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, TIBETAN VOWEL SIGN U, COMBINING CEDILLA, LATIN SMALL LETTER B
+0061 0327 031B 0321 0F74 0062;0061 0F74 0327 0321 031B 0062;0061 0F74 0327 0321 031B 0062;0061 0F74 0327 0321 031B 0062;0061 0F74 0327 0321 031B 0062; # (a◌̧◌̛◌̡◌ུb; a◌ུ◌̧◌̡◌̛b; a◌ུ◌̧◌̡◌̛b; a◌ུ◌̧◌̡◌̛b; a◌ུ◌̧◌̡◌̛b; ) LATIN SMALL LETTER A, COMBINING CEDILLA, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, TIBETAN VOWEL SIGN U, LATIN SMALL LETTER B
+0061 031B 0321 0F74 0328 0062;0061 0F74 0321 0328 031B 0062;0061 0F74 0321 0328 031B 0062;0061 0F74 0321 0328 031B 0062;0061 0F74 0321 0328 031B 0062; # (a◌̛◌̡◌ུ◌̨b; a◌ུ◌̡◌̨◌̛b; a◌ུ◌̡◌̨◌̛b; a◌ུ◌̡◌̨◌̛b; a◌ུ◌̡◌̨◌̛b; ) LATIN SMALL LETTER A, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, TIBETAN VOWEL SIGN U, COMBINING OGONEK, LATIN SMALL LETTER B
+0061 0328 031B 0321 0F74 0062;0105 0F74 0321 031B 0062;0061 0F74 0328 0321 031B 0062;0105 0F74 0321 031B 0062;0061 0F74 0328 0321 031B 0062; # (a◌̨◌̛◌̡◌ུb; ą◌ུ◌̡◌̛b; a◌ུ◌̨◌̡◌̛b; ą◌ུ◌̡◌̛b; a◌ུ◌̨◌̡◌̛b; ) LATIN SMALL LETTER A, COMBINING OGONEK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, TIBETAN VOWEL SIGN U, LATIN SMALL LETTER B
+0061 059A 0316 302A 0329 0062;0061 302A 0316 0329 059A 0062;0061 302A 0316 0329 059A 0062;0061 302A 0316 0329 059A 0062;0061 302A 0316 0329 059A 0062; # (a◌֚◌̖◌〪◌̩b; a◌〪◌̖◌̩◌֚b; a◌〪◌̖◌̩◌֚b; a◌〪◌̖◌̩◌֚b; a◌〪◌̖◌̩◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING VERTICAL LINE BELOW, LATIN SMALL LETTER B
+0061 0329 059A 0316 302A 0062;0061 302A 0329 0316 059A 0062;0061 302A 0329 0316 059A 0062;0061 302A 0329 0316 059A 0062;0061 302A 0329 0316 059A 0062; # (a◌̩◌֚◌̖◌〪b; a◌〪◌̩◌̖◌֚b; a◌〪◌̩◌̖◌֚b; a◌〪◌̩◌̖◌֚b; a◌〪◌̩◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING VERTICAL LINE BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 032A 0062;0061 302A 0316 032A 059A 0062;0061 302A 0316 032A 059A 0062;0061 302A 0316 032A 059A 0062;0061 302A 0316 032A 059A 0062; # (a◌֚◌̖◌〪◌̪b; a◌〪◌̖◌̪◌֚b; a◌〪◌̖◌̪◌֚b; a◌〪◌̖◌̪◌֚b; a◌〪◌̖◌̪◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING BRIDGE BELOW, LATIN SMALL LETTER B
+0061 032A 059A 0316 302A 0062;0061 302A 032A 0316 059A 0062;0061 302A 032A 0316 059A 0062;0061 302A 032A 0316 059A 0062;0061 302A 032A 0316 059A 0062; # (a◌̪◌֚◌̖◌〪b; a◌〪◌̪◌̖◌֚b; a◌〪◌̪◌̖◌֚b; a◌〪◌̪◌̖◌֚b; a◌〪◌̪◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING BRIDGE BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 032B 0062;0061 302A 0316 032B 059A 0062;0061 302A 0316 032B 059A 0062;0061 302A 0316 032B 059A 0062;0061 302A 0316 032B 059A 0062; # (a◌֚◌̖◌〪◌̫b; a◌〪◌̖◌̫◌֚b; a◌〪◌̖◌̫◌֚b; a◌〪◌̖◌̫◌֚b; a◌〪◌̖◌̫◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING INVERTED DOUBLE ARCH BELOW, LATIN SMALL LETTER B
+0061 032B 059A 0316 302A 0062;0061 302A 032B 0316 059A 0062;0061 302A 032B 0316 059A 0062;0061 302A 032B 0316 059A 0062;0061 302A 032B 0316 059A 0062; # (a◌̫◌֚◌̖◌〪b; a◌〪◌̫◌̖◌֚b; a◌〪◌̫◌̖◌֚b; a◌〪◌̫◌̖◌֚b; a◌〪◌̫◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING INVERTED DOUBLE ARCH BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 032C 0062;0061 302A 0316 032C 059A 0062;0061 302A 0316 032C 059A 0062;0061 302A 0316 032C 059A 0062;0061 302A 0316 032C 059A 0062; # (a◌֚◌̖◌〪◌̬b; a◌〪◌̖◌̬◌֚b; a◌〪◌̖◌̬◌֚b; a◌〪◌̖◌̬◌֚b; a◌〪◌̖◌̬◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING CARON BELOW, LATIN SMALL LETTER B
+0061 032C 059A 0316 302A 0062;0061 302A 032C 0316 059A 0062;0061 302A 032C 0316 059A 0062;0061 302A 032C 0316 059A 0062;0061 302A 032C 0316 059A 0062; # (a◌̬◌֚◌̖◌〪b; a◌〪◌̬◌̖◌֚b; a◌〪◌̬◌̖◌֚b; a◌〪◌̬◌̖◌֚b; a◌〪◌̬◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING CARON BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 032D 0062;0061 302A 0316 032D 059A 0062;0061 302A 0316 032D 059A 0062;0061 302A 0316 032D 059A 0062;0061 302A 0316 032D 059A 0062; # (a◌֚◌̖◌〪◌̭b; a◌〪◌̖◌̭◌֚b; a◌〪◌̖◌̭◌֚b; a◌〪◌̖◌̭◌֚b; a◌〪◌̖◌̭◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING CIRCUMFLEX ACCENT BELOW, LATIN SMALL LETTER B
+0061 032D 059A 0316 302A 0062;0061 302A 032D 0316 059A 0062;0061 302A 032D 0316 059A 0062;0061 302A 032D 0316 059A 0062;0061 302A 032D 0316 059A 0062; # (a◌̭◌֚◌̖◌〪b; a◌〪◌̭◌̖◌֚b; a◌〪◌̭◌̖◌֚b; a◌〪◌̭◌̖◌֚b; a◌〪◌̭◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING CIRCUMFLEX ACCENT BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 032E 0062;0061 302A 0316 032E 059A 0062;0061 302A 0316 032E 059A 0062;0061 302A 0316 032E 059A 0062;0061 302A 0316 032E 059A 0062; # (a◌֚◌̖◌〪◌̮b; a◌〪◌̖◌̮◌֚b; a◌〪◌̖◌̮◌֚b; a◌〪◌̖◌̮◌֚b; a◌〪◌̖◌̮◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING BREVE BELOW, LATIN SMALL LETTER B
+0061 032E 059A 0316 302A 0062;0061 302A 032E 0316 059A 0062;0061 302A 032E 0316 059A 0062;0061 302A 032E 0316 059A 0062;0061 302A 032E 0316 059A 0062; # (a◌̮◌֚◌̖◌〪b; a◌〪◌̮◌̖◌֚b; a◌〪◌̮◌̖◌֚b; a◌〪◌̮◌̖◌֚b; a◌〪◌̮◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING BREVE BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 032F 0062;0061 302A 0316 032F 059A 0062;0061 302A 0316 032F 059A 0062;0061 302A 0316 032F 059A 0062;0061 302A 0316 032F 059A 0062; # (a◌֚◌̖◌〪◌̯b; a◌〪◌̖◌̯◌֚b; a◌〪◌̖◌̯◌֚b; a◌〪◌̖◌̯◌֚b; a◌〪◌̖◌̯◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING INVERTED BREVE BELOW, LATIN SMALL LETTER B
+0061 032F 059A 0316 302A 0062;0061 302A 032F 0316 059A 0062;0061 302A 032F 0316 059A 0062;0061 302A 032F 0316 059A 0062;0061 302A 032F 0316 059A 0062; # (a◌̯◌֚◌̖◌〪b; a◌〪◌̯◌̖◌֚b; a◌〪◌̯◌̖◌֚b; a◌〪◌̯◌̖◌֚b; a◌〪◌̯◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING INVERTED BREVE BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0330 0062;0061 302A 0316 0330 059A 0062;0061 302A 0316 0330 059A 0062;0061 302A 0316 0330 059A 0062;0061 302A 0316 0330 059A 0062; # (a◌֚◌̖◌〪◌̰b; a◌〪◌̖◌̰◌֚b; a◌〪◌̖◌̰◌֚b; a◌〪◌̖◌̰◌֚b; a◌〪◌̖◌̰◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING TILDE BELOW, LATIN SMALL LETTER B
+0061 0330 059A 0316 302A 0062;0061 302A 0330 0316 059A 0062;0061 302A 0330 0316 059A 0062;0061 302A 0330 0316 059A 0062;0061 302A 0330 0316 059A 0062; # (a◌̰◌֚◌̖◌〪b; a◌〪◌̰◌̖◌֚b; a◌〪◌̰◌̖◌֚b; a◌〪◌̰◌̖◌֚b; a◌〪◌̰◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING TILDE BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0331 0062;0061 302A 0316 0331 059A 0062;0061 302A 0316 0331 059A 0062;0061 302A 0316 0331 059A 0062;0061 302A 0316 0331 059A 0062; # (a◌֚◌̖◌〪◌̱b; a◌〪◌̖◌̱◌֚b; a◌〪◌̖◌̱◌֚b; a◌〪◌̖◌̱◌֚b; a◌〪◌̖◌̱◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING MACRON BELOW, LATIN SMALL LETTER B
+0061 0331 059A 0316 302A 0062;0061 302A 0331 0316 059A 0062;0061 302A 0331 0316 059A 0062;0061 302A 0331 0316 059A 0062;0061 302A 0331 0316 059A 0062; # (a◌̱◌֚◌̖◌〪b; a◌〪◌̱◌̖◌֚b; a◌〪◌̱◌̖◌֚b; a◌〪◌̱◌̖◌֚b; a◌〪◌̱◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING MACRON BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0332 0062;0061 302A 0316 0332 059A 0062;0061 302A 0316 0332 059A 0062;0061 302A 0316 0332 059A 0062;0061 302A 0316 0332 059A 0062; # (a◌֚◌̖◌〪◌̲b; a◌〪◌̖◌̲◌֚b; a◌〪◌̖◌̲◌֚b; a◌〪◌̖◌̲◌֚b; a◌〪◌̖◌̲◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING LOW LINE, LATIN SMALL LETTER B
+0061 0332 059A 0316 302A 0062;0061 302A 0332 0316 059A 0062;0061 302A 0332 0316 059A 0062;0061 302A 0332 0316 059A 0062;0061 302A 0332 0316 059A 0062; # (a◌̲◌֚◌̖◌〪b; a◌〪◌̲◌̖◌֚b; a◌〪◌̲◌̖◌֚b; a◌〪◌̲◌̖◌֚b; a◌〪◌̲◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING LOW LINE, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0333 0062;0061 302A 0316 0333 059A 0062;0061 302A 0316 0333 059A 0062;0061 302A 0316 0333 059A 0062;0061 302A 0316 0333 059A 0062; # (a◌֚◌̖◌〪◌̳b; a◌〪◌̖◌̳◌֚b; a◌〪◌̖◌̳◌֚b; a◌〪◌̖◌̳◌֚b; a◌〪◌̖◌̳◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING DOUBLE LOW LINE, LATIN SMALL LETTER B
+0061 0333 059A 0316 302A 0062;0061 302A 0333 0316 059A 0062;0061 302A 0333 0316 059A 0062;0061 302A 0333 0316 059A 0062;0061 302A 0333 0316 059A 0062; # (a◌̳◌֚◌̖◌〪b; a◌〪◌̳◌̖◌֚b; a◌〪◌̳◌̖◌֚b; a◌〪◌̳◌̖◌֚b; a◌〪◌̳◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING DOUBLE LOW LINE, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 093C 0334 0334 0062;0061 0334 0334 093C 0062;0061 0334 0334 093C 0062;0061 0334 0334 093C 0062;0061 0334 0334 093C 0062; # (a◌़◌̴◌̴b; a◌̴◌̴◌़b; a◌̴◌̴◌़b; a◌̴◌̴◌़b; a◌̴◌̴◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 0334 093C 0334 0062;0061 0334 0334 093C 0062;0061 0334 0334 093C 0062;0061 0334 0334 093C 0062;0061 0334 0334 093C 0062; # (a◌̴◌़◌̴b; a◌̴◌̴◌़b; a◌̴◌̴◌़b; a◌̴◌̴◌़b; a◌̴◌̴◌़b; ) LATIN SMALL LETTER A, COMBINING TILDE OVERLAY, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 093C 0334 0335 0062;0061 0334 0335 093C 0062;0061 0334 0335 093C 0062;0061 0334 0335 093C 0062;0061 0334 0335 093C 0062; # (a◌़◌̴◌̵b; a◌̴◌̵◌़b; a◌̴◌̵◌़b; a◌̴◌̵◌़b; a◌̴◌̵◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, COMBINING SHORT STROKE OVERLAY, LATIN SMALL LETTER B
+0061 0335 093C 0334 0062;0061 0335 0334 093C 0062;0061 0335 0334 093C 0062;0061 0335 0334 093C 0062;0061 0335 0334 093C 0062; # (a◌̵◌़◌̴b; a◌̵◌̴◌़b; a◌̵◌̴◌़b; a◌̵◌̴◌़b; a◌̵◌̴◌़b; ) LATIN SMALL LETTER A, COMBINING SHORT STROKE OVERLAY, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 093C 0334 0336 0062;0061 0334 0336 093C 0062;0061 0334 0336 093C 0062;0061 0334 0336 093C 0062;0061 0334 0336 093C 0062; # (a◌़◌̴◌̶b; a◌̴◌̶◌़b; a◌̴◌̶◌़b; a◌̴◌̶◌़b; a◌̴◌̶◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, COMBINING LONG STROKE OVERLAY, LATIN SMALL LETTER B
+0061 0336 093C 0334 0062;0061 0336 0334 093C 0062;0061 0336 0334 093C 0062;0061 0336 0334 093C 0062;0061 0336 0334 093C 0062; # (a◌̶◌़◌̴b; a◌̶◌̴◌़b; a◌̶◌̴◌़b; a◌̶◌̴◌़b; a◌̶◌̴◌़b; ) LATIN SMALL LETTER A, COMBINING LONG STROKE OVERLAY, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 093C 0334 0337 0062;0061 0334 0337 093C 0062;0061 0334 0337 093C 0062;0061 0334 0337 093C 0062;0061 0334 0337 093C 0062; # (a◌़◌̴◌̷b; a◌̴◌̷◌़b; a◌̴◌̷◌़b; a◌̴◌̷◌़b; a◌̴◌̷◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, COMBINING SHORT SOLIDUS OVERLAY, LATIN SMALL LETTER B
+0061 0337 093C 0334 0062;0061 0337 0334 093C 0062;0061 0337 0334 093C 0062;0061 0337 0334 093C 0062;0061 0337 0334 093C 0062; # (a◌̷◌़◌̴b; a◌̷◌̴◌़b; a◌̷◌̴◌़b; a◌̷◌̴◌़b; a◌̷◌̴◌़b; ) LATIN SMALL LETTER A, COMBINING SHORT SOLIDUS OVERLAY, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 093C 0334 0338 0062;0061 0334 0338 093C 0062;0061 0334 0338 093C 0062;0061 0334 0338 093C 0062;0061 0334 0338 093C 0062; # (a◌़◌̴◌̸b; a◌̴◌̸◌़b; a◌̴◌̸◌़b; a◌̴◌̸◌़b; a◌̴◌̸◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, COMBINING LONG SOLIDUS OVERLAY, LATIN SMALL LETTER B
+0061 0338 093C 0334 0062;0061 0338 0334 093C 0062;0061 0338 0334 093C 0062;0061 0338 0334 093C 0062;0061 0338 0334 093C 0062; # (a◌̸◌़◌̴b; a◌̸◌̴◌़b; a◌̸◌̴◌़b; a◌̸◌̴◌़b; a◌̸◌̴◌़b; ) LATIN SMALL LETTER A, COMBINING LONG SOLIDUS OVERLAY, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 059A 0316 302A 0339 0062;0061 302A 0316 0339 059A 0062;0061 302A 0316 0339 059A 0062;0061 302A 0316 0339 059A 0062;0061 302A 0316 0339 059A 0062; # (a◌֚◌̖◌〪◌̹b; a◌〪◌̖◌̹◌֚b; a◌〪◌̖◌̹◌֚b; a◌〪◌̖◌̹◌֚b; a◌〪◌̖◌̹◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING RIGHT HALF RING BELOW, LATIN SMALL LETTER B
+0061 0339 059A 0316 302A 0062;0061 302A 0339 0316 059A 0062;0061 302A 0339 0316 059A 0062;0061 302A 0339 0316 059A 0062;0061 302A 0339 0316 059A 0062; # (a◌̹◌֚◌̖◌〪b; a◌〪◌̹◌̖◌֚b; a◌〪◌̹◌̖◌֚b; a◌〪◌̹◌̖◌֚b; a◌〪◌̹◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING RIGHT HALF RING BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 033A 0062;0061 302A 0316 033A 059A 0062;0061 302A 0316 033A 059A 0062;0061 302A 0316 033A 059A 0062;0061 302A 0316 033A 059A 0062; # (a◌֚◌̖◌〪◌̺b; a◌〪◌̖◌̺◌֚b; a◌〪◌̖◌̺◌֚b; a◌〪◌̖◌̺◌֚b; a◌〪◌̖◌̺◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING INVERTED BRIDGE BELOW, LATIN SMALL LETTER B
+0061 033A 059A 0316 302A 0062;0061 302A 033A 0316 059A 0062;0061 302A 033A 0316 059A 0062;0061 302A 033A 0316 059A 0062;0061 302A 033A 0316 059A 0062; # (a◌̺◌֚◌̖◌〪b; a◌〪◌̺◌̖◌֚b; a◌〪◌̺◌̖◌֚b; a◌〪◌̺◌̖◌֚b; a◌〪◌̺◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING INVERTED BRIDGE BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 033B 0062;0061 302A 0316 033B 059A 0062;0061 302A 0316 033B 059A 0062;0061 302A 0316 033B 059A 0062;0061 302A 0316 033B 059A 0062; # (a◌֚◌̖◌〪◌̻b; a◌〪◌̖◌̻◌֚b; a◌〪◌̖◌̻◌֚b; a◌〪◌̖◌̻◌֚b; a◌〪◌̖◌̻◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING SQUARE BELOW, LATIN SMALL LETTER B
+0061 033B 059A 0316 302A 0062;0061 302A 033B 0316 059A 0062;0061 302A 033B 0316 059A 0062;0061 302A 033B 0316 059A 0062;0061 302A 033B 0316 059A 0062; # (a◌̻◌֚◌̖◌〪b; a◌〪◌̻◌̖◌֚b; a◌〪◌̻◌̖◌֚b; a◌〪◌̻◌̖◌֚b; a◌〪◌̻◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING SQUARE BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 033C 0062;0061 302A 0316 033C 059A 0062;0061 302A 0316 033C 059A 0062;0061 302A 0316 033C 059A 0062;0061 302A 0316 033C 059A 0062; # (a◌֚◌̖◌〪◌̼b; a◌〪◌̖◌̼◌֚b; a◌〪◌̖◌̼◌֚b; a◌〪◌̖◌̼◌֚b; a◌〪◌̖◌̼◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING SEAGULL BELOW, LATIN SMALL LETTER B
+0061 033C 059A 0316 302A 0062;0061 302A 033C 0316 059A 0062;0061 302A 033C 0316 059A 0062;0061 302A 033C 0316 059A 0062;0061 302A 033C 0316 059A 0062; # (a◌̼◌֚◌̖◌〪b; a◌〪◌̼◌̖◌֚b; a◌〪◌̼◌̖◌֚b; a◌〪◌̼◌̖◌֚b; a◌〪◌̼◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING SEAGULL BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 033D 0062;00E0 05AE 033D 0315 0062;0061 05AE 0300 033D 0315 0062;00E0 05AE 033D 0315 0062;0061 05AE 0300 033D 0315 0062; # (a◌̕◌̀◌֮◌̽b; à◌֮◌̽◌̕b; a◌֮◌̀◌̽◌̕b; à◌֮◌̽◌̕b; a◌֮◌̀◌̽◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING X ABOVE, LATIN SMALL LETTER B
+0061 033D 0315 0300 05AE 0062;0061 05AE 033D 0300 0315 0062;0061 05AE 033D 0300 0315 0062;0061 05AE 033D 0300 0315 0062;0061 05AE 033D 0300 0315 0062; # (a◌̽◌̕◌̀◌֮b; a◌֮◌̽◌̀◌̕b; a◌֮◌̽◌̀◌̕b; a◌֮◌̽◌̀◌̕b; a◌֮◌̽◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING X ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 033E 0062;00E0 05AE 033E 0315 0062;0061 05AE 0300 033E 0315 0062;00E0 05AE 033E 0315 0062;0061 05AE 0300 033E 0315 0062; # (a◌̕◌̀◌֮◌̾b; à◌֮◌̾◌̕b; a◌֮◌̀◌̾◌̕b; à◌֮◌̾◌̕b; a◌֮◌̀◌̾◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING VERTICAL TILDE, LATIN SMALL LETTER B
+0061 033E 0315 0300 05AE 0062;0061 05AE 033E 0300 0315 0062;0061 05AE 033E 0300 0315 0062;0061 05AE 033E 0300 0315 0062;0061 05AE 033E 0300 0315 0062; # (a◌̾◌̕◌̀◌֮b; a◌֮◌̾◌̀◌̕b; a◌֮◌̾◌̀◌̕b; a◌֮◌̾◌̀◌̕b; a◌֮◌̾◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING VERTICAL TILDE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 033F 0062;00E0 05AE 033F 0315 0062;0061 05AE 0300 033F 0315 0062;00E0 05AE 033F 0315 0062;0061 05AE 0300 033F 0315 0062; # (a◌̕◌̀◌֮◌̿b; à◌֮◌̿◌̕b; a◌֮◌̀◌̿◌̕b; à◌֮◌̿◌̕b; a◌֮◌̀◌̿◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING DOUBLE OVERLINE, LATIN SMALL LETTER B
+0061 033F 0315 0300 05AE 0062;0061 05AE 033F 0300 0315 0062;0061 05AE 033F 0300 0315 0062;0061 05AE 033F 0300 0315 0062;0061 05AE 033F 0300 0315 0062; # (a◌̿◌̕◌̀◌֮b; a◌֮◌̿◌̀◌̕b; a◌֮◌̿◌̀◌̕b; a◌֮◌̿◌̀◌̕b; a◌֮◌̿◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING DOUBLE OVERLINE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0340 0062;00E0 05AE 0300 0315 0062;0061 05AE 0300 0300 0315 0062;00E0 05AE 0300 0315 0062;0061 05AE 0300 0300 0315 0062; # (a◌̕◌̀◌֮◌̀b; à◌֮◌̀◌̕b; a◌֮◌̀◌̀◌̕b; à◌֮◌̀◌̕b; a◌֮◌̀◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING GRAVE TONE MARK, LATIN SMALL LETTER B
+0061 0340 0315 0300 05AE 0062;00E0 05AE 0300 0315 0062;0061 05AE 0300 0300 0315 0062;00E0 05AE 0300 0315 0062;0061 05AE 0300 0300 0315 0062; # (a◌̀◌̕◌̀◌֮b; à◌֮◌̀◌̕b; a◌֮◌̀◌̀◌̕b; à◌֮◌̀◌̕b; a◌֮◌̀◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING GRAVE TONE MARK, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0341 0062;00E0 05AE 0301 0315 0062;0061 05AE 0300 0301 0315 0062;00E0 05AE 0301 0315 0062;0061 05AE 0300 0301 0315 0062; # (a◌̕◌̀◌֮◌́b; à◌֮◌́◌̕b; a◌֮◌̀◌́◌̕b; à◌֮◌́◌̕b; a◌֮◌̀◌́◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING ACUTE TONE MARK, LATIN SMALL LETTER B
+0061 0341 0315 0300 05AE 0062;00E1 05AE 0300 0315 0062;0061 05AE 0301 0300 0315 0062;00E1 05AE 0300 0315 0062;0061 05AE 0301 0300 0315 0062; # (a◌́◌̕◌̀◌֮b; á◌֮◌̀◌̕b; a◌֮◌́◌̀◌̕b; á◌֮◌̀◌̕b; a◌֮◌́◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING ACUTE TONE MARK, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0342 0062;00E0 05AE 0342 0315 0062;0061 05AE 0300 0342 0315 0062;00E0 05AE 0342 0315 0062;0061 05AE 0300 0342 0315 0062; # (a◌̕◌̀◌֮◌͂b; à◌֮◌͂◌̕b; a◌֮◌̀◌͂◌̕b; à◌֮◌͂◌̕b; a◌֮◌̀◌͂◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING GREEK PERISPOMENI, LATIN SMALL LETTER B
+0061 0342 0315 0300 05AE 0062;0061 05AE 0342 0300 0315 0062;0061 05AE 0342 0300 0315 0062;0061 05AE 0342 0300 0315 0062;0061 05AE 0342 0300 0315 0062; # (a◌͂◌̕◌̀◌֮b; a◌֮◌͂◌̀◌̕b; a◌֮◌͂◌̀◌̕b; a◌֮◌͂◌̀◌̕b; a◌֮◌͂◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING GREEK PERISPOMENI, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0343 0062;00E0 05AE 0313 0315 0062;0061 05AE 0300 0313 0315 0062;00E0 05AE 0313 0315 0062;0061 05AE 0300 0313 0315 0062; # (a◌̕◌̀◌֮◌̓b; à◌֮◌̓◌̕b; a◌֮◌̀◌̓◌̕b; à◌֮◌̓◌̕b; a◌֮◌̀◌̓◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING GREEK KORONIS, LATIN SMALL LETTER B
+0061 0343 0315 0300 05AE 0062;0061 05AE 0313 0300 0315 0062;0061 05AE 0313 0300 0315 0062;0061 05AE 0313 0300 0315 0062;0061 05AE 0313 0300 0315 0062; # (a◌̓◌̕◌̀◌֮b; a◌֮◌̓◌̀◌̕b; a◌֮◌̓◌̀◌̕b; a◌֮◌̓◌̀◌̕b; a◌֮◌̓◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING GREEK KORONIS, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0344 0062;00E0 05AE 0308 0301 0315 0062;0061 05AE 0300 0308 0301 0315 0062;00E0 05AE 0308 0301 0315 0062;0061 05AE 0300 0308 0301 0315 0062; # (a◌̕◌̀◌֮◌̈́b; à◌֮◌̈◌́◌̕b; a◌֮◌̀◌̈◌́◌̕b; à◌֮◌̈◌́◌̕b; a◌֮◌̀◌̈◌́◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING GREEK DIALYTIKA TONOS, LATIN SMALL LETTER B
+0061 0344 0315 0300 05AE 0062;00E4 05AE 0301 0300 0315 0062;0061 05AE 0308 0301 0300 0315 0062;00E4 05AE 0301 0300 0315 0062;0061 05AE 0308 0301 0300 0315 0062; # (a◌̈́◌̕◌̀◌֮b; ä◌֮◌́◌̀◌̕b; a◌֮◌̈◌́◌̀◌̕b; ä◌֮◌́◌̀◌̕b; a◌֮◌̈◌́◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING GREEK DIALYTIKA TONOS, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0345 035D 0345 0062;0061 035D 0345 0345 0062;0061 035D 0345 0345 0062;0061 035D 0345 0345 0062;0061 035D 0345 0345 0062; # (a◌ͅ◌͝◌ͅb; a◌͝◌ͅ◌ͅb; a◌͝◌ͅ◌ͅb; a◌͝◌ͅ◌ͅb; a◌͝◌ͅ◌ͅb; ) LATIN SMALL LETTER A, COMBINING GREEK YPOGEGRAMMENI, COMBINING DOUBLE BREVE, COMBINING GREEK YPOGEGRAMMENI, LATIN SMALL LETTER B
+0061 0345 0345 035D 0062;0061 035D 0345 0345 0062;0061 035D 0345 0345 0062;0061 035D 0345 0345 0062;0061 035D 0345 0345 0062; # (a◌ͅ◌ͅ◌͝b; a◌͝◌ͅ◌ͅb; a◌͝◌ͅ◌ͅb; a◌͝◌ͅ◌ͅb; a◌͝◌ͅ◌ͅb; ) LATIN SMALL LETTER A, COMBINING GREEK YPOGEGRAMMENI, COMBINING GREEK YPOGEGRAMMENI, COMBINING DOUBLE BREVE, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0346 0062;00E0 05AE 0346 0315 0062;0061 05AE 0300 0346 0315 0062;00E0 05AE 0346 0315 0062;0061 05AE 0300 0346 0315 0062; # (a◌̕◌̀◌֮◌͆b; à◌֮◌͆◌̕b; a◌֮◌̀◌͆◌̕b; à◌֮◌͆◌̕b; a◌֮◌̀◌͆◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING BRIDGE ABOVE, LATIN SMALL LETTER B
+0061 0346 0315 0300 05AE 0062;0061 05AE 0346 0300 0315 0062;0061 05AE 0346 0300 0315 0062;0061 05AE 0346 0300 0315 0062;0061 05AE 0346 0300 0315 0062; # (a◌͆◌̕◌̀◌֮b; a◌֮◌͆◌̀◌̕b; a◌֮◌͆◌̀◌̕b; a◌֮◌͆◌̀◌̕b; a◌֮◌͆◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING BRIDGE ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 0347 0062;0061 302A 0316 0347 059A 0062;0061 302A 0316 0347 059A 0062;0061 302A 0316 0347 059A 0062;0061 302A 0316 0347 059A 0062; # (a◌֚◌̖◌〪◌͇b; a◌〪◌̖◌͇◌֚b; a◌〪◌̖◌͇◌֚b; a◌〪◌̖◌͇◌֚b; a◌〪◌̖◌͇◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING EQUALS SIGN BELOW, LATIN SMALL LETTER B
+0061 0347 059A 0316 302A 0062;0061 302A 0347 0316 059A 0062;0061 302A 0347 0316 059A 0062;0061 302A 0347 0316 059A 0062;0061 302A 0347 0316 059A 0062; # (a◌͇◌֚◌̖◌〪b; a◌〪◌͇◌̖◌֚b; a◌〪◌͇◌̖◌֚b; a◌〪◌͇◌̖◌֚b; a◌〪◌͇◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING EQUALS SIGN BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0348 0062;0061 302A 0316 0348 059A 0062;0061 302A 0316 0348 059A 0062;0061 302A 0316 0348 059A 0062;0061 302A 0316 0348 059A 0062; # (a◌֚◌̖◌〪◌͈b; a◌〪◌̖◌͈◌֚b; a◌〪◌̖◌͈◌֚b; a◌〪◌̖◌͈◌֚b; a◌〪◌̖◌͈◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING DOUBLE VERTICAL LINE BELOW, LATIN SMALL LETTER B
+0061 0348 059A 0316 302A 0062;0061 302A 0348 0316 059A 0062;0061 302A 0348 0316 059A 0062;0061 302A 0348 0316 059A 0062;0061 302A 0348 0316 059A 0062; # (a◌͈◌֚◌̖◌〪b; a◌〪◌͈◌̖◌֚b; a◌〪◌͈◌̖◌֚b; a◌〪◌͈◌̖◌֚b; a◌〪◌͈◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING DOUBLE VERTICAL LINE BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0349 0062;0061 302A 0316 0349 059A 0062;0061 302A 0316 0349 059A 0062;0061 302A 0316 0349 059A 0062;0061 302A 0316 0349 059A 0062; # (a◌֚◌̖◌〪◌͉b; a◌〪◌̖◌͉◌֚b; a◌〪◌̖◌͉◌֚b; a◌〪◌̖◌͉◌֚b; a◌〪◌̖◌͉◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING LEFT ANGLE BELOW, LATIN SMALL LETTER B
+0061 0349 059A 0316 302A 0062;0061 302A 0349 0316 059A 0062;0061 302A 0349 0316 059A 0062;0061 302A 0349 0316 059A 0062;0061 302A 0349 0316 059A 0062; # (a◌͉◌֚◌̖◌〪b; a◌〪◌͉◌̖◌֚b; a◌〪◌͉◌̖◌֚b; a◌〪◌͉◌̖◌֚b; a◌〪◌͉◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING LEFT ANGLE BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 034A 0062;00E0 05AE 034A 0315 0062;0061 05AE 0300 034A 0315 0062;00E0 05AE 034A 0315 0062;0061 05AE 0300 034A 0315 0062; # (a◌̕◌̀◌֮◌͊b; à◌֮◌͊◌̕b; a◌֮◌̀◌͊◌̕b; à◌֮◌͊◌̕b; a◌֮◌̀◌͊◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING NOT TILDE ABOVE, LATIN SMALL LETTER B
+0061 034A 0315 0300 05AE 0062;0061 05AE 034A 0300 0315 0062;0061 05AE 034A 0300 0315 0062;0061 05AE 034A 0300 0315 0062;0061 05AE 034A 0300 0315 0062; # (a◌͊◌̕◌̀◌֮b; a◌֮◌͊◌̀◌̕b; a◌֮◌͊◌̀◌̕b; a◌֮◌͊◌̀◌̕b; a◌֮◌͊◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING NOT TILDE ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 034B 0062;00E0 05AE 034B 0315 0062;0061 05AE 0300 034B 0315 0062;00E0 05AE 034B 0315 0062;0061 05AE 0300 034B 0315 0062; # (a◌̕◌̀◌֮◌͋b; à◌֮◌͋◌̕b; a◌֮◌̀◌͋◌̕b; à◌֮◌͋◌̕b; a◌֮◌̀◌͋◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING HOMOTHETIC ABOVE, LATIN SMALL LETTER B
+0061 034B 0315 0300 05AE 0062;0061 05AE 034B 0300 0315 0062;0061 05AE 034B 0300 0315 0062;0061 05AE 034B 0300 0315 0062;0061 05AE 034B 0300 0315 0062; # (a◌͋◌̕◌̀◌֮b; a◌֮◌͋◌̀◌̕b; a◌֮◌͋◌̀◌̕b; a◌֮◌͋◌̀◌̕b; a◌֮◌͋◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING HOMOTHETIC ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 034C 0062;00E0 05AE 034C 0315 0062;0061 05AE 0300 034C 0315 0062;00E0 05AE 034C 0315 0062;0061 05AE 0300 034C 0315 0062; # (a◌̕◌̀◌֮◌͌b; à◌֮◌͌◌̕b; a◌֮◌̀◌͌◌̕b; à◌֮◌͌◌̕b; a◌֮◌̀◌͌◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING ALMOST EQUAL TO ABOVE, LATIN SMALL LETTER B
+0061 034C 0315 0300 05AE 0062;0061 05AE 034C 0300 0315 0062;0061 05AE 034C 0300 0315 0062;0061 05AE 034C 0300 0315 0062;0061 05AE 034C 0300 0315 0062; # (a◌͌◌̕◌̀◌֮b; a◌֮◌͌◌̀◌̕b; a◌֮◌͌◌̀◌̕b; a◌֮◌͌◌̀◌̕b; a◌֮◌͌◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING ALMOST EQUAL TO ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 034D 0062;0061 302A 0316 034D 059A 0062;0061 302A 0316 034D 059A 0062;0061 302A 0316 034D 059A 0062;0061 302A 0316 034D 059A 0062; # (a◌֚◌̖◌〪◌͍b; a◌〪◌̖◌͍◌֚b; a◌〪◌̖◌͍◌֚b; a◌〪◌̖◌͍◌֚b; a◌〪◌̖◌͍◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING LEFT RIGHT ARROW BELOW, LATIN SMALL LETTER B
+0061 034D 059A 0316 302A 0062;0061 302A 034D 0316 059A 0062;0061 302A 034D 0316 059A 0062;0061 302A 034D 0316 059A 0062;0061 302A 034D 0316 059A 0062; # (a◌͍◌֚◌̖◌〪b; a◌〪◌͍◌̖◌֚b; a◌〪◌͍◌̖◌֚b; a◌〪◌͍◌̖◌֚b; a◌〪◌͍◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING LEFT RIGHT ARROW BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 034E 0062;0061 302A 0316 034E 059A 0062;0061 302A 0316 034E 059A 0062;0061 302A 0316 034E 059A 0062;0061 302A 0316 034E 059A 0062; # (a◌֚◌̖◌〪◌͎b; a◌〪◌̖◌͎◌֚b; a◌〪◌̖◌͎◌֚b; a◌〪◌̖◌͎◌֚b; a◌〪◌̖◌͎◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING UPWARDS ARROW BELOW, LATIN SMALL LETTER B
+0061 034E 059A 0316 302A 0062;0061 302A 034E 0316 059A 0062;0061 302A 034E 0316 059A 0062;0061 302A 034E 0316 059A 0062;0061 302A 034E 0316 059A 0062; # (a◌͎◌֚◌̖◌〪b; a◌〪◌͎◌̖◌֚b; a◌〪◌͎◌̖◌֚b; a◌〪◌͎◌̖◌֚b; a◌〪◌͎◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING UPWARDS ARROW BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0350 0062;00E0 05AE 0350 0315 0062;0061 05AE 0300 0350 0315 0062;00E0 05AE 0350 0315 0062;0061 05AE 0300 0350 0315 0062; # (a◌̕◌̀◌֮◌͐b; à◌֮◌͐◌̕b; a◌֮◌̀◌͐◌̕b; à◌֮◌͐◌̕b; a◌֮◌̀◌͐◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING RIGHT ARROWHEAD ABOVE, LATIN SMALL LETTER B
+0061 0350 0315 0300 05AE 0062;0061 05AE 0350 0300 0315 0062;0061 05AE 0350 0300 0315 0062;0061 05AE 0350 0300 0315 0062;0061 05AE 0350 0300 0315 0062; # (a◌͐◌̕◌̀◌֮b; a◌֮◌͐◌̀◌̕b; a◌֮◌͐◌̀◌̕b; a◌֮◌͐◌̀◌̕b; a◌֮◌͐◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING RIGHT ARROWHEAD ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0351 0062;00E0 05AE 0351 0315 0062;0061 05AE 0300 0351 0315 0062;00E0 05AE 0351 0315 0062;0061 05AE 0300 0351 0315 0062; # (a◌̕◌̀◌֮◌͑b; à◌֮◌͑◌̕b; a◌֮◌̀◌͑◌̕b; à◌֮◌͑◌̕b; a◌֮◌̀◌͑◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LEFT HALF RING ABOVE, LATIN SMALL LETTER B
+0061 0351 0315 0300 05AE 0062;0061 05AE 0351 0300 0315 0062;0061 05AE 0351 0300 0315 0062;0061 05AE 0351 0300 0315 0062;0061 05AE 0351 0300 0315 0062; # (a◌͑◌̕◌̀◌֮b; a◌֮◌͑◌̀◌̕b; a◌֮◌͑◌̀◌̕b; a◌֮◌͑◌̀◌̕b; a◌֮◌͑◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LEFT HALF RING ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0352 0062;00E0 05AE 0352 0315 0062;0061 05AE 0300 0352 0315 0062;00E0 05AE 0352 0315 0062;0061 05AE 0300 0352 0315 0062; # (a◌̕◌̀◌֮◌͒b; à◌֮◌͒◌̕b; a◌֮◌̀◌͒◌̕b; à◌֮◌͒◌̕b; a◌֮◌̀◌͒◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING FERMATA, LATIN SMALL LETTER B
+0061 0352 0315 0300 05AE 0062;0061 05AE 0352 0300 0315 0062;0061 05AE 0352 0300 0315 0062;0061 05AE 0352 0300 0315 0062;0061 05AE 0352 0300 0315 0062; # (a◌͒◌̕◌̀◌֮b; a◌֮◌͒◌̀◌̕b; a◌֮◌͒◌̀◌̕b; a◌֮◌͒◌̀◌̕b; a◌֮◌͒◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING FERMATA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 0353 0062;0061 302A 0316 0353 059A 0062;0061 302A 0316 0353 059A 0062;0061 302A 0316 0353 059A 0062;0061 302A 0316 0353 059A 0062; # (a◌֚◌̖◌〪◌͓b; a◌〪◌̖◌͓◌֚b; a◌〪◌̖◌͓◌֚b; a◌〪◌̖◌͓◌֚b; a◌〪◌̖◌͓◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING X BELOW, LATIN SMALL LETTER B
+0061 0353 059A 0316 302A 0062;0061 302A 0353 0316 059A 0062;0061 302A 0353 0316 059A 0062;0061 302A 0353 0316 059A 0062;0061 302A 0353 0316 059A 0062; # (a◌͓◌֚◌̖◌〪b; a◌〪◌͓◌̖◌֚b; a◌〪◌͓◌̖◌֚b; a◌〪◌͓◌̖◌֚b; a◌〪◌͓◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING X BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0354 0062;0061 302A 0316 0354 059A 0062;0061 302A 0316 0354 059A 0062;0061 302A 0316 0354 059A 0062;0061 302A 0316 0354 059A 0062; # (a◌֚◌̖◌〪◌͔b; a◌〪◌̖◌͔◌֚b; a◌〪◌̖◌͔◌֚b; a◌〪◌̖◌͔◌֚b; a◌〪◌̖◌͔◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING LEFT ARROWHEAD BELOW, LATIN SMALL LETTER B
+0061 0354 059A 0316 302A 0062;0061 302A 0354 0316 059A 0062;0061 302A 0354 0316 059A 0062;0061 302A 0354 0316 059A 0062;0061 302A 0354 0316 059A 0062; # (a◌͔◌֚◌̖◌〪b; a◌〪◌͔◌̖◌֚b; a◌〪◌͔◌̖◌֚b; a◌〪◌͔◌̖◌֚b; a◌〪◌͔◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING LEFT ARROWHEAD BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0355 0062;0061 302A 0316 0355 059A 0062;0061 302A 0316 0355 059A 0062;0061 302A 0316 0355 059A 0062;0061 302A 0316 0355 059A 0062; # (a◌֚◌̖◌〪◌͕b; a◌〪◌̖◌͕◌֚b; a◌〪◌̖◌͕◌֚b; a◌〪◌̖◌͕◌֚b; a◌〪◌̖◌͕◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING RIGHT ARROWHEAD BELOW, LATIN SMALL LETTER B
+0061 0355 059A 0316 302A 0062;0061 302A 0355 0316 059A 0062;0061 302A 0355 0316 059A 0062;0061 302A 0355 0316 059A 0062;0061 302A 0355 0316 059A 0062; # (a◌͕◌֚◌̖◌〪b; a◌〪◌͕◌̖◌֚b; a◌〪◌͕◌̖◌֚b; a◌〪◌͕◌̖◌֚b; a◌〪◌͕◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING RIGHT ARROWHEAD BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0356 0062;0061 302A 0316 0356 059A 0062;0061 302A 0316 0356 059A 0062;0061 302A 0316 0356 059A 0062;0061 302A 0316 0356 059A 0062; # (a◌֚◌̖◌〪◌͖b; a◌〪◌̖◌͖◌֚b; a◌〪◌̖◌͖◌֚b; a◌〪◌̖◌͖◌֚b; a◌〪◌̖◌͖◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING RIGHT ARROWHEAD AND UP ARROWHEAD BELOW, LATIN SMALL LETTER B
+0061 0356 059A 0316 302A 0062;0061 302A 0356 0316 059A 0062;0061 302A 0356 0316 059A 0062;0061 302A 0356 0316 059A 0062;0061 302A 0356 0316 059A 0062; # (a◌͖◌֚◌̖◌〪b; a◌〪◌͖◌̖◌֚b; a◌〪◌͖◌̖◌֚b; a◌〪◌͖◌̖◌֚b; a◌〪◌͖◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING RIGHT ARROWHEAD AND UP ARROWHEAD BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0357 0062;00E0 05AE 0357 0315 0062;0061 05AE 0300 0357 0315 0062;00E0 05AE 0357 0315 0062;0061 05AE 0300 0357 0315 0062; # (a◌̕◌̀◌֮◌͗b; à◌֮◌͗◌̕b; a◌֮◌̀◌͗◌̕b; à◌֮◌͗◌̕b; a◌֮◌̀◌͗◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING RIGHT HALF RING ABOVE, LATIN SMALL LETTER B
+0061 0357 0315 0300 05AE 0062;0061 05AE 0357 0300 0315 0062;0061 05AE 0357 0300 0315 0062;0061 05AE 0357 0300 0315 0062;0061 05AE 0357 0300 0315 0062; # (a◌͗◌̕◌̀◌֮b; a◌֮◌͗◌̀◌̕b; a◌֮◌͗◌̀◌̕b; a◌֮◌͗◌̀◌̕b; a◌֮◌͗◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING RIGHT HALF RING ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0345 035D 035F 035D 0062;0061 035F 035D 035D 0345 0062;0061 035F 035D 035D 0345 0062;0061 035F 035D 035D 0345 0062;0061 035F 035D 035D 0345 0062; # (a◌ͅ◌͝◌͟◌͝b; a◌͟◌͝◌͝◌ͅb; a◌͟◌͝◌͝◌ͅb; a◌͟◌͝◌͝◌ͅb; a◌͟◌͝◌͝◌ͅb; ) LATIN SMALL LETTER A, COMBINING GREEK YPOGEGRAMMENI, COMBINING DOUBLE BREVE, COMBINING DOUBLE MACRON BELOW, COMBINING DOUBLE BREVE, LATIN SMALL LETTER B
+0061 035D 0345 035D 035F 0062;0061 035F 035D 035D 0345 0062;0061 035F 035D 035D 0345 0062;0061 035F 035D 035D 0345 0062;0061 035F 035D 035D 0345 0062; # (a◌͝◌ͅ◌͝◌͟b; a◌͟◌͝◌͝◌ͅb; a◌͟◌͝◌͝◌ͅb; a◌͟◌͝◌͝◌ͅb; a◌͟◌͝◌͝◌ͅb; ) LATIN SMALL LETTER A, COMBINING DOUBLE BREVE, COMBINING GREEK YPOGEGRAMMENI, COMBINING DOUBLE BREVE, COMBINING DOUBLE MACRON BELOW, LATIN SMALL LETTER B
+0061 0345 035D 035F 035E 0062;0061 035F 035D 035E 0345 0062;0061 035F 035D 035E 0345 0062;0061 035F 035D 035E 0345 0062;0061 035F 035D 035E 0345 0062; # (a◌ͅ◌͝◌͟◌͞b; a◌͟◌͝◌͞◌ͅb; a◌͟◌͝◌͞◌ͅb; a◌͟◌͝◌͞◌ͅb; a◌͟◌͝◌͞◌ͅb; ) LATIN SMALL LETTER A, COMBINING GREEK YPOGEGRAMMENI, COMBINING DOUBLE BREVE, COMBINING DOUBLE MACRON BELOW, COMBINING DOUBLE MACRON, LATIN SMALL LETTER B
+0061 035E 0345 035D 035F 0062;0061 035F 035E 035D 0345 0062;0061 035F 035E 035D 0345 0062;0061 035F 035E 035D 0345 0062;0061 035F 035E 035D 0345 0062; # (a◌͞◌ͅ◌͝◌͟b; a◌͟◌͞◌͝◌ͅb; a◌͟◌͞◌͝◌ͅb; a◌͟◌͞◌͝◌ͅb; a◌͟◌͞◌͝◌ͅb; ) LATIN SMALL LETTER A, COMBINING DOUBLE MACRON, COMBINING GREEK YPOGEGRAMMENI, COMBINING DOUBLE BREVE, COMBINING DOUBLE MACRON BELOW, LATIN SMALL LETTER B
+0061 035D 035F 0315 035F 0062;0061 0315 035F 035F 035D 0062;0061 0315 035F 035F 035D 0062;0061 0315 035F 035F 035D 0062;0061 0315 035F 035F 035D 0062; # (a◌͝◌͟◌̕◌͟b; a◌̕◌͟◌͟◌͝b; a◌̕◌͟◌͟◌͝b; a◌̕◌͟◌͟◌͝b; a◌̕◌͟◌͟◌͝b; ) LATIN SMALL LETTER A, COMBINING DOUBLE BREVE, COMBINING DOUBLE MACRON BELOW, COMBINING COMMA ABOVE RIGHT, COMBINING DOUBLE MACRON BELOW, LATIN SMALL LETTER B
+0061 035F 035D 035F 0315 0062;0061 0315 035F 035F 035D 0062;0061 0315 035F 035F 035D 0062;0061 0315 035F 035F 035D 0062;0061 0315 035F 035F 035D 0062; # (a◌͟◌͝◌͟◌̕b; a◌̕◌͟◌͟◌͝b; a◌̕◌͟◌͟◌͝b; a◌̕◌͟◌͟◌͝b; a◌̕◌͟◌͟◌͝b; ) LATIN SMALL LETTER A, COMBINING DOUBLE MACRON BELOW, COMBINING DOUBLE BREVE, COMBINING DOUBLE MACRON BELOW, COMBINING COMMA ABOVE RIGHT, LATIN SMALL LETTER B
+0061 0345 035D 035F 0360 0062;0061 035F 035D 0360 0345 0062;0061 035F 035D 0360 0345 0062;0061 035F 035D 0360 0345 0062;0061 035F 035D 0360 0345 0062; # (a◌ͅ◌͝◌͟◌͠b; a◌͟◌͝◌͠◌ͅb; a◌͟◌͝◌͠◌ͅb; a◌͟◌͝◌͠◌ͅb; a◌͟◌͝◌͠◌ͅb; ) LATIN SMALL LETTER A, COMBINING GREEK YPOGEGRAMMENI, COMBINING DOUBLE BREVE, COMBINING DOUBLE MACRON BELOW, COMBINING DOUBLE TILDE, LATIN SMALL LETTER B
+0061 0360 0345 035D 035F 0062;0061 035F 0360 035D 0345 0062;0061 035F 0360 035D 0345 0062;0061 035F 0360 035D 0345 0062;0061 035F 0360 035D 0345 0062; # (a◌͠◌ͅ◌͝◌͟b; a◌͟◌͠◌͝◌ͅb; a◌͟◌͠◌͝◌ͅb; a◌͟◌͠◌͝◌ͅb; a◌͟◌͠◌͝◌ͅb; ) LATIN SMALL LETTER A, COMBINING DOUBLE TILDE, COMBINING GREEK YPOGEGRAMMENI, COMBINING DOUBLE BREVE, COMBINING DOUBLE MACRON BELOW, LATIN SMALL LETTER B
+0061 0345 035D 035F 0361 0062;0061 035F 035D 0361 0345 0062;0061 035F 035D 0361 0345 0062;0061 035F 035D 0361 0345 0062;0061 035F 035D 0361 0345 0062; # (a◌ͅ◌͝◌͟◌͡b; a◌͟◌͝◌͡◌ͅb; a◌͟◌͝◌͡◌ͅb; a◌͟◌͝◌͡◌ͅb; a◌͟◌͝◌͡◌ͅb; ) LATIN SMALL LETTER A, COMBINING GREEK YPOGEGRAMMENI, COMBINING DOUBLE BREVE, COMBINING DOUBLE MACRON BELOW, COMBINING DOUBLE INVERTED BREVE, LATIN SMALL LETTER B
+0061 0361 0345 035D 035F 0062;0061 035F 0361 035D 0345 0062;0061 035F 0361 035D 0345 0062;0061 035F 0361 035D 0345 0062;0061 035F 0361 035D 0345 0062; # (a◌͡◌ͅ◌͝◌͟b; a◌͟◌͡◌͝◌ͅb; a◌͟◌͡◌͝◌ͅb; a◌͟◌͡◌͝◌ͅb; a◌͟◌͡◌͝◌ͅb; ) LATIN SMALL LETTER A, COMBINING DOUBLE INVERTED BREVE, COMBINING GREEK YPOGEGRAMMENI, COMBINING DOUBLE BREVE, COMBINING DOUBLE MACRON BELOW, LATIN SMALL LETTER B
+0061 035D 035F 0315 0362 0062;0061 0315 035F 0362 035D 0062;0061 0315 035F 0362 035D 0062;0061 0315 035F 0362 035D 0062;0061 0315 035F 0362 035D 0062; # (a◌͝◌͟◌̕◌͢b; a◌̕◌͟◌͢◌͝b; a◌̕◌͟◌͢◌͝b; a◌̕◌͟◌͢◌͝b; a◌̕◌͟◌͢◌͝b; ) LATIN SMALL LETTER A, COMBINING DOUBLE BREVE, COMBINING DOUBLE MACRON BELOW, COMBINING COMMA ABOVE RIGHT, COMBINING DOUBLE RIGHTWARDS ARROW BELOW, LATIN SMALL LETTER B
+0061 0362 035D 035F 0315 0062;0061 0315 0362 035F 035D 0062;0061 0315 0362 035F 035D 0062;0061 0315 0362 035F 035D 0062;0061 0315 0362 035F 035D 0062; # (a◌͢◌͝◌͟◌̕b; a◌̕◌͢◌͟◌͝b; a◌̕◌͢◌͟◌͝b; a◌̕◌͢◌͟◌͝b; a◌̕◌͢◌͟◌͝b; ) LATIN SMALL LETTER A, COMBINING DOUBLE RIGHTWARDS ARROW BELOW, COMBINING DOUBLE BREVE, COMBINING DOUBLE MACRON BELOW, COMBINING COMMA ABOVE RIGHT, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0363 0062;00E0 05AE 0363 0315 0062;0061 05AE 0300 0363 0315 0062;00E0 05AE 0363 0315 0062;0061 05AE 0300 0363 0315 0062; # (a◌̕◌̀◌֮◌ͣb; à◌֮◌ͣ◌̕b; a◌֮◌̀◌ͣ◌̕b; à◌֮◌ͣ◌̕b; a◌֮◌̀◌ͣ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LATIN SMALL LETTER A, LATIN SMALL LETTER B
+0061 0363 0315 0300 05AE 0062;0061 05AE 0363 0300 0315 0062;0061 05AE 0363 0300 0315 0062;0061 05AE 0363 0300 0315 0062;0061 05AE 0363 0300 0315 0062; # (a◌ͣ◌̕◌̀◌֮b; a◌֮◌ͣ◌̀◌̕b; a◌֮◌ͣ◌̀◌̕b; a◌֮◌ͣ◌̀◌̕b; a◌֮◌ͣ◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0364 0062;00E0 05AE 0364 0315 0062;0061 05AE 0300 0364 0315 0062;00E0 05AE 0364 0315 0062;0061 05AE 0300 0364 0315 0062; # (a◌̕◌̀◌֮◌ͤb; à◌֮◌ͤ◌̕b; a◌֮◌̀◌ͤ◌̕b; à◌֮◌ͤ◌̕b; a◌֮◌̀◌ͤ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LATIN SMALL LETTER E, LATIN SMALL LETTER B
+0061 0364 0315 0300 05AE 0062;0061 05AE 0364 0300 0315 0062;0061 05AE 0364 0300 0315 0062;0061 05AE 0364 0300 0315 0062;0061 05AE 0364 0300 0315 0062; # (a◌ͤ◌̕◌̀◌֮b; a◌֮◌ͤ◌̀◌̕b; a◌֮◌ͤ◌̀◌̕b; a◌֮◌ͤ◌̀◌̕b; a◌֮◌ͤ◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LATIN SMALL LETTER E, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0365 0062;00E0 05AE 0365 0315 0062;0061 05AE 0300 0365 0315 0062;00E0 05AE 0365 0315 0062;0061 05AE 0300 0365 0315 0062; # (a◌̕◌̀◌֮◌ͥb; à◌֮◌ͥ◌̕b; a◌֮◌̀◌ͥ◌̕b; à◌֮◌ͥ◌̕b; a◌֮◌̀◌ͥ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LATIN SMALL LETTER I, LATIN SMALL LETTER B
+0061 0365 0315 0300 05AE 0062;0061 05AE 0365 0300 0315 0062;0061 05AE 0365 0300 0315 0062;0061 05AE 0365 0300 0315 0062;0061 05AE 0365 0300 0315 0062; # (a◌ͥ◌̕◌̀◌֮b; a◌֮◌ͥ◌̀◌̕b; a◌֮◌ͥ◌̀◌̕b; a◌֮◌ͥ◌̀◌̕b; a◌֮◌ͥ◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LATIN SMALL LETTER I, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0366 0062;00E0 05AE 0366 0315 0062;0061 05AE 0300 0366 0315 0062;00E0 05AE 0366 0315 0062;0061 05AE 0300 0366 0315 0062; # (a◌̕◌̀◌֮◌ͦb; à◌֮◌ͦ◌̕b; a◌֮◌̀◌ͦ◌̕b; à◌֮◌ͦ◌̕b; a◌֮◌̀◌ͦ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LATIN SMALL LETTER O, LATIN SMALL LETTER B
+0061 0366 0315 0300 05AE 0062;0061 05AE 0366 0300 0315 0062;0061 05AE 0366 0300 0315 0062;0061 05AE 0366 0300 0315 0062;0061 05AE 0366 0300 0315 0062; # (a◌ͦ◌̕◌̀◌֮b; a◌֮◌ͦ◌̀◌̕b; a◌֮◌ͦ◌̀◌̕b; a◌֮◌ͦ◌̀◌̕b; a◌֮◌ͦ◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LATIN SMALL LETTER O, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0367 0062;00E0 05AE 0367 0315 0062;0061 05AE 0300 0367 0315 0062;00E0 05AE 0367 0315 0062;0061 05AE 0300 0367 0315 0062; # (a◌̕◌̀◌֮◌ͧb; à◌֮◌ͧ◌̕b; a◌֮◌̀◌ͧ◌̕b; à◌֮◌ͧ◌̕b; a◌֮◌̀◌ͧ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LATIN SMALL LETTER U, LATIN SMALL LETTER B
+0061 0367 0315 0300 05AE 0062;0061 05AE 0367 0300 0315 0062;0061 05AE 0367 0300 0315 0062;0061 05AE 0367 0300 0315 0062;0061 05AE 0367 0300 0315 0062; # (a◌ͧ◌̕◌̀◌֮b; a◌֮◌ͧ◌̀◌̕b; a◌֮◌ͧ◌̀◌̕b; a◌֮◌ͧ◌̀◌̕b; a◌֮◌ͧ◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LATIN SMALL LETTER U, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0368 0062;00E0 05AE 0368 0315 0062;0061 05AE 0300 0368 0315 0062;00E0 05AE 0368 0315 0062;0061 05AE 0300 0368 0315 0062; # (a◌̕◌̀◌֮◌ͨb; à◌֮◌ͨ◌̕b; a◌֮◌̀◌ͨ◌̕b; à◌֮◌ͨ◌̕b; a◌֮◌̀◌ͨ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LATIN SMALL LETTER C, LATIN SMALL LETTER B
+0061 0368 0315 0300 05AE 0062;0061 05AE 0368 0300 0315 0062;0061 05AE 0368 0300 0315 0062;0061 05AE 0368 0300 0315 0062;0061 05AE 0368 0300 0315 0062; # (a◌ͨ◌̕◌̀◌֮b; a◌֮◌ͨ◌̀◌̕b; a◌֮◌ͨ◌̀◌̕b; a◌֮◌ͨ◌̀◌̕b; a◌֮◌ͨ◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LATIN SMALL LETTER C, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0369 0062;00E0 05AE 0369 0315 0062;0061 05AE 0300 0369 0315 0062;00E0 05AE 0369 0315 0062;0061 05AE 0300 0369 0315 0062; # (a◌̕◌̀◌֮◌ͩb; à◌֮◌ͩ◌̕b; a◌֮◌̀◌ͩ◌̕b; à◌֮◌ͩ◌̕b; a◌֮◌̀◌ͩ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LATIN SMALL LETTER D, LATIN SMALL LETTER B
+0061 0369 0315 0300 05AE 0062;0061 05AE 0369 0300 0315 0062;0061 05AE 0369 0300 0315 0062;0061 05AE 0369 0300 0315 0062;0061 05AE 0369 0300 0315 0062; # (a◌ͩ◌̕◌̀◌֮b; a◌֮◌ͩ◌̀◌̕b; a◌֮◌ͩ◌̀◌̕b; a◌֮◌ͩ◌̀◌̕b; a◌֮◌ͩ◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LATIN SMALL LETTER D, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 036A 0062;00E0 05AE 036A 0315 0062;0061 05AE 0300 036A 0315 0062;00E0 05AE 036A 0315 0062;0061 05AE 0300 036A 0315 0062; # (a◌̕◌̀◌֮◌ͪb; à◌֮◌ͪ◌̕b; a◌֮◌̀◌ͪ◌̕b; à◌֮◌ͪ◌̕b; a◌֮◌̀◌ͪ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LATIN SMALL LETTER H, LATIN SMALL LETTER B
+0061 036A 0315 0300 05AE 0062;0061 05AE 036A 0300 0315 0062;0061 05AE 036A 0300 0315 0062;0061 05AE 036A 0300 0315 0062;0061 05AE 036A 0300 0315 0062; # (a◌ͪ◌̕◌̀◌֮b; a◌֮◌ͪ◌̀◌̕b; a◌֮◌ͪ◌̀◌̕b; a◌֮◌ͪ◌̀◌̕b; a◌֮◌ͪ◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LATIN SMALL LETTER H, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 036B 0062;00E0 05AE 036B 0315 0062;0061 05AE 0300 036B 0315 0062;00E0 05AE 036B 0315 0062;0061 05AE 0300 036B 0315 0062; # (a◌̕◌̀◌֮◌ͫb; à◌֮◌ͫ◌̕b; a◌֮◌̀◌ͫ◌̕b; à◌֮◌ͫ◌̕b; a◌֮◌̀◌ͫ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LATIN SMALL LETTER M, LATIN SMALL LETTER B
+0061 036B 0315 0300 05AE 0062;0061 05AE 036B 0300 0315 0062;0061 05AE 036B 0300 0315 0062;0061 05AE 036B 0300 0315 0062;0061 05AE 036B 0300 0315 0062; # (a◌ͫ◌̕◌̀◌֮b; a◌֮◌ͫ◌̀◌̕b; a◌֮◌ͫ◌̀◌̕b; a◌֮◌ͫ◌̀◌̕b; a◌֮◌ͫ◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LATIN SMALL LETTER M, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 036C 0062;00E0 05AE 036C 0315 0062;0061 05AE 0300 036C 0315 0062;00E0 05AE 036C 0315 0062;0061 05AE 0300 036C 0315 0062; # (a◌̕◌̀◌֮◌ͬb; à◌֮◌ͬ◌̕b; a◌֮◌̀◌ͬ◌̕b; à◌֮◌ͬ◌̕b; a◌֮◌̀◌ͬ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LATIN SMALL LETTER R, LATIN SMALL LETTER B
+0061 036C 0315 0300 05AE 0062;0061 05AE 036C 0300 0315 0062;0061 05AE 036C 0300 0315 0062;0061 05AE 036C 0300 0315 0062;0061 05AE 036C 0300 0315 0062; # (a◌ͬ◌̕◌̀◌֮b; a◌֮◌ͬ◌̀◌̕b; a◌֮◌ͬ◌̀◌̕b; a◌֮◌ͬ◌̀◌̕b; a◌֮◌ͬ◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LATIN SMALL LETTER R, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 036D 0062;00E0 05AE 036D 0315 0062;0061 05AE 0300 036D 0315 0062;00E0 05AE 036D 0315 0062;0061 05AE 0300 036D 0315 0062; # (a◌̕◌̀◌֮◌ͭb; à◌֮◌ͭ◌̕b; a◌֮◌̀◌ͭ◌̕b; à◌֮◌ͭ◌̕b; a◌֮◌̀◌ͭ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LATIN SMALL LETTER T, LATIN SMALL LETTER B
+0061 036D 0315 0300 05AE 0062;0061 05AE 036D 0300 0315 0062;0061 05AE 036D 0300 0315 0062;0061 05AE 036D 0300 0315 0062;0061 05AE 036D 0300 0315 0062; # (a◌ͭ◌̕◌̀◌֮b; a◌֮◌ͭ◌̀◌̕b; a◌֮◌ͭ◌̀◌̕b; a◌֮◌ͭ◌̀◌̕b; a◌֮◌ͭ◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LATIN SMALL LETTER T, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 036E 0062;00E0 05AE 036E 0315 0062;0061 05AE 0300 036E 0315 0062;00E0 05AE 036E 0315 0062;0061 05AE 0300 036E 0315 0062; # (a◌̕◌̀◌֮◌ͮb; à◌֮◌ͮ◌̕b; a◌֮◌̀◌ͮ◌̕b; à◌֮◌ͮ◌̕b; a◌֮◌̀◌ͮ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LATIN SMALL LETTER V, LATIN SMALL LETTER B
+0061 036E 0315 0300 05AE 0062;0061 05AE 036E 0300 0315 0062;0061 05AE 036E 0300 0315 0062;0061 05AE 036E 0300 0315 0062;0061 05AE 036E 0300 0315 0062; # (a◌ͮ◌̕◌̀◌֮b; a◌֮◌ͮ◌̀◌̕b; a◌֮◌ͮ◌̀◌̕b; a◌֮◌ͮ◌̀◌̕b; a◌֮◌ͮ◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LATIN SMALL LETTER V, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 036F 0062;00E0 05AE 036F 0315 0062;0061 05AE 0300 036F 0315 0062;00E0 05AE 036F 0315 0062;0061 05AE 0300 036F 0315 0062; # (a◌̕◌̀◌֮◌ͯb; à◌֮◌ͯ◌̕b; a◌֮◌̀◌ͯ◌̕b; à◌֮◌ͯ◌̕b; a◌֮◌̀◌ͯ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LATIN SMALL LETTER X, LATIN SMALL LETTER B
+0061 036F 0315 0300 05AE 0062;0061 05AE 036F 0300 0315 0062;0061 05AE 036F 0300 0315 0062;0061 05AE 036F 0300 0315 0062;0061 05AE 036F 0300 0315 0062; # (a◌ͯ◌̕◌̀◌֮b; a◌֮◌ͯ◌̀◌̕b; a◌֮◌ͯ◌̀◌̕b; a◌֮◌ͯ◌̀◌̕b; a◌֮◌ͯ◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LATIN SMALL LETTER X, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0483 0062;00E0 05AE 0483 0315 0062;0061 05AE 0300 0483 0315 0062;00E0 05AE 0483 0315 0062;0061 05AE 0300 0483 0315 0062; # (a◌̕◌̀◌֮◌҃b; à◌֮◌҃◌̕b; a◌֮◌̀◌҃◌̕b; à◌֮◌҃◌̕b; a◌֮◌̀◌҃◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING CYRILLIC TITLO, LATIN SMALL LETTER B
+0061 0483 0315 0300 05AE 0062;0061 05AE 0483 0300 0315 0062;0061 05AE 0483 0300 0315 0062;0061 05AE 0483 0300 0315 0062;0061 05AE 0483 0300 0315 0062; # (a◌҃◌̕◌̀◌֮b; a◌֮◌҃◌̀◌̕b; a◌֮◌҃◌̀◌̕b; a◌֮◌҃◌̀◌̕b; a◌֮◌҃◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING CYRILLIC TITLO, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0484 0062;00E0 05AE 0484 0315 0062;0061 05AE 0300 0484 0315 0062;00E0 05AE 0484 0315 0062;0061 05AE 0300 0484 0315 0062; # (a◌̕◌̀◌֮◌҄b; à◌֮◌҄◌̕b; a◌֮◌̀◌҄◌̕b; à◌֮◌҄◌̕b; a◌֮◌̀◌҄◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING CYRILLIC PALATALIZATION, LATIN SMALL LETTER B
+0061 0484 0315 0300 05AE 0062;0061 05AE 0484 0300 0315 0062;0061 05AE 0484 0300 0315 0062;0061 05AE 0484 0300 0315 0062;0061 05AE 0484 0300 0315 0062; # (a◌҄◌̕◌̀◌֮b; a◌֮◌҄◌̀◌̕b; a◌֮◌҄◌̀◌̕b; a◌֮◌҄◌̀◌̕b; a◌֮◌҄◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING CYRILLIC PALATALIZATION, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0485 0062;00E0 05AE 0485 0315 0062;0061 05AE 0300 0485 0315 0062;00E0 05AE 0485 0315 0062;0061 05AE 0300 0485 0315 0062; # (a◌̕◌̀◌֮◌҅b; à◌֮◌҅◌̕b; a◌֮◌̀◌҅◌̕b; à◌֮◌҅◌̕b; a◌֮◌̀◌҅◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING CYRILLIC DASIA PNEUMATA, LATIN SMALL LETTER B
+0061 0485 0315 0300 05AE 0062;0061 05AE 0485 0300 0315 0062;0061 05AE 0485 0300 0315 0062;0061 05AE 0485 0300 0315 0062;0061 05AE 0485 0300 0315 0062; # (a◌҅◌̕◌̀◌֮b; a◌֮◌҅◌̀◌̕b; a◌֮◌҅◌̀◌̕b; a◌֮◌҅◌̀◌̕b; a◌֮◌҅◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING CYRILLIC DASIA PNEUMATA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0486 0062;00E0 05AE 0486 0315 0062;0061 05AE 0300 0486 0315 0062;00E0 05AE 0486 0315 0062;0061 05AE 0300 0486 0315 0062; # (a◌̕◌̀◌֮◌҆b; à◌֮◌҆◌̕b; a◌֮◌̀◌҆◌̕b; à◌֮◌҆◌̕b; a◌֮◌̀◌҆◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING CYRILLIC PSILI PNEUMATA, LATIN SMALL LETTER B
+0061 0486 0315 0300 05AE 0062;0061 05AE 0486 0300 0315 0062;0061 05AE 0486 0300 0315 0062;0061 05AE 0486 0300 0315 0062;0061 05AE 0486 0300 0315 0062; # (a◌҆◌̕◌̀◌֮b; a◌֮◌҆◌̀◌̕b; a◌֮◌҆◌̀◌̕b; a◌֮◌҆◌̀◌̕b; a◌֮◌҆◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING CYRILLIC PSILI PNEUMATA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 0591 0062;0061 302A 0316 0591 059A 0062;0061 302A 0316 0591 059A 0062;0061 302A 0316 0591 059A 0062;0061 302A 0316 0591 059A 0062; # (a◌֚◌̖◌〪◌֑b; a◌〪◌̖◌֑◌֚b; a◌〪◌̖◌֑◌֚b; a◌〪◌̖◌֑◌֚b; a◌〪◌̖◌֑◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, HEBREW ACCENT ETNAHTA, LATIN SMALL LETTER B
+0061 0591 059A 0316 302A 0062;0061 302A 0591 0316 059A 0062;0061 302A 0591 0316 059A 0062;0061 302A 0591 0316 059A 0062;0061 302A 0591 0316 059A 0062; # (a◌֑◌֚◌̖◌〪b; a◌〪◌֑◌̖◌֚b; a◌〪◌֑◌̖◌֚b; a◌〪◌֑◌̖◌֚b; a◌〪◌֑◌̖◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT ETNAHTA, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0592 0062;00E0 05AE 0592 0315 0062;0061 05AE 0300 0592 0315 0062;00E0 05AE 0592 0315 0062;0061 05AE 0300 0592 0315 0062; # (a◌̕◌̀◌֮◌֒b; à◌֮◌֒◌̕b; a◌֮◌̀◌֒◌̕b; à◌֮◌֒◌̕b; a◌֮◌̀◌֒◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT SEGOL, LATIN SMALL LETTER B
+0061 0592 0315 0300 05AE 0062;0061 05AE 0592 0300 0315 0062;0061 05AE 0592 0300 0315 0062;0061 05AE 0592 0300 0315 0062;0061 05AE 0592 0300 0315 0062; # (a◌֒◌̕◌̀◌֮b; a◌֮◌֒◌̀◌̕b; a◌֮◌֒◌̀◌̕b; a◌֮◌֒◌̀◌̕b; a◌֮◌֒◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT SEGOL, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0593 0062;00E0 05AE 0593 0315 0062;0061 05AE 0300 0593 0315 0062;00E0 05AE 0593 0315 0062;0061 05AE 0300 0593 0315 0062; # (a◌̕◌̀◌֮◌֓b; à◌֮◌֓◌̕b; a◌֮◌̀◌֓◌̕b; à◌֮◌֓◌̕b; a◌֮◌̀◌֓◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT SHALSHELET, LATIN SMALL LETTER B
+0061 0593 0315 0300 05AE 0062;0061 05AE 0593 0300 0315 0062;0061 05AE 0593 0300 0315 0062;0061 05AE 0593 0300 0315 0062;0061 05AE 0593 0300 0315 0062; # (a◌֓◌̕◌̀◌֮b; a◌֮◌֓◌̀◌̕b; a◌֮◌֓◌̀◌̕b; a◌֮◌֓◌̀◌̕b; a◌֮◌֓◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT SHALSHELET, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0594 0062;00E0 05AE 0594 0315 0062;0061 05AE 0300 0594 0315 0062;00E0 05AE 0594 0315 0062;0061 05AE 0300 0594 0315 0062; # (a◌̕◌̀◌֮◌֔b; à◌֮◌֔◌̕b; a◌֮◌̀◌֔◌̕b; à◌֮◌֔◌̕b; a◌֮◌̀◌֔◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT ZAQEF QATAN, LATIN SMALL LETTER B
+0061 0594 0315 0300 05AE 0062;0061 05AE 0594 0300 0315 0062;0061 05AE 0594 0300 0315 0062;0061 05AE 0594 0300 0315 0062;0061 05AE 0594 0300 0315 0062; # (a◌֔◌̕◌̀◌֮b; a◌֮◌֔◌̀◌̕b; a◌֮◌֔◌̀◌̕b; a◌֮◌֔◌̀◌̕b; a◌֮◌֔◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT ZAQEF QATAN, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0595 0062;00E0 05AE 0595 0315 0062;0061 05AE 0300 0595 0315 0062;00E0 05AE 0595 0315 0062;0061 05AE 0300 0595 0315 0062; # (a◌̕◌̀◌֮◌֕b; à◌֮◌֕◌̕b; a◌֮◌̀◌֕◌̕b; à◌֮◌֕◌̕b; a◌֮◌̀◌֕◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT ZAQEF GADOL, LATIN SMALL LETTER B
+0061 0595 0315 0300 05AE 0062;0061 05AE 0595 0300 0315 0062;0061 05AE 0595 0300 0315 0062;0061 05AE 0595 0300 0315 0062;0061 05AE 0595 0300 0315 0062; # (a◌֕◌̕◌̀◌֮b; a◌֮◌֕◌̀◌̕b; a◌֮◌֕◌̀◌̕b; a◌֮◌֕◌̀◌̕b; a◌֮◌֕◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT ZAQEF GADOL, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 0596 0062;0061 302A 0316 0596 059A 0062;0061 302A 0316 0596 059A 0062;0061 302A 0316 0596 059A 0062;0061 302A 0316 0596 059A 0062; # (a◌֚◌̖◌〪◌֖b; a◌〪◌̖◌֖◌֚b; a◌〪◌̖◌֖◌֚b; a◌〪◌̖◌֖◌֚b; a◌〪◌̖◌֖◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, HEBREW ACCENT TIPEHA, LATIN SMALL LETTER B
+0061 0596 059A 0316 302A 0062;0061 302A 0596 0316 059A 0062;0061 302A 0596 0316 059A 0062;0061 302A 0596 0316 059A 0062;0061 302A 0596 0316 059A 0062; # (a◌֖◌֚◌̖◌〪b; a◌〪◌֖◌̖◌֚b; a◌〪◌֖◌̖◌֚b; a◌〪◌֖◌̖◌֚b; a◌〪◌֖◌̖◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT TIPEHA, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0597 0062;00E0 05AE 0597 0315 0062;0061 05AE 0300 0597 0315 0062;00E0 05AE 0597 0315 0062;0061 05AE 0300 0597 0315 0062; # (a◌̕◌̀◌֮◌֗b; à◌֮◌֗◌̕b; a◌֮◌̀◌֗◌̕b; à◌֮◌֗◌̕b; a◌֮◌̀◌֗◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT REVIA, LATIN SMALL LETTER B
+0061 0597 0315 0300 05AE 0062;0061 05AE 0597 0300 0315 0062;0061 05AE 0597 0300 0315 0062;0061 05AE 0597 0300 0315 0062;0061 05AE 0597 0300 0315 0062; # (a◌֗◌̕◌̀◌֮b; a◌֮◌֗◌̀◌̕b; a◌֮◌֗◌̀◌̕b; a◌֮◌֗◌̀◌̕b; a◌֮◌֗◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT REVIA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0598 0062;00E0 05AE 0598 0315 0062;0061 05AE 0300 0598 0315 0062;00E0 05AE 0598 0315 0062;0061 05AE 0300 0598 0315 0062; # (a◌̕◌̀◌֮◌֘b; à◌֮◌֘◌̕b; a◌֮◌̀◌֘◌̕b; à◌֮◌֘◌̕b; a◌֮◌̀◌֘◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT ZARQA, LATIN SMALL LETTER B
+0061 0598 0315 0300 05AE 0062;0061 05AE 0598 0300 0315 0062;0061 05AE 0598 0300 0315 0062;0061 05AE 0598 0300 0315 0062;0061 05AE 0598 0300 0315 0062; # (a◌֘◌̕◌̀◌֮b; a◌֮◌֘◌̀◌̕b; a◌֮◌֘◌̀◌̕b; a◌֮◌֘◌̀◌̕b; a◌֮◌֘◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT ZARQA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0599 0062;00E0 05AE 0599 0315 0062;0061 05AE 0300 0599 0315 0062;00E0 05AE 0599 0315 0062;0061 05AE 0300 0599 0315 0062; # (a◌̕◌̀◌֮◌֙b; à◌֮◌֙◌̕b; a◌֮◌̀◌֙◌̕b; à◌֮◌֙◌̕b; a◌֮◌̀◌֙◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT PASHTA, LATIN SMALL LETTER B
+0061 0599 0315 0300 05AE 0062;0061 05AE 0599 0300 0315 0062;0061 05AE 0599 0300 0315 0062;0061 05AE 0599 0300 0315 0062;0061 05AE 0599 0300 0315 0062; # (a◌֙◌̕◌̀◌֮b; a◌֮◌֙◌̀◌̕b; a◌֮◌֙◌̀◌̕b; a◌֮◌֙◌̀◌̕b; a◌֮◌֙◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT PASHTA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 302E 059A 0316 059A 0062;0061 0316 059A 059A 302E 0062;0061 0316 059A 059A 302E 0062;0061 0316 059A 059A 302E 0062;0061 0316 059A 059A 302E 0062; # (a◌〮◌֚◌̖◌֚b; a◌̖◌֚◌֚◌〮b; a◌̖◌֚◌֚◌〮b; a◌̖◌֚◌֚◌〮b; a◌̖◌֚◌֚◌〮b; ) LATIN SMALL LETTER A, HANGUL SINGLE DOT TONE MARK, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, HEBREW ACCENT YETIV, LATIN SMALL LETTER B
+0061 059A 302E 059A 0316 0062;0061 0316 059A 059A 302E 0062;0061 0316 059A 059A 302E 0062;0061 0316 059A 059A 302E 0062;0061 0316 059A 059A 302E 0062; # (a◌֚◌〮◌֚◌̖b; a◌̖◌֚◌֚◌〮b; a◌̖◌֚◌֚◌〮b; a◌̖◌֚◌֚◌〮b; a◌̖◌֚◌֚◌〮b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, HANGUL SINGLE DOT TONE MARK, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, LATIN SMALL LETTER B
+0061 059A 0316 302A 059B 0062;0061 302A 0316 059B 059A 0062;0061 302A 0316 059B 059A 0062;0061 302A 0316 059B 059A 0062;0061 302A 0316 059B 059A 0062; # (a◌֚◌̖◌〪◌֛b; a◌〪◌̖◌֛◌֚b; a◌〪◌̖◌֛◌֚b; a◌〪◌̖◌֛◌֚b; a◌〪◌̖◌֛◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, HEBREW ACCENT TEVIR, LATIN SMALL LETTER B
+0061 059B 059A 0316 302A 0062;0061 302A 059B 0316 059A 0062;0061 302A 059B 0316 059A 0062;0061 302A 059B 0316 059A 0062;0061 302A 059B 0316 059A 0062; # (a◌֛◌֚◌̖◌〪b; a◌〪◌֛◌̖◌֚b; a◌〪◌֛◌̖◌֚b; a◌〪◌֛◌̖◌֚b; a◌〪◌֛◌̖◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT TEVIR, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 059C 0062;00E0 05AE 059C 0315 0062;0061 05AE 0300 059C 0315 0062;00E0 05AE 059C 0315 0062;0061 05AE 0300 059C 0315 0062; # (a◌̕◌̀◌֮◌֜b; à◌֮◌֜◌̕b; a◌֮◌̀◌֜◌̕b; à◌֮◌֜◌̕b; a◌֮◌̀◌֜◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT GERESH, LATIN SMALL LETTER B
+0061 059C 0315 0300 05AE 0062;0061 05AE 059C 0300 0315 0062;0061 05AE 059C 0300 0315 0062;0061 05AE 059C 0300 0315 0062;0061 05AE 059C 0300 0315 0062; # (a◌֜◌̕◌̀◌֮b; a◌֮◌֜◌̀◌̕b; a◌֮◌֜◌̀◌̕b; a◌֮◌֜◌̀◌̕b; a◌֮◌֜◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT GERESH, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 059D 0062;00E0 05AE 059D 0315 0062;0061 05AE 0300 059D 0315 0062;00E0 05AE 059D 0315 0062;0061 05AE 0300 059D 0315 0062; # (a◌̕◌̀◌֮◌֝b; à◌֮◌֝◌̕b; a◌֮◌̀◌֝◌̕b; à◌֮◌֝◌̕b; a◌֮◌̀◌֝◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT GERESH MUQDAM, LATIN SMALL LETTER B
+0061 059D 0315 0300 05AE 0062;0061 05AE 059D 0300 0315 0062;0061 05AE 059D 0300 0315 0062;0061 05AE 059D 0300 0315 0062;0061 05AE 059D 0300 0315 0062; # (a◌֝◌̕◌̀◌֮b; a◌֮◌֝◌̀◌̕b; a◌֮◌֝◌̀◌̕b; a◌֮◌֝◌̀◌̕b; a◌֮◌֝◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT GERESH MUQDAM, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 059E 0062;00E0 05AE 059E 0315 0062;0061 05AE 0300 059E 0315 0062;00E0 05AE 059E 0315 0062;0061 05AE 0300 059E 0315 0062; # (a◌̕◌̀◌֮◌֞b; à◌֮◌֞◌̕b; a◌֮◌̀◌֞◌̕b; à◌֮◌֞◌̕b; a◌֮◌̀◌֞◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT GERSHAYIM, LATIN SMALL LETTER B
+0061 059E 0315 0300 05AE 0062;0061 05AE 059E 0300 0315 0062;0061 05AE 059E 0300 0315 0062;0061 05AE 059E 0300 0315 0062;0061 05AE 059E 0300 0315 0062; # (a◌֞◌̕◌̀◌֮b; a◌֮◌֞◌̀◌̕b; a◌֮◌֞◌̀◌̕b; a◌֮◌֞◌̀◌̕b; a◌֮◌֞◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT GERSHAYIM, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 059F 0062;00E0 05AE 059F 0315 0062;0061 05AE 0300 059F 0315 0062;00E0 05AE 059F 0315 0062;0061 05AE 0300 059F 0315 0062; # (a◌̕◌̀◌֮◌֟b; à◌֮◌֟◌̕b; a◌֮◌̀◌֟◌̕b; à◌֮◌֟◌̕b; a◌֮◌̀◌֟◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT QARNEY PARA, LATIN SMALL LETTER B
+0061 059F 0315 0300 05AE 0062;0061 05AE 059F 0300 0315 0062;0061 05AE 059F 0300 0315 0062;0061 05AE 059F 0300 0315 0062;0061 05AE 059F 0300 0315 0062; # (a◌֟◌̕◌̀◌֮b; a◌֮◌֟◌̀◌̕b; a◌֮◌֟◌̀◌̕b; a◌֮◌֟◌̀◌̕b; a◌֮◌֟◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT QARNEY PARA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 05A0 0062;00E0 05AE 05A0 0315 0062;0061 05AE 0300 05A0 0315 0062;00E0 05AE 05A0 0315 0062;0061 05AE 0300 05A0 0315 0062; # (a◌̕◌̀◌֮◌֠b; à◌֮◌֠◌̕b; a◌֮◌̀◌֠◌̕b; à◌֮◌֠◌̕b; a◌֮◌̀◌֠◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT TELISHA GEDOLA, LATIN SMALL LETTER B
+0061 05A0 0315 0300 05AE 0062;0061 05AE 05A0 0300 0315 0062;0061 05AE 05A0 0300 0315 0062;0061 05AE 05A0 0300 0315 0062;0061 05AE 05A0 0300 0315 0062; # (a◌֠◌̕◌̀◌֮b; a◌֮◌֠◌̀◌̕b; a◌֮◌֠◌̀◌̕b; a◌֮◌֠◌̀◌̕b; a◌֮◌֠◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT TELISHA GEDOLA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 05A1 0062;00E0 05AE 05A1 0315 0062;0061 05AE 0300 05A1 0315 0062;00E0 05AE 05A1 0315 0062;0061 05AE 0300 05A1 0315 0062; # (a◌̕◌̀◌֮◌֡b; à◌֮◌֡◌̕b; a◌֮◌̀◌֡◌̕b; à◌֮◌֡◌̕b; a◌֮◌̀◌֡◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT PAZER, LATIN SMALL LETTER B
+0061 05A1 0315 0300 05AE 0062;0061 05AE 05A1 0300 0315 0062;0061 05AE 05A1 0300 0315 0062;0061 05AE 05A1 0300 0315 0062;0061 05AE 05A1 0300 0315 0062; # (a◌֡◌̕◌̀◌֮b; a◌֮◌֡◌̀◌̕b; a◌֮◌֡◌̀◌̕b; a◌֮◌֡◌̀◌̕b; a◌֮◌֡◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT PAZER, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 05A3 0062;0061 302A 0316 05A3 059A 0062;0061 302A 0316 05A3 059A 0062;0061 302A 0316 05A3 059A 0062;0061 302A 0316 05A3 059A 0062; # (a◌֚◌̖◌〪◌֣b; a◌〪◌̖◌֣◌֚b; a◌〪◌̖◌֣◌֚b; a◌〪◌̖◌֣◌֚b; a◌〪◌̖◌֣◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, HEBREW ACCENT MUNAH, LATIN SMALL LETTER B
+0061 05A3 059A 0316 302A 0062;0061 302A 05A3 0316 059A 0062;0061 302A 05A3 0316 059A 0062;0061 302A 05A3 0316 059A 0062;0061 302A 05A3 0316 059A 0062; # (a◌֣◌֚◌̖◌〪b; a◌〪◌֣◌̖◌֚b; a◌〪◌֣◌̖◌֚b; a◌〪◌֣◌̖◌֚b; a◌〪◌֣◌̖◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT MUNAH, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 05A4 0062;0061 302A 0316 05A4 059A 0062;0061 302A 0316 05A4 059A 0062;0061 302A 0316 05A4 059A 0062;0061 302A 0316 05A4 059A 0062; # (a◌֚◌̖◌〪◌֤b; a◌〪◌̖◌֤◌֚b; a◌〪◌̖◌֤◌֚b; a◌〪◌̖◌֤◌֚b; a◌〪◌̖◌֤◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, HEBREW ACCENT MAHAPAKH, LATIN SMALL LETTER B
+0061 05A4 059A 0316 302A 0062;0061 302A 05A4 0316 059A 0062;0061 302A 05A4 0316 059A 0062;0061 302A 05A4 0316 059A 0062;0061 302A 05A4 0316 059A 0062; # (a◌֤◌֚◌̖◌〪b; a◌〪◌֤◌̖◌֚b; a◌〪◌֤◌̖◌֚b; a◌〪◌֤◌̖◌֚b; a◌〪◌֤◌̖◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT MAHAPAKH, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 05A5 0062;0061 302A 0316 05A5 059A 0062;0061 302A 0316 05A5 059A 0062;0061 302A 0316 05A5 059A 0062;0061 302A 0316 05A5 059A 0062; # (a◌֚◌̖◌〪◌֥b; a◌〪◌̖◌֥◌֚b; a◌〪◌̖◌֥◌֚b; a◌〪◌̖◌֥◌֚b; a◌〪◌̖◌֥◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, HEBREW ACCENT MERKHA, LATIN SMALL LETTER B
+0061 05A5 059A 0316 302A 0062;0061 302A 05A5 0316 059A 0062;0061 302A 05A5 0316 059A 0062;0061 302A 05A5 0316 059A 0062;0061 302A 05A5 0316 059A 0062; # (a◌֥◌֚◌̖◌〪b; a◌〪◌֥◌̖◌֚b; a◌〪◌֥◌̖◌֚b; a◌〪◌֥◌̖◌֚b; a◌〪◌֥◌̖◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT MERKHA, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 05A6 0062;0061 302A 0316 05A6 059A 0062;0061 302A 0316 05A6 059A 0062;0061 302A 0316 05A6 059A 0062;0061 302A 0316 05A6 059A 0062; # (a◌֚◌̖◌〪◌֦b; a◌〪◌̖◌֦◌֚b; a◌〪◌̖◌֦◌֚b; a◌〪◌̖◌֦◌֚b; a◌〪◌̖◌֦◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, HEBREW ACCENT MERKHA KEFULA, LATIN SMALL LETTER B
+0061 05A6 059A 0316 302A 0062;0061 302A 05A6 0316 059A 0062;0061 302A 05A6 0316 059A 0062;0061 302A 05A6 0316 059A 0062;0061 302A 05A6 0316 059A 0062; # (a◌֦◌֚◌̖◌〪b; a◌〪◌֦◌̖◌֚b; a◌〪◌֦◌̖◌֚b; a◌〪◌֦◌̖◌֚b; a◌〪◌֦◌̖◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT MERKHA KEFULA, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 05A7 0062;0061 302A 0316 05A7 059A 0062;0061 302A 0316 05A7 059A 0062;0061 302A 0316 05A7 059A 0062;0061 302A 0316 05A7 059A 0062; # (a◌֚◌̖◌〪◌֧b; a◌〪◌̖◌֧◌֚b; a◌〪◌̖◌֧◌֚b; a◌〪◌̖◌֧◌֚b; a◌〪◌̖◌֧◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, HEBREW ACCENT DARGA, LATIN SMALL LETTER B
+0061 05A7 059A 0316 302A 0062;0061 302A 05A7 0316 059A 0062;0061 302A 05A7 0316 059A 0062;0061 302A 05A7 0316 059A 0062;0061 302A 05A7 0316 059A 0062; # (a◌֧◌֚◌̖◌〪b; a◌〪◌֧◌̖◌֚b; a◌〪◌֧◌̖◌֚b; a◌〪◌֧◌̖◌֚b; a◌〪◌֧◌̖◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT DARGA, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 05A8 0062;00E0 05AE 05A8 0315 0062;0061 05AE 0300 05A8 0315 0062;00E0 05AE 05A8 0315 0062;0061 05AE 0300 05A8 0315 0062; # (a◌̕◌̀◌֮◌֨b; à◌֮◌֨◌̕b; a◌֮◌̀◌֨◌̕b; à◌֮◌֨◌̕b; a◌֮◌̀◌֨◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT QADMA, LATIN SMALL LETTER B
+0061 05A8 0315 0300 05AE 0062;0061 05AE 05A8 0300 0315 0062;0061 05AE 05A8 0300 0315 0062;0061 05AE 05A8 0300 0315 0062;0061 05AE 05A8 0300 0315 0062; # (a◌֨◌̕◌̀◌֮b; a◌֮◌֨◌̀◌̕b; a◌֮◌֨◌̀◌̕b; a◌֮◌֨◌̀◌̕b; a◌֮◌֨◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT QADMA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 05A9 0062;00E0 05AE 05A9 0315 0062;0061 05AE 0300 05A9 0315 0062;00E0 05AE 05A9 0315 0062;0061 05AE 0300 05A9 0315 0062; # (a◌̕◌̀◌֮◌֩b; à◌֮◌֩◌̕b; a◌֮◌̀◌֩◌̕b; à◌֮◌֩◌̕b; a◌֮◌̀◌֩◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT TELISHA QETANA, LATIN SMALL LETTER B
+0061 05A9 0315 0300 05AE 0062;0061 05AE 05A9 0300 0315 0062;0061 05AE 05A9 0300 0315 0062;0061 05AE 05A9 0300 0315 0062;0061 05AE 05A9 0300 0315 0062; # (a◌֩◌̕◌̀◌֮b; a◌֮◌֩◌̀◌̕b; a◌֮◌֩◌̀◌̕b; a◌֮◌֩◌̀◌̕b; a◌֮◌֩◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT TELISHA QETANA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 05AA 0062;0061 302A 0316 05AA 059A 0062;0061 302A 0316 05AA 059A 0062;0061 302A 0316 05AA 059A 0062;0061 302A 0316 05AA 059A 0062; # (a◌֚◌̖◌〪◌֪b; a◌〪◌̖◌֪◌֚b; a◌〪◌̖◌֪◌֚b; a◌〪◌̖◌֪◌֚b; a◌〪◌̖◌֪◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, HEBREW ACCENT YERAH BEN YOMO, LATIN SMALL LETTER B
+0061 05AA 059A 0316 302A 0062;0061 302A 05AA 0316 059A 0062;0061 302A 05AA 0316 059A 0062;0061 302A 05AA 0316 059A 0062;0061 302A 05AA 0316 059A 0062; # (a◌֪◌֚◌̖◌〪b; a◌〪◌֪◌̖◌֚b; a◌〪◌֪◌̖◌֚b; a◌〪◌֪◌̖◌֚b; a◌〪◌֪◌̖◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YERAH BEN YOMO, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 05AB 0062;00E0 05AE 05AB 0315 0062;0061 05AE 0300 05AB 0315 0062;00E0 05AE 05AB 0315 0062;0061 05AE 0300 05AB 0315 0062; # (a◌̕◌̀◌֮◌֫b; à◌֮◌֫◌̕b; a◌֮◌̀◌֫◌̕b; à◌֮◌֫◌̕b; a◌֮◌̀◌֫◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT OLE, LATIN SMALL LETTER B
+0061 05AB 0315 0300 05AE 0062;0061 05AE 05AB 0300 0315 0062;0061 05AE 05AB 0300 0315 0062;0061 05AE 05AB 0300 0315 0062;0061 05AE 05AB 0300 0315 0062; # (a◌֫◌̕◌̀◌֮b; a◌֮◌֫◌̀◌̕b; a◌֮◌֫◌̀◌̕b; a◌֮◌֫◌̀◌̕b; a◌֮◌֫◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT OLE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 05AC 0062;00E0 05AE 05AC 0315 0062;0061 05AE 0300 05AC 0315 0062;00E0 05AE 05AC 0315 0062;0061 05AE 0300 05AC 0315 0062; # (a◌̕◌̀◌֮◌֬b; à◌֮◌֬◌̕b; a◌֮◌̀◌֬◌̕b; à◌֮◌֬◌̕b; a◌֮◌̀◌֬◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW ACCENT ILUY, LATIN SMALL LETTER B
+0061 05AC 0315 0300 05AE 0062;0061 05AE 05AC 0300 0315 0062;0061 05AE 05AC 0300 0315 0062;0061 05AE 05AC 0300 0315 0062;0061 05AE 05AC 0300 0315 0062; # (a◌֬◌̕◌̀◌֮b; a◌֮◌֬◌̀◌̕b; a◌֮◌֬◌̀◌̕b; a◌֮◌֬◌̀◌̕b; a◌֮◌֬◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW ACCENT ILUY, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 302E 059A 0316 05AD 0062;0061 0316 059A 05AD 302E 0062;0061 0316 059A 05AD 302E 0062;0061 0316 059A 05AD 302E 0062;0061 0316 059A 05AD 302E 0062; # (a◌〮◌֚◌̖◌֭b; a◌̖◌֚◌֭◌〮b; a◌̖◌֚◌֭◌〮b; a◌̖◌֚◌֭◌〮b; a◌̖◌֚◌֭◌〮b; ) LATIN SMALL LETTER A, HANGUL SINGLE DOT TONE MARK, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, HEBREW ACCENT DEHI, LATIN SMALL LETTER B
+0061 05AD 302E 059A 0316 0062;0061 0316 05AD 059A 302E 0062;0061 0316 05AD 059A 302E 0062;0061 0316 05AD 059A 302E 0062;0061 0316 05AD 059A 302E 0062; # (a◌֭◌〮◌֚◌̖b; a◌̖◌֭◌֚◌〮b; a◌̖◌֭◌֚◌〮b; a◌̖◌֭◌֚◌〮b; a◌̖◌֭◌֚◌〮b; ) LATIN SMALL LETTER A, HEBREW ACCENT DEHI, HANGUL SINGLE DOT TONE MARK, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, LATIN SMALL LETTER B
+0061 0300 05AE 1D16D 05AE 0062;00E0 1D16D 05AE 05AE 0062;0061 1D16D 05AE 05AE 0300 0062;00E0 1D16D 05AE 05AE 0062;0061 1D16D 05AE 05AE 0300 0062; # (a◌̀◌𝅭𝅭֮◌֮b; à𝅭𝅭◌֮◌֮b; a𝅭𝅭◌֮◌֮◌̀b; à𝅭𝅭◌֮◌֮b; a𝅭𝅭◌֮◌֮◌̀b; ) LATIN SMALL LETTER A, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING AUGMENTATION DOT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 05AE 0300 05AE 1D16D 0062;00E0 1D16D 05AE 05AE 0062;0061 1D16D 05AE 05AE 0300 0062;00E0 1D16D 05AE 05AE 0062;0061 1D16D 05AE 05AE 0300 0062; # (a◌֮◌̀◌𝅭𝅭֮b; à𝅭𝅭◌֮◌֮b; a𝅭𝅭◌֮◌֮◌̀b; à𝅭𝅭◌֮◌֮b; a𝅭𝅭◌֮◌֮◌̀b; ) LATIN SMALL LETTER A, HEBREW ACCENT ZINOR, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING AUGMENTATION DOT, LATIN SMALL LETTER B
+0061 0315 0300 05AE 05AF 0062;00E0 05AE 05AF 0315 0062;0061 05AE 0300 05AF 0315 0062;00E0 05AE 05AF 0315 0062;0061 05AE 0300 05AF 0315 0062; # (a◌̕◌̀◌֮◌֯b; à◌֮◌֯◌̕b; a◌֮◌̀◌֯◌̕b; à◌֮◌֯◌̕b; a◌֮◌̀◌֯◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW MARK MASORA CIRCLE, LATIN SMALL LETTER B
+0061 05AF 0315 0300 05AE 0062;0061 05AE 05AF 0300 0315 0062;0061 05AE 05AF 0300 0315 0062;0061 05AE 05AF 0300 0315 0062;0061 05AE 05AF 0300 0315 0062; # (a◌֯◌̕◌̀◌֮b; a◌֮◌֯◌̀◌̕b; a◌֮◌֯◌̀◌̕b; a◌֮◌֯◌̀◌̕b; a◌֮◌֯◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW MARK MASORA CIRCLE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 05B1 05B0 094D 05B0 0062;0061 094D 05B0 05B0 05B1 0062;0061 094D 05B0 05B0 05B1 0062;0061 094D 05B0 05B0 05B1 0062;0061 094D 05B0 05B0 05B1 0062; # (a◌ֱ◌ְ◌्◌ְb; a◌्◌ְ◌ְ◌ֱb; a◌्◌ְ◌ְ◌ֱb; a◌्◌ְ◌ְ◌ֱb; a◌्◌ְ◌ְ◌ֱb; ) LATIN SMALL LETTER A, HEBREW POINT HATAF SEGOL, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, HEBREW POINT SHEVA, LATIN SMALL LETTER B
+0061 05B0 05B1 05B0 094D 0062;0061 094D 05B0 05B0 05B1 0062;0061 094D 05B0 05B0 05B1 0062;0061 094D 05B0 05B0 05B1 0062;0061 094D 05B0 05B0 05B1 0062; # (a◌ְ◌ֱ◌ְ◌्b; a◌्◌ְ◌ְ◌ֱb; a◌्◌ְ◌ְ◌ֱb; a◌्◌ְ◌ְ◌ֱb; a◌्◌ְ◌ְ◌ֱb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, HEBREW POINT HATAF SEGOL, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, LATIN SMALL LETTER B
+0061 05B2 05B1 05B0 05B1 0062;0061 05B0 05B1 05B1 05B2 0062;0061 05B0 05B1 05B1 05B2 0062;0061 05B0 05B1 05B1 05B2 0062;0061 05B0 05B1 05B1 05B2 0062; # (a◌ֲ◌ֱ◌ְ◌ֱb; a◌ְ◌ֱ◌ֱ◌ֲb; a◌ְ◌ֱ◌ֱ◌ֲb; a◌ְ◌ֱ◌ֱ◌ֲb; a◌ְ◌ֱ◌ֱ◌ֲb; ) LATIN SMALL LETTER A, HEBREW POINT HATAF PATAH, HEBREW POINT HATAF SEGOL, HEBREW POINT SHEVA, HEBREW POINT HATAF SEGOL, LATIN SMALL LETTER B
+0061 05B1 05B2 05B1 05B0 0062;0061 05B0 05B1 05B1 05B2 0062;0061 05B0 05B1 05B1 05B2 0062;0061 05B0 05B1 05B1 05B2 0062;0061 05B0 05B1 05B1 05B2 0062; # (a◌ֱ◌ֲ◌ֱ◌ְb; a◌ְ◌ֱ◌ֱ◌ֲb; a◌ְ◌ֱ◌ֱ◌ֲb; a◌ְ◌ֱ◌ֱ◌ֲb; a◌ְ◌ֱ◌ֱ◌ֲb; ) LATIN SMALL LETTER A, HEBREW POINT HATAF SEGOL, HEBREW POINT HATAF PATAH, HEBREW POINT HATAF SEGOL, HEBREW POINT SHEVA, LATIN SMALL LETTER B
+0061 05B3 05B2 05B1 05B2 0062;0061 05B1 05B2 05B2 05B3 0062;0061 05B1 05B2 05B2 05B3 0062;0061 05B1 05B2 05B2 05B3 0062;0061 05B1 05B2 05B2 05B3 0062; # (a◌ֳ◌ֲ◌ֱ◌ֲb; a◌ֱ◌ֲ◌ֲ◌ֳb; a◌ֱ◌ֲ◌ֲ◌ֳb; a◌ֱ◌ֲ◌ֲ◌ֳb; a◌ֱ◌ֲ◌ֲ◌ֳb; ) LATIN SMALL LETTER A, HEBREW POINT HATAF QAMATS, HEBREW POINT HATAF PATAH, HEBREW POINT HATAF SEGOL, HEBREW POINT HATAF PATAH, LATIN SMALL LETTER B
+0061 05B2 05B3 05B2 05B1 0062;0061 05B1 05B2 05B2 05B3 0062;0061 05B1 05B2 05B2 05B3 0062;0061 05B1 05B2 05B2 05B3 0062;0061 05B1 05B2 05B2 05B3 0062; # (a◌ֲ◌ֳ◌ֲ◌ֱb; a◌ֱ◌ֲ◌ֲ◌ֳb; a◌ֱ◌ֲ◌ֲ◌ֳb; a◌ֱ◌ֲ◌ֲ◌ֳb; a◌ֱ◌ֲ◌ֲ◌ֳb; ) LATIN SMALL LETTER A, HEBREW POINT HATAF PATAH, HEBREW POINT HATAF QAMATS, HEBREW POINT HATAF PATAH, HEBREW POINT HATAF SEGOL, LATIN SMALL LETTER B
+0061 05B4 05B3 05B2 05B3 0062;0061 05B2 05B3 05B3 05B4 0062;0061 05B2 05B3 05B3 05B4 0062;0061 05B2 05B3 05B3 05B4 0062;0061 05B2 05B3 05B3 05B4 0062; # (a◌ִ◌ֳ◌ֲ◌ֳb; a◌ֲ◌ֳ◌ֳ◌ִb; a◌ֲ◌ֳ◌ֳ◌ִb; a◌ֲ◌ֳ◌ֳ◌ִb; a◌ֲ◌ֳ◌ֳ◌ִb; ) LATIN SMALL LETTER A, HEBREW POINT HIRIQ, HEBREW POINT HATAF QAMATS, HEBREW POINT HATAF PATAH, HEBREW POINT HATAF QAMATS, LATIN SMALL LETTER B
+0061 05B3 05B4 05B3 05B2 0062;0061 05B2 05B3 05B3 05B4 0062;0061 05B2 05B3 05B3 05B4 0062;0061 05B2 05B3 05B3 05B4 0062;0061 05B2 05B3 05B3 05B4 0062; # (a◌ֳ◌ִ◌ֳ◌ֲb; a◌ֲ◌ֳ◌ֳ◌ִb; a◌ֲ◌ֳ◌ֳ◌ִb; a◌ֲ◌ֳ◌ֳ◌ִb; a◌ֲ◌ֳ◌ֳ◌ִb; ) LATIN SMALL LETTER A, HEBREW POINT HATAF QAMATS, HEBREW POINT HIRIQ, HEBREW POINT HATAF QAMATS, HEBREW POINT HATAF PATAH, LATIN SMALL LETTER B
+0061 05B5 05B4 05B3 05B4 0062;0061 05B3 05B4 05B4 05B5 0062;0061 05B3 05B4 05B4 05B5 0062;0061 05B3 05B4 05B4 05B5 0062;0061 05B3 05B4 05B4 05B5 0062; # (a◌ֵ◌ִ◌ֳ◌ִb; a◌ֳ◌ִ◌ִ◌ֵb; a◌ֳ◌ִ◌ִ◌ֵb; a◌ֳ◌ִ◌ִ◌ֵb; a◌ֳ◌ִ◌ִ◌ֵb; ) LATIN SMALL LETTER A, HEBREW POINT TSERE, HEBREW POINT HIRIQ, HEBREW POINT HATAF QAMATS, HEBREW POINT HIRIQ, LATIN SMALL LETTER B
+0061 05B4 05B5 05B4 05B3 0062;0061 05B3 05B4 05B4 05B5 0062;0061 05B3 05B4 05B4 05B5 0062;0061 05B3 05B4 05B4 05B5 0062;0061 05B3 05B4 05B4 05B5 0062; # (a◌ִ◌ֵ◌ִ◌ֳb; a◌ֳ◌ִ◌ִ◌ֵb; a◌ֳ◌ִ◌ִ◌ֵb; a◌ֳ◌ִ◌ִ◌ֵb; a◌ֳ◌ִ◌ִ◌ֵb; ) LATIN SMALL LETTER A, HEBREW POINT HIRIQ, HEBREW POINT TSERE, HEBREW POINT HIRIQ, HEBREW POINT HATAF QAMATS, LATIN SMALL LETTER B
+0061 05B6 05B5 05B4 05B5 0062;0061 05B4 05B5 05B5 05B6 0062;0061 05B4 05B5 05B5 05B6 0062;0061 05B4 05B5 05B5 05B6 0062;0061 05B4 05B5 05B5 05B6 0062; # (a◌ֶ◌ֵ◌ִ◌ֵb; a◌ִ◌ֵ◌ֵ◌ֶb; a◌ִ◌ֵ◌ֵ◌ֶb; a◌ִ◌ֵ◌ֵ◌ֶb; a◌ִ◌ֵ◌ֵ◌ֶb; ) LATIN SMALL LETTER A, HEBREW POINT SEGOL, HEBREW POINT TSERE, HEBREW POINT HIRIQ, HEBREW POINT TSERE, LATIN SMALL LETTER B
+0061 05B5 05B6 05B5 05B4 0062;0061 05B4 05B5 05B5 05B6 0062;0061 05B4 05B5 05B5 05B6 0062;0061 05B4 05B5 05B5 05B6 0062;0061 05B4 05B5 05B5 05B6 0062; # (a◌ֵ◌ֶ◌ֵ◌ִb; a◌ִ◌ֵ◌ֵ◌ֶb; a◌ִ◌ֵ◌ֵ◌ֶb; a◌ִ◌ֵ◌ֵ◌ֶb; a◌ִ◌ֵ◌ֵ◌ֶb; ) LATIN SMALL LETTER A, HEBREW POINT TSERE, HEBREW POINT SEGOL, HEBREW POINT TSERE, HEBREW POINT HIRIQ, LATIN SMALL LETTER B
+0061 05B7 05B6 05B5 05B6 0062;0061 05B5 05B6 05B6 05B7 0062;0061 05B5 05B6 05B6 05B7 0062;0061 05B5 05B6 05B6 05B7 0062;0061 05B5 05B6 05B6 05B7 0062; # (a◌ַ◌ֶ◌ֵ◌ֶb; a◌ֵ◌ֶ◌ֶ◌ַb; a◌ֵ◌ֶ◌ֶ◌ַb; a◌ֵ◌ֶ◌ֶ◌ַb; a◌ֵ◌ֶ◌ֶ◌ַb; ) LATIN SMALL LETTER A, HEBREW POINT PATAH, HEBREW POINT SEGOL, HEBREW POINT TSERE, HEBREW POINT SEGOL, LATIN SMALL LETTER B
+0061 05B6 05B7 05B6 05B5 0062;0061 05B5 05B6 05B6 05B7 0062;0061 05B5 05B6 05B6 05B7 0062;0061 05B5 05B6 05B6 05B7 0062;0061 05B5 05B6 05B6 05B7 0062; # (a◌ֶ◌ַ◌ֶ◌ֵb; a◌ֵ◌ֶ◌ֶ◌ַb; a◌ֵ◌ֶ◌ֶ◌ַb; a◌ֵ◌ֶ◌ֶ◌ַb; a◌ֵ◌ֶ◌ֶ◌ַb; ) LATIN SMALL LETTER A, HEBREW POINT SEGOL, HEBREW POINT PATAH, HEBREW POINT SEGOL, HEBREW POINT TSERE, LATIN SMALL LETTER B
+0061 05B8 05B7 05B6 05B7 0062;0061 05B6 05B7 05B7 05B8 0062;0061 05B6 05B7 05B7 05B8 0062;0061 05B6 05B7 05B7 05B8 0062;0061 05B6 05B7 05B7 05B8 0062; # (a◌ָ◌ַ◌ֶ◌ַb; a◌ֶ◌ַ◌ַ◌ָb; a◌ֶ◌ַ◌ַ◌ָb; a◌ֶ◌ַ◌ַ◌ָb; a◌ֶ◌ַ◌ַ◌ָb; ) LATIN SMALL LETTER A, HEBREW POINT QAMATS, HEBREW POINT PATAH, HEBREW POINT SEGOL, HEBREW POINT PATAH, LATIN SMALL LETTER B
+0061 05B7 05B8 05B7 05B6 0062;0061 05B6 05B7 05B7 05B8 0062;0061 05B6 05B7 05B7 05B8 0062;0061 05B6 05B7 05B7 05B8 0062;0061 05B6 05B7 05B7 05B8 0062; # (a◌ַ◌ָ◌ַ◌ֶb; a◌ֶ◌ַ◌ַ◌ָb; a◌ֶ◌ַ◌ַ◌ָb; a◌ֶ◌ַ◌ַ◌ָb; a◌ֶ◌ַ◌ַ◌ָb; ) LATIN SMALL LETTER A, HEBREW POINT PATAH, HEBREW POINT QAMATS, HEBREW POINT PATAH, HEBREW POINT SEGOL, LATIN SMALL LETTER B
+0061 05B9 05B8 05B7 05B8 0062;0061 05B7 05B8 05B8 05B9 0062;0061 05B7 05B8 05B8 05B9 0062;0061 05B7 05B8 05B8 05B9 0062;0061 05B7 05B8 05B8 05B9 0062; # (a◌ֹ◌ָ◌ַ◌ָb; a◌ַ◌ָ◌ָ◌ֹb; a◌ַ◌ָ◌ָ◌ֹb; a◌ַ◌ָ◌ָ◌ֹb; a◌ַ◌ָ◌ָ◌ֹb; ) LATIN SMALL LETTER A, HEBREW POINT HOLAM, HEBREW POINT QAMATS, HEBREW POINT PATAH, HEBREW POINT QAMATS, LATIN SMALL LETTER B
+0061 05B8 05B9 05B8 05B7 0062;0061 05B7 05B8 05B8 05B9 0062;0061 05B7 05B8 05B8 05B9 0062;0061 05B7 05B8 05B8 05B9 0062;0061 05B7 05B8 05B8 05B9 0062; # (a◌ָ◌ֹ◌ָ◌ַb; a◌ַ◌ָ◌ָ◌ֹb; a◌ַ◌ָ◌ָ◌ֹb; a◌ַ◌ָ◌ָ◌ֹb; a◌ַ◌ָ◌ָ◌ֹb; ) LATIN SMALL LETTER A, HEBREW POINT QAMATS, HEBREW POINT HOLAM, HEBREW POINT QAMATS, HEBREW POINT PATAH, LATIN SMALL LETTER B
+0061 05BB 05B9 05B8 05B9 0062;0061 05B8 05B9 05B9 05BB 0062;0061 05B8 05B9 05B9 05BB 0062;0061 05B8 05B9 05B9 05BB 0062;0061 05B8 05B9 05B9 05BB 0062; # (a◌ֻ◌ֹ◌ָ◌ֹb; a◌ָ◌ֹ◌ֹ◌ֻb; a◌ָ◌ֹ◌ֹ◌ֻb; a◌ָ◌ֹ◌ֹ◌ֻb; a◌ָ◌ֹ◌ֹ◌ֻb; ) LATIN SMALL LETTER A, HEBREW POINT QUBUTS, HEBREW POINT HOLAM, HEBREW POINT QAMATS, HEBREW POINT HOLAM, LATIN SMALL LETTER B
+0061 05B9 05BB 05B9 05B8 0062;0061 05B8 05B9 05B9 05BB 0062;0061 05B8 05B9 05B9 05BB 0062;0061 05B8 05B9 05B9 05BB 0062;0061 05B8 05B9 05B9 05BB 0062; # (a◌ֹ◌ֻ◌ֹ◌ָb; a◌ָ◌ֹ◌ֹ◌ֻb; a◌ָ◌ֹ◌ֹ◌ֻb; a◌ָ◌ֹ◌ֹ◌ֻb; a◌ָ◌ֹ◌ֹ◌ֻb; ) LATIN SMALL LETTER A, HEBREW POINT HOLAM, HEBREW POINT QUBUTS, HEBREW POINT HOLAM, HEBREW POINT QAMATS, LATIN SMALL LETTER B
+0061 05BC 05BB 05B9 05BB 0062;0061 05B9 05BB 05BB 05BC 0062;0061 05B9 05BB 05BB 05BC 0062;0061 05B9 05BB 05BB 05BC 0062;0061 05B9 05BB 05BB 05BC 0062; # (a◌ּ◌ֻ◌ֹ◌ֻb; a◌ֹ◌ֻ◌ֻ◌ּb; a◌ֹ◌ֻ◌ֻ◌ּb; a◌ֹ◌ֻ◌ֻ◌ּb; a◌ֹ◌ֻ◌ֻ◌ּb; ) LATIN SMALL LETTER A, HEBREW POINT DAGESH OR MAPIQ, HEBREW POINT QUBUTS, HEBREW POINT HOLAM, HEBREW POINT QUBUTS, LATIN SMALL LETTER B
+0061 05BB 05BC 05BB 05B9 0062;0061 05B9 05BB 05BB 05BC 0062;0061 05B9 05BB 05BB 05BC 0062;0061 05B9 05BB 05BB 05BC 0062;0061 05B9 05BB 05BB 05BC 0062; # (a◌ֻ◌ּ◌ֻ◌ֹb; a◌ֹ◌ֻ◌ֻ◌ּb; a◌ֹ◌ֻ◌ֻ◌ּb; a◌ֹ◌ֻ◌ֻ◌ּb; a◌ֹ◌ֻ◌ֻ◌ּb; ) LATIN SMALL LETTER A, HEBREW POINT QUBUTS, HEBREW POINT DAGESH OR MAPIQ, HEBREW POINT QUBUTS, HEBREW POINT HOLAM, LATIN SMALL LETTER B
+0061 05BD 05BC 05BB 05BC 0062;0061 05BB 05BC 05BC 05BD 0062;0061 05BB 05BC 05BC 05BD 0062;0061 05BB 05BC 05BC 05BD 0062;0061 05BB 05BC 05BC 05BD 0062; # (a◌ֽ◌ּ◌ֻ◌ּb; a◌ֻ◌ּ◌ּ◌ֽb; a◌ֻ◌ּ◌ּ◌ֽb; a◌ֻ◌ּ◌ּ◌ֽb; a◌ֻ◌ּ◌ּ◌ֽb; ) LATIN SMALL LETTER A, HEBREW POINT METEG, HEBREW POINT DAGESH OR MAPIQ, HEBREW POINT QUBUTS, HEBREW POINT DAGESH OR MAPIQ, LATIN SMALL LETTER B
+0061 05BC 05BD 05BC 05BB 0062;0061 05BB 05BC 05BC 05BD 0062;0061 05BB 05BC 05BC 05BD 0062;0061 05BB 05BC 05BC 05BD 0062;0061 05BB 05BC 05BC 05BD 0062; # (a◌ּ◌ֽ◌ּ◌ֻb; a◌ֻ◌ּ◌ּ◌ֽb; a◌ֻ◌ּ◌ּ◌ֽb; a◌ֻ◌ּ◌ּ◌ֽb; a◌ֻ◌ּ◌ּ◌ֽb; ) LATIN SMALL LETTER A, HEBREW POINT DAGESH OR MAPIQ, HEBREW POINT METEG, HEBREW POINT DAGESH OR MAPIQ, HEBREW POINT QUBUTS, LATIN SMALL LETTER B
+0061 05BF 05BD 05BC 05BD 0062;0061 05BC 05BD 05BD 05BF 0062;0061 05BC 05BD 05BD 05BF 0062;0061 05BC 05BD 05BD 05BF 0062;0061 05BC 05BD 05BD 05BF 0062; # (a◌ֿ◌ֽ◌ּ◌ֽb; a◌ּ◌ֽ◌ֽ◌ֿb; a◌ּ◌ֽ◌ֽ◌ֿb; a◌ּ◌ֽ◌ֽ◌ֿb; a◌ּ◌ֽ◌ֽ◌ֿb; ) LATIN SMALL LETTER A, HEBREW POINT RAFE, HEBREW POINT METEG, HEBREW POINT DAGESH OR MAPIQ, HEBREW POINT METEG, LATIN SMALL LETTER B
+0061 05BD 05BF 05BD 05BC 0062;0061 05BC 05BD 05BD 05BF 0062;0061 05BC 05BD 05BD 05BF 0062;0061 05BC 05BD 05BD 05BF 0062;0061 05BC 05BD 05BD 05BF 0062; # (a◌ֽ◌ֿ◌ֽ◌ּb; a◌ּ◌ֽ◌ֽ◌ֿb; a◌ּ◌ֽ◌ֽ◌ֿb; a◌ּ◌ֽ◌ֽ◌ֿb; a◌ּ◌ֽ◌ֽ◌ֿb; ) LATIN SMALL LETTER A, HEBREW POINT METEG, HEBREW POINT RAFE, HEBREW POINT METEG, HEBREW POINT DAGESH OR MAPIQ, LATIN SMALL LETTER B
+0061 05C1 05BF 05BD 05BF 0062;0061 05BD 05BF 05BF 05C1 0062;0061 05BD 05BF 05BF 05C1 0062;0061 05BD 05BF 05BF 05C1 0062;0061 05BD 05BF 05BF 05C1 0062; # (a◌ׁ◌ֿ◌ֽ◌ֿb; a◌ֽ◌ֿ◌ֿ◌ׁb; a◌ֽ◌ֿ◌ֿ◌ׁb; a◌ֽ◌ֿ◌ֿ◌ׁb; a◌ֽ◌ֿ◌ֿ◌ׁb; ) LATIN SMALL LETTER A, HEBREW POINT SHIN DOT, HEBREW POINT RAFE, HEBREW POINT METEG, HEBREW POINT RAFE, LATIN SMALL LETTER B
+0061 05BF 05C1 05BF 05BD 0062;0061 05BD 05BF 05BF 05C1 0062;0061 05BD 05BF 05BF 05C1 0062;0061 05BD 05BF 05BF 05C1 0062;0061 05BD 05BF 05BF 05C1 0062; # (a◌ֿ◌ׁ◌ֿ◌ֽb; a◌ֽ◌ֿ◌ֿ◌ׁb; a◌ֽ◌ֿ◌ֿ◌ׁb; a◌ֽ◌ֿ◌ֿ◌ׁb; a◌ֽ◌ֿ◌ֿ◌ׁb; ) LATIN SMALL LETTER A, HEBREW POINT RAFE, HEBREW POINT SHIN DOT, HEBREW POINT RAFE, HEBREW POINT METEG, LATIN SMALL LETTER B
+0061 05C2 05C1 05BF 05C1 0062;0061 05BF 05C1 05C1 05C2 0062;0061 05BF 05C1 05C1 05C2 0062;0061 05BF 05C1 05C1 05C2 0062;0061 05BF 05C1 05C1 05C2 0062; # (a◌ׂ◌ׁ◌ֿ◌ׁb; a◌ֿ◌ׁ◌ׁ◌ׂb; a◌ֿ◌ׁ◌ׁ◌ׂb; a◌ֿ◌ׁ◌ׁ◌ׂb; a◌ֿ◌ׁ◌ׁ◌ׂb; ) LATIN SMALL LETTER A, HEBREW POINT SIN DOT, HEBREW POINT SHIN DOT, HEBREW POINT RAFE, HEBREW POINT SHIN DOT, LATIN SMALL LETTER B
+0061 05C1 05C2 05C1 05BF 0062;0061 05BF 05C1 05C1 05C2 0062;0061 05BF 05C1 05C1 05C2 0062;0061 05BF 05C1 05C1 05C2 0062;0061 05BF 05C1 05C1 05C2 0062; # (a◌ׁ◌ׂ◌ׁ◌ֿb; a◌ֿ◌ׁ◌ׁ◌ׂb; a◌ֿ◌ׁ◌ׁ◌ׂb; a◌ֿ◌ׁ◌ׁ◌ׂb; a◌ֿ◌ׁ◌ׁ◌ׂb; ) LATIN SMALL LETTER A, HEBREW POINT SHIN DOT, HEBREW POINT SIN DOT, HEBREW POINT SHIN DOT, HEBREW POINT RAFE, LATIN SMALL LETTER B
+0061 FB1E 05C2 05C1 05C2 0062;0061 05C1 05C2 05C2 FB1E 0062;0061 05C1 05C2 05C2 FB1E 0062;0061 05C1 05C2 05C2 FB1E 0062;0061 05C1 05C2 05C2 FB1E 0062; # (a◌ﬞ◌ׂ◌ׁ◌ׂb; a◌ׁ◌ׂ◌ׂ◌ﬞb; a◌ׁ◌ׂ◌ׂ◌ﬞb; a◌ׁ◌ׂ◌ׂ◌ﬞb; a◌ׁ◌ׂ◌ׂ◌ﬞb; ) LATIN SMALL LETTER A, HEBREW POINT JUDEO-SPANISH VARIKA, HEBREW POINT SIN DOT, HEBREW POINT SHIN DOT, HEBREW POINT SIN DOT, LATIN SMALL LETTER B
+0061 05C2 FB1E 05C2 05C1 0062;0061 05C1 05C2 05C2 FB1E 0062;0061 05C1 05C2 05C2 FB1E 0062;0061 05C1 05C2 05C2 FB1E 0062;0061 05C1 05C2 05C2 FB1E 0062; # (a◌ׂ◌ﬞ◌ׂ◌ׁb; a◌ׁ◌ׂ◌ׂ◌ﬞb; a◌ׁ◌ׂ◌ׂ◌ﬞb; a◌ׁ◌ׂ◌ׂ◌ﬞb; a◌ׁ◌ׂ◌ׂ◌ﬞb; ) LATIN SMALL LETTER A, HEBREW POINT SIN DOT, HEBREW POINT JUDEO-SPANISH VARIKA, HEBREW POINT SIN DOT, HEBREW POINT SHIN DOT, LATIN SMALL LETTER B
+0061 0315 0300 05AE 05C4 0062;00E0 05AE 05C4 0315 0062;0061 05AE 0300 05C4 0315 0062;00E0 05AE 05C4 0315 0062;0061 05AE 0300 05C4 0315 0062; # (a◌̕◌̀◌֮◌ׄb; à◌֮◌ׄ◌̕b; a◌֮◌̀◌ׄ◌̕b; à◌֮◌ׄ◌̕b; a◌֮◌̀◌ׄ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, HEBREW MARK UPPER DOT, LATIN SMALL LETTER B
+0061 05C4 0315 0300 05AE 0062;0061 05AE 05C4 0300 0315 0062;0061 05AE 05C4 0300 0315 0062;0061 05AE 05C4 0300 0315 0062;0061 05AE 05C4 0300 0315 0062; # (a◌ׄ◌̕◌̀◌֮b; a◌֮◌ׄ◌̀◌̕b; a◌֮◌ׄ◌̀◌̕b; a◌֮◌ׄ◌̀◌̕b; a◌֮◌ׄ◌̀◌̕b; ) LATIN SMALL LETTER A, HEBREW MARK UPPER DOT, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0610 0062;00E0 05AE 0610 0315 0062;0061 05AE 0300 0610 0315 0062;00E0 05AE 0610 0315 0062;0061 05AE 0300 0610 0315 0062; # (a◌̕◌̀◌֮◌ؐb; à◌֮◌ؐ◌̕b; a◌֮◌̀◌ؐ◌̕b; à◌֮◌ؐ◌̕b; a◌֮◌̀◌ؐ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SIGN SALLALLAHOU ALAYHE WASSALLAM, LATIN SMALL LETTER B
+0061 0610 0315 0300 05AE 0062;0061 05AE 0610 0300 0315 0062;0061 05AE 0610 0300 0315 0062;0061 05AE 0610 0300 0315 0062;0061 05AE 0610 0300 0315 0062; # (a◌ؐ◌̕◌̀◌֮b; a◌֮◌ؐ◌̀◌̕b; a◌֮◌ؐ◌̀◌̕b; a◌֮◌ؐ◌̀◌̕b; a◌֮◌ؐ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SIGN SALLALLAHOU ALAYHE WASSALLAM, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0611 0062;00E0 05AE 0611 0315 0062;0061 05AE 0300 0611 0315 0062;00E0 05AE 0611 0315 0062;0061 05AE 0300 0611 0315 0062; # (a◌̕◌̀◌֮◌ؑb; à◌֮◌ؑ◌̕b; a◌֮◌̀◌ؑ◌̕b; à◌֮◌ؑ◌̕b; a◌֮◌̀◌ؑ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SIGN ALAYHE ASSALLAM, LATIN SMALL LETTER B
+0061 0611 0315 0300 05AE 0062;0061 05AE 0611 0300 0315 0062;0061 05AE 0611 0300 0315 0062;0061 05AE 0611 0300 0315 0062;0061 05AE 0611 0300 0315 0062; # (a◌ؑ◌̕◌̀◌֮b; a◌֮◌ؑ◌̀◌̕b; a◌֮◌ؑ◌̀◌̕b; a◌֮◌ؑ◌̀◌̕b; a◌֮◌ؑ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SIGN ALAYHE ASSALLAM, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0612 0062;00E0 05AE 0612 0315 0062;0061 05AE 0300 0612 0315 0062;00E0 05AE 0612 0315 0062;0061 05AE 0300 0612 0315 0062; # (a◌̕◌̀◌֮◌ؒb; à◌֮◌ؒ◌̕b; a◌֮◌̀◌ؒ◌̕b; à◌֮◌ؒ◌̕b; a◌֮◌̀◌ؒ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SIGN RAHMATULLAH ALAYHE, LATIN SMALL LETTER B
+0061 0612 0315 0300 05AE 0062;0061 05AE 0612 0300 0315 0062;0061 05AE 0612 0300 0315 0062;0061 05AE 0612 0300 0315 0062;0061 05AE 0612 0300 0315 0062; # (a◌ؒ◌̕◌̀◌֮b; a◌֮◌ؒ◌̀◌̕b; a◌֮◌ؒ◌̀◌̕b; a◌֮◌ؒ◌̀◌̕b; a◌֮◌ؒ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SIGN RAHMATULLAH ALAYHE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0613 0062;00E0 05AE 0613 0315 0062;0061 05AE 0300 0613 0315 0062;00E0 05AE 0613 0315 0062;0061 05AE 0300 0613 0315 0062; # (a◌̕◌̀◌֮◌ؓb; à◌֮◌ؓ◌̕b; a◌֮◌̀◌ؓ◌̕b; à◌֮◌ؓ◌̕b; a◌֮◌̀◌ؓ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SIGN RADI ALLAHOU ANHU, LATIN SMALL LETTER B
+0061 0613 0315 0300 05AE 0062;0061 05AE 0613 0300 0315 0062;0061 05AE 0613 0300 0315 0062;0061 05AE 0613 0300 0315 0062;0061 05AE 0613 0300 0315 0062; # (a◌ؓ◌̕◌̀◌֮b; a◌֮◌ؓ◌̀◌̕b; a◌֮◌ؓ◌̀◌̕b; a◌֮◌ؓ◌̀◌̕b; a◌֮◌ؓ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SIGN RADI ALLAHOU ANHU, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0614 0062;00E0 05AE 0614 0315 0062;0061 05AE 0300 0614 0315 0062;00E0 05AE 0614 0315 0062;0061 05AE 0300 0614 0315 0062; # (a◌̕◌̀◌֮◌ؔb; à◌֮◌ؔ◌̕b; a◌֮◌̀◌ؔ◌̕b; à◌֮◌ؔ◌̕b; a◌֮◌̀◌ؔ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SIGN TAKHALLUS, LATIN SMALL LETTER B
+0061 0614 0315 0300 05AE 0062;0061 05AE 0614 0300 0315 0062;0061 05AE 0614 0300 0315 0062;0061 05AE 0614 0300 0315 0062;0061 05AE 0614 0300 0315 0062; # (a◌ؔ◌̕◌̀◌֮b; a◌֮◌ؔ◌̀◌̕b; a◌֮◌ؔ◌̀◌̕b; a◌֮◌ؔ◌̀◌̕b; a◌֮◌ؔ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SIGN TAKHALLUS, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0615 0062;00E0 05AE 0615 0315 0062;0061 05AE 0300 0615 0315 0062;00E0 05AE 0615 0315 0062;0061 05AE 0300 0615 0315 0062; # (a◌̕◌̀◌֮◌ؕb; à◌֮◌ؕ◌̕b; a◌֮◌̀◌ؕ◌̕b; à◌֮◌ؕ◌̕b; a◌֮◌̀◌ؕ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH TAH, LATIN SMALL LETTER B
+0061 0615 0315 0300 05AE 0062;0061 05AE 0615 0300 0315 0062;0061 05AE 0615 0300 0315 0062;0061 05AE 0615 0300 0315 0062;0061 05AE 0615 0300 0315 0062; # (a◌ؕ◌̕◌̀◌֮b; a◌֮◌ؕ◌̀◌̕b; a◌֮◌ؕ◌̀◌̕b; a◌֮◌ؕ◌̀◌̕b; a◌֮◌ؕ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH TAH, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 064C 064B FB1E 064B 0062;0061 FB1E 064B 064B 064C 0062;0061 FB1E 064B 064B 064C 0062;0061 FB1E 064B 064B 064C 0062;0061 FB1E 064B 064B 064C 0062; # (a◌ٌ◌ً◌ﬞ◌ًb; a◌ﬞ◌ً◌ً◌ٌb; a◌ﬞ◌ً◌ً◌ٌb; a◌ﬞ◌ً◌ً◌ٌb; a◌ﬞ◌ً◌ً◌ٌb; ) LATIN SMALL LETTER A, ARABIC DAMMATAN, ARABIC FATHATAN, HEBREW POINT JUDEO-SPANISH VARIKA, ARABIC FATHATAN, LATIN SMALL LETTER B
+0061 064B 064C 064B FB1E 0062;0061 FB1E 064B 064B 064C 0062;0061 FB1E 064B 064B 064C 0062;0061 FB1E 064B 064B 064C 0062;0061 FB1E 064B 064B 064C 0062; # (a◌ً◌ٌ◌ً◌ﬞb; a◌ﬞ◌ً◌ً◌ٌb; a◌ﬞ◌ً◌ً◌ٌb; a◌ﬞ◌ً◌ً◌ٌb; a◌ﬞ◌ً◌ً◌ٌb; ) LATIN SMALL LETTER A, ARABIC FATHATAN, ARABIC DAMMATAN, ARABIC FATHATAN, HEBREW POINT JUDEO-SPANISH VARIKA, LATIN SMALL LETTER B
+0061 064D 064C 064B 064C 0062;0061 064B 064C 064C 064D 0062;0061 064B 064C 064C 064D 0062;0061 064B 064C 064C 064D 0062;0061 064B 064C 064C 064D 0062; # (a◌ٍ◌ٌ◌ً◌ٌb; a◌ً◌ٌ◌ٌ◌ٍb; a◌ً◌ٌ◌ٌ◌ٍb; a◌ً◌ٌ◌ٌ◌ٍb; a◌ً◌ٌ◌ٌ◌ٍb; ) LATIN SMALL LETTER A, ARABIC KASRATAN, ARABIC DAMMATAN, ARABIC FATHATAN, ARABIC DAMMATAN, LATIN SMALL LETTER B
+0061 064C 064D 064C 064B 0062;0061 064B 064C 064C 064D 0062;0061 064B 064C 064C 064D 0062;0061 064B 064C 064C 064D 0062;0061 064B 064C 064C 064D 0062; # (a◌ٌ◌ٍ◌ٌ◌ًb; a◌ً◌ٌ◌ٌ◌ٍb; a◌ً◌ٌ◌ٌ◌ٍb; a◌ً◌ٌ◌ٌ◌ٍb; a◌ً◌ٌ◌ٌ◌ٍb; ) LATIN SMALL LETTER A, ARABIC DAMMATAN, ARABIC KASRATAN, ARABIC DAMMATAN, ARABIC FATHATAN, LATIN SMALL LETTER B
+0061 064E 064D 064C 064D 0062;0061 064C 064D 064D 064E 0062;0061 064C 064D 064D 064E 0062;0061 064C 064D 064D 064E 0062;0061 064C 064D 064D 064E 0062; # (a◌َ◌ٍ◌ٌ◌ٍb; a◌ٌ◌ٍ◌ٍ◌َb; a◌ٌ◌ٍ◌ٍ◌َb; a◌ٌ◌ٍ◌ٍ◌َb; a◌ٌ◌ٍ◌ٍ◌َb; ) LATIN SMALL LETTER A, ARABIC FATHA, ARABIC KASRATAN, ARABIC DAMMATAN, ARABIC KASRATAN, LATIN SMALL LETTER B
+0061 064D 064E 064D 064C 0062;0061 064C 064D 064D 064E 0062;0061 064C 064D 064D 064E 0062;0061 064C 064D 064D 064E 0062;0061 064C 064D 064D 064E 0062; # (a◌ٍ◌َ◌ٍ◌ٌb; a◌ٌ◌ٍ◌ٍ◌َb; a◌ٌ◌ٍ◌ٍ◌َb; a◌ٌ◌ٍ◌ٍ◌َb; a◌ٌ◌ٍ◌ٍ◌َb; ) LATIN SMALL LETTER A, ARABIC KASRATAN, ARABIC FATHA, ARABIC KASRATAN, ARABIC DAMMATAN, LATIN SMALL LETTER B
+0061 064F 064E 064D 064E 0062;0061 064D 064E 064E 064F 0062;0061 064D 064E 064E 064F 0062;0061 064D 064E 064E 064F 0062;0061 064D 064E 064E 064F 0062; # (a◌ُ◌َ◌ٍ◌َb; a◌ٍ◌َ◌َ◌ُb; a◌ٍ◌َ◌َ◌ُb; a◌ٍ◌َ◌َ◌ُb; a◌ٍ◌َ◌َ◌ُb; ) LATIN SMALL LETTER A, ARABIC DAMMA, ARABIC FATHA, ARABIC KASRATAN, ARABIC FATHA, LATIN SMALL LETTER B
+0061 064E 064F 064E 064D 0062;0061 064D 064E 064E 064F 0062;0061 064D 064E 064E 064F 0062;0061 064D 064E 064E 064F 0062;0061 064D 064E 064E 064F 0062; # (a◌َ◌ُ◌َ◌ٍb; a◌ٍ◌َ◌َ◌ُb; a◌ٍ◌َ◌َ◌ُb; a◌ٍ◌َ◌َ◌ُb; a◌ٍ◌َ◌َ◌ُb; ) LATIN SMALL LETTER A, ARABIC FATHA, ARABIC DAMMA, ARABIC FATHA, ARABIC KASRATAN, LATIN SMALL LETTER B
+0061 0650 064F 064E 064F 0062;0061 064E 064F 064F 0650 0062;0061 064E 064F 064F 0650 0062;0061 064E 064F 064F 0650 0062;0061 064E 064F 064F 0650 0062; # (a◌ِ◌ُ◌َ◌ُb; a◌َ◌ُ◌ُ◌ِb; a◌َ◌ُ◌ُ◌ِb; a◌َ◌ُ◌ُ◌ِb; a◌َ◌ُ◌ُ◌ِb; ) LATIN SMALL LETTER A, ARABIC KASRA, ARABIC DAMMA, ARABIC FATHA, ARABIC DAMMA, LATIN SMALL LETTER B
+0061 064F 0650 064F 064E 0062;0061 064E 064F 064F 0650 0062;0061 064E 064F 064F 0650 0062;0061 064E 064F 064F 0650 0062;0061 064E 064F 064F 0650 0062; # (a◌ُ◌ِ◌ُ◌َb; a◌َ◌ُ◌ُ◌ِb; a◌َ◌ُ◌ُ◌ِb; a◌َ◌ُ◌ُ◌ِb; a◌َ◌ُ◌ُ◌ِb; ) LATIN SMALL LETTER A, ARABIC DAMMA, ARABIC KASRA, ARABIC DAMMA, ARABIC FATHA, LATIN SMALL LETTER B
+0061 0651 0650 064F 0650 0062;0061 064F 0650 0650 0651 0062;0061 064F 0650 0650 0651 0062;0061 064F 0650 0650 0651 0062;0061 064F 0650 0650 0651 0062; # (a◌ّ◌ِ◌ُ◌ِb; a◌ُ◌ِ◌ِ◌ّb; a◌ُ◌ِ◌ِ◌ّb; a◌ُ◌ِ◌ِ◌ّb; a◌ُ◌ِ◌ِ◌ّb; ) LATIN SMALL LETTER A, ARABIC SHADDA, ARABIC KASRA, ARABIC DAMMA, ARABIC KASRA, LATIN SMALL LETTER B
+0061 0650 0651 0650 064F 0062;0061 064F 0650 0650 0651 0062;0061 064F 0650 0650 0651 0062;0061 064F 0650 0650 0651 0062;0061 064F 0650 0650 0651 0062; # (a◌ِ◌ّ◌ِ◌ُb; a◌ُ◌ِ◌ِ◌ّb; a◌ُ◌ِ◌ِ◌ّb; a◌ُ◌ِ◌ِ◌ّb; a◌ُ◌ِ◌ِ◌ّb; ) LATIN SMALL LETTER A, ARABIC KASRA, ARABIC SHADDA, ARABIC KASRA, ARABIC DAMMA, LATIN SMALL LETTER B
+0061 0652 0651 0650 0651 0062;0061 0650 0651 0651 0652 0062;0061 0650 0651 0651 0652 0062;0061 0650 0651 0651 0652 0062;0061 0650 0651 0651 0652 0062; # (a◌ْ◌ّ◌ِ◌ّb; a◌ِ◌ّ◌ّ◌ْb; a◌ِ◌ّ◌ّ◌ْb; a◌ِ◌ّ◌ّ◌ْb; a◌ِ◌ّ◌ّ◌ْb; ) LATIN SMALL LETTER A, ARABIC SUKUN, ARABIC SHADDA, ARABIC KASRA, ARABIC SHADDA, LATIN SMALL LETTER B
+0061 0651 0652 0651 0650 0062;0061 0650 0651 0651 0652 0062;0061 0650 0651 0651 0652 0062;0061 0650 0651 0651 0652 0062;0061 0650 0651 0651 0652 0062; # (a◌ّ◌ْ◌ّ◌ِb; a◌ِ◌ّ◌ّ◌ْb; a◌ِ◌ّ◌ّ◌ْb; a◌ِ◌ّ◌ّ◌ْb; a◌ِ◌ّ◌ّ◌ْb; ) LATIN SMALL LETTER A, ARABIC SHADDA, ARABIC SUKUN, ARABIC SHADDA, ARABIC KASRA, LATIN SMALL LETTER B
+0061 0670 0652 0651 0652 0062;0061 0651 0652 0652 0670 0062;0061 0651 0652 0652 0670 0062;0061 0651 0652 0652 0670 0062;0061 0651 0652 0652 0670 0062; # (a◌ٰ◌ْ◌ّ◌ْb; a◌ّ◌ْ◌ْ◌ٰb; a◌ّ◌ْ◌ْ◌ٰb; a◌ّ◌ْ◌ْ◌ٰb; a◌ّ◌ْ◌ْ◌ٰb; ) LATIN SMALL LETTER A, ARABIC LETTER SUPERSCRIPT ALEF, ARABIC SUKUN, ARABIC SHADDA, ARABIC SUKUN, LATIN SMALL LETTER B
+0061 0652 0670 0652 0651 0062;0061 0651 0652 0652 0670 0062;0061 0651 0652 0652 0670 0062;0061 0651 0652 0652 0670 0062;0061 0651 0652 0652 0670 0062; # (a◌ْ◌ٰ◌ْ◌ّb; a◌ّ◌ْ◌ْ◌ٰb; a◌ّ◌ْ◌ْ◌ٰb; a◌ّ◌ْ◌ْ◌ٰb; a◌ّ◌ْ◌ْ◌ٰb; ) LATIN SMALL LETTER A, ARABIC SUKUN, ARABIC LETTER SUPERSCRIPT ALEF, ARABIC SUKUN, ARABIC SHADDA, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0653 0062;00E0 05AE 0653 0315 0062;0061 05AE 0300 0653 0315 0062;00E0 05AE 0653 0315 0062;0061 05AE 0300 0653 0315 0062; # (a◌̕◌̀◌֮◌ٓb; à◌֮◌ٓ◌̕b; a◌֮◌̀◌ٓ◌̕b; à◌֮◌ٓ◌̕b; a◌֮◌̀◌ٓ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC MADDAH ABOVE, LATIN SMALL LETTER B
+0061 0653 0315 0300 05AE 0062;0061 05AE 0653 0300 0315 0062;0061 05AE 0653 0300 0315 0062;0061 05AE 0653 0300 0315 0062;0061 05AE 0653 0300 0315 0062; # (a◌ٓ◌̕◌̀◌֮b; a◌֮◌ٓ◌̀◌̕b; a◌֮◌ٓ◌̀◌̕b; a◌֮◌ٓ◌̀◌̕b; a◌֮◌ٓ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC MADDAH ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0654 0062;00E0 05AE 0654 0315 0062;0061 05AE 0300 0654 0315 0062;00E0 05AE 0654 0315 0062;0061 05AE 0300 0654 0315 0062; # (a◌̕◌̀◌֮◌ٔb; à◌֮◌ٔ◌̕b; a◌֮◌̀◌ٔ◌̕b; à◌֮◌ٔ◌̕b; a◌֮◌̀◌ٔ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC HAMZA ABOVE, LATIN SMALL LETTER B
+0061 0654 0315 0300 05AE 0062;0061 05AE 0654 0300 0315 0062;0061 05AE 0654 0300 0315 0062;0061 05AE 0654 0300 0315 0062;0061 05AE 0654 0300 0315 0062; # (a◌ٔ◌̕◌̀◌֮b; a◌֮◌ٔ◌̀◌̕b; a◌֮◌ٔ◌̀◌̕b; a◌֮◌ٔ◌̀◌̕b; a◌֮◌ٔ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC HAMZA ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 0655 0062;0061 302A 0316 0655 059A 0062;0061 302A 0316 0655 059A 0062;0061 302A 0316 0655 059A 0062;0061 302A 0316 0655 059A 0062; # (a◌֚◌̖◌〪◌ٕb; a◌〪◌̖◌ٕ◌֚b; a◌〪◌̖◌ٕ◌֚b; a◌〪◌̖◌ٕ◌֚b; a◌〪◌̖◌ٕ◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, ARABIC HAMZA BELOW, LATIN SMALL LETTER B
+0061 0655 059A 0316 302A 0062;0061 302A 0655 0316 059A 0062;0061 302A 0655 0316 059A 0062;0061 302A 0655 0316 059A 0062;0061 302A 0655 0316 059A 0062; # (a◌ٕ◌֚◌̖◌〪b; a◌〪◌ٕ◌̖◌֚b; a◌〪◌ٕ◌̖◌֚b; a◌〪◌ٕ◌̖◌֚b; a◌〪◌ٕ◌̖◌֚b; ) LATIN SMALL LETTER A, ARABIC HAMZA BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0656 0062;0061 302A 0316 0656 059A 0062;0061 302A 0316 0656 059A 0062;0061 302A 0316 0656 059A 0062;0061 302A 0316 0656 059A 0062; # (a◌֚◌̖◌〪◌ٖb; a◌〪◌̖◌ٖ◌֚b; a◌〪◌̖◌ٖ◌֚b; a◌〪◌̖◌ٖ◌֚b; a◌〪◌̖◌ٖ◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, ARABIC SUBSCRIPT ALEF, LATIN SMALL LETTER B
+0061 0656 059A 0316 302A 0062;0061 302A 0656 0316 059A 0062;0061 302A 0656 0316 059A 0062;0061 302A 0656 0316 059A 0062;0061 302A 0656 0316 059A 0062; # (a◌ٖ◌֚◌̖◌〪b; a◌〪◌ٖ◌̖◌֚b; a◌〪◌ٖ◌̖◌֚b; a◌〪◌ٖ◌̖◌֚b; a◌〪◌ٖ◌̖◌֚b; ) LATIN SMALL LETTER A, ARABIC SUBSCRIPT ALEF, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0657 0062;00E0 05AE 0657 0315 0062;0061 05AE 0300 0657 0315 0062;00E0 05AE 0657 0315 0062;0061 05AE 0300 0657 0315 0062; # (a◌̕◌̀◌֮◌ٗb; à◌֮◌ٗ◌̕b; a◌֮◌̀◌ٗ◌̕b; à◌֮◌ٗ◌̕b; a◌֮◌̀◌ٗ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC INVERTED DAMMA, LATIN SMALL LETTER B
+0061 0657 0315 0300 05AE 0062;0061 05AE 0657 0300 0315 0062;0061 05AE 0657 0300 0315 0062;0061 05AE 0657 0300 0315 0062;0061 05AE 0657 0300 0315 0062; # (a◌ٗ◌̕◌̀◌֮b; a◌֮◌ٗ◌̀◌̕b; a◌֮◌ٗ◌̀◌̕b; a◌֮◌ٗ◌̀◌̕b; a◌֮◌ٗ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC INVERTED DAMMA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0658 0062;00E0 05AE 0658 0315 0062;0061 05AE 0300 0658 0315 0062;00E0 05AE 0658 0315 0062;0061 05AE 0300 0658 0315 0062; # (a◌̕◌̀◌֮◌٘b; à◌֮◌٘◌̕b; a◌֮◌̀◌٘◌̕b; à◌֮◌٘◌̕b; a◌֮◌̀◌٘◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC MARK NOON GHUNNA, LATIN SMALL LETTER B
+0061 0658 0315 0300 05AE 0062;0061 05AE 0658 0300 0315 0062;0061 05AE 0658 0300 0315 0062;0061 05AE 0658 0300 0315 0062;0061 05AE 0658 0300 0315 0062; # (a◌٘◌̕◌̀◌֮b; a◌֮◌٘◌̀◌̕b; a◌֮◌٘◌̀◌̕b; a◌֮◌٘◌̀◌̕b; a◌֮◌٘◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC MARK NOON GHUNNA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0711 0670 0652 0670 0062;0061 0652 0670 0670 0711 0062;0061 0652 0670 0670 0711 0062;0061 0652 0670 0670 0711 0062;0061 0652 0670 0670 0711 0062; # (a◌ܑ◌ٰ◌ْ◌ٰb; a◌ْ◌ٰ◌ٰ◌ܑb; a◌ْ◌ٰ◌ٰ◌ܑb; a◌ْ◌ٰ◌ٰ◌ܑb; a◌ْ◌ٰ◌ٰ◌ܑb; ) LATIN SMALL LETTER A, SYRIAC LETTER SUPERSCRIPT ALAPH, ARABIC LETTER SUPERSCRIPT ALEF, ARABIC SUKUN, ARABIC LETTER SUPERSCRIPT ALEF, LATIN SMALL LETTER B
+0061 0670 0711 0670 0652 0062;0061 0652 0670 0670 0711 0062;0061 0652 0670 0670 0711 0062;0061 0652 0670 0670 0711 0062;0061 0652 0670 0670 0711 0062; # (a◌ٰ◌ܑ◌ٰ◌ْb; a◌ْ◌ٰ◌ٰ◌ܑb; a◌ْ◌ٰ◌ٰ◌ܑb; a◌ْ◌ٰ◌ٰ◌ܑb; a◌ْ◌ٰ◌ٰ◌ܑb; ) LATIN SMALL LETTER A, ARABIC LETTER SUPERSCRIPT ALEF, SYRIAC LETTER SUPERSCRIPT ALAPH, ARABIC LETTER SUPERSCRIPT ALEF, ARABIC SUKUN, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06D6 0062;00E0 05AE 06D6 0315 0062;0061 05AE 0300 06D6 0315 0062;00E0 05AE 06D6 0315 0062;0061 05AE 0300 06D6 0315 0062; # (a◌̕◌̀◌֮◌ۖb; à◌֮◌ۖ◌̕b; a◌֮◌̀◌ۖ◌̕b; à◌֮◌ۖ◌̕b; a◌֮◌̀◌ۖ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH LIGATURE SAD WITH LAM WITH ALEF MAKSURA, LATIN SMALL LETTER B
+0061 06D6 0315 0300 05AE 0062;0061 05AE 06D6 0300 0315 0062;0061 05AE 06D6 0300 0315 0062;0061 05AE 06D6 0300 0315 0062;0061 05AE 06D6 0300 0315 0062; # (a◌ۖ◌̕◌̀◌֮b; a◌֮◌ۖ◌̀◌̕b; a◌֮◌ۖ◌̀◌̕b; a◌֮◌ۖ◌̀◌̕b; a◌֮◌ۖ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH LIGATURE SAD WITH LAM WITH ALEF MAKSURA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06D7 0062;00E0 05AE 06D7 0315 0062;0061 05AE 0300 06D7 0315 0062;00E0 05AE 06D7 0315 0062;0061 05AE 0300 06D7 0315 0062; # (a◌̕◌̀◌֮◌ۗb; à◌֮◌ۗ◌̕b; a◌֮◌̀◌ۗ◌̕b; à◌֮◌ۗ◌̕b; a◌֮◌̀◌ۗ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH LIGATURE QAF WITH LAM WITH ALEF MAKSURA, LATIN SMALL LETTER B
+0061 06D7 0315 0300 05AE 0062;0061 05AE 06D7 0300 0315 0062;0061 05AE 06D7 0300 0315 0062;0061 05AE 06D7 0300 0315 0062;0061 05AE 06D7 0300 0315 0062; # (a◌ۗ◌̕◌̀◌֮b; a◌֮◌ۗ◌̀◌̕b; a◌֮◌ۗ◌̀◌̕b; a◌֮◌ۗ◌̀◌̕b; a◌֮◌ۗ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH LIGATURE QAF WITH LAM WITH ALEF MAKSURA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06D8 0062;00E0 05AE 06D8 0315 0062;0061 05AE 0300 06D8 0315 0062;00E0 05AE 06D8 0315 0062;0061 05AE 0300 06D8 0315 0062; # (a◌̕◌̀◌֮◌ۘb; à◌֮◌ۘ◌̕b; a◌֮◌̀◌ۘ◌̕b; à◌֮◌ۘ◌̕b; a◌֮◌̀◌ۘ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH MEEM INITIAL FORM, LATIN SMALL LETTER B
+0061 06D8 0315 0300 05AE 0062;0061 05AE 06D8 0300 0315 0062;0061 05AE 06D8 0300 0315 0062;0061 05AE 06D8 0300 0315 0062;0061 05AE 06D8 0300 0315 0062; # (a◌ۘ◌̕◌̀◌֮b; a◌֮◌ۘ◌̀◌̕b; a◌֮◌ۘ◌̀◌̕b; a◌֮◌ۘ◌̀◌̕b; a◌֮◌ۘ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH MEEM INITIAL FORM, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06D9 0062;00E0 05AE 06D9 0315 0062;0061 05AE 0300 06D9 0315 0062;00E0 05AE 06D9 0315 0062;0061 05AE 0300 06D9 0315 0062; # (a◌̕◌̀◌֮◌ۙb; à◌֮◌ۙ◌̕b; a◌֮◌̀◌ۙ◌̕b; à◌֮◌ۙ◌̕b; a◌֮◌̀◌ۙ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH LAM ALEF, LATIN SMALL LETTER B
+0061 06D9 0315 0300 05AE 0062;0061 05AE 06D9 0300 0315 0062;0061 05AE 06D9 0300 0315 0062;0061 05AE 06D9 0300 0315 0062;0061 05AE 06D9 0300 0315 0062; # (a◌ۙ◌̕◌̀◌֮b; a◌֮◌ۙ◌̀◌̕b; a◌֮◌ۙ◌̀◌̕b; a◌֮◌ۙ◌̀◌̕b; a◌֮◌ۙ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH LAM ALEF, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06DA 0062;00E0 05AE 06DA 0315 0062;0061 05AE 0300 06DA 0315 0062;00E0 05AE 06DA 0315 0062;0061 05AE 0300 06DA 0315 0062; # (a◌̕◌̀◌֮◌ۚb; à◌֮◌ۚ◌̕b; a◌֮◌̀◌ۚ◌̕b; à◌֮◌ۚ◌̕b; a◌֮◌̀◌ۚ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH JEEM, LATIN SMALL LETTER B
+0061 06DA 0315 0300 05AE 0062;0061 05AE 06DA 0300 0315 0062;0061 05AE 06DA 0300 0315 0062;0061 05AE 06DA 0300 0315 0062;0061 05AE 06DA 0300 0315 0062; # (a◌ۚ◌̕◌̀◌֮b; a◌֮◌ۚ◌̀◌̕b; a◌֮◌ۚ◌̀◌̕b; a◌֮◌ۚ◌̀◌̕b; a◌֮◌ۚ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH JEEM, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06DB 0062;00E0 05AE 06DB 0315 0062;0061 05AE 0300 06DB 0315 0062;00E0 05AE 06DB 0315 0062;0061 05AE 0300 06DB 0315 0062; # (a◌̕◌̀◌֮◌ۛb; à◌֮◌ۛ◌̕b; a◌֮◌̀◌ۛ◌̕b; à◌֮◌ۛ◌̕b; a◌֮◌̀◌ۛ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH THREE DOTS, LATIN SMALL LETTER B
+0061 06DB 0315 0300 05AE 0062;0061 05AE 06DB 0300 0315 0062;0061 05AE 06DB 0300 0315 0062;0061 05AE 06DB 0300 0315 0062;0061 05AE 06DB 0300 0315 0062; # (a◌ۛ◌̕◌̀◌֮b; a◌֮◌ۛ◌̀◌̕b; a◌֮◌ۛ◌̀◌̕b; a◌֮◌ۛ◌̀◌̕b; a◌֮◌ۛ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH THREE DOTS, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06DC 0062;00E0 05AE 06DC 0315 0062;0061 05AE 0300 06DC 0315 0062;00E0 05AE 06DC 0315 0062;0061 05AE 0300 06DC 0315 0062; # (a◌̕◌̀◌֮◌ۜb; à◌֮◌ۜ◌̕b; a◌֮◌̀◌ۜ◌̕b; à◌֮◌ۜ◌̕b; a◌֮◌̀◌ۜ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH SEEN, LATIN SMALL LETTER B
+0061 06DC 0315 0300 05AE 0062;0061 05AE 06DC 0300 0315 0062;0061 05AE 06DC 0300 0315 0062;0061 05AE 06DC 0300 0315 0062;0061 05AE 06DC 0300 0315 0062; # (a◌ۜ◌̕◌̀◌֮b; a◌֮◌ۜ◌̀◌̕b; a◌֮◌ۜ◌̀◌̕b; a◌֮◌ۜ◌̀◌̕b; a◌֮◌ۜ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH SEEN, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06DF 0062;00E0 05AE 06DF 0315 0062;0061 05AE 0300 06DF 0315 0062;00E0 05AE 06DF 0315 0062;0061 05AE 0300 06DF 0315 0062; # (a◌̕◌̀◌֮◌۟b; à◌֮◌۟◌̕b; a◌֮◌̀◌۟◌̕b; à◌֮◌۟◌̕b; a◌֮◌̀◌۟◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH ROUNDED ZERO, LATIN SMALL LETTER B
+0061 06DF 0315 0300 05AE 0062;0061 05AE 06DF 0300 0315 0062;0061 05AE 06DF 0300 0315 0062;0061 05AE 06DF 0300 0315 0062;0061 05AE 06DF 0300 0315 0062; # (a◌۟◌̕◌̀◌֮b; a◌֮◌۟◌̀◌̕b; a◌֮◌۟◌̀◌̕b; a◌֮◌۟◌̀◌̕b; a◌֮◌۟◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH ROUNDED ZERO, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06E0 0062;00E0 05AE 06E0 0315 0062;0061 05AE 0300 06E0 0315 0062;00E0 05AE 06E0 0315 0062;0061 05AE 0300 06E0 0315 0062; # (a◌̕◌̀◌֮◌۠b; à◌֮◌۠◌̕b; a◌֮◌̀◌۠◌̕b; à◌֮◌۠◌̕b; a◌֮◌̀◌۠◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH UPRIGHT RECTANGULAR ZERO, LATIN SMALL LETTER B
+0061 06E0 0315 0300 05AE 0062;0061 05AE 06E0 0300 0315 0062;0061 05AE 06E0 0300 0315 0062;0061 05AE 06E0 0300 0315 0062;0061 05AE 06E0 0300 0315 0062; # (a◌۠◌̕◌̀◌֮b; a◌֮◌۠◌̀◌̕b; a◌֮◌۠◌̀◌̕b; a◌֮◌۠◌̀◌̕b; a◌֮◌۠◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH UPRIGHT RECTANGULAR ZERO, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06E1 0062;00E0 05AE 06E1 0315 0062;0061 05AE 0300 06E1 0315 0062;00E0 05AE 06E1 0315 0062;0061 05AE 0300 06E1 0315 0062; # (a◌̕◌̀◌֮◌ۡb; à◌֮◌ۡ◌̕b; a◌֮◌̀◌ۡ◌̕b; à◌֮◌ۡ◌̕b; a◌֮◌̀◌ۡ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH DOTLESS HEAD OF KHAH, LATIN SMALL LETTER B
+0061 06E1 0315 0300 05AE 0062;0061 05AE 06E1 0300 0315 0062;0061 05AE 06E1 0300 0315 0062;0061 05AE 06E1 0300 0315 0062;0061 05AE 06E1 0300 0315 0062; # (a◌ۡ◌̕◌̀◌֮b; a◌֮◌ۡ◌̀◌̕b; a◌֮◌ۡ◌̀◌̕b; a◌֮◌ۡ◌̀◌̕b; a◌֮◌ۡ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH DOTLESS HEAD OF KHAH, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06E2 0062;00E0 05AE 06E2 0315 0062;0061 05AE 0300 06E2 0315 0062;00E0 05AE 06E2 0315 0062;0061 05AE 0300 06E2 0315 0062; # (a◌̕◌̀◌֮◌ۢb; à◌֮◌ۢ◌̕b; a◌֮◌̀◌ۢ◌̕b; à◌֮◌ۢ◌̕b; a◌֮◌̀◌ۢ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH MEEM ISOLATED FORM, LATIN SMALL LETTER B
+0061 06E2 0315 0300 05AE 0062;0061 05AE 06E2 0300 0315 0062;0061 05AE 06E2 0300 0315 0062;0061 05AE 06E2 0300 0315 0062;0061 05AE 06E2 0300 0315 0062; # (a◌ۢ◌̕◌̀◌֮b; a◌֮◌ۢ◌̀◌̕b; a◌֮◌ۢ◌̀◌̕b; a◌֮◌ۢ◌̀◌̕b; a◌֮◌ۢ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH MEEM ISOLATED FORM, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 06E3 0062;0061 302A 0316 06E3 059A 0062;0061 302A 0316 06E3 059A 0062;0061 302A 0316 06E3 059A 0062;0061 302A 0316 06E3 059A 0062; # (a◌֚◌̖◌〪◌ۣb; a◌〪◌̖◌ۣ◌֚b; a◌〪◌̖◌ۣ◌֚b; a◌〪◌̖◌ۣ◌֚b; a◌〪◌̖◌ۣ◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, ARABIC SMALL LOW SEEN, LATIN SMALL LETTER B
+0061 06E3 059A 0316 302A 0062;0061 302A 06E3 0316 059A 0062;0061 302A 06E3 0316 059A 0062;0061 302A 06E3 0316 059A 0062;0061 302A 06E3 0316 059A 0062; # (a◌ۣ◌֚◌̖◌〪b; a◌〪◌ۣ◌̖◌֚b; a◌〪◌ۣ◌̖◌֚b; a◌〪◌ۣ◌̖◌֚b; a◌〪◌ۣ◌̖◌֚b; ) LATIN SMALL LETTER A, ARABIC SMALL LOW SEEN, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06E4 0062;00E0 05AE 06E4 0315 0062;0061 05AE 0300 06E4 0315 0062;00E0 05AE 06E4 0315 0062;0061 05AE 0300 06E4 0315 0062; # (a◌̕◌̀◌֮◌ۤb; à◌֮◌ۤ◌̕b; a◌֮◌̀◌ۤ◌̕b; à◌֮◌ۤ◌̕b; a◌֮◌̀◌ۤ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH MADDA, LATIN SMALL LETTER B
+0061 06E4 0315 0300 05AE 0062;0061 05AE 06E4 0300 0315 0062;0061 05AE 06E4 0300 0315 0062;0061 05AE 06E4 0300 0315 0062;0061 05AE 06E4 0300 0315 0062; # (a◌ۤ◌̕◌̀◌֮b; a◌֮◌ۤ◌̀◌̕b; a◌֮◌ۤ◌̀◌̕b; a◌֮◌ۤ◌̀◌̕b; a◌֮◌ۤ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH MADDA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06E7 0062;00E0 05AE 06E7 0315 0062;0061 05AE 0300 06E7 0315 0062;00E0 05AE 06E7 0315 0062;0061 05AE 0300 06E7 0315 0062; # (a◌̕◌̀◌֮◌ۧb; à◌֮◌ۧ◌̕b; a◌֮◌̀◌ۧ◌̕b; à◌֮◌ۧ◌̕b; a◌֮◌̀◌ۧ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH YEH, LATIN SMALL LETTER B
+0061 06E7 0315 0300 05AE 0062;0061 05AE 06E7 0300 0315 0062;0061 05AE 06E7 0300 0315 0062;0061 05AE 06E7 0300 0315 0062;0061 05AE 06E7 0300 0315 0062; # (a◌ۧ◌̕◌̀◌֮b; a◌֮◌ۧ◌̀◌̕b; a◌֮◌ۧ◌̀◌̕b; a◌֮◌ۧ◌̀◌̕b; a◌֮◌ۧ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH YEH, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06E8 0062;00E0 05AE 06E8 0315 0062;0061 05AE 0300 06E8 0315 0062;00E0 05AE 06E8 0315 0062;0061 05AE 0300 06E8 0315 0062; # (a◌̕◌̀◌֮◌ۨb; à◌֮◌ۨ◌̕b; a◌֮◌̀◌ۨ◌̕b; à◌֮◌ۨ◌̕b; a◌֮◌̀◌ۨ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC SMALL HIGH NOON, LATIN SMALL LETTER B
+0061 06E8 0315 0300 05AE 0062;0061 05AE 06E8 0300 0315 0062;0061 05AE 06E8 0300 0315 0062;0061 05AE 06E8 0300 0315 0062;0061 05AE 06E8 0300 0315 0062; # (a◌ۨ◌̕◌̀◌֮b; a◌֮◌ۨ◌̀◌̕b; a◌֮◌ۨ◌̀◌̕b; a◌֮◌ۨ◌̀◌̕b; a◌֮◌ۨ◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC SMALL HIGH NOON, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 06EA 0062;0061 302A 0316 06EA 059A 0062;0061 302A 0316 06EA 059A 0062;0061 302A 0316 06EA 059A 0062;0061 302A 0316 06EA 059A 0062; # (a◌֚◌̖◌〪◌۪b; a◌〪◌̖◌۪◌֚b; a◌〪◌̖◌۪◌֚b; a◌〪◌̖◌۪◌֚b; a◌〪◌̖◌۪◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, ARABIC EMPTY CENTRE LOW STOP, LATIN SMALL LETTER B
+0061 06EA 059A 0316 302A 0062;0061 302A 06EA 0316 059A 0062;0061 302A 06EA 0316 059A 0062;0061 302A 06EA 0316 059A 0062;0061 302A 06EA 0316 059A 0062; # (a◌۪◌֚◌̖◌〪b; a◌〪◌۪◌̖◌֚b; a◌〪◌۪◌̖◌֚b; a◌〪◌۪◌̖◌֚b; a◌〪◌۪◌̖◌֚b; ) LATIN SMALL LETTER A, ARABIC EMPTY CENTRE LOW STOP, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06EB 0062;00E0 05AE 06EB 0315 0062;0061 05AE 0300 06EB 0315 0062;00E0 05AE 06EB 0315 0062;0061 05AE 0300 06EB 0315 0062; # (a◌̕◌̀◌֮◌۫b; à◌֮◌۫◌̕b; a◌֮◌̀◌۫◌̕b; à◌֮◌۫◌̕b; a◌֮◌̀◌۫◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC EMPTY CENTRE HIGH STOP, LATIN SMALL LETTER B
+0061 06EB 0315 0300 05AE 0062;0061 05AE 06EB 0300 0315 0062;0061 05AE 06EB 0300 0315 0062;0061 05AE 06EB 0300 0315 0062;0061 05AE 06EB 0300 0315 0062; # (a◌۫◌̕◌̀◌֮b; a◌֮◌۫◌̀◌̕b; a◌֮◌۫◌̀◌̕b; a◌֮◌۫◌̀◌̕b; a◌֮◌۫◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC EMPTY CENTRE HIGH STOP, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 06EC 0062;00E0 05AE 06EC 0315 0062;0061 05AE 0300 06EC 0315 0062;00E0 05AE 06EC 0315 0062;0061 05AE 0300 06EC 0315 0062; # (a◌̕◌̀◌֮◌۬b; à◌֮◌۬◌̕b; a◌֮◌̀◌۬◌̕b; à◌֮◌۬◌̕b; a◌֮◌̀◌۬◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, ARABIC ROUNDED HIGH STOP WITH FILLED CENTRE, LATIN SMALL LETTER B
+0061 06EC 0315 0300 05AE 0062;0061 05AE 06EC 0300 0315 0062;0061 05AE 06EC 0300 0315 0062;0061 05AE 06EC 0300 0315 0062;0061 05AE 06EC 0300 0315 0062; # (a◌۬◌̕◌̀◌֮b; a◌֮◌۬◌̀◌̕b; a◌֮◌۬◌̀◌̕b; a◌֮◌۬◌̀◌̕b; a◌֮◌۬◌̀◌̕b; ) LATIN SMALL LETTER A, ARABIC ROUNDED HIGH STOP WITH FILLED CENTRE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 06ED 0062;0061 302A 0316 06ED 059A 0062;0061 302A 0316 06ED 059A 0062;0061 302A 0316 06ED 059A 0062;0061 302A 0316 06ED 059A 0062; # (a◌֚◌̖◌〪◌ۭb; a◌〪◌̖◌ۭ◌֚b; a◌〪◌̖◌ۭ◌֚b; a◌〪◌̖◌ۭ◌֚b; a◌〪◌̖◌ۭ◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, ARABIC SMALL LOW MEEM, LATIN SMALL LETTER B
+0061 06ED 059A 0316 302A 0062;0061 302A 06ED 0316 059A 0062;0061 302A 06ED 0316 059A 0062;0061 302A 06ED 0316 059A 0062;0061 302A 06ED 0316 059A 0062; # (a◌ۭ◌֚◌̖◌〪b; a◌〪◌ۭ◌̖◌֚b; a◌〪◌ۭ◌̖◌֚b; a◌〪◌ۭ◌̖◌֚b; a◌〪◌ۭ◌̖◌֚b; ) LATIN SMALL LETTER A, ARABIC SMALL LOW MEEM, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0C55 0711 0670 0711 0062;0061 0670 0711 0711 0C55 0062;0061 0670 0711 0711 0C55 0062;0061 0670 0711 0711 0C55 0062;0061 0670 0711 0711 0C55 0062; # (a◌ౕ◌ܑ◌ٰ◌ܑb; a◌ٰ◌ܑ◌ܑ◌ౕb; a◌ٰ◌ܑ◌ܑ◌ౕb; a◌ٰ◌ܑ◌ܑ◌ౕb; a◌ٰ◌ܑ◌ܑ◌ౕb; ) LATIN SMALL LETTER A, TELUGU LENGTH MARK, SYRIAC LETTER SUPERSCRIPT ALAPH, ARABIC LETTER SUPERSCRIPT ALEF, SYRIAC LETTER SUPERSCRIPT ALAPH, LATIN SMALL LETTER B
+0061 0711 0C55 0711 0670 0062;0061 0670 0711 0711 0C55 0062;0061 0670 0711 0711 0C55 0062;0061 0670 0711 0711 0C55 0062;0061 0670 0711 0711 0C55 0062; # (a◌ܑ◌ౕ◌ܑ◌ٰb; a◌ٰ◌ܑ◌ܑ◌ౕb; a◌ٰ◌ܑ◌ܑ◌ౕb; a◌ٰ◌ܑ◌ܑ◌ౕb; a◌ٰ◌ܑ◌ܑ◌ౕb; ) LATIN SMALL LETTER A, SYRIAC LETTER SUPERSCRIPT ALAPH, TELUGU LENGTH MARK, SYRIAC LETTER SUPERSCRIPT ALAPH, ARABIC LETTER SUPERSCRIPT ALEF, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0730 0062;00E0 05AE 0730 0315 0062;0061 05AE 0300 0730 0315 0062;00E0 05AE 0730 0315 0062;0061 05AE 0300 0730 0315 0062; # (a◌̕◌̀◌֮◌ܰb; à◌֮◌ܰ◌̕b; a◌֮◌̀◌ܰ◌̕b; à◌֮◌ܰ◌̕b; a◌֮◌̀◌ܰ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC PTHAHA ABOVE, LATIN SMALL LETTER B
+0061 0730 0315 0300 05AE 0062;0061 05AE 0730 0300 0315 0062;0061 05AE 0730 0300 0315 0062;0061 05AE 0730 0300 0315 0062;0061 05AE 0730 0300 0315 0062; # (a◌ܰ◌̕◌̀◌֮b; a◌֮◌ܰ◌̀◌̕b; a◌֮◌ܰ◌̀◌̕b; a◌֮◌ܰ◌̀◌̕b; a◌֮◌ܰ◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC PTHAHA ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 0731 0062;0061 302A 0316 0731 059A 0062;0061 302A 0316 0731 059A 0062;0061 302A 0316 0731 059A 0062;0061 302A 0316 0731 059A 0062; # (a◌֚◌̖◌〪◌ܱb; a◌〪◌̖◌ܱ◌֚b; a◌〪◌̖◌ܱ◌֚b; a◌〪◌̖◌ܱ◌֚b; a◌〪◌̖◌ܱ◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, SYRIAC PTHAHA BELOW, LATIN SMALL LETTER B
+0061 0731 059A 0316 302A 0062;0061 302A 0731 0316 059A 0062;0061 302A 0731 0316 059A 0062;0061 302A 0731 0316 059A 0062;0061 302A 0731 0316 059A 0062; # (a◌ܱ◌֚◌̖◌〪b; a◌〪◌ܱ◌̖◌֚b; a◌〪◌ܱ◌̖◌֚b; a◌〪◌ܱ◌̖◌֚b; a◌〪◌ܱ◌̖◌֚b; ) LATIN SMALL LETTER A, SYRIAC PTHAHA BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0732 0062;00E0 05AE 0732 0315 0062;0061 05AE 0300 0732 0315 0062;00E0 05AE 0732 0315 0062;0061 05AE 0300 0732 0315 0062; # (a◌̕◌̀◌֮◌ܲb; à◌֮◌ܲ◌̕b; a◌֮◌̀◌ܲ◌̕b; à◌֮◌ܲ◌̕b; a◌֮◌̀◌ܲ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC PTHAHA DOTTED, LATIN SMALL LETTER B
+0061 0732 0315 0300 05AE 0062;0061 05AE 0732 0300 0315 0062;0061 05AE 0732 0300 0315 0062;0061 05AE 0732 0300 0315 0062;0061 05AE 0732 0300 0315 0062; # (a◌ܲ◌̕◌̀◌֮b; a◌֮◌ܲ◌̀◌̕b; a◌֮◌ܲ◌̀◌̕b; a◌֮◌ܲ◌̀◌̕b; a◌֮◌ܲ◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC PTHAHA DOTTED, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0733 0062;00E0 05AE 0733 0315 0062;0061 05AE 0300 0733 0315 0062;00E0 05AE 0733 0315 0062;0061 05AE 0300 0733 0315 0062; # (a◌̕◌̀◌֮◌ܳb; à◌֮◌ܳ◌̕b; a◌֮◌̀◌ܳ◌̕b; à◌֮◌ܳ◌̕b; a◌֮◌̀◌ܳ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC ZQAPHA ABOVE, LATIN SMALL LETTER B
+0061 0733 0315 0300 05AE 0062;0061 05AE 0733 0300 0315 0062;0061 05AE 0733 0300 0315 0062;0061 05AE 0733 0300 0315 0062;0061 05AE 0733 0300 0315 0062; # (a◌ܳ◌̕◌̀◌֮b; a◌֮◌ܳ◌̀◌̕b; a◌֮◌ܳ◌̀◌̕b; a◌֮◌ܳ◌̀◌̕b; a◌֮◌ܳ◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC ZQAPHA ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 0734 0062;0061 302A 0316 0734 059A 0062;0061 302A 0316 0734 059A 0062;0061 302A 0316 0734 059A 0062;0061 302A 0316 0734 059A 0062; # (a◌֚◌̖◌〪◌ܴb; a◌〪◌̖◌ܴ◌֚b; a◌〪◌̖◌ܴ◌֚b; a◌〪◌̖◌ܴ◌֚b; a◌〪◌̖◌ܴ◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, SYRIAC ZQAPHA BELOW, LATIN SMALL LETTER B
+0061 0734 059A 0316 302A 0062;0061 302A 0734 0316 059A 0062;0061 302A 0734 0316 059A 0062;0061 302A 0734 0316 059A 0062;0061 302A 0734 0316 059A 0062; # (a◌ܴ◌֚◌̖◌〪b; a◌〪◌ܴ◌̖◌֚b; a◌〪◌ܴ◌̖◌֚b; a◌〪◌ܴ◌̖◌֚b; a◌〪◌ܴ◌̖◌֚b; ) LATIN SMALL LETTER A, SYRIAC ZQAPHA BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0735 0062;00E0 05AE 0735 0315 0062;0061 05AE 0300 0735 0315 0062;00E0 05AE 0735 0315 0062;0061 05AE 0300 0735 0315 0062; # (a◌̕◌̀◌֮◌ܵb; à◌֮◌ܵ◌̕b; a◌֮◌̀◌ܵ◌̕b; à◌֮◌ܵ◌̕b; a◌֮◌̀◌ܵ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC ZQAPHA DOTTED, LATIN SMALL LETTER B
+0061 0735 0315 0300 05AE 0062;0061 05AE 0735 0300 0315 0062;0061 05AE 0735 0300 0315 0062;0061 05AE 0735 0300 0315 0062;0061 05AE 0735 0300 0315 0062; # (a◌ܵ◌̕◌̀◌֮b; a◌֮◌ܵ◌̀◌̕b; a◌֮◌ܵ◌̀◌̕b; a◌֮◌ܵ◌̀◌̕b; a◌֮◌ܵ◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC ZQAPHA DOTTED, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0736 0062;00E0 05AE 0736 0315 0062;0061 05AE 0300 0736 0315 0062;00E0 05AE 0736 0315 0062;0061 05AE 0300 0736 0315 0062; # (a◌̕◌̀◌֮◌ܶb; à◌֮◌ܶ◌̕b; a◌֮◌̀◌ܶ◌̕b; à◌֮◌ܶ◌̕b; a◌֮◌̀◌ܶ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC RBASA ABOVE, LATIN SMALL LETTER B
+0061 0736 0315 0300 05AE 0062;0061 05AE 0736 0300 0315 0062;0061 05AE 0736 0300 0315 0062;0061 05AE 0736 0300 0315 0062;0061 05AE 0736 0300 0315 0062; # (a◌ܶ◌̕◌̀◌֮b; a◌֮◌ܶ◌̀◌̕b; a◌֮◌ܶ◌̀◌̕b; a◌֮◌ܶ◌̀◌̕b; a◌֮◌ܶ◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC RBASA ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 0737 0062;0061 302A 0316 0737 059A 0062;0061 302A 0316 0737 059A 0062;0061 302A 0316 0737 059A 0062;0061 302A 0316 0737 059A 0062; # (a◌֚◌̖◌〪◌ܷb; a◌〪◌̖◌ܷ◌֚b; a◌〪◌̖◌ܷ◌֚b; a◌〪◌̖◌ܷ◌֚b; a◌〪◌̖◌ܷ◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, SYRIAC RBASA BELOW, LATIN SMALL LETTER B
+0061 0737 059A 0316 302A 0062;0061 302A 0737 0316 059A 0062;0061 302A 0737 0316 059A 0062;0061 302A 0737 0316 059A 0062;0061 302A 0737 0316 059A 0062; # (a◌ܷ◌֚◌̖◌〪b; a◌〪◌ܷ◌̖◌֚b; a◌〪◌ܷ◌̖◌֚b; a◌〪◌ܷ◌̖◌֚b; a◌〪◌ܷ◌̖◌֚b; ) LATIN SMALL LETTER A, SYRIAC RBASA BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0738 0062;0061 302A 0316 0738 059A 0062;0061 302A 0316 0738 059A 0062;0061 302A 0316 0738 059A 0062;0061 302A 0316 0738 059A 0062; # (a◌֚◌̖◌〪◌ܸb; a◌〪◌̖◌ܸ◌֚b; a◌〪◌̖◌ܸ◌֚b; a◌〪◌̖◌ܸ◌֚b; a◌〪◌̖◌ܸ◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, SYRIAC DOTTED ZLAMA HORIZONTAL, LATIN SMALL LETTER B
+0061 0738 059A 0316 302A 0062;0061 302A 0738 0316 059A 0062;0061 302A 0738 0316 059A 0062;0061 302A 0738 0316 059A 0062;0061 302A 0738 0316 059A 0062; # (a◌ܸ◌֚◌̖◌〪b; a◌〪◌ܸ◌̖◌֚b; a◌〪◌ܸ◌̖◌֚b; a◌〪◌ܸ◌̖◌֚b; a◌〪◌ܸ◌̖◌֚b; ) LATIN SMALL LETTER A, SYRIAC DOTTED ZLAMA HORIZONTAL, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0739 0062;0061 302A 0316 0739 059A 0062;0061 302A 0316 0739 059A 0062;0061 302A 0316 0739 059A 0062;0061 302A 0316 0739 059A 0062; # (a◌֚◌̖◌〪◌ܹb; a◌〪◌̖◌ܹ◌֚b; a◌〪◌̖◌ܹ◌֚b; a◌〪◌̖◌ܹ◌֚b; a◌〪◌̖◌ܹ◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, SYRIAC DOTTED ZLAMA ANGULAR, LATIN SMALL LETTER B
+0061 0739 059A 0316 302A 0062;0061 302A 0739 0316 059A 0062;0061 302A 0739 0316 059A 0062;0061 302A 0739 0316 059A 0062;0061 302A 0739 0316 059A 0062; # (a◌ܹ◌֚◌̖◌〪b; a◌〪◌ܹ◌̖◌֚b; a◌〪◌ܹ◌̖◌֚b; a◌〪◌ܹ◌̖◌֚b; a◌〪◌ܹ◌̖◌֚b; ) LATIN SMALL LETTER A, SYRIAC DOTTED ZLAMA ANGULAR, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 073A 0062;00E0 05AE 073A 0315 0062;0061 05AE 0300 073A 0315 0062;00E0 05AE 073A 0315 0062;0061 05AE 0300 073A 0315 0062; # (a◌̕◌̀◌֮◌ܺb; à◌֮◌ܺ◌̕b; a◌֮◌̀◌ܺ◌̕b; à◌֮◌ܺ◌̕b; a◌֮◌̀◌ܺ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC HBASA ABOVE, LATIN SMALL LETTER B
+0061 073A 0315 0300 05AE 0062;0061 05AE 073A 0300 0315 0062;0061 05AE 073A 0300 0315 0062;0061 05AE 073A 0300 0315 0062;0061 05AE 073A 0300 0315 0062; # (a◌ܺ◌̕◌̀◌֮b; a◌֮◌ܺ◌̀◌̕b; a◌֮◌ܺ◌̀◌̕b; a◌֮◌ܺ◌̀◌̕b; a◌֮◌ܺ◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC HBASA ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 073B 0062;0061 302A 0316 073B 059A 0062;0061 302A 0316 073B 059A 0062;0061 302A 0316 073B 059A 0062;0061 302A 0316 073B 059A 0062; # (a◌֚◌̖◌〪◌ܻb; a◌〪◌̖◌ܻ◌֚b; a◌〪◌̖◌ܻ◌֚b; a◌〪◌̖◌ܻ◌֚b; a◌〪◌̖◌ܻ◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, SYRIAC HBASA BELOW, LATIN SMALL LETTER B
+0061 073B 059A 0316 302A 0062;0061 302A 073B 0316 059A 0062;0061 302A 073B 0316 059A 0062;0061 302A 073B 0316 059A 0062;0061 302A 073B 0316 059A 0062; # (a◌ܻ◌֚◌̖◌〪b; a◌〪◌ܻ◌̖◌֚b; a◌〪◌ܻ◌̖◌֚b; a◌〪◌ܻ◌̖◌֚b; a◌〪◌ܻ◌̖◌֚b; ) LATIN SMALL LETTER A, SYRIAC HBASA BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 073C 0062;0061 302A 0316 073C 059A 0062;0061 302A 0316 073C 059A 0062;0061 302A 0316 073C 059A 0062;0061 302A 0316 073C 059A 0062; # (a◌֚◌̖◌〪◌ܼb; a◌〪◌̖◌ܼ◌֚b; a◌〪◌̖◌ܼ◌֚b; a◌〪◌̖◌ܼ◌֚b; a◌〪◌̖◌ܼ◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, SYRIAC HBASA-ESASA DOTTED, LATIN SMALL LETTER B
+0061 073C 059A 0316 302A 0062;0061 302A 073C 0316 059A 0062;0061 302A 073C 0316 059A 0062;0061 302A 073C 0316 059A 0062;0061 302A 073C 0316 059A 0062; # (a◌ܼ◌֚◌̖◌〪b; a◌〪◌ܼ◌̖◌֚b; a◌〪◌ܼ◌̖◌֚b; a◌〪◌ܼ◌̖◌֚b; a◌〪◌ܼ◌̖◌֚b; ) LATIN SMALL LETTER A, SYRIAC HBASA-ESASA DOTTED, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 073D 0062;00E0 05AE 073D 0315 0062;0061 05AE 0300 073D 0315 0062;00E0 05AE 073D 0315 0062;0061 05AE 0300 073D 0315 0062; # (a◌̕◌̀◌֮◌ܽb; à◌֮◌ܽ◌̕b; a◌֮◌̀◌ܽ◌̕b; à◌֮◌ܽ◌̕b; a◌֮◌̀◌ܽ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC ESASA ABOVE, LATIN SMALL LETTER B
+0061 073D 0315 0300 05AE 0062;0061 05AE 073D 0300 0315 0062;0061 05AE 073D 0300 0315 0062;0061 05AE 073D 0300 0315 0062;0061 05AE 073D 0300 0315 0062; # (a◌ܽ◌̕◌̀◌֮b; a◌֮◌ܽ◌̀◌̕b; a◌֮◌ܽ◌̀◌̕b; a◌֮◌ܽ◌̀◌̕b; a◌֮◌ܽ◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC ESASA ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 073E 0062;0061 302A 0316 073E 059A 0062;0061 302A 0316 073E 059A 0062;0061 302A 0316 073E 059A 0062;0061 302A 0316 073E 059A 0062; # (a◌֚◌̖◌〪◌ܾb; a◌〪◌̖◌ܾ◌֚b; a◌〪◌̖◌ܾ◌֚b; a◌〪◌̖◌ܾ◌֚b; a◌〪◌̖◌ܾ◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, SYRIAC ESASA BELOW, LATIN SMALL LETTER B
+0061 073E 059A 0316 302A 0062;0061 302A 073E 0316 059A 0062;0061 302A 073E 0316 059A 0062;0061 302A 073E 0316 059A 0062;0061 302A 073E 0316 059A 0062; # (a◌ܾ◌֚◌̖◌〪b; a◌〪◌ܾ◌̖◌֚b; a◌〪◌ܾ◌̖◌֚b; a◌〪◌ܾ◌̖◌֚b; a◌〪◌ܾ◌̖◌֚b; ) LATIN SMALL LETTER A, SYRIAC ESASA BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 073F 0062;00E0 05AE 073F 0315 0062;0061 05AE 0300 073F 0315 0062;00E0 05AE 073F 0315 0062;0061 05AE 0300 073F 0315 0062; # (a◌̕◌̀◌֮◌ܿb; à◌֮◌ܿ◌̕b; a◌֮◌̀◌ܿ◌̕b; à◌֮◌ܿ◌̕b; a◌֮◌̀◌ܿ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC RWAHA, LATIN SMALL LETTER B
+0061 073F 0315 0300 05AE 0062;0061 05AE 073F 0300 0315 0062;0061 05AE 073F 0300 0315 0062;0061 05AE 073F 0300 0315 0062;0061 05AE 073F 0300 0315 0062; # (a◌ܿ◌̕◌̀◌֮b; a◌֮◌ܿ◌̀◌̕b; a◌֮◌ܿ◌̀◌̕b; a◌֮◌ܿ◌̀◌̕b; a◌֮◌ܿ◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC RWAHA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0740 0062;00E0 05AE 0740 0315 0062;0061 05AE 0300 0740 0315 0062;00E0 05AE 0740 0315 0062;0061 05AE 0300 0740 0315 0062; # (a◌̕◌̀◌֮◌݀b; à◌֮◌݀◌̕b; a◌֮◌̀◌݀◌̕b; à◌֮◌݀◌̕b; a◌֮◌̀◌݀◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC FEMININE DOT, LATIN SMALL LETTER B
+0061 0740 0315 0300 05AE 0062;0061 05AE 0740 0300 0315 0062;0061 05AE 0740 0300 0315 0062;0061 05AE 0740 0300 0315 0062;0061 05AE 0740 0300 0315 0062; # (a◌݀◌̕◌̀◌֮b; a◌֮◌݀◌̀◌̕b; a◌֮◌݀◌̀◌̕b; a◌֮◌݀◌̀◌̕b; a◌֮◌݀◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC FEMININE DOT, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0741 0062;00E0 05AE 0741 0315 0062;0061 05AE 0300 0741 0315 0062;00E0 05AE 0741 0315 0062;0061 05AE 0300 0741 0315 0062; # (a◌̕◌̀◌֮◌݁b; à◌֮◌݁◌̕b; a◌֮◌̀◌݁◌̕b; à◌֮◌݁◌̕b; a◌֮◌̀◌݁◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC QUSHSHAYA, LATIN SMALL LETTER B
+0061 0741 0315 0300 05AE 0062;0061 05AE 0741 0300 0315 0062;0061 05AE 0741 0300 0315 0062;0061 05AE 0741 0300 0315 0062;0061 05AE 0741 0300 0315 0062; # (a◌݁◌̕◌̀◌֮b; a◌֮◌݁◌̀◌̕b; a◌֮◌݁◌̀◌̕b; a◌֮◌݁◌̀◌̕b; a◌֮◌݁◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC QUSHSHAYA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 0742 0062;0061 302A 0316 0742 059A 0062;0061 302A 0316 0742 059A 0062;0061 302A 0316 0742 059A 0062;0061 302A 0316 0742 059A 0062; # (a◌֚◌̖◌〪◌݂b; a◌〪◌̖◌݂◌֚b; a◌〪◌̖◌݂◌֚b; a◌〪◌̖◌݂◌֚b; a◌〪◌̖◌݂◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, SYRIAC RUKKAKHA, LATIN SMALL LETTER B
+0061 0742 059A 0316 302A 0062;0061 302A 0742 0316 059A 0062;0061 302A 0742 0316 059A 0062;0061 302A 0742 0316 059A 0062;0061 302A 0742 0316 059A 0062; # (a◌݂◌֚◌̖◌〪b; a◌〪◌݂◌̖◌֚b; a◌〪◌݂◌̖◌֚b; a◌〪◌݂◌̖◌֚b; a◌〪◌݂◌̖◌֚b; ) LATIN SMALL LETTER A, SYRIAC RUKKAKHA, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0743 0062;00E0 05AE 0743 0315 0062;0061 05AE 0300 0743 0315 0062;00E0 05AE 0743 0315 0062;0061 05AE 0300 0743 0315 0062; # (a◌̕◌̀◌֮◌݃b; à◌֮◌݃◌̕b; a◌֮◌̀◌݃◌̕b; à◌֮◌݃◌̕b; a◌֮◌̀◌݃◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC TWO VERTICAL DOTS ABOVE, LATIN SMALL LETTER B
+0061 0743 0315 0300 05AE 0062;0061 05AE 0743 0300 0315 0062;0061 05AE 0743 0300 0315 0062;0061 05AE 0743 0300 0315 0062;0061 05AE 0743 0300 0315 0062; # (a◌݃◌̕◌̀◌֮b; a◌֮◌݃◌̀◌̕b; a◌֮◌݃◌̀◌̕b; a◌֮◌݃◌̀◌̕b; a◌֮◌݃◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC TWO VERTICAL DOTS ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 0744 0062;0061 302A 0316 0744 059A 0062;0061 302A 0316 0744 059A 0062;0061 302A 0316 0744 059A 0062;0061 302A 0316 0744 059A 0062; # (a◌֚◌̖◌〪◌݄b; a◌〪◌̖◌݄◌֚b; a◌〪◌̖◌݄◌֚b; a◌〪◌̖◌݄◌֚b; a◌〪◌̖◌݄◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, SYRIAC TWO VERTICAL DOTS BELOW, LATIN SMALL LETTER B
+0061 0744 059A 0316 302A 0062;0061 302A 0744 0316 059A 0062;0061 302A 0744 0316 059A 0062;0061 302A 0744 0316 059A 0062;0061 302A 0744 0316 059A 0062; # (a◌݄◌֚◌̖◌〪b; a◌〪◌݄◌̖◌֚b; a◌〪◌݄◌̖◌֚b; a◌〪◌݄◌̖◌֚b; a◌〪◌݄◌̖◌֚b; ) LATIN SMALL LETTER A, SYRIAC TWO VERTICAL DOTS BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0745 0062;00E0 05AE 0745 0315 0062;0061 05AE 0300 0745 0315 0062;00E0 05AE 0745 0315 0062;0061 05AE 0300 0745 0315 0062; # (a◌̕◌̀◌֮◌݅b; à◌֮◌݅◌̕b; a◌֮◌̀◌݅◌̕b; à◌֮◌݅◌̕b; a◌֮◌̀◌݅◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC THREE DOTS ABOVE, LATIN SMALL LETTER B
+0061 0745 0315 0300 05AE 0062;0061 05AE 0745 0300 0315 0062;0061 05AE 0745 0300 0315 0062;0061 05AE 0745 0300 0315 0062;0061 05AE 0745 0300 0315 0062; # (a◌݅◌̕◌̀◌֮b; a◌֮◌݅◌̀◌̕b; a◌֮◌݅◌̀◌̕b; a◌֮◌݅◌̀◌̕b; a◌֮◌݅◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC THREE DOTS ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 0746 0062;0061 302A 0316 0746 059A 0062;0061 302A 0316 0746 059A 0062;0061 302A 0316 0746 059A 0062;0061 302A 0316 0746 059A 0062; # (a◌֚◌̖◌〪◌݆b; a◌〪◌̖◌݆◌֚b; a◌〪◌̖◌݆◌֚b; a◌〪◌̖◌݆◌֚b; a◌〪◌̖◌݆◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, SYRIAC THREE DOTS BELOW, LATIN SMALL LETTER B
+0061 0746 059A 0316 302A 0062;0061 302A 0746 0316 059A 0062;0061 302A 0746 0316 059A 0062;0061 302A 0746 0316 059A 0062;0061 302A 0746 0316 059A 0062; # (a◌݆◌֚◌̖◌〪b; a◌〪◌݆◌̖◌֚b; a◌〪◌݆◌̖◌֚b; a◌〪◌݆◌̖◌֚b; a◌〪◌݆◌̖◌֚b; ) LATIN SMALL LETTER A, SYRIAC THREE DOTS BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0747 0062;00E0 05AE 0747 0315 0062;0061 05AE 0300 0747 0315 0062;00E0 05AE 0747 0315 0062;0061 05AE 0300 0747 0315 0062; # (a◌̕◌̀◌֮◌݇b; à◌֮◌݇◌̕b; a◌֮◌̀◌݇◌̕b; à◌֮◌݇◌̕b; a◌֮◌̀◌݇◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC OBLIQUE LINE ABOVE, LATIN SMALL LETTER B
+0061 0747 0315 0300 05AE 0062;0061 05AE 0747 0300 0315 0062;0061 05AE 0747 0300 0315 0062;0061 05AE 0747 0300 0315 0062;0061 05AE 0747 0300 0315 0062; # (a◌݇◌̕◌̀◌֮b; a◌֮◌݇◌̀◌̕b; a◌֮◌݇◌̀◌̕b; a◌֮◌݇◌̀◌̕b; a◌֮◌݇◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC OBLIQUE LINE ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 0748 0062;0061 302A 0316 0748 059A 0062;0061 302A 0316 0748 059A 0062;0061 302A 0316 0748 059A 0062;0061 302A 0316 0748 059A 0062; # (a◌֚◌̖◌〪◌݈b; a◌〪◌̖◌݈◌֚b; a◌〪◌̖◌݈◌֚b; a◌〪◌̖◌݈◌֚b; a◌〪◌̖◌݈◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, SYRIAC OBLIQUE LINE BELOW, LATIN SMALL LETTER B
+0061 0748 059A 0316 302A 0062;0061 302A 0748 0316 059A 0062;0061 302A 0748 0316 059A 0062;0061 302A 0748 0316 059A 0062;0061 302A 0748 0316 059A 0062; # (a◌݈◌֚◌̖◌〪b; a◌〪◌݈◌̖◌֚b; a◌〪◌݈◌̖◌֚b; a◌〪◌݈◌̖◌֚b; a◌〪◌݈◌̖◌֚b; ) LATIN SMALL LETTER A, SYRIAC OBLIQUE LINE BELOW, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0749 0062;00E0 05AE 0749 0315 0062;0061 05AE 0300 0749 0315 0062;00E0 05AE 0749 0315 0062;0061 05AE 0300 0749 0315 0062; # (a◌̕◌̀◌֮◌݉b; à◌֮◌݉◌̕b; a◌֮◌̀◌݉◌̕b; à◌֮◌݉◌̕b; a◌֮◌̀◌݉◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC MUSIC, LATIN SMALL LETTER B
+0061 0749 0315 0300 05AE 0062;0061 05AE 0749 0300 0315 0062;0061 05AE 0749 0300 0315 0062;0061 05AE 0749 0300 0315 0062;0061 05AE 0749 0300 0315 0062; # (a◌݉◌̕◌̀◌֮b; a◌֮◌݉◌̀◌̕b; a◌֮◌݉◌̀◌̕b; a◌֮◌݉◌̀◌̕b; a◌֮◌݉◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC MUSIC, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 074A 0062;00E0 05AE 074A 0315 0062;0061 05AE 0300 074A 0315 0062;00E0 05AE 074A 0315 0062;0061 05AE 0300 074A 0315 0062; # (a◌̕◌̀◌֮◌݊b; à◌֮◌݊◌̕b; a◌֮◌̀◌݊◌̕b; à◌֮◌݊◌̕b; a◌֮◌̀◌݊◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, SYRIAC BARREKH, LATIN SMALL LETTER B
+0061 074A 0315 0300 05AE 0062;0061 05AE 074A 0300 0315 0062;0061 05AE 074A 0300 0315 0062;0061 05AE 074A 0300 0315 0062;0061 05AE 074A 0300 0315 0062; # (a◌݊◌̕◌̀◌֮b; a◌֮◌݊◌̀◌̕b; a◌֮◌݊◌̀◌̕b; a◌֮◌݊◌̀◌̕b; a◌֮◌݊◌̀◌̕b; ) LATIN SMALL LETTER A, SYRIAC BARREKH, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 3099 093C 0334 093C 0062;0061 0334 093C 093C 3099 0062;0061 0334 093C 093C 3099 0062;0061 0334 093C 093C 3099 0062;0061 0334 093C 093C 3099 0062; # (a◌゙◌़◌̴◌़b; a◌̴◌़◌़◌゙b; a◌̴◌़◌़◌゙b; a◌̴◌़◌़◌゙b; a◌̴◌़◌़◌゙b; ) LATIN SMALL LETTER A, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, DEVANAGARI SIGN NUKTA, LATIN SMALL LETTER B
+0061 093C 3099 093C 0334 0062;0061 0334 093C 093C 3099 0062;0061 0334 093C 093C 3099 0062;0061 0334 093C 093C 3099 0062;0061 0334 093C 093C 3099 0062; # (a◌़◌゙◌़◌̴b; a◌̴◌़◌़◌゙b; a◌̴◌़◌़◌゙b; a◌̴◌़◌़◌゙b; a◌̴◌़◌़◌゙b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 05B0 094D 3099 094D 0062;0061 3099 094D 094D 05B0 0062;0061 3099 094D 094D 05B0 0062;0061 3099 094D 094D 05B0 0062;0061 3099 094D 094D 05B0 0062; # (a◌ְ◌्◌゙◌्b; a◌゙◌्◌्◌ְb; a◌゙◌्◌्◌ְb; a◌゙◌्◌्◌ְb; a◌゙◌्◌्◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN VIRAMA, LATIN SMALL LETTER B
+0061 094D 05B0 094D 3099 0062;0061 3099 094D 094D 05B0 0062;0061 3099 094D 094D 05B0 0062;0061 3099 094D 094D 05B0 0062;0061 3099 094D 094D 05B0 0062; # (a◌्◌ְ◌्◌゙b; a◌゙◌्◌्◌ְb; a◌゙◌्◌्◌ְb; a◌゙◌्◌्◌ְb; a◌゙◌्◌्◌ְb; ) LATIN SMALL LETTER A, DEVANAGARI SIGN VIRAMA, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0951 0062;00E0 05AE 0951 0315 0062;0061 05AE 0300 0951 0315 0062;00E0 05AE 0951 0315 0062;0061 05AE 0300 0951 0315 0062; # (a◌̕◌̀◌֮◌॑b; à◌֮◌॑◌̕b; a◌֮◌̀◌॑◌̕b; à◌֮◌॑◌̕b; a◌֮◌̀◌॑◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, DEVANAGARI STRESS SIGN UDATTA, LATIN SMALL LETTER B
+0061 0951 0315 0300 05AE 0062;0061 05AE 0951 0300 0315 0062;0061 05AE 0951 0300 0315 0062;0061 05AE 0951 0300 0315 0062;0061 05AE 0951 0300 0315 0062; # (a◌॑◌̕◌̀◌֮b; a◌֮◌॑◌̀◌̕b; a◌֮◌॑◌̀◌̕b; a◌֮◌॑◌̀◌̕b; a◌֮◌॑◌̀◌̕b; ) LATIN SMALL LETTER A, DEVANAGARI STRESS SIGN UDATTA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 0952 0062;0061 302A 0316 0952 059A 0062;0061 302A 0316 0952 059A 0062;0061 302A 0316 0952 059A 0062;0061 302A 0316 0952 059A 0062; # (a◌֚◌̖◌〪◌॒b; a◌〪◌̖◌॒◌֚b; a◌〪◌̖◌॒◌֚b; a◌〪◌̖◌॒◌֚b; a◌〪◌̖◌॒◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, DEVANAGARI STRESS SIGN ANUDATTA, LATIN SMALL LETTER B
+0061 0952 059A 0316 302A 0062;0061 302A 0952 0316 059A 0062;0061 302A 0952 0316 059A 0062;0061 302A 0952 0316 059A 0062;0061 302A 0952 0316 059A 0062; # (a◌॒◌֚◌̖◌〪b; a◌〪◌॒◌̖◌֚b; a◌〪◌॒◌̖◌֚b; a◌〪◌॒◌̖◌֚b; a◌〪◌॒◌̖◌֚b; ) LATIN SMALL LETTER A, DEVANAGARI STRESS SIGN ANUDATTA, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0953 0062;00E0 05AE 0953 0315 0062;0061 05AE 0300 0953 0315 0062;00E0 05AE 0953 0315 0062;0061 05AE 0300 0953 0315 0062; # (a◌̕◌̀◌֮◌॓b; à◌֮◌॓◌̕b; a◌֮◌̀◌॓◌̕b; à◌֮◌॓◌̕b; a◌֮◌̀◌॓◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, DEVANAGARI GRAVE ACCENT, LATIN SMALL LETTER B
+0061 0953 0315 0300 05AE 0062;0061 05AE 0953 0300 0315 0062;0061 05AE 0953 0300 0315 0062;0061 05AE 0953 0300 0315 0062;0061 05AE 0953 0300 0315 0062; # (a◌॓◌̕◌̀◌֮b; a◌֮◌॓◌̀◌̕b; a◌֮◌॓◌̀◌̕b; a◌֮◌॓◌̀◌̕b; a◌֮◌॓◌̀◌̕b; ) LATIN SMALL LETTER A, DEVANAGARI GRAVE ACCENT, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0954 0062;00E0 05AE 0954 0315 0062;0061 05AE 0300 0954 0315 0062;00E0 05AE 0954 0315 0062;0061 05AE 0300 0954 0315 0062; # (a◌̕◌̀◌֮◌॔b; à◌֮◌॔◌̕b; a◌֮◌̀◌॔◌̕b; à◌֮◌॔◌̕b; a◌֮◌̀◌॔◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, DEVANAGARI ACUTE ACCENT, LATIN SMALL LETTER B
+0061 0954 0315 0300 05AE 0062;0061 05AE 0954 0300 0315 0062;0061 05AE 0954 0300 0315 0062;0061 05AE 0954 0300 0315 0062;0061 05AE 0954 0300 0315 0062; # (a◌॔◌̕◌̀◌֮b; a◌֮◌॔◌̀◌̕b; a◌֮◌॔◌̀◌̕b; a◌֮◌॔◌̀◌̕b; a◌֮◌॔◌̀◌̕b; ) LATIN SMALL LETTER A, DEVANAGARI ACUTE ACCENT, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 3099 093C 0334 09BC 0062;0061 0334 093C 09BC 3099 0062;0061 0334 093C 09BC 3099 0062;0061 0334 093C 09BC 3099 0062;0061 0334 093C 09BC 3099 0062; # (a◌゙◌़◌̴◌়b; a◌̴◌़◌়◌゙b; a◌̴◌़◌়◌゙b; a◌̴◌़◌়◌゙b; a◌̴◌़◌়◌゙b; ) LATIN SMALL LETTER A, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, BENGALI SIGN NUKTA, LATIN SMALL LETTER B
+0061 09BC 3099 093C 0334 0062;0061 0334 09BC 093C 3099 0062;0061 0334 09BC 093C 3099 0062;0061 0334 09BC 093C 3099 0062;0061 0334 09BC 093C 3099 0062; # (a◌়◌゙◌़◌̴b; a◌̴◌়◌़◌゙b; a◌̴◌়◌़◌゙b; a◌̴◌়◌़◌゙b; a◌̴◌়◌़◌゙b; ) LATIN SMALL LETTER A, BENGALI SIGN NUKTA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 05B0 094D 3099 09CD 0062;0061 3099 094D 09CD 05B0 0062;0061 3099 094D 09CD 05B0 0062;0061 3099 094D 09CD 05B0 0062;0061 3099 094D 09CD 05B0 0062; # (a◌ְ◌्◌゙◌্b; a◌゙◌्◌্◌ְb; a◌゙◌्◌্◌ְb; a◌゙◌्◌্◌ְb; a◌゙◌्◌্◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, BENGALI SIGN VIRAMA, LATIN SMALL LETTER B
+0061 09CD 05B0 094D 3099 0062;0061 3099 09CD 094D 05B0 0062;0061 3099 09CD 094D 05B0 0062;0061 3099 09CD 094D 05B0 0062;0061 3099 09CD 094D 05B0 0062; # (a◌্◌ְ◌्◌゙b; a◌゙◌্◌्◌ְb; a◌゙◌্◌्◌ְb; a◌゙◌্◌्◌ְb; a◌゙◌্◌्◌ְb; ) LATIN SMALL LETTER A, BENGALI SIGN VIRAMA, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 3099 093C 0334 0A3C 0062;0061 0334 093C 0A3C 3099 0062;0061 0334 093C 0A3C 3099 0062;0061 0334 093C 0A3C 3099 0062;0061 0334 093C 0A3C 3099 0062; # (a◌゙◌़◌̴◌਼b; a◌̴◌़◌਼◌゙b; a◌̴◌़◌਼◌゙b; a◌̴◌़◌਼◌゙b; a◌̴◌़◌਼◌゙b; ) LATIN SMALL LETTER A, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, GURMUKHI SIGN NUKTA, LATIN SMALL LETTER B
+0061 0A3C 3099 093C 0334 0062;0061 0334 0A3C 093C 3099 0062;0061 0334 0A3C 093C 3099 0062;0061 0334 0A3C 093C 3099 0062;0061 0334 0A3C 093C 3099 0062; # (a◌਼◌゙◌़◌̴b; a◌̴◌਼◌़◌゙b; a◌̴◌਼◌़◌゙b; a◌̴◌਼◌़◌゙b; a◌̴◌਼◌़◌゙b; ) LATIN SMALL LETTER A, GURMUKHI SIGN NUKTA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 05B0 094D 3099 0A4D 0062;0061 3099 094D 0A4D 05B0 0062;0061 3099 094D 0A4D 05B0 0062;0061 3099 094D 0A4D 05B0 0062;0061 3099 094D 0A4D 05B0 0062; # (a◌ְ◌्◌゙◌੍b; a◌゙◌्◌੍◌ְb; a◌゙◌्◌੍◌ְb; a◌゙◌्◌੍◌ְb; a◌゙◌्◌੍◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, GURMUKHI SIGN VIRAMA, LATIN SMALL LETTER B
+0061 0A4D 05B0 094D 3099 0062;0061 3099 0A4D 094D 05B0 0062;0061 3099 0A4D 094D 05B0 0062;0061 3099 0A4D 094D 05B0 0062;0061 3099 0A4D 094D 05B0 0062; # (a◌੍◌ְ◌्◌゙b; a◌゙◌੍◌्◌ְb; a◌゙◌੍◌्◌ְb; a◌゙◌੍◌्◌ְb; a◌゙◌੍◌्◌ְb; ) LATIN SMALL LETTER A, GURMUKHI SIGN VIRAMA, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 3099 093C 0334 0ABC 0062;0061 0334 093C 0ABC 3099 0062;0061 0334 093C 0ABC 3099 0062;0061 0334 093C 0ABC 3099 0062;0061 0334 093C 0ABC 3099 0062; # (a◌゙◌़◌̴◌઼b; a◌̴◌़◌઼◌゙b; a◌̴◌़◌઼◌゙b; a◌̴◌़◌઼◌゙b; a◌̴◌़◌઼◌゙b; ) LATIN SMALL LETTER A, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, GUJARATI SIGN NUKTA, LATIN SMALL LETTER B
+0061 0ABC 3099 093C 0334 0062;0061 0334 0ABC 093C 3099 0062;0061 0334 0ABC 093C 3099 0062;0061 0334 0ABC 093C 3099 0062;0061 0334 0ABC 093C 3099 0062; # (a◌઼◌゙◌़◌̴b; a◌̴◌઼◌़◌゙b; a◌̴◌઼◌़◌゙b; a◌̴◌઼◌़◌゙b; a◌̴◌઼◌़◌゙b; ) LATIN SMALL LETTER A, GUJARATI SIGN NUKTA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 05B0 094D 3099 0ACD 0062;0061 3099 094D 0ACD 05B0 0062;0061 3099 094D 0ACD 05B0 0062;0061 3099 094D 0ACD 05B0 0062;0061 3099 094D 0ACD 05B0 0062; # (a◌ְ◌्◌゙◌્b; a◌゙◌्◌્◌ְb; a◌゙◌्◌્◌ְb; a◌゙◌्◌્◌ְb; a◌゙◌्◌્◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, GUJARATI SIGN VIRAMA, LATIN SMALL LETTER B
+0061 0ACD 05B0 094D 3099 0062;0061 3099 0ACD 094D 05B0 0062;0061 3099 0ACD 094D 05B0 0062;0061 3099 0ACD 094D 05B0 0062;0061 3099 0ACD 094D 05B0 0062; # (a◌્◌ְ◌्◌゙b; a◌゙◌્◌्◌ְb; a◌゙◌્◌्◌ְb; a◌゙◌્◌्◌ְb; a◌゙◌્◌्◌ְb; ) LATIN SMALL LETTER A, GUJARATI SIGN VIRAMA, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 3099 093C 0334 0B3C 0062;0061 0334 093C 0B3C 3099 0062;0061 0334 093C 0B3C 3099 0062;0061 0334 093C 0B3C 3099 0062;0061 0334 093C 0B3C 3099 0062; # (a◌゙◌़◌̴◌଼b; a◌̴◌़◌଼◌゙b; a◌̴◌़◌଼◌゙b; a◌̴◌़◌଼◌゙b; a◌̴◌़◌଼◌゙b; ) LATIN SMALL LETTER A, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, ORIYA SIGN NUKTA, LATIN SMALL LETTER B
+0061 0B3C 3099 093C 0334 0062;0061 0334 0B3C 093C 3099 0062;0061 0334 0B3C 093C 3099 0062;0061 0334 0B3C 093C 3099 0062;0061 0334 0B3C 093C 3099 0062; # (a◌଼◌゙◌़◌̴b; a◌̴◌଼◌़◌゙b; a◌̴◌଼◌़◌゙b; a◌̴◌଼◌़◌゙b; a◌̴◌଼◌़◌゙b; ) LATIN SMALL LETTER A, ORIYA SIGN NUKTA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 05B0 094D 3099 0B4D 0062;0061 3099 094D 0B4D 05B0 0062;0061 3099 094D 0B4D 05B0 0062;0061 3099 094D 0B4D 05B0 0062;0061 3099 094D 0B4D 05B0 0062; # (a◌ְ◌्◌゙◌୍b; a◌゙◌्◌୍◌ְb; a◌゙◌्◌୍◌ְb; a◌゙◌्◌୍◌ְb; a◌゙◌्◌୍◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, ORIYA SIGN VIRAMA, LATIN SMALL LETTER B
+0061 0B4D 05B0 094D 3099 0062;0061 3099 0B4D 094D 05B0 0062;0061 3099 0B4D 094D 05B0 0062;0061 3099 0B4D 094D 05B0 0062;0061 3099 0B4D 094D 05B0 0062; # (a◌୍◌ְ◌्◌゙b; a◌゙◌୍◌्◌ְb; a◌゙◌୍◌्◌ְb; a◌゙◌୍◌्◌ְb; a◌゙◌୍◌्◌ְb; ) LATIN SMALL LETTER A, ORIYA SIGN VIRAMA, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 05B0 094D 3099 0BCD 0062;0061 3099 094D 0BCD 05B0 0062;0061 3099 094D 0BCD 05B0 0062;0061 3099 094D 0BCD 05B0 0062;0061 3099 094D 0BCD 05B0 0062; # (a◌ְ◌्◌゙◌்b; a◌゙◌्◌்◌ְb; a◌゙◌्◌்◌ְb; a◌゙◌्◌்◌ְb; a◌゙◌्◌்◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, TAMIL SIGN VIRAMA, LATIN SMALL LETTER B
+0061 0BCD 05B0 094D 3099 0062;0061 3099 0BCD 094D 05B0 0062;0061 3099 0BCD 094D 05B0 0062;0061 3099 0BCD 094D 05B0 0062;0061 3099 0BCD 094D 05B0 0062; # (a◌்◌ְ◌्◌゙b; a◌゙◌்◌्◌ְb; a◌゙◌்◌्◌ְb; a◌゙◌்◌्◌ְb; a◌゙◌்◌्◌ְb; ) LATIN SMALL LETTER A, TAMIL SIGN VIRAMA, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 05B0 094D 3099 0C4D 0062;0061 3099 094D 0C4D 05B0 0062;0061 3099 094D 0C4D 05B0 0062;0061 3099 094D 0C4D 05B0 0062;0061 3099 094D 0C4D 05B0 0062; # (a◌ְ◌्◌゙◌్b; a◌゙◌्◌్◌ְb; a◌゙◌्◌్◌ְb; a◌゙◌्◌్◌ְb; a◌゙◌्◌్◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, TELUGU SIGN VIRAMA, LATIN SMALL LETTER B
+0061 0C4D 05B0 094D 3099 0062;0061 3099 0C4D 094D 05B0 0062;0061 3099 0C4D 094D 05B0 0062;0061 3099 0C4D 094D 05B0 0062;0061 3099 0C4D 094D 05B0 0062; # (a◌్◌ְ◌्◌゙b; a◌゙◌్◌्◌ְb; a◌゙◌్◌्◌ְb; a◌゙◌్◌्◌ְb; a◌゙◌్◌्◌ְb; ) LATIN SMALL LETTER A, TELUGU SIGN VIRAMA, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 0C56 0C55 0711 0C55 0062;0061 0711 0C55 0C55 0C56 0062;0061 0711 0C55 0C55 0C56 0062;0061 0711 0C55 0C55 0C56 0062;0061 0711 0C55 0C55 0C56 0062; # (a◌ౖ◌ౕ◌ܑ◌ౕb; a◌ܑ◌ౕ◌ౕ◌ౖb; a◌ܑ◌ౕ◌ౕ◌ౖb; a◌ܑ◌ౕ◌ౕ◌ౖb; a◌ܑ◌ౕ◌ౕ◌ౖb; ) LATIN SMALL LETTER A, TELUGU AI LENGTH MARK, TELUGU LENGTH MARK, SYRIAC LETTER SUPERSCRIPT ALAPH, TELUGU LENGTH MARK, LATIN SMALL LETTER B
+0061 0C55 0C56 0C55 0711 0062;0061 0711 0C55 0C55 0C56 0062;0061 0711 0C55 0C55 0C56 0062;0061 0711 0C55 0C55 0C56 0062;0061 0711 0C55 0C55 0C56 0062; # (a◌ౕ◌ౖ◌ౕ◌ܑb; a◌ܑ◌ౕ◌ౕ◌ౖb; a◌ܑ◌ౕ◌ౕ◌ౖb; a◌ܑ◌ౕ◌ౕ◌ౖb; a◌ܑ◌ౕ◌ౕ◌ౖb; ) LATIN SMALL LETTER A, TELUGU LENGTH MARK, TELUGU AI LENGTH MARK, TELUGU LENGTH MARK, SYRIAC LETTER SUPERSCRIPT ALAPH, LATIN SMALL LETTER B
+0061 0E38 0C56 0C55 0C56 0062;0061 0C55 0C56 0C56 0E38 0062;0061 0C55 0C56 0C56 0E38 0062;0061 0C55 0C56 0C56 0E38 0062;0061 0C55 0C56 0C56 0E38 0062; # (a◌ุ◌ౖ◌ౕ◌ౖb; a◌ౕ◌ౖ◌ౖ◌ุb; a◌ౕ◌ౖ◌ౖ◌ุb; a◌ౕ◌ౖ◌ౖ◌ุb; a◌ౕ◌ౖ◌ౖ◌ุb; ) LATIN SMALL LETTER A, THAI CHARACTER SARA U, TELUGU AI LENGTH MARK, TELUGU LENGTH MARK, TELUGU AI LENGTH MARK, LATIN SMALL LETTER B
+0061 0C56 0E38 0C56 0C55 0062;0061 0C55 0C56 0C56 0E38 0062;0061 0C55 0C56 0C56 0E38 0062;0061 0C55 0C56 0C56 0E38 0062;0061 0C55 0C56 0C56 0E38 0062; # (a◌ౖ◌ุ◌ౖ◌ౕb; a◌ౕ◌ౖ◌ౖ◌ุb; a◌ౕ◌ౖ◌ౖ◌ุb; a◌ౕ◌ౖ◌ౖ◌ุb; a◌ౕ◌ౖ◌ౖ◌ุb; ) LATIN SMALL LETTER A, TELUGU AI LENGTH MARK, THAI CHARACTER SARA U, TELUGU AI LENGTH MARK, TELUGU LENGTH MARK, LATIN SMALL LETTER B
+0061 3099 093C 0334 0CBC 0062;0061 0334 093C 0CBC 3099 0062;0061 0334 093C 0CBC 3099 0062;0061 0334 093C 0CBC 3099 0062;0061 0334 093C 0CBC 3099 0062; # (a◌゙◌़◌̴◌಼b; a◌̴◌़◌಼◌゙b; a◌̴◌़◌಼◌゙b; a◌̴◌़◌಼◌゙b; a◌̴◌़◌಼◌゙b; ) LATIN SMALL LETTER A, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, KANNADA SIGN NUKTA, LATIN SMALL LETTER B
+0061 0CBC 3099 093C 0334 0062;0061 0334 0CBC 093C 3099 0062;0061 0334 0CBC 093C 3099 0062;0061 0334 0CBC 093C 3099 0062;0061 0334 0CBC 093C 3099 0062; # (a◌಼◌゙◌़◌̴b; a◌̴◌಼◌़◌゙b; a◌̴◌಼◌़◌゙b; a◌̴◌಼◌़◌゙b; a◌̴◌಼◌़◌゙b; ) LATIN SMALL LETTER A, KANNADA SIGN NUKTA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 05B0 094D 3099 0CCD 0062;0061 3099 094D 0CCD 05B0 0062;0061 3099 094D 0CCD 05B0 0062;0061 3099 094D 0CCD 05B0 0062;0061 3099 094D 0CCD 05B0 0062; # (a◌ְ◌्◌゙◌್b; a◌゙◌्◌್◌ְb; a◌゙◌्◌್◌ְb; a◌゙◌्◌್◌ְb; a◌゙◌्◌್◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, KANNADA SIGN VIRAMA, LATIN SMALL LETTER B
+0061 0CCD 05B0 094D 3099 0062;0061 3099 0CCD 094D 05B0 0062;0061 3099 0CCD 094D 05B0 0062;0061 3099 0CCD 094D 05B0 0062;0061 3099 0CCD 094D 05B0 0062; # (a◌್◌ְ◌्◌゙b; a◌゙◌್◌्◌ְb; a◌゙◌್◌्◌ְb; a◌゙◌್◌्◌ְb; a◌゙◌್◌्◌ְb; ) LATIN SMALL LETTER A, KANNADA SIGN VIRAMA, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 05B0 094D 3099 0D4D 0062;0061 3099 094D 0D4D 05B0 0062;0061 3099 094D 0D4D 05B0 0062;0061 3099 094D 0D4D 05B0 0062;0061 3099 094D 0D4D 05B0 0062; # (a◌ְ◌्◌゙◌്b; a◌゙◌्◌്◌ְb; a◌゙◌्◌്◌ְb; a◌゙◌्◌്◌ְb; a◌゙◌्◌്◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, MALAYALAM SIGN VIRAMA, LATIN SMALL LETTER B
+0061 0D4D 05B0 094D 3099 0062;0061 3099 0D4D 094D 05B0 0062;0061 3099 0D4D 094D 05B0 0062;0061 3099 0D4D 094D 05B0 0062;0061 3099 0D4D 094D 05B0 0062; # (a◌്◌ְ◌्◌゙b; a◌゙◌്◌्◌ְb; a◌゙◌്◌्◌ְb; a◌゙◌്◌्◌ְb; a◌゙◌്◌्◌ְb; ) LATIN SMALL LETTER A, MALAYALAM SIGN VIRAMA, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 05B0 094D 3099 0DCA 0062;0061 3099 094D 0DCA 05B0 0062;0061 3099 094D 0DCA 05B0 0062;0061 3099 094D 0DCA 05B0 0062;0061 3099 094D 0DCA 05B0 0062; # (a◌ְ◌्◌゙◌්b; a◌゙◌्◌්◌ְb; a◌゙◌्◌්◌ְb; a◌゙◌्◌්◌ְb; a◌゙◌्◌්◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, SINHALA SIGN AL-LAKUNA, LATIN SMALL LETTER B
+0061 0DCA 05B0 094D 3099 0062;0061 3099 0DCA 094D 05B0 0062;0061 3099 0DCA 094D 05B0 0062;0061 3099 0DCA 094D 05B0 0062;0061 3099 0DCA 094D 05B0 0062; # (a◌්◌ְ◌्◌゙b; a◌゙◌්◌्◌ְb; a◌゙◌්◌्◌ְb; a◌゙◌්◌्◌ְb; a◌゙◌්◌्◌ְb; ) LATIN SMALL LETTER A, SINHALA SIGN AL-LAKUNA, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 0E48 0E38 0C56 0E38 0062;0061 0C56 0E38 0E38 0E48 0062;0061 0C56 0E38 0E38 0E48 0062;0061 0C56 0E38 0E38 0E48 0062;0061 0C56 0E38 0E38 0E48 0062; # (a◌่◌ุ◌ౖ◌ุb; a◌ౖ◌ุ◌ุ◌่b; a◌ౖ◌ุ◌ุ◌่b; a◌ౖ◌ุ◌ุ◌่b; a◌ౖ◌ุ◌ุ◌่b; ) LATIN SMALL LETTER A, THAI CHARACTER MAI EK, THAI CHARACTER SARA U, TELUGU AI LENGTH MARK, THAI CHARACTER SARA U, LATIN SMALL LETTER B
+0061 0E38 0E48 0E38 0C56 0062;0061 0C56 0E38 0E38 0E48 0062;0061 0C56 0E38 0E38 0E48 0062;0061 0C56 0E38 0E38 0E48 0062;0061 0C56 0E38 0E38 0E48 0062; # (a◌ุ◌่◌ุ◌ౖb; a◌ౖ◌ุ◌ุ◌่b; a◌ౖ◌ุ◌ุ◌่b; a◌ౖ◌ุ◌ุ◌่b; a◌ౖ◌ุ◌ุ◌่b; ) LATIN SMALL LETTER A, THAI CHARACTER SARA U, THAI CHARACTER MAI EK, THAI CHARACTER SARA U, TELUGU AI LENGTH MARK, LATIN SMALL LETTER B
+0061 0E48 0E38 0C56 0E39 0062;0061 0C56 0E38 0E39 0E48 0062;0061 0C56 0E38 0E39 0E48 0062;0061 0C56 0E38 0E39 0E48 0062;0061 0C56 0E38 0E39 0E48 0062; # (a◌่◌ุ◌ౖ◌ูb; a◌ౖ◌ุ◌ู◌่b; a◌ౖ◌ุ◌ู◌่b; a◌ౖ◌ุ◌ู◌่b; a◌ౖ◌ุ◌ู◌่b; ) LATIN SMALL LETTER A, THAI CHARACTER MAI EK, THAI CHARACTER SARA U, TELUGU AI LENGTH MARK, THAI CHARACTER SARA UU, LATIN SMALL LETTER B
+0061 0E39 0E48 0E38 0C56 0062;0061 0C56 0E39 0E38 0E48 0062;0061 0C56 0E39 0E38 0E48 0062;0061 0C56 0E39 0E38 0E48 0062;0061 0C56 0E39 0E38 0E48 0062; # (a◌ู◌่◌ุ◌ౖb; a◌ౖ◌ู◌ุ◌่b; a◌ౖ◌ู◌ุ◌่b; a◌ౖ◌ู◌ุ◌่b; a◌ౖ◌ู◌ุ◌่b; ) LATIN SMALL LETTER A, THAI CHARACTER SARA UU, THAI CHARACTER MAI EK, THAI CHARACTER SARA U, TELUGU AI LENGTH MARK, LATIN SMALL LETTER B
+0061 05B0 094D 3099 0E3A 0062;0061 3099 094D 0E3A 05B0 0062;0061 3099 094D 0E3A 05B0 0062;0061 3099 094D 0E3A 05B0 0062;0061 3099 094D 0E3A 05B0 0062; # (a◌ְ◌्◌゙◌ฺb; a◌゙◌्◌ฺ◌ְb; a◌゙◌्◌ฺ◌ְb; a◌゙◌्◌ฺ◌ְb; a◌゙◌्◌ฺ◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, THAI CHARACTER PHINTHU, LATIN SMALL LETTER B
+0061 0E3A 05B0 094D 3099 0062;0061 3099 0E3A 094D 05B0 0062;0061 3099 0E3A 094D 05B0 0062;0061 3099 0E3A 094D 05B0 0062;0061 3099 0E3A 094D 05B0 0062; # (a◌ฺ◌ְ◌्◌゙b; a◌゙◌ฺ◌्◌ְb; a◌゙◌ฺ◌्◌ְb; a◌゙◌ฺ◌्◌ְb; a◌゙◌ฺ◌्◌ְb; ) LATIN SMALL LETTER A, THAI CHARACTER PHINTHU, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 0EB8 0E48 0E38 0E48 0062;0061 0E38 0E48 0E48 0EB8 0062;0061 0E38 0E48 0E48 0EB8 0062;0061 0E38 0E48 0E48 0EB8 0062;0061 0E38 0E48 0E48 0EB8 0062; # (a◌ຸ◌่◌ุ◌่b; a◌ุ◌่◌่◌ຸb; a◌ุ◌่◌่◌ຸb; a◌ุ◌่◌่◌ຸb; a◌ุ◌่◌่◌ຸb; ) LATIN SMALL LETTER A, LAO VOWEL SIGN U, THAI CHARACTER MAI EK, THAI CHARACTER SARA U, THAI CHARACTER MAI EK, LATIN SMALL LETTER B
+0061 0E48 0EB8 0E48 0E38 0062;0061 0E38 0E48 0E48 0EB8 0062;0061 0E38 0E48 0E48 0EB8 0062;0061 0E38 0E48 0E48 0EB8 0062;0061 0E38 0E48 0E48 0EB8 0062; # (a◌่◌ຸ◌่◌ุb; a◌ุ◌่◌่◌ຸb; a◌ุ◌่◌่◌ຸb; a◌ุ◌่◌่◌ຸb; a◌ุ◌่◌่◌ຸb; ) LATIN SMALL LETTER A, THAI CHARACTER MAI EK, LAO VOWEL SIGN U, THAI CHARACTER MAI EK, THAI CHARACTER SARA U, LATIN SMALL LETTER B
+0061 0EB8 0E48 0E38 0E49 0062;0061 0E38 0E48 0E49 0EB8 0062;0061 0E38 0E48 0E49 0EB8 0062;0061 0E38 0E48 0E49 0EB8 0062;0061 0E38 0E48 0E49 0EB8 0062; # (a◌ຸ◌่◌ุ◌้b; a◌ุ◌่◌้◌ຸb; a◌ุ◌่◌้◌ຸb; a◌ุ◌่◌้◌ຸb; a◌ุ◌่◌้◌ຸb; ) LATIN SMALL LETTER A, LAO VOWEL SIGN U, THAI CHARACTER MAI EK, THAI CHARACTER SARA U, THAI CHARACTER MAI THO, LATIN SMALL LETTER B
+0061 0E49 0EB8 0E48 0E38 0062;0061 0E38 0E49 0E48 0EB8 0062;0061 0E38 0E49 0E48 0EB8 0062;0061 0E38 0E49 0E48 0EB8 0062;0061 0E38 0E49 0E48 0EB8 0062; # (a◌้◌ຸ◌่◌ุb; a◌ุ◌้◌่◌ຸb; a◌ุ◌้◌่◌ຸb; a◌ุ◌้◌่◌ຸb; a◌ุ◌้◌่◌ຸb; ) LATIN SMALL LETTER A, THAI CHARACTER MAI THO, LAO VOWEL SIGN U, THAI CHARACTER MAI EK, THAI CHARACTER SARA U, LATIN SMALL LETTER B
+0061 0EB8 0E48 0E38 0E4A 0062;0061 0E38 0E48 0E4A 0EB8 0062;0061 0E38 0E48 0E4A 0EB8 0062;0061 0E38 0E48 0E4A 0EB8 0062;0061 0E38 0E48 0E4A 0EB8 0062; # (a◌ຸ◌่◌ุ◌๊b; a◌ุ◌่◌๊◌ຸb; a◌ุ◌่◌๊◌ຸb; a◌ุ◌่◌๊◌ຸb; a◌ุ◌่◌๊◌ຸb; ) LATIN SMALL LETTER A, LAO VOWEL SIGN U, THAI CHARACTER MAI EK, THAI CHARACTER SARA U, THAI CHARACTER MAI TRI, LATIN SMALL LETTER B
+0061 0E4A 0EB8 0E48 0E38 0062;0061 0E38 0E4A 0E48 0EB8 0062;0061 0E38 0E4A 0E48 0EB8 0062;0061 0E38 0E4A 0E48 0EB8 0062;0061 0E38 0E4A 0E48 0EB8 0062; # (a◌๊◌ຸ◌่◌ุb; a◌ุ◌๊◌่◌ຸb; a◌ุ◌๊◌่◌ຸb; a◌ุ◌๊◌่◌ຸb; a◌ุ◌๊◌่◌ຸb; ) LATIN SMALL LETTER A, THAI CHARACTER MAI TRI, LAO VOWEL SIGN U, THAI CHARACTER MAI EK, THAI CHARACTER SARA U, LATIN SMALL LETTER B
+0061 0EB8 0E48 0E38 0E4B 0062;0061 0E38 0E48 0E4B 0EB8 0062;0061 0E38 0E48 0E4B 0EB8 0062;0061 0E38 0E48 0E4B 0EB8 0062;0061 0E38 0E48 0E4B 0EB8 0062; # (a◌ຸ◌่◌ุ◌๋b; a◌ุ◌่◌๋◌ຸb; a◌ุ◌่◌๋◌ຸb; a◌ุ◌่◌๋◌ຸb; a◌ุ◌่◌๋◌ຸb; ) LATIN SMALL LETTER A, LAO VOWEL SIGN U, THAI CHARACTER MAI EK, THAI CHARACTER SARA U, THAI CHARACTER MAI CHATTAWA, LATIN SMALL LETTER B
+0061 0E4B 0EB8 0E48 0E38 0062;0061 0E38 0E4B 0E48 0EB8 0062;0061 0E38 0E4B 0E48 0EB8 0062;0061 0E38 0E4B 0E48 0EB8 0062;0061 0E38 0E4B 0E48 0EB8 0062; # (a◌๋◌ຸ◌่◌ุb; a◌ุ◌๋◌่◌ຸb; a◌ุ◌๋◌่◌ຸb; a◌ุ◌๋◌่◌ຸb; a◌ุ◌๋◌่◌ຸb; ) LATIN SMALL LETTER A, THAI CHARACTER MAI CHATTAWA, LAO VOWEL SIGN U, THAI CHARACTER MAI EK, THAI CHARACTER SARA U, LATIN SMALL LETTER B
+0061 0EC8 0EB8 0E48 0EB8 0062;0061 0E48 0EB8 0EB8 0EC8 0062;0061 0E48 0EB8 0EB8 0EC8 0062;0061 0E48 0EB8 0EB8 0EC8 0062;0061 0E48 0EB8 0EB8 0EC8 0062; # (a◌່◌ຸ◌่◌ຸb; a◌่◌ຸ◌ຸ◌່b; a◌่◌ຸ◌ຸ◌່b; a◌่◌ຸ◌ຸ◌່b; a◌่◌ຸ◌ຸ◌່b; ) LATIN SMALL LETTER A, LAO TONE MAI EK, LAO VOWEL SIGN U, THAI CHARACTER MAI EK, LAO VOWEL SIGN U, LATIN SMALL LETTER B
+0061 0EB8 0EC8 0EB8 0E48 0062;0061 0E48 0EB8 0EB8 0EC8 0062;0061 0E48 0EB8 0EB8 0EC8 0062;0061 0E48 0EB8 0EB8 0EC8 0062;0061 0E48 0EB8 0EB8 0EC8 0062; # (a◌ຸ◌່◌ຸ◌่b; a◌่◌ຸ◌ຸ◌່b; a◌่◌ຸ◌ຸ◌່b; a◌่◌ຸ◌ຸ◌່b; a◌่◌ຸ◌ຸ◌່b; ) LATIN SMALL LETTER A, LAO VOWEL SIGN U, LAO TONE MAI EK, LAO VOWEL SIGN U, THAI CHARACTER MAI EK, LATIN SMALL LETTER B
+0061 0EC8 0EB8 0E48 0EB9 0062;0061 0E48 0EB8 0EB9 0EC8 0062;0061 0E48 0EB8 0EB9 0EC8 0062;0061 0E48 0EB8 0EB9 0EC8 0062;0061 0E48 0EB8 0EB9 0EC8 0062; # (a◌່◌ຸ◌่◌ູb; a◌่◌ຸ◌ູ◌່b; a◌่◌ຸ◌ູ◌່b; a◌่◌ຸ◌ູ◌່b; a◌่◌ຸ◌ູ◌່b; ) LATIN SMALL LETTER A, LAO TONE MAI EK, LAO VOWEL SIGN U, THAI CHARACTER MAI EK, LAO VOWEL SIGN UU, LATIN SMALL LETTER B
+0061 0EB9 0EC8 0EB8 0E48 0062;0061 0E48 0EB9 0EB8 0EC8 0062;0061 0E48 0EB9 0EB8 0EC8 0062;0061 0E48 0EB9 0EB8 0EC8 0062;0061 0E48 0EB9 0EB8 0EC8 0062; # (a◌ູ◌່◌ຸ◌่b; a◌่◌ູ◌ຸ◌່b; a◌่◌ູ◌ຸ◌່b; a◌่◌ູ◌ຸ◌່b; a◌่◌ູ◌ຸ◌່b; ) LATIN SMALL LETTER A, LAO VOWEL SIGN UU, LAO TONE MAI EK, LAO VOWEL SIGN U, THAI CHARACTER MAI EK, LATIN SMALL LETTER B
+0061 0F71 0EC8 0EB8 0EC8 0062;0061 0EB8 0EC8 0EC8 0F71 0062;0061 0EB8 0EC8 0EC8 0F71 0062;0061 0EB8 0EC8 0EC8 0F71 0062;0061 0EB8 0EC8 0EC8 0F71 0062; # (a◌ཱ◌່◌ຸ◌່b; a◌ຸ◌່◌່◌ཱb; a◌ຸ◌່◌່◌ཱb; a◌ຸ◌່◌່◌ཱb; a◌ຸ◌່◌່◌ཱb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN AA, LAO TONE MAI EK, LAO VOWEL SIGN U, LAO TONE MAI EK, LATIN SMALL LETTER B
+0061 0EC8 0F71 0EC8 0EB8 0062;0061 0EB8 0EC8 0EC8 0F71 0062;0061 0EB8 0EC8 0EC8 0F71 0062;0061 0EB8 0EC8 0EC8 0F71 0062;0061 0EB8 0EC8 0EC8 0F71 0062; # (a◌່◌ཱ◌່◌ຸb; a◌ຸ◌່◌່◌ཱb; a◌ຸ◌່◌່◌ཱb; a◌ຸ◌່◌່◌ཱb; a◌ຸ◌່◌່◌ཱb; ) LATIN SMALL LETTER A, LAO TONE MAI EK, TIBETAN VOWEL SIGN AA, LAO TONE MAI EK, LAO VOWEL SIGN U, LATIN SMALL LETTER B
+0061 0F71 0EC8 0EB8 0EC9 0062;0061 0EB8 0EC8 0EC9 0F71 0062;0061 0EB8 0EC8 0EC9 0F71 0062;0061 0EB8 0EC8 0EC9 0F71 0062;0061 0EB8 0EC8 0EC9 0F71 0062; # (a◌ཱ◌່◌ຸ◌້b; a◌ຸ◌່◌້◌ཱb; a◌ຸ◌່◌້◌ཱb; a◌ຸ◌່◌້◌ཱb; a◌ຸ◌່◌້◌ཱb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN AA, LAO TONE MAI EK, LAO VOWEL SIGN U, LAO TONE MAI THO, LATIN SMALL LETTER B
+0061 0EC9 0F71 0EC8 0EB8 0062;0061 0EB8 0EC9 0EC8 0F71 0062;0061 0EB8 0EC9 0EC8 0F71 0062;0061 0EB8 0EC9 0EC8 0F71 0062;0061 0EB8 0EC9 0EC8 0F71 0062; # (a◌້◌ཱ◌່◌ຸb; a◌ຸ◌້◌່◌ཱb; a◌ຸ◌້◌່◌ཱb; a◌ຸ◌້◌່◌ཱb; a◌ຸ◌້◌່◌ཱb; ) LATIN SMALL LETTER A, LAO TONE MAI THO, TIBETAN VOWEL SIGN AA, LAO TONE MAI EK, LAO VOWEL SIGN U, LATIN SMALL LETTER B
+0061 0F71 0EC8 0EB8 0ECA 0062;0061 0EB8 0EC8 0ECA 0F71 0062;0061 0EB8 0EC8 0ECA 0F71 0062;0061 0EB8 0EC8 0ECA 0F71 0062;0061 0EB8 0EC8 0ECA 0F71 0062; # (a◌ཱ◌່◌ຸ◌໊b; a◌ຸ◌່◌໊◌ཱb; a◌ຸ◌່◌໊◌ཱb; a◌ຸ◌່◌໊◌ཱb; a◌ຸ◌່◌໊◌ཱb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN AA, LAO TONE MAI EK, LAO VOWEL SIGN U, LAO TONE MAI TI, LATIN SMALL LETTER B
+0061 0ECA 0F71 0EC8 0EB8 0062;0061 0EB8 0ECA 0EC8 0F71 0062;0061 0EB8 0ECA 0EC8 0F71 0062;0061 0EB8 0ECA 0EC8 0F71 0062;0061 0EB8 0ECA 0EC8 0F71 0062; # (a◌໊◌ཱ◌່◌ຸb; a◌ຸ◌໊◌່◌ཱb; a◌ຸ◌໊◌່◌ཱb; a◌ຸ◌໊◌່◌ཱb; a◌ຸ◌໊◌່◌ཱb; ) LATIN SMALL LETTER A, LAO TONE MAI TI, TIBETAN VOWEL SIGN AA, LAO TONE MAI EK, LAO VOWEL SIGN U, LATIN SMALL LETTER B
+0061 0F71 0EC8 0EB8 0ECB 0062;0061 0EB8 0EC8 0ECB 0F71 0062;0061 0EB8 0EC8 0ECB 0F71 0062;0061 0EB8 0EC8 0ECB 0F71 0062;0061 0EB8 0EC8 0ECB 0F71 0062; # (a◌ཱ◌່◌ຸ◌໋b; a◌ຸ◌່◌໋◌ཱb; a◌ຸ◌່◌໋◌ཱb; a◌ຸ◌່◌໋◌ཱb; a◌ຸ◌່◌໋◌ཱb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN AA, LAO TONE MAI EK, LAO VOWEL SIGN U, LAO TONE MAI CATAWA, LATIN SMALL LETTER B
+0061 0ECB 0F71 0EC8 0EB8 0062;0061 0EB8 0ECB 0EC8 0F71 0062;0061 0EB8 0ECB 0EC8 0F71 0062;0061 0EB8 0ECB 0EC8 0F71 0062;0061 0EB8 0ECB 0EC8 0F71 0062; # (a◌໋◌ཱ◌່◌ຸb; a◌ຸ◌໋◌່◌ཱb; a◌ຸ◌໋◌່◌ཱb; a◌ຸ◌໋◌່◌ཱb; a◌ຸ◌໋◌່◌ཱb; ) LATIN SMALL LETTER A, LAO TONE MAI CATAWA, TIBETAN VOWEL SIGN AA, LAO TONE MAI EK, LAO VOWEL SIGN U, LATIN SMALL LETTER B
+0061 059A 0316 302A 0F18 0062;0061 302A 0316 0F18 059A 0062;0061 302A 0316 0F18 059A 0062;0061 302A 0316 0F18 059A 0062;0061 302A 0316 0F18 059A 0062; # (a◌֚◌̖◌〪◌༘b; a◌〪◌̖◌༘◌֚b; a◌〪◌̖◌༘◌֚b; a◌〪◌̖◌༘◌֚b; a◌〪◌̖◌༘◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, TIBETAN ASTROLOGICAL SIGN -KHYUD PA, LATIN SMALL LETTER B
+0061 0F18 059A 0316 302A 0062;0061 302A 0F18 0316 059A 0062;0061 302A 0F18 0316 059A 0062;0061 302A 0F18 0316 059A 0062;0061 302A 0F18 0316 059A 0062; # (a◌༘◌֚◌̖◌〪b; a◌〪◌༘◌̖◌֚b; a◌〪◌༘◌̖◌֚b; a◌〪◌༘◌̖◌֚b; a◌〪◌༘◌̖◌֚b; ) LATIN SMALL LETTER A, TIBETAN ASTROLOGICAL SIGN -KHYUD PA, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0F19 0062;0061 302A 0316 0F19 059A 0062;0061 302A 0316 0F19 059A 0062;0061 302A 0316 0F19 059A 0062;0061 302A 0316 0F19 059A 0062; # (a◌֚◌̖◌〪◌༙b; a◌〪◌̖◌༙◌֚b; a◌〪◌̖◌༙◌֚b; a◌〪◌̖◌༙◌֚b; a◌〪◌̖◌༙◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, TIBETAN ASTROLOGICAL SIGN SDONG TSHUGS, LATIN SMALL LETTER B
+0061 0F19 059A 0316 302A 0062;0061 302A 0F19 0316 059A 0062;0061 302A 0F19 0316 059A 0062;0061 302A 0F19 0316 059A 0062;0061 302A 0F19 0316 059A 0062; # (a◌༙◌֚◌̖◌〪b; a◌〪◌༙◌̖◌֚b; a◌〪◌༙◌̖◌֚b; a◌〪◌༙◌̖◌֚b; a◌〪◌༙◌̖◌֚b; ) LATIN SMALL LETTER A, TIBETAN ASTROLOGICAL SIGN SDONG TSHUGS, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0F35 0062;0061 302A 0316 0F35 059A 0062;0061 302A 0316 0F35 059A 0062;0061 302A 0316 0F35 059A 0062;0061 302A 0316 0F35 059A 0062; # (a◌֚◌̖◌〪◌༵b; a◌〪◌̖◌༵◌֚b; a◌〪◌̖◌༵◌֚b; a◌〪◌̖◌༵◌֚b; a◌〪◌̖◌༵◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, TIBETAN MARK NGAS BZUNG NYI ZLA, LATIN SMALL LETTER B
+0061 0F35 059A 0316 302A 0062;0061 302A 0F35 0316 059A 0062;0061 302A 0F35 0316 059A 0062;0061 302A 0F35 0316 059A 0062;0061 302A 0F35 0316 059A 0062; # (a◌༵◌֚◌̖◌〪b; a◌〪◌༵◌̖◌֚b; a◌〪◌༵◌̖◌֚b; a◌〪◌༵◌̖◌֚b; a◌〪◌༵◌̖◌֚b; ) LATIN SMALL LETTER A, TIBETAN MARK NGAS BZUNG NYI ZLA, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 0F37 0062;0061 302A 0316 0F37 059A 0062;0061 302A 0316 0F37 059A 0062;0061 302A 0316 0F37 059A 0062;0061 302A 0316 0F37 059A 0062; # (a◌֚◌̖◌〪◌༷b; a◌〪◌̖◌༷◌֚b; a◌〪◌̖◌༷◌֚b; a◌〪◌̖◌༷◌֚b; a◌〪◌̖◌༷◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, TIBETAN MARK NGAS BZUNG SGOR RTAGS, LATIN SMALL LETTER B
+0061 0F37 059A 0316 302A 0062;0061 302A 0F37 0316 059A 0062;0061 302A 0F37 0316 059A 0062;0061 302A 0F37 0316 059A 0062;0061 302A 0F37 0316 059A 0062; # (a◌༷◌֚◌̖◌〪b; a◌〪◌༷◌̖◌֚b; a◌〪◌༷◌̖◌֚b; a◌〪◌༷◌̖◌֚b; a◌〪◌༷◌̖◌֚b; ) LATIN SMALL LETTER A, TIBETAN MARK NGAS BZUNG SGOR RTAGS, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 302A 031B 0321 0F39 0062;0061 0321 031B 0F39 302A 0062;0061 0321 031B 0F39 302A 0062;0061 0321 031B 0F39 302A 0062;0061 0321 031B 0F39 302A 0062; # (a◌〪◌̛◌̡◌༹b; a◌̡◌̛◌༹◌〪b; a◌̡◌̛◌༹◌〪b; a◌̡◌̛◌༹◌〪b; a◌̡◌̛◌༹◌〪b; ) LATIN SMALL LETTER A, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, TIBETAN MARK TSA -PHRU, LATIN SMALL LETTER B
+0061 0F39 302A 031B 0321 0062;0061 0321 0F39 031B 302A 0062;0061 0321 0F39 031B 302A 0062;0061 0321 0F39 031B 302A 0062;0061 0321 0F39 031B 302A 0062; # (a◌༹◌〪◌̛◌̡b; a◌̡◌༹◌̛◌〪b; a◌̡◌༹◌̛◌〪b; a◌̡◌༹◌̛◌〪b; a◌̡◌༹◌̛◌〪b; ) LATIN SMALL LETTER A, TIBETAN MARK TSA -PHRU, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, LATIN SMALL LETTER B
+0061 0F72 0F71 0EC8 0F71 0062;0061 0EC8 0F71 0F71 0F72 0062;0061 0EC8 0F71 0F71 0F72 0062;0061 0EC8 0F71 0F71 0F72 0062;0061 0EC8 0F71 0F71 0F72 0062; # (a◌ི◌ཱ◌່◌ཱb; a◌່◌ཱ◌ཱ◌ིb; a◌່◌ཱ◌ཱ◌ིb; a◌່◌ཱ◌ཱ◌ིb; a◌່◌ཱ◌ཱ◌ིb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN AA, LAO TONE MAI EK, TIBETAN VOWEL SIGN AA, LATIN SMALL LETTER B
+0061 0F71 0F72 0F71 0EC8 0062;0061 0EC8 0F71 0F71 0F72 0062;0061 0EC8 0F71 0F71 0F72 0062;0061 0EC8 0F71 0F71 0F72 0062;0061 0EC8 0F71 0F71 0F72 0062; # (a◌ཱ◌ི◌ཱ◌່b; a◌່◌ཱ◌ཱ◌ིb; a◌່◌ཱ◌ཱ◌ིb; a◌່◌ཱ◌ཱ◌ིb; a◌່◌ཱ◌ཱ◌ིb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN AA, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN AA, LAO TONE MAI EK, LATIN SMALL LETTER B
+0061 0F74 0F72 0F71 0F72 0062;0061 0F71 0F72 0F72 0F74 0062;0061 0F71 0F72 0F72 0F74 0062;0061 0F71 0F72 0F72 0F74 0062;0061 0F71 0F72 0F72 0F74 0062; # (a◌ུ◌ི◌ཱ◌ིb; a◌ཱ◌ི◌ི◌ུb; a◌ཱ◌ི◌ི◌ུb; a◌ཱ◌ི◌ི◌ུb; a◌ཱ◌ི◌ི◌ུb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN U, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN AA, TIBETAN VOWEL SIGN I, LATIN SMALL LETTER B
+0061 0F72 0F74 0F72 0F71 0062;0061 0F71 0F72 0F72 0F74 0062;0061 0F71 0F72 0F72 0F74 0062;0061 0F71 0F72 0F72 0F74 0062;0061 0F71 0F72 0F72 0F74 0062; # (a◌ི◌ུ◌ི◌ཱb; a◌ཱ◌ི◌ི◌ུb; a◌ཱ◌ི◌ི◌ུb; a◌ཱ◌ི◌ི◌ུb; a◌ཱ◌ི◌ི◌ུb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN U, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN AA, LATIN SMALL LETTER B
+0061 0321 0F74 0F72 0F74 0062;0061 0F72 0F74 0F74 0321 0062;0061 0F72 0F74 0F74 0321 0062;0061 0F72 0F74 0F74 0321 0062;0061 0F72 0F74 0F74 0321 0062; # (a◌̡◌ུ◌ི◌ུb; a◌ི◌ུ◌ུ◌̡b; a◌ི◌ུ◌ུ◌̡b; a◌ི◌ུ◌ུ◌̡b; a◌ི◌ུ◌ུ◌̡b; ) LATIN SMALL LETTER A, COMBINING PALATALIZED HOOK BELOW, TIBETAN VOWEL SIGN U, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN U, LATIN SMALL LETTER B
+0061 0F74 0321 0F74 0F72 0062;0061 0F72 0F74 0F74 0321 0062;0061 0F72 0F74 0F74 0321 0062;0061 0F72 0F74 0F74 0321 0062;0061 0F72 0F74 0F74 0321 0062; # (a◌ུ◌̡◌ུ◌ིb; a◌ི◌ུ◌ུ◌̡b; a◌ི◌ུ◌ུ◌̡b; a◌ི◌ུ◌ུ◌̡b; a◌ི◌ུ◌ུ◌̡b; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN U, COMBINING PALATALIZED HOOK BELOW, TIBETAN VOWEL SIGN U, TIBETAN VOWEL SIGN I, LATIN SMALL LETTER B
+0061 0F74 0F72 0F71 0F7A 0062;0061 0F71 0F72 0F7A 0F74 0062;0061 0F71 0F72 0F7A 0F74 0062;0061 0F71 0F72 0F7A 0F74 0062;0061 0F71 0F72 0F7A 0F74 0062; # (a◌ུ◌ི◌ཱ◌ེb; a◌ཱ◌ི◌ེ◌ུb; a◌ཱ◌ི◌ེ◌ུb; a◌ཱ◌ི◌ེ◌ུb; a◌ཱ◌ི◌ེ◌ུb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN U, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN AA, TIBETAN VOWEL SIGN E, LATIN SMALL LETTER B
+0061 0F7A 0F74 0F72 0F71 0062;0061 0F71 0F7A 0F72 0F74 0062;0061 0F71 0F7A 0F72 0F74 0062;0061 0F71 0F7A 0F72 0F74 0062;0061 0F71 0F7A 0F72 0F74 0062; # (a◌ེ◌ུ◌ི◌ཱb; a◌ཱ◌ེ◌ི◌ུb; a◌ཱ◌ེ◌ི◌ུb; a◌ཱ◌ེ◌ི◌ུb; a◌ཱ◌ེ◌ི◌ུb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN E, TIBETAN VOWEL SIGN U, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN AA, LATIN SMALL LETTER B
+0061 0F74 0F72 0F71 0F7B 0062;0061 0F71 0F72 0F7B 0F74 0062;0061 0F71 0F72 0F7B 0F74 0062;0061 0F71 0F72 0F7B 0F74 0062;0061 0F71 0F72 0F7B 0F74 0062; # (a◌ུ◌ི◌ཱ◌ཻb; a◌ཱ◌ི◌ཻ◌ུb; a◌ཱ◌ི◌ཻ◌ུb; a◌ཱ◌ི◌ཻ◌ུb; a◌ཱ◌ི◌ཻ◌ུb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN U, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN AA, TIBETAN VOWEL SIGN EE, LATIN SMALL LETTER B
+0061 0F7B 0F74 0F72 0F71 0062;0061 0F71 0F7B 0F72 0F74 0062;0061 0F71 0F7B 0F72 0F74 0062;0061 0F71 0F7B 0F72 0F74 0062;0061 0F71 0F7B 0F72 0F74 0062; # (a◌ཻ◌ུ◌ི◌ཱb; a◌ཱ◌ཻ◌ི◌ུb; a◌ཱ◌ཻ◌ི◌ུb; a◌ཱ◌ཻ◌ི◌ུb; a◌ཱ◌ཻ◌ི◌ུb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN EE, TIBETAN VOWEL SIGN U, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN AA, LATIN SMALL LETTER B
+0061 0F74 0F72 0F71 0F7C 0062;0061 0F71 0F72 0F7C 0F74 0062;0061 0F71 0F72 0F7C 0F74 0062;0061 0F71 0F72 0F7C 0F74 0062;0061 0F71 0F72 0F7C 0F74 0062; # (a◌ུ◌ི◌ཱ◌ོb; a◌ཱ◌ི◌ོ◌ུb; a◌ཱ◌ི◌ོ◌ུb; a◌ཱ◌ི◌ོ◌ུb; a◌ཱ◌ི◌ོ◌ུb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN U, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN AA, TIBETAN VOWEL SIGN O, LATIN SMALL LETTER B
+0061 0F7C 0F74 0F72 0F71 0062;0061 0F71 0F7C 0F72 0F74 0062;0061 0F71 0F7C 0F72 0F74 0062;0061 0F71 0F7C 0F72 0F74 0062;0061 0F71 0F7C 0F72 0F74 0062; # (a◌ོ◌ུ◌ི◌ཱb; a◌ཱ◌ོ◌ི◌ུb; a◌ཱ◌ོ◌ི◌ུb; a◌ཱ◌ོ◌ི◌ུb; a◌ཱ◌ོ◌ི◌ུb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN O, TIBETAN VOWEL SIGN U, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN AA, LATIN SMALL LETTER B
+0061 0F74 0F72 0F71 0F7D 0062;0061 0F71 0F72 0F7D 0F74 0062;0061 0F71 0F72 0F7D 0F74 0062;0061 0F71 0F72 0F7D 0F74 0062;0061 0F71 0F72 0F7D 0F74 0062; # (a◌ུ◌ི◌ཱ◌ཽb; a◌ཱ◌ི◌ཽ◌ུb; a◌ཱ◌ི◌ཽ◌ུb; a◌ཱ◌ི◌ཽ◌ུb; a◌ཱ◌ི◌ཽ◌ུb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN U, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN AA, TIBETAN VOWEL SIGN OO, LATIN SMALL LETTER B
+0061 0F7D 0F74 0F72 0F71 0062;0061 0F71 0F7D 0F72 0F74 0062;0061 0F71 0F7D 0F72 0F74 0062;0061 0F71 0F7D 0F72 0F74 0062;0061 0F71 0F7D 0F72 0F74 0062; # (a◌ཽ◌ུ◌ི◌ཱb; a◌ཱ◌ཽ◌ི◌ུb; a◌ཱ◌ཽ◌ི◌ུb; a◌ཱ◌ཽ◌ི◌ུb; a◌ཱ◌ཽ◌ི◌ུb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN OO, TIBETAN VOWEL SIGN U, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN AA, LATIN SMALL LETTER B
+0061 0F74 0F72 0F71 0F80 0062;0061 0F71 0F72 0F80 0F74 0062;0061 0F71 0F72 0F80 0F74 0062;0061 0F71 0F72 0F80 0F74 0062;0061 0F71 0F72 0F80 0F74 0062; # (a◌ུ◌ི◌ཱ◌ྀb; a◌ཱ◌ི◌ྀ◌ུb; a◌ཱ◌ི◌ྀ◌ུb; a◌ཱ◌ི◌ྀ◌ུb; a◌ཱ◌ི◌ྀ◌ུb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN U, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN AA, TIBETAN VOWEL SIGN REVERSED I, LATIN SMALL LETTER B
+0061 0F80 0F74 0F72 0F71 0062;0061 0F71 0F80 0F72 0F74 0062;0061 0F71 0F80 0F72 0F74 0062;0061 0F71 0F80 0F72 0F74 0062;0061 0F71 0F80 0F72 0F74 0062; # (a◌ྀ◌ུ◌ི◌ཱb; a◌ཱ◌ྀ◌ི◌ུb; a◌ཱ◌ྀ◌ི◌ུb; a◌ཱ◌ྀ◌ི◌ུb; a◌ཱ◌ྀ◌ི◌ུb; ) LATIN SMALL LETTER A, TIBETAN VOWEL SIGN REVERSED I, TIBETAN VOWEL SIGN U, TIBETAN VOWEL SIGN I, TIBETAN VOWEL SIGN AA, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0F82 0062;00E0 05AE 0F82 0315 0062;0061 05AE 0300 0F82 0315 0062;00E0 05AE 0F82 0315 0062;0061 05AE 0300 0F82 0315 0062; # (a◌̕◌̀◌֮◌ྂb; à◌֮◌ྂ◌̕b; a◌֮◌̀◌ྂ◌̕b; à◌֮◌ྂ◌̕b; a◌֮◌̀◌ྂ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, TIBETAN SIGN NYI ZLA NAA DA, LATIN SMALL LETTER B
+0061 0F82 0315 0300 05AE 0062;0061 05AE 0F82 0300 0315 0062;0061 05AE 0F82 0300 0315 0062;0061 05AE 0F82 0300 0315 0062;0061 05AE 0F82 0300 0315 0062; # (a◌ྂ◌̕◌̀◌֮b; a◌֮◌ྂ◌̀◌̕b; a◌֮◌ྂ◌̀◌̕b; a◌֮◌ྂ◌̀◌̕b; a◌֮◌ྂ◌̀◌̕b; ) LATIN SMALL LETTER A, TIBETAN SIGN NYI ZLA NAA DA, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0F83 0062;00E0 05AE 0F83 0315 0062;0061 05AE 0300 0F83 0315 0062;00E0 05AE 0F83 0315 0062;0061 05AE 0300 0F83 0315 0062; # (a◌̕◌̀◌֮◌ྃb; à◌֮◌ྃ◌̕b; a◌֮◌̀◌ྃ◌̕b; à◌֮◌ྃ◌̕b; a◌֮◌̀◌ྃ◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, TIBETAN SIGN SNA LDAN, LATIN SMALL LETTER B
+0061 0F83 0315 0300 05AE 0062;0061 05AE 0F83 0300 0315 0062;0061 05AE 0F83 0300 0315 0062;0061 05AE 0F83 0300 0315 0062;0061 05AE 0F83 0300 0315 0062; # (a◌ྃ◌̕◌̀◌֮b; a◌֮◌ྃ◌̀◌̕b; a◌֮◌ྃ◌̀◌̕b; a◌֮◌ྃ◌̀◌̕b; a◌֮◌ྃ◌̀◌̕b; ) LATIN SMALL LETTER A, TIBETAN SIGN SNA LDAN, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 05B0 094D 3099 0F84 0062;0061 3099 094D 0F84 05B0 0062;0061 3099 094D 0F84 05B0 0062;0061 3099 094D 0F84 05B0 0062;0061 3099 094D 0F84 05B0 0062; # (a◌ְ◌्◌゙◌྄b; a◌゙◌्◌྄◌ְb; a◌゙◌्◌྄◌ְb; a◌゙◌्◌྄◌ְb; a◌゙◌्◌྄◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, TIBETAN MARK HALANTA, LATIN SMALL LETTER B
+0061 0F84 05B0 094D 3099 0062;0061 3099 0F84 094D 05B0 0062;0061 3099 0F84 094D 05B0 0062;0061 3099 0F84 094D 05B0 0062;0061 3099 0F84 094D 05B0 0062; # (a◌྄◌ְ◌्◌゙b; a◌゙◌྄◌्◌ְb; a◌゙◌྄◌्◌ְb; a◌゙◌྄◌्◌ְb; a◌゙◌྄◌्◌ְb; ) LATIN SMALL LETTER A, TIBETAN MARK HALANTA, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0F86 0062;00E0 05AE 0F86 0315 0062;0061 05AE 0300 0F86 0315 0062;00E0 05AE 0F86 0315 0062;0061 05AE 0300 0F86 0315 0062; # (a◌̕◌̀◌֮◌྆b; à◌֮◌྆◌̕b; a◌֮◌̀◌྆◌̕b; à◌֮◌྆◌̕b; a◌֮◌̀◌྆◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, TIBETAN SIGN LCI RTAGS, LATIN SMALL LETTER B
+0061 0F86 0315 0300 05AE 0062;0061 05AE 0F86 0300 0315 0062;0061 05AE 0F86 0300 0315 0062;0061 05AE 0F86 0300 0315 0062;0061 05AE 0F86 0300 0315 0062; # (a◌྆◌̕◌̀◌֮b; a◌֮◌྆◌̀◌̕b; a◌֮◌྆◌̀◌̕b; a◌֮◌྆◌̀◌̕b; a◌֮◌྆◌̀◌̕b; ) LATIN SMALL LETTER A, TIBETAN SIGN LCI RTAGS, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 0F87 0062;00E0 05AE 0F87 0315 0062;0061 05AE 0300 0F87 0315 0062;00E0 05AE 0F87 0315 0062;0061 05AE 0300 0F87 0315 0062; # (a◌̕◌̀◌֮◌྇b; à◌֮◌྇◌̕b; a◌֮◌̀◌྇◌̕b; à◌֮◌྇◌̕b; a◌֮◌̀◌྇◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, TIBETAN SIGN YANG RTAGS, LATIN SMALL LETTER B
+0061 0F87 0315 0300 05AE 0062;0061 05AE 0F87 0300 0315 0062;0061 05AE 0F87 0300 0315 0062;0061 05AE 0F87 0300 0315 0062;0061 05AE 0F87 0300 0315 0062; # (a◌྇◌̕◌̀◌֮b; a◌֮◌྇◌̀◌̕b; a◌֮◌྇◌̀◌̕b; a◌֮◌྇◌̀◌̕b; a◌֮◌྇◌̀◌̕b; ) LATIN SMALL LETTER A, TIBETAN SIGN YANG RTAGS, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 0FC6 0062;0061 302A 0316 0FC6 059A 0062;0061 302A 0316 0FC6 059A 0062;0061 302A 0316 0FC6 059A 0062;0061 302A 0316 0FC6 059A 0062; # (a◌֚◌̖◌〪◌࿆b; a◌〪◌̖◌࿆◌֚b; a◌〪◌̖◌࿆◌֚b; a◌〪◌̖◌࿆◌֚b; a◌〪◌̖◌࿆◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, TIBETAN SYMBOL PADMA GDAN, LATIN SMALL LETTER B
+0061 0FC6 059A 0316 302A 0062;0061 302A 0FC6 0316 059A 0062;0061 302A 0FC6 0316 059A 0062;0061 302A 0FC6 0316 059A 0062;0061 302A 0FC6 0316 059A 0062; # (a◌࿆◌֚◌̖◌〪b; a◌〪◌࿆◌̖◌֚b; a◌〪◌࿆◌̖◌֚b; a◌〪◌࿆◌̖◌֚b; a◌〪◌࿆◌̖◌֚b; ) LATIN SMALL LETTER A, TIBETAN SYMBOL PADMA GDAN, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 3099 093C 0334 1037 0062;0061 0334 093C 1037 3099 0062;0061 0334 093C 1037 3099 0062;0061 0334 093C 1037 3099 0062;0061 0334 093C 1037 3099 0062; # (a◌゙◌़◌̴◌့b; a◌̴◌़◌့◌゙b; a◌̴◌़◌့◌゙b; a◌̴◌़◌့◌゙b; a◌̴◌़◌့◌゙b; ) LATIN SMALL LETTER A, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, MYANMAR SIGN DOT BELOW, LATIN SMALL LETTER B
+0061 1037 3099 093C 0334 0062;0061 0334 1037 093C 3099 0062;0061 0334 1037 093C 3099 0062;0061 0334 1037 093C 3099 0062;0061 0334 1037 093C 3099 0062; # (a◌့◌゙◌़◌̴b; a◌̴◌့◌़◌゙b; a◌̴◌့◌़◌゙b; a◌̴◌့◌़◌゙b; a◌̴◌့◌़◌゙b; ) LATIN SMALL LETTER A, MYANMAR SIGN DOT BELOW, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 05B0 094D 3099 1039 0062;0061 3099 094D 1039 05B0 0062;0061 3099 094D 1039 05B0 0062;0061 3099 094D 1039 05B0 0062;0061 3099 094D 1039 05B0 0062; # (a◌ְ◌्◌゙◌္b; a◌゙◌्◌္◌ְb; a◌゙◌्◌္◌ְb; a◌゙◌्◌္◌ְb; a◌゙◌्◌္◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, MYANMAR SIGN VIRAMA, LATIN SMALL LETTER B
+0061 1039 05B0 094D 3099 0062;0061 3099 1039 094D 05B0 0062;0061 3099 1039 094D 05B0 0062;0061 3099 1039 094D 05B0 0062;0061 3099 1039 094D 05B0 0062; # (a◌္◌ְ◌्◌゙b; a◌゙◌္◌्◌ְb; a◌゙◌္◌्◌ְb; a◌゙◌္◌्◌ְb; a◌゙◌္◌्◌ְb; ) LATIN SMALL LETTER A, MYANMAR SIGN VIRAMA, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 05B0 094D 3099 1714 0062;0061 3099 094D 1714 05B0 0062;0061 3099 094D 1714 05B0 0062;0061 3099 094D 1714 05B0 0062;0061 3099 094D 1714 05B0 0062; # (a◌ְ◌्◌゙◌᜔b; a◌゙◌्◌᜔◌ְb; a◌゙◌्◌᜔◌ְb; a◌゙◌्◌᜔◌ְb; a◌゙◌्◌᜔◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, TAGALOG SIGN VIRAMA, LATIN SMALL LETTER B
+0061 1714 05B0 094D 3099 0062;0061 3099 1714 094D 05B0 0062;0061 3099 1714 094D 05B0 0062;0061 3099 1714 094D 05B0 0062;0061 3099 1714 094D 05B0 0062; # (a◌᜔◌ְ◌्◌゙b; a◌゙◌᜔◌्◌ְb; a◌゙◌᜔◌्◌ְb; a◌゙◌᜔◌्◌ְb; a◌゙◌᜔◌्◌ְb; ) LATIN SMALL LETTER A, TAGALOG SIGN VIRAMA, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 05B0 094D 3099 1734 0062;0061 3099 094D 1734 05B0 0062;0061 3099 094D 1734 05B0 0062;0061 3099 094D 1734 05B0 0062;0061 3099 094D 1734 05B0 0062; # (a◌ְ◌्◌゙◌᜴b; a◌゙◌्◌᜴◌ְb; a◌゙◌्◌᜴◌ְb; a◌゙◌्◌᜴◌ְb; a◌゙◌्◌᜴◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, HANUNOO SIGN PAMUDPOD, LATIN SMALL LETTER B
+0061 1734 05B0 094D 3099 0062;0061 3099 1734 094D 05B0 0062;0061 3099 1734 094D 05B0 0062;0061 3099 1734 094D 05B0 0062;0061 3099 1734 094D 05B0 0062; # (a◌᜴◌ְ◌्◌゙b; a◌゙◌᜴◌्◌ְb; a◌゙◌᜴◌्◌ְb; a◌゙◌᜴◌्◌ְb; a◌゙◌᜴◌्◌ְb; ) LATIN SMALL LETTER A, HANUNOO SIGN PAMUDPOD, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 05B0 094D 3099 17D2 0062;0061 3099 094D 17D2 05B0 0062;0061 3099 094D 17D2 05B0 0062;0061 3099 094D 17D2 05B0 0062;0061 3099 094D 17D2 05B0 0062; # (a◌ְ◌्◌゙◌្b; a◌゙◌्◌្◌ְb; a◌゙◌्◌្◌ְb; a◌゙◌्◌្◌ְb; a◌゙◌्◌្◌ְb; ) LATIN SMALL LETTER A, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, KHMER SIGN COENG, LATIN SMALL LETTER B
+0061 17D2 05B0 094D 3099 0062;0061 3099 17D2 094D 05B0 0062;0061 3099 17D2 094D 05B0 0062;0061 3099 17D2 094D 05B0 0062;0061 3099 17D2 094D 05B0 0062; # (a◌្◌ְ◌्◌゙b; a◌゙◌្◌्◌ְb; a◌゙◌្◌्◌ְb; a◌゙◌្◌्◌ְb; a◌゙◌្◌्◌ְb; ) LATIN SMALL LETTER A, KHMER SIGN COENG, HEBREW POINT SHEVA, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 17DD 0062;00E0 05AE 17DD 0315 0062;0061 05AE 0300 17DD 0315 0062;00E0 05AE 17DD 0315 0062;0061 05AE 0300 17DD 0315 0062; # (a◌̕◌̀◌֮◌៝b; à◌֮◌៝◌̕b; a◌֮◌̀◌៝◌̕b; à◌֮◌៝◌̕b; a◌֮◌̀◌៝◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, KHMER SIGN ATTHACAN, LATIN SMALL LETTER B
+0061 17DD 0315 0300 05AE 0062;0061 05AE 17DD 0300 0315 0062;0061 05AE 17DD 0300 0315 0062;0061 05AE 17DD 0300 0315 0062;0061 05AE 17DD 0300 0315 0062; # (a◌៝◌̕◌̀◌֮b; a◌֮◌៝◌̀◌̕b; a◌֮◌៝◌̀◌̕b; a◌֮◌៝◌̀◌̕b; a◌֮◌៝◌̀◌̕b; ) LATIN SMALL LETTER A, KHMER SIGN ATTHACAN, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0300 05AE 1D16D 18A9 0062;00E0 1D16D 05AE 18A9 0062;0061 1D16D 05AE 18A9 0300 0062;00E0 1D16D 05AE 18A9 0062;0061 1D16D 05AE 18A9 0300 0062; # (a◌̀◌𝅭𝅭֮◌ᢩb; à𝅭𝅭◌֮◌ᢩb; a𝅭𝅭◌֮◌ᢩ◌̀b; à𝅭𝅭◌֮◌ᢩb; a𝅭𝅭◌֮◌ᢩ◌̀b; ) LATIN SMALL LETTER A, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING AUGMENTATION DOT, MONGOLIAN LETTER ALI GALI DAGALGA, LATIN SMALL LETTER B
+0061 18A9 0300 05AE 1D16D 0062;00E0 1D16D 18A9 05AE 0062;0061 1D16D 18A9 05AE 0300 0062;00E0 1D16D 18A9 05AE 0062;0061 1D16D 18A9 05AE 0300 0062; # (a◌ᢩ◌̀◌𝅭𝅭֮b; à𝅭𝅭◌ᢩ◌֮b; a𝅭𝅭◌ᢩ◌֮◌̀b; à𝅭𝅭◌ᢩ◌֮b; a𝅭𝅭◌ᢩ◌֮◌̀b; ) LATIN SMALL LETTER A, MONGOLIAN LETTER ALI GALI DAGALGA, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING AUGMENTATION DOT, LATIN SMALL LETTER B
+0061 302E 059A 0316 1939 0062;0061 0316 059A 1939 302E 0062;0061 0316 059A 1939 302E 0062;0061 0316 059A 1939 302E 0062;0061 0316 059A 1939 302E 0062; # (a◌〮◌֚◌̖◌᤹b; a◌̖◌֚◌᤹◌〮b; a◌̖◌֚◌᤹◌〮b; a◌̖◌֚◌᤹◌〮b; a◌̖◌֚◌᤹◌〮b; ) LATIN SMALL LETTER A, HANGUL SINGLE DOT TONE MARK, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, LIMBU SIGN MUKPHRENG, LATIN SMALL LETTER B
+0061 1939 302E 059A 0316 0062;0061 0316 1939 059A 302E 0062;0061 0316 1939 059A 302E 0062;0061 0316 1939 059A 302E 0062;0061 0316 1939 059A 302E 0062; # (a◌᤹◌〮◌֚◌̖b; a◌̖◌᤹◌֚◌〮b; a◌̖◌᤹◌֚◌〮b; a◌̖◌᤹◌֚◌〮b; a◌̖◌᤹◌֚◌〮b; ) LATIN SMALL LETTER A, LIMBU SIGN MUKPHRENG, HANGUL SINGLE DOT TONE MARK, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, LATIN SMALL LETTER B
+0061 0315 0300 05AE 193A 0062;00E0 05AE 193A 0315 0062;0061 05AE 0300 193A 0315 0062;00E0 05AE 193A 0315 0062;0061 05AE 0300 193A 0315 0062; # (a◌̕◌̀◌֮◌᤺b; à◌֮◌᤺◌̕b; a◌֮◌̀◌᤺◌̕b; à◌֮◌᤺◌̕b; a◌֮◌̀◌᤺◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LIMBU SIGN KEMPHRENG, LATIN SMALL LETTER B
+0061 193A 0315 0300 05AE 0062;0061 05AE 193A 0300 0315 0062;0061 05AE 193A 0300 0315 0062;0061 05AE 193A 0300 0315 0062;0061 05AE 193A 0300 0315 0062; # (a◌᤺◌̕◌̀◌֮b; a◌֮◌᤺◌̀◌̕b; a◌֮◌᤺◌̀◌̕b; a◌֮◌᤺◌̀◌̕b; a◌֮◌᤺◌̀◌̕b; ) LATIN SMALL LETTER A, LIMBU SIGN KEMPHRENG, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 193B 0062;0061 302A 0316 193B 059A 0062;0061 302A 0316 193B 059A 0062;0061 302A 0316 193B 059A 0062;0061 302A 0316 193B 059A 0062; # (a◌֚◌̖◌〪◌᤻b; a◌〪◌̖◌᤻◌֚b; a◌〪◌̖◌᤻◌֚b; a◌〪◌̖◌᤻◌֚b; a◌〪◌̖◌᤻◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LIMBU SIGN SA-I, LATIN SMALL LETTER B
+0061 193B 059A 0316 302A 0062;0061 302A 193B 0316 059A 0062;0061 302A 193B 0316 059A 0062;0061 302A 193B 0316 059A 0062;0061 302A 193B 0316 059A 0062; # (a◌᤻◌֚◌̖◌〪b; a◌〪◌᤻◌̖◌֚b; a◌〪◌᤻◌̖◌֚b; a◌〪◌᤻◌̖◌֚b; a◌〪◌᤻◌̖◌֚b; ) LATIN SMALL LETTER A, LIMBU SIGN SA-I, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 20D0 0062;00E0 05AE 20D0 0315 0062;0061 05AE 0300 20D0 0315 0062;00E0 05AE 20D0 0315 0062;0061 05AE 0300 20D0 0315 0062; # (a◌̕◌̀◌֮◌⃐b; à◌֮◌⃐◌̕b; a◌֮◌̀◌⃐◌̕b; à◌֮◌⃐◌̕b; a◌֮◌̀◌⃐◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LEFT HARPOON ABOVE, LATIN SMALL LETTER B
+0061 20D0 0315 0300 05AE 0062;0061 05AE 20D0 0300 0315 0062;0061 05AE 20D0 0300 0315 0062;0061 05AE 20D0 0300 0315 0062;0061 05AE 20D0 0300 0315 0062; # (a◌⃐◌̕◌̀◌֮b; a◌֮◌⃐◌̀◌̕b; a◌֮◌⃐◌̀◌̕b; a◌֮◌⃐◌̀◌̕b; a◌֮◌⃐◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LEFT HARPOON ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 20D1 0062;00E0 05AE 20D1 0315 0062;0061 05AE 0300 20D1 0315 0062;00E0 05AE 20D1 0315 0062;0061 05AE 0300 20D1 0315 0062; # (a◌̕◌̀◌֮◌⃑b; à◌֮◌⃑◌̕b; a◌֮◌̀◌⃑◌̕b; à◌֮◌⃑◌̕b; a◌֮◌̀◌⃑◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING RIGHT HARPOON ABOVE, LATIN SMALL LETTER B
+0061 20D1 0315 0300 05AE 0062;0061 05AE 20D1 0300 0315 0062;0061 05AE 20D1 0300 0315 0062;0061 05AE 20D1 0300 0315 0062;0061 05AE 20D1 0300 0315 0062; # (a◌⃑◌̕◌̀◌֮b; a◌֮◌⃑◌̀◌̕b; a◌֮◌⃑◌̀◌̕b; a◌֮◌⃑◌̀◌̕b; a◌֮◌⃑◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING RIGHT HARPOON ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 093C 0334 20D2 0062;0061 0334 20D2 093C 0062;0061 0334 20D2 093C 0062;0061 0334 20D2 093C 0062;0061 0334 20D2 093C 0062; # (a◌़◌̴◌⃒b; a◌̴◌⃒◌़b; a◌̴◌⃒◌़b; a◌̴◌⃒◌़b; a◌̴◌⃒◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, COMBINING LONG VERTICAL LINE OVERLAY, LATIN SMALL LETTER B
+0061 20D2 093C 0334 0062;0061 20D2 0334 093C 0062;0061 20D2 0334 093C 0062;0061 20D2 0334 093C 0062;0061 20D2 0334 093C 0062; # (a◌⃒◌़◌̴b; a◌⃒◌̴◌़b; a◌⃒◌̴◌़b; a◌⃒◌̴◌़b; a◌⃒◌̴◌़b; ) LATIN SMALL LETTER A, COMBINING LONG VERTICAL LINE OVERLAY, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 093C 0334 20D3 0062;0061 0334 20D3 093C 0062;0061 0334 20D3 093C 0062;0061 0334 20D3 093C 0062;0061 0334 20D3 093C 0062; # (a◌़◌̴◌⃓b; a◌̴◌⃓◌़b; a◌̴◌⃓◌़b; a◌̴◌⃓◌़b; a◌̴◌⃓◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, COMBINING SHORT VERTICAL LINE OVERLAY, LATIN SMALL LETTER B
+0061 20D3 093C 0334 0062;0061 20D3 0334 093C 0062;0061 20D3 0334 093C 0062;0061 20D3 0334 093C 0062;0061 20D3 0334 093C 0062; # (a◌⃓◌़◌̴b; a◌⃓◌̴◌़b; a◌⃓◌̴◌़b; a◌⃓◌̴◌़b; a◌⃓◌̴◌़b; ) LATIN SMALL LETTER A, COMBINING SHORT VERTICAL LINE OVERLAY, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 0315 0300 05AE 20D4 0062;00E0 05AE 20D4 0315 0062;0061 05AE 0300 20D4 0315 0062;00E0 05AE 20D4 0315 0062;0061 05AE 0300 20D4 0315 0062; # (a◌̕◌̀◌֮◌⃔b; à◌֮◌⃔◌̕b; a◌֮◌̀◌⃔◌̕b; à◌֮◌⃔◌̕b; a◌֮◌̀◌⃔◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING ANTICLOCKWISE ARROW ABOVE, LATIN SMALL LETTER B
+0061 20D4 0315 0300 05AE 0062;0061 05AE 20D4 0300 0315 0062;0061 05AE 20D4 0300 0315 0062;0061 05AE 20D4 0300 0315 0062;0061 05AE 20D4 0300 0315 0062; # (a◌⃔◌̕◌̀◌֮b; a◌֮◌⃔◌̀◌̕b; a◌֮◌⃔◌̀◌̕b; a◌֮◌⃔◌̀◌̕b; a◌֮◌⃔◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING ANTICLOCKWISE ARROW ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 20D5 0062;00E0 05AE 20D5 0315 0062;0061 05AE 0300 20D5 0315 0062;00E0 05AE 20D5 0315 0062;0061 05AE 0300 20D5 0315 0062; # (a◌̕◌̀◌֮◌⃕b; à◌֮◌⃕◌̕b; a◌֮◌̀◌⃕◌̕b; à◌֮◌⃕◌̕b; a◌֮◌̀◌⃕◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING CLOCKWISE ARROW ABOVE, LATIN SMALL LETTER B
+0061 20D5 0315 0300 05AE 0062;0061 05AE 20D5 0300 0315 0062;0061 05AE 20D5 0300 0315 0062;0061 05AE 20D5 0300 0315 0062;0061 05AE 20D5 0300 0315 0062; # (a◌⃕◌̕◌̀◌֮b; a◌֮◌⃕◌̀◌̕b; a◌֮◌⃕◌̀◌̕b; a◌֮◌⃕◌̀◌̕b; a◌֮◌⃕◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING CLOCKWISE ARROW ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 20D6 0062;00E0 05AE 20D6 0315 0062;0061 05AE 0300 20D6 0315 0062;00E0 05AE 20D6 0315 0062;0061 05AE 0300 20D6 0315 0062; # (a◌̕◌̀◌֮◌⃖b; à◌֮◌⃖◌̕b; a◌֮◌̀◌⃖◌̕b; à◌֮◌⃖◌̕b; a◌֮◌̀◌⃖◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LEFT ARROW ABOVE, LATIN SMALL LETTER B
+0061 20D6 0315 0300 05AE 0062;0061 05AE 20D6 0300 0315 0062;0061 05AE 20D6 0300 0315 0062;0061 05AE 20D6 0300 0315 0062;0061 05AE 20D6 0300 0315 0062; # (a◌⃖◌̕◌̀◌֮b; a◌֮◌⃖◌̀◌̕b; a◌֮◌⃖◌̀◌̕b; a◌֮◌⃖◌̀◌̕b; a◌֮◌⃖◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LEFT ARROW ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 20D7 0062;00E0 05AE 20D7 0315 0062;0061 05AE 0300 20D7 0315 0062;00E0 05AE 20D7 0315 0062;0061 05AE 0300 20D7 0315 0062; # (a◌̕◌̀◌֮◌⃗b; à◌֮◌⃗◌̕b; a◌֮◌̀◌⃗◌̕b; à◌֮◌⃗◌̕b; a◌֮◌̀◌⃗◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING RIGHT ARROW ABOVE, LATIN SMALL LETTER B
+0061 20D7 0315 0300 05AE 0062;0061 05AE 20D7 0300 0315 0062;0061 05AE 20D7 0300 0315 0062;0061 05AE 20D7 0300 0315 0062;0061 05AE 20D7 0300 0315 0062; # (a◌⃗◌̕◌̀◌֮b; a◌֮◌⃗◌̀◌̕b; a◌֮◌⃗◌̀◌̕b; a◌֮◌⃗◌̀◌̕b; a◌֮◌⃗◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING RIGHT ARROW ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 093C 0334 20D8 0062;0061 0334 20D8 093C 0062;0061 0334 20D8 093C 0062;0061 0334 20D8 093C 0062;0061 0334 20D8 093C 0062; # (a◌़◌̴◌⃘b; a◌̴◌⃘◌़b; a◌̴◌⃘◌़b; a◌̴◌⃘◌़b; a◌̴◌⃘◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, COMBINING RING OVERLAY, LATIN SMALL LETTER B
+0061 20D8 093C 0334 0062;0061 20D8 0334 093C 0062;0061 20D8 0334 093C 0062;0061 20D8 0334 093C 0062;0061 20D8 0334 093C 0062; # (a◌⃘◌़◌̴b; a◌⃘◌̴◌़b; a◌⃘◌̴◌़b; a◌⃘◌̴◌़b; a◌⃘◌̴◌़b; ) LATIN SMALL LETTER A, COMBINING RING OVERLAY, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 093C 0334 20D9 0062;0061 0334 20D9 093C 0062;0061 0334 20D9 093C 0062;0061 0334 20D9 093C 0062;0061 0334 20D9 093C 0062; # (a◌़◌̴◌⃙b; a◌̴◌⃙◌़b; a◌̴◌⃙◌़b; a◌̴◌⃙◌़b; a◌̴◌⃙◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, COMBINING CLOCKWISE RING OVERLAY, LATIN SMALL LETTER B
+0061 20D9 093C 0334 0062;0061 20D9 0334 093C 0062;0061 20D9 0334 093C 0062;0061 20D9 0334 093C 0062;0061 20D9 0334 093C 0062; # (a◌⃙◌़◌̴b; a◌⃙◌̴◌़b; a◌⃙◌̴◌़b; a◌⃙◌̴◌़b; a◌⃙◌̴◌़b; ) LATIN SMALL LETTER A, COMBINING CLOCKWISE RING OVERLAY, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 093C 0334 20DA 0062;0061 0334 20DA 093C 0062;0061 0334 20DA 093C 0062;0061 0334 20DA 093C 0062;0061 0334 20DA 093C 0062; # (a◌़◌̴◌⃚b; a◌̴◌⃚◌़b; a◌̴◌⃚◌़b; a◌̴◌⃚◌़b; a◌̴◌⃚◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, COMBINING ANTICLOCKWISE RING OVERLAY, LATIN SMALL LETTER B
+0061 20DA 093C 0334 0062;0061 20DA 0334 093C 0062;0061 20DA 0334 093C 0062;0061 20DA 0334 093C 0062;0061 20DA 0334 093C 0062; # (a◌⃚◌़◌̴b; a◌⃚◌̴◌़b; a◌⃚◌̴◌़b; a◌⃚◌̴◌़b; a◌⃚◌̴◌़b; ) LATIN SMALL LETTER A, COMBINING ANTICLOCKWISE RING OVERLAY, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 0315 0300 05AE 20DB 0062;00E0 05AE 20DB 0315 0062;0061 05AE 0300 20DB 0315 0062;00E0 05AE 20DB 0315 0062;0061 05AE 0300 20DB 0315 0062; # (a◌̕◌̀◌֮◌⃛b; à◌֮◌⃛◌̕b; a◌֮◌̀◌⃛◌̕b; à◌֮◌⃛◌̕b; a◌֮◌̀◌⃛◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING THREE DOTS ABOVE, LATIN SMALL LETTER B
+0061 20DB 0315 0300 05AE 0062;0061 05AE 20DB 0300 0315 0062;0061 05AE 20DB 0300 0315 0062;0061 05AE 20DB 0300 0315 0062;0061 05AE 20DB 0300 0315 0062; # (a◌⃛◌̕◌̀◌֮b; a◌֮◌⃛◌̀◌̕b; a◌֮◌⃛◌̀◌̕b; a◌֮◌⃛◌̀◌̕b; a◌֮◌⃛◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING THREE DOTS ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 20DC 0062;00E0 05AE 20DC 0315 0062;0061 05AE 0300 20DC 0315 0062;00E0 05AE 20DC 0315 0062;0061 05AE 0300 20DC 0315 0062; # (a◌̕◌̀◌֮◌⃜b; à◌֮◌⃜◌̕b; a◌֮◌̀◌⃜◌̕b; à◌֮◌⃜◌̕b; a◌֮◌̀◌⃜◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING FOUR DOTS ABOVE, LATIN SMALL LETTER B
+0061 20DC 0315 0300 05AE 0062;0061 05AE 20DC 0300 0315 0062;0061 05AE 20DC 0300 0315 0062;0061 05AE 20DC 0300 0315 0062;0061 05AE 20DC 0300 0315 0062; # (a◌⃜◌̕◌̀◌֮b; a◌֮◌⃜◌̀◌̕b; a◌֮◌⃜◌̀◌̕b; a◌֮◌⃜◌̀◌̕b; a◌֮◌⃜◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING FOUR DOTS ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 20E1 0062;00E0 05AE 20E1 0315 0062;0061 05AE 0300 20E1 0315 0062;00E0 05AE 20E1 0315 0062;0061 05AE 0300 20E1 0315 0062; # (a◌̕◌̀◌֮◌⃡b; à◌֮◌⃡◌̕b; a◌֮◌̀◌⃡◌̕b; à◌֮◌⃡◌̕b; a◌֮◌̀◌⃡◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LEFT RIGHT ARROW ABOVE, LATIN SMALL LETTER B
+0061 20E1 0315 0300 05AE 0062;0061 05AE 20E1 0300 0315 0062;0061 05AE 20E1 0300 0315 0062;0061 05AE 20E1 0300 0315 0062;0061 05AE 20E1 0300 0315 0062; # (a◌⃡◌̕◌̀◌֮b; a◌֮◌⃡◌̀◌̕b; a◌֮◌⃡◌̀◌̕b; a◌֮◌⃡◌̀◌̕b; a◌֮◌⃡◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LEFT RIGHT ARROW ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 093C 0334 20E5 0062;0061 0334 20E5 093C 0062;0061 0334 20E5 093C 0062;0061 0334 20E5 093C 0062;0061 0334 20E5 093C 0062; # (a◌़◌̴◌⃥b; a◌̴◌⃥◌़b; a◌̴◌⃥◌़b; a◌̴◌⃥◌़b; a◌̴◌⃥◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, COMBINING REVERSE SOLIDUS OVERLAY, LATIN SMALL LETTER B
+0061 20E5 093C 0334 0062;0061 20E5 0334 093C 0062;0061 20E5 0334 093C 0062;0061 20E5 0334 093C 0062;0061 20E5 0334 093C 0062; # (a◌⃥◌़◌̴b; a◌⃥◌̴◌़b; a◌⃥◌̴◌़b; a◌⃥◌̴◌़b; a◌⃥◌̴◌़b; ) LATIN SMALL LETTER A, COMBINING REVERSE SOLIDUS OVERLAY, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 093C 0334 20E6 0062;0061 0334 20E6 093C 0062;0061 0334 20E6 093C 0062;0061 0334 20E6 093C 0062;0061 0334 20E6 093C 0062; # (a◌़◌̴◌⃦b; a◌̴◌⃦◌़b; a◌̴◌⃦◌़b; a◌̴◌⃦◌़b; a◌̴◌⃦◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, COMBINING DOUBLE VERTICAL STROKE OVERLAY, LATIN SMALL LETTER B
+0061 20E6 093C 0334 0062;0061 20E6 0334 093C 0062;0061 20E6 0334 093C 0062;0061 20E6 0334 093C 0062;0061 20E6 0334 093C 0062; # (a◌⃦◌़◌̴b; a◌⃦◌̴◌़b; a◌⃦◌̴◌़b; a◌⃦◌̴◌़b; a◌⃦◌̴◌़b; ) LATIN SMALL LETTER A, COMBINING DOUBLE VERTICAL STROKE OVERLAY, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 0315 0300 05AE 20E7 0062;00E0 05AE 20E7 0315 0062;0061 05AE 0300 20E7 0315 0062;00E0 05AE 20E7 0315 0062;0061 05AE 0300 20E7 0315 0062; # (a◌̕◌̀◌֮◌⃧b; à◌֮◌⃧◌̕b; a◌֮◌̀◌⃧◌̕b; à◌֮◌⃧◌̕b; a◌֮◌̀◌⃧◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING ANNUITY SYMBOL, LATIN SMALL LETTER B
+0061 20E7 0315 0300 05AE 0062;0061 05AE 20E7 0300 0315 0062;0061 05AE 20E7 0300 0315 0062;0061 05AE 20E7 0300 0315 0062;0061 05AE 20E7 0300 0315 0062; # (a◌⃧◌̕◌̀◌֮b; a◌֮◌⃧◌̀◌̕b; a◌֮◌⃧◌̀◌̕b; a◌֮◌⃧◌̀◌̕b; a◌֮◌⃧◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING ANNUITY SYMBOL, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 20E8 0062;0061 302A 0316 20E8 059A 0062;0061 302A 0316 20E8 059A 0062;0061 302A 0316 20E8 059A 0062;0061 302A 0316 20E8 059A 0062; # (a◌֚◌̖◌〪◌⃨b; a◌〪◌̖◌⃨◌֚b; a◌〪◌̖◌⃨◌֚b; a◌〪◌̖◌⃨◌֚b; a◌〪◌̖◌⃨◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING TRIPLE UNDERDOT, LATIN SMALL LETTER B
+0061 20E8 059A 0316 302A 0062;0061 302A 20E8 0316 059A 0062;0061 302A 20E8 0316 059A 0062;0061 302A 20E8 0316 059A 0062;0061 302A 20E8 0316 059A 0062; # (a◌⃨◌֚◌̖◌〪b; a◌〪◌⃨◌̖◌֚b; a◌〪◌⃨◌̖◌֚b; a◌〪◌⃨◌̖◌֚b; a◌〪◌⃨◌̖◌֚b; ) LATIN SMALL LETTER A, COMBINING TRIPLE UNDERDOT, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 20E9 0062;00E0 05AE 20E9 0315 0062;0061 05AE 0300 20E9 0315 0062;00E0 05AE 20E9 0315 0062;0061 05AE 0300 20E9 0315 0062; # (a◌̕◌̀◌֮◌⃩b; à◌֮◌⃩◌̕b; a◌֮◌̀◌⃩◌̕b; à◌֮◌⃩◌̕b; a◌֮◌̀◌⃩◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING WIDE BRIDGE ABOVE, LATIN SMALL LETTER B
+0061 20E9 0315 0300 05AE 0062;0061 05AE 20E9 0300 0315 0062;0061 05AE 20E9 0300 0315 0062;0061 05AE 20E9 0300 0315 0062;0061 05AE 20E9 0300 0315 0062; # (a◌⃩◌̕◌̀◌֮b; a◌֮◌⃩◌̀◌̕b; a◌֮◌⃩◌̀◌̕b; a◌֮◌⃩◌̀◌̕b; a◌֮◌⃩◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING WIDE BRIDGE ABOVE, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 093C 0334 20EA 0062;0061 0334 20EA 093C 0062;0061 0334 20EA 093C 0062;0061 0334 20EA 093C 0062;0061 0334 20EA 093C 0062; # (a◌़◌̴◌⃪b; a◌̴◌⃪◌़b; a◌̴◌⃪◌़b; a◌̴◌⃪◌़b; a◌̴◌⃪◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, COMBINING LEFTWARDS ARROW OVERLAY, LATIN SMALL LETTER B
+0061 20EA 093C 0334 0062;0061 20EA 0334 093C 0062;0061 20EA 0334 093C 0062;0061 20EA 0334 093C 0062;0061 20EA 0334 093C 0062; # (a◌⃪◌़◌̴b; a◌⃪◌̴◌़b; a◌⃪◌̴◌़b; a◌⃪◌̴◌़b; a◌⃪◌̴◌़b; ) LATIN SMALL LETTER A, COMBINING LEFTWARDS ARROW OVERLAY, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 0316 302A 031B 302A 0062;0061 031B 302A 302A 0316 0062;0061 031B 302A 302A 0316 0062;0061 031B 302A 302A 0316 0062;0061 031B 302A 302A 0316 0062; # (a◌̖◌〪◌̛◌〪b; a◌̛◌〪◌〪◌̖b; a◌̛◌〪◌〪◌̖b; a◌̛◌〪◌〪◌̖b; a◌̛◌〪◌〪◌̖b; ) LATIN SMALL LETTER A, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 302A 0316 302A 031B 0062;0061 031B 302A 302A 0316 0062;0061 031B 302A 302A 0316 0062;0061 031B 302A 302A 0316 0062;0061 031B 302A 302A 0316 0062; # (a◌〪◌̖◌〪◌̛b; a◌̛◌〪◌〪◌̖b; a◌̛◌〪◌〪◌̖b; a◌̛◌〪◌〪◌̖b; a◌̛◌〪◌〪◌̖b; ) LATIN SMALL LETTER A, IDEOGRAPHIC LEVEL TONE MARK, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, LATIN SMALL LETTER B
+0061 0300 05AE 1D16D 302B 0062;00E0 1D16D 05AE 302B 0062;0061 1D16D 05AE 302B 0300 0062;00E0 1D16D 05AE 302B 0062;0061 1D16D 05AE 302B 0300 0062; # (a◌̀◌𝅭𝅭֮◌〫b; à𝅭𝅭◌֮◌〫b; a𝅭𝅭◌֮◌〫◌̀b; à𝅭𝅭◌֮◌〫b; a𝅭𝅭◌֮◌〫◌̀b; ) LATIN SMALL LETTER A, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING AUGMENTATION DOT, IDEOGRAPHIC RISING TONE MARK, LATIN SMALL LETTER B
+0061 302B 0300 05AE 1D16D 0062;00E0 1D16D 302B 05AE 0062;0061 1D16D 302B 05AE 0300 0062;00E0 1D16D 302B 05AE 0062;0061 1D16D 302B 05AE 0300 0062; # (a◌〫◌̀◌𝅭𝅭֮b; à𝅭𝅭◌〫◌֮b; a𝅭𝅭◌〫◌֮◌̀b; à𝅭𝅭◌〫◌֮b; a𝅭𝅭◌〫◌֮◌̀b; ) LATIN SMALL LETTER A, IDEOGRAPHIC RISING TONE MARK, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING AUGMENTATION DOT, LATIN SMALL LETTER B
+0061 035F 0315 0300 302C 0062;00E0 0315 302C 035F 0062;0061 0300 0315 302C 035F 0062;00E0 0315 302C 035F 0062;0061 0300 0315 302C 035F 0062; # (a◌͟◌̕◌̀◌〬b; à◌̕◌〬◌͟b; a◌̀◌̕◌〬◌͟b; à◌̕◌〬◌͟b; a◌̀◌̕◌〬◌͟b; ) LATIN SMALL LETTER A, COMBINING DOUBLE MACRON BELOW, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, IDEOGRAPHIC DEPARTING TONE MARK, LATIN SMALL LETTER B
+0061 302C 035F 0315 0300 0062;00E0 302C 0315 035F 0062;0061 0300 302C 0315 035F 0062;00E0 302C 0315 035F 0062;0061 0300 302C 0315 035F 0062; # (a◌〬◌͟◌̕◌̀b; à◌〬◌̕◌͟b; a◌̀◌〬◌̕◌͟b; à◌〬◌̕◌͟b; a◌̀◌〬◌̕◌͟b; ) LATIN SMALL LETTER A, IDEOGRAPHIC DEPARTING TONE MARK, COMBINING DOUBLE MACRON BELOW, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, LATIN SMALL LETTER B
+0061 302E 059A 0316 302D 0062;0061 0316 059A 302D 302E 0062;0061 0316 059A 302D 302E 0062;0061 0316 059A 302D 302E 0062;0061 0316 059A 302D 302E 0062; # (a◌〮◌֚◌̖◌〭b; a◌̖◌֚◌〭◌〮b; a◌̖◌֚◌〭◌〮b; a◌̖◌֚◌〭◌〮b; a◌̖◌֚◌〭◌〮b; ) LATIN SMALL LETTER A, HANGUL SINGLE DOT TONE MARK, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC ENTERING TONE MARK, LATIN SMALL LETTER B
+0061 302D 302E 059A 0316 0062;0061 0316 302D 059A 302E 0062;0061 0316 302D 059A 302E 0062;0061 0316 302D 059A 302E 0062;0061 0316 302D 059A 302E 0062; # (a◌〭◌〮◌֚◌̖b; a◌̖◌〭◌֚◌〮b; a◌̖◌〭◌֚◌〮b; a◌̖◌〭◌֚◌〮b; a◌̖◌〭◌֚◌〮b; ) LATIN SMALL LETTER A, IDEOGRAPHIC ENTERING TONE MARK, HANGUL SINGLE DOT TONE MARK, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, LATIN SMALL LETTER B
+0061 1D16D 302E 059A 302E 0062;0061 059A 302E 302E 1D16D 0062;0061 059A 302E 302E 1D16D 0062;0061 059A 302E 302E 1D16D 0062;0061 059A 302E 302E 1D16D 0062; # (a𝅭𝅭◌〮◌֚◌〮b; a◌֚◌〮◌〮𝅭𝅭b; a◌֚◌〮◌〮𝅭𝅭b; a◌֚◌〮◌〮𝅭𝅭b; a◌֚◌〮◌〮𝅭𝅭b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING AUGMENTATION DOT, HANGUL SINGLE DOT TONE MARK, HEBREW ACCENT YETIV, HANGUL SINGLE DOT TONE MARK, LATIN SMALL LETTER B
+0061 302E 1D16D 302E 059A 0062;0061 059A 302E 302E 1D16D 0062;0061 059A 302E 302E 1D16D 0062;0061 059A 302E 302E 1D16D 0062;0061 059A 302E 302E 1D16D 0062; # (a◌〮𝅭𝅭◌〮◌֚b; a◌֚◌〮◌〮𝅭𝅭b; a◌֚◌〮◌〮𝅭𝅭b; a◌֚◌〮◌〮𝅭𝅭b; a◌֚◌〮◌〮𝅭𝅭b; ) LATIN SMALL LETTER A, HANGUL SINGLE DOT TONE MARK, MUSICAL SYMBOL COMBINING AUGMENTATION DOT, HANGUL SINGLE DOT TONE MARK, HEBREW ACCENT YETIV, LATIN SMALL LETTER B
+0061 1D16D 302E 059A 302F 0062;0061 059A 302E 302F 1D16D 0062;0061 059A 302E 302F 1D16D 0062;0061 059A 302E 302F 1D16D 0062;0061 059A 302E 302F 1D16D 0062; # (a𝅭𝅭◌〮◌֚◌〯b; a◌֚◌〮◌〯𝅭𝅭b; a◌֚◌〮◌〯𝅭𝅭b; a◌֚◌〮◌〯𝅭𝅭b; a◌֚◌〮◌〯𝅭𝅭b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING AUGMENTATION DOT, HANGUL SINGLE DOT TONE MARK, HEBREW ACCENT YETIV, HANGUL DOUBLE DOT TONE MARK, LATIN SMALL LETTER B
+0061 302F 1D16D 302E 059A 0062;0061 059A 302F 302E 1D16D 0062;0061 059A 302F 302E 1D16D 0062;0061 059A 302F 302E 1D16D 0062;0061 059A 302F 302E 1D16D 0062; # (a◌〯𝅭𝅭◌〮◌֚b; a◌֚◌〯◌〮𝅭𝅭b; a◌֚◌〯◌〮𝅭𝅭b; a◌֚◌〯◌〮𝅭𝅭b; a◌֚◌〯◌〮𝅭𝅭b; ) LATIN SMALL LETTER A, HANGUL DOUBLE DOT TONE MARK, MUSICAL SYMBOL COMBINING AUGMENTATION DOT, HANGUL SINGLE DOT TONE MARK, HEBREW ACCENT YETIV, LATIN SMALL LETTER B
+0061 094D 3099 093C 3099 0062;0061 093C 3099 3099 094D 0062;0061 093C 3099 3099 094D 0062;0061 093C 3099 3099 094D 0062;0061 093C 3099 3099 094D 0062; # (a◌्◌゙◌़◌゙b; a◌़◌゙◌゙◌्b; a◌़◌゙◌゙◌्b; a◌़◌゙◌゙◌्b; a◌़◌゙◌゙◌्b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 3099 094D 3099 093C 0062;0061 093C 3099 3099 094D 0062;0061 093C 3099 3099 094D 0062;0061 093C 3099 3099 094D 0062;0061 093C 3099 3099 094D 0062; # (a◌゙◌्◌゙◌़b; a◌़◌゙◌゙◌्b; a◌़◌゙◌゙◌्b; a◌़◌゙◌゙◌्b; a◌़◌゙◌゙◌्b; ) LATIN SMALL LETTER A, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, LATIN SMALL LETTER B
+0061 094D 3099 093C 309A 0062;0061 093C 3099 309A 094D 0062;0061 093C 3099 309A 094D 0062;0061 093C 3099 309A 094D 0062;0061 093C 3099 309A 094D 0062; # (a◌्◌゙◌़◌゚b; a◌़◌゙◌゚◌्b; a◌़◌゙◌゚◌्b; a◌़◌゙◌゚◌्b; a◌़◌゙◌゚◌्b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK, LATIN SMALL LETTER B
+0061 309A 094D 3099 093C 0062;0061 093C 309A 3099 094D 0062;0061 093C 309A 3099 094D 0062;0061 093C 309A 3099 094D 0062;0061 093C 309A 3099 094D 0062; # (a◌゚◌्◌゙◌़b; a◌़◌゚◌゙◌्b; a◌़◌゚◌゙◌्b; a◌़◌゚◌゙◌्b; a◌़◌゚◌゙◌्b; ) LATIN SMALL LETTER A, COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK, DEVANAGARI SIGN VIRAMA, COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK, DEVANAGARI SIGN NUKTA, LATIN SMALL LETTER B
+0061 064B FB1E 05C2 FB1E 0062;0061 05C2 FB1E FB1E 064B 0062;0061 05C2 FB1E FB1E 064B 0062;0061 05C2 FB1E FB1E 064B 0062;0061 05C2 FB1E FB1E 064B 0062; # (a◌ً◌ﬞ◌ׂ◌ﬞb; a◌ׂ◌ﬞ◌ﬞ◌ًb; a◌ׂ◌ﬞ◌ﬞ◌ًb; a◌ׂ◌ﬞ◌ﬞ◌ًb; a◌ׂ◌ﬞ◌ﬞ◌ًb; ) LATIN SMALL LETTER A, ARABIC FATHATAN, HEBREW POINT JUDEO-SPANISH VARIKA, HEBREW POINT SIN DOT, HEBREW POINT JUDEO-SPANISH VARIKA, LATIN SMALL LETTER B
+0061 FB1E 064B FB1E 05C2 0062;0061 05C2 FB1E FB1E 064B 0062;0061 05C2 FB1E FB1E 064B 0062;0061 05C2 FB1E FB1E 064B 0062;0061 05C2 FB1E FB1E 064B 0062; # (a◌ﬞ◌ً◌ﬞ◌ׂb; a◌ׂ◌ﬞ◌ﬞ◌ًb; a◌ׂ◌ﬞ◌ﬞ◌ًb; a◌ׂ◌ﬞ◌ﬞ◌ًb; a◌ׂ◌ﬞ◌ﬞ◌ًb; ) LATIN SMALL LETTER A, HEBREW POINT JUDEO-SPANISH VARIKA, ARABIC FATHATAN, HEBREW POINT JUDEO-SPANISH VARIKA, HEBREW POINT SIN DOT, LATIN SMALL LETTER B
+0061 0315 0300 05AE FE20 0062;00E0 05AE FE20 0315 0062;0061 05AE 0300 FE20 0315 0062;00E0 05AE FE20 0315 0062;0061 05AE 0300 FE20 0315 0062; # (a◌̕◌̀◌֮◌︠b; à◌֮◌︠◌̕b; a◌֮◌̀◌︠◌̕b; à◌֮◌︠◌̕b; a◌֮◌̀◌︠◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LIGATURE LEFT HALF, LATIN SMALL LETTER B
+0061 FE20 0315 0300 05AE 0062;0061 05AE FE20 0300 0315 0062;0061 05AE FE20 0300 0315 0062;0061 05AE FE20 0300 0315 0062;0061 05AE FE20 0300 0315 0062; # (a◌︠◌̕◌̀◌֮b; a◌֮◌︠◌̀◌̕b; a◌֮◌︠◌̀◌̕b; a◌֮◌︠◌̀◌̕b; a◌֮◌︠◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LIGATURE LEFT HALF, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE FE21 0062;00E0 05AE FE21 0315 0062;0061 05AE 0300 FE21 0315 0062;00E0 05AE FE21 0315 0062;0061 05AE 0300 FE21 0315 0062; # (a◌̕◌̀◌֮◌︡b; à◌֮◌︡◌̕b; a◌֮◌̀◌︡◌̕b; à◌֮◌︡◌̕b; a◌֮◌̀◌︡◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING LIGATURE RIGHT HALF, LATIN SMALL LETTER B
+0061 FE21 0315 0300 05AE 0062;0061 05AE FE21 0300 0315 0062;0061 05AE FE21 0300 0315 0062;0061 05AE FE21 0300 0315 0062;0061 05AE FE21 0300 0315 0062; # (a◌︡◌̕◌̀◌֮b; a◌֮◌︡◌̀◌̕b; a◌֮◌︡◌̀◌̕b; a◌֮◌︡◌̀◌̕b; a◌֮◌︡◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING LIGATURE RIGHT HALF, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE FE22 0062;00E0 05AE FE22 0315 0062;0061 05AE 0300 FE22 0315 0062;00E0 05AE FE22 0315 0062;0061 05AE 0300 FE22 0315 0062; # (a◌̕◌̀◌֮◌︢b; à◌֮◌︢◌̕b; a◌֮◌̀◌︢◌̕b; à◌֮◌︢◌̕b; a◌֮◌̀◌︢◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING DOUBLE TILDE LEFT HALF, LATIN SMALL LETTER B
+0061 FE22 0315 0300 05AE 0062;0061 05AE FE22 0300 0315 0062;0061 05AE FE22 0300 0315 0062;0061 05AE FE22 0300 0315 0062;0061 05AE FE22 0300 0315 0062; # (a◌︢◌̕◌̀◌֮b; a◌֮◌︢◌̀◌̕b; a◌֮◌︢◌̀◌̕b; a◌֮◌︢◌̀◌̕b; a◌֮◌︢◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING DOUBLE TILDE LEFT HALF, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE FE23 0062;00E0 05AE FE23 0315 0062;0061 05AE 0300 FE23 0315 0062;00E0 05AE FE23 0315 0062;0061 05AE 0300 FE23 0315 0062; # (a◌̕◌̀◌֮◌︣b; à◌֮◌︣◌̕b; a◌֮◌̀◌︣◌̕b; à◌֮◌︣◌̕b; a◌֮◌̀◌︣◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, COMBINING DOUBLE TILDE RIGHT HALF, LATIN SMALL LETTER B
+0061 FE23 0315 0300 05AE 0062;0061 05AE FE23 0300 0315 0062;0061 05AE FE23 0300 0315 0062;0061 05AE FE23 0300 0315 0062;0061 05AE FE23 0300 0315 0062; # (a◌︣◌̕◌̀◌֮b; a◌֮◌︣◌̀◌̕b; a◌֮◌︣◌̀◌̕b; a◌֮◌︣◌̀◌̕b; a◌֮◌︣◌̀◌̕b; ) LATIN SMALL LETTER A, COMBINING DOUBLE TILDE RIGHT HALF, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 302A 031B 0321 1D165 0062;0061 0321 031B 1D165 302A 0062;0061 0321 031B 1D165 302A 0062;0061 0321 031B 1D165 302A 0062;0061 0321 031B 1D165 302A 0062; # (a◌〪◌̛◌̡𝅥𝅥b; a◌̡◌̛𝅥𝅥◌〪b; a◌̡◌̛𝅥𝅥◌〪b; a◌̡◌̛𝅥𝅥◌〪b; a◌̡◌̛𝅥𝅥◌〪b; ) LATIN SMALL LETTER A, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, MUSICAL SYMBOL COMBINING STEM, LATIN SMALL LETTER B
+0061 1D165 302A 031B 0321 0062;0061 0321 1D165 031B 302A 0062;0061 0321 1D165 031B 302A 0062;0061 0321 1D165 031B 302A 0062;0061 0321 1D165 031B 302A 0062; # (a𝅥𝅥◌〪◌̛◌̡b; a◌̡𝅥𝅥◌̛◌〪b; a◌̡𝅥𝅥◌̛◌〪b; a◌̡𝅥𝅥◌̛◌〪b; a◌̡𝅥𝅥◌̛◌〪b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING STEM, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, LATIN SMALL LETTER B
+0061 302A 031B 0321 1D166 0062;0061 0321 031B 1D166 302A 0062;0061 0321 031B 1D166 302A 0062;0061 0321 031B 1D166 302A 0062;0061 0321 031B 1D166 302A 0062; # (a◌〪◌̛◌̡𝅦𝅦b; a◌̡◌̛𝅦𝅦◌〪b; a◌̡◌̛𝅦𝅦◌〪b; a◌̡◌̛𝅦𝅦◌〪b; a◌̡◌̛𝅦𝅦◌〪b; ) LATIN SMALL LETTER A, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, MUSICAL SYMBOL COMBINING SPRECHGESANG STEM, LATIN SMALL LETTER B
+0061 1D166 302A 031B 0321 0062;0061 0321 1D166 031B 302A 0062;0061 0321 1D166 031B 302A 0062;0061 0321 1D166 031B 302A 0062;0061 0321 1D166 031B 302A 0062; # (a𝅦𝅦◌〪◌̛◌̡b; a◌̡𝅦𝅦◌̛◌〪b; a◌̡𝅦𝅦◌̛◌〪b; a◌̡𝅦𝅦◌̛◌〪b; a◌̡𝅦𝅦◌̛◌〪b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING SPRECHGESANG STEM, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, LATIN SMALL LETTER B
+0061 093C 0334 1D167 0062;0061 0334 1D167 093C 0062;0061 0334 1D167 093C 0062;0061 0334 1D167 093C 0062;0061 0334 1D167 093C 0062; # (a◌़◌̴◌𝅧◌𝅧b; a◌̴◌𝅧◌𝅧◌़b; a◌̴◌𝅧◌𝅧◌़b; a◌̴◌𝅧◌𝅧◌़b; a◌̴◌𝅧◌𝅧◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, MUSICAL SYMBOL COMBINING TREMOLO-1, LATIN SMALL LETTER B
+0061 1D167 093C 0334 0062;0061 1D167 0334 093C 0062;0061 1D167 0334 093C 0062;0061 1D167 0334 093C 0062;0061 1D167 0334 093C 0062; # (a◌𝅧◌𝅧◌़◌̴b; a◌𝅧◌𝅧◌̴◌़b; a◌𝅧◌𝅧◌̴◌़b; a◌𝅧◌𝅧◌̴◌़b; a◌𝅧◌𝅧◌̴◌़b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING TREMOLO-1, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 093C 0334 1D168 0062;0061 0334 1D168 093C 0062;0061 0334 1D168 093C 0062;0061 0334 1D168 093C 0062;0061 0334 1D168 093C 0062; # (a◌़◌̴◌𝅨◌𝅨b; a◌̴◌𝅨◌𝅨◌़b; a◌̴◌𝅨◌𝅨◌़b; a◌̴◌𝅨◌𝅨◌़b; a◌̴◌𝅨◌𝅨◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, MUSICAL SYMBOL COMBINING TREMOLO-2, LATIN SMALL LETTER B
+0061 1D168 093C 0334 0062;0061 1D168 0334 093C 0062;0061 1D168 0334 093C 0062;0061 1D168 0334 093C 0062;0061 1D168 0334 093C 0062; # (a◌𝅨◌𝅨◌़◌̴b; a◌𝅨◌𝅨◌̴◌़b; a◌𝅨◌𝅨◌̴◌़b; a◌𝅨◌𝅨◌̴◌़b; a◌𝅨◌𝅨◌̴◌़b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING TREMOLO-2, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 093C 0334 1D169 0062;0061 0334 1D169 093C 0062;0061 0334 1D169 093C 0062;0061 0334 1D169 093C 0062;0061 0334 1D169 093C 0062; # (a◌़◌̴◌𝅩◌𝅩b; a◌̴◌𝅩◌𝅩◌़b; a◌̴◌𝅩◌𝅩◌़b; a◌̴◌𝅩◌𝅩◌़b; a◌̴◌𝅩◌𝅩◌़b; ) LATIN SMALL LETTER A, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, MUSICAL SYMBOL COMBINING TREMOLO-3, LATIN SMALL LETTER B
+0061 1D169 093C 0334 0062;0061 1D169 0334 093C 0062;0061 1D169 0334 093C 0062;0061 1D169 0334 093C 0062;0061 1D169 0334 093C 0062; # (a◌𝅩◌𝅩◌़◌̴b; a◌𝅩◌𝅩◌̴◌़b; a◌𝅩◌𝅩◌̴◌़b; a◌𝅩◌𝅩◌̴◌़b; a◌𝅩◌𝅩◌̴◌़b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING TREMOLO-3, DEVANAGARI SIGN NUKTA, COMBINING TILDE OVERLAY, LATIN SMALL LETTER B
+0061 05AE 1D16D 302E 1D16D 0062;0061 302E 1D16D 1D16D 05AE 0062;0061 302E 1D16D 1D16D 05AE 0062;0061 302E 1D16D 1D16D 05AE 0062;0061 302E 1D16D 1D16D 05AE 0062; # (a◌𝅭𝅭֮◌〮𝅭𝅭b; a◌〮𝅭𝅭𝅭𝅭◌֮b; a◌〮𝅭𝅭𝅭𝅭◌֮b; a◌〮𝅭𝅭𝅭𝅭◌֮b; a◌〮𝅭𝅭𝅭𝅭◌֮b; ) LATIN SMALL LETTER A, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING AUGMENTATION DOT, HANGUL SINGLE DOT TONE MARK, MUSICAL SYMBOL COMBINING AUGMENTATION DOT, LATIN SMALL LETTER B
+0061 1D16D 05AE 1D16D 302E 0062;0061 302E 1D16D 1D16D 05AE 0062;0061 302E 1D16D 1D16D 05AE 0062;0061 302E 1D16D 1D16D 05AE 0062;0061 302E 1D16D 1D16D 05AE 0062; # (a𝅭𝅭◌𝅭𝅭֮◌〮b; a◌〮𝅭𝅭𝅭𝅭◌֮b; a◌〮𝅭𝅭𝅭𝅭◌֮b; a◌〮𝅭𝅭𝅭𝅭◌֮b; a◌〮𝅭𝅭𝅭𝅭◌֮b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING AUGMENTATION DOT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING AUGMENTATION DOT, HANGUL SINGLE DOT TONE MARK, LATIN SMALL LETTER B
+0061 302A 031B 0321 1D16E 0062;0061 0321 031B 1D16E 302A 0062;0061 0321 031B 1D16E 302A 0062;0061 0321 031B 1D16E 302A 0062;0061 0321 031B 1D16E 302A 0062; # (a◌〪◌̛◌̡𝅮𝅮b; a◌̡◌̛𝅮𝅮◌〪b; a◌̡◌̛𝅮𝅮◌〪b; a◌̡◌̛𝅮𝅮◌〪b; a◌̡◌̛𝅮𝅮◌〪b; ) LATIN SMALL LETTER A, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, MUSICAL SYMBOL COMBINING FLAG-1, LATIN SMALL LETTER B
+0061 1D16E 302A 031B 0321 0062;0061 0321 1D16E 031B 302A 0062;0061 0321 1D16E 031B 302A 0062;0061 0321 1D16E 031B 302A 0062;0061 0321 1D16E 031B 302A 0062; # (a𝅮𝅮◌〪◌̛◌̡b; a◌̡𝅮𝅮◌̛◌〪b; a◌̡𝅮𝅮◌̛◌〪b; a◌̡𝅮𝅮◌̛◌〪b; a◌̡𝅮𝅮◌̛◌〪b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING FLAG-1, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, LATIN SMALL LETTER B
+0061 302A 031B 0321 1D16F 0062;0061 0321 031B 1D16F 302A 0062;0061 0321 031B 1D16F 302A 0062;0061 0321 031B 1D16F 302A 0062;0061 0321 031B 1D16F 302A 0062; # (a◌〪◌̛◌̡𝅯𝅯b; a◌̡◌̛𝅯𝅯◌〪b; a◌̡◌̛𝅯𝅯◌〪b; a◌̡◌̛𝅯𝅯◌〪b; a◌̡◌̛𝅯𝅯◌〪b; ) LATIN SMALL LETTER A, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, MUSICAL SYMBOL COMBINING FLAG-2, LATIN SMALL LETTER B
+0061 1D16F 302A 031B 0321 0062;0061 0321 1D16F 031B 302A 0062;0061 0321 1D16F 031B 302A 0062;0061 0321 1D16F 031B 302A 0062;0061 0321 1D16F 031B 302A 0062; # (a𝅯𝅯◌〪◌̛◌̡b; a◌̡𝅯𝅯◌̛◌〪b; a◌̡𝅯𝅯◌̛◌〪b; a◌̡𝅯𝅯◌̛◌〪b; a◌̡𝅯𝅯◌̛◌〪b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING FLAG-2, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, LATIN SMALL LETTER B
+0061 302A 031B 0321 1D170 0062;0061 0321 031B 1D170 302A 0062;0061 0321 031B 1D170 302A 0062;0061 0321 031B 1D170 302A 0062;0061 0321 031B 1D170 302A 0062; # (a◌〪◌̛◌̡𝅰𝅰b; a◌̡◌̛𝅰𝅰◌〪b; a◌̡◌̛𝅰𝅰◌〪b; a◌̡◌̛𝅰𝅰◌〪b; a◌̡◌̛𝅰𝅰◌〪b; ) LATIN SMALL LETTER A, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, MUSICAL SYMBOL COMBINING FLAG-3, LATIN SMALL LETTER B
+0061 1D170 302A 031B 0321 0062;0061 0321 1D170 031B 302A 0062;0061 0321 1D170 031B 302A 0062;0061 0321 1D170 031B 302A 0062;0061 0321 1D170 031B 302A 0062; # (a𝅰𝅰◌〪◌̛◌̡b; a◌̡𝅰𝅰◌̛◌〪b; a◌̡𝅰𝅰◌̛◌〪b; a◌̡𝅰𝅰◌̛◌〪b; a◌̡𝅰𝅰◌̛◌〪b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING FLAG-3, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, LATIN SMALL LETTER B
+0061 302A 031B 0321 1D171 0062;0061 0321 031B 1D171 302A 0062;0061 0321 031B 1D171 302A 0062;0061 0321 031B 1D171 302A 0062;0061 0321 031B 1D171 302A 0062; # (a◌〪◌̛◌̡𝅱𝅱b; a◌̡◌̛𝅱𝅱◌〪b; a◌̡◌̛𝅱𝅱◌〪b; a◌̡◌̛𝅱𝅱◌〪b; a◌̡◌̛𝅱𝅱◌〪b; ) LATIN SMALL LETTER A, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, MUSICAL SYMBOL COMBINING FLAG-4, LATIN SMALL LETTER B
+0061 1D171 302A 031B 0321 0062;0061 0321 1D171 031B 302A 0062;0061 0321 1D171 031B 302A 0062;0061 0321 1D171 031B 302A 0062;0061 0321 1D171 031B 302A 0062; # (a𝅱𝅱◌〪◌̛◌̡b; a◌̡𝅱𝅱◌̛◌〪b; a◌̡𝅱𝅱◌̛◌〪b; a◌̡𝅱𝅱◌̛◌〪b; a◌̡𝅱𝅱◌̛◌〪b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING FLAG-4, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, LATIN SMALL LETTER B
+0061 302A 031B 0321 1D172 0062;0061 0321 031B 1D172 302A 0062;0061 0321 031B 1D172 302A 0062;0061 0321 031B 1D172 302A 0062;0061 0321 031B 1D172 302A 0062; # (a◌〪◌̛◌̡𝅲𝅲b; a◌̡◌̛𝅲𝅲◌〪b; a◌̡◌̛𝅲𝅲◌〪b; a◌̡◌̛𝅲𝅲◌〪b; a◌̡◌̛𝅲𝅲◌〪b; ) LATIN SMALL LETTER A, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, MUSICAL SYMBOL COMBINING FLAG-5, LATIN SMALL LETTER B
+0061 1D172 302A 031B 0321 0062;0061 0321 1D172 031B 302A 0062;0061 0321 1D172 031B 302A 0062;0061 0321 1D172 031B 302A 0062;0061 0321 1D172 031B 302A 0062; # (a𝅲𝅲◌〪◌̛◌̡b; a◌̡𝅲𝅲◌̛◌〪b; a◌̡𝅲𝅲◌̛◌〪b; a◌̡𝅲𝅲◌̛◌〪b; a◌̡𝅲𝅲◌̛◌〪b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING FLAG-5, IDEOGRAPHIC LEVEL TONE MARK, COMBINING HORN, COMBINING PALATALIZED HOOK BELOW, LATIN SMALL LETTER B
+0061 059A 0316 302A 1D17B 0062;0061 302A 0316 1D17B 059A 0062;0061 302A 0316 1D17B 059A 0062;0061 302A 0316 1D17B 059A 0062;0061 302A 0316 1D17B 059A 0062; # (a◌֚◌̖◌〪◌𝅻◌𝅻b; a◌〪◌̖◌𝅻◌𝅻◌֚b; a◌〪◌̖◌𝅻◌𝅻◌֚b; a◌〪◌̖◌𝅻◌𝅻◌֚b; a◌〪◌̖◌𝅻◌𝅻◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, MUSICAL SYMBOL COMBINING ACCENT, LATIN SMALL LETTER B
+0061 1D17B 059A 0316 302A 0062;0061 302A 1D17B 0316 059A 0062;0061 302A 1D17B 0316 059A 0062;0061 302A 1D17B 0316 059A 0062;0061 302A 1D17B 0316 059A 0062; # (a◌𝅻◌𝅻◌֚◌̖◌〪b; a◌〪◌𝅻◌𝅻◌̖◌֚b; a◌〪◌𝅻◌𝅻◌̖◌֚b; a◌〪◌𝅻◌𝅻◌̖◌֚b; a◌〪◌𝅻◌𝅻◌̖◌֚b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING ACCENT, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 1D17C 0062;0061 302A 0316 1D17C 059A 0062;0061 302A 0316 1D17C 059A 0062;0061 302A 0316 1D17C 059A 0062;0061 302A 0316 1D17C 059A 0062; # (a◌֚◌̖◌〪◌𝅼◌𝅼b; a◌〪◌̖◌𝅼◌𝅼◌֚b; a◌〪◌̖◌𝅼◌𝅼◌֚b; a◌〪◌̖◌𝅼◌𝅼◌֚b; a◌〪◌̖◌𝅼◌𝅼◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, MUSICAL SYMBOL COMBINING STACCATO, LATIN SMALL LETTER B
+0061 1D17C 059A 0316 302A 0062;0061 302A 1D17C 0316 059A 0062;0061 302A 1D17C 0316 059A 0062;0061 302A 1D17C 0316 059A 0062;0061 302A 1D17C 0316 059A 0062; # (a◌𝅼◌𝅼◌֚◌̖◌〪b; a◌〪◌𝅼◌𝅼◌̖◌֚b; a◌〪◌𝅼◌𝅼◌̖◌֚b; a◌〪◌𝅼◌𝅼◌̖◌֚b; a◌〪◌𝅼◌𝅼◌̖◌֚b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING STACCATO, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 1D17D 0062;0061 302A 0316 1D17D 059A 0062;0061 302A 0316 1D17D 059A 0062;0061 302A 0316 1D17D 059A 0062;0061 302A 0316 1D17D 059A 0062; # (a◌֚◌̖◌〪◌𝅽◌𝅽b; a◌〪◌̖◌𝅽◌𝅽◌֚b; a◌〪◌̖◌𝅽◌𝅽◌֚b; a◌〪◌̖◌𝅽◌𝅽◌֚b; a◌〪◌̖◌𝅽◌𝅽◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, MUSICAL SYMBOL COMBINING TENUTO, LATIN SMALL LETTER B
+0061 1D17D 059A 0316 302A 0062;0061 302A 1D17D 0316 059A 0062;0061 302A 1D17D 0316 059A 0062;0061 302A 1D17D 0316 059A 0062;0061 302A 1D17D 0316 059A 0062; # (a◌𝅽◌𝅽◌֚◌̖◌〪b; a◌〪◌𝅽◌𝅽◌̖◌֚b; a◌〪◌𝅽◌𝅽◌̖◌֚b; a◌〪◌𝅽◌𝅽◌̖◌֚b; a◌〪◌𝅽◌𝅽◌̖◌֚b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING TENUTO, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 1D17E 0062;0061 302A 0316 1D17E 059A 0062;0061 302A 0316 1D17E 059A 0062;0061 302A 0316 1D17E 059A 0062;0061 302A 0316 1D17E 059A 0062; # (a◌֚◌̖◌〪◌𝅾◌𝅾b; a◌〪◌̖◌𝅾◌𝅾◌֚b; a◌〪◌̖◌𝅾◌𝅾◌֚b; a◌〪◌̖◌𝅾◌𝅾◌֚b; a◌〪◌̖◌𝅾◌𝅾◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, MUSICAL SYMBOL COMBINING STACCATISSIMO, LATIN SMALL LETTER B
+0061 1D17E 059A 0316 302A 0062;0061 302A 1D17E 0316 059A 0062;0061 302A 1D17E 0316 059A 0062;0061 302A 1D17E 0316 059A 0062;0061 302A 1D17E 0316 059A 0062; # (a◌𝅾◌𝅾◌֚◌̖◌〪b; a◌〪◌𝅾◌𝅾◌̖◌֚b; a◌〪◌𝅾◌𝅾◌̖◌֚b; a◌〪◌𝅾◌𝅾◌̖◌֚b; a◌〪◌𝅾◌𝅾◌̖◌֚b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING STACCATISSIMO, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 1D17F 0062;0061 302A 0316 1D17F 059A 0062;0061 302A 0316 1D17F 059A 0062;0061 302A 0316 1D17F 059A 0062;0061 302A 0316 1D17F 059A 0062; # (a◌֚◌̖◌〪◌𝅿◌𝅿b; a◌〪◌̖◌𝅿◌𝅿◌֚b; a◌〪◌̖◌𝅿◌𝅿◌֚b; a◌〪◌̖◌𝅿◌𝅿◌֚b; a◌〪◌̖◌𝅿◌𝅿◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, MUSICAL SYMBOL COMBINING MARCATO, LATIN SMALL LETTER B
+0061 1D17F 059A 0316 302A 0062;0061 302A 1D17F 0316 059A 0062;0061 302A 1D17F 0316 059A 0062;0061 302A 1D17F 0316 059A 0062;0061 302A 1D17F 0316 059A 0062; # (a◌𝅿◌𝅿◌֚◌̖◌〪b; a◌〪◌𝅿◌𝅿◌̖◌֚b; a◌〪◌𝅿◌𝅿◌̖◌֚b; a◌〪◌𝅿◌𝅿◌̖◌֚b; a◌〪◌𝅿◌𝅿◌̖◌֚b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING MARCATO, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 1D180 0062;0061 302A 0316 1D180 059A 0062;0061 302A 0316 1D180 059A 0062;0061 302A 0316 1D180 059A 0062;0061 302A 0316 1D180 059A 0062; # (a◌֚◌̖◌〪◌𝆀◌𝆀b; a◌〪◌̖◌𝆀◌𝆀◌֚b; a◌〪◌̖◌𝆀◌𝆀◌֚b; a◌〪◌̖◌𝆀◌𝆀◌֚b; a◌〪◌̖◌𝆀◌𝆀◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, MUSICAL SYMBOL COMBINING MARCATO-STACCATO, LATIN SMALL LETTER B
+0061 1D180 059A 0316 302A 0062;0061 302A 1D180 0316 059A 0062;0061 302A 1D180 0316 059A 0062;0061 302A 1D180 0316 059A 0062;0061 302A 1D180 0316 059A 0062; # (a◌𝆀◌𝆀◌֚◌̖◌〪b; a◌〪◌𝆀◌𝆀◌̖◌֚b; a◌〪◌𝆀◌𝆀◌̖◌֚b; a◌〪◌𝆀◌𝆀◌̖◌֚b; a◌〪◌𝆀◌𝆀◌̖◌֚b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING MARCATO-STACCATO, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 1D181 0062;0061 302A 0316 1D181 059A 0062;0061 302A 0316 1D181 059A 0062;0061 302A 0316 1D181 059A 0062;0061 302A 0316 1D181 059A 0062; # (a◌֚◌̖◌〪◌𝆁◌𝆁b; a◌〪◌̖◌𝆁◌𝆁◌֚b; a◌〪◌̖◌𝆁◌𝆁◌֚b; a◌〪◌̖◌𝆁◌𝆁◌֚b; a◌〪◌̖◌𝆁◌𝆁◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, MUSICAL SYMBOL COMBINING ACCENT-STACCATO, LATIN SMALL LETTER B
+0061 1D181 059A 0316 302A 0062;0061 302A 1D181 0316 059A 0062;0061 302A 1D181 0316 059A 0062;0061 302A 1D181 0316 059A 0062;0061 302A 1D181 0316 059A 0062; # (a◌𝆁◌𝆁◌֚◌̖◌〪b; a◌〪◌𝆁◌𝆁◌̖◌֚b; a◌〪◌𝆁◌𝆁◌̖◌֚b; a◌〪◌𝆁◌𝆁◌̖◌֚b; a◌〪◌𝆁◌𝆁◌̖◌֚b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING ACCENT-STACCATO, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 1D182 0062;0061 302A 0316 1D182 059A 0062;0061 302A 0316 1D182 059A 0062;0061 302A 0316 1D182 059A 0062;0061 302A 0316 1D182 059A 0062; # (a◌֚◌̖◌〪◌𝆂◌𝆂b; a◌〪◌̖◌𝆂◌𝆂◌֚b; a◌〪◌̖◌𝆂◌𝆂◌֚b; a◌〪◌̖◌𝆂◌𝆂◌֚b; a◌〪◌̖◌𝆂◌𝆂◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, MUSICAL SYMBOL COMBINING LOURE, LATIN SMALL LETTER B
+0061 1D182 059A 0316 302A 0062;0061 302A 1D182 0316 059A 0062;0061 302A 1D182 0316 059A 0062;0061 302A 1D182 0316 059A 0062;0061 302A 1D182 0316 059A 0062; # (a◌𝆂◌𝆂◌֚◌̖◌〪b; a◌〪◌𝆂◌𝆂◌̖◌֚b; a◌〪◌𝆂◌𝆂◌̖◌֚b; a◌〪◌𝆂◌𝆂◌̖◌֚b; a◌〪◌𝆂◌𝆂◌̖◌֚b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING LOURE, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 1D185 0062;00E0 05AE 1D185 0315 0062;0061 05AE 0300 1D185 0315 0062;00E0 05AE 1D185 0315 0062;0061 05AE 0300 1D185 0315 0062; # (a◌̕◌̀◌֮◌𝆅◌𝆅b; à◌֮◌𝆅◌𝆅◌̕b; a◌֮◌̀◌𝆅◌𝆅◌̕b; à◌֮◌𝆅◌𝆅◌̕b; a◌֮◌̀◌𝆅◌𝆅◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING DOIT, LATIN SMALL LETTER B
+0061 1D185 0315 0300 05AE 0062;0061 05AE 1D185 0300 0315 0062;0061 05AE 1D185 0300 0315 0062;0061 05AE 1D185 0300 0315 0062;0061 05AE 1D185 0300 0315 0062; # (a◌𝆅◌𝆅◌̕◌̀◌֮b; a◌֮◌𝆅◌𝆅◌̀◌̕b; a◌֮◌𝆅◌𝆅◌̀◌̕b; a◌֮◌𝆅◌𝆅◌̀◌̕b; a◌֮◌𝆅◌𝆅◌̀◌̕b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING DOIT, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 1D186 0062;00E0 05AE 1D186 0315 0062;0061 05AE 0300 1D186 0315 0062;00E0 05AE 1D186 0315 0062;0061 05AE 0300 1D186 0315 0062; # (a◌̕◌̀◌֮◌𝆆◌𝆆b; à◌֮◌𝆆◌𝆆◌̕b; a◌֮◌̀◌𝆆◌𝆆◌̕b; à◌֮◌𝆆◌𝆆◌̕b; a◌֮◌̀◌𝆆◌𝆆◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING RIP, LATIN SMALL LETTER B
+0061 1D186 0315 0300 05AE 0062;0061 05AE 1D186 0300 0315 0062;0061 05AE 1D186 0300 0315 0062;0061 05AE 1D186 0300 0315 0062;0061 05AE 1D186 0300 0315 0062; # (a◌𝆆◌𝆆◌̕◌̀◌֮b; a◌֮◌𝆆◌𝆆◌̀◌̕b; a◌֮◌𝆆◌𝆆◌̀◌̕b; a◌֮◌𝆆◌𝆆◌̀◌̕b; a◌֮◌𝆆◌𝆆◌̀◌̕b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING RIP, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 1D187 0062;00E0 05AE 1D187 0315 0062;0061 05AE 0300 1D187 0315 0062;00E0 05AE 1D187 0315 0062;0061 05AE 0300 1D187 0315 0062; # (a◌̕◌̀◌֮◌𝆇◌𝆇b; à◌֮◌𝆇◌𝆇◌̕b; a◌֮◌̀◌𝆇◌𝆇◌̕b; à◌֮◌𝆇◌𝆇◌̕b; a◌֮◌̀◌𝆇◌𝆇◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING FLIP, LATIN SMALL LETTER B
+0061 1D187 0315 0300 05AE 0062;0061 05AE 1D187 0300 0315 0062;0061 05AE 1D187 0300 0315 0062;0061 05AE 1D187 0300 0315 0062;0061 05AE 1D187 0300 0315 0062; # (a◌𝆇◌𝆇◌̕◌̀◌֮b; a◌֮◌𝆇◌𝆇◌̀◌̕b; a◌֮◌𝆇◌𝆇◌̀◌̕b; a◌֮◌𝆇◌𝆇◌̀◌̕b; a◌֮◌𝆇◌𝆇◌̀◌̕b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING FLIP, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 1D188 0062;00E0 05AE 1D188 0315 0062;0061 05AE 0300 1D188 0315 0062;00E0 05AE 1D188 0315 0062;0061 05AE 0300 1D188 0315 0062; # (a◌̕◌̀◌֮◌𝆈◌𝆈b; à◌֮◌𝆈◌𝆈◌̕b; a◌֮◌̀◌𝆈◌𝆈◌̕b; à◌֮◌𝆈◌𝆈◌̕b; a◌֮◌̀◌𝆈◌𝆈◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING SMEAR, LATIN SMALL LETTER B
+0061 1D188 0315 0300 05AE 0062;0061 05AE 1D188 0300 0315 0062;0061 05AE 1D188 0300 0315 0062;0061 05AE 1D188 0300 0315 0062;0061 05AE 1D188 0300 0315 0062; # (a◌𝆈◌𝆈◌̕◌̀◌֮b; a◌֮◌𝆈◌𝆈◌̀◌̕b; a◌֮◌𝆈◌𝆈◌̀◌̕b; a◌֮◌𝆈◌𝆈◌̀◌̕b; a◌֮◌𝆈◌𝆈◌̀◌̕b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING SMEAR, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 1D189 0062;00E0 05AE 1D189 0315 0062;0061 05AE 0300 1D189 0315 0062;00E0 05AE 1D189 0315 0062;0061 05AE 0300 1D189 0315 0062; # (a◌̕◌̀◌֮◌𝆉◌𝆉b; à◌֮◌𝆉◌𝆉◌̕b; a◌֮◌̀◌𝆉◌𝆉◌̕b; à◌֮◌𝆉◌𝆉◌̕b; a◌֮◌̀◌𝆉◌𝆉◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING BEND, LATIN SMALL LETTER B
+0061 1D189 0315 0300 05AE 0062;0061 05AE 1D189 0300 0315 0062;0061 05AE 1D189 0300 0315 0062;0061 05AE 1D189 0300 0315 0062;0061 05AE 1D189 0300 0315 0062; # (a◌𝆉◌𝆉◌̕◌̀◌֮b; a◌֮◌𝆉◌𝆉◌̀◌̕b; a◌֮◌𝆉◌𝆉◌̀◌̕b; a◌֮◌𝆉◌𝆉◌̀◌̕b; a◌֮◌𝆉◌𝆉◌̀◌̕b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING BEND, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 059A 0316 302A 1D18A 0062;0061 302A 0316 1D18A 059A 0062;0061 302A 0316 1D18A 059A 0062;0061 302A 0316 1D18A 059A 0062;0061 302A 0316 1D18A 059A 0062; # (a◌֚◌̖◌〪◌𝆊◌𝆊b; a◌〪◌̖◌𝆊◌𝆊◌֚b; a◌〪◌̖◌𝆊◌𝆊◌֚b; a◌〪◌̖◌𝆊◌𝆊◌֚b; a◌〪◌̖◌𝆊◌𝆊◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, MUSICAL SYMBOL COMBINING DOUBLE TONGUE, LATIN SMALL LETTER B
+0061 1D18A 059A 0316 302A 0062;0061 302A 1D18A 0316 059A 0062;0061 302A 1D18A 0316 059A 0062;0061 302A 1D18A 0316 059A 0062;0061 302A 1D18A 0316 059A 0062; # (a◌𝆊◌𝆊◌֚◌̖◌〪b; a◌〪◌𝆊◌𝆊◌̖◌֚b; a◌〪◌𝆊◌𝆊◌̖◌֚b; a◌〪◌𝆊◌𝆊◌̖◌֚b; a◌〪◌𝆊◌𝆊◌̖◌֚b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING DOUBLE TONGUE, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 059A 0316 302A 1D18B 0062;0061 302A 0316 1D18B 059A 0062;0061 302A 0316 1D18B 059A 0062;0061 302A 0316 1D18B 059A 0062;0061 302A 0316 1D18B 059A 0062; # (a◌֚◌̖◌〪◌𝆋◌𝆋b; a◌〪◌̖◌𝆋◌𝆋◌֚b; a◌〪◌̖◌𝆋◌𝆋◌֚b; a◌〪◌̖◌𝆋◌𝆋◌֚b; a◌〪◌̖◌𝆋◌𝆋◌֚b; ) LATIN SMALL LETTER A, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, MUSICAL SYMBOL COMBINING TRIPLE TONGUE, LATIN SMALL LETTER B
+0061 1D18B 059A 0316 302A 0062;0061 302A 1D18B 0316 059A 0062;0061 302A 1D18B 0316 059A 0062;0061 302A 1D18B 0316 059A 0062;0061 302A 1D18B 0316 059A 0062; # (a◌𝆋◌𝆋◌֚◌̖◌〪b; a◌〪◌𝆋◌𝆋◌̖◌֚b; a◌〪◌𝆋◌𝆋◌̖◌֚b; a◌〪◌𝆋◌𝆋◌̖◌֚b; a◌〪◌𝆋◌𝆋◌̖◌֚b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING TRIPLE TONGUE, HEBREW ACCENT YETIV, COMBINING GRAVE ACCENT BELOW, IDEOGRAPHIC LEVEL TONE MARK, LATIN SMALL LETTER B
+0061 0315 0300 05AE 1D1AA 0062;00E0 05AE 1D1AA 0315 0062;0061 05AE 0300 1D1AA 0315 0062;00E0 05AE 1D1AA 0315 0062;0061 05AE 0300 1D1AA 0315 0062; # (a◌̕◌̀◌֮◌𝆪◌𝆪b; à◌֮◌𝆪◌𝆪◌̕b; a◌֮◌̀◌𝆪◌𝆪◌̕b; à◌֮◌𝆪◌𝆪◌̕b; a◌֮◌̀◌𝆪◌𝆪◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING DOWN BOW, LATIN SMALL LETTER B
+0061 1D1AA 0315 0300 05AE 0062;0061 05AE 1D1AA 0300 0315 0062;0061 05AE 1D1AA 0300 0315 0062;0061 05AE 1D1AA 0300 0315 0062;0061 05AE 1D1AA 0300 0315 0062; # (a◌𝆪◌𝆪◌̕◌̀◌֮b; a◌֮◌𝆪◌𝆪◌̀◌̕b; a◌֮◌𝆪◌𝆪◌̀◌̕b; a◌֮◌𝆪◌𝆪◌̀◌̕b; a◌֮◌𝆪◌𝆪◌̀◌̕b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING DOWN BOW, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 1D1AB 0062;00E0 05AE 1D1AB 0315 0062;0061 05AE 0300 1D1AB 0315 0062;00E0 05AE 1D1AB 0315 0062;0061 05AE 0300 1D1AB 0315 0062; # (a◌̕◌̀◌֮◌𝆫◌𝆫b; à◌֮◌𝆫◌𝆫◌̕b; a◌֮◌̀◌𝆫◌𝆫◌̕b; à◌֮◌𝆫◌𝆫◌̕b; a◌֮◌̀◌𝆫◌𝆫◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING UP BOW, LATIN SMALL LETTER B
+0061 1D1AB 0315 0300 05AE 0062;0061 05AE 1D1AB 0300 0315 0062;0061 05AE 1D1AB 0300 0315 0062;0061 05AE 1D1AB 0300 0315 0062;0061 05AE 1D1AB 0300 0315 0062; # (a◌𝆫◌𝆫◌̕◌̀◌֮b; a◌֮◌𝆫◌𝆫◌̀◌̕b; a◌֮◌𝆫◌𝆫◌̀◌̕b; a◌֮◌𝆫◌𝆫◌̀◌̕b; a◌֮◌𝆫◌𝆫◌̀◌̕b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING UP BOW, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 1D1AC 0062;00E0 05AE 1D1AC 0315 0062;0061 05AE 0300 1D1AC 0315 0062;00E0 05AE 1D1AC 0315 0062;0061 05AE 0300 1D1AC 0315 0062; # (a◌̕◌̀◌֮◌𝆬◌𝆬b; à◌֮◌𝆬◌𝆬◌̕b; a◌֮◌̀◌𝆬◌𝆬◌̕b; à◌֮◌𝆬◌𝆬◌̕b; a◌֮◌̀◌𝆬◌𝆬◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING HARMONIC, LATIN SMALL LETTER B
+0061 1D1AC 0315 0300 05AE 0062;0061 05AE 1D1AC 0300 0315 0062;0061 05AE 1D1AC 0300 0315 0062;0061 05AE 1D1AC 0300 0315 0062;0061 05AE 1D1AC 0300 0315 0062; # (a◌𝆬◌𝆬◌̕◌̀◌֮b; a◌֮◌𝆬◌𝆬◌̀◌̕b; a◌֮◌𝆬◌𝆬◌̀◌̕b; a◌֮◌𝆬◌𝆬◌̀◌̕b; a◌֮◌𝆬◌𝆬◌̀◌̕b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING HARMONIC, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+0061 0315 0300 05AE 1D1AD 0062;00E0 05AE 1D1AD 0315 0062;0061 05AE 0300 1D1AD 0315 0062;00E0 05AE 1D1AD 0315 0062;0061 05AE 0300 1D1AD 0315 0062; # (a◌̕◌̀◌֮◌𝆭◌𝆭b; à◌֮◌𝆭◌𝆭◌̕b; a◌֮◌̀◌𝆭◌𝆭◌̕b; à◌֮◌𝆭◌𝆭◌̕b; a◌֮◌̀◌𝆭◌𝆭◌̕b; ) LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, MUSICAL SYMBOL COMBINING SNAP PIZZICATO, LATIN SMALL LETTER B
+0061 1D1AD 0315 0300 05AE 0062;0061 05AE 1D1AD 0300 0315 0062;0061 05AE 1D1AD 0300 0315 0062;0061 05AE 1D1AD 0300 0315 0062;0061 05AE 1D1AD 0300 0315 0062; # (a◌𝆭◌𝆭◌̕◌̀◌֮b; a◌֮◌𝆭◌𝆭◌̀◌̕b; a◌֮◌𝆭◌𝆭◌̀◌̕b; a◌֮◌𝆭◌𝆭◌̀◌̕b; a◌֮◌𝆭◌𝆭◌̀◌̕b; ) LATIN SMALL LETTER A, MUSICAL SYMBOL COMBINING SNAP PIZZICATO, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT, HEBREW ACCENT ZINOR, LATIN SMALL LETTER B
+#
+# END OF FILE
diff --git a/third_party/heimdal/lib/wind/UnicodeData.py b/third_party/heimdal/lib/wind/UnicodeData.py
new file mode 100644
index 0000000..8ce3bca
--- /dev/null
+++ b/third_party/heimdal/lib/wind/UnicodeData.py
@@ -0,0 +1,57 @@
+#!/usr/local/bin/python
+# -*- coding: iso-8859-1 -*-
+
+# $Id$
+
+# Copyright (c) 2004 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+import re
+import string
+
+def read(filename):
+ """return a dict of unicode characters"""
+ ud = open(filename, 'r')
+ ret = {}
+ while True:
+ l = ud.readline()
+ if not l:
+ break
+ l = re.sub('#.*$', '', l)
+ if l == "\n":
+ continue
+ f = l.split(';')
+ key = int(f[0], 0x10)
+ if key in ret:
+ raise Exception('Duplicate key in UnicodeData')
+ ret[key] = f[1:]
+ ud.close()
+ return ret
diff --git a/third_party/heimdal/lib/wind/UnicodeData.txt b/third_party/heimdal/lib/wind/UnicodeData.txt
new file mode 100644
index 0000000..3710e17
--- /dev/null
+++ b/third_party/heimdal/lib/wind/UnicodeData.txt
@@ -0,0 +1,15100 @@
+0000;<control>;Cc;0;BN;;;;;N;NULL;;;;
+0001;<control>;Cc;0;BN;;;;;N;START OF HEADING;;;;
+0002;<control>;Cc;0;BN;;;;;N;START OF TEXT;;;;
+0003;<control>;Cc;0;BN;;;;;N;END OF TEXT;;;;
+0004;<control>;Cc;0;BN;;;;;N;END OF TRANSMISSION;;;;
+0005;<control>;Cc;0;BN;;;;;N;ENQUIRY;;;;
+0006;<control>;Cc;0;BN;;;;;N;ACKNOWLEDGE;;;;
+0007;<control>;Cc;0;BN;;;;;N;BELL;;;;
+0008;<control>;Cc;0;BN;;;;;N;BACKSPACE;;;;
+0009;<control>;Cc;0;S;;;;;N;CHARACTER TABULATION;;;;
+000A;<control>;Cc;0;B;;;;;N;LINE FEED (LF);;;;
+000B;<control>;Cc;0;S;;;;;N;LINE TABULATION;;;;
+000C;<control>;Cc;0;WS;;;;;N;FORM FEED (FF);;;;
+000D;<control>;Cc;0;B;;;;;N;CARRIAGE RETURN (CR);;;;
+000E;<control>;Cc;0;BN;;;;;N;SHIFT OUT;;;;
+000F;<control>;Cc;0;BN;;;;;N;SHIFT IN;;;;
+0010;<control>;Cc;0;BN;;;;;N;DATA LINK ESCAPE;;;;
+0011;<control>;Cc;0;BN;;;;;N;DEVICE CONTROL ONE;;;;
+0012;<control>;Cc;0;BN;;;;;N;DEVICE CONTROL TWO;;;;
+0013;<control>;Cc;0;BN;;;;;N;DEVICE CONTROL THREE;;;;
+0014;<control>;Cc;0;BN;;;;;N;DEVICE CONTROL FOUR;;;;
+0015;<control>;Cc;0;BN;;;;;N;NEGATIVE ACKNOWLEDGE;;;;
+0016;<control>;Cc;0;BN;;;;;N;SYNCHRONOUS IDLE;;;;
+0017;<control>;Cc;0;BN;;;;;N;END OF TRANSMISSION BLOCK;;;;
+0018;<control>;Cc;0;BN;;;;;N;CANCEL;;;;
+0019;<control>;Cc;0;BN;;;;;N;END OF MEDIUM;;;;
+001A;<control>;Cc;0;BN;;;;;N;SUBSTITUTE;;;;
+001B;<control>;Cc;0;BN;;;;;N;ESCAPE;;;;
+001C;<control>;Cc;0;B;;;;;N;INFORMATION SEPARATOR FOUR;;;;
+001D;<control>;Cc;0;B;;;;;N;INFORMATION SEPARATOR THREE;;;;
+001E;<control>;Cc;0;B;;;;;N;INFORMATION SEPARATOR TWO;;;;
+001F;<control>;Cc;0;S;;;;;N;INFORMATION SEPARATOR ONE;;;;
+0020;SPACE;Zs;0;WS;;;;;N;;;;;
+0021;EXCLAMATION MARK;Po;0;ON;;;;;N;;;;;
+0022;QUOTATION MARK;Po;0;ON;;;;;N;;;;;
+0023;NUMBER SIGN;Po;0;ET;;;;;N;;;;;
+0024;DOLLAR SIGN;Sc;0;ET;;;;;N;;;;;
+0025;PERCENT SIGN;Po;0;ET;;;;;N;;;;;
+0026;AMPERSAND;Po;0;ON;;;;;N;;;;;
+0027;APOSTROPHE;Po;0;ON;;;;;N;APOSTROPHE-QUOTE;;;;
+0028;LEFT PARENTHESIS;Ps;0;ON;;;;;Y;OPENING PARENTHESIS;;;;
+0029;RIGHT PARENTHESIS;Pe;0;ON;;;;;Y;CLOSING PARENTHESIS;;;;
+002A;ASTERISK;Po;0;ON;;;;;N;;;;;
+002B;PLUS SIGN;Sm;0;ES;;;;;N;;;;;
+002C;COMMA;Po;0;CS;;;;;N;;;;;
+002D;HYPHEN-MINUS;Pd;0;ES;;;;;N;;;;;
+002E;FULL STOP;Po;0;CS;;;;;N;PERIOD;;;;
+002F;SOLIDUS;Po;0;CS;;;;;N;SLASH;;;;
+0030;DIGIT ZERO;Nd;0;EN;;0;0;0;N;;;;;
+0031;DIGIT ONE;Nd;0;EN;;1;1;1;N;;;;;
+0032;DIGIT TWO;Nd;0;EN;;2;2;2;N;;;;;
+0033;DIGIT THREE;Nd;0;EN;;3;3;3;N;;;;;
+0034;DIGIT FOUR;Nd;0;EN;;4;4;4;N;;;;;
+0035;DIGIT FIVE;Nd;0;EN;;5;5;5;N;;;;;
+0036;DIGIT SIX;Nd;0;EN;;6;6;6;N;;;;;
+0037;DIGIT SEVEN;Nd;0;EN;;7;7;7;N;;;;;
+0038;DIGIT EIGHT;Nd;0;EN;;8;8;8;N;;;;;
+0039;DIGIT NINE;Nd;0;EN;;9;9;9;N;;;;;
+003A;COLON;Po;0;CS;;;;;N;;;;;
+003B;SEMICOLON;Po;0;ON;;;;;N;;;;;
+003C;LESS-THAN SIGN;Sm;0;ON;;;;;Y;;;;;
+003D;EQUALS SIGN;Sm;0;ON;;;;;N;;;;;
+003E;GREATER-THAN SIGN;Sm;0;ON;;;;;Y;;;;;
+003F;QUESTION MARK;Po;0;ON;;;;;N;;;;;
+0040;COMMERCIAL AT;Po;0;ON;;;;;N;;;;;
+0041;LATIN CAPITAL LETTER A;Lu;0;L;;;;;N;;;;0061;
+0042;LATIN CAPITAL LETTER B;Lu;0;L;;;;;N;;;;0062;
+0043;LATIN CAPITAL LETTER C;Lu;0;L;;;;;N;;;;0063;
+0044;LATIN CAPITAL LETTER D;Lu;0;L;;;;;N;;;;0064;
+0045;LATIN CAPITAL LETTER E;Lu;0;L;;;;;N;;;;0065;
+0046;LATIN CAPITAL LETTER F;Lu;0;L;;;;;N;;;;0066;
+0047;LATIN CAPITAL LETTER G;Lu;0;L;;;;;N;;;;0067;
+0048;LATIN CAPITAL LETTER H;Lu;0;L;;;;;N;;;;0068;
+0049;LATIN CAPITAL LETTER I;Lu;0;L;;;;;N;;;;0069;
+004A;LATIN CAPITAL LETTER J;Lu;0;L;;;;;N;;;;006A;
+004B;LATIN CAPITAL LETTER K;Lu;0;L;;;;;N;;;;006B;
+004C;LATIN CAPITAL LETTER L;Lu;0;L;;;;;N;;;;006C;
+004D;LATIN CAPITAL LETTER M;Lu;0;L;;;;;N;;;;006D;
+004E;LATIN CAPITAL LETTER N;Lu;0;L;;;;;N;;;;006E;
+004F;LATIN CAPITAL LETTER O;Lu;0;L;;;;;N;;;;006F;
+0050;LATIN CAPITAL LETTER P;Lu;0;L;;;;;N;;;;0070;
+0051;LATIN CAPITAL LETTER Q;Lu;0;L;;;;;N;;;;0071;
+0052;LATIN CAPITAL LETTER R;Lu;0;L;;;;;N;;;;0072;
+0053;LATIN CAPITAL LETTER S;Lu;0;L;;;;;N;;;;0073;
+0054;LATIN CAPITAL LETTER T;Lu;0;L;;;;;N;;;;0074;
+0055;LATIN CAPITAL LETTER U;Lu;0;L;;;;;N;;;;0075;
+0056;LATIN CAPITAL LETTER V;Lu;0;L;;;;;N;;;;0076;
+0057;LATIN CAPITAL LETTER W;Lu;0;L;;;;;N;;;;0077;
+0058;LATIN CAPITAL LETTER X;Lu;0;L;;;;;N;;;;0078;
+0059;LATIN CAPITAL LETTER Y;Lu;0;L;;;;;N;;;;0079;
+005A;LATIN CAPITAL LETTER Z;Lu;0;L;;;;;N;;;;007A;
+005B;LEFT SQUARE BRACKET;Ps;0;ON;;;;;Y;OPENING SQUARE BRACKET;;;;
+005C;REVERSE SOLIDUS;Po;0;ON;;;;;N;BACKSLASH;;;;
+005D;RIGHT SQUARE BRACKET;Pe;0;ON;;;;;Y;CLOSING SQUARE BRACKET;;;;
+005E;CIRCUMFLEX ACCENT;Sk;0;ON;;;;;N;SPACING CIRCUMFLEX;;;;
+005F;LOW LINE;Pc;0;ON;;;;;N;SPACING UNDERSCORE;;;;
+0060;GRAVE ACCENT;Sk;0;ON;;;;;N;SPACING GRAVE;;;;
+0061;LATIN SMALL LETTER A;Ll;0;L;;;;;N;;;0041;;0041
+0062;LATIN SMALL LETTER B;Ll;0;L;;;;;N;;;0042;;0042
+0063;LATIN SMALL LETTER C;Ll;0;L;;;;;N;;;0043;;0043
+0064;LATIN SMALL LETTER D;Ll;0;L;;;;;N;;;0044;;0044
+0065;LATIN SMALL LETTER E;Ll;0;L;;;;;N;;;0045;;0045
+0066;LATIN SMALL LETTER F;Ll;0;L;;;;;N;;;0046;;0046
+0067;LATIN SMALL LETTER G;Ll;0;L;;;;;N;;;0047;;0047
+0068;LATIN SMALL LETTER H;Ll;0;L;;;;;N;;;0048;;0048
+0069;LATIN SMALL LETTER I;Ll;0;L;;;;;N;;;0049;;0049
+006A;LATIN SMALL LETTER J;Ll;0;L;;;;;N;;;004A;;004A
+006B;LATIN SMALL LETTER K;Ll;0;L;;;;;N;;;004B;;004B
+006C;LATIN SMALL LETTER L;Ll;0;L;;;;;N;;;004C;;004C
+006D;LATIN SMALL LETTER M;Ll;0;L;;;;;N;;;004D;;004D
+006E;LATIN SMALL LETTER N;Ll;0;L;;;;;N;;;004E;;004E
+006F;LATIN SMALL LETTER O;Ll;0;L;;;;;N;;;004F;;004F
+0070;LATIN SMALL LETTER P;Ll;0;L;;;;;N;;;0050;;0050
+0071;LATIN SMALL LETTER Q;Ll;0;L;;;;;N;;;0051;;0051
+0072;LATIN SMALL LETTER R;Ll;0;L;;;;;N;;;0052;;0052
+0073;LATIN SMALL LETTER S;Ll;0;L;;;;;N;;;0053;;0053
+0074;LATIN SMALL LETTER T;Ll;0;L;;;;;N;;;0054;;0054
+0075;LATIN SMALL LETTER U;Ll;0;L;;;;;N;;;0055;;0055
+0076;LATIN SMALL LETTER V;Ll;0;L;;;;;N;;;0056;;0056
+0077;LATIN SMALL LETTER W;Ll;0;L;;;;;N;;;0057;;0057
+0078;LATIN SMALL LETTER X;Ll;0;L;;;;;N;;;0058;;0058
+0079;LATIN SMALL LETTER Y;Ll;0;L;;;;;N;;;0059;;0059
+007A;LATIN SMALL LETTER Z;Ll;0;L;;;;;N;;;005A;;005A
+007B;LEFT CURLY BRACKET;Ps;0;ON;;;;;Y;OPENING CURLY BRACKET;;;;
+007C;VERTICAL LINE;Sm;0;ON;;;;;N;VERTICAL BAR;;;;
+007D;RIGHT CURLY BRACKET;Pe;0;ON;;;;;Y;CLOSING CURLY BRACKET;;;;
+007E;TILDE;Sm;0;ON;;;;;N;;;;;
+007F;<control>;Cc;0;BN;;;;;N;DELETE;;;;
+0080;<control>;Cc;0;BN;;;;;N;;;;;
+0081;<control>;Cc;0;BN;;;;;N;;;;;
+0082;<control>;Cc;0;BN;;;;;N;BREAK PERMITTED HERE;;;;
+0083;<control>;Cc;0;BN;;;;;N;NO BREAK HERE;;;;
+0084;<control>;Cc;0;BN;;;;;N;;;;;
+0085;<control>;Cc;0;B;;;;;N;NEXT LINE (NEL);;;;
+0086;<control>;Cc;0;BN;;;;;N;START OF SELECTED AREA;;;;
+0087;<control>;Cc;0;BN;;;;;N;END OF SELECTED AREA;;;;
+0088;<control>;Cc;0;BN;;;;;N;CHARACTER TABULATION SET;;;;
+0089;<control>;Cc;0;BN;;;;;N;CHARACTER TABULATION WITH JUSTIFICATION;;;;
+008A;<control>;Cc;0;BN;;;;;N;LINE TABULATION SET;;;;
+008B;<control>;Cc;0;BN;;;;;N;PARTIAL LINE FORWARD;;;;
+008C;<control>;Cc;0;BN;;;;;N;PARTIAL LINE BACKWARD;;;;
+008D;<control>;Cc;0;BN;;;;;N;REVERSE LINE FEED;;;;
+008E;<control>;Cc;0;BN;;;;;N;SINGLE SHIFT TWO;;;;
+008F;<control>;Cc;0;BN;;;;;N;SINGLE SHIFT THREE;;;;
+0090;<control>;Cc;0;BN;;;;;N;DEVICE CONTROL STRING;;;;
+0091;<control>;Cc;0;BN;;;;;N;PRIVATE USE ONE;;;;
+0092;<control>;Cc;0;BN;;;;;N;PRIVATE USE TWO;;;;
+0093;<control>;Cc;0;BN;;;;;N;SET TRANSMIT STATE;;;;
+0094;<control>;Cc;0;BN;;;;;N;CANCEL CHARACTER;;;;
+0095;<control>;Cc;0;BN;;;;;N;MESSAGE WAITING;;;;
+0096;<control>;Cc;0;BN;;;;;N;START OF GUARDED AREA;;;;
+0097;<control>;Cc;0;BN;;;;;N;END OF GUARDED AREA;;;;
+0098;<control>;Cc;0;BN;;;;;N;START OF STRING;;;;
+0099;<control>;Cc;0;BN;;;;;N;;;;;
+009A;<control>;Cc;0;BN;;;;;N;SINGLE CHARACTER INTRODUCER;;;;
+009B;<control>;Cc;0;BN;;;;;N;CONTROL SEQUENCE INTRODUCER;;;;
+009C;<control>;Cc;0;BN;;;;;N;STRING TERMINATOR;;;;
+009D;<control>;Cc;0;BN;;;;;N;OPERATING SYSTEM COMMAND;;;;
+009E;<control>;Cc;0;BN;;;;;N;PRIVACY MESSAGE;;;;
+009F;<control>;Cc;0;BN;;;;;N;APPLICATION PROGRAM COMMAND;;;;
+00A0;NO-BREAK SPACE;Zs;0;CS;<noBreak> 0020;;;;N;NON-BREAKING SPACE;;;;
+00A1;INVERTED EXCLAMATION MARK;Po;0;ON;;;;;N;;;;;
+00A2;CENT SIGN;Sc;0;ET;;;;;N;;;;;
+00A3;POUND SIGN;Sc;0;ET;;;;;N;;;;;
+00A4;CURRENCY SIGN;Sc;0;ET;;;;;N;;;;;
+00A5;YEN SIGN;Sc;0;ET;;;;;N;;;;;
+00A6;BROKEN BAR;So;0;ON;;;;;N;BROKEN VERTICAL BAR;;;;
+00A7;SECTION SIGN;So;0;ON;;;;;N;;;;;
+00A8;DIAERESIS;Sk;0;ON;<compat> 0020 0308;;;;N;SPACING DIAERESIS;;;;
+00A9;COPYRIGHT SIGN;So;0;ON;;;;;N;;;;;
+00AA;FEMININE ORDINAL INDICATOR;Ll;0;L;<super> 0061;;;;N;;;;;
+00AB;LEFT-POINTING DOUBLE ANGLE QUOTATION MARK;Pi;0;ON;;;;;Y;LEFT POINTING GUILLEMET;*;;;
+00AC;NOT SIGN;Sm;0;ON;;;;;N;;;;;
+00AD;SOFT HYPHEN;Cf;0;BN;;;;;N;;;;;
+00AE;REGISTERED SIGN;So;0;ON;;;;;N;REGISTERED TRADE MARK SIGN;;;;
+00AF;MACRON;Sk;0;ON;<compat> 0020 0304;;;;N;SPACING MACRON;;;;
+00B0;DEGREE SIGN;So;0;ET;;;;;N;;;;;
+00B1;PLUS-MINUS SIGN;Sm;0;ET;;;;;N;PLUS-OR-MINUS SIGN;;;;
+00B2;SUPERSCRIPT TWO;No;0;EN;<super> 0032;;2;2;N;SUPERSCRIPT DIGIT TWO;;;;
+00B3;SUPERSCRIPT THREE;No;0;EN;<super> 0033;;3;3;N;SUPERSCRIPT DIGIT THREE;;;;
+00B4;ACUTE ACCENT;Sk;0;ON;<compat> 0020 0301;;;;N;SPACING ACUTE;;;;
+00B5;MICRO SIGN;Ll;0;L;<compat> 03BC;;;;N;;;039C;;039C
+00B6;PILCROW SIGN;So;0;ON;;;;;N;PARAGRAPH SIGN;;;;
+00B7;MIDDLE DOT;Po;0;ON;;;;;N;;;;;
+00B8;CEDILLA;Sk;0;ON;<compat> 0020 0327;;;;N;SPACING CEDILLA;;;;
+00B9;SUPERSCRIPT ONE;No;0;EN;<super> 0031;;1;1;N;SUPERSCRIPT DIGIT ONE;;;;
+00BA;MASCULINE ORDINAL INDICATOR;Ll;0;L;<super> 006F;;;;N;;;;;
+00BB;RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK;Pf;0;ON;;;;;Y;RIGHT POINTING GUILLEMET;*;;;
+00BC;VULGAR FRACTION ONE QUARTER;No;0;ON;<fraction> 0031 2044 0034;;;1/4;N;FRACTION ONE QUARTER;;;;
+00BD;VULGAR FRACTION ONE HALF;No;0;ON;<fraction> 0031 2044 0032;;;1/2;N;FRACTION ONE HALF;;;;
+00BE;VULGAR FRACTION THREE QUARTERS;No;0;ON;<fraction> 0033 2044 0034;;;3/4;N;FRACTION THREE QUARTERS;;;;
+00BF;INVERTED QUESTION MARK;Po;0;ON;;;;;N;;;;;
+00C0;LATIN CAPITAL LETTER A WITH GRAVE;Lu;0;L;0041 0300;;;;N;LATIN CAPITAL LETTER A GRAVE;;;00E0;
+00C1;LATIN CAPITAL LETTER A WITH ACUTE;Lu;0;L;0041 0301;;;;N;LATIN CAPITAL LETTER A ACUTE;;;00E1;
+00C2;LATIN CAPITAL LETTER A WITH CIRCUMFLEX;Lu;0;L;0041 0302;;;;N;LATIN CAPITAL LETTER A CIRCUMFLEX;;;00E2;
+00C3;LATIN CAPITAL LETTER A WITH TILDE;Lu;0;L;0041 0303;;;;N;LATIN CAPITAL LETTER A TILDE;;;00E3;
+00C4;LATIN CAPITAL LETTER A WITH DIAERESIS;Lu;0;L;0041 0308;;;;N;LATIN CAPITAL LETTER A DIAERESIS;;;00E4;
+00C5;LATIN CAPITAL LETTER A WITH RING ABOVE;Lu;0;L;0041 030A;;;;N;LATIN CAPITAL LETTER A RING;;;00E5;
+00C6;LATIN CAPITAL LETTER AE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER A E;ash *;;00E6;
+00C7;LATIN CAPITAL LETTER C WITH CEDILLA;Lu;0;L;0043 0327;;;;N;LATIN CAPITAL LETTER C CEDILLA;;;00E7;
+00C8;LATIN CAPITAL LETTER E WITH GRAVE;Lu;0;L;0045 0300;;;;N;LATIN CAPITAL LETTER E GRAVE;;;00E8;
+00C9;LATIN CAPITAL LETTER E WITH ACUTE;Lu;0;L;0045 0301;;;;N;LATIN CAPITAL LETTER E ACUTE;;;00E9;
+00CA;LATIN CAPITAL LETTER E WITH CIRCUMFLEX;Lu;0;L;0045 0302;;;;N;LATIN CAPITAL LETTER E CIRCUMFLEX;;;00EA;
+00CB;LATIN CAPITAL LETTER E WITH DIAERESIS;Lu;0;L;0045 0308;;;;N;LATIN CAPITAL LETTER E DIAERESIS;;;00EB;
+00CC;LATIN CAPITAL LETTER I WITH GRAVE;Lu;0;L;0049 0300;;;;N;LATIN CAPITAL LETTER I GRAVE;;;00EC;
+00CD;LATIN CAPITAL LETTER I WITH ACUTE;Lu;0;L;0049 0301;;;;N;LATIN CAPITAL LETTER I ACUTE;;;00ED;
+00CE;LATIN CAPITAL LETTER I WITH CIRCUMFLEX;Lu;0;L;0049 0302;;;;N;LATIN CAPITAL LETTER I CIRCUMFLEX;;;00EE;
+00CF;LATIN CAPITAL LETTER I WITH DIAERESIS;Lu;0;L;0049 0308;;;;N;LATIN CAPITAL LETTER I DIAERESIS;;;00EF;
+00D0;LATIN CAPITAL LETTER ETH;Lu;0;L;;;;;N;;Icelandic;;00F0;
+00D1;LATIN CAPITAL LETTER N WITH TILDE;Lu;0;L;004E 0303;;;;N;LATIN CAPITAL LETTER N TILDE;;;00F1;
+00D2;LATIN CAPITAL LETTER O WITH GRAVE;Lu;0;L;004F 0300;;;;N;LATIN CAPITAL LETTER O GRAVE;;;00F2;
+00D3;LATIN CAPITAL LETTER O WITH ACUTE;Lu;0;L;004F 0301;;;;N;LATIN CAPITAL LETTER O ACUTE;;;00F3;
+00D4;LATIN CAPITAL LETTER O WITH CIRCUMFLEX;Lu;0;L;004F 0302;;;;N;LATIN CAPITAL LETTER O CIRCUMFLEX;;;00F4;
+00D5;LATIN CAPITAL LETTER O WITH TILDE;Lu;0;L;004F 0303;;;;N;LATIN CAPITAL LETTER O TILDE;;;00F5;
+00D6;LATIN CAPITAL LETTER O WITH DIAERESIS;Lu;0;L;004F 0308;;;;N;LATIN CAPITAL LETTER O DIAERESIS;;;00F6;
+00D7;MULTIPLICATION SIGN;Sm;0;ON;;;;;N;;;;;
+00D8;LATIN CAPITAL LETTER O WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER O SLASH;;;00F8;
+00D9;LATIN CAPITAL LETTER U WITH GRAVE;Lu;0;L;0055 0300;;;;N;LATIN CAPITAL LETTER U GRAVE;;;00F9;
+00DA;LATIN CAPITAL LETTER U WITH ACUTE;Lu;0;L;0055 0301;;;;N;LATIN CAPITAL LETTER U ACUTE;;;00FA;
+00DB;LATIN CAPITAL LETTER U WITH CIRCUMFLEX;Lu;0;L;0055 0302;;;;N;LATIN CAPITAL LETTER U CIRCUMFLEX;;;00FB;
+00DC;LATIN CAPITAL LETTER U WITH DIAERESIS;Lu;0;L;0055 0308;;;;N;LATIN CAPITAL LETTER U DIAERESIS;;;00FC;
+00DD;LATIN CAPITAL LETTER Y WITH ACUTE;Lu;0;L;0059 0301;;;;N;LATIN CAPITAL LETTER Y ACUTE;;;00FD;
+00DE;LATIN CAPITAL LETTER THORN;Lu;0;L;;;;;N;;Icelandic;;00FE;
+00DF;LATIN SMALL LETTER SHARP S;Ll;0;L;;;;;N;;German;;;
+00E0;LATIN SMALL LETTER A WITH GRAVE;Ll;0;L;0061 0300;;;;N;LATIN SMALL LETTER A GRAVE;;00C0;;00C0
+00E1;LATIN SMALL LETTER A WITH ACUTE;Ll;0;L;0061 0301;;;;N;LATIN SMALL LETTER A ACUTE;;00C1;;00C1
+00E2;LATIN SMALL LETTER A WITH CIRCUMFLEX;Ll;0;L;0061 0302;;;;N;LATIN SMALL LETTER A CIRCUMFLEX;;00C2;;00C2
+00E3;LATIN SMALL LETTER A WITH TILDE;Ll;0;L;0061 0303;;;;N;LATIN SMALL LETTER A TILDE;;00C3;;00C3
+00E4;LATIN SMALL LETTER A WITH DIAERESIS;Ll;0;L;0061 0308;;;;N;LATIN SMALL LETTER A DIAERESIS;;00C4;;00C4
+00E5;LATIN SMALL LETTER A WITH RING ABOVE;Ll;0;L;0061 030A;;;;N;LATIN SMALL LETTER A RING;;00C5;;00C5
+00E6;LATIN SMALL LETTER AE;Ll;0;L;;;;;N;LATIN SMALL LETTER A E;ash *;00C6;;00C6
+00E7;LATIN SMALL LETTER C WITH CEDILLA;Ll;0;L;0063 0327;;;;N;LATIN SMALL LETTER C CEDILLA;;00C7;;00C7
+00E8;LATIN SMALL LETTER E WITH GRAVE;Ll;0;L;0065 0300;;;;N;LATIN SMALL LETTER E GRAVE;;00C8;;00C8
+00E9;LATIN SMALL LETTER E WITH ACUTE;Ll;0;L;0065 0301;;;;N;LATIN SMALL LETTER E ACUTE;;00C9;;00C9
+00EA;LATIN SMALL LETTER E WITH CIRCUMFLEX;Ll;0;L;0065 0302;;;;N;LATIN SMALL LETTER E CIRCUMFLEX;;00CA;;00CA
+00EB;LATIN SMALL LETTER E WITH DIAERESIS;Ll;0;L;0065 0308;;;;N;LATIN SMALL LETTER E DIAERESIS;;00CB;;00CB
+00EC;LATIN SMALL LETTER I WITH GRAVE;Ll;0;L;0069 0300;;;;N;LATIN SMALL LETTER I GRAVE;;00CC;;00CC
+00ED;LATIN SMALL LETTER I WITH ACUTE;Ll;0;L;0069 0301;;;;N;LATIN SMALL LETTER I ACUTE;;00CD;;00CD
+00EE;LATIN SMALL LETTER I WITH CIRCUMFLEX;Ll;0;L;0069 0302;;;;N;LATIN SMALL LETTER I CIRCUMFLEX;;00CE;;00CE
+00EF;LATIN SMALL LETTER I WITH DIAERESIS;Ll;0;L;0069 0308;;;;N;LATIN SMALL LETTER I DIAERESIS;;00CF;;00CF
+00F0;LATIN SMALL LETTER ETH;Ll;0;L;;;;;N;;Icelandic;00D0;;00D0
+00F1;LATIN SMALL LETTER N WITH TILDE;Ll;0;L;006E 0303;;;;N;LATIN SMALL LETTER N TILDE;;00D1;;00D1
+00F2;LATIN SMALL LETTER O WITH GRAVE;Ll;0;L;006F 0300;;;;N;LATIN SMALL LETTER O GRAVE;;00D2;;00D2
+00F3;LATIN SMALL LETTER O WITH ACUTE;Ll;0;L;006F 0301;;;;N;LATIN SMALL LETTER O ACUTE;;00D3;;00D3
+00F4;LATIN SMALL LETTER O WITH CIRCUMFLEX;Ll;0;L;006F 0302;;;;N;LATIN SMALL LETTER O CIRCUMFLEX;;00D4;;00D4
+00F5;LATIN SMALL LETTER O WITH TILDE;Ll;0;L;006F 0303;;;;N;LATIN SMALL LETTER O TILDE;;00D5;;00D5
+00F6;LATIN SMALL LETTER O WITH DIAERESIS;Ll;0;L;006F 0308;;;;N;LATIN SMALL LETTER O DIAERESIS;;00D6;;00D6
+00F7;DIVISION SIGN;Sm;0;ON;;;;;N;;;;;
+00F8;LATIN SMALL LETTER O WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER O SLASH;;00D8;;00D8
+00F9;LATIN SMALL LETTER U WITH GRAVE;Ll;0;L;0075 0300;;;;N;LATIN SMALL LETTER U GRAVE;;00D9;;00D9
+00FA;LATIN SMALL LETTER U WITH ACUTE;Ll;0;L;0075 0301;;;;N;LATIN SMALL LETTER U ACUTE;;00DA;;00DA
+00FB;LATIN SMALL LETTER U WITH CIRCUMFLEX;Ll;0;L;0075 0302;;;;N;LATIN SMALL LETTER U CIRCUMFLEX;;00DB;;00DB
+00FC;LATIN SMALL LETTER U WITH DIAERESIS;Ll;0;L;0075 0308;;;;N;LATIN SMALL LETTER U DIAERESIS;;00DC;;00DC
+00FD;LATIN SMALL LETTER Y WITH ACUTE;Ll;0;L;0079 0301;;;;N;LATIN SMALL LETTER Y ACUTE;;00DD;;00DD
+00FE;LATIN SMALL LETTER THORN;Ll;0;L;;;;;N;;Icelandic;00DE;;00DE
+00FF;LATIN SMALL LETTER Y WITH DIAERESIS;Ll;0;L;0079 0308;;;;N;LATIN SMALL LETTER Y DIAERESIS;;0178;;0178
+0100;LATIN CAPITAL LETTER A WITH MACRON;Lu;0;L;0041 0304;;;;N;LATIN CAPITAL LETTER A MACRON;;;0101;
+0101;LATIN SMALL LETTER A WITH MACRON;Ll;0;L;0061 0304;;;;N;LATIN SMALL LETTER A MACRON;;0100;;0100
+0102;LATIN CAPITAL LETTER A WITH BREVE;Lu;0;L;0041 0306;;;;N;LATIN CAPITAL LETTER A BREVE;;;0103;
+0103;LATIN SMALL LETTER A WITH BREVE;Ll;0;L;0061 0306;;;;N;LATIN SMALL LETTER A BREVE;;0102;;0102
+0104;LATIN CAPITAL LETTER A WITH OGONEK;Lu;0;L;0041 0328;;;;N;LATIN CAPITAL LETTER A OGONEK;;;0105;
+0105;LATIN SMALL LETTER A WITH OGONEK;Ll;0;L;0061 0328;;;;N;LATIN SMALL LETTER A OGONEK;;0104;;0104
+0106;LATIN CAPITAL LETTER C WITH ACUTE;Lu;0;L;0043 0301;;;;N;LATIN CAPITAL LETTER C ACUTE;;;0107;
+0107;LATIN SMALL LETTER C WITH ACUTE;Ll;0;L;0063 0301;;;;N;LATIN SMALL LETTER C ACUTE;;0106;;0106
+0108;LATIN CAPITAL LETTER C WITH CIRCUMFLEX;Lu;0;L;0043 0302;;;;N;LATIN CAPITAL LETTER C CIRCUMFLEX;;;0109;
+0109;LATIN SMALL LETTER C WITH CIRCUMFLEX;Ll;0;L;0063 0302;;;;N;LATIN SMALL LETTER C CIRCUMFLEX;;0108;;0108
+010A;LATIN CAPITAL LETTER C WITH DOT ABOVE;Lu;0;L;0043 0307;;;;N;LATIN CAPITAL LETTER C DOT;;;010B;
+010B;LATIN SMALL LETTER C WITH DOT ABOVE;Ll;0;L;0063 0307;;;;N;LATIN SMALL LETTER C DOT;;010A;;010A
+010C;LATIN CAPITAL LETTER C WITH CARON;Lu;0;L;0043 030C;;;;N;LATIN CAPITAL LETTER C HACEK;;;010D;
+010D;LATIN SMALL LETTER C WITH CARON;Ll;0;L;0063 030C;;;;N;LATIN SMALL LETTER C HACEK;;010C;;010C
+010E;LATIN CAPITAL LETTER D WITH CARON;Lu;0;L;0044 030C;;;;N;LATIN CAPITAL LETTER D HACEK;;;010F;
+010F;LATIN SMALL LETTER D WITH CARON;Ll;0;L;0064 030C;;;;N;LATIN SMALL LETTER D HACEK;;010E;;010E
+0110;LATIN CAPITAL LETTER D WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER D BAR;;;0111;
+0111;LATIN SMALL LETTER D WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER D BAR;;0110;;0110
+0112;LATIN CAPITAL LETTER E WITH MACRON;Lu;0;L;0045 0304;;;;N;LATIN CAPITAL LETTER E MACRON;;;0113;
+0113;LATIN SMALL LETTER E WITH MACRON;Ll;0;L;0065 0304;;;;N;LATIN SMALL LETTER E MACRON;;0112;;0112
+0114;LATIN CAPITAL LETTER E WITH BREVE;Lu;0;L;0045 0306;;;;N;LATIN CAPITAL LETTER E BREVE;;;0115;
+0115;LATIN SMALL LETTER E WITH BREVE;Ll;0;L;0065 0306;;;;N;LATIN SMALL LETTER E BREVE;;0114;;0114
+0116;LATIN CAPITAL LETTER E WITH DOT ABOVE;Lu;0;L;0045 0307;;;;N;LATIN CAPITAL LETTER E DOT;;;0117;
+0117;LATIN SMALL LETTER E WITH DOT ABOVE;Ll;0;L;0065 0307;;;;N;LATIN SMALL LETTER E DOT;;0116;;0116
+0118;LATIN CAPITAL LETTER E WITH OGONEK;Lu;0;L;0045 0328;;;;N;LATIN CAPITAL LETTER E OGONEK;;;0119;
+0119;LATIN SMALL LETTER E WITH OGONEK;Ll;0;L;0065 0328;;;;N;LATIN SMALL LETTER E OGONEK;;0118;;0118
+011A;LATIN CAPITAL LETTER E WITH CARON;Lu;0;L;0045 030C;;;;N;LATIN CAPITAL LETTER E HACEK;;;011B;
+011B;LATIN SMALL LETTER E WITH CARON;Ll;0;L;0065 030C;;;;N;LATIN SMALL LETTER E HACEK;;011A;;011A
+011C;LATIN CAPITAL LETTER G WITH CIRCUMFLEX;Lu;0;L;0047 0302;;;;N;LATIN CAPITAL LETTER G CIRCUMFLEX;;;011D;
+011D;LATIN SMALL LETTER G WITH CIRCUMFLEX;Ll;0;L;0067 0302;;;;N;LATIN SMALL LETTER G CIRCUMFLEX;;011C;;011C
+011E;LATIN CAPITAL LETTER G WITH BREVE;Lu;0;L;0047 0306;;;;N;LATIN CAPITAL LETTER G BREVE;;;011F;
+011F;LATIN SMALL LETTER G WITH BREVE;Ll;0;L;0067 0306;;;;N;LATIN SMALL LETTER G BREVE;;011E;;011E
+0120;LATIN CAPITAL LETTER G WITH DOT ABOVE;Lu;0;L;0047 0307;;;;N;LATIN CAPITAL LETTER G DOT;;;0121;
+0121;LATIN SMALL LETTER G WITH DOT ABOVE;Ll;0;L;0067 0307;;;;N;LATIN SMALL LETTER G DOT;;0120;;0120
+0122;LATIN CAPITAL LETTER G WITH CEDILLA;Lu;0;L;0047 0327;;;;N;LATIN CAPITAL LETTER G CEDILLA;;;0123;
+0123;LATIN SMALL LETTER G WITH CEDILLA;Ll;0;L;0067 0327;;;;N;LATIN SMALL LETTER G CEDILLA;;0122;;0122
+0124;LATIN CAPITAL LETTER H WITH CIRCUMFLEX;Lu;0;L;0048 0302;;;;N;LATIN CAPITAL LETTER H CIRCUMFLEX;;;0125;
+0125;LATIN SMALL LETTER H WITH CIRCUMFLEX;Ll;0;L;0068 0302;;;;N;LATIN SMALL LETTER H CIRCUMFLEX;;0124;;0124
+0126;LATIN CAPITAL LETTER H WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER H BAR;;;0127;
+0127;LATIN SMALL LETTER H WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER H BAR;;0126;;0126
+0128;LATIN CAPITAL LETTER I WITH TILDE;Lu;0;L;0049 0303;;;;N;LATIN CAPITAL LETTER I TILDE;;;0129;
+0129;LATIN SMALL LETTER I WITH TILDE;Ll;0;L;0069 0303;;;;N;LATIN SMALL LETTER I TILDE;;0128;;0128
+012A;LATIN CAPITAL LETTER I WITH MACRON;Lu;0;L;0049 0304;;;;N;LATIN CAPITAL LETTER I MACRON;;;012B;
+012B;LATIN SMALL LETTER I WITH MACRON;Ll;0;L;0069 0304;;;;N;LATIN SMALL LETTER I MACRON;;012A;;012A
+012C;LATIN CAPITAL LETTER I WITH BREVE;Lu;0;L;0049 0306;;;;N;LATIN CAPITAL LETTER I BREVE;;;012D;
+012D;LATIN SMALL LETTER I WITH BREVE;Ll;0;L;0069 0306;;;;N;LATIN SMALL LETTER I BREVE;;012C;;012C
+012E;LATIN CAPITAL LETTER I WITH OGONEK;Lu;0;L;0049 0328;;;;N;LATIN CAPITAL LETTER I OGONEK;;;012F;
+012F;LATIN SMALL LETTER I WITH OGONEK;Ll;0;L;0069 0328;;;;N;LATIN SMALL LETTER I OGONEK;;012E;;012E
+0130;LATIN CAPITAL LETTER I WITH DOT ABOVE;Lu;0;L;0049 0307;;;;N;LATIN CAPITAL LETTER I DOT;;;0069;
+0131;LATIN SMALL LETTER DOTLESS I;Ll;0;L;;;;;N;;;0049;;0049
+0132;LATIN CAPITAL LIGATURE IJ;Lu;0;L;<compat> 0049 004A;;;;N;LATIN CAPITAL LETTER I J;;;0133;
+0133;LATIN SMALL LIGATURE IJ;Ll;0;L;<compat> 0069 006A;;;;N;LATIN SMALL LETTER I J;;0132;;0132
+0134;LATIN CAPITAL LETTER J WITH CIRCUMFLEX;Lu;0;L;004A 0302;;;;N;LATIN CAPITAL LETTER J CIRCUMFLEX;;;0135;
+0135;LATIN SMALL LETTER J WITH CIRCUMFLEX;Ll;0;L;006A 0302;;;;N;LATIN SMALL LETTER J CIRCUMFLEX;;0134;;0134
+0136;LATIN CAPITAL LETTER K WITH CEDILLA;Lu;0;L;004B 0327;;;;N;LATIN CAPITAL LETTER K CEDILLA;;;0137;
+0137;LATIN SMALL LETTER K WITH CEDILLA;Ll;0;L;006B 0327;;;;N;LATIN SMALL LETTER K CEDILLA;;0136;;0136
+0138;LATIN SMALL LETTER KRA;Ll;0;L;;;;;N;;Greenlandic;;;
+0139;LATIN CAPITAL LETTER L WITH ACUTE;Lu;0;L;004C 0301;;;;N;LATIN CAPITAL LETTER L ACUTE;;;013A;
+013A;LATIN SMALL LETTER L WITH ACUTE;Ll;0;L;006C 0301;;;;N;LATIN SMALL LETTER L ACUTE;;0139;;0139
+013B;LATIN CAPITAL LETTER L WITH CEDILLA;Lu;0;L;004C 0327;;;;N;LATIN CAPITAL LETTER L CEDILLA;;;013C;
+013C;LATIN SMALL LETTER L WITH CEDILLA;Ll;0;L;006C 0327;;;;N;LATIN SMALL LETTER L CEDILLA;;013B;;013B
+013D;LATIN CAPITAL LETTER L WITH CARON;Lu;0;L;004C 030C;;;;N;LATIN CAPITAL LETTER L HACEK;;;013E;
+013E;LATIN SMALL LETTER L WITH CARON;Ll;0;L;006C 030C;;;;N;LATIN SMALL LETTER L HACEK;;013D;;013D
+013F;LATIN CAPITAL LETTER L WITH MIDDLE DOT;Lu;0;L;<compat> 004C 00B7;;;;N;;;;0140;
+0140;LATIN SMALL LETTER L WITH MIDDLE DOT;Ll;0;L;<compat> 006C 00B7;;;;N;;;013F;;013F
+0141;LATIN CAPITAL LETTER L WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER L SLASH;;;0142;
+0142;LATIN SMALL LETTER L WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER L SLASH;;0141;;0141
+0143;LATIN CAPITAL LETTER N WITH ACUTE;Lu;0;L;004E 0301;;;;N;LATIN CAPITAL LETTER N ACUTE;;;0144;
+0144;LATIN SMALL LETTER N WITH ACUTE;Ll;0;L;006E 0301;;;;N;LATIN SMALL LETTER N ACUTE;;0143;;0143
+0145;LATIN CAPITAL LETTER N WITH CEDILLA;Lu;0;L;004E 0327;;;;N;LATIN CAPITAL LETTER N CEDILLA;;;0146;
+0146;LATIN SMALL LETTER N WITH CEDILLA;Ll;0;L;006E 0327;;;;N;LATIN SMALL LETTER N CEDILLA;;0145;;0145
+0147;LATIN CAPITAL LETTER N WITH CARON;Lu;0;L;004E 030C;;;;N;LATIN CAPITAL LETTER N HACEK;;;0148;
+0148;LATIN SMALL LETTER N WITH CARON;Ll;0;L;006E 030C;;;;N;LATIN SMALL LETTER N HACEK;;0147;;0147
+0149;LATIN SMALL LETTER N PRECEDED BY APOSTROPHE;Ll;0;L;<compat> 02BC 006E;;;;N;LATIN SMALL LETTER APOSTROPHE N;;;;
+014A;LATIN CAPITAL LETTER ENG;Lu;0;L;;;;;N;;Sami;;014B;
+014B;LATIN SMALL LETTER ENG;Ll;0;L;;;;;N;;Sami;014A;;014A
+014C;LATIN CAPITAL LETTER O WITH MACRON;Lu;0;L;004F 0304;;;;N;LATIN CAPITAL LETTER O MACRON;;;014D;
+014D;LATIN SMALL LETTER O WITH MACRON;Ll;0;L;006F 0304;;;;N;LATIN SMALL LETTER O MACRON;;014C;;014C
+014E;LATIN CAPITAL LETTER O WITH BREVE;Lu;0;L;004F 0306;;;;N;LATIN CAPITAL LETTER O BREVE;;;014F;
+014F;LATIN SMALL LETTER O WITH BREVE;Ll;0;L;006F 0306;;;;N;LATIN SMALL LETTER O BREVE;;014E;;014E
+0150;LATIN CAPITAL LETTER O WITH DOUBLE ACUTE;Lu;0;L;004F 030B;;;;N;LATIN CAPITAL LETTER O DOUBLE ACUTE;;;0151;
+0151;LATIN SMALL LETTER O WITH DOUBLE ACUTE;Ll;0;L;006F 030B;;;;N;LATIN SMALL LETTER O DOUBLE ACUTE;;0150;;0150
+0152;LATIN CAPITAL LIGATURE OE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER O E;;;0153;
+0153;LATIN SMALL LIGATURE OE;Ll;0;L;;;;;N;LATIN SMALL LETTER O E;;0152;;0152
+0154;LATIN CAPITAL LETTER R WITH ACUTE;Lu;0;L;0052 0301;;;;N;LATIN CAPITAL LETTER R ACUTE;;;0155;
+0155;LATIN SMALL LETTER R WITH ACUTE;Ll;0;L;0072 0301;;;;N;LATIN SMALL LETTER R ACUTE;;0154;;0154
+0156;LATIN CAPITAL LETTER R WITH CEDILLA;Lu;0;L;0052 0327;;;;N;LATIN CAPITAL LETTER R CEDILLA;;;0157;
+0157;LATIN SMALL LETTER R WITH CEDILLA;Ll;0;L;0072 0327;;;;N;LATIN SMALL LETTER R CEDILLA;;0156;;0156
+0158;LATIN CAPITAL LETTER R WITH CARON;Lu;0;L;0052 030C;;;;N;LATIN CAPITAL LETTER R HACEK;;;0159;
+0159;LATIN SMALL LETTER R WITH CARON;Ll;0;L;0072 030C;;;;N;LATIN SMALL LETTER R HACEK;;0158;;0158
+015A;LATIN CAPITAL LETTER S WITH ACUTE;Lu;0;L;0053 0301;;;;N;LATIN CAPITAL LETTER S ACUTE;;;015B;
+015B;LATIN SMALL LETTER S WITH ACUTE;Ll;0;L;0073 0301;;;;N;LATIN SMALL LETTER S ACUTE;;015A;;015A
+015C;LATIN CAPITAL LETTER S WITH CIRCUMFLEX;Lu;0;L;0053 0302;;;;N;LATIN CAPITAL LETTER S CIRCUMFLEX;;;015D;
+015D;LATIN SMALL LETTER S WITH CIRCUMFLEX;Ll;0;L;0073 0302;;;;N;LATIN SMALL LETTER S CIRCUMFLEX;;015C;;015C
+015E;LATIN CAPITAL LETTER S WITH CEDILLA;Lu;0;L;0053 0327;;;;N;LATIN CAPITAL LETTER S CEDILLA;*;;015F;
+015F;LATIN SMALL LETTER S WITH CEDILLA;Ll;0;L;0073 0327;;;;N;LATIN SMALL LETTER S CEDILLA;*;015E;;015E
+0160;LATIN CAPITAL LETTER S WITH CARON;Lu;0;L;0053 030C;;;;N;LATIN CAPITAL LETTER S HACEK;;;0161;
+0161;LATIN SMALL LETTER S WITH CARON;Ll;0;L;0073 030C;;;;N;LATIN SMALL LETTER S HACEK;;0160;;0160
+0162;LATIN CAPITAL LETTER T WITH CEDILLA;Lu;0;L;0054 0327;;;;N;LATIN CAPITAL LETTER T CEDILLA;*;;0163;
+0163;LATIN SMALL LETTER T WITH CEDILLA;Ll;0;L;0074 0327;;;;N;LATIN SMALL LETTER T CEDILLA;*;0162;;0162
+0164;LATIN CAPITAL LETTER T WITH CARON;Lu;0;L;0054 030C;;;;N;LATIN CAPITAL LETTER T HACEK;;;0165;
+0165;LATIN SMALL LETTER T WITH CARON;Ll;0;L;0074 030C;;;;N;LATIN SMALL LETTER T HACEK;;0164;;0164
+0166;LATIN CAPITAL LETTER T WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER T BAR;;;0167;
+0167;LATIN SMALL LETTER T WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER T BAR;;0166;;0166
+0168;LATIN CAPITAL LETTER U WITH TILDE;Lu;0;L;0055 0303;;;;N;LATIN CAPITAL LETTER U TILDE;;;0169;
+0169;LATIN SMALL LETTER U WITH TILDE;Ll;0;L;0075 0303;;;;N;LATIN SMALL LETTER U TILDE;;0168;;0168
+016A;LATIN CAPITAL LETTER U WITH MACRON;Lu;0;L;0055 0304;;;;N;LATIN CAPITAL LETTER U MACRON;;;016B;
+016B;LATIN SMALL LETTER U WITH MACRON;Ll;0;L;0075 0304;;;;N;LATIN SMALL LETTER U MACRON;;016A;;016A
+016C;LATIN CAPITAL LETTER U WITH BREVE;Lu;0;L;0055 0306;;;;N;LATIN CAPITAL LETTER U BREVE;;;016D;
+016D;LATIN SMALL LETTER U WITH BREVE;Ll;0;L;0075 0306;;;;N;LATIN SMALL LETTER U BREVE;;016C;;016C
+016E;LATIN CAPITAL LETTER U WITH RING ABOVE;Lu;0;L;0055 030A;;;;N;LATIN CAPITAL LETTER U RING;;;016F;
+016F;LATIN SMALL LETTER U WITH RING ABOVE;Ll;0;L;0075 030A;;;;N;LATIN SMALL LETTER U RING;;016E;;016E
+0170;LATIN CAPITAL LETTER U WITH DOUBLE ACUTE;Lu;0;L;0055 030B;;;;N;LATIN CAPITAL LETTER U DOUBLE ACUTE;;;0171;
+0171;LATIN SMALL LETTER U WITH DOUBLE ACUTE;Ll;0;L;0075 030B;;;;N;LATIN SMALL LETTER U DOUBLE ACUTE;;0170;;0170
+0172;LATIN CAPITAL LETTER U WITH OGONEK;Lu;0;L;0055 0328;;;;N;LATIN CAPITAL LETTER U OGONEK;;;0173;
+0173;LATIN SMALL LETTER U WITH OGONEK;Ll;0;L;0075 0328;;;;N;LATIN SMALL LETTER U OGONEK;;0172;;0172
+0174;LATIN CAPITAL LETTER W WITH CIRCUMFLEX;Lu;0;L;0057 0302;;;;N;LATIN CAPITAL LETTER W CIRCUMFLEX;;;0175;
+0175;LATIN SMALL LETTER W WITH CIRCUMFLEX;Ll;0;L;0077 0302;;;;N;LATIN SMALL LETTER W CIRCUMFLEX;;0174;;0174
+0176;LATIN CAPITAL LETTER Y WITH CIRCUMFLEX;Lu;0;L;0059 0302;;;;N;LATIN CAPITAL LETTER Y CIRCUMFLEX;;;0177;
+0177;LATIN SMALL LETTER Y WITH CIRCUMFLEX;Ll;0;L;0079 0302;;;;N;LATIN SMALL LETTER Y CIRCUMFLEX;;0176;;0176
+0178;LATIN CAPITAL LETTER Y WITH DIAERESIS;Lu;0;L;0059 0308;;;;N;LATIN CAPITAL LETTER Y DIAERESIS;;;00FF;
+0179;LATIN CAPITAL LETTER Z WITH ACUTE;Lu;0;L;005A 0301;;;;N;LATIN CAPITAL LETTER Z ACUTE;;;017A;
+017A;LATIN SMALL LETTER Z WITH ACUTE;Ll;0;L;007A 0301;;;;N;LATIN SMALL LETTER Z ACUTE;;0179;;0179
+017B;LATIN CAPITAL LETTER Z WITH DOT ABOVE;Lu;0;L;005A 0307;;;;N;LATIN CAPITAL LETTER Z DOT;;;017C;
+017C;LATIN SMALL LETTER Z WITH DOT ABOVE;Ll;0;L;007A 0307;;;;N;LATIN SMALL LETTER Z DOT;;017B;;017B
+017D;LATIN CAPITAL LETTER Z WITH CARON;Lu;0;L;005A 030C;;;;N;LATIN CAPITAL LETTER Z HACEK;;;017E;
+017E;LATIN SMALL LETTER Z WITH CARON;Ll;0;L;007A 030C;;;;N;LATIN SMALL LETTER Z HACEK;;017D;;017D
+017F;LATIN SMALL LETTER LONG S;Ll;0;L;<compat> 0073;;;;N;;;0053;;0053
+0180;LATIN SMALL LETTER B WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER B BAR;;;;
+0181;LATIN CAPITAL LETTER B WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER B HOOK;;;0253;
+0182;LATIN CAPITAL LETTER B WITH TOPBAR;Lu;0;L;;;;;N;LATIN CAPITAL LETTER B TOPBAR;;;0183;
+0183;LATIN SMALL LETTER B WITH TOPBAR;Ll;0;L;;;;;N;LATIN SMALL LETTER B TOPBAR;;0182;;0182
+0184;LATIN CAPITAL LETTER TONE SIX;Lu;0;L;;;;;N;;;;0185;
+0185;LATIN SMALL LETTER TONE SIX;Ll;0;L;;;;;N;;;0184;;0184
+0186;LATIN CAPITAL LETTER OPEN O;Lu;0;L;;;;;N;;;;0254;
+0187;LATIN CAPITAL LETTER C WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER C HOOK;;;0188;
+0188;LATIN SMALL LETTER C WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER C HOOK;;0187;;0187
+0189;LATIN CAPITAL LETTER AFRICAN D;Lu;0;L;;;;;N;;*;;0256;
+018A;LATIN CAPITAL LETTER D WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER D HOOK;;;0257;
+018B;LATIN CAPITAL LETTER D WITH TOPBAR;Lu;0;L;;;;;N;LATIN CAPITAL LETTER D TOPBAR;;;018C;
+018C;LATIN SMALL LETTER D WITH TOPBAR;Ll;0;L;;;;;N;LATIN SMALL LETTER D TOPBAR;;018B;;018B
+018D;LATIN SMALL LETTER TURNED DELTA;Ll;0;L;;;;;N;;;;;
+018E;LATIN CAPITAL LETTER REVERSED E;Lu;0;L;;;;;N;LATIN CAPITAL LETTER TURNED E;;;01DD;
+018F;LATIN CAPITAL LETTER SCHWA;Lu;0;L;;;;;N;;;;0259;
+0190;LATIN CAPITAL LETTER OPEN E;Lu;0;L;;;;;N;LATIN CAPITAL LETTER EPSILON;;;025B;
+0191;LATIN CAPITAL LETTER F WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER F HOOK;;;0192;
+0192;LATIN SMALL LETTER F WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER SCRIPT F;;0191;;0191
+0193;LATIN CAPITAL LETTER G WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER G HOOK;;;0260;
+0194;LATIN CAPITAL LETTER GAMMA;Lu;0;L;;;;;N;;;;0263;
+0195;LATIN SMALL LETTER HV;Ll;0;L;;;;;N;LATIN SMALL LETTER H V;hwair;01F6;;01F6
+0196;LATIN CAPITAL LETTER IOTA;Lu;0;L;;;;;N;;;;0269;
+0197;LATIN CAPITAL LETTER I WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER BARRED I;;;0268;
+0198;LATIN CAPITAL LETTER K WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER K HOOK;;;0199;
+0199;LATIN SMALL LETTER K WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER K HOOK;;0198;;0198
+019A;LATIN SMALL LETTER L WITH BAR;Ll;0;L;;;;;N;LATIN SMALL LETTER BARRED L;;;;
+019B;LATIN SMALL LETTER LAMBDA WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER BARRED LAMBDA;;;;
+019C;LATIN CAPITAL LETTER TURNED M;Lu;0;L;;;;;N;;;;026F;
+019D;LATIN CAPITAL LETTER N WITH LEFT HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER N HOOK;;;0272;
+019E;LATIN SMALL LETTER N WITH LONG RIGHT LEG;Ll;0;L;;;;;N;;;0220;;0220
+019F;LATIN CAPITAL LETTER O WITH MIDDLE TILDE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER BARRED O;*;;0275;
+01A0;LATIN CAPITAL LETTER O WITH HORN;Lu;0;L;004F 031B;;;;N;LATIN CAPITAL LETTER O HORN;;;01A1;
+01A1;LATIN SMALL LETTER O WITH HORN;Ll;0;L;006F 031B;;;;N;LATIN SMALL LETTER O HORN;;01A0;;01A0
+01A2;LATIN CAPITAL LETTER OI;Lu;0;L;;;;;N;LATIN CAPITAL LETTER O I;gha;;01A3;
+01A3;LATIN SMALL LETTER OI;Ll;0;L;;;;;N;LATIN SMALL LETTER O I;gha;01A2;;01A2
+01A4;LATIN CAPITAL LETTER P WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER P HOOK;;;01A5;
+01A5;LATIN SMALL LETTER P WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER P HOOK;;01A4;;01A4
+01A6;LATIN LETTER YR;Lu;0;L;;;;;N;LATIN LETTER Y R;*;;0280;
+01A7;LATIN CAPITAL LETTER TONE TWO;Lu;0;L;;;;;N;;;;01A8;
+01A8;LATIN SMALL LETTER TONE TWO;Ll;0;L;;;;;N;;;01A7;;01A7
+01A9;LATIN CAPITAL LETTER ESH;Lu;0;L;;;;;N;;;;0283;
+01AA;LATIN LETTER REVERSED ESH LOOP;Ll;0;L;;;;;N;;;;;
+01AB;LATIN SMALL LETTER T WITH PALATAL HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER T PALATAL HOOK;;;;
+01AC;LATIN CAPITAL LETTER T WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER T HOOK;;;01AD;
+01AD;LATIN SMALL LETTER T WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER T HOOK;;01AC;;01AC
+01AE;LATIN CAPITAL LETTER T WITH RETROFLEX HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER T RETROFLEX HOOK;;;0288;
+01AF;LATIN CAPITAL LETTER U WITH HORN;Lu;0;L;0055 031B;;;;N;LATIN CAPITAL LETTER U HORN;;;01B0;
+01B0;LATIN SMALL LETTER U WITH HORN;Ll;0;L;0075 031B;;;;N;LATIN SMALL LETTER U HORN;;01AF;;01AF
+01B1;LATIN CAPITAL LETTER UPSILON;Lu;0;L;;;;;N;;;;028A;
+01B2;LATIN CAPITAL LETTER V WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER SCRIPT V;;;028B;
+01B3;LATIN CAPITAL LETTER Y WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER Y HOOK;;;01B4;
+01B4;LATIN SMALL LETTER Y WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER Y HOOK;;01B3;;01B3
+01B5;LATIN CAPITAL LETTER Z WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER Z BAR;;;01B6;
+01B6;LATIN SMALL LETTER Z WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER Z BAR;;01B5;;01B5
+01B7;LATIN CAPITAL LETTER EZH;Lu;0;L;;;;;N;LATIN CAPITAL LETTER YOGH;;;0292;
+01B8;LATIN CAPITAL LETTER EZH REVERSED;Lu;0;L;;;;;N;LATIN CAPITAL LETTER REVERSED YOGH;;;01B9;
+01B9;LATIN SMALL LETTER EZH REVERSED;Ll;0;L;;;;;N;LATIN SMALL LETTER REVERSED YOGH;;01B8;;01B8
+01BA;LATIN SMALL LETTER EZH WITH TAIL;Ll;0;L;;;;;N;LATIN SMALL LETTER YOGH WITH TAIL;;;;
+01BB;LATIN LETTER TWO WITH STROKE;Lo;0;L;;;;;N;LATIN LETTER TWO BAR;;;;
+01BC;LATIN CAPITAL LETTER TONE FIVE;Lu;0;L;;;;;N;;;;01BD;
+01BD;LATIN SMALL LETTER TONE FIVE;Ll;0;L;;;;;N;;;01BC;;01BC
+01BE;LATIN LETTER INVERTED GLOTTAL STOP WITH STROKE;Ll;0;L;;;;;N;LATIN LETTER INVERTED GLOTTAL STOP BAR;;;;
+01BF;LATIN LETTER WYNN;Ll;0;L;;;;;N;;;01F7;;01F7
+01C0;LATIN LETTER DENTAL CLICK;Lo;0;L;;;;;N;LATIN LETTER PIPE;;;;
+01C1;LATIN LETTER LATERAL CLICK;Lo;0;L;;;;;N;LATIN LETTER DOUBLE PIPE;;;;
+01C2;LATIN LETTER ALVEOLAR CLICK;Lo;0;L;;;;;N;LATIN LETTER PIPE DOUBLE BAR;;;;
+01C3;LATIN LETTER RETROFLEX CLICK;Lo;0;L;;;;;N;LATIN LETTER EXCLAMATION MARK;;;;
+01C4;LATIN CAPITAL LETTER DZ WITH CARON;Lu;0;L;<compat> 0044 017D;;;;N;LATIN CAPITAL LETTER D Z HACEK;;;01C6;01C5
+01C5;LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON;Lt;0;L;<compat> 0044 017E;;;;N;LATIN LETTER CAPITAL D SMALL Z HACEK;;01C4;01C6;01C5
+01C6;LATIN SMALL LETTER DZ WITH CARON;Ll;0;L;<compat> 0064 017E;;;;N;LATIN SMALL LETTER D Z HACEK;;01C4;;01C5
+01C7;LATIN CAPITAL LETTER LJ;Lu;0;L;<compat> 004C 004A;;;;N;LATIN CAPITAL LETTER L J;;;01C9;01C8
+01C8;LATIN CAPITAL LETTER L WITH SMALL LETTER J;Lt;0;L;<compat> 004C 006A;;;;N;LATIN LETTER CAPITAL L SMALL J;;01C7;01C9;01C8
+01C9;LATIN SMALL LETTER LJ;Ll;0;L;<compat> 006C 006A;;;;N;LATIN SMALL LETTER L J;;01C7;;01C8
+01CA;LATIN CAPITAL LETTER NJ;Lu;0;L;<compat> 004E 004A;;;;N;LATIN CAPITAL LETTER N J;;;01CC;01CB
+01CB;LATIN CAPITAL LETTER N WITH SMALL LETTER J;Lt;0;L;<compat> 004E 006A;;;;N;LATIN LETTER CAPITAL N SMALL J;;01CA;01CC;01CB
+01CC;LATIN SMALL LETTER NJ;Ll;0;L;<compat> 006E 006A;;;;N;LATIN SMALL LETTER N J;;01CA;;01CB
+01CD;LATIN CAPITAL LETTER A WITH CARON;Lu;0;L;0041 030C;;;;N;LATIN CAPITAL LETTER A HACEK;;;01CE;
+01CE;LATIN SMALL LETTER A WITH CARON;Ll;0;L;0061 030C;;;;N;LATIN SMALL LETTER A HACEK;;01CD;;01CD
+01CF;LATIN CAPITAL LETTER I WITH CARON;Lu;0;L;0049 030C;;;;N;LATIN CAPITAL LETTER I HACEK;;;01D0;
+01D0;LATIN SMALL LETTER I WITH CARON;Ll;0;L;0069 030C;;;;N;LATIN SMALL LETTER I HACEK;;01CF;;01CF
+01D1;LATIN CAPITAL LETTER O WITH CARON;Lu;0;L;004F 030C;;;;N;LATIN CAPITAL LETTER O HACEK;;;01D2;
+01D2;LATIN SMALL LETTER O WITH CARON;Ll;0;L;006F 030C;;;;N;LATIN SMALL LETTER O HACEK;;01D1;;01D1
+01D3;LATIN CAPITAL LETTER U WITH CARON;Lu;0;L;0055 030C;;;;N;LATIN CAPITAL LETTER U HACEK;;;01D4;
+01D4;LATIN SMALL LETTER U WITH CARON;Ll;0;L;0075 030C;;;;N;LATIN SMALL LETTER U HACEK;;01D3;;01D3
+01D5;LATIN CAPITAL LETTER U WITH DIAERESIS AND MACRON;Lu;0;L;00DC 0304;;;;N;LATIN CAPITAL LETTER U DIAERESIS MACRON;;;01D6;
+01D6;LATIN SMALL LETTER U WITH DIAERESIS AND MACRON;Ll;0;L;00FC 0304;;;;N;LATIN SMALL LETTER U DIAERESIS MACRON;;01D5;;01D5
+01D7;LATIN CAPITAL LETTER U WITH DIAERESIS AND ACUTE;Lu;0;L;00DC 0301;;;;N;LATIN CAPITAL LETTER U DIAERESIS ACUTE;;;01D8;
+01D8;LATIN SMALL LETTER U WITH DIAERESIS AND ACUTE;Ll;0;L;00FC 0301;;;;N;LATIN SMALL LETTER U DIAERESIS ACUTE;;01D7;;01D7
+01D9;LATIN CAPITAL LETTER U WITH DIAERESIS AND CARON;Lu;0;L;00DC 030C;;;;N;LATIN CAPITAL LETTER U DIAERESIS HACEK;;;01DA;
+01DA;LATIN SMALL LETTER U WITH DIAERESIS AND CARON;Ll;0;L;00FC 030C;;;;N;LATIN SMALL LETTER U DIAERESIS HACEK;;01D9;;01D9
+01DB;LATIN CAPITAL LETTER U WITH DIAERESIS AND GRAVE;Lu;0;L;00DC 0300;;;;N;LATIN CAPITAL LETTER U DIAERESIS GRAVE;;;01DC;
+01DC;LATIN SMALL LETTER U WITH DIAERESIS AND GRAVE;Ll;0;L;00FC 0300;;;;N;LATIN SMALL LETTER U DIAERESIS GRAVE;;01DB;;01DB
+01DD;LATIN SMALL LETTER TURNED E;Ll;0;L;;;;;N;;;018E;;018E
+01DE;LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON;Lu;0;L;00C4 0304;;;;N;LATIN CAPITAL LETTER A DIAERESIS MACRON;;;01DF;
+01DF;LATIN SMALL LETTER A WITH DIAERESIS AND MACRON;Ll;0;L;00E4 0304;;;;N;LATIN SMALL LETTER A DIAERESIS MACRON;;01DE;;01DE
+01E0;LATIN CAPITAL LETTER A WITH DOT ABOVE AND MACRON;Lu;0;L;0226 0304;;;;N;LATIN CAPITAL LETTER A DOT MACRON;;;01E1;
+01E1;LATIN SMALL LETTER A WITH DOT ABOVE AND MACRON;Ll;0;L;0227 0304;;;;N;LATIN SMALL LETTER A DOT MACRON;;01E0;;01E0
+01E2;LATIN CAPITAL LETTER AE WITH MACRON;Lu;0;L;00C6 0304;;;;N;LATIN CAPITAL LETTER A E MACRON;ash *;;01E3;
+01E3;LATIN SMALL LETTER AE WITH MACRON;Ll;0;L;00E6 0304;;;;N;LATIN SMALL LETTER A E MACRON;ash *;01E2;;01E2
+01E4;LATIN CAPITAL LETTER G WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER G BAR;;;01E5;
+01E5;LATIN SMALL LETTER G WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER G BAR;;01E4;;01E4
+01E6;LATIN CAPITAL LETTER G WITH CARON;Lu;0;L;0047 030C;;;;N;LATIN CAPITAL LETTER G HACEK;;;01E7;
+01E7;LATIN SMALL LETTER G WITH CARON;Ll;0;L;0067 030C;;;;N;LATIN SMALL LETTER G HACEK;;01E6;;01E6
+01E8;LATIN CAPITAL LETTER K WITH CARON;Lu;0;L;004B 030C;;;;N;LATIN CAPITAL LETTER K HACEK;;;01E9;
+01E9;LATIN SMALL LETTER K WITH CARON;Ll;0;L;006B 030C;;;;N;LATIN SMALL LETTER K HACEK;;01E8;;01E8
+01EA;LATIN CAPITAL LETTER O WITH OGONEK;Lu;0;L;004F 0328;;;;N;LATIN CAPITAL LETTER O OGONEK;;;01EB;
+01EB;LATIN SMALL LETTER O WITH OGONEK;Ll;0;L;006F 0328;;;;N;LATIN SMALL LETTER O OGONEK;;01EA;;01EA
+01EC;LATIN CAPITAL LETTER O WITH OGONEK AND MACRON;Lu;0;L;01EA 0304;;;;N;LATIN CAPITAL LETTER O OGONEK MACRON;;;01ED;
+01ED;LATIN SMALL LETTER O WITH OGONEK AND MACRON;Ll;0;L;01EB 0304;;;;N;LATIN SMALL LETTER O OGONEK MACRON;;01EC;;01EC
+01EE;LATIN CAPITAL LETTER EZH WITH CARON;Lu;0;L;01B7 030C;;;;N;LATIN CAPITAL LETTER YOGH HACEK;;;01EF;
+01EF;LATIN SMALL LETTER EZH WITH CARON;Ll;0;L;0292 030C;;;;N;LATIN SMALL LETTER YOGH HACEK;;01EE;;01EE
+01F0;LATIN SMALL LETTER J WITH CARON;Ll;0;L;006A 030C;;;;N;LATIN SMALL LETTER J HACEK;;;;
+01F1;LATIN CAPITAL LETTER DZ;Lu;0;L;<compat> 0044 005A;;;;N;;;;01F3;01F2
+01F2;LATIN CAPITAL LETTER D WITH SMALL LETTER Z;Lt;0;L;<compat> 0044 007A;;;;N;;;01F1;01F3;01F2
+01F3;LATIN SMALL LETTER DZ;Ll;0;L;<compat> 0064 007A;;;;N;;;01F1;;01F2
+01F4;LATIN CAPITAL LETTER G WITH ACUTE;Lu;0;L;0047 0301;;;;N;;;;01F5;
+01F5;LATIN SMALL LETTER G WITH ACUTE;Ll;0;L;0067 0301;;;;N;;;01F4;;01F4
+01F6;LATIN CAPITAL LETTER HWAIR;Lu;0;L;;;;;N;;;;0195;
+01F7;LATIN CAPITAL LETTER WYNN;Lu;0;L;;;;;N;;;;01BF;
+01F8;LATIN CAPITAL LETTER N WITH GRAVE;Lu;0;L;004E 0300;;;;N;;;;01F9;
+01F9;LATIN SMALL LETTER N WITH GRAVE;Ll;0;L;006E 0300;;;;N;;;01F8;;01F8
+01FA;LATIN CAPITAL LETTER A WITH RING ABOVE AND ACUTE;Lu;0;L;00C5 0301;;;;N;;;;01FB;
+01FB;LATIN SMALL LETTER A WITH RING ABOVE AND ACUTE;Ll;0;L;00E5 0301;;;;N;;;01FA;;01FA
+01FC;LATIN CAPITAL LETTER AE WITH ACUTE;Lu;0;L;00C6 0301;;;;N;;ash *;;01FD;
+01FD;LATIN SMALL LETTER AE WITH ACUTE;Ll;0;L;00E6 0301;;;;N;;ash *;01FC;;01FC
+01FE;LATIN CAPITAL LETTER O WITH STROKE AND ACUTE;Lu;0;L;00D8 0301;;;;N;;;;01FF;
+01FF;LATIN SMALL LETTER O WITH STROKE AND ACUTE;Ll;0;L;00F8 0301;;;;N;;;01FE;;01FE
+0200;LATIN CAPITAL LETTER A WITH DOUBLE GRAVE;Lu;0;L;0041 030F;;;;N;;;;0201;
+0201;LATIN SMALL LETTER A WITH DOUBLE GRAVE;Ll;0;L;0061 030F;;;;N;;;0200;;0200
+0202;LATIN CAPITAL LETTER A WITH INVERTED BREVE;Lu;0;L;0041 0311;;;;N;;;;0203;
+0203;LATIN SMALL LETTER A WITH INVERTED BREVE;Ll;0;L;0061 0311;;;;N;;;0202;;0202
+0204;LATIN CAPITAL LETTER E WITH DOUBLE GRAVE;Lu;0;L;0045 030F;;;;N;;;;0205;
+0205;LATIN SMALL LETTER E WITH DOUBLE GRAVE;Ll;0;L;0065 030F;;;;N;;;0204;;0204
+0206;LATIN CAPITAL LETTER E WITH INVERTED BREVE;Lu;0;L;0045 0311;;;;N;;;;0207;
+0207;LATIN SMALL LETTER E WITH INVERTED BREVE;Ll;0;L;0065 0311;;;;N;;;0206;;0206
+0208;LATIN CAPITAL LETTER I WITH DOUBLE GRAVE;Lu;0;L;0049 030F;;;;N;;;;0209;
+0209;LATIN SMALL LETTER I WITH DOUBLE GRAVE;Ll;0;L;0069 030F;;;;N;;;0208;;0208
+020A;LATIN CAPITAL LETTER I WITH INVERTED BREVE;Lu;0;L;0049 0311;;;;N;;;;020B;
+020B;LATIN SMALL LETTER I WITH INVERTED BREVE;Ll;0;L;0069 0311;;;;N;;;020A;;020A
+020C;LATIN CAPITAL LETTER O WITH DOUBLE GRAVE;Lu;0;L;004F 030F;;;;N;;;;020D;
+020D;LATIN SMALL LETTER O WITH DOUBLE GRAVE;Ll;0;L;006F 030F;;;;N;;;020C;;020C
+020E;LATIN CAPITAL LETTER O WITH INVERTED BREVE;Lu;0;L;004F 0311;;;;N;;;;020F;
+020F;LATIN SMALL LETTER O WITH INVERTED BREVE;Ll;0;L;006F 0311;;;;N;;;020E;;020E
+0210;LATIN CAPITAL LETTER R WITH DOUBLE GRAVE;Lu;0;L;0052 030F;;;;N;;;;0211;
+0211;LATIN SMALL LETTER R WITH DOUBLE GRAVE;Ll;0;L;0072 030F;;;;N;;;0210;;0210
+0212;LATIN CAPITAL LETTER R WITH INVERTED BREVE;Lu;0;L;0052 0311;;;;N;;;;0213;
+0213;LATIN SMALL LETTER R WITH INVERTED BREVE;Ll;0;L;0072 0311;;;;N;;;0212;;0212
+0214;LATIN CAPITAL LETTER U WITH DOUBLE GRAVE;Lu;0;L;0055 030F;;;;N;;;;0215;
+0215;LATIN SMALL LETTER U WITH DOUBLE GRAVE;Ll;0;L;0075 030F;;;;N;;;0214;;0214
+0216;LATIN CAPITAL LETTER U WITH INVERTED BREVE;Lu;0;L;0055 0311;;;;N;;;;0217;
+0217;LATIN SMALL LETTER U WITH INVERTED BREVE;Ll;0;L;0075 0311;;;;N;;;0216;;0216
+0218;LATIN CAPITAL LETTER S WITH COMMA BELOW;Lu;0;L;0053 0326;;;;N;;*;;0219;
+0219;LATIN SMALL LETTER S WITH COMMA BELOW;Ll;0;L;0073 0326;;;;N;;*;0218;;0218
+021A;LATIN CAPITAL LETTER T WITH COMMA BELOW;Lu;0;L;0054 0326;;;;N;;*;;021B;
+021B;LATIN SMALL LETTER T WITH COMMA BELOW;Ll;0;L;0074 0326;;;;N;;*;021A;;021A
+021C;LATIN CAPITAL LETTER YOGH;Lu;0;L;;;;;N;;;;021D;
+021D;LATIN SMALL LETTER YOGH;Ll;0;L;;;;;N;;;021C;;021C
+021E;LATIN CAPITAL LETTER H WITH CARON;Lu;0;L;0048 030C;;;;N;;;;021F;
+021F;LATIN SMALL LETTER H WITH CARON;Ll;0;L;0068 030C;;;;N;;;021E;;021E
+0220;LATIN CAPITAL LETTER N WITH LONG RIGHT LEG;Lu;0;L;;;;;N;;;;019E;
+0221;LATIN SMALL LETTER D WITH CURL;Ll;0;L;;;;;N;;;;;
+0222;LATIN CAPITAL LETTER OU;Lu;0;L;;;;;N;;;;0223;
+0223;LATIN SMALL LETTER OU;Ll;0;L;;;;;N;;;0222;;0222
+0224;LATIN CAPITAL LETTER Z WITH HOOK;Lu;0;L;;;;;N;;;;0225;
+0225;LATIN SMALL LETTER Z WITH HOOK;Ll;0;L;;;;;N;;;0224;;0224
+0226;LATIN CAPITAL LETTER A WITH DOT ABOVE;Lu;0;L;0041 0307;;;;N;;;;0227;
+0227;LATIN SMALL LETTER A WITH DOT ABOVE;Ll;0;L;0061 0307;;;;N;;;0226;;0226
+0228;LATIN CAPITAL LETTER E WITH CEDILLA;Lu;0;L;0045 0327;;;;N;;;;0229;
+0229;LATIN SMALL LETTER E WITH CEDILLA;Ll;0;L;0065 0327;;;;N;;;0228;;0228
+022A;LATIN CAPITAL LETTER O WITH DIAERESIS AND MACRON;Lu;0;L;00D6 0304;;;;N;;;;022B;
+022B;LATIN SMALL LETTER O WITH DIAERESIS AND MACRON;Ll;0;L;00F6 0304;;;;N;;;022A;;022A
+022C;LATIN CAPITAL LETTER O WITH TILDE AND MACRON;Lu;0;L;00D5 0304;;;;N;;;;022D;
+022D;LATIN SMALL LETTER O WITH TILDE AND MACRON;Ll;0;L;00F5 0304;;;;N;;;022C;;022C
+022E;LATIN CAPITAL LETTER O WITH DOT ABOVE;Lu;0;L;004F 0307;;;;N;;;;022F;
+022F;LATIN SMALL LETTER O WITH DOT ABOVE;Ll;0;L;006F 0307;;;;N;;;022E;;022E
+0230;LATIN CAPITAL LETTER O WITH DOT ABOVE AND MACRON;Lu;0;L;022E 0304;;;;N;;;;0231;
+0231;LATIN SMALL LETTER O WITH DOT ABOVE AND MACRON;Ll;0;L;022F 0304;;;;N;;;0230;;0230
+0232;LATIN CAPITAL LETTER Y WITH MACRON;Lu;0;L;0059 0304;;;;N;;;;0233;
+0233;LATIN SMALL LETTER Y WITH MACRON;Ll;0;L;0079 0304;;;;N;;;0232;;0232
+0234;LATIN SMALL LETTER L WITH CURL;Ll;0;L;;;;;N;;;;;
+0235;LATIN SMALL LETTER N WITH CURL;Ll;0;L;;;;;N;;;;;
+0236;LATIN SMALL LETTER T WITH CURL;Ll;0;L;;;;;N;;;;;
+0250;LATIN SMALL LETTER TURNED A;Ll;0;L;;;;;N;;;;;
+0251;LATIN SMALL LETTER ALPHA;Ll;0;L;;;;;N;LATIN SMALL LETTER SCRIPT A;;;;
+0252;LATIN SMALL LETTER TURNED ALPHA;Ll;0;L;;;;;N;LATIN SMALL LETTER TURNED SCRIPT A;;;;
+0253;LATIN SMALL LETTER B WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER B HOOK;;0181;;0181
+0254;LATIN SMALL LETTER OPEN O;Ll;0;L;;;;;N;;;0186;;0186
+0255;LATIN SMALL LETTER C WITH CURL;Ll;0;L;;;;;N;LATIN SMALL LETTER C CURL;;;;
+0256;LATIN SMALL LETTER D WITH TAIL;Ll;0;L;;;;;N;LATIN SMALL LETTER D RETROFLEX HOOK;;0189;;0189
+0257;LATIN SMALL LETTER D WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER D HOOK;;018A;;018A
+0258;LATIN SMALL LETTER REVERSED E;Ll;0;L;;;;;N;;;;;
+0259;LATIN SMALL LETTER SCHWA;Ll;0;L;;;;;N;;;018F;;018F
+025A;LATIN SMALL LETTER SCHWA WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER SCHWA HOOK;;;;
+025B;LATIN SMALL LETTER OPEN E;Ll;0;L;;;;;N;LATIN SMALL LETTER EPSILON;;0190;;0190
+025C;LATIN SMALL LETTER REVERSED OPEN E;Ll;0;L;;;;;N;LATIN SMALL LETTER REVERSED EPSILON;;;;
+025D;LATIN SMALL LETTER REVERSED OPEN E WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER REVERSED EPSILON HOOK;;;;
+025E;LATIN SMALL LETTER CLOSED REVERSED OPEN E;Ll;0;L;;;;;N;LATIN SMALL LETTER CLOSED REVERSED EPSILON;;;;
+025F;LATIN SMALL LETTER DOTLESS J WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER DOTLESS J BAR;;;;
+0260;LATIN SMALL LETTER G WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER G HOOK;;0193;;0193
+0261;LATIN SMALL LETTER SCRIPT G;Ll;0;L;;;;;N;;;;;
+0262;LATIN LETTER SMALL CAPITAL G;Ll;0;L;;;;;N;;;;;
+0263;LATIN SMALL LETTER GAMMA;Ll;0;L;;;;;N;;;0194;;0194
+0264;LATIN SMALL LETTER RAMS HORN;Ll;0;L;;;;;N;LATIN SMALL LETTER BABY GAMMA;;;;
+0265;LATIN SMALL LETTER TURNED H;Ll;0;L;;;;;N;;;;;
+0266;LATIN SMALL LETTER H WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER H HOOK;;;;
+0267;LATIN SMALL LETTER HENG WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER HENG HOOK;;;;
+0268;LATIN SMALL LETTER I WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER BARRED I;;0197;;0197
+0269;LATIN SMALL LETTER IOTA;Ll;0;L;;;;;N;;;0196;;0196
+026A;LATIN LETTER SMALL CAPITAL I;Ll;0;L;;;;;N;;;;;
+026B;LATIN SMALL LETTER L WITH MIDDLE TILDE;Ll;0;L;;;;;N;;;;;
+026C;LATIN SMALL LETTER L WITH BELT;Ll;0;L;;;;;N;LATIN SMALL LETTER L BELT;;;;
+026D;LATIN SMALL LETTER L WITH RETROFLEX HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER L RETROFLEX HOOK;;;;
+026E;LATIN SMALL LETTER LEZH;Ll;0;L;;;;;N;LATIN SMALL LETTER L YOGH;;;;
+026F;LATIN SMALL LETTER TURNED M;Ll;0;L;;;;;N;;;019C;;019C
+0270;LATIN SMALL LETTER TURNED M WITH LONG LEG;Ll;0;L;;;;;N;;;;;
+0271;LATIN SMALL LETTER M WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER M HOOK;;;;
+0272;LATIN SMALL LETTER N WITH LEFT HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER N HOOK;;019D;;019D
+0273;LATIN SMALL LETTER N WITH RETROFLEX HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER N RETROFLEX HOOK;;;;
+0274;LATIN LETTER SMALL CAPITAL N;Ll;0;L;;;;;N;;;;;
+0275;LATIN SMALL LETTER BARRED O;Ll;0;L;;;;;N;;;019F;;019F
+0276;LATIN LETTER SMALL CAPITAL OE;Ll;0;L;;;;;N;LATIN LETTER SMALL CAPITAL O E;;;;
+0277;LATIN SMALL LETTER CLOSED OMEGA;Ll;0;L;;;;;N;;;;;
+0278;LATIN SMALL LETTER PHI;Ll;0;L;;;;;N;;;;;
+0279;LATIN SMALL LETTER TURNED R;Ll;0;L;;;;;N;;;;;
+027A;LATIN SMALL LETTER TURNED R WITH LONG LEG;Ll;0;L;;;;;N;;;;;
+027B;LATIN SMALL LETTER TURNED R WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER TURNED R HOOK;;;;
+027C;LATIN SMALL LETTER R WITH LONG LEG;Ll;0;L;;;;;N;;;;;
+027D;LATIN SMALL LETTER R WITH TAIL;Ll;0;L;;;;;N;LATIN SMALL LETTER R HOOK;;;;
+027E;LATIN SMALL LETTER R WITH FISHHOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER FISHHOOK R;;;;
+027F;LATIN SMALL LETTER REVERSED R WITH FISHHOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER REVERSED FISHHOOK R;;;;
+0280;LATIN LETTER SMALL CAPITAL R;Ll;0;L;;;;;N;;*;01A6;;01A6
+0281;LATIN LETTER SMALL CAPITAL INVERTED R;Ll;0;L;;;;;N;;;;;
+0282;LATIN SMALL LETTER S WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER S HOOK;;;;
+0283;LATIN SMALL LETTER ESH;Ll;0;L;;;;;N;;;01A9;;01A9
+0284;LATIN SMALL LETTER DOTLESS J WITH STROKE AND HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER DOTLESS J BAR HOOK;;;;
+0285;LATIN SMALL LETTER SQUAT REVERSED ESH;Ll;0;L;;;;;N;;;;;
+0286;LATIN SMALL LETTER ESH WITH CURL;Ll;0;L;;;;;N;LATIN SMALL LETTER ESH CURL;;;;
+0287;LATIN SMALL LETTER TURNED T;Ll;0;L;;;;;N;;;;;
+0288;LATIN SMALL LETTER T WITH RETROFLEX HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER T RETROFLEX HOOK;;01AE;;01AE
+0289;LATIN SMALL LETTER U BAR;Ll;0;L;;;;;N;;;;;
+028A;LATIN SMALL LETTER UPSILON;Ll;0;L;;;;;N;;;01B1;;01B1
+028B;LATIN SMALL LETTER V WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER SCRIPT V;;01B2;;01B2
+028C;LATIN SMALL LETTER TURNED V;Ll;0;L;;;;;N;;;;;
+028D;LATIN SMALL LETTER TURNED W;Ll;0;L;;;;;N;;;;;
+028E;LATIN SMALL LETTER TURNED Y;Ll;0;L;;;;;N;;;;;
+028F;LATIN LETTER SMALL CAPITAL Y;Ll;0;L;;;;;N;;;;;
+0290;LATIN SMALL LETTER Z WITH RETROFLEX HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER Z RETROFLEX HOOK;;;;
+0291;LATIN SMALL LETTER Z WITH CURL;Ll;0;L;;;;;N;LATIN SMALL LETTER Z CURL;;;;
+0292;LATIN SMALL LETTER EZH;Ll;0;L;;;;;N;LATIN SMALL LETTER YOGH;;01B7;;01B7
+0293;LATIN SMALL LETTER EZH WITH CURL;Ll;0;L;;;;;N;LATIN SMALL LETTER YOGH CURL;;;;
+0294;LATIN LETTER GLOTTAL STOP;Ll;0;L;;;;;N;;;;;
+0295;LATIN LETTER PHARYNGEAL VOICED FRICATIVE;Ll;0;L;;;;;N;LATIN LETTER REVERSED GLOTTAL STOP;;;;
+0296;LATIN LETTER INVERTED GLOTTAL STOP;Ll;0;L;;;;;N;;;;;
+0297;LATIN LETTER STRETCHED C;Ll;0;L;;;;;N;;;;;
+0298;LATIN LETTER BILABIAL CLICK;Ll;0;L;;;;;N;LATIN LETTER BULLSEYE;;;;
+0299;LATIN LETTER SMALL CAPITAL B;Ll;0;L;;;;;N;;;;;
+029A;LATIN SMALL LETTER CLOSED OPEN E;Ll;0;L;;;;;N;LATIN SMALL LETTER CLOSED EPSILON;;;;
+029B;LATIN LETTER SMALL CAPITAL G WITH HOOK;Ll;0;L;;;;;N;LATIN LETTER SMALL CAPITAL G HOOK;;;;
+029C;LATIN LETTER SMALL CAPITAL H;Ll;0;L;;;;;N;;;;;
+029D;LATIN SMALL LETTER J WITH CROSSED-TAIL;Ll;0;L;;;;;N;LATIN SMALL LETTER CROSSED-TAIL J;;;;
+029E;LATIN SMALL LETTER TURNED K;Ll;0;L;;;;;N;;;;;
+029F;LATIN LETTER SMALL CAPITAL L;Ll;0;L;;;;;N;;;;;
+02A0;LATIN SMALL LETTER Q WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER Q HOOK;;;;
+02A1;LATIN LETTER GLOTTAL STOP WITH STROKE;Ll;0;L;;;;;N;LATIN LETTER GLOTTAL STOP BAR;;;;
+02A2;LATIN LETTER REVERSED GLOTTAL STOP WITH STROKE;Ll;0;L;;;;;N;LATIN LETTER REVERSED GLOTTAL STOP BAR;;;;
+02A3;LATIN SMALL LETTER DZ DIGRAPH;Ll;0;L;;;;;N;LATIN SMALL LETTER D Z;;;;
+02A4;LATIN SMALL LETTER DEZH DIGRAPH;Ll;0;L;;;;;N;LATIN SMALL LETTER D YOGH;;;;
+02A5;LATIN SMALL LETTER DZ DIGRAPH WITH CURL;Ll;0;L;;;;;N;LATIN SMALL LETTER D Z CURL;;;;
+02A6;LATIN SMALL LETTER TS DIGRAPH;Ll;0;L;;;;;N;LATIN SMALL LETTER T S;;;;
+02A7;LATIN SMALL LETTER TESH DIGRAPH;Ll;0;L;;;;;N;LATIN SMALL LETTER T ESH;;;;
+02A8;LATIN SMALL LETTER TC DIGRAPH WITH CURL;Ll;0;L;;;;;N;LATIN SMALL LETTER T C CURL;;;;
+02A9;LATIN SMALL LETTER FENG DIGRAPH;Ll;0;L;;;;;N;;;;;
+02AA;LATIN SMALL LETTER LS DIGRAPH;Ll;0;L;;;;;N;;;;;
+02AB;LATIN SMALL LETTER LZ DIGRAPH;Ll;0;L;;;;;N;;;;;
+02AC;LATIN LETTER BILABIAL PERCUSSIVE;Ll;0;L;;;;;N;;;;;
+02AD;LATIN LETTER BIDENTAL PERCUSSIVE;Ll;0;L;;;;;N;;;;;
+02AE;LATIN SMALL LETTER TURNED H WITH FISHHOOK;Ll;0;L;;;;;N;;;;;
+02AF;LATIN SMALL LETTER TURNED H WITH FISHHOOK AND TAIL;Ll;0;L;;;;;N;;;;;
+02B0;MODIFIER LETTER SMALL H;Lm;0;L;<super> 0068;;;;N;;;;;
+02B1;MODIFIER LETTER SMALL H WITH HOOK;Lm;0;L;<super> 0266;;;;N;MODIFIER LETTER SMALL H HOOK;;;;
+02B2;MODIFIER LETTER SMALL J;Lm;0;L;<super> 006A;;;;N;;;;;
+02B3;MODIFIER LETTER SMALL R;Lm;0;L;<super> 0072;;;;N;;;;;
+02B4;MODIFIER LETTER SMALL TURNED R;Lm;0;L;<super> 0279;;;;N;;;;;
+02B5;MODIFIER LETTER SMALL TURNED R WITH HOOK;Lm;0;L;<super> 027B;;;;N;MODIFIER LETTER SMALL TURNED R HOOK;;;;
+02B6;MODIFIER LETTER SMALL CAPITAL INVERTED R;Lm;0;L;<super> 0281;;;;N;;;;;
+02B7;MODIFIER LETTER SMALL W;Lm;0;L;<super> 0077;;;;N;;;;;
+02B8;MODIFIER LETTER SMALL Y;Lm;0;L;<super> 0079;;;;N;;;;;
+02B9;MODIFIER LETTER PRIME;Lm;0;ON;;;;;N;;;;;
+02BA;MODIFIER LETTER DOUBLE PRIME;Lm;0;ON;;;;;N;;;;;
+02BB;MODIFIER LETTER TURNED COMMA;Lm;0;L;;;;;N;;;;;
+02BC;MODIFIER LETTER APOSTROPHE;Lm;0;L;;;;;N;;;;;
+02BD;MODIFIER LETTER REVERSED COMMA;Lm;0;L;;;;;N;;;;;
+02BE;MODIFIER LETTER RIGHT HALF RING;Lm;0;L;;;;;N;;;;;
+02BF;MODIFIER LETTER LEFT HALF RING;Lm;0;L;;;;;N;;;;;
+02C0;MODIFIER LETTER GLOTTAL STOP;Lm;0;L;;;;;N;;;;;
+02C1;MODIFIER LETTER REVERSED GLOTTAL STOP;Lm;0;L;;;;;N;;;;;
+02C2;MODIFIER LETTER LEFT ARROWHEAD;Sk;0;ON;;;;;N;;;;;
+02C3;MODIFIER LETTER RIGHT ARROWHEAD;Sk;0;ON;;;;;N;;;;;
+02C4;MODIFIER LETTER UP ARROWHEAD;Sk;0;ON;;;;;N;;;;;
+02C5;MODIFIER LETTER DOWN ARROWHEAD;Sk;0;ON;;;;;N;;;;;
+02C6;MODIFIER LETTER CIRCUMFLEX ACCENT;Lm;0;ON;;;;;N;MODIFIER LETTER CIRCUMFLEX;;;;
+02C7;CARON;Lm;0;ON;;;;;N;MODIFIER LETTER HACEK;Mandarin Chinese third tone;;;
+02C8;MODIFIER LETTER VERTICAL LINE;Lm;0;ON;;;;;N;;;;;
+02C9;MODIFIER LETTER MACRON;Lm;0;ON;;;;;N;;Mandarin Chinese first tone;;;
+02CA;MODIFIER LETTER ACUTE ACCENT;Lm;0;ON;;;;;N;MODIFIER LETTER ACUTE;Mandarin Chinese second tone;;;
+02CB;MODIFIER LETTER GRAVE ACCENT;Lm;0;ON;;;;;N;MODIFIER LETTER GRAVE;Mandarin Chinese fourth tone;;;
+02CC;MODIFIER LETTER LOW VERTICAL LINE;Lm;0;ON;;;;;N;;;;;
+02CD;MODIFIER LETTER LOW MACRON;Lm;0;ON;;;;;N;;;;;
+02CE;MODIFIER LETTER LOW GRAVE ACCENT;Lm;0;ON;;;;;N;MODIFIER LETTER LOW GRAVE;;;;
+02CF;MODIFIER LETTER LOW ACUTE ACCENT;Lm;0;ON;;;;;N;MODIFIER LETTER LOW ACUTE;;;;
+02D0;MODIFIER LETTER TRIANGULAR COLON;Lm;0;L;;;;;N;;;;;
+02D1;MODIFIER LETTER HALF TRIANGULAR COLON;Lm;0;L;;;;;N;;;;;
+02D2;MODIFIER LETTER CENTRED RIGHT HALF RING;Sk;0;ON;;;;;N;MODIFIER LETTER CENTERED RIGHT HALF RING;;;;
+02D3;MODIFIER LETTER CENTRED LEFT HALF RING;Sk;0;ON;;;;;N;MODIFIER LETTER CENTERED LEFT HALF RING;;;;
+02D4;MODIFIER LETTER UP TACK;Sk;0;ON;;;;;N;;;;;
+02D5;MODIFIER LETTER DOWN TACK;Sk;0;ON;;;;;N;;;;;
+02D6;MODIFIER LETTER PLUS SIGN;Sk;0;ON;;;;;N;;;;;
+02D7;MODIFIER LETTER MINUS SIGN;Sk;0;ON;;;;;N;;;;;
+02D8;BREVE;Sk;0;ON;<compat> 0020 0306;;;;N;SPACING BREVE;;;;
+02D9;DOT ABOVE;Sk;0;ON;<compat> 0020 0307;;;;N;SPACING DOT ABOVE;Mandarin Chinese light tone;;;
+02DA;RING ABOVE;Sk;0;ON;<compat> 0020 030A;;;;N;SPACING RING ABOVE;;;;
+02DB;OGONEK;Sk;0;ON;<compat> 0020 0328;;;;N;SPACING OGONEK;;;;
+02DC;SMALL TILDE;Sk;0;ON;<compat> 0020 0303;;;;N;SPACING TILDE;;;;
+02DD;DOUBLE ACUTE ACCENT;Sk;0;ON;<compat> 0020 030B;;;;N;SPACING DOUBLE ACUTE;;;;
+02DE;MODIFIER LETTER RHOTIC HOOK;Sk;0;ON;;;;;N;;;;;
+02DF;MODIFIER LETTER CROSS ACCENT;Sk;0;ON;;;;;N;;;;;
+02E0;MODIFIER LETTER SMALL GAMMA;Lm;0;L;<super> 0263;;;;N;;;;;
+02E1;MODIFIER LETTER SMALL L;Lm;0;L;<super> 006C;;;;N;;;;;
+02E2;MODIFIER LETTER SMALL S;Lm;0;L;<super> 0073;;;;N;;;;;
+02E3;MODIFIER LETTER SMALL X;Lm;0;L;<super> 0078;;;;N;;;;;
+02E4;MODIFIER LETTER SMALL REVERSED GLOTTAL STOP;Lm;0;L;<super> 0295;;;;N;;;;;
+02E5;MODIFIER LETTER EXTRA-HIGH TONE BAR;Sk;0;ON;;;;;N;;;;;
+02E6;MODIFIER LETTER HIGH TONE BAR;Sk;0;ON;;;;;N;;;;;
+02E7;MODIFIER LETTER MID TONE BAR;Sk;0;ON;;;;;N;;;;;
+02E8;MODIFIER LETTER LOW TONE BAR;Sk;0;ON;;;;;N;;;;;
+02E9;MODIFIER LETTER EXTRA-LOW TONE BAR;Sk;0;ON;;;;;N;;;;;
+02EA;MODIFIER LETTER YIN DEPARTING TONE MARK;Sk;0;ON;;;;;N;;;;;
+02EB;MODIFIER LETTER YANG DEPARTING TONE MARK;Sk;0;ON;;;;;N;;;;;
+02EC;MODIFIER LETTER VOICING;Sk;0;ON;;;;;N;;;;;
+02ED;MODIFIER LETTER UNASPIRATED;Sk;0;ON;;;;;N;;;;;
+02EE;MODIFIER LETTER DOUBLE APOSTROPHE;Lm;0;L;;;;;N;;;;;
+02EF;MODIFIER LETTER LOW DOWN ARROWHEAD;Sk;0;ON;;;;;N;;;;;
+02F0;MODIFIER LETTER LOW UP ARROWHEAD;Sk;0;ON;;;;;N;;;;;
+02F1;MODIFIER LETTER LOW LEFT ARROWHEAD;Sk;0;ON;;;;;N;;;;;
+02F2;MODIFIER LETTER LOW RIGHT ARROWHEAD;Sk;0;ON;;;;;N;;;;;
+02F3;MODIFIER LETTER LOW RING;Sk;0;ON;;;;;N;;;;;
+02F4;MODIFIER LETTER MIDDLE GRAVE ACCENT;Sk;0;ON;;;;;N;;;;;
+02F5;MODIFIER LETTER MIDDLE DOUBLE GRAVE ACCENT;Sk;0;ON;;;;;N;;;;;
+02F6;MODIFIER LETTER MIDDLE DOUBLE ACUTE ACCENT;Sk;0;ON;;;;;N;;;;;
+02F7;MODIFIER LETTER LOW TILDE;Sk;0;ON;;;;;N;;;;;
+02F8;MODIFIER LETTER RAISED COLON;Sk;0;ON;;;;;N;;;;;
+02F9;MODIFIER LETTER BEGIN HIGH TONE;Sk;0;ON;;;;;N;;;;;
+02FA;MODIFIER LETTER END HIGH TONE;Sk;0;ON;;;;;N;;;;;
+02FB;MODIFIER LETTER BEGIN LOW TONE;Sk;0;ON;;;;;N;;;;;
+02FC;MODIFIER LETTER END LOW TONE;Sk;0;ON;;;;;N;;;;;
+02FD;MODIFIER LETTER SHELF;Sk;0;ON;;;;;N;;;;;
+02FE;MODIFIER LETTER OPEN SHELF;Sk;0;ON;;;;;N;;;;;
+02FF;MODIFIER LETTER LOW LEFT ARROW;Sk;0;ON;;;;;N;;;;;
+0300;COMBINING GRAVE ACCENT;Mn;230;NSM;;;;;N;NON-SPACING GRAVE;Varia;;;
+0301;COMBINING ACUTE ACCENT;Mn;230;NSM;;;;;N;NON-SPACING ACUTE;Oxia, Tonos;;;
+0302;COMBINING CIRCUMFLEX ACCENT;Mn;230;NSM;;;;;N;NON-SPACING CIRCUMFLEX;;;;
+0303;COMBINING TILDE;Mn;230;NSM;;;;;N;NON-SPACING TILDE;;;;
+0304;COMBINING MACRON;Mn;230;NSM;;;;;N;NON-SPACING MACRON;;;;
+0305;COMBINING OVERLINE;Mn;230;NSM;;;;;N;NON-SPACING OVERSCORE;;;;
+0306;COMBINING BREVE;Mn;230;NSM;;;;;N;NON-SPACING BREVE;Vrachy;;;
+0307;COMBINING DOT ABOVE;Mn;230;NSM;;;;;N;NON-SPACING DOT ABOVE;;;;
+0308;COMBINING DIAERESIS;Mn;230;NSM;;;;;N;NON-SPACING DIAERESIS;Dialytika;;;
+0309;COMBINING HOOK ABOVE;Mn;230;NSM;;;;;N;NON-SPACING HOOK ABOVE;;;;
+030A;COMBINING RING ABOVE;Mn;230;NSM;;;;;N;NON-SPACING RING ABOVE;;;;
+030B;COMBINING DOUBLE ACUTE ACCENT;Mn;230;NSM;;;;;N;NON-SPACING DOUBLE ACUTE;;;;
+030C;COMBINING CARON;Mn;230;NSM;;;;;N;NON-SPACING HACEK;;;;
+030D;COMBINING VERTICAL LINE ABOVE;Mn;230;NSM;;;;;N;NON-SPACING VERTICAL LINE ABOVE;;;;
+030E;COMBINING DOUBLE VERTICAL LINE ABOVE;Mn;230;NSM;;;;;N;NON-SPACING DOUBLE VERTICAL LINE ABOVE;;;;
+030F;COMBINING DOUBLE GRAVE ACCENT;Mn;230;NSM;;;;;N;NON-SPACING DOUBLE GRAVE;;;;
+0310;COMBINING CANDRABINDU;Mn;230;NSM;;;;;N;NON-SPACING CANDRABINDU;;;;
+0311;COMBINING INVERTED BREVE;Mn;230;NSM;;;;;N;NON-SPACING INVERTED BREVE;;;;
+0312;COMBINING TURNED COMMA ABOVE;Mn;230;NSM;;;;;N;NON-SPACING TURNED COMMA ABOVE;;;;
+0313;COMBINING COMMA ABOVE;Mn;230;NSM;;;;;N;NON-SPACING COMMA ABOVE;Psili;;;
+0314;COMBINING REVERSED COMMA ABOVE;Mn;230;NSM;;;;;N;NON-SPACING REVERSED COMMA ABOVE;Dasia;;;
+0315;COMBINING COMMA ABOVE RIGHT;Mn;232;NSM;;;;;N;NON-SPACING COMMA ABOVE RIGHT;;;;
+0316;COMBINING GRAVE ACCENT BELOW;Mn;220;NSM;;;;;N;NON-SPACING GRAVE BELOW;;;;
+0317;COMBINING ACUTE ACCENT BELOW;Mn;220;NSM;;;;;N;NON-SPACING ACUTE BELOW;;;;
+0318;COMBINING LEFT TACK BELOW;Mn;220;NSM;;;;;N;NON-SPACING LEFT TACK BELOW;;;;
+0319;COMBINING RIGHT TACK BELOW;Mn;220;NSM;;;;;N;NON-SPACING RIGHT TACK BELOW;;;;
+031A;COMBINING LEFT ANGLE ABOVE;Mn;232;NSM;;;;;N;NON-SPACING LEFT ANGLE ABOVE;;;;
+031B;COMBINING HORN;Mn;216;NSM;;;;;N;NON-SPACING HORN;;;;
+031C;COMBINING LEFT HALF RING BELOW;Mn;220;NSM;;;;;N;NON-SPACING LEFT HALF RING BELOW;;;;
+031D;COMBINING UP TACK BELOW;Mn;220;NSM;;;;;N;NON-SPACING UP TACK BELOW;;;;
+031E;COMBINING DOWN TACK BELOW;Mn;220;NSM;;;;;N;NON-SPACING DOWN TACK BELOW;;;;
+031F;COMBINING PLUS SIGN BELOW;Mn;220;NSM;;;;;N;NON-SPACING PLUS SIGN BELOW;;;;
+0320;COMBINING MINUS SIGN BELOW;Mn;220;NSM;;;;;N;NON-SPACING MINUS SIGN BELOW;;;;
+0321;COMBINING PALATALIZED HOOK BELOW;Mn;202;NSM;;;;;N;NON-SPACING PALATALIZED HOOK BELOW;;;;
+0322;COMBINING RETROFLEX HOOK BELOW;Mn;202;NSM;;;;;N;NON-SPACING RETROFLEX HOOK BELOW;;;;
+0323;COMBINING DOT BELOW;Mn;220;NSM;;;;;N;NON-SPACING DOT BELOW;;;;
+0324;COMBINING DIAERESIS BELOW;Mn;220;NSM;;;;;N;NON-SPACING DOUBLE DOT BELOW;;;;
+0325;COMBINING RING BELOW;Mn;220;NSM;;;;;N;NON-SPACING RING BELOW;;;;
+0326;COMBINING COMMA BELOW;Mn;220;NSM;;;;;N;NON-SPACING COMMA BELOW;;;;
+0327;COMBINING CEDILLA;Mn;202;NSM;;;;;N;NON-SPACING CEDILLA;;;;
+0328;COMBINING OGONEK;Mn;202;NSM;;;;;N;NON-SPACING OGONEK;;;;
+0329;COMBINING VERTICAL LINE BELOW;Mn;220;NSM;;;;;N;NON-SPACING VERTICAL LINE BELOW;;;;
+032A;COMBINING BRIDGE BELOW;Mn;220;NSM;;;;;N;NON-SPACING BRIDGE BELOW;;;;
+032B;COMBINING INVERTED DOUBLE ARCH BELOW;Mn;220;NSM;;;;;N;NON-SPACING INVERTED DOUBLE ARCH BELOW;;;;
+032C;COMBINING CARON BELOW;Mn;220;NSM;;;;;N;NON-SPACING HACEK BELOW;;;;
+032D;COMBINING CIRCUMFLEX ACCENT BELOW;Mn;220;NSM;;;;;N;NON-SPACING CIRCUMFLEX BELOW;;;;
+032E;COMBINING BREVE BELOW;Mn;220;NSM;;;;;N;NON-SPACING BREVE BELOW;;;;
+032F;COMBINING INVERTED BREVE BELOW;Mn;220;NSM;;;;;N;NON-SPACING INVERTED BREVE BELOW;;;;
+0330;COMBINING TILDE BELOW;Mn;220;NSM;;;;;N;NON-SPACING TILDE BELOW;;;;
+0331;COMBINING MACRON BELOW;Mn;220;NSM;;;;;N;NON-SPACING MACRON BELOW;;;;
+0332;COMBINING LOW LINE;Mn;220;NSM;;;;;N;NON-SPACING UNDERSCORE;;;;
+0333;COMBINING DOUBLE LOW LINE;Mn;220;NSM;;;;;N;NON-SPACING DOUBLE UNDERSCORE;;;;
+0334;COMBINING TILDE OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING TILDE OVERLAY;;;;
+0335;COMBINING SHORT STROKE OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING SHORT BAR OVERLAY;;;;
+0336;COMBINING LONG STROKE OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING LONG BAR OVERLAY;;;;
+0337;COMBINING SHORT SOLIDUS OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING SHORT SLASH OVERLAY;;;;
+0338;COMBINING LONG SOLIDUS OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING LONG SLASH OVERLAY;;;;
+0339;COMBINING RIGHT HALF RING BELOW;Mn;220;NSM;;;;;N;NON-SPACING RIGHT HALF RING BELOW;;;;
+033A;COMBINING INVERTED BRIDGE BELOW;Mn;220;NSM;;;;;N;NON-SPACING INVERTED BRIDGE BELOW;;;;
+033B;COMBINING SQUARE BELOW;Mn;220;NSM;;;;;N;NON-SPACING SQUARE BELOW;;;;
+033C;COMBINING SEAGULL BELOW;Mn;220;NSM;;;;;N;NON-SPACING SEAGULL BELOW;;;;
+033D;COMBINING X ABOVE;Mn;230;NSM;;;;;N;NON-SPACING X ABOVE;;;;
+033E;COMBINING VERTICAL TILDE;Mn;230;NSM;;;;;N;NON-SPACING VERTICAL TILDE;;;;
+033F;COMBINING DOUBLE OVERLINE;Mn;230;NSM;;;;;N;NON-SPACING DOUBLE OVERSCORE;;;;
+0340;COMBINING GRAVE TONE MARK;Mn;230;NSM;0300;;;;N;NON-SPACING GRAVE TONE MARK;Vietnamese;;;
+0341;COMBINING ACUTE TONE MARK;Mn;230;NSM;0301;;;;N;NON-SPACING ACUTE TONE MARK;Vietnamese;;;
+0342;COMBINING GREEK PERISPOMENI;Mn;230;NSM;;;;;N;;;;;
+0343;COMBINING GREEK KORONIS;Mn;230;NSM;0313;;;;N;;;;;
+0344;COMBINING GREEK DIALYTIKA TONOS;Mn;230;NSM;0308 0301;;;;N;GREEK NON-SPACING DIAERESIS TONOS;;;;
+0345;COMBINING GREEK YPOGEGRAMMENI;Mn;240;NSM;;;;;N;GREEK NON-SPACING IOTA BELOW;;0399;;0399
+0346;COMBINING BRIDGE ABOVE;Mn;230;NSM;;;;;N;;;;;
+0347;COMBINING EQUALS SIGN BELOW;Mn;220;NSM;;;;;N;;;;;
+0348;COMBINING DOUBLE VERTICAL LINE BELOW;Mn;220;NSM;;;;;N;;;;;
+0349;COMBINING LEFT ANGLE BELOW;Mn;220;NSM;;;;;N;;;;;
+034A;COMBINING NOT TILDE ABOVE;Mn;230;NSM;;;;;N;;;;;
+034B;COMBINING HOMOTHETIC ABOVE;Mn;230;NSM;;;;;N;;;;;
+034C;COMBINING ALMOST EQUAL TO ABOVE;Mn;230;NSM;;;;;N;;;;;
+034D;COMBINING LEFT RIGHT ARROW BELOW;Mn;220;NSM;;;;;N;;;;;
+034E;COMBINING UPWARDS ARROW BELOW;Mn;220;NSM;;;;;N;;;;;
+034F;COMBINING GRAPHEME JOINER;Mn;0;NSM;;;;;N;;;;;
+0350;COMBINING RIGHT ARROWHEAD ABOVE;Mn;230;NSM;;;;;N;;;;;
+0351;COMBINING LEFT HALF RING ABOVE;Mn;230;NSM;;;;;N;;;;;
+0352;COMBINING FERMATA;Mn;230;NSM;;;;;N;;;;;
+0353;COMBINING X BELOW;Mn;220;NSM;;;;;N;;;;;
+0354;COMBINING LEFT ARROWHEAD BELOW;Mn;220;NSM;;;;;N;;;;;
+0355;COMBINING RIGHT ARROWHEAD BELOW;Mn;220;NSM;;;;;N;;;;;
+0356;COMBINING RIGHT ARROWHEAD AND UP ARROWHEAD BELOW;Mn;220;NSM;;;;;N;;;;;
+0357;COMBINING RIGHT HALF RING ABOVE;Mn;230;NSM;;;;;N;;;;;
+035D;COMBINING DOUBLE BREVE;Mn;234;NSM;;;;;N;;;;;
+035E;COMBINING DOUBLE MACRON;Mn;234;NSM;;;;;N;;;;;
+035F;COMBINING DOUBLE MACRON BELOW;Mn;233;NSM;;;;;N;;;;;
+0360;COMBINING DOUBLE TILDE;Mn;234;NSM;;;;;N;;;;;
+0361;COMBINING DOUBLE INVERTED BREVE;Mn;234;NSM;;;;;N;;;;;
+0362;COMBINING DOUBLE RIGHTWARDS ARROW BELOW;Mn;233;NSM;;;;;N;;;;;
+0363;COMBINING LATIN SMALL LETTER A;Mn;230;NSM;;;;;N;;;;;
+0364;COMBINING LATIN SMALL LETTER E;Mn;230;NSM;;;;;N;;;;;
+0365;COMBINING LATIN SMALL LETTER I;Mn;230;NSM;;;;;N;;;;;
+0366;COMBINING LATIN SMALL LETTER O;Mn;230;NSM;;;;;N;;;;;
+0367;COMBINING LATIN SMALL LETTER U;Mn;230;NSM;;;;;N;;;;;
+0368;COMBINING LATIN SMALL LETTER C;Mn;230;NSM;;;;;N;;;;;
+0369;COMBINING LATIN SMALL LETTER D;Mn;230;NSM;;;;;N;;;;;
+036A;COMBINING LATIN SMALL LETTER H;Mn;230;NSM;;;;;N;;;;;
+036B;COMBINING LATIN SMALL LETTER M;Mn;230;NSM;;;;;N;;;;;
+036C;COMBINING LATIN SMALL LETTER R;Mn;230;NSM;;;;;N;;;;;
+036D;COMBINING LATIN SMALL LETTER T;Mn;230;NSM;;;;;N;;;;;
+036E;COMBINING LATIN SMALL LETTER V;Mn;230;NSM;;;;;N;;;;;
+036F;COMBINING LATIN SMALL LETTER X;Mn;230;NSM;;;;;N;;;;;
+0374;GREEK NUMERAL SIGN;Sk;0;ON;02B9;;;;N;GREEK UPPER NUMERAL SIGN;Dexia keraia;;;
+0375;GREEK LOWER NUMERAL SIGN;Sk;0;ON;;;;;N;;Aristeri keraia;;;
+037A;GREEK YPOGEGRAMMENI;Lm;0;L;<compat> 0020 0345;;;;N;GREEK SPACING IOTA BELOW;;;;
+037E;GREEK QUESTION MARK;Po;0;ON;003B;;;;N;;Erotimatiko;;;
+0384;GREEK TONOS;Sk;0;ON;<compat> 0020 0301;;;;N;GREEK SPACING TONOS;;;;
+0385;GREEK DIALYTIKA TONOS;Sk;0;ON;00A8 0301;;;;N;GREEK SPACING DIAERESIS TONOS;;;;
+0386;GREEK CAPITAL LETTER ALPHA WITH TONOS;Lu;0;L;0391 0301;;;;N;GREEK CAPITAL LETTER ALPHA TONOS;;;03AC;
+0387;GREEK ANO TELEIA;Po;0;ON;00B7;;;;N;;;;;
+0388;GREEK CAPITAL LETTER EPSILON WITH TONOS;Lu;0;L;0395 0301;;;;N;GREEK CAPITAL LETTER EPSILON TONOS;;;03AD;
+0389;GREEK CAPITAL LETTER ETA WITH TONOS;Lu;0;L;0397 0301;;;;N;GREEK CAPITAL LETTER ETA TONOS;;;03AE;
+038A;GREEK CAPITAL LETTER IOTA WITH TONOS;Lu;0;L;0399 0301;;;;N;GREEK CAPITAL LETTER IOTA TONOS;;;03AF;
+038C;GREEK CAPITAL LETTER OMICRON WITH TONOS;Lu;0;L;039F 0301;;;;N;GREEK CAPITAL LETTER OMICRON TONOS;;;03CC;
+038E;GREEK CAPITAL LETTER UPSILON WITH TONOS;Lu;0;L;03A5 0301;;;;N;GREEK CAPITAL LETTER UPSILON TONOS;;;03CD;
+038F;GREEK CAPITAL LETTER OMEGA WITH TONOS;Lu;0;L;03A9 0301;;;;N;GREEK CAPITAL LETTER OMEGA TONOS;;;03CE;
+0390;GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS;Ll;0;L;03CA 0301;;;;N;GREEK SMALL LETTER IOTA DIAERESIS TONOS;;;;
+0391;GREEK CAPITAL LETTER ALPHA;Lu;0;L;;;;;N;;;;03B1;
+0392;GREEK CAPITAL LETTER BETA;Lu;0;L;;;;;N;;;;03B2;
+0393;GREEK CAPITAL LETTER GAMMA;Lu;0;L;;;;;N;;;;03B3;
+0394;GREEK CAPITAL LETTER DELTA;Lu;0;L;;;;;N;;;;03B4;
+0395;GREEK CAPITAL LETTER EPSILON;Lu;0;L;;;;;N;;;;03B5;
+0396;GREEK CAPITAL LETTER ZETA;Lu;0;L;;;;;N;;;;03B6;
+0397;GREEK CAPITAL LETTER ETA;Lu;0;L;;;;;N;;;;03B7;
+0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8;
+0399;GREEK CAPITAL LETTER IOTA;Lu;0;L;;;;;N;;;;03B9;
+039A;GREEK CAPITAL LETTER KAPPA;Lu;0;L;;;;;N;;;;03BA;
+039B;GREEK CAPITAL LETTER LAMDA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER LAMBDA;;;03BB;
+039C;GREEK CAPITAL LETTER MU;Lu;0;L;;;;;N;;;;03BC;
+039D;GREEK CAPITAL LETTER NU;Lu;0;L;;;;;N;;;;03BD;
+039E;GREEK CAPITAL LETTER XI;Lu;0;L;;;;;N;;;;03BE;
+039F;GREEK CAPITAL LETTER OMICRON;Lu;0;L;;;;;N;;;;03BF;
+03A0;GREEK CAPITAL LETTER PI;Lu;0;L;;;;;N;;;;03C0;
+03A1;GREEK CAPITAL LETTER RHO;Lu;0;L;;;;;N;;;;03C1;
+03A3;GREEK CAPITAL LETTER SIGMA;Lu;0;L;;;;;N;;;;03C3;
+03A4;GREEK CAPITAL LETTER TAU;Lu;0;L;;;;;N;;;;03C4;
+03A5;GREEK CAPITAL LETTER UPSILON;Lu;0;L;;;;;N;;;;03C5;
+03A6;GREEK CAPITAL LETTER PHI;Lu;0;L;;;;;N;;;;03C6;
+03A7;GREEK CAPITAL LETTER CHI;Lu;0;L;;;;;N;;;;03C7;
+03A8;GREEK CAPITAL LETTER PSI;Lu;0;L;;;;;N;;;;03C8;
+03A9;GREEK CAPITAL LETTER OMEGA;Lu;0;L;;;;;N;;;;03C9;
+03AA;GREEK CAPITAL LETTER IOTA WITH DIALYTIKA;Lu;0;L;0399 0308;;;;N;GREEK CAPITAL LETTER IOTA DIAERESIS;;;03CA;
+03AB;GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA;Lu;0;L;03A5 0308;;;;N;GREEK CAPITAL LETTER UPSILON DIAERESIS;;;03CB;
+03AC;GREEK SMALL LETTER ALPHA WITH TONOS;Ll;0;L;03B1 0301;;;;N;GREEK SMALL LETTER ALPHA TONOS;;0386;;0386
+03AD;GREEK SMALL LETTER EPSILON WITH TONOS;Ll;0;L;03B5 0301;;;;N;GREEK SMALL LETTER EPSILON TONOS;;0388;;0388
+03AE;GREEK SMALL LETTER ETA WITH TONOS;Ll;0;L;03B7 0301;;;;N;GREEK SMALL LETTER ETA TONOS;;0389;;0389
+03AF;GREEK SMALL LETTER IOTA WITH TONOS;Ll;0;L;03B9 0301;;;;N;GREEK SMALL LETTER IOTA TONOS;;038A;;038A
+03B0;GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS;Ll;0;L;03CB 0301;;;;N;GREEK SMALL LETTER UPSILON DIAERESIS TONOS;;;;
+03B1;GREEK SMALL LETTER ALPHA;Ll;0;L;;;;;N;;;0391;;0391
+03B2;GREEK SMALL LETTER BETA;Ll;0;L;;;;;N;;;0392;;0392
+03B3;GREEK SMALL LETTER GAMMA;Ll;0;L;;;;;N;;;0393;;0393
+03B4;GREEK SMALL LETTER DELTA;Ll;0;L;;;;;N;;;0394;;0394
+03B5;GREEK SMALL LETTER EPSILON;Ll;0;L;;;;;N;;;0395;;0395
+03B6;GREEK SMALL LETTER ZETA;Ll;0;L;;;;;N;;;0396;;0396
+03B7;GREEK SMALL LETTER ETA;Ll;0;L;;;;;N;;;0397;;0397
+03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398
+03B9;GREEK SMALL LETTER IOTA;Ll;0;L;;;;;N;;;0399;;0399
+03BA;GREEK SMALL LETTER KAPPA;Ll;0;L;;;;;N;;;039A;;039A
+03BB;GREEK SMALL LETTER LAMDA;Ll;0;L;;;;;N;GREEK SMALL LETTER LAMBDA;;039B;;039B
+03BC;GREEK SMALL LETTER MU;Ll;0;L;;;;;N;;;039C;;039C
+03BD;GREEK SMALL LETTER NU;Ll;0;L;;;;;N;;;039D;;039D
+03BE;GREEK SMALL LETTER XI;Ll;0;L;;;;;N;;;039E;;039E
+03BF;GREEK SMALL LETTER OMICRON;Ll;0;L;;;;;N;;;039F;;039F
+03C0;GREEK SMALL LETTER PI;Ll;0;L;;;;;N;;;03A0;;03A0
+03C1;GREEK SMALL LETTER RHO;Ll;0;L;;;;;N;;;03A1;;03A1
+03C2;GREEK SMALL LETTER FINAL SIGMA;Ll;0;L;;;;;N;;;03A3;;03A3
+03C3;GREEK SMALL LETTER SIGMA;Ll;0;L;;;;;N;;;03A3;;03A3
+03C4;GREEK SMALL LETTER TAU;Ll;0;L;;;;;N;;;03A4;;03A4
+03C5;GREEK SMALL LETTER UPSILON;Ll;0;L;;;;;N;;;03A5;;03A5
+03C6;GREEK SMALL LETTER PHI;Ll;0;L;;;;;N;;;03A6;;03A6
+03C7;GREEK SMALL LETTER CHI;Ll;0;L;;;;;N;;;03A7;;03A7
+03C8;GREEK SMALL LETTER PSI;Ll;0;L;;;;;N;;;03A8;;03A8
+03C9;GREEK SMALL LETTER OMEGA;Ll;0;L;;;;;N;;;03A9;;03A9
+03CA;GREEK SMALL LETTER IOTA WITH DIALYTIKA;Ll;0;L;03B9 0308;;;;N;GREEK SMALL LETTER IOTA DIAERESIS;;03AA;;03AA
+03CB;GREEK SMALL LETTER UPSILON WITH DIALYTIKA;Ll;0;L;03C5 0308;;;;N;GREEK SMALL LETTER UPSILON DIAERESIS;;03AB;;03AB
+03CC;GREEK SMALL LETTER OMICRON WITH TONOS;Ll;0;L;03BF 0301;;;;N;GREEK SMALL LETTER OMICRON TONOS;;038C;;038C
+03CD;GREEK SMALL LETTER UPSILON WITH TONOS;Ll;0;L;03C5 0301;;;;N;GREEK SMALL LETTER UPSILON TONOS;;038E;;038E
+03CE;GREEK SMALL LETTER OMEGA WITH TONOS;Ll;0;L;03C9 0301;;;;N;GREEK SMALL LETTER OMEGA TONOS;;038F;;038F
+03D0;GREEK BETA SYMBOL;Ll;0;L;<compat> 03B2;;;;N;GREEK SMALL LETTER CURLED BETA;;0392;;0392
+03D1;GREEK THETA SYMBOL;Ll;0;L;<compat> 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398
+03D2;GREEK UPSILON WITH HOOK SYMBOL;Lu;0;L;<compat> 03A5;;;;N;GREEK CAPITAL LETTER UPSILON HOOK;;;;
+03D3;GREEK UPSILON WITH ACUTE AND HOOK SYMBOL;Lu;0;L;03D2 0301;;;;N;GREEK CAPITAL LETTER UPSILON HOOK TONOS;;;;
+03D4;GREEK UPSILON WITH DIAERESIS AND HOOK SYMBOL;Lu;0;L;03D2 0308;;;;N;GREEK CAPITAL LETTER UPSILON HOOK DIAERESIS;;;;
+03D5;GREEK PHI SYMBOL;Ll;0;L;<compat> 03C6;;;;N;GREEK SMALL LETTER SCRIPT PHI;;03A6;;03A6
+03D6;GREEK PI SYMBOL;Ll;0;L;<compat> 03C0;;;;N;GREEK SMALL LETTER OMEGA PI;;03A0;;03A0
+03D7;GREEK KAI SYMBOL;Ll;0;L;;;;;N;;;;;
+03D8;GREEK LETTER ARCHAIC KOPPA;Lu;0;L;;;;;N;;*;;03D9;
+03D9;GREEK SMALL LETTER ARCHAIC KOPPA;Ll;0;L;;;;;N;;*;03D8;;03D8
+03DA;GREEK LETTER STIGMA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER STIGMA;;;03DB;
+03DB;GREEK SMALL LETTER STIGMA;Ll;0;L;;;;;N;;;03DA;;03DA
+03DC;GREEK LETTER DIGAMMA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER DIGAMMA;;;03DD;
+03DD;GREEK SMALL LETTER DIGAMMA;Ll;0;L;;;;;N;;;03DC;;03DC
+03DE;GREEK LETTER KOPPA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER KOPPA;;;03DF;
+03DF;GREEK SMALL LETTER KOPPA;Ll;0;L;;;;;N;;;03DE;;03DE
+03E0;GREEK LETTER SAMPI;Lu;0;L;;;;;N;GREEK CAPITAL LETTER SAMPI;;;03E1;
+03E1;GREEK SMALL LETTER SAMPI;Ll;0;L;;;;;N;;;03E0;;03E0
+03E2;COPTIC CAPITAL LETTER SHEI;Lu;0;L;;;;;N;GREEK CAPITAL LETTER SHEI;;;03E3;
+03E3;COPTIC SMALL LETTER SHEI;Ll;0;L;;;;;N;GREEK SMALL LETTER SHEI;;03E2;;03E2
+03E4;COPTIC CAPITAL LETTER FEI;Lu;0;L;;;;;N;GREEK CAPITAL LETTER FEI;;;03E5;
+03E5;COPTIC SMALL LETTER FEI;Ll;0;L;;;;;N;GREEK SMALL LETTER FEI;;03E4;;03E4
+03E6;COPTIC CAPITAL LETTER KHEI;Lu;0;L;;;;;N;GREEK CAPITAL LETTER KHEI;;;03E7;
+03E7;COPTIC SMALL LETTER KHEI;Ll;0;L;;;;;N;GREEK SMALL LETTER KHEI;;03E6;;03E6
+03E8;COPTIC CAPITAL LETTER HORI;Lu;0;L;;;;;N;GREEK CAPITAL LETTER HORI;;;03E9;
+03E9;COPTIC SMALL LETTER HORI;Ll;0;L;;;;;N;GREEK SMALL LETTER HORI;;03E8;;03E8
+03EA;COPTIC CAPITAL LETTER GANGIA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER GANGIA;;;03EB;
+03EB;COPTIC SMALL LETTER GANGIA;Ll;0;L;;;;;N;GREEK SMALL LETTER GANGIA;;03EA;;03EA
+03EC;COPTIC CAPITAL LETTER SHIMA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER SHIMA;;;03ED;
+03ED;COPTIC SMALL LETTER SHIMA;Ll;0;L;;;;;N;GREEK SMALL LETTER SHIMA;;03EC;;03EC
+03EE;COPTIC CAPITAL LETTER DEI;Lu;0;L;;;;;N;GREEK CAPITAL LETTER DEI;;;03EF;
+03EF;COPTIC SMALL LETTER DEI;Ll;0;L;;;;;N;GREEK SMALL LETTER DEI;;03EE;;03EE
+03F0;GREEK KAPPA SYMBOL;Ll;0;L;<compat> 03BA;;;;N;GREEK SMALL LETTER SCRIPT KAPPA;;039A;;039A
+03F1;GREEK RHO SYMBOL;Ll;0;L;<compat> 03C1;;;;N;GREEK SMALL LETTER TAILED RHO;;03A1;;03A1
+03F2;GREEK LUNATE SIGMA SYMBOL;Ll;0;L;<compat> 03C2;;;;N;GREEK SMALL LETTER LUNATE SIGMA;;03F9;;03F9
+03F3;GREEK LETTER YOT;Ll;0;L;;;;;N;;;;;
+03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L;<compat> 0398;;;;N;;;;03B8;
+03F5;GREEK LUNATE EPSILON SYMBOL;Ll;0;L;<compat> 03B5;;;;N;;;0395;;0395
+03F6;GREEK REVERSED LUNATE EPSILON SYMBOL;Sm;0;ON;;;;;N;;;;;
+03F7;GREEK CAPITAL LETTER SHO;Lu;0;L;;;;;N;;;;03F8;
+03F8;GREEK SMALL LETTER SHO;Ll;0;L;;;;;N;;;03F7;;03F7
+03F9;GREEK CAPITAL LUNATE SIGMA SYMBOL;Lu;0;L;<compat> 03A3;;;;N;;;;03F2;
+03FA;GREEK CAPITAL LETTER SAN;Lu;0;L;;;;;N;;;;03FB;
+03FB;GREEK SMALL LETTER SAN;Ll;0;L;;;;;N;;;03FA;;03FA
+0400;CYRILLIC CAPITAL LETTER IE WITH GRAVE;Lu;0;L;0415 0300;;;;N;;;;0450;
+0401;CYRILLIC CAPITAL LETTER IO;Lu;0;L;0415 0308;;;;N;;;;0451;
+0402;CYRILLIC CAPITAL LETTER DJE;Lu;0;L;;;;;N;;Serbocroatian;;0452;
+0403;CYRILLIC CAPITAL LETTER GJE;Lu;0;L;0413 0301;;;;N;;;;0453;
+0404;CYRILLIC CAPITAL LETTER UKRAINIAN IE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER E;;;0454;
+0405;CYRILLIC CAPITAL LETTER DZE;Lu;0;L;;;;;N;;;;0455;
+0406;CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER I;;;0456;
+0407;CYRILLIC CAPITAL LETTER YI;Lu;0;L;0406 0308;;;;N;;Ukrainian;;0457;
+0408;CYRILLIC CAPITAL LETTER JE;Lu;0;L;;;;;N;;;;0458;
+0409;CYRILLIC CAPITAL LETTER LJE;Lu;0;L;;;;;N;;;;0459;
+040A;CYRILLIC CAPITAL LETTER NJE;Lu;0;L;;;;;N;;;;045A;
+040B;CYRILLIC CAPITAL LETTER TSHE;Lu;0;L;;;;;N;;Serbocroatian;;045B;
+040C;CYRILLIC CAPITAL LETTER KJE;Lu;0;L;041A 0301;;;;N;;;;045C;
+040D;CYRILLIC CAPITAL LETTER I WITH GRAVE;Lu;0;L;0418 0300;;;;N;;;;045D;
+040E;CYRILLIC CAPITAL LETTER SHORT U;Lu;0;L;0423 0306;;;;N;;Byelorussian;;045E;
+040F;CYRILLIC CAPITAL LETTER DZHE;Lu;0;L;;;;;N;;;;045F;
+0410;CYRILLIC CAPITAL LETTER A;Lu;0;L;;;;;N;;;;0430;
+0411;CYRILLIC CAPITAL LETTER BE;Lu;0;L;;;;;N;;;;0431;
+0412;CYRILLIC CAPITAL LETTER VE;Lu;0;L;;;;;N;;;;0432;
+0413;CYRILLIC CAPITAL LETTER GHE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER GE;;;0433;
+0414;CYRILLIC CAPITAL LETTER DE;Lu;0;L;;;;;N;;;;0434;
+0415;CYRILLIC CAPITAL LETTER IE;Lu;0;L;;;;;N;;;;0435;
+0416;CYRILLIC CAPITAL LETTER ZHE;Lu;0;L;;;;;N;;;;0436;
+0417;CYRILLIC CAPITAL LETTER ZE;Lu;0;L;;;;;N;;;;0437;
+0418;CYRILLIC CAPITAL LETTER I;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER II;;;0438;
+0419;CYRILLIC CAPITAL LETTER SHORT I;Lu;0;L;0418 0306;;;;N;CYRILLIC CAPITAL LETTER SHORT II;;;0439;
+041A;CYRILLIC CAPITAL LETTER KA;Lu;0;L;;;;;N;;;;043A;
+041B;CYRILLIC CAPITAL LETTER EL;Lu;0;L;;;;;N;;;;043B;
+041C;CYRILLIC CAPITAL LETTER EM;Lu;0;L;;;;;N;;;;043C;
+041D;CYRILLIC CAPITAL LETTER EN;Lu;0;L;;;;;N;;;;043D;
+041E;CYRILLIC CAPITAL LETTER O;Lu;0;L;;;;;N;;;;043E;
+041F;CYRILLIC CAPITAL LETTER PE;Lu;0;L;;;;;N;;;;043F;
+0420;CYRILLIC CAPITAL LETTER ER;Lu;0;L;;;;;N;;;;0440;
+0421;CYRILLIC CAPITAL LETTER ES;Lu;0;L;;;;;N;;;;0441;
+0422;CYRILLIC CAPITAL LETTER TE;Lu;0;L;;;;;N;;;;0442;
+0423;CYRILLIC CAPITAL LETTER U;Lu;0;L;;;;;N;;;;0443;
+0424;CYRILLIC CAPITAL LETTER EF;Lu;0;L;;;;;N;;;;0444;
+0425;CYRILLIC CAPITAL LETTER HA;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER KHA;;;0445;
+0426;CYRILLIC CAPITAL LETTER TSE;Lu;0;L;;;;;N;;;;0446;
+0427;CYRILLIC CAPITAL LETTER CHE;Lu;0;L;;;;;N;;;;0447;
+0428;CYRILLIC CAPITAL LETTER SHA;Lu;0;L;;;;;N;;;;0448;
+0429;CYRILLIC CAPITAL LETTER SHCHA;Lu;0;L;;;;;N;;;;0449;
+042A;CYRILLIC CAPITAL LETTER HARD SIGN;Lu;0;L;;;;;N;;;;044A;
+042B;CYRILLIC CAPITAL LETTER YERU;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER YERI;;;044B;
+042C;CYRILLIC CAPITAL LETTER SOFT SIGN;Lu;0;L;;;;;N;;;;044C;
+042D;CYRILLIC CAPITAL LETTER E;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER REVERSED E;;;044D;
+042E;CYRILLIC CAPITAL LETTER YU;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER IU;;;044E;
+042F;CYRILLIC CAPITAL LETTER YA;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER IA;;;044F;
+0430;CYRILLIC SMALL LETTER A;Ll;0;L;;;;;N;;;0410;;0410
+0431;CYRILLIC SMALL LETTER BE;Ll;0;L;;;;;N;;;0411;;0411
+0432;CYRILLIC SMALL LETTER VE;Ll;0;L;;;;;N;;;0412;;0412
+0433;CYRILLIC SMALL LETTER GHE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER GE;;0413;;0413
+0434;CYRILLIC SMALL LETTER DE;Ll;0;L;;;;;N;;;0414;;0414
+0435;CYRILLIC SMALL LETTER IE;Ll;0;L;;;;;N;;;0415;;0415
+0436;CYRILLIC SMALL LETTER ZHE;Ll;0;L;;;;;N;;;0416;;0416
+0437;CYRILLIC SMALL LETTER ZE;Ll;0;L;;;;;N;;;0417;;0417
+0438;CYRILLIC SMALL LETTER I;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER II;;0418;;0418
+0439;CYRILLIC SMALL LETTER SHORT I;Ll;0;L;0438 0306;;;;N;CYRILLIC SMALL LETTER SHORT II;;0419;;0419
+043A;CYRILLIC SMALL LETTER KA;Ll;0;L;;;;;N;;;041A;;041A
+043B;CYRILLIC SMALL LETTER EL;Ll;0;L;;;;;N;;;041B;;041B
+043C;CYRILLIC SMALL LETTER EM;Ll;0;L;;;;;N;;;041C;;041C
+043D;CYRILLIC SMALL LETTER EN;Ll;0;L;;;;;N;;;041D;;041D
+043E;CYRILLIC SMALL LETTER O;Ll;0;L;;;;;N;;;041E;;041E
+043F;CYRILLIC SMALL LETTER PE;Ll;0;L;;;;;N;;;041F;;041F
+0440;CYRILLIC SMALL LETTER ER;Ll;0;L;;;;;N;;;0420;;0420
+0441;CYRILLIC SMALL LETTER ES;Ll;0;L;;;;;N;;;0421;;0421
+0442;CYRILLIC SMALL LETTER TE;Ll;0;L;;;;;N;;;0422;;0422
+0443;CYRILLIC SMALL LETTER U;Ll;0;L;;;;;N;;;0423;;0423
+0444;CYRILLIC SMALL LETTER EF;Ll;0;L;;;;;N;;;0424;;0424
+0445;CYRILLIC SMALL LETTER HA;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER KHA;;0425;;0425
+0446;CYRILLIC SMALL LETTER TSE;Ll;0;L;;;;;N;;;0426;;0426
+0447;CYRILLIC SMALL LETTER CHE;Ll;0;L;;;;;N;;;0427;;0427
+0448;CYRILLIC SMALL LETTER SHA;Ll;0;L;;;;;N;;;0428;;0428
+0449;CYRILLIC SMALL LETTER SHCHA;Ll;0;L;;;;;N;;;0429;;0429
+044A;CYRILLIC SMALL LETTER HARD SIGN;Ll;0;L;;;;;N;;;042A;;042A
+044B;CYRILLIC SMALL LETTER YERU;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER YERI;;042B;;042B
+044C;CYRILLIC SMALL LETTER SOFT SIGN;Ll;0;L;;;;;N;;;042C;;042C
+044D;CYRILLIC SMALL LETTER E;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER REVERSED E;;042D;;042D
+044E;CYRILLIC SMALL LETTER YU;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER IU;;042E;;042E
+044F;CYRILLIC SMALL LETTER YA;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER IA;;042F;;042F
+0450;CYRILLIC SMALL LETTER IE WITH GRAVE;Ll;0;L;0435 0300;;;;N;;;0400;;0400
+0451;CYRILLIC SMALL LETTER IO;Ll;0;L;0435 0308;;;;N;;;0401;;0401
+0452;CYRILLIC SMALL LETTER DJE;Ll;0;L;;;;;N;;Serbocroatian;0402;;0402
+0453;CYRILLIC SMALL LETTER GJE;Ll;0;L;0433 0301;;;;N;;;0403;;0403
+0454;CYRILLIC SMALL LETTER UKRAINIAN IE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER E;;0404;;0404
+0455;CYRILLIC SMALL LETTER DZE;Ll;0;L;;;;;N;;;0405;;0405
+0456;CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER I;;0406;;0406
+0457;CYRILLIC SMALL LETTER YI;Ll;0;L;0456 0308;;;;N;;Ukrainian;0407;;0407
+0458;CYRILLIC SMALL LETTER JE;Ll;0;L;;;;;N;;;0408;;0408
+0459;CYRILLIC SMALL LETTER LJE;Ll;0;L;;;;;N;;;0409;;0409
+045A;CYRILLIC SMALL LETTER NJE;Ll;0;L;;;;;N;;;040A;;040A
+045B;CYRILLIC SMALL LETTER TSHE;Ll;0;L;;;;;N;;Serbocroatian;040B;;040B
+045C;CYRILLIC SMALL LETTER KJE;Ll;0;L;043A 0301;;;;N;;;040C;;040C
+045D;CYRILLIC SMALL LETTER I WITH GRAVE;Ll;0;L;0438 0300;;;;N;;;040D;;040D
+045E;CYRILLIC SMALL LETTER SHORT U;Ll;0;L;0443 0306;;;;N;;Byelorussian;040E;;040E
+045F;CYRILLIC SMALL LETTER DZHE;Ll;0;L;;;;;N;;;040F;;040F
+0460;CYRILLIC CAPITAL LETTER OMEGA;Lu;0;L;;;;;N;;;;0461;
+0461;CYRILLIC SMALL LETTER OMEGA;Ll;0;L;;;;;N;;;0460;;0460
+0462;CYRILLIC CAPITAL LETTER YAT;Lu;0;L;;;;;N;;;;0463;
+0463;CYRILLIC SMALL LETTER YAT;Ll;0;L;;;;;N;;;0462;;0462
+0464;CYRILLIC CAPITAL LETTER IOTIFIED E;Lu;0;L;;;;;N;;;;0465;
+0465;CYRILLIC SMALL LETTER IOTIFIED E;Ll;0;L;;;;;N;;;0464;;0464
+0466;CYRILLIC CAPITAL LETTER LITTLE YUS;Lu;0;L;;;;;N;;;;0467;
+0467;CYRILLIC SMALL LETTER LITTLE YUS;Ll;0;L;;;;;N;;;0466;;0466
+0468;CYRILLIC CAPITAL LETTER IOTIFIED LITTLE YUS;Lu;0;L;;;;;N;;;;0469;
+0469;CYRILLIC SMALL LETTER IOTIFIED LITTLE YUS;Ll;0;L;;;;;N;;;0468;;0468
+046A;CYRILLIC CAPITAL LETTER BIG YUS;Lu;0;L;;;;;N;;;;046B;
+046B;CYRILLIC SMALL LETTER BIG YUS;Ll;0;L;;;;;N;;;046A;;046A
+046C;CYRILLIC CAPITAL LETTER IOTIFIED BIG YUS;Lu;0;L;;;;;N;;;;046D;
+046D;CYRILLIC SMALL LETTER IOTIFIED BIG YUS;Ll;0;L;;;;;N;;;046C;;046C
+046E;CYRILLIC CAPITAL LETTER KSI;Lu;0;L;;;;;N;;;;046F;
+046F;CYRILLIC SMALL LETTER KSI;Ll;0;L;;;;;N;;;046E;;046E
+0470;CYRILLIC CAPITAL LETTER PSI;Lu;0;L;;;;;N;;;;0471;
+0471;CYRILLIC SMALL LETTER PSI;Ll;0;L;;;;;N;;;0470;;0470
+0472;CYRILLIC CAPITAL LETTER FITA;Lu;0;L;;;;;N;;;;0473;
+0473;CYRILLIC SMALL LETTER FITA;Ll;0;L;;;;;N;;;0472;;0472
+0474;CYRILLIC CAPITAL LETTER IZHITSA;Lu;0;L;;;;;N;;;;0475;
+0475;CYRILLIC SMALL LETTER IZHITSA;Ll;0;L;;;;;N;;;0474;;0474
+0476;CYRILLIC CAPITAL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT;Lu;0;L;0474 030F;;;;N;CYRILLIC CAPITAL LETTER IZHITSA DOUBLE GRAVE;;;0477;
+0477;CYRILLIC SMALL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT;Ll;0;L;0475 030F;;;;N;CYRILLIC SMALL LETTER IZHITSA DOUBLE GRAVE;;0476;;0476
+0478;CYRILLIC CAPITAL LETTER UK;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER UK DIGRAPH;;;0479;
+0479;CYRILLIC SMALL LETTER UK;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER UK DIGRAPH;;0478;;0478
+047A;CYRILLIC CAPITAL LETTER ROUND OMEGA;Lu;0;L;;;;;N;;;;047B;
+047B;CYRILLIC SMALL LETTER ROUND OMEGA;Ll;0;L;;;;;N;;;047A;;047A
+047C;CYRILLIC CAPITAL LETTER OMEGA WITH TITLO;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER OMEGA TITLO;;;047D;
+047D;CYRILLIC SMALL LETTER OMEGA WITH TITLO;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER OMEGA TITLO;;047C;;047C
+047E;CYRILLIC CAPITAL LETTER OT;Lu;0;L;;;;;N;;;;047F;
+047F;CYRILLIC SMALL LETTER OT;Ll;0;L;;;;;N;;;047E;;047E
+0480;CYRILLIC CAPITAL LETTER KOPPA;Lu;0;L;;;;;N;;;;0481;
+0481;CYRILLIC SMALL LETTER KOPPA;Ll;0;L;;;;;N;;;0480;;0480
+0482;CYRILLIC THOUSANDS SIGN;So;0;L;;;;;N;;;;;
+0483;COMBINING CYRILLIC TITLO;Mn;230;NSM;;;;;N;CYRILLIC NON-SPACING TITLO;;;;
+0484;COMBINING CYRILLIC PALATALIZATION;Mn;230;NSM;;;;;N;CYRILLIC NON-SPACING PALATALIZATION;;;;
+0485;COMBINING CYRILLIC DASIA PNEUMATA;Mn;230;NSM;;;;;N;CYRILLIC NON-SPACING DASIA PNEUMATA;;;;
+0486;COMBINING CYRILLIC PSILI PNEUMATA;Mn;230;NSM;;;;;N;CYRILLIC NON-SPACING PSILI PNEUMATA;;;;
+0488;COMBINING CYRILLIC HUNDRED THOUSANDS SIGN;Me;0;NSM;;;;;N;;;;;
+0489;COMBINING CYRILLIC MILLIONS SIGN;Me;0;NSM;;;;;N;;;;;
+048A;CYRILLIC CAPITAL LETTER SHORT I WITH TAIL;Lu;0;L;;;;;N;;;;048B;
+048B;CYRILLIC SMALL LETTER SHORT I WITH TAIL;Ll;0;L;;;;;N;;;048A;;048A
+048C;CYRILLIC CAPITAL LETTER SEMISOFT SIGN;Lu;0;L;;;;;N;;;;048D;
+048D;CYRILLIC SMALL LETTER SEMISOFT SIGN;Ll;0;L;;;;;N;;;048C;;048C
+048E;CYRILLIC CAPITAL LETTER ER WITH TICK;Lu;0;L;;;;;N;;;;048F;
+048F;CYRILLIC SMALL LETTER ER WITH TICK;Ll;0;L;;;;;N;;;048E;;048E
+0490;CYRILLIC CAPITAL LETTER GHE WITH UPTURN;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER GE WITH UPTURN;;;0491;
+0491;CYRILLIC SMALL LETTER GHE WITH UPTURN;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER GE WITH UPTURN;;0490;;0490
+0492;CYRILLIC CAPITAL LETTER GHE WITH STROKE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER GE BAR;;;0493;
+0493;CYRILLIC SMALL LETTER GHE WITH STROKE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER GE BAR;;0492;;0492
+0494;CYRILLIC CAPITAL LETTER GHE WITH MIDDLE HOOK;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER GE HOOK;;;0495;
+0495;CYRILLIC SMALL LETTER GHE WITH MIDDLE HOOK;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER GE HOOK;;0494;;0494
+0496;CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER ZHE WITH RIGHT DESCENDER;;;0497;
+0497;CYRILLIC SMALL LETTER ZHE WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER ZHE WITH RIGHT DESCENDER;;0496;;0496
+0498;CYRILLIC CAPITAL LETTER ZE WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER ZE CEDILLA;;;0499;
+0499;CYRILLIC SMALL LETTER ZE WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER ZE CEDILLA;;0498;;0498
+049A;CYRILLIC CAPITAL LETTER KA WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER KA WITH RIGHT DESCENDER;;;049B;
+049B;CYRILLIC SMALL LETTER KA WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER KA WITH RIGHT DESCENDER;;049A;;049A
+049C;CYRILLIC CAPITAL LETTER KA WITH VERTICAL STROKE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER KA VERTICAL BAR;;;049D;
+049D;CYRILLIC SMALL LETTER KA WITH VERTICAL STROKE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER KA VERTICAL BAR;;049C;;049C
+049E;CYRILLIC CAPITAL LETTER KA WITH STROKE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER KA BAR;;;049F;
+049F;CYRILLIC SMALL LETTER KA WITH STROKE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER KA BAR;;049E;;049E
+04A0;CYRILLIC CAPITAL LETTER BASHKIR KA;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER REVERSED GE KA;;;04A1;
+04A1;CYRILLIC SMALL LETTER BASHKIR KA;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER REVERSED GE KA;;04A0;;04A0
+04A2;CYRILLIC CAPITAL LETTER EN WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER EN WITH RIGHT DESCENDER;;;04A3;
+04A3;CYRILLIC SMALL LETTER EN WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER EN WITH RIGHT DESCENDER;;04A2;;04A2
+04A4;CYRILLIC CAPITAL LIGATURE EN GHE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER EN GE;;;04A5;
+04A5;CYRILLIC SMALL LIGATURE EN GHE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER EN GE;;04A4;;04A4
+04A6;CYRILLIC CAPITAL LETTER PE WITH MIDDLE HOOK;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER PE HOOK;Abkhasian;;04A7;
+04A7;CYRILLIC SMALL LETTER PE WITH MIDDLE HOOK;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER PE HOOK;Abkhasian;04A6;;04A6
+04A8;CYRILLIC CAPITAL LETTER ABKHASIAN HA;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER O HOOK;;;04A9;
+04A9;CYRILLIC SMALL LETTER ABKHASIAN HA;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER O HOOK;;04A8;;04A8
+04AA;CYRILLIC CAPITAL LETTER ES WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER ES CEDILLA;;;04AB;
+04AB;CYRILLIC SMALL LETTER ES WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER ES CEDILLA;;04AA;;04AA
+04AC;CYRILLIC CAPITAL LETTER TE WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER TE WITH RIGHT DESCENDER;;;04AD;
+04AD;CYRILLIC SMALL LETTER TE WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER TE WITH RIGHT DESCENDER;;04AC;;04AC
+04AE;CYRILLIC CAPITAL LETTER STRAIGHT U;Lu;0;L;;;;;N;;;;04AF;
+04AF;CYRILLIC SMALL LETTER STRAIGHT U;Ll;0;L;;;;;N;;;04AE;;04AE
+04B0;CYRILLIC CAPITAL LETTER STRAIGHT U WITH STROKE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER STRAIGHT U BAR;;;04B1;
+04B1;CYRILLIC SMALL LETTER STRAIGHT U WITH STROKE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER STRAIGHT U BAR;;04B0;;04B0
+04B2;CYRILLIC CAPITAL LETTER HA WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER KHA WITH RIGHT DESCENDER;;;04B3;
+04B3;CYRILLIC SMALL LETTER HA WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER KHA WITH RIGHT DESCENDER;;04B2;;04B2
+04B4;CYRILLIC CAPITAL LIGATURE TE TSE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER TE TSE;Abkhasian;;04B5;
+04B5;CYRILLIC SMALL LIGATURE TE TSE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER TE TSE;Abkhasian;04B4;;04B4
+04B6;CYRILLIC CAPITAL LETTER CHE WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER CHE WITH RIGHT DESCENDER;;;04B7;
+04B7;CYRILLIC SMALL LETTER CHE WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER CHE WITH RIGHT DESCENDER;;04B6;;04B6
+04B8;CYRILLIC CAPITAL LETTER CHE WITH VERTICAL STROKE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER CHE VERTICAL BAR;;;04B9;
+04B9;CYRILLIC SMALL LETTER CHE WITH VERTICAL STROKE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER CHE VERTICAL BAR;;04B8;;04B8
+04BA;CYRILLIC CAPITAL LETTER SHHA;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER H;;;04BB;
+04BB;CYRILLIC SMALL LETTER SHHA;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER H;;04BA;;04BA
+04BC;CYRILLIC CAPITAL LETTER ABKHASIAN CHE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER IE HOOK;;;04BD;
+04BD;CYRILLIC SMALL LETTER ABKHASIAN CHE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER IE HOOK;;04BC;;04BC
+04BE;CYRILLIC CAPITAL LETTER ABKHASIAN CHE WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER IE HOOK OGONEK;;;04BF;
+04BF;CYRILLIC SMALL LETTER ABKHASIAN CHE WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER IE HOOK OGONEK;;04BE;;04BE
+04C0;CYRILLIC LETTER PALOCHKA;Lu;0;L;;;;;N;CYRILLIC LETTER I;;;;
+04C1;CYRILLIC CAPITAL LETTER ZHE WITH BREVE;Lu;0;L;0416 0306;;;;N;CYRILLIC CAPITAL LETTER SHORT ZHE;;;04C2;
+04C2;CYRILLIC SMALL LETTER ZHE WITH BREVE;Ll;0;L;0436 0306;;;;N;CYRILLIC SMALL LETTER SHORT ZHE;;04C1;;04C1
+04C3;CYRILLIC CAPITAL LETTER KA WITH HOOK;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER KA HOOK;;;04C4;
+04C4;CYRILLIC SMALL LETTER KA WITH HOOK;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER KA HOOK;;04C3;;04C3
+04C5;CYRILLIC CAPITAL LETTER EL WITH TAIL;Lu;0;L;;;;;N;;;;04C6;
+04C6;CYRILLIC SMALL LETTER EL WITH TAIL;Ll;0;L;;;;;N;;;04C5;;04C5
+04C7;CYRILLIC CAPITAL LETTER EN WITH HOOK;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER EN HOOK;;;04C8;
+04C8;CYRILLIC SMALL LETTER EN WITH HOOK;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER EN HOOK;;04C7;;04C7
+04C9;CYRILLIC CAPITAL LETTER EN WITH TAIL;Lu;0;L;;;;;N;;;;04CA;
+04CA;CYRILLIC SMALL LETTER EN WITH TAIL;Ll;0;L;;;;;N;;;04C9;;04C9
+04CB;CYRILLIC CAPITAL LETTER KHAKASSIAN CHE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER CHE WITH LEFT DESCENDER;;;04CC;
+04CC;CYRILLIC SMALL LETTER KHAKASSIAN CHE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER CHE WITH LEFT DESCENDER;;04CB;;04CB
+04CD;CYRILLIC CAPITAL LETTER EM WITH TAIL;Lu;0;L;;;;;N;;;;04CE;
+04CE;CYRILLIC SMALL LETTER EM WITH TAIL;Ll;0;L;;;;;N;;;04CD;;04CD
+04D0;CYRILLIC CAPITAL LETTER A WITH BREVE;Lu;0;L;0410 0306;;;;N;;;;04D1;
+04D1;CYRILLIC SMALL LETTER A WITH BREVE;Ll;0;L;0430 0306;;;;N;;;04D0;;04D0
+04D2;CYRILLIC CAPITAL LETTER A WITH DIAERESIS;Lu;0;L;0410 0308;;;;N;;;;04D3;
+04D3;CYRILLIC SMALL LETTER A WITH DIAERESIS;Ll;0;L;0430 0308;;;;N;;;04D2;;04D2
+04D4;CYRILLIC CAPITAL LIGATURE A IE;Lu;0;L;;;;;N;;;;04D5;
+04D5;CYRILLIC SMALL LIGATURE A IE;Ll;0;L;;;;;N;;;04D4;;04D4
+04D6;CYRILLIC CAPITAL LETTER IE WITH BREVE;Lu;0;L;0415 0306;;;;N;;;;04D7;
+04D7;CYRILLIC SMALL LETTER IE WITH BREVE;Ll;0;L;0435 0306;;;;N;;;04D6;;04D6
+04D8;CYRILLIC CAPITAL LETTER SCHWA;Lu;0;L;;;;;N;;;;04D9;
+04D9;CYRILLIC SMALL LETTER SCHWA;Ll;0;L;;;;;N;;;04D8;;04D8
+04DA;CYRILLIC CAPITAL LETTER SCHWA WITH DIAERESIS;Lu;0;L;04D8 0308;;;;N;;;;04DB;
+04DB;CYRILLIC SMALL LETTER SCHWA WITH DIAERESIS;Ll;0;L;04D9 0308;;;;N;;;04DA;;04DA
+04DC;CYRILLIC CAPITAL LETTER ZHE WITH DIAERESIS;Lu;0;L;0416 0308;;;;N;;;;04DD;
+04DD;CYRILLIC SMALL LETTER ZHE WITH DIAERESIS;Ll;0;L;0436 0308;;;;N;;;04DC;;04DC
+04DE;CYRILLIC CAPITAL LETTER ZE WITH DIAERESIS;Lu;0;L;0417 0308;;;;N;;;;04DF;
+04DF;CYRILLIC SMALL LETTER ZE WITH DIAERESIS;Ll;0;L;0437 0308;;;;N;;;04DE;;04DE
+04E0;CYRILLIC CAPITAL LETTER ABKHASIAN DZE;Lu;0;L;;;;;N;;;;04E1;
+04E1;CYRILLIC SMALL LETTER ABKHASIAN DZE;Ll;0;L;;;;;N;;;04E0;;04E0
+04E2;CYRILLIC CAPITAL LETTER I WITH MACRON;Lu;0;L;0418 0304;;;;N;;;;04E3;
+04E3;CYRILLIC SMALL LETTER I WITH MACRON;Ll;0;L;0438 0304;;;;N;;;04E2;;04E2
+04E4;CYRILLIC CAPITAL LETTER I WITH DIAERESIS;Lu;0;L;0418 0308;;;;N;;;;04E5;
+04E5;CYRILLIC SMALL LETTER I WITH DIAERESIS;Ll;0;L;0438 0308;;;;N;;;04E4;;04E4
+04E6;CYRILLIC CAPITAL LETTER O WITH DIAERESIS;Lu;0;L;041E 0308;;;;N;;;;04E7;
+04E7;CYRILLIC SMALL LETTER O WITH DIAERESIS;Ll;0;L;043E 0308;;;;N;;;04E6;;04E6
+04E8;CYRILLIC CAPITAL LETTER BARRED O;Lu;0;L;;;;;N;;;;04E9;
+04E9;CYRILLIC SMALL LETTER BARRED O;Ll;0;L;;;;;N;;;04E8;;04E8
+04EA;CYRILLIC CAPITAL LETTER BARRED O WITH DIAERESIS;Lu;0;L;04E8 0308;;;;N;;;;04EB;
+04EB;CYRILLIC SMALL LETTER BARRED O WITH DIAERESIS;Ll;0;L;04E9 0308;;;;N;;;04EA;;04EA
+04EC;CYRILLIC CAPITAL LETTER E WITH DIAERESIS;Lu;0;L;042D 0308;;;;N;;;;04ED;
+04ED;CYRILLIC SMALL LETTER E WITH DIAERESIS;Ll;0;L;044D 0308;;;;N;;;04EC;;04EC
+04EE;CYRILLIC CAPITAL LETTER U WITH MACRON;Lu;0;L;0423 0304;;;;N;;;;04EF;
+04EF;CYRILLIC SMALL LETTER U WITH MACRON;Ll;0;L;0443 0304;;;;N;;;04EE;;04EE
+04F0;CYRILLIC CAPITAL LETTER U WITH DIAERESIS;Lu;0;L;0423 0308;;;;N;;;;04F1;
+04F1;CYRILLIC SMALL LETTER U WITH DIAERESIS;Ll;0;L;0443 0308;;;;N;;;04F0;;04F0
+04F2;CYRILLIC CAPITAL LETTER U WITH DOUBLE ACUTE;Lu;0;L;0423 030B;;;;N;;;;04F3;
+04F3;CYRILLIC SMALL LETTER U WITH DOUBLE ACUTE;Ll;0;L;0443 030B;;;;N;;;04F2;;04F2
+04F4;CYRILLIC CAPITAL LETTER CHE WITH DIAERESIS;Lu;0;L;0427 0308;;;;N;;;;04F5;
+04F5;CYRILLIC SMALL LETTER CHE WITH DIAERESIS;Ll;0;L;0447 0308;;;;N;;;04F4;;04F4
+04F8;CYRILLIC CAPITAL LETTER YERU WITH DIAERESIS;Lu;0;L;042B 0308;;;;N;;;;04F9;
+04F9;CYRILLIC SMALL LETTER YERU WITH DIAERESIS;Ll;0;L;044B 0308;;;;N;;;04F8;;04F8
+0500;CYRILLIC CAPITAL LETTER KOMI DE;Lu;0;L;;;;;N;;;;0501;
+0501;CYRILLIC SMALL LETTER KOMI DE;Ll;0;L;;;;;N;;;0500;;0500
+0502;CYRILLIC CAPITAL LETTER KOMI DJE;Lu;0;L;;;;;N;;;;0503;
+0503;CYRILLIC SMALL LETTER KOMI DJE;Ll;0;L;;;;;N;;;0502;;0502
+0504;CYRILLIC CAPITAL LETTER KOMI ZJE;Lu;0;L;;;;;N;;;;0505;
+0505;CYRILLIC SMALL LETTER KOMI ZJE;Ll;0;L;;;;;N;;;0504;;0504
+0506;CYRILLIC CAPITAL LETTER KOMI DZJE;Lu;0;L;;;;;N;;;;0507;
+0507;CYRILLIC SMALL LETTER KOMI DZJE;Ll;0;L;;;;;N;;;0506;;0506
+0508;CYRILLIC CAPITAL LETTER KOMI LJE;Lu;0;L;;;;;N;;;;0509;
+0509;CYRILLIC SMALL LETTER KOMI LJE;Ll;0;L;;;;;N;;;0508;;0508
+050A;CYRILLIC CAPITAL LETTER KOMI NJE;Lu;0;L;;;;;N;;;;050B;
+050B;CYRILLIC SMALL LETTER KOMI NJE;Ll;0;L;;;;;N;;;050A;;050A
+050C;CYRILLIC CAPITAL LETTER KOMI SJE;Lu;0;L;;;;;N;;;;050D;
+050D;CYRILLIC SMALL LETTER KOMI SJE;Ll;0;L;;;;;N;;;050C;;050C
+050E;CYRILLIC CAPITAL LETTER KOMI TJE;Lu;0;L;;;;;N;;;;050F;
+050F;CYRILLIC SMALL LETTER KOMI TJE;Ll;0;L;;;;;N;;;050E;;050E
+0531;ARMENIAN CAPITAL LETTER AYB;Lu;0;L;;;;;N;;;;0561;
+0532;ARMENIAN CAPITAL LETTER BEN;Lu;0;L;;;;;N;;;;0562;
+0533;ARMENIAN CAPITAL LETTER GIM;Lu;0;L;;;;;N;;;;0563;
+0534;ARMENIAN CAPITAL LETTER DA;Lu;0;L;;;;;N;;;;0564;
+0535;ARMENIAN CAPITAL LETTER ECH;Lu;0;L;;;;;N;;;;0565;
+0536;ARMENIAN CAPITAL LETTER ZA;Lu;0;L;;;;;N;;;;0566;
+0537;ARMENIAN CAPITAL LETTER EH;Lu;0;L;;;;;N;;;;0567;
+0538;ARMENIAN CAPITAL LETTER ET;Lu;0;L;;;;;N;;;;0568;
+0539;ARMENIAN CAPITAL LETTER TO;Lu;0;L;;;;;N;;;;0569;
+053A;ARMENIAN CAPITAL LETTER ZHE;Lu;0;L;;;;;N;;;;056A;
+053B;ARMENIAN CAPITAL LETTER INI;Lu;0;L;;;;;N;;;;056B;
+053C;ARMENIAN CAPITAL LETTER LIWN;Lu;0;L;;;;;N;;;;056C;
+053D;ARMENIAN CAPITAL LETTER XEH;Lu;0;L;;;;;N;;;;056D;
+053E;ARMENIAN CAPITAL LETTER CA;Lu;0;L;;;;;N;;;;056E;
+053F;ARMENIAN CAPITAL LETTER KEN;Lu;0;L;;;;;N;;;;056F;
+0540;ARMENIAN CAPITAL LETTER HO;Lu;0;L;;;;;N;;;;0570;
+0541;ARMENIAN CAPITAL LETTER JA;Lu;0;L;;;;;N;;;;0571;
+0542;ARMENIAN CAPITAL LETTER GHAD;Lu;0;L;;;;;N;ARMENIAN CAPITAL LETTER LAD;;;0572;
+0543;ARMENIAN CAPITAL LETTER CHEH;Lu;0;L;;;;;N;;;;0573;
+0544;ARMENIAN CAPITAL LETTER MEN;Lu;0;L;;;;;N;;;;0574;
+0545;ARMENIAN CAPITAL LETTER YI;Lu;0;L;;;;;N;;;;0575;
+0546;ARMENIAN CAPITAL LETTER NOW;Lu;0;L;;;;;N;;;;0576;
+0547;ARMENIAN CAPITAL LETTER SHA;Lu;0;L;;;;;N;;;;0577;
+0548;ARMENIAN CAPITAL LETTER VO;Lu;0;L;;;;;N;;;;0578;
+0549;ARMENIAN CAPITAL LETTER CHA;Lu;0;L;;;;;N;;;;0579;
+054A;ARMENIAN CAPITAL LETTER PEH;Lu;0;L;;;;;N;;;;057A;
+054B;ARMENIAN CAPITAL LETTER JHEH;Lu;0;L;;;;;N;;;;057B;
+054C;ARMENIAN CAPITAL LETTER RA;Lu;0;L;;;;;N;;;;057C;
+054D;ARMENIAN CAPITAL LETTER SEH;Lu;0;L;;;;;N;;;;057D;
+054E;ARMENIAN CAPITAL LETTER VEW;Lu;0;L;;;;;N;;;;057E;
+054F;ARMENIAN CAPITAL LETTER TIWN;Lu;0;L;;;;;N;;;;057F;
+0550;ARMENIAN CAPITAL LETTER REH;Lu;0;L;;;;;N;;;;0580;
+0551;ARMENIAN CAPITAL LETTER CO;Lu;0;L;;;;;N;;;;0581;
+0552;ARMENIAN CAPITAL LETTER YIWN;Lu;0;L;;;;;N;;;;0582;
+0553;ARMENIAN CAPITAL LETTER PIWR;Lu;0;L;;;;;N;;;;0583;
+0554;ARMENIAN CAPITAL LETTER KEH;Lu;0;L;;;;;N;;;;0584;
+0555;ARMENIAN CAPITAL LETTER OH;Lu;0;L;;;;;N;;;;0585;
+0556;ARMENIAN CAPITAL LETTER FEH;Lu;0;L;;;;;N;;;;0586;
+0559;ARMENIAN MODIFIER LETTER LEFT HALF RING;Lm;0;L;;;;;N;;;;;
+055A;ARMENIAN APOSTROPHE;Po;0;L;;;;;N;ARMENIAN MODIFIER LETTER RIGHT HALF RING;;;;
+055B;ARMENIAN EMPHASIS MARK;Po;0;L;;;;;N;;;;;
+055C;ARMENIAN EXCLAMATION MARK;Po;0;L;;;;;N;;;;;
+055D;ARMENIAN COMMA;Po;0;L;;;;;N;;;;;
+055E;ARMENIAN QUESTION MARK;Po;0;L;;;;;N;;;;;
+055F;ARMENIAN ABBREVIATION MARK;Po;0;L;;;;;N;;;;;
+0561;ARMENIAN SMALL LETTER AYB;Ll;0;L;;;;;N;;;0531;;0531
+0562;ARMENIAN SMALL LETTER BEN;Ll;0;L;;;;;N;;;0532;;0532
+0563;ARMENIAN SMALL LETTER GIM;Ll;0;L;;;;;N;;;0533;;0533
+0564;ARMENIAN SMALL LETTER DA;Ll;0;L;;;;;N;;;0534;;0534
+0565;ARMENIAN SMALL LETTER ECH;Ll;0;L;;;;;N;;;0535;;0535
+0566;ARMENIAN SMALL LETTER ZA;Ll;0;L;;;;;N;;;0536;;0536
+0567;ARMENIAN SMALL LETTER EH;Ll;0;L;;;;;N;;;0537;;0537
+0568;ARMENIAN SMALL LETTER ET;Ll;0;L;;;;;N;;;0538;;0538
+0569;ARMENIAN SMALL LETTER TO;Ll;0;L;;;;;N;;;0539;;0539
+056A;ARMENIAN SMALL LETTER ZHE;Ll;0;L;;;;;N;;;053A;;053A
+056B;ARMENIAN SMALL LETTER INI;Ll;0;L;;;;;N;;;053B;;053B
+056C;ARMENIAN SMALL LETTER LIWN;Ll;0;L;;;;;N;;;053C;;053C
+056D;ARMENIAN SMALL LETTER XEH;Ll;0;L;;;;;N;;;053D;;053D
+056E;ARMENIAN SMALL LETTER CA;Ll;0;L;;;;;N;;;053E;;053E
+056F;ARMENIAN SMALL LETTER KEN;Ll;0;L;;;;;N;;;053F;;053F
+0570;ARMENIAN SMALL LETTER HO;Ll;0;L;;;;;N;;;0540;;0540
+0571;ARMENIAN SMALL LETTER JA;Ll;0;L;;;;;N;;;0541;;0541
+0572;ARMENIAN SMALL LETTER GHAD;Ll;0;L;;;;;N;ARMENIAN SMALL LETTER LAD;;0542;;0542
+0573;ARMENIAN SMALL LETTER CHEH;Ll;0;L;;;;;N;;;0543;;0543
+0574;ARMENIAN SMALL LETTER MEN;Ll;0;L;;;;;N;;;0544;;0544
+0575;ARMENIAN SMALL LETTER YI;Ll;0;L;;;;;N;;;0545;;0545
+0576;ARMENIAN SMALL LETTER NOW;Ll;0;L;;;;;N;;;0546;;0546
+0577;ARMENIAN SMALL LETTER SHA;Ll;0;L;;;;;N;;;0547;;0547
+0578;ARMENIAN SMALL LETTER VO;Ll;0;L;;;;;N;;;0548;;0548
+0579;ARMENIAN SMALL LETTER CHA;Ll;0;L;;;;;N;;;0549;;0549
+057A;ARMENIAN SMALL LETTER PEH;Ll;0;L;;;;;N;;;054A;;054A
+057B;ARMENIAN SMALL LETTER JHEH;Ll;0;L;;;;;N;;;054B;;054B
+057C;ARMENIAN SMALL LETTER RA;Ll;0;L;;;;;N;;;054C;;054C
+057D;ARMENIAN SMALL LETTER SEH;Ll;0;L;;;;;N;;;054D;;054D
+057E;ARMENIAN SMALL LETTER VEW;Ll;0;L;;;;;N;;;054E;;054E
+057F;ARMENIAN SMALL LETTER TIWN;Ll;0;L;;;;;N;;;054F;;054F
+0580;ARMENIAN SMALL LETTER REH;Ll;0;L;;;;;N;;;0550;;0550
+0581;ARMENIAN SMALL LETTER CO;Ll;0;L;;;;;N;;;0551;;0551
+0582;ARMENIAN SMALL LETTER YIWN;Ll;0;L;;;;;N;;;0552;;0552
+0583;ARMENIAN SMALL LETTER PIWR;Ll;0;L;;;;;N;;;0553;;0553
+0584;ARMENIAN SMALL LETTER KEH;Ll;0;L;;;;;N;;;0554;;0554
+0585;ARMENIAN SMALL LETTER OH;Ll;0;L;;;;;N;;;0555;;0555
+0586;ARMENIAN SMALL LETTER FEH;Ll;0;L;;;;;N;;;0556;;0556
+0587;ARMENIAN SMALL LIGATURE ECH YIWN;Ll;0;L;<compat> 0565 0582;;;;N;;;;;
+0589;ARMENIAN FULL STOP;Po;0;L;;;;;N;ARMENIAN PERIOD;;;;
+058A;ARMENIAN HYPHEN;Pd;0;ON;;;;;N;;;;;
+0591;HEBREW ACCENT ETNAHTA;Mn;220;NSM;;;;;N;;;;;
+0592;HEBREW ACCENT SEGOL;Mn;230;NSM;;;;;N;;;;;
+0593;HEBREW ACCENT SHALSHELET;Mn;230;NSM;;;;;N;;;;;
+0594;HEBREW ACCENT ZAQEF QATAN;Mn;230;NSM;;;;;N;;;;;
+0595;HEBREW ACCENT ZAQEF GADOL;Mn;230;NSM;;;;;N;;;;;
+0596;HEBREW ACCENT TIPEHA;Mn;220;NSM;;;;;N;;*;;;
+0597;HEBREW ACCENT REVIA;Mn;230;NSM;;;;;N;;;;;
+0598;HEBREW ACCENT ZARQA;Mn;230;NSM;;;;;N;;*;;;
+0599;HEBREW ACCENT PASHTA;Mn;230;NSM;;;;;N;;;;;
+059A;HEBREW ACCENT YETIV;Mn;222;NSM;;;;;N;;;;;
+059B;HEBREW ACCENT TEVIR;Mn;220;NSM;;;;;N;;;;;
+059C;HEBREW ACCENT GERESH;Mn;230;NSM;;;;;N;;;;;
+059D;HEBREW ACCENT GERESH MUQDAM;Mn;230;NSM;;;;;N;;;;;
+059E;HEBREW ACCENT GERSHAYIM;Mn;230;NSM;;;;;N;;;;;
+059F;HEBREW ACCENT QARNEY PARA;Mn;230;NSM;;;;;N;;;;;
+05A0;HEBREW ACCENT TELISHA GEDOLA;Mn;230;NSM;;;;;N;;;;;
+05A1;HEBREW ACCENT PAZER;Mn;230;NSM;;;;;N;;;;;
+05A3;HEBREW ACCENT MUNAH;Mn;220;NSM;;;;;N;;;;;
+05A4;HEBREW ACCENT MAHAPAKH;Mn;220;NSM;;;;;N;;;;;
+05A5;HEBREW ACCENT MERKHA;Mn;220;NSM;;;;;N;;*;;;
+05A6;HEBREW ACCENT MERKHA KEFULA;Mn;220;NSM;;;;;N;;;;;
+05A7;HEBREW ACCENT DARGA;Mn;220;NSM;;;;;N;;;;;
+05A8;HEBREW ACCENT QADMA;Mn;230;NSM;;;;;N;;*;;;
+05A9;HEBREW ACCENT TELISHA QETANA;Mn;230;NSM;;;;;N;;;;;
+05AA;HEBREW ACCENT YERAH BEN YOMO;Mn;220;NSM;;;;;N;;*;;;
+05AB;HEBREW ACCENT OLE;Mn;230;NSM;;;;;N;;;;;
+05AC;HEBREW ACCENT ILUY;Mn;230;NSM;;;;;N;;;;;
+05AD;HEBREW ACCENT DEHI;Mn;222;NSM;;;;;N;;;;;
+05AE;HEBREW ACCENT ZINOR;Mn;228;NSM;;;;;N;;;;;
+05AF;HEBREW MARK MASORA CIRCLE;Mn;230;NSM;;;;;N;;;;;
+05B0;HEBREW POINT SHEVA;Mn;10;NSM;;;;;N;;;;;
+05B1;HEBREW POINT HATAF SEGOL;Mn;11;NSM;;;;;N;;;;;
+05B2;HEBREW POINT HATAF PATAH;Mn;12;NSM;;;;;N;;;;;
+05B3;HEBREW POINT HATAF QAMATS;Mn;13;NSM;;;;;N;;;;;
+05B4;HEBREW POINT HIRIQ;Mn;14;NSM;;;;;N;;;;;
+05B5;HEBREW POINT TSERE;Mn;15;NSM;;;;;N;;;;;
+05B6;HEBREW POINT SEGOL;Mn;16;NSM;;;;;N;;;;;
+05B7;HEBREW POINT PATAH;Mn;17;NSM;;;;;N;;;;;
+05B8;HEBREW POINT QAMATS;Mn;18;NSM;;;;;N;;;;;
+05B9;HEBREW POINT HOLAM;Mn;19;NSM;;;;;N;;;;;
+05BB;HEBREW POINT QUBUTS;Mn;20;NSM;;;;;N;;;;;
+05BC;HEBREW POINT DAGESH OR MAPIQ;Mn;21;NSM;;;;;N;HEBREW POINT DAGESH;or shuruq;;;
+05BD;HEBREW POINT METEG;Mn;22;NSM;;;;;N;;*;;;
+05BE;HEBREW PUNCTUATION MAQAF;Po;0;R;;;;;N;;;;;
+05BF;HEBREW POINT RAFE;Mn;23;NSM;;;;;N;;;;;
+05C0;HEBREW PUNCTUATION PASEQ;Po;0;R;;;;;N;HEBREW POINT PASEQ;*;;;
+05C1;HEBREW POINT SHIN DOT;Mn;24;NSM;;;;;N;;;;;
+05C2;HEBREW POINT SIN DOT;Mn;25;NSM;;;;;N;;;;;
+05C3;HEBREW PUNCTUATION SOF PASUQ;Po;0;R;;;;;N;;*;;;
+05C4;HEBREW MARK UPPER DOT;Mn;230;NSM;;;;;N;;;;;
+05D0;HEBREW LETTER ALEF;Lo;0;R;;;;;N;;;;;
+05D1;HEBREW LETTER BET;Lo;0;R;;;;;N;;;;;
+05D2;HEBREW LETTER GIMEL;Lo;0;R;;;;;N;;;;;
+05D3;HEBREW LETTER DALET;Lo;0;R;;;;;N;;;;;
+05D4;HEBREW LETTER HE;Lo;0;R;;;;;N;;;;;
+05D5;HEBREW LETTER VAV;Lo;0;R;;;;;N;;;;;
+05D6;HEBREW LETTER ZAYIN;Lo;0;R;;;;;N;;;;;
+05D7;HEBREW LETTER HET;Lo;0;R;;;;;N;;;;;
+05D8;HEBREW LETTER TET;Lo;0;R;;;;;N;;;;;
+05D9;HEBREW LETTER YOD;Lo;0;R;;;;;N;;;;;
+05DA;HEBREW LETTER FINAL KAF;Lo;0;R;;;;;N;;;;;
+05DB;HEBREW LETTER KAF;Lo;0;R;;;;;N;;;;;
+05DC;HEBREW LETTER LAMED;Lo;0;R;;;;;N;;;;;
+05DD;HEBREW LETTER FINAL MEM;Lo;0;R;;;;;N;;;;;
+05DE;HEBREW LETTER MEM;Lo;0;R;;;;;N;;;;;
+05DF;HEBREW LETTER FINAL NUN;Lo;0;R;;;;;N;;;;;
+05E0;HEBREW LETTER NUN;Lo;0;R;;;;;N;;;;;
+05E1;HEBREW LETTER SAMEKH;Lo;0;R;;;;;N;;;;;
+05E2;HEBREW LETTER AYIN;Lo;0;R;;;;;N;;;;;
+05E3;HEBREW LETTER FINAL PE;Lo;0;R;;;;;N;;;;;
+05E4;HEBREW LETTER PE;Lo;0;R;;;;;N;;;;;
+05E5;HEBREW LETTER FINAL TSADI;Lo;0;R;;;;;N;;;;;
+05E6;HEBREW LETTER TSADI;Lo;0;R;;;;;N;;;;;
+05E7;HEBREW LETTER QOF;Lo;0;R;;;;;N;;;;;
+05E8;HEBREW LETTER RESH;Lo;0;R;;;;;N;;;;;
+05E9;HEBREW LETTER SHIN;Lo;0;R;;;;;N;;;;;
+05EA;HEBREW LETTER TAV;Lo;0;R;;;;;N;;;;;
+05F0;HEBREW LIGATURE YIDDISH DOUBLE VAV;Lo;0;R;;;;;N;HEBREW LETTER DOUBLE VAV;;;;
+05F1;HEBREW LIGATURE YIDDISH VAV YOD;Lo;0;R;;;;;N;HEBREW LETTER VAV YOD;;;;
+05F2;HEBREW LIGATURE YIDDISH DOUBLE YOD;Lo;0;R;;;;;N;HEBREW LETTER DOUBLE YOD;;;;
+05F3;HEBREW PUNCTUATION GERESH;Po;0;R;;;;;N;;;;;
+05F4;HEBREW PUNCTUATION GERSHAYIM;Po;0;R;;;;;N;;;;;
+0600;ARABIC NUMBER SIGN;Cf;0;AL;;;;;N;;;;;
+0601;ARABIC SIGN SANAH;Cf;0;AL;;;;;N;;;;;
+0602;ARABIC FOOTNOTE MARKER;Cf;0;AL;;;;;N;;;;;
+0603;ARABIC SIGN SAFHA;Cf;0;AL;;;;;N;;;;;
+060C;ARABIC COMMA;Po;0;CS;;;;;N;;;;;
+060D;ARABIC DATE SEPARATOR;Po;0;AL;;;;;N;;;;;
+060E;ARABIC POETIC VERSE SIGN;So;0;ON;;;;;N;;;;;
+060F;ARABIC SIGN MISRA;So;0;ON;;;;;N;;;;;
+0610;ARABIC SIGN SALLALLAHOU ALAYHE WASSALLAM;Mn;230;NSM;;;;;N;;;;;
+0611;ARABIC SIGN ALAYHE ASSALLAM;Mn;230;NSM;;;;;N;;;;;
+0612;ARABIC SIGN RAHMATULLAH ALAYHE;Mn;230;NSM;;;;;N;;;;;
+0613;ARABIC SIGN RADI ALLAHOU ANHU;Mn;230;NSM;;;;;N;;;;;
+0614;ARABIC SIGN TAKHALLUS;Mn;230;NSM;;;;;N;;;;;
+0615;ARABIC SMALL HIGH TAH;Mn;230;NSM;;;;;N;;;;;
+061B;ARABIC SEMICOLON;Po;0;AL;;;;;N;;;;;
+061F;ARABIC QUESTION MARK;Po;0;AL;;;;;N;;;;;
+0621;ARABIC LETTER HAMZA;Lo;0;AL;;;;;N;ARABIC LETTER HAMZAH;;;;
+0622;ARABIC LETTER ALEF WITH MADDA ABOVE;Lo;0;AL;0627 0653;;;;N;ARABIC LETTER MADDAH ON ALEF;;;;
+0623;ARABIC LETTER ALEF WITH HAMZA ABOVE;Lo;0;AL;0627 0654;;;;N;ARABIC LETTER HAMZAH ON ALEF;;;;
+0624;ARABIC LETTER WAW WITH HAMZA ABOVE;Lo;0;AL;0648 0654;;;;N;ARABIC LETTER HAMZAH ON WAW;;;;
+0625;ARABIC LETTER ALEF WITH HAMZA BELOW;Lo;0;AL;0627 0655;;;;N;ARABIC LETTER HAMZAH UNDER ALEF;;;;
+0626;ARABIC LETTER YEH WITH HAMZA ABOVE;Lo;0;AL;064A 0654;;;;N;ARABIC LETTER HAMZAH ON YA;;;;
+0627;ARABIC LETTER ALEF;Lo;0;AL;;;;;N;;;;;
+0628;ARABIC LETTER BEH;Lo;0;AL;;;;;N;ARABIC LETTER BAA;;;;
+0629;ARABIC LETTER TEH MARBUTA;Lo;0;AL;;;;;N;ARABIC LETTER TAA MARBUTAH;;;;
+062A;ARABIC LETTER TEH;Lo;0;AL;;;;;N;ARABIC LETTER TAA;;;;
+062B;ARABIC LETTER THEH;Lo;0;AL;;;;;N;ARABIC LETTER THAA;;;;
+062C;ARABIC LETTER JEEM;Lo;0;AL;;;;;N;;;;;
+062D;ARABIC LETTER HAH;Lo;0;AL;;;;;N;ARABIC LETTER HAA;;;;
+062E;ARABIC LETTER KHAH;Lo;0;AL;;;;;N;ARABIC LETTER KHAA;;;;
+062F;ARABIC LETTER DAL;Lo;0;AL;;;;;N;;;;;
+0630;ARABIC LETTER THAL;Lo;0;AL;;;;;N;;;;;
+0631;ARABIC LETTER REH;Lo;0;AL;;;;;N;ARABIC LETTER RA;;;;
+0632;ARABIC LETTER ZAIN;Lo;0;AL;;;;;N;;;;;
+0633;ARABIC LETTER SEEN;Lo;0;AL;;;;;N;;;;;
+0634;ARABIC LETTER SHEEN;Lo;0;AL;;;;;N;;;;;
+0635;ARABIC LETTER SAD;Lo;0;AL;;;;;N;;;;;
+0636;ARABIC LETTER DAD;Lo;0;AL;;;;;N;;;;;
+0637;ARABIC LETTER TAH;Lo;0;AL;;;;;N;;;;;
+0638;ARABIC LETTER ZAH;Lo;0;AL;;;;;N;ARABIC LETTER DHAH;;;;
+0639;ARABIC LETTER AIN;Lo;0;AL;;;;;N;;;;;
+063A;ARABIC LETTER GHAIN;Lo;0;AL;;;;;N;;;;;
+0640;ARABIC TATWEEL;Lm;0;AL;;;;;N;;;;;
+0641;ARABIC LETTER FEH;Lo;0;AL;;;;;N;ARABIC LETTER FA;;;;
+0642;ARABIC LETTER QAF;Lo;0;AL;;;;;N;;;;;
+0643;ARABIC LETTER KAF;Lo;0;AL;;;;;N;ARABIC LETTER CAF;;;;
+0644;ARABIC LETTER LAM;Lo;0;AL;;;;;N;;;;;
+0645;ARABIC LETTER MEEM;Lo;0;AL;;;;;N;;;;;
+0646;ARABIC LETTER NOON;Lo;0;AL;;;;;N;;;;;
+0647;ARABIC LETTER HEH;Lo;0;AL;;;;;N;ARABIC LETTER HA;;;;
+0648;ARABIC LETTER WAW;Lo;0;AL;;;;;N;;;;;
+0649;ARABIC LETTER ALEF MAKSURA;Lo;0;AL;;;;;N;ARABIC LETTER ALEF MAQSURAH;;;;
+064A;ARABIC LETTER YEH;Lo;0;AL;;;;;N;ARABIC LETTER YA;;;;
+064B;ARABIC FATHATAN;Mn;27;NSM;;;;;N;;;;;
+064C;ARABIC DAMMATAN;Mn;28;NSM;;;;;N;;;;;
+064D;ARABIC KASRATAN;Mn;29;NSM;;;;;N;;;;;
+064E;ARABIC FATHA;Mn;30;NSM;;;;;N;ARABIC FATHAH;;;;
+064F;ARABIC DAMMA;Mn;31;NSM;;;;;N;ARABIC DAMMAH;;;;
+0650;ARABIC KASRA;Mn;32;NSM;;;;;N;ARABIC KASRAH;;;;
+0651;ARABIC SHADDA;Mn;33;NSM;;;;;N;ARABIC SHADDAH;;;;
+0652;ARABIC SUKUN;Mn;34;NSM;;;;;N;;;;;
+0653;ARABIC MADDAH ABOVE;Mn;230;NSM;;;;;N;;;;;
+0654;ARABIC HAMZA ABOVE;Mn;230;NSM;;;;;N;;;;;
+0655;ARABIC HAMZA BELOW;Mn;220;NSM;;;;;N;;;;;
+0656;ARABIC SUBSCRIPT ALEF;Mn;220;NSM;;;;;N;;;;;
+0657;ARABIC INVERTED DAMMA;Mn;230;NSM;;;;;N;;;;;
+0658;ARABIC MARK NOON GHUNNA;Mn;230;NSM;;;;;N;;;;;
+0660;ARABIC-INDIC DIGIT ZERO;Nd;0;AN;;0;0;0;N;;;;;
+0661;ARABIC-INDIC DIGIT ONE;Nd;0;AN;;1;1;1;N;;;;;
+0662;ARABIC-INDIC DIGIT TWO;Nd;0;AN;;2;2;2;N;;;;;
+0663;ARABIC-INDIC DIGIT THREE;Nd;0;AN;;3;3;3;N;;;;;
+0664;ARABIC-INDIC DIGIT FOUR;Nd;0;AN;;4;4;4;N;;;;;
+0665;ARABIC-INDIC DIGIT FIVE;Nd;0;AN;;5;5;5;N;;;;;
+0666;ARABIC-INDIC DIGIT SIX;Nd;0;AN;;6;6;6;N;;;;;
+0667;ARABIC-INDIC DIGIT SEVEN;Nd;0;AN;;7;7;7;N;;;;;
+0668;ARABIC-INDIC DIGIT EIGHT;Nd;0;AN;;8;8;8;N;;;;;
+0669;ARABIC-INDIC DIGIT NINE;Nd;0;AN;;9;9;9;N;;;;;
+066A;ARABIC PERCENT SIGN;Po;0;ET;;;;;N;;;;;
+066B;ARABIC DECIMAL SEPARATOR;Po;0;AN;;;;;N;;;;;
+066C;ARABIC THOUSANDS SEPARATOR;Po;0;AN;;;;;N;;;;;
+066D;ARABIC FIVE POINTED STAR;Po;0;AL;;;;;N;;;;;
+066E;ARABIC LETTER DOTLESS BEH;Lo;0;AL;;;;;N;;;;;
+066F;ARABIC LETTER DOTLESS QAF;Lo;0;AL;;;;;N;;;;;
+0670;ARABIC LETTER SUPERSCRIPT ALEF;Mn;35;NSM;;;;;N;ARABIC ALEF ABOVE;;;;
+0671;ARABIC LETTER ALEF WASLA;Lo;0;AL;;;;;N;ARABIC LETTER HAMZAT WASL ON ALEF;;;;
+0672;ARABIC LETTER ALEF WITH WAVY HAMZA ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER WAVY HAMZAH ON ALEF;;;;
+0673;ARABIC LETTER ALEF WITH WAVY HAMZA BELOW;Lo;0;AL;;;;;N;ARABIC LETTER WAVY HAMZAH UNDER ALEF;;;;
+0674;ARABIC LETTER HIGH HAMZA;Lo;0;AL;;;;;N;ARABIC LETTER HIGH HAMZAH;;;;
+0675;ARABIC LETTER HIGH HAMZA ALEF;Lo;0;AL;<compat> 0627 0674;;;;N;ARABIC LETTER HIGH HAMZAH ALEF;;;;
+0676;ARABIC LETTER HIGH HAMZA WAW;Lo;0;AL;<compat> 0648 0674;;;;N;ARABIC LETTER HIGH HAMZAH WAW;;;;
+0677;ARABIC LETTER U WITH HAMZA ABOVE;Lo;0;AL;<compat> 06C7 0674;;;;N;ARABIC LETTER HIGH HAMZAH WAW WITH DAMMAH;;;;
+0678;ARABIC LETTER HIGH HAMZA YEH;Lo;0;AL;<compat> 064A 0674;;;;N;ARABIC LETTER HIGH HAMZAH YA;;;;
+0679;ARABIC LETTER TTEH;Lo;0;AL;;;;;N;ARABIC LETTER TAA WITH SMALL TAH;;;;
+067A;ARABIC LETTER TTEHEH;Lo;0;AL;;;;;N;ARABIC LETTER TAA WITH TWO DOTS VERTICAL ABOVE;;;;
+067B;ARABIC LETTER BEEH;Lo;0;AL;;;;;N;ARABIC LETTER BAA WITH TWO DOTS VERTICAL BELOW;;;;
+067C;ARABIC LETTER TEH WITH RING;Lo;0;AL;;;;;N;ARABIC LETTER TAA WITH RING;;;;
+067D;ARABIC LETTER TEH WITH THREE DOTS ABOVE DOWNWARDS;Lo;0;AL;;;;;N;ARABIC LETTER TAA WITH THREE DOTS ABOVE DOWNWARD;;;;
+067E;ARABIC LETTER PEH;Lo;0;AL;;;;;N;ARABIC LETTER TAA WITH THREE DOTS BELOW;;;;
+067F;ARABIC LETTER TEHEH;Lo;0;AL;;;;;N;ARABIC LETTER TAA WITH FOUR DOTS ABOVE;;;;
+0680;ARABIC LETTER BEHEH;Lo;0;AL;;;;;N;ARABIC LETTER BAA WITH FOUR DOTS BELOW;;;;
+0681;ARABIC LETTER HAH WITH HAMZA ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER HAMZAH ON HAA;;;;
+0682;ARABIC LETTER HAH WITH TWO DOTS VERTICAL ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER HAA WITH TWO DOTS VERTICAL ABOVE;;;;
+0683;ARABIC LETTER NYEH;Lo;0;AL;;;;;N;ARABIC LETTER HAA WITH MIDDLE TWO DOTS;;;;
+0684;ARABIC LETTER DYEH;Lo;0;AL;;;;;N;ARABIC LETTER HAA WITH MIDDLE TWO DOTS VERTICAL;;;;
+0685;ARABIC LETTER HAH WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER HAA WITH THREE DOTS ABOVE;;;;
+0686;ARABIC LETTER TCHEH;Lo;0;AL;;;;;N;ARABIC LETTER HAA WITH MIDDLE THREE DOTS DOWNWARD;;;;
+0687;ARABIC LETTER TCHEHEH;Lo;0;AL;;;;;N;ARABIC LETTER HAA WITH MIDDLE FOUR DOTS;;;;
+0688;ARABIC LETTER DDAL;Lo;0;AL;;;;;N;ARABIC LETTER DAL WITH SMALL TAH;;;;
+0689;ARABIC LETTER DAL WITH RING;Lo;0;AL;;;;;N;;;;;
+068A;ARABIC LETTER DAL WITH DOT BELOW;Lo;0;AL;;;;;N;;;;;
+068B;ARABIC LETTER DAL WITH DOT BELOW AND SMALL TAH;Lo;0;AL;;;;;N;;;;;
+068C;ARABIC LETTER DAHAL;Lo;0;AL;;;;;N;ARABIC LETTER DAL WITH TWO DOTS ABOVE;;;;
+068D;ARABIC LETTER DDAHAL;Lo;0;AL;;;;;N;ARABIC LETTER DAL WITH TWO DOTS BELOW;;;;
+068E;ARABIC LETTER DUL;Lo;0;AL;;;;;N;ARABIC LETTER DAL WITH THREE DOTS ABOVE;;;;
+068F;ARABIC LETTER DAL WITH THREE DOTS ABOVE DOWNWARDS;Lo;0;AL;;;;;N;ARABIC LETTER DAL WITH THREE DOTS ABOVE DOWNWARD;;;;
+0690;ARABIC LETTER DAL WITH FOUR DOTS ABOVE;Lo;0;AL;;;;;N;;;;;
+0691;ARABIC LETTER RREH;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH SMALL TAH;;;;
+0692;ARABIC LETTER REH WITH SMALL V;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH SMALL V;;;;
+0693;ARABIC LETTER REH WITH RING;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH RING;;;;
+0694;ARABIC LETTER REH WITH DOT BELOW;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH DOT BELOW;;;;
+0695;ARABIC LETTER REH WITH SMALL V BELOW;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH SMALL V BELOW;;;;
+0696;ARABIC LETTER REH WITH DOT BELOW AND DOT ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH DOT BELOW AND DOT ABOVE;;;;
+0697;ARABIC LETTER REH WITH TWO DOTS ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH TWO DOTS ABOVE;;;;
+0698;ARABIC LETTER JEH;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH THREE DOTS ABOVE;;;;
+0699;ARABIC LETTER REH WITH FOUR DOTS ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH FOUR DOTS ABOVE;;;;
+069A;ARABIC LETTER SEEN WITH DOT BELOW AND DOT ABOVE;Lo;0;AL;;;;;N;;;;;
+069B;ARABIC LETTER SEEN WITH THREE DOTS BELOW;Lo;0;AL;;;;;N;;;;;
+069C;ARABIC LETTER SEEN WITH THREE DOTS BELOW AND THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;;
+069D;ARABIC LETTER SAD WITH TWO DOTS BELOW;Lo;0;AL;;;;;N;;;;;
+069E;ARABIC LETTER SAD WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;;
+069F;ARABIC LETTER TAH WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;;
+06A0;ARABIC LETTER AIN WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;;
+06A1;ARABIC LETTER DOTLESS FEH;Lo;0;AL;;;;;N;ARABIC LETTER DOTLESS FA;;;;
+06A2;ARABIC LETTER FEH WITH DOT MOVED BELOW;Lo;0;AL;;;;;N;ARABIC LETTER FA WITH DOT MOVED BELOW;;;;
+06A3;ARABIC LETTER FEH WITH DOT BELOW;Lo;0;AL;;;;;N;ARABIC LETTER FA WITH DOT BELOW;;;;
+06A4;ARABIC LETTER VEH;Lo;0;AL;;;;;N;ARABIC LETTER FA WITH THREE DOTS ABOVE;;;;
+06A5;ARABIC LETTER FEH WITH THREE DOTS BELOW;Lo;0;AL;;;;;N;ARABIC LETTER FA WITH THREE DOTS BELOW;;;;
+06A6;ARABIC LETTER PEHEH;Lo;0;AL;;;;;N;ARABIC LETTER FA WITH FOUR DOTS ABOVE;;;;
+06A7;ARABIC LETTER QAF WITH DOT ABOVE;Lo;0;AL;;;;;N;;;;;
+06A8;ARABIC LETTER QAF WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;;
+06A9;ARABIC LETTER KEHEH;Lo;0;AL;;;;;N;ARABIC LETTER OPEN CAF;;;;
+06AA;ARABIC LETTER SWASH KAF;Lo;0;AL;;;;;N;ARABIC LETTER SWASH CAF;;;;
+06AB;ARABIC LETTER KAF WITH RING;Lo;0;AL;;;;;N;ARABIC LETTER CAF WITH RING;;;;
+06AC;ARABIC LETTER KAF WITH DOT ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER CAF WITH DOT ABOVE;;;;
+06AD;ARABIC LETTER NG;Lo;0;AL;;;;;N;ARABIC LETTER CAF WITH THREE DOTS ABOVE;;;;
+06AE;ARABIC LETTER KAF WITH THREE DOTS BELOW;Lo;0;AL;;;;;N;ARABIC LETTER CAF WITH THREE DOTS BELOW;;;;
+06AF;ARABIC LETTER GAF;Lo;0;AL;;;;;N;;*;;;
+06B0;ARABIC LETTER GAF WITH RING;Lo;0;AL;;;;;N;;;;;
+06B1;ARABIC LETTER NGOEH;Lo;0;AL;;;;;N;ARABIC LETTER GAF WITH TWO DOTS ABOVE;;;;
+06B2;ARABIC LETTER GAF WITH TWO DOTS BELOW;Lo;0;AL;;;;;N;;;;;
+06B3;ARABIC LETTER GUEH;Lo;0;AL;;;;;N;ARABIC LETTER GAF WITH TWO DOTS VERTICAL BELOW;;;;
+06B4;ARABIC LETTER GAF WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;;
+06B5;ARABIC LETTER LAM WITH SMALL V;Lo;0;AL;;;;;N;;;;;
+06B6;ARABIC LETTER LAM WITH DOT ABOVE;Lo;0;AL;;;;;N;;;;;
+06B7;ARABIC LETTER LAM WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;;
+06B8;ARABIC LETTER LAM WITH THREE DOTS BELOW;Lo;0;AL;;;;;N;;;;;
+06B9;ARABIC LETTER NOON WITH DOT BELOW;Lo;0;AL;;;;;N;;;;;
+06BA;ARABIC LETTER NOON GHUNNA;Lo;0;AL;;;;;N;ARABIC LETTER DOTLESS NOON;;;;
+06BB;ARABIC LETTER RNOON;Lo;0;AL;;;;;N;ARABIC LETTER DOTLESS NOON WITH SMALL TAH;;;;
+06BC;ARABIC LETTER NOON WITH RING;Lo;0;AL;;;;;N;;;;;
+06BD;ARABIC LETTER NOON WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;;
+06BE;ARABIC LETTER HEH DOACHASHMEE;Lo;0;AL;;;;;N;ARABIC LETTER KNOTTED HA;;;;
+06BF;ARABIC LETTER TCHEH WITH DOT ABOVE;Lo;0;AL;;;;;N;;;;;
+06C0;ARABIC LETTER HEH WITH YEH ABOVE;Lo;0;AL;06D5 0654;;;;N;ARABIC LETTER HAMZAH ON HA;;;;
+06C1;ARABIC LETTER HEH GOAL;Lo;0;AL;;;;;N;ARABIC LETTER HA GOAL;;;;
+06C2;ARABIC LETTER HEH GOAL WITH HAMZA ABOVE;Lo;0;AL;06C1 0654;;;;N;ARABIC LETTER HAMZAH ON HA GOAL;;;;
+06C3;ARABIC LETTER TEH MARBUTA GOAL;Lo;0;AL;;;;;N;ARABIC LETTER TAA MARBUTAH GOAL;;;;
+06C4;ARABIC LETTER WAW WITH RING;Lo;0;AL;;;;;N;;;;;
+06C5;ARABIC LETTER KIRGHIZ OE;Lo;0;AL;;;;;N;ARABIC LETTER WAW WITH BAR;;;;
+06C6;ARABIC LETTER OE;Lo;0;AL;;;;;N;ARABIC LETTER WAW WITH SMALL V;;;;
+06C7;ARABIC LETTER U;Lo;0;AL;;;;;N;ARABIC LETTER WAW WITH DAMMAH;;;;
+06C8;ARABIC LETTER YU;Lo;0;AL;;;;;N;ARABIC LETTER WAW WITH ALEF ABOVE;;;;
+06C9;ARABIC LETTER KIRGHIZ YU;Lo;0;AL;;;;;N;ARABIC LETTER WAW WITH INVERTED SMALL V;;;;
+06CA;ARABIC LETTER WAW WITH TWO DOTS ABOVE;Lo;0;AL;;;;;N;;;;;
+06CB;ARABIC LETTER VE;Lo;0;AL;;;;;N;ARABIC LETTER WAW WITH THREE DOTS ABOVE;;;;
+06CC;ARABIC LETTER FARSI YEH;Lo;0;AL;;;;;N;ARABIC LETTER DOTLESS YA;;;;
+06CD;ARABIC LETTER YEH WITH TAIL;Lo;0;AL;;;;;N;ARABIC LETTER YA WITH TAIL;;;;
+06CE;ARABIC LETTER YEH WITH SMALL V;Lo;0;AL;;;;;N;ARABIC LETTER YA WITH SMALL V;;;;
+06CF;ARABIC LETTER WAW WITH DOT ABOVE;Lo;0;AL;;;;;N;;;;;
+06D0;ARABIC LETTER E;Lo;0;AL;;;;;N;ARABIC LETTER YA WITH TWO DOTS VERTICAL BELOW;*;;;
+06D1;ARABIC LETTER YEH WITH THREE DOTS BELOW;Lo;0;AL;;;;;N;ARABIC LETTER YA WITH THREE DOTS BELOW;;;;
+06D2;ARABIC LETTER YEH BARREE;Lo;0;AL;;;;;N;ARABIC LETTER YA BARREE;;;;
+06D3;ARABIC LETTER YEH BARREE WITH HAMZA ABOVE;Lo;0;AL;06D2 0654;;;;N;ARABIC LETTER HAMZAH ON YA BARREE;;;;
+06D4;ARABIC FULL STOP;Po;0;AL;;;;;N;ARABIC PERIOD;;;;
+06D5;ARABIC LETTER AE;Lo;0;AL;;;;;N;;;;;
+06D6;ARABIC SMALL HIGH LIGATURE SAD WITH LAM WITH ALEF MAKSURA;Mn;230;NSM;;;;;N;;;;;
+06D7;ARABIC SMALL HIGH LIGATURE QAF WITH LAM WITH ALEF MAKSURA;Mn;230;NSM;;;;;N;;;;;
+06D8;ARABIC SMALL HIGH MEEM INITIAL FORM;Mn;230;NSM;;;;;N;;;;;
+06D9;ARABIC SMALL HIGH LAM ALEF;Mn;230;NSM;;;;;N;;;;;
+06DA;ARABIC SMALL HIGH JEEM;Mn;230;NSM;;;;;N;;;;;
+06DB;ARABIC SMALL HIGH THREE DOTS;Mn;230;NSM;;;;;N;;;;;
+06DC;ARABIC SMALL HIGH SEEN;Mn;230;NSM;;;;;N;;;;;
+06DD;ARABIC END OF AYAH;Cf;0;AL;;;;;N;;;;;
+06DE;ARABIC START OF RUB EL HIZB;Me;0;NSM;;;;;N;;;;;
+06DF;ARABIC SMALL HIGH ROUNDED ZERO;Mn;230;NSM;;;;;N;;;;;
+06E0;ARABIC SMALL HIGH UPRIGHT RECTANGULAR ZERO;Mn;230;NSM;;;;;N;;;;;
+06E1;ARABIC SMALL HIGH DOTLESS HEAD OF KHAH;Mn;230;NSM;;;;;N;;;;;
+06E2;ARABIC SMALL HIGH MEEM ISOLATED FORM;Mn;230;NSM;;;;;N;;;;;
+06E3;ARABIC SMALL LOW SEEN;Mn;220;NSM;;;;;N;;;;;
+06E4;ARABIC SMALL HIGH MADDA;Mn;230;NSM;;;;;N;;;;;
+06E5;ARABIC SMALL WAW;Lm;0;AL;;;;;N;;;;;
+06E6;ARABIC SMALL YEH;Lm;0;AL;;;;;N;;;;;
+06E7;ARABIC SMALL HIGH YEH;Mn;230;NSM;;;;;N;;;;;
+06E8;ARABIC SMALL HIGH NOON;Mn;230;NSM;;;;;N;;;;;
+06E9;ARABIC PLACE OF SAJDAH;So;0;ON;;;;;N;;;;;
+06EA;ARABIC EMPTY CENTRE LOW STOP;Mn;220;NSM;;;;;N;;;;;
+06EB;ARABIC EMPTY CENTRE HIGH STOP;Mn;230;NSM;;;;;N;;;;;
+06EC;ARABIC ROUNDED HIGH STOP WITH FILLED CENTRE;Mn;230;NSM;;;;;N;;;;;
+06ED;ARABIC SMALL LOW MEEM;Mn;220;NSM;;;;;N;;;;;
+06EE;ARABIC LETTER DAL WITH INVERTED V;Lo;0;AL;;;;;N;;;;;
+06EF;ARABIC LETTER REH WITH INVERTED V;Lo;0;AL;;;;;N;;;;;
+06F0;EXTENDED ARABIC-INDIC DIGIT ZERO;Nd;0;EN;;0;0;0;N;EASTERN ARABIC-INDIC DIGIT ZERO;;;;
+06F1;EXTENDED ARABIC-INDIC DIGIT ONE;Nd;0;EN;;1;1;1;N;EASTERN ARABIC-INDIC DIGIT ONE;;;;
+06F2;EXTENDED ARABIC-INDIC DIGIT TWO;Nd;0;EN;;2;2;2;N;EASTERN ARABIC-INDIC DIGIT TWO;;;;
+06F3;EXTENDED ARABIC-INDIC DIGIT THREE;Nd;0;EN;;3;3;3;N;EASTERN ARABIC-INDIC DIGIT THREE;;;;
+06F4;EXTENDED ARABIC-INDIC DIGIT FOUR;Nd;0;EN;;4;4;4;N;EASTERN ARABIC-INDIC DIGIT FOUR;;;;
+06F5;EXTENDED ARABIC-INDIC DIGIT FIVE;Nd;0;EN;;5;5;5;N;EASTERN ARABIC-INDIC DIGIT FIVE;;;;
+06F6;EXTENDED ARABIC-INDIC DIGIT SIX;Nd;0;EN;;6;6;6;N;EASTERN ARABIC-INDIC DIGIT SIX;;;;
+06F7;EXTENDED ARABIC-INDIC DIGIT SEVEN;Nd;0;EN;;7;7;7;N;EASTERN ARABIC-INDIC DIGIT SEVEN;;;;
+06F8;EXTENDED ARABIC-INDIC DIGIT EIGHT;Nd;0;EN;;8;8;8;N;EASTERN ARABIC-INDIC DIGIT EIGHT;;;;
+06F9;EXTENDED ARABIC-INDIC DIGIT NINE;Nd;0;EN;;9;9;9;N;EASTERN ARABIC-INDIC DIGIT NINE;;;;
+06FA;ARABIC LETTER SHEEN WITH DOT BELOW;Lo;0;AL;;;;;N;;;;;
+06FB;ARABIC LETTER DAD WITH DOT BELOW;Lo;0;AL;;;;;N;;;;;
+06FC;ARABIC LETTER GHAIN WITH DOT BELOW;Lo;0;AL;;;;;N;;;;;
+06FD;ARABIC SIGN SINDHI AMPERSAND;So;0;AL;;;;;N;;;;;
+06FE;ARABIC SIGN SINDHI POSTPOSITION MEN;So;0;AL;;;;;N;;;;;
+06FF;ARABIC LETTER HEH WITH INVERTED V;Lo;0;AL;;;;;N;;;;;
+0700;SYRIAC END OF PARAGRAPH;Po;0;AL;;;;;N;;;;;
+0701;SYRIAC SUPRALINEAR FULL STOP;Po;0;AL;;;;;N;;;;;
+0702;SYRIAC SUBLINEAR FULL STOP;Po;0;AL;;;;;N;;;;;
+0703;SYRIAC SUPRALINEAR COLON;Po;0;AL;;;;;N;;;;;
+0704;SYRIAC SUBLINEAR COLON;Po;0;AL;;;;;N;;;;;
+0705;SYRIAC HORIZONTAL COLON;Po;0;AL;;;;;N;;;;;
+0706;SYRIAC COLON SKEWED LEFT;Po;0;AL;;;;;N;;;;;
+0707;SYRIAC COLON SKEWED RIGHT;Po;0;AL;;;;;N;;;;;
+0708;SYRIAC SUPRALINEAR COLON SKEWED LEFT;Po;0;AL;;;;;N;;;;;
+0709;SYRIAC SUBLINEAR COLON SKEWED RIGHT;Po;0;AL;;;;;N;;;;;
+070A;SYRIAC CONTRACTION;Po;0;AL;;;;;N;;;;;
+070B;SYRIAC HARKLEAN OBELUS;Po;0;AL;;;;;N;;;;;
+070C;SYRIAC HARKLEAN METOBELUS;Po;0;AL;;;;;N;;;;;
+070D;SYRIAC HARKLEAN ASTERISCUS;Po;0;AL;;;;;N;;;;;
+070F;SYRIAC ABBREVIATION MARK;Cf;0;BN;;;;;N;;;;;
+0710;SYRIAC LETTER ALAPH;Lo;0;AL;;;;;N;;;;;
+0711;SYRIAC LETTER SUPERSCRIPT ALAPH;Mn;36;NSM;;;;;N;;;;;
+0712;SYRIAC LETTER BETH;Lo;0;AL;;;;;N;;;;;
+0713;SYRIAC LETTER GAMAL;Lo;0;AL;;;;;N;;;;;
+0714;SYRIAC LETTER GAMAL GARSHUNI;Lo;0;AL;;;;;N;;;;;
+0715;SYRIAC LETTER DALATH;Lo;0;AL;;;;;N;;;;;
+0716;SYRIAC LETTER DOTLESS DALATH RISH;Lo;0;AL;;;;;N;;;;;
+0717;SYRIAC LETTER HE;Lo;0;AL;;;;;N;;;;;
+0718;SYRIAC LETTER WAW;Lo;0;AL;;;;;N;;;;;
+0719;SYRIAC LETTER ZAIN;Lo;0;AL;;;;;N;;;;;
+071A;SYRIAC LETTER HETH;Lo;0;AL;;;;;N;;;;;
+071B;SYRIAC LETTER TETH;Lo;0;AL;;;;;N;;;;;
+071C;SYRIAC LETTER TETH GARSHUNI;Lo;0;AL;;;;;N;;;;;
+071D;SYRIAC LETTER YUDH;Lo;0;AL;;;;;N;;;;;
+071E;SYRIAC LETTER YUDH HE;Lo;0;AL;;;;;N;;;;;
+071F;SYRIAC LETTER KAPH;Lo;0;AL;;;;;N;;;;;
+0720;SYRIAC LETTER LAMADH;Lo;0;AL;;;;;N;;;;;
+0721;SYRIAC LETTER MIM;Lo;0;AL;;;;;N;;;;;
+0722;SYRIAC LETTER NUN;Lo;0;AL;;;;;N;;;;;
+0723;SYRIAC LETTER SEMKATH;Lo;0;AL;;;;;N;;;;;
+0724;SYRIAC LETTER FINAL SEMKATH;Lo;0;AL;;;;;N;;;;;
+0725;SYRIAC LETTER E;Lo;0;AL;;;;;N;;;;;
+0726;SYRIAC LETTER PE;Lo;0;AL;;;;;N;;;;;
+0727;SYRIAC LETTER REVERSED PE;Lo;0;AL;;;;;N;;;;;
+0728;SYRIAC LETTER SADHE;Lo;0;AL;;;;;N;;;;;
+0729;SYRIAC LETTER QAPH;Lo;0;AL;;;;;N;;;;;
+072A;SYRIAC LETTER RISH;Lo;0;AL;;;;;N;;;;;
+072B;SYRIAC LETTER SHIN;Lo;0;AL;;;;;N;;;;;
+072C;SYRIAC LETTER TAW;Lo;0;AL;;;;;N;;;;;
+072D;SYRIAC LETTER PERSIAN BHETH;Lo;0;AL;;;;;N;;;;;
+072E;SYRIAC LETTER PERSIAN GHAMAL;Lo;0;AL;;;;;N;;;;;
+072F;SYRIAC LETTER PERSIAN DHALATH;Lo;0;AL;;;;;N;;;;;
+0730;SYRIAC PTHAHA ABOVE;Mn;230;NSM;;;;;N;;;;;
+0731;SYRIAC PTHAHA BELOW;Mn;220;NSM;;;;;N;;;;;
+0732;SYRIAC PTHAHA DOTTED;Mn;230;NSM;;;;;N;;;;;
+0733;SYRIAC ZQAPHA ABOVE;Mn;230;NSM;;;;;N;;;;;
+0734;SYRIAC ZQAPHA BELOW;Mn;220;NSM;;;;;N;;;;;
+0735;SYRIAC ZQAPHA DOTTED;Mn;230;NSM;;;;;N;;;;;
+0736;SYRIAC RBASA ABOVE;Mn;230;NSM;;;;;N;;;;;
+0737;SYRIAC RBASA BELOW;Mn;220;NSM;;;;;N;;;;;
+0738;SYRIAC DOTTED ZLAMA HORIZONTAL;Mn;220;NSM;;;;;N;;;;;
+0739;SYRIAC DOTTED ZLAMA ANGULAR;Mn;220;NSM;;;;;N;;;;;
+073A;SYRIAC HBASA ABOVE;Mn;230;NSM;;;;;N;;;;;
+073B;SYRIAC HBASA BELOW;Mn;220;NSM;;;;;N;;;;;
+073C;SYRIAC HBASA-ESASA DOTTED;Mn;220;NSM;;;;;N;;;;;
+073D;SYRIAC ESASA ABOVE;Mn;230;NSM;;;;;N;;;;;
+073E;SYRIAC ESASA BELOW;Mn;220;NSM;;;;;N;;;;;
+073F;SYRIAC RWAHA;Mn;230;NSM;;;;;N;;;;;
+0740;SYRIAC FEMININE DOT;Mn;230;NSM;;;;;N;;;;;
+0741;SYRIAC QUSHSHAYA;Mn;230;NSM;;;;;N;;;;;
+0742;SYRIAC RUKKAKHA;Mn;220;NSM;;;;;N;;;;;
+0743;SYRIAC TWO VERTICAL DOTS ABOVE;Mn;230;NSM;;;;;N;;;;;
+0744;SYRIAC TWO VERTICAL DOTS BELOW;Mn;220;NSM;;;;;N;;;;;
+0745;SYRIAC THREE DOTS ABOVE;Mn;230;NSM;;;;;N;;;;;
+0746;SYRIAC THREE DOTS BELOW;Mn;220;NSM;;;;;N;;;;;
+0747;SYRIAC OBLIQUE LINE ABOVE;Mn;230;NSM;;;;;N;;;;;
+0748;SYRIAC OBLIQUE LINE BELOW;Mn;220;NSM;;;;;N;;;;;
+0749;SYRIAC MUSIC;Mn;230;NSM;;;;;N;;;;;
+074A;SYRIAC BARREKH;Mn;230;NSM;;;;;N;;;;;
+074D;SYRIAC LETTER SOGDIAN ZHAIN;Lo;0;AL;;;;;N;;;;;
+074E;SYRIAC LETTER SOGDIAN KHAPH;Lo;0;AL;;;;;N;;;;;
+074F;SYRIAC LETTER SOGDIAN FE;Lo;0;AL;;;;;N;;;;;
+0780;THAANA LETTER HAA;Lo;0;AL;;;;;N;;;;;
+0781;THAANA LETTER SHAVIYANI;Lo;0;AL;;;;;N;;;;;
+0782;THAANA LETTER NOONU;Lo;0;AL;;;;;N;;;;;
+0783;THAANA LETTER RAA;Lo;0;AL;;;;;N;;;;;
+0784;THAANA LETTER BAA;Lo;0;AL;;;;;N;;;;;
+0785;THAANA LETTER LHAVIYANI;Lo;0;AL;;;;;N;;;;;
+0786;THAANA LETTER KAAFU;Lo;0;AL;;;;;N;;;;;
+0787;THAANA LETTER ALIFU;Lo;0;AL;;;;;N;;;;;
+0788;THAANA LETTER VAAVU;Lo;0;AL;;;;;N;;;;;
+0789;THAANA LETTER MEEMU;Lo;0;AL;;;;;N;;;;;
+078A;THAANA LETTER FAAFU;Lo;0;AL;;;;;N;;;;;
+078B;THAANA LETTER DHAALU;Lo;0;AL;;;;;N;;;;;
+078C;THAANA LETTER THAA;Lo;0;AL;;;;;N;;;;;
+078D;THAANA LETTER LAAMU;Lo;0;AL;;;;;N;;;;;
+078E;THAANA LETTER GAAFU;Lo;0;AL;;;;;N;;;;;
+078F;THAANA LETTER GNAVIYANI;Lo;0;AL;;;;;N;;;;;
+0790;THAANA LETTER SEENU;Lo;0;AL;;;;;N;;;;;
+0791;THAANA LETTER DAVIYANI;Lo;0;AL;;;;;N;;;;;
+0792;THAANA LETTER ZAVIYANI;Lo;0;AL;;;;;N;;;;;
+0793;THAANA LETTER TAVIYANI;Lo;0;AL;;;;;N;;;;;
+0794;THAANA LETTER YAA;Lo;0;AL;;;;;N;;;;;
+0795;THAANA LETTER PAVIYANI;Lo;0;AL;;;;;N;;;;;
+0796;THAANA LETTER JAVIYANI;Lo;0;AL;;;;;N;;;;;
+0797;THAANA LETTER CHAVIYANI;Lo;0;AL;;;;;N;;;;;
+0798;THAANA LETTER TTAA;Lo;0;AL;;;;;N;;;;;
+0799;THAANA LETTER HHAA;Lo;0;AL;;;;;N;;;;;
+079A;THAANA LETTER KHAA;Lo;0;AL;;;;;N;;;;;
+079B;THAANA LETTER THAALU;Lo;0;AL;;;;;N;;;;;
+079C;THAANA LETTER ZAA;Lo;0;AL;;;;;N;;;;;
+079D;THAANA LETTER SHEENU;Lo;0;AL;;;;;N;;;;;
+079E;THAANA LETTER SAADHU;Lo;0;AL;;;;;N;;;;;
+079F;THAANA LETTER DAADHU;Lo;0;AL;;;;;N;;;;;
+07A0;THAANA LETTER TO;Lo;0;AL;;;;;N;;;;;
+07A1;THAANA LETTER ZO;Lo;0;AL;;;;;N;;;;;
+07A2;THAANA LETTER AINU;Lo;0;AL;;;;;N;;;;;
+07A3;THAANA LETTER GHAINU;Lo;0;AL;;;;;N;;;;;
+07A4;THAANA LETTER QAAFU;Lo;0;AL;;;;;N;;;;;
+07A5;THAANA LETTER WAAVU;Lo;0;AL;;;;;N;;;;;
+07A6;THAANA ABAFILI;Mn;0;NSM;;;;;N;;;;;
+07A7;THAANA AABAAFILI;Mn;0;NSM;;;;;N;;;;;
+07A8;THAANA IBIFILI;Mn;0;NSM;;;;;N;;;;;
+07A9;THAANA EEBEEFILI;Mn;0;NSM;;;;;N;;;;;
+07AA;THAANA UBUFILI;Mn;0;NSM;;;;;N;;;;;
+07AB;THAANA OOBOOFILI;Mn;0;NSM;;;;;N;;;;;
+07AC;THAANA EBEFILI;Mn;0;NSM;;;;;N;;;;;
+07AD;THAANA EYBEYFILI;Mn;0;NSM;;;;;N;;;;;
+07AE;THAANA OBOFILI;Mn;0;NSM;;;;;N;;;;;
+07AF;THAANA OABOAFILI;Mn;0;NSM;;;;;N;;;;;
+07B0;THAANA SUKUN;Mn;0;NSM;;;;;N;;;;;
+07B1;THAANA LETTER NAA;Lo;0;AL;;;;;N;;;;;
+0901;DEVANAGARI SIGN CANDRABINDU;Mn;0;NSM;;;;;N;;;;;
+0902;DEVANAGARI SIGN ANUSVARA;Mn;0;NSM;;;;;N;;;;;
+0903;DEVANAGARI SIGN VISARGA;Mc;0;L;;;;;N;;;;;
+0904;DEVANAGARI LETTER SHORT A;Lo;0;L;;;;;N;;;;;
+0905;DEVANAGARI LETTER A;Lo;0;L;;;;;N;;;;;
+0906;DEVANAGARI LETTER AA;Lo;0;L;;;;;N;;;;;
+0907;DEVANAGARI LETTER I;Lo;0;L;;;;;N;;;;;
+0908;DEVANAGARI LETTER II;Lo;0;L;;;;;N;;;;;
+0909;DEVANAGARI LETTER U;Lo;0;L;;;;;N;;;;;
+090A;DEVANAGARI LETTER UU;Lo;0;L;;;;;N;;;;;
+090B;DEVANAGARI LETTER VOCALIC R;Lo;0;L;;;;;N;;;;;
+090C;DEVANAGARI LETTER VOCALIC L;Lo;0;L;;;;;N;;;;;
+090D;DEVANAGARI LETTER CANDRA E;Lo;0;L;;;;;N;;;;;
+090E;DEVANAGARI LETTER SHORT E;Lo;0;L;;;;;N;;;;;
+090F;DEVANAGARI LETTER E;Lo;0;L;;;;;N;;;;;
+0910;DEVANAGARI LETTER AI;Lo;0;L;;;;;N;;;;;
+0911;DEVANAGARI LETTER CANDRA O;Lo;0;L;;;;;N;;;;;
+0912;DEVANAGARI LETTER SHORT O;Lo;0;L;;;;;N;;;;;
+0913;DEVANAGARI LETTER O;Lo;0;L;;;;;N;;;;;
+0914;DEVANAGARI LETTER AU;Lo;0;L;;;;;N;;;;;
+0915;DEVANAGARI LETTER KA;Lo;0;L;;;;;N;;;;;
+0916;DEVANAGARI LETTER KHA;Lo;0;L;;;;;N;;;;;
+0917;DEVANAGARI LETTER GA;Lo;0;L;;;;;N;;;;;
+0918;DEVANAGARI LETTER GHA;Lo;0;L;;;;;N;;;;;
+0919;DEVANAGARI LETTER NGA;Lo;0;L;;;;;N;;;;;
+091A;DEVANAGARI LETTER CA;Lo;0;L;;;;;N;;;;;
+091B;DEVANAGARI LETTER CHA;Lo;0;L;;;;;N;;;;;
+091C;DEVANAGARI LETTER JA;Lo;0;L;;;;;N;;;;;
+091D;DEVANAGARI LETTER JHA;Lo;0;L;;;;;N;;;;;
+091E;DEVANAGARI LETTER NYA;Lo;0;L;;;;;N;;;;;
+091F;DEVANAGARI LETTER TTA;Lo;0;L;;;;;N;;;;;
+0920;DEVANAGARI LETTER TTHA;Lo;0;L;;;;;N;;;;;
+0921;DEVANAGARI LETTER DDA;Lo;0;L;;;;;N;;;;;
+0922;DEVANAGARI LETTER DDHA;Lo;0;L;;;;;N;;;;;
+0923;DEVANAGARI LETTER NNA;Lo;0;L;;;;;N;;;;;
+0924;DEVANAGARI LETTER TA;Lo;0;L;;;;;N;;;;;
+0925;DEVANAGARI LETTER THA;Lo;0;L;;;;;N;;;;;
+0926;DEVANAGARI LETTER DA;Lo;0;L;;;;;N;;;;;
+0927;DEVANAGARI LETTER DHA;Lo;0;L;;;;;N;;;;;
+0928;DEVANAGARI LETTER NA;Lo;0;L;;;;;N;;;;;
+0929;DEVANAGARI LETTER NNNA;Lo;0;L;0928 093C;;;;N;;;;;
+092A;DEVANAGARI LETTER PA;Lo;0;L;;;;;N;;;;;
+092B;DEVANAGARI LETTER PHA;Lo;0;L;;;;;N;;;;;
+092C;DEVANAGARI LETTER BA;Lo;0;L;;;;;N;;;;;
+092D;DEVANAGARI LETTER BHA;Lo;0;L;;;;;N;;;;;
+092E;DEVANAGARI LETTER MA;Lo;0;L;;;;;N;;;;;
+092F;DEVANAGARI LETTER YA;Lo;0;L;;;;;N;;;;;
+0930;DEVANAGARI LETTER RA;Lo;0;L;;;;;N;;;;;
+0931;DEVANAGARI LETTER RRA;Lo;0;L;0930 093C;;;;N;;;;;
+0932;DEVANAGARI LETTER LA;Lo;0;L;;;;;N;;;;;
+0933;DEVANAGARI LETTER LLA;Lo;0;L;;;;;N;;;;;
+0934;DEVANAGARI LETTER LLLA;Lo;0;L;0933 093C;;;;N;;;;;
+0935;DEVANAGARI LETTER VA;Lo;0;L;;;;;N;;;;;
+0936;DEVANAGARI LETTER SHA;Lo;0;L;;;;;N;;;;;
+0937;DEVANAGARI LETTER SSA;Lo;0;L;;;;;N;;;;;
+0938;DEVANAGARI LETTER SA;Lo;0;L;;;;;N;;;;;
+0939;DEVANAGARI LETTER HA;Lo;0;L;;;;;N;;;;;
+093C;DEVANAGARI SIGN NUKTA;Mn;7;NSM;;;;;N;;;;;
+093D;DEVANAGARI SIGN AVAGRAHA;Lo;0;L;;;;;N;;;;;
+093E;DEVANAGARI VOWEL SIGN AA;Mc;0;L;;;;;N;;;;;
+093F;DEVANAGARI VOWEL SIGN I;Mc;0;L;;;;;N;;;;;
+0940;DEVANAGARI VOWEL SIGN II;Mc;0;L;;;;;N;;;;;
+0941;DEVANAGARI VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;;
+0942;DEVANAGARI VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;;
+0943;DEVANAGARI VOWEL SIGN VOCALIC R;Mn;0;NSM;;;;;N;;;;;
+0944;DEVANAGARI VOWEL SIGN VOCALIC RR;Mn;0;NSM;;;;;N;;;;;
+0945;DEVANAGARI VOWEL SIGN CANDRA E;Mn;0;NSM;;;;;N;;;;;
+0946;DEVANAGARI VOWEL SIGN SHORT E;Mn;0;NSM;;;;;N;;;;;
+0947;DEVANAGARI VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;;
+0948;DEVANAGARI VOWEL SIGN AI;Mn;0;NSM;;;;;N;;;;;
+0949;DEVANAGARI VOWEL SIGN CANDRA O;Mc;0;L;;;;;N;;;;;
+094A;DEVANAGARI VOWEL SIGN SHORT O;Mc;0;L;;;;;N;;;;;
+094B;DEVANAGARI VOWEL SIGN O;Mc;0;L;;;;;N;;;;;
+094C;DEVANAGARI VOWEL SIGN AU;Mc;0;L;;;;;N;;;;;
+094D;DEVANAGARI SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;;
+0950;DEVANAGARI OM;Lo;0;L;;;;;N;;;;;
+0951;DEVANAGARI STRESS SIGN UDATTA;Mn;230;NSM;;;;;N;;;;;
+0952;DEVANAGARI STRESS SIGN ANUDATTA;Mn;220;NSM;;;;;N;;;;;
+0953;DEVANAGARI GRAVE ACCENT;Mn;230;NSM;;;;;N;;;;;
+0954;DEVANAGARI ACUTE ACCENT;Mn;230;NSM;;;;;N;;;;;
+0958;DEVANAGARI LETTER QA;Lo;0;L;0915 093C;;;;N;;;;;
+0959;DEVANAGARI LETTER KHHA;Lo;0;L;0916 093C;;;;N;;;;;
+095A;DEVANAGARI LETTER GHHA;Lo;0;L;0917 093C;;;;N;;;;;
+095B;DEVANAGARI LETTER ZA;Lo;0;L;091C 093C;;;;N;;;;;
+095C;DEVANAGARI LETTER DDDHA;Lo;0;L;0921 093C;;;;N;;;;;
+095D;DEVANAGARI LETTER RHA;Lo;0;L;0922 093C;;;;N;;;;;
+095E;DEVANAGARI LETTER FA;Lo;0;L;092B 093C;;;;N;;;;;
+095F;DEVANAGARI LETTER YYA;Lo;0;L;092F 093C;;;;N;;;;;
+0960;DEVANAGARI LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;;
+0961;DEVANAGARI LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;;
+0962;DEVANAGARI VOWEL SIGN VOCALIC L;Mn;0;NSM;;;;;N;;;;;
+0963;DEVANAGARI VOWEL SIGN VOCALIC LL;Mn;0;NSM;;;;;N;;;;;
+0964;DEVANAGARI DANDA;Po;0;L;;;;;N;;;;;
+0965;DEVANAGARI DOUBLE DANDA;Po;0;L;;;;;N;;;;;
+0966;DEVANAGARI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+0967;DEVANAGARI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+0968;DEVANAGARI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+0969;DEVANAGARI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+096A;DEVANAGARI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+096B;DEVANAGARI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+096C;DEVANAGARI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+096D;DEVANAGARI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+096E;DEVANAGARI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+096F;DEVANAGARI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+0970;DEVANAGARI ABBREVIATION SIGN;Po;0;L;;;;;N;;;;;
+0981;BENGALI SIGN CANDRABINDU;Mn;0;NSM;;;;;N;;;;;
+0982;BENGALI SIGN ANUSVARA;Mc;0;L;;;;;N;;;;;
+0983;BENGALI SIGN VISARGA;Mc;0;L;;;;;N;;;;;
+0985;BENGALI LETTER A;Lo;0;L;;;;;N;;;;;
+0986;BENGALI LETTER AA;Lo;0;L;;;;;N;;;;;
+0987;BENGALI LETTER I;Lo;0;L;;;;;N;;;;;
+0988;BENGALI LETTER II;Lo;0;L;;;;;N;;;;;
+0989;BENGALI LETTER U;Lo;0;L;;;;;N;;;;;
+098A;BENGALI LETTER UU;Lo;0;L;;;;;N;;;;;
+098B;BENGALI LETTER VOCALIC R;Lo;0;L;;;;;N;;;;;
+098C;BENGALI LETTER VOCALIC L;Lo;0;L;;;;;N;;;;;
+098F;BENGALI LETTER E;Lo;0;L;;;;;N;;;;;
+0990;BENGALI LETTER AI;Lo;0;L;;;;;N;;;;;
+0993;BENGALI LETTER O;Lo;0;L;;;;;N;;;;;
+0994;BENGALI LETTER AU;Lo;0;L;;;;;N;;;;;
+0995;BENGALI LETTER KA;Lo;0;L;;;;;N;;;;;
+0996;BENGALI LETTER KHA;Lo;0;L;;;;;N;;;;;
+0997;BENGALI LETTER GA;Lo;0;L;;;;;N;;;;;
+0998;BENGALI LETTER GHA;Lo;0;L;;;;;N;;;;;
+0999;BENGALI LETTER NGA;Lo;0;L;;;;;N;;;;;
+099A;BENGALI LETTER CA;Lo;0;L;;;;;N;;;;;
+099B;BENGALI LETTER CHA;Lo;0;L;;;;;N;;;;;
+099C;BENGALI LETTER JA;Lo;0;L;;;;;N;;;;;
+099D;BENGALI LETTER JHA;Lo;0;L;;;;;N;;;;;
+099E;BENGALI LETTER NYA;Lo;0;L;;;;;N;;;;;
+099F;BENGALI LETTER TTA;Lo;0;L;;;;;N;;;;;
+09A0;BENGALI LETTER TTHA;Lo;0;L;;;;;N;;;;;
+09A1;BENGALI LETTER DDA;Lo;0;L;;;;;N;;;;;
+09A2;BENGALI LETTER DDHA;Lo;0;L;;;;;N;;;;;
+09A3;BENGALI LETTER NNA;Lo;0;L;;;;;N;;;;;
+09A4;BENGALI LETTER TA;Lo;0;L;;;;;N;;;;;
+09A5;BENGALI LETTER THA;Lo;0;L;;;;;N;;;;;
+09A6;BENGALI LETTER DA;Lo;0;L;;;;;N;;;;;
+09A7;BENGALI LETTER DHA;Lo;0;L;;;;;N;;;;;
+09A8;BENGALI LETTER NA;Lo;0;L;;;;;N;;;;;
+09AA;BENGALI LETTER PA;Lo;0;L;;;;;N;;;;;
+09AB;BENGALI LETTER PHA;Lo;0;L;;;;;N;;;;;
+09AC;BENGALI LETTER BA;Lo;0;L;;;;;N;;;;;
+09AD;BENGALI LETTER BHA;Lo;0;L;;;;;N;;;;;
+09AE;BENGALI LETTER MA;Lo;0;L;;;;;N;;;;;
+09AF;BENGALI LETTER YA;Lo;0;L;;;;;N;;;;;
+09B0;BENGALI LETTER RA;Lo;0;L;;;;;N;;;;;
+09B2;BENGALI LETTER LA;Lo;0;L;;;;;N;;;;;
+09B6;BENGALI LETTER SHA;Lo;0;L;;;;;N;;;;;
+09B7;BENGALI LETTER SSA;Lo;0;L;;;;;N;;;;;
+09B8;BENGALI LETTER SA;Lo;0;L;;;;;N;;;;;
+09B9;BENGALI LETTER HA;Lo;0;L;;;;;N;;;;;
+09BC;BENGALI SIGN NUKTA;Mn;7;NSM;;;;;N;;;;;
+09BD;BENGALI SIGN AVAGRAHA;Lo;0;L;;;;;N;;;;;
+09BE;BENGALI VOWEL SIGN AA;Mc;0;L;;;;;N;;;;;
+09BF;BENGALI VOWEL SIGN I;Mc;0;L;;;;;N;;;;;
+09C0;BENGALI VOWEL SIGN II;Mc;0;L;;;;;N;;;;;
+09C1;BENGALI VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;;
+09C2;BENGALI VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;;
+09C3;BENGALI VOWEL SIGN VOCALIC R;Mn;0;NSM;;;;;N;;;;;
+09C4;BENGALI VOWEL SIGN VOCALIC RR;Mn;0;NSM;;;;;N;;;;;
+09C7;BENGALI VOWEL SIGN E;Mc;0;L;;;;;N;;;;;
+09C8;BENGALI VOWEL SIGN AI;Mc;0;L;;;;;N;;;;;
+09CB;BENGALI VOWEL SIGN O;Mc;0;L;09C7 09BE;;;;N;;;;;
+09CC;BENGALI VOWEL SIGN AU;Mc;0;L;09C7 09D7;;;;N;;;;;
+09CD;BENGALI SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;;
+09D7;BENGALI AU LENGTH MARK;Mc;0;L;;;;;N;;;;;
+09DC;BENGALI LETTER RRA;Lo;0;L;09A1 09BC;;;;N;;;;;
+09DD;BENGALI LETTER RHA;Lo;0;L;09A2 09BC;;;;N;;;;;
+09DF;BENGALI LETTER YYA;Lo;0;L;09AF 09BC;;;;N;;;;;
+09E0;BENGALI LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;;
+09E1;BENGALI LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;;
+09E2;BENGALI VOWEL SIGN VOCALIC L;Mn;0;NSM;;;;;N;;;;;
+09E3;BENGALI VOWEL SIGN VOCALIC LL;Mn;0;NSM;;;;;N;;;;;
+09E6;BENGALI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+09E7;BENGALI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+09E8;BENGALI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+09E9;BENGALI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+09EA;BENGALI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+09EB;BENGALI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+09EC;BENGALI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+09ED;BENGALI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+09EE;BENGALI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+09EF;BENGALI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+09F0;BENGALI LETTER RA WITH MIDDLE DIAGONAL;Lo;0;L;;;;;N;;Assamese;;;
+09F1;BENGALI LETTER RA WITH LOWER DIAGONAL;Lo;0;L;;;;;N;BENGALI LETTER VA WITH LOWER DIAGONAL;Assamese;;;
+09F2;BENGALI RUPEE MARK;Sc;0;ET;;;;;N;;;;;
+09F3;BENGALI RUPEE SIGN;Sc;0;ET;;;;;N;;;;;
+09F4;BENGALI CURRENCY NUMERATOR ONE;No;0;L;;;;1;N;;;;;
+09F5;BENGALI CURRENCY NUMERATOR TWO;No;0;L;;;;2;N;;;;;
+09F6;BENGALI CURRENCY NUMERATOR THREE;No;0;L;;;;3;N;;;;;
+09F7;BENGALI CURRENCY NUMERATOR FOUR;No;0;L;;;;4;N;;;;;
+09F8;BENGALI CURRENCY NUMERATOR ONE LESS THAN THE DENOMINATOR;No;0;L;;;;;N;;;;;
+09F9;BENGALI CURRENCY DENOMINATOR SIXTEEN;No;0;L;;;;16;N;;;;;
+09FA;BENGALI ISSHAR;So;0;L;;;;;N;;;;;
+0A01;GURMUKHI SIGN ADAK BINDI;Mn;0;NSM;;;;;N;;;;;
+0A02;GURMUKHI SIGN BINDI;Mn;0;NSM;;;;;N;;;;;
+0A03;GURMUKHI SIGN VISARGA;Mc;0;L;;;;;N;;;;;
+0A05;GURMUKHI LETTER A;Lo;0;L;;;;;N;;;;;
+0A06;GURMUKHI LETTER AA;Lo;0;L;;;;;N;;;;;
+0A07;GURMUKHI LETTER I;Lo;0;L;;;;;N;;;;;
+0A08;GURMUKHI LETTER II;Lo;0;L;;;;;N;;;;;
+0A09;GURMUKHI LETTER U;Lo;0;L;;;;;N;;;;;
+0A0A;GURMUKHI LETTER UU;Lo;0;L;;;;;N;;;;;
+0A0F;GURMUKHI LETTER EE;Lo;0;L;;;;;N;;;;;
+0A10;GURMUKHI LETTER AI;Lo;0;L;;;;;N;;;;;
+0A13;GURMUKHI LETTER OO;Lo;0;L;;;;;N;;;;;
+0A14;GURMUKHI LETTER AU;Lo;0;L;;;;;N;;;;;
+0A15;GURMUKHI LETTER KA;Lo;0;L;;;;;N;;;;;
+0A16;GURMUKHI LETTER KHA;Lo;0;L;;;;;N;;;;;
+0A17;GURMUKHI LETTER GA;Lo;0;L;;;;;N;;;;;
+0A18;GURMUKHI LETTER GHA;Lo;0;L;;;;;N;;;;;
+0A19;GURMUKHI LETTER NGA;Lo;0;L;;;;;N;;;;;
+0A1A;GURMUKHI LETTER CA;Lo;0;L;;;;;N;;;;;
+0A1B;GURMUKHI LETTER CHA;Lo;0;L;;;;;N;;;;;
+0A1C;GURMUKHI LETTER JA;Lo;0;L;;;;;N;;;;;
+0A1D;GURMUKHI LETTER JHA;Lo;0;L;;;;;N;;;;;
+0A1E;GURMUKHI LETTER NYA;Lo;0;L;;;;;N;;;;;
+0A1F;GURMUKHI LETTER TTA;Lo;0;L;;;;;N;;;;;
+0A20;GURMUKHI LETTER TTHA;Lo;0;L;;;;;N;;;;;
+0A21;GURMUKHI LETTER DDA;Lo;0;L;;;;;N;;;;;
+0A22;GURMUKHI LETTER DDHA;Lo;0;L;;;;;N;;;;;
+0A23;GURMUKHI LETTER NNA;Lo;0;L;;;;;N;;;;;
+0A24;GURMUKHI LETTER TA;Lo;0;L;;;;;N;;;;;
+0A25;GURMUKHI LETTER THA;Lo;0;L;;;;;N;;;;;
+0A26;GURMUKHI LETTER DA;Lo;0;L;;;;;N;;;;;
+0A27;GURMUKHI LETTER DHA;Lo;0;L;;;;;N;;;;;
+0A28;GURMUKHI LETTER NA;Lo;0;L;;;;;N;;;;;
+0A2A;GURMUKHI LETTER PA;Lo;0;L;;;;;N;;;;;
+0A2B;GURMUKHI LETTER PHA;Lo;0;L;;;;;N;;;;;
+0A2C;GURMUKHI LETTER BA;Lo;0;L;;;;;N;;;;;
+0A2D;GURMUKHI LETTER BHA;Lo;0;L;;;;;N;;;;;
+0A2E;GURMUKHI LETTER MA;Lo;0;L;;;;;N;;;;;
+0A2F;GURMUKHI LETTER YA;Lo;0;L;;;;;N;;;;;
+0A30;GURMUKHI LETTER RA;Lo;0;L;;;;;N;;;;;
+0A32;GURMUKHI LETTER LA;Lo;0;L;;;;;N;;;;;
+0A33;GURMUKHI LETTER LLA;Lo;0;L;0A32 0A3C;;;;N;;;;;
+0A35;GURMUKHI LETTER VA;Lo;0;L;;;;;N;;;;;
+0A36;GURMUKHI LETTER SHA;Lo;0;L;0A38 0A3C;;;;N;;;;;
+0A38;GURMUKHI LETTER SA;Lo;0;L;;;;;N;;;;;
+0A39;GURMUKHI LETTER HA;Lo;0;L;;;;;N;;;;;
+0A3C;GURMUKHI SIGN NUKTA;Mn;7;NSM;;;;;N;;;;;
+0A3E;GURMUKHI VOWEL SIGN AA;Mc;0;L;;;;;N;;;;;
+0A3F;GURMUKHI VOWEL SIGN I;Mc;0;L;;;;;N;;;;;
+0A40;GURMUKHI VOWEL SIGN II;Mc;0;L;;;;;N;;;;;
+0A41;GURMUKHI VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;;
+0A42;GURMUKHI VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;;
+0A47;GURMUKHI VOWEL SIGN EE;Mn;0;NSM;;;;;N;;;;;
+0A48;GURMUKHI VOWEL SIGN AI;Mn;0;NSM;;;;;N;;;;;
+0A4B;GURMUKHI VOWEL SIGN OO;Mn;0;NSM;;;;;N;;;;;
+0A4C;GURMUKHI VOWEL SIGN AU;Mn;0;NSM;;;;;N;;;;;
+0A4D;GURMUKHI SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;;
+0A59;GURMUKHI LETTER KHHA;Lo;0;L;0A16 0A3C;;;;N;;;;;
+0A5A;GURMUKHI LETTER GHHA;Lo;0;L;0A17 0A3C;;;;N;;;;;
+0A5B;GURMUKHI LETTER ZA;Lo;0;L;0A1C 0A3C;;;;N;;;;;
+0A5C;GURMUKHI LETTER RRA;Lo;0;L;;;;;N;;;;;
+0A5E;GURMUKHI LETTER FA;Lo;0;L;0A2B 0A3C;;;;N;;;;;
+0A66;GURMUKHI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+0A67;GURMUKHI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+0A68;GURMUKHI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+0A69;GURMUKHI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+0A6A;GURMUKHI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+0A6B;GURMUKHI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+0A6C;GURMUKHI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+0A6D;GURMUKHI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+0A6E;GURMUKHI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+0A6F;GURMUKHI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+0A70;GURMUKHI TIPPI;Mn;0;NSM;;;;;N;;;;;
+0A71;GURMUKHI ADDAK;Mn;0;NSM;;;;;N;;;;;
+0A72;GURMUKHI IRI;Lo;0;L;;;;;N;;;;;
+0A73;GURMUKHI URA;Lo;0;L;;;;;N;;;;;
+0A74;GURMUKHI EK ONKAR;Lo;0;L;;;;;N;;;;;
+0A81;GUJARATI SIGN CANDRABINDU;Mn;0;NSM;;;;;N;;;;;
+0A82;GUJARATI SIGN ANUSVARA;Mn;0;NSM;;;;;N;;;;;
+0A83;GUJARATI SIGN VISARGA;Mc;0;L;;;;;N;;;;;
+0A85;GUJARATI LETTER A;Lo;0;L;;;;;N;;;;;
+0A86;GUJARATI LETTER AA;Lo;0;L;;;;;N;;;;;
+0A87;GUJARATI LETTER I;Lo;0;L;;;;;N;;;;;
+0A88;GUJARATI LETTER II;Lo;0;L;;;;;N;;;;;
+0A89;GUJARATI LETTER U;Lo;0;L;;;;;N;;;;;
+0A8A;GUJARATI LETTER UU;Lo;0;L;;;;;N;;;;;
+0A8B;GUJARATI LETTER VOCALIC R;Lo;0;L;;;;;N;;;;;
+0A8C;GUJARATI LETTER VOCALIC L;Lo;0;L;;;;;N;;;;;
+0A8D;GUJARATI VOWEL CANDRA E;Lo;0;L;;;;;N;;;;;
+0A8F;GUJARATI LETTER E;Lo;0;L;;;;;N;;;;;
+0A90;GUJARATI LETTER AI;Lo;0;L;;;;;N;;;;;
+0A91;GUJARATI VOWEL CANDRA O;Lo;0;L;;;;;N;;;;;
+0A93;GUJARATI LETTER O;Lo;0;L;;;;;N;;;;;
+0A94;GUJARATI LETTER AU;Lo;0;L;;;;;N;;;;;
+0A95;GUJARATI LETTER KA;Lo;0;L;;;;;N;;;;;
+0A96;GUJARATI LETTER KHA;Lo;0;L;;;;;N;;;;;
+0A97;GUJARATI LETTER GA;Lo;0;L;;;;;N;;;;;
+0A98;GUJARATI LETTER GHA;Lo;0;L;;;;;N;;;;;
+0A99;GUJARATI LETTER NGA;Lo;0;L;;;;;N;;;;;
+0A9A;GUJARATI LETTER CA;Lo;0;L;;;;;N;;;;;
+0A9B;GUJARATI LETTER CHA;Lo;0;L;;;;;N;;;;;
+0A9C;GUJARATI LETTER JA;Lo;0;L;;;;;N;;;;;
+0A9D;GUJARATI LETTER JHA;Lo;0;L;;;;;N;;;;;
+0A9E;GUJARATI LETTER NYA;Lo;0;L;;;;;N;;;;;
+0A9F;GUJARATI LETTER TTA;Lo;0;L;;;;;N;;;;;
+0AA0;GUJARATI LETTER TTHA;Lo;0;L;;;;;N;;;;;
+0AA1;GUJARATI LETTER DDA;Lo;0;L;;;;;N;;;;;
+0AA2;GUJARATI LETTER DDHA;Lo;0;L;;;;;N;;;;;
+0AA3;GUJARATI LETTER NNA;Lo;0;L;;;;;N;;;;;
+0AA4;GUJARATI LETTER TA;Lo;0;L;;;;;N;;;;;
+0AA5;GUJARATI LETTER THA;Lo;0;L;;;;;N;;;;;
+0AA6;GUJARATI LETTER DA;Lo;0;L;;;;;N;;;;;
+0AA7;GUJARATI LETTER DHA;Lo;0;L;;;;;N;;;;;
+0AA8;GUJARATI LETTER NA;Lo;0;L;;;;;N;;;;;
+0AAA;GUJARATI LETTER PA;Lo;0;L;;;;;N;;;;;
+0AAB;GUJARATI LETTER PHA;Lo;0;L;;;;;N;;;;;
+0AAC;GUJARATI LETTER BA;Lo;0;L;;;;;N;;;;;
+0AAD;GUJARATI LETTER BHA;Lo;0;L;;;;;N;;;;;
+0AAE;GUJARATI LETTER MA;Lo;0;L;;;;;N;;;;;
+0AAF;GUJARATI LETTER YA;Lo;0;L;;;;;N;;;;;
+0AB0;GUJARATI LETTER RA;Lo;0;L;;;;;N;;;;;
+0AB2;GUJARATI LETTER LA;Lo;0;L;;;;;N;;;;;
+0AB3;GUJARATI LETTER LLA;Lo;0;L;;;;;N;;;;;
+0AB5;GUJARATI LETTER VA;Lo;0;L;;;;;N;;;;;
+0AB6;GUJARATI LETTER SHA;Lo;0;L;;;;;N;;;;;
+0AB7;GUJARATI LETTER SSA;Lo;0;L;;;;;N;;;;;
+0AB8;GUJARATI LETTER SA;Lo;0;L;;;;;N;;;;;
+0AB9;GUJARATI LETTER HA;Lo;0;L;;;;;N;;;;;
+0ABC;GUJARATI SIGN NUKTA;Mn;7;NSM;;;;;N;;;;;
+0ABD;GUJARATI SIGN AVAGRAHA;Lo;0;L;;;;;N;;;;;
+0ABE;GUJARATI VOWEL SIGN AA;Mc;0;L;;;;;N;;;;;
+0ABF;GUJARATI VOWEL SIGN I;Mc;0;L;;;;;N;;;;;
+0AC0;GUJARATI VOWEL SIGN II;Mc;0;L;;;;;N;;;;;
+0AC1;GUJARATI VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;;
+0AC2;GUJARATI VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;;
+0AC3;GUJARATI VOWEL SIGN VOCALIC R;Mn;0;NSM;;;;;N;;;;;
+0AC4;GUJARATI VOWEL SIGN VOCALIC RR;Mn;0;NSM;;;;;N;;;;;
+0AC5;GUJARATI VOWEL SIGN CANDRA E;Mn;0;NSM;;;;;N;;;;;
+0AC7;GUJARATI VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;;
+0AC8;GUJARATI VOWEL SIGN AI;Mn;0;NSM;;;;;N;;;;;
+0AC9;GUJARATI VOWEL SIGN CANDRA O;Mc;0;L;;;;;N;;;;;
+0ACB;GUJARATI VOWEL SIGN O;Mc;0;L;;;;;N;;;;;
+0ACC;GUJARATI VOWEL SIGN AU;Mc;0;L;;;;;N;;;;;
+0ACD;GUJARATI SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;;
+0AD0;GUJARATI OM;Lo;0;L;;;;;N;;;;;
+0AE0;GUJARATI LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;;
+0AE1;GUJARATI LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;;
+0AE2;GUJARATI VOWEL SIGN VOCALIC L;Mn;0;NSM;;;;;N;;;;;
+0AE3;GUJARATI VOWEL SIGN VOCALIC LL;Mn;0;NSM;;;;;N;;;;;
+0AE6;GUJARATI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+0AE7;GUJARATI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+0AE8;GUJARATI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+0AE9;GUJARATI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+0AEA;GUJARATI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+0AEB;GUJARATI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+0AEC;GUJARATI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+0AED;GUJARATI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+0AEE;GUJARATI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+0AEF;GUJARATI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+0AF1;GUJARATI RUPEE SIGN;Sc;0;ET;;;;;N;;;;;
+0B01;ORIYA SIGN CANDRABINDU;Mn;0;NSM;;;;;N;;;;;
+0B02;ORIYA SIGN ANUSVARA;Mc;0;L;;;;;N;;;;;
+0B03;ORIYA SIGN VISARGA;Mc;0;L;;;;;N;;;;;
+0B05;ORIYA LETTER A;Lo;0;L;;;;;N;;;;;
+0B06;ORIYA LETTER AA;Lo;0;L;;;;;N;;;;;
+0B07;ORIYA LETTER I;Lo;0;L;;;;;N;;;;;
+0B08;ORIYA LETTER II;Lo;0;L;;;;;N;;;;;
+0B09;ORIYA LETTER U;Lo;0;L;;;;;N;;;;;
+0B0A;ORIYA LETTER UU;Lo;0;L;;;;;N;;;;;
+0B0B;ORIYA LETTER VOCALIC R;Lo;0;L;;;;;N;;;;;
+0B0C;ORIYA LETTER VOCALIC L;Lo;0;L;;;;;N;;;;;
+0B0F;ORIYA LETTER E;Lo;0;L;;;;;N;;;;;
+0B10;ORIYA LETTER AI;Lo;0;L;;;;;N;;;;;
+0B13;ORIYA LETTER O;Lo;0;L;;;;;N;;;;;
+0B14;ORIYA LETTER AU;Lo;0;L;;;;;N;;;;;
+0B15;ORIYA LETTER KA;Lo;0;L;;;;;N;;;;;
+0B16;ORIYA LETTER KHA;Lo;0;L;;;;;N;;;;;
+0B17;ORIYA LETTER GA;Lo;0;L;;;;;N;;;;;
+0B18;ORIYA LETTER GHA;Lo;0;L;;;;;N;;;;;
+0B19;ORIYA LETTER NGA;Lo;0;L;;;;;N;;;;;
+0B1A;ORIYA LETTER CA;Lo;0;L;;;;;N;;;;;
+0B1B;ORIYA LETTER CHA;Lo;0;L;;;;;N;;;;;
+0B1C;ORIYA LETTER JA;Lo;0;L;;;;;N;;;;;
+0B1D;ORIYA LETTER JHA;Lo;0;L;;;;;N;;;;;
+0B1E;ORIYA LETTER NYA;Lo;0;L;;;;;N;;;;;
+0B1F;ORIYA LETTER TTA;Lo;0;L;;;;;N;;;;;
+0B20;ORIYA LETTER TTHA;Lo;0;L;;;;;N;;;;;
+0B21;ORIYA LETTER DDA;Lo;0;L;;;;;N;;;;;
+0B22;ORIYA LETTER DDHA;Lo;0;L;;;;;N;;;;;
+0B23;ORIYA LETTER NNA;Lo;0;L;;;;;N;;;;;
+0B24;ORIYA LETTER TA;Lo;0;L;;;;;N;;;;;
+0B25;ORIYA LETTER THA;Lo;0;L;;;;;N;;;;;
+0B26;ORIYA LETTER DA;Lo;0;L;;;;;N;;;;;
+0B27;ORIYA LETTER DHA;Lo;0;L;;;;;N;;;;;
+0B28;ORIYA LETTER NA;Lo;0;L;;;;;N;;;;;
+0B2A;ORIYA LETTER PA;Lo;0;L;;;;;N;;;;;
+0B2B;ORIYA LETTER PHA;Lo;0;L;;;;;N;;;;;
+0B2C;ORIYA LETTER BA;Lo;0;L;;;;;N;;;;;
+0B2D;ORIYA LETTER BHA;Lo;0;L;;;;;N;;;;;
+0B2E;ORIYA LETTER MA;Lo;0;L;;;;;N;;;;;
+0B2F;ORIYA LETTER YA;Lo;0;L;;;;;N;;;;;
+0B30;ORIYA LETTER RA;Lo;0;L;;;;;N;;;;;
+0B32;ORIYA LETTER LA;Lo;0;L;;;;;N;;;;;
+0B33;ORIYA LETTER LLA;Lo;0;L;;;;;N;;;;;
+0B35;ORIYA LETTER VA;Lo;0;L;;;;;N;;;;;
+0B36;ORIYA LETTER SHA;Lo;0;L;;;;;N;;;;;
+0B37;ORIYA LETTER SSA;Lo;0;L;;;;;N;;;;;
+0B38;ORIYA LETTER SA;Lo;0;L;;;;;N;;;;;
+0B39;ORIYA LETTER HA;Lo;0;L;;;;;N;;;;;
+0B3C;ORIYA SIGN NUKTA;Mn;7;NSM;;;;;N;;;;;
+0B3D;ORIYA SIGN AVAGRAHA;Lo;0;L;;;;;N;;;;;
+0B3E;ORIYA VOWEL SIGN AA;Mc;0;L;;;;;N;;;;;
+0B3F;ORIYA VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;;
+0B40;ORIYA VOWEL SIGN II;Mc;0;L;;;;;N;;;;;
+0B41;ORIYA VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;;
+0B42;ORIYA VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;;
+0B43;ORIYA VOWEL SIGN VOCALIC R;Mn;0;NSM;;;;;N;;;;;
+0B47;ORIYA VOWEL SIGN E;Mc;0;L;;;;;N;;;;;
+0B48;ORIYA VOWEL SIGN AI;Mc;0;L;0B47 0B56;;;;N;;;;;
+0B4B;ORIYA VOWEL SIGN O;Mc;0;L;0B47 0B3E;;;;N;;;;;
+0B4C;ORIYA VOWEL SIGN AU;Mc;0;L;0B47 0B57;;;;N;;;;;
+0B4D;ORIYA SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;;
+0B56;ORIYA AI LENGTH MARK;Mn;0;NSM;;;;;N;;;;;
+0B57;ORIYA AU LENGTH MARK;Mc;0;L;;;;;N;;;;;
+0B5C;ORIYA LETTER RRA;Lo;0;L;0B21 0B3C;;;;N;;;;;
+0B5D;ORIYA LETTER RHA;Lo;0;L;0B22 0B3C;;;;N;;;;;
+0B5F;ORIYA LETTER YYA;Lo;0;L;;;;;N;;;;;
+0B60;ORIYA LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;;
+0B61;ORIYA LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;;
+0B66;ORIYA DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+0B67;ORIYA DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+0B68;ORIYA DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+0B69;ORIYA DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+0B6A;ORIYA DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+0B6B;ORIYA DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+0B6C;ORIYA DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+0B6D;ORIYA DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+0B6E;ORIYA DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+0B6F;ORIYA DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+0B70;ORIYA ISSHAR;So;0;L;;;;;N;;;;;
+0B71;ORIYA LETTER WA;Lo;0;L;;;;;N;;;;;
+0B82;TAMIL SIGN ANUSVARA;Mn;0;NSM;;;;;N;;;;;
+0B83;TAMIL SIGN VISARGA;Lo;0;L;;;;;N;;;;;
+0B85;TAMIL LETTER A;Lo;0;L;;;;;N;;;;;
+0B86;TAMIL LETTER AA;Lo;0;L;;;;;N;;;;;
+0B87;TAMIL LETTER I;Lo;0;L;;;;;N;;;;;
+0B88;TAMIL LETTER II;Lo;0;L;;;;;N;;;;;
+0B89;TAMIL LETTER U;Lo;0;L;;;;;N;;;;;
+0B8A;TAMIL LETTER UU;Lo;0;L;;;;;N;;;;;
+0B8E;TAMIL LETTER E;Lo;0;L;;;;;N;;;;;
+0B8F;TAMIL LETTER EE;Lo;0;L;;;;;N;;;;;
+0B90;TAMIL LETTER AI;Lo;0;L;;;;;N;;;;;
+0B92;TAMIL LETTER O;Lo;0;L;;;;;N;;;;;
+0B93;TAMIL LETTER OO;Lo;0;L;;;;;N;;;;;
+0B94;TAMIL LETTER AU;Lo;0;L;0B92 0BD7;;;;N;;;;;
+0B95;TAMIL LETTER KA;Lo;0;L;;;;;N;;;;;
+0B99;TAMIL LETTER NGA;Lo;0;L;;;;;N;;;;;
+0B9A;TAMIL LETTER CA;Lo;0;L;;;;;N;;;;;
+0B9C;TAMIL LETTER JA;Lo;0;L;;;;;N;;;;;
+0B9E;TAMIL LETTER NYA;Lo;0;L;;;;;N;;;;;
+0B9F;TAMIL LETTER TTA;Lo;0;L;;;;;N;;;;;
+0BA3;TAMIL LETTER NNA;Lo;0;L;;;;;N;;;;;
+0BA4;TAMIL LETTER TA;Lo;0;L;;;;;N;;;;;
+0BA8;TAMIL LETTER NA;Lo;0;L;;;;;N;;;;;
+0BA9;TAMIL LETTER NNNA;Lo;0;L;;;;;N;;;;;
+0BAA;TAMIL LETTER PA;Lo;0;L;;;;;N;;;;;
+0BAE;TAMIL LETTER MA;Lo;0;L;;;;;N;;;;;
+0BAF;TAMIL LETTER YA;Lo;0;L;;;;;N;;;;;
+0BB0;TAMIL LETTER RA;Lo;0;L;;;;;N;;;;;
+0BB1;TAMIL LETTER RRA;Lo;0;L;;;;;N;;;;;
+0BB2;TAMIL LETTER LA;Lo;0;L;;;;;N;;;;;
+0BB3;TAMIL LETTER LLA;Lo;0;L;;;;;N;;;;;
+0BB4;TAMIL LETTER LLLA;Lo;0;L;;;;;N;;;;;
+0BB5;TAMIL LETTER VA;Lo;0;L;;;;;N;;;;;
+0BB7;TAMIL LETTER SSA;Lo;0;L;;;;;N;;;;;
+0BB8;TAMIL LETTER SA;Lo;0;L;;;;;N;;;;;
+0BB9;TAMIL LETTER HA;Lo;0;L;;;;;N;;;;;
+0BBE;TAMIL VOWEL SIGN AA;Mc;0;L;;;;;N;;;;;
+0BBF;TAMIL VOWEL SIGN I;Mc;0;L;;;;;N;;;;;
+0BC0;TAMIL VOWEL SIGN II;Mn;0;NSM;;;;;N;;;;;
+0BC1;TAMIL VOWEL SIGN U;Mc;0;L;;;;;N;;;;;
+0BC2;TAMIL VOWEL SIGN UU;Mc;0;L;;;;;N;;;;;
+0BC6;TAMIL VOWEL SIGN E;Mc;0;L;;;;;N;;;;;
+0BC7;TAMIL VOWEL SIGN EE;Mc;0;L;;;;;N;;;;;
+0BC8;TAMIL VOWEL SIGN AI;Mc;0;L;;;;;N;;;;;
+0BCA;TAMIL VOWEL SIGN O;Mc;0;L;0BC6 0BBE;;;;N;;;;;
+0BCB;TAMIL VOWEL SIGN OO;Mc;0;L;0BC7 0BBE;;;;N;;;;;
+0BCC;TAMIL VOWEL SIGN AU;Mc;0;L;0BC6 0BD7;;;;N;;;;;
+0BCD;TAMIL SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;;
+0BD7;TAMIL AU LENGTH MARK;Mc;0;L;;;;;N;;;;;
+0BE7;TAMIL DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+0BE8;TAMIL DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+0BE9;TAMIL DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+0BEA;TAMIL DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+0BEB;TAMIL DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+0BEC;TAMIL DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+0BED;TAMIL DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+0BEE;TAMIL DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+0BEF;TAMIL DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+0BF0;TAMIL NUMBER TEN;No;0;L;;;;10;N;;;;;
+0BF1;TAMIL NUMBER ONE HUNDRED;No;0;L;;;;100;N;;;;;
+0BF2;TAMIL NUMBER ONE THOUSAND;No;0;L;;;;1000;N;;;;;
+0BF3;TAMIL DAY SIGN;So;0;ON;;;;;N;;Naal;;;
+0BF4;TAMIL MONTH SIGN;So;0;ON;;;;;N;;Maatham;;;
+0BF5;TAMIL YEAR SIGN;So;0;ON;;;;;N;;Varudam;;;
+0BF6;TAMIL DEBIT SIGN;So;0;ON;;;;;N;;Patru;;;
+0BF7;TAMIL CREDIT SIGN;So;0;ON;;;;;N;;Varavu;;;
+0BF8;TAMIL AS ABOVE SIGN;So;0;ON;;;;;N;;Merpadi;;;
+0BF9;TAMIL RUPEE SIGN;Sc;0;ET;;;;;N;;Rupai;;;
+0BFA;TAMIL NUMBER SIGN;So;0;ON;;;;;N;;Enn;;;
+0C01;TELUGU SIGN CANDRABINDU;Mc;0;L;;;;;N;;;;;
+0C02;TELUGU SIGN ANUSVARA;Mc;0;L;;;;;N;;;;;
+0C03;TELUGU SIGN VISARGA;Mc;0;L;;;;;N;;;;;
+0C05;TELUGU LETTER A;Lo;0;L;;;;;N;;;;;
+0C06;TELUGU LETTER AA;Lo;0;L;;;;;N;;;;;
+0C07;TELUGU LETTER I;Lo;0;L;;;;;N;;;;;
+0C08;TELUGU LETTER II;Lo;0;L;;;;;N;;;;;
+0C09;TELUGU LETTER U;Lo;0;L;;;;;N;;;;;
+0C0A;TELUGU LETTER UU;Lo;0;L;;;;;N;;;;;
+0C0B;TELUGU LETTER VOCALIC R;Lo;0;L;;;;;N;;;;;
+0C0C;TELUGU LETTER VOCALIC L;Lo;0;L;;;;;N;;;;;
+0C0E;TELUGU LETTER E;Lo;0;L;;;;;N;;;;;
+0C0F;TELUGU LETTER EE;Lo;0;L;;;;;N;;;;;
+0C10;TELUGU LETTER AI;Lo;0;L;;;;;N;;;;;
+0C12;TELUGU LETTER O;Lo;0;L;;;;;N;;;;;
+0C13;TELUGU LETTER OO;Lo;0;L;;;;;N;;;;;
+0C14;TELUGU LETTER AU;Lo;0;L;;;;;N;;;;;
+0C15;TELUGU LETTER KA;Lo;0;L;;;;;N;;;;;
+0C16;TELUGU LETTER KHA;Lo;0;L;;;;;N;;;;;
+0C17;TELUGU LETTER GA;Lo;0;L;;;;;N;;;;;
+0C18;TELUGU LETTER GHA;Lo;0;L;;;;;N;;;;;
+0C19;TELUGU LETTER NGA;Lo;0;L;;;;;N;;;;;
+0C1A;TELUGU LETTER CA;Lo;0;L;;;;;N;;;;;
+0C1B;TELUGU LETTER CHA;Lo;0;L;;;;;N;;;;;
+0C1C;TELUGU LETTER JA;Lo;0;L;;;;;N;;;;;
+0C1D;TELUGU LETTER JHA;Lo;0;L;;;;;N;;;;;
+0C1E;TELUGU LETTER NYA;Lo;0;L;;;;;N;;;;;
+0C1F;TELUGU LETTER TTA;Lo;0;L;;;;;N;;;;;
+0C20;TELUGU LETTER TTHA;Lo;0;L;;;;;N;;;;;
+0C21;TELUGU LETTER DDA;Lo;0;L;;;;;N;;;;;
+0C22;TELUGU LETTER DDHA;Lo;0;L;;;;;N;;;;;
+0C23;TELUGU LETTER NNA;Lo;0;L;;;;;N;;;;;
+0C24;TELUGU LETTER TA;Lo;0;L;;;;;N;;;;;
+0C25;TELUGU LETTER THA;Lo;0;L;;;;;N;;;;;
+0C26;TELUGU LETTER DA;Lo;0;L;;;;;N;;;;;
+0C27;TELUGU LETTER DHA;Lo;0;L;;;;;N;;;;;
+0C28;TELUGU LETTER NA;Lo;0;L;;;;;N;;;;;
+0C2A;TELUGU LETTER PA;Lo;0;L;;;;;N;;;;;
+0C2B;TELUGU LETTER PHA;Lo;0;L;;;;;N;;;;;
+0C2C;TELUGU LETTER BA;Lo;0;L;;;;;N;;;;;
+0C2D;TELUGU LETTER BHA;Lo;0;L;;;;;N;;;;;
+0C2E;TELUGU LETTER MA;Lo;0;L;;;;;N;;;;;
+0C2F;TELUGU LETTER YA;Lo;0;L;;;;;N;;;;;
+0C30;TELUGU LETTER RA;Lo;0;L;;;;;N;;;;;
+0C31;TELUGU LETTER RRA;Lo;0;L;;;;;N;;;;;
+0C32;TELUGU LETTER LA;Lo;0;L;;;;;N;;;;;
+0C33;TELUGU LETTER LLA;Lo;0;L;;;;;N;;;;;
+0C35;TELUGU LETTER VA;Lo;0;L;;;;;N;;;;;
+0C36;TELUGU LETTER SHA;Lo;0;L;;;;;N;;;;;
+0C37;TELUGU LETTER SSA;Lo;0;L;;;;;N;;;;;
+0C38;TELUGU LETTER SA;Lo;0;L;;;;;N;;;;;
+0C39;TELUGU LETTER HA;Lo;0;L;;;;;N;;;;;
+0C3E;TELUGU VOWEL SIGN AA;Mn;0;NSM;;;;;N;;;;;
+0C3F;TELUGU VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;;
+0C40;TELUGU VOWEL SIGN II;Mn;0;NSM;;;;;N;;;;;
+0C41;TELUGU VOWEL SIGN U;Mc;0;L;;;;;N;;;;;
+0C42;TELUGU VOWEL SIGN UU;Mc;0;L;;;;;N;;;;;
+0C43;TELUGU VOWEL SIGN VOCALIC R;Mc;0;L;;;;;N;;;;;
+0C44;TELUGU VOWEL SIGN VOCALIC RR;Mc;0;L;;;;;N;;;;;
+0C46;TELUGU VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;;
+0C47;TELUGU VOWEL SIGN EE;Mn;0;NSM;;;;;N;;;;;
+0C48;TELUGU VOWEL SIGN AI;Mn;0;NSM;0C46 0C56;;;;N;;;;;
+0C4A;TELUGU VOWEL SIGN O;Mn;0;NSM;;;;;N;;;;;
+0C4B;TELUGU VOWEL SIGN OO;Mn;0;NSM;;;;;N;;;;;
+0C4C;TELUGU VOWEL SIGN AU;Mn;0;NSM;;;;;N;;;;;
+0C4D;TELUGU SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;;
+0C55;TELUGU LENGTH MARK;Mn;84;NSM;;;;;N;;;;;
+0C56;TELUGU AI LENGTH MARK;Mn;91;NSM;;;;;N;;;;;
+0C60;TELUGU LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;;
+0C61;TELUGU LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;;
+0C66;TELUGU DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+0C67;TELUGU DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+0C68;TELUGU DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+0C69;TELUGU DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+0C6A;TELUGU DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+0C6B;TELUGU DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+0C6C;TELUGU DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+0C6D;TELUGU DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+0C6E;TELUGU DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+0C6F;TELUGU DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+0C82;KANNADA SIGN ANUSVARA;Mc;0;L;;;;;N;;;;;
+0C83;KANNADA SIGN VISARGA;Mc;0;L;;;;;N;;;;;
+0C85;KANNADA LETTER A;Lo;0;L;;;;;N;;;;;
+0C86;KANNADA LETTER AA;Lo;0;L;;;;;N;;;;;
+0C87;KANNADA LETTER I;Lo;0;L;;;;;N;;;;;
+0C88;KANNADA LETTER II;Lo;0;L;;;;;N;;;;;
+0C89;KANNADA LETTER U;Lo;0;L;;;;;N;;;;;
+0C8A;KANNADA LETTER UU;Lo;0;L;;;;;N;;;;;
+0C8B;KANNADA LETTER VOCALIC R;Lo;0;L;;;;;N;;;;;
+0C8C;KANNADA LETTER VOCALIC L;Lo;0;L;;;;;N;;;;;
+0C8E;KANNADA LETTER E;Lo;0;L;;;;;N;;;;;
+0C8F;KANNADA LETTER EE;Lo;0;L;;;;;N;;;;;
+0C90;KANNADA LETTER AI;Lo;0;L;;;;;N;;;;;
+0C92;KANNADA LETTER O;Lo;0;L;;;;;N;;;;;
+0C93;KANNADA LETTER OO;Lo;0;L;;;;;N;;;;;
+0C94;KANNADA LETTER AU;Lo;0;L;;;;;N;;;;;
+0C95;KANNADA LETTER KA;Lo;0;L;;;;;N;;;;;
+0C96;KANNADA LETTER KHA;Lo;0;L;;;;;N;;;;;
+0C97;KANNADA LETTER GA;Lo;0;L;;;;;N;;;;;
+0C98;KANNADA LETTER GHA;Lo;0;L;;;;;N;;;;;
+0C99;KANNADA LETTER NGA;Lo;0;L;;;;;N;;;;;
+0C9A;KANNADA LETTER CA;Lo;0;L;;;;;N;;;;;
+0C9B;KANNADA LETTER CHA;Lo;0;L;;;;;N;;;;;
+0C9C;KANNADA LETTER JA;Lo;0;L;;;;;N;;;;;
+0C9D;KANNADA LETTER JHA;Lo;0;L;;;;;N;;;;;
+0C9E;KANNADA LETTER NYA;Lo;0;L;;;;;N;;;;;
+0C9F;KANNADA LETTER TTA;Lo;0;L;;;;;N;;;;;
+0CA0;KANNADA LETTER TTHA;Lo;0;L;;;;;N;;;;;
+0CA1;KANNADA LETTER DDA;Lo;0;L;;;;;N;;;;;
+0CA2;KANNADA LETTER DDHA;Lo;0;L;;;;;N;;;;;
+0CA3;KANNADA LETTER NNA;Lo;0;L;;;;;N;;;;;
+0CA4;KANNADA LETTER TA;Lo;0;L;;;;;N;;;;;
+0CA5;KANNADA LETTER THA;Lo;0;L;;;;;N;;;;;
+0CA6;KANNADA LETTER DA;Lo;0;L;;;;;N;;;;;
+0CA7;KANNADA LETTER DHA;Lo;0;L;;;;;N;;;;;
+0CA8;KANNADA LETTER NA;Lo;0;L;;;;;N;;;;;
+0CAA;KANNADA LETTER PA;Lo;0;L;;;;;N;;;;;
+0CAB;KANNADA LETTER PHA;Lo;0;L;;;;;N;;;;;
+0CAC;KANNADA LETTER BA;Lo;0;L;;;;;N;;;;;
+0CAD;KANNADA LETTER BHA;Lo;0;L;;;;;N;;;;;
+0CAE;KANNADA LETTER MA;Lo;0;L;;;;;N;;;;;
+0CAF;KANNADA LETTER YA;Lo;0;L;;;;;N;;;;;
+0CB0;KANNADA LETTER RA;Lo;0;L;;;;;N;;;;;
+0CB1;KANNADA LETTER RRA;Lo;0;L;;;;;N;;;;;
+0CB2;KANNADA LETTER LA;Lo;0;L;;;;;N;;;;;
+0CB3;KANNADA LETTER LLA;Lo;0;L;;;;;N;;;;;
+0CB5;KANNADA LETTER VA;Lo;0;L;;;;;N;;;;;
+0CB6;KANNADA LETTER SHA;Lo;0;L;;;;;N;;;;;
+0CB7;KANNADA LETTER SSA;Lo;0;L;;;;;N;;;;;
+0CB8;KANNADA LETTER SA;Lo;0;L;;;;;N;;;;;
+0CB9;KANNADA LETTER HA;Lo;0;L;;;;;N;;;;;
+0CBC;KANNADA SIGN NUKTA;Mn;7;NSM;;;;;N;;;;;
+0CBD;KANNADA SIGN AVAGRAHA;Lo;0;L;;;;;N;;;;;
+0CBE;KANNADA VOWEL SIGN AA;Mc;0;L;;;;;N;;;;;
+0CBF;KANNADA VOWEL SIGN I;Mn;0;L;;;;;N;;;;;
+0CC0;KANNADA VOWEL SIGN II;Mc;0;L;0CBF 0CD5;;;;N;;;;;
+0CC1;KANNADA VOWEL SIGN U;Mc;0;L;;;;;N;;;;;
+0CC2;KANNADA VOWEL SIGN UU;Mc;0;L;;;;;N;;;;;
+0CC3;KANNADA VOWEL SIGN VOCALIC R;Mc;0;L;;;;;N;;;;;
+0CC4;KANNADA VOWEL SIGN VOCALIC RR;Mc;0;L;;;;;N;;;;;
+0CC6;KANNADA VOWEL SIGN E;Mn;0;L;;;;;N;;;;;
+0CC7;KANNADA VOWEL SIGN EE;Mc;0;L;0CC6 0CD5;;;;N;;;;;
+0CC8;KANNADA VOWEL SIGN AI;Mc;0;L;0CC6 0CD6;;;;N;;;;;
+0CCA;KANNADA VOWEL SIGN O;Mc;0;L;0CC6 0CC2;;;;N;;;;;
+0CCB;KANNADA VOWEL SIGN OO;Mc;0;L;0CCA 0CD5;;;;N;;;;;
+0CCC;KANNADA VOWEL SIGN AU;Mn;0;NSM;;;;;N;;;;;
+0CCD;KANNADA SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;;
+0CD5;KANNADA LENGTH MARK;Mc;0;L;;;;;N;;;;;
+0CD6;KANNADA AI LENGTH MARK;Mc;0;L;;;;;N;;;;;
+0CDE;KANNADA LETTER FA;Lo;0;L;;;;;N;;;;;
+0CE0;KANNADA LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;;
+0CE1;KANNADA LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;;
+0CE6;KANNADA DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+0CE7;KANNADA DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+0CE8;KANNADA DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+0CE9;KANNADA DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+0CEA;KANNADA DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+0CEB;KANNADA DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+0CEC;KANNADA DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+0CED;KANNADA DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+0CEE;KANNADA DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+0CEF;KANNADA DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+0D02;MALAYALAM SIGN ANUSVARA;Mc;0;L;;;;;N;;;;;
+0D03;MALAYALAM SIGN VISARGA;Mc;0;L;;;;;N;;;;;
+0D05;MALAYALAM LETTER A;Lo;0;L;;;;;N;;;;;
+0D06;MALAYALAM LETTER AA;Lo;0;L;;;;;N;;;;;
+0D07;MALAYALAM LETTER I;Lo;0;L;;;;;N;;;;;
+0D08;MALAYALAM LETTER II;Lo;0;L;;;;;N;;;;;
+0D09;MALAYALAM LETTER U;Lo;0;L;;;;;N;;;;;
+0D0A;MALAYALAM LETTER UU;Lo;0;L;;;;;N;;;;;
+0D0B;MALAYALAM LETTER VOCALIC R;Lo;0;L;;;;;N;;;;;
+0D0C;MALAYALAM LETTER VOCALIC L;Lo;0;L;;;;;N;;;;;
+0D0E;MALAYALAM LETTER E;Lo;0;L;;;;;N;;;;;
+0D0F;MALAYALAM LETTER EE;Lo;0;L;;;;;N;;;;;
+0D10;MALAYALAM LETTER AI;Lo;0;L;;;;;N;;;;;
+0D12;MALAYALAM LETTER O;Lo;0;L;;;;;N;;;;;
+0D13;MALAYALAM LETTER OO;Lo;0;L;;;;;N;;;;;
+0D14;MALAYALAM LETTER AU;Lo;0;L;;;;;N;;;;;
+0D15;MALAYALAM LETTER KA;Lo;0;L;;;;;N;;;;;
+0D16;MALAYALAM LETTER KHA;Lo;0;L;;;;;N;;;;;
+0D17;MALAYALAM LETTER GA;Lo;0;L;;;;;N;;;;;
+0D18;MALAYALAM LETTER GHA;Lo;0;L;;;;;N;;;;;
+0D19;MALAYALAM LETTER NGA;Lo;0;L;;;;;N;;;;;
+0D1A;MALAYALAM LETTER CA;Lo;0;L;;;;;N;;;;;
+0D1B;MALAYALAM LETTER CHA;Lo;0;L;;;;;N;;;;;
+0D1C;MALAYALAM LETTER JA;Lo;0;L;;;;;N;;;;;
+0D1D;MALAYALAM LETTER JHA;Lo;0;L;;;;;N;;;;;
+0D1E;MALAYALAM LETTER NYA;Lo;0;L;;;;;N;;;;;
+0D1F;MALAYALAM LETTER TTA;Lo;0;L;;;;;N;;;;;
+0D20;MALAYALAM LETTER TTHA;Lo;0;L;;;;;N;;;;;
+0D21;MALAYALAM LETTER DDA;Lo;0;L;;;;;N;;;;;
+0D22;MALAYALAM LETTER DDHA;Lo;0;L;;;;;N;;;;;
+0D23;MALAYALAM LETTER NNA;Lo;0;L;;;;;N;;;;;
+0D24;MALAYALAM LETTER TA;Lo;0;L;;;;;N;;;;;
+0D25;MALAYALAM LETTER THA;Lo;0;L;;;;;N;;;;;
+0D26;MALAYALAM LETTER DA;Lo;0;L;;;;;N;;;;;
+0D27;MALAYALAM LETTER DHA;Lo;0;L;;;;;N;;;;;
+0D28;MALAYALAM LETTER NA;Lo;0;L;;;;;N;;;;;
+0D2A;MALAYALAM LETTER PA;Lo;0;L;;;;;N;;;;;
+0D2B;MALAYALAM LETTER PHA;Lo;0;L;;;;;N;;;;;
+0D2C;MALAYALAM LETTER BA;Lo;0;L;;;;;N;;;;;
+0D2D;MALAYALAM LETTER BHA;Lo;0;L;;;;;N;;;;;
+0D2E;MALAYALAM LETTER MA;Lo;0;L;;;;;N;;;;;
+0D2F;MALAYALAM LETTER YA;Lo;0;L;;;;;N;;;;;
+0D30;MALAYALAM LETTER RA;Lo;0;L;;;;;N;;;;;
+0D31;MALAYALAM LETTER RRA;Lo;0;L;;;;;N;;;;;
+0D32;MALAYALAM LETTER LA;Lo;0;L;;;;;N;;;;;
+0D33;MALAYALAM LETTER LLA;Lo;0;L;;;;;N;;;;;
+0D34;MALAYALAM LETTER LLLA;Lo;0;L;;;;;N;;;;;
+0D35;MALAYALAM LETTER VA;Lo;0;L;;;;;N;;;;;
+0D36;MALAYALAM LETTER SHA;Lo;0;L;;;;;N;;;;;
+0D37;MALAYALAM LETTER SSA;Lo;0;L;;;;;N;;;;;
+0D38;MALAYALAM LETTER SA;Lo;0;L;;;;;N;;;;;
+0D39;MALAYALAM LETTER HA;Lo;0;L;;;;;N;;;;;
+0D3E;MALAYALAM VOWEL SIGN AA;Mc;0;L;;;;;N;;;;;
+0D3F;MALAYALAM VOWEL SIGN I;Mc;0;L;;;;;N;;;;;
+0D40;MALAYALAM VOWEL SIGN II;Mc;0;L;;;;;N;;;;;
+0D41;MALAYALAM VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;;
+0D42;MALAYALAM VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;;
+0D43;MALAYALAM VOWEL SIGN VOCALIC R;Mn;0;NSM;;;;;N;;;;;
+0D46;MALAYALAM VOWEL SIGN E;Mc;0;L;;;;;N;;;;;
+0D47;MALAYALAM VOWEL SIGN EE;Mc;0;L;;;;;N;;;;;
+0D48;MALAYALAM VOWEL SIGN AI;Mc;0;L;;;;;N;;;;;
+0D4A;MALAYALAM VOWEL SIGN O;Mc;0;L;0D46 0D3E;;;;N;;;;;
+0D4B;MALAYALAM VOWEL SIGN OO;Mc;0;L;0D47 0D3E;;;;N;;;;;
+0D4C;MALAYALAM VOWEL SIGN AU;Mc;0;L;0D46 0D57;;;;N;;;;;
+0D4D;MALAYALAM SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;;
+0D57;MALAYALAM AU LENGTH MARK;Mc;0;L;;;;;N;;;;;
+0D60;MALAYALAM LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;;
+0D61;MALAYALAM LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;;
+0D66;MALAYALAM DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+0D67;MALAYALAM DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+0D68;MALAYALAM DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+0D69;MALAYALAM DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+0D6A;MALAYALAM DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+0D6B;MALAYALAM DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+0D6C;MALAYALAM DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+0D6D;MALAYALAM DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+0D6E;MALAYALAM DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+0D6F;MALAYALAM DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+0D82;SINHALA SIGN ANUSVARAYA;Mc;0;L;;;;;N;;;;;
+0D83;SINHALA SIGN VISARGAYA;Mc;0;L;;;;;N;;;;;
+0D85;SINHALA LETTER AYANNA;Lo;0;L;;;;;N;;;;;
+0D86;SINHALA LETTER AAYANNA;Lo;0;L;;;;;N;;;;;
+0D87;SINHALA LETTER AEYANNA;Lo;0;L;;;;;N;;;;;
+0D88;SINHALA LETTER AEEYANNA;Lo;0;L;;;;;N;;;;;
+0D89;SINHALA LETTER IYANNA;Lo;0;L;;;;;N;;;;;
+0D8A;SINHALA LETTER IIYANNA;Lo;0;L;;;;;N;;;;;
+0D8B;SINHALA LETTER UYANNA;Lo;0;L;;;;;N;;;;;
+0D8C;SINHALA LETTER UUYANNA;Lo;0;L;;;;;N;;;;;
+0D8D;SINHALA LETTER IRUYANNA;Lo;0;L;;;;;N;;;;;
+0D8E;SINHALA LETTER IRUUYANNA;Lo;0;L;;;;;N;;;;;
+0D8F;SINHALA LETTER ILUYANNA;Lo;0;L;;;;;N;;;;;
+0D90;SINHALA LETTER ILUUYANNA;Lo;0;L;;;;;N;;;;;
+0D91;SINHALA LETTER EYANNA;Lo;0;L;;;;;N;;;;;
+0D92;SINHALA LETTER EEYANNA;Lo;0;L;;;;;N;;;;;
+0D93;SINHALA LETTER AIYANNA;Lo;0;L;;;;;N;;;;;
+0D94;SINHALA LETTER OYANNA;Lo;0;L;;;;;N;;;;;
+0D95;SINHALA LETTER OOYANNA;Lo;0;L;;;;;N;;;;;
+0D96;SINHALA LETTER AUYANNA;Lo;0;L;;;;;N;;;;;
+0D9A;SINHALA LETTER ALPAPRAANA KAYANNA;Lo;0;L;;;;;N;;;;;
+0D9B;SINHALA LETTER MAHAAPRAANA KAYANNA;Lo;0;L;;;;;N;;;;;
+0D9C;SINHALA LETTER ALPAPRAANA GAYANNA;Lo;0;L;;;;;N;;;;;
+0D9D;SINHALA LETTER MAHAAPRAANA GAYANNA;Lo;0;L;;;;;N;;;;;
+0D9E;SINHALA LETTER KANTAJA NAASIKYAYA;Lo;0;L;;;;;N;;;;;
+0D9F;SINHALA LETTER SANYAKA GAYANNA;Lo;0;L;;;;;N;;;;;
+0DA0;SINHALA LETTER ALPAPRAANA CAYANNA;Lo;0;L;;;;;N;;;;;
+0DA1;SINHALA LETTER MAHAAPRAANA CAYANNA;Lo;0;L;;;;;N;;;;;
+0DA2;SINHALA LETTER ALPAPRAANA JAYANNA;Lo;0;L;;;;;N;;;;;
+0DA3;SINHALA LETTER MAHAAPRAANA JAYANNA;Lo;0;L;;;;;N;;;;;
+0DA4;SINHALA LETTER TAALUJA NAASIKYAYA;Lo;0;L;;;;;N;;;;;
+0DA5;SINHALA LETTER TAALUJA SANYOOGA NAAKSIKYAYA;Lo;0;L;;;;;N;;;;;
+0DA6;SINHALA LETTER SANYAKA JAYANNA;Lo;0;L;;;;;N;;;;;
+0DA7;SINHALA LETTER ALPAPRAANA TTAYANNA;Lo;0;L;;;;;N;;;;;
+0DA8;SINHALA LETTER MAHAAPRAANA TTAYANNA;Lo;0;L;;;;;N;;;;;
+0DA9;SINHALA LETTER ALPAPRAANA DDAYANNA;Lo;0;L;;;;;N;;;;;
+0DAA;SINHALA LETTER MAHAAPRAANA DDAYANNA;Lo;0;L;;;;;N;;;;;
+0DAB;SINHALA LETTER MUURDHAJA NAYANNA;Lo;0;L;;;;;N;;;;;
+0DAC;SINHALA LETTER SANYAKA DDAYANNA;Lo;0;L;;;;;N;;;;;
+0DAD;SINHALA LETTER ALPAPRAANA TAYANNA;Lo;0;L;;;;;N;;;;;
+0DAE;SINHALA LETTER MAHAAPRAANA TAYANNA;Lo;0;L;;;;;N;;;;;
+0DAF;SINHALA LETTER ALPAPRAANA DAYANNA;Lo;0;L;;;;;N;;;;;
+0DB0;SINHALA LETTER MAHAAPRAANA DAYANNA;Lo;0;L;;;;;N;;;;;
+0DB1;SINHALA LETTER DANTAJA NAYANNA;Lo;0;L;;;;;N;;;;;
+0DB3;SINHALA LETTER SANYAKA DAYANNA;Lo;0;L;;;;;N;;;;;
+0DB4;SINHALA LETTER ALPAPRAANA PAYANNA;Lo;0;L;;;;;N;;;;;
+0DB5;SINHALA LETTER MAHAAPRAANA PAYANNA;Lo;0;L;;;;;N;;;;;
+0DB6;SINHALA LETTER ALPAPRAANA BAYANNA;Lo;0;L;;;;;N;;;;;
+0DB7;SINHALA LETTER MAHAAPRAANA BAYANNA;Lo;0;L;;;;;N;;;;;
+0DB8;SINHALA LETTER MAYANNA;Lo;0;L;;;;;N;;;;;
+0DB9;SINHALA LETTER AMBA BAYANNA;Lo;0;L;;;;;N;;;;;
+0DBA;SINHALA LETTER YAYANNA;Lo;0;L;;;;;N;;;;;
+0DBB;SINHALA LETTER RAYANNA;Lo;0;L;;;;;N;;;;;
+0DBD;SINHALA LETTER DANTAJA LAYANNA;Lo;0;L;;;;;N;;;;;
+0DC0;SINHALA LETTER VAYANNA;Lo;0;L;;;;;N;;;;;
+0DC1;SINHALA LETTER TAALUJA SAYANNA;Lo;0;L;;;;;N;;;;;
+0DC2;SINHALA LETTER MUURDHAJA SAYANNA;Lo;0;L;;;;;N;;;;;
+0DC3;SINHALA LETTER DANTAJA SAYANNA;Lo;0;L;;;;;N;;;;;
+0DC4;SINHALA LETTER HAYANNA;Lo;0;L;;;;;N;;;;;
+0DC5;SINHALA LETTER MUURDHAJA LAYANNA;Lo;0;L;;;;;N;;;;;
+0DC6;SINHALA LETTER FAYANNA;Lo;0;L;;;;;N;;;;;
+0DCA;SINHALA SIGN AL-LAKUNA;Mn;9;NSM;;;;;N;;;;;
+0DCF;SINHALA VOWEL SIGN AELA-PILLA;Mc;0;L;;;;;N;;;;;
+0DD0;SINHALA VOWEL SIGN KETTI AEDA-PILLA;Mc;0;L;;;;;N;;;;;
+0DD1;SINHALA VOWEL SIGN DIGA AEDA-PILLA;Mc;0;L;;;;;N;;;;;
+0DD2;SINHALA VOWEL SIGN KETTI IS-PILLA;Mn;0;NSM;;;;;N;;;;;
+0DD3;SINHALA VOWEL SIGN DIGA IS-PILLA;Mn;0;NSM;;;;;N;;;;;
+0DD4;SINHALA VOWEL SIGN KETTI PAA-PILLA;Mn;0;NSM;;;;;N;;;;;
+0DD6;SINHALA VOWEL SIGN DIGA PAA-PILLA;Mn;0;NSM;;;;;N;;;;;
+0DD8;SINHALA VOWEL SIGN GAETTA-PILLA;Mc;0;L;;;;;N;;;;;
+0DD9;SINHALA VOWEL SIGN KOMBUVA;Mc;0;L;;;;;N;;;;;
+0DDA;SINHALA VOWEL SIGN DIGA KOMBUVA;Mc;0;L;0DD9 0DCA;;;;N;;;;;
+0DDB;SINHALA VOWEL SIGN KOMBU DEKA;Mc;0;L;;;;;N;;;;;
+0DDC;SINHALA VOWEL SIGN KOMBUVA HAA AELA-PILLA;Mc;0;L;0DD9 0DCF;;;;N;;;;;
+0DDD;SINHALA VOWEL SIGN KOMBUVA HAA DIGA AELA-PILLA;Mc;0;L;0DDC 0DCA;;;;N;;;;;
+0DDE;SINHALA VOWEL SIGN KOMBUVA HAA GAYANUKITTA;Mc;0;L;0DD9 0DDF;;;;N;;;;;
+0DDF;SINHALA VOWEL SIGN GAYANUKITTA;Mc;0;L;;;;;N;;;;;
+0DF2;SINHALA VOWEL SIGN DIGA GAETTA-PILLA;Mc;0;L;;;;;N;;;;;
+0DF3;SINHALA VOWEL SIGN DIGA GAYANUKITTA;Mc;0;L;;;;;N;;;;;
+0DF4;SINHALA PUNCTUATION KUNDDALIYA;Po;0;L;;;;;N;;;;;
+0E01;THAI CHARACTER KO KAI;Lo;0;L;;;;;N;THAI LETTER KO KAI;;;;
+0E02;THAI CHARACTER KHO KHAI;Lo;0;L;;;;;N;THAI LETTER KHO KHAI;;;;
+0E03;THAI CHARACTER KHO KHUAT;Lo;0;L;;;;;N;THAI LETTER KHO KHUAT;;;;
+0E04;THAI CHARACTER KHO KHWAI;Lo;0;L;;;;;N;THAI LETTER KHO KHWAI;;;;
+0E05;THAI CHARACTER KHO KHON;Lo;0;L;;;;;N;THAI LETTER KHO KHON;;;;
+0E06;THAI CHARACTER KHO RAKHANG;Lo;0;L;;;;;N;THAI LETTER KHO RAKHANG;;;;
+0E07;THAI CHARACTER NGO NGU;Lo;0;L;;;;;N;THAI LETTER NGO NGU;;;;
+0E08;THAI CHARACTER CHO CHAN;Lo;0;L;;;;;N;THAI LETTER CHO CHAN;;;;
+0E09;THAI CHARACTER CHO CHING;Lo;0;L;;;;;N;THAI LETTER CHO CHING;;;;
+0E0A;THAI CHARACTER CHO CHANG;Lo;0;L;;;;;N;THAI LETTER CHO CHANG;;;;
+0E0B;THAI CHARACTER SO SO;Lo;0;L;;;;;N;THAI LETTER SO SO;;;;
+0E0C;THAI CHARACTER CHO CHOE;Lo;0;L;;;;;N;THAI LETTER CHO CHOE;;;;
+0E0D;THAI CHARACTER YO YING;Lo;0;L;;;;;N;THAI LETTER YO YING;;;;
+0E0E;THAI CHARACTER DO CHADA;Lo;0;L;;;;;N;THAI LETTER DO CHADA;;;;
+0E0F;THAI CHARACTER TO PATAK;Lo;0;L;;;;;N;THAI LETTER TO PATAK;;;;
+0E10;THAI CHARACTER THO THAN;Lo;0;L;;;;;N;THAI LETTER THO THAN;;;;
+0E11;THAI CHARACTER THO NANGMONTHO;Lo;0;L;;;;;N;THAI LETTER THO NANGMONTHO;;;;
+0E12;THAI CHARACTER THO PHUTHAO;Lo;0;L;;;;;N;THAI LETTER THO PHUTHAO;;;;
+0E13;THAI CHARACTER NO NEN;Lo;0;L;;;;;N;THAI LETTER NO NEN;;;;
+0E14;THAI CHARACTER DO DEK;Lo;0;L;;;;;N;THAI LETTER DO DEK;;;;
+0E15;THAI CHARACTER TO TAO;Lo;0;L;;;;;N;THAI LETTER TO TAO;;;;
+0E16;THAI CHARACTER THO THUNG;Lo;0;L;;;;;N;THAI LETTER THO THUNG;;;;
+0E17;THAI CHARACTER THO THAHAN;Lo;0;L;;;;;N;THAI LETTER THO THAHAN;;;;
+0E18;THAI CHARACTER THO THONG;Lo;0;L;;;;;N;THAI LETTER THO THONG;;;;
+0E19;THAI CHARACTER NO NU;Lo;0;L;;;;;N;THAI LETTER NO NU;;;;
+0E1A;THAI CHARACTER BO BAIMAI;Lo;0;L;;;;;N;THAI LETTER BO BAIMAI;;;;
+0E1B;THAI CHARACTER PO PLA;Lo;0;L;;;;;N;THAI LETTER PO PLA;;;;
+0E1C;THAI CHARACTER PHO PHUNG;Lo;0;L;;;;;N;THAI LETTER PHO PHUNG;;;;
+0E1D;THAI CHARACTER FO FA;Lo;0;L;;;;;N;THAI LETTER FO FA;;;;
+0E1E;THAI CHARACTER PHO PHAN;Lo;0;L;;;;;N;THAI LETTER PHO PHAN;;;;
+0E1F;THAI CHARACTER FO FAN;Lo;0;L;;;;;N;THAI LETTER FO FAN;;;;
+0E20;THAI CHARACTER PHO SAMPHAO;Lo;0;L;;;;;N;THAI LETTER PHO SAMPHAO;;;;
+0E21;THAI CHARACTER MO MA;Lo;0;L;;;;;N;THAI LETTER MO MA;;;;
+0E22;THAI CHARACTER YO YAK;Lo;0;L;;;;;N;THAI LETTER YO YAK;;;;
+0E23;THAI CHARACTER RO RUA;Lo;0;L;;;;;N;THAI LETTER RO RUA;;;;
+0E24;THAI CHARACTER RU;Lo;0;L;;;;;N;THAI LETTER RU;;;;
+0E25;THAI CHARACTER LO LING;Lo;0;L;;;;;N;THAI LETTER LO LING;;;;
+0E26;THAI CHARACTER LU;Lo;0;L;;;;;N;THAI LETTER LU;;;;
+0E27;THAI CHARACTER WO WAEN;Lo;0;L;;;;;N;THAI LETTER WO WAEN;;;;
+0E28;THAI CHARACTER SO SALA;Lo;0;L;;;;;N;THAI LETTER SO SALA;;;;
+0E29;THAI CHARACTER SO RUSI;Lo;0;L;;;;;N;THAI LETTER SO RUSI;;;;
+0E2A;THAI CHARACTER SO SUA;Lo;0;L;;;;;N;THAI LETTER SO SUA;;;;
+0E2B;THAI CHARACTER HO HIP;Lo;0;L;;;;;N;THAI LETTER HO HIP;;;;
+0E2C;THAI CHARACTER LO CHULA;Lo;0;L;;;;;N;THAI LETTER LO CHULA;;;;
+0E2D;THAI CHARACTER O ANG;Lo;0;L;;;;;N;THAI LETTER O ANG;;;;
+0E2E;THAI CHARACTER HO NOKHUK;Lo;0;L;;;;;N;THAI LETTER HO NOK HUK;;;;
+0E2F;THAI CHARACTER PAIYANNOI;Lo;0;L;;;;;N;THAI PAI YAN NOI;paiyan noi;;;
+0E30;THAI CHARACTER SARA A;Lo;0;L;;;;;N;THAI VOWEL SIGN SARA A;;;;
+0E31;THAI CHARACTER MAI HAN-AKAT;Mn;0;NSM;;;;;N;THAI VOWEL SIGN MAI HAN-AKAT;;;;
+0E32;THAI CHARACTER SARA AA;Lo;0;L;;;;;N;THAI VOWEL SIGN SARA AA;;;;
+0E33;THAI CHARACTER SARA AM;Lo;0;L;<compat> 0E4D 0E32;;;;N;THAI VOWEL SIGN SARA AM;;;;
+0E34;THAI CHARACTER SARA I;Mn;0;NSM;;;;;N;THAI VOWEL SIGN SARA I;;;;
+0E35;THAI CHARACTER SARA II;Mn;0;NSM;;;;;N;THAI VOWEL SIGN SARA II;;;;
+0E36;THAI CHARACTER SARA UE;Mn;0;NSM;;;;;N;THAI VOWEL SIGN SARA UE;;;;
+0E37;THAI CHARACTER SARA UEE;Mn;0;NSM;;;;;N;THAI VOWEL SIGN SARA UEE;sara uue;;;
+0E38;THAI CHARACTER SARA U;Mn;103;NSM;;;;;N;THAI VOWEL SIGN SARA U;;;;
+0E39;THAI CHARACTER SARA UU;Mn;103;NSM;;;;;N;THAI VOWEL SIGN SARA UU;;;;
+0E3A;THAI CHARACTER PHINTHU;Mn;9;NSM;;;;;N;THAI VOWEL SIGN PHINTHU;;;;
+0E3F;THAI CURRENCY SYMBOL BAHT;Sc;0;ET;;;;;N;THAI BAHT SIGN;;;;
+0E40;THAI CHARACTER SARA E;Lo;0;L;;;;;N;THAI VOWEL SIGN SARA E;;;;
+0E41;THAI CHARACTER SARA AE;Lo;0;L;;;;;N;THAI VOWEL SIGN SARA AE;;;;
+0E42;THAI CHARACTER SARA O;Lo;0;L;;;;;N;THAI VOWEL SIGN SARA O;;;;
+0E43;THAI CHARACTER SARA AI MAIMUAN;Lo;0;L;;;;;N;THAI VOWEL SIGN SARA MAI MUAN;sara ai mai muan;;;
+0E44;THAI CHARACTER SARA AI MAIMALAI;Lo;0;L;;;;;N;THAI VOWEL SIGN SARA MAI MALAI;sara ai mai malai;;;
+0E45;THAI CHARACTER LAKKHANGYAO;Lo;0;L;;;;;N;THAI LAK KHANG YAO;lakkhang yao;;;
+0E46;THAI CHARACTER MAIYAMOK;Lm;0;L;;;;;N;THAI MAI YAMOK;mai yamok;;;
+0E47;THAI CHARACTER MAITAIKHU;Mn;0;NSM;;;;;N;THAI VOWEL SIGN MAI TAI KHU;mai taikhu;;;
+0E48;THAI CHARACTER MAI EK;Mn;107;NSM;;;;;N;THAI TONE MAI EK;;;;
+0E49;THAI CHARACTER MAI THO;Mn;107;NSM;;;;;N;THAI TONE MAI THO;;;;
+0E4A;THAI CHARACTER MAI TRI;Mn;107;NSM;;;;;N;THAI TONE MAI TRI;;;;
+0E4B;THAI CHARACTER MAI CHATTAWA;Mn;107;NSM;;;;;N;THAI TONE MAI CHATTAWA;;;;
+0E4C;THAI CHARACTER THANTHAKHAT;Mn;0;NSM;;;;;N;THAI THANTHAKHAT;;;;
+0E4D;THAI CHARACTER NIKHAHIT;Mn;0;NSM;;;;;N;THAI NIKKHAHIT;nikkhahit;;;
+0E4E;THAI CHARACTER YAMAKKAN;Mn;0;NSM;;;;;N;THAI YAMAKKAN;;;;
+0E4F;THAI CHARACTER FONGMAN;Po;0;L;;;;;N;THAI FONGMAN;;;;
+0E50;THAI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+0E51;THAI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+0E52;THAI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+0E53;THAI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+0E54;THAI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+0E55;THAI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+0E56;THAI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+0E57;THAI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+0E58;THAI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+0E59;THAI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+0E5A;THAI CHARACTER ANGKHANKHU;Po;0;L;;;;;N;THAI ANGKHANKHU;;;;
+0E5B;THAI CHARACTER KHOMUT;Po;0;L;;;;;N;THAI KHOMUT;;;;
+0E81;LAO LETTER KO;Lo;0;L;;;;;N;;;;;
+0E82;LAO LETTER KHO SUNG;Lo;0;L;;;;;N;;;;;
+0E84;LAO LETTER KHO TAM;Lo;0;L;;;;;N;;;;;
+0E87;LAO LETTER NGO;Lo;0;L;;;;;N;;;;;
+0E88;LAO LETTER CO;Lo;0;L;;;;;N;;;;;
+0E8A;LAO LETTER SO TAM;Lo;0;L;;;;;N;;;;;
+0E8D;LAO LETTER NYO;Lo;0;L;;;;;N;;;;;
+0E94;LAO LETTER DO;Lo;0;L;;;;;N;;;;;
+0E95;LAO LETTER TO;Lo;0;L;;;;;N;;;;;
+0E96;LAO LETTER THO SUNG;Lo;0;L;;;;;N;;;;;
+0E97;LAO LETTER THO TAM;Lo;0;L;;;;;N;;;;;
+0E99;LAO LETTER NO;Lo;0;L;;;;;N;;;;;
+0E9A;LAO LETTER BO;Lo;0;L;;;;;N;;;;;
+0E9B;LAO LETTER PO;Lo;0;L;;;;;N;;;;;
+0E9C;LAO LETTER PHO SUNG;Lo;0;L;;;;;N;;;;;
+0E9D;LAO LETTER FO TAM;Lo;0;L;;;;;N;;;;;
+0E9E;LAO LETTER PHO TAM;Lo;0;L;;;;;N;;;;;
+0E9F;LAO LETTER FO SUNG;Lo;0;L;;;;;N;;;;;
+0EA1;LAO LETTER MO;Lo;0;L;;;;;N;;;;;
+0EA2;LAO LETTER YO;Lo;0;L;;;;;N;;;;;
+0EA3;LAO LETTER LO LING;Lo;0;L;;;;;N;;;;;
+0EA5;LAO LETTER LO LOOT;Lo;0;L;;;;;N;;;;;
+0EA7;LAO LETTER WO;Lo;0;L;;;;;N;;;;;
+0EAA;LAO LETTER SO SUNG;Lo;0;L;;;;;N;;;;;
+0EAB;LAO LETTER HO SUNG;Lo;0;L;;;;;N;;;;;
+0EAD;LAO LETTER O;Lo;0;L;;;;;N;;;;;
+0EAE;LAO LETTER HO TAM;Lo;0;L;;;;;N;;;;;
+0EAF;LAO ELLIPSIS;Lo;0;L;;;;;N;;;;;
+0EB0;LAO VOWEL SIGN A;Lo;0;L;;;;;N;;;;;
+0EB1;LAO VOWEL SIGN MAI KAN;Mn;0;NSM;;;;;N;;;;;
+0EB2;LAO VOWEL SIGN AA;Lo;0;L;;;;;N;;;;;
+0EB3;LAO VOWEL SIGN AM;Lo;0;L;<compat> 0ECD 0EB2;;;;N;;;;;
+0EB4;LAO VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;;
+0EB5;LAO VOWEL SIGN II;Mn;0;NSM;;;;;N;;;;;
+0EB6;LAO VOWEL SIGN Y;Mn;0;NSM;;;;;N;;;;;
+0EB7;LAO VOWEL SIGN YY;Mn;0;NSM;;;;;N;;;;;
+0EB8;LAO VOWEL SIGN U;Mn;118;NSM;;;;;N;;;;;
+0EB9;LAO VOWEL SIGN UU;Mn;118;NSM;;;;;N;;;;;
+0EBB;LAO VOWEL SIGN MAI KON;Mn;0;NSM;;;;;N;;;;;
+0EBC;LAO SEMIVOWEL SIGN LO;Mn;0;NSM;;;;;N;;;;;
+0EBD;LAO SEMIVOWEL SIGN NYO;Lo;0;L;;;;;N;;;;;
+0EC0;LAO VOWEL SIGN E;Lo;0;L;;;;;N;;;;;
+0EC1;LAO VOWEL SIGN EI;Lo;0;L;;;;;N;;;;;
+0EC2;LAO VOWEL SIGN O;Lo;0;L;;;;;N;;;;;
+0EC3;LAO VOWEL SIGN AY;Lo;0;L;;;;;N;;;;;
+0EC4;LAO VOWEL SIGN AI;Lo;0;L;;;;;N;;;;;
+0EC6;LAO KO LA;Lm;0;L;;;;;N;;;;;
+0EC8;LAO TONE MAI EK;Mn;122;NSM;;;;;N;;;;;
+0EC9;LAO TONE MAI THO;Mn;122;NSM;;;;;N;;;;;
+0ECA;LAO TONE MAI TI;Mn;122;NSM;;;;;N;;;;;
+0ECB;LAO TONE MAI CATAWA;Mn;122;NSM;;;;;N;;;;;
+0ECC;LAO CANCELLATION MARK;Mn;0;NSM;;;;;N;;;;;
+0ECD;LAO NIGGAHITA;Mn;0;NSM;;;;;N;;;;;
+0ED0;LAO DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+0ED1;LAO DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+0ED2;LAO DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+0ED3;LAO DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+0ED4;LAO DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+0ED5;LAO DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+0ED6;LAO DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+0ED7;LAO DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+0ED8;LAO DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+0ED9;LAO DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+0EDC;LAO HO NO;Lo;0;L;<compat> 0EAB 0E99;;;;N;;;;;
+0EDD;LAO HO MO;Lo;0;L;<compat> 0EAB 0EA1;;;;N;;;;;
+0F00;TIBETAN SYLLABLE OM;Lo;0;L;;;;;N;;;;;
+0F01;TIBETAN MARK GTER YIG MGO TRUNCATED A;So;0;L;;;;;N;;ter yik go a thung;;;
+0F02;TIBETAN MARK GTER YIG MGO -UM RNAM BCAD MA;So;0;L;;;;;N;;ter yik go wum nam chey ma;;;
+0F03;TIBETAN MARK GTER YIG MGO -UM GTER TSHEG MA;So;0;L;;;;;N;;ter yik go wum ter tsek ma;;;
+0F04;TIBETAN MARK INITIAL YIG MGO MDUN MA;Po;0;L;;;;;N;TIBETAN SINGLE ORNAMENT;yik go dun ma;;;
+0F05;TIBETAN MARK CLOSING YIG MGO SGAB MA;Po;0;L;;;;;N;;yik go kab ma;;;
+0F06;TIBETAN MARK CARET YIG MGO PHUR SHAD MA;Po;0;L;;;;;N;;yik go pur shey ma;;;
+0F07;TIBETAN MARK YIG MGO TSHEG SHAD MA;Po;0;L;;;;;N;;yik go tsek shey ma;;;
+0F08;TIBETAN MARK SBRUL SHAD;Po;0;L;;;;;N;TIBETAN RGYANSHAD;drul shey;;;
+0F09;TIBETAN MARK BSKUR YIG MGO;Po;0;L;;;;;N;;kur yik go;;;
+0F0A;TIBETAN MARK BKA- SHOG YIG MGO;Po;0;L;;;;;N;;ka sho yik go;;;
+0F0B;TIBETAN MARK INTERSYLLABIC TSHEG;Po;0;L;;;;;N;TIBETAN TSEG;tsek;;;
+0F0C;TIBETAN MARK DELIMITER TSHEG BSTAR;Po;0;L;<noBreak> 0F0B;;;;N;;tsek tar;;;
+0F0D;TIBETAN MARK SHAD;Po;0;L;;;;;N;TIBETAN SHAD;shey;;;
+0F0E;TIBETAN MARK NYIS SHAD;Po;0;L;;;;;N;TIBETAN DOUBLE SHAD;nyi shey;;;
+0F0F;TIBETAN MARK TSHEG SHAD;Po;0;L;;;;;N;;tsek shey;;;
+0F10;TIBETAN MARK NYIS TSHEG SHAD;Po;0;L;;;;;N;;nyi tsek shey;;;
+0F11;TIBETAN MARK RIN CHEN SPUNGS SHAD;Po;0;L;;;;;N;TIBETAN RINCHANPHUNGSHAD;rinchen pung shey;;;
+0F12;TIBETAN MARK RGYA GRAM SHAD;Po;0;L;;;;;N;;gya tram shey;;;
+0F13;TIBETAN MARK CARET -DZUD RTAGS ME LONG CAN;So;0;L;;;;;N;;dzu ta me long chen;;;
+0F14;TIBETAN MARK GTER TSHEG;So;0;L;;;;;N;TIBETAN COMMA;ter tsek;;;
+0F15;TIBETAN LOGOTYPE SIGN CHAD RTAGS;So;0;L;;;;;N;;che ta;;;
+0F16;TIBETAN LOGOTYPE SIGN LHAG RTAGS;So;0;L;;;;;N;;hlak ta;;;
+0F17;TIBETAN ASTROLOGICAL SIGN SGRA GCAN -CHAR RTAGS;So;0;L;;;;;N;;trachen char ta;;;
+0F18;TIBETAN ASTROLOGICAL SIGN -KHYUD PA;Mn;220;NSM;;;;;N;;kyu pa;;;
+0F19;TIBETAN ASTROLOGICAL SIGN SDONG TSHUGS;Mn;220;NSM;;;;;N;;dong tsu;;;
+0F1A;TIBETAN SIGN RDEL DKAR GCIG;So;0;L;;;;;N;;deka chig;;;
+0F1B;TIBETAN SIGN RDEL DKAR GNYIS;So;0;L;;;;;N;;deka nyi;;;
+0F1C;TIBETAN SIGN RDEL DKAR GSUM;So;0;L;;;;;N;;deka sum;;;
+0F1D;TIBETAN SIGN RDEL NAG GCIG;So;0;L;;;;;N;;dena chig;;;
+0F1E;TIBETAN SIGN RDEL NAG GNYIS;So;0;L;;;;;N;;dena nyi;;;
+0F1F;TIBETAN SIGN RDEL DKAR RDEL NAG;So;0;L;;;;;N;;deka dena;;;
+0F20;TIBETAN DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+0F21;TIBETAN DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+0F22;TIBETAN DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+0F23;TIBETAN DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+0F24;TIBETAN DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+0F25;TIBETAN DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+0F26;TIBETAN DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+0F27;TIBETAN DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+0F28;TIBETAN DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+0F29;TIBETAN DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+0F2A;TIBETAN DIGIT HALF ONE;No;0;L;;;;1/2;N;;;;;
+0F2B;TIBETAN DIGIT HALF TWO;No;0;L;;;;3/2;N;;;;;
+0F2C;TIBETAN DIGIT HALF THREE;No;0;L;;;;5/2;N;;;;;
+0F2D;TIBETAN DIGIT HALF FOUR;No;0;L;;;;7/2;N;;;;;
+0F2E;TIBETAN DIGIT HALF FIVE;No;0;L;;;;9/2;N;;;;;
+0F2F;TIBETAN DIGIT HALF SIX;No;0;L;;;;11/2;N;;;;;
+0F30;TIBETAN DIGIT HALF SEVEN;No;0;L;;;;13/2;N;;;;;
+0F31;TIBETAN DIGIT HALF EIGHT;No;0;L;;;;15/2;N;;;;;
+0F32;TIBETAN DIGIT HALF NINE;No;0;L;;;;17/2;N;;;;;
+0F33;TIBETAN DIGIT HALF ZERO;No;0;L;;;;-1/2;N;;;;;
+0F34;TIBETAN MARK BSDUS RTAGS;So;0;L;;;;;N;;du ta;;;
+0F35;TIBETAN MARK NGAS BZUNG NYI ZLA;Mn;220;NSM;;;;;N;TIBETAN HONORIFIC UNDER RING;nge zung nyi da;;;
+0F36;TIBETAN MARK CARET -DZUD RTAGS BZHI MIG CAN;So;0;L;;;;;N;;dzu ta shi mig chen;;;
+0F37;TIBETAN MARK NGAS BZUNG SGOR RTAGS;Mn;220;NSM;;;;;N;TIBETAN UNDER RING;nge zung gor ta;;;
+0F38;TIBETAN MARK CHE MGO;So;0;L;;;;;N;;che go;;;
+0F39;TIBETAN MARK TSA -PHRU;Mn;216;NSM;;;;;N;TIBETAN LENITION MARK;tsa tru;;;
+0F3A;TIBETAN MARK GUG RTAGS GYON;Ps;0;ON;;;;;N;;gug ta yun;;;
+0F3B;TIBETAN MARK GUG RTAGS GYAS;Pe;0;ON;;;;;N;;gug ta ye;;;
+0F3C;TIBETAN MARK ANG KHANG GYON;Ps;0;ON;;;;;N;TIBETAN LEFT BRACE;ang kang yun;;;
+0F3D;TIBETAN MARK ANG KHANG GYAS;Pe;0;ON;;;;;N;TIBETAN RIGHT BRACE;ang kang ye;;;
+0F3E;TIBETAN SIGN YAR TSHES;Mc;0;L;;;;;N;;yar tse;;;
+0F3F;TIBETAN SIGN MAR TSHES;Mc;0;L;;;;;N;;mar tse;;;
+0F40;TIBETAN LETTER KA;Lo;0;L;;;;;N;;;;;
+0F41;TIBETAN LETTER KHA;Lo;0;L;;;;;N;;;;;
+0F42;TIBETAN LETTER GA;Lo;0;L;;;;;N;;;;;
+0F43;TIBETAN LETTER GHA;Lo;0;L;0F42 0FB7;;;;N;;;;;
+0F44;TIBETAN LETTER NGA;Lo;0;L;;;;;N;;;;;
+0F45;TIBETAN LETTER CA;Lo;0;L;;;;;N;;;;;
+0F46;TIBETAN LETTER CHA;Lo;0;L;;;;;N;;;;;
+0F47;TIBETAN LETTER JA;Lo;0;L;;;;;N;;;;;
+0F49;TIBETAN LETTER NYA;Lo;0;L;;;;;N;;;;;
+0F4A;TIBETAN LETTER TTA;Lo;0;L;;;;;N;TIBETAN LETTER REVERSED TA;;;;
+0F4B;TIBETAN LETTER TTHA;Lo;0;L;;;;;N;TIBETAN LETTER REVERSED THA;;;;
+0F4C;TIBETAN LETTER DDA;Lo;0;L;;;;;N;TIBETAN LETTER REVERSED DA;;;;
+0F4D;TIBETAN LETTER DDHA;Lo;0;L;0F4C 0FB7;;;;N;;;;;
+0F4E;TIBETAN LETTER NNA;Lo;0;L;;;;;N;TIBETAN LETTER REVERSED NA;;;;
+0F4F;TIBETAN LETTER TA;Lo;0;L;;;;;N;;;;;
+0F50;TIBETAN LETTER THA;Lo;0;L;;;;;N;;;;;
+0F51;TIBETAN LETTER DA;Lo;0;L;;;;;N;;;;;
+0F52;TIBETAN LETTER DHA;Lo;0;L;0F51 0FB7;;;;N;;;;;
+0F53;TIBETAN LETTER NA;Lo;0;L;;;;;N;;;;;
+0F54;TIBETAN LETTER PA;Lo;0;L;;;;;N;;;;;
+0F55;TIBETAN LETTER PHA;Lo;0;L;;;;;N;;;;;
+0F56;TIBETAN LETTER BA;Lo;0;L;;;;;N;;;;;
+0F57;TIBETAN LETTER BHA;Lo;0;L;0F56 0FB7;;;;N;;;;;
+0F58;TIBETAN LETTER MA;Lo;0;L;;;;;N;;;;;
+0F59;TIBETAN LETTER TSA;Lo;0;L;;;;;N;;;;;
+0F5A;TIBETAN LETTER TSHA;Lo;0;L;;;;;N;;;;;
+0F5B;TIBETAN LETTER DZA;Lo;0;L;;;;;N;;;;;
+0F5C;TIBETAN LETTER DZHA;Lo;0;L;0F5B 0FB7;;;;N;;;;;
+0F5D;TIBETAN LETTER WA;Lo;0;L;;;;;N;;;;;
+0F5E;TIBETAN LETTER ZHA;Lo;0;L;;;;;N;;;;;
+0F5F;TIBETAN LETTER ZA;Lo;0;L;;;;;N;;;;;
+0F60;TIBETAN LETTER -A;Lo;0;L;;;;;N;TIBETAN LETTER AA;;;;
+0F61;TIBETAN LETTER YA;Lo;0;L;;;;;N;;;;;
+0F62;TIBETAN LETTER RA;Lo;0;L;;;;;N;;*;;;
+0F63;TIBETAN LETTER LA;Lo;0;L;;;;;N;;;;;
+0F64;TIBETAN LETTER SHA;Lo;0;L;;;;;N;;;;;
+0F65;TIBETAN LETTER SSA;Lo;0;L;;;;;N;TIBETAN LETTER REVERSED SHA;;;;
+0F66;TIBETAN LETTER SA;Lo;0;L;;;;;N;;;;;
+0F67;TIBETAN LETTER HA;Lo;0;L;;;;;N;;;;;
+0F68;TIBETAN LETTER A;Lo;0;L;;;;;N;;;;;
+0F69;TIBETAN LETTER KSSA;Lo;0;L;0F40 0FB5;;;;N;;;;;
+0F6A;TIBETAN LETTER FIXED-FORM RA;Lo;0;L;;;;;N;;*;;;
+0F71;TIBETAN VOWEL SIGN AA;Mn;129;NSM;;;;;N;;;;;
+0F72;TIBETAN VOWEL SIGN I;Mn;130;NSM;;;;;N;;;;;
+0F73;TIBETAN VOWEL SIGN II;Mn;0;NSM;0F71 0F72;;;;N;;;;;
+0F74;TIBETAN VOWEL SIGN U;Mn;132;NSM;;;;;N;;;;;
+0F75;TIBETAN VOWEL SIGN UU;Mn;0;NSM;0F71 0F74;;;;N;;;;;
+0F76;TIBETAN VOWEL SIGN VOCALIC R;Mn;0;NSM;0FB2 0F80;;;;N;;;;;
+0F77;TIBETAN VOWEL SIGN VOCALIC RR;Mn;0;NSM;<compat> 0FB2 0F81;;;;N;;;;;
+0F78;TIBETAN VOWEL SIGN VOCALIC L;Mn;0;NSM;0FB3 0F80;;;;N;;;;;
+0F79;TIBETAN VOWEL SIGN VOCALIC LL;Mn;0;NSM;<compat> 0FB3 0F81;;;;N;;;;;
+0F7A;TIBETAN VOWEL SIGN E;Mn;130;NSM;;;;;N;;;;;
+0F7B;TIBETAN VOWEL SIGN EE;Mn;130;NSM;;;;;N;TIBETAN VOWEL SIGN AI;;;;
+0F7C;TIBETAN VOWEL SIGN O;Mn;130;NSM;;;;;N;;;;;
+0F7D;TIBETAN VOWEL SIGN OO;Mn;130;NSM;;;;;N;TIBETAN VOWEL SIGN AU;;;;
+0F7E;TIBETAN SIGN RJES SU NGA RO;Mn;0;NSM;;;;;N;TIBETAN ANUSVARA;je su nga ro;;;
+0F7F;TIBETAN SIGN RNAM BCAD;Mc;0;L;;;;;N;TIBETAN VISARGA;nam chey;;;
+0F80;TIBETAN VOWEL SIGN REVERSED I;Mn;130;NSM;;;;;N;TIBETAN VOWEL SIGN SHORT I;;;;
+0F81;TIBETAN VOWEL SIGN REVERSED II;Mn;0;NSM;0F71 0F80;;;;N;;;;;
+0F82;TIBETAN SIGN NYI ZLA NAA DA;Mn;230;NSM;;;;;N;TIBETAN CANDRABINDU WITH ORNAMENT;nyi da na da;;;
+0F83;TIBETAN SIGN SNA LDAN;Mn;230;NSM;;;;;N;TIBETAN CANDRABINDU;nan de;;;
+0F84;TIBETAN MARK HALANTA;Mn;9;NSM;;;;;N;TIBETAN VIRAMA;;;;
+0F85;TIBETAN MARK PALUTA;Po;0;L;;;;;N;TIBETAN CHUCHENYIGE;;;;
+0F86;TIBETAN SIGN LCI RTAGS;Mn;230;NSM;;;;;N;;ji ta;;;
+0F87;TIBETAN SIGN YANG RTAGS;Mn;230;NSM;;;;;N;;yang ta;;;
+0F88;TIBETAN SIGN LCE TSA CAN;Lo;0;L;;;;;N;;che tsa chen;;;
+0F89;TIBETAN SIGN MCHU CAN;Lo;0;L;;;;;N;;chu chen;;;
+0F8A;TIBETAN SIGN GRU CAN RGYINGS;Lo;0;L;;;;;N;;tru chen ging;;;
+0F8B;TIBETAN SIGN GRU MED RGYINGS;Lo;0;L;;;;;N;;tru me ging;;;
+0F90;TIBETAN SUBJOINED LETTER KA;Mn;0;NSM;;;;;N;;;;;
+0F91;TIBETAN SUBJOINED LETTER KHA;Mn;0;NSM;;;;;N;;;;;
+0F92;TIBETAN SUBJOINED LETTER GA;Mn;0;NSM;;;;;N;;;;;
+0F93;TIBETAN SUBJOINED LETTER GHA;Mn;0;NSM;0F92 0FB7;;;;N;;;;;
+0F94;TIBETAN SUBJOINED LETTER NGA;Mn;0;NSM;;;;;N;;;;;
+0F95;TIBETAN SUBJOINED LETTER CA;Mn;0;NSM;;;;;N;;;;;
+0F96;TIBETAN SUBJOINED LETTER CHA;Mn;0;NSM;;;;;N;;;;;
+0F97;TIBETAN SUBJOINED LETTER JA;Mn;0;NSM;;;;;N;;;;;
+0F99;TIBETAN SUBJOINED LETTER NYA;Mn;0;NSM;;;;;N;;;;;
+0F9A;TIBETAN SUBJOINED LETTER TTA;Mn;0;NSM;;;;;N;;;;;
+0F9B;TIBETAN SUBJOINED LETTER TTHA;Mn;0;NSM;;;;;N;;;;;
+0F9C;TIBETAN SUBJOINED LETTER DDA;Mn;0;NSM;;;;;N;;;;;
+0F9D;TIBETAN SUBJOINED LETTER DDHA;Mn;0;NSM;0F9C 0FB7;;;;N;;;;;
+0F9E;TIBETAN SUBJOINED LETTER NNA;Mn;0;NSM;;;;;N;;;;;
+0F9F;TIBETAN SUBJOINED LETTER TA;Mn;0;NSM;;;;;N;;;;;
+0FA0;TIBETAN SUBJOINED LETTER THA;Mn;0;NSM;;;;;N;;;;;
+0FA1;TIBETAN SUBJOINED LETTER DA;Mn;0;NSM;;;;;N;;;;;
+0FA2;TIBETAN SUBJOINED LETTER DHA;Mn;0;NSM;0FA1 0FB7;;;;N;;;;;
+0FA3;TIBETAN SUBJOINED LETTER NA;Mn;0;NSM;;;;;N;;;;;
+0FA4;TIBETAN SUBJOINED LETTER PA;Mn;0;NSM;;;;;N;;;;;
+0FA5;TIBETAN SUBJOINED LETTER PHA;Mn;0;NSM;;;;;N;;;;;
+0FA6;TIBETAN SUBJOINED LETTER BA;Mn;0;NSM;;;;;N;;;;;
+0FA7;TIBETAN SUBJOINED LETTER BHA;Mn;0;NSM;0FA6 0FB7;;;;N;;;;;
+0FA8;TIBETAN SUBJOINED LETTER MA;Mn;0;NSM;;;;;N;;;;;
+0FA9;TIBETAN SUBJOINED LETTER TSA;Mn;0;NSM;;;;;N;;;;;
+0FAA;TIBETAN SUBJOINED LETTER TSHA;Mn;0;NSM;;;;;N;;;;;
+0FAB;TIBETAN SUBJOINED LETTER DZA;Mn;0;NSM;;;;;N;;;;;
+0FAC;TIBETAN SUBJOINED LETTER DZHA;Mn;0;NSM;0FAB 0FB7;;;;N;;;;;
+0FAD;TIBETAN SUBJOINED LETTER WA;Mn;0;NSM;;;;;N;;*;;;
+0FAE;TIBETAN SUBJOINED LETTER ZHA;Mn;0;NSM;;;;;N;;;;;
+0FAF;TIBETAN SUBJOINED LETTER ZA;Mn;0;NSM;;;;;N;;;;;
+0FB0;TIBETAN SUBJOINED LETTER -A;Mn;0;NSM;;;;;N;;;;;
+0FB1;TIBETAN SUBJOINED LETTER YA;Mn;0;NSM;;;;;N;;*;;;
+0FB2;TIBETAN SUBJOINED LETTER RA;Mn;0;NSM;;;;;N;;*;;;
+0FB3;TIBETAN SUBJOINED LETTER LA;Mn;0;NSM;;;;;N;;;;;
+0FB4;TIBETAN SUBJOINED LETTER SHA;Mn;0;NSM;;;;;N;;;;;
+0FB5;TIBETAN SUBJOINED LETTER SSA;Mn;0;NSM;;;;;N;;;;;
+0FB6;TIBETAN SUBJOINED LETTER SA;Mn;0;NSM;;;;;N;;;;;
+0FB7;TIBETAN SUBJOINED LETTER HA;Mn;0;NSM;;;;;N;;;;;
+0FB8;TIBETAN SUBJOINED LETTER A;Mn;0;NSM;;;;;N;;;;;
+0FB9;TIBETAN SUBJOINED LETTER KSSA;Mn;0;NSM;0F90 0FB5;;;;N;;;;;
+0FBA;TIBETAN SUBJOINED LETTER FIXED-FORM WA;Mn;0;NSM;;;;;N;;*;;;
+0FBB;TIBETAN SUBJOINED LETTER FIXED-FORM YA;Mn;0;NSM;;;;;N;;*;;;
+0FBC;TIBETAN SUBJOINED LETTER FIXED-FORM RA;Mn;0;NSM;;;;;N;;*;;;
+0FBE;TIBETAN KU RU KHA;So;0;L;;;;;N;;kuruka;;;
+0FBF;TIBETAN KU RU KHA BZHI MIG CAN;So;0;L;;;;;N;;kuruka shi mik chen;;;
+0FC0;TIBETAN CANTILLATION SIGN HEAVY BEAT;So;0;L;;;;;N;;;;;
+0FC1;TIBETAN CANTILLATION SIGN LIGHT BEAT;So;0;L;;;;;N;;;;;
+0FC2;TIBETAN CANTILLATION SIGN CANG TE-U;So;0;L;;;;;N;;chang tyu;;;
+0FC3;TIBETAN CANTILLATION SIGN SBUB -CHAL;So;0;L;;;;;N;;bub chey;;;
+0FC4;TIBETAN SYMBOL DRIL BU;So;0;L;;;;;N;;drilbu;;;
+0FC5;TIBETAN SYMBOL RDO RJE;So;0;L;;;;;N;;dorje;;;
+0FC6;TIBETAN SYMBOL PADMA GDAN;Mn;220;NSM;;;;;N;;pema den;;;
+0FC7;TIBETAN SYMBOL RDO RJE RGYA GRAM;So;0;L;;;;;N;;dorje gya dram;;;
+0FC8;TIBETAN SYMBOL PHUR PA;So;0;L;;;;;N;;phurba;;;
+0FC9;TIBETAN SYMBOL NOR BU;So;0;L;;;;;N;;norbu;;;
+0FCA;TIBETAN SYMBOL NOR BU NYIS -KHYIL;So;0;L;;;;;N;;norbu nyi khyi;;;
+0FCB;TIBETAN SYMBOL NOR BU GSUM -KHYIL;So;0;L;;;;;N;;norbu sum khyi;;;
+0FCC;TIBETAN SYMBOL NOR BU BZHI -KHYIL;So;0;L;;;;;N;;norbu shi khyi;;;
+0FCF;TIBETAN SIGN RDEL NAG GSUM;So;0;L;;;;;N;;dena sum;;;
+1000;MYANMAR LETTER KA;Lo;0;L;;;;;N;;;;;
+1001;MYANMAR LETTER KHA;Lo;0;L;;;;;N;;;;;
+1002;MYANMAR LETTER GA;Lo;0;L;;;;;N;;;;;
+1003;MYANMAR LETTER GHA;Lo;0;L;;;;;N;;;;;
+1004;MYANMAR LETTER NGA;Lo;0;L;;;;;N;;;;;
+1005;MYANMAR LETTER CA;Lo;0;L;;;;;N;;;;;
+1006;MYANMAR LETTER CHA;Lo;0;L;;;;;N;;;;;
+1007;MYANMAR LETTER JA;Lo;0;L;;;;;N;;;;;
+1008;MYANMAR LETTER JHA;Lo;0;L;;;;;N;;;;;
+1009;MYANMAR LETTER NYA;Lo;0;L;;;;;N;;;;;
+100A;MYANMAR LETTER NNYA;Lo;0;L;;;;;N;;;;;
+100B;MYANMAR LETTER TTA;Lo;0;L;;;;;N;;;;;
+100C;MYANMAR LETTER TTHA;Lo;0;L;;;;;N;;;;;
+100D;MYANMAR LETTER DDA;Lo;0;L;;;;;N;;;;;
+100E;MYANMAR LETTER DDHA;Lo;0;L;;;;;N;;;;;
+100F;MYANMAR LETTER NNA;Lo;0;L;;;;;N;;;;;
+1010;MYANMAR LETTER TA;Lo;0;L;;;;;N;;;;;
+1011;MYANMAR LETTER THA;Lo;0;L;;;;;N;;;;;
+1012;MYANMAR LETTER DA;Lo;0;L;;;;;N;;;;;
+1013;MYANMAR LETTER DHA;Lo;0;L;;;;;N;;;;;
+1014;MYANMAR LETTER NA;Lo;0;L;;;;;N;;;;;
+1015;MYANMAR LETTER PA;Lo;0;L;;;;;N;;;;;
+1016;MYANMAR LETTER PHA;Lo;0;L;;;;;N;;;;;
+1017;MYANMAR LETTER BA;Lo;0;L;;;;;N;;;;;
+1018;MYANMAR LETTER BHA;Lo;0;L;;;;;N;;;;;
+1019;MYANMAR LETTER MA;Lo;0;L;;;;;N;;;;;
+101A;MYANMAR LETTER YA;Lo;0;L;;;;;N;;;;;
+101B;MYANMAR LETTER RA;Lo;0;L;;;;;N;;;;;
+101C;MYANMAR LETTER LA;Lo;0;L;;;;;N;;;;;
+101D;MYANMAR LETTER WA;Lo;0;L;;;;;N;;;;;
+101E;MYANMAR LETTER SA;Lo;0;L;;;;;N;;;;;
+101F;MYANMAR LETTER HA;Lo;0;L;;;;;N;;;;;
+1020;MYANMAR LETTER LLA;Lo;0;L;;;;;N;;;;;
+1021;MYANMAR LETTER A;Lo;0;L;;;;;N;;;;;
+1023;MYANMAR LETTER I;Lo;0;L;;;;;N;;;;;
+1024;MYANMAR LETTER II;Lo;0;L;;;;;N;;;;;
+1025;MYANMAR LETTER U;Lo;0;L;;;;;N;;;;;
+1026;MYANMAR LETTER UU;Lo;0;L;1025 102E;;;;N;;;;;
+1027;MYANMAR LETTER E;Lo;0;L;;;;;N;;;;;
+1029;MYANMAR LETTER O;Lo;0;L;;;;;N;;;;;
+102A;MYANMAR LETTER AU;Lo;0;L;;;;;N;;;;;
+102C;MYANMAR VOWEL SIGN AA;Mc;0;L;;;;;N;;;;;
+102D;MYANMAR VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;;
+102E;MYANMAR VOWEL SIGN II;Mn;0;NSM;;;;;N;;;;;
+102F;MYANMAR VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;;
+1030;MYANMAR VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;;
+1031;MYANMAR VOWEL SIGN E;Mc;0;L;;;;;N;;;;;
+1032;MYANMAR VOWEL SIGN AI;Mn;0;NSM;;;;;N;;;;;
+1036;MYANMAR SIGN ANUSVARA;Mn;0;NSM;;;;;N;;;;;
+1037;MYANMAR SIGN DOT BELOW;Mn;7;NSM;;;;;N;;;;;
+1038;MYANMAR SIGN VISARGA;Mc;0;L;;;;;N;;;;;
+1039;MYANMAR SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;;
+1040;MYANMAR DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+1041;MYANMAR DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+1042;MYANMAR DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+1043;MYANMAR DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+1044;MYANMAR DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+1045;MYANMAR DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+1046;MYANMAR DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+1047;MYANMAR DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+1048;MYANMAR DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+1049;MYANMAR DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+104A;MYANMAR SIGN LITTLE SECTION;Po;0;L;;;;;N;;;;;
+104B;MYANMAR SIGN SECTION;Po;0;L;;;;;N;;;;;
+104C;MYANMAR SYMBOL LOCATIVE;Po;0;L;;;;;N;;;;;
+104D;MYANMAR SYMBOL COMPLETED;Po;0;L;;;;;N;;;;;
+104E;MYANMAR SYMBOL AFOREMENTIONED;Po;0;L;;;;;N;;;;;
+104F;MYANMAR SYMBOL GENITIVE;Po;0;L;;;;;N;;;;;
+1050;MYANMAR LETTER SHA;Lo;0;L;;;;;N;;;;;
+1051;MYANMAR LETTER SSA;Lo;0;L;;;;;N;;;;;
+1052;MYANMAR LETTER VOCALIC R;Lo;0;L;;;;;N;;;;;
+1053;MYANMAR LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;;
+1054;MYANMAR LETTER VOCALIC L;Lo;0;L;;;;;N;;;;;
+1055;MYANMAR LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;;
+1056;MYANMAR VOWEL SIGN VOCALIC R;Mc;0;L;;;;;N;;;;;
+1057;MYANMAR VOWEL SIGN VOCALIC RR;Mc;0;L;;;;;N;;;;;
+1058;MYANMAR VOWEL SIGN VOCALIC L;Mn;0;NSM;;;;;N;;;;;
+1059;MYANMAR VOWEL SIGN VOCALIC LL;Mn;0;NSM;;;;;N;;;;;
+10A0;GEORGIAN CAPITAL LETTER AN;Lu;0;L;;;;;N;;Khutsuri;;;
+10A1;GEORGIAN CAPITAL LETTER BAN;Lu;0;L;;;;;N;;Khutsuri;;;
+10A2;GEORGIAN CAPITAL LETTER GAN;Lu;0;L;;;;;N;;Khutsuri;;;
+10A3;GEORGIAN CAPITAL LETTER DON;Lu;0;L;;;;;N;;Khutsuri;;;
+10A4;GEORGIAN CAPITAL LETTER EN;Lu;0;L;;;;;N;;Khutsuri;;;
+10A5;GEORGIAN CAPITAL LETTER VIN;Lu;0;L;;;;;N;;Khutsuri;;;
+10A6;GEORGIAN CAPITAL LETTER ZEN;Lu;0;L;;;;;N;;Khutsuri;;;
+10A7;GEORGIAN CAPITAL LETTER TAN;Lu;0;L;;;;;N;;Khutsuri;;;
+10A8;GEORGIAN CAPITAL LETTER IN;Lu;0;L;;;;;N;;Khutsuri;;;
+10A9;GEORGIAN CAPITAL LETTER KAN;Lu;0;L;;;;;N;;Khutsuri;;;
+10AA;GEORGIAN CAPITAL LETTER LAS;Lu;0;L;;;;;N;;Khutsuri;;;
+10AB;GEORGIAN CAPITAL LETTER MAN;Lu;0;L;;;;;N;;Khutsuri;;;
+10AC;GEORGIAN CAPITAL LETTER NAR;Lu;0;L;;;;;N;;Khutsuri;;;
+10AD;GEORGIAN CAPITAL LETTER ON;Lu;0;L;;;;;N;;Khutsuri;;;
+10AE;GEORGIAN CAPITAL LETTER PAR;Lu;0;L;;;;;N;;Khutsuri;;;
+10AF;GEORGIAN CAPITAL LETTER ZHAR;Lu;0;L;;;;;N;;Khutsuri;;;
+10B0;GEORGIAN CAPITAL LETTER RAE;Lu;0;L;;;;;N;;Khutsuri;;;
+10B1;GEORGIAN CAPITAL LETTER SAN;Lu;0;L;;;;;N;;Khutsuri;;;
+10B2;GEORGIAN CAPITAL LETTER TAR;Lu;0;L;;;;;N;;Khutsuri;;;
+10B3;GEORGIAN CAPITAL LETTER UN;Lu;0;L;;;;;N;;Khutsuri;;;
+10B4;GEORGIAN CAPITAL LETTER PHAR;Lu;0;L;;;;;N;;Khutsuri;;;
+10B5;GEORGIAN CAPITAL LETTER KHAR;Lu;0;L;;;;;N;;Khutsuri;;;
+10B6;GEORGIAN CAPITAL LETTER GHAN;Lu;0;L;;;;;N;;Khutsuri;;;
+10B7;GEORGIAN CAPITAL LETTER QAR;Lu;0;L;;;;;N;;Khutsuri;;;
+10B8;GEORGIAN CAPITAL LETTER SHIN;Lu;0;L;;;;;N;;Khutsuri;;;
+10B9;GEORGIAN CAPITAL LETTER CHIN;Lu;0;L;;;;;N;;Khutsuri;;;
+10BA;GEORGIAN CAPITAL LETTER CAN;Lu;0;L;;;;;N;;Khutsuri;;;
+10BB;GEORGIAN CAPITAL LETTER JIL;Lu;0;L;;;;;N;;Khutsuri;;;
+10BC;GEORGIAN CAPITAL LETTER CIL;Lu;0;L;;;;;N;;Khutsuri;;;
+10BD;GEORGIAN CAPITAL LETTER CHAR;Lu;0;L;;;;;N;;Khutsuri;;;
+10BE;GEORGIAN CAPITAL LETTER XAN;Lu;0;L;;;;;N;;Khutsuri;;;
+10BF;GEORGIAN CAPITAL LETTER JHAN;Lu;0;L;;;;;N;;Khutsuri;;;
+10C0;GEORGIAN CAPITAL LETTER HAE;Lu;0;L;;;;;N;;Khutsuri;;;
+10C1;GEORGIAN CAPITAL LETTER HE;Lu;0;L;;;;;N;;Khutsuri;;;
+10C2;GEORGIAN CAPITAL LETTER HIE;Lu;0;L;;;;;N;;Khutsuri;;;
+10C3;GEORGIAN CAPITAL LETTER WE;Lu;0;L;;;;;N;;Khutsuri;;;
+10C4;GEORGIAN CAPITAL LETTER HAR;Lu;0;L;;;;;N;;Khutsuri;;;
+10C5;GEORGIAN CAPITAL LETTER HOE;Lu;0;L;;;;;N;;Khutsuri;;;
+10D0;GEORGIAN LETTER AN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER AN;;;;
+10D1;GEORGIAN LETTER BAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER BAN;;;;
+10D2;GEORGIAN LETTER GAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER GAN;;;;
+10D3;GEORGIAN LETTER DON;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER DON;;;;
+10D4;GEORGIAN LETTER EN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER EN;;;;
+10D5;GEORGIAN LETTER VIN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER VIN;;;;
+10D6;GEORGIAN LETTER ZEN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER ZEN;;;;
+10D7;GEORGIAN LETTER TAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER TAN;;;;
+10D8;GEORGIAN LETTER IN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER IN;;;;
+10D9;GEORGIAN LETTER KAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER KAN;;;;
+10DA;GEORGIAN LETTER LAS;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER LAS;;;;
+10DB;GEORGIAN LETTER MAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER MAN;;;;
+10DC;GEORGIAN LETTER NAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER NAR;;;;
+10DD;GEORGIAN LETTER ON;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER ON;;;;
+10DE;GEORGIAN LETTER PAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER PAR;;;;
+10DF;GEORGIAN LETTER ZHAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER ZHAR;;;;
+10E0;GEORGIAN LETTER RAE;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER RAE;;;;
+10E1;GEORGIAN LETTER SAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER SAN;;;;
+10E2;GEORGIAN LETTER TAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER TAR;;;;
+10E3;GEORGIAN LETTER UN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER UN;;;;
+10E4;GEORGIAN LETTER PHAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER PHAR;;;;
+10E5;GEORGIAN LETTER KHAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER KHAR;;;;
+10E6;GEORGIAN LETTER GHAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER GHAN;;;;
+10E7;GEORGIAN LETTER QAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER QAR;;;;
+10E8;GEORGIAN LETTER SHIN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER SHIN;;;;
+10E9;GEORGIAN LETTER CHIN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER CHIN;;;;
+10EA;GEORGIAN LETTER CAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER CAN;;;;
+10EB;GEORGIAN LETTER JIL;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER JIL;;;;
+10EC;GEORGIAN LETTER CIL;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER CIL;;;;
+10ED;GEORGIAN LETTER CHAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER CHAR;;;;
+10EE;GEORGIAN LETTER XAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER XAN;;;;
+10EF;GEORGIAN LETTER JHAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER JHAN;;;;
+10F0;GEORGIAN LETTER HAE;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER HAE;;;;
+10F1;GEORGIAN LETTER HE;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER HE;;;;
+10F2;GEORGIAN LETTER HIE;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER HIE;;;;
+10F3;GEORGIAN LETTER WE;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER WE;;;;
+10F4;GEORGIAN LETTER HAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER HAR;;;;
+10F5;GEORGIAN LETTER HOE;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER HOE;;;;
+10F6;GEORGIAN LETTER FI;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER FI;;;;
+10F7;GEORGIAN LETTER YN;Lo;0;L;;;;;N;;;;;
+10F8;GEORGIAN LETTER ELIFI;Lo;0;L;;;;;N;;;;;
+10FB;GEORGIAN PARAGRAPH SEPARATOR;Po;0;L;;;;;N;;;;;
+1100;HANGUL CHOSEONG KIYEOK;Lo;0;L;;;;;N;;g *;;;
+1101;HANGUL CHOSEONG SSANGKIYEOK;Lo;0;L;;;;;N;;gg *;;;
+1102;HANGUL CHOSEONG NIEUN;Lo;0;L;;;;;N;;n *;;;
+1103;HANGUL CHOSEONG TIKEUT;Lo;0;L;;;;;N;;d *;;;
+1104;HANGUL CHOSEONG SSANGTIKEUT;Lo;0;L;;;;;N;;dd *;;;
+1105;HANGUL CHOSEONG RIEUL;Lo;0;L;;;;;N;;r *;;;
+1106;HANGUL CHOSEONG MIEUM;Lo;0;L;;;;;N;;m *;;;
+1107;HANGUL CHOSEONG PIEUP;Lo;0;L;;;;;N;;b *;;;
+1108;HANGUL CHOSEONG SSANGPIEUP;Lo;0;L;;;;;N;;bb *;;;
+1109;HANGUL CHOSEONG SIOS;Lo;0;L;;;;;N;;s *;;;
+110A;HANGUL CHOSEONG SSANGSIOS;Lo;0;L;;;;;N;;ss *;;;
+110B;HANGUL CHOSEONG IEUNG;Lo;0;L;;;;;N;;;;;
+110C;HANGUL CHOSEONG CIEUC;Lo;0;L;;;;;N;;j *;;;
+110D;HANGUL CHOSEONG SSANGCIEUC;Lo;0;L;;;;;N;;jj *;;;
+110E;HANGUL CHOSEONG CHIEUCH;Lo;0;L;;;;;N;;c *;;;
+110F;HANGUL CHOSEONG KHIEUKH;Lo;0;L;;;;;N;;k *;;;
+1110;HANGUL CHOSEONG THIEUTH;Lo;0;L;;;;;N;;t *;;;
+1111;HANGUL CHOSEONG PHIEUPH;Lo;0;L;;;;;N;;p *;;;
+1112;HANGUL CHOSEONG HIEUH;Lo;0;L;;;;;N;;h *;;;
+1113;HANGUL CHOSEONG NIEUN-KIYEOK;Lo;0;L;;;;;N;;;;;
+1114;HANGUL CHOSEONG SSANGNIEUN;Lo;0;L;;;;;N;;;;;
+1115;HANGUL CHOSEONG NIEUN-TIKEUT;Lo;0;L;;;;;N;;;;;
+1116;HANGUL CHOSEONG NIEUN-PIEUP;Lo;0;L;;;;;N;;;;;
+1117;HANGUL CHOSEONG TIKEUT-KIYEOK;Lo;0;L;;;;;N;;;;;
+1118;HANGUL CHOSEONG RIEUL-NIEUN;Lo;0;L;;;;;N;;;;;
+1119;HANGUL CHOSEONG SSANGRIEUL;Lo;0;L;;;;;N;;;;;
+111A;HANGUL CHOSEONG RIEUL-HIEUH;Lo;0;L;;;;;N;;;;;
+111B;HANGUL CHOSEONG KAPYEOUNRIEUL;Lo;0;L;;;;;N;;;;;
+111C;HANGUL CHOSEONG MIEUM-PIEUP;Lo;0;L;;;;;N;;;;;
+111D;HANGUL CHOSEONG KAPYEOUNMIEUM;Lo;0;L;;;;;N;;;;;
+111E;HANGUL CHOSEONG PIEUP-KIYEOK;Lo;0;L;;;;;N;;;;;
+111F;HANGUL CHOSEONG PIEUP-NIEUN;Lo;0;L;;;;;N;;;;;
+1120;HANGUL CHOSEONG PIEUP-TIKEUT;Lo;0;L;;;;;N;;;;;
+1121;HANGUL CHOSEONG PIEUP-SIOS;Lo;0;L;;;;;N;;;;;
+1122;HANGUL CHOSEONG PIEUP-SIOS-KIYEOK;Lo;0;L;;;;;N;;;;;
+1123;HANGUL CHOSEONG PIEUP-SIOS-TIKEUT;Lo;0;L;;;;;N;;;;;
+1124;HANGUL CHOSEONG PIEUP-SIOS-PIEUP;Lo;0;L;;;;;N;;;;;
+1125;HANGUL CHOSEONG PIEUP-SSANGSIOS;Lo;0;L;;;;;N;;;;;
+1126;HANGUL CHOSEONG PIEUP-SIOS-CIEUC;Lo;0;L;;;;;N;;;;;
+1127;HANGUL CHOSEONG PIEUP-CIEUC;Lo;0;L;;;;;N;;;;;
+1128;HANGUL CHOSEONG PIEUP-CHIEUCH;Lo;0;L;;;;;N;;;;;
+1129;HANGUL CHOSEONG PIEUP-THIEUTH;Lo;0;L;;;;;N;;;;;
+112A;HANGUL CHOSEONG PIEUP-PHIEUPH;Lo;0;L;;;;;N;;;;;
+112B;HANGUL CHOSEONG KAPYEOUNPIEUP;Lo;0;L;;;;;N;;;;;
+112C;HANGUL CHOSEONG KAPYEOUNSSANGPIEUP;Lo;0;L;;;;;N;;;;;
+112D;HANGUL CHOSEONG SIOS-KIYEOK;Lo;0;L;;;;;N;;;;;
+112E;HANGUL CHOSEONG SIOS-NIEUN;Lo;0;L;;;;;N;;;;;
+112F;HANGUL CHOSEONG SIOS-TIKEUT;Lo;0;L;;;;;N;;;;;
+1130;HANGUL CHOSEONG SIOS-RIEUL;Lo;0;L;;;;;N;;;;;
+1131;HANGUL CHOSEONG SIOS-MIEUM;Lo;0;L;;;;;N;;;;;
+1132;HANGUL CHOSEONG SIOS-PIEUP;Lo;0;L;;;;;N;;;;;
+1133;HANGUL CHOSEONG SIOS-PIEUP-KIYEOK;Lo;0;L;;;;;N;;;;;
+1134;HANGUL CHOSEONG SIOS-SSANGSIOS;Lo;0;L;;;;;N;;;;;
+1135;HANGUL CHOSEONG SIOS-IEUNG;Lo;0;L;;;;;N;;;;;
+1136;HANGUL CHOSEONG SIOS-CIEUC;Lo;0;L;;;;;N;;;;;
+1137;HANGUL CHOSEONG SIOS-CHIEUCH;Lo;0;L;;;;;N;;;;;
+1138;HANGUL CHOSEONG SIOS-KHIEUKH;Lo;0;L;;;;;N;;;;;
+1139;HANGUL CHOSEONG SIOS-THIEUTH;Lo;0;L;;;;;N;;;;;
+113A;HANGUL CHOSEONG SIOS-PHIEUPH;Lo;0;L;;;;;N;;;;;
+113B;HANGUL CHOSEONG SIOS-HIEUH;Lo;0;L;;;;;N;;;;;
+113C;HANGUL CHOSEONG CHITUEUMSIOS;Lo;0;L;;;;;N;;;;;
+113D;HANGUL CHOSEONG CHITUEUMSSANGSIOS;Lo;0;L;;;;;N;;;;;
+113E;HANGUL CHOSEONG CEONGCHIEUMSIOS;Lo;0;L;;;;;N;;;;;
+113F;HANGUL CHOSEONG CEONGCHIEUMSSANGSIOS;Lo;0;L;;;;;N;;;;;
+1140;HANGUL CHOSEONG PANSIOS;Lo;0;L;;;;;N;;;;;
+1141;HANGUL CHOSEONG IEUNG-KIYEOK;Lo;0;L;;;;;N;;;;;
+1142;HANGUL CHOSEONG IEUNG-TIKEUT;Lo;0;L;;;;;N;;;;;
+1143;HANGUL CHOSEONG IEUNG-MIEUM;Lo;0;L;;;;;N;;;;;
+1144;HANGUL CHOSEONG IEUNG-PIEUP;Lo;0;L;;;;;N;;;;;
+1145;HANGUL CHOSEONG IEUNG-SIOS;Lo;0;L;;;;;N;;;;;
+1146;HANGUL CHOSEONG IEUNG-PANSIOS;Lo;0;L;;;;;N;;;;;
+1147;HANGUL CHOSEONG SSANGIEUNG;Lo;0;L;;;;;N;;;;;
+1148;HANGUL CHOSEONG IEUNG-CIEUC;Lo;0;L;;;;;N;;;;;
+1149;HANGUL CHOSEONG IEUNG-CHIEUCH;Lo;0;L;;;;;N;;;;;
+114A;HANGUL CHOSEONG IEUNG-THIEUTH;Lo;0;L;;;;;N;;;;;
+114B;HANGUL CHOSEONG IEUNG-PHIEUPH;Lo;0;L;;;;;N;;;;;
+114C;HANGUL CHOSEONG YESIEUNG;Lo;0;L;;;;;N;;;;;
+114D;HANGUL CHOSEONG CIEUC-IEUNG;Lo;0;L;;;;;N;;;;;
+114E;HANGUL CHOSEONG CHITUEUMCIEUC;Lo;0;L;;;;;N;;;;;
+114F;HANGUL CHOSEONG CHITUEUMSSANGCIEUC;Lo;0;L;;;;;N;;;;;
+1150;HANGUL CHOSEONG CEONGCHIEUMCIEUC;Lo;0;L;;;;;N;;;;;
+1151;HANGUL CHOSEONG CEONGCHIEUMSSANGCIEUC;Lo;0;L;;;;;N;;;;;
+1152;HANGUL CHOSEONG CHIEUCH-KHIEUKH;Lo;0;L;;;;;N;;;;;
+1153;HANGUL CHOSEONG CHIEUCH-HIEUH;Lo;0;L;;;;;N;;;;;
+1154;HANGUL CHOSEONG CHITUEUMCHIEUCH;Lo;0;L;;;;;N;;;;;
+1155;HANGUL CHOSEONG CEONGCHIEUMCHIEUCH;Lo;0;L;;;;;N;;;;;
+1156;HANGUL CHOSEONG PHIEUPH-PIEUP;Lo;0;L;;;;;N;;;;;
+1157;HANGUL CHOSEONG KAPYEOUNPHIEUPH;Lo;0;L;;;;;N;;;;;
+1158;HANGUL CHOSEONG SSANGHIEUH;Lo;0;L;;;;;N;;;;;
+1159;HANGUL CHOSEONG YEORINHIEUH;Lo;0;L;;;;;N;;;;;
+115F;HANGUL CHOSEONG FILLER;Lo;0;L;;;;;N;;;;;
+1160;HANGUL JUNGSEONG FILLER;Lo;0;L;;;;;N;;;;;
+1161;HANGUL JUNGSEONG A;Lo;0;L;;;;;N;;;;;
+1162;HANGUL JUNGSEONG AE;Lo;0;L;;;;;N;;;;;
+1163;HANGUL JUNGSEONG YA;Lo;0;L;;;;;N;;;;;
+1164;HANGUL JUNGSEONG YAE;Lo;0;L;;;;;N;;;;;
+1165;HANGUL JUNGSEONG EO;Lo;0;L;;;;;N;;;;;
+1166;HANGUL JUNGSEONG E;Lo;0;L;;;;;N;;;;;
+1167;HANGUL JUNGSEONG YEO;Lo;0;L;;;;;N;;;;;
+1168;HANGUL JUNGSEONG YE;Lo;0;L;;;;;N;;;;;
+1169;HANGUL JUNGSEONG O;Lo;0;L;;;;;N;;;;;
+116A;HANGUL JUNGSEONG WA;Lo;0;L;;;;;N;;;;;
+116B;HANGUL JUNGSEONG WAE;Lo;0;L;;;;;N;;;;;
+116C;HANGUL JUNGSEONG OE;Lo;0;L;;;;;N;;;;;
+116D;HANGUL JUNGSEONG YO;Lo;0;L;;;;;N;;;;;
+116E;HANGUL JUNGSEONG U;Lo;0;L;;;;;N;;;;;
+116F;HANGUL JUNGSEONG WEO;Lo;0;L;;;;;N;;;;;
+1170;HANGUL JUNGSEONG WE;Lo;0;L;;;;;N;;;;;
+1171;HANGUL JUNGSEONG WI;Lo;0;L;;;;;N;;;;;
+1172;HANGUL JUNGSEONG YU;Lo;0;L;;;;;N;;;;;
+1173;HANGUL JUNGSEONG EU;Lo;0;L;;;;;N;;;;;
+1174;HANGUL JUNGSEONG YI;Lo;0;L;;;;;N;;;;;
+1175;HANGUL JUNGSEONG I;Lo;0;L;;;;;N;;;;;
+1176;HANGUL JUNGSEONG A-O;Lo;0;L;;;;;N;;;;;
+1177;HANGUL JUNGSEONG A-U;Lo;0;L;;;;;N;;;;;
+1178;HANGUL JUNGSEONG YA-O;Lo;0;L;;;;;N;;;;;
+1179;HANGUL JUNGSEONG YA-YO;Lo;0;L;;;;;N;;;;;
+117A;HANGUL JUNGSEONG EO-O;Lo;0;L;;;;;N;;;;;
+117B;HANGUL JUNGSEONG EO-U;Lo;0;L;;;;;N;;;;;
+117C;HANGUL JUNGSEONG EO-EU;Lo;0;L;;;;;N;;;;;
+117D;HANGUL JUNGSEONG YEO-O;Lo;0;L;;;;;N;;;;;
+117E;HANGUL JUNGSEONG YEO-U;Lo;0;L;;;;;N;;;;;
+117F;HANGUL JUNGSEONG O-EO;Lo;0;L;;;;;N;;;;;
+1180;HANGUL JUNGSEONG O-E;Lo;0;L;;;;;N;;;;;
+1181;HANGUL JUNGSEONG O-YE;Lo;0;L;;;;;N;;;;;
+1182;HANGUL JUNGSEONG O-O;Lo;0;L;;;;;N;;;;;
+1183;HANGUL JUNGSEONG O-U;Lo;0;L;;;;;N;;;;;
+1184;HANGUL JUNGSEONG YO-YA;Lo;0;L;;;;;N;;;;;
+1185;HANGUL JUNGSEONG YO-YAE;Lo;0;L;;;;;N;;;;;
+1186;HANGUL JUNGSEONG YO-YEO;Lo;0;L;;;;;N;;;;;
+1187;HANGUL JUNGSEONG YO-O;Lo;0;L;;;;;N;;;;;
+1188;HANGUL JUNGSEONG YO-I;Lo;0;L;;;;;N;;;;;
+1189;HANGUL JUNGSEONG U-A;Lo;0;L;;;;;N;;;;;
+118A;HANGUL JUNGSEONG U-AE;Lo;0;L;;;;;N;;;;;
+118B;HANGUL JUNGSEONG U-EO-EU;Lo;0;L;;;;;N;;;;;
+118C;HANGUL JUNGSEONG U-YE;Lo;0;L;;;;;N;;;;;
+118D;HANGUL JUNGSEONG U-U;Lo;0;L;;;;;N;;;;;
+118E;HANGUL JUNGSEONG YU-A;Lo;0;L;;;;;N;;;;;
+118F;HANGUL JUNGSEONG YU-EO;Lo;0;L;;;;;N;;;;;
+1190;HANGUL JUNGSEONG YU-E;Lo;0;L;;;;;N;;;;;
+1191;HANGUL JUNGSEONG YU-YEO;Lo;0;L;;;;;N;;;;;
+1192;HANGUL JUNGSEONG YU-YE;Lo;0;L;;;;;N;;;;;
+1193;HANGUL JUNGSEONG YU-U;Lo;0;L;;;;;N;;;;;
+1194;HANGUL JUNGSEONG YU-I;Lo;0;L;;;;;N;;;;;
+1195;HANGUL JUNGSEONG EU-U;Lo;0;L;;;;;N;;;;;
+1196;HANGUL JUNGSEONG EU-EU;Lo;0;L;;;;;N;;;;;
+1197;HANGUL JUNGSEONG YI-U;Lo;0;L;;;;;N;;;;;
+1198;HANGUL JUNGSEONG I-A;Lo;0;L;;;;;N;;;;;
+1199;HANGUL JUNGSEONG I-YA;Lo;0;L;;;;;N;;;;;
+119A;HANGUL JUNGSEONG I-O;Lo;0;L;;;;;N;;;;;
+119B;HANGUL JUNGSEONG I-U;Lo;0;L;;;;;N;;;;;
+119C;HANGUL JUNGSEONG I-EU;Lo;0;L;;;;;N;;;;;
+119D;HANGUL JUNGSEONG I-ARAEA;Lo;0;L;;;;;N;;;;;
+119E;HANGUL JUNGSEONG ARAEA;Lo;0;L;;;;;N;;;;;
+119F;HANGUL JUNGSEONG ARAEA-EO;Lo;0;L;;;;;N;;;;;
+11A0;HANGUL JUNGSEONG ARAEA-U;Lo;0;L;;;;;N;;;;;
+11A1;HANGUL JUNGSEONG ARAEA-I;Lo;0;L;;;;;N;;;;;
+11A2;HANGUL JUNGSEONG SSANGARAEA;Lo;0;L;;;;;N;;;;;
+11A8;HANGUL JONGSEONG KIYEOK;Lo;0;L;;;;;N;;g *;;;
+11A9;HANGUL JONGSEONG SSANGKIYEOK;Lo;0;L;;;;;N;;gg *;;;
+11AA;HANGUL JONGSEONG KIYEOK-SIOS;Lo;0;L;;;;;N;;gs *;;;
+11AB;HANGUL JONGSEONG NIEUN;Lo;0;L;;;;;N;;n *;;;
+11AC;HANGUL JONGSEONG NIEUN-CIEUC;Lo;0;L;;;;;N;;nj *;;;
+11AD;HANGUL JONGSEONG NIEUN-HIEUH;Lo;0;L;;;;;N;;nh *;;;
+11AE;HANGUL JONGSEONG TIKEUT;Lo;0;L;;;;;N;;d *;;;
+11AF;HANGUL JONGSEONG RIEUL;Lo;0;L;;;;;N;;l *;;;
+11B0;HANGUL JONGSEONG RIEUL-KIYEOK;Lo;0;L;;;;;N;;lg *;;;
+11B1;HANGUL JONGSEONG RIEUL-MIEUM;Lo;0;L;;;;;N;;lm *;;;
+11B2;HANGUL JONGSEONG RIEUL-PIEUP;Lo;0;L;;;;;N;;lb *;;;
+11B3;HANGUL JONGSEONG RIEUL-SIOS;Lo;0;L;;;;;N;;ls *;;;
+11B4;HANGUL JONGSEONG RIEUL-THIEUTH;Lo;0;L;;;;;N;;lt *;;;
+11B5;HANGUL JONGSEONG RIEUL-PHIEUPH;Lo;0;L;;;;;N;;lp *;;;
+11B6;HANGUL JONGSEONG RIEUL-HIEUH;Lo;0;L;;;;;N;;lh *;;;
+11B7;HANGUL JONGSEONG MIEUM;Lo;0;L;;;;;N;;m *;;;
+11B8;HANGUL JONGSEONG PIEUP;Lo;0;L;;;;;N;;b *;;;
+11B9;HANGUL JONGSEONG PIEUP-SIOS;Lo;0;L;;;;;N;;bs *;;;
+11BA;HANGUL JONGSEONG SIOS;Lo;0;L;;;;;N;;s *;;;
+11BB;HANGUL JONGSEONG SSANGSIOS;Lo;0;L;;;;;N;;ss *;;;
+11BC;HANGUL JONGSEONG IEUNG;Lo;0;L;;;;;N;;ng *;;;
+11BD;HANGUL JONGSEONG CIEUC;Lo;0;L;;;;;N;;j *;;;
+11BE;HANGUL JONGSEONG CHIEUCH;Lo;0;L;;;;;N;;c *;;;
+11BF;HANGUL JONGSEONG KHIEUKH;Lo;0;L;;;;;N;;k *;;;
+11C0;HANGUL JONGSEONG THIEUTH;Lo;0;L;;;;;N;;t *;;;
+11C1;HANGUL JONGSEONG PHIEUPH;Lo;0;L;;;;;N;;p *;;;
+11C2;HANGUL JONGSEONG HIEUH;Lo;0;L;;;;;N;;h *;;;
+11C3;HANGUL JONGSEONG KIYEOK-RIEUL;Lo;0;L;;;;;N;;;;;
+11C4;HANGUL JONGSEONG KIYEOK-SIOS-KIYEOK;Lo;0;L;;;;;N;;;;;
+11C5;HANGUL JONGSEONG NIEUN-KIYEOK;Lo;0;L;;;;;N;;;;;
+11C6;HANGUL JONGSEONG NIEUN-TIKEUT;Lo;0;L;;;;;N;;;;;
+11C7;HANGUL JONGSEONG NIEUN-SIOS;Lo;0;L;;;;;N;;;;;
+11C8;HANGUL JONGSEONG NIEUN-PANSIOS;Lo;0;L;;;;;N;;;;;
+11C9;HANGUL JONGSEONG NIEUN-THIEUTH;Lo;0;L;;;;;N;;;;;
+11CA;HANGUL JONGSEONG TIKEUT-KIYEOK;Lo;0;L;;;;;N;;;;;
+11CB;HANGUL JONGSEONG TIKEUT-RIEUL;Lo;0;L;;;;;N;;;;;
+11CC;HANGUL JONGSEONG RIEUL-KIYEOK-SIOS;Lo;0;L;;;;;N;;;;;
+11CD;HANGUL JONGSEONG RIEUL-NIEUN;Lo;0;L;;;;;N;;;;;
+11CE;HANGUL JONGSEONG RIEUL-TIKEUT;Lo;0;L;;;;;N;;;;;
+11CF;HANGUL JONGSEONG RIEUL-TIKEUT-HIEUH;Lo;0;L;;;;;N;;;;;
+11D0;HANGUL JONGSEONG SSANGRIEUL;Lo;0;L;;;;;N;;;;;
+11D1;HANGUL JONGSEONG RIEUL-MIEUM-KIYEOK;Lo;0;L;;;;;N;;;;;
+11D2;HANGUL JONGSEONG RIEUL-MIEUM-SIOS;Lo;0;L;;;;;N;;;;;
+11D3;HANGUL JONGSEONG RIEUL-PIEUP-SIOS;Lo;0;L;;;;;N;;;;;
+11D4;HANGUL JONGSEONG RIEUL-PIEUP-HIEUH;Lo;0;L;;;;;N;;;;;
+11D5;HANGUL JONGSEONG RIEUL-KAPYEOUNPIEUP;Lo;0;L;;;;;N;;;;;
+11D6;HANGUL JONGSEONG RIEUL-SSANGSIOS;Lo;0;L;;;;;N;;;;;
+11D7;HANGUL JONGSEONG RIEUL-PANSIOS;Lo;0;L;;;;;N;;;;;
+11D8;HANGUL JONGSEONG RIEUL-KHIEUKH;Lo;0;L;;;;;N;;;;;
+11D9;HANGUL JONGSEONG RIEUL-YEORINHIEUH;Lo;0;L;;;;;N;;;;;
+11DA;HANGUL JONGSEONG MIEUM-KIYEOK;Lo;0;L;;;;;N;;;;;
+11DB;HANGUL JONGSEONG MIEUM-RIEUL;Lo;0;L;;;;;N;;;;;
+11DC;HANGUL JONGSEONG MIEUM-PIEUP;Lo;0;L;;;;;N;;;;;
+11DD;HANGUL JONGSEONG MIEUM-SIOS;Lo;0;L;;;;;N;;;;;
+11DE;HANGUL JONGSEONG MIEUM-SSANGSIOS;Lo;0;L;;;;;N;;;;;
+11DF;HANGUL JONGSEONG MIEUM-PANSIOS;Lo;0;L;;;;;N;;;;;
+11E0;HANGUL JONGSEONG MIEUM-CHIEUCH;Lo;0;L;;;;;N;;;;;
+11E1;HANGUL JONGSEONG MIEUM-HIEUH;Lo;0;L;;;;;N;;;;;
+11E2;HANGUL JONGSEONG KAPYEOUNMIEUM;Lo;0;L;;;;;N;;;;;
+11E3;HANGUL JONGSEONG PIEUP-RIEUL;Lo;0;L;;;;;N;;;;;
+11E4;HANGUL JONGSEONG PIEUP-PHIEUPH;Lo;0;L;;;;;N;;;;;
+11E5;HANGUL JONGSEONG PIEUP-HIEUH;Lo;0;L;;;;;N;;;;;
+11E6;HANGUL JONGSEONG KAPYEOUNPIEUP;Lo;0;L;;;;;N;;;;;
+11E7;HANGUL JONGSEONG SIOS-KIYEOK;Lo;0;L;;;;;N;;;;;
+11E8;HANGUL JONGSEONG SIOS-TIKEUT;Lo;0;L;;;;;N;;;;;
+11E9;HANGUL JONGSEONG SIOS-RIEUL;Lo;0;L;;;;;N;;;;;
+11EA;HANGUL JONGSEONG SIOS-PIEUP;Lo;0;L;;;;;N;;;;;
+11EB;HANGUL JONGSEONG PANSIOS;Lo;0;L;;;;;N;;;;;
+11EC;HANGUL JONGSEONG IEUNG-KIYEOK;Lo;0;L;;;;;N;;;;;
+11ED;HANGUL JONGSEONG IEUNG-SSANGKIYEOK;Lo;0;L;;;;;N;;;;;
+11EE;HANGUL JONGSEONG SSANGIEUNG;Lo;0;L;;;;;N;;;;;
+11EF;HANGUL JONGSEONG IEUNG-KHIEUKH;Lo;0;L;;;;;N;;;;;
+11F0;HANGUL JONGSEONG YESIEUNG;Lo;0;L;;;;;N;;;;;
+11F1;HANGUL JONGSEONG YESIEUNG-SIOS;Lo;0;L;;;;;N;;;;;
+11F2;HANGUL JONGSEONG YESIEUNG-PANSIOS;Lo;0;L;;;;;N;;;;;
+11F3;HANGUL JONGSEONG PHIEUPH-PIEUP;Lo;0;L;;;;;N;;;;;
+11F4;HANGUL JONGSEONG KAPYEOUNPHIEUPH;Lo;0;L;;;;;N;;;;;
+11F5;HANGUL JONGSEONG HIEUH-NIEUN;Lo;0;L;;;;;N;;;;;
+11F6;HANGUL JONGSEONG HIEUH-RIEUL;Lo;0;L;;;;;N;;;;;
+11F7;HANGUL JONGSEONG HIEUH-MIEUM;Lo;0;L;;;;;N;;;;;
+11F8;HANGUL JONGSEONG HIEUH-PIEUP;Lo;0;L;;;;;N;;;;;
+11F9;HANGUL JONGSEONG YEORINHIEUH;Lo;0;L;;;;;N;;;;;
+1200;ETHIOPIC SYLLABLE HA;Lo;0;L;;;;;N;;;;;
+1201;ETHIOPIC SYLLABLE HU;Lo;0;L;;;;;N;;;;;
+1202;ETHIOPIC SYLLABLE HI;Lo;0;L;;;;;N;;;;;
+1203;ETHIOPIC SYLLABLE HAA;Lo;0;L;;;;;N;;;;;
+1204;ETHIOPIC SYLLABLE HEE;Lo;0;L;;;;;N;;;;;
+1205;ETHIOPIC SYLLABLE HE;Lo;0;L;;;;;N;;;;;
+1206;ETHIOPIC SYLLABLE HO;Lo;0;L;;;;;N;;;;;
+1208;ETHIOPIC SYLLABLE LA;Lo;0;L;;;;;N;;;;;
+1209;ETHIOPIC SYLLABLE LU;Lo;0;L;;;;;N;;;;;
+120A;ETHIOPIC SYLLABLE LI;Lo;0;L;;;;;N;;;;;
+120B;ETHIOPIC SYLLABLE LAA;Lo;0;L;;;;;N;;;;;
+120C;ETHIOPIC SYLLABLE LEE;Lo;0;L;;;;;N;;;;;
+120D;ETHIOPIC SYLLABLE LE;Lo;0;L;;;;;N;;;;;
+120E;ETHIOPIC SYLLABLE LO;Lo;0;L;;;;;N;;;;;
+120F;ETHIOPIC SYLLABLE LWA;Lo;0;L;;;;;N;;;;;
+1210;ETHIOPIC SYLLABLE HHA;Lo;0;L;;;;;N;;;;;
+1211;ETHIOPIC SYLLABLE HHU;Lo;0;L;;;;;N;;;;;
+1212;ETHIOPIC SYLLABLE HHI;Lo;0;L;;;;;N;;;;;
+1213;ETHIOPIC SYLLABLE HHAA;Lo;0;L;;;;;N;;;;;
+1214;ETHIOPIC SYLLABLE HHEE;Lo;0;L;;;;;N;;;;;
+1215;ETHIOPIC SYLLABLE HHE;Lo;0;L;;;;;N;;;;;
+1216;ETHIOPIC SYLLABLE HHO;Lo;0;L;;;;;N;;;;;
+1217;ETHIOPIC SYLLABLE HHWA;Lo;0;L;;;;;N;;;;;
+1218;ETHIOPIC SYLLABLE MA;Lo;0;L;;;;;N;;;;;
+1219;ETHIOPIC SYLLABLE MU;Lo;0;L;;;;;N;;;;;
+121A;ETHIOPIC SYLLABLE MI;Lo;0;L;;;;;N;;;;;
+121B;ETHIOPIC SYLLABLE MAA;Lo;0;L;;;;;N;;;;;
+121C;ETHIOPIC SYLLABLE MEE;Lo;0;L;;;;;N;;;;;
+121D;ETHIOPIC SYLLABLE ME;Lo;0;L;;;;;N;;;;;
+121E;ETHIOPIC SYLLABLE MO;Lo;0;L;;;;;N;;;;;
+121F;ETHIOPIC SYLLABLE MWA;Lo;0;L;;;;;N;;;;;
+1220;ETHIOPIC SYLLABLE SZA;Lo;0;L;;;;;N;;;;;
+1221;ETHIOPIC SYLLABLE SZU;Lo;0;L;;;;;N;;;;;
+1222;ETHIOPIC SYLLABLE SZI;Lo;0;L;;;;;N;;;;;
+1223;ETHIOPIC SYLLABLE SZAA;Lo;0;L;;;;;N;;;;;
+1224;ETHIOPIC SYLLABLE SZEE;Lo;0;L;;;;;N;;;;;
+1225;ETHIOPIC SYLLABLE SZE;Lo;0;L;;;;;N;;;;;
+1226;ETHIOPIC SYLLABLE SZO;Lo;0;L;;;;;N;;;;;
+1227;ETHIOPIC SYLLABLE SZWA;Lo;0;L;;;;;N;;;;;
+1228;ETHIOPIC SYLLABLE RA;Lo;0;L;;;;;N;;;;;
+1229;ETHIOPIC SYLLABLE RU;Lo;0;L;;;;;N;;;;;
+122A;ETHIOPIC SYLLABLE RI;Lo;0;L;;;;;N;;;;;
+122B;ETHIOPIC SYLLABLE RAA;Lo;0;L;;;;;N;;;;;
+122C;ETHIOPIC SYLLABLE REE;Lo;0;L;;;;;N;;;;;
+122D;ETHIOPIC SYLLABLE RE;Lo;0;L;;;;;N;;;;;
+122E;ETHIOPIC SYLLABLE RO;Lo;0;L;;;;;N;;;;;
+122F;ETHIOPIC SYLLABLE RWA;Lo;0;L;;;;;N;;;;;
+1230;ETHIOPIC SYLLABLE SA;Lo;0;L;;;;;N;;;;;
+1231;ETHIOPIC SYLLABLE SU;Lo;0;L;;;;;N;;;;;
+1232;ETHIOPIC SYLLABLE SI;Lo;0;L;;;;;N;;;;;
+1233;ETHIOPIC SYLLABLE SAA;Lo;0;L;;;;;N;;;;;
+1234;ETHIOPIC SYLLABLE SEE;Lo;0;L;;;;;N;;;;;
+1235;ETHIOPIC SYLLABLE SE;Lo;0;L;;;;;N;;;;;
+1236;ETHIOPIC SYLLABLE SO;Lo;0;L;;;;;N;;;;;
+1237;ETHIOPIC SYLLABLE SWA;Lo;0;L;;;;;N;;;;;
+1238;ETHIOPIC SYLLABLE SHA;Lo;0;L;;;;;N;;;;;
+1239;ETHIOPIC SYLLABLE SHU;Lo;0;L;;;;;N;;;;;
+123A;ETHIOPIC SYLLABLE SHI;Lo;0;L;;;;;N;;;;;
+123B;ETHIOPIC SYLLABLE SHAA;Lo;0;L;;;;;N;;;;;
+123C;ETHIOPIC SYLLABLE SHEE;Lo;0;L;;;;;N;;;;;
+123D;ETHIOPIC SYLLABLE SHE;Lo;0;L;;;;;N;;;;;
+123E;ETHIOPIC SYLLABLE SHO;Lo;0;L;;;;;N;;;;;
+123F;ETHIOPIC SYLLABLE SHWA;Lo;0;L;;;;;N;;;;;
+1240;ETHIOPIC SYLLABLE QA;Lo;0;L;;;;;N;;;;;
+1241;ETHIOPIC SYLLABLE QU;Lo;0;L;;;;;N;;;;;
+1242;ETHIOPIC SYLLABLE QI;Lo;0;L;;;;;N;;;;;
+1243;ETHIOPIC SYLLABLE QAA;Lo;0;L;;;;;N;;;;;
+1244;ETHIOPIC SYLLABLE QEE;Lo;0;L;;;;;N;;;;;
+1245;ETHIOPIC SYLLABLE QE;Lo;0;L;;;;;N;;;;;
+1246;ETHIOPIC SYLLABLE QO;Lo;0;L;;;;;N;;;;;
+1248;ETHIOPIC SYLLABLE QWA;Lo;0;L;;;;;N;;;;;
+124A;ETHIOPIC SYLLABLE QWI;Lo;0;L;;;;;N;;;;;
+124B;ETHIOPIC SYLLABLE QWAA;Lo;0;L;;;;;N;;;;;
+124C;ETHIOPIC SYLLABLE QWEE;Lo;0;L;;;;;N;;;;;
+124D;ETHIOPIC SYLLABLE QWE;Lo;0;L;;;;;N;;;;;
+1250;ETHIOPIC SYLLABLE QHA;Lo;0;L;;;;;N;;;;;
+1251;ETHIOPIC SYLLABLE QHU;Lo;0;L;;;;;N;;;;;
+1252;ETHIOPIC SYLLABLE QHI;Lo;0;L;;;;;N;;;;;
+1253;ETHIOPIC SYLLABLE QHAA;Lo;0;L;;;;;N;;;;;
+1254;ETHIOPIC SYLLABLE QHEE;Lo;0;L;;;;;N;;;;;
+1255;ETHIOPIC SYLLABLE QHE;Lo;0;L;;;;;N;;;;;
+1256;ETHIOPIC SYLLABLE QHO;Lo;0;L;;;;;N;;;;;
+1258;ETHIOPIC SYLLABLE QHWA;Lo;0;L;;;;;N;;;;;
+125A;ETHIOPIC SYLLABLE QHWI;Lo;0;L;;;;;N;;;;;
+125B;ETHIOPIC SYLLABLE QHWAA;Lo;0;L;;;;;N;;;;;
+125C;ETHIOPIC SYLLABLE QHWEE;Lo;0;L;;;;;N;;;;;
+125D;ETHIOPIC SYLLABLE QHWE;Lo;0;L;;;;;N;;;;;
+1260;ETHIOPIC SYLLABLE BA;Lo;0;L;;;;;N;;;;;
+1261;ETHIOPIC SYLLABLE BU;Lo;0;L;;;;;N;;;;;
+1262;ETHIOPIC SYLLABLE BI;Lo;0;L;;;;;N;;;;;
+1263;ETHIOPIC SYLLABLE BAA;Lo;0;L;;;;;N;;;;;
+1264;ETHIOPIC SYLLABLE BEE;Lo;0;L;;;;;N;;;;;
+1265;ETHIOPIC SYLLABLE BE;Lo;0;L;;;;;N;;;;;
+1266;ETHIOPIC SYLLABLE BO;Lo;0;L;;;;;N;;;;;
+1267;ETHIOPIC SYLLABLE BWA;Lo;0;L;;;;;N;;;;;
+1268;ETHIOPIC SYLLABLE VA;Lo;0;L;;;;;N;;;;;
+1269;ETHIOPIC SYLLABLE VU;Lo;0;L;;;;;N;;;;;
+126A;ETHIOPIC SYLLABLE VI;Lo;0;L;;;;;N;;;;;
+126B;ETHIOPIC SYLLABLE VAA;Lo;0;L;;;;;N;;;;;
+126C;ETHIOPIC SYLLABLE VEE;Lo;0;L;;;;;N;;;;;
+126D;ETHIOPIC SYLLABLE VE;Lo;0;L;;;;;N;;;;;
+126E;ETHIOPIC SYLLABLE VO;Lo;0;L;;;;;N;;;;;
+126F;ETHIOPIC SYLLABLE VWA;Lo;0;L;;;;;N;;;;;
+1270;ETHIOPIC SYLLABLE TA;Lo;0;L;;;;;N;;;;;
+1271;ETHIOPIC SYLLABLE TU;Lo;0;L;;;;;N;;;;;
+1272;ETHIOPIC SYLLABLE TI;Lo;0;L;;;;;N;;;;;
+1273;ETHIOPIC SYLLABLE TAA;Lo;0;L;;;;;N;;;;;
+1274;ETHIOPIC SYLLABLE TEE;Lo;0;L;;;;;N;;;;;
+1275;ETHIOPIC SYLLABLE TE;Lo;0;L;;;;;N;;;;;
+1276;ETHIOPIC SYLLABLE TO;Lo;0;L;;;;;N;;;;;
+1277;ETHIOPIC SYLLABLE TWA;Lo;0;L;;;;;N;;;;;
+1278;ETHIOPIC SYLLABLE CA;Lo;0;L;;;;;N;;;;;
+1279;ETHIOPIC SYLLABLE CU;Lo;0;L;;;;;N;;;;;
+127A;ETHIOPIC SYLLABLE CI;Lo;0;L;;;;;N;;;;;
+127B;ETHIOPIC SYLLABLE CAA;Lo;0;L;;;;;N;;;;;
+127C;ETHIOPIC SYLLABLE CEE;Lo;0;L;;;;;N;;;;;
+127D;ETHIOPIC SYLLABLE CE;Lo;0;L;;;;;N;;;;;
+127E;ETHIOPIC SYLLABLE CO;Lo;0;L;;;;;N;;;;;
+127F;ETHIOPIC SYLLABLE CWA;Lo;0;L;;;;;N;;;;;
+1280;ETHIOPIC SYLLABLE XA;Lo;0;L;;;;;N;;;;;
+1281;ETHIOPIC SYLLABLE XU;Lo;0;L;;;;;N;;;;;
+1282;ETHIOPIC SYLLABLE XI;Lo;0;L;;;;;N;;;;;
+1283;ETHIOPIC SYLLABLE XAA;Lo;0;L;;;;;N;;;;;
+1284;ETHIOPIC SYLLABLE XEE;Lo;0;L;;;;;N;;;;;
+1285;ETHIOPIC SYLLABLE XE;Lo;0;L;;;;;N;;;;;
+1286;ETHIOPIC SYLLABLE XO;Lo;0;L;;;;;N;;;;;
+1288;ETHIOPIC SYLLABLE XWA;Lo;0;L;;;;;N;;;;;
+128A;ETHIOPIC SYLLABLE XWI;Lo;0;L;;;;;N;;;;;
+128B;ETHIOPIC SYLLABLE XWAA;Lo;0;L;;;;;N;;;;;
+128C;ETHIOPIC SYLLABLE XWEE;Lo;0;L;;;;;N;;;;;
+128D;ETHIOPIC SYLLABLE XWE;Lo;0;L;;;;;N;;;;;
+1290;ETHIOPIC SYLLABLE NA;Lo;0;L;;;;;N;;;;;
+1291;ETHIOPIC SYLLABLE NU;Lo;0;L;;;;;N;;;;;
+1292;ETHIOPIC SYLLABLE NI;Lo;0;L;;;;;N;;;;;
+1293;ETHIOPIC SYLLABLE NAA;Lo;0;L;;;;;N;;;;;
+1294;ETHIOPIC SYLLABLE NEE;Lo;0;L;;;;;N;;;;;
+1295;ETHIOPIC SYLLABLE NE;Lo;0;L;;;;;N;;;;;
+1296;ETHIOPIC SYLLABLE NO;Lo;0;L;;;;;N;;;;;
+1297;ETHIOPIC SYLLABLE NWA;Lo;0;L;;;;;N;;;;;
+1298;ETHIOPIC SYLLABLE NYA;Lo;0;L;;;;;N;;;;;
+1299;ETHIOPIC SYLLABLE NYU;Lo;0;L;;;;;N;;;;;
+129A;ETHIOPIC SYLLABLE NYI;Lo;0;L;;;;;N;;;;;
+129B;ETHIOPIC SYLLABLE NYAA;Lo;0;L;;;;;N;;;;;
+129C;ETHIOPIC SYLLABLE NYEE;Lo;0;L;;;;;N;;;;;
+129D;ETHIOPIC SYLLABLE NYE;Lo;0;L;;;;;N;;;;;
+129E;ETHIOPIC SYLLABLE NYO;Lo;0;L;;;;;N;;;;;
+129F;ETHIOPIC SYLLABLE NYWA;Lo;0;L;;;;;N;;;;;
+12A0;ETHIOPIC SYLLABLE GLOTTAL A;Lo;0;L;;;;;N;;;;;
+12A1;ETHIOPIC SYLLABLE GLOTTAL U;Lo;0;L;;;;;N;;;;;
+12A2;ETHIOPIC SYLLABLE GLOTTAL I;Lo;0;L;;;;;N;;;;;
+12A3;ETHIOPIC SYLLABLE GLOTTAL AA;Lo;0;L;;;;;N;;;;;
+12A4;ETHIOPIC SYLLABLE GLOTTAL EE;Lo;0;L;;;;;N;;;;;
+12A5;ETHIOPIC SYLLABLE GLOTTAL E;Lo;0;L;;;;;N;;;;;
+12A6;ETHIOPIC SYLLABLE GLOTTAL O;Lo;0;L;;;;;N;;;;;
+12A7;ETHIOPIC SYLLABLE GLOTTAL WA;Lo;0;L;;;;;N;;;;;
+12A8;ETHIOPIC SYLLABLE KA;Lo;0;L;;;;;N;;;;;
+12A9;ETHIOPIC SYLLABLE KU;Lo;0;L;;;;;N;;;;;
+12AA;ETHIOPIC SYLLABLE KI;Lo;0;L;;;;;N;;;;;
+12AB;ETHIOPIC SYLLABLE KAA;Lo;0;L;;;;;N;;;;;
+12AC;ETHIOPIC SYLLABLE KEE;Lo;0;L;;;;;N;;;;;
+12AD;ETHIOPIC SYLLABLE KE;Lo;0;L;;;;;N;;;;;
+12AE;ETHIOPIC SYLLABLE KO;Lo;0;L;;;;;N;;;;;
+12B0;ETHIOPIC SYLLABLE KWA;Lo;0;L;;;;;N;;;;;
+12B2;ETHIOPIC SYLLABLE KWI;Lo;0;L;;;;;N;;;;;
+12B3;ETHIOPIC SYLLABLE KWAA;Lo;0;L;;;;;N;;;;;
+12B4;ETHIOPIC SYLLABLE KWEE;Lo;0;L;;;;;N;;;;;
+12B5;ETHIOPIC SYLLABLE KWE;Lo;0;L;;;;;N;;;;;
+12B8;ETHIOPIC SYLLABLE KXA;Lo;0;L;;;;;N;;;;;
+12B9;ETHIOPIC SYLLABLE KXU;Lo;0;L;;;;;N;;;;;
+12BA;ETHIOPIC SYLLABLE KXI;Lo;0;L;;;;;N;;;;;
+12BB;ETHIOPIC SYLLABLE KXAA;Lo;0;L;;;;;N;;;;;
+12BC;ETHIOPIC SYLLABLE KXEE;Lo;0;L;;;;;N;;;;;
+12BD;ETHIOPIC SYLLABLE KXE;Lo;0;L;;;;;N;;;;;
+12BE;ETHIOPIC SYLLABLE KXO;Lo;0;L;;;;;N;;;;;
+12C0;ETHIOPIC SYLLABLE KXWA;Lo;0;L;;;;;N;;;;;
+12C2;ETHIOPIC SYLLABLE KXWI;Lo;0;L;;;;;N;;;;;
+12C3;ETHIOPIC SYLLABLE KXWAA;Lo;0;L;;;;;N;;;;;
+12C4;ETHIOPIC SYLLABLE KXWEE;Lo;0;L;;;;;N;;;;;
+12C5;ETHIOPIC SYLLABLE KXWE;Lo;0;L;;;;;N;;;;;
+12C8;ETHIOPIC SYLLABLE WA;Lo;0;L;;;;;N;;;;;
+12C9;ETHIOPIC SYLLABLE WU;Lo;0;L;;;;;N;;;;;
+12CA;ETHIOPIC SYLLABLE WI;Lo;0;L;;;;;N;;;;;
+12CB;ETHIOPIC SYLLABLE WAA;Lo;0;L;;;;;N;;;;;
+12CC;ETHIOPIC SYLLABLE WEE;Lo;0;L;;;;;N;;;;;
+12CD;ETHIOPIC SYLLABLE WE;Lo;0;L;;;;;N;;;;;
+12CE;ETHIOPIC SYLLABLE WO;Lo;0;L;;;;;N;;;;;
+12D0;ETHIOPIC SYLLABLE PHARYNGEAL A;Lo;0;L;;;;;N;;;;;
+12D1;ETHIOPIC SYLLABLE PHARYNGEAL U;Lo;0;L;;;;;N;;;;;
+12D2;ETHIOPIC SYLLABLE PHARYNGEAL I;Lo;0;L;;;;;N;;;;;
+12D3;ETHIOPIC SYLLABLE PHARYNGEAL AA;Lo;0;L;;;;;N;;;;;
+12D4;ETHIOPIC SYLLABLE PHARYNGEAL EE;Lo;0;L;;;;;N;;;;;
+12D5;ETHIOPIC SYLLABLE PHARYNGEAL E;Lo;0;L;;;;;N;;;;;
+12D6;ETHIOPIC SYLLABLE PHARYNGEAL O;Lo;0;L;;;;;N;;;;;
+12D8;ETHIOPIC SYLLABLE ZA;Lo;0;L;;;;;N;;;;;
+12D9;ETHIOPIC SYLLABLE ZU;Lo;0;L;;;;;N;;;;;
+12DA;ETHIOPIC SYLLABLE ZI;Lo;0;L;;;;;N;;;;;
+12DB;ETHIOPIC SYLLABLE ZAA;Lo;0;L;;;;;N;;;;;
+12DC;ETHIOPIC SYLLABLE ZEE;Lo;0;L;;;;;N;;;;;
+12DD;ETHIOPIC SYLLABLE ZE;Lo;0;L;;;;;N;;;;;
+12DE;ETHIOPIC SYLLABLE ZO;Lo;0;L;;;;;N;;;;;
+12DF;ETHIOPIC SYLLABLE ZWA;Lo;0;L;;;;;N;;;;;
+12E0;ETHIOPIC SYLLABLE ZHA;Lo;0;L;;;;;N;;;;;
+12E1;ETHIOPIC SYLLABLE ZHU;Lo;0;L;;;;;N;;;;;
+12E2;ETHIOPIC SYLLABLE ZHI;Lo;0;L;;;;;N;;;;;
+12E3;ETHIOPIC SYLLABLE ZHAA;Lo;0;L;;;;;N;;;;;
+12E4;ETHIOPIC SYLLABLE ZHEE;Lo;0;L;;;;;N;;;;;
+12E5;ETHIOPIC SYLLABLE ZHE;Lo;0;L;;;;;N;;;;;
+12E6;ETHIOPIC SYLLABLE ZHO;Lo;0;L;;;;;N;;;;;
+12E7;ETHIOPIC SYLLABLE ZHWA;Lo;0;L;;;;;N;;;;;
+12E8;ETHIOPIC SYLLABLE YA;Lo;0;L;;;;;N;;;;;
+12E9;ETHIOPIC SYLLABLE YU;Lo;0;L;;;;;N;;;;;
+12EA;ETHIOPIC SYLLABLE YI;Lo;0;L;;;;;N;;;;;
+12EB;ETHIOPIC SYLLABLE YAA;Lo;0;L;;;;;N;;;;;
+12EC;ETHIOPIC SYLLABLE YEE;Lo;0;L;;;;;N;;;;;
+12ED;ETHIOPIC SYLLABLE YE;Lo;0;L;;;;;N;;;;;
+12EE;ETHIOPIC SYLLABLE YO;Lo;0;L;;;;;N;;;;;
+12F0;ETHIOPIC SYLLABLE DA;Lo;0;L;;;;;N;;;;;
+12F1;ETHIOPIC SYLLABLE DU;Lo;0;L;;;;;N;;;;;
+12F2;ETHIOPIC SYLLABLE DI;Lo;0;L;;;;;N;;;;;
+12F3;ETHIOPIC SYLLABLE DAA;Lo;0;L;;;;;N;;;;;
+12F4;ETHIOPIC SYLLABLE DEE;Lo;0;L;;;;;N;;;;;
+12F5;ETHIOPIC SYLLABLE DE;Lo;0;L;;;;;N;;;;;
+12F6;ETHIOPIC SYLLABLE DO;Lo;0;L;;;;;N;;;;;
+12F7;ETHIOPIC SYLLABLE DWA;Lo;0;L;;;;;N;;;;;
+12F8;ETHIOPIC SYLLABLE DDA;Lo;0;L;;;;;N;;;;;
+12F9;ETHIOPIC SYLLABLE DDU;Lo;0;L;;;;;N;;;;;
+12FA;ETHIOPIC SYLLABLE DDI;Lo;0;L;;;;;N;;;;;
+12FB;ETHIOPIC SYLLABLE DDAA;Lo;0;L;;;;;N;;;;;
+12FC;ETHIOPIC SYLLABLE DDEE;Lo;0;L;;;;;N;;;;;
+12FD;ETHIOPIC SYLLABLE DDE;Lo;0;L;;;;;N;;;;;
+12FE;ETHIOPIC SYLLABLE DDO;Lo;0;L;;;;;N;;;;;
+12FF;ETHIOPIC SYLLABLE DDWA;Lo;0;L;;;;;N;;;;;
+1300;ETHIOPIC SYLLABLE JA;Lo;0;L;;;;;N;;;;;
+1301;ETHIOPIC SYLLABLE JU;Lo;0;L;;;;;N;;;;;
+1302;ETHIOPIC SYLLABLE JI;Lo;0;L;;;;;N;;;;;
+1303;ETHIOPIC SYLLABLE JAA;Lo;0;L;;;;;N;;;;;
+1304;ETHIOPIC SYLLABLE JEE;Lo;0;L;;;;;N;;;;;
+1305;ETHIOPIC SYLLABLE JE;Lo;0;L;;;;;N;;;;;
+1306;ETHIOPIC SYLLABLE JO;Lo;0;L;;;;;N;;;;;
+1307;ETHIOPIC SYLLABLE JWA;Lo;0;L;;;;;N;;;;;
+1308;ETHIOPIC SYLLABLE GA;Lo;0;L;;;;;N;;;;;
+1309;ETHIOPIC SYLLABLE GU;Lo;0;L;;;;;N;;;;;
+130A;ETHIOPIC SYLLABLE GI;Lo;0;L;;;;;N;;;;;
+130B;ETHIOPIC SYLLABLE GAA;Lo;0;L;;;;;N;;;;;
+130C;ETHIOPIC SYLLABLE GEE;Lo;0;L;;;;;N;;;;;
+130D;ETHIOPIC SYLLABLE GE;Lo;0;L;;;;;N;;;;;
+130E;ETHIOPIC SYLLABLE GO;Lo;0;L;;;;;N;;;;;
+1310;ETHIOPIC SYLLABLE GWA;Lo;0;L;;;;;N;;;;;
+1312;ETHIOPIC SYLLABLE GWI;Lo;0;L;;;;;N;;;;;
+1313;ETHIOPIC SYLLABLE GWAA;Lo;0;L;;;;;N;;;;;
+1314;ETHIOPIC SYLLABLE GWEE;Lo;0;L;;;;;N;;;;;
+1315;ETHIOPIC SYLLABLE GWE;Lo;0;L;;;;;N;;;;;
+1318;ETHIOPIC SYLLABLE GGA;Lo;0;L;;;;;N;;;;;
+1319;ETHIOPIC SYLLABLE GGU;Lo;0;L;;;;;N;;;;;
+131A;ETHIOPIC SYLLABLE GGI;Lo;0;L;;;;;N;;;;;
+131B;ETHIOPIC SYLLABLE GGAA;Lo;0;L;;;;;N;;;;;
+131C;ETHIOPIC SYLLABLE GGEE;Lo;0;L;;;;;N;;;;;
+131D;ETHIOPIC SYLLABLE GGE;Lo;0;L;;;;;N;;;;;
+131E;ETHIOPIC SYLLABLE GGO;Lo;0;L;;;;;N;;;;;
+1320;ETHIOPIC SYLLABLE THA;Lo;0;L;;;;;N;;;;;
+1321;ETHIOPIC SYLLABLE THU;Lo;0;L;;;;;N;;;;;
+1322;ETHIOPIC SYLLABLE THI;Lo;0;L;;;;;N;;;;;
+1323;ETHIOPIC SYLLABLE THAA;Lo;0;L;;;;;N;;;;;
+1324;ETHIOPIC SYLLABLE THEE;Lo;0;L;;;;;N;;;;;
+1325;ETHIOPIC SYLLABLE THE;Lo;0;L;;;;;N;;;;;
+1326;ETHIOPIC SYLLABLE THO;Lo;0;L;;;;;N;;;;;
+1327;ETHIOPIC SYLLABLE THWA;Lo;0;L;;;;;N;;;;;
+1328;ETHIOPIC SYLLABLE CHA;Lo;0;L;;;;;N;;;;;
+1329;ETHIOPIC SYLLABLE CHU;Lo;0;L;;;;;N;;;;;
+132A;ETHIOPIC SYLLABLE CHI;Lo;0;L;;;;;N;;;;;
+132B;ETHIOPIC SYLLABLE CHAA;Lo;0;L;;;;;N;;;;;
+132C;ETHIOPIC SYLLABLE CHEE;Lo;0;L;;;;;N;;;;;
+132D;ETHIOPIC SYLLABLE CHE;Lo;0;L;;;;;N;;;;;
+132E;ETHIOPIC SYLLABLE CHO;Lo;0;L;;;;;N;;;;;
+132F;ETHIOPIC SYLLABLE CHWA;Lo;0;L;;;;;N;;;;;
+1330;ETHIOPIC SYLLABLE PHA;Lo;0;L;;;;;N;;;;;
+1331;ETHIOPIC SYLLABLE PHU;Lo;0;L;;;;;N;;;;;
+1332;ETHIOPIC SYLLABLE PHI;Lo;0;L;;;;;N;;;;;
+1333;ETHIOPIC SYLLABLE PHAA;Lo;0;L;;;;;N;;;;;
+1334;ETHIOPIC SYLLABLE PHEE;Lo;0;L;;;;;N;;;;;
+1335;ETHIOPIC SYLLABLE PHE;Lo;0;L;;;;;N;;;;;
+1336;ETHIOPIC SYLLABLE PHO;Lo;0;L;;;;;N;;;;;
+1337;ETHIOPIC SYLLABLE PHWA;Lo;0;L;;;;;N;;;;;
+1338;ETHIOPIC SYLLABLE TSA;Lo;0;L;;;;;N;;;;;
+1339;ETHIOPIC SYLLABLE TSU;Lo;0;L;;;;;N;;;;;
+133A;ETHIOPIC SYLLABLE TSI;Lo;0;L;;;;;N;;;;;
+133B;ETHIOPIC SYLLABLE TSAA;Lo;0;L;;;;;N;;;;;
+133C;ETHIOPIC SYLLABLE TSEE;Lo;0;L;;;;;N;;;;;
+133D;ETHIOPIC SYLLABLE TSE;Lo;0;L;;;;;N;;;;;
+133E;ETHIOPIC SYLLABLE TSO;Lo;0;L;;;;;N;;;;;
+133F;ETHIOPIC SYLLABLE TSWA;Lo;0;L;;;;;N;;;;;
+1340;ETHIOPIC SYLLABLE TZA;Lo;0;L;;;;;N;;;;;
+1341;ETHIOPIC SYLLABLE TZU;Lo;0;L;;;;;N;;;;;
+1342;ETHIOPIC SYLLABLE TZI;Lo;0;L;;;;;N;;;;;
+1343;ETHIOPIC SYLLABLE TZAA;Lo;0;L;;;;;N;;;;;
+1344;ETHIOPIC SYLLABLE TZEE;Lo;0;L;;;;;N;;;;;
+1345;ETHIOPIC SYLLABLE TZE;Lo;0;L;;;;;N;;;;;
+1346;ETHIOPIC SYLLABLE TZO;Lo;0;L;;;;;N;;;;;
+1348;ETHIOPIC SYLLABLE FA;Lo;0;L;;;;;N;;;;;
+1349;ETHIOPIC SYLLABLE FU;Lo;0;L;;;;;N;;;;;
+134A;ETHIOPIC SYLLABLE FI;Lo;0;L;;;;;N;;;;;
+134B;ETHIOPIC SYLLABLE FAA;Lo;0;L;;;;;N;;;;;
+134C;ETHIOPIC SYLLABLE FEE;Lo;0;L;;;;;N;;;;;
+134D;ETHIOPIC SYLLABLE FE;Lo;0;L;;;;;N;;;;;
+134E;ETHIOPIC SYLLABLE FO;Lo;0;L;;;;;N;;;;;
+134F;ETHIOPIC SYLLABLE FWA;Lo;0;L;;;;;N;;;;;
+1350;ETHIOPIC SYLLABLE PA;Lo;0;L;;;;;N;;;;;
+1351;ETHIOPIC SYLLABLE PU;Lo;0;L;;;;;N;;;;;
+1352;ETHIOPIC SYLLABLE PI;Lo;0;L;;;;;N;;;;;
+1353;ETHIOPIC SYLLABLE PAA;Lo;0;L;;;;;N;;;;;
+1354;ETHIOPIC SYLLABLE PEE;Lo;0;L;;;;;N;;;;;
+1355;ETHIOPIC SYLLABLE PE;Lo;0;L;;;;;N;;;;;
+1356;ETHIOPIC SYLLABLE PO;Lo;0;L;;;;;N;;;;;
+1357;ETHIOPIC SYLLABLE PWA;Lo;0;L;;;;;N;;;;;
+1358;ETHIOPIC SYLLABLE RYA;Lo;0;L;;;;;N;;;;;
+1359;ETHIOPIC SYLLABLE MYA;Lo;0;L;;;;;N;;;;;
+135A;ETHIOPIC SYLLABLE FYA;Lo;0;L;;;;;N;;;;;
+1361;ETHIOPIC WORDSPACE;Po;0;L;;;;;N;;;;;
+1362;ETHIOPIC FULL STOP;Po;0;L;;;;;N;;;;;
+1363;ETHIOPIC COMMA;Po;0;L;;;;;N;;;;;
+1364;ETHIOPIC SEMICOLON;Po;0;L;;;;;N;;;;;
+1365;ETHIOPIC COLON;Po;0;L;;;;;N;;;;;
+1366;ETHIOPIC PREFACE COLON;Po;0;L;;;;;N;;;;;
+1367;ETHIOPIC QUESTION MARK;Po;0;L;;;;;N;;;;;
+1368;ETHIOPIC PARAGRAPH SEPARATOR;Po;0;L;;;;;N;;;;;
+1369;ETHIOPIC DIGIT ONE;Nd;0;L;;;1;1;N;;;;;
+136A;ETHIOPIC DIGIT TWO;Nd;0;L;;;2;2;N;;;;;
+136B;ETHIOPIC DIGIT THREE;Nd;0;L;;;3;3;N;;;;;
+136C;ETHIOPIC DIGIT FOUR;Nd;0;L;;;4;4;N;;;;;
+136D;ETHIOPIC DIGIT FIVE;Nd;0;L;;;5;5;N;;;;;
+136E;ETHIOPIC DIGIT SIX;Nd;0;L;;;6;6;N;;;;;
+136F;ETHIOPIC DIGIT SEVEN;Nd;0;L;;;7;7;N;;;;;
+1370;ETHIOPIC DIGIT EIGHT;Nd;0;L;;;8;8;N;;;;;
+1371;ETHIOPIC DIGIT NINE;Nd;0;L;;;9;9;N;;;;;
+1372;ETHIOPIC NUMBER TEN;No;0;L;;;;10;N;;;;;
+1373;ETHIOPIC NUMBER TWENTY;No;0;L;;;;20;N;;;;;
+1374;ETHIOPIC NUMBER THIRTY;No;0;L;;;;30;N;;;;;
+1375;ETHIOPIC NUMBER FORTY;No;0;L;;;;40;N;;;;;
+1376;ETHIOPIC NUMBER FIFTY;No;0;L;;;;50;N;;;;;
+1377;ETHIOPIC NUMBER SIXTY;No;0;L;;;;60;N;;;;;
+1378;ETHIOPIC NUMBER SEVENTY;No;0;L;;;;70;N;;;;;
+1379;ETHIOPIC NUMBER EIGHTY;No;0;L;;;;80;N;;;;;
+137A;ETHIOPIC NUMBER NINETY;No;0;L;;;;90;N;;;;;
+137B;ETHIOPIC NUMBER HUNDRED;No;0;L;;;;100;N;;;;;
+137C;ETHIOPIC NUMBER TEN THOUSAND;No;0;L;;;;10000;N;;;;;
+13A0;CHEROKEE LETTER A;Lo;0;L;;;;;N;;;;;
+13A1;CHEROKEE LETTER E;Lo;0;L;;;;;N;;;;;
+13A2;CHEROKEE LETTER I;Lo;0;L;;;;;N;;;;;
+13A3;CHEROKEE LETTER O;Lo;0;L;;;;;N;;;;;
+13A4;CHEROKEE LETTER U;Lo;0;L;;;;;N;;;;;
+13A5;CHEROKEE LETTER V;Lo;0;L;;;;;N;;;;;
+13A6;CHEROKEE LETTER GA;Lo;0;L;;;;;N;;;;;
+13A7;CHEROKEE LETTER KA;Lo;0;L;;;;;N;;;;;
+13A8;CHEROKEE LETTER GE;Lo;0;L;;;;;N;;;;;
+13A9;CHEROKEE LETTER GI;Lo;0;L;;;;;N;;;;;
+13AA;CHEROKEE LETTER GO;Lo;0;L;;;;;N;;;;;
+13AB;CHEROKEE LETTER GU;Lo;0;L;;;;;N;;;;;
+13AC;CHEROKEE LETTER GV;Lo;0;L;;;;;N;;;;;
+13AD;CHEROKEE LETTER HA;Lo;0;L;;;;;N;;;;;
+13AE;CHEROKEE LETTER HE;Lo;0;L;;;;;N;;;;;
+13AF;CHEROKEE LETTER HI;Lo;0;L;;;;;N;;;;;
+13B0;CHEROKEE LETTER HO;Lo;0;L;;;;;N;;;;;
+13B1;CHEROKEE LETTER HU;Lo;0;L;;;;;N;;;;;
+13B2;CHEROKEE LETTER HV;Lo;0;L;;;;;N;;;;;
+13B3;CHEROKEE LETTER LA;Lo;0;L;;;;;N;;;;;
+13B4;CHEROKEE LETTER LE;Lo;0;L;;;;;N;;;;;
+13B5;CHEROKEE LETTER LI;Lo;0;L;;;;;N;;;;;
+13B6;CHEROKEE LETTER LO;Lo;0;L;;;;;N;;;;;
+13B7;CHEROKEE LETTER LU;Lo;0;L;;;;;N;;;;;
+13B8;CHEROKEE LETTER LV;Lo;0;L;;;;;N;;;;;
+13B9;CHEROKEE LETTER MA;Lo;0;L;;;;;N;;;;;
+13BA;CHEROKEE LETTER ME;Lo;0;L;;;;;N;;;;;
+13BB;CHEROKEE LETTER MI;Lo;0;L;;;;;N;;;;;
+13BC;CHEROKEE LETTER MO;Lo;0;L;;;;;N;;;;;
+13BD;CHEROKEE LETTER MU;Lo;0;L;;;;;N;;;;;
+13BE;CHEROKEE LETTER NA;Lo;0;L;;;;;N;;;;;
+13BF;CHEROKEE LETTER HNA;Lo;0;L;;;;;N;;;;;
+13C0;CHEROKEE LETTER NAH;Lo;0;L;;;;;N;;;;;
+13C1;CHEROKEE LETTER NE;Lo;0;L;;;;;N;;;;;
+13C2;CHEROKEE LETTER NI;Lo;0;L;;;;;N;;;;;
+13C3;CHEROKEE LETTER NO;Lo;0;L;;;;;N;;;;;
+13C4;CHEROKEE LETTER NU;Lo;0;L;;;;;N;;;;;
+13C5;CHEROKEE LETTER NV;Lo;0;L;;;;;N;;;;;
+13C6;CHEROKEE LETTER QUA;Lo;0;L;;;;;N;;;;;
+13C7;CHEROKEE LETTER QUE;Lo;0;L;;;;;N;;;;;
+13C8;CHEROKEE LETTER QUI;Lo;0;L;;;;;N;;;;;
+13C9;CHEROKEE LETTER QUO;Lo;0;L;;;;;N;;;;;
+13CA;CHEROKEE LETTER QUU;Lo;0;L;;;;;N;;;;;
+13CB;CHEROKEE LETTER QUV;Lo;0;L;;;;;N;;;;;
+13CC;CHEROKEE LETTER SA;Lo;0;L;;;;;N;;;;;
+13CD;CHEROKEE LETTER S;Lo;0;L;;;;;N;;;;;
+13CE;CHEROKEE LETTER SE;Lo;0;L;;;;;N;;;;;
+13CF;CHEROKEE LETTER SI;Lo;0;L;;;;;N;;;;;
+13D0;CHEROKEE LETTER SO;Lo;0;L;;;;;N;;;;;
+13D1;CHEROKEE LETTER SU;Lo;0;L;;;;;N;;;;;
+13D2;CHEROKEE LETTER SV;Lo;0;L;;;;;N;;;;;
+13D3;CHEROKEE LETTER DA;Lo;0;L;;;;;N;;;;;
+13D4;CHEROKEE LETTER TA;Lo;0;L;;;;;N;;;;;
+13D5;CHEROKEE LETTER DE;Lo;0;L;;;;;N;;;;;
+13D6;CHEROKEE LETTER TE;Lo;0;L;;;;;N;;;;;
+13D7;CHEROKEE LETTER DI;Lo;0;L;;;;;N;;;;;
+13D8;CHEROKEE LETTER TI;Lo;0;L;;;;;N;;;;;
+13D9;CHEROKEE LETTER DO;Lo;0;L;;;;;N;;;;;
+13DA;CHEROKEE LETTER DU;Lo;0;L;;;;;N;;;;;
+13DB;CHEROKEE LETTER DV;Lo;0;L;;;;;N;;;;;
+13DC;CHEROKEE LETTER DLA;Lo;0;L;;;;;N;;;;;
+13DD;CHEROKEE LETTER TLA;Lo;0;L;;;;;N;;;;;
+13DE;CHEROKEE LETTER TLE;Lo;0;L;;;;;N;;;;;
+13DF;CHEROKEE LETTER TLI;Lo;0;L;;;;;N;;;;;
+13E0;CHEROKEE LETTER TLO;Lo;0;L;;;;;N;;;;;
+13E1;CHEROKEE LETTER TLU;Lo;0;L;;;;;N;;;;;
+13E2;CHEROKEE LETTER TLV;Lo;0;L;;;;;N;;;;;
+13E3;CHEROKEE LETTER TSA;Lo;0;L;;;;;N;;;;;
+13E4;CHEROKEE LETTER TSE;Lo;0;L;;;;;N;;;;;
+13E5;CHEROKEE LETTER TSI;Lo;0;L;;;;;N;;;;;
+13E6;CHEROKEE LETTER TSO;Lo;0;L;;;;;N;;;;;
+13E7;CHEROKEE LETTER TSU;Lo;0;L;;;;;N;;;;;
+13E8;CHEROKEE LETTER TSV;Lo;0;L;;;;;N;;;;;
+13E9;CHEROKEE LETTER WA;Lo;0;L;;;;;N;;;;;
+13EA;CHEROKEE LETTER WE;Lo;0;L;;;;;N;;;;;
+13EB;CHEROKEE LETTER WI;Lo;0;L;;;;;N;;;;;
+13EC;CHEROKEE LETTER WO;Lo;0;L;;;;;N;;;;;
+13ED;CHEROKEE LETTER WU;Lo;0;L;;;;;N;;;;;
+13EE;CHEROKEE LETTER WV;Lo;0;L;;;;;N;;;;;
+13EF;CHEROKEE LETTER YA;Lo;0;L;;;;;N;;;;;
+13F0;CHEROKEE LETTER YE;Lo;0;L;;;;;N;;;;;
+13F1;CHEROKEE LETTER YI;Lo;0;L;;;;;N;;;;;
+13F2;CHEROKEE LETTER YO;Lo;0;L;;;;;N;;;;;
+13F3;CHEROKEE LETTER YU;Lo;0;L;;;;;N;;;;;
+13F4;CHEROKEE LETTER YV;Lo;0;L;;;;;N;;;;;
+1401;CANADIAN SYLLABICS E;Lo;0;L;;;;;N;;;;;
+1402;CANADIAN SYLLABICS AAI;Lo;0;L;;;;;N;;;;;
+1403;CANADIAN SYLLABICS I;Lo;0;L;;;;;N;;;;;
+1404;CANADIAN SYLLABICS II;Lo;0;L;;;;;N;;;;;
+1405;CANADIAN SYLLABICS O;Lo;0;L;;;;;N;;;;;
+1406;CANADIAN SYLLABICS OO;Lo;0;L;;;;;N;;;;;
+1407;CANADIAN SYLLABICS Y-CREE OO;Lo;0;L;;;;;N;;;;;
+1408;CANADIAN SYLLABICS CARRIER EE;Lo;0;L;;;;;N;;;;;
+1409;CANADIAN SYLLABICS CARRIER I;Lo;0;L;;;;;N;;;;;
+140A;CANADIAN SYLLABICS A;Lo;0;L;;;;;N;;;;;
+140B;CANADIAN SYLLABICS AA;Lo;0;L;;;;;N;;;;;
+140C;CANADIAN SYLLABICS WE;Lo;0;L;;;;;N;;;;;
+140D;CANADIAN SYLLABICS WEST-CREE WE;Lo;0;L;;;;;N;;;;;
+140E;CANADIAN SYLLABICS WI;Lo;0;L;;;;;N;;;;;
+140F;CANADIAN SYLLABICS WEST-CREE WI;Lo;0;L;;;;;N;;;;;
+1410;CANADIAN SYLLABICS WII;Lo;0;L;;;;;N;;;;;
+1411;CANADIAN SYLLABICS WEST-CREE WII;Lo;0;L;;;;;N;;;;;
+1412;CANADIAN SYLLABICS WO;Lo;0;L;;;;;N;;;;;
+1413;CANADIAN SYLLABICS WEST-CREE WO;Lo;0;L;;;;;N;;;;;
+1414;CANADIAN SYLLABICS WOO;Lo;0;L;;;;;N;;;;;
+1415;CANADIAN SYLLABICS WEST-CREE WOO;Lo;0;L;;;;;N;;;;;
+1416;CANADIAN SYLLABICS NASKAPI WOO;Lo;0;L;;;;;N;;;;;
+1417;CANADIAN SYLLABICS WA;Lo;0;L;;;;;N;;;;;
+1418;CANADIAN SYLLABICS WEST-CREE WA;Lo;0;L;;;;;N;;;;;
+1419;CANADIAN SYLLABICS WAA;Lo;0;L;;;;;N;;;;;
+141A;CANADIAN SYLLABICS WEST-CREE WAA;Lo;0;L;;;;;N;;;;;
+141B;CANADIAN SYLLABICS NASKAPI WAA;Lo;0;L;;;;;N;;;;;
+141C;CANADIAN SYLLABICS AI;Lo;0;L;;;;;N;;;;;
+141D;CANADIAN SYLLABICS Y-CREE W;Lo;0;L;;;;;N;;;;;
+141E;CANADIAN SYLLABICS GLOTTAL STOP;Lo;0;L;;;;;N;;;;;
+141F;CANADIAN SYLLABICS FINAL ACUTE;Lo;0;L;;;;;N;;;;;
+1420;CANADIAN SYLLABICS FINAL GRAVE;Lo;0;L;;;;;N;;;;;
+1421;CANADIAN SYLLABICS FINAL BOTTOM HALF RING;Lo;0;L;;;;;N;;;;;
+1422;CANADIAN SYLLABICS FINAL TOP HALF RING;Lo;0;L;;;;;N;;;;;
+1423;CANADIAN SYLLABICS FINAL RIGHT HALF RING;Lo;0;L;;;;;N;;;;;
+1424;CANADIAN SYLLABICS FINAL RING;Lo;0;L;;;;;N;;;;;
+1425;CANADIAN SYLLABICS FINAL DOUBLE ACUTE;Lo;0;L;;;;;N;;;;;
+1426;CANADIAN SYLLABICS FINAL DOUBLE SHORT VERTICAL STROKES;Lo;0;L;;;;;N;;;;;
+1427;CANADIAN SYLLABICS FINAL MIDDLE DOT;Lo;0;L;;;;;N;;;;;
+1428;CANADIAN SYLLABICS FINAL SHORT HORIZONTAL STROKE;Lo;0;L;;;;;N;;;;;
+1429;CANADIAN SYLLABICS FINAL PLUS;Lo;0;L;;;;;N;;;;;
+142A;CANADIAN SYLLABICS FINAL DOWN TACK;Lo;0;L;;;;;N;;;;;
+142B;CANADIAN SYLLABICS EN;Lo;0;L;;;;;N;;;;;
+142C;CANADIAN SYLLABICS IN;Lo;0;L;;;;;N;;;;;
+142D;CANADIAN SYLLABICS ON;Lo;0;L;;;;;N;;;;;
+142E;CANADIAN SYLLABICS AN;Lo;0;L;;;;;N;;;;;
+142F;CANADIAN SYLLABICS PE;Lo;0;L;;;;;N;;;;;
+1430;CANADIAN SYLLABICS PAAI;Lo;0;L;;;;;N;;;;;
+1431;CANADIAN SYLLABICS PI;Lo;0;L;;;;;N;;;;;
+1432;CANADIAN SYLLABICS PII;Lo;0;L;;;;;N;;;;;
+1433;CANADIAN SYLLABICS PO;Lo;0;L;;;;;N;;;;;
+1434;CANADIAN SYLLABICS POO;Lo;0;L;;;;;N;;;;;
+1435;CANADIAN SYLLABICS Y-CREE POO;Lo;0;L;;;;;N;;;;;
+1436;CANADIAN SYLLABICS CARRIER HEE;Lo;0;L;;;;;N;;;;;
+1437;CANADIAN SYLLABICS CARRIER HI;Lo;0;L;;;;;N;;;;;
+1438;CANADIAN SYLLABICS PA;Lo;0;L;;;;;N;;;;;
+1439;CANADIAN SYLLABICS PAA;Lo;0;L;;;;;N;;;;;
+143A;CANADIAN SYLLABICS PWE;Lo;0;L;;;;;N;;;;;
+143B;CANADIAN SYLLABICS WEST-CREE PWE;Lo;0;L;;;;;N;;;;;
+143C;CANADIAN SYLLABICS PWI;Lo;0;L;;;;;N;;;;;
+143D;CANADIAN SYLLABICS WEST-CREE PWI;Lo;0;L;;;;;N;;;;;
+143E;CANADIAN SYLLABICS PWII;Lo;0;L;;;;;N;;;;;
+143F;CANADIAN SYLLABICS WEST-CREE PWII;Lo;0;L;;;;;N;;;;;
+1440;CANADIAN SYLLABICS PWO;Lo;0;L;;;;;N;;;;;
+1441;CANADIAN SYLLABICS WEST-CREE PWO;Lo;0;L;;;;;N;;;;;
+1442;CANADIAN SYLLABICS PWOO;Lo;0;L;;;;;N;;;;;
+1443;CANADIAN SYLLABICS WEST-CREE PWOO;Lo;0;L;;;;;N;;;;;
+1444;CANADIAN SYLLABICS PWA;Lo;0;L;;;;;N;;;;;
+1445;CANADIAN SYLLABICS WEST-CREE PWA;Lo;0;L;;;;;N;;;;;
+1446;CANADIAN SYLLABICS PWAA;Lo;0;L;;;;;N;;;;;
+1447;CANADIAN SYLLABICS WEST-CREE PWAA;Lo;0;L;;;;;N;;;;;
+1448;CANADIAN SYLLABICS Y-CREE PWAA;Lo;0;L;;;;;N;;;;;
+1449;CANADIAN SYLLABICS P;Lo;0;L;;;;;N;;;;;
+144A;CANADIAN SYLLABICS WEST-CREE P;Lo;0;L;;;;;N;;;;;
+144B;CANADIAN SYLLABICS CARRIER H;Lo;0;L;;;;;N;;;;;
+144C;CANADIAN SYLLABICS TE;Lo;0;L;;;;;N;;;;;
+144D;CANADIAN SYLLABICS TAAI;Lo;0;L;;;;;N;;;;;
+144E;CANADIAN SYLLABICS TI;Lo;0;L;;;;;N;;;;;
+144F;CANADIAN SYLLABICS TII;Lo;0;L;;;;;N;;;;;
+1450;CANADIAN SYLLABICS TO;Lo;0;L;;;;;N;;;;;
+1451;CANADIAN SYLLABICS TOO;Lo;0;L;;;;;N;;;;;
+1452;CANADIAN SYLLABICS Y-CREE TOO;Lo;0;L;;;;;N;;;;;
+1453;CANADIAN SYLLABICS CARRIER DEE;Lo;0;L;;;;;N;;;;;
+1454;CANADIAN SYLLABICS CARRIER DI;Lo;0;L;;;;;N;;;;;
+1455;CANADIAN SYLLABICS TA;Lo;0;L;;;;;N;;;;;
+1456;CANADIAN SYLLABICS TAA;Lo;0;L;;;;;N;;;;;
+1457;CANADIAN SYLLABICS TWE;Lo;0;L;;;;;N;;;;;
+1458;CANADIAN SYLLABICS WEST-CREE TWE;Lo;0;L;;;;;N;;;;;
+1459;CANADIAN SYLLABICS TWI;Lo;0;L;;;;;N;;;;;
+145A;CANADIAN SYLLABICS WEST-CREE TWI;Lo;0;L;;;;;N;;;;;
+145B;CANADIAN SYLLABICS TWII;Lo;0;L;;;;;N;;;;;
+145C;CANADIAN SYLLABICS WEST-CREE TWII;Lo;0;L;;;;;N;;;;;
+145D;CANADIAN SYLLABICS TWO;Lo;0;L;;;;;N;;;;;
+145E;CANADIAN SYLLABICS WEST-CREE TWO;Lo;0;L;;;;;N;;;;;
+145F;CANADIAN SYLLABICS TWOO;Lo;0;L;;;;;N;;;;;
+1460;CANADIAN SYLLABICS WEST-CREE TWOO;Lo;0;L;;;;;N;;;;;
+1461;CANADIAN SYLLABICS TWA;Lo;0;L;;;;;N;;;;;
+1462;CANADIAN SYLLABICS WEST-CREE TWA;Lo;0;L;;;;;N;;;;;
+1463;CANADIAN SYLLABICS TWAA;Lo;0;L;;;;;N;;;;;
+1464;CANADIAN SYLLABICS WEST-CREE TWAA;Lo;0;L;;;;;N;;;;;
+1465;CANADIAN SYLLABICS NASKAPI TWAA;Lo;0;L;;;;;N;;;;;
+1466;CANADIAN SYLLABICS T;Lo;0;L;;;;;N;;;;;
+1467;CANADIAN SYLLABICS TTE;Lo;0;L;;;;;N;;;;;
+1468;CANADIAN SYLLABICS TTI;Lo;0;L;;;;;N;;;;;
+1469;CANADIAN SYLLABICS TTO;Lo;0;L;;;;;N;;;;;
+146A;CANADIAN SYLLABICS TTA;Lo;0;L;;;;;N;;;;;
+146B;CANADIAN SYLLABICS KE;Lo;0;L;;;;;N;;;;;
+146C;CANADIAN SYLLABICS KAAI;Lo;0;L;;;;;N;;;;;
+146D;CANADIAN SYLLABICS KI;Lo;0;L;;;;;N;;;;;
+146E;CANADIAN SYLLABICS KII;Lo;0;L;;;;;N;;;;;
+146F;CANADIAN SYLLABICS KO;Lo;0;L;;;;;N;;;;;
+1470;CANADIAN SYLLABICS KOO;Lo;0;L;;;;;N;;;;;
+1471;CANADIAN SYLLABICS Y-CREE KOO;Lo;0;L;;;;;N;;;;;
+1472;CANADIAN SYLLABICS KA;Lo;0;L;;;;;N;;;;;
+1473;CANADIAN SYLLABICS KAA;Lo;0;L;;;;;N;;;;;
+1474;CANADIAN SYLLABICS KWE;Lo;0;L;;;;;N;;;;;
+1475;CANADIAN SYLLABICS WEST-CREE KWE;Lo;0;L;;;;;N;;;;;
+1476;CANADIAN SYLLABICS KWI;Lo;0;L;;;;;N;;;;;
+1477;CANADIAN SYLLABICS WEST-CREE KWI;Lo;0;L;;;;;N;;;;;
+1478;CANADIAN SYLLABICS KWII;Lo;0;L;;;;;N;;;;;
+1479;CANADIAN SYLLABICS WEST-CREE KWII;Lo;0;L;;;;;N;;;;;
+147A;CANADIAN SYLLABICS KWO;Lo;0;L;;;;;N;;;;;
+147B;CANADIAN SYLLABICS WEST-CREE KWO;Lo;0;L;;;;;N;;;;;
+147C;CANADIAN SYLLABICS KWOO;Lo;0;L;;;;;N;;;;;
+147D;CANADIAN SYLLABICS WEST-CREE KWOO;Lo;0;L;;;;;N;;;;;
+147E;CANADIAN SYLLABICS KWA;Lo;0;L;;;;;N;;;;;
+147F;CANADIAN SYLLABICS WEST-CREE KWA;Lo;0;L;;;;;N;;;;;
+1480;CANADIAN SYLLABICS KWAA;Lo;0;L;;;;;N;;;;;
+1481;CANADIAN SYLLABICS WEST-CREE KWAA;Lo;0;L;;;;;N;;;;;
+1482;CANADIAN SYLLABICS NASKAPI KWAA;Lo;0;L;;;;;N;;;;;
+1483;CANADIAN SYLLABICS K;Lo;0;L;;;;;N;;;;;
+1484;CANADIAN SYLLABICS KW;Lo;0;L;;;;;N;;;;;
+1485;CANADIAN SYLLABICS SOUTH-SLAVEY KEH;Lo;0;L;;;;;N;;;;;
+1486;CANADIAN SYLLABICS SOUTH-SLAVEY KIH;Lo;0;L;;;;;N;;;;;
+1487;CANADIAN SYLLABICS SOUTH-SLAVEY KOH;Lo;0;L;;;;;N;;;;;
+1488;CANADIAN SYLLABICS SOUTH-SLAVEY KAH;Lo;0;L;;;;;N;;;;;
+1489;CANADIAN SYLLABICS CE;Lo;0;L;;;;;N;;;;;
+148A;CANADIAN SYLLABICS CAAI;Lo;0;L;;;;;N;;;;;
+148B;CANADIAN SYLLABICS CI;Lo;0;L;;;;;N;;;;;
+148C;CANADIAN SYLLABICS CII;Lo;0;L;;;;;N;;;;;
+148D;CANADIAN SYLLABICS CO;Lo;0;L;;;;;N;;;;;
+148E;CANADIAN SYLLABICS COO;Lo;0;L;;;;;N;;;;;
+148F;CANADIAN SYLLABICS Y-CREE COO;Lo;0;L;;;;;N;;;;;
+1490;CANADIAN SYLLABICS CA;Lo;0;L;;;;;N;;;;;
+1491;CANADIAN SYLLABICS CAA;Lo;0;L;;;;;N;;;;;
+1492;CANADIAN SYLLABICS CWE;Lo;0;L;;;;;N;;;;;
+1493;CANADIAN SYLLABICS WEST-CREE CWE;Lo;0;L;;;;;N;;;;;
+1494;CANADIAN SYLLABICS CWI;Lo;0;L;;;;;N;;;;;
+1495;CANADIAN SYLLABICS WEST-CREE CWI;Lo;0;L;;;;;N;;;;;
+1496;CANADIAN SYLLABICS CWII;Lo;0;L;;;;;N;;;;;
+1497;CANADIAN SYLLABICS WEST-CREE CWII;Lo;0;L;;;;;N;;;;;
+1498;CANADIAN SYLLABICS CWO;Lo;0;L;;;;;N;;;;;
+1499;CANADIAN SYLLABICS WEST-CREE CWO;Lo;0;L;;;;;N;;;;;
+149A;CANADIAN SYLLABICS CWOO;Lo;0;L;;;;;N;;;;;
+149B;CANADIAN SYLLABICS WEST-CREE CWOO;Lo;0;L;;;;;N;;;;;
+149C;CANADIAN SYLLABICS CWA;Lo;0;L;;;;;N;;;;;
+149D;CANADIAN SYLLABICS WEST-CREE CWA;Lo;0;L;;;;;N;;;;;
+149E;CANADIAN SYLLABICS CWAA;Lo;0;L;;;;;N;;;;;
+149F;CANADIAN SYLLABICS WEST-CREE CWAA;Lo;0;L;;;;;N;;;;;
+14A0;CANADIAN SYLLABICS NASKAPI CWAA;Lo;0;L;;;;;N;;;;;
+14A1;CANADIAN SYLLABICS C;Lo;0;L;;;;;N;;;;;
+14A2;CANADIAN SYLLABICS SAYISI TH;Lo;0;L;;;;;N;;;;;
+14A3;CANADIAN SYLLABICS ME;Lo;0;L;;;;;N;;;;;
+14A4;CANADIAN SYLLABICS MAAI;Lo;0;L;;;;;N;;;;;
+14A5;CANADIAN SYLLABICS MI;Lo;0;L;;;;;N;;;;;
+14A6;CANADIAN SYLLABICS MII;Lo;0;L;;;;;N;;;;;
+14A7;CANADIAN SYLLABICS MO;Lo;0;L;;;;;N;;;;;
+14A8;CANADIAN SYLLABICS MOO;Lo;0;L;;;;;N;;;;;
+14A9;CANADIAN SYLLABICS Y-CREE MOO;Lo;0;L;;;;;N;;;;;
+14AA;CANADIAN SYLLABICS MA;Lo;0;L;;;;;N;;;;;
+14AB;CANADIAN SYLLABICS MAA;Lo;0;L;;;;;N;;;;;
+14AC;CANADIAN SYLLABICS MWE;Lo;0;L;;;;;N;;;;;
+14AD;CANADIAN SYLLABICS WEST-CREE MWE;Lo;0;L;;;;;N;;;;;
+14AE;CANADIAN SYLLABICS MWI;Lo;0;L;;;;;N;;;;;
+14AF;CANADIAN SYLLABICS WEST-CREE MWI;Lo;0;L;;;;;N;;;;;
+14B0;CANADIAN SYLLABICS MWII;Lo;0;L;;;;;N;;;;;
+14B1;CANADIAN SYLLABICS WEST-CREE MWII;Lo;0;L;;;;;N;;;;;
+14B2;CANADIAN SYLLABICS MWO;Lo;0;L;;;;;N;;;;;
+14B3;CANADIAN SYLLABICS WEST-CREE MWO;Lo;0;L;;;;;N;;;;;
+14B4;CANADIAN SYLLABICS MWOO;Lo;0;L;;;;;N;;;;;
+14B5;CANADIAN SYLLABICS WEST-CREE MWOO;Lo;0;L;;;;;N;;;;;
+14B6;CANADIAN SYLLABICS MWA;Lo;0;L;;;;;N;;;;;
+14B7;CANADIAN SYLLABICS WEST-CREE MWA;Lo;0;L;;;;;N;;;;;
+14B8;CANADIAN SYLLABICS MWAA;Lo;0;L;;;;;N;;;;;
+14B9;CANADIAN SYLLABICS WEST-CREE MWAA;Lo;0;L;;;;;N;;;;;
+14BA;CANADIAN SYLLABICS NASKAPI MWAA;Lo;0;L;;;;;N;;;;;
+14BB;CANADIAN SYLLABICS M;Lo;0;L;;;;;N;;;;;
+14BC;CANADIAN SYLLABICS WEST-CREE M;Lo;0;L;;;;;N;;;;;
+14BD;CANADIAN SYLLABICS MH;Lo;0;L;;;;;N;;;;;
+14BE;CANADIAN SYLLABICS ATHAPASCAN M;Lo;0;L;;;;;N;;;;;
+14BF;CANADIAN SYLLABICS SAYISI M;Lo;0;L;;;;;N;;;;;
+14C0;CANADIAN SYLLABICS NE;Lo;0;L;;;;;N;;;;;
+14C1;CANADIAN SYLLABICS NAAI;Lo;0;L;;;;;N;;;;;
+14C2;CANADIAN SYLLABICS NI;Lo;0;L;;;;;N;;;;;
+14C3;CANADIAN SYLLABICS NII;Lo;0;L;;;;;N;;;;;
+14C4;CANADIAN SYLLABICS NO;Lo;0;L;;;;;N;;;;;
+14C5;CANADIAN SYLLABICS NOO;Lo;0;L;;;;;N;;;;;
+14C6;CANADIAN SYLLABICS Y-CREE NOO;Lo;0;L;;;;;N;;;;;
+14C7;CANADIAN SYLLABICS NA;Lo;0;L;;;;;N;;;;;
+14C8;CANADIAN SYLLABICS NAA;Lo;0;L;;;;;N;;;;;
+14C9;CANADIAN SYLLABICS NWE;Lo;0;L;;;;;N;;;;;
+14CA;CANADIAN SYLLABICS WEST-CREE NWE;Lo;0;L;;;;;N;;;;;
+14CB;CANADIAN SYLLABICS NWA;Lo;0;L;;;;;N;;;;;
+14CC;CANADIAN SYLLABICS WEST-CREE NWA;Lo;0;L;;;;;N;;;;;
+14CD;CANADIAN SYLLABICS NWAA;Lo;0;L;;;;;N;;;;;
+14CE;CANADIAN SYLLABICS WEST-CREE NWAA;Lo;0;L;;;;;N;;;;;
+14CF;CANADIAN SYLLABICS NASKAPI NWAA;Lo;0;L;;;;;N;;;;;
+14D0;CANADIAN SYLLABICS N;Lo;0;L;;;;;N;;;;;
+14D1;CANADIAN SYLLABICS CARRIER NG;Lo;0;L;;;;;N;;;;;
+14D2;CANADIAN SYLLABICS NH;Lo;0;L;;;;;N;;;;;
+14D3;CANADIAN SYLLABICS LE;Lo;0;L;;;;;N;;;;;
+14D4;CANADIAN SYLLABICS LAAI;Lo;0;L;;;;;N;;;;;
+14D5;CANADIAN SYLLABICS LI;Lo;0;L;;;;;N;;;;;
+14D6;CANADIAN SYLLABICS LII;Lo;0;L;;;;;N;;;;;
+14D7;CANADIAN SYLLABICS LO;Lo;0;L;;;;;N;;;;;
+14D8;CANADIAN SYLLABICS LOO;Lo;0;L;;;;;N;;;;;
+14D9;CANADIAN SYLLABICS Y-CREE LOO;Lo;0;L;;;;;N;;;;;
+14DA;CANADIAN SYLLABICS LA;Lo;0;L;;;;;N;;;;;
+14DB;CANADIAN SYLLABICS LAA;Lo;0;L;;;;;N;;;;;
+14DC;CANADIAN SYLLABICS LWE;Lo;0;L;;;;;N;;;;;
+14DD;CANADIAN SYLLABICS WEST-CREE LWE;Lo;0;L;;;;;N;;;;;
+14DE;CANADIAN SYLLABICS LWI;Lo;0;L;;;;;N;;;;;
+14DF;CANADIAN SYLLABICS WEST-CREE LWI;Lo;0;L;;;;;N;;;;;
+14E0;CANADIAN SYLLABICS LWII;Lo;0;L;;;;;N;;;;;
+14E1;CANADIAN SYLLABICS WEST-CREE LWII;Lo;0;L;;;;;N;;;;;
+14E2;CANADIAN SYLLABICS LWO;Lo;0;L;;;;;N;;;;;
+14E3;CANADIAN SYLLABICS WEST-CREE LWO;Lo;0;L;;;;;N;;;;;
+14E4;CANADIAN SYLLABICS LWOO;Lo;0;L;;;;;N;;;;;
+14E5;CANADIAN SYLLABICS WEST-CREE LWOO;Lo;0;L;;;;;N;;;;;
+14E6;CANADIAN SYLLABICS LWA;Lo;0;L;;;;;N;;;;;
+14E7;CANADIAN SYLLABICS WEST-CREE LWA;Lo;0;L;;;;;N;;;;;
+14E8;CANADIAN SYLLABICS LWAA;Lo;0;L;;;;;N;;;;;
+14E9;CANADIAN SYLLABICS WEST-CREE LWAA;Lo;0;L;;;;;N;;;;;
+14EA;CANADIAN SYLLABICS L;Lo;0;L;;;;;N;;;;;
+14EB;CANADIAN SYLLABICS WEST-CREE L;Lo;0;L;;;;;N;;;;;
+14EC;CANADIAN SYLLABICS MEDIAL L;Lo;0;L;;;;;N;;;;;
+14ED;CANADIAN SYLLABICS SE;Lo;0;L;;;;;N;;;;;
+14EE;CANADIAN SYLLABICS SAAI;Lo;0;L;;;;;N;;;;;
+14EF;CANADIAN SYLLABICS SI;Lo;0;L;;;;;N;;;;;
+14F0;CANADIAN SYLLABICS SII;Lo;0;L;;;;;N;;;;;
+14F1;CANADIAN SYLLABICS SO;Lo;0;L;;;;;N;;;;;
+14F2;CANADIAN SYLLABICS SOO;Lo;0;L;;;;;N;;;;;
+14F3;CANADIAN SYLLABICS Y-CREE SOO;Lo;0;L;;;;;N;;;;;
+14F4;CANADIAN SYLLABICS SA;Lo;0;L;;;;;N;;;;;
+14F5;CANADIAN SYLLABICS SAA;Lo;0;L;;;;;N;;;;;
+14F6;CANADIAN SYLLABICS SWE;Lo;0;L;;;;;N;;;;;
+14F7;CANADIAN SYLLABICS WEST-CREE SWE;Lo;0;L;;;;;N;;;;;
+14F8;CANADIAN SYLLABICS SWI;Lo;0;L;;;;;N;;;;;
+14F9;CANADIAN SYLLABICS WEST-CREE SWI;Lo;0;L;;;;;N;;;;;
+14FA;CANADIAN SYLLABICS SWII;Lo;0;L;;;;;N;;;;;
+14FB;CANADIAN SYLLABICS WEST-CREE SWII;Lo;0;L;;;;;N;;;;;
+14FC;CANADIAN SYLLABICS SWO;Lo;0;L;;;;;N;;;;;
+14FD;CANADIAN SYLLABICS WEST-CREE SWO;Lo;0;L;;;;;N;;;;;
+14FE;CANADIAN SYLLABICS SWOO;Lo;0;L;;;;;N;;;;;
+14FF;CANADIAN SYLLABICS WEST-CREE SWOO;Lo;0;L;;;;;N;;;;;
+1500;CANADIAN SYLLABICS SWA;Lo;0;L;;;;;N;;;;;
+1501;CANADIAN SYLLABICS WEST-CREE SWA;Lo;0;L;;;;;N;;;;;
+1502;CANADIAN SYLLABICS SWAA;Lo;0;L;;;;;N;;;;;
+1503;CANADIAN SYLLABICS WEST-CREE SWAA;Lo;0;L;;;;;N;;;;;
+1504;CANADIAN SYLLABICS NASKAPI SWAA;Lo;0;L;;;;;N;;;;;
+1505;CANADIAN SYLLABICS S;Lo;0;L;;;;;N;;;;;
+1506;CANADIAN SYLLABICS ATHAPASCAN S;Lo;0;L;;;;;N;;;;;
+1507;CANADIAN SYLLABICS SW;Lo;0;L;;;;;N;;;;;
+1508;CANADIAN SYLLABICS BLACKFOOT S;Lo;0;L;;;;;N;;;;;
+1509;CANADIAN SYLLABICS MOOSE-CREE SK;Lo;0;L;;;;;N;;;;;
+150A;CANADIAN SYLLABICS NASKAPI SKW;Lo;0;L;;;;;N;;;;;
+150B;CANADIAN SYLLABICS NASKAPI S-W;Lo;0;L;;;;;N;;;;;
+150C;CANADIAN SYLLABICS NASKAPI SPWA;Lo;0;L;;;;;N;;;;;
+150D;CANADIAN SYLLABICS NASKAPI STWA;Lo;0;L;;;;;N;;;;;
+150E;CANADIAN SYLLABICS NASKAPI SKWA;Lo;0;L;;;;;N;;;;;
+150F;CANADIAN SYLLABICS NASKAPI SCWA;Lo;0;L;;;;;N;;;;;
+1510;CANADIAN SYLLABICS SHE;Lo;0;L;;;;;N;;;;;
+1511;CANADIAN SYLLABICS SHI;Lo;0;L;;;;;N;;;;;
+1512;CANADIAN SYLLABICS SHII;Lo;0;L;;;;;N;;;;;
+1513;CANADIAN SYLLABICS SHO;Lo;0;L;;;;;N;;;;;
+1514;CANADIAN SYLLABICS SHOO;Lo;0;L;;;;;N;;;;;
+1515;CANADIAN SYLLABICS SHA;Lo;0;L;;;;;N;;;;;
+1516;CANADIAN SYLLABICS SHAA;Lo;0;L;;;;;N;;;;;
+1517;CANADIAN SYLLABICS SHWE;Lo;0;L;;;;;N;;;;;
+1518;CANADIAN SYLLABICS WEST-CREE SHWE;Lo;0;L;;;;;N;;;;;
+1519;CANADIAN SYLLABICS SHWI;Lo;0;L;;;;;N;;;;;
+151A;CANADIAN SYLLABICS WEST-CREE SHWI;Lo;0;L;;;;;N;;;;;
+151B;CANADIAN SYLLABICS SHWII;Lo;0;L;;;;;N;;;;;
+151C;CANADIAN SYLLABICS WEST-CREE SHWII;Lo;0;L;;;;;N;;;;;
+151D;CANADIAN SYLLABICS SHWO;Lo;0;L;;;;;N;;;;;
+151E;CANADIAN SYLLABICS WEST-CREE SHWO;Lo;0;L;;;;;N;;;;;
+151F;CANADIAN SYLLABICS SHWOO;Lo;0;L;;;;;N;;;;;
+1520;CANADIAN SYLLABICS WEST-CREE SHWOO;Lo;0;L;;;;;N;;;;;
+1521;CANADIAN SYLLABICS SHWA;Lo;0;L;;;;;N;;;;;
+1522;CANADIAN SYLLABICS WEST-CREE SHWA;Lo;0;L;;;;;N;;;;;
+1523;CANADIAN SYLLABICS SHWAA;Lo;0;L;;;;;N;;;;;
+1524;CANADIAN SYLLABICS WEST-CREE SHWAA;Lo;0;L;;;;;N;;;;;
+1525;CANADIAN SYLLABICS SH;Lo;0;L;;;;;N;;;;;
+1526;CANADIAN SYLLABICS YE;Lo;0;L;;;;;N;;;;;
+1527;CANADIAN SYLLABICS YAAI;Lo;0;L;;;;;N;;;;;
+1528;CANADIAN SYLLABICS YI;Lo;0;L;;;;;N;;;;;
+1529;CANADIAN SYLLABICS YII;Lo;0;L;;;;;N;;;;;
+152A;CANADIAN SYLLABICS YO;Lo;0;L;;;;;N;;;;;
+152B;CANADIAN SYLLABICS YOO;Lo;0;L;;;;;N;;;;;
+152C;CANADIAN SYLLABICS Y-CREE YOO;Lo;0;L;;;;;N;;;;;
+152D;CANADIAN SYLLABICS YA;Lo;0;L;;;;;N;;;;;
+152E;CANADIAN SYLLABICS YAA;Lo;0;L;;;;;N;;;;;
+152F;CANADIAN SYLLABICS YWE;Lo;0;L;;;;;N;;;;;
+1530;CANADIAN SYLLABICS WEST-CREE YWE;Lo;0;L;;;;;N;;;;;
+1531;CANADIAN SYLLABICS YWI;Lo;0;L;;;;;N;;;;;
+1532;CANADIAN SYLLABICS WEST-CREE YWI;Lo;0;L;;;;;N;;;;;
+1533;CANADIAN SYLLABICS YWII;Lo;0;L;;;;;N;;;;;
+1534;CANADIAN SYLLABICS WEST-CREE YWII;Lo;0;L;;;;;N;;;;;
+1535;CANADIAN SYLLABICS YWO;Lo;0;L;;;;;N;;;;;
+1536;CANADIAN SYLLABICS WEST-CREE YWO;Lo;0;L;;;;;N;;;;;
+1537;CANADIAN SYLLABICS YWOO;Lo;0;L;;;;;N;;;;;
+1538;CANADIAN SYLLABICS WEST-CREE YWOO;Lo;0;L;;;;;N;;;;;
+1539;CANADIAN SYLLABICS YWA;Lo;0;L;;;;;N;;;;;
+153A;CANADIAN SYLLABICS WEST-CREE YWA;Lo;0;L;;;;;N;;;;;
+153B;CANADIAN SYLLABICS YWAA;Lo;0;L;;;;;N;;;;;
+153C;CANADIAN SYLLABICS WEST-CREE YWAA;Lo;0;L;;;;;N;;;;;
+153D;CANADIAN SYLLABICS NASKAPI YWAA;Lo;0;L;;;;;N;;;;;
+153E;CANADIAN SYLLABICS Y;Lo;0;L;;;;;N;;;;;
+153F;CANADIAN SYLLABICS BIBLE-CREE Y;Lo;0;L;;;;;N;;;;;
+1540;CANADIAN SYLLABICS WEST-CREE Y;Lo;0;L;;;;;N;;;;;
+1541;CANADIAN SYLLABICS SAYISI YI;Lo;0;L;;;;;N;;;;;
+1542;CANADIAN SYLLABICS RE;Lo;0;L;;;;;N;;;;;
+1543;CANADIAN SYLLABICS R-CREE RE;Lo;0;L;;;;;N;;;;;
+1544;CANADIAN SYLLABICS WEST-CREE LE;Lo;0;L;;;;;N;;;;;
+1545;CANADIAN SYLLABICS RAAI;Lo;0;L;;;;;N;;;;;
+1546;CANADIAN SYLLABICS RI;Lo;0;L;;;;;N;;;;;
+1547;CANADIAN SYLLABICS RII;Lo;0;L;;;;;N;;;;;
+1548;CANADIAN SYLLABICS RO;Lo;0;L;;;;;N;;;;;
+1549;CANADIAN SYLLABICS ROO;Lo;0;L;;;;;N;;;;;
+154A;CANADIAN SYLLABICS WEST-CREE LO;Lo;0;L;;;;;N;;;;;
+154B;CANADIAN SYLLABICS RA;Lo;0;L;;;;;N;;;;;
+154C;CANADIAN SYLLABICS RAA;Lo;0;L;;;;;N;;;;;
+154D;CANADIAN SYLLABICS WEST-CREE LA;Lo;0;L;;;;;N;;;;;
+154E;CANADIAN SYLLABICS RWAA;Lo;0;L;;;;;N;;;;;
+154F;CANADIAN SYLLABICS WEST-CREE RWAA;Lo;0;L;;;;;N;;;;;
+1550;CANADIAN SYLLABICS R;Lo;0;L;;;;;N;;;;;
+1551;CANADIAN SYLLABICS WEST-CREE R;Lo;0;L;;;;;N;;;;;
+1552;CANADIAN SYLLABICS MEDIAL R;Lo;0;L;;;;;N;;;;;
+1553;CANADIAN SYLLABICS FE;Lo;0;L;;;;;N;;;;;
+1554;CANADIAN SYLLABICS FAAI;Lo;0;L;;;;;N;;;;;
+1555;CANADIAN SYLLABICS FI;Lo;0;L;;;;;N;;;;;
+1556;CANADIAN SYLLABICS FII;Lo;0;L;;;;;N;;;;;
+1557;CANADIAN SYLLABICS FO;Lo;0;L;;;;;N;;;;;
+1558;CANADIAN SYLLABICS FOO;Lo;0;L;;;;;N;;;;;
+1559;CANADIAN SYLLABICS FA;Lo;0;L;;;;;N;;;;;
+155A;CANADIAN SYLLABICS FAA;Lo;0;L;;;;;N;;;;;
+155B;CANADIAN SYLLABICS FWAA;Lo;0;L;;;;;N;;;;;
+155C;CANADIAN SYLLABICS WEST-CREE FWAA;Lo;0;L;;;;;N;;;;;
+155D;CANADIAN SYLLABICS F;Lo;0;L;;;;;N;;;;;
+155E;CANADIAN SYLLABICS THE;Lo;0;L;;;;;N;;;;;
+155F;CANADIAN SYLLABICS N-CREE THE;Lo;0;L;;;;;N;;;;;
+1560;CANADIAN SYLLABICS THI;Lo;0;L;;;;;N;;;;;
+1561;CANADIAN SYLLABICS N-CREE THI;Lo;0;L;;;;;N;;;;;
+1562;CANADIAN SYLLABICS THII;Lo;0;L;;;;;N;;;;;
+1563;CANADIAN SYLLABICS N-CREE THII;Lo;0;L;;;;;N;;;;;
+1564;CANADIAN SYLLABICS THO;Lo;0;L;;;;;N;;;;;
+1565;CANADIAN SYLLABICS THOO;Lo;0;L;;;;;N;;;;;
+1566;CANADIAN SYLLABICS THA;Lo;0;L;;;;;N;;;;;
+1567;CANADIAN SYLLABICS THAA;Lo;0;L;;;;;N;;;;;
+1568;CANADIAN SYLLABICS THWAA;Lo;0;L;;;;;N;;;;;
+1569;CANADIAN SYLLABICS WEST-CREE THWAA;Lo;0;L;;;;;N;;;;;
+156A;CANADIAN SYLLABICS TH;Lo;0;L;;;;;N;;;;;
+156B;CANADIAN SYLLABICS TTHE;Lo;0;L;;;;;N;;;;;
+156C;CANADIAN SYLLABICS TTHI;Lo;0;L;;;;;N;;;;;
+156D;CANADIAN SYLLABICS TTHO;Lo;0;L;;;;;N;;;;;
+156E;CANADIAN SYLLABICS TTHA;Lo;0;L;;;;;N;;;;;
+156F;CANADIAN SYLLABICS TTH;Lo;0;L;;;;;N;;;;;
+1570;CANADIAN SYLLABICS TYE;Lo;0;L;;;;;N;;;;;
+1571;CANADIAN SYLLABICS TYI;Lo;0;L;;;;;N;;;;;
+1572;CANADIAN SYLLABICS TYO;Lo;0;L;;;;;N;;;;;
+1573;CANADIAN SYLLABICS TYA;Lo;0;L;;;;;N;;;;;
+1574;CANADIAN SYLLABICS NUNAVIK HE;Lo;0;L;;;;;N;;;;;
+1575;CANADIAN SYLLABICS NUNAVIK HI;Lo;0;L;;;;;N;;;;;
+1576;CANADIAN SYLLABICS NUNAVIK HII;Lo;0;L;;;;;N;;;;;
+1577;CANADIAN SYLLABICS NUNAVIK HO;Lo;0;L;;;;;N;;;;;
+1578;CANADIAN SYLLABICS NUNAVIK HOO;Lo;0;L;;;;;N;;;;;
+1579;CANADIAN SYLLABICS NUNAVIK HA;Lo;0;L;;;;;N;;;;;
+157A;CANADIAN SYLLABICS NUNAVIK HAA;Lo;0;L;;;;;N;;;;;
+157B;CANADIAN SYLLABICS NUNAVIK H;Lo;0;L;;;;;N;;;;;
+157C;CANADIAN SYLLABICS NUNAVUT H;Lo;0;L;;;;;N;;;;;
+157D;CANADIAN SYLLABICS HK;Lo;0;L;;;;;N;;;;;
+157E;CANADIAN SYLLABICS QAAI;Lo;0;L;;;;;N;;;;;
+157F;CANADIAN SYLLABICS QI;Lo;0;L;;;;;N;;;;;
+1580;CANADIAN SYLLABICS QII;Lo;0;L;;;;;N;;;;;
+1581;CANADIAN SYLLABICS QO;Lo;0;L;;;;;N;;;;;
+1582;CANADIAN SYLLABICS QOO;Lo;0;L;;;;;N;;;;;
+1583;CANADIAN SYLLABICS QA;Lo;0;L;;;;;N;;;;;
+1584;CANADIAN SYLLABICS QAA;Lo;0;L;;;;;N;;;;;
+1585;CANADIAN SYLLABICS Q;Lo;0;L;;;;;N;;;;;
+1586;CANADIAN SYLLABICS TLHE;Lo;0;L;;;;;N;;;;;
+1587;CANADIAN SYLLABICS TLHI;Lo;0;L;;;;;N;;;;;
+1588;CANADIAN SYLLABICS TLHO;Lo;0;L;;;;;N;;;;;
+1589;CANADIAN SYLLABICS TLHA;Lo;0;L;;;;;N;;;;;
+158A;CANADIAN SYLLABICS WEST-CREE RE;Lo;0;L;;;;;N;;;;;
+158B;CANADIAN SYLLABICS WEST-CREE RI;Lo;0;L;;;;;N;;;;;
+158C;CANADIAN SYLLABICS WEST-CREE RO;Lo;0;L;;;;;N;;;;;
+158D;CANADIAN SYLLABICS WEST-CREE RA;Lo;0;L;;;;;N;;;;;
+158E;CANADIAN SYLLABICS NGAAI;Lo;0;L;;;;;N;;;;;
+158F;CANADIAN SYLLABICS NGI;Lo;0;L;;;;;N;;;;;
+1590;CANADIAN SYLLABICS NGII;Lo;0;L;;;;;N;;;;;
+1591;CANADIAN SYLLABICS NGO;Lo;0;L;;;;;N;;;;;
+1592;CANADIAN SYLLABICS NGOO;Lo;0;L;;;;;N;;;;;
+1593;CANADIAN SYLLABICS NGA;Lo;0;L;;;;;N;;;;;
+1594;CANADIAN SYLLABICS NGAA;Lo;0;L;;;;;N;;;;;
+1595;CANADIAN SYLLABICS NG;Lo;0;L;;;;;N;;;;;
+1596;CANADIAN SYLLABICS NNG;Lo;0;L;;;;;N;;;;;
+1597;CANADIAN SYLLABICS SAYISI SHE;Lo;0;L;;;;;N;;;;;
+1598;CANADIAN SYLLABICS SAYISI SHI;Lo;0;L;;;;;N;;;;;
+1599;CANADIAN SYLLABICS SAYISI SHO;Lo;0;L;;;;;N;;;;;
+159A;CANADIAN SYLLABICS SAYISI SHA;Lo;0;L;;;;;N;;;;;
+159B;CANADIAN SYLLABICS WOODS-CREE THE;Lo;0;L;;;;;N;;;;;
+159C;CANADIAN SYLLABICS WOODS-CREE THI;Lo;0;L;;;;;N;;;;;
+159D;CANADIAN SYLLABICS WOODS-CREE THO;Lo;0;L;;;;;N;;;;;
+159E;CANADIAN SYLLABICS WOODS-CREE THA;Lo;0;L;;;;;N;;;;;
+159F;CANADIAN SYLLABICS WOODS-CREE TH;Lo;0;L;;;;;N;;;;;
+15A0;CANADIAN SYLLABICS LHI;Lo;0;L;;;;;N;;;;;
+15A1;CANADIAN SYLLABICS LHII;Lo;0;L;;;;;N;;;;;
+15A2;CANADIAN SYLLABICS LHO;Lo;0;L;;;;;N;;;;;
+15A3;CANADIAN SYLLABICS LHOO;Lo;0;L;;;;;N;;;;;
+15A4;CANADIAN SYLLABICS LHA;Lo;0;L;;;;;N;;;;;
+15A5;CANADIAN SYLLABICS LHAA;Lo;0;L;;;;;N;;;;;
+15A6;CANADIAN SYLLABICS LH;Lo;0;L;;;;;N;;;;;
+15A7;CANADIAN SYLLABICS TH-CREE THE;Lo;0;L;;;;;N;;;;;
+15A8;CANADIAN SYLLABICS TH-CREE THI;Lo;0;L;;;;;N;;;;;
+15A9;CANADIAN SYLLABICS TH-CREE THII;Lo;0;L;;;;;N;;;;;
+15AA;CANADIAN SYLLABICS TH-CREE THO;Lo;0;L;;;;;N;;;;;
+15AB;CANADIAN SYLLABICS TH-CREE THOO;Lo;0;L;;;;;N;;;;;
+15AC;CANADIAN SYLLABICS TH-CREE THA;Lo;0;L;;;;;N;;;;;
+15AD;CANADIAN SYLLABICS TH-CREE THAA;Lo;0;L;;;;;N;;;;;
+15AE;CANADIAN SYLLABICS TH-CREE TH;Lo;0;L;;;;;N;;;;;
+15AF;CANADIAN SYLLABICS AIVILIK B;Lo;0;L;;;;;N;;;;;
+15B0;CANADIAN SYLLABICS BLACKFOOT E;Lo;0;L;;;;;N;;;;;
+15B1;CANADIAN SYLLABICS BLACKFOOT I;Lo;0;L;;;;;N;;;;;
+15B2;CANADIAN SYLLABICS BLACKFOOT O;Lo;0;L;;;;;N;;;;;
+15B3;CANADIAN SYLLABICS BLACKFOOT A;Lo;0;L;;;;;N;;;;;
+15B4;CANADIAN SYLLABICS BLACKFOOT WE;Lo;0;L;;;;;N;;;;;
+15B5;CANADIAN SYLLABICS BLACKFOOT WI;Lo;0;L;;;;;N;;;;;
+15B6;CANADIAN SYLLABICS BLACKFOOT WO;Lo;0;L;;;;;N;;;;;
+15B7;CANADIAN SYLLABICS BLACKFOOT WA;Lo;0;L;;;;;N;;;;;
+15B8;CANADIAN SYLLABICS BLACKFOOT NE;Lo;0;L;;;;;N;;;;;
+15B9;CANADIAN SYLLABICS BLACKFOOT NI;Lo;0;L;;;;;N;;;;;
+15BA;CANADIAN SYLLABICS BLACKFOOT NO;Lo;0;L;;;;;N;;;;;
+15BB;CANADIAN SYLLABICS BLACKFOOT NA;Lo;0;L;;;;;N;;;;;
+15BC;CANADIAN SYLLABICS BLACKFOOT KE;Lo;0;L;;;;;N;;;;;
+15BD;CANADIAN SYLLABICS BLACKFOOT KI;Lo;0;L;;;;;N;;;;;
+15BE;CANADIAN SYLLABICS BLACKFOOT KO;Lo;0;L;;;;;N;;;;;
+15BF;CANADIAN SYLLABICS BLACKFOOT KA;Lo;0;L;;;;;N;;;;;
+15C0;CANADIAN SYLLABICS SAYISI HE;Lo;0;L;;;;;N;;;;;
+15C1;CANADIAN SYLLABICS SAYISI HI;Lo;0;L;;;;;N;;;;;
+15C2;CANADIAN SYLLABICS SAYISI HO;Lo;0;L;;;;;N;;;;;
+15C3;CANADIAN SYLLABICS SAYISI HA;Lo;0;L;;;;;N;;;;;
+15C4;CANADIAN SYLLABICS CARRIER GHU;Lo;0;L;;;;;N;;;;;
+15C5;CANADIAN SYLLABICS CARRIER GHO;Lo;0;L;;;;;N;;;;;
+15C6;CANADIAN SYLLABICS CARRIER GHE;Lo;0;L;;;;;N;;;;;
+15C7;CANADIAN SYLLABICS CARRIER GHEE;Lo;0;L;;;;;N;;;;;
+15C8;CANADIAN SYLLABICS CARRIER GHI;Lo;0;L;;;;;N;;;;;
+15C9;CANADIAN SYLLABICS CARRIER GHA;Lo;0;L;;;;;N;;;;;
+15CA;CANADIAN SYLLABICS CARRIER RU;Lo;0;L;;;;;N;;;;;
+15CB;CANADIAN SYLLABICS CARRIER RO;Lo;0;L;;;;;N;;;;;
+15CC;CANADIAN SYLLABICS CARRIER RE;Lo;0;L;;;;;N;;;;;
+15CD;CANADIAN SYLLABICS CARRIER REE;Lo;0;L;;;;;N;;;;;
+15CE;CANADIAN SYLLABICS CARRIER RI;Lo;0;L;;;;;N;;;;;
+15CF;CANADIAN SYLLABICS CARRIER RA;Lo;0;L;;;;;N;;;;;
+15D0;CANADIAN SYLLABICS CARRIER WU;Lo;0;L;;;;;N;;;;;
+15D1;CANADIAN SYLLABICS CARRIER WO;Lo;0;L;;;;;N;;;;;
+15D2;CANADIAN SYLLABICS CARRIER WE;Lo;0;L;;;;;N;;;;;
+15D3;CANADIAN SYLLABICS CARRIER WEE;Lo;0;L;;;;;N;;;;;
+15D4;CANADIAN SYLLABICS CARRIER WI;Lo;0;L;;;;;N;;;;;
+15D5;CANADIAN SYLLABICS CARRIER WA;Lo;0;L;;;;;N;;;;;
+15D6;CANADIAN SYLLABICS CARRIER HWU;Lo;0;L;;;;;N;;;;;
+15D7;CANADIAN SYLLABICS CARRIER HWO;Lo;0;L;;;;;N;;;;;
+15D8;CANADIAN SYLLABICS CARRIER HWE;Lo;0;L;;;;;N;;;;;
+15D9;CANADIAN SYLLABICS CARRIER HWEE;Lo;0;L;;;;;N;;;;;
+15DA;CANADIAN SYLLABICS CARRIER HWI;Lo;0;L;;;;;N;;;;;
+15DB;CANADIAN SYLLABICS CARRIER HWA;Lo;0;L;;;;;N;;;;;
+15DC;CANADIAN SYLLABICS CARRIER THU;Lo;0;L;;;;;N;;;;;
+15DD;CANADIAN SYLLABICS CARRIER THO;Lo;0;L;;;;;N;;;;;
+15DE;CANADIAN SYLLABICS CARRIER THE;Lo;0;L;;;;;N;;;;;
+15DF;CANADIAN SYLLABICS CARRIER THEE;Lo;0;L;;;;;N;;;;;
+15E0;CANADIAN SYLLABICS CARRIER THI;Lo;0;L;;;;;N;;;;;
+15E1;CANADIAN SYLLABICS CARRIER THA;Lo;0;L;;;;;N;;;;;
+15E2;CANADIAN SYLLABICS CARRIER TTU;Lo;0;L;;;;;N;;;;;
+15E3;CANADIAN SYLLABICS CARRIER TTO;Lo;0;L;;;;;N;;;;;
+15E4;CANADIAN SYLLABICS CARRIER TTE;Lo;0;L;;;;;N;;;;;
+15E5;CANADIAN SYLLABICS CARRIER TTEE;Lo;0;L;;;;;N;;;;;
+15E6;CANADIAN SYLLABICS CARRIER TTI;Lo;0;L;;;;;N;;;;;
+15E7;CANADIAN SYLLABICS CARRIER TTA;Lo;0;L;;;;;N;;;;;
+15E8;CANADIAN SYLLABICS CARRIER PU;Lo;0;L;;;;;N;;;;;
+15E9;CANADIAN SYLLABICS CARRIER PO;Lo;0;L;;;;;N;;;;;
+15EA;CANADIAN SYLLABICS CARRIER PE;Lo;0;L;;;;;N;;;;;
+15EB;CANADIAN SYLLABICS CARRIER PEE;Lo;0;L;;;;;N;;;;;
+15EC;CANADIAN SYLLABICS CARRIER PI;Lo;0;L;;;;;N;;;;;
+15ED;CANADIAN SYLLABICS CARRIER PA;Lo;0;L;;;;;N;;;;;
+15EE;CANADIAN SYLLABICS CARRIER P;Lo;0;L;;;;;N;;;;;
+15EF;CANADIAN SYLLABICS CARRIER GU;Lo;0;L;;;;;N;;;;;
+15F0;CANADIAN SYLLABICS CARRIER GO;Lo;0;L;;;;;N;;;;;
+15F1;CANADIAN SYLLABICS CARRIER GE;Lo;0;L;;;;;N;;;;;
+15F2;CANADIAN SYLLABICS CARRIER GEE;Lo;0;L;;;;;N;;;;;
+15F3;CANADIAN SYLLABICS CARRIER GI;Lo;0;L;;;;;N;;;;;
+15F4;CANADIAN SYLLABICS CARRIER GA;Lo;0;L;;;;;N;;;;;
+15F5;CANADIAN SYLLABICS CARRIER KHU;Lo;0;L;;;;;N;;;;;
+15F6;CANADIAN SYLLABICS CARRIER KHO;Lo;0;L;;;;;N;;;;;
+15F7;CANADIAN SYLLABICS CARRIER KHE;Lo;0;L;;;;;N;;;;;
+15F8;CANADIAN SYLLABICS CARRIER KHEE;Lo;0;L;;;;;N;;;;;
+15F9;CANADIAN SYLLABICS CARRIER KHI;Lo;0;L;;;;;N;;;;;
+15FA;CANADIAN SYLLABICS CARRIER KHA;Lo;0;L;;;;;N;;;;;
+15FB;CANADIAN SYLLABICS CARRIER KKU;Lo;0;L;;;;;N;;;;;
+15FC;CANADIAN SYLLABICS CARRIER KKO;Lo;0;L;;;;;N;;;;;
+15FD;CANADIAN SYLLABICS CARRIER KKE;Lo;0;L;;;;;N;;;;;
+15FE;CANADIAN SYLLABICS CARRIER KKEE;Lo;0;L;;;;;N;;;;;
+15FF;CANADIAN SYLLABICS CARRIER KKI;Lo;0;L;;;;;N;;;;;
+1600;CANADIAN SYLLABICS CARRIER KKA;Lo;0;L;;;;;N;;;;;
+1601;CANADIAN SYLLABICS CARRIER KK;Lo;0;L;;;;;N;;;;;
+1602;CANADIAN SYLLABICS CARRIER NU;Lo;0;L;;;;;N;;;;;
+1603;CANADIAN SYLLABICS CARRIER NO;Lo;0;L;;;;;N;;;;;
+1604;CANADIAN SYLLABICS CARRIER NE;Lo;0;L;;;;;N;;;;;
+1605;CANADIAN SYLLABICS CARRIER NEE;Lo;0;L;;;;;N;;;;;
+1606;CANADIAN SYLLABICS CARRIER NI;Lo;0;L;;;;;N;;;;;
+1607;CANADIAN SYLLABICS CARRIER NA;Lo;0;L;;;;;N;;;;;
+1608;CANADIAN SYLLABICS CARRIER MU;Lo;0;L;;;;;N;;;;;
+1609;CANADIAN SYLLABICS CARRIER MO;Lo;0;L;;;;;N;;;;;
+160A;CANADIAN SYLLABICS CARRIER ME;Lo;0;L;;;;;N;;;;;
+160B;CANADIAN SYLLABICS CARRIER MEE;Lo;0;L;;;;;N;;;;;
+160C;CANADIAN SYLLABICS CARRIER MI;Lo;0;L;;;;;N;;;;;
+160D;CANADIAN SYLLABICS CARRIER MA;Lo;0;L;;;;;N;;;;;
+160E;CANADIAN SYLLABICS CARRIER YU;Lo;0;L;;;;;N;;;;;
+160F;CANADIAN SYLLABICS CARRIER YO;Lo;0;L;;;;;N;;;;;
+1610;CANADIAN SYLLABICS CARRIER YE;Lo;0;L;;;;;N;;;;;
+1611;CANADIAN SYLLABICS CARRIER YEE;Lo;0;L;;;;;N;;;;;
+1612;CANADIAN SYLLABICS CARRIER YI;Lo;0;L;;;;;N;;;;;
+1613;CANADIAN SYLLABICS CARRIER YA;Lo;0;L;;;;;N;;;;;
+1614;CANADIAN SYLLABICS CARRIER JU;Lo;0;L;;;;;N;;;;;
+1615;CANADIAN SYLLABICS SAYISI JU;Lo;0;L;;;;;N;;;;;
+1616;CANADIAN SYLLABICS CARRIER JO;Lo;0;L;;;;;N;;;;;
+1617;CANADIAN SYLLABICS CARRIER JE;Lo;0;L;;;;;N;;;;;
+1618;CANADIAN SYLLABICS CARRIER JEE;Lo;0;L;;;;;N;;;;;
+1619;CANADIAN SYLLABICS CARRIER JI;Lo;0;L;;;;;N;;;;;
+161A;CANADIAN SYLLABICS SAYISI JI;Lo;0;L;;;;;N;;;;;
+161B;CANADIAN SYLLABICS CARRIER JA;Lo;0;L;;;;;N;;;;;
+161C;CANADIAN SYLLABICS CARRIER JJU;Lo;0;L;;;;;N;;;;;
+161D;CANADIAN SYLLABICS CARRIER JJO;Lo;0;L;;;;;N;;;;;
+161E;CANADIAN SYLLABICS CARRIER JJE;Lo;0;L;;;;;N;;;;;
+161F;CANADIAN SYLLABICS CARRIER JJEE;Lo;0;L;;;;;N;;;;;
+1620;CANADIAN SYLLABICS CARRIER JJI;Lo;0;L;;;;;N;;;;;
+1621;CANADIAN SYLLABICS CARRIER JJA;Lo;0;L;;;;;N;;;;;
+1622;CANADIAN SYLLABICS CARRIER LU;Lo;0;L;;;;;N;;;;;
+1623;CANADIAN SYLLABICS CARRIER LO;Lo;0;L;;;;;N;;;;;
+1624;CANADIAN SYLLABICS CARRIER LE;Lo;0;L;;;;;N;;;;;
+1625;CANADIAN SYLLABICS CARRIER LEE;Lo;0;L;;;;;N;;;;;
+1626;CANADIAN SYLLABICS CARRIER LI;Lo;0;L;;;;;N;;;;;
+1627;CANADIAN SYLLABICS CARRIER LA;Lo;0;L;;;;;N;;;;;
+1628;CANADIAN SYLLABICS CARRIER DLU;Lo;0;L;;;;;N;;;;;
+1629;CANADIAN SYLLABICS CARRIER DLO;Lo;0;L;;;;;N;;;;;
+162A;CANADIAN SYLLABICS CARRIER DLE;Lo;0;L;;;;;N;;;;;
+162B;CANADIAN SYLLABICS CARRIER DLEE;Lo;0;L;;;;;N;;;;;
+162C;CANADIAN SYLLABICS CARRIER DLI;Lo;0;L;;;;;N;;;;;
+162D;CANADIAN SYLLABICS CARRIER DLA;Lo;0;L;;;;;N;;;;;
+162E;CANADIAN SYLLABICS CARRIER LHU;Lo;0;L;;;;;N;;;;;
+162F;CANADIAN SYLLABICS CARRIER LHO;Lo;0;L;;;;;N;;;;;
+1630;CANADIAN SYLLABICS CARRIER LHE;Lo;0;L;;;;;N;;;;;
+1631;CANADIAN SYLLABICS CARRIER LHEE;Lo;0;L;;;;;N;;;;;
+1632;CANADIAN SYLLABICS CARRIER LHI;Lo;0;L;;;;;N;;;;;
+1633;CANADIAN SYLLABICS CARRIER LHA;Lo;0;L;;;;;N;;;;;
+1634;CANADIAN SYLLABICS CARRIER TLHU;Lo;0;L;;;;;N;;;;;
+1635;CANADIAN SYLLABICS CARRIER TLHO;Lo;0;L;;;;;N;;;;;
+1636;CANADIAN SYLLABICS CARRIER TLHE;Lo;0;L;;;;;N;;;;;
+1637;CANADIAN SYLLABICS CARRIER TLHEE;Lo;0;L;;;;;N;;;;;
+1638;CANADIAN SYLLABICS CARRIER TLHI;Lo;0;L;;;;;N;;;;;
+1639;CANADIAN SYLLABICS CARRIER TLHA;Lo;0;L;;;;;N;;;;;
+163A;CANADIAN SYLLABICS CARRIER TLU;Lo;0;L;;;;;N;;;;;
+163B;CANADIAN SYLLABICS CARRIER TLO;Lo;0;L;;;;;N;;;;;
+163C;CANADIAN SYLLABICS CARRIER TLE;Lo;0;L;;;;;N;;;;;
+163D;CANADIAN SYLLABICS CARRIER TLEE;Lo;0;L;;;;;N;;;;;
+163E;CANADIAN SYLLABICS CARRIER TLI;Lo;0;L;;;;;N;;;;;
+163F;CANADIAN SYLLABICS CARRIER TLA;Lo;0;L;;;;;N;;;;;
+1640;CANADIAN SYLLABICS CARRIER ZU;Lo;0;L;;;;;N;;;;;
+1641;CANADIAN SYLLABICS CARRIER ZO;Lo;0;L;;;;;N;;;;;
+1642;CANADIAN SYLLABICS CARRIER ZE;Lo;0;L;;;;;N;;;;;
+1643;CANADIAN SYLLABICS CARRIER ZEE;Lo;0;L;;;;;N;;;;;
+1644;CANADIAN SYLLABICS CARRIER ZI;Lo;0;L;;;;;N;;;;;
+1645;CANADIAN SYLLABICS CARRIER ZA;Lo;0;L;;;;;N;;;;;
+1646;CANADIAN SYLLABICS CARRIER Z;Lo;0;L;;;;;N;;;;;
+1647;CANADIAN SYLLABICS CARRIER INITIAL Z;Lo;0;L;;;;;N;;;;;
+1648;CANADIAN SYLLABICS CARRIER DZU;Lo;0;L;;;;;N;;;;;
+1649;CANADIAN SYLLABICS CARRIER DZO;Lo;0;L;;;;;N;;;;;
+164A;CANADIAN SYLLABICS CARRIER DZE;Lo;0;L;;;;;N;;;;;
+164B;CANADIAN SYLLABICS CARRIER DZEE;Lo;0;L;;;;;N;;;;;
+164C;CANADIAN SYLLABICS CARRIER DZI;Lo;0;L;;;;;N;;;;;
+164D;CANADIAN SYLLABICS CARRIER DZA;Lo;0;L;;;;;N;;;;;
+164E;CANADIAN SYLLABICS CARRIER SU;Lo;0;L;;;;;N;;;;;
+164F;CANADIAN SYLLABICS CARRIER SO;Lo;0;L;;;;;N;;;;;
+1650;CANADIAN SYLLABICS CARRIER SE;Lo;0;L;;;;;N;;;;;
+1651;CANADIAN SYLLABICS CARRIER SEE;Lo;0;L;;;;;N;;;;;
+1652;CANADIAN SYLLABICS CARRIER SI;Lo;0;L;;;;;N;;;;;
+1653;CANADIAN SYLLABICS CARRIER SA;Lo;0;L;;;;;N;;;;;
+1654;CANADIAN SYLLABICS CARRIER SHU;Lo;0;L;;;;;N;;;;;
+1655;CANADIAN SYLLABICS CARRIER SHO;Lo;0;L;;;;;N;;;;;
+1656;CANADIAN SYLLABICS CARRIER SHE;Lo;0;L;;;;;N;;;;;
+1657;CANADIAN SYLLABICS CARRIER SHEE;Lo;0;L;;;;;N;;;;;
+1658;CANADIAN SYLLABICS CARRIER SHI;Lo;0;L;;;;;N;;;;;
+1659;CANADIAN SYLLABICS CARRIER SHA;Lo;0;L;;;;;N;;;;;
+165A;CANADIAN SYLLABICS CARRIER SH;Lo;0;L;;;;;N;;;;;
+165B;CANADIAN SYLLABICS CARRIER TSU;Lo;0;L;;;;;N;;;;;
+165C;CANADIAN SYLLABICS CARRIER TSO;Lo;0;L;;;;;N;;;;;
+165D;CANADIAN SYLLABICS CARRIER TSE;Lo;0;L;;;;;N;;;;;
+165E;CANADIAN SYLLABICS CARRIER TSEE;Lo;0;L;;;;;N;;;;;
+165F;CANADIAN SYLLABICS CARRIER TSI;Lo;0;L;;;;;N;;;;;
+1660;CANADIAN SYLLABICS CARRIER TSA;Lo;0;L;;;;;N;;;;;
+1661;CANADIAN SYLLABICS CARRIER CHU;Lo;0;L;;;;;N;;;;;
+1662;CANADIAN SYLLABICS CARRIER CHO;Lo;0;L;;;;;N;;;;;
+1663;CANADIAN SYLLABICS CARRIER CHE;Lo;0;L;;;;;N;;;;;
+1664;CANADIAN SYLLABICS CARRIER CHEE;Lo;0;L;;;;;N;;;;;
+1665;CANADIAN SYLLABICS CARRIER CHI;Lo;0;L;;;;;N;;;;;
+1666;CANADIAN SYLLABICS CARRIER CHA;Lo;0;L;;;;;N;;;;;
+1667;CANADIAN SYLLABICS CARRIER TTSU;Lo;0;L;;;;;N;;;;;
+1668;CANADIAN SYLLABICS CARRIER TTSO;Lo;0;L;;;;;N;;;;;
+1669;CANADIAN SYLLABICS CARRIER TTSE;Lo;0;L;;;;;N;;;;;
+166A;CANADIAN SYLLABICS CARRIER TTSEE;Lo;0;L;;;;;N;;;;;
+166B;CANADIAN SYLLABICS CARRIER TTSI;Lo;0;L;;;;;N;;;;;
+166C;CANADIAN SYLLABICS CARRIER TTSA;Lo;0;L;;;;;N;;;;;
+166D;CANADIAN SYLLABICS CHI SIGN;Po;0;L;;;;;N;;;;;
+166E;CANADIAN SYLLABICS FULL STOP;Po;0;L;;;;;N;;;;;
+166F;CANADIAN SYLLABICS QAI;Lo;0;L;;;;;N;;;;;
+1670;CANADIAN SYLLABICS NGAI;Lo;0;L;;;;;N;;;;;
+1671;CANADIAN SYLLABICS NNGI;Lo;0;L;;;;;N;;;;;
+1672;CANADIAN SYLLABICS NNGII;Lo;0;L;;;;;N;;;;;
+1673;CANADIAN SYLLABICS NNGO;Lo;0;L;;;;;N;;;;;
+1674;CANADIAN SYLLABICS NNGOO;Lo;0;L;;;;;N;;;;;
+1675;CANADIAN SYLLABICS NNGA;Lo;0;L;;;;;N;;;;;
+1676;CANADIAN SYLLABICS NNGAA;Lo;0;L;;;;;N;;;;;
+1680;OGHAM SPACE MARK;Zs;0;WS;;;;;N;;;;;
+1681;OGHAM LETTER BEITH;Lo;0;L;;;;;N;;;;;
+1682;OGHAM LETTER LUIS;Lo;0;L;;;;;N;;;;;
+1683;OGHAM LETTER FEARN;Lo;0;L;;;;;N;;;;;
+1684;OGHAM LETTER SAIL;Lo;0;L;;;;;N;;;;;
+1685;OGHAM LETTER NION;Lo;0;L;;;;;N;;;;;
+1686;OGHAM LETTER UATH;Lo;0;L;;;;;N;;;;;
+1687;OGHAM LETTER DAIR;Lo;0;L;;;;;N;;;;;
+1688;OGHAM LETTER TINNE;Lo;0;L;;;;;N;;;;;
+1689;OGHAM LETTER COLL;Lo;0;L;;;;;N;;;;;
+168A;OGHAM LETTER CEIRT;Lo;0;L;;;;;N;;;;;
+168B;OGHAM LETTER MUIN;Lo;0;L;;;;;N;;;;;
+168C;OGHAM LETTER GORT;Lo;0;L;;;;;N;;;;;
+168D;OGHAM LETTER NGEADAL;Lo;0;L;;;;;N;;;;;
+168E;OGHAM LETTER STRAIF;Lo;0;L;;;;;N;;;;;
+168F;OGHAM LETTER RUIS;Lo;0;L;;;;;N;;;;;
+1690;OGHAM LETTER AILM;Lo;0;L;;;;;N;;;;;
+1691;OGHAM LETTER ONN;Lo;0;L;;;;;N;;;;;
+1692;OGHAM LETTER UR;Lo;0;L;;;;;N;;;;;
+1693;OGHAM LETTER EADHADH;Lo;0;L;;;;;N;;;;;
+1694;OGHAM LETTER IODHADH;Lo;0;L;;;;;N;;;;;
+1695;OGHAM LETTER EABHADH;Lo;0;L;;;;;N;;;;;
+1696;OGHAM LETTER OR;Lo;0;L;;;;;N;;;;;
+1697;OGHAM LETTER UILLEANN;Lo;0;L;;;;;N;;;;;
+1698;OGHAM LETTER IFIN;Lo;0;L;;;;;N;;;;;
+1699;OGHAM LETTER EAMHANCHOLL;Lo;0;L;;;;;N;;;;;
+169A;OGHAM LETTER PEITH;Lo;0;L;;;;;N;;;;;
+169B;OGHAM FEATHER MARK;Ps;0;ON;;;;;N;;;;;
+169C;OGHAM REVERSED FEATHER MARK;Pe;0;ON;;;;;N;;;;;
+16A0;RUNIC LETTER FEHU FEOH FE F;Lo;0;L;;;;;N;;;;;
+16A1;RUNIC LETTER V;Lo;0;L;;;;;N;;;;;
+16A2;RUNIC LETTER URUZ UR U;Lo;0;L;;;;;N;;;;;
+16A3;RUNIC LETTER YR;Lo;0;L;;;;;N;;;;;
+16A4;RUNIC LETTER Y;Lo;0;L;;;;;N;;;;;
+16A5;RUNIC LETTER W;Lo;0;L;;;;;N;;;;;
+16A6;RUNIC LETTER THURISAZ THURS THORN;Lo;0;L;;;;;N;;;;;
+16A7;RUNIC LETTER ETH;Lo;0;L;;;;;N;;;;;
+16A8;RUNIC LETTER ANSUZ A;Lo;0;L;;;;;N;;;;;
+16A9;RUNIC LETTER OS O;Lo;0;L;;;;;N;;;;;
+16AA;RUNIC LETTER AC A;Lo;0;L;;;;;N;;;;;
+16AB;RUNIC LETTER AESC;Lo;0;L;;;;;N;;;;;
+16AC;RUNIC LETTER LONG-BRANCH-OSS O;Lo;0;L;;;;;N;;;;;
+16AD;RUNIC LETTER SHORT-TWIG-OSS O;Lo;0;L;;;;;N;;;;;
+16AE;RUNIC LETTER O;Lo;0;L;;;;;N;;;;;
+16AF;RUNIC LETTER OE;Lo;0;L;;;;;N;;;;;
+16B0;RUNIC LETTER ON;Lo;0;L;;;;;N;;;;;
+16B1;RUNIC LETTER RAIDO RAD REID R;Lo;0;L;;;;;N;;;;;
+16B2;RUNIC LETTER KAUNA;Lo;0;L;;;;;N;;;;;
+16B3;RUNIC LETTER CEN;Lo;0;L;;;;;N;;;;;
+16B4;RUNIC LETTER KAUN K;Lo;0;L;;;;;N;;;;;
+16B5;RUNIC LETTER G;Lo;0;L;;;;;N;;;;;
+16B6;RUNIC LETTER ENG;Lo;0;L;;;;;N;;;;;
+16B7;RUNIC LETTER GEBO GYFU G;Lo;0;L;;;;;N;;;;;
+16B8;RUNIC LETTER GAR;Lo;0;L;;;;;N;;;;;
+16B9;RUNIC LETTER WUNJO WYNN W;Lo;0;L;;;;;N;;;;;
+16BA;RUNIC LETTER HAGLAZ H;Lo;0;L;;;;;N;;;;;
+16BB;RUNIC LETTER HAEGL H;Lo;0;L;;;;;N;;;;;
+16BC;RUNIC LETTER LONG-BRANCH-HAGALL H;Lo;0;L;;;;;N;;;;;
+16BD;RUNIC LETTER SHORT-TWIG-HAGALL H;Lo;0;L;;;;;N;;;;;
+16BE;RUNIC LETTER NAUDIZ NYD NAUD N;Lo;0;L;;;;;N;;;;;
+16BF;RUNIC LETTER SHORT-TWIG-NAUD N;Lo;0;L;;;;;N;;;;;
+16C0;RUNIC LETTER DOTTED-N;Lo;0;L;;;;;N;;;;;
+16C1;RUNIC LETTER ISAZ IS ISS I;Lo;0;L;;;;;N;;;;;
+16C2;RUNIC LETTER E;Lo;0;L;;;;;N;;;;;
+16C3;RUNIC LETTER JERAN J;Lo;0;L;;;;;N;;;;;
+16C4;RUNIC LETTER GER;Lo;0;L;;;;;N;;;;;
+16C5;RUNIC LETTER LONG-BRANCH-AR AE;Lo;0;L;;;;;N;;;;;
+16C6;RUNIC LETTER SHORT-TWIG-AR A;Lo;0;L;;;;;N;;;;;
+16C7;RUNIC LETTER IWAZ EOH;Lo;0;L;;;;;N;;;;;
+16C8;RUNIC LETTER PERTHO PEORTH P;Lo;0;L;;;;;N;;;;;
+16C9;RUNIC LETTER ALGIZ EOLHX;Lo;0;L;;;;;N;;;;;
+16CA;RUNIC LETTER SOWILO S;Lo;0;L;;;;;N;;;;;
+16CB;RUNIC LETTER SIGEL LONG-BRANCH-SOL S;Lo;0;L;;;;;N;;;;;
+16CC;RUNIC LETTER SHORT-TWIG-SOL S;Lo;0;L;;;;;N;;;;;
+16CD;RUNIC LETTER C;Lo;0;L;;;;;N;;;;;
+16CE;RUNIC LETTER Z;Lo;0;L;;;;;N;;;;;
+16CF;RUNIC LETTER TIWAZ TIR TYR T;Lo;0;L;;;;;N;;;;;
+16D0;RUNIC LETTER SHORT-TWIG-TYR T;Lo;0;L;;;;;N;;;;;
+16D1;RUNIC LETTER D;Lo;0;L;;;;;N;;;;;
+16D2;RUNIC LETTER BERKANAN BEORC BJARKAN B;Lo;0;L;;;;;N;;;;;
+16D3;RUNIC LETTER SHORT-TWIG-BJARKAN B;Lo;0;L;;;;;N;;;;;
+16D4;RUNIC LETTER DOTTED-P;Lo;0;L;;;;;N;;;;;
+16D5;RUNIC LETTER OPEN-P;Lo;0;L;;;;;N;;;;;
+16D6;RUNIC LETTER EHWAZ EH E;Lo;0;L;;;;;N;;;;;
+16D7;RUNIC LETTER MANNAZ MAN M;Lo;0;L;;;;;N;;;;;
+16D8;RUNIC LETTER LONG-BRANCH-MADR M;Lo;0;L;;;;;N;;;;;
+16D9;RUNIC LETTER SHORT-TWIG-MADR M;Lo;0;L;;;;;N;;;;;
+16DA;RUNIC LETTER LAUKAZ LAGU LOGR L;Lo;0;L;;;;;N;;;;;
+16DB;RUNIC LETTER DOTTED-L;Lo;0;L;;;;;N;;;;;
+16DC;RUNIC LETTER INGWAZ;Lo;0;L;;;;;N;;;;;
+16DD;RUNIC LETTER ING;Lo;0;L;;;;;N;;;;;
+16DE;RUNIC LETTER DAGAZ DAEG D;Lo;0;L;;;;;N;;;;;
+16DF;RUNIC LETTER OTHALAN ETHEL O;Lo;0;L;;;;;N;;;;;
+16E0;RUNIC LETTER EAR;Lo;0;L;;;;;N;;;;;
+16E1;RUNIC LETTER IOR;Lo;0;L;;;;;N;;;;;
+16E2;RUNIC LETTER CWEORTH;Lo;0;L;;;;;N;;;;;
+16E3;RUNIC LETTER CALC;Lo;0;L;;;;;N;;;;;
+16E4;RUNIC LETTER CEALC;Lo;0;L;;;;;N;;;;;
+16E5;RUNIC LETTER STAN;Lo;0;L;;;;;N;;;;;
+16E6;RUNIC LETTER LONG-BRANCH-YR;Lo;0;L;;;;;N;;;;;
+16E7;RUNIC LETTER SHORT-TWIG-YR;Lo;0;L;;;;;N;;;;;
+16E8;RUNIC LETTER ICELANDIC-YR;Lo;0;L;;;;;N;;;;;
+16E9;RUNIC LETTER Q;Lo;0;L;;;;;N;;;;;
+16EA;RUNIC LETTER X;Lo;0;L;;;;;N;;;;;
+16EB;RUNIC SINGLE PUNCTUATION;Po;0;L;;;;;N;;;;;
+16EC;RUNIC MULTIPLE PUNCTUATION;Po;0;L;;;;;N;;;;;
+16ED;RUNIC CROSS PUNCTUATION;Po;0;L;;;;;N;;;;;
+16EE;RUNIC ARLAUG SYMBOL;Nl;0;L;;;;17;N;;golden number 17;;;
+16EF;RUNIC TVIMADUR SYMBOL;Nl;0;L;;;;18;N;;golden number 18;;;
+16F0;RUNIC BELGTHOR SYMBOL;Nl;0;L;;;;19;N;;golden number 19;;;
+1700;TAGALOG LETTER A;Lo;0;L;;;;;N;;;;;
+1701;TAGALOG LETTER I;Lo;0;L;;;;;N;;;;;
+1702;TAGALOG LETTER U;Lo;0;L;;;;;N;;;;;
+1703;TAGALOG LETTER KA;Lo;0;L;;;;;N;;;;;
+1704;TAGALOG LETTER GA;Lo;0;L;;;;;N;;;;;
+1705;TAGALOG LETTER NGA;Lo;0;L;;;;;N;;;;;
+1706;TAGALOG LETTER TA;Lo;0;L;;;;;N;;;;;
+1707;TAGALOG LETTER DA;Lo;0;L;;;;;N;;;;;
+1708;TAGALOG LETTER NA;Lo;0;L;;;;;N;;;;;
+1709;TAGALOG LETTER PA;Lo;0;L;;;;;N;;;;;
+170A;TAGALOG LETTER BA;Lo;0;L;;;;;N;;;;;
+170B;TAGALOG LETTER MA;Lo;0;L;;;;;N;;;;;
+170C;TAGALOG LETTER YA;Lo;0;L;;;;;N;;;;;
+170E;TAGALOG LETTER LA;Lo;0;L;;;;;N;;;;;
+170F;TAGALOG LETTER WA;Lo;0;L;;;;;N;;;;;
+1710;TAGALOG LETTER SA;Lo;0;L;;;;;N;;;;;
+1711;TAGALOG LETTER HA;Lo;0;L;;;;;N;;;;;
+1712;TAGALOG VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;;
+1713;TAGALOG VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;;
+1714;TAGALOG SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;;
+1720;HANUNOO LETTER A;Lo;0;L;;;;;N;;;;;
+1721;HANUNOO LETTER I;Lo;0;L;;;;;N;;;;;
+1722;HANUNOO LETTER U;Lo;0;L;;;;;N;;;;;
+1723;HANUNOO LETTER KA;Lo;0;L;;;;;N;;;;;
+1724;HANUNOO LETTER GA;Lo;0;L;;;;;N;;;;;
+1725;HANUNOO LETTER NGA;Lo;0;L;;;;;N;;;;;
+1726;HANUNOO LETTER TA;Lo;0;L;;;;;N;;;;;
+1727;HANUNOO LETTER DA;Lo;0;L;;;;;N;;;;;
+1728;HANUNOO LETTER NA;Lo;0;L;;;;;N;;;;;
+1729;HANUNOO LETTER PA;Lo;0;L;;;;;N;;;;;
+172A;HANUNOO LETTER BA;Lo;0;L;;;;;N;;;;;
+172B;HANUNOO LETTER MA;Lo;0;L;;;;;N;;;;;
+172C;HANUNOO LETTER YA;Lo;0;L;;;;;N;;;;;
+172D;HANUNOO LETTER RA;Lo;0;L;;;;;N;;;;;
+172E;HANUNOO LETTER LA;Lo;0;L;;;;;N;;;;;
+172F;HANUNOO LETTER WA;Lo;0;L;;;;;N;;;;;
+1730;HANUNOO LETTER SA;Lo;0;L;;;;;N;;;;;
+1731;HANUNOO LETTER HA;Lo;0;L;;;;;N;;;;;
+1732;HANUNOO VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;;
+1733;HANUNOO VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;;
+1734;HANUNOO SIGN PAMUDPOD;Mn;9;NSM;;;;;N;;;;;
+1735;PHILIPPINE SINGLE PUNCTUATION;Po;0;L;;;;;N;;;;;
+1736;PHILIPPINE DOUBLE PUNCTUATION;Po;0;L;;;;;N;;;;;
+1740;BUHID LETTER A;Lo;0;L;;;;;N;;;;;
+1741;BUHID LETTER I;Lo;0;L;;;;;N;;;;;
+1742;BUHID LETTER U;Lo;0;L;;;;;N;;;;;
+1743;BUHID LETTER KA;Lo;0;L;;;;;N;;;;;
+1744;BUHID LETTER GA;Lo;0;L;;;;;N;;;;;
+1745;BUHID LETTER NGA;Lo;0;L;;;;;N;;;;;
+1746;BUHID LETTER TA;Lo;0;L;;;;;N;;;;;
+1747;BUHID LETTER DA;Lo;0;L;;;;;N;;;;;
+1748;BUHID LETTER NA;Lo;0;L;;;;;N;;;;;
+1749;BUHID LETTER PA;Lo;0;L;;;;;N;;;;;
+174A;BUHID LETTER BA;Lo;0;L;;;;;N;;;;;
+174B;BUHID LETTER MA;Lo;0;L;;;;;N;;;;;
+174C;BUHID LETTER YA;Lo;0;L;;;;;N;;;;;
+174D;BUHID LETTER RA;Lo;0;L;;;;;N;;;;;
+174E;BUHID LETTER LA;Lo;0;L;;;;;N;;;;;
+174F;BUHID LETTER WA;Lo;0;L;;;;;N;;;;;
+1750;BUHID LETTER SA;Lo;0;L;;;;;N;;;;;
+1751;BUHID LETTER HA;Lo;0;L;;;;;N;;;;;
+1752;BUHID VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;;
+1753;BUHID VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;;
+1760;TAGBANWA LETTER A;Lo;0;L;;;;;N;;;;;
+1761;TAGBANWA LETTER I;Lo;0;L;;;;;N;;;;;
+1762;TAGBANWA LETTER U;Lo;0;L;;;;;N;;;;;
+1763;TAGBANWA LETTER KA;Lo;0;L;;;;;N;;;;;
+1764;TAGBANWA LETTER GA;Lo;0;L;;;;;N;;;;;
+1765;TAGBANWA LETTER NGA;Lo;0;L;;;;;N;;;;;
+1766;TAGBANWA LETTER TA;Lo;0;L;;;;;N;;;;;
+1767;TAGBANWA LETTER DA;Lo;0;L;;;;;N;;;;;
+1768;TAGBANWA LETTER NA;Lo;0;L;;;;;N;;;;;
+1769;TAGBANWA LETTER PA;Lo;0;L;;;;;N;;;;;
+176A;TAGBANWA LETTER BA;Lo;0;L;;;;;N;;;;;
+176B;TAGBANWA LETTER MA;Lo;0;L;;;;;N;;;;;
+176C;TAGBANWA LETTER YA;Lo;0;L;;;;;N;;;;;
+176E;TAGBANWA LETTER LA;Lo;0;L;;;;;N;;;;;
+176F;TAGBANWA LETTER WA;Lo;0;L;;;;;N;;;;;
+1770;TAGBANWA LETTER SA;Lo;0;L;;;;;N;;;;;
+1772;TAGBANWA VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;;
+1773;TAGBANWA VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;;
+1780;KHMER LETTER KA;Lo;0;L;;;;;N;;;;;
+1781;KHMER LETTER KHA;Lo;0;L;;;;;N;;;;;
+1782;KHMER LETTER KO;Lo;0;L;;;;;N;;;;;
+1783;KHMER LETTER KHO;Lo;0;L;;;;;N;;;;;
+1784;KHMER LETTER NGO;Lo;0;L;;;;;N;;;;;
+1785;KHMER LETTER CA;Lo;0;L;;;;;N;;;;;
+1786;KHMER LETTER CHA;Lo;0;L;;;;;N;;;;;
+1787;KHMER LETTER CO;Lo;0;L;;;;;N;;;;;
+1788;KHMER LETTER CHO;Lo;0;L;;;;;N;;;;;
+1789;KHMER LETTER NYO;Lo;0;L;;;;;N;;;;;
+178A;KHMER LETTER DA;Lo;0;L;;;;;N;;;;;
+178B;KHMER LETTER TTHA;Lo;0;L;;;;;N;;;;;
+178C;KHMER LETTER DO;Lo;0;L;;;;;N;;;;;
+178D;KHMER LETTER TTHO;Lo;0;L;;;;;N;;;;;
+178E;KHMER LETTER NNO;Lo;0;L;;;;;N;;;;;
+178F;KHMER LETTER TA;Lo;0;L;;;;;N;;;;;
+1790;KHMER LETTER THA;Lo;0;L;;;;;N;;;;;
+1791;KHMER LETTER TO;Lo;0;L;;;;;N;;;;;
+1792;KHMER LETTER THO;Lo;0;L;;;;;N;;;;;
+1793;KHMER LETTER NO;Lo;0;L;;;;;N;;;;;
+1794;KHMER LETTER BA;Lo;0;L;;;;;N;;;;;
+1795;KHMER LETTER PHA;Lo;0;L;;;;;N;;;;;
+1796;KHMER LETTER PO;Lo;0;L;;;;;N;;;;;
+1797;KHMER LETTER PHO;Lo;0;L;;;;;N;;;;;
+1798;KHMER LETTER MO;Lo;0;L;;;;;N;;;;;
+1799;KHMER LETTER YO;Lo;0;L;;;;;N;;;;;
+179A;KHMER LETTER RO;Lo;0;L;;;;;N;;;;;
+179B;KHMER LETTER LO;Lo;0;L;;;;;N;;;;;
+179C;KHMER LETTER VO;Lo;0;L;;;;;N;;;;;
+179D;KHMER LETTER SHA;Lo;0;L;;;;;N;;;;;
+179E;KHMER LETTER SSO;Lo;0;L;;;;;N;;;;;
+179F;KHMER LETTER SA;Lo;0;L;;;;;N;;;;;
+17A0;KHMER LETTER HA;Lo;0;L;;;;;N;;;;;
+17A1;KHMER LETTER LA;Lo;0;L;;;;;N;;;;;
+17A2;KHMER LETTER QA;Lo;0;L;;;;;N;;;;;
+17A3;KHMER INDEPENDENT VOWEL QAQ;Lo;0;L;;;;;N;;*;;;
+17A4;KHMER INDEPENDENT VOWEL QAA;Lo;0;L;;;;;N;;*;;;
+17A5;KHMER INDEPENDENT VOWEL QI;Lo;0;L;;;;;N;;;;;
+17A6;KHMER INDEPENDENT VOWEL QII;Lo;0;L;;;;;N;;;;;
+17A7;KHMER INDEPENDENT VOWEL QU;Lo;0;L;;;;;N;;;;;
+17A8;KHMER INDEPENDENT VOWEL QUK;Lo;0;L;;;;;N;;;;;
+17A9;KHMER INDEPENDENT VOWEL QUU;Lo;0;L;;;;;N;;;;;
+17AA;KHMER INDEPENDENT VOWEL QUUV;Lo;0;L;;;;;N;;;;;
+17AB;KHMER INDEPENDENT VOWEL RY;Lo;0;L;;;;;N;;;;;
+17AC;KHMER INDEPENDENT VOWEL RYY;Lo;0;L;;;;;N;;;;;
+17AD;KHMER INDEPENDENT VOWEL LY;Lo;0;L;;;;;N;;;;;
+17AE;KHMER INDEPENDENT VOWEL LYY;Lo;0;L;;;;;N;;;;;
+17AF;KHMER INDEPENDENT VOWEL QE;Lo;0;L;;;;;N;;;;;
+17B0;KHMER INDEPENDENT VOWEL QAI;Lo;0;L;;;;;N;;;;;
+17B1;KHMER INDEPENDENT VOWEL QOO TYPE ONE;Lo;0;L;;;;;N;;;;;
+17B2;KHMER INDEPENDENT VOWEL QOO TYPE TWO;Lo;0;L;;;;;N;;;;;
+17B3;KHMER INDEPENDENT VOWEL QAU;Lo;0;L;;;;;N;;;;;
+17B4;KHMER VOWEL INHERENT AQ;Cf;0;L;;;;;N;;*;;;
+17B5;KHMER VOWEL INHERENT AA;Cf;0;L;;;;;N;;*;;;
+17B6;KHMER VOWEL SIGN AA;Mc;0;L;;;;;N;;;;;
+17B7;KHMER VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;;
+17B8;KHMER VOWEL SIGN II;Mn;0;NSM;;;;;N;;;;;
+17B9;KHMER VOWEL SIGN Y;Mn;0;NSM;;;;;N;;;;;
+17BA;KHMER VOWEL SIGN YY;Mn;0;NSM;;;;;N;;;;;
+17BB;KHMER VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;;
+17BC;KHMER VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;;
+17BD;KHMER VOWEL SIGN UA;Mn;0;NSM;;;;;N;;;;;
+17BE;KHMER VOWEL SIGN OE;Mc;0;L;;;;;N;;;;;
+17BF;KHMER VOWEL SIGN YA;Mc;0;L;;;;;N;;;;;
+17C0;KHMER VOWEL SIGN IE;Mc;0;L;;;;;N;;;;;
+17C1;KHMER VOWEL SIGN E;Mc;0;L;;;;;N;;;;;
+17C2;KHMER VOWEL SIGN AE;Mc;0;L;;;;;N;;;;;
+17C3;KHMER VOWEL SIGN AI;Mc;0;L;;;;;N;;;;;
+17C4;KHMER VOWEL SIGN OO;Mc;0;L;;;;;N;;;;;
+17C5;KHMER VOWEL SIGN AU;Mc;0;L;;;;;N;;;;;
+17C6;KHMER SIGN NIKAHIT;Mn;0;NSM;;;;;N;;;;;
+17C7;KHMER SIGN REAHMUK;Mc;0;L;;;;;N;;;;;
+17C8;KHMER SIGN YUUKALEAPINTU;Mc;0;L;;;;;N;;;;;
+17C9;KHMER SIGN MUUSIKATOAN;Mn;0;NSM;;;;;N;;;;;
+17CA;KHMER SIGN TRIISAP;Mn;0;NSM;;;;;N;;;;;
+17CB;KHMER SIGN BANTOC;Mn;0;NSM;;;;;N;;;;;
+17CC;KHMER SIGN ROBAT;Mn;0;NSM;;;;;N;;;;;
+17CD;KHMER SIGN TOANDAKHIAT;Mn;0;NSM;;;;;N;;;;;
+17CE;KHMER SIGN KAKABAT;Mn;0;NSM;;;;;N;;;;;
+17CF;KHMER SIGN AHSDA;Mn;0;NSM;;;;;N;;;;;
+17D0;KHMER SIGN SAMYOK SANNYA;Mn;0;NSM;;;;;N;;;;;
+17D1;KHMER SIGN VIRIAM;Mn;0;NSM;;;;;N;;;;;
+17D2;KHMER SIGN COENG;Mn;9;NSM;;;;;N;;;;;
+17D3;KHMER SIGN BATHAMASAT;Mn;0;NSM;;;;;N;;*;;;
+17D4;KHMER SIGN KHAN;Po;0;L;;;;;N;;;;;
+17D5;KHMER SIGN BARIYOOSAN;Po;0;L;;;;;N;;;;;
+17D6;KHMER SIGN CAMNUC PII KUUH;Po;0;L;;;;;N;;;;;
+17D7;KHMER SIGN LEK TOO;Lm;0;L;;;;;N;;;;;
+17D8;KHMER SIGN BEYYAL;Po;0;L;;;;;N;;*;;;
+17D9;KHMER SIGN PHNAEK MUAN;Po;0;L;;;;;N;;;;;
+17DA;KHMER SIGN KOOMUUT;Po;0;L;;;;;N;;;;;
+17DB;KHMER CURRENCY SYMBOL RIEL;Sc;0;ET;;;;;N;;;;;
+17DC;KHMER SIGN AVAKRAHASANYA;Lo;0;L;;;;;N;;;;;
+17DD;KHMER SIGN ATTHACAN;Mn;230;NSM;;;;;N;;;;;
+17E0;KHMER DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+17E1;KHMER DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+17E2;KHMER DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+17E3;KHMER DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+17E4;KHMER DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+17E5;KHMER DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+17E6;KHMER DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+17E7;KHMER DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+17E8;KHMER DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+17E9;KHMER DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+17F0;KHMER SYMBOL LEK ATTAK SON;No;0;ON;;;;0;N;;;;;
+17F1;KHMER SYMBOL LEK ATTAK MUOY;No;0;ON;;;;1;N;;;;;
+17F2;KHMER SYMBOL LEK ATTAK PII;No;0;ON;;;;2;N;;;;;
+17F3;KHMER SYMBOL LEK ATTAK BEI;No;0;ON;;;;3;N;;;;;
+17F4;KHMER SYMBOL LEK ATTAK BUON;No;0;ON;;;;4;N;;;;;
+17F5;KHMER SYMBOL LEK ATTAK PRAM;No;0;ON;;;;5;N;;;;;
+17F6;KHMER SYMBOL LEK ATTAK PRAM-MUOY;No;0;ON;;;;6;N;;;;;
+17F7;KHMER SYMBOL LEK ATTAK PRAM-PII;No;0;ON;;;;7;N;;;;;
+17F8;KHMER SYMBOL LEK ATTAK PRAM-BEI;No;0;ON;;;;8;N;;;;;
+17F9;KHMER SYMBOL LEK ATTAK PRAM-BUON;No;0;ON;;;;9;N;;;;;
+1800;MONGOLIAN BIRGA;Po;0;ON;;;;;N;;;;;
+1801;MONGOLIAN ELLIPSIS;Po;0;ON;;;;;N;;;;;
+1802;MONGOLIAN COMMA;Po;0;ON;;;;;N;;;;;
+1803;MONGOLIAN FULL STOP;Po;0;ON;;;;;N;;;;;
+1804;MONGOLIAN COLON;Po;0;ON;;;;;N;;;;;
+1805;MONGOLIAN FOUR DOTS;Po;0;ON;;;;;N;;;;;
+1806;MONGOLIAN TODO SOFT HYPHEN;Pd;0;ON;;;;;N;;;;;
+1807;MONGOLIAN SIBE SYLLABLE BOUNDARY MARKER;Po;0;ON;;;;;N;;;;;
+1808;MONGOLIAN MANCHU COMMA;Po;0;ON;;;;;N;;;;;
+1809;MONGOLIAN MANCHU FULL STOP;Po;0;ON;;;;;N;;;;;
+180A;MONGOLIAN NIRUGU;Po;0;ON;;;;;N;;;;;
+180B;MONGOLIAN FREE VARIATION SELECTOR ONE;Mn;0;NSM;;;;;N;;;;;
+180C;MONGOLIAN FREE VARIATION SELECTOR TWO;Mn;0;NSM;;;;;N;;;;;
+180D;MONGOLIAN FREE VARIATION SELECTOR THREE;Mn;0;NSM;;;;;N;;;;;
+180E;MONGOLIAN VOWEL SEPARATOR;Zs;0;WS;;;;;N;;;;;
+1810;MONGOLIAN DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+1811;MONGOLIAN DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+1812;MONGOLIAN DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+1813;MONGOLIAN DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+1814;MONGOLIAN DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+1815;MONGOLIAN DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+1816;MONGOLIAN DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+1817;MONGOLIAN DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+1818;MONGOLIAN DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+1819;MONGOLIAN DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+1820;MONGOLIAN LETTER A;Lo;0;L;;;;;N;;;;;
+1821;MONGOLIAN LETTER E;Lo;0;L;;;;;N;;;;;
+1822;MONGOLIAN LETTER I;Lo;0;L;;;;;N;;;;;
+1823;MONGOLIAN LETTER O;Lo;0;L;;;;;N;;;;;
+1824;MONGOLIAN LETTER U;Lo;0;L;;;;;N;;;;;
+1825;MONGOLIAN LETTER OE;Lo;0;L;;;;;N;;;;;
+1826;MONGOLIAN LETTER UE;Lo;0;L;;;;;N;;;;;
+1827;MONGOLIAN LETTER EE;Lo;0;L;;;;;N;;;;;
+1828;MONGOLIAN LETTER NA;Lo;0;L;;;;;N;;;;;
+1829;MONGOLIAN LETTER ANG;Lo;0;L;;;;;N;;;;;
+182A;MONGOLIAN LETTER BA;Lo;0;L;;;;;N;;;;;
+182B;MONGOLIAN LETTER PA;Lo;0;L;;;;;N;;;;;
+182C;MONGOLIAN LETTER QA;Lo;0;L;;;;;N;;;;;
+182D;MONGOLIAN LETTER GA;Lo;0;L;;;;;N;;;;;
+182E;MONGOLIAN LETTER MA;Lo;0;L;;;;;N;;;;;
+182F;MONGOLIAN LETTER LA;Lo;0;L;;;;;N;;;;;
+1830;MONGOLIAN LETTER SA;Lo;0;L;;;;;N;;;;;
+1831;MONGOLIAN LETTER SHA;Lo;0;L;;;;;N;;;;;
+1832;MONGOLIAN LETTER TA;Lo;0;L;;;;;N;;;;;
+1833;MONGOLIAN LETTER DA;Lo;0;L;;;;;N;;;;;
+1834;MONGOLIAN LETTER CHA;Lo;0;L;;;;;N;;;;;
+1835;MONGOLIAN LETTER JA;Lo;0;L;;;;;N;;;;;
+1836;MONGOLIAN LETTER YA;Lo;0;L;;;;;N;;;;;
+1837;MONGOLIAN LETTER RA;Lo;0;L;;;;;N;;;;;
+1838;MONGOLIAN LETTER WA;Lo;0;L;;;;;N;;;;;
+1839;MONGOLIAN LETTER FA;Lo;0;L;;;;;N;;;;;
+183A;MONGOLIAN LETTER KA;Lo;0;L;;;;;N;;;;;
+183B;MONGOLIAN LETTER KHA;Lo;0;L;;;;;N;;;;;
+183C;MONGOLIAN LETTER TSA;Lo;0;L;;;;;N;;;;;
+183D;MONGOLIAN LETTER ZA;Lo;0;L;;;;;N;;;;;
+183E;MONGOLIAN LETTER HAA;Lo;0;L;;;;;N;;;;;
+183F;MONGOLIAN LETTER ZRA;Lo;0;L;;;;;N;;;;;
+1840;MONGOLIAN LETTER LHA;Lo;0;L;;;;;N;;;;;
+1841;MONGOLIAN LETTER ZHI;Lo;0;L;;;;;N;;;;;
+1842;MONGOLIAN LETTER CHI;Lo;0;L;;;;;N;;;;;
+1843;MONGOLIAN LETTER TODO LONG VOWEL SIGN;Lm;0;L;;;;;N;;;;;
+1844;MONGOLIAN LETTER TODO E;Lo;0;L;;;;;N;;;;;
+1845;MONGOLIAN LETTER TODO I;Lo;0;L;;;;;N;;;;;
+1846;MONGOLIAN LETTER TODO O;Lo;0;L;;;;;N;;;;;
+1847;MONGOLIAN LETTER TODO U;Lo;0;L;;;;;N;;;;;
+1848;MONGOLIAN LETTER TODO OE;Lo;0;L;;;;;N;;;;;
+1849;MONGOLIAN LETTER TODO UE;Lo;0;L;;;;;N;;;;;
+184A;MONGOLIAN LETTER TODO ANG;Lo;0;L;;;;;N;;;;;
+184B;MONGOLIAN LETTER TODO BA;Lo;0;L;;;;;N;;;;;
+184C;MONGOLIAN LETTER TODO PA;Lo;0;L;;;;;N;;;;;
+184D;MONGOLIAN LETTER TODO QA;Lo;0;L;;;;;N;;;;;
+184E;MONGOLIAN LETTER TODO GA;Lo;0;L;;;;;N;;;;;
+184F;MONGOLIAN LETTER TODO MA;Lo;0;L;;;;;N;;;;;
+1850;MONGOLIAN LETTER TODO TA;Lo;0;L;;;;;N;;;;;
+1851;MONGOLIAN LETTER TODO DA;Lo;0;L;;;;;N;;;;;
+1852;MONGOLIAN LETTER TODO CHA;Lo;0;L;;;;;N;;;;;
+1853;MONGOLIAN LETTER TODO JA;Lo;0;L;;;;;N;;;;;
+1854;MONGOLIAN LETTER TODO TSA;Lo;0;L;;;;;N;;;;;
+1855;MONGOLIAN LETTER TODO YA;Lo;0;L;;;;;N;;;;;
+1856;MONGOLIAN LETTER TODO WA;Lo;0;L;;;;;N;;;;;
+1857;MONGOLIAN LETTER TODO KA;Lo;0;L;;;;;N;;;;;
+1858;MONGOLIAN LETTER TODO GAA;Lo;0;L;;;;;N;;;;;
+1859;MONGOLIAN LETTER TODO HAA;Lo;0;L;;;;;N;;;;;
+185A;MONGOLIAN LETTER TODO JIA;Lo;0;L;;;;;N;;;;;
+185B;MONGOLIAN LETTER TODO NIA;Lo;0;L;;;;;N;;;;;
+185C;MONGOLIAN LETTER TODO DZA;Lo;0;L;;;;;N;;;;;
+185D;MONGOLIAN LETTER SIBE E;Lo;0;L;;;;;N;;;;;
+185E;MONGOLIAN LETTER SIBE I;Lo;0;L;;;;;N;;;;;
+185F;MONGOLIAN LETTER SIBE IY;Lo;0;L;;;;;N;;;;;
+1860;MONGOLIAN LETTER SIBE UE;Lo;0;L;;;;;N;;;;;
+1861;MONGOLIAN LETTER SIBE U;Lo;0;L;;;;;N;;;;;
+1862;MONGOLIAN LETTER SIBE ANG;Lo;0;L;;;;;N;;;;;
+1863;MONGOLIAN LETTER SIBE KA;Lo;0;L;;;;;N;;;;;
+1864;MONGOLIAN LETTER SIBE GA;Lo;0;L;;;;;N;;;;;
+1865;MONGOLIAN LETTER SIBE HA;Lo;0;L;;;;;N;;;;;
+1866;MONGOLIAN LETTER SIBE PA;Lo;0;L;;;;;N;;;;;
+1867;MONGOLIAN LETTER SIBE SHA;Lo;0;L;;;;;N;;;;;
+1868;MONGOLIAN LETTER SIBE TA;Lo;0;L;;;;;N;;;;;
+1869;MONGOLIAN LETTER SIBE DA;Lo;0;L;;;;;N;;;;;
+186A;MONGOLIAN LETTER SIBE JA;Lo;0;L;;;;;N;;;;;
+186B;MONGOLIAN LETTER SIBE FA;Lo;0;L;;;;;N;;;;;
+186C;MONGOLIAN LETTER SIBE GAA;Lo;0;L;;;;;N;;;;;
+186D;MONGOLIAN LETTER SIBE HAA;Lo;0;L;;;;;N;;;;;
+186E;MONGOLIAN LETTER SIBE TSA;Lo;0;L;;;;;N;;;;;
+186F;MONGOLIAN LETTER SIBE ZA;Lo;0;L;;;;;N;;;;;
+1870;MONGOLIAN LETTER SIBE RAA;Lo;0;L;;;;;N;;;;;
+1871;MONGOLIAN LETTER SIBE CHA;Lo;0;L;;;;;N;;;;;
+1872;MONGOLIAN LETTER SIBE ZHA;Lo;0;L;;;;;N;;;;;
+1873;MONGOLIAN LETTER MANCHU I;Lo;0;L;;;;;N;;;;;
+1874;MONGOLIAN LETTER MANCHU KA;Lo;0;L;;;;;N;;;;;
+1875;MONGOLIAN LETTER MANCHU RA;Lo;0;L;;;;;N;;;;;
+1876;MONGOLIAN LETTER MANCHU FA;Lo;0;L;;;;;N;;;;;
+1877;MONGOLIAN LETTER MANCHU ZHA;Lo;0;L;;;;;N;;;;;
+1880;MONGOLIAN LETTER ALI GALI ANUSVARA ONE;Lo;0;L;;;;;N;;;;;
+1881;MONGOLIAN LETTER ALI GALI VISARGA ONE;Lo;0;L;;;;;N;;;;;
+1882;MONGOLIAN LETTER ALI GALI DAMARU;Lo;0;L;;;;;N;;;;;
+1883;MONGOLIAN LETTER ALI GALI UBADAMA;Lo;0;L;;;;;N;;;;;
+1884;MONGOLIAN LETTER ALI GALI INVERTED UBADAMA;Lo;0;L;;;;;N;;;;;
+1885;MONGOLIAN LETTER ALI GALI BALUDA;Lo;0;L;;;;;N;;;;;
+1886;MONGOLIAN LETTER ALI GALI THREE BALUDA;Lo;0;L;;;;;N;;;;;
+1887;MONGOLIAN LETTER ALI GALI A;Lo;0;L;;;;;N;;;;;
+1888;MONGOLIAN LETTER ALI GALI I;Lo;0;L;;;;;N;;;;;
+1889;MONGOLIAN LETTER ALI GALI KA;Lo;0;L;;;;;N;;;;;
+188A;MONGOLIAN LETTER ALI GALI NGA;Lo;0;L;;;;;N;;;;;
+188B;MONGOLIAN LETTER ALI GALI CA;Lo;0;L;;;;;N;;;;;
+188C;MONGOLIAN LETTER ALI GALI TTA;Lo;0;L;;;;;N;;;;;
+188D;MONGOLIAN LETTER ALI GALI TTHA;Lo;0;L;;;;;N;;;;;
+188E;MONGOLIAN LETTER ALI GALI DDA;Lo;0;L;;;;;N;;;;;
+188F;MONGOLIAN LETTER ALI GALI NNA;Lo;0;L;;;;;N;;;;;
+1890;MONGOLIAN LETTER ALI GALI TA;Lo;0;L;;;;;N;;;;;
+1891;MONGOLIAN LETTER ALI GALI DA;Lo;0;L;;;;;N;;;;;
+1892;MONGOLIAN LETTER ALI GALI PA;Lo;0;L;;;;;N;;;;;
+1893;MONGOLIAN LETTER ALI GALI PHA;Lo;0;L;;;;;N;;;;;
+1894;MONGOLIAN LETTER ALI GALI SSA;Lo;0;L;;;;;N;;;;;
+1895;MONGOLIAN LETTER ALI GALI ZHA;Lo;0;L;;;;;N;;;;;
+1896;MONGOLIAN LETTER ALI GALI ZA;Lo;0;L;;;;;N;;;;;
+1897;MONGOLIAN LETTER ALI GALI AH;Lo;0;L;;;;;N;;;;;
+1898;MONGOLIAN LETTER TODO ALI GALI TA;Lo;0;L;;;;;N;;;;;
+1899;MONGOLIAN LETTER TODO ALI GALI ZHA;Lo;0;L;;;;;N;;;;;
+189A;MONGOLIAN LETTER MANCHU ALI GALI GHA;Lo;0;L;;;;;N;;;;;
+189B;MONGOLIAN LETTER MANCHU ALI GALI NGA;Lo;0;L;;;;;N;;;;;
+189C;MONGOLIAN LETTER MANCHU ALI GALI CA;Lo;0;L;;;;;N;;;;;
+189D;MONGOLIAN LETTER MANCHU ALI GALI JHA;Lo;0;L;;;;;N;;;;;
+189E;MONGOLIAN LETTER MANCHU ALI GALI TTA;Lo;0;L;;;;;N;;;;;
+189F;MONGOLIAN LETTER MANCHU ALI GALI DDHA;Lo;0;L;;;;;N;;;;;
+18A0;MONGOLIAN LETTER MANCHU ALI GALI TA;Lo;0;L;;;;;N;;;;;
+18A1;MONGOLIAN LETTER MANCHU ALI GALI DHA;Lo;0;L;;;;;N;;;;;
+18A2;MONGOLIAN LETTER MANCHU ALI GALI SSA;Lo;0;L;;;;;N;;;;;
+18A3;MONGOLIAN LETTER MANCHU ALI GALI CYA;Lo;0;L;;;;;N;;;;;
+18A4;MONGOLIAN LETTER MANCHU ALI GALI ZHA;Lo;0;L;;;;;N;;;;;
+18A5;MONGOLIAN LETTER MANCHU ALI GALI ZA;Lo;0;L;;;;;N;;;;;
+18A6;MONGOLIAN LETTER ALI GALI HALF U;Lo;0;L;;;;;N;;;;;
+18A7;MONGOLIAN LETTER ALI GALI HALF YA;Lo;0;L;;;;;N;;;;;
+18A8;MONGOLIAN LETTER MANCHU ALI GALI BHA;Lo;0;L;;;;;N;;;;;
+18A9;MONGOLIAN LETTER ALI GALI DAGALGA;Mn;228;NSM;;;;;N;;;;;
+1900;LIMBU VOWEL-CARRIER LETTER;Lo;0;L;;;;;N;;;;;
+1901;LIMBU LETTER KA;Lo;0;L;;;;;N;;;;;
+1902;LIMBU LETTER KHA;Lo;0;L;;;;;N;;;;;
+1903;LIMBU LETTER GA;Lo;0;L;;;;;N;;;;;
+1904;LIMBU LETTER GHA;Lo;0;L;;;;;N;;;;;
+1905;LIMBU LETTER NGA;Lo;0;L;;;;;N;;;;;
+1906;LIMBU LETTER CA;Lo;0;L;;;;;N;;;;;
+1907;LIMBU LETTER CHA;Lo;0;L;;;;;N;;;;;
+1908;LIMBU LETTER JA;Lo;0;L;;;;;N;;;;;
+1909;LIMBU LETTER JHA;Lo;0;L;;;;;N;;;;;
+190A;LIMBU LETTER YAN;Lo;0;L;;;;;N;;;;;
+190B;LIMBU LETTER TA;Lo;0;L;;;;;N;;;;;
+190C;LIMBU LETTER THA;Lo;0;L;;;;;N;;;;;
+190D;LIMBU LETTER DA;Lo;0;L;;;;;N;;;;;
+190E;LIMBU LETTER DHA;Lo;0;L;;;;;N;;;;;
+190F;LIMBU LETTER NA;Lo;0;L;;;;;N;;;;;
+1910;LIMBU LETTER PA;Lo;0;L;;;;;N;;;;;
+1911;LIMBU LETTER PHA;Lo;0;L;;;;;N;;;;;
+1912;LIMBU LETTER BA;Lo;0;L;;;;;N;;;;;
+1913;LIMBU LETTER BHA;Lo;0;L;;;;;N;;;;;
+1914;LIMBU LETTER MA;Lo;0;L;;;;;N;;;;;
+1915;LIMBU LETTER YA;Lo;0;L;;;;;N;;;;;
+1916;LIMBU LETTER RA;Lo;0;L;;;;;N;;;;;
+1917;LIMBU LETTER LA;Lo;0;L;;;;;N;;;;;
+1918;LIMBU LETTER WA;Lo;0;L;;;;;N;;;;;
+1919;LIMBU LETTER SHA;Lo;0;L;;;;;N;;;;;
+191A;LIMBU LETTER SSA;Lo;0;L;;;;;N;;;;;
+191B;LIMBU LETTER SA;Lo;0;L;;;;;N;;;;;
+191C;LIMBU LETTER HA;Lo;0;L;;;;;N;;;;;
+1920;LIMBU VOWEL SIGN A;Mn;0;NSM;;;;;N;;;;;
+1921;LIMBU VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;;
+1922;LIMBU VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;;
+1923;LIMBU VOWEL SIGN EE;Mc;0;L;;;;;N;;;;;
+1924;LIMBU VOWEL SIGN AI;Mc;0;L;;;;;N;;;;;
+1925;LIMBU VOWEL SIGN OO;Mc;0;L;;;;;N;;;;;
+1926;LIMBU VOWEL SIGN AU;Mc;0;L;;;;;N;;;;;
+1927;LIMBU VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;;
+1928;LIMBU VOWEL SIGN O;Mn;0;NSM;;;;;N;;;;;
+1929;LIMBU SUBJOINED LETTER YA;Mc;0;NSM;;;;;N;;;;;
+192A;LIMBU SUBJOINED LETTER RA;Mc;0;NSM;;;;;N;;;;;
+192B;LIMBU SUBJOINED LETTER WA;Mc;0;NSM;;;;;N;;;;;
+1930;LIMBU SMALL LETTER KA;Mc;0;L;;;;;N;;;;;
+1931;LIMBU SMALL LETTER NGA;Mc;0;L;;;;;N;;;;;
+1932;LIMBU SMALL LETTER ANUSVARA;Mn;0;NSM;;;;;N;;;;;
+1933;LIMBU SMALL LETTER TA;Mc;0;L;;;;;N;;;;;
+1934;LIMBU SMALL LETTER NA;Mc;0;L;;;;;N;;;;;
+1935;LIMBU SMALL LETTER PA;Mc;0;L;;;;;N;;;;;
+1936;LIMBU SMALL LETTER MA;Mc;0;L;;;;;N;;;;;
+1937;LIMBU SMALL LETTER RA;Mc;0;L;;;;;N;;;;;
+1938;LIMBU SMALL LETTER LA;Mc;0;L;;;;;N;;;;;
+1939;LIMBU SIGN MUKPHRENG;Mn;222;NSM;;;;;N;;;;;
+193A;LIMBU SIGN KEMPHRENG;Mn;230;NSM;;;;;N;;;;;
+193B;LIMBU SIGN SA-I;Mn;220;NSM;;;;;N;;;;;
+1940;LIMBU SIGN LOO;So;0;ON;;;;;N;;;;;
+1944;LIMBU EXCLAMATION MARK;Po;0;ON;;;;;N;;;;;
+1945;LIMBU QUESTION MARK;Po;0;ON;;;;;N;;;;;
+1946;LIMBU DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+1947;LIMBU DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+1948;LIMBU DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+1949;LIMBU DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+194A;LIMBU DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+194B;LIMBU DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+194C;LIMBU DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+194D;LIMBU DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+194E;LIMBU DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+194F;LIMBU DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+1950;TAI LE LETTER KA;Lo;0;L;;;;;N;;;;;
+1951;TAI LE LETTER XA;Lo;0;L;;;;;N;;;;;
+1952;TAI LE LETTER NGA;Lo;0;L;;;;;N;;;;;
+1953;TAI LE LETTER TSA;Lo;0;L;;;;;N;;;;;
+1954;TAI LE LETTER SA;Lo;0;L;;;;;N;;;;;
+1955;TAI LE LETTER YA;Lo;0;L;;;;;N;;;;;
+1956;TAI LE LETTER TA;Lo;0;L;;;;;N;;;;;
+1957;TAI LE LETTER THA;Lo;0;L;;;;;N;;;;;
+1958;TAI LE LETTER LA;Lo;0;L;;;;;N;;;;;
+1959;TAI LE LETTER PA;Lo;0;L;;;;;N;;;;;
+195A;TAI LE LETTER PHA;Lo;0;L;;;;;N;;;;;
+195B;TAI LE LETTER MA;Lo;0;L;;;;;N;;;;;
+195C;TAI LE LETTER FA;Lo;0;L;;;;;N;;;;;
+195D;TAI LE LETTER VA;Lo;0;L;;;;;N;;;;;
+195E;TAI LE LETTER HA;Lo;0;L;;;;;N;;;;;
+195F;TAI LE LETTER QA;Lo;0;L;;;;;N;;;;;
+1960;TAI LE LETTER KHA;Lo;0;L;;;;;N;;;;;
+1961;TAI LE LETTER TSHA;Lo;0;L;;;;;N;;;;;
+1962;TAI LE LETTER NA;Lo;0;L;;;;;N;;;;;
+1963;TAI LE LETTER A;Lo;0;L;;;;;N;;;;;
+1964;TAI LE LETTER I;Lo;0;L;;;;;N;;;;;
+1965;TAI LE LETTER EE;Lo;0;L;;;;;N;;;;;
+1966;TAI LE LETTER EH;Lo;0;L;;;;;N;;;;;
+1967;TAI LE LETTER U;Lo;0;L;;;;;N;;;;;
+1968;TAI LE LETTER OO;Lo;0;L;;;;;N;;;;;
+1969;TAI LE LETTER O;Lo;0;L;;;;;N;;;;;
+196A;TAI LE LETTER UE;Lo;0;L;;;;;N;;;;;
+196B;TAI LE LETTER E;Lo;0;L;;;;;N;;;;;
+196C;TAI LE LETTER AUE;Lo;0;L;;;;;N;;;;;
+196D;TAI LE LETTER AI;Lo;0;L;;;;;N;;;;;
+1970;TAI LE LETTER TONE-2;Lo;0;L;;;;;N;;;;;
+1971;TAI LE LETTER TONE-3;Lo;0;L;;;;;N;;;;;
+1972;TAI LE LETTER TONE-4;Lo;0;L;;;;;N;;;;;
+1973;TAI LE LETTER TONE-5;Lo;0;L;;;;;N;;;;;
+1974;TAI LE LETTER TONE-6;Lo;0;L;;;;;N;;;;;
+19E0;KHMER SYMBOL PATHAMASAT;So;0;ON;;;;;N;;;;;
+19E1;KHMER SYMBOL MUOY KOET;So;0;ON;;;;;N;;;;;
+19E2;KHMER SYMBOL PII KOET;So;0;ON;;;;;N;;;;;
+19E3;KHMER SYMBOL BEI KOET;So;0;ON;;;;;N;;;;;
+19E4;KHMER SYMBOL BUON KOET;So;0;ON;;;;;N;;;;;
+19E5;KHMER SYMBOL PRAM KOET;So;0;ON;;;;;N;;;;;
+19E6;KHMER SYMBOL PRAM-MUOY KOET;So;0;ON;;;;;N;;;;;
+19E7;KHMER SYMBOL PRAM-PII KOET;So;0;ON;;;;;N;;;;;
+19E8;KHMER SYMBOL PRAM-BEI KOET;So;0;ON;;;;;N;;;;;
+19E9;KHMER SYMBOL PRAM-BUON KOET;So;0;ON;;;;;N;;;;;
+19EA;KHMER SYMBOL DAP KOET;So;0;ON;;;;;N;;;;;
+19EB;KHMER SYMBOL DAP-MUOY KOET;So;0;ON;;;;;N;;;;;
+19EC;KHMER SYMBOL DAP-PII KOET;So;0;ON;;;;;N;;;;;
+19ED;KHMER SYMBOL DAP-BEI KOET;So;0;ON;;;;;N;;;;;
+19EE;KHMER SYMBOL DAP-BUON KOET;So;0;ON;;;;;N;;;;;
+19EF;KHMER SYMBOL DAP-PRAM KOET;So;0;ON;;;;;N;;;;;
+19F0;KHMER SYMBOL TUTEYASAT;So;0;ON;;;;;N;;;;;
+19F1;KHMER SYMBOL MUOY ROC;So;0;ON;;;;;N;;;;;
+19F2;KHMER SYMBOL PII ROC;So;0;ON;;;;;N;;;;;
+19F3;KHMER SYMBOL BEI ROC;So;0;ON;;;;;N;;;;;
+19F4;KHMER SYMBOL BUON ROC;So;0;ON;;;;;N;;;;;
+19F5;KHMER SYMBOL PRAM ROC;So;0;ON;;;;;N;;;;;
+19F6;KHMER SYMBOL PRAM-MUOY ROC;So;0;ON;;;;;N;;;;;
+19F7;KHMER SYMBOL PRAM-PII ROC;So;0;ON;;;;;N;;;;;
+19F8;KHMER SYMBOL PRAM-BEI ROC;So;0;ON;;;;;N;;;;;
+19F9;KHMER SYMBOL PRAM-BUON ROC;So;0;ON;;;;;N;;;;;
+19FA;KHMER SYMBOL DAP ROC;So;0;ON;;;;;N;;;;;
+19FB;KHMER SYMBOL DAP-MUOY ROC;So;0;ON;;;;;N;;;;;
+19FC;KHMER SYMBOL DAP-PII ROC;So;0;ON;;;;;N;;;;;
+19FD;KHMER SYMBOL DAP-BEI ROC;So;0;ON;;;;;N;;;;;
+19FE;KHMER SYMBOL DAP-BUON ROC;So;0;ON;;;;;N;;;;;
+19FF;KHMER SYMBOL DAP-PRAM ROC;So;0;ON;;;;;N;;;;;
+1D00;LATIN LETTER SMALL CAPITAL A;Ll;0;L;;;;;N;;;;;
+1D01;LATIN LETTER SMALL CAPITAL AE;Ll;0;L;;;;;N;;;;;
+1D02;LATIN SMALL LETTER TURNED AE;Ll;0;L;;;;;N;;;;;
+1D03;LATIN LETTER SMALL CAPITAL BARRED B;Ll;0;L;;;;;N;;;;;
+1D04;LATIN LETTER SMALL CAPITAL C;Ll;0;L;;;;;N;;;;;
+1D05;LATIN LETTER SMALL CAPITAL D;Ll;0;L;;;;;N;;;;;
+1D06;LATIN LETTER SMALL CAPITAL ETH;Ll;0;L;;;;;N;;;;;
+1D07;LATIN LETTER SMALL CAPITAL E;Ll;0;L;;;;;N;;;;;
+1D08;LATIN SMALL LETTER TURNED OPEN E;Ll;0;L;;;;;N;;;;;
+1D09;LATIN SMALL LETTER TURNED I;Ll;0;L;;;;;N;;;;;
+1D0A;LATIN LETTER SMALL CAPITAL J;Ll;0;L;;;;;N;;;;;
+1D0B;LATIN LETTER SMALL CAPITAL K;Ll;0;L;;;;;N;;;;;
+1D0C;LATIN LETTER SMALL CAPITAL L WITH STROKE;Ll;0;L;;;;;N;;;;;
+1D0D;LATIN LETTER SMALL CAPITAL M;Ll;0;L;;;;;N;;;;;
+1D0E;LATIN LETTER SMALL CAPITAL REVERSED N;Ll;0;L;;;;;N;;;;;
+1D0F;LATIN LETTER SMALL CAPITAL O;Ll;0;L;;;;;N;;;;;
+1D10;LATIN LETTER SMALL CAPITAL OPEN O;Ll;0;L;;;;;N;;;;;
+1D11;LATIN SMALL LETTER SIDEWAYS O;Ll;0;L;;;;;N;;;;;
+1D12;LATIN SMALL LETTER SIDEWAYS OPEN O;Ll;0;L;;;;;N;;;;;
+1D13;LATIN SMALL LETTER SIDEWAYS O WITH STROKE;Ll;0;L;;;;;N;;;;;
+1D14;LATIN SMALL LETTER TURNED OE;Ll;0;L;;;;;N;;;;;
+1D15;LATIN LETTER SMALL CAPITAL OU;Ll;0;L;;;;;N;;;;;
+1D16;LATIN SMALL LETTER TOP HALF O;Ll;0;L;;;;;N;;;;;
+1D17;LATIN SMALL LETTER BOTTOM HALF O;Ll;0;L;;;;;N;;;;;
+1D18;LATIN LETTER SMALL CAPITAL P;Ll;0;L;;;;;N;;;;;
+1D19;LATIN LETTER SMALL CAPITAL REVERSED R;Ll;0;L;;;;;N;;;;;
+1D1A;LATIN LETTER SMALL CAPITAL TURNED R;Ll;0;L;;;;;N;;;;;
+1D1B;LATIN LETTER SMALL CAPITAL T;Ll;0;L;;;;;N;;;;;
+1D1C;LATIN LETTER SMALL CAPITAL U;Ll;0;L;;;;;N;;;;;
+1D1D;LATIN SMALL LETTER SIDEWAYS U;Ll;0;L;;;;;N;;;;;
+1D1E;LATIN SMALL LETTER SIDEWAYS DIAERESIZED U;Ll;0;L;;;;;N;;;;;
+1D1F;LATIN SMALL LETTER SIDEWAYS TURNED M;Ll;0;L;;;;;N;;;;;
+1D20;LATIN LETTER SMALL CAPITAL V;Ll;0;L;;;;;N;;;;;
+1D21;LATIN LETTER SMALL CAPITAL W;Ll;0;L;;;;;N;;;;;
+1D22;LATIN LETTER SMALL CAPITAL Z;Ll;0;L;;;;;N;;;;;
+1D23;LATIN LETTER SMALL CAPITAL EZH;Ll;0;L;;;;;N;;;;;
+1D24;LATIN LETTER VOICED LARYNGEAL SPIRANT;Ll;0;L;;;;;N;;;;;
+1D25;LATIN LETTER AIN;Ll;0;L;;;;;N;;;;;
+1D26;GREEK LETTER SMALL CAPITAL GAMMA;Ll;0;L;;;;;N;;;;;
+1D27;GREEK LETTER SMALL CAPITAL LAMDA;Ll;0;L;;;;;N;;;;;
+1D28;GREEK LETTER SMALL CAPITAL PI;Ll;0;L;;;;;N;;;;;
+1D29;GREEK LETTER SMALL CAPITAL RHO;Ll;0;L;;;;;N;;;;;
+1D2A;GREEK LETTER SMALL CAPITAL PSI;Ll;0;L;;;;;N;;;;;
+1D2B;CYRILLIC LETTER SMALL CAPITAL EL;Ll;0;L;;;;;N;;;;;
+1D2C;MODIFIER LETTER CAPITAL A;Lm;0;L;<super> 0041;;;;N;;;;;
+1D2D;MODIFIER LETTER CAPITAL AE;Lm;0;L;<super> 00C6;;;;N;;;;;
+1D2E;MODIFIER LETTER CAPITAL B;Lm;0;L;<super> 0042;;;;N;;;;;
+1D2F;MODIFIER LETTER CAPITAL BARRED B;Lm;0;L;;;;;N;;;;;
+1D30;MODIFIER LETTER CAPITAL D;Lm;0;L;<super> 0044;;;;N;;;;;
+1D31;MODIFIER LETTER CAPITAL E;Lm;0;L;<super> 0045;;;;N;;;;;
+1D32;MODIFIER LETTER CAPITAL REVERSED E;Lm;0;L;<super> 018E;;;;N;;;;;
+1D33;MODIFIER LETTER CAPITAL G;Lm;0;L;<super> 0047;;;;N;;;;;
+1D34;MODIFIER LETTER CAPITAL H;Lm;0;L;<super> 0048;;;;N;;;;;
+1D35;MODIFIER LETTER CAPITAL I;Lm;0;L;<super> 0049;;;;N;;;;;
+1D36;MODIFIER LETTER CAPITAL J;Lm;0;L;<super> 004A;;;;N;;;;;
+1D37;MODIFIER LETTER CAPITAL K;Lm;0;L;<super> 004B;;;;N;;;;;
+1D38;MODIFIER LETTER CAPITAL L;Lm;0;L;<super> 004C;;;;N;;;;;
+1D39;MODIFIER LETTER CAPITAL M;Lm;0;L;<super> 004D;;;;N;;;;;
+1D3A;MODIFIER LETTER CAPITAL N;Lm;0;L;<super> 004E;;;;N;;;;;
+1D3B;MODIFIER LETTER CAPITAL REVERSED N;Lm;0;L;;;;;N;;;;;
+1D3C;MODIFIER LETTER CAPITAL O;Lm;0;L;<super> 004F;;;;N;;;;;
+1D3D;MODIFIER LETTER CAPITAL OU;Lm;0;L;<super> 0222;;;;N;;;;;
+1D3E;MODIFIER LETTER CAPITAL P;Lm;0;L;<super> 0050;;;;N;;;;;
+1D3F;MODIFIER LETTER CAPITAL R;Lm;0;L;<super> 0052;;;;N;;;;;
+1D40;MODIFIER LETTER CAPITAL T;Lm;0;L;<super> 0054;;;;N;;;;;
+1D41;MODIFIER LETTER CAPITAL U;Lm;0;L;<super> 0055;;;;N;;;;;
+1D42;MODIFIER LETTER CAPITAL W;Lm;0;L;<super> 0057;;;;N;;;;;
+1D43;MODIFIER LETTER SMALL A;Lm;0;L;<super> 0061;;;;N;;;;;
+1D44;MODIFIER LETTER SMALL TURNED A;Lm;0;L;<super> 0250;;;;N;;;;;
+1D45;MODIFIER LETTER SMALL ALPHA;Lm;0;L;<super> 0251;;;;N;;;;;
+1D46;MODIFIER LETTER SMALL TURNED AE;Lm;0;L;<super> 1D02;;;;N;;;;;
+1D47;MODIFIER LETTER SMALL B;Lm;0;L;<super> 0062;;;;N;;;;;
+1D48;MODIFIER LETTER SMALL D;Lm;0;L;<super> 0064;;;;N;;;;;
+1D49;MODIFIER LETTER SMALL E;Lm;0;L;<super> 0065;;;;N;;;;;
+1D4A;MODIFIER LETTER SMALL SCHWA;Lm;0;L;<super> 0259;;;;N;;;;;
+1D4B;MODIFIER LETTER SMALL OPEN E;Lm;0;L;<super> 025B;;;;N;;;;;
+1D4C;MODIFIER LETTER SMALL TURNED OPEN E;Lm;0;L;<super> 025C;;;;N;;;;;
+1D4D;MODIFIER LETTER SMALL G;Lm;0;L;<super> 0067;;;;N;;;;;
+1D4E;MODIFIER LETTER SMALL TURNED I;Lm;0;L;;;;;N;;;;;
+1D4F;MODIFIER LETTER SMALL K;Lm;0;L;<super> 006B;;;;N;;;;;
+1D50;MODIFIER LETTER SMALL M;Lm;0;L;<super> 006D;;;;N;;;;;
+1D51;MODIFIER LETTER SMALL ENG;Lm;0;L;<super> 014B;;;;N;;;;;
+1D52;MODIFIER LETTER SMALL O;Lm;0;L;<super> 006F;;;;N;;;;;
+1D53;MODIFIER LETTER SMALL OPEN O;Lm;0;L;<super> 0254;;;;N;;;;;
+1D54;MODIFIER LETTER SMALL TOP HALF O;Lm;0;L;<super> 1D16;;;;N;;;;;
+1D55;MODIFIER LETTER SMALL BOTTOM HALF O;Lm;0;L;<super> 1D17;;;;N;;;;;
+1D56;MODIFIER LETTER SMALL P;Lm;0;L;<super> 0070;;;;N;;;;;
+1D57;MODIFIER LETTER SMALL T;Lm;0;L;<super> 0074;;;;N;;;;;
+1D58;MODIFIER LETTER SMALL U;Lm;0;L;<super> 0075;;;;N;;;;;
+1D59;MODIFIER LETTER SMALL SIDEWAYS U;Lm;0;L;<super> 1D1D;;;;N;;;;;
+1D5A;MODIFIER LETTER SMALL TURNED M;Lm;0;L;<super> 026F;;;;N;;;;;
+1D5B;MODIFIER LETTER SMALL V;Lm;0;L;<super> 0076;;;;N;;;;;
+1D5C;MODIFIER LETTER SMALL AIN;Lm;0;L;<super> 1D25;;;;N;;;;;
+1D5D;MODIFIER LETTER SMALL BETA;Lm;0;L;<super> 03B2;;;;N;;;;;
+1D5E;MODIFIER LETTER SMALL GREEK GAMMA;Lm;0;L;<super> 03B3;;;;N;;;;;
+1D5F;MODIFIER LETTER SMALL DELTA;Lm;0;L;<super> 03B4;;;;N;;;;;
+1D60;MODIFIER LETTER SMALL GREEK PHI;Lm;0;L;<super> 03C6;;;;N;;;;;
+1D61;MODIFIER LETTER SMALL CHI;Lm;0;L;<super> 03C7;;;;N;;;;;
+1D62;LATIN SUBSCRIPT SMALL LETTER I;Ll;0;L;<sub> 0069;;;;N;;;;;
+1D63;LATIN SUBSCRIPT SMALL LETTER R;Ll;0;L;<sub> 0072;;;;N;;;;;
+1D64;LATIN SUBSCRIPT SMALL LETTER U;Ll;0;L;<sub> 0075;;;;N;;;;;
+1D65;LATIN SUBSCRIPT SMALL LETTER V;Ll;0;L;<sub> 0076;;;;N;;;;;
+1D66;GREEK SUBSCRIPT SMALL LETTER BETA;Ll;0;L;<sub> 03B2;;;;N;;;;;
+1D67;GREEK SUBSCRIPT SMALL LETTER GAMMA;Ll;0;L;<sub> 03B3;;;;N;;;;;
+1D68;GREEK SUBSCRIPT SMALL LETTER RHO;Ll;0;L;<sub> 03C1;;;;N;;;;;
+1D69;GREEK SUBSCRIPT SMALL LETTER PHI;Ll;0;L;<sub> 03C6;;;;N;;;;;
+1D6A;GREEK SUBSCRIPT SMALL LETTER CHI;Ll;0;L;<sub> 03C7;;;;N;;;;;
+1D6B;LATIN SMALL LETTER UE;Ll;0;L;;;;;N;;;;;
+1E00;LATIN CAPITAL LETTER A WITH RING BELOW;Lu;0;L;0041 0325;;;;N;;;;1E01;
+1E01;LATIN SMALL LETTER A WITH RING BELOW;Ll;0;L;0061 0325;;;;N;;;1E00;;1E00
+1E02;LATIN CAPITAL LETTER B WITH DOT ABOVE;Lu;0;L;0042 0307;;;;N;;;;1E03;
+1E03;LATIN SMALL LETTER B WITH DOT ABOVE;Ll;0;L;0062 0307;;;;N;;;1E02;;1E02
+1E04;LATIN CAPITAL LETTER B WITH DOT BELOW;Lu;0;L;0042 0323;;;;N;;;;1E05;
+1E05;LATIN SMALL LETTER B WITH DOT BELOW;Ll;0;L;0062 0323;;;;N;;;1E04;;1E04
+1E06;LATIN CAPITAL LETTER B WITH LINE BELOW;Lu;0;L;0042 0331;;;;N;;;;1E07;
+1E07;LATIN SMALL LETTER B WITH LINE BELOW;Ll;0;L;0062 0331;;;;N;;;1E06;;1E06
+1E08;LATIN CAPITAL LETTER C WITH CEDILLA AND ACUTE;Lu;0;L;00C7 0301;;;;N;;;;1E09;
+1E09;LATIN SMALL LETTER C WITH CEDILLA AND ACUTE;Ll;0;L;00E7 0301;;;;N;;;1E08;;1E08
+1E0A;LATIN CAPITAL LETTER D WITH DOT ABOVE;Lu;0;L;0044 0307;;;;N;;;;1E0B;
+1E0B;LATIN SMALL LETTER D WITH DOT ABOVE;Ll;0;L;0064 0307;;;;N;;;1E0A;;1E0A
+1E0C;LATIN CAPITAL LETTER D WITH DOT BELOW;Lu;0;L;0044 0323;;;;N;;;;1E0D;
+1E0D;LATIN SMALL LETTER D WITH DOT BELOW;Ll;0;L;0064 0323;;;;N;;;1E0C;;1E0C
+1E0E;LATIN CAPITAL LETTER D WITH LINE BELOW;Lu;0;L;0044 0331;;;;N;;;;1E0F;
+1E0F;LATIN SMALL LETTER D WITH LINE BELOW;Ll;0;L;0064 0331;;;;N;;;1E0E;;1E0E
+1E10;LATIN CAPITAL LETTER D WITH CEDILLA;Lu;0;L;0044 0327;;;;N;;;;1E11;
+1E11;LATIN SMALL LETTER D WITH CEDILLA;Ll;0;L;0064 0327;;;;N;;;1E10;;1E10
+1E12;LATIN CAPITAL LETTER D WITH CIRCUMFLEX BELOW;Lu;0;L;0044 032D;;;;N;;;;1E13;
+1E13;LATIN SMALL LETTER D WITH CIRCUMFLEX BELOW;Ll;0;L;0064 032D;;;;N;;;1E12;;1E12
+1E14;LATIN CAPITAL LETTER E WITH MACRON AND GRAVE;Lu;0;L;0112 0300;;;;N;;;;1E15;
+1E15;LATIN SMALL LETTER E WITH MACRON AND GRAVE;Ll;0;L;0113 0300;;;;N;;;1E14;;1E14
+1E16;LATIN CAPITAL LETTER E WITH MACRON AND ACUTE;Lu;0;L;0112 0301;;;;N;;;;1E17;
+1E17;LATIN SMALL LETTER E WITH MACRON AND ACUTE;Ll;0;L;0113 0301;;;;N;;;1E16;;1E16
+1E18;LATIN CAPITAL LETTER E WITH CIRCUMFLEX BELOW;Lu;0;L;0045 032D;;;;N;;;;1E19;
+1E19;LATIN SMALL LETTER E WITH CIRCUMFLEX BELOW;Ll;0;L;0065 032D;;;;N;;;1E18;;1E18
+1E1A;LATIN CAPITAL LETTER E WITH TILDE BELOW;Lu;0;L;0045 0330;;;;N;;;;1E1B;
+1E1B;LATIN SMALL LETTER E WITH TILDE BELOW;Ll;0;L;0065 0330;;;;N;;;1E1A;;1E1A
+1E1C;LATIN CAPITAL LETTER E WITH CEDILLA AND BREVE;Lu;0;L;0228 0306;;;;N;;;;1E1D;
+1E1D;LATIN SMALL LETTER E WITH CEDILLA AND BREVE;Ll;0;L;0229 0306;;;;N;;;1E1C;;1E1C
+1E1E;LATIN CAPITAL LETTER F WITH DOT ABOVE;Lu;0;L;0046 0307;;;;N;;;;1E1F;
+1E1F;LATIN SMALL LETTER F WITH DOT ABOVE;Ll;0;L;0066 0307;;;;N;;;1E1E;;1E1E
+1E20;LATIN CAPITAL LETTER G WITH MACRON;Lu;0;L;0047 0304;;;;N;;;;1E21;
+1E21;LATIN SMALL LETTER G WITH MACRON;Ll;0;L;0067 0304;;;;N;;;1E20;;1E20
+1E22;LATIN CAPITAL LETTER H WITH DOT ABOVE;Lu;0;L;0048 0307;;;;N;;;;1E23;
+1E23;LATIN SMALL LETTER H WITH DOT ABOVE;Ll;0;L;0068 0307;;;;N;;;1E22;;1E22
+1E24;LATIN CAPITAL LETTER H WITH DOT BELOW;Lu;0;L;0048 0323;;;;N;;;;1E25;
+1E25;LATIN SMALL LETTER H WITH DOT BELOW;Ll;0;L;0068 0323;;;;N;;;1E24;;1E24
+1E26;LATIN CAPITAL LETTER H WITH DIAERESIS;Lu;0;L;0048 0308;;;;N;;;;1E27;
+1E27;LATIN SMALL LETTER H WITH DIAERESIS;Ll;0;L;0068 0308;;;;N;;;1E26;;1E26
+1E28;LATIN CAPITAL LETTER H WITH CEDILLA;Lu;0;L;0048 0327;;;;N;;;;1E29;
+1E29;LATIN SMALL LETTER H WITH CEDILLA;Ll;0;L;0068 0327;;;;N;;;1E28;;1E28
+1E2A;LATIN CAPITAL LETTER H WITH BREVE BELOW;Lu;0;L;0048 032E;;;;N;;;;1E2B;
+1E2B;LATIN SMALL LETTER H WITH BREVE BELOW;Ll;0;L;0068 032E;;;;N;;;1E2A;;1E2A
+1E2C;LATIN CAPITAL LETTER I WITH TILDE BELOW;Lu;0;L;0049 0330;;;;N;;;;1E2D;
+1E2D;LATIN SMALL LETTER I WITH TILDE BELOW;Ll;0;L;0069 0330;;;;N;;;1E2C;;1E2C
+1E2E;LATIN CAPITAL LETTER I WITH DIAERESIS AND ACUTE;Lu;0;L;00CF 0301;;;;N;;;;1E2F;
+1E2F;LATIN SMALL LETTER I WITH DIAERESIS AND ACUTE;Ll;0;L;00EF 0301;;;;N;;;1E2E;;1E2E
+1E30;LATIN CAPITAL LETTER K WITH ACUTE;Lu;0;L;004B 0301;;;;N;;;;1E31;
+1E31;LATIN SMALL LETTER K WITH ACUTE;Ll;0;L;006B 0301;;;;N;;;1E30;;1E30
+1E32;LATIN CAPITAL LETTER K WITH DOT BELOW;Lu;0;L;004B 0323;;;;N;;;;1E33;
+1E33;LATIN SMALL LETTER K WITH DOT BELOW;Ll;0;L;006B 0323;;;;N;;;1E32;;1E32
+1E34;LATIN CAPITAL LETTER K WITH LINE BELOW;Lu;0;L;004B 0331;;;;N;;;;1E35;
+1E35;LATIN SMALL LETTER K WITH LINE BELOW;Ll;0;L;006B 0331;;;;N;;;1E34;;1E34
+1E36;LATIN CAPITAL LETTER L WITH DOT BELOW;Lu;0;L;004C 0323;;;;N;;;;1E37;
+1E37;LATIN SMALL LETTER L WITH DOT BELOW;Ll;0;L;006C 0323;;;;N;;;1E36;;1E36
+1E38;LATIN CAPITAL LETTER L WITH DOT BELOW AND MACRON;Lu;0;L;1E36 0304;;;;N;;;;1E39;
+1E39;LATIN SMALL LETTER L WITH DOT BELOW AND MACRON;Ll;0;L;1E37 0304;;;;N;;;1E38;;1E38
+1E3A;LATIN CAPITAL LETTER L WITH LINE BELOW;Lu;0;L;004C 0331;;;;N;;;;1E3B;
+1E3B;LATIN SMALL LETTER L WITH LINE BELOW;Ll;0;L;006C 0331;;;;N;;;1E3A;;1E3A
+1E3C;LATIN CAPITAL LETTER L WITH CIRCUMFLEX BELOW;Lu;0;L;004C 032D;;;;N;;;;1E3D;
+1E3D;LATIN SMALL LETTER L WITH CIRCUMFLEX BELOW;Ll;0;L;006C 032D;;;;N;;;1E3C;;1E3C
+1E3E;LATIN CAPITAL LETTER M WITH ACUTE;Lu;0;L;004D 0301;;;;N;;;;1E3F;
+1E3F;LATIN SMALL LETTER M WITH ACUTE;Ll;0;L;006D 0301;;;;N;;;1E3E;;1E3E
+1E40;LATIN CAPITAL LETTER M WITH DOT ABOVE;Lu;0;L;004D 0307;;;;N;;;;1E41;
+1E41;LATIN SMALL LETTER M WITH DOT ABOVE;Ll;0;L;006D 0307;;;;N;;;1E40;;1E40
+1E42;LATIN CAPITAL LETTER M WITH DOT BELOW;Lu;0;L;004D 0323;;;;N;;;;1E43;
+1E43;LATIN SMALL LETTER M WITH DOT BELOW;Ll;0;L;006D 0323;;;;N;;;1E42;;1E42
+1E44;LATIN CAPITAL LETTER N WITH DOT ABOVE;Lu;0;L;004E 0307;;;;N;;;;1E45;
+1E45;LATIN SMALL LETTER N WITH DOT ABOVE;Ll;0;L;006E 0307;;;;N;;;1E44;;1E44
+1E46;LATIN CAPITAL LETTER N WITH DOT BELOW;Lu;0;L;004E 0323;;;;N;;;;1E47;
+1E47;LATIN SMALL LETTER N WITH DOT BELOW;Ll;0;L;006E 0323;;;;N;;;1E46;;1E46
+1E48;LATIN CAPITAL LETTER N WITH LINE BELOW;Lu;0;L;004E 0331;;;;N;;;;1E49;
+1E49;LATIN SMALL LETTER N WITH LINE BELOW;Ll;0;L;006E 0331;;;;N;;;1E48;;1E48
+1E4A;LATIN CAPITAL LETTER N WITH CIRCUMFLEX BELOW;Lu;0;L;004E 032D;;;;N;;;;1E4B;
+1E4B;LATIN SMALL LETTER N WITH CIRCUMFLEX BELOW;Ll;0;L;006E 032D;;;;N;;;1E4A;;1E4A
+1E4C;LATIN CAPITAL LETTER O WITH TILDE AND ACUTE;Lu;0;L;00D5 0301;;;;N;;;;1E4D;
+1E4D;LATIN SMALL LETTER O WITH TILDE AND ACUTE;Ll;0;L;00F5 0301;;;;N;;;1E4C;;1E4C
+1E4E;LATIN CAPITAL LETTER O WITH TILDE AND DIAERESIS;Lu;0;L;00D5 0308;;;;N;;;;1E4F;
+1E4F;LATIN SMALL LETTER O WITH TILDE AND DIAERESIS;Ll;0;L;00F5 0308;;;;N;;;1E4E;;1E4E
+1E50;LATIN CAPITAL LETTER O WITH MACRON AND GRAVE;Lu;0;L;014C 0300;;;;N;;;;1E51;
+1E51;LATIN SMALL LETTER O WITH MACRON AND GRAVE;Ll;0;L;014D 0300;;;;N;;;1E50;;1E50
+1E52;LATIN CAPITAL LETTER O WITH MACRON AND ACUTE;Lu;0;L;014C 0301;;;;N;;;;1E53;
+1E53;LATIN SMALL LETTER O WITH MACRON AND ACUTE;Ll;0;L;014D 0301;;;;N;;;1E52;;1E52
+1E54;LATIN CAPITAL LETTER P WITH ACUTE;Lu;0;L;0050 0301;;;;N;;;;1E55;
+1E55;LATIN SMALL LETTER P WITH ACUTE;Ll;0;L;0070 0301;;;;N;;;1E54;;1E54
+1E56;LATIN CAPITAL LETTER P WITH DOT ABOVE;Lu;0;L;0050 0307;;;;N;;;;1E57;
+1E57;LATIN SMALL LETTER P WITH DOT ABOVE;Ll;0;L;0070 0307;;;;N;;;1E56;;1E56
+1E58;LATIN CAPITAL LETTER R WITH DOT ABOVE;Lu;0;L;0052 0307;;;;N;;;;1E59;
+1E59;LATIN SMALL LETTER R WITH DOT ABOVE;Ll;0;L;0072 0307;;;;N;;;1E58;;1E58
+1E5A;LATIN CAPITAL LETTER R WITH DOT BELOW;Lu;0;L;0052 0323;;;;N;;;;1E5B;
+1E5B;LATIN SMALL LETTER R WITH DOT BELOW;Ll;0;L;0072 0323;;;;N;;;1E5A;;1E5A
+1E5C;LATIN CAPITAL LETTER R WITH DOT BELOW AND MACRON;Lu;0;L;1E5A 0304;;;;N;;;;1E5D;
+1E5D;LATIN SMALL LETTER R WITH DOT BELOW AND MACRON;Ll;0;L;1E5B 0304;;;;N;;;1E5C;;1E5C
+1E5E;LATIN CAPITAL LETTER R WITH LINE BELOW;Lu;0;L;0052 0331;;;;N;;;;1E5F;
+1E5F;LATIN SMALL LETTER R WITH LINE BELOW;Ll;0;L;0072 0331;;;;N;;;1E5E;;1E5E
+1E60;LATIN CAPITAL LETTER S WITH DOT ABOVE;Lu;0;L;0053 0307;;;;N;;;;1E61;
+1E61;LATIN SMALL LETTER S WITH DOT ABOVE;Ll;0;L;0073 0307;;;;N;;;1E60;;1E60
+1E62;LATIN CAPITAL LETTER S WITH DOT BELOW;Lu;0;L;0053 0323;;;;N;;;;1E63;
+1E63;LATIN SMALL LETTER S WITH DOT BELOW;Ll;0;L;0073 0323;;;;N;;;1E62;;1E62
+1E64;LATIN CAPITAL LETTER S WITH ACUTE AND DOT ABOVE;Lu;0;L;015A 0307;;;;N;;;;1E65;
+1E65;LATIN SMALL LETTER S WITH ACUTE AND DOT ABOVE;Ll;0;L;015B 0307;;;;N;;;1E64;;1E64
+1E66;LATIN CAPITAL LETTER S WITH CARON AND DOT ABOVE;Lu;0;L;0160 0307;;;;N;;;;1E67;
+1E67;LATIN SMALL LETTER S WITH CARON AND DOT ABOVE;Ll;0;L;0161 0307;;;;N;;;1E66;;1E66
+1E68;LATIN CAPITAL LETTER S WITH DOT BELOW AND DOT ABOVE;Lu;0;L;1E62 0307;;;;N;;;;1E69;
+1E69;LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE;Ll;0;L;1E63 0307;;;;N;;;1E68;;1E68
+1E6A;LATIN CAPITAL LETTER T WITH DOT ABOVE;Lu;0;L;0054 0307;;;;N;;;;1E6B;
+1E6B;LATIN SMALL LETTER T WITH DOT ABOVE;Ll;0;L;0074 0307;;;;N;;;1E6A;;1E6A
+1E6C;LATIN CAPITAL LETTER T WITH DOT BELOW;Lu;0;L;0054 0323;;;;N;;;;1E6D;
+1E6D;LATIN SMALL LETTER T WITH DOT BELOW;Ll;0;L;0074 0323;;;;N;;;1E6C;;1E6C
+1E6E;LATIN CAPITAL LETTER T WITH LINE BELOW;Lu;0;L;0054 0331;;;;N;;;;1E6F;
+1E6F;LATIN SMALL LETTER T WITH LINE BELOW;Ll;0;L;0074 0331;;;;N;;;1E6E;;1E6E
+1E70;LATIN CAPITAL LETTER T WITH CIRCUMFLEX BELOW;Lu;0;L;0054 032D;;;;N;;;;1E71;
+1E71;LATIN SMALL LETTER T WITH CIRCUMFLEX BELOW;Ll;0;L;0074 032D;;;;N;;;1E70;;1E70
+1E72;LATIN CAPITAL LETTER U WITH DIAERESIS BELOW;Lu;0;L;0055 0324;;;;N;;;;1E73;
+1E73;LATIN SMALL LETTER U WITH DIAERESIS BELOW;Ll;0;L;0075 0324;;;;N;;;1E72;;1E72
+1E74;LATIN CAPITAL LETTER U WITH TILDE BELOW;Lu;0;L;0055 0330;;;;N;;;;1E75;
+1E75;LATIN SMALL LETTER U WITH TILDE BELOW;Ll;0;L;0075 0330;;;;N;;;1E74;;1E74
+1E76;LATIN CAPITAL LETTER U WITH CIRCUMFLEX BELOW;Lu;0;L;0055 032D;;;;N;;;;1E77;
+1E77;LATIN SMALL LETTER U WITH CIRCUMFLEX BELOW;Ll;0;L;0075 032D;;;;N;;;1E76;;1E76
+1E78;LATIN CAPITAL LETTER U WITH TILDE AND ACUTE;Lu;0;L;0168 0301;;;;N;;;;1E79;
+1E79;LATIN SMALL LETTER U WITH TILDE AND ACUTE;Ll;0;L;0169 0301;;;;N;;;1E78;;1E78
+1E7A;LATIN CAPITAL LETTER U WITH MACRON AND DIAERESIS;Lu;0;L;016A 0308;;;;N;;;;1E7B;
+1E7B;LATIN SMALL LETTER U WITH MACRON AND DIAERESIS;Ll;0;L;016B 0308;;;;N;;;1E7A;;1E7A
+1E7C;LATIN CAPITAL LETTER V WITH TILDE;Lu;0;L;0056 0303;;;;N;;;;1E7D;
+1E7D;LATIN SMALL LETTER V WITH TILDE;Ll;0;L;0076 0303;;;;N;;;1E7C;;1E7C
+1E7E;LATIN CAPITAL LETTER V WITH DOT BELOW;Lu;0;L;0056 0323;;;;N;;;;1E7F;
+1E7F;LATIN SMALL LETTER V WITH DOT BELOW;Ll;0;L;0076 0323;;;;N;;;1E7E;;1E7E
+1E80;LATIN CAPITAL LETTER W WITH GRAVE;Lu;0;L;0057 0300;;;;N;;;;1E81;
+1E81;LATIN SMALL LETTER W WITH GRAVE;Ll;0;L;0077 0300;;;;N;;;1E80;;1E80
+1E82;LATIN CAPITAL LETTER W WITH ACUTE;Lu;0;L;0057 0301;;;;N;;;;1E83;
+1E83;LATIN SMALL LETTER W WITH ACUTE;Ll;0;L;0077 0301;;;;N;;;1E82;;1E82
+1E84;LATIN CAPITAL LETTER W WITH DIAERESIS;Lu;0;L;0057 0308;;;;N;;;;1E85;
+1E85;LATIN SMALL LETTER W WITH DIAERESIS;Ll;0;L;0077 0308;;;;N;;;1E84;;1E84
+1E86;LATIN CAPITAL LETTER W WITH DOT ABOVE;Lu;0;L;0057 0307;;;;N;;;;1E87;
+1E87;LATIN SMALL LETTER W WITH DOT ABOVE;Ll;0;L;0077 0307;;;;N;;;1E86;;1E86
+1E88;LATIN CAPITAL LETTER W WITH DOT BELOW;Lu;0;L;0057 0323;;;;N;;;;1E89;
+1E89;LATIN SMALL LETTER W WITH DOT BELOW;Ll;0;L;0077 0323;;;;N;;;1E88;;1E88
+1E8A;LATIN CAPITAL LETTER X WITH DOT ABOVE;Lu;0;L;0058 0307;;;;N;;;;1E8B;
+1E8B;LATIN SMALL LETTER X WITH DOT ABOVE;Ll;0;L;0078 0307;;;;N;;;1E8A;;1E8A
+1E8C;LATIN CAPITAL LETTER X WITH DIAERESIS;Lu;0;L;0058 0308;;;;N;;;;1E8D;
+1E8D;LATIN SMALL LETTER X WITH DIAERESIS;Ll;0;L;0078 0308;;;;N;;;1E8C;;1E8C
+1E8E;LATIN CAPITAL LETTER Y WITH DOT ABOVE;Lu;0;L;0059 0307;;;;N;;;;1E8F;
+1E8F;LATIN SMALL LETTER Y WITH DOT ABOVE;Ll;0;L;0079 0307;;;;N;;;1E8E;;1E8E
+1E90;LATIN CAPITAL LETTER Z WITH CIRCUMFLEX;Lu;0;L;005A 0302;;;;N;;;;1E91;
+1E91;LATIN SMALL LETTER Z WITH CIRCUMFLEX;Ll;0;L;007A 0302;;;;N;;;1E90;;1E90
+1E92;LATIN CAPITAL LETTER Z WITH DOT BELOW;Lu;0;L;005A 0323;;;;N;;;;1E93;
+1E93;LATIN SMALL LETTER Z WITH DOT BELOW;Ll;0;L;007A 0323;;;;N;;;1E92;;1E92
+1E94;LATIN CAPITAL LETTER Z WITH LINE BELOW;Lu;0;L;005A 0331;;;;N;;;;1E95;
+1E95;LATIN SMALL LETTER Z WITH LINE BELOW;Ll;0;L;007A 0331;;;;N;;;1E94;;1E94
+1E96;LATIN SMALL LETTER H WITH LINE BELOW;Ll;0;L;0068 0331;;;;N;;;;;
+1E97;LATIN SMALL LETTER T WITH DIAERESIS;Ll;0;L;0074 0308;;;;N;;;;;
+1E98;LATIN SMALL LETTER W WITH RING ABOVE;Ll;0;L;0077 030A;;;;N;;;;;
+1E99;LATIN SMALL LETTER Y WITH RING ABOVE;Ll;0;L;0079 030A;;;;N;;;;;
+1E9A;LATIN SMALL LETTER A WITH RIGHT HALF RING;Ll;0;L;<compat> 0061 02BE;;;;N;;;;;
+1E9B;LATIN SMALL LETTER LONG S WITH DOT ABOVE;Ll;0;L;017F 0307;;;;N;;;1E60;;1E60
+1EA0;LATIN CAPITAL LETTER A WITH DOT BELOW;Lu;0;L;0041 0323;;;;N;;;;1EA1;
+1EA1;LATIN SMALL LETTER A WITH DOT BELOW;Ll;0;L;0061 0323;;;;N;;;1EA0;;1EA0
+1EA2;LATIN CAPITAL LETTER A WITH HOOK ABOVE;Lu;0;L;0041 0309;;;;N;;;;1EA3;
+1EA3;LATIN SMALL LETTER A WITH HOOK ABOVE;Ll;0;L;0061 0309;;;;N;;;1EA2;;1EA2
+1EA4;LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND ACUTE;Lu;0;L;00C2 0301;;;;N;;;;1EA5;
+1EA5;LATIN SMALL LETTER A WITH CIRCUMFLEX AND ACUTE;Ll;0;L;00E2 0301;;;;N;;;1EA4;;1EA4
+1EA6;LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND GRAVE;Lu;0;L;00C2 0300;;;;N;;;;1EA7;
+1EA7;LATIN SMALL LETTER A WITH CIRCUMFLEX AND GRAVE;Ll;0;L;00E2 0300;;;;N;;;1EA6;;1EA6
+1EA8;LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE;Lu;0;L;00C2 0309;;;;N;;;;1EA9;
+1EA9;LATIN SMALL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE;Ll;0;L;00E2 0309;;;;N;;;1EA8;;1EA8
+1EAA;LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND TILDE;Lu;0;L;00C2 0303;;;;N;;;;1EAB;
+1EAB;LATIN SMALL LETTER A WITH CIRCUMFLEX AND TILDE;Ll;0;L;00E2 0303;;;;N;;;1EAA;;1EAA
+1EAC;LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND DOT BELOW;Lu;0;L;1EA0 0302;;;;N;;;;1EAD;
+1EAD;LATIN SMALL LETTER A WITH CIRCUMFLEX AND DOT BELOW;Ll;0;L;1EA1 0302;;;;N;;;1EAC;;1EAC
+1EAE;LATIN CAPITAL LETTER A WITH BREVE AND ACUTE;Lu;0;L;0102 0301;;;;N;;;;1EAF;
+1EAF;LATIN SMALL LETTER A WITH BREVE AND ACUTE;Ll;0;L;0103 0301;;;;N;;;1EAE;;1EAE
+1EB0;LATIN CAPITAL LETTER A WITH BREVE AND GRAVE;Lu;0;L;0102 0300;;;;N;;;;1EB1;
+1EB1;LATIN SMALL LETTER A WITH BREVE AND GRAVE;Ll;0;L;0103 0300;;;;N;;;1EB0;;1EB0
+1EB2;LATIN CAPITAL LETTER A WITH BREVE AND HOOK ABOVE;Lu;0;L;0102 0309;;;;N;;;;1EB3;
+1EB3;LATIN SMALL LETTER A WITH BREVE AND HOOK ABOVE;Ll;0;L;0103 0309;;;;N;;;1EB2;;1EB2
+1EB4;LATIN CAPITAL LETTER A WITH BREVE AND TILDE;Lu;0;L;0102 0303;;;;N;;;;1EB5;
+1EB5;LATIN SMALL LETTER A WITH BREVE AND TILDE;Ll;0;L;0103 0303;;;;N;;;1EB4;;1EB4
+1EB6;LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW;Lu;0;L;1EA0 0306;;;;N;;;;1EB7;
+1EB7;LATIN SMALL LETTER A WITH BREVE AND DOT BELOW;Ll;0;L;1EA1 0306;;;;N;;;1EB6;;1EB6
+1EB8;LATIN CAPITAL LETTER E WITH DOT BELOW;Lu;0;L;0045 0323;;;;N;;;;1EB9;
+1EB9;LATIN SMALL LETTER E WITH DOT BELOW;Ll;0;L;0065 0323;;;;N;;;1EB8;;1EB8
+1EBA;LATIN CAPITAL LETTER E WITH HOOK ABOVE;Lu;0;L;0045 0309;;;;N;;;;1EBB;
+1EBB;LATIN SMALL LETTER E WITH HOOK ABOVE;Ll;0;L;0065 0309;;;;N;;;1EBA;;1EBA
+1EBC;LATIN CAPITAL LETTER E WITH TILDE;Lu;0;L;0045 0303;;;;N;;;;1EBD;
+1EBD;LATIN SMALL LETTER E WITH TILDE;Ll;0;L;0065 0303;;;;N;;;1EBC;;1EBC
+1EBE;LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND ACUTE;Lu;0;L;00CA 0301;;;;N;;;;1EBF;
+1EBF;LATIN SMALL LETTER E WITH CIRCUMFLEX AND ACUTE;Ll;0;L;00EA 0301;;;;N;;;1EBE;;1EBE
+1EC0;LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND GRAVE;Lu;0;L;00CA 0300;;;;N;;;;1EC1;
+1EC1;LATIN SMALL LETTER E WITH CIRCUMFLEX AND GRAVE;Ll;0;L;00EA 0300;;;;N;;;1EC0;;1EC0
+1EC2;LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE;Lu;0;L;00CA 0309;;;;N;;;;1EC3;
+1EC3;LATIN SMALL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE;Ll;0;L;00EA 0309;;;;N;;;1EC2;;1EC2
+1EC4;LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND TILDE;Lu;0;L;00CA 0303;;;;N;;;;1EC5;
+1EC5;LATIN SMALL LETTER E WITH CIRCUMFLEX AND TILDE;Ll;0;L;00EA 0303;;;;N;;;1EC4;;1EC4
+1EC6;LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND DOT BELOW;Lu;0;L;1EB8 0302;;;;N;;;;1EC7;
+1EC7;LATIN SMALL LETTER E WITH CIRCUMFLEX AND DOT BELOW;Ll;0;L;1EB9 0302;;;;N;;;1EC6;;1EC6
+1EC8;LATIN CAPITAL LETTER I WITH HOOK ABOVE;Lu;0;L;0049 0309;;;;N;;;;1EC9;
+1EC9;LATIN SMALL LETTER I WITH HOOK ABOVE;Ll;0;L;0069 0309;;;;N;;;1EC8;;1EC8
+1ECA;LATIN CAPITAL LETTER I WITH DOT BELOW;Lu;0;L;0049 0323;;;;N;;;;1ECB;
+1ECB;LATIN SMALL LETTER I WITH DOT BELOW;Ll;0;L;0069 0323;;;;N;;;1ECA;;1ECA
+1ECC;LATIN CAPITAL LETTER O WITH DOT BELOW;Lu;0;L;004F 0323;;;;N;;;;1ECD;
+1ECD;LATIN SMALL LETTER O WITH DOT BELOW;Ll;0;L;006F 0323;;;;N;;;1ECC;;1ECC
+1ECE;LATIN CAPITAL LETTER O WITH HOOK ABOVE;Lu;0;L;004F 0309;;;;N;;;;1ECF;
+1ECF;LATIN SMALL LETTER O WITH HOOK ABOVE;Ll;0;L;006F 0309;;;;N;;;1ECE;;1ECE
+1ED0;LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND ACUTE;Lu;0;L;00D4 0301;;;;N;;;;1ED1;
+1ED1;LATIN SMALL LETTER O WITH CIRCUMFLEX AND ACUTE;Ll;0;L;00F4 0301;;;;N;;;1ED0;;1ED0
+1ED2;LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND GRAVE;Lu;0;L;00D4 0300;;;;N;;;;1ED3;
+1ED3;LATIN SMALL LETTER O WITH CIRCUMFLEX AND GRAVE;Ll;0;L;00F4 0300;;;;N;;;1ED2;;1ED2
+1ED4;LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE;Lu;0;L;00D4 0309;;;;N;;;;1ED5;
+1ED5;LATIN SMALL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE;Ll;0;L;00F4 0309;;;;N;;;1ED4;;1ED4
+1ED6;LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND TILDE;Lu;0;L;00D4 0303;;;;N;;;;1ED7;
+1ED7;LATIN SMALL LETTER O WITH CIRCUMFLEX AND TILDE;Ll;0;L;00F4 0303;;;;N;;;1ED6;;1ED6
+1ED8;LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND DOT BELOW;Lu;0;L;1ECC 0302;;;;N;;;;1ED9;
+1ED9;LATIN SMALL LETTER O WITH CIRCUMFLEX AND DOT BELOW;Ll;0;L;1ECD 0302;;;;N;;;1ED8;;1ED8
+1EDA;LATIN CAPITAL LETTER O WITH HORN AND ACUTE;Lu;0;L;01A0 0301;;;;N;;;;1EDB;
+1EDB;LATIN SMALL LETTER O WITH HORN AND ACUTE;Ll;0;L;01A1 0301;;;;N;;;1EDA;;1EDA
+1EDC;LATIN CAPITAL LETTER O WITH HORN AND GRAVE;Lu;0;L;01A0 0300;;;;N;;;;1EDD;
+1EDD;LATIN SMALL LETTER O WITH HORN AND GRAVE;Ll;0;L;01A1 0300;;;;N;;;1EDC;;1EDC
+1EDE;LATIN CAPITAL LETTER O WITH HORN AND HOOK ABOVE;Lu;0;L;01A0 0309;;;;N;;;;1EDF;
+1EDF;LATIN SMALL LETTER O WITH HORN AND HOOK ABOVE;Ll;0;L;01A1 0309;;;;N;;;1EDE;;1EDE
+1EE0;LATIN CAPITAL LETTER O WITH HORN AND TILDE;Lu;0;L;01A0 0303;;;;N;;;;1EE1;
+1EE1;LATIN SMALL LETTER O WITH HORN AND TILDE;Ll;0;L;01A1 0303;;;;N;;;1EE0;;1EE0
+1EE2;LATIN CAPITAL LETTER O WITH HORN AND DOT BELOW;Lu;0;L;01A0 0323;;;;N;;;;1EE3;
+1EE3;LATIN SMALL LETTER O WITH HORN AND DOT BELOW;Ll;0;L;01A1 0323;;;;N;;;1EE2;;1EE2
+1EE4;LATIN CAPITAL LETTER U WITH DOT BELOW;Lu;0;L;0055 0323;;;;N;;;;1EE5;
+1EE5;LATIN SMALL LETTER U WITH DOT BELOW;Ll;0;L;0075 0323;;;;N;;;1EE4;;1EE4
+1EE6;LATIN CAPITAL LETTER U WITH HOOK ABOVE;Lu;0;L;0055 0309;;;;N;;;;1EE7;
+1EE7;LATIN SMALL LETTER U WITH HOOK ABOVE;Ll;0;L;0075 0309;;;;N;;;1EE6;;1EE6
+1EE8;LATIN CAPITAL LETTER U WITH HORN AND ACUTE;Lu;0;L;01AF 0301;;;;N;;;;1EE9;
+1EE9;LATIN SMALL LETTER U WITH HORN AND ACUTE;Ll;0;L;01B0 0301;;;;N;;;1EE8;;1EE8
+1EEA;LATIN CAPITAL LETTER U WITH HORN AND GRAVE;Lu;0;L;01AF 0300;;;;N;;;;1EEB;
+1EEB;LATIN SMALL LETTER U WITH HORN AND GRAVE;Ll;0;L;01B0 0300;;;;N;;;1EEA;;1EEA
+1EEC;LATIN CAPITAL LETTER U WITH HORN AND HOOK ABOVE;Lu;0;L;01AF 0309;;;;N;;;;1EED;
+1EED;LATIN SMALL LETTER U WITH HORN AND HOOK ABOVE;Ll;0;L;01B0 0309;;;;N;;;1EEC;;1EEC
+1EEE;LATIN CAPITAL LETTER U WITH HORN AND TILDE;Lu;0;L;01AF 0303;;;;N;;;;1EEF;
+1EEF;LATIN SMALL LETTER U WITH HORN AND TILDE;Ll;0;L;01B0 0303;;;;N;;;1EEE;;1EEE
+1EF0;LATIN CAPITAL LETTER U WITH HORN AND DOT BELOW;Lu;0;L;01AF 0323;;;;N;;;;1EF1;
+1EF1;LATIN SMALL LETTER U WITH HORN AND DOT BELOW;Ll;0;L;01B0 0323;;;;N;;;1EF0;;1EF0
+1EF2;LATIN CAPITAL LETTER Y WITH GRAVE;Lu;0;L;0059 0300;;;;N;;;;1EF3;
+1EF3;LATIN SMALL LETTER Y WITH GRAVE;Ll;0;L;0079 0300;;;;N;;;1EF2;;1EF2
+1EF4;LATIN CAPITAL LETTER Y WITH DOT BELOW;Lu;0;L;0059 0323;;;;N;;;;1EF5;
+1EF5;LATIN SMALL LETTER Y WITH DOT BELOW;Ll;0;L;0079 0323;;;;N;;;1EF4;;1EF4
+1EF6;LATIN CAPITAL LETTER Y WITH HOOK ABOVE;Lu;0;L;0059 0309;;;;N;;;;1EF7;
+1EF7;LATIN SMALL LETTER Y WITH HOOK ABOVE;Ll;0;L;0079 0309;;;;N;;;1EF6;;1EF6
+1EF8;LATIN CAPITAL LETTER Y WITH TILDE;Lu;0;L;0059 0303;;;;N;;;;1EF9;
+1EF9;LATIN SMALL LETTER Y WITH TILDE;Ll;0;L;0079 0303;;;;N;;;1EF8;;1EF8
+1F00;GREEK SMALL LETTER ALPHA WITH PSILI;Ll;0;L;03B1 0313;;;;N;;;1F08;;1F08
+1F01;GREEK SMALL LETTER ALPHA WITH DASIA;Ll;0;L;03B1 0314;;;;N;;;1F09;;1F09
+1F02;GREEK SMALL LETTER ALPHA WITH PSILI AND VARIA;Ll;0;L;1F00 0300;;;;N;;;1F0A;;1F0A
+1F03;GREEK SMALL LETTER ALPHA WITH DASIA AND VARIA;Ll;0;L;1F01 0300;;;;N;;;1F0B;;1F0B
+1F04;GREEK SMALL LETTER ALPHA WITH PSILI AND OXIA;Ll;0;L;1F00 0301;;;;N;;;1F0C;;1F0C
+1F05;GREEK SMALL LETTER ALPHA WITH DASIA AND OXIA;Ll;0;L;1F01 0301;;;;N;;;1F0D;;1F0D
+1F06;GREEK SMALL LETTER ALPHA WITH PSILI AND PERISPOMENI;Ll;0;L;1F00 0342;;;;N;;;1F0E;;1F0E
+1F07;GREEK SMALL LETTER ALPHA WITH DASIA AND PERISPOMENI;Ll;0;L;1F01 0342;;;;N;;;1F0F;;1F0F
+1F08;GREEK CAPITAL LETTER ALPHA WITH PSILI;Lu;0;L;0391 0313;;;;N;;;;1F00;
+1F09;GREEK CAPITAL LETTER ALPHA WITH DASIA;Lu;0;L;0391 0314;;;;N;;;;1F01;
+1F0A;GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA;Lu;0;L;1F08 0300;;;;N;;;;1F02;
+1F0B;GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA;Lu;0;L;1F09 0300;;;;N;;;;1F03;
+1F0C;GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA;Lu;0;L;1F08 0301;;;;N;;;;1F04;
+1F0D;GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA;Lu;0;L;1F09 0301;;;;N;;;;1F05;
+1F0E;GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI;Lu;0;L;1F08 0342;;;;N;;;;1F06;
+1F0F;GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI;Lu;0;L;1F09 0342;;;;N;;;;1F07;
+1F10;GREEK SMALL LETTER EPSILON WITH PSILI;Ll;0;L;03B5 0313;;;;N;;;1F18;;1F18
+1F11;GREEK SMALL LETTER EPSILON WITH DASIA;Ll;0;L;03B5 0314;;;;N;;;1F19;;1F19
+1F12;GREEK SMALL LETTER EPSILON WITH PSILI AND VARIA;Ll;0;L;1F10 0300;;;;N;;;1F1A;;1F1A
+1F13;GREEK SMALL LETTER EPSILON WITH DASIA AND VARIA;Ll;0;L;1F11 0300;;;;N;;;1F1B;;1F1B
+1F14;GREEK SMALL LETTER EPSILON WITH PSILI AND OXIA;Ll;0;L;1F10 0301;;;;N;;;1F1C;;1F1C
+1F15;GREEK SMALL LETTER EPSILON WITH DASIA AND OXIA;Ll;0;L;1F11 0301;;;;N;;;1F1D;;1F1D
+1F18;GREEK CAPITAL LETTER EPSILON WITH PSILI;Lu;0;L;0395 0313;;;;N;;;;1F10;
+1F19;GREEK CAPITAL LETTER EPSILON WITH DASIA;Lu;0;L;0395 0314;;;;N;;;;1F11;
+1F1A;GREEK CAPITAL LETTER EPSILON WITH PSILI AND VARIA;Lu;0;L;1F18 0300;;;;N;;;;1F12;
+1F1B;GREEK CAPITAL LETTER EPSILON WITH DASIA AND VARIA;Lu;0;L;1F19 0300;;;;N;;;;1F13;
+1F1C;GREEK CAPITAL LETTER EPSILON WITH PSILI AND OXIA;Lu;0;L;1F18 0301;;;;N;;;;1F14;
+1F1D;GREEK CAPITAL LETTER EPSILON WITH DASIA AND OXIA;Lu;0;L;1F19 0301;;;;N;;;;1F15;
+1F20;GREEK SMALL LETTER ETA WITH PSILI;Ll;0;L;03B7 0313;;;;N;;;1F28;;1F28
+1F21;GREEK SMALL LETTER ETA WITH DASIA;Ll;0;L;03B7 0314;;;;N;;;1F29;;1F29
+1F22;GREEK SMALL LETTER ETA WITH PSILI AND VARIA;Ll;0;L;1F20 0300;;;;N;;;1F2A;;1F2A
+1F23;GREEK SMALL LETTER ETA WITH DASIA AND VARIA;Ll;0;L;1F21 0300;;;;N;;;1F2B;;1F2B
+1F24;GREEK SMALL LETTER ETA WITH PSILI AND OXIA;Ll;0;L;1F20 0301;;;;N;;;1F2C;;1F2C
+1F25;GREEK SMALL LETTER ETA WITH DASIA AND OXIA;Ll;0;L;1F21 0301;;;;N;;;1F2D;;1F2D
+1F26;GREEK SMALL LETTER ETA WITH PSILI AND PERISPOMENI;Ll;0;L;1F20 0342;;;;N;;;1F2E;;1F2E
+1F27;GREEK SMALL LETTER ETA WITH DASIA AND PERISPOMENI;Ll;0;L;1F21 0342;;;;N;;;1F2F;;1F2F
+1F28;GREEK CAPITAL LETTER ETA WITH PSILI;Lu;0;L;0397 0313;;;;N;;;;1F20;
+1F29;GREEK CAPITAL LETTER ETA WITH DASIA;Lu;0;L;0397 0314;;;;N;;;;1F21;
+1F2A;GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA;Lu;0;L;1F28 0300;;;;N;;;;1F22;
+1F2B;GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA;Lu;0;L;1F29 0300;;;;N;;;;1F23;
+1F2C;GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA;Lu;0;L;1F28 0301;;;;N;;;;1F24;
+1F2D;GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA;Lu;0;L;1F29 0301;;;;N;;;;1F25;
+1F2E;GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI;Lu;0;L;1F28 0342;;;;N;;;;1F26;
+1F2F;GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI;Lu;0;L;1F29 0342;;;;N;;;;1F27;
+1F30;GREEK SMALL LETTER IOTA WITH PSILI;Ll;0;L;03B9 0313;;;;N;;;1F38;;1F38
+1F31;GREEK SMALL LETTER IOTA WITH DASIA;Ll;0;L;03B9 0314;;;;N;;;1F39;;1F39
+1F32;GREEK SMALL LETTER IOTA WITH PSILI AND VARIA;Ll;0;L;1F30 0300;;;;N;;;1F3A;;1F3A
+1F33;GREEK SMALL LETTER IOTA WITH DASIA AND VARIA;Ll;0;L;1F31 0300;;;;N;;;1F3B;;1F3B
+1F34;GREEK SMALL LETTER IOTA WITH PSILI AND OXIA;Ll;0;L;1F30 0301;;;;N;;;1F3C;;1F3C
+1F35;GREEK SMALL LETTER IOTA WITH DASIA AND OXIA;Ll;0;L;1F31 0301;;;;N;;;1F3D;;1F3D
+1F36;GREEK SMALL LETTER IOTA WITH PSILI AND PERISPOMENI;Ll;0;L;1F30 0342;;;;N;;;1F3E;;1F3E
+1F37;GREEK SMALL LETTER IOTA WITH DASIA AND PERISPOMENI;Ll;0;L;1F31 0342;;;;N;;;1F3F;;1F3F
+1F38;GREEK CAPITAL LETTER IOTA WITH PSILI;Lu;0;L;0399 0313;;;;N;;;;1F30;
+1F39;GREEK CAPITAL LETTER IOTA WITH DASIA;Lu;0;L;0399 0314;;;;N;;;;1F31;
+1F3A;GREEK CAPITAL LETTER IOTA WITH PSILI AND VARIA;Lu;0;L;1F38 0300;;;;N;;;;1F32;
+1F3B;GREEK CAPITAL LETTER IOTA WITH DASIA AND VARIA;Lu;0;L;1F39 0300;;;;N;;;;1F33;
+1F3C;GREEK CAPITAL LETTER IOTA WITH PSILI AND OXIA;Lu;0;L;1F38 0301;;;;N;;;;1F34;
+1F3D;GREEK CAPITAL LETTER IOTA WITH DASIA AND OXIA;Lu;0;L;1F39 0301;;;;N;;;;1F35;
+1F3E;GREEK CAPITAL LETTER IOTA WITH PSILI AND PERISPOMENI;Lu;0;L;1F38 0342;;;;N;;;;1F36;
+1F3F;GREEK CAPITAL LETTER IOTA WITH DASIA AND PERISPOMENI;Lu;0;L;1F39 0342;;;;N;;;;1F37;
+1F40;GREEK SMALL LETTER OMICRON WITH PSILI;Ll;0;L;03BF 0313;;;;N;;;1F48;;1F48
+1F41;GREEK SMALL LETTER OMICRON WITH DASIA;Ll;0;L;03BF 0314;;;;N;;;1F49;;1F49
+1F42;GREEK SMALL LETTER OMICRON WITH PSILI AND VARIA;Ll;0;L;1F40 0300;;;;N;;;1F4A;;1F4A
+1F43;GREEK SMALL LETTER OMICRON WITH DASIA AND VARIA;Ll;0;L;1F41 0300;;;;N;;;1F4B;;1F4B
+1F44;GREEK SMALL LETTER OMICRON WITH PSILI AND OXIA;Ll;0;L;1F40 0301;;;;N;;;1F4C;;1F4C
+1F45;GREEK SMALL LETTER OMICRON WITH DASIA AND OXIA;Ll;0;L;1F41 0301;;;;N;;;1F4D;;1F4D
+1F48;GREEK CAPITAL LETTER OMICRON WITH PSILI;Lu;0;L;039F 0313;;;;N;;;;1F40;
+1F49;GREEK CAPITAL LETTER OMICRON WITH DASIA;Lu;0;L;039F 0314;;;;N;;;;1F41;
+1F4A;GREEK CAPITAL LETTER OMICRON WITH PSILI AND VARIA;Lu;0;L;1F48 0300;;;;N;;;;1F42;
+1F4B;GREEK CAPITAL LETTER OMICRON WITH DASIA AND VARIA;Lu;0;L;1F49 0300;;;;N;;;;1F43;
+1F4C;GREEK CAPITAL LETTER OMICRON WITH PSILI AND OXIA;Lu;0;L;1F48 0301;;;;N;;;;1F44;
+1F4D;GREEK CAPITAL LETTER OMICRON WITH DASIA AND OXIA;Lu;0;L;1F49 0301;;;;N;;;;1F45;
+1F50;GREEK SMALL LETTER UPSILON WITH PSILI;Ll;0;L;03C5 0313;;;;N;;;;;
+1F51;GREEK SMALL LETTER UPSILON WITH DASIA;Ll;0;L;03C5 0314;;;;N;;;1F59;;1F59
+1F52;GREEK SMALL LETTER UPSILON WITH PSILI AND VARIA;Ll;0;L;1F50 0300;;;;N;;;;;
+1F53;GREEK SMALL LETTER UPSILON WITH DASIA AND VARIA;Ll;0;L;1F51 0300;;;;N;;;1F5B;;1F5B
+1F54;GREEK SMALL LETTER UPSILON WITH PSILI AND OXIA;Ll;0;L;1F50 0301;;;;N;;;;;
+1F55;GREEK SMALL LETTER UPSILON WITH DASIA AND OXIA;Ll;0;L;1F51 0301;;;;N;;;1F5D;;1F5D
+1F56;GREEK SMALL LETTER UPSILON WITH PSILI AND PERISPOMENI;Ll;0;L;1F50 0342;;;;N;;;;;
+1F57;GREEK SMALL LETTER UPSILON WITH DASIA AND PERISPOMENI;Ll;0;L;1F51 0342;;;;N;;;1F5F;;1F5F
+1F59;GREEK CAPITAL LETTER UPSILON WITH DASIA;Lu;0;L;03A5 0314;;;;N;;;;1F51;
+1F5B;GREEK CAPITAL LETTER UPSILON WITH DASIA AND VARIA;Lu;0;L;1F59 0300;;;;N;;;;1F53;
+1F5D;GREEK CAPITAL LETTER UPSILON WITH DASIA AND OXIA;Lu;0;L;1F59 0301;;;;N;;;;1F55;
+1F5F;GREEK CAPITAL LETTER UPSILON WITH DASIA AND PERISPOMENI;Lu;0;L;1F59 0342;;;;N;;;;1F57;
+1F60;GREEK SMALL LETTER OMEGA WITH PSILI;Ll;0;L;03C9 0313;;;;N;;;1F68;;1F68
+1F61;GREEK SMALL LETTER OMEGA WITH DASIA;Ll;0;L;03C9 0314;;;;N;;;1F69;;1F69
+1F62;GREEK SMALL LETTER OMEGA WITH PSILI AND VARIA;Ll;0;L;1F60 0300;;;;N;;;1F6A;;1F6A
+1F63;GREEK SMALL LETTER OMEGA WITH DASIA AND VARIA;Ll;0;L;1F61 0300;;;;N;;;1F6B;;1F6B
+1F64;GREEK SMALL LETTER OMEGA WITH PSILI AND OXIA;Ll;0;L;1F60 0301;;;;N;;;1F6C;;1F6C
+1F65;GREEK SMALL LETTER OMEGA WITH DASIA AND OXIA;Ll;0;L;1F61 0301;;;;N;;;1F6D;;1F6D
+1F66;GREEK SMALL LETTER OMEGA WITH PSILI AND PERISPOMENI;Ll;0;L;1F60 0342;;;;N;;;1F6E;;1F6E
+1F67;GREEK SMALL LETTER OMEGA WITH DASIA AND PERISPOMENI;Ll;0;L;1F61 0342;;;;N;;;1F6F;;1F6F
+1F68;GREEK CAPITAL LETTER OMEGA WITH PSILI;Lu;0;L;03A9 0313;;;;N;;;;1F60;
+1F69;GREEK CAPITAL LETTER OMEGA WITH DASIA;Lu;0;L;03A9 0314;;;;N;;;;1F61;
+1F6A;GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA;Lu;0;L;1F68 0300;;;;N;;;;1F62;
+1F6B;GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA;Lu;0;L;1F69 0300;;;;N;;;;1F63;
+1F6C;GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA;Lu;0;L;1F68 0301;;;;N;;;;1F64;
+1F6D;GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA;Lu;0;L;1F69 0301;;;;N;;;;1F65;
+1F6E;GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI;Lu;0;L;1F68 0342;;;;N;;;;1F66;
+1F6F;GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI;Lu;0;L;1F69 0342;;;;N;;;;1F67;
+1F70;GREEK SMALL LETTER ALPHA WITH VARIA;Ll;0;L;03B1 0300;;;;N;;;1FBA;;1FBA
+1F71;GREEK SMALL LETTER ALPHA WITH OXIA;Ll;0;L;03AC;;;;N;;;1FBB;;1FBB
+1F72;GREEK SMALL LETTER EPSILON WITH VARIA;Ll;0;L;03B5 0300;;;;N;;;1FC8;;1FC8
+1F73;GREEK SMALL LETTER EPSILON WITH OXIA;Ll;0;L;03AD;;;;N;;;1FC9;;1FC9
+1F74;GREEK SMALL LETTER ETA WITH VARIA;Ll;0;L;03B7 0300;;;;N;;;1FCA;;1FCA
+1F75;GREEK SMALL LETTER ETA WITH OXIA;Ll;0;L;03AE;;;;N;;;1FCB;;1FCB
+1F76;GREEK SMALL LETTER IOTA WITH VARIA;Ll;0;L;03B9 0300;;;;N;;;1FDA;;1FDA
+1F77;GREEK SMALL LETTER IOTA WITH OXIA;Ll;0;L;03AF;;;;N;;;1FDB;;1FDB
+1F78;GREEK SMALL LETTER OMICRON WITH VARIA;Ll;0;L;03BF 0300;;;;N;;;1FF8;;1FF8
+1F79;GREEK SMALL LETTER OMICRON WITH OXIA;Ll;0;L;03CC;;;;N;;;1FF9;;1FF9
+1F7A;GREEK SMALL LETTER UPSILON WITH VARIA;Ll;0;L;03C5 0300;;;;N;;;1FEA;;1FEA
+1F7B;GREEK SMALL LETTER UPSILON WITH OXIA;Ll;0;L;03CD;;;;N;;;1FEB;;1FEB
+1F7C;GREEK SMALL LETTER OMEGA WITH VARIA;Ll;0;L;03C9 0300;;;;N;;;1FFA;;1FFA
+1F7D;GREEK SMALL LETTER OMEGA WITH OXIA;Ll;0;L;03CE;;;;N;;;1FFB;;1FFB
+1F80;GREEK SMALL LETTER ALPHA WITH PSILI AND YPOGEGRAMMENI;Ll;0;L;1F00 0345;;;;N;;;1F88;;1F88
+1F81;GREEK SMALL LETTER ALPHA WITH DASIA AND YPOGEGRAMMENI;Ll;0;L;1F01 0345;;;;N;;;1F89;;1F89
+1F82;GREEK SMALL LETTER ALPHA WITH PSILI AND VARIA AND YPOGEGRAMMENI;Ll;0;L;1F02 0345;;;;N;;;1F8A;;1F8A
+1F83;GREEK SMALL LETTER ALPHA WITH DASIA AND VARIA AND YPOGEGRAMMENI;Ll;0;L;1F03 0345;;;;N;;;1F8B;;1F8B
+1F84;GREEK SMALL LETTER ALPHA WITH PSILI AND OXIA AND YPOGEGRAMMENI;Ll;0;L;1F04 0345;;;;N;;;1F8C;;1F8C
+1F85;GREEK SMALL LETTER ALPHA WITH DASIA AND OXIA AND YPOGEGRAMMENI;Ll;0;L;1F05 0345;;;;N;;;1F8D;;1F8D
+1F86;GREEK SMALL LETTER ALPHA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1F06 0345;;;;N;;;1F8E;;1F8E
+1F87;GREEK SMALL LETTER ALPHA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1F07 0345;;;;N;;;1F8F;;1F8F
+1F88;GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI;Lt;0;L;1F08 0345;;;;N;;;;1F80;
+1F89;GREEK CAPITAL LETTER ALPHA WITH DASIA AND PROSGEGRAMMENI;Lt;0;L;1F09 0345;;;;N;;;;1F81;
+1F8A;GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA AND PROSGEGRAMMENI;Lt;0;L;1F0A 0345;;;;N;;;;1F82;
+1F8B;GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA AND PROSGEGRAMMENI;Lt;0;L;1F0B 0345;;;;N;;;;1F83;
+1F8C;GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA AND PROSGEGRAMMENI;Lt;0;L;1F0C 0345;;;;N;;;;1F84;
+1F8D;GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA AND PROSGEGRAMMENI;Lt;0;L;1F0D 0345;;;;N;;;;1F85;
+1F8E;GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI;Lt;0;L;1F0E 0345;;;;N;;;;1F86;
+1F8F;GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI;Lt;0;L;1F0F 0345;;;;N;;;;1F87;
+1F90;GREEK SMALL LETTER ETA WITH PSILI AND YPOGEGRAMMENI;Ll;0;L;1F20 0345;;;;N;;;1F98;;1F98
+1F91;GREEK SMALL LETTER ETA WITH DASIA AND YPOGEGRAMMENI;Ll;0;L;1F21 0345;;;;N;;;1F99;;1F99
+1F92;GREEK SMALL LETTER ETA WITH PSILI AND VARIA AND YPOGEGRAMMENI;Ll;0;L;1F22 0345;;;;N;;;1F9A;;1F9A
+1F93;GREEK SMALL LETTER ETA WITH DASIA AND VARIA AND YPOGEGRAMMENI;Ll;0;L;1F23 0345;;;;N;;;1F9B;;1F9B
+1F94;GREEK SMALL LETTER ETA WITH PSILI AND OXIA AND YPOGEGRAMMENI;Ll;0;L;1F24 0345;;;;N;;;1F9C;;1F9C
+1F95;GREEK SMALL LETTER ETA WITH DASIA AND OXIA AND YPOGEGRAMMENI;Ll;0;L;1F25 0345;;;;N;;;1F9D;;1F9D
+1F96;GREEK SMALL LETTER ETA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1F26 0345;;;;N;;;1F9E;;1F9E
+1F97;GREEK SMALL LETTER ETA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1F27 0345;;;;N;;;1F9F;;1F9F
+1F98;GREEK CAPITAL LETTER ETA WITH PSILI AND PROSGEGRAMMENI;Lt;0;L;1F28 0345;;;;N;;;;1F90;
+1F99;GREEK CAPITAL LETTER ETA WITH DASIA AND PROSGEGRAMMENI;Lt;0;L;1F29 0345;;;;N;;;;1F91;
+1F9A;GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA AND PROSGEGRAMMENI;Lt;0;L;1F2A 0345;;;;N;;;;1F92;
+1F9B;GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA AND PROSGEGRAMMENI;Lt;0;L;1F2B 0345;;;;N;;;;1F93;
+1F9C;GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA AND PROSGEGRAMMENI;Lt;0;L;1F2C 0345;;;;N;;;;1F94;
+1F9D;GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA AND PROSGEGRAMMENI;Lt;0;L;1F2D 0345;;;;N;;;;1F95;
+1F9E;GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI;Lt;0;L;1F2E 0345;;;;N;;;;1F96;
+1F9F;GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI;Lt;0;L;1F2F 0345;;;;N;;;;1F97;
+1FA0;GREEK SMALL LETTER OMEGA WITH PSILI AND YPOGEGRAMMENI;Ll;0;L;1F60 0345;;;;N;;;1FA8;;1FA8
+1FA1;GREEK SMALL LETTER OMEGA WITH DASIA AND YPOGEGRAMMENI;Ll;0;L;1F61 0345;;;;N;;;1FA9;;1FA9
+1FA2;GREEK SMALL LETTER OMEGA WITH PSILI AND VARIA AND YPOGEGRAMMENI;Ll;0;L;1F62 0345;;;;N;;;1FAA;;1FAA
+1FA3;GREEK SMALL LETTER OMEGA WITH DASIA AND VARIA AND YPOGEGRAMMENI;Ll;0;L;1F63 0345;;;;N;;;1FAB;;1FAB
+1FA4;GREEK SMALL LETTER OMEGA WITH PSILI AND OXIA AND YPOGEGRAMMENI;Ll;0;L;1F64 0345;;;;N;;;1FAC;;1FAC
+1FA5;GREEK SMALL LETTER OMEGA WITH DASIA AND OXIA AND YPOGEGRAMMENI;Ll;0;L;1F65 0345;;;;N;;;1FAD;;1FAD
+1FA6;GREEK SMALL LETTER OMEGA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1F66 0345;;;;N;;;1FAE;;1FAE
+1FA7;GREEK SMALL LETTER OMEGA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1F67 0345;;;;N;;;1FAF;;1FAF
+1FA8;GREEK CAPITAL LETTER OMEGA WITH PSILI AND PROSGEGRAMMENI;Lt;0;L;1F68 0345;;;;N;;;;1FA0;
+1FA9;GREEK CAPITAL LETTER OMEGA WITH DASIA AND PROSGEGRAMMENI;Lt;0;L;1F69 0345;;;;N;;;;1FA1;
+1FAA;GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA AND PROSGEGRAMMENI;Lt;0;L;1F6A 0345;;;;N;;;;1FA2;
+1FAB;GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA AND PROSGEGRAMMENI;Lt;0;L;1F6B 0345;;;;N;;;;1FA3;
+1FAC;GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA AND PROSGEGRAMMENI;Lt;0;L;1F6C 0345;;;;N;;;;1FA4;
+1FAD;GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA AND PROSGEGRAMMENI;Lt;0;L;1F6D 0345;;;;N;;;;1FA5;
+1FAE;GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI;Lt;0;L;1F6E 0345;;;;N;;;;1FA6;
+1FAF;GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI;Lt;0;L;1F6F 0345;;;;N;;;;1FA7;
+1FB0;GREEK SMALL LETTER ALPHA WITH VRACHY;Ll;0;L;03B1 0306;;;;N;;;1FB8;;1FB8
+1FB1;GREEK SMALL LETTER ALPHA WITH MACRON;Ll;0;L;03B1 0304;;;;N;;;1FB9;;1FB9
+1FB2;GREEK SMALL LETTER ALPHA WITH VARIA AND YPOGEGRAMMENI;Ll;0;L;1F70 0345;;;;N;;;;;
+1FB3;GREEK SMALL LETTER ALPHA WITH YPOGEGRAMMENI;Ll;0;L;03B1 0345;;;;N;;;1FBC;;1FBC
+1FB4;GREEK SMALL LETTER ALPHA WITH OXIA AND YPOGEGRAMMENI;Ll;0;L;03AC 0345;;;;N;;;;;
+1FB6;GREEK SMALL LETTER ALPHA WITH PERISPOMENI;Ll;0;L;03B1 0342;;;;N;;;;;
+1FB7;GREEK SMALL LETTER ALPHA WITH PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1FB6 0345;;;;N;;;;;
+1FB8;GREEK CAPITAL LETTER ALPHA WITH VRACHY;Lu;0;L;0391 0306;;;;N;;;;1FB0;
+1FB9;GREEK CAPITAL LETTER ALPHA WITH MACRON;Lu;0;L;0391 0304;;;;N;;;;1FB1;
+1FBA;GREEK CAPITAL LETTER ALPHA WITH VARIA;Lu;0;L;0391 0300;;;;N;;;;1F70;
+1FBB;GREEK CAPITAL LETTER ALPHA WITH OXIA;Lu;0;L;0386;;;;N;;;;1F71;
+1FBC;GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI;Lt;0;L;0391 0345;;;;N;;;;1FB3;
+1FBD;GREEK KORONIS;Sk;0;ON;<compat> 0020 0313;;;;N;;;;;
+1FBE;GREEK PROSGEGRAMMENI;Ll;0;L;03B9;;;;N;;;0399;;0399
+1FBF;GREEK PSILI;Sk;0;ON;<compat> 0020 0313;;;;N;;;;;
+1FC0;GREEK PERISPOMENI;Sk;0;ON;<compat> 0020 0342;;;;N;;;;;
+1FC1;GREEK DIALYTIKA AND PERISPOMENI;Sk;0;ON;00A8 0342;;;;N;;;;;
+1FC2;GREEK SMALL LETTER ETA WITH VARIA AND YPOGEGRAMMENI;Ll;0;L;1F74 0345;;;;N;;;;;
+1FC3;GREEK SMALL LETTER ETA WITH YPOGEGRAMMENI;Ll;0;L;03B7 0345;;;;N;;;1FCC;;1FCC
+1FC4;GREEK SMALL LETTER ETA WITH OXIA AND YPOGEGRAMMENI;Ll;0;L;03AE 0345;;;;N;;;;;
+1FC6;GREEK SMALL LETTER ETA WITH PERISPOMENI;Ll;0;L;03B7 0342;;;;N;;;;;
+1FC7;GREEK SMALL LETTER ETA WITH PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1FC6 0345;;;;N;;;;;
+1FC8;GREEK CAPITAL LETTER EPSILON WITH VARIA;Lu;0;L;0395 0300;;;;N;;;;1F72;
+1FC9;GREEK CAPITAL LETTER EPSILON WITH OXIA;Lu;0;L;0388;;;;N;;;;1F73;
+1FCA;GREEK CAPITAL LETTER ETA WITH VARIA;Lu;0;L;0397 0300;;;;N;;;;1F74;
+1FCB;GREEK CAPITAL LETTER ETA WITH OXIA;Lu;0;L;0389;;;;N;;;;1F75;
+1FCC;GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI;Lt;0;L;0397 0345;;;;N;;;;1FC3;
+1FCD;GREEK PSILI AND VARIA;Sk;0;ON;1FBF 0300;;;;N;;;;;
+1FCE;GREEK PSILI AND OXIA;Sk;0;ON;1FBF 0301;;;;N;;;;;
+1FCF;GREEK PSILI AND PERISPOMENI;Sk;0;ON;1FBF 0342;;;;N;;;;;
+1FD0;GREEK SMALL LETTER IOTA WITH VRACHY;Ll;0;L;03B9 0306;;;;N;;;1FD8;;1FD8
+1FD1;GREEK SMALL LETTER IOTA WITH MACRON;Ll;0;L;03B9 0304;;;;N;;;1FD9;;1FD9
+1FD2;GREEK SMALL LETTER IOTA WITH DIALYTIKA AND VARIA;Ll;0;L;03CA 0300;;;;N;;;;;
+1FD3;GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA;Ll;0;L;0390;;;;N;;;;;
+1FD6;GREEK SMALL LETTER IOTA WITH PERISPOMENI;Ll;0;L;03B9 0342;;;;N;;;;;
+1FD7;GREEK SMALL LETTER IOTA WITH DIALYTIKA AND PERISPOMENI;Ll;0;L;03CA 0342;;;;N;;;;;
+1FD8;GREEK CAPITAL LETTER IOTA WITH VRACHY;Lu;0;L;0399 0306;;;;N;;;;1FD0;
+1FD9;GREEK CAPITAL LETTER IOTA WITH MACRON;Lu;0;L;0399 0304;;;;N;;;;1FD1;
+1FDA;GREEK CAPITAL LETTER IOTA WITH VARIA;Lu;0;L;0399 0300;;;;N;;;;1F76;
+1FDB;GREEK CAPITAL LETTER IOTA WITH OXIA;Lu;0;L;038A;;;;N;;;;1F77;
+1FDD;GREEK DASIA AND VARIA;Sk;0;ON;1FFE 0300;;;;N;;;;;
+1FDE;GREEK DASIA AND OXIA;Sk;0;ON;1FFE 0301;;;;N;;;;;
+1FDF;GREEK DASIA AND PERISPOMENI;Sk;0;ON;1FFE 0342;;;;N;;;;;
+1FE0;GREEK SMALL LETTER UPSILON WITH VRACHY;Ll;0;L;03C5 0306;;;;N;;;1FE8;;1FE8
+1FE1;GREEK SMALL LETTER UPSILON WITH MACRON;Ll;0;L;03C5 0304;;;;N;;;1FE9;;1FE9
+1FE2;GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND VARIA;Ll;0;L;03CB 0300;;;;N;;;;;
+1FE3;GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA;Ll;0;L;03B0;;;;N;;;;;
+1FE4;GREEK SMALL LETTER RHO WITH PSILI;Ll;0;L;03C1 0313;;;;N;;;;;
+1FE5;GREEK SMALL LETTER RHO WITH DASIA;Ll;0;L;03C1 0314;;;;N;;;1FEC;;1FEC
+1FE6;GREEK SMALL LETTER UPSILON WITH PERISPOMENI;Ll;0;L;03C5 0342;;;;N;;;;;
+1FE7;GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND PERISPOMENI;Ll;0;L;03CB 0342;;;;N;;;;;
+1FE8;GREEK CAPITAL LETTER UPSILON WITH VRACHY;Lu;0;L;03A5 0306;;;;N;;;;1FE0;
+1FE9;GREEK CAPITAL LETTER UPSILON WITH MACRON;Lu;0;L;03A5 0304;;;;N;;;;1FE1;
+1FEA;GREEK CAPITAL LETTER UPSILON WITH VARIA;Lu;0;L;03A5 0300;;;;N;;;;1F7A;
+1FEB;GREEK CAPITAL LETTER UPSILON WITH OXIA;Lu;0;L;038E;;;;N;;;;1F7B;
+1FEC;GREEK CAPITAL LETTER RHO WITH DASIA;Lu;0;L;03A1 0314;;;;N;;;;1FE5;
+1FED;GREEK DIALYTIKA AND VARIA;Sk;0;ON;00A8 0300;;;;N;;;;;
+1FEE;GREEK DIALYTIKA AND OXIA;Sk;0;ON;0385;;;;N;;;;;
+1FEF;GREEK VARIA;Sk;0;ON;0060;;;;N;;;;;
+1FF2;GREEK SMALL LETTER OMEGA WITH VARIA AND YPOGEGRAMMENI;Ll;0;L;1F7C 0345;;;;N;;;;;
+1FF3;GREEK SMALL LETTER OMEGA WITH YPOGEGRAMMENI;Ll;0;L;03C9 0345;;;;N;;;1FFC;;1FFC
+1FF4;GREEK SMALL LETTER OMEGA WITH OXIA AND YPOGEGRAMMENI;Ll;0;L;03CE 0345;;;;N;;;;;
+1FF6;GREEK SMALL LETTER OMEGA WITH PERISPOMENI;Ll;0;L;03C9 0342;;;;N;;;;;
+1FF7;GREEK SMALL LETTER OMEGA WITH PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1FF6 0345;;;;N;;;;;
+1FF8;GREEK CAPITAL LETTER OMICRON WITH VARIA;Lu;0;L;039F 0300;;;;N;;;;1F78;
+1FF9;GREEK CAPITAL LETTER OMICRON WITH OXIA;Lu;0;L;038C;;;;N;;;;1F79;
+1FFA;GREEK CAPITAL LETTER OMEGA WITH VARIA;Lu;0;L;03A9 0300;;;;N;;;;1F7C;
+1FFB;GREEK CAPITAL LETTER OMEGA WITH OXIA;Lu;0;L;038F;;;;N;;;;1F7D;
+1FFC;GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI;Lt;0;L;03A9 0345;;;;N;;;;1FF3;
+1FFD;GREEK OXIA;Sk;0;ON;00B4;;;;N;;;;;
+1FFE;GREEK DASIA;Sk;0;ON;<compat> 0020 0314;;;;N;;;;;
+2000;EN QUAD;Zs;0;WS;2002;;;;N;;;;;
+2001;EM QUAD;Zs;0;WS;2003;;;;N;;;;;
+2002;EN SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
+2003;EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
+2004;THREE-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
+2005;FOUR-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
+2006;SIX-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
+2007;FIGURE SPACE;Zs;0;WS;<noBreak> 0020;;;;N;;;;;
+2008;PUNCTUATION SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
+2009;THIN SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
+200A;HAIR SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
+200B;ZERO WIDTH SPACE;Cf;0;BN;;;;;N;;;;;
+200C;ZERO WIDTH NON-JOINER;Cf;0;BN;;;;;N;;;;;
+200D;ZERO WIDTH JOINER;Cf;0;BN;;;;;N;;;;;
+200E;LEFT-TO-RIGHT MARK;Cf;0;L;;;;;N;;;;;
+200F;RIGHT-TO-LEFT MARK;Cf;0;R;;;;;N;;;;;
+2010;HYPHEN;Pd;0;ON;;;;;N;;;;;
+2011;NON-BREAKING HYPHEN;Pd;0;ON;<noBreak> 2010;;;;N;;;;;
+2012;FIGURE DASH;Pd;0;ON;;;;;N;;;;;
+2013;EN DASH;Pd;0;ON;;;;;N;;;;;
+2014;EM DASH;Pd;0;ON;;;;;N;;;;;
+2015;HORIZONTAL BAR;Pd;0;ON;;;;;N;QUOTATION DASH;;;;
+2016;DOUBLE VERTICAL LINE;Po;0;ON;;;;;N;DOUBLE VERTICAL BAR;;;;
+2017;DOUBLE LOW LINE;Po;0;ON;<compat> 0020 0333;;;;N;SPACING DOUBLE UNDERSCORE;;;;
+2018;LEFT SINGLE QUOTATION MARK;Pi;0;ON;;;;;N;SINGLE TURNED COMMA QUOTATION MARK;;;;
+2019;RIGHT SINGLE QUOTATION MARK;Pf;0;ON;;;;;N;SINGLE COMMA QUOTATION MARK;;;;
+201A;SINGLE LOW-9 QUOTATION MARK;Ps;0;ON;;;;;N;LOW SINGLE COMMA QUOTATION MARK;;;;
+201B;SINGLE HIGH-REVERSED-9 QUOTATION MARK;Pi;0;ON;;;;;N;SINGLE REVERSED COMMA QUOTATION MARK;;;;
+201C;LEFT DOUBLE QUOTATION MARK;Pi;0;ON;;;;;N;DOUBLE TURNED COMMA QUOTATION MARK;;;;
+201D;RIGHT DOUBLE QUOTATION MARK;Pf;0;ON;;;;;N;DOUBLE COMMA QUOTATION MARK;;;;
+201E;DOUBLE LOW-9 QUOTATION MARK;Ps;0;ON;;;;;N;LOW DOUBLE COMMA QUOTATION MARK;;;;
+201F;DOUBLE HIGH-REVERSED-9 QUOTATION MARK;Pi;0;ON;;;;;N;DOUBLE REVERSED COMMA QUOTATION MARK;;;;
+2020;DAGGER;Po;0;ON;;;;;N;;;;;
+2021;DOUBLE DAGGER;Po;0;ON;;;;;N;;;;;
+2022;BULLET;Po;0;ON;;;;;N;;;;;
+2023;TRIANGULAR BULLET;Po;0;ON;;;;;N;;;;;
+2024;ONE DOT LEADER;Po;0;ON;<compat> 002E;;;;N;;;;;
+2025;TWO DOT LEADER;Po;0;ON;<compat> 002E 002E;;;;N;;;;;
+2026;HORIZONTAL ELLIPSIS;Po;0;ON;<compat> 002E 002E 002E;;;;N;;;;;
+2027;HYPHENATION POINT;Po;0;ON;;;;;N;;;;;
+2028;LINE SEPARATOR;Zl;0;WS;;;;;N;;;;;
+2029;PARAGRAPH SEPARATOR;Zp;0;B;;;;;N;;;;;
+202A;LEFT-TO-RIGHT EMBEDDING;Cf;0;LRE;;;;;N;;;;;
+202B;RIGHT-TO-LEFT EMBEDDING;Cf;0;RLE;;;;;N;;;;;
+202C;POP DIRECTIONAL FORMATTING;Cf;0;PDF;;;;;N;;;;;
+202D;LEFT-TO-RIGHT OVERRIDE;Cf;0;LRO;;;;;N;;;;;
+202E;RIGHT-TO-LEFT OVERRIDE;Cf;0;RLO;;;;;N;;;;;
+202F;NARROW NO-BREAK SPACE;Zs;0;WS;<noBreak> 0020;;;;N;;;;;
+2030;PER MILLE SIGN;Po;0;ET;;;;;N;;;;;
+2031;PER TEN THOUSAND SIGN;Po;0;ET;;;;;N;;;;;
+2032;PRIME;Po;0;ET;;;;;N;;;;;
+2033;DOUBLE PRIME;Po;0;ET;<compat> 2032 2032;;;;N;;;;;
+2034;TRIPLE PRIME;Po;0;ET;<compat> 2032 2032 2032;;;;N;;;;;
+2035;REVERSED PRIME;Po;0;ON;;;;;N;;;;;
+2036;REVERSED DOUBLE PRIME;Po;0;ON;<compat> 2035 2035;;;;N;;;;;
+2037;REVERSED TRIPLE PRIME;Po;0;ON;<compat> 2035 2035 2035;;;;N;;;;;
+2038;CARET;Po;0;ON;;;;;N;;;;;
+2039;SINGLE LEFT-POINTING ANGLE QUOTATION MARK;Pi;0;ON;;;;;Y;LEFT POINTING SINGLE GUILLEMET;;;;
+203A;SINGLE RIGHT-POINTING ANGLE QUOTATION MARK;Pf;0;ON;;;;;Y;RIGHT POINTING SINGLE GUILLEMET;;;;
+203B;REFERENCE MARK;Po;0;ON;;;;;N;;;;;
+203C;DOUBLE EXCLAMATION MARK;Po;0;ON;<compat> 0021 0021;;;;N;;;;;
+203D;INTERROBANG;Po;0;ON;;;;;N;;;;;
+203E;OVERLINE;Po;0;ON;<compat> 0020 0305;;;;N;SPACING OVERSCORE;;;;
+203F;UNDERTIE;Pc;0;ON;;;;;N;;Enotikon;;;
+2040;CHARACTER TIE;Pc;0;ON;;;;;N;;;;;
+2041;CARET INSERTION POINT;Po;0;ON;;;;;N;;;;;
+2042;ASTERISM;Po;0;ON;;;;;N;;;;;
+2043;HYPHEN BULLET;Po;0;ON;;;;;N;;;;;
+2044;FRACTION SLASH;Sm;0;CS;;;;;N;;;;;
+2045;LEFT SQUARE BRACKET WITH QUILL;Ps;0;ON;;;;;Y;;;;;
+2046;RIGHT SQUARE BRACKET WITH QUILL;Pe;0;ON;;;;;Y;;;;;
+2047;DOUBLE QUESTION MARK;Po;0;ON;<compat> 003F 003F;;;;N;;;;;
+2048;QUESTION EXCLAMATION MARK;Po;0;ON;<compat> 003F 0021;;;;N;;;;;
+2049;EXCLAMATION QUESTION MARK;Po;0;ON;<compat> 0021 003F;;;;N;;;;;
+204A;TIRONIAN SIGN ET;Po;0;ON;;;;;N;;;;;
+204B;REVERSED PILCROW SIGN;Po;0;ON;;;;;N;;;;;
+204C;BLACK LEFTWARDS BULLET;Po;0;ON;;;;;N;;;;;
+204D;BLACK RIGHTWARDS BULLET;Po;0;ON;;;;;N;;;;;
+204E;LOW ASTERISK;Po;0;ON;;;;;N;;;;;
+204F;REVERSED SEMICOLON;Po;0;ON;;;;;N;;;;;
+2050;CLOSE UP;Po;0;ON;;;;;N;;;;;
+2051;TWO ASTERISKS ALIGNED VERTICALLY;Po;0;ON;;;;;N;;;;;
+2052;COMMERCIAL MINUS SIGN;Sm;0;ON;;;;;N;;;;;
+2053;SWUNG DASH;Po;0;ON;;;;;N;;;;;
+2054;INVERTED UNDERTIE;Pc;0;ON;;;;;N;;;;;
+2057;QUADRUPLE PRIME;Po;0;ON;<compat> 2032 2032 2032 2032;;;;N;;;;;
+205F;MEDIUM MATHEMATICAL SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
+2060;WORD JOINER;Cf;0;BN;;;;;N;;;;;
+2061;FUNCTION APPLICATION;Cf;0;BN;;;;;N;;;;;
+2062;INVISIBLE TIMES;Cf;0;BN;;;;;N;;;;;
+2063;INVISIBLE SEPARATOR;Cf;0;BN;;;;;N;;;;;
+206A;INHIBIT SYMMETRIC SWAPPING;Cf;0;BN;;;;;N;;;;;
+206B;ACTIVATE SYMMETRIC SWAPPING;Cf;0;BN;;;;;N;;;;;
+206C;INHIBIT ARABIC FORM SHAPING;Cf;0;BN;;;;;N;;;;;
+206D;ACTIVATE ARABIC FORM SHAPING;Cf;0;BN;;;;;N;;;;;
+206E;NATIONAL DIGIT SHAPES;Cf;0;BN;;;;;N;;;;;
+206F;NOMINAL DIGIT SHAPES;Cf;0;BN;;;;;N;;;;;
+2070;SUPERSCRIPT ZERO;No;0;EN;<super> 0030;;0;0;N;SUPERSCRIPT DIGIT ZERO;;;;
+2071;SUPERSCRIPT LATIN SMALL LETTER I;Ll;0;L;<super> 0069;;;;N;;;;;
+2074;SUPERSCRIPT FOUR;No;0;EN;<super> 0034;;4;4;N;SUPERSCRIPT DIGIT FOUR;;;;
+2075;SUPERSCRIPT FIVE;No;0;EN;<super> 0035;;5;5;N;SUPERSCRIPT DIGIT FIVE;;;;
+2076;SUPERSCRIPT SIX;No;0;EN;<super> 0036;;6;6;N;SUPERSCRIPT DIGIT SIX;;;;
+2077;SUPERSCRIPT SEVEN;No;0;EN;<super> 0037;;7;7;N;SUPERSCRIPT DIGIT SEVEN;;;;
+2078;SUPERSCRIPT EIGHT;No;0;EN;<super> 0038;;8;8;N;SUPERSCRIPT DIGIT EIGHT;;;;
+2079;SUPERSCRIPT NINE;No;0;EN;<super> 0039;;9;9;N;SUPERSCRIPT DIGIT NINE;;;;
+207A;SUPERSCRIPT PLUS SIGN;Sm;0;ET;<super> 002B;;;;N;;;;;
+207B;SUPERSCRIPT MINUS;Sm;0;ET;<super> 2212;;;;N;SUPERSCRIPT HYPHEN-MINUS;;;;
+207C;SUPERSCRIPT EQUALS SIGN;Sm;0;ON;<super> 003D;;;;N;;;;;
+207D;SUPERSCRIPT LEFT PARENTHESIS;Ps;0;ON;<super> 0028;;;;Y;SUPERSCRIPT OPENING PARENTHESIS;;;;
+207E;SUPERSCRIPT RIGHT PARENTHESIS;Pe;0;ON;<super> 0029;;;;Y;SUPERSCRIPT CLOSING PARENTHESIS;;;;
+207F;SUPERSCRIPT LATIN SMALL LETTER N;Ll;0;L;<super> 006E;;;;N;;;;;
+2080;SUBSCRIPT ZERO;No;0;EN;<sub> 0030;;0;0;N;SUBSCRIPT DIGIT ZERO;;;;
+2081;SUBSCRIPT ONE;No;0;EN;<sub> 0031;;1;1;N;SUBSCRIPT DIGIT ONE;;;;
+2082;SUBSCRIPT TWO;No;0;EN;<sub> 0032;;2;2;N;SUBSCRIPT DIGIT TWO;;;;
+2083;SUBSCRIPT THREE;No;0;EN;<sub> 0033;;3;3;N;SUBSCRIPT DIGIT THREE;;;;
+2084;SUBSCRIPT FOUR;No;0;EN;<sub> 0034;;4;4;N;SUBSCRIPT DIGIT FOUR;;;;
+2085;SUBSCRIPT FIVE;No;0;EN;<sub> 0035;;5;5;N;SUBSCRIPT DIGIT FIVE;;;;
+2086;SUBSCRIPT SIX;No;0;EN;<sub> 0036;;6;6;N;SUBSCRIPT DIGIT SIX;;;;
+2087;SUBSCRIPT SEVEN;No;0;EN;<sub> 0037;;7;7;N;SUBSCRIPT DIGIT SEVEN;;;;
+2088;SUBSCRIPT EIGHT;No;0;EN;<sub> 0038;;8;8;N;SUBSCRIPT DIGIT EIGHT;;;;
+2089;SUBSCRIPT NINE;No;0;EN;<sub> 0039;;9;9;N;SUBSCRIPT DIGIT NINE;;;;
+208A;SUBSCRIPT PLUS SIGN;Sm;0;ET;<sub> 002B;;;;N;;;;;
+208B;SUBSCRIPT MINUS;Sm;0;ET;<sub> 2212;;;;N;SUBSCRIPT HYPHEN-MINUS;;;;
+208C;SUBSCRIPT EQUALS SIGN;Sm;0;ON;<sub> 003D;;;;N;;;;;
+208D;SUBSCRIPT LEFT PARENTHESIS;Ps;0;ON;<sub> 0028;;;;Y;SUBSCRIPT OPENING PARENTHESIS;;;;
+208E;SUBSCRIPT RIGHT PARENTHESIS;Pe;0;ON;<sub> 0029;;;;Y;SUBSCRIPT CLOSING PARENTHESIS;;;;
+20A0;EURO-CURRENCY SIGN;Sc;0;ET;;;;;N;;;;;
+20A1;COLON SIGN;Sc;0;ET;;;;;N;;;;;
+20A2;CRUZEIRO SIGN;Sc;0;ET;;;;;N;;;;;
+20A3;FRENCH FRANC SIGN;Sc;0;ET;;;;;N;;;;;
+20A4;LIRA SIGN;Sc;0;ET;;;;;N;;;;;
+20A5;MILL SIGN;Sc;0;ET;;;;;N;;;;;
+20A6;NAIRA SIGN;Sc;0;ET;;;;;N;;;;;
+20A7;PESETA SIGN;Sc;0;ET;;;;;N;;;;;
+20A8;RUPEE SIGN;Sc;0;ET;<compat> 0052 0073;;;;N;;;;;
+20A9;WON SIGN;Sc;0;ET;;;;;N;;;;;
+20AA;NEW SHEQEL SIGN;Sc;0;ET;;;;;N;;;;;
+20AB;DONG SIGN;Sc;0;ET;;;;;N;;;;;
+20AC;EURO SIGN;Sc;0;ET;;;;;N;;;;;
+20AD;KIP SIGN;Sc;0;ET;;;;;N;;;;;
+20AE;TUGRIK SIGN;Sc;0;ET;;;;;N;;;;;
+20AF;DRACHMA SIGN;Sc;0;ET;;;;;N;;;;;
+20B0;GERMAN PENNY SIGN;Sc;0;ET;;;;;N;;;;;
+20B1;PESO SIGN;Sc;0;ET;;;;;N;;;;;
+20D0;COMBINING LEFT HARPOON ABOVE;Mn;230;NSM;;;;;N;NON-SPACING LEFT HARPOON ABOVE;;;;
+20D1;COMBINING RIGHT HARPOON ABOVE;Mn;230;NSM;;;;;N;NON-SPACING RIGHT HARPOON ABOVE;;;;
+20D2;COMBINING LONG VERTICAL LINE OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING LONG VERTICAL BAR OVERLAY;;;;
+20D3;COMBINING SHORT VERTICAL LINE OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING SHORT VERTICAL BAR OVERLAY;;;;
+20D4;COMBINING ANTICLOCKWISE ARROW ABOVE;Mn;230;NSM;;;;;N;NON-SPACING ANTICLOCKWISE ARROW ABOVE;;;;
+20D5;COMBINING CLOCKWISE ARROW ABOVE;Mn;230;NSM;;;;;N;NON-SPACING CLOCKWISE ARROW ABOVE;;;;
+20D6;COMBINING LEFT ARROW ABOVE;Mn;230;NSM;;;;;N;NON-SPACING LEFT ARROW ABOVE;;;;
+20D7;COMBINING RIGHT ARROW ABOVE;Mn;230;NSM;;;;;N;NON-SPACING RIGHT ARROW ABOVE;;;;
+20D8;COMBINING RING OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING RING OVERLAY;;;;
+20D9;COMBINING CLOCKWISE RING OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING CLOCKWISE RING OVERLAY;;;;
+20DA;COMBINING ANTICLOCKWISE RING OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING ANTICLOCKWISE RING OVERLAY;;;;
+20DB;COMBINING THREE DOTS ABOVE;Mn;230;NSM;;;;;N;NON-SPACING THREE DOTS ABOVE;;;;
+20DC;COMBINING FOUR DOTS ABOVE;Mn;230;NSM;;;;;N;NON-SPACING FOUR DOTS ABOVE;;;;
+20DD;COMBINING ENCLOSING CIRCLE;Me;0;NSM;;;;;N;ENCLOSING CIRCLE;;;;
+20DE;COMBINING ENCLOSING SQUARE;Me;0;NSM;;;;;N;ENCLOSING SQUARE;;;;
+20DF;COMBINING ENCLOSING DIAMOND;Me;0;NSM;;;;;N;ENCLOSING DIAMOND;;;;
+20E0;COMBINING ENCLOSING CIRCLE BACKSLASH;Me;0;NSM;;;;;N;ENCLOSING CIRCLE SLASH;;;;
+20E1;COMBINING LEFT RIGHT ARROW ABOVE;Mn;230;NSM;;;;;N;NON-SPACING LEFT RIGHT ARROW ABOVE;;;;
+20E2;COMBINING ENCLOSING SCREEN;Me;0;NSM;;;;;N;;;;;
+20E3;COMBINING ENCLOSING KEYCAP;Me;0;NSM;;;;;N;;;;;
+20E4;COMBINING ENCLOSING UPWARD POINTING TRIANGLE;Me;0;NSM;;;;;N;;;;;
+20E5;COMBINING REVERSE SOLIDUS OVERLAY;Mn;1;NSM;;;;;N;;;;;
+20E6;COMBINING DOUBLE VERTICAL STROKE OVERLAY;Mn;1;NSM;;;;;N;;;;;
+20E7;COMBINING ANNUITY SYMBOL;Mn;230;NSM;;;;;N;;;;;
+20E8;COMBINING TRIPLE UNDERDOT;Mn;220;NSM;;;;;N;;;;;
+20E9;COMBINING WIDE BRIDGE ABOVE;Mn;230;NSM;;;;;N;;;;;
+20EA;COMBINING LEFTWARDS ARROW OVERLAY;Mn;1;NSM;;;;;N;;;;;
+2100;ACCOUNT OF;So;0;ON;<compat> 0061 002F 0063;;;;N;;;;;
+2101;ADDRESSED TO THE SUBJECT;So;0;ON;<compat> 0061 002F 0073;;;;N;;;;;
+2102;DOUBLE-STRUCK CAPITAL C;Lu;0;L;<font> 0043;;;;N;DOUBLE-STRUCK C;;;;
+2103;DEGREE CELSIUS;So;0;ON;<compat> 00B0 0043;;;;N;DEGREES CENTIGRADE;;;;
+2104;CENTRE LINE SYMBOL;So;0;ON;;;;;N;C L SYMBOL;;;;
+2105;CARE OF;So;0;ON;<compat> 0063 002F 006F;;;;N;;;;;
+2106;CADA UNA;So;0;ON;<compat> 0063 002F 0075;;;;N;;;;;
+2107;EULER CONSTANT;Lu;0;L;<compat> 0190;;;;N;EULERS;;;;
+2108;SCRUPLE;So;0;ON;;;;;N;;;;;
+2109;DEGREE FAHRENHEIT;So;0;ON;<compat> 00B0 0046;;;;N;DEGREES FAHRENHEIT;;;;
+210A;SCRIPT SMALL G;Ll;0;L;<font> 0067;;;;N;;;;;
+210B;SCRIPT CAPITAL H;Lu;0;L;<font> 0048;;;;N;SCRIPT H;;;;
+210C;BLACK-LETTER CAPITAL H;Lu;0;L;<font> 0048;;;;N;BLACK-LETTER H;;;;
+210D;DOUBLE-STRUCK CAPITAL H;Lu;0;L;<font> 0048;;;;N;DOUBLE-STRUCK H;;;;
+210E;PLANCK CONSTANT;Ll;0;L;<font> 0068;;;;N;;;;;
+210F;PLANCK CONSTANT OVER TWO PI;Ll;0;L;<font> 0127;;;;N;PLANCK CONSTANT OVER 2 PI;;;;
+2110;SCRIPT CAPITAL I;Lu;0;L;<font> 0049;;;;N;SCRIPT I;;;;
+2111;BLACK-LETTER CAPITAL I;Lu;0;L;<font> 0049;;;;N;BLACK-LETTER I;;;;
+2112;SCRIPT CAPITAL L;Lu;0;L;<font> 004C;;;;N;SCRIPT L;;;;
+2113;SCRIPT SMALL L;Ll;0;L;<font> 006C;;;;N;;;;;
+2114;L B BAR SYMBOL;So;0;ON;;;;;N;;;;;
+2115;DOUBLE-STRUCK CAPITAL N;Lu;0;L;<font> 004E;;;;N;DOUBLE-STRUCK N;;;;
+2116;NUMERO SIGN;So;0;ON;<compat> 004E 006F;;;;N;NUMERO;;;;
+2117;SOUND RECORDING COPYRIGHT;So;0;ON;;;;;N;;;;;
+2118;SCRIPT CAPITAL P;So;0;ON;;;;;N;SCRIPT P;;;;
+2119;DOUBLE-STRUCK CAPITAL P;Lu;0;L;<font> 0050;;;;N;DOUBLE-STRUCK P;;;;
+211A;DOUBLE-STRUCK CAPITAL Q;Lu;0;L;<font> 0051;;;;N;DOUBLE-STRUCK Q;;;;
+211B;SCRIPT CAPITAL R;Lu;0;L;<font> 0052;;;;N;SCRIPT R;;;;
+211C;BLACK-LETTER CAPITAL R;Lu;0;L;<font> 0052;;;;N;BLACK-LETTER R;;;;
+211D;DOUBLE-STRUCK CAPITAL R;Lu;0;L;<font> 0052;;;;N;DOUBLE-STRUCK R;;;;
+211E;PRESCRIPTION TAKE;So;0;ON;;;;;N;;;;;
+211F;RESPONSE;So;0;ON;;;;;N;;;;;
+2120;SERVICE MARK;So;0;ON;<super> 0053 004D;;;;N;;;;;
+2121;TELEPHONE SIGN;So;0;ON;<compat> 0054 0045 004C;;;;N;T E L SYMBOL;;;;
+2122;TRADE MARK SIGN;So;0;ON;<super> 0054 004D;;;;N;TRADEMARK;;;;
+2123;VERSICLE;So;0;ON;;;;;N;;;;;
+2124;DOUBLE-STRUCK CAPITAL Z;Lu;0;L;<font> 005A;;;;N;DOUBLE-STRUCK Z;;;;
+2125;OUNCE SIGN;So;0;ON;;;;;N;OUNCE;;;;
+2126;OHM SIGN;Lu;0;L;03A9;;;;N;OHM;;;03C9;
+2127;INVERTED OHM SIGN;So;0;ON;;;;;N;MHO;;;;
+2128;BLACK-LETTER CAPITAL Z;Lu;0;L;<font> 005A;;;;N;BLACK-LETTER Z;;;;
+2129;TURNED GREEK SMALL LETTER IOTA;So;0;ON;;;;;N;;;;;
+212A;KELVIN SIGN;Lu;0;L;004B;;;;N;DEGREES KELVIN;;;006B;
+212B;ANGSTROM SIGN;Lu;0;L;00C5;;;;N;ANGSTROM UNIT;;;00E5;
+212C;SCRIPT CAPITAL B;Lu;0;L;<font> 0042;;;;N;SCRIPT B;;;;
+212D;BLACK-LETTER CAPITAL C;Lu;0;L;<font> 0043;;;;N;BLACK-LETTER C;;;;
+212E;ESTIMATED SYMBOL;So;0;ET;;;;;N;;;;;
+212F;SCRIPT SMALL E;Ll;0;L;<font> 0065;;;;N;;;;;
+2130;SCRIPT CAPITAL E;Lu;0;L;<font> 0045;;;;N;SCRIPT E;;;;
+2131;SCRIPT CAPITAL F;Lu;0;L;<font> 0046;;;;N;SCRIPT F;;;;
+2132;TURNED CAPITAL F;So;0;ON;;;;;N;TURNED F;;;;
+2133;SCRIPT CAPITAL M;Lu;0;L;<font> 004D;;;;N;SCRIPT M;;;;
+2134;SCRIPT SMALL O;Ll;0;L;<font> 006F;;;;N;;;;;
+2135;ALEF SYMBOL;Lo;0;L;<compat> 05D0;;;;N;FIRST TRANSFINITE CARDINAL;;;;
+2136;BET SYMBOL;Lo;0;L;<compat> 05D1;;;;N;SECOND TRANSFINITE CARDINAL;;;;
+2137;GIMEL SYMBOL;Lo;0;L;<compat> 05D2;;;;N;THIRD TRANSFINITE CARDINAL;;;;
+2138;DALET SYMBOL;Lo;0;L;<compat> 05D3;;;;N;FOURTH TRANSFINITE CARDINAL;;;;
+2139;INFORMATION SOURCE;Ll;0;L;<font> 0069;;;;N;;;;;
+213A;ROTATED CAPITAL Q;So;0;ON;;;;;N;;;;;
+213B;FACSIMILE SIGN;So;0;ON;<compat> 0046 0041 0058;;;;N;;;;;
+213D;DOUBLE-STRUCK SMALL GAMMA;Ll;0;L;<font> 03B3;;;;N;;;;;
+213E;DOUBLE-STRUCK CAPITAL GAMMA;Lu;0;L;<font> 0393;;;;N;;;;;
+213F;DOUBLE-STRUCK CAPITAL PI;Lu;0;L;<font> 03A0;;;;N;;;;;
+2140;DOUBLE-STRUCK N-ARY SUMMATION;Sm;0;ON;<font> 2211;;;;Y;;;;;
+2141;TURNED SANS-SERIF CAPITAL G;Sm;0;ON;;;;;N;;;;;
+2142;TURNED SANS-SERIF CAPITAL L;Sm;0;ON;;;;;N;;;;;
+2143;REVERSED SANS-SERIF CAPITAL L;Sm;0;ON;;;;;N;;;;;
+2144;TURNED SANS-SERIF CAPITAL Y;Sm;0;ON;;;;;N;;;;;
+2145;DOUBLE-STRUCK ITALIC CAPITAL D;Lu;0;L;<font> 0044;;;;N;;;;;
+2146;DOUBLE-STRUCK ITALIC SMALL D;Ll;0;L;<font> 0064;;;;N;;;;;
+2147;DOUBLE-STRUCK ITALIC SMALL E;Ll;0;L;<font> 0065;;;;N;;;;;
+2148;DOUBLE-STRUCK ITALIC SMALL I;Ll;0;L;<font> 0069;;;;N;;;;;
+2149;DOUBLE-STRUCK ITALIC SMALL J;Ll;0;L;<font> 006A;;;;N;;;;;
+214A;PROPERTY LINE;So;0;ON;;;;;N;;;;;
+214B;TURNED AMPERSAND;Sm;0;ON;;;;;N;;;;;
+2153;VULGAR FRACTION ONE THIRD;No;0;ON;<fraction> 0031 2044 0033;;;1/3;N;FRACTION ONE THIRD;;;;
+2154;VULGAR FRACTION TWO THIRDS;No;0;ON;<fraction> 0032 2044 0033;;;2/3;N;FRACTION TWO THIRDS;;;;
+2155;VULGAR FRACTION ONE FIFTH;No;0;ON;<fraction> 0031 2044 0035;;;1/5;N;FRACTION ONE FIFTH;;;;
+2156;VULGAR FRACTION TWO FIFTHS;No;0;ON;<fraction> 0032 2044 0035;;;2/5;N;FRACTION TWO FIFTHS;;;;
+2157;VULGAR FRACTION THREE FIFTHS;No;0;ON;<fraction> 0033 2044 0035;;;3/5;N;FRACTION THREE FIFTHS;;;;
+2158;VULGAR FRACTION FOUR FIFTHS;No;0;ON;<fraction> 0034 2044 0035;;;4/5;N;FRACTION FOUR FIFTHS;;;;
+2159;VULGAR FRACTION ONE SIXTH;No;0;ON;<fraction> 0031 2044 0036;;;1/6;N;FRACTION ONE SIXTH;;;;
+215A;VULGAR FRACTION FIVE SIXTHS;No;0;ON;<fraction> 0035 2044 0036;;;5/6;N;FRACTION FIVE SIXTHS;;;;
+215B;VULGAR FRACTION ONE EIGHTH;No;0;ON;<fraction> 0031 2044 0038;;;1/8;N;FRACTION ONE EIGHTH;;;;
+215C;VULGAR FRACTION THREE EIGHTHS;No;0;ON;<fraction> 0033 2044 0038;;;3/8;N;FRACTION THREE EIGHTHS;;;;
+215D;VULGAR FRACTION FIVE EIGHTHS;No;0;ON;<fraction> 0035 2044 0038;;;5/8;N;FRACTION FIVE EIGHTHS;;;;
+215E;VULGAR FRACTION SEVEN EIGHTHS;No;0;ON;<fraction> 0037 2044 0038;;;7/8;N;FRACTION SEVEN EIGHTHS;;;;
+215F;FRACTION NUMERATOR ONE;No;0;ON;<fraction> 0031 2044;;;1;N;;;;;
+2160;ROMAN NUMERAL ONE;Nl;0;L;<compat> 0049;;;1;N;;;;2170;
+2161;ROMAN NUMERAL TWO;Nl;0;L;<compat> 0049 0049;;;2;N;;;;2171;
+2162;ROMAN NUMERAL THREE;Nl;0;L;<compat> 0049 0049 0049;;;3;N;;;;2172;
+2163;ROMAN NUMERAL FOUR;Nl;0;L;<compat> 0049 0056;;;4;N;;;;2173;
+2164;ROMAN NUMERAL FIVE;Nl;0;L;<compat> 0056;;;5;N;;;;2174;
+2165;ROMAN NUMERAL SIX;Nl;0;L;<compat> 0056 0049;;;6;N;;;;2175;
+2166;ROMAN NUMERAL SEVEN;Nl;0;L;<compat> 0056 0049 0049;;;7;N;;;;2176;
+2167;ROMAN NUMERAL EIGHT;Nl;0;L;<compat> 0056 0049 0049 0049;;;8;N;;;;2177;
+2168;ROMAN NUMERAL NINE;Nl;0;L;<compat> 0049 0058;;;9;N;;;;2178;
+2169;ROMAN NUMERAL TEN;Nl;0;L;<compat> 0058;;;10;N;;;;2179;
+216A;ROMAN NUMERAL ELEVEN;Nl;0;L;<compat> 0058 0049;;;11;N;;;;217A;
+216B;ROMAN NUMERAL TWELVE;Nl;0;L;<compat> 0058 0049 0049;;;12;N;;;;217B;
+216C;ROMAN NUMERAL FIFTY;Nl;0;L;<compat> 004C;;;50;N;;;;217C;
+216D;ROMAN NUMERAL ONE HUNDRED;Nl;0;L;<compat> 0043;;;100;N;;;;217D;
+216E;ROMAN NUMERAL FIVE HUNDRED;Nl;0;L;<compat> 0044;;;500;N;;;;217E;
+216F;ROMAN NUMERAL ONE THOUSAND;Nl;0;L;<compat> 004D;;;1000;N;;;;217F;
+2170;SMALL ROMAN NUMERAL ONE;Nl;0;L;<compat> 0069;;;1;N;;;2160;;2160
+2171;SMALL ROMAN NUMERAL TWO;Nl;0;L;<compat> 0069 0069;;;2;N;;;2161;;2161
+2172;SMALL ROMAN NUMERAL THREE;Nl;0;L;<compat> 0069 0069 0069;;;3;N;;;2162;;2162
+2173;SMALL ROMAN NUMERAL FOUR;Nl;0;L;<compat> 0069 0076;;;4;N;;;2163;;2163
+2174;SMALL ROMAN NUMERAL FIVE;Nl;0;L;<compat> 0076;;;5;N;;;2164;;2164
+2175;SMALL ROMAN NUMERAL SIX;Nl;0;L;<compat> 0076 0069;;;6;N;;;2165;;2165
+2176;SMALL ROMAN NUMERAL SEVEN;Nl;0;L;<compat> 0076 0069 0069;;;7;N;;;2166;;2166
+2177;SMALL ROMAN NUMERAL EIGHT;Nl;0;L;<compat> 0076 0069 0069 0069;;;8;N;;;2167;;2167
+2178;SMALL ROMAN NUMERAL NINE;Nl;0;L;<compat> 0069 0078;;;9;N;;;2168;;2168
+2179;SMALL ROMAN NUMERAL TEN;Nl;0;L;<compat> 0078;;;10;N;;;2169;;2169
+217A;SMALL ROMAN NUMERAL ELEVEN;Nl;0;L;<compat> 0078 0069;;;11;N;;;216A;;216A
+217B;SMALL ROMAN NUMERAL TWELVE;Nl;0;L;<compat> 0078 0069 0069;;;12;N;;;216B;;216B
+217C;SMALL ROMAN NUMERAL FIFTY;Nl;0;L;<compat> 006C;;;50;N;;;216C;;216C
+217D;SMALL ROMAN NUMERAL ONE HUNDRED;Nl;0;L;<compat> 0063;;;100;N;;;216D;;216D
+217E;SMALL ROMAN NUMERAL FIVE HUNDRED;Nl;0;L;<compat> 0064;;;500;N;;;216E;;216E
+217F;SMALL ROMAN NUMERAL ONE THOUSAND;Nl;0;L;<compat> 006D;;;1000;N;;;216F;;216F
+2180;ROMAN NUMERAL ONE THOUSAND C D;Nl;0;L;;;;1000;N;;;;;
+2181;ROMAN NUMERAL FIVE THOUSAND;Nl;0;L;;;;5000;N;;;;;
+2182;ROMAN NUMERAL TEN THOUSAND;Nl;0;L;;;;10000;N;;;;;
+2183;ROMAN NUMERAL REVERSED ONE HUNDRED;Nl;0;L;;;;;N;;;;;
+2190;LEFTWARDS ARROW;Sm;0;ON;;;;;N;LEFT ARROW;;;;
+2191;UPWARDS ARROW;Sm;0;ON;;;;;N;UP ARROW;;;;
+2192;RIGHTWARDS ARROW;Sm;0;ON;;;;;N;RIGHT ARROW;;;;
+2193;DOWNWARDS ARROW;Sm;0;ON;;;;;N;DOWN ARROW;;;;
+2194;LEFT RIGHT ARROW;Sm;0;ON;;;;;N;;;;;
+2195;UP DOWN ARROW;So;0;ON;;;;;N;;;;;
+2196;NORTH WEST ARROW;So;0;ON;;;;;N;UPPER LEFT ARROW;;;;
+2197;NORTH EAST ARROW;So;0;ON;;;;;N;UPPER RIGHT ARROW;;;;
+2198;SOUTH EAST ARROW;So;0;ON;;;;;N;LOWER RIGHT ARROW;;;;
+2199;SOUTH WEST ARROW;So;0;ON;;;;;N;LOWER LEFT ARROW;;;;
+219A;LEFTWARDS ARROW WITH STROKE;Sm;0;ON;2190 0338;;;;N;LEFT ARROW WITH STROKE;;;;
+219B;RIGHTWARDS ARROW WITH STROKE;Sm;0;ON;2192 0338;;;;N;RIGHT ARROW WITH STROKE;;;;
+219C;LEFTWARDS WAVE ARROW;So;0;ON;;;;;N;LEFT WAVE ARROW;;;;
+219D;RIGHTWARDS WAVE ARROW;So;0;ON;;;;;N;RIGHT WAVE ARROW;;;;
+219E;LEFTWARDS TWO HEADED ARROW;So;0;ON;;;;;N;LEFT TWO HEADED ARROW;;;;
+219F;UPWARDS TWO HEADED ARROW;So;0;ON;;;;;N;UP TWO HEADED ARROW;;;;
+21A0;RIGHTWARDS TWO HEADED ARROW;Sm;0;ON;;;;;N;RIGHT TWO HEADED ARROW;;;;
+21A1;DOWNWARDS TWO HEADED ARROW;So;0;ON;;;;;N;DOWN TWO HEADED ARROW;;;;
+21A2;LEFTWARDS ARROW WITH TAIL;So;0;ON;;;;;N;LEFT ARROW WITH TAIL;;;;
+21A3;RIGHTWARDS ARROW WITH TAIL;Sm;0;ON;;;;;N;RIGHT ARROW WITH TAIL;;;;
+21A4;LEFTWARDS ARROW FROM BAR;So;0;ON;;;;;N;LEFT ARROW FROM BAR;;;;
+21A5;UPWARDS ARROW FROM BAR;So;0;ON;;;;;N;UP ARROW FROM BAR;;;;
+21A6;RIGHTWARDS ARROW FROM BAR;Sm;0;ON;;;;;N;RIGHT ARROW FROM BAR;;;;
+21A7;DOWNWARDS ARROW FROM BAR;So;0;ON;;;;;N;DOWN ARROW FROM BAR;;;;
+21A8;UP DOWN ARROW WITH BASE;So;0;ON;;;;;N;;;;;
+21A9;LEFTWARDS ARROW WITH HOOK;So;0;ON;;;;;N;LEFT ARROW WITH HOOK;;;;
+21AA;RIGHTWARDS ARROW WITH HOOK;So;0;ON;;;;;N;RIGHT ARROW WITH HOOK;;;;
+21AB;LEFTWARDS ARROW WITH LOOP;So;0;ON;;;;;N;LEFT ARROW WITH LOOP;;;;
+21AC;RIGHTWARDS ARROW WITH LOOP;So;0;ON;;;;;N;RIGHT ARROW WITH LOOP;;;;
+21AD;LEFT RIGHT WAVE ARROW;So;0;ON;;;;;N;;;;;
+21AE;LEFT RIGHT ARROW WITH STROKE;Sm;0;ON;2194 0338;;;;N;;;;;
+21AF;DOWNWARDS ZIGZAG ARROW;So;0;ON;;;;;N;DOWN ZIGZAG ARROW;;;;
+21B0;UPWARDS ARROW WITH TIP LEFTWARDS;So;0;ON;;;;;N;UP ARROW WITH TIP LEFT;;;;
+21B1;UPWARDS ARROW WITH TIP RIGHTWARDS;So;0;ON;;;;;N;UP ARROW WITH TIP RIGHT;;;;
+21B2;DOWNWARDS ARROW WITH TIP LEFTWARDS;So;0;ON;;;;;N;DOWN ARROW WITH TIP LEFT;;;;
+21B3;DOWNWARDS ARROW WITH TIP RIGHTWARDS;So;0;ON;;;;;N;DOWN ARROW WITH TIP RIGHT;;;;
+21B4;RIGHTWARDS ARROW WITH CORNER DOWNWARDS;So;0;ON;;;;;N;RIGHT ARROW WITH CORNER DOWN;;;;
+21B5;DOWNWARDS ARROW WITH CORNER LEFTWARDS;So;0;ON;;;;;N;DOWN ARROW WITH CORNER LEFT;;;;
+21B6;ANTICLOCKWISE TOP SEMICIRCLE ARROW;So;0;ON;;;;;N;;;;;
+21B7;CLOCKWISE TOP SEMICIRCLE ARROW;So;0;ON;;;;;N;;;;;
+21B8;NORTH WEST ARROW TO LONG BAR;So;0;ON;;;;;N;UPPER LEFT ARROW TO LONG BAR;;;;
+21B9;LEFTWARDS ARROW TO BAR OVER RIGHTWARDS ARROW TO BAR;So;0;ON;;;;;N;LEFT ARROW TO BAR OVER RIGHT ARROW TO BAR;;;;
+21BA;ANTICLOCKWISE OPEN CIRCLE ARROW;So;0;ON;;;;;N;;;;;
+21BB;CLOCKWISE OPEN CIRCLE ARROW;So;0;ON;;;;;N;;;;;
+21BC;LEFTWARDS HARPOON WITH BARB UPWARDS;So;0;ON;;;;;N;LEFT HARPOON WITH BARB UP;;;;
+21BD;LEFTWARDS HARPOON WITH BARB DOWNWARDS;So;0;ON;;;;;N;LEFT HARPOON WITH BARB DOWN;;;;
+21BE;UPWARDS HARPOON WITH BARB RIGHTWARDS;So;0;ON;;;;;N;UP HARPOON WITH BARB RIGHT;;;;
+21BF;UPWARDS HARPOON WITH BARB LEFTWARDS;So;0;ON;;;;;N;UP HARPOON WITH BARB LEFT;;;;
+21C0;RIGHTWARDS HARPOON WITH BARB UPWARDS;So;0;ON;;;;;N;RIGHT HARPOON WITH BARB UP;;;;
+21C1;RIGHTWARDS HARPOON WITH BARB DOWNWARDS;So;0;ON;;;;;N;RIGHT HARPOON WITH BARB DOWN;;;;
+21C2;DOWNWARDS HARPOON WITH BARB RIGHTWARDS;So;0;ON;;;;;N;DOWN HARPOON WITH BARB RIGHT;;;;
+21C3;DOWNWARDS HARPOON WITH BARB LEFTWARDS;So;0;ON;;;;;N;DOWN HARPOON WITH BARB LEFT;;;;
+21C4;RIGHTWARDS ARROW OVER LEFTWARDS ARROW;So;0;ON;;;;;N;RIGHT ARROW OVER LEFT ARROW;;;;
+21C5;UPWARDS ARROW LEFTWARDS OF DOWNWARDS ARROW;So;0;ON;;;;;N;UP ARROW LEFT OF DOWN ARROW;;;;
+21C6;LEFTWARDS ARROW OVER RIGHTWARDS ARROW;So;0;ON;;;;;N;LEFT ARROW OVER RIGHT ARROW;;;;
+21C7;LEFTWARDS PAIRED ARROWS;So;0;ON;;;;;N;LEFT PAIRED ARROWS;;;;
+21C8;UPWARDS PAIRED ARROWS;So;0;ON;;;;;N;UP PAIRED ARROWS;;;;
+21C9;RIGHTWARDS PAIRED ARROWS;So;0;ON;;;;;N;RIGHT PAIRED ARROWS;;;;
+21CA;DOWNWARDS PAIRED ARROWS;So;0;ON;;;;;N;DOWN PAIRED ARROWS;;;;
+21CB;LEFTWARDS HARPOON OVER RIGHTWARDS HARPOON;So;0;ON;;;;;N;LEFT HARPOON OVER RIGHT HARPOON;;;;
+21CC;RIGHTWARDS HARPOON OVER LEFTWARDS HARPOON;So;0;ON;;;;;N;RIGHT HARPOON OVER LEFT HARPOON;;;;
+21CD;LEFTWARDS DOUBLE ARROW WITH STROKE;So;0;ON;21D0 0338;;;;N;LEFT DOUBLE ARROW WITH STROKE;;;;
+21CE;LEFT RIGHT DOUBLE ARROW WITH STROKE;Sm;0;ON;21D4 0338;;;;N;;;;;
+21CF;RIGHTWARDS DOUBLE ARROW WITH STROKE;Sm;0;ON;21D2 0338;;;;N;RIGHT DOUBLE ARROW WITH STROKE;;;;
+21D0;LEFTWARDS DOUBLE ARROW;So;0;ON;;;;;N;LEFT DOUBLE ARROW;;;;
+21D1;UPWARDS DOUBLE ARROW;So;0;ON;;;;;N;UP DOUBLE ARROW;;;;
+21D2;RIGHTWARDS DOUBLE ARROW;Sm;0;ON;;;;;N;RIGHT DOUBLE ARROW;;;;
+21D3;DOWNWARDS DOUBLE ARROW;So;0;ON;;;;;N;DOWN DOUBLE ARROW;;;;
+21D4;LEFT RIGHT DOUBLE ARROW;Sm;0;ON;;;;;N;;;;;
+21D5;UP DOWN DOUBLE ARROW;So;0;ON;;;;;N;;;;;
+21D6;NORTH WEST DOUBLE ARROW;So;0;ON;;;;;N;UPPER LEFT DOUBLE ARROW;;;;
+21D7;NORTH EAST DOUBLE ARROW;So;0;ON;;;;;N;UPPER RIGHT DOUBLE ARROW;;;;
+21D8;SOUTH EAST DOUBLE ARROW;So;0;ON;;;;;N;LOWER RIGHT DOUBLE ARROW;;;;
+21D9;SOUTH WEST DOUBLE ARROW;So;0;ON;;;;;N;LOWER LEFT DOUBLE ARROW;;;;
+21DA;LEFTWARDS TRIPLE ARROW;So;0;ON;;;;;N;LEFT TRIPLE ARROW;;;;
+21DB;RIGHTWARDS TRIPLE ARROW;So;0;ON;;;;;N;RIGHT TRIPLE ARROW;;;;
+21DC;LEFTWARDS SQUIGGLE ARROW;So;0;ON;;;;;N;LEFT SQUIGGLE ARROW;;;;
+21DD;RIGHTWARDS SQUIGGLE ARROW;So;0;ON;;;;;N;RIGHT SQUIGGLE ARROW;;;;
+21DE;UPWARDS ARROW WITH DOUBLE STROKE;So;0;ON;;;;;N;UP ARROW WITH DOUBLE STROKE;;;;
+21DF;DOWNWARDS ARROW WITH DOUBLE STROKE;So;0;ON;;;;;N;DOWN ARROW WITH DOUBLE STROKE;;;;
+21E0;LEFTWARDS DASHED ARROW;So;0;ON;;;;;N;LEFT DASHED ARROW;;;;
+21E1;UPWARDS DASHED ARROW;So;0;ON;;;;;N;UP DASHED ARROW;;;;
+21E2;RIGHTWARDS DASHED ARROW;So;0;ON;;;;;N;RIGHT DASHED ARROW;;;;
+21E3;DOWNWARDS DASHED ARROW;So;0;ON;;;;;N;DOWN DASHED ARROW;;;;
+21E4;LEFTWARDS ARROW TO BAR;So;0;ON;;;;;N;LEFT ARROW TO BAR;;;;
+21E5;RIGHTWARDS ARROW TO BAR;So;0;ON;;;;;N;RIGHT ARROW TO BAR;;;;
+21E6;LEFTWARDS WHITE ARROW;So;0;ON;;;;;N;WHITE LEFT ARROW;;;;
+21E7;UPWARDS WHITE ARROW;So;0;ON;;;;;N;WHITE UP ARROW;;;;
+21E8;RIGHTWARDS WHITE ARROW;So;0;ON;;;;;N;WHITE RIGHT ARROW;;;;
+21E9;DOWNWARDS WHITE ARROW;So;0;ON;;;;;N;WHITE DOWN ARROW;;;;
+21EA;UPWARDS WHITE ARROW FROM BAR;So;0;ON;;;;;N;WHITE UP ARROW FROM BAR;;;;
+21EB;UPWARDS WHITE ARROW ON PEDESTAL;So;0;ON;;;;;N;;;;;
+21EC;UPWARDS WHITE ARROW ON PEDESTAL WITH HORIZONTAL BAR;So;0;ON;;;;;N;;;;;
+21ED;UPWARDS WHITE ARROW ON PEDESTAL WITH VERTICAL BAR;So;0;ON;;;;;N;;;;;
+21EE;UPWARDS WHITE DOUBLE ARROW;So;0;ON;;;;;N;;;;;
+21EF;UPWARDS WHITE DOUBLE ARROW ON PEDESTAL;So;0;ON;;;;;N;;;;;
+21F0;RIGHTWARDS WHITE ARROW FROM WALL;So;0;ON;;;;;N;;;;;
+21F1;NORTH WEST ARROW TO CORNER;So;0;ON;;;;;N;;;;;
+21F2;SOUTH EAST ARROW TO CORNER;So;0;ON;;;;;N;;;;;
+21F3;UP DOWN WHITE ARROW;So;0;ON;;;;;N;;;;;
+21F4;RIGHT ARROW WITH SMALL CIRCLE;Sm;0;ON;;;;;N;;;;;
+21F5;DOWNWARDS ARROW LEFTWARDS OF UPWARDS ARROW;Sm;0;ON;;;;;N;;;;;
+21F6;THREE RIGHTWARDS ARROWS;Sm;0;ON;;;;;N;;;;;
+21F7;LEFTWARDS ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+21F8;RIGHTWARDS ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+21F9;LEFT RIGHT ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+21FA;LEFTWARDS ARROW WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+21FB;RIGHTWARDS ARROW WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+21FC;LEFT RIGHT ARROW WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+21FD;LEFTWARDS OPEN-HEADED ARROW;Sm;0;ON;;;;;N;;;;;
+21FE;RIGHTWARDS OPEN-HEADED ARROW;Sm;0;ON;;;;;N;;;;;
+21FF;LEFT RIGHT OPEN-HEADED ARROW;Sm;0;ON;;;;;N;;;;;
+2200;FOR ALL;Sm;0;ON;;;;;N;;;;;
+2201;COMPLEMENT;Sm;0;ON;;;;;Y;;;;;
+2202;PARTIAL DIFFERENTIAL;Sm;0;ON;;;;;Y;;;;;
+2203;THERE EXISTS;Sm;0;ON;;;;;Y;;;;;
+2204;THERE DOES NOT EXIST;Sm;0;ON;2203 0338;;;;Y;;;;;
+2205;EMPTY SET;Sm;0;ON;;;;;N;;;;;
+2206;INCREMENT;Sm;0;ON;;;;;N;;;;;
+2207;NABLA;Sm;0;ON;;;;;N;;;;;
+2208;ELEMENT OF;Sm;0;ON;;;;;Y;;;;;
+2209;NOT AN ELEMENT OF;Sm;0;ON;2208 0338;;;;Y;;;;;
+220A;SMALL ELEMENT OF;Sm;0;ON;;;;;Y;;;;;
+220B;CONTAINS AS MEMBER;Sm;0;ON;;;;;Y;;;;;
+220C;DOES NOT CONTAIN AS MEMBER;Sm;0;ON;220B 0338;;;;Y;;;;;
+220D;SMALL CONTAINS AS MEMBER;Sm;0;ON;;;;;Y;;;;;
+220E;END OF PROOF;Sm;0;ON;;;;;N;;;;;
+220F;N-ARY PRODUCT;Sm;0;ON;;;;;N;;;;;
+2210;N-ARY COPRODUCT;Sm;0;ON;;;;;N;;;;;
+2211;N-ARY SUMMATION;Sm;0;ON;;;;;Y;;;;;
+2212;MINUS SIGN;Sm;0;ET;;;;;N;;;;;
+2213;MINUS-OR-PLUS SIGN;Sm;0;ET;;;;;N;;;;;
+2214;DOT PLUS;Sm;0;ON;;;;;N;;;;;
+2215;DIVISION SLASH;Sm;0;ON;;;;;Y;;;;;
+2216;SET MINUS;Sm;0;ON;;;;;Y;;;;;
+2217;ASTERISK OPERATOR;Sm;0;ON;;;;;N;;;;;
+2218;RING OPERATOR;Sm;0;ON;;;;;N;;;;;
+2219;BULLET OPERATOR;Sm;0;ON;;;;;N;;;;;
+221A;SQUARE ROOT;Sm;0;ON;;;;;Y;;;;;
+221B;CUBE ROOT;Sm;0;ON;;;;;Y;;;;;
+221C;FOURTH ROOT;Sm;0;ON;;;;;Y;;;;;
+221D;PROPORTIONAL TO;Sm;0;ON;;;;;Y;;;;;
+221E;INFINITY;Sm;0;ON;;;;;N;;;;;
+221F;RIGHT ANGLE;Sm;0;ON;;;;;Y;;;;;
+2220;ANGLE;Sm;0;ON;;;;;Y;;;;;
+2221;MEASURED ANGLE;Sm;0;ON;;;;;Y;;;;;
+2222;SPHERICAL ANGLE;Sm;0;ON;;;;;Y;;;;;
+2223;DIVIDES;Sm;0;ON;;;;;N;;;;;
+2224;DOES NOT DIVIDE;Sm;0;ON;2223 0338;;;;Y;;;;;
+2225;PARALLEL TO;Sm;0;ON;;;;;N;;;;;
+2226;NOT PARALLEL TO;Sm;0;ON;2225 0338;;;;Y;;;;;
+2227;LOGICAL AND;Sm;0;ON;;;;;N;;;;;
+2228;LOGICAL OR;Sm;0;ON;;;;;N;;;;;
+2229;INTERSECTION;Sm;0;ON;;;;;N;;;;;
+222A;UNION;Sm;0;ON;;;;;N;;;;;
+222B;INTEGRAL;Sm;0;ON;;;;;Y;;;;;
+222C;DOUBLE INTEGRAL;Sm;0;ON;<compat> 222B 222B;;;;Y;;;;;
+222D;TRIPLE INTEGRAL;Sm;0;ON;<compat> 222B 222B 222B;;;;Y;;;;;
+222E;CONTOUR INTEGRAL;Sm;0;ON;;;;;Y;;;;;
+222F;SURFACE INTEGRAL;Sm;0;ON;<compat> 222E 222E;;;;Y;;;;;
+2230;VOLUME INTEGRAL;Sm;0;ON;<compat> 222E 222E 222E;;;;Y;;;;;
+2231;CLOCKWISE INTEGRAL;Sm;0;ON;;;;;Y;;;;;
+2232;CLOCKWISE CONTOUR INTEGRAL;Sm;0;ON;;;;;Y;;;;;
+2233;ANTICLOCKWISE CONTOUR INTEGRAL;Sm;0;ON;;;;;Y;;;;;
+2234;THEREFORE;Sm;0;ON;;;;;N;;;;;
+2235;BECAUSE;Sm;0;ON;;;;;N;;;;;
+2236;RATIO;Sm;0;ON;;;;;N;;;;;
+2237;PROPORTION;Sm;0;ON;;;;;N;;;;;
+2238;DOT MINUS;Sm;0;ON;;;;;N;;;;;
+2239;EXCESS;Sm;0;ON;;;;;Y;;;;;
+223A;GEOMETRIC PROPORTION;Sm;0;ON;;;;;N;;;;;
+223B;HOMOTHETIC;Sm;0;ON;;;;;Y;;;;;
+223C;TILDE OPERATOR;Sm;0;ON;;;;;Y;;;;;
+223D;REVERSED TILDE;Sm;0;ON;;;;;Y;;lazy S;;;
+223E;INVERTED LAZY S;Sm;0;ON;;;;;Y;;;;;
+223F;SINE WAVE;Sm;0;ON;;;;;Y;;;;;
+2240;WREATH PRODUCT;Sm;0;ON;;;;;Y;;;;;
+2241;NOT TILDE;Sm;0;ON;223C 0338;;;;Y;;;;;
+2242;MINUS TILDE;Sm;0;ON;;;;;Y;;;;;
+2243;ASYMPTOTICALLY EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2244;NOT ASYMPTOTICALLY EQUAL TO;Sm;0;ON;2243 0338;;;;Y;;;;;
+2245;APPROXIMATELY EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2246;APPROXIMATELY BUT NOT ACTUALLY EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2247;NEITHER APPROXIMATELY NOR ACTUALLY EQUAL TO;Sm;0;ON;2245 0338;;;;Y;;;;;
+2248;ALMOST EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2249;NOT ALMOST EQUAL TO;Sm;0;ON;2248 0338;;;;Y;;;;;
+224A;ALMOST EQUAL OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+224B;TRIPLE TILDE;Sm;0;ON;;;;;Y;;;;;
+224C;ALL EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+224D;EQUIVALENT TO;Sm;0;ON;;;;;N;;;;;
+224E;GEOMETRICALLY EQUIVALENT TO;Sm;0;ON;;;;;N;;;;;
+224F;DIFFERENCE BETWEEN;Sm;0;ON;;;;;N;;;;;
+2250;APPROACHES THE LIMIT;Sm;0;ON;;;;;N;;;;;
+2251;GEOMETRICALLY EQUAL TO;Sm;0;ON;;;;;N;;;;;
+2252;APPROXIMATELY EQUAL TO OR THE IMAGE OF;Sm;0;ON;;;;;Y;;;;;
+2253;IMAGE OF OR APPROXIMATELY EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2254;COLON EQUALS;Sm;0;ON;;;;;Y;COLON EQUAL;;;;
+2255;EQUALS COLON;Sm;0;ON;;;;;Y;EQUAL COLON;;;;
+2256;RING IN EQUAL TO;Sm;0;ON;;;;;N;;;;;
+2257;RING EQUAL TO;Sm;0;ON;;;;;N;;;;;
+2258;CORRESPONDS TO;Sm;0;ON;;;;;N;;;;;
+2259;ESTIMATES;Sm;0;ON;;;;;N;;;;;
+225A;EQUIANGULAR TO;Sm;0;ON;;;;;N;;;;;
+225B;STAR EQUALS;Sm;0;ON;;;;;N;;;;;
+225C;DELTA EQUAL TO;Sm;0;ON;;;;;N;;;;;
+225D;EQUAL TO BY DEFINITION;Sm;0;ON;;;;;N;;;;;
+225E;MEASURED BY;Sm;0;ON;;;;;N;;;;;
+225F;QUESTIONED EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2260;NOT EQUAL TO;Sm;0;ON;003D 0338;;;;Y;;;;;
+2261;IDENTICAL TO;Sm;0;ON;;;;;N;;;;;
+2262;NOT IDENTICAL TO;Sm;0;ON;2261 0338;;;;Y;;;;;
+2263;STRICTLY EQUIVALENT TO;Sm;0;ON;;;;;N;;;;;
+2264;LESS-THAN OR EQUAL TO;Sm;0;ON;;;;;Y;LESS THAN OR EQUAL TO;;;;
+2265;GREATER-THAN OR EQUAL TO;Sm;0;ON;;;;;Y;GREATER THAN OR EQUAL TO;;;;
+2266;LESS-THAN OVER EQUAL TO;Sm;0;ON;;;;;Y;LESS THAN OVER EQUAL TO;;;;
+2267;GREATER-THAN OVER EQUAL TO;Sm;0;ON;;;;;Y;GREATER THAN OVER EQUAL TO;;;;
+2268;LESS-THAN BUT NOT EQUAL TO;Sm;0;ON;;;;;Y;LESS THAN BUT NOT EQUAL TO;;;;
+2269;GREATER-THAN BUT NOT EQUAL TO;Sm;0;ON;;;;;Y;GREATER THAN BUT NOT EQUAL TO;;;;
+226A;MUCH LESS-THAN;Sm;0;ON;;;;;Y;MUCH LESS THAN;;;;
+226B;MUCH GREATER-THAN;Sm;0;ON;;;;;Y;MUCH GREATER THAN;;;;
+226C;BETWEEN;Sm;0;ON;;;;;N;;;;;
+226D;NOT EQUIVALENT TO;Sm;0;ON;224D 0338;;;;N;;;;;
+226E;NOT LESS-THAN;Sm;0;ON;003C 0338;;;;Y;NOT LESS THAN;;;;
+226F;NOT GREATER-THAN;Sm;0;ON;003E 0338;;;;Y;NOT GREATER THAN;;;;
+2270;NEITHER LESS-THAN NOR EQUAL TO;Sm;0;ON;2264 0338;;;;Y;NEITHER LESS THAN NOR EQUAL TO;;;;
+2271;NEITHER GREATER-THAN NOR EQUAL TO;Sm;0;ON;2265 0338;;;;Y;NEITHER GREATER THAN NOR EQUAL TO;;;;
+2272;LESS-THAN OR EQUIVALENT TO;Sm;0;ON;;;;;Y;LESS THAN OR EQUIVALENT TO;;;;
+2273;GREATER-THAN OR EQUIVALENT TO;Sm;0;ON;;;;;Y;GREATER THAN OR EQUIVALENT TO;;;;
+2274;NEITHER LESS-THAN NOR EQUIVALENT TO;Sm;0;ON;2272 0338;;;;Y;NEITHER LESS THAN NOR EQUIVALENT TO;;;;
+2275;NEITHER GREATER-THAN NOR EQUIVALENT TO;Sm;0;ON;2273 0338;;;;Y;NEITHER GREATER THAN NOR EQUIVALENT TO;;;;
+2276;LESS-THAN OR GREATER-THAN;Sm;0;ON;;;;;Y;LESS THAN OR GREATER THAN;;;;
+2277;GREATER-THAN OR LESS-THAN;Sm;0;ON;;;;;Y;GREATER THAN OR LESS THAN;;;;
+2278;NEITHER LESS-THAN NOR GREATER-THAN;Sm;0;ON;2276 0338;;;;Y;NEITHER LESS THAN NOR GREATER THAN;;;;
+2279;NEITHER GREATER-THAN NOR LESS-THAN;Sm;0;ON;2277 0338;;;;Y;NEITHER GREATER THAN NOR LESS THAN;;;;
+227A;PRECEDES;Sm;0;ON;;;;;Y;;;;;
+227B;SUCCEEDS;Sm;0;ON;;;;;Y;;;;;
+227C;PRECEDES OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+227D;SUCCEEDS OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+227E;PRECEDES OR EQUIVALENT TO;Sm;0;ON;;;;;Y;;;;;
+227F;SUCCEEDS OR EQUIVALENT TO;Sm;0;ON;;;;;Y;;;;;
+2280;DOES NOT PRECEDE;Sm;0;ON;227A 0338;;;;Y;;;;;
+2281;DOES NOT SUCCEED;Sm;0;ON;227B 0338;;;;Y;;;;;
+2282;SUBSET OF;Sm;0;ON;;;;;Y;;;;;
+2283;SUPERSET OF;Sm;0;ON;;;;;Y;;;;;
+2284;NOT A SUBSET OF;Sm;0;ON;2282 0338;;;;Y;;;;;
+2285;NOT A SUPERSET OF;Sm;0;ON;2283 0338;;;;Y;;;;;
+2286;SUBSET OF OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2287;SUPERSET OF OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2288;NEITHER A SUBSET OF NOR EQUAL TO;Sm;0;ON;2286 0338;;;;Y;;;;;
+2289;NEITHER A SUPERSET OF NOR EQUAL TO;Sm;0;ON;2287 0338;;;;Y;;;;;
+228A;SUBSET OF WITH NOT EQUAL TO;Sm;0;ON;;;;;Y;SUBSET OF OR NOT EQUAL TO;;;;
+228B;SUPERSET OF WITH NOT EQUAL TO;Sm;0;ON;;;;;Y;SUPERSET OF OR NOT EQUAL TO;;;;
+228C;MULTISET;Sm;0;ON;;;;;Y;;;;;
+228D;MULTISET MULTIPLICATION;Sm;0;ON;;;;;N;;;;;
+228E;MULTISET UNION;Sm;0;ON;;;;;N;;;;;
+228F;SQUARE IMAGE OF;Sm;0;ON;;;;;Y;;;;;
+2290;SQUARE ORIGINAL OF;Sm;0;ON;;;;;Y;;;;;
+2291;SQUARE IMAGE OF OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2292;SQUARE ORIGINAL OF OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2293;SQUARE CAP;Sm;0;ON;;;;;N;;;;;
+2294;SQUARE CUP;Sm;0;ON;;;;;N;;;;;
+2295;CIRCLED PLUS;Sm;0;ON;;;;;N;;;;;
+2296;CIRCLED MINUS;Sm;0;ON;;;;;N;;;;;
+2297;CIRCLED TIMES;Sm;0;ON;;;;;N;;;;;
+2298;CIRCLED DIVISION SLASH;Sm;0;ON;;;;;Y;;;;;
+2299;CIRCLED DOT OPERATOR;Sm;0;ON;;;;;N;;;;;
+229A;CIRCLED RING OPERATOR;Sm;0;ON;;;;;N;;;;;
+229B;CIRCLED ASTERISK OPERATOR;Sm;0;ON;;;;;N;;;;;
+229C;CIRCLED EQUALS;Sm;0;ON;;;;;N;;;;;
+229D;CIRCLED DASH;Sm;0;ON;;;;;N;;;;;
+229E;SQUARED PLUS;Sm;0;ON;;;;;N;;;;;
+229F;SQUARED MINUS;Sm;0;ON;;;;;N;;;;;
+22A0;SQUARED TIMES;Sm;0;ON;;;;;N;;;;;
+22A1;SQUARED DOT OPERATOR;Sm;0;ON;;;;;N;;;;;
+22A2;RIGHT TACK;Sm;0;ON;;;;;Y;;;;;
+22A3;LEFT TACK;Sm;0;ON;;;;;Y;;;;;
+22A4;DOWN TACK;Sm;0;ON;;;;;N;;;;;
+22A5;UP TACK;Sm;0;ON;;;;;N;;;;;
+22A6;ASSERTION;Sm;0;ON;;;;;Y;;;;;
+22A7;MODELS;Sm;0;ON;;;;;Y;;;;;
+22A8;TRUE;Sm;0;ON;;;;;Y;;;;;
+22A9;FORCES;Sm;0;ON;;;;;Y;;;;;
+22AA;TRIPLE VERTICAL BAR RIGHT TURNSTILE;Sm;0;ON;;;;;Y;;;;;
+22AB;DOUBLE VERTICAL BAR DOUBLE RIGHT TURNSTILE;Sm;0;ON;;;;;Y;;;;;
+22AC;DOES NOT PROVE;Sm;0;ON;22A2 0338;;;;Y;;;;;
+22AD;NOT TRUE;Sm;0;ON;22A8 0338;;;;Y;;;;;
+22AE;DOES NOT FORCE;Sm;0;ON;22A9 0338;;;;Y;;;;;
+22AF;NEGATED DOUBLE VERTICAL BAR DOUBLE RIGHT TURNSTILE;Sm;0;ON;22AB 0338;;;;Y;;;;;
+22B0;PRECEDES UNDER RELATION;Sm;0;ON;;;;;Y;;;;;
+22B1;SUCCEEDS UNDER RELATION;Sm;0;ON;;;;;Y;;;;;
+22B2;NORMAL SUBGROUP OF;Sm;0;ON;;;;;Y;;;;;
+22B3;CONTAINS AS NORMAL SUBGROUP;Sm;0;ON;;;;;Y;;;;;
+22B4;NORMAL SUBGROUP OF OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+22B5;CONTAINS AS NORMAL SUBGROUP OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+22B6;ORIGINAL OF;Sm;0;ON;;;;;Y;;;;;
+22B7;IMAGE OF;Sm;0;ON;;;;;Y;;;;;
+22B8;MULTIMAP;Sm;0;ON;;;;;Y;;;;;
+22B9;HERMITIAN CONJUGATE MATRIX;Sm;0;ON;;;;;N;;;;;
+22BA;INTERCALATE;Sm;0;ON;;;;;N;;;;;
+22BB;XOR;Sm;0;ON;;;;;N;;;;;
+22BC;NAND;Sm;0;ON;;;;;N;;;;;
+22BD;NOR;Sm;0;ON;;;;;N;;;;;
+22BE;RIGHT ANGLE WITH ARC;Sm;0;ON;;;;;Y;;;;;
+22BF;RIGHT TRIANGLE;Sm;0;ON;;;;;Y;;;;;
+22C0;N-ARY LOGICAL AND;Sm;0;ON;;;;;N;;;;;
+22C1;N-ARY LOGICAL OR;Sm;0;ON;;;;;N;;;;;
+22C2;N-ARY INTERSECTION;Sm;0;ON;;;;;N;;;;;
+22C3;N-ARY UNION;Sm;0;ON;;;;;N;;;;;
+22C4;DIAMOND OPERATOR;Sm;0;ON;;;;;N;;;;;
+22C5;DOT OPERATOR;Sm;0;ON;;;;;N;;;;;
+22C6;STAR OPERATOR;Sm;0;ON;;;;;N;;;;;
+22C7;DIVISION TIMES;Sm;0;ON;;;;;N;;;;;
+22C8;BOWTIE;Sm;0;ON;;;;;N;;;;;
+22C9;LEFT NORMAL FACTOR SEMIDIRECT PRODUCT;Sm;0;ON;;;;;Y;;;;;
+22CA;RIGHT NORMAL FACTOR SEMIDIRECT PRODUCT;Sm;0;ON;;;;;Y;;;;;
+22CB;LEFT SEMIDIRECT PRODUCT;Sm;0;ON;;;;;Y;;;;;
+22CC;RIGHT SEMIDIRECT PRODUCT;Sm;0;ON;;;;;Y;;;;;
+22CD;REVERSED TILDE EQUALS;Sm;0;ON;;;;;Y;;;;;
+22CE;CURLY LOGICAL OR;Sm;0;ON;;;;;N;;;;;
+22CF;CURLY LOGICAL AND;Sm;0;ON;;;;;N;;;;;
+22D0;DOUBLE SUBSET;Sm;0;ON;;;;;Y;;;;;
+22D1;DOUBLE SUPERSET;Sm;0;ON;;;;;Y;;;;;
+22D2;DOUBLE INTERSECTION;Sm;0;ON;;;;;N;;;;;
+22D3;DOUBLE UNION;Sm;0;ON;;;;;N;;;;;
+22D4;PITCHFORK;Sm;0;ON;;;;;N;;;;;
+22D5;EQUAL AND PARALLEL TO;Sm;0;ON;;;;;N;;;;;
+22D6;LESS-THAN WITH DOT;Sm;0;ON;;;;;Y;LESS THAN WITH DOT;;;;
+22D7;GREATER-THAN WITH DOT;Sm;0;ON;;;;;Y;GREATER THAN WITH DOT;;;;
+22D8;VERY MUCH LESS-THAN;Sm;0;ON;;;;;Y;VERY MUCH LESS THAN;;;;
+22D9;VERY MUCH GREATER-THAN;Sm;0;ON;;;;;Y;VERY MUCH GREATER THAN;;;;
+22DA;LESS-THAN EQUAL TO OR GREATER-THAN;Sm;0;ON;;;;;Y;LESS THAN EQUAL TO OR GREATER THAN;;;;
+22DB;GREATER-THAN EQUAL TO OR LESS-THAN;Sm;0;ON;;;;;Y;GREATER THAN EQUAL TO OR LESS THAN;;;;
+22DC;EQUAL TO OR LESS-THAN;Sm;0;ON;;;;;Y;EQUAL TO OR LESS THAN;;;;
+22DD;EQUAL TO OR GREATER-THAN;Sm;0;ON;;;;;Y;EQUAL TO OR GREATER THAN;;;;
+22DE;EQUAL TO OR PRECEDES;Sm;0;ON;;;;;Y;;;;;
+22DF;EQUAL TO OR SUCCEEDS;Sm;0;ON;;;;;Y;;;;;
+22E0;DOES NOT PRECEDE OR EQUAL;Sm;0;ON;227C 0338;;;;Y;;;;;
+22E1;DOES NOT SUCCEED OR EQUAL;Sm;0;ON;227D 0338;;;;Y;;;;;
+22E2;NOT SQUARE IMAGE OF OR EQUAL TO;Sm;0;ON;2291 0338;;;;Y;;;;;
+22E3;NOT SQUARE ORIGINAL OF OR EQUAL TO;Sm;0;ON;2292 0338;;;;Y;;;;;
+22E4;SQUARE IMAGE OF OR NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+22E5;SQUARE ORIGINAL OF OR NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+22E6;LESS-THAN BUT NOT EQUIVALENT TO;Sm;0;ON;;;;;Y;LESS THAN BUT NOT EQUIVALENT TO;;;;
+22E7;GREATER-THAN BUT NOT EQUIVALENT TO;Sm;0;ON;;;;;Y;GREATER THAN BUT NOT EQUIVALENT TO;;;;
+22E8;PRECEDES BUT NOT EQUIVALENT TO;Sm;0;ON;;;;;Y;;;;;
+22E9;SUCCEEDS BUT NOT EQUIVALENT TO;Sm;0;ON;;;;;Y;;;;;
+22EA;NOT NORMAL SUBGROUP OF;Sm;0;ON;22B2 0338;;;;Y;;;;;
+22EB;DOES NOT CONTAIN AS NORMAL SUBGROUP;Sm;0;ON;22B3 0338;;;;Y;;;;;
+22EC;NOT NORMAL SUBGROUP OF OR EQUAL TO;Sm;0;ON;22B4 0338;;;;Y;;;;;
+22ED;DOES NOT CONTAIN AS NORMAL SUBGROUP OR EQUAL;Sm;0;ON;22B5 0338;;;;Y;;;;;
+22EE;VERTICAL ELLIPSIS;Sm;0;ON;;;;;N;;;;;
+22EF;MIDLINE HORIZONTAL ELLIPSIS;Sm;0;ON;;;;;N;;;;;
+22F0;UP RIGHT DIAGONAL ELLIPSIS;Sm;0;ON;;;;;Y;;;;;
+22F1;DOWN RIGHT DIAGONAL ELLIPSIS;Sm;0;ON;;;;;Y;;;;;
+22F2;ELEMENT OF WITH LONG HORIZONTAL STROKE;Sm;0;ON;;;;;Y;;;;;
+22F3;ELEMENT OF WITH VERTICAL BAR AT END OF HORIZONTAL STROKE;Sm;0;ON;;;;;Y;;;;;
+22F4;SMALL ELEMENT OF WITH VERTICAL BAR AT END OF HORIZONTAL STROKE;Sm;0;ON;;;;;Y;;;;;
+22F5;ELEMENT OF WITH DOT ABOVE;Sm;0;ON;;;;;Y;;;;;
+22F6;ELEMENT OF WITH OVERBAR;Sm;0;ON;;;;;Y;;;;;
+22F7;SMALL ELEMENT OF WITH OVERBAR;Sm;0;ON;;;;;Y;;;;;
+22F8;ELEMENT OF WITH UNDERBAR;Sm;0;ON;;;;;Y;;;;;
+22F9;ELEMENT OF WITH TWO HORIZONTAL STROKES;Sm;0;ON;;;;;Y;;;;;
+22FA;CONTAINS WITH LONG HORIZONTAL STROKE;Sm;0;ON;;;;;Y;;;;;
+22FB;CONTAINS WITH VERTICAL BAR AT END OF HORIZONTAL STROKE;Sm;0;ON;;;;;Y;;;;;
+22FC;SMALL CONTAINS WITH VERTICAL BAR AT END OF HORIZONTAL STROKE;Sm;0;ON;;;;;Y;;;;;
+22FD;CONTAINS WITH OVERBAR;Sm;0;ON;;;;;Y;;;;;
+22FE;SMALL CONTAINS WITH OVERBAR;Sm;0;ON;;;;;Y;;;;;
+22FF;Z NOTATION BAG MEMBERSHIP;Sm;0;ON;;;;;Y;;;;;
+2300;DIAMETER SIGN;So;0;ON;;;;;N;;;;;
+2301;ELECTRIC ARROW;So;0;ON;;;;;N;;;;;
+2302;HOUSE;So;0;ON;;;;;N;;;;;
+2303;UP ARROWHEAD;So;0;ON;;;;;N;;;;;
+2304;DOWN ARROWHEAD;So;0;ON;;;;;N;;;;;
+2305;PROJECTIVE;So;0;ON;;;;;N;;;;;
+2306;PERSPECTIVE;So;0;ON;;;;;N;;;;;
+2307;WAVY LINE;So;0;ON;;;;;N;;;;;
+2308;LEFT CEILING;Sm;0;ON;;;;;Y;;;;;
+2309;RIGHT CEILING;Sm;0;ON;;;;;Y;;;;;
+230A;LEFT FLOOR;Sm;0;ON;;;;;Y;;;;;
+230B;RIGHT FLOOR;Sm;0;ON;;;;;Y;;;;;
+230C;BOTTOM RIGHT CROP;So;0;ON;;;;;N;;;;;
+230D;BOTTOM LEFT CROP;So;0;ON;;;;;N;;;;;
+230E;TOP RIGHT CROP;So;0;ON;;;;;N;;;;;
+230F;TOP LEFT CROP;So;0;ON;;;;;N;;;;;
+2310;REVERSED NOT SIGN;So;0;ON;;;;;N;;;;;
+2311;SQUARE LOZENGE;So;0;ON;;;;;N;;;;;
+2312;ARC;So;0;ON;;;;;N;;;;;
+2313;SEGMENT;So;0;ON;;;;;N;;;;;
+2314;SECTOR;So;0;ON;;;;;N;;;;;
+2315;TELEPHONE RECORDER;So;0;ON;;;;;N;;;;;
+2316;POSITION INDICATOR;So;0;ON;;;;;N;;;;;
+2317;VIEWDATA SQUARE;So;0;ON;;;;;N;;;;;
+2318;PLACE OF INTEREST SIGN;So;0;ON;;;;;N;COMMAND KEY;;;;
+2319;TURNED NOT SIGN;So;0;ON;;;;;N;;;;;
+231A;WATCH;So;0;ON;;;;;N;;;;;
+231B;HOURGLASS;So;0;ON;;;;;N;;;;;
+231C;TOP LEFT CORNER;So;0;ON;;;;;N;;;;;
+231D;TOP RIGHT CORNER;So;0;ON;;;;;N;;;;;
+231E;BOTTOM LEFT CORNER;So;0;ON;;;;;N;;;;;
+231F;BOTTOM RIGHT CORNER;So;0;ON;;;;;N;;;;;
+2320;TOP HALF INTEGRAL;Sm;0;ON;;;;;Y;;;;;
+2321;BOTTOM HALF INTEGRAL;Sm;0;ON;;;;;Y;;;;;
+2322;FROWN;So;0;ON;;;;;N;;;;;
+2323;SMILE;So;0;ON;;;;;N;;;;;
+2324;UP ARROWHEAD BETWEEN TWO HORIZONTAL BARS;So;0;ON;;;;;N;ENTER KEY;;;;
+2325;OPTION KEY;So;0;ON;;;;;N;;;;;
+2326;ERASE TO THE RIGHT;So;0;ON;;;;;N;DELETE TO THE RIGHT KEY;;;;
+2327;X IN A RECTANGLE BOX;So;0;ON;;;;;N;CLEAR KEY;;;;
+2328;KEYBOARD;So;0;ON;;;;;N;;;;;
+2329;LEFT-POINTING ANGLE BRACKET;Ps;0;ON;3008;;;;Y;BRA;;;;
+232A;RIGHT-POINTING ANGLE BRACKET;Pe;0;ON;3009;;;;Y;KET;;;;
+232B;ERASE TO THE LEFT;So;0;ON;;;;;N;DELETE TO THE LEFT KEY;;;;
+232C;BENZENE RING;So;0;ON;;;;;N;;;;;
+232D;CYLINDRICITY;So;0;ON;;;;;N;;;;;
+232E;ALL AROUND-PROFILE;So;0;ON;;;;;N;;;;;
+232F;SYMMETRY;So;0;ON;;;;;N;;;;;
+2330;TOTAL RUNOUT;So;0;ON;;;;;N;;;;;
+2331;DIMENSION ORIGIN;So;0;ON;;;;;N;;;;;
+2332;CONICAL TAPER;So;0;ON;;;;;N;;;;;
+2333;SLOPE;So;0;ON;;;;;N;;;;;
+2334;COUNTERBORE;So;0;ON;;;;;N;;;;;
+2335;COUNTERSINK;So;0;ON;;;;;N;;;;;
+2336;APL FUNCTIONAL SYMBOL I-BEAM;So;0;L;;;;;N;;;;;
+2337;APL FUNCTIONAL SYMBOL SQUISH QUAD;So;0;L;;;;;N;;;;;
+2338;APL FUNCTIONAL SYMBOL QUAD EQUAL;So;0;L;;;;;N;;;;;
+2339;APL FUNCTIONAL SYMBOL QUAD DIVIDE;So;0;L;;;;;N;;;;;
+233A;APL FUNCTIONAL SYMBOL QUAD DIAMOND;So;0;L;;;;;N;;;;;
+233B;APL FUNCTIONAL SYMBOL QUAD JOT;So;0;L;;;;;N;;;;;
+233C;APL FUNCTIONAL SYMBOL QUAD CIRCLE;So;0;L;;;;;N;;;;;
+233D;APL FUNCTIONAL SYMBOL CIRCLE STILE;So;0;L;;;;;N;;;;;
+233E;APL FUNCTIONAL SYMBOL CIRCLE JOT;So;0;L;;;;;N;;;;;
+233F;APL FUNCTIONAL SYMBOL SLASH BAR;So;0;L;;;;;N;;;;;
+2340;APL FUNCTIONAL SYMBOL BACKSLASH BAR;So;0;L;;;;;N;;;;;
+2341;APL FUNCTIONAL SYMBOL QUAD SLASH;So;0;L;;;;;N;;;;;
+2342;APL FUNCTIONAL SYMBOL QUAD BACKSLASH;So;0;L;;;;;N;;;;;
+2343;APL FUNCTIONAL SYMBOL QUAD LESS-THAN;So;0;L;;;;;N;;;;;
+2344;APL FUNCTIONAL SYMBOL QUAD GREATER-THAN;So;0;L;;;;;N;;;;;
+2345;APL FUNCTIONAL SYMBOL LEFTWARDS VANE;So;0;L;;;;;N;;;;;
+2346;APL FUNCTIONAL SYMBOL RIGHTWARDS VANE;So;0;L;;;;;N;;;;;
+2347;APL FUNCTIONAL SYMBOL QUAD LEFTWARDS ARROW;So;0;L;;;;;N;;;;;
+2348;APL FUNCTIONAL SYMBOL QUAD RIGHTWARDS ARROW;So;0;L;;;;;N;;;;;
+2349;APL FUNCTIONAL SYMBOL CIRCLE BACKSLASH;So;0;L;;;;;N;;;;;
+234A;APL FUNCTIONAL SYMBOL DOWN TACK UNDERBAR;So;0;L;;;;;N;;*;;;
+234B;APL FUNCTIONAL SYMBOL DELTA STILE;So;0;L;;;;;N;;;;;
+234C;APL FUNCTIONAL SYMBOL QUAD DOWN CARET;So;0;L;;;;;N;;;;;
+234D;APL FUNCTIONAL SYMBOL QUAD DELTA;So;0;L;;;;;N;;;;;
+234E;APL FUNCTIONAL SYMBOL DOWN TACK JOT;So;0;L;;;;;N;;*;;;
+234F;APL FUNCTIONAL SYMBOL UPWARDS VANE;So;0;L;;;;;N;;;;;
+2350;APL FUNCTIONAL SYMBOL QUAD UPWARDS ARROW;So;0;L;;;;;N;;;;;
+2351;APL FUNCTIONAL SYMBOL UP TACK OVERBAR;So;0;L;;;;;N;;*;;;
+2352;APL FUNCTIONAL SYMBOL DEL STILE;So;0;L;;;;;N;;;;;
+2353;APL FUNCTIONAL SYMBOL QUAD UP CARET;So;0;L;;;;;N;;;;;
+2354;APL FUNCTIONAL SYMBOL QUAD DEL;So;0;L;;;;;N;;;;;
+2355;APL FUNCTIONAL SYMBOL UP TACK JOT;So;0;L;;;;;N;;*;;;
+2356;APL FUNCTIONAL SYMBOL DOWNWARDS VANE;So;0;L;;;;;N;;;;;
+2357;APL FUNCTIONAL SYMBOL QUAD DOWNWARDS ARROW;So;0;L;;;;;N;;;;;
+2358;APL FUNCTIONAL SYMBOL QUOTE UNDERBAR;So;0;L;;;;;N;;;;;
+2359;APL FUNCTIONAL SYMBOL DELTA UNDERBAR;So;0;L;;;;;N;;;;;
+235A;APL FUNCTIONAL SYMBOL DIAMOND UNDERBAR;So;0;L;;;;;N;;;;;
+235B;APL FUNCTIONAL SYMBOL JOT UNDERBAR;So;0;L;;;;;N;;;;;
+235C;APL FUNCTIONAL SYMBOL CIRCLE UNDERBAR;So;0;L;;;;;N;;;;;
+235D;APL FUNCTIONAL SYMBOL UP SHOE JOT;So;0;L;;;;;N;;;;;
+235E;APL FUNCTIONAL SYMBOL QUOTE QUAD;So;0;L;;;;;N;;;;;
+235F;APL FUNCTIONAL SYMBOL CIRCLE STAR;So;0;L;;;;;N;;;;;
+2360;APL FUNCTIONAL SYMBOL QUAD COLON;So;0;L;;;;;N;;;;;
+2361;APL FUNCTIONAL SYMBOL UP TACK DIAERESIS;So;0;L;;;;;N;;*;;;
+2362;APL FUNCTIONAL SYMBOL DEL DIAERESIS;So;0;L;;;;;N;;;;;
+2363;APL FUNCTIONAL SYMBOL STAR DIAERESIS;So;0;L;;;;;N;;;;;
+2364;APL FUNCTIONAL SYMBOL JOT DIAERESIS;So;0;L;;;;;N;;;;;
+2365;APL FUNCTIONAL SYMBOL CIRCLE DIAERESIS;So;0;L;;;;;N;;;;;
+2366;APL FUNCTIONAL SYMBOL DOWN SHOE STILE;So;0;L;;;;;N;;;;;
+2367;APL FUNCTIONAL SYMBOL LEFT SHOE STILE;So;0;L;;;;;N;;;;;
+2368;APL FUNCTIONAL SYMBOL TILDE DIAERESIS;So;0;L;;;;;N;;;;;
+2369;APL FUNCTIONAL SYMBOL GREATER-THAN DIAERESIS;So;0;L;;;;;N;;;;;
+236A;APL FUNCTIONAL SYMBOL COMMA BAR;So;0;L;;;;;N;;;;;
+236B;APL FUNCTIONAL SYMBOL DEL TILDE;So;0;L;;;;;N;;;;;
+236C;APL FUNCTIONAL SYMBOL ZILDE;So;0;L;;;;;N;;;;;
+236D;APL FUNCTIONAL SYMBOL STILE TILDE;So;0;L;;;;;N;;;;;
+236E;APL FUNCTIONAL SYMBOL SEMICOLON UNDERBAR;So;0;L;;;;;N;;;;;
+236F;APL FUNCTIONAL SYMBOL QUAD NOT EQUAL;So;0;L;;;;;N;;;;;
+2370;APL FUNCTIONAL SYMBOL QUAD QUESTION;So;0;L;;;;;N;;;;;
+2371;APL FUNCTIONAL SYMBOL DOWN CARET TILDE;So;0;L;;;;;N;;;;;
+2372;APL FUNCTIONAL SYMBOL UP CARET TILDE;So;0;L;;;;;N;;;;;
+2373;APL FUNCTIONAL SYMBOL IOTA;So;0;L;;;;;N;;;;;
+2374;APL FUNCTIONAL SYMBOL RHO;So;0;L;;;;;N;;;;;
+2375;APL FUNCTIONAL SYMBOL OMEGA;So;0;L;;;;;N;;;;;
+2376;APL FUNCTIONAL SYMBOL ALPHA UNDERBAR;So;0;L;;;;;N;;;;;
+2377;APL FUNCTIONAL SYMBOL EPSILON UNDERBAR;So;0;L;;;;;N;;;;;
+2378;APL FUNCTIONAL SYMBOL IOTA UNDERBAR;So;0;L;;;;;N;;;;;
+2379;APL FUNCTIONAL SYMBOL OMEGA UNDERBAR;So;0;L;;;;;N;;;;;
+237A;APL FUNCTIONAL SYMBOL ALPHA;So;0;L;;;;;N;;;;;
+237B;NOT CHECK MARK;So;0;ON;;;;;N;;;;;
+237C;RIGHT ANGLE WITH DOWNWARDS ZIGZAG ARROW;Sm;0;ON;;;;;N;;;;;
+237D;SHOULDERED OPEN BOX;So;0;ON;;;;;N;;;;;
+237E;BELL SYMBOL;So;0;ON;;;;;N;;;;;
+237F;VERTICAL LINE WITH MIDDLE DOT;So;0;ON;;;;;N;;;;;
+2380;INSERTION SYMBOL;So;0;ON;;;;;N;;;;;
+2381;CONTINUOUS UNDERLINE SYMBOL;So;0;ON;;;;;N;;;;;
+2382;DISCONTINUOUS UNDERLINE SYMBOL;So;0;ON;;;;;N;;;;;
+2383;EMPHASIS SYMBOL;So;0;ON;;;;;N;;;;;
+2384;COMPOSITION SYMBOL;So;0;ON;;;;;N;;;;;
+2385;WHITE SQUARE WITH CENTRE VERTICAL LINE;So;0;ON;;;;;N;;;;;
+2386;ENTER SYMBOL;So;0;ON;;;;;N;;;;;
+2387;ALTERNATIVE KEY SYMBOL;So;0;ON;;;;;N;;;;;
+2388;HELM SYMBOL;So;0;ON;;;;;N;;;;;
+2389;CIRCLED HORIZONTAL BAR WITH NOTCH;So;0;ON;;;;;N;;pause;;;
+238A;CIRCLED TRIANGLE DOWN;So;0;ON;;;;;N;;break;;;
+238B;BROKEN CIRCLE WITH NORTHWEST ARROW;So;0;ON;;;;;N;;escape;;;
+238C;UNDO SYMBOL;So;0;ON;;;;;N;;;;;
+238D;MONOSTABLE SYMBOL;So;0;ON;;;;;N;;;;;
+238E;HYSTERESIS SYMBOL;So;0;ON;;;;;N;;;;;
+238F;OPEN-CIRCUIT-OUTPUT H-TYPE SYMBOL;So;0;ON;;;;;N;;;;;
+2390;OPEN-CIRCUIT-OUTPUT L-TYPE SYMBOL;So;0;ON;;;;;N;;;;;
+2391;PASSIVE-PULL-DOWN-OUTPUT SYMBOL;So;0;ON;;;;;N;;;;;
+2392;PASSIVE-PULL-UP-OUTPUT SYMBOL;So;0;ON;;;;;N;;;;;
+2393;DIRECT CURRENT SYMBOL FORM TWO;So;0;ON;;;;;N;;;;;
+2394;SOFTWARE-FUNCTION SYMBOL;So;0;ON;;;;;N;;;;;
+2395;APL FUNCTIONAL SYMBOL QUAD;So;0;L;;;;;N;;;;;
+2396;DECIMAL SEPARATOR KEY SYMBOL;So;0;ON;;;;;N;;;;;
+2397;PREVIOUS PAGE;So;0;ON;;;;;N;;;;;
+2398;NEXT PAGE;So;0;ON;;;;;N;;;;;
+2399;PRINT SCREEN SYMBOL;So;0;ON;;;;;N;;;;;
+239A;CLEAR SCREEN SYMBOL;So;0;ON;;;;;N;;;;;
+239B;LEFT PARENTHESIS UPPER HOOK;Sm;0;ON;;;;;N;;;;;
+239C;LEFT PARENTHESIS EXTENSION;Sm;0;ON;;;;;N;;;;;
+239D;LEFT PARENTHESIS LOWER HOOK;Sm;0;ON;;;;;N;;;;;
+239E;RIGHT PARENTHESIS UPPER HOOK;Sm;0;ON;;;;;N;;;;;
+239F;RIGHT PARENTHESIS EXTENSION;Sm;0;ON;;;;;N;;;;;
+23A0;RIGHT PARENTHESIS LOWER HOOK;Sm;0;ON;;;;;N;;;;;
+23A1;LEFT SQUARE BRACKET UPPER CORNER;Sm;0;ON;;;;;N;;;;;
+23A2;LEFT SQUARE BRACKET EXTENSION;Sm;0;ON;;;;;N;;;;;
+23A3;LEFT SQUARE BRACKET LOWER CORNER;Sm;0;ON;;;;;N;;;;;
+23A4;RIGHT SQUARE BRACKET UPPER CORNER;Sm;0;ON;;;;;N;;;;;
+23A5;RIGHT SQUARE BRACKET EXTENSION;Sm;0;ON;;;;;N;;;;;
+23A6;RIGHT SQUARE BRACKET LOWER CORNER;Sm;0;ON;;;;;N;;;;;
+23A7;LEFT CURLY BRACKET UPPER HOOK;Sm;0;ON;;;;;N;;;;;
+23A8;LEFT CURLY BRACKET MIDDLE PIECE;Sm;0;ON;;;;;N;;;;;
+23A9;LEFT CURLY BRACKET LOWER HOOK;Sm;0;ON;;;;;N;;;;;
+23AA;CURLY BRACKET EXTENSION;Sm;0;ON;;;;;N;;;;;
+23AB;RIGHT CURLY BRACKET UPPER HOOK;Sm;0;ON;;;;;N;;;;;
+23AC;RIGHT CURLY BRACKET MIDDLE PIECE;Sm;0;ON;;;;;N;;;;;
+23AD;RIGHT CURLY BRACKET LOWER HOOK;Sm;0;ON;;;;;N;;;;;
+23AE;INTEGRAL EXTENSION;Sm;0;ON;;;;;N;;;;;
+23AF;HORIZONTAL LINE EXTENSION;Sm;0;ON;;;;;N;;;;;
+23B0;UPPER LEFT OR LOWER RIGHT CURLY BRACKET SECTION;Sm;0;ON;;;;;N;;;;;
+23B1;UPPER RIGHT OR LOWER LEFT CURLY BRACKET SECTION;Sm;0;ON;;;;;N;;;;;
+23B2;SUMMATION TOP;Sm;0;ON;;;;;N;;;;;
+23B3;SUMMATION BOTTOM;Sm;0;ON;;;;;N;;;;;
+23B4;TOP SQUARE BRACKET;Ps;0;ON;;;;;N;;;;;
+23B5;BOTTOM SQUARE BRACKET;Pe;0;ON;;;;;N;;;;;
+23B6;BOTTOM SQUARE BRACKET OVER TOP SQUARE BRACKET;Po;0;ON;;;;;N;;;;;
+23B7;RADICAL SYMBOL BOTTOM;So;0;ON;;;;;N;;;;;
+23B8;LEFT VERTICAL BOX LINE;So;0;ON;;;;;N;;;;;
+23B9;RIGHT VERTICAL BOX LINE;So;0;ON;;;;;N;;;;;
+23BA;HORIZONTAL SCAN LINE-1;So;0;ON;;;;;N;;;;;
+23BB;HORIZONTAL SCAN LINE-3;So;0;ON;;;;;N;;;;;
+23BC;HORIZONTAL SCAN LINE-7;So;0;ON;;;;;N;;;;;
+23BD;HORIZONTAL SCAN LINE-9;So;0;ON;;;;;N;;;;;
+23BE;DENTISTRY SYMBOL LIGHT VERTICAL AND TOP RIGHT;So;0;ON;;;;;N;;;;;
+23BF;DENTISTRY SYMBOL LIGHT VERTICAL AND BOTTOM RIGHT;So;0;ON;;;;;N;;;;;
+23C0;DENTISTRY SYMBOL LIGHT VERTICAL WITH CIRCLE;So;0;ON;;;;;N;;;;;
+23C1;DENTISTRY SYMBOL LIGHT DOWN AND HORIZONTAL WITH CIRCLE;So;0;ON;;;;;N;;;;;
+23C2;DENTISTRY SYMBOL LIGHT UP AND HORIZONTAL WITH CIRCLE;So;0;ON;;;;;N;;;;;
+23C3;DENTISTRY SYMBOL LIGHT VERTICAL WITH TRIANGLE;So;0;ON;;;;;N;;;;;
+23C4;DENTISTRY SYMBOL LIGHT DOWN AND HORIZONTAL WITH TRIANGLE;So;0;ON;;;;;N;;;;;
+23C5;DENTISTRY SYMBOL LIGHT UP AND HORIZONTAL WITH TRIANGLE;So;0;ON;;;;;N;;;;;
+23C6;DENTISTRY SYMBOL LIGHT VERTICAL AND WAVE;So;0;ON;;;;;N;;;;;
+23C7;DENTISTRY SYMBOL LIGHT DOWN AND HORIZONTAL WITH WAVE;So;0;ON;;;;;N;;;;;
+23C8;DENTISTRY SYMBOL LIGHT UP AND HORIZONTAL WITH WAVE;So;0;ON;;;;;N;;;;;
+23C9;DENTISTRY SYMBOL LIGHT DOWN AND HORIZONTAL;So;0;ON;;;;;N;;;;;
+23CA;DENTISTRY SYMBOL LIGHT UP AND HORIZONTAL;So;0;ON;;;;;N;;;;;
+23CB;DENTISTRY SYMBOL LIGHT VERTICAL AND TOP LEFT;So;0;ON;;;;;N;;;;;
+23CC;DENTISTRY SYMBOL LIGHT VERTICAL AND BOTTOM LEFT;So;0;ON;;;;;N;;;;;
+23CD;SQUARE FOOT;So;0;ON;;;;;N;;;;;
+23CE;RETURN SYMBOL;So;0;ON;;;;;N;;;;;
+23CF;EJECT SYMBOL;So;0;ON;;;;;N;;;;;
+23D0;VERTICAL LINE EXTENSION;So;0;ON;;;;;N;;;;;
+2400;SYMBOL FOR NULL;So;0;ON;;;;;N;GRAPHIC FOR NULL;;;;
+2401;SYMBOL FOR START OF HEADING;So;0;ON;;;;;N;GRAPHIC FOR START OF HEADING;;;;
+2402;SYMBOL FOR START OF TEXT;So;0;ON;;;;;N;GRAPHIC FOR START OF TEXT;;;;
+2403;SYMBOL FOR END OF TEXT;So;0;ON;;;;;N;GRAPHIC FOR END OF TEXT;;;;
+2404;SYMBOL FOR END OF TRANSMISSION;So;0;ON;;;;;N;GRAPHIC FOR END OF TRANSMISSION;;;;
+2405;SYMBOL FOR ENQUIRY;So;0;ON;;;;;N;GRAPHIC FOR ENQUIRY;;;;
+2406;SYMBOL FOR ACKNOWLEDGE;So;0;ON;;;;;N;GRAPHIC FOR ACKNOWLEDGE;;;;
+2407;SYMBOL FOR BELL;So;0;ON;;;;;N;GRAPHIC FOR BELL;;;;
+2408;SYMBOL FOR BACKSPACE;So;0;ON;;;;;N;GRAPHIC FOR BACKSPACE;;;;
+2409;SYMBOL FOR HORIZONTAL TABULATION;So;0;ON;;;;;N;GRAPHIC FOR HORIZONTAL TABULATION;;;;
+240A;SYMBOL FOR LINE FEED;So;0;ON;;;;;N;GRAPHIC FOR LINE FEED;;;;
+240B;SYMBOL FOR VERTICAL TABULATION;So;0;ON;;;;;N;GRAPHIC FOR VERTICAL TABULATION;;;;
+240C;SYMBOL FOR FORM FEED;So;0;ON;;;;;N;GRAPHIC FOR FORM FEED;;;;
+240D;SYMBOL FOR CARRIAGE RETURN;So;0;ON;;;;;N;GRAPHIC FOR CARRIAGE RETURN;;;;
+240E;SYMBOL FOR SHIFT OUT;So;0;ON;;;;;N;GRAPHIC FOR SHIFT OUT;;;;
+240F;SYMBOL FOR SHIFT IN;So;0;ON;;;;;N;GRAPHIC FOR SHIFT IN;;;;
+2410;SYMBOL FOR DATA LINK ESCAPE;So;0;ON;;;;;N;GRAPHIC FOR DATA LINK ESCAPE;;;;
+2411;SYMBOL FOR DEVICE CONTROL ONE;So;0;ON;;;;;N;GRAPHIC FOR DEVICE CONTROL ONE;;;;
+2412;SYMBOL FOR DEVICE CONTROL TWO;So;0;ON;;;;;N;GRAPHIC FOR DEVICE CONTROL TWO;;;;
+2413;SYMBOL FOR DEVICE CONTROL THREE;So;0;ON;;;;;N;GRAPHIC FOR DEVICE CONTROL THREE;;;;
+2414;SYMBOL FOR DEVICE CONTROL FOUR;So;0;ON;;;;;N;GRAPHIC FOR DEVICE CONTROL FOUR;;;;
+2415;SYMBOL FOR NEGATIVE ACKNOWLEDGE;So;0;ON;;;;;N;GRAPHIC FOR NEGATIVE ACKNOWLEDGE;;;;
+2416;SYMBOL FOR SYNCHRONOUS IDLE;So;0;ON;;;;;N;GRAPHIC FOR SYNCHRONOUS IDLE;;;;
+2417;SYMBOL FOR END OF TRANSMISSION BLOCK;So;0;ON;;;;;N;GRAPHIC FOR END OF TRANSMISSION BLOCK;;;;
+2418;SYMBOL FOR CANCEL;So;0;ON;;;;;N;GRAPHIC FOR CANCEL;;;;
+2419;SYMBOL FOR END OF MEDIUM;So;0;ON;;;;;N;GRAPHIC FOR END OF MEDIUM;;;;
+241A;SYMBOL FOR SUBSTITUTE;So;0;ON;;;;;N;GRAPHIC FOR SUBSTITUTE;;;;
+241B;SYMBOL FOR ESCAPE;So;0;ON;;;;;N;GRAPHIC FOR ESCAPE;;;;
+241C;SYMBOL FOR FILE SEPARATOR;So;0;ON;;;;;N;GRAPHIC FOR FILE SEPARATOR;;;;
+241D;SYMBOL FOR GROUP SEPARATOR;So;0;ON;;;;;N;GRAPHIC FOR GROUP SEPARATOR;;;;
+241E;SYMBOL FOR RECORD SEPARATOR;So;0;ON;;;;;N;GRAPHIC FOR RECORD SEPARATOR;;;;
+241F;SYMBOL FOR UNIT SEPARATOR;So;0;ON;;;;;N;GRAPHIC FOR UNIT SEPARATOR;;;;
+2420;SYMBOL FOR SPACE;So;0;ON;;;;;N;GRAPHIC FOR SPACE;;;;
+2421;SYMBOL FOR DELETE;So;0;ON;;;;;N;GRAPHIC FOR DELETE;;;;
+2422;BLANK SYMBOL;So;0;ON;;;;;N;BLANK;;;;
+2423;OPEN BOX;So;0;ON;;;;;N;;;;;
+2424;SYMBOL FOR NEWLINE;So;0;ON;;;;;N;GRAPHIC FOR NEWLINE;;;;
+2425;SYMBOL FOR DELETE FORM TWO;So;0;ON;;;;;N;;;;;
+2426;SYMBOL FOR SUBSTITUTE FORM TWO;So;0;ON;;;;;N;;;;;
+2440;OCR HOOK;So;0;ON;;;;;N;;;;;
+2441;OCR CHAIR;So;0;ON;;;;;N;;;;;
+2442;OCR FORK;So;0;ON;;;;;N;;;;;
+2443;OCR INVERTED FORK;So;0;ON;;;;;N;;;;;
+2444;OCR BELT BUCKLE;So;0;ON;;;;;N;;;;;
+2445;OCR BOW TIE;So;0;ON;;;;;N;;;;;
+2446;OCR BRANCH BANK IDENTIFICATION;So;0;ON;;;;;N;;;;;
+2447;OCR AMOUNT OF CHECK;So;0;ON;;;;;N;;;;;
+2448;OCR DASH;So;0;ON;;;;;N;;;;;
+2449;OCR CUSTOMER ACCOUNT NUMBER;So;0;ON;;;;;N;;;;;
+244A;OCR DOUBLE BACKSLASH;So;0;ON;;;;;N;;;;;
+2460;CIRCLED DIGIT ONE;No;0;ON;<circle> 0031;;1;1;N;;;;;
+2461;CIRCLED DIGIT TWO;No;0;ON;<circle> 0032;;2;2;N;;;;;
+2462;CIRCLED DIGIT THREE;No;0;ON;<circle> 0033;;3;3;N;;;;;
+2463;CIRCLED DIGIT FOUR;No;0;ON;<circle> 0034;;4;4;N;;;;;
+2464;CIRCLED DIGIT FIVE;No;0;ON;<circle> 0035;;5;5;N;;;;;
+2465;CIRCLED DIGIT SIX;No;0;ON;<circle> 0036;;6;6;N;;;;;
+2466;CIRCLED DIGIT SEVEN;No;0;ON;<circle> 0037;;7;7;N;;;;;
+2467;CIRCLED DIGIT EIGHT;No;0;ON;<circle> 0038;;8;8;N;;;;;
+2468;CIRCLED DIGIT NINE;No;0;ON;<circle> 0039;;9;9;N;;;;;
+2469;CIRCLED NUMBER TEN;No;0;ON;<circle> 0031 0030;;;10;N;;;;;
+246A;CIRCLED NUMBER ELEVEN;No;0;ON;<circle> 0031 0031;;;11;N;;;;;
+246B;CIRCLED NUMBER TWELVE;No;0;ON;<circle> 0031 0032;;;12;N;;;;;
+246C;CIRCLED NUMBER THIRTEEN;No;0;ON;<circle> 0031 0033;;;13;N;;;;;
+246D;CIRCLED NUMBER FOURTEEN;No;0;ON;<circle> 0031 0034;;;14;N;;;;;
+246E;CIRCLED NUMBER FIFTEEN;No;0;ON;<circle> 0031 0035;;;15;N;;;;;
+246F;CIRCLED NUMBER SIXTEEN;No;0;ON;<circle> 0031 0036;;;16;N;;;;;
+2470;CIRCLED NUMBER SEVENTEEN;No;0;ON;<circle> 0031 0037;;;17;N;;;;;
+2471;CIRCLED NUMBER EIGHTEEN;No;0;ON;<circle> 0031 0038;;;18;N;;;;;
+2472;CIRCLED NUMBER NINETEEN;No;0;ON;<circle> 0031 0039;;;19;N;;;;;
+2473;CIRCLED NUMBER TWENTY;No;0;ON;<circle> 0032 0030;;;20;N;;;;;
+2474;PARENTHESIZED DIGIT ONE;No;0;ON;<compat> 0028 0031 0029;;1;1;N;;;;;
+2475;PARENTHESIZED DIGIT TWO;No;0;ON;<compat> 0028 0032 0029;;2;2;N;;;;;
+2476;PARENTHESIZED DIGIT THREE;No;0;ON;<compat> 0028 0033 0029;;3;3;N;;;;;
+2477;PARENTHESIZED DIGIT FOUR;No;0;ON;<compat> 0028 0034 0029;;4;4;N;;;;;
+2478;PARENTHESIZED DIGIT FIVE;No;0;ON;<compat> 0028 0035 0029;;5;5;N;;;;;
+2479;PARENTHESIZED DIGIT SIX;No;0;ON;<compat> 0028 0036 0029;;6;6;N;;;;;
+247A;PARENTHESIZED DIGIT SEVEN;No;0;ON;<compat> 0028 0037 0029;;7;7;N;;;;;
+247B;PARENTHESIZED DIGIT EIGHT;No;0;ON;<compat> 0028 0038 0029;;8;8;N;;;;;
+247C;PARENTHESIZED DIGIT NINE;No;0;ON;<compat> 0028 0039 0029;;9;9;N;;;;;
+247D;PARENTHESIZED NUMBER TEN;No;0;ON;<compat> 0028 0031 0030 0029;;;10;N;;;;;
+247E;PARENTHESIZED NUMBER ELEVEN;No;0;ON;<compat> 0028 0031 0031 0029;;;11;N;;;;;
+247F;PARENTHESIZED NUMBER TWELVE;No;0;ON;<compat> 0028 0031 0032 0029;;;12;N;;;;;
+2480;PARENTHESIZED NUMBER THIRTEEN;No;0;ON;<compat> 0028 0031 0033 0029;;;13;N;;;;;
+2481;PARENTHESIZED NUMBER FOURTEEN;No;0;ON;<compat> 0028 0031 0034 0029;;;14;N;;;;;
+2482;PARENTHESIZED NUMBER FIFTEEN;No;0;ON;<compat> 0028 0031 0035 0029;;;15;N;;;;;
+2483;PARENTHESIZED NUMBER SIXTEEN;No;0;ON;<compat> 0028 0031 0036 0029;;;16;N;;;;;
+2484;PARENTHESIZED NUMBER SEVENTEEN;No;0;ON;<compat> 0028 0031 0037 0029;;;17;N;;;;;
+2485;PARENTHESIZED NUMBER EIGHTEEN;No;0;ON;<compat> 0028 0031 0038 0029;;;18;N;;;;;
+2486;PARENTHESIZED NUMBER NINETEEN;No;0;ON;<compat> 0028 0031 0039 0029;;;19;N;;;;;
+2487;PARENTHESIZED NUMBER TWENTY;No;0;ON;<compat> 0028 0032 0030 0029;;;20;N;;;;;
+2488;DIGIT ONE FULL STOP;No;0;EN;<compat> 0031 002E;;1;1;N;DIGIT ONE PERIOD;;;;
+2489;DIGIT TWO FULL STOP;No;0;EN;<compat> 0032 002E;;2;2;N;DIGIT TWO PERIOD;;;;
+248A;DIGIT THREE FULL STOP;No;0;EN;<compat> 0033 002E;;3;3;N;DIGIT THREE PERIOD;;;;
+248B;DIGIT FOUR FULL STOP;No;0;EN;<compat> 0034 002E;;4;4;N;DIGIT FOUR PERIOD;;;;
+248C;DIGIT FIVE FULL STOP;No;0;EN;<compat> 0035 002E;;5;5;N;DIGIT FIVE PERIOD;;;;
+248D;DIGIT SIX FULL STOP;No;0;EN;<compat> 0036 002E;;6;6;N;DIGIT SIX PERIOD;;;;
+248E;DIGIT SEVEN FULL STOP;No;0;EN;<compat> 0037 002E;;7;7;N;DIGIT SEVEN PERIOD;;;;
+248F;DIGIT EIGHT FULL STOP;No;0;EN;<compat> 0038 002E;;8;8;N;DIGIT EIGHT PERIOD;;;;
+2490;DIGIT NINE FULL STOP;No;0;EN;<compat> 0039 002E;;9;9;N;DIGIT NINE PERIOD;;;;
+2491;NUMBER TEN FULL STOP;No;0;EN;<compat> 0031 0030 002E;;;10;N;NUMBER TEN PERIOD;;;;
+2492;NUMBER ELEVEN FULL STOP;No;0;EN;<compat> 0031 0031 002E;;;11;N;NUMBER ELEVEN PERIOD;;;;
+2493;NUMBER TWELVE FULL STOP;No;0;EN;<compat> 0031 0032 002E;;;12;N;NUMBER TWELVE PERIOD;;;;
+2494;NUMBER THIRTEEN FULL STOP;No;0;EN;<compat> 0031 0033 002E;;;13;N;NUMBER THIRTEEN PERIOD;;;;
+2495;NUMBER FOURTEEN FULL STOP;No;0;EN;<compat> 0031 0034 002E;;;14;N;NUMBER FOURTEEN PERIOD;;;;
+2496;NUMBER FIFTEEN FULL STOP;No;0;EN;<compat> 0031 0035 002E;;;15;N;NUMBER FIFTEEN PERIOD;;;;
+2497;NUMBER SIXTEEN FULL STOP;No;0;EN;<compat> 0031 0036 002E;;;16;N;NUMBER SIXTEEN PERIOD;;;;
+2498;NUMBER SEVENTEEN FULL STOP;No;0;EN;<compat> 0031 0037 002E;;;17;N;NUMBER SEVENTEEN PERIOD;;;;
+2499;NUMBER EIGHTEEN FULL STOP;No;0;EN;<compat> 0031 0038 002E;;;18;N;NUMBER EIGHTEEN PERIOD;;;;
+249A;NUMBER NINETEEN FULL STOP;No;0;EN;<compat> 0031 0039 002E;;;19;N;NUMBER NINETEEN PERIOD;;;;
+249B;NUMBER TWENTY FULL STOP;No;0;EN;<compat> 0032 0030 002E;;;20;N;NUMBER TWENTY PERIOD;;;;
+249C;PARENTHESIZED LATIN SMALL LETTER A;So;0;L;<compat> 0028 0061 0029;;;;N;;;;;
+249D;PARENTHESIZED LATIN SMALL LETTER B;So;0;L;<compat> 0028 0062 0029;;;;N;;;;;
+249E;PARENTHESIZED LATIN SMALL LETTER C;So;0;L;<compat> 0028 0063 0029;;;;N;;;;;
+249F;PARENTHESIZED LATIN SMALL LETTER D;So;0;L;<compat> 0028 0064 0029;;;;N;;;;;
+24A0;PARENTHESIZED LATIN SMALL LETTER E;So;0;L;<compat> 0028 0065 0029;;;;N;;;;;
+24A1;PARENTHESIZED LATIN SMALL LETTER F;So;0;L;<compat> 0028 0066 0029;;;;N;;;;;
+24A2;PARENTHESIZED LATIN SMALL LETTER G;So;0;L;<compat> 0028 0067 0029;;;;N;;;;;
+24A3;PARENTHESIZED LATIN SMALL LETTER H;So;0;L;<compat> 0028 0068 0029;;;;N;;;;;
+24A4;PARENTHESIZED LATIN SMALL LETTER I;So;0;L;<compat> 0028 0069 0029;;;;N;;;;;
+24A5;PARENTHESIZED LATIN SMALL LETTER J;So;0;L;<compat> 0028 006A 0029;;;;N;;;;;
+24A6;PARENTHESIZED LATIN SMALL LETTER K;So;0;L;<compat> 0028 006B 0029;;;;N;;;;;
+24A7;PARENTHESIZED LATIN SMALL LETTER L;So;0;L;<compat> 0028 006C 0029;;;;N;;;;;
+24A8;PARENTHESIZED LATIN SMALL LETTER M;So;0;L;<compat> 0028 006D 0029;;;;N;;;;;
+24A9;PARENTHESIZED LATIN SMALL LETTER N;So;0;L;<compat> 0028 006E 0029;;;;N;;;;;
+24AA;PARENTHESIZED LATIN SMALL LETTER O;So;0;L;<compat> 0028 006F 0029;;;;N;;;;;
+24AB;PARENTHESIZED LATIN SMALL LETTER P;So;0;L;<compat> 0028 0070 0029;;;;N;;;;;
+24AC;PARENTHESIZED LATIN SMALL LETTER Q;So;0;L;<compat> 0028 0071 0029;;;;N;;;;;
+24AD;PARENTHESIZED LATIN SMALL LETTER R;So;0;L;<compat> 0028 0072 0029;;;;N;;;;;
+24AE;PARENTHESIZED LATIN SMALL LETTER S;So;0;L;<compat> 0028 0073 0029;;;;N;;;;;
+24AF;PARENTHESIZED LATIN SMALL LETTER T;So;0;L;<compat> 0028 0074 0029;;;;N;;;;;
+24B0;PARENTHESIZED LATIN SMALL LETTER U;So;0;L;<compat> 0028 0075 0029;;;;N;;;;;
+24B1;PARENTHESIZED LATIN SMALL LETTER V;So;0;L;<compat> 0028 0076 0029;;;;N;;;;;
+24B2;PARENTHESIZED LATIN SMALL LETTER W;So;0;L;<compat> 0028 0077 0029;;;;N;;;;;
+24B3;PARENTHESIZED LATIN SMALL LETTER X;So;0;L;<compat> 0028 0078 0029;;;;N;;;;;
+24B4;PARENTHESIZED LATIN SMALL LETTER Y;So;0;L;<compat> 0028 0079 0029;;;;N;;;;;
+24B5;PARENTHESIZED LATIN SMALL LETTER Z;So;0;L;<compat> 0028 007A 0029;;;;N;;;;;
+24B6;CIRCLED LATIN CAPITAL LETTER A;So;0;L;<circle> 0041;;;;N;;;;24D0;
+24B7;CIRCLED LATIN CAPITAL LETTER B;So;0;L;<circle> 0042;;;;N;;;;24D1;
+24B8;CIRCLED LATIN CAPITAL LETTER C;So;0;L;<circle> 0043;;;;N;;;;24D2;
+24B9;CIRCLED LATIN CAPITAL LETTER D;So;0;L;<circle> 0044;;;;N;;;;24D3;
+24BA;CIRCLED LATIN CAPITAL LETTER E;So;0;L;<circle> 0045;;;;N;;;;24D4;
+24BB;CIRCLED LATIN CAPITAL LETTER F;So;0;L;<circle> 0046;;;;N;;;;24D5;
+24BC;CIRCLED LATIN CAPITAL LETTER G;So;0;L;<circle> 0047;;;;N;;;;24D6;
+24BD;CIRCLED LATIN CAPITAL LETTER H;So;0;L;<circle> 0048;;;;N;;;;24D7;
+24BE;CIRCLED LATIN CAPITAL LETTER I;So;0;L;<circle> 0049;;;;N;;;;24D8;
+24BF;CIRCLED LATIN CAPITAL LETTER J;So;0;L;<circle> 004A;;;;N;;;;24D9;
+24C0;CIRCLED LATIN CAPITAL LETTER K;So;0;L;<circle> 004B;;;;N;;;;24DA;
+24C1;CIRCLED LATIN CAPITAL LETTER L;So;0;L;<circle> 004C;;;;N;;;;24DB;
+24C2;CIRCLED LATIN CAPITAL LETTER M;So;0;L;<circle> 004D;;;;N;;;;24DC;
+24C3;CIRCLED LATIN CAPITAL LETTER N;So;0;L;<circle> 004E;;;;N;;;;24DD;
+24C4;CIRCLED LATIN CAPITAL LETTER O;So;0;L;<circle> 004F;;;;N;;;;24DE;
+24C5;CIRCLED LATIN CAPITAL LETTER P;So;0;L;<circle> 0050;;;;N;;;;24DF;
+24C6;CIRCLED LATIN CAPITAL LETTER Q;So;0;L;<circle> 0051;;;;N;;;;24E0;
+24C7;CIRCLED LATIN CAPITAL LETTER R;So;0;L;<circle> 0052;;;;N;;;;24E1;
+24C8;CIRCLED LATIN CAPITAL LETTER S;So;0;L;<circle> 0053;;;;N;;;;24E2;
+24C9;CIRCLED LATIN CAPITAL LETTER T;So;0;L;<circle> 0054;;;;N;;;;24E3;
+24CA;CIRCLED LATIN CAPITAL LETTER U;So;0;L;<circle> 0055;;;;N;;;;24E4;
+24CB;CIRCLED LATIN CAPITAL LETTER V;So;0;L;<circle> 0056;;;;N;;;;24E5;
+24CC;CIRCLED LATIN CAPITAL LETTER W;So;0;L;<circle> 0057;;;;N;;;;24E6;
+24CD;CIRCLED LATIN CAPITAL LETTER X;So;0;L;<circle> 0058;;;;N;;;;24E7;
+24CE;CIRCLED LATIN CAPITAL LETTER Y;So;0;L;<circle> 0059;;;;N;;;;24E8;
+24CF;CIRCLED LATIN CAPITAL LETTER Z;So;0;L;<circle> 005A;;;;N;;;;24E9;
+24D0;CIRCLED LATIN SMALL LETTER A;So;0;L;<circle> 0061;;;;N;;;24B6;;24B6
+24D1;CIRCLED LATIN SMALL LETTER B;So;0;L;<circle> 0062;;;;N;;;24B7;;24B7
+24D2;CIRCLED LATIN SMALL LETTER C;So;0;L;<circle> 0063;;;;N;;;24B8;;24B8
+24D3;CIRCLED LATIN SMALL LETTER D;So;0;L;<circle> 0064;;;;N;;;24B9;;24B9
+24D4;CIRCLED LATIN SMALL LETTER E;So;0;L;<circle> 0065;;;;N;;;24BA;;24BA
+24D5;CIRCLED LATIN SMALL LETTER F;So;0;L;<circle> 0066;;;;N;;;24BB;;24BB
+24D6;CIRCLED LATIN SMALL LETTER G;So;0;L;<circle> 0067;;;;N;;;24BC;;24BC
+24D7;CIRCLED LATIN SMALL LETTER H;So;0;L;<circle> 0068;;;;N;;;24BD;;24BD
+24D8;CIRCLED LATIN SMALL LETTER I;So;0;L;<circle> 0069;;;;N;;;24BE;;24BE
+24D9;CIRCLED LATIN SMALL LETTER J;So;0;L;<circle> 006A;;;;N;;;24BF;;24BF
+24DA;CIRCLED LATIN SMALL LETTER K;So;0;L;<circle> 006B;;;;N;;;24C0;;24C0
+24DB;CIRCLED LATIN SMALL LETTER L;So;0;L;<circle> 006C;;;;N;;;24C1;;24C1
+24DC;CIRCLED LATIN SMALL LETTER M;So;0;L;<circle> 006D;;;;N;;;24C2;;24C2
+24DD;CIRCLED LATIN SMALL LETTER N;So;0;L;<circle> 006E;;;;N;;;24C3;;24C3
+24DE;CIRCLED LATIN SMALL LETTER O;So;0;L;<circle> 006F;;;;N;;;24C4;;24C4
+24DF;CIRCLED LATIN SMALL LETTER P;So;0;L;<circle> 0070;;;;N;;;24C5;;24C5
+24E0;CIRCLED LATIN SMALL LETTER Q;So;0;L;<circle> 0071;;;;N;;;24C6;;24C6
+24E1;CIRCLED LATIN SMALL LETTER R;So;0;L;<circle> 0072;;;;N;;;24C7;;24C7
+24E2;CIRCLED LATIN SMALL LETTER S;So;0;L;<circle> 0073;;;;N;;;24C8;;24C8
+24E3;CIRCLED LATIN SMALL LETTER T;So;0;L;<circle> 0074;;;;N;;;24C9;;24C9
+24E4;CIRCLED LATIN SMALL LETTER U;So;0;L;<circle> 0075;;;;N;;;24CA;;24CA
+24E5;CIRCLED LATIN SMALL LETTER V;So;0;L;<circle> 0076;;;;N;;;24CB;;24CB
+24E6;CIRCLED LATIN SMALL LETTER W;So;0;L;<circle> 0077;;;;N;;;24CC;;24CC
+24E7;CIRCLED LATIN SMALL LETTER X;So;0;L;<circle> 0078;;;;N;;;24CD;;24CD
+24E8;CIRCLED LATIN SMALL LETTER Y;So;0;L;<circle> 0079;;;;N;;;24CE;;24CE
+24E9;CIRCLED LATIN SMALL LETTER Z;So;0;L;<circle> 007A;;;;N;;;24CF;;24CF
+24EA;CIRCLED DIGIT ZERO;No;0;ON;<circle> 0030;;0;0;N;;;;;
+24EB;NEGATIVE CIRCLED NUMBER ELEVEN;No;0;ON;;;;11;N;;;;;
+24EC;NEGATIVE CIRCLED NUMBER TWELVE;No;0;ON;;;;12;N;;;;;
+24ED;NEGATIVE CIRCLED NUMBER THIRTEEN;No;0;ON;;;;13;N;;;;;
+24EE;NEGATIVE CIRCLED NUMBER FOURTEEN;No;0;ON;;;;14;N;;;;;
+24EF;NEGATIVE CIRCLED NUMBER FIFTEEN;No;0;ON;;;;15;N;;;;;
+24F0;NEGATIVE CIRCLED NUMBER SIXTEEN;No;0;ON;;;;16;N;;;;;
+24F1;NEGATIVE CIRCLED NUMBER SEVENTEEN;No;0;ON;;;;17;N;;;;;
+24F2;NEGATIVE CIRCLED NUMBER EIGHTEEN;No;0;ON;;;;18;N;;;;;
+24F3;NEGATIVE CIRCLED NUMBER NINETEEN;No;0;ON;;;;19;N;;;;;
+24F4;NEGATIVE CIRCLED NUMBER TWENTY;No;0;ON;;;;20;N;;;;;
+24F5;DOUBLE CIRCLED DIGIT ONE;No;0;ON;;;1;1;N;;;;;
+24F6;DOUBLE CIRCLED DIGIT TWO;No;0;ON;;;2;2;N;;;;;
+24F7;DOUBLE CIRCLED DIGIT THREE;No;0;ON;;;3;3;N;;;;;
+24F8;DOUBLE CIRCLED DIGIT FOUR;No;0;ON;;;4;4;N;;;;;
+24F9;DOUBLE CIRCLED DIGIT FIVE;No;0;ON;;;5;5;N;;;;;
+24FA;DOUBLE CIRCLED DIGIT SIX;No;0;ON;;;6;6;N;;;;;
+24FB;DOUBLE CIRCLED DIGIT SEVEN;No;0;ON;;;7;7;N;;;;;
+24FC;DOUBLE CIRCLED DIGIT EIGHT;No;0;ON;;;8;8;N;;;;;
+24FD;DOUBLE CIRCLED DIGIT NINE;No;0;ON;;;9;9;N;;;;;
+24FE;DOUBLE CIRCLED NUMBER TEN;No;0;ON;;;;10;N;;;;;
+24FF;NEGATIVE CIRCLED DIGIT ZERO;No;0;ON;;;0;0;N;;;;;
+2500;BOX DRAWINGS LIGHT HORIZONTAL;So;0;ON;;;;;N;FORMS LIGHT HORIZONTAL;;;;
+2501;BOX DRAWINGS HEAVY HORIZONTAL;So;0;ON;;;;;N;FORMS HEAVY HORIZONTAL;;;;
+2502;BOX DRAWINGS LIGHT VERTICAL;So;0;ON;;;;;N;FORMS LIGHT VERTICAL;;;;
+2503;BOX DRAWINGS HEAVY VERTICAL;So;0;ON;;;;;N;FORMS HEAVY VERTICAL;;;;
+2504;BOX DRAWINGS LIGHT TRIPLE DASH HORIZONTAL;So;0;ON;;;;;N;FORMS LIGHT TRIPLE DASH HORIZONTAL;;;;
+2505;BOX DRAWINGS HEAVY TRIPLE DASH HORIZONTAL;So;0;ON;;;;;N;FORMS HEAVY TRIPLE DASH HORIZONTAL;;;;
+2506;BOX DRAWINGS LIGHT TRIPLE DASH VERTICAL;So;0;ON;;;;;N;FORMS LIGHT TRIPLE DASH VERTICAL;;;;
+2507;BOX DRAWINGS HEAVY TRIPLE DASH VERTICAL;So;0;ON;;;;;N;FORMS HEAVY TRIPLE DASH VERTICAL;;;;
+2508;BOX DRAWINGS LIGHT QUADRUPLE DASH HORIZONTAL;So;0;ON;;;;;N;FORMS LIGHT QUADRUPLE DASH HORIZONTAL;;;;
+2509;BOX DRAWINGS HEAVY QUADRUPLE DASH HORIZONTAL;So;0;ON;;;;;N;FORMS HEAVY QUADRUPLE DASH HORIZONTAL;;;;
+250A;BOX DRAWINGS LIGHT QUADRUPLE DASH VERTICAL;So;0;ON;;;;;N;FORMS LIGHT QUADRUPLE DASH VERTICAL;;;;
+250B;BOX DRAWINGS HEAVY QUADRUPLE DASH VERTICAL;So;0;ON;;;;;N;FORMS HEAVY QUADRUPLE DASH VERTICAL;;;;
+250C;BOX DRAWINGS LIGHT DOWN AND RIGHT;So;0;ON;;;;;N;FORMS LIGHT DOWN AND RIGHT;;;;
+250D;BOX DRAWINGS DOWN LIGHT AND RIGHT HEAVY;So;0;ON;;;;;N;FORMS DOWN LIGHT AND RIGHT HEAVY;;;;
+250E;BOX DRAWINGS DOWN HEAVY AND RIGHT LIGHT;So;0;ON;;;;;N;FORMS DOWN HEAVY AND RIGHT LIGHT;;;;
+250F;BOX DRAWINGS HEAVY DOWN AND RIGHT;So;0;ON;;;;;N;FORMS HEAVY DOWN AND RIGHT;;;;
+2510;BOX DRAWINGS LIGHT DOWN AND LEFT;So;0;ON;;;;;N;FORMS LIGHT DOWN AND LEFT;;;;
+2511;BOX DRAWINGS DOWN LIGHT AND LEFT HEAVY;So;0;ON;;;;;N;FORMS DOWN LIGHT AND LEFT HEAVY;;;;
+2512;BOX DRAWINGS DOWN HEAVY AND LEFT LIGHT;So;0;ON;;;;;N;FORMS DOWN HEAVY AND LEFT LIGHT;;;;
+2513;BOX DRAWINGS HEAVY DOWN AND LEFT;So;0;ON;;;;;N;FORMS HEAVY DOWN AND LEFT;;;;
+2514;BOX DRAWINGS LIGHT UP AND RIGHT;So;0;ON;;;;;N;FORMS LIGHT UP AND RIGHT;;;;
+2515;BOX DRAWINGS UP LIGHT AND RIGHT HEAVY;So;0;ON;;;;;N;FORMS UP LIGHT AND RIGHT HEAVY;;;;
+2516;BOX DRAWINGS UP HEAVY AND RIGHT LIGHT;So;0;ON;;;;;N;FORMS UP HEAVY AND RIGHT LIGHT;;;;
+2517;BOX DRAWINGS HEAVY UP AND RIGHT;So;0;ON;;;;;N;FORMS HEAVY UP AND RIGHT;;;;
+2518;BOX DRAWINGS LIGHT UP AND LEFT;So;0;ON;;;;;N;FORMS LIGHT UP AND LEFT;;;;
+2519;BOX DRAWINGS UP LIGHT AND LEFT HEAVY;So;0;ON;;;;;N;FORMS UP LIGHT AND LEFT HEAVY;;;;
+251A;BOX DRAWINGS UP HEAVY AND LEFT LIGHT;So;0;ON;;;;;N;FORMS UP HEAVY AND LEFT LIGHT;;;;
+251B;BOX DRAWINGS HEAVY UP AND LEFT;So;0;ON;;;;;N;FORMS HEAVY UP AND LEFT;;;;
+251C;BOX DRAWINGS LIGHT VERTICAL AND RIGHT;So;0;ON;;;;;N;FORMS LIGHT VERTICAL AND RIGHT;;;;
+251D;BOX DRAWINGS VERTICAL LIGHT AND RIGHT HEAVY;So;0;ON;;;;;N;FORMS VERTICAL LIGHT AND RIGHT HEAVY;;;;
+251E;BOX DRAWINGS UP HEAVY AND RIGHT DOWN LIGHT;So;0;ON;;;;;N;FORMS UP HEAVY AND RIGHT DOWN LIGHT;;;;
+251F;BOX DRAWINGS DOWN HEAVY AND RIGHT UP LIGHT;So;0;ON;;;;;N;FORMS DOWN HEAVY AND RIGHT UP LIGHT;;;;
+2520;BOX DRAWINGS VERTICAL HEAVY AND RIGHT LIGHT;So;0;ON;;;;;N;FORMS VERTICAL HEAVY AND RIGHT LIGHT;;;;
+2521;BOX DRAWINGS DOWN LIGHT AND RIGHT UP HEAVY;So;0;ON;;;;;N;FORMS DOWN LIGHT AND RIGHT UP HEAVY;;;;
+2522;BOX DRAWINGS UP LIGHT AND RIGHT DOWN HEAVY;So;0;ON;;;;;N;FORMS UP LIGHT AND RIGHT DOWN HEAVY;;;;
+2523;BOX DRAWINGS HEAVY VERTICAL AND RIGHT;So;0;ON;;;;;N;FORMS HEAVY VERTICAL AND RIGHT;;;;
+2524;BOX DRAWINGS LIGHT VERTICAL AND LEFT;So;0;ON;;;;;N;FORMS LIGHT VERTICAL AND LEFT;;;;
+2525;BOX DRAWINGS VERTICAL LIGHT AND LEFT HEAVY;So;0;ON;;;;;N;FORMS VERTICAL LIGHT AND LEFT HEAVY;;;;
+2526;BOX DRAWINGS UP HEAVY AND LEFT DOWN LIGHT;So;0;ON;;;;;N;FORMS UP HEAVY AND LEFT DOWN LIGHT;;;;
+2527;BOX DRAWINGS DOWN HEAVY AND LEFT UP LIGHT;So;0;ON;;;;;N;FORMS DOWN HEAVY AND LEFT UP LIGHT;;;;
+2528;BOX DRAWINGS VERTICAL HEAVY AND LEFT LIGHT;So;0;ON;;;;;N;FORMS VERTICAL HEAVY AND LEFT LIGHT;;;;
+2529;BOX DRAWINGS DOWN LIGHT AND LEFT UP HEAVY;So;0;ON;;;;;N;FORMS DOWN LIGHT AND LEFT UP HEAVY;;;;
+252A;BOX DRAWINGS UP LIGHT AND LEFT DOWN HEAVY;So;0;ON;;;;;N;FORMS UP LIGHT AND LEFT DOWN HEAVY;;;;
+252B;BOX DRAWINGS HEAVY VERTICAL AND LEFT;So;0;ON;;;;;N;FORMS HEAVY VERTICAL AND LEFT;;;;
+252C;BOX DRAWINGS LIGHT DOWN AND HORIZONTAL;So;0;ON;;;;;N;FORMS LIGHT DOWN AND HORIZONTAL;;;;
+252D;BOX DRAWINGS LEFT HEAVY AND RIGHT DOWN LIGHT;So;0;ON;;;;;N;FORMS LEFT HEAVY AND RIGHT DOWN LIGHT;;;;
+252E;BOX DRAWINGS RIGHT HEAVY AND LEFT DOWN LIGHT;So;0;ON;;;;;N;FORMS RIGHT HEAVY AND LEFT DOWN LIGHT;;;;
+252F;BOX DRAWINGS DOWN LIGHT AND HORIZONTAL HEAVY;So;0;ON;;;;;N;FORMS DOWN LIGHT AND HORIZONTAL HEAVY;;;;
+2530;BOX DRAWINGS DOWN HEAVY AND HORIZONTAL LIGHT;So;0;ON;;;;;N;FORMS DOWN HEAVY AND HORIZONTAL LIGHT;;;;
+2531;BOX DRAWINGS RIGHT LIGHT AND LEFT DOWN HEAVY;So;0;ON;;;;;N;FORMS RIGHT LIGHT AND LEFT DOWN HEAVY;;;;
+2532;BOX DRAWINGS LEFT LIGHT AND RIGHT DOWN HEAVY;So;0;ON;;;;;N;FORMS LEFT LIGHT AND RIGHT DOWN HEAVY;;;;
+2533;BOX DRAWINGS HEAVY DOWN AND HORIZONTAL;So;0;ON;;;;;N;FORMS HEAVY DOWN AND HORIZONTAL;;;;
+2534;BOX DRAWINGS LIGHT UP AND HORIZONTAL;So;0;ON;;;;;N;FORMS LIGHT UP AND HORIZONTAL;;;;
+2535;BOX DRAWINGS LEFT HEAVY AND RIGHT UP LIGHT;So;0;ON;;;;;N;FORMS LEFT HEAVY AND RIGHT UP LIGHT;;;;
+2536;BOX DRAWINGS RIGHT HEAVY AND LEFT UP LIGHT;So;0;ON;;;;;N;FORMS RIGHT HEAVY AND LEFT UP LIGHT;;;;
+2537;BOX DRAWINGS UP LIGHT AND HORIZONTAL HEAVY;So;0;ON;;;;;N;FORMS UP LIGHT AND HORIZONTAL HEAVY;;;;
+2538;BOX DRAWINGS UP HEAVY AND HORIZONTAL LIGHT;So;0;ON;;;;;N;FORMS UP HEAVY AND HORIZONTAL LIGHT;;;;
+2539;BOX DRAWINGS RIGHT LIGHT AND LEFT UP HEAVY;So;0;ON;;;;;N;FORMS RIGHT LIGHT AND LEFT UP HEAVY;;;;
+253A;BOX DRAWINGS LEFT LIGHT AND RIGHT UP HEAVY;So;0;ON;;;;;N;FORMS LEFT LIGHT AND RIGHT UP HEAVY;;;;
+253B;BOX DRAWINGS HEAVY UP AND HORIZONTAL;So;0;ON;;;;;N;FORMS HEAVY UP AND HORIZONTAL;;;;
+253C;BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL;So;0;ON;;;;;N;FORMS LIGHT VERTICAL AND HORIZONTAL;;;;
+253D;BOX DRAWINGS LEFT HEAVY AND RIGHT VERTICAL LIGHT;So;0;ON;;;;;N;FORMS LEFT HEAVY AND RIGHT VERTICAL LIGHT;;;;
+253E;BOX DRAWINGS RIGHT HEAVY AND LEFT VERTICAL LIGHT;So;0;ON;;;;;N;FORMS RIGHT HEAVY AND LEFT VERTICAL LIGHT;;;;
+253F;BOX DRAWINGS VERTICAL LIGHT AND HORIZONTAL HEAVY;So;0;ON;;;;;N;FORMS VERTICAL LIGHT AND HORIZONTAL HEAVY;;;;
+2540;BOX DRAWINGS UP HEAVY AND DOWN HORIZONTAL LIGHT;So;0;ON;;;;;N;FORMS UP HEAVY AND DOWN HORIZONTAL LIGHT;;;;
+2541;BOX DRAWINGS DOWN HEAVY AND UP HORIZONTAL LIGHT;So;0;ON;;;;;N;FORMS DOWN HEAVY AND UP HORIZONTAL LIGHT;;;;
+2542;BOX DRAWINGS VERTICAL HEAVY AND HORIZONTAL LIGHT;So;0;ON;;;;;N;FORMS VERTICAL HEAVY AND HORIZONTAL LIGHT;;;;
+2543;BOX DRAWINGS LEFT UP HEAVY AND RIGHT DOWN LIGHT;So;0;ON;;;;;N;FORMS LEFT UP HEAVY AND RIGHT DOWN LIGHT;;;;
+2544;BOX DRAWINGS RIGHT UP HEAVY AND LEFT DOWN LIGHT;So;0;ON;;;;;N;FORMS RIGHT UP HEAVY AND LEFT DOWN LIGHT;;;;
+2545;BOX DRAWINGS LEFT DOWN HEAVY AND RIGHT UP LIGHT;So;0;ON;;;;;N;FORMS LEFT DOWN HEAVY AND RIGHT UP LIGHT;;;;
+2546;BOX DRAWINGS RIGHT DOWN HEAVY AND LEFT UP LIGHT;So;0;ON;;;;;N;FORMS RIGHT DOWN HEAVY AND LEFT UP LIGHT;;;;
+2547;BOX DRAWINGS DOWN LIGHT AND UP HORIZONTAL HEAVY;So;0;ON;;;;;N;FORMS DOWN LIGHT AND UP HORIZONTAL HEAVY;;;;
+2548;BOX DRAWINGS UP LIGHT AND DOWN HORIZONTAL HEAVY;So;0;ON;;;;;N;FORMS UP LIGHT AND DOWN HORIZONTAL HEAVY;;;;
+2549;BOX DRAWINGS RIGHT LIGHT AND LEFT VERTICAL HEAVY;So;0;ON;;;;;N;FORMS RIGHT LIGHT AND LEFT VERTICAL HEAVY;;;;
+254A;BOX DRAWINGS LEFT LIGHT AND RIGHT VERTICAL HEAVY;So;0;ON;;;;;N;FORMS LEFT LIGHT AND RIGHT VERTICAL HEAVY;;;;
+254B;BOX DRAWINGS HEAVY VERTICAL AND HORIZONTAL;So;0;ON;;;;;N;FORMS HEAVY VERTICAL AND HORIZONTAL;;;;
+254C;BOX DRAWINGS LIGHT DOUBLE DASH HORIZONTAL;So;0;ON;;;;;N;FORMS LIGHT DOUBLE DASH HORIZONTAL;;;;
+254D;BOX DRAWINGS HEAVY DOUBLE DASH HORIZONTAL;So;0;ON;;;;;N;FORMS HEAVY DOUBLE DASH HORIZONTAL;;;;
+254E;BOX DRAWINGS LIGHT DOUBLE DASH VERTICAL;So;0;ON;;;;;N;FORMS LIGHT DOUBLE DASH VERTICAL;;;;
+254F;BOX DRAWINGS HEAVY DOUBLE DASH VERTICAL;So;0;ON;;;;;N;FORMS HEAVY DOUBLE DASH VERTICAL;;;;
+2550;BOX DRAWINGS DOUBLE HORIZONTAL;So;0;ON;;;;;N;FORMS DOUBLE HORIZONTAL;;;;
+2551;BOX DRAWINGS DOUBLE VERTICAL;So;0;ON;;;;;N;FORMS DOUBLE VERTICAL;;;;
+2552;BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE;So;0;ON;;;;;N;FORMS DOWN SINGLE AND RIGHT DOUBLE;;;;
+2553;BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE;So;0;ON;;;;;N;FORMS DOWN DOUBLE AND RIGHT SINGLE;;;;
+2554;BOX DRAWINGS DOUBLE DOWN AND RIGHT;So;0;ON;;;;;N;FORMS DOUBLE DOWN AND RIGHT;;;;
+2555;BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE;So;0;ON;;;;;N;FORMS DOWN SINGLE AND LEFT DOUBLE;;;;
+2556;BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE;So;0;ON;;;;;N;FORMS DOWN DOUBLE AND LEFT SINGLE;;;;
+2557;BOX DRAWINGS DOUBLE DOWN AND LEFT;So;0;ON;;;;;N;FORMS DOUBLE DOWN AND LEFT;;;;
+2558;BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE;So;0;ON;;;;;N;FORMS UP SINGLE AND RIGHT DOUBLE;;;;
+2559;BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE;So;0;ON;;;;;N;FORMS UP DOUBLE AND RIGHT SINGLE;;;;
+255A;BOX DRAWINGS DOUBLE UP AND RIGHT;So;0;ON;;;;;N;FORMS DOUBLE UP AND RIGHT;;;;
+255B;BOX DRAWINGS UP SINGLE AND LEFT DOUBLE;So;0;ON;;;;;N;FORMS UP SINGLE AND LEFT DOUBLE;;;;
+255C;BOX DRAWINGS UP DOUBLE AND LEFT SINGLE;So;0;ON;;;;;N;FORMS UP DOUBLE AND LEFT SINGLE;;;;
+255D;BOX DRAWINGS DOUBLE UP AND LEFT;So;0;ON;;;;;N;FORMS DOUBLE UP AND LEFT;;;;
+255E;BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE;So;0;ON;;;;;N;FORMS VERTICAL SINGLE AND RIGHT DOUBLE;;;;
+255F;BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE;So;0;ON;;;;;N;FORMS VERTICAL DOUBLE AND RIGHT SINGLE;;;;
+2560;BOX DRAWINGS DOUBLE VERTICAL AND RIGHT;So;0;ON;;;;;N;FORMS DOUBLE VERTICAL AND RIGHT;;;;
+2561;BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE;So;0;ON;;;;;N;FORMS VERTICAL SINGLE AND LEFT DOUBLE;;;;
+2562;BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE;So;0;ON;;;;;N;FORMS VERTICAL DOUBLE AND LEFT SINGLE;;;;
+2563;BOX DRAWINGS DOUBLE VERTICAL AND LEFT;So;0;ON;;;;;N;FORMS DOUBLE VERTICAL AND LEFT;;;;
+2564;BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE;So;0;ON;;;;;N;FORMS DOWN SINGLE AND HORIZONTAL DOUBLE;;;;
+2565;BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE;So;0;ON;;;;;N;FORMS DOWN DOUBLE AND HORIZONTAL SINGLE;;;;
+2566;BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL;So;0;ON;;;;;N;FORMS DOUBLE DOWN AND HORIZONTAL;;;;
+2567;BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE;So;0;ON;;;;;N;FORMS UP SINGLE AND HORIZONTAL DOUBLE;;;;
+2568;BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE;So;0;ON;;;;;N;FORMS UP DOUBLE AND HORIZONTAL SINGLE;;;;
+2569;BOX DRAWINGS DOUBLE UP AND HORIZONTAL;So;0;ON;;;;;N;FORMS DOUBLE UP AND HORIZONTAL;;;;
+256A;BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE;So;0;ON;;;;;N;FORMS VERTICAL SINGLE AND HORIZONTAL DOUBLE;;;;
+256B;BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE;So;0;ON;;;;;N;FORMS VERTICAL DOUBLE AND HORIZONTAL SINGLE;;;;
+256C;BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL;So;0;ON;;;;;N;FORMS DOUBLE VERTICAL AND HORIZONTAL;;;;
+256D;BOX DRAWINGS LIGHT ARC DOWN AND RIGHT;So;0;ON;;;;;N;FORMS LIGHT ARC DOWN AND RIGHT;;;;
+256E;BOX DRAWINGS LIGHT ARC DOWN AND LEFT;So;0;ON;;;;;N;FORMS LIGHT ARC DOWN AND LEFT;;;;
+256F;BOX DRAWINGS LIGHT ARC UP AND LEFT;So;0;ON;;;;;N;FORMS LIGHT ARC UP AND LEFT;;;;
+2570;BOX DRAWINGS LIGHT ARC UP AND RIGHT;So;0;ON;;;;;N;FORMS LIGHT ARC UP AND RIGHT;;;;
+2571;BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT;So;0;ON;;;;;N;FORMS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT;;;;
+2572;BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT;So;0;ON;;;;;N;FORMS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT;;;;
+2573;BOX DRAWINGS LIGHT DIAGONAL CROSS;So;0;ON;;;;;N;FORMS LIGHT DIAGONAL CROSS;;;;
+2574;BOX DRAWINGS LIGHT LEFT;So;0;ON;;;;;N;FORMS LIGHT LEFT;;;;
+2575;BOX DRAWINGS LIGHT UP;So;0;ON;;;;;N;FORMS LIGHT UP;;;;
+2576;BOX DRAWINGS LIGHT RIGHT;So;0;ON;;;;;N;FORMS LIGHT RIGHT;;;;
+2577;BOX DRAWINGS LIGHT DOWN;So;0;ON;;;;;N;FORMS LIGHT DOWN;;;;
+2578;BOX DRAWINGS HEAVY LEFT;So;0;ON;;;;;N;FORMS HEAVY LEFT;;;;
+2579;BOX DRAWINGS HEAVY UP;So;0;ON;;;;;N;FORMS HEAVY UP;;;;
+257A;BOX DRAWINGS HEAVY RIGHT;So;0;ON;;;;;N;FORMS HEAVY RIGHT;;;;
+257B;BOX DRAWINGS HEAVY DOWN;So;0;ON;;;;;N;FORMS HEAVY DOWN;;;;
+257C;BOX DRAWINGS LIGHT LEFT AND HEAVY RIGHT;So;0;ON;;;;;N;FORMS LIGHT LEFT AND HEAVY RIGHT;;;;
+257D;BOX DRAWINGS LIGHT UP AND HEAVY DOWN;So;0;ON;;;;;N;FORMS LIGHT UP AND HEAVY DOWN;;;;
+257E;BOX DRAWINGS HEAVY LEFT AND LIGHT RIGHT;So;0;ON;;;;;N;FORMS HEAVY LEFT AND LIGHT RIGHT;;;;
+257F;BOX DRAWINGS HEAVY UP AND LIGHT DOWN;So;0;ON;;;;;N;FORMS HEAVY UP AND LIGHT DOWN;;;;
+2580;UPPER HALF BLOCK;So;0;ON;;;;;N;;;;;
+2581;LOWER ONE EIGHTH BLOCK;So;0;ON;;;;;N;;;;;
+2582;LOWER ONE QUARTER BLOCK;So;0;ON;;;;;N;;;;;
+2583;LOWER THREE EIGHTHS BLOCK;So;0;ON;;;;;N;;;;;
+2584;LOWER HALF BLOCK;So;0;ON;;;;;N;;;;;
+2585;LOWER FIVE EIGHTHS BLOCK;So;0;ON;;;;;N;;;;;
+2586;LOWER THREE QUARTERS BLOCK;So;0;ON;;;;;N;LOWER THREE QUARTER BLOCK;;;;
+2587;LOWER SEVEN EIGHTHS BLOCK;So;0;ON;;;;;N;;;;;
+2588;FULL BLOCK;So;0;ON;;;;;N;;;;;
+2589;LEFT SEVEN EIGHTHS BLOCK;So;0;ON;;;;;N;;;;;
+258A;LEFT THREE QUARTERS BLOCK;So;0;ON;;;;;N;LEFT THREE QUARTER BLOCK;;;;
+258B;LEFT FIVE EIGHTHS BLOCK;So;0;ON;;;;;N;;;;;
+258C;LEFT HALF BLOCK;So;0;ON;;;;;N;;;;;
+258D;LEFT THREE EIGHTHS BLOCK;So;0;ON;;;;;N;;;;;
+258E;LEFT ONE QUARTER BLOCK;So;0;ON;;;;;N;;;;;
+258F;LEFT ONE EIGHTH BLOCK;So;0;ON;;;;;N;;;;;
+2590;RIGHT HALF BLOCK;So;0;ON;;;;;N;;;;;
+2591;LIGHT SHADE;So;0;ON;;;;;N;;;;;
+2592;MEDIUM SHADE;So;0;ON;;;;;N;;;;;
+2593;DARK SHADE;So;0;ON;;;;;N;;;;;
+2594;UPPER ONE EIGHTH BLOCK;So;0;ON;;;;;N;;;;;
+2595;RIGHT ONE EIGHTH BLOCK;So;0;ON;;;;;N;;;;;
+2596;QUADRANT LOWER LEFT;So;0;ON;;;;;N;;;;;
+2597;QUADRANT LOWER RIGHT;So;0;ON;;;;;N;;;;;
+2598;QUADRANT UPPER LEFT;So;0;ON;;;;;N;;;;;
+2599;QUADRANT UPPER LEFT AND LOWER LEFT AND LOWER RIGHT;So;0;ON;;;;;N;;;;;
+259A;QUADRANT UPPER LEFT AND LOWER RIGHT;So;0;ON;;;;;N;;;;;
+259B;QUADRANT UPPER LEFT AND UPPER RIGHT AND LOWER LEFT;So;0;ON;;;;;N;;;;;
+259C;QUADRANT UPPER LEFT AND UPPER RIGHT AND LOWER RIGHT;So;0;ON;;;;;N;;;;;
+259D;QUADRANT UPPER RIGHT;So;0;ON;;;;;N;;;;;
+259E;QUADRANT UPPER RIGHT AND LOWER LEFT;So;0;ON;;;;;N;;;;;
+259F;QUADRANT UPPER RIGHT AND LOWER LEFT AND LOWER RIGHT;So;0;ON;;;;;N;;;;;
+25A0;BLACK SQUARE;So;0;ON;;;;;N;;;;;
+25A1;WHITE SQUARE;So;0;ON;;;;;N;;;;;
+25A2;WHITE SQUARE WITH ROUNDED CORNERS;So;0;ON;;;;;N;;;;;
+25A3;WHITE SQUARE CONTAINING BLACK SMALL SQUARE;So;0;ON;;;;;N;;;;;
+25A4;SQUARE WITH HORIZONTAL FILL;So;0;ON;;;;;N;;;;;
+25A5;SQUARE WITH VERTICAL FILL;So;0;ON;;;;;N;;;;;
+25A6;SQUARE WITH ORTHOGONAL CROSSHATCH FILL;So;0;ON;;;;;N;;;;;
+25A7;SQUARE WITH UPPER LEFT TO LOWER RIGHT FILL;So;0;ON;;;;;N;;;;;
+25A8;SQUARE WITH UPPER RIGHT TO LOWER LEFT FILL;So;0;ON;;;;;N;;;;;
+25A9;SQUARE WITH DIAGONAL CROSSHATCH FILL;So;0;ON;;;;;N;;;;;
+25AA;BLACK SMALL SQUARE;So;0;ON;;;;;N;;;;;
+25AB;WHITE SMALL SQUARE;So;0;ON;;;;;N;;;;;
+25AC;BLACK RECTANGLE;So;0;ON;;;;;N;;;;;
+25AD;WHITE RECTANGLE;So;0;ON;;;;;N;;;;;
+25AE;BLACK VERTICAL RECTANGLE;So;0;ON;;;;;N;;;;;
+25AF;WHITE VERTICAL RECTANGLE;So;0;ON;;;;;N;;;;;
+25B0;BLACK PARALLELOGRAM;So;0;ON;;;;;N;;;;;
+25B1;WHITE PARALLELOGRAM;So;0;ON;;;;;N;;;;;
+25B2;BLACK UP-POINTING TRIANGLE;So;0;ON;;;;;N;BLACK UP POINTING TRIANGLE;;;;
+25B3;WHITE UP-POINTING TRIANGLE;So;0;ON;;;;;N;WHITE UP POINTING TRIANGLE;;;;
+25B4;BLACK UP-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;BLACK UP POINTING SMALL TRIANGLE;;;;
+25B5;WHITE UP-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;WHITE UP POINTING SMALL TRIANGLE;;;;
+25B6;BLACK RIGHT-POINTING TRIANGLE;So;0;ON;;;;;N;BLACK RIGHT POINTING TRIANGLE;;;;
+25B7;WHITE RIGHT-POINTING TRIANGLE;Sm;0;ON;;;;;N;WHITE RIGHT POINTING TRIANGLE;;;;
+25B8;BLACK RIGHT-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;BLACK RIGHT POINTING SMALL TRIANGLE;;;;
+25B9;WHITE RIGHT-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;WHITE RIGHT POINTING SMALL TRIANGLE;;;;
+25BA;BLACK RIGHT-POINTING POINTER;So;0;ON;;;;;N;BLACK RIGHT POINTING POINTER;;;;
+25BB;WHITE RIGHT-POINTING POINTER;So;0;ON;;;;;N;WHITE RIGHT POINTING POINTER;;;;
+25BC;BLACK DOWN-POINTING TRIANGLE;So;0;ON;;;;;N;BLACK DOWN POINTING TRIANGLE;;;;
+25BD;WHITE DOWN-POINTING TRIANGLE;So;0;ON;;;;;N;WHITE DOWN POINTING TRIANGLE;;;;
+25BE;BLACK DOWN-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;BLACK DOWN POINTING SMALL TRIANGLE;;;;
+25BF;WHITE DOWN-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;WHITE DOWN POINTING SMALL TRIANGLE;;;;
+25C0;BLACK LEFT-POINTING TRIANGLE;So;0;ON;;;;;N;BLACK LEFT POINTING TRIANGLE;;;;
+25C1;WHITE LEFT-POINTING TRIANGLE;Sm;0;ON;;;;;N;WHITE LEFT POINTING TRIANGLE;;;;
+25C2;BLACK LEFT-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;BLACK LEFT POINTING SMALL TRIANGLE;;;;
+25C3;WHITE LEFT-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;WHITE LEFT POINTING SMALL TRIANGLE;;;;
+25C4;BLACK LEFT-POINTING POINTER;So;0;ON;;;;;N;BLACK LEFT POINTING POINTER;;;;
+25C5;WHITE LEFT-POINTING POINTER;So;0;ON;;;;;N;WHITE LEFT POINTING POINTER;;;;
+25C6;BLACK DIAMOND;So;0;ON;;;;;N;;;;;
+25C7;WHITE DIAMOND;So;0;ON;;;;;N;;;;;
+25C8;WHITE DIAMOND CONTAINING BLACK SMALL DIAMOND;So;0;ON;;;;;N;;;;;
+25C9;FISHEYE;So;0;ON;;;;;N;;;;;
+25CA;LOZENGE;So;0;ON;;;;;N;;;;;
+25CB;WHITE CIRCLE;So;0;ON;;;;;N;;;;;
+25CC;DOTTED CIRCLE;So;0;ON;;;;;N;;;;;
+25CD;CIRCLE WITH VERTICAL FILL;So;0;ON;;;;;N;;;;;
+25CE;BULLSEYE;So;0;ON;;;;;N;;;;;
+25CF;BLACK CIRCLE;So;0;ON;;;;;N;;;;;
+25D0;CIRCLE WITH LEFT HALF BLACK;So;0;ON;;;;;N;;;;;
+25D1;CIRCLE WITH RIGHT HALF BLACK;So;0;ON;;;;;N;;;;;
+25D2;CIRCLE WITH LOWER HALF BLACK;So;0;ON;;;;;N;;;;;
+25D3;CIRCLE WITH UPPER HALF BLACK;So;0;ON;;;;;N;;;;;
+25D4;CIRCLE WITH UPPER RIGHT QUADRANT BLACK;So;0;ON;;;;;N;;;;;
+25D5;CIRCLE WITH ALL BUT UPPER LEFT QUADRANT BLACK;So;0;ON;;;;;N;;;;;
+25D6;LEFT HALF BLACK CIRCLE;So;0;ON;;;;;N;;;;;
+25D7;RIGHT HALF BLACK CIRCLE;So;0;ON;;;;;N;;;;;
+25D8;INVERSE BULLET;So;0;ON;;;;;N;;;;;
+25D9;INVERSE WHITE CIRCLE;So;0;ON;;;;;N;;;;;
+25DA;UPPER HALF INVERSE WHITE CIRCLE;So;0;ON;;;;;N;;;;;
+25DB;LOWER HALF INVERSE WHITE CIRCLE;So;0;ON;;;;;N;;;;;
+25DC;UPPER LEFT QUADRANT CIRCULAR ARC;So;0;ON;;;;;N;;;;;
+25DD;UPPER RIGHT QUADRANT CIRCULAR ARC;So;0;ON;;;;;N;;;;;
+25DE;LOWER RIGHT QUADRANT CIRCULAR ARC;So;0;ON;;;;;N;;;;;
+25DF;LOWER LEFT QUADRANT CIRCULAR ARC;So;0;ON;;;;;N;;;;;
+25E0;UPPER HALF CIRCLE;So;0;ON;;;;;N;;;;;
+25E1;LOWER HALF CIRCLE;So;0;ON;;;;;N;;;;;
+25E2;BLACK LOWER RIGHT TRIANGLE;So;0;ON;;;;;N;;;;;
+25E3;BLACK LOWER LEFT TRIANGLE;So;0;ON;;;;;N;;;;;
+25E4;BLACK UPPER LEFT TRIANGLE;So;0;ON;;;;;N;;;;;
+25E5;BLACK UPPER RIGHT TRIANGLE;So;0;ON;;;;;N;;;;;
+25E6;WHITE BULLET;So;0;ON;;;;;N;;;;;
+25E7;SQUARE WITH LEFT HALF BLACK;So;0;ON;;;;;N;;;;;
+25E8;SQUARE WITH RIGHT HALF BLACK;So;0;ON;;;;;N;;;;;
+25E9;SQUARE WITH UPPER LEFT DIAGONAL HALF BLACK;So;0;ON;;;;;N;;;;;
+25EA;SQUARE WITH LOWER RIGHT DIAGONAL HALF BLACK;So;0;ON;;;;;N;;;;;
+25EB;WHITE SQUARE WITH VERTICAL BISECTING LINE;So;0;ON;;;;;N;;;;;
+25EC;WHITE UP-POINTING TRIANGLE WITH DOT;So;0;ON;;;;;N;WHITE UP POINTING TRIANGLE WITH DOT;;;;
+25ED;UP-POINTING TRIANGLE WITH LEFT HALF BLACK;So;0;ON;;;;;N;UP POINTING TRIANGLE WITH LEFT HALF BLACK;;;;
+25EE;UP-POINTING TRIANGLE WITH RIGHT HALF BLACK;So;0;ON;;;;;N;UP POINTING TRIANGLE WITH RIGHT HALF BLACK;;;;
+25EF;LARGE CIRCLE;So;0;ON;;;;;N;;;;;
+25F0;WHITE SQUARE WITH UPPER LEFT QUADRANT;So;0;ON;;;;;N;;;;;
+25F1;WHITE SQUARE WITH LOWER LEFT QUADRANT;So;0;ON;;;;;N;;;;;
+25F2;WHITE SQUARE WITH LOWER RIGHT QUADRANT;So;0;ON;;;;;N;;;;;
+25F3;WHITE SQUARE WITH UPPER RIGHT QUADRANT;So;0;ON;;;;;N;;;;;
+25F4;WHITE CIRCLE WITH UPPER LEFT QUADRANT;So;0;ON;;;;;N;;;;;
+25F5;WHITE CIRCLE WITH LOWER LEFT QUADRANT;So;0;ON;;;;;N;;;;;
+25F6;WHITE CIRCLE WITH LOWER RIGHT QUADRANT;So;0;ON;;;;;N;;;;;
+25F7;WHITE CIRCLE WITH UPPER RIGHT QUADRANT;So;0;ON;;;;;N;;;;;
+25F8;UPPER LEFT TRIANGLE;Sm;0;ON;;;;;N;;;;;
+25F9;UPPER RIGHT TRIANGLE;Sm;0;ON;;;;;N;;;;;
+25FA;LOWER LEFT TRIANGLE;Sm;0;ON;;;;;N;;;;;
+25FB;WHITE MEDIUM SQUARE;Sm;0;ON;;;;;N;;;;;
+25FC;BLACK MEDIUM SQUARE;Sm;0;ON;;;;;N;;;;;
+25FD;WHITE MEDIUM SMALL SQUARE;Sm;0;ON;;;;;N;;;;;
+25FE;BLACK MEDIUM SMALL SQUARE;Sm;0;ON;;;;;N;;;;;
+25FF;LOWER RIGHT TRIANGLE;Sm;0;ON;;;;;N;;;;;
+2600;BLACK SUN WITH RAYS;So;0;ON;;;;;N;;;;;
+2601;CLOUD;So;0;ON;;;;;N;;;;;
+2602;UMBRELLA;So;0;ON;;;;;N;;;;;
+2603;SNOWMAN;So;0;ON;;;;;N;;;;;
+2604;COMET;So;0;ON;;;;;N;;;;;
+2605;BLACK STAR;So;0;ON;;;;;N;;;;;
+2606;WHITE STAR;So;0;ON;;;;;N;;;;;
+2607;LIGHTNING;So;0;ON;;;;;N;;;;;
+2608;THUNDERSTORM;So;0;ON;;;;;N;;;;;
+2609;SUN;So;0;ON;;;;;N;;;;;
+260A;ASCENDING NODE;So;0;ON;;;;;N;;;;;
+260B;DESCENDING NODE;So;0;ON;;;;;N;;;;;
+260C;CONJUNCTION;So;0;ON;;;;;N;;;;;
+260D;OPPOSITION;So;0;ON;;;;;N;;;;;
+260E;BLACK TELEPHONE;So;0;ON;;;;;N;;;;;
+260F;WHITE TELEPHONE;So;0;ON;;;;;N;;;;;
+2610;BALLOT BOX;So;0;ON;;;;;N;;;;;
+2611;BALLOT BOX WITH CHECK;So;0;ON;;;;;N;;;;;
+2612;BALLOT BOX WITH X;So;0;ON;;;;;N;;;;;
+2613;SALTIRE;So;0;ON;;;;;N;;;;;
+2614;UMBRELLA WITH RAIN DROPS;So;0;ON;;;;;N;;;;;
+2615;HOT BEVERAGE;So;0;ON;;;;;N;;;;;
+2616;WHITE SHOGI PIECE;So;0;ON;;;;;N;;;;;
+2617;BLACK SHOGI PIECE;So;0;ON;;;;;N;;;;;
+2619;REVERSED ROTATED FLORAL HEART BULLET;So;0;ON;;;;;N;;;;;
+261A;BLACK LEFT POINTING INDEX;So;0;ON;;;;;N;;;;;
+261B;BLACK RIGHT POINTING INDEX;So;0;ON;;;;;N;;;;;
+261C;WHITE LEFT POINTING INDEX;So;0;ON;;;;;N;;;;;
+261D;WHITE UP POINTING INDEX;So;0;ON;;;;;N;;;;;
+261E;WHITE RIGHT POINTING INDEX;So;0;ON;;;;;N;;;;;
+261F;WHITE DOWN POINTING INDEX;So;0;ON;;;;;N;;;;;
+2620;SKULL AND CROSSBONES;So;0;ON;;;;;N;;;;;
+2621;CAUTION SIGN;So;0;ON;;;;;N;;;;;
+2622;RADIOACTIVE SIGN;So;0;ON;;;;;N;;;;;
+2623;BIOHAZARD SIGN;So;0;ON;;;;;N;;;;;
+2624;CADUCEUS;So;0;ON;;;;;N;;;;;
+2625;ANKH;So;0;ON;;;;;N;;;;;
+2626;ORTHODOX CROSS;So;0;ON;;;;;N;;;;;
+2627;CHI RHO;So;0;ON;;;;;N;;;;;
+2628;CROSS OF LORRAINE;So;0;ON;;;;;N;;;;;
+2629;CROSS OF JERUSALEM;So;0;ON;;;;;N;;;;;
+262A;STAR AND CRESCENT;So;0;ON;;;;;N;;;;;
+262B;FARSI SYMBOL;So;0;ON;;;;;N;SYMBOL OF IRAN;;;;
+262C;ADI SHAKTI;So;0;ON;;;;;N;;;;;
+262D;HAMMER AND SICKLE;So;0;ON;;;;;N;;;;;
+262E;PEACE SYMBOL;So;0;ON;;;;;N;;;;;
+262F;YIN YANG;So;0;ON;;;;;N;;;;;
+2630;TRIGRAM FOR HEAVEN;So;0;ON;;;;;N;;;;;
+2631;TRIGRAM FOR LAKE;So;0;ON;;;;;N;;;;;
+2632;TRIGRAM FOR FIRE;So;0;ON;;;;;N;;;;;
+2633;TRIGRAM FOR THUNDER;So;0;ON;;;;;N;;;;;
+2634;TRIGRAM FOR WIND;So;0;ON;;;;;N;;;;;
+2635;TRIGRAM FOR WATER;So;0;ON;;;;;N;;;;;
+2636;TRIGRAM FOR MOUNTAIN;So;0;ON;;;;;N;;;;;
+2637;TRIGRAM FOR EARTH;So;0;ON;;;;;N;;;;;
+2638;WHEEL OF DHARMA;So;0;ON;;;;;N;;;;;
+2639;WHITE FROWNING FACE;So;0;ON;;;;;N;;;;;
+263A;WHITE SMILING FACE;So;0;ON;;;;;N;;;;;
+263B;BLACK SMILING FACE;So;0;ON;;;;;N;;;;;
+263C;WHITE SUN WITH RAYS;So;0;ON;;;;;N;;;;;
+263D;FIRST QUARTER MOON;So;0;ON;;;;;N;;;;;
+263E;LAST QUARTER MOON;So;0;ON;;;;;N;;;;;
+263F;MERCURY;So;0;ON;;;;;N;;;;;
+2640;FEMALE SIGN;So;0;ON;;;;;N;;;;;
+2641;EARTH;So;0;ON;;;;;N;;;;;
+2642;MALE SIGN;So;0;ON;;;;;N;;;;;
+2643;JUPITER;So;0;ON;;;;;N;;;;;
+2644;SATURN;So;0;ON;;;;;N;;;;;
+2645;URANUS;So;0;ON;;;;;N;;;;;
+2646;NEPTUNE;So;0;ON;;;;;N;;;;;
+2647;PLUTO;So;0;ON;;;;;N;;;;;
+2648;ARIES;So;0;ON;;;;;N;;;;;
+2649;TAURUS;So;0;ON;;;;;N;;;;;
+264A;GEMINI;So;0;ON;;;;;N;;;;;
+264B;CANCER;So;0;ON;;;;;N;;;;;
+264C;LEO;So;0;ON;;;;;N;;;;;
+264D;VIRGO;So;0;ON;;;;;N;;;;;
+264E;LIBRA;So;0;ON;;;;;N;;;;;
+264F;SCORPIUS;So;0;ON;;;;;N;;;;;
+2650;SAGITTARIUS;So;0;ON;;;;;N;;;;;
+2651;CAPRICORN;So;0;ON;;;;;N;;;;;
+2652;AQUARIUS;So;0;ON;;;;;N;;;;;
+2653;PISCES;So;0;ON;;;;;N;;;;;
+2654;WHITE CHESS KING;So;0;ON;;;;;N;;;;;
+2655;WHITE CHESS QUEEN;So;0;ON;;;;;N;;;;;
+2656;WHITE CHESS ROOK;So;0;ON;;;;;N;;;;;
+2657;WHITE CHESS BISHOP;So;0;ON;;;;;N;;;;;
+2658;WHITE CHESS KNIGHT;So;0;ON;;;;;N;;;;;
+2659;WHITE CHESS PAWN;So;0;ON;;;;;N;;;;;
+265A;BLACK CHESS KING;So;0;ON;;;;;N;;;;;
+265B;BLACK CHESS QUEEN;So;0;ON;;;;;N;;;;;
+265C;BLACK CHESS ROOK;So;0;ON;;;;;N;;;;;
+265D;BLACK CHESS BISHOP;So;0;ON;;;;;N;;;;;
+265E;BLACK CHESS KNIGHT;So;0;ON;;;;;N;;;;;
+265F;BLACK CHESS PAWN;So;0;ON;;;;;N;;;;;
+2660;BLACK SPADE SUIT;So;0;ON;;;;;N;;;;;
+2661;WHITE HEART SUIT;So;0;ON;;;;;N;;;;;
+2662;WHITE DIAMOND SUIT;So;0;ON;;;;;N;;;;;
+2663;BLACK CLUB SUIT;So;0;ON;;;;;N;;;;;
+2664;WHITE SPADE SUIT;So;0;ON;;;;;N;;;;;
+2665;BLACK HEART SUIT;So;0;ON;;;;;N;;;;;
+2666;BLACK DIAMOND SUIT;So;0;ON;;;;;N;;;;;
+2667;WHITE CLUB SUIT;So;0;ON;;;;;N;;;;;
+2668;HOT SPRINGS;So;0;ON;;;;;N;;;;;
+2669;QUARTER NOTE;So;0;ON;;;;;N;;;;;
+266A;EIGHTH NOTE;So;0;ON;;;;;N;;;;;
+266B;BEAMED EIGHTH NOTES;So;0;ON;;;;;N;BARRED EIGHTH NOTES;;;;
+266C;BEAMED SIXTEENTH NOTES;So;0;ON;;;;;N;BARRED SIXTEENTH NOTES;;;;
+266D;MUSIC FLAT SIGN;So;0;ON;;;;;N;FLAT;;;;
+266E;MUSIC NATURAL SIGN;So;0;ON;;;;;N;NATURAL;;;;
+266F;MUSIC SHARP SIGN;Sm;0;ON;;;;;N;SHARP;;;;
+2670;WEST SYRIAC CROSS;So;0;ON;;;;;N;;;;;
+2671;EAST SYRIAC CROSS;So;0;ON;;;;;N;;;;;
+2672;UNIVERSAL RECYCLING SYMBOL;So;0;ON;;;;;N;;;;;
+2673;RECYCLING SYMBOL FOR TYPE-1 PLASTICS;So;0;ON;;;;;N;;pete;;;
+2674;RECYCLING SYMBOL FOR TYPE-2 PLASTICS;So;0;ON;;;;;N;;hdpe;;;
+2675;RECYCLING SYMBOL FOR TYPE-3 PLASTICS;So;0;ON;;;;;N;;pvc;;;
+2676;RECYCLING SYMBOL FOR TYPE-4 PLASTICS;So;0;ON;;;;;N;;ldpe;;;
+2677;RECYCLING SYMBOL FOR TYPE-5 PLASTICS;So;0;ON;;;;;N;;pp;;;
+2678;RECYCLING SYMBOL FOR TYPE-6 PLASTICS;So;0;ON;;;;;N;;ps;;;
+2679;RECYCLING SYMBOL FOR TYPE-7 PLASTICS;So;0;ON;;;;;N;;other;;;
+267A;RECYCLING SYMBOL FOR GENERIC MATERIALS;So;0;ON;;;;;N;;;;;
+267B;BLACK UNIVERSAL RECYCLING SYMBOL;So;0;ON;;;;;N;;;;;
+267C;RECYCLED PAPER SYMBOL;So;0;ON;;;;;N;;;;;
+267D;PARTIALLY-RECYCLED PAPER SYMBOL;So;0;ON;;;;;N;;;;;
+2680;DIE FACE-1;So;0;ON;;;;;N;;;;;
+2681;DIE FACE-2;So;0;ON;;;;;N;;;;;
+2682;DIE FACE-3;So;0;ON;;;;;N;;;;;
+2683;DIE FACE-4;So;0;ON;;;;;N;;;;;
+2684;DIE FACE-5;So;0;ON;;;;;N;;;;;
+2685;DIE FACE-6;So;0;ON;;;;;N;;;;;
+2686;WHITE CIRCLE WITH DOT RIGHT;So;0;ON;;;;;N;;;;;
+2687;WHITE CIRCLE WITH TWO DOTS;So;0;ON;;;;;N;;;;;
+2688;BLACK CIRCLE WITH WHITE DOT RIGHT;So;0;ON;;;;;N;;;;;
+2689;BLACK CIRCLE WITH TWO WHITE DOTS;So;0;ON;;;;;N;;;;;
+268A;MONOGRAM FOR YANG;So;0;ON;;;;;N;;;;;
+268B;MONOGRAM FOR YIN;So;0;ON;;;;;N;;;;;
+268C;DIGRAM FOR GREATER YANG;So;0;ON;;;;;N;;;;;
+268D;DIGRAM FOR LESSER YIN;So;0;ON;;;;;N;;;;;
+268E;DIGRAM FOR LESSER YANG;So;0;ON;;;;;N;;;;;
+268F;DIGRAM FOR GREATER YIN;So;0;ON;;;;;N;;;;;
+2690;WHITE FLAG;So;0;ON;;;;;N;;;;;
+2691;BLACK FLAG;So;0;ON;;;;;N;;;;;
+26A0;WARNING SIGN;So;0;ON;;;;;N;;;;;
+26A1;HIGH VOLTAGE SIGN;So;0;ON;;;;;N;;;;;
+2701;UPPER BLADE SCISSORS;So;0;ON;;;;;N;;;;;
+2702;BLACK SCISSORS;So;0;ON;;;;;N;;;;;
+2703;LOWER BLADE SCISSORS;So;0;ON;;;;;N;;;;;
+2704;WHITE SCISSORS;So;0;ON;;;;;N;;;;;
+2706;TELEPHONE LOCATION SIGN;So;0;ON;;;;;N;;;;;
+2707;TAPE DRIVE;So;0;ON;;;;;N;;;;;
+2708;AIRPLANE;So;0;ON;;;;;N;;;;;
+2709;ENVELOPE;So;0;ON;;;;;N;;;;;
+270C;VICTORY HAND;So;0;ON;;;;;N;;;;;
+270D;WRITING HAND;So;0;ON;;;;;N;;;;;
+270E;LOWER RIGHT PENCIL;So;0;ON;;;;;N;;;;;
+270F;PENCIL;So;0;ON;;;;;N;;;;;
+2710;UPPER RIGHT PENCIL;So;0;ON;;;;;N;;;;;
+2711;WHITE NIB;So;0;ON;;;;;N;;;;;
+2712;BLACK NIB;So;0;ON;;;;;N;;;;;
+2713;CHECK MARK;So;0;ON;;;;;N;;;;;
+2714;HEAVY CHECK MARK;So;0;ON;;;;;N;;;;;
+2715;MULTIPLICATION X;So;0;ON;;;;;N;;;;;
+2716;HEAVY MULTIPLICATION X;So;0;ON;;;;;N;;;;;
+2717;BALLOT X;So;0;ON;;;;;N;;;;;
+2718;HEAVY BALLOT X;So;0;ON;;;;;N;;;;;
+2719;OUTLINED GREEK CROSS;So;0;ON;;;;;N;;;;;
+271A;HEAVY GREEK CROSS;So;0;ON;;;;;N;;;;;
+271B;OPEN CENTRE CROSS;So;0;ON;;;;;N;OPEN CENTER CROSS;;;;
+271C;HEAVY OPEN CENTRE CROSS;So;0;ON;;;;;N;HEAVY OPEN CENTER CROSS;;;;
+271D;LATIN CROSS;So;0;ON;;;;;N;;;;;
+271E;SHADOWED WHITE LATIN CROSS;So;0;ON;;;;;N;;;;;
+271F;OUTLINED LATIN CROSS;So;0;ON;;;;;N;;;;;
+2720;MALTESE CROSS;So;0;ON;;;;;N;;;;;
+2721;STAR OF DAVID;So;0;ON;;;;;N;;;;;
+2722;FOUR TEARDROP-SPOKED ASTERISK;So;0;ON;;;;;N;;;;;
+2723;FOUR BALLOON-SPOKED ASTERISK;So;0;ON;;;;;N;;;;;
+2724;HEAVY FOUR BALLOON-SPOKED ASTERISK;So;0;ON;;;;;N;;;;;
+2725;FOUR CLUB-SPOKED ASTERISK;So;0;ON;;;;;N;;;;;
+2726;BLACK FOUR POINTED STAR;So;0;ON;;;;;N;;;;;
+2727;WHITE FOUR POINTED STAR;So;0;ON;;;;;N;;;;;
+2729;STRESS OUTLINED WHITE STAR;So;0;ON;;;;;N;;;;;
+272A;CIRCLED WHITE STAR;So;0;ON;;;;;N;;;;;
+272B;OPEN CENTRE BLACK STAR;So;0;ON;;;;;N;OPEN CENTER BLACK STAR;;;;
+272C;BLACK CENTRE WHITE STAR;So;0;ON;;;;;N;BLACK CENTER WHITE STAR;;;;
+272D;OUTLINED BLACK STAR;So;0;ON;;;;;N;;;;;
+272E;HEAVY OUTLINED BLACK STAR;So;0;ON;;;;;N;;;;;
+272F;PINWHEEL STAR;So;0;ON;;;;;N;;;;;
+2730;SHADOWED WHITE STAR;So;0;ON;;;;;N;;;;;
+2731;HEAVY ASTERISK;So;0;ON;;;;;N;;;;;
+2732;OPEN CENTRE ASTERISK;So;0;ON;;;;;N;OPEN CENTER ASTERISK;;;;
+2733;EIGHT SPOKED ASTERISK;So;0;ON;;;;;N;;;;;
+2734;EIGHT POINTED BLACK STAR;So;0;ON;;;;;N;;;;;
+2735;EIGHT POINTED PINWHEEL STAR;So;0;ON;;;;;N;;;;;
+2736;SIX POINTED BLACK STAR;So;0;ON;;;;;N;;;;;
+2737;EIGHT POINTED RECTILINEAR BLACK STAR;So;0;ON;;;;;N;;;;;
+2738;HEAVY EIGHT POINTED RECTILINEAR BLACK STAR;So;0;ON;;;;;N;;;;;
+2739;TWELVE POINTED BLACK STAR;So;0;ON;;;;;N;;;;;
+273A;SIXTEEN POINTED ASTERISK;So;0;ON;;;;;N;;;;;
+273B;TEARDROP-SPOKED ASTERISK;So;0;ON;;;;;N;;;;;
+273C;OPEN CENTRE TEARDROP-SPOKED ASTERISK;So;0;ON;;;;;N;OPEN CENTER TEARDROP-SPOKED ASTERISK;;;;
+273D;HEAVY TEARDROP-SPOKED ASTERISK;So;0;ON;;;;;N;;;;;
+273E;SIX PETALLED BLACK AND WHITE FLORETTE;So;0;ON;;;;;N;;;;;
+273F;BLACK FLORETTE;So;0;ON;;;;;N;;;;;
+2740;WHITE FLORETTE;So;0;ON;;;;;N;;;;;
+2741;EIGHT PETALLED OUTLINED BLACK FLORETTE;So;0;ON;;;;;N;;;;;
+2742;CIRCLED OPEN CENTRE EIGHT POINTED STAR;So;0;ON;;;;;N;CIRCLED OPEN CENTER EIGHT POINTED STAR;;;;
+2743;HEAVY TEARDROP-SPOKED PINWHEEL ASTERISK;So;0;ON;;;;;N;;;;;
+2744;SNOWFLAKE;So;0;ON;;;;;N;;;;;
+2745;TIGHT TRIFOLIATE SNOWFLAKE;So;0;ON;;;;;N;;;;;
+2746;HEAVY CHEVRON SNOWFLAKE;So;0;ON;;;;;N;;;;;
+2747;SPARKLE;So;0;ON;;;;;N;;;;;
+2748;HEAVY SPARKLE;So;0;ON;;;;;N;;;;;
+2749;BALLOON-SPOKED ASTERISK;So;0;ON;;;;;N;;;;;
+274A;EIGHT TEARDROP-SPOKED PROPELLER ASTERISK;So;0;ON;;;;;N;;;;;
+274B;HEAVY EIGHT TEARDROP-SPOKED PROPELLER ASTERISK;So;0;ON;;;;;N;;;;;
+274D;SHADOWED WHITE CIRCLE;So;0;ON;;;;;N;;;;;
+274F;LOWER RIGHT DROP-SHADOWED WHITE SQUARE;So;0;ON;;;;;N;;;;;
+2750;UPPER RIGHT DROP-SHADOWED WHITE SQUARE;So;0;ON;;;;;N;;;;;
+2751;LOWER RIGHT SHADOWED WHITE SQUARE;So;0;ON;;;;;N;;;;;
+2752;UPPER RIGHT SHADOWED WHITE SQUARE;So;0;ON;;;;;N;;;;;
+2756;BLACK DIAMOND MINUS WHITE X;So;0;ON;;;;;N;;;;;
+2758;LIGHT VERTICAL BAR;So;0;ON;;;;;N;;;;;
+2759;MEDIUM VERTICAL BAR;So;0;ON;;;;;N;;;;;
+275A;HEAVY VERTICAL BAR;So;0;ON;;;;;N;;;;;
+275B;HEAVY SINGLE TURNED COMMA QUOTATION MARK ORNAMENT;So;0;ON;;;;;N;;;;;
+275C;HEAVY SINGLE COMMA QUOTATION MARK ORNAMENT;So;0;ON;;;;;N;;;;;
+275D;HEAVY DOUBLE TURNED COMMA QUOTATION MARK ORNAMENT;So;0;ON;;;;;N;;;;;
+275E;HEAVY DOUBLE COMMA QUOTATION MARK ORNAMENT;So;0;ON;;;;;N;;;;;
+2761;CURVED STEM PARAGRAPH SIGN ORNAMENT;So;0;ON;;;;;N;;;;;
+2762;HEAVY EXCLAMATION MARK ORNAMENT;So;0;ON;;;;;N;;;;;
+2763;HEAVY HEART EXCLAMATION MARK ORNAMENT;So;0;ON;;;;;N;;;;;
+2764;HEAVY BLACK HEART;So;0;ON;;;;;N;;;;;
+2765;ROTATED HEAVY BLACK HEART BULLET;So;0;ON;;;;;N;;;;;
+2766;FLORAL HEART;So;0;ON;;;;;N;;;;;
+2767;ROTATED FLORAL HEART BULLET;So;0;ON;;;;;N;;;;;
+2768;MEDIUM LEFT PARENTHESIS ORNAMENT;Ps;0;ON;;;;;Y;;;;;
+2769;MEDIUM RIGHT PARENTHESIS ORNAMENT;Pe;0;ON;;;;;Y;;;;;
+276A;MEDIUM FLATTENED LEFT PARENTHESIS ORNAMENT;Ps;0;ON;;;;;Y;;;;;
+276B;MEDIUM FLATTENED RIGHT PARENTHESIS ORNAMENT;Pe;0;ON;;;;;Y;;;;;
+276C;MEDIUM LEFT-POINTING ANGLE BRACKET ORNAMENT;Ps;0;ON;;;;;Y;;;;;
+276D;MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT;Pe;0;ON;;;;;Y;;;;;
+276E;HEAVY LEFT-POINTING ANGLE QUOTATION MARK ORNAMENT;Ps;0;ON;;;;;Y;;;;;
+276F;HEAVY RIGHT-POINTING ANGLE QUOTATION MARK ORNAMENT;Pe;0;ON;;;;;Y;;;;;
+2770;HEAVY LEFT-POINTING ANGLE BRACKET ORNAMENT;Ps;0;ON;;;;;Y;;;;;
+2771;HEAVY RIGHT-POINTING ANGLE BRACKET ORNAMENT;Pe;0;ON;;;;;Y;;;;;
+2772;LIGHT LEFT TORTOISE SHELL BRACKET ORNAMENT;Ps;0;ON;;;;;Y;;;;;
+2773;LIGHT RIGHT TORTOISE SHELL BRACKET ORNAMENT;Pe;0;ON;;;;;Y;;;;;
+2774;MEDIUM LEFT CURLY BRACKET ORNAMENT;Ps;0;ON;;;;;Y;;;;;
+2775;MEDIUM RIGHT CURLY BRACKET ORNAMENT;Pe;0;ON;;;;;Y;;;;;
+2776;DINGBAT NEGATIVE CIRCLED DIGIT ONE;No;0;ON;;;1;1;N;INVERSE CIRCLED DIGIT ONE;;;;
+2777;DINGBAT NEGATIVE CIRCLED DIGIT TWO;No;0;ON;;;2;2;N;INVERSE CIRCLED DIGIT TWO;;;;
+2778;DINGBAT NEGATIVE CIRCLED DIGIT THREE;No;0;ON;;;3;3;N;INVERSE CIRCLED DIGIT THREE;;;;
+2779;DINGBAT NEGATIVE CIRCLED DIGIT FOUR;No;0;ON;;;4;4;N;INVERSE CIRCLED DIGIT FOUR;;;;
+277A;DINGBAT NEGATIVE CIRCLED DIGIT FIVE;No;0;ON;;;5;5;N;INVERSE CIRCLED DIGIT FIVE;;;;
+277B;DINGBAT NEGATIVE CIRCLED DIGIT SIX;No;0;ON;;;6;6;N;INVERSE CIRCLED DIGIT SIX;;;;
+277C;DINGBAT NEGATIVE CIRCLED DIGIT SEVEN;No;0;ON;;;7;7;N;INVERSE CIRCLED DIGIT SEVEN;;;;
+277D;DINGBAT NEGATIVE CIRCLED DIGIT EIGHT;No;0;ON;;;8;8;N;INVERSE CIRCLED DIGIT EIGHT;;;;
+277E;DINGBAT NEGATIVE CIRCLED DIGIT NINE;No;0;ON;;;9;9;N;INVERSE CIRCLED DIGIT NINE;;;;
+277F;DINGBAT NEGATIVE CIRCLED NUMBER TEN;No;0;ON;;;;10;N;INVERSE CIRCLED NUMBER TEN;;;;
+2780;DINGBAT CIRCLED SANS-SERIF DIGIT ONE;No;0;ON;;;1;1;N;CIRCLED SANS-SERIF DIGIT ONE;;;;
+2781;DINGBAT CIRCLED SANS-SERIF DIGIT TWO;No;0;ON;;;2;2;N;CIRCLED SANS-SERIF DIGIT TWO;;;;
+2782;DINGBAT CIRCLED SANS-SERIF DIGIT THREE;No;0;ON;;;3;3;N;CIRCLED SANS-SERIF DIGIT THREE;;;;
+2783;DINGBAT CIRCLED SANS-SERIF DIGIT FOUR;No;0;ON;;;4;4;N;CIRCLED SANS-SERIF DIGIT FOUR;;;;
+2784;DINGBAT CIRCLED SANS-SERIF DIGIT FIVE;No;0;ON;;;5;5;N;CIRCLED SANS-SERIF DIGIT FIVE;;;;
+2785;DINGBAT CIRCLED SANS-SERIF DIGIT SIX;No;0;ON;;;6;6;N;CIRCLED SANS-SERIF DIGIT SIX;;;;
+2786;DINGBAT CIRCLED SANS-SERIF DIGIT SEVEN;No;0;ON;;;7;7;N;CIRCLED SANS-SERIF DIGIT SEVEN;;;;
+2787;DINGBAT CIRCLED SANS-SERIF DIGIT EIGHT;No;0;ON;;;8;8;N;CIRCLED SANS-SERIF DIGIT EIGHT;;;;
+2788;DINGBAT CIRCLED SANS-SERIF DIGIT NINE;No;0;ON;;;9;9;N;CIRCLED SANS-SERIF DIGIT NINE;;;;
+2789;DINGBAT CIRCLED SANS-SERIF NUMBER TEN;No;0;ON;;;;10;N;CIRCLED SANS-SERIF NUMBER TEN;;;;
+278A;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT ONE;No;0;ON;;;1;1;N;INVERSE CIRCLED SANS-SERIF DIGIT ONE;;;;
+278B;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT TWO;No;0;ON;;;2;2;N;INVERSE CIRCLED SANS-SERIF DIGIT TWO;;;;
+278C;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT THREE;No;0;ON;;;3;3;N;INVERSE CIRCLED SANS-SERIF DIGIT THREE;;;;
+278D;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT FOUR;No;0;ON;;;4;4;N;INVERSE CIRCLED SANS-SERIF DIGIT FOUR;;;;
+278E;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT FIVE;No;0;ON;;;5;5;N;INVERSE CIRCLED SANS-SERIF DIGIT FIVE;;;;
+278F;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT SIX;No;0;ON;;;6;6;N;INVERSE CIRCLED SANS-SERIF DIGIT SIX;;;;
+2790;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT SEVEN;No;0;ON;;;7;7;N;INVERSE CIRCLED SANS-SERIF DIGIT SEVEN;;;;
+2791;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT EIGHT;No;0;ON;;;8;8;N;INVERSE CIRCLED SANS-SERIF DIGIT EIGHT;;;;
+2792;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT NINE;No;0;ON;;;9;9;N;INVERSE CIRCLED SANS-SERIF DIGIT NINE;;;;
+2793;DINGBAT NEGATIVE CIRCLED SANS-SERIF NUMBER TEN;No;0;ON;;;;10;N;INVERSE CIRCLED SANS-SERIF NUMBER TEN;;;;
+2794;HEAVY WIDE-HEADED RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY WIDE-HEADED RIGHT ARROW;;;;
+2798;HEAVY SOUTH EAST ARROW;So;0;ON;;;;;N;HEAVY LOWER RIGHT ARROW;;;;
+2799;HEAVY RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY RIGHT ARROW;;;;
+279A;HEAVY NORTH EAST ARROW;So;0;ON;;;;;N;HEAVY UPPER RIGHT ARROW;;;;
+279B;DRAFTING POINT RIGHTWARDS ARROW;So;0;ON;;;;;N;DRAFTING POINT RIGHT ARROW;;;;
+279C;HEAVY ROUND-TIPPED RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY ROUND-TIPPED RIGHT ARROW;;;;
+279D;TRIANGLE-HEADED RIGHTWARDS ARROW;So;0;ON;;;;;N;TRIANGLE-HEADED RIGHT ARROW;;;;
+279E;HEAVY TRIANGLE-HEADED RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY TRIANGLE-HEADED RIGHT ARROW;;;;
+279F;DASHED TRIANGLE-HEADED RIGHTWARDS ARROW;So;0;ON;;;;;N;DASHED TRIANGLE-HEADED RIGHT ARROW;;;;
+27A0;HEAVY DASHED TRIANGLE-HEADED RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY DASHED TRIANGLE-HEADED RIGHT ARROW;;;;
+27A1;BLACK RIGHTWARDS ARROW;So;0;ON;;;;;N;BLACK RIGHT ARROW;;;;
+27A2;THREE-D TOP-LIGHTED RIGHTWARDS ARROWHEAD;So;0;ON;;;;;N;THREE-D TOP-LIGHTED RIGHT ARROWHEAD;;;;
+27A3;THREE-D BOTTOM-LIGHTED RIGHTWARDS ARROWHEAD;So;0;ON;;;;;N;THREE-D BOTTOM-LIGHTED RIGHT ARROWHEAD;;;;
+27A4;BLACK RIGHTWARDS ARROWHEAD;So;0;ON;;;;;N;BLACK RIGHT ARROWHEAD;;;;
+27A5;HEAVY BLACK CURVED DOWNWARDS AND RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY BLACK CURVED DOWN AND RIGHT ARROW;;;;
+27A6;HEAVY BLACK CURVED UPWARDS AND RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY BLACK CURVED UP AND RIGHT ARROW;;;;
+27A7;SQUAT BLACK RIGHTWARDS ARROW;So;0;ON;;;;;N;SQUAT BLACK RIGHT ARROW;;;;
+27A8;HEAVY CONCAVE-POINTED BLACK RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY CONCAVE-POINTED BLACK RIGHT ARROW;;;;
+27A9;RIGHT-SHADED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;RIGHT-SHADED WHITE RIGHT ARROW;;;;
+27AA;LEFT-SHADED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;LEFT-SHADED WHITE RIGHT ARROW;;;;
+27AB;BACK-TILTED SHADOWED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;BACK-TILTED SHADOWED WHITE RIGHT ARROW;;;;
+27AC;FRONT-TILTED SHADOWED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;FRONT-TILTED SHADOWED WHITE RIGHT ARROW;;;;
+27AD;HEAVY LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY LOWER RIGHT-SHADOWED WHITE RIGHT ARROW;;;;
+27AE;HEAVY UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY UPPER RIGHT-SHADOWED WHITE RIGHT ARROW;;;;
+27AF;NOTCHED LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;NOTCHED LOWER RIGHT-SHADOWED WHITE RIGHT ARROW;;;;
+27B1;NOTCHED UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;NOTCHED UPPER RIGHT-SHADOWED WHITE RIGHT ARROW;;;;
+27B2;CIRCLED HEAVY WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;CIRCLED HEAVY WHITE RIGHT ARROW;;;;
+27B3;WHITE-FEATHERED RIGHTWARDS ARROW;So;0;ON;;;;;N;WHITE-FEATHERED RIGHT ARROW;;;;
+27B4;BLACK-FEATHERED SOUTH EAST ARROW;So;0;ON;;;;;N;BLACK-FEATHERED LOWER RIGHT ARROW;;;;
+27B5;BLACK-FEATHERED RIGHTWARDS ARROW;So;0;ON;;;;;N;BLACK-FEATHERED RIGHT ARROW;;;;
+27B6;BLACK-FEATHERED NORTH EAST ARROW;So;0;ON;;;;;N;BLACK-FEATHERED UPPER RIGHT ARROW;;;;
+27B7;HEAVY BLACK-FEATHERED SOUTH EAST ARROW;So;0;ON;;;;;N;HEAVY BLACK-FEATHERED LOWER RIGHT ARROW;;;;
+27B8;HEAVY BLACK-FEATHERED RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY BLACK-FEATHERED RIGHT ARROW;;;;
+27B9;HEAVY BLACK-FEATHERED NORTH EAST ARROW;So;0;ON;;;;;N;HEAVY BLACK-FEATHERED UPPER RIGHT ARROW;;;;
+27BA;TEARDROP-BARBED RIGHTWARDS ARROW;So;0;ON;;;;;N;TEARDROP-BARBED RIGHT ARROW;;;;
+27BB;HEAVY TEARDROP-SHANKED RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY TEARDROP-SHANKED RIGHT ARROW;;;;
+27BC;WEDGE-TAILED RIGHTWARDS ARROW;So;0;ON;;;;;N;WEDGE-TAILED RIGHT ARROW;;;;
+27BD;HEAVY WEDGE-TAILED RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY WEDGE-TAILED RIGHT ARROW;;;;
+27BE;OPEN-OUTLINED RIGHTWARDS ARROW;So;0;ON;;;;;N;OPEN-OUTLINED RIGHT ARROW;;;;
+27D0;WHITE DIAMOND WITH CENTRED DOT;Sm;0;ON;;;;;N;;;;;
+27D1;AND WITH DOT;Sm;0;ON;;;;;N;;;;;
+27D2;ELEMENT OF OPENING UPWARDS;Sm;0;ON;;;;;N;;;;;
+27D3;LOWER RIGHT CORNER WITH DOT;Sm;0;ON;;;;;Y;;;;;
+27D4;UPPER LEFT CORNER WITH DOT;Sm;0;ON;;;;;Y;;;;;
+27D5;LEFT OUTER JOIN;Sm;0;ON;;;;;Y;;;;;
+27D6;RIGHT OUTER JOIN;Sm;0;ON;;;;;Y;;;;;
+27D7;FULL OUTER JOIN;Sm;0;ON;;;;;N;;;;;
+27D8;LARGE UP TACK;Sm;0;ON;;;;;N;;;;;
+27D9;LARGE DOWN TACK;Sm;0;ON;;;;;N;;;;;
+27DA;LEFT AND RIGHT DOUBLE TURNSTILE;Sm;0;ON;;;;;N;;;;;
+27DB;LEFT AND RIGHT TACK;Sm;0;ON;;;;;N;;;;;
+27DC;LEFT MULTIMAP;Sm;0;ON;;;;;Y;;;;;
+27DD;LONG RIGHT TACK;Sm;0;ON;;;;;Y;;;;;
+27DE;LONG LEFT TACK;Sm;0;ON;;;;;Y;;;;;
+27DF;UP TACK WITH CIRCLE ABOVE;Sm;0;ON;;;;;N;;;;;
+27E0;LOZENGE DIVIDED BY HORIZONTAL RULE;Sm;0;ON;;;;;N;;;;;
+27E1;WHITE CONCAVE-SIDED DIAMOND;Sm;0;ON;;;;;N;;;;;
+27E2;WHITE CONCAVE-SIDED DIAMOND WITH LEFTWARDS TICK;Sm;0;ON;;;;;Y;;;;;
+27E3;WHITE CONCAVE-SIDED DIAMOND WITH RIGHTWARDS TICK;Sm;0;ON;;;;;Y;;;;;
+27E4;WHITE SQUARE WITH LEFTWARDS TICK;Sm;0;ON;;;;;Y;;;;;
+27E5;WHITE SQUARE WITH RIGHTWARDS TICK;Sm;0;ON;;;;;Y;;;;;
+27E6;MATHEMATICAL LEFT WHITE SQUARE BRACKET;Ps;0;ON;;;;;Y;;;;;
+27E7;MATHEMATICAL RIGHT WHITE SQUARE BRACKET;Pe;0;ON;;;;;Y;;;;;
+27E8;MATHEMATICAL LEFT ANGLE BRACKET;Ps;0;ON;;;;;Y;;;;;
+27E9;MATHEMATICAL RIGHT ANGLE BRACKET;Pe;0;ON;;;;;Y;;;;;
+27EA;MATHEMATICAL LEFT DOUBLE ANGLE BRACKET;Ps;0;ON;;;;;Y;;;;;
+27EB;MATHEMATICAL RIGHT DOUBLE ANGLE BRACKET;Pe;0;ON;;;;;Y;;;;;
+27F0;UPWARDS QUADRUPLE ARROW;Sm;0;ON;;;;;N;;;;;
+27F1;DOWNWARDS QUADRUPLE ARROW;Sm;0;ON;;;;;N;;;;;
+27F2;ANTICLOCKWISE GAPPED CIRCLE ARROW;Sm;0;ON;;;;;N;;;;;
+27F3;CLOCKWISE GAPPED CIRCLE ARROW;Sm;0;ON;;;;;N;;;;;
+27F4;RIGHT ARROW WITH CIRCLED PLUS;Sm;0;ON;;;;;N;;;;;
+27F5;LONG LEFTWARDS ARROW;Sm;0;ON;;;;;N;;;;;
+27F6;LONG RIGHTWARDS ARROW;Sm;0;ON;;;;;N;;;;;
+27F7;LONG LEFT RIGHT ARROW;Sm;0;ON;;;;;N;;;;;
+27F8;LONG LEFTWARDS DOUBLE ARROW;Sm;0;ON;;;;;N;;;;;
+27F9;LONG RIGHTWARDS DOUBLE ARROW;Sm;0;ON;;;;;N;;;;;
+27FA;LONG LEFT RIGHT DOUBLE ARROW;Sm;0;ON;;;;;N;;;;;
+27FB;LONG LEFTWARDS ARROW FROM BAR;Sm;0;ON;;;;;N;;;;;
+27FC;LONG RIGHTWARDS ARROW FROM BAR;Sm;0;ON;;;;;N;;;;;
+27FD;LONG LEFTWARDS DOUBLE ARROW FROM BAR;Sm;0;ON;;;;;N;;;;;
+27FE;LONG RIGHTWARDS DOUBLE ARROW FROM BAR;Sm;0;ON;;;;;N;;;;;
+27FF;LONG RIGHTWARDS SQUIGGLE ARROW;Sm;0;ON;;;;;N;;;;;
+2800;BRAILLE PATTERN BLANK;So;0;L;;;;;N;;;;;
+2801;BRAILLE PATTERN DOTS-1;So;0;L;;;;;N;;;;;
+2802;BRAILLE PATTERN DOTS-2;So;0;L;;;;;N;;;;;
+2803;BRAILLE PATTERN DOTS-12;So;0;L;;;;;N;;;;;
+2804;BRAILLE PATTERN DOTS-3;So;0;L;;;;;N;;;;;
+2805;BRAILLE PATTERN DOTS-13;So;0;L;;;;;N;;;;;
+2806;BRAILLE PATTERN DOTS-23;So;0;L;;;;;N;;;;;
+2807;BRAILLE PATTERN DOTS-123;So;0;L;;;;;N;;;;;
+2808;BRAILLE PATTERN DOTS-4;So;0;L;;;;;N;;;;;
+2809;BRAILLE PATTERN DOTS-14;So;0;L;;;;;N;;;;;
+280A;BRAILLE PATTERN DOTS-24;So;0;L;;;;;N;;;;;
+280B;BRAILLE PATTERN DOTS-124;So;0;L;;;;;N;;;;;
+280C;BRAILLE PATTERN DOTS-34;So;0;L;;;;;N;;;;;
+280D;BRAILLE PATTERN DOTS-134;So;0;L;;;;;N;;;;;
+280E;BRAILLE PATTERN DOTS-234;So;0;L;;;;;N;;;;;
+280F;BRAILLE PATTERN DOTS-1234;So;0;L;;;;;N;;;;;
+2810;BRAILLE PATTERN DOTS-5;So;0;L;;;;;N;;;;;
+2811;BRAILLE PATTERN DOTS-15;So;0;L;;;;;N;;;;;
+2812;BRAILLE PATTERN DOTS-25;So;0;L;;;;;N;;;;;
+2813;BRAILLE PATTERN DOTS-125;So;0;L;;;;;N;;;;;
+2814;BRAILLE PATTERN DOTS-35;So;0;L;;;;;N;;;;;
+2815;BRAILLE PATTERN DOTS-135;So;0;L;;;;;N;;;;;
+2816;BRAILLE PATTERN DOTS-235;So;0;L;;;;;N;;;;;
+2817;BRAILLE PATTERN DOTS-1235;So;0;L;;;;;N;;;;;
+2818;BRAILLE PATTERN DOTS-45;So;0;L;;;;;N;;;;;
+2819;BRAILLE PATTERN DOTS-145;So;0;L;;;;;N;;;;;
+281A;BRAILLE PATTERN DOTS-245;So;0;L;;;;;N;;;;;
+281B;BRAILLE PATTERN DOTS-1245;So;0;L;;;;;N;;;;;
+281C;BRAILLE PATTERN DOTS-345;So;0;L;;;;;N;;;;;
+281D;BRAILLE PATTERN DOTS-1345;So;0;L;;;;;N;;;;;
+281E;BRAILLE PATTERN DOTS-2345;So;0;L;;;;;N;;;;;
+281F;BRAILLE PATTERN DOTS-12345;So;0;L;;;;;N;;;;;
+2820;BRAILLE PATTERN DOTS-6;So;0;L;;;;;N;;;;;
+2821;BRAILLE PATTERN DOTS-16;So;0;L;;;;;N;;;;;
+2822;BRAILLE PATTERN DOTS-26;So;0;L;;;;;N;;;;;
+2823;BRAILLE PATTERN DOTS-126;So;0;L;;;;;N;;;;;
+2824;BRAILLE PATTERN DOTS-36;So;0;L;;;;;N;;;;;
+2825;BRAILLE PATTERN DOTS-136;So;0;L;;;;;N;;;;;
+2826;BRAILLE PATTERN DOTS-236;So;0;L;;;;;N;;;;;
+2827;BRAILLE PATTERN DOTS-1236;So;0;L;;;;;N;;;;;
+2828;BRAILLE PATTERN DOTS-46;So;0;L;;;;;N;;;;;
+2829;BRAILLE PATTERN DOTS-146;So;0;L;;;;;N;;;;;
+282A;BRAILLE PATTERN DOTS-246;So;0;L;;;;;N;;;;;
+282B;BRAILLE PATTERN DOTS-1246;So;0;L;;;;;N;;;;;
+282C;BRAILLE PATTERN DOTS-346;So;0;L;;;;;N;;;;;
+282D;BRAILLE PATTERN DOTS-1346;So;0;L;;;;;N;;;;;
+282E;BRAILLE PATTERN DOTS-2346;So;0;L;;;;;N;;;;;
+282F;BRAILLE PATTERN DOTS-12346;So;0;L;;;;;N;;;;;
+2830;BRAILLE PATTERN DOTS-56;So;0;L;;;;;N;;;;;
+2831;BRAILLE PATTERN DOTS-156;So;0;L;;;;;N;;;;;
+2832;BRAILLE PATTERN DOTS-256;So;0;L;;;;;N;;;;;
+2833;BRAILLE PATTERN DOTS-1256;So;0;L;;;;;N;;;;;
+2834;BRAILLE PATTERN DOTS-356;So;0;L;;;;;N;;;;;
+2835;BRAILLE PATTERN DOTS-1356;So;0;L;;;;;N;;;;;
+2836;BRAILLE PATTERN DOTS-2356;So;0;L;;;;;N;;;;;
+2837;BRAILLE PATTERN DOTS-12356;So;0;L;;;;;N;;;;;
+2838;BRAILLE PATTERN DOTS-456;So;0;L;;;;;N;;;;;
+2839;BRAILLE PATTERN DOTS-1456;So;0;L;;;;;N;;;;;
+283A;BRAILLE PATTERN DOTS-2456;So;0;L;;;;;N;;;;;
+283B;BRAILLE PATTERN DOTS-12456;So;0;L;;;;;N;;;;;
+283C;BRAILLE PATTERN DOTS-3456;So;0;L;;;;;N;;;;;
+283D;BRAILLE PATTERN DOTS-13456;So;0;L;;;;;N;;;;;
+283E;BRAILLE PATTERN DOTS-23456;So;0;L;;;;;N;;;;;
+283F;BRAILLE PATTERN DOTS-123456;So;0;L;;;;;N;;;;;
+2840;BRAILLE PATTERN DOTS-7;So;0;L;;;;;N;;;;;
+2841;BRAILLE PATTERN DOTS-17;So;0;L;;;;;N;;;;;
+2842;BRAILLE PATTERN DOTS-27;So;0;L;;;;;N;;;;;
+2843;BRAILLE PATTERN DOTS-127;So;0;L;;;;;N;;;;;
+2844;BRAILLE PATTERN DOTS-37;So;0;L;;;;;N;;;;;
+2845;BRAILLE PATTERN DOTS-137;So;0;L;;;;;N;;;;;
+2846;BRAILLE PATTERN DOTS-237;So;0;L;;;;;N;;;;;
+2847;BRAILLE PATTERN DOTS-1237;So;0;L;;;;;N;;;;;
+2848;BRAILLE PATTERN DOTS-47;So;0;L;;;;;N;;;;;
+2849;BRAILLE PATTERN DOTS-147;So;0;L;;;;;N;;;;;
+284A;BRAILLE PATTERN DOTS-247;So;0;L;;;;;N;;;;;
+284B;BRAILLE PATTERN DOTS-1247;So;0;L;;;;;N;;;;;
+284C;BRAILLE PATTERN DOTS-347;So;0;L;;;;;N;;;;;
+284D;BRAILLE PATTERN DOTS-1347;So;0;L;;;;;N;;;;;
+284E;BRAILLE PATTERN DOTS-2347;So;0;L;;;;;N;;;;;
+284F;BRAILLE PATTERN DOTS-12347;So;0;L;;;;;N;;;;;
+2850;BRAILLE PATTERN DOTS-57;So;0;L;;;;;N;;;;;
+2851;BRAILLE PATTERN DOTS-157;So;0;L;;;;;N;;;;;
+2852;BRAILLE PATTERN DOTS-257;So;0;L;;;;;N;;;;;
+2853;BRAILLE PATTERN DOTS-1257;So;0;L;;;;;N;;;;;
+2854;BRAILLE PATTERN DOTS-357;So;0;L;;;;;N;;;;;
+2855;BRAILLE PATTERN DOTS-1357;So;0;L;;;;;N;;;;;
+2856;BRAILLE PATTERN DOTS-2357;So;0;L;;;;;N;;;;;
+2857;BRAILLE PATTERN DOTS-12357;So;0;L;;;;;N;;;;;
+2858;BRAILLE PATTERN DOTS-457;So;0;L;;;;;N;;;;;
+2859;BRAILLE PATTERN DOTS-1457;So;0;L;;;;;N;;;;;
+285A;BRAILLE PATTERN DOTS-2457;So;0;L;;;;;N;;;;;
+285B;BRAILLE PATTERN DOTS-12457;So;0;L;;;;;N;;;;;
+285C;BRAILLE PATTERN DOTS-3457;So;0;L;;;;;N;;;;;
+285D;BRAILLE PATTERN DOTS-13457;So;0;L;;;;;N;;;;;
+285E;BRAILLE PATTERN DOTS-23457;So;0;L;;;;;N;;;;;
+285F;BRAILLE PATTERN DOTS-123457;So;0;L;;;;;N;;;;;
+2860;BRAILLE PATTERN DOTS-67;So;0;L;;;;;N;;;;;
+2861;BRAILLE PATTERN DOTS-167;So;0;L;;;;;N;;;;;
+2862;BRAILLE PATTERN DOTS-267;So;0;L;;;;;N;;;;;
+2863;BRAILLE PATTERN DOTS-1267;So;0;L;;;;;N;;;;;
+2864;BRAILLE PATTERN DOTS-367;So;0;L;;;;;N;;;;;
+2865;BRAILLE PATTERN DOTS-1367;So;0;L;;;;;N;;;;;
+2866;BRAILLE PATTERN DOTS-2367;So;0;L;;;;;N;;;;;
+2867;BRAILLE PATTERN DOTS-12367;So;0;L;;;;;N;;;;;
+2868;BRAILLE PATTERN DOTS-467;So;0;L;;;;;N;;;;;
+2869;BRAILLE PATTERN DOTS-1467;So;0;L;;;;;N;;;;;
+286A;BRAILLE PATTERN DOTS-2467;So;0;L;;;;;N;;;;;
+286B;BRAILLE PATTERN DOTS-12467;So;0;L;;;;;N;;;;;
+286C;BRAILLE PATTERN DOTS-3467;So;0;L;;;;;N;;;;;
+286D;BRAILLE PATTERN DOTS-13467;So;0;L;;;;;N;;;;;
+286E;BRAILLE PATTERN DOTS-23467;So;0;L;;;;;N;;;;;
+286F;BRAILLE PATTERN DOTS-123467;So;0;L;;;;;N;;;;;
+2870;BRAILLE PATTERN DOTS-567;So;0;L;;;;;N;;;;;
+2871;BRAILLE PATTERN DOTS-1567;So;0;L;;;;;N;;;;;
+2872;BRAILLE PATTERN DOTS-2567;So;0;L;;;;;N;;;;;
+2873;BRAILLE PATTERN DOTS-12567;So;0;L;;;;;N;;;;;
+2874;BRAILLE PATTERN DOTS-3567;So;0;L;;;;;N;;;;;
+2875;BRAILLE PATTERN DOTS-13567;So;0;L;;;;;N;;;;;
+2876;BRAILLE PATTERN DOTS-23567;So;0;L;;;;;N;;;;;
+2877;BRAILLE PATTERN DOTS-123567;So;0;L;;;;;N;;;;;
+2878;BRAILLE PATTERN DOTS-4567;So;0;L;;;;;N;;;;;
+2879;BRAILLE PATTERN DOTS-14567;So;0;L;;;;;N;;;;;
+287A;BRAILLE PATTERN DOTS-24567;So;0;L;;;;;N;;;;;
+287B;BRAILLE PATTERN DOTS-124567;So;0;L;;;;;N;;;;;
+287C;BRAILLE PATTERN DOTS-34567;So;0;L;;;;;N;;;;;
+287D;BRAILLE PATTERN DOTS-134567;So;0;L;;;;;N;;;;;
+287E;BRAILLE PATTERN DOTS-234567;So;0;L;;;;;N;;;;;
+287F;BRAILLE PATTERN DOTS-1234567;So;0;L;;;;;N;;;;;
+2880;BRAILLE PATTERN DOTS-8;So;0;L;;;;;N;;;;;
+2881;BRAILLE PATTERN DOTS-18;So;0;L;;;;;N;;;;;
+2882;BRAILLE PATTERN DOTS-28;So;0;L;;;;;N;;;;;
+2883;BRAILLE PATTERN DOTS-128;So;0;L;;;;;N;;;;;
+2884;BRAILLE PATTERN DOTS-38;So;0;L;;;;;N;;;;;
+2885;BRAILLE PATTERN DOTS-138;So;0;L;;;;;N;;;;;
+2886;BRAILLE PATTERN DOTS-238;So;0;L;;;;;N;;;;;
+2887;BRAILLE PATTERN DOTS-1238;So;0;L;;;;;N;;;;;
+2888;BRAILLE PATTERN DOTS-48;So;0;L;;;;;N;;;;;
+2889;BRAILLE PATTERN DOTS-148;So;0;L;;;;;N;;;;;
+288A;BRAILLE PATTERN DOTS-248;So;0;L;;;;;N;;;;;
+288B;BRAILLE PATTERN DOTS-1248;So;0;L;;;;;N;;;;;
+288C;BRAILLE PATTERN DOTS-348;So;0;L;;;;;N;;;;;
+288D;BRAILLE PATTERN DOTS-1348;So;0;L;;;;;N;;;;;
+288E;BRAILLE PATTERN DOTS-2348;So;0;L;;;;;N;;;;;
+288F;BRAILLE PATTERN DOTS-12348;So;0;L;;;;;N;;;;;
+2890;BRAILLE PATTERN DOTS-58;So;0;L;;;;;N;;;;;
+2891;BRAILLE PATTERN DOTS-158;So;0;L;;;;;N;;;;;
+2892;BRAILLE PATTERN DOTS-258;So;0;L;;;;;N;;;;;
+2893;BRAILLE PATTERN DOTS-1258;So;0;L;;;;;N;;;;;
+2894;BRAILLE PATTERN DOTS-358;So;0;L;;;;;N;;;;;
+2895;BRAILLE PATTERN DOTS-1358;So;0;L;;;;;N;;;;;
+2896;BRAILLE PATTERN DOTS-2358;So;0;L;;;;;N;;;;;
+2897;BRAILLE PATTERN DOTS-12358;So;0;L;;;;;N;;;;;
+2898;BRAILLE PATTERN DOTS-458;So;0;L;;;;;N;;;;;
+2899;BRAILLE PATTERN DOTS-1458;So;0;L;;;;;N;;;;;
+289A;BRAILLE PATTERN DOTS-2458;So;0;L;;;;;N;;;;;
+289B;BRAILLE PATTERN DOTS-12458;So;0;L;;;;;N;;;;;
+289C;BRAILLE PATTERN DOTS-3458;So;0;L;;;;;N;;;;;
+289D;BRAILLE PATTERN DOTS-13458;So;0;L;;;;;N;;;;;
+289E;BRAILLE PATTERN DOTS-23458;So;0;L;;;;;N;;;;;
+289F;BRAILLE PATTERN DOTS-123458;So;0;L;;;;;N;;;;;
+28A0;BRAILLE PATTERN DOTS-68;So;0;L;;;;;N;;;;;
+28A1;BRAILLE PATTERN DOTS-168;So;0;L;;;;;N;;;;;
+28A2;BRAILLE PATTERN DOTS-268;So;0;L;;;;;N;;;;;
+28A3;BRAILLE PATTERN DOTS-1268;So;0;L;;;;;N;;;;;
+28A4;BRAILLE PATTERN DOTS-368;So;0;L;;;;;N;;;;;
+28A5;BRAILLE PATTERN DOTS-1368;So;0;L;;;;;N;;;;;
+28A6;BRAILLE PATTERN DOTS-2368;So;0;L;;;;;N;;;;;
+28A7;BRAILLE PATTERN DOTS-12368;So;0;L;;;;;N;;;;;
+28A8;BRAILLE PATTERN DOTS-468;So;0;L;;;;;N;;;;;
+28A9;BRAILLE PATTERN DOTS-1468;So;0;L;;;;;N;;;;;
+28AA;BRAILLE PATTERN DOTS-2468;So;0;L;;;;;N;;;;;
+28AB;BRAILLE PATTERN DOTS-12468;So;0;L;;;;;N;;;;;
+28AC;BRAILLE PATTERN DOTS-3468;So;0;L;;;;;N;;;;;
+28AD;BRAILLE PATTERN DOTS-13468;So;0;L;;;;;N;;;;;
+28AE;BRAILLE PATTERN DOTS-23468;So;0;L;;;;;N;;;;;
+28AF;BRAILLE PATTERN DOTS-123468;So;0;L;;;;;N;;;;;
+28B0;BRAILLE PATTERN DOTS-568;So;0;L;;;;;N;;;;;
+28B1;BRAILLE PATTERN DOTS-1568;So;0;L;;;;;N;;;;;
+28B2;BRAILLE PATTERN DOTS-2568;So;0;L;;;;;N;;;;;
+28B3;BRAILLE PATTERN DOTS-12568;So;0;L;;;;;N;;;;;
+28B4;BRAILLE PATTERN DOTS-3568;So;0;L;;;;;N;;;;;
+28B5;BRAILLE PATTERN DOTS-13568;So;0;L;;;;;N;;;;;
+28B6;BRAILLE PATTERN DOTS-23568;So;0;L;;;;;N;;;;;
+28B7;BRAILLE PATTERN DOTS-123568;So;0;L;;;;;N;;;;;
+28B8;BRAILLE PATTERN DOTS-4568;So;0;L;;;;;N;;;;;
+28B9;BRAILLE PATTERN DOTS-14568;So;0;L;;;;;N;;;;;
+28BA;BRAILLE PATTERN DOTS-24568;So;0;L;;;;;N;;;;;
+28BB;BRAILLE PATTERN DOTS-124568;So;0;L;;;;;N;;;;;
+28BC;BRAILLE PATTERN DOTS-34568;So;0;L;;;;;N;;;;;
+28BD;BRAILLE PATTERN DOTS-134568;So;0;L;;;;;N;;;;;
+28BE;BRAILLE PATTERN DOTS-234568;So;0;L;;;;;N;;;;;
+28BF;BRAILLE PATTERN DOTS-1234568;So;0;L;;;;;N;;;;;
+28C0;BRAILLE PATTERN DOTS-78;So;0;L;;;;;N;;;;;
+28C1;BRAILLE PATTERN DOTS-178;So;0;L;;;;;N;;;;;
+28C2;BRAILLE PATTERN DOTS-278;So;0;L;;;;;N;;;;;
+28C3;BRAILLE PATTERN DOTS-1278;So;0;L;;;;;N;;;;;
+28C4;BRAILLE PATTERN DOTS-378;So;0;L;;;;;N;;;;;
+28C5;BRAILLE PATTERN DOTS-1378;So;0;L;;;;;N;;;;;
+28C6;BRAILLE PATTERN DOTS-2378;So;0;L;;;;;N;;;;;
+28C7;BRAILLE PATTERN DOTS-12378;So;0;L;;;;;N;;;;;
+28C8;BRAILLE PATTERN DOTS-478;So;0;L;;;;;N;;;;;
+28C9;BRAILLE PATTERN DOTS-1478;So;0;L;;;;;N;;;;;
+28CA;BRAILLE PATTERN DOTS-2478;So;0;L;;;;;N;;;;;
+28CB;BRAILLE PATTERN DOTS-12478;So;0;L;;;;;N;;;;;
+28CC;BRAILLE PATTERN DOTS-3478;So;0;L;;;;;N;;;;;
+28CD;BRAILLE PATTERN DOTS-13478;So;0;L;;;;;N;;;;;
+28CE;BRAILLE PATTERN DOTS-23478;So;0;L;;;;;N;;;;;
+28CF;BRAILLE PATTERN DOTS-123478;So;0;L;;;;;N;;;;;
+28D0;BRAILLE PATTERN DOTS-578;So;0;L;;;;;N;;;;;
+28D1;BRAILLE PATTERN DOTS-1578;So;0;L;;;;;N;;;;;
+28D2;BRAILLE PATTERN DOTS-2578;So;0;L;;;;;N;;;;;
+28D3;BRAILLE PATTERN DOTS-12578;So;0;L;;;;;N;;;;;
+28D4;BRAILLE PATTERN DOTS-3578;So;0;L;;;;;N;;;;;
+28D5;BRAILLE PATTERN DOTS-13578;So;0;L;;;;;N;;;;;
+28D6;BRAILLE PATTERN DOTS-23578;So;0;L;;;;;N;;;;;
+28D7;BRAILLE PATTERN DOTS-123578;So;0;L;;;;;N;;;;;
+28D8;BRAILLE PATTERN DOTS-4578;So;0;L;;;;;N;;;;;
+28D9;BRAILLE PATTERN DOTS-14578;So;0;L;;;;;N;;;;;
+28DA;BRAILLE PATTERN DOTS-24578;So;0;L;;;;;N;;;;;
+28DB;BRAILLE PATTERN DOTS-124578;So;0;L;;;;;N;;;;;
+28DC;BRAILLE PATTERN DOTS-34578;So;0;L;;;;;N;;;;;
+28DD;BRAILLE PATTERN DOTS-134578;So;0;L;;;;;N;;;;;
+28DE;BRAILLE PATTERN DOTS-234578;So;0;L;;;;;N;;;;;
+28DF;BRAILLE PATTERN DOTS-1234578;So;0;L;;;;;N;;;;;
+28E0;BRAILLE PATTERN DOTS-678;So;0;L;;;;;N;;;;;
+28E1;BRAILLE PATTERN DOTS-1678;So;0;L;;;;;N;;;;;
+28E2;BRAILLE PATTERN DOTS-2678;So;0;L;;;;;N;;;;;
+28E3;BRAILLE PATTERN DOTS-12678;So;0;L;;;;;N;;;;;
+28E4;BRAILLE PATTERN DOTS-3678;So;0;L;;;;;N;;;;;
+28E5;BRAILLE PATTERN DOTS-13678;So;0;L;;;;;N;;;;;
+28E6;BRAILLE PATTERN DOTS-23678;So;0;L;;;;;N;;;;;
+28E7;BRAILLE PATTERN DOTS-123678;So;0;L;;;;;N;;;;;
+28E8;BRAILLE PATTERN DOTS-4678;So;0;L;;;;;N;;;;;
+28E9;BRAILLE PATTERN DOTS-14678;So;0;L;;;;;N;;;;;
+28EA;BRAILLE PATTERN DOTS-24678;So;0;L;;;;;N;;;;;
+28EB;BRAILLE PATTERN DOTS-124678;So;0;L;;;;;N;;;;;
+28EC;BRAILLE PATTERN DOTS-34678;So;0;L;;;;;N;;;;;
+28ED;BRAILLE PATTERN DOTS-134678;So;0;L;;;;;N;;;;;
+28EE;BRAILLE PATTERN DOTS-234678;So;0;L;;;;;N;;;;;
+28EF;BRAILLE PATTERN DOTS-1234678;So;0;L;;;;;N;;;;;
+28F0;BRAILLE PATTERN DOTS-5678;So;0;L;;;;;N;;;;;
+28F1;BRAILLE PATTERN DOTS-15678;So;0;L;;;;;N;;;;;
+28F2;BRAILLE PATTERN DOTS-25678;So;0;L;;;;;N;;;;;
+28F3;BRAILLE PATTERN DOTS-125678;So;0;L;;;;;N;;;;;
+28F4;BRAILLE PATTERN DOTS-35678;So;0;L;;;;;N;;;;;
+28F5;BRAILLE PATTERN DOTS-135678;So;0;L;;;;;N;;;;;
+28F6;BRAILLE PATTERN DOTS-235678;So;0;L;;;;;N;;;;;
+28F7;BRAILLE PATTERN DOTS-1235678;So;0;L;;;;;N;;;;;
+28F8;BRAILLE PATTERN DOTS-45678;So;0;L;;;;;N;;;;;
+28F9;BRAILLE PATTERN DOTS-145678;So;0;L;;;;;N;;;;;
+28FA;BRAILLE PATTERN DOTS-245678;So;0;L;;;;;N;;;;;
+28FB;BRAILLE PATTERN DOTS-1245678;So;0;L;;;;;N;;;;;
+28FC;BRAILLE PATTERN DOTS-345678;So;0;L;;;;;N;;;;;
+28FD;BRAILLE PATTERN DOTS-1345678;So;0;L;;;;;N;;;;;
+28FE;BRAILLE PATTERN DOTS-2345678;So;0;L;;;;;N;;;;;
+28FF;BRAILLE PATTERN DOTS-12345678;So;0;L;;;;;N;;;;;
+2900;RIGHTWARDS TWO-HEADED ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+2901;RIGHTWARDS TWO-HEADED ARROW WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+2902;LEFTWARDS DOUBLE ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+2903;RIGHTWARDS DOUBLE ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+2904;LEFT RIGHT DOUBLE ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+2905;RIGHTWARDS TWO-HEADED ARROW FROM BAR;Sm;0;ON;;;;;N;;;;;
+2906;LEFTWARDS DOUBLE ARROW FROM BAR;Sm;0;ON;;;;;N;;;;;
+2907;RIGHTWARDS DOUBLE ARROW FROM BAR;Sm;0;ON;;;;;N;;;;;
+2908;DOWNWARDS ARROW WITH HORIZONTAL STROKE;Sm;0;ON;;;;;N;;;;;
+2909;UPWARDS ARROW WITH HORIZONTAL STROKE;Sm;0;ON;;;;;N;;;;;
+290A;UPWARDS TRIPLE ARROW;Sm;0;ON;;;;;N;;;;;
+290B;DOWNWARDS TRIPLE ARROW;Sm;0;ON;;;;;N;;;;;
+290C;LEFTWARDS DOUBLE DASH ARROW;Sm;0;ON;;;;;N;;;;;
+290D;RIGHTWARDS DOUBLE DASH ARROW;Sm;0;ON;;;;;N;;;;;
+290E;LEFTWARDS TRIPLE DASH ARROW;Sm;0;ON;;;;;N;;;;;
+290F;RIGHTWARDS TRIPLE DASH ARROW;Sm;0;ON;;;;;N;;;;;
+2910;RIGHTWARDS TWO-HEADED TRIPLE DASH ARROW;Sm;0;ON;;;;;N;;;;;
+2911;RIGHTWARDS ARROW WITH DOTTED STEM;Sm;0;ON;;;;;N;;;;;
+2912;UPWARDS ARROW TO BAR;Sm;0;ON;;;;;N;;;;;
+2913;DOWNWARDS ARROW TO BAR;Sm;0;ON;;;;;N;;;;;
+2914;RIGHTWARDS ARROW WITH TAIL WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+2915;RIGHTWARDS ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+2916;RIGHTWARDS TWO-HEADED ARROW WITH TAIL;Sm;0;ON;;;;;N;;;;;
+2917;RIGHTWARDS TWO-HEADED ARROW WITH TAIL WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+2918;RIGHTWARDS TWO-HEADED ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+2919;LEFTWARDS ARROW-TAIL;Sm;0;ON;;;;;N;;;;;
+291A;RIGHTWARDS ARROW-TAIL;Sm;0;ON;;;;;N;;;;;
+291B;LEFTWARDS DOUBLE ARROW-TAIL;Sm;0;ON;;;;;N;;;;;
+291C;RIGHTWARDS DOUBLE ARROW-TAIL;Sm;0;ON;;;;;N;;;;;
+291D;LEFTWARDS ARROW TO BLACK DIAMOND;Sm;0;ON;;;;;N;;;;;
+291E;RIGHTWARDS ARROW TO BLACK DIAMOND;Sm;0;ON;;;;;N;;;;;
+291F;LEFTWARDS ARROW FROM BAR TO BLACK DIAMOND;Sm;0;ON;;;;;N;;;;;
+2920;RIGHTWARDS ARROW FROM BAR TO BLACK DIAMOND;Sm;0;ON;;;;;N;;;;;
+2921;NORTH WEST AND SOUTH EAST ARROW;Sm;0;ON;;;;;N;;;;;
+2922;NORTH EAST AND SOUTH WEST ARROW;Sm;0;ON;;;;;N;;;;;
+2923;NORTH WEST ARROW WITH HOOK;Sm;0;ON;;;;;N;;;;;
+2924;NORTH EAST ARROW WITH HOOK;Sm;0;ON;;;;;N;;;;;
+2925;SOUTH EAST ARROW WITH HOOK;Sm;0;ON;;;;;N;;;;;
+2926;SOUTH WEST ARROW WITH HOOK;Sm;0;ON;;;;;N;;;;;
+2927;NORTH WEST ARROW AND NORTH EAST ARROW;Sm;0;ON;;;;;N;;;;;
+2928;NORTH EAST ARROW AND SOUTH EAST ARROW;Sm;0;ON;;;;;N;;;;;
+2929;SOUTH EAST ARROW AND SOUTH WEST ARROW;Sm;0;ON;;;;;N;;;;;
+292A;SOUTH WEST ARROW AND NORTH WEST ARROW;Sm;0;ON;;;;;N;;;;;
+292B;RISING DIAGONAL CROSSING FALLING DIAGONAL;Sm;0;ON;;;;;N;;;;;
+292C;FALLING DIAGONAL CROSSING RISING DIAGONAL;Sm;0;ON;;;;;N;;;;;
+292D;SOUTH EAST ARROW CROSSING NORTH EAST ARROW;Sm;0;ON;;;;;N;;;;;
+292E;NORTH EAST ARROW CROSSING SOUTH EAST ARROW;Sm;0;ON;;;;;N;;;;;
+292F;FALLING DIAGONAL CROSSING NORTH EAST ARROW;Sm;0;ON;;;;;N;;;;;
+2930;RISING DIAGONAL CROSSING SOUTH EAST ARROW;Sm;0;ON;;;;;N;;;;;
+2931;NORTH EAST ARROW CROSSING NORTH WEST ARROW;Sm;0;ON;;;;;N;;;;;
+2932;NORTH WEST ARROW CROSSING NORTH EAST ARROW;Sm;0;ON;;;;;N;;;;;
+2933;WAVE ARROW POINTING DIRECTLY RIGHT;Sm;0;ON;;;;;N;;;;;
+2934;ARROW POINTING RIGHTWARDS THEN CURVING UPWARDS;Sm;0;ON;;;;;N;;;;;
+2935;ARROW POINTING RIGHTWARDS THEN CURVING DOWNWARDS;Sm;0;ON;;;;;N;;;;;
+2936;ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS;Sm;0;ON;;;;;N;;;;;
+2937;ARROW POINTING DOWNWARDS THEN CURVING RIGHTWARDS;Sm;0;ON;;;;;N;;;;;
+2938;RIGHT-SIDE ARC CLOCKWISE ARROW;Sm;0;ON;;;;;N;;;;;
+2939;LEFT-SIDE ARC ANTICLOCKWISE ARROW;Sm;0;ON;;;;;N;;;;;
+293A;TOP ARC ANTICLOCKWISE ARROW;Sm;0;ON;;;;;N;;;;;
+293B;BOTTOM ARC ANTICLOCKWISE ARROW;Sm;0;ON;;;;;N;;;;;
+293C;TOP ARC CLOCKWISE ARROW WITH MINUS;Sm;0;ON;;;;;N;;;;;
+293D;TOP ARC ANTICLOCKWISE ARROW WITH PLUS;Sm;0;ON;;;;;N;;;;;
+293E;LOWER RIGHT SEMICIRCULAR CLOCKWISE ARROW;Sm;0;ON;;;;;N;;;;;
+293F;LOWER LEFT SEMICIRCULAR ANTICLOCKWISE ARROW;Sm;0;ON;;;;;N;;;;;
+2940;ANTICLOCKWISE CLOSED CIRCLE ARROW;Sm;0;ON;;;;;N;;;;;
+2941;CLOCKWISE CLOSED CIRCLE ARROW;Sm;0;ON;;;;;N;;;;;
+2942;RIGHTWARDS ARROW ABOVE SHORT LEFTWARDS ARROW;Sm;0;ON;;;;;N;;;;;
+2943;LEFTWARDS ARROW ABOVE SHORT RIGHTWARDS ARROW;Sm;0;ON;;;;;N;;;;;
+2944;SHORT RIGHTWARDS ARROW ABOVE LEFTWARDS ARROW;Sm;0;ON;;;;;N;;;;;
+2945;RIGHTWARDS ARROW WITH PLUS BELOW;Sm;0;ON;;;;;N;;;;;
+2946;LEFTWARDS ARROW WITH PLUS BELOW;Sm;0;ON;;;;;N;;;;;
+2947;RIGHTWARDS ARROW THROUGH X;Sm;0;ON;;;;;N;;;;;
+2948;LEFT RIGHT ARROW THROUGH SMALL CIRCLE;Sm;0;ON;;;;;N;;;;;
+2949;UPWARDS TWO-HEADED ARROW FROM SMALL CIRCLE;Sm;0;ON;;;;;N;;;;;
+294A;LEFT BARB UP RIGHT BARB DOWN HARPOON;Sm;0;ON;;;;;N;;;;;
+294B;LEFT BARB DOWN RIGHT BARB UP HARPOON;Sm;0;ON;;;;;N;;;;;
+294C;UP BARB RIGHT DOWN BARB LEFT HARPOON;Sm;0;ON;;;;;N;;;;;
+294D;UP BARB LEFT DOWN BARB RIGHT HARPOON;Sm;0;ON;;;;;N;;;;;
+294E;LEFT BARB UP RIGHT BARB UP HARPOON;Sm;0;ON;;;;;N;;;;;
+294F;UP BARB RIGHT DOWN BARB RIGHT HARPOON;Sm;0;ON;;;;;N;;;;;
+2950;LEFT BARB DOWN RIGHT BARB DOWN HARPOON;Sm;0;ON;;;;;N;;;;;
+2951;UP BARB LEFT DOWN BARB LEFT HARPOON;Sm;0;ON;;;;;N;;;;;
+2952;LEFTWARDS HARPOON WITH BARB UP TO BAR;Sm;0;ON;;;;;N;;;;;
+2953;RIGHTWARDS HARPOON WITH BARB UP TO BAR;Sm;0;ON;;;;;N;;;;;
+2954;UPWARDS HARPOON WITH BARB RIGHT TO BAR;Sm;0;ON;;;;;N;;;;;
+2955;DOWNWARDS HARPOON WITH BARB RIGHT TO BAR;Sm;0;ON;;;;;N;;;;;
+2956;LEFTWARDS HARPOON WITH BARB DOWN TO BAR;Sm;0;ON;;;;;N;;;;;
+2957;RIGHTWARDS HARPOON WITH BARB DOWN TO BAR;Sm;0;ON;;;;;N;;;;;
+2958;UPWARDS HARPOON WITH BARB LEFT TO BAR;Sm;0;ON;;;;;N;;;;;
+2959;DOWNWARDS HARPOON WITH BARB LEFT TO BAR;Sm;0;ON;;;;;N;;;;;
+295A;LEFTWARDS HARPOON WITH BARB UP FROM BAR;Sm;0;ON;;;;;N;;;;;
+295B;RIGHTWARDS HARPOON WITH BARB UP FROM BAR;Sm;0;ON;;;;;N;;;;;
+295C;UPWARDS HARPOON WITH BARB RIGHT FROM BAR;Sm;0;ON;;;;;N;;;;;
+295D;DOWNWARDS HARPOON WITH BARB RIGHT FROM BAR;Sm;0;ON;;;;;N;;;;;
+295E;LEFTWARDS HARPOON WITH BARB DOWN FROM BAR;Sm;0;ON;;;;;N;;;;;
+295F;RIGHTWARDS HARPOON WITH BARB DOWN FROM BAR;Sm;0;ON;;;;;N;;;;;
+2960;UPWARDS HARPOON WITH BARB LEFT FROM BAR;Sm;0;ON;;;;;N;;;;;
+2961;DOWNWARDS HARPOON WITH BARB LEFT FROM BAR;Sm;0;ON;;;;;N;;;;;
+2962;LEFTWARDS HARPOON WITH BARB UP ABOVE LEFTWARDS HARPOON WITH BARB DOWN;Sm;0;ON;;;;;N;;;;;
+2963;UPWARDS HARPOON WITH BARB LEFT BESIDE UPWARDS HARPOON WITH BARB RIGHT;Sm;0;ON;;;;;N;;;;;
+2964;RIGHTWARDS HARPOON WITH BARB UP ABOVE RIGHTWARDS HARPOON WITH BARB DOWN;Sm;0;ON;;;;;N;;;;;
+2965;DOWNWARDS HARPOON WITH BARB LEFT BESIDE DOWNWARDS HARPOON WITH BARB RIGHT;Sm;0;ON;;;;;N;;;;;
+2966;LEFTWARDS HARPOON WITH BARB UP ABOVE RIGHTWARDS HARPOON WITH BARB UP;Sm;0;ON;;;;;N;;;;;
+2967;LEFTWARDS HARPOON WITH BARB DOWN ABOVE RIGHTWARDS HARPOON WITH BARB DOWN;Sm;0;ON;;;;;N;;;;;
+2968;RIGHTWARDS HARPOON WITH BARB UP ABOVE LEFTWARDS HARPOON WITH BARB UP;Sm;0;ON;;;;;N;;;;;
+2969;RIGHTWARDS HARPOON WITH BARB DOWN ABOVE LEFTWARDS HARPOON WITH BARB DOWN;Sm;0;ON;;;;;N;;;;;
+296A;LEFTWARDS HARPOON WITH BARB UP ABOVE LONG DASH;Sm;0;ON;;;;;N;;;;;
+296B;LEFTWARDS HARPOON WITH BARB DOWN BELOW LONG DASH;Sm;0;ON;;;;;N;;;;;
+296C;RIGHTWARDS HARPOON WITH BARB UP ABOVE LONG DASH;Sm;0;ON;;;;;N;;;;;
+296D;RIGHTWARDS HARPOON WITH BARB DOWN BELOW LONG DASH;Sm;0;ON;;;;;N;;;;;
+296E;UPWARDS HARPOON WITH BARB LEFT BESIDE DOWNWARDS HARPOON WITH BARB RIGHT;Sm;0;ON;;;;;N;;;;;
+296F;DOWNWARDS HARPOON WITH BARB LEFT BESIDE UPWARDS HARPOON WITH BARB RIGHT;Sm;0;ON;;;;;N;;;;;
+2970;RIGHT DOUBLE ARROW WITH ROUNDED HEAD;Sm;0;ON;;;;;N;;;;;
+2971;EQUALS SIGN ABOVE RIGHTWARDS ARROW;Sm;0;ON;;;;;N;;;;;
+2972;TILDE OPERATOR ABOVE RIGHTWARDS ARROW;Sm;0;ON;;;;;N;;;;;
+2973;LEFTWARDS ARROW ABOVE TILDE OPERATOR;Sm;0;ON;;;;;N;;;;;
+2974;RIGHTWARDS ARROW ABOVE TILDE OPERATOR;Sm;0;ON;;;;;N;;;;;
+2975;RIGHTWARDS ARROW ABOVE ALMOST EQUAL TO;Sm;0;ON;;;;;N;;;;;
+2976;LESS-THAN ABOVE LEFTWARDS ARROW;Sm;0;ON;;;;;N;;;;;
+2977;LEFTWARDS ARROW THROUGH LESS-THAN;Sm;0;ON;;;;;N;;;;;
+2978;GREATER-THAN ABOVE RIGHTWARDS ARROW;Sm;0;ON;;;;;N;;;;;
+2979;SUBSET ABOVE RIGHTWARDS ARROW;Sm;0;ON;;;;;N;;;;;
+297A;LEFTWARDS ARROW THROUGH SUBSET;Sm;0;ON;;;;;N;;;;;
+297B;SUPERSET ABOVE LEFTWARDS ARROW;Sm;0;ON;;;;;N;;;;;
+297C;LEFT FISH TAIL;Sm;0;ON;;;;;N;;;;;
+297D;RIGHT FISH TAIL;Sm;0;ON;;;;;N;;;;;
+297E;UP FISH TAIL;Sm;0;ON;;;;;N;;;;;
+297F;DOWN FISH TAIL;Sm;0;ON;;;;;N;;;;;
+2980;TRIPLE VERTICAL BAR DELIMITER;Sm;0;ON;;;;;N;;;;;
+2981;Z NOTATION SPOT;Sm;0;ON;;;;;N;;;;;
+2982;Z NOTATION TYPE COLON;Sm;0;ON;;;;;N;;;;;
+2983;LEFT WHITE CURLY BRACKET;Ps;0;ON;;;;;Y;;;;;
+2984;RIGHT WHITE CURLY BRACKET;Pe;0;ON;;;;;Y;;;;;
+2985;LEFT WHITE PARENTHESIS;Ps;0;ON;;;;;Y;;;;;
+2986;RIGHT WHITE PARENTHESIS;Pe;0;ON;;;;;Y;;;;;
+2987;Z NOTATION LEFT IMAGE BRACKET;Ps;0;ON;;;;;Y;;;;;
+2988;Z NOTATION RIGHT IMAGE BRACKET;Pe;0;ON;;;;;Y;;;;;
+2989;Z NOTATION LEFT BINDING BRACKET;Ps;0;ON;;;;;Y;;;;;
+298A;Z NOTATION RIGHT BINDING BRACKET;Pe;0;ON;;;;;Y;;;;;
+298B;LEFT SQUARE BRACKET WITH UNDERBAR;Ps;0;ON;;;;;Y;;;;;
+298C;RIGHT SQUARE BRACKET WITH UNDERBAR;Pe;0;ON;;;;;Y;;;;;
+298D;LEFT SQUARE BRACKET WITH TICK IN TOP CORNER;Ps;0;ON;;;;;Y;;;;;
+298E;RIGHT SQUARE BRACKET WITH TICK IN BOTTOM CORNER;Pe;0;ON;;;;;Y;;;;;
+298F;LEFT SQUARE BRACKET WITH TICK IN BOTTOM CORNER;Ps;0;ON;;;;;Y;;;;;
+2990;RIGHT SQUARE BRACKET WITH TICK IN TOP CORNER;Pe;0;ON;;;;;Y;;;;;
+2991;LEFT ANGLE BRACKET WITH DOT;Ps;0;ON;;;;;Y;;;;;
+2992;RIGHT ANGLE BRACKET WITH DOT;Pe;0;ON;;;;;Y;;;;;
+2993;LEFT ARC LESS-THAN BRACKET;Ps;0;ON;;;;;Y;;;;;
+2994;RIGHT ARC GREATER-THAN BRACKET;Pe;0;ON;;;;;Y;;;;;
+2995;DOUBLE LEFT ARC GREATER-THAN BRACKET;Ps;0;ON;;;;;Y;;;;;
+2996;DOUBLE RIGHT ARC LESS-THAN BRACKET;Pe;0;ON;;;;;Y;;;;;
+2997;LEFT BLACK TORTOISE SHELL BRACKET;Ps;0;ON;;;;;Y;;;;;
+2998;RIGHT BLACK TORTOISE SHELL BRACKET;Pe;0;ON;;;;;Y;;;;;
+2999;DOTTED FENCE;Sm;0;ON;;;;;N;;;;;
+299A;VERTICAL ZIGZAG LINE;Sm;0;ON;;;;;N;;;;;
+299B;MEASURED ANGLE OPENING LEFT;Sm;0;ON;;;;;Y;;;;;
+299C;RIGHT ANGLE VARIANT WITH SQUARE;Sm;0;ON;;;;;Y;;;;;
+299D;MEASURED RIGHT ANGLE WITH DOT;Sm;0;ON;;;;;Y;;;;;
+299E;ANGLE WITH S INSIDE;Sm;0;ON;;;;;Y;;;;;
+299F;ACUTE ANGLE;Sm;0;ON;;;;;Y;;;;;
+29A0;SPHERICAL ANGLE OPENING LEFT;Sm;0;ON;;;;;Y;;;;;
+29A1;SPHERICAL ANGLE OPENING UP;Sm;0;ON;;;;;Y;;;;;
+29A2;TURNED ANGLE;Sm;0;ON;;;;;Y;;;;;
+29A3;REVERSED ANGLE;Sm;0;ON;;;;;Y;;;;;
+29A4;ANGLE WITH UNDERBAR;Sm;0;ON;;;;;Y;;;;;
+29A5;REVERSED ANGLE WITH UNDERBAR;Sm;0;ON;;;;;Y;;;;;
+29A6;OBLIQUE ANGLE OPENING UP;Sm;0;ON;;;;;Y;;;;;
+29A7;OBLIQUE ANGLE OPENING DOWN;Sm;0;ON;;;;;Y;;;;;
+29A8;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING UP AND RIGHT;Sm;0;ON;;;;;Y;;;;;
+29A9;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING UP AND LEFT;Sm;0;ON;;;;;Y;;;;;
+29AA;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING DOWN AND RIGHT;Sm;0;ON;;;;;Y;;;;;
+29AB;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING DOWN AND LEFT;Sm;0;ON;;;;;Y;;;;;
+29AC;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING RIGHT AND UP;Sm;0;ON;;;;;Y;;;;;
+29AD;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING LEFT AND UP;Sm;0;ON;;;;;Y;;;;;
+29AE;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING RIGHT AND DOWN;Sm;0;ON;;;;;Y;;;;;
+29AF;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING LEFT AND DOWN;Sm;0;ON;;;;;Y;;;;;
+29B0;REVERSED EMPTY SET;Sm;0;ON;;;;;N;;;;;
+29B1;EMPTY SET WITH OVERBAR;Sm;0;ON;;;;;N;;;;;
+29B2;EMPTY SET WITH SMALL CIRCLE ABOVE;Sm;0;ON;;;;;N;;;;;
+29B3;EMPTY SET WITH RIGHT ARROW ABOVE;Sm;0;ON;;;;;N;;;;;
+29B4;EMPTY SET WITH LEFT ARROW ABOVE;Sm;0;ON;;;;;N;;;;;
+29B5;CIRCLE WITH HORIZONTAL BAR;Sm;0;ON;;;;;N;;;;;
+29B6;CIRCLED VERTICAL BAR;Sm;0;ON;;;;;N;;;;;
+29B7;CIRCLED PARALLEL;Sm;0;ON;;;;;N;;;;;
+29B8;CIRCLED REVERSE SOLIDUS;Sm;0;ON;;;;;Y;;;;;
+29B9;CIRCLED PERPENDICULAR;Sm;0;ON;;;;;N;;;;;
+29BA;CIRCLE DIVIDED BY HORIZONTAL BAR AND TOP HALF DIVIDED BY VERTICAL BAR;Sm;0;ON;;;;;N;;;;;
+29BB;CIRCLE WITH SUPERIMPOSED X;Sm;0;ON;;;;;N;;;;;
+29BC;CIRCLED ANTICLOCKWISE-ROTATED DIVISION SIGN;Sm;0;ON;;;;;N;;;;;
+29BD;UP ARROW THROUGH CIRCLE;Sm;0;ON;;;;;N;;;;;
+29BE;CIRCLED WHITE BULLET;Sm;0;ON;;;;;N;;;;;
+29BF;CIRCLED BULLET;Sm;0;ON;;;;;N;;;;;
+29C0;CIRCLED LESS-THAN;Sm;0;ON;;;;;Y;;;;;
+29C1;CIRCLED GREATER-THAN;Sm;0;ON;;;;;Y;;;;;
+29C2;CIRCLE WITH SMALL CIRCLE TO THE RIGHT;Sm;0;ON;;;;;Y;;;;;
+29C3;CIRCLE WITH TWO HORIZONTAL STROKES TO THE RIGHT;Sm;0;ON;;;;;Y;;;;;
+29C4;SQUARED RISING DIAGONAL SLASH;Sm;0;ON;;;;;Y;;;;;
+29C5;SQUARED FALLING DIAGONAL SLASH;Sm;0;ON;;;;;Y;;;;;
+29C6;SQUARED ASTERISK;Sm;0;ON;;;;;N;;;;;
+29C7;SQUARED SMALL CIRCLE;Sm;0;ON;;;;;N;;;;;
+29C8;SQUARED SQUARE;Sm;0;ON;;;;;N;;;;;
+29C9;TWO JOINED SQUARES;Sm;0;ON;;;;;Y;;;;;
+29CA;TRIANGLE WITH DOT ABOVE;Sm;0;ON;;;;;N;;;;;
+29CB;TRIANGLE WITH UNDERBAR;Sm;0;ON;;;;;N;;;;;
+29CC;S IN TRIANGLE;Sm;0;ON;;;;;N;;;;;
+29CD;TRIANGLE WITH SERIFS AT BOTTOM;Sm;0;ON;;;;;N;;;;;
+29CE;RIGHT TRIANGLE ABOVE LEFT TRIANGLE;Sm;0;ON;;;;;Y;;;;;
+29CF;LEFT TRIANGLE BESIDE VERTICAL BAR;Sm;0;ON;;;;;Y;;;;;
+29D0;VERTICAL BAR BESIDE RIGHT TRIANGLE;Sm;0;ON;;;;;Y;;;;;
+29D1;BOWTIE WITH LEFT HALF BLACK;Sm;0;ON;;;;;Y;;;;;
+29D2;BOWTIE WITH RIGHT HALF BLACK;Sm;0;ON;;;;;Y;;;;;
+29D3;BLACK BOWTIE;Sm;0;ON;;;;;N;;;;;
+29D4;TIMES WITH LEFT HALF BLACK;Sm;0;ON;;;;;Y;;;;;
+29D5;TIMES WITH RIGHT HALF BLACK;Sm;0;ON;;;;;Y;;;;;
+29D6;WHITE HOURGLASS;Sm;0;ON;;;;;N;;;;;
+29D7;BLACK HOURGLASS;Sm;0;ON;;;;;N;;;;;
+29D8;LEFT WIGGLY FENCE;Ps;0;ON;;;;;Y;;;;;
+29D9;RIGHT WIGGLY FENCE;Pe;0;ON;;;;;Y;;;;;
+29DA;LEFT DOUBLE WIGGLY FENCE;Ps;0;ON;;;;;Y;;;;;
+29DB;RIGHT DOUBLE WIGGLY FENCE;Pe;0;ON;;;;;Y;;;;;
+29DC;INCOMPLETE INFINITY;Sm;0;ON;;;;;Y;;;;;
+29DD;TIE OVER INFINITY;Sm;0;ON;;;;;N;;;;;
+29DE;INFINITY NEGATED WITH VERTICAL BAR;Sm;0;ON;;;;;N;;;;;
+29DF;DOUBLE-ENDED MULTIMAP;Sm;0;ON;;;;;N;;;;;
+29E0;SQUARE WITH CONTOURED OUTLINE;Sm;0;ON;;;;;N;;;;;
+29E1;INCREASES AS;Sm;0;ON;;;;;Y;;;;;
+29E2;SHUFFLE PRODUCT;Sm;0;ON;;;;;N;;;;;
+29E3;EQUALS SIGN AND SLANTED PARALLEL;Sm;0;ON;;;;;Y;;;;;
+29E4;EQUALS SIGN AND SLANTED PARALLEL WITH TILDE ABOVE;Sm;0;ON;;;;;Y;;;;;
+29E5;IDENTICAL TO AND SLANTED PARALLEL;Sm;0;ON;;;;;Y;;;;;
+29E6;GLEICH STARK;Sm;0;ON;;;;;N;;;;;
+29E7;THERMODYNAMIC;Sm;0;ON;;;;;N;;;;;
+29E8;DOWN-POINTING TRIANGLE WITH LEFT HALF BLACK;Sm;0;ON;;;;;Y;;;;;
+29E9;DOWN-POINTING TRIANGLE WITH RIGHT HALF BLACK;Sm;0;ON;;;;;Y;;;;;
+29EA;BLACK DIAMOND WITH DOWN ARROW;Sm;0;ON;;;;;N;;;;;
+29EB;BLACK LOZENGE;Sm;0;ON;;;;;N;;;;;
+29EC;WHITE CIRCLE WITH DOWN ARROW;Sm;0;ON;;;;;N;;;;;
+29ED;BLACK CIRCLE WITH DOWN ARROW;Sm;0;ON;;;;;N;;;;;
+29EE;ERROR-BARRED WHITE SQUARE;Sm;0;ON;;;;;N;;;;;
+29EF;ERROR-BARRED BLACK SQUARE;Sm;0;ON;;;;;N;;;;;
+29F0;ERROR-BARRED WHITE DIAMOND;Sm;0;ON;;;;;N;;;;;
+29F1;ERROR-BARRED BLACK DIAMOND;Sm;0;ON;;;;;N;;;;;
+29F2;ERROR-BARRED WHITE CIRCLE;Sm;0;ON;;;;;N;;;;;
+29F3;ERROR-BARRED BLACK CIRCLE;Sm;0;ON;;;;;N;;;;;
+29F4;RULE-DELAYED;Sm;0;ON;;;;;Y;;;;;
+29F5;REVERSE SOLIDUS OPERATOR;Sm;0;ON;;;;;Y;;;;;
+29F6;SOLIDUS WITH OVERBAR;Sm;0;ON;;;;;Y;;;;;
+29F7;REVERSE SOLIDUS WITH HORIZONTAL STROKE;Sm;0;ON;;;;;Y;;;;;
+29F8;BIG SOLIDUS;Sm;0;ON;;;;;Y;;;;;
+29F9;BIG REVERSE SOLIDUS;Sm;0;ON;;;;;Y;;;;;
+29FA;DOUBLE PLUS;Sm;0;ON;;;;;N;;;;;
+29FB;TRIPLE PLUS;Sm;0;ON;;;;;N;;;;;
+29FC;LEFT-POINTING CURVED ANGLE BRACKET;Ps;0;ON;;;;;Y;;;;;
+29FD;RIGHT-POINTING CURVED ANGLE BRACKET;Pe;0;ON;;;;;Y;;;;;
+29FE;TINY;Sm;0;ON;;;;;N;;;;;
+29FF;MINY;Sm;0;ON;;;;;N;;;;;
+2A00;N-ARY CIRCLED DOT OPERATOR;Sm;0;ON;;;;;N;;;;;
+2A01;N-ARY CIRCLED PLUS OPERATOR;Sm;0;ON;;;;;N;;;;;
+2A02;N-ARY CIRCLED TIMES OPERATOR;Sm;0;ON;;;;;N;;;;;
+2A03;N-ARY UNION OPERATOR WITH DOT;Sm;0;ON;;;;;N;;;;;
+2A04;N-ARY UNION OPERATOR WITH PLUS;Sm;0;ON;;;;;N;;;;;
+2A05;N-ARY SQUARE INTERSECTION OPERATOR;Sm;0;ON;;;;;N;;;;;
+2A06;N-ARY SQUARE UNION OPERATOR;Sm;0;ON;;;;;N;;;;;
+2A07;TWO LOGICAL AND OPERATOR;Sm;0;ON;;;;;N;;;;;
+2A08;TWO LOGICAL OR OPERATOR;Sm;0;ON;;;;;N;;;;;
+2A09;N-ARY TIMES OPERATOR;Sm;0;ON;;;;;N;;;;;
+2A0A;MODULO TWO SUM;Sm;0;ON;;;;;Y;;;;;
+2A0B;SUMMATION WITH INTEGRAL;Sm;0;ON;;;;;Y;;;;;
+2A0C;QUADRUPLE INTEGRAL OPERATOR;Sm;0;ON;<compat> 222B 222B 222B 222B;;;;Y;;;;;
+2A0D;FINITE PART INTEGRAL;Sm;0;ON;;;;;Y;;;;;
+2A0E;INTEGRAL WITH DOUBLE STROKE;Sm;0;ON;;;;;Y;;;;;
+2A0F;INTEGRAL AVERAGE WITH SLASH;Sm;0;ON;;;;;Y;;;;;
+2A10;CIRCULATION FUNCTION;Sm;0;ON;;;;;Y;;;;;
+2A11;ANTICLOCKWISE INTEGRATION;Sm;0;ON;;;;;Y;;;;;
+2A12;LINE INTEGRATION WITH RECTANGULAR PATH AROUND POLE;Sm;0;ON;;;;;Y;;;;;
+2A13;LINE INTEGRATION WITH SEMICIRCULAR PATH AROUND POLE;Sm;0;ON;;;;;Y;;;;;
+2A14;LINE INTEGRATION NOT INCLUDING THE POLE;Sm;0;ON;;;;;Y;;;;;
+2A15;INTEGRAL AROUND A POINT OPERATOR;Sm;0;ON;;;;;Y;;;;;
+2A16;QUATERNION INTEGRAL OPERATOR;Sm;0;ON;;;;;Y;;;;;
+2A17;INTEGRAL WITH LEFTWARDS ARROW WITH HOOK;Sm;0;ON;;;;;Y;;;;;
+2A18;INTEGRAL WITH TIMES SIGN;Sm;0;ON;;;;;Y;;;;;
+2A19;INTEGRAL WITH INTERSECTION;Sm;0;ON;;;;;Y;;;;;
+2A1A;INTEGRAL WITH UNION;Sm;0;ON;;;;;Y;;;;;
+2A1B;INTEGRAL WITH OVERBAR;Sm;0;ON;;;;;Y;;;;;
+2A1C;INTEGRAL WITH UNDERBAR;Sm;0;ON;;;;;Y;;;;;
+2A1D;JOIN;Sm;0;ON;;;;;N;;;;;
+2A1E;LARGE LEFT TRIANGLE OPERATOR;Sm;0;ON;;;;;Y;;;;;
+2A1F;Z NOTATION SCHEMA COMPOSITION;Sm;0;ON;;;;;Y;;;;;
+2A20;Z NOTATION SCHEMA PIPING;Sm;0;ON;;;;;Y;;;;;
+2A21;Z NOTATION SCHEMA PROJECTION;Sm;0;ON;;;;;Y;;;;;
+2A22;PLUS SIGN WITH SMALL CIRCLE ABOVE;Sm;0;ON;;;;;N;;;;;
+2A23;PLUS SIGN WITH CIRCUMFLEX ACCENT ABOVE;Sm;0;ON;;;;;N;;;;;
+2A24;PLUS SIGN WITH TILDE ABOVE;Sm;0;ON;;;;;Y;;;;;
+2A25;PLUS SIGN WITH DOT BELOW;Sm;0;ON;;;;;N;;;;;
+2A26;PLUS SIGN WITH TILDE BELOW;Sm;0;ON;;;;;Y;;;;;
+2A27;PLUS SIGN WITH SUBSCRIPT TWO;Sm;0;ON;;;;;N;;;;;
+2A28;PLUS SIGN WITH BLACK TRIANGLE;Sm;0;ON;;;;;N;;;;;
+2A29;MINUS SIGN WITH COMMA ABOVE;Sm;0;ON;;;;;Y;;;;;
+2A2A;MINUS SIGN WITH DOT BELOW;Sm;0;ON;;;;;N;;;;;
+2A2B;MINUS SIGN WITH FALLING DOTS;Sm;0;ON;;;;;Y;;;;;
+2A2C;MINUS SIGN WITH RISING DOTS;Sm;0;ON;;;;;Y;;;;;
+2A2D;PLUS SIGN IN LEFT HALF CIRCLE;Sm;0;ON;;;;;Y;;;;;
+2A2E;PLUS SIGN IN RIGHT HALF CIRCLE;Sm;0;ON;;;;;Y;;;;;
+2A2F;VECTOR OR CROSS PRODUCT;Sm;0;ON;;;;;N;;;;;
+2A30;MULTIPLICATION SIGN WITH DOT ABOVE;Sm;0;ON;;;;;N;;;;;
+2A31;MULTIPLICATION SIGN WITH UNDERBAR;Sm;0;ON;;;;;N;;;;;
+2A32;SEMIDIRECT PRODUCT WITH BOTTOM CLOSED;Sm;0;ON;;;;;N;;;;;
+2A33;SMASH PRODUCT;Sm;0;ON;;;;;N;;;;;
+2A34;MULTIPLICATION SIGN IN LEFT HALF CIRCLE;Sm;0;ON;;;;;Y;;;;;
+2A35;MULTIPLICATION SIGN IN RIGHT HALF CIRCLE;Sm;0;ON;;;;;Y;;;;;
+2A36;CIRCLED MULTIPLICATION SIGN WITH CIRCUMFLEX ACCENT;Sm;0;ON;;;;;N;;;;;
+2A37;MULTIPLICATION SIGN IN DOUBLE CIRCLE;Sm;0;ON;;;;;N;;;;;
+2A38;CIRCLED DIVISION SIGN;Sm;0;ON;;;;;N;;;;;
+2A39;PLUS SIGN IN TRIANGLE;Sm;0;ON;;;;;N;;;;;
+2A3A;MINUS SIGN IN TRIANGLE;Sm;0;ON;;;;;N;;;;;
+2A3B;MULTIPLICATION SIGN IN TRIANGLE;Sm;0;ON;;;;;N;;;;;
+2A3C;INTERIOR PRODUCT;Sm;0;ON;;;;;Y;;;;;
+2A3D;RIGHTHAND INTERIOR PRODUCT;Sm;0;ON;;;;;Y;;;;;
+2A3E;Z NOTATION RELATIONAL COMPOSITION;Sm;0;ON;;;;;Y;;;;;
+2A3F;AMALGAMATION OR COPRODUCT;Sm;0;ON;;;;;N;;;;;
+2A40;INTERSECTION WITH DOT;Sm;0;ON;;;;;N;;;;;
+2A41;UNION WITH MINUS SIGN;Sm;0;ON;;;;;N;;;;;
+2A42;UNION WITH OVERBAR;Sm;0;ON;;;;;N;;;;;
+2A43;INTERSECTION WITH OVERBAR;Sm;0;ON;;;;;N;;;;;
+2A44;INTERSECTION WITH LOGICAL AND;Sm;0;ON;;;;;N;;;;;
+2A45;UNION WITH LOGICAL OR;Sm;0;ON;;;;;N;;;;;
+2A46;UNION ABOVE INTERSECTION;Sm;0;ON;;;;;N;;;;;
+2A47;INTERSECTION ABOVE UNION;Sm;0;ON;;;;;N;;;;;
+2A48;UNION ABOVE BAR ABOVE INTERSECTION;Sm;0;ON;;;;;N;;;;;
+2A49;INTERSECTION ABOVE BAR ABOVE UNION;Sm;0;ON;;;;;N;;;;;
+2A4A;UNION BESIDE AND JOINED WITH UNION;Sm;0;ON;;;;;N;;;;;
+2A4B;INTERSECTION BESIDE AND JOINED WITH INTERSECTION;Sm;0;ON;;;;;N;;;;;
+2A4C;CLOSED UNION WITH SERIFS;Sm;0;ON;;;;;N;;;;;
+2A4D;CLOSED INTERSECTION WITH SERIFS;Sm;0;ON;;;;;N;;;;;
+2A4E;DOUBLE SQUARE INTERSECTION;Sm;0;ON;;;;;N;;;;;
+2A4F;DOUBLE SQUARE UNION;Sm;0;ON;;;;;N;;;;;
+2A50;CLOSED UNION WITH SERIFS AND SMASH PRODUCT;Sm;0;ON;;;;;N;;;;;
+2A51;LOGICAL AND WITH DOT ABOVE;Sm;0;ON;;;;;N;;;;;
+2A52;LOGICAL OR WITH DOT ABOVE;Sm;0;ON;;;;;N;;;;;
+2A53;DOUBLE LOGICAL AND;Sm;0;ON;;;;;N;;;;;
+2A54;DOUBLE LOGICAL OR;Sm;0;ON;;;;;N;;;;;
+2A55;TWO INTERSECTING LOGICAL AND;Sm;0;ON;;;;;N;;;;;
+2A56;TWO INTERSECTING LOGICAL OR;Sm;0;ON;;;;;N;;;;;
+2A57;SLOPING LARGE OR;Sm;0;ON;;;;;Y;;;;;
+2A58;SLOPING LARGE AND;Sm;0;ON;;;;;Y;;;;;
+2A59;LOGICAL OR OVERLAPPING LOGICAL AND;Sm;0;ON;;;;;N;;;;;
+2A5A;LOGICAL AND WITH MIDDLE STEM;Sm;0;ON;;;;;N;;;;;
+2A5B;LOGICAL OR WITH MIDDLE STEM;Sm;0;ON;;;;;N;;;;;
+2A5C;LOGICAL AND WITH HORIZONTAL DASH;Sm;0;ON;;;;;N;;;;;
+2A5D;LOGICAL OR WITH HORIZONTAL DASH;Sm;0;ON;;;;;N;;;;;
+2A5E;LOGICAL AND WITH DOUBLE OVERBAR;Sm;0;ON;;;;;N;;;;;
+2A5F;LOGICAL AND WITH UNDERBAR;Sm;0;ON;;;;;N;;;;;
+2A60;LOGICAL AND WITH DOUBLE UNDERBAR;Sm;0;ON;;;;;N;;;;;
+2A61;SMALL VEE WITH UNDERBAR;Sm;0;ON;;;;;N;;;;;
+2A62;LOGICAL OR WITH DOUBLE OVERBAR;Sm;0;ON;;;;;N;;;;;
+2A63;LOGICAL OR WITH DOUBLE UNDERBAR;Sm;0;ON;;;;;N;;;;;
+2A64;Z NOTATION DOMAIN ANTIRESTRICTION;Sm;0;ON;;;;;Y;;;;;
+2A65;Z NOTATION RANGE ANTIRESTRICTION;Sm;0;ON;;;;;Y;;;;;
+2A66;EQUALS SIGN WITH DOT BELOW;Sm;0;ON;;;;;N;;;;;
+2A67;IDENTICAL WITH DOT ABOVE;Sm;0;ON;;;;;N;;;;;
+2A68;TRIPLE HORIZONTAL BAR WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+2A69;TRIPLE HORIZONTAL BAR WITH TRIPLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;;
+2A6A;TILDE OPERATOR WITH DOT ABOVE;Sm;0;ON;;;;;Y;;;;;
+2A6B;TILDE OPERATOR WITH RISING DOTS;Sm;0;ON;;;;;Y;;;;;
+2A6C;SIMILAR MINUS SIMILAR;Sm;0;ON;;;;;Y;;;;;
+2A6D;CONGRUENT WITH DOT ABOVE;Sm;0;ON;;;;;Y;;;;;
+2A6E;EQUALS WITH ASTERISK;Sm;0;ON;;;;;N;;;;;
+2A6F;ALMOST EQUAL TO WITH CIRCUMFLEX ACCENT;Sm;0;ON;;;;;Y;;;;;
+2A70;APPROXIMATELY EQUAL OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2A71;EQUALS SIGN ABOVE PLUS SIGN;Sm;0;ON;;;;;N;;;;;
+2A72;PLUS SIGN ABOVE EQUALS SIGN;Sm;0;ON;;;;;N;;;;;
+2A73;EQUALS SIGN ABOVE TILDE OPERATOR;Sm;0;ON;;;;;Y;;;;;
+2A74;DOUBLE COLON EQUAL;Sm;0;ON;<compat> 003A 003A 003D;;;;Y;;;;;
+2A75;TWO CONSECUTIVE EQUALS SIGNS;Sm;0;ON;<compat> 003D 003D;;;;N;;;;;
+2A76;THREE CONSECUTIVE EQUALS SIGNS;Sm;0;ON;<compat> 003D 003D 003D;;;;N;;;;;
+2A77;EQUALS SIGN WITH TWO DOTS ABOVE AND TWO DOTS BELOW;Sm;0;ON;;;;;N;;;;;
+2A78;EQUIVALENT WITH FOUR DOTS ABOVE;Sm;0;ON;;;;;N;;;;;
+2A79;LESS-THAN WITH CIRCLE INSIDE;Sm;0;ON;;;;;Y;;;;;
+2A7A;GREATER-THAN WITH CIRCLE INSIDE;Sm;0;ON;;;;;Y;;;;;
+2A7B;LESS-THAN WITH QUESTION MARK ABOVE;Sm;0;ON;;;;;Y;;;;;
+2A7C;GREATER-THAN WITH QUESTION MARK ABOVE;Sm;0;ON;;;;;Y;;;;;
+2A7D;LESS-THAN OR SLANTED EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2A7E;GREATER-THAN OR SLANTED EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2A7F;LESS-THAN OR SLANTED EQUAL TO WITH DOT INSIDE;Sm;0;ON;;;;;Y;;;;;
+2A80;GREATER-THAN OR SLANTED EQUAL TO WITH DOT INSIDE;Sm;0;ON;;;;;Y;;;;;
+2A81;LESS-THAN OR SLANTED EQUAL TO WITH DOT ABOVE;Sm;0;ON;;;;;Y;;;;;
+2A82;GREATER-THAN OR SLANTED EQUAL TO WITH DOT ABOVE;Sm;0;ON;;;;;Y;;;;;
+2A83;LESS-THAN OR SLANTED EQUAL TO WITH DOT ABOVE RIGHT;Sm;0;ON;;;;;Y;;;;;
+2A84;GREATER-THAN OR SLANTED EQUAL TO WITH DOT ABOVE LEFT;Sm;0;ON;;;;;Y;;;;;
+2A85;LESS-THAN OR APPROXIMATE;Sm;0;ON;;;;;Y;;;;;
+2A86;GREATER-THAN OR APPROXIMATE;Sm;0;ON;;;;;Y;;;;;
+2A87;LESS-THAN AND SINGLE-LINE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2A88;GREATER-THAN AND SINGLE-LINE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2A89;LESS-THAN AND NOT APPROXIMATE;Sm;0;ON;;;;;Y;;;;;
+2A8A;GREATER-THAN AND NOT APPROXIMATE;Sm;0;ON;;;;;Y;;;;;
+2A8B;LESS-THAN ABOVE DOUBLE-LINE EQUAL ABOVE GREATER-THAN;Sm;0;ON;;;;;Y;;;;;
+2A8C;GREATER-THAN ABOVE DOUBLE-LINE EQUAL ABOVE LESS-THAN;Sm;0;ON;;;;;Y;;;;;
+2A8D;LESS-THAN ABOVE SIMILAR OR EQUAL;Sm;0;ON;;;;;Y;;;;;
+2A8E;GREATER-THAN ABOVE SIMILAR OR EQUAL;Sm;0;ON;;;;;Y;;;;;
+2A8F;LESS-THAN ABOVE SIMILAR ABOVE GREATER-THAN;Sm;0;ON;;;;;Y;;;;;
+2A90;GREATER-THAN ABOVE SIMILAR ABOVE LESS-THAN;Sm;0;ON;;;;;Y;;;;;
+2A91;LESS-THAN ABOVE GREATER-THAN ABOVE DOUBLE-LINE EQUAL;Sm;0;ON;;;;;Y;;;;;
+2A92;GREATER-THAN ABOVE LESS-THAN ABOVE DOUBLE-LINE EQUAL;Sm;0;ON;;;;;Y;;;;;
+2A93;LESS-THAN ABOVE SLANTED EQUAL ABOVE GREATER-THAN ABOVE SLANTED EQUAL;Sm;0;ON;;;;;Y;;;;;
+2A94;GREATER-THAN ABOVE SLANTED EQUAL ABOVE LESS-THAN ABOVE SLANTED EQUAL;Sm;0;ON;;;;;Y;;;;;
+2A95;SLANTED EQUAL TO OR LESS-THAN;Sm;0;ON;;;;;Y;;;;;
+2A96;SLANTED EQUAL TO OR GREATER-THAN;Sm;0;ON;;;;;Y;;;;;
+2A97;SLANTED EQUAL TO OR LESS-THAN WITH DOT INSIDE;Sm;0;ON;;;;;Y;;;;;
+2A98;SLANTED EQUAL TO OR GREATER-THAN WITH DOT INSIDE;Sm;0;ON;;;;;Y;;;;;
+2A99;DOUBLE-LINE EQUAL TO OR LESS-THAN;Sm;0;ON;;;;;Y;;;;;
+2A9A;DOUBLE-LINE EQUAL TO OR GREATER-THAN;Sm;0;ON;;;;;Y;;;;;
+2A9B;DOUBLE-LINE SLANTED EQUAL TO OR LESS-THAN;Sm;0;ON;;;;;Y;;;;;
+2A9C;DOUBLE-LINE SLANTED EQUAL TO OR GREATER-THAN;Sm;0;ON;;;;;Y;;;;;
+2A9D;SIMILAR OR LESS-THAN;Sm;0;ON;;;;;Y;;;;;
+2A9E;SIMILAR OR GREATER-THAN;Sm;0;ON;;;;;Y;;;;;
+2A9F;SIMILAR ABOVE LESS-THAN ABOVE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;;
+2AA0;SIMILAR ABOVE GREATER-THAN ABOVE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;;
+2AA1;DOUBLE NESTED LESS-THAN;Sm;0;ON;;;;;Y;;;;;
+2AA2;DOUBLE NESTED GREATER-THAN;Sm;0;ON;;;;;Y;;;;;
+2AA3;DOUBLE NESTED LESS-THAN WITH UNDERBAR;Sm;0;ON;;;;;Y;;;;;
+2AA4;GREATER-THAN OVERLAPPING LESS-THAN;Sm;0;ON;;;;;N;;;;;
+2AA5;GREATER-THAN BESIDE LESS-THAN;Sm;0;ON;;;;;N;;;;;
+2AA6;LESS-THAN CLOSED BY CURVE;Sm;0;ON;;;;;Y;;;;;
+2AA7;GREATER-THAN CLOSED BY CURVE;Sm;0;ON;;;;;Y;;;;;
+2AA8;LESS-THAN CLOSED BY CURVE ABOVE SLANTED EQUAL;Sm;0;ON;;;;;Y;;;;;
+2AA9;GREATER-THAN CLOSED BY CURVE ABOVE SLANTED EQUAL;Sm;0;ON;;;;;Y;;;;;
+2AAA;SMALLER THAN;Sm;0;ON;;;;;Y;;;;;
+2AAB;LARGER THAN;Sm;0;ON;;;;;Y;;;;;
+2AAC;SMALLER THAN OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2AAD;LARGER THAN OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2AAE;EQUALS SIGN WITH BUMPY ABOVE;Sm;0;ON;;;;;N;;;;;
+2AAF;PRECEDES ABOVE SINGLE-LINE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;;
+2AB0;SUCCEEDS ABOVE SINGLE-LINE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;;
+2AB1;PRECEDES ABOVE SINGLE-LINE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2AB2;SUCCEEDS ABOVE SINGLE-LINE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2AB3;PRECEDES ABOVE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;;
+2AB4;SUCCEEDS ABOVE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;;
+2AB5;PRECEDES ABOVE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2AB6;SUCCEEDS ABOVE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2AB7;PRECEDES ABOVE ALMOST EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2AB8;SUCCEEDS ABOVE ALMOST EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2AB9;PRECEDES ABOVE NOT ALMOST EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2ABA;SUCCEEDS ABOVE NOT ALMOST EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2ABB;DOUBLE PRECEDES;Sm;0;ON;;;;;Y;;;;;
+2ABC;DOUBLE SUCCEEDS;Sm;0;ON;;;;;Y;;;;;
+2ABD;SUBSET WITH DOT;Sm;0;ON;;;;;Y;;;;;
+2ABE;SUPERSET WITH DOT;Sm;0;ON;;;;;Y;;;;;
+2ABF;SUBSET WITH PLUS SIGN BELOW;Sm;0;ON;;;;;Y;;;;;
+2AC0;SUPERSET WITH PLUS SIGN BELOW;Sm;0;ON;;;;;Y;;;;;
+2AC1;SUBSET WITH MULTIPLICATION SIGN BELOW;Sm;0;ON;;;;;Y;;;;;
+2AC2;SUPERSET WITH MULTIPLICATION SIGN BELOW;Sm;0;ON;;;;;Y;;;;;
+2AC3;SUBSET OF OR EQUAL TO WITH DOT ABOVE;Sm;0;ON;;;;;Y;;;;;
+2AC4;SUPERSET OF OR EQUAL TO WITH DOT ABOVE;Sm;0;ON;;;;;Y;;;;;
+2AC5;SUBSET OF ABOVE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;;
+2AC6;SUPERSET OF ABOVE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;;
+2AC7;SUBSET OF ABOVE TILDE OPERATOR;Sm;0;ON;;;;;Y;;;;;
+2AC8;SUPERSET OF ABOVE TILDE OPERATOR;Sm;0;ON;;;;;Y;;;;;
+2AC9;SUBSET OF ABOVE ALMOST EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2ACA;SUPERSET OF ABOVE ALMOST EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2ACB;SUBSET OF ABOVE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2ACC;SUPERSET OF ABOVE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2ACD;SQUARE LEFT OPEN BOX OPERATOR;Sm;0;ON;;;;;Y;;;;;
+2ACE;SQUARE RIGHT OPEN BOX OPERATOR;Sm;0;ON;;;;;Y;;;;;
+2ACF;CLOSED SUBSET;Sm;0;ON;;;;;Y;;;;;
+2AD0;CLOSED SUPERSET;Sm;0;ON;;;;;Y;;;;;
+2AD1;CLOSED SUBSET OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2AD2;CLOSED SUPERSET OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2AD3;SUBSET ABOVE SUPERSET;Sm;0;ON;;;;;Y;;;;;
+2AD4;SUPERSET ABOVE SUBSET;Sm;0;ON;;;;;Y;;;;;
+2AD5;SUBSET ABOVE SUBSET;Sm;0;ON;;;;;Y;;;;;
+2AD6;SUPERSET ABOVE SUPERSET;Sm;0;ON;;;;;Y;;;;;
+2AD7;SUPERSET BESIDE SUBSET;Sm;0;ON;;;;;N;;;;;
+2AD8;SUPERSET BESIDE AND JOINED BY DASH WITH SUBSET;Sm;0;ON;;;;;N;;;;;
+2AD9;ELEMENT OF OPENING DOWNWARDS;Sm;0;ON;;;;;N;;;;;
+2ADA;PITCHFORK WITH TEE TOP;Sm;0;ON;;;;;N;;;;;
+2ADB;TRANSVERSAL INTERSECTION;Sm;0;ON;;;;;N;;;;;
+2ADC;FORKING;Sm;0;ON;2ADD 0338;;;;Y;;not independent;;;
+2ADD;NONFORKING;Sm;0;ON;;;;;N;;independent;;;
+2ADE;SHORT LEFT TACK;Sm;0;ON;;;;;Y;;;;;
+2ADF;SHORT DOWN TACK;Sm;0;ON;;;;;N;;;;;
+2AE0;SHORT UP TACK;Sm;0;ON;;;;;N;;;;;
+2AE1;PERPENDICULAR WITH S;Sm;0;ON;;;;;N;;;;;
+2AE2;VERTICAL BAR TRIPLE RIGHT TURNSTILE;Sm;0;ON;;;;;Y;;;;;
+2AE3;DOUBLE VERTICAL BAR LEFT TURNSTILE;Sm;0;ON;;;;;Y;;;;;
+2AE4;VERTICAL BAR DOUBLE LEFT TURNSTILE;Sm;0;ON;;;;;Y;;;;;
+2AE5;DOUBLE VERTICAL BAR DOUBLE LEFT TURNSTILE;Sm;0;ON;;;;;Y;;;;;
+2AE6;LONG DASH FROM LEFT MEMBER OF DOUBLE VERTICAL;Sm;0;ON;;;;;Y;;;;;
+2AE7;SHORT DOWN TACK WITH OVERBAR;Sm;0;ON;;;;;N;;;;;
+2AE8;SHORT UP TACK WITH UNDERBAR;Sm;0;ON;;;;;N;;;;;
+2AE9;SHORT UP TACK ABOVE SHORT DOWN TACK;Sm;0;ON;;;;;N;;;;;
+2AEA;DOUBLE DOWN TACK;Sm;0;ON;;;;;N;;;;;
+2AEB;DOUBLE UP TACK;Sm;0;ON;;;;;N;;;;;
+2AEC;DOUBLE STROKE NOT SIGN;Sm;0;ON;;;;;Y;;;;;
+2AED;REVERSED DOUBLE STROKE NOT SIGN;Sm;0;ON;;;;;Y;;;;;
+2AEE;DOES NOT DIVIDE WITH REVERSED NEGATION SLASH;Sm;0;ON;;;;;Y;;;;;
+2AEF;VERTICAL LINE WITH CIRCLE ABOVE;Sm;0;ON;;;;;N;;;;;
+2AF0;VERTICAL LINE WITH CIRCLE BELOW;Sm;0;ON;;;;;N;;;;;
+2AF1;DOWN TACK WITH CIRCLE BELOW;Sm;0;ON;;;;;N;;;;;
+2AF2;PARALLEL WITH HORIZONTAL STROKE;Sm;0;ON;;;;;N;;;;;
+2AF3;PARALLEL WITH TILDE OPERATOR;Sm;0;ON;;;;;Y;;;;;
+2AF4;TRIPLE VERTICAL BAR BINARY RELATION;Sm;0;ON;;;;;N;;;;;
+2AF5;TRIPLE VERTICAL BAR WITH HORIZONTAL STROKE;Sm;0;ON;;;;;N;;;;;
+2AF6;TRIPLE COLON OPERATOR;Sm;0;ON;;;;;N;;;;;
+2AF7;TRIPLE NESTED LESS-THAN;Sm;0;ON;;;;;Y;;;;;
+2AF8;TRIPLE NESTED GREATER-THAN;Sm;0;ON;;;;;Y;;;;;
+2AF9;DOUBLE-LINE SLANTED LESS-THAN OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2AFA;DOUBLE-LINE SLANTED GREATER-THAN OR EQUAL TO;Sm;0;ON;;;;;Y;;;;;
+2AFB;TRIPLE SOLIDUS BINARY RELATION;Sm;0;ON;;;;;Y;;;;;
+2AFC;LARGE TRIPLE VERTICAL BAR OPERATOR;Sm;0;ON;;;;;N;;;;;
+2AFD;DOUBLE SOLIDUS OPERATOR;Sm;0;ON;;;;;Y;;;;;
+2AFE;WHITE VERTICAL BAR;Sm;0;ON;;;;;N;;;;;
+2AFF;N-ARY WHITE VERTICAL BAR;Sm;0;ON;;;;;N;;;;;
+2B00;NORTH EAST WHITE ARROW;So;0;ON;;;;;N;;;;;
+2B01;NORTH WEST WHITE ARROW;So;0;ON;;;;;N;;;;;
+2B02;SOUTH EAST WHITE ARROW;So;0;ON;;;;;N;;;;;
+2B03;SOUTH WEST WHITE ARROW;So;0;ON;;;;;N;;;;;
+2B04;LEFT RIGHT WHITE ARROW;So;0;ON;;;;;N;;;;;
+2B05;LEFTWARDS BLACK ARROW;So;0;ON;;;;;N;;;;;
+2B06;UPWARDS BLACK ARROW;So;0;ON;;;;;N;;;;;
+2B07;DOWNWARDS BLACK ARROW;So;0;ON;;;;;N;;;;;
+2B08;NORTH EAST BLACK ARROW;So;0;ON;;;;;N;;;;;
+2B09;NORTH WEST BLACK ARROW;So;0;ON;;;;;N;;;;;
+2B0A;SOUTH EAST BLACK ARROW;So;0;ON;;;;;N;;;;;
+2B0B;SOUTH WEST BLACK ARROW;So;0;ON;;;;;N;;;;;
+2B0C;LEFT RIGHT BLACK ARROW;So;0;ON;;;;;N;;;;;
+2B0D;UP DOWN BLACK ARROW;So;0;ON;;;;;N;;;;;
+2E80;CJK RADICAL REPEAT;So;0;ON;;;;;N;;;;;
+2E81;CJK RADICAL CLIFF;So;0;ON;;;;;N;;;;;
+2E82;CJK RADICAL SECOND ONE;So;0;ON;;;;;N;;;;;
+2E83;CJK RADICAL SECOND TWO;So;0;ON;;;;;N;;;;;
+2E84;CJK RADICAL SECOND THREE;So;0;ON;;;;;N;;;;;
+2E85;CJK RADICAL PERSON;So;0;ON;;;;;N;;;;;
+2E86;CJK RADICAL BOX;So;0;ON;;;;;N;;;;;
+2E87;CJK RADICAL TABLE;So;0;ON;;;;;N;;;;;
+2E88;CJK RADICAL KNIFE ONE;So;0;ON;;;;;N;;;;;
+2E89;CJK RADICAL KNIFE TWO;So;0;ON;;;;;N;;;;;
+2E8A;CJK RADICAL DIVINATION;So;0;ON;;;;;N;;;;;
+2E8B;CJK RADICAL SEAL;So;0;ON;;;;;N;;;;;
+2E8C;CJK RADICAL SMALL ONE;So;0;ON;;;;;N;;;;;
+2E8D;CJK RADICAL SMALL TWO;So;0;ON;;;;;N;;;;;
+2E8E;CJK RADICAL LAME ONE;So;0;ON;;;;;N;;;;;
+2E8F;CJK RADICAL LAME TWO;So;0;ON;;;;;N;;;;;
+2E90;CJK RADICAL LAME THREE;So;0;ON;;;;;N;;;;;
+2E91;CJK RADICAL LAME FOUR;So;0;ON;;;;;N;;;;;
+2E92;CJK RADICAL SNAKE;So;0;ON;;;;;N;;;;;
+2E93;CJK RADICAL THREAD;So;0;ON;;;;;N;;;;;
+2E94;CJK RADICAL SNOUT ONE;So;0;ON;;;;;N;;;;;
+2E95;CJK RADICAL SNOUT TWO;So;0;ON;;;;;N;;;;;
+2E96;CJK RADICAL HEART ONE;So;0;ON;;;;;N;;;;;
+2E97;CJK RADICAL HEART TWO;So;0;ON;;;;;N;;;;;
+2E98;CJK RADICAL HAND;So;0;ON;;;;;N;;;;;
+2E99;CJK RADICAL RAP;So;0;ON;;;;;N;;;;;
+2E9B;CJK RADICAL CHOKE;So;0;ON;;;;;N;;;;;
+2E9C;CJK RADICAL SUN;So;0;ON;;;;;N;;;;;
+2E9D;CJK RADICAL MOON;So;0;ON;;;;;N;;;;;
+2E9E;CJK RADICAL DEATH;So;0;ON;;;;;N;;;;;
+2E9F;CJK RADICAL MOTHER;So;0;ON;<compat> 6BCD;;;;N;;;;;
+2EA0;CJK RADICAL CIVILIAN;So;0;ON;;;;;N;;;;;
+2EA1;CJK RADICAL WATER ONE;So;0;ON;;;;;N;;;;;
+2EA2;CJK RADICAL WATER TWO;So;0;ON;;;;;N;;;;;
+2EA3;CJK RADICAL FIRE;So;0;ON;;;;;N;;;;;
+2EA4;CJK RADICAL PAW ONE;So;0;ON;;;;;N;;;;;
+2EA5;CJK RADICAL PAW TWO;So;0;ON;;;;;N;;;;;
+2EA6;CJK RADICAL SIMPLIFIED HALF TREE TRUNK;So;0;ON;;;;;N;;;;;
+2EA7;CJK RADICAL COW;So;0;ON;;;;;N;;;;;
+2EA8;CJK RADICAL DOG;So;0;ON;;;;;N;;;;;
+2EA9;CJK RADICAL JADE;So;0;ON;;;;;N;;;;;
+2EAA;CJK RADICAL BOLT OF CLOTH;So;0;ON;;;;;N;;;;;
+2EAB;CJK RADICAL EYE;So;0;ON;;;;;N;;;;;
+2EAC;CJK RADICAL SPIRIT ONE;So;0;ON;;;;;N;;;;;
+2EAD;CJK RADICAL SPIRIT TWO;So;0;ON;;;;;N;;;;;
+2EAE;CJK RADICAL BAMBOO;So;0;ON;;;;;N;;;;;
+2EAF;CJK RADICAL SILK;So;0;ON;;;;;N;;;;;
+2EB0;CJK RADICAL C-SIMPLIFIED SILK;So;0;ON;;;;;N;;;;;
+2EB1;CJK RADICAL NET ONE;So;0;ON;;;;;N;;;;;
+2EB2;CJK RADICAL NET TWO;So;0;ON;;;;;N;;;;;
+2EB3;CJK RADICAL NET THREE;So;0;ON;;;;;N;;;;;
+2EB4;CJK RADICAL NET FOUR;So;0;ON;;;;;N;;;;;
+2EB5;CJK RADICAL MESH;So;0;ON;;;;;N;;;;;
+2EB6;CJK RADICAL SHEEP;So;0;ON;;;;;N;;;;;
+2EB7;CJK RADICAL RAM;So;0;ON;;;;;N;;;;;
+2EB8;CJK RADICAL EWE;So;0;ON;;;;;N;;;;;
+2EB9;CJK RADICAL OLD;So;0;ON;;;;;N;;;;;
+2EBA;CJK RADICAL BRUSH ONE;So;0;ON;;;;;N;;;;;
+2EBB;CJK RADICAL BRUSH TWO;So;0;ON;;;;;N;;;;;
+2EBC;CJK RADICAL MEAT;So;0;ON;;;;;N;;;;;
+2EBD;CJK RADICAL MORTAR;So;0;ON;;;;;N;;;;;
+2EBE;CJK RADICAL GRASS ONE;So;0;ON;;;;;N;;;;;
+2EBF;CJK RADICAL GRASS TWO;So;0;ON;;;;;N;;;;;
+2EC0;CJK RADICAL GRASS THREE;So;0;ON;;;;;N;;;;;
+2EC1;CJK RADICAL TIGER;So;0;ON;;;;;N;;;;;
+2EC2;CJK RADICAL CLOTHES;So;0;ON;;;;;N;;;;;
+2EC3;CJK RADICAL WEST ONE;So;0;ON;;;;;N;;;;;
+2EC4;CJK RADICAL WEST TWO;So;0;ON;;;;;N;;;;;
+2EC5;CJK RADICAL C-SIMPLIFIED SEE;So;0;ON;;;;;N;;;;;
+2EC6;CJK RADICAL SIMPLIFIED HORN;So;0;ON;;;;;N;;;;;
+2EC7;CJK RADICAL HORN;So;0;ON;;;;;N;;;;;
+2EC8;CJK RADICAL C-SIMPLIFIED SPEECH;So;0;ON;;;;;N;;;;;
+2EC9;CJK RADICAL C-SIMPLIFIED SHELL;So;0;ON;;;;;N;;;;;
+2ECA;CJK RADICAL FOOT;So;0;ON;;;;;N;;;;;
+2ECB;CJK RADICAL C-SIMPLIFIED CART;So;0;ON;;;;;N;;;;;
+2ECC;CJK RADICAL SIMPLIFIED WALK;So;0;ON;;;;;N;;;;;
+2ECD;CJK RADICAL WALK ONE;So;0;ON;;;;;N;;;;;
+2ECE;CJK RADICAL WALK TWO;So;0;ON;;;;;N;;;;;
+2ECF;CJK RADICAL CITY;So;0;ON;;;;;N;;;;;
+2ED0;CJK RADICAL C-SIMPLIFIED GOLD;So;0;ON;;;;;N;;;;;
+2ED1;CJK RADICAL LONG ONE;So;0;ON;;;;;N;;;;;
+2ED2;CJK RADICAL LONG TWO;So;0;ON;;;;;N;;;;;
+2ED3;CJK RADICAL C-SIMPLIFIED LONG;So;0;ON;;;;;N;;;;;
+2ED4;CJK RADICAL C-SIMPLIFIED GATE;So;0;ON;;;;;N;;;;;
+2ED5;CJK RADICAL MOUND ONE;So;0;ON;;;;;N;;;;;
+2ED6;CJK RADICAL MOUND TWO;So;0;ON;;;;;N;;;;;
+2ED7;CJK RADICAL RAIN;So;0;ON;;;;;N;;;;;
+2ED8;CJK RADICAL BLUE;So;0;ON;;;;;N;;;;;
+2ED9;CJK RADICAL C-SIMPLIFIED TANNED LEATHER;So;0;ON;;;;;N;;;;;
+2EDA;CJK RADICAL C-SIMPLIFIED LEAF;So;0;ON;;;;;N;;;;;
+2EDB;CJK RADICAL C-SIMPLIFIED WIND;So;0;ON;;;;;N;;;;;
+2EDC;CJK RADICAL C-SIMPLIFIED FLY;So;0;ON;;;;;N;;;;;
+2EDD;CJK RADICAL EAT ONE;So;0;ON;;;;;N;;;;;
+2EDE;CJK RADICAL EAT TWO;So;0;ON;;;;;N;;;;;
+2EDF;CJK RADICAL EAT THREE;So;0;ON;;;;;N;;;;;
+2EE0;CJK RADICAL C-SIMPLIFIED EAT;So;0;ON;;;;;N;;;;;
+2EE1;CJK RADICAL HEAD;So;0;ON;;;;;N;;;;;
+2EE2;CJK RADICAL C-SIMPLIFIED HORSE;So;0;ON;;;;;N;;;;;
+2EE3;CJK RADICAL BONE;So;0;ON;;;;;N;;;;;
+2EE4;CJK RADICAL GHOST;So;0;ON;;;;;N;;;;;
+2EE5;CJK RADICAL C-SIMPLIFIED FISH;So;0;ON;;;;;N;;;;;
+2EE6;CJK RADICAL C-SIMPLIFIED BIRD;So;0;ON;;;;;N;;;;;
+2EE7;CJK RADICAL C-SIMPLIFIED SALT;So;0;ON;;;;;N;;;;;
+2EE8;CJK RADICAL SIMPLIFIED WHEAT;So;0;ON;;;;;N;;;;;
+2EE9;CJK RADICAL SIMPLIFIED YELLOW;So;0;ON;;;;;N;;;;;
+2EEA;CJK RADICAL C-SIMPLIFIED FROG;So;0;ON;;;;;N;;;;;
+2EEB;CJK RADICAL J-SIMPLIFIED EVEN;So;0;ON;;;;;N;;;;;
+2EEC;CJK RADICAL C-SIMPLIFIED EVEN;So;0;ON;;;;;N;;;;;
+2EED;CJK RADICAL J-SIMPLIFIED TOOTH;So;0;ON;;;;;N;;;;;
+2EEE;CJK RADICAL C-SIMPLIFIED TOOTH;So;0;ON;;;;;N;;;;;
+2EEF;CJK RADICAL J-SIMPLIFIED DRAGON;So;0;ON;;;;;N;;;;;
+2EF0;CJK RADICAL C-SIMPLIFIED DRAGON;So;0;ON;;;;;N;;;;;
+2EF1;CJK RADICAL TURTLE;So;0;ON;;;;;N;;;;;
+2EF2;CJK RADICAL J-SIMPLIFIED TURTLE;So;0;ON;;;;;N;;;;;
+2EF3;CJK RADICAL C-SIMPLIFIED TURTLE;So;0;ON;<compat> 9F9F;;;;N;;;;;
+2F00;KANGXI RADICAL ONE;So;0;ON;<compat> 4E00;;;;N;;;;;
+2F01;KANGXI RADICAL LINE;So;0;ON;<compat> 4E28;;;;N;;;;;
+2F02;KANGXI RADICAL DOT;So;0;ON;<compat> 4E36;;;;N;;;;;
+2F03;KANGXI RADICAL SLASH;So;0;ON;<compat> 4E3F;;;;N;;;;;
+2F04;KANGXI RADICAL SECOND;So;0;ON;<compat> 4E59;;;;N;;;;;
+2F05;KANGXI RADICAL HOOK;So;0;ON;<compat> 4E85;;;;N;;;;;
+2F06;KANGXI RADICAL TWO;So;0;ON;<compat> 4E8C;;;;N;;;;;
+2F07;KANGXI RADICAL LID;So;0;ON;<compat> 4EA0;;;;N;;;;;
+2F08;KANGXI RADICAL MAN;So;0;ON;<compat> 4EBA;;;;N;;;;;
+2F09;KANGXI RADICAL LEGS;So;0;ON;<compat> 513F;;;;N;;;;;
+2F0A;KANGXI RADICAL ENTER;So;0;ON;<compat> 5165;;;;N;;;;;
+2F0B;KANGXI RADICAL EIGHT;So;0;ON;<compat> 516B;;;;N;;;;;
+2F0C;KANGXI RADICAL DOWN BOX;So;0;ON;<compat> 5182;;;;N;;;;;
+2F0D;KANGXI RADICAL COVER;So;0;ON;<compat> 5196;;;;N;;;;;
+2F0E;KANGXI RADICAL ICE;So;0;ON;<compat> 51AB;;;;N;;;;;
+2F0F;KANGXI RADICAL TABLE;So;0;ON;<compat> 51E0;;;;N;;;;;
+2F10;KANGXI RADICAL OPEN BOX;So;0;ON;<compat> 51F5;;;;N;;;;;
+2F11;KANGXI RADICAL KNIFE;So;0;ON;<compat> 5200;;;;N;;;;;
+2F12;KANGXI RADICAL POWER;So;0;ON;<compat> 529B;;;;N;;;;;
+2F13;KANGXI RADICAL WRAP;So;0;ON;<compat> 52F9;;;;N;;;;;
+2F14;KANGXI RADICAL SPOON;So;0;ON;<compat> 5315;;;;N;;;;;
+2F15;KANGXI RADICAL RIGHT OPEN BOX;So;0;ON;<compat> 531A;;;;N;;;;;
+2F16;KANGXI RADICAL HIDING ENCLOSURE;So;0;ON;<compat> 5338;;;;N;;;;;
+2F17;KANGXI RADICAL TEN;So;0;ON;<compat> 5341;;;;N;;;;;
+2F18;KANGXI RADICAL DIVINATION;So;0;ON;<compat> 535C;;;;N;;;;;
+2F19;KANGXI RADICAL SEAL;So;0;ON;<compat> 5369;;;;N;;;;;
+2F1A;KANGXI RADICAL CLIFF;So;0;ON;<compat> 5382;;;;N;;;;;
+2F1B;KANGXI RADICAL PRIVATE;So;0;ON;<compat> 53B6;;;;N;;;;;
+2F1C;KANGXI RADICAL AGAIN;So;0;ON;<compat> 53C8;;;;N;;;;;
+2F1D;KANGXI RADICAL MOUTH;So;0;ON;<compat> 53E3;;;;N;;;;;
+2F1E;KANGXI RADICAL ENCLOSURE;So;0;ON;<compat> 56D7;;;;N;;;;;
+2F1F;KANGXI RADICAL EARTH;So;0;ON;<compat> 571F;;;;N;;;;;
+2F20;KANGXI RADICAL SCHOLAR;So;0;ON;<compat> 58EB;;;;N;;;;;
+2F21;KANGXI RADICAL GO;So;0;ON;<compat> 5902;;;;N;;;;;
+2F22;KANGXI RADICAL GO SLOWLY;So;0;ON;<compat> 590A;;;;N;;;;;
+2F23;KANGXI RADICAL EVENING;So;0;ON;<compat> 5915;;;;N;;;;;
+2F24;KANGXI RADICAL BIG;So;0;ON;<compat> 5927;;;;N;;;;;
+2F25;KANGXI RADICAL WOMAN;So;0;ON;<compat> 5973;;;;N;;;;;
+2F26;KANGXI RADICAL CHILD;So;0;ON;<compat> 5B50;;;;N;;;;;
+2F27;KANGXI RADICAL ROOF;So;0;ON;<compat> 5B80;;;;N;;;;;
+2F28;KANGXI RADICAL INCH;So;0;ON;<compat> 5BF8;;;;N;;;;;
+2F29;KANGXI RADICAL SMALL;So;0;ON;<compat> 5C0F;;;;N;;;;;
+2F2A;KANGXI RADICAL LAME;So;0;ON;<compat> 5C22;;;;N;;;;;
+2F2B;KANGXI RADICAL CORPSE;So;0;ON;<compat> 5C38;;;;N;;;;;
+2F2C;KANGXI RADICAL SPROUT;So;0;ON;<compat> 5C6E;;;;N;;;;;
+2F2D;KANGXI RADICAL MOUNTAIN;So;0;ON;<compat> 5C71;;;;N;;;;;
+2F2E;KANGXI RADICAL RIVER;So;0;ON;<compat> 5DDB;;;;N;;;;;
+2F2F;KANGXI RADICAL WORK;So;0;ON;<compat> 5DE5;;;;N;;;;;
+2F30;KANGXI RADICAL ONESELF;So;0;ON;<compat> 5DF1;;;;N;;;;;
+2F31;KANGXI RADICAL TURBAN;So;0;ON;<compat> 5DFE;;;;N;;;;;
+2F32;KANGXI RADICAL DRY;So;0;ON;<compat> 5E72;;;;N;;;;;
+2F33;KANGXI RADICAL SHORT THREAD;So;0;ON;<compat> 5E7A;;;;N;;;;;
+2F34;KANGXI RADICAL DOTTED CLIFF;So;0;ON;<compat> 5E7F;;;;N;;;;;
+2F35;KANGXI RADICAL LONG STRIDE;So;0;ON;<compat> 5EF4;;;;N;;;;;
+2F36;KANGXI RADICAL TWO HANDS;So;0;ON;<compat> 5EFE;;;;N;;;;;
+2F37;KANGXI RADICAL SHOOT;So;0;ON;<compat> 5F0B;;;;N;;;;;
+2F38;KANGXI RADICAL BOW;So;0;ON;<compat> 5F13;;;;N;;;;;
+2F39;KANGXI RADICAL SNOUT;So;0;ON;<compat> 5F50;;;;N;;;;;
+2F3A;KANGXI RADICAL BRISTLE;So;0;ON;<compat> 5F61;;;;N;;;;;
+2F3B;KANGXI RADICAL STEP;So;0;ON;<compat> 5F73;;;;N;;;;;
+2F3C;KANGXI RADICAL HEART;So;0;ON;<compat> 5FC3;;;;N;;;;;
+2F3D;KANGXI RADICAL HALBERD;So;0;ON;<compat> 6208;;;;N;;;;;
+2F3E;KANGXI RADICAL DOOR;So;0;ON;<compat> 6236;;;;N;;;;;
+2F3F;KANGXI RADICAL HAND;So;0;ON;<compat> 624B;;;;N;;;;;
+2F40;KANGXI RADICAL BRANCH;So;0;ON;<compat> 652F;;;;N;;;;;
+2F41;KANGXI RADICAL RAP;So;0;ON;<compat> 6534;;;;N;;;;;
+2F42;KANGXI RADICAL SCRIPT;So;0;ON;<compat> 6587;;;;N;;;;;
+2F43;KANGXI RADICAL DIPPER;So;0;ON;<compat> 6597;;;;N;;;;;
+2F44;KANGXI RADICAL AXE;So;0;ON;<compat> 65A4;;;;N;;;;;
+2F45;KANGXI RADICAL SQUARE;So;0;ON;<compat> 65B9;;;;N;;;;;
+2F46;KANGXI RADICAL NOT;So;0;ON;<compat> 65E0;;;;N;;;;;
+2F47;KANGXI RADICAL SUN;So;0;ON;<compat> 65E5;;;;N;;;;;
+2F48;KANGXI RADICAL SAY;So;0;ON;<compat> 66F0;;;;N;;;;;
+2F49;KANGXI RADICAL MOON;So;0;ON;<compat> 6708;;;;N;;;;;
+2F4A;KANGXI RADICAL TREE;So;0;ON;<compat> 6728;;;;N;;;;;
+2F4B;KANGXI RADICAL LACK;So;0;ON;<compat> 6B20;;;;N;;;;;
+2F4C;KANGXI RADICAL STOP;So;0;ON;<compat> 6B62;;;;N;;;;;
+2F4D;KANGXI RADICAL DEATH;So;0;ON;<compat> 6B79;;;;N;;;;;
+2F4E;KANGXI RADICAL WEAPON;So;0;ON;<compat> 6BB3;;;;N;;;;;
+2F4F;KANGXI RADICAL DO NOT;So;0;ON;<compat> 6BCB;;;;N;;;;;
+2F50;KANGXI RADICAL COMPARE;So;0;ON;<compat> 6BD4;;;;N;;;;;
+2F51;KANGXI RADICAL FUR;So;0;ON;<compat> 6BDB;;;;N;;;;;
+2F52;KANGXI RADICAL CLAN;So;0;ON;<compat> 6C0F;;;;N;;;;;
+2F53;KANGXI RADICAL STEAM;So;0;ON;<compat> 6C14;;;;N;;;;;
+2F54;KANGXI RADICAL WATER;So;0;ON;<compat> 6C34;;;;N;;;;;
+2F55;KANGXI RADICAL FIRE;So;0;ON;<compat> 706B;;;;N;;;;;
+2F56;KANGXI RADICAL CLAW;So;0;ON;<compat> 722A;;;;N;;;;;
+2F57;KANGXI RADICAL FATHER;So;0;ON;<compat> 7236;;;;N;;;;;
+2F58;KANGXI RADICAL DOUBLE X;So;0;ON;<compat> 723B;;;;N;;;;;
+2F59;KANGXI RADICAL HALF TREE TRUNK;So;0;ON;<compat> 723F;;;;N;;;;;
+2F5A;KANGXI RADICAL SLICE;So;0;ON;<compat> 7247;;;;N;;;;;
+2F5B;KANGXI RADICAL FANG;So;0;ON;<compat> 7259;;;;N;;;;;
+2F5C;KANGXI RADICAL COW;So;0;ON;<compat> 725B;;;;N;;;;;
+2F5D;KANGXI RADICAL DOG;So;0;ON;<compat> 72AC;;;;N;;;;;
+2F5E;KANGXI RADICAL PROFOUND;So;0;ON;<compat> 7384;;;;N;;;;;
+2F5F;KANGXI RADICAL JADE;So;0;ON;<compat> 7389;;;;N;;;;;
+2F60;KANGXI RADICAL MELON;So;0;ON;<compat> 74DC;;;;N;;;;;
+2F61;KANGXI RADICAL TILE;So;0;ON;<compat> 74E6;;;;N;;;;;
+2F62;KANGXI RADICAL SWEET;So;0;ON;<compat> 7518;;;;N;;;;;
+2F63;KANGXI RADICAL LIFE;So;0;ON;<compat> 751F;;;;N;;;;;
+2F64;KANGXI RADICAL USE;So;0;ON;<compat> 7528;;;;N;;;;;
+2F65;KANGXI RADICAL FIELD;So;0;ON;<compat> 7530;;;;N;;;;;
+2F66;KANGXI RADICAL BOLT OF CLOTH;So;0;ON;<compat> 758B;;;;N;;;;;
+2F67;KANGXI RADICAL SICKNESS;So;0;ON;<compat> 7592;;;;N;;;;;
+2F68;KANGXI RADICAL DOTTED TENT;So;0;ON;<compat> 7676;;;;N;;;;;
+2F69;KANGXI RADICAL WHITE;So;0;ON;<compat> 767D;;;;N;;;;;
+2F6A;KANGXI RADICAL SKIN;So;0;ON;<compat> 76AE;;;;N;;;;;
+2F6B;KANGXI RADICAL DISH;So;0;ON;<compat> 76BF;;;;N;;;;;
+2F6C;KANGXI RADICAL EYE;So;0;ON;<compat> 76EE;;;;N;;;;;
+2F6D;KANGXI RADICAL SPEAR;So;0;ON;<compat> 77DB;;;;N;;;;;
+2F6E;KANGXI RADICAL ARROW;So;0;ON;<compat> 77E2;;;;N;;;;;
+2F6F;KANGXI RADICAL STONE;So;0;ON;<compat> 77F3;;;;N;;;;;
+2F70;KANGXI RADICAL SPIRIT;So;0;ON;<compat> 793A;;;;N;;;;;
+2F71;KANGXI RADICAL TRACK;So;0;ON;<compat> 79B8;;;;N;;;;;
+2F72;KANGXI RADICAL GRAIN;So;0;ON;<compat> 79BE;;;;N;;;;;
+2F73;KANGXI RADICAL CAVE;So;0;ON;<compat> 7A74;;;;N;;;;;
+2F74;KANGXI RADICAL STAND;So;0;ON;<compat> 7ACB;;;;N;;;;;
+2F75;KANGXI RADICAL BAMBOO;So;0;ON;<compat> 7AF9;;;;N;;;;;
+2F76;KANGXI RADICAL RICE;So;0;ON;<compat> 7C73;;;;N;;;;;
+2F77;KANGXI RADICAL SILK;So;0;ON;<compat> 7CF8;;;;N;;;;;
+2F78;KANGXI RADICAL JAR;So;0;ON;<compat> 7F36;;;;N;;;;;
+2F79;KANGXI RADICAL NET;So;0;ON;<compat> 7F51;;;;N;;;;;
+2F7A;KANGXI RADICAL SHEEP;So;0;ON;<compat> 7F8A;;;;N;;;;;
+2F7B;KANGXI RADICAL FEATHER;So;0;ON;<compat> 7FBD;;;;N;;;;;
+2F7C;KANGXI RADICAL OLD;So;0;ON;<compat> 8001;;;;N;;;;;
+2F7D;KANGXI RADICAL AND;So;0;ON;<compat> 800C;;;;N;;;;;
+2F7E;KANGXI RADICAL PLOW;So;0;ON;<compat> 8012;;;;N;;;;;
+2F7F;KANGXI RADICAL EAR;So;0;ON;<compat> 8033;;;;N;;;;;
+2F80;KANGXI RADICAL BRUSH;So;0;ON;<compat> 807F;;;;N;;;;;
+2F81;KANGXI RADICAL MEAT;So;0;ON;<compat> 8089;;;;N;;;;;
+2F82;KANGXI RADICAL MINISTER;So;0;ON;<compat> 81E3;;;;N;;;;;
+2F83;KANGXI RADICAL SELF;So;0;ON;<compat> 81EA;;;;N;;;;;
+2F84;KANGXI RADICAL ARRIVE;So;0;ON;<compat> 81F3;;;;N;;;;;
+2F85;KANGXI RADICAL MORTAR;So;0;ON;<compat> 81FC;;;;N;;;;;
+2F86;KANGXI RADICAL TONGUE;So;0;ON;<compat> 820C;;;;N;;;;;
+2F87;KANGXI RADICAL OPPOSE;So;0;ON;<compat> 821B;;;;N;;;;;
+2F88;KANGXI RADICAL BOAT;So;0;ON;<compat> 821F;;;;N;;;;;
+2F89;KANGXI RADICAL STOPPING;So;0;ON;<compat> 826E;;;;N;;;;;
+2F8A;KANGXI RADICAL COLOR;So;0;ON;<compat> 8272;;;;N;;;;;
+2F8B;KANGXI RADICAL GRASS;So;0;ON;<compat> 8278;;;;N;;;;;
+2F8C;KANGXI RADICAL TIGER;So;0;ON;<compat> 864D;;;;N;;;;;
+2F8D;KANGXI RADICAL INSECT;So;0;ON;<compat> 866B;;;;N;;;;;
+2F8E;KANGXI RADICAL BLOOD;So;0;ON;<compat> 8840;;;;N;;;;;
+2F8F;KANGXI RADICAL WALK ENCLOSURE;So;0;ON;<compat> 884C;;;;N;;;;;
+2F90;KANGXI RADICAL CLOTHES;So;0;ON;<compat> 8863;;;;N;;;;;
+2F91;KANGXI RADICAL WEST;So;0;ON;<compat> 897E;;;;N;;;;;
+2F92;KANGXI RADICAL SEE;So;0;ON;<compat> 898B;;;;N;;;;;
+2F93;KANGXI RADICAL HORN;So;0;ON;<compat> 89D2;;;;N;;;;;
+2F94;KANGXI RADICAL SPEECH;So;0;ON;<compat> 8A00;;;;N;;;;;
+2F95;KANGXI RADICAL VALLEY;So;0;ON;<compat> 8C37;;;;N;;;;;
+2F96;KANGXI RADICAL BEAN;So;0;ON;<compat> 8C46;;;;N;;;;;
+2F97;KANGXI RADICAL PIG;So;0;ON;<compat> 8C55;;;;N;;;;;
+2F98;KANGXI RADICAL BADGER;So;0;ON;<compat> 8C78;;;;N;;;;;
+2F99;KANGXI RADICAL SHELL;So;0;ON;<compat> 8C9D;;;;N;;;;;
+2F9A;KANGXI RADICAL RED;So;0;ON;<compat> 8D64;;;;N;;;;;
+2F9B;KANGXI RADICAL RUN;So;0;ON;<compat> 8D70;;;;N;;;;;
+2F9C;KANGXI RADICAL FOOT;So;0;ON;<compat> 8DB3;;;;N;;;;;
+2F9D;KANGXI RADICAL BODY;So;0;ON;<compat> 8EAB;;;;N;;;;;
+2F9E;KANGXI RADICAL CART;So;0;ON;<compat> 8ECA;;;;N;;;;;
+2F9F;KANGXI RADICAL BITTER;So;0;ON;<compat> 8F9B;;;;N;;;;;
+2FA0;KANGXI RADICAL MORNING;So;0;ON;<compat> 8FB0;;;;N;;;;;
+2FA1;KANGXI RADICAL WALK;So;0;ON;<compat> 8FB5;;;;N;;;;;
+2FA2;KANGXI RADICAL CITY;So;0;ON;<compat> 9091;;;;N;;;;;
+2FA3;KANGXI RADICAL WINE;So;0;ON;<compat> 9149;;;;N;;;;;
+2FA4;KANGXI RADICAL DISTINGUISH;So;0;ON;<compat> 91C6;;;;N;;;;;
+2FA5;KANGXI RADICAL VILLAGE;So;0;ON;<compat> 91CC;;;;N;;;;;
+2FA6;KANGXI RADICAL GOLD;So;0;ON;<compat> 91D1;;;;N;;;;;
+2FA7;KANGXI RADICAL LONG;So;0;ON;<compat> 9577;;;;N;;;;;
+2FA8;KANGXI RADICAL GATE;So;0;ON;<compat> 9580;;;;N;;;;;
+2FA9;KANGXI RADICAL MOUND;So;0;ON;<compat> 961C;;;;N;;;;;
+2FAA;KANGXI RADICAL SLAVE;So;0;ON;<compat> 96B6;;;;N;;;;;
+2FAB;KANGXI RADICAL SHORT TAILED BIRD;So;0;ON;<compat> 96B9;;;;N;;;;;
+2FAC;KANGXI RADICAL RAIN;So;0;ON;<compat> 96E8;;;;N;;;;;
+2FAD;KANGXI RADICAL BLUE;So;0;ON;<compat> 9751;;;;N;;;;;
+2FAE;KANGXI RADICAL WRONG;So;0;ON;<compat> 975E;;;;N;;;;;
+2FAF;KANGXI RADICAL FACE;So;0;ON;<compat> 9762;;;;N;;;;;
+2FB0;KANGXI RADICAL LEATHER;So;0;ON;<compat> 9769;;;;N;;;;;
+2FB1;KANGXI RADICAL TANNED LEATHER;So;0;ON;<compat> 97CB;;;;N;;;;;
+2FB2;KANGXI RADICAL LEEK;So;0;ON;<compat> 97ED;;;;N;;;;;
+2FB3;KANGXI RADICAL SOUND;So;0;ON;<compat> 97F3;;;;N;;;;;
+2FB4;KANGXI RADICAL LEAF;So;0;ON;<compat> 9801;;;;N;;;;;
+2FB5;KANGXI RADICAL WIND;So;0;ON;<compat> 98A8;;;;N;;;;;
+2FB6;KANGXI RADICAL FLY;So;0;ON;<compat> 98DB;;;;N;;;;;
+2FB7;KANGXI RADICAL EAT;So;0;ON;<compat> 98DF;;;;N;;;;;
+2FB8;KANGXI RADICAL HEAD;So;0;ON;<compat> 9996;;;;N;;;;;
+2FB9;KANGXI RADICAL FRAGRANT;So;0;ON;<compat> 9999;;;;N;;;;;
+2FBA;KANGXI RADICAL HORSE;So;0;ON;<compat> 99AC;;;;N;;;;;
+2FBB;KANGXI RADICAL BONE;So;0;ON;<compat> 9AA8;;;;N;;;;;
+2FBC;KANGXI RADICAL TALL;So;0;ON;<compat> 9AD8;;;;N;;;;;
+2FBD;KANGXI RADICAL HAIR;So;0;ON;<compat> 9ADF;;;;N;;;;;
+2FBE;KANGXI RADICAL FIGHT;So;0;ON;<compat> 9B25;;;;N;;;;;
+2FBF;KANGXI RADICAL SACRIFICIAL WINE;So;0;ON;<compat> 9B2F;;;;N;;;;;
+2FC0;KANGXI RADICAL CAULDRON;So;0;ON;<compat> 9B32;;;;N;;;;;
+2FC1;KANGXI RADICAL GHOST;So;0;ON;<compat> 9B3C;;;;N;;;;;
+2FC2;KANGXI RADICAL FISH;So;0;ON;<compat> 9B5A;;;;N;;;;;
+2FC3;KANGXI RADICAL BIRD;So;0;ON;<compat> 9CE5;;;;N;;;;;
+2FC4;KANGXI RADICAL SALT;So;0;ON;<compat> 9E75;;;;N;;;;;
+2FC5;KANGXI RADICAL DEER;So;0;ON;<compat> 9E7F;;;;N;;;;;
+2FC6;KANGXI RADICAL WHEAT;So;0;ON;<compat> 9EA5;;;;N;;;;;
+2FC7;KANGXI RADICAL HEMP;So;0;ON;<compat> 9EBB;;;;N;;;;;
+2FC8;KANGXI RADICAL YELLOW;So;0;ON;<compat> 9EC3;;;;N;;;;;
+2FC9;KANGXI RADICAL MILLET;So;0;ON;<compat> 9ECD;;;;N;;;;;
+2FCA;KANGXI RADICAL BLACK;So;0;ON;<compat> 9ED1;;;;N;;;;;
+2FCB;KANGXI RADICAL EMBROIDERY;So;0;ON;<compat> 9EF9;;;;N;;;;;
+2FCC;KANGXI RADICAL FROG;So;0;ON;<compat> 9EFD;;;;N;;;;;
+2FCD;KANGXI RADICAL TRIPOD;So;0;ON;<compat> 9F0E;;;;N;;;;;
+2FCE;KANGXI RADICAL DRUM;So;0;ON;<compat> 9F13;;;;N;;;;;
+2FCF;KANGXI RADICAL RAT;So;0;ON;<compat> 9F20;;;;N;;;;;
+2FD0;KANGXI RADICAL NOSE;So;0;ON;<compat> 9F3B;;;;N;;;;;
+2FD1;KANGXI RADICAL EVEN;So;0;ON;<compat> 9F4A;;;;N;;;;;
+2FD2;KANGXI RADICAL TOOTH;So;0;ON;<compat> 9F52;;;;N;;;;;
+2FD3;KANGXI RADICAL DRAGON;So;0;ON;<compat> 9F8D;;;;N;;;;;
+2FD4;KANGXI RADICAL TURTLE;So;0;ON;<compat> 9F9C;;;;N;;;;;
+2FD5;KANGXI RADICAL FLUTE;So;0;ON;<compat> 9FA0;;;;N;;;;;
+2FF0;IDEOGRAPHIC DESCRIPTION CHARACTER LEFT TO RIGHT;So;0;ON;;;;;N;;;;;
+2FF1;IDEOGRAPHIC DESCRIPTION CHARACTER ABOVE TO BELOW;So;0;ON;;;;;N;;;;;
+2FF2;IDEOGRAPHIC DESCRIPTION CHARACTER LEFT TO MIDDLE AND RIGHT;So;0;ON;;;;;N;;;;;
+2FF3;IDEOGRAPHIC DESCRIPTION CHARACTER ABOVE TO MIDDLE AND BELOW;So;0;ON;;;;;N;;;;;
+2FF4;IDEOGRAPHIC DESCRIPTION CHARACTER FULL SURROUND;So;0;ON;;;;;N;;;;;
+2FF5;IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM ABOVE;So;0;ON;;;;;N;;;;;
+2FF6;IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM BELOW;So;0;ON;;;;;N;;;;;
+2FF7;IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM LEFT;So;0;ON;;;;;N;;;;;
+2FF8;IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM UPPER LEFT;So;0;ON;;;;;N;;;;;
+2FF9;IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM UPPER RIGHT;So;0;ON;;;;;N;;;;;
+2FFA;IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM LOWER LEFT;So;0;ON;;;;;N;;;;;
+2FFB;IDEOGRAPHIC DESCRIPTION CHARACTER OVERLAID;So;0;ON;;;;;N;;;;;
+3000;IDEOGRAPHIC SPACE;Zs;0;WS;<wide> 0020;;;;N;;;;;
+3001;IDEOGRAPHIC COMMA;Po;0;ON;;;;;N;;;;;
+3002;IDEOGRAPHIC FULL STOP;Po;0;ON;;;;;N;IDEOGRAPHIC PERIOD;;;;
+3003;DITTO MARK;Po;0;ON;;;;;N;;;;;
+3004;JAPANESE INDUSTRIAL STANDARD SYMBOL;So;0;ON;;;;;N;;;;;
+3005;IDEOGRAPHIC ITERATION MARK;Lm;0;L;;;;;N;;;;;
+3006;IDEOGRAPHIC CLOSING MARK;Lo;0;L;;;;;N;;;;;
+3007;IDEOGRAPHIC NUMBER ZERO;Nl;0;L;;;;0;N;;;;;
+3008;LEFT ANGLE BRACKET;Ps;0;ON;;;;;Y;OPENING ANGLE BRACKET;;;;
+3009;RIGHT ANGLE BRACKET;Pe;0;ON;;;;;Y;CLOSING ANGLE BRACKET;;;;
+300A;LEFT DOUBLE ANGLE BRACKET;Ps;0;ON;;;;;Y;OPENING DOUBLE ANGLE BRACKET;;;;
+300B;RIGHT DOUBLE ANGLE BRACKET;Pe;0;ON;;;;;Y;CLOSING DOUBLE ANGLE BRACKET;;;;
+300C;LEFT CORNER BRACKET;Ps;0;ON;;;;;Y;OPENING CORNER BRACKET;;;;
+300D;RIGHT CORNER BRACKET;Pe;0;ON;;;;;Y;CLOSING CORNER BRACKET;;;;
+300E;LEFT WHITE CORNER BRACKET;Ps;0;ON;;;;;Y;OPENING WHITE CORNER BRACKET;;;;
+300F;RIGHT WHITE CORNER BRACKET;Pe;0;ON;;;;;Y;CLOSING WHITE CORNER BRACKET;;;;
+3010;LEFT BLACK LENTICULAR BRACKET;Ps;0;ON;;;;;Y;OPENING BLACK LENTICULAR BRACKET;;;;
+3011;RIGHT BLACK LENTICULAR BRACKET;Pe;0;ON;;;;;Y;CLOSING BLACK LENTICULAR BRACKET;;;;
+3012;POSTAL MARK;So;0;ON;;;;;N;;;;;
+3013;GETA MARK;So;0;ON;;;;;N;;;;;
+3014;LEFT TORTOISE SHELL BRACKET;Ps;0;ON;;;;;Y;OPENING TORTOISE SHELL BRACKET;;;;
+3015;RIGHT TORTOISE SHELL BRACKET;Pe;0;ON;;;;;Y;CLOSING TORTOISE SHELL BRACKET;;;;
+3016;LEFT WHITE LENTICULAR BRACKET;Ps;0;ON;;;;;Y;OPENING WHITE LENTICULAR BRACKET;;;;
+3017;RIGHT WHITE LENTICULAR BRACKET;Pe;0;ON;;;;;Y;CLOSING WHITE LENTICULAR BRACKET;;;;
+3018;LEFT WHITE TORTOISE SHELL BRACKET;Ps;0;ON;;;;;Y;OPENING WHITE TORTOISE SHELL BRACKET;;;;
+3019;RIGHT WHITE TORTOISE SHELL BRACKET;Pe;0;ON;;;;;Y;CLOSING WHITE TORTOISE SHELL BRACKET;;;;
+301A;LEFT WHITE SQUARE BRACKET;Ps;0;ON;;;;;Y;OPENING WHITE SQUARE BRACKET;;;;
+301B;RIGHT WHITE SQUARE BRACKET;Pe;0;ON;;;;;Y;CLOSING WHITE SQUARE BRACKET;;;;
+301C;WAVE DASH;Pd;0;ON;;;;;N;;;;;
+301D;REVERSED DOUBLE PRIME QUOTATION MARK;Ps;0;ON;;;;;N;;;;;
+301E;DOUBLE PRIME QUOTATION MARK;Pe;0;ON;;;;;N;;;;;
+301F;LOW DOUBLE PRIME QUOTATION MARK;Pe;0;ON;;;;;N;;;;;
+3020;POSTAL MARK FACE;So;0;ON;;;;;N;;;;;
+3021;HANGZHOU NUMERAL ONE;Nl;0;L;;;;1;N;;;;;
+3022;HANGZHOU NUMERAL TWO;Nl;0;L;;;;2;N;;;;;
+3023;HANGZHOU NUMERAL THREE;Nl;0;L;;;;3;N;;;;;
+3024;HANGZHOU NUMERAL FOUR;Nl;0;L;;;;4;N;;;;;
+3025;HANGZHOU NUMERAL FIVE;Nl;0;L;;;;5;N;;;;;
+3026;HANGZHOU NUMERAL SIX;Nl;0;L;;;;6;N;;;;;
+3027;HANGZHOU NUMERAL SEVEN;Nl;0;L;;;;7;N;;;;;
+3028;HANGZHOU NUMERAL EIGHT;Nl;0;L;;;;8;N;;;;;
+3029;HANGZHOU NUMERAL NINE;Nl;0;L;;;;9;N;;;;;
+302A;IDEOGRAPHIC LEVEL TONE MARK;Mn;218;NSM;;;;;N;;;;;
+302B;IDEOGRAPHIC RISING TONE MARK;Mn;228;NSM;;;;;N;;;;;
+302C;IDEOGRAPHIC DEPARTING TONE MARK;Mn;232;NSM;;;;;N;;;;;
+302D;IDEOGRAPHIC ENTERING TONE MARK;Mn;222;NSM;;;;;N;;;;;
+302E;HANGUL SINGLE DOT TONE MARK;Mn;224;NSM;;;;;N;;;;;
+302F;HANGUL DOUBLE DOT TONE MARK;Mn;224;NSM;;;;;N;;;;;
+3030;WAVY DASH;Pd;0;ON;;;;;N;;;;;
+3031;VERTICAL KANA REPEAT MARK;Lm;0;L;;;;;N;;;;;
+3032;VERTICAL KANA REPEAT WITH VOICED SOUND MARK;Lm;0;L;;;;;N;;;;;
+3033;VERTICAL KANA REPEAT MARK UPPER HALF;Lm;0;L;;;;;N;;;;;
+3034;VERTICAL KANA REPEAT WITH VOICED SOUND MARK UPPER HALF;Lm;0;L;;;;;N;;;;;
+3035;VERTICAL KANA REPEAT MARK LOWER HALF;Lm;0;L;;;;;N;;;;;
+3036;CIRCLED POSTAL MARK;So;0;ON;<compat> 3012;;;;N;;;;;
+3037;IDEOGRAPHIC TELEGRAPH LINE FEED SEPARATOR SYMBOL;So;0;ON;;;;;N;;;;;
+3038;HANGZHOU NUMERAL TEN;Nl;0;L;<compat> 5341;;;10;N;;;;;
+3039;HANGZHOU NUMERAL TWENTY;Nl;0;L;<compat> 5344;;;20;N;;;;;
+303A;HANGZHOU NUMERAL THIRTY;Nl;0;L;<compat> 5345;;;30;N;;;;;
+303B;VERTICAL IDEOGRAPHIC ITERATION MARK;Lm;0;L;;;;;N;;;;;
+303C;MASU MARK;Lo;0;L;;;;;N;;;;;
+303D;PART ALTERNATION MARK;Po;0;ON;;;;;N;;;;;
+303E;IDEOGRAPHIC VARIATION INDICATOR;So;0;ON;;;;;N;;;;;
+303F;IDEOGRAPHIC HALF FILL SPACE;So;0;ON;;;;;N;;;;;
+3041;HIRAGANA LETTER SMALL A;Lo;0;L;;;;;N;;;;;
+3042;HIRAGANA LETTER A;Lo;0;L;;;;;N;;;;;
+3043;HIRAGANA LETTER SMALL I;Lo;0;L;;;;;N;;;;;
+3044;HIRAGANA LETTER I;Lo;0;L;;;;;N;;;;;
+3045;HIRAGANA LETTER SMALL U;Lo;0;L;;;;;N;;;;;
+3046;HIRAGANA LETTER U;Lo;0;L;;;;;N;;;;;
+3047;HIRAGANA LETTER SMALL E;Lo;0;L;;;;;N;;;;;
+3048;HIRAGANA LETTER E;Lo;0;L;;;;;N;;;;;
+3049;HIRAGANA LETTER SMALL O;Lo;0;L;;;;;N;;;;;
+304A;HIRAGANA LETTER O;Lo;0;L;;;;;N;;;;;
+304B;HIRAGANA LETTER KA;Lo;0;L;;;;;N;;;;;
+304C;HIRAGANA LETTER GA;Lo;0;L;304B 3099;;;;N;;;;;
+304D;HIRAGANA LETTER KI;Lo;0;L;;;;;N;;;;;
+304E;HIRAGANA LETTER GI;Lo;0;L;304D 3099;;;;N;;;;;
+304F;HIRAGANA LETTER KU;Lo;0;L;;;;;N;;;;;
+3050;HIRAGANA LETTER GU;Lo;0;L;304F 3099;;;;N;;;;;
+3051;HIRAGANA LETTER KE;Lo;0;L;;;;;N;;;;;
+3052;HIRAGANA LETTER GE;Lo;0;L;3051 3099;;;;N;;;;;
+3053;HIRAGANA LETTER KO;Lo;0;L;;;;;N;;;;;
+3054;HIRAGANA LETTER GO;Lo;0;L;3053 3099;;;;N;;;;;
+3055;HIRAGANA LETTER SA;Lo;0;L;;;;;N;;;;;
+3056;HIRAGANA LETTER ZA;Lo;0;L;3055 3099;;;;N;;;;;
+3057;HIRAGANA LETTER SI;Lo;0;L;;;;;N;;;;;
+3058;HIRAGANA LETTER ZI;Lo;0;L;3057 3099;;;;N;;;;;
+3059;HIRAGANA LETTER SU;Lo;0;L;;;;;N;;;;;
+305A;HIRAGANA LETTER ZU;Lo;0;L;3059 3099;;;;N;;;;;
+305B;HIRAGANA LETTER SE;Lo;0;L;;;;;N;;;;;
+305C;HIRAGANA LETTER ZE;Lo;0;L;305B 3099;;;;N;;;;;
+305D;HIRAGANA LETTER SO;Lo;0;L;;;;;N;;;;;
+305E;HIRAGANA LETTER ZO;Lo;0;L;305D 3099;;;;N;;;;;
+305F;HIRAGANA LETTER TA;Lo;0;L;;;;;N;;;;;
+3060;HIRAGANA LETTER DA;Lo;0;L;305F 3099;;;;N;;;;;
+3061;HIRAGANA LETTER TI;Lo;0;L;;;;;N;;;;;
+3062;HIRAGANA LETTER DI;Lo;0;L;3061 3099;;;;N;;;;;
+3063;HIRAGANA LETTER SMALL TU;Lo;0;L;;;;;N;;;;;
+3064;HIRAGANA LETTER TU;Lo;0;L;;;;;N;;;;;
+3065;HIRAGANA LETTER DU;Lo;0;L;3064 3099;;;;N;;;;;
+3066;HIRAGANA LETTER TE;Lo;0;L;;;;;N;;;;;
+3067;HIRAGANA LETTER DE;Lo;0;L;3066 3099;;;;N;;;;;
+3068;HIRAGANA LETTER TO;Lo;0;L;;;;;N;;;;;
+3069;HIRAGANA LETTER DO;Lo;0;L;3068 3099;;;;N;;;;;
+306A;HIRAGANA LETTER NA;Lo;0;L;;;;;N;;;;;
+306B;HIRAGANA LETTER NI;Lo;0;L;;;;;N;;;;;
+306C;HIRAGANA LETTER NU;Lo;0;L;;;;;N;;;;;
+306D;HIRAGANA LETTER NE;Lo;0;L;;;;;N;;;;;
+306E;HIRAGANA LETTER NO;Lo;0;L;;;;;N;;;;;
+306F;HIRAGANA LETTER HA;Lo;0;L;;;;;N;;;;;
+3070;HIRAGANA LETTER BA;Lo;0;L;306F 3099;;;;N;;;;;
+3071;HIRAGANA LETTER PA;Lo;0;L;306F 309A;;;;N;;;;;
+3072;HIRAGANA LETTER HI;Lo;0;L;;;;;N;;;;;
+3073;HIRAGANA LETTER BI;Lo;0;L;3072 3099;;;;N;;;;;
+3074;HIRAGANA LETTER PI;Lo;0;L;3072 309A;;;;N;;;;;
+3075;HIRAGANA LETTER HU;Lo;0;L;;;;;N;;;;;
+3076;HIRAGANA LETTER BU;Lo;0;L;3075 3099;;;;N;;;;;
+3077;HIRAGANA LETTER PU;Lo;0;L;3075 309A;;;;N;;;;;
+3078;HIRAGANA LETTER HE;Lo;0;L;;;;;N;;;;;
+3079;HIRAGANA LETTER BE;Lo;0;L;3078 3099;;;;N;;;;;
+307A;HIRAGANA LETTER PE;Lo;0;L;3078 309A;;;;N;;;;;
+307B;HIRAGANA LETTER HO;Lo;0;L;;;;;N;;;;;
+307C;HIRAGANA LETTER BO;Lo;0;L;307B 3099;;;;N;;;;;
+307D;HIRAGANA LETTER PO;Lo;0;L;307B 309A;;;;N;;;;;
+307E;HIRAGANA LETTER MA;Lo;0;L;;;;;N;;;;;
+307F;HIRAGANA LETTER MI;Lo;0;L;;;;;N;;;;;
+3080;HIRAGANA LETTER MU;Lo;0;L;;;;;N;;;;;
+3081;HIRAGANA LETTER ME;Lo;0;L;;;;;N;;;;;
+3082;HIRAGANA LETTER MO;Lo;0;L;;;;;N;;;;;
+3083;HIRAGANA LETTER SMALL YA;Lo;0;L;;;;;N;;;;;
+3084;HIRAGANA LETTER YA;Lo;0;L;;;;;N;;;;;
+3085;HIRAGANA LETTER SMALL YU;Lo;0;L;;;;;N;;;;;
+3086;HIRAGANA LETTER YU;Lo;0;L;;;;;N;;;;;
+3087;HIRAGANA LETTER SMALL YO;Lo;0;L;;;;;N;;;;;
+3088;HIRAGANA LETTER YO;Lo;0;L;;;;;N;;;;;
+3089;HIRAGANA LETTER RA;Lo;0;L;;;;;N;;;;;
+308A;HIRAGANA LETTER RI;Lo;0;L;;;;;N;;;;;
+308B;HIRAGANA LETTER RU;Lo;0;L;;;;;N;;;;;
+308C;HIRAGANA LETTER RE;Lo;0;L;;;;;N;;;;;
+308D;HIRAGANA LETTER RO;Lo;0;L;;;;;N;;;;;
+308E;HIRAGANA LETTER SMALL WA;Lo;0;L;;;;;N;;;;;
+308F;HIRAGANA LETTER WA;Lo;0;L;;;;;N;;;;;
+3090;HIRAGANA LETTER WI;Lo;0;L;;;;;N;;;;;
+3091;HIRAGANA LETTER WE;Lo;0;L;;;;;N;;;;;
+3092;HIRAGANA LETTER WO;Lo;0;L;;;;;N;;;;;
+3093;HIRAGANA LETTER N;Lo;0;L;;;;;N;;;;;
+3094;HIRAGANA LETTER VU;Lo;0;L;3046 3099;;;;N;;;;;
+3095;HIRAGANA LETTER SMALL KA;Lo;0;L;;;;;N;;;;;
+3096;HIRAGANA LETTER SMALL KE;Lo;0;L;;;;;N;;;;;
+3099;COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK;Mn;8;NSM;;;;;N;NON-SPACING KATAKANA-HIRAGANA VOICED SOUND MARK;;;;
+309A;COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK;Mn;8;NSM;;;;;N;NON-SPACING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK;;;;
+309B;KATAKANA-HIRAGANA VOICED SOUND MARK;Sk;0;ON;<compat> 0020 3099;;;;N;;;;;
+309C;KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK;Sk;0;ON;<compat> 0020 309A;;;;N;;;;;
+309D;HIRAGANA ITERATION MARK;Lm;0;L;;;;;N;;;;;
+309E;HIRAGANA VOICED ITERATION MARK;Lm;0;L;309D 3099;;;;N;;;;;
+309F;HIRAGANA DIGRAPH YORI;Lo;0;L;<vertical> 3088 308A;;;;N;;;;;
+30A0;KATAKANA-HIRAGANA DOUBLE HYPHEN;Pd;0;ON;;;;;N;;;;;
+30A1;KATAKANA LETTER SMALL A;Lo;0;L;;;;;N;;;;;
+30A2;KATAKANA LETTER A;Lo;0;L;;;;;N;;;;;
+30A3;KATAKANA LETTER SMALL I;Lo;0;L;;;;;N;;;;;
+30A4;KATAKANA LETTER I;Lo;0;L;;;;;N;;;;;
+30A5;KATAKANA LETTER SMALL U;Lo;0;L;;;;;N;;;;;
+30A6;KATAKANA LETTER U;Lo;0;L;;;;;N;;;;;
+30A7;KATAKANA LETTER SMALL E;Lo;0;L;;;;;N;;;;;
+30A8;KATAKANA LETTER E;Lo;0;L;;;;;N;;;;;
+30A9;KATAKANA LETTER SMALL O;Lo;0;L;;;;;N;;;;;
+30AA;KATAKANA LETTER O;Lo;0;L;;;;;N;;;;;
+30AB;KATAKANA LETTER KA;Lo;0;L;;;;;N;;;;;
+30AC;KATAKANA LETTER GA;Lo;0;L;30AB 3099;;;;N;;;;;
+30AD;KATAKANA LETTER KI;Lo;0;L;;;;;N;;;;;
+30AE;KATAKANA LETTER GI;Lo;0;L;30AD 3099;;;;N;;;;;
+30AF;KATAKANA LETTER KU;Lo;0;L;;;;;N;;;;;
+30B0;KATAKANA LETTER GU;Lo;0;L;30AF 3099;;;;N;;;;;
+30B1;KATAKANA LETTER KE;Lo;0;L;;;;;N;;;;;
+30B2;KATAKANA LETTER GE;Lo;0;L;30B1 3099;;;;N;;;;;
+30B3;KATAKANA LETTER KO;Lo;0;L;;;;;N;;;;;
+30B4;KATAKANA LETTER GO;Lo;0;L;30B3 3099;;;;N;;;;;
+30B5;KATAKANA LETTER SA;Lo;0;L;;;;;N;;;;;
+30B6;KATAKANA LETTER ZA;Lo;0;L;30B5 3099;;;;N;;;;;
+30B7;KATAKANA LETTER SI;Lo;0;L;;;;;N;;;;;
+30B8;KATAKANA LETTER ZI;Lo;0;L;30B7 3099;;;;N;;;;;
+30B9;KATAKANA LETTER SU;Lo;0;L;;;;;N;;;;;
+30BA;KATAKANA LETTER ZU;Lo;0;L;30B9 3099;;;;N;;;;;
+30BB;KATAKANA LETTER SE;Lo;0;L;;;;;N;;;;;
+30BC;KATAKANA LETTER ZE;Lo;0;L;30BB 3099;;;;N;;;;;
+30BD;KATAKANA LETTER SO;Lo;0;L;;;;;N;;;;;
+30BE;KATAKANA LETTER ZO;Lo;0;L;30BD 3099;;;;N;;;;;
+30BF;KATAKANA LETTER TA;Lo;0;L;;;;;N;;;;;
+30C0;KATAKANA LETTER DA;Lo;0;L;30BF 3099;;;;N;;;;;
+30C1;KATAKANA LETTER TI;Lo;0;L;;;;;N;;;;;
+30C2;KATAKANA LETTER DI;Lo;0;L;30C1 3099;;;;N;;;;;
+30C3;KATAKANA LETTER SMALL TU;Lo;0;L;;;;;N;;;;;
+30C4;KATAKANA LETTER TU;Lo;0;L;;;;;N;;;;;
+30C5;KATAKANA LETTER DU;Lo;0;L;30C4 3099;;;;N;;;;;
+30C6;KATAKANA LETTER TE;Lo;0;L;;;;;N;;;;;
+30C7;KATAKANA LETTER DE;Lo;0;L;30C6 3099;;;;N;;;;;
+30C8;KATAKANA LETTER TO;Lo;0;L;;;;;N;;;;;
+30C9;KATAKANA LETTER DO;Lo;0;L;30C8 3099;;;;N;;;;;
+30CA;KATAKANA LETTER NA;Lo;0;L;;;;;N;;;;;
+30CB;KATAKANA LETTER NI;Lo;0;L;;;;;N;;;;;
+30CC;KATAKANA LETTER NU;Lo;0;L;;;;;N;;;;;
+30CD;KATAKANA LETTER NE;Lo;0;L;;;;;N;;;;;
+30CE;KATAKANA LETTER NO;Lo;0;L;;;;;N;;;;;
+30CF;KATAKANA LETTER HA;Lo;0;L;;;;;N;;;;;
+30D0;KATAKANA LETTER BA;Lo;0;L;30CF 3099;;;;N;;;;;
+30D1;KATAKANA LETTER PA;Lo;0;L;30CF 309A;;;;N;;;;;
+30D2;KATAKANA LETTER HI;Lo;0;L;;;;;N;;;;;
+30D3;KATAKANA LETTER BI;Lo;0;L;30D2 3099;;;;N;;;;;
+30D4;KATAKANA LETTER PI;Lo;0;L;30D2 309A;;;;N;;;;;
+30D5;KATAKANA LETTER HU;Lo;0;L;;;;;N;;;;;
+30D6;KATAKANA LETTER BU;Lo;0;L;30D5 3099;;;;N;;;;;
+30D7;KATAKANA LETTER PU;Lo;0;L;30D5 309A;;;;N;;;;;
+30D8;KATAKANA LETTER HE;Lo;0;L;;;;;N;;;;;
+30D9;KATAKANA LETTER BE;Lo;0;L;30D8 3099;;;;N;;;;;
+30DA;KATAKANA LETTER PE;Lo;0;L;30D8 309A;;;;N;;;;;
+30DB;KATAKANA LETTER HO;Lo;0;L;;;;;N;;;;;
+30DC;KATAKANA LETTER BO;Lo;0;L;30DB 3099;;;;N;;;;;
+30DD;KATAKANA LETTER PO;Lo;0;L;30DB 309A;;;;N;;;;;
+30DE;KATAKANA LETTER MA;Lo;0;L;;;;;N;;;;;
+30DF;KATAKANA LETTER MI;Lo;0;L;;;;;N;;;;;
+30E0;KATAKANA LETTER MU;Lo;0;L;;;;;N;;;;;
+30E1;KATAKANA LETTER ME;Lo;0;L;;;;;N;;;;;
+30E2;KATAKANA LETTER MO;Lo;0;L;;;;;N;;;;;
+30E3;KATAKANA LETTER SMALL YA;Lo;0;L;;;;;N;;;;;
+30E4;KATAKANA LETTER YA;Lo;0;L;;;;;N;;;;;
+30E5;KATAKANA LETTER SMALL YU;Lo;0;L;;;;;N;;;;;
+30E6;KATAKANA LETTER YU;Lo;0;L;;;;;N;;;;;
+30E7;KATAKANA LETTER SMALL YO;Lo;0;L;;;;;N;;;;;
+30E8;KATAKANA LETTER YO;Lo;0;L;;;;;N;;;;;
+30E9;KATAKANA LETTER RA;Lo;0;L;;;;;N;;;;;
+30EA;KATAKANA LETTER RI;Lo;0;L;;;;;N;;;;;
+30EB;KATAKANA LETTER RU;Lo;0;L;;;;;N;;;;;
+30EC;KATAKANA LETTER RE;Lo;0;L;;;;;N;;;;;
+30ED;KATAKANA LETTER RO;Lo;0;L;;;;;N;;;;;
+30EE;KATAKANA LETTER SMALL WA;Lo;0;L;;;;;N;;;;;
+30EF;KATAKANA LETTER WA;Lo;0;L;;;;;N;;;;;
+30F0;KATAKANA LETTER WI;Lo;0;L;;;;;N;;;;;
+30F1;KATAKANA LETTER WE;Lo;0;L;;;;;N;;;;;
+30F2;KATAKANA LETTER WO;Lo;0;L;;;;;N;;;;;
+30F3;KATAKANA LETTER N;Lo;0;L;;;;;N;;;;;
+30F4;KATAKANA LETTER VU;Lo;0;L;30A6 3099;;;;N;;;;;
+30F5;KATAKANA LETTER SMALL KA;Lo;0;L;;;;;N;;;;;
+30F6;KATAKANA LETTER SMALL KE;Lo;0;L;;;;;N;;;;;
+30F7;KATAKANA LETTER VA;Lo;0;L;30EF 3099;;;;N;;;;;
+30F8;KATAKANA LETTER VI;Lo;0;L;30F0 3099;;;;N;;;;;
+30F9;KATAKANA LETTER VE;Lo;0;L;30F1 3099;;;;N;;;;;
+30FA;KATAKANA LETTER VO;Lo;0;L;30F2 3099;;;;N;;;;;
+30FB;KATAKANA MIDDLE DOT;Pc;0;ON;;;;;N;;;;;
+30FC;KATAKANA-HIRAGANA PROLONGED SOUND MARK;Lm;0;L;;;;;N;;;;;
+30FD;KATAKANA ITERATION MARK;Lm;0;L;;;;;N;;;;;
+30FE;KATAKANA VOICED ITERATION MARK;Lm;0;L;30FD 3099;;;;N;;;;;
+30FF;KATAKANA DIGRAPH KOTO;Lo;0;L;<vertical> 30B3 30C8;;;;N;;;;;
+3105;BOPOMOFO LETTER B;Lo;0;L;;;;;N;;;;;
+3106;BOPOMOFO LETTER P;Lo;0;L;;;;;N;;;;;
+3107;BOPOMOFO LETTER M;Lo;0;L;;;;;N;;;;;
+3108;BOPOMOFO LETTER F;Lo;0;L;;;;;N;;;;;
+3109;BOPOMOFO LETTER D;Lo;0;L;;;;;N;;;;;
+310A;BOPOMOFO LETTER T;Lo;0;L;;;;;N;;;;;
+310B;BOPOMOFO LETTER N;Lo;0;L;;;;;N;;;;;
+310C;BOPOMOFO LETTER L;Lo;0;L;;;;;N;;;;;
+310D;BOPOMOFO LETTER G;Lo;0;L;;;;;N;;;;;
+310E;BOPOMOFO LETTER K;Lo;0;L;;;;;N;;;;;
+310F;BOPOMOFO LETTER H;Lo;0;L;;;;;N;;;;;
+3110;BOPOMOFO LETTER J;Lo;0;L;;;;;N;;;;;
+3111;BOPOMOFO LETTER Q;Lo;0;L;;;;;N;;;;;
+3112;BOPOMOFO LETTER X;Lo;0;L;;;;;N;;;;;
+3113;BOPOMOFO LETTER ZH;Lo;0;L;;;;;N;;;;;
+3114;BOPOMOFO LETTER CH;Lo;0;L;;;;;N;;;;;
+3115;BOPOMOFO LETTER SH;Lo;0;L;;;;;N;;;;;
+3116;BOPOMOFO LETTER R;Lo;0;L;;;;;N;;;;;
+3117;BOPOMOFO LETTER Z;Lo;0;L;;;;;N;;;;;
+3118;BOPOMOFO LETTER C;Lo;0;L;;;;;N;;;;;
+3119;BOPOMOFO LETTER S;Lo;0;L;;;;;N;;;;;
+311A;BOPOMOFO LETTER A;Lo;0;L;;;;;N;;;;;
+311B;BOPOMOFO LETTER O;Lo;0;L;;;;;N;;;;;
+311C;BOPOMOFO LETTER E;Lo;0;L;;;;;N;;;;;
+311D;BOPOMOFO LETTER EH;Lo;0;L;;;;;N;;;;;
+311E;BOPOMOFO LETTER AI;Lo;0;L;;;;;N;;;;;
+311F;BOPOMOFO LETTER EI;Lo;0;L;;;;;N;;;;;
+3120;BOPOMOFO LETTER AU;Lo;0;L;;;;;N;;;;;
+3121;BOPOMOFO LETTER OU;Lo;0;L;;;;;N;;;;;
+3122;BOPOMOFO LETTER AN;Lo;0;L;;;;;N;;;;;
+3123;BOPOMOFO LETTER EN;Lo;0;L;;;;;N;;;;;
+3124;BOPOMOFO LETTER ANG;Lo;0;L;;;;;N;;;;;
+3125;BOPOMOFO LETTER ENG;Lo;0;L;;;;;N;;;;;
+3126;BOPOMOFO LETTER ER;Lo;0;L;;;;;N;;;;;
+3127;BOPOMOFO LETTER I;Lo;0;L;;;;;N;;;;;
+3128;BOPOMOFO LETTER U;Lo;0;L;;;;;N;;;;;
+3129;BOPOMOFO LETTER IU;Lo;0;L;;;;;N;;;;;
+312A;BOPOMOFO LETTER V;Lo;0;L;;;;;N;;;;;
+312B;BOPOMOFO LETTER NG;Lo;0;L;;;;;N;;;;;
+312C;BOPOMOFO LETTER GN;Lo;0;L;;;;;N;;;;;
+3131;HANGUL LETTER KIYEOK;Lo;0;L;<compat> 1100;;;;N;HANGUL LETTER GIYEOG;;;;
+3132;HANGUL LETTER SSANGKIYEOK;Lo;0;L;<compat> 1101;;;;N;HANGUL LETTER SSANG GIYEOG;;;;
+3133;HANGUL LETTER KIYEOK-SIOS;Lo;0;L;<compat> 11AA;;;;N;HANGUL LETTER GIYEOG SIOS;;;;
+3134;HANGUL LETTER NIEUN;Lo;0;L;<compat> 1102;;;;N;;;;;
+3135;HANGUL LETTER NIEUN-CIEUC;Lo;0;L;<compat> 11AC;;;;N;HANGUL LETTER NIEUN JIEUJ;;;;
+3136;HANGUL LETTER NIEUN-HIEUH;Lo;0;L;<compat> 11AD;;;;N;HANGUL LETTER NIEUN HIEUH;;;;
+3137;HANGUL LETTER TIKEUT;Lo;0;L;<compat> 1103;;;;N;HANGUL LETTER DIGEUD;;;;
+3138;HANGUL LETTER SSANGTIKEUT;Lo;0;L;<compat> 1104;;;;N;HANGUL LETTER SSANG DIGEUD;;;;
+3139;HANGUL LETTER RIEUL;Lo;0;L;<compat> 1105;;;;N;HANGUL LETTER LIEUL;;;;
+313A;HANGUL LETTER RIEUL-KIYEOK;Lo;0;L;<compat> 11B0;;;;N;HANGUL LETTER LIEUL GIYEOG;;;;
+313B;HANGUL LETTER RIEUL-MIEUM;Lo;0;L;<compat> 11B1;;;;N;HANGUL LETTER LIEUL MIEUM;;;;
+313C;HANGUL LETTER RIEUL-PIEUP;Lo;0;L;<compat> 11B2;;;;N;HANGUL LETTER LIEUL BIEUB;;;;
+313D;HANGUL LETTER RIEUL-SIOS;Lo;0;L;<compat> 11B3;;;;N;HANGUL LETTER LIEUL SIOS;;;;
+313E;HANGUL LETTER RIEUL-THIEUTH;Lo;0;L;<compat> 11B4;;;;N;HANGUL LETTER LIEUL TIEUT;;;;
+313F;HANGUL LETTER RIEUL-PHIEUPH;Lo;0;L;<compat> 11B5;;;;N;HANGUL LETTER LIEUL PIEUP;;;;
+3140;HANGUL LETTER RIEUL-HIEUH;Lo;0;L;<compat> 111A;;;;N;HANGUL LETTER LIEUL HIEUH;;;;
+3141;HANGUL LETTER MIEUM;Lo;0;L;<compat> 1106;;;;N;;;;;
+3142;HANGUL LETTER PIEUP;Lo;0;L;<compat> 1107;;;;N;HANGUL LETTER BIEUB;;;;
+3143;HANGUL LETTER SSANGPIEUP;Lo;0;L;<compat> 1108;;;;N;HANGUL LETTER SSANG BIEUB;;;;
+3144;HANGUL LETTER PIEUP-SIOS;Lo;0;L;<compat> 1121;;;;N;HANGUL LETTER BIEUB SIOS;;;;
+3145;HANGUL LETTER SIOS;Lo;0;L;<compat> 1109;;;;N;;;;;
+3146;HANGUL LETTER SSANGSIOS;Lo;0;L;<compat> 110A;;;;N;HANGUL LETTER SSANG SIOS;;;;
+3147;HANGUL LETTER IEUNG;Lo;0;L;<compat> 110B;;;;N;;;;;
+3148;HANGUL LETTER CIEUC;Lo;0;L;<compat> 110C;;;;N;HANGUL LETTER JIEUJ;;;;
+3149;HANGUL LETTER SSANGCIEUC;Lo;0;L;<compat> 110D;;;;N;HANGUL LETTER SSANG JIEUJ;;;;
+314A;HANGUL LETTER CHIEUCH;Lo;0;L;<compat> 110E;;;;N;HANGUL LETTER CIEUC;;;;
+314B;HANGUL LETTER KHIEUKH;Lo;0;L;<compat> 110F;;;;N;HANGUL LETTER KIYEOK;;;;
+314C;HANGUL LETTER THIEUTH;Lo;0;L;<compat> 1110;;;;N;HANGUL LETTER TIEUT;;;;
+314D;HANGUL LETTER PHIEUPH;Lo;0;L;<compat> 1111;;;;N;HANGUL LETTER PIEUP;;;;
+314E;HANGUL LETTER HIEUH;Lo;0;L;<compat> 1112;;;;N;;;;;
+314F;HANGUL LETTER A;Lo;0;L;<compat> 1161;;;;N;;;;;
+3150;HANGUL LETTER AE;Lo;0;L;<compat> 1162;;;;N;;;;;
+3151;HANGUL LETTER YA;Lo;0;L;<compat> 1163;;;;N;;;;;
+3152;HANGUL LETTER YAE;Lo;0;L;<compat> 1164;;;;N;;;;;
+3153;HANGUL LETTER EO;Lo;0;L;<compat> 1165;;;;N;;;;;
+3154;HANGUL LETTER E;Lo;0;L;<compat> 1166;;;;N;;;;;
+3155;HANGUL LETTER YEO;Lo;0;L;<compat> 1167;;;;N;;;;;
+3156;HANGUL LETTER YE;Lo;0;L;<compat> 1168;;;;N;;;;;
+3157;HANGUL LETTER O;Lo;0;L;<compat> 1169;;;;N;;;;;
+3158;HANGUL LETTER WA;Lo;0;L;<compat> 116A;;;;N;;;;;
+3159;HANGUL LETTER WAE;Lo;0;L;<compat> 116B;;;;N;;;;;
+315A;HANGUL LETTER OE;Lo;0;L;<compat> 116C;;;;N;;;;;
+315B;HANGUL LETTER YO;Lo;0;L;<compat> 116D;;;;N;;;;;
+315C;HANGUL LETTER U;Lo;0;L;<compat> 116E;;;;N;;;;;
+315D;HANGUL LETTER WEO;Lo;0;L;<compat> 116F;;;;N;;;;;
+315E;HANGUL LETTER WE;Lo;0;L;<compat> 1170;;;;N;;;;;
+315F;HANGUL LETTER WI;Lo;0;L;<compat> 1171;;;;N;;;;;
+3160;HANGUL LETTER YU;Lo;0;L;<compat> 1172;;;;N;;;;;
+3161;HANGUL LETTER EU;Lo;0;L;<compat> 1173;;;;N;;;;;
+3162;HANGUL LETTER YI;Lo;0;L;<compat> 1174;;;;N;;;;;
+3163;HANGUL LETTER I;Lo;0;L;<compat> 1175;;;;N;;;;;
+3164;HANGUL FILLER;Lo;0;L;<compat> 1160;;;;N;HANGUL CAE OM;;;;
+3165;HANGUL LETTER SSANGNIEUN;Lo;0;L;<compat> 1114;;;;N;HANGUL LETTER SSANG NIEUN;;;;
+3166;HANGUL LETTER NIEUN-TIKEUT;Lo;0;L;<compat> 1115;;;;N;HANGUL LETTER NIEUN DIGEUD;;;;
+3167;HANGUL LETTER NIEUN-SIOS;Lo;0;L;<compat> 11C7;;;;N;HANGUL LETTER NIEUN SIOS;;;;
+3168;HANGUL LETTER NIEUN-PANSIOS;Lo;0;L;<compat> 11C8;;;;N;HANGUL LETTER NIEUN BAN CHI EUM;;;;
+3169;HANGUL LETTER RIEUL-KIYEOK-SIOS;Lo;0;L;<compat> 11CC;;;;N;HANGUL LETTER LIEUL GIYEOG SIOS;;;;
+316A;HANGUL LETTER RIEUL-TIKEUT;Lo;0;L;<compat> 11CE;;;;N;HANGUL LETTER LIEUL DIGEUD;;;;
+316B;HANGUL LETTER RIEUL-PIEUP-SIOS;Lo;0;L;<compat> 11D3;;;;N;HANGUL LETTER LIEUL BIEUB SIOS;;;;
+316C;HANGUL LETTER RIEUL-PANSIOS;Lo;0;L;<compat> 11D7;;;;N;HANGUL LETTER LIEUL BAN CHI EUM;;;;
+316D;HANGUL LETTER RIEUL-YEORINHIEUH;Lo;0;L;<compat> 11D9;;;;N;HANGUL LETTER LIEUL YEOLIN HIEUH;;;;
+316E;HANGUL LETTER MIEUM-PIEUP;Lo;0;L;<compat> 111C;;;;N;HANGUL LETTER MIEUM BIEUB;;;;
+316F;HANGUL LETTER MIEUM-SIOS;Lo;0;L;<compat> 11DD;;;;N;HANGUL LETTER MIEUM SIOS;;;;
+3170;HANGUL LETTER MIEUM-PANSIOS;Lo;0;L;<compat> 11DF;;;;N;HANGUL LETTER BIEUB BAN CHI EUM;;;;
+3171;HANGUL LETTER KAPYEOUNMIEUM;Lo;0;L;<compat> 111D;;;;N;HANGUL LETTER MIEUM SUN GYEONG EUM;;;;
+3172;HANGUL LETTER PIEUP-KIYEOK;Lo;0;L;<compat> 111E;;;;N;HANGUL LETTER BIEUB GIYEOG;;;;
+3173;HANGUL LETTER PIEUP-TIKEUT;Lo;0;L;<compat> 1120;;;;N;HANGUL LETTER BIEUB DIGEUD;;;;
+3174;HANGUL LETTER PIEUP-SIOS-KIYEOK;Lo;0;L;<compat> 1122;;;;N;HANGUL LETTER BIEUB SIOS GIYEOG;;;;
+3175;HANGUL LETTER PIEUP-SIOS-TIKEUT;Lo;0;L;<compat> 1123;;;;N;HANGUL LETTER BIEUB SIOS DIGEUD;;;;
+3176;HANGUL LETTER PIEUP-CIEUC;Lo;0;L;<compat> 1127;;;;N;HANGUL LETTER BIEUB JIEUJ;;;;
+3177;HANGUL LETTER PIEUP-THIEUTH;Lo;0;L;<compat> 1129;;;;N;HANGUL LETTER BIEUB TIEUT;;;;
+3178;HANGUL LETTER KAPYEOUNPIEUP;Lo;0;L;<compat> 112B;;;;N;HANGUL LETTER BIEUB SUN GYEONG EUM;;;;
+3179;HANGUL LETTER KAPYEOUNSSANGPIEUP;Lo;0;L;<compat> 112C;;;;N;HANGUL LETTER SSANG BIEUB SUN GYEONG EUM;;;;
+317A;HANGUL LETTER SIOS-KIYEOK;Lo;0;L;<compat> 112D;;;;N;HANGUL LETTER SIOS GIYEOG;;;;
+317B;HANGUL LETTER SIOS-NIEUN;Lo;0;L;<compat> 112E;;;;N;HANGUL LETTER SIOS NIEUN;;;;
+317C;HANGUL LETTER SIOS-TIKEUT;Lo;0;L;<compat> 112F;;;;N;HANGUL LETTER SIOS DIGEUD;;;;
+317D;HANGUL LETTER SIOS-PIEUP;Lo;0;L;<compat> 1132;;;;N;HANGUL LETTER SIOS BIEUB;;;;
+317E;HANGUL LETTER SIOS-CIEUC;Lo;0;L;<compat> 1136;;;;N;HANGUL LETTER SIOS JIEUJ;;;;
+317F;HANGUL LETTER PANSIOS;Lo;0;L;<compat> 1140;;;;N;HANGUL LETTER BAN CHI EUM;;;;
+3180;HANGUL LETTER SSANGIEUNG;Lo;0;L;<compat> 1147;;;;N;HANGUL LETTER SSANG IEUNG;;;;
+3181;HANGUL LETTER YESIEUNG;Lo;0;L;<compat> 114C;;;;N;HANGUL LETTER NGIEUNG;;;;
+3182;HANGUL LETTER YESIEUNG-SIOS;Lo;0;L;<compat> 11F1;;;;N;HANGUL LETTER NGIEUNG SIOS;;;;
+3183;HANGUL LETTER YESIEUNG-PANSIOS;Lo;0;L;<compat> 11F2;;;;N;HANGUL LETTER NGIEUNG BAN CHI EUM;;;;
+3184;HANGUL LETTER KAPYEOUNPHIEUPH;Lo;0;L;<compat> 1157;;;;N;HANGUL LETTER PIEUP SUN GYEONG EUM;;;;
+3185;HANGUL LETTER SSANGHIEUH;Lo;0;L;<compat> 1158;;;;N;HANGUL LETTER SSANG HIEUH;;;;
+3186;HANGUL LETTER YEORINHIEUH;Lo;0;L;<compat> 1159;;;;N;HANGUL LETTER YEOLIN HIEUH;;;;
+3187;HANGUL LETTER YO-YA;Lo;0;L;<compat> 1184;;;;N;HANGUL LETTER YOYA;;;;
+3188;HANGUL LETTER YO-YAE;Lo;0;L;<compat> 1185;;;;N;HANGUL LETTER YOYAE;;;;
+3189;HANGUL LETTER YO-I;Lo;0;L;<compat> 1188;;;;N;HANGUL LETTER YOI;;;;
+318A;HANGUL LETTER YU-YEO;Lo;0;L;<compat> 1191;;;;N;HANGUL LETTER YUYEO;;;;
+318B;HANGUL LETTER YU-YE;Lo;0;L;<compat> 1192;;;;N;HANGUL LETTER YUYE;;;;
+318C;HANGUL LETTER YU-I;Lo;0;L;<compat> 1194;;;;N;HANGUL LETTER YUI;;;;
+318D;HANGUL LETTER ARAEA;Lo;0;L;<compat> 119E;;;;N;HANGUL LETTER ALAE A;;;;
+318E;HANGUL LETTER ARAEAE;Lo;0;L;<compat> 11A1;;;;N;HANGUL LETTER ALAE AE;;;;
+3190;IDEOGRAPHIC ANNOTATION LINKING MARK;So;0;L;;;;;N;KANBUN TATETEN;Kanbun Tateten;;;
+3191;IDEOGRAPHIC ANNOTATION REVERSE MARK;So;0;L;;;;;N;KAERITEN RE;Kaeriten;;;
+3192;IDEOGRAPHIC ANNOTATION ONE MARK;No;0;L;<super> 4E00;;;1;N;KAERITEN ITI;Kaeriten;;;
+3193;IDEOGRAPHIC ANNOTATION TWO MARK;No;0;L;<super> 4E8C;;;2;N;KAERITEN NI;Kaeriten;;;
+3194;IDEOGRAPHIC ANNOTATION THREE MARK;No;0;L;<super> 4E09;;;3;N;KAERITEN SAN;Kaeriten;;;
+3195;IDEOGRAPHIC ANNOTATION FOUR MARK;No;0;L;<super> 56DB;;;4;N;KAERITEN SI;Kaeriten;;;
+3196;IDEOGRAPHIC ANNOTATION TOP MARK;So;0;L;<super> 4E0A;;;;N;KAERITEN ZYOU;Kaeriten;;;
+3197;IDEOGRAPHIC ANNOTATION MIDDLE MARK;So;0;L;<super> 4E2D;;;;N;KAERITEN TYUU;Kaeriten;;;
+3198;IDEOGRAPHIC ANNOTATION BOTTOM MARK;So;0;L;<super> 4E0B;;;;N;KAERITEN GE;Kaeriten;;;
+3199;IDEOGRAPHIC ANNOTATION FIRST MARK;So;0;L;<super> 7532;;;;N;KAERITEN KOU;Kaeriten;;;
+319A;IDEOGRAPHIC ANNOTATION SECOND MARK;So;0;L;<super> 4E59;;;;N;KAERITEN OTU;Kaeriten;;;
+319B;IDEOGRAPHIC ANNOTATION THIRD MARK;So;0;L;<super> 4E19;;;;N;KAERITEN HEI;Kaeriten;;;
+319C;IDEOGRAPHIC ANNOTATION FOURTH MARK;So;0;L;<super> 4E01;;;;N;KAERITEN TEI;Kaeriten;;;
+319D;IDEOGRAPHIC ANNOTATION HEAVEN MARK;So;0;L;<super> 5929;;;;N;KAERITEN TEN;Kaeriten;;;
+319E;IDEOGRAPHIC ANNOTATION EARTH MARK;So;0;L;<super> 5730;;;;N;KAERITEN TI;Kaeriten;;;
+319F;IDEOGRAPHIC ANNOTATION MAN MARK;So;0;L;<super> 4EBA;;;;N;KAERITEN ZIN;Kaeriten;;;
+31A0;BOPOMOFO LETTER BU;Lo;0;L;;;;;N;;;;;
+31A1;BOPOMOFO LETTER ZI;Lo;0;L;;;;;N;;;;;
+31A2;BOPOMOFO LETTER JI;Lo;0;L;;;;;N;;;;;
+31A3;BOPOMOFO LETTER GU;Lo;0;L;;;;;N;;;;;
+31A4;BOPOMOFO LETTER EE;Lo;0;L;;;;;N;;;;;
+31A5;BOPOMOFO LETTER ENN;Lo;0;L;;;;;N;;;;;
+31A6;BOPOMOFO LETTER OO;Lo;0;L;;;;;N;;;;;
+31A7;BOPOMOFO LETTER ONN;Lo;0;L;;;;;N;;;;;
+31A8;BOPOMOFO LETTER IR;Lo;0;L;;;;;N;;;;;
+31A9;BOPOMOFO LETTER ANN;Lo;0;L;;;;;N;;;;;
+31AA;BOPOMOFO LETTER INN;Lo;0;L;;;;;N;;;;;
+31AB;BOPOMOFO LETTER UNN;Lo;0;L;;;;;N;;;;;
+31AC;BOPOMOFO LETTER IM;Lo;0;L;;;;;N;;;;;
+31AD;BOPOMOFO LETTER NGG;Lo;0;L;;;;;N;;;;;
+31AE;BOPOMOFO LETTER AINN;Lo;0;L;;;;;N;;;;;
+31AF;BOPOMOFO LETTER AUNN;Lo;0;L;;;;;N;;;;;
+31B0;BOPOMOFO LETTER AM;Lo;0;L;;;;;N;;;;;
+31B1;BOPOMOFO LETTER OM;Lo;0;L;;;;;N;;;;;
+31B2;BOPOMOFO LETTER ONG;Lo;0;L;;;;;N;;;;;
+31B3;BOPOMOFO LETTER INNN;Lo;0;L;;;;;N;;;;;
+31B4;BOPOMOFO FINAL LETTER P;Lo;0;L;;;;;N;;;;;
+31B5;BOPOMOFO FINAL LETTER T;Lo;0;L;;;;;N;;;;;
+31B6;BOPOMOFO FINAL LETTER K;Lo;0;L;;;;;N;;;;;
+31B7;BOPOMOFO FINAL LETTER H;Lo;0;L;;;;;N;;;;;
+31F0;KATAKANA LETTER SMALL KU;Lo;0;L;;;;;N;;;;;
+31F1;KATAKANA LETTER SMALL SI;Lo;0;L;;;;;N;;;;;
+31F2;KATAKANA LETTER SMALL SU;Lo;0;L;;;;;N;;;;;
+31F3;KATAKANA LETTER SMALL TO;Lo;0;L;;;;;N;;;;;
+31F4;KATAKANA LETTER SMALL NU;Lo;0;L;;;;;N;;;;;
+31F5;KATAKANA LETTER SMALL HA;Lo;0;L;;;;;N;;;;;
+31F6;KATAKANA LETTER SMALL HI;Lo;0;L;;;;;N;;;;;
+31F7;KATAKANA LETTER SMALL HU;Lo;0;L;;;;;N;;;;;
+31F8;KATAKANA LETTER SMALL HE;Lo;0;L;;;;;N;;;;;
+31F9;KATAKANA LETTER SMALL HO;Lo;0;L;;;;;N;;;;;
+31FA;KATAKANA LETTER SMALL MU;Lo;0;L;;;;;N;;;;;
+31FB;KATAKANA LETTER SMALL RA;Lo;0;L;;;;;N;;;;;
+31FC;KATAKANA LETTER SMALL RI;Lo;0;L;;;;;N;;;;;
+31FD;KATAKANA LETTER SMALL RU;Lo;0;L;;;;;N;;;;;
+31FE;KATAKANA LETTER SMALL RE;Lo;0;L;;;;;N;;;;;
+31FF;KATAKANA LETTER SMALL RO;Lo;0;L;;;;;N;;;;;
+3200;PARENTHESIZED HANGUL KIYEOK;So;0;L;<compat> 0028 1100 0029;;;;N;PARENTHESIZED HANGUL GIYEOG;;;;
+3201;PARENTHESIZED HANGUL NIEUN;So;0;L;<compat> 0028 1102 0029;;;;N;;;;;
+3202;PARENTHESIZED HANGUL TIKEUT;So;0;L;<compat> 0028 1103 0029;;;;N;PARENTHESIZED HANGUL DIGEUD;;;;
+3203;PARENTHESIZED HANGUL RIEUL;So;0;L;<compat> 0028 1105 0029;;;;N;PARENTHESIZED HANGUL LIEUL;;;;
+3204;PARENTHESIZED HANGUL MIEUM;So;0;L;<compat> 0028 1106 0029;;;;N;;;;;
+3205;PARENTHESIZED HANGUL PIEUP;So;0;L;<compat> 0028 1107 0029;;;;N;PARENTHESIZED HANGUL BIEUB;;;;
+3206;PARENTHESIZED HANGUL SIOS;So;0;L;<compat> 0028 1109 0029;;;;N;;;;;
+3207;PARENTHESIZED HANGUL IEUNG;So;0;L;<compat> 0028 110B 0029;;;;N;;;;;
+3208;PARENTHESIZED HANGUL CIEUC;So;0;L;<compat> 0028 110C 0029;;;;N;PARENTHESIZED HANGUL JIEUJ;;;;
+3209;PARENTHESIZED HANGUL CHIEUCH;So;0;L;<compat> 0028 110E 0029;;;;N;PARENTHESIZED HANGUL CIEUC;;;;
+320A;PARENTHESIZED HANGUL KHIEUKH;So;0;L;<compat> 0028 110F 0029;;;;N;PARENTHESIZED HANGUL KIYEOK;;;;
+320B;PARENTHESIZED HANGUL THIEUTH;So;0;L;<compat> 0028 1110 0029;;;;N;PARENTHESIZED HANGUL TIEUT;;;;
+320C;PARENTHESIZED HANGUL PHIEUPH;So;0;L;<compat> 0028 1111 0029;;;;N;PARENTHESIZED HANGUL PIEUP;;;;
+320D;PARENTHESIZED HANGUL HIEUH;So;0;L;<compat> 0028 1112 0029;;;;N;;;;;
+320E;PARENTHESIZED HANGUL KIYEOK A;So;0;L;<compat> 0028 1100 1161 0029;;;;N;PARENTHESIZED HANGUL GA;;;;
+320F;PARENTHESIZED HANGUL NIEUN A;So;0;L;<compat> 0028 1102 1161 0029;;;;N;PARENTHESIZED HANGUL NA;;;;
+3210;PARENTHESIZED HANGUL TIKEUT A;So;0;L;<compat> 0028 1103 1161 0029;;;;N;PARENTHESIZED HANGUL DA;;;;
+3211;PARENTHESIZED HANGUL RIEUL A;So;0;L;<compat> 0028 1105 1161 0029;;;;N;PARENTHESIZED HANGUL LA;;;;
+3212;PARENTHESIZED HANGUL MIEUM A;So;0;L;<compat> 0028 1106 1161 0029;;;;N;PARENTHESIZED HANGUL MA;;;;
+3213;PARENTHESIZED HANGUL PIEUP A;So;0;L;<compat> 0028 1107 1161 0029;;;;N;PARENTHESIZED HANGUL BA;;;;
+3214;PARENTHESIZED HANGUL SIOS A;So;0;L;<compat> 0028 1109 1161 0029;;;;N;PARENTHESIZED HANGUL SA;;;;
+3215;PARENTHESIZED HANGUL IEUNG A;So;0;L;<compat> 0028 110B 1161 0029;;;;N;PARENTHESIZED HANGUL A;;;;
+3216;PARENTHESIZED HANGUL CIEUC A;So;0;L;<compat> 0028 110C 1161 0029;;;;N;PARENTHESIZED HANGUL JA;;;;
+3217;PARENTHESIZED HANGUL CHIEUCH A;So;0;L;<compat> 0028 110E 1161 0029;;;;N;PARENTHESIZED HANGUL CA;;;;
+3218;PARENTHESIZED HANGUL KHIEUKH A;So;0;L;<compat> 0028 110F 1161 0029;;;;N;PARENTHESIZED HANGUL KA;;;;
+3219;PARENTHESIZED HANGUL THIEUTH A;So;0;L;<compat> 0028 1110 1161 0029;;;;N;PARENTHESIZED HANGUL TA;;;;
+321A;PARENTHESIZED HANGUL PHIEUPH A;So;0;L;<compat> 0028 1111 1161 0029;;;;N;PARENTHESIZED HANGUL PA;;;;
+321B;PARENTHESIZED HANGUL HIEUH A;So;0;L;<compat> 0028 1112 1161 0029;;;;N;PARENTHESIZED HANGUL HA;;;;
+321C;PARENTHESIZED HANGUL CIEUC U;So;0;L;<compat> 0028 110C 116E 0029;;;;N;PARENTHESIZED HANGUL JU;;;;
+321D;PARENTHESIZED KOREAN CHARACTER OJEON;So;0;ON;<compat> 0028 110B 1169 110C 1165 11AB 0029;;;;N;;;;;
+321E;PARENTHESIZED KOREAN CHARACTER O HU;So;0;ON;<compat> 0028 110B 1169 1112 116E 0029;;;;N;;;;;
+3220;PARENTHESIZED IDEOGRAPH ONE;No;0;L;<compat> 0028 4E00 0029;;;1;N;;;;;
+3221;PARENTHESIZED IDEOGRAPH TWO;No;0;L;<compat> 0028 4E8C 0029;;;2;N;;;;;
+3222;PARENTHESIZED IDEOGRAPH THREE;No;0;L;<compat> 0028 4E09 0029;;;3;N;;;;;
+3223;PARENTHESIZED IDEOGRAPH FOUR;No;0;L;<compat> 0028 56DB 0029;;;4;N;;;;;
+3224;PARENTHESIZED IDEOGRAPH FIVE;No;0;L;<compat> 0028 4E94 0029;;;5;N;;;;;
+3225;PARENTHESIZED IDEOGRAPH SIX;No;0;L;<compat> 0028 516D 0029;;;6;N;;;;;
+3226;PARENTHESIZED IDEOGRAPH SEVEN;No;0;L;<compat> 0028 4E03 0029;;;7;N;;;;;
+3227;PARENTHESIZED IDEOGRAPH EIGHT;No;0;L;<compat> 0028 516B 0029;;;8;N;;;;;
+3228;PARENTHESIZED IDEOGRAPH NINE;No;0;L;<compat> 0028 4E5D 0029;;;9;N;;;;;
+3229;PARENTHESIZED IDEOGRAPH TEN;No;0;L;<compat> 0028 5341 0029;;;10;N;;;;;
+322A;PARENTHESIZED IDEOGRAPH MOON;So;0;L;<compat> 0028 6708 0029;;;;N;;;;;
+322B;PARENTHESIZED IDEOGRAPH FIRE;So;0;L;<compat> 0028 706B 0029;;;;N;;;;;
+322C;PARENTHESIZED IDEOGRAPH WATER;So;0;L;<compat> 0028 6C34 0029;;;;N;;;;;
+322D;PARENTHESIZED IDEOGRAPH WOOD;So;0;L;<compat> 0028 6728 0029;;;;N;;;;;
+322E;PARENTHESIZED IDEOGRAPH METAL;So;0;L;<compat> 0028 91D1 0029;;;;N;;;;;
+322F;PARENTHESIZED IDEOGRAPH EARTH;So;0;L;<compat> 0028 571F 0029;;;;N;;;;;
+3230;PARENTHESIZED IDEOGRAPH SUN;So;0;L;<compat> 0028 65E5 0029;;;;N;;;;;
+3231;PARENTHESIZED IDEOGRAPH STOCK;So;0;L;<compat> 0028 682A 0029;;;;N;;;;;
+3232;PARENTHESIZED IDEOGRAPH HAVE;So;0;L;<compat> 0028 6709 0029;;;;N;;;;;
+3233;PARENTHESIZED IDEOGRAPH SOCIETY;So;0;L;<compat> 0028 793E 0029;;;;N;;;;;
+3234;PARENTHESIZED IDEOGRAPH NAME;So;0;L;<compat> 0028 540D 0029;;;;N;;;;;
+3235;PARENTHESIZED IDEOGRAPH SPECIAL;So;0;L;<compat> 0028 7279 0029;;;;N;;;;;
+3236;PARENTHESIZED IDEOGRAPH FINANCIAL;So;0;L;<compat> 0028 8CA1 0029;;;;N;;;;;
+3237;PARENTHESIZED IDEOGRAPH CONGRATULATION;So;0;L;<compat> 0028 795D 0029;;;;N;;;;;
+3238;PARENTHESIZED IDEOGRAPH LABOR;So;0;L;<compat> 0028 52B4 0029;;;;N;;;;;
+3239;PARENTHESIZED IDEOGRAPH REPRESENT;So;0;L;<compat> 0028 4EE3 0029;;;;N;;;;;
+323A;PARENTHESIZED IDEOGRAPH CALL;So;0;L;<compat> 0028 547C 0029;;;;N;;;;;
+323B;PARENTHESIZED IDEOGRAPH STUDY;So;0;L;<compat> 0028 5B66 0029;;;;N;;;;;
+323C;PARENTHESIZED IDEOGRAPH SUPERVISE;So;0;L;<compat> 0028 76E3 0029;;;;N;;;;;
+323D;PARENTHESIZED IDEOGRAPH ENTERPRISE;So;0;L;<compat> 0028 4F01 0029;;;;N;;;;;
+323E;PARENTHESIZED IDEOGRAPH RESOURCE;So;0;L;<compat> 0028 8CC7 0029;;;;N;;;;;
+323F;PARENTHESIZED IDEOGRAPH ALLIANCE;So;0;L;<compat> 0028 5354 0029;;;;N;;;;;
+3240;PARENTHESIZED IDEOGRAPH FESTIVAL;So;0;L;<compat> 0028 796D 0029;;;;N;;;;;
+3241;PARENTHESIZED IDEOGRAPH REST;So;0;L;<compat> 0028 4F11 0029;;;;N;;;;;
+3242;PARENTHESIZED IDEOGRAPH SELF;So;0;L;<compat> 0028 81EA 0029;;;;N;;;;;
+3243;PARENTHESIZED IDEOGRAPH REACH;So;0;L;<compat> 0028 81F3 0029;;;;N;;;;;
+3250;PARTNERSHIP SIGN;So;0;ON;<square> 0050 0054 0045;;;;N;;;;;
+3251;CIRCLED NUMBER TWENTY ONE;No;0;ON;<circle> 0032 0031;;;21;N;;;;;
+3252;CIRCLED NUMBER TWENTY TWO;No;0;ON;<circle> 0032 0032;;;22;N;;;;;
+3253;CIRCLED NUMBER TWENTY THREE;No;0;ON;<circle> 0032 0033;;;23;N;;;;;
+3254;CIRCLED NUMBER TWENTY FOUR;No;0;ON;<circle> 0032 0034;;;24;N;;;;;
+3255;CIRCLED NUMBER TWENTY FIVE;No;0;ON;<circle> 0032 0035;;;25;N;;;;;
+3256;CIRCLED NUMBER TWENTY SIX;No;0;ON;<circle> 0032 0036;;;26;N;;;;;
+3257;CIRCLED NUMBER TWENTY SEVEN;No;0;ON;<circle> 0032 0037;;;27;N;;;;;
+3258;CIRCLED NUMBER TWENTY EIGHT;No;0;ON;<circle> 0032 0038;;;28;N;;;;;
+3259;CIRCLED NUMBER TWENTY NINE;No;0;ON;<circle> 0032 0039;;;29;N;;;;;
+325A;CIRCLED NUMBER THIRTY;No;0;ON;<circle> 0033 0030;;;30;N;;;;;
+325B;CIRCLED NUMBER THIRTY ONE;No;0;ON;<circle> 0033 0031;;;31;N;;;;;
+325C;CIRCLED NUMBER THIRTY TWO;No;0;ON;<circle> 0033 0032;;;32;N;;;;;
+325D;CIRCLED NUMBER THIRTY THREE;No;0;ON;<circle> 0033 0033;;;33;N;;;;;
+325E;CIRCLED NUMBER THIRTY FOUR;No;0;ON;<circle> 0033 0034;;;34;N;;;;;
+325F;CIRCLED NUMBER THIRTY FIVE;No;0;ON;<circle> 0033 0035;;;35;N;;;;;
+3260;CIRCLED HANGUL KIYEOK;So;0;L;<circle> 1100;;;;N;CIRCLED HANGUL GIYEOG;;;;
+3261;CIRCLED HANGUL NIEUN;So;0;L;<circle> 1102;;;;N;;;;;
+3262;CIRCLED HANGUL TIKEUT;So;0;L;<circle> 1103;;;;N;CIRCLED HANGUL DIGEUD;;;;
+3263;CIRCLED HANGUL RIEUL;So;0;L;<circle> 1105;;;;N;CIRCLED HANGUL LIEUL;;;;
+3264;CIRCLED HANGUL MIEUM;So;0;L;<circle> 1106;;;;N;;;;;
+3265;CIRCLED HANGUL PIEUP;So;0;L;<circle> 1107;;;;N;CIRCLED HANGUL BIEUB;;;;
+3266;CIRCLED HANGUL SIOS;So;0;L;<circle> 1109;;;;N;;;;;
+3267;CIRCLED HANGUL IEUNG;So;0;L;<circle> 110B;;;;N;;;;;
+3268;CIRCLED HANGUL CIEUC;So;0;L;<circle> 110C;;;;N;CIRCLED HANGUL JIEUJ;;;;
+3269;CIRCLED HANGUL CHIEUCH;So;0;L;<circle> 110E;;;;N;CIRCLED HANGUL CIEUC;;;;
+326A;CIRCLED HANGUL KHIEUKH;So;0;L;<circle> 110F;;;;N;CIRCLED HANGUL KIYEOK;;;;
+326B;CIRCLED HANGUL THIEUTH;So;0;L;<circle> 1110;;;;N;CIRCLED HANGUL TIEUT;;;;
+326C;CIRCLED HANGUL PHIEUPH;So;0;L;<circle> 1111;;;;N;CIRCLED HANGUL PIEUP;;;;
+326D;CIRCLED HANGUL HIEUH;So;0;L;<circle> 1112;;;;N;;;;;
+326E;CIRCLED HANGUL KIYEOK A;So;0;L;<circle> 1100 1161;;;;N;CIRCLED HANGUL GA;;;;
+326F;CIRCLED HANGUL NIEUN A;So;0;L;<circle> 1102 1161;;;;N;CIRCLED HANGUL NA;;;;
+3270;CIRCLED HANGUL TIKEUT A;So;0;L;<circle> 1103 1161;;;;N;CIRCLED HANGUL DA;;;;
+3271;CIRCLED HANGUL RIEUL A;So;0;L;<circle> 1105 1161;;;;N;CIRCLED HANGUL LA;;;;
+3272;CIRCLED HANGUL MIEUM A;So;0;L;<circle> 1106 1161;;;;N;CIRCLED HANGUL MA;;;;
+3273;CIRCLED HANGUL PIEUP A;So;0;L;<circle> 1107 1161;;;;N;CIRCLED HANGUL BA;;;;
+3274;CIRCLED HANGUL SIOS A;So;0;L;<circle> 1109 1161;;;;N;CIRCLED HANGUL SA;;;;
+3275;CIRCLED HANGUL IEUNG A;So;0;L;<circle> 110B 1161;;;;N;CIRCLED HANGUL A;;;;
+3276;CIRCLED HANGUL CIEUC A;So;0;L;<circle> 110C 1161;;;;N;CIRCLED HANGUL JA;;;;
+3277;CIRCLED HANGUL CHIEUCH A;So;0;L;<circle> 110E 1161;;;;N;CIRCLED HANGUL CA;;;;
+3278;CIRCLED HANGUL KHIEUKH A;So;0;L;<circle> 110F 1161;;;;N;CIRCLED HANGUL KA;;;;
+3279;CIRCLED HANGUL THIEUTH A;So;0;L;<circle> 1110 1161;;;;N;CIRCLED HANGUL TA;;;;
+327A;CIRCLED HANGUL PHIEUPH A;So;0;L;<circle> 1111 1161;;;;N;CIRCLED HANGUL PA;;;;
+327B;CIRCLED HANGUL HIEUH A;So;0;L;<circle> 1112 1161;;;;N;CIRCLED HANGUL HA;;;;
+327C;CIRCLED KOREAN CHARACTER CHAMKO;So;0;ON;<circle> 110E 1161 11B7 1100 1169;;;;N;;;;;
+327D;CIRCLED KOREAN CHARACTER JUEUI;So;0;ON;<circle> 110C 116E 110B 1174;;;;N;;;;;
+327F;KOREAN STANDARD SYMBOL;So;0;L;;;;;N;;;;;
+3280;CIRCLED IDEOGRAPH ONE;No;0;L;<circle> 4E00;;;1;N;;;;;
+3281;CIRCLED IDEOGRAPH TWO;No;0;L;<circle> 4E8C;;;2;N;;;;;
+3282;CIRCLED IDEOGRAPH THREE;No;0;L;<circle> 4E09;;;3;N;;;;;
+3283;CIRCLED IDEOGRAPH FOUR;No;0;L;<circle> 56DB;;;4;N;;;;;
+3284;CIRCLED IDEOGRAPH FIVE;No;0;L;<circle> 4E94;;;5;N;;;;;
+3285;CIRCLED IDEOGRAPH SIX;No;0;L;<circle> 516D;;;6;N;;;;;
+3286;CIRCLED IDEOGRAPH SEVEN;No;0;L;<circle> 4E03;;;7;N;;;;;
+3287;CIRCLED IDEOGRAPH EIGHT;No;0;L;<circle> 516B;;;8;N;;;;;
+3288;CIRCLED IDEOGRAPH NINE;No;0;L;<circle> 4E5D;;;9;N;;;;;
+3289;CIRCLED IDEOGRAPH TEN;No;0;L;<circle> 5341;;;10;N;;;;;
+328A;CIRCLED IDEOGRAPH MOON;So;0;L;<circle> 6708;;;;N;;;;;
+328B;CIRCLED IDEOGRAPH FIRE;So;0;L;<circle> 706B;;;;N;;;;;
+328C;CIRCLED IDEOGRAPH WATER;So;0;L;<circle> 6C34;;;;N;;;;;
+328D;CIRCLED IDEOGRAPH WOOD;So;0;L;<circle> 6728;;;;N;;;;;
+328E;CIRCLED IDEOGRAPH METAL;So;0;L;<circle> 91D1;;;;N;;;;;
+328F;CIRCLED IDEOGRAPH EARTH;So;0;L;<circle> 571F;;;;N;;;;;
+3290;CIRCLED IDEOGRAPH SUN;So;0;L;<circle> 65E5;;;;N;;;;;
+3291;CIRCLED IDEOGRAPH STOCK;So;0;L;<circle> 682A;;;;N;;;;;
+3292;CIRCLED IDEOGRAPH HAVE;So;0;L;<circle> 6709;;;;N;;;;;
+3293;CIRCLED IDEOGRAPH SOCIETY;So;0;L;<circle> 793E;;;;N;;;;;
+3294;CIRCLED IDEOGRAPH NAME;So;0;L;<circle> 540D;;;;N;;;;;
+3295;CIRCLED IDEOGRAPH SPECIAL;So;0;L;<circle> 7279;;;;N;;;;;
+3296;CIRCLED IDEOGRAPH FINANCIAL;So;0;L;<circle> 8CA1;;;;N;;;;;
+3297;CIRCLED IDEOGRAPH CONGRATULATION;So;0;L;<circle> 795D;;;;N;;;;;
+3298;CIRCLED IDEOGRAPH LABOR;So;0;L;<circle> 52B4;;;;N;;;;;
+3299;CIRCLED IDEOGRAPH SECRET;So;0;L;<circle> 79D8;;;;N;;;;;
+329A;CIRCLED IDEOGRAPH MALE;So;0;L;<circle> 7537;;;;N;;;;;
+329B;CIRCLED IDEOGRAPH FEMALE;So;0;L;<circle> 5973;;;;N;;;;;
+329C;CIRCLED IDEOGRAPH SUITABLE;So;0;L;<circle> 9069;;;;N;;;;;
+329D;CIRCLED IDEOGRAPH EXCELLENT;So;0;L;<circle> 512A;;;;N;;;;;
+329E;CIRCLED IDEOGRAPH PRINT;So;0;L;<circle> 5370;;;;N;;;;;
+329F;CIRCLED IDEOGRAPH ATTENTION;So;0;L;<circle> 6CE8;;;;N;;;;;
+32A0;CIRCLED IDEOGRAPH ITEM;So;0;L;<circle> 9805;;;;N;;;;;
+32A1;CIRCLED IDEOGRAPH REST;So;0;L;<circle> 4F11;;;;N;;;;;
+32A2;CIRCLED IDEOGRAPH COPY;So;0;L;<circle> 5199;;;;N;;;;;
+32A3;CIRCLED IDEOGRAPH CORRECT;So;0;L;<circle> 6B63;;;;N;;;;;
+32A4;CIRCLED IDEOGRAPH HIGH;So;0;L;<circle> 4E0A;;;;N;;;;;
+32A5;CIRCLED IDEOGRAPH CENTRE;So;0;L;<circle> 4E2D;;;;N;CIRCLED IDEOGRAPH CENTER;;;;
+32A6;CIRCLED IDEOGRAPH LOW;So;0;L;<circle> 4E0B;;;;N;;;;;
+32A7;CIRCLED IDEOGRAPH LEFT;So;0;L;<circle> 5DE6;;;;N;;;;;
+32A8;CIRCLED IDEOGRAPH RIGHT;So;0;L;<circle> 53F3;;;;N;;;;;
+32A9;CIRCLED IDEOGRAPH MEDICINE;So;0;L;<circle> 533B;;;;N;;;;;
+32AA;CIRCLED IDEOGRAPH RELIGION;So;0;L;<circle> 5B97;;;;N;;;;;
+32AB;CIRCLED IDEOGRAPH STUDY;So;0;L;<circle> 5B66;;;;N;;;;;
+32AC;CIRCLED IDEOGRAPH SUPERVISE;So;0;L;<circle> 76E3;;;;N;;;;;
+32AD;CIRCLED IDEOGRAPH ENTERPRISE;So;0;L;<circle> 4F01;;;;N;;;;;
+32AE;CIRCLED IDEOGRAPH RESOURCE;So;0;L;<circle> 8CC7;;;;N;;;;;
+32AF;CIRCLED IDEOGRAPH ALLIANCE;So;0;L;<circle> 5354;;;;N;;;;;
+32B0;CIRCLED IDEOGRAPH NIGHT;So;0;L;<circle> 591C;;;;N;;;;;
+32B1;CIRCLED NUMBER THIRTY SIX;No;0;ON;<circle> 0033 0036;;;36;N;;;;;
+32B2;CIRCLED NUMBER THIRTY SEVEN;No;0;ON;<circle> 0033 0037;;;37;N;;;;;
+32B3;CIRCLED NUMBER THIRTY EIGHT;No;0;ON;<circle> 0033 0038;;;38;N;;;;;
+32B4;CIRCLED NUMBER THIRTY NINE;No;0;ON;<circle> 0033 0039;;;39;N;;;;;
+32B5;CIRCLED NUMBER FORTY;No;0;ON;<circle> 0034 0030;;;40;N;;;;;
+32B6;CIRCLED NUMBER FORTY ONE;No;0;ON;<circle> 0034 0031;;;41;N;;;;;
+32B7;CIRCLED NUMBER FORTY TWO;No;0;ON;<circle> 0034 0032;;;42;N;;;;;
+32B8;CIRCLED NUMBER FORTY THREE;No;0;ON;<circle> 0034 0033;;;43;N;;;;;
+32B9;CIRCLED NUMBER FORTY FOUR;No;0;ON;<circle> 0034 0034;;;44;N;;;;;
+32BA;CIRCLED NUMBER FORTY FIVE;No;0;ON;<circle> 0034 0035;;;45;N;;;;;
+32BB;CIRCLED NUMBER FORTY SIX;No;0;ON;<circle> 0034 0036;;;46;N;;;;;
+32BC;CIRCLED NUMBER FORTY SEVEN;No;0;ON;<circle> 0034 0037;;;47;N;;;;;
+32BD;CIRCLED NUMBER FORTY EIGHT;No;0;ON;<circle> 0034 0038;;;48;N;;;;;
+32BE;CIRCLED NUMBER FORTY NINE;No;0;ON;<circle> 0034 0039;;;49;N;;;;;
+32BF;CIRCLED NUMBER FIFTY;No;0;ON;<circle> 0035 0030;;;50;N;;;;;
+32C0;IDEOGRAPHIC TELEGRAPH SYMBOL FOR JANUARY;So;0;L;<compat> 0031 6708;;;;N;;;;;
+32C1;IDEOGRAPHIC TELEGRAPH SYMBOL FOR FEBRUARY;So;0;L;<compat> 0032 6708;;;;N;;;;;
+32C2;IDEOGRAPHIC TELEGRAPH SYMBOL FOR MARCH;So;0;L;<compat> 0033 6708;;;;N;;;;;
+32C3;IDEOGRAPHIC TELEGRAPH SYMBOL FOR APRIL;So;0;L;<compat> 0034 6708;;;;N;;;;;
+32C4;IDEOGRAPHIC TELEGRAPH SYMBOL FOR MAY;So;0;L;<compat> 0035 6708;;;;N;;;;;
+32C5;IDEOGRAPHIC TELEGRAPH SYMBOL FOR JUNE;So;0;L;<compat> 0036 6708;;;;N;;;;;
+32C6;IDEOGRAPHIC TELEGRAPH SYMBOL FOR JULY;So;0;L;<compat> 0037 6708;;;;N;;;;;
+32C7;IDEOGRAPHIC TELEGRAPH SYMBOL FOR AUGUST;So;0;L;<compat> 0038 6708;;;;N;;;;;
+32C8;IDEOGRAPHIC TELEGRAPH SYMBOL FOR SEPTEMBER;So;0;L;<compat> 0039 6708;;;;N;;;;;
+32C9;IDEOGRAPHIC TELEGRAPH SYMBOL FOR OCTOBER;So;0;L;<compat> 0031 0030 6708;;;;N;;;;;
+32CA;IDEOGRAPHIC TELEGRAPH SYMBOL FOR NOVEMBER;So;0;L;<compat> 0031 0031 6708;;;;N;;;;;
+32CB;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DECEMBER;So;0;L;<compat> 0031 0032 6708;;;;N;;;;;
+32CC;SQUARE HG;So;0;ON;<square> 0048 0067;;;;N;;;;;
+32CD;SQUARE ERG;So;0;ON;<square> 0065 0072 0067;;;;N;;;;;
+32CE;SQUARE EV;So;0;ON;<square> 0065 0056;;;;N;;;;;
+32CF;LIMITED LIABILITY SIGN;So;0;ON;<square> 004C 0054 0044;;;;N;;;;;
+32D0;CIRCLED KATAKANA A;So;0;L;<circle> 30A2;;;;N;;;;;
+32D1;CIRCLED KATAKANA I;So;0;L;<circle> 30A4;;;;N;;;;;
+32D2;CIRCLED KATAKANA U;So;0;L;<circle> 30A6;;;;N;;;;;
+32D3;CIRCLED KATAKANA E;So;0;L;<circle> 30A8;;;;N;;;;;
+32D4;CIRCLED KATAKANA O;So;0;L;<circle> 30AA;;;;N;;;;;
+32D5;CIRCLED KATAKANA KA;So;0;L;<circle> 30AB;;;;N;;;;;
+32D6;CIRCLED KATAKANA KI;So;0;L;<circle> 30AD;;;;N;;;;;
+32D7;CIRCLED KATAKANA KU;So;0;L;<circle> 30AF;;;;N;;;;;
+32D8;CIRCLED KATAKANA KE;So;0;L;<circle> 30B1;;;;N;;;;;
+32D9;CIRCLED KATAKANA KO;So;0;L;<circle> 30B3;;;;N;;;;;
+32DA;CIRCLED KATAKANA SA;So;0;L;<circle> 30B5;;;;N;;;;;
+32DB;CIRCLED KATAKANA SI;So;0;L;<circle> 30B7;;;;N;;;;;
+32DC;CIRCLED KATAKANA SU;So;0;L;<circle> 30B9;;;;N;;;;;
+32DD;CIRCLED KATAKANA SE;So;0;L;<circle> 30BB;;;;N;;;;;
+32DE;CIRCLED KATAKANA SO;So;0;L;<circle> 30BD;;;;N;;;;;
+32DF;CIRCLED KATAKANA TA;So;0;L;<circle> 30BF;;;;N;;;;;
+32E0;CIRCLED KATAKANA TI;So;0;L;<circle> 30C1;;;;N;;;;;
+32E1;CIRCLED KATAKANA TU;So;0;L;<circle> 30C4;;;;N;;;;;
+32E2;CIRCLED KATAKANA TE;So;0;L;<circle> 30C6;;;;N;;;;;
+32E3;CIRCLED KATAKANA TO;So;0;L;<circle> 30C8;;;;N;;;;;
+32E4;CIRCLED KATAKANA NA;So;0;L;<circle> 30CA;;;;N;;;;;
+32E5;CIRCLED KATAKANA NI;So;0;L;<circle> 30CB;;;;N;;;;;
+32E6;CIRCLED KATAKANA NU;So;0;L;<circle> 30CC;;;;N;;;;;
+32E7;CIRCLED KATAKANA NE;So;0;L;<circle> 30CD;;;;N;;;;;
+32E8;CIRCLED KATAKANA NO;So;0;L;<circle> 30CE;;;;N;;;;;
+32E9;CIRCLED KATAKANA HA;So;0;L;<circle> 30CF;;;;N;;;;;
+32EA;CIRCLED KATAKANA HI;So;0;L;<circle> 30D2;;;;N;;;;;
+32EB;CIRCLED KATAKANA HU;So;0;L;<circle> 30D5;;;;N;;;;;
+32EC;CIRCLED KATAKANA HE;So;0;L;<circle> 30D8;;;;N;;;;;
+32ED;CIRCLED KATAKANA HO;So;0;L;<circle> 30DB;;;;N;;;;;
+32EE;CIRCLED KATAKANA MA;So;0;L;<circle> 30DE;;;;N;;;;;
+32EF;CIRCLED KATAKANA MI;So;0;L;<circle> 30DF;;;;N;;;;;
+32F0;CIRCLED KATAKANA MU;So;0;L;<circle> 30E0;;;;N;;;;;
+32F1;CIRCLED KATAKANA ME;So;0;L;<circle> 30E1;;;;N;;;;;
+32F2;CIRCLED KATAKANA MO;So;0;L;<circle> 30E2;;;;N;;;;;
+32F3;CIRCLED KATAKANA YA;So;0;L;<circle> 30E4;;;;N;;;;;
+32F4;CIRCLED KATAKANA YU;So;0;L;<circle> 30E6;;;;N;;;;;
+32F5;CIRCLED KATAKANA YO;So;0;L;<circle> 30E8;;;;N;;;;;
+32F6;CIRCLED KATAKANA RA;So;0;L;<circle> 30E9;;;;N;;;;;
+32F7;CIRCLED KATAKANA RI;So;0;L;<circle> 30EA;;;;N;;;;;
+32F8;CIRCLED KATAKANA RU;So;0;L;<circle> 30EB;;;;N;;;;;
+32F9;CIRCLED KATAKANA RE;So;0;L;<circle> 30EC;;;;N;;;;;
+32FA;CIRCLED KATAKANA RO;So;0;L;<circle> 30ED;;;;N;;;;;
+32FB;CIRCLED KATAKANA WA;So;0;L;<circle> 30EF;;;;N;;;;;
+32FC;CIRCLED KATAKANA WI;So;0;L;<circle> 30F0;;;;N;;;;;
+32FD;CIRCLED KATAKANA WE;So;0;L;<circle> 30F1;;;;N;;;;;
+32FE;CIRCLED KATAKANA WO;So;0;L;<circle> 30F2;;;;N;;;;;
+3300;SQUARE APAATO;So;0;L;<square> 30A2 30D1 30FC 30C8;;;;N;SQUARED APAATO;;;;
+3301;SQUARE ARUHUA;So;0;L;<square> 30A2 30EB 30D5 30A1;;;;N;SQUARED ARUHUA;;;;
+3302;SQUARE ANPEA;So;0;L;<square> 30A2 30F3 30DA 30A2;;;;N;SQUARED ANPEA;;;;
+3303;SQUARE AARU;So;0;L;<square> 30A2 30FC 30EB;;;;N;SQUARED AARU;;;;
+3304;SQUARE ININGU;So;0;L;<square> 30A4 30CB 30F3 30B0;;;;N;SQUARED ININGU;;;;
+3305;SQUARE INTI;So;0;L;<square> 30A4 30F3 30C1;;;;N;SQUARED INTI;;;;
+3306;SQUARE UON;So;0;L;<square> 30A6 30A9 30F3;;;;N;SQUARED UON;;;;
+3307;SQUARE ESUKUUDO;So;0;L;<square> 30A8 30B9 30AF 30FC 30C9;;;;N;SQUARED ESUKUUDO;;;;
+3308;SQUARE EEKAA;So;0;L;<square> 30A8 30FC 30AB 30FC;;;;N;SQUARED EEKAA;;;;
+3309;SQUARE ONSU;So;0;L;<square> 30AA 30F3 30B9;;;;N;SQUARED ONSU;;;;
+330A;SQUARE OOMU;So;0;L;<square> 30AA 30FC 30E0;;;;N;SQUARED OOMU;;;;
+330B;SQUARE KAIRI;So;0;L;<square> 30AB 30A4 30EA;;;;N;SQUARED KAIRI;;;;
+330C;SQUARE KARATTO;So;0;L;<square> 30AB 30E9 30C3 30C8;;;;N;SQUARED KARATTO;;;;
+330D;SQUARE KARORII;So;0;L;<square> 30AB 30ED 30EA 30FC;;;;N;SQUARED KARORII;;;;
+330E;SQUARE GARON;So;0;L;<square> 30AC 30ED 30F3;;;;N;SQUARED GARON;;;;
+330F;SQUARE GANMA;So;0;L;<square> 30AC 30F3 30DE;;;;N;SQUARED GANMA;;;;
+3310;SQUARE GIGA;So;0;L;<square> 30AE 30AC;;;;N;SQUARED GIGA;;;;
+3311;SQUARE GINII;So;0;L;<square> 30AE 30CB 30FC;;;;N;SQUARED GINII;;;;
+3312;SQUARE KYURII;So;0;L;<square> 30AD 30E5 30EA 30FC;;;;N;SQUARED KYURII;;;;
+3313;SQUARE GIRUDAA;So;0;L;<square> 30AE 30EB 30C0 30FC;;;;N;SQUARED GIRUDAA;;;;
+3314;SQUARE KIRO;So;0;L;<square> 30AD 30ED;;;;N;SQUARED KIRO;;;;
+3315;SQUARE KIROGURAMU;So;0;L;<square> 30AD 30ED 30B0 30E9 30E0;;;;N;SQUARED KIROGURAMU;;;;
+3316;SQUARE KIROMEETORU;So;0;L;<square> 30AD 30ED 30E1 30FC 30C8 30EB;;;;N;SQUARED KIROMEETORU;;;;
+3317;SQUARE KIROWATTO;So;0;L;<square> 30AD 30ED 30EF 30C3 30C8;;;;N;SQUARED KIROWATTO;;;;
+3318;SQUARE GURAMU;So;0;L;<square> 30B0 30E9 30E0;;;;N;SQUARED GURAMU;;;;
+3319;SQUARE GURAMUTON;So;0;L;<square> 30B0 30E9 30E0 30C8 30F3;;;;N;SQUARED GURAMUTON;;;;
+331A;SQUARE KURUZEIRO;So;0;L;<square> 30AF 30EB 30BC 30A4 30ED;;;;N;SQUARED KURUZEIRO;;;;
+331B;SQUARE KUROONE;So;0;L;<square> 30AF 30ED 30FC 30CD;;;;N;SQUARED KUROONE;;;;
+331C;SQUARE KEESU;So;0;L;<square> 30B1 30FC 30B9;;;;N;SQUARED KEESU;;;;
+331D;SQUARE KORUNA;So;0;L;<square> 30B3 30EB 30CA;;;;N;SQUARED KORUNA;;;;
+331E;SQUARE KOOPO;So;0;L;<square> 30B3 30FC 30DD;;;;N;SQUARED KOOPO;;;;
+331F;SQUARE SAIKURU;So;0;L;<square> 30B5 30A4 30AF 30EB;;;;N;SQUARED SAIKURU;;;;
+3320;SQUARE SANTIIMU;So;0;L;<square> 30B5 30F3 30C1 30FC 30E0;;;;N;SQUARED SANTIIMU;;;;
+3321;SQUARE SIRINGU;So;0;L;<square> 30B7 30EA 30F3 30B0;;;;N;SQUARED SIRINGU;;;;
+3322;SQUARE SENTI;So;0;L;<square> 30BB 30F3 30C1;;;;N;SQUARED SENTI;;;;
+3323;SQUARE SENTO;So;0;L;<square> 30BB 30F3 30C8;;;;N;SQUARED SENTO;;;;
+3324;SQUARE DAASU;So;0;L;<square> 30C0 30FC 30B9;;;;N;SQUARED DAASU;;;;
+3325;SQUARE DESI;So;0;L;<square> 30C7 30B7;;;;N;SQUARED DESI;;;;
+3326;SQUARE DORU;So;0;L;<square> 30C9 30EB;;;;N;SQUARED DORU;;;;
+3327;SQUARE TON;So;0;L;<square> 30C8 30F3;;;;N;SQUARED TON;;;;
+3328;SQUARE NANO;So;0;L;<square> 30CA 30CE;;;;N;SQUARED NANO;;;;
+3329;SQUARE NOTTO;So;0;L;<square> 30CE 30C3 30C8;;;;N;SQUARED NOTTO;;;;
+332A;SQUARE HAITU;So;0;L;<square> 30CF 30A4 30C4;;;;N;SQUARED HAITU;;;;
+332B;SQUARE PAASENTO;So;0;L;<square> 30D1 30FC 30BB 30F3 30C8;;;;N;SQUARED PAASENTO;;;;
+332C;SQUARE PAATU;So;0;L;<square> 30D1 30FC 30C4;;;;N;SQUARED PAATU;;;;
+332D;SQUARE BAARERU;So;0;L;<square> 30D0 30FC 30EC 30EB;;;;N;SQUARED BAARERU;;;;
+332E;SQUARE PIASUTORU;So;0;L;<square> 30D4 30A2 30B9 30C8 30EB;;;;N;SQUARED PIASUTORU;;;;
+332F;SQUARE PIKURU;So;0;L;<square> 30D4 30AF 30EB;;;;N;SQUARED PIKURU;;;;
+3330;SQUARE PIKO;So;0;L;<square> 30D4 30B3;;;;N;SQUARED PIKO;;;;
+3331;SQUARE BIRU;So;0;L;<square> 30D3 30EB;;;;N;SQUARED BIRU;;;;
+3332;SQUARE HUARADDO;So;0;L;<square> 30D5 30A1 30E9 30C3 30C9;;;;N;SQUARED HUARADDO;;;;
+3333;SQUARE HUIITO;So;0;L;<square> 30D5 30A3 30FC 30C8;;;;N;SQUARED HUIITO;;;;
+3334;SQUARE BUSSYERU;So;0;L;<square> 30D6 30C3 30B7 30A7 30EB;;;;N;SQUARED BUSSYERU;;;;
+3335;SQUARE HURAN;So;0;L;<square> 30D5 30E9 30F3;;;;N;SQUARED HURAN;;;;
+3336;SQUARE HEKUTAARU;So;0;L;<square> 30D8 30AF 30BF 30FC 30EB;;;;N;SQUARED HEKUTAARU;;;;
+3337;SQUARE PESO;So;0;L;<square> 30DA 30BD;;;;N;SQUARED PESO;;;;
+3338;SQUARE PENIHI;So;0;L;<square> 30DA 30CB 30D2;;;;N;SQUARED PENIHI;;;;
+3339;SQUARE HERUTU;So;0;L;<square> 30D8 30EB 30C4;;;;N;SQUARED HERUTU;;;;
+333A;SQUARE PENSU;So;0;L;<square> 30DA 30F3 30B9;;;;N;SQUARED PENSU;;;;
+333B;SQUARE PEEZI;So;0;L;<square> 30DA 30FC 30B8;;;;N;SQUARED PEEZI;;;;
+333C;SQUARE BEETA;So;0;L;<square> 30D9 30FC 30BF;;;;N;SQUARED BEETA;;;;
+333D;SQUARE POINTO;So;0;L;<square> 30DD 30A4 30F3 30C8;;;;N;SQUARED POINTO;;;;
+333E;SQUARE BORUTO;So;0;L;<square> 30DC 30EB 30C8;;;;N;SQUARED BORUTO;;;;
+333F;SQUARE HON;So;0;L;<square> 30DB 30F3;;;;N;SQUARED HON;;;;
+3340;SQUARE PONDO;So;0;L;<square> 30DD 30F3 30C9;;;;N;SQUARED PONDO;;;;
+3341;SQUARE HOORU;So;0;L;<square> 30DB 30FC 30EB;;;;N;SQUARED HOORU;;;;
+3342;SQUARE HOON;So;0;L;<square> 30DB 30FC 30F3;;;;N;SQUARED HOON;;;;
+3343;SQUARE MAIKURO;So;0;L;<square> 30DE 30A4 30AF 30ED;;;;N;SQUARED MAIKURO;;;;
+3344;SQUARE MAIRU;So;0;L;<square> 30DE 30A4 30EB;;;;N;SQUARED MAIRU;;;;
+3345;SQUARE MAHHA;So;0;L;<square> 30DE 30C3 30CF;;;;N;SQUARED MAHHA;;;;
+3346;SQUARE MARUKU;So;0;L;<square> 30DE 30EB 30AF;;;;N;SQUARED MARUKU;;;;
+3347;SQUARE MANSYON;So;0;L;<square> 30DE 30F3 30B7 30E7 30F3;;;;N;SQUARED MANSYON;;;;
+3348;SQUARE MIKURON;So;0;L;<square> 30DF 30AF 30ED 30F3;;;;N;SQUARED MIKURON;;;;
+3349;SQUARE MIRI;So;0;L;<square> 30DF 30EA;;;;N;SQUARED MIRI;;;;
+334A;SQUARE MIRIBAARU;So;0;L;<square> 30DF 30EA 30D0 30FC 30EB;;;;N;SQUARED MIRIBAARU;;;;
+334B;SQUARE MEGA;So;0;L;<square> 30E1 30AC;;;;N;SQUARED MEGA;;;;
+334C;SQUARE MEGATON;So;0;L;<square> 30E1 30AC 30C8 30F3;;;;N;SQUARED MEGATON;;;;
+334D;SQUARE MEETORU;So;0;L;<square> 30E1 30FC 30C8 30EB;;;;N;SQUARED MEETORU;;;;
+334E;SQUARE YAADO;So;0;L;<square> 30E4 30FC 30C9;;;;N;SQUARED YAADO;;;;
+334F;SQUARE YAARU;So;0;L;<square> 30E4 30FC 30EB;;;;N;SQUARED YAARU;;;;
+3350;SQUARE YUAN;So;0;L;<square> 30E6 30A2 30F3;;;;N;SQUARED YUAN;;;;
+3351;SQUARE RITTORU;So;0;L;<square> 30EA 30C3 30C8 30EB;;;;N;SQUARED RITTORU;;;;
+3352;SQUARE RIRA;So;0;L;<square> 30EA 30E9;;;;N;SQUARED RIRA;;;;
+3353;SQUARE RUPII;So;0;L;<square> 30EB 30D4 30FC;;;;N;SQUARED RUPII;;;;
+3354;SQUARE RUUBURU;So;0;L;<square> 30EB 30FC 30D6 30EB;;;;N;SQUARED RUUBURU;;;;
+3355;SQUARE REMU;So;0;L;<square> 30EC 30E0;;;;N;SQUARED REMU;;;;
+3356;SQUARE RENTOGEN;So;0;L;<square> 30EC 30F3 30C8 30B2 30F3;;;;N;SQUARED RENTOGEN;;;;
+3357;SQUARE WATTO;So;0;L;<square> 30EF 30C3 30C8;;;;N;SQUARED WATTO;;;;
+3358;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR ZERO;So;0;L;<compat> 0030 70B9;;;;N;;;;;
+3359;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR ONE;So;0;L;<compat> 0031 70B9;;;;N;;;;;
+335A;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWO;So;0;L;<compat> 0032 70B9;;;;N;;;;;
+335B;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR THREE;So;0;L;<compat> 0033 70B9;;;;N;;;;;
+335C;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FOUR;So;0;L;<compat> 0034 70B9;;;;N;;;;;
+335D;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FIVE;So;0;L;<compat> 0035 70B9;;;;N;;;;;
+335E;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SIX;So;0;L;<compat> 0036 70B9;;;;N;;;;;
+335F;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SEVEN;So;0;L;<compat> 0037 70B9;;;;N;;;;;
+3360;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR EIGHT;So;0;L;<compat> 0038 70B9;;;;N;;;;;
+3361;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR NINE;So;0;L;<compat> 0039 70B9;;;;N;;;;;
+3362;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TEN;So;0;L;<compat> 0031 0030 70B9;;;;N;;;;;
+3363;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR ELEVEN;So;0;L;<compat> 0031 0031 70B9;;;;N;;;;;
+3364;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWELVE;So;0;L;<compat> 0031 0032 70B9;;;;N;;;;;
+3365;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR THIRTEEN;So;0;L;<compat> 0031 0033 70B9;;;;N;;;;;
+3366;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FOURTEEN;So;0;L;<compat> 0031 0034 70B9;;;;N;;;;;
+3367;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FIFTEEN;So;0;L;<compat> 0031 0035 70B9;;;;N;;;;;
+3368;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SIXTEEN;So;0;L;<compat> 0031 0036 70B9;;;;N;;;;;
+3369;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SEVENTEEN;So;0;L;<compat> 0031 0037 70B9;;;;N;;;;;
+336A;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR EIGHTEEN;So;0;L;<compat> 0031 0038 70B9;;;;N;;;;;
+336B;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR NINETEEN;So;0;L;<compat> 0031 0039 70B9;;;;N;;;;;
+336C;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY;So;0;L;<compat> 0032 0030 70B9;;;;N;;;;;
+336D;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-ONE;So;0;L;<compat> 0032 0031 70B9;;;;N;;;;;
+336E;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-TWO;So;0;L;<compat> 0032 0032 70B9;;;;N;;;;;
+336F;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-THREE;So;0;L;<compat> 0032 0033 70B9;;;;N;;;;;
+3370;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-FOUR;So;0;L;<compat> 0032 0034 70B9;;;;N;;;;;
+3371;SQUARE HPA;So;0;L;<square> 0068 0050 0061;;;;N;;;;;
+3372;SQUARE DA;So;0;L;<square> 0064 0061;;;;N;;;;;
+3373;SQUARE AU;So;0;L;<square> 0041 0055;;;;N;;;;;
+3374;SQUARE BAR;So;0;L;<square> 0062 0061 0072;;;;N;;;;;
+3375;SQUARE OV;So;0;L;<square> 006F 0056;;;;N;;;;;
+3376;SQUARE PC;So;0;L;<square> 0070 0063;;;;N;;;;;
+3377;SQUARE DM;So;0;ON;<square> 0064 006D;;;;N;;;;;
+3378;SQUARE DM SQUARED;So;0;ON;<square> 0064 006D 00B2;;;;N;;;;;
+3379;SQUARE DM CUBED;So;0;ON;<square> 0064 006D 00B3;;;;N;;;;;
+337A;SQUARE IU;So;0;ON;<square> 0049 0055;;;;N;;;;;
+337B;SQUARE ERA NAME HEISEI;So;0;L;<square> 5E73 6210;;;;N;SQUARED TWO IDEOGRAPHS ERA NAME HEISEI;;;;
+337C;SQUARE ERA NAME SYOUWA;So;0;L;<square> 662D 548C;;;;N;SQUARED TWO IDEOGRAPHS ERA NAME SYOUWA;;;;
+337D;SQUARE ERA NAME TAISYOU;So;0;L;<square> 5927 6B63;;;;N;SQUARED TWO IDEOGRAPHS ERA NAME TAISYOU;;;;
+337E;SQUARE ERA NAME MEIZI;So;0;L;<square> 660E 6CBB;;;;N;SQUARED TWO IDEOGRAPHS ERA NAME MEIZI;;;;
+337F;SQUARE CORPORATION;So;0;L;<square> 682A 5F0F 4F1A 793E;;;;N;SQUARED FOUR IDEOGRAPHS CORPORATION;;;;
+3380;SQUARE PA AMPS;So;0;L;<square> 0070 0041;;;;N;SQUARED PA AMPS;;;;
+3381;SQUARE NA;So;0;L;<square> 006E 0041;;;;N;SQUARED NA;;;;
+3382;SQUARE MU A;So;0;L;<square> 03BC 0041;;;;N;SQUARED MU A;;;;
+3383;SQUARE MA;So;0;L;<square> 006D 0041;;;;N;SQUARED MA;;;;
+3384;SQUARE KA;So;0;L;<square> 006B 0041;;;;N;SQUARED KA;;;;
+3385;SQUARE KB;So;0;L;<square> 004B 0042;;;;N;SQUARED KB;;;;
+3386;SQUARE MB;So;0;L;<square> 004D 0042;;;;N;SQUARED MB;;;;
+3387;SQUARE GB;So;0;L;<square> 0047 0042;;;;N;SQUARED GB;;;;
+3388;SQUARE CAL;So;0;L;<square> 0063 0061 006C;;;;N;SQUARED CAL;;;;
+3389;SQUARE KCAL;So;0;L;<square> 006B 0063 0061 006C;;;;N;SQUARED KCAL;;;;
+338A;SQUARE PF;So;0;L;<square> 0070 0046;;;;N;SQUARED PF;;;;
+338B;SQUARE NF;So;0;L;<square> 006E 0046;;;;N;SQUARED NF;;;;
+338C;SQUARE MU F;So;0;L;<square> 03BC 0046;;;;N;SQUARED MU F;;;;
+338D;SQUARE MU G;So;0;L;<square> 03BC 0067;;;;N;SQUARED MU G;;;;
+338E;SQUARE MG;So;0;L;<square> 006D 0067;;;;N;SQUARED MG;;;;
+338F;SQUARE KG;So;0;L;<square> 006B 0067;;;;N;SQUARED KG;;;;
+3390;SQUARE HZ;So;0;L;<square> 0048 007A;;;;N;SQUARED HZ;;;;
+3391;SQUARE KHZ;So;0;L;<square> 006B 0048 007A;;;;N;SQUARED KHZ;;;;
+3392;SQUARE MHZ;So;0;L;<square> 004D 0048 007A;;;;N;SQUARED MHZ;;;;
+3393;SQUARE GHZ;So;0;L;<square> 0047 0048 007A;;;;N;SQUARED GHZ;;;;
+3394;SQUARE THZ;So;0;L;<square> 0054 0048 007A;;;;N;SQUARED THZ;;;;
+3395;SQUARE MU L;So;0;L;<square> 03BC 2113;;;;N;SQUARED MU L;;;;
+3396;SQUARE ML;So;0;L;<square> 006D 2113;;;;N;SQUARED ML;;;;
+3397;SQUARE DL;So;0;L;<square> 0064 2113;;;;N;SQUARED DL;;;;
+3398;SQUARE KL;So;0;L;<square> 006B 2113;;;;N;SQUARED KL;;;;
+3399;SQUARE FM;So;0;L;<square> 0066 006D;;;;N;SQUARED FM;;;;
+339A;SQUARE NM;So;0;L;<square> 006E 006D;;;;N;SQUARED NM;;;;
+339B;SQUARE MU M;So;0;L;<square> 03BC 006D;;;;N;SQUARED MU M;;;;
+339C;SQUARE MM;So;0;L;<square> 006D 006D;;;;N;SQUARED MM;;;;
+339D;SQUARE CM;So;0;L;<square> 0063 006D;;;;N;SQUARED CM;;;;
+339E;SQUARE KM;So;0;L;<square> 006B 006D;;;;N;SQUARED KM;;;;
+339F;SQUARE MM SQUARED;So;0;L;<square> 006D 006D 00B2;;;;N;SQUARED MM SQUARED;;;;
+33A0;SQUARE CM SQUARED;So;0;L;<square> 0063 006D 00B2;;;;N;SQUARED CM SQUARED;;;;
+33A1;SQUARE M SQUARED;So;0;L;<square> 006D 00B2;;;;N;SQUARED M SQUARED;;;;
+33A2;SQUARE KM SQUARED;So;0;L;<square> 006B 006D 00B2;;;;N;SQUARED KM SQUARED;;;;
+33A3;SQUARE MM CUBED;So;0;L;<square> 006D 006D 00B3;;;;N;SQUARED MM CUBED;;;;
+33A4;SQUARE CM CUBED;So;0;L;<square> 0063 006D 00B3;;;;N;SQUARED CM CUBED;;;;
+33A5;SQUARE M CUBED;So;0;L;<square> 006D 00B3;;;;N;SQUARED M CUBED;;;;
+33A6;SQUARE KM CUBED;So;0;L;<square> 006B 006D 00B3;;;;N;SQUARED KM CUBED;;;;
+33A7;SQUARE M OVER S;So;0;L;<square> 006D 2215 0073;;;;N;SQUARED M OVER S;;;;
+33A8;SQUARE M OVER S SQUARED;So;0;L;<square> 006D 2215 0073 00B2;;;;N;SQUARED M OVER S SQUARED;;;;
+33A9;SQUARE PA;So;0;L;<square> 0050 0061;;;;N;SQUARED PA;;;;
+33AA;SQUARE KPA;So;0;L;<square> 006B 0050 0061;;;;N;SQUARED KPA;;;;
+33AB;SQUARE MPA;So;0;L;<square> 004D 0050 0061;;;;N;SQUARED MPA;;;;
+33AC;SQUARE GPA;So;0;L;<square> 0047 0050 0061;;;;N;SQUARED GPA;;;;
+33AD;SQUARE RAD;So;0;L;<square> 0072 0061 0064;;;;N;SQUARED RAD;;;;
+33AE;SQUARE RAD OVER S;So;0;L;<square> 0072 0061 0064 2215 0073;;;;N;SQUARED RAD OVER S;;;;
+33AF;SQUARE RAD OVER S SQUARED;So;0;L;<square> 0072 0061 0064 2215 0073 00B2;;;;N;SQUARED RAD OVER S SQUARED;;;;
+33B0;SQUARE PS;So;0;L;<square> 0070 0073;;;;N;SQUARED PS;;;;
+33B1;SQUARE NS;So;0;L;<square> 006E 0073;;;;N;SQUARED NS;;;;
+33B2;SQUARE MU S;So;0;L;<square> 03BC 0073;;;;N;SQUARED MU S;;;;
+33B3;SQUARE MS;So;0;L;<square> 006D 0073;;;;N;SQUARED MS;;;;
+33B4;SQUARE PV;So;0;L;<square> 0070 0056;;;;N;SQUARED PV;;;;
+33B5;SQUARE NV;So;0;L;<square> 006E 0056;;;;N;SQUARED NV;;;;
+33B6;SQUARE MU V;So;0;L;<square> 03BC 0056;;;;N;SQUARED MU V;;;;
+33B7;SQUARE MV;So;0;L;<square> 006D 0056;;;;N;SQUARED MV;;;;
+33B8;SQUARE KV;So;0;L;<square> 006B 0056;;;;N;SQUARED KV;;;;
+33B9;SQUARE MV MEGA;So;0;L;<square> 004D 0056;;;;N;SQUARED MV MEGA;;;;
+33BA;SQUARE PW;So;0;L;<square> 0070 0057;;;;N;SQUARED PW;;;;
+33BB;SQUARE NW;So;0;L;<square> 006E 0057;;;;N;SQUARED NW;;;;
+33BC;SQUARE MU W;So;0;L;<square> 03BC 0057;;;;N;SQUARED MU W;;;;
+33BD;SQUARE MW;So;0;L;<square> 006D 0057;;;;N;SQUARED MW;;;;
+33BE;SQUARE KW;So;0;L;<square> 006B 0057;;;;N;SQUARED KW;;;;
+33BF;SQUARE MW MEGA;So;0;L;<square> 004D 0057;;;;N;SQUARED MW MEGA;;;;
+33C0;SQUARE K OHM;So;0;L;<square> 006B 03A9;;;;N;SQUARED K OHM;;;;
+33C1;SQUARE M OHM;So;0;L;<square> 004D 03A9;;;;N;SQUARED M OHM;;;;
+33C2;SQUARE AM;So;0;L;<square> 0061 002E 006D 002E;;;;N;SQUARED AM;;;;
+33C3;SQUARE BQ;So;0;L;<square> 0042 0071;;;;N;SQUARED BQ;;;;
+33C4;SQUARE CC;So;0;L;<square> 0063 0063;;;;N;SQUARED CC;;;;
+33C5;SQUARE CD;So;0;L;<square> 0063 0064;;;;N;SQUARED CD;;;;
+33C6;SQUARE C OVER KG;So;0;L;<square> 0043 2215 006B 0067;;;;N;SQUARED C OVER KG;;;;
+33C7;SQUARE CO;So;0;L;<square> 0043 006F 002E;;;;N;SQUARED CO;;;;
+33C8;SQUARE DB;So;0;L;<square> 0064 0042;;;;N;SQUARED DB;;;;
+33C9;SQUARE GY;So;0;L;<square> 0047 0079;;;;N;SQUARED GY;;;;
+33CA;SQUARE HA;So;0;L;<square> 0068 0061;;;;N;SQUARED HA;;;;
+33CB;SQUARE HP;So;0;L;<square> 0048 0050;;;;N;SQUARED HP;;;;
+33CC;SQUARE IN;So;0;L;<square> 0069 006E;;;;N;SQUARED IN;;;;
+33CD;SQUARE KK;So;0;L;<square> 004B 004B;;;;N;SQUARED KK;;;;
+33CE;SQUARE KM CAPITAL;So;0;L;<square> 004B 004D;;;;N;SQUARED KM CAPITAL;;;;
+33CF;SQUARE KT;So;0;L;<square> 006B 0074;;;;N;SQUARED KT;;;;
+33D0;SQUARE LM;So;0;L;<square> 006C 006D;;;;N;SQUARED LM;;;;
+33D1;SQUARE LN;So;0;L;<square> 006C 006E;;;;N;SQUARED LN;;;;
+33D2;SQUARE LOG;So;0;L;<square> 006C 006F 0067;;;;N;SQUARED LOG;;;;
+33D3;SQUARE LX;So;0;L;<square> 006C 0078;;;;N;SQUARED LX;;;;
+33D4;SQUARE MB SMALL;So;0;L;<square> 006D 0062;;;;N;SQUARED MB SMALL;;;;
+33D5;SQUARE MIL;So;0;L;<square> 006D 0069 006C;;;;N;SQUARED MIL;;;;
+33D6;SQUARE MOL;So;0;L;<square> 006D 006F 006C;;;;N;SQUARED MOL;;;;
+33D7;SQUARE PH;So;0;L;<square> 0050 0048;;;;N;SQUARED PH;;;;
+33D8;SQUARE PM;So;0;L;<square> 0070 002E 006D 002E;;;;N;SQUARED PM;;;;
+33D9;SQUARE PPM;So;0;L;<square> 0050 0050 004D;;;;N;SQUARED PPM;;;;
+33DA;SQUARE PR;So;0;L;<square> 0050 0052;;;;N;SQUARED PR;;;;
+33DB;SQUARE SR;So;0;L;<square> 0073 0072;;;;N;SQUARED SR;;;;
+33DC;SQUARE SV;So;0;L;<square> 0053 0076;;;;N;SQUARED SV;;;;
+33DD;SQUARE WB;So;0;L;<square> 0057 0062;;;;N;SQUARED WB;;;;
+33DE;SQUARE V OVER M;So;0;ON;<square> 0056 2215 006D;;;;N;;;;;
+33DF;SQUARE A OVER M;So;0;ON;<square> 0041 2215 006D;;;;N;;;;;
+33E0;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY ONE;So;0;L;<compat> 0031 65E5;;;;N;;;;;
+33E1;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWO;So;0;L;<compat> 0032 65E5;;;;N;;;;;
+33E2;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THREE;So;0;L;<compat> 0033 65E5;;;;N;;;;;
+33E3;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FOUR;So;0;L;<compat> 0034 65E5;;;;N;;;;;
+33E4;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FIVE;So;0;L;<compat> 0035 65E5;;;;N;;;;;
+33E5;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SIX;So;0;L;<compat> 0036 65E5;;;;N;;;;;
+33E6;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SEVEN;So;0;L;<compat> 0037 65E5;;;;N;;;;;
+33E7;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY EIGHT;So;0;L;<compat> 0038 65E5;;;;N;;;;;
+33E8;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY NINE;So;0;L;<compat> 0039 65E5;;;;N;;;;;
+33E9;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TEN;So;0;L;<compat> 0031 0030 65E5;;;;N;;;;;
+33EA;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY ELEVEN;So;0;L;<compat> 0031 0031 65E5;;;;N;;;;;
+33EB;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWELVE;So;0;L;<compat> 0031 0032 65E5;;;;N;;;;;
+33EC;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THIRTEEN;So;0;L;<compat> 0031 0033 65E5;;;;N;;;;;
+33ED;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FOURTEEN;So;0;L;<compat> 0031 0034 65E5;;;;N;;;;;
+33EE;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FIFTEEN;So;0;L;<compat> 0031 0035 65E5;;;;N;;;;;
+33EF;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SIXTEEN;So;0;L;<compat> 0031 0036 65E5;;;;N;;;;;
+33F0;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SEVENTEEN;So;0;L;<compat> 0031 0037 65E5;;;;N;;;;;
+33F1;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY EIGHTEEN;So;0;L;<compat> 0031 0038 65E5;;;;N;;;;;
+33F2;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY NINETEEN;So;0;L;<compat> 0031 0039 65E5;;;;N;;;;;
+33F3;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY;So;0;L;<compat> 0032 0030 65E5;;;;N;;;;;
+33F4;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-ONE;So;0;L;<compat> 0032 0031 65E5;;;;N;;;;;
+33F5;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-TWO;So;0;L;<compat> 0032 0032 65E5;;;;N;;;;;
+33F6;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-THREE;So;0;L;<compat> 0032 0033 65E5;;;;N;;;;;
+33F7;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-FOUR;So;0;L;<compat> 0032 0034 65E5;;;;N;;;;;
+33F8;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-FIVE;So;0;L;<compat> 0032 0035 65E5;;;;N;;;;;
+33F9;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-SIX;So;0;L;<compat> 0032 0036 65E5;;;;N;;;;;
+33FA;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-SEVEN;So;0;L;<compat> 0032 0037 65E5;;;;N;;;;;
+33FB;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-EIGHT;So;0;L;<compat> 0032 0038 65E5;;;;N;;;;;
+33FC;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-NINE;So;0;L;<compat> 0032 0039 65E5;;;;N;;;;;
+33FD;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THIRTY;So;0;L;<compat> 0033 0030 65E5;;;;N;;;;;
+33FE;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THIRTY-ONE;So;0;L;<compat> 0033 0031 65E5;;;;N;;;;;
+33FF;SQUARE GAL;So;0;ON;<square> 0067 0061 006C;;;;N;;;;;
+3400;<CJK Ideograph Extension A, First>;Lo;0;L;;;;;N;;;;;
+4DB5;<CJK Ideograph Extension A, Last>;Lo;0;L;;;;;N;;;;;
+4DC0;HEXAGRAM FOR THE CREATIVE HEAVEN;So;0;ON;;;;;N;;;;;
+4DC1;HEXAGRAM FOR THE RECEPTIVE EARTH;So;0;ON;;;;;N;;;;;
+4DC2;HEXAGRAM FOR DIFFICULTY AT THE BEGINNING;So;0;ON;;;;;N;;;;;
+4DC3;HEXAGRAM FOR YOUTHFUL FOLLY;So;0;ON;;;;;N;;;;;
+4DC4;HEXAGRAM FOR WAITING;So;0;ON;;;;;N;;;;;
+4DC5;HEXAGRAM FOR CONFLICT;So;0;ON;;;;;N;;;;;
+4DC6;HEXAGRAM FOR THE ARMY;So;0;ON;;;;;N;;;;;
+4DC7;HEXAGRAM FOR HOLDING TOGETHER;So;0;ON;;;;;N;;;;;
+4DC8;HEXAGRAM FOR SMALL TAMING;So;0;ON;;;;;N;;;;;
+4DC9;HEXAGRAM FOR TREADING;So;0;ON;;;;;N;;;;;
+4DCA;HEXAGRAM FOR PEACE;So;0;ON;;;;;N;;;;;
+4DCB;HEXAGRAM FOR STANDSTILL;So;0;ON;;;;;N;;;;;
+4DCC;HEXAGRAM FOR FELLOWSHIP;So;0;ON;;;;;N;;;;;
+4DCD;HEXAGRAM FOR GREAT POSSESSION;So;0;ON;;;;;N;;;;;
+4DCE;HEXAGRAM FOR MODESTY;So;0;ON;;;;;N;;;;;
+4DCF;HEXAGRAM FOR ENTHUSIASM;So;0;ON;;;;;N;;;;;
+4DD0;HEXAGRAM FOR FOLLOWING;So;0;ON;;;;;N;;;;;
+4DD1;HEXAGRAM FOR WORK ON THE DECAYED;So;0;ON;;;;;N;;;;;
+4DD2;HEXAGRAM FOR APPROACH;So;0;ON;;;;;N;;;;;
+4DD3;HEXAGRAM FOR CONTEMPLATION;So;0;ON;;;;;N;;;;;
+4DD4;HEXAGRAM FOR BITING THROUGH;So;0;ON;;;;;N;;;;;
+4DD5;HEXAGRAM FOR GRACE;So;0;ON;;;;;N;;;;;
+4DD6;HEXAGRAM FOR SPLITTING APART;So;0;ON;;;;;N;;;;;
+4DD7;HEXAGRAM FOR RETURN;So;0;ON;;;;;N;;;;;
+4DD8;HEXAGRAM FOR INNOCENCE;So;0;ON;;;;;N;;;;;
+4DD9;HEXAGRAM FOR GREAT TAMING;So;0;ON;;;;;N;;;;;
+4DDA;HEXAGRAM FOR MOUTH CORNERS;So;0;ON;;;;;N;;;;;
+4DDB;HEXAGRAM FOR GREAT PREPONDERANCE;So;0;ON;;;;;N;;;;;
+4DDC;HEXAGRAM FOR THE ABYSMAL WATER;So;0;ON;;;;;N;;;;;
+4DDD;HEXAGRAM FOR THE CLINGING FIRE;So;0;ON;;;;;N;;;;;
+4DDE;HEXAGRAM FOR INFLUENCE;So;0;ON;;;;;N;;;;;
+4DDF;HEXAGRAM FOR DURATION;So;0;ON;;;;;N;;;;;
+4DE0;HEXAGRAM FOR RETREAT;So;0;ON;;;;;N;;;;;
+4DE1;HEXAGRAM FOR GREAT POWER;So;0;ON;;;;;N;;;;;
+4DE2;HEXAGRAM FOR PROGRESS;So;0;ON;;;;;N;;;;;
+4DE3;HEXAGRAM FOR DARKENING OF THE LIGHT;So;0;ON;;;;;N;;;;;
+4DE4;HEXAGRAM FOR THE FAMILY;So;0;ON;;;;;N;;;;;
+4DE5;HEXAGRAM FOR OPPOSITION;So;0;ON;;;;;N;;;;;
+4DE6;HEXAGRAM FOR OBSTRUCTION;So;0;ON;;;;;N;;;;;
+4DE7;HEXAGRAM FOR DELIVERANCE;So;0;ON;;;;;N;;;;;
+4DE8;HEXAGRAM FOR DECREASE;So;0;ON;;;;;N;;;;;
+4DE9;HEXAGRAM FOR INCREASE;So;0;ON;;;;;N;;;;;
+4DEA;HEXAGRAM FOR BREAKTHROUGH;So;0;ON;;;;;N;;;;;
+4DEB;HEXAGRAM FOR COMING TO MEET;So;0;ON;;;;;N;;;;;
+4DEC;HEXAGRAM FOR GATHERING TOGETHER;So;0;ON;;;;;N;;;;;
+4DED;HEXAGRAM FOR PUSHING UPWARD;So;0;ON;;;;;N;;;;;
+4DEE;HEXAGRAM FOR OPPRESSION;So;0;ON;;;;;N;;;;;
+4DEF;HEXAGRAM FOR THE WELL;So;0;ON;;;;;N;;;;;
+4DF0;HEXAGRAM FOR REVOLUTION;So;0;ON;;;;;N;;;;;
+4DF1;HEXAGRAM FOR THE CAULDRON;So;0;ON;;;;;N;;;;;
+4DF2;HEXAGRAM FOR THE AROUSING THUNDER;So;0;ON;;;;;N;;;;;
+4DF3;HEXAGRAM FOR THE KEEPING STILL MOUNTAIN;So;0;ON;;;;;N;;;;;
+4DF4;HEXAGRAM FOR DEVELOPMENT;So;0;ON;;;;;N;;;;;
+4DF5;HEXAGRAM FOR THE MARRYING MAIDEN;So;0;ON;;;;;N;;;;;
+4DF6;HEXAGRAM FOR ABUNDANCE;So;0;ON;;;;;N;;;;;
+4DF7;HEXAGRAM FOR THE WANDERER;So;0;ON;;;;;N;;;;;
+4DF8;HEXAGRAM FOR THE GENTLE WIND;So;0;ON;;;;;N;;;;;
+4DF9;HEXAGRAM FOR THE JOYOUS LAKE;So;0;ON;;;;;N;;;;;
+4DFA;HEXAGRAM FOR DISPERSION;So;0;ON;;;;;N;;;;;
+4DFB;HEXAGRAM FOR LIMITATION;So;0;ON;;;;;N;;;;;
+4DFC;HEXAGRAM FOR INNER TRUTH;So;0;ON;;;;;N;;;;;
+4DFD;HEXAGRAM FOR SMALL PREPONDERANCE;So;0;ON;;;;;N;;;;;
+4DFE;HEXAGRAM FOR AFTER COMPLETION;So;0;ON;;;;;N;;;;;
+4DFF;HEXAGRAM FOR BEFORE COMPLETION;So;0;ON;;;;;N;;;;;
+4E00;<CJK Ideograph, First>;Lo;0;L;;;;;N;;;;;
+9FA5;<CJK Ideograph, Last>;Lo;0;L;;;;;N;;;;;
+A000;YI SYLLABLE IT;Lo;0;L;;;;;N;;;;;
+A001;YI SYLLABLE IX;Lo;0;L;;;;;N;;;;;
+A002;YI SYLLABLE I;Lo;0;L;;;;;N;;;;;
+A003;YI SYLLABLE IP;Lo;0;L;;;;;N;;;;;
+A004;YI SYLLABLE IET;Lo;0;L;;;;;N;;;;;
+A005;YI SYLLABLE IEX;Lo;0;L;;;;;N;;;;;
+A006;YI SYLLABLE IE;Lo;0;L;;;;;N;;;;;
+A007;YI SYLLABLE IEP;Lo;0;L;;;;;N;;;;;
+A008;YI SYLLABLE AT;Lo;0;L;;;;;N;;;;;
+A009;YI SYLLABLE AX;Lo;0;L;;;;;N;;;;;
+A00A;YI SYLLABLE A;Lo;0;L;;;;;N;;;;;
+A00B;YI SYLLABLE AP;Lo;0;L;;;;;N;;;;;
+A00C;YI SYLLABLE UOX;Lo;0;L;;;;;N;;;;;
+A00D;YI SYLLABLE UO;Lo;0;L;;;;;N;;;;;
+A00E;YI SYLLABLE UOP;Lo;0;L;;;;;N;;;;;
+A00F;YI SYLLABLE OT;Lo;0;L;;;;;N;;;;;
+A010;YI SYLLABLE OX;Lo;0;L;;;;;N;;;;;
+A011;YI SYLLABLE O;Lo;0;L;;;;;N;;;;;
+A012;YI SYLLABLE OP;Lo;0;L;;;;;N;;;;;
+A013;YI SYLLABLE EX;Lo;0;L;;;;;N;;;;;
+A014;YI SYLLABLE E;Lo;0;L;;;;;N;;;;;
+A015;YI SYLLABLE WU;Lo;0;L;;;;;N;;;;;
+A016;YI SYLLABLE BIT;Lo;0;L;;;;;N;;;;;
+A017;YI SYLLABLE BIX;Lo;0;L;;;;;N;;;;;
+A018;YI SYLLABLE BI;Lo;0;L;;;;;N;;;;;
+A019;YI SYLLABLE BIP;Lo;0;L;;;;;N;;;;;
+A01A;YI SYLLABLE BIET;Lo;0;L;;;;;N;;;;;
+A01B;YI SYLLABLE BIEX;Lo;0;L;;;;;N;;;;;
+A01C;YI SYLLABLE BIE;Lo;0;L;;;;;N;;;;;
+A01D;YI SYLLABLE BIEP;Lo;0;L;;;;;N;;;;;
+A01E;YI SYLLABLE BAT;Lo;0;L;;;;;N;;;;;
+A01F;YI SYLLABLE BAX;Lo;0;L;;;;;N;;;;;
+A020;YI SYLLABLE BA;Lo;0;L;;;;;N;;;;;
+A021;YI SYLLABLE BAP;Lo;0;L;;;;;N;;;;;
+A022;YI SYLLABLE BUOX;Lo;0;L;;;;;N;;;;;
+A023;YI SYLLABLE BUO;Lo;0;L;;;;;N;;;;;
+A024;YI SYLLABLE BUOP;Lo;0;L;;;;;N;;;;;
+A025;YI SYLLABLE BOT;Lo;0;L;;;;;N;;;;;
+A026;YI SYLLABLE BOX;Lo;0;L;;;;;N;;;;;
+A027;YI SYLLABLE BO;Lo;0;L;;;;;N;;;;;
+A028;YI SYLLABLE BOP;Lo;0;L;;;;;N;;;;;
+A029;YI SYLLABLE BEX;Lo;0;L;;;;;N;;;;;
+A02A;YI SYLLABLE BE;Lo;0;L;;;;;N;;;;;
+A02B;YI SYLLABLE BEP;Lo;0;L;;;;;N;;;;;
+A02C;YI SYLLABLE BUT;Lo;0;L;;;;;N;;;;;
+A02D;YI SYLLABLE BUX;Lo;0;L;;;;;N;;;;;
+A02E;YI SYLLABLE BU;Lo;0;L;;;;;N;;;;;
+A02F;YI SYLLABLE BUP;Lo;0;L;;;;;N;;;;;
+A030;YI SYLLABLE BURX;Lo;0;L;;;;;N;;;;;
+A031;YI SYLLABLE BUR;Lo;0;L;;;;;N;;;;;
+A032;YI SYLLABLE BYT;Lo;0;L;;;;;N;;;;;
+A033;YI SYLLABLE BYX;Lo;0;L;;;;;N;;;;;
+A034;YI SYLLABLE BY;Lo;0;L;;;;;N;;;;;
+A035;YI SYLLABLE BYP;Lo;0;L;;;;;N;;;;;
+A036;YI SYLLABLE BYRX;Lo;0;L;;;;;N;;;;;
+A037;YI SYLLABLE BYR;Lo;0;L;;;;;N;;;;;
+A038;YI SYLLABLE PIT;Lo;0;L;;;;;N;;;;;
+A039;YI SYLLABLE PIX;Lo;0;L;;;;;N;;;;;
+A03A;YI SYLLABLE PI;Lo;0;L;;;;;N;;;;;
+A03B;YI SYLLABLE PIP;Lo;0;L;;;;;N;;;;;
+A03C;YI SYLLABLE PIEX;Lo;0;L;;;;;N;;;;;
+A03D;YI SYLLABLE PIE;Lo;0;L;;;;;N;;;;;
+A03E;YI SYLLABLE PIEP;Lo;0;L;;;;;N;;;;;
+A03F;YI SYLLABLE PAT;Lo;0;L;;;;;N;;;;;
+A040;YI SYLLABLE PAX;Lo;0;L;;;;;N;;;;;
+A041;YI SYLLABLE PA;Lo;0;L;;;;;N;;;;;
+A042;YI SYLLABLE PAP;Lo;0;L;;;;;N;;;;;
+A043;YI SYLLABLE PUOX;Lo;0;L;;;;;N;;;;;
+A044;YI SYLLABLE PUO;Lo;0;L;;;;;N;;;;;
+A045;YI SYLLABLE PUOP;Lo;0;L;;;;;N;;;;;
+A046;YI SYLLABLE POT;Lo;0;L;;;;;N;;;;;
+A047;YI SYLLABLE POX;Lo;0;L;;;;;N;;;;;
+A048;YI SYLLABLE PO;Lo;0;L;;;;;N;;;;;
+A049;YI SYLLABLE POP;Lo;0;L;;;;;N;;;;;
+A04A;YI SYLLABLE PUT;Lo;0;L;;;;;N;;;;;
+A04B;YI SYLLABLE PUX;Lo;0;L;;;;;N;;;;;
+A04C;YI SYLLABLE PU;Lo;0;L;;;;;N;;;;;
+A04D;YI SYLLABLE PUP;Lo;0;L;;;;;N;;;;;
+A04E;YI SYLLABLE PURX;Lo;0;L;;;;;N;;;;;
+A04F;YI SYLLABLE PUR;Lo;0;L;;;;;N;;;;;
+A050;YI SYLLABLE PYT;Lo;0;L;;;;;N;;;;;
+A051;YI SYLLABLE PYX;Lo;0;L;;;;;N;;;;;
+A052;YI SYLLABLE PY;Lo;0;L;;;;;N;;;;;
+A053;YI SYLLABLE PYP;Lo;0;L;;;;;N;;;;;
+A054;YI SYLLABLE PYRX;Lo;0;L;;;;;N;;;;;
+A055;YI SYLLABLE PYR;Lo;0;L;;;;;N;;;;;
+A056;YI SYLLABLE BBIT;Lo;0;L;;;;;N;;;;;
+A057;YI SYLLABLE BBIX;Lo;0;L;;;;;N;;;;;
+A058;YI SYLLABLE BBI;Lo;0;L;;;;;N;;;;;
+A059;YI SYLLABLE BBIP;Lo;0;L;;;;;N;;;;;
+A05A;YI SYLLABLE BBIET;Lo;0;L;;;;;N;;;;;
+A05B;YI SYLLABLE BBIEX;Lo;0;L;;;;;N;;;;;
+A05C;YI SYLLABLE BBIE;Lo;0;L;;;;;N;;;;;
+A05D;YI SYLLABLE BBIEP;Lo;0;L;;;;;N;;;;;
+A05E;YI SYLLABLE BBAT;Lo;0;L;;;;;N;;;;;
+A05F;YI SYLLABLE BBAX;Lo;0;L;;;;;N;;;;;
+A060;YI SYLLABLE BBA;Lo;0;L;;;;;N;;;;;
+A061;YI SYLLABLE BBAP;Lo;0;L;;;;;N;;;;;
+A062;YI SYLLABLE BBUOX;Lo;0;L;;;;;N;;;;;
+A063;YI SYLLABLE BBUO;Lo;0;L;;;;;N;;;;;
+A064;YI SYLLABLE BBUOP;Lo;0;L;;;;;N;;;;;
+A065;YI SYLLABLE BBOT;Lo;0;L;;;;;N;;;;;
+A066;YI SYLLABLE BBOX;Lo;0;L;;;;;N;;;;;
+A067;YI SYLLABLE BBO;Lo;0;L;;;;;N;;;;;
+A068;YI SYLLABLE BBOP;Lo;0;L;;;;;N;;;;;
+A069;YI SYLLABLE BBEX;Lo;0;L;;;;;N;;;;;
+A06A;YI SYLLABLE BBE;Lo;0;L;;;;;N;;;;;
+A06B;YI SYLLABLE BBEP;Lo;0;L;;;;;N;;;;;
+A06C;YI SYLLABLE BBUT;Lo;0;L;;;;;N;;;;;
+A06D;YI SYLLABLE BBUX;Lo;0;L;;;;;N;;;;;
+A06E;YI SYLLABLE BBU;Lo;0;L;;;;;N;;;;;
+A06F;YI SYLLABLE BBUP;Lo;0;L;;;;;N;;;;;
+A070;YI SYLLABLE BBURX;Lo;0;L;;;;;N;;;;;
+A071;YI SYLLABLE BBUR;Lo;0;L;;;;;N;;;;;
+A072;YI SYLLABLE BBYT;Lo;0;L;;;;;N;;;;;
+A073;YI SYLLABLE BBYX;Lo;0;L;;;;;N;;;;;
+A074;YI SYLLABLE BBY;Lo;0;L;;;;;N;;;;;
+A075;YI SYLLABLE BBYP;Lo;0;L;;;;;N;;;;;
+A076;YI SYLLABLE NBIT;Lo;0;L;;;;;N;;;;;
+A077;YI SYLLABLE NBIX;Lo;0;L;;;;;N;;;;;
+A078;YI SYLLABLE NBI;Lo;0;L;;;;;N;;;;;
+A079;YI SYLLABLE NBIP;Lo;0;L;;;;;N;;;;;
+A07A;YI SYLLABLE NBIEX;Lo;0;L;;;;;N;;;;;
+A07B;YI SYLLABLE NBIE;Lo;0;L;;;;;N;;;;;
+A07C;YI SYLLABLE NBIEP;Lo;0;L;;;;;N;;;;;
+A07D;YI SYLLABLE NBAT;Lo;0;L;;;;;N;;;;;
+A07E;YI SYLLABLE NBAX;Lo;0;L;;;;;N;;;;;
+A07F;YI SYLLABLE NBA;Lo;0;L;;;;;N;;;;;
+A080;YI SYLLABLE NBAP;Lo;0;L;;;;;N;;;;;
+A081;YI SYLLABLE NBOT;Lo;0;L;;;;;N;;;;;
+A082;YI SYLLABLE NBOX;Lo;0;L;;;;;N;;;;;
+A083;YI SYLLABLE NBO;Lo;0;L;;;;;N;;;;;
+A084;YI SYLLABLE NBOP;Lo;0;L;;;;;N;;;;;
+A085;YI SYLLABLE NBUT;Lo;0;L;;;;;N;;;;;
+A086;YI SYLLABLE NBUX;Lo;0;L;;;;;N;;;;;
+A087;YI SYLLABLE NBU;Lo;0;L;;;;;N;;;;;
+A088;YI SYLLABLE NBUP;Lo;0;L;;;;;N;;;;;
+A089;YI SYLLABLE NBURX;Lo;0;L;;;;;N;;;;;
+A08A;YI SYLLABLE NBUR;Lo;0;L;;;;;N;;;;;
+A08B;YI SYLLABLE NBYT;Lo;0;L;;;;;N;;;;;
+A08C;YI SYLLABLE NBYX;Lo;0;L;;;;;N;;;;;
+A08D;YI SYLLABLE NBY;Lo;0;L;;;;;N;;;;;
+A08E;YI SYLLABLE NBYP;Lo;0;L;;;;;N;;;;;
+A08F;YI SYLLABLE NBYRX;Lo;0;L;;;;;N;;;;;
+A090;YI SYLLABLE NBYR;Lo;0;L;;;;;N;;;;;
+A091;YI SYLLABLE HMIT;Lo;0;L;;;;;N;;;;;
+A092;YI SYLLABLE HMIX;Lo;0;L;;;;;N;;;;;
+A093;YI SYLLABLE HMI;Lo;0;L;;;;;N;;;;;
+A094;YI SYLLABLE HMIP;Lo;0;L;;;;;N;;;;;
+A095;YI SYLLABLE HMIEX;Lo;0;L;;;;;N;;;;;
+A096;YI SYLLABLE HMIE;Lo;0;L;;;;;N;;;;;
+A097;YI SYLLABLE HMIEP;Lo;0;L;;;;;N;;;;;
+A098;YI SYLLABLE HMAT;Lo;0;L;;;;;N;;;;;
+A099;YI SYLLABLE HMAX;Lo;0;L;;;;;N;;;;;
+A09A;YI SYLLABLE HMA;Lo;0;L;;;;;N;;;;;
+A09B;YI SYLLABLE HMAP;Lo;0;L;;;;;N;;;;;
+A09C;YI SYLLABLE HMUOX;Lo;0;L;;;;;N;;;;;
+A09D;YI SYLLABLE HMUO;Lo;0;L;;;;;N;;;;;
+A09E;YI SYLLABLE HMUOP;Lo;0;L;;;;;N;;;;;
+A09F;YI SYLLABLE HMOT;Lo;0;L;;;;;N;;;;;
+A0A0;YI SYLLABLE HMOX;Lo;0;L;;;;;N;;;;;
+A0A1;YI SYLLABLE HMO;Lo;0;L;;;;;N;;;;;
+A0A2;YI SYLLABLE HMOP;Lo;0;L;;;;;N;;;;;
+A0A3;YI SYLLABLE HMUT;Lo;0;L;;;;;N;;;;;
+A0A4;YI SYLLABLE HMUX;Lo;0;L;;;;;N;;;;;
+A0A5;YI SYLLABLE HMU;Lo;0;L;;;;;N;;;;;
+A0A6;YI SYLLABLE HMUP;Lo;0;L;;;;;N;;;;;
+A0A7;YI SYLLABLE HMURX;Lo;0;L;;;;;N;;;;;
+A0A8;YI SYLLABLE HMUR;Lo;0;L;;;;;N;;;;;
+A0A9;YI SYLLABLE HMYX;Lo;0;L;;;;;N;;;;;
+A0AA;YI SYLLABLE HMY;Lo;0;L;;;;;N;;;;;
+A0AB;YI SYLLABLE HMYP;Lo;0;L;;;;;N;;;;;
+A0AC;YI SYLLABLE HMYRX;Lo;0;L;;;;;N;;;;;
+A0AD;YI SYLLABLE HMYR;Lo;0;L;;;;;N;;;;;
+A0AE;YI SYLLABLE MIT;Lo;0;L;;;;;N;;;;;
+A0AF;YI SYLLABLE MIX;Lo;0;L;;;;;N;;;;;
+A0B0;YI SYLLABLE MI;Lo;0;L;;;;;N;;;;;
+A0B1;YI SYLLABLE MIP;Lo;0;L;;;;;N;;;;;
+A0B2;YI SYLLABLE MIEX;Lo;0;L;;;;;N;;;;;
+A0B3;YI SYLLABLE MIE;Lo;0;L;;;;;N;;;;;
+A0B4;YI SYLLABLE MIEP;Lo;0;L;;;;;N;;;;;
+A0B5;YI SYLLABLE MAT;Lo;0;L;;;;;N;;;;;
+A0B6;YI SYLLABLE MAX;Lo;0;L;;;;;N;;;;;
+A0B7;YI SYLLABLE MA;Lo;0;L;;;;;N;;;;;
+A0B8;YI SYLLABLE MAP;Lo;0;L;;;;;N;;;;;
+A0B9;YI SYLLABLE MUOT;Lo;0;L;;;;;N;;;;;
+A0BA;YI SYLLABLE MUOX;Lo;0;L;;;;;N;;;;;
+A0BB;YI SYLLABLE MUO;Lo;0;L;;;;;N;;;;;
+A0BC;YI SYLLABLE MUOP;Lo;0;L;;;;;N;;;;;
+A0BD;YI SYLLABLE MOT;Lo;0;L;;;;;N;;;;;
+A0BE;YI SYLLABLE MOX;Lo;0;L;;;;;N;;;;;
+A0BF;YI SYLLABLE MO;Lo;0;L;;;;;N;;;;;
+A0C0;YI SYLLABLE MOP;Lo;0;L;;;;;N;;;;;
+A0C1;YI SYLLABLE MEX;Lo;0;L;;;;;N;;;;;
+A0C2;YI SYLLABLE ME;Lo;0;L;;;;;N;;;;;
+A0C3;YI SYLLABLE MUT;Lo;0;L;;;;;N;;;;;
+A0C4;YI SYLLABLE MUX;Lo;0;L;;;;;N;;;;;
+A0C5;YI SYLLABLE MU;Lo;0;L;;;;;N;;;;;
+A0C6;YI SYLLABLE MUP;Lo;0;L;;;;;N;;;;;
+A0C7;YI SYLLABLE MURX;Lo;0;L;;;;;N;;;;;
+A0C8;YI SYLLABLE MUR;Lo;0;L;;;;;N;;;;;
+A0C9;YI SYLLABLE MYT;Lo;0;L;;;;;N;;;;;
+A0CA;YI SYLLABLE MYX;Lo;0;L;;;;;N;;;;;
+A0CB;YI SYLLABLE MY;Lo;0;L;;;;;N;;;;;
+A0CC;YI SYLLABLE MYP;Lo;0;L;;;;;N;;;;;
+A0CD;YI SYLLABLE FIT;Lo;0;L;;;;;N;;;;;
+A0CE;YI SYLLABLE FIX;Lo;0;L;;;;;N;;;;;
+A0CF;YI SYLLABLE FI;Lo;0;L;;;;;N;;;;;
+A0D0;YI SYLLABLE FIP;Lo;0;L;;;;;N;;;;;
+A0D1;YI SYLLABLE FAT;Lo;0;L;;;;;N;;;;;
+A0D2;YI SYLLABLE FAX;Lo;0;L;;;;;N;;;;;
+A0D3;YI SYLLABLE FA;Lo;0;L;;;;;N;;;;;
+A0D4;YI SYLLABLE FAP;Lo;0;L;;;;;N;;;;;
+A0D5;YI SYLLABLE FOX;Lo;0;L;;;;;N;;;;;
+A0D6;YI SYLLABLE FO;Lo;0;L;;;;;N;;;;;
+A0D7;YI SYLLABLE FOP;Lo;0;L;;;;;N;;;;;
+A0D8;YI SYLLABLE FUT;Lo;0;L;;;;;N;;;;;
+A0D9;YI SYLLABLE FUX;Lo;0;L;;;;;N;;;;;
+A0DA;YI SYLLABLE FU;Lo;0;L;;;;;N;;;;;
+A0DB;YI SYLLABLE FUP;Lo;0;L;;;;;N;;;;;
+A0DC;YI SYLLABLE FURX;Lo;0;L;;;;;N;;;;;
+A0DD;YI SYLLABLE FUR;Lo;0;L;;;;;N;;;;;
+A0DE;YI SYLLABLE FYT;Lo;0;L;;;;;N;;;;;
+A0DF;YI SYLLABLE FYX;Lo;0;L;;;;;N;;;;;
+A0E0;YI SYLLABLE FY;Lo;0;L;;;;;N;;;;;
+A0E1;YI SYLLABLE FYP;Lo;0;L;;;;;N;;;;;
+A0E2;YI SYLLABLE VIT;Lo;0;L;;;;;N;;;;;
+A0E3;YI SYLLABLE VIX;Lo;0;L;;;;;N;;;;;
+A0E4;YI SYLLABLE VI;Lo;0;L;;;;;N;;;;;
+A0E5;YI SYLLABLE VIP;Lo;0;L;;;;;N;;;;;
+A0E6;YI SYLLABLE VIET;Lo;0;L;;;;;N;;;;;
+A0E7;YI SYLLABLE VIEX;Lo;0;L;;;;;N;;;;;
+A0E8;YI SYLLABLE VIE;Lo;0;L;;;;;N;;;;;
+A0E9;YI SYLLABLE VIEP;Lo;0;L;;;;;N;;;;;
+A0EA;YI SYLLABLE VAT;Lo;0;L;;;;;N;;;;;
+A0EB;YI SYLLABLE VAX;Lo;0;L;;;;;N;;;;;
+A0EC;YI SYLLABLE VA;Lo;0;L;;;;;N;;;;;
+A0ED;YI SYLLABLE VAP;Lo;0;L;;;;;N;;;;;
+A0EE;YI SYLLABLE VOT;Lo;0;L;;;;;N;;;;;
+A0EF;YI SYLLABLE VOX;Lo;0;L;;;;;N;;;;;
+A0F0;YI SYLLABLE VO;Lo;0;L;;;;;N;;;;;
+A0F1;YI SYLLABLE VOP;Lo;0;L;;;;;N;;;;;
+A0F2;YI SYLLABLE VEX;Lo;0;L;;;;;N;;;;;
+A0F3;YI SYLLABLE VEP;Lo;0;L;;;;;N;;;;;
+A0F4;YI SYLLABLE VUT;Lo;0;L;;;;;N;;;;;
+A0F5;YI SYLLABLE VUX;Lo;0;L;;;;;N;;;;;
+A0F6;YI SYLLABLE VU;Lo;0;L;;;;;N;;;;;
+A0F7;YI SYLLABLE VUP;Lo;0;L;;;;;N;;;;;
+A0F8;YI SYLLABLE VURX;Lo;0;L;;;;;N;;;;;
+A0F9;YI SYLLABLE VUR;Lo;0;L;;;;;N;;;;;
+A0FA;YI SYLLABLE VYT;Lo;0;L;;;;;N;;;;;
+A0FB;YI SYLLABLE VYX;Lo;0;L;;;;;N;;;;;
+A0FC;YI SYLLABLE VY;Lo;0;L;;;;;N;;;;;
+A0FD;YI SYLLABLE VYP;Lo;0;L;;;;;N;;;;;
+A0FE;YI SYLLABLE VYRX;Lo;0;L;;;;;N;;;;;
+A0FF;YI SYLLABLE VYR;Lo;0;L;;;;;N;;;;;
+A100;YI SYLLABLE DIT;Lo;0;L;;;;;N;;;;;
+A101;YI SYLLABLE DIX;Lo;0;L;;;;;N;;;;;
+A102;YI SYLLABLE DI;Lo;0;L;;;;;N;;;;;
+A103;YI SYLLABLE DIP;Lo;0;L;;;;;N;;;;;
+A104;YI SYLLABLE DIEX;Lo;0;L;;;;;N;;;;;
+A105;YI SYLLABLE DIE;Lo;0;L;;;;;N;;;;;
+A106;YI SYLLABLE DIEP;Lo;0;L;;;;;N;;;;;
+A107;YI SYLLABLE DAT;Lo;0;L;;;;;N;;;;;
+A108;YI SYLLABLE DAX;Lo;0;L;;;;;N;;;;;
+A109;YI SYLLABLE DA;Lo;0;L;;;;;N;;;;;
+A10A;YI SYLLABLE DAP;Lo;0;L;;;;;N;;;;;
+A10B;YI SYLLABLE DUOX;Lo;0;L;;;;;N;;;;;
+A10C;YI SYLLABLE DUO;Lo;0;L;;;;;N;;;;;
+A10D;YI SYLLABLE DOT;Lo;0;L;;;;;N;;;;;
+A10E;YI SYLLABLE DOX;Lo;0;L;;;;;N;;;;;
+A10F;YI SYLLABLE DO;Lo;0;L;;;;;N;;;;;
+A110;YI SYLLABLE DOP;Lo;0;L;;;;;N;;;;;
+A111;YI SYLLABLE DEX;Lo;0;L;;;;;N;;;;;
+A112;YI SYLLABLE DE;Lo;0;L;;;;;N;;;;;
+A113;YI SYLLABLE DEP;Lo;0;L;;;;;N;;;;;
+A114;YI SYLLABLE DUT;Lo;0;L;;;;;N;;;;;
+A115;YI SYLLABLE DUX;Lo;0;L;;;;;N;;;;;
+A116;YI SYLLABLE DU;Lo;0;L;;;;;N;;;;;
+A117;YI SYLLABLE DUP;Lo;0;L;;;;;N;;;;;
+A118;YI SYLLABLE DURX;Lo;0;L;;;;;N;;;;;
+A119;YI SYLLABLE DUR;Lo;0;L;;;;;N;;;;;
+A11A;YI SYLLABLE TIT;Lo;0;L;;;;;N;;;;;
+A11B;YI SYLLABLE TIX;Lo;0;L;;;;;N;;;;;
+A11C;YI SYLLABLE TI;Lo;0;L;;;;;N;;;;;
+A11D;YI SYLLABLE TIP;Lo;0;L;;;;;N;;;;;
+A11E;YI SYLLABLE TIEX;Lo;0;L;;;;;N;;;;;
+A11F;YI SYLLABLE TIE;Lo;0;L;;;;;N;;;;;
+A120;YI SYLLABLE TIEP;Lo;0;L;;;;;N;;;;;
+A121;YI SYLLABLE TAT;Lo;0;L;;;;;N;;;;;
+A122;YI SYLLABLE TAX;Lo;0;L;;;;;N;;;;;
+A123;YI SYLLABLE TA;Lo;0;L;;;;;N;;;;;
+A124;YI SYLLABLE TAP;Lo;0;L;;;;;N;;;;;
+A125;YI SYLLABLE TUOT;Lo;0;L;;;;;N;;;;;
+A126;YI SYLLABLE TUOX;Lo;0;L;;;;;N;;;;;
+A127;YI SYLLABLE TUO;Lo;0;L;;;;;N;;;;;
+A128;YI SYLLABLE TUOP;Lo;0;L;;;;;N;;;;;
+A129;YI SYLLABLE TOT;Lo;0;L;;;;;N;;;;;
+A12A;YI SYLLABLE TOX;Lo;0;L;;;;;N;;;;;
+A12B;YI SYLLABLE TO;Lo;0;L;;;;;N;;;;;
+A12C;YI SYLLABLE TOP;Lo;0;L;;;;;N;;;;;
+A12D;YI SYLLABLE TEX;Lo;0;L;;;;;N;;;;;
+A12E;YI SYLLABLE TE;Lo;0;L;;;;;N;;;;;
+A12F;YI SYLLABLE TEP;Lo;0;L;;;;;N;;;;;
+A130;YI SYLLABLE TUT;Lo;0;L;;;;;N;;;;;
+A131;YI SYLLABLE TUX;Lo;0;L;;;;;N;;;;;
+A132;YI SYLLABLE TU;Lo;0;L;;;;;N;;;;;
+A133;YI SYLLABLE TUP;Lo;0;L;;;;;N;;;;;
+A134;YI SYLLABLE TURX;Lo;0;L;;;;;N;;;;;
+A135;YI SYLLABLE TUR;Lo;0;L;;;;;N;;;;;
+A136;YI SYLLABLE DDIT;Lo;0;L;;;;;N;;;;;
+A137;YI SYLLABLE DDIX;Lo;0;L;;;;;N;;;;;
+A138;YI SYLLABLE DDI;Lo;0;L;;;;;N;;;;;
+A139;YI SYLLABLE DDIP;Lo;0;L;;;;;N;;;;;
+A13A;YI SYLLABLE DDIEX;Lo;0;L;;;;;N;;;;;
+A13B;YI SYLLABLE DDIE;Lo;0;L;;;;;N;;;;;
+A13C;YI SYLLABLE DDIEP;Lo;0;L;;;;;N;;;;;
+A13D;YI SYLLABLE DDAT;Lo;0;L;;;;;N;;;;;
+A13E;YI SYLLABLE DDAX;Lo;0;L;;;;;N;;;;;
+A13F;YI SYLLABLE DDA;Lo;0;L;;;;;N;;;;;
+A140;YI SYLLABLE DDAP;Lo;0;L;;;;;N;;;;;
+A141;YI SYLLABLE DDUOX;Lo;0;L;;;;;N;;;;;
+A142;YI SYLLABLE DDUO;Lo;0;L;;;;;N;;;;;
+A143;YI SYLLABLE DDUOP;Lo;0;L;;;;;N;;;;;
+A144;YI SYLLABLE DDOT;Lo;0;L;;;;;N;;;;;
+A145;YI SYLLABLE DDOX;Lo;0;L;;;;;N;;;;;
+A146;YI SYLLABLE DDO;Lo;0;L;;;;;N;;;;;
+A147;YI SYLLABLE DDOP;Lo;0;L;;;;;N;;;;;
+A148;YI SYLLABLE DDEX;Lo;0;L;;;;;N;;;;;
+A149;YI SYLLABLE DDE;Lo;0;L;;;;;N;;;;;
+A14A;YI SYLLABLE DDEP;Lo;0;L;;;;;N;;;;;
+A14B;YI SYLLABLE DDUT;Lo;0;L;;;;;N;;;;;
+A14C;YI SYLLABLE DDUX;Lo;0;L;;;;;N;;;;;
+A14D;YI SYLLABLE DDU;Lo;0;L;;;;;N;;;;;
+A14E;YI SYLLABLE DDUP;Lo;0;L;;;;;N;;;;;
+A14F;YI SYLLABLE DDURX;Lo;0;L;;;;;N;;;;;
+A150;YI SYLLABLE DDUR;Lo;0;L;;;;;N;;;;;
+A151;YI SYLLABLE NDIT;Lo;0;L;;;;;N;;;;;
+A152;YI SYLLABLE NDIX;Lo;0;L;;;;;N;;;;;
+A153;YI SYLLABLE NDI;Lo;0;L;;;;;N;;;;;
+A154;YI SYLLABLE NDIP;Lo;0;L;;;;;N;;;;;
+A155;YI SYLLABLE NDIEX;Lo;0;L;;;;;N;;;;;
+A156;YI SYLLABLE NDIE;Lo;0;L;;;;;N;;;;;
+A157;YI SYLLABLE NDAT;Lo;0;L;;;;;N;;;;;
+A158;YI SYLLABLE NDAX;Lo;0;L;;;;;N;;;;;
+A159;YI SYLLABLE NDA;Lo;0;L;;;;;N;;;;;
+A15A;YI SYLLABLE NDAP;Lo;0;L;;;;;N;;;;;
+A15B;YI SYLLABLE NDOT;Lo;0;L;;;;;N;;;;;
+A15C;YI SYLLABLE NDOX;Lo;0;L;;;;;N;;;;;
+A15D;YI SYLLABLE NDO;Lo;0;L;;;;;N;;;;;
+A15E;YI SYLLABLE NDOP;Lo;0;L;;;;;N;;;;;
+A15F;YI SYLLABLE NDEX;Lo;0;L;;;;;N;;;;;
+A160;YI SYLLABLE NDE;Lo;0;L;;;;;N;;;;;
+A161;YI SYLLABLE NDEP;Lo;0;L;;;;;N;;;;;
+A162;YI SYLLABLE NDUT;Lo;0;L;;;;;N;;;;;
+A163;YI SYLLABLE NDUX;Lo;0;L;;;;;N;;;;;
+A164;YI SYLLABLE NDU;Lo;0;L;;;;;N;;;;;
+A165;YI SYLLABLE NDUP;Lo;0;L;;;;;N;;;;;
+A166;YI SYLLABLE NDURX;Lo;0;L;;;;;N;;;;;
+A167;YI SYLLABLE NDUR;Lo;0;L;;;;;N;;;;;
+A168;YI SYLLABLE HNIT;Lo;0;L;;;;;N;;;;;
+A169;YI SYLLABLE HNIX;Lo;0;L;;;;;N;;;;;
+A16A;YI SYLLABLE HNI;Lo;0;L;;;;;N;;;;;
+A16B;YI SYLLABLE HNIP;Lo;0;L;;;;;N;;;;;
+A16C;YI SYLLABLE HNIET;Lo;0;L;;;;;N;;;;;
+A16D;YI SYLLABLE HNIEX;Lo;0;L;;;;;N;;;;;
+A16E;YI SYLLABLE HNIE;Lo;0;L;;;;;N;;;;;
+A16F;YI SYLLABLE HNIEP;Lo;0;L;;;;;N;;;;;
+A170;YI SYLLABLE HNAT;Lo;0;L;;;;;N;;;;;
+A171;YI SYLLABLE HNAX;Lo;0;L;;;;;N;;;;;
+A172;YI SYLLABLE HNA;Lo;0;L;;;;;N;;;;;
+A173;YI SYLLABLE HNAP;Lo;0;L;;;;;N;;;;;
+A174;YI SYLLABLE HNUOX;Lo;0;L;;;;;N;;;;;
+A175;YI SYLLABLE HNUO;Lo;0;L;;;;;N;;;;;
+A176;YI SYLLABLE HNOT;Lo;0;L;;;;;N;;;;;
+A177;YI SYLLABLE HNOX;Lo;0;L;;;;;N;;;;;
+A178;YI SYLLABLE HNOP;Lo;0;L;;;;;N;;;;;
+A179;YI SYLLABLE HNEX;Lo;0;L;;;;;N;;;;;
+A17A;YI SYLLABLE HNE;Lo;0;L;;;;;N;;;;;
+A17B;YI SYLLABLE HNEP;Lo;0;L;;;;;N;;;;;
+A17C;YI SYLLABLE HNUT;Lo;0;L;;;;;N;;;;;
+A17D;YI SYLLABLE NIT;Lo;0;L;;;;;N;;;;;
+A17E;YI SYLLABLE NIX;Lo;0;L;;;;;N;;;;;
+A17F;YI SYLLABLE NI;Lo;0;L;;;;;N;;;;;
+A180;YI SYLLABLE NIP;Lo;0;L;;;;;N;;;;;
+A181;YI SYLLABLE NIEX;Lo;0;L;;;;;N;;;;;
+A182;YI SYLLABLE NIE;Lo;0;L;;;;;N;;;;;
+A183;YI SYLLABLE NIEP;Lo;0;L;;;;;N;;;;;
+A184;YI SYLLABLE NAX;Lo;0;L;;;;;N;;;;;
+A185;YI SYLLABLE NA;Lo;0;L;;;;;N;;;;;
+A186;YI SYLLABLE NAP;Lo;0;L;;;;;N;;;;;
+A187;YI SYLLABLE NUOX;Lo;0;L;;;;;N;;;;;
+A188;YI SYLLABLE NUO;Lo;0;L;;;;;N;;;;;
+A189;YI SYLLABLE NUOP;Lo;0;L;;;;;N;;;;;
+A18A;YI SYLLABLE NOT;Lo;0;L;;;;;N;;;;;
+A18B;YI SYLLABLE NOX;Lo;0;L;;;;;N;;;;;
+A18C;YI SYLLABLE NO;Lo;0;L;;;;;N;;;;;
+A18D;YI SYLLABLE NOP;Lo;0;L;;;;;N;;;;;
+A18E;YI SYLLABLE NEX;Lo;0;L;;;;;N;;;;;
+A18F;YI SYLLABLE NE;Lo;0;L;;;;;N;;;;;
+A190;YI SYLLABLE NEP;Lo;0;L;;;;;N;;;;;
+A191;YI SYLLABLE NUT;Lo;0;L;;;;;N;;;;;
+A192;YI SYLLABLE NUX;Lo;0;L;;;;;N;;;;;
+A193;YI SYLLABLE NU;Lo;0;L;;;;;N;;;;;
+A194;YI SYLLABLE NUP;Lo;0;L;;;;;N;;;;;
+A195;YI SYLLABLE NURX;Lo;0;L;;;;;N;;;;;
+A196;YI SYLLABLE NUR;Lo;0;L;;;;;N;;;;;
+A197;YI SYLLABLE HLIT;Lo;0;L;;;;;N;;;;;
+A198;YI SYLLABLE HLIX;Lo;0;L;;;;;N;;;;;
+A199;YI SYLLABLE HLI;Lo;0;L;;;;;N;;;;;
+A19A;YI SYLLABLE HLIP;Lo;0;L;;;;;N;;;;;
+A19B;YI SYLLABLE HLIEX;Lo;0;L;;;;;N;;;;;
+A19C;YI SYLLABLE HLIE;Lo;0;L;;;;;N;;;;;
+A19D;YI SYLLABLE HLIEP;Lo;0;L;;;;;N;;;;;
+A19E;YI SYLLABLE HLAT;Lo;0;L;;;;;N;;;;;
+A19F;YI SYLLABLE HLAX;Lo;0;L;;;;;N;;;;;
+A1A0;YI SYLLABLE HLA;Lo;0;L;;;;;N;;;;;
+A1A1;YI SYLLABLE HLAP;Lo;0;L;;;;;N;;;;;
+A1A2;YI SYLLABLE HLUOX;Lo;0;L;;;;;N;;;;;
+A1A3;YI SYLLABLE HLUO;Lo;0;L;;;;;N;;;;;
+A1A4;YI SYLLABLE HLUOP;Lo;0;L;;;;;N;;;;;
+A1A5;YI SYLLABLE HLOX;Lo;0;L;;;;;N;;;;;
+A1A6;YI SYLLABLE HLO;Lo;0;L;;;;;N;;;;;
+A1A7;YI SYLLABLE HLOP;Lo;0;L;;;;;N;;;;;
+A1A8;YI SYLLABLE HLEX;Lo;0;L;;;;;N;;;;;
+A1A9;YI SYLLABLE HLE;Lo;0;L;;;;;N;;;;;
+A1AA;YI SYLLABLE HLEP;Lo;0;L;;;;;N;;;;;
+A1AB;YI SYLLABLE HLUT;Lo;0;L;;;;;N;;;;;
+A1AC;YI SYLLABLE HLUX;Lo;0;L;;;;;N;;;;;
+A1AD;YI SYLLABLE HLU;Lo;0;L;;;;;N;;;;;
+A1AE;YI SYLLABLE HLUP;Lo;0;L;;;;;N;;;;;
+A1AF;YI SYLLABLE HLURX;Lo;0;L;;;;;N;;;;;
+A1B0;YI SYLLABLE HLUR;Lo;0;L;;;;;N;;;;;
+A1B1;YI SYLLABLE HLYT;Lo;0;L;;;;;N;;;;;
+A1B2;YI SYLLABLE HLYX;Lo;0;L;;;;;N;;;;;
+A1B3;YI SYLLABLE HLY;Lo;0;L;;;;;N;;;;;
+A1B4;YI SYLLABLE HLYP;Lo;0;L;;;;;N;;;;;
+A1B5;YI SYLLABLE HLYRX;Lo;0;L;;;;;N;;;;;
+A1B6;YI SYLLABLE HLYR;Lo;0;L;;;;;N;;;;;
+A1B7;YI SYLLABLE LIT;Lo;0;L;;;;;N;;;;;
+A1B8;YI SYLLABLE LIX;Lo;0;L;;;;;N;;;;;
+A1B9;YI SYLLABLE LI;Lo;0;L;;;;;N;;;;;
+A1BA;YI SYLLABLE LIP;Lo;0;L;;;;;N;;;;;
+A1BB;YI SYLLABLE LIET;Lo;0;L;;;;;N;;;;;
+A1BC;YI SYLLABLE LIEX;Lo;0;L;;;;;N;;;;;
+A1BD;YI SYLLABLE LIE;Lo;0;L;;;;;N;;;;;
+A1BE;YI SYLLABLE LIEP;Lo;0;L;;;;;N;;;;;
+A1BF;YI SYLLABLE LAT;Lo;0;L;;;;;N;;;;;
+A1C0;YI SYLLABLE LAX;Lo;0;L;;;;;N;;;;;
+A1C1;YI SYLLABLE LA;Lo;0;L;;;;;N;;;;;
+A1C2;YI SYLLABLE LAP;Lo;0;L;;;;;N;;;;;
+A1C3;YI SYLLABLE LUOT;Lo;0;L;;;;;N;;;;;
+A1C4;YI SYLLABLE LUOX;Lo;0;L;;;;;N;;;;;
+A1C5;YI SYLLABLE LUO;Lo;0;L;;;;;N;;;;;
+A1C6;YI SYLLABLE LUOP;Lo;0;L;;;;;N;;;;;
+A1C7;YI SYLLABLE LOT;Lo;0;L;;;;;N;;;;;
+A1C8;YI SYLLABLE LOX;Lo;0;L;;;;;N;;;;;
+A1C9;YI SYLLABLE LO;Lo;0;L;;;;;N;;;;;
+A1CA;YI SYLLABLE LOP;Lo;0;L;;;;;N;;;;;
+A1CB;YI SYLLABLE LEX;Lo;0;L;;;;;N;;;;;
+A1CC;YI SYLLABLE LE;Lo;0;L;;;;;N;;;;;
+A1CD;YI SYLLABLE LEP;Lo;0;L;;;;;N;;;;;
+A1CE;YI SYLLABLE LUT;Lo;0;L;;;;;N;;;;;
+A1CF;YI SYLLABLE LUX;Lo;0;L;;;;;N;;;;;
+A1D0;YI SYLLABLE LU;Lo;0;L;;;;;N;;;;;
+A1D1;YI SYLLABLE LUP;Lo;0;L;;;;;N;;;;;
+A1D2;YI SYLLABLE LURX;Lo;0;L;;;;;N;;;;;
+A1D3;YI SYLLABLE LUR;Lo;0;L;;;;;N;;;;;
+A1D4;YI SYLLABLE LYT;Lo;0;L;;;;;N;;;;;
+A1D5;YI SYLLABLE LYX;Lo;0;L;;;;;N;;;;;
+A1D6;YI SYLLABLE LY;Lo;0;L;;;;;N;;;;;
+A1D7;YI SYLLABLE LYP;Lo;0;L;;;;;N;;;;;
+A1D8;YI SYLLABLE LYRX;Lo;0;L;;;;;N;;;;;
+A1D9;YI SYLLABLE LYR;Lo;0;L;;;;;N;;;;;
+A1DA;YI SYLLABLE GIT;Lo;0;L;;;;;N;;;;;
+A1DB;YI SYLLABLE GIX;Lo;0;L;;;;;N;;;;;
+A1DC;YI SYLLABLE GI;Lo;0;L;;;;;N;;;;;
+A1DD;YI SYLLABLE GIP;Lo;0;L;;;;;N;;;;;
+A1DE;YI SYLLABLE GIET;Lo;0;L;;;;;N;;;;;
+A1DF;YI SYLLABLE GIEX;Lo;0;L;;;;;N;;;;;
+A1E0;YI SYLLABLE GIE;Lo;0;L;;;;;N;;;;;
+A1E1;YI SYLLABLE GIEP;Lo;0;L;;;;;N;;;;;
+A1E2;YI SYLLABLE GAT;Lo;0;L;;;;;N;;;;;
+A1E3;YI SYLLABLE GAX;Lo;0;L;;;;;N;;;;;
+A1E4;YI SYLLABLE GA;Lo;0;L;;;;;N;;;;;
+A1E5;YI SYLLABLE GAP;Lo;0;L;;;;;N;;;;;
+A1E6;YI SYLLABLE GUOT;Lo;0;L;;;;;N;;;;;
+A1E7;YI SYLLABLE GUOX;Lo;0;L;;;;;N;;;;;
+A1E8;YI SYLLABLE GUO;Lo;0;L;;;;;N;;;;;
+A1E9;YI SYLLABLE GUOP;Lo;0;L;;;;;N;;;;;
+A1EA;YI SYLLABLE GOT;Lo;0;L;;;;;N;;;;;
+A1EB;YI SYLLABLE GOX;Lo;0;L;;;;;N;;;;;
+A1EC;YI SYLLABLE GO;Lo;0;L;;;;;N;;;;;
+A1ED;YI SYLLABLE GOP;Lo;0;L;;;;;N;;;;;
+A1EE;YI SYLLABLE GET;Lo;0;L;;;;;N;;;;;
+A1EF;YI SYLLABLE GEX;Lo;0;L;;;;;N;;;;;
+A1F0;YI SYLLABLE GE;Lo;0;L;;;;;N;;;;;
+A1F1;YI SYLLABLE GEP;Lo;0;L;;;;;N;;;;;
+A1F2;YI SYLLABLE GUT;Lo;0;L;;;;;N;;;;;
+A1F3;YI SYLLABLE GUX;Lo;0;L;;;;;N;;;;;
+A1F4;YI SYLLABLE GU;Lo;0;L;;;;;N;;;;;
+A1F5;YI SYLLABLE GUP;Lo;0;L;;;;;N;;;;;
+A1F6;YI SYLLABLE GURX;Lo;0;L;;;;;N;;;;;
+A1F7;YI SYLLABLE GUR;Lo;0;L;;;;;N;;;;;
+A1F8;YI SYLLABLE KIT;Lo;0;L;;;;;N;;;;;
+A1F9;YI SYLLABLE KIX;Lo;0;L;;;;;N;;;;;
+A1FA;YI SYLLABLE KI;Lo;0;L;;;;;N;;;;;
+A1FB;YI SYLLABLE KIP;Lo;0;L;;;;;N;;;;;
+A1FC;YI SYLLABLE KIEX;Lo;0;L;;;;;N;;;;;
+A1FD;YI SYLLABLE KIE;Lo;0;L;;;;;N;;;;;
+A1FE;YI SYLLABLE KIEP;Lo;0;L;;;;;N;;;;;
+A1FF;YI SYLLABLE KAT;Lo;0;L;;;;;N;;;;;
+A200;YI SYLLABLE KAX;Lo;0;L;;;;;N;;;;;
+A201;YI SYLLABLE KA;Lo;0;L;;;;;N;;;;;
+A202;YI SYLLABLE KAP;Lo;0;L;;;;;N;;;;;
+A203;YI SYLLABLE KUOX;Lo;0;L;;;;;N;;;;;
+A204;YI SYLLABLE KUO;Lo;0;L;;;;;N;;;;;
+A205;YI SYLLABLE KUOP;Lo;0;L;;;;;N;;;;;
+A206;YI SYLLABLE KOT;Lo;0;L;;;;;N;;;;;
+A207;YI SYLLABLE KOX;Lo;0;L;;;;;N;;;;;
+A208;YI SYLLABLE KO;Lo;0;L;;;;;N;;;;;
+A209;YI SYLLABLE KOP;Lo;0;L;;;;;N;;;;;
+A20A;YI SYLLABLE KET;Lo;0;L;;;;;N;;;;;
+A20B;YI SYLLABLE KEX;Lo;0;L;;;;;N;;;;;
+A20C;YI SYLLABLE KE;Lo;0;L;;;;;N;;;;;
+A20D;YI SYLLABLE KEP;Lo;0;L;;;;;N;;;;;
+A20E;YI SYLLABLE KUT;Lo;0;L;;;;;N;;;;;
+A20F;YI SYLLABLE KUX;Lo;0;L;;;;;N;;;;;
+A210;YI SYLLABLE KU;Lo;0;L;;;;;N;;;;;
+A211;YI SYLLABLE KUP;Lo;0;L;;;;;N;;;;;
+A212;YI SYLLABLE KURX;Lo;0;L;;;;;N;;;;;
+A213;YI SYLLABLE KUR;Lo;0;L;;;;;N;;;;;
+A214;YI SYLLABLE GGIT;Lo;0;L;;;;;N;;;;;
+A215;YI SYLLABLE GGIX;Lo;0;L;;;;;N;;;;;
+A216;YI SYLLABLE GGI;Lo;0;L;;;;;N;;;;;
+A217;YI SYLLABLE GGIEX;Lo;0;L;;;;;N;;;;;
+A218;YI SYLLABLE GGIE;Lo;0;L;;;;;N;;;;;
+A219;YI SYLLABLE GGIEP;Lo;0;L;;;;;N;;;;;
+A21A;YI SYLLABLE GGAT;Lo;0;L;;;;;N;;;;;
+A21B;YI SYLLABLE GGAX;Lo;0;L;;;;;N;;;;;
+A21C;YI SYLLABLE GGA;Lo;0;L;;;;;N;;;;;
+A21D;YI SYLLABLE GGAP;Lo;0;L;;;;;N;;;;;
+A21E;YI SYLLABLE GGUOT;Lo;0;L;;;;;N;;;;;
+A21F;YI SYLLABLE GGUOX;Lo;0;L;;;;;N;;;;;
+A220;YI SYLLABLE GGUO;Lo;0;L;;;;;N;;;;;
+A221;YI SYLLABLE GGUOP;Lo;0;L;;;;;N;;;;;
+A222;YI SYLLABLE GGOT;Lo;0;L;;;;;N;;;;;
+A223;YI SYLLABLE GGOX;Lo;0;L;;;;;N;;;;;
+A224;YI SYLLABLE GGO;Lo;0;L;;;;;N;;;;;
+A225;YI SYLLABLE GGOP;Lo;0;L;;;;;N;;;;;
+A226;YI SYLLABLE GGET;Lo;0;L;;;;;N;;;;;
+A227;YI SYLLABLE GGEX;Lo;0;L;;;;;N;;;;;
+A228;YI SYLLABLE GGE;Lo;0;L;;;;;N;;;;;
+A229;YI SYLLABLE GGEP;Lo;0;L;;;;;N;;;;;
+A22A;YI SYLLABLE GGUT;Lo;0;L;;;;;N;;;;;
+A22B;YI SYLLABLE GGUX;Lo;0;L;;;;;N;;;;;
+A22C;YI SYLLABLE GGU;Lo;0;L;;;;;N;;;;;
+A22D;YI SYLLABLE GGUP;Lo;0;L;;;;;N;;;;;
+A22E;YI SYLLABLE GGURX;Lo;0;L;;;;;N;;;;;
+A22F;YI SYLLABLE GGUR;Lo;0;L;;;;;N;;;;;
+A230;YI SYLLABLE MGIEX;Lo;0;L;;;;;N;;;;;
+A231;YI SYLLABLE MGIE;Lo;0;L;;;;;N;;;;;
+A232;YI SYLLABLE MGAT;Lo;0;L;;;;;N;;;;;
+A233;YI SYLLABLE MGAX;Lo;0;L;;;;;N;;;;;
+A234;YI SYLLABLE MGA;Lo;0;L;;;;;N;;;;;
+A235;YI SYLLABLE MGAP;Lo;0;L;;;;;N;;;;;
+A236;YI SYLLABLE MGUOX;Lo;0;L;;;;;N;;;;;
+A237;YI SYLLABLE MGUO;Lo;0;L;;;;;N;;;;;
+A238;YI SYLLABLE MGUOP;Lo;0;L;;;;;N;;;;;
+A239;YI SYLLABLE MGOT;Lo;0;L;;;;;N;;;;;
+A23A;YI SYLLABLE MGOX;Lo;0;L;;;;;N;;;;;
+A23B;YI SYLLABLE MGO;Lo;0;L;;;;;N;;;;;
+A23C;YI SYLLABLE MGOP;Lo;0;L;;;;;N;;;;;
+A23D;YI SYLLABLE MGEX;Lo;0;L;;;;;N;;;;;
+A23E;YI SYLLABLE MGE;Lo;0;L;;;;;N;;;;;
+A23F;YI SYLLABLE MGEP;Lo;0;L;;;;;N;;;;;
+A240;YI SYLLABLE MGUT;Lo;0;L;;;;;N;;;;;
+A241;YI SYLLABLE MGUX;Lo;0;L;;;;;N;;;;;
+A242;YI SYLLABLE MGU;Lo;0;L;;;;;N;;;;;
+A243;YI SYLLABLE MGUP;Lo;0;L;;;;;N;;;;;
+A244;YI SYLLABLE MGURX;Lo;0;L;;;;;N;;;;;
+A245;YI SYLLABLE MGUR;Lo;0;L;;;;;N;;;;;
+A246;YI SYLLABLE HXIT;Lo;0;L;;;;;N;;;;;
+A247;YI SYLLABLE HXIX;Lo;0;L;;;;;N;;;;;
+A248;YI SYLLABLE HXI;Lo;0;L;;;;;N;;;;;
+A249;YI SYLLABLE HXIP;Lo;0;L;;;;;N;;;;;
+A24A;YI SYLLABLE HXIET;Lo;0;L;;;;;N;;;;;
+A24B;YI SYLLABLE HXIEX;Lo;0;L;;;;;N;;;;;
+A24C;YI SYLLABLE HXIE;Lo;0;L;;;;;N;;;;;
+A24D;YI SYLLABLE HXIEP;Lo;0;L;;;;;N;;;;;
+A24E;YI SYLLABLE HXAT;Lo;0;L;;;;;N;;;;;
+A24F;YI SYLLABLE HXAX;Lo;0;L;;;;;N;;;;;
+A250;YI SYLLABLE HXA;Lo;0;L;;;;;N;;;;;
+A251;YI SYLLABLE HXAP;Lo;0;L;;;;;N;;;;;
+A252;YI SYLLABLE HXUOT;Lo;0;L;;;;;N;;;;;
+A253;YI SYLLABLE HXUOX;Lo;0;L;;;;;N;;;;;
+A254;YI SYLLABLE HXUO;Lo;0;L;;;;;N;;;;;
+A255;YI SYLLABLE HXUOP;Lo;0;L;;;;;N;;;;;
+A256;YI SYLLABLE HXOT;Lo;0;L;;;;;N;;;;;
+A257;YI SYLLABLE HXOX;Lo;0;L;;;;;N;;;;;
+A258;YI SYLLABLE HXO;Lo;0;L;;;;;N;;;;;
+A259;YI SYLLABLE HXOP;Lo;0;L;;;;;N;;;;;
+A25A;YI SYLLABLE HXEX;Lo;0;L;;;;;N;;;;;
+A25B;YI SYLLABLE HXE;Lo;0;L;;;;;N;;;;;
+A25C;YI SYLLABLE HXEP;Lo;0;L;;;;;N;;;;;
+A25D;YI SYLLABLE NGIEX;Lo;0;L;;;;;N;;;;;
+A25E;YI SYLLABLE NGIE;Lo;0;L;;;;;N;;;;;
+A25F;YI SYLLABLE NGIEP;Lo;0;L;;;;;N;;;;;
+A260;YI SYLLABLE NGAT;Lo;0;L;;;;;N;;;;;
+A261;YI SYLLABLE NGAX;Lo;0;L;;;;;N;;;;;
+A262;YI SYLLABLE NGA;Lo;0;L;;;;;N;;;;;
+A263;YI SYLLABLE NGAP;Lo;0;L;;;;;N;;;;;
+A264;YI SYLLABLE NGUOT;Lo;0;L;;;;;N;;;;;
+A265;YI SYLLABLE NGUOX;Lo;0;L;;;;;N;;;;;
+A266;YI SYLLABLE NGUO;Lo;0;L;;;;;N;;;;;
+A267;YI SYLLABLE NGOT;Lo;0;L;;;;;N;;;;;
+A268;YI SYLLABLE NGOX;Lo;0;L;;;;;N;;;;;
+A269;YI SYLLABLE NGO;Lo;0;L;;;;;N;;;;;
+A26A;YI SYLLABLE NGOP;Lo;0;L;;;;;N;;;;;
+A26B;YI SYLLABLE NGEX;Lo;0;L;;;;;N;;;;;
+A26C;YI SYLLABLE NGE;Lo;0;L;;;;;N;;;;;
+A26D;YI SYLLABLE NGEP;Lo;0;L;;;;;N;;;;;
+A26E;YI SYLLABLE HIT;Lo;0;L;;;;;N;;;;;
+A26F;YI SYLLABLE HIEX;Lo;0;L;;;;;N;;;;;
+A270;YI SYLLABLE HIE;Lo;0;L;;;;;N;;;;;
+A271;YI SYLLABLE HAT;Lo;0;L;;;;;N;;;;;
+A272;YI SYLLABLE HAX;Lo;0;L;;;;;N;;;;;
+A273;YI SYLLABLE HA;Lo;0;L;;;;;N;;;;;
+A274;YI SYLLABLE HAP;Lo;0;L;;;;;N;;;;;
+A275;YI SYLLABLE HUOT;Lo;0;L;;;;;N;;;;;
+A276;YI SYLLABLE HUOX;Lo;0;L;;;;;N;;;;;
+A277;YI SYLLABLE HUO;Lo;0;L;;;;;N;;;;;
+A278;YI SYLLABLE HUOP;Lo;0;L;;;;;N;;;;;
+A279;YI SYLLABLE HOT;Lo;0;L;;;;;N;;;;;
+A27A;YI SYLLABLE HOX;Lo;0;L;;;;;N;;;;;
+A27B;YI SYLLABLE HO;Lo;0;L;;;;;N;;;;;
+A27C;YI SYLLABLE HOP;Lo;0;L;;;;;N;;;;;
+A27D;YI SYLLABLE HEX;Lo;0;L;;;;;N;;;;;
+A27E;YI SYLLABLE HE;Lo;0;L;;;;;N;;;;;
+A27F;YI SYLLABLE HEP;Lo;0;L;;;;;N;;;;;
+A280;YI SYLLABLE WAT;Lo;0;L;;;;;N;;;;;
+A281;YI SYLLABLE WAX;Lo;0;L;;;;;N;;;;;
+A282;YI SYLLABLE WA;Lo;0;L;;;;;N;;;;;
+A283;YI SYLLABLE WAP;Lo;0;L;;;;;N;;;;;
+A284;YI SYLLABLE WUOX;Lo;0;L;;;;;N;;;;;
+A285;YI SYLLABLE WUO;Lo;0;L;;;;;N;;;;;
+A286;YI SYLLABLE WUOP;Lo;0;L;;;;;N;;;;;
+A287;YI SYLLABLE WOX;Lo;0;L;;;;;N;;;;;
+A288;YI SYLLABLE WO;Lo;0;L;;;;;N;;;;;
+A289;YI SYLLABLE WOP;Lo;0;L;;;;;N;;;;;
+A28A;YI SYLLABLE WEX;Lo;0;L;;;;;N;;;;;
+A28B;YI SYLLABLE WE;Lo;0;L;;;;;N;;;;;
+A28C;YI SYLLABLE WEP;Lo;0;L;;;;;N;;;;;
+A28D;YI SYLLABLE ZIT;Lo;0;L;;;;;N;;;;;
+A28E;YI SYLLABLE ZIX;Lo;0;L;;;;;N;;;;;
+A28F;YI SYLLABLE ZI;Lo;0;L;;;;;N;;;;;
+A290;YI SYLLABLE ZIP;Lo;0;L;;;;;N;;;;;
+A291;YI SYLLABLE ZIEX;Lo;0;L;;;;;N;;;;;
+A292;YI SYLLABLE ZIE;Lo;0;L;;;;;N;;;;;
+A293;YI SYLLABLE ZIEP;Lo;0;L;;;;;N;;;;;
+A294;YI SYLLABLE ZAT;Lo;0;L;;;;;N;;;;;
+A295;YI SYLLABLE ZAX;Lo;0;L;;;;;N;;;;;
+A296;YI SYLLABLE ZA;Lo;0;L;;;;;N;;;;;
+A297;YI SYLLABLE ZAP;Lo;0;L;;;;;N;;;;;
+A298;YI SYLLABLE ZUOX;Lo;0;L;;;;;N;;;;;
+A299;YI SYLLABLE ZUO;Lo;0;L;;;;;N;;;;;
+A29A;YI SYLLABLE ZUOP;Lo;0;L;;;;;N;;;;;
+A29B;YI SYLLABLE ZOT;Lo;0;L;;;;;N;;;;;
+A29C;YI SYLLABLE ZOX;Lo;0;L;;;;;N;;;;;
+A29D;YI SYLLABLE ZO;Lo;0;L;;;;;N;;;;;
+A29E;YI SYLLABLE ZOP;Lo;0;L;;;;;N;;;;;
+A29F;YI SYLLABLE ZEX;Lo;0;L;;;;;N;;;;;
+A2A0;YI SYLLABLE ZE;Lo;0;L;;;;;N;;;;;
+A2A1;YI SYLLABLE ZEP;Lo;0;L;;;;;N;;;;;
+A2A2;YI SYLLABLE ZUT;Lo;0;L;;;;;N;;;;;
+A2A3;YI SYLLABLE ZUX;Lo;0;L;;;;;N;;;;;
+A2A4;YI SYLLABLE ZU;Lo;0;L;;;;;N;;;;;
+A2A5;YI SYLLABLE ZUP;Lo;0;L;;;;;N;;;;;
+A2A6;YI SYLLABLE ZURX;Lo;0;L;;;;;N;;;;;
+A2A7;YI SYLLABLE ZUR;Lo;0;L;;;;;N;;;;;
+A2A8;YI SYLLABLE ZYT;Lo;0;L;;;;;N;;;;;
+A2A9;YI SYLLABLE ZYX;Lo;0;L;;;;;N;;;;;
+A2AA;YI SYLLABLE ZY;Lo;0;L;;;;;N;;;;;
+A2AB;YI SYLLABLE ZYP;Lo;0;L;;;;;N;;;;;
+A2AC;YI SYLLABLE ZYRX;Lo;0;L;;;;;N;;;;;
+A2AD;YI SYLLABLE ZYR;Lo;0;L;;;;;N;;;;;
+A2AE;YI SYLLABLE CIT;Lo;0;L;;;;;N;;;;;
+A2AF;YI SYLLABLE CIX;Lo;0;L;;;;;N;;;;;
+A2B0;YI SYLLABLE CI;Lo;0;L;;;;;N;;;;;
+A2B1;YI SYLLABLE CIP;Lo;0;L;;;;;N;;;;;
+A2B2;YI SYLLABLE CIET;Lo;0;L;;;;;N;;;;;
+A2B3;YI SYLLABLE CIEX;Lo;0;L;;;;;N;;;;;
+A2B4;YI SYLLABLE CIE;Lo;0;L;;;;;N;;;;;
+A2B5;YI SYLLABLE CIEP;Lo;0;L;;;;;N;;;;;
+A2B6;YI SYLLABLE CAT;Lo;0;L;;;;;N;;;;;
+A2B7;YI SYLLABLE CAX;Lo;0;L;;;;;N;;;;;
+A2B8;YI SYLLABLE CA;Lo;0;L;;;;;N;;;;;
+A2B9;YI SYLLABLE CAP;Lo;0;L;;;;;N;;;;;
+A2BA;YI SYLLABLE CUOX;Lo;0;L;;;;;N;;;;;
+A2BB;YI SYLLABLE CUO;Lo;0;L;;;;;N;;;;;
+A2BC;YI SYLLABLE CUOP;Lo;0;L;;;;;N;;;;;
+A2BD;YI SYLLABLE COT;Lo;0;L;;;;;N;;;;;
+A2BE;YI SYLLABLE COX;Lo;0;L;;;;;N;;;;;
+A2BF;YI SYLLABLE CO;Lo;0;L;;;;;N;;;;;
+A2C0;YI SYLLABLE COP;Lo;0;L;;;;;N;;;;;
+A2C1;YI SYLLABLE CEX;Lo;0;L;;;;;N;;;;;
+A2C2;YI SYLLABLE CE;Lo;0;L;;;;;N;;;;;
+A2C3;YI SYLLABLE CEP;Lo;0;L;;;;;N;;;;;
+A2C4;YI SYLLABLE CUT;Lo;0;L;;;;;N;;;;;
+A2C5;YI SYLLABLE CUX;Lo;0;L;;;;;N;;;;;
+A2C6;YI SYLLABLE CU;Lo;0;L;;;;;N;;;;;
+A2C7;YI SYLLABLE CUP;Lo;0;L;;;;;N;;;;;
+A2C8;YI SYLLABLE CURX;Lo;0;L;;;;;N;;;;;
+A2C9;YI SYLLABLE CUR;Lo;0;L;;;;;N;;;;;
+A2CA;YI SYLLABLE CYT;Lo;0;L;;;;;N;;;;;
+A2CB;YI SYLLABLE CYX;Lo;0;L;;;;;N;;;;;
+A2CC;YI SYLLABLE CY;Lo;0;L;;;;;N;;;;;
+A2CD;YI SYLLABLE CYP;Lo;0;L;;;;;N;;;;;
+A2CE;YI SYLLABLE CYRX;Lo;0;L;;;;;N;;;;;
+A2CF;YI SYLLABLE CYR;Lo;0;L;;;;;N;;;;;
+A2D0;YI SYLLABLE ZZIT;Lo;0;L;;;;;N;;;;;
+A2D1;YI SYLLABLE ZZIX;Lo;0;L;;;;;N;;;;;
+A2D2;YI SYLLABLE ZZI;Lo;0;L;;;;;N;;;;;
+A2D3;YI SYLLABLE ZZIP;Lo;0;L;;;;;N;;;;;
+A2D4;YI SYLLABLE ZZIET;Lo;0;L;;;;;N;;;;;
+A2D5;YI SYLLABLE ZZIEX;Lo;0;L;;;;;N;;;;;
+A2D6;YI SYLLABLE ZZIE;Lo;0;L;;;;;N;;;;;
+A2D7;YI SYLLABLE ZZIEP;Lo;0;L;;;;;N;;;;;
+A2D8;YI SYLLABLE ZZAT;Lo;0;L;;;;;N;;;;;
+A2D9;YI SYLLABLE ZZAX;Lo;0;L;;;;;N;;;;;
+A2DA;YI SYLLABLE ZZA;Lo;0;L;;;;;N;;;;;
+A2DB;YI SYLLABLE ZZAP;Lo;0;L;;;;;N;;;;;
+A2DC;YI SYLLABLE ZZOX;Lo;0;L;;;;;N;;;;;
+A2DD;YI SYLLABLE ZZO;Lo;0;L;;;;;N;;;;;
+A2DE;YI SYLLABLE ZZOP;Lo;0;L;;;;;N;;;;;
+A2DF;YI SYLLABLE ZZEX;Lo;0;L;;;;;N;;;;;
+A2E0;YI SYLLABLE ZZE;Lo;0;L;;;;;N;;;;;
+A2E1;YI SYLLABLE ZZEP;Lo;0;L;;;;;N;;;;;
+A2E2;YI SYLLABLE ZZUX;Lo;0;L;;;;;N;;;;;
+A2E3;YI SYLLABLE ZZU;Lo;0;L;;;;;N;;;;;
+A2E4;YI SYLLABLE ZZUP;Lo;0;L;;;;;N;;;;;
+A2E5;YI SYLLABLE ZZURX;Lo;0;L;;;;;N;;;;;
+A2E6;YI SYLLABLE ZZUR;Lo;0;L;;;;;N;;;;;
+A2E7;YI SYLLABLE ZZYT;Lo;0;L;;;;;N;;;;;
+A2E8;YI SYLLABLE ZZYX;Lo;0;L;;;;;N;;;;;
+A2E9;YI SYLLABLE ZZY;Lo;0;L;;;;;N;;;;;
+A2EA;YI SYLLABLE ZZYP;Lo;0;L;;;;;N;;;;;
+A2EB;YI SYLLABLE ZZYRX;Lo;0;L;;;;;N;;;;;
+A2EC;YI SYLLABLE ZZYR;Lo;0;L;;;;;N;;;;;
+A2ED;YI SYLLABLE NZIT;Lo;0;L;;;;;N;;;;;
+A2EE;YI SYLLABLE NZIX;Lo;0;L;;;;;N;;;;;
+A2EF;YI SYLLABLE NZI;Lo;0;L;;;;;N;;;;;
+A2F0;YI SYLLABLE NZIP;Lo;0;L;;;;;N;;;;;
+A2F1;YI SYLLABLE NZIEX;Lo;0;L;;;;;N;;;;;
+A2F2;YI SYLLABLE NZIE;Lo;0;L;;;;;N;;;;;
+A2F3;YI SYLLABLE NZIEP;Lo;0;L;;;;;N;;;;;
+A2F4;YI SYLLABLE NZAT;Lo;0;L;;;;;N;;;;;
+A2F5;YI SYLLABLE NZAX;Lo;0;L;;;;;N;;;;;
+A2F6;YI SYLLABLE NZA;Lo;0;L;;;;;N;;;;;
+A2F7;YI SYLLABLE NZAP;Lo;0;L;;;;;N;;;;;
+A2F8;YI SYLLABLE NZUOX;Lo;0;L;;;;;N;;;;;
+A2F9;YI SYLLABLE NZUO;Lo;0;L;;;;;N;;;;;
+A2FA;YI SYLLABLE NZOX;Lo;0;L;;;;;N;;;;;
+A2FB;YI SYLLABLE NZOP;Lo;0;L;;;;;N;;;;;
+A2FC;YI SYLLABLE NZEX;Lo;0;L;;;;;N;;;;;
+A2FD;YI SYLLABLE NZE;Lo;0;L;;;;;N;;;;;
+A2FE;YI SYLLABLE NZUX;Lo;0;L;;;;;N;;;;;
+A2FF;YI SYLLABLE NZU;Lo;0;L;;;;;N;;;;;
+A300;YI SYLLABLE NZUP;Lo;0;L;;;;;N;;;;;
+A301;YI SYLLABLE NZURX;Lo;0;L;;;;;N;;;;;
+A302;YI SYLLABLE NZUR;Lo;0;L;;;;;N;;;;;
+A303;YI SYLLABLE NZYT;Lo;0;L;;;;;N;;;;;
+A304;YI SYLLABLE NZYX;Lo;0;L;;;;;N;;;;;
+A305;YI SYLLABLE NZY;Lo;0;L;;;;;N;;;;;
+A306;YI SYLLABLE NZYP;Lo;0;L;;;;;N;;;;;
+A307;YI SYLLABLE NZYRX;Lo;0;L;;;;;N;;;;;
+A308;YI SYLLABLE NZYR;Lo;0;L;;;;;N;;;;;
+A309;YI SYLLABLE SIT;Lo;0;L;;;;;N;;;;;
+A30A;YI SYLLABLE SIX;Lo;0;L;;;;;N;;;;;
+A30B;YI SYLLABLE SI;Lo;0;L;;;;;N;;;;;
+A30C;YI SYLLABLE SIP;Lo;0;L;;;;;N;;;;;
+A30D;YI SYLLABLE SIEX;Lo;0;L;;;;;N;;;;;
+A30E;YI SYLLABLE SIE;Lo;0;L;;;;;N;;;;;
+A30F;YI SYLLABLE SIEP;Lo;0;L;;;;;N;;;;;
+A310;YI SYLLABLE SAT;Lo;0;L;;;;;N;;;;;
+A311;YI SYLLABLE SAX;Lo;0;L;;;;;N;;;;;
+A312;YI SYLLABLE SA;Lo;0;L;;;;;N;;;;;
+A313;YI SYLLABLE SAP;Lo;0;L;;;;;N;;;;;
+A314;YI SYLLABLE SUOX;Lo;0;L;;;;;N;;;;;
+A315;YI SYLLABLE SUO;Lo;0;L;;;;;N;;;;;
+A316;YI SYLLABLE SUOP;Lo;0;L;;;;;N;;;;;
+A317;YI SYLLABLE SOT;Lo;0;L;;;;;N;;;;;
+A318;YI SYLLABLE SOX;Lo;0;L;;;;;N;;;;;
+A319;YI SYLLABLE SO;Lo;0;L;;;;;N;;;;;
+A31A;YI SYLLABLE SOP;Lo;0;L;;;;;N;;;;;
+A31B;YI SYLLABLE SEX;Lo;0;L;;;;;N;;;;;
+A31C;YI SYLLABLE SE;Lo;0;L;;;;;N;;;;;
+A31D;YI SYLLABLE SEP;Lo;0;L;;;;;N;;;;;
+A31E;YI SYLLABLE SUT;Lo;0;L;;;;;N;;;;;
+A31F;YI SYLLABLE SUX;Lo;0;L;;;;;N;;;;;
+A320;YI SYLLABLE SU;Lo;0;L;;;;;N;;;;;
+A321;YI SYLLABLE SUP;Lo;0;L;;;;;N;;;;;
+A322;YI SYLLABLE SURX;Lo;0;L;;;;;N;;;;;
+A323;YI SYLLABLE SUR;Lo;0;L;;;;;N;;;;;
+A324;YI SYLLABLE SYT;Lo;0;L;;;;;N;;;;;
+A325;YI SYLLABLE SYX;Lo;0;L;;;;;N;;;;;
+A326;YI SYLLABLE SY;Lo;0;L;;;;;N;;;;;
+A327;YI SYLLABLE SYP;Lo;0;L;;;;;N;;;;;
+A328;YI SYLLABLE SYRX;Lo;0;L;;;;;N;;;;;
+A329;YI SYLLABLE SYR;Lo;0;L;;;;;N;;;;;
+A32A;YI SYLLABLE SSIT;Lo;0;L;;;;;N;;;;;
+A32B;YI SYLLABLE SSIX;Lo;0;L;;;;;N;;;;;
+A32C;YI SYLLABLE SSI;Lo;0;L;;;;;N;;;;;
+A32D;YI SYLLABLE SSIP;Lo;0;L;;;;;N;;;;;
+A32E;YI SYLLABLE SSIEX;Lo;0;L;;;;;N;;;;;
+A32F;YI SYLLABLE SSIE;Lo;0;L;;;;;N;;;;;
+A330;YI SYLLABLE SSIEP;Lo;0;L;;;;;N;;;;;
+A331;YI SYLLABLE SSAT;Lo;0;L;;;;;N;;;;;
+A332;YI SYLLABLE SSAX;Lo;0;L;;;;;N;;;;;
+A333;YI SYLLABLE SSA;Lo;0;L;;;;;N;;;;;
+A334;YI SYLLABLE SSAP;Lo;0;L;;;;;N;;;;;
+A335;YI SYLLABLE SSOT;Lo;0;L;;;;;N;;;;;
+A336;YI SYLLABLE SSOX;Lo;0;L;;;;;N;;;;;
+A337;YI SYLLABLE SSO;Lo;0;L;;;;;N;;;;;
+A338;YI SYLLABLE SSOP;Lo;0;L;;;;;N;;;;;
+A339;YI SYLLABLE SSEX;Lo;0;L;;;;;N;;;;;
+A33A;YI SYLLABLE SSE;Lo;0;L;;;;;N;;;;;
+A33B;YI SYLLABLE SSEP;Lo;0;L;;;;;N;;;;;
+A33C;YI SYLLABLE SSUT;Lo;0;L;;;;;N;;;;;
+A33D;YI SYLLABLE SSUX;Lo;0;L;;;;;N;;;;;
+A33E;YI SYLLABLE SSU;Lo;0;L;;;;;N;;;;;
+A33F;YI SYLLABLE SSUP;Lo;0;L;;;;;N;;;;;
+A340;YI SYLLABLE SSYT;Lo;0;L;;;;;N;;;;;
+A341;YI SYLLABLE SSYX;Lo;0;L;;;;;N;;;;;
+A342;YI SYLLABLE SSY;Lo;0;L;;;;;N;;;;;
+A343;YI SYLLABLE SSYP;Lo;0;L;;;;;N;;;;;
+A344;YI SYLLABLE SSYRX;Lo;0;L;;;;;N;;;;;
+A345;YI SYLLABLE SSYR;Lo;0;L;;;;;N;;;;;
+A346;YI SYLLABLE ZHAT;Lo;0;L;;;;;N;;;;;
+A347;YI SYLLABLE ZHAX;Lo;0;L;;;;;N;;;;;
+A348;YI SYLLABLE ZHA;Lo;0;L;;;;;N;;;;;
+A349;YI SYLLABLE ZHAP;Lo;0;L;;;;;N;;;;;
+A34A;YI SYLLABLE ZHUOX;Lo;0;L;;;;;N;;;;;
+A34B;YI SYLLABLE ZHUO;Lo;0;L;;;;;N;;;;;
+A34C;YI SYLLABLE ZHUOP;Lo;0;L;;;;;N;;;;;
+A34D;YI SYLLABLE ZHOT;Lo;0;L;;;;;N;;;;;
+A34E;YI SYLLABLE ZHOX;Lo;0;L;;;;;N;;;;;
+A34F;YI SYLLABLE ZHO;Lo;0;L;;;;;N;;;;;
+A350;YI SYLLABLE ZHOP;Lo;0;L;;;;;N;;;;;
+A351;YI SYLLABLE ZHET;Lo;0;L;;;;;N;;;;;
+A352;YI SYLLABLE ZHEX;Lo;0;L;;;;;N;;;;;
+A353;YI SYLLABLE ZHE;Lo;0;L;;;;;N;;;;;
+A354;YI SYLLABLE ZHEP;Lo;0;L;;;;;N;;;;;
+A355;YI SYLLABLE ZHUT;Lo;0;L;;;;;N;;;;;
+A356;YI SYLLABLE ZHUX;Lo;0;L;;;;;N;;;;;
+A357;YI SYLLABLE ZHU;Lo;0;L;;;;;N;;;;;
+A358;YI SYLLABLE ZHUP;Lo;0;L;;;;;N;;;;;
+A359;YI SYLLABLE ZHURX;Lo;0;L;;;;;N;;;;;
+A35A;YI SYLLABLE ZHUR;Lo;0;L;;;;;N;;;;;
+A35B;YI SYLLABLE ZHYT;Lo;0;L;;;;;N;;;;;
+A35C;YI SYLLABLE ZHYX;Lo;0;L;;;;;N;;;;;
+A35D;YI SYLLABLE ZHY;Lo;0;L;;;;;N;;;;;
+A35E;YI SYLLABLE ZHYP;Lo;0;L;;;;;N;;;;;
+A35F;YI SYLLABLE ZHYRX;Lo;0;L;;;;;N;;;;;
+A360;YI SYLLABLE ZHYR;Lo;0;L;;;;;N;;;;;
+A361;YI SYLLABLE CHAT;Lo;0;L;;;;;N;;;;;
+A362;YI SYLLABLE CHAX;Lo;0;L;;;;;N;;;;;
+A363;YI SYLLABLE CHA;Lo;0;L;;;;;N;;;;;
+A364;YI SYLLABLE CHAP;Lo;0;L;;;;;N;;;;;
+A365;YI SYLLABLE CHUOT;Lo;0;L;;;;;N;;;;;
+A366;YI SYLLABLE CHUOX;Lo;0;L;;;;;N;;;;;
+A367;YI SYLLABLE CHUO;Lo;0;L;;;;;N;;;;;
+A368;YI SYLLABLE CHUOP;Lo;0;L;;;;;N;;;;;
+A369;YI SYLLABLE CHOT;Lo;0;L;;;;;N;;;;;
+A36A;YI SYLLABLE CHOX;Lo;0;L;;;;;N;;;;;
+A36B;YI SYLLABLE CHO;Lo;0;L;;;;;N;;;;;
+A36C;YI SYLLABLE CHOP;Lo;0;L;;;;;N;;;;;
+A36D;YI SYLLABLE CHET;Lo;0;L;;;;;N;;;;;
+A36E;YI SYLLABLE CHEX;Lo;0;L;;;;;N;;;;;
+A36F;YI SYLLABLE CHE;Lo;0;L;;;;;N;;;;;
+A370;YI SYLLABLE CHEP;Lo;0;L;;;;;N;;;;;
+A371;YI SYLLABLE CHUX;Lo;0;L;;;;;N;;;;;
+A372;YI SYLLABLE CHU;Lo;0;L;;;;;N;;;;;
+A373;YI SYLLABLE CHUP;Lo;0;L;;;;;N;;;;;
+A374;YI SYLLABLE CHURX;Lo;0;L;;;;;N;;;;;
+A375;YI SYLLABLE CHUR;Lo;0;L;;;;;N;;;;;
+A376;YI SYLLABLE CHYT;Lo;0;L;;;;;N;;;;;
+A377;YI SYLLABLE CHYX;Lo;0;L;;;;;N;;;;;
+A378;YI SYLLABLE CHY;Lo;0;L;;;;;N;;;;;
+A379;YI SYLLABLE CHYP;Lo;0;L;;;;;N;;;;;
+A37A;YI SYLLABLE CHYRX;Lo;0;L;;;;;N;;;;;
+A37B;YI SYLLABLE CHYR;Lo;0;L;;;;;N;;;;;
+A37C;YI SYLLABLE RRAX;Lo;0;L;;;;;N;;;;;
+A37D;YI SYLLABLE RRA;Lo;0;L;;;;;N;;;;;
+A37E;YI SYLLABLE RRUOX;Lo;0;L;;;;;N;;;;;
+A37F;YI SYLLABLE RRUO;Lo;0;L;;;;;N;;;;;
+A380;YI SYLLABLE RROT;Lo;0;L;;;;;N;;;;;
+A381;YI SYLLABLE RROX;Lo;0;L;;;;;N;;;;;
+A382;YI SYLLABLE RRO;Lo;0;L;;;;;N;;;;;
+A383;YI SYLLABLE RROP;Lo;0;L;;;;;N;;;;;
+A384;YI SYLLABLE RRET;Lo;0;L;;;;;N;;;;;
+A385;YI SYLLABLE RREX;Lo;0;L;;;;;N;;;;;
+A386;YI SYLLABLE RRE;Lo;0;L;;;;;N;;;;;
+A387;YI SYLLABLE RREP;Lo;0;L;;;;;N;;;;;
+A388;YI SYLLABLE RRUT;Lo;0;L;;;;;N;;;;;
+A389;YI SYLLABLE RRUX;Lo;0;L;;;;;N;;;;;
+A38A;YI SYLLABLE RRU;Lo;0;L;;;;;N;;;;;
+A38B;YI SYLLABLE RRUP;Lo;0;L;;;;;N;;;;;
+A38C;YI SYLLABLE RRURX;Lo;0;L;;;;;N;;;;;
+A38D;YI SYLLABLE RRUR;Lo;0;L;;;;;N;;;;;
+A38E;YI SYLLABLE RRYT;Lo;0;L;;;;;N;;;;;
+A38F;YI SYLLABLE RRYX;Lo;0;L;;;;;N;;;;;
+A390;YI SYLLABLE RRY;Lo;0;L;;;;;N;;;;;
+A391;YI SYLLABLE RRYP;Lo;0;L;;;;;N;;;;;
+A392;YI SYLLABLE RRYRX;Lo;0;L;;;;;N;;;;;
+A393;YI SYLLABLE RRYR;Lo;0;L;;;;;N;;;;;
+A394;YI SYLLABLE NRAT;Lo;0;L;;;;;N;;;;;
+A395;YI SYLLABLE NRAX;Lo;0;L;;;;;N;;;;;
+A396;YI SYLLABLE NRA;Lo;0;L;;;;;N;;;;;
+A397;YI SYLLABLE NRAP;Lo;0;L;;;;;N;;;;;
+A398;YI SYLLABLE NROX;Lo;0;L;;;;;N;;;;;
+A399;YI SYLLABLE NRO;Lo;0;L;;;;;N;;;;;
+A39A;YI SYLLABLE NROP;Lo;0;L;;;;;N;;;;;
+A39B;YI SYLLABLE NRET;Lo;0;L;;;;;N;;;;;
+A39C;YI SYLLABLE NREX;Lo;0;L;;;;;N;;;;;
+A39D;YI SYLLABLE NRE;Lo;0;L;;;;;N;;;;;
+A39E;YI SYLLABLE NREP;Lo;0;L;;;;;N;;;;;
+A39F;YI SYLLABLE NRUT;Lo;0;L;;;;;N;;;;;
+A3A0;YI SYLLABLE NRUX;Lo;0;L;;;;;N;;;;;
+A3A1;YI SYLLABLE NRU;Lo;0;L;;;;;N;;;;;
+A3A2;YI SYLLABLE NRUP;Lo;0;L;;;;;N;;;;;
+A3A3;YI SYLLABLE NRURX;Lo;0;L;;;;;N;;;;;
+A3A4;YI SYLLABLE NRUR;Lo;0;L;;;;;N;;;;;
+A3A5;YI SYLLABLE NRYT;Lo;0;L;;;;;N;;;;;
+A3A6;YI SYLLABLE NRYX;Lo;0;L;;;;;N;;;;;
+A3A7;YI SYLLABLE NRY;Lo;0;L;;;;;N;;;;;
+A3A8;YI SYLLABLE NRYP;Lo;0;L;;;;;N;;;;;
+A3A9;YI SYLLABLE NRYRX;Lo;0;L;;;;;N;;;;;
+A3AA;YI SYLLABLE NRYR;Lo;0;L;;;;;N;;;;;
+A3AB;YI SYLLABLE SHAT;Lo;0;L;;;;;N;;;;;
+A3AC;YI SYLLABLE SHAX;Lo;0;L;;;;;N;;;;;
+A3AD;YI SYLLABLE SHA;Lo;0;L;;;;;N;;;;;
+A3AE;YI SYLLABLE SHAP;Lo;0;L;;;;;N;;;;;
+A3AF;YI SYLLABLE SHUOX;Lo;0;L;;;;;N;;;;;
+A3B0;YI SYLLABLE SHUO;Lo;0;L;;;;;N;;;;;
+A3B1;YI SYLLABLE SHUOP;Lo;0;L;;;;;N;;;;;
+A3B2;YI SYLLABLE SHOT;Lo;0;L;;;;;N;;;;;
+A3B3;YI SYLLABLE SHOX;Lo;0;L;;;;;N;;;;;
+A3B4;YI SYLLABLE SHO;Lo;0;L;;;;;N;;;;;
+A3B5;YI SYLLABLE SHOP;Lo;0;L;;;;;N;;;;;
+A3B6;YI SYLLABLE SHET;Lo;0;L;;;;;N;;;;;
+A3B7;YI SYLLABLE SHEX;Lo;0;L;;;;;N;;;;;
+A3B8;YI SYLLABLE SHE;Lo;0;L;;;;;N;;;;;
+A3B9;YI SYLLABLE SHEP;Lo;0;L;;;;;N;;;;;
+A3BA;YI SYLLABLE SHUT;Lo;0;L;;;;;N;;;;;
+A3BB;YI SYLLABLE SHUX;Lo;0;L;;;;;N;;;;;
+A3BC;YI SYLLABLE SHU;Lo;0;L;;;;;N;;;;;
+A3BD;YI SYLLABLE SHUP;Lo;0;L;;;;;N;;;;;
+A3BE;YI SYLLABLE SHURX;Lo;0;L;;;;;N;;;;;
+A3BF;YI SYLLABLE SHUR;Lo;0;L;;;;;N;;;;;
+A3C0;YI SYLLABLE SHYT;Lo;0;L;;;;;N;;;;;
+A3C1;YI SYLLABLE SHYX;Lo;0;L;;;;;N;;;;;
+A3C2;YI SYLLABLE SHY;Lo;0;L;;;;;N;;;;;
+A3C3;YI SYLLABLE SHYP;Lo;0;L;;;;;N;;;;;
+A3C4;YI SYLLABLE SHYRX;Lo;0;L;;;;;N;;;;;
+A3C5;YI SYLLABLE SHYR;Lo;0;L;;;;;N;;;;;
+A3C6;YI SYLLABLE RAT;Lo;0;L;;;;;N;;;;;
+A3C7;YI SYLLABLE RAX;Lo;0;L;;;;;N;;;;;
+A3C8;YI SYLLABLE RA;Lo;0;L;;;;;N;;;;;
+A3C9;YI SYLLABLE RAP;Lo;0;L;;;;;N;;;;;
+A3CA;YI SYLLABLE RUOX;Lo;0;L;;;;;N;;;;;
+A3CB;YI SYLLABLE RUO;Lo;0;L;;;;;N;;;;;
+A3CC;YI SYLLABLE RUOP;Lo;0;L;;;;;N;;;;;
+A3CD;YI SYLLABLE ROT;Lo;0;L;;;;;N;;;;;
+A3CE;YI SYLLABLE ROX;Lo;0;L;;;;;N;;;;;
+A3CF;YI SYLLABLE RO;Lo;0;L;;;;;N;;;;;
+A3D0;YI SYLLABLE ROP;Lo;0;L;;;;;N;;;;;
+A3D1;YI SYLLABLE REX;Lo;0;L;;;;;N;;;;;
+A3D2;YI SYLLABLE RE;Lo;0;L;;;;;N;;;;;
+A3D3;YI SYLLABLE REP;Lo;0;L;;;;;N;;;;;
+A3D4;YI SYLLABLE RUT;Lo;0;L;;;;;N;;;;;
+A3D5;YI SYLLABLE RUX;Lo;0;L;;;;;N;;;;;
+A3D6;YI SYLLABLE RU;Lo;0;L;;;;;N;;;;;
+A3D7;YI SYLLABLE RUP;Lo;0;L;;;;;N;;;;;
+A3D8;YI SYLLABLE RURX;Lo;0;L;;;;;N;;;;;
+A3D9;YI SYLLABLE RUR;Lo;0;L;;;;;N;;;;;
+A3DA;YI SYLLABLE RYT;Lo;0;L;;;;;N;;;;;
+A3DB;YI SYLLABLE RYX;Lo;0;L;;;;;N;;;;;
+A3DC;YI SYLLABLE RY;Lo;0;L;;;;;N;;;;;
+A3DD;YI SYLLABLE RYP;Lo;0;L;;;;;N;;;;;
+A3DE;YI SYLLABLE RYRX;Lo;0;L;;;;;N;;;;;
+A3DF;YI SYLLABLE RYR;Lo;0;L;;;;;N;;;;;
+A3E0;YI SYLLABLE JIT;Lo;0;L;;;;;N;;;;;
+A3E1;YI SYLLABLE JIX;Lo;0;L;;;;;N;;;;;
+A3E2;YI SYLLABLE JI;Lo;0;L;;;;;N;;;;;
+A3E3;YI SYLLABLE JIP;Lo;0;L;;;;;N;;;;;
+A3E4;YI SYLLABLE JIET;Lo;0;L;;;;;N;;;;;
+A3E5;YI SYLLABLE JIEX;Lo;0;L;;;;;N;;;;;
+A3E6;YI SYLLABLE JIE;Lo;0;L;;;;;N;;;;;
+A3E7;YI SYLLABLE JIEP;Lo;0;L;;;;;N;;;;;
+A3E8;YI SYLLABLE JUOT;Lo;0;L;;;;;N;;;;;
+A3E9;YI SYLLABLE JUOX;Lo;0;L;;;;;N;;;;;
+A3EA;YI SYLLABLE JUO;Lo;0;L;;;;;N;;;;;
+A3EB;YI SYLLABLE JUOP;Lo;0;L;;;;;N;;;;;
+A3EC;YI SYLLABLE JOT;Lo;0;L;;;;;N;;;;;
+A3ED;YI SYLLABLE JOX;Lo;0;L;;;;;N;;;;;
+A3EE;YI SYLLABLE JO;Lo;0;L;;;;;N;;;;;
+A3EF;YI SYLLABLE JOP;Lo;0;L;;;;;N;;;;;
+A3F0;YI SYLLABLE JUT;Lo;0;L;;;;;N;;;;;
+A3F1;YI SYLLABLE JUX;Lo;0;L;;;;;N;;;;;
+A3F2;YI SYLLABLE JU;Lo;0;L;;;;;N;;;;;
+A3F3;YI SYLLABLE JUP;Lo;0;L;;;;;N;;;;;
+A3F4;YI SYLLABLE JURX;Lo;0;L;;;;;N;;;;;
+A3F5;YI SYLLABLE JUR;Lo;0;L;;;;;N;;;;;
+A3F6;YI SYLLABLE JYT;Lo;0;L;;;;;N;;;;;
+A3F7;YI SYLLABLE JYX;Lo;0;L;;;;;N;;;;;
+A3F8;YI SYLLABLE JY;Lo;0;L;;;;;N;;;;;
+A3F9;YI SYLLABLE JYP;Lo;0;L;;;;;N;;;;;
+A3FA;YI SYLLABLE JYRX;Lo;0;L;;;;;N;;;;;
+A3FB;YI SYLLABLE JYR;Lo;0;L;;;;;N;;;;;
+A3FC;YI SYLLABLE QIT;Lo;0;L;;;;;N;;;;;
+A3FD;YI SYLLABLE QIX;Lo;0;L;;;;;N;;;;;
+A3FE;YI SYLLABLE QI;Lo;0;L;;;;;N;;;;;
+A3FF;YI SYLLABLE QIP;Lo;0;L;;;;;N;;;;;
+A400;YI SYLLABLE QIET;Lo;0;L;;;;;N;;;;;
+A401;YI SYLLABLE QIEX;Lo;0;L;;;;;N;;;;;
+A402;YI SYLLABLE QIE;Lo;0;L;;;;;N;;;;;
+A403;YI SYLLABLE QIEP;Lo;0;L;;;;;N;;;;;
+A404;YI SYLLABLE QUOT;Lo;0;L;;;;;N;;;;;
+A405;YI SYLLABLE QUOX;Lo;0;L;;;;;N;;;;;
+A406;YI SYLLABLE QUO;Lo;0;L;;;;;N;;;;;
+A407;YI SYLLABLE QUOP;Lo;0;L;;;;;N;;;;;
+A408;YI SYLLABLE QOT;Lo;0;L;;;;;N;;;;;
+A409;YI SYLLABLE QOX;Lo;0;L;;;;;N;;;;;
+A40A;YI SYLLABLE QO;Lo;0;L;;;;;N;;;;;
+A40B;YI SYLLABLE QOP;Lo;0;L;;;;;N;;;;;
+A40C;YI SYLLABLE QUT;Lo;0;L;;;;;N;;;;;
+A40D;YI SYLLABLE QUX;Lo;0;L;;;;;N;;;;;
+A40E;YI SYLLABLE QU;Lo;0;L;;;;;N;;;;;
+A40F;YI SYLLABLE QUP;Lo;0;L;;;;;N;;;;;
+A410;YI SYLLABLE QURX;Lo;0;L;;;;;N;;;;;
+A411;YI SYLLABLE QUR;Lo;0;L;;;;;N;;;;;
+A412;YI SYLLABLE QYT;Lo;0;L;;;;;N;;;;;
+A413;YI SYLLABLE QYX;Lo;0;L;;;;;N;;;;;
+A414;YI SYLLABLE QY;Lo;0;L;;;;;N;;;;;
+A415;YI SYLLABLE QYP;Lo;0;L;;;;;N;;;;;
+A416;YI SYLLABLE QYRX;Lo;0;L;;;;;N;;;;;
+A417;YI SYLLABLE QYR;Lo;0;L;;;;;N;;;;;
+A418;YI SYLLABLE JJIT;Lo;0;L;;;;;N;;;;;
+A419;YI SYLLABLE JJIX;Lo;0;L;;;;;N;;;;;
+A41A;YI SYLLABLE JJI;Lo;0;L;;;;;N;;;;;
+A41B;YI SYLLABLE JJIP;Lo;0;L;;;;;N;;;;;
+A41C;YI SYLLABLE JJIET;Lo;0;L;;;;;N;;;;;
+A41D;YI SYLLABLE JJIEX;Lo;0;L;;;;;N;;;;;
+A41E;YI SYLLABLE JJIE;Lo;0;L;;;;;N;;;;;
+A41F;YI SYLLABLE JJIEP;Lo;0;L;;;;;N;;;;;
+A420;YI SYLLABLE JJUOX;Lo;0;L;;;;;N;;;;;
+A421;YI SYLLABLE JJUO;Lo;0;L;;;;;N;;;;;
+A422;YI SYLLABLE JJUOP;Lo;0;L;;;;;N;;;;;
+A423;YI SYLLABLE JJOT;Lo;0;L;;;;;N;;;;;
+A424;YI SYLLABLE JJOX;Lo;0;L;;;;;N;;;;;
+A425;YI SYLLABLE JJO;Lo;0;L;;;;;N;;;;;
+A426;YI SYLLABLE JJOP;Lo;0;L;;;;;N;;;;;
+A427;YI SYLLABLE JJUT;Lo;0;L;;;;;N;;;;;
+A428;YI SYLLABLE JJUX;Lo;0;L;;;;;N;;;;;
+A429;YI SYLLABLE JJU;Lo;0;L;;;;;N;;;;;
+A42A;YI SYLLABLE JJUP;Lo;0;L;;;;;N;;;;;
+A42B;YI SYLLABLE JJURX;Lo;0;L;;;;;N;;;;;
+A42C;YI SYLLABLE JJUR;Lo;0;L;;;;;N;;;;;
+A42D;YI SYLLABLE JJYT;Lo;0;L;;;;;N;;;;;
+A42E;YI SYLLABLE JJYX;Lo;0;L;;;;;N;;;;;
+A42F;YI SYLLABLE JJY;Lo;0;L;;;;;N;;;;;
+A430;YI SYLLABLE JJYP;Lo;0;L;;;;;N;;;;;
+A431;YI SYLLABLE NJIT;Lo;0;L;;;;;N;;;;;
+A432;YI SYLLABLE NJIX;Lo;0;L;;;;;N;;;;;
+A433;YI SYLLABLE NJI;Lo;0;L;;;;;N;;;;;
+A434;YI SYLLABLE NJIP;Lo;0;L;;;;;N;;;;;
+A435;YI SYLLABLE NJIET;Lo;0;L;;;;;N;;;;;
+A436;YI SYLLABLE NJIEX;Lo;0;L;;;;;N;;;;;
+A437;YI SYLLABLE NJIE;Lo;0;L;;;;;N;;;;;
+A438;YI SYLLABLE NJIEP;Lo;0;L;;;;;N;;;;;
+A439;YI SYLLABLE NJUOX;Lo;0;L;;;;;N;;;;;
+A43A;YI SYLLABLE NJUO;Lo;0;L;;;;;N;;;;;
+A43B;YI SYLLABLE NJOT;Lo;0;L;;;;;N;;;;;
+A43C;YI SYLLABLE NJOX;Lo;0;L;;;;;N;;;;;
+A43D;YI SYLLABLE NJO;Lo;0;L;;;;;N;;;;;
+A43E;YI SYLLABLE NJOP;Lo;0;L;;;;;N;;;;;
+A43F;YI SYLLABLE NJUX;Lo;0;L;;;;;N;;;;;
+A440;YI SYLLABLE NJU;Lo;0;L;;;;;N;;;;;
+A441;YI SYLLABLE NJUP;Lo;0;L;;;;;N;;;;;
+A442;YI SYLLABLE NJURX;Lo;0;L;;;;;N;;;;;
+A443;YI SYLLABLE NJUR;Lo;0;L;;;;;N;;;;;
+A444;YI SYLLABLE NJYT;Lo;0;L;;;;;N;;;;;
+A445;YI SYLLABLE NJYX;Lo;0;L;;;;;N;;;;;
+A446;YI SYLLABLE NJY;Lo;0;L;;;;;N;;;;;
+A447;YI SYLLABLE NJYP;Lo;0;L;;;;;N;;;;;
+A448;YI SYLLABLE NJYRX;Lo;0;L;;;;;N;;;;;
+A449;YI SYLLABLE NJYR;Lo;0;L;;;;;N;;;;;
+A44A;YI SYLLABLE NYIT;Lo;0;L;;;;;N;;;;;
+A44B;YI SYLLABLE NYIX;Lo;0;L;;;;;N;;;;;
+A44C;YI SYLLABLE NYI;Lo;0;L;;;;;N;;;;;
+A44D;YI SYLLABLE NYIP;Lo;0;L;;;;;N;;;;;
+A44E;YI SYLLABLE NYIET;Lo;0;L;;;;;N;;;;;
+A44F;YI SYLLABLE NYIEX;Lo;0;L;;;;;N;;;;;
+A450;YI SYLLABLE NYIE;Lo;0;L;;;;;N;;;;;
+A451;YI SYLLABLE NYIEP;Lo;0;L;;;;;N;;;;;
+A452;YI SYLLABLE NYUOX;Lo;0;L;;;;;N;;;;;
+A453;YI SYLLABLE NYUO;Lo;0;L;;;;;N;;;;;
+A454;YI SYLLABLE NYUOP;Lo;0;L;;;;;N;;;;;
+A455;YI SYLLABLE NYOT;Lo;0;L;;;;;N;;;;;
+A456;YI SYLLABLE NYOX;Lo;0;L;;;;;N;;;;;
+A457;YI SYLLABLE NYO;Lo;0;L;;;;;N;;;;;
+A458;YI SYLLABLE NYOP;Lo;0;L;;;;;N;;;;;
+A459;YI SYLLABLE NYUT;Lo;0;L;;;;;N;;;;;
+A45A;YI SYLLABLE NYUX;Lo;0;L;;;;;N;;;;;
+A45B;YI SYLLABLE NYU;Lo;0;L;;;;;N;;;;;
+A45C;YI SYLLABLE NYUP;Lo;0;L;;;;;N;;;;;
+A45D;YI SYLLABLE XIT;Lo;0;L;;;;;N;;;;;
+A45E;YI SYLLABLE XIX;Lo;0;L;;;;;N;;;;;
+A45F;YI SYLLABLE XI;Lo;0;L;;;;;N;;;;;
+A460;YI SYLLABLE XIP;Lo;0;L;;;;;N;;;;;
+A461;YI SYLLABLE XIET;Lo;0;L;;;;;N;;;;;
+A462;YI SYLLABLE XIEX;Lo;0;L;;;;;N;;;;;
+A463;YI SYLLABLE XIE;Lo;0;L;;;;;N;;;;;
+A464;YI SYLLABLE XIEP;Lo;0;L;;;;;N;;;;;
+A465;YI SYLLABLE XUOX;Lo;0;L;;;;;N;;;;;
+A466;YI SYLLABLE XUO;Lo;0;L;;;;;N;;;;;
+A467;YI SYLLABLE XOT;Lo;0;L;;;;;N;;;;;
+A468;YI SYLLABLE XOX;Lo;0;L;;;;;N;;;;;
+A469;YI SYLLABLE XO;Lo;0;L;;;;;N;;;;;
+A46A;YI SYLLABLE XOP;Lo;0;L;;;;;N;;;;;
+A46B;YI SYLLABLE XYT;Lo;0;L;;;;;N;;;;;
+A46C;YI SYLLABLE XYX;Lo;0;L;;;;;N;;;;;
+A46D;YI SYLLABLE XY;Lo;0;L;;;;;N;;;;;
+A46E;YI SYLLABLE XYP;Lo;0;L;;;;;N;;;;;
+A46F;YI SYLLABLE XYRX;Lo;0;L;;;;;N;;;;;
+A470;YI SYLLABLE XYR;Lo;0;L;;;;;N;;;;;
+A471;YI SYLLABLE YIT;Lo;0;L;;;;;N;;;;;
+A472;YI SYLLABLE YIX;Lo;0;L;;;;;N;;;;;
+A473;YI SYLLABLE YI;Lo;0;L;;;;;N;;;;;
+A474;YI SYLLABLE YIP;Lo;0;L;;;;;N;;;;;
+A475;YI SYLLABLE YIET;Lo;0;L;;;;;N;;;;;
+A476;YI SYLLABLE YIEX;Lo;0;L;;;;;N;;;;;
+A477;YI SYLLABLE YIE;Lo;0;L;;;;;N;;;;;
+A478;YI SYLLABLE YIEP;Lo;0;L;;;;;N;;;;;
+A479;YI SYLLABLE YUOT;Lo;0;L;;;;;N;;;;;
+A47A;YI SYLLABLE YUOX;Lo;0;L;;;;;N;;;;;
+A47B;YI SYLLABLE YUO;Lo;0;L;;;;;N;;;;;
+A47C;YI SYLLABLE YUOP;Lo;0;L;;;;;N;;;;;
+A47D;YI SYLLABLE YOT;Lo;0;L;;;;;N;;;;;
+A47E;YI SYLLABLE YOX;Lo;0;L;;;;;N;;;;;
+A47F;YI SYLLABLE YO;Lo;0;L;;;;;N;;;;;
+A480;YI SYLLABLE YOP;Lo;0;L;;;;;N;;;;;
+A481;YI SYLLABLE YUT;Lo;0;L;;;;;N;;;;;
+A482;YI SYLLABLE YUX;Lo;0;L;;;;;N;;;;;
+A483;YI SYLLABLE YU;Lo;0;L;;;;;N;;;;;
+A484;YI SYLLABLE YUP;Lo;0;L;;;;;N;;;;;
+A485;YI SYLLABLE YURX;Lo;0;L;;;;;N;;;;;
+A486;YI SYLLABLE YUR;Lo;0;L;;;;;N;;;;;
+A487;YI SYLLABLE YYT;Lo;0;L;;;;;N;;;;;
+A488;YI SYLLABLE YYX;Lo;0;L;;;;;N;;;;;
+A489;YI SYLLABLE YY;Lo;0;L;;;;;N;;;;;
+A48A;YI SYLLABLE YYP;Lo;0;L;;;;;N;;;;;
+A48B;YI SYLLABLE YYRX;Lo;0;L;;;;;N;;;;;
+A48C;YI SYLLABLE YYR;Lo;0;L;;;;;N;;;;;
+A490;YI RADICAL QOT;So;0;ON;;;;;N;;;;;
+A491;YI RADICAL LI;So;0;ON;;;;;N;;;;;
+A492;YI RADICAL KIT;So;0;ON;;;;;N;;;;;
+A493;YI RADICAL NYIP;So;0;ON;;;;;N;;;;;
+A494;YI RADICAL CYP;So;0;ON;;;;;N;;;;;
+A495;YI RADICAL SSI;So;0;ON;;;;;N;;;;;
+A496;YI RADICAL GGOP;So;0;ON;;;;;N;;;;;
+A497;YI RADICAL GEP;So;0;ON;;;;;N;;;;;
+A498;YI RADICAL MI;So;0;ON;;;;;N;;;;;
+A499;YI RADICAL HXIT;So;0;ON;;;;;N;;;;;
+A49A;YI RADICAL LYR;So;0;ON;;;;;N;;;;;
+A49B;YI RADICAL BBUT;So;0;ON;;;;;N;;;;;
+A49C;YI RADICAL MOP;So;0;ON;;;;;N;;;;;
+A49D;YI RADICAL YO;So;0;ON;;;;;N;;;;;
+A49E;YI RADICAL PUT;So;0;ON;;;;;N;;;;;
+A49F;YI RADICAL HXUO;So;0;ON;;;;;N;;;;;
+A4A0;YI RADICAL TAT;So;0;ON;;;;;N;;;;;
+A4A1;YI RADICAL GA;So;0;ON;;;;;N;;;;;
+A4A2;YI RADICAL ZUP;So;0;ON;;;;;N;;;;;
+A4A3;YI RADICAL CYT;So;0;ON;;;;;N;;;;;
+A4A4;YI RADICAL DDUR;So;0;ON;;;;;N;;;;;
+A4A5;YI RADICAL BUR;So;0;ON;;;;;N;;;;;
+A4A6;YI RADICAL GGUO;So;0;ON;;;;;N;;;;;
+A4A7;YI RADICAL NYOP;So;0;ON;;;;;N;;;;;
+A4A8;YI RADICAL TU;So;0;ON;;;;;N;;;;;
+A4A9;YI RADICAL OP;So;0;ON;;;;;N;;;;;
+A4AA;YI RADICAL JJUT;So;0;ON;;;;;N;;;;;
+A4AB;YI RADICAL ZOT;So;0;ON;;;;;N;;;;;
+A4AC;YI RADICAL PYT;So;0;ON;;;;;N;;;;;
+A4AD;YI RADICAL HMO;So;0;ON;;;;;N;;;;;
+A4AE;YI RADICAL YIT;So;0;ON;;;;;N;;;;;
+A4AF;YI RADICAL VUR;So;0;ON;;;;;N;;;;;
+A4B0;YI RADICAL SHY;So;0;ON;;;;;N;;;;;
+A4B1;YI RADICAL VEP;So;0;ON;;;;;N;;;;;
+A4B2;YI RADICAL ZA;So;0;ON;;;;;N;;;;;
+A4B3;YI RADICAL JO;So;0;ON;;;;;N;;;;;
+A4B4;YI RADICAL NZUP;So;0;ON;;;;;N;;;;;
+A4B5;YI RADICAL JJY;So;0;ON;;;;;N;;;;;
+A4B6;YI RADICAL GOT;So;0;ON;;;;;N;;;;;
+A4B7;YI RADICAL JJIE;So;0;ON;;;;;N;;;;;
+A4B8;YI RADICAL WO;So;0;ON;;;;;N;;;;;
+A4B9;YI RADICAL DU;So;0;ON;;;;;N;;;;;
+A4BA;YI RADICAL SHUR;So;0;ON;;;;;N;;;;;
+A4BB;YI RADICAL LIE;So;0;ON;;;;;N;;;;;
+A4BC;YI RADICAL CY;So;0;ON;;;;;N;;;;;
+A4BD;YI RADICAL CUOP;So;0;ON;;;;;N;;;;;
+A4BE;YI RADICAL CIP;So;0;ON;;;;;N;;;;;
+A4BF;YI RADICAL HXOP;So;0;ON;;;;;N;;;;;
+A4C0;YI RADICAL SHAT;So;0;ON;;;;;N;;;;;
+A4C1;YI RADICAL ZUR;So;0;ON;;;;;N;;;;;
+A4C2;YI RADICAL SHOP;So;0;ON;;;;;N;;;;;
+A4C3;YI RADICAL CHE;So;0;ON;;;;;N;;;;;
+A4C4;YI RADICAL ZZIET;So;0;ON;;;;;N;;;;;
+A4C5;YI RADICAL NBIE;So;0;ON;;;;;N;;;;;
+A4C6;YI RADICAL KE;So;0;ON;;;;;N;;;;;
+AC00;<Hangul Syllable, First>;Lo;0;L;;;;;N;;;;;
+D7A3;<Hangul Syllable, Last>;Lo;0;L;;;;;N;;;;;
+D800;<Non Private Use High Surrogate, First>;Cs;0;L;;;;;N;;;;;
+DB7F;<Non Private Use High Surrogate, Last>;Cs;0;L;;;;;N;;;;;
+DB80;<Private Use High Surrogate, First>;Cs;0;L;;;;;N;;;;;
+DBFF;<Private Use High Surrogate, Last>;Cs;0;L;;;;;N;;;;;
+DC00;<Low Surrogate, First>;Cs;0;L;;;;;N;;;;;
+DFFF;<Low Surrogate, Last>;Cs;0;L;;;;;N;;;;;
+E000;<Private Use, First>;Co;0;L;;;;;N;;;;;
+F8FF;<Private Use, Last>;Co;0;L;;;;;N;;;;;
+F900;CJK COMPATIBILITY IDEOGRAPH-F900;Lo;0;L;8C48;;;;N;;;;;
+F901;CJK COMPATIBILITY IDEOGRAPH-F901;Lo;0;L;66F4;;;;N;;;;;
+F902;CJK COMPATIBILITY IDEOGRAPH-F902;Lo;0;L;8ECA;;;;N;;;;;
+F903;CJK COMPATIBILITY IDEOGRAPH-F903;Lo;0;L;8CC8;;;;N;;;;;
+F904;CJK COMPATIBILITY IDEOGRAPH-F904;Lo;0;L;6ED1;;;;N;;;;;
+F905;CJK COMPATIBILITY IDEOGRAPH-F905;Lo;0;L;4E32;;;;N;;;;;
+F906;CJK COMPATIBILITY IDEOGRAPH-F906;Lo;0;L;53E5;;;;N;;;;;
+F907;CJK COMPATIBILITY IDEOGRAPH-F907;Lo;0;L;9F9C;;;;N;;;;;
+F908;CJK COMPATIBILITY IDEOGRAPH-F908;Lo;0;L;9F9C;;;;N;;;;;
+F909;CJK COMPATIBILITY IDEOGRAPH-F909;Lo;0;L;5951;;;;N;;;;;
+F90A;CJK COMPATIBILITY IDEOGRAPH-F90A;Lo;0;L;91D1;;;;N;;;;;
+F90B;CJK COMPATIBILITY IDEOGRAPH-F90B;Lo;0;L;5587;;;;N;;;;;
+F90C;CJK COMPATIBILITY IDEOGRAPH-F90C;Lo;0;L;5948;;;;N;;;;;
+F90D;CJK COMPATIBILITY IDEOGRAPH-F90D;Lo;0;L;61F6;;;;N;;;;;
+F90E;CJK COMPATIBILITY IDEOGRAPH-F90E;Lo;0;L;7669;;;;N;;;;;
+F90F;CJK COMPATIBILITY IDEOGRAPH-F90F;Lo;0;L;7F85;;;;N;;;;;
+F910;CJK COMPATIBILITY IDEOGRAPH-F910;Lo;0;L;863F;;;;N;;;;;
+F911;CJK COMPATIBILITY IDEOGRAPH-F911;Lo;0;L;87BA;;;;N;;;;;
+F912;CJK COMPATIBILITY IDEOGRAPH-F912;Lo;0;L;88F8;;;;N;;;;;
+F913;CJK COMPATIBILITY IDEOGRAPH-F913;Lo;0;L;908F;;;;N;;;;;
+F914;CJK COMPATIBILITY IDEOGRAPH-F914;Lo;0;L;6A02;;;;N;;;;;
+F915;CJK COMPATIBILITY IDEOGRAPH-F915;Lo;0;L;6D1B;;;;N;;;;;
+F916;CJK COMPATIBILITY IDEOGRAPH-F916;Lo;0;L;70D9;;;;N;;;;;
+F917;CJK COMPATIBILITY IDEOGRAPH-F917;Lo;0;L;73DE;;;;N;;;;;
+F918;CJK COMPATIBILITY IDEOGRAPH-F918;Lo;0;L;843D;;;;N;;;;;
+F919;CJK COMPATIBILITY IDEOGRAPH-F919;Lo;0;L;916A;;;;N;;;;;
+F91A;CJK COMPATIBILITY IDEOGRAPH-F91A;Lo;0;L;99F1;;;;N;;;;;
+F91B;CJK COMPATIBILITY IDEOGRAPH-F91B;Lo;0;L;4E82;;;;N;;;;;
+F91C;CJK COMPATIBILITY IDEOGRAPH-F91C;Lo;0;L;5375;;;;N;;;;;
+F91D;CJK COMPATIBILITY IDEOGRAPH-F91D;Lo;0;L;6B04;;;;N;;;;;
+F91E;CJK COMPATIBILITY IDEOGRAPH-F91E;Lo;0;L;721B;;;;N;;;;;
+F91F;CJK COMPATIBILITY IDEOGRAPH-F91F;Lo;0;L;862D;;;;N;;;;;
+F920;CJK COMPATIBILITY IDEOGRAPH-F920;Lo;0;L;9E1E;;;;N;;;;;
+F921;CJK COMPATIBILITY IDEOGRAPH-F921;Lo;0;L;5D50;;;;N;;;;;
+F922;CJK COMPATIBILITY IDEOGRAPH-F922;Lo;0;L;6FEB;;;;N;;;;;
+F923;CJK COMPATIBILITY IDEOGRAPH-F923;Lo;0;L;85CD;;;;N;;;;;
+F924;CJK COMPATIBILITY IDEOGRAPH-F924;Lo;0;L;8964;;;;N;;;;;
+F925;CJK COMPATIBILITY IDEOGRAPH-F925;Lo;0;L;62C9;;;;N;;;;;
+F926;CJK COMPATIBILITY IDEOGRAPH-F926;Lo;0;L;81D8;;;;N;;;;;
+F927;CJK COMPATIBILITY IDEOGRAPH-F927;Lo;0;L;881F;;;;N;;;;;
+F928;CJK COMPATIBILITY IDEOGRAPH-F928;Lo;0;L;5ECA;;;;N;;;;;
+F929;CJK COMPATIBILITY IDEOGRAPH-F929;Lo;0;L;6717;;;;N;;;;;
+F92A;CJK COMPATIBILITY IDEOGRAPH-F92A;Lo;0;L;6D6A;;;;N;;;;;
+F92B;CJK COMPATIBILITY IDEOGRAPH-F92B;Lo;0;L;72FC;;;;N;;;;;
+F92C;CJK COMPATIBILITY IDEOGRAPH-F92C;Lo;0;L;90CE;;;;N;;;;;
+F92D;CJK COMPATIBILITY IDEOGRAPH-F92D;Lo;0;L;4F86;;;;N;;;;;
+F92E;CJK COMPATIBILITY IDEOGRAPH-F92E;Lo;0;L;51B7;;;;N;;;;;
+F92F;CJK COMPATIBILITY IDEOGRAPH-F92F;Lo;0;L;52DE;;;;N;;;;;
+F930;CJK COMPATIBILITY IDEOGRAPH-F930;Lo;0;L;64C4;;;;N;;;;;
+F931;CJK COMPATIBILITY IDEOGRAPH-F931;Lo;0;L;6AD3;;;;N;;;;;
+F932;CJK COMPATIBILITY IDEOGRAPH-F932;Lo;0;L;7210;;;;N;;;;;
+F933;CJK COMPATIBILITY IDEOGRAPH-F933;Lo;0;L;76E7;;;;N;;;;;
+F934;CJK COMPATIBILITY IDEOGRAPH-F934;Lo;0;L;8001;;;;N;;;;;
+F935;CJK COMPATIBILITY IDEOGRAPH-F935;Lo;0;L;8606;;;;N;;;;;
+F936;CJK COMPATIBILITY IDEOGRAPH-F936;Lo;0;L;865C;;;;N;;;;;
+F937;CJK COMPATIBILITY IDEOGRAPH-F937;Lo;0;L;8DEF;;;;N;;;;;
+F938;CJK COMPATIBILITY IDEOGRAPH-F938;Lo;0;L;9732;;;;N;;;;;
+F939;CJK COMPATIBILITY IDEOGRAPH-F939;Lo;0;L;9B6F;;;;N;;;;;
+F93A;CJK COMPATIBILITY IDEOGRAPH-F93A;Lo;0;L;9DFA;;;;N;;;;;
+F93B;CJK COMPATIBILITY IDEOGRAPH-F93B;Lo;0;L;788C;;;;N;;;;;
+F93C;CJK COMPATIBILITY IDEOGRAPH-F93C;Lo;0;L;797F;;;;N;;;;;
+F93D;CJK COMPATIBILITY IDEOGRAPH-F93D;Lo;0;L;7DA0;;;;N;;;;;
+F93E;CJK COMPATIBILITY IDEOGRAPH-F93E;Lo;0;L;83C9;;;;N;;;;;
+F93F;CJK COMPATIBILITY IDEOGRAPH-F93F;Lo;0;L;9304;;;;N;;;;;
+F940;CJK COMPATIBILITY IDEOGRAPH-F940;Lo;0;L;9E7F;;;;N;;;;;
+F941;CJK COMPATIBILITY IDEOGRAPH-F941;Lo;0;L;8AD6;;;;N;;;;;
+F942;CJK COMPATIBILITY IDEOGRAPH-F942;Lo;0;L;58DF;;;;N;;;;;
+F943;CJK COMPATIBILITY IDEOGRAPH-F943;Lo;0;L;5F04;;;;N;;;;;
+F944;CJK COMPATIBILITY IDEOGRAPH-F944;Lo;0;L;7C60;;;;N;;;;;
+F945;CJK COMPATIBILITY IDEOGRAPH-F945;Lo;0;L;807E;;;;N;;;;;
+F946;CJK COMPATIBILITY IDEOGRAPH-F946;Lo;0;L;7262;;;;N;;;;;
+F947;CJK COMPATIBILITY IDEOGRAPH-F947;Lo;0;L;78CA;;;;N;;;;;
+F948;CJK COMPATIBILITY IDEOGRAPH-F948;Lo;0;L;8CC2;;;;N;;;;;
+F949;CJK COMPATIBILITY IDEOGRAPH-F949;Lo;0;L;96F7;;;;N;;;;;
+F94A;CJK COMPATIBILITY IDEOGRAPH-F94A;Lo;0;L;58D8;;;;N;;;;;
+F94B;CJK COMPATIBILITY IDEOGRAPH-F94B;Lo;0;L;5C62;;;;N;;;;;
+F94C;CJK COMPATIBILITY IDEOGRAPH-F94C;Lo;0;L;6A13;;;;N;;;;;
+F94D;CJK COMPATIBILITY IDEOGRAPH-F94D;Lo;0;L;6DDA;;;;N;;;;;
+F94E;CJK COMPATIBILITY IDEOGRAPH-F94E;Lo;0;L;6F0F;;;;N;;;;;
+F94F;CJK COMPATIBILITY IDEOGRAPH-F94F;Lo;0;L;7D2F;;;;N;;;;;
+F950;CJK COMPATIBILITY IDEOGRAPH-F950;Lo;0;L;7E37;;;;N;;;;;
+F951;CJK COMPATIBILITY IDEOGRAPH-F951;Lo;0;L;964B;;;;N;;;;;
+F952;CJK COMPATIBILITY IDEOGRAPH-F952;Lo;0;L;52D2;;;;N;;;;;
+F953;CJK COMPATIBILITY IDEOGRAPH-F953;Lo;0;L;808B;;;;N;;;;;
+F954;CJK COMPATIBILITY IDEOGRAPH-F954;Lo;0;L;51DC;;;;N;;;;;
+F955;CJK COMPATIBILITY IDEOGRAPH-F955;Lo;0;L;51CC;;;;N;;;;;
+F956;CJK COMPATIBILITY IDEOGRAPH-F956;Lo;0;L;7A1C;;;;N;;;;;
+F957;CJK COMPATIBILITY IDEOGRAPH-F957;Lo;0;L;7DBE;;;;N;;;;;
+F958;CJK COMPATIBILITY IDEOGRAPH-F958;Lo;0;L;83F1;;;;N;;;;;
+F959;CJK COMPATIBILITY IDEOGRAPH-F959;Lo;0;L;9675;;;;N;;;;;
+F95A;CJK COMPATIBILITY IDEOGRAPH-F95A;Lo;0;L;8B80;;;;N;;;;;
+F95B;CJK COMPATIBILITY IDEOGRAPH-F95B;Lo;0;L;62CF;;;;N;;;;;
+F95C;CJK COMPATIBILITY IDEOGRAPH-F95C;Lo;0;L;6A02;;;;N;;;;;
+F95D;CJK COMPATIBILITY IDEOGRAPH-F95D;Lo;0;L;8AFE;;;;N;;;;;
+F95E;CJK COMPATIBILITY IDEOGRAPH-F95E;Lo;0;L;4E39;;;;N;;;;;
+F95F;CJK COMPATIBILITY IDEOGRAPH-F95F;Lo;0;L;5BE7;;;;N;;;;;
+F960;CJK COMPATIBILITY IDEOGRAPH-F960;Lo;0;L;6012;;;;N;;;;;
+F961;CJK COMPATIBILITY IDEOGRAPH-F961;Lo;0;L;7387;;;;N;;;;;
+F962;CJK COMPATIBILITY IDEOGRAPH-F962;Lo;0;L;7570;;;;N;;;;;
+F963;CJK COMPATIBILITY IDEOGRAPH-F963;Lo;0;L;5317;;;;N;;;;;
+F964;CJK COMPATIBILITY IDEOGRAPH-F964;Lo;0;L;78FB;;;;N;;;;;
+F965;CJK COMPATIBILITY IDEOGRAPH-F965;Lo;0;L;4FBF;;;;N;;;;;
+F966;CJK COMPATIBILITY IDEOGRAPH-F966;Lo;0;L;5FA9;;;;N;;;;;
+F967;CJK COMPATIBILITY IDEOGRAPH-F967;Lo;0;L;4E0D;;;;N;;;;;
+F968;CJK COMPATIBILITY IDEOGRAPH-F968;Lo;0;L;6CCC;;;;N;;;;;
+F969;CJK COMPATIBILITY IDEOGRAPH-F969;Lo;0;L;6578;;;;N;;;;;
+F96A;CJK COMPATIBILITY IDEOGRAPH-F96A;Lo;0;L;7D22;;;;N;;;;;
+F96B;CJK COMPATIBILITY IDEOGRAPH-F96B;Lo;0;L;53C3;;;;N;;;;;
+F96C;CJK COMPATIBILITY IDEOGRAPH-F96C;Lo;0;L;585E;;;;N;;;;;
+F96D;CJK COMPATIBILITY IDEOGRAPH-F96D;Lo;0;L;7701;;;;N;;;;;
+F96E;CJK COMPATIBILITY IDEOGRAPH-F96E;Lo;0;L;8449;;;;N;;;;;
+F96F;CJK COMPATIBILITY IDEOGRAPH-F96F;Lo;0;L;8AAA;;;;N;;;;;
+F970;CJK COMPATIBILITY IDEOGRAPH-F970;Lo;0;L;6BBA;;;;N;;;;;
+F971;CJK COMPATIBILITY IDEOGRAPH-F971;Lo;0;L;8FB0;;;;N;;;;;
+F972;CJK COMPATIBILITY IDEOGRAPH-F972;Lo;0;L;6C88;;;;N;;;;;
+F973;CJK COMPATIBILITY IDEOGRAPH-F973;Lo;0;L;62FE;;;;N;;;;;
+F974;CJK COMPATIBILITY IDEOGRAPH-F974;Lo;0;L;82E5;;;;N;;;;;
+F975;CJK COMPATIBILITY IDEOGRAPH-F975;Lo;0;L;63A0;;;;N;;;;;
+F976;CJK COMPATIBILITY IDEOGRAPH-F976;Lo;0;L;7565;;;;N;;;;;
+F977;CJK COMPATIBILITY IDEOGRAPH-F977;Lo;0;L;4EAE;;;;N;;;;;
+F978;CJK COMPATIBILITY IDEOGRAPH-F978;Lo;0;L;5169;;;;N;;;;;
+F979;CJK COMPATIBILITY IDEOGRAPH-F979;Lo;0;L;51C9;;;;N;;;;;
+F97A;CJK COMPATIBILITY IDEOGRAPH-F97A;Lo;0;L;6881;;;;N;;;;;
+F97B;CJK COMPATIBILITY IDEOGRAPH-F97B;Lo;0;L;7CE7;;;;N;;;;;
+F97C;CJK COMPATIBILITY IDEOGRAPH-F97C;Lo;0;L;826F;;;;N;;;;;
+F97D;CJK COMPATIBILITY IDEOGRAPH-F97D;Lo;0;L;8AD2;;;;N;;;;;
+F97E;CJK COMPATIBILITY IDEOGRAPH-F97E;Lo;0;L;91CF;;;;N;;;;;
+F97F;CJK COMPATIBILITY IDEOGRAPH-F97F;Lo;0;L;52F5;;;;N;;;;;
+F980;CJK COMPATIBILITY IDEOGRAPH-F980;Lo;0;L;5442;;;;N;;;;;
+F981;CJK COMPATIBILITY IDEOGRAPH-F981;Lo;0;L;5973;;;;N;;;;;
+F982;CJK COMPATIBILITY IDEOGRAPH-F982;Lo;0;L;5EEC;;;;N;;;;;
+F983;CJK COMPATIBILITY IDEOGRAPH-F983;Lo;0;L;65C5;;;;N;;;;;
+F984;CJK COMPATIBILITY IDEOGRAPH-F984;Lo;0;L;6FFE;;;;N;;;;;
+F985;CJK COMPATIBILITY IDEOGRAPH-F985;Lo;0;L;792A;;;;N;;;;;
+F986;CJK COMPATIBILITY IDEOGRAPH-F986;Lo;0;L;95AD;;;;N;;;;;
+F987;CJK COMPATIBILITY IDEOGRAPH-F987;Lo;0;L;9A6A;;;;N;;;;;
+F988;CJK COMPATIBILITY IDEOGRAPH-F988;Lo;0;L;9E97;;;;N;;;;;
+F989;CJK COMPATIBILITY IDEOGRAPH-F989;Lo;0;L;9ECE;;;;N;;;;;
+F98A;CJK COMPATIBILITY IDEOGRAPH-F98A;Lo;0;L;529B;;;;N;;;;;
+F98B;CJK COMPATIBILITY IDEOGRAPH-F98B;Lo;0;L;66C6;;;;N;;;;;
+F98C;CJK COMPATIBILITY IDEOGRAPH-F98C;Lo;0;L;6B77;;;;N;;;;;
+F98D;CJK COMPATIBILITY IDEOGRAPH-F98D;Lo;0;L;8F62;;;;N;;;;;
+F98E;CJK COMPATIBILITY IDEOGRAPH-F98E;Lo;0;L;5E74;;;;N;;;;;
+F98F;CJK COMPATIBILITY IDEOGRAPH-F98F;Lo;0;L;6190;;;;N;;;;;
+F990;CJK COMPATIBILITY IDEOGRAPH-F990;Lo;0;L;6200;;;;N;;;;;
+F991;CJK COMPATIBILITY IDEOGRAPH-F991;Lo;0;L;649A;;;;N;;;;;
+F992;CJK COMPATIBILITY IDEOGRAPH-F992;Lo;0;L;6F23;;;;N;;;;;
+F993;CJK COMPATIBILITY IDEOGRAPH-F993;Lo;0;L;7149;;;;N;;;;;
+F994;CJK COMPATIBILITY IDEOGRAPH-F994;Lo;0;L;7489;;;;N;;;;;
+F995;CJK COMPATIBILITY IDEOGRAPH-F995;Lo;0;L;79CA;;;;N;;;;;
+F996;CJK COMPATIBILITY IDEOGRAPH-F996;Lo;0;L;7DF4;;;;N;;;;;
+F997;CJK COMPATIBILITY IDEOGRAPH-F997;Lo;0;L;806F;;;;N;;;;;
+F998;CJK COMPATIBILITY IDEOGRAPH-F998;Lo;0;L;8F26;;;;N;;;;;
+F999;CJK COMPATIBILITY IDEOGRAPH-F999;Lo;0;L;84EE;;;;N;;;;;
+F99A;CJK COMPATIBILITY IDEOGRAPH-F99A;Lo;0;L;9023;;;;N;;;;;
+F99B;CJK COMPATIBILITY IDEOGRAPH-F99B;Lo;0;L;934A;;;;N;;;;;
+F99C;CJK COMPATIBILITY IDEOGRAPH-F99C;Lo;0;L;5217;;;;N;;;;;
+F99D;CJK COMPATIBILITY IDEOGRAPH-F99D;Lo;0;L;52A3;;;;N;;;;;
+F99E;CJK COMPATIBILITY IDEOGRAPH-F99E;Lo;0;L;54BD;;;;N;;;;;
+F99F;CJK COMPATIBILITY IDEOGRAPH-F99F;Lo;0;L;70C8;;;;N;;;;;
+F9A0;CJK COMPATIBILITY IDEOGRAPH-F9A0;Lo;0;L;88C2;;;;N;;;;;
+F9A1;CJK COMPATIBILITY IDEOGRAPH-F9A1;Lo;0;L;8AAA;;;;N;;;;;
+F9A2;CJK COMPATIBILITY IDEOGRAPH-F9A2;Lo;0;L;5EC9;;;;N;;;;;
+F9A3;CJK COMPATIBILITY IDEOGRAPH-F9A3;Lo;0;L;5FF5;;;;N;;;;;
+F9A4;CJK COMPATIBILITY IDEOGRAPH-F9A4;Lo;0;L;637B;;;;N;;;;;
+F9A5;CJK COMPATIBILITY IDEOGRAPH-F9A5;Lo;0;L;6BAE;;;;N;;;;;
+F9A6;CJK COMPATIBILITY IDEOGRAPH-F9A6;Lo;0;L;7C3E;;;;N;;;;;
+F9A7;CJK COMPATIBILITY IDEOGRAPH-F9A7;Lo;0;L;7375;;;;N;;;;;
+F9A8;CJK COMPATIBILITY IDEOGRAPH-F9A8;Lo;0;L;4EE4;;;;N;;;;;
+F9A9;CJK COMPATIBILITY IDEOGRAPH-F9A9;Lo;0;L;56F9;;;;N;;;;;
+F9AA;CJK COMPATIBILITY IDEOGRAPH-F9AA;Lo;0;L;5BE7;;;;N;;;;;
+F9AB;CJK COMPATIBILITY IDEOGRAPH-F9AB;Lo;0;L;5DBA;;;;N;;;;;
+F9AC;CJK COMPATIBILITY IDEOGRAPH-F9AC;Lo;0;L;601C;;;;N;;;;;
+F9AD;CJK COMPATIBILITY IDEOGRAPH-F9AD;Lo;0;L;73B2;;;;N;;;;;
+F9AE;CJK COMPATIBILITY IDEOGRAPH-F9AE;Lo;0;L;7469;;;;N;;;;;
+F9AF;CJK COMPATIBILITY IDEOGRAPH-F9AF;Lo;0;L;7F9A;;;;N;;;;;
+F9B0;CJK COMPATIBILITY IDEOGRAPH-F9B0;Lo;0;L;8046;;;;N;;;;;
+F9B1;CJK COMPATIBILITY IDEOGRAPH-F9B1;Lo;0;L;9234;;;;N;;;;;
+F9B2;CJK COMPATIBILITY IDEOGRAPH-F9B2;Lo;0;L;96F6;;;;N;;;;;
+F9B3;CJK COMPATIBILITY IDEOGRAPH-F9B3;Lo;0;L;9748;;;;N;;;;;
+F9B4;CJK COMPATIBILITY IDEOGRAPH-F9B4;Lo;0;L;9818;;;;N;;;;;
+F9B5;CJK COMPATIBILITY IDEOGRAPH-F9B5;Lo;0;L;4F8B;;;;N;;;;;
+F9B6;CJK COMPATIBILITY IDEOGRAPH-F9B6;Lo;0;L;79AE;;;;N;;;;;
+F9B7;CJK COMPATIBILITY IDEOGRAPH-F9B7;Lo;0;L;91B4;;;;N;;;;;
+F9B8;CJK COMPATIBILITY IDEOGRAPH-F9B8;Lo;0;L;96B8;;;;N;;;;;
+F9B9;CJK COMPATIBILITY IDEOGRAPH-F9B9;Lo;0;L;60E1;;;;N;;;;;
+F9BA;CJK COMPATIBILITY IDEOGRAPH-F9BA;Lo;0;L;4E86;;;;N;;;;;
+F9BB;CJK COMPATIBILITY IDEOGRAPH-F9BB;Lo;0;L;50DA;;;;N;;;;;
+F9BC;CJK COMPATIBILITY IDEOGRAPH-F9BC;Lo;0;L;5BEE;;;;N;;;;;
+F9BD;CJK COMPATIBILITY IDEOGRAPH-F9BD;Lo;0;L;5C3F;;;;N;;;;;
+F9BE;CJK COMPATIBILITY IDEOGRAPH-F9BE;Lo;0;L;6599;;;;N;;;;;
+F9BF;CJK COMPATIBILITY IDEOGRAPH-F9BF;Lo;0;L;6A02;;;;N;;;;;
+F9C0;CJK COMPATIBILITY IDEOGRAPH-F9C0;Lo;0;L;71CE;;;;N;;;;;
+F9C1;CJK COMPATIBILITY IDEOGRAPH-F9C1;Lo;0;L;7642;;;;N;;;;;
+F9C2;CJK COMPATIBILITY IDEOGRAPH-F9C2;Lo;0;L;84FC;;;;N;;;;;
+F9C3;CJK COMPATIBILITY IDEOGRAPH-F9C3;Lo;0;L;907C;;;;N;;;;;
+F9C4;CJK COMPATIBILITY IDEOGRAPH-F9C4;Lo;0;L;9F8D;;;;N;;;;;
+F9C5;CJK COMPATIBILITY IDEOGRAPH-F9C5;Lo;0;L;6688;;;;N;;;;;
+F9C6;CJK COMPATIBILITY IDEOGRAPH-F9C6;Lo;0;L;962E;;;;N;;;;;
+F9C7;CJK COMPATIBILITY IDEOGRAPH-F9C7;Lo;0;L;5289;;;;N;;;;;
+F9C8;CJK COMPATIBILITY IDEOGRAPH-F9C8;Lo;0;L;677B;;;;N;;;;;
+F9C9;CJK COMPATIBILITY IDEOGRAPH-F9C9;Lo;0;L;67F3;;;;N;;;;;
+F9CA;CJK COMPATIBILITY IDEOGRAPH-F9CA;Lo;0;L;6D41;;;;N;;;;;
+F9CB;CJK COMPATIBILITY IDEOGRAPH-F9CB;Lo;0;L;6E9C;;;;N;;;;;
+F9CC;CJK COMPATIBILITY IDEOGRAPH-F9CC;Lo;0;L;7409;;;;N;;;;;
+F9CD;CJK COMPATIBILITY IDEOGRAPH-F9CD;Lo;0;L;7559;;;;N;;;;;
+F9CE;CJK COMPATIBILITY IDEOGRAPH-F9CE;Lo;0;L;786B;;;;N;;;;;
+F9CF;CJK COMPATIBILITY IDEOGRAPH-F9CF;Lo;0;L;7D10;;;;N;;;;;
+F9D0;CJK COMPATIBILITY IDEOGRAPH-F9D0;Lo;0;L;985E;;;;N;;;;;
+F9D1;CJK COMPATIBILITY IDEOGRAPH-F9D1;Lo;0;L;516D;;;;N;;;;;
+F9D2;CJK COMPATIBILITY IDEOGRAPH-F9D2;Lo;0;L;622E;;;;N;;;;;
+F9D3;CJK COMPATIBILITY IDEOGRAPH-F9D3;Lo;0;L;9678;;;;N;;;;;
+F9D4;CJK COMPATIBILITY IDEOGRAPH-F9D4;Lo;0;L;502B;;;;N;;;;;
+F9D5;CJK COMPATIBILITY IDEOGRAPH-F9D5;Lo;0;L;5D19;;;;N;;;;;
+F9D6;CJK COMPATIBILITY IDEOGRAPH-F9D6;Lo;0;L;6DEA;;;;N;;;;;
+F9D7;CJK COMPATIBILITY IDEOGRAPH-F9D7;Lo;0;L;8F2A;;;;N;;;;;
+F9D8;CJK COMPATIBILITY IDEOGRAPH-F9D8;Lo;0;L;5F8B;;;;N;;;;;
+F9D9;CJK COMPATIBILITY IDEOGRAPH-F9D9;Lo;0;L;6144;;;;N;;;;;
+F9DA;CJK COMPATIBILITY IDEOGRAPH-F9DA;Lo;0;L;6817;;;;N;;;;;
+F9DB;CJK COMPATIBILITY IDEOGRAPH-F9DB;Lo;0;L;7387;;;;N;;;;;
+F9DC;CJK COMPATIBILITY IDEOGRAPH-F9DC;Lo;0;L;9686;;;;N;;;;;
+F9DD;CJK COMPATIBILITY IDEOGRAPH-F9DD;Lo;0;L;5229;;;;N;;;;;
+F9DE;CJK COMPATIBILITY IDEOGRAPH-F9DE;Lo;0;L;540F;;;;N;;;;;
+F9DF;CJK COMPATIBILITY IDEOGRAPH-F9DF;Lo;0;L;5C65;;;;N;;;;;
+F9E0;CJK COMPATIBILITY IDEOGRAPH-F9E0;Lo;0;L;6613;;;;N;;;;;
+F9E1;CJK COMPATIBILITY IDEOGRAPH-F9E1;Lo;0;L;674E;;;;N;;;;;
+F9E2;CJK COMPATIBILITY IDEOGRAPH-F9E2;Lo;0;L;68A8;;;;N;;;;;
+F9E3;CJK COMPATIBILITY IDEOGRAPH-F9E3;Lo;0;L;6CE5;;;;N;;;;;
+F9E4;CJK COMPATIBILITY IDEOGRAPH-F9E4;Lo;0;L;7406;;;;N;;;;;
+F9E5;CJK COMPATIBILITY IDEOGRAPH-F9E5;Lo;0;L;75E2;;;;N;;;;;
+F9E6;CJK COMPATIBILITY IDEOGRAPH-F9E6;Lo;0;L;7F79;;;;N;;;;;
+F9E7;CJK COMPATIBILITY IDEOGRAPH-F9E7;Lo;0;L;88CF;;;;N;;;;;
+F9E8;CJK COMPATIBILITY IDEOGRAPH-F9E8;Lo;0;L;88E1;;;;N;;;;;
+F9E9;CJK COMPATIBILITY IDEOGRAPH-F9E9;Lo;0;L;91CC;;;;N;;;;;
+F9EA;CJK COMPATIBILITY IDEOGRAPH-F9EA;Lo;0;L;96E2;;;;N;;;;;
+F9EB;CJK COMPATIBILITY IDEOGRAPH-F9EB;Lo;0;L;533F;;;;N;;;;;
+F9EC;CJK COMPATIBILITY IDEOGRAPH-F9EC;Lo;0;L;6EBA;;;;N;;;;;
+F9ED;CJK COMPATIBILITY IDEOGRAPH-F9ED;Lo;0;L;541D;;;;N;;;;;
+F9EE;CJK COMPATIBILITY IDEOGRAPH-F9EE;Lo;0;L;71D0;;;;N;;;;;
+F9EF;CJK COMPATIBILITY IDEOGRAPH-F9EF;Lo;0;L;7498;;;;N;;;;;
+F9F0;CJK COMPATIBILITY IDEOGRAPH-F9F0;Lo;0;L;85FA;;;;N;;;;;
+F9F1;CJK COMPATIBILITY IDEOGRAPH-F9F1;Lo;0;L;96A3;;;;N;;;;;
+F9F2;CJK COMPATIBILITY IDEOGRAPH-F9F2;Lo;0;L;9C57;;;;N;;;;;
+F9F3;CJK COMPATIBILITY IDEOGRAPH-F9F3;Lo;0;L;9E9F;;;;N;;;;;
+F9F4;CJK COMPATIBILITY IDEOGRAPH-F9F4;Lo;0;L;6797;;;;N;;;;;
+F9F5;CJK COMPATIBILITY IDEOGRAPH-F9F5;Lo;0;L;6DCB;;;;N;;;;;
+F9F6;CJK COMPATIBILITY IDEOGRAPH-F9F6;Lo;0;L;81E8;;;;N;;;;;
+F9F7;CJK COMPATIBILITY IDEOGRAPH-F9F7;Lo;0;L;7ACB;;;;N;;;;;
+F9F8;CJK COMPATIBILITY IDEOGRAPH-F9F8;Lo;0;L;7B20;;;;N;;;;;
+F9F9;CJK COMPATIBILITY IDEOGRAPH-F9F9;Lo;0;L;7C92;;;;N;;;;;
+F9FA;CJK COMPATIBILITY IDEOGRAPH-F9FA;Lo;0;L;72C0;;;;N;;;;;
+F9FB;CJK COMPATIBILITY IDEOGRAPH-F9FB;Lo;0;L;7099;;;;N;;;;;
+F9FC;CJK COMPATIBILITY IDEOGRAPH-F9FC;Lo;0;L;8B58;;;;N;;;;;
+F9FD;CJK COMPATIBILITY IDEOGRAPH-F9FD;Lo;0;L;4EC0;;;;N;;;;;
+F9FE;CJK COMPATIBILITY IDEOGRAPH-F9FE;Lo;0;L;8336;;;;N;;;;;
+F9FF;CJK COMPATIBILITY IDEOGRAPH-F9FF;Lo;0;L;523A;;;;N;;;;;
+FA00;CJK COMPATIBILITY IDEOGRAPH-FA00;Lo;0;L;5207;;;;N;;;;;
+FA01;CJK COMPATIBILITY IDEOGRAPH-FA01;Lo;0;L;5EA6;;;;N;;;;;
+FA02;CJK COMPATIBILITY IDEOGRAPH-FA02;Lo;0;L;62D3;;;;N;;;;;
+FA03;CJK COMPATIBILITY IDEOGRAPH-FA03;Lo;0;L;7CD6;;;;N;;;;;
+FA04;CJK COMPATIBILITY IDEOGRAPH-FA04;Lo;0;L;5B85;;;;N;;;;;
+FA05;CJK COMPATIBILITY IDEOGRAPH-FA05;Lo;0;L;6D1E;;;;N;;;;;
+FA06;CJK COMPATIBILITY IDEOGRAPH-FA06;Lo;0;L;66B4;;;;N;;;;;
+FA07;CJK COMPATIBILITY IDEOGRAPH-FA07;Lo;0;L;8F3B;;;;N;;;;;
+FA08;CJK COMPATIBILITY IDEOGRAPH-FA08;Lo;0;L;884C;;;;N;;;;;
+FA09;CJK COMPATIBILITY IDEOGRAPH-FA09;Lo;0;L;964D;;;;N;;;;;
+FA0A;CJK COMPATIBILITY IDEOGRAPH-FA0A;Lo;0;L;898B;;;;N;;;;;
+FA0B;CJK COMPATIBILITY IDEOGRAPH-FA0B;Lo;0;L;5ED3;;;;N;;;;;
+FA0C;CJK COMPATIBILITY IDEOGRAPH-FA0C;Lo;0;L;5140;;;;N;;;;;
+FA0D;CJK COMPATIBILITY IDEOGRAPH-FA0D;Lo;0;L;55C0;;;;N;;;;;
+FA0E;CJK COMPATIBILITY IDEOGRAPH-FA0E;Lo;0;L;;;;;N;;;;;
+FA0F;CJK COMPATIBILITY IDEOGRAPH-FA0F;Lo;0;L;;;;;N;;;;;
+FA10;CJK COMPATIBILITY IDEOGRAPH-FA10;Lo;0;L;585A;;;;N;;;;;
+FA11;CJK COMPATIBILITY IDEOGRAPH-FA11;Lo;0;L;;;;;N;;;;;
+FA12;CJK COMPATIBILITY IDEOGRAPH-FA12;Lo;0;L;6674;;;;N;;;;;
+FA13;CJK COMPATIBILITY IDEOGRAPH-FA13;Lo;0;L;;;;;N;;;;;
+FA14;CJK COMPATIBILITY IDEOGRAPH-FA14;Lo;0;L;;;;;N;;;;;
+FA15;CJK COMPATIBILITY IDEOGRAPH-FA15;Lo;0;L;51DE;;;;N;;;;;
+FA16;CJK COMPATIBILITY IDEOGRAPH-FA16;Lo;0;L;732A;;;;N;;;;;
+FA17;CJK COMPATIBILITY IDEOGRAPH-FA17;Lo;0;L;76CA;;;;N;;;;;
+FA18;CJK COMPATIBILITY IDEOGRAPH-FA18;Lo;0;L;793C;;;;N;;;;;
+FA19;CJK COMPATIBILITY IDEOGRAPH-FA19;Lo;0;L;795E;;;;N;;;;;
+FA1A;CJK COMPATIBILITY IDEOGRAPH-FA1A;Lo;0;L;7965;;;;N;;;;;
+FA1B;CJK COMPATIBILITY IDEOGRAPH-FA1B;Lo;0;L;798F;;;;N;;;;;
+FA1C;CJK COMPATIBILITY IDEOGRAPH-FA1C;Lo;0;L;9756;;;;N;;;;;
+FA1D;CJK COMPATIBILITY IDEOGRAPH-FA1D;Lo;0;L;7CBE;;;;N;;;;;
+FA1E;CJK COMPATIBILITY IDEOGRAPH-FA1E;Lo;0;L;7FBD;;;;N;;;;;
+FA1F;CJK COMPATIBILITY IDEOGRAPH-FA1F;Lo;0;L;;;;;N;;*;;;
+FA20;CJK COMPATIBILITY IDEOGRAPH-FA20;Lo;0;L;8612;;;;N;;;;;
+FA21;CJK COMPATIBILITY IDEOGRAPH-FA21;Lo;0;L;;;;;N;;;;;
+FA22;CJK COMPATIBILITY IDEOGRAPH-FA22;Lo;0;L;8AF8;;;;N;;;;;
+FA23;CJK COMPATIBILITY IDEOGRAPH-FA23;Lo;0;L;;;;;N;;*;;;
+FA24;CJK COMPATIBILITY IDEOGRAPH-FA24;Lo;0;L;;;;;N;;;;;
+FA25;CJK COMPATIBILITY IDEOGRAPH-FA25;Lo;0;L;9038;;;;N;;;;;
+FA26;CJK COMPATIBILITY IDEOGRAPH-FA26;Lo;0;L;90FD;;;;N;;;;;
+FA27;CJK COMPATIBILITY IDEOGRAPH-FA27;Lo;0;L;;;;;N;;;;;
+FA28;CJK COMPATIBILITY IDEOGRAPH-FA28;Lo;0;L;;;;;N;;;;;
+FA29;CJK COMPATIBILITY IDEOGRAPH-FA29;Lo;0;L;;;;;N;;;;;
+FA2A;CJK COMPATIBILITY IDEOGRAPH-FA2A;Lo;0;L;98EF;;;;N;;;;;
+FA2B;CJK COMPATIBILITY IDEOGRAPH-FA2B;Lo;0;L;98FC;;;;N;;;;;
+FA2C;CJK COMPATIBILITY IDEOGRAPH-FA2C;Lo;0;L;9928;;;;N;;;;;
+FA2D;CJK COMPATIBILITY IDEOGRAPH-FA2D;Lo;0;L;9DB4;;;;N;;;;;
+FA30;CJK COMPATIBILITY IDEOGRAPH-FA30;Lo;0;L;4FAE;;;;N;;;;;
+FA31;CJK COMPATIBILITY IDEOGRAPH-FA31;Lo;0;L;50E7;;;;N;;;;;
+FA32;CJK COMPATIBILITY IDEOGRAPH-FA32;Lo;0;L;514D;;;;N;;;;;
+FA33;CJK COMPATIBILITY IDEOGRAPH-FA33;Lo;0;L;52C9;;;;N;;;;;
+FA34;CJK COMPATIBILITY IDEOGRAPH-FA34;Lo;0;L;52E4;;;;N;;;;;
+FA35;CJK COMPATIBILITY IDEOGRAPH-FA35;Lo;0;L;5351;;;;N;;;;;
+FA36;CJK COMPATIBILITY IDEOGRAPH-FA36;Lo;0;L;559D;;;;N;;;;;
+FA37;CJK COMPATIBILITY IDEOGRAPH-FA37;Lo;0;L;5606;;;;N;;;;;
+FA38;CJK COMPATIBILITY IDEOGRAPH-FA38;Lo;0;L;5668;;;;N;;;;;
+FA39;CJK COMPATIBILITY IDEOGRAPH-FA39;Lo;0;L;5840;;;;N;;;;;
+FA3A;CJK COMPATIBILITY IDEOGRAPH-FA3A;Lo;0;L;58A8;;;;N;;;;;
+FA3B;CJK COMPATIBILITY IDEOGRAPH-FA3B;Lo;0;L;5C64;;;;N;;;;;
+FA3C;CJK COMPATIBILITY IDEOGRAPH-FA3C;Lo;0;L;5C6E;;;;N;;;;;
+FA3D;CJK COMPATIBILITY IDEOGRAPH-FA3D;Lo;0;L;6094;;;;N;;;;;
+FA3E;CJK COMPATIBILITY IDEOGRAPH-FA3E;Lo;0;L;6168;;;;N;;;;;
+FA3F;CJK COMPATIBILITY IDEOGRAPH-FA3F;Lo;0;L;618E;;;;N;;;;;
+FA40;CJK COMPATIBILITY IDEOGRAPH-FA40;Lo;0;L;61F2;;;;N;;;;;
+FA41;CJK COMPATIBILITY IDEOGRAPH-FA41;Lo;0;L;654F;;;;N;;;;;
+FA42;CJK COMPATIBILITY IDEOGRAPH-FA42;Lo;0;L;65E2;;;;N;;;;;
+FA43;CJK COMPATIBILITY IDEOGRAPH-FA43;Lo;0;L;6691;;;;N;;;;;
+FA44;CJK COMPATIBILITY IDEOGRAPH-FA44;Lo;0;L;6885;;;;N;;;;;
+FA45;CJK COMPATIBILITY IDEOGRAPH-FA45;Lo;0;L;6D77;;;;N;;;;;
+FA46;CJK COMPATIBILITY IDEOGRAPH-FA46;Lo;0;L;6E1A;;;;N;;;;;
+FA47;CJK COMPATIBILITY IDEOGRAPH-FA47;Lo;0;L;6F22;;;;N;;;;;
+FA48;CJK COMPATIBILITY IDEOGRAPH-FA48;Lo;0;L;716E;;;;N;;;;;
+FA49;CJK COMPATIBILITY IDEOGRAPH-FA49;Lo;0;L;722B;;;;N;;;;;
+FA4A;CJK COMPATIBILITY IDEOGRAPH-FA4A;Lo;0;L;7422;;;;N;;;;;
+FA4B;CJK COMPATIBILITY IDEOGRAPH-FA4B;Lo;0;L;7891;;;;N;;;;;
+FA4C;CJK COMPATIBILITY IDEOGRAPH-FA4C;Lo;0;L;793E;;;;N;;;;;
+FA4D;CJK COMPATIBILITY IDEOGRAPH-FA4D;Lo;0;L;7949;;;;N;;;;;
+FA4E;CJK COMPATIBILITY IDEOGRAPH-FA4E;Lo;0;L;7948;;;;N;;;;;
+FA4F;CJK COMPATIBILITY IDEOGRAPH-FA4F;Lo;0;L;7950;;;;N;;;;;
+FA50;CJK COMPATIBILITY IDEOGRAPH-FA50;Lo;0;L;7956;;;;N;;;;;
+FA51;CJK COMPATIBILITY IDEOGRAPH-FA51;Lo;0;L;795D;;;;N;;;;;
+FA52;CJK COMPATIBILITY IDEOGRAPH-FA52;Lo;0;L;798D;;;;N;;;;;
+FA53;CJK COMPATIBILITY IDEOGRAPH-FA53;Lo;0;L;798E;;;;N;;;;;
+FA54;CJK COMPATIBILITY IDEOGRAPH-FA54;Lo;0;L;7A40;;;;N;;;;;
+FA55;CJK COMPATIBILITY IDEOGRAPH-FA55;Lo;0;L;7A81;;;;N;;;;;
+FA56;CJK COMPATIBILITY IDEOGRAPH-FA56;Lo;0;L;7BC0;;;;N;;;;;
+FA57;CJK COMPATIBILITY IDEOGRAPH-FA57;Lo;0;L;7DF4;;;;N;;;;;
+FA58;CJK COMPATIBILITY IDEOGRAPH-FA58;Lo;0;L;7E09;;;;N;;;;;
+FA59;CJK COMPATIBILITY IDEOGRAPH-FA59;Lo;0;L;7E41;;;;N;;;;;
+FA5A;CJK COMPATIBILITY IDEOGRAPH-FA5A;Lo;0;L;7F72;;;;N;;;;;
+FA5B;CJK COMPATIBILITY IDEOGRAPH-FA5B;Lo;0;L;8005;;;;N;;;;;
+FA5C;CJK COMPATIBILITY IDEOGRAPH-FA5C;Lo;0;L;81ED;;;;N;;;;;
+FA5D;CJK COMPATIBILITY IDEOGRAPH-FA5D;Lo;0;L;8279;;;;N;;;;;
+FA5E;CJK COMPATIBILITY IDEOGRAPH-FA5E;Lo;0;L;8279;;;;N;;;;;
+FA5F;CJK COMPATIBILITY IDEOGRAPH-FA5F;Lo;0;L;8457;;;;N;;;;;
+FA60;CJK COMPATIBILITY IDEOGRAPH-FA60;Lo;0;L;8910;;;;N;;;;;
+FA61;CJK COMPATIBILITY IDEOGRAPH-FA61;Lo;0;L;8996;;;;N;;;;;
+FA62;CJK COMPATIBILITY IDEOGRAPH-FA62;Lo;0;L;8B01;;;;N;;;;;
+FA63;CJK COMPATIBILITY IDEOGRAPH-FA63;Lo;0;L;8B39;;;;N;;;;;
+FA64;CJK COMPATIBILITY IDEOGRAPH-FA64;Lo;0;L;8CD3;;;;N;;;;;
+FA65;CJK COMPATIBILITY IDEOGRAPH-FA65;Lo;0;L;8D08;;;;N;;;;;
+FA66;CJK COMPATIBILITY IDEOGRAPH-FA66;Lo;0;L;8FB6;;;;N;;;;;
+FA67;CJK COMPATIBILITY IDEOGRAPH-FA67;Lo;0;L;9038;;;;N;;;;;
+FA68;CJK COMPATIBILITY IDEOGRAPH-FA68;Lo;0;L;96E3;;;;N;;;;;
+FA69;CJK COMPATIBILITY IDEOGRAPH-FA69;Lo;0;L;97FF;;;;N;;;;;
+FA6A;CJK COMPATIBILITY IDEOGRAPH-FA6A;Lo;0;L;983B;;;;N;;;;;
+FB00;LATIN SMALL LIGATURE FF;Ll;0;L;<compat> 0066 0066;;;;N;;;;;
+FB01;LATIN SMALL LIGATURE FI;Ll;0;L;<compat> 0066 0069;;;;N;;;;;
+FB02;LATIN SMALL LIGATURE FL;Ll;0;L;<compat> 0066 006C;;;;N;;;;;
+FB03;LATIN SMALL LIGATURE FFI;Ll;0;L;<compat> 0066 0066 0069;;;;N;;;;;
+FB04;LATIN SMALL LIGATURE FFL;Ll;0;L;<compat> 0066 0066 006C;;;;N;;;;;
+FB05;LATIN SMALL LIGATURE LONG S T;Ll;0;L;<compat> 017F 0074;;;;N;;;;;
+FB06;LATIN SMALL LIGATURE ST;Ll;0;L;<compat> 0073 0074;;;;N;;;;;
+FB13;ARMENIAN SMALL LIGATURE MEN NOW;Ll;0;L;<compat> 0574 0576;;;;N;;;;;
+FB14;ARMENIAN SMALL LIGATURE MEN ECH;Ll;0;L;<compat> 0574 0565;;;;N;;;;;
+FB15;ARMENIAN SMALL LIGATURE MEN INI;Ll;0;L;<compat> 0574 056B;;;;N;;;;;
+FB16;ARMENIAN SMALL LIGATURE VEW NOW;Ll;0;L;<compat> 057E 0576;;;;N;;;;;
+FB17;ARMENIAN SMALL LIGATURE MEN XEH;Ll;0;L;<compat> 0574 056D;;;;N;;;;;
+FB1D;HEBREW LETTER YOD WITH HIRIQ;Lo;0;R;05D9 05B4;;;;N;;;;;
+FB1E;HEBREW POINT JUDEO-SPANISH VARIKA;Mn;26;NSM;;;;;N;HEBREW POINT VARIKA;;;;
+FB1F;HEBREW LIGATURE YIDDISH YOD YOD PATAH;Lo;0;R;05F2 05B7;;;;N;;;;;
+FB20;HEBREW LETTER ALTERNATIVE AYIN;Lo;0;R;<font> 05E2;;;;N;;;;;
+FB21;HEBREW LETTER WIDE ALEF;Lo;0;R;<font> 05D0;;;;N;;;;;
+FB22;HEBREW LETTER WIDE DALET;Lo;0;R;<font> 05D3;;;;N;;;;;
+FB23;HEBREW LETTER WIDE HE;Lo;0;R;<font> 05D4;;;;N;;;;;
+FB24;HEBREW LETTER WIDE KAF;Lo;0;R;<font> 05DB;;;;N;;;;;
+FB25;HEBREW LETTER WIDE LAMED;Lo;0;R;<font> 05DC;;;;N;;;;;
+FB26;HEBREW LETTER WIDE FINAL MEM;Lo;0;R;<font> 05DD;;;;N;;;;;
+FB27;HEBREW LETTER WIDE RESH;Lo;0;R;<font> 05E8;;;;N;;;;;
+FB28;HEBREW LETTER WIDE TAV;Lo;0;R;<font> 05EA;;;;N;;;;;
+FB29;HEBREW LETTER ALTERNATIVE PLUS SIGN;Sm;0;ET;<font> 002B;;;;N;;;;;
+FB2A;HEBREW LETTER SHIN WITH SHIN DOT;Lo;0;R;05E9 05C1;;;;N;;;;;
+FB2B;HEBREW LETTER SHIN WITH SIN DOT;Lo;0;R;05E9 05C2;;;;N;;;;;
+FB2C;HEBREW LETTER SHIN WITH DAGESH AND SHIN DOT;Lo;0;R;FB49 05C1;;;;N;;;;;
+FB2D;HEBREW LETTER SHIN WITH DAGESH AND SIN DOT;Lo;0;R;FB49 05C2;;;;N;;;;;
+FB2E;HEBREW LETTER ALEF WITH PATAH;Lo;0;R;05D0 05B7;;;;N;;;;;
+FB2F;HEBREW LETTER ALEF WITH QAMATS;Lo;0;R;05D0 05B8;;;;N;;;;;
+FB30;HEBREW LETTER ALEF WITH MAPIQ;Lo;0;R;05D0 05BC;;;;N;;;;;
+FB31;HEBREW LETTER BET WITH DAGESH;Lo;0;R;05D1 05BC;;;;N;;;;;
+FB32;HEBREW LETTER GIMEL WITH DAGESH;Lo;0;R;05D2 05BC;;;;N;;;;;
+FB33;HEBREW LETTER DALET WITH DAGESH;Lo;0;R;05D3 05BC;;;;N;;;;;
+FB34;HEBREW LETTER HE WITH MAPIQ;Lo;0;R;05D4 05BC;;;;N;;;;;
+FB35;HEBREW LETTER VAV WITH DAGESH;Lo;0;R;05D5 05BC;;;;N;;;;;
+FB36;HEBREW LETTER ZAYIN WITH DAGESH;Lo;0;R;05D6 05BC;;;;N;;;;;
+FB38;HEBREW LETTER TET WITH DAGESH;Lo;0;R;05D8 05BC;;;;N;;;;;
+FB39;HEBREW LETTER YOD WITH DAGESH;Lo;0;R;05D9 05BC;;;;N;;;;;
+FB3A;HEBREW LETTER FINAL KAF WITH DAGESH;Lo;0;R;05DA 05BC;;;;N;;;;;
+FB3B;HEBREW LETTER KAF WITH DAGESH;Lo;0;R;05DB 05BC;;;;N;;;;;
+FB3C;HEBREW LETTER LAMED WITH DAGESH;Lo;0;R;05DC 05BC;;;;N;;;;;
+FB3E;HEBREW LETTER MEM WITH DAGESH;Lo;0;R;05DE 05BC;;;;N;;;;;
+FB40;HEBREW LETTER NUN WITH DAGESH;Lo;0;R;05E0 05BC;;;;N;;;;;
+FB41;HEBREW LETTER SAMEKH WITH DAGESH;Lo;0;R;05E1 05BC;;;;N;;;;;
+FB43;HEBREW LETTER FINAL PE WITH DAGESH;Lo;0;R;05E3 05BC;;;;N;;;;;
+FB44;HEBREW LETTER PE WITH DAGESH;Lo;0;R;05E4 05BC;;;;N;;;;;
+FB46;HEBREW LETTER TSADI WITH DAGESH;Lo;0;R;05E6 05BC;;;;N;;;;;
+FB47;HEBREW LETTER QOF WITH DAGESH;Lo;0;R;05E7 05BC;;;;N;;;;;
+FB48;HEBREW LETTER RESH WITH DAGESH;Lo;0;R;05E8 05BC;;;;N;;;;;
+FB49;HEBREW LETTER SHIN WITH DAGESH;Lo;0;R;05E9 05BC;;;;N;;;;;
+FB4A;HEBREW LETTER TAV WITH DAGESH;Lo;0;R;05EA 05BC;;;;N;;;;;
+FB4B;HEBREW LETTER VAV WITH HOLAM;Lo;0;R;05D5 05B9;;;;N;;;;;
+FB4C;HEBREW LETTER BET WITH RAFE;Lo;0;R;05D1 05BF;;;;N;;;;;
+FB4D;HEBREW LETTER KAF WITH RAFE;Lo;0;R;05DB 05BF;;;;N;;;;;
+FB4E;HEBREW LETTER PE WITH RAFE;Lo;0;R;05E4 05BF;;;;N;;;;;
+FB4F;HEBREW LIGATURE ALEF LAMED;Lo;0;R;<compat> 05D0 05DC;;;;N;;;;;
+FB50;ARABIC LETTER ALEF WASLA ISOLATED FORM;Lo;0;AL;<isolated> 0671;;;;N;;;;;
+FB51;ARABIC LETTER ALEF WASLA FINAL FORM;Lo;0;AL;<final> 0671;;;;N;;;;;
+FB52;ARABIC LETTER BEEH ISOLATED FORM;Lo;0;AL;<isolated> 067B;;;;N;;;;;
+FB53;ARABIC LETTER BEEH FINAL FORM;Lo;0;AL;<final> 067B;;;;N;;;;;
+FB54;ARABIC LETTER BEEH INITIAL FORM;Lo;0;AL;<initial> 067B;;;;N;;;;;
+FB55;ARABIC LETTER BEEH MEDIAL FORM;Lo;0;AL;<medial> 067B;;;;N;;;;;
+FB56;ARABIC LETTER PEH ISOLATED FORM;Lo;0;AL;<isolated> 067E;;;;N;;;;;
+FB57;ARABIC LETTER PEH FINAL FORM;Lo;0;AL;<final> 067E;;;;N;;;;;
+FB58;ARABIC LETTER PEH INITIAL FORM;Lo;0;AL;<initial> 067E;;;;N;;;;;
+FB59;ARABIC LETTER PEH MEDIAL FORM;Lo;0;AL;<medial> 067E;;;;N;;;;;
+FB5A;ARABIC LETTER BEHEH ISOLATED FORM;Lo;0;AL;<isolated> 0680;;;;N;;;;;
+FB5B;ARABIC LETTER BEHEH FINAL FORM;Lo;0;AL;<final> 0680;;;;N;;;;;
+FB5C;ARABIC LETTER BEHEH INITIAL FORM;Lo;0;AL;<initial> 0680;;;;N;;;;;
+FB5D;ARABIC LETTER BEHEH MEDIAL FORM;Lo;0;AL;<medial> 0680;;;;N;;;;;
+FB5E;ARABIC LETTER TTEHEH ISOLATED FORM;Lo;0;AL;<isolated> 067A;;;;N;;;;;
+FB5F;ARABIC LETTER TTEHEH FINAL FORM;Lo;0;AL;<final> 067A;;;;N;;;;;
+FB60;ARABIC LETTER TTEHEH INITIAL FORM;Lo;0;AL;<initial> 067A;;;;N;;;;;
+FB61;ARABIC LETTER TTEHEH MEDIAL FORM;Lo;0;AL;<medial> 067A;;;;N;;;;;
+FB62;ARABIC LETTER TEHEH ISOLATED FORM;Lo;0;AL;<isolated> 067F;;;;N;;;;;
+FB63;ARABIC LETTER TEHEH FINAL FORM;Lo;0;AL;<final> 067F;;;;N;;;;;
+FB64;ARABIC LETTER TEHEH INITIAL FORM;Lo;0;AL;<initial> 067F;;;;N;;;;;
+FB65;ARABIC LETTER TEHEH MEDIAL FORM;Lo;0;AL;<medial> 067F;;;;N;;;;;
+FB66;ARABIC LETTER TTEH ISOLATED FORM;Lo;0;AL;<isolated> 0679;;;;N;;;;;
+FB67;ARABIC LETTER TTEH FINAL FORM;Lo;0;AL;<final> 0679;;;;N;;;;;
+FB68;ARABIC LETTER TTEH INITIAL FORM;Lo;0;AL;<initial> 0679;;;;N;;;;;
+FB69;ARABIC LETTER TTEH MEDIAL FORM;Lo;0;AL;<medial> 0679;;;;N;;;;;
+FB6A;ARABIC LETTER VEH ISOLATED FORM;Lo;0;AL;<isolated> 06A4;;;;N;;;;;
+FB6B;ARABIC LETTER VEH FINAL FORM;Lo;0;AL;<final> 06A4;;;;N;;;;;
+FB6C;ARABIC LETTER VEH INITIAL FORM;Lo;0;AL;<initial> 06A4;;;;N;;;;;
+FB6D;ARABIC LETTER VEH MEDIAL FORM;Lo;0;AL;<medial> 06A4;;;;N;;;;;
+FB6E;ARABIC LETTER PEHEH ISOLATED FORM;Lo;0;AL;<isolated> 06A6;;;;N;;;;;
+FB6F;ARABIC LETTER PEHEH FINAL FORM;Lo;0;AL;<final> 06A6;;;;N;;;;;
+FB70;ARABIC LETTER PEHEH INITIAL FORM;Lo;0;AL;<initial> 06A6;;;;N;;;;;
+FB71;ARABIC LETTER PEHEH MEDIAL FORM;Lo;0;AL;<medial> 06A6;;;;N;;;;;
+FB72;ARABIC LETTER DYEH ISOLATED FORM;Lo;0;AL;<isolated> 0684;;;;N;;;;;
+FB73;ARABIC LETTER DYEH FINAL FORM;Lo;0;AL;<final> 0684;;;;N;;;;;
+FB74;ARABIC LETTER DYEH INITIAL FORM;Lo;0;AL;<initial> 0684;;;;N;;;;;
+FB75;ARABIC LETTER DYEH MEDIAL FORM;Lo;0;AL;<medial> 0684;;;;N;;;;;
+FB76;ARABIC LETTER NYEH ISOLATED FORM;Lo;0;AL;<isolated> 0683;;;;N;;;;;
+FB77;ARABIC LETTER NYEH FINAL FORM;Lo;0;AL;<final> 0683;;;;N;;;;;
+FB78;ARABIC LETTER NYEH INITIAL FORM;Lo;0;AL;<initial> 0683;;;;N;;;;;
+FB79;ARABIC LETTER NYEH MEDIAL FORM;Lo;0;AL;<medial> 0683;;;;N;;;;;
+FB7A;ARABIC LETTER TCHEH ISOLATED FORM;Lo;0;AL;<isolated> 0686;;;;N;;;;;
+FB7B;ARABIC LETTER TCHEH FINAL FORM;Lo;0;AL;<final> 0686;;;;N;;;;;
+FB7C;ARABIC LETTER TCHEH INITIAL FORM;Lo;0;AL;<initial> 0686;;;;N;;;;;
+FB7D;ARABIC LETTER TCHEH MEDIAL FORM;Lo;0;AL;<medial> 0686;;;;N;;;;;
+FB7E;ARABIC LETTER TCHEHEH ISOLATED FORM;Lo;0;AL;<isolated> 0687;;;;N;;;;;
+FB7F;ARABIC LETTER TCHEHEH FINAL FORM;Lo;0;AL;<final> 0687;;;;N;;;;;
+FB80;ARABIC LETTER TCHEHEH INITIAL FORM;Lo;0;AL;<initial> 0687;;;;N;;;;;
+FB81;ARABIC LETTER TCHEHEH MEDIAL FORM;Lo;0;AL;<medial> 0687;;;;N;;;;;
+FB82;ARABIC LETTER DDAHAL ISOLATED FORM;Lo;0;AL;<isolated> 068D;;;;N;;;;;
+FB83;ARABIC LETTER DDAHAL FINAL FORM;Lo;0;AL;<final> 068D;;;;N;;;;;
+FB84;ARABIC LETTER DAHAL ISOLATED FORM;Lo;0;AL;<isolated> 068C;;;;N;;;;;
+FB85;ARABIC LETTER DAHAL FINAL FORM;Lo;0;AL;<final> 068C;;;;N;;;;;
+FB86;ARABIC LETTER DUL ISOLATED FORM;Lo;0;AL;<isolated> 068E;;;;N;;;;;
+FB87;ARABIC LETTER DUL FINAL FORM;Lo;0;AL;<final> 068E;;;;N;;;;;
+FB88;ARABIC LETTER DDAL ISOLATED FORM;Lo;0;AL;<isolated> 0688;;;;N;;;;;
+FB89;ARABIC LETTER DDAL FINAL FORM;Lo;0;AL;<final> 0688;;;;N;;;;;
+FB8A;ARABIC LETTER JEH ISOLATED FORM;Lo;0;AL;<isolated> 0698;;;;N;;;;;
+FB8B;ARABIC LETTER JEH FINAL FORM;Lo;0;AL;<final> 0698;;;;N;;;;;
+FB8C;ARABIC LETTER RREH ISOLATED FORM;Lo;0;AL;<isolated> 0691;;;;N;;;;;
+FB8D;ARABIC LETTER RREH FINAL FORM;Lo;0;AL;<final> 0691;;;;N;;;;;
+FB8E;ARABIC LETTER KEHEH ISOLATED FORM;Lo;0;AL;<isolated> 06A9;;;;N;;;;;
+FB8F;ARABIC LETTER KEHEH FINAL FORM;Lo;0;AL;<final> 06A9;;;;N;;;;;
+FB90;ARABIC LETTER KEHEH INITIAL FORM;Lo;0;AL;<initial> 06A9;;;;N;;;;;
+FB91;ARABIC LETTER KEHEH MEDIAL FORM;Lo;0;AL;<medial> 06A9;;;;N;;;;;
+FB92;ARABIC LETTER GAF ISOLATED FORM;Lo;0;AL;<isolated> 06AF;;;;N;;;;;
+FB93;ARABIC LETTER GAF FINAL FORM;Lo;0;AL;<final> 06AF;;;;N;;;;;
+FB94;ARABIC LETTER GAF INITIAL FORM;Lo;0;AL;<initial> 06AF;;;;N;;;;;
+FB95;ARABIC LETTER GAF MEDIAL FORM;Lo;0;AL;<medial> 06AF;;;;N;;;;;
+FB96;ARABIC LETTER GUEH ISOLATED FORM;Lo;0;AL;<isolated> 06B3;;;;N;;;;;
+FB97;ARABIC LETTER GUEH FINAL FORM;Lo;0;AL;<final> 06B3;;;;N;;;;;
+FB98;ARABIC LETTER GUEH INITIAL FORM;Lo;0;AL;<initial> 06B3;;;;N;;;;;
+FB99;ARABIC LETTER GUEH MEDIAL FORM;Lo;0;AL;<medial> 06B3;;;;N;;;;;
+FB9A;ARABIC LETTER NGOEH ISOLATED FORM;Lo;0;AL;<isolated> 06B1;;;;N;;;;;
+FB9B;ARABIC LETTER NGOEH FINAL FORM;Lo;0;AL;<final> 06B1;;;;N;;;;;
+FB9C;ARABIC LETTER NGOEH INITIAL FORM;Lo;0;AL;<initial> 06B1;;;;N;;;;;
+FB9D;ARABIC LETTER NGOEH MEDIAL FORM;Lo;0;AL;<medial> 06B1;;;;N;;;;;
+FB9E;ARABIC LETTER NOON GHUNNA ISOLATED FORM;Lo;0;AL;<isolated> 06BA;;;;N;;;;;
+FB9F;ARABIC LETTER NOON GHUNNA FINAL FORM;Lo;0;AL;<final> 06BA;;;;N;;;;;
+FBA0;ARABIC LETTER RNOON ISOLATED FORM;Lo;0;AL;<isolated> 06BB;;;;N;;;;;
+FBA1;ARABIC LETTER RNOON FINAL FORM;Lo;0;AL;<final> 06BB;;;;N;;;;;
+FBA2;ARABIC LETTER RNOON INITIAL FORM;Lo;0;AL;<initial> 06BB;;;;N;;;;;
+FBA3;ARABIC LETTER RNOON MEDIAL FORM;Lo;0;AL;<medial> 06BB;;;;N;;;;;
+FBA4;ARABIC LETTER HEH WITH YEH ABOVE ISOLATED FORM;Lo;0;AL;<isolated> 06C0;;;;N;;;;;
+FBA5;ARABIC LETTER HEH WITH YEH ABOVE FINAL FORM;Lo;0;AL;<final> 06C0;;;;N;;;;;
+FBA6;ARABIC LETTER HEH GOAL ISOLATED FORM;Lo;0;AL;<isolated> 06C1;;;;N;;;;;
+FBA7;ARABIC LETTER HEH GOAL FINAL FORM;Lo;0;AL;<final> 06C1;;;;N;;;;;
+FBA8;ARABIC LETTER HEH GOAL INITIAL FORM;Lo;0;AL;<initial> 06C1;;;;N;;;;;
+FBA9;ARABIC LETTER HEH GOAL MEDIAL FORM;Lo;0;AL;<medial> 06C1;;;;N;;;;;
+FBAA;ARABIC LETTER HEH DOACHASHMEE ISOLATED FORM;Lo;0;AL;<isolated> 06BE;;;;N;;;;;
+FBAB;ARABIC LETTER HEH DOACHASHMEE FINAL FORM;Lo;0;AL;<final> 06BE;;;;N;;;;;
+FBAC;ARABIC LETTER HEH DOACHASHMEE INITIAL FORM;Lo;0;AL;<initial> 06BE;;;;N;;;;;
+FBAD;ARABIC LETTER HEH DOACHASHMEE MEDIAL FORM;Lo;0;AL;<medial> 06BE;;;;N;;;;;
+FBAE;ARABIC LETTER YEH BARREE ISOLATED FORM;Lo;0;AL;<isolated> 06D2;;;;N;;;;;
+FBAF;ARABIC LETTER YEH BARREE FINAL FORM;Lo;0;AL;<final> 06D2;;;;N;;;;;
+FBB0;ARABIC LETTER YEH BARREE WITH HAMZA ABOVE ISOLATED FORM;Lo;0;AL;<isolated> 06D3;;;;N;;;;;
+FBB1;ARABIC LETTER YEH BARREE WITH HAMZA ABOVE FINAL FORM;Lo;0;AL;<final> 06D3;;;;N;;;;;
+FBD3;ARABIC LETTER NG ISOLATED FORM;Lo;0;AL;<isolated> 06AD;;;;N;;;;;
+FBD4;ARABIC LETTER NG FINAL FORM;Lo;0;AL;<final> 06AD;;;;N;;;;;
+FBD5;ARABIC LETTER NG INITIAL FORM;Lo;0;AL;<initial> 06AD;;;;N;;;;;
+FBD6;ARABIC LETTER NG MEDIAL FORM;Lo;0;AL;<medial> 06AD;;;;N;;;;;
+FBD7;ARABIC LETTER U ISOLATED FORM;Lo;0;AL;<isolated> 06C7;;;;N;;;;;
+FBD8;ARABIC LETTER U FINAL FORM;Lo;0;AL;<final> 06C7;;;;N;;;;;
+FBD9;ARABIC LETTER OE ISOLATED FORM;Lo;0;AL;<isolated> 06C6;;;;N;;;;;
+FBDA;ARABIC LETTER OE FINAL FORM;Lo;0;AL;<final> 06C6;;;;N;;;;;
+FBDB;ARABIC LETTER YU ISOLATED FORM;Lo;0;AL;<isolated> 06C8;;;;N;;;;;
+FBDC;ARABIC LETTER YU FINAL FORM;Lo;0;AL;<final> 06C8;;;;N;;;;;
+FBDD;ARABIC LETTER U WITH HAMZA ABOVE ISOLATED FORM;Lo;0;AL;<isolated> 0677;;;;N;;;;;
+FBDE;ARABIC LETTER VE ISOLATED FORM;Lo;0;AL;<isolated> 06CB;;;;N;;;;;
+FBDF;ARABIC LETTER VE FINAL FORM;Lo;0;AL;<final> 06CB;;;;N;;;;;
+FBE0;ARABIC LETTER KIRGHIZ OE ISOLATED FORM;Lo;0;AL;<isolated> 06C5;;;;N;;;;;
+FBE1;ARABIC LETTER KIRGHIZ OE FINAL FORM;Lo;0;AL;<final> 06C5;;;;N;;;;;
+FBE2;ARABIC LETTER KIRGHIZ YU ISOLATED FORM;Lo;0;AL;<isolated> 06C9;;;;N;;;;;
+FBE3;ARABIC LETTER KIRGHIZ YU FINAL FORM;Lo;0;AL;<final> 06C9;;;;N;;;;;
+FBE4;ARABIC LETTER E ISOLATED FORM;Lo;0;AL;<isolated> 06D0;;;;N;;;;;
+FBE5;ARABIC LETTER E FINAL FORM;Lo;0;AL;<final> 06D0;;;;N;;;;;
+FBE6;ARABIC LETTER E INITIAL FORM;Lo;0;AL;<initial> 06D0;;;;N;;;;;
+FBE7;ARABIC LETTER E MEDIAL FORM;Lo;0;AL;<medial> 06D0;;;;N;;;;;
+FBE8;ARABIC LETTER UIGHUR KAZAKH KIRGHIZ ALEF MAKSURA INITIAL FORM;Lo;0;AL;<initial> 0649;;;;N;;;;;
+FBE9;ARABIC LETTER UIGHUR KAZAKH KIRGHIZ ALEF MAKSURA MEDIAL FORM;Lo;0;AL;<medial> 0649;;;;N;;;;;
+FBEA;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF ISOLATED FORM;Lo;0;AL;<isolated> 0626 0627;;;;N;;;;;
+FBEB;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF FINAL FORM;Lo;0;AL;<final> 0626 0627;;;;N;;;;;
+FBEC;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH AE ISOLATED FORM;Lo;0;AL;<isolated> 0626 06D5;;;;N;;;;;
+FBED;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH AE FINAL FORM;Lo;0;AL;<final> 0626 06D5;;;;N;;;;;
+FBEE;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH WAW ISOLATED FORM;Lo;0;AL;<isolated> 0626 0648;;;;N;;;;;
+FBEF;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH WAW FINAL FORM;Lo;0;AL;<final> 0626 0648;;;;N;;;;;
+FBF0;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH U ISOLATED FORM;Lo;0;AL;<isolated> 0626 06C7;;;;N;;;;;
+FBF1;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH U FINAL FORM;Lo;0;AL;<final> 0626 06C7;;;;N;;;;;
+FBF2;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH OE ISOLATED FORM;Lo;0;AL;<isolated> 0626 06C6;;;;N;;;;;
+FBF3;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH OE FINAL FORM;Lo;0;AL;<final> 0626 06C6;;;;N;;;;;
+FBF4;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH YU ISOLATED FORM;Lo;0;AL;<isolated> 0626 06C8;;;;N;;;;;
+FBF5;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH YU FINAL FORM;Lo;0;AL;<final> 0626 06C8;;;;N;;;;;
+FBF6;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH E ISOLATED FORM;Lo;0;AL;<isolated> 0626 06D0;;;;N;;;;;
+FBF7;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH E FINAL FORM;Lo;0;AL;<final> 0626 06D0;;;;N;;;;;
+FBF8;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH E INITIAL FORM;Lo;0;AL;<initial> 0626 06D0;;;;N;;;;;
+FBF9;ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH HAMZA ABOVE WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0626 0649;;;;N;;;;;
+FBFA;ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH HAMZA ABOVE WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0626 0649;;;;N;;;;;
+FBFB;ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH HAMZA ABOVE WITH ALEF MAKSURA INITIAL FORM;Lo;0;AL;<initial> 0626 0649;;;;N;;;;;
+FBFC;ARABIC LETTER FARSI YEH ISOLATED FORM;Lo;0;AL;<isolated> 06CC;;;;N;;;;;
+FBFD;ARABIC LETTER FARSI YEH FINAL FORM;Lo;0;AL;<final> 06CC;;;;N;;;;;
+FBFE;ARABIC LETTER FARSI YEH INITIAL FORM;Lo;0;AL;<initial> 06CC;;;;N;;;;;
+FBFF;ARABIC LETTER FARSI YEH MEDIAL FORM;Lo;0;AL;<medial> 06CC;;;;N;;;;;
+FC00;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 0626 062C;;;;N;;;;;
+FC01;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 0626 062D;;;;N;;;;;
+FC02;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0626 0645;;;;N;;;;;
+FC03;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0626 0649;;;;N;;;;;
+FC04;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0626 064A;;;;N;;;;;
+FC05;ARABIC LIGATURE BEH WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 0628 062C;;;;N;;;;;
+FC06;ARABIC LIGATURE BEH WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 0628 062D;;;;N;;;;;
+FC07;ARABIC LIGATURE BEH WITH KHAH ISOLATED FORM;Lo;0;AL;<isolated> 0628 062E;;;;N;;;;;
+FC08;ARABIC LIGATURE BEH WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0628 0645;;;;N;;;;;
+FC09;ARABIC LIGATURE BEH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0628 0649;;;;N;;;;;
+FC0A;ARABIC LIGATURE BEH WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0628 064A;;;;N;;;;;
+FC0B;ARABIC LIGATURE TEH WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 062A 062C;;;;N;;;;;
+FC0C;ARABIC LIGATURE TEH WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 062A 062D;;;;N;;;;;
+FC0D;ARABIC LIGATURE TEH WITH KHAH ISOLATED FORM;Lo;0;AL;<isolated> 062A 062E;;;;N;;;;;
+FC0E;ARABIC LIGATURE TEH WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 062A 0645;;;;N;;;;;
+FC0F;ARABIC LIGATURE TEH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 062A 0649;;;;N;;;;;
+FC10;ARABIC LIGATURE TEH WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 062A 064A;;;;N;;;;;
+FC11;ARABIC LIGATURE THEH WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 062B 062C;;;;N;;;;;
+FC12;ARABIC LIGATURE THEH WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 062B 0645;;;;N;;;;;
+FC13;ARABIC LIGATURE THEH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 062B 0649;;;;N;;;;;
+FC14;ARABIC LIGATURE THEH WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 062B 064A;;;;N;;;;;
+FC15;ARABIC LIGATURE JEEM WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 062C 062D;;;;N;;;;;
+FC16;ARABIC LIGATURE JEEM WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 062C 0645;;;;N;;;;;
+FC17;ARABIC LIGATURE HAH WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 062D 062C;;;;N;;;;;
+FC18;ARABIC LIGATURE HAH WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 062D 0645;;;;N;;;;;
+FC19;ARABIC LIGATURE KHAH WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 062E 062C;;;;N;;;;;
+FC1A;ARABIC LIGATURE KHAH WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 062E 062D;;;;N;;;;;
+FC1B;ARABIC LIGATURE KHAH WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 062E 0645;;;;N;;;;;
+FC1C;ARABIC LIGATURE SEEN WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 0633 062C;;;;N;;;;;
+FC1D;ARABIC LIGATURE SEEN WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 0633 062D;;;;N;;;;;
+FC1E;ARABIC LIGATURE SEEN WITH KHAH ISOLATED FORM;Lo;0;AL;<isolated> 0633 062E;;;;N;;;;;
+FC1F;ARABIC LIGATURE SEEN WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0633 0645;;;;N;;;;;
+FC20;ARABIC LIGATURE SAD WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 0635 062D;;;;N;;;;;
+FC21;ARABIC LIGATURE SAD WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0635 0645;;;;N;;;;;
+FC22;ARABIC LIGATURE DAD WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 0636 062C;;;;N;;;;;
+FC23;ARABIC LIGATURE DAD WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 0636 062D;;;;N;;;;;
+FC24;ARABIC LIGATURE DAD WITH KHAH ISOLATED FORM;Lo;0;AL;<isolated> 0636 062E;;;;N;;;;;
+FC25;ARABIC LIGATURE DAD WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0636 0645;;;;N;;;;;
+FC26;ARABIC LIGATURE TAH WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 0637 062D;;;;N;;;;;
+FC27;ARABIC LIGATURE TAH WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0637 0645;;;;N;;;;;
+FC28;ARABIC LIGATURE ZAH WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0638 0645;;;;N;;;;;
+FC29;ARABIC LIGATURE AIN WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 0639 062C;;;;N;;;;;
+FC2A;ARABIC LIGATURE AIN WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0639 0645;;;;N;;;;;
+FC2B;ARABIC LIGATURE GHAIN WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 063A 062C;;;;N;;;;;
+FC2C;ARABIC LIGATURE GHAIN WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 063A 0645;;;;N;;;;;
+FC2D;ARABIC LIGATURE FEH WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 0641 062C;;;;N;;;;;
+FC2E;ARABIC LIGATURE FEH WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 0641 062D;;;;N;;;;;
+FC2F;ARABIC LIGATURE FEH WITH KHAH ISOLATED FORM;Lo;0;AL;<isolated> 0641 062E;;;;N;;;;;
+FC30;ARABIC LIGATURE FEH WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0641 0645;;;;N;;;;;
+FC31;ARABIC LIGATURE FEH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0641 0649;;;;N;;;;;
+FC32;ARABIC LIGATURE FEH WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0641 064A;;;;N;;;;;
+FC33;ARABIC LIGATURE QAF WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 0642 062D;;;;N;;;;;
+FC34;ARABIC LIGATURE QAF WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0642 0645;;;;N;;;;;
+FC35;ARABIC LIGATURE QAF WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0642 0649;;;;N;;;;;
+FC36;ARABIC LIGATURE QAF WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0642 064A;;;;N;;;;;
+FC37;ARABIC LIGATURE KAF WITH ALEF ISOLATED FORM;Lo;0;AL;<isolated> 0643 0627;;;;N;;;;;
+FC38;ARABIC LIGATURE KAF WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 0643 062C;;;;N;;;;;
+FC39;ARABIC LIGATURE KAF WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 0643 062D;;;;N;;;;;
+FC3A;ARABIC LIGATURE KAF WITH KHAH ISOLATED FORM;Lo;0;AL;<isolated> 0643 062E;;;;N;;;;;
+FC3B;ARABIC LIGATURE KAF WITH LAM ISOLATED FORM;Lo;0;AL;<isolated> 0643 0644;;;;N;;;;;
+FC3C;ARABIC LIGATURE KAF WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0643 0645;;;;N;;;;;
+FC3D;ARABIC LIGATURE KAF WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0643 0649;;;;N;;;;;
+FC3E;ARABIC LIGATURE KAF WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0643 064A;;;;N;;;;;
+FC3F;ARABIC LIGATURE LAM WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 0644 062C;;;;N;;;;;
+FC40;ARABIC LIGATURE LAM WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 0644 062D;;;;N;;;;;
+FC41;ARABIC LIGATURE LAM WITH KHAH ISOLATED FORM;Lo;0;AL;<isolated> 0644 062E;;;;N;;;;;
+FC42;ARABIC LIGATURE LAM WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0644 0645;;;;N;;;;;
+FC43;ARABIC LIGATURE LAM WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0644 0649;;;;N;;;;;
+FC44;ARABIC LIGATURE LAM WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0644 064A;;;;N;;;;;
+FC45;ARABIC LIGATURE MEEM WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 0645 062C;;;;N;;;;;
+FC46;ARABIC LIGATURE MEEM WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 0645 062D;;;;N;;;;;
+FC47;ARABIC LIGATURE MEEM WITH KHAH ISOLATED FORM;Lo;0;AL;<isolated> 0645 062E;;;;N;;;;;
+FC48;ARABIC LIGATURE MEEM WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0645 0645;;;;N;;;;;
+FC49;ARABIC LIGATURE MEEM WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0645 0649;;;;N;;;;;
+FC4A;ARABIC LIGATURE MEEM WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0645 064A;;;;N;;;;;
+FC4B;ARABIC LIGATURE NOON WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 0646 062C;;;;N;;;;;
+FC4C;ARABIC LIGATURE NOON WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 0646 062D;;;;N;;;;;
+FC4D;ARABIC LIGATURE NOON WITH KHAH ISOLATED FORM;Lo;0;AL;<isolated> 0646 062E;;;;N;;;;;
+FC4E;ARABIC LIGATURE NOON WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0646 0645;;;;N;;;;;
+FC4F;ARABIC LIGATURE NOON WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0646 0649;;;;N;;;;;
+FC50;ARABIC LIGATURE NOON WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0646 064A;;;;N;;;;;
+FC51;ARABIC LIGATURE HEH WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 0647 062C;;;;N;;;;;
+FC52;ARABIC LIGATURE HEH WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0647 0645;;;;N;;;;;
+FC53;ARABIC LIGATURE HEH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0647 0649;;;;N;;;;;
+FC54;ARABIC LIGATURE HEH WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0647 064A;;;;N;;;;;
+FC55;ARABIC LIGATURE YEH WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 064A 062C;;;;N;;;;;
+FC56;ARABIC LIGATURE YEH WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 064A 062D;;;;N;;;;;
+FC57;ARABIC LIGATURE YEH WITH KHAH ISOLATED FORM;Lo;0;AL;<isolated> 064A 062E;;;;N;;;;;
+FC58;ARABIC LIGATURE YEH WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 064A 0645;;;;N;;;;;
+FC59;ARABIC LIGATURE YEH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 064A 0649;;;;N;;;;;
+FC5A;ARABIC LIGATURE YEH WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 064A 064A;;;;N;;;;;
+FC5B;ARABIC LIGATURE THAL WITH SUPERSCRIPT ALEF ISOLATED FORM;Lo;0;AL;<isolated> 0630 0670;;;;N;;;;;
+FC5C;ARABIC LIGATURE REH WITH SUPERSCRIPT ALEF ISOLATED FORM;Lo;0;AL;<isolated> 0631 0670;;;;N;;;;;
+FC5D;ARABIC LIGATURE ALEF MAKSURA WITH SUPERSCRIPT ALEF ISOLATED FORM;Lo;0;AL;<isolated> 0649 0670;;;;N;;;;;
+FC5E;ARABIC LIGATURE SHADDA WITH DAMMATAN ISOLATED FORM;Lo;0;AL;<isolated> 0020 064C 0651;;;;N;;;;;
+FC5F;ARABIC LIGATURE SHADDA WITH KASRATAN ISOLATED FORM;Lo;0;AL;<isolated> 0020 064D 0651;;;;N;;;;;
+FC60;ARABIC LIGATURE SHADDA WITH FATHA ISOLATED FORM;Lo;0;AL;<isolated> 0020 064E 0651;;;;N;;;;;
+FC61;ARABIC LIGATURE SHADDA WITH DAMMA ISOLATED FORM;Lo;0;AL;<isolated> 0020 064F 0651;;;;N;;;;;
+FC62;ARABIC LIGATURE SHADDA WITH KASRA ISOLATED FORM;Lo;0;AL;<isolated> 0020 0650 0651;;;;N;;;;;
+FC63;ARABIC LIGATURE SHADDA WITH SUPERSCRIPT ALEF ISOLATED FORM;Lo;0;AL;<isolated> 0020 0651 0670;;;;N;;;;;
+FC64;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH REH FINAL FORM;Lo;0;AL;<final> 0626 0631;;;;N;;;;;
+FC65;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ZAIN FINAL FORM;Lo;0;AL;<final> 0626 0632;;;;N;;;;;
+FC66;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH MEEM FINAL FORM;Lo;0;AL;<final> 0626 0645;;;;N;;;;;
+FC67;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH NOON FINAL FORM;Lo;0;AL;<final> 0626 0646;;;;N;;;;;
+FC68;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0626 0649;;;;N;;;;;
+FC69;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH YEH FINAL FORM;Lo;0;AL;<final> 0626 064A;;;;N;;;;;
+FC6A;ARABIC LIGATURE BEH WITH REH FINAL FORM;Lo;0;AL;<final> 0628 0631;;;;N;;;;;
+FC6B;ARABIC LIGATURE BEH WITH ZAIN FINAL FORM;Lo;0;AL;<final> 0628 0632;;;;N;;;;;
+FC6C;ARABIC LIGATURE BEH WITH MEEM FINAL FORM;Lo;0;AL;<final> 0628 0645;;;;N;;;;;
+FC6D;ARABIC LIGATURE BEH WITH NOON FINAL FORM;Lo;0;AL;<final> 0628 0646;;;;N;;;;;
+FC6E;ARABIC LIGATURE BEH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0628 0649;;;;N;;;;;
+FC6F;ARABIC LIGATURE BEH WITH YEH FINAL FORM;Lo;0;AL;<final> 0628 064A;;;;N;;;;;
+FC70;ARABIC LIGATURE TEH WITH REH FINAL FORM;Lo;0;AL;<final> 062A 0631;;;;N;;;;;
+FC71;ARABIC LIGATURE TEH WITH ZAIN FINAL FORM;Lo;0;AL;<final> 062A 0632;;;;N;;;;;
+FC72;ARABIC LIGATURE TEH WITH MEEM FINAL FORM;Lo;0;AL;<final> 062A 0645;;;;N;;;;;
+FC73;ARABIC LIGATURE TEH WITH NOON FINAL FORM;Lo;0;AL;<final> 062A 0646;;;;N;;;;;
+FC74;ARABIC LIGATURE TEH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 062A 0649;;;;N;;;;;
+FC75;ARABIC LIGATURE TEH WITH YEH FINAL FORM;Lo;0;AL;<final> 062A 064A;;;;N;;;;;
+FC76;ARABIC LIGATURE THEH WITH REH FINAL FORM;Lo;0;AL;<final> 062B 0631;;;;N;;;;;
+FC77;ARABIC LIGATURE THEH WITH ZAIN FINAL FORM;Lo;0;AL;<final> 062B 0632;;;;N;;;;;
+FC78;ARABIC LIGATURE THEH WITH MEEM FINAL FORM;Lo;0;AL;<final> 062B 0645;;;;N;;;;;
+FC79;ARABIC LIGATURE THEH WITH NOON FINAL FORM;Lo;0;AL;<final> 062B 0646;;;;N;;;;;
+FC7A;ARABIC LIGATURE THEH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 062B 0649;;;;N;;;;;
+FC7B;ARABIC LIGATURE THEH WITH YEH FINAL FORM;Lo;0;AL;<final> 062B 064A;;;;N;;;;;
+FC7C;ARABIC LIGATURE FEH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0641 0649;;;;N;;;;;
+FC7D;ARABIC LIGATURE FEH WITH YEH FINAL FORM;Lo;0;AL;<final> 0641 064A;;;;N;;;;;
+FC7E;ARABIC LIGATURE QAF WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0642 0649;;;;N;;;;;
+FC7F;ARABIC LIGATURE QAF WITH YEH FINAL FORM;Lo;0;AL;<final> 0642 064A;;;;N;;;;;
+FC80;ARABIC LIGATURE KAF WITH ALEF FINAL FORM;Lo;0;AL;<final> 0643 0627;;;;N;;;;;
+FC81;ARABIC LIGATURE KAF WITH LAM FINAL FORM;Lo;0;AL;<final> 0643 0644;;;;N;;;;;
+FC82;ARABIC LIGATURE KAF WITH MEEM FINAL FORM;Lo;0;AL;<final> 0643 0645;;;;N;;;;;
+FC83;ARABIC LIGATURE KAF WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0643 0649;;;;N;;;;;
+FC84;ARABIC LIGATURE KAF WITH YEH FINAL FORM;Lo;0;AL;<final> 0643 064A;;;;N;;;;;
+FC85;ARABIC LIGATURE LAM WITH MEEM FINAL FORM;Lo;0;AL;<final> 0644 0645;;;;N;;;;;
+FC86;ARABIC LIGATURE LAM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0644 0649;;;;N;;;;;
+FC87;ARABIC LIGATURE LAM WITH YEH FINAL FORM;Lo;0;AL;<final> 0644 064A;;;;N;;;;;
+FC88;ARABIC LIGATURE MEEM WITH ALEF FINAL FORM;Lo;0;AL;<final> 0645 0627;;;;N;;;;;
+FC89;ARABIC LIGATURE MEEM WITH MEEM FINAL FORM;Lo;0;AL;<final> 0645 0645;;;;N;;;;;
+FC8A;ARABIC LIGATURE NOON WITH REH FINAL FORM;Lo;0;AL;<final> 0646 0631;;;;N;;;;;
+FC8B;ARABIC LIGATURE NOON WITH ZAIN FINAL FORM;Lo;0;AL;<final> 0646 0632;;;;N;;;;;
+FC8C;ARABIC LIGATURE NOON WITH MEEM FINAL FORM;Lo;0;AL;<final> 0646 0645;;;;N;;;;;
+FC8D;ARABIC LIGATURE NOON WITH NOON FINAL FORM;Lo;0;AL;<final> 0646 0646;;;;N;;;;;
+FC8E;ARABIC LIGATURE NOON WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0646 0649;;;;N;;;;;
+FC8F;ARABIC LIGATURE NOON WITH YEH FINAL FORM;Lo;0;AL;<final> 0646 064A;;;;N;;;;;
+FC90;ARABIC LIGATURE ALEF MAKSURA WITH SUPERSCRIPT ALEF FINAL FORM;Lo;0;AL;<final> 0649 0670;;;;N;;;;;
+FC91;ARABIC LIGATURE YEH WITH REH FINAL FORM;Lo;0;AL;<final> 064A 0631;;;;N;;;;;
+FC92;ARABIC LIGATURE YEH WITH ZAIN FINAL FORM;Lo;0;AL;<final> 064A 0632;;;;N;;;;;
+FC93;ARABIC LIGATURE YEH WITH MEEM FINAL FORM;Lo;0;AL;<final> 064A 0645;;;;N;;;;;
+FC94;ARABIC LIGATURE YEH WITH NOON FINAL FORM;Lo;0;AL;<final> 064A 0646;;;;N;;;;;
+FC95;ARABIC LIGATURE YEH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 064A 0649;;;;N;;;;;
+FC96;ARABIC LIGATURE YEH WITH YEH FINAL FORM;Lo;0;AL;<final> 064A 064A;;;;N;;;;;
+FC97;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0626 062C;;;;N;;;;;
+FC98;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0626 062D;;;;N;;;;;
+FC99;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 0626 062E;;;;N;;;;;
+FC9A;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0626 0645;;;;N;;;;;
+FC9B;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH HEH INITIAL FORM;Lo;0;AL;<initial> 0626 0647;;;;N;;;;;
+FC9C;ARABIC LIGATURE BEH WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0628 062C;;;;N;;;;;
+FC9D;ARABIC LIGATURE BEH WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0628 062D;;;;N;;;;;
+FC9E;ARABIC LIGATURE BEH WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 0628 062E;;;;N;;;;;
+FC9F;ARABIC LIGATURE BEH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0628 0645;;;;N;;;;;
+FCA0;ARABIC LIGATURE BEH WITH HEH INITIAL FORM;Lo;0;AL;<initial> 0628 0647;;;;N;;;;;
+FCA1;ARABIC LIGATURE TEH WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 062A 062C;;;;N;;;;;
+FCA2;ARABIC LIGATURE TEH WITH HAH INITIAL FORM;Lo;0;AL;<initial> 062A 062D;;;;N;;;;;
+FCA3;ARABIC LIGATURE TEH WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 062A 062E;;;;N;;;;;
+FCA4;ARABIC LIGATURE TEH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 062A 0645;;;;N;;;;;
+FCA5;ARABIC LIGATURE TEH WITH HEH INITIAL FORM;Lo;0;AL;<initial> 062A 0647;;;;N;;;;;
+FCA6;ARABIC LIGATURE THEH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 062B 0645;;;;N;;;;;
+FCA7;ARABIC LIGATURE JEEM WITH HAH INITIAL FORM;Lo;0;AL;<initial> 062C 062D;;;;N;;;;;
+FCA8;ARABIC LIGATURE JEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 062C 0645;;;;N;;;;;
+FCA9;ARABIC LIGATURE HAH WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 062D 062C;;;;N;;;;;
+FCAA;ARABIC LIGATURE HAH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 062D 0645;;;;N;;;;;
+FCAB;ARABIC LIGATURE KHAH WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 062E 062C;;;;N;;;;;
+FCAC;ARABIC LIGATURE KHAH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 062E 0645;;;;N;;;;;
+FCAD;ARABIC LIGATURE SEEN WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0633 062C;;;;N;;;;;
+FCAE;ARABIC LIGATURE SEEN WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0633 062D;;;;N;;;;;
+FCAF;ARABIC LIGATURE SEEN WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 0633 062E;;;;N;;;;;
+FCB0;ARABIC LIGATURE SEEN WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0633 0645;;;;N;;;;;
+FCB1;ARABIC LIGATURE SAD WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0635 062D;;;;N;;;;;
+FCB2;ARABIC LIGATURE SAD WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 0635 062E;;;;N;;;;;
+FCB3;ARABIC LIGATURE SAD WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0635 0645;;;;N;;;;;
+FCB4;ARABIC LIGATURE DAD WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0636 062C;;;;N;;;;;
+FCB5;ARABIC LIGATURE DAD WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0636 062D;;;;N;;;;;
+FCB6;ARABIC LIGATURE DAD WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 0636 062E;;;;N;;;;;
+FCB7;ARABIC LIGATURE DAD WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0636 0645;;;;N;;;;;
+FCB8;ARABIC LIGATURE TAH WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0637 062D;;;;N;;;;;
+FCB9;ARABIC LIGATURE ZAH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0638 0645;;;;N;;;;;
+FCBA;ARABIC LIGATURE AIN WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0639 062C;;;;N;;;;;
+FCBB;ARABIC LIGATURE AIN WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0639 0645;;;;N;;;;;
+FCBC;ARABIC LIGATURE GHAIN WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 063A 062C;;;;N;;;;;
+FCBD;ARABIC LIGATURE GHAIN WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 063A 0645;;;;N;;;;;
+FCBE;ARABIC LIGATURE FEH WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0641 062C;;;;N;;;;;
+FCBF;ARABIC LIGATURE FEH WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0641 062D;;;;N;;;;;
+FCC0;ARABIC LIGATURE FEH WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 0641 062E;;;;N;;;;;
+FCC1;ARABIC LIGATURE FEH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0641 0645;;;;N;;;;;
+FCC2;ARABIC LIGATURE QAF WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0642 062D;;;;N;;;;;
+FCC3;ARABIC LIGATURE QAF WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0642 0645;;;;N;;;;;
+FCC4;ARABIC LIGATURE KAF WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0643 062C;;;;N;;;;;
+FCC5;ARABIC LIGATURE KAF WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0643 062D;;;;N;;;;;
+FCC6;ARABIC LIGATURE KAF WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 0643 062E;;;;N;;;;;
+FCC7;ARABIC LIGATURE KAF WITH LAM INITIAL FORM;Lo;0;AL;<initial> 0643 0644;;;;N;;;;;
+FCC8;ARABIC LIGATURE KAF WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0643 0645;;;;N;;;;;
+FCC9;ARABIC LIGATURE LAM WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0644 062C;;;;N;;;;;
+FCCA;ARABIC LIGATURE LAM WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0644 062D;;;;N;;;;;
+FCCB;ARABIC LIGATURE LAM WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 0644 062E;;;;N;;;;;
+FCCC;ARABIC LIGATURE LAM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0644 0645;;;;N;;;;;
+FCCD;ARABIC LIGATURE LAM WITH HEH INITIAL FORM;Lo;0;AL;<initial> 0644 0647;;;;N;;;;;
+FCCE;ARABIC LIGATURE MEEM WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0645 062C;;;;N;;;;;
+FCCF;ARABIC LIGATURE MEEM WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0645 062D;;;;N;;;;;
+FCD0;ARABIC LIGATURE MEEM WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 0645 062E;;;;N;;;;;
+FCD1;ARABIC LIGATURE MEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0645 0645;;;;N;;;;;
+FCD2;ARABIC LIGATURE NOON WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0646 062C;;;;N;;;;;
+FCD3;ARABIC LIGATURE NOON WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0646 062D;;;;N;;;;;
+FCD4;ARABIC LIGATURE NOON WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 0646 062E;;;;N;;;;;
+FCD5;ARABIC LIGATURE NOON WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0646 0645;;;;N;;;;;
+FCD6;ARABIC LIGATURE NOON WITH HEH INITIAL FORM;Lo;0;AL;<initial> 0646 0647;;;;N;;;;;
+FCD7;ARABIC LIGATURE HEH WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0647 062C;;;;N;;;;;
+FCD8;ARABIC LIGATURE HEH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0647 0645;;;;N;;;;;
+FCD9;ARABIC LIGATURE HEH WITH SUPERSCRIPT ALEF INITIAL FORM;Lo;0;AL;<initial> 0647 0670;;;;N;;;;;
+FCDA;ARABIC LIGATURE YEH WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 064A 062C;;;;N;;;;;
+FCDB;ARABIC LIGATURE YEH WITH HAH INITIAL FORM;Lo;0;AL;<initial> 064A 062D;;;;N;;;;;
+FCDC;ARABIC LIGATURE YEH WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 064A 062E;;;;N;;;;;
+FCDD;ARABIC LIGATURE YEH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 064A 0645;;;;N;;;;;
+FCDE;ARABIC LIGATURE YEH WITH HEH INITIAL FORM;Lo;0;AL;<initial> 064A 0647;;;;N;;;;;
+FCDF;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH MEEM MEDIAL FORM;Lo;0;AL;<medial> 0626 0645;;;;N;;;;;
+FCE0;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH HEH MEDIAL FORM;Lo;0;AL;<medial> 0626 0647;;;;N;;;;;
+FCE1;ARABIC LIGATURE BEH WITH MEEM MEDIAL FORM;Lo;0;AL;<medial> 0628 0645;;;;N;;;;;
+FCE2;ARABIC LIGATURE BEH WITH HEH MEDIAL FORM;Lo;0;AL;<medial> 0628 0647;;;;N;;;;;
+FCE3;ARABIC LIGATURE TEH WITH MEEM MEDIAL FORM;Lo;0;AL;<medial> 062A 0645;;;;N;;;;;
+FCE4;ARABIC LIGATURE TEH WITH HEH MEDIAL FORM;Lo;0;AL;<medial> 062A 0647;;;;N;;;;;
+FCE5;ARABIC LIGATURE THEH WITH MEEM MEDIAL FORM;Lo;0;AL;<medial> 062B 0645;;;;N;;;;;
+FCE6;ARABIC LIGATURE THEH WITH HEH MEDIAL FORM;Lo;0;AL;<medial> 062B 0647;;;;N;;;;;
+FCE7;ARABIC LIGATURE SEEN WITH MEEM MEDIAL FORM;Lo;0;AL;<medial> 0633 0645;;;;N;;;;;
+FCE8;ARABIC LIGATURE SEEN WITH HEH MEDIAL FORM;Lo;0;AL;<medial> 0633 0647;;;;N;;;;;
+FCE9;ARABIC LIGATURE SHEEN WITH MEEM MEDIAL FORM;Lo;0;AL;<medial> 0634 0645;;;;N;;;;;
+FCEA;ARABIC LIGATURE SHEEN WITH HEH MEDIAL FORM;Lo;0;AL;<medial> 0634 0647;;;;N;;;;;
+FCEB;ARABIC LIGATURE KAF WITH LAM MEDIAL FORM;Lo;0;AL;<medial> 0643 0644;;;;N;;;;;
+FCEC;ARABIC LIGATURE KAF WITH MEEM MEDIAL FORM;Lo;0;AL;<medial> 0643 0645;;;;N;;;;;
+FCED;ARABIC LIGATURE LAM WITH MEEM MEDIAL FORM;Lo;0;AL;<medial> 0644 0645;;;;N;;;;;
+FCEE;ARABIC LIGATURE NOON WITH MEEM MEDIAL FORM;Lo;0;AL;<medial> 0646 0645;;;;N;;;;;
+FCEF;ARABIC LIGATURE NOON WITH HEH MEDIAL FORM;Lo;0;AL;<medial> 0646 0647;;;;N;;;;;
+FCF0;ARABIC LIGATURE YEH WITH MEEM MEDIAL FORM;Lo;0;AL;<medial> 064A 0645;;;;N;;;;;
+FCF1;ARABIC LIGATURE YEH WITH HEH MEDIAL FORM;Lo;0;AL;<medial> 064A 0647;;;;N;;;;;
+FCF2;ARABIC LIGATURE SHADDA WITH FATHA MEDIAL FORM;Lo;0;AL;<medial> 0640 064E 0651;;;;N;;;;;
+FCF3;ARABIC LIGATURE SHADDA WITH DAMMA MEDIAL FORM;Lo;0;AL;<medial> 0640 064F 0651;;;;N;;;;;
+FCF4;ARABIC LIGATURE SHADDA WITH KASRA MEDIAL FORM;Lo;0;AL;<medial> 0640 0650 0651;;;;N;;;;;
+FCF5;ARABIC LIGATURE TAH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0637 0649;;;;N;;;;;
+FCF6;ARABIC LIGATURE TAH WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0637 064A;;;;N;;;;;
+FCF7;ARABIC LIGATURE AIN WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0639 0649;;;;N;;;;;
+FCF8;ARABIC LIGATURE AIN WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0639 064A;;;;N;;;;;
+FCF9;ARABIC LIGATURE GHAIN WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 063A 0649;;;;N;;;;;
+FCFA;ARABIC LIGATURE GHAIN WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 063A 064A;;;;N;;;;;
+FCFB;ARABIC LIGATURE SEEN WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0633 0649;;;;N;;;;;
+FCFC;ARABIC LIGATURE SEEN WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0633 064A;;;;N;;;;;
+FCFD;ARABIC LIGATURE SHEEN WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0634 0649;;;;N;;;;;
+FCFE;ARABIC LIGATURE SHEEN WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0634 064A;;;;N;;;;;
+FCFF;ARABIC LIGATURE HAH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 062D 0649;;;;N;;;;;
+FD00;ARABIC LIGATURE HAH WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 062D 064A;;;;N;;;;;
+FD01;ARABIC LIGATURE JEEM WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 062C 0649;;;;N;;;;;
+FD02;ARABIC LIGATURE JEEM WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 062C 064A;;;;N;;;;;
+FD03;ARABIC LIGATURE KHAH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 062E 0649;;;;N;;;;;
+FD04;ARABIC LIGATURE KHAH WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 062E 064A;;;;N;;;;;
+FD05;ARABIC LIGATURE SAD WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0635 0649;;;;N;;;;;
+FD06;ARABIC LIGATURE SAD WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0635 064A;;;;N;;;;;
+FD07;ARABIC LIGATURE DAD WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0636 0649;;;;N;;;;;
+FD08;ARABIC LIGATURE DAD WITH YEH ISOLATED FORM;Lo;0;AL;<isolated> 0636 064A;;;;N;;;;;
+FD09;ARABIC LIGATURE SHEEN WITH JEEM ISOLATED FORM;Lo;0;AL;<isolated> 0634 062C;;;;N;;;;;
+FD0A;ARABIC LIGATURE SHEEN WITH HAH ISOLATED FORM;Lo;0;AL;<isolated> 0634 062D;;;;N;;;;;
+FD0B;ARABIC LIGATURE SHEEN WITH KHAH ISOLATED FORM;Lo;0;AL;<isolated> 0634 062E;;;;N;;;;;
+FD0C;ARABIC LIGATURE SHEEN WITH MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0634 0645;;;;N;;;;;
+FD0D;ARABIC LIGATURE SHEEN WITH REH ISOLATED FORM;Lo;0;AL;<isolated> 0634 0631;;;;N;;;;;
+FD0E;ARABIC LIGATURE SEEN WITH REH ISOLATED FORM;Lo;0;AL;<isolated> 0633 0631;;;;N;;;;;
+FD0F;ARABIC LIGATURE SAD WITH REH ISOLATED FORM;Lo;0;AL;<isolated> 0635 0631;;;;N;;;;;
+FD10;ARABIC LIGATURE DAD WITH REH ISOLATED FORM;Lo;0;AL;<isolated> 0636 0631;;;;N;;;;;
+FD11;ARABIC LIGATURE TAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0637 0649;;;;N;;;;;
+FD12;ARABIC LIGATURE TAH WITH YEH FINAL FORM;Lo;0;AL;<final> 0637 064A;;;;N;;;;;
+FD13;ARABIC LIGATURE AIN WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0639 0649;;;;N;;;;;
+FD14;ARABIC LIGATURE AIN WITH YEH FINAL FORM;Lo;0;AL;<final> 0639 064A;;;;N;;;;;
+FD15;ARABIC LIGATURE GHAIN WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 063A 0649;;;;N;;;;;
+FD16;ARABIC LIGATURE GHAIN WITH YEH FINAL FORM;Lo;0;AL;<final> 063A 064A;;;;N;;;;;
+FD17;ARABIC LIGATURE SEEN WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0633 0649;;;;N;;;;;
+FD18;ARABIC LIGATURE SEEN WITH YEH FINAL FORM;Lo;0;AL;<final> 0633 064A;;;;N;;;;;
+FD19;ARABIC LIGATURE SHEEN WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0634 0649;;;;N;;;;;
+FD1A;ARABIC LIGATURE SHEEN WITH YEH FINAL FORM;Lo;0;AL;<final> 0634 064A;;;;N;;;;;
+FD1B;ARABIC LIGATURE HAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 062D 0649;;;;N;;;;;
+FD1C;ARABIC LIGATURE HAH WITH YEH FINAL FORM;Lo;0;AL;<final> 062D 064A;;;;N;;;;;
+FD1D;ARABIC LIGATURE JEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 062C 0649;;;;N;;;;;
+FD1E;ARABIC LIGATURE JEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 062C 064A;;;;N;;;;;
+FD1F;ARABIC LIGATURE KHAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 062E 0649;;;;N;;;;;
+FD20;ARABIC LIGATURE KHAH WITH YEH FINAL FORM;Lo;0;AL;<final> 062E 064A;;;;N;;;;;
+FD21;ARABIC LIGATURE SAD WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0635 0649;;;;N;;;;;
+FD22;ARABIC LIGATURE SAD WITH YEH FINAL FORM;Lo;0;AL;<final> 0635 064A;;;;N;;;;;
+FD23;ARABIC LIGATURE DAD WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0636 0649;;;;N;;;;;
+FD24;ARABIC LIGATURE DAD WITH YEH FINAL FORM;Lo;0;AL;<final> 0636 064A;;;;N;;;;;
+FD25;ARABIC LIGATURE SHEEN WITH JEEM FINAL FORM;Lo;0;AL;<final> 0634 062C;;;;N;;;;;
+FD26;ARABIC LIGATURE SHEEN WITH HAH FINAL FORM;Lo;0;AL;<final> 0634 062D;;;;N;;;;;
+FD27;ARABIC LIGATURE SHEEN WITH KHAH FINAL FORM;Lo;0;AL;<final> 0634 062E;;;;N;;;;;
+FD28;ARABIC LIGATURE SHEEN WITH MEEM FINAL FORM;Lo;0;AL;<final> 0634 0645;;;;N;;;;;
+FD29;ARABIC LIGATURE SHEEN WITH REH FINAL FORM;Lo;0;AL;<final> 0634 0631;;;;N;;;;;
+FD2A;ARABIC LIGATURE SEEN WITH REH FINAL FORM;Lo;0;AL;<final> 0633 0631;;;;N;;;;;
+FD2B;ARABIC LIGATURE SAD WITH REH FINAL FORM;Lo;0;AL;<final> 0635 0631;;;;N;;;;;
+FD2C;ARABIC LIGATURE DAD WITH REH FINAL FORM;Lo;0;AL;<final> 0636 0631;;;;N;;;;;
+FD2D;ARABIC LIGATURE SHEEN WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0634 062C;;;;N;;;;;
+FD2E;ARABIC LIGATURE SHEEN WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0634 062D;;;;N;;;;;
+FD2F;ARABIC LIGATURE SHEEN WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 0634 062E;;;;N;;;;;
+FD30;ARABIC LIGATURE SHEEN WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0634 0645;;;;N;;;;;
+FD31;ARABIC LIGATURE SEEN WITH HEH INITIAL FORM;Lo;0;AL;<initial> 0633 0647;;;;N;;;;;
+FD32;ARABIC LIGATURE SHEEN WITH HEH INITIAL FORM;Lo;0;AL;<initial> 0634 0647;;;;N;;;;;
+FD33;ARABIC LIGATURE TAH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0637 0645;;;;N;;;;;
+FD34;ARABIC LIGATURE SEEN WITH JEEM MEDIAL FORM;Lo;0;AL;<medial> 0633 062C;;;;N;;;;;
+FD35;ARABIC LIGATURE SEEN WITH HAH MEDIAL FORM;Lo;0;AL;<medial> 0633 062D;;;;N;;;;;
+FD36;ARABIC LIGATURE SEEN WITH KHAH MEDIAL FORM;Lo;0;AL;<medial> 0633 062E;;;;N;;;;;
+FD37;ARABIC LIGATURE SHEEN WITH JEEM MEDIAL FORM;Lo;0;AL;<medial> 0634 062C;;;;N;;;;;
+FD38;ARABIC LIGATURE SHEEN WITH HAH MEDIAL FORM;Lo;0;AL;<medial> 0634 062D;;;;N;;;;;
+FD39;ARABIC LIGATURE SHEEN WITH KHAH MEDIAL FORM;Lo;0;AL;<medial> 0634 062E;;;;N;;;;;
+FD3A;ARABIC LIGATURE TAH WITH MEEM MEDIAL FORM;Lo;0;AL;<medial> 0637 0645;;;;N;;;;;
+FD3B;ARABIC LIGATURE ZAH WITH MEEM MEDIAL FORM;Lo;0;AL;<medial> 0638 0645;;;;N;;;;;
+FD3C;ARABIC LIGATURE ALEF WITH FATHATAN FINAL FORM;Lo;0;AL;<final> 0627 064B;;;;N;;;;;
+FD3D;ARABIC LIGATURE ALEF WITH FATHATAN ISOLATED FORM;Lo;0;AL;<isolated> 0627 064B;;;;N;;;;;
+FD3E;ORNATE LEFT PARENTHESIS;Ps;0;ON;;;;;N;;;;;
+FD3F;ORNATE RIGHT PARENTHESIS;Pe;0;ON;;;;;N;;;;;
+FD50;ARABIC LIGATURE TEH WITH JEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 062A 062C 0645;;;;N;;;;;
+FD51;ARABIC LIGATURE TEH WITH HAH WITH JEEM FINAL FORM;Lo;0;AL;<final> 062A 062D 062C;;;;N;;;;;
+FD52;ARABIC LIGATURE TEH WITH HAH WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 062A 062D 062C;;;;N;;;;;
+FD53;ARABIC LIGATURE TEH WITH HAH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 062A 062D 0645;;;;N;;;;;
+FD54;ARABIC LIGATURE TEH WITH KHAH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 062A 062E 0645;;;;N;;;;;
+FD55;ARABIC LIGATURE TEH WITH MEEM WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 062A 0645 062C;;;;N;;;;;
+FD56;ARABIC LIGATURE TEH WITH MEEM WITH HAH INITIAL FORM;Lo;0;AL;<initial> 062A 0645 062D;;;;N;;;;;
+FD57;ARABIC LIGATURE TEH WITH MEEM WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 062A 0645 062E;;;;N;;;;;
+FD58;ARABIC LIGATURE JEEM WITH MEEM WITH HAH FINAL FORM;Lo;0;AL;<final> 062C 0645 062D;;;;N;;;;;
+FD59;ARABIC LIGATURE JEEM WITH MEEM WITH HAH INITIAL FORM;Lo;0;AL;<initial> 062C 0645 062D;;;;N;;;;;
+FD5A;ARABIC LIGATURE HAH WITH MEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 062D 0645 064A;;;;N;;;;;
+FD5B;ARABIC LIGATURE HAH WITH MEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 062D 0645 0649;;;;N;;;;;
+FD5C;ARABIC LIGATURE SEEN WITH HAH WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0633 062D 062C;;;;N;;;;;
+FD5D;ARABIC LIGATURE SEEN WITH JEEM WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0633 062C 062D;;;;N;;;;;
+FD5E;ARABIC LIGATURE SEEN WITH JEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0633 062C 0649;;;;N;;;;;
+FD5F;ARABIC LIGATURE SEEN WITH MEEM WITH HAH FINAL FORM;Lo;0;AL;<final> 0633 0645 062D;;;;N;;;;;
+FD60;ARABIC LIGATURE SEEN WITH MEEM WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0633 0645 062D;;;;N;;;;;
+FD61;ARABIC LIGATURE SEEN WITH MEEM WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0633 0645 062C;;;;N;;;;;
+FD62;ARABIC LIGATURE SEEN WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL;<final> 0633 0645 0645;;;;N;;;;;
+FD63;ARABIC LIGATURE SEEN WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0633 0645 0645;;;;N;;;;;
+FD64;ARABIC LIGATURE SAD WITH HAH WITH HAH FINAL FORM;Lo;0;AL;<final> 0635 062D 062D;;;;N;;;;;
+FD65;ARABIC LIGATURE SAD WITH HAH WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0635 062D 062D;;;;N;;;;;
+FD66;ARABIC LIGATURE SAD WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL;<final> 0635 0645 0645;;;;N;;;;;
+FD67;ARABIC LIGATURE SHEEN WITH HAH WITH MEEM FINAL FORM;Lo;0;AL;<final> 0634 062D 0645;;;;N;;;;;
+FD68;ARABIC LIGATURE SHEEN WITH HAH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0634 062D 0645;;;;N;;;;;
+FD69;ARABIC LIGATURE SHEEN WITH JEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 0634 062C 064A;;;;N;;;;;
+FD6A;ARABIC LIGATURE SHEEN WITH MEEM WITH KHAH FINAL FORM;Lo;0;AL;<final> 0634 0645 062E;;;;N;;;;;
+FD6B;ARABIC LIGATURE SHEEN WITH MEEM WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 0634 0645 062E;;;;N;;;;;
+FD6C;ARABIC LIGATURE SHEEN WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL;<final> 0634 0645 0645;;;;N;;;;;
+FD6D;ARABIC LIGATURE SHEEN WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0634 0645 0645;;;;N;;;;;
+FD6E;ARABIC LIGATURE DAD WITH HAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0636 062D 0649;;;;N;;;;;
+FD6F;ARABIC LIGATURE DAD WITH KHAH WITH MEEM FINAL FORM;Lo;0;AL;<final> 0636 062E 0645;;;;N;;;;;
+FD70;ARABIC LIGATURE DAD WITH KHAH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0636 062E 0645;;;;N;;;;;
+FD71;ARABIC LIGATURE TAH WITH MEEM WITH HAH FINAL FORM;Lo;0;AL;<final> 0637 0645 062D;;;;N;;;;;
+FD72;ARABIC LIGATURE TAH WITH MEEM WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0637 0645 062D;;;;N;;;;;
+FD73;ARABIC LIGATURE TAH WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0637 0645 0645;;;;N;;;;;
+FD74;ARABIC LIGATURE TAH WITH MEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 0637 0645 064A;;;;N;;;;;
+FD75;ARABIC LIGATURE AIN WITH JEEM WITH MEEM FINAL FORM;Lo;0;AL;<final> 0639 062C 0645;;;;N;;;;;
+FD76;ARABIC LIGATURE AIN WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL;<final> 0639 0645 0645;;;;N;;;;;
+FD77;ARABIC LIGATURE AIN WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0639 0645 0645;;;;N;;;;;
+FD78;ARABIC LIGATURE AIN WITH MEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0639 0645 0649;;;;N;;;;;
+FD79;ARABIC LIGATURE GHAIN WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL;<final> 063A 0645 0645;;;;N;;;;;
+FD7A;ARABIC LIGATURE GHAIN WITH MEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 063A 0645 064A;;;;N;;;;;
+FD7B;ARABIC LIGATURE GHAIN WITH MEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 063A 0645 0649;;;;N;;;;;
+FD7C;ARABIC LIGATURE FEH WITH KHAH WITH MEEM FINAL FORM;Lo;0;AL;<final> 0641 062E 0645;;;;N;;;;;
+FD7D;ARABIC LIGATURE FEH WITH KHAH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0641 062E 0645;;;;N;;;;;
+FD7E;ARABIC LIGATURE QAF WITH MEEM WITH HAH FINAL FORM;Lo;0;AL;<final> 0642 0645 062D;;;;N;;;;;
+FD7F;ARABIC LIGATURE QAF WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL;<final> 0642 0645 0645;;;;N;;;;;
+FD80;ARABIC LIGATURE LAM WITH HAH WITH MEEM FINAL FORM;Lo;0;AL;<final> 0644 062D 0645;;;;N;;;;;
+FD81;ARABIC LIGATURE LAM WITH HAH WITH YEH FINAL FORM;Lo;0;AL;<final> 0644 062D 064A;;;;N;;;;;
+FD82;ARABIC LIGATURE LAM WITH HAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0644 062D 0649;;;;N;;;;;
+FD83;ARABIC LIGATURE LAM WITH JEEM WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0644 062C 062C;;;;N;;;;;
+FD84;ARABIC LIGATURE LAM WITH JEEM WITH JEEM FINAL FORM;Lo;0;AL;<final> 0644 062C 062C;;;;N;;;;;
+FD85;ARABIC LIGATURE LAM WITH KHAH WITH MEEM FINAL FORM;Lo;0;AL;<final> 0644 062E 0645;;;;N;;;;;
+FD86;ARABIC LIGATURE LAM WITH KHAH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0644 062E 0645;;;;N;;;;;
+FD87;ARABIC LIGATURE LAM WITH MEEM WITH HAH FINAL FORM;Lo;0;AL;<final> 0644 0645 062D;;;;N;;;;;
+FD88;ARABIC LIGATURE LAM WITH MEEM WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0644 0645 062D;;;;N;;;;;
+FD89;ARABIC LIGATURE MEEM WITH HAH WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0645 062D 062C;;;;N;;;;;
+FD8A;ARABIC LIGATURE MEEM WITH HAH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0645 062D 0645;;;;N;;;;;
+FD8B;ARABIC LIGATURE MEEM WITH HAH WITH YEH FINAL FORM;Lo;0;AL;<final> 0645 062D 064A;;;;N;;;;;
+FD8C;ARABIC LIGATURE MEEM WITH JEEM WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0645 062C 062D;;;;N;;;;;
+FD8D;ARABIC LIGATURE MEEM WITH JEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0645 062C 0645;;;;N;;;;;
+FD8E;ARABIC LIGATURE MEEM WITH KHAH WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0645 062E 062C;;;;N;;;;;
+FD8F;ARABIC LIGATURE MEEM WITH KHAH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0645 062E 0645;;;;N;;;;;
+FD92;ARABIC LIGATURE MEEM WITH JEEM WITH KHAH INITIAL FORM;Lo;0;AL;<initial> 0645 062C 062E;;;;N;;;;;
+FD93;ARABIC LIGATURE HEH WITH MEEM WITH JEEM INITIAL FORM;Lo;0;AL;<initial> 0647 0645 062C;;;;N;;;;;
+FD94;ARABIC LIGATURE HEH WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0647 0645 0645;;;;N;;;;;
+FD95;ARABIC LIGATURE NOON WITH HAH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0646 062D 0645;;;;N;;;;;
+FD96;ARABIC LIGATURE NOON WITH HAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0646 062D 0649;;;;N;;;;;
+FD97;ARABIC LIGATURE NOON WITH JEEM WITH MEEM FINAL FORM;Lo;0;AL;<final> 0646 062C 0645;;;;N;;;;;
+FD98;ARABIC LIGATURE NOON WITH JEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0646 062C 0645;;;;N;;;;;
+FD99;ARABIC LIGATURE NOON WITH JEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0646 062C 0649;;;;N;;;;;
+FD9A;ARABIC LIGATURE NOON WITH MEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 0646 0645 064A;;;;N;;;;;
+FD9B;ARABIC LIGATURE NOON WITH MEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0646 0645 0649;;;;N;;;;;
+FD9C;ARABIC LIGATURE YEH WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL;<final> 064A 0645 0645;;;;N;;;;;
+FD9D;ARABIC LIGATURE YEH WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 064A 0645 0645;;;;N;;;;;
+FD9E;ARABIC LIGATURE BEH WITH KHAH WITH YEH FINAL FORM;Lo;0;AL;<final> 0628 062E 064A;;;;N;;;;;
+FD9F;ARABIC LIGATURE TEH WITH JEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 062A 062C 064A;;;;N;;;;;
+FDA0;ARABIC LIGATURE TEH WITH JEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 062A 062C 0649;;;;N;;;;;
+FDA1;ARABIC LIGATURE TEH WITH KHAH WITH YEH FINAL FORM;Lo;0;AL;<final> 062A 062E 064A;;;;N;;;;;
+FDA2;ARABIC LIGATURE TEH WITH KHAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 062A 062E 0649;;;;N;;;;;
+FDA3;ARABIC LIGATURE TEH WITH MEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 062A 0645 064A;;;;N;;;;;
+FDA4;ARABIC LIGATURE TEH WITH MEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 062A 0645 0649;;;;N;;;;;
+FDA5;ARABIC LIGATURE JEEM WITH MEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 062C 0645 064A;;;;N;;;;;
+FDA6;ARABIC LIGATURE JEEM WITH HAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 062C 062D 0649;;;;N;;;;;
+FDA7;ARABIC LIGATURE JEEM WITH MEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 062C 0645 0649;;;;N;;;;;
+FDA8;ARABIC LIGATURE SEEN WITH KHAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0633 062E 0649;;;;N;;;;;
+FDA9;ARABIC LIGATURE SAD WITH HAH WITH YEH FINAL FORM;Lo;0;AL;<final> 0635 062D 064A;;;;N;;;;;
+FDAA;ARABIC LIGATURE SHEEN WITH HAH WITH YEH FINAL FORM;Lo;0;AL;<final> 0634 062D 064A;;;;N;;;;;
+FDAB;ARABIC LIGATURE DAD WITH HAH WITH YEH FINAL FORM;Lo;0;AL;<final> 0636 062D 064A;;;;N;;;;;
+FDAC;ARABIC LIGATURE LAM WITH JEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 0644 062C 064A;;;;N;;;;;
+FDAD;ARABIC LIGATURE LAM WITH MEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 0644 0645 064A;;;;N;;;;;
+FDAE;ARABIC LIGATURE YEH WITH HAH WITH YEH FINAL FORM;Lo;0;AL;<final> 064A 062D 064A;;;;N;;;;;
+FDAF;ARABIC LIGATURE YEH WITH JEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 064A 062C 064A;;;;N;;;;;
+FDB0;ARABIC LIGATURE YEH WITH MEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 064A 0645 064A;;;;N;;;;;
+FDB1;ARABIC LIGATURE MEEM WITH MEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 0645 0645 064A;;;;N;;;;;
+FDB2;ARABIC LIGATURE QAF WITH MEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 0642 0645 064A;;;;N;;;;;
+FDB3;ARABIC LIGATURE NOON WITH HAH WITH YEH FINAL FORM;Lo;0;AL;<final> 0646 062D 064A;;;;N;;;;;
+FDB4;ARABIC LIGATURE QAF WITH MEEM WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0642 0645 062D;;;;N;;;;;
+FDB5;ARABIC LIGATURE LAM WITH HAH WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0644 062D 0645;;;;N;;;;;
+FDB6;ARABIC LIGATURE AIN WITH MEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 0639 0645 064A;;;;N;;;;;
+FDB7;ARABIC LIGATURE KAF WITH MEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 0643 0645 064A;;;;N;;;;;
+FDB8;ARABIC LIGATURE NOON WITH JEEM WITH HAH INITIAL FORM;Lo;0;AL;<initial> 0646 062C 062D;;;;N;;;;;
+FDB9;ARABIC LIGATURE MEEM WITH KHAH WITH YEH FINAL FORM;Lo;0;AL;<final> 0645 062E 064A;;;;N;;;;;
+FDBA;ARABIC LIGATURE LAM WITH JEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0644 062C 0645;;;;N;;;;;
+FDBB;ARABIC LIGATURE KAF WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL;<final> 0643 0645 0645;;;;N;;;;;
+FDBC;ARABIC LIGATURE LAM WITH JEEM WITH MEEM FINAL FORM;Lo;0;AL;<final> 0644 062C 0645;;;;N;;;;;
+FDBD;ARABIC LIGATURE NOON WITH JEEM WITH HAH FINAL FORM;Lo;0;AL;<final> 0646 062C 062D;;;;N;;;;;
+FDBE;ARABIC LIGATURE JEEM WITH HAH WITH YEH FINAL FORM;Lo;0;AL;<final> 062C 062D 064A;;;;N;;;;;
+FDBF;ARABIC LIGATURE HAH WITH JEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 062D 062C 064A;;;;N;;;;;
+FDC0;ARABIC LIGATURE MEEM WITH JEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 0645 062C 064A;;;;N;;;;;
+FDC1;ARABIC LIGATURE FEH WITH MEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 0641 0645 064A;;;;N;;;;;
+FDC2;ARABIC LIGATURE BEH WITH HAH WITH YEH FINAL FORM;Lo;0;AL;<final> 0628 062D 064A;;;;N;;;;;
+FDC3;ARABIC LIGATURE KAF WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0643 0645 0645;;;;N;;;;;
+FDC4;ARABIC LIGATURE AIN WITH JEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0639 062C 0645;;;;N;;;;;
+FDC5;ARABIC LIGATURE SAD WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL;<initial> 0635 0645 0645;;;;N;;;;;
+FDC6;ARABIC LIGATURE SEEN WITH KHAH WITH YEH FINAL FORM;Lo;0;AL;<final> 0633 062E 064A;;;;N;;;;;
+FDC7;ARABIC LIGATURE NOON WITH JEEM WITH YEH FINAL FORM;Lo;0;AL;<final> 0646 062C 064A;;;;N;;;;;
+FDF0;ARABIC LIGATURE SALLA USED AS KORANIC STOP SIGN ISOLATED FORM;Lo;0;AL;<isolated> 0635 0644 06D2;;;;N;;;;;
+FDF1;ARABIC LIGATURE QALA USED AS KORANIC STOP SIGN ISOLATED FORM;Lo;0;AL;<isolated> 0642 0644 06D2;;;;N;;;;;
+FDF2;ARABIC LIGATURE ALLAH ISOLATED FORM;Lo;0;AL;<isolated> 0627 0644 0644 0647;;;;N;;;;;
+FDF3;ARABIC LIGATURE AKBAR ISOLATED FORM;Lo;0;AL;<isolated> 0627 0643 0628 0631;;;;N;;;;;
+FDF4;ARABIC LIGATURE MOHAMMAD ISOLATED FORM;Lo;0;AL;<isolated> 0645 062D 0645 062F;;;;N;;;;;
+FDF5;ARABIC LIGATURE SALAM ISOLATED FORM;Lo;0;AL;<isolated> 0635 0644 0639 0645;;;;N;;;;;
+FDF6;ARABIC LIGATURE RASOUL ISOLATED FORM;Lo;0;AL;<isolated> 0631 0633 0648 0644;;;;N;;;;;
+FDF7;ARABIC LIGATURE ALAYHE ISOLATED FORM;Lo;0;AL;<isolated> 0639 0644 064A 0647;;;;N;;;;;
+FDF8;ARABIC LIGATURE WASALLAM ISOLATED FORM;Lo;0;AL;<isolated> 0648 0633 0644 0645;;;;N;;;;;
+FDF9;ARABIC LIGATURE SALLA ISOLATED FORM;Lo;0;AL;<isolated> 0635 0644 0649;;;;N;;;;;
+FDFA;ARABIC LIGATURE SALLALLAHOU ALAYHE WASALLAM;Lo;0;AL;<isolated> 0635 0644 0649 0020 0627 0644 0644 0647 0020 0639 0644 064A 0647 0020 0648 0633 0644 0645;;;;N;ARABIC LETTER SALLALLAHOU ALAYHE WASALLAM;;;;
+FDFB;ARABIC LIGATURE JALLAJALALOUHOU;Lo;0;AL;<isolated> 062C 0644 0020 062C 0644 0627 0644 0647;;;;N;ARABIC LETTER JALLAJALALOUHOU;;;;
+FDFC;RIAL SIGN;Sc;0;AL;<isolated> 0631 06CC 0627 0644;;;;N;;;;;
+FDFD;ARABIC LIGATURE BISMILLAH AR-RAHMAN AR-RAHEEM;So;0;ON;;;;;N;;;;;
+FE00;VARIATION SELECTOR-1;Mn;0;NSM;;;;;N;;;;;
+FE01;VARIATION SELECTOR-2;Mn;0;NSM;;;;;N;;;;;
+FE02;VARIATION SELECTOR-3;Mn;0;NSM;;;;;N;;;;;
+FE03;VARIATION SELECTOR-4;Mn;0;NSM;;;;;N;;;;;
+FE04;VARIATION SELECTOR-5;Mn;0;NSM;;;;;N;;;;;
+FE05;VARIATION SELECTOR-6;Mn;0;NSM;;;;;N;;;;;
+FE06;VARIATION SELECTOR-7;Mn;0;NSM;;;;;N;;;;;
+FE07;VARIATION SELECTOR-8;Mn;0;NSM;;;;;N;;;;;
+FE08;VARIATION SELECTOR-9;Mn;0;NSM;;;;;N;;;;;
+FE09;VARIATION SELECTOR-10;Mn;0;NSM;;;;;N;;;;;
+FE0A;VARIATION SELECTOR-11;Mn;0;NSM;;;;;N;;;;;
+FE0B;VARIATION SELECTOR-12;Mn;0;NSM;;;;;N;;;;;
+FE0C;VARIATION SELECTOR-13;Mn;0;NSM;;;;;N;;;;;
+FE0D;VARIATION SELECTOR-14;Mn;0;NSM;;;;;N;;;;;
+FE0E;VARIATION SELECTOR-15;Mn;0;NSM;;;;;N;;;;;
+FE0F;VARIATION SELECTOR-16;Mn;0;NSM;;;;;N;;;;;
+FE20;COMBINING LIGATURE LEFT HALF;Mn;230;NSM;;;;;N;;;;;
+FE21;COMBINING LIGATURE RIGHT HALF;Mn;230;NSM;;;;;N;;;;;
+FE22;COMBINING DOUBLE TILDE LEFT HALF;Mn;230;NSM;;;;;N;;;;;
+FE23;COMBINING DOUBLE TILDE RIGHT HALF;Mn;230;NSM;;;;;N;;;;;
+FE30;PRESENTATION FORM FOR VERTICAL TWO DOT LEADER;Po;0;ON;<vertical> 2025;;;;N;GLYPH FOR VERTICAL TWO DOT LEADER;;;;
+FE31;PRESENTATION FORM FOR VERTICAL EM DASH;Pd;0;ON;<vertical> 2014;;;;N;GLYPH FOR VERTICAL EM DASH;;;;
+FE32;PRESENTATION FORM FOR VERTICAL EN DASH;Pd;0;ON;<vertical> 2013;;;;N;GLYPH FOR VERTICAL EN DASH;;;;
+FE33;PRESENTATION FORM FOR VERTICAL LOW LINE;Pc;0;ON;<vertical> 005F;;;;N;GLYPH FOR VERTICAL SPACING UNDERSCORE;;;;
+FE34;PRESENTATION FORM FOR VERTICAL WAVY LOW LINE;Pc;0;ON;<vertical> 005F;;;;N;GLYPH FOR VERTICAL SPACING WAVY UNDERSCORE;;;;
+FE35;PRESENTATION FORM FOR VERTICAL LEFT PARENTHESIS;Ps;0;ON;<vertical> 0028;;;;N;GLYPH FOR VERTICAL OPENING PARENTHESIS;;;;
+FE36;PRESENTATION FORM FOR VERTICAL RIGHT PARENTHESIS;Pe;0;ON;<vertical> 0029;;;;N;GLYPH FOR VERTICAL CLOSING PARENTHESIS;;;;
+FE37;PRESENTATION FORM FOR VERTICAL LEFT CURLY BRACKET;Ps;0;ON;<vertical> 007B;;;;N;GLYPH FOR VERTICAL OPENING CURLY BRACKET;;;;
+FE38;PRESENTATION FORM FOR VERTICAL RIGHT CURLY BRACKET;Pe;0;ON;<vertical> 007D;;;;N;GLYPH FOR VERTICAL CLOSING CURLY BRACKET;;;;
+FE39;PRESENTATION FORM FOR VERTICAL LEFT TORTOISE SHELL BRACKET;Ps;0;ON;<vertical> 3014;;;;N;GLYPH FOR VERTICAL OPENING TORTOISE SHELL BRACKET;;;;
+FE3A;PRESENTATION FORM FOR VERTICAL RIGHT TORTOISE SHELL BRACKET;Pe;0;ON;<vertical> 3015;;;;N;GLYPH FOR VERTICAL CLOSING TORTOISE SHELL BRACKET;;;;
+FE3B;PRESENTATION FORM FOR VERTICAL LEFT BLACK LENTICULAR BRACKET;Ps;0;ON;<vertical> 3010;;;;N;GLYPH FOR VERTICAL OPENING BLACK LENTICULAR BRACKET;;;;
+FE3C;PRESENTATION FORM FOR VERTICAL RIGHT BLACK LENTICULAR BRACKET;Pe;0;ON;<vertical> 3011;;;;N;GLYPH FOR VERTICAL CLOSING BLACK LENTICULAR BRACKET;;;;
+FE3D;PRESENTATION FORM FOR VERTICAL LEFT DOUBLE ANGLE BRACKET;Ps;0;ON;<vertical> 300A;;;;N;GLYPH FOR VERTICAL OPENING DOUBLE ANGLE BRACKET;;;;
+FE3E;PRESENTATION FORM FOR VERTICAL RIGHT DOUBLE ANGLE BRACKET;Pe;0;ON;<vertical> 300B;;;;N;GLYPH FOR VERTICAL CLOSING DOUBLE ANGLE BRACKET;;;;
+FE3F;PRESENTATION FORM FOR VERTICAL LEFT ANGLE BRACKET;Ps;0;ON;<vertical> 3008;;;;N;GLYPH FOR VERTICAL OPENING ANGLE BRACKET;;;;
+FE40;PRESENTATION FORM FOR VERTICAL RIGHT ANGLE BRACKET;Pe;0;ON;<vertical> 3009;;;;N;GLYPH FOR VERTICAL CLOSING ANGLE BRACKET;;;;
+FE41;PRESENTATION FORM FOR VERTICAL LEFT CORNER BRACKET;Ps;0;ON;<vertical> 300C;;;;N;GLYPH FOR VERTICAL OPENING CORNER BRACKET;;;;
+FE42;PRESENTATION FORM FOR VERTICAL RIGHT CORNER BRACKET;Pe;0;ON;<vertical> 300D;;;;N;GLYPH FOR VERTICAL CLOSING CORNER BRACKET;;;;
+FE43;PRESENTATION FORM FOR VERTICAL LEFT WHITE CORNER BRACKET;Ps;0;ON;<vertical> 300E;;;;N;GLYPH FOR VERTICAL OPENING WHITE CORNER BRACKET;;;;
+FE44;PRESENTATION FORM FOR VERTICAL RIGHT WHITE CORNER BRACKET;Pe;0;ON;<vertical> 300F;;;;N;GLYPH FOR VERTICAL CLOSING WHITE CORNER BRACKET;;;;
+FE45;SESAME DOT;Po;0;ON;;;;;N;;;;;
+FE46;WHITE SESAME DOT;Po;0;ON;;;;;N;;;;;
+FE47;PRESENTATION FORM FOR VERTICAL LEFT SQUARE BRACKET;Ps;0;ON;<vertical> 005B;;;;N;;;;;
+FE48;PRESENTATION FORM FOR VERTICAL RIGHT SQUARE BRACKET;Pe;0;ON;<vertical> 005D;;;;N;;;;;
+FE49;DASHED OVERLINE;Po;0;ON;<compat> 203E;;;;N;SPACING DASHED OVERSCORE;;;;
+FE4A;CENTRELINE OVERLINE;Po;0;ON;<compat> 203E;;;;N;SPACING CENTERLINE OVERSCORE;;;;
+FE4B;WAVY OVERLINE;Po;0;ON;<compat> 203E;;;;N;SPACING WAVY OVERSCORE;;;;
+FE4C;DOUBLE WAVY OVERLINE;Po;0;ON;<compat> 203E;;;;N;SPACING DOUBLE WAVY OVERSCORE;;;;
+FE4D;DASHED LOW LINE;Pc;0;ON;<compat> 005F;;;;N;SPACING DASHED UNDERSCORE;;;;
+FE4E;CENTRELINE LOW LINE;Pc;0;ON;<compat> 005F;;;;N;SPACING CENTERLINE UNDERSCORE;;;;
+FE4F;WAVY LOW LINE;Pc;0;ON;<compat> 005F;;;;N;SPACING WAVY UNDERSCORE;;;;
+FE50;SMALL COMMA;Po;0;CS;<small> 002C;;;;N;;;;;
+FE51;SMALL IDEOGRAPHIC COMMA;Po;0;ON;<small> 3001;;;;N;;;;;
+FE52;SMALL FULL STOP;Po;0;CS;<small> 002E;;;;N;SMALL PERIOD;;;;
+FE54;SMALL SEMICOLON;Po;0;ON;<small> 003B;;;;N;;;;;
+FE55;SMALL COLON;Po;0;CS;<small> 003A;;;;N;;;;;
+FE56;SMALL QUESTION MARK;Po;0;ON;<small> 003F;;;;N;;;;;
+FE57;SMALL EXCLAMATION MARK;Po;0;ON;<small> 0021;;;;N;;;;;
+FE58;SMALL EM DASH;Pd;0;ON;<small> 2014;;;;N;;;;;
+FE59;SMALL LEFT PARENTHESIS;Ps;0;ON;<small> 0028;;;;N;SMALL OPENING PARENTHESIS;;;;
+FE5A;SMALL RIGHT PARENTHESIS;Pe;0;ON;<small> 0029;;;;N;SMALL CLOSING PARENTHESIS;;;;
+FE5B;SMALL LEFT CURLY BRACKET;Ps;0;ON;<small> 007B;;;;N;SMALL OPENING CURLY BRACKET;;;;
+FE5C;SMALL RIGHT CURLY BRACKET;Pe;0;ON;<small> 007D;;;;N;SMALL CLOSING CURLY BRACKET;;;;
+FE5D;SMALL LEFT TORTOISE SHELL BRACKET;Ps;0;ON;<small> 3014;;;;N;SMALL OPENING TORTOISE SHELL BRACKET;;;;
+FE5E;SMALL RIGHT TORTOISE SHELL BRACKET;Pe;0;ON;<small> 3015;;;;N;SMALL CLOSING TORTOISE SHELL BRACKET;;;;
+FE5F;SMALL NUMBER SIGN;Po;0;ET;<small> 0023;;;;N;;;;;
+FE60;SMALL AMPERSAND;Po;0;ON;<small> 0026;;;;N;;;;;
+FE61;SMALL ASTERISK;Po;0;ON;<small> 002A;;;;N;;;;;
+FE62;SMALL PLUS SIGN;Sm;0;ET;<small> 002B;;;;N;;;;;
+FE63;SMALL HYPHEN-MINUS;Pd;0;ET;<small> 002D;;;;N;;;;;
+FE64;SMALL LESS-THAN SIGN;Sm;0;ON;<small> 003C;;;;N;;;;;
+FE65;SMALL GREATER-THAN SIGN;Sm;0;ON;<small> 003E;;;;N;;;;;
+FE66;SMALL EQUALS SIGN;Sm;0;ON;<small> 003D;;;;N;;;;;
+FE68;SMALL REVERSE SOLIDUS;Po;0;ON;<small> 005C;;;;N;SMALL BACKSLASH;;;;
+FE69;SMALL DOLLAR SIGN;Sc;0;ET;<small> 0024;;;;N;;;;;
+FE6A;SMALL PERCENT SIGN;Po;0;ET;<small> 0025;;;;N;;;;;
+FE6B;SMALL COMMERCIAL AT;Po;0;ON;<small> 0040;;;;N;;;;;
+FE70;ARABIC FATHATAN ISOLATED FORM;Lo;0;AL;<isolated> 0020 064B;;;;N;ARABIC SPACING FATHATAN;;;;
+FE71;ARABIC TATWEEL WITH FATHATAN ABOVE;Lo;0;AL;<medial> 0640 064B;;;;N;ARABIC FATHATAN ON TATWEEL;;;;
+FE72;ARABIC DAMMATAN ISOLATED FORM;Lo;0;AL;<isolated> 0020 064C;;;;N;ARABIC SPACING DAMMATAN;;;;
+FE73;ARABIC TAIL FRAGMENT;Lo;0;AL;;;;;N;;;;;
+FE74;ARABIC KASRATAN ISOLATED FORM;Lo;0;AL;<isolated> 0020 064D;;;;N;ARABIC SPACING KASRATAN;;;;
+FE76;ARABIC FATHA ISOLATED FORM;Lo;0;AL;<isolated> 0020 064E;;;;N;ARABIC SPACING FATHAH;;;;
+FE77;ARABIC FATHA MEDIAL FORM;Lo;0;AL;<medial> 0640 064E;;;;N;ARABIC FATHAH ON TATWEEL;;;;
+FE78;ARABIC DAMMA ISOLATED FORM;Lo;0;AL;<isolated> 0020 064F;;;;N;ARABIC SPACING DAMMAH;;;;
+FE79;ARABIC DAMMA MEDIAL FORM;Lo;0;AL;<medial> 0640 064F;;;;N;ARABIC DAMMAH ON TATWEEL;;;;
+FE7A;ARABIC KASRA ISOLATED FORM;Lo;0;AL;<isolated> 0020 0650;;;;N;ARABIC SPACING KASRAH;;;;
+FE7B;ARABIC KASRA MEDIAL FORM;Lo;0;AL;<medial> 0640 0650;;;;N;ARABIC KASRAH ON TATWEEL;;;;
+FE7C;ARABIC SHADDA ISOLATED FORM;Lo;0;AL;<isolated> 0020 0651;;;;N;ARABIC SPACING SHADDAH;;;;
+FE7D;ARABIC SHADDA MEDIAL FORM;Lo;0;AL;<medial> 0640 0651;;;;N;ARABIC SHADDAH ON TATWEEL;;;;
+FE7E;ARABIC SUKUN ISOLATED FORM;Lo;0;AL;<isolated> 0020 0652;;;;N;ARABIC SPACING SUKUN;;;;
+FE7F;ARABIC SUKUN MEDIAL FORM;Lo;0;AL;<medial> 0640 0652;;;;N;ARABIC SUKUN ON TATWEEL;;;;
+FE80;ARABIC LETTER HAMZA ISOLATED FORM;Lo;0;AL;<isolated> 0621;;;;N;GLYPH FOR ISOLATE ARABIC HAMZAH;;;;
+FE81;ARABIC LETTER ALEF WITH MADDA ABOVE ISOLATED FORM;Lo;0;AL;<isolated> 0622;;;;N;GLYPH FOR ISOLATE ARABIC MADDAH ON ALEF;;;;
+FE82;ARABIC LETTER ALEF WITH MADDA ABOVE FINAL FORM;Lo;0;AL;<final> 0622;;;;N;GLYPH FOR FINAL ARABIC MADDAH ON ALEF;;;;
+FE83;ARABIC LETTER ALEF WITH HAMZA ABOVE ISOLATED FORM;Lo;0;AL;<isolated> 0623;;;;N;GLYPH FOR ISOLATE ARABIC HAMZAH ON ALEF;;;;
+FE84;ARABIC LETTER ALEF WITH HAMZA ABOVE FINAL FORM;Lo;0;AL;<final> 0623;;;;N;GLYPH FOR FINAL ARABIC HAMZAH ON ALEF;;;;
+FE85;ARABIC LETTER WAW WITH HAMZA ABOVE ISOLATED FORM;Lo;0;AL;<isolated> 0624;;;;N;GLYPH FOR ISOLATE ARABIC HAMZAH ON WAW;;;;
+FE86;ARABIC LETTER WAW WITH HAMZA ABOVE FINAL FORM;Lo;0;AL;<final> 0624;;;;N;GLYPH FOR FINAL ARABIC HAMZAH ON WAW;;;;
+FE87;ARABIC LETTER ALEF WITH HAMZA BELOW ISOLATED FORM;Lo;0;AL;<isolated> 0625;;;;N;GLYPH FOR ISOLATE ARABIC HAMZAH UNDER ALEF;;;;
+FE88;ARABIC LETTER ALEF WITH HAMZA BELOW FINAL FORM;Lo;0;AL;<final> 0625;;;;N;GLYPH FOR FINAL ARABIC HAMZAH UNDER ALEF;;;;
+FE89;ARABIC LETTER YEH WITH HAMZA ABOVE ISOLATED FORM;Lo;0;AL;<isolated> 0626;;;;N;GLYPH FOR ISOLATE ARABIC HAMZAH ON YA;;;;
+FE8A;ARABIC LETTER YEH WITH HAMZA ABOVE FINAL FORM;Lo;0;AL;<final> 0626;;;;N;GLYPH FOR FINAL ARABIC HAMZAH ON YA;;;;
+FE8B;ARABIC LETTER YEH WITH HAMZA ABOVE INITIAL FORM;Lo;0;AL;<initial> 0626;;;;N;GLYPH FOR INITIAL ARABIC HAMZAH ON YA;;;;
+FE8C;ARABIC LETTER YEH WITH HAMZA ABOVE MEDIAL FORM;Lo;0;AL;<medial> 0626;;;;N;GLYPH FOR MEDIAL ARABIC HAMZAH ON YA;;;;
+FE8D;ARABIC LETTER ALEF ISOLATED FORM;Lo;0;AL;<isolated> 0627;;;;N;GLYPH FOR ISOLATE ARABIC ALEF;;;;
+FE8E;ARABIC LETTER ALEF FINAL FORM;Lo;0;AL;<final> 0627;;;;N;GLYPH FOR FINAL ARABIC ALEF;;;;
+FE8F;ARABIC LETTER BEH ISOLATED FORM;Lo;0;AL;<isolated> 0628;;;;N;GLYPH FOR ISOLATE ARABIC BAA;;;;
+FE90;ARABIC LETTER BEH FINAL FORM;Lo;0;AL;<final> 0628;;;;N;GLYPH FOR FINAL ARABIC BAA;;;;
+FE91;ARABIC LETTER BEH INITIAL FORM;Lo;0;AL;<initial> 0628;;;;N;GLYPH FOR INITIAL ARABIC BAA;;;;
+FE92;ARABIC LETTER BEH MEDIAL FORM;Lo;0;AL;<medial> 0628;;;;N;GLYPH FOR MEDIAL ARABIC BAA;;;;
+FE93;ARABIC LETTER TEH MARBUTA ISOLATED FORM;Lo;0;AL;<isolated> 0629;;;;N;GLYPH FOR ISOLATE ARABIC TAA MARBUTAH;;;;
+FE94;ARABIC LETTER TEH MARBUTA FINAL FORM;Lo;0;AL;<final> 0629;;;;N;GLYPH FOR FINAL ARABIC TAA MARBUTAH;;;;
+FE95;ARABIC LETTER TEH ISOLATED FORM;Lo;0;AL;<isolated> 062A;;;;N;GLYPH FOR ISOLATE ARABIC TAA;;;;
+FE96;ARABIC LETTER TEH FINAL FORM;Lo;0;AL;<final> 062A;;;;N;GLYPH FOR FINAL ARABIC TAA;;;;
+FE97;ARABIC LETTER TEH INITIAL FORM;Lo;0;AL;<initial> 062A;;;;N;GLYPH FOR INITIAL ARABIC TAA;;;;
+FE98;ARABIC LETTER TEH MEDIAL FORM;Lo;0;AL;<medial> 062A;;;;N;GLYPH FOR MEDIAL ARABIC TAA;;;;
+FE99;ARABIC LETTER THEH ISOLATED FORM;Lo;0;AL;<isolated> 062B;;;;N;GLYPH FOR ISOLATE ARABIC THAA;;;;
+FE9A;ARABIC LETTER THEH FINAL FORM;Lo;0;AL;<final> 062B;;;;N;GLYPH FOR FINAL ARABIC THAA;;;;
+FE9B;ARABIC LETTER THEH INITIAL FORM;Lo;0;AL;<initial> 062B;;;;N;GLYPH FOR INITIAL ARABIC THAA;;;;
+FE9C;ARABIC LETTER THEH MEDIAL FORM;Lo;0;AL;<medial> 062B;;;;N;GLYPH FOR MEDIAL ARABIC THAA;;;;
+FE9D;ARABIC LETTER JEEM ISOLATED FORM;Lo;0;AL;<isolated> 062C;;;;N;GLYPH FOR ISOLATE ARABIC JEEM;;;;
+FE9E;ARABIC LETTER JEEM FINAL FORM;Lo;0;AL;<final> 062C;;;;N;GLYPH FOR FINAL ARABIC JEEM;;;;
+FE9F;ARABIC LETTER JEEM INITIAL FORM;Lo;0;AL;<initial> 062C;;;;N;GLYPH FOR INITIAL ARABIC JEEM;;;;
+FEA0;ARABIC LETTER JEEM MEDIAL FORM;Lo;0;AL;<medial> 062C;;;;N;GLYPH FOR MEDIAL ARABIC JEEM;;;;
+FEA1;ARABIC LETTER HAH ISOLATED FORM;Lo;0;AL;<isolated> 062D;;;;N;GLYPH FOR ISOLATE ARABIC HAA;;;;
+FEA2;ARABIC LETTER HAH FINAL FORM;Lo;0;AL;<final> 062D;;;;N;GLYPH FOR FINAL ARABIC HAA;;;;
+FEA3;ARABIC LETTER HAH INITIAL FORM;Lo;0;AL;<initial> 062D;;;;N;GLYPH FOR INITIAL ARABIC HAA;;;;
+FEA4;ARABIC LETTER HAH MEDIAL FORM;Lo;0;AL;<medial> 062D;;;;N;GLYPH FOR MEDIAL ARABIC HAA;;;;
+FEA5;ARABIC LETTER KHAH ISOLATED FORM;Lo;0;AL;<isolated> 062E;;;;N;GLYPH FOR ISOLATE ARABIC KHAA;;;;
+FEA6;ARABIC LETTER KHAH FINAL FORM;Lo;0;AL;<final> 062E;;;;N;GLYPH FOR FINAL ARABIC KHAA;;;;
+FEA7;ARABIC LETTER KHAH INITIAL FORM;Lo;0;AL;<initial> 062E;;;;N;GLYPH FOR INITIAL ARABIC KHAA;;;;
+FEA8;ARABIC LETTER KHAH MEDIAL FORM;Lo;0;AL;<medial> 062E;;;;N;GLYPH FOR MEDIAL ARABIC KHAA;;;;
+FEA9;ARABIC LETTER DAL ISOLATED FORM;Lo;0;AL;<isolated> 062F;;;;N;GLYPH FOR ISOLATE ARABIC DAL;;;;
+FEAA;ARABIC LETTER DAL FINAL FORM;Lo;0;AL;<final> 062F;;;;N;GLYPH FOR FINAL ARABIC DAL;;;;
+FEAB;ARABIC LETTER THAL ISOLATED FORM;Lo;0;AL;<isolated> 0630;;;;N;GLYPH FOR ISOLATE ARABIC THAL;;;;
+FEAC;ARABIC LETTER THAL FINAL FORM;Lo;0;AL;<final> 0630;;;;N;GLYPH FOR FINAL ARABIC THAL;;;;
+FEAD;ARABIC LETTER REH ISOLATED FORM;Lo;0;AL;<isolated> 0631;;;;N;GLYPH FOR ISOLATE ARABIC RA;;;;
+FEAE;ARABIC LETTER REH FINAL FORM;Lo;0;AL;<final> 0631;;;;N;GLYPH FOR FINAL ARABIC RA;;;;
+FEAF;ARABIC LETTER ZAIN ISOLATED FORM;Lo;0;AL;<isolated> 0632;;;;N;GLYPH FOR ISOLATE ARABIC ZAIN;;;;
+FEB0;ARABIC LETTER ZAIN FINAL FORM;Lo;0;AL;<final> 0632;;;;N;GLYPH FOR FINAL ARABIC ZAIN;;;;
+FEB1;ARABIC LETTER SEEN ISOLATED FORM;Lo;0;AL;<isolated> 0633;;;;N;GLYPH FOR ISOLATE ARABIC SEEN;;;;
+FEB2;ARABIC LETTER SEEN FINAL FORM;Lo;0;AL;<final> 0633;;;;N;GLYPH FOR FINAL ARABIC SEEN;;;;
+FEB3;ARABIC LETTER SEEN INITIAL FORM;Lo;0;AL;<initial> 0633;;;;N;GLYPH FOR INITIAL ARABIC SEEN;;;;
+FEB4;ARABIC LETTER SEEN MEDIAL FORM;Lo;0;AL;<medial> 0633;;;;N;GLYPH FOR MEDIAL ARABIC SEEN;;;;
+FEB5;ARABIC LETTER SHEEN ISOLATED FORM;Lo;0;AL;<isolated> 0634;;;;N;GLYPH FOR ISOLATE ARABIC SHEEN;;;;
+FEB6;ARABIC LETTER SHEEN FINAL FORM;Lo;0;AL;<final> 0634;;;;N;GLYPH FOR FINAL ARABIC SHEEN;;;;
+FEB7;ARABIC LETTER SHEEN INITIAL FORM;Lo;0;AL;<initial> 0634;;;;N;GLYPH FOR INITIAL ARABIC SHEEN;;;;
+FEB8;ARABIC LETTER SHEEN MEDIAL FORM;Lo;0;AL;<medial> 0634;;;;N;GLYPH FOR MEDIAL ARABIC SHEEN;;;;
+FEB9;ARABIC LETTER SAD ISOLATED FORM;Lo;0;AL;<isolated> 0635;;;;N;GLYPH FOR ISOLATE ARABIC SAD;;;;
+FEBA;ARABIC LETTER SAD FINAL FORM;Lo;0;AL;<final> 0635;;;;N;GLYPH FOR FINAL ARABIC SAD;;;;
+FEBB;ARABIC LETTER SAD INITIAL FORM;Lo;0;AL;<initial> 0635;;;;N;GLYPH FOR INITIAL ARABIC SAD;;;;
+FEBC;ARABIC LETTER SAD MEDIAL FORM;Lo;0;AL;<medial> 0635;;;;N;GLYPH FOR MEDIAL ARABIC SAD;;;;
+FEBD;ARABIC LETTER DAD ISOLATED FORM;Lo;0;AL;<isolated> 0636;;;;N;GLYPH FOR ISOLATE ARABIC DAD;;;;
+FEBE;ARABIC LETTER DAD FINAL FORM;Lo;0;AL;<final> 0636;;;;N;GLYPH FOR FINAL ARABIC DAD;;;;
+FEBF;ARABIC LETTER DAD INITIAL FORM;Lo;0;AL;<initial> 0636;;;;N;GLYPH FOR INITIAL ARABIC DAD;;;;
+FEC0;ARABIC LETTER DAD MEDIAL FORM;Lo;0;AL;<medial> 0636;;;;N;GLYPH FOR MEDIAL ARABIC DAD;;;;
+FEC1;ARABIC LETTER TAH ISOLATED FORM;Lo;0;AL;<isolated> 0637;;;;N;GLYPH FOR ISOLATE ARABIC TAH;;;;
+FEC2;ARABIC LETTER TAH FINAL FORM;Lo;0;AL;<final> 0637;;;;N;GLYPH FOR FINAL ARABIC TAH;;;;
+FEC3;ARABIC LETTER TAH INITIAL FORM;Lo;0;AL;<initial> 0637;;;;N;GLYPH FOR INITIAL ARABIC TAH;;;;
+FEC4;ARABIC LETTER TAH MEDIAL FORM;Lo;0;AL;<medial> 0637;;;;N;GLYPH FOR MEDIAL ARABIC TAH;;;;
+FEC5;ARABIC LETTER ZAH ISOLATED FORM;Lo;0;AL;<isolated> 0638;;;;N;GLYPH FOR ISOLATE ARABIC DHAH;;;;
+FEC6;ARABIC LETTER ZAH FINAL FORM;Lo;0;AL;<final> 0638;;;;N;GLYPH FOR FINAL ARABIC DHAH;;;;
+FEC7;ARABIC LETTER ZAH INITIAL FORM;Lo;0;AL;<initial> 0638;;;;N;GLYPH FOR INITIAL ARABIC DHAH;;;;
+FEC8;ARABIC LETTER ZAH MEDIAL FORM;Lo;0;AL;<medial> 0638;;;;N;GLYPH FOR MEDIAL ARABIC DHAH;;;;
+FEC9;ARABIC LETTER AIN ISOLATED FORM;Lo;0;AL;<isolated> 0639;;;;N;GLYPH FOR ISOLATE ARABIC AIN;;;;
+FECA;ARABIC LETTER AIN FINAL FORM;Lo;0;AL;<final> 0639;;;;N;GLYPH FOR FINAL ARABIC AIN;;;;
+FECB;ARABIC LETTER AIN INITIAL FORM;Lo;0;AL;<initial> 0639;;;;N;GLYPH FOR INITIAL ARABIC AIN;;;;
+FECC;ARABIC LETTER AIN MEDIAL FORM;Lo;0;AL;<medial> 0639;;;;N;GLYPH FOR MEDIAL ARABIC AIN;;;;
+FECD;ARABIC LETTER GHAIN ISOLATED FORM;Lo;0;AL;<isolated> 063A;;;;N;GLYPH FOR ISOLATE ARABIC GHAIN;;;;
+FECE;ARABIC LETTER GHAIN FINAL FORM;Lo;0;AL;<final> 063A;;;;N;GLYPH FOR FINAL ARABIC GHAIN;;;;
+FECF;ARABIC LETTER GHAIN INITIAL FORM;Lo;0;AL;<initial> 063A;;;;N;GLYPH FOR INITIAL ARABIC GHAIN;;;;
+FED0;ARABIC LETTER GHAIN MEDIAL FORM;Lo;0;AL;<medial> 063A;;;;N;GLYPH FOR MEDIAL ARABIC GHAIN;;;;
+FED1;ARABIC LETTER FEH ISOLATED FORM;Lo;0;AL;<isolated> 0641;;;;N;GLYPH FOR ISOLATE ARABIC FA;;;;
+FED2;ARABIC LETTER FEH FINAL FORM;Lo;0;AL;<final> 0641;;;;N;GLYPH FOR FINAL ARABIC FA;;;;
+FED3;ARABIC LETTER FEH INITIAL FORM;Lo;0;AL;<initial> 0641;;;;N;GLYPH FOR INITIAL ARABIC FA;;;;
+FED4;ARABIC LETTER FEH MEDIAL FORM;Lo;0;AL;<medial> 0641;;;;N;GLYPH FOR MEDIAL ARABIC FA;;;;
+FED5;ARABIC LETTER QAF ISOLATED FORM;Lo;0;AL;<isolated> 0642;;;;N;GLYPH FOR ISOLATE ARABIC QAF;;;;
+FED6;ARABIC LETTER QAF FINAL FORM;Lo;0;AL;<final> 0642;;;;N;GLYPH FOR FINAL ARABIC QAF;;;;
+FED7;ARABIC LETTER QAF INITIAL FORM;Lo;0;AL;<initial> 0642;;;;N;GLYPH FOR INITIAL ARABIC QAF;;;;
+FED8;ARABIC LETTER QAF MEDIAL FORM;Lo;0;AL;<medial> 0642;;;;N;GLYPH FOR MEDIAL ARABIC QAF;;;;
+FED9;ARABIC LETTER KAF ISOLATED FORM;Lo;0;AL;<isolated> 0643;;;;N;GLYPH FOR ISOLATE ARABIC CAF;;;;
+FEDA;ARABIC LETTER KAF FINAL FORM;Lo;0;AL;<final> 0643;;;;N;GLYPH FOR FINAL ARABIC CAF;;;;
+FEDB;ARABIC LETTER KAF INITIAL FORM;Lo;0;AL;<initial> 0643;;;;N;GLYPH FOR INITIAL ARABIC CAF;;;;
+FEDC;ARABIC LETTER KAF MEDIAL FORM;Lo;0;AL;<medial> 0643;;;;N;GLYPH FOR MEDIAL ARABIC CAF;;;;
+FEDD;ARABIC LETTER LAM ISOLATED FORM;Lo;0;AL;<isolated> 0644;;;;N;GLYPH FOR ISOLATE ARABIC LAM;;;;
+FEDE;ARABIC LETTER LAM FINAL FORM;Lo;0;AL;<final> 0644;;;;N;GLYPH FOR FINAL ARABIC LAM;;;;
+FEDF;ARABIC LETTER LAM INITIAL FORM;Lo;0;AL;<initial> 0644;;;;N;GLYPH FOR INITIAL ARABIC LAM;;;;
+FEE0;ARABIC LETTER LAM MEDIAL FORM;Lo;0;AL;<medial> 0644;;;;N;GLYPH FOR MEDIAL ARABIC LAM;;;;
+FEE1;ARABIC LETTER MEEM ISOLATED FORM;Lo;0;AL;<isolated> 0645;;;;N;GLYPH FOR ISOLATE ARABIC MEEM;;;;
+FEE2;ARABIC LETTER MEEM FINAL FORM;Lo;0;AL;<final> 0645;;;;N;GLYPH FOR FINAL ARABIC MEEM;;;;
+FEE3;ARABIC LETTER MEEM INITIAL FORM;Lo;0;AL;<initial> 0645;;;;N;GLYPH FOR INITIAL ARABIC MEEM;;;;
+FEE4;ARABIC LETTER MEEM MEDIAL FORM;Lo;0;AL;<medial> 0645;;;;N;GLYPH FOR MEDIAL ARABIC MEEM;;;;
+FEE5;ARABIC LETTER NOON ISOLATED FORM;Lo;0;AL;<isolated> 0646;;;;N;GLYPH FOR ISOLATE ARABIC NOON;;;;
+FEE6;ARABIC LETTER NOON FINAL FORM;Lo;0;AL;<final> 0646;;;;N;GLYPH FOR FINAL ARABIC NOON;;;;
+FEE7;ARABIC LETTER NOON INITIAL FORM;Lo;0;AL;<initial> 0646;;;;N;GLYPH FOR INITIAL ARABIC NOON;;;;
+FEE8;ARABIC LETTER NOON MEDIAL FORM;Lo;0;AL;<medial> 0646;;;;N;GLYPH FOR MEDIAL ARABIC NOON;;;;
+FEE9;ARABIC LETTER HEH ISOLATED FORM;Lo;0;AL;<isolated> 0647;;;;N;GLYPH FOR ISOLATE ARABIC HA;;;;
+FEEA;ARABIC LETTER HEH FINAL FORM;Lo;0;AL;<final> 0647;;;;N;GLYPH FOR FINAL ARABIC HA;;;;
+FEEB;ARABIC LETTER HEH INITIAL FORM;Lo;0;AL;<initial> 0647;;;;N;GLYPH FOR INITIAL ARABIC HA;;;;
+FEEC;ARABIC LETTER HEH MEDIAL FORM;Lo;0;AL;<medial> 0647;;;;N;GLYPH FOR MEDIAL ARABIC HA;;;;
+FEED;ARABIC LETTER WAW ISOLATED FORM;Lo;0;AL;<isolated> 0648;;;;N;GLYPH FOR ISOLATE ARABIC WAW;;;;
+FEEE;ARABIC LETTER WAW FINAL FORM;Lo;0;AL;<final> 0648;;;;N;GLYPH FOR FINAL ARABIC WAW;;;;
+FEEF;ARABIC LETTER ALEF MAKSURA ISOLATED FORM;Lo;0;AL;<isolated> 0649;;;;N;GLYPH FOR ISOLATE ARABIC ALEF MAQSURAH;;;;
+FEF0;ARABIC LETTER ALEF MAKSURA FINAL FORM;Lo;0;AL;<final> 0649;;;;N;GLYPH FOR FINAL ARABIC ALEF MAQSURAH;;;;
+FEF1;ARABIC LETTER YEH ISOLATED FORM;Lo;0;AL;<isolated> 064A;;;;N;GLYPH FOR ISOLATE ARABIC YA;;;;
+FEF2;ARABIC LETTER YEH FINAL FORM;Lo;0;AL;<final> 064A;;;;N;GLYPH FOR FINAL ARABIC YA;;;;
+FEF3;ARABIC LETTER YEH INITIAL FORM;Lo;0;AL;<initial> 064A;;;;N;GLYPH FOR INITIAL ARABIC YA;;;;
+FEF4;ARABIC LETTER YEH MEDIAL FORM;Lo;0;AL;<medial> 064A;;;;N;GLYPH FOR MEDIAL ARABIC YA;;;;
+FEF5;ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM;Lo;0;AL;<isolated> 0644 0622;;;;N;GLYPH FOR ISOLATE ARABIC MADDAH ON LIGATURE LAM ALEF;;;;
+FEF6;ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE FINAL FORM;Lo;0;AL;<final> 0644 0622;;;;N;GLYPH FOR FINAL ARABIC MADDAH ON LIGATURE LAM ALEF;;;;
+FEF7;ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE ISOLATED FORM;Lo;0;AL;<isolated> 0644 0623;;;;N;GLYPH FOR ISOLATE ARABIC HAMZAH ON LIGATURE LAM ALEF;;;;
+FEF8;ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE FINAL FORM;Lo;0;AL;<final> 0644 0623;;;;N;GLYPH FOR FINAL ARABIC HAMZAH ON LIGATURE LAM ALEF;;;;
+FEF9;ARABIC LIGATURE LAM WITH ALEF WITH HAMZA BELOW ISOLATED FORM;Lo;0;AL;<isolated> 0644 0625;;;;N;GLYPH FOR ISOLATE ARABIC HAMZAH UNDER LIGATURE LAM ALEF;;;;
+FEFA;ARABIC LIGATURE LAM WITH ALEF WITH HAMZA BELOW FINAL FORM;Lo;0;AL;<final> 0644 0625;;;;N;GLYPH FOR FINAL ARABIC HAMZAH UNDER LIGATURE LAM ALEF;;;;
+FEFB;ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM;Lo;0;AL;<isolated> 0644 0627;;;;N;GLYPH FOR ISOLATE ARABIC LIGATURE LAM ALEF;;;;
+FEFC;ARABIC LIGATURE LAM WITH ALEF FINAL FORM;Lo;0;AL;<final> 0644 0627;;;;N;GLYPH FOR FINAL ARABIC LIGATURE LAM ALEF;;;;
+FEFF;ZERO WIDTH NO-BREAK SPACE;Cf;0;BN;;;;;N;BYTE ORDER MARK;;;;
+FF01;FULLWIDTH EXCLAMATION MARK;Po;0;ON;<wide> 0021;;;;N;;;;;
+FF02;FULLWIDTH QUOTATION MARK;Po;0;ON;<wide> 0022;;;;N;;;;;
+FF03;FULLWIDTH NUMBER SIGN;Po;0;ET;<wide> 0023;;;;N;;;;;
+FF04;FULLWIDTH DOLLAR SIGN;Sc;0;ET;<wide> 0024;;;;N;;;;;
+FF05;FULLWIDTH PERCENT SIGN;Po;0;ET;<wide> 0025;;;;N;;;;;
+FF06;FULLWIDTH AMPERSAND;Po;0;ON;<wide> 0026;;;;N;;;;;
+FF07;FULLWIDTH APOSTROPHE;Po;0;ON;<wide> 0027;;;;N;;;;;
+FF08;FULLWIDTH LEFT PARENTHESIS;Ps;0;ON;<wide> 0028;;;;Y;FULLWIDTH OPENING PARENTHESIS;;;;
+FF09;FULLWIDTH RIGHT PARENTHESIS;Pe;0;ON;<wide> 0029;;;;Y;FULLWIDTH CLOSING PARENTHESIS;;;;
+FF0A;FULLWIDTH ASTERISK;Po;0;ON;<wide> 002A;;;;N;;;;;
+FF0B;FULLWIDTH PLUS SIGN;Sm;0;ET;<wide> 002B;;;;N;;;;;
+FF0C;FULLWIDTH COMMA;Po;0;CS;<wide> 002C;;;;N;;;;;
+FF0D;FULLWIDTH HYPHEN-MINUS;Pd;0;ET;<wide> 002D;;;;N;;;;;
+FF0E;FULLWIDTH FULL STOP;Po;0;CS;<wide> 002E;;;;N;FULLWIDTH PERIOD;;;;
+FF0F;FULLWIDTH SOLIDUS;Po;0;ES;<wide> 002F;;;;N;FULLWIDTH SLASH;;;;
+FF10;FULLWIDTH DIGIT ZERO;Nd;0;EN;<wide> 0030;0;0;0;N;;;;;
+FF11;FULLWIDTH DIGIT ONE;Nd;0;EN;<wide> 0031;1;1;1;N;;;;;
+FF12;FULLWIDTH DIGIT TWO;Nd;0;EN;<wide> 0032;2;2;2;N;;;;;
+FF13;FULLWIDTH DIGIT THREE;Nd;0;EN;<wide> 0033;3;3;3;N;;;;;
+FF14;FULLWIDTH DIGIT FOUR;Nd;0;EN;<wide> 0034;4;4;4;N;;;;;
+FF15;FULLWIDTH DIGIT FIVE;Nd;0;EN;<wide> 0035;5;5;5;N;;;;;
+FF16;FULLWIDTH DIGIT SIX;Nd;0;EN;<wide> 0036;6;6;6;N;;;;;
+FF17;FULLWIDTH DIGIT SEVEN;Nd;0;EN;<wide> 0037;7;7;7;N;;;;;
+FF18;FULLWIDTH DIGIT EIGHT;Nd;0;EN;<wide> 0038;8;8;8;N;;;;;
+FF19;FULLWIDTH DIGIT NINE;Nd;0;EN;<wide> 0039;9;9;9;N;;;;;
+FF1A;FULLWIDTH COLON;Po;0;CS;<wide> 003A;;;;N;;;;;
+FF1B;FULLWIDTH SEMICOLON;Po;0;ON;<wide> 003B;;;;N;;;;;
+FF1C;FULLWIDTH LESS-THAN SIGN;Sm;0;ON;<wide> 003C;;;;Y;;;;;
+FF1D;FULLWIDTH EQUALS SIGN;Sm;0;ON;<wide> 003D;;;;N;;;;;
+FF1E;FULLWIDTH GREATER-THAN SIGN;Sm;0;ON;<wide> 003E;;;;Y;;;;;
+FF1F;FULLWIDTH QUESTION MARK;Po;0;ON;<wide> 003F;;;;N;;;;;
+FF20;FULLWIDTH COMMERCIAL AT;Po;0;ON;<wide> 0040;;;;N;;;;;
+FF21;FULLWIDTH LATIN CAPITAL LETTER A;Lu;0;L;<wide> 0041;;;;N;;;;FF41;
+FF22;FULLWIDTH LATIN CAPITAL LETTER B;Lu;0;L;<wide> 0042;;;;N;;;;FF42;
+FF23;FULLWIDTH LATIN CAPITAL LETTER C;Lu;0;L;<wide> 0043;;;;N;;;;FF43;
+FF24;FULLWIDTH LATIN CAPITAL LETTER D;Lu;0;L;<wide> 0044;;;;N;;;;FF44;
+FF25;FULLWIDTH LATIN CAPITAL LETTER E;Lu;0;L;<wide> 0045;;;;N;;;;FF45;
+FF26;FULLWIDTH LATIN CAPITAL LETTER F;Lu;0;L;<wide> 0046;;;;N;;;;FF46;
+FF27;FULLWIDTH LATIN CAPITAL LETTER G;Lu;0;L;<wide> 0047;;;;N;;;;FF47;
+FF28;FULLWIDTH LATIN CAPITAL LETTER H;Lu;0;L;<wide> 0048;;;;N;;;;FF48;
+FF29;FULLWIDTH LATIN CAPITAL LETTER I;Lu;0;L;<wide> 0049;;;;N;;;;FF49;
+FF2A;FULLWIDTH LATIN CAPITAL LETTER J;Lu;0;L;<wide> 004A;;;;N;;;;FF4A;
+FF2B;FULLWIDTH LATIN CAPITAL LETTER K;Lu;0;L;<wide> 004B;;;;N;;;;FF4B;
+FF2C;FULLWIDTH LATIN CAPITAL LETTER L;Lu;0;L;<wide> 004C;;;;N;;;;FF4C;
+FF2D;FULLWIDTH LATIN CAPITAL LETTER M;Lu;0;L;<wide> 004D;;;;N;;;;FF4D;
+FF2E;FULLWIDTH LATIN CAPITAL LETTER N;Lu;0;L;<wide> 004E;;;;N;;;;FF4E;
+FF2F;FULLWIDTH LATIN CAPITAL LETTER O;Lu;0;L;<wide> 004F;;;;N;;;;FF4F;
+FF30;FULLWIDTH LATIN CAPITAL LETTER P;Lu;0;L;<wide> 0050;;;;N;;;;FF50;
+FF31;FULLWIDTH LATIN CAPITAL LETTER Q;Lu;0;L;<wide> 0051;;;;N;;;;FF51;
+FF32;FULLWIDTH LATIN CAPITAL LETTER R;Lu;0;L;<wide> 0052;;;;N;;;;FF52;
+FF33;FULLWIDTH LATIN CAPITAL LETTER S;Lu;0;L;<wide> 0053;;;;N;;;;FF53;
+FF34;FULLWIDTH LATIN CAPITAL LETTER T;Lu;0;L;<wide> 0054;;;;N;;;;FF54;
+FF35;FULLWIDTH LATIN CAPITAL LETTER U;Lu;0;L;<wide> 0055;;;;N;;;;FF55;
+FF36;FULLWIDTH LATIN CAPITAL LETTER V;Lu;0;L;<wide> 0056;;;;N;;;;FF56;
+FF37;FULLWIDTH LATIN CAPITAL LETTER W;Lu;0;L;<wide> 0057;;;;N;;;;FF57;
+FF38;FULLWIDTH LATIN CAPITAL LETTER X;Lu;0;L;<wide> 0058;;;;N;;;;FF58;
+FF39;FULLWIDTH LATIN CAPITAL LETTER Y;Lu;0;L;<wide> 0059;;;;N;;;;FF59;
+FF3A;FULLWIDTH LATIN CAPITAL LETTER Z;Lu;0;L;<wide> 005A;;;;N;;;;FF5A;
+FF3B;FULLWIDTH LEFT SQUARE BRACKET;Ps;0;ON;<wide> 005B;;;;Y;FULLWIDTH OPENING SQUARE BRACKET;;;;
+FF3C;FULLWIDTH REVERSE SOLIDUS;Po;0;ON;<wide> 005C;;;;N;FULLWIDTH BACKSLASH;;;;
+FF3D;FULLWIDTH RIGHT SQUARE BRACKET;Pe;0;ON;<wide> 005D;;;;Y;FULLWIDTH CLOSING SQUARE BRACKET;;;;
+FF3E;FULLWIDTH CIRCUMFLEX ACCENT;Sk;0;ON;<wide> 005E;;;;N;FULLWIDTH SPACING CIRCUMFLEX;;;;
+FF3F;FULLWIDTH LOW LINE;Pc;0;ON;<wide> 005F;;;;N;FULLWIDTH SPACING UNDERSCORE;;;;
+FF40;FULLWIDTH GRAVE ACCENT;Sk;0;ON;<wide> 0060;;;;N;FULLWIDTH SPACING GRAVE;;;;
+FF41;FULLWIDTH LATIN SMALL LETTER A;Ll;0;L;<wide> 0061;;;;N;;;FF21;;FF21
+FF42;FULLWIDTH LATIN SMALL LETTER B;Ll;0;L;<wide> 0062;;;;N;;;FF22;;FF22
+FF43;FULLWIDTH LATIN SMALL LETTER C;Ll;0;L;<wide> 0063;;;;N;;;FF23;;FF23
+FF44;FULLWIDTH LATIN SMALL LETTER D;Ll;0;L;<wide> 0064;;;;N;;;FF24;;FF24
+FF45;FULLWIDTH LATIN SMALL LETTER E;Ll;0;L;<wide> 0065;;;;N;;;FF25;;FF25
+FF46;FULLWIDTH LATIN SMALL LETTER F;Ll;0;L;<wide> 0066;;;;N;;;FF26;;FF26
+FF47;FULLWIDTH LATIN SMALL LETTER G;Ll;0;L;<wide> 0067;;;;N;;;FF27;;FF27
+FF48;FULLWIDTH LATIN SMALL LETTER H;Ll;0;L;<wide> 0068;;;;N;;;FF28;;FF28
+FF49;FULLWIDTH LATIN SMALL LETTER I;Ll;0;L;<wide> 0069;;;;N;;;FF29;;FF29
+FF4A;FULLWIDTH LATIN SMALL LETTER J;Ll;0;L;<wide> 006A;;;;N;;;FF2A;;FF2A
+FF4B;FULLWIDTH LATIN SMALL LETTER K;Ll;0;L;<wide> 006B;;;;N;;;FF2B;;FF2B
+FF4C;FULLWIDTH LATIN SMALL LETTER L;Ll;0;L;<wide> 006C;;;;N;;;FF2C;;FF2C
+FF4D;FULLWIDTH LATIN SMALL LETTER M;Ll;0;L;<wide> 006D;;;;N;;;FF2D;;FF2D
+FF4E;FULLWIDTH LATIN SMALL LETTER N;Ll;0;L;<wide> 006E;;;;N;;;FF2E;;FF2E
+FF4F;FULLWIDTH LATIN SMALL LETTER O;Ll;0;L;<wide> 006F;;;;N;;;FF2F;;FF2F
+FF50;FULLWIDTH LATIN SMALL LETTER P;Ll;0;L;<wide> 0070;;;;N;;;FF30;;FF30
+FF51;FULLWIDTH LATIN SMALL LETTER Q;Ll;0;L;<wide> 0071;;;;N;;;FF31;;FF31
+FF52;FULLWIDTH LATIN SMALL LETTER R;Ll;0;L;<wide> 0072;;;;N;;;FF32;;FF32
+FF53;FULLWIDTH LATIN SMALL LETTER S;Ll;0;L;<wide> 0073;;;;N;;;FF33;;FF33
+FF54;FULLWIDTH LATIN SMALL LETTER T;Ll;0;L;<wide> 0074;;;;N;;;FF34;;FF34
+FF55;FULLWIDTH LATIN SMALL LETTER U;Ll;0;L;<wide> 0075;;;;N;;;FF35;;FF35
+FF56;FULLWIDTH LATIN SMALL LETTER V;Ll;0;L;<wide> 0076;;;;N;;;FF36;;FF36
+FF57;FULLWIDTH LATIN SMALL LETTER W;Ll;0;L;<wide> 0077;;;;N;;;FF37;;FF37
+FF58;FULLWIDTH LATIN SMALL LETTER X;Ll;0;L;<wide> 0078;;;;N;;;FF38;;FF38
+FF59;FULLWIDTH LATIN SMALL LETTER Y;Ll;0;L;<wide> 0079;;;;N;;;FF39;;FF39
+FF5A;FULLWIDTH LATIN SMALL LETTER Z;Ll;0;L;<wide> 007A;;;;N;;;FF3A;;FF3A
+FF5B;FULLWIDTH LEFT CURLY BRACKET;Ps;0;ON;<wide> 007B;;;;Y;FULLWIDTH OPENING CURLY BRACKET;;;;
+FF5C;FULLWIDTH VERTICAL LINE;Sm;0;ON;<wide> 007C;;;;N;FULLWIDTH VERTICAL BAR;;;;
+FF5D;FULLWIDTH RIGHT CURLY BRACKET;Pe;0;ON;<wide> 007D;;;;Y;FULLWIDTH CLOSING CURLY BRACKET;;;;
+FF5E;FULLWIDTH TILDE;Sm;0;ON;<wide> 007E;;;;N;FULLWIDTH SPACING TILDE;;;;
+FF5F;FULLWIDTH LEFT WHITE PARENTHESIS;Ps;0;ON;<wide> 2985;;;;Y;;*;;;
+FF60;FULLWIDTH RIGHT WHITE PARENTHESIS;Pe;0;ON;<wide> 2986;;;;Y;;*;;;
+FF61;HALFWIDTH IDEOGRAPHIC FULL STOP;Po;0;ON;<narrow> 3002;;;;N;HALFWIDTH IDEOGRAPHIC PERIOD;;;;
+FF62;HALFWIDTH LEFT CORNER BRACKET;Ps;0;ON;<narrow> 300C;;;;Y;HALFWIDTH OPENING CORNER BRACKET;;;;
+FF63;HALFWIDTH RIGHT CORNER BRACKET;Pe;0;ON;<narrow> 300D;;;;Y;HALFWIDTH CLOSING CORNER BRACKET;;;;
+FF64;HALFWIDTH IDEOGRAPHIC COMMA;Po;0;ON;<narrow> 3001;;;;N;;;;;
+FF65;HALFWIDTH KATAKANA MIDDLE DOT;Pc;0;ON;<narrow> 30FB;;;;N;;;;;
+FF66;HALFWIDTH KATAKANA LETTER WO;Lo;0;L;<narrow> 30F2;;;;N;;;;;
+FF67;HALFWIDTH KATAKANA LETTER SMALL A;Lo;0;L;<narrow> 30A1;;;;N;;;;;
+FF68;HALFWIDTH KATAKANA LETTER SMALL I;Lo;0;L;<narrow> 30A3;;;;N;;;;;
+FF69;HALFWIDTH KATAKANA LETTER SMALL U;Lo;0;L;<narrow> 30A5;;;;N;;;;;
+FF6A;HALFWIDTH KATAKANA LETTER SMALL E;Lo;0;L;<narrow> 30A7;;;;N;;;;;
+FF6B;HALFWIDTH KATAKANA LETTER SMALL O;Lo;0;L;<narrow> 30A9;;;;N;;;;;
+FF6C;HALFWIDTH KATAKANA LETTER SMALL YA;Lo;0;L;<narrow> 30E3;;;;N;;;;;
+FF6D;HALFWIDTH KATAKANA LETTER SMALL YU;Lo;0;L;<narrow> 30E5;;;;N;;;;;
+FF6E;HALFWIDTH KATAKANA LETTER SMALL YO;Lo;0;L;<narrow> 30E7;;;;N;;;;;
+FF6F;HALFWIDTH KATAKANA LETTER SMALL TU;Lo;0;L;<narrow> 30C3;;;;N;;;;;
+FF70;HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK;Lm;0;L;<narrow> 30FC;;;;N;;;;;
+FF71;HALFWIDTH KATAKANA LETTER A;Lo;0;L;<narrow> 30A2;;;;N;;;;;
+FF72;HALFWIDTH KATAKANA LETTER I;Lo;0;L;<narrow> 30A4;;;;N;;;;;
+FF73;HALFWIDTH KATAKANA LETTER U;Lo;0;L;<narrow> 30A6;;;;N;;;;;
+FF74;HALFWIDTH KATAKANA LETTER E;Lo;0;L;<narrow> 30A8;;;;N;;;;;
+FF75;HALFWIDTH KATAKANA LETTER O;Lo;0;L;<narrow> 30AA;;;;N;;;;;
+FF76;HALFWIDTH KATAKANA LETTER KA;Lo;0;L;<narrow> 30AB;;;;N;;;;;
+FF77;HALFWIDTH KATAKANA LETTER KI;Lo;0;L;<narrow> 30AD;;;;N;;;;;
+FF78;HALFWIDTH KATAKANA LETTER KU;Lo;0;L;<narrow> 30AF;;;;N;;;;;
+FF79;HALFWIDTH KATAKANA LETTER KE;Lo;0;L;<narrow> 30B1;;;;N;;;;;
+FF7A;HALFWIDTH KATAKANA LETTER KO;Lo;0;L;<narrow> 30B3;;;;N;;;;;
+FF7B;HALFWIDTH KATAKANA LETTER SA;Lo;0;L;<narrow> 30B5;;;;N;;;;;
+FF7C;HALFWIDTH KATAKANA LETTER SI;Lo;0;L;<narrow> 30B7;;;;N;;;;;
+FF7D;HALFWIDTH KATAKANA LETTER SU;Lo;0;L;<narrow> 30B9;;;;N;;;;;
+FF7E;HALFWIDTH KATAKANA LETTER SE;Lo;0;L;<narrow> 30BB;;;;N;;;;;
+FF7F;HALFWIDTH KATAKANA LETTER SO;Lo;0;L;<narrow> 30BD;;;;N;;;;;
+FF80;HALFWIDTH KATAKANA LETTER TA;Lo;0;L;<narrow> 30BF;;;;N;;;;;
+FF81;HALFWIDTH KATAKANA LETTER TI;Lo;0;L;<narrow> 30C1;;;;N;;;;;
+FF82;HALFWIDTH KATAKANA LETTER TU;Lo;0;L;<narrow> 30C4;;;;N;;;;;
+FF83;HALFWIDTH KATAKANA LETTER TE;Lo;0;L;<narrow> 30C6;;;;N;;;;;
+FF84;HALFWIDTH KATAKANA LETTER TO;Lo;0;L;<narrow> 30C8;;;;N;;;;;
+FF85;HALFWIDTH KATAKANA LETTER NA;Lo;0;L;<narrow> 30CA;;;;N;;;;;
+FF86;HALFWIDTH KATAKANA LETTER NI;Lo;0;L;<narrow> 30CB;;;;N;;;;;
+FF87;HALFWIDTH KATAKANA LETTER NU;Lo;0;L;<narrow> 30CC;;;;N;;;;;
+FF88;HALFWIDTH KATAKANA LETTER NE;Lo;0;L;<narrow> 30CD;;;;N;;;;;
+FF89;HALFWIDTH KATAKANA LETTER NO;Lo;0;L;<narrow> 30CE;;;;N;;;;;
+FF8A;HALFWIDTH KATAKANA LETTER HA;Lo;0;L;<narrow> 30CF;;;;N;;;;;
+FF8B;HALFWIDTH KATAKANA LETTER HI;Lo;0;L;<narrow> 30D2;;;;N;;;;;
+FF8C;HALFWIDTH KATAKANA LETTER HU;Lo;0;L;<narrow> 30D5;;;;N;;;;;
+FF8D;HALFWIDTH KATAKANA LETTER HE;Lo;0;L;<narrow> 30D8;;;;N;;;;;
+FF8E;HALFWIDTH KATAKANA LETTER HO;Lo;0;L;<narrow> 30DB;;;;N;;;;;
+FF8F;HALFWIDTH KATAKANA LETTER MA;Lo;0;L;<narrow> 30DE;;;;N;;;;;
+FF90;HALFWIDTH KATAKANA LETTER MI;Lo;0;L;<narrow> 30DF;;;;N;;;;;
+FF91;HALFWIDTH KATAKANA LETTER MU;Lo;0;L;<narrow> 30E0;;;;N;;;;;
+FF92;HALFWIDTH KATAKANA LETTER ME;Lo;0;L;<narrow> 30E1;;;;N;;;;;
+FF93;HALFWIDTH KATAKANA LETTER MO;Lo;0;L;<narrow> 30E2;;;;N;;;;;
+FF94;HALFWIDTH KATAKANA LETTER YA;Lo;0;L;<narrow> 30E4;;;;N;;;;;
+FF95;HALFWIDTH KATAKANA LETTER YU;Lo;0;L;<narrow> 30E6;;;;N;;;;;
+FF96;HALFWIDTH KATAKANA LETTER YO;Lo;0;L;<narrow> 30E8;;;;N;;;;;
+FF97;HALFWIDTH KATAKANA LETTER RA;Lo;0;L;<narrow> 30E9;;;;N;;;;;
+FF98;HALFWIDTH KATAKANA LETTER RI;Lo;0;L;<narrow> 30EA;;;;N;;;;;
+FF99;HALFWIDTH KATAKANA LETTER RU;Lo;0;L;<narrow> 30EB;;;;N;;;;;
+FF9A;HALFWIDTH KATAKANA LETTER RE;Lo;0;L;<narrow> 30EC;;;;N;;;;;
+FF9B;HALFWIDTH KATAKANA LETTER RO;Lo;0;L;<narrow> 30ED;;;;N;;;;;
+FF9C;HALFWIDTH KATAKANA LETTER WA;Lo;0;L;<narrow> 30EF;;;;N;;;;;
+FF9D;HALFWIDTH KATAKANA LETTER N;Lo;0;L;<narrow> 30F3;;;;N;;;;;
+FF9E;HALFWIDTH KATAKANA VOICED SOUND MARK;Lm;0;L;<narrow> 3099;;;;N;;halfwidth katakana-hiragana voiced sound mark;;;
+FF9F;HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK;Lm;0;L;<narrow> 309A;;;;N;;halfwidth katakana-hiragana semi-voiced sound mark;;;
+FFA0;HALFWIDTH HANGUL FILLER;Lo;0;L;<narrow> 3164;;;;N;HALFWIDTH HANGUL CAE OM;;;;
+FFA1;HALFWIDTH HANGUL LETTER KIYEOK;Lo;0;L;<narrow> 3131;;;;N;HALFWIDTH HANGUL LETTER GIYEOG;;;;
+FFA2;HALFWIDTH HANGUL LETTER SSANGKIYEOK;Lo;0;L;<narrow> 3132;;;;N;HALFWIDTH HANGUL LETTER SSANG GIYEOG;;;;
+FFA3;HALFWIDTH HANGUL LETTER KIYEOK-SIOS;Lo;0;L;<narrow> 3133;;;;N;HALFWIDTH HANGUL LETTER GIYEOG SIOS;;;;
+FFA4;HALFWIDTH HANGUL LETTER NIEUN;Lo;0;L;<narrow> 3134;;;;N;;;;;
+FFA5;HALFWIDTH HANGUL LETTER NIEUN-CIEUC;Lo;0;L;<narrow> 3135;;;;N;HALFWIDTH HANGUL LETTER NIEUN JIEUJ;;;;
+FFA6;HALFWIDTH HANGUL LETTER NIEUN-HIEUH;Lo;0;L;<narrow> 3136;;;;N;HALFWIDTH HANGUL LETTER NIEUN HIEUH;;;;
+FFA7;HALFWIDTH HANGUL LETTER TIKEUT;Lo;0;L;<narrow> 3137;;;;N;HALFWIDTH HANGUL LETTER DIGEUD;;;;
+FFA8;HALFWIDTH HANGUL LETTER SSANGTIKEUT;Lo;0;L;<narrow> 3138;;;;N;HALFWIDTH HANGUL LETTER SSANG DIGEUD;;;;
+FFA9;HALFWIDTH HANGUL LETTER RIEUL;Lo;0;L;<narrow> 3139;;;;N;HALFWIDTH HANGUL LETTER LIEUL;;;;
+FFAA;HALFWIDTH HANGUL LETTER RIEUL-KIYEOK;Lo;0;L;<narrow> 313A;;;;N;HALFWIDTH HANGUL LETTER LIEUL GIYEOG;;;;
+FFAB;HALFWIDTH HANGUL LETTER RIEUL-MIEUM;Lo;0;L;<narrow> 313B;;;;N;HALFWIDTH HANGUL LETTER LIEUL MIEUM;;;;
+FFAC;HALFWIDTH HANGUL LETTER RIEUL-PIEUP;Lo;0;L;<narrow> 313C;;;;N;HALFWIDTH HANGUL LETTER LIEUL BIEUB;;;;
+FFAD;HALFWIDTH HANGUL LETTER RIEUL-SIOS;Lo;0;L;<narrow> 313D;;;;N;HALFWIDTH HANGUL LETTER LIEUL SIOS;;;;
+FFAE;HALFWIDTH HANGUL LETTER RIEUL-THIEUTH;Lo;0;L;<narrow> 313E;;;;N;HALFWIDTH HANGUL LETTER LIEUL TIEUT;;;;
+FFAF;HALFWIDTH HANGUL LETTER RIEUL-PHIEUPH;Lo;0;L;<narrow> 313F;;;;N;HALFWIDTH HANGUL LETTER LIEUL PIEUP;;;;
+FFB0;HALFWIDTH HANGUL LETTER RIEUL-HIEUH;Lo;0;L;<narrow> 3140;;;;N;HALFWIDTH HANGUL LETTER LIEUL HIEUH;;;;
+FFB1;HALFWIDTH HANGUL LETTER MIEUM;Lo;0;L;<narrow> 3141;;;;N;;;;;
+FFB2;HALFWIDTH HANGUL LETTER PIEUP;Lo;0;L;<narrow> 3142;;;;N;HALFWIDTH HANGUL LETTER BIEUB;;;;
+FFB3;HALFWIDTH HANGUL LETTER SSANGPIEUP;Lo;0;L;<narrow> 3143;;;;N;HALFWIDTH HANGUL LETTER SSANG BIEUB;;;;
+FFB4;HALFWIDTH HANGUL LETTER PIEUP-SIOS;Lo;0;L;<narrow> 3144;;;;N;HALFWIDTH HANGUL LETTER BIEUB SIOS;;;;
+FFB5;HALFWIDTH HANGUL LETTER SIOS;Lo;0;L;<narrow> 3145;;;;N;;;;;
+FFB6;HALFWIDTH HANGUL LETTER SSANGSIOS;Lo;0;L;<narrow> 3146;;;;N;HALFWIDTH HANGUL LETTER SSANG SIOS;;;;
+FFB7;HALFWIDTH HANGUL LETTER IEUNG;Lo;0;L;<narrow> 3147;;;;N;;;;;
+FFB8;HALFWIDTH HANGUL LETTER CIEUC;Lo;0;L;<narrow> 3148;;;;N;HALFWIDTH HANGUL LETTER JIEUJ;;;;
+FFB9;HALFWIDTH HANGUL LETTER SSANGCIEUC;Lo;0;L;<narrow> 3149;;;;N;HALFWIDTH HANGUL LETTER SSANG JIEUJ;;;;
+FFBA;HALFWIDTH HANGUL LETTER CHIEUCH;Lo;0;L;<narrow> 314A;;;;N;HALFWIDTH HANGUL LETTER CIEUC;;;;
+FFBB;HALFWIDTH HANGUL LETTER KHIEUKH;Lo;0;L;<narrow> 314B;;;;N;HALFWIDTH HANGUL LETTER KIYEOK;;;;
+FFBC;HALFWIDTH HANGUL LETTER THIEUTH;Lo;0;L;<narrow> 314C;;;;N;HALFWIDTH HANGUL LETTER TIEUT;;;;
+FFBD;HALFWIDTH HANGUL LETTER PHIEUPH;Lo;0;L;<narrow> 314D;;;;N;HALFWIDTH HANGUL LETTER PIEUP;;;;
+FFBE;HALFWIDTH HANGUL LETTER HIEUH;Lo;0;L;<narrow> 314E;;;;N;;;;;
+FFC2;HALFWIDTH HANGUL LETTER A;Lo;0;L;<narrow> 314F;;;;N;;;;;
+FFC3;HALFWIDTH HANGUL LETTER AE;Lo;0;L;<narrow> 3150;;;;N;;;;;
+FFC4;HALFWIDTH HANGUL LETTER YA;Lo;0;L;<narrow> 3151;;;;N;;;;;
+FFC5;HALFWIDTH HANGUL LETTER YAE;Lo;0;L;<narrow> 3152;;;;N;;;;;
+FFC6;HALFWIDTH HANGUL LETTER EO;Lo;0;L;<narrow> 3153;;;;N;;;;;
+FFC7;HALFWIDTH HANGUL LETTER E;Lo;0;L;<narrow> 3154;;;;N;;;;;
+FFCA;HALFWIDTH HANGUL LETTER YEO;Lo;0;L;<narrow> 3155;;;;N;;;;;
+FFCB;HALFWIDTH HANGUL LETTER YE;Lo;0;L;<narrow> 3156;;;;N;;;;;
+FFCC;HALFWIDTH HANGUL LETTER O;Lo;0;L;<narrow> 3157;;;;N;;;;;
+FFCD;HALFWIDTH HANGUL LETTER WA;Lo;0;L;<narrow> 3158;;;;N;;;;;
+FFCE;HALFWIDTH HANGUL LETTER WAE;Lo;0;L;<narrow> 3159;;;;N;;;;;
+FFCF;HALFWIDTH HANGUL LETTER OE;Lo;0;L;<narrow> 315A;;;;N;;;;;
+FFD2;HALFWIDTH HANGUL LETTER YO;Lo;0;L;<narrow> 315B;;;;N;;;;;
+FFD3;HALFWIDTH HANGUL LETTER U;Lo;0;L;<narrow> 315C;;;;N;;;;;
+FFD4;HALFWIDTH HANGUL LETTER WEO;Lo;0;L;<narrow> 315D;;;;N;;;;;
+FFD5;HALFWIDTH HANGUL LETTER WE;Lo;0;L;<narrow> 315E;;;;N;;;;;
+FFD6;HALFWIDTH HANGUL LETTER WI;Lo;0;L;<narrow> 315F;;;;N;;;;;
+FFD7;HALFWIDTH HANGUL LETTER YU;Lo;0;L;<narrow> 3160;;;;N;;;;;
+FFDA;HALFWIDTH HANGUL LETTER EU;Lo;0;L;<narrow> 3161;;;;N;;;;;
+FFDB;HALFWIDTH HANGUL LETTER YI;Lo;0;L;<narrow> 3162;;;;N;;;;;
+FFDC;HALFWIDTH HANGUL LETTER I;Lo;0;L;<narrow> 3163;;;;N;;;;;
+FFE0;FULLWIDTH CENT SIGN;Sc;0;ET;<wide> 00A2;;;;N;;;;;
+FFE1;FULLWIDTH POUND SIGN;Sc;0;ET;<wide> 00A3;;;;N;;;;;
+FFE2;FULLWIDTH NOT SIGN;Sm;0;ON;<wide> 00AC;;;;N;;;;;
+FFE3;FULLWIDTH MACRON;Sk;0;ON;<wide> 00AF;;;;N;FULLWIDTH SPACING MACRON;*;;;
+FFE4;FULLWIDTH BROKEN BAR;So;0;ON;<wide> 00A6;;;;N;FULLWIDTH BROKEN VERTICAL BAR;;;;
+FFE5;FULLWIDTH YEN SIGN;Sc;0;ET;<wide> 00A5;;;;N;;;;;
+FFE6;FULLWIDTH WON SIGN;Sc;0;ET;<wide> 20A9;;;;N;;;;;
+FFE8;HALFWIDTH FORMS LIGHT VERTICAL;So;0;ON;<narrow> 2502;;;;N;;;;;
+FFE9;HALFWIDTH LEFTWARDS ARROW;Sm;0;ON;<narrow> 2190;;;;N;;;;;
+FFEA;HALFWIDTH UPWARDS ARROW;Sm;0;ON;<narrow> 2191;;;;N;;;;;
+FFEB;HALFWIDTH RIGHTWARDS ARROW;Sm;0;ON;<narrow> 2192;;;;N;;;;;
+FFEC;HALFWIDTH DOWNWARDS ARROW;Sm;0;ON;<narrow> 2193;;;;N;;;;;
+FFED;HALFWIDTH BLACK SQUARE;So;0;ON;<narrow> 25A0;;;;N;;;;;
+FFEE;HALFWIDTH WHITE CIRCLE;So;0;ON;<narrow> 25CB;;;;N;;;;;
+FFF9;INTERLINEAR ANNOTATION ANCHOR;Cf;0;ON;;;;;N;;;;;
+FFFA;INTERLINEAR ANNOTATION SEPARATOR;Cf;0;ON;;;;;N;;;;;
+FFFB;INTERLINEAR ANNOTATION TERMINATOR;Cf;0;ON;;;;;N;;;;;
+FFFC;OBJECT REPLACEMENT CHARACTER;So;0;ON;;;;;N;;;;;
+FFFD;REPLACEMENT CHARACTER;So;0;ON;;;;;N;;;;;
+10000;LINEAR B SYLLABLE B008 A;Lo;0;L;;;;;N;;;;;
+10001;LINEAR B SYLLABLE B038 E;Lo;0;L;;;;;N;;;;;
+10002;LINEAR B SYLLABLE B028 I;Lo;0;L;;;;;N;;;;;
+10003;LINEAR B SYLLABLE B061 O;Lo;0;L;;;;;N;;;;;
+10004;LINEAR B SYLLABLE B010 U;Lo;0;L;;;;;N;;;;;
+10005;LINEAR B SYLLABLE B001 DA;Lo;0;L;;;;;N;;;;;
+10006;LINEAR B SYLLABLE B045 DE;Lo;0;L;;;;;N;;;;;
+10007;LINEAR B SYLLABLE B007 DI;Lo;0;L;;;;;N;;;;;
+10008;LINEAR B SYLLABLE B014 DO;Lo;0;L;;;;;N;;;;;
+10009;LINEAR B SYLLABLE B051 DU;Lo;0;L;;;;;N;;;;;
+1000A;LINEAR B SYLLABLE B057 JA;Lo;0;L;;;;;N;;;;;
+1000B;LINEAR B SYLLABLE B046 JE;Lo;0;L;;;;;N;;;;;
+1000D;LINEAR B SYLLABLE B036 JO;Lo;0;L;;;;;N;;;;;
+1000E;LINEAR B SYLLABLE B065 JU;Lo;0;L;;;;;N;;;;;
+1000F;LINEAR B SYLLABLE B077 KA;Lo;0;L;;;;;N;;;;;
+10010;LINEAR B SYLLABLE B044 KE;Lo;0;L;;;;;N;;;;;
+10011;LINEAR B SYLLABLE B067 KI;Lo;0;L;;;;;N;;;;;
+10012;LINEAR B SYLLABLE B070 KO;Lo;0;L;;;;;N;;;;;
+10013;LINEAR B SYLLABLE B081 KU;Lo;0;L;;;;;N;;;;;
+10014;LINEAR B SYLLABLE B080 MA;Lo;0;L;;;;;N;;;;;
+10015;LINEAR B SYLLABLE B013 ME;Lo;0;L;;;;;N;;;;;
+10016;LINEAR B SYLLABLE B073 MI;Lo;0;L;;;;;N;;;;;
+10017;LINEAR B SYLLABLE B015 MO;Lo;0;L;;;;;N;;;;;
+10018;LINEAR B SYLLABLE B023 MU;Lo;0;L;;;;;N;;;;;
+10019;LINEAR B SYLLABLE B006 NA;Lo;0;L;;;;;N;;;;;
+1001A;LINEAR B SYLLABLE B024 NE;Lo;0;L;;;;;N;;;;;
+1001B;LINEAR B SYLLABLE B030 NI;Lo;0;L;;;;;N;;;;;
+1001C;LINEAR B SYLLABLE B052 NO;Lo;0;L;;;;;N;;;;;
+1001D;LINEAR B SYLLABLE B055 NU;Lo;0;L;;;;;N;;;;;
+1001E;LINEAR B SYLLABLE B003 PA;Lo;0;L;;;;;N;;;;;
+1001F;LINEAR B SYLLABLE B072 PE;Lo;0;L;;;;;N;;;;;
+10020;LINEAR B SYLLABLE B039 PI;Lo;0;L;;;;;N;;;;;
+10021;LINEAR B SYLLABLE B011 PO;Lo;0;L;;;;;N;;;;;
+10022;LINEAR B SYLLABLE B050 PU;Lo;0;L;;;;;N;;;;;
+10023;LINEAR B SYLLABLE B016 QA;Lo;0;L;;;;;N;;;;;
+10024;LINEAR B SYLLABLE B078 QE;Lo;0;L;;;;;N;;;;;
+10025;LINEAR B SYLLABLE B021 QI;Lo;0;L;;;;;N;;;;;
+10026;LINEAR B SYLLABLE B032 QO;Lo;0;L;;;;;N;;;;;
+10028;LINEAR B SYLLABLE B060 RA;Lo;0;L;;;;;N;;;;;
+10029;LINEAR B SYLLABLE B027 RE;Lo;0;L;;;;;N;;;;;
+1002A;LINEAR B SYLLABLE B053 RI;Lo;0;L;;;;;N;;;;;
+1002B;LINEAR B SYLLABLE B002 RO;Lo;0;L;;;;;N;;;;;
+1002C;LINEAR B SYLLABLE B026 RU;Lo;0;L;;;;;N;;;;;
+1002D;LINEAR B SYLLABLE B031 SA;Lo;0;L;;;;;N;;;;;
+1002E;LINEAR B SYLLABLE B009 SE;Lo;0;L;;;;;N;;;;;
+1002F;LINEAR B SYLLABLE B041 SI;Lo;0;L;;;;;N;;;;;
+10030;LINEAR B SYLLABLE B012 SO;Lo;0;L;;;;;N;;;;;
+10031;LINEAR B SYLLABLE B058 SU;Lo;0;L;;;;;N;;;;;
+10032;LINEAR B SYLLABLE B059 TA;Lo;0;L;;;;;N;;;;;
+10033;LINEAR B SYLLABLE B004 TE;Lo;0;L;;;;;N;;;;;
+10034;LINEAR B SYLLABLE B037 TI;Lo;0;L;;;;;N;;;;;
+10035;LINEAR B SYLLABLE B005 TO;Lo;0;L;;;;;N;;;;;
+10036;LINEAR B SYLLABLE B069 TU;Lo;0;L;;;;;N;;;;;
+10037;LINEAR B SYLLABLE B054 WA;Lo;0;L;;;;;N;;;;;
+10038;LINEAR B SYLLABLE B075 WE;Lo;0;L;;;;;N;;;;;
+10039;LINEAR B SYLLABLE B040 WI;Lo;0;L;;;;;N;;;;;
+1003A;LINEAR B SYLLABLE B042 WO;Lo;0;L;;;;;N;;;;;
+1003C;LINEAR B SYLLABLE B017 ZA;Lo;0;L;;;;;N;;;;;
+1003D;LINEAR B SYLLABLE B074 ZE;Lo;0;L;;;;;N;;;;;
+1003F;LINEAR B SYLLABLE B020 ZO;Lo;0;L;;;;;N;;;;;
+10040;LINEAR B SYLLABLE B025 A2;Lo;0;L;;;;;N;;;;;
+10041;LINEAR B SYLLABLE B043 A3;Lo;0;L;;;;;N;;;;;
+10042;LINEAR B SYLLABLE B085 AU;Lo;0;L;;;;;N;;;;;
+10043;LINEAR B SYLLABLE B071 DWE;Lo;0;L;;;;;N;;;;;
+10044;LINEAR B SYLLABLE B090 DWO;Lo;0;L;;;;;N;;;;;
+10045;LINEAR B SYLLABLE B048 NWA;Lo;0;L;;;;;N;;;;;
+10046;LINEAR B SYLLABLE B029 PU2;Lo;0;L;;;;;N;;;;;
+10047;LINEAR B SYLLABLE B062 PTE;Lo;0;L;;;;;N;;;;;
+10048;LINEAR B SYLLABLE B076 RA2;Lo;0;L;;;;;N;;;;;
+10049;LINEAR B SYLLABLE B033 RA3;Lo;0;L;;;;;N;;;;;
+1004A;LINEAR B SYLLABLE B068 RO2;Lo;0;L;;;;;N;;;;;
+1004B;LINEAR B SYLLABLE B066 TA2;Lo;0;L;;;;;N;;;;;
+1004C;LINEAR B SYLLABLE B087 TWE;Lo;0;L;;;;;N;;;;;
+1004D;LINEAR B SYLLABLE B091 TWO;Lo;0;L;;;;;N;;;;;
+10050;LINEAR B SYMBOL B018;Lo;0;L;;;;;N;;;;;
+10051;LINEAR B SYMBOL B019;Lo;0;L;;;;;N;;;;;
+10052;LINEAR B SYMBOL B022;Lo;0;L;;;;;N;;;;;
+10053;LINEAR B SYMBOL B034;Lo;0;L;;;;;N;;;;;
+10054;LINEAR B SYMBOL B047;Lo;0;L;;;;;N;;;;;
+10055;LINEAR B SYMBOL B049;Lo;0;L;;;;;N;;;;;
+10056;LINEAR B SYMBOL B056;Lo;0;L;;;;;N;;;;;
+10057;LINEAR B SYMBOL B063;Lo;0;L;;;;;N;;;;;
+10058;LINEAR B SYMBOL B064;Lo;0;L;;;;;N;;;;;
+10059;LINEAR B SYMBOL B079;Lo;0;L;;;;;N;;;;;
+1005A;LINEAR B SYMBOL B082;Lo;0;L;;;;;N;;;;;
+1005B;LINEAR B SYMBOL B083;Lo;0;L;;;;;N;;;;;
+1005C;LINEAR B SYMBOL B086;Lo;0;L;;;;;N;;;;;
+1005D;LINEAR B SYMBOL B089;Lo;0;L;;;;;N;;;;;
+10080;LINEAR B IDEOGRAM B100 MAN;Lo;0;L;;;;;N;;;;;
+10081;LINEAR B IDEOGRAM B102 WOMAN;Lo;0;L;;;;;N;;;;;
+10082;LINEAR B IDEOGRAM B104 DEER;Lo;0;L;;;;;N;;;;;
+10083;LINEAR B IDEOGRAM B105 EQUID;Lo;0;L;;;;;N;;;;;
+10084;LINEAR B IDEOGRAM B105F MARE;Lo;0;L;;;;;N;;;;;
+10085;LINEAR B IDEOGRAM B105M STALLION;Lo;0;L;;;;;N;;;;;
+10086;LINEAR B IDEOGRAM B106F EWE;Lo;0;L;;;;;N;;;;;
+10087;LINEAR B IDEOGRAM B106M RAM;Lo;0;L;;;;;N;;;;;
+10088;LINEAR B IDEOGRAM B107F SHE-GOAT;Lo;0;L;;;;;N;;;;;
+10089;LINEAR B IDEOGRAM B107M HE-GOAT;Lo;0;L;;;;;N;;;;;
+1008A;LINEAR B IDEOGRAM B108F SOW;Lo;0;L;;;;;N;;;;;
+1008B;LINEAR B IDEOGRAM B108M BOAR;Lo;0;L;;;;;N;;;;;
+1008C;LINEAR B IDEOGRAM B109F COW;Lo;0;L;;;;;N;;;;;
+1008D;LINEAR B IDEOGRAM B109M BULL;Lo;0;L;;;;;N;;;;;
+1008E;LINEAR B IDEOGRAM B120 WHEAT;Lo;0;L;;;;;N;;;;;
+1008F;LINEAR B IDEOGRAM B121 BARLEY;Lo;0;L;;;;;N;;;;;
+10090;LINEAR B IDEOGRAM B122 OLIVE;Lo;0;L;;;;;N;;;;;
+10091;LINEAR B IDEOGRAM B123 SPICE;Lo;0;L;;;;;N;;;;;
+10092;LINEAR B IDEOGRAM B125 CYPERUS;Lo;0;L;;;;;N;;;;;
+10093;LINEAR B MONOGRAM B127 KAPO;Lo;0;L;;;;;N;;;;;
+10094;LINEAR B MONOGRAM B128 KANAKO;Lo;0;L;;;;;N;;;;;
+10095;LINEAR B IDEOGRAM B130 OIL;Lo;0;L;;;;;N;;;;;
+10096;LINEAR B IDEOGRAM B131 WINE;Lo;0;L;;;;;N;;;;;
+10097;LINEAR B IDEOGRAM B132;Lo;0;L;;;;;N;;;;;
+10098;LINEAR B MONOGRAM B133 AREPA;Lo;0;L;;;;;N;;;;;
+10099;LINEAR B MONOGRAM B135 MERI;Lo;0;L;;;;;N;;;;;
+1009A;LINEAR B IDEOGRAM B140 BRONZE;Lo;0;L;;;;;N;;;;;
+1009B;LINEAR B IDEOGRAM B141 GOLD;Lo;0;L;;;;;N;;;;;
+1009C;LINEAR B IDEOGRAM B142;Lo;0;L;;;;;N;;;;;
+1009D;LINEAR B IDEOGRAM B145 WOOL;Lo;0;L;;;;;N;;;;;
+1009E;LINEAR B IDEOGRAM B146;Lo;0;L;;;;;N;;;;;
+1009F;LINEAR B IDEOGRAM B150;Lo;0;L;;;;;N;;;;;
+100A0;LINEAR B IDEOGRAM B151 HORN;Lo;0;L;;;;;N;;;;;
+100A1;LINEAR B IDEOGRAM B152;Lo;0;L;;;;;N;;;;;
+100A2;LINEAR B IDEOGRAM B153;Lo;0;L;;;;;N;;;;;
+100A3;LINEAR B IDEOGRAM B154;Lo;0;L;;;;;N;;;;;
+100A4;LINEAR B MONOGRAM B156 TURO2;Lo;0;L;;;;;N;;;;;
+100A5;LINEAR B IDEOGRAM B157;Lo;0;L;;;;;N;;;;;
+100A6;LINEAR B IDEOGRAM B158;Lo;0;L;;;;;N;;;;;
+100A7;LINEAR B IDEOGRAM B159 CLOTH;Lo;0;L;;;;;N;;;;;
+100A8;LINEAR B IDEOGRAM B160;Lo;0;L;;;;;N;;;;;
+100A9;LINEAR B IDEOGRAM B161;Lo;0;L;;;;;N;;;;;
+100AA;LINEAR B IDEOGRAM B162 GARMENT;Lo;0;L;;;;;N;;;;;
+100AB;LINEAR B IDEOGRAM B163 ARMOUR;Lo;0;L;;;;;N;;;;;
+100AC;LINEAR B IDEOGRAM B164;Lo;0;L;;;;;N;;;;;
+100AD;LINEAR B IDEOGRAM B165;Lo;0;L;;;;;N;;;;;
+100AE;LINEAR B IDEOGRAM B166;Lo;0;L;;;;;N;;;;;
+100AF;LINEAR B IDEOGRAM B167;Lo;0;L;;;;;N;;;;;
+100B0;LINEAR B IDEOGRAM B168;Lo;0;L;;;;;N;;;;;
+100B1;LINEAR B IDEOGRAM B169;Lo;0;L;;;;;N;;;;;
+100B2;LINEAR B IDEOGRAM B170;Lo;0;L;;;;;N;;;;;
+100B3;LINEAR B IDEOGRAM B171;Lo;0;L;;;;;N;;;;;
+100B4;LINEAR B IDEOGRAM B172;Lo;0;L;;;;;N;;;;;
+100B5;LINEAR B IDEOGRAM B173 MONTH;Lo;0;L;;;;;N;;;;;
+100B6;LINEAR B IDEOGRAM B174;Lo;0;L;;;;;N;;;;;
+100B7;LINEAR B IDEOGRAM B176 TREE;Lo;0;L;;;;;N;;;;;
+100B8;LINEAR B IDEOGRAM B177;Lo;0;L;;;;;N;;;;;
+100B9;LINEAR B IDEOGRAM B178;Lo;0;L;;;;;N;;;;;
+100BA;LINEAR B IDEOGRAM B179;Lo;0;L;;;;;N;;;;;
+100BB;LINEAR B IDEOGRAM B180;Lo;0;L;;;;;N;;;;;
+100BC;LINEAR B IDEOGRAM B181;Lo;0;L;;;;;N;;;;;
+100BD;LINEAR B IDEOGRAM B182;Lo;0;L;;;;;N;;;;;
+100BE;LINEAR B IDEOGRAM B183;Lo;0;L;;;;;N;;;;;
+100BF;LINEAR B IDEOGRAM B184;Lo;0;L;;;;;N;;;;;
+100C0;LINEAR B IDEOGRAM B185;Lo;0;L;;;;;N;;;;;
+100C1;LINEAR B IDEOGRAM B189;Lo;0;L;;;;;N;;;;;
+100C2;LINEAR B IDEOGRAM B190;Lo;0;L;;;;;N;;;;;
+100C3;LINEAR B IDEOGRAM B191 HELMET;Lo;0;L;;;;;N;;;;;
+100C4;LINEAR B IDEOGRAM B220 FOOTSTOOL;Lo;0;L;;;;;N;;;;;
+100C5;LINEAR B IDEOGRAM B225 BATHTUB;Lo;0;L;;;;;N;;;;;
+100C6;LINEAR B IDEOGRAM B230 SPEAR;Lo;0;L;;;;;N;;;;;
+100C7;LINEAR B IDEOGRAM B231 ARROW;Lo;0;L;;;;;N;;;;;
+100C8;LINEAR B IDEOGRAM B232;Lo;0;L;;;;;N;;;;;
+100C9;LINEAR B IDEOGRAM B233 SWORD;Lo;0;L;;;;;N;;pug;;;
+100CA;LINEAR B IDEOGRAM B234;Lo;0;L;;;;;N;;;;;
+100CB;LINEAR B IDEOGRAM B236;Lo;0;L;;;;;N;;gup;;;
+100CC;LINEAR B IDEOGRAM B240 WHEELED CHARIOT;Lo;0;L;;;;;N;;;;;
+100CD;LINEAR B IDEOGRAM B241 CHARIOT;Lo;0;L;;;;;N;;;;;
+100CE;LINEAR B IDEOGRAM B242 CHARIOT FRAME;Lo;0;L;;;;;N;;;;;
+100CF;LINEAR B IDEOGRAM B243 WHEEL;Lo;0;L;;;;;N;;;;;
+100D0;LINEAR B IDEOGRAM B245;Lo;0;L;;;;;N;;;;;
+100D1;LINEAR B IDEOGRAM B246;Lo;0;L;;;;;N;;;;;
+100D2;LINEAR B MONOGRAM B247 DIPTE;Lo;0;L;;;;;N;;;;;
+100D3;LINEAR B IDEOGRAM B248;Lo;0;L;;;;;N;;;;;
+100D4;LINEAR B IDEOGRAM B249;Lo;0;L;;;;;N;;;;;
+100D5;LINEAR B IDEOGRAM B251;Lo;0;L;;;;;N;;;;;
+100D6;LINEAR B IDEOGRAM B252;Lo;0;L;;;;;N;;;;;
+100D7;LINEAR B IDEOGRAM B253;Lo;0;L;;;;;N;;;;;
+100D8;LINEAR B IDEOGRAM B254 DART;Lo;0;L;;;;;N;;;;;
+100D9;LINEAR B IDEOGRAM B255;Lo;0;L;;;;;N;;;;;
+100DA;LINEAR B IDEOGRAM B256;Lo;0;L;;;;;N;;;;;
+100DB;LINEAR B IDEOGRAM B257;Lo;0;L;;;;;N;;;;;
+100DC;LINEAR B IDEOGRAM B258;Lo;0;L;;;;;N;;;;;
+100DD;LINEAR B IDEOGRAM B259;Lo;0;L;;;;;N;;;;;
+100DE;LINEAR B IDEOGRAM VESSEL B155;Lo;0;L;;;;;N;;;;;
+100DF;LINEAR B IDEOGRAM VESSEL B200;Lo;0;L;;;;;N;;;;;
+100E0;LINEAR B IDEOGRAM VESSEL B201;Lo;0;L;;;;;N;;;;;
+100E1;LINEAR B IDEOGRAM VESSEL B202;Lo;0;L;;;;;N;;;;;
+100E2;LINEAR B IDEOGRAM VESSEL B203;Lo;0;L;;;;;N;;;;;
+100E3;LINEAR B IDEOGRAM VESSEL B204;Lo;0;L;;;;;N;;;;;
+100E4;LINEAR B IDEOGRAM VESSEL B205;Lo;0;L;;;;;N;;;;;
+100E5;LINEAR B IDEOGRAM VESSEL B206;Lo;0;L;;;;;N;;;;;
+100E6;LINEAR B IDEOGRAM VESSEL B207;Lo;0;L;;;;;N;;;;;
+100E7;LINEAR B IDEOGRAM VESSEL B208;Lo;0;L;;;;;N;;;;;
+100E8;LINEAR B IDEOGRAM VESSEL B209;Lo;0;L;;;;;N;;;;;
+100E9;LINEAR B IDEOGRAM VESSEL B210;Lo;0;L;;;;;N;;;;;
+100EA;LINEAR B IDEOGRAM VESSEL B211;Lo;0;L;;;;;N;;;;;
+100EB;LINEAR B IDEOGRAM VESSEL B212;Lo;0;L;;;;;N;;;;;
+100EC;LINEAR B IDEOGRAM VESSEL B213;Lo;0;L;;;;;N;;;;;
+100ED;LINEAR B IDEOGRAM VESSEL B214;Lo;0;L;;;;;N;;;;;
+100EE;LINEAR B IDEOGRAM VESSEL B215;Lo;0;L;;;;;N;;;;;
+100EF;LINEAR B IDEOGRAM VESSEL B216;Lo;0;L;;;;;N;;;;;
+100F0;LINEAR B IDEOGRAM VESSEL B217;Lo;0;L;;;;;N;;;;;
+100F1;LINEAR B IDEOGRAM VESSEL B218;Lo;0;L;;;;;N;;;;;
+100F2;LINEAR B IDEOGRAM VESSEL B219;Lo;0;L;;;;;N;;;;;
+100F3;LINEAR B IDEOGRAM VESSEL B221;Lo;0;L;;;;;N;;;;;
+100F4;LINEAR B IDEOGRAM VESSEL B222;Lo;0;L;;;;;N;;;;;
+100F5;LINEAR B IDEOGRAM VESSEL B226;Lo;0;L;;;;;N;;;;;
+100F6;LINEAR B IDEOGRAM VESSEL B227;Lo;0;L;;;;;N;;;;;
+100F7;LINEAR B IDEOGRAM VESSEL B228;Lo;0;L;;;;;N;;;;;
+100F8;LINEAR B IDEOGRAM VESSEL B229;Lo;0;L;;;;;N;;;;;
+100F9;LINEAR B IDEOGRAM VESSEL B250;Lo;0;L;;;;;N;;;;;
+100FA;LINEAR B IDEOGRAM VESSEL B305;Lo;0;L;;;;;N;;;;;
+10100;AEGEAN WORD SEPARATOR LINE;Po;0;L;;;;;N;;;;;
+10101;AEGEAN WORD SEPARATOR DOT;Po;0;ON;;;;;N;;;;;
+10102;AEGEAN CHECK MARK;So;0;L;;;;;N;;;;;
+10107;AEGEAN NUMBER ONE;No;0;L;;;;1;N;;;;;
+10108;AEGEAN NUMBER TWO;No;0;L;;;;2;N;;;;;
+10109;AEGEAN NUMBER THREE;No;0;L;;;;3;N;;;;;
+1010A;AEGEAN NUMBER FOUR;No;0;L;;;;4;N;;;;;
+1010B;AEGEAN NUMBER FIVE;No;0;L;;;;5;N;;;;;
+1010C;AEGEAN NUMBER SIX;No;0;L;;;;6;N;;;;;
+1010D;AEGEAN NUMBER SEVEN;No;0;L;;;;7;N;;;;;
+1010E;AEGEAN NUMBER EIGHT;No;0;L;;;;8;N;;;;;
+1010F;AEGEAN NUMBER NINE;No;0;L;;;;9;N;;;;;
+10110;AEGEAN NUMBER TEN;No;0;L;;;;10;N;;;;;
+10111;AEGEAN NUMBER TWENTY;No;0;L;;;;20;N;;;;;
+10112;AEGEAN NUMBER THIRTY;No;0;L;;;;30;N;;;;;
+10113;AEGEAN NUMBER FORTY;No;0;L;;;;40;N;;;;;
+10114;AEGEAN NUMBER FIFTY;No;0;L;;;;50;N;;;;;
+10115;AEGEAN NUMBER SIXTY;No;0;L;;;;60;N;;;;;
+10116;AEGEAN NUMBER SEVENTY;No;0;L;;;;70;N;;;;;
+10117;AEGEAN NUMBER EIGHTY;No;0;L;;;;80;N;;;;;
+10118;AEGEAN NUMBER NINETY;No;0;L;;;;90;N;;;;;
+10119;AEGEAN NUMBER ONE HUNDRED;No;0;L;;;;100;N;;;;;
+1011A;AEGEAN NUMBER TWO HUNDRED;No;0;L;;;;200;N;;;;;
+1011B;AEGEAN NUMBER THREE HUNDRED;No;0;L;;;;300;N;;;;;
+1011C;AEGEAN NUMBER FOUR HUNDRED;No;0;L;;;;400;N;;;;;
+1011D;AEGEAN NUMBER FIVE HUNDRED;No;0;L;;;;500;N;;;;;
+1011E;AEGEAN NUMBER SIX HUNDRED;No;0;L;;;;600;N;;;;;
+1011F;AEGEAN NUMBER SEVEN HUNDRED;No;0;L;;;;700;N;;;;;
+10120;AEGEAN NUMBER EIGHT HUNDRED;No;0;L;;;;800;N;;;;;
+10121;AEGEAN NUMBER NINE HUNDRED;No;0;L;;;;900;N;;;;;
+10122;AEGEAN NUMBER ONE THOUSAND;No;0;L;;;;1000;N;;;;;
+10123;AEGEAN NUMBER TWO THOUSAND;No;0;L;;;;2000;N;;;;;
+10124;AEGEAN NUMBER THREE THOUSAND;No;0;L;;;;3000;N;;;;;
+10125;AEGEAN NUMBER FOUR THOUSAND;No;0;L;;;;4000;N;;;;;
+10126;AEGEAN NUMBER FIVE THOUSAND;No;0;L;;;;5000;N;;;;;
+10127;AEGEAN NUMBER SIX THOUSAND;No;0;L;;;;6000;N;;;;;
+10128;AEGEAN NUMBER SEVEN THOUSAND;No;0;L;;;;7000;N;;;;;
+10129;AEGEAN NUMBER EIGHT THOUSAND;No;0;L;;;;8000;N;;;;;
+1012A;AEGEAN NUMBER NINE THOUSAND;No;0;L;;;;9000;N;;;;;
+1012B;AEGEAN NUMBER TEN THOUSAND;No;0;L;;;;10000;N;;;;;
+1012C;AEGEAN NUMBER TWENTY THOUSAND;No;0;L;;;;20000;N;;;;;
+1012D;AEGEAN NUMBER THIRTY THOUSAND;No;0;L;;;;30000;N;;;;;
+1012E;AEGEAN NUMBER FORTY THOUSAND;No;0;L;;;;40000;N;;;;;
+1012F;AEGEAN NUMBER FIFTY THOUSAND;No;0;L;;;;50000;N;;;;;
+10130;AEGEAN NUMBER SIXTY THOUSAND;No;0;L;;;;60000;N;;;;;
+10131;AEGEAN NUMBER SEVENTY THOUSAND;No;0;L;;;;70000;N;;;;;
+10132;AEGEAN NUMBER EIGHTY THOUSAND;No;0;L;;;;80000;N;;;;;
+10133;AEGEAN NUMBER NINETY THOUSAND;No;0;L;;;;90000;N;;;;;
+10137;AEGEAN WEIGHT BASE UNIT;So;0;L;;;;;N;;;;;
+10138;AEGEAN WEIGHT FIRST SUBUNIT;So;0;L;;;;;N;;;;;
+10139;AEGEAN WEIGHT SECOND SUBUNIT;So;0;L;;;;;N;;;;;
+1013A;AEGEAN WEIGHT THIRD SUBUNIT;So;0;L;;;;;N;;;;;
+1013B;AEGEAN WEIGHT FOURTH SUBUNIT;So;0;L;;;;;N;;;;;
+1013C;AEGEAN DRY MEASURE FIRST SUBUNIT;So;0;L;;;;;N;;;;;
+1013D;AEGEAN LIQUID MEASURE FIRST SUBUNIT;So;0;L;;;;;N;;;;;
+1013E;AEGEAN MEASURE SECOND SUBUNIT;So;0;L;;;;;N;;;;;
+1013F;AEGEAN MEASURE THIRD SUBUNIT;So;0;L;;;;;N;;;;;
+10300;OLD ITALIC LETTER A;Lo;0;L;;;;;N;;;;;
+10301;OLD ITALIC LETTER BE;Lo;0;L;;;;;N;;;;;
+10302;OLD ITALIC LETTER KE;Lo;0;L;;;;;N;;;;;
+10303;OLD ITALIC LETTER DE;Lo;0;L;;;;;N;;;;;
+10304;OLD ITALIC LETTER E;Lo;0;L;;;;;N;;;;;
+10305;OLD ITALIC LETTER VE;Lo;0;L;;;;;N;;;;;
+10306;OLD ITALIC LETTER ZE;Lo;0;L;;;;;N;;;;;
+10307;OLD ITALIC LETTER HE;Lo;0;L;;;;;N;;;;;
+10308;OLD ITALIC LETTER THE;Lo;0;L;;;;;N;;;;;
+10309;OLD ITALIC LETTER I;Lo;0;L;;;;;N;;;;;
+1030A;OLD ITALIC LETTER KA;Lo;0;L;;;;;N;;;;;
+1030B;OLD ITALIC LETTER EL;Lo;0;L;;;;;N;;;;;
+1030C;OLD ITALIC LETTER EM;Lo;0;L;;;;;N;;;;;
+1030D;OLD ITALIC LETTER EN;Lo;0;L;;;;;N;;;;;
+1030E;OLD ITALIC LETTER ESH;Lo;0;L;;;;;N;;;;;
+1030F;OLD ITALIC LETTER O;Lo;0;L;;;;;N;;Faliscan;;;
+10310;OLD ITALIC LETTER PE;Lo;0;L;;;;;N;;;;;
+10311;OLD ITALIC LETTER SHE;Lo;0;L;;;;;N;;;;;
+10312;OLD ITALIC LETTER KU;Lo;0;L;;;;;N;;;;;
+10313;OLD ITALIC LETTER ER;Lo;0;L;;;;;N;;;;;
+10314;OLD ITALIC LETTER ES;Lo;0;L;;;;;N;;;;;
+10315;OLD ITALIC LETTER TE;Lo;0;L;;;;;N;;;;;
+10316;OLD ITALIC LETTER U;Lo;0;L;;;;;N;;;;;
+10317;OLD ITALIC LETTER EKS;Lo;0;L;;;;;N;;Faliscan;;;
+10318;OLD ITALIC LETTER PHE;Lo;0;L;;;;;N;;;;;
+10319;OLD ITALIC LETTER KHE;Lo;0;L;;;;;N;;;;;
+1031A;OLD ITALIC LETTER EF;Lo;0;L;;;;;N;;;;;
+1031B;OLD ITALIC LETTER ERS;Lo;0;L;;;;;N;;Umbrian;;;
+1031C;OLD ITALIC LETTER CHE;Lo;0;L;;;;;N;;Umbrian;;;
+1031D;OLD ITALIC LETTER II;Lo;0;L;;;;;N;;Oscan;;;
+1031E;OLD ITALIC LETTER UU;Lo;0;L;;;;;N;;Oscan;;;
+10320;OLD ITALIC NUMERAL ONE;No;0;L;;;;1;N;;;;;
+10321;OLD ITALIC NUMERAL FIVE;No;0;L;;;;5;N;;;;;
+10322;OLD ITALIC NUMERAL TEN;No;0;L;;;;10;N;;;;;
+10323;OLD ITALIC NUMERAL FIFTY;No;0;L;;;;50;N;;;;;
+10330;GOTHIC LETTER AHSA;Lo;0;L;;;;;N;;;;;
+10331;GOTHIC LETTER BAIRKAN;Lo;0;L;;;;;N;;;;;
+10332;GOTHIC LETTER GIBA;Lo;0;L;;;;;N;;;;;
+10333;GOTHIC LETTER DAGS;Lo;0;L;;;;;N;;;;;
+10334;GOTHIC LETTER AIHVUS;Lo;0;L;;;;;N;;;;;
+10335;GOTHIC LETTER QAIRTHRA;Lo;0;L;;;;;N;;;;;
+10336;GOTHIC LETTER IUJA;Lo;0;L;;;;;N;;;;;
+10337;GOTHIC LETTER HAGL;Lo;0;L;;;;;N;;;;;
+10338;GOTHIC LETTER THIUTH;Lo;0;L;;;;;N;;;;;
+10339;GOTHIC LETTER EIS;Lo;0;L;;;;;N;;;;;
+1033A;GOTHIC LETTER KUSMA;Lo;0;L;;;;;N;;;;;
+1033B;GOTHIC LETTER LAGUS;Lo;0;L;;;;;N;;;;;
+1033C;GOTHIC LETTER MANNA;Lo;0;L;;;;;N;;;;;
+1033D;GOTHIC LETTER NAUTHS;Lo;0;L;;;;;N;;;;;
+1033E;GOTHIC LETTER JER;Lo;0;L;;;;;N;;;;;
+1033F;GOTHIC LETTER URUS;Lo;0;L;;;;;N;;;;;
+10340;GOTHIC LETTER PAIRTHRA;Lo;0;L;;;;;N;;;;;
+10341;GOTHIC LETTER NINETY;Lo;0;L;;;;;N;;;;;
+10342;GOTHIC LETTER RAIDA;Lo;0;L;;;;;N;;;;;
+10343;GOTHIC LETTER SAUIL;Lo;0;L;;;;;N;;;;;
+10344;GOTHIC LETTER TEIWS;Lo;0;L;;;;;N;;;;;
+10345;GOTHIC LETTER WINJA;Lo;0;L;;;;;N;;;;;
+10346;GOTHIC LETTER FAIHU;Lo;0;L;;;;;N;;;;;
+10347;GOTHIC LETTER IGGWS;Lo;0;L;;;;;N;;;;;
+10348;GOTHIC LETTER HWAIR;Lo;0;L;;;;;N;;;;;
+10349;GOTHIC LETTER OTHAL;Lo;0;L;;;;;N;;;;;
+1034A;GOTHIC LETTER NINE HUNDRED;Nl;0;L;;;;;N;;;;;
+10380;UGARITIC LETTER ALPA;Lo;0;L;;;;;N;;;;;
+10381;UGARITIC LETTER BETA;Lo;0;L;;;;;N;;;;;
+10382;UGARITIC LETTER GAMLA;Lo;0;L;;;;;N;;;;;
+10383;UGARITIC LETTER KHA;Lo;0;L;;;;;N;;;;;
+10384;UGARITIC LETTER DELTA;Lo;0;L;;;;;N;;;;;
+10385;UGARITIC LETTER HO;Lo;0;L;;;;;N;;;;;
+10386;UGARITIC LETTER WO;Lo;0;L;;;;;N;;;;;
+10387;UGARITIC LETTER ZETA;Lo;0;L;;;;;N;;;;;
+10388;UGARITIC LETTER HOTA;Lo;0;L;;;;;N;;;;;
+10389;UGARITIC LETTER TET;Lo;0;L;;;;;N;;;;;
+1038A;UGARITIC LETTER YOD;Lo;0;L;;;;;N;;;;;
+1038B;UGARITIC LETTER KAF;Lo;0;L;;;;;N;;;;;
+1038C;UGARITIC LETTER SHIN;Lo;0;L;;;;;N;;;;;
+1038D;UGARITIC LETTER LAMDA;Lo;0;L;;;;;N;;;;;
+1038E;UGARITIC LETTER MEM;Lo;0;L;;;;;N;;;;;
+1038F;UGARITIC LETTER DHAL;Lo;0;L;;;;;N;;;;;
+10390;UGARITIC LETTER NUN;Lo;0;L;;;;;N;;;;;
+10391;UGARITIC LETTER ZU;Lo;0;L;;;;;N;;;;;
+10392;UGARITIC LETTER SAMKA;Lo;0;L;;;;;N;;;;;
+10393;UGARITIC LETTER AIN;Lo;0;L;;;;;N;;;;;
+10394;UGARITIC LETTER PU;Lo;0;L;;;;;N;;;;;
+10395;UGARITIC LETTER SADE;Lo;0;L;;;;;N;;;;;
+10396;UGARITIC LETTER QOPA;Lo;0;L;;;;;N;;;;;
+10397;UGARITIC LETTER RASHA;Lo;0;L;;;;;N;;;;;
+10398;UGARITIC LETTER THANNA;Lo;0;L;;;;;N;;;;;
+10399;UGARITIC LETTER GHAIN;Lo;0;L;;;;;N;;;;;
+1039A;UGARITIC LETTER TO;Lo;0;L;;;;;N;;;;;
+1039B;UGARITIC LETTER I;Lo;0;L;;;;;N;;;;;
+1039C;UGARITIC LETTER U;Lo;0;L;;;;;N;;;;;
+1039D;UGARITIC LETTER SSU;Lo;0;L;;;;;N;;;;;
+1039F;UGARITIC WORD DIVIDER;Po;0;L;;;;;N;;;;;
+10400;DESERET CAPITAL LETTER LONG I;Lu;0;L;;;;;N;;;;10428;
+10401;DESERET CAPITAL LETTER LONG E;Lu;0;L;;;;;N;;;;10429;
+10402;DESERET CAPITAL LETTER LONG A;Lu;0;L;;;;;N;;;;1042A;
+10403;DESERET CAPITAL LETTER LONG AH;Lu;0;L;;;;;N;;;;1042B;
+10404;DESERET CAPITAL LETTER LONG O;Lu;0;L;;;;;N;;;;1042C;
+10405;DESERET CAPITAL LETTER LONG OO;Lu;0;L;;;;;N;;;;1042D;
+10406;DESERET CAPITAL LETTER SHORT I;Lu;0;L;;;;;N;;;;1042E;
+10407;DESERET CAPITAL LETTER SHORT E;Lu;0;L;;;;;N;;;;1042F;
+10408;DESERET CAPITAL LETTER SHORT A;Lu;0;L;;;;;N;;;;10430;
+10409;DESERET CAPITAL LETTER SHORT AH;Lu;0;L;;;;;N;;;;10431;
+1040A;DESERET CAPITAL LETTER SHORT O;Lu;0;L;;;;;N;;;;10432;
+1040B;DESERET CAPITAL LETTER SHORT OO;Lu;0;L;;;;;N;;;;10433;
+1040C;DESERET CAPITAL LETTER AY;Lu;0;L;;;;;N;;;;10434;
+1040D;DESERET CAPITAL LETTER OW;Lu;0;L;;;;;N;;;;10435;
+1040E;DESERET CAPITAL LETTER WU;Lu;0;L;;;;;N;;;;10436;
+1040F;DESERET CAPITAL LETTER YEE;Lu;0;L;;;;;N;;;;10437;
+10410;DESERET CAPITAL LETTER H;Lu;0;L;;;;;N;;;;10438;
+10411;DESERET CAPITAL LETTER PEE;Lu;0;L;;;;;N;;;;10439;
+10412;DESERET CAPITAL LETTER BEE;Lu;0;L;;;;;N;;;;1043A;
+10413;DESERET CAPITAL LETTER TEE;Lu;0;L;;;;;N;;;;1043B;
+10414;DESERET CAPITAL LETTER DEE;Lu;0;L;;;;;N;;;;1043C;
+10415;DESERET CAPITAL LETTER CHEE;Lu;0;L;;;;;N;;;;1043D;
+10416;DESERET CAPITAL LETTER JEE;Lu;0;L;;;;;N;;;;1043E;
+10417;DESERET CAPITAL LETTER KAY;Lu;0;L;;;;;N;;;;1043F;
+10418;DESERET CAPITAL LETTER GAY;Lu;0;L;;;;;N;;;;10440;
+10419;DESERET CAPITAL LETTER EF;Lu;0;L;;;;;N;;;;10441;
+1041A;DESERET CAPITAL LETTER VEE;Lu;0;L;;;;;N;;;;10442;
+1041B;DESERET CAPITAL LETTER ETH;Lu;0;L;;;;;N;;;;10443;
+1041C;DESERET CAPITAL LETTER THEE;Lu;0;L;;;;;N;;;;10444;
+1041D;DESERET CAPITAL LETTER ES;Lu;0;L;;;;;N;;;;10445;
+1041E;DESERET CAPITAL LETTER ZEE;Lu;0;L;;;;;N;;;;10446;
+1041F;DESERET CAPITAL LETTER ESH;Lu;0;L;;;;;N;;;;10447;
+10420;DESERET CAPITAL LETTER ZHEE;Lu;0;L;;;;;N;;;;10448;
+10421;DESERET CAPITAL LETTER ER;Lu;0;L;;;;;N;;;;10449;
+10422;DESERET CAPITAL LETTER EL;Lu;0;L;;;;;N;;;;1044A;
+10423;DESERET CAPITAL LETTER EM;Lu;0;L;;;;;N;;;;1044B;
+10424;DESERET CAPITAL LETTER EN;Lu;0;L;;;;;N;;;;1044C;
+10425;DESERET CAPITAL LETTER ENG;Lu;0;L;;;;;N;;;;1044D;
+10426;DESERET CAPITAL LETTER OI;Lu;0;L;;;;;N;;;;1044E;
+10427;DESERET CAPITAL LETTER EW;Lu;0;L;;;;;N;;;;1044F;
+10428;DESERET SMALL LETTER LONG I;Ll;0;L;;;;;N;;;10400;;10400
+10429;DESERET SMALL LETTER LONG E;Ll;0;L;;;;;N;;;10401;;10401
+1042A;DESERET SMALL LETTER LONG A;Ll;0;L;;;;;N;;;10402;;10402
+1042B;DESERET SMALL LETTER LONG AH;Ll;0;L;;;;;N;;;10403;;10403
+1042C;DESERET SMALL LETTER LONG O;Ll;0;L;;;;;N;;;10404;;10404
+1042D;DESERET SMALL LETTER LONG OO;Ll;0;L;;;;;N;;;10405;;10405
+1042E;DESERET SMALL LETTER SHORT I;Ll;0;L;;;;;N;;;10406;;10406
+1042F;DESERET SMALL LETTER SHORT E;Ll;0;L;;;;;N;;;10407;;10407
+10430;DESERET SMALL LETTER SHORT A;Ll;0;L;;;;;N;;;10408;;10408
+10431;DESERET SMALL LETTER SHORT AH;Ll;0;L;;;;;N;;;10409;;10409
+10432;DESERET SMALL LETTER SHORT O;Ll;0;L;;;;;N;;;1040A;;1040A
+10433;DESERET SMALL LETTER SHORT OO;Ll;0;L;;;;;N;;;1040B;;1040B
+10434;DESERET SMALL LETTER AY;Ll;0;L;;;;;N;;;1040C;;1040C
+10435;DESERET SMALL LETTER OW;Ll;0;L;;;;;N;;;1040D;;1040D
+10436;DESERET SMALL LETTER WU;Ll;0;L;;;;;N;;;1040E;;1040E
+10437;DESERET SMALL LETTER YEE;Ll;0;L;;;;;N;;;1040F;;1040F
+10438;DESERET SMALL LETTER H;Ll;0;L;;;;;N;;;10410;;10410
+10439;DESERET SMALL LETTER PEE;Ll;0;L;;;;;N;;;10411;;10411
+1043A;DESERET SMALL LETTER BEE;Ll;0;L;;;;;N;;;10412;;10412
+1043B;DESERET SMALL LETTER TEE;Ll;0;L;;;;;N;;;10413;;10413
+1043C;DESERET SMALL LETTER DEE;Ll;0;L;;;;;N;;;10414;;10414
+1043D;DESERET SMALL LETTER CHEE;Ll;0;L;;;;;N;;;10415;;10415
+1043E;DESERET SMALL LETTER JEE;Ll;0;L;;;;;N;;;10416;;10416
+1043F;DESERET SMALL LETTER KAY;Ll;0;L;;;;;N;;;10417;;10417
+10440;DESERET SMALL LETTER GAY;Ll;0;L;;;;;N;;;10418;;10418
+10441;DESERET SMALL LETTER EF;Ll;0;L;;;;;N;;;10419;;10419
+10442;DESERET SMALL LETTER VEE;Ll;0;L;;;;;N;;;1041A;;1041A
+10443;DESERET SMALL LETTER ETH;Ll;0;L;;;;;N;;;1041B;;1041B
+10444;DESERET SMALL LETTER THEE;Ll;0;L;;;;;N;;;1041C;;1041C
+10445;DESERET SMALL LETTER ES;Ll;0;L;;;;;N;;;1041D;;1041D
+10446;DESERET SMALL LETTER ZEE;Ll;0;L;;;;;N;;;1041E;;1041E
+10447;DESERET SMALL LETTER ESH;Ll;0;L;;;;;N;;;1041F;;1041F
+10448;DESERET SMALL LETTER ZHEE;Ll;0;L;;;;;N;;;10420;;10420
+10449;DESERET SMALL LETTER ER;Ll;0;L;;;;;N;;;10421;;10421
+1044A;DESERET SMALL LETTER EL;Ll;0;L;;;;;N;;;10422;;10422
+1044B;DESERET SMALL LETTER EM;Ll;0;L;;;;;N;;;10423;;10423
+1044C;DESERET SMALL LETTER EN;Ll;0;L;;;;;N;;;10424;;10424
+1044D;DESERET SMALL LETTER ENG;Ll;0;L;;;;;N;;;10425;;10425
+1044E;DESERET SMALL LETTER OI;Ll;0;L;;;;;N;;;10426;;10426
+1044F;DESERET SMALL LETTER EW;Ll;0;L;;;;;N;;;10427;;10427
+10450;SHAVIAN LETTER PEEP;Lo;0;L;;;;;N;;;;;
+10451;SHAVIAN LETTER TOT;Lo;0;L;;;;;N;;;;;
+10452;SHAVIAN LETTER KICK;Lo;0;L;;;;;N;;;;;
+10453;SHAVIAN LETTER FEE;Lo;0;L;;;;;N;;;;;
+10454;SHAVIAN LETTER THIGH;Lo;0;L;;;;;N;;;;;
+10455;SHAVIAN LETTER SO;Lo;0;L;;;;;N;;;;;
+10456;SHAVIAN LETTER SURE;Lo;0;L;;;;;N;;;;;
+10457;SHAVIAN LETTER CHURCH;Lo;0;L;;;;;N;;;;;
+10458;SHAVIAN LETTER YEA;Lo;0;L;;;;;N;;;;;
+10459;SHAVIAN LETTER HUNG;Lo;0;L;;;;;N;;;;;
+1045A;SHAVIAN LETTER BIB;Lo;0;L;;;;;N;;;;;
+1045B;SHAVIAN LETTER DEAD;Lo;0;L;;;;;N;;;;;
+1045C;SHAVIAN LETTER GAG;Lo;0;L;;;;;N;;;;;
+1045D;SHAVIAN LETTER VOW;Lo;0;L;;;;;N;;;;;
+1045E;SHAVIAN LETTER THEY;Lo;0;L;;;;;N;;;;;
+1045F;SHAVIAN LETTER ZOO;Lo;0;L;;;;;N;;;;;
+10460;SHAVIAN LETTER MEASURE;Lo;0;L;;;;;N;;;;;
+10461;SHAVIAN LETTER JUDGE;Lo;0;L;;;;;N;;;;;
+10462;SHAVIAN LETTER WOE;Lo;0;L;;;;;N;;;;;
+10463;SHAVIAN LETTER HA-HA;Lo;0;L;;;;;N;;;;;
+10464;SHAVIAN LETTER LOLL;Lo;0;L;;;;;N;;;;;
+10465;SHAVIAN LETTER MIME;Lo;0;L;;;;;N;;;;;
+10466;SHAVIAN LETTER IF;Lo;0;L;;;;;N;;;;;
+10467;SHAVIAN LETTER EGG;Lo;0;L;;;;;N;;;;;
+10468;SHAVIAN LETTER ASH;Lo;0;L;;;;;N;;;;;
+10469;SHAVIAN LETTER ADO;Lo;0;L;;;;;N;;;;;
+1046A;SHAVIAN LETTER ON;Lo;0;L;;;;;N;;;;;
+1046B;SHAVIAN LETTER WOOL;Lo;0;L;;;;;N;;;;;
+1046C;SHAVIAN LETTER OUT;Lo;0;L;;;;;N;;;;;
+1046D;SHAVIAN LETTER AH;Lo;0;L;;;;;N;;;;;
+1046E;SHAVIAN LETTER ROAR;Lo;0;L;;;;;N;;;;;
+1046F;SHAVIAN LETTER NUN;Lo;0;L;;;;;N;;;;;
+10470;SHAVIAN LETTER EAT;Lo;0;L;;;;;N;;;;;
+10471;SHAVIAN LETTER AGE;Lo;0;L;;;;;N;;;;;
+10472;SHAVIAN LETTER ICE;Lo;0;L;;;;;N;;;;;
+10473;SHAVIAN LETTER UP;Lo;0;L;;;;;N;;;;;
+10474;SHAVIAN LETTER OAK;Lo;0;L;;;;;N;;;;;
+10475;SHAVIAN LETTER OOZE;Lo;0;L;;;;;N;;;;;
+10476;SHAVIAN LETTER OIL;Lo;0;L;;;;;N;;;;;
+10477;SHAVIAN LETTER AWE;Lo;0;L;;;;;N;;;;;
+10478;SHAVIAN LETTER ARE;Lo;0;L;;;;;N;;;;;
+10479;SHAVIAN LETTER OR;Lo;0;L;;;;;N;;;;;
+1047A;SHAVIAN LETTER AIR;Lo;0;L;;;;;N;;;;;
+1047B;SHAVIAN LETTER ERR;Lo;0;L;;;;;N;;;;;
+1047C;SHAVIAN LETTER ARRAY;Lo;0;L;;;;;N;;;;;
+1047D;SHAVIAN LETTER EAR;Lo;0;L;;;;;N;;;;;
+1047E;SHAVIAN LETTER IAN;Lo;0;L;;;;;N;;;;;
+1047F;SHAVIAN LETTER YEW;Lo;0;L;;;;;N;;;;;
+10480;OSMANYA LETTER ALEF;Lo;0;L;;;;;N;;;;;
+10481;OSMANYA LETTER BA;Lo;0;L;;;;;N;;;;;
+10482;OSMANYA LETTER TA;Lo;0;L;;;;;N;;;;;
+10483;OSMANYA LETTER JA;Lo;0;L;;;;;N;;;;;
+10484;OSMANYA LETTER XA;Lo;0;L;;;;;N;;;;;
+10485;OSMANYA LETTER KHA;Lo;0;L;;;;;N;;;;;
+10486;OSMANYA LETTER DEEL;Lo;0;L;;;;;N;;;;;
+10487;OSMANYA LETTER RA;Lo;0;L;;;;;N;;;;;
+10488;OSMANYA LETTER SA;Lo;0;L;;;;;N;;;;;
+10489;OSMANYA LETTER SHIIN;Lo;0;L;;;;;N;;;;;
+1048A;OSMANYA LETTER DHA;Lo;0;L;;;;;N;;;;;
+1048B;OSMANYA LETTER CAYN;Lo;0;L;;;;;N;;;;;
+1048C;OSMANYA LETTER GA;Lo;0;L;;;;;N;;;;;
+1048D;OSMANYA LETTER FA;Lo;0;L;;;;;N;;;;;
+1048E;OSMANYA LETTER QAAF;Lo;0;L;;;;;N;;;;;
+1048F;OSMANYA LETTER KAAF;Lo;0;L;;;;;N;;;;;
+10490;OSMANYA LETTER LAAN;Lo;0;L;;;;;N;;;;;
+10491;OSMANYA LETTER MIIN;Lo;0;L;;;;;N;;;;;
+10492;OSMANYA LETTER NUUN;Lo;0;L;;;;;N;;;;;
+10493;OSMANYA LETTER WAW;Lo;0;L;;;;;N;;;;;
+10494;OSMANYA LETTER HA;Lo;0;L;;;;;N;;;;;
+10495;OSMANYA LETTER YA;Lo;0;L;;;;;N;;;;;
+10496;OSMANYA LETTER A;Lo;0;L;;;;;N;;;;;
+10497;OSMANYA LETTER E;Lo;0;L;;;;;N;;;;;
+10498;OSMANYA LETTER I;Lo;0;L;;;;;N;;;;;
+10499;OSMANYA LETTER O;Lo;0;L;;;;;N;;;;;
+1049A;OSMANYA LETTER U;Lo;0;L;;;;;N;;;;;
+1049B;OSMANYA LETTER AA;Lo;0;L;;;;;N;;;;;
+1049C;OSMANYA LETTER EE;Lo;0;L;;;;;N;;;;;
+1049D;OSMANYA LETTER OO;Lo;0;L;;;;;N;;;;;
+104A0;OSMANYA DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;;
+104A1;OSMANYA DIGIT ONE;Nd;0;L;;1;1;1;N;;;;;
+104A2;OSMANYA DIGIT TWO;Nd;0;L;;2;2;2;N;;;;;
+104A3;OSMANYA DIGIT THREE;Nd;0;L;;3;3;3;N;;;;;
+104A4;OSMANYA DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;;
+104A5;OSMANYA DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;;
+104A6;OSMANYA DIGIT SIX;Nd;0;L;;6;6;6;N;;;;;
+104A7;OSMANYA DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;;
+104A8;OSMANYA DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;;
+104A9;OSMANYA DIGIT NINE;Nd;0;L;;9;9;9;N;;;;;
+10800;CYPRIOT SYLLABLE A;Lo;0;R;;;;;N;;;;;
+10801;CYPRIOT SYLLABLE E;Lo;0;R;;;;;N;;;;;
+10802;CYPRIOT SYLLABLE I;Lo;0;R;;;;;N;;;;;
+10803;CYPRIOT SYLLABLE O;Lo;0;R;;;;;N;;;;;
+10804;CYPRIOT SYLLABLE U;Lo;0;R;;;;;N;;;;;
+10805;CYPRIOT SYLLABLE JA;Lo;0;R;;;;;N;;;;;
+10808;CYPRIOT SYLLABLE JO;Lo;0;R;;;;;N;;;;;
+1080A;CYPRIOT SYLLABLE KA;Lo;0;R;;;;;N;;;;;
+1080B;CYPRIOT SYLLABLE KE;Lo;0;R;;;;;N;;;;;
+1080C;CYPRIOT SYLLABLE KI;Lo;0;R;;;;;N;;;;;
+1080D;CYPRIOT SYLLABLE KO;Lo;0;R;;;;;N;;;;;
+1080E;CYPRIOT SYLLABLE KU;Lo;0;R;;;;;N;;;;;
+1080F;CYPRIOT SYLLABLE LA;Lo;0;R;;;;;N;;;;;
+10810;CYPRIOT SYLLABLE LE;Lo;0;R;;;;;N;;;;;
+10811;CYPRIOT SYLLABLE LI;Lo;0;R;;;;;N;;;;;
+10812;CYPRIOT SYLLABLE LO;Lo;0;R;;;;;N;;;;;
+10813;CYPRIOT SYLLABLE LU;Lo;0;R;;;;;N;;;;;
+10814;CYPRIOT SYLLABLE MA;Lo;0;R;;;;;N;;;;;
+10815;CYPRIOT SYLLABLE ME;Lo;0;R;;;;;N;;;;;
+10816;CYPRIOT SYLLABLE MI;Lo;0;R;;;;;N;;;;;
+10817;CYPRIOT SYLLABLE MO;Lo;0;R;;;;;N;;;;;
+10818;CYPRIOT SYLLABLE MU;Lo;0;R;;;;;N;;;;;
+10819;CYPRIOT SYLLABLE NA;Lo;0;R;;;;;N;;;;;
+1081A;CYPRIOT SYLLABLE NE;Lo;0;R;;;;;N;;;;;
+1081B;CYPRIOT SYLLABLE NI;Lo;0;R;;;;;N;;;;;
+1081C;CYPRIOT SYLLABLE NO;Lo;0;R;;;;;N;;;;;
+1081D;CYPRIOT SYLLABLE NU;Lo;0;R;;;;;N;;;;;
+1081E;CYPRIOT SYLLABLE PA;Lo;0;R;;;;;N;;;;;
+1081F;CYPRIOT SYLLABLE PE;Lo;0;R;;;;;N;;;;;
+10820;CYPRIOT SYLLABLE PI;Lo;0;R;;;;;N;;;;;
+10821;CYPRIOT SYLLABLE PO;Lo;0;R;;;;;N;;;;;
+10822;CYPRIOT SYLLABLE PU;Lo;0;R;;;;;N;;;;;
+10823;CYPRIOT SYLLABLE RA;Lo;0;R;;;;;N;;;;;
+10824;CYPRIOT SYLLABLE RE;Lo;0;R;;;;;N;;;;;
+10825;CYPRIOT SYLLABLE RI;Lo;0;R;;;;;N;;;;;
+10826;CYPRIOT SYLLABLE RO;Lo;0;R;;;;;N;;;;;
+10827;CYPRIOT SYLLABLE RU;Lo;0;R;;;;;N;;;;;
+10828;CYPRIOT SYLLABLE SA;Lo;0;R;;;;;N;;;;;
+10829;CYPRIOT SYLLABLE SE;Lo;0;R;;;;;N;;;;;
+1082A;CYPRIOT SYLLABLE SI;Lo;0;R;;;;;N;;;;;
+1082B;CYPRIOT SYLLABLE SO;Lo;0;R;;;;;N;;;;;
+1082C;CYPRIOT SYLLABLE SU;Lo;0;R;;;;;N;;;;;
+1082D;CYPRIOT SYLLABLE TA;Lo;0;R;;;;;N;;;;;
+1082E;CYPRIOT SYLLABLE TE;Lo;0;R;;;;;N;;;;;
+1082F;CYPRIOT SYLLABLE TI;Lo;0;R;;;;;N;;;;;
+10830;CYPRIOT SYLLABLE TO;Lo;0;R;;;;;N;;;;;
+10831;CYPRIOT SYLLABLE TU;Lo;0;R;;;;;N;;;;;
+10832;CYPRIOT SYLLABLE WA;Lo;0;R;;;;;N;;;;;
+10833;CYPRIOT SYLLABLE WE;Lo;0;R;;;;;N;;;;;
+10834;CYPRIOT SYLLABLE WI;Lo;0;R;;;;;N;;;;;
+10835;CYPRIOT SYLLABLE WO;Lo;0;R;;;;;N;;;;;
+10837;CYPRIOT SYLLABLE XA;Lo;0;R;;;;;N;;;;;
+10838;CYPRIOT SYLLABLE XE;Lo;0;R;;;;;N;;;;;
+1083C;CYPRIOT SYLLABLE ZA;Lo;0;R;;;;;N;;;;;
+1083F;CYPRIOT SYLLABLE ZO;Lo;0;R;;;;;N;;;;;
+1D000;BYZANTINE MUSICAL SYMBOL PSILI;So;0;L;;;;;N;;;;;
+1D001;BYZANTINE MUSICAL SYMBOL DASEIA;So;0;L;;;;;N;;;;;
+1D002;BYZANTINE MUSICAL SYMBOL PERISPOMENI;So;0;L;;;;;N;;;;;
+1D003;BYZANTINE MUSICAL SYMBOL OXEIA EKFONITIKON;So;0;L;;;;;N;;;;;
+1D004;BYZANTINE MUSICAL SYMBOL OXEIA DIPLI;So;0;L;;;;;N;;;;;
+1D005;BYZANTINE MUSICAL SYMBOL VAREIA EKFONITIKON;So;0;L;;;;;N;;;;;
+1D006;BYZANTINE MUSICAL SYMBOL VAREIA DIPLI;So;0;L;;;;;N;;;;;
+1D007;BYZANTINE MUSICAL SYMBOL KATHISTI;So;0;L;;;;;N;;;;;
+1D008;BYZANTINE MUSICAL SYMBOL SYRMATIKI;So;0;L;;;;;N;;;;;
+1D009;BYZANTINE MUSICAL SYMBOL PARAKLITIKI;So;0;L;;;;;N;;;;;
+1D00A;BYZANTINE MUSICAL SYMBOL YPOKRISIS;So;0;L;;;;;N;;;;;
+1D00B;BYZANTINE MUSICAL SYMBOL YPOKRISIS DIPLI;So;0;L;;;;;N;;;;;
+1D00C;BYZANTINE MUSICAL SYMBOL KREMASTI;So;0;L;;;;;N;;;;;
+1D00D;BYZANTINE MUSICAL SYMBOL APESO EKFONITIKON;So;0;L;;;;;N;;;;;
+1D00E;BYZANTINE MUSICAL SYMBOL EXO EKFONITIKON;So;0;L;;;;;N;;;;;
+1D00F;BYZANTINE MUSICAL SYMBOL TELEIA;So;0;L;;;;;N;;;;;
+1D010;BYZANTINE MUSICAL SYMBOL KENTIMATA;So;0;L;;;;;N;;;;;
+1D011;BYZANTINE MUSICAL SYMBOL APOSTROFOS;So;0;L;;;;;N;;;;;
+1D012;BYZANTINE MUSICAL SYMBOL APOSTROFOS DIPLI;So;0;L;;;;;N;;;;;
+1D013;BYZANTINE MUSICAL SYMBOL SYNEVMA;So;0;L;;;;;N;;;;;
+1D014;BYZANTINE MUSICAL SYMBOL THITA;So;0;L;;;;;N;;;;;
+1D015;BYZANTINE MUSICAL SYMBOL OLIGON ARCHAION;So;0;L;;;;;N;;;;;
+1D016;BYZANTINE MUSICAL SYMBOL GORGON ARCHAION;So;0;L;;;;;N;;;;;
+1D017;BYZANTINE MUSICAL SYMBOL PSILON;So;0;L;;;;;N;;;;;
+1D018;BYZANTINE MUSICAL SYMBOL CHAMILON;So;0;L;;;;;N;;;;;
+1D019;BYZANTINE MUSICAL SYMBOL VATHY;So;0;L;;;;;N;;;;;
+1D01A;BYZANTINE MUSICAL SYMBOL ISON ARCHAION;So;0;L;;;;;N;;;;;
+1D01B;BYZANTINE MUSICAL SYMBOL KENTIMA ARCHAION;So;0;L;;;;;N;;;;;
+1D01C;BYZANTINE MUSICAL SYMBOL KENTIMATA ARCHAION;So;0;L;;;;;N;;;;;
+1D01D;BYZANTINE MUSICAL SYMBOL SAXIMATA;So;0;L;;;;;N;;;;;
+1D01E;BYZANTINE MUSICAL SYMBOL PARICHON;So;0;L;;;;;N;;;;;
+1D01F;BYZANTINE MUSICAL SYMBOL STAVROS APODEXIA;So;0;L;;;;;N;;;;;
+1D020;BYZANTINE MUSICAL SYMBOL OXEIAI ARCHAION;So;0;L;;;;;N;;;;;
+1D021;BYZANTINE MUSICAL SYMBOL VAREIAI ARCHAION;So;0;L;;;;;N;;;;;
+1D022;BYZANTINE MUSICAL SYMBOL APODERMA ARCHAION;So;0;L;;;;;N;;;;;
+1D023;BYZANTINE MUSICAL SYMBOL APOTHEMA;So;0;L;;;;;N;;;;;
+1D024;BYZANTINE MUSICAL SYMBOL KLASMA;So;0;L;;;;;N;;;;;
+1D025;BYZANTINE MUSICAL SYMBOL REVMA;So;0;L;;;;;N;;;;;
+1D026;BYZANTINE MUSICAL SYMBOL PIASMA ARCHAION;So;0;L;;;;;N;;;;;
+1D027;BYZANTINE MUSICAL SYMBOL TINAGMA;So;0;L;;;;;N;;;;;
+1D028;BYZANTINE MUSICAL SYMBOL ANATRICHISMA;So;0;L;;;;;N;;;;;
+1D029;BYZANTINE MUSICAL SYMBOL SEISMA;So;0;L;;;;;N;;;;;
+1D02A;BYZANTINE MUSICAL SYMBOL SYNAGMA ARCHAION;So;0;L;;;;;N;;;;;
+1D02B;BYZANTINE MUSICAL SYMBOL SYNAGMA META STAVROU;So;0;L;;;;;N;;;;;
+1D02C;BYZANTINE MUSICAL SYMBOL OYRANISMA ARCHAION;So;0;L;;;;;N;;;;;
+1D02D;BYZANTINE MUSICAL SYMBOL THEMA;So;0;L;;;;;N;;;;;
+1D02E;BYZANTINE MUSICAL SYMBOL LEMOI;So;0;L;;;;;N;;;;;
+1D02F;BYZANTINE MUSICAL SYMBOL DYO;So;0;L;;;;;N;;;;;
+1D030;BYZANTINE MUSICAL SYMBOL TRIA;So;0;L;;;;;N;;;;;
+1D031;BYZANTINE MUSICAL SYMBOL TESSERA;So;0;L;;;;;N;;;;;
+1D032;BYZANTINE MUSICAL SYMBOL KRATIMATA;So;0;L;;;;;N;;;;;
+1D033;BYZANTINE MUSICAL SYMBOL APESO EXO NEO;So;0;L;;;;;N;;;;;
+1D034;BYZANTINE MUSICAL SYMBOL FTHORA ARCHAION;So;0;L;;;;;N;;;;;
+1D035;BYZANTINE MUSICAL SYMBOL IMIFTHORA;So;0;L;;;;;N;;;;;
+1D036;BYZANTINE MUSICAL SYMBOL TROMIKON ARCHAION;So;0;L;;;;;N;;;;;
+1D037;BYZANTINE MUSICAL SYMBOL KATAVA TROMIKON;So;0;L;;;;;N;;;;;
+1D038;BYZANTINE MUSICAL SYMBOL PELASTON;So;0;L;;;;;N;;;;;
+1D039;BYZANTINE MUSICAL SYMBOL PSIFISTON;So;0;L;;;;;N;;;;;
+1D03A;BYZANTINE MUSICAL SYMBOL KONTEVMA;So;0;L;;;;;N;;;;;
+1D03B;BYZANTINE MUSICAL SYMBOL CHOREVMA ARCHAION;So;0;L;;;;;N;;;;;
+1D03C;BYZANTINE MUSICAL SYMBOL RAPISMA;So;0;L;;;;;N;;;;;
+1D03D;BYZANTINE MUSICAL SYMBOL PARAKALESMA ARCHAION;So;0;L;;;;;N;;;;;
+1D03E;BYZANTINE MUSICAL SYMBOL PARAKLITIKI ARCHAION;So;0;L;;;;;N;;;;;
+1D03F;BYZANTINE MUSICAL SYMBOL ICHADIN;So;0;L;;;;;N;;;;;
+1D040;BYZANTINE MUSICAL SYMBOL NANA;So;0;L;;;;;N;;;;;
+1D041;BYZANTINE MUSICAL SYMBOL PETASMA;So;0;L;;;;;N;;;;;
+1D042;BYZANTINE MUSICAL SYMBOL KONTEVMA ALLO;So;0;L;;;;;N;;;;;
+1D043;BYZANTINE MUSICAL SYMBOL TROMIKON ALLO;So;0;L;;;;;N;;;;;
+1D044;BYZANTINE MUSICAL SYMBOL STRAGGISMATA;So;0;L;;;;;N;;;;;
+1D045;BYZANTINE MUSICAL SYMBOL GRONTHISMATA;So;0;L;;;;;N;;;;;
+1D046;BYZANTINE MUSICAL SYMBOL ISON NEO;So;0;L;;;;;N;;;;;
+1D047;BYZANTINE MUSICAL SYMBOL OLIGON NEO;So;0;L;;;;;N;;;;;
+1D048;BYZANTINE MUSICAL SYMBOL OXEIA NEO;So;0;L;;;;;N;;;;;
+1D049;BYZANTINE MUSICAL SYMBOL PETASTI;So;0;L;;;;;N;;;;;
+1D04A;BYZANTINE MUSICAL SYMBOL KOUFISMA;So;0;L;;;;;N;;;;;
+1D04B;BYZANTINE MUSICAL SYMBOL PETASTOKOUFISMA;So;0;L;;;;;N;;;;;
+1D04C;BYZANTINE MUSICAL SYMBOL KRATIMOKOUFISMA;So;0;L;;;;;N;;;;;
+1D04D;BYZANTINE MUSICAL SYMBOL PELASTON NEO;So;0;L;;;;;N;;;;;
+1D04E;BYZANTINE MUSICAL SYMBOL KENTIMATA NEO ANO;So;0;L;;;;;N;;;;;
+1D04F;BYZANTINE MUSICAL SYMBOL KENTIMA NEO ANO;So;0;L;;;;;N;;;;;
+1D050;BYZANTINE MUSICAL SYMBOL YPSILI;So;0;L;;;;;N;;;;;
+1D051;BYZANTINE MUSICAL SYMBOL APOSTROFOS NEO;So;0;L;;;;;N;;;;;
+1D052;BYZANTINE MUSICAL SYMBOL APOSTROFOI SYNDESMOS NEO;So;0;L;;;;;N;;;;;
+1D053;BYZANTINE MUSICAL SYMBOL YPORROI;So;0;L;;;;;N;;;;;
+1D054;BYZANTINE MUSICAL SYMBOL KRATIMOYPORROON;So;0;L;;;;;N;;;;;
+1D055;BYZANTINE MUSICAL SYMBOL ELAFRON;So;0;L;;;;;N;;;;;
+1D056;BYZANTINE MUSICAL SYMBOL CHAMILI;So;0;L;;;;;N;;;;;
+1D057;BYZANTINE MUSICAL SYMBOL MIKRON ISON;So;0;L;;;;;N;;;;;
+1D058;BYZANTINE MUSICAL SYMBOL VAREIA NEO;So;0;L;;;;;N;;;;;
+1D059;BYZANTINE MUSICAL SYMBOL PIASMA NEO;So;0;L;;;;;N;;;;;
+1D05A;BYZANTINE MUSICAL SYMBOL PSIFISTON NEO;So;0;L;;;;;N;;;;;
+1D05B;BYZANTINE MUSICAL SYMBOL OMALON;So;0;L;;;;;N;;;;;
+1D05C;BYZANTINE MUSICAL SYMBOL ANTIKENOMA;So;0;L;;;;;N;;;;;
+1D05D;BYZANTINE MUSICAL SYMBOL LYGISMA;So;0;L;;;;;N;;;;;
+1D05E;BYZANTINE MUSICAL SYMBOL PARAKLITIKI NEO;So;0;L;;;;;N;;;;;
+1D05F;BYZANTINE MUSICAL SYMBOL PARAKALESMA NEO;So;0;L;;;;;N;;;;;
+1D060;BYZANTINE MUSICAL SYMBOL ETERON PARAKALESMA;So;0;L;;;;;N;;;;;
+1D061;BYZANTINE MUSICAL SYMBOL KYLISMA;So;0;L;;;;;N;;;;;
+1D062;BYZANTINE MUSICAL SYMBOL ANTIKENOKYLISMA;So;0;L;;;;;N;;;;;
+1D063;BYZANTINE MUSICAL SYMBOL TROMIKON NEO;So;0;L;;;;;N;;;;;
+1D064;BYZANTINE MUSICAL SYMBOL EKSTREPTON;So;0;L;;;;;N;;;;;
+1D065;BYZANTINE MUSICAL SYMBOL SYNAGMA NEO;So;0;L;;;;;N;;;;;
+1D066;BYZANTINE MUSICAL SYMBOL SYRMA;So;0;L;;;;;N;;;;;
+1D067;BYZANTINE MUSICAL SYMBOL CHOREVMA NEO;So;0;L;;;;;N;;;;;
+1D068;BYZANTINE MUSICAL SYMBOL EPEGERMA;So;0;L;;;;;N;;;;;
+1D069;BYZANTINE MUSICAL SYMBOL SEISMA NEO;So;0;L;;;;;N;;;;;
+1D06A;BYZANTINE MUSICAL SYMBOL XIRON KLASMA;So;0;L;;;;;N;;;;;
+1D06B;BYZANTINE MUSICAL SYMBOL TROMIKOPSIFISTON;So;0;L;;;;;N;;;;;
+1D06C;BYZANTINE MUSICAL SYMBOL PSIFISTOLYGISMA;So;0;L;;;;;N;;;;;
+1D06D;BYZANTINE MUSICAL SYMBOL TROMIKOLYGISMA;So;0;L;;;;;N;;;;;
+1D06E;BYZANTINE MUSICAL SYMBOL TROMIKOPARAKALESMA;So;0;L;;;;;N;;;;;
+1D06F;BYZANTINE MUSICAL SYMBOL PSIFISTOPARAKALESMA;So;0;L;;;;;N;;;;;
+1D070;BYZANTINE MUSICAL SYMBOL TROMIKOSYNAGMA;So;0;L;;;;;N;;;;;
+1D071;BYZANTINE MUSICAL SYMBOL PSIFISTOSYNAGMA;So;0;L;;;;;N;;;;;
+1D072;BYZANTINE MUSICAL SYMBOL GORGOSYNTHETON;So;0;L;;;;;N;;;;;
+1D073;BYZANTINE MUSICAL SYMBOL ARGOSYNTHETON;So;0;L;;;;;N;;;;;
+1D074;BYZANTINE MUSICAL SYMBOL ETERON ARGOSYNTHETON;So;0;L;;;;;N;;;;;
+1D075;BYZANTINE MUSICAL SYMBOL OYRANISMA NEO;So;0;L;;;;;N;;;;;
+1D076;BYZANTINE MUSICAL SYMBOL THEMATISMOS ESO;So;0;L;;;;;N;;;;;
+1D077;BYZANTINE MUSICAL SYMBOL THEMATISMOS EXO;So;0;L;;;;;N;;;;;
+1D078;BYZANTINE MUSICAL SYMBOL THEMA APLOUN;So;0;L;;;;;N;;;;;
+1D079;BYZANTINE MUSICAL SYMBOL THES KAI APOTHES;So;0;L;;;;;N;;;;;
+1D07A;BYZANTINE MUSICAL SYMBOL KATAVASMA;So;0;L;;;;;N;;;;;
+1D07B;BYZANTINE MUSICAL SYMBOL ENDOFONON;So;0;L;;;;;N;;;;;
+1D07C;BYZANTINE MUSICAL SYMBOL YFEN KATO;So;0;L;;;;;N;;;;;
+1D07D;BYZANTINE MUSICAL SYMBOL YFEN ANO;So;0;L;;;;;N;;;;;
+1D07E;BYZANTINE MUSICAL SYMBOL STAVROS;So;0;L;;;;;N;;;;;
+1D07F;BYZANTINE MUSICAL SYMBOL KLASMA ANO;So;0;L;;;;;N;;;;;
+1D080;BYZANTINE MUSICAL SYMBOL DIPLI ARCHAION;So;0;L;;;;;N;;;;;
+1D081;BYZANTINE MUSICAL SYMBOL KRATIMA ARCHAION;So;0;L;;;;;N;;;;;
+1D082;BYZANTINE MUSICAL SYMBOL KRATIMA ALLO;So;0;L;;;;;N;;;;;
+1D083;BYZANTINE MUSICAL SYMBOL KRATIMA NEO;So;0;L;;;;;N;;;;;
+1D084;BYZANTINE MUSICAL SYMBOL APODERMA NEO;So;0;L;;;;;N;;;;;
+1D085;BYZANTINE MUSICAL SYMBOL APLI;So;0;L;;;;;N;;;;;
+1D086;BYZANTINE MUSICAL SYMBOL DIPLI;So;0;L;;;;;N;;;;;
+1D087;BYZANTINE MUSICAL SYMBOL TRIPLI;So;0;L;;;;;N;;;;;
+1D088;BYZANTINE MUSICAL SYMBOL TETRAPLI;So;0;L;;;;;N;;;;;
+1D089;BYZANTINE MUSICAL SYMBOL KORONIS;So;0;L;;;;;N;;;;;
+1D08A;BYZANTINE MUSICAL SYMBOL LEIMMA ENOS CHRONOU;So;0;L;;;;;N;;;;;
+1D08B;BYZANTINE MUSICAL SYMBOL LEIMMA DYO CHRONON;So;0;L;;;;;N;;;;;
+1D08C;BYZANTINE MUSICAL SYMBOL LEIMMA TRION CHRONON;So;0;L;;;;;N;;;;;
+1D08D;BYZANTINE MUSICAL SYMBOL LEIMMA TESSARON CHRONON;So;0;L;;;;;N;;;;;
+1D08E;BYZANTINE MUSICAL SYMBOL LEIMMA IMISEOS CHRONOU;So;0;L;;;;;N;;;;;
+1D08F;BYZANTINE MUSICAL SYMBOL GORGON NEO ANO;So;0;L;;;;;N;;;;;
+1D090;BYZANTINE MUSICAL SYMBOL GORGON PARESTIGMENON ARISTERA;So;0;L;;;;;N;;;;;
+1D091;BYZANTINE MUSICAL SYMBOL GORGON PARESTIGMENON DEXIA;So;0;L;;;;;N;;;;;
+1D092;BYZANTINE MUSICAL SYMBOL DIGORGON;So;0;L;;;;;N;;;;;
+1D093;BYZANTINE MUSICAL SYMBOL DIGORGON PARESTIGMENON ARISTERA KATO;So;0;L;;;;;N;;;;;
+1D094;BYZANTINE MUSICAL SYMBOL DIGORGON PARESTIGMENON ARISTERA ANO;So;0;L;;;;;N;;;;;
+1D095;BYZANTINE MUSICAL SYMBOL DIGORGON PARESTIGMENON DEXIA;So;0;L;;;;;N;;;;;
+1D096;BYZANTINE MUSICAL SYMBOL TRIGORGON;So;0;L;;;;;N;;;;;
+1D097;BYZANTINE MUSICAL SYMBOL ARGON;So;0;L;;;;;N;;;;;
+1D098;BYZANTINE MUSICAL SYMBOL IMIDIARGON;So;0;L;;;;;N;;;;;
+1D099;BYZANTINE MUSICAL SYMBOL DIARGON;So;0;L;;;;;N;;;;;
+1D09A;BYZANTINE MUSICAL SYMBOL AGOGI POLI ARGI;So;0;L;;;;;N;;;;;
+1D09B;BYZANTINE MUSICAL SYMBOL AGOGI ARGOTERI;So;0;L;;;;;N;;;;;
+1D09C;BYZANTINE MUSICAL SYMBOL AGOGI ARGI;So;0;L;;;;;N;;;;;
+1D09D;BYZANTINE MUSICAL SYMBOL AGOGI METRIA;So;0;L;;;;;N;;;;;
+1D09E;BYZANTINE MUSICAL SYMBOL AGOGI MESI;So;0;L;;;;;N;;;;;
+1D09F;BYZANTINE MUSICAL SYMBOL AGOGI GORGI;So;0;L;;;;;N;;;;;
+1D0A0;BYZANTINE MUSICAL SYMBOL AGOGI GORGOTERI;So;0;L;;;;;N;;;;;
+1D0A1;BYZANTINE MUSICAL SYMBOL AGOGI POLI GORGI;So;0;L;;;;;N;;;;;
+1D0A2;BYZANTINE MUSICAL SYMBOL MARTYRIA PROTOS ICHOS;So;0;L;;;;;N;;;;;
+1D0A3;BYZANTINE MUSICAL SYMBOL MARTYRIA ALLI PROTOS ICHOS;So;0;L;;;;;N;;;;;
+1D0A4;BYZANTINE MUSICAL SYMBOL MARTYRIA DEYTEROS ICHOS;So;0;L;;;;;N;;;;;
+1D0A5;BYZANTINE MUSICAL SYMBOL MARTYRIA ALLI DEYTEROS ICHOS;So;0;L;;;;;N;;;;;
+1D0A6;BYZANTINE MUSICAL SYMBOL MARTYRIA TRITOS ICHOS;So;0;L;;;;;N;;;;;
+1D0A7;BYZANTINE MUSICAL SYMBOL MARTYRIA TRIFONIAS;So;0;L;;;;;N;;;;;
+1D0A8;BYZANTINE MUSICAL SYMBOL MARTYRIA TETARTOS ICHOS;So;0;L;;;;;N;;;;;
+1D0A9;BYZANTINE MUSICAL SYMBOL MARTYRIA TETARTOS LEGETOS ICHOS;So;0;L;;;;;N;;;;;
+1D0AA;BYZANTINE MUSICAL SYMBOL MARTYRIA LEGETOS ICHOS;So;0;L;;;;;N;;;;;
+1D0AB;BYZANTINE MUSICAL SYMBOL MARTYRIA PLAGIOS ICHOS;So;0;L;;;;;N;;;;;
+1D0AC;BYZANTINE MUSICAL SYMBOL ISAKIA TELOUS ICHIMATOS;So;0;L;;;;;N;;;;;
+1D0AD;BYZANTINE MUSICAL SYMBOL APOSTROFOI TELOUS ICHIMATOS;So;0;L;;;;;N;;;;;
+1D0AE;BYZANTINE MUSICAL SYMBOL FANEROSIS TETRAFONIAS;So;0;L;;;;;N;;;;;
+1D0AF;BYZANTINE MUSICAL SYMBOL FANEROSIS MONOFONIAS;So;0;L;;;;;N;;;;;
+1D0B0;BYZANTINE MUSICAL SYMBOL FANEROSIS DIFONIAS;So;0;L;;;;;N;;;;;
+1D0B1;BYZANTINE MUSICAL SYMBOL MARTYRIA VARYS ICHOS;So;0;L;;;;;N;;;;;
+1D0B2;BYZANTINE MUSICAL SYMBOL MARTYRIA PROTOVARYS ICHOS;So;0;L;;;;;N;;;;;
+1D0B3;BYZANTINE MUSICAL SYMBOL MARTYRIA PLAGIOS TETARTOS ICHOS;So;0;L;;;;;N;;;;;
+1D0B4;BYZANTINE MUSICAL SYMBOL GORTHMIKON N APLOUN;So;0;L;;;;;N;;;;;
+1D0B5;BYZANTINE MUSICAL SYMBOL GORTHMIKON N DIPLOUN;So;0;L;;;;;N;;;;;
+1D0B6;BYZANTINE MUSICAL SYMBOL ENARXIS KAI FTHORA VOU;So;0;L;;;;;N;;;;;
+1D0B7;BYZANTINE MUSICAL SYMBOL IMIFONON;So;0;L;;;;;N;;;;;
+1D0B8;BYZANTINE MUSICAL SYMBOL IMIFTHORON;So;0;L;;;;;N;;;;;
+1D0B9;BYZANTINE MUSICAL SYMBOL FTHORA ARCHAION DEYTEROU ICHOU;So;0;L;;;;;N;;;;;
+1D0BA;BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI PA;So;0;L;;;;;N;;;;;
+1D0BB;BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI NANA;So;0;L;;;;;N;;;;;
+1D0BC;BYZANTINE MUSICAL SYMBOL FTHORA NAOS ICHOS;So;0;L;;;;;N;;;;;
+1D0BD;BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI DI;So;0;L;;;;;N;;;;;
+1D0BE;BYZANTINE MUSICAL SYMBOL FTHORA SKLIRON DIATONON DI;So;0;L;;;;;N;;;;;
+1D0BF;BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI KE;So;0;L;;;;;N;;;;;
+1D0C0;BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI ZO;So;0;L;;;;;N;;;;;
+1D0C1;BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI NI KATO;So;0;L;;;;;N;;;;;
+1D0C2;BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI NI ANO;So;0;L;;;;;N;;;;;
+1D0C3;BYZANTINE MUSICAL SYMBOL FTHORA MALAKON CHROMA DIFONIAS;So;0;L;;;;;N;;;;;
+1D0C4;BYZANTINE MUSICAL SYMBOL FTHORA MALAKON CHROMA MONOFONIAS;So;0;L;;;;;N;;;;;
+1D0C5;BYZANTINE MUSICAL SYMBOL FHTORA SKLIRON CHROMA VASIS;So;0;L;;;;;N;;;;;
+1D0C6;BYZANTINE MUSICAL SYMBOL FTHORA SKLIRON CHROMA SYNAFI;So;0;L;;;;;N;;;;;
+1D0C7;BYZANTINE MUSICAL SYMBOL FTHORA NENANO;So;0;L;;;;;N;;;;;
+1D0C8;BYZANTINE MUSICAL SYMBOL CHROA ZYGOS;So;0;L;;;;;N;;;;;
+1D0C9;BYZANTINE MUSICAL SYMBOL CHROA KLITON;So;0;L;;;;;N;;;;;
+1D0CA;BYZANTINE MUSICAL SYMBOL CHROA SPATHI;So;0;L;;;;;N;;;;;
+1D0CB;BYZANTINE MUSICAL SYMBOL FTHORA I YFESIS TETARTIMORION;So;0;L;;;;;N;;;;;
+1D0CC;BYZANTINE MUSICAL SYMBOL FTHORA ENARMONIOS ANTIFONIA;So;0;L;;;;;N;;;;;
+1D0CD;BYZANTINE MUSICAL SYMBOL YFESIS TRITIMORION;So;0;L;;;;;N;;;;;
+1D0CE;BYZANTINE MUSICAL SYMBOL DIESIS TRITIMORION;So;0;L;;;;;N;;;;;
+1D0CF;BYZANTINE MUSICAL SYMBOL DIESIS TETARTIMORION;So;0;L;;;;;N;;;;;
+1D0D0;BYZANTINE MUSICAL SYMBOL DIESIS APLI DYO DODEKATA;So;0;L;;;;;N;;;;;
+1D0D1;BYZANTINE MUSICAL SYMBOL DIESIS MONOGRAMMOS TESSERA DODEKATA;So;0;L;;;;;N;;;;;
+1D0D2;BYZANTINE MUSICAL SYMBOL DIESIS DIGRAMMOS EX DODEKATA;So;0;L;;;;;N;;;;;
+1D0D3;BYZANTINE MUSICAL SYMBOL DIESIS TRIGRAMMOS OKTO DODEKATA;So;0;L;;;;;N;;;;;
+1D0D4;BYZANTINE MUSICAL SYMBOL YFESIS APLI DYO DODEKATA;So;0;L;;;;;N;;;;;
+1D0D5;BYZANTINE MUSICAL SYMBOL YFESIS MONOGRAMMOS TESSERA DODEKATA;So;0;L;;;;;N;;;;;
+1D0D6;BYZANTINE MUSICAL SYMBOL YFESIS DIGRAMMOS EX DODEKATA;So;0;L;;;;;N;;;;;
+1D0D7;BYZANTINE MUSICAL SYMBOL YFESIS TRIGRAMMOS OKTO DODEKATA;So;0;L;;;;;N;;;;;
+1D0D8;BYZANTINE MUSICAL SYMBOL GENIKI DIESIS;So;0;L;;;;;N;;;;;
+1D0D9;BYZANTINE MUSICAL SYMBOL GENIKI YFESIS;So;0;L;;;;;N;;;;;
+1D0DA;BYZANTINE MUSICAL SYMBOL DIASTOLI APLI MIKRI;So;0;L;;;;;N;;;;;
+1D0DB;BYZANTINE MUSICAL SYMBOL DIASTOLI APLI MEGALI;So;0;L;;;;;N;;;;;
+1D0DC;BYZANTINE MUSICAL SYMBOL DIASTOLI DIPLI;So;0;L;;;;;N;;;;;
+1D0DD;BYZANTINE MUSICAL SYMBOL DIASTOLI THESEOS;So;0;L;;;;;N;;;;;
+1D0DE;BYZANTINE MUSICAL SYMBOL SIMANSIS THESEOS;So;0;L;;;;;N;;;;;
+1D0DF;BYZANTINE MUSICAL SYMBOL SIMANSIS THESEOS DISIMOU;So;0;L;;;;;N;;;;;
+1D0E0;BYZANTINE MUSICAL SYMBOL SIMANSIS THESEOS TRISIMOU;So;0;L;;;;;N;;;;;
+1D0E1;BYZANTINE MUSICAL SYMBOL SIMANSIS THESEOS TETRASIMOU;So;0;L;;;;;N;;;;;
+1D0E2;BYZANTINE MUSICAL SYMBOL SIMANSIS ARSEOS;So;0;L;;;;;N;;;;;
+1D0E3;BYZANTINE MUSICAL SYMBOL SIMANSIS ARSEOS DISIMOU;So;0;L;;;;;N;;;;;
+1D0E4;BYZANTINE MUSICAL SYMBOL SIMANSIS ARSEOS TRISIMOU;So;0;L;;;;;N;;;;;
+1D0E5;BYZANTINE MUSICAL SYMBOL SIMANSIS ARSEOS TETRASIMOU;So;0;L;;;;;N;;;;;
+1D0E6;BYZANTINE MUSICAL SYMBOL DIGRAMMA GG;So;0;L;;;;;N;;;;;
+1D0E7;BYZANTINE MUSICAL SYMBOL DIFTOGGOS OU;So;0;L;;;;;N;;;;;
+1D0E8;BYZANTINE MUSICAL SYMBOL STIGMA;So;0;L;;;;;N;;;;;
+1D0E9;BYZANTINE MUSICAL SYMBOL ARKTIKO PA;So;0;L;;;;;N;;;;;
+1D0EA;BYZANTINE MUSICAL SYMBOL ARKTIKO VOU;So;0;L;;;;;N;;;;;
+1D0EB;BYZANTINE MUSICAL SYMBOL ARKTIKO GA;So;0;L;;;;;N;;;;;
+1D0EC;BYZANTINE MUSICAL SYMBOL ARKTIKO DI;So;0;L;;;;;N;;;;;
+1D0ED;BYZANTINE MUSICAL SYMBOL ARKTIKO KE;So;0;L;;;;;N;;;;;
+1D0EE;BYZANTINE MUSICAL SYMBOL ARKTIKO ZO;So;0;L;;;;;N;;;;;
+1D0EF;BYZANTINE MUSICAL SYMBOL ARKTIKO NI;So;0;L;;;;;N;;;;;
+1D0F0;BYZANTINE MUSICAL SYMBOL KENTIMATA NEO MESO;So;0;L;;;;;N;;;;;
+1D0F1;BYZANTINE MUSICAL SYMBOL KENTIMA NEO MESO;So;0;L;;;;;N;;;;;
+1D0F2;BYZANTINE MUSICAL SYMBOL KENTIMATA NEO KATO;So;0;L;;;;;N;;;;;
+1D0F3;BYZANTINE MUSICAL SYMBOL KENTIMA NEO KATO;So;0;L;;;;;N;;;;;
+1D0F4;BYZANTINE MUSICAL SYMBOL KLASMA KATO;So;0;L;;;;;N;;;;;
+1D0F5;BYZANTINE MUSICAL SYMBOL GORGON NEO KATO;So;0;L;;;;;N;;;;;
+1D100;MUSICAL SYMBOL SINGLE BARLINE;So;0;L;;;;;N;;;;;
+1D101;MUSICAL SYMBOL DOUBLE BARLINE;So;0;L;;;;;N;;;;;
+1D102;MUSICAL SYMBOL FINAL BARLINE;So;0;L;;;;;N;;;;;
+1D103;MUSICAL SYMBOL REVERSE FINAL BARLINE;So;0;L;;;;;N;;;;;
+1D104;MUSICAL SYMBOL DASHED BARLINE;So;0;L;;;;;N;;;;;
+1D105;MUSICAL SYMBOL SHORT BARLINE;So;0;L;;;;;N;;;;;
+1D106;MUSICAL SYMBOL LEFT REPEAT SIGN;So;0;L;;;;;N;;;;;
+1D107;MUSICAL SYMBOL RIGHT REPEAT SIGN;So;0;L;;;;;N;;;;;
+1D108;MUSICAL SYMBOL REPEAT DOTS;So;0;L;;;;;N;;;;;
+1D109;MUSICAL SYMBOL DAL SEGNO;So;0;L;;;;;N;;;;;
+1D10A;MUSICAL SYMBOL DA CAPO;So;0;L;;;;;N;;;;;
+1D10B;MUSICAL SYMBOL SEGNO;So;0;L;;;;;N;;;;;
+1D10C;MUSICAL SYMBOL CODA;So;0;L;;;;;N;;;;;
+1D10D;MUSICAL SYMBOL REPEATED FIGURE-1;So;0;L;;;;;N;;;;;
+1D10E;MUSICAL SYMBOL REPEATED FIGURE-2;So;0;L;;;;;N;;;;;
+1D10F;MUSICAL SYMBOL REPEATED FIGURE-3;So;0;L;;;;;N;;;;;
+1D110;MUSICAL SYMBOL FERMATA;So;0;L;;;;;N;;;;;
+1D111;MUSICAL SYMBOL FERMATA BELOW;So;0;L;;;;;N;;;;;
+1D112;MUSICAL SYMBOL BREATH MARK;So;0;L;;;;;N;;;;;
+1D113;MUSICAL SYMBOL CAESURA;So;0;L;;;;;N;;;;;
+1D114;MUSICAL SYMBOL BRACE;So;0;L;;;;;N;;;;;
+1D115;MUSICAL SYMBOL BRACKET;So;0;L;;;;;N;;;;;
+1D116;MUSICAL SYMBOL ONE-LINE STAFF;So;0;L;;;;;N;;;;;
+1D117;MUSICAL SYMBOL TWO-LINE STAFF;So;0;L;;;;;N;;;;;
+1D118;MUSICAL SYMBOL THREE-LINE STAFF;So;0;L;;;;;N;;;;;
+1D119;MUSICAL SYMBOL FOUR-LINE STAFF;So;0;L;;;;;N;;;;;
+1D11A;MUSICAL SYMBOL FIVE-LINE STAFF;So;0;L;;;;;N;;;;;
+1D11B;MUSICAL SYMBOL SIX-LINE STAFF;So;0;L;;;;;N;;;;;
+1D11C;MUSICAL SYMBOL SIX-STRING FRETBOARD;So;0;L;;;;;N;;;;;
+1D11D;MUSICAL SYMBOL FOUR-STRING FRETBOARD;So;0;L;;;;;N;;;;;
+1D11E;MUSICAL SYMBOL G CLEF;So;0;L;;;;;N;;;;;
+1D11F;MUSICAL SYMBOL G CLEF OTTAVA ALTA;So;0;L;;;;;N;;;;;
+1D120;MUSICAL SYMBOL G CLEF OTTAVA BASSA;So;0;L;;;;;N;;;;;
+1D121;MUSICAL SYMBOL C CLEF;So;0;L;;;;;N;;;;;
+1D122;MUSICAL SYMBOL F CLEF;So;0;L;;;;;N;;;;;
+1D123;MUSICAL SYMBOL F CLEF OTTAVA ALTA;So;0;L;;;;;N;;;;;
+1D124;MUSICAL SYMBOL F CLEF OTTAVA BASSA;So;0;L;;;;;N;;;;;
+1D125;MUSICAL SYMBOL DRUM CLEF-1;So;0;L;;;;;N;;;;;
+1D126;MUSICAL SYMBOL DRUM CLEF-2;So;0;L;;;;;N;;;;;
+1D12A;MUSICAL SYMBOL DOUBLE SHARP;So;0;L;;;;;N;;;;;
+1D12B;MUSICAL SYMBOL DOUBLE FLAT;So;0;L;;;;;N;;;;;
+1D12C;MUSICAL SYMBOL FLAT UP;So;0;L;;;;;N;;;;;
+1D12D;MUSICAL SYMBOL FLAT DOWN;So;0;L;;;;;N;;;;;
+1D12E;MUSICAL SYMBOL NATURAL UP;So;0;L;;;;;N;;;;;
+1D12F;MUSICAL SYMBOL NATURAL DOWN;So;0;L;;;;;N;;;;;
+1D130;MUSICAL SYMBOL SHARP UP;So;0;L;;;;;N;;;;;
+1D131;MUSICAL SYMBOL SHARP DOWN;So;0;L;;;;;N;;;;;
+1D132;MUSICAL SYMBOL QUARTER TONE SHARP;So;0;L;;;;;N;;;;;
+1D133;MUSICAL SYMBOL QUARTER TONE FLAT;So;0;L;;;;;N;;;;;
+1D134;MUSICAL SYMBOL COMMON TIME;So;0;L;;;;;N;;;;;
+1D135;MUSICAL SYMBOL CUT TIME;So;0;L;;;;;N;;;;;
+1D136;MUSICAL SYMBOL OTTAVA ALTA;So;0;L;;;;;N;;;;;
+1D137;MUSICAL SYMBOL OTTAVA BASSA;So;0;L;;;;;N;;;;;
+1D138;MUSICAL SYMBOL QUINDICESIMA ALTA;So;0;L;;;;;N;;;;;
+1D139;MUSICAL SYMBOL QUINDICESIMA BASSA;So;0;L;;;;;N;;;;;
+1D13A;MUSICAL SYMBOL MULTI REST;So;0;L;;;;;N;;;;;
+1D13B;MUSICAL SYMBOL WHOLE REST;So;0;L;;;;;N;;;;;
+1D13C;MUSICAL SYMBOL HALF REST;So;0;L;;;;;N;;;;;
+1D13D;MUSICAL SYMBOL QUARTER REST;So;0;L;;;;;N;;;;;
+1D13E;MUSICAL SYMBOL EIGHTH REST;So;0;L;;;;;N;;;;;
+1D13F;MUSICAL SYMBOL SIXTEENTH REST;So;0;L;;;;;N;;;;;
+1D140;MUSICAL SYMBOL THIRTY-SECOND REST;So;0;L;;;;;N;;;;;
+1D141;MUSICAL SYMBOL SIXTY-FOURTH REST;So;0;L;;;;;N;;;;;
+1D142;MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH REST;So;0;L;;;;;N;;;;;
+1D143;MUSICAL SYMBOL X NOTEHEAD;So;0;L;;;;;N;;;;;
+1D144;MUSICAL SYMBOL PLUS NOTEHEAD;So;0;L;;;;;N;;;;;
+1D145;MUSICAL SYMBOL CIRCLE X NOTEHEAD;So;0;L;;;;;N;;;;;
+1D146;MUSICAL SYMBOL SQUARE NOTEHEAD WHITE;So;0;L;;;;;N;;;;;
+1D147;MUSICAL SYMBOL SQUARE NOTEHEAD BLACK;So;0;L;;;;;N;;;;;
+1D148;MUSICAL SYMBOL TRIANGLE NOTEHEAD UP WHITE;So;0;L;;;;;N;;;;;
+1D149;MUSICAL SYMBOL TRIANGLE NOTEHEAD UP BLACK;So;0;L;;;;;N;;;;;
+1D14A;MUSICAL SYMBOL TRIANGLE NOTEHEAD LEFT WHITE;So;0;L;;;;;N;;;;;
+1D14B;MUSICAL SYMBOL TRIANGLE NOTEHEAD LEFT BLACK;So;0;L;;;;;N;;;;;
+1D14C;MUSICAL SYMBOL TRIANGLE NOTEHEAD RIGHT WHITE;So;0;L;;;;;N;;;;;
+1D14D;MUSICAL SYMBOL TRIANGLE NOTEHEAD RIGHT BLACK;So;0;L;;;;;N;;;;;
+1D14E;MUSICAL SYMBOL TRIANGLE NOTEHEAD DOWN WHITE;So;0;L;;;;;N;;;;;
+1D14F;MUSICAL SYMBOL TRIANGLE NOTEHEAD DOWN BLACK;So;0;L;;;;;N;;;;;
+1D150;MUSICAL SYMBOL TRIANGLE NOTEHEAD UP RIGHT WHITE;So;0;L;;;;;N;;;;;
+1D151;MUSICAL SYMBOL TRIANGLE NOTEHEAD UP RIGHT BLACK;So;0;L;;;;;N;;;;;
+1D152;MUSICAL SYMBOL MOON NOTEHEAD WHITE;So;0;L;;;;;N;;;;;
+1D153;MUSICAL SYMBOL MOON NOTEHEAD BLACK;So;0;L;;;;;N;;;;;
+1D154;MUSICAL SYMBOL TRIANGLE-ROUND NOTEHEAD DOWN WHITE;So;0;L;;;;;N;;;;;
+1D155;MUSICAL SYMBOL TRIANGLE-ROUND NOTEHEAD DOWN BLACK;So;0;L;;;;;N;;;;;
+1D156;MUSICAL SYMBOL PARENTHESIS NOTEHEAD;So;0;L;;;;;N;;;;;
+1D157;MUSICAL SYMBOL VOID NOTEHEAD;So;0;L;;;;;N;;;;;
+1D158;MUSICAL SYMBOL NOTEHEAD BLACK;So;0;L;;;;;N;;;;;
+1D159;MUSICAL SYMBOL NULL NOTEHEAD;So;0;L;;;;;N;;;;;
+1D15A;MUSICAL SYMBOL CLUSTER NOTEHEAD WHITE;So;0;L;;;;;N;;;;;
+1D15B;MUSICAL SYMBOL CLUSTER NOTEHEAD BLACK;So;0;L;;;;;N;;;;;
+1D15C;MUSICAL SYMBOL BREVE;So;0;L;;;;;N;;;;;
+1D15D;MUSICAL SYMBOL WHOLE NOTE;So;0;L;;;;;N;;;;;
+1D15E;MUSICAL SYMBOL HALF NOTE;So;0;L;1D157 1D165;;;;N;;;;;
+1D15F;MUSICAL SYMBOL QUARTER NOTE;So;0;L;1D158 1D165;;;;N;;;;;
+1D160;MUSICAL SYMBOL EIGHTH NOTE;So;0;L;1D15F 1D16E;;;;N;;;;;
+1D161;MUSICAL SYMBOL SIXTEENTH NOTE;So;0;L;1D15F 1D16F;;;;N;;;;;
+1D162;MUSICAL SYMBOL THIRTY-SECOND NOTE;So;0;L;1D15F 1D170;;;;N;;;;;
+1D163;MUSICAL SYMBOL SIXTY-FOURTH NOTE;So;0;L;1D15F 1D171;;;;N;;;;;
+1D164;MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH NOTE;So;0;L;1D15F 1D172;;;;N;;;;;
+1D165;MUSICAL SYMBOL COMBINING STEM;Mc;216;L;;;;;N;;;;;
+1D166;MUSICAL SYMBOL COMBINING SPRECHGESANG STEM;Mc;216;L;;;;;N;;;;;
+1D167;MUSICAL SYMBOL COMBINING TREMOLO-1;Mn;1;NSM;;;;;N;;;;;
+1D168;MUSICAL SYMBOL COMBINING TREMOLO-2;Mn;1;NSM;;;;;N;;;;;
+1D169;MUSICAL SYMBOL COMBINING TREMOLO-3;Mn;1;NSM;;;;;N;;;;;
+1D16A;MUSICAL SYMBOL FINGERED TREMOLO-1;So;0;L;;;;;N;;;;;
+1D16B;MUSICAL SYMBOL FINGERED TREMOLO-2;So;0;L;;;;;N;;;;;
+1D16C;MUSICAL SYMBOL FINGERED TREMOLO-3;So;0;L;;;;;N;;;;;
+1D16D;MUSICAL SYMBOL COMBINING AUGMENTATION DOT;Mc;226;L;;;;;N;;;;;
+1D16E;MUSICAL SYMBOL COMBINING FLAG-1;Mc;216;L;;;;;N;;;;;
+1D16F;MUSICAL SYMBOL COMBINING FLAG-2;Mc;216;L;;;;;N;;;;;
+1D170;MUSICAL SYMBOL COMBINING FLAG-3;Mc;216;L;;;;;N;;;;;
+1D171;MUSICAL SYMBOL COMBINING FLAG-4;Mc;216;L;;;;;N;;;;;
+1D172;MUSICAL SYMBOL COMBINING FLAG-5;Mc;216;L;;;;;N;;;;;
+1D173;MUSICAL SYMBOL BEGIN BEAM;Cf;0;BN;;;;;N;;;;;
+1D174;MUSICAL SYMBOL END BEAM;Cf;0;BN;;;;;N;;;;;
+1D175;MUSICAL SYMBOL BEGIN TIE;Cf;0;BN;;;;;N;;;;;
+1D176;MUSICAL SYMBOL END TIE;Cf;0;BN;;;;;N;;;;;
+1D177;MUSICAL SYMBOL BEGIN SLUR;Cf;0;BN;;;;;N;;;;;
+1D178;MUSICAL SYMBOL END SLUR;Cf;0;BN;;;;;N;;;;;
+1D179;MUSICAL SYMBOL BEGIN PHRASE;Cf;0;BN;;;;;N;;;;;
+1D17A;MUSICAL SYMBOL END PHRASE;Cf;0;BN;;;;;N;;;;;
+1D17B;MUSICAL SYMBOL COMBINING ACCENT;Mn;220;NSM;;;;;N;;;;;
+1D17C;MUSICAL SYMBOL COMBINING STACCATO;Mn;220;NSM;;;;;N;;;;;
+1D17D;MUSICAL SYMBOL COMBINING TENUTO;Mn;220;NSM;;;;;N;;;;;
+1D17E;MUSICAL SYMBOL COMBINING STACCATISSIMO;Mn;220;NSM;;;;;N;;;;;
+1D17F;MUSICAL SYMBOL COMBINING MARCATO;Mn;220;NSM;;;;;N;;;;;
+1D180;MUSICAL SYMBOL COMBINING MARCATO-STACCATO;Mn;220;NSM;;;;;N;;;;;
+1D181;MUSICAL SYMBOL COMBINING ACCENT-STACCATO;Mn;220;NSM;;;;;N;;;;;
+1D182;MUSICAL SYMBOL COMBINING LOURE;Mn;220;NSM;;;;;N;;;;;
+1D183;MUSICAL SYMBOL ARPEGGIATO UP;So;0;L;;;;;N;;;;;
+1D184;MUSICAL SYMBOL ARPEGGIATO DOWN;So;0;L;;;;;N;;;;;
+1D185;MUSICAL SYMBOL COMBINING DOIT;Mn;230;NSM;;;;;N;;;;;
+1D186;MUSICAL SYMBOL COMBINING RIP;Mn;230;NSM;;;;;N;;;;;
+1D187;MUSICAL SYMBOL COMBINING FLIP;Mn;230;NSM;;;;;N;;;;;
+1D188;MUSICAL SYMBOL COMBINING SMEAR;Mn;230;NSM;;;;;N;;;;;
+1D189;MUSICAL SYMBOL COMBINING BEND;Mn;230;NSM;;;;;N;;;;;
+1D18A;MUSICAL SYMBOL COMBINING DOUBLE TONGUE;Mn;220;NSM;;;;;N;;;;;
+1D18B;MUSICAL SYMBOL COMBINING TRIPLE TONGUE;Mn;220;NSM;;;;;N;;;;;
+1D18C;MUSICAL SYMBOL RINFORZANDO;So;0;L;;;;;N;;;;;
+1D18D;MUSICAL SYMBOL SUBITO;So;0;L;;;;;N;;;;;
+1D18E;MUSICAL SYMBOL Z;So;0;L;;;;;N;;;;;
+1D18F;MUSICAL SYMBOL PIANO;So;0;L;;;;;N;;;;;
+1D190;MUSICAL SYMBOL MEZZO;So;0;L;;;;;N;;;;;
+1D191;MUSICAL SYMBOL FORTE;So;0;L;;;;;N;;;;;
+1D192;MUSICAL SYMBOL CRESCENDO;So;0;L;;;;;N;;;;;
+1D193;MUSICAL SYMBOL DECRESCENDO;So;0;L;;;;;N;;;;;
+1D194;MUSICAL SYMBOL GRACE NOTE SLASH;So;0;L;;;;;N;;;;;
+1D195;MUSICAL SYMBOL GRACE NOTE NO SLASH;So;0;L;;;;;N;;;;;
+1D196;MUSICAL SYMBOL TR;So;0;L;;;;;N;;;;;
+1D197;MUSICAL SYMBOL TURN;So;0;L;;;;;N;;;;;
+1D198;MUSICAL SYMBOL INVERTED TURN;So;0;L;;;;;N;;;;;
+1D199;MUSICAL SYMBOL TURN SLASH;So;0;L;;;;;N;;;;;
+1D19A;MUSICAL SYMBOL TURN UP;So;0;L;;;;;N;;;;;
+1D19B;MUSICAL SYMBOL ORNAMENT STROKE-1;So;0;L;;;;;N;;;;;
+1D19C;MUSICAL SYMBOL ORNAMENT STROKE-2;So;0;L;;;;;N;;;;;
+1D19D;MUSICAL SYMBOL ORNAMENT STROKE-3;So;0;L;;;;;N;;;;;
+1D19E;MUSICAL SYMBOL ORNAMENT STROKE-4;So;0;L;;;;;N;;;;;
+1D19F;MUSICAL SYMBOL ORNAMENT STROKE-5;So;0;L;;;;;N;;;;;
+1D1A0;MUSICAL SYMBOL ORNAMENT STROKE-6;So;0;L;;;;;N;;;;;
+1D1A1;MUSICAL SYMBOL ORNAMENT STROKE-7;So;0;L;;;;;N;;;;;
+1D1A2;MUSICAL SYMBOL ORNAMENT STROKE-8;So;0;L;;;;;N;;;;;
+1D1A3;MUSICAL SYMBOL ORNAMENT STROKE-9;So;0;L;;;;;N;;;;;
+1D1A4;MUSICAL SYMBOL ORNAMENT STROKE-10;So;0;L;;;;;N;;;;;
+1D1A5;MUSICAL SYMBOL ORNAMENT STROKE-11;So;0;L;;;;;N;;;;;
+1D1A6;MUSICAL SYMBOL HAUPTSTIMME;So;0;L;;;;;N;;;;;
+1D1A7;MUSICAL SYMBOL NEBENSTIMME;So;0;L;;;;;N;;;;;
+1D1A8;MUSICAL SYMBOL END OF STIMME;So;0;L;;;;;N;;;;;
+1D1A9;MUSICAL SYMBOL DEGREE SLASH;So;0;L;;;;;N;;;;;
+1D1AA;MUSICAL SYMBOL COMBINING DOWN BOW;Mn;230;NSM;;;;;N;;;;;
+1D1AB;MUSICAL SYMBOL COMBINING UP BOW;Mn;230;NSM;;;;;N;;;;;
+1D1AC;MUSICAL SYMBOL COMBINING HARMONIC;Mn;230;NSM;;;;;N;;;;;
+1D1AD;MUSICAL SYMBOL COMBINING SNAP PIZZICATO;Mn;230;NSM;;;;;N;;;;;
+1D1AE;MUSICAL SYMBOL PEDAL MARK;So;0;L;;;;;N;;;;;
+1D1AF;MUSICAL SYMBOL PEDAL UP MARK;So;0;L;;;;;N;;;;;
+1D1B0;MUSICAL SYMBOL HALF PEDAL MARK;So;0;L;;;;;N;;;;;
+1D1B1;MUSICAL SYMBOL GLISSANDO UP;So;0;L;;;;;N;;;;;
+1D1B2;MUSICAL SYMBOL GLISSANDO DOWN;So;0;L;;;;;N;;;;;
+1D1B3;MUSICAL SYMBOL WITH FINGERNAILS;So;0;L;;;;;N;;;;;
+1D1B4;MUSICAL SYMBOL DAMP;So;0;L;;;;;N;;;;;
+1D1B5;MUSICAL SYMBOL DAMP ALL;So;0;L;;;;;N;;;;;
+1D1B6;MUSICAL SYMBOL MAXIMA;So;0;L;;;;;N;;;;;
+1D1B7;MUSICAL SYMBOL LONGA;So;0;L;;;;;N;;;;;
+1D1B8;MUSICAL SYMBOL BREVIS;So;0;L;;;;;N;;;;;
+1D1B9;MUSICAL SYMBOL SEMIBREVIS WHITE;So;0;L;;;;;N;;;;;
+1D1BA;MUSICAL SYMBOL SEMIBREVIS BLACK;So;0;L;;;;;N;;;;;
+1D1BB;MUSICAL SYMBOL MINIMA;So;0;L;1D1B9 1D165;;;;N;;;;;
+1D1BC;MUSICAL SYMBOL MINIMA BLACK;So;0;L;1D1BA 1D165;;;;N;;;;;
+1D1BD;MUSICAL SYMBOL SEMIMINIMA WHITE;So;0;L;1D1BB 1D16E;;;;N;;;;;
+1D1BE;MUSICAL SYMBOL SEMIMINIMA BLACK;So;0;L;1D1BC 1D16E;;;;N;;;;;
+1D1BF;MUSICAL SYMBOL FUSA WHITE;So;0;L;1D1BB 1D16F;;;;N;;;;;
+1D1C0;MUSICAL SYMBOL FUSA BLACK;So;0;L;1D1BC 1D16F;;;;N;;;;;
+1D1C1;MUSICAL SYMBOL LONGA PERFECTA REST;So;0;L;;;;;N;;;;;
+1D1C2;MUSICAL SYMBOL LONGA IMPERFECTA REST;So;0;L;;;;;N;;;;;
+1D1C3;MUSICAL SYMBOL BREVIS REST;So;0;L;;;;;N;;;;;
+1D1C4;MUSICAL SYMBOL SEMIBREVIS REST;So;0;L;;;;;N;;;;;
+1D1C5;MUSICAL SYMBOL MINIMA REST;So;0;L;;;;;N;;;;;
+1D1C6;MUSICAL SYMBOL SEMIMINIMA REST;So;0;L;;;;;N;;;;;
+1D1C7;MUSICAL SYMBOL TEMPUS PERFECTUM CUM PROLATIONE PERFECTA;So;0;L;;;;;N;;;;;
+1D1C8;MUSICAL SYMBOL TEMPUS PERFECTUM CUM PROLATIONE IMPERFECTA;So;0;L;;;;;N;;;;;
+1D1C9;MUSICAL SYMBOL TEMPUS PERFECTUM CUM PROLATIONE PERFECTA DIMINUTION-1;So;0;L;;;;;N;;;;;
+1D1CA;MUSICAL SYMBOL TEMPUS IMPERFECTUM CUM PROLATIONE PERFECTA;So;0;L;;;;;N;;;;;
+1D1CB;MUSICAL SYMBOL TEMPUS IMPERFECTUM CUM PROLATIONE IMPERFECTA;So;0;L;;;;;N;;;;;
+1D1CC;MUSICAL SYMBOL TEMPUS IMPERFECTUM CUM PROLATIONE IMPERFECTA DIMINUTION-1;So;0;L;;;;;N;;;;;
+1D1CD;MUSICAL SYMBOL TEMPUS IMPERFECTUM CUM PROLATIONE IMPERFECTA DIMINUTION-2;So;0;L;;;;;N;;;;;
+1D1CE;MUSICAL SYMBOL TEMPUS IMPERFECTUM CUM PROLATIONE IMPERFECTA DIMINUTION-3;So;0;L;;;;;N;;;;;
+1D1CF;MUSICAL SYMBOL CROIX;So;0;L;;;;;N;;;;;
+1D1D0;MUSICAL SYMBOL GREGORIAN C CLEF;So;0;L;;;;;N;;;;;
+1D1D1;MUSICAL SYMBOL GREGORIAN F CLEF;So;0;L;;;;;N;;;;;
+1D1D2;MUSICAL SYMBOL SQUARE B;So;0;L;;;;;N;;;;;
+1D1D3;MUSICAL SYMBOL VIRGA;So;0;L;;;;;N;;;;;
+1D1D4;MUSICAL SYMBOL PODATUS;So;0;L;;;;;N;;;;;
+1D1D5;MUSICAL SYMBOL CLIVIS;So;0;L;;;;;N;;;;;
+1D1D6;MUSICAL SYMBOL SCANDICUS;So;0;L;;;;;N;;;;;
+1D1D7;MUSICAL SYMBOL CLIMACUS;So;0;L;;;;;N;;;;;
+1D1D8;MUSICAL SYMBOL TORCULUS;So;0;L;;;;;N;;;;;
+1D1D9;MUSICAL SYMBOL PORRECTUS;So;0;L;;;;;N;;;;;
+1D1DA;MUSICAL SYMBOL PORRECTUS FLEXUS;So;0;L;;;;;N;;;;;
+1D1DB;MUSICAL SYMBOL SCANDICUS FLEXUS;So;0;L;;;;;N;;;;;
+1D1DC;MUSICAL SYMBOL TORCULUS RESUPINUS;So;0;L;;;;;N;;;;;
+1D1DD;MUSICAL SYMBOL PES SUBPUNCTIS;So;0;L;;;;;N;;;;;
+1D300;MONOGRAM FOR EARTH;So;0;ON;;;;;N;;;;;
+1D301;DIGRAM FOR HEAVENLY EARTH;So;0;ON;;;;;N;;;;;
+1D302;DIGRAM FOR HUMAN EARTH;So;0;ON;;;;;N;;;;;
+1D303;DIGRAM FOR EARTHLY HEAVEN;So;0;ON;;;;;N;;;;;
+1D304;DIGRAM FOR EARTHLY HUMAN;So;0;ON;;;;;N;;;;;
+1D305;DIGRAM FOR EARTH;So;0;ON;;;;;N;;;;;
+1D306;TETRAGRAM FOR CENTRE;So;0;ON;;;;;N;;;;;
+1D307;TETRAGRAM FOR FULL CIRCLE;So;0;ON;;;;;N;;;;;
+1D308;TETRAGRAM FOR MIRED;So;0;ON;;;;;N;;;;;
+1D309;TETRAGRAM FOR BARRIER;So;0;ON;;;;;N;;;;;
+1D30A;TETRAGRAM FOR KEEPING SMALL;So;0;ON;;;;;N;;;;;
+1D30B;TETRAGRAM FOR CONTRARIETY;So;0;ON;;;;;N;;;;;
+1D30C;TETRAGRAM FOR ASCENT;So;0;ON;;;;;N;;;;;
+1D30D;TETRAGRAM FOR OPPOSITION;So;0;ON;;;;;N;;;;;
+1D30E;TETRAGRAM FOR BRANCHING OUT;So;0;ON;;;;;N;;;;;
+1D30F;TETRAGRAM FOR DEFECTIVENESS OR DISTORTION;So;0;ON;;;;;N;;;;;
+1D310;TETRAGRAM FOR DIVERGENCE;So;0;ON;;;;;N;;;;;
+1D311;TETRAGRAM FOR YOUTHFULNESS;So;0;ON;;;;;N;;;;;
+1D312;TETRAGRAM FOR INCREASE;So;0;ON;;;;;N;;;;;
+1D313;TETRAGRAM FOR PENETRATION;So;0;ON;;;;;N;;;;;
+1D314;TETRAGRAM FOR REACH;So;0;ON;;;;;N;;;;;
+1D315;TETRAGRAM FOR CONTACT;So;0;ON;;;;;N;;;;;
+1D316;TETRAGRAM FOR HOLDING BACK;So;0;ON;;;;;N;;;;;
+1D317;TETRAGRAM FOR WAITING;So;0;ON;;;;;N;;;;;
+1D318;TETRAGRAM FOR FOLLOWING;So;0;ON;;;;;N;;;;;
+1D319;TETRAGRAM FOR ADVANCE;So;0;ON;;;;;N;;;;;
+1D31A;TETRAGRAM FOR RELEASE;So;0;ON;;;;;N;;;;;
+1D31B;TETRAGRAM FOR RESISTANCE;So;0;ON;;;;;N;;;;;
+1D31C;TETRAGRAM FOR EASE;So;0;ON;;;;;N;;;;;
+1D31D;TETRAGRAM FOR JOY;So;0;ON;;;;;N;;;;;
+1D31E;TETRAGRAM FOR CONTENTION;So;0;ON;;;;;N;;;;;
+1D31F;TETRAGRAM FOR ENDEAVOUR;So;0;ON;;;;;N;;;;;
+1D320;TETRAGRAM FOR DUTIES;So;0;ON;;;;;N;;;;;
+1D321;TETRAGRAM FOR CHANGE;So;0;ON;;;;;N;;;;;
+1D322;TETRAGRAM FOR DECISIVENESS;So;0;ON;;;;;N;;;;;
+1D323;TETRAGRAM FOR BOLD RESOLUTION;So;0;ON;;;;;N;;;;;
+1D324;TETRAGRAM FOR PACKING;So;0;ON;;;;;N;;;;;
+1D325;TETRAGRAM FOR LEGION;So;0;ON;;;;;N;;;;;
+1D326;TETRAGRAM FOR CLOSENESS;So;0;ON;;;;;N;;;;;
+1D327;TETRAGRAM FOR KINSHIP;So;0;ON;;;;;N;;;;;
+1D328;TETRAGRAM FOR GATHERING;So;0;ON;;;;;N;;;;;
+1D329;TETRAGRAM FOR STRENGTH;So;0;ON;;;;;N;;;;;
+1D32A;TETRAGRAM FOR PURITY;So;0;ON;;;;;N;;;;;
+1D32B;TETRAGRAM FOR FULLNESS;So;0;ON;;;;;N;;;;;
+1D32C;TETRAGRAM FOR RESIDENCE;So;0;ON;;;;;N;;;;;
+1D32D;TETRAGRAM FOR LAW OR MODEL;So;0;ON;;;;;N;;;;;
+1D32E;TETRAGRAM FOR RESPONSE;So;0;ON;;;;;N;;;;;
+1D32F;TETRAGRAM FOR GOING TO MEET;So;0;ON;;;;;N;;;;;
+1D330;TETRAGRAM FOR ENCOUNTERS;So;0;ON;;;;;N;;;;;
+1D331;TETRAGRAM FOR STOVE;So;0;ON;;;;;N;;;;;
+1D332;TETRAGRAM FOR GREATNESS;So;0;ON;;;;;N;;;;;
+1D333;TETRAGRAM FOR ENLARGEMENT;So;0;ON;;;;;N;;;;;
+1D334;TETRAGRAM FOR PATTERN;So;0;ON;;;;;N;;;;;
+1D335;TETRAGRAM FOR RITUAL;So;0;ON;;;;;N;;;;;
+1D336;TETRAGRAM FOR FLIGHT;So;0;ON;;;;;N;;;;;
+1D337;TETRAGRAM FOR VASTNESS OR WASTING;So;0;ON;;;;;N;;;;;
+1D338;TETRAGRAM FOR CONSTANCY;So;0;ON;;;;;N;;;;;
+1D339;TETRAGRAM FOR MEASURE;So;0;ON;;;;;N;;;;;
+1D33A;TETRAGRAM FOR ETERNITY;So;0;ON;;;;;N;;;;;
+1D33B;TETRAGRAM FOR UNITY;So;0;ON;;;;;N;;;;;
+1D33C;TETRAGRAM FOR DIMINISHMENT;So;0;ON;;;;;N;;;;;
+1D33D;TETRAGRAM FOR CLOSED MOUTH;So;0;ON;;;;;N;;;;;
+1D33E;TETRAGRAM FOR GUARDEDNESS;So;0;ON;;;;;N;;;;;
+1D33F;TETRAGRAM FOR GATHERING IN;So;0;ON;;;;;N;;;;;
+1D340;TETRAGRAM FOR MASSING;So;0;ON;;;;;N;;;;;
+1D341;TETRAGRAM FOR ACCUMULATION;So;0;ON;;;;;N;;;;;
+1D342;TETRAGRAM FOR EMBELLISHMENT;So;0;ON;;;;;N;;;;;
+1D343;TETRAGRAM FOR DOUBT;So;0;ON;;;;;N;;;;;
+1D344;TETRAGRAM FOR WATCH;So;0;ON;;;;;N;;;;;
+1D345;TETRAGRAM FOR SINKING;So;0;ON;;;;;N;;;;;
+1D346;TETRAGRAM FOR INNER;So;0;ON;;;;;N;;;;;
+1D347;TETRAGRAM FOR DEPARTURE;So;0;ON;;;;;N;;;;;
+1D348;TETRAGRAM FOR DARKENING;So;0;ON;;;;;N;;;;;
+1D349;TETRAGRAM FOR DIMMING;So;0;ON;;;;;N;;;;;
+1D34A;TETRAGRAM FOR EXHAUSTION;So;0;ON;;;;;N;;;;;
+1D34B;TETRAGRAM FOR SEVERANCE;So;0;ON;;;;;N;;;;;
+1D34C;TETRAGRAM FOR STOPPAGE;So;0;ON;;;;;N;;;;;
+1D34D;TETRAGRAM FOR HARDNESS;So;0;ON;;;;;N;;;;;
+1D34E;TETRAGRAM FOR COMPLETION;So;0;ON;;;;;N;;;;;
+1D34F;TETRAGRAM FOR CLOSURE;So;0;ON;;;;;N;;;;;
+1D350;TETRAGRAM FOR FAILURE;So;0;ON;;;;;N;;;;;
+1D351;TETRAGRAM FOR AGGRAVATION;So;0;ON;;;;;N;;;;;
+1D352;TETRAGRAM FOR COMPLIANCE;So;0;ON;;;;;N;;;;;
+1D353;TETRAGRAM FOR ON THE VERGE;So;0;ON;;;;;N;;;;;
+1D354;TETRAGRAM FOR DIFFICULTIES;So;0;ON;;;;;N;;;;;
+1D355;TETRAGRAM FOR LABOURING;So;0;ON;;;;;N;;;;;
+1D356;TETRAGRAM FOR FOSTERING;So;0;ON;;;;;N;;;;;
+1D400;MATHEMATICAL BOLD CAPITAL A;Lu;0;L;<font> 0041;;;;N;;;;;
+1D401;MATHEMATICAL BOLD CAPITAL B;Lu;0;L;<font> 0042;;;;N;;;;;
+1D402;MATHEMATICAL BOLD CAPITAL C;Lu;0;L;<font> 0043;;;;N;;;;;
+1D403;MATHEMATICAL BOLD CAPITAL D;Lu;0;L;<font> 0044;;;;N;;;;;
+1D404;MATHEMATICAL BOLD CAPITAL E;Lu;0;L;<font> 0045;;;;N;;;;;
+1D405;MATHEMATICAL BOLD CAPITAL F;Lu;0;L;<font> 0046;;;;N;;;;;
+1D406;MATHEMATICAL BOLD CAPITAL G;Lu;0;L;<font> 0047;;;;N;;;;;
+1D407;MATHEMATICAL BOLD CAPITAL H;Lu;0;L;<font> 0048;;;;N;;;;;
+1D408;MATHEMATICAL BOLD CAPITAL I;Lu;0;L;<font> 0049;;;;N;;;;;
+1D409;MATHEMATICAL BOLD CAPITAL J;Lu;0;L;<font> 004A;;;;N;;;;;
+1D40A;MATHEMATICAL BOLD CAPITAL K;Lu;0;L;<font> 004B;;;;N;;;;;
+1D40B;MATHEMATICAL BOLD CAPITAL L;Lu;0;L;<font> 004C;;;;N;;;;;
+1D40C;MATHEMATICAL BOLD CAPITAL M;Lu;0;L;<font> 004D;;;;N;;;;;
+1D40D;MATHEMATICAL BOLD CAPITAL N;Lu;0;L;<font> 004E;;;;N;;;;;
+1D40E;MATHEMATICAL BOLD CAPITAL O;Lu;0;L;<font> 004F;;;;N;;;;;
+1D40F;MATHEMATICAL BOLD CAPITAL P;Lu;0;L;<font> 0050;;;;N;;;;;
+1D410;MATHEMATICAL BOLD CAPITAL Q;Lu;0;L;<font> 0051;;;;N;;;;;
+1D411;MATHEMATICAL BOLD CAPITAL R;Lu;0;L;<font> 0052;;;;N;;;;;
+1D412;MATHEMATICAL BOLD CAPITAL S;Lu;0;L;<font> 0053;;;;N;;;;;
+1D413;MATHEMATICAL BOLD CAPITAL T;Lu;0;L;<font> 0054;;;;N;;;;;
+1D414;MATHEMATICAL BOLD CAPITAL U;Lu;0;L;<font> 0055;;;;N;;;;;
+1D415;MATHEMATICAL BOLD CAPITAL V;Lu;0;L;<font> 0056;;;;N;;;;;
+1D416;MATHEMATICAL BOLD CAPITAL W;Lu;0;L;<font> 0057;;;;N;;;;;
+1D417;MATHEMATICAL BOLD CAPITAL X;Lu;0;L;<font> 0058;;;;N;;;;;
+1D418;MATHEMATICAL BOLD CAPITAL Y;Lu;0;L;<font> 0059;;;;N;;;;;
+1D419;MATHEMATICAL BOLD CAPITAL Z;Lu;0;L;<font> 005A;;;;N;;;;;
+1D41A;MATHEMATICAL BOLD SMALL A;Ll;0;L;<font> 0061;;;;N;;;;;
+1D41B;MATHEMATICAL BOLD SMALL B;Ll;0;L;<font> 0062;;;;N;;;;;
+1D41C;MATHEMATICAL BOLD SMALL C;Ll;0;L;<font> 0063;;;;N;;;;;
+1D41D;MATHEMATICAL BOLD SMALL D;Ll;0;L;<font> 0064;;;;N;;;;;
+1D41E;MATHEMATICAL BOLD SMALL E;Ll;0;L;<font> 0065;;;;N;;;;;
+1D41F;MATHEMATICAL BOLD SMALL F;Ll;0;L;<font> 0066;;;;N;;;;;
+1D420;MATHEMATICAL BOLD SMALL G;Ll;0;L;<font> 0067;;;;N;;;;;
+1D421;MATHEMATICAL BOLD SMALL H;Ll;0;L;<font> 0068;;;;N;;;;;
+1D422;MATHEMATICAL BOLD SMALL I;Ll;0;L;<font> 0069;;;;N;;;;;
+1D423;MATHEMATICAL BOLD SMALL J;Ll;0;L;<font> 006A;;;;N;;;;;
+1D424;MATHEMATICAL BOLD SMALL K;Ll;0;L;<font> 006B;;;;N;;;;;
+1D425;MATHEMATICAL BOLD SMALL L;Ll;0;L;<font> 006C;;;;N;;;;;
+1D426;MATHEMATICAL BOLD SMALL M;Ll;0;L;<font> 006D;;;;N;;;;;
+1D427;MATHEMATICAL BOLD SMALL N;Ll;0;L;<font> 006E;;;;N;;;;;
+1D428;MATHEMATICAL BOLD SMALL O;Ll;0;L;<font> 006F;;;;N;;;;;
+1D429;MATHEMATICAL BOLD SMALL P;Ll;0;L;<font> 0070;;;;N;;;;;
+1D42A;MATHEMATICAL BOLD SMALL Q;Ll;0;L;<font> 0071;;;;N;;;;;
+1D42B;MATHEMATICAL BOLD SMALL R;Ll;0;L;<font> 0072;;;;N;;;;;
+1D42C;MATHEMATICAL BOLD SMALL S;Ll;0;L;<font> 0073;;;;N;;;;;
+1D42D;MATHEMATICAL BOLD SMALL T;Ll;0;L;<font> 0074;;;;N;;;;;
+1D42E;MATHEMATICAL BOLD SMALL U;Ll;0;L;<font> 0075;;;;N;;;;;
+1D42F;MATHEMATICAL BOLD SMALL V;Ll;0;L;<font> 0076;;;;N;;;;;
+1D430;MATHEMATICAL BOLD SMALL W;Ll;0;L;<font> 0077;;;;N;;;;;
+1D431;MATHEMATICAL BOLD SMALL X;Ll;0;L;<font> 0078;;;;N;;;;;
+1D432;MATHEMATICAL BOLD SMALL Y;Ll;0;L;<font> 0079;;;;N;;;;;
+1D433;MATHEMATICAL BOLD SMALL Z;Ll;0;L;<font> 007A;;;;N;;;;;
+1D434;MATHEMATICAL ITALIC CAPITAL A;Lu;0;L;<font> 0041;;;;N;;;;;
+1D435;MATHEMATICAL ITALIC CAPITAL B;Lu;0;L;<font> 0042;;;;N;;;;;
+1D436;MATHEMATICAL ITALIC CAPITAL C;Lu;0;L;<font> 0043;;;;N;;;;;
+1D437;MATHEMATICAL ITALIC CAPITAL D;Lu;0;L;<font> 0044;;;;N;;;;;
+1D438;MATHEMATICAL ITALIC CAPITAL E;Lu;0;L;<font> 0045;;;;N;;;;;
+1D439;MATHEMATICAL ITALIC CAPITAL F;Lu;0;L;<font> 0046;;;;N;;;;;
+1D43A;MATHEMATICAL ITALIC CAPITAL G;Lu;0;L;<font> 0047;;;;N;;;;;
+1D43B;MATHEMATICAL ITALIC CAPITAL H;Lu;0;L;<font> 0048;;;;N;;;;;
+1D43C;MATHEMATICAL ITALIC CAPITAL I;Lu;0;L;<font> 0049;;;;N;;;;;
+1D43D;MATHEMATICAL ITALIC CAPITAL J;Lu;0;L;<font> 004A;;;;N;;;;;
+1D43E;MATHEMATICAL ITALIC CAPITAL K;Lu;0;L;<font> 004B;;;;N;;;;;
+1D43F;MATHEMATICAL ITALIC CAPITAL L;Lu;0;L;<font> 004C;;;;N;;;;;
+1D440;MATHEMATICAL ITALIC CAPITAL M;Lu;0;L;<font> 004D;;;;N;;;;;
+1D441;MATHEMATICAL ITALIC CAPITAL N;Lu;0;L;<font> 004E;;;;N;;;;;
+1D442;MATHEMATICAL ITALIC CAPITAL O;Lu;0;L;<font> 004F;;;;N;;;;;
+1D443;MATHEMATICAL ITALIC CAPITAL P;Lu;0;L;<font> 0050;;;;N;;;;;
+1D444;MATHEMATICAL ITALIC CAPITAL Q;Lu;0;L;<font> 0051;;;;N;;;;;
+1D445;MATHEMATICAL ITALIC CAPITAL R;Lu;0;L;<font> 0052;;;;N;;;;;
+1D446;MATHEMATICAL ITALIC CAPITAL S;Lu;0;L;<font> 0053;;;;N;;;;;
+1D447;MATHEMATICAL ITALIC CAPITAL T;Lu;0;L;<font> 0054;;;;N;;;;;
+1D448;MATHEMATICAL ITALIC CAPITAL U;Lu;0;L;<font> 0055;;;;N;;;;;
+1D449;MATHEMATICAL ITALIC CAPITAL V;Lu;0;L;<font> 0056;;;;N;;;;;
+1D44A;MATHEMATICAL ITALIC CAPITAL W;Lu;0;L;<font> 0057;;;;N;;;;;
+1D44B;MATHEMATICAL ITALIC CAPITAL X;Lu;0;L;<font> 0058;;;;N;;;;;
+1D44C;MATHEMATICAL ITALIC CAPITAL Y;Lu;0;L;<font> 0059;;;;N;;;;;
+1D44D;MATHEMATICAL ITALIC CAPITAL Z;Lu;0;L;<font> 005A;;;;N;;;;;
+1D44E;MATHEMATICAL ITALIC SMALL A;Ll;0;L;<font> 0061;;;;N;;;;;
+1D44F;MATHEMATICAL ITALIC SMALL B;Ll;0;L;<font> 0062;;;;N;;;;;
+1D450;MATHEMATICAL ITALIC SMALL C;Ll;0;L;<font> 0063;;;;N;;;;;
+1D451;MATHEMATICAL ITALIC SMALL D;Ll;0;L;<font> 0064;;;;N;;;;;
+1D452;MATHEMATICAL ITALIC SMALL E;Ll;0;L;<font> 0065;;;;N;;;;;
+1D453;MATHEMATICAL ITALIC SMALL F;Ll;0;L;<font> 0066;;;;N;;;;;
+1D454;MATHEMATICAL ITALIC SMALL G;Ll;0;L;<font> 0067;;;;N;;;;;
+1D456;MATHEMATICAL ITALIC SMALL I;Ll;0;L;<font> 0069;;;;N;;;;;
+1D457;MATHEMATICAL ITALIC SMALL J;Ll;0;L;<font> 006A;;;;N;;;;;
+1D458;MATHEMATICAL ITALIC SMALL K;Ll;0;L;<font> 006B;;;;N;;;;;
+1D459;MATHEMATICAL ITALIC SMALL L;Ll;0;L;<font> 006C;;;;N;;;;;
+1D45A;MATHEMATICAL ITALIC SMALL M;Ll;0;L;<font> 006D;;;;N;;;;;
+1D45B;MATHEMATICAL ITALIC SMALL N;Ll;0;L;<font> 006E;;;;N;;;;;
+1D45C;MATHEMATICAL ITALIC SMALL O;Ll;0;L;<font> 006F;;;;N;;;;;
+1D45D;MATHEMATICAL ITALIC SMALL P;Ll;0;L;<font> 0070;;;;N;;;;;
+1D45E;MATHEMATICAL ITALIC SMALL Q;Ll;0;L;<font> 0071;;;;N;;;;;
+1D45F;MATHEMATICAL ITALIC SMALL R;Ll;0;L;<font> 0072;;;;N;;;;;
+1D460;MATHEMATICAL ITALIC SMALL S;Ll;0;L;<font> 0073;;;;N;;;;;
+1D461;MATHEMATICAL ITALIC SMALL T;Ll;0;L;<font> 0074;;;;N;;;;;
+1D462;MATHEMATICAL ITALIC SMALL U;Ll;0;L;<font> 0075;;;;N;;;;;
+1D463;MATHEMATICAL ITALIC SMALL V;Ll;0;L;<font> 0076;;;;N;;;;;
+1D464;MATHEMATICAL ITALIC SMALL W;Ll;0;L;<font> 0077;;;;N;;;;;
+1D465;MATHEMATICAL ITALIC SMALL X;Ll;0;L;<font> 0078;;;;N;;;;;
+1D466;MATHEMATICAL ITALIC SMALL Y;Ll;0;L;<font> 0079;;;;N;;;;;
+1D467;MATHEMATICAL ITALIC SMALL Z;Ll;0;L;<font> 007A;;;;N;;;;;
+1D468;MATHEMATICAL BOLD ITALIC CAPITAL A;Lu;0;L;<font> 0041;;;;N;;;;;
+1D469;MATHEMATICAL BOLD ITALIC CAPITAL B;Lu;0;L;<font> 0042;;;;N;;;;;
+1D46A;MATHEMATICAL BOLD ITALIC CAPITAL C;Lu;0;L;<font> 0043;;;;N;;;;;
+1D46B;MATHEMATICAL BOLD ITALIC CAPITAL D;Lu;0;L;<font> 0044;;;;N;;;;;
+1D46C;MATHEMATICAL BOLD ITALIC CAPITAL E;Lu;0;L;<font> 0045;;;;N;;;;;
+1D46D;MATHEMATICAL BOLD ITALIC CAPITAL F;Lu;0;L;<font> 0046;;;;N;;;;;
+1D46E;MATHEMATICAL BOLD ITALIC CAPITAL G;Lu;0;L;<font> 0047;;;;N;;;;;
+1D46F;MATHEMATICAL BOLD ITALIC CAPITAL H;Lu;0;L;<font> 0048;;;;N;;;;;
+1D470;MATHEMATICAL BOLD ITALIC CAPITAL I;Lu;0;L;<font> 0049;;;;N;;;;;
+1D471;MATHEMATICAL BOLD ITALIC CAPITAL J;Lu;0;L;<font> 004A;;;;N;;;;;
+1D472;MATHEMATICAL BOLD ITALIC CAPITAL K;Lu;0;L;<font> 004B;;;;N;;;;;
+1D473;MATHEMATICAL BOLD ITALIC CAPITAL L;Lu;0;L;<font> 004C;;;;N;;;;;
+1D474;MATHEMATICAL BOLD ITALIC CAPITAL M;Lu;0;L;<font> 004D;;;;N;;;;;
+1D475;MATHEMATICAL BOLD ITALIC CAPITAL N;Lu;0;L;<font> 004E;;;;N;;;;;
+1D476;MATHEMATICAL BOLD ITALIC CAPITAL O;Lu;0;L;<font> 004F;;;;N;;;;;
+1D477;MATHEMATICAL BOLD ITALIC CAPITAL P;Lu;0;L;<font> 0050;;;;N;;;;;
+1D478;MATHEMATICAL BOLD ITALIC CAPITAL Q;Lu;0;L;<font> 0051;;;;N;;;;;
+1D479;MATHEMATICAL BOLD ITALIC CAPITAL R;Lu;0;L;<font> 0052;;;;N;;;;;
+1D47A;MATHEMATICAL BOLD ITALIC CAPITAL S;Lu;0;L;<font> 0053;;;;N;;;;;
+1D47B;MATHEMATICAL BOLD ITALIC CAPITAL T;Lu;0;L;<font> 0054;;;;N;;;;;
+1D47C;MATHEMATICAL BOLD ITALIC CAPITAL U;Lu;0;L;<font> 0055;;;;N;;;;;
+1D47D;MATHEMATICAL BOLD ITALIC CAPITAL V;Lu;0;L;<font> 0056;;;;N;;;;;
+1D47E;MATHEMATICAL BOLD ITALIC CAPITAL W;Lu;0;L;<font> 0057;;;;N;;;;;
+1D47F;MATHEMATICAL BOLD ITALIC CAPITAL X;Lu;0;L;<font> 0058;;;;N;;;;;
+1D480;MATHEMATICAL BOLD ITALIC CAPITAL Y;Lu;0;L;<font> 0059;;;;N;;;;;
+1D481;MATHEMATICAL BOLD ITALIC CAPITAL Z;Lu;0;L;<font> 005A;;;;N;;;;;
+1D482;MATHEMATICAL BOLD ITALIC SMALL A;Ll;0;L;<font> 0061;;;;N;;;;;
+1D483;MATHEMATICAL BOLD ITALIC SMALL B;Ll;0;L;<font> 0062;;;;N;;;;;
+1D484;MATHEMATICAL BOLD ITALIC SMALL C;Ll;0;L;<font> 0063;;;;N;;;;;
+1D485;MATHEMATICAL BOLD ITALIC SMALL D;Ll;0;L;<font> 0064;;;;N;;;;;
+1D486;MATHEMATICAL BOLD ITALIC SMALL E;Ll;0;L;<font> 0065;;;;N;;;;;
+1D487;MATHEMATICAL BOLD ITALIC SMALL F;Ll;0;L;<font> 0066;;;;N;;;;;
+1D488;MATHEMATICAL BOLD ITALIC SMALL G;Ll;0;L;<font> 0067;;;;N;;;;;
+1D489;MATHEMATICAL BOLD ITALIC SMALL H;Ll;0;L;<font> 0068;;;;N;;;;;
+1D48A;MATHEMATICAL BOLD ITALIC SMALL I;Ll;0;L;<font> 0069;;;;N;;;;;
+1D48B;MATHEMATICAL BOLD ITALIC SMALL J;Ll;0;L;<font> 006A;;;;N;;;;;
+1D48C;MATHEMATICAL BOLD ITALIC SMALL K;Ll;0;L;<font> 006B;;;;N;;;;;
+1D48D;MATHEMATICAL BOLD ITALIC SMALL L;Ll;0;L;<font> 006C;;;;N;;;;;
+1D48E;MATHEMATICAL BOLD ITALIC SMALL M;Ll;0;L;<font> 006D;;;;N;;;;;
+1D48F;MATHEMATICAL BOLD ITALIC SMALL N;Ll;0;L;<font> 006E;;;;N;;;;;
+1D490;MATHEMATICAL BOLD ITALIC SMALL O;Ll;0;L;<font> 006F;;;;N;;;;;
+1D491;MATHEMATICAL BOLD ITALIC SMALL P;Ll;0;L;<font> 0070;;;;N;;;;;
+1D492;MATHEMATICAL BOLD ITALIC SMALL Q;Ll;0;L;<font> 0071;;;;N;;;;;
+1D493;MATHEMATICAL BOLD ITALIC SMALL R;Ll;0;L;<font> 0072;;;;N;;;;;
+1D494;MATHEMATICAL BOLD ITALIC SMALL S;Ll;0;L;<font> 0073;;;;N;;;;;
+1D495;MATHEMATICAL BOLD ITALIC SMALL T;Ll;0;L;<font> 0074;;;;N;;;;;
+1D496;MATHEMATICAL BOLD ITALIC SMALL U;Ll;0;L;<font> 0075;;;;N;;;;;
+1D497;MATHEMATICAL BOLD ITALIC SMALL V;Ll;0;L;<font> 0076;;;;N;;;;;
+1D498;MATHEMATICAL BOLD ITALIC SMALL W;Ll;0;L;<font> 0077;;;;N;;;;;
+1D499;MATHEMATICAL BOLD ITALIC SMALL X;Ll;0;L;<font> 0078;;;;N;;;;;
+1D49A;MATHEMATICAL BOLD ITALIC SMALL Y;Ll;0;L;<font> 0079;;;;N;;;;;
+1D49B;MATHEMATICAL BOLD ITALIC SMALL Z;Ll;0;L;<font> 007A;;;;N;;;;;
+1D49C;MATHEMATICAL SCRIPT CAPITAL A;Lu;0;L;<font> 0041;;;;N;;;;;
+1D49E;MATHEMATICAL SCRIPT CAPITAL C;Lu;0;L;<font> 0043;;;;N;;;;;
+1D49F;MATHEMATICAL SCRIPT CAPITAL D;Lu;0;L;<font> 0044;;;;N;;;;;
+1D4A2;MATHEMATICAL SCRIPT CAPITAL G;Lu;0;L;<font> 0047;;;;N;;;;;
+1D4A5;MATHEMATICAL SCRIPT CAPITAL J;Lu;0;L;<font> 004A;;;;N;;;;;
+1D4A6;MATHEMATICAL SCRIPT CAPITAL K;Lu;0;L;<font> 004B;;;;N;;;;;
+1D4A9;MATHEMATICAL SCRIPT CAPITAL N;Lu;0;L;<font> 004E;;;;N;;;;;
+1D4AA;MATHEMATICAL SCRIPT CAPITAL O;Lu;0;L;<font> 004F;;;;N;;;;;
+1D4AB;MATHEMATICAL SCRIPT CAPITAL P;Lu;0;L;<font> 0050;;;;N;;;;;
+1D4AC;MATHEMATICAL SCRIPT CAPITAL Q;Lu;0;L;<font> 0051;;;;N;;;;;
+1D4AE;MATHEMATICAL SCRIPT CAPITAL S;Lu;0;L;<font> 0053;;;;N;;;;;
+1D4AF;MATHEMATICAL SCRIPT CAPITAL T;Lu;0;L;<font> 0054;;;;N;;;;;
+1D4B0;MATHEMATICAL SCRIPT CAPITAL U;Lu;0;L;<font> 0055;;;;N;;;;;
+1D4B1;MATHEMATICAL SCRIPT CAPITAL V;Lu;0;L;<font> 0056;;;;N;;;;;
+1D4B2;MATHEMATICAL SCRIPT CAPITAL W;Lu;0;L;<font> 0057;;;;N;;;;;
+1D4B3;MATHEMATICAL SCRIPT CAPITAL X;Lu;0;L;<font> 0058;;;;N;;;;;
+1D4B4;MATHEMATICAL SCRIPT CAPITAL Y;Lu;0;L;<font> 0059;;;;N;;;;;
+1D4B5;MATHEMATICAL SCRIPT CAPITAL Z;Lu;0;L;<font> 005A;;;;N;;;;;
+1D4B6;MATHEMATICAL SCRIPT SMALL A;Ll;0;L;<font> 0061;;;;N;;;;;
+1D4B7;MATHEMATICAL SCRIPT SMALL B;Ll;0;L;<font> 0062;;;;N;;;;;
+1D4B8;MATHEMATICAL SCRIPT SMALL C;Ll;0;L;<font> 0063;;;;N;;;;;
+1D4B9;MATHEMATICAL SCRIPT SMALL D;Ll;0;L;<font> 0064;;;;N;;;;;
+1D4BB;MATHEMATICAL SCRIPT SMALL F;Ll;0;L;<font> 0066;;;;N;;;;;
+1D4BD;MATHEMATICAL SCRIPT SMALL H;Ll;0;L;<font> 0068;;;;N;;;;;
+1D4BE;MATHEMATICAL SCRIPT SMALL I;Ll;0;L;<font> 0069;;;;N;;;;;
+1D4BF;MATHEMATICAL SCRIPT SMALL J;Ll;0;L;<font> 006A;;;;N;;;;;
+1D4C0;MATHEMATICAL SCRIPT SMALL K;Ll;0;L;<font> 006B;;;;N;;;;;
+1D4C1;MATHEMATICAL SCRIPT SMALL L;Ll;0;L;<font> 006C;;;;N;;;;;
+1D4C2;MATHEMATICAL SCRIPT SMALL M;Ll;0;L;<font> 006D;;;;N;;;;;
+1D4C3;MATHEMATICAL SCRIPT SMALL N;Ll;0;L;<font> 006E;;;;N;;;;;
+1D4C5;MATHEMATICAL SCRIPT SMALL P;Ll;0;L;<font> 0070;;;;N;;;;;
+1D4C6;MATHEMATICAL SCRIPT SMALL Q;Ll;0;L;<font> 0071;;;;N;;;;;
+1D4C7;MATHEMATICAL SCRIPT SMALL R;Ll;0;L;<font> 0072;;;;N;;;;;
+1D4C8;MATHEMATICAL SCRIPT SMALL S;Ll;0;L;<font> 0073;;;;N;;;;;
+1D4C9;MATHEMATICAL SCRIPT SMALL T;Ll;0;L;<font> 0074;;;;N;;;;;
+1D4CA;MATHEMATICAL SCRIPT SMALL U;Ll;0;L;<font> 0075;;;;N;;;;;
+1D4CB;MATHEMATICAL SCRIPT SMALL V;Ll;0;L;<font> 0076;;;;N;;;;;
+1D4CC;MATHEMATICAL SCRIPT SMALL W;Ll;0;L;<font> 0077;;;;N;;;;;
+1D4CD;MATHEMATICAL SCRIPT SMALL X;Ll;0;L;<font> 0078;;;;N;;;;;
+1D4CE;MATHEMATICAL SCRIPT SMALL Y;Ll;0;L;<font> 0079;;;;N;;;;;
+1D4CF;MATHEMATICAL SCRIPT SMALL Z;Ll;0;L;<font> 007A;;;;N;;;;;
+1D4D0;MATHEMATICAL BOLD SCRIPT CAPITAL A;Lu;0;L;<font> 0041;;;;N;;;;;
+1D4D1;MATHEMATICAL BOLD SCRIPT CAPITAL B;Lu;0;L;<font> 0042;;;;N;;;;;
+1D4D2;MATHEMATICAL BOLD SCRIPT CAPITAL C;Lu;0;L;<font> 0043;;;;N;;;;;
+1D4D3;MATHEMATICAL BOLD SCRIPT CAPITAL D;Lu;0;L;<font> 0044;;;;N;;;;;
+1D4D4;MATHEMATICAL BOLD SCRIPT CAPITAL E;Lu;0;L;<font> 0045;;;;N;;;;;
+1D4D5;MATHEMATICAL BOLD SCRIPT CAPITAL F;Lu;0;L;<font> 0046;;;;N;;;;;
+1D4D6;MATHEMATICAL BOLD SCRIPT CAPITAL G;Lu;0;L;<font> 0047;;;;N;;;;;
+1D4D7;MATHEMATICAL BOLD SCRIPT CAPITAL H;Lu;0;L;<font> 0048;;;;N;;;;;
+1D4D8;MATHEMATICAL BOLD SCRIPT CAPITAL I;Lu;0;L;<font> 0049;;;;N;;;;;
+1D4D9;MATHEMATICAL BOLD SCRIPT CAPITAL J;Lu;0;L;<font> 004A;;;;N;;;;;
+1D4DA;MATHEMATICAL BOLD SCRIPT CAPITAL K;Lu;0;L;<font> 004B;;;;N;;;;;
+1D4DB;MATHEMATICAL BOLD SCRIPT CAPITAL L;Lu;0;L;<font> 004C;;;;N;;;;;
+1D4DC;MATHEMATICAL BOLD SCRIPT CAPITAL M;Lu;0;L;<font> 004D;;;;N;;;;;
+1D4DD;MATHEMATICAL BOLD SCRIPT CAPITAL N;Lu;0;L;<font> 004E;;;;N;;;;;
+1D4DE;MATHEMATICAL BOLD SCRIPT CAPITAL O;Lu;0;L;<font> 004F;;;;N;;;;;
+1D4DF;MATHEMATICAL BOLD SCRIPT CAPITAL P;Lu;0;L;<font> 0050;;;;N;;;;;
+1D4E0;MATHEMATICAL BOLD SCRIPT CAPITAL Q;Lu;0;L;<font> 0051;;;;N;;;;;
+1D4E1;MATHEMATICAL BOLD SCRIPT CAPITAL R;Lu;0;L;<font> 0052;;;;N;;;;;
+1D4E2;MATHEMATICAL BOLD SCRIPT CAPITAL S;Lu;0;L;<font> 0053;;;;N;;;;;
+1D4E3;MATHEMATICAL BOLD SCRIPT CAPITAL T;Lu;0;L;<font> 0054;;;;N;;;;;
+1D4E4;MATHEMATICAL BOLD SCRIPT CAPITAL U;Lu;0;L;<font> 0055;;;;N;;;;;
+1D4E5;MATHEMATICAL BOLD SCRIPT CAPITAL V;Lu;0;L;<font> 0056;;;;N;;;;;
+1D4E6;MATHEMATICAL BOLD SCRIPT CAPITAL W;Lu;0;L;<font> 0057;;;;N;;;;;
+1D4E7;MATHEMATICAL BOLD SCRIPT CAPITAL X;Lu;0;L;<font> 0058;;;;N;;;;;
+1D4E8;MATHEMATICAL BOLD SCRIPT CAPITAL Y;Lu;0;L;<font> 0059;;;;N;;;;;
+1D4E9;MATHEMATICAL BOLD SCRIPT CAPITAL Z;Lu;0;L;<font> 005A;;;;N;;;;;
+1D4EA;MATHEMATICAL BOLD SCRIPT SMALL A;Ll;0;L;<font> 0061;;;;N;;;;;
+1D4EB;MATHEMATICAL BOLD SCRIPT SMALL B;Ll;0;L;<font> 0062;;;;N;;;;;
+1D4EC;MATHEMATICAL BOLD SCRIPT SMALL C;Ll;0;L;<font> 0063;;;;N;;;;;
+1D4ED;MATHEMATICAL BOLD SCRIPT SMALL D;Ll;0;L;<font> 0064;;;;N;;;;;
+1D4EE;MATHEMATICAL BOLD SCRIPT SMALL E;Ll;0;L;<font> 0065;;;;N;;;;;
+1D4EF;MATHEMATICAL BOLD SCRIPT SMALL F;Ll;0;L;<font> 0066;;;;N;;;;;
+1D4F0;MATHEMATICAL BOLD SCRIPT SMALL G;Ll;0;L;<font> 0067;;;;N;;;;;
+1D4F1;MATHEMATICAL BOLD SCRIPT SMALL H;Ll;0;L;<font> 0068;;;;N;;;;;
+1D4F2;MATHEMATICAL BOLD SCRIPT SMALL I;Ll;0;L;<font> 0069;;;;N;;;;;
+1D4F3;MATHEMATICAL BOLD SCRIPT SMALL J;Ll;0;L;<font> 006A;;;;N;;;;;
+1D4F4;MATHEMATICAL BOLD SCRIPT SMALL K;Ll;0;L;<font> 006B;;;;N;;;;;
+1D4F5;MATHEMATICAL BOLD SCRIPT SMALL L;Ll;0;L;<font> 006C;;;;N;;;;;
+1D4F6;MATHEMATICAL BOLD SCRIPT SMALL M;Ll;0;L;<font> 006D;;;;N;;;;;
+1D4F7;MATHEMATICAL BOLD SCRIPT SMALL N;Ll;0;L;<font> 006E;;;;N;;;;;
+1D4F8;MATHEMATICAL BOLD SCRIPT SMALL O;Ll;0;L;<font> 006F;;;;N;;;;;
+1D4F9;MATHEMATICAL BOLD SCRIPT SMALL P;Ll;0;L;<font> 0070;;;;N;;;;;
+1D4FA;MATHEMATICAL BOLD SCRIPT SMALL Q;Ll;0;L;<font> 0071;;;;N;;;;;
+1D4FB;MATHEMATICAL BOLD SCRIPT SMALL R;Ll;0;L;<font> 0072;;;;N;;;;;
+1D4FC;MATHEMATICAL BOLD SCRIPT SMALL S;Ll;0;L;<font> 0073;;;;N;;;;;
+1D4FD;MATHEMATICAL BOLD SCRIPT SMALL T;Ll;0;L;<font> 0074;;;;N;;;;;
+1D4FE;MATHEMATICAL BOLD SCRIPT SMALL U;Ll;0;L;<font> 0075;;;;N;;;;;
+1D4FF;MATHEMATICAL BOLD SCRIPT SMALL V;Ll;0;L;<font> 0076;;;;N;;;;;
+1D500;MATHEMATICAL BOLD SCRIPT SMALL W;Ll;0;L;<font> 0077;;;;N;;;;;
+1D501;MATHEMATICAL BOLD SCRIPT SMALL X;Ll;0;L;<font> 0078;;;;N;;;;;
+1D502;MATHEMATICAL BOLD SCRIPT SMALL Y;Ll;0;L;<font> 0079;;;;N;;;;;
+1D503;MATHEMATICAL BOLD SCRIPT SMALL Z;Ll;0;L;<font> 007A;;;;N;;;;;
+1D504;MATHEMATICAL FRAKTUR CAPITAL A;Lu;0;L;<font> 0041;;;;N;;;;;
+1D505;MATHEMATICAL FRAKTUR CAPITAL B;Lu;0;L;<font> 0042;;;;N;;;;;
+1D507;MATHEMATICAL FRAKTUR CAPITAL D;Lu;0;L;<font> 0044;;;;N;;;;;
+1D508;MATHEMATICAL FRAKTUR CAPITAL E;Lu;0;L;<font> 0045;;;;N;;;;;
+1D509;MATHEMATICAL FRAKTUR CAPITAL F;Lu;0;L;<font> 0046;;;;N;;;;;
+1D50A;MATHEMATICAL FRAKTUR CAPITAL G;Lu;0;L;<font> 0047;;;;N;;;;;
+1D50D;MATHEMATICAL FRAKTUR CAPITAL J;Lu;0;L;<font> 004A;;;;N;;;;;
+1D50E;MATHEMATICAL FRAKTUR CAPITAL K;Lu;0;L;<font> 004B;;;;N;;;;;
+1D50F;MATHEMATICAL FRAKTUR CAPITAL L;Lu;0;L;<font> 004C;;;;N;;;;;
+1D510;MATHEMATICAL FRAKTUR CAPITAL M;Lu;0;L;<font> 004D;;;;N;;;;;
+1D511;MATHEMATICAL FRAKTUR CAPITAL N;Lu;0;L;<font> 004E;;;;N;;;;;
+1D512;MATHEMATICAL FRAKTUR CAPITAL O;Lu;0;L;<font> 004F;;;;N;;;;;
+1D513;MATHEMATICAL FRAKTUR CAPITAL P;Lu;0;L;<font> 0050;;;;N;;;;;
+1D514;MATHEMATICAL FRAKTUR CAPITAL Q;Lu;0;L;<font> 0051;;;;N;;;;;
+1D516;MATHEMATICAL FRAKTUR CAPITAL S;Lu;0;L;<font> 0053;;;;N;;;;;
+1D517;MATHEMATICAL FRAKTUR CAPITAL T;Lu;0;L;<font> 0054;;;;N;;;;;
+1D518;MATHEMATICAL FRAKTUR CAPITAL U;Lu;0;L;<font> 0055;;;;N;;;;;
+1D519;MATHEMATICAL FRAKTUR CAPITAL V;Lu;0;L;<font> 0056;;;;N;;;;;
+1D51A;MATHEMATICAL FRAKTUR CAPITAL W;Lu;0;L;<font> 0057;;;;N;;;;;
+1D51B;MATHEMATICAL FRAKTUR CAPITAL X;Lu;0;L;<font> 0058;;;;N;;;;;
+1D51C;MATHEMATICAL FRAKTUR CAPITAL Y;Lu;0;L;<font> 0059;;;;N;;;;;
+1D51E;MATHEMATICAL FRAKTUR SMALL A;Ll;0;L;<font> 0061;;;;N;;;;;
+1D51F;MATHEMATICAL FRAKTUR SMALL B;Ll;0;L;<font> 0062;;;;N;;;;;
+1D520;MATHEMATICAL FRAKTUR SMALL C;Ll;0;L;<font> 0063;;;;N;;;;;
+1D521;MATHEMATICAL FRAKTUR SMALL D;Ll;0;L;<font> 0064;;;;N;;;;;
+1D522;MATHEMATICAL FRAKTUR SMALL E;Ll;0;L;<font> 0065;;;;N;;;;;
+1D523;MATHEMATICAL FRAKTUR SMALL F;Ll;0;L;<font> 0066;;;;N;;;;;
+1D524;MATHEMATICAL FRAKTUR SMALL G;Ll;0;L;<font> 0067;;;;N;;;;;
+1D525;MATHEMATICAL FRAKTUR SMALL H;Ll;0;L;<font> 0068;;;;N;;;;;
+1D526;MATHEMATICAL FRAKTUR SMALL I;Ll;0;L;<font> 0069;;;;N;;;;;
+1D527;MATHEMATICAL FRAKTUR SMALL J;Ll;0;L;<font> 006A;;;;N;;;;;
+1D528;MATHEMATICAL FRAKTUR SMALL K;Ll;0;L;<font> 006B;;;;N;;;;;
+1D529;MATHEMATICAL FRAKTUR SMALL L;Ll;0;L;<font> 006C;;;;N;;;;;
+1D52A;MATHEMATICAL FRAKTUR SMALL M;Ll;0;L;<font> 006D;;;;N;;;;;
+1D52B;MATHEMATICAL FRAKTUR SMALL N;Ll;0;L;<font> 006E;;;;N;;;;;
+1D52C;MATHEMATICAL FRAKTUR SMALL O;Ll;0;L;<font> 006F;;;;N;;;;;
+1D52D;MATHEMATICAL FRAKTUR SMALL P;Ll;0;L;<font> 0070;;;;N;;;;;
+1D52E;MATHEMATICAL FRAKTUR SMALL Q;Ll;0;L;<font> 0071;;;;N;;;;;
+1D52F;MATHEMATICAL FRAKTUR SMALL R;Ll;0;L;<font> 0072;;;;N;;;;;
+1D530;MATHEMATICAL FRAKTUR SMALL S;Ll;0;L;<font> 0073;;;;N;;;;;
+1D531;MATHEMATICAL FRAKTUR SMALL T;Ll;0;L;<font> 0074;;;;N;;;;;
+1D532;MATHEMATICAL FRAKTUR SMALL U;Ll;0;L;<font> 0075;;;;N;;;;;
+1D533;MATHEMATICAL FRAKTUR SMALL V;Ll;0;L;<font> 0076;;;;N;;;;;
+1D534;MATHEMATICAL FRAKTUR SMALL W;Ll;0;L;<font> 0077;;;;N;;;;;
+1D535;MATHEMATICAL FRAKTUR SMALL X;Ll;0;L;<font> 0078;;;;N;;;;;
+1D536;MATHEMATICAL FRAKTUR SMALL Y;Ll;0;L;<font> 0079;;;;N;;;;;
+1D537;MATHEMATICAL FRAKTUR SMALL Z;Ll;0;L;<font> 007A;;;;N;;;;;
+1D538;MATHEMATICAL DOUBLE-STRUCK CAPITAL A;Lu;0;L;<font> 0041;;;;N;;;;;
+1D539;MATHEMATICAL DOUBLE-STRUCK CAPITAL B;Lu;0;L;<font> 0042;;;;N;;;;;
+1D53B;MATHEMATICAL DOUBLE-STRUCK CAPITAL D;Lu;0;L;<font> 0044;;;;N;;;;;
+1D53C;MATHEMATICAL DOUBLE-STRUCK CAPITAL E;Lu;0;L;<font> 0045;;;;N;;;;;
+1D53D;MATHEMATICAL DOUBLE-STRUCK CAPITAL F;Lu;0;L;<font> 0046;;;;N;;;;;
+1D53E;MATHEMATICAL DOUBLE-STRUCK CAPITAL G;Lu;0;L;<font> 0047;;;;N;;;;;
+1D540;MATHEMATICAL DOUBLE-STRUCK CAPITAL I;Lu;0;L;<font> 0049;;;;N;;;;;
+1D541;MATHEMATICAL DOUBLE-STRUCK CAPITAL J;Lu;0;L;<font> 004A;;;;N;;;;;
+1D542;MATHEMATICAL DOUBLE-STRUCK CAPITAL K;Lu;0;L;<font> 004B;;;;N;;;;;
+1D543;MATHEMATICAL DOUBLE-STRUCK CAPITAL L;Lu;0;L;<font> 004C;;;;N;;;;;
+1D544;MATHEMATICAL DOUBLE-STRUCK CAPITAL M;Lu;0;L;<font> 004D;;;;N;;;;;
+1D546;MATHEMATICAL DOUBLE-STRUCK CAPITAL O;Lu;0;L;<font> 004F;;;;N;;;;;
+1D54A;MATHEMATICAL DOUBLE-STRUCK CAPITAL S;Lu;0;L;<font> 0053;;;;N;;;;;
+1D54B;MATHEMATICAL DOUBLE-STRUCK CAPITAL T;Lu;0;L;<font> 0054;;;;N;;;;;
+1D54C;MATHEMATICAL DOUBLE-STRUCK CAPITAL U;Lu;0;L;<font> 0055;;;;N;;;;;
+1D54D;MATHEMATICAL DOUBLE-STRUCK CAPITAL V;Lu;0;L;<font> 0056;;;;N;;;;;
+1D54E;MATHEMATICAL DOUBLE-STRUCK CAPITAL W;Lu;0;L;<font> 0057;;;;N;;;;;
+1D54F;MATHEMATICAL DOUBLE-STRUCK CAPITAL X;Lu;0;L;<font> 0058;;;;N;;;;;
+1D550;MATHEMATICAL DOUBLE-STRUCK CAPITAL Y;Lu;0;L;<font> 0059;;;;N;;;;;
+1D552;MATHEMATICAL DOUBLE-STRUCK SMALL A;Ll;0;L;<font> 0061;;;;N;;;;;
+1D553;MATHEMATICAL DOUBLE-STRUCK SMALL B;Ll;0;L;<font> 0062;;;;N;;;;;
+1D554;MATHEMATICAL DOUBLE-STRUCK SMALL C;Ll;0;L;<font> 0063;;;;N;;;;;
+1D555;MATHEMATICAL DOUBLE-STRUCK SMALL D;Ll;0;L;<font> 0064;;;;N;;;;;
+1D556;MATHEMATICAL DOUBLE-STRUCK SMALL E;Ll;0;L;<font> 0065;;;;N;;;;;
+1D557;MATHEMATICAL DOUBLE-STRUCK SMALL F;Ll;0;L;<font> 0066;;;;N;;;;;
+1D558;MATHEMATICAL DOUBLE-STRUCK SMALL G;Ll;0;L;<font> 0067;;;;N;;;;;
+1D559;MATHEMATICAL DOUBLE-STRUCK SMALL H;Ll;0;L;<font> 0068;;;;N;;;;;
+1D55A;MATHEMATICAL DOUBLE-STRUCK SMALL I;Ll;0;L;<font> 0069;;;;N;;;;;
+1D55B;MATHEMATICAL DOUBLE-STRUCK SMALL J;Ll;0;L;<font> 006A;;;;N;;;;;
+1D55C;MATHEMATICAL DOUBLE-STRUCK SMALL K;Ll;0;L;<font> 006B;;;;N;;;;;
+1D55D;MATHEMATICAL DOUBLE-STRUCK SMALL L;Ll;0;L;<font> 006C;;;;N;;;;;
+1D55E;MATHEMATICAL DOUBLE-STRUCK SMALL M;Ll;0;L;<font> 006D;;;;N;;;;;
+1D55F;MATHEMATICAL DOUBLE-STRUCK SMALL N;Ll;0;L;<font> 006E;;;;N;;;;;
+1D560;MATHEMATICAL DOUBLE-STRUCK SMALL O;Ll;0;L;<font> 006F;;;;N;;;;;
+1D561;MATHEMATICAL DOUBLE-STRUCK SMALL P;Ll;0;L;<font> 0070;;;;N;;;;;
+1D562;MATHEMATICAL DOUBLE-STRUCK SMALL Q;Ll;0;L;<font> 0071;;;;N;;;;;
+1D563;MATHEMATICAL DOUBLE-STRUCK SMALL R;Ll;0;L;<font> 0072;;;;N;;;;;
+1D564;MATHEMATICAL DOUBLE-STRUCK SMALL S;Ll;0;L;<font> 0073;;;;N;;;;;
+1D565;MATHEMATICAL DOUBLE-STRUCK SMALL T;Ll;0;L;<font> 0074;;;;N;;;;;
+1D566;MATHEMATICAL DOUBLE-STRUCK SMALL U;Ll;0;L;<font> 0075;;;;N;;;;;
+1D567;MATHEMATICAL DOUBLE-STRUCK SMALL V;Ll;0;L;<font> 0076;;;;N;;;;;
+1D568;MATHEMATICAL DOUBLE-STRUCK SMALL W;Ll;0;L;<font> 0077;;;;N;;;;;
+1D569;MATHEMATICAL DOUBLE-STRUCK SMALL X;Ll;0;L;<font> 0078;;;;N;;;;;
+1D56A;MATHEMATICAL DOUBLE-STRUCK SMALL Y;Ll;0;L;<font> 0079;;;;N;;;;;
+1D56B;MATHEMATICAL DOUBLE-STRUCK SMALL Z;Ll;0;L;<font> 007A;;;;N;;;;;
+1D56C;MATHEMATICAL BOLD FRAKTUR CAPITAL A;Lu;0;L;<font> 0041;;;;N;;;;;
+1D56D;MATHEMATICAL BOLD FRAKTUR CAPITAL B;Lu;0;L;<font> 0042;;;;N;;;;;
+1D56E;MATHEMATICAL BOLD FRAKTUR CAPITAL C;Lu;0;L;<font> 0043;;;;N;;;;;
+1D56F;MATHEMATICAL BOLD FRAKTUR CAPITAL D;Lu;0;L;<font> 0044;;;;N;;;;;
+1D570;MATHEMATICAL BOLD FRAKTUR CAPITAL E;Lu;0;L;<font> 0045;;;;N;;;;;
+1D571;MATHEMATICAL BOLD FRAKTUR CAPITAL F;Lu;0;L;<font> 0046;;;;N;;;;;
+1D572;MATHEMATICAL BOLD FRAKTUR CAPITAL G;Lu;0;L;<font> 0047;;;;N;;;;;
+1D573;MATHEMATICAL BOLD FRAKTUR CAPITAL H;Lu;0;L;<font> 0048;;;;N;;;;;
+1D574;MATHEMATICAL BOLD FRAKTUR CAPITAL I;Lu;0;L;<font> 0049;;;;N;;;;;
+1D575;MATHEMATICAL BOLD FRAKTUR CAPITAL J;Lu;0;L;<font> 004A;;;;N;;;;;
+1D576;MATHEMATICAL BOLD FRAKTUR CAPITAL K;Lu;0;L;<font> 004B;;;;N;;;;;
+1D577;MATHEMATICAL BOLD FRAKTUR CAPITAL L;Lu;0;L;<font> 004C;;;;N;;;;;
+1D578;MATHEMATICAL BOLD FRAKTUR CAPITAL M;Lu;0;L;<font> 004D;;;;N;;;;;
+1D579;MATHEMATICAL BOLD FRAKTUR CAPITAL N;Lu;0;L;<font> 004E;;;;N;;;;;
+1D57A;MATHEMATICAL BOLD FRAKTUR CAPITAL O;Lu;0;L;<font> 004F;;;;N;;;;;
+1D57B;MATHEMATICAL BOLD FRAKTUR CAPITAL P;Lu;0;L;<font> 0050;;;;N;;;;;
+1D57C;MATHEMATICAL BOLD FRAKTUR CAPITAL Q;Lu;0;L;<font> 0051;;;;N;;;;;
+1D57D;MATHEMATICAL BOLD FRAKTUR CAPITAL R;Lu;0;L;<font> 0052;;;;N;;;;;
+1D57E;MATHEMATICAL BOLD FRAKTUR CAPITAL S;Lu;0;L;<font> 0053;;;;N;;;;;
+1D57F;MATHEMATICAL BOLD FRAKTUR CAPITAL T;Lu;0;L;<font> 0054;;;;N;;;;;
+1D580;MATHEMATICAL BOLD FRAKTUR CAPITAL U;Lu;0;L;<font> 0055;;;;N;;;;;
+1D581;MATHEMATICAL BOLD FRAKTUR CAPITAL V;Lu;0;L;<font> 0056;;;;N;;;;;
+1D582;MATHEMATICAL BOLD FRAKTUR CAPITAL W;Lu;0;L;<font> 0057;;;;N;;;;;
+1D583;MATHEMATICAL BOLD FRAKTUR CAPITAL X;Lu;0;L;<font> 0058;;;;N;;;;;
+1D584;MATHEMATICAL BOLD FRAKTUR CAPITAL Y;Lu;0;L;<font> 0059;;;;N;;;;;
+1D585;MATHEMATICAL BOLD FRAKTUR CAPITAL Z;Lu;0;L;<font> 005A;;;;N;;;;;
+1D586;MATHEMATICAL BOLD FRAKTUR SMALL A;Ll;0;L;<font> 0061;;;;N;;;;;
+1D587;MATHEMATICAL BOLD FRAKTUR SMALL B;Ll;0;L;<font> 0062;;;;N;;;;;
+1D588;MATHEMATICAL BOLD FRAKTUR SMALL C;Ll;0;L;<font> 0063;;;;N;;;;;
+1D589;MATHEMATICAL BOLD FRAKTUR SMALL D;Ll;0;L;<font> 0064;;;;N;;;;;
+1D58A;MATHEMATICAL BOLD FRAKTUR SMALL E;Ll;0;L;<font> 0065;;;;N;;;;;
+1D58B;MATHEMATICAL BOLD FRAKTUR SMALL F;Ll;0;L;<font> 0066;;;;N;;;;;
+1D58C;MATHEMATICAL BOLD FRAKTUR SMALL G;Ll;0;L;<font> 0067;;;;N;;;;;
+1D58D;MATHEMATICAL BOLD FRAKTUR SMALL H;Ll;0;L;<font> 0068;;;;N;;;;;
+1D58E;MATHEMATICAL BOLD FRAKTUR SMALL I;Ll;0;L;<font> 0069;;;;N;;;;;
+1D58F;MATHEMATICAL BOLD FRAKTUR SMALL J;Ll;0;L;<font> 006A;;;;N;;;;;
+1D590;MATHEMATICAL BOLD FRAKTUR SMALL K;Ll;0;L;<font> 006B;;;;N;;;;;
+1D591;MATHEMATICAL BOLD FRAKTUR SMALL L;Ll;0;L;<font> 006C;;;;N;;;;;
+1D592;MATHEMATICAL BOLD FRAKTUR SMALL M;Ll;0;L;<font> 006D;;;;N;;;;;
+1D593;MATHEMATICAL BOLD FRAKTUR SMALL N;Ll;0;L;<font> 006E;;;;N;;;;;
+1D594;MATHEMATICAL BOLD FRAKTUR SMALL O;Ll;0;L;<font> 006F;;;;N;;;;;
+1D595;MATHEMATICAL BOLD FRAKTUR SMALL P;Ll;0;L;<font> 0070;;;;N;;;;;
+1D596;MATHEMATICAL BOLD FRAKTUR SMALL Q;Ll;0;L;<font> 0071;;;;N;;;;;
+1D597;MATHEMATICAL BOLD FRAKTUR SMALL R;Ll;0;L;<font> 0072;;;;N;;;;;
+1D598;MATHEMATICAL BOLD FRAKTUR SMALL S;Ll;0;L;<font> 0073;;;;N;;;;;
+1D599;MATHEMATICAL BOLD FRAKTUR SMALL T;Ll;0;L;<font> 0074;;;;N;;;;;
+1D59A;MATHEMATICAL BOLD FRAKTUR SMALL U;Ll;0;L;<font> 0075;;;;N;;;;;
+1D59B;MATHEMATICAL BOLD FRAKTUR SMALL V;Ll;0;L;<font> 0076;;;;N;;;;;
+1D59C;MATHEMATICAL BOLD FRAKTUR SMALL W;Ll;0;L;<font> 0077;;;;N;;;;;
+1D59D;MATHEMATICAL BOLD FRAKTUR SMALL X;Ll;0;L;<font> 0078;;;;N;;;;;
+1D59E;MATHEMATICAL BOLD FRAKTUR SMALL Y;Ll;0;L;<font> 0079;;;;N;;;;;
+1D59F;MATHEMATICAL BOLD FRAKTUR SMALL Z;Ll;0;L;<font> 007A;;;;N;;;;;
+1D5A0;MATHEMATICAL SANS-SERIF CAPITAL A;Lu;0;L;<font> 0041;;;;N;;;;;
+1D5A1;MATHEMATICAL SANS-SERIF CAPITAL B;Lu;0;L;<font> 0042;;;;N;;;;;
+1D5A2;MATHEMATICAL SANS-SERIF CAPITAL C;Lu;0;L;<font> 0043;;;;N;;;;;
+1D5A3;MATHEMATICAL SANS-SERIF CAPITAL D;Lu;0;L;<font> 0044;;;;N;;;;;
+1D5A4;MATHEMATICAL SANS-SERIF CAPITAL E;Lu;0;L;<font> 0045;;;;N;;;;;
+1D5A5;MATHEMATICAL SANS-SERIF CAPITAL F;Lu;0;L;<font> 0046;;;;N;;;;;
+1D5A6;MATHEMATICAL SANS-SERIF CAPITAL G;Lu;0;L;<font> 0047;;;;N;;;;;
+1D5A7;MATHEMATICAL SANS-SERIF CAPITAL H;Lu;0;L;<font> 0048;;;;N;;;;;
+1D5A8;MATHEMATICAL SANS-SERIF CAPITAL I;Lu;0;L;<font> 0049;;;;N;;;;;
+1D5A9;MATHEMATICAL SANS-SERIF CAPITAL J;Lu;0;L;<font> 004A;;;;N;;;;;
+1D5AA;MATHEMATICAL SANS-SERIF CAPITAL K;Lu;0;L;<font> 004B;;;;N;;;;;
+1D5AB;MATHEMATICAL SANS-SERIF CAPITAL L;Lu;0;L;<font> 004C;;;;N;;;;;
+1D5AC;MATHEMATICAL SANS-SERIF CAPITAL M;Lu;0;L;<font> 004D;;;;N;;;;;
+1D5AD;MATHEMATICAL SANS-SERIF CAPITAL N;Lu;0;L;<font> 004E;;;;N;;;;;
+1D5AE;MATHEMATICAL SANS-SERIF CAPITAL O;Lu;0;L;<font> 004F;;;;N;;;;;
+1D5AF;MATHEMATICAL SANS-SERIF CAPITAL P;Lu;0;L;<font> 0050;;;;N;;;;;
+1D5B0;MATHEMATICAL SANS-SERIF CAPITAL Q;Lu;0;L;<font> 0051;;;;N;;;;;
+1D5B1;MATHEMATICAL SANS-SERIF CAPITAL R;Lu;0;L;<font> 0052;;;;N;;;;;
+1D5B2;MATHEMATICAL SANS-SERIF CAPITAL S;Lu;0;L;<font> 0053;;;;N;;;;;
+1D5B3;MATHEMATICAL SANS-SERIF CAPITAL T;Lu;0;L;<font> 0054;;;;N;;;;;
+1D5B4;MATHEMATICAL SANS-SERIF CAPITAL U;Lu;0;L;<font> 0055;;;;N;;;;;
+1D5B5;MATHEMATICAL SANS-SERIF CAPITAL V;Lu;0;L;<font> 0056;;;;N;;;;;
+1D5B6;MATHEMATICAL SANS-SERIF CAPITAL W;Lu;0;L;<font> 0057;;;;N;;;;;
+1D5B7;MATHEMATICAL SANS-SERIF CAPITAL X;Lu;0;L;<font> 0058;;;;N;;;;;
+1D5B8;MATHEMATICAL SANS-SERIF CAPITAL Y;Lu;0;L;<font> 0059;;;;N;;;;;
+1D5B9;MATHEMATICAL SANS-SERIF CAPITAL Z;Lu;0;L;<font> 005A;;;;N;;;;;
+1D5BA;MATHEMATICAL SANS-SERIF SMALL A;Ll;0;L;<font> 0061;;;;N;;;;;
+1D5BB;MATHEMATICAL SANS-SERIF SMALL B;Ll;0;L;<font> 0062;;;;N;;;;;
+1D5BC;MATHEMATICAL SANS-SERIF SMALL C;Ll;0;L;<font> 0063;;;;N;;;;;
+1D5BD;MATHEMATICAL SANS-SERIF SMALL D;Ll;0;L;<font> 0064;;;;N;;;;;
+1D5BE;MATHEMATICAL SANS-SERIF SMALL E;Ll;0;L;<font> 0065;;;;N;;;;;
+1D5BF;MATHEMATICAL SANS-SERIF SMALL F;Ll;0;L;<font> 0066;;;;N;;;;;
+1D5C0;MATHEMATICAL SANS-SERIF SMALL G;Ll;0;L;<font> 0067;;;;N;;;;;
+1D5C1;MATHEMATICAL SANS-SERIF SMALL H;Ll;0;L;<font> 0068;;;;N;;;;;
+1D5C2;MATHEMATICAL SANS-SERIF SMALL I;Ll;0;L;<font> 0069;;;;N;;;;;
+1D5C3;MATHEMATICAL SANS-SERIF SMALL J;Ll;0;L;<font> 006A;;;;N;;;;;
+1D5C4;MATHEMATICAL SANS-SERIF SMALL K;Ll;0;L;<font> 006B;;;;N;;;;;
+1D5C5;MATHEMATICAL SANS-SERIF SMALL L;Ll;0;L;<font> 006C;;;;N;;;;;
+1D5C6;MATHEMATICAL SANS-SERIF SMALL M;Ll;0;L;<font> 006D;;;;N;;;;;
+1D5C7;MATHEMATICAL SANS-SERIF SMALL N;Ll;0;L;<font> 006E;;;;N;;;;;
+1D5C8;MATHEMATICAL SANS-SERIF SMALL O;Ll;0;L;<font> 006F;;;;N;;;;;
+1D5C9;MATHEMATICAL SANS-SERIF SMALL P;Ll;0;L;<font> 0070;;;;N;;;;;
+1D5CA;MATHEMATICAL SANS-SERIF SMALL Q;Ll;0;L;<font> 0071;;;;N;;;;;
+1D5CB;MATHEMATICAL SANS-SERIF SMALL R;Ll;0;L;<font> 0072;;;;N;;;;;
+1D5CC;MATHEMATICAL SANS-SERIF SMALL S;Ll;0;L;<font> 0073;;;;N;;;;;
+1D5CD;MATHEMATICAL SANS-SERIF SMALL T;Ll;0;L;<font> 0074;;;;N;;;;;
+1D5CE;MATHEMATICAL SANS-SERIF SMALL U;Ll;0;L;<font> 0075;;;;N;;;;;
+1D5CF;MATHEMATICAL SANS-SERIF SMALL V;Ll;0;L;<font> 0076;;;;N;;;;;
+1D5D0;MATHEMATICAL SANS-SERIF SMALL W;Ll;0;L;<font> 0077;;;;N;;;;;
+1D5D1;MATHEMATICAL SANS-SERIF SMALL X;Ll;0;L;<font> 0078;;;;N;;;;;
+1D5D2;MATHEMATICAL SANS-SERIF SMALL Y;Ll;0;L;<font> 0079;;;;N;;;;;
+1D5D3;MATHEMATICAL SANS-SERIF SMALL Z;Ll;0;L;<font> 007A;;;;N;;;;;
+1D5D4;MATHEMATICAL SANS-SERIF BOLD CAPITAL A;Lu;0;L;<font> 0041;;;;N;;;;;
+1D5D5;MATHEMATICAL SANS-SERIF BOLD CAPITAL B;Lu;0;L;<font> 0042;;;;N;;;;;
+1D5D6;MATHEMATICAL SANS-SERIF BOLD CAPITAL C;Lu;0;L;<font> 0043;;;;N;;;;;
+1D5D7;MATHEMATICAL SANS-SERIF BOLD CAPITAL D;Lu;0;L;<font> 0044;;;;N;;;;;
+1D5D8;MATHEMATICAL SANS-SERIF BOLD CAPITAL E;Lu;0;L;<font> 0045;;;;N;;;;;
+1D5D9;MATHEMATICAL SANS-SERIF BOLD CAPITAL F;Lu;0;L;<font> 0046;;;;N;;;;;
+1D5DA;MATHEMATICAL SANS-SERIF BOLD CAPITAL G;Lu;0;L;<font> 0047;;;;N;;;;;
+1D5DB;MATHEMATICAL SANS-SERIF BOLD CAPITAL H;Lu;0;L;<font> 0048;;;;N;;;;;
+1D5DC;MATHEMATICAL SANS-SERIF BOLD CAPITAL I;Lu;0;L;<font> 0049;;;;N;;;;;
+1D5DD;MATHEMATICAL SANS-SERIF BOLD CAPITAL J;Lu;0;L;<font> 004A;;;;N;;;;;
+1D5DE;MATHEMATICAL SANS-SERIF BOLD CAPITAL K;Lu;0;L;<font> 004B;;;;N;;;;;
+1D5DF;MATHEMATICAL SANS-SERIF BOLD CAPITAL L;Lu;0;L;<font> 004C;;;;N;;;;;
+1D5E0;MATHEMATICAL SANS-SERIF BOLD CAPITAL M;Lu;0;L;<font> 004D;;;;N;;;;;
+1D5E1;MATHEMATICAL SANS-SERIF BOLD CAPITAL N;Lu;0;L;<font> 004E;;;;N;;;;;
+1D5E2;MATHEMATICAL SANS-SERIF BOLD CAPITAL O;Lu;0;L;<font> 004F;;;;N;;;;;
+1D5E3;MATHEMATICAL SANS-SERIF BOLD CAPITAL P;Lu;0;L;<font> 0050;;;;N;;;;;
+1D5E4;MATHEMATICAL SANS-SERIF BOLD CAPITAL Q;Lu;0;L;<font> 0051;;;;N;;;;;
+1D5E5;MATHEMATICAL SANS-SERIF BOLD CAPITAL R;Lu;0;L;<font> 0052;;;;N;;;;;
+1D5E6;MATHEMATICAL SANS-SERIF BOLD CAPITAL S;Lu;0;L;<font> 0053;;;;N;;;;;
+1D5E7;MATHEMATICAL SANS-SERIF BOLD CAPITAL T;Lu;0;L;<font> 0054;;;;N;;;;;
+1D5E8;MATHEMATICAL SANS-SERIF BOLD CAPITAL U;Lu;0;L;<font> 0055;;;;N;;;;;
+1D5E9;MATHEMATICAL SANS-SERIF BOLD CAPITAL V;Lu;0;L;<font> 0056;;;;N;;;;;
+1D5EA;MATHEMATICAL SANS-SERIF BOLD CAPITAL W;Lu;0;L;<font> 0057;;;;N;;;;;
+1D5EB;MATHEMATICAL SANS-SERIF BOLD CAPITAL X;Lu;0;L;<font> 0058;;;;N;;;;;
+1D5EC;MATHEMATICAL SANS-SERIF BOLD CAPITAL Y;Lu;0;L;<font> 0059;;;;N;;;;;
+1D5ED;MATHEMATICAL SANS-SERIF BOLD CAPITAL Z;Lu;0;L;<font> 005A;;;;N;;;;;
+1D5EE;MATHEMATICAL SANS-SERIF BOLD SMALL A;Ll;0;L;<font> 0061;;;;N;;;;;
+1D5EF;MATHEMATICAL SANS-SERIF BOLD SMALL B;Ll;0;L;<font> 0062;;;;N;;;;;
+1D5F0;MATHEMATICAL SANS-SERIF BOLD SMALL C;Ll;0;L;<font> 0063;;;;N;;;;;
+1D5F1;MATHEMATICAL SANS-SERIF BOLD SMALL D;Ll;0;L;<font> 0064;;;;N;;;;;
+1D5F2;MATHEMATICAL SANS-SERIF BOLD SMALL E;Ll;0;L;<font> 0065;;;;N;;;;;
+1D5F3;MATHEMATICAL SANS-SERIF BOLD SMALL F;Ll;0;L;<font> 0066;;;;N;;;;;
+1D5F4;MATHEMATICAL SANS-SERIF BOLD SMALL G;Ll;0;L;<font> 0067;;;;N;;;;;
+1D5F5;MATHEMATICAL SANS-SERIF BOLD SMALL H;Ll;0;L;<font> 0068;;;;N;;;;;
+1D5F6;MATHEMATICAL SANS-SERIF BOLD SMALL I;Ll;0;L;<font> 0069;;;;N;;;;;
+1D5F7;MATHEMATICAL SANS-SERIF BOLD SMALL J;Ll;0;L;<font> 006A;;;;N;;;;;
+1D5F8;MATHEMATICAL SANS-SERIF BOLD SMALL K;Ll;0;L;<font> 006B;;;;N;;;;;
+1D5F9;MATHEMATICAL SANS-SERIF BOLD SMALL L;Ll;0;L;<font> 006C;;;;N;;;;;
+1D5FA;MATHEMATICAL SANS-SERIF BOLD SMALL M;Ll;0;L;<font> 006D;;;;N;;;;;
+1D5FB;MATHEMATICAL SANS-SERIF BOLD SMALL N;Ll;0;L;<font> 006E;;;;N;;;;;
+1D5FC;MATHEMATICAL SANS-SERIF BOLD SMALL O;Ll;0;L;<font> 006F;;;;N;;;;;
+1D5FD;MATHEMATICAL SANS-SERIF BOLD SMALL P;Ll;0;L;<font> 0070;;;;N;;;;;
+1D5FE;MATHEMATICAL SANS-SERIF BOLD SMALL Q;Ll;0;L;<font> 0071;;;;N;;;;;
+1D5FF;MATHEMATICAL SANS-SERIF BOLD SMALL R;Ll;0;L;<font> 0072;;;;N;;;;;
+1D600;MATHEMATICAL SANS-SERIF BOLD SMALL S;Ll;0;L;<font> 0073;;;;N;;;;;
+1D601;MATHEMATICAL SANS-SERIF BOLD SMALL T;Ll;0;L;<font> 0074;;;;N;;;;;
+1D602;MATHEMATICAL SANS-SERIF BOLD SMALL U;Ll;0;L;<font> 0075;;;;N;;;;;
+1D603;MATHEMATICAL SANS-SERIF BOLD SMALL V;Ll;0;L;<font> 0076;;;;N;;;;;
+1D604;MATHEMATICAL SANS-SERIF BOLD SMALL W;Ll;0;L;<font> 0077;;;;N;;;;;
+1D605;MATHEMATICAL SANS-SERIF BOLD SMALL X;Ll;0;L;<font> 0078;;;;N;;;;;
+1D606;MATHEMATICAL SANS-SERIF BOLD SMALL Y;Ll;0;L;<font> 0079;;;;N;;;;;
+1D607;MATHEMATICAL SANS-SERIF BOLD SMALL Z;Ll;0;L;<font> 007A;;;;N;;;;;
+1D608;MATHEMATICAL SANS-SERIF ITALIC CAPITAL A;Lu;0;L;<font> 0041;;;;N;;;;;
+1D609;MATHEMATICAL SANS-SERIF ITALIC CAPITAL B;Lu;0;L;<font> 0042;;;;N;;;;;
+1D60A;MATHEMATICAL SANS-SERIF ITALIC CAPITAL C;Lu;0;L;<font> 0043;;;;N;;;;;
+1D60B;MATHEMATICAL SANS-SERIF ITALIC CAPITAL D;Lu;0;L;<font> 0044;;;;N;;;;;
+1D60C;MATHEMATICAL SANS-SERIF ITALIC CAPITAL E;Lu;0;L;<font> 0045;;;;N;;;;;
+1D60D;MATHEMATICAL SANS-SERIF ITALIC CAPITAL F;Lu;0;L;<font> 0046;;;;N;;;;;
+1D60E;MATHEMATICAL SANS-SERIF ITALIC CAPITAL G;Lu;0;L;<font> 0047;;;;N;;;;;
+1D60F;MATHEMATICAL SANS-SERIF ITALIC CAPITAL H;Lu;0;L;<font> 0048;;;;N;;;;;
+1D610;MATHEMATICAL SANS-SERIF ITALIC CAPITAL I;Lu;0;L;<font> 0049;;;;N;;;;;
+1D611;MATHEMATICAL SANS-SERIF ITALIC CAPITAL J;Lu;0;L;<font> 004A;;;;N;;;;;
+1D612;MATHEMATICAL SANS-SERIF ITALIC CAPITAL K;Lu;0;L;<font> 004B;;;;N;;;;;
+1D613;MATHEMATICAL SANS-SERIF ITALIC CAPITAL L;Lu;0;L;<font> 004C;;;;N;;;;;
+1D614;MATHEMATICAL SANS-SERIF ITALIC CAPITAL M;Lu;0;L;<font> 004D;;;;N;;;;;
+1D615;MATHEMATICAL SANS-SERIF ITALIC CAPITAL N;Lu;0;L;<font> 004E;;;;N;;;;;
+1D616;MATHEMATICAL SANS-SERIF ITALIC CAPITAL O;Lu;0;L;<font> 004F;;;;N;;;;;
+1D617;MATHEMATICAL SANS-SERIF ITALIC CAPITAL P;Lu;0;L;<font> 0050;;;;N;;;;;
+1D618;MATHEMATICAL SANS-SERIF ITALIC CAPITAL Q;Lu;0;L;<font> 0051;;;;N;;;;;
+1D619;MATHEMATICAL SANS-SERIF ITALIC CAPITAL R;Lu;0;L;<font> 0052;;;;N;;;;;
+1D61A;MATHEMATICAL SANS-SERIF ITALIC CAPITAL S;Lu;0;L;<font> 0053;;;;N;;;;;
+1D61B;MATHEMATICAL SANS-SERIF ITALIC CAPITAL T;Lu;0;L;<font> 0054;;;;N;;;;;
+1D61C;MATHEMATICAL SANS-SERIF ITALIC CAPITAL U;Lu;0;L;<font> 0055;;;;N;;;;;
+1D61D;MATHEMATICAL SANS-SERIF ITALIC CAPITAL V;Lu;0;L;<font> 0056;;;;N;;;;;
+1D61E;MATHEMATICAL SANS-SERIF ITALIC CAPITAL W;Lu;0;L;<font> 0057;;;;N;;;;;
+1D61F;MATHEMATICAL SANS-SERIF ITALIC CAPITAL X;Lu;0;L;<font> 0058;;;;N;;;;;
+1D620;MATHEMATICAL SANS-SERIF ITALIC CAPITAL Y;Lu;0;L;<font> 0059;;;;N;;;;;
+1D621;MATHEMATICAL SANS-SERIF ITALIC CAPITAL Z;Lu;0;L;<font> 005A;;;;N;;;;;
+1D622;MATHEMATICAL SANS-SERIF ITALIC SMALL A;Ll;0;L;<font> 0061;;;;N;;;;;
+1D623;MATHEMATICAL SANS-SERIF ITALIC SMALL B;Ll;0;L;<font> 0062;;;;N;;;;;
+1D624;MATHEMATICAL SANS-SERIF ITALIC SMALL C;Ll;0;L;<font> 0063;;;;N;;;;;
+1D625;MATHEMATICAL SANS-SERIF ITALIC SMALL D;Ll;0;L;<font> 0064;;;;N;;;;;
+1D626;MATHEMATICAL SANS-SERIF ITALIC SMALL E;Ll;0;L;<font> 0065;;;;N;;;;;
+1D627;MATHEMATICAL SANS-SERIF ITALIC SMALL F;Ll;0;L;<font> 0066;;;;N;;;;;
+1D628;MATHEMATICAL SANS-SERIF ITALIC SMALL G;Ll;0;L;<font> 0067;;;;N;;;;;
+1D629;MATHEMATICAL SANS-SERIF ITALIC SMALL H;Ll;0;L;<font> 0068;;;;N;;;;;
+1D62A;MATHEMATICAL SANS-SERIF ITALIC SMALL I;Ll;0;L;<font> 0069;;;;N;;;;;
+1D62B;MATHEMATICAL SANS-SERIF ITALIC SMALL J;Ll;0;L;<font> 006A;;;;N;;;;;
+1D62C;MATHEMATICAL SANS-SERIF ITALIC SMALL K;Ll;0;L;<font> 006B;;;;N;;;;;
+1D62D;MATHEMATICAL SANS-SERIF ITALIC SMALL L;Ll;0;L;<font> 006C;;;;N;;;;;
+1D62E;MATHEMATICAL SANS-SERIF ITALIC SMALL M;Ll;0;L;<font> 006D;;;;N;;;;;
+1D62F;MATHEMATICAL SANS-SERIF ITALIC SMALL N;Ll;0;L;<font> 006E;;;;N;;;;;
+1D630;MATHEMATICAL SANS-SERIF ITALIC SMALL O;Ll;0;L;<font> 006F;;;;N;;;;;
+1D631;MATHEMATICAL SANS-SERIF ITALIC SMALL P;Ll;0;L;<font> 0070;;;;N;;;;;
+1D632;MATHEMATICAL SANS-SERIF ITALIC SMALL Q;Ll;0;L;<font> 0071;;;;N;;;;;
+1D633;MATHEMATICAL SANS-SERIF ITALIC SMALL R;Ll;0;L;<font> 0072;;;;N;;;;;
+1D634;MATHEMATICAL SANS-SERIF ITALIC SMALL S;Ll;0;L;<font> 0073;;;;N;;;;;
+1D635;MATHEMATICAL SANS-SERIF ITALIC SMALL T;Ll;0;L;<font> 0074;;;;N;;;;;
+1D636;MATHEMATICAL SANS-SERIF ITALIC SMALL U;Ll;0;L;<font> 0075;;;;N;;;;;
+1D637;MATHEMATICAL SANS-SERIF ITALIC SMALL V;Ll;0;L;<font> 0076;;;;N;;;;;
+1D638;MATHEMATICAL SANS-SERIF ITALIC SMALL W;Ll;0;L;<font> 0077;;;;N;;;;;
+1D639;MATHEMATICAL SANS-SERIF ITALIC SMALL X;Ll;0;L;<font> 0078;;;;N;;;;;
+1D63A;MATHEMATICAL SANS-SERIF ITALIC SMALL Y;Ll;0;L;<font> 0079;;;;N;;;;;
+1D63B;MATHEMATICAL SANS-SERIF ITALIC SMALL Z;Ll;0;L;<font> 007A;;;;N;;;;;
+1D63C;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL A;Lu;0;L;<font> 0041;;;;N;;;;;
+1D63D;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL B;Lu;0;L;<font> 0042;;;;N;;;;;
+1D63E;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL C;Lu;0;L;<font> 0043;;;;N;;;;;
+1D63F;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL D;Lu;0;L;<font> 0044;;;;N;;;;;
+1D640;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL E;Lu;0;L;<font> 0045;;;;N;;;;;
+1D641;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL F;Lu;0;L;<font> 0046;;;;N;;;;;
+1D642;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL G;Lu;0;L;<font> 0047;;;;N;;;;;
+1D643;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL H;Lu;0;L;<font> 0048;;;;N;;;;;
+1D644;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL I;Lu;0;L;<font> 0049;;;;N;;;;;
+1D645;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL J;Lu;0;L;<font> 004A;;;;N;;;;;
+1D646;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL K;Lu;0;L;<font> 004B;;;;N;;;;;
+1D647;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL L;Lu;0;L;<font> 004C;;;;N;;;;;
+1D648;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL M;Lu;0;L;<font> 004D;;;;N;;;;;
+1D649;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL N;Lu;0;L;<font> 004E;;;;N;;;;;
+1D64A;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL O;Lu;0;L;<font> 004F;;;;N;;;;;
+1D64B;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL P;Lu;0;L;<font> 0050;;;;N;;;;;
+1D64C;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL Q;Lu;0;L;<font> 0051;;;;N;;;;;
+1D64D;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL R;Lu;0;L;<font> 0052;;;;N;;;;;
+1D64E;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL S;Lu;0;L;<font> 0053;;;;N;;;;;
+1D64F;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL T;Lu;0;L;<font> 0054;;;;N;;;;;
+1D650;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL U;Lu;0;L;<font> 0055;;;;N;;;;;
+1D651;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL V;Lu;0;L;<font> 0056;;;;N;;;;;
+1D652;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL W;Lu;0;L;<font> 0057;;;;N;;;;;
+1D653;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL X;Lu;0;L;<font> 0058;;;;N;;;;;
+1D654;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL Y;Lu;0;L;<font> 0059;;;;N;;;;;
+1D655;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL Z;Lu;0;L;<font> 005A;;;;N;;;;;
+1D656;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL A;Ll;0;L;<font> 0061;;;;N;;;;;
+1D657;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL B;Ll;0;L;<font> 0062;;;;N;;;;;
+1D658;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL C;Ll;0;L;<font> 0063;;;;N;;;;;
+1D659;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL D;Ll;0;L;<font> 0064;;;;N;;;;;
+1D65A;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL E;Ll;0;L;<font> 0065;;;;N;;;;;
+1D65B;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL F;Ll;0;L;<font> 0066;;;;N;;;;;
+1D65C;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL G;Ll;0;L;<font> 0067;;;;N;;;;;
+1D65D;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL H;Ll;0;L;<font> 0068;;;;N;;;;;
+1D65E;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL I;Ll;0;L;<font> 0069;;;;N;;;;;
+1D65F;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL J;Ll;0;L;<font> 006A;;;;N;;;;;
+1D660;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL K;Ll;0;L;<font> 006B;;;;N;;;;;
+1D661;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL L;Ll;0;L;<font> 006C;;;;N;;;;;
+1D662;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL M;Ll;0;L;<font> 006D;;;;N;;;;;
+1D663;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL N;Ll;0;L;<font> 006E;;;;N;;;;;
+1D664;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL O;Ll;0;L;<font> 006F;;;;N;;;;;
+1D665;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL P;Ll;0;L;<font> 0070;;;;N;;;;;
+1D666;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL Q;Ll;0;L;<font> 0071;;;;N;;;;;
+1D667;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL R;Ll;0;L;<font> 0072;;;;N;;;;;
+1D668;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL S;Ll;0;L;<font> 0073;;;;N;;;;;
+1D669;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL T;Ll;0;L;<font> 0074;;;;N;;;;;
+1D66A;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL U;Ll;0;L;<font> 0075;;;;N;;;;;
+1D66B;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL V;Ll;0;L;<font> 0076;;;;N;;;;;
+1D66C;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL W;Ll;0;L;<font> 0077;;;;N;;;;;
+1D66D;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL X;Ll;0;L;<font> 0078;;;;N;;;;;
+1D66E;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL Y;Ll;0;L;<font> 0079;;;;N;;;;;
+1D66F;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL Z;Ll;0;L;<font> 007A;;;;N;;;;;
+1D670;MATHEMATICAL MONOSPACE CAPITAL A;Lu;0;L;<font> 0041;;;;N;;;;;
+1D671;MATHEMATICAL MONOSPACE CAPITAL B;Lu;0;L;<font> 0042;;;;N;;;;;
+1D672;MATHEMATICAL MONOSPACE CAPITAL C;Lu;0;L;<font> 0043;;;;N;;;;;
+1D673;MATHEMATICAL MONOSPACE CAPITAL D;Lu;0;L;<font> 0044;;;;N;;;;;
+1D674;MATHEMATICAL MONOSPACE CAPITAL E;Lu;0;L;<font> 0045;;;;N;;;;;
+1D675;MATHEMATICAL MONOSPACE CAPITAL F;Lu;0;L;<font> 0046;;;;N;;;;;
+1D676;MATHEMATICAL MONOSPACE CAPITAL G;Lu;0;L;<font> 0047;;;;N;;;;;
+1D677;MATHEMATICAL MONOSPACE CAPITAL H;Lu;0;L;<font> 0048;;;;N;;;;;
+1D678;MATHEMATICAL MONOSPACE CAPITAL I;Lu;0;L;<font> 0049;;;;N;;;;;
+1D679;MATHEMATICAL MONOSPACE CAPITAL J;Lu;0;L;<font> 004A;;;;N;;;;;
+1D67A;MATHEMATICAL MONOSPACE CAPITAL K;Lu;0;L;<font> 004B;;;;N;;;;;
+1D67B;MATHEMATICAL MONOSPACE CAPITAL L;Lu;0;L;<font> 004C;;;;N;;;;;
+1D67C;MATHEMATICAL MONOSPACE CAPITAL M;Lu;0;L;<font> 004D;;;;N;;;;;
+1D67D;MATHEMATICAL MONOSPACE CAPITAL N;Lu;0;L;<font> 004E;;;;N;;;;;
+1D67E;MATHEMATICAL MONOSPACE CAPITAL O;Lu;0;L;<font> 004F;;;;N;;;;;
+1D67F;MATHEMATICAL MONOSPACE CAPITAL P;Lu;0;L;<font> 0050;;;;N;;;;;
+1D680;MATHEMATICAL MONOSPACE CAPITAL Q;Lu;0;L;<font> 0051;;;;N;;;;;
+1D681;MATHEMATICAL MONOSPACE CAPITAL R;Lu;0;L;<font> 0052;;;;N;;;;;
+1D682;MATHEMATICAL MONOSPACE CAPITAL S;Lu;0;L;<font> 0053;;;;N;;;;;
+1D683;MATHEMATICAL MONOSPACE CAPITAL T;Lu;0;L;<font> 0054;;;;N;;;;;
+1D684;MATHEMATICAL MONOSPACE CAPITAL U;Lu;0;L;<font> 0055;;;;N;;;;;
+1D685;MATHEMATICAL MONOSPACE CAPITAL V;Lu;0;L;<font> 0056;;;;N;;;;;
+1D686;MATHEMATICAL MONOSPACE CAPITAL W;Lu;0;L;<font> 0057;;;;N;;;;;
+1D687;MATHEMATICAL MONOSPACE CAPITAL X;Lu;0;L;<font> 0058;;;;N;;;;;
+1D688;MATHEMATICAL MONOSPACE CAPITAL Y;Lu;0;L;<font> 0059;;;;N;;;;;
+1D689;MATHEMATICAL MONOSPACE CAPITAL Z;Lu;0;L;<font> 005A;;;;N;;;;;
+1D68A;MATHEMATICAL MONOSPACE SMALL A;Ll;0;L;<font> 0061;;;;N;;;;;
+1D68B;MATHEMATICAL MONOSPACE SMALL B;Ll;0;L;<font> 0062;;;;N;;;;;
+1D68C;MATHEMATICAL MONOSPACE SMALL C;Ll;0;L;<font> 0063;;;;N;;;;;
+1D68D;MATHEMATICAL MONOSPACE SMALL D;Ll;0;L;<font> 0064;;;;N;;;;;
+1D68E;MATHEMATICAL MONOSPACE SMALL E;Ll;0;L;<font> 0065;;;;N;;;;;
+1D68F;MATHEMATICAL MONOSPACE SMALL F;Ll;0;L;<font> 0066;;;;N;;;;;
+1D690;MATHEMATICAL MONOSPACE SMALL G;Ll;0;L;<font> 0067;;;;N;;;;;
+1D691;MATHEMATICAL MONOSPACE SMALL H;Ll;0;L;<font> 0068;;;;N;;;;;
+1D692;MATHEMATICAL MONOSPACE SMALL I;Ll;0;L;<font> 0069;;;;N;;;;;
+1D693;MATHEMATICAL MONOSPACE SMALL J;Ll;0;L;<font> 006A;;;;N;;;;;
+1D694;MATHEMATICAL MONOSPACE SMALL K;Ll;0;L;<font> 006B;;;;N;;;;;
+1D695;MATHEMATICAL MONOSPACE SMALL L;Ll;0;L;<font> 006C;;;;N;;;;;
+1D696;MATHEMATICAL MONOSPACE SMALL M;Ll;0;L;<font> 006D;;;;N;;;;;
+1D697;MATHEMATICAL MONOSPACE SMALL N;Ll;0;L;<font> 006E;;;;N;;;;;
+1D698;MATHEMATICAL MONOSPACE SMALL O;Ll;0;L;<font> 006F;;;;N;;;;;
+1D699;MATHEMATICAL MONOSPACE SMALL P;Ll;0;L;<font> 0070;;;;N;;;;;
+1D69A;MATHEMATICAL MONOSPACE SMALL Q;Ll;0;L;<font> 0071;;;;N;;;;;
+1D69B;MATHEMATICAL MONOSPACE SMALL R;Ll;0;L;<font> 0072;;;;N;;;;;
+1D69C;MATHEMATICAL MONOSPACE SMALL S;Ll;0;L;<font> 0073;;;;N;;;;;
+1D69D;MATHEMATICAL MONOSPACE SMALL T;Ll;0;L;<font> 0074;;;;N;;;;;
+1D69E;MATHEMATICAL MONOSPACE SMALL U;Ll;0;L;<font> 0075;;;;N;;;;;
+1D69F;MATHEMATICAL MONOSPACE SMALL V;Ll;0;L;<font> 0076;;;;N;;;;;
+1D6A0;MATHEMATICAL MONOSPACE SMALL W;Ll;0;L;<font> 0077;;;;N;;;;;
+1D6A1;MATHEMATICAL MONOSPACE SMALL X;Ll;0;L;<font> 0078;;;;N;;;;;
+1D6A2;MATHEMATICAL MONOSPACE SMALL Y;Ll;0;L;<font> 0079;;;;N;;;;;
+1D6A3;MATHEMATICAL MONOSPACE SMALL Z;Ll;0;L;<font> 007A;;;;N;;;;;
+1D6A8;MATHEMATICAL BOLD CAPITAL ALPHA;Lu;0;L;<font> 0391;;;;N;;;;;
+1D6A9;MATHEMATICAL BOLD CAPITAL BETA;Lu;0;L;<font> 0392;;;;N;;;;;
+1D6AA;MATHEMATICAL BOLD CAPITAL GAMMA;Lu;0;L;<font> 0393;;;;N;;;;;
+1D6AB;MATHEMATICAL BOLD CAPITAL DELTA;Lu;0;L;<font> 0394;;;;N;;;;;
+1D6AC;MATHEMATICAL BOLD CAPITAL EPSILON;Lu;0;L;<font> 0395;;;;N;;;;;
+1D6AD;MATHEMATICAL BOLD CAPITAL ZETA;Lu;0;L;<font> 0396;;;;N;;;;;
+1D6AE;MATHEMATICAL BOLD CAPITAL ETA;Lu;0;L;<font> 0397;;;;N;;;;;
+1D6AF;MATHEMATICAL BOLD CAPITAL THETA;Lu;0;L;<font> 0398;;;;N;;;;;
+1D6B0;MATHEMATICAL BOLD CAPITAL IOTA;Lu;0;L;<font> 0399;;;;N;;;;;
+1D6B1;MATHEMATICAL BOLD CAPITAL KAPPA;Lu;0;L;<font> 039A;;;;N;;;;;
+1D6B2;MATHEMATICAL BOLD CAPITAL LAMDA;Lu;0;L;<font> 039B;;;;N;;;;;
+1D6B3;MATHEMATICAL BOLD CAPITAL MU;Lu;0;L;<font> 039C;;;;N;;;;;
+1D6B4;MATHEMATICAL BOLD CAPITAL NU;Lu;0;L;<font> 039D;;;;N;;;;;
+1D6B5;MATHEMATICAL BOLD CAPITAL XI;Lu;0;L;<font> 039E;;;;N;;;;;
+1D6B6;MATHEMATICAL BOLD CAPITAL OMICRON;Lu;0;L;<font> 039F;;;;N;;;;;
+1D6B7;MATHEMATICAL BOLD CAPITAL PI;Lu;0;L;<font> 03A0;;;;N;;;;;
+1D6B8;MATHEMATICAL BOLD CAPITAL RHO;Lu;0;L;<font> 03A1;;;;N;;;;;
+1D6B9;MATHEMATICAL BOLD CAPITAL THETA SYMBOL;Lu;0;L;<font> 03F4;;;;N;;;;;
+1D6BA;MATHEMATICAL BOLD CAPITAL SIGMA;Lu;0;L;<font> 03A3;;;;N;;;;;
+1D6BB;MATHEMATICAL BOLD CAPITAL TAU;Lu;0;L;<font> 03A4;;;;N;;;;;
+1D6BC;MATHEMATICAL BOLD CAPITAL UPSILON;Lu;0;L;<font> 03A5;;;;N;;;;;
+1D6BD;MATHEMATICAL BOLD CAPITAL PHI;Lu;0;L;<font> 03A6;;;;N;;;;;
+1D6BE;MATHEMATICAL BOLD CAPITAL CHI;Lu;0;L;<font> 03A7;;;;N;;;;;
+1D6BF;MATHEMATICAL BOLD CAPITAL PSI;Lu;0;L;<font> 03A8;;;;N;;;;;
+1D6C0;MATHEMATICAL BOLD CAPITAL OMEGA;Lu;0;L;<font> 03A9;;;;N;;;;;
+1D6C1;MATHEMATICAL BOLD NABLA;Sm;0;L;<font> 2207;;;;N;;;;;
+1D6C2;MATHEMATICAL BOLD SMALL ALPHA;Ll;0;L;<font> 03B1;;;;N;;;;;
+1D6C3;MATHEMATICAL BOLD SMALL BETA;Ll;0;L;<font> 03B2;;;;N;;;;;
+1D6C4;MATHEMATICAL BOLD SMALL GAMMA;Ll;0;L;<font> 03B3;;;;N;;;;;
+1D6C5;MATHEMATICAL BOLD SMALL DELTA;Ll;0;L;<font> 03B4;;;;N;;;;;
+1D6C6;MATHEMATICAL BOLD SMALL EPSILON;Ll;0;L;<font> 03B5;;;;N;;;;;
+1D6C7;MATHEMATICAL BOLD SMALL ZETA;Ll;0;L;<font> 03B6;;;;N;;;;;
+1D6C8;MATHEMATICAL BOLD SMALL ETA;Ll;0;L;<font> 03B7;;;;N;;;;;
+1D6C9;MATHEMATICAL BOLD SMALL THETA;Ll;0;L;<font> 03B8;;;;N;;;;;
+1D6CA;MATHEMATICAL BOLD SMALL IOTA;Ll;0;L;<font> 03B9;;;;N;;;;;
+1D6CB;MATHEMATICAL BOLD SMALL KAPPA;Ll;0;L;<font> 03BA;;;;N;;;;;
+1D6CC;MATHEMATICAL BOLD SMALL LAMDA;Ll;0;L;<font> 03BB;;;;N;;;;;
+1D6CD;MATHEMATICAL BOLD SMALL MU;Ll;0;L;<font> 03BC;;;;N;;;;;
+1D6CE;MATHEMATICAL BOLD SMALL NU;Ll;0;L;<font> 03BD;;;;N;;;;;
+1D6CF;MATHEMATICAL BOLD SMALL XI;Ll;0;L;<font> 03BE;;;;N;;;;;
+1D6D0;MATHEMATICAL BOLD SMALL OMICRON;Ll;0;L;<font> 03BF;;;;N;;;;;
+1D6D1;MATHEMATICAL BOLD SMALL PI;Ll;0;L;<font> 03C0;;;;N;;;;;
+1D6D2;MATHEMATICAL BOLD SMALL RHO;Ll;0;L;<font> 03C1;;;;N;;;;;
+1D6D3;MATHEMATICAL BOLD SMALL FINAL SIGMA;Ll;0;L;<font> 03C2;;;;N;;;;;
+1D6D4;MATHEMATICAL BOLD SMALL SIGMA;Ll;0;L;<font> 03C3;;;;N;;;;;
+1D6D5;MATHEMATICAL BOLD SMALL TAU;Ll;0;L;<font> 03C4;;;;N;;;;;
+1D6D6;MATHEMATICAL BOLD SMALL UPSILON;Ll;0;L;<font> 03C5;;;;N;;;;;
+1D6D7;MATHEMATICAL BOLD SMALL PHI;Ll;0;L;<font> 03C6;;;;N;;;;;
+1D6D8;MATHEMATICAL BOLD SMALL CHI;Ll;0;L;<font> 03C7;;;;N;;;;;
+1D6D9;MATHEMATICAL BOLD SMALL PSI;Ll;0;L;<font> 03C8;;;;N;;;;;
+1D6DA;MATHEMATICAL BOLD SMALL OMEGA;Ll;0;L;<font> 03C9;;;;N;;;;;
+1D6DB;MATHEMATICAL BOLD PARTIAL DIFFERENTIAL;Sm;0;L;<font> 2202;;;;N;;;;;
+1D6DC;MATHEMATICAL BOLD EPSILON SYMBOL;Ll;0;L;<font> 03F5;;;;N;;;;;
+1D6DD;MATHEMATICAL BOLD THETA SYMBOL;Ll;0;L;<font> 03D1;;;;N;;;;;
+1D6DE;MATHEMATICAL BOLD KAPPA SYMBOL;Ll;0;L;<font> 03F0;;;;N;;;;;
+1D6DF;MATHEMATICAL BOLD PHI SYMBOL;Ll;0;L;<font> 03D5;;;;N;;;;;
+1D6E0;MATHEMATICAL BOLD RHO SYMBOL;Ll;0;L;<font> 03F1;;;;N;;;;;
+1D6E1;MATHEMATICAL BOLD PI SYMBOL;Ll;0;L;<font> 03D6;;;;N;;;;;
+1D6E2;MATHEMATICAL ITALIC CAPITAL ALPHA;Lu;0;L;<font> 0391;;;;N;;;;;
+1D6E3;MATHEMATICAL ITALIC CAPITAL BETA;Lu;0;L;<font> 0392;;;;N;;;;;
+1D6E4;MATHEMATICAL ITALIC CAPITAL GAMMA;Lu;0;L;<font> 0393;;;;N;;;;;
+1D6E5;MATHEMATICAL ITALIC CAPITAL DELTA;Lu;0;L;<font> 0394;;;;N;;;;;
+1D6E6;MATHEMATICAL ITALIC CAPITAL EPSILON;Lu;0;L;<font> 0395;;;;N;;;;;
+1D6E7;MATHEMATICAL ITALIC CAPITAL ZETA;Lu;0;L;<font> 0396;;;;N;;;;;
+1D6E8;MATHEMATICAL ITALIC CAPITAL ETA;Lu;0;L;<font> 0397;;;;N;;;;;
+1D6E9;MATHEMATICAL ITALIC CAPITAL THETA;Lu;0;L;<font> 0398;;;;N;;;;;
+1D6EA;MATHEMATICAL ITALIC CAPITAL IOTA;Lu;0;L;<font> 0399;;;;N;;;;;
+1D6EB;MATHEMATICAL ITALIC CAPITAL KAPPA;Lu;0;L;<font> 039A;;;;N;;;;;
+1D6EC;MATHEMATICAL ITALIC CAPITAL LAMDA;Lu;0;L;<font> 039B;;;;N;;;;;
+1D6ED;MATHEMATICAL ITALIC CAPITAL MU;Lu;0;L;<font> 039C;;;;N;;;;;
+1D6EE;MATHEMATICAL ITALIC CAPITAL NU;Lu;0;L;<font> 039D;;;;N;;;;;
+1D6EF;MATHEMATICAL ITALIC CAPITAL XI;Lu;0;L;<font> 039E;;;;N;;;;;
+1D6F0;MATHEMATICAL ITALIC CAPITAL OMICRON;Lu;0;L;<font> 039F;;;;N;;;;;
+1D6F1;MATHEMATICAL ITALIC CAPITAL PI;Lu;0;L;<font> 03A0;;;;N;;;;;
+1D6F2;MATHEMATICAL ITALIC CAPITAL RHO;Lu;0;L;<font> 03A1;;;;N;;;;;
+1D6F3;MATHEMATICAL ITALIC CAPITAL THETA SYMBOL;Lu;0;L;<font> 03F4;;;;N;;;;;
+1D6F4;MATHEMATICAL ITALIC CAPITAL SIGMA;Lu;0;L;<font> 03A3;;;;N;;;;;
+1D6F5;MATHEMATICAL ITALIC CAPITAL TAU;Lu;0;L;<font> 03A4;;;;N;;;;;
+1D6F6;MATHEMATICAL ITALIC CAPITAL UPSILON;Lu;0;L;<font> 03A5;;;;N;;;;;
+1D6F7;MATHEMATICAL ITALIC CAPITAL PHI;Lu;0;L;<font> 03A6;;;;N;;;;;
+1D6F8;MATHEMATICAL ITALIC CAPITAL CHI;Lu;0;L;<font> 03A7;;;;N;;;;;
+1D6F9;MATHEMATICAL ITALIC CAPITAL PSI;Lu;0;L;<font> 03A8;;;;N;;;;;
+1D6FA;MATHEMATICAL ITALIC CAPITAL OMEGA;Lu;0;L;<font> 03A9;;;;N;;;;;
+1D6FB;MATHEMATICAL ITALIC NABLA;Sm;0;L;<font> 2207;;;;N;;;;;
+1D6FC;MATHEMATICAL ITALIC SMALL ALPHA;Ll;0;L;<font> 03B1;;;;N;;;;;
+1D6FD;MATHEMATICAL ITALIC SMALL BETA;Ll;0;L;<font> 03B2;;;;N;;;;;
+1D6FE;MATHEMATICAL ITALIC SMALL GAMMA;Ll;0;L;<font> 03B3;;;;N;;;;;
+1D6FF;MATHEMATICAL ITALIC SMALL DELTA;Ll;0;L;<font> 03B4;;;;N;;;;;
+1D700;MATHEMATICAL ITALIC SMALL EPSILON;Ll;0;L;<font> 03B5;;;;N;;;;;
+1D701;MATHEMATICAL ITALIC SMALL ZETA;Ll;0;L;<font> 03B6;;;;N;;;;;
+1D702;MATHEMATICAL ITALIC SMALL ETA;Ll;0;L;<font> 03B7;;;;N;;;;;
+1D703;MATHEMATICAL ITALIC SMALL THETA;Ll;0;L;<font> 03B8;;;;N;;;;;
+1D704;MATHEMATICAL ITALIC SMALL IOTA;Ll;0;L;<font> 03B9;;;;N;;;;;
+1D705;MATHEMATICAL ITALIC SMALL KAPPA;Ll;0;L;<font> 03BA;;;;N;;;;;
+1D706;MATHEMATICAL ITALIC SMALL LAMDA;Ll;0;L;<font> 03BB;;;;N;;;;;
+1D707;MATHEMATICAL ITALIC SMALL MU;Ll;0;L;<font> 03BC;;;;N;;;;;
+1D708;MATHEMATICAL ITALIC SMALL NU;Ll;0;L;<font> 03BD;;;;N;;;;;
+1D709;MATHEMATICAL ITALIC SMALL XI;Ll;0;L;<font> 03BE;;;;N;;;;;
+1D70A;MATHEMATICAL ITALIC SMALL OMICRON;Ll;0;L;<font> 03BF;;;;N;;;;;
+1D70B;MATHEMATICAL ITALIC SMALL PI;Ll;0;L;<font> 03C0;;;;N;;;;;
+1D70C;MATHEMATICAL ITALIC SMALL RHO;Ll;0;L;<font> 03C1;;;;N;;;;;
+1D70D;MATHEMATICAL ITALIC SMALL FINAL SIGMA;Ll;0;L;<font> 03C2;;;;N;;;;;
+1D70E;MATHEMATICAL ITALIC SMALL SIGMA;Ll;0;L;<font> 03C3;;;;N;;;;;
+1D70F;MATHEMATICAL ITALIC SMALL TAU;Ll;0;L;<font> 03C4;;;;N;;;;;
+1D710;MATHEMATICAL ITALIC SMALL UPSILON;Ll;0;L;<font> 03C5;;;;N;;;;;
+1D711;MATHEMATICAL ITALIC SMALL PHI;Ll;0;L;<font> 03C6;;;;N;;;;;
+1D712;MATHEMATICAL ITALIC SMALL CHI;Ll;0;L;<font> 03C7;;;;N;;;;;
+1D713;MATHEMATICAL ITALIC SMALL PSI;Ll;0;L;<font> 03C8;;;;N;;;;;
+1D714;MATHEMATICAL ITALIC SMALL OMEGA;Ll;0;L;<font> 03C9;;;;N;;;;;
+1D715;MATHEMATICAL ITALIC PARTIAL DIFFERENTIAL;Sm;0;L;<font> 2202;;;;N;;;;;
+1D716;MATHEMATICAL ITALIC EPSILON SYMBOL;Ll;0;L;<font> 03F5;;;;N;;;;;
+1D717;MATHEMATICAL ITALIC THETA SYMBOL;Ll;0;L;<font> 03D1;;;;N;;;;;
+1D718;MATHEMATICAL ITALIC KAPPA SYMBOL;Ll;0;L;<font> 03F0;;;;N;;;;;
+1D719;MATHEMATICAL ITALIC PHI SYMBOL;Ll;0;L;<font> 03D5;;;;N;;;;;
+1D71A;MATHEMATICAL ITALIC RHO SYMBOL;Ll;0;L;<font> 03F1;;;;N;;;;;
+1D71B;MATHEMATICAL ITALIC PI SYMBOL;Ll;0;L;<font> 03D6;;;;N;;;;;
+1D71C;MATHEMATICAL BOLD ITALIC CAPITAL ALPHA;Lu;0;L;<font> 0391;;;;N;;;;;
+1D71D;MATHEMATICAL BOLD ITALIC CAPITAL BETA;Lu;0;L;<font> 0392;;;;N;;;;;
+1D71E;MATHEMATICAL BOLD ITALIC CAPITAL GAMMA;Lu;0;L;<font> 0393;;;;N;;;;;
+1D71F;MATHEMATICAL BOLD ITALIC CAPITAL DELTA;Lu;0;L;<font> 0394;;;;N;;;;;
+1D720;MATHEMATICAL BOLD ITALIC CAPITAL EPSILON;Lu;0;L;<font> 0395;;;;N;;;;;
+1D721;MATHEMATICAL BOLD ITALIC CAPITAL ZETA;Lu;0;L;<font> 0396;;;;N;;;;;
+1D722;MATHEMATICAL BOLD ITALIC CAPITAL ETA;Lu;0;L;<font> 0397;;;;N;;;;;
+1D723;MATHEMATICAL BOLD ITALIC CAPITAL THETA;Lu;0;L;<font> 0398;;;;N;;;;;
+1D724;MATHEMATICAL BOLD ITALIC CAPITAL IOTA;Lu;0;L;<font> 0399;;;;N;;;;;
+1D725;MATHEMATICAL BOLD ITALIC CAPITAL KAPPA;Lu;0;L;<font> 039A;;;;N;;;;;
+1D726;MATHEMATICAL BOLD ITALIC CAPITAL LAMDA;Lu;0;L;<font> 039B;;;;N;;;;;
+1D727;MATHEMATICAL BOLD ITALIC CAPITAL MU;Lu;0;L;<font> 039C;;;;N;;;;;
+1D728;MATHEMATICAL BOLD ITALIC CAPITAL NU;Lu;0;L;<font> 039D;;;;N;;;;;
+1D729;MATHEMATICAL BOLD ITALIC CAPITAL XI;Lu;0;L;<font> 039E;;;;N;;;;;
+1D72A;MATHEMATICAL BOLD ITALIC CAPITAL OMICRON;Lu;0;L;<font> 039F;;;;N;;;;;
+1D72B;MATHEMATICAL BOLD ITALIC CAPITAL PI;Lu;0;L;<font> 03A0;;;;N;;;;;
+1D72C;MATHEMATICAL BOLD ITALIC CAPITAL RHO;Lu;0;L;<font> 03A1;;;;N;;;;;
+1D72D;MATHEMATICAL BOLD ITALIC CAPITAL THETA SYMBOL;Lu;0;L;<font> 03F4;;;;N;;;;;
+1D72E;MATHEMATICAL BOLD ITALIC CAPITAL SIGMA;Lu;0;L;<font> 03A3;;;;N;;;;;
+1D72F;MATHEMATICAL BOLD ITALIC CAPITAL TAU;Lu;0;L;<font> 03A4;;;;N;;;;;
+1D730;MATHEMATICAL BOLD ITALIC CAPITAL UPSILON;Lu;0;L;<font> 03A5;;;;N;;;;;
+1D731;MATHEMATICAL BOLD ITALIC CAPITAL PHI;Lu;0;L;<font> 03A6;;;;N;;;;;
+1D732;MATHEMATICAL BOLD ITALIC CAPITAL CHI;Lu;0;L;<font> 03A7;;;;N;;;;;
+1D733;MATHEMATICAL BOLD ITALIC CAPITAL PSI;Lu;0;L;<font> 03A8;;;;N;;;;;
+1D734;MATHEMATICAL BOLD ITALIC CAPITAL OMEGA;Lu;0;L;<font> 03A9;;;;N;;;;;
+1D735;MATHEMATICAL BOLD ITALIC NABLA;Sm;0;L;<font> 2207;;;;N;;;;;
+1D736;MATHEMATICAL BOLD ITALIC SMALL ALPHA;Ll;0;L;<font> 03B1;;;;N;;;;;
+1D737;MATHEMATICAL BOLD ITALIC SMALL BETA;Ll;0;L;<font> 03B2;;;;N;;;;;
+1D738;MATHEMATICAL BOLD ITALIC SMALL GAMMA;Ll;0;L;<font> 03B3;;;;N;;;;;
+1D739;MATHEMATICAL BOLD ITALIC SMALL DELTA;Ll;0;L;<font> 03B4;;;;N;;;;;
+1D73A;MATHEMATICAL BOLD ITALIC SMALL EPSILON;Ll;0;L;<font> 03B5;;;;N;;;;;
+1D73B;MATHEMATICAL BOLD ITALIC SMALL ZETA;Ll;0;L;<font> 03B6;;;;N;;;;;
+1D73C;MATHEMATICAL BOLD ITALIC SMALL ETA;Ll;0;L;<font> 03B7;;;;N;;;;;
+1D73D;MATHEMATICAL BOLD ITALIC SMALL THETA;Ll;0;L;<font> 03B8;;;;N;;;;;
+1D73E;MATHEMATICAL BOLD ITALIC SMALL IOTA;Ll;0;L;<font> 03B9;;;;N;;;;;
+1D73F;MATHEMATICAL BOLD ITALIC SMALL KAPPA;Ll;0;L;<font> 03BA;;;;N;;;;;
+1D740;MATHEMATICAL BOLD ITALIC SMALL LAMDA;Ll;0;L;<font> 03BB;;;;N;;;;;
+1D741;MATHEMATICAL BOLD ITALIC SMALL MU;Ll;0;L;<font> 03BC;;;;N;;;;;
+1D742;MATHEMATICAL BOLD ITALIC SMALL NU;Ll;0;L;<font> 03BD;;;;N;;;;;
+1D743;MATHEMATICAL BOLD ITALIC SMALL XI;Ll;0;L;<font> 03BE;;;;N;;;;;
+1D744;MATHEMATICAL BOLD ITALIC SMALL OMICRON;Ll;0;L;<font> 03BF;;;;N;;;;;
+1D745;MATHEMATICAL BOLD ITALIC SMALL PI;Ll;0;L;<font> 03C0;;;;N;;;;;
+1D746;MATHEMATICAL BOLD ITALIC SMALL RHO;Ll;0;L;<font> 03C1;;;;N;;;;;
+1D747;MATHEMATICAL BOLD ITALIC SMALL FINAL SIGMA;Ll;0;L;<font> 03C2;;;;N;;;;;
+1D748;MATHEMATICAL BOLD ITALIC SMALL SIGMA;Ll;0;L;<font> 03C3;;;;N;;;;;
+1D749;MATHEMATICAL BOLD ITALIC SMALL TAU;Ll;0;L;<font> 03C4;;;;N;;;;;
+1D74A;MATHEMATICAL BOLD ITALIC SMALL UPSILON;Ll;0;L;<font> 03C5;;;;N;;;;;
+1D74B;MATHEMATICAL BOLD ITALIC SMALL PHI;Ll;0;L;<font> 03C6;;;;N;;;;;
+1D74C;MATHEMATICAL BOLD ITALIC SMALL CHI;Ll;0;L;<font> 03C7;;;;N;;;;;
+1D74D;MATHEMATICAL BOLD ITALIC SMALL PSI;Ll;0;L;<font> 03C8;;;;N;;;;;
+1D74E;MATHEMATICAL BOLD ITALIC SMALL OMEGA;Ll;0;L;<font> 03C9;;;;N;;;;;
+1D74F;MATHEMATICAL BOLD ITALIC PARTIAL DIFFERENTIAL;Sm;0;L;<font> 2202;;;;N;;;;;
+1D750;MATHEMATICAL BOLD ITALIC EPSILON SYMBOL;Ll;0;L;<font> 03F5;;;;N;;;;;
+1D751;MATHEMATICAL BOLD ITALIC THETA SYMBOL;Ll;0;L;<font> 03D1;;;;N;;;;;
+1D752;MATHEMATICAL BOLD ITALIC KAPPA SYMBOL;Ll;0;L;<font> 03F0;;;;N;;;;;
+1D753;MATHEMATICAL BOLD ITALIC PHI SYMBOL;Ll;0;L;<font> 03D5;;;;N;;;;;
+1D754;MATHEMATICAL BOLD ITALIC RHO SYMBOL;Ll;0;L;<font> 03F1;;;;N;;;;;
+1D755;MATHEMATICAL BOLD ITALIC PI SYMBOL;Ll;0;L;<font> 03D6;;;;N;;;;;
+1D756;MATHEMATICAL SANS-SERIF BOLD CAPITAL ALPHA;Lu;0;L;<font> 0391;;;;N;;;;;
+1D757;MATHEMATICAL SANS-SERIF BOLD CAPITAL BETA;Lu;0;L;<font> 0392;;;;N;;;;;
+1D758;MATHEMATICAL SANS-SERIF BOLD CAPITAL GAMMA;Lu;0;L;<font> 0393;;;;N;;;;;
+1D759;MATHEMATICAL SANS-SERIF BOLD CAPITAL DELTA;Lu;0;L;<font> 0394;;;;N;;;;;
+1D75A;MATHEMATICAL SANS-SERIF BOLD CAPITAL EPSILON;Lu;0;L;<font> 0395;;;;N;;;;;
+1D75B;MATHEMATICAL SANS-SERIF BOLD CAPITAL ZETA;Lu;0;L;<font> 0396;;;;N;;;;;
+1D75C;MATHEMATICAL SANS-SERIF BOLD CAPITAL ETA;Lu;0;L;<font> 0397;;;;N;;;;;
+1D75D;MATHEMATICAL SANS-SERIF BOLD CAPITAL THETA;Lu;0;L;<font> 0398;;;;N;;;;;
+1D75E;MATHEMATICAL SANS-SERIF BOLD CAPITAL IOTA;Lu;0;L;<font> 0399;;;;N;;;;;
+1D75F;MATHEMATICAL SANS-SERIF BOLD CAPITAL KAPPA;Lu;0;L;<font> 039A;;;;N;;;;;
+1D760;MATHEMATICAL SANS-SERIF BOLD CAPITAL LAMDA;Lu;0;L;<font> 039B;;;;N;;;;;
+1D761;MATHEMATICAL SANS-SERIF BOLD CAPITAL MU;Lu;0;L;<font> 039C;;;;N;;;;;
+1D762;MATHEMATICAL SANS-SERIF BOLD CAPITAL NU;Lu;0;L;<font> 039D;;;;N;;;;;
+1D763;MATHEMATICAL SANS-SERIF BOLD CAPITAL XI;Lu;0;L;<font> 039E;;;;N;;;;;
+1D764;MATHEMATICAL SANS-SERIF BOLD CAPITAL OMICRON;Lu;0;L;<font> 039F;;;;N;;;;;
+1D765;MATHEMATICAL SANS-SERIF BOLD CAPITAL PI;Lu;0;L;<font> 03A0;;;;N;;;;;
+1D766;MATHEMATICAL SANS-SERIF BOLD CAPITAL RHO;Lu;0;L;<font> 03A1;;;;N;;;;;
+1D767;MATHEMATICAL SANS-SERIF BOLD CAPITAL THETA SYMBOL;Lu;0;L;<font> 03F4;;;;N;;;;;
+1D768;MATHEMATICAL SANS-SERIF BOLD CAPITAL SIGMA;Lu;0;L;<font> 03A3;;;;N;;;;;
+1D769;MATHEMATICAL SANS-SERIF BOLD CAPITAL TAU;Lu;0;L;<font> 03A4;;;;N;;;;;
+1D76A;MATHEMATICAL SANS-SERIF BOLD CAPITAL UPSILON;Lu;0;L;<font> 03A5;;;;N;;;;;
+1D76B;MATHEMATICAL SANS-SERIF BOLD CAPITAL PHI;Lu;0;L;<font> 03A6;;;;N;;;;;
+1D76C;MATHEMATICAL SANS-SERIF BOLD CAPITAL CHI;Lu;0;L;<font> 03A7;;;;N;;;;;
+1D76D;MATHEMATICAL SANS-SERIF BOLD CAPITAL PSI;Lu;0;L;<font> 03A8;;;;N;;;;;
+1D76E;MATHEMATICAL SANS-SERIF BOLD CAPITAL OMEGA;Lu;0;L;<font> 03A9;;;;N;;;;;
+1D76F;MATHEMATICAL SANS-SERIF BOLD NABLA;Sm;0;L;<font> 2207;;;;N;;;;;
+1D770;MATHEMATICAL SANS-SERIF BOLD SMALL ALPHA;Ll;0;L;<font> 03B1;;;;N;;;;;
+1D771;MATHEMATICAL SANS-SERIF BOLD SMALL BETA;Ll;0;L;<font> 03B2;;;;N;;;;;
+1D772;MATHEMATICAL SANS-SERIF BOLD SMALL GAMMA;Ll;0;L;<font> 03B3;;;;N;;;;;
+1D773;MATHEMATICAL SANS-SERIF BOLD SMALL DELTA;Ll;0;L;<font> 03B4;;;;N;;;;;
+1D774;MATHEMATICAL SANS-SERIF BOLD SMALL EPSILON;Ll;0;L;<font> 03B5;;;;N;;;;;
+1D775;MATHEMATICAL SANS-SERIF BOLD SMALL ZETA;Ll;0;L;<font> 03B6;;;;N;;;;;
+1D776;MATHEMATICAL SANS-SERIF BOLD SMALL ETA;Ll;0;L;<font> 03B7;;;;N;;;;;
+1D777;MATHEMATICAL SANS-SERIF BOLD SMALL THETA;Ll;0;L;<font> 03B8;;;;N;;;;;
+1D778;MATHEMATICAL SANS-SERIF BOLD SMALL IOTA;Ll;0;L;<font> 03B9;;;;N;;;;;
+1D779;MATHEMATICAL SANS-SERIF BOLD SMALL KAPPA;Ll;0;L;<font> 03BA;;;;N;;;;;
+1D77A;MATHEMATICAL SANS-SERIF BOLD SMALL LAMDA;Ll;0;L;<font> 03BB;;;;N;;;;;
+1D77B;MATHEMATICAL SANS-SERIF BOLD SMALL MU;Ll;0;L;<font> 03BC;;;;N;;;;;
+1D77C;MATHEMATICAL SANS-SERIF BOLD SMALL NU;Ll;0;L;<font> 03BD;;;;N;;;;;
+1D77D;MATHEMATICAL SANS-SERIF BOLD SMALL XI;Ll;0;L;<font> 03BE;;;;N;;;;;
+1D77E;MATHEMATICAL SANS-SERIF BOLD SMALL OMICRON;Ll;0;L;<font> 03BF;;;;N;;;;;
+1D77F;MATHEMATICAL SANS-SERIF BOLD SMALL PI;Ll;0;L;<font> 03C0;;;;N;;;;;
+1D780;MATHEMATICAL SANS-SERIF BOLD SMALL RHO;Ll;0;L;<font> 03C1;;;;N;;;;;
+1D781;MATHEMATICAL SANS-SERIF BOLD SMALL FINAL SIGMA;Ll;0;L;<font> 03C2;;;;N;;;;;
+1D782;MATHEMATICAL SANS-SERIF BOLD SMALL SIGMA;Ll;0;L;<font> 03C3;;;;N;;;;;
+1D783;MATHEMATICAL SANS-SERIF BOLD SMALL TAU;Ll;0;L;<font> 03C4;;;;N;;;;;
+1D784;MATHEMATICAL SANS-SERIF BOLD SMALL UPSILON;Ll;0;L;<font> 03C5;;;;N;;;;;
+1D785;MATHEMATICAL SANS-SERIF BOLD SMALL PHI;Ll;0;L;<font> 03C6;;;;N;;;;;
+1D786;MATHEMATICAL SANS-SERIF BOLD SMALL CHI;Ll;0;L;<font> 03C7;;;;N;;;;;
+1D787;MATHEMATICAL SANS-SERIF BOLD SMALL PSI;Ll;0;L;<font> 03C8;;;;N;;;;;
+1D788;MATHEMATICAL SANS-SERIF BOLD SMALL OMEGA;Ll;0;L;<font> 03C9;;;;N;;;;;
+1D789;MATHEMATICAL SANS-SERIF BOLD PARTIAL DIFFERENTIAL;Sm;0;L;<font> 2202;;;;N;;;;;
+1D78A;MATHEMATICAL SANS-SERIF BOLD EPSILON SYMBOL;Ll;0;L;<font> 03F5;;;;N;;;;;
+1D78B;MATHEMATICAL SANS-SERIF BOLD THETA SYMBOL;Ll;0;L;<font> 03D1;;;;N;;;;;
+1D78C;MATHEMATICAL SANS-SERIF BOLD KAPPA SYMBOL;Ll;0;L;<font> 03F0;;;;N;;;;;
+1D78D;MATHEMATICAL SANS-SERIF BOLD PHI SYMBOL;Ll;0;L;<font> 03D5;;;;N;;;;;
+1D78E;MATHEMATICAL SANS-SERIF BOLD RHO SYMBOL;Ll;0;L;<font> 03F1;;;;N;;;;;
+1D78F;MATHEMATICAL SANS-SERIF BOLD PI SYMBOL;Ll;0;L;<font> 03D6;;;;N;;;;;
+1D790;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ALPHA;Lu;0;L;<font> 0391;;;;N;;;;;
+1D791;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL BETA;Lu;0;L;<font> 0392;;;;N;;;;;
+1D792;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL GAMMA;Lu;0;L;<font> 0393;;;;N;;;;;
+1D793;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL DELTA;Lu;0;L;<font> 0394;;;;N;;;;;
+1D794;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL EPSILON;Lu;0;L;<font> 0395;;;;N;;;;;
+1D795;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ZETA;Lu;0;L;<font> 0396;;;;N;;;;;
+1D796;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ETA;Lu;0;L;<font> 0397;;;;N;;;;;
+1D797;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL THETA;Lu;0;L;<font> 0398;;;;N;;;;;
+1D798;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL IOTA;Lu;0;L;<font> 0399;;;;N;;;;;
+1D799;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL KAPPA;Lu;0;L;<font> 039A;;;;N;;;;;
+1D79A;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL LAMDA;Lu;0;L;<font> 039B;;;;N;;;;;
+1D79B;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL MU;Lu;0;L;<font> 039C;;;;N;;;;;
+1D79C;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL NU;Lu;0;L;<font> 039D;;;;N;;;;;
+1D79D;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL XI;Lu;0;L;<font> 039E;;;;N;;;;;
+1D79E;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL OMICRON;Lu;0;L;<font> 039F;;;;N;;;;;
+1D79F;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PI;Lu;0;L;<font> 03A0;;;;N;;;;;
+1D7A0;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL RHO;Lu;0;L;<font> 03A1;;;;N;;;;;
+1D7A1;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL THETA SYMBOL;Lu;0;L;<font> 03F4;;;;N;;;;;
+1D7A2;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL SIGMA;Lu;0;L;<font> 03A3;;;;N;;;;;
+1D7A3;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL TAU;Lu;0;L;<font> 03A4;;;;N;;;;;
+1D7A4;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL UPSILON;Lu;0;L;<font> 03A5;;;;N;;;;;
+1D7A5;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PHI;Lu;0;L;<font> 03A6;;;;N;;;;;
+1D7A6;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL CHI;Lu;0;L;<font> 03A7;;;;N;;;;;
+1D7A7;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PSI;Lu;0;L;<font> 03A8;;;;N;;;;;
+1D7A8;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL OMEGA;Lu;0;L;<font> 03A9;;;;N;;;;;
+1D7A9;MATHEMATICAL SANS-SERIF BOLD ITALIC NABLA;Sm;0;L;<font> 2207;;;;N;;;;;
+1D7AA;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ALPHA;Ll;0;L;<font> 03B1;;;;N;;;;;
+1D7AB;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL BETA;Ll;0;L;<font> 03B2;;;;N;;;;;
+1D7AC;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL GAMMA;Ll;0;L;<font> 03B3;;;;N;;;;;
+1D7AD;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL DELTA;Ll;0;L;<font> 03B4;;;;N;;;;;
+1D7AE;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL EPSILON;Ll;0;L;<font> 03B5;;;;N;;;;;
+1D7AF;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ZETA;Ll;0;L;<font> 03B6;;;;N;;;;;
+1D7B0;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ETA;Ll;0;L;<font> 03B7;;;;N;;;;;
+1D7B1;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL THETA;Ll;0;L;<font> 03B8;;;;N;;;;;
+1D7B2;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL IOTA;Ll;0;L;<font> 03B9;;;;N;;;;;
+1D7B3;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL KAPPA;Ll;0;L;<font> 03BA;;;;N;;;;;
+1D7B4;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL LAMDA;Ll;0;L;<font> 03BB;;;;N;;;;;
+1D7B5;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL MU;Ll;0;L;<font> 03BC;;;;N;;;;;
+1D7B6;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL NU;Ll;0;L;<font> 03BD;;;;N;;;;;
+1D7B7;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL XI;Ll;0;L;<font> 03BE;;;;N;;;;;
+1D7B8;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL OMICRON;Ll;0;L;<font> 03BF;;;;N;;;;;
+1D7B9;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL PI;Ll;0;L;<font> 03C0;;;;N;;;;;
+1D7BA;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL RHO;Ll;0;L;<font> 03C1;;;;N;;;;;
+1D7BB;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL FINAL SIGMA;Ll;0;L;<font> 03C2;;;;N;;;;;
+1D7BC;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL SIGMA;Ll;0;L;<font> 03C3;;;;N;;;;;
+1D7BD;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL TAU;Ll;0;L;<font> 03C4;;;;N;;;;;
+1D7BE;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL UPSILON;Ll;0;L;<font> 03C5;;;;N;;;;;
+1D7BF;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL PHI;Ll;0;L;<font> 03C6;;;;N;;;;;
+1D7C0;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL CHI;Ll;0;L;<font> 03C7;;;;N;;;;;
+1D7C1;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL PSI;Ll;0;L;<font> 03C8;;;;N;;;;;
+1D7C2;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL OMEGA;Ll;0;L;<font> 03C9;;;;N;;;;;
+1D7C3;MATHEMATICAL SANS-SERIF BOLD ITALIC PARTIAL DIFFERENTIAL;Sm;0;L;<font> 2202;;;;N;;;;;
+1D7C4;MATHEMATICAL SANS-SERIF BOLD ITALIC EPSILON SYMBOL;Ll;0;L;<font> 03F5;;;;N;;;;;
+1D7C5;MATHEMATICAL SANS-SERIF BOLD ITALIC THETA SYMBOL;Ll;0;L;<font> 03D1;;;;N;;;;;
+1D7C6;MATHEMATICAL SANS-SERIF BOLD ITALIC KAPPA SYMBOL;Ll;0;L;<font> 03F0;;;;N;;;;;
+1D7C7;MATHEMATICAL SANS-SERIF BOLD ITALIC PHI SYMBOL;Ll;0;L;<font> 03D5;;;;N;;;;;
+1D7C8;MATHEMATICAL SANS-SERIF BOLD ITALIC RHO SYMBOL;Ll;0;L;<font> 03F1;;;;N;;;;;
+1D7C9;MATHEMATICAL SANS-SERIF BOLD ITALIC PI SYMBOL;Ll;0;L;<font> 03D6;;;;N;;;;;
+1D7CE;MATHEMATICAL BOLD DIGIT ZERO;Nd;0;EN;<font> 0030;0;0;0;N;;;;;
+1D7CF;MATHEMATICAL BOLD DIGIT ONE;Nd;0;EN;<font> 0031;1;1;1;N;;;;;
+1D7D0;MATHEMATICAL BOLD DIGIT TWO;Nd;0;EN;<font> 0032;2;2;2;N;;;;;
+1D7D1;MATHEMATICAL BOLD DIGIT THREE;Nd;0;EN;<font> 0033;3;3;3;N;;;;;
+1D7D2;MATHEMATICAL BOLD DIGIT FOUR;Nd;0;EN;<font> 0034;4;4;4;N;;;;;
+1D7D3;MATHEMATICAL BOLD DIGIT FIVE;Nd;0;EN;<font> 0035;5;5;5;N;;;;;
+1D7D4;MATHEMATICAL BOLD DIGIT SIX;Nd;0;EN;<font> 0036;6;6;6;N;;;;;
+1D7D5;MATHEMATICAL BOLD DIGIT SEVEN;Nd;0;EN;<font> 0037;7;7;7;N;;;;;
+1D7D6;MATHEMATICAL BOLD DIGIT EIGHT;Nd;0;EN;<font> 0038;8;8;8;N;;;;;
+1D7D7;MATHEMATICAL BOLD DIGIT NINE;Nd;0;EN;<font> 0039;9;9;9;N;;;;;
+1D7D8;MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO;Nd;0;EN;<font> 0030;0;0;0;N;;;;;
+1D7D9;MATHEMATICAL DOUBLE-STRUCK DIGIT ONE;Nd;0;EN;<font> 0031;1;1;1;N;;;;;
+1D7DA;MATHEMATICAL DOUBLE-STRUCK DIGIT TWO;Nd;0;EN;<font> 0032;2;2;2;N;;;;;
+1D7DB;MATHEMATICAL DOUBLE-STRUCK DIGIT THREE;Nd;0;EN;<font> 0033;3;3;3;N;;;;;
+1D7DC;MATHEMATICAL DOUBLE-STRUCK DIGIT FOUR;Nd;0;EN;<font> 0034;4;4;4;N;;;;;
+1D7DD;MATHEMATICAL DOUBLE-STRUCK DIGIT FIVE;Nd;0;EN;<font> 0035;5;5;5;N;;;;;
+1D7DE;MATHEMATICAL DOUBLE-STRUCK DIGIT SIX;Nd;0;EN;<font> 0036;6;6;6;N;;;;;
+1D7DF;MATHEMATICAL DOUBLE-STRUCK DIGIT SEVEN;Nd;0;EN;<font> 0037;7;7;7;N;;;;;
+1D7E0;MATHEMATICAL DOUBLE-STRUCK DIGIT EIGHT;Nd;0;EN;<font> 0038;8;8;8;N;;;;;
+1D7E1;MATHEMATICAL DOUBLE-STRUCK DIGIT NINE;Nd;0;EN;<font> 0039;9;9;9;N;;;;;
+1D7E2;MATHEMATICAL SANS-SERIF DIGIT ZERO;Nd;0;EN;<font> 0030;0;0;0;N;;;;;
+1D7E3;MATHEMATICAL SANS-SERIF DIGIT ONE;Nd;0;EN;<font> 0031;1;1;1;N;;;;;
+1D7E4;MATHEMATICAL SANS-SERIF DIGIT TWO;Nd;0;EN;<font> 0032;2;2;2;N;;;;;
+1D7E5;MATHEMATICAL SANS-SERIF DIGIT THREE;Nd;0;EN;<font> 0033;3;3;3;N;;;;;
+1D7E6;MATHEMATICAL SANS-SERIF DIGIT FOUR;Nd;0;EN;<font> 0034;4;4;4;N;;;;;
+1D7E7;MATHEMATICAL SANS-SERIF DIGIT FIVE;Nd;0;EN;<font> 0035;5;5;5;N;;;;;
+1D7E8;MATHEMATICAL SANS-SERIF DIGIT SIX;Nd;0;EN;<font> 0036;6;6;6;N;;;;;
+1D7E9;MATHEMATICAL SANS-SERIF DIGIT SEVEN;Nd;0;EN;<font> 0037;7;7;7;N;;;;;
+1D7EA;MATHEMATICAL SANS-SERIF DIGIT EIGHT;Nd;0;EN;<font> 0038;8;8;8;N;;;;;
+1D7EB;MATHEMATICAL SANS-SERIF DIGIT NINE;Nd;0;EN;<font> 0039;9;9;9;N;;;;;
+1D7EC;MATHEMATICAL SANS-SERIF BOLD DIGIT ZERO;Nd;0;EN;<font> 0030;0;0;0;N;;;;;
+1D7ED;MATHEMATICAL SANS-SERIF BOLD DIGIT ONE;Nd;0;EN;<font> 0031;1;1;1;N;;;;;
+1D7EE;MATHEMATICAL SANS-SERIF BOLD DIGIT TWO;Nd;0;EN;<font> 0032;2;2;2;N;;;;;
+1D7EF;MATHEMATICAL SANS-SERIF BOLD DIGIT THREE;Nd;0;EN;<font> 0033;3;3;3;N;;;;;
+1D7F0;MATHEMATICAL SANS-SERIF BOLD DIGIT FOUR;Nd;0;EN;<font> 0034;4;4;4;N;;;;;
+1D7F1;MATHEMATICAL SANS-SERIF BOLD DIGIT FIVE;Nd;0;EN;<font> 0035;5;5;5;N;;;;;
+1D7F2;MATHEMATICAL SANS-SERIF BOLD DIGIT SIX;Nd;0;EN;<font> 0036;6;6;6;N;;;;;
+1D7F3;MATHEMATICAL SANS-SERIF BOLD DIGIT SEVEN;Nd;0;EN;<font> 0037;7;7;7;N;;;;;
+1D7F4;MATHEMATICAL SANS-SERIF BOLD DIGIT EIGHT;Nd;0;EN;<font> 0038;8;8;8;N;;;;;
+1D7F5;MATHEMATICAL SANS-SERIF BOLD DIGIT NINE;Nd;0;EN;<font> 0039;9;9;9;N;;;;;
+1D7F6;MATHEMATICAL MONOSPACE DIGIT ZERO;Nd;0;EN;<font> 0030;0;0;0;N;;;;;
+1D7F7;MATHEMATICAL MONOSPACE DIGIT ONE;Nd;0;EN;<font> 0031;1;1;1;N;;;;;
+1D7F8;MATHEMATICAL MONOSPACE DIGIT TWO;Nd;0;EN;<font> 0032;2;2;2;N;;;;;
+1D7F9;MATHEMATICAL MONOSPACE DIGIT THREE;Nd;0;EN;<font> 0033;3;3;3;N;;;;;
+1D7FA;MATHEMATICAL MONOSPACE DIGIT FOUR;Nd;0;EN;<font> 0034;4;4;4;N;;;;;
+1D7FB;MATHEMATICAL MONOSPACE DIGIT FIVE;Nd;0;EN;<font> 0035;5;5;5;N;;;;;
+1D7FC;MATHEMATICAL MONOSPACE DIGIT SIX;Nd;0;EN;<font> 0036;6;6;6;N;;;;;
+1D7FD;MATHEMATICAL MONOSPACE DIGIT SEVEN;Nd;0;EN;<font> 0037;7;7;7;N;;;;;
+1D7FE;MATHEMATICAL MONOSPACE DIGIT EIGHT;Nd;0;EN;<font> 0038;8;8;8;N;;;;;
+1D7FF;MATHEMATICAL MONOSPACE DIGIT NINE;Nd;0;EN;<font> 0039;9;9;9;N;;;;;
+20000;<CJK Ideograph Extension B, First>;Lo;0;L;;;;;N;;;;;
+2A6D6;<CJK Ideograph Extension B, Last>;Lo;0;L;;;;;N;;;;;
+2F800;CJK COMPATIBILITY IDEOGRAPH-2F800;Lo;0;L;4E3D;;;;N;;;;;
+2F801;CJK COMPATIBILITY IDEOGRAPH-2F801;Lo;0;L;4E38;;;;N;;;;;
+2F802;CJK COMPATIBILITY IDEOGRAPH-2F802;Lo;0;L;4E41;;;;N;;;;;
+2F803;CJK COMPATIBILITY IDEOGRAPH-2F803;Lo;0;L;20122;;;;N;;;;;
+2F804;CJK COMPATIBILITY IDEOGRAPH-2F804;Lo;0;L;4F60;;;;N;;;;;
+2F805;CJK COMPATIBILITY IDEOGRAPH-2F805;Lo;0;L;4FAE;;;;N;;;;;
+2F806;CJK COMPATIBILITY IDEOGRAPH-2F806;Lo;0;L;4FBB;;;;N;;;;;
+2F807;CJK COMPATIBILITY IDEOGRAPH-2F807;Lo;0;L;5002;;;;N;;;;;
+2F808;CJK COMPATIBILITY IDEOGRAPH-2F808;Lo;0;L;507A;;;;N;;;;;
+2F809;CJK COMPATIBILITY IDEOGRAPH-2F809;Lo;0;L;5099;;;;N;;;;;
+2F80A;CJK COMPATIBILITY IDEOGRAPH-2F80A;Lo;0;L;50E7;;;;N;;;;;
+2F80B;CJK COMPATIBILITY IDEOGRAPH-2F80B;Lo;0;L;50CF;;;;N;;;;;
+2F80C;CJK COMPATIBILITY IDEOGRAPH-2F80C;Lo;0;L;349E;;;;N;;;;;
+2F80D;CJK COMPATIBILITY IDEOGRAPH-2F80D;Lo;0;L;2063A;;;;N;;;;;
+2F80E;CJK COMPATIBILITY IDEOGRAPH-2F80E;Lo;0;L;514D;;;;N;;;;;
+2F80F;CJK COMPATIBILITY IDEOGRAPH-2F80F;Lo;0;L;5154;;;;N;;;;;
+2F810;CJK COMPATIBILITY IDEOGRAPH-2F810;Lo;0;L;5164;;;;N;;;;;
+2F811;CJK COMPATIBILITY IDEOGRAPH-2F811;Lo;0;L;5177;;;;N;;;;;
+2F812;CJK COMPATIBILITY IDEOGRAPH-2F812;Lo;0;L;2051C;;;;N;;;;;
+2F813;CJK COMPATIBILITY IDEOGRAPH-2F813;Lo;0;L;34B9;;;;N;;;;;
+2F814;CJK COMPATIBILITY IDEOGRAPH-2F814;Lo;0;L;5167;;;;N;;;;;
+2F815;CJK COMPATIBILITY IDEOGRAPH-2F815;Lo;0;L;518D;;;;N;;;;;
+2F816;CJK COMPATIBILITY IDEOGRAPH-2F816;Lo;0;L;2054B;;;;N;;;;;
+2F817;CJK COMPATIBILITY IDEOGRAPH-2F817;Lo;0;L;5197;;;;N;;;;;
+2F818;CJK COMPATIBILITY IDEOGRAPH-2F818;Lo;0;L;51A4;;;;N;;;;;
+2F819;CJK COMPATIBILITY IDEOGRAPH-2F819;Lo;0;L;4ECC;;;;N;;;;;
+2F81A;CJK COMPATIBILITY IDEOGRAPH-2F81A;Lo;0;L;51AC;;;;N;;;;;
+2F81B;CJK COMPATIBILITY IDEOGRAPH-2F81B;Lo;0;L;51B5;;;;N;;;;;
+2F81C;CJK COMPATIBILITY IDEOGRAPH-2F81C;Lo;0;L;291DF;;;;N;;;;;
+2F81D;CJK COMPATIBILITY IDEOGRAPH-2F81D;Lo;0;L;51F5;;;;N;;;;;
+2F81E;CJK COMPATIBILITY IDEOGRAPH-2F81E;Lo;0;L;5203;;;;N;;;;;
+2F81F;CJK COMPATIBILITY IDEOGRAPH-2F81F;Lo;0;L;34DF;;;;N;;;;;
+2F820;CJK COMPATIBILITY IDEOGRAPH-2F820;Lo;0;L;523B;;;;N;;;;;
+2F821;CJK COMPATIBILITY IDEOGRAPH-2F821;Lo;0;L;5246;;;;N;;;;;
+2F822;CJK COMPATIBILITY IDEOGRAPH-2F822;Lo;0;L;5272;;;;N;;;;;
+2F823;CJK COMPATIBILITY IDEOGRAPH-2F823;Lo;0;L;5277;;;;N;;;;;
+2F824;CJK COMPATIBILITY IDEOGRAPH-2F824;Lo;0;L;3515;;;;N;;;;;
+2F825;CJK COMPATIBILITY IDEOGRAPH-2F825;Lo;0;L;52C7;;;;N;;;;;
+2F826;CJK COMPATIBILITY IDEOGRAPH-2F826;Lo;0;L;52C9;;;;N;;;;;
+2F827;CJK COMPATIBILITY IDEOGRAPH-2F827;Lo;0;L;52E4;;;;N;;;;;
+2F828;CJK COMPATIBILITY IDEOGRAPH-2F828;Lo;0;L;52FA;;;;N;;;;;
+2F829;CJK COMPATIBILITY IDEOGRAPH-2F829;Lo;0;L;5305;;;;N;;;;;
+2F82A;CJK COMPATIBILITY IDEOGRAPH-2F82A;Lo;0;L;5306;;;;N;;;;;
+2F82B;CJK COMPATIBILITY IDEOGRAPH-2F82B;Lo;0;L;5317;;;;N;;;;;
+2F82C;CJK COMPATIBILITY IDEOGRAPH-2F82C;Lo;0;L;5349;;;;N;;;;;
+2F82D;CJK COMPATIBILITY IDEOGRAPH-2F82D;Lo;0;L;5351;;;;N;;;;;
+2F82E;CJK COMPATIBILITY IDEOGRAPH-2F82E;Lo;0;L;535A;;;;N;;;;;
+2F82F;CJK COMPATIBILITY IDEOGRAPH-2F82F;Lo;0;L;5373;;;;N;;;;;
+2F830;CJK COMPATIBILITY IDEOGRAPH-2F830;Lo;0;L;537D;;;;N;;;;;
+2F831;CJK COMPATIBILITY IDEOGRAPH-2F831;Lo;0;L;537F;;;;N;;;;;
+2F832;CJK COMPATIBILITY IDEOGRAPH-2F832;Lo;0;L;537F;;;;N;;;;;
+2F833;CJK COMPATIBILITY IDEOGRAPH-2F833;Lo;0;L;537F;;;;N;;;;;
+2F834;CJK COMPATIBILITY IDEOGRAPH-2F834;Lo;0;L;20A2C;;;;N;;;;;
+2F835;CJK COMPATIBILITY IDEOGRAPH-2F835;Lo;0;L;7070;;;;N;;;;;
+2F836;CJK COMPATIBILITY IDEOGRAPH-2F836;Lo;0;L;53CA;;;;N;;;;;
+2F837;CJK COMPATIBILITY IDEOGRAPH-2F837;Lo;0;L;53DF;;;;N;;;;;
+2F838;CJK COMPATIBILITY IDEOGRAPH-2F838;Lo;0;L;20B63;;;;N;;;;;
+2F839;CJK COMPATIBILITY IDEOGRAPH-2F839;Lo;0;L;53EB;;;;N;;;;;
+2F83A;CJK COMPATIBILITY IDEOGRAPH-2F83A;Lo;0;L;53F1;;;;N;;;;;
+2F83B;CJK COMPATIBILITY IDEOGRAPH-2F83B;Lo;0;L;5406;;;;N;;;;;
+2F83C;CJK COMPATIBILITY IDEOGRAPH-2F83C;Lo;0;L;549E;;;;N;;;;;
+2F83D;CJK COMPATIBILITY IDEOGRAPH-2F83D;Lo;0;L;5438;;;;N;;;;;
+2F83E;CJK COMPATIBILITY IDEOGRAPH-2F83E;Lo;0;L;5448;;;;N;;;;;
+2F83F;CJK COMPATIBILITY IDEOGRAPH-2F83F;Lo;0;L;5468;;;;N;;;;;
+2F840;CJK COMPATIBILITY IDEOGRAPH-2F840;Lo;0;L;54A2;;;;N;;;;;
+2F841;CJK COMPATIBILITY IDEOGRAPH-2F841;Lo;0;L;54F6;;;;N;;;;;
+2F842;CJK COMPATIBILITY IDEOGRAPH-2F842;Lo;0;L;5510;;;;N;;;;;
+2F843;CJK COMPATIBILITY IDEOGRAPH-2F843;Lo;0;L;5553;;;;N;;;;;
+2F844;CJK COMPATIBILITY IDEOGRAPH-2F844;Lo;0;L;5563;;;;N;;;;;
+2F845;CJK COMPATIBILITY IDEOGRAPH-2F845;Lo;0;L;5584;;;;N;;;;;
+2F846;CJK COMPATIBILITY IDEOGRAPH-2F846;Lo;0;L;5584;;;;N;;;;;
+2F847;CJK COMPATIBILITY IDEOGRAPH-2F847;Lo;0;L;5599;;;;N;;;;;
+2F848;CJK COMPATIBILITY IDEOGRAPH-2F848;Lo;0;L;55AB;;;;N;;;;;
+2F849;CJK COMPATIBILITY IDEOGRAPH-2F849;Lo;0;L;55B3;;;;N;;;;;
+2F84A;CJK COMPATIBILITY IDEOGRAPH-2F84A;Lo;0;L;55C2;;;;N;;;;;
+2F84B;CJK COMPATIBILITY IDEOGRAPH-2F84B;Lo;0;L;5716;;;;N;;;;;
+2F84C;CJK COMPATIBILITY IDEOGRAPH-2F84C;Lo;0;L;5606;;;;N;;;;;
+2F84D;CJK COMPATIBILITY IDEOGRAPH-2F84D;Lo;0;L;5717;;;;N;;;;;
+2F84E;CJK COMPATIBILITY IDEOGRAPH-2F84E;Lo;0;L;5651;;;;N;;;;;
+2F84F;CJK COMPATIBILITY IDEOGRAPH-2F84F;Lo;0;L;5674;;;;N;;;;;
+2F850;CJK COMPATIBILITY IDEOGRAPH-2F850;Lo;0;L;5207;;;;N;;;;;
+2F851;CJK COMPATIBILITY IDEOGRAPH-2F851;Lo;0;L;58EE;;;;N;;;;;
+2F852;CJK COMPATIBILITY IDEOGRAPH-2F852;Lo;0;L;57CE;;;;N;;;;;
+2F853;CJK COMPATIBILITY IDEOGRAPH-2F853;Lo;0;L;57F4;;;;N;;;;;
+2F854;CJK COMPATIBILITY IDEOGRAPH-2F854;Lo;0;L;580D;;;;N;;;;;
+2F855;CJK COMPATIBILITY IDEOGRAPH-2F855;Lo;0;L;578B;;;;N;;;;;
+2F856;CJK COMPATIBILITY IDEOGRAPH-2F856;Lo;0;L;5832;;;;N;;;;;
+2F857;CJK COMPATIBILITY IDEOGRAPH-2F857;Lo;0;L;5831;;;;N;;;;;
+2F858;CJK COMPATIBILITY IDEOGRAPH-2F858;Lo;0;L;58AC;;;;N;;;;;
+2F859;CJK COMPATIBILITY IDEOGRAPH-2F859;Lo;0;L;214E4;;;;N;;;;;
+2F85A;CJK COMPATIBILITY IDEOGRAPH-2F85A;Lo;0;L;58F2;;;;N;;;;;
+2F85B;CJK COMPATIBILITY IDEOGRAPH-2F85B;Lo;0;L;58F7;;;;N;;;;;
+2F85C;CJK COMPATIBILITY IDEOGRAPH-2F85C;Lo;0;L;5906;;;;N;;;;;
+2F85D;CJK COMPATIBILITY IDEOGRAPH-2F85D;Lo;0;L;591A;;;;N;;;;;
+2F85E;CJK COMPATIBILITY IDEOGRAPH-2F85E;Lo;0;L;5922;;;;N;;;;;
+2F85F;CJK COMPATIBILITY IDEOGRAPH-2F85F;Lo;0;L;5962;;;;N;;;;;
+2F860;CJK COMPATIBILITY IDEOGRAPH-2F860;Lo;0;L;216A8;;;;N;;;;;
+2F861;CJK COMPATIBILITY IDEOGRAPH-2F861;Lo;0;L;216EA;;;;N;;;;;
+2F862;CJK COMPATIBILITY IDEOGRAPH-2F862;Lo;0;L;59EC;;;;N;;;;;
+2F863;CJK COMPATIBILITY IDEOGRAPH-2F863;Lo;0;L;5A1B;;;;N;;;;;
+2F864;CJK COMPATIBILITY IDEOGRAPH-2F864;Lo;0;L;5A27;;;;N;;;;;
+2F865;CJK COMPATIBILITY IDEOGRAPH-2F865;Lo;0;L;59D8;;;;N;;;;;
+2F866;CJK COMPATIBILITY IDEOGRAPH-2F866;Lo;0;L;5A66;;;;N;;;;;
+2F867;CJK COMPATIBILITY IDEOGRAPH-2F867;Lo;0;L;36EE;;;;N;;;;;
+2F868;CJK COMPATIBILITY IDEOGRAPH-2F868;Lo;0;L;36FC;;;;N;;;;;
+2F869;CJK COMPATIBILITY IDEOGRAPH-2F869;Lo;0;L;5B08;;;;N;;;;;
+2F86A;CJK COMPATIBILITY IDEOGRAPH-2F86A;Lo;0;L;5B3E;;;;N;;;;;
+2F86B;CJK COMPATIBILITY IDEOGRAPH-2F86B;Lo;0;L;5B3E;;;;N;;;;;
+2F86C;CJK COMPATIBILITY IDEOGRAPH-2F86C;Lo;0;L;219C8;;;;N;;;;;
+2F86D;CJK COMPATIBILITY IDEOGRAPH-2F86D;Lo;0;L;5BC3;;;;N;;;;;
+2F86E;CJK COMPATIBILITY IDEOGRAPH-2F86E;Lo;0;L;5BD8;;;;N;;;;;
+2F86F;CJK COMPATIBILITY IDEOGRAPH-2F86F;Lo;0;L;5BE7;;;;N;;;;;
+2F870;CJK COMPATIBILITY IDEOGRAPH-2F870;Lo;0;L;5BF3;;;;N;;;;;
+2F871;CJK COMPATIBILITY IDEOGRAPH-2F871;Lo;0;L;21B18;;;;N;;;;;
+2F872;CJK COMPATIBILITY IDEOGRAPH-2F872;Lo;0;L;5BFF;;;;N;;;;;
+2F873;CJK COMPATIBILITY IDEOGRAPH-2F873;Lo;0;L;5C06;;;;N;;;;;
+2F874;CJK COMPATIBILITY IDEOGRAPH-2F874;Lo;0;L;5F53;;;;N;;;;;
+2F875;CJK COMPATIBILITY IDEOGRAPH-2F875;Lo;0;L;5C22;;;;N;;;;;
+2F876;CJK COMPATIBILITY IDEOGRAPH-2F876;Lo;0;L;3781;;;;N;;;;;
+2F877;CJK COMPATIBILITY IDEOGRAPH-2F877;Lo;0;L;5C60;;;;N;;;;;
+2F878;CJK COMPATIBILITY IDEOGRAPH-2F878;Lo;0;L;5C6E;;;;N;;;;;
+2F879;CJK COMPATIBILITY IDEOGRAPH-2F879;Lo;0;L;5CC0;;;;N;;;;;
+2F87A;CJK COMPATIBILITY IDEOGRAPH-2F87A;Lo;0;L;5C8D;;;;N;;;;;
+2F87B;CJK COMPATIBILITY IDEOGRAPH-2F87B;Lo;0;L;21DE4;;;;N;;;;;
+2F87C;CJK COMPATIBILITY IDEOGRAPH-2F87C;Lo;0;L;5D43;;;;N;;;;;
+2F87D;CJK COMPATIBILITY IDEOGRAPH-2F87D;Lo;0;L;21DE6;;;;N;;;;;
+2F87E;CJK COMPATIBILITY IDEOGRAPH-2F87E;Lo;0;L;5D6E;;;;N;;;;;
+2F87F;CJK COMPATIBILITY IDEOGRAPH-2F87F;Lo;0;L;5D6B;;;;N;;;;;
+2F880;CJK COMPATIBILITY IDEOGRAPH-2F880;Lo;0;L;5D7C;;;;N;;;;;
+2F881;CJK COMPATIBILITY IDEOGRAPH-2F881;Lo;0;L;5DE1;;;;N;;;;;
+2F882;CJK COMPATIBILITY IDEOGRAPH-2F882;Lo;0;L;5DE2;;;;N;;;;;
+2F883;CJK COMPATIBILITY IDEOGRAPH-2F883;Lo;0;L;382F;;;;N;;;;;
+2F884;CJK COMPATIBILITY IDEOGRAPH-2F884;Lo;0;L;5DFD;;;;N;;;;;
+2F885;CJK COMPATIBILITY IDEOGRAPH-2F885;Lo;0;L;5E28;;;;N;;;;;
+2F886;CJK COMPATIBILITY IDEOGRAPH-2F886;Lo;0;L;5E3D;;;;N;;;;;
+2F887;CJK COMPATIBILITY IDEOGRAPH-2F887;Lo;0;L;5E69;;;;N;;;;;
+2F888;CJK COMPATIBILITY IDEOGRAPH-2F888;Lo;0;L;3862;;;;N;;;;;
+2F889;CJK COMPATIBILITY IDEOGRAPH-2F889;Lo;0;L;22183;;;;N;;;;;
+2F88A;CJK COMPATIBILITY IDEOGRAPH-2F88A;Lo;0;L;387C;;;;N;;;;;
+2F88B;CJK COMPATIBILITY IDEOGRAPH-2F88B;Lo;0;L;5EB0;;;;N;;;;;
+2F88C;CJK COMPATIBILITY IDEOGRAPH-2F88C;Lo;0;L;5EB3;;;;N;;;;;
+2F88D;CJK COMPATIBILITY IDEOGRAPH-2F88D;Lo;0;L;5EB6;;;;N;;;;;
+2F88E;CJK COMPATIBILITY IDEOGRAPH-2F88E;Lo;0;L;5ECA;;;;N;;;;;
+2F88F;CJK COMPATIBILITY IDEOGRAPH-2F88F;Lo;0;L;2A392;;;;N;;;;;
+2F890;CJK COMPATIBILITY IDEOGRAPH-2F890;Lo;0;L;5EFE;;;;N;;;;;
+2F891;CJK COMPATIBILITY IDEOGRAPH-2F891;Lo;0;L;22331;;;;N;;;;;
+2F892;CJK COMPATIBILITY IDEOGRAPH-2F892;Lo;0;L;22331;;;;N;;;;;
+2F893;CJK COMPATIBILITY IDEOGRAPH-2F893;Lo;0;L;8201;;;;N;;;;;
+2F894;CJK COMPATIBILITY IDEOGRAPH-2F894;Lo;0;L;5F22;;;;N;;;;;
+2F895;CJK COMPATIBILITY IDEOGRAPH-2F895;Lo;0;L;5F22;;;;N;;;;;
+2F896;CJK COMPATIBILITY IDEOGRAPH-2F896;Lo;0;L;38C7;;;;N;;;;;
+2F897;CJK COMPATIBILITY IDEOGRAPH-2F897;Lo;0;L;232B8;;;;N;;;;;
+2F898;CJK COMPATIBILITY IDEOGRAPH-2F898;Lo;0;L;261DA;;;;N;;;;;
+2F899;CJK COMPATIBILITY IDEOGRAPH-2F899;Lo;0;L;5F62;;;;N;;;;;
+2F89A;CJK COMPATIBILITY IDEOGRAPH-2F89A;Lo;0;L;5F6B;;;;N;;;;;
+2F89B;CJK COMPATIBILITY IDEOGRAPH-2F89B;Lo;0;L;38E3;;;;N;;;;;
+2F89C;CJK COMPATIBILITY IDEOGRAPH-2F89C;Lo;0;L;5F9A;;;;N;;;;;
+2F89D;CJK COMPATIBILITY IDEOGRAPH-2F89D;Lo;0;L;5FCD;;;;N;;;;;
+2F89E;CJK COMPATIBILITY IDEOGRAPH-2F89E;Lo;0;L;5FD7;;;;N;;;;;
+2F89F;CJK COMPATIBILITY IDEOGRAPH-2F89F;Lo;0;L;5FF9;;;;N;;;;;
+2F8A0;CJK COMPATIBILITY IDEOGRAPH-2F8A0;Lo;0;L;6081;;;;N;;;;;
+2F8A1;CJK COMPATIBILITY IDEOGRAPH-2F8A1;Lo;0;L;393A;;;;N;;;;;
+2F8A2;CJK COMPATIBILITY IDEOGRAPH-2F8A2;Lo;0;L;391C;;;;N;;;;;
+2F8A3;CJK COMPATIBILITY IDEOGRAPH-2F8A3;Lo;0;L;6094;;;;N;;;;;
+2F8A4;CJK COMPATIBILITY IDEOGRAPH-2F8A4;Lo;0;L;226D4;;;;N;;;;;
+2F8A5;CJK COMPATIBILITY IDEOGRAPH-2F8A5;Lo;0;L;60C7;;;;N;;;;;
+2F8A6;CJK COMPATIBILITY IDEOGRAPH-2F8A6;Lo;0;L;6148;;;;N;;;;;
+2F8A7;CJK COMPATIBILITY IDEOGRAPH-2F8A7;Lo;0;L;614C;;;;N;;;;;
+2F8A8;CJK COMPATIBILITY IDEOGRAPH-2F8A8;Lo;0;L;614E;;;;N;;;;;
+2F8A9;CJK COMPATIBILITY IDEOGRAPH-2F8A9;Lo;0;L;614C;;;;N;;;;;
+2F8AA;CJK COMPATIBILITY IDEOGRAPH-2F8AA;Lo;0;L;617A;;;;N;;;;;
+2F8AB;CJK COMPATIBILITY IDEOGRAPH-2F8AB;Lo;0;L;618E;;;;N;;;;;
+2F8AC;CJK COMPATIBILITY IDEOGRAPH-2F8AC;Lo;0;L;61B2;;;;N;;;;;
+2F8AD;CJK COMPATIBILITY IDEOGRAPH-2F8AD;Lo;0;L;61A4;;;;N;;;;;
+2F8AE;CJK COMPATIBILITY IDEOGRAPH-2F8AE;Lo;0;L;61AF;;;;N;;;;;
+2F8AF;CJK COMPATIBILITY IDEOGRAPH-2F8AF;Lo;0;L;61DE;;;;N;;;;;
+2F8B0;CJK COMPATIBILITY IDEOGRAPH-2F8B0;Lo;0;L;61F2;;;;N;;;;;
+2F8B1;CJK COMPATIBILITY IDEOGRAPH-2F8B1;Lo;0;L;61F6;;;;N;;;;;
+2F8B2;CJK COMPATIBILITY IDEOGRAPH-2F8B2;Lo;0;L;6210;;;;N;;;;;
+2F8B3;CJK COMPATIBILITY IDEOGRAPH-2F8B3;Lo;0;L;621B;;;;N;;;;;
+2F8B4;CJK COMPATIBILITY IDEOGRAPH-2F8B4;Lo;0;L;625D;;;;N;;;;;
+2F8B5;CJK COMPATIBILITY IDEOGRAPH-2F8B5;Lo;0;L;62B1;;;;N;;;;;
+2F8B6;CJK COMPATIBILITY IDEOGRAPH-2F8B6;Lo;0;L;62D4;;;;N;;;;;
+2F8B7;CJK COMPATIBILITY IDEOGRAPH-2F8B7;Lo;0;L;6350;;;;N;;;;;
+2F8B8;CJK COMPATIBILITY IDEOGRAPH-2F8B8;Lo;0;L;22B0C;;;;N;;;;;
+2F8B9;CJK COMPATIBILITY IDEOGRAPH-2F8B9;Lo;0;L;633D;;;;N;;;;;
+2F8BA;CJK COMPATIBILITY IDEOGRAPH-2F8BA;Lo;0;L;62FC;;;;N;;;;;
+2F8BB;CJK COMPATIBILITY IDEOGRAPH-2F8BB;Lo;0;L;6368;;;;N;;;;;
+2F8BC;CJK COMPATIBILITY IDEOGRAPH-2F8BC;Lo;0;L;6383;;;;N;;;;;
+2F8BD;CJK COMPATIBILITY IDEOGRAPH-2F8BD;Lo;0;L;63E4;;;;N;;;;;
+2F8BE;CJK COMPATIBILITY IDEOGRAPH-2F8BE;Lo;0;L;22BF1;;;;N;;;;;
+2F8BF;CJK COMPATIBILITY IDEOGRAPH-2F8BF;Lo;0;L;6422;;;;N;;;;;
+2F8C0;CJK COMPATIBILITY IDEOGRAPH-2F8C0;Lo;0;L;63C5;;;;N;;;;;
+2F8C1;CJK COMPATIBILITY IDEOGRAPH-2F8C1;Lo;0;L;63A9;;;;N;;;;;
+2F8C2;CJK COMPATIBILITY IDEOGRAPH-2F8C2;Lo;0;L;3A2E;;;;N;;;;;
+2F8C3;CJK COMPATIBILITY IDEOGRAPH-2F8C3;Lo;0;L;6469;;;;N;;;;;
+2F8C4;CJK COMPATIBILITY IDEOGRAPH-2F8C4;Lo;0;L;647E;;;;N;;;;;
+2F8C5;CJK COMPATIBILITY IDEOGRAPH-2F8C5;Lo;0;L;649D;;;;N;;;;;
+2F8C6;CJK COMPATIBILITY IDEOGRAPH-2F8C6;Lo;0;L;6477;;;;N;;;;;
+2F8C7;CJK COMPATIBILITY IDEOGRAPH-2F8C7;Lo;0;L;3A6C;;;;N;;;;;
+2F8C8;CJK COMPATIBILITY IDEOGRAPH-2F8C8;Lo;0;L;654F;;;;N;;;;;
+2F8C9;CJK COMPATIBILITY IDEOGRAPH-2F8C9;Lo;0;L;656C;;;;N;;;;;
+2F8CA;CJK COMPATIBILITY IDEOGRAPH-2F8CA;Lo;0;L;2300A;;;;N;;;;;
+2F8CB;CJK COMPATIBILITY IDEOGRAPH-2F8CB;Lo;0;L;65E3;;;;N;;;;;
+2F8CC;CJK COMPATIBILITY IDEOGRAPH-2F8CC;Lo;0;L;66F8;;;;N;;;;;
+2F8CD;CJK COMPATIBILITY IDEOGRAPH-2F8CD;Lo;0;L;6649;;;;N;;;;;
+2F8CE;CJK COMPATIBILITY IDEOGRAPH-2F8CE;Lo;0;L;3B19;;;;N;;;;;
+2F8CF;CJK COMPATIBILITY IDEOGRAPH-2F8CF;Lo;0;L;6691;;;;N;;;;;
+2F8D0;CJK COMPATIBILITY IDEOGRAPH-2F8D0;Lo;0;L;3B08;;;;N;;;;;
+2F8D1;CJK COMPATIBILITY IDEOGRAPH-2F8D1;Lo;0;L;3AE4;;;;N;;;;;
+2F8D2;CJK COMPATIBILITY IDEOGRAPH-2F8D2;Lo;0;L;5192;;;;N;;;;;
+2F8D3;CJK COMPATIBILITY IDEOGRAPH-2F8D3;Lo;0;L;5195;;;;N;;;;;
+2F8D4;CJK COMPATIBILITY IDEOGRAPH-2F8D4;Lo;0;L;6700;;;;N;;;;;
+2F8D5;CJK COMPATIBILITY IDEOGRAPH-2F8D5;Lo;0;L;669C;;;;N;;;;;
+2F8D6;CJK COMPATIBILITY IDEOGRAPH-2F8D6;Lo;0;L;80AD;;;;N;;;;;
+2F8D7;CJK COMPATIBILITY IDEOGRAPH-2F8D7;Lo;0;L;43D9;;;;N;;;;;
+2F8D8;CJK COMPATIBILITY IDEOGRAPH-2F8D8;Lo;0;L;6717;;;;N;;;;;
+2F8D9;CJK COMPATIBILITY IDEOGRAPH-2F8D9;Lo;0;L;671B;;;;N;;;;;
+2F8DA;CJK COMPATIBILITY IDEOGRAPH-2F8DA;Lo;0;L;6721;;;;N;;;;;
+2F8DB;CJK COMPATIBILITY IDEOGRAPH-2F8DB;Lo;0;L;675E;;;;N;;;;;
+2F8DC;CJK COMPATIBILITY IDEOGRAPH-2F8DC;Lo;0;L;6753;;;;N;;;;;
+2F8DD;CJK COMPATIBILITY IDEOGRAPH-2F8DD;Lo;0;L;233C3;;;;N;;;;;
+2F8DE;CJK COMPATIBILITY IDEOGRAPH-2F8DE;Lo;0;L;3B49;;;;N;;;;;
+2F8DF;CJK COMPATIBILITY IDEOGRAPH-2F8DF;Lo;0;L;67FA;;;;N;;;;;
+2F8E0;CJK COMPATIBILITY IDEOGRAPH-2F8E0;Lo;0;L;6785;;;;N;;;;;
+2F8E1;CJK COMPATIBILITY IDEOGRAPH-2F8E1;Lo;0;L;6852;;;;N;;;;;
+2F8E2;CJK COMPATIBILITY IDEOGRAPH-2F8E2;Lo;0;L;6885;;;;N;;;;;
+2F8E3;CJK COMPATIBILITY IDEOGRAPH-2F8E3;Lo;0;L;2346D;;;;N;;;;;
+2F8E4;CJK COMPATIBILITY IDEOGRAPH-2F8E4;Lo;0;L;688E;;;;N;;;;;
+2F8E5;CJK COMPATIBILITY IDEOGRAPH-2F8E5;Lo;0;L;681F;;;;N;;;;;
+2F8E6;CJK COMPATIBILITY IDEOGRAPH-2F8E6;Lo;0;L;6914;;;;N;;;;;
+2F8E7;CJK COMPATIBILITY IDEOGRAPH-2F8E7;Lo;0;L;3B9D;;;;N;;;;;
+2F8E8;CJK COMPATIBILITY IDEOGRAPH-2F8E8;Lo;0;L;6942;;;;N;;;;;
+2F8E9;CJK COMPATIBILITY IDEOGRAPH-2F8E9;Lo;0;L;69A3;;;;N;;;;;
+2F8EA;CJK COMPATIBILITY IDEOGRAPH-2F8EA;Lo;0;L;69EA;;;;N;;;;;
+2F8EB;CJK COMPATIBILITY IDEOGRAPH-2F8EB;Lo;0;L;6AA8;;;;N;;;;;
+2F8EC;CJK COMPATIBILITY IDEOGRAPH-2F8EC;Lo;0;L;236A3;;;;N;;;;;
+2F8ED;CJK COMPATIBILITY IDEOGRAPH-2F8ED;Lo;0;L;6ADB;;;;N;;;;;
+2F8EE;CJK COMPATIBILITY IDEOGRAPH-2F8EE;Lo;0;L;3C18;;;;N;;;;;
+2F8EF;CJK COMPATIBILITY IDEOGRAPH-2F8EF;Lo;0;L;6B21;;;;N;;;;;
+2F8F0;CJK COMPATIBILITY IDEOGRAPH-2F8F0;Lo;0;L;238A7;;;;N;;;;;
+2F8F1;CJK COMPATIBILITY IDEOGRAPH-2F8F1;Lo;0;L;6B54;;;;N;;;;;
+2F8F2;CJK COMPATIBILITY IDEOGRAPH-2F8F2;Lo;0;L;3C4E;;;;N;;;;;
+2F8F3;CJK COMPATIBILITY IDEOGRAPH-2F8F3;Lo;0;L;6B72;;;;N;;;;;
+2F8F4;CJK COMPATIBILITY IDEOGRAPH-2F8F4;Lo;0;L;6B9F;;;;N;;;;;
+2F8F5;CJK COMPATIBILITY IDEOGRAPH-2F8F5;Lo;0;L;6BBA;;;;N;;;;;
+2F8F6;CJK COMPATIBILITY IDEOGRAPH-2F8F6;Lo;0;L;6BBB;;;;N;;;;;
+2F8F7;CJK COMPATIBILITY IDEOGRAPH-2F8F7;Lo;0;L;23A8D;;;;N;;;;;
+2F8F8;CJK COMPATIBILITY IDEOGRAPH-2F8F8;Lo;0;L;21D0B;;;;N;;;;;
+2F8F9;CJK COMPATIBILITY IDEOGRAPH-2F8F9;Lo;0;L;23AFA;;;;N;;;;;
+2F8FA;CJK COMPATIBILITY IDEOGRAPH-2F8FA;Lo;0;L;6C4E;;;;N;;;;;
+2F8FB;CJK COMPATIBILITY IDEOGRAPH-2F8FB;Lo;0;L;23CBC;;;;N;;;;;
+2F8FC;CJK COMPATIBILITY IDEOGRAPH-2F8FC;Lo;0;L;6CBF;;;;N;;;;;
+2F8FD;CJK COMPATIBILITY IDEOGRAPH-2F8FD;Lo;0;L;6CCD;;;;N;;;;;
+2F8FE;CJK COMPATIBILITY IDEOGRAPH-2F8FE;Lo;0;L;6C67;;;;N;;;;;
+2F8FF;CJK COMPATIBILITY IDEOGRAPH-2F8FF;Lo;0;L;6D16;;;;N;;;;;
+2F900;CJK COMPATIBILITY IDEOGRAPH-2F900;Lo;0;L;6D3E;;;;N;;;;;
+2F901;CJK COMPATIBILITY IDEOGRAPH-2F901;Lo;0;L;6D77;;;;N;;;;;
+2F902;CJK COMPATIBILITY IDEOGRAPH-2F902;Lo;0;L;6D41;;;;N;;;;;
+2F903;CJK COMPATIBILITY IDEOGRAPH-2F903;Lo;0;L;6D69;;;;N;;;;;
+2F904;CJK COMPATIBILITY IDEOGRAPH-2F904;Lo;0;L;6D78;;;;N;;;;;
+2F905;CJK COMPATIBILITY IDEOGRAPH-2F905;Lo;0;L;6D85;;;;N;;;;;
+2F906;CJK COMPATIBILITY IDEOGRAPH-2F906;Lo;0;L;23D1E;;;;N;;;;;
+2F907;CJK COMPATIBILITY IDEOGRAPH-2F907;Lo;0;L;6D34;;;;N;;;;;
+2F908;CJK COMPATIBILITY IDEOGRAPH-2F908;Lo;0;L;6E2F;;;;N;;;;;
+2F909;CJK COMPATIBILITY IDEOGRAPH-2F909;Lo;0;L;6E6E;;;;N;;;;;
+2F90A;CJK COMPATIBILITY IDEOGRAPH-2F90A;Lo;0;L;3D33;;;;N;;;;;
+2F90B;CJK COMPATIBILITY IDEOGRAPH-2F90B;Lo;0;L;6ECB;;;;N;;;;;
+2F90C;CJK COMPATIBILITY IDEOGRAPH-2F90C;Lo;0;L;6EC7;;;;N;;;;;
+2F90D;CJK COMPATIBILITY IDEOGRAPH-2F90D;Lo;0;L;23ED1;;;;N;;;;;
+2F90E;CJK COMPATIBILITY IDEOGRAPH-2F90E;Lo;0;L;6DF9;;;;N;;;;;
+2F90F;CJK COMPATIBILITY IDEOGRAPH-2F90F;Lo;0;L;6F6E;;;;N;;;;;
+2F910;CJK COMPATIBILITY IDEOGRAPH-2F910;Lo;0;L;23F5E;;;;N;;;;;
+2F911;CJK COMPATIBILITY IDEOGRAPH-2F911;Lo;0;L;23F8E;;;;N;;;;;
+2F912;CJK COMPATIBILITY IDEOGRAPH-2F912;Lo;0;L;6FC6;;;;N;;;;;
+2F913;CJK COMPATIBILITY IDEOGRAPH-2F913;Lo;0;L;7039;;;;N;;;;;
+2F914;CJK COMPATIBILITY IDEOGRAPH-2F914;Lo;0;L;701E;;;;N;;;;;
+2F915;CJK COMPATIBILITY IDEOGRAPH-2F915;Lo;0;L;701B;;;;N;;;;;
+2F916;CJK COMPATIBILITY IDEOGRAPH-2F916;Lo;0;L;3D96;;;;N;;;;;
+2F917;CJK COMPATIBILITY IDEOGRAPH-2F917;Lo;0;L;704A;;;;N;;;;;
+2F918;CJK COMPATIBILITY IDEOGRAPH-2F918;Lo;0;L;707D;;;;N;;;;;
+2F919;CJK COMPATIBILITY IDEOGRAPH-2F919;Lo;0;L;7077;;;;N;;;;;
+2F91A;CJK COMPATIBILITY IDEOGRAPH-2F91A;Lo;0;L;70AD;;;;N;;;;;
+2F91B;CJK COMPATIBILITY IDEOGRAPH-2F91B;Lo;0;L;20525;;;;N;;;;;
+2F91C;CJK COMPATIBILITY IDEOGRAPH-2F91C;Lo;0;L;7145;;;;N;;;;;
+2F91D;CJK COMPATIBILITY IDEOGRAPH-2F91D;Lo;0;L;24263;;;;N;;;;;
+2F91E;CJK COMPATIBILITY IDEOGRAPH-2F91E;Lo;0;L;719C;;;;N;;;;;
+2F91F;CJK COMPATIBILITY IDEOGRAPH-2F91F;Lo;0;L;243AB;;;;N;;;;;
+2F920;CJK COMPATIBILITY IDEOGRAPH-2F920;Lo;0;L;7228;;;;N;;;;;
+2F921;CJK COMPATIBILITY IDEOGRAPH-2F921;Lo;0;L;7235;;;;N;;;;;
+2F922;CJK COMPATIBILITY IDEOGRAPH-2F922;Lo;0;L;7250;;;;N;;;;;
+2F923;CJK COMPATIBILITY IDEOGRAPH-2F923;Lo;0;L;24608;;;;N;;;;;
+2F924;CJK COMPATIBILITY IDEOGRAPH-2F924;Lo;0;L;7280;;;;N;;;;;
+2F925;CJK COMPATIBILITY IDEOGRAPH-2F925;Lo;0;L;7295;;;;N;;;;;
+2F926;CJK COMPATIBILITY IDEOGRAPH-2F926;Lo;0;L;24735;;;;N;;;;;
+2F927;CJK COMPATIBILITY IDEOGRAPH-2F927;Lo;0;L;24814;;;;N;;;;;
+2F928;CJK COMPATIBILITY IDEOGRAPH-2F928;Lo;0;L;737A;;;;N;;;;;
+2F929;CJK COMPATIBILITY IDEOGRAPH-2F929;Lo;0;L;738B;;;;N;;;;;
+2F92A;CJK COMPATIBILITY IDEOGRAPH-2F92A;Lo;0;L;3EAC;;;;N;;;;;
+2F92B;CJK COMPATIBILITY IDEOGRAPH-2F92B;Lo;0;L;73A5;;;;N;;;;;
+2F92C;CJK COMPATIBILITY IDEOGRAPH-2F92C;Lo;0;L;3EB8;;;;N;;;;;
+2F92D;CJK COMPATIBILITY IDEOGRAPH-2F92D;Lo;0;L;3EB8;;;;N;;;;;
+2F92E;CJK COMPATIBILITY IDEOGRAPH-2F92E;Lo;0;L;7447;;;;N;;;;;
+2F92F;CJK COMPATIBILITY IDEOGRAPH-2F92F;Lo;0;L;745C;;;;N;;;;;
+2F930;CJK COMPATIBILITY IDEOGRAPH-2F930;Lo;0;L;7471;;;;N;;;;;
+2F931;CJK COMPATIBILITY IDEOGRAPH-2F931;Lo;0;L;7485;;;;N;;;;;
+2F932;CJK COMPATIBILITY IDEOGRAPH-2F932;Lo;0;L;74CA;;;;N;;;;;
+2F933;CJK COMPATIBILITY IDEOGRAPH-2F933;Lo;0;L;3F1B;;;;N;;;;;
+2F934;CJK COMPATIBILITY IDEOGRAPH-2F934;Lo;0;L;7524;;;;N;;;;;
+2F935;CJK COMPATIBILITY IDEOGRAPH-2F935;Lo;0;L;24C36;;;;N;;;;;
+2F936;CJK COMPATIBILITY IDEOGRAPH-2F936;Lo;0;L;753E;;;;N;;;;;
+2F937;CJK COMPATIBILITY IDEOGRAPH-2F937;Lo;0;L;24C92;;;;N;;;;;
+2F938;CJK COMPATIBILITY IDEOGRAPH-2F938;Lo;0;L;7570;;;;N;;;;;
+2F939;CJK COMPATIBILITY IDEOGRAPH-2F939;Lo;0;L;2219F;;;;N;;;;;
+2F93A;CJK COMPATIBILITY IDEOGRAPH-2F93A;Lo;0;L;7610;;;;N;;;;;
+2F93B;CJK COMPATIBILITY IDEOGRAPH-2F93B;Lo;0;L;24FA1;;;;N;;;;;
+2F93C;CJK COMPATIBILITY IDEOGRAPH-2F93C;Lo;0;L;24FB8;;;;N;;;;;
+2F93D;CJK COMPATIBILITY IDEOGRAPH-2F93D;Lo;0;L;25044;;;;N;;;;;
+2F93E;CJK COMPATIBILITY IDEOGRAPH-2F93E;Lo;0;L;3FFC;;;;N;;;;;
+2F93F;CJK COMPATIBILITY IDEOGRAPH-2F93F;Lo;0;L;4008;;;;N;;;;;
+2F940;CJK COMPATIBILITY IDEOGRAPH-2F940;Lo;0;L;76F4;;;;N;;;;;
+2F941;CJK COMPATIBILITY IDEOGRAPH-2F941;Lo;0;L;250F3;;;;N;;;;;
+2F942;CJK COMPATIBILITY IDEOGRAPH-2F942;Lo;0;L;250F2;;;;N;;;;;
+2F943;CJK COMPATIBILITY IDEOGRAPH-2F943;Lo;0;L;25119;;;;N;;;;;
+2F944;CJK COMPATIBILITY IDEOGRAPH-2F944;Lo;0;L;25133;;;;N;;;;;
+2F945;CJK COMPATIBILITY IDEOGRAPH-2F945;Lo;0;L;771E;;;;N;;;;;
+2F946;CJK COMPATIBILITY IDEOGRAPH-2F946;Lo;0;L;771F;;;;N;;;;;
+2F947;CJK COMPATIBILITY IDEOGRAPH-2F947;Lo;0;L;771F;;;;N;;;;;
+2F948;CJK COMPATIBILITY IDEOGRAPH-2F948;Lo;0;L;774A;;;;N;;;;;
+2F949;CJK COMPATIBILITY IDEOGRAPH-2F949;Lo;0;L;4039;;;;N;;;;;
+2F94A;CJK COMPATIBILITY IDEOGRAPH-2F94A;Lo;0;L;778B;;;;N;;;;;
+2F94B;CJK COMPATIBILITY IDEOGRAPH-2F94B;Lo;0;L;4046;;;;N;;;;;
+2F94C;CJK COMPATIBILITY IDEOGRAPH-2F94C;Lo;0;L;4096;;;;N;;;;;
+2F94D;CJK COMPATIBILITY IDEOGRAPH-2F94D;Lo;0;L;2541D;;;;N;;;;;
+2F94E;CJK COMPATIBILITY IDEOGRAPH-2F94E;Lo;0;L;784E;;;;N;;;;;
+2F94F;CJK COMPATIBILITY IDEOGRAPH-2F94F;Lo;0;L;788C;;;;N;;;;;
+2F950;CJK COMPATIBILITY IDEOGRAPH-2F950;Lo;0;L;78CC;;;;N;;;;;
+2F951;CJK COMPATIBILITY IDEOGRAPH-2F951;Lo;0;L;40E3;;;;N;;;;;
+2F952;CJK COMPATIBILITY IDEOGRAPH-2F952;Lo;0;L;25626;;;;N;;;;;
+2F953;CJK COMPATIBILITY IDEOGRAPH-2F953;Lo;0;L;7956;;;;N;;;;;
+2F954;CJK COMPATIBILITY IDEOGRAPH-2F954;Lo;0;L;2569A;;;;N;;;;;
+2F955;CJK COMPATIBILITY IDEOGRAPH-2F955;Lo;0;L;256C5;;;;N;;;;;
+2F956;CJK COMPATIBILITY IDEOGRAPH-2F956;Lo;0;L;798F;;;;N;;;;;
+2F957;CJK COMPATIBILITY IDEOGRAPH-2F957;Lo;0;L;79EB;;;;N;;;;;
+2F958;CJK COMPATIBILITY IDEOGRAPH-2F958;Lo;0;L;412F;;;;N;;;;;
+2F959;CJK COMPATIBILITY IDEOGRAPH-2F959;Lo;0;L;7A40;;;;N;;;;;
+2F95A;CJK COMPATIBILITY IDEOGRAPH-2F95A;Lo;0;L;7A4A;;;;N;;;;;
+2F95B;CJK COMPATIBILITY IDEOGRAPH-2F95B;Lo;0;L;7A4F;;;;N;;;;;
+2F95C;CJK COMPATIBILITY IDEOGRAPH-2F95C;Lo;0;L;2597C;;;;N;;;;;
+2F95D;CJK COMPATIBILITY IDEOGRAPH-2F95D;Lo;0;L;25AA7;;;;N;;;;;
+2F95E;CJK COMPATIBILITY IDEOGRAPH-2F95E;Lo;0;L;25AA7;;;;N;;;;;
+2F95F;CJK COMPATIBILITY IDEOGRAPH-2F95F;Lo;0;L;7AEE;;;;N;;;;;
+2F960;CJK COMPATIBILITY IDEOGRAPH-2F960;Lo;0;L;4202;;;;N;;;;;
+2F961;CJK COMPATIBILITY IDEOGRAPH-2F961;Lo;0;L;25BAB;;;;N;;;;;
+2F962;CJK COMPATIBILITY IDEOGRAPH-2F962;Lo;0;L;7BC6;;;;N;;;;;
+2F963;CJK COMPATIBILITY IDEOGRAPH-2F963;Lo;0;L;7BC9;;;;N;;;;;
+2F964;CJK COMPATIBILITY IDEOGRAPH-2F964;Lo;0;L;4227;;;;N;;;;;
+2F965;CJK COMPATIBILITY IDEOGRAPH-2F965;Lo;0;L;25C80;;;;N;;;;;
+2F966;CJK COMPATIBILITY IDEOGRAPH-2F966;Lo;0;L;7CD2;;;;N;;;;;
+2F967;CJK COMPATIBILITY IDEOGRAPH-2F967;Lo;0;L;42A0;;;;N;;;;;
+2F968;CJK COMPATIBILITY IDEOGRAPH-2F968;Lo;0;L;7CE8;;;;N;;;;;
+2F969;CJK COMPATIBILITY IDEOGRAPH-2F969;Lo;0;L;7CE3;;;;N;;;;;
+2F96A;CJK COMPATIBILITY IDEOGRAPH-2F96A;Lo;0;L;7D00;;;;N;;;;;
+2F96B;CJK COMPATIBILITY IDEOGRAPH-2F96B;Lo;0;L;25F86;;;;N;;;;;
+2F96C;CJK COMPATIBILITY IDEOGRAPH-2F96C;Lo;0;L;7D63;;;;N;;;;;
+2F96D;CJK COMPATIBILITY IDEOGRAPH-2F96D;Lo;0;L;4301;;;;N;;;;;
+2F96E;CJK COMPATIBILITY IDEOGRAPH-2F96E;Lo;0;L;7DC7;;;;N;;;;;
+2F96F;CJK COMPATIBILITY IDEOGRAPH-2F96F;Lo;0;L;7E02;;;;N;;;;;
+2F970;CJK COMPATIBILITY IDEOGRAPH-2F970;Lo;0;L;7E45;;;;N;;;;;
+2F971;CJK COMPATIBILITY IDEOGRAPH-2F971;Lo;0;L;4334;;;;N;;;;;
+2F972;CJK COMPATIBILITY IDEOGRAPH-2F972;Lo;0;L;26228;;;;N;;;;;
+2F973;CJK COMPATIBILITY IDEOGRAPH-2F973;Lo;0;L;26247;;;;N;;;;;
+2F974;CJK COMPATIBILITY IDEOGRAPH-2F974;Lo;0;L;4359;;;;N;;;;;
+2F975;CJK COMPATIBILITY IDEOGRAPH-2F975;Lo;0;L;262D9;;;;N;;;;;
+2F976;CJK COMPATIBILITY IDEOGRAPH-2F976;Lo;0;L;7F7A;;;;N;;;;;
+2F977;CJK COMPATIBILITY IDEOGRAPH-2F977;Lo;0;L;2633E;;;;N;;;;;
+2F978;CJK COMPATIBILITY IDEOGRAPH-2F978;Lo;0;L;7F95;;;;N;;;;;
+2F979;CJK COMPATIBILITY IDEOGRAPH-2F979;Lo;0;L;7FFA;;;;N;;;;;
+2F97A;CJK COMPATIBILITY IDEOGRAPH-2F97A;Lo;0;L;8005;;;;N;;;;;
+2F97B;CJK COMPATIBILITY IDEOGRAPH-2F97B;Lo;0;L;264DA;;;;N;;;;;
+2F97C;CJK COMPATIBILITY IDEOGRAPH-2F97C;Lo;0;L;26523;;;;N;;;;;
+2F97D;CJK COMPATIBILITY IDEOGRAPH-2F97D;Lo;0;L;8060;;;;N;;;;;
+2F97E;CJK COMPATIBILITY IDEOGRAPH-2F97E;Lo;0;L;265A8;;;;N;;;;;
+2F97F;CJK COMPATIBILITY IDEOGRAPH-2F97F;Lo;0;L;8070;;;;N;;;;;
+2F980;CJK COMPATIBILITY IDEOGRAPH-2F980;Lo;0;L;2335F;;;;N;;;;;
+2F981;CJK COMPATIBILITY IDEOGRAPH-2F981;Lo;0;L;43D5;;;;N;;;;;
+2F982;CJK COMPATIBILITY IDEOGRAPH-2F982;Lo;0;L;80B2;;;;N;;;;;
+2F983;CJK COMPATIBILITY IDEOGRAPH-2F983;Lo;0;L;8103;;;;N;;;;;
+2F984;CJK COMPATIBILITY IDEOGRAPH-2F984;Lo;0;L;440B;;;;N;;;;;
+2F985;CJK COMPATIBILITY IDEOGRAPH-2F985;Lo;0;L;813E;;;;N;;;;;
+2F986;CJK COMPATIBILITY IDEOGRAPH-2F986;Lo;0;L;5AB5;;;;N;;;;;
+2F987;CJK COMPATIBILITY IDEOGRAPH-2F987;Lo;0;L;267A7;;;;N;;;;;
+2F988;CJK COMPATIBILITY IDEOGRAPH-2F988;Lo;0;L;267B5;;;;N;;;;;
+2F989;CJK COMPATIBILITY IDEOGRAPH-2F989;Lo;0;L;23393;;;;N;;;;;
+2F98A;CJK COMPATIBILITY IDEOGRAPH-2F98A;Lo;0;L;2339C;;;;N;;;;;
+2F98B;CJK COMPATIBILITY IDEOGRAPH-2F98B;Lo;0;L;8201;;;;N;;;;;
+2F98C;CJK COMPATIBILITY IDEOGRAPH-2F98C;Lo;0;L;8204;;;;N;;;;;
+2F98D;CJK COMPATIBILITY IDEOGRAPH-2F98D;Lo;0;L;8F9E;;;;N;;;;;
+2F98E;CJK COMPATIBILITY IDEOGRAPH-2F98E;Lo;0;L;446B;;;;N;;;;;
+2F98F;CJK COMPATIBILITY IDEOGRAPH-2F98F;Lo;0;L;8291;;;;N;;;;;
+2F990;CJK COMPATIBILITY IDEOGRAPH-2F990;Lo;0;L;828B;;;;N;;;;;
+2F991;CJK COMPATIBILITY IDEOGRAPH-2F991;Lo;0;L;829D;;;;N;;;;;
+2F992;CJK COMPATIBILITY IDEOGRAPH-2F992;Lo;0;L;52B3;;;;N;;;;;
+2F993;CJK COMPATIBILITY IDEOGRAPH-2F993;Lo;0;L;82B1;;;;N;;;;;
+2F994;CJK COMPATIBILITY IDEOGRAPH-2F994;Lo;0;L;82B3;;;;N;;;;;
+2F995;CJK COMPATIBILITY IDEOGRAPH-2F995;Lo;0;L;82BD;;;;N;;;;;
+2F996;CJK COMPATIBILITY IDEOGRAPH-2F996;Lo;0;L;82E6;;;;N;;;;;
+2F997;CJK COMPATIBILITY IDEOGRAPH-2F997;Lo;0;L;26B3C;;;;N;;;;;
+2F998;CJK COMPATIBILITY IDEOGRAPH-2F998;Lo;0;L;82E5;;;;N;;;;;
+2F999;CJK COMPATIBILITY IDEOGRAPH-2F999;Lo;0;L;831D;;;;N;;;;;
+2F99A;CJK COMPATIBILITY IDEOGRAPH-2F99A;Lo;0;L;8363;;;;N;;;;;
+2F99B;CJK COMPATIBILITY IDEOGRAPH-2F99B;Lo;0;L;83AD;;;;N;;;;;
+2F99C;CJK COMPATIBILITY IDEOGRAPH-2F99C;Lo;0;L;8323;;;;N;;;;;
+2F99D;CJK COMPATIBILITY IDEOGRAPH-2F99D;Lo;0;L;83BD;;;;N;;;;;
+2F99E;CJK COMPATIBILITY IDEOGRAPH-2F99E;Lo;0;L;83E7;;;;N;;;;;
+2F99F;CJK COMPATIBILITY IDEOGRAPH-2F99F;Lo;0;L;8457;;;;N;;;;;
+2F9A0;CJK COMPATIBILITY IDEOGRAPH-2F9A0;Lo;0;L;8353;;;;N;;;;;
+2F9A1;CJK COMPATIBILITY IDEOGRAPH-2F9A1;Lo;0;L;83CA;;;;N;;;;;
+2F9A2;CJK COMPATIBILITY IDEOGRAPH-2F9A2;Lo;0;L;83CC;;;;N;;;;;
+2F9A3;CJK COMPATIBILITY IDEOGRAPH-2F9A3;Lo;0;L;83DC;;;;N;;;;;
+2F9A4;CJK COMPATIBILITY IDEOGRAPH-2F9A4;Lo;0;L;26C36;;;;N;;;;;
+2F9A5;CJK COMPATIBILITY IDEOGRAPH-2F9A5;Lo;0;L;26D6B;;;;N;;;;;
+2F9A6;CJK COMPATIBILITY IDEOGRAPH-2F9A6;Lo;0;L;26CD5;;;;N;;;;;
+2F9A7;CJK COMPATIBILITY IDEOGRAPH-2F9A7;Lo;0;L;452B;;;;N;;;;;
+2F9A8;CJK COMPATIBILITY IDEOGRAPH-2F9A8;Lo;0;L;84F1;;;;N;;;;;
+2F9A9;CJK COMPATIBILITY IDEOGRAPH-2F9A9;Lo;0;L;84F3;;;;N;;;;;
+2F9AA;CJK COMPATIBILITY IDEOGRAPH-2F9AA;Lo;0;L;8516;;;;N;;;;;
+2F9AB;CJK COMPATIBILITY IDEOGRAPH-2F9AB;Lo;0;L;273CA;;;;N;;;;;
+2F9AC;CJK COMPATIBILITY IDEOGRAPH-2F9AC;Lo;0;L;8564;;;;N;;;;;
+2F9AD;CJK COMPATIBILITY IDEOGRAPH-2F9AD;Lo;0;L;26F2C;;;;N;;;;;
+2F9AE;CJK COMPATIBILITY IDEOGRAPH-2F9AE;Lo;0;L;455D;;;;N;;;;;
+2F9AF;CJK COMPATIBILITY IDEOGRAPH-2F9AF;Lo;0;L;4561;;;;N;;;;;
+2F9B0;CJK COMPATIBILITY IDEOGRAPH-2F9B0;Lo;0;L;26FB1;;;;N;;;;;
+2F9B1;CJK COMPATIBILITY IDEOGRAPH-2F9B1;Lo;0;L;270D2;;;;N;;;;;
+2F9B2;CJK COMPATIBILITY IDEOGRAPH-2F9B2;Lo;0;L;456B;;;;N;;;;;
+2F9B3;CJK COMPATIBILITY IDEOGRAPH-2F9B3;Lo;0;L;8650;;;;N;;;;;
+2F9B4;CJK COMPATIBILITY IDEOGRAPH-2F9B4;Lo;0;L;865C;;;;N;;;;;
+2F9B5;CJK COMPATIBILITY IDEOGRAPH-2F9B5;Lo;0;L;8667;;;;N;;;;;
+2F9B6;CJK COMPATIBILITY IDEOGRAPH-2F9B6;Lo;0;L;8669;;;;N;;;;;
+2F9B7;CJK COMPATIBILITY IDEOGRAPH-2F9B7;Lo;0;L;86A9;;;;N;;;;;
+2F9B8;CJK COMPATIBILITY IDEOGRAPH-2F9B8;Lo;0;L;8688;;;;N;;;;;
+2F9B9;CJK COMPATIBILITY IDEOGRAPH-2F9B9;Lo;0;L;870E;;;;N;;;;;
+2F9BA;CJK COMPATIBILITY IDEOGRAPH-2F9BA;Lo;0;L;86E2;;;;N;;;;;
+2F9BB;CJK COMPATIBILITY IDEOGRAPH-2F9BB;Lo;0;L;8779;;;;N;;;;;
+2F9BC;CJK COMPATIBILITY IDEOGRAPH-2F9BC;Lo;0;L;8728;;;;N;;;;;
+2F9BD;CJK COMPATIBILITY IDEOGRAPH-2F9BD;Lo;0;L;876B;;;;N;;;;;
+2F9BE;CJK COMPATIBILITY IDEOGRAPH-2F9BE;Lo;0;L;8786;;;;N;;;;;
+2F9BF;CJK COMPATIBILITY IDEOGRAPH-2F9BF;Lo;0;L;45D7;;;;N;;;;;
+2F9C0;CJK COMPATIBILITY IDEOGRAPH-2F9C0;Lo;0;L;87E1;;;;N;;;;;
+2F9C1;CJK COMPATIBILITY IDEOGRAPH-2F9C1;Lo;0;L;8801;;;;N;;;;;
+2F9C2;CJK COMPATIBILITY IDEOGRAPH-2F9C2;Lo;0;L;45F9;;;;N;;;;;
+2F9C3;CJK COMPATIBILITY IDEOGRAPH-2F9C3;Lo;0;L;8860;;;;N;;;;;
+2F9C4;CJK COMPATIBILITY IDEOGRAPH-2F9C4;Lo;0;L;8863;;;;N;;;;;
+2F9C5;CJK COMPATIBILITY IDEOGRAPH-2F9C5;Lo;0;L;27667;;;;N;;;;;
+2F9C6;CJK COMPATIBILITY IDEOGRAPH-2F9C6;Lo;0;L;88D7;;;;N;;;;;
+2F9C7;CJK COMPATIBILITY IDEOGRAPH-2F9C7;Lo;0;L;88DE;;;;N;;;;;
+2F9C8;CJK COMPATIBILITY IDEOGRAPH-2F9C8;Lo;0;L;4635;;;;N;;;;;
+2F9C9;CJK COMPATIBILITY IDEOGRAPH-2F9C9;Lo;0;L;88FA;;;;N;;;;;
+2F9CA;CJK COMPATIBILITY IDEOGRAPH-2F9CA;Lo;0;L;34BB;;;;N;;;;;
+2F9CB;CJK COMPATIBILITY IDEOGRAPH-2F9CB;Lo;0;L;278AE;;;;N;;;;;
+2F9CC;CJK COMPATIBILITY IDEOGRAPH-2F9CC;Lo;0;L;27966;;;;N;;;;;
+2F9CD;CJK COMPATIBILITY IDEOGRAPH-2F9CD;Lo;0;L;46BE;;;;N;;;;;
+2F9CE;CJK COMPATIBILITY IDEOGRAPH-2F9CE;Lo;0;L;46C7;;;;N;;;;;
+2F9CF;CJK COMPATIBILITY IDEOGRAPH-2F9CF;Lo;0;L;8AA0;;;;N;;;;;
+2F9D0;CJK COMPATIBILITY IDEOGRAPH-2F9D0;Lo;0;L;8AED;;;;N;;;;;
+2F9D1;CJK COMPATIBILITY IDEOGRAPH-2F9D1;Lo;0;L;8B8A;;;;N;;;;;
+2F9D2;CJK COMPATIBILITY IDEOGRAPH-2F9D2;Lo;0;L;8C55;;;;N;;;;;
+2F9D3;CJK COMPATIBILITY IDEOGRAPH-2F9D3;Lo;0;L;27CA8;;;;N;;;;;
+2F9D4;CJK COMPATIBILITY IDEOGRAPH-2F9D4;Lo;0;L;8CAB;;;;N;;;;;
+2F9D5;CJK COMPATIBILITY IDEOGRAPH-2F9D5;Lo;0;L;8CC1;;;;N;;;;;
+2F9D6;CJK COMPATIBILITY IDEOGRAPH-2F9D6;Lo;0;L;8D1B;;;;N;;;;;
+2F9D7;CJK COMPATIBILITY IDEOGRAPH-2F9D7;Lo;0;L;8D77;;;;N;;;;;
+2F9D8;CJK COMPATIBILITY IDEOGRAPH-2F9D8;Lo;0;L;27F2F;;;;N;;;;;
+2F9D9;CJK COMPATIBILITY IDEOGRAPH-2F9D9;Lo;0;L;20804;;;;N;;;;;
+2F9DA;CJK COMPATIBILITY IDEOGRAPH-2F9DA;Lo;0;L;8DCB;;;;N;;;;;
+2F9DB;CJK COMPATIBILITY IDEOGRAPH-2F9DB;Lo;0;L;8DBC;;;;N;;;;;
+2F9DC;CJK COMPATIBILITY IDEOGRAPH-2F9DC;Lo;0;L;8DF0;;;;N;;;;;
+2F9DD;CJK COMPATIBILITY IDEOGRAPH-2F9DD;Lo;0;L;208DE;;;;N;;;;;
+2F9DE;CJK COMPATIBILITY IDEOGRAPH-2F9DE;Lo;0;L;8ED4;;;;N;;;;;
+2F9DF;CJK COMPATIBILITY IDEOGRAPH-2F9DF;Lo;0;L;8F38;;;;N;;;;;
+2F9E0;CJK COMPATIBILITY IDEOGRAPH-2F9E0;Lo;0;L;285D2;;;;N;;;;;
+2F9E1;CJK COMPATIBILITY IDEOGRAPH-2F9E1;Lo;0;L;285ED;;;;N;;;;;
+2F9E2;CJK COMPATIBILITY IDEOGRAPH-2F9E2;Lo;0;L;9094;;;;N;;;;;
+2F9E3;CJK COMPATIBILITY IDEOGRAPH-2F9E3;Lo;0;L;90F1;;;;N;;;;;
+2F9E4;CJK COMPATIBILITY IDEOGRAPH-2F9E4;Lo;0;L;9111;;;;N;;;;;
+2F9E5;CJK COMPATIBILITY IDEOGRAPH-2F9E5;Lo;0;L;2872E;;;;N;;;;;
+2F9E6;CJK COMPATIBILITY IDEOGRAPH-2F9E6;Lo;0;L;911B;;;;N;;;;;
+2F9E7;CJK COMPATIBILITY IDEOGRAPH-2F9E7;Lo;0;L;9238;;;;N;;;;;
+2F9E8;CJK COMPATIBILITY IDEOGRAPH-2F9E8;Lo;0;L;92D7;;;;N;;;;;
+2F9E9;CJK COMPATIBILITY IDEOGRAPH-2F9E9;Lo;0;L;92D8;;;;N;;;;;
+2F9EA;CJK COMPATIBILITY IDEOGRAPH-2F9EA;Lo;0;L;927C;;;;N;;;;;
+2F9EB;CJK COMPATIBILITY IDEOGRAPH-2F9EB;Lo;0;L;93F9;;;;N;;;;;
+2F9EC;CJK COMPATIBILITY IDEOGRAPH-2F9EC;Lo;0;L;9415;;;;N;;;;;
+2F9ED;CJK COMPATIBILITY IDEOGRAPH-2F9ED;Lo;0;L;28BFA;;;;N;;;;;
+2F9EE;CJK COMPATIBILITY IDEOGRAPH-2F9EE;Lo;0;L;958B;;;;N;;;;;
+2F9EF;CJK COMPATIBILITY IDEOGRAPH-2F9EF;Lo;0;L;4995;;;;N;;;;;
+2F9F0;CJK COMPATIBILITY IDEOGRAPH-2F9F0;Lo;0;L;95B7;;;;N;;;;;
+2F9F1;CJK COMPATIBILITY IDEOGRAPH-2F9F1;Lo;0;L;28D77;;;;N;;;;;
+2F9F2;CJK COMPATIBILITY IDEOGRAPH-2F9F2;Lo;0;L;49E6;;;;N;;;;;
+2F9F3;CJK COMPATIBILITY IDEOGRAPH-2F9F3;Lo;0;L;96C3;;;;N;;;;;
+2F9F4;CJK COMPATIBILITY IDEOGRAPH-2F9F4;Lo;0;L;5DB2;;;;N;;;;;
+2F9F5;CJK COMPATIBILITY IDEOGRAPH-2F9F5;Lo;0;L;9723;;;;N;;;;;
+2F9F6;CJK COMPATIBILITY IDEOGRAPH-2F9F6;Lo;0;L;29145;;;;N;;;;;
+2F9F7;CJK COMPATIBILITY IDEOGRAPH-2F9F7;Lo;0;L;2921A;;;;N;;;;;
+2F9F8;CJK COMPATIBILITY IDEOGRAPH-2F9F8;Lo;0;L;4A6E;;;;N;;;;;
+2F9F9;CJK COMPATIBILITY IDEOGRAPH-2F9F9;Lo;0;L;4A76;;;;N;;;;;
+2F9FA;CJK COMPATIBILITY IDEOGRAPH-2F9FA;Lo;0;L;97E0;;;;N;;;;;
+2F9FB;CJK COMPATIBILITY IDEOGRAPH-2F9FB;Lo;0;L;2940A;;;;N;;;;;
+2F9FC;CJK COMPATIBILITY IDEOGRAPH-2F9FC;Lo;0;L;4AB2;;;;N;;;;;
+2F9FD;CJK COMPATIBILITY IDEOGRAPH-2F9FD;Lo;0;L;29496;;;;N;;;;;
+2F9FE;CJK COMPATIBILITY IDEOGRAPH-2F9FE;Lo;0;L;980B;;;;N;;;;;
+2F9FF;CJK COMPATIBILITY IDEOGRAPH-2F9FF;Lo;0;L;980B;;;;N;;;;;
+2FA00;CJK COMPATIBILITY IDEOGRAPH-2FA00;Lo;0;L;9829;;;;N;;;;;
+2FA01;CJK COMPATIBILITY IDEOGRAPH-2FA01;Lo;0;L;295B6;;;;N;;;;;
+2FA02;CJK COMPATIBILITY IDEOGRAPH-2FA02;Lo;0;L;98E2;;;;N;;;;;
+2FA03;CJK COMPATIBILITY IDEOGRAPH-2FA03;Lo;0;L;4B33;;;;N;;;;;
+2FA04;CJK COMPATIBILITY IDEOGRAPH-2FA04;Lo;0;L;9929;;;;N;;;;;
+2FA05;CJK COMPATIBILITY IDEOGRAPH-2FA05;Lo;0;L;99A7;;;;N;;;;;
+2FA06;CJK COMPATIBILITY IDEOGRAPH-2FA06;Lo;0;L;99C2;;;;N;;;;;
+2FA07;CJK COMPATIBILITY IDEOGRAPH-2FA07;Lo;0;L;99FE;;;;N;;;;;
+2FA08;CJK COMPATIBILITY IDEOGRAPH-2FA08;Lo;0;L;4BCE;;;;N;;;;;
+2FA09;CJK COMPATIBILITY IDEOGRAPH-2FA09;Lo;0;L;29B30;;;;N;;;;;
+2FA0A;CJK COMPATIBILITY IDEOGRAPH-2FA0A;Lo;0;L;9B12;;;;N;;;;;
+2FA0B;CJK COMPATIBILITY IDEOGRAPH-2FA0B;Lo;0;L;9C40;;;;N;;;;;
+2FA0C;CJK COMPATIBILITY IDEOGRAPH-2FA0C;Lo;0;L;9CFD;;;;N;;;;;
+2FA0D;CJK COMPATIBILITY IDEOGRAPH-2FA0D;Lo;0;L;4CCE;;;;N;;;;;
+2FA0E;CJK COMPATIBILITY IDEOGRAPH-2FA0E;Lo;0;L;4CED;;;;N;;;;;
+2FA0F;CJK COMPATIBILITY IDEOGRAPH-2FA0F;Lo;0;L;9D67;;;;N;;;;;
+2FA10;CJK COMPATIBILITY IDEOGRAPH-2FA10;Lo;0;L;2A0CE;;;;N;;;;;
+2FA11;CJK COMPATIBILITY IDEOGRAPH-2FA11;Lo;0;L;4CF8;;;;N;;;;;
+2FA12;CJK COMPATIBILITY IDEOGRAPH-2FA12;Lo;0;L;2A105;;;;N;;;;;
+2FA13;CJK COMPATIBILITY IDEOGRAPH-2FA13;Lo;0;L;2A20E;;;;N;;;;;
+2FA14;CJK COMPATIBILITY IDEOGRAPH-2FA14;Lo;0;L;2A291;;;;N;;;;;
+2FA15;CJK COMPATIBILITY IDEOGRAPH-2FA15;Lo;0;L;9EBB;;;;N;;;;;
+2FA16;CJK COMPATIBILITY IDEOGRAPH-2FA16;Lo;0;L;4D56;;;;N;;;;;
+2FA17;CJK COMPATIBILITY IDEOGRAPH-2FA17;Lo;0;L;9EF9;;;;N;;;;;
+2FA18;CJK COMPATIBILITY IDEOGRAPH-2FA18;Lo;0;L;9EFE;;;;N;;;;;
+2FA19;CJK COMPATIBILITY IDEOGRAPH-2FA19;Lo;0;L;9F05;;;;N;;;;;
+2FA1A;CJK COMPATIBILITY IDEOGRAPH-2FA1A;Lo;0;L;9F0F;;;;N;;;;;
+2FA1B;CJK COMPATIBILITY IDEOGRAPH-2FA1B;Lo;0;L;9F16;;;;N;;;;;
+2FA1C;CJK COMPATIBILITY IDEOGRAPH-2FA1C;Lo;0;L;9F3B;;;;N;;;;;
+2FA1D;CJK COMPATIBILITY IDEOGRAPH-2FA1D;Lo;0;L;2A600;;;;N;;;;;
+E0001;LANGUAGE TAG;Cf;0;BN;;;;;N;;;;;
+E0020;TAG SPACE;Cf;0;BN;;;;;N;;;;;
+E0021;TAG EXCLAMATION MARK;Cf;0;BN;;;;;N;;;;;
+E0022;TAG QUOTATION MARK;Cf;0;BN;;;;;N;;;;;
+E0023;TAG NUMBER SIGN;Cf;0;BN;;;;;N;;;;;
+E0024;TAG DOLLAR SIGN;Cf;0;BN;;;;;N;;;;;
+E0025;TAG PERCENT SIGN;Cf;0;BN;;;;;N;;;;;
+E0026;TAG AMPERSAND;Cf;0;BN;;;;;N;;;;;
+E0027;TAG APOSTROPHE;Cf;0;BN;;;;;N;;;;;
+E0028;TAG LEFT PARENTHESIS;Cf;0;BN;;;;;N;;;;;
+E0029;TAG RIGHT PARENTHESIS;Cf;0;BN;;;;;N;;;;;
+E002A;TAG ASTERISK;Cf;0;BN;;;;;N;;;;;
+E002B;TAG PLUS SIGN;Cf;0;BN;;;;;N;;;;;
+E002C;TAG COMMA;Cf;0;BN;;;;;N;;;;;
+E002D;TAG HYPHEN-MINUS;Cf;0;BN;;;;;N;;;;;
+E002E;TAG FULL STOP;Cf;0;BN;;;;;N;;;;;
+E002F;TAG SOLIDUS;Cf;0;BN;;;;;N;;;;;
+E0030;TAG DIGIT ZERO;Cf;0;BN;;;;;N;;;;;
+E0031;TAG DIGIT ONE;Cf;0;BN;;;;;N;;;;;
+E0032;TAG DIGIT TWO;Cf;0;BN;;;;;N;;;;;
+E0033;TAG DIGIT THREE;Cf;0;BN;;;;;N;;;;;
+E0034;TAG DIGIT FOUR;Cf;0;BN;;;;;N;;;;;
+E0035;TAG DIGIT FIVE;Cf;0;BN;;;;;N;;;;;
+E0036;TAG DIGIT SIX;Cf;0;BN;;;;;N;;;;;
+E0037;TAG DIGIT SEVEN;Cf;0;BN;;;;;N;;;;;
+E0038;TAG DIGIT EIGHT;Cf;0;BN;;;;;N;;;;;
+E0039;TAG DIGIT NINE;Cf;0;BN;;;;;N;;;;;
+E003A;TAG COLON;Cf;0;BN;;;;;N;;;;;
+E003B;TAG SEMICOLON;Cf;0;BN;;;;;N;;;;;
+E003C;TAG LESS-THAN SIGN;Cf;0;BN;;;;;N;;;;;
+E003D;TAG EQUALS SIGN;Cf;0;BN;;;;;N;;;;;
+E003E;TAG GREATER-THAN SIGN;Cf;0;BN;;;;;N;;;;;
+E003F;TAG QUESTION MARK;Cf;0;BN;;;;;N;;;;;
+E0040;TAG COMMERCIAL AT;Cf;0;BN;;;;;N;;;;;
+E0041;TAG LATIN CAPITAL LETTER A;Cf;0;BN;;;;;N;;;;;
+E0042;TAG LATIN CAPITAL LETTER B;Cf;0;BN;;;;;N;;;;;
+E0043;TAG LATIN CAPITAL LETTER C;Cf;0;BN;;;;;N;;;;;
+E0044;TAG LATIN CAPITAL LETTER D;Cf;0;BN;;;;;N;;;;;
+E0045;TAG LATIN CAPITAL LETTER E;Cf;0;BN;;;;;N;;;;;
+E0046;TAG LATIN CAPITAL LETTER F;Cf;0;BN;;;;;N;;;;;
+E0047;TAG LATIN CAPITAL LETTER G;Cf;0;BN;;;;;N;;;;;
+E0048;TAG LATIN CAPITAL LETTER H;Cf;0;BN;;;;;N;;;;;
+E0049;TAG LATIN CAPITAL LETTER I;Cf;0;BN;;;;;N;;;;;
+E004A;TAG LATIN CAPITAL LETTER J;Cf;0;BN;;;;;N;;;;;
+E004B;TAG LATIN CAPITAL LETTER K;Cf;0;BN;;;;;N;;;;;
+E004C;TAG LATIN CAPITAL LETTER L;Cf;0;BN;;;;;N;;;;;
+E004D;TAG LATIN CAPITAL LETTER M;Cf;0;BN;;;;;N;;;;;
+E004E;TAG LATIN CAPITAL LETTER N;Cf;0;BN;;;;;N;;;;;
+E004F;TAG LATIN CAPITAL LETTER O;Cf;0;BN;;;;;N;;;;;
+E0050;TAG LATIN CAPITAL LETTER P;Cf;0;BN;;;;;N;;;;;
+E0051;TAG LATIN CAPITAL LETTER Q;Cf;0;BN;;;;;N;;;;;
+E0052;TAG LATIN CAPITAL LETTER R;Cf;0;BN;;;;;N;;;;;
+E0053;TAG LATIN CAPITAL LETTER S;Cf;0;BN;;;;;N;;;;;
+E0054;TAG LATIN CAPITAL LETTER T;Cf;0;BN;;;;;N;;;;;
+E0055;TAG LATIN CAPITAL LETTER U;Cf;0;BN;;;;;N;;;;;
+E0056;TAG LATIN CAPITAL LETTER V;Cf;0;BN;;;;;N;;;;;
+E0057;TAG LATIN CAPITAL LETTER W;Cf;0;BN;;;;;N;;;;;
+E0058;TAG LATIN CAPITAL LETTER X;Cf;0;BN;;;;;N;;;;;
+E0059;TAG LATIN CAPITAL LETTER Y;Cf;0;BN;;;;;N;;;;;
+E005A;TAG LATIN CAPITAL LETTER Z;Cf;0;BN;;;;;N;;;;;
+E005B;TAG LEFT SQUARE BRACKET;Cf;0;BN;;;;;N;;;;;
+E005C;TAG REVERSE SOLIDUS;Cf;0;BN;;;;;N;;;;;
+E005D;TAG RIGHT SQUARE BRACKET;Cf;0;BN;;;;;N;;;;;
+E005E;TAG CIRCUMFLEX ACCENT;Cf;0;BN;;;;;N;;;;;
+E005F;TAG LOW LINE;Cf;0;BN;;;;;N;;;;;
+E0060;TAG GRAVE ACCENT;Cf;0;BN;;;;;N;;;;;
+E0061;TAG LATIN SMALL LETTER A;Cf;0;BN;;;;;N;;;;;
+E0062;TAG LATIN SMALL LETTER B;Cf;0;BN;;;;;N;;;;;
+E0063;TAG LATIN SMALL LETTER C;Cf;0;BN;;;;;N;;;;;
+E0064;TAG LATIN SMALL LETTER D;Cf;0;BN;;;;;N;;;;;
+E0065;TAG LATIN SMALL LETTER E;Cf;0;BN;;;;;N;;;;;
+E0066;TAG LATIN SMALL LETTER F;Cf;0;BN;;;;;N;;;;;
+E0067;TAG LATIN SMALL LETTER G;Cf;0;BN;;;;;N;;;;;
+E0068;TAG LATIN SMALL LETTER H;Cf;0;BN;;;;;N;;;;;
+E0069;TAG LATIN SMALL LETTER I;Cf;0;BN;;;;;N;;;;;
+E006A;TAG LATIN SMALL LETTER J;Cf;0;BN;;;;;N;;;;;
+E006B;TAG LATIN SMALL LETTER K;Cf;0;BN;;;;;N;;;;;
+E006C;TAG LATIN SMALL LETTER L;Cf;0;BN;;;;;N;;;;;
+E006D;TAG LATIN SMALL LETTER M;Cf;0;BN;;;;;N;;;;;
+E006E;TAG LATIN SMALL LETTER N;Cf;0;BN;;;;;N;;;;;
+E006F;TAG LATIN SMALL LETTER O;Cf;0;BN;;;;;N;;;;;
+E0070;TAG LATIN SMALL LETTER P;Cf;0;BN;;;;;N;;;;;
+E0071;TAG LATIN SMALL LETTER Q;Cf;0;BN;;;;;N;;;;;
+E0072;TAG LATIN SMALL LETTER R;Cf;0;BN;;;;;N;;;;;
+E0073;TAG LATIN SMALL LETTER S;Cf;0;BN;;;;;N;;;;;
+E0074;TAG LATIN SMALL LETTER T;Cf;0;BN;;;;;N;;;;;
+E0075;TAG LATIN SMALL LETTER U;Cf;0;BN;;;;;N;;;;;
+E0076;TAG LATIN SMALL LETTER V;Cf;0;BN;;;;;N;;;;;
+E0077;TAG LATIN SMALL LETTER W;Cf;0;BN;;;;;N;;;;;
+E0078;TAG LATIN SMALL LETTER X;Cf;0;BN;;;;;N;;;;;
+E0079;TAG LATIN SMALL LETTER Y;Cf;0;BN;;;;;N;;;;;
+E007A;TAG LATIN SMALL LETTER Z;Cf;0;BN;;;;;N;;;;;
+E007B;TAG LEFT CURLY BRACKET;Cf;0;BN;;;;;N;;;;;
+E007C;TAG VERTICAL LINE;Cf;0;BN;;;;;N;;;;;
+E007D;TAG RIGHT CURLY BRACKET;Cf;0;BN;;;;;N;;;;;
+E007E;TAG TILDE;Cf;0;BN;;;;;N;;;;;
+E007F;CANCEL TAG;Cf;0;BN;;;;;N;;;;;
+E0100;VARIATION SELECTOR-17;Mn;0;NSM;;;;;N;;;;;
+E0101;VARIATION SELECTOR-18;Mn;0;NSM;;;;;N;;;;;
+E0102;VARIATION SELECTOR-19;Mn;0;NSM;;;;;N;;;;;
+E0103;VARIATION SELECTOR-20;Mn;0;NSM;;;;;N;;;;;
+E0104;VARIATION SELECTOR-21;Mn;0;NSM;;;;;N;;;;;
+E0105;VARIATION SELECTOR-22;Mn;0;NSM;;;;;N;;;;;
+E0106;VARIATION SELECTOR-23;Mn;0;NSM;;;;;N;;;;;
+E0107;VARIATION SELECTOR-24;Mn;0;NSM;;;;;N;;;;;
+E0108;VARIATION SELECTOR-25;Mn;0;NSM;;;;;N;;;;;
+E0109;VARIATION SELECTOR-26;Mn;0;NSM;;;;;N;;;;;
+E010A;VARIATION SELECTOR-27;Mn;0;NSM;;;;;N;;;;;
+E010B;VARIATION SELECTOR-28;Mn;0;NSM;;;;;N;;;;;
+E010C;VARIATION SELECTOR-29;Mn;0;NSM;;;;;N;;;;;
+E010D;VARIATION SELECTOR-30;Mn;0;NSM;;;;;N;;;;;
+E010E;VARIATION SELECTOR-31;Mn;0;NSM;;;;;N;;;;;
+E010F;VARIATION SELECTOR-32;Mn;0;NSM;;;;;N;;;;;
+E0110;VARIATION SELECTOR-33;Mn;0;NSM;;;;;N;;;;;
+E0111;VARIATION SELECTOR-34;Mn;0;NSM;;;;;N;;;;;
+E0112;VARIATION SELECTOR-35;Mn;0;NSM;;;;;N;;;;;
+E0113;VARIATION SELECTOR-36;Mn;0;NSM;;;;;N;;;;;
+E0114;VARIATION SELECTOR-37;Mn;0;NSM;;;;;N;;;;;
+E0115;VARIATION SELECTOR-38;Mn;0;NSM;;;;;N;;;;;
+E0116;VARIATION SELECTOR-39;Mn;0;NSM;;;;;N;;;;;
+E0117;VARIATION SELECTOR-40;Mn;0;NSM;;;;;N;;;;;
+E0118;VARIATION SELECTOR-41;Mn;0;NSM;;;;;N;;;;;
+E0119;VARIATION SELECTOR-42;Mn;0;NSM;;;;;N;;;;;
+E011A;VARIATION SELECTOR-43;Mn;0;NSM;;;;;N;;;;;
+E011B;VARIATION SELECTOR-44;Mn;0;NSM;;;;;N;;;;;
+E011C;VARIATION SELECTOR-45;Mn;0;NSM;;;;;N;;;;;
+E011D;VARIATION SELECTOR-46;Mn;0;NSM;;;;;N;;;;;
+E011E;VARIATION SELECTOR-47;Mn;0;NSM;;;;;N;;;;;
+E011F;VARIATION SELECTOR-48;Mn;0;NSM;;;;;N;;;;;
+E0120;VARIATION SELECTOR-49;Mn;0;NSM;;;;;N;;;;;
+E0121;VARIATION SELECTOR-50;Mn;0;NSM;;;;;N;;;;;
+E0122;VARIATION SELECTOR-51;Mn;0;NSM;;;;;N;;;;;
+E0123;VARIATION SELECTOR-52;Mn;0;NSM;;;;;N;;;;;
+E0124;VARIATION SELECTOR-53;Mn;0;NSM;;;;;N;;;;;
+E0125;VARIATION SELECTOR-54;Mn;0;NSM;;;;;N;;;;;
+E0126;VARIATION SELECTOR-55;Mn;0;NSM;;;;;N;;;;;
+E0127;VARIATION SELECTOR-56;Mn;0;NSM;;;;;N;;;;;
+E0128;VARIATION SELECTOR-57;Mn;0;NSM;;;;;N;;;;;
+E0129;VARIATION SELECTOR-58;Mn;0;NSM;;;;;N;;;;;
+E012A;VARIATION SELECTOR-59;Mn;0;NSM;;;;;N;;;;;
+E012B;VARIATION SELECTOR-60;Mn;0;NSM;;;;;N;;;;;
+E012C;VARIATION SELECTOR-61;Mn;0;NSM;;;;;N;;;;;
+E012D;VARIATION SELECTOR-62;Mn;0;NSM;;;;;N;;;;;
+E012E;VARIATION SELECTOR-63;Mn;0;NSM;;;;;N;;;;;
+E012F;VARIATION SELECTOR-64;Mn;0;NSM;;;;;N;;;;;
+E0130;VARIATION SELECTOR-65;Mn;0;NSM;;;;;N;;;;;
+E0131;VARIATION SELECTOR-66;Mn;0;NSM;;;;;N;;;;;
+E0132;VARIATION SELECTOR-67;Mn;0;NSM;;;;;N;;;;;
+E0133;VARIATION SELECTOR-68;Mn;0;NSM;;;;;N;;;;;
+E0134;VARIATION SELECTOR-69;Mn;0;NSM;;;;;N;;;;;
+E0135;VARIATION SELECTOR-70;Mn;0;NSM;;;;;N;;;;;
+E0136;VARIATION SELECTOR-71;Mn;0;NSM;;;;;N;;;;;
+E0137;VARIATION SELECTOR-72;Mn;0;NSM;;;;;N;;;;;
+E0138;VARIATION SELECTOR-73;Mn;0;NSM;;;;;N;;;;;
+E0139;VARIATION SELECTOR-74;Mn;0;NSM;;;;;N;;;;;
+E013A;VARIATION SELECTOR-75;Mn;0;NSM;;;;;N;;;;;
+E013B;VARIATION SELECTOR-76;Mn;0;NSM;;;;;N;;;;;
+E013C;VARIATION SELECTOR-77;Mn;0;NSM;;;;;N;;;;;
+E013D;VARIATION SELECTOR-78;Mn;0;NSM;;;;;N;;;;;
+E013E;VARIATION SELECTOR-79;Mn;0;NSM;;;;;N;;;;;
+E013F;VARIATION SELECTOR-80;Mn;0;NSM;;;;;N;;;;;
+E0140;VARIATION SELECTOR-81;Mn;0;NSM;;;;;N;;;;;
+E0141;VARIATION SELECTOR-82;Mn;0;NSM;;;;;N;;;;;
+E0142;VARIATION SELECTOR-83;Mn;0;NSM;;;;;N;;;;;
+E0143;VARIATION SELECTOR-84;Mn;0;NSM;;;;;N;;;;;
+E0144;VARIATION SELECTOR-85;Mn;0;NSM;;;;;N;;;;;
+E0145;VARIATION SELECTOR-86;Mn;0;NSM;;;;;N;;;;;
+E0146;VARIATION SELECTOR-87;Mn;0;NSM;;;;;N;;;;;
+E0147;VARIATION SELECTOR-88;Mn;0;NSM;;;;;N;;;;;
+E0148;VARIATION SELECTOR-89;Mn;0;NSM;;;;;N;;;;;
+E0149;VARIATION SELECTOR-90;Mn;0;NSM;;;;;N;;;;;
+E014A;VARIATION SELECTOR-91;Mn;0;NSM;;;;;N;;;;;
+E014B;VARIATION SELECTOR-92;Mn;0;NSM;;;;;N;;;;;
+E014C;VARIATION SELECTOR-93;Mn;0;NSM;;;;;N;;;;;
+E014D;VARIATION SELECTOR-94;Mn;0;NSM;;;;;N;;;;;
+E014E;VARIATION SELECTOR-95;Mn;0;NSM;;;;;N;;;;;
+E014F;VARIATION SELECTOR-96;Mn;0;NSM;;;;;N;;;;;
+E0150;VARIATION SELECTOR-97;Mn;0;NSM;;;;;N;;;;;
+E0151;VARIATION SELECTOR-98;Mn;0;NSM;;;;;N;;;;;
+E0152;VARIATION SELECTOR-99;Mn;0;NSM;;;;;N;;;;;
+E0153;VARIATION SELECTOR-100;Mn;0;NSM;;;;;N;;;;;
+E0154;VARIATION SELECTOR-101;Mn;0;NSM;;;;;N;;;;;
+E0155;VARIATION SELECTOR-102;Mn;0;NSM;;;;;N;;;;;
+E0156;VARIATION SELECTOR-103;Mn;0;NSM;;;;;N;;;;;
+E0157;VARIATION SELECTOR-104;Mn;0;NSM;;;;;N;;;;;
+E0158;VARIATION SELECTOR-105;Mn;0;NSM;;;;;N;;;;;
+E0159;VARIATION SELECTOR-106;Mn;0;NSM;;;;;N;;;;;
+E015A;VARIATION SELECTOR-107;Mn;0;NSM;;;;;N;;;;;
+E015B;VARIATION SELECTOR-108;Mn;0;NSM;;;;;N;;;;;
+E015C;VARIATION SELECTOR-109;Mn;0;NSM;;;;;N;;;;;
+E015D;VARIATION SELECTOR-110;Mn;0;NSM;;;;;N;;;;;
+E015E;VARIATION SELECTOR-111;Mn;0;NSM;;;;;N;;;;;
+E015F;VARIATION SELECTOR-112;Mn;0;NSM;;;;;N;;;;;
+E0160;VARIATION SELECTOR-113;Mn;0;NSM;;;;;N;;;;;
+E0161;VARIATION SELECTOR-114;Mn;0;NSM;;;;;N;;;;;
+E0162;VARIATION SELECTOR-115;Mn;0;NSM;;;;;N;;;;;
+E0163;VARIATION SELECTOR-116;Mn;0;NSM;;;;;N;;;;;
+E0164;VARIATION SELECTOR-117;Mn;0;NSM;;;;;N;;;;;
+E0165;VARIATION SELECTOR-118;Mn;0;NSM;;;;;N;;;;;
+E0166;VARIATION SELECTOR-119;Mn;0;NSM;;;;;N;;;;;
+E0167;VARIATION SELECTOR-120;Mn;0;NSM;;;;;N;;;;;
+E0168;VARIATION SELECTOR-121;Mn;0;NSM;;;;;N;;;;;
+E0169;VARIATION SELECTOR-122;Mn;0;NSM;;;;;N;;;;;
+E016A;VARIATION SELECTOR-123;Mn;0;NSM;;;;;N;;;;;
+E016B;VARIATION SELECTOR-124;Mn;0;NSM;;;;;N;;;;;
+E016C;VARIATION SELECTOR-125;Mn;0;NSM;;;;;N;;;;;
+E016D;VARIATION SELECTOR-126;Mn;0;NSM;;;;;N;;;;;
+E016E;VARIATION SELECTOR-127;Mn;0;NSM;;;;;N;;;;;
+E016F;VARIATION SELECTOR-128;Mn;0;NSM;;;;;N;;;;;
+E0170;VARIATION SELECTOR-129;Mn;0;NSM;;;;;N;;;;;
+E0171;VARIATION SELECTOR-130;Mn;0;NSM;;;;;N;;;;;
+E0172;VARIATION SELECTOR-131;Mn;0;NSM;;;;;N;;;;;
+E0173;VARIATION SELECTOR-132;Mn;0;NSM;;;;;N;;;;;
+E0174;VARIATION SELECTOR-133;Mn;0;NSM;;;;;N;;;;;
+E0175;VARIATION SELECTOR-134;Mn;0;NSM;;;;;N;;;;;
+E0176;VARIATION SELECTOR-135;Mn;0;NSM;;;;;N;;;;;
+E0177;VARIATION SELECTOR-136;Mn;0;NSM;;;;;N;;;;;
+E0178;VARIATION SELECTOR-137;Mn;0;NSM;;;;;N;;;;;
+E0179;VARIATION SELECTOR-138;Mn;0;NSM;;;;;N;;;;;
+E017A;VARIATION SELECTOR-139;Mn;0;NSM;;;;;N;;;;;
+E017B;VARIATION SELECTOR-140;Mn;0;NSM;;;;;N;;;;;
+E017C;VARIATION SELECTOR-141;Mn;0;NSM;;;;;N;;;;;
+E017D;VARIATION SELECTOR-142;Mn;0;NSM;;;;;N;;;;;
+E017E;VARIATION SELECTOR-143;Mn;0;NSM;;;;;N;;;;;
+E017F;VARIATION SELECTOR-144;Mn;0;NSM;;;;;N;;;;;
+E0180;VARIATION SELECTOR-145;Mn;0;NSM;;;;;N;;;;;
+E0181;VARIATION SELECTOR-146;Mn;0;NSM;;;;;N;;;;;
+E0182;VARIATION SELECTOR-147;Mn;0;NSM;;;;;N;;;;;
+E0183;VARIATION SELECTOR-148;Mn;0;NSM;;;;;N;;;;;
+E0184;VARIATION SELECTOR-149;Mn;0;NSM;;;;;N;;;;;
+E0185;VARIATION SELECTOR-150;Mn;0;NSM;;;;;N;;;;;
+E0186;VARIATION SELECTOR-151;Mn;0;NSM;;;;;N;;;;;
+E0187;VARIATION SELECTOR-152;Mn;0;NSM;;;;;N;;;;;
+E0188;VARIATION SELECTOR-153;Mn;0;NSM;;;;;N;;;;;
+E0189;VARIATION SELECTOR-154;Mn;0;NSM;;;;;N;;;;;
+E018A;VARIATION SELECTOR-155;Mn;0;NSM;;;;;N;;;;;
+E018B;VARIATION SELECTOR-156;Mn;0;NSM;;;;;N;;;;;
+E018C;VARIATION SELECTOR-157;Mn;0;NSM;;;;;N;;;;;
+E018D;VARIATION SELECTOR-158;Mn;0;NSM;;;;;N;;;;;
+E018E;VARIATION SELECTOR-159;Mn;0;NSM;;;;;N;;;;;
+E018F;VARIATION SELECTOR-160;Mn;0;NSM;;;;;N;;;;;
+E0190;VARIATION SELECTOR-161;Mn;0;NSM;;;;;N;;;;;
+E0191;VARIATION SELECTOR-162;Mn;0;NSM;;;;;N;;;;;
+E0192;VARIATION SELECTOR-163;Mn;0;NSM;;;;;N;;;;;
+E0193;VARIATION SELECTOR-164;Mn;0;NSM;;;;;N;;;;;
+E0194;VARIATION SELECTOR-165;Mn;0;NSM;;;;;N;;;;;
+E0195;VARIATION SELECTOR-166;Mn;0;NSM;;;;;N;;;;;
+E0196;VARIATION SELECTOR-167;Mn;0;NSM;;;;;N;;;;;
+E0197;VARIATION SELECTOR-168;Mn;0;NSM;;;;;N;;;;;
+E0198;VARIATION SELECTOR-169;Mn;0;NSM;;;;;N;;;;;
+E0199;VARIATION SELECTOR-170;Mn;0;NSM;;;;;N;;;;;
+E019A;VARIATION SELECTOR-171;Mn;0;NSM;;;;;N;;;;;
+E019B;VARIATION SELECTOR-172;Mn;0;NSM;;;;;N;;;;;
+E019C;VARIATION SELECTOR-173;Mn;0;NSM;;;;;N;;;;;
+E019D;VARIATION SELECTOR-174;Mn;0;NSM;;;;;N;;;;;
+E019E;VARIATION SELECTOR-175;Mn;0;NSM;;;;;N;;;;;
+E019F;VARIATION SELECTOR-176;Mn;0;NSM;;;;;N;;;;;
+E01A0;VARIATION SELECTOR-177;Mn;0;NSM;;;;;N;;;;;
+E01A1;VARIATION SELECTOR-178;Mn;0;NSM;;;;;N;;;;;
+E01A2;VARIATION SELECTOR-179;Mn;0;NSM;;;;;N;;;;;
+E01A3;VARIATION SELECTOR-180;Mn;0;NSM;;;;;N;;;;;
+E01A4;VARIATION SELECTOR-181;Mn;0;NSM;;;;;N;;;;;
+E01A5;VARIATION SELECTOR-182;Mn;0;NSM;;;;;N;;;;;
+E01A6;VARIATION SELECTOR-183;Mn;0;NSM;;;;;N;;;;;
+E01A7;VARIATION SELECTOR-184;Mn;0;NSM;;;;;N;;;;;
+E01A8;VARIATION SELECTOR-185;Mn;0;NSM;;;;;N;;;;;
+E01A9;VARIATION SELECTOR-186;Mn;0;NSM;;;;;N;;;;;
+E01AA;VARIATION SELECTOR-187;Mn;0;NSM;;;;;N;;;;;
+E01AB;VARIATION SELECTOR-188;Mn;0;NSM;;;;;N;;;;;
+E01AC;VARIATION SELECTOR-189;Mn;0;NSM;;;;;N;;;;;
+E01AD;VARIATION SELECTOR-190;Mn;0;NSM;;;;;N;;;;;
+E01AE;VARIATION SELECTOR-191;Mn;0;NSM;;;;;N;;;;;
+E01AF;VARIATION SELECTOR-192;Mn;0;NSM;;;;;N;;;;;
+E01B0;VARIATION SELECTOR-193;Mn;0;NSM;;;;;N;;;;;
+E01B1;VARIATION SELECTOR-194;Mn;0;NSM;;;;;N;;;;;
+E01B2;VARIATION SELECTOR-195;Mn;0;NSM;;;;;N;;;;;
+E01B3;VARIATION SELECTOR-196;Mn;0;NSM;;;;;N;;;;;
+E01B4;VARIATION SELECTOR-197;Mn;0;NSM;;;;;N;;;;;
+E01B5;VARIATION SELECTOR-198;Mn;0;NSM;;;;;N;;;;;
+E01B6;VARIATION SELECTOR-199;Mn;0;NSM;;;;;N;;;;;
+E01B7;VARIATION SELECTOR-200;Mn;0;NSM;;;;;N;;;;;
+E01B8;VARIATION SELECTOR-201;Mn;0;NSM;;;;;N;;;;;
+E01B9;VARIATION SELECTOR-202;Mn;0;NSM;;;;;N;;;;;
+E01BA;VARIATION SELECTOR-203;Mn;0;NSM;;;;;N;;;;;
+E01BB;VARIATION SELECTOR-204;Mn;0;NSM;;;;;N;;;;;
+E01BC;VARIATION SELECTOR-205;Mn;0;NSM;;;;;N;;;;;
+E01BD;VARIATION SELECTOR-206;Mn;0;NSM;;;;;N;;;;;
+E01BE;VARIATION SELECTOR-207;Mn;0;NSM;;;;;N;;;;;
+E01BF;VARIATION SELECTOR-208;Mn;0;NSM;;;;;N;;;;;
+E01C0;VARIATION SELECTOR-209;Mn;0;NSM;;;;;N;;;;;
+E01C1;VARIATION SELECTOR-210;Mn;0;NSM;;;;;N;;;;;
+E01C2;VARIATION SELECTOR-211;Mn;0;NSM;;;;;N;;;;;
+E01C3;VARIATION SELECTOR-212;Mn;0;NSM;;;;;N;;;;;
+E01C4;VARIATION SELECTOR-213;Mn;0;NSM;;;;;N;;;;;
+E01C5;VARIATION SELECTOR-214;Mn;0;NSM;;;;;N;;;;;
+E01C6;VARIATION SELECTOR-215;Mn;0;NSM;;;;;N;;;;;
+E01C7;VARIATION SELECTOR-216;Mn;0;NSM;;;;;N;;;;;
+E01C8;VARIATION SELECTOR-217;Mn;0;NSM;;;;;N;;;;;
+E01C9;VARIATION SELECTOR-218;Mn;0;NSM;;;;;N;;;;;
+E01CA;VARIATION SELECTOR-219;Mn;0;NSM;;;;;N;;;;;
+E01CB;VARIATION SELECTOR-220;Mn;0;NSM;;;;;N;;;;;
+E01CC;VARIATION SELECTOR-221;Mn;0;NSM;;;;;N;;;;;
+E01CD;VARIATION SELECTOR-222;Mn;0;NSM;;;;;N;;;;;
+E01CE;VARIATION SELECTOR-223;Mn;0;NSM;;;;;N;;;;;
+E01CF;VARIATION SELECTOR-224;Mn;0;NSM;;;;;N;;;;;
+E01D0;VARIATION SELECTOR-225;Mn;0;NSM;;;;;N;;;;;
+E01D1;VARIATION SELECTOR-226;Mn;0;NSM;;;;;N;;;;;
+E01D2;VARIATION SELECTOR-227;Mn;0;NSM;;;;;N;;;;;
+E01D3;VARIATION SELECTOR-228;Mn;0;NSM;;;;;N;;;;;
+E01D4;VARIATION SELECTOR-229;Mn;0;NSM;;;;;N;;;;;
+E01D5;VARIATION SELECTOR-230;Mn;0;NSM;;;;;N;;;;;
+E01D6;VARIATION SELECTOR-231;Mn;0;NSM;;;;;N;;;;;
+E01D7;VARIATION SELECTOR-232;Mn;0;NSM;;;;;N;;;;;
+E01D8;VARIATION SELECTOR-233;Mn;0;NSM;;;;;N;;;;;
+E01D9;VARIATION SELECTOR-234;Mn;0;NSM;;;;;N;;;;;
+E01DA;VARIATION SELECTOR-235;Mn;0;NSM;;;;;N;;;;;
+E01DB;VARIATION SELECTOR-236;Mn;0;NSM;;;;;N;;;;;
+E01DC;VARIATION SELECTOR-237;Mn;0;NSM;;;;;N;;;;;
+E01DD;VARIATION SELECTOR-238;Mn;0;NSM;;;;;N;;;;;
+E01DE;VARIATION SELECTOR-239;Mn;0;NSM;;;;;N;;;;;
+E01DF;VARIATION SELECTOR-240;Mn;0;NSM;;;;;N;;;;;
+E01E0;VARIATION SELECTOR-241;Mn;0;NSM;;;;;N;;;;;
+E01E1;VARIATION SELECTOR-242;Mn;0;NSM;;;;;N;;;;;
+E01E2;VARIATION SELECTOR-243;Mn;0;NSM;;;;;N;;;;;
+E01E3;VARIATION SELECTOR-244;Mn;0;NSM;;;;;N;;;;;
+E01E4;VARIATION SELECTOR-245;Mn;0;NSM;;;;;N;;;;;
+E01E5;VARIATION SELECTOR-246;Mn;0;NSM;;;;;N;;;;;
+E01E6;VARIATION SELECTOR-247;Mn;0;NSM;;;;;N;;;;;
+E01E7;VARIATION SELECTOR-248;Mn;0;NSM;;;;;N;;;;;
+E01E8;VARIATION SELECTOR-249;Mn;0;NSM;;;;;N;;;;;
+E01E9;VARIATION SELECTOR-250;Mn;0;NSM;;;;;N;;;;;
+E01EA;VARIATION SELECTOR-251;Mn;0;NSM;;;;;N;;;;;
+E01EB;VARIATION SELECTOR-252;Mn;0;NSM;;;;;N;;;;;
+E01EC;VARIATION SELECTOR-253;Mn;0;NSM;;;;;N;;;;;
+E01ED;VARIATION SELECTOR-254;Mn;0;NSM;;;;;N;;;;;
+E01EE;VARIATION SELECTOR-255;Mn;0;NSM;;;;;N;;;;;
+E01EF;VARIATION SELECTOR-256;Mn;0;NSM;;;;;N;;;;;
+F0000;<Plane 15 Private Use, First>;Co;0;L;;;;;N;;;;;
+FFFFD;<Plane 15 Private Use, Last>;Co;0;L;;;;;N;;;;;
+100000;<Plane 16 Private Use, First>;Co;0;L;;;;;N;;;;;
+10FFFD;<Plane 16 Private Use, Last>;Co;0;L;;;;;N;;;;;
diff --git a/third_party/heimdal/lib/wind/bidi.c b/third_party/heimdal/lib/wind/bidi.c
new file mode 100644
index 0000000..7fdbc2a
--- /dev/null
+++ b/third_party/heimdal/lib/wind/bidi.c
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "windlocl.h"
+
+#include <stdlib.h>
+
+#include "bidi_table.h"
+
+static int
+range_entry_cmp(const void *a, const void *b)
+{
+ const struct range_entry *ea = (const struct range_entry*)a;
+ const struct range_entry *eb = (const struct range_entry*)b;
+
+ if (ea->start >= eb->start && ea->start < eb->start + eb->len)
+ return 0;
+ return ea->start - eb->start;
+}
+
+static int
+is_ral(uint32_t cp)
+{
+ struct range_entry ee = {cp, 0};
+ void *s = bsearch(&ee, _wind_ral_table, _wind_ral_table_size,
+ sizeof(_wind_ral_table[0]),
+ range_entry_cmp);
+ return s != NULL;
+}
+
+static int
+is_l(uint32_t cp)
+{
+ struct range_entry ee = {cp, 0};
+ void *s = bsearch(&ee, _wind_l_table, _wind_l_table_size,
+ sizeof(_wind_l_table[0]),
+ range_entry_cmp);
+ return s != NULL;
+}
+
+int
+_wind_stringprep_testbidi(const uint32_t *in, size_t in_len, wind_profile_flags flags)
+{
+ size_t i;
+ unsigned ral = 0;
+ unsigned l = 0;
+
+ if ((flags & (WIND_PROFILE_NAME|WIND_PROFILE_SASL)) == 0)
+ return 0;
+
+ for (i = 0; i < in_len; ++i) {
+ ral |= is_ral(in[i]);
+ l |= is_l(in[i]);
+ }
+ if (ral) {
+ if (l)
+ return 1;
+ if (!is_ral(in[0]) || !is_ral(in[in_len - 1]))
+ return 1;
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/wind/combining.c b/third_party/heimdal/lib/wind/combining.c
new file mode 100644
index 0000000..764acc3
--- /dev/null
+++ b/third_party/heimdal/lib/wind/combining.c
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "windlocl.h"
+
+#include <stdlib.h>
+
+#include "combining_table.h"
+
+static int
+translation_cmp(const void *key, const void *data)
+{
+ const struct translation *t1 = (const struct translation *)key;
+ const struct translation *t2 = (const struct translation *)data;
+
+ return t1->key - t2->key;
+}
+
+int
+_wind_combining_class(uint32_t code_point)
+{
+ struct translation ts = {code_point, 0};
+ void *s = bsearch(&ts, _wind_combining_table, _wind_combining_table_size,
+ sizeof(_wind_combining_table[0]),
+ translation_cmp);
+ if (s != NULL) {
+ const struct translation *t = (const struct translation *)s;
+ return t->combining_class;
+ } else {
+ return 0;
+ }
+}
diff --git a/third_party/heimdal/lib/wind/doxygen.c b/third_party/heimdal/lib/wind/doxygen.c
new file mode 100644
index 0000000..7470ed2
--- /dev/null
+++ b/third_party/heimdal/lib/wind/doxygen.c
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+
+/*! @mainpage Heimdal wind library
+ *
+ * @section intro Introduction
+ *
+ * Heimdal wind library is a implementation of stringprep and some of
+ * its profiles.
+ *
+ * The project web page: http://www.h5l.org/
+ *
+ */
+
+/** @defgroup wind Heimdal wind library */
diff --git a/third_party/heimdal/lib/wind/errorlist.c b/third_party/heimdal/lib/wind/errorlist.c
new file mode 100644
index 0000000..8a9d4a5
--- /dev/null
+++ b/third_party/heimdal/lib/wind/errorlist.c
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "windlocl.h"
+
+#include <stdlib.h>
+
+#include "errorlist_table.h"
+
+static int
+error_entry_cmp(const void *a, const void *b)
+{
+ const struct error_entry *ea = (const struct error_entry*)a;
+ const struct error_entry *eb = (const struct error_entry*)b;
+
+ if (ea->start >= eb->start && ea->start < eb->start + eb->len)
+ return 0;
+ return ea->start - eb->start;
+}
+
+int
+_wind_stringprep_error(const uint32_t cp, wind_profile_flags flags)
+{
+ struct error_entry ee = {cp, 0, 0};
+ const struct error_entry *s;
+
+ s = (const struct error_entry *)
+ bsearch(&ee, _wind_errorlist_table,
+ _wind_errorlist_table_size,
+ sizeof(_wind_errorlist_table[0]),
+ error_entry_cmp);
+ if (s == NULL)
+ return 0;
+ return (s->flags & flags);
+}
+
+int
+_wind_stringprep_prohibited(const uint32_t *in, size_t in_len,
+ wind_profile_flags flags)
+{
+ unsigned i;
+
+ for (i = 0; i < in_len; ++i)
+ if (_wind_stringprep_error(in[i], flags))
+ return 1;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/wind/gen-bidi.py b/third_party/heimdal/lib/wind/gen-bidi.py
new file mode 100644
index 0000000..e2efcbb
--- /dev/null
+++ b/third_party/heimdal/lib/wind/gen-bidi.py
@@ -0,0 +1,102 @@
+#!/usr/local/bin/python
+# -*- coding: iso-8859-1 -*-
+
+# $Id$
+
+# Copyright (c) 2004 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+import re
+import string
+import sys
+
+import generate
+import rfc3454
+
+if len(sys.argv) != 3:
+ print("usage: %s rfc3454.txt outdir" % sys.argv[0])
+ sys.exit(1)
+
+tables = rfc3454.read(sys.argv[1])
+
+bidi_h = generate.Header('%s/bidi_table.h' % sys.argv[2])
+
+bidi_c = generate.Implementation('%s/bidi_table.c' % sys.argv[2])
+
+bidi_h.file.write(
+'''
+#include <krb5-types.h>
+
+struct range_entry {
+ uint32_t start;
+ unsigned len;
+};
+
+extern const struct range_entry _wind_ral_table[];
+extern const struct range_entry _wind_l_table[];
+
+extern const size_t _wind_ral_table_size;
+extern const size_t _wind_l_table_size;
+
+''')
+
+bidi_c.file.write(
+'''
+#include "bidi_table.h"
+#include <stdlib.h>
+
+''')
+
+def printTable(file, table, variable):
+ """print table to file named as variable"""
+ file.write("const struct range_entry %s[] = {\n" % variable)
+ count = 0
+ for l in tables[table]:
+ m = re.search('^ *([0-9A-F]+)-([0-9A-F]+) *$', l)
+ if m:
+ start = int(m.group(1), 0x10)
+ end = int(m.group(2), 0x10)
+ file.write(" {0x%x, 0x%x},\n" % (start, end - start + 1))
+ count += 1
+ else:
+ m = re.search('^ *([0-9A-F]+) *$', l)
+ if m:
+ v = int(m.group(1), 0x10)
+ file.write(" {0x%x, 1},\n" % v)
+ count += 1
+ file.write("};\n\n")
+ file.write("const size_t %s_size = %u;\n\n" % (variable, count))
+
+printTable(bidi_c.file, 'D.1', '_wind_ral_table')
+printTable(bidi_c.file, 'D.2', '_wind_l_table')
+
+bidi_h.close()
+bidi_c.close()
diff --git a/third_party/heimdal/lib/wind/gen-combining.py b/third_party/heimdal/lib/wind/gen-combining.py
new file mode 100644
index 0000000..43e0d52
--- /dev/null
+++ b/third_party/heimdal/lib/wind/gen-combining.py
@@ -0,0 +1,104 @@
+#!/usr/local/bin/python
+# -*- coding: iso-8859-1 -*-
+
+# $Id$
+
+# Copyright (c) 2004 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+import re
+import string
+import sys
+
+import generate
+import UnicodeData
+
+if len(sys.argv) != 3:
+ print("usage: %s UnicodeData.txt out-dir" % sys.argv[0])
+ sys.exit(1)
+
+ud = UnicodeData.read(sys.argv[1])
+
+trans = {}
+for k,v in ud.items():
+ if int(v[2]) != 0 :
+ trans[k] = [int(v[2]), v[1]]
+
+# trans = [(x[0], int(x[3]), x[1]) for x in UnicodeData.read() if int(x[3]) != 0]
+
+combining_h = generate.Header('%s/combining_table.h' % sys.argv[2])
+combining_c = generate.Implementation('%s/combining_table.c' % sys.argv[2])
+
+combining_h.file.write(
+'''
+#include <krb5-types.h>
+
+struct translation {
+ uint32_t key;
+ unsigned combining_class;
+};
+
+extern const struct translation _wind_combining_table[];
+
+extern const size_t _wind_combining_table_size;
+''')
+
+combining_c.file.write(
+'''
+#include "combining_table.h"
+#include <stdlib.h>
+
+const struct translation _wind_combining_table[] = {
+''')
+
+s = sorted(trans)
+for k in s:
+ v = trans[k]
+ combining_c.file.write("{0x%x, %u}, /* %s */\n"
+ % (k, v[0], v[1]))
+
+
+#trans.sort()
+#for x in trans:
+# combining_c.file.write("{0x%x, %u}, /* %s */\n"
+# % (x[0], x[1], x[2]))
+
+combining_c.file.write(
+'''
+};
+''')
+
+combining_c.file.write(
+ "const size_t _wind_combining_table_size = %u;\n" % len(trans))
+
+
+combining_h.close()
+combining_c.close()
diff --git a/third_party/heimdal/lib/wind/gen-errorlist.py b/third_party/heimdal/lib/wind/gen-errorlist.py
new file mode 100644
index 0000000..97646cf
--- /dev/null
+++ b/third_party/heimdal/lib/wind/gen-errorlist.py
@@ -0,0 +1,121 @@
+#!/usr/local/bin/python
+# -*- coding: iso-8859-1 -*-
+
+# $Id$
+
+# Copyright (c) 2004 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+import re
+import string
+import sys
+
+import generate
+import rfc3454
+import rfc4518
+import stringprep
+
+if len(sys.argv) != 3:
+ print("usage: %s rfc3454.txt out-dir" % sys.argv[0])
+ sys.exit(1)
+
+tables = rfc3454.read(sys.argv[1])
+t2 = rfc4518.read()
+
+for x in t2.keys():
+ tables[x] = t2[x]
+
+error_list = stringprep.get_errorlist()
+
+errorlist_h = generate.Header('%s/errorlist_table.h' % sys.argv[2])
+
+errorlist_c = generate.Implementation('%s/errorlist_table.c' % sys.argv[2])
+
+errorlist_h.file.write(
+'''
+#include "windlocl.h"
+
+struct error_entry {
+ uint32_t start;
+ unsigned len;
+ wind_profile_flags flags;
+};
+
+extern const struct error_entry _wind_errorlist_table[];
+
+extern const size_t _wind_errorlist_table_size;
+
+''')
+
+errorlist_c.file.write(
+'''
+#include "errorlist_table.h"
+#include <stdlib.h>
+
+const struct error_entry _wind_errorlist_table[] = {
+''')
+
+trans=[]
+
+for t in error_list.keys():
+ for l in tables[t]:
+ m = re.search('^ *([0-9A-F]+)-([0-9A-F]+); *(.*) *$', l)
+ if m:
+ start = int(m.group(1), 0x10)
+ end = int(m.group(2), 0x10)
+ desc = m.group(3)
+ trans.append([start, end - start + 1, desc, [t]])
+ else:
+ m = re.search('^ *([0-9A-F]+); *(.*) *$', l)
+ if m:
+ trans.append([int(m.group(1), 0x10), 1, m.group(2), [t]])
+
+trans = stringprep.sort_merge_trans(trans)
+
+for x in trans:
+ (start, length, description, tables) = x
+ symbols = stringprep.symbols(error_list, tables)
+ if len(symbols) == 0:
+ print("no symbol for %s" % description)
+ sys.exit(1)
+ errorlist_c.file.write(" {0x%x, 0x%x, %s}, /* %s: %s */\n"
+ % (start, length, symbols, ",".join(tables), description))
+
+errorlist_c.file.write(
+'''};
+
+''')
+
+errorlist_c.file.write(
+ "const size_t _wind_errorlist_table_size = %u;\n" % len(trans))
+
+errorlist_h.close()
+errorlist_c.close()
diff --git a/third_party/heimdal/lib/wind/gen-map.py b/third_party/heimdal/lib/wind/gen-map.py
new file mode 100644
index 0000000..dc10d6f
--- /dev/null
+++ b/third_party/heimdal/lib/wind/gen-map.py
@@ -0,0 +1,158 @@
+#!/usr/local/bin/python
+# -*- coding: iso-8859-1 -*-
+
+# $Id$
+
+# Copyright (c) 2004 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+import re
+import string
+import sys
+
+import generate
+import rfc3454
+import rfc4518
+import stringprep
+import util
+
+if len(sys.argv) != 3:
+ print("usage: %s rfc3454.txt out-dir" % sys.argv[0])
+ sys.exit(1)
+
+tables = rfc3454.read(sys.argv[1])
+t2 = rfc4518.read()
+
+for x in t2:
+ tables[x] = t2[x]
+
+map_list = stringprep.get_maplist()
+
+map_h = generate.Header('%s/map_table.h' % sys.argv[2])
+
+map_c = generate.Implementation('%s/map_table.c' % sys.argv[2])
+
+map_h.file.write(
+'''
+#include "windlocl.h"
+
+struct translation {
+ uint32_t key;
+ unsigned short val_len;
+ unsigned short val_offset;
+ wind_profile_flags flags;
+};
+
+extern const struct translation _wind_map_table[];
+
+extern const size_t _wind_map_table_size;
+
+extern const uint32_t _wind_map_table_val[];
+
+''')
+
+map_c.file.write(
+'''
+#include "map_table.h"
+
+const struct translation _wind_map_table[] = {
+''')
+
+trans=[]
+
+for t in map_list:
+ for l in tables[t]:
+ m = re.search('^ *([0-9A-F]+)-([0-9A-F]+); *([^;]+); *(.*) *$', l)
+ if m:
+ start = int(m.group(1), 0x10)
+ end = int(m.group(2), 0x10)
+ value = m.group(3)
+ desc = m.group(4)
+ for key in range(start,end,1):
+ trans.append((key, value, desc, [t]))
+ continue
+ m = re.search('^ *([^;]+); *([^;]+); *(.*) *$', l)
+ if m:
+ key = int(m.group(1), 0x10)
+ value = m.group(2)
+ desc = m.group(3)
+ trans.append((key, value, desc, [t]))
+ continue
+
+valTable = []
+offsetTable = {}
+
+trans = stringprep.sort_merge_trans(trans)
+
+for x in trans:
+ if x[0] == 0xad:
+ print("fooresult %s" % ",".join(x[3]))
+
+for x in trans:
+ (key, value, description, table) = x
+ v = value.split()
+ i = util.subList(valTable, v)
+ if i:
+ offsetTable[key] = i
+ else:
+ offsetTable[key] = len(valTable)
+ valTable.extend(v)
+
+for x in trans:
+ (key, value, description, tables) = x
+ symbols = stringprep.symbols(map_list, tables)
+ if len(symbols) == 0:
+ print("no symbol for %s %s (%s)" % (key, description, tables))
+ sys.exit(1)
+ v = value.split()
+ map_c.file.write(" {0x%x, %u, %u, %s}, /* %s: %s */\n"
+ % (key, len(v), offsetTable[key], symbols, ",".join(tables), description))
+
+map_c.file.write(
+'''
+};
+
+''')
+
+map_c.file.write(
+ "const size_t _wind_map_table_size = %u;\n\n" % len(trans))
+
+map_c.file.write(
+ "const uint32_t _wind_map_table_val[] = {\n")
+
+for x in valTable:
+ map_c.file.write(" 0x%s,\n" % x)
+
+map_c.file.write(
+ "};\n\n")
+
+map_h.close()
+map_c.close()
diff --git a/third_party/heimdal/lib/wind/gen-normalize.py b/third_party/heimdal/lib/wind/gen-normalize.py
new file mode 100644
index 0000000..daf3c3d
--- /dev/null
+++ b/third_party/heimdal/lib/wind/gen-normalize.py
@@ -0,0 +1,211 @@
+#!/usr/local/bin/python
+# -*- coding: iso-8859-1 -*-
+
+# $Id$
+
+# Copyright (c) 2004 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+import re
+import string
+import sys
+
+import generate
+import UnicodeData
+import util
+
+if len(sys.argv) != 4:
+ print("usage: %s UnicodeData.txt"
+ " CompositionExclusions-3.2.0.txt out-dir" % sys.argv[0])
+ sys.exit(1)
+
+ud = UnicodeData.read(sys.argv[1])
+
+def sortedKeys(d):
+ """Return a sorted list of the keys of a dict"""
+ keys = list(d.keys())
+ keys.sort()
+ return keys
+
+trans = dict([(k, [re.sub('<[a-zA-Z]+>', '', v[4]), v[0]])
+ for k,v in ud.items() if v[4]])
+
+maxLength = 0
+for v in trans.values():
+ maxLength = max(maxLength, len(v[0].split()))
+
+normalize_h = generate.Header('%s/normalize_table.h' % sys.argv[3])
+normalize_c = generate.Implementation('%s/normalize_table.c' % sys.argv[3])
+
+normalize_h.file.write(
+'''
+#include <krb5-types.h>
+
+#define MAX_LENGTH_CANON %u
+
+struct translation {
+ uint32_t key;
+ unsigned short val_len;
+ unsigned short val_offset;
+};
+
+extern const struct translation _wind_normalize_table[];
+
+extern const uint32_t _wind_normalize_val_table[];
+
+extern const size_t _wind_normalize_table_size;
+
+struct canon_node {
+ uint32_t val;
+ unsigned char next_start;
+ unsigned char next_end;
+ unsigned short next_offset;
+};
+
+extern const struct canon_node _wind_canon_table[];
+
+extern const unsigned short _wind_canon_next_table[];
+''' % maxLength)
+
+normalize_c.file.write(
+'''
+#include "normalize_table.h"
+#include <stdlib.h>
+
+const struct translation _wind_normalize_table[] = {
+''')
+
+normalizeValTable = []
+
+for k in sortedKeys(trans) :
+ v = trans[k]
+ (key, value, description) = k, v[0], v[1]
+ vec = [int(x, 0x10) for x in value.split()];
+ offset = util.subList(normalizeValTable, vec)
+ if not offset:
+ offset = len(normalizeValTable)
+ normalizeValTable.extend(vec) # [("0x%s" % i) for i in vec])
+ normalize_c.file.write(" {0x%x, %u, %u}, /* %s */\n"
+ % (key, len(vec), offset, description))
+
+normalize_c.file.write(
+'''};
+
+''')
+
+normalize_c.file.write(
+ "const size_t _wind_normalize_table_size = %u;\n\n" % len(trans))
+
+normalize_c.file.write("const uint32_t _wind_normalize_val_table[] = {\n")
+
+for v in normalizeValTable:
+ normalize_c.file.write(" 0x%x,\n" % v)
+
+normalize_c.file.write("};\n\n");
+
+exclusions = UnicodeData.read(sys.argv[2])
+
+inv = dict([(''.join(["%05x" % int(x, 0x10) for x in v[4].split(' ')]),
+ [k, v[0]])
+ for k,v in ud.items()
+ if v[4] and not re.search('<[a-zA-Z]+> *', v[4]) and not k in exclusions])
+
+table = 0
+
+tables = {}
+
+def createTable():
+ """add a new table"""
+ global table, tables
+ ret = table
+ table += 1
+ tables[ret] = [0] + [None] * 16
+ return ret
+
+def add(table, k, v):
+ """add an entry (k, v) to table (recursively)"""
+ if len(k) == 0:
+ table[0] = v[0]
+ else:
+ i = int(k[0], 0x10) + 1
+ if table[i] == None:
+ table[i] = createTable()
+ add(tables[table[i]], k[1:], v)
+
+top = createTable()
+
+for k,v in inv.items():
+ add(tables[top], k, v)
+
+next_table = []
+tableToNext = {}
+tableEnd = {}
+tableStart = {}
+
+for k in sortedKeys(tables) :
+ t = tables[k]
+ tableToNext[k] = len(next_table)
+ l = t[1:]
+ start = 0
+ while start < 16 and l[start] == None:
+ start += 1
+ end = 16
+ while end > start and l[end - 1] == None:
+ end -= 1
+ tableStart[k] = start
+ tableEnd[k] = end
+ n = []
+ for i in range(start, end):
+ x = l[i]
+ if x:
+ n.append(x)
+ else:
+ n.append(0)
+ next_table.extend(n)
+
+normalize_c.file.write("const struct canon_node _wind_canon_table[] = {\n")
+
+for k in sortedKeys(tables) :
+ t = tables[k]
+ normalize_c.file.write(" {0x%x, %u, %u, %u},\n" %
+ (t[0], tableStart[k], tableEnd[k], tableToNext[k]))
+
+normalize_c.file.write("};\n\n")
+
+normalize_c.file.write("const unsigned short _wind_canon_next_table[] = {\n")
+
+for k in next_table:
+ normalize_c.file.write(" %u,\n" % k)
+
+normalize_c.file.write("};\n\n")
+
+normalize_h.close()
+normalize_c.close()
diff --git a/third_party/heimdal/lib/wind/gen-punycode-examples.py b/third_party/heimdal/lib/wind/gen-punycode-examples.py
new file mode 100644
index 0000000..f2eddbb
--- /dev/null
+++ b/third_party/heimdal/lib/wind/gen-punycode-examples.py
@@ -0,0 +1,130 @@
+#!/usr/local/bin/python
+# -*- coding: iso-8859-1 -*-
+
+# $Id$
+
+# Copyright (c) 2004 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+import re
+import sys
+
+import generate
+
+if len(sys.argv) != 3:
+ print("usage: %s rfc3492.txt" % sys.argv[0])
+ sys.exit(1)
+
+f = open(sys.argv[1], 'r')
+
+examples_h = generate.Header('%s/punycode_examples.h' % sys.argv[2])
+examples_c = generate.Header('%s/punycode_examples.c' % sys.argv[2])
+
+start = False
+
+while True:
+ l = f.readline()
+ if not l:
+ break
+ if l[-2:] == "\\\n":
+ l2 = f.readline()
+ if not l2:
+ raise Exception("EOF in backslash escape")
+ l2 = re.sub('^ *', '', l2)
+ l = l[:-2] + l2
+ if start:
+ if re.match('7\.2', l):
+ start = False
+ else:
+ m = re.search('^ *\([A-Z]\) *(.*)$', l);
+ if m:
+ desc = m.group(1)
+ codes = []
+ else:
+ m = re.search('^ *([uU]+.*) *$', l)
+ if m:
+ codes.extend(m.group(1).split(' '))
+ else:
+ m = re.search('^ *Punycode: (.*) *$', l)
+ if m:
+ cases.append([codes, m.group(1), desc])
+ else:
+ if re.match('^7\.1', l):
+ start = True
+ cases = []
+
+f.close()
+
+examples_h.file.write(
+'''
+#include <krb5-types.h>
+
+#define MAX_LENGTH 40
+
+struct punycode_example {
+ size_t len;
+ uint32_t val[MAX_LENGTH];
+ const char *pc;
+ const char *description;
+};
+
+extern const struct punycode_example punycode_examples[];
+
+extern const size_t punycode_examples_size;
+''')
+
+examples_c.file.write(
+'''
+#include <stdlib.h>
+#include "punycode_examples.h"
+
+const struct punycode_example punycode_examples[] = {
+''')
+
+for x in cases:
+ [cp, pc, desc] = x
+ examples_c.file.write(
+ " {%u, {%s}, \"%s\", \"%s\"},\n" %
+ (len(cp),
+ ",".join([re.sub('[uU]\+', '0x', x) for x in cp]),
+ pc,
+ desc))
+
+examples_c.file.write(
+'''};
+
+''')
+
+examples_c.file.write(
+ "const size_t punycode_examples_size = %u;\n\n" % len(cases))
+
+examples_h.close()
+examples_c.close()
diff --git a/third_party/heimdal/lib/wind/generate.py b/third_party/heimdal/lib/wind/generate.py
new file mode 100644
index 0000000..0a32fcd
--- /dev/null
+++ b/third_party/heimdal/lib/wind/generate.py
@@ -0,0 +1,86 @@
+#!/usr/local/bin/python
+# -*- coding: iso-8859-1 -*-
+
+# $Id$
+
+# Copyright (c) 2004 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+import datetime
+import string
+import os
+import sys
+
+class GeneratedFile :
+ "Represents a generated file"
+ def __init__(self, name) :
+ "Create a new GeneratedFile with name"
+ self.name = os.path.basename(name)
+ self.file = open(name, 'w')
+ self.file.write('/* ' + name + ' */\n')
+ self.file.write('/* Automatically generated at ' +
+ datetime.datetime.now().isoformat() +
+ ' */\n\n')
+
+ def close(self) :
+ """End and close the file header"""
+ self.file.close()
+
+
+class Header(GeneratedFile) :
+ "Represents a generated header file"
+ if sys.hexversion>0x300000f:
+ guardTrans = bytes.maketrans(b'-.', b'__')
+ else:
+ import string
+ guardTrans = string.maketrans('-.', '__')
+ def makeGuard(self) :
+ """Return a name to be used as ifdef guard"""
+ return self.name.translate(self.guardTrans).upper()
+
+ def __init__(self, name) :
+ "Create a new Header with name"
+ GeneratedFile.__init__(self, name)
+ self.guard = self.makeGuard()
+ self.file.write('#ifndef ' + self.guard + '\n')
+ self.file.write('#define ' + self.guard + ' 1\n')
+
+ def close(self) :
+ """End and close the file header"""
+ self.file.write('#endif /* ' + self.guard + ' */\n')
+ GeneratedFile.close(self)
+
+
+class Implementation(GeneratedFile) :
+ "Represents a generated implementation file"
+ def __init__(self, name) :
+ "Create a new Implementation with name"
+ GeneratedFile.__init__(self, name)
diff --git a/third_party/heimdal/lib/wind/idn-lookup.c b/third_party/heimdal/lib/wind/idn-lookup.c
new file mode 100644
index 0000000..378c912
--- /dev/null
+++ b/third_party/heimdal/lib/wind/idn-lookup.c
@@ -0,0 +1,164 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <assert.h>
+#include <err.h>
+#include <netdb.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+
+#include <getarg.h>
+#include <roken.h>
+
+#include "windlocl.h"
+
+static int version_flag = 0;
+static int help_flag = 0;
+
+
+static int
+is_separator(uint32_t u)
+{
+ return u == 0x002E || u == 0x3002;
+}
+
+static void
+lookup(const char *name)
+{
+ unsigned i;
+ char encoded[1024];
+ char *ep;
+ int ret;
+ struct addrinfo hints;
+ struct addrinfo *ai;
+
+ size_t u_len = strlen(name);
+ uint32_t *u = malloc(u_len * sizeof(uint32_t));
+ size_t norm_len = u_len * 2;
+ uint32_t *norm = malloc(norm_len * sizeof(uint32_t));
+
+ if (u == NULL && u_len != 0)
+ errx(1, "malloc failed");
+ if (norm == NULL && norm_len != 0)
+ errx(1, "malloc failed");
+
+ ret = wind_utf8ucs4(name, u, &u_len);
+ if (ret)
+ errx(1, "utf8 conversion failed");
+ ret = wind_stringprep(u, u_len, norm, &norm_len, WIND_PROFILE_NAME);
+ if (ret)
+ errx(1, "stringprep failed");
+ free(u);
+
+ ep = encoded;
+ for (i = 0; i < norm_len; ++i) {
+ unsigned j;
+ size_t len;
+
+ for (j = i; j < norm_len && !is_separator(norm[j]); ++j)
+ ;
+ len = sizeof(encoded) - (ep - encoded);
+ ret = wind_punycode_label_toascii(norm + i, j - i, ep, &len);
+ if (ret)
+ errx(1, "punycode failed");
+
+ ep += len;
+ *ep++ = '.';
+ i = j;
+ }
+ *ep = '\0';
+ free(norm);
+
+ printf("Converted \"%s\" into \"%s\"\n", name, encoded);
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_flags = AI_CANONNAME;
+ ret = getaddrinfo(encoded, NULL, &hints, &ai);
+ if(ret)
+ errx(1, "getaddrinfo failed: %s", gai_strerror(ret));
+ printf("canonical-name: %s\n", ai->ai_canonname);
+ freeaddrinfo(ai);
+}
+
+static struct getargs args[] = {
+ {"version", 0, arg_flag, &version_flag,
+ "print version", NULL },
+ {"help", 0, arg_flag, &help_flag,
+ NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+ arg_printusage(args, sizeof(args)/sizeof(args[0]), NULL,
+ "dns-names ...");
+ exit (ret);
+}
+
+int
+main(int argc, char **argv)
+{
+ int optidx = 0;
+ unsigned i;
+
+ setprogname (argv[0]);
+
+ if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+ usage(1);
+
+ if (help_flag)
+ usage (0);
+
+ if(version_flag){
+ print_version(NULL);
+ exit(0);
+ }
+
+ argc -= optidx;
+ argv += optidx;
+
+ if (argc == 0)
+ usage(1);
+
+ for (i = 0; i < argc; ++i) {
+ if (argv[i][0]) /* Quiet lint */
+ lookup(argv[i]);
+ }
+ return 0;
+}
diff --git a/third_party/heimdal/lib/wind/ldap.c b/third_party/heimdal/lib/wind/ldap.c
new file mode 100644
index 0000000..e7cab8e
--- /dev/null
+++ b/third_party/heimdal/lib/wind/ldap.c
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "windlocl.h"
+#include <assert.h>
+
+static int
+put_char(uint32_t *out, size_t *o, uint32_t c, size_t out_len)
+{
+ if (*o >= out_len)
+ return 1;
+ out[*o] = c;
+ (*o)++;
+ return 0;
+}
+
+int
+_wind_ldap_case_exact_attribute(const uint32_t *tmp,
+ size_t olen,
+ uint32_t *out,
+ size_t *out_len)
+{
+ size_t o = 0, i = 0;
+
+ if (olen == 0) {
+ *out_len = 0;
+ return 0;
+ }
+
+ if (put_char(out, &o, 0x20, *out_len))
+ return WIND_ERR_OVERRUN;
+ while(i < olen && tmp[i] == 0x20) /* skip initial spaces */
+ i++;
+
+ while (i < olen) {
+ if (tmp[i] == 0x20) {
+ if (put_char(out, &o, 0x20, *out_len) ||
+ put_char(out, &o, 0x20, *out_len))
+ return WIND_ERR_OVERRUN;
+ while(i < olen && tmp[i] == 0x20) /* skip middle spaces */
+ i++;
+ } else {
+ if (put_char(out, &o, tmp[i++], *out_len))
+ return WIND_ERR_OVERRUN;
+ }
+ }
+ assert(o > 0);
+
+ /* only one spaces at the end */
+ if (o == 1 && out[0] == 0x20)
+ o = 0;
+ else if (out[o - 1] == 0x20) {
+ if (out[o - 2] == 0x20)
+ o--;
+ } else
+ put_char(out, &o, 0x20, *out_len);
+
+ *out_len = o;
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/wind/libwind-exports.def b/third_party/heimdal/lib/wind/libwind-exports.def
new file mode 100644
index 0000000..32dab4b
--- /dev/null
+++ b/third_party/heimdal/lib/wind/libwind-exports.def
@@ -0,0 +1,27 @@
+EXPORTS
+ wind_stringprep
+ wind_profile
+ wind_punycode_label_toascii
+ wind_utf8ucs4
+ wind_utf8ucs4_length
+ wind_ucs4utf8
+ wind_ucs4utf8_length
+ wind_ucs2utf8
+ wind_utf8ucs2
+ wind_utf8ucs2_length
+ wind_ucs2utf8_length
+ wind_ucs2read
+ wind_ucs2write
+
+ initialize_wind_error_table_r ;!
+
+; testing
+ _wind_combining_class
+ _wind_stringprep_testbidi
+ _wind_stringprep_error
+ _wind_stringprep_prohibited
+ _wind_stringprep_map
+ _wind_stringprep_normalize
+ _wind_ldap_case_exact_attribute
+;! _wind_ucs2read
+
diff --git a/third_party/heimdal/lib/wind/map.c b/third_party/heimdal/lib/wind/map.c
new file mode 100644
index 0000000..2485d39
--- /dev/null
+++ b/third_party/heimdal/lib/wind/map.c
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include "windlocl.h"
+
+#include <stdlib.h>
+
+#include "map_table.h"
+
+static int
+translation_cmp(const void *key, const void *data)
+{
+ const struct translation *t1 = (const struct translation *)key;
+ const struct translation *t2 = (const struct translation *)data;
+
+ return t1->key - t2->key;
+}
+
+int
+_wind_stringprep_map(const uint32_t *in, size_t in_len,
+ uint32_t *out, size_t *out_len,
+ wind_profile_flags flags)
+{
+ unsigned i;
+ unsigned o = 0;
+
+ for (i = 0; i < in_len; ++i) {
+ struct translation ts = {in[i], 0, 0, 0};
+ const struct translation *s;
+
+ s = (const struct translation *)
+ bsearch(&ts, _wind_map_table, _wind_map_table_size,
+ sizeof(_wind_map_table[0]),
+ translation_cmp);
+ if (s != NULL && (s->flags & flags)) {
+ unsigned j;
+
+ for (j = 0; j < s->val_len; ++j) {
+ if (o >= *out_len)
+ return WIND_ERR_OVERRUN;
+ out[o++] = _wind_map_table_val[s->val_offset + j];
+ }
+ } else {
+ if (o >= *out_len)
+ return WIND_ERR_OVERRUN;
+ out[o++] = in[i];
+
+ }
+ }
+ *out_len = o;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/wind/normalize.c b/third_party/heimdal/lib/wind/normalize.c
new file mode 100644
index 0000000..8f3991d
--- /dev/null
+++ b/third_party/heimdal/lib/wind/normalize.c
@@ -0,0 +1,325 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include "windlocl.h"
+
+#include <assert.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <stdio.h>
+
+#include "roken.h"
+
+#include "normalize_table.h"
+
+static int
+translation_cmp(const void *key, const void *data)
+{
+ const struct translation *t1 = (const struct translation *)key;
+ const struct translation *t2 = (const struct translation *)data;
+
+ return t1->key - t2->key;
+}
+
+enum { s_base = 0xAC00};
+enum { s_count = 11172};
+enum { l_base = 0x1100};
+enum { l_count = 19};
+enum { v_base = 0x1161};
+enum { v_count = 21};
+enum { t_base = 0x11A7};
+enum { t_count = 28};
+enum { n_count = v_count * t_count};
+
+static int
+hangul_decomp(const uint32_t *in, size_t in_len,
+ uint32_t *out, size_t *out_len)
+{
+ uint32_t u = *in;
+ unsigned s_index;
+ unsigned l, v, t;
+ unsigned o;
+
+ if (u < s_base || u >= s_base + s_count)
+ return 0;
+ s_index = u - s_base;
+ l = l_base + s_index / n_count;
+ v = v_base + (s_index % n_count) / t_count;
+ t = t_base + s_index % t_count;
+ o = 2;
+ if (t != t_base)
+ ++o;
+ if (*out_len < o)
+ return WIND_ERR_OVERRUN;
+ out[0] = l;
+ out[1] = v;
+ if (t != t_base)
+ out[2] = t;
+ *out_len = o;
+ return 1;
+}
+
+static uint32_t
+hangul_composition(const uint32_t *in, size_t in_len)
+{
+ if (in_len < 2)
+ return 0;
+ if (in[0] >= l_base && in[0] < l_base + l_count) {
+ unsigned l_index = in[0] - l_base;
+ unsigned v_index;
+
+ if (in[1] < v_base || in[1] >= v_base + v_count)
+ return 0;
+ v_index = in[1] - v_base;
+ return (l_index * v_count + v_index) * t_count + s_base;
+ } else if (in[0] >= s_base && in[0] < s_base + s_count) {
+ unsigned s_index = in[0] - s_base;
+ unsigned t_index;
+
+ if (s_index % t_count != 0)
+ return 0;
+ if (in[1] < t_base || in[1] >= t_base + t_count)
+ return 0;
+ t_index = in[1] - t_base;
+ return in[0] + t_index;
+ }
+ return 0;
+}
+
+static int
+compat_decomp(const uint32_t *in, size_t in_len,
+ uint32_t *out, size_t *out_len)
+{
+ unsigned i;
+ unsigned o = 0;
+
+ for (i = 0; i < in_len; ++i) {
+ struct translation ts = {in[i], 0, 0};
+ size_t sub_len = *out_len - o;
+ int ret;
+
+ ret = hangul_decomp(in + i, in_len - i,
+ out + o, &sub_len);
+ if (ret) {
+ if (ret == WIND_ERR_OVERRUN)
+ return ret;
+ o += sub_len;
+ } else {
+ void *s = bsearch(&ts,
+ _wind_normalize_table,
+ _wind_normalize_table_size,
+ sizeof(_wind_normalize_table[0]),
+ translation_cmp);
+ if (s != NULL) {
+ const struct translation *t = (const struct translation *)s;
+
+ ret = compat_decomp(_wind_normalize_val_table + t->val_offset,
+ t->val_len,
+ out + o, &sub_len);
+ if (ret)
+ return ret;
+ o += sub_len;
+ } else {
+ if (o >= *out_len)
+ return WIND_ERR_OVERRUN;
+ out[o++] = in[i];
+
+ }
+ }
+ }
+ *out_len = o;
+ return 0;
+}
+
+static void
+swap_char(uint32_t * a, uint32_t * b)
+{
+ uint32_t t;
+ t = *a;
+ *a = *b;
+ *b = t;
+}
+
+/* Unicode 5.2.0 D109 Canonical Ordering for a sequence of code points
+ * that all have Canonical_Combining_Class > 0 */
+static void
+canonical_reorder_sequence(uint32_t * a, size_t len)
+{
+ size_t i, j;
+
+ if (len <= 1)
+ return;
+
+ for (i = 1; i < len; i++) {
+ for (j = i;
+ j > 0 &&
+ _wind_combining_class(a[j]) < _wind_combining_class(a[j-1]);
+ j--)
+ swap_char(&a[j], &a[j-1]);
+ }
+}
+
+static void
+canonical_reorder(uint32_t *tmp, size_t tmp_len)
+{
+ size_t i;
+
+ for (i = 0; i < tmp_len; ++i) {
+ int cc = _wind_combining_class(tmp[i]);
+ if (cc) {
+ size_t j;
+ for (j = i + 1;
+ j < tmp_len && _wind_combining_class(tmp[j]);
+ ++j)
+ ;
+ canonical_reorder_sequence(&tmp[i], j - i);
+ i = j;
+ }
+ }
+}
+
+static uint32_t
+find_composition(const uint32_t *in, unsigned in_len)
+{
+ unsigned short canon_index = 0;
+ uint32_t cur;
+ unsigned n = 0;
+
+ cur = hangul_composition(in, in_len);
+ if (cur)
+ return cur;
+
+ do {
+ const struct canon_node *c = &_wind_canon_table[canon_index];
+ unsigned i;
+
+ if (n % 5 == 0) {
+ if (in_len-- == 0)
+ return c->val;
+ cur = *in++;
+ }
+
+ i = cur >> 16;
+ if (i < c->next_start || i >= c->next_end)
+ canon_index = 0;
+ else
+ canon_index =
+ _wind_canon_next_table[c->next_offset + i - c->next_start];
+ if (canon_index != 0) {
+ cur = (cur << 4) & 0xFFFFF;
+ ++n;
+ }
+ } while (canon_index != 0);
+ return 0;
+}
+
+static int
+combine(const uint32_t *in, size_t in_len,
+ uint32_t *out, size_t *out_len)
+{
+ unsigned i;
+ int ostarter;
+ unsigned o = 0;
+ int old_cc;
+
+ for (i = 0; i < in_len;) {
+ while (i < in_len && _wind_combining_class(in[i]) != 0) {
+ out[o++] = in[i++];
+ }
+ if (i < in_len) {
+ if (o >= *out_len)
+ return WIND_ERR_OVERRUN;
+ ostarter = o;
+ out[o++] = in[i++];
+ old_cc = -1;
+
+ while (i < in_len) {
+ uint32_t comb;
+ uint32_t v[2];
+ int cc;
+
+ v[0] = out[ostarter];
+ v[1] = in[i];
+
+ cc = _wind_combining_class(in[i]);
+ if (old_cc != cc && (comb = find_composition(v, 2))) {
+ out[ostarter] = comb;
+ } else if (cc == 0) {
+ break;
+ } else {
+ if (o >= *out_len)
+ return WIND_ERR_OVERRUN;
+ out[o++] = in[i];
+ old_cc = cc;
+ }
+ ++i;
+ }
+ }
+ }
+ *out_len = o;
+ return 0;
+}
+
+int
+_wind_stringprep_normalize(const uint32_t *in, size_t in_len,
+ uint32_t *out, size_t *out_len)
+{
+ size_t tmp_len;
+ uint32_t *tmp;
+ int ret;
+
+ if (in_len == 0) {
+ *out_len = 0;
+ return 0;
+ }
+
+ tmp_len = in_len * 4;
+ if (tmp_len < MAX_LENGTH_CANON)
+ tmp_len = MAX_LENGTH_CANON;
+ tmp = malloc(tmp_len * sizeof(uint32_t));
+ if (tmp == NULL)
+ return ENOMEM;
+
+ ret = compat_decomp(in, in_len, tmp, &tmp_len);
+ if (ret) {
+ free(tmp);
+ return ret;
+ }
+ canonical_reorder(tmp, tmp_len);
+ ret = combine(tmp, tmp_len, out, out_len);
+ free(tmp);
+ return ret;
+}
diff --git a/third_party/heimdal/lib/wind/punycode.c b/third_party/heimdal/lib/wind/punycode.c
new file mode 100644
index 0000000..2b190ce
--- /dev/null
+++ b/third_party/heimdal/lib/wind/punycode.c
@@ -0,0 +1,168 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <string.h>
+#include "windlocl.h"
+
+static const unsigned base = 36;
+static const unsigned t_min = 1;
+static const unsigned t_max = 26;
+static const unsigned skew = 38;
+static const unsigned damp = 700;
+static const unsigned initial_n = 128;
+static const unsigned initial_bias = 72;
+
+static unsigned
+digit(unsigned n)
+{
+ return "abcdefghijklmnopqrstuvwxyz0123456789"[n];
+}
+
+static unsigned
+adapt(unsigned delta, unsigned numpoints, int first)
+{
+ unsigned k;
+
+ if (first)
+ delta = delta / damp;
+ else
+ delta /= 2;
+ delta += delta / numpoints;
+ k = 0;
+ while (delta > ((base - t_min) * t_max) / 2) {
+ delta /= base - t_min;
+ k += base;
+ }
+ return k + (((base - t_min + 1) * delta) / (delta + skew));
+}
+
+/**
+ * Convert an UCS4 string to a puny-coded DNS label string suitable
+ * when combined with delimiters and other labels for DNS lookup.
+ *
+ * @param in an UCS4 string to convert
+ * @param in_len the length of in.
+ * @param out the resulting puny-coded string. The string is not NUL
+ * terminatied.
+ * @param out_len before processing out_len should be the length of
+ * the out variable, after processing it will be the length of the out
+ * string.
+ *
+ * @return returns 0 on success, an wind error code otherwise
+ * @ingroup wind
+ */
+
+int
+wind_punycode_label_toascii(const uint32_t *in, size_t in_len,
+ char *out, size_t *out_len)
+{
+ unsigned n = initial_n;
+ unsigned delta = 0;
+ unsigned bias = initial_bias;
+ unsigned h = 0;
+ unsigned b;
+ unsigned i;
+ unsigned o = 0;
+ unsigned m;
+
+ for (i = 0; i < in_len; ++i) {
+ if (in[i] < 0x80) {
+ ++h;
+ if (o >= *out_len)
+ return WIND_ERR_OVERRUN;
+ out[o++] = in[i];
+ }
+ }
+ b = h;
+ if (b > 0) {
+ if (o >= *out_len)
+ return WIND_ERR_OVERRUN;
+ out[o++] = 0x2D;
+ }
+ /* is this string punycoded */
+ if (h < in_len) {
+ if (o + 4 >= *out_len)
+ return WIND_ERR_OVERRUN;
+ memmove(out + 4, out, o);
+ memcpy(out, "xn--", 4);
+ o += 4;
+ }
+
+ while (h < in_len) {
+ m = (unsigned)-1;
+ for (i = 0; i < in_len; ++i)
+ if(in[i] < m && in[i] >= n)
+ m = in[i];
+
+ delta += (m - n) * (h + 1);
+ n = m;
+ for (i = 0; i < in_len; ++i) {
+ if (in[i] < n) {
+ ++delta;
+ } else if (in[i] == n) {
+ unsigned q = delta;
+ unsigned k;
+ for (k = base; ; k += base) {
+ unsigned t;
+ if (k <= bias)
+ t = t_min;
+ else if (k >= bias + t_max)
+ t = t_max;
+ else
+ t = k - bias;
+ if (q < t)
+ break;
+ if (o >= *out_len)
+ return WIND_ERR_OVERRUN;
+ out[o++] = digit(t + ((q - t) % (base - t)));
+ q = (q - t) / (base - t);
+ }
+ if (o >= *out_len)
+ return WIND_ERR_OVERRUN;
+ out[o++] = digit(q);
+ /* output */
+ bias = adapt(delta, h + 1, h == b);
+ delta = 0;
+ ++h;
+ }
+ }
+ ++delta;
+ ++n;
+ }
+
+ *out_len = o;
+ return 0;
+}
diff --git a/third_party/heimdal/lib/wind/rfc3454.py b/third_party/heimdal/lib/wind/rfc3454.py
new file mode 100644
index 0000000..33f70a9
--- /dev/null
+++ b/third_party/heimdal/lib/wind/rfc3454.py
@@ -0,0 +1,60 @@
+#!/usr/local/bin/python
+# -*- coding: iso-8859-1 -*-
+
+# $Id$
+
+# Copyright (c) 2004 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+import re
+import string
+
+def read(filename):
+ """return a dict of tables from rfc3454"""
+ f = open(filename, 'r')
+ inTable = False
+ ret = {}
+ while True:
+ l = f.readline()
+ if not l:
+ break
+ if inTable:
+ m = re.search('^ *----- End Table ([A-Z0-9\.]+) ----- *$', l)
+ if m:
+ ret[m.group(1)] = t
+ inTable = False
+ else:
+ t.append(l)
+ if re.search('^ *----- Start Table ([A-Z0-9\.]+) ----- *$', l):
+ inTable = True
+ t = []
+ f.close()
+ return ret
diff --git a/third_party/heimdal/lib/wind/rfc4518.py b/third_party/heimdal/lib/wind/rfc4518.py
new file mode 100644
index 0000000..a222fce
--- /dev/null
+++ b/third_party/heimdal/lib/wind/rfc4518.py
@@ -0,0 +1,150 @@
+#!/usr/local/bin/python
+# -*- coding: iso-8859-1 -*-
+
+# $Id$
+
+# Copyright (c) 2004, 2008 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+import re
+import string
+
+def read():
+ """return a dict of tables from rfc4518"""
+
+ ret = {}
+
+#2.2. Map
+#
+# SOFT HYPHEN (U+00AD) and MONGOLIAN TODO SOFT HYPHEN (U+1806) code
+# points are mapped to nothing. COMBINING GRAPHEME JOINER (U+034F) and
+# VARIATION SELECTORs (U+180B-180D, FF00-FE0F) code points are also
+# mapped to nothing. The OBJECT REPLACEMENT CHARACTER (U+FFFC) is
+# mapped to nothing.
+
+ t = []
+ t.append(" 00AD; ; Map to nothing")
+ t.append(" 1806; ; Map to nothing")
+ t.append(" 034F; ; Map to nothing")
+
+ t.append(" 180B; ; Map to nothing")
+ t.append(" 180C; ; Map to nothing")
+ t.append(" 180D; ; Map to nothing")
+
+ t.append(" FE00; ; Map to nothing")
+ t.append(" FE01; ; Map to nothing")
+ t.append(" FE02; ; Map to nothing")
+ t.append(" FE03; ; Map to nothing")
+ t.append(" FE04; ; Map to nothing")
+ t.append(" FE05; ; Map to nothing")
+ t.append(" FE06; ; Map to nothing")
+ t.append(" FE07; ; Map to nothing")
+ t.append(" FE08; ; Map to nothing")
+ t.append(" FE09; ; Map to nothing")
+ t.append(" FE0A; ; Map to nothing")
+ t.append(" FE0B; ; Map to nothing")
+ t.append(" FE0C; ; Map to nothing")
+ t.append(" FE0D; ; Map to nothing")
+ t.append(" FE0E; ; Map to nothing")
+ t.append(" FE0F; ; Map to nothing")
+
+ t.append(" FFFC; ; Map to nothing")
+
+# CHARACTER TABULATION (U+0009), LINE FEED (LF) (U+000A), LINE
+# TABULATION (U+000B), FORM FEED (FF) (U+000C), CARRIAGE RETURN (CR)
+# (U+000D), and NEXT LINE (NEL) (U+0085) are mapped to SPACE (U+0020).
+
+ t.append(" 0009; 0020 ; Map to SPACE")
+ t.append(" 000A; 0020 ; Map to SPACE")
+ t.append(" 000B; 0020 ; Map to SPACE")
+ t.append(" 000C; 0020 ; Map to SPACE")
+ t.append(" 000D; 0020 ; Map to SPACE")
+ t.append(" 0085; 0020 ; Map to SPACE")
+
+# All other control code (e.g., Cc) points or code points with a
+# control function (e.g., Cf) are mapped to nothing. The following is
+# a complete list of these code points: U+0000-0008, 000E-001F, 007F-
+# 0084, 0086-009F, 06DD, 070F, 180E, 200C-200F, 202A-202E, 2060-2063,
+# 206A-206F, FEFF, FFF9-FFFB, 1D173-1D17A, E0001, E0020-E007F.
+
+ t.append(" 0000-0008; ; Map to nothing")
+ t.append(" 000E-001F; ; Map to nothing")
+ t.append(" 007F-0084; ; Map to nothing")
+ t.append(" 0086-009F; ; Map to nothing")
+ t.append(" 06DD; ; Map to nothing")
+ t.append(" 070F; ; Map to nothing")
+ t.append(" 180E; ; Map to nothing")
+ t.append(" 200C-200F; ; Map to nothing")
+ t.append(" 202A-202E; ; Map to nothing")
+ t.append(" 2060-2063; ; Map to nothing")
+ t.append(" 206A-206F; ; Map to nothing")
+ t.append(" FEFF; ; Map to nothing")
+ t.append(" FFF9-FFFB; ; Map to nothing")
+ t.append(" 1D173-1D17A; ; Map to nothing")
+ t.append(" E0001; ; Map to nothing")
+ t.append(" E0020-E007F; ; Map to nothing")
+
+# ZERO WIDTH SPACE (U+200B) is mapped to nothing. All other code
+# points with Separator (space, line, or paragraph) property (e.g., Zs,
+# Zl, or Zp) are mapped to SPACE (U+0020). The following is a complete
+# list of these code points: U+0020, 00A0, 1680, 2000-200A, 2028-2029,
+# 202F, 205F, 3000.
+
+ t.append(" 200B; ; Map to nothing")
+ t.append(" 0020; 0020; Map to SPACE")
+ t.append(" 00A0; 0020; Map to SPACE")
+ t.append(" 1680; 0020; Map to SPACE")
+ t.append(" 2000-200A; 0020; Map to SPACE")
+ t.append(" 2028-2029; 0020; Map to SPACE")
+ t.append(" 202F; 0020; Map to SPACE")
+ t.append(" 205F; 0020; Map to SPACE")
+ t.append(" 3000; 0020; Map to SPACE")
+
+ ret["rfc4518-map"] = t
+
+# For case ignore, numeric, and stored prefix string matching rules,
+# characters are case folded per B.2 of [RFC3454].
+
+ t = []
+
+#2.4. Prohibit
+
+# The REPLACEMENT CHARACTER (U+FFFD) code point is prohibited.
+
+ t.append(" FFFD;")
+
+ ret["rfc4518-error"] = t
+
+ t = []
+
+
+
+ return ret
diff --git a/third_party/heimdal/lib/wind/stringprep.c b/third_party/heimdal/lib/wind/stringprep.c
new file mode 100644
index 0000000..002bc72
--- /dev/null
+++ b/third_party/heimdal/lib/wind/stringprep.c
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) 2004, 2006, 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include "windlocl.h"
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+/**
+ * Process a input UCS4 string according a string-prep profile.
+ *
+ * @param in input UCS4 string to process
+ * @param in_len length of the input string
+ * @param out output UCS4 string
+ * @param out_len length of the output string.
+ * @param flags stringprep profile.
+ *
+ * @return returns 0 on success, an wind error code otherwise
+ * @ingroup wind
+ */
+
+int
+wind_stringprep(const uint32_t *in, size_t in_len,
+ uint32_t *out, size_t *out_len,
+ wind_profile_flags flags)
+{
+ size_t tmp_len = in_len * 3;
+ uint32_t *tmp;
+ int ret;
+ size_t olen;
+
+ if (in_len == 0) {
+ *out_len = 0;
+ return 0;
+ }
+
+ tmp = malloc(tmp_len * sizeof(uint32_t));
+ if (tmp == NULL)
+ return ENOMEM;
+
+ ret = _wind_stringprep_map(in, in_len, tmp, &tmp_len, flags);
+ if (ret) {
+ free(tmp);
+ return ret;
+ }
+
+ olen = *out_len;
+ ret = _wind_stringprep_normalize(tmp, tmp_len, tmp, &olen);
+ if (ret) {
+ free(tmp);
+ return ret;
+ }
+ ret = _wind_stringprep_prohibited(tmp, olen, flags);
+ if (ret) {
+ free(tmp);
+ return ret;
+ }
+ ret = _wind_stringprep_testbidi(tmp, olen, flags);
+ if (ret) {
+ free(tmp);
+ return ret;
+ }
+
+ /* Insignificant Character Handling for ldap-prep */
+ if (flags & WIND_PROFILE_LDAP_CASE_EXACT_ATTRIBUTE) {
+ ret = _wind_ldap_case_exact_attribute(tmp, olen, out, out_len);
+#if 0
+ } else if (flags & WIND_PROFILE_LDAP_CASE_EXACT_ASSERTION) {
+ } else if (flags & WIND_PROFILE_LDAP_NUMERIC) {
+ } else if (flags & WIND_PROFILE_LDAP_TELEPHONE) {
+#endif
+ } else {
+ memcpy(out, tmp, sizeof(out[0]) * olen);
+ *out_len = olen;
+ }
+ free(tmp);
+
+ return ret;
+}
+
+static const struct {
+ const char *name;
+ wind_profile_flags flags;
+} profiles[] = {
+ { "nameprep", WIND_PROFILE_NAME },
+ { "saslprep", WIND_PROFILE_SASL },
+ { "ldapprep", WIND_PROFILE_LDAP }
+};
+
+/**
+ * Try to find the profile given a name.
+ *
+ * @param name name of the profile.
+ * @param flags the resulting profile.
+ *
+ * @return returns 0 on success, an wind error code otherwise
+ * @ingroup wind
+ */
+
+int
+wind_profile(const char *name, wind_profile_flags *flags)
+{
+ unsigned int i;
+
+ for (i = 0; i < sizeof(profiles)/sizeof(profiles[0]); i++) {
+ if (strcasecmp(profiles[i].name, name) == 0) {
+ *flags = profiles[i].flags;
+ return 0;
+ }
+ }
+ return WIND_ERR_NO_PROFILE;
+}
diff --git a/third_party/heimdal/lib/wind/stringprep.py b/third_party/heimdal/lib/wind/stringprep.py
new file mode 100644
index 0000000..cff4d02
--- /dev/null
+++ b/third_party/heimdal/lib/wind/stringprep.py
@@ -0,0 +1,92 @@
+#!/usr/local/bin/python
+# -*- coding: iso-8859-1 -*-
+
+# $Id$
+
+# Copyright (c) 2008 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+import re
+import string
+
+def _merge_table(res, source):
+ for table in source.keys():
+ res[table] = res.get(table, []) + source.get(table, [])
+
+name_error = ['C.1.2', 'C.2.2', 'C.3', 'C.4', 'C.5', 'C.6', 'C.7', 'C.8', 'C.9']
+ldap_error = ['A.1', 'C.3', 'C.4', 'C.5', 'C.8', 'rfc4518-error' ]
+sasl_error = ['C.1.2', 'C.2.1', 'C.2.2', 'C.3', 'C.4', 'C.5', 'C.6', 'C.7', 'C.8', 'C.9']
+
+name_map = ['B.1', 'B.2']
+ldap_map = ['rfc4518-map']
+ldap_case_map = ['rfc4518-map', 'B.2']
+sasl_map = ['C.1.2', 'B.1']
+
+def symbols(tabledict, tables):
+ """return CPP symbols to use for this symbols"""
+ list = []
+ for x in tables:
+ list = list + tabledict.get(x, [])
+ if len(list) == 0:
+ return ""
+ return "|".join(map(lambda x: "WIND_PROFILE_%s" % (x.upper()), list))
+
+def get_errorlist():
+ d = dict()
+ _merge_table(d, dict(map(lambda x: [x, ['name']], name_error)))
+ _merge_table(d, dict(map(lambda x: [x, ['ldap']], ldap_error)))
+ _merge_table(d, dict(map(lambda x: [x, ['sasl']], sasl_error)))
+ return d
+
+def get_maplist():
+ d = dict()
+ _merge_table(d, dict(map(lambda x: [x, ['name']], name_map)))
+ _merge_table(d, dict(map(lambda x: [x, ['ldap']], ldap_map)))
+ _merge_table(d, dict(map(lambda x: [x, ['ldap_case']], ldap_case_map)))
+ _merge_table(d, dict(map(lambda x: [x, ['sasl']], sasl_map)))
+ return d
+
+def sort_merge_trans(trans):
+ trans.sort()
+ ret = []
+ last = 0
+ for x in trans:
+ if last:
+ if last[0] == x[0]:
+ last = (last[0], last[1], last[2], last[3] + x[3])
+ else:
+ ret.append(last)
+ last = x
+ else:
+ last = x
+ if last:
+ ret.append(last)
+ return ret
diff --git a/third_party/heimdal/lib/wind/test-bidi.c b/third_party/heimdal/lib/wind/test-bidi.c
new file mode 100644
index 0000000..6cf5f73
--- /dev/null
+++ b/third_party/heimdal/lib/wind/test-bidi.c
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <stdio.h>
+#include "windlocl.h"
+
+#define MAX_LENGTH 10
+
+struct test {
+ unsigned len;
+ uint32_t vals[MAX_LENGTH];
+};
+
+static struct test passing_cases[] = {
+ {0, {0}},
+ {1, {0x0041}},
+ {1, {0x05be}},
+};
+
+static struct test failing_cases[] = {
+ {2, {0x05be, 0x0041}},
+ {3, {0x05be, 0x0041, 0x05be}},
+};
+
+int
+main(void)
+{
+ unsigned i;
+ unsigned failures = 0;
+
+ for (i = 0; i < sizeof(passing_cases)/sizeof(passing_cases[0]); ++i) {
+ const struct test *t = &passing_cases[i];
+ if (_wind_stringprep_testbidi(t->vals, t->len, WIND_PROFILE_NAME)) {
+ printf ("passing case %u failed\n", i);
+ ++failures;
+ }
+ }
+
+ for (i = 0; i < sizeof(failing_cases)/sizeof(failing_cases[0]); ++i) {
+ const struct test *t = &failing_cases[i];
+ if (!_wind_stringprep_testbidi(t->vals, t->len, WIND_PROFILE_NAME)) {
+ printf ("failing case %u passed\n", i);
+ ++failures;
+ }
+ }
+
+ return failures != 0;
+}
diff --git a/third_party/heimdal/lib/wind/test-ldap.c b/third_party/heimdal/lib/wind/test-ldap.c
new file mode 100644
index 0000000..562c49a
--- /dev/null
+++ b/third_party/heimdal/lib/wind/test-ldap.c
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <stdio.h>
+#include <string.h>
+#include <err.h>
+#include <assert.h>
+#include "windlocl.h"
+
+#define MAX_LENGTH 10
+
+struct testcase {
+ uint32_t in[MAX_LENGTH];
+ size_t ilen;
+ uint32_t out[MAX_LENGTH];
+ size_t olen;
+};
+
+static const struct testcase testcases[] = {
+ { { 0x20 }, 1, { 0 }, 0 },
+ { { 0x20, 0x61 }, 2, { 0x20, 0x61, 0x20}, 3 },
+ { { 0x20, 0x61, 0x20 }, 3, { 0x20, 0x61, 0x20}, 3 },
+ { { 0x20, 0x61, 0x20, 0x61 }, 4, { 0x20, 0x61, 0x20, 0x20, 0x61, 0x20}, 6 }
+};
+
+static const struct testcase testcases2[] = {
+ { { 0x20 }, 1, { 0x20 }, 1 },
+ { { 0x20, 0x41 }, 2, { 0x20, 0x61}, 2 }
+};
+
+
+int
+main(void)
+{
+ uint32_t out[MAX_LENGTH];
+ unsigned failures = 0;
+ unsigned i;
+ size_t olen;
+ int ret;
+
+
+ for (i = 0; i < sizeof(testcases)/sizeof(testcases[0]); ++i) {
+ const struct testcase *t = &testcases[i];
+
+ olen = sizeof(out)/sizeof(out[0]);
+ assert(olen > t->olen);
+
+ ret = _wind_ldap_case_exact_attribute(t->in, t->ilen, out, &olen);
+ if (ret) {
+ printf("wlcea: %u: %d\n", i, ret);
+ ++failures;
+ continue;
+ }
+ if (olen != t->olen) {
+ printf("len wlcea: %u %u != %u\n", i,
+ (unsigned)olen, (unsigned)t->olen);
+ failures++;
+ continue;
+ }
+ if (memcmp(t->out, out, sizeof(out[0]) * olen) != 0) {
+ printf("memcmp wlcea: %u\n", i);
+ failures++;
+ continue;
+ }
+ }
+
+ for (i = 0; i < sizeof(testcases2)/sizeof(testcases2[0]); ++i) {
+ const struct testcase *t = &testcases2[i];
+
+ olen = sizeof(out)/sizeof(out[0]);
+ assert(olen > t->olen);
+
+ ret = wind_stringprep(t->in, t->ilen, out, &olen,
+ WIND_PROFILE_LDAP_CASE);
+
+ if (ret) {
+ printf("wsplc: %u: %d\n", i, ret);
+ ++failures;
+ continue;
+ }
+
+ if (olen != t->olen) {
+ printf("strlen wsplc: %u: %d\n", i, ret);
+ ++failures;
+ continue;
+ }
+ if (memcmp(t->out, out, sizeof(out[0]) * olen) != 0) {
+ printf("memcmp wsplc: %u\n", i);
+ failures++;
+ continue;
+ }
+ }
+
+ return failures != 0;
+}
diff --git a/third_party/heimdal/lib/wind/test-map.c b/third_party/heimdal/lib/wind/test-map.c
new file mode 100644
index 0000000..fcc8600
--- /dev/null
+++ b/third_party/heimdal/lib/wind/test-map.c
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <err.h>
+
+#include "windlocl.h"
+
+#define MAX_LENGTH 2
+
+struct example {
+ uint32_t in[MAX_LENGTH];
+ size_t in_len;
+ uint32_t out[MAX_LENGTH];
+ size_t out_len;
+};
+
+static struct example cases[] = {
+ {{0}, 0, {0}, 0},
+ {{0x0041}, 1, {0x0061}, 1},
+ {{0x0061}, 1, {0x0061}, 1},
+ {{0x00AD}, 1, {0}, 0},
+ {{0x00DF}, 1, {0x0073, 0x0073}, 2}
+};
+
+static int
+try(const struct example *c)
+{
+ int ret;
+ size_t out_len = c->out_len;
+ uint32_t *tmp = malloc(out_len * sizeof(uint32_t));
+ if (tmp == NULL && out_len != 0)
+ err(1, "malloc");
+ ret = _wind_stringprep_map(c->in, c->in_len, tmp, &out_len, WIND_PROFILE_NAME);
+ if (ret) {
+ printf("wind_stringprep_map failed\n");
+ return 1;
+ }
+ if (out_len != c->out_len) {
+ printf("wrong out len\n");
+ free(tmp);
+ return 1;
+ }
+ if (memcmp(c->out, tmp, out_len * sizeof(uint32_t)) != 0) {
+ printf("wrong out data\n");
+ free(tmp);
+ return 1;
+ }
+ free(tmp);
+ return 0;
+}
+
+int
+main(void)
+{
+ unsigned i;
+ unsigned failures = 0;
+
+ for (i = 0; i < sizeof(cases)/sizeof(cases[0]); ++i)
+ failures += try(&cases[i]);
+ return failures != 0;
+}
+
diff --git a/third_party/heimdal/lib/wind/test-normalize.c b/third_party/heimdal/lib/wind/test-normalize.c
new file mode 100644
index 0000000..3e13aee
--- /dev/null
+++ b/third_party/heimdal/lib/wind/test-normalize.c
@@ -0,0 +1,176 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <err.h>
+
+#include <roken.h>
+
+#include "windlocl.h"
+#include "normalize_table.h"
+
+static size_t
+parse_vector(char *buf, uint32_t *v)
+{
+ char *last = NULL;
+ unsigned ret = 0;
+ const char *n;
+ unsigned u;
+
+ for(n = strtok_r(buf, " ", &last);
+ n != NULL;
+ n = strtok_r(NULL, " ", &last)) {
+ if (ret >= MAX_LENGTH_CANON) {
+ errx(1, "increase MAX_LENGTH_CANON");
+ }
+ if (sscanf(n, "%x", &u) != 1) {
+ errx(1, "failed to parse hex: %s", n);
+ }
+ v[ret] = u;
+ ++ret;
+ }
+ return ret;
+}
+
+static void
+dump_vector(const char * msg, uint32_t * v, size_t len)
+{
+ size_t i;
+
+ printf("%s: (%d) ", msg, (int)len);
+ for (i=0; i < len; i++) {
+ printf("%s%x", (i > 0? " ":""), v[i]);
+ }
+ printf("\n");
+}
+
+static int
+test(char *buf, unsigned lineno)
+{
+ char *last;
+ char *c;
+ uint32_t in[MAX_LENGTH_CANON];
+ size_t in_len;
+ uint32_t out[MAX_LENGTH_CANON];
+ size_t out_len;
+ uint32_t *tmp;
+ size_t norm_len;
+ int ret;
+
+ c = strtok_r(buf, ";", &last);
+ if (c == NULL)
+ return 0;
+
+ in_len = parse_vector(c, in);
+ if (strtok_r(NULL, ";", &last) == NULL)
+ return 0;
+ if (strtok_r(NULL, ";", &last) == NULL)
+ return 0;
+ c = strtok_r(NULL, ";", &last);
+ if (c == NULL)
+ return 0;
+ out_len = parse_vector(c, out);
+ if (strtok_r(NULL, ";", &last) == NULL)
+ return 0;
+ c = last;
+
+ norm_len = MAX_LENGTH_CANON;
+ tmp = malloc(norm_len * sizeof(uint32_t));
+ if (tmp == NULL && norm_len != 0)
+ err(1, "malloc");
+ ret = _wind_stringprep_normalize(in, in_len, tmp, &norm_len);
+ if (ret) {
+ printf("wind_stringprep_normalize %s failed\n", c);
+ free(tmp);
+ return 1;
+ }
+ if (out_len != norm_len) {
+ printf("%u: wrong out len (%s)\n", lineno, c);
+ dump_vector("Expected", out, out_len);
+ dump_vector("Received", tmp, norm_len);
+ free(tmp);
+ return 1;
+ }
+ if (memcmp(out, tmp, out_len * sizeof(uint32_t)) != 0) {
+ printf("%u: wrong out data (%s)\n", lineno, c);
+ dump_vector("Expected", out, out_len);
+ dump_vector("Received", tmp, norm_len);
+ free(tmp);
+ return 1;
+ }
+ free(tmp);
+ return 0;
+}
+
+int
+main(int argc, char **argv)
+{
+ FILE *f;
+ char buf[1024];
+ char filename[256] = "NormalizationTest.txt";
+ unsigned failures = 0;
+ unsigned lineno = 0;
+
+ if (argc > 2)
+ errx(1, "usage: %s [file]", argv[0]);
+ else if (argc == 2)
+ strlcpy(filename, argv[1], sizeof(filename));
+
+ f = fopen(filename, "r");
+ if (f == NULL) {
+ const char *srcdir = getenv("srcdir");
+ if (srcdir != NULL) {
+ char longname[256];
+ snprintf(longname, sizeof(longname), "%s/%s", srcdir, filename);
+ f = fopen(longname, "r");
+ }
+ if (f == NULL)
+ err(1, "open %s", filename);
+ }
+ while (fgets(buf, sizeof(buf), f) != NULL) {
+ lineno++;
+ if (buf[0] == '#')
+ continue;
+ if (buf[0] == '@') {
+ continue;
+ }
+ failures += test(buf, lineno);
+ }
+ fclose(f);
+ return failures != 0;
+}
diff --git a/third_party/heimdal/lib/wind/test-prohibited.c b/third_party/heimdal/lib/wind/test-prohibited.c
new file mode 100644
index 0000000..77f62f7
--- /dev/null
+++ b/third_party/heimdal/lib/wind/test-prohibited.c
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <stdio.h>
+#include "windlocl.h"
+
+static uint32_t positives[] = {
+ 0x00A0, 0x3000,
+ 0x0080, 0x009F, 0x206A, 0x206F, 0xFEFF,
+ 0xFFF9, 0xFFFD, 0xFFFE, 0xFFFF,
+ 0x1D173, 0x1D17A,
+ 0xE000, 0xF8FF, 0xF0000, 0xFFFFD,
+ 0x100000, 0x10FFFD,
+ 0xFDD0, 0xFDEF,
+ 0xFFFE, 0xFFFF,
+ 0x1FFFE, 0x1FFFF,
+ 0x2FFFE, 0x2FFFF,
+ 0x3FFFE, 0x3FFFF,
+ 0x4FFFE, 0x4FFFF,
+ 0x5FFFE, 0x5FFFF,
+ 0x6FFFE, 0x6FFFF,
+ 0x7FFFE, 0x7FFFF,
+ 0x8FFFE, 0x8FFFF,
+ 0x9FFFE, 0x9FFFF,
+ 0xAFFFE, 0xAFFFF,
+ 0xBFFFE, 0xBFFFF,
+ 0xCFFFE, 0xCFFFF,
+ 0xDFFFE, 0xDFFFF,
+ 0xEFFFE, 0xEFFFF,
+ 0xFFFFE, 0xFFFFF,
+ 0x10FFFE, 0x10FFFF,
+ 0xD800, 0xDFFF,
+ 0xFFF9,
+ 0xFFFA,
+ 0xFFFB,
+ 0xFFFC,
+ 0x2FF0, 0x2FFB,
+ 0x0340,
+ 0x0341,
+ 0x200E,
+ 0x200F,
+ 0x202A,
+ 0x202B,
+ 0x202C,
+ 0x202D,
+ 0x202E,
+ 0x206A,
+ 0x206B,
+ 0x206C,
+ 0x206D,
+ 0x206E,
+ 0x206F,
+ 0xE0001,
+ 0xE0020,
+ 0xE007F,
+};
+
+static uint32_t negatives[] = {
+ 0x0000, 0x001F, 0x007F,
+ 0x0020, 0x2069, 0x2070, 0x0FFF8,
+ 0x1D172, 0x1D17B,
+ 0xF900,
+ 0xFDCF, 0xFDF0,
+ 0x10000,
+ 0x1FFFD, 0x20000,
+ 0x2FFFD, 0x30000,
+ 0x3FFFD, 0x40000,
+ 0x4FFFD, 0x50000,
+ 0x5FFFD, 0x60000,
+ 0x6FFFD, 0x70000,
+ 0x7FFFD, 0x80000,
+ 0x8FFFD, 0x90000,
+ 0x9FFFD, 0xA0000,
+ 0xAFFFD, 0xB0000,
+ 0xBFFFD, 0xC0000,
+ 0xCFFFD, 0xD0000,
+ 0xDFFFD, 0xE0000,
+ 0xEFFFD,
+ 0x110000,
+ 0xD7FF,
+ 0xFFF8,
+ 0x2FEF, 0x2FFC,
+};
+
+int
+main(void)
+{
+ unsigned i;
+ unsigned failures = 0;
+
+ for (i = 0; i < sizeof(positives)/sizeof(positives[0]); ++i)
+ if (!_wind_stringprep_error(positives[i], WIND_PROFILE_NAME)) {
+ printf ("code-point 0x%x not marked as prohibited\n",
+ positives[i]);
+ ++failures;
+ }
+
+ for (i = 0; i < sizeof(negatives)/sizeof(negatives[0]); ++i)
+ if (_wind_stringprep_error(negatives[i], WIND_PROFILE_NAME)) {
+ printf ("code-point 0x%x not marked as non-prohibited\n",
+ negatives[i]);
+ ++failures;
+ }
+ return failures != 0;
+}
diff --git a/third_party/heimdal/lib/wind/test-punycode.c b/third_party/heimdal/lib/wind/test-punycode.c
new file mode 100644
index 0000000..3dcfe81
--- /dev/null
+++ b/third_party/heimdal/lib/wind/test-punycode.c
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <stdio.h>
+#include <string.h>
+
+#include "windlocl.h"
+#include "punycode_examples.h"
+
+int
+main(void)
+{
+ unsigned i;
+ unsigned failures = 0;
+
+ for (i = 0; i < punycode_examples_size; ++i) {
+ char buf[256];
+ int ret;
+ const struct punycode_example *e = &punycode_examples[i];
+ size_t len;
+
+ len = sizeof(buf);
+ ret = wind_punycode_label_toascii(e->val, e->len, buf, &len);
+ if (ret) {
+ printf("punycode %u (%s) failed: %d\n", i, e->description, ret);
+ ++failures;
+ continue;
+ }
+ if (strncmp(buf, "xn--", 4) == 0) {
+ memmove(buf, buf + 4, len - 4);
+ len -= 4;
+ }
+ if (len != strlen(e->pc)) {
+ printf("punycode %u (%s) wrong len, actual: %u, expected: %u\n",
+ i, e->description,
+ (unsigned int)len, (unsigned int)strlen(e->pc));
+ printf("buf %s != pc: %s\n", buf, e->pc);
+ ++failures;
+ continue;
+ }
+ if (strncasecmp(buf, e->pc, len) != 0) {
+ printf("punycode %u (%s) wrong contents, "
+ "actual: \"%.*s\", expected: \"%s\"\n",
+ i, e->description, (unsigned int)len, buf, e->pc);
+ ++failures;
+ continue;
+ }
+ }
+ return failures != 0;
+}
diff --git a/third_party/heimdal/lib/wind/test-rw.c b/third_party/heimdal/lib/wind/test-rw.c
new file mode 100644
index 0000000..9e39d85
--- /dev/null
+++ b/third_party/heimdal/lib/wind/test-rw.c
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "windlocl.h"
+#include <stdio.h>
+#include <err.h>
+#include <assert.h>
+
+#define MAX_LENGTH 10
+
+
+struct testcase {
+ unsigned int in_flags;
+ size_t in_len;
+ const char *in_ptr;
+ int ret;
+ size_t ucs2_len;
+ uint16_t ucs2[MAX_LENGTH];
+ unsigned int out_flags;
+} testcases[] = {
+ {
+ WIND_RW_BOM,
+ 4, "\xff\xfe\x20\x00",
+ 0,
+ 1, { 0x0020 },
+ WIND_RW_LE
+ },
+ {
+ WIND_RW_BOM,
+ 4, "\xfe\xff\x00\x20",
+ 0,
+ 1, { 0x0020 },
+ WIND_RW_BE
+ },
+ /* only BE BOM */
+ {
+ WIND_RW_BOM,
+ 2, "\xfe\xff",
+ 0,
+ 0, { 0 },
+ WIND_RW_BE
+ },
+ /* no input */
+ {
+ WIND_RW_BOM,
+ 0, "",
+ 0,
+ 0, { 0 },
+ WIND_RW_BOM
+ },
+ /* BOM only */
+ {
+ WIND_RW_BOM,
+ 2, "\xff\xfe",
+ 0,
+ 0, { 0 },
+ WIND_RW_LE
+ },
+ /* water + z */
+ {
+ WIND_RW_BOM|WIND_RW_LE,
+ 4, "\x34\x6C\x7A\x00",
+ 0,
+ 2, { 0x6C34, 0x7a },
+ WIND_RW_LE
+ },
+ /* water + z */
+ {
+ WIND_RW_LE,
+ 4, "\x34\x6C\x7A\x00",
+ 0,
+ 2, { 0x6C34, 0x7a },
+ WIND_RW_LE
+ },
+ /* BOM + water + z */
+ {
+ WIND_RW_BOM,
+ 6, "\xFF\xFE\x34\x6C\x7A\x00",
+ 0,
+ 2, { 0x6C34, 0x7a },
+ WIND_RW_LE
+ },
+ /* BOM + water + z */
+ {
+ WIND_RW_BOM,
+ 6, "\xFE\xFF\x6C\x34\x00\x7A",
+ 0,
+ 2, { 0x6C34, 0x7a },
+ WIND_RW_BE
+ },
+ /* error, odd length */
+ {
+ WIND_RW_BOM,
+ 1, "\xfe",
+ WIND_ERR_LENGTH_NOT_MOD2,
+ 0, { 0 },
+ WIND_RW_BOM
+ },
+ /* error, missing BOM */
+ {
+ WIND_RW_BOM,
+ 2, "\x00\x20",
+ WIND_ERR_NO_BOM,
+ 0, { 0 },
+ WIND_RW_BOM
+ },
+ /* error, overrun */
+ {
+ WIND_RW_BE,
+ 4, "\x00\x20\x00\x20",
+ WIND_ERR_OVERRUN,
+ 1, { 0x20 },
+ WIND_RW_BOM
+ }
+
+};
+
+int
+main(void)
+{
+ unsigned int n, m, flags;
+ uint16_t data[MAX_LENGTH];
+ size_t datalen;
+ int ret;
+
+ for (n = 0; n < sizeof(testcases)/sizeof(testcases[0]); n++) {
+ flags = testcases[n].in_flags;
+
+ datalen = testcases[n].ucs2_len;
+ assert(datalen < sizeof(data));
+
+ ret = wind_ucs2read(testcases[n].in_ptr,
+ testcases[n].in_len,
+ &flags,
+ data,
+ &datalen);
+ if (ret != testcases[n].ret)
+ errx(1, "testcases %u: wind_ucs2read: %d", n, ret);
+
+ /* on error, skip all other tests */
+ if (ret)
+ continue;
+
+ if (flags != testcases[n].out_flags)
+ errx(1, "testcases %u: flags wrong", n);
+
+ if (datalen != testcases[n].ucs2_len)
+ errx(1, "testcases %u: ucs len wrong", n);
+
+ for (m = 0; m < datalen; m++)
+ if (testcases[n].ucs2[m] != data[m])
+ errx(1, "testcases %u: char %u wrong", n, m);
+ }
+
+ return 0;
+}
diff --git a/third_party/heimdal/lib/wind/test-utf8.c b/third_party/heimdal/lib/wind/test-utf8.c
new file mode 100644
index 0000000..0b95032
--- /dev/null
+++ b/third_party/heimdal/lib/wind/test-utf8.c
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <stdio.h>
+#include <string.h>
+#include <err.h>
+#include "windlocl.h"
+
+static const char *failing_testcases[] = {
+ "\x80",
+ "\xFF",
+ "\xC0",
+ "\xDF",
+ "\xE0",
+ "\xEF",
+ "\xF0",
+ "\xF7",
+ "\xC0\x01",
+ "\xC0\x7F",
+ "\xC0\xFF",
+ "\xC0\x80\x80",
+ "\xE0\x01",
+ "\xE0\x7F",
+ "\xE0\x80",
+ "\xE0\xFF",
+ "\xE0\x80\x20",
+ "\xE0\x80\xFF",
+ "\xE0\x80\x80\x80",
+ "\xF0\x01",
+ "\xF0\x80",
+ "\xF0\x80\x01",
+ "\xF0\x80\x80",
+ "\xF0\x80\x80\x01",
+ "\xF0\x80\x80\xFF",
+ NULL
+};
+
+#define MAX_LENGTH 10
+
+struct testcase {
+ const char *utf8_str;
+ size_t len;
+ uint32_t u[MAX_LENGTH];
+ int invalid_ucs2;
+};
+
+static const struct testcase testcases[] = {
+ {"", 0, {0}, 0},
+ {"\x01", 1, {1}, 0},
+ {"\x7F", 1, {0x7F}, 0},
+ {"\x01\x7F", 2, {0x01, 0x7F}, 0},
+ {"\xC0\x80", 1, {0}, 0},
+ {"\xC0\x81", 1, {1}, 0},
+ {"\xC1\x80", 1, {0x40}, 0},
+ {"\xDF\xBF", 1, {0x7FF}, 0},
+ {"\xE0\x80\x80", 1, {0}, 0},
+ {"\xE0\x80\x81", 1, {1}, 0},
+ {"\xE0\x81\x80", 1, {0x40}, 0},
+ {"\xE1\x80\x80", 1, {0x1000}, 0},
+ {"\xEF\xBF\xBF", 1, {0xFFFF}, 0},
+ {"\xF0\x80\x80\x80", 1, {0}, 0},
+ {"\xF0\x80\x80\x81", 1, {1}, 0},
+ {"\xF0\x80\x81\x80", 1, {0x40}, 0},
+ {"\xF0\x81\x80\x80", 1, {0x1000}, 0},
+ {"\xF1\x80\x80\x80", 1, {0x40000}, 0},
+ {"\xF7\xBF\xBF\xBF", 1, {0X1FFFFF}, 1},
+};
+
+int
+main(void)
+{
+ unsigned failures = 0;
+ unsigned i;
+ const char **s;
+ int ret;
+ size_t len, len2;
+ uint32_t u[MAX_LENGTH];
+ char str[MAX_LENGTH * 4];
+
+ for (s = failing_testcases; *s != NULL; ++s) {
+ len = MAX_LENGTH;
+ ret = wind_utf8ucs4(*s, u, &len);
+ if (ret == 0) {
+ printf("utf8 decode of \"%s\" should have failed\n", *s);
+ ++failures;
+ }
+ }
+
+ for (i = 0; i < sizeof(testcases)/sizeof(testcases[0]); ++i) {
+ const struct testcase *t = &testcases[i];
+
+ ret = wind_utf8ucs4_length(t->utf8_str, &len);
+ if (ret) {
+ printf("utf8ucs4 length of \"%s\" should have succeeded\n",
+ t->utf8_str);
+ ++failures;
+ continue;
+ }
+ if (len != t->len) {
+ printf("utf8ucs4_length of \"%s\" has wrong length: "
+ "expected: %u, actual: %u\n",
+ t->utf8_str, (unsigned int)t->len, (unsigned int)len);
+ ++failures;
+ continue;
+ }
+
+ len = MAX_LENGTH;
+ ret = wind_utf8ucs4(t->utf8_str, u, &len);
+ if (ret) {
+ printf("utf8 decode of \"%s\" should have succeeded\n",
+ t->utf8_str);
+ ++failures;
+ continue;
+ }
+ if (len != t->len) {
+ printf("utf8 decode of \"%s\" has wrong length: "
+ "expected: %u, actual: %u\n",
+ t->utf8_str, (unsigned int)t->len, (unsigned int)len);
+ ++failures;
+ continue;
+ }
+ if (memcmp(t->u, u, len * sizeof(uint32_t)) != 0) {
+ printf("utf8 decode of \"%s\" has wrong data\n",
+ t->utf8_str);
+ ++failures;
+ continue;
+ }
+ if (t->invalid_ucs2 == 0) {
+ len2 = sizeof(str);
+ ret = wind_ucs4utf8(u, len, str, &len2);
+ if (ret) {
+ printf("ucs4 decode of \"%s\" should have succeeded\n",
+ t->utf8_str);
+ ++failures;
+ continue;
+ }
+ }
+ }
+
+ return failures != 0;
+}
diff --git a/third_party/heimdal/lib/wind/utf8.c b/third_party/heimdal/lib/wind/utf8.c
new file mode 100644
index 0000000..452b7b2
--- /dev/null
+++ b/third_party/heimdal/lib/wind/utf8.c
@@ -0,0 +1,527 @@
+/*
+ * Copyright (c) 2004, 2006, 2007, 2008 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <config.h>
+#include "windlocl.h"
+
+static int
+utf8toutf32(const unsigned char **pp, uint32_t *out)
+{
+ const unsigned char *p = *pp;
+ unsigned c = *p;
+
+ if (c & 0x80) {
+ if ((c & 0xE0) == 0xC0) {
+ const unsigned c2 = *++p;
+ if ((c2 & 0xC0) == 0x80) {
+ *out = ((c & 0x1F) << 6)
+ | (c2 & 0x3F);
+ } else {
+ return WIND_ERR_INVALID_UTF8;
+ }
+ } else if ((c & 0xF0) == 0xE0) {
+ const unsigned c2 = *++p;
+ if ((c2 & 0xC0) == 0x80) {
+ const unsigned c3 = *++p;
+ if ((c3 & 0xC0) == 0x80) {
+ *out = ((c & 0x0F) << 12)
+ | ((c2 & 0x3F) << 6)
+ | (c3 & 0x3F);
+ } else {
+ return WIND_ERR_INVALID_UTF8;
+ }
+ } else {
+ return WIND_ERR_INVALID_UTF8;
+ }
+ } else if ((c & 0xF8) == 0xF0) {
+ const unsigned c2 = *++p;
+ if ((c2 & 0xC0) == 0x80) {
+ const unsigned c3 = *++p;
+ if ((c3 & 0xC0) == 0x80) {
+ const unsigned c4 = *++p;
+ if ((c4 & 0xC0) == 0x80) {
+ *out = ((c & 0x07) << 18)
+ | ((c2 & 0x3F) << 12)
+ | ((c3 & 0x3F) << 6)
+ | (c4 & 0x3F);
+ } else {
+ return WIND_ERR_INVALID_UTF8;
+ }
+ } else {
+ return WIND_ERR_INVALID_UTF8;
+ }
+ } else {
+ return WIND_ERR_INVALID_UTF8;
+ }
+ } else {
+ return WIND_ERR_INVALID_UTF8;
+ }
+ } else {
+ *out = c;
+ }
+
+ *pp = p;
+
+ return 0;
+}
+
+/**
+ * Convert an UTF-8 string to an UCS4 string.
+ *
+ * @param in an UTF-8 string to convert.
+ * @param out the resulting UCS4 strint, must be at least
+ * wind_utf8ucs4_length() long. If out is NULL, the function will
+ * calculate the needed space for the out variable (just like
+ * wind_utf8ucs4_length()).
+ * @param out_len before processing out_len should be the length of
+ * the out variable, after processing it will be the length of the out
+ * string.
+ *
+ * @return returns 0 on success, an wind error code otherwise
+ * @ingroup wind
+ */
+
+int
+wind_utf8ucs4(const char *in, uint32_t *out, size_t *out_len)
+{
+ const unsigned char *p;
+ size_t o = 0;
+ int ret;
+
+ for (p = (const unsigned char *)in; *p != '\0'; ++p) {
+ uint32_t u;
+
+ ret = utf8toutf32(&p, &u);
+ if (ret)
+ return ret;
+
+ if (out) {
+ if (o >= *out_len)
+ return WIND_ERR_OVERRUN;
+ out[o] = u;
+ }
+ o++;
+ }
+ *out_len = o;
+ return 0;
+}
+
+/**
+ * Calculate the length of from converting a UTF-8 string to a UCS4
+ * string.
+ *
+ * @param in an UTF-8 string to convert.
+ * @param out_len the length of the resulting UCS4 string.
+ *
+ * @return returns 0 on success, an wind error code otherwise
+ * @ingroup wind
+ */
+
+int
+wind_utf8ucs4_length(const char *in, size_t *out_len)
+{
+ return wind_utf8ucs4(in, NULL, out_len);
+}
+
+static const char first_char[4] =
+ { 0x00, 0xC0, 0xE0, 0xF0 };
+
+/**
+ * Convert an UCS4 string to a UTF-8 string.
+ *
+ * @param in an UCS4 string to convert.
+ * @param in_len the length input array.
+
+ * @param out the resulting UTF-8 strint, must be at least
+ * wind_ucs4utf8_length() + 1 long (the extra char for the NUL). If
+ * out is NULL, the function will calculate the needed space for the
+ * out variable (just like wind_ucs4utf8_length()).
+
+ * @param out_len before processing out_len should be the length of
+ * the out variable, after processing it will be the length of the out
+ * string.
+ *
+ * @return returns 0 on success, an wind error code otherwise
+ * @ingroup wind
+ */
+
+int
+wind_ucs4utf8(const uint32_t *in, size_t in_len, char *out, size_t *out_len)
+{
+ uint32_t ch;
+ size_t i, len, o;
+
+ for (o = 0, i = 0; i < in_len; i++) {
+ ch = in[i];
+
+ if (ch < 0x80) {
+ len = 1;
+ } else if (ch < 0x800) {
+ len = 2;
+ } else if (ch < 0x10000) {
+ len = 3;
+ } else if (ch <= 0x10FFFF) {
+ len = 4;
+ } else
+ return WIND_ERR_INVALID_UTF32;
+
+ o += len;
+
+ if (out) {
+ if (o >= *out_len)
+ return WIND_ERR_OVERRUN;
+
+ switch(len) {
+ case 4:
+ out[3] = (ch | 0x80) & 0xbf;
+ ch = ch >> 6;
+ fallthrough;
+ case 3:
+ out[2] = (ch | 0x80) & 0xbf;
+ ch = ch >> 6;
+ fallthrough;
+ case 2:
+ out[1] = (ch | 0x80) & 0xbf;
+ ch = ch >> 6;
+ fallthrough;
+ case 1:
+ out[0] = ch | first_char[len - 1];
+ fallthrough;
+ default:
+ break;
+ }
+ }
+ out += len;
+ }
+ if (out) {
+ if (o + 1 >= *out_len)
+ return WIND_ERR_OVERRUN;
+ *out = '\0';
+ }
+ *out_len = o;
+ return 0;
+}
+
+/**
+ * Calculate the length of from converting a UCS4 string to an UTF-8 string.
+ *
+ * @param in an UCS4 string to convert.
+ * @param in_len the length of UCS4 string to convert.
+ * @param out_len the length of the resulting UTF-8 string.
+ *
+ * @return returns 0 on success, an wind error code otherwise
+ * @ingroup wind
+ */
+
+int
+wind_ucs4utf8_length(const uint32_t *in, size_t in_len, size_t *out_len)
+{
+ return wind_ucs4utf8(in, in_len, NULL, out_len);
+}
+
+/**
+ * Read in an UCS2 from a buffer.
+ *
+ * @param ptr The input buffer to read from.
+ * @param len the length of the input buffer.
+ * @param flags Flags to control the behavior of the function.
+ * @param out the output UCS2, the array must be at least out/2 long.
+ * @param out_len the output length
+ *
+ * @return returns 0 on success, an wind error code otherwise.
+ * @ingroup wind
+ */
+
+int
+wind_ucs2read(const void *ptr, size_t len, unsigned int *flags,
+ uint16_t *out, size_t *out_len)
+{
+ const unsigned char *p = ptr;
+ int little = ((*flags) & WIND_RW_LE);
+ size_t olen = *out_len;
+
+ /** if len is zero, flags are unchanged */
+ if (len == 0) {
+ *out_len = 0;
+ return 0;
+ }
+
+ /** if len is odd, WIND_ERR_LENGTH_NOT_MOD2 is returned */
+ if (len & 1)
+ return WIND_ERR_LENGTH_NOT_MOD2;
+
+ /**
+ * If the flags WIND_RW_BOM is set, check for BOM. If not BOM is
+ * found, check is LE/BE flag is already and use that otherwise
+ * fail with WIND_ERR_NO_BOM. When done, clear WIND_RW_BOM and
+ * the LE/BE flag and set the resulting LE/BE flag.
+ */
+ if ((*flags) & WIND_RW_BOM) {
+ uint16_t bom = (p[0] << 8) + p[1];
+ if (bom == 0xfffe || bom == 0xfeff) {
+ little = (bom == 0xfffe);
+ p += 2;
+ len -= 2;
+ } else if (((*flags) & (WIND_RW_LE|WIND_RW_BE)) != 0) {
+ /* little already set */
+ } else
+ return WIND_ERR_NO_BOM;
+ *flags = ((*flags) & ~(WIND_RW_BOM|WIND_RW_LE|WIND_RW_BE));
+ *flags |= little ? WIND_RW_LE : WIND_RW_BE;
+ }
+
+ while (len) {
+ if (olen < 1)
+ return WIND_ERR_OVERRUN;
+ if (little)
+ *out = (p[1] << 8) + p[0];
+ else
+ *out = (p[0] << 8) + p[1];
+ out++; p += 2; len -= 2; olen--;
+ }
+ *out_len -= olen;
+ return 0;
+}
+
+/**
+ * Write an UCS2 string to a buffer.
+ *
+ * @param in The input UCS2 string.
+ * @param in_len the length of the input buffer.
+ * @param flags Flags to control the behavior of the function.
+ * @param ptr The input buffer to write to, the array must be at least
+ * (in + 1) * 2 bytes long.
+ * @param out_len the output length
+ *
+ * @return returns 0 on success, an wind error code otherwise.
+ * @ingroup wind
+ */
+
+int
+wind_ucs2write(const uint16_t *in, size_t in_len, unsigned int *flags,
+ void *ptr, size_t *out_len)
+{
+ unsigned char *p = ptr;
+ size_t len = *out_len;
+
+ /** If in buffer is not of length be mod 2, WIND_ERR_LENGTH_NOT_MOD2 is returned*/
+ if (len & 1)
+ return WIND_ERR_LENGTH_NOT_MOD2;
+
+ /** On zero input length, flags are preserved */
+ if (in_len == 0) {
+ *out_len = 0;
+ return 0;
+ }
+ /** If flags have WIND_RW_BOM set, the byte order mark is written
+ * first to the output data */
+ if ((*flags) & WIND_RW_BOM) {
+ uint16_t bom = 0xfffe;
+
+ if (len < 2)
+ return WIND_ERR_OVERRUN;
+
+ if ((*flags) & WIND_RW_LE) {
+ p[0] = (bom ) & 0xff;
+ p[1] = (bom >> 8) & 0xff;
+ } else {
+ p[1] = (bom ) & 0xff;
+ p[0] = (bom >> 8) & 0xff;
+ }
+ len -= 2;
+ }
+
+ while (in_len) {
+ /** If the output wont fit into out_len, WIND_ERR_OVERRUN is returned */
+ if (len < 2)
+ return WIND_ERR_OVERRUN;
+ if ((*flags) & WIND_RW_LE) {
+ p[0] = (in[0] ) & 0xff;
+ p[1] = (in[0] >> 8) & 0xff;
+ } else {
+ p[1] = (in[0] ) & 0xff;
+ p[0] = (in[0] >> 8) & 0xff;
+ }
+ len -= 2;
+ in_len--;
+ p += 2;
+ in++;
+ }
+ *out_len -= len;
+ return 0;
+}
+
+
+/**
+ * Convert an UTF-8 string to an UCS2 string.
+ *
+ * @param in an UTF-8 string to convert.
+ * @param out the resulting UCS2 strint, must be at least
+ * wind_utf8ucs2_length() long. If out is NULL, the function will
+ * calculate the needed space for the out variable (just like
+ * wind_utf8ucs2_length()).
+ * @param out_len before processing out_len should be the length of
+ * the out variable, after processing it will be the length of the out
+ * string.
+ *
+ * @return returns 0 on success, an wind error code otherwise
+ * @ingroup wind
+ */
+
+int
+wind_utf8ucs2(const char *in, uint16_t *out, size_t *out_len)
+{
+ const unsigned char *p;
+ size_t o = 0;
+ int ret;
+
+ for (p = (const unsigned char *)in; *p != '\0'; ++p) {
+ uint32_t u;
+
+ ret = utf8toutf32(&p, &u);
+ if (ret)
+ return ret;
+
+ if (u & 0xffff0000)
+ return WIND_ERR_NOT_UTF16;
+
+ if (out) {
+ if (o >= *out_len)
+ return WIND_ERR_OVERRUN;
+ out[o] = u;
+ }
+ o++;
+ }
+ *out_len = o;
+ return 0;
+}
+
+/**
+ * Calculate the length of from converting a UTF-8 string to a UCS2
+ * string.
+ *
+ * @param in an UTF-8 string to convert.
+ * @param out_len the length of the resulting UCS4 string.
+ *
+ * @return returns 0 on success, an wind error code otherwise
+ * @ingroup wind
+ */
+
+int
+wind_utf8ucs2_length(const char *in, size_t *out_len)
+{
+ return wind_utf8ucs2(in, NULL, out_len);
+}
+
+/**
+ * Convert an UCS2 string to a UTF-8 string.
+ *
+ * @param in an UCS2 string to convert.
+ * @param in_len the length of the in UCS2 string.
+ * @param out the resulting UTF-8 strint, must be at least
+ * wind_ucs2utf8_length() long. If out is NULL, the function will
+ * calculate the needed space for the out variable (just like
+ * wind_ucs2utf8_length()).
+ * @param out_len before processing out_len should be the length of
+ * the out variable, after processing it will be the length of the out
+ * string.
+ *
+ * @return returns 0 on success, an wind error code otherwise
+ * @ingroup wind
+ */
+
+int
+wind_ucs2utf8(const uint16_t *in, size_t in_len, char *out, size_t *out_len)
+{
+ uint16_t ch;
+ size_t i, len, o;
+
+ for (o = 0, i = 0; i < in_len; i++) {
+ ch = in[i];
+
+ if (ch < 0x80) {
+ len = 1;
+ } else if (ch < 0x800) {
+ len = 2;
+ } else
+ len = 3;
+
+ o += len;
+
+ if (out) {
+ if (o >= *out_len)
+ return WIND_ERR_OVERRUN;
+
+ switch(len) {
+ case 3:
+ out[2] = (ch | 0x80) & 0xbf;
+ ch = ch >> 6;
+ fallthrough;
+ case 2:
+ out[1] = (ch | 0x80) & 0xbf;
+ ch = ch >> 6;
+ fallthrough;
+ case 1:
+ out[0] = ch | first_char[len - 1];
+ fallthrough;
+ default:
+ break;
+ }
+ out += len;
+ }
+ }
+ if (out) {
+ if (o >= *out_len)
+ return WIND_ERR_OVERRUN;
+ *out = '\0';
+ }
+ *out_len = o;
+ return 0;
+}
+
+/**
+ * Calculate the length of from converting a UCS2 string to an UTF-8 string.
+ *
+ * @param in an UCS2 string to convert.
+ * @param in_len an UCS2 string length to convert.
+ * @param out_len the length of the resulting UTF-8 string.
+ *
+ * @return returns 0 on success, an wind error code otherwise
+ * @ingroup wind
+ */
+
+int
+wind_ucs2utf8_length(const uint16_t *in, size_t in_len, size_t *out_len)
+{
+ return wind_ucs2utf8(in, in_len, NULL, out_len);
+}
diff --git a/third_party/heimdal/lib/wind/util.py b/third_party/heimdal/lib/wind/util.py
new file mode 100644
index 0000000..a05c739
--- /dev/null
+++ b/third_party/heimdal/lib/wind/util.py
@@ -0,0 +1,48 @@
+#!/usr/local/bin/python
+# -*- coding: iso-8859-1 -*-
+
+# $Id$
+
+# Copyright (c) 2004 Kungliga Tekniska Högskolan
+# (Royal Institute of Technology, Stockholm, Sweden).
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the Institute nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+def subList(l, sl) :
+ """return the index of sl in l or None"""
+ lLen = len(l)
+ slLen = len(sl)
+ for i in range(lLen - slLen + 1):
+ j = 0
+ while j < slLen and l[i + j] == sl[j]:
+ j += 1
+ if j == slLen:
+ return i
+ return None
+
diff --git a/third_party/heimdal/lib/wind/version-script.map b/third_party/heimdal/lib/wind/version-script.map
new file mode 100644
index 0000000..6b5abb5
--- /dev/null
+++ b/third_party/heimdal/lib/wind/version-script.map
@@ -0,0 +1,29 @@
+# $Id$
+
+HEIMDAL_WIND_1.0 {
+ global:
+ wind_stringprep;
+ wind_profile;
+ wind_punycode_label_toascii;
+ wind_utf8ucs4;
+ wind_utf8ucs4_length;
+ wind_ucs4utf8;
+ wind_ucs4utf8_length;
+ wind_ucs2utf8;
+ wind_utf8ucs2;
+ wind_utf8ucs2_length;
+ wind_ucs2utf8_length;
+ wind_ucs2read;
+ wind_ucs2write;
+ # testing
+ _wind_combining_class;
+ _wind_stringprep_testbidi;
+ _wind_stringprep_error;
+ _wind_stringprep_prohibited;
+ _wind_stringprep_map;
+ _wind_stringprep_normalize;
+ _wind_ldap_case_exact_attribute;
+ _wind_ucs2read;
+ local:
+ *;
+};
diff --git a/third_party/heimdal/lib/wind/wind.h b/third_party/heimdal/lib/wind/wind.h
new file mode 100644
index 0000000..dd55ea3
--- /dev/null
+++ b/third_party/heimdal/lib/wind/wind.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef _WIND_H_
+#define _WIND_H_
+
+#include <stddef.h>
+#include <krb5-types.h>
+
+#include <wind_err.h>
+
+typedef unsigned int wind_profile_flags;
+
+#define WIND_PROFILE_NAME 0x00000001
+#define WIND_PROFILE_SASL 0x00000002
+#define WIND_PROFILE_LDAP 0x00000004
+#define WIND_PROFILE_LDAP_CASE 0x00000008
+
+#define WIND_PROFILE_LDAP_CASE_EXACT_ATTRIBUTE 0x00010000
+#define WIND_PROFILE_LDAP_CASE_EXACT_ASSERTION 0x00020000
+#define WIND_PROFILE_LDAP_NUMERIC 0x00040000
+#define WIND_PROFILE_LDAP_TELEPHONE 0x00080000
+
+
+/* flags to wind_ucs2read/wind_ucs2write */
+#define WIND_RW_LE 1
+#define WIND_RW_BE 2
+#define WIND_RW_BOM 4
+
+int wind_stringprep(const uint32_t *, size_t,
+ uint32_t *, size_t *,
+ wind_profile_flags);
+int wind_profile(const char *, wind_profile_flags *);
+
+int wind_punycode_label_toascii(const uint32_t *, size_t,
+ char *, size_t *);
+
+int wind_utf8ucs4(const char *, uint32_t *, size_t *);
+int wind_utf8ucs4_length(const char *, size_t *);
+
+int wind_ucs4utf8(const uint32_t *, size_t, char *, size_t *);
+int wind_ucs4utf8_length(const uint32_t *, size_t, size_t *);
+
+int wind_utf8ucs2(const char *, uint16_t *, size_t *);
+int wind_utf8ucs2_length(const char *, size_t *);
+
+int wind_ucs2utf8(const uint16_t *, size_t, char *, size_t *);
+int wind_ucs2utf8_length(const uint16_t *, size_t, size_t *);
+
+
+int wind_ucs2read(const void *, size_t, unsigned int *, uint16_t *, size_t *);
+int wind_ucs2write(const uint16_t *, size_t, unsigned int *, void *, size_t *);
+
+#endif /* _WIND_H_ */
diff --git a/third_party/heimdal/lib/wind/wind_err.et b/third_party/heimdal/lib/wind/wind_err.et
new file mode 100644
index 0000000..01c0d0f
--- /dev/null
+++ b/third_party/heimdal/lib/wind/wind_err.et
@@ -0,0 +1,23 @@
+#
+# Error messages for the wind library
+#
+# This might look like a com_err file, but is not
+#
+id "$Id$"
+
+error_table wind
+
+prefix WIND_ERR
+error_code NONE, "No error"
+error_code NO_PROFILE, "No such profile"
+error_code OVERRUN, "Buffer overrun"
+error_code UNDERUN, "Buffer underrun"
+error_code LENGTH_NOT_MOD2, "Length not mod2"
+error_code LENGTH_NOT_MOD4, "Length not mod4"
+error_code INVALID_UTF8, "Invalid UTF-8 combination in string"
+error_code INVALID_UTF16, "Invalid UTF-16 combination in string"
+error_code INVALID_UTF32, "Invalid UTF-32 combination in string"
+error_code NO_BOM, "No byte order mark (BOM) in string"
+error_code NOT_UTF16, "Code can't be represented as UTF-16"
+
+end
diff --git a/third_party/heimdal/lib/wind/windlocl.h b/third_party/heimdal/lib/wind/windlocl.h
new file mode 100644
index 0000000..da9d58c
--- /dev/null
+++ b/third_party/heimdal/lib/wind/windlocl.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2004 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* $Id$ */
+
+#ifndef _WINDLOCL_H_
+#define _WINDLOCL_H_
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <krb5-types.h>
+#include <roken.h>
+
+#include "wind.h"
+#include "wind_err.h"
+
+int _wind_combining_class(uint32_t);
+
+int _wind_stringprep_testbidi(const uint32_t *, size_t, wind_profile_flags);
+
+int _wind_stringprep_error(const uint32_t, wind_profile_flags);
+
+int _wind_stringprep_prohibited(const uint32_t *, size_t, wind_profile_flags);
+
+int _wind_stringprep_map(const uint32_t *, size_t,
+ uint32_t *, size_t *,
+ wind_profile_flags);
+
+int _wind_stringprep_normalize(const uint32_t *, size_t, uint32_t *, size_t *);
+
+int _wind_ldap_case_exact_attribute(const uint32_t *, size_t,
+ uint32_t *, size_t *);
+
+
+#endif /* _WINDLOCL_H_ */